diff --git a/.config/1espt/PipelineAutobaseliningConfig.yml b/.config/1espt/PipelineAutobaseliningConfig.yml index 11630c158384..1f99e3822276 100644 --- a/.config/1espt/PipelineAutobaseliningConfig.yml +++ b/.config/1espt/PipelineAutobaseliningConfig.yml @@ -1,13 +1,18 @@ -## DO NOT MODIFY THIS FILE MANUALLY. This is part of auto-baselining from 1ES Pipeline Templates. Go to [https://aka.ms/1espt-autobaselining] for more details. - -pipelines: - '*': - mainPipelineId: 694 - retail: - source: - credscan: - lastModifiedDate: 2024-09-18 - psscriptanalyzer: - lastModifiedDate: 2024-09-18 - armory: - lastModifiedDate: 2024-09-18 +## DO NOT MODIFY THIS FILE MANUALLY. This is part of auto-baselining from 1ES Pipeline Templates. Go to [https://aka.ms/1espt-autobaselining] for more details. + +pipelines: + '*': + mainPipelineId: 694 + retail: + source: + credscan: + lastModifiedDate: 2024-09-18 + psscriptanalyzer: + lastModifiedDate: 2024-09-18 + armory: + lastModifiedDate: 2024-09-18 + binary: + credscan: + lastModifiedDate: 2025-02-04 + binskim: + lastModifiedDate: 2025-02-04 diff --git a/.config/guardian/.gdnbaselines b/.config/guardian/.gdnbaselines index fcdfe46d6f1d..0ae2739dada6 100644 --- a/.config/guardian/.gdnbaselines +++ b/.config/guardian/.gdnbaselines @@ -21,9 +21,9 @@ ], "tool": "credscan", "ruleId": "CSCAN-GENERAL0020", - "createdDate": "2024-09-18 20:29:54Z", - "expirationDate": "2025-03-07 20:32:04Z", - "justification": "This error is baselined with an expiration date of 180 days from 2024-09-18 20:32:04Z" + "createdDate": "2025-02-05 22:57:45Z", + "expirationDate": "2025-07-25 23:22:36Z", + "justification": "This error is baselined with an expiration date of 180 days from 2025-02-05 23:22:36Z" }, "015badaee4e664447eb72fa5ee4b6768abd1049e98b456520e73167865eb7ca3": { "signature": "015badaee4e664447eb72fa5ee4b6768abd1049e98b456520e73167865eb7ca3", @@ -35,9 +35,9 @@ ], "tool": "credscan", "ruleId": "CSCAN-GENERAL0020", - "createdDate": "2024-09-18 20:29:54Z", - "expirationDate": "2025-03-07 20:32:04Z", - "justification": "This error is baselined with an expiration date of 180 days from 2024-09-18 20:32:04Z" + "createdDate": "2025-02-05 22:57:45Z", + "expirationDate": "2025-07-25 23:22:36Z", + "justification": "This error is baselined with an expiration date of 180 days from 2025-02-05 23:22:36Z" }, "8f8be7872e2e5d3a6a7f706aab3cbf01d1b7cb993e8c13a194f94f4340f01a8b": { "signature": "8f8be7872e2e5d3a6a7f706aab3cbf01d1b7cb993e8c13a194f94f4340f01a8b", @@ -49,9 +49,9 @@ ], "tool": "credscan", "ruleId": "CSCAN-GENERAL0020", - "createdDate": "2024-09-18 20:29:54Z", - "expirationDate": "2025-03-07 20:32:04Z", - "justification": "This error is baselined with an expiration date of 180 days from 2024-09-18 20:32:04Z" + "createdDate": "2025-02-05 22:57:45Z", + "expirationDate": "2025-07-25 23:22:36Z", + "justification": "This error is baselined with an expiration date of 180 days from 2025-02-05 23:22:36Z" }, "510286ddf3eef1a02d6e8a4d5273652860401a0d675660a053a6f139de1fc732": { "signature": "510286ddf3eef1a02d6e8a4d5273652860401a0d675660a053a6f139de1fc732", @@ -63,9 +63,9 @@ ], "tool": "credscan", "ruleId": "CSCAN-GENERAL0020", - "createdDate": "2024-09-18 20:29:54Z", - "expirationDate": "2025-03-07 20:32:04Z", - "justification": "This error is baselined with an expiration date of 180 days from 2024-09-18 20:32:04Z" + "createdDate": "2025-02-05 22:57:45Z", + "expirationDate": "2025-07-25 23:22:36Z", + "justification": "This error is baselined with an expiration date of 180 days from 2025-02-05 23:22:36Z" }, "7bf23d8a7acbf759fcb4fa85d2aa1f0ef7572015b4a2fc4dc2bb82120d131134": { "signature": "7bf23d8a7acbf759fcb4fa85d2aa1f0ef7572015b4a2fc4dc2bb82120d131134", @@ -77,9 +77,9 @@ ], "tool": "credscan", "ruleId": "CSCAN-GENERAL0020", - "createdDate": "2024-09-18 20:29:54Z", - "expirationDate": "2025-03-07 20:32:04Z", - "justification": "This error is baselined with an expiration date of 180 days from 2024-09-18 20:32:04Z" + "createdDate": "2025-02-05 22:57:45Z", + "expirationDate": "2025-07-25 23:22:36Z", + "justification": "This error is baselined with an expiration date of 180 days from 2025-02-05 23:22:36Z" }, "0434dbf288ae1a732d4aee4aa4a1a3c83d4fac11dde2f99aa14993e6d2870c5b": { "signature": "0434dbf288ae1a732d4aee4aa4a1a3c83d4fac11dde2f99aa14993e6d2870c5b", @@ -91,9 +91,9 @@ ], "tool": "credscan", "ruleId": "CSCAN-GENERAL0020", - "createdDate": "2024-09-18 20:29:54Z", - "expirationDate": "2025-03-07 20:32:04Z", - "justification": "This error is baselined with an expiration date of 180 days from 2024-09-18 20:32:04Z" + "createdDate": "2025-02-05 22:57:45Z", + "expirationDate": "2025-07-25 23:22:36Z", + "justification": "This error is baselined with an expiration date of 180 days from 2025-02-05 23:22:36Z" }, "7e9266d66cc95f85f30945d5b467b9ec23775649b68c298c544a9089add4fc87": { "signature": "7e9266d66cc95f85f30945d5b467b9ec23775649b68c298c544a9089add4fc87", @@ -105,9 +105,9 @@ ], "tool": "credscan", "ruleId": "CSCAN-GENERAL0020", - "createdDate": "2024-09-18 20:29:54Z", - "expirationDate": "2025-03-07 20:32:04Z", - "justification": "This error is baselined with an expiration date of 180 days from 2024-09-18 20:32:04Z" + "createdDate": "2025-02-05 22:57:45Z", + "expirationDate": "2025-07-25 23:22:36Z", + "justification": "This error is baselined with an expiration date of 180 days from 2025-02-05 23:22:36Z" }, "49d1295ecc9fac075aaf2860401c681ab86da25591e09f76e9bbac9c88dd17e6": { "signature": "49d1295ecc9fac075aaf2860401c681ab86da25591e09f76e9bbac9c88dd17e6", @@ -119,9 +119,9 @@ ], "tool": "credscan", "ruleId": "CSCAN-GENERAL0020", - "createdDate": "2024-09-18 20:29:54Z", - "expirationDate": "2025-03-07 20:32:04Z", - "justification": "This error is baselined with an expiration date of 180 days from 2024-09-18 20:32:04Z" + "createdDate": "2025-02-05 22:57:45Z", + "expirationDate": "2025-07-25 23:22:36Z", + "justification": "This error is baselined with an expiration date of 180 days from 2025-02-05 23:22:36Z" }, "fffa6ce6e45b64e624d950a2e2f59a89538c6bb9e624ae3a895d11cf73d8428b": { "signature": "fffa6ce6e45b64e624d950a2e2f59a89538c6bb9e624ae3a895d11cf73d8428b", @@ -133,9 +133,23 @@ ], "tool": "credscan", "ruleId": "CSCAN-GENERAL0020", - "createdDate": "2024-09-18 20:29:54Z", - "expirationDate": "2025-03-07 20:32:04Z", - "justification": "This error is baselined with an expiration date of 180 days from 2024-09-18 20:32:04Z" + "createdDate": "2025-02-05 22:57:45Z", + "expirationDate": "2025-07-25 23:22:36Z", + "justification": "This error is baselined with an expiration date of 180 days from 2025-02-05 23:22:36Z" + }, + "00b768f4ad6e8e609271b6c229074d39aaf6a1ffa45b34b20fecbc0e3d2d5b27": { + "signature": "00b768f4ad6e8e609271b6c229074d39aaf6a1ffa45b34b20fecbc0e3d2d5b27", + "alternativeSignatures": [], + "target": "sdk/cosmos/azure-cosmos-spark_3_2-12/docs/AAD-Auth.md", + "line": 140, + "memberOf": [ + "default" + ], + "tool": "credscan", + "ruleId": "CSCAN-GENERAL0060", + "createdDate": "2025-02-05 22:57:45Z", + "expirationDate": "2025-07-25 23:22:36Z", + "justification": "This error is baselined with an expiration date of 180 days from 2025-02-05 23:22:36Z" } } } \ No newline at end of file diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index a7f4c5824343..4f7bebb0b4f3 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -32,10 +32,16 @@ # ######## Core Libraries ######## # PRLabel: %Azure.Core -/sdk/core/ @alzimmermsft @srnagar @anuchandy @lmolkova @vcolin7 @mssfang @jonathangiles @billwert +/sdk/core/ @alzimmermsft @samvaity @srnagar @anuchandy @lmolkova @vcolin7 @mssfang @jonathangiles @billwert # ServiceLabel: %Azure.Core -# AzureSdkOwners: @alzimmermsft +# AzureSdkOwners: @alzimmermsft @samvaity + +# PRLabel: %Azure.Core.V2 +/sdk/corev2/ @alzimmermsft @samvaity @srnagar @anuchandy @lmolkova @vcolin7 @mssfang @jonathangiles @billwert + +# ServiceLabel: %Azure.Core.V2 +# AzureSdkOwners: @alzimmermsft @samvaity # PRLabel: %Azure.Core.AMQP /sdk/core/azure-core-amqp/ @anuchandy @conniey @lmolkova @@ -48,7 +54,7 @@ # ServiceLabel: %OpenTelemetry # AzureSdkOwners: @lmolkova -# ServiceOwners: @cijothomas @reyang @rajkumar-rangaraj @TimothyMothra @vishweshbankwar @ramthi +# ServiceOwners: @trask @ramthi @jeanbisutti @harsimar @rajkumar-rangaraj # PRLabel: %Azure.Core /sdk/parents/ @alzimmermsft @srnagar @jonathangiles @samvaity @@ -585,7 +591,7 @@ /sdk/monitor/azure-monitor-opentelemetry-exporter/ @trask @ramthi @heyams @jeanbisutti @harsimar # PRLabel: %OpenTelemetry -/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/ @trask @ramthi @heyams @jeanbisutti @harsimar +/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/ @trask @ramthi @heyams @jeanbisutti @harsimar @rajkumar-rangaraj # ServiceLabel: %Network # ServiceOwners: @aznetsuppgithub @@ -843,13 +849,13 @@ /sdk/spring-experimental/ @rujche @netyyyy @saragluna @moarychan # PRLabel: %Monitor - Spring -/sdk/spring/spring-cloud-azure-starter-monitor @jeanbisutti @trask @ramthi @heyams @harsimar @rujche @netyyyy @saragluna @moarychan +/sdk/spring/spring-cloud-azure-starter-monitor @jeanbisutti @trask @ramthi @heyams @harsimar @rujche @netyyyy @saragluna @moarychan @rajkumar-rangaraj # PRLabel: %Monitor - Spring -/sdk/spring/spring-cloud-azure-starter-monitor-test @jeanbisutti @trask @ramthi @heyams @harsimar @rujche @netyyyy @saragluna @moarychan +/sdk/spring/spring-cloud-azure-starter-monitor-test @jeanbisutti @trask @ramthi @heyams @harsimar @rujche @netyyyy @saragluna @moarychan @rajkumar-rangaraj # ServiceLabel: %Monitor - Spring -# AzureSdkOwners: @jeanbisutti @trask @ramthi @heyams @harsimar +# AzureSdkOwners: @jeanbisutti @trask @ramthi @heyams @harsimar @rajkumar-rangaraj # PRLabel: %azure-spring /sdk/spring/spring-cloud-azure-appconfiguration-config*/ @mrm9084 @rujche @netyyyy @saragluna @moarychan diff --git a/.vscode/cspell.json b/.vscode/cspell.json index 1141fc83e4a2..eb760b45a7e8 100644 --- a/.vscode/cspell.json +++ b/.vscode/cspell.json @@ -13,6 +13,8 @@ ], "ignorePaths": [ "eng/**", + "**/checkstyle-suppressions.xml", + "**/spotbugs-exclude.xml", "**/sdk/**/target/**", "**/session-records/**", "**/sdk/**/**/assets.json", @@ -136,6 +138,7 @@ "sdk/cosmos/azure-cosmos/**", "sdk/cosmos/azure-cosmos-test/**", "sdk/identity/azure-identity/**", + "sdk/identity/azure-identity-v2/**", "sdk/keyvault/azure-security-keyvault-administration/**", "sdk/keyvault/azure-security-keyvault-certificates/**", "sdk/keyvault/azure-security-keyvault-jca/**", @@ -200,6 +203,8 @@ "sdk/loadtesting/azure-developer-loadtesting/**", "sdk/clientcore/core/**", "sdk/clientcore/http-okhttp3/**", + "sdk/clientcore/annotation-processor/**", + "sdk/clientcore/annotation-processor-test/**", "sdk/clientcore/tools/**", "sdk/serialization/azure-json-gson/**", "sdk/serialization/azure-json/**", @@ -1339,7 +1344,19 @@ "tmpdir", "aarch", "CNCF" - ] + ] + }, + { + "filename": "sdk/corev2/**", + "words": [ + "aarch", + "junitextensions", + "tmpdir", + "urllistofbytes", + "urllistoflistofbytes", + "urlmapofbytes", + "xffffffffffff" + ] }, { "filename": "sdk/translation/azure-ai-translation-document/**", @@ -1351,6 +1368,15 @@ "submitadocumenttranslationrequesttothedocumenttranslationservice", "translateasingledocument" ] + }, + { + "filename": "sdk/eventgrid/**", + "words": [ + "mqtt", + "rservice", // appears in the name SignalRService + "gcch", + "updation" // current typo in a swagger + ] } ], "allowCompoundWords": true diff --git a/README.md b/README.md index b2024b7f913c..c00b0eacd3d2 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,10 @@ The management libraries can be identified by namespaces that start with `azure- Note that the latest libraries from Microsoft are in the `com.azure` Maven group ID, and have the package naming pattern of beginning with `com.azure`. If you're using libraries that are in `com.microsoft.azure` Maven group ID, or have this as the package structure, please consider migrating to the latest libraries. You can find a mapping table from these historical releases to their equivalent [here](https://azure.github.io/azure-sdk/releases/deprecated/index.html#java). +### Android Support + +The Azure SDKs for Java do not provide support for Android. While we attempt to allow the SDKs to be used on Android, we do not test or support this scenario. + ## Need help? - For reference documentation visit the [Azure SDK for Java documentation](https://aka.ms/java-docs). @@ -98,4 +102,4 @@ Azure SDK for Java is licensed under the [MIT](https://github.com/Azure/azure-sd [aug_19_release_page]: https://azure.github.io/azure-sdk/releases/2019-08-06/java.html [jul_19_release_page]: https://azure.github.io/azure-sdk/releases/2019-07-10/java.html -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2FREADME.png) + diff --git a/common/perf-test-core/README.md b/common/perf-test-core/README.md index b15c29a0f230..cb83599ac7e9 100644 --- a/common/perf-test-core/README.md +++ b/common/perf-test-core/README.md @@ -40,4 +40,4 @@ For details on contributing to this repository, see the [contributing guide](htt 1. Push to the branch (`git push origin my-new-feature`) 1. Create new Pull Request -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fcommon%2Fperf-test-core%2FREADME.png) + diff --git a/common/perf-test-core/pom.xml b/common/perf-test-core/pom.xml index c67024b47cbd..816af647adcc 100644 --- a/common/perf-test-core/pom.xml +++ b/common/perf-test-core/pom.xml @@ -57,7 +57,7 @@ com.beust:jcommander:[1.82] io.projectreactor:reactor-core:[3.4.41] - io.vertx:vertx-codegen:[4.5.10] + io.vertx:vertx-codegen:[4.5.13] @@ -75,27 +75,27 @@ com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-http-okhttp - 1.12.6 + 1.12.10 com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.19 + 1.0.3 com.azure azure-core-http-vertx - 1.0.0-beta.24 + 1.0.3 io.vertx vertx-codegen - 4.5.10 + 4.5.13 provided diff --git a/common/smoke-tests/README.md b/common/smoke-tests/README.md index 75ebf78a1565..22281739b1b6 100644 --- a/common/smoke-tests/README.md +++ b/common/smoke-tests/README.md @@ -135,4 +135,4 @@ If you'd like to contribute to this library, please read the contributing guide This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments. -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Feng%2Fsmoke-tests%2FREADME.png) + diff --git a/common/smoke-tests/pom.xml b/common/smoke-tests/pom.xml index 81f1abf28221..4ca7c7a39a11 100644 --- a/common/smoke-tests/pom.xml +++ b/common/smoke-tests/pom.xml @@ -88,67 +88,67 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.52 + 1.0.0-beta.56 com.azure azure-core-http-okhttp - 1.12.6 + 1.12.10 com.azure azure-core-amqp - 2.9.12 + 2.9.16 com.azure azure-cosmos - 4.66.0 + 4.67.0 com.azure azure-identity - 1.15.0 + 1.15.4 com.azure azure-security-keyvault-secrets - 4.9.1 + 4.9.3 com.azure azure-messaging-eventhubs - 5.19.2 + 5.20.1 com.azure azure-messaging-eventhubs-checkpointstore-blob - 1.20.2 + 1.20.5 com.azure azure-storage-blob - 12.29.0 + 12.29.1 diff --git a/doc/README.md b/doc/README.md index ec8af514220a..b667548caac9 100644 --- a/doc/README.md +++ b/doc/README.md @@ -3,4 +3,3 @@ This folder contains some documentations for this repository: The folder structure is the following - [dev](https://github.com/Azure/azure-sdk-for-java/blob/main/doc/dev) : contains advanced documentation for _developers_ of SDK (not _consumers_ of SDK) -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fdoc%2FREADME.png) \ No newline at end of file diff --git a/eng/.docsettings.yml b/eng/.docsettings.yml index fe80ed5dca5e..3854a066efd5 100644 --- a/eng/.docsettings.yml +++ b/eng/.docsettings.yml @@ -101,6 +101,8 @@ known_content_issues: - ['sdk/clientcore/http-okhttp3/README.md', '#3113'] - ['sdk/clientcore/tools/annotation-processor/README.md', '#3113'] - ['sdk/clientcore/optional-dependency-tests/README.md', '#3113'] + - ['sdk/clientcore/annotation-processor/README.md', '#3113'] + - ['sdk/clientcore/annotation-processor-test/README.md', '#3113'] - ['sdk/core/azure-core-experimental/README.md', '#3113'] - ['sdk/cosmos/faq/README.md', '#3113'] - ['sdk/cosmos/azure-cosmos-benchmark/README.md', '#3113'] @@ -129,6 +131,7 @@ known_content_issues: - ['sdk/keyvault/azure-security-keyvault-administration/README.md', '#3113'] - ['sdk/monitor/azure-monitor-spring-native/README.md', '#3113'] - ['sdk/parents/azure-client-sdk-parent/README.md', '#3113'] + - ['sdk/parents/azure-client-sdk-parent-v2/README.md', '#3113'] - ['sdk/parents/azure-code-customization-parent/README.md', '#3113'] - ['sdk/parents/azure-perf-test-parent/README.md', '#3113'] - ['sdk/parents/clientcore-parent/README.md', '#3113'] diff --git a/eng/README.md b/eng/README.md index e80fb87c995f..e3953f83ce5a 100644 --- a/eng/README.md +++ b/eng/README.md @@ -6,4 +6,4 @@ All the tools/utilities used in Microsoft Azure Java SDK's build config are defi - `pipelines` - Directory that contains yml files for our DevOps pipelines or supporting yml templates for them. -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Feng%2FREADME.png) + diff --git a/eng/automation/api-specs.yaml b/eng/automation/api-specs.yaml index 0ca05362c099..e1784ce597af 100644 --- a/eng/automation/api-specs.yaml +++ b/eng/automation/api-specs.yaml @@ -74,6 +74,9 @@ loadtestservice: service: loadtesting machinelearningservices: service: machinelearning +migrate/Microsoft.Migrate/AssessmentProjects: + service: migration + suffix: assessment monitor: suffix: generated msi: diff --git a/eng/automation/changelog/pom.xml b/eng/automation/changelog/pom.xml index 35408fbb3239..75bb7b965797 100644 --- a/eng/automation/changelog/pom.xml +++ b/eng/automation/changelog/pom.xml @@ -68,7 +68,7 @@ com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test diff --git a/eng/automation/generate.py b/eng/automation/generate.py index f480f0f41bd9..38e76b500a08 100755 --- a/eng/automation/generate.py +++ b/eng/automation/generate.py @@ -111,11 +111,15 @@ def sdk_automation(input_file: str, output_file: str): with open(input_file, "r") as fin: config = json.load(fin) - # typespec - packages = sdk_automation_typespec(config) - # autorest - if not packages: - packages = sdk_automation_autorest(config) + packages = [] + try: + # typespec + packages = sdk_automation_typespec(config) + # autorest + if not packages: + packages = sdk_automation_autorest(config) + except Exception: + logging.error("[GENERATE] Code generation failed. Unknown exception", exc_info=True) with open(output_file, "w", encoding="utf-8") as fout: output = { @@ -244,7 +248,6 @@ def sdk_automation_typespec(config: dict) -> List[dict]: def sdk_automation_typespec_project(tsp_project: str, config: dict) -> dict: - # TODO(xiaofei) support changelog, etc base_dir = os.path.abspath(os.path.dirname(sys.argv[0])) sdk_root = os.path.abspath(os.path.join(base_dir, SDK_ROOT)) spec_root = os.path.abspath(config["specFolder"]) @@ -272,14 +275,27 @@ def sdk_automation_typespec_project(tsp_project: str, config: dict) -> dict: # compile succeeded = compile_arm_package(sdk_root, module) if succeeded: + logging.info("[Changelog] Start breaking change detection for SDK automation.") breaking, changelog, breaking_change_items = compare_with_maven_package( sdk_root, GROUP_ID, service, get_latest_ga_version(GROUP_ID, module, stable_version), current_version, - module, + module + ) + logging.info("[Changelog] Complete breaking change detection for SDK automation.") + logging.info("[Changelog] Start generating changelog.") + compare_with_maven_package( + sdk_root, + GROUP_ID, + service, + get_latest_release_version(stable_version, current_version), + current_version, + module ) + update_changelog_version(sdk_root, output_folder, current_version) + logging.info("[Changelog] Complete generating changelog.") # output if sdk_folder and module and service: @@ -359,7 +375,7 @@ def main(): tsp_config = args["tsp_config"] succeeded, require_sdk_integration, sdk_folder, service, module = generate_typespec_project( - tsp_project=tsp_config, sdk_root=sdk_root, remove_before_regen=True, group_id=GROUP_ID + tsp_project=tsp_config, sdk_root=sdk_root, remove_before_regen=True, group_id=GROUP_ID, **args ) stable_version, current_version = set_or_increase_version(sdk_root, GROUP_ID, module, **args) diff --git a/eng/automation/generate_utils.py b/eng/automation/generate_utils.py index e27371209285..ce077ac9beaf 100755 --- a/eng/automation/generate_utils.py +++ b/eng/automation/generate_utils.py @@ -20,6 +20,7 @@ from utils import update_root_pom from utils import update_version from utils import is_windows +from utils import set_or_default_version os.chdir(pwd) @@ -333,6 +334,8 @@ def generate_typespec_project( repo_url: str = "", remove_before_regen: bool = False, group_id: str = None, + version: str = None, + **kwargs, ): if not tsp_project: @@ -411,6 +414,9 @@ def generate_typespec_project( # clear existing generated source code, and regenerate drop_changes(sdk_root) remove_generated_source_code(sdk_folder, f"{group_id}.{service}") + _, current_version = set_or_default_version(sdk_root, group_id, module, version=version) + tsp_cmd.append("--emitter-options") + tsp_cmd.append(f'package-version={current_version}') # regenerate check_call(tsp_cmd, sdk_root) succeeded = True @@ -443,7 +449,7 @@ def check_call(cmd: List[str], work_dir: str, shell: bool = False): def drop_changes(work_dir: str): - check_call(["git", "checkout", "--", "."], work_dir) + check_call(["git", "reset", "--hard", "-q"], work_dir) check_call(["git", "clean", "-qf", "."], work_dir) diff --git a/eng/automation/generation.yml b/eng/automation/generation.yml index a6d67ef0d706..ba2d98d65ac8 100644 --- a/eng/automation/generation.yml +++ b/eng/automation/generation.yml @@ -12,77 +12,67 @@ parameters: # parameters(instead of variables) is used here for template compile default: Swagger variables: -- group: Release Secrets for GitHub -- name: MAVEN_CACHE_FOLDER - value: $(Pipeline.Workspace)/.m2/repository -- name: MAVEN_OPTS - value: '-Dmaven.repo.local=$(MAVEN_CACHE_FOLDER)' -- name: NodeVersion - value: '18.x' -- name: JavaVersion - value: '17' + - group: Release Secrets for GitHub + - name: MAVEN_CACHE_FOLDER + value: $(Pipeline.Workspace)/.m2/repository + - name: MAVEN_OPTS + value: '-Dmaven.repo.local=$(MAVEN_CACHE_FOLDER)' + - name: NodeVersion + value: '20.x' + - name: JavaVersion + value: '17' -jobs: - - job: FluentLiteGenerationForMgmtSDK - pool: - ${{ if eq(parameters.RELEASE_TYPE, 'TypeSpec')}}: - vmImage: 'macOS-13' # tsp-client command will get permanent stuck on linux/windows: https://github.com/Azure/azure-sdk-tools/issues/8368 - ${{ else }}: - vmImage: 'ubuntu-20.04' - steps: - - bash: | - pip3 install --upgrade wheel - pip3 install --upgrade PyYAML requests - displayName: Update python - - - task: JavaToolInstaller@0 - inputs: - versionSpec: '$(JavaVersion)' - jdkArchitectureOption: '$(Agent.OSArchitecture)' - jdkSourceOption: 'PreInstalled' +steps: + - bash: | + sudo apt-get install -y --upgrade python3-pip python3-setuptools + pip3 install --upgrade wheel + pip3 install --upgrade PyYAML requests + displayName: Update python - - task: NodeTool@0 - displayName: 'Install Node.js $(NodeVersion)' - inputs: - versionSpec: '$(NodeVersion)' + - task: NodeTool@0 + displayName: 'Install Node.js $(NodeVersion)' + inputs: + versionSpec: '$(NodeVersion)' - - bash: | - npm install -g autorest - displayName: 'Install autorest' - condition: ${{ eq(parameters.RELEASE_TYPE, 'Swagger') }} + - bash: | + npm install -g autorest + displayName: 'Install autorest' + condition: ${{ eq(parameters.RELEASE_TYPE, 'Swagger') }} - - bash: | - npm install -g @azure-tools/typespec-client-generator-cli - displayName: 'Install tsp-client' - condition: ${{ eq(parameters.RELEASE_TYPE, 'TypeSpec') }} + - bash: | + npm install -g @azure-tools/typespec-client-generator-cli + displayName: 'Install tsp-client' + condition: ${{ eq(parameters.RELEASE_TYPE, 'TypeSpec') }} - # - template: /eng/common/testproxy/test-proxy-tool.yml - # parameters: - # runProxy: true - # targetVersion: 1.0.0-dev.20230908.1 + # - template: /eng/common/testproxy/test-proxy-tool.yml + # parameters: + # runProxy: true + # targetVersion: 1.0.0-dev.20230908.1 - - bash: | - java -version - set -x - ./eng/automation/generate.py --tsp-config "$(TSP_CONFIG)" --version "$(VERSION)" --auto-commit-external-change --user-name "azure-sdk" --user-email "azuresdk@microsoft.com" - displayName: Generation from TypeSpec - condition: ${{ eq(parameters.RELEASE_TYPE, 'TypeSpec') }} + - bash: | + export PATH=$JAVA_HOME_11_X64/bin:$PATH + java -version + set -x + ./eng/automation/generate.py --tsp-config "$(TSP_CONFIG)" --version "$(VERSION)" --auto-commit-external-change --user-name "azure-sdk" --user-email "azuresdk@microsoft.com" + displayName: Generation from TypeSpec + condition: ${{ eq(parameters.RELEASE_TYPE, 'TypeSpec') }} - - bash: | - java -version - set -x - ./eng/automation/generate.py --readme "$(README)" --tag "$(TAG)" --autorest-options="$(AUTOREST_OPTIONS)" --service "$(SERVICE)" --version "$(VERSION)" --suffix "$(SUFFIX)" --auto-commit-external-change --user-name "azure-sdk" --user-email "azuresdk@microsoft.com" - displayName: Generation from Swagger - condition: ${{ eq(parameters.RELEASE_TYPE, 'Swagger') }} + - bash: | + export PATH=$JAVA_HOME_11_X64/bin:$PATH + java -version + set -x + ./eng/automation/generate.py --readme "$(README)" --tag "$(TAG)" --autorest-options="$(AUTOREST_OPTIONS)" --service "$(SERVICE)" --version "$(VERSION)" --suffix "$(SUFFIX)" --auto-commit-external-change --user-name "azure-sdk" --user-email "azuresdk@microsoft.com" + displayName: Generation from Swagger + condition: ${{ eq(parameters.RELEASE_TYPE, 'Swagger') }} - - template: /eng/common/pipelines/templates/steps/create-pull-request.yml - parameters: - PRBranchName: fluent-lite-generation-$(Build.BuildId) - ${{ if eq(parameters.RELEASE_TYPE, 'TypeSpec') }}: # Have to use parameter here. The ${{}} is compile time expression, it won't resolve against runtime variables. - CommitMsg: '[Automation] Generate Fluent Lite from TypeSpec $(README)' - PRTitle: '[Automation] Generate Fluent Lite from TypeSpec $(README)' - ${{ else }}: - CommitMsg: '[Automation] Generate Fluent Lite from Swagger $(README)#$(TAG)' - PRTitle: '[Automation] Generate Fluent Lite from Swagger $(README)#$(TAG)' - PRLabels: 'Mgmt - Track 2' - OpenAsDraft: '$(DRAFT_PULL_REQUEST)' + - template: /eng/common/pipelines/templates/steps/create-pull-request.yml + parameters: + PRBranchName: fluent-lite-generation-$(Build.BuildId) + ${{ if eq(parameters.RELEASE_TYPE, 'TypeSpec') }}: # Have to use parameter here. The ${{}} is compile time expression, it won't resolve against runtime variables. + CommitMsg: '[Automation] Generate Fluent Lite from TypeSpec $(README)' + PRTitle: '[Automation] Generate Fluent Lite from TypeSpec $(README)' + ${{ else }}: + CommitMsg: '[Automation] Generate Fluent Lite from Swagger $(README)#$(TAG)' + PRTitle: '[Automation] Generate Fluent Lite from Swagger $(README)#$(TAG)' + PRLabels: 'Mgmt - Track 2' + OpenAsDraft: '$(DRAFT_PULL_REQUEST)' diff --git a/eng/automation/parameters.py b/eng/automation/parameters.py index 69c57462bf84..f028e16f1ef5 100755 --- a/eng/automation/parameters.py +++ b/eng/automation/parameters.py @@ -17,7 +17,7 @@ SDK_ROOT = "../../" # related to file dir AUTOREST_CORE_VERSION = "3.9.7" -AUTOREST_JAVA = "@autorest/java@4.1.43" +AUTOREST_JAVA = "@autorest/java@4.1.45" DEFAULT_VERSION = "1.0.0-beta.1" GROUP_ID = "com.azure.resourcemanager" API_SPECS_FILE = "api-specs.yaml" diff --git a/eng/automation/utils.py b/eng/automation/utils.py index 5d4bc4fba5c0..12ce83622339 100644 --- a/eng/automation/utils.py +++ b/eng/automation/utils.py @@ -255,6 +255,7 @@ def set_or_default_version( sdk_root: str, group: str, module: str, + version=None, ) -> Tuple[str, str]: version_file = os.path.join(sdk_root, "eng/versioning/version_client.txt") project = "{0}:{1}".format(group, module) @@ -288,6 +289,9 @@ def set_or_default_version( stable_version = "" current_version = default_version + if version: + current_version = version + if not stable_version: stable_version = current_version @@ -346,7 +350,10 @@ def set_or_increase_version( write_version(version_file, lines, version_index, project, stable_version, version) return stable_version, version + # 1.0.0-beta.1 -> [1,0,0,"-beta.1"] current_versions = list(re.findall(version_pattern, current_version)[0]) + # 1.0.0 -> [(1,0,0,"")] + # 1.0.0-beta.1 -> [(1,0,0,"-beta.1")] stable_versions = re.findall(version_pattern, stable_version) # no stable version if len(stable_versions) < 1 or stable_versions[0][-1] != "": @@ -409,7 +416,7 @@ def get_latest_ga_version(group_id: str, module: str, previous_version: str) -> response.raise_for_status() - ga_version_pattern = r" EXCLUSION_LIST = Arrays.asList("azure-spring-data-cosmos", "azure-core-test", "azure-sdk-all", "azure-sdk-parent", "azure-client-sdk-parent"); public static final Pattern SDK_DEPENDENCY_PATTERN = Pattern.compile("com.azure:(.+);(.+);(.+)"); + // TODO (alzimmer): Handle creation of BOM for v2 libraries. https://github.com/Azure/azure-sdk-for-java/issues/44475 public static final String BASE_AZURE_GROUPID = "com.azure"; public static final String AZURE_TEST_LIBRARY_IDENTIFIER = "-test"; public static final String AZURE_PERF_LIBRARY_IDENTIFIER = "-perf"; diff --git a/eng/code-quality-reports/README.md b/eng/code-quality-reports/README.md index fbfed68343c5..26eefda7c4d3 100644 --- a/eng/code-quality-reports/README.md +++ b/eng/code-quality-reports/README.md @@ -3,4 +3,4 @@ This module defines/configures the rules for code quality analysis tools such as checkstyle and spotbugs. For more information refer to [Checkstyle](https://checkstyle.org/) and [Spotbugs](https://spotbugs.github.io/). -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Feng%2Fcode-quality-reports%2FREADME.png) + diff --git a/eng/code-quality-reports/ci.yml b/eng/code-quality-reports/ci.yml index 84196c2b063b..3b51d92cde9d 100644 --- a/eng/code-quality-reports/ci.yml +++ b/eng/code-quality-reports/ci.yml @@ -11,6 +11,8 @@ trigger: - .vscode/eclipse-format-azure-sdk-for-java.xml - eng/code-quality-reports/ - eng/pipelines/code-quality-reports.yml + - eng/pipelines/scripts/Get-Linting-Commands.ps1 + - eng/pipelines/scripts/Get-Linting-Reports.ps1 pr: branches: @@ -24,6 +26,8 @@ pr: - .vscode/eclipse-format-azure-sdk-for-java.xml - eng/code-quality-reports/ - eng/pipelines/code-quality-reports.yml + - eng/pipelines/scripts/Get-Linting-Commands.ps1 + - eng/pipelines/scripts/Get-Linting-Reports.ps1 extends: template: /eng/pipelines/code-quality-reports.yml diff --git a/eng/code-quality-reports/pom.xml b/eng/code-quality-reports/pom.xml index 8e928bb08c29..adce786e0266 100755 --- a/eng/code-quality-reports/pom.xml +++ b/eng/code-quality-reports/pom.xml @@ -82,6 +82,10 @@ org.apache.logging.log4j log4j-core + + org.apache.logging.log4j + log4j-api + @@ -123,12 +127,12 @@ org.apache.maven.plugins maven-project-info-reports-plugin - 3.7.0 + 3.8.0 org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 diff --git a/eng/code-quality-reports/src/main/java/com/azure/tools/checkstyle/checks/DenyListedWordsCheck.java b/eng/code-quality-reports/src/main/java/com/azure/tools/checkstyle/checks/DenyListedWordsCheck.java index 6051d95b6392..e79aefe0967e 100644 --- a/eng/code-quality-reports/src/main/java/com/azure/tools/checkstyle/checks/DenyListedWordsCheck.java +++ b/eng/code-quality-reports/src/main/java/com/azure/tools/checkstyle/checks/DenyListedWordsCheck.java @@ -5,6 +5,7 @@ import com.puppycrawl.tools.checkstyle.api.AbstractCheck; import com.puppycrawl.tools.checkstyle.api.DetailAST; +import com.puppycrawl.tools.checkstyle.api.FullIdent; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.checks.naming.AccessModifierOption; import com.puppycrawl.tools.checkstyle.utils.CheckUtil; @@ -21,6 +22,8 @@ public class DenyListedWordsCheck extends AbstractCheck { private String[] denyListedWords = new String[0]; + private boolean implementationPackage = false; + static final String ERROR_MESSAGE = "%s, All Public API Classes, Fields and Methods should follow " + "Camelcase standards for the following words: %s."; @@ -47,14 +50,35 @@ public int[] getAcceptableTokens() { @Override public int[] getRequiredTokens() { - return new int[]{TokenTypes.CLASS_DEF, - TokenTypes.METHOD_DEF, - TokenTypes.VARIABLE_DEF}; + return new int[] { + TokenTypes.PACKAGE_DEF, TokenTypes.CLASS_DEF, TokenTypes.METHOD_DEF, TokenTypes.VARIABLE_DEF }; + } + + @Override + public void beginTree(DetailAST rootAST) { + implementationPackage = false; + } + + @Override + public void finishTree(DetailAST rootAST) { + implementationPackage = false; } @Override public void visitToken(DetailAST token) { + // If we're in an implementation package ignore this check. + // If a PACKAGE_DEF is not found, then assume it's not an implementation package. + if (implementationPackage) { + return; + } + switch (token.getType()) { + case TokenTypes.PACKAGE_DEF: + // Check if we're in an implementation package. + final String packageName = FullIdent.createFullIdent(token.findFirstToken(TokenTypes.DOT)).getText(); + implementationPackage = packageName.contains("implementation"); + break; + case TokenTypes.CLASS_DEF: case TokenTypes.METHOD_DEF: case TokenTypes.VARIABLE_DEF: @@ -67,7 +91,7 @@ public void visitToken(DetailAST token) { break; } - // In an interface all the fields (variables) are by default public, static and final. + // In an interface all the fields (variables) are by default public, static, and final. if (token.getType() == TokenTypes.VARIABLE_DEF && ScopeUtil.isInInterfaceBlock(token)) { break; } @@ -91,7 +115,8 @@ private boolean isPublicApi(DetailAST token) { final DetailAST modifiersAST = token.findFirstToken(TokenTypes.MODIFIERS); final AccessModifierOption accessModifier = CheckUtil.getAccessModifierFromModifiersToken(token); final boolean isStatic = modifiersAST.findFirstToken(TokenTypes.LITERAL_STATIC) != null; - return (accessModifier.equals(AccessModifierOption.PUBLIC) || accessModifier.equals(AccessModifierOption.PROTECTED)) && !isStatic; + return (accessModifier.equals(AccessModifierOption.PUBLIC) || accessModifier.equals( + AccessModifierOption.PROTECTED)) && !isStatic; } /** diff --git a/eng/code-quality-reports/src/main/resources/checkstyle/clientcore-checkstyle.xml b/eng/code-quality-reports/src/main/resources/checkstyle/clientcore-checkstyle.xml index fb503c81b3fe..a785c526b977 100644 --- a/eng/code-quality-reports/src/main/resources/checkstyle/clientcore-checkstyle.xml +++ b/eng/code-quality-reports/src/main/resources/checkstyle/clientcore-checkstyle.xml @@ -391,7 +391,7 @@ page at http://checkstyle.sourceforge.net/config.html --> 'System.out' and 'System.err' is not allowed as well. 4) All classes should use ClientLogger as logger only but except ClientLogger itself --> - + diff --git a/eng/code-quality-reports/src/main/resources/revapi/revapi.json b/eng/code-quality-reports/src/main/resources/revapi/revapi.json index 923af61d9e10..892a76305e87 100644 --- a/eng/code-quality-reports/src/main/resources/revapi/revapi.json +++ b/eng/code-quality-reports/src/main/resources/revapi/revapi.json @@ -204,7 +204,7 @@ }, { "code": "java.method.addedToInterface", - "new" : "method long com.azure.spring.data.cosmos.core.CosmosOperations::sum(com.azure.cosmos.models.SqlQuerySpec, java.lang.String)", + "new" : "method long com.azure.spring.data.cosmos.core.CosmosOperations::sum(com.azure.cosmos.models.SqlQuerySpec, java.lang.String)", "justification": "Spring interfaces are allowed to add methods." }, { @@ -719,6 +719,18 @@ "code" : "java.method.removed", "old" : "method com.azure.resourcemanager.cosmos.models.DatabaseAccountCreateUpdateParameters com.azure.resourcemanager.cosmos.models.DatabaseAccountCreateUpdateParameters::withDatabaseAccountOfferType(java.lang.String)", "justification": "The property is a constant, which should not be changed." + }, + { + "ignore": true, + "code" : "java.method.removed", + "old" : "method com.azure.resourcemanager.storage.models.StorageAccountCheckNameAvailabilityParameters com.azure.resourcemanager.storage.models.StorageAccountCheckNameAvailabilityParameters::withType(java.lang.String)", + "justification": "The property is a constant, which should not be changed." + }, + { + "ignore": true, + "code": "java.field.addedStaticField", + "new": "field com.azure.messaging.webpubsub.models.WebPubSubClientProtocol.SOCKETIO", + "justification": "Additional protocols are supported by Web PubSub." } ] } diff --git a/eng/code-quality-reports/src/test/java/com/azure/tools/checkstyle/checks/DenyListedWordsCheckTest.java b/eng/code-quality-reports/src/test/java/com/azure/tools/checkstyle/checks/DenyListedWordsCheckTest.java index a61c55ab4bf6..0be357fe7285 100644 --- a/eng/code-quality-reports/src/test/java/com/azure/tools/checkstyle/checks/DenyListedWordsCheckTest.java +++ b/eng/code-quality-reports/src/test/java/com/azure/tools/checkstyle/checks/DenyListedWordsCheckTest.java @@ -11,6 +11,9 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.io.File; +import java.util.Arrays; + public class DenyListedWordsCheckTest extends AbstractModuleTestSupport { private Checker checker; @@ -44,6 +47,23 @@ public void denyListedWordsInterface() throws Exception { verify(checker, getPath("DenyListedWordsInterface.java")); } + @Test + public void implementationPackageIgnored() throws Exception { + File file = TestUtils.createCheckFile("implementationPackageIgnored", Arrays.asList( + "package com.test.implementation;", + "@JacksonXmlRootElement(localName = \"File-SetHTTPHeaders-Headers\")", + "public class CamelCaseTestData {", + " public void errorHTTPMethod() { throw new RuntimeException(\"Error Messages.\"); }", + " public void validHttpMethod() { throw new RuntimeException(\"Error Messages.\"); }", + " public static void itIsAURLError() { throw new RuntimeException(\"Error Messages.\"); }", + " protected void invalidXMLMethod() { throw new RuntimeException(\"Error Messages.\"); }", + " private void shouldNotSearch() { throw new RuntimeException(\"Error Messages.\"); }", + "}" + )); + + verify(checker, new File[]{file}, file.getAbsolutePath()); + } + private String expectedErrorMessage(int line, int column, String errorMessage) { return String.format("%d:%d: %s", line, column, errorMessage); } diff --git a/eng/common/TestResources/New-TestResources.ps1 b/eng/common/TestResources/New-TestResources.ps1 old mode 100644 new mode 100755 index 8a61b68c6b2e..0b1fa603c158 --- a/eng/common/TestResources/New-TestResources.ps1 +++ b/eng/common/TestResources/New-TestResources.ps1 @@ -121,6 +121,8 @@ param ( . $PSScriptRoot/TestResources-Helpers.ps1 . $PSScriptRoot/SubConfig-Helpers.ps1 +$wellKnownTMETenants = @('70a036f6-8e4d-4615-bad6-149c02e7720d') + if (!$ServicePrincipalAuth) { # Clear secrets if not using Service Principal auth. This prevents secrets # from being passed to pre- and post-scripts. @@ -320,8 +322,14 @@ try { # Make sure the provisioner OID is set so we can pass it through to the deployment. if (!$ProvisionerApplicationId -and !$ProvisionerApplicationOid) { if ($context.Account.Type -eq 'User') { - # Use -Mail as the lookup works in both corp and TME tenants + # Support corp tenant and TME tenant user id lookups $user = Get-AzADUser -Mail $context.Account.Id + if ($user -eq $null -or !$user.Id) { + $user = Get-AzADUser -UserPrincipalName $context.Account.Id + } + if ($user -eq $null -or !$user.Id) { + throw "Failed to find entra object ID for the current user" + } $ProvisionerApplicationOid = $user.Id } elseif ($context.Account.Type -eq 'ServicePrincipal') { $sp = Get-AzADServicePrincipal -ApplicationId $context.Account.Id @@ -391,8 +399,14 @@ try { Write-Warning "The specified TestApplicationId '$TestApplicationId' will be ignored when -ServicePrincipalAutth is not set." } - # Use -Mail as the lookup works in both corp and TME tenants + # Support corp tenant and TME tenant user id lookups $userAccount = (Get-AzADUser -Mail (Get-AzContext).Account.Id) + if ($userAccount -eq $null -or !$userAccount.Id) { + $userAccount = (Get-AzADUser -UserPrincipalName (Get-AzContext).Account) + } + if ($userAccount -eq $null -or !$userAccount.Id) { + throw "Failed to find entra object ID for the current user" + } $TestApplicationOid = $userAccount.Id $TestApplicationId = $testApplicationOid $userAccountName = $userAccount.UserPrincipalName @@ -515,7 +529,11 @@ try { if ($CI -and $Environment -eq 'AzureCloud' -and $env:PoolSubnet) { $templateParameters.Add('azsdkPipelineSubnetList', @($env:PoolSubnet)) } - + # The TME tenants are our place for local auth testing so we do not support safe secret standard there. + # Some arm/bicep templates may want to change deployment settings like local auth in sandboxed TME tenants. + # The pipeline account context does not have the .Tenant.Name property, so check against subscription via + # naming convention instead. + $templateParameters.Add('supportsSafeSecretStandard', (!$wellKnownTMETenants.Contains($TenantId))) $defaultCloudParameters = LoadCloudConfig $Environment MergeHashes $defaultCloudParameters $(Get-Variable templateParameters) MergeHashes $ArmTemplateParameters $(Get-Variable templateParameters) diff --git a/eng/common/TestResources/Remove-TestResources.ps1 b/eng/common/TestResources/Remove-TestResources.ps1 old mode 100644 new mode 100755 diff --git a/eng/common/TestResources/TestResources-Helpers.ps1 b/eng/common/TestResources/TestResources-Helpers.ps1 index 6dee017aec9a..400cafcefd5b 100644 --- a/eng/common/TestResources/TestResources-Helpers.ps1 +++ b/eng/common/TestResources/TestResources-Helpers.ps1 @@ -131,7 +131,7 @@ function MergeHashes([hashtable] $source, [psvariable] $dest) { function BuildBicepFile([System.IO.FileSystemInfo] $file) { if (!(Get-Command bicep -ErrorAction Ignore)) { - Write-Error "A bicep file was found at '$($file.FullName)' but the Azure Bicep CLI is not installed. See aka.ms/bicep-install" + Write-Error "A bicep file was found at '$($file.FullName)' but the Azure Bicep CLI is not installed. See https://aka.ms/bicep-install" throw } diff --git a/eng/common/TestResources/Update-TestResources.ps1 b/eng/common/TestResources/Update-TestResources.ps1 old mode 100644 new mode 100755 diff --git a/eng/common/docgeneration/Generate-DocIndex.ps1 b/eng/common/docgeneration/Generate-DocIndex.ps1 index 2b8d59468bab..a279a2934511 100644 --- a/eng/common/docgeneration/Generate-DocIndex.ps1 +++ b/eng/common/docgeneration/Generate-DocIndex.ps1 @@ -25,13 +25,14 @@ function Get-BlobStorage-Artifacts( # "--query '[].name'" returns a list of only blob names # "--num-results *" handles pagination so the caller does not have to $artifacts = az storage blob list ` + --auth-mode login ` --account-name $storageAccountName ` --container-name $storageContainerName ` --prefix $storagePrefix ` --delimiter / ` --only-show-errors ` --query '[].name' ` - --num-results * | ConvertFrom-Json + --num-results * | ConvertFrom-Json LogDebug "Number of artifacts found: $($artifacts.Length)" # example: "python/azure-storage-blob" -> "azure-storage-blob" diff --git a/eng/common/docgeneration/templates/matthews/styles/main.js b/eng/common/docgeneration/templates/matthews/styles/main.js index 7ab1dd9e28ff..2bda06d0c2e1 100644 --- a/eng/common/docgeneration/templates/matthews/styles/main.js +++ b/eng/common/docgeneration/templates/matthews/styles/main.js @@ -108,7 +108,7 @@ function httpGetAsyncFallbackOnFail(targetUrl, successCallback, failureCallback) } function populateOptions(selector, packageName) { - var versionRequestUrl = "https://azuresdkdocs.blob.core.windows.net/$web/" + SELECTED_LANGUAGE + "/" + packageName + "/versioning/versions" + var versionRequestUrl = "https://azuresdkdocs.z19.web.core.windows.net/" + SELECTED_LANGUAGE + "/" + packageName + "/versioning/versions" httpGetAsync(versionRequestUrl, function (responseText) { var versionselector = document.createElement("select") @@ -181,9 +181,9 @@ function loadedOtherVersions(url, latestVersions, publishedVersions, selector, c } function populateIndexList(selector, packageName) { - var url = "https://azuresdkdocs.blob.core.windows.net/$web/" + SELECTED_LANGUAGE + "/" + packageName + "/versioning/versions" - var latestGAUrl = "https://azuresdkdocs.blob.core.windows.net/$web/" + SELECTED_LANGUAGE + "/" + packageName + "/versioning/latest-ga" - var latestPreviewUrl = "https://azuresdkdocs.blob.core.windows.net/$web/" + SELECTED_LANGUAGE + "/" + packageName + "/versioning/latest-preview" + var url = "https://azuresdkdocs.z19.web.core.windows.net/" + SELECTED_LANGUAGE + "/" + packageName + "/versioning/versions" + var latestGAUrl = "https://azuresdkdocs.z19.web.core.windows.net/" + SELECTED_LANGUAGE + "/" + packageName + "/versioning/latest-ga" + var latestPreviewUrl = "https://azuresdkdocs.z19.web.core.windows.net/" + SELECTED_LANGUAGE + "/" + packageName + "/versioning/latest-preview" var latestVersions = document.createElement("ul") httpGetLatestAsync(latestGAUrl, latestVersions, packageName) httpGetLatestAsync(latestPreviewUrl, latestVersions, packageName) @@ -217,7 +217,7 @@ function populateIndexList(selector, packageName) { } function getPackageUrl(language, package, version) { - return "https://azuresdkdocs.blob.core.windows.net/$web/" + language + "/" + package + "/" + version + "/index.html" + return "https://azuresdkdocs.z19.web.core.windows.net/" + language + "/" + package + "/" + version + "/index.html" } // Populate Versions diff --git a/eng/common/pipelines/templates/archetype-typespec-emitter.yml b/eng/common/pipelines/templates/archetype-typespec-emitter.yml index fd725b3bc7d5..21fafd58d05e 100644 --- a/eng/common/pipelines/templates/archetype-typespec-emitter.yml +++ b/eng/common/pipelines/templates/archetype-typespec-emitter.yml @@ -172,14 +172,15 @@ extends: - ${{ if parameters.PublishPublic }}: # publish to npmjs.org using ESRP - - task: EsrpRelease@7 + - task: EsrpRelease@9 inputs: displayName: Publish to npmjs.org - ConnectedServiceName: Azure SDK Engineering System + ConnectedServiceName: Azure SDK PME Managed Identity ClientId: 5f81938c-2544-4f1f-9251-dd9de5b8a81b - KeyVaultName: AzureSDKEngKeyVault - AuthCertName: azure-sdk-esrp-release-auth-certificate - SignCertName: azure-sdk-esrp-release-sign-certificate + DomainTenantId: 975f013f-7f24-47e8-a7d3-abc4752bf346 + UseManagedIdentity: true + KeyVaultName: kv-azuresdk-codesign + SignCertName: azure-sdk-esrp-release-certificate Intent: PackageDistribution ContentType: npm FolderLocation: $(buildArtifactsPath)/packages @@ -187,7 +188,6 @@ extends: Approvers: ${{ coalesce(variables['Build.RequestedForEmail'], 'azuresdk@microsoft.com') }} ServiceEndpointUrl: https://api.esrp.microsoft.com MainPublisher: ESRPRELPACMANTEST - DomainTenantId: 72f988bf-86f1-41af-91ab-2d7cd011db47 - task: PowerShell@2 displayName: Create emitter-package.json @@ -447,3 +447,14 @@ extends: parameters: artifactName: test_artifacts_$(System.JobName) artifactPath: $(Build.ArtifactStagingDirectory) + + - ${{ if and(eq(variables['System.TeamProject'], 'internal'), ne(variables['Build.Reason'], 'PullRequest')) }}: + - task: AzureCLI@2 + displayName: "Upload Spector Standard Coverage Report" + condition: and(ne(variables['SpectorName'], ''), succeeded()) + inputs: + azureSubscription: "TypeSpec Storage" + scriptType: "bash" + scriptLocation: "inlineScript" + inlineScript: npx tsp-spector upload-coverage --coverageFile $(Build.ArtifactStagingDirectory)/tsp-spector-coverage-azure.json --generatorName @azure-typespec/$(SpectorName) --storageAccountName typespec --containerName coverages --generatorVersion $(node -p -e "require('./package.json').version") --generatorMode azure + workingDirectory: $(Build.SourcesDirectory)/eng/packages/$(SpectorName) diff --git a/eng/common/pipelines/templates/jobs/archetype-spec-gen-sdk.yml b/eng/common/pipelines/templates/jobs/archetype-spec-gen-sdk.yml deleted file mode 100644 index 2eb1ca65992b..000000000000 --- a/eng/common/pipelines/templates/jobs/archetype-spec-gen-sdk.yml +++ /dev/null @@ -1,199 +0,0 @@ -parameters: - - name: SpecRepoUrl - type: string - - name: SdkRepoUrl - type: string - - name: SpecRepoCommit - type: string - default: 'HEAD' - - name: SdkRepoCommit - type: string - default: 'HEAD' - - name: ConfigType - type: string - values: - - 'TypeSpec' - - 'OpenAPI' - default: 'TypeSpec' - displayName: 'API specification type' - - name: ConfigPath - type: string - default: 'specification/contosowidgetmanager/Contoso.Management/tspconfig.yaml' - displayName: 'Path to API specification file (TypeSpec/OpenAPI)' - - name: SkipPullRequestCreation - type: boolean - default: false - -jobs: -- job: - displayName: 'SDK Generation' - - variables: - - template: /eng/pipelines/templates/variables/image.yml - - name: NodeVersion - value: '22.13.x' - - name: PythonVersion - value: '3.13' - - name: SpecGenSdkVersion - value: 'latest' - - name: SdkArtifactName - value: SDK_Artifact - - pool: - name: $(LINUXPOOL) - vmImage: $(LINUXVMIMAGE) - - steps: - - checkout: none - - - pwsh: | - $urlPattern = '^https://github\.com/(?[^/]+)/(?[^/]+)' - if ('${{ parameters.SpecRepoUrl }}' -match $urlPattern) { - $specRepoOwner = $Matches['organization'] - Write-Host "##vso[task.setvariable variable=SpecRepoOwner]$specRepoOwner" - Write-Host "SpecRepoOwner variable set to: $specRepoOwner" - - $specRepoName = $Matches['repository'] - Write-Host "##vso[task.setvariable variable=SpecRepoName]$specRepoName" - Write-Host "SpecRepoName variable set to: $specRepoName" - - $specRepoDirectory = "$(System.DefaultWorkingDirectory)/$specRepoName" - Write-Host "##vso[task.setvariable variable=SpecRepoDirectory]$specRepoDirectory" - Write-Host "SpecRepoDirectory variable set to: $specRepoDirectory" - } - - if ('${{ parameters.SdkRepoUrl }}' -match $urlPattern) { - if ('${{ parameters.SpecRepoUrl }}'.EndsWith('-pr') -and (-not '${{ parameters.SdkRepoUrl }}'.EndsWith('-pr'))) { - Write-Host "SdkRepoUrl must be a private repository if SpecRepoUrl is a private repository." - Exit 1 - } - - $sdkRepoOwner = if ('$(SdkRepoOwner)' -eq '') { $Matches['organization'] } else { '$(SdkRepoOwner)' } - Write-Host "##vso[task.setvariable variable=SdkRepoOwner]$sdkRepoOwner" - Write-Host "SdkRepoOwner variable set to: $sdkRepoOwner" - - $sdkRepoName = $Matches['repository'] - Write-Host "##vso[task.setvariable variable=SdkRepoName]$sdkRepoName" - Write-Host "SdkRepoName variable set to: $sdkRepoName" - - $sdkRepoDirectory = "$(System.DefaultWorkingDirectory)/$sdkRepoName" - Write-Host "##vso[task.setvariable variable=SdkRepoDirectory]$sdkRepoDirectory" - Write-Host "SdkRepoDirectory variable set to: $sdkRepoDirectory" - } - - if ([string]::IsNullOrEmpty($SpecRepoOwner) -or [string]::IsNullOrEmpty($SpecRepoName) -or [string]::IsNullOrEmpty($SdkRepoOwner) -or [string]::IsNullOrEmpty($SdkRepoName)) { - Write-Host "One or more required variables is empty or invalid. Ensure that SpecRepourl and SdkRepoUrl are set to valid GitHub repository URLs." - Exit 1 - } - - $sdkRepoNameForSpecGen = $sdkRepoName - if ($sdkRepoName.EndsWith('-for-net')) { - $sdkRepoNameForSpecGen = $sdkRepoName + "-track2" - } - Write-Host "##vso[task.setvariable variable=SdkRepoNameForSpecGen]$sdkRepoNameForSpecGen" - Write-Host "SdkRepoNameForSpecGen variable set to: $sdkRepoNameForSpecGen" - displayName: "Create Run Time Variables" - - - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml - parameters: - Paths: - - '/*' - - '!sdk/**/test-recordings/*' - - '!sdk/**/recordings/*' - - '!sdk/**/SessionRecords/*' - - '!sdk/**/session-records/*' - Repositories: - - Name: $(SpecRepoOwner)/$(SpecRepoName) - Commitish: ${{ parameters.SpecRepoCommit }} - WorkingDirectory: $(SpecRepoDirectory) - - Name: $(SdkRepoOwner)/$(SdkRepoName) - Commitish: ${{ parameters.SdkRepoCommit }} - WorkingDirectory: $(SdkRepoDirectory) - SkipCheckoutNone: true - - - script: | - if [ "${{ parameters.SpecRepoCommit }}" = "HEAD" ]; then - cd $(SpecRepoDirectory) - default_commit=$(git rev-parse HEAD) - echo "##vso[task.setvariable variable=SpecRepoCommit]$default_commit" - echo "SpecRepoCommit variable set to default commit: $default_commit" - else - echo "##vso[task.setvariable variable=SpecRepoCommit]${{ parameters.SpecRepoCommit }}" - echo "SpecRepoCommit variable set to: ${{ parameters.SpecRepoCommit }}" - fi - displayName: 'Set SpecRepoCommit variable' - - - task: NodeTool@0 - inputs: - versionSpec: $(NodeVersion) - displayName: 'Install Node.js' - - - task: UsePythonVersion@0 - inputs: - versionSpec: $(PythonVersion) - - - script: | - npm install -g @azure-tools/spec-gen-sdk@$(SpecGenSdkVersion) - displayName: 'Install spec-gen-sdk' - - - script: | - optional_params="" - sdk_gen_info="sdk generation from Config : " - - if [ "${{ parameters.ConfigType }}" = "TypeSpec" ]; then - optional_params="$optional_params --tsp-config-relative-path ${{ parameters.ConfigPath }}" - sdk_gen_info="$sdk_gen_info '${{ parameters.ConfigPath }}'," - else - optional_params="$optional_params --readme-relative-path ${{ parameters.ConfigPath }}" - sdk_gen_info="$sdk_gen_info '${{ parameters.ConfigPath }}'," - fi - - sdk_gen_info="$sdk_gen_info and CommitSHA: '$(SpecRepoCommit)', in SpecRepo: '${{ parameters.SpecRepoUrl }}'" - echo "##vso[task.setvariable variable=GeneratedSDKInformation]$sdk_gen_info" - echo "Generated SDK Information : $sdk_gen_info" - - spec-gen-sdk \ - --scp "$(SpecRepoDirectory)" \ - --sdp "$(SdkRepoDirectory)" \ - --wf "$(System.DefaultWorkingDirectory)" \ - -l "$(SdkRepoNameForSpecGen)" \ - -c "$(SpecRepoCommit)" \ - -t $true \ - $optional_params - displayName: 'Generate SDK' - - - task: PublishPipelineArtifact@1 - displayName: Publish SDK Artifact to Pipeline Artifacts - inputs: - artifactName: $(sdkArtifactName) - targetPath: "$(System.DefaultWorkingDirectory)/generatedSdkArtifacts" - - - ${{ if eq(parameters.SkipPullRequestCreation, false) }}: - - template: /eng/common/pipelines/templates/steps/git-push-changes.yml - parameters: - BaseRepoBranch: $(PrBranch)-$(Build.BuildId) - BaseRepoOwner: azure-sdk - CommitMsg: $(GeneratedSDKInformation) - TargetRepoOwner: $(SdkRepoOwner) - TargetRepoName: $(SdkRepoName) - PushArgs: "--force" - WorkingDirectory: $(SdkRepoDirectory) - ScriptDirectory: $(SdkRepoDirectory)/eng/common/scripts - - - task: PowerShell@2 - displayName: Create pull request - condition: and(succeeded(), eq(variables['HasChanges'], 'true')) - inputs: - pwsh: true - workingDirectory: $(SdkRepoDirectory) - filePath: $(SdkRepoDirectory)/eng/common/scripts/Submit-PullRequest.ps1 - arguments: > - -RepoOwner "$(SdkRepoOwner)" - -RepoName "$(SdkRepoName)" - -BaseBranch "main" - -PROwner "azure-sdk" - -PRBranch "$(PrBranch)-$(Build.BuildId)" - -AuthToken "$(azuresdk-github-pat)" - -PRTitle "$(PrTitle)-generated-from-$(Build.DefinitionName)-$(Build.BuildId)" - -PRBody "$(GeneratedSDKInformation)" - -OpenAsDraft $true diff --git a/eng/common/pipelines/templates/jobs/docindex.yml b/eng/common/pipelines/templates/jobs/docindex.yml index 8ba898e4c14d..45c19dc21000 100644 --- a/eng/common/pipelines/templates/jobs/docindex.yml +++ b/eng/common/pipelines/templates/jobs/docindex.yml @@ -15,12 +15,14 @@ jobs: workingDirectory: $(Build.BinariesDirectory) displayName: Download and Extract DocFX - - task: PowerShell@2 + - task: AzureCLI@2 displayName: 'Generate Doc Index' inputs: - pwsh: true - filePath: $(Build.SourcesDirectory)/eng/common/docgeneration/Generate-DocIndex.ps1 - arguments: > + azureSubscription: 'Azure SDK Artifacts' + scriptType: pscore + scriptLocation: inlineScript + inlineScript: > + $(Build.SourcesDirectory)/eng/common/docgeneration/Generate-DocIndex.ps1 -Docfx $(docfxPath) -RepoRoot $(Build.SourcesDirectory) -DocGenDir "$(Build.SourcesDirectory)/eng/common/docgeneration" diff --git a/eng/common/pipelines/templates/jobs/generate-job-matrix.yml b/eng/common/pipelines/templates/jobs/generate-job-matrix.yml index d1db47b30b22..7cb3a785cea5 100644 --- a/eng/common/pipelines/templates/jobs/generate-job-matrix.yml +++ b/eng/common/pipelines/templates/jobs/generate-job-matrix.yml @@ -54,6 +54,9 @@ parameters: - name: PRMatrixIndirectFilters type: object default: [] +- name: PRMatrixSparseIndirect + type: boolean + default: true # Mappings to OS name required at template compile time by 1es pipeline templates - name: Pools type: object @@ -142,7 +145,8 @@ jobs: -Filters '${{ join(''',''', parameters.MatrixFilters) }}', 'container=^$', 'SupportedClouds=^$|${{ parameters.CloudConfig.Cloud }}', 'Pool=${{ pool.filter }}' ` -IndirectFilters '${{ join(''',''', parameters.PRMatrixIndirectFilters) }}' ` -Replace '${{ join(''',''', parameters.MatrixReplace) }}' ` - -PackagesPerPRJob ${{ parameters.PRJobBatchSize }} + -PackagesPerPRJob ${{ parameters.PRJobBatchSize }} ` + -SparseIndirect $${{ parameters.PRMatrixSparseIndirect }} displayName: Create ${{ pool.name }} PR Matrix name: vm_job_matrix_pr_${{ pool.name }} diff --git a/eng/common/pipelines/templates/jobs/prepare-pipelines.yml b/eng/common/pipelines/templates/jobs/prepare-pipelines.yml index 0d3f7397541a..d874216cc8d8 100644 --- a/eng/common/pipelines/templates/jobs/prepare-pipelines.yml +++ b/eng/common/pipelines/templates/jobs/prepare-pipelines.yml @@ -32,6 +32,7 @@ jobs: AzureSDK_Maven_Release_Pipeline_Secrets: 1 AzureSDK_Nuget_Release_Pipeline_Secrets: 13 AzureSDK_CocoaPods_Release_Pipeline_Secrets: 98 + AzureSDK_CratesIo_Release_Pipeline_Secrets: 150 NPM_Registry_Authentication: 24 Release_Secrets_for_GitHub: 58 Secrets_for_Resource_Provisioner: 64 @@ -50,17 +51,21 @@ jobs: - '!sdk/**/recordings/*' - '!sdk/**/SessionRecords/*' - '!sdk/**/session-records/*' + ${{ if endsWith(parameters.Repository, '-pr') }}: + TokenToUseForAuth: $(azuresdk-github-pat) + - template: /eng/common/pipelines/templates/steps/install-pipeline-generation.yml - template: /eng/common/pipelines/templates/steps/set-default-branch.yml - pwsh: | Write-Host "Setting up pipeline variables" - if ("${{ parameters.Repository }}" -match "Azure/azure-sdk-for-(?[^-]*)(?-pr)?") { - $prefix = $matches['prefix'] - $devOpsPath = "\$prefix" + if ("${{ parameters.Repository }}" -match "Azure/azure-sdk-for-(?[^-]*)(?-pr)?") { + $lang = $matches['lang'] + $devOpsPath = "\$lang" + $prefix = $lang if ($matches['pr']) { $devOpsPath = "${devOpsPath}\pr" - $prefix = "${prefix}-pr" + $prefix += "-pr" Write-Host "##vso[task.setvariable variable=ProjectForPRValidation]internal" } Write-Host "Prefix = $prefix" @@ -77,10 +82,10 @@ jobs: $generateUnifiedWeekly = 'false' $testServiceConnections = '"Azure" "azure-sdk-tests" "azure-sdk-tests-preview" "azure-sdk-tests-public" "Azure SDK Test Resources - LiveTestSecrets"' - $internalServiceConnections = '"Azure" "Azure SDK Artifacts" "Azure SDK Engineering System" "opensource-api-connection" "AzureSDKEngKeyVault Secrets"' + $internalServiceConnections = '"Azure" "Azure SDK Artifacts" "Azure SDK Engineering System" "opensource-api-connection" "AzureSDKEngKeyVault Secrets" "Azure SDK PME Managed Identity"' - # Map the language prefix to the appropriate variable groups - switch ($prefix) + # Map the language to the appropriate variable groups + switch ($lang) { "java" { $internalVariableGroups = '$(AzureSDK_Maven_Release_Pipeline_Secrets) $(Release_Secrets_for_GitHub) $(APIReview_AutoCreate_Configurations)' @@ -99,6 +104,11 @@ jobs: $internalVariableGroups = '$(Release_Secrets_for_GitHub) $(APIReview_AutoCreate_Configurations)' $testVariableGroups = '$(Secrets_for_Resource_Provisioner)' } + "rust" { + $generatePublicCIPipeline = 'false' + $internalVariableGroups = '$(AzureSDK_CratesIo_Release_Pipeline_Secrets) $(Release_Secrets_for_GitHub) $(APIReview_AutoCreate_Configurations)' + $testVariableGroups = '$(Secrets_for_Resource_Provisioner)' + } "net" { $internalVariableGroups = '$(AzureSDK_Nuget_Release_Pipeline_Secrets) $(Release_Secrets_for_GitHub) $(APIReview_AutoCreate_Configurations)' $testVariableGroups = '$(Secrets_for_Resource_Provisioner)' @@ -115,7 +125,7 @@ jobs: $generateUnifiedWeekly = 'true' } default { - Write-Error "Prefix '$prefix' is not recognized." + Write-Error "Language '$lang' is not recognized." exit 1 } } diff --git a/eng/common/pipelines/templates/stages/archetype-spec-gen-sdk.yml b/eng/common/pipelines/templates/stages/archetype-spec-gen-sdk.yml new file mode 100644 index 000000000000..f97b3c9c054c --- /dev/null +++ b/eng/common/pipelines/templates/stages/archetype-spec-gen-sdk.yml @@ -0,0 +1,256 @@ +parameters: + - name: SpecRepoUrl + type: string + - name: SdkRepoUrl + type: string + - name: SpecRepoCommit + type: string + default: '$(Build.SourceBranch)' + - name: SdkRepoCommit + type: string + default: 'HEAD' + - name: ConfigType + type: string + values: + - 'TypeSpec' + - 'OpenAPI' + default: 'TypeSpec' + displayName: 'API specification type' + - name: ConfigPath + type: string + default: 'specification/contosowidgetmanager/Contoso.Management/tspconfig.yaml' + displayName: 'Path to API specification file (TypeSpec/OpenAPI)' + - name: SkipPullRequestCreation + type: boolean + default: false + +extends: + template: /eng/pipelines/templates/stages/1es-redirect.yml + parameters: + stages: + - stage: Build + displayName: 'SDK Generation' + jobs: + - job: + displayName: 'SDK Generation' + + variables: + - template: /eng/pipelines/templates/variables/image.yml + - name: NodeVersion + value: '22.13.x' + - name: PythonVersion + value: '3.13' + - name: SpecGenSdkVersion + value: 'latest' + - name: SdkArtifactName + value: SDK_Artifact + + pool: + name: $(LINUXPOOL) + vmImage: $(LINUXVMIMAGE) + os: linux + + templateContext: + outputParentDirectory: $(System.DefaultWorkingDirectory)/out + outputs: + - output: pipelineArtifact + displayName: Publish SDK artifacts to Pipeline Artifacts + condition: and(ne(variables['ValidationResult'], ''), eq(variables['HasSDKArtifact'], 'true')) + artifactName: $(sdkArtifactName) + targetPath: "$(System.DefaultWorkingDirectory)/out/generatedSdkArtifacts" + - output: pipelineArtifact + displayName: Publish API View artifacts to Pipeline Artifacts + condition: and(ne(variables['ValidationResult'], ''), eq(variables['HasApiViewArtifact'], 'true')) + artifactName: $(ArtifactName) + targetPath: "$(System.DefaultWorkingDirectory)/out/sdkApiViewArtifacts" + - output: pipelineArtifact + displayName: Publish logs to Pipeline Artifacts + condition: ne(variables['ValidationResult'], '') + artifactName: "spec-gen-sdk-logs" + targetPath: "$(System.DefaultWorkingDirectory)/out/logs" + + steps: + - checkout: none + + - pwsh: | + $tspConfigPathPattern = '^specification\/([^\/]+\/)+tspconfig\.yaml$' + $readmePathPattern = '^specification\/([^\/]+\/){2,}readme\.md$' + if (('${{ parameters.ConfigType }}' -eq 'TypeSpec') -and ('${{ parameters.ConfigPath }}' -notmatch $tspConfigPathPattern)) { + Write-Host "##vso[task.logissue type=error]'ConfigPath' must be a valid 'tspconfig.yaml' file path when 'ConfigType' is set to 'TypeSpec'. For example, 'specification/contosowidgetmanager/Contoso.Management/tspconfig.yaml'" + Exit 1 + } elseif (('${{ parameters.ConfigType }}' -eq 'OpenAPI') -and ('${{ parameters.ConfigPath }}' -notmatch $readmePathPattern)) { + Write-Host "##vso[task.logissue type=error]'ConfigPath' must be a valid 'readme.md' file path when 'ConfigType' is set to 'OpenAPI'. For example, 'specification/appplatform/resource-manager/readme.md'" + Exit 1 + } + $urlPattern = '^https://github\.com/(?[^/]+)/(?[^/]+)' + if ('${{ parameters.SpecRepoUrl }}' -match $urlPattern) { + $specRepoOwner = $Matches['organization'] + Write-Host "##vso[task.setvariable variable=SpecRepoOwner]$specRepoOwner" + Write-Host "SpecRepoOwner variable set to: $specRepoOwner" + + $specRepoName = $Matches['repository'] + Write-Host "##vso[task.setvariable variable=SpecRepoName]$specRepoName" + Write-Host "SpecRepoName variable set to: $specRepoName" + + $specRepoDirectory = "$(System.DefaultWorkingDirectory)/$specRepoName" + Write-Host "##vso[task.setvariable variable=SpecRepoDirectory]$specRepoDirectory" + Write-Host "SpecRepoDirectory variable set to: $specRepoDirectory" + } + + if ('${{ parameters.SdkRepoUrl }}' -match $urlPattern) { + if ('${{ parameters.SpecRepoUrl }}'.EndsWith('-pr') -and (-not '${{ parameters.SdkRepoUrl }}'.EndsWith('-pr'))) { + Write-Host "##vso[task.logissue type=error]SdkRepoUrl must be a private repository if SpecRepoUrl is a private repository." + Exit 1 + } + + $sdkRepoOwner = $Matches['organization'] + Write-Host "##vso[task.setvariable variable=SdkRepoOwner]$sdkRepoOwner" + Write-Host "SdkRepoOwner variable set to: $sdkRepoOwner" + + $sdkRepoName = $Matches['repository'] + Write-Host "##vso[task.setvariable variable=SdkRepoName]$sdkRepoName" + Write-Host "SdkRepoName variable set to: $sdkRepoName" + + $sdkRepoDirectory = "$(System.DefaultWorkingDirectory)/$sdkRepoName" + Write-Host "##vso[task.setvariable variable=SdkRepoDirectory]$sdkRepoDirectory" + Write-Host "SdkRepoDirectory variable set to: $sdkRepoDirectory" + } + + if ([string]::IsNullOrEmpty($SpecRepoOwner) -or [string]::IsNullOrEmpty($SpecRepoName) -or [string]::IsNullOrEmpty($SdkRepoOwner) -or [string]::IsNullOrEmpty($SdkRepoName)) { + Write-Host "##vso[task.logissue type=error]One or more required variables is empty or invalid. Ensure that SpecRepoUrl and SdkRepoUrl are set to valid GitHub repository URLs." + Exit 1 + } + + displayName: "Create Run Time Variables" + + - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml + parameters: + Paths: + - '/*' + - '!sdk/**/test-recordings/*' + - '!sdk/**/recordings/*' + - '!sdk/**/SessionRecords/*' + - '!sdk/**/session-records/*' + Repositories: + - Name: $(SpecRepoOwner)/$(SpecRepoName) + Commitish: ${{ parameters.SpecRepoCommit }} + WorkingDirectory: $(SpecRepoDirectory) + - Name: $(SdkRepoOwner)/$(SdkRepoName) + Commitish: ${{ parameters.SdkRepoCommit }} + WorkingDirectory: $(SdkRepoDirectory) + SkipCheckoutNone: true + + - script: | + if [ "${{ parameters.SpecRepoCommit }}" = "$(Build.SourceBranch)" ]; then + cd $(SpecRepoDirectory) + default_commit=$(git rev-parse HEAD) + echo "##vso[task.setvariable variable=SpecRepoCommit]$default_commit" + echo "SpecRepoCommit variable set to default commit: $default_commit" + else + echo "##vso[task.setvariable variable=SpecRepoCommit]${{ parameters.SpecRepoCommit }}" + echo "SpecRepoCommit variable set to: ${{ parameters.SpecRepoCommit }}" + fi + displayName: 'Set SpecRepoCommit variable' + + - task: NodeTool@0 + inputs: + versionSpec: $(NodeVersion) + displayName: 'Install Node.js' + + - task: UsePythonVersion@0 + inputs: + versionSpec: $(PythonVersion) + + - script: | + npm install -g @azure-tools/spec-gen-sdk@$(SpecGenSdkVersion) + displayName: 'Install spec-gen-sdk' + + - script: | + optional_params="" + sdk_gen_info="sdk generation from Config : " + + if [ "${{ parameters.ConfigType }}" = "TypeSpec" ]; then + optional_params="$optional_params --tsp-config-relative-path ${{ parameters.ConfigPath }}" + sdk_gen_info="$sdk_gen_info '${{ parameters.ConfigPath }}'," + else + optional_params="$optional_params --readme-relative-path ${{ parameters.ConfigPath }}" + sdk_gen_info="$sdk_gen_info '${{ parameters.ConfigPath }}'," + fi + + if [ "$(Build.Reason)" = "PullRequest" ]; then + optional_params="$optional_params --n=$(System.PullRequest.PullRequestNumber)" + specPrUrl="${{ parameters.SpecRepoUrl }}/pull/$(System.PullRequest.PullRequestNumber)" + sdk_gen_info="$sdk_gen_info spec PR: $specPrUrl" + fi + + sdk_gen_info="$sdk_gen_info and CommitSHA: '$(SpecRepoCommit)', in SpecRepo: '${{ parameters.SpecRepoUrl }}'" + echo "##vso[task.setvariable variable=GeneratedSDKInformation]$sdk_gen_info" + echo "Generated SDK Information : $sdk_gen_info" + + spec-gen-sdk \ + --scp "$(SpecRepoDirectory)" \ + --sdp "$(SdkRepoDirectory)" \ + --wf "$(System.DefaultWorkingDirectory)" \ + -l "$(SdkRepoName)" \ + -c "$(SpecRepoCommit)" \ + -t $true \ + $optional_params + displayName: 'Generate SDK' + + - task: PowerShell@2 + displayName: Add label to the spec PR + condition: and(eq(variables['Build.Reason'], 'PullRequest'), ne(variables['BreakingChangeLabel'], ''), eq(variables['BreakingChangeLabelAction'], 'add')) + inputs: + pwsh: true + workingDirectory: $(SdkRepoDirectory) + filePath: $(SdkRepoDirectory)/eng/common/scripts/Add-IssueLabels.ps1 + arguments: > + -RepoOwner $(SpecRepoOwner) + -RepoName $(SpecRepoName) + -IssueNumber "$(System.PullRequest.PullRequestNumber)" + -Labels $(BreakingChangeLabel) + -AuthToken "$(azuresdk-github-pat)" + + - task: PowerShell@2 + displayName: Remove label from the spec PR + condition: and(eq(variables['Build.Reason'], 'PullRequest'), ne(variables['BreakingChangeLabel'], ''), eq(variables['BreakingChangeLabelAction'], 'remove')) + inputs: + pwsh: true + workingDirectory: $(SdkRepoDirectory) + filePath: $(SdkRepoDirectory)/eng/common/scripts/Remove-IssueLabel.ps1 + arguments: > + -RepoOwner $(SpecRepoOwner) + -RepoName $(SpecRepoName) + -IssueNumber "$(System.PullRequest.PullRequestNumber)" + -LabelName $(BreakingChangeLabel) + -AuthToken "$(azuresdk-github-pat)" + + - ${{ if eq(parameters.SkipPullRequestCreation, false) }}: + - template: /eng/common/pipelines/templates/steps/git-push-changes.yml + parameters: + BaseRepoBranch: $(PrBranch)-$(Build.BuildId) + BaseRepoOwner: azure-sdk + CommitMsg: $(GeneratedSDKInformation) + TargetRepoOwner: $(SdkRepoOwner) + TargetRepoName: $(SdkRepoName) + PushArgs: "--force" + WorkingDirectory: $(SdkRepoDirectory) + ScriptDirectory: $(SdkRepoDirectory)/eng/common/scripts + + - task: PowerShell@2 + displayName: Create pull request + condition: and(succeeded(), eq(variables['HasChanges'], 'true'), ne(variables['Build.Reason'], 'PullRequest')) + inputs: + pwsh: true + workingDirectory: $(SdkRepoDirectory) + filePath: $(SdkRepoDirectory)/eng/common/scripts/Submit-PullRequest.ps1 + arguments: > + -RepoOwner "$(SdkRepoOwner)" + -RepoName "$(SdkRepoName)" + -BaseBranch "main" + -PROwner "azure-sdk" + -PRBranch "$(PrBranch)-$(Build.BuildId)" + -AuthToken "$(azuresdk-github-pat)" + -PRTitle "$(PrTitle)-generated-from-$(Build.DefinitionName)-$(Build.BuildId)" + -PRBody "$(GeneratedSDKInformation)" + -OpenAsDraft $true diff --git a/eng/common/pipelines/templates/steps/detect-api-changes.yml b/eng/common/pipelines/templates/steps/detect-api-changes.yml index 8d605d8694b1..2525dade5205 100644 --- a/eng/common/pipelines/templates/steps/detect-api-changes.yml +++ b/eng/common/pipelines/templates/steps/detect-api-changes.yml @@ -1,20 +1,22 @@ parameters: ArtifactPath: $(Build.ArtifactStagingDirectory) ArtifactName: 'packages' + RepoRoot: $(Build.SourcesDirectory) + Condition: true steps: - pwsh: | $apiChangeDetectRequestUrl = "https://apiview.dev/PullRequest/DetectApiChanges" echo "##vso[task.setvariable variable=ApiChangeDetectRequestUrl]$apiChangeDetectRequestUrl" displayName: "Set API change detect request URL" - condition: eq(variables['ApiChangeDetectRequestUrl'], '') + condition: and(${{ parameters.Condition}}, eq(variables['ApiChangeDetectRequestUrl'], '')) - task: Powershell@2 inputs: - filePath: $(Build.SourcesDirectory)/eng/common/scripts/Detect-Api-Changes.ps1 + filePath: ${{ parameters.RepoRoot }}/eng/common/scripts/Detect-Api-Changes.ps1 arguments: > -ArtifactPath ${{parameters.ArtifactPath}} - -CommitSha '$(Build.SourceVersion)' + -CommitSha '$(System.PullRequest.SourceCommitId)' -BuildId $(Build.BuildId) -PullRequestNumber $(System.PullRequest.PullRequestNumber) -RepoFullName $(Build.Repository.Name) @@ -23,4 +25,4 @@ steps: -DevopsProject $(System.TeamProject) pwsh: true displayName: Detect API changes - condition: and(succeededOrFailed(), eq(variables['Build.Reason'],'PullRequest')) + condition: and(${{ parameters.Condition }}, succeededOrFailed(), eq(variables['Build.Reason'],'PullRequest')) diff --git a/eng/common/pipelines/templates/steps/install-pipeline-generation.yml b/eng/common/pipelines/templates/steps/install-pipeline-generation.yml index e16671294fdc..94587dfc1979 100644 --- a/eng/common/pipelines/templates/steps/install-pipeline-generation.yml +++ b/eng/common/pipelines/templates/steps/install-pipeline-generation.yml @@ -9,7 +9,7 @@ steps: - script: > dotnet tool install Azure.Sdk.Tools.PipelineGenerator - --version 1.1.0-dev.20241204.1 + --version 1.1.0-dev.20250206.1 --add-source https://pkgs.dev.azure.com/azure-sdk/public/_packaging/azure-sdk-for-net/nuget/v3/index.json --tool-path ${{parameters.ToolPath}} workingDirectory: $(Pipeline.Workspace)/pipeline-generator diff --git a/eng/common/pipelines/templates/steps/save-package-properties.yml b/eng/common/pipelines/templates/steps/save-package-properties.yml index 5ac89da9cdee..fff6f3093633 100644 --- a/eng/common/pipelines/templates/steps/save-package-properties.yml +++ b/eng/common/pipelines/templates/steps/save-package-properties.yml @@ -66,5 +66,5 @@ steps: arguments: > -ServiceDirectory '${{parameters.ServiceDirectory}}' -OutDirectory '${{ parameters.PackageInfoDirectory }}' - -AddDevVersion:$${{ eq(variables['SetDevVersion'],'true') }} + -AddDevVersion:($env:SETDEVVERSION -eq 'true') pwsh: true diff --git a/eng/common/pipelines/templates/steps/set-test-pipeline-version.yml b/eng/common/pipelines/templates/steps/set-test-pipeline-version.yml index dee4e38349d2..61d49cdb7db4 100644 --- a/eng/common/pipelines/templates/steps/set-test-pipeline-version.yml +++ b/eng/common/pipelines/templates/steps/set-test-pipeline-version.yml @@ -2,6 +2,7 @@ parameters: PackageName: '' PackageNames: '' ServiceDirectory: '' + TagSeparator: '_' TestPipeline: false steps: @@ -16,4 +17,5 @@ steps: -BuildID $(Build.BuildId) -PackageNames '${{ coalesce(parameters.PackageName, parameters.PackageNames) }}' -ServiceDirectory '${{ parameters.ServiceDirectory }}' + -TagSeparator '${{ parameters.TagSeparator }}' pwsh: true diff --git a/eng/common/pipelines/templates/steps/sparse-checkout.yml b/eng/common/pipelines/templates/steps/sparse-checkout.yml index 9e3cc3164abf..d3992a85e3f6 100644 --- a/eng/common/pipelines/templates/steps/sparse-checkout.yml +++ b/eng/common/pipelines/templates/steps/sparse-checkout.yml @@ -11,11 +11,21 @@ parameters: - name: SkipCheckoutNone type: boolean default: false + - name: TokenToUseForAuth + type: string + default: '' steps: - ${{ if not(parameters.SkipCheckoutNone) }}: - checkout: none + - ${{ if ne(parameters.TokenToUseForAuth, '') }}: + - pwsh: | + $base64Token = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("nobody:${{ parameters.TokenToUseForAuth }}")) + Write-Host "##vso[task.setvariable variable=_base64AuthToken;issecret=true;]$base64Token" + git config set --global "http.extraheader" "AUTHORIZATION: basic $base64Token" + displayName: Setup git config auth header + - task: PowerShell@2 ${{ if eq(length(parameters.Repositories), 1) }}: displayName: 'Sparse checkout ${{ parameters.Repositories[0].Name }}' @@ -69,9 +79,9 @@ steps: if (Test-Path .git/info/sparse-checkout) { $hasInitialized = $true - Write-Host "Repository $($repository.Name) has already been initialized. Skipping this step." + Write-Host "Repository $($repository.Name) has already been initialized in $pwd. Skipping this step." } else { - Write-Host "Repository $($repository.Name) is being initialized." + Write-Host "Repository $($repository.Name) is being initialized in $pwd" if ($repository.Commitish -match '^refs/pull/\d+/merge$') { Retry git clone --no-checkout --filter=tree:0 -c remote.origin.fetch=''+$($repository.Commitish):refs/remotes/origin/$($repository.Commitish)'' https://github.com/$($repository.Name) . @@ -86,7 +96,10 @@ steps: # Set non-cone mode otherwise path filters will not work in git >= 2.37.0 # See https://github.blog/2022-06-27-highlights-from-git-2-37/#tidbits - git sparse-checkout set --no-cone '/*' '!/*/' '/eng' + # '/*' '!/*/' -> only checkout files in top level directory + # '/eng' -> checkout required eng/ scripts/configs + # '.config' -> required for files like .config/1espt/PipelineAutobaseliningConfig.yml and .config/guardian/.gdnbaselines used by 1es PT scripts + git sparse-checkout set --no-cone '/*' '!/*/' '/eng' '/.config' } # Prevent wildcard expansion in Invoke-Expression (e.g. for checkout path '/*') @@ -123,3 +136,9 @@ steps: } pwsh: true workingDirectory: $(System.DefaultWorkingDirectory) + + - ${{ if ne(parameters.TokenToUseForAuth, '') }}: + - pwsh: | + git config unset --global "http.extraheader" + displayName: Removing git config auth header + condition: always() diff --git a/eng/common/pipelines/templates/steps/validate-all-packages.yml b/eng/common/pipelines/templates/steps/validate-all-packages.yml index 679d8830a459..03a5f84cc29a 100644 --- a/eng/common/pipelines/templates/steps/validate-all-packages.yml +++ b/eng/common/pipelines/templates/steps/validate-all-packages.yml @@ -4,7 +4,7 @@ parameters: ConfigFileDir: $(Build.ArtifactStagingDirectory)/PackageInfo steps: - - ${{ if and(ne(variables['Skip.PackageValidation'], 'true'), eq(variables['System.TeamProject'], 'internal')) }}: + - ${{ if and(ne(variables['Skip.PackageValidation'], 'true'), and(ne(variables['Build.Reason'], 'PullRequest'), eq(variables['System.TeamProject'], 'internal'))) }}: - pwsh: | echo "##vso[task.setvariable variable=SetAsReleaseBuild]false" displayName: "Set as release build" diff --git a/eng/common/scripts/Detect-Api-Changes.ps1 b/eng/common/scripts/Detect-Api-Changes.ps1 index 72163ce66fda..6be93332118c 100644 --- a/eng/common/scripts/Detect-Api-Changes.ps1 +++ b/eng/common/scripts/Detect-Api-Changes.ps1 @@ -40,13 +40,22 @@ function Submit-Request($filePath, $packageName) $query.Add('language', $LanguageShort) $query.Add('project', $DevopsProject) $reviewFileFullName = Join-Path -Path $ArtifactPath $packageName $reviewFileName + # If CI generates token file then it passes both token file name and original file (filePath) to APIView + # If both files are passed then APIView downloads the parent directory as a zip + # If code file is not passed(for e.g. .NET or Java) then APIView needs full path to original file to download only that file. if (Test-Path $reviewFileFullName) { $query.Add('codeFile', $reviewFileName) + # Pass only relative path in package artifact directory when code file is also present + $query.Add('filePath', (Split-Path -Leaf $filePath)) + } + else + { + $query.Add('filePath', $filePath) } $uri = [System.UriBuilder]$APIViewUri $uri.query = $query.toString() - Write-Host "Request URI: $($uri.Uri.OriginalString)" + LogInfo "Request URI: $($uri.Uri.OriginalString)" try { $Response = Invoke-WebRequest -Method 'GET' -Uri $uri.Uri -MaximumRetryCount 3 @@ -54,7 +63,7 @@ function Submit-Request($filePath, $packageName) } catch { - Write-Host "Error $StatusCode - Exception details: $($_.Exception.Response)" + LogError "Error $StatusCode - Exception details: $($_.Exception.Response)" $StatusCode = $_.Exception.Response.StatusCode } @@ -67,7 +76,7 @@ function Should-Process-Package($pkgPath, $packageName) $pkgPropPath = Join-Path -Path $configFileDir "$packageName.json" if (!(Test-Path $pkgPropPath)) { - Write-Host " Package property file path $($pkgPropPath) is invalid." + LogWarning "Package property file path $($pkgPropPath) is invalid." return $False } # Get package info from json file created before updating version to daily dev @@ -75,27 +84,29 @@ function Should-Process-Package($pkgPath, $packageName) $packagePath = $pkgInfo.DirectoryPath $modifiedFiles = @(Get-ChangedFiles -DiffPath "$packagePath/*" -DiffFilterType '') $filteredFileCount = $modifiedFiles.Count - Write-Host "Number of modified files for package: $filteredFileCount" + LogInfo "Number of modified files for package: $filteredFileCount" return ($filteredFileCount -gt 0 -and $pkgInfo.IsNewSdk) } function Log-Input-Params() { - Write-Host "Artifact Path: $($ArtifactPath)" - Write-Host "Artifact Name: $($ArtifactName)" - Write-Host "PullRequest Number: $($PullRequestNumber)" - Write-Host "BuildId: $($BuildId)" - Write-Host "Language: $($Language)" - Write-Host "Commit SHA: $($CommitSha)" - Write-Host "Repo Name: $($RepoFullName)" - Write-Host "Project: $($DevopsProject)" + LogGroupStart "Input Parameters for $($ArtifactName)" + LogInfo "Artifact Path: $($ArtifactPath)" + LogInfo "Artifact Name: $($ArtifactName)" + LogInfo "PullRequest Number: $($PullRequestNumber)" + LogInfo "BuildId: $($BuildId)" + LogInfo "Language: $($Language)" + LogInfo "Commit SHA: $($CommitSha)" + LogInfo "Repo Name: $($RepoFullName)" + LogInfo "Project: $($DevopsProject)" + LogGroupEnd } Log-Input-Params if (!($FindArtifactForApiReviewFn -and (Test-Path "Function:$FindArtifactForApiReviewFn"))) { - Write-Host "The function for 'FindArtifactForApiReviewFn' was not found.` + LogError "The function for 'FindArtifactForApiReviewFn' was not found.` Make sure it is present in eng/scripts/Language-Settings.ps1 and referenced in eng/common/scripts/common.ps1.` See https://github.com/Azure/azure-sdk-tools/blob/main/doc/common/common_engsys.md#code-structure" exit 1 @@ -103,42 +114,48 @@ if (!($FindArtifactForApiReviewFn -and (Test-Path "Function:$FindArtifactForApiR $responses = @{} +LogInfo "Processing PackageInfo at $configFileDir" + $packageProperties = Get-ChildItem -Recurse -Force "$configFileDir" ` - | Where-Object { $_.Extension -eq '.json' } + | Where-Object { + $_.Extension -eq '.json' -and ($_.FullName.Substring($configFileDir.Length + 1) -notmatch '^_.*?[\\\/]') + } foreach ($packagePropFile in $packageProperties) { $packageMetadata = Get-Content $packagePropFile | ConvertFrom-Json - Write-Host "Processing $($packageMetadata.ArtifactName)" + $pkgArtifactName = $packageMetadata.ArtifactName ?? $packageMetadata.Name + + LogInfo "Processing $($pkgArtifactName)" - $packages = &$FindArtifactForApiReviewFn $ArtifactPath $packageMetadata.ArtifactName + $packages = &$FindArtifactForApiReviewFn $ArtifactPath $pkgArtifactName if ($packages) { $pkgPath = $packages.Values[0] - $isRequired = Should-Process-Package -pkgPath $pkgPath -packageName $($packageMetadata.ArtifactName) - Write-Host "Is API change detect required for $($packages.ArtifactName):$($isRequired)" + $isRequired = Should-Process-Package -pkgPath $pkgPath -packageName $pkgArtifactName + LogInfo "Is API change detect required for $($pkgArtifactName):$($isRequired)" if ($isRequired -eq $True) { $filePath = $pkgPath.Replace($ArtifactPath , "").Replace("\", "/") - $respCode = Submit-Request -filePath $filePath -packageName $($packageMetadata.ArtifactName) + $respCode = Submit-Request -filePath $filePath -packageName $pkgArtifactName if ($respCode -ne '200') { - $responses[$($packageMetadata.ArtifactName)] = $respCode + $responses[$pkgArtifactName] = $respCode } } else { - Write-Host "Pull request does not have any change for $($packageMetadata.ArtifactName)). Skipping API change detect." + LogInfo "Pull request does not have any change for $($pkgArtifactName)). Skipping API change detect." } } else { - Write-Host "No package is found in artifact path to find API changes for $($packageMetadata.ArtifactName)" + LogInfo "No package is found in artifact path to find API changes for $($pkgArtifactName)" } } foreach($pkg in $responses.keys) { - Write-Host "API detection request status for $($pkg) : $($responses[$pkg])" + LogInfo "API detection request status for $($pkg) : $($responses[$pkg])" } diff --git a/eng/common/scripts/Generate-PR-Diff.ps1 b/eng/common/scripts/Generate-PR-Diff.ps1 index e010e176399d..50f6ec2b2d1a 100644 --- a/eng/common/scripts/Generate-PR-Diff.ps1 +++ b/eng/common/scripts/Generate-PR-Diff.ps1 @@ -48,10 +48,15 @@ $changedFiles = @() $changedServices = @() $changedFiles = Get-ChangedFiles -DiffPath $TargetPath +$deletedFiles = Get-ChangedFiles -DiffPath $TargetPath -DiffFilterType "D" if ($changedFiles) { $changedServices = Get-ChangedServices -ChangedFiles $changedFiles } +else { + # ensure we default this to an empty array if not set + $changedFiles = @() +} # ExcludePaths is an object array with the default of [] which evaluates to null. # If the value is null, set it to empty list to ensure that the empty list is @@ -59,10 +64,17 @@ if ($changedFiles) { if (-not $ExcludePaths) { $ExcludePaths = @() } +if (-not $deletedFiles) { + $deletedFiles = @() +} +if (-not $changedServices) { + $changedServices = @() +} $result = [PSCustomObject]@{ "ChangedFiles" = $changedFiles "ChangedServices" = $changedServices "ExcludePaths" = $ExcludePaths + "DeletedFiles" = $deletedFiles "PRNumber" = if ($env:SYSTEM_PULLREQUEST_PULLREQUESTNUMBER) { $env:SYSTEM_PULLREQUEST_PULLREQUESTNUMBER } else { "-1" } } diff --git a/eng/common/scripts/Helpers/DevOps-WorkItem-Helpers.ps1 b/eng/common/scripts/Helpers/DevOps-WorkItem-Helpers.ps1 index 010c84f92015..9a46e2c126f1 100644 --- a/eng/common/scripts/Helpers/DevOps-WorkItem-Helpers.ps1 +++ b/eng/common/scripts/Helpers/DevOps-WorkItem-Helpers.ps1 @@ -55,7 +55,7 @@ function Invoke-Query($fields, $wiql, $output = $true) } $response = Invoke-RestMethod -Method POST ` - -Uri "https://dev.azure.com/azure-sdk/Release/_apis/wit/wiql/?`$top=10000&api-version=6.0" ` + -Uri "https://dev.azure.com/azure-sdk/Release/_apis/wit/wiql/?`$top=100000&api-version=6.0" ` -Headers (Get-DevOpsRestHeaders) -Body $body -ContentType "application/json" | ConvertTo-Json -Depth 10 | ConvertFrom-Json -AsHashTable if ($response -isnot [HashTable] -or !$response.ContainsKey("workItems") -or $response.workItems.Count -eq 0) { diff --git a/eng/common/scripts/Helpers/PSModule-Helpers.ps1 b/eng/common/scripts/Helpers/PSModule-Helpers.ps1 index da2e6de4cc69..f79ce1a5214b 100644 --- a/eng/common/scripts/Helpers/PSModule-Helpers.ps1 +++ b/eng/common/scripts/Helpers/PSModule-Helpers.ps1 @@ -79,7 +79,7 @@ function moduleIsInstalled([string]$moduleName, [string]$version) { if ($version -as [Version]) { $modules = $modules.Where({ [Version]$_.Version -ge [Version]$version }) if ($modules.Count -gt 0) { - Write-Host "Using module $($modules[0].Name) with version $($modules[0].Version)." + Write-Verbose "Using module $($modules[0].Name) with version $($modules[0].Version)." return $modules[0] } } @@ -100,9 +100,9 @@ function installModule([string]$moduleName, [string]$version, $repoUrl) { Set-PSRepository -Name $repo.Name -InstallationPolicy "Trusted" | Out-Null } - Write-Host "Installing module $moduleName with min version $version from $repoUrl" + Write-Verbose "Installing module $moduleName with min version $version from $repoUrl" # Install under CurrentUser scope so that the end up under $CurrentUserModulePath for caching - Install-Module $moduleName -MinimumVersion $version -Repository $repo.Name -Scope CurrentUser -Force + Install-Module $moduleName -MinimumVersion $version -Repository $repo.Name -Scope CurrentUser -Force -WhatIf:$false # Ensure module installed $modules = (Get-Module -ListAvailable $moduleName) if ($version -as [Version]) { @@ -171,7 +171,7 @@ function Install-ModuleIfNotInstalled() { break } - Write-Host "Using module '$($module.Name)' with version '$($module.Version)'." + Write-Verbose "Using module '$($module.Name)' with version '$($module.Version)'." } finally { $mutex.ReleaseMutex() diff --git a/eng/common/scripts/Helpers/Package-Helpers.ps1 b/eng/common/scripts/Helpers/Package-Helpers.ps1 index b545872dbbbd..084bc34ab529 100644 --- a/eng/common/scripts/Helpers/Package-Helpers.ps1 +++ b/eng/common/scripts/Helpers/Package-Helpers.ps1 @@ -155,7 +155,7 @@ function GetValueSafelyFrom-Yaml { ) $current = $YamlContentAsHashtable foreach ($key in $Keys) { - if ($current.ContainsKey($key) -or $current[$key]) { + if ($current -is [HashTable] -and ($current.ContainsKey($key) -or $current[$key])) { $current = $current[$key] } else { @@ -178,13 +178,13 @@ function Get-ObjectKey { if ($Object -is [hashtable] -or $Object -is [System.Collections.Specialized.OrderedDictionary]) { $sortedEntries = $Object.GetEnumerator() | Sort-Object Name - $hashString = ($sortedEntries | ForEach-Object { "$($_.Key)=$($_.Value)" }) -join ";" + $hashString = ($sortedEntries | ForEach-Object { "$($_.Key)=$(Get-ObjectKey $_.Value)" }) -join ";" return $hashString.GetHashCode() } elseif ($Object -is [PSCustomObject]) { $sortedProperties = $Object.PSObject.Properties | Sort-Object Name - $propertyString = ($sortedProperties | ForEach-Object { "$($_.Name)=$($_.Value)" }) -join ";" + $propertyString = ($sortedProperties | ForEach-Object { "$($_.Name)=$(Get-ObjectKey $_.Value)" }) -join ";" return $propertyString.GetHashCode() } @@ -194,7 +194,12 @@ function Get-ObjectKey { } else { - return $Object.GetHashCode() + $parsedBool = $null + if ([bool]::TryParse($Object, [ref]$parsedBool)) { + return $parsedBool.GetHashCode() + } else { + return $Object.GetHashCode() + } } } @@ -210,14 +215,33 @@ function Group-ByObjectKey { $groupedDictionary = @{} foreach ($item in $Items) { - $key = Get-ObjectKey $item."$GroupByProperty" + # if the item is an array, we need to group by each element in the array + # however if it's an empty array we want to treat it as a single item + if ($item."$GroupByProperty" -and $item."$GroupByProperty" -is [array]) { + foreach ($GroupByPropertyValue in $item."$GroupByProperty") { + $key = Get-ObjectKey $GroupByPropertyValue + + if (-not $groupedDictionary.ContainsKey($key)) { + $groupedDictionary[$key] = @() + } - if (-not $groupedDictionary.ContainsKey($key)) { - $groupedDictionary[$key] = @() + $groupedDictionary[$key] += $item + } } + else { + if ($item."$GroupByProperty") { + $key = Get-ObjectKey $item."$GroupByProperty" + } + else { + $key = "unset" + } + + if (-not $groupedDictionary.ContainsKey($key)) { + $groupedDictionary[$key] = @() + } - # Add the current item to the array for this key - $groupedDictionary[$key] += $item + $groupedDictionary[$key] += $item + } } return $groupedDictionary diff --git a/eng/common/scripts/Invoke-GitHubAPI.ps1 b/eng/common/scripts/Invoke-GitHubAPI.ps1 index c4a9fa5bb11e..3c7c0596dfcd 100644 --- a/eng/common/scripts/Invoke-GitHubAPI.ps1 +++ b/eng/common/scripts/Invoke-GitHubAPI.ps1 @@ -258,6 +258,39 @@ function Add-GitHubIssueComment { -MaximumRetryCount 3 } +# Will delete label from the issue if it exists +function Remove-GitHubIssueLabel { + param ( + [Parameter(Mandatory = $true)] + $RepoOwner, + [Parameter(Mandatory = $true)] + $RepoName, + [Parameter(Mandatory = $true)] + $IssueNumber, + [ValidateNotNullOrEmpty()] + [Parameter(Mandatory = $true)] + $LabelName, + [ValidateNotNullOrEmpty()] + [Parameter(Mandatory = $true)] + $AuthToken + ) + + if ($LabelName.Trim().Length -eq 0) + { + throw " The 'LabelName' parameter should not be empty or whitespace." + } + # Encode the label name + $encodedLabelName = [System.Web.HttpUtility]::UrlEncode($LabelName) + + $uri = "$GithubAPIBaseURI/$RepoOwner/$RepoName/issues/$IssueNumber/labels/$encodedLabelName" + + return Invoke-RestMethod ` + -Method DELETE ` + -Uri $uri ` + -Headers (Get-GitHubApiHeaders -token $AuthToken) ` + -MaximumRetryCount 3 +} + # Will add labels to existing labels on the issue function Add-GitHubIssueLabels { param ( diff --git a/eng/common/scripts/Package-Properties.ps1 b/eng/common/scripts/Package-Properties.ps1 index bc7b5738e2d3..f8daf09c29f6 100644 --- a/eng/common/scripts/Package-Properties.ps1 +++ b/eng/common/scripts/Package-Properties.ps1 @@ -20,7 +20,7 @@ class PackageProps { # additional packages required for validation of this one [string[]]$AdditionalValidationPackages [HashTable]$ArtifactDetails - [HashTable[]]$CIMatrixConfigs + [HashTable]$CIParameters PackageProps([string]$name, [string]$version, [string]$directoryPath, [string]$serviceDirectory) { $this.Initialize($name, $version, $directoryPath, $serviceDirectory) @@ -61,6 +61,7 @@ class PackageProps { $this.ChangeLogPath = $null } + $this.CIParameters = @{"CIMatrixConfigs" = @()} $this.InitializeCIArtifacts() } @@ -89,14 +90,8 @@ class PackageProps { if ($artifactForCurrentPackage) { $result = [PSCustomObject]@{ ArtifactConfig = [HashTable]$artifactForCurrentPackage - MatrixConfigs = @() - } - - # if we know this is the matrix for our file, we should now see if there is a custom matrix config for the package - $matrixConfigList = GetValueSafelyFrom-Yaml $content @("extends", "parameters", "MatrixConfigs") - - if ($matrixConfigList) { - $result.MatrixConfigs = $matrixConfigList + ParsedYml = $content + Location = $ymlPath } return $result @@ -105,25 +100,77 @@ class PackageProps { return $null } + [PSCustomObject]GetCIYmlForArtifact() { + $RepoRoot = Resolve-Path (Join-Path $PSScriptRoot ".." ".." "..") + + $ciFolderPath = Join-Path -Path $RepoRoot -ChildPath (Join-Path "sdk" $this.ServiceDirectory) + $ciFiles = Get-ChildItem -Path $ciFolderPath -Filter "ci*.yml" -File + $ciArtifactResult = $null + + foreach ($ciFile in $ciFiles) { + $ciArtifactResult = $this.ParseYmlForArtifact($ciFile.FullName) + if ($ciArtifactResult) { + break + } + } + + return $ciArtifactResult + } + [void]InitializeCIArtifacts() { if (-not $env:SYSTEM_TEAMPROJECTID -and -not $env:GITHUB_ACTIONS) { return } - $RepoRoot = Resolve-Path (Join-Path $PSScriptRoot ".." ".." "..") + if (-not $this.ArtifactDetails) { + $ciArtifactResult = $this.GetCIYmlForArtifact() - $ciFolderPath = Join-Path -Path $RepoRoot -ChildPath (Join-Path "sdk" $this.ServiceDirectory) - $ciFiles = Get-ChildItem -Path $ciFolderPath -Filter "ci*.yml" -File + if ($ciArtifactResult) { + $this.ArtifactDetails = [Hashtable]$ciArtifactResult.ArtifactConfig - if (-not $this.ArtifactDetails) { - foreach ($ciFile in $ciFiles) { - $ciArtifactResult = $this.ParseYmlForArtifact($ciFile.FullName) - if ($ciArtifactResult) { - $this.ArtifactDetails = [Hashtable]$ciArtifactResult.ArtifactConfig - $this.CIMatrixConfigs = $ciArtifactResult.MatrixConfigs - # if this package appeared in this ci file, then we should - # treat this CI file as the source of the Matrix for this package - break + $repoRoot = Resolve-Path (Join-Path $PSScriptRoot ".." ".." "..") + $ciYamlPath = (Resolve-Path -Path $ciArtifactResult.Location -Relative -RelativeBasePath $repoRoot).TrimStart(".").Replace("`\", "/") + $relRoot = [System.IO.Path]::GetDirectoryName($ciYamlPath).Replace("`\", "/") + + if (-not $this.ArtifactDetails["triggeringPaths"]) { + $this.ArtifactDetails["triggeringPaths"] = @() + } + else { + $adjustedPaths = @() + + # we need to convert relative references to absolute references within the repo + # this will make it extremely easy to compare triggering paths to files in the deleted+changed file list. + for ($i = 0; $i -lt $this.ArtifactDetails["triggeringPaths"].Count; $i++) { + $currentPath = $this.ArtifactDetails["triggeringPaths"][$i] + $newPath = Join-Path $repoRoot $currentPath + if (!$currentPath.StartsWith("/")) { + $newPath = Join-Path $repoRoot $relRoot $currentPath + } + # it is a possibility that users may have a triggerPath dependency on a file that no longer exists. + # before we resolve it to get rid of possible relative references, we should check if the file exists + # if it doesn't, we should just leave it as is. Otherwise we would _crash_ here when a user accidentally + # left a triggeringPath on a file that had been deleted + if (Test-Path $newPath) { + $adjustedPaths += (Resolve-Path -Path $newPath -Relative -RelativeBasePath $repoRoot).TrimStart(".").Replace("`\", "/") + } + } + $this.ArtifactDetails["triggeringPaths"] = $adjustedPaths + } + $this.ArtifactDetails["triggeringPaths"] += $ciYamlPath + + $this.CIParameters["CIMatrixConfigs"] = @() + + # if we know this is the matrix for our file, we should now see if there is a custom matrix config for the package + $matrixConfigList = GetValueSafelyFrom-Yaml $ciArtifactResult.ParsedYml @("extends", "parameters", "MatrixConfigs") + + if ($matrixConfigList) { + $this.CIParameters["CIMatrixConfigs"] += $matrixConfigList + } + + $additionalMatrixConfigList = GetValueSafelyFrom-Yaml $ciArtifactResult.ParsedYml @("extends", "parameters", "AdditionalMatrixConfigs") + + if ($additionalMatrixConfigList) { + $this.CIParameters["CIMatrixConfigs"] += $additionalMatrixConfigList } } } @@ -156,42 +203,197 @@ function Get-PkgProperties { return $null } + +function Get-TriggerPaths([PSCustomObject]$AllPackageProperties) { + $existingTriggeringPaths = @() + $AllPackageProperties | ForEach-Object { + if ($_.ArtifactDetails) { + $pathsForArtifact = $_.ArtifactDetails["triggeringPaths"] + foreach ($triggerPath in $pathsForArtifact){ + # we only care about triggering paths that are actual files, not directories + # go by by the assumption that if the triggerPath has an extension, it's a file :) + if ([System.IO.Path]::HasExtension($triggerPath)) { + $existingTriggeringPaths += $triggerPath + } + } + } + } + + return ($existingTriggeringPaths | Select-Object -Unique) +} + +function Update-TargetedFilesForTriggerPaths([string[]]$TargetedFiles, [string[]]$TriggeringPaths) { + # now we simply loop through the files a single time, keeping all the files that are a triggeringPath + # for the rest of the files, simply group by what directory they belong to + # the new TargetedFiles array will contain only the changed directories + the files that actually aligned to a triggeringPath + $processedFiles = @() + $Triggers = [System.Collections.ArrayList]$TriggeringPaths + $i = 0 + foreach ($file in $TargetedFiles) { + $isExistingTriggerPath = $false + + for ($i = 0; $i -lt $Triggers.Count; $i++) { + $triggerPath = $Triggers[$i] + if ($triggerPath -and $file -eq "$triggerPath") { + $isExistingTriggerPath = $true + break + } + } + + if ($isExistingTriggerPath) { + # we know that we should have a valid $i that we can use to remove the triggerPath from the list + # so that it gets smaller as we find items + $Triggers.RemoveAt($i) + $processedFiles += $file + } + else { + # Get directory path by removing the filename + $directoryPath = Split-Path -Path $file -Parent + if ($directoryPath) { + $processedFiles += $directoryPath + } else { + # In case there's no parent directory (root file), keep the original + $processedFiles += $file + } + } + } + + return ($processedFiles | Select-Object -Unique) +} + +function Update-TargetedFilesForExclude([string[]]$TargetedFiles, [string[]]$ExcludePaths) { + $files = @() + foreach ($file in $TargetedFiles) { + $shouldExclude = $false + foreach ($exclude in $ExcludePaths) { + if (!$file.StartsWith($exclude,'CurrentCultureIgnoreCase')) { + $shouldExclude = $true + break + } + } + if (!$shouldExclude) { + $files += $file + } + } + return ,$files +} + function Get-PrPkgProperties([string]$InputDiffJson) { $packagesWithChanges = @() + $additionalValidationPackages = @() + $lookup = @{} + $directoryIndex = @{} $allPackageProperties = Get-AllPkgProperties $diff = Get-Content $InputDiffJson | ConvertFrom-Json $targetedFiles = $diff.ChangedFiles - # The exclude paths and the targeted files paths aren't full OS paths, they're - # GitHub paths meaning they're relative to the repo root and slashes are forward - # slashes "/". The ExcludePaths need to have a trailing slash added in order - # correctly test for string matches without overmatching. For example, if a pr - # had files sdk/foo/file1 and sdk/foobar/file2 with the exclude of anything in - # sdk/foo, it should only exclude things under sdk/foo. The TrimEnd is just in - # case one of the paths ends with a slash, it doesn't add a second one. - $excludePaths = $diff.ExcludePaths | ForEach-Object { $_.TrimEnd("/") + "/" } - $additionalValidationPackages = @() - $lookup = @{} + if ($diff.DeletedFiles) { + if (-not $targetedFiles) { + $targetedFiles = @() + } + $targetedFiles += $diff.DeletedFiles + } + $existingTriggeringPaths = Get-TriggerPaths $allPackageProperties + $targetedFiles = Update-TargetedFilesForExclude $targetedFiles $diff.ExcludePaths + $targetedFiles = Update-TargetedFilesForTriggerPaths $targetedFiles $existingTriggeringPaths + + # Sort so that we very quickly find any directly changed packages before hitting service level changes. + # This is important because due to the way we traverse the changed files, the instant we evaluate a pkg + # as directly or indirectly changed, we exit the file loop and move on to the next pkg. + # The problem is, a package may be detected as indirectly changed _before_ we get to the file that directly changed it! + # To avoid this without wonky changes to the detection algorithm, we simply sort our files by their depth, so we will always + # detect direct package changes first! + $targetedFiles = $targetedFiles | Sort-Object { ($_.Split("/").Count) } -Descending + $pkgCounter = 1 + + # this is the primary loop that identifies the packages that have changes foreach ($pkg in $allPackageProperties) { + Write-Host "Processing changed files against $($pkg.Name). $pkgCounter of $($allPackageProperties.Count)." $pkgDirectory = Resolve-Path "$($pkg.DirectoryPath)" $lookupKey = ($pkg.DirectoryPath).Replace($RepoRoot, "").TrimStart('\/') $lookup[$lookupKey] = $pkg + # we only honor the individual artifact triggers + # if we were to honor the ci-level triggers, we would simply + # end up in a situation where any change to a service would + # still trigger every package in that service. individual package triggers + # must be added to handle this. + $triggeringPaths = @() + if ($pkg.ArtifactDetails -and $pkg.ArtifactDetails["triggeringPaths"]) { + $triggeringPaths = $pkg.ArtifactDetails["triggeringPaths"] + } + foreach ($file in $targetedFiles) { - $shouldExclude = $false - foreach ($exclude in $excludePaths) { - if ($file.StartsWith($exclude,'CurrentCultureIgnoreCase')) { - $shouldExclude = $true + $filePath = (Join-Path $RepoRoot $file) + + # handle direct changes to packages + $shouldInclude = $filePath -eq $pkgDirectory -or $filePath -like (Join-Path "$pkgDirectory" "*") + + # we only need to do additional work for indirect packages if we haven't already decided + # to include this package due to this file + if (-not $shouldInclude) { + # handle changes to files that are RELATED to each package + foreach($triggerPath in $triggeringPaths) { + $resolvedRelativePath = (Join-Path $RepoRoot $triggerPath) + # triggerPaths can be direct files, so we need to check both startswith and direct equality + $includedForValidation = ($filePath -like (Join-Path "$resolvedRelativePath" "*") -or $filePath -eq $resolvedRelativePath) + $shouldInclude = $shouldInclude -or $includedForValidation + if ($includedForValidation) { + $pkg.IncludedForValidation = $true + } break } + + # handle service-level changes to the ci.yml files + # we are using the ci.yml file being added automatically to each artifactdetails as the input + # for this task. This is because we can resolve a service directory from the ci.yml, and if + # there is a single ci.yml in that directory, we can assume that any file change in that directory + # will apply to all packages that exist in that directory. + $triggeringCIYmls = $triggeringPaths | Where-Object { $_ -like "*ci*.yml" } + + foreach($yml in $triggeringCIYmls) { + # given that this path is coming from the populated triggering paths in the artifact, + # we can assume that the path to the ci.yml will successfully resolve. + $ciYml = Join-Path $RepoRoot $yml + # ensure we terminate the service directory with a / + $directory = [System.IO.Path]::GetDirectoryName($ciYml).Replace("`\", "/") + + # we should only continue with this check if the file being changed is "in the service directory" + # files that are directly included in triggerPaths will kept in full form, but otherwise we pre-process the targetedFiles to the + # directory containing the change. Given that pre-process, we should check both direct equality (when not triggeringPath) and parent directory + # for the case where the full form of the file has been left behind (because it was a triggeringPath) + $serviceDirectoryChange = (Split-Path $filePath -Parent).Replace("`\", "/") -eq $directory -or $filePath.Replace("`\", "/") -eq $directory + if (!$serviceDirectoryChange) { + break + } + + # this GCI is very expensive, so we want to cache the result + $soleCIYml = $true + if ($directoryIndex[$directory]) { + $soleCIYml = $directoryIndex[$directory] + } + else { + $soleCIYml = (Get-ChildItem -Path $directory -Filter "ci*.yml" -File).Count -eq 1 + $directoryIndex[$directory] = $soleCIYml + } + + if ($soleCIYml -and $filePath.Replace("`\", "/").StartsWith($directory)) { + if (-not $shouldInclude) { + $pkg.IncludedForValidation = $true + $shouldInclude = $true + } + break + } + else { + # if the ci.yml is not the only file in the directory, we cannot assume that any file changed within the directory that isn't the ci.yml + # should trigger this package + Write-Host "Skipping adding package for file `"$file`" because the ci yml `"$yml`" is not the only file in the service directory `"$directory`"" + } + } } - if ($shouldExclude) { - continue - } - $filePath = (Join-Path $RepoRoot $file) - $shouldInclude = $filePath -like (Join-Path "$pkgDirectory" "*") + if ($shouldInclude) { $packagesWithChanges += $pkg @@ -203,8 +405,13 @@ function Get-PrPkgProperties([string]$InputDiffJson) { break } } + + $pkgCounter++ } + # add all of the packages that were added purely for validation purposes + # this is executed separately because we need to identify packages added this way as only included for validation + # we don't actually need to build or analyze them. only test them. $existingPackageNames = @($packagesWithChanges | ForEach-Object { $_.Name }) foreach ($addition in $additionalValidationPackages) { $key = $addition.Replace($RepoRoot, "").TrimStart('\/') @@ -219,10 +426,21 @@ function Get-PrPkgProperties([string]$InputDiffJson) { } } + # now pass along the set of packages we've identified, the diff itself, and the full set of package properties + # to locate any additional packages that should be included for validation if ($AdditionalValidationPackagesFromPackageSetFn -and (Test-Path "Function:$AdditionalValidationPackagesFromPackageSetFn")) { $packagesWithChanges += &$AdditionalValidationPackagesFromPackageSetFn $packagesWithChanges $diff $allPackageProperties } + # finally, if we have gotten all the way here and we still don't have any packages, we should include the template service + # packages. We should never return NO validation. + if ($packagesWithChanges.Count -eq 0) { + $packagesWithChanges += ($allPackageProperties | Where-Object { $_.ServiceDirectory -eq "template" }) + foreach ($package in $packagesWithChanges) { + $package.IncludedForValidation = $true + } + } + return $packagesWithChanges } diff --git a/eng/common/scripts/Remove-IssueLabel.ps1 b/eng/common/scripts/Remove-IssueLabel.ps1 new file mode 100644 index 000000000000..1af5bea443c9 --- /dev/null +++ b/eng/common/scripts/Remove-IssueLabel.ps1 @@ -0,0 +1,32 @@ +[CmdletBinding(SupportsShouldProcess = $true)] +param( + [Parameter(Mandatory = $true)] + [string]$RepoOwner, + + [Parameter(Mandatory = $true)] + [string]$RepoName, + + [Parameter(Mandatory = $true)] + [string]$IssueNumber, + + [Parameter(Mandatory = $true)] + [string]$LabelName, + + [Parameter(Mandatory = $true)] + [string]$AuthToken +) + +. (Join-Path $PSScriptRoot common.ps1) + +try { + Remove-GitHubIssueLabel -RepoOwner $RepoOwner -RepoName $RepoName ` + -IssueNumber $IssueNumber -LabelName $LabelName -AuthToken $AuthToken +} +catch { + if ($_.Exception.Response.StatusCode -eq 404) { + LogWarning "Label $LabelName not found on issue" + exit 0 + } + LogError "Remove-GithubIssueLabel failed with exception:`n$_" + exit 1 +} \ No newline at end of file diff --git a/eng/common/scripts/SemVer.ps1 b/eng/common/scripts/SemVer.ps1 index 6459f252a67c..689a70e778c4 100644 --- a/eng/common/scripts/SemVer.ps1 +++ b/eng/common/scripts/SemVer.ps1 @@ -78,13 +78,10 @@ class AzureEngSemanticVersion : IComparable { if ($null -eq $matches['prelabel']) { - # artifically provide these values for non-prereleases to enable easy sorting of them later than prereleases. - $this.PrereleaseLabel = "zzz" - $this.PrereleaseNumber = 99999999 $this.IsPrerelease = $false $this.VersionType = "GA" if ($this.Major -eq 0) { - # Treat initial 0 versions as a prerelease beta's + # Treat initial 0 versions as a prerelease beta's $this.VersionType = "Beta" $this.IsPrerelease = $true } @@ -116,7 +113,7 @@ class AzureEngSemanticVersion : IComparable { # See https://azure.github.io/azure-sdk/policies_releases.html#package-versioning [bool] HasValidPrereleaseLabel() { - if ($this.IsPrerelease -eq $true) { + if ($this.PrereleaseLabel) { if ($this.PrereleaseLabel -ne $this.DefaultPrereleaseLabel -and $this.PrereleaseLabel -ne $this.DefaultAlphaReleaseLabel) { Write-Host "Unexpected pre-release identifier '$($this.PrereleaseLabel)', "` "should be '$($this.DefaultPrereleaseLabel)' or '$($this.DefaultAlphaReleaseLabel)'" @@ -136,7 +133,7 @@ class AzureEngSemanticVersion : IComparable { { $versionString = "{0}.{1}.{2}" -F $this.Major, $this.Minor, $this.Patch - if ($this.IsPrerelease -and $this.PrereleaseLabel -ne "zzz") + if ($this.PrereleaseLabel) { $versionString += $this.PrereleaseLabelSeparator + $this.PrereleaseLabel + ` $this.PrereleaseNumberSeparator + $this.PrereleaseNumber @@ -147,24 +144,42 @@ class AzureEngSemanticVersion : IComparable { return $versionString; } - [void] IncrementAndSetToPrerelease() { - if ($this.IsPrerelease -eq $false) + [void] IncrementAndSetToPrerelease($Segment) { + if ($this.BuildNumber) { - $this.PrereleaseLabel = $this.DefaultPrereleaseLabel - $this.PrereleaseNumber = 1 - $this.Minor++ - $this.Patch = 0 - $this.IsPrerelease = $true + throw "Cannot increment releases tagged with azure pipelines build numbers" + } + + if ($this.PrereleaseLabel) + { + $this.PrereleaseNumber++ } else { - if ($this.BuildNumber) { - throw "Cannot increment releases tagged with azure pipelines build numbers" + $this.$Segment++ + if($Segment -eq "Major") { + $this.Minor = 0 + $this.Patch = 0 } - $this.PrereleaseNumber++ + if($Segment -eq "Minor") { + $this.Patch = 0 + } + + # If the major version is 0, we don't need a prerelease label + if ($this.Major -ne 0) + { + $this.PrereleaseLabel = $this.DefaultPrereleaseLabel + $this.PrereleaseNumber = 1 + } + + $this.IsPrerelease = $true } } + [void] IncrementAndSetToPrerelease() { + $this.IncrementAndSetToPrerelease("Minor") + } + [void] SetupPythonConventions() { # Python uses no separators and "b" for beta so this sets up the the object to work with those conventions @@ -198,11 +213,30 @@ class AzureEngSemanticVersion : IComparable { $ret = $this.Patch.CompareTo($other.Patch) if ($ret) { return $ret } + # provide artificial prerelease values for non-prereleases to sort them later than prereleases. + if ($this.PrereleaseLabel) { + $thisPrereleaseLabel = $this.PrereleaseLabel + $thisPrereleaseNumber = $this.PrereleaseNumber + } + else { + $thisPrereleaseLabel = "zzz" + $thisPrereleaseNumber = 99999999 + } + + if ($other.PrereleaseLabel) { + $otherPrereleaseLabel = $other.PrereleaseLabel + $otherPrereleaseNumber = $other.PrereleaseNumber + } + else { + $otherPrereleaseLabel = "zzz" + $otherPrereleaseNumber = 99999999 + } + # Mimic PowerShell that uses case-insensitive comparisons by default. - $ret = [string]::Compare($this.PrereleaseLabel, $other.PrereleaseLabel, $true) + $ret = [string]::Compare($thisPrereleaseLabel, $otherPrereleaseLabel, $true) if ($ret) { return $ret } - $ret = $this.PrereleaseNumber.CompareTo($other.PrereleaseNumber) + $ret = $thisPrereleaseNumber.CompareTo($otherPrereleaseNumber) if ($ret) { return $ret } return ([int] $this.BuildNumber).CompareTo([int] $other.BuildNumber) @@ -360,6 +394,41 @@ class AzureEngSemanticVersion : IComparable { Write-Host "Error: Python beta string did not correctly increment" } + $version = [AzureEngSemanticVersion]::ParseVersionString("0.1.2") + $version.IncrementAndSetToPrerelease() + $expected = "0.2.0" + if ($expected -ne $version.ToString()) { + Write-Host "Error: version string did not correctly increment. Expected: $expected, Actual: $version" + } + + $version = [AzureEngSemanticVersion]::ParseVersionString("0.1.2") + $version.IncrementAndSetToPrerelease("patch") + $expected = "0.1.3" + if ($expected -ne $version.ToString()) { + Write-Host "Error: version string did not correctly increment. Expected: $expected, Actual: $version" + } + + $version = [AzureEngSemanticVersion]::ParseVersionString("0.1.2") + $version.IncrementAndSetToPrerelease("minor") + $expected = "0.2.0" + if ($expected -ne $version.ToString()) { + Write-Host "Error: version string did not correctly increment. Expected: $expected, Actual: $version" + } + + $version = [AzureEngSemanticVersion]::ParseVersionString("0.1.2") + $version.IncrementAndSetToPrerelease("major") + $expected = "1.0.0-beta.1" + if ($expected -ne $version.ToString()) { + Write-Host "Error: version string did not correctly increment. Expected: $expected, Actual: $version" + } + + $version = [AzureEngSemanticVersion]::ParseVersionString("1.0.0-beta.1") + $version.IncrementAndSetToPrerelease() + $expected = "1.0.0-beta.2" + if ($expected -ne $version.ToString()) { + Write-Host "Error: version string did not correctly increment. Expected: $expected, Actual: $version" + } + Write-Host "QuickTests done" } -} +} \ No newline at end of file diff --git a/eng/common/scripts/SetTestPipelineVersion.ps1 b/eng/common/scripts/SetTestPipelineVersion.ps1 index a24c011f85eb..2b2ee70ef97e 100644 --- a/eng/common/scripts/SetTestPipelineVersion.ps1 +++ b/eng/common/scripts/SetTestPipelineVersion.ps1 @@ -6,7 +6,9 @@ param ( [Parameter(mandatory = $true)] [string]$PackageNames, [Parameter(mandatory = $true)] - [string]$ServiceDirectory + [string]$ServiceDirectory, + [Parameter(mandatory = $false)] + [string]$TagSeparator = "_" ) . (Join-Path $PSScriptRoot common.ps1) @@ -20,23 +22,23 @@ $packageNamesArray = @() if ([String]::IsNullOrWhiteSpace($PackageNames)) { LogError "PackageNames cannot be empty." exit 1 -} else { +} +else { $packageNamesArray = $PackageNames.Split(',') } foreach ($packageName in $packageNamesArray) { Write-Host "Processing $packageName" $newVersion = [AzureEngSemanticVersion]::new("1.0.0") - $latestTags = git tag -l "${packageName}_*" + $prefix = "$packageName$TagSeparator" + Write-Host "Get Latest Tag : git tag -l $prefix*" + $latestTags = git tag -l "$prefix*" - Write-Host "Get Latest Tag : git tag -l ${packageName}_*" $semVars = @() - if ($latestTags -and ($latestTags.Length -gt 0)) - { - foreach ($tags in $latestTags) - { - $semVars += $tags.Replace("${packageName}_", "") + if ($latestTags -and ($latestTags.Length -gt 0)) { + foreach ($tag in $latestTags) { + $semVars += $tag.Substring($prefix.Length) } $semVarsSorted = [AzureEngSemanticVersion]::SortVersionStrings($semVars) diff --git a/eng/common/scripts/Verify-Links.ps1 b/eng/common/scripts/Verify-Links.ps1 index 31cc84846caf..003e83f0e4e5 100644 --- a/eng/common/scripts/Verify-Links.ps1 +++ b/eng/common/scripts/Verify-Links.ps1 @@ -89,8 +89,9 @@ function ProcessLink([System.Uri]$linkUri) { # and invalid links return a 302 redirecting the user to a Bing search return ProcessRedirectLink $linkUri -invalidStatusCodes 302 } - elseif ($linkUri -match '^https?://crates\.io/(?(crates|users|teams)/.+)') { - return ProcessCratesIoLink $linkUri $matches.path + elseif ($linkUri -match '^https?://crates\.io(/(?(crates|users|teams)/.+))?') { + # See comment in function below for details. + return ProcessCratesIoLink $linkUri $matches['path'] } else { return ProcessStandardLink $linkUri @@ -113,8 +114,14 @@ function ProcessRedirectLink([System.Uri]$linkUri, [int[]]$invalidStatusCodes) { } function ProcessCratesIoLink([System.Uri]$linkUri, $path) { - # Crates.io links are handled by a SPA. Even for missing pages, the response will be a 200, and the spa will only - # show a 404 page after it makes a request to the api. We can check the api to see if the page exists. + # crates.io is an SPA that will return a 404 if no 'accept: text/html' header is sent; however, even if you do + # send that header it will 200 on every request - even for missing pages. If a create/user/team path was sent, + # call into their API documented at https://doc.rust-lang.org/cargo/reference/registry-web-api.html; otherwise, + # assume the page exists since there's no other way to know. + if (!$path) { + return $true + } + $apiUri = "https://crates.io/api/v1/$path" # Invoke-WebRequest will throw an exception for invalid status codes. They are handled in CheckLink diff --git a/eng/common/scripts/copy-docs-to-blobstorage.ps1 b/eng/common/scripts/copy-docs-to-blobstorage.ps1 index c4f88ce756f2..bfcae988b875 100644 --- a/eng/common/scripts/copy-docs-to-blobstorage.ps1 +++ b/eng/common/scripts/copy-docs-to-blobstorage.ps1 @@ -116,7 +116,7 @@ function Get-Existing-Versions Param ( [Parameter(Mandatory=$true)] [String]$PkgName ) - $versionUri = "${BlobAccountName}/`$web/$($Language)/$($PkgName)/versioning/versions" + $versionUri = "https://azuresdkdocs.z19.web.core.windows.net/$Language/$PkgName/versioning/versions" LogDebug "Heading to $versionUri to retrieve known versions" try { diff --git a/eng/common/scripts/job-matrix/Create-PrJobMatrix.ps1 b/eng/common/scripts/job-matrix/Create-PrJobMatrix.ps1 index 8e18e2479ca4..d93872328dd5 100644 --- a/eng/common/scripts/job-matrix/Create-PrJobMatrix.ps1 +++ b/eng/common/scripts/job-matrix/Create-PrJobMatrix.ps1 @@ -44,6 +44,7 @@ param ( [Parameter(Mandatory = $False)][array] $Filters, [Parameter(Mandatory = $False)][array] $IndirectFilters, [Parameter(Mandatory = $False)][array] $Replace, + [Parameter(Mandatory = $False)][bool] $SparseIndirect = $true, [Parameter(Mandatory = $False)][int] $PackagesPerPRJob = 10, [Parameter()][switch] $CI = ($null -ne $env:SYSTEM_TEAMPROJECTID) ) @@ -72,7 +73,8 @@ function QueuePop([ref]$queue) { function GeneratePRMatrixForBatch { param ( - [Parameter(Mandatory = $true)][array] $Packages + [Parameter(Mandatory = $true)][array] $Packages, + [Parameter(Mandatory = $false)][bool] $FullSparseMatrix = $false ) $OverallResult = @() @@ -85,94 +87,92 @@ function GeneratePRMatrixForBatch { $directBatch = $Packages[0].IncludedForValidation -eq $false Write-Host "Generating matrix for $($directBatch ? 'direct' : 'indirect') packages" + $batchNamePrefix = $($directBatch ? 'b' : 'ib') + # The key here is that after we group the packages by the matrix config objects, we can use the first item's MatrixConfig # to generate the matrix for the group, no reason to have to parse the key value backwards to get the matrix config. $matrixBatchesByConfig = Group-ByObjectKey $Packages "CIMatrixConfigs" foreach ($matrixBatchKey in $matrixBatchesByConfig.Keys) { + # recall that while we have grouped the package info by the matrix config object, each package still has knowledge about + # every other matrix that it belongs to. + # so we actually need to get a valid matrix config object from the first package in the batch, but we need to be certain + # that the matrix config object we get is the SAME ONE that we are iterating through $matrixBatch = $matrixBatchesByConfig[$matrixBatchKey] - $matrixConfigs = $matrixBatch | Select-Object -First 1 -ExpandProperty CIMatrixConfigs - + $allPossibleMatrixConfigsForFirstPackage = $matrixBatch | Select-Object -First 1 -ExpandProperty CIMatrixConfigs + $matrixConfig = $allPossibleMatrixConfigsForFirstPackage | Where-Object { (Get-ObjectKey $_) -eq $matrixBatchKey } $matrixResults = @() - foreach ($matrixConfig in $matrixConfigs) { - Write-Host "Generating config for $($matrixConfig.Path)" - - $matrixResults = @() - if ($directBatch) { - $matrixResults = GenerateMatrixForConfig ` - -ConfigPath $matrixConfig.Path ` - -Selection $matrixConfig.Selection ` - -DisplayNameFilter $DisplayNameFilter ` - -Filters $Filters ` - -Replace $Replace - - if ($matrixResults) { - Write-Host "We have the following direct matrix results: " - Write-Host ($matrixResults | Out-String) - } + + if (!$matrixConfig) { + Write-Error "Unable to find matrix config for $matrixBatchKey. Check the package properties for the package $($matrixBatch[0].ArtifactName)." + exit 1 + } + + Write-Host "Generating config for $($matrixConfig.Path)" + $nonSparse = $matrixConfig.PSObject.Properties['NonSparseParameters'] ? $matrixConfig.NonSparseParameters : @() + + if ($directBatch) { + $matrixResults = GenerateMatrixForConfig ` + -ConfigPath $matrixConfig.Path ` + -Selection $matrixConfig.Selection ` + -DisplayNameFilter $DisplayNameFilter ` + -Filters $Filters ` + -Replace $Replace ` + -NonSparseParameters $nonSparse + + if ($matrixResults) { + Write-Host "We have the following direct matrix results: " + Write-Host ($matrixResults | Out-String) + } + } + else { + $matrixResults = GenerateMatrixForConfig ` + -ConfigPath $matrixConfig.Path ` + -Selection $matrixConfig.Selection ` + -DisplayNameFilter $DisplayNameFilter ` + -Filters ($Filters + $IndirectFilters) ` + -Replace $Replace ` + -NonSparseParameters $nonSparse + + if ($matrixResults) { + Write-Host "We have the following indirect matrix results: " + Write-Host ($matrixResults | Out-String) } else { - $matrixResults = GenerateMatrixForConfig ` - -ConfigPath $matrixConfig.Path ` - -Selection $matrixConfig.Selection ` - -DisplayNameFilter $DisplayNameFilter ` - -Filters ($Filters + $IndirectFilters) ` - -Replace $Replace - - if ($matrixResults) { - Write-Host "We have the following indirect matrix results: " - Write-Host ($matrixResults | Out-String) - } - else { - Write-Host "No indirect matrix results found for $($matrixConfig.Path)" - continue - } + Write-Host "No indirect matrix results found for $($matrixConfig.Path)" + continue } + } - $packageBatches = Split-ArrayIntoBatches -InputArray $matrixBatch -BatchSize $BATCHSIZE - - # we only need to modify the generated job name if there is more than one matrix config + batch - $matrixSuffixNecessary = $matrixBatchesByConfig.Keys.Count -gt 1 - - # if we are doing direct packages, we need to walk the batches and duplicate the matrix config for each batch, fully assigning - # the each batch's packages to the matrix config. This will generate a _non-sparse_ matrix for the incoming packages - if ($directBatch) { - $batchSuffixNecessary = $packageBatches.Length -gt 1 - $batchCounter = 1 - - foreach ($batch in $packageBatches) { - $namesForBatch = ($batch | ForEach-Object { $_.ArtifactName }) -join "," + if ($matrixConfig.PSObject.Properties['PRBatching']) { + # if we are doing a PR Batch, we need to just add the matrix items directly to the OverallResult + # as the users have explicitly disabled PR batching for this matrix. + if (!$matrixConfig.PRBatching) { + Write-Host "The matrix config $($matrixConfig.Path) with name $($matrixConfig.Name) has PRBatch set to false, the matrix members will be directly added without batching by $PRMatrixSetting." + $OverallResult += $matrixResults + continue + } + } - foreach ($matrixOutputItem in $matrixResults) { - # we need to clone this, as each item is an object with possible children - $outputItem = $matrixOutputItem | ConvertTo-Json -Depth 100 | ConvertFrom-Json -AsHashtable - # we just need to iterate across them, grab the parameters hashtable, and add the new key - # if there is more than one batch, we will need to add a suffix including the batch name to the job name - $outputItem["parameters"]["$PRMatrixSetting"] = $namesForBatch + $packageBatches = Split-ArrayIntoBatches -InputArray $matrixBatch -BatchSize $BATCHSIZE - if ($matrixSuffixNecessary) { - $outputItem["name"] = $outputItem["name"] + "_" + $matrixConfig.Name - } + # we only need to modify the generated job name if there is more than one matrix config + batch + $matrixSuffixNecessary = $matrixBatchesByConfig.Keys.Count -gt 1 - if ($batchSuffixNecessary) { - $outputItem["name"] = $outputItem["name"] + "_b$batchCounter" - } + # if we are doing direct packages (or a full indirect matrix), we need to walk the batches and duplicate the matrix config for each batch, fully assigning + # the each batch's packages to the matrix config. This will generate a _non-sparse_ matrix for the incoming packages + if ($directBatch -or $FullSparseMatrix) { + $batchSuffixNecessary = $packageBatches.Length -gt $($directBatch ? 1 : 0) + $batchCounter = 1 - $OverallResult += $outputItem - } - $batchCounter += 1 - } - } - # in the case of indirect packages, instead of walking the batches and duplicating their matrix config entirely, - # we instead will walk each each matrix, create a parameter named for the PRMatrixSetting, and add the targeted packages - # as an array. This will generate a _sparse_ matrix for for whatever the incoming packages are - else { - $batchSuffixNecessary = $packageBatches.Length -gt 0 - $batchCounter = 1 - foreach ($batch in $packageBatches) { - $namesForBatch = ($batch | ForEach-Object { $_.ArtifactName }) -join "," - $outputItem = QueuePop -queue ([ref]$matrixResults) + foreach ($batch in $packageBatches) { + $namesForBatch = ($batch | ForEach-Object { $_.ArtifactName }) -join "," + foreach ($matrixOutputItem in $matrixResults) { + # we need to clone this, as each item is an object with possible children + $outputItem = $matrixOutputItem | ConvertTo-Json -Depth 100 | ConvertFrom-Json -AsHashtable + # we just need to iterate across them, grab the parameters hashtable, and add the new key + # if there is more than one batch, we will need to add a suffix including the batch name to the job name $outputItem["parameters"]["$PRMatrixSetting"] = $namesForBatch if ($matrixSuffixNecessary) { @@ -180,17 +180,40 @@ function GeneratePRMatrixForBatch { } if ($batchSuffixNecessary) { - $outputItem["name"] = $outputItem["name"] + "_ib$batchCounter" + $outputItem["name"] = $outputItem["name"] + "$batchNamePrefix$batchCounter" } - # now we need to take an item from the front of the matrix results, clone it, and add it to the back of the matrix results - # we will add the cloned version to OverallResult + $OverallResult += $outputItem - $batchCounter += 1 } + $batchCounter += 1 } } - } + # in the case of indirect packages, instead of walking the batches and duplicating their matrix config entirely, + # we instead will walk each each matrix, create a parameter named for the PRMatrixSetting, and add the targeted packages + # as an array. This will generate a _sparse_ matrix for for whatever the incoming packages are + else { + $batchSuffixNecessary = $packageBatches.Length -gt 0 + $batchCounter = 1 + foreach ($batch in $packageBatches) { + $namesForBatch = ($batch | ForEach-Object { $_.ArtifactName }) -join "," + $outputItem = QueuePop -queue ([ref]$matrixResults) + + $outputItem["parameters"]["$PRMatrixSetting"] = $namesForBatch + + if ($matrixSuffixNecessary) { + $outputItem["name"] = $outputItem["name"] + "_" + $matrixConfig.Name + } + if ($batchSuffixNecessary) { + $outputItem["name"] = $outputItem["name"] + "_$batchNamePrefix$batchCounter" + } + # now we need to take an item from the front of the matrix results, clone it, and add it to the back of the matrix results + # we will add the cloned version to OverallResult + $OverallResult += $outputItem + $batchCounter += 1 + } + } + } return ,$OverallResult } @@ -212,6 +235,7 @@ $configs = Get-Content -Raw $PRMatrixFile | ConvertFrom-Json # get all the package property objects loaded $packageProperties = Get-ChildItem -Recurse "$PackagePropertiesFolder" *.json ` | ForEach-Object { Get-Content -Path $_.FullName | ConvertFrom-Json } +| ForEach-Object { Add-Member -InputObject $_ -MemberType NoteProperty -Name CIMatrixConfigs -Value $_.CIParameters.CIMatrixConfigs -PassThru } # enhance the package props with a default matrix config if one isn't present $packageProperties | ForEach-Object { @@ -236,7 +260,7 @@ if ($indirectPackages) { foreach($artifact in $indirectPackages) { Write-Host "-> $($artifact.ArtifactName)" } - $OverallResult += GeneratePRMatrixForBatch -Packages $indirectPackages + $OverallResult += GeneratePRMatrixForBatch -Packages $indirectPackages -FullSparseMatrix (-not $SparseIndirect) } $serialized = SerializePipelineMatrix $OverallResult diff --git a/eng/common/scripts/job-matrix/job-matrix-functions.ps1 b/eng/common/scripts/job-matrix/job-matrix-functions.ps1 index e327763bd724..75c9d4b8edb5 100644 --- a/eng/common/scripts/job-matrix/job-matrix-functions.ps1 +++ b/eng/common/scripts/job-matrix/job-matrix-functions.ps1 @@ -743,10 +743,11 @@ function Get4dMatrixIndex([int]$index, [Array]$dimensions) { function GenerateMatrixForConfig { param ( [Parameter(Mandatory = $true)][string] $ConfigPath, - [Parameter(Mandatory = $True)][string] $Selection, + [Parameter(Mandatory = $true)][string] $Selection, [Parameter(Mandatory = $false)][string] $DisplayNameFilter, [Parameter(Mandatory = $false)][array] $Filters, - [Parameter(Mandatory = $false)][array] $Replace + [Parameter(Mandatory = $false)][array] $Replace, + [Parameter(Mandatory = $false)][Array] $NonSparseParameters = @() ) $matrixFile = Join-Path $PSScriptRoot ".." ".." ".." ".." $ConfigPath @@ -761,7 +762,8 @@ function GenerateMatrixForConfig { -selectFromMatrixType $Selection ` -displayNameFilter $DisplayNameFilter ` -filters $Filters ` - -replace $Replace + -replace $Replace ` + -nonSparseParameters $NonSparseParameters return , $matrix } diff --git a/eng/common/scripts/job-matrix/pullrequest-faq.md b/eng/common/scripts/job-matrix/pullrequest-faq.md new file mode 100644 index 000000000000..de80ebe48405 --- /dev/null +++ b/eng/common/scripts/job-matrix/pullrequest-faq.md @@ -0,0 +1,89 @@ +# Pull Request FAQ + +The `pullrequest` pipeline is a single public definition that handles all `pull request` changes to an `azure-sdk-for-X` repository. This document is intended to answer some common questions that users may have about the `pullrequest` definition. + +## Can I get a bit more context first? + +Let's get some basic repo structure discussion out of the way. The `azure-sdk` team maintains a consistent repo structure for all shipping packages to package managers (Read NPM, Nuget, pypi, Maven, etc) + +```jsonc +sdk/ + storage + Azure.Storage.Blobs + Azure.Storage.Queues + ... + + + .. + + // the ci.yml is what AZDO build defs are based upon + ci.yml +``` + +This necessitates that release definitions on the [internal](https://dev.azure.com/azure-sdk/internal/) azure devops exist for each service in a repository. However, each build definition can only build and ship packages **within the service it was created for**. + +This service-directory also applied to `public` build definitions that triggered on [pull requests](https://github.com/Azure/azure-sdk-for-python/pulls) in our repos. Due to this, large changesets that touched multiple service directories would incur a build for _every service directory that was touched_. The `azure-sdk` EngSys calls this situation a `build storm`. + +The ` - pullrequest` definitions entirely replace service-specific build definitions. It has the ability to expand and contract the targeted packages for build according to a **git diff** of the actual changes made. Because of this, any repo that has cut over to `pullrequest` will enjoy no longer incurring build storms on large cross-cutting changes. While the individual build run will be very long running and batch up tests across a bunch of agents, it _will_ eventually complete. It will be _impossible_ to exhaust GitHub or Azure DevOps token utilization as well, given that it is a single definition triggering checks. + +The `pullrequest` pipeline is currently deployed in the following `azure-sdk` repositories: + +| Pipeline Def | Completed? | +|---|---| +| [Java](https://dev.azure.com/azure-sdk/public/_build?definitionId=7413) |❌| +| [JS](https://dev.azure.com/azure-sdk/public/_build?definitionId=7140) |✅| +| [.NET](https://dev.azure.com/azure-sdk/public/_build?definitionId=7327) |❌| +| [Python](https://dev.azure.com/azure-sdk/public/_build?definitionId=7050) |✅| +| [Rust](https://dev.azure.com/azure-sdk/public/_build?definitionId=7126) |✅| + +Only repos that appear in the above list are enabled with a single unified `pullrequest` pipeline. All other `azure-sdk` shipping repositories ship and PR using a build definition per service directory. + +## Pullrequest pipeline order of operations + +- Generate a PR diff +- Save Package Properties using the `diff` +- Run `build` and `analyze` steps only against artifacts that come out of the package-properties folder + - The primary change between service build and the pullrequest build is the scoping mechanism. For a service build, a specific service directory is examined for packages. For a pullrequest build, the entire repository is considered before being scoped down to only packages that were actually changed. +- Tests are run against `indirect`ly and `direct`ly changed packages separately in batches. + +## What is a `direct` vs `indirect` change? + +- A `direct`ly changed package is one whose actual package code has changed. +- An `indirect` changed package is a package that has been added for verification of code that is not directly within the package itself. + - For example, in `java`, when the `eng/` package is changed, we trigger `azure-core` indirectly. + +## Why do I see jobs with `bX` or `ibY` suffixes? + +As mentioned above, direct and indirect packages are batched separately. Batching is best explained by the following pseudocode + +``` +batchSize = configurable # of packages in each test batch, defaults to 10 +directPackages = the list of packages with directly changed code in the PR + +group the direct packages by matrix configuration + - each matrix contribution + - group by batch size + - assign the matrix to the full batch + - if multiple batches exist, add suffix +``` + +Notice that packages are grouped initially by _the matrix associated with their ci.yml_. In the `pullrequest` pipeline, the service directory of a package no longer matters, only what matrix it belongs to. + +`indirect` batching works the same way, but doesn't use the _full_ test matrix by default. It instead deterministically selects a single item from the resolved test matrix and assigns the batch of packages to it. + +The suffixes `b1` or `ib1` or are added automatically as needed by the job pull request [matrix creation.](https://github.com/Azure/azure-sdk-tools/blob/main/eng/common/scripts/job-matrix/Create-PrJobMatrix.ps1). + +## Can I disable this matrix batching? + +Yes! Users can entirely disable the batching for a specific matrix by setting `PRBatching` to false in the matrix configuration. + +Example: + +```yml +MatrixConfigs: + - Name: version_overrides_tests + Path: sdk/core/version-overrides-matrix.json + Selection: all + PRBatching: false # the new key + GenerateVMJobs: true +``` diff --git a/eng/common/scripts/stress-testing/deploy-stress-tests.ps1 b/eng/common/scripts/stress-testing/deploy-stress-tests.ps1 old mode 100644 new mode 100755 index 61d8f947d800..cf763b5bb1cd --- a/eng/common/scripts/stress-testing/deploy-stress-tests.ps1 +++ b/eng/common/scripts/stress-testing/deploy-stress-tests.ps1 @@ -1,3 +1,5 @@ +#! /bin/env pwsh + # Not defining a default parameter set makes SkipLogin/Subscription required all the time. [CmdletBinding(DefaultParameterSetName = 'Default')] param( @@ -10,6 +12,7 @@ param( [string]$DeployId, [switch]$SkipLogin, [string]$Subscription, + [string]$Tenant, # Default to true in Azure Pipelines environments [switch] $CI = ($null -ne $env:SYSTEM_TEAMPROJECTID), diff --git a/eng/common/scripts/stress-testing/stress-test-deployment-lib.ps1 b/eng/common/scripts/stress-testing/stress-test-deployment-lib.ps1 index 56876ba0e1be..3de02c1d7ac5 100644 --- a/eng/common/scripts/stress-testing/stress-test-deployment-lib.ps1 +++ b/eng/common/scripts/stress-testing/stress-test-deployment-lib.ps1 @@ -43,12 +43,12 @@ function RunOrExitOnFailure() } } -function Login([string]$subscription, [string]$clusterGroup, [switch]$skipPushImages) +function Login([string]$subscription, [string]$tenant, [string]$clusterGroup, [switch]$skipPushImages) { Write-Host "Logging in to subscription, cluster and container registry" az account show -s "$subscription" *> $null if ($LASTEXITCODE) { - RunOrExitOnFailure az login --allow-no-subscriptions + RunOrExitOnFailure az login --allow-no-subscriptions --tenant $tenant } # Discover cluster name, only one cluster per group is expected @@ -115,25 +115,28 @@ function DeployStressTests( Write-Warning "Overriding cluster group and subscription with defaults for 'pg' environment." } $clusterGroup = 'rg-stress-cluster-pg' - $subscription = 'Azure SDK Developer Playground' + $subscription = 'Azure SDK Test Resources - TME' + $tenant = '70a036f6-8e4d-4615-bad6-149c02e7720d' } elseif ($environment -eq 'prod') { if ($clusterGroup -or $subscription) { Write-Warning "Overriding cluster group and subscription with defaults for 'prod' environment." } $clusterGroup = 'rg-stress-cluster-prod' $subscription = 'Azure SDK Test Resources - TME' + $tenant = '70a036f6-8e4d-4615-bad6-149c02e7720d' } elseif ($environment -eq 'storage') { if ($clusterGroup -or $subscription) { Write-Warning "Overriding cluster group and subscription with defaults for 'storage' environment." } $clusterGroup = 'rg-stress-cluster-storage' - $subscription = 'XClient' - } elseif (!$clusterGroup -or !$subscription) { - throw "clusterGroup and subscription parameters must be specified when deploying to an environment that is not pg or prod." + $subscription = 'Azure SDK Test Resources - TME' + $tenant = '72f988bf-86f1-41af-91ab-2d7cd011db47' + } elseif (!$clusterGroup -or !$subscription -or $tenant) { + throw "-ClusterGroup, -Subscription and -Tenant parameters must be specified when deploying to an environment that is not pg or prod." } if (!$skipLogin) { - Login -subscription $subscription -clusterGroup $clusterGroup -skipPushImages:$skipPushImages + Login -subscription $subscription -tenant $tenant -clusterGroup $clusterGroup -skipPushImages:$skipPushImages } $chartRepoName = 'stress-test-charts' @@ -144,7 +147,7 @@ function DeployStressTests( } RunOrExitOnFailure helm repo add --force-update $chartRepoName file://$absAddonsPath } else { - RunOrExitOnFailure helm repo add --force-update $chartRepoName https://stresstestcharts.blob.core.windows.net/helm/ + RunOrExitOnFailure helm repo add --force-update $chartRepoName https://azuresdkartifacts.z5.web.core.windows.net/stress/ } Run helm repo update diff --git a/eng/common/testproxy/target_version.txt b/eng/common/testproxy/target_version.txt index 7c3d75f3a484..ac6bc7f9f590 100644 --- a/eng/common/testproxy/target_version.txt +++ b/eng/common/testproxy/target_version.txt @@ -1 +1 @@ -1.0.0-dev.20241213.1 +1.0.0-dev.20250221.1 diff --git a/eng/emitter-package-lock.json b/eng/emitter-package-lock.json index 3574218d813a..73b02b41ded8 100644 --- a/eng/emitter-package-lock.json +++ b/eng/emitter-package-lock.json @@ -1,31 +1,33 @@ { - "name": "TempTypeSpecFiles", + "name": "dist/src/index.js", "lockfileVersion": 3, "requires": true, "packages": { "": { + "name": "dist/src/index.js", "dependencies": { - "@azure-tools/typespec-java": "0.27.2" + "@azure-tools/typespec-java": "0.27.9" }, "devDependencies": { - "@azure-tools/typespec-autorest": "0.50.0", - "@azure-tools/typespec-azure-core": "0.50.0", - "@azure-tools/typespec-azure-resource-manager": "0.50.0", - "@azure-tools/typespec-azure-rulesets": "0.50.0", - "@azure-tools/typespec-client-generator-core": "0.50.0", - "@azure-tools/typespec-liftr-base": "0.6.0", - "@typespec/compiler": "0.64.0", - "@typespec/http": "0.64.0", - "@typespec/openapi": "0.64.0", - "@typespec/rest": "0.64.0", - "@typespec/versioning": "0.64.0", - "@typespec/xml": "0.64.0" + "@azure-tools/typespec-autorest": "0.52.0", + "@azure-tools/typespec-azure-core": "0.52.0", + "@azure-tools/typespec-azure-resource-manager": "0.52.0", + "@azure-tools/typespec-azure-rulesets": "0.52.0", + "@azure-tools/typespec-client-generator-core": "0.52.0", + "@azure-tools/typespec-liftr-base": "0.8.0", + "@typespec/compiler": "0.66.0", + "@typespec/http": "0.66.0", + "@typespec/openapi": "0.66.0", + "@typespec/rest": "0.66.0", + "@typespec/versioning": "0.66.0", + "@typespec/xml": "0.66.0" } }, "node_modules/@autorest/codemodel": { "version": "4.20.0", "resolved": "https://registry.npmjs.org/@autorest/codemodel/-/codemodel-4.20.0.tgz", "integrity": "sha512-Z2GwVwAGNTcfGUmrWT5LJqZv/WDXKBBpxhZrHu6zco/HrEGrqKQcKx5whlLX/GmAB/KmhcOWYr6aIyWomcoisQ==", + "license": "MIT", "dependencies": { "@azure-tools/codegen": "~2.10.0", "js-yaml": "~4.1.0" @@ -38,6 +40,7 @@ "version": "3.0.254", "resolved": "https://registry.npmjs.org/@azure-tools/async-io/-/async-io-3.0.254.tgz", "integrity": "sha512-X1C7XdyCuo50ch9FzKtTvmK18FgDxxf1Bbt3cSoknQqeDaRegHSSCO+zByq2YA4NvUzKXeZ1engh29IDxZXgpQ==", + "license": "MIT", "dependencies": { "@azure-tools/tasks": "~3.0.255", "proper-lockfile": "~2.0.1" @@ -50,6 +53,7 @@ "version": "2.10.0", "resolved": "https://registry.npmjs.org/@azure-tools/codegen/-/codegen-2.10.0.tgz", "integrity": "sha512-gdy0at3BUZAAARgiX9Ye6SNCKhcjLs5FNUewa/KV/dMGcPv7mBvbslt5VO3W8wj0n96ifk970aIFaivjacBxeQ==", + "license": "MIT", "dependencies": { "@azure-tools/async-io": "~3.0.0", "js-yaml": "~4.1.0", @@ -63,45 +67,49 @@ "version": "3.0.255", "resolved": "https://registry.npmjs.org/@azure-tools/tasks/-/tasks-3.0.255.tgz", "integrity": "sha512-GjALNLz7kWMEdRVbaN5g0cJHNAr3XVTbP0611Mv2UzMgGL6FOhNZJK+oPHJKLDR8EEDZNnkwPlyi7B+INXUSQA==", + "license": "MIT", "engines": { "node": ">=10.12.0" } }, "node_modules/@azure-tools/typespec-autorest": { - "version": "0.50.0", - "resolved": "https://registry.npmjs.org/@azure-tools/typespec-autorest/-/typespec-autorest-0.50.0.tgz", - "integrity": "sha512-CYzqN11NGU2HNJcycph7HCpjQoOR+XzyySDi6Z6rsXhZa/XTPDYJtmGHNVHXYGgvxJPxPJ9jm13DiLf/ReJnSA==", + "version": "0.52.0", + "resolved": "https://registry.npmjs.org/@azure-tools/typespec-autorest/-/typespec-autorest-0.52.0.tgz", + "integrity": "sha512-r08neSPfski9Q3Jvp6tardmS4KXHOML0wSdz5DZgVg0UN+yaVFgLIvMy7VwS636bjpNhwZj8gMT4jYyVM44hlw==", + "license": "MIT", "engines": { "node": ">=18.0.0" }, "peerDependencies": { - "@azure-tools/typespec-azure-core": "~0.50.0", - "@azure-tools/typespec-azure-resource-manager": "~0.50.0", - "@azure-tools/typespec-client-generator-core": "~0.50.0", - "@typespec/compiler": "~0.64.0", - "@typespec/http": "~0.64.0", - "@typespec/openapi": "~0.64.0", - "@typespec/rest": "~0.64.0", - "@typespec/versioning": "~0.64.0" + "@azure-tools/typespec-azure-core": "~0.52.0", + "@azure-tools/typespec-azure-resource-manager": "~0.52.0", + "@azure-tools/typespec-client-generator-core": "~0.52.0", + "@typespec/compiler": "~0.66.0", + "@typespec/http": "~0.66.0", + "@typespec/openapi": "~0.66.0", + "@typespec/rest": "~0.66.0", + "@typespec/versioning": "~0.66.0" } }, "node_modules/@azure-tools/typespec-azure-core": { - "version": "0.50.0", - "resolved": "https://registry.npmjs.org/@azure-tools/typespec-azure-core/-/typespec-azure-core-0.50.0.tgz", - "integrity": "sha512-6kUhWNQc4Btgx7rIbx3dubBLst73qv04dGWg0yNoVi86iIXy+8wr4ee6pgk+niMsZDeHEBEWeeLy9VwCg3MgTg==", + "version": "0.52.0", + "resolved": "https://registry.npmjs.org/@azure-tools/typespec-azure-core/-/typespec-azure-core-0.52.0.tgz", + "integrity": "sha512-pZkzjQCIgnUdVY0e4YNAAD3vN3HaZim1MMZJRiQaD5vK7WuQQLKYfOf/y8W5zim0GLpvKLNg8mMMmPrRZlW0BQ==", + "license": "MIT", "engines": { "node": ">=18.0.0" }, "peerDependencies": { - "@typespec/compiler": "~0.64.0", - "@typespec/http": "~0.64.0", - "@typespec/rest": "~0.64.0" + "@typespec/compiler": "~0.66.0", + "@typespec/http": "~0.66.0", + "@typespec/rest": "~0.66.0" } }, "node_modules/@azure-tools/typespec-azure-resource-manager": { - "version": "0.50.0", - "resolved": "https://registry.npmjs.org/@azure-tools/typespec-azure-resource-manager/-/typespec-azure-resource-manager-0.50.0.tgz", - "integrity": "sha512-ekLAyPyy9eMMqdi3pj3g+iw9NNiK6ObDIU/W/bwSBSPwN2Po9d46fb65vcsjPeEkBceeRIPP6p54QtG9JYhSfg==", + "version": "0.52.0", + "resolved": "https://registry.npmjs.org/@azure-tools/typespec-azure-resource-manager/-/typespec-azure-resource-manager-0.52.0.tgz", + "integrity": "sha512-A5nCTEWdAo1tpG5nwWHDMDqEAopp3K3CgbnOB0wwiAV8+zkr5qNC0/48WQvu7pmwlgMDgdvZpNty3bWdLRztQQ==", + "license": "MIT", "dependencies": { "change-case": "~5.4.4", "pluralize": "^8.0.0" @@ -110,87 +118,93 @@ "node": ">=18.0.0" }, "peerDependencies": { - "@azure-tools/typespec-azure-core": "~0.50.0", - "@typespec/compiler": "~0.64.0", - "@typespec/http": "~0.64.0", - "@typespec/openapi": "~0.64.0", - "@typespec/rest": "~0.64.0", - "@typespec/versioning": "~0.64.0" + "@azure-tools/typespec-azure-core": "~0.52.0", + "@typespec/compiler": "~0.66.0", + "@typespec/http": "~0.66.0", + "@typespec/openapi": "~0.66.0", + "@typespec/rest": "~0.66.0", + "@typespec/versioning": "~0.66.0" } }, "node_modules/@azure-tools/typespec-azure-rulesets": { - "version": "0.50.0", - "resolved": "https://registry.npmjs.org/@azure-tools/typespec-azure-rulesets/-/typespec-azure-rulesets-0.50.0.tgz", - "integrity": "sha512-b2YjhaUqPxk53eswZKPzK1IzTJJe/AD+Yi/G15+fiar7oozQJtZpe7ysrSsknzKEoy92iiknsIVa5giRie0ATg==", + "version": "0.52.0", + "resolved": "https://registry.npmjs.org/@azure-tools/typespec-azure-rulesets/-/typespec-azure-rulesets-0.52.0.tgz", + "integrity": "sha512-fvp2YffW55wSjDMaBA9H/kfxHN6pvPM3JWgUcD4QuC7lnTrBymJHpWIW19X8BbiVPwz9dKEcyY6iHyU/iOyehw==", + "license": "MIT", "engines": { "node": ">=18.0.0" }, "peerDependencies": { - "@azure-tools/typespec-azure-core": "~0.50.0", - "@azure-tools/typespec-azure-resource-manager": "~0.50.0", - "@azure-tools/typespec-client-generator-core": "~0.50.0", - "@typespec/compiler": "~0.64.0" + "@azure-tools/typespec-azure-core": "~0.52.0", + "@azure-tools/typespec-azure-resource-manager": "~0.52.0", + "@azure-tools/typespec-client-generator-core": "~0.52.0", + "@typespec/compiler": "~0.66.0" } }, "node_modules/@azure-tools/typespec-client-generator-core": { - "version": "0.50.0", - "resolved": "https://registry.npmjs.org/@azure-tools/typespec-client-generator-core/-/typespec-client-generator-core-0.50.0.tgz", - "integrity": "sha512-Zk62SZb6W5neTtajcQAKll4zYSf3aKaMEDLymMTajXTsWxAlrb7sqnc8vTZWSIymaRI0A9olEL2luw9OLywUYA==", + "version": "0.52.0", + "resolved": "https://registry.npmjs.org/@azure-tools/typespec-client-generator-core/-/typespec-client-generator-core-0.52.0.tgz", + "integrity": "sha512-P1kh4mkqPmZY0JsJAtnTRDjzynI05TybgRTsaEnQtFwnlbfUzu1KtKDF4midQDMT6Ao8JEt/S2Nd4nQ1/qrHyQ==", + "license": "MIT", "dependencies": { "change-case": "~5.4.4", "pluralize": "^8.0.0", - "yaml": "~2.5.1" + "yaml": "~2.7.0" }, "engines": { "node": ">=18.0.0" }, "peerDependencies": { - "@azure-tools/typespec-azure-core": "~0.50.0", - "@typespec/compiler": "~0.64.0", - "@typespec/http": "~0.64.0", - "@typespec/openapi": "~0.64.0", - "@typespec/rest": "~0.64.0", - "@typespec/versioning": "~0.64.0" + "@azure-tools/typespec-azure-core": "~0.52.0", + "@typespec/compiler": "~0.66.0", + "@typespec/http": "~0.66.0", + "@typespec/openapi": "~0.66.0", + "@typespec/rest": "~0.66.0", + "@typespec/versioning": "~0.66.0", + "@typespec/xml": "~0.66.0" } }, "node_modules/@azure-tools/typespec-java": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/@azure-tools/typespec-java/-/typespec-java-0.27.2.tgz", - "integrity": "sha512-CptKcnrSfN9ywJWJtKKMT9gG0iOYRKqunu/44FgFOS7e+7fFuNNZ46SaPeyQmUZe0I4/l+ECZDkZSHFr+ECEBg==", + "version": "0.27.9", + "resolved": "https://registry.npmjs.org/@azure-tools/typespec-java/-/typespec-java-0.27.9.tgz", + "integrity": "sha512-ZNEy3M0iF+w75dbJrBnqXA/hexTe9yZxBKN1iVcAKFztmMsZn6iLO2QpYreve4unhZJa7USabtvkAViY0LHjrg==", + "license": "MIT", "dependencies": { "@autorest/codemodel": "~4.20.0", "js-yaml": "~4.1.0", "lodash": "~4.17.21" }, "engines": { - "node": ">=14.0.0" + "node": ">=20.0.0" }, "peerDependencies": { - "@azure-tools/typespec-autorest": ">=0.50.0 <1.0.0", - "@azure-tools/typespec-azure-core": ">=0.50.0 <1.0.0", - "@azure-tools/typespec-azure-resource-manager": ">=0.50.0 <1.0.0", - "@azure-tools/typespec-azure-rulesets": ">=0.50.0 <1.0.0", - "@azure-tools/typespec-client-generator-core": ">=0.50.0 <1.0.0", - "@typespec/compiler": ">=0.64.0 <1.0.0", - "@typespec/http": ">=0.64.0 <1.0.0", - "@typespec/openapi": ">=0.64.0 <1.0.0", - "@typespec/rest": ">=0.64.0 <1.0.0", - "@typespec/versioning": ">=0.64.0 <1.0.0", - "@typespec/xml": ">=0.64.0 <1.0.0" + "@azure-tools/typespec-autorest": ">=0.52.0 <1.0.0", + "@azure-tools/typespec-azure-core": ">=0.52.0 <1.0.0", + "@azure-tools/typespec-azure-resource-manager": ">=0.52.0 <1.0.0", + "@azure-tools/typespec-azure-rulesets": ">=0.52.0 <1.0.0", + "@azure-tools/typespec-client-generator-core": ">=0.52.0 <1.0.0", + "@azure-tools/typespec-liftr-base": ">=0.8.0 <1.0.0", + "@typespec/compiler": ">=0.66.0 <1.0.0", + "@typespec/http": ">=0.66.0 <1.0.0", + "@typespec/openapi": ">=0.66.0 <1.0.0", + "@typespec/rest": ">=0.66.0 <1.0.0", + "@typespec/versioning": ">=0.66.0 <1.0.0", + "@typespec/xml": ">=0.66.0 <1.0.0" } }, "node_modules/@azure-tools/typespec-liftr-base": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/@azure-tools/typespec-liftr-base/-/typespec-liftr-base-0.6.0.tgz", - "integrity": "sha512-MQV7ESlCqWrgclTSgs/dllS/jKrMrjs9C0UNExXsYhpjUtpv/BnmToWaWL4hA/5rg5JgxDp1MSAjZ5PBjGo1ig==", - "dev": true + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/@azure-tools/typespec-liftr-base/-/typespec-liftr-base-0.8.0.tgz", + "integrity": "sha512-xftTTtVjDuxIzugQ9nL/abmttdDM3HAf5HhqKzs9DO0Kl0ZhXQlB2DYlT1hBs/N+IWerMF9k2eKs2RncngA03g==" }, "node_modules/@babel/code-frame": { - "version": "7.25.9", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.25.9.tgz", - "integrity": "sha512-z88xeGxnzehn2sqZ8UdGQEvYErF1odv2CftxInpSYJt6uHuPe9YjahKZITGs3l5LeI9d2ROG+obuDAoSlqbNfQ==", + "version": "7.26.2", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.26.2.tgz", + "integrity": "sha512-RJlIHRueQgwWitWgF8OdFYGZX328Ax5BCemNGlqHfplnRT9ESi8JkFlvaVYbS+UubVY6dpv87Fs2u5M29iNFVQ==", + "license": "MIT", "dependencies": { - "@babel/highlight": "^7.25.9", + "@babel/helper-validator-identifier": "^7.25.9", + "js-tokens": "^4.0.0", "picocolors": "^1.0.0" }, "engines": { @@ -201,358 +215,2232 @@ "version": "7.25.9", "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.25.9.tgz", "integrity": "sha512-Ed61U6XJc3CVRfkERJWDz4dJwKe7iLmmJsbOGu9wSloNSFttHV0I8g6UAgb7qnK5ly5bGLPd4oXZlxCdANBOWQ==", + "license": "MIT", "engines": { "node": ">=6.9.0" } }, - "node_modules/@babel/highlight": { - "version": "7.25.9", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.25.9.tgz", - "integrity": "sha512-llL88JShoCsth8fF8R4SJnIn+WLvR6ccFxu1H3FlMhDontdcmZWf2HgIZ7AIqV3Xcck1idlohrN4EUBQz6klbw==", + "node_modules/@inquirer/checkbox": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/@inquirer/checkbox/-/checkbox-4.1.3.tgz", + "integrity": "sha512-KU1MGwf24iABJjGESxhyj+/rlQYSRoCfcuHDEHXfZ1DENmbuSRfyrUb+LLjHoee5TNOFKwaFxDXc5/zRwJUPMQ==", + "license": "MIT", "dependencies": { - "@babel/helper-validator-identifier": "^7.25.9", - "chalk": "^2.4.2", - "js-tokens": "^4.0.0", - "picocolors": "^1.0.0" + "@inquirer/core": "^10.1.8", + "@inquirer/figures": "^1.0.11", + "@inquirer/type": "^3.0.5", + "ansi-escapes": "^4.3.2", + "yoctocolors-cjs": "^2.1.2" }, "engines": { - "node": ">=6.9.0" + "node": ">=18" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } } }, - "node_modules/@nodelib/fs.scandir": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", - "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "node_modules/@inquirer/confirm": { + "version": "5.1.7", + "resolved": "https://registry.npmjs.org/@inquirer/confirm/-/confirm-5.1.7.tgz", + "integrity": "sha512-Xrfbrw9eSiHb+GsesO8TQIeHSMTP0xyvTCeeYevgZ4sKW+iz9w/47bgfG9b0niQm+xaLY2EWPBINUPldLwvYiw==", + "license": "MIT", "dependencies": { - "@nodelib/fs.stat": "2.0.5", - "run-parallel": "^1.1.9" + "@inquirer/core": "^10.1.8", + "@inquirer/type": "^3.0.5" }, "engines": { - "node": ">= 8" + "node": ">=18" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } } }, - "node_modules/@nodelib/fs.stat": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", - "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "node_modules/@inquirer/core": { + "version": "10.1.8", + "resolved": "https://registry.npmjs.org/@inquirer/core/-/core-10.1.8.tgz", + "integrity": "sha512-HpAqR8y715zPpM9e/9Q+N88bnGwqqL8ePgZ0SMv/s3673JLMv3bIkoivGmjPqXlEgisUksSXibweQccUwEx4qQ==", + "license": "MIT", + "dependencies": { + "@inquirer/figures": "^1.0.11", + "@inquirer/type": "^3.0.5", + "ansi-escapes": "^4.3.2", + "cli-width": "^4.1.0", + "mute-stream": "^2.0.0", + "signal-exit": "^4.1.0", + "wrap-ansi": "^6.2.0", + "yoctocolors-cjs": "^2.1.2" + }, "engines": { - "node": ">= 8" + "node": ">=18" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } } }, - "node_modules/@nodelib/fs.walk": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", - "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "node_modules/@inquirer/editor": { + "version": "4.2.8", + "resolved": "https://registry.npmjs.org/@inquirer/editor/-/editor-4.2.8.tgz", + "integrity": "sha512-UkGKbMFlQw5k4ZLjDwEi5z8NIVlP/3DAlLHta0o0pSsdpPThNmPtUL8mvGCHUaQtR+QrxR9yRYNWgKMsHkfIUA==", + "license": "MIT", "dependencies": { - "@nodelib/fs.scandir": "2.1.5", - "fastq": "^1.6.0" + "@inquirer/core": "^10.1.8", + "@inquirer/type": "^3.0.5", + "external-editor": "^3.1.0" }, "engines": { - "node": ">= 8" + "node": ">=18" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } } }, - "node_modules/@sindresorhus/merge-streams": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/@sindresorhus/merge-streams/-/merge-streams-2.3.0.tgz", - "integrity": "sha512-LtoMMhxAlorcGhmFYI+LhPgbPZCkgP6ra1YL604EeF6U98pLlQ3iWIGMdWSC+vWmPBWBNgmDBAhnAobLROJmwg==", + "node_modules/@inquirer/expand": { + "version": "4.0.10", + "resolved": "https://registry.npmjs.org/@inquirer/expand/-/expand-4.0.10.tgz", + "integrity": "sha512-leyBouGJ77ggv51Jb/OJmLGGnU2HYc13MZ2iiPNLwe2VgFgZPVqsrRWSa1RAHKyazjOyvSNKLD1B2K7A/iWi1g==", + "license": "MIT", + "dependencies": { + "@inquirer/core": "^10.1.8", + "@inquirer/type": "^3.0.5", + "yoctocolors-cjs": "^2.1.2" + }, "engines": { "node": ">=18" }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } } }, - "node_modules/@typespec/compiler": { - "version": "0.64.0", - "resolved": "https://registry.npmjs.org/@typespec/compiler/-/compiler-0.64.0.tgz", - "integrity": "sha512-LnQGlQMWyqvhGg4Z9iyr5qSBTjI9zd49sodbEJbLafrxbj9pbHyjfSFbvt60gVbfuNvLErsdXvZiqqXV5nZdmQ==", + "node_modules/@inquirer/figures": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@inquirer/figures/-/figures-1.0.11.tgz", + "integrity": "sha512-eOg92lvrn/aRUqbxRyvpEWnrvRuTYRifixHkYVpJiygTgVSBIHDqLh0SrMQXkafvULg3ck11V7xvR+zcgvpHFw==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@inquirer/input": { + "version": "4.1.7", + "resolved": "https://registry.npmjs.org/@inquirer/input/-/input-4.1.7.tgz", + "integrity": "sha512-rCQAipJNA14UTH84df/z4jDJ9LZ54H6zzuCAi7WZ0qVqx3CSqLjfXAMd5cpISIxbiHVJCPRB81gZksq6CZsqDg==", + "license": "MIT", "dependencies": { - "@babel/code-frame": "~7.25.7", - "ajv": "~8.17.1", - "change-case": "~5.4.4", - "globby": "~14.0.2", - "mustache": "~4.2.0", - "picocolors": "~1.1.1", - "prettier": "~3.3.3", - "prompts": "~2.4.2", - "semver": "^7.6.3", - "temporal-polyfill": "^0.2.5", - "vscode-languageserver": "~9.0.1", - "vscode-languageserver-textdocument": "~1.0.12", - "yaml": "~2.5.1", - "yargs": "~17.7.2" - }, - "bin": { - "tsp": "cmd/tsp.js", - "tsp-server": "cmd/tsp-server.js" + "@inquirer/core": "^10.1.8", + "@inquirer/type": "^3.0.5" }, "engines": { - "node": ">=18.0.0" + "node": ">=18" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } } }, - "node_modules/@typespec/http": { - "version": "0.64.0", - "resolved": "https://registry.npmjs.org/@typespec/http/-/http-0.64.0.tgz", - "integrity": "sha512-vyyZP3Woo7or/2Oiq1fH+R0X/4WOBDjAlGsb9tLQzswfQHp710kNfiecA10y9gDC/9h+PjKsTElS1RcRRanpwA==", + "node_modules/@inquirer/number": { + "version": "3.0.10", + "resolved": "https://registry.npmjs.org/@inquirer/number/-/number-3.0.10.tgz", + "integrity": "sha512-GLsdnxzNefjCJUmWyjaAuNklHgDpCTL4RMllAVhVvAzBwRW9g38eZ5tWgzo1lirtSDTpsh593hqXVhxvdrjfwA==", + "license": "MIT", + "dependencies": { + "@inquirer/core": "^10.1.8", + "@inquirer/type": "^3.0.5" + }, "engines": { - "node": ">=18.0.0" + "node": ">=18" }, "peerDependencies": { - "@typespec/compiler": "~0.64.0", - "@typespec/streams": "~0.64.0" + "@types/node": ">=18" }, "peerDependenciesMeta": { - "@typespec/streams": { + "@types/node": { "optional": true } } }, - "node_modules/@typespec/openapi": { - "version": "0.64.0", - "resolved": "https://registry.npmjs.org/@typespec/openapi/-/openapi-0.64.0.tgz", - "integrity": "sha512-C4sPdj86ejsNkpmEaAMMqQR+0kq4Ayp4sPKvj4OTtawLXacXKzZ9NYng2jrguO6WbLr5f3NyRZKi7Ys2suT27A==", + "node_modules/@inquirer/password": { + "version": "4.0.10", + "resolved": "https://registry.npmjs.org/@inquirer/password/-/password-4.0.10.tgz", + "integrity": "sha512-JC538ujqeYKkFqLoWZ0ILBteIUO2yajBMVEUZSxjl9x6fiEQtM+I5Rca7M2D8edMDbyHLnXifGH1hJZdh8V5rA==", + "license": "MIT", + "dependencies": { + "@inquirer/core": "^10.1.8", + "@inquirer/type": "^3.0.5", + "ansi-escapes": "^4.3.2" + }, "engines": { - "node": ">=18.0.0" + "node": ">=18" }, "peerDependencies": { - "@typespec/compiler": "~0.64.0", - "@typespec/http": "~0.64.0" + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } } }, - "node_modules/@typespec/rest": { - "version": "0.64.0", - "resolved": "https://registry.npmjs.org/@typespec/rest/-/rest-0.64.0.tgz", - "integrity": "sha512-7+oUajQzOkZPTMtRiGp6hzTTmy7mRaxOYqxIPgDhYyr9I6oQPLAcBsYhFNk/ulcqld/ApaV5ycXaOlK41REOyQ==", + "node_modules/@inquirer/prompts": { + "version": "7.3.3", + "resolved": "https://registry.npmjs.org/@inquirer/prompts/-/prompts-7.3.3.tgz", + "integrity": "sha512-QS1AQgJ113iE/nmym03yKZKHvGjVWwkGZT3B1yKrrMG0bJKQg1jUkntFP8aPd2FUQzu/nga7QU2eDpzIP5it0Q==", + "license": "MIT", + "dependencies": { + "@inquirer/checkbox": "^4.1.3", + "@inquirer/confirm": "^5.1.7", + "@inquirer/editor": "^4.2.8", + "@inquirer/expand": "^4.0.10", + "@inquirer/input": "^4.1.7", + "@inquirer/number": "^3.0.10", + "@inquirer/password": "^4.0.10", + "@inquirer/rawlist": "^4.0.10", + "@inquirer/search": "^3.0.10", + "@inquirer/select": "^4.0.10" + }, "engines": { - "node": ">=18.0.0" + "node": ">=18" }, "peerDependencies": { - "@typespec/compiler": "~0.64.0", - "@typespec/http": "~0.64.0" + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } } }, - "node_modules/@typespec/versioning": { - "version": "0.64.0", - "resolved": "https://registry.npmjs.org/@typespec/versioning/-/versioning-0.64.0.tgz", - "integrity": "sha512-GtmuE7UwVYuVwgSpbSWzZB5UO6O/f/o1NqjLStctF8zkv2/5s+RbeqRyamjDuUyhMrIwqw+TMXtAnMXpSHlB8A==", + "node_modules/@inquirer/rawlist": { + "version": "4.0.10", + "resolved": "https://registry.npmjs.org/@inquirer/rawlist/-/rawlist-4.0.10.tgz", + "integrity": "sha512-vOQbQkmhaCsF2bUmjoyRSZJBz77UnIF/F3ZS2LMgwbgyaG2WgwKHh0WKNj0APDB72WDbZijhW5nObQbk+TnbcA==", + "license": "MIT", + "dependencies": { + "@inquirer/core": "^10.1.8", + "@inquirer/type": "^3.0.5", + "yoctocolors-cjs": "^2.1.2" + }, "engines": { - "node": ">=18.0.0" + "node": ">=18" }, "peerDependencies": { - "@typespec/compiler": "~0.64.0" + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } } }, - "node_modules/@typespec/xml": { - "version": "0.64.0", - "resolved": "https://registry.npmjs.org/@typespec/xml/-/xml-0.64.0.tgz", - "integrity": "sha512-Sk+5S2C4YK+fqSadAlzRBSZbhvtDtxLQUS+vrYgiqzVS1F61nUmP7gQGUj+Kps7ncZSppPZystWJJnF7K34UJg==", + "node_modules/@inquirer/search": { + "version": "3.0.10", + "resolved": "https://registry.npmjs.org/@inquirer/search/-/search-3.0.10.tgz", + "integrity": "sha512-EAVKAz6P1LajZOdoL+R+XC3HJYSU261fbJzO4fCkJJ7UPFcm+nP+gzC+DDZWsb2WK9PQvKsnaKiNKsY8B6dBWQ==", + "license": "MIT", + "dependencies": { + "@inquirer/core": "^10.1.8", + "@inquirer/figures": "^1.0.11", + "@inquirer/type": "^3.0.5", + "yoctocolors-cjs": "^2.1.2" + }, "engines": { - "node": ">=18.0.0" + "node": ">=18" }, "peerDependencies": { - "@typespec/compiler": "~0.64.0" + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } } }, - "node_modules/ajv": { - "version": "8.17.1", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz", - "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", + "node_modules/@inquirer/select": { + "version": "4.0.10", + "resolved": "https://registry.npmjs.org/@inquirer/select/-/select-4.0.10.tgz", + "integrity": "sha512-Tg8S9nESnCfISu5tCZSuXpXq0wHuDVimj7xyHstABgR34zcJnLdq/VbjB2mdZvNAMAehYBnNzSjxB06UE8LLAA==", + "license": "MIT", "dependencies": { - "fast-deep-equal": "^3.1.3", - "fast-uri": "^3.0.1", - "json-schema-traverse": "^1.0.0", - "require-from-string": "^2.0.2" + "@inquirer/core": "^10.1.8", + "@inquirer/figures": "^1.0.11", + "@inquirer/type": "^3.0.5", + "ansi-escapes": "^4.3.2", + "yoctocolors-cjs": "^2.1.2" }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } } }, - "node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "node_modules/@inquirer/type": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-3.0.5.tgz", + "integrity": "sha512-ZJpeIYYueOz/i/ONzrfof8g89kNdO2hjGuvULROo3O8rlB2CRtSseE5KeirnyE4t/thAn/EwvS/vuQeJCn+NZg==", + "license": "MIT", "engines": { - "node": ">=8" + "node": ">=18" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } } }, - "node_modules/ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "license": "ISC", "dependencies": { - "color-convert": "^1.9.0" + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" }, "engines": { - "node": ">=4" + "node": ">=12" } }, - "node_modules/argparse": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==" + "node_modules/@isaacs/cliui/node_modules/ansi-styles": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } }, - "node_modules/braces": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", - "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "node_modules/@isaacs/cliui/node_modules/wrap-ansi": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "license": "MIT", "dependencies": { - "fill-range": "^7.1.1" + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" }, "engines": { - "node": ">=8" + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" } }, - "node_modules/chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "node_modules/@isaacs/fs-minipass": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz", + "integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==", + "license": "ISC", "dependencies": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" + "minipass": "^7.0.4" }, "engines": { - "node": ">=4" + "node": ">=18.0.0" } }, - "node_modules/change-case": { - "version": "5.4.4", - "resolved": "https://registry.npmjs.org/change-case/-/change-case-5.4.4.tgz", - "integrity": "sha512-HRQyTk2/YPEkt9TnUPbOpr64Uw3KOicFWPVBb+xiHvd6eBx/qPr9xqfBFDT8P2vWsvvz4jbEkfDe71W3VyNu2w==" + "node_modules/@isaacs/string-locale-compare": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@isaacs/string-locale-compare/-/string-locale-compare-1.1.0.tgz", + "integrity": "sha512-SQ7Kzhh9+D+ZW9MA0zkYv3VXhIDNx+LzM6EJ+/65I3QY+enU6Itte7E5XX7EWrqLW2FN4n06GWzBnPoC3th2aQ==", + "license": "ISC" }, - "node_modules/cliui": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", - "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "license": "MIT", "dependencies": { - "string-width": "^4.2.0", - "strip-ansi": "^6.0.1", - "wrap-ansi": "^7.0.0" + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" }, "engines": { - "node": ">=12" + "node": ">= 8" } }, - "node_modules/color-convert": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "license": "MIT", "dependencies": { - "color-name": "1.1.3" + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" } }, - "node_modules/color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==" + "node_modules/@npmcli/agent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/agent/-/agent-3.0.0.tgz", + "integrity": "sha512-S79NdEgDQd/NGCay6TCoVzXSj74skRZIKJcpJjC5lOq34SZzyI6MqtiiWoiVWoVrTcGjNeC4ipbh1VIHlpfF5Q==", + "license": "ISC", + "dependencies": { + "agent-base": "^7.1.0", + "http-proxy-agent": "^7.0.0", + "https-proxy-agent": "^7.0.1", + "lru-cache": "^10.0.1", + "socks-proxy-agent": "^8.0.3" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } }, - "node_modules/emoji-regex": { + "node_modules/@npmcli/arborist": { "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" + "resolved": "https://registry.npmjs.org/@npmcli/arborist/-/arborist-8.0.0.tgz", + "integrity": "sha512-APDXxtXGSftyXibl0dZ3CuZYmmVnkiN3+gkqwXshY4GKC2rof2+Lg0sGuj6H1p2YfBAKd7PRwuMVhu6Pf/nQ/A==", + "license": "ISC", + "dependencies": { + "@isaacs/string-locale-compare": "^1.1.0", + "@npmcli/fs": "^4.0.0", + "@npmcli/installed-package-contents": "^3.0.0", + "@npmcli/map-workspaces": "^4.0.1", + "@npmcli/metavuln-calculator": "^8.0.0", + "@npmcli/name-from-folder": "^3.0.0", + "@npmcli/node-gyp": "^4.0.0", + "@npmcli/package-json": "^6.0.1", + "@npmcli/query": "^4.0.0", + "@npmcli/redact": "^3.0.0", + "@npmcli/run-script": "^9.0.1", + "bin-links": "^5.0.0", + "cacache": "^19.0.1", + "common-ancestor-path": "^1.0.1", + "hosted-git-info": "^8.0.0", + "json-parse-even-better-errors": "^4.0.0", + "json-stringify-nice": "^1.1.4", + "lru-cache": "^10.2.2", + "minimatch": "^9.0.4", + "nopt": "^8.0.0", + "npm-install-checks": "^7.1.0", + "npm-package-arg": "^12.0.0", + "npm-pick-manifest": "^10.0.0", + "npm-registry-fetch": "^18.0.1", + "pacote": "^19.0.0", + "parse-conflict-json": "^4.0.0", + "proc-log": "^5.0.0", + "proggy": "^3.0.0", + "promise-all-reject-late": "^1.0.0", + "promise-call-limit": "^3.0.1", + "read-package-json-fast": "^4.0.0", + "semver": "^7.3.7", + "ssri": "^12.0.0", + "treeverse": "^3.0.0", + "walk-up-path": "^3.0.1" + }, + "bin": { + "arborist": "bin/index.js" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } }, - "node_modules/escalade": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", - "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "node_modules/@npmcli/fs": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/fs/-/fs-4.0.0.tgz", + "integrity": "sha512-/xGlezI6xfGO9NwuJlnwz/K14qD1kCSAGtacBHnGzeAIuJGazcp45KP5NuyARXoKb7cwulAGWVsbeSxdG/cb0Q==", + "license": "ISC", + "dependencies": { + "semver": "^7.3.5" + }, "engines": { - "node": ">=6" + "node": "^18.17.0 || >=20.5.0" } }, - "node_modules/escape-string-regexp": { + "node_modules/@npmcli/git": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/@npmcli/git/-/git-6.0.3.tgz", + "integrity": "sha512-GUYESQlxZRAdhs3UhbB6pVRNUELQOHXwK9ruDkwmCv2aZ5y0SApQzUJCg02p3A7Ue2J5hxvlk1YI53c00NmRyQ==", + "license": "ISC", + "dependencies": { + "@npmcli/promise-spawn": "^8.0.0", + "ini": "^5.0.0", + "lru-cache": "^10.0.1", + "npm-pick-manifest": "^10.0.0", + "proc-log": "^5.0.0", + "promise-retry": "^2.0.1", + "semver": "^7.3.5", + "which": "^5.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@npmcli/installed-package-contents": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/installed-package-contents/-/installed-package-contents-3.0.0.tgz", + "integrity": "sha512-fkxoPuFGvxyrH+OQzyTkX2LUEamrF4jZSmxjAtPPHHGO0dqsQ8tTKjnIS8SAnPHdk2I03BDtSMR5K/4loKg79Q==", + "license": "ISC", + "dependencies": { + "npm-bundled": "^4.0.0", + "npm-normalize-package-bin": "^4.0.0" + }, + "bin": { + "installed-package-contents": "bin/index.js" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@npmcli/map-workspaces": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@npmcli/map-workspaces/-/map-workspaces-4.0.2.tgz", + "integrity": "sha512-mnuMuibEbkaBTYj9HQ3dMe6L0ylYW+s/gfz7tBDMFY/la0w9Kf44P9aLn4/+/t3aTR3YUHKoT6XQL9rlicIe3Q==", + "license": "ISC", + "dependencies": { + "@npmcli/name-from-folder": "^3.0.0", + "@npmcli/package-json": "^6.0.0", + "glob": "^10.2.2", + "minimatch": "^9.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@npmcli/metavuln-calculator": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/@npmcli/metavuln-calculator/-/metavuln-calculator-8.0.1.tgz", + "integrity": "sha512-WXlJx9cz3CfHSt9W9Opi1PTFc4WZLFomm5O8wekxQZmkyljrBRwATwDxfC9iOXJwYVmfiW1C1dUe0W2aN0UrSg==", + "license": "ISC", + "dependencies": { + "cacache": "^19.0.0", + "json-parse-even-better-errors": "^4.0.0", + "pacote": "^20.0.0", + "proc-log": "^5.0.0", + "semver": "^7.3.5" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@npmcli/metavuln-calculator/node_modules/chownr": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz", + "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==", + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/@npmcli/metavuln-calculator/node_modules/minizlib": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz", + "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==", + "license": "MIT", + "dependencies": { + "minipass": "^3.0.0", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@npmcli/metavuln-calculator/node_modules/minizlib/node_modules/minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@npmcli/metavuln-calculator/node_modules/mkdirp": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", + "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", + "license": "MIT", + "bin": { + "mkdirp": "bin/cmd.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@npmcli/metavuln-calculator/node_modules/pacote": { + "version": "20.0.0", + "resolved": "https://registry.npmjs.org/pacote/-/pacote-20.0.0.tgz", + "integrity": "sha512-pRjC5UFwZCgx9kUFDVM9YEahv4guZ1nSLqwmWiLUnDbGsjs+U5w7z6Uc8HNR1a6x8qnu5y9xtGE6D1uAuYz+0A==", + "license": "ISC", + "dependencies": { + "@npmcli/git": "^6.0.0", + "@npmcli/installed-package-contents": "^3.0.0", + "@npmcli/package-json": "^6.0.0", + "@npmcli/promise-spawn": "^8.0.0", + "@npmcli/run-script": "^9.0.0", + "cacache": "^19.0.0", + "fs-minipass": "^3.0.0", + "minipass": "^7.0.2", + "npm-package-arg": "^12.0.0", + "npm-packlist": "^9.0.0", + "npm-pick-manifest": "^10.0.0", + "npm-registry-fetch": "^18.0.0", + "proc-log": "^5.0.0", + "promise-retry": "^2.0.1", + "sigstore": "^3.0.0", + "ssri": "^12.0.0", + "tar": "^6.1.11" + }, + "bin": { + "pacote": "bin/index.js" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@npmcli/metavuln-calculator/node_modules/tar": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/tar/-/tar-6.2.1.tgz", + "integrity": "sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A==", + "license": "ISC", + "dependencies": { + "chownr": "^2.0.0", + "fs-minipass": "^2.0.0", + "minipass": "^5.0.0", + "minizlib": "^2.1.1", + "mkdirp": "^1.0.3", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@npmcli/metavuln-calculator/node_modules/tar/node_modules/fs-minipass": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", + "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==", + "license": "ISC", + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@npmcli/metavuln-calculator/node_modules/tar/node_modules/fs-minipass/node_modules/minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@npmcli/metavuln-calculator/node_modules/tar/node_modules/minipass": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz", + "integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==", + "license": "ISC", + "engines": { + "node": ">=8" + } + }, + "node_modules/@npmcli/metavuln-calculator/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "license": "ISC" + }, + "node_modules/@npmcli/name-from-folder": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/name-from-folder/-/name-from-folder-3.0.0.tgz", + "integrity": "sha512-61cDL8LUc9y80fXn+lir+iVt8IS0xHqEKwPu/5jCjxQTVoSCmkXvw4vbMrzAMtmghz3/AkiBjhHkDKUH+kf7kA==", + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@npmcli/node-gyp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/node-gyp/-/node-gyp-4.0.0.tgz", + "integrity": "sha512-+t5DZ6mO/QFh78PByMq1fGSAub/agLJZDRfJRMeOSNCt8s9YVlTjmGpIPwPhvXTGUIJk+WszlT0rQa1W33yzNA==", + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@npmcli/package-json": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/@npmcli/package-json/-/package-json-6.1.1.tgz", + "integrity": "sha512-d5qimadRAUCO4A/Txw71VM7UrRZzV+NPclxz/dc+M6B2oYwjWTjqh8HA/sGQgs9VZuJ6I/P7XIAlJvgrl27ZOw==", + "license": "ISC", + "dependencies": { + "@npmcli/git": "^6.0.0", + "glob": "^10.2.2", + "hosted-git-info": "^8.0.0", + "json-parse-even-better-errors": "^4.0.0", + "proc-log": "^5.0.0", + "semver": "^7.5.3", + "validate-npm-package-license": "^3.0.4" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@npmcli/promise-spawn": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@npmcli/promise-spawn/-/promise-spawn-8.0.2.tgz", + "integrity": "sha512-/bNJhjc+o6qL+Dwz/bqfTQClkEO5nTQ1ZEcdCkAQjhkZMHIh22LPG7fNh1enJP1NKWDqYiiABnjFCY7E0zHYtQ==", + "license": "ISC", + "dependencies": { + "which": "^5.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@npmcli/query": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@npmcli/query/-/query-4.0.0.tgz", + "integrity": "sha512-3pPbese0fbCiFJ/7/X1GBgxAKYFE8sxBddA7GtuRmOgNseH4YbGsXJ807Ig3AEwNITjDUISHglvy89cyDJnAwA==", + "license": "ISC", + "dependencies": { + "postcss-selector-parser": "^6.1.2" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@npmcli/redact": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@npmcli/redact/-/redact-3.1.1.tgz", + "integrity": "sha512-3Hc2KGIkrvJWJqTbvueXzBeZlmvoOxc2jyX00yzr3+sNFquJg0N8hH4SAPLPVrkWIRQICVpVgjrss971awXVnA==", + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@npmcli/run-script": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/@npmcli/run-script/-/run-script-9.1.0.tgz", + "integrity": "sha512-aoNSbxtkePXUlbZB+anS1LqsJdctG5n3UVhfU47+CDdwMi6uNTBMF9gPcQRnqghQd2FGzcwwIFBruFMxjhBewg==", + "license": "ISC", + "dependencies": { + "@npmcli/node-gyp": "^4.0.0", + "@npmcli/package-json": "^6.0.0", + "@npmcli/promise-spawn": "^8.0.0", + "node-gyp": "^11.0.0", + "proc-log": "^5.0.0", + "which": "^5.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@pkgjs/parseargs": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", + "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=14" + } + }, + "node_modules/@sigstore/bundle": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@sigstore/bundle/-/bundle-3.1.0.tgz", + "integrity": "sha512-Mm1E3/CmDDCz3nDhFKTuYdB47EdRFRQMOE/EAbiG1MJW77/w1b3P7Qx7JSrVJs8PfwOLOVcKQCHErIwCTyPbag==", + "license": "Apache-2.0", + "dependencies": { + "@sigstore/protobuf-specs": "^0.4.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@sigstore/core": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@sigstore/core/-/core-2.0.0.tgz", + "integrity": "sha512-nYxaSb/MtlSI+JWcwTHQxyNmWeWrUXJJ/G4liLrGG7+tS4vAz6LF3xRXqLH6wPIVUoZQel2Fs4ddLx4NCpiIYg==", + "license": "Apache-2.0", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@sigstore/protobuf-specs": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/@sigstore/protobuf-specs/-/protobuf-specs-0.4.0.tgz", + "integrity": "sha512-o09cLSIq9EKyRXwryWDOJagkml9XgQCoCSRjHOnHLnvsivaW7Qznzz6yjfV7PHJHhIvyp8OH7OX8w0Dc5bQK7A==", + "license": "Apache-2.0", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@sigstore/sign": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@sigstore/sign/-/sign-3.1.0.tgz", + "integrity": "sha512-knzjmaOHOov1Ur7N/z4B1oPqZ0QX5geUfhrVaqVlu+hl0EAoL4o+l0MSULINcD5GCWe3Z0+YJO8ues6vFlW0Yw==", + "license": "Apache-2.0", + "dependencies": { + "@sigstore/bundle": "^3.1.0", + "@sigstore/core": "^2.0.0", + "@sigstore/protobuf-specs": "^0.4.0", + "make-fetch-happen": "^14.0.2", + "proc-log": "^5.0.0", + "promise-retry": "^2.0.1" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@sigstore/tuf": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@sigstore/tuf/-/tuf-3.1.0.tgz", + "integrity": "sha512-suVMQEA+sKdOz5hwP9qNcEjX6B45R+hFFr4LAWzbRc5O+U2IInwvay/bpG5a4s+qR35P/JK/PiKiRGjfuLy1IA==", + "license": "Apache-2.0", + "dependencies": { + "@sigstore/protobuf-specs": "^0.4.0", + "tuf-js": "^3.0.1" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@sigstore/verify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@sigstore/verify/-/verify-2.1.0.tgz", + "integrity": "sha512-kAAM06ca4CzhvjIZdONAL9+MLppW3K48wOFy1TbuaWFW/OMfl8JuTgW0Bm02JB1WJGT/ET2eqav0KTEKmxqkIA==", + "license": "Apache-2.0", + "dependencies": { + "@sigstore/bundle": "^3.1.0", + "@sigstore/core": "^2.0.0", + "@sigstore/protobuf-specs": "^0.4.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@sindresorhus/merge-streams": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/merge-streams/-/merge-streams-2.3.0.tgz", + "integrity": "sha512-LtoMMhxAlorcGhmFYI+LhPgbPZCkgP6ra1YL604EeF6U98pLlQ3iWIGMdWSC+vWmPBWBNgmDBAhnAobLROJmwg==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@tufjs/canonical-json": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@tufjs/canonical-json/-/canonical-json-2.0.0.tgz", + "integrity": "sha512-yVtV8zsdo8qFHe+/3kw81dSLyF7D576A5cCFCi4X7B39tWT7SekaEFUnvnWJHz+9qO7qJTah1JbrDjWKqFtdWA==", + "license": "MIT", + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/@tufjs/models": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@tufjs/models/-/models-3.0.1.tgz", + "integrity": "sha512-UUYHISyhCU3ZgN8yaear3cGATHb3SMuKHsQ/nVbHXcmnBf+LzQ/cQfhNG+rfaSHgqGKNEm2cOCLVLELStUQ1JA==", + "license": "MIT", + "dependencies": { + "@tufjs/canonical-json": "2.0.0", + "minimatch": "^9.0.5" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@typespec/compiler": { + "version": "0.66.0", + "resolved": "https://registry.npmjs.org/@typespec/compiler/-/compiler-0.66.0.tgz", + "integrity": "sha512-JoaHQCc1Va48xuiws7UHFa9ix1bxxJrjTud69mrbu67HerqLN5meLwNkqVGrOlEfUnvMcnaXNQlHbMbixmshQA==", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "~7.26.2", + "@inquirer/prompts": "^7.3.1", + "@npmcli/arborist": "^8.0.0", + "ajv": "~8.17.1", + "change-case": "~5.4.4", + "globby": "~14.0.2", + "is-unicode-supported": "^2.1.0", + "mustache": "~4.2.0", + "picocolors": "~1.1.1", + "prettier": "~3.4.2", + "semver": "^7.6.3", + "temporal-polyfill": "^0.2.5", + "vscode-languageserver": "~9.0.1", + "vscode-languageserver-textdocument": "~1.0.12", + "yaml": "~2.7.0", + "yargs": "~17.7.2" + }, + "bin": { + "tsp": "cmd/tsp.js", + "tsp-server": "cmd/tsp-server.js" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@typespec/http": { + "version": "0.66.0", + "resolved": "https://registry.npmjs.org/@typespec/http/-/http-0.66.0.tgz", + "integrity": "sha512-IKD5FMvnjbZ5cdQ3wTXXAnnQgDcqFuPtVphpTdnYER87gGEa8YNLocgK44CLFB+GvVkTecDltG0CNKPSPQ0RMw==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + }, + "peerDependencies": { + "@typespec/compiler": "~0.66.0", + "@typespec/streams": "~0.66.0" + }, + "peerDependenciesMeta": { + "@typespec/streams": { + "optional": true + } + } + }, + "node_modules/@typespec/openapi": { + "version": "0.66.0", + "resolved": "https://registry.npmjs.org/@typespec/openapi/-/openapi-0.66.0.tgz", + "integrity": "sha512-Oiwx2glN5bET4C3cuU5DIhd7nL/wBi+tg1KGBx0bU4KogLaGf+BLW5ak0Epxnvhy8VYvPhCpTGbez0I6gkEOwA==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + }, + "peerDependencies": { + "@typespec/compiler": "~0.66.0", + "@typespec/http": "~0.66.0" + } + }, + "node_modules/@typespec/rest": { + "version": "0.66.0", + "resolved": "https://registry.npmjs.org/@typespec/rest/-/rest-0.66.0.tgz", + "integrity": "sha512-r/o1GXz/BB9lgMPzMkrLIhTUm4elx5JAD/t6QGWDdUptXntVSapCYmIwCV/Iv10+QnHrsB1/v152nz9nd4lOHg==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + }, + "peerDependencies": { + "@typespec/compiler": "~0.66.0", + "@typespec/http": "~0.66.0" + } + }, + "node_modules/@typespec/versioning": { + "version": "0.66.0", + "resolved": "https://registry.npmjs.org/@typespec/versioning/-/versioning-0.66.0.tgz", + "integrity": "sha512-8AhTpo6jxcjwxZPAegI/sDEePoqXz5Si8XBw/x7jz+EkBvbgqT9GT0UUzJL1XgOwQaks2aMr4DdOn8n9kOCltg==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + }, + "peerDependencies": { + "@typespec/compiler": "~0.66.0" + } + }, + "node_modules/@typespec/xml": { + "version": "0.66.0", + "resolved": "https://registry.npmjs.org/@typespec/xml/-/xml-0.66.0.tgz", + "integrity": "sha512-jbBRctPzroJK+ANxe1YNXwTsx99N6rLuaxbb/jVShgHPTzLAD1LckswEMO9HPfQWF8ld1+YB0yJQMoMjY1ZGjg==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + }, + "peerDependencies": { + "@typespec/compiler": "~0.66.0" + } + }, + "node_modules/abbrev": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-3.0.0.tgz", + "integrity": "sha512-+/kfrslGQ7TNV2ecmQwMJj/B65g5KVq1/L3SGVZ3tCYGqlzFuFCGBZJtMP99wH3NpEUyAjn0zPdPUg0D+DwrOA==", + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/agent-base": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.3.tgz", + "integrity": "sha512-jRR5wdylq8CkOe6hei19GGZnxM6rBGwFl3Bg0YItGDimvjGtAvdZk4Pu6Cl4u4Igsws4a1fd1Vq3ezrhn4KmFw==", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/ajv": { + "version": "8.17.1", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz", + "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ansi-escapes": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", + "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", + "license": "MIT", + "dependencies": { + "type-fest": "^0.21.3" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ansi-regex": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", + "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "license": "Python-2.0" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "license": "MIT" + }, + "node_modules/bin-links": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/bin-links/-/bin-links-5.0.0.tgz", + "integrity": "sha512-sdleLVfCjBtgO5cNjA2HVRvWBJAHs4zwenaCPMNJAJU0yNxpzj80IpjOIimkpkr+mhlA+how5poQtt53PygbHA==", + "license": "ISC", + "dependencies": { + "cmd-shim": "^7.0.0", + "npm-normalize-package-bin": "^4.0.0", + "proc-log": "^5.0.0", + "read-cmd-shim": "^5.0.0", + "write-file-atomic": "^6.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cacache": { + "version": "19.0.1", + "resolved": "https://registry.npmjs.org/cacache/-/cacache-19.0.1.tgz", + "integrity": "sha512-hdsUxulXCi5STId78vRVYEtDAjq99ICAUktLTeTYsLoTE6Z8dS0c8pWNCxwdrk9YfJeobDZc2Y186hD/5ZQgFQ==", + "license": "ISC", + "dependencies": { + "@npmcli/fs": "^4.0.0", + "fs-minipass": "^3.0.0", + "glob": "^10.2.2", + "lru-cache": "^10.0.1", + "minipass": "^7.0.3", + "minipass-collect": "^2.0.1", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "p-map": "^7.0.2", + "ssri": "^12.0.0", + "tar": "^7.4.3", + "unique-filename": "^4.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/change-case": { + "version": "5.4.4", + "resolved": "https://registry.npmjs.org/change-case/-/change-case-5.4.4.tgz", + "integrity": "sha512-HRQyTk2/YPEkt9TnUPbOpr64Uw3KOicFWPVBb+xiHvd6eBx/qPr9xqfBFDT8P2vWsvvz4jbEkfDe71W3VyNu2w==", + "license": "MIT" + }, + "node_modules/chardet": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz", + "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==", + "license": "MIT" + }, + "node_modules/chownr": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", + "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/cli-width": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-4.1.0.tgz", + "integrity": "sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==", + "license": "ISC", + "engines": { + "node": ">= 12" + } + }, + "node_modules/cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/cliui/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/cliui/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/cliui/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cliui/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cliui/node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/cmd-shim": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/cmd-shim/-/cmd-shim-7.0.0.tgz", + "integrity": "sha512-rtpaCbr164TPPh+zFdkWpCyZuKkjpAzODfaZCf/SVJZzJN+4bHQb/LP3Jzq5/+84um3XXY8r548XiWKSborwVw==", + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, + "node_modules/common-ancestor-path": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/common-ancestor-path/-/common-ancestor-path-1.0.1.tgz", + "integrity": "sha512-L3sHRo1pXXEqX8VU28kfgUY+YGsk09hPqZiZmLacNib6XNTCM8ubYeT7ryXQw8asB1sKgcU5lkB7ONug08aB8w==", + "license": "ISC" + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/cross-spawn/node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, + "node_modules/cross-spawn/node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/cssesc": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", + "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", + "license": "MIT", + "bin": { + "cssesc": "bin/cssesc" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/debug": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", + "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/eastasianwidth": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", + "license": "MIT" + }, + "node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "license": "MIT" + }, + "node_modules/encoding": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.13.tgz", + "integrity": "sha512-ETBauow1T35Y/WZMkio9jiM0Z5xjHHmJ4XmjZOq1l/dXz3lr2sRn87nJy20RupqSh1F2m3HHPSp8ShIPQJrJ3A==", + "license": "MIT", + "optional": true, + "dependencies": { + "iconv-lite": "^0.6.2" + } + }, + "node_modules/encoding/node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "license": "MIT", + "optional": true, + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/env-paths": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz", + "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/err-code": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/err-code/-/err-code-2.0.3.tgz", + "integrity": "sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA==", + "license": "MIT" + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/exponential-backoff": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/exponential-backoff/-/exponential-backoff-3.1.2.tgz", + "integrity": "sha512-8QxYTVXUkuy7fIIoitQkPwGonB8F3Zj8eEO8Sqg9Zv/bkI7RJAzowee4gr81Hak/dUTpA2Z7VfQgoijjPNlUZA==", + "license": "Apache-2.0" + }, + "node_modules/external-editor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-3.1.0.tgz", + "integrity": "sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew==", + "license": "MIT", + "dependencies": { + "chardet": "^0.7.0", + "iconv-lite": "^0.4.24", + "tmp": "^0.0.33" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-glob": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", + "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.8" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/fast-uri": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.0.6.tgz", + "integrity": "sha512-Atfo14OibSv5wAp4VWNsFYE1AchQRTv9cBGWET4pZWHzYshFSS9NQI6I57rdKn9croWVMbYFbLhJ+yJvmZIIHw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/fastq": { + "version": "1.19.1", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.19.1.tgz", + "integrity": "sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==", + "license": "ISC", + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/foreground-child": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", + "integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==", + "license": "ISC", + "dependencies": { + "cross-spawn": "^7.0.6", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/fs-minipass": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-3.0.3.tgz", + "integrity": "sha512-XUBA9XClHbnJWSfBzjkm6RvPsyg3sryZt06BEQoXcF7EK/xpGaQYJgQKDJSUH5SGZ76Y7pFx1QBnXz09rU5Fbw==", + "license": "ISC", + "dependencies": { + "minipass": "^7.0.3" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/glob": { + "version": "10.4.5", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz", + "integrity": "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg==", + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/globby": { + "version": "14.0.2", + "resolved": "https://registry.npmjs.org/globby/-/globby-14.0.2.tgz", + "integrity": "sha512-s3Fq41ZVh7vbbe2PN3nrW7yC7U7MFVc5c98/iTl9c2GawNMKx/J648KQRW6WKkuU8GIbbh2IXfIRQjOZnXcTnw==", + "license": "MIT", + "dependencies": { + "@sindresorhus/merge-streams": "^2.1.0", + "fast-glob": "^3.3.2", + "ignore": "^5.2.4", + "path-type": "^5.0.0", + "slash": "^5.1.0", + "unicorn-magic": "^0.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "license": "ISC" + }, + "node_modules/hosted-git-info": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-8.0.2.tgz", + "integrity": "sha512-sYKnA7eGln5ov8T8gnYlkSOxFJvywzEx9BueN6xo/GKO8PGiI6uK6xx+DIGe45T3bdVjLAQDQW1aicT8z8JwQg==", + "license": "ISC", + "dependencies": { + "lru-cache": "^10.0.1" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/http-cache-semantics": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.1.1.tgz", + "integrity": "sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ==", + "license": "BSD-2-Clause" + }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/ignore-walk": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/ignore-walk/-/ignore-walk-7.0.0.tgz", + "integrity": "sha512-T4gbf83A4NH95zvhVYZc+qWocBBGlpzUXLPGurJggw/WIOwicfXJChLDP/iBZnN5WqROSu5Bm3hhle4z8a8YGQ==", + "license": "ISC", + "dependencies": { + "minimatch": "^9.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/ini": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ini/-/ini-5.0.0.tgz", + "integrity": "sha512-+N0ngpO3e7cRUWOJAS7qw0IZIVc6XPrW4MlFBdD066F2L4k1L6ker3hLqSq7iXxU5tgS4WGkIUElWn5vogAEnw==", + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/ip-address": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-9.0.5.tgz", + "integrity": "sha512-zHtQzGojZXTwZTHQqra+ETKd4Sn3vgi7uBmlPoXVWZqYvuKmtI0l/VZTjqGmJY9x88GGOaZ9+G9ES8hC4T4X8g==", + "license": "MIT", + "dependencies": { + "jsbn": "1.1.0", + "sprintf-js": "^1.1.3" + }, + "engines": { + "node": ">= 12" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-unicode-supported": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-2.1.0.tgz", + "integrity": "sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/isexe": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.1.tgz", + "integrity": "sha512-LpB/54B+/2J5hqQ7imZHfdU31OlgQqx7ZicVlkm9kzg9/w8GKLEcFfJl/t7DCEDueOyBAD6zCCwTO6Fzs0NoEQ==", + "license": "ISC", + "engines": { + "node": ">=16" + } + }, + "node_modules/jackspeak": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz", + "integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==", + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "optionalDependencies": { + "@pkgjs/parseargs": "^0.11.0" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "license": "MIT" + }, + "node_modules/js-yaml": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsbn": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-1.1.0.tgz", + "integrity": "sha512-4bYVV3aAMtDTTu4+xsDYa6sy9GyJ69/amsu9sYF2zqjiEoZA5xJi3BrfX3uY+/IekIu7MwdObdbDWpoZdBv3/A==", + "license": "MIT" + }, + "node_modules/json-parse-even-better-errors": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-4.0.0.tgz", + "integrity": "sha512-lR4MXjGNgkJc7tkQ97kb2nuEMnNCyU//XYVH0MKTGcXEiSudQ5MKGKen3C5QubYy0vmq+JGitUg92uuywGEwIA==", + "license": "MIT", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "license": "MIT" + }, + "node_modules/json-stringify-nice": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/json-stringify-nice/-/json-stringify-nice-1.1.4.tgz", + "integrity": "sha512-5Z5RFW63yxReJ7vANgW6eZFGWaQvnPE3WNmZoOJrSkGju2etKA2L5rrOa1sm877TVTFt57A80BH1bArcmlLfPw==", + "license": "ISC", + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/jsonparse": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/jsonparse/-/jsonparse-1.3.1.tgz", + "integrity": "sha512-POQXvpdL69+CluYsillJ7SUhKvytYjW9vG/GKpnf+xP8UWgYEM/RaMzHHofbALDiKbbP1W8UEYmgGl39WkPZsg==", + "engines": [ + "node >= 0.2.0" + ], + "license": "MIT" + }, + "node_modules/just-diff": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/just-diff/-/just-diff-6.0.2.tgz", + "integrity": "sha512-S59eriX5u3/QhMNq3v/gm8Kd0w8OS6Tz2FS1NG4blv+z0MuQcBRJyFWjdovM0Rad4/P4aUPFtnkNjMjyMlMSYA==", + "license": "MIT" + }, + "node_modules/just-diff-apply": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/just-diff-apply/-/just-diff-apply-5.5.0.tgz", + "integrity": "sha512-OYTthRfSh55WOItVqwpefPtNt2VdKsq5AnAK6apdtR6yCH8pr0CmSr710J0Mf+WdQy7K/OzMy7K2MgAfdQURDw==", + "license": "MIT" + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "license": "MIT" + }, + "node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "license": "ISC" + }, + "node_modules/make-fetch-happen": { + "version": "14.0.3", + "resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-14.0.3.tgz", + "integrity": "sha512-QMjGbFTP0blj97EeidG5hk/QhKQ3T4ICckQGLgz38QF7Vgbk6e6FTARN8KhKxyBbWn8R0HU+bnw8aSoFPD4qtQ==", + "license": "ISC", + "dependencies": { + "@npmcli/agent": "^3.0.0", + "cacache": "^19.0.1", + "http-cache-semantics": "^4.1.1", + "minipass": "^7.0.2", + "minipass-fetch": "^4.0.0", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "negotiator": "^1.0.0", + "proc-log": "^5.0.0", + "promise-retry": "^2.0.1", + "ssri": "^12.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/merge2": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/minimatch": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", + "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/minipass": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", + "license": "ISC", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/minipass-collect": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/minipass-collect/-/minipass-collect-2.0.1.tgz", + "integrity": "sha512-D7V8PO9oaz7PWGLbCACuI1qEOsq7UKfLotx/C0Aet43fCUB/wfQ7DYeq2oR/svFJGYDHPr38SHATeaj/ZoKHKw==", + "license": "ISC", + "dependencies": { + "minipass": "^7.0.3" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/minipass-fetch": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/minipass-fetch/-/minipass-fetch-4.0.1.tgz", + "integrity": "sha512-j7U11C5HXigVuutxebFadoYBbd7VSdZWggSe64NVdvWNBqGAiXPL2QVCehjmw7lY1oF9gOllYbORh+hiNgfPgQ==", + "license": "MIT", + "dependencies": { + "minipass": "^7.0.3", + "minipass-sized": "^1.0.3", + "minizlib": "^3.0.1" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + }, + "optionalDependencies": { + "encoding": "^0.1.13" + } + }, + "node_modules/minipass-flush": { "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "resolved": "https://registry.npmjs.org/minipass-flush/-/minipass-flush-1.0.5.tgz", + "integrity": "sha512-JmQSYYpPUqX5Jyn1mXaRwOda1uQ8HP5KAT/oDSLCzt1BYRhQU0/hDtsB1ufZfEEzMZ9aAVmsBw8+FWsIXlClWw==", + "license": "ISC", + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/minipass-flush/node_modules/minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minipass-flush/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "license": "ISC" + }, + "node_modules/minipass-pipeline": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/minipass-pipeline/-/minipass-pipeline-1.2.4.tgz", + "integrity": "sha512-xuIq7cIOt09RPRJ19gdi4b+RiNvDFYe5JH+ggNvBqGqpQXcru3PcRmOZuHBKWK1Txf9+cQ+HMVN4d6z46LZP7A==", + "license": "ISC", + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minipass-pipeline/node_modules/minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minipass-pipeline/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "license": "ISC" + }, + "node_modules/minipass-sized": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/minipass-sized/-/minipass-sized-1.0.3.tgz", + "integrity": "sha512-MbkQQ2CTiBMlA2Dm/5cY+9SWFEN8pzzOXi6rlM5Xxq0Yqbda5ZQy9sU75a673FE9ZK0Zsbr6Y5iP6u9nktfg2g==", + "license": "ISC", + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minipass-sized/node_modules/minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minipass-sized/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "license": "ISC" + }, + "node_modules/minizlib": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.0.1.tgz", + "integrity": "sha512-umcy022ILvb5/3Djuu8LWeqUa8D68JaBzlttKeMWen48SjabqS3iY5w/vzeMzMUNhLDifyhbOwKDSznB1vvrwg==", + "license": "MIT", + "dependencies": { + "minipass": "^7.0.4", + "rimraf": "^5.0.5" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/mkdirp": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-3.0.1.tgz", + "integrity": "sha512-+NsyUUAZDmo6YVHzL/stxSu3t9YS1iljliy3BSDrXJ/dkn1KYdmtZODGGjLcc9XLgVVpH4KshHB8XmZgMhaBXg==", + "license": "MIT", + "bin": { + "mkdirp": "dist/cjs/src/bin.js" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/mustache": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/mustache/-/mustache-4.2.0.tgz", + "integrity": "sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ==", + "license": "MIT", + "bin": { + "mustache": "bin/mustache" + } + }, + "node_modules/mute-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-2.0.0.tgz", + "integrity": "sha512-WWdIxpyjEn+FhQJQQv9aQAYlHoNVdzIzUySNV1gHUPDSdZJ3yZn7pAAbQcV7B56Mvu881q9FZV+0Vx2xC44VWA==", + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/node-gyp": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-11.1.0.tgz", + "integrity": "sha512-/+7TuHKnBpnMvUQnsYEb0JOozDZqarQbfNuSGLXIjhStMT0fbw7IdSqWgopOP5xhRZE+lsbIvAHcekddruPZgQ==", + "license": "MIT", + "dependencies": { + "env-paths": "^2.2.0", + "exponential-backoff": "^3.1.1", + "glob": "^10.3.10", + "graceful-fs": "^4.2.6", + "make-fetch-happen": "^14.0.3", + "nopt": "^8.0.0", + "proc-log": "^5.0.0", + "semver": "^7.3.5", + "tar": "^7.4.3", + "which": "^5.0.0" + }, + "bin": { + "node-gyp": "bin/node-gyp.js" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/nopt": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-8.1.0.tgz", + "integrity": "sha512-ieGu42u/Qsa4TFktmaKEwM6MQH0pOWnaB3htzh0JRtx84+Mebc0cbZYN5bC+6WTZ4+77xrL9Pn5m7CV6VIkV7A==", + "license": "ISC", + "dependencies": { + "abbrev": "^3.0.0" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm-bundled": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/npm-bundled/-/npm-bundled-4.0.0.tgz", + "integrity": "sha512-IxaQZDMsqfQ2Lz37VvyyEtKLe8FsRZuysmedy/N06TU1RyVppYKXrO4xIhR0F+7ubIBox6Q7nir6fQI3ej39iA==", + "license": "ISC", + "dependencies": { + "npm-normalize-package-bin": "^4.0.0" + }, "engines": { - "node": ">=0.8.0" + "node": "^18.17.0 || >=20.5.0" } }, - "node_modules/fast-deep-equal": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", - "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" - }, - "node_modules/fast-glob": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", - "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", + "node_modules/npm-install-checks": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/npm-install-checks/-/npm-install-checks-7.1.1.tgz", + "integrity": "sha512-u6DCwbow5ynAX5BdiHQ9qvexme4U3qHW3MWe5NqH+NeBm0LbiH6zvGjNNew1fY+AZZUtVHbOPF3j7mJxbUzpXg==", + "license": "BSD-2-Clause", "dependencies": { - "@nodelib/fs.stat": "^2.0.2", - "@nodelib/fs.walk": "^1.2.3", - "glob-parent": "^5.1.2", - "merge2": "^1.3.0", - "micromatch": "^4.0.8" + "semver": "^7.1.1" }, "engines": { - "node": ">=8.6.0" + "node": "^18.17.0 || >=20.5.0" } }, - "node_modules/fast-uri": { - "version": "3.0.5", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.0.5.tgz", - "integrity": "sha512-5JnBCWpFlMo0a3ciDy/JckMzzv1U9coZrIhedq+HXxxUfDTAiS0LA8OKVao4G9BxmCVck/jtA5r3KAtRWEyD8Q==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ] - }, - "node_modules/fastq": { - "version": "1.18.0", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.18.0.tgz", - "integrity": "sha512-QKHXPW0hD8g4UET03SdOdunzSouc9N4AuHdsX8XNcTsuz+yYFILVNIX4l9yHABMhiEI9Db0JTTIpu0wB+Y1QQw==", - "dependencies": { - "reusify": "^1.0.4" + "node_modules/npm-normalize-package-bin": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/npm-normalize-package-bin/-/npm-normalize-package-bin-4.0.0.tgz", + "integrity": "sha512-TZKxPvItzai9kN9H/TkmCtx/ZN/hvr3vUycjlfmH0ootY9yFBzNOpiXAdIn1Iteqsvk4lQn6B5PTrt+n6h8k/w==", + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" } }, - "node_modules/fill-range": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", - "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "node_modules/npm-package-arg": { + "version": "12.0.2", + "resolved": "https://registry.npmjs.org/npm-package-arg/-/npm-package-arg-12.0.2.tgz", + "integrity": "sha512-f1NpFjNI9O4VbKMOlA5QoBq/vSQPORHcTZ2feJpFkTHJ9eQkdlmZEKSjcAhxTGInC7RlEyScT9ui67NaOsjFWA==", + "license": "ISC", "dependencies": { - "to-regex-range": "^5.0.1" + "hosted-git-info": "^8.0.0", + "proc-log": "^5.0.0", + "semver": "^7.3.5", + "validate-npm-package-name": "^6.0.0" }, "engines": { - "node": ">=8" + "node": "^18.17.0 || >=20.5.0" } }, - "node_modules/get-caller-file": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", - "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "node_modules/npm-packlist": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/npm-packlist/-/npm-packlist-9.0.0.tgz", + "integrity": "sha512-8qSayfmHJQTx3nJWYbbUmflpyarbLMBc6LCAjYsiGtXxDB68HaZpb8re6zeaLGxZzDuMdhsg70jryJe+RrItVQ==", + "license": "ISC", + "dependencies": { + "ignore-walk": "^7.0.0" + }, "engines": { - "node": "6.* || 8.* || >= 10.*" + "node": "^18.17.0 || >=20.5.0" } }, - "node_modules/glob-parent": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", - "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "node_modules/npm-pick-manifest": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/npm-pick-manifest/-/npm-pick-manifest-10.0.0.tgz", + "integrity": "sha512-r4fFa4FqYY8xaM7fHecQ9Z2nE9hgNfJR+EmoKv0+chvzWkBcORX3r0FpTByP+CbOVJDladMXnPQGVN8PBLGuTQ==", + "license": "ISC", "dependencies": { - "is-glob": "^4.0.1" + "npm-install-checks": "^7.1.0", + "npm-normalize-package-bin": "^4.0.0", + "npm-package-arg": "^12.0.0", + "semver": "^7.3.5" }, "engines": { - "node": ">= 6" + "node": "^18.17.0 || >=20.5.0" } }, - "node_modules/globby": { - "version": "14.0.2", - "resolved": "https://registry.npmjs.org/globby/-/globby-14.0.2.tgz", - "integrity": "sha512-s3Fq41ZVh7vbbe2PN3nrW7yC7U7MFVc5c98/iTl9c2GawNMKx/J648KQRW6WKkuU8GIbbh2IXfIRQjOZnXcTnw==", + "node_modules/npm-registry-fetch": { + "version": "18.0.2", + "resolved": "https://registry.npmjs.org/npm-registry-fetch/-/npm-registry-fetch-18.0.2.tgz", + "integrity": "sha512-LeVMZBBVy+oQb5R6FDV9OlJCcWDU+al10oKpe+nsvcHnG24Z3uM3SvJYKfGJlfGjVU8v9liejCrUR/M5HO5NEQ==", + "license": "ISC", "dependencies": { - "@sindresorhus/merge-streams": "^2.1.0", - "fast-glob": "^3.3.2", - "ignore": "^5.2.4", - "path-type": "^5.0.0", - "slash": "^5.1.0", - "unicorn-magic": "^0.1.0" + "@npmcli/redact": "^3.0.0", + "jsonparse": "^1.3.1", + "make-fetch-happen": "^14.0.0", + "minipass": "^7.0.2", + "minipass-fetch": "^4.0.0", + "minizlib": "^3.0.1", + "npm-package-arg": "^12.0.0", + "proc-log": "^5.0.0" }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/os-tmpdir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/p-map": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/p-map/-/p-map-7.0.3.tgz", + "integrity": "sha512-VkndIv2fIB99swvQoA65bm+fsmt6UNdGeIB0oxBs+WhAhdh08QA04JXpI7rbB9r08/nkbysKoya9rtDERYOYMA==", + "license": "MIT", "engines": { "node": ">=18" }, @@ -560,128 +2448,189 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/graceful-fs": { - "version": "4.2.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", - "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==" + "node_modules/package-json-from-dist": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", + "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", + "license": "BlueOak-1.0.0" }, - "node_modules/has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "node_modules/pacote": { + "version": "19.0.1", + "resolved": "https://registry.npmjs.org/pacote/-/pacote-19.0.1.tgz", + "integrity": "sha512-zIpxWAsr/BvhrkSruspG8aqCQUUrWtpwx0GjiRZQhEM/pZXrigA32ElN3vTcCPUDOFmHr6SFxwYrvVUs5NTEUg==", + "license": "ISC", + "dependencies": { + "@npmcli/git": "^6.0.0", + "@npmcli/installed-package-contents": "^3.0.0", + "@npmcli/package-json": "^6.0.0", + "@npmcli/promise-spawn": "^8.0.0", + "@npmcli/run-script": "^9.0.0", + "cacache": "^19.0.0", + "fs-minipass": "^3.0.0", + "minipass": "^7.0.2", + "npm-package-arg": "^12.0.0", + "npm-packlist": "^9.0.0", + "npm-pick-manifest": "^10.0.0", + "npm-registry-fetch": "^18.0.0", + "proc-log": "^5.0.0", + "promise-retry": "^2.0.1", + "sigstore": "^3.0.0", + "ssri": "^12.0.0", + "tar": "^6.1.11" + }, + "bin": { + "pacote": "bin/index.js" + }, "engines": { - "node": ">=4" + "node": "^18.17.0 || >=20.5.0" } }, - "node_modules/ignore": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", - "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "node_modules/pacote/node_modules/chownr": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz", + "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==", + "license": "ISC", "engines": { - "node": ">= 4" + "node": ">=10" } }, - "node_modules/is-extglob": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", - "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "node_modules/pacote/node_modules/minizlib": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz", + "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==", + "license": "MIT", + "dependencies": { + "minipass": "^3.0.0", + "yallist": "^4.0.0" + }, "engines": { - "node": ">=0.10.0" + "node": ">= 8" } }, - "node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "node_modules/pacote/node_modules/minizlib/node_modules/minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, "engines": { "node": ">=8" } }, - "node_modules/is-glob": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", - "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", - "dependencies": { - "is-extglob": "^2.1.1" + "node_modules/pacote/node_modules/mkdirp": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", + "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", + "license": "MIT", + "bin": { + "mkdirp": "bin/cmd.js" }, "engines": { - "node": ">=0.10.0" + "node": ">=10" } }, - "node_modules/is-number": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", - "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "node_modules/pacote/node_modules/tar": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/tar/-/tar-6.2.1.tgz", + "integrity": "sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A==", + "license": "ISC", + "dependencies": { + "chownr": "^2.0.0", + "fs-minipass": "^2.0.0", + "minipass": "^5.0.0", + "minizlib": "^2.1.1", + "mkdirp": "^1.0.3", + "yallist": "^4.0.0" + }, "engines": { - "node": ">=0.12.0" + "node": ">=10" } }, - "node_modules/js-tokens": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" - }, - "node_modules/js-yaml": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", - "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "node_modules/pacote/node_modules/tar/node_modules/fs-minipass": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", + "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==", + "license": "ISC", "dependencies": { - "argparse": "^2.0.1" + "minipass": "^3.0.0" }, - "bin": { - "js-yaml": "bin/js-yaml.js" + "engines": { + "node": ">= 8" } }, - "node_modules/json-schema-traverse": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", - "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==" - }, - "node_modules/kleur": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", - "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", + "node_modules/pacote/node_modules/tar/node_modules/fs-minipass/node_modules/minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, "engines": { - "node": ">=6" + "node": ">=8" } }, - "node_modules/lodash": { - "version": "4.17.21", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", - "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" - }, - "node_modules/merge2": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", - "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "node_modules/pacote/node_modules/tar/node_modules/minipass": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz", + "integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==", + "license": "ISC", "engines": { - "node": ">= 8" + "node": ">=8" } }, - "node_modules/micromatch": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", - "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "node_modules/pacote/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "license": "ISC" + }, + "node_modules/parse-conflict-json": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/parse-conflict-json/-/parse-conflict-json-4.0.0.tgz", + "integrity": "sha512-37CN2VtcuvKgHUs8+0b1uJeEsbGn61GRHz469C94P5xiOoqpDYJYwjg4RY9Vmz39WyZAVkR5++nbJwLMIgOCnQ==", + "license": "ISC", "dependencies": { - "braces": "^3.0.3", - "picomatch": "^2.3.1" + "json-parse-even-better-errors": "^4.0.0", + "just-diff": "^6.0.0", + "just-diff-apply": "^5.2.0" }, "engines": { - "node": ">=8.6" + "node": "^18.17.0 || >=20.5.0" } }, - "node_modules/mustache": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/mustache/-/mustache-4.2.0.tgz", - "integrity": "sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ==", - "bin": { - "mustache": "bin/mustache" + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-scurry": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz", + "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==", + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^10.2.0", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + }, + "engines": { + "node": ">=16 || 14 >=14.18" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" } }, "node_modules/path-type": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/path-type/-/path-type-5.0.0.tgz", "integrity": "sha512-5HviZNaZcfqP95rwpv+1HDgUamezbqdSYTyzjTvwtJSnIH+3vnbmWsItli8OFEndS984VT55M3jduxZbX351gg==", + "license": "MIT", "engines": { "node": ">=12" }, @@ -692,12 +2641,14 @@ "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", - "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==" + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" }, "node_modules/picomatch": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "license": "MIT", "engines": { "node": ">=8.6" }, @@ -709,14 +2660,29 @@ "version": "8.0.0", "resolved": "https://registry.npmjs.org/pluralize/-/pluralize-8.0.0.tgz", "integrity": "sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/postcss-selector-parser": { + "version": "6.1.2", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.2.tgz", + "integrity": "sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg==", + "license": "MIT", + "dependencies": { + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" + }, "engines": { "node": ">=4" } }, "node_modules/prettier": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.3.3.tgz", - "integrity": "sha512-i2tDNA0O5IrMO757lfrdQZCc2jPNDVntV0m/+4whiDfWaTKfMNgR7Qz0NAeGz/nRqF4m5/6CLzbP4/liHt12Ew==", + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.4.2.tgz", + "integrity": "sha512-e9MewbtFo+Fevyuxn/4rrcDAaq0IYxPGLvObpQjiZBMAzB9IGmzlnG9RZy3FFas+eBMu2vA0CszMeduow5dIuQ==", + "license": "MIT", "bin": { "prettier": "bin/prettier.cjs" }, @@ -727,22 +2693,60 @@ "url": "https://github.com/prettier/prettier?sponsor=1" } }, - "node_modules/prompts": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", - "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==", + "node_modules/proc-log": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-5.0.0.tgz", + "integrity": "sha512-Azwzvl90HaF0aCz1JrDdXQykFakSSNPaPoiZ9fm5qJIMHioDZEi7OAdRwSm6rSoPtY3Qutnm3L7ogmg3dc+wbQ==", + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/proggy": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/proggy/-/proggy-3.0.0.tgz", + "integrity": "sha512-QE8RApCM3IaRRxVzxrjbgNMpQEX6Wu0p0KBeoSiSEw5/bsGwZHsshF4LCxH2jp/r6BU+bqA3LrMDEYNfJnpD8Q==", + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/promise-all-reject-late": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/promise-all-reject-late/-/promise-all-reject-late-1.0.1.tgz", + "integrity": "sha512-vuf0Lf0lOxyQREH7GDIOUMLS7kz+gs8i6B+Yi8dC68a2sychGrHTJYghMBD6k7eUcH0H5P73EckCA48xijWqXw==", + "license": "ISC", + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/promise-call-limit": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/promise-call-limit/-/promise-call-limit-3.0.2.tgz", + "integrity": "sha512-mRPQO2T1QQVw11E7+UdCJu7S61eJVWknzml9sC1heAdj1jxl0fWMBypIt9ZOcLFf8FkG995ZD7RnVk7HH72fZw==", + "license": "ISC", + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/promise-retry": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/promise-retry/-/promise-retry-2.0.1.tgz", + "integrity": "sha512-y+WKFlBR8BGXnsNlIHFGPZmyDf3DFMoLhaflAnyZgV6rG6xu+JwesTo2Q9R6XwYmtmwAFCkAk3e35jEdoeh/3g==", + "license": "MIT", "dependencies": { - "kleur": "^3.0.3", - "sisteransi": "^1.0.5" + "err-code": "^2.0.2", + "retry": "^0.12.0" }, "engines": { - "node": ">= 6" + "node": ">=10" } }, "node_modules/proper-lockfile": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/proper-lockfile/-/proper-lockfile-2.0.1.tgz", "integrity": "sha512-rjaeGbsmhNDcDInmwi4MuI6mRwJu6zq8GjYCLuSuE7GF+4UjgzkL69sVKKJ2T2xH61kK7rXvGYpvaTu909oXaQ==", + "license": "MIT", "dependencies": { "graceful-fs": "^4.1.2", "retry": "^0.10.0" @@ -751,6 +2755,15 @@ "node": ">=4.0.0" } }, + "node_modules/proper-lockfile/node_modules/retry": { + "version": "0.10.1", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.10.1.tgz", + "integrity": "sha512-ZXUSQYTHdl3uS7IuCehYfMzKyIDBNoAuUblvy5oGO5UJSUTmStUUVPXbA9Qxd173Bgre53yCQczQuHgRWAdvJQ==", + "license": "MIT", + "engines": { + "node": "*" + } + }, "node_modules/queue-microtask": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", @@ -768,12 +2781,36 @@ "type": "consulting", "url": "https://feross.org/support" } - ] + ], + "license": "MIT" + }, + "node_modules/read-cmd-shim": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/read-cmd-shim/-/read-cmd-shim-5.0.0.tgz", + "integrity": "sha512-SEbJV7tohp3DAAILbEMPXavBjAnMN0tVnh4+9G8ihV4Pq3HYF9h8QNez9zkJ1ILkv9G2BjdzwctznGZXgu/HGw==", + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/read-package-json-fast": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/read-package-json-fast/-/read-package-json-fast-4.0.0.tgz", + "integrity": "sha512-qpt8EwugBWDw2cgE2W+/3oxC+KTez2uSVR8JU9Q36TXPAGCaozfQUs59v4j4GFpWTaw0i6hAZSvOmu1J0uOEUg==", + "license": "ISC", + "dependencies": { + "json-parse-even-better-errors": "^4.0.0", + "npm-normalize-package-bin": "^4.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } }, "node_modules/require-directory": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "license": "MIT", "engines": { "node": ">=0.10.0" } @@ -782,27 +2819,45 @@ "version": "2.0.2", "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "license": "MIT", "engines": { "node": ">=0.10.0" } }, "node_modules/retry": { - "version": "0.10.1", - "resolved": "https://registry.npmjs.org/retry/-/retry-0.10.1.tgz", - "integrity": "sha512-ZXUSQYTHdl3uS7IuCehYfMzKyIDBNoAuUblvy5oGO5UJSUTmStUUVPXbA9Qxd173Bgre53yCQczQuHgRWAdvJQ==", + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz", + "integrity": "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==", + "license": "MIT", "engines": { - "node": "*" + "node": ">= 4" } }, "node_modules/reusify": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", - "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", + "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", + "license": "MIT", "engines": { "iojs": ">=1.0.0", "node": ">=0.10.0" } }, + "node_modules/rimraf": { + "version": "5.0.10", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-5.0.10.tgz", + "integrity": "sha512-l0OE8wL34P4nJH/H2ffoaniAokM2qSmrtXHmlpvYr5AVVX8msAyW0l8NVJFDxlSK4u3Uh/f41cQheDVdnYijwQ==", + "license": "ISC", + "dependencies": { + "glob": "^10.3.7" + }, + "bin": { + "rimraf": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/run-parallel": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", @@ -821,30 +2876,84 @@ "url": "https://feross.org/support" } ], + "license": "MIT", "dependencies": { "queue-microtask": "^1.2.2" } }, - "node_modules/semver": { - "version": "7.6.3", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", - "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", - "bin": { - "semver": "bin/semver.js" + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.1.tgz", + "integrity": "sha512-hlq8tAfn0m/61p4BVRcPzIGr6LKiMwo4VM6dGi6pt4qcRkmNzTcWq6eCEjEh+qXjkMDvPlOFFSGwQjoEa6gyMA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/sigstore": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/sigstore/-/sigstore-3.1.0.tgz", + "integrity": "sha512-ZpzWAFHIFqyFE56dXqgX/DkDRZdz+rRcjoIk/RQU4IX0wiCv1l8S7ZrXDHcCc+uaf+6o7w3h2l3g6GYG5TKN9Q==", + "license": "Apache-2.0", + "dependencies": { + "@sigstore/bundle": "^3.1.0", + "@sigstore/core": "^2.0.0", + "@sigstore/protobuf-specs": "^0.4.0", + "@sigstore/sign": "^3.1.0", + "@sigstore/tuf": "^3.1.0", + "@sigstore/verify": "^2.1.0" }, "engines": { - "node": ">=10" + "node": "^18.17.0 || >=20.5.0" } }, - "node_modules/sisteransi": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", - "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==" - }, "node_modules/slash": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/slash/-/slash-5.1.0.tgz", "integrity": "sha512-ZA6oR3T/pEyuqwMgAKT0/hAv8oAXckzbkmR0UkUosQ+Mc4RxGoJkRmwHgHufaenlyAgE1Mxgpdcrf75y6XcnDg==", + "license": "MIT", "engines": { "node": ">=14.16" }, @@ -852,10 +2961,117 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/smart-buffer": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", + "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", + "license": "MIT", + "engines": { + "node": ">= 6.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks": { + "version": "2.8.4", + "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.4.tgz", + "integrity": "sha512-D3YaD0aRxR3mEcqnidIs7ReYJFVzWdd6fXJYUM8ixcQcJRGTka/b3saV0KflYhyVJXKhb947GndU35SxYNResQ==", + "license": "MIT", + "dependencies": { + "ip-address": "^9.0.5", + "smart-buffer": "^4.2.0" + }, + "engines": { + "node": ">= 10.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks-proxy-agent": { + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz", + "integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "^4.3.4", + "socks": "^2.8.3" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/spdx-correct": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.2.0.tgz", + "integrity": "sha512-kN9dJbvnySHULIluDHy32WHRUu3Og7B9sbY7tsFLctQkIqnMh3hErYgdMjTYuqmcXX+lK5T1lnUt3G7zNswmZA==", + "license": "Apache-2.0", + "dependencies": { + "spdx-expression-parse": "^3.0.0", + "spdx-license-ids": "^3.0.0" + } + }, + "node_modules/spdx-exceptions": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.5.0.tgz", + "integrity": "sha512-PiU42r+xO4UbUS1buo3LPJkjlO7430Xn5SVAhdpzzsPHsjbYVflnnFdATgabnLude+Cqu25p6N+g2lw/PFsa4w==", + "license": "CC-BY-3.0" + }, + "node_modules/spdx-expression-parse": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz", + "integrity": "sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==", + "license": "MIT", + "dependencies": { + "spdx-exceptions": "^2.1.0", + "spdx-license-ids": "^3.0.0" + } + }, + "node_modules/spdx-license-ids": { + "version": "3.0.21", + "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.21.tgz", + "integrity": "sha512-Bvg/8F5XephndSK3JffaRqdT+gyhfqIPwDHpX80tJrF8QQRYMo8sNMeaZ2Dp5+jhwKnUmIOyFFQfHRkjJm5nXg==", + "license": "CC0-1.0" + }, + "node_modules/sprintf-js": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz", + "integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==", + "license": "BSD-3-Clause" + }, + "node_modules/ssri": { + "version": "12.0.0", + "resolved": "https://registry.npmjs.org/ssri/-/ssri-12.0.0.tgz", + "integrity": "sha512-S7iGNosepx9RadX82oimUkvr0Ct7IjJbEbs4mJcTxst8um95J3sDYU1RBEOvdu6oL1Wek2ODI5i4MAw+dZ6cAQ==", + "license": "ISC", + "dependencies": { + "minipass": "^7.0.3" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, "node_modules/string-width": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", + "license": "MIT", + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/string-width-cjs": { + "name": "string-width", "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", @@ -865,10 +3081,54 @@ "node": ">=8" } }, + "node_modules/string-width-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/string-width-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", "dependencies": { "ansi-regex": "^5.0.1" }, @@ -876,21 +3136,37 @@ "node": ">=8" } }, - "node_modules/supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "node_modules/strip-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/tar": { + "version": "7.4.3", + "resolved": "https://registry.npmjs.org/tar/-/tar-7.4.3.tgz", + "integrity": "sha512-5S7Va8hKfV7W5U6g3aYxXmlPoZVAwUMy9AOKyF2fVuZa2UD3qZjg578OrLRt8PcNN1PleVaL/5/yYATNL0ICUw==", + "license": "ISC", "dependencies": { - "has-flag": "^3.0.0" + "@isaacs/fs-minipass": "^4.0.0", + "chownr": "^3.0.0", + "minipass": "^7.1.2", + "minizlib": "^3.0.1", + "mkdirp": "^3.0.1", + "yallist": "^5.0.0" }, "engines": { - "node": ">=4" + "node": ">=18" } }, "node_modules/temporal-polyfill": { "version": "0.2.5", "resolved": "https://registry.npmjs.org/temporal-polyfill/-/temporal-polyfill-0.2.5.tgz", "integrity": "sha512-ye47xp8Cb0nDguAhrrDS1JT1SzwEV9e26sSsrWzVu+yPZ7LzceEcH0i2gci9jWfOfSCCgM3Qv5nOYShVUUFUXA==", + "license": "MIT", "dependencies": { "temporal-spec": "^0.2.4" } @@ -898,12 +3174,26 @@ "node_modules/temporal-spec": { "version": "0.2.4", "resolved": "https://registry.npmjs.org/temporal-spec/-/temporal-spec-0.2.4.tgz", - "integrity": "sha512-lDMFv4nKQrSjlkHKAlHVqKrBG4DyFfa9F74cmBZ3Iy3ed8yvWnlWSIdi4IKfSqwmazAohBNwiN64qGx4y5Q3IQ==" + "integrity": "sha512-lDMFv4nKQrSjlkHKAlHVqKrBG4DyFfa9F74cmBZ3Iy3ed8yvWnlWSIdi4IKfSqwmazAohBNwiN64qGx4y5Q3IQ==", + "license": "ISC" + }, + "node_modules/tmp": { + "version": "0.0.33", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", + "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", + "license": "MIT", + "dependencies": { + "os-tmpdir": "~1.0.2" + }, + "engines": { + "node": ">=0.6.0" + } }, "node_modules/to-regex-range": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "license": "MIT", "dependencies": { "is-number": "^7.0.0" }, @@ -911,10 +3201,46 @@ "node": ">=8.0" } }, + "node_modules/treeverse": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/treeverse/-/treeverse-3.0.0.tgz", + "integrity": "sha512-gcANaAnd2QDZFmHFEOF4k7uc1J/6a6z3DJMd/QwEyxLoKGiptJRwid582r7QIsFlFMIZ3SnxfS52S4hm2DHkuQ==", + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/tuf-js": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/tuf-js/-/tuf-js-3.0.1.tgz", + "integrity": "sha512-+68OP1ZzSF84rTckf3FA95vJ1Zlx/uaXyiiKyPd1pA4rZNkpEvDAKmsu1xUSmbF/chCRYgZ6UZkDwC7PmzmAyA==", + "license": "MIT", + "dependencies": { + "@tufjs/models": "3.0.1", + "debug": "^4.3.6", + "make-fetch-happen": "^14.0.1" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/type-fest": { + "version": "0.21.3", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", + "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/unicorn-magic": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/unicorn-magic/-/unicorn-magic-0.1.0.tgz", "integrity": "sha512-lRfVq8fE8gz6QMBuDM6a+LO3IAzTi05H6gCVaUpir2E1Rwpo4ZUog45KpNXKC/Mn3Yb9UDuHumeFTo9iV/D9FQ==", + "license": "MIT", "engines": { "node": ">=18" }, @@ -922,10 +3248,60 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/unique-filename": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/unique-filename/-/unique-filename-4.0.0.tgz", + "integrity": "sha512-XSnEewXmQ+veP7xX2dS5Q4yZAvO40cBN2MWkJ7D/6sW4Dg6wYBNwM1Vrnz1FhH5AdeLIlUXRI9e28z1YZi71NQ==", + "license": "ISC", + "dependencies": { + "unique-slug": "^5.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/unique-slug": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/unique-slug/-/unique-slug-5.0.0.tgz", + "integrity": "sha512-9OdaqO5kwqR+1kVgHAhsp5vPNU0hnxRa26rBFNfNgM7M6pNtgzeBn3s/xbyCQL3dcjzOatcef6UUHpB/6MaETg==", + "license": "ISC", + "dependencies": { + "imurmurhash": "^0.1.4" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/validate-npm-package-license": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", + "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==", + "license": "Apache-2.0", + "dependencies": { + "spdx-correct": "^3.0.0", + "spdx-expression-parse": "^3.0.0" + } + }, + "node_modules/validate-npm-package-name": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/validate-npm-package-name/-/validate-npm-package-name-6.0.0.tgz", + "integrity": "sha512-d7KLgL1LD3U3fgnvWEY1cQXoO/q6EQ1BSz48Sa149V/5zVTAbgmZIpyI8TRi6U9/JNyeYLlTKsEMPtLC27RFUg==", + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, "node_modules/vscode-jsonrpc": { "version": "8.2.0", "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-8.2.0.tgz", "integrity": "sha512-C+r0eKJUIfiDIfwJhria30+TYWPtuHJXHtI7J0YlOmKAo7ogxP20T0zxB7HZQIFhIyvoBPwWskjxrvAtfjyZfA==", + "license": "MIT", "engines": { "node": ">=14.0.0" } @@ -934,6 +3310,7 @@ "version": "9.0.1", "resolved": "https://registry.npmjs.org/vscode-languageserver/-/vscode-languageserver-9.0.1.tgz", "integrity": "sha512-woByF3PDpkHFUreUa7Hos7+pUWdeWMXRd26+ZX2A8cFx6v/JPTtd4/uN0/jB6XQHYaOlHbio03NTHCqrgG5n7g==", + "license": "MIT", "dependencies": { "vscode-languageserver-protocol": "3.17.5" }, @@ -945,6 +3322,7 @@ "version": "3.17.5", "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.17.5.tgz", "integrity": "sha512-mb1bvRJN8SVznADSGWM9u/b07H7Ecg0I3OgXDuLdn307rl/J3A9YD6/eYOssqhecL27hK1IPZAsaqh00i/Jljg==", + "license": "MIT", "dependencies": { "vscode-jsonrpc": "8.2.0", "vscode-languageserver-types": "3.17.5" @@ -953,17 +3331,56 @@ "node_modules/vscode-languageserver-textdocument": { "version": "1.0.12", "resolved": "https://registry.npmjs.org/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.12.tgz", - "integrity": "sha512-cxWNPesCnQCcMPeenjKKsOCKQZ/L6Tv19DTRIGuLWe32lyzWhihGVJ/rcckZXJxfdKCFvRLS3fpBIsV/ZGX4zA==" + "integrity": "sha512-cxWNPesCnQCcMPeenjKKsOCKQZ/L6Tv19DTRIGuLWe32lyzWhihGVJ/rcckZXJxfdKCFvRLS3fpBIsV/ZGX4zA==", + "license": "MIT" }, "node_modules/vscode-languageserver-types": { "version": "3.17.5", "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.17.5.tgz", - "integrity": "sha512-Ld1VelNuX9pdF39h2Hgaeb5hEZM2Z3jUrrMgWQAu82jMtZp7p3vJT3BzToKtZI7NgQssZje5o0zryOrhQvzQAg==" + "integrity": "sha512-Ld1VelNuX9pdF39h2Hgaeb5hEZM2Z3jUrrMgWQAu82jMtZp7p3vJT3BzToKtZI7NgQssZje5o0zryOrhQvzQAg==", + "license": "MIT" + }, + "node_modules/walk-up-path": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/walk-up-path/-/walk-up-path-3.0.1.tgz", + "integrity": "sha512-9YlCL/ynK3CTlrSRrDxZvUauLzAswPCrsaCgilqFevUYpeEW0/3ScEjaa3kbW/T0ghhkEr7mv+fpjqn1Y1YuTA==", + "license": "ISC" + }, + "node_modules/which": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/which/-/which-5.0.0.tgz", + "integrity": "sha512-JEdGzHwwkrbWoGOlIHqQ5gtprKGOenpDHpxE9zVR1bWbOtYRyPPHMe9FaP6x61CmNaTThSkb0DAJte5jD+DmzQ==", + "license": "ISC", + "dependencies": { + "isexe": "^3.1.1" + }, + "bin": { + "node-which": "bin/which.js" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } }, "node_modules/wrap-ansi": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs": { + "name": "wrap-ansi", "version": "7.0.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "license": "MIT", "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", @@ -976,48 +3393,124 @@ "url": "https://github.com/chalk/wrap-ansi?sponsor=1" } }, - "node_modules/wrap-ansi/node_modules/ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "node_modules/wrap-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/wrap-ansi-cjs/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", "dependencies": { - "color-convert": "^2.0.1" + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" }, "engines": { "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" + "engines": { + "node": ">=8" } }, - "node_modules/wrap-ansi/node_modules/color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "node_modules/wrap-ansi/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/wrap-ansi/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", "dependencies": { - "color-name": "~1.1.4" + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" }, "engines": { - "node": ">=7.0.0" + "node": ">=8" } }, - "node_modules/wrap-ansi/node_modules/color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + "node_modules/wrap-ansi/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/write-file-atomic": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-6.0.0.tgz", + "integrity": "sha512-GmqrO8WJ1NuzJ2DrziEI2o57jKAVIQNf8a18W3nCYU3H7PNWqCCVTeH6/NQE93CIllIgQS98rrmVkYgTX9fFJQ==", + "license": "ISC", + "dependencies": { + "imurmurhash": "^0.1.4", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } }, "node_modules/y18n": { "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "license": "ISC", "engines": { "node": ">=10" } }, + "node_modules/yallist": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", + "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, "node_modules/yaml": { - "version": "2.5.1", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.5.1.tgz", - "integrity": "sha512-bLQOjaX/ADgQ20isPJRvF0iRUHIxVhYvr53Of7wGcWlO2jvtUlH5m87DsmulFVxRpNLOnI4tB6p/oh8D7kpn9Q==", + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.7.0.tgz", + "integrity": "sha512-+hSoy/QHluxmC9kCIJyL/uyFmLmc+e5CFR5Wa+bpIhIj85LVb9ZH2nVnqrHoSvKogwODv0ClqZkmiSSaIH5LTA==", + "license": "ISC", "bin": { "yaml": "bin.mjs" }, @@ -1029,6 +3522,7 @@ "version": "17.7.2", "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", + "license": "MIT", "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", @@ -1046,9 +3540,63 @@ "version": "21.1.1", "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "license": "ISC", "engines": { "node": ">=12" } + }, + "node_modules/yargs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/yargs/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yoctocolors-cjs": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/yoctocolors-cjs/-/yoctocolors-cjs-2.1.2.tgz", + "integrity": "sha512-cYVsTjKl8b+FrnidjibDWskAv7UKOfcwaVZdp/it9n1s9fU3IkgDbhdIRKCW4JDsAlECJY0ytoVPT3sK6kideA==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } } } } diff --git a/eng/emitter-package.json b/eng/emitter-package.json index db543aee21f5..44d2504ba311 100644 --- a/eng/emitter-package.json +++ b/eng/emitter-package.json @@ -1,20 +1,20 @@ { - "main": "dist/src/index.js", + "name": "dist/src/index.js", "dependencies": { - "@azure-tools/typespec-java": "0.27.2" + "@azure-tools/typespec-java": "0.27.9" }, "devDependencies": { - "@azure-tools/typespec-autorest": "0.50.0", - "@azure-tools/typespec-azure-core": "0.50.0", - "@azure-tools/typespec-azure-resource-manager": "0.50.0", - "@azure-tools/typespec-azure-rulesets": "0.50.0", - "@azure-tools/typespec-client-generator-core": "0.50.0", - "@typespec/compiler": "0.64.0", - "@typespec/http": "0.64.0", - "@typespec/openapi": "0.64.0", - "@typespec/rest": "0.64.0", - "@typespec/versioning": "0.64.0", - "@typespec/xml": "0.64.0", - "@azure-tools/typespec-liftr-base": "0.6.0" + "@azure-tools/typespec-autorest": "0.52.0", + "@azure-tools/typespec-azure-core": "0.52.0", + "@azure-tools/typespec-azure-resource-manager": "0.52.0", + "@azure-tools/typespec-azure-rulesets": "0.52.0", + "@azure-tools/typespec-client-generator-core": "0.52.0", + "@azure-tools/typespec-liftr-base": "0.8.0", + "@typespec/compiler": "0.66.0", + "@typespec/http": "0.66.0", + "@typespec/openapi": "0.66.0", + "@typespec/rest": "0.66.0", + "@typespec/versioning": "0.66.0", + "@typespec/xml": "0.66.0" } -} +} \ No newline at end of file diff --git a/eng/pipelines/partner-release.yml b/eng/pipelines/partner-release.yml index 09054c7cec08..1a33ae4daf52 100644 --- a/eng/pipelines/partner-release.yml +++ b/eng/pipelines/partner-release.yml @@ -33,6 +33,14 @@ extends: - checkout: azure-sdk-build-tools path: azure-sdk-build-tools + - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml + parameters: + SkipCheckoutNone: true + Repositories: + - Name: Azure/azure-sdk-for-java + Commitish: $(Build.SourceVersion) + WorkingDirectory: $(Pipeline.Workspace)/azure-sdk-for-java + - template: /eng/pipelines/templates/steps/download-credscan-suppressions.yml - task: AzurePowerShell@5 @@ -41,18 +49,18 @@ extends: inputs: azureSubscription: 'azuresdkpartnerdrops - Storage Partner Drops' ScriptType: 'InlineScript' - azurePowerShellVersion: LatestVersion + azurePowerShellVersion: LatestVersion pwsh: true Inline: | echo "azcopy copy 'https://azuresdkpartnerdrops.blob.core.windows.net/drops/${{ parameters.BlobPath }}/*' '$(Artifacts)' --recursive=true" azcopy copy 'https://azuresdkpartnerdrops.blob.core.windows.net/drops/${{ parameters.BlobPath }}/*' '$(Artifacts)' --recursive=true $copiedFiles = (dir '$(Artifacts)' -r | % { $_.FullName }) echo "Copied files: $copiedFiles" - if (!$copiedFiles) { + if (!$copiedFiles) { echo "Failed to copy any files from 'https://azuresdkpartnerdrops.blob.core.windows.net/drops/${{ parameters.BlobPath }}/*' please double check they exist" exit 1 } - env: + env: AZCOPY_AUTO_LOGIN_TYPE: 'PSCRED' - template: tools/java-esrp-signing/java-esrp-signing.yml@azure-sdk-build-tools @@ -61,40 +69,55 @@ extends: - template: /eng/common/pipelines/templates/steps/publish-1es-artifact.yml parameters: - ArtifactName: packages-signed ArtifactPath: $(Artifacts) + ArtifactName: packages-signed - - job: Release - dependsOn: Signing - pool: - name: $(WINDOWSPOOL) - image: $(WINDOWSVMIMAGE) - os: windows - steps: - - checkout: self - path: azure-sdk-for-java - - - checkout: azure-sdk-build-tools - path: azure-sdk-build-tools - - - template: /eng/pipelines/templates/steps/download-credscan-suppressions.yml - + # Downloading the ESRP signed artifacts - download: current - displayName: Download Signed Artifacts + displayName: 'Download Signed Artifacts' artifact: packages-signed + # gpg-sign and create the flattened directory for ESRP bulk publish + # Note: The maven release requires the files to be local GPG signed + # Dev feed publishes use the gpg-sign-and-deply to do it in one step - template: tools/gpg/gpg.yml@azure-sdk-build-tools - - - template: /eng/pipelines/templates/steps/java-publishing.yml + - template: /eng/pipelines/templates/steps/gpg-sign-and-flatten.yml parameters: ArtifactDirectory: $(Pipeline.Workspace)/packages-signed - OutputDirectory: $(EsrpArtifacts) - Target: EsrpRelease - JavaRepoRoot: $(Pipeline.Workspace)/azure-sdk-for-java - ShouldPublish: ${{ parameters.ShouldPublish }} - StageOnly: false + OutputDirectory: $(Pipeline.Workspace)/packages-esrp-gpg-signed + FlattenedESRPDirectory: $(Pipeline.Workspace)/packages-esrp-flattened + # The packages-esrp-flattened will be used for the ESRP publish - template: /eng/common/pipelines/templates/steps/publish-1es-artifact.yml parameters: - ArtifactName: packages-esrp-$(System.JobAttempt) - ArtifactPath: $(EsrpArtifacts) + ArtifactPath: '$(Pipeline.Workspace)/packages-esrp-flattened' + ArtifactName: 'packages-esrp-flattened' + + + - deployment: PublishESRPPackage + displayName: "Publish to Maven Central via ESRP" + condition: and(succeeded(), ne(variables['Skip.PublishPackage'], 'true')) + timeoutInMinutes: 60 + environment: none # this is satisfy the 1ES requirement for pipelines that shouldn't need the approval step + dependsOn: Signing + + templateContext: + type: releaseJob + isProduction: true + inputs: + - input: pipelineArtifact + artifactName: 'packages-esrp-flattened' + targetPath: '$(Pipeline.Workspace)/packages-esrp-flattened' + + pool: + name: azsdk-pool-mms-win-2022-general + image: azsdk-pool-mms-win-2022-1espt + os: windows + strategy: + runOnce: + deploy: + steps: + - template: /eng/pipelines/templates/steps/java-esrp-publishing.yml + parameters: + FlattenedDirectory: $(Pipeline.Workspace)/packages-esrp-flattened + ShouldPublish: ${{ parameters.ShouldPublish }} diff --git a/eng/pipelines/patch-release.yml b/eng/pipelines/patch-release.yml index d9559a5bd310..1cff7999a982 100644 --- a/eng/pipelines/patch-release.yml +++ b/eng/pipelines/patch-release.yml @@ -7,13 +7,16 @@ extends: - name: azure-sdk-template groupId: com.azure safeName: azuresdktemplate + skipPublishDocMs: true ServiceDirectory: template - name: azure-sdk-template-two groupId: com.azure safeName: azuresdktemplatetwo + skipPublishDocMs: true ServiceDirectory: template - name: azure-sdk-template-three groupId: com.azure safeName: azuresdktemplatethree + skipPublishDocMs: true ServiceDirectory: template diff --git a/eng/pipelines/patch_release_client.txt b/eng/pipelines/patch_release_client.txt index fd0e82a9752c..a4560961a0d4 100644 --- a/eng/pipelines/patch_release_client.txt +++ b/eng/pipelines/patch_release_client.txt @@ -20,9 +20,12 @@ # performance regressions or bugs. They are also responsible for smoke testing their library after every release. com.azure:azure-ai-contentsafety # Tests owner: zhaiyutong +com.azure:azure-ai-documentintelligence # Tests owner: samvaity com.azure:azure-ai-metricsadvisor # Tests owner: samvaity com.azure:azure-ai-textanalytics # Tests owner: mssfang +com.azure:azure-ai-translation-document # Tests owner: sg-ms com.azure:azure-ai-translation-text # Tests owner: MikeyMCZ +com.azure:azure-ai-vision-imageanalysis # Tests owner: dargilco com.azure:azure-communication-callautomation # Tests owner: minwoolee-msft, juntuchen-msft com.azure:azure-communication-chat # Tests owner: jiminwen com.azure:azure-communication-common # Tests owner: AikoBB, maximrytych-ms, mjafferi-msft @@ -37,10 +40,12 @@ com.azure:azure-containers-containerregistry # Tests owner: lmolkova com.azure:azure-data-appconfiguration # Tests owner: mssfang com.azure:azure-data-schemaregistry # Tests owner: conniey com.azure:azure-data-schemaregistry-apacheavro # Tests owner: conniey +com.azure:azure-data-schemaregistry-jsonschema # Tests owner: conniey com.azure:azure-data-tables # Tests owner: jairmyree com.azure:azure-developer-devcenter # Tests owner: drielenr, leti367 com.azure:azure-developer-loadtesting # Tests owner: Harshan01, prativen com.azure:azure-digitaltwins-core # Tests owner: sjiherzig +com.azure:azure-health-insights-radiologyinsights # Tests owner: tomsft, koen-mertens com.azure:azure-identity-broker # Tests owner: billwert, vigera com.azure:azure-identity-extensions # Tests owner: saragluna, backwind1233 com.azure:azure-iot-deviceupdate # Tests owner: leolie, ryzhan diff --git a/eng/pipelines/pullrequest.yml b/eng/pipelines/pullrequest.yml new file mode 100644 index 000000000000..f22f1bbdca34 --- /dev/null +++ b/eng/pipelines/pullrequest.yml @@ -0,0 +1,100 @@ +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + - restapi* + - pipelinev3* + paths: + include: + - "*" + # Note: The ExcludePaths template below needs to duplicate + # any excludes here. The reason being is that we can't access + # pr->paths->exclude. Path matching is done with startsWith + # meaning that path entries should end with a trailing "/" in + # order to prevent greedy matching. Centralized versioning files + # are added to this list to prevent the PR pipeline from running + # when it shouldn't. When someone updates these files there will + # be other updates that'll cause the PR pipeline, or the appropriate + # pipeline if not PR, to run. + exclude: + - eng/versioning/external_dependencies.txt + - eng/versioning/version_client.txt + - eng/versioning/version_data.txt + - eng/versioning/version_data_java_files.txt + - sdk/batch/microsoft-azure-batch/ # track 1 + - sdk/boms/ # pom only release pipeline + - sdk/cosmos/ # emulator tests + - sdk/e2e/ # no pipeline, nothing to build + - sdk/cognitiveservices/ms-azure-cs-autosuggest/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-computervision/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-contentmoderator/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-customimagesearch/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-customsearch/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-customvision-prediction/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-customvision-training/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-entitysearch/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-faceapi/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-imagesearch/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-luis-authoring/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-luis-runtime/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-newssearch/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-qnamaker/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-spellcheck/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-videosearch/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-visualsearch/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-websearch/ # track 1 + - sdk/eventhubs/microsoft-azure-eventhubs/ # track 1 + - sdk/eventhubs/microsoft-azure-eventhubs-eph/ # track 1 + - sdk/mediaservices/microsoft-azure-media/ # track 1 + - sdk/servicebus/microsoft-azure-servicebus/ # track 1 + - sdk/spring/ + +parameters: + - name: Service + type: string + default: auto + +extends: + template: /eng/pipelines/templates/stages/archetype-sdk-client.yml + parameters: + ServiceDirectory: ${{ parameters.Service }} + # This is Necessary since FromSource runs hover around 60, + # which is the default, and intermittently time out. + TimeoutInMinutes: 90 + # See pr->paths->exclude comment above. Anything added/removed there + # needs to be added/removed here. + ExcludePaths: + - eng/versioning/external_dependencies.txt + - eng/versioning/version_client.txt + - eng/versioning/version_data.txt + - eng/versioning/version_data_java_files.txt + - sdk/batch/microsoft-azure-batch/ # track 1 + - sdk/boms/ # pom only release pipeline + - sdk/cosmos/ # emulator tests + - sdk/e2e/ # no pipeline, nothing to build + - sdk/cognitiveservices/ms-azure-cs-autosuggest/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-computervision/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-contentmoderator/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-customimagesearch/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-customsearch/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-customvision-prediction/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-customvision-training/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-entitysearch/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-faceapi/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-imagesearch/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-luis-authoring/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-luis-runtime/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-newssearch/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-qnamaker/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-spellcheck/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-videosearch/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-visualsearch/ # track 1 + - sdk/cognitiveservices/ms-azure-cs-websearch/ # track 1 + - sdk/eventhubs/microsoft-azure-eventhubs/ # track 1 + - sdk/eventhubs/microsoft-azure-eventhubs-eph/ # track 1 + - sdk/mediaservices/microsoft-azure-media/ # track 1 + - sdk/servicebus/microsoft-azure-servicebus/ # track 1 + - sdk/spring/ diff --git a/eng/pipelines/scripts/Get-Linting-Commands.ps1 b/eng/pipelines/scripts/Get-Linting-Commands.ps1 index f30a86a40d6b..664167995c8b 100644 --- a/eng/pipelines/scripts/Get-Linting-Commands.ps1 +++ b/eng/pipelines/scripts/Get-Linting-Commands.ps1 @@ -56,7 +56,12 @@ if ($BuildReason -ne "PullRequest") { } $diffFiles = (git diff $TargetBranch $SourceBranch --name-only --relative) -if ($diffFiles -contains 'eng/code-quality-reports/ci.yml') { +# Run all linting steps if any of the shared CI configuration files changed. +$runAll = $diffFiles -contains 'eng/code-quality-reports/ci.yml' ` + -or $diffFiles -contains 'eng/pipelines/code-quality-reports.yml' ` + -or $diffFiles -contains 'eng/pipelines/scripts/Get-Linting-Commands.ps1' ` + -or $diffFiles -contains 'eng/pipelines/scripts/Get-Linting-Reports.ps1' +if ($runAll) { Write-Host "PR changed the CI configuration, running all linting steps." Write-Host "##vso[task.setvariable variable=${LintingPipelineVariable};]-Dcheckstyle.failOnViolation=false -Dcheckstyle.failsOnError=false -Dspotbugs.failOnError=false -Drevapi.failBuildOnProblemsFound=false" Write-Host "##vso[task.setvariable variable=RunLinting;]true" diff --git a/eng/pipelines/scripts/generate-project-list.ps1 b/eng/pipelines/scripts/generate-project-list.ps1 index 836763022c2f..a4432a8b3977 100644 --- a/eng/pipelines/scripts/generate-project-list.ps1 +++ b/eng/pipelines/scripts/generate-project-list.ps1 @@ -2,6 +2,8 @@ $projectList = @() $artifactsList = @() $additionalModulesList = @() +. "${PSScriptRoot}/../../common/scripts/common.ps1" + if ($env:ARTIFACTSJSON -and $env:ARTIFACTSJSON -notlike '*ArtifactsJson*') { $artifacts = $env:ARTIFACTSJSON | ConvertFrom-Json foreach ($artifact in $artifacts) { @@ -23,7 +25,30 @@ if ($env:ADDITIONALMODULESJSON -and $env:ADDITIONALMODULESJSON -notlike '*Additi # which means this is running as part of the pullrequest pipeline and the project list needs to # be figured out from the packageInfo files. if ($projectList.Length -eq 0 -and $ENV:PACKAGEINFODIR) { - [array]$packageInfoFiles = Get-ChildItem -Path $ENV:PACKAGEINFODIR "*.json" + $packageInfoFiles = @() + # This is the case where this is being called as part of the set of test matrix runs. + # The ArtifactPackageNames environment variable will be set if this is being called + # as one of the test matrix runs. In this case, the project and additional modules lists + # need to be filtered by the ArtifactPackageNames otherwise there will be artifacts on + # the maven command line, for a matrix, that don't belong to the matrx if the PR has + # changes to multiple libraries that have different test matrices. + if (-not [string]::IsNullOrEmpty($ENV:ARTIFACTPACKAGENAMES)) { + Write-Host "ArtifactPackageNames is set to: $($ENV:ARTIFACTPACKAGENAMES)" + # The ArtifactPackageNames is a comma separated list + foreach ($artifactPackageName in $ENV:ARTIFACTPACKAGENAMES.Split(',')) { + # There should only be 1 PackageInfo file for each ArtifactPackageName. + # Also, this is doing a Get-ChildItem without -Recurse, meaning it's not digging into + # subdirectories and it's literally impossible to have the exact same file twice in one directory. + [array]$pkgInfoFiles = Get-ChildItem -Path $ENV:PACKAGEINFODIR "$($artifactPackageName).json" + if ($pkgInfoFiles) { + $packageInfoFiles += $pkgInfoFiles + } else { + LogError "No PackageInfo file found for $artifactPackageName" + } + } + } else { + $packageInfoFiles = Get-ChildItem -Path $ENV:PACKAGEINFODIR "*.json" + } foreach($packageInfoFile in $packageInfoFiles) { $packageInfoJson = Get-Content $packageInfoFile -Raw $packageInfo = ConvertFrom-Json $packageInfoJson diff --git a/eng/pipelines/templates/jobs/ci.tests.yml b/eng/pipelines/templates/jobs/ci.tests.yml index 181e7543f2e5..6195ff3979ac 100644 --- a/eng/pipelines/templates/jobs/ci.tests.yml +++ b/eng/pipelines/templates/jobs/ci.tests.yml @@ -5,6 +5,9 @@ parameters: - name: ServiceDirectory type: string default: 'not-specified' # Set a default that breaks in obvious ways. + - name: ExcludePaths + type: object + default: [] - name: TestPipeline type: boolean default: false @@ -104,6 +107,8 @@ jobs: - template: /eng/pipelines/templates/steps/initialize-test-environment.yml parameters: CheckoutRecordings: true + ServiceDirectory: ${{parameters.ServiceDirectory}} + ExcludePaths: ${{parameters.ExcludePaths}} - template: /eng/common/testproxy/test-proxy-tool.yml parameters: diff --git a/eng/pipelines/templates/jobs/ci.yml b/eng/pipelines/templates/jobs/ci.yml index b3944bc6583f..e5076c76a7aa 100644 --- a/eng/pipelines/templates/jobs/ci.yml +++ b/eng/pipelines/templates/jobs/ci.yml @@ -95,18 +95,11 @@ jobs: - '!sdk/**/test-recordings' - '!sdk/**/session-records' - # This is the case for the PullReqest pipeline which has a ServiceDirectory of 'auto'. - # For the PullRequest pipeline, the packageInfo files generated from the diff end up - # being the source of truth for the artifacts list. - - ${{ if and(eq(variables['Build.Reason'], 'PullRequest'), eq(parameters.ServiceDirectory, 'auto')) }}: - - template: /eng/common/pipelines/templates/steps/save-package-properties.yml - parameters: - ServiceDirectory: ${{parameters.ServiceDirectory}} - ExcludePaths: ${{parameters.ExcludePaths}} - - template: /eng/pipelines/templates/steps/generate-project-list-and-cache-maven-repository.yml parameters: JobType: 'Build' + ServiceDirectory: ${{parameters.ServiceDirectory}} + ExcludePaths: ${{parameters.ExcludePaths}} - task: UsePythonVersion@0 displayName: 'Use Python $(PythonVersion)' @@ -203,8 +196,11 @@ jobs: arguments: > -BuildOutputDirectory $(System.DefaultWorkingDirectory)/build -ArtifactsList ('$(ArtifactsJson)' | ConvertFrom-Json | Select-Object name, groupId) + -PackageInfoDir $(Build.ArtifactStagingDirectory)/PackageInfo -InformationAction Continue + # This only copies the ReleaseArtifacts but for the PR pipeline just copy + # all of the built artifacts. - task: PowerShell@2 displayName: 'Copy artifacts to staging' inputs: @@ -215,6 +211,7 @@ jobs: -SourceDirectory $(System.DefaultWorkingDirectory)/build -TargetDirectory $(Build.ArtifactStagingDirectory) -Artifacts ('${{ replace(convertToJson(parameters.ReleaseArtifacts), '''', '`''') }}' | ConvertFrom-Json | Where-Object -Not skipPublishPackage ) + -PackageInfoDir $(Build.ArtifactStagingDirectory)/PackageInfo -InformationAction Continue - task: Powershell@2 @@ -303,6 +300,8 @@ jobs: - template: /eng/pipelines/templates/steps/generate-project-list-and-cache-maven-repository.yml parameters: JobType: 'Analyze' + ServiceDirectory: ${{parameters.ServiceDirectory}} + ExcludePaths: ${{parameters.ExcludePaths}} - task: PowerShell@2 displayName: Generate directories variable for sparse checkout @@ -332,9 +331,14 @@ jobs: ServiceDirectory: "template" TestPipeline: ${{ parameters.TestPipeline }} - - template: /eng/common/pipelines/templates/steps/verify-readme.yml - parameters: - ScanPath: $(Build.SourcesDirectory)/sdk/${{ parameters.ServiceDirectory }} + - ${{ if and(eq(variables['Build.Reason'], 'PullRequest'), eq(parameters.ServiceDirectory, 'auto')) }}: + - template: /eng/common/pipelines/templates/steps/verify-readmes.yml + parameters: + PackagePropertiesFolder: $(Build.ArtifactStagingDirectory)/PackageInfo + - ${{ else }}: + - template: /eng/common/pipelines/templates/steps/verify-readme.yml + parameters: + ScanPath: $(Build.SourcesDirectory)/sdk/${{ parameters.ServiceDirectory }} - template: /eng/common/pipelines/templates/steps/verify-links.yml parameters: @@ -345,9 +349,24 @@ jobs: Directory: sdk/${{ parameters.ServiceDirectory }} CheckLinkGuidance: $true - - template: /eng/common/pipelines/templates/steps/verify-samples.yml - parameters: - ServiceDirectory: ${{ parameters.ServiceDirectory }} + - ${{ if and(eq(variables['Build.Reason'], 'PullRequest'), eq(parameters.ServiceDirectory, 'auto')) }}: + - pwsh: | + $diffJson = Get-Content '$(Build.ArtifactStagingDirectory)/diff/diff.json' -Raw + $diff = ConvertFrom-Json $diffJson + $changedServicesString = '' + if ($diff.ChangedServices) { + $changedServicesString = $diff.ChangedServices -join "," + } + Write-Host "changedServicesString='$changedServicesString'" + Write-Host "##vso[task.setvariable variable=SamplesServiceDirectories;]$changedServicesString" + displayName: Get samples service directories from PR diff + - template: /eng/common/pipelines/templates/steps/verify-samples.yml + parameters: + ServiceDirectories: $(SamplesServiceDirectories) + - ${{ else }}: + - template: /eng/common/pipelines/templates/steps/verify-samples.yml + parameters: + ServiceDirectory: ${{ parameters.ServiceDirectory }} # Use BasePathLength of 38 instead of the default 49 as some released files fail when the number is higher. - template: /eng/common/pipelines/templates/steps/verify-path-length.yml @@ -356,13 +375,18 @@ jobs: BasePathLength: 38 - ${{if ne(parameters.SDKType, 'data')}}: - - ${{ each artifact in parameters.Artifacts }}: - - ${{if ne(artifact.skipVerifyChangelog, 'true')}}: - - template: /eng/common/pipelines/templates/steps/verify-changelog.yml - parameters: - PackageName: ${{artifact.name}} - ServiceName: ${{parameters.ServiceDirectory}} - ForRelease: false + - ${{ if and(eq(variables['Build.Reason'], 'PullRequest'), eq(parameters.ServiceDirectory, 'auto')) }}: + - template: /eng/common/pipelines/templates/steps/verify-changelogs.yml + parameters: + PackagePropertiesFolder: $(Build.ArtifactStagingDirectory)/PackageInfo + - ${{ else }}: + - ${{ each artifact in parameters.Artifacts }}: + - ${{if ne(artifact.skipVerifyChangelog, 'true')}}: + - template: /eng/common/pipelines/templates/steps/verify-changelog.yml + parameters: + PackageName: ${{artifact.name}} + ServiceName: ${{parameters.ServiceDirectory}} + ForRelease: false # We `install` the code quality reports tooling into our local m2 cache separately from building the Maven project # reports. This means it is available as part of that, but also so that this is not documented in the project report. @@ -422,7 +446,29 @@ jobs: OsVmImage: $(LINUXVMIMAGE) Pool: $(LINUXPOOL) Os: linux - MatrixConfigs: ${{ parameters.MatrixConfigs }} + MatrixConfigs: + - ${{ each config in parameters.MatrixConfigs }}: + - ${{ config }} + - ${{ each config in parameters.AdditionalMatrixConfigs }}: + - ${{ config }} + ${{ if eq(parameters.ServiceDirectory, 'auto') }}: + EnablePRGeneration: true + # We want full matrix for indirect packages + PRMatrixSparseIndirect: false + SparseCheckoutPaths: + - '**/*.xml' + - '**/*.md' + - '**/ci*.yml' # necessary for save-package-properties.yml + - "**/*matrix*.json" # necessary for test matrix generation + PreGenerationSteps: + - task: UsePythonVersion@0 + displayName: 'Use Python $(PythonVersion)' + inputs: + versionSpec: $(PythonVersion) + - template: /eng/common/pipelines/templates/steps/save-package-properties.yml + parameters: + ServiceDirectory: ${{parameters.ServiceDirectory}} + ExcludePaths: ${{parameters.ExcludePaths}} MatrixFilters: ${{ parameters.MatrixFilters }} MatrixReplace: ${{ parameters.MatrixReplace }} CloudConfig: @@ -430,6 +476,7 @@ jobs: AdditionalParameters: SDKType: ${{ parameters.SDKType }} ServiceDirectory: ${{ parameters.ServiceDirectory }} + ExcludePaths: ${{ parameters.ExcludePaths }} TestPipeline: ${{ parameters.TestPipeline }} PreTestSteps: ${{ parameters.PreTestSteps }} PreBuildSteps: ${{ parameters.PreBuildSteps }} diff --git a/eng/pipelines/templates/stages/1es-redirect.yml b/eng/pipelines/templates/stages/1es-redirect.yml index 972f3068c32c..fc5a08654b31 100644 --- a/eng/pipelines/templates/stages/1es-redirect.yml +++ b/eng/pipelines/templates/stages/1es-redirect.yml @@ -11,7 +11,7 @@ resources: - repository: azure-sdk-build-tools type: git name: internal/azure-sdk-build-tools - ref: refs/tags/azure-sdk-build-tools_20241126.1 + ref: refs/tags/azure-sdk-build-tools_20250228.1 parameters: - name: stages diff --git a/eng/pipelines/templates/stages/archetype-java-release-batch.yml b/eng/pipelines/templates/stages/archetype-java-release-batch.yml index aed82338ac51..7e30c86a1b64 100644 --- a/eng/pipelines/templates/stages/archetype-java-release-batch.yml +++ b/eng/pipelines/templates/stages/archetype-java-release-batch.yml @@ -31,36 +31,63 @@ stages: - stage: Signing dependsOn: ${{parameters.DependsOn}} jobs: - - deployment: SignPackage - environment: esrp + - job: SignPackage timeoutInMinutes: 20 variables: - template: /eng/pipelines/templates/variables/globals.yml - template: /eng/pipelines/templates/variables/image.yml pool: - name: azsdk-pool-mms-ubuntu-2004-general - image: azsdk-pool-mms-ubuntu-2004-1espt - os: linux - strategy: - runOnce: - deploy: - steps: - - checkout: none - - template: /eng/pipelines/templates/steps/download-credscan-suppressions.yml - - - download: current - displayName: 'Download Artifact: ${{parameters.ArtifactName}}' - artifact: ${{parameters.ArtifactName}} - - - template: tools/java-esrp-signing/java-esrp-signing.yml@azure-sdk-build-tools - parameters: - Artifacts: ${{parameters.Artifacts}} - ArtifactDirectory: $(Pipeline.Workspace)/${{parameters.ArtifactName}} + name: azsdk-pool-mms-win-2022-general + image: azsdk-pool-mms-win-2022-1espt + os: windows + steps: + - checkout: azure-sdk-build-tools + path: azure-sdk-build-tools + - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml + parameters: + SkipCheckoutNone: true + Repositories: + - Name: Azure/azure-sdk-for-java + Commitish: $(Build.SourceVersion) + WorkingDirectory: $(Pipeline.Workspace)/azure-sdk-for-java + - template: /eng/pipelines/templates/steps/download-credscan-suppressions.yml - - template: /eng/common/pipelines/templates/steps/publish-1es-artifact.yml - parameters: - ArtifactPath: '$(Pipeline.Workspace)/${{parameters.ArtifactName}}' - ArtifactName: '${{parameters.ArtifactName}}-signed' + - download: current + displayName: 'Download Artifact: ${{parameters.ArtifactName}}' + artifact: ${{parameters.ArtifactName}} + + - template: tools/java-esrp-signing/java-esrp-signing.yml@azure-sdk-build-tools + parameters: + Artifacts: ${{parameters.Artifacts}} + ArtifactDirectory: $(Pipeline.Workspace)/${{parameters.ArtifactName}} + + # Publish the ESRP signed directory. This will still be used by the + # Dev feed publish. + - template: /eng/common/pipelines/templates/steps/publish-1es-artifact.yml + parameters: + ArtifactPath: '$(Pipeline.Workspace)/${{parameters.ArtifactName}}' + ArtifactName: '${{parameters.ArtifactName}}-signed' + + # Downloading the ESRP signed artifacts + - download: current + displayName: 'Download Signed Artifacts' + artifact: ${{parameters.ArtifactName}}-signed + + # gpg-sign and create the flattened directory for ESRP bulk publish + # Note: The maven release requires the files to be local GPG signed + # Dev feed publishes use the gpg-sign-and-deply to do it in one step + - template: tools/gpg/gpg.yml@azure-sdk-build-tools + - template: /eng/pipelines/templates/steps/gpg-sign-and-flatten.yml + parameters: + ArtifactDirectory: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed + OutputDirectory: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-esrp-gpg-signed + FlattenedESRPDirectory: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-esrp-flattened + + # The packages-esrp-flattened will be used for the ESRP publish + - template: /eng/common/pipelines/templates/steps/publish-1es-artifact.yml + parameters: + ArtifactPath: '$(Pipeline.Workspace)/${{parameters.ArtifactName}}-esrp-flattened' + ArtifactName: '${{parameters.ArtifactName}}-esrp-flattened' # We generate two interdependent stages for each artifact listed in the ci.yml file, creates the release # in GitHub. The Release stage publishes to Maven Central. Both stages require approval since they @@ -158,40 +185,45 @@ stages: -ServiceDirectory $(Build.SourcesDirectory)/sdk/${{parameters.ServiceDirectory}} -ArtifactsList ('$(ArtifactsJson)' | ConvertFrom-Json | Select-Object name, groupId, uberJar) - - deployment: TagRepository + - job: TagRepository displayName: "Create release tag" condition: and(succeeded(), ne(variables['Skip.TagRepository'], 'true')) - environment: ${{ parameters.Environment }} dependsOn: VerifyReleaseVersion pool: name: azsdk-pool-mms-win-2022-general image: azsdk-pool-mms-win-2022-1espt os: windows - strategy: - runOnce: - deploy: - steps: - - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml - - template: /eng/common/pipelines/templates/steps/retain-run.yml - # No pattern, just download everything that's been signed - - download: current - displayName: 'Download Artifact: ${{parameters.ArtifactName}}-signed' - artifact: ${{parameters.ArtifactName}}-signed - - ${{ each artifact in parameters.Artifacts }}: - - template: /eng/common/pipelines/templates/steps/create-tags-and-git-release.yml - parameters: - ArtifactLocation: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed/${{artifact.groupId}}/${{artifact.name}} - PackageRepository: Maven - ReleaseSha: $(Build.SourceVersion) - - - deployment: PublishPackage - displayName: "Publish to Maven Central" + steps: + - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml + - template: /eng/common/pipelines/templates/steps/retain-run.yml + # No pattern, just download everything that's been signed + - download: current + displayName: 'Download Artifact: ${{parameters.ArtifactName}}-signed' + artifact: ${{parameters.ArtifactName}}-signed + - ${{ each artifact in parameters.Artifacts }}: + - template: /eng/common/pipelines/templates/steps/create-tags-and-git-release.yml + parameters: + ArtifactLocation: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed/${{artifact.groupId}}/${{artifact.name}} + PackageRepository: Maven + ReleaseSha: $(Build.SourceVersion) + + - deployment: PublishESRPPackage + displayName: "Publish to Maven Central via ESRP" condition: and(succeeded(), ne(variables['Skip.PublishPackage'], 'true')) # This timeout shouldn't be necessary once we're able to parallelize better. Right now, # this is here to ensure larger areas (30+) libraries don't time out. timeoutInMinutes: 120 environment: ${{ parameters.Environment }} dependsOn: TagRepository + + templateContext: + type: releaseJob + isProduction: true + inputs: + - input: pipelineArtifact + artifactName: '${{parameters.ArtifactName}}-esrp-flattened' + targetPath: '$(Pipeline.Workspace)/${{parameters.ArtifactName}}-esrp-flattened' + pool: name: azsdk-pool-mms-win-2022-general image: azsdk-pool-mms-win-2022-1espt @@ -200,177 +232,169 @@ stages: runOnce: deploy: steps: - - checkout: azure-sdk-build-tools - path: azure-sdk-build-tools - - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml - parameters: - SkipCheckoutNone: true - Repositories: - - Name: Azure/azure-sdk-for-java - Commitish: $(Build.SourceVersion) - WorkingDirectory: $(Pipeline.Workspace)/azure-sdk-for-java - - template: /eng/pipelines/templates/steps/download-credscan-suppressions.yml - - download: current - displayName: 'Download Artifacts' - artifact: ${{parameters.ArtifactName}}-signed - - template: tools/gpg/gpg.yml@azure-sdk-build-tools - - template: /eng/pipelines/templates/steps/java-publishing.yml - parameters: - ArtifactDirectory: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed - OutputDirectory: $(Pipeline.Workspace)/EsrpPackages - Target: EsrpRelease - JavaRepoRoot: $(Pipeline.Workspace)/azure-sdk-for-java - - template: /eng/common/pipelines/templates/steps/publish-1es-artifact.yml + - template: /eng/pipelines/templates/steps/java-esrp-publishing.yml parameters: - ArtifactName: ${{parameters.ArtifactName}}-esrp-$(System.JobAttempt) - ArtifactPath: $(Pipeline.Workspace)/EsrpPackages - # After publishing to Maven, publish to the azure-sdk-for-java feed. The reason for - # this is that the azure-sdk-for-java feed will have the package available immediately - # whereas Maven can take several hours for the package to become available. - - template: /eng/pipelines/templates/steps/java-publishing.yml - parameters: - ArtifactDirectory: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed - RepositoryUrl: https://pkgs.dev.azure.com/azure-sdk/public/_packaging/azure-sdk-for-java/maven/v1 - Target: JavaDevFeed - JavaRepoRoot: $(Pipeline.Workspace)/azure-sdk-for-java - - template: /eng/common/pipelines/templates/steps/publish-1es-artifact.yml - parameters: - ArtifactName: ${{parameters.ArtifactName}}-javadevfeed-$(System.JobAttempt) - ArtifactPath: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed - - template: /eng/common/pipelines/templates/steps/create-apireview.yml - parameters: - ArtifactPath: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed - Artifacts: ${{parameters.Artifacts}} - ConfigFileDir: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed/PackageInfo - MarkPackageAsShipped: true - ArtifactName: ${{parameters.ArtifactName}}-signed - SourceRootPath: $(Pipeline.Workspace)/azure-sdk-for-java - - - deployment: UpdatePackageVersion + FlattenedDirectory: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-esrp-flattened + + - job: PublishDevFeedPackage + displayName: "Publish to Java Dev feed" + condition: and(succeeded(), ne(variables['Skip.PublishPackage'], 'true')) + # This timeout shouldn't be necessary once we're able to parallelize better. Right now, + # this is here to ensure larger areas (30+) libraries don't time out. + timeoutInMinutes: 120 + dependsOn: PublishESRPPackage + pool: + name: azsdk-pool-mms-win-2022-general + image: azsdk-pool-mms-win-2022-1espt + os: windows + steps: + - checkout: azure-sdk-build-tools + path: azure-sdk-build-tools + - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml + parameters: + SkipCheckoutNone: true + Repositories: + - Name: Azure/azure-sdk-for-java + Commitish: $(Build.SourceVersion) + WorkingDirectory: $(Pipeline.Workspace)/azure-sdk-for-java + - template: /eng/pipelines/templates/steps/download-credscan-suppressions.yml + - download: current + displayName: 'Download Artifacts' + artifact: ${{parameters.ArtifactName}}-signed + - template: tools/gpg/gpg.yml@azure-sdk-build-tools + # Publish to the azure-sdk-for-java feed. + - template: /eng/pipelines/templates/steps/java-dev-feed-publishing.yml + parameters: + ArtifactDirectory: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed + RepositoryUrl: https://pkgs.dev.azure.com/azure-sdk/public/_packaging/azure-sdk-for-java/maven/v1 + Target: JavaDevFeed + JavaRepoRoot: $(Pipeline.Workspace)/azure-sdk-for-java + - template: /eng/common/pipelines/templates/steps/publish-1es-artifact.yml + parameters: + ArtifactName: ${{parameters.ArtifactName}}-javadevfeed-$(System.JobAttempt) + ArtifactPath: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed + - template: /eng/common/pipelines/templates/steps/create-apireview.yml + parameters: + ArtifactPath: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed + Artifacts: ${{parameters.Artifacts}} + ConfigFileDir: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed/PackageInfo + MarkPackageAsShipped: true + ArtifactName: ${{parameters.ArtifactName}}-signed + SourceRootPath: $(Pipeline.Workspace)/azure-sdk-for-java + + - job: UpdatePackageVersion displayName: "Update Package Version" condition: and(succeeded(), ne(variables['Skip.UpdatePackageVersion'], 'true')) - environment: ${{ parameters.Environment }} - dependsOn: PublishPackage + dependsOn: PublishESRPPackage pool: name: azsdk-pool-mms-win-2022-general image: azsdk-pool-mms-win-2022-1espt os: windows - strategy: - runOnce: - deploy: - steps: - - download: none + steps: + - download: none - - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml - parameters: - Paths: - - '${{ parameters.ServiceDirectory }}' - - '**/*.xml' - - '**/*.md' - - '!sdk/**/test-recordings' - - '!sdk/**/session-records' - - - task: UsePythonVersion@0 - displayName: 'Use Python $(PythonVersion)' - inputs: - versionSpec: $(PythonVersion) - - # Apply the version increment to each library, which only updates the version_client.txt file, - # and then call to update_versions will then apply all the updates. - - pwsh: | - $ArtifactsList = $('$(ArtifactsJson)' | ConvertFrom-Json | Select-Object name, groupId) - $ArtifactsList | Format-Table -Property GroupId, Name | Out-String | Write-Host - python --version - foreach($artifact in $ArtifactsList) { - python eng/versioning/set_versions.py --build-type ${{ parameters.SDKType }} --increment-version --ai $($artifact.name) --gi $($artifact.groupId) - } - displayName: Increment package versions - - - script: | - python --version - python eng/versioning/update_versions.py --update-type library --build-type ${{ parameters.SDKType }} --avi --sr - displayName: Update pom files for incremented versions - - - template: /eng/common/pipelines/templates/steps/create-pull-request.yml - parameters: - PRBranchName: increment-package-version-${{ parameters.ServiceDirectory }}-$(Build.BuildId) - CommitMsg: "Increment package versions for ${{ parameters.ServiceDirectory }} releases" - PRTitle: "Increment versions for ${{ parameters.ServiceDirectory }} releases" - CloseAfterOpenForTesting: '${{ parameters.TestPipeline }}' + - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml + parameters: + Paths: + - '${{ parameters.ServiceDirectory }}' + - '**/*.xml' + - '**/*.md' + - '!sdk/**/test-recordings' + - '!sdk/**/session-records' + + - task: UsePythonVersion@0 + displayName: 'Use Python $(PythonVersion)' + inputs: + versionSpec: $(PythonVersion) + + # Apply the version increment to each library, which only updates the version_client.txt file, + # and then call to update_versions will then apply all the updates. + - pwsh: | + $ArtifactsList = $('$(ArtifactsJson)' | ConvertFrom-Json | Select-Object name, groupId) + $ArtifactsList | Format-Table -Property GroupId, Name | Out-String | Write-Host + python --version + foreach($artifact in $ArtifactsList) { + python eng/versioning/set_versions.py --build-type ${{ parameters.SDKType }} --increment-version --ai $($artifact.name) --gi $($artifact.groupId) + } + displayName: Increment package versions + + - script: | + python --version + python eng/versioning/update_versions.py --update-type library --build-type ${{ parameters.SDKType }} --avi --sr + displayName: Update pom files for incremented versions + + - template: /eng/common/pipelines/templates/steps/create-pull-request.yml + parameters: + PRBranchName: increment-package-version-${{ parameters.ServiceDirectory }}-$(Build.BuildId) + CommitMsg: "Increment package versions for ${{ parameters.ServiceDirectory }} releases" + PRTitle: "Increment versions for ${{ parameters.ServiceDirectory }} releases" + CloseAfterOpenForTesting: '${{ parameters.TestPipeline }}' - - deployment: PublishDocsMs + - job: PublishDocsMs displayName: Docs.MS Release condition: and(succeeded(), ne(variables['Skip.PublishDocs'], 'true')) - environment: ${{ parameters.Environment }} - dependsOn: PublishPackage + dependsOn: PublishESRPPackage pool: name: azsdk-pool-mms-ubuntu-2004-general image: azsdk-pool-mms-ubuntu-2004-1espt os: linux - strategy: - runOnce: - deploy: - steps: - - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml - parameters: - Paths: - - sdk - - common/perf-test-core - - .github/CODEOWNERS - - '!sdk/**/test-recordings' - - '!sdk/**/session-records' - - download: current - displayName: 'Download Artifact: ${{parameters.ArtifactName}}' - artifact: ${{parameters.ArtifactName}} + steps: + - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml + parameters: + Paths: + - sdk + - common/perf-test-core + - .github/CODEOWNERS + - '!sdk/**/test-recordings' + - '!sdk/**/session-records' + - download: current + displayName: 'Download Artifact: ${{parameters.ArtifactName}}' + artifact: ${{parameters.ArtifactName}} - - template: /eng/pipelines/templates/steps/mvn-linux-repository-settings.yml + - template: /eng/pipelines/templates/steps/mvn-linux-repository-settings.yml - - template: /eng/pipelines/templates/steps/install-rex-validation-tool.yml + - template: /eng/pipelines/templates/steps/install-rex-validation-tool.yml - - template: /eng/common/pipelines/templates/steps/update-docsms-metadata.yml - parameters: - PackageInfoLocations: - - ${{ each artifact in parameters.Artifacts }}: - - ${{if ne(artifact.skipPublishDocMs, 'true')}}: - - $(Pipeline.Workspace)/${{parameters.ArtifactName}}/PackageInfo/${{artifact.name}}.json - WorkingDirectory: $(System.DefaultWorkingDirectory) - TargetDocRepoOwner: $(DocRepoOwner) - TargetDocRepoName: $(DocRepoName) - Language: 'java' - SparseCheckoutPaths: - - docs-ref-services/ - - metadata/ - - - deployment: PublishDocs + - template: /eng/common/pipelines/templates/steps/update-docsms-metadata.yml + parameters: + PackageInfoLocations: + - ${{ each artifact in parameters.Artifacts }}: + - ${{if ne(artifact.skipPublishDocMs, 'true')}}: + - $(Pipeline.Workspace)/${{parameters.ArtifactName}}/PackageInfo/${{artifact.name}}.json + WorkingDirectory: $(System.DefaultWorkingDirectory) + TargetDocRepoOwner: $(DocRepoOwner) + TargetDocRepoName: $(DocRepoName) + Language: 'java' + SparseCheckoutPaths: + - docs-ref-services/ + - metadata/ + + - job: PublishDocs displayName: Publish Docs to GitHubIO Blob Storage condition: and(succeeded(), ne(variables['Skip.PublishDocs'], 'true')) - environment: ${{ parameters.Environment }} - dependsOn: PublishPackage + dependsOn: PublishESRPPackage pool: name: azsdk-pool-mms-win-2022-general image: azsdk-pool-mms-win-2022-1espt os: windows - strategy: - runOnce: - deploy: - steps: - - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml - - download: current - displayName: 'Download Artifact: ${{parameters.ArtifactName}}-signed' - artifact: ${{parameters.ArtifactName}}-signed - - ${{ each artifact in parameters.Artifacts }}: - - ${{if ne(artifact.skipPublishDocGithubIo, 'true')}}: - - pwsh: | - Get-ChildItem -Recurse $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed/${{artifact.groupId}}/${{artifact.name}} - workingDirectory: $(Pipeline.Workspace) - displayName: Output Visible Artifacts - - template: /eng/common/pipelines/templates/steps/publish-blobs.yml - parameters: - FolderForUpload: '$(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed/${{artifact.groupId}}/${{artifact.name}}' - TargetLanguage: 'java' - ArtifactLocation: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed/${{artifact.groupId}}/${{artifact.name}} + steps: + - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml + - download: current + displayName: 'Download Artifact: ${{parameters.ArtifactName}}-signed' + artifact: ${{parameters.ArtifactName}}-signed + - ${{ each artifact in parameters.Artifacts }}: + - ${{if ne(artifact.skipPublishDocGithubIo, 'true')}}: + - pwsh: | + Get-ChildItem -Recurse $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed/${{artifact.groupId}}/${{artifact.name}} + workingDirectory: $(Pipeline.Workspace) + displayName: Output Visible Artifacts + - template: /eng/common/pipelines/templates/steps/publish-blobs.yml + parameters: + FolderForUpload: '$(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed/${{artifact.groupId}}/${{artifact.name}}' + TargetLanguage: 'java' + ArtifactLocation: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed/${{artifact.groupId}}/${{artifact.name}} - ${{if ne(parameters.EnableIntegrationStage, false)}}: - stage: Integration @@ -431,7 +455,7 @@ stages: - ${{ each artifact in parameters.Artifacts }}: - ${{if ne(artifact.skipPublishDevFeed, 'true')}}: - - template: /eng/pipelines/templates/steps/java-publishing.yml + - template: /eng/pipelines/templates/steps/java-dev-feed-publishing.yml parameters: ArtifactID: ${{artifact.name}} GroupID: ${{artifact.groupId}} diff --git a/eng/pipelines/templates/stages/archetype-java-release-patch.yml b/eng/pipelines/templates/stages/archetype-java-release-patch.yml index d3215880fc3a..77e3322402bb 100644 --- a/eng/pipelines/templates/stages/archetype-java-release-patch.yml +++ b/eng/pipelines/templates/stages/archetype-java-release-patch.yml @@ -26,35 +26,57 @@ stages: - stage: Signing dependsOn: ${{parameters.DependsOn}} jobs: - - deployment: SignPackage - environment: esrp + - job: SignPackage timeoutInMinutes: 240 variables: - template: /eng/pipelines/templates/variables/globals.yml pool: - name: azsdk-pool-mms-ubuntu-2004-general - image: azsdk-pool-mms-ubuntu-2004-1espt - os: linux - strategy: - runOnce: - deploy: - steps: - - checkout: none - - template: /eng/pipelines/templates/steps/download-credscan-suppressions.yml + name: azsdk-pool-mms-win-2022-general + image: azsdk-pool-mms-win-2022-1espt + os: windows + steps: + - checkout: azure-sdk-build-tools + path: azure-sdk-build-tools + - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml + parameters: + SkipCheckoutNone: true + Repositories: + - Name: Azure/azure-sdk-for-java + Commitish: $(Build.SourceVersion) + WorkingDirectory: $(Pipeline.Workspace)/azure-sdk-for-java + - template: /eng/pipelines/templates/steps/download-credscan-suppressions.yml - - download: current - displayName: 'Download Artifact: ${{parameters.ArtifactName}}' - artifact: ${{parameters.ArtifactName}} + - download: current + displayName: 'Download Artifact: ${{parameters.ArtifactName}}' + artifact: ${{parameters.ArtifactName}} - - template: tools/java-esrp-signing/java-esrp-signing.yml@azure-sdk-build-tools - parameters: - Artifacts: ${{parameters.Artifacts}} - ArtifactDirectory: $(Pipeline.Workspace)/${{parameters.ArtifactName}} + # Publish the ESRP signed directory. This will still be used by the + # Dev feed publish. + - template: /eng/common/pipelines/templates/steps/publish-1es-artifact.yml + parameters: + ArtifactPath: '$(Pipeline.Workspace)/${{parameters.ArtifactName}}' + ArtifactName: '${{parameters.ArtifactName}}-signed' - - template: /eng/common/pipelines/templates/steps/publish-1es-artifact.yml - parameters: - ArtifactPath: '$(Pipeline.Workspace)/${{parameters.ArtifactName}}' - ArtifactName: '${{parameters.ArtifactName}}-signed' + # Downloading the ESRP signed artifacts + - download: current + displayName: 'Download Signed Artifacts' + artifact: ${{parameters.ArtifactName}}-signed + + # gpg-sign and create the flattened directory for ESRP bulk publish + # Note: The maven release requires the files to be local GPG signed + # Dev feed publishes use the gpg-sign-and-deply to do it in one step + - template: tools/gpg/gpg.yml@azure-sdk-build-tools + - template: /eng/pipelines/templates/steps/gpg-sign-and-flatten.yml + parameters: + ArtifactDirectory: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed + OutputDirectory: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-esrp-gpg-signed + FlattenedESRPDirectory: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-esrp-flattened + + # The packages-esrp-flattened will be used for the ESRP publish + - template: /eng/common/pipelines/templates/steps/publish-1es-artifact.yml + parameters: + ArtifactPath: '$(Pipeline.Workspace)/${{parameters.ArtifactName}}-esrp-flattened' + ArtifactName: '${{parameters.ArtifactName}}-esrp-flattened' # We generate two interdependent stages for each artifact listed in the ci.yml file, creates the release # in GitHub. The Release stage publishes to Maven Central. Both stages require approval since they @@ -67,44 +89,47 @@ stages: dependsOn: Signing condition: and(succeeded(), ne(variables['SetDevVersion'], 'true'), ne(variables['Skip.Release'], 'true'), ne(variables['Build.Repository.Name'], 'Azure/azure-sdk-for-java-pr')) jobs: - - deployment: TagRepository + - job: TagRepository displayName: "Create release tag" condition: and(succeeded(), ne(variables['Skip.TagRepository'], 'true')) - environment: ${{ parameters.Environment }} variables: - template: /eng/pipelines/templates/variables/globals.yml pool: name: azsdk-pool-mms-win-2022-general image: azsdk-pool-mms-win-2022-1espt os: windows - strategy: - runOnce: - deploy: - steps: - - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml - - template: /eng/common/pipelines/templates/steps/retain-run.yml - # No pattern, just download everything that's been signed - - download: current - displayName: 'Download Artifact: ${{parameters.ArtifactName}}-signed' - artifact: ${{parameters.ArtifactName}}-signed - - ${{ each artifact in parameters.Artifacts }}: - - template: /eng/common/pipelines/templates/steps/create-tags-and-git-release.yml - parameters: - ArtifactLocation: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed/${{artifact.groupId}}/${{artifact.name}} - PackageRepository: Maven - ReleaseSha: $(Build.SourceVersion) + steps: + - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml + - template: /eng/common/pipelines/templates/steps/retain-run.yml + # No pattern, just download everything that's been signed + - download: current + displayName: 'Download Artifact: ${{parameters.ArtifactName}}-signed' + artifact: ${{parameters.ArtifactName}}-signed + - ${{ each artifact in parameters.Artifacts }}: + - template: /eng/common/pipelines/templates/steps/create-tags-and-git-release.yml + parameters: + ArtifactLocation: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed/${{artifact.groupId}}/${{artifact.name}} + PackageRepository: Maven + ReleaseSha: $(Build.SourceVersion) - - deployment: PublishPackage - displayName: "Publish to Maven Central" + - deployment: PublishESRPPackage + displayName: "Publish to Maven Central via ESRP" condition: and(succeeded(), ne(variables['Skip.PublishPackage'], 'true')) - # There are over 130 com.azure libraries. At roughly 3m 20s per ESRP release - # this timeout should be enough to allow release of everything. Things should - # change once ESRP has batch release enabled. - timeoutInMinutes: 540 + # There are over several hundred com.azure libraries but ESRP batch release is + # a lot faster than releasing individual libraries. This timeout is probably a + # a bit high but far, far lower than when releases were single library. + timeoutInMinutes: 120 environment: ${{ parameters.Environment }} dependsOn: TagRepository - variables: - - template: /eng/pipelines/templates/variables/globals.yml + + templateContext: + type: releaseJob + isProduction: true + inputs: + - input: pipelineArtifact + artifactName: '${{parameters.ArtifactName}}-esrp-flattened' + targetPath: '$(Pipeline.Workspace)/${{parameters.ArtifactName}}-esrp-flattened' + pool: name: azsdk-pool-mms-win-2022-general image: azsdk-pool-mms-win-2022-1espt @@ -113,57 +138,62 @@ stages: runOnce: deploy: steps: - - checkout: azure-sdk-build-tools - path: azure-sdk-build-tools - - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml - parameters: - SkipCheckoutNone: true - Repositories: - - Name: Azure/azure-sdk-for-java - Commitish: $(Build.SourceVersion) - WorkingDirectory: $(Pipeline.Workspace)/azure-sdk-for-java - - template: /eng/pipelines/templates/steps/download-credscan-suppressions.yml - - download: current - displayName: 'Download Artifacts' - artifact: ${{parameters.ArtifactName}}-signed - - template: tools/gpg/gpg.yml@azure-sdk-build-tools - - template: /eng/pipelines/templates/steps/java-publishing.yml - parameters: - ArtifactDirectory: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed - OutputDirectory: $(Pipeline.Workspace)/EsrpPackages - Target: EsrpRelease - JavaRepoRoot: $(Pipeline.Workspace)/azure-sdk-for-java - - template: /eng/common/pipelines/templates/steps/publish-1es-artifact.yml - parameters: - ArtifactName: ${{parameters.ArtifactName}}-esrp-$(System.JobAttempt) - ArtifactPath: $(Pipeline.Workspace)/EsrpPackages - # After publishing to Maven, publish to the azure-sdk-for-java feed. The reason for - # this is that the azure-sdk-for-java feed will have the package available immediately - # whereas Maven can take several hours for the package to become available. - - template: /eng/pipelines/templates/steps/java-publishing.yml - parameters: - ArtifactDirectory: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed - RepositoryUrl: https://pkgs.dev.azure.com/azure-sdk/public/_packaging/azure-sdk-for-java/maven/v1 - Target: JavaDevFeed - JavaRepoRoot: $(Pipeline.Workspace)/azure-sdk-for-java - - template: /eng/common/pipelines/templates/steps/publish-1es-artifact.yml + - template: /eng/pipelines/templates/steps/java-esrp-publishing.yml parameters: - ArtifactName: ${{parameters.ArtifactName}}-javadevfeed-$(System.JobAttempt) - ArtifactPath: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed - - template: /eng/common/pipelines/templates/steps/create-apireview.yml - parameters: - ArtifactPath: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed - Artifacts: ${{parameters.Artifacts}} - ConfigFileDir: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed/PackageInfo - MarkPackageAsShipped: true - ArtifactName: ${{parameters.ArtifactName}}-signed - SourceRootPath: $(Pipeline.Workspace)/azure-sdk-for-java + FlattenedDirectory: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-esrp-flattened - - deployment: UpdatePackageVersion + - job: PublishDevFeedPackage + displayName: "Publish to Java Dev feed" + condition: and(succeeded(), ne(variables['Skip.PublishPackage'], 'true')) + # This timeout shouldn't be necessary once we're able to parallelize better. Right now, + # this is here to ensure larger areas (30+) libraries don't time out. + timeoutInMinutes: 120 + dependsOn: PublishESRPPackage + pool: + name: azsdk-pool-mms-win-2022-general + image: azsdk-pool-mms-win-2022-1espt + os: windows + steps: + - checkout: azure-sdk-build-tools + path: azure-sdk-build-tools + - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml + parameters: + SkipCheckoutNone: true + Repositories: + - Name: Azure/azure-sdk-for-java + Commitish: $(Build.SourceVersion) + WorkingDirectory: $(Pipeline.Workspace)/azure-sdk-for-java + - template: /eng/pipelines/templates/steps/download-credscan-suppressions.yml + - download: current + displayName: 'Download Artifacts' + artifact: ${{parameters.ArtifactName}}-signed + - template: tools/gpg/gpg.yml@azure-sdk-build-tools + # After publishing to Maven, publish to the azure-sdk-for-java feed. The reason for + # this is that the azure-sdk-for-java feed will have the package available immediately + # whereas Maven can take several hours for the package to become available. + - template: /eng/pipelines/templates/steps/java-dev-feed-publishing.yml + parameters: + ArtifactDirectory: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed + RepositoryUrl: https://pkgs.dev.azure.com/azure-sdk/public/_packaging/azure-sdk-for-java/maven/v1 + Target: JavaDevFeed + JavaRepoRoot: $(Pipeline.Workspace)/azure-sdk-for-java + - template: /eng/common/pipelines/templates/steps/publish-1es-artifact.yml + parameters: + ArtifactName: ${{parameters.ArtifactName}}-javadevfeed-$(System.JobAttempt) + ArtifactPath: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed + - template: /eng/common/pipelines/templates/steps/create-apireview.yml + parameters: + ArtifactPath: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed + Artifacts: ${{parameters.Artifacts}} + ConfigFileDir: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed/PackageInfo + MarkPackageAsShipped: true + ArtifactName: ${{parameters.ArtifactName}}-signed + SourceRootPath: $(Pipeline.Workspace)/azure-sdk-for-java + + - job: UpdatePackageVersion displayName: "Update Package Version" condition: and(succeeded(), ne(variables['Skip.UpdatePackageVersion'], 'true')) - environment: ${{ parameters.Environment }} - dependsOn: PublishPackage + dependsOn: PublishESRPPackage variables: - template: /eng/pipelines/templates/variables/globals.yml - name: ArtifactsJson @@ -172,54 +202,50 @@ stages: name: azsdk-pool-mms-win-2022-general image: azsdk-pool-mms-win-2022-1espt os: windows - strategy: - runOnce: - deploy: - steps: - - download: none + steps: + - download: none - - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml - parameters: - Paths: - - '**/*.xml' - - '**/*.md' - - '!sdk/**/test-recordings/*' - - '!sdk/**/session-records/*' + - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml + parameters: + Paths: + - '**/*.xml' + - '**/*.md' + - '!sdk/**/test-recordings/*' + - '!sdk/**/session-records/*' - - task: UsePythonVersion@0 - displayName: 'Use Python $(PythonVersion)' - inputs: - versionSpec: $(PythonVersion) + - task: UsePythonVersion@0 + displayName: 'Use Python $(PythonVersion)' + inputs: + versionSpec: $(PythonVersion) - # Apply the version increment to each library, which only updates the version_client.txt file, - # and then call to update_versions will then apply all of the updates. - - pwsh: | - $ArtifactsList = $('$(ArtifactsJson)' | ConvertFrom-Json | Select-Object name, groupId) - $ArtifactsList | Format-Table -Property GroupId, Name | Out-String | Write-Host - python --version - foreach($artifact in $ArtifactsList) { - python eng/versioning/set_versions.py --build-type ${{ parameters.SDKType }} --increment-version --ai $($artifact.name) --gi $($artifact.groupId) - } - displayName: Increment package versions + # Apply the version increment to each library, which only updates the version_client.txt file, + # and then call to update_versions will then apply all of the updates. + - pwsh: | + $ArtifactsList = $('$(ArtifactsJson)' | ConvertFrom-Json | Select-Object name, groupId) + $ArtifactsList | Format-Table -Property GroupId, Name | Out-String | Write-Host + python --version + foreach($artifact in $ArtifactsList) { + python eng/versioning/set_versions.py --build-type ${{ parameters.SDKType }} --increment-version --ai $($artifact.name) --gi $($artifact.groupId) + } + displayName: Increment package versions - - script: | - python --version - python eng/versioning/update_versions.py --update-type library --build-type ${{ parameters.SDKType }} --avi --sr - displayName: Update pom files for incremented versions + - script: | + python --version + python eng/versioning/update_versions.py --update-type library --build-type ${{ parameters.SDKType }} --avi --sr + displayName: Update pom files for incremented versions - - template: /eng/common/pipelines/templates/steps/create-pull-request.yml - parameters: - PRBranchName: increment-package-version-patch-release-$(Build.BuildId) - CommitMsg: "Increment package versions for patch releases" - PRTitle: "Increment versions for patch releases" - CloseAfterOpenForTesting: '${{ parameters.TestPipeline }}' + - template: /eng/common/pipelines/templates/steps/create-pull-request.yml + parameters: + PRBranchName: increment-package-version-patch-release-$(Build.BuildId) + CommitMsg: "Increment package versions for patch releases" + PRTitle: "Increment versions for patch releases" + CloseAfterOpenForTesting: '${{ parameters.TestPipeline }}' - - deployment: PublishDocsMs + - job: PublishDocsMs displayName: Docs.MS Release condition: and(succeeded(), ne(variables['Skip.PublishDocs'], 'true')) timeoutInMinutes: 180 - environment: ${{ parameters.Environment }} - dependsOn: PublishPackage + dependsOn: PublishESRPPackage pool: name: azsdk-pool-mms-ubuntu-2004-general @@ -229,69 +255,61 @@ stages: variables: - template: /eng/pipelines/templates/variables/globals.yml - strategy: - runOnce: - deploy: - steps: - - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml - parameters: - SkipCheckoutNone: true - Paths: - - sdk - - common/perf-test-core - - .github/CODEOWNERS - - '!sdk/**/test-recordings/*' - - '!sdk/**/session-records/*' - - download: current - displayName: 'Download Artifact: ${{parameters.ArtifactName}}' - artifact: ${{parameters.ArtifactName}} + steps: + - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml + parameters: + Paths: + - sdk + - common/perf-test-core + - .github/CODEOWNERS + - '!sdk/**/test-recordings/*' + - '!sdk/**/session-records/*' + - download: current + displayName: 'Download Artifact: ${{parameters.ArtifactName}}' + artifact: ${{parameters.ArtifactName}} - - template: /eng/pipelines/templates/steps/mvn-linux-repository-settings.yml + - template: /eng/pipelines/templates/steps/mvn-linux-repository-settings.yml - - template: /eng/pipelines/templates/steps/install-rex-validation-tool.yml + - template: /eng/pipelines/templates/steps/install-rex-validation-tool.yml - - template: /eng/common/pipelines/templates/steps/update-docsms-metadata.yml - parameters: - PackageInfoLocations: - - ${{ each artifact in parameters.Artifacts }}: - - ${{if ne(artifact.skipPublishDocMs, 'true')}}: - - $(Pipeline.Workspace)/${{parameters.ArtifactName}}/PackageInfo/${{artifact.name}}.json - WorkingDirectory: $(System.DefaultWorkingDirectory) - TargetDocRepoOwner: $(DocRepoOwner) - TargetDocRepoName: $(DocRepoName) - Language: 'java' - SparseCheckoutPaths: - - docs-ref-services/ - - metadata/ + - template: /eng/common/pipelines/templates/steps/update-docsms-metadata.yml + parameters: + PackageInfoLocations: + - ${{ each artifact in parameters.Artifacts }}: + - ${{if ne(artifact.skipPublishDocMs, 'true')}}: + - $(Pipeline.Workspace)/${{parameters.ArtifactName}}/PackageInfo/${{artifact.name}}.json + WorkingDirectory: $(System.DefaultWorkingDirectory) + TargetDocRepoOwner: $(DocRepoOwner) + TargetDocRepoName: $(DocRepoName) + Language: 'java' + SparseCheckoutPaths: + - docs-ref-services/ + - metadata/ - - deployment: PublishDocs + - job: PublishDocs displayName: Publish Docs to GitHubIO Blob Storage condition: and(succeeded(), ne(variables['Skip.PublishDocs'], 'true')) timeoutInMinutes: 120 - environment: ${{ parameters.Environment }} - dependsOn: PublishPackage + dependsOn: PublishESRPPackage variables: - template: /eng/pipelines/templates/variables/globals.yml pool: name: azsdk-pool-mms-win-2022-general image: azsdk-pool-mms-win-2022-1espt os: windows - strategy: - runOnce: - deploy: - steps: - - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml - - download: current - displayName: 'Download Artifact: ${{parameters.ArtifactName}}-signed' - artifact: ${{parameters.ArtifactName}}-signed - - ${{ each artifact in parameters.Artifacts }}: - - ${{if ne(artifact.skipPublishDocGithubIo, 'true')}}: - - pwsh: | - Get-ChildItem -Recurse $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed/${{artifact.groupId}}/${{artifact.name}} - workingDirectory: $(Pipeline.Workspace) - displayName: Output Visible Artifacts - - template: /eng/common/pipelines/templates/steps/publish-blobs.yml - parameters: - FolderForUpload: '$(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed/${{artifact.groupId}}/${{artifact.name}}' - TargetLanguage: 'java' - ArtifactLocation: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed/${{artifact.groupId}}/${{artifact.name}} + steps: + - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml + - download: current + displayName: 'Download Artifact: ${{parameters.ArtifactName}}-signed' + artifact: ${{parameters.ArtifactName}}-signed + - ${{ each artifact in parameters.Artifacts }}: + - ${{if ne(artifact.skipPublishDocGithubIo, 'true')}}: + - pwsh: | + Get-ChildItem -Recurse $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed/${{artifact.groupId}}/${{artifact.name}} + workingDirectory: $(Pipeline.Workspace) + displayName: Output Visible Artifacts + - template: /eng/common/pipelines/templates/steps/publish-blobs.yml + parameters: + FolderForUpload: '$(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed/${{artifact.groupId}}/${{artifact.name}}' + TargetLanguage: 'java' + ArtifactLocation: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed/${{artifact.groupId}}/${{artifact.name}} diff --git a/eng/pipelines/templates/stages/archetype-java-release-pom-only.yml b/eng/pipelines/templates/stages/archetype-java-release-pom-only.yml index ca824b7fcdb2..e58675156284 100644 --- a/eng/pipelines/templates/stages/archetype-java-release-pom-only.yml +++ b/eng/pipelines/templates/stages/archetype-java-release-pom-only.yml @@ -11,35 +11,61 @@ stages: - stage: Signing dependsOn: ${{parameters.DependsOn}} jobs: - - deployment: SignPackage - environment: esrp + - job: SignPackage timeoutInMinutes: 20 variables: - - template: ../variables/globals.yml + - template: /eng/pipelines/templates/variables/globals.yml pool: - name: azsdk-pool-mms-ubuntu-2004-general - image: azsdk-pool-mms-ubuntu-2004-1espt - os: linux - strategy: - runOnce: - deploy: - steps: - - checkout: none - - template: /eng/pipelines/templates/steps/download-credscan-suppressions.yml + name: azsdk-pool-mms-win-2022-general + image: azsdk-pool-mms-win-2022-1espt + os: windows + steps: + - checkout: azure-sdk-build-tools + path: azure-sdk-build-tools + - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml + parameters: + SkipCheckoutNone: true + Repositories: + - Name: Azure/azure-sdk-for-java + Commitish: $(Build.SourceVersion) + WorkingDirectory: $(Pipeline.Workspace)/azure-sdk-for-java + - template: /eng/pipelines/templates/steps/download-credscan-suppressions.yml - - download: current - displayName: 'Download Artifact: ${{parameters.ArtifactName}}' - artifact: ${{parameters.ArtifactName}} + - download: current + displayName: 'Download Artifact: ${{parameters.ArtifactName}}' + artifact: ${{parameters.ArtifactName}} - - template: tools/java-esrp-signing/java-esrp-signing.yml@azure-sdk-build-tools - parameters: - Artifacts: ${{parameters.Artifacts}} - ArtifactDirectory: $(Pipeline.Workspace)/${{parameters.ArtifactName}} + - template: tools/java-esrp-signing/java-esrp-signing.yml@azure-sdk-build-tools + parameters: + Artifacts: ${{parameters.Artifacts}} + ArtifactDirectory: $(Pipeline.Workspace)/${{parameters.ArtifactName}} - - template: /eng/common/pipelines/templates/steps/publish-1es-artifact.yml - parameters: - ArtifactPath: '$(Pipeline.Workspace)/${{parameters.ArtifactName}}' - ArtifactName: '${{parameters.ArtifactName}}-signed' + # Publish the ESRP signed directory. + - template: /eng/common/pipelines/templates/steps/publish-1es-artifact.yml + parameters: + ArtifactPath: '$(Pipeline.Workspace)/${{parameters.ArtifactName}}' + ArtifactName: '${{parameters.ArtifactName}}-signed' + + # Downloading the ESRP signed artifacts + - download: current + displayName: 'Download Signed Artifacts' + artifact: ${{parameters.ArtifactName}}-signed + + # gpg-sign and create the flattened directory for ESRP bulk publish + # Note: The maven release requires the files to be local GPG signed + # Dev feed publishes use the gpg-sign-and-deply to do it in one step + - template: tools/gpg/gpg.yml@azure-sdk-build-tools + - template: /eng/pipelines/templates/steps/gpg-sign-and-flatten.yml + parameters: + ArtifactDirectory: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed + OutputDirectory: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-esrp-gpg-signed + FlattenedESRPDirectory: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-esrp-flattened + + # The packages-esrp-flattened will be used for the ESRP publish + - template: /eng/common/pipelines/templates/steps/publish-1es-artifact.yml + parameters: + ArtifactPath: '$(Pipeline.Workspace)/${{parameters.ArtifactName}}-esrp-flattened' + ArtifactName: '${{parameters.ArtifactName}}-esrp-flattened' # We generate two interdepdent stages for each artifact listed in the ci.yml file, creates the release # in GitHub. The Release stage publishes to Maven Central. Both stages require approval since they @@ -53,12 +79,42 @@ stages: dependsOn: Signing condition: and(succeeded(), ne(variables['SetDevVersion'], 'true'), ne(variables['Skip.Release'], 'true'), ne(variables['Build.Repository.Name'], 'Azure/azure-sdk-for-java-pr')) jobs: - - deployment: TagRepository + - job: TagRepository displayName: "Create release tag" condition: ne(variables['Skip.TagRepository'], 'true') - environment: maven variables: - - template: ../variables/globals.yml + - template: /eng/pipelines/templates/variables/globals.yml + pool: + name: azsdk-pool-mms-win-2022-general + image: azsdk-pool-mms-win-2022-1espt + os: windows + steps: + - download: current + displayName: 'Download Artifact: ${{parameters.ArtifactName}}-signed' + artifact: ${{parameters.ArtifactName}}-signed + patterns: ${{artifact.groupId}}/${{artifact.name}}/** + - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml + - template: /eng/common/pipelines/templates/steps/retain-run.yml + - template: /eng/common/pipelines/templates/steps/create-tags-and-git-release.yml + parameters: + ArtifactLocation: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed/${{artifact.groupId}}/${{artifact.name}} + PackageRepository: Maven + ReleaseSha: $(Build.SourceVersion) + + - deployment: PublishESRPPackage + displayName: "Publish to Maven Central via ESRP" + condition: and(succeeded(), ne(variables['Skip.PublishPackage'], 'true')) + environment: maven + dependsOn: TagRepository + + templateContext: + type: releaseJob + isProduction: true + inputs: + - input: pipelineArtifact + artifactName: '${{parameters.ArtifactName}}-esrp-flattened' + targetPath: '$(Pipeline.Workspace)/${{parameters.ArtifactName}}-esrp-flattened' + pool: name: azsdk-pool-mms-win-2022-general image: azsdk-pool-mms-win-2022-1espt @@ -67,73 +123,46 @@ stages: runOnce: deploy: steps: - - download: current - displayName: 'Download Artifact: ${{parameters.ArtifactName}}-signed' - artifact: ${{parameters.ArtifactName}}-signed - patterns: ${{artifact.groupId}}/${{artifact.name}}/** - - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml - - template: /eng/common/pipelines/templates/steps/retain-run.yml - - template: /eng/common/pipelines/templates/steps/create-tags-and-git-release.yml + - template: /eng/pipelines/templates/steps/java-esrp-publishing.yml parameters: - ArtifactLocation: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed/${{artifact.groupId}}/${{artifact.name}} - PackageRepository: Maven - ReleaseSha: $(Build.SourceVersion) + FlattenedDirectory: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-esrp-flattened - - ${{if ne(artifact.options.skipPublishPackage, 'true')}}: - - deployment: PublishPackage - displayName: "Publish to Maven Central" - condition: and(succeeded(), ne(variables['Skip.PublishPackage'], 'true')) - environment: maven - dependsOn: TagRepository - variables: - - template: ../variables/globals.yml - pool: - name: azsdk-pool-mms-win-2022-general - image: azsdk-pool-mms-win-2022-1espt - os: windows - strategy: - runOnce: - deploy: - steps: - - download: current - displayName: 'Download Artifact: ${{parameters.ArtifactName}}-signed' - artifact: ${{parameters.ArtifactName}}-signed - patterns: ${{artifact.groupId}}/${{artifact.name}}/** - - checkout: azure-sdk-build-tools - path: azure-sdk-build-tools - - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml - parameters: - SkipCheckoutNone: true - Repositories: - - Name: Azure/azure-sdk-for-java - Commitish: $(Build.SourceVersion) - WorkingDirectory: $(Pipeline.Workspace)/azure-sdk-for-java - - template: /eng/pipelines/templates/steps/download-credscan-suppressions.yml - - template: tools/gpg/gpg.yml@azure-sdk-build-tools - - template: /eng/pipelines/templates/steps/java-publishing.yml - parameters: - ArtifactID: ${{artifact.name}} - GroupID: ${{artifact.groupId}} - ArtifactDirectory: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed - OutputDirectory: $(Pipeline.Workspace)/EsrpPackages - Target: EsrpRelease - JavaRepoRoot: $(Pipeline.Workspace)/azure-sdk-for-java - - template: /eng/common/pipelines/templates/steps/publish-1es-artifact.yml - parameters: - ArtifactName: ${{parameters.ArtifactName}}-${{artifact.name}}-esrp-$(System.JobAttempt) - ArtifactPath: $(Pipeline.Workspace)/EsrpPackages - # After publishing to Maven, publish to the azure-sdk-for-java feed. The reason for - # this is that the azure-sdk-for-java feed will have the package available immediately - # whereas Maven can take several hours for the package to become available. - - template: /eng/pipelines/templates/steps/java-publishing.yml - parameters: - ArtifactID: ${{artifact.name}} - GroupID: ${{artifact.groupId}} - ArtifactDirectory: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed - RepositoryUrl: https://pkgs.dev.azure.com/azure-sdk/public/_packaging/azure-sdk-for-java/maven/v1 - Target: JavaDevFeed - JavaRepoRoot: $(Pipeline.Workspace)/azure-sdk-for-java - - template: /eng/common/pipelines/templates/steps/publish-1es-artifact.yml - parameters: - ArtifactName: ${{parameters.ArtifactName}}-${{artifact.name}}-javadevfeed-$(System.JobAttempt) - ArtifactPath: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed + - job: PublishDevFeedPackage + displayName: "Publish to Java Dev feed" + condition: and(succeeded(), ne(variables['Skip.PublishPackage'], 'true')) + dependsOn: PublishESRPPackage + variables: + - template: /eng/pipelines/templates/variables/globals.yml + pool: + name: azsdk-pool-mms-win-2022-general + image: azsdk-pool-mms-win-2022-1espt + os: windows + steps: + - download: current + displayName: 'Download Artifact: ${{parameters.ArtifactName}}-signed' + artifact: ${{parameters.ArtifactName}}-signed + patterns: ${{artifact.groupId}}/${{artifact.name}}/** + - checkout: azure-sdk-build-tools + path: azure-sdk-build-tools + - template: /eng/common/pipelines/templates/steps/sparse-checkout.yml + parameters: + SkipCheckoutNone: true + Repositories: + - Name: Azure/azure-sdk-for-java + Commitish: $(Build.SourceVersion) + WorkingDirectory: $(Pipeline.Workspace)/azure-sdk-for-java + - template: /eng/pipelines/templates/steps/download-credscan-suppressions.yml + - template: tools/gpg/gpg.yml@azure-sdk-build-tools + # Publish to the azure-sdk-for-java feed. + - template: /eng/pipelines/templates/steps/java-dev-feed-publishing.yml + parameters: + ArtifactID: ${{artifact.name}} + GroupID: ${{artifact.groupId}} + ArtifactDirectory: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed + RepositoryUrl: https://pkgs.dev.azure.com/azure-sdk/public/_packaging/azure-sdk-for-java/maven/v1 + Target: JavaDevFeed + JavaRepoRoot: $(Pipeline.Workspace)/azure-sdk-for-java + - template: /eng/common/pipelines/templates/steps/publish-1es-artifact.yml + parameters: + ArtifactName: ${{parameters.ArtifactName}}-${{artifact.name}}-javadevfeed-$(System.JobAttempt) + ArtifactPath: $(Pipeline.Workspace)/${{parameters.ArtifactName}}-signed diff --git a/eng/pipelines/templates/stages/archetype-sdk-client-patch.yml b/eng/pipelines/templates/stages/archetype-sdk-client-patch.yml index 049407da743c..f11848e74f97 100644 --- a/eng/pipelines/templates/stages/archetype-sdk-client-patch.yml +++ b/eng/pipelines/templates/stages/archetype-sdk-client-patch.yml @@ -201,6 +201,7 @@ extends: Paths: - '**/*.xml' - '**/*.md' + - '**/*.yml' # needed for package properties when setting the test pipeline version - '.vscode/cspell.json' - '!sdk/**/test-recordings/*' - '!sdk/**/session-records/*' diff --git a/eng/pipelines/templates/steps/build-and-test.yml b/eng/pipelines/templates/steps/build-and-test.yml index 7d154211052c..5d700cc80439 100644 --- a/eng/pipelines/templates/steps/build-and-test.yml +++ b/eng/pipelines/templates/steps/build-and-test.yml @@ -267,6 +267,7 @@ steps: $xml.Save($_.FullName) } displayName: 'Update test case names for reporting' + condition: always() workingDirectory: $(System.DefaultWorkingDirectory)/sdk - task: PublishTestResults@2 diff --git a/eng/pipelines/templates/steps/generate-project-list-and-cache-maven-repository.yml b/eng/pipelines/templates/steps/generate-project-list-and-cache-maven-repository.yml index 7eacf7243480..da5b450f5575 100644 --- a/eng/pipelines/templates/steps/generate-project-list-and-cache-maven-repository.yml +++ b/eng/pipelines/templates/steps/generate-project-list-and-cache-maven-repository.yml @@ -15,12 +15,33 @@ parameters: - name: UseCache type: boolean default: true + - name: ServiceDirectory + type: string + default: 'not-specified' # Set a default that breaks in obvious ways. + - name: ExcludePaths + type: object + default: [] steps: - # Create the ProjectList and ProjectListSha256 variables. - # The ProjectList is used by subsequent steps and tasks to run CI. - # The ProjectListSha256 is used by the cache key, previously the cache key was using ProjectList but it was found - # that long cache keys cause caching to fail. + +# This is the case for the PullReqest pipeline which has a ServiceDirectory of 'auto'. +# For the PullRequest pipeline, the packageInfo files generated from the diff end up +# being the source of truth for the artifacts list. +- ${{ if and(eq(variables['Build.Reason'], 'PullRequest'), eq(parameters.ServiceDirectory, 'auto')) }}: + - template: /eng/common/pipelines/templates/steps/save-package-properties.yml + parameters: + ServiceDirectory: ${{parameters.ServiceDirectory}} + ExcludePaths: ${{parameters.ExcludePaths}} + +# Create the ProjectList and ProjectListSha256 variables. +# The ProjectList is used by subsequent steps and tasks to run CI. +# The ProjectListSha256 is used by the cache key, previously the cache key was using ProjectList but it was found +# that long cache keys cause caching to fail. + +# ArtifactPackageNames is set by the generate test matrix and is only set for test runs. This needs to be +# used to correctly set the project list and additional modules for what should be running for this particular +# matrix run. The reason for this is that different service directories, like clientcore, have their own +# default test matrix as compared to something like azure-template, which uses the default test matrix - task: PowerShell@2 displayName: Initialize project list variable inputs: @@ -30,6 +51,19 @@ steps: ARTIFACTSJSON: $(ArtifactsJson) ADDITIONALMODULESJSON: $(AdditionalModulesJson) PACKAGEINFODIR: $(Build.ArtifactStagingDirectory)/PackageInfo + condition: eq(variables['ArtifactPackageNames'], '') + +- task: PowerShell@2 + displayName: Initialize project list variable for PR test run + inputs: + pwsh: true + filePath: eng/pipelines/scripts/generate-project-list.ps1 + env: + ARTIFACTSJSON: $(ArtifactsJson) + ADDITIONALMODULESJSON: $(AdditionalModulesJson) + PACKAGEINFODIR: $(Build.ArtifactStagingDirectory)/PackageInfo + ARTIFACTPACKAGENAMES: $(ArtifactPackageNames) + condition: ne(variables['ArtifactPackageNames'], '') # The Cache task, when restoring, can have a miss and still pass but, if nothing is built, the # Post-Job Cache will fail because there's no .m2/repository diff --git a/eng/pipelines/templates/steps/gpg-sign-and-flatten.yml b/eng/pipelines/templates/steps/gpg-sign-and-flatten.yml new file mode 100644 index 000000000000..e044c4e5b537 --- /dev/null +++ b/eng/pipelines/templates/steps/gpg-sign-and-flatten.yml @@ -0,0 +1,35 @@ +parameters: + ArtifactDirectory: not-specified + OutputDirectory: not-specified + FlattenedESRPDirectory: not-specified + GroupID: + ArtifactID: + GPGExecutablePath: $(Pipeline.Workspace)/azure-sdk-build-tools/tools/gpg/bin/gpg.exe + JavaRepoRoot: $(Pipeline.Workspace)/azure-sdk-for-java + +steps: + - task: PowerShell@2 + displayName: 'Gpg sign and hash packages' + inputs: + pwsh: true + workingDirectory: $(Agent.BuildDirectory) + filePath: ${{ parameters.JavaRepoRoot }}/eng/scripts/SignAndHash-MavenPackages.ps1 + arguments: > + -Path ${{ parameters.ArtifactDirectory }} + -DestinationPath ${{ parameters.OutputDirectory }} + -GroupIDFilter "${{ parameters.GroupID }}" + -ArtifactIDFilter "${{ parameters.ArtifactID }}" + -GPGExecutablePath ${{ parameters.GPGExecutablePath }} + -InformationAction Continue + # ESRP needs to have the output folder flattened in order to do a bulk publish + # The flattened folder is only used by ESRP + - task: PowerShell@2 + displayName: 'Flatten output folder for ESRP' + inputs: + pwsh: true + workingDirectory: $(Agent.BuildDirectory) + filePath: ${{ parameters.JavaRepoRoot }}/eng/scripts/Flatten-MavenPackageFolder.ps1 + arguments: > + -SignedDirectory ${{ parameters.OutputDirectory }} + -FlattenedDirectory ${{ parameters.FlattenedESRPDirectory }} + -InformationAction Continue diff --git a/eng/pipelines/templates/steps/initialize-test-environment.yml b/eng/pipelines/templates/steps/initialize-test-environment.yml index 62a437b7f87b..4ee90d3fec21 100644 --- a/eng/pipelines/templates/steps/initialize-test-environment.yml +++ b/eng/pipelines/templates/steps/initialize-test-environment.yml @@ -5,6 +5,12 @@ parameters: - name: OS type: string default: $(OSVmImage) + - name: ServiceDirectory + type: string + default: 'not-specified' # Set a default that breaks in obvious ways. + - name: ExcludePaths + type: object + default: [] steps: # Skip sparse checkout for the `azure-sdk-for--pr` private mirrored repositories @@ -14,6 +20,7 @@ steps: parameters: Paths: - '**/*.xml' + - '**/ci*.yml' # necessary for save-package-properties.yml - ${{ if not(parameters.CheckoutRecordings) }}: - '!sdk/**/test-recordings' - '!sdk/**/session-records' @@ -44,6 +51,8 @@ steps: - template: /eng/pipelines/templates/steps/generate-project-list-and-cache-maven-repository.yml parameters: JobType: 'test' + ServiceDirectory: ${{parameters.ServiceDirectory}} + ExcludePaths: ${{parameters.ExcludePaths}} # This call is used generate the sparse checkout variables for non-FromSource runs. - task: PowerShell@2 diff --git a/eng/pipelines/templates/steps/java-dev-feed-publishing.yml b/eng/pipelines/templates/steps/java-dev-feed-publishing.yml new file mode 100644 index 000000000000..c1395ef5ce19 --- /dev/null +++ b/eng/pipelines/templates/steps/java-dev-feed-publishing.yml @@ -0,0 +1,46 @@ +parameters: + ArtifactDirectory: not-specified + OutputDirectory: not-specified + RepositoryUrl: not-specified + GroupID: + ArtifactID: + GPGExecutablePath: $(Pipeline.Workspace)/azure-sdk-build-tools/tools/gpg/bin/gpg.exe + JavaRepoRoot: $(Pipeline.Workspace)/azure-sdk-for-java + ShouldPublish: true + +steps: + - ${{if eq(parameters.Target, 'JavaDevFeed')}}: + - task: PowerShell@2 + displayName: 'Publish to Java Dev Feed' + inputs: + pwsh: true + workingDirectory: $(Agent.BuildDirectory) + filePath: ${{ parameters.JavaRepoRoot }}/eng/scripts/Publish-MavenPackages.ps1 + arguments: > + -ArtifactDirectory ${{ parameters.ArtifactDirectory }} + -GroupIDFilter "${{ parameters.GroupID }}" + -ArtifactIDFilter "${{ parameters.ArtifactID }}" + -RepositoryUrl ${{ parameters.RepositoryUrl }} + -RepositoryUsername nobody + -RepositoryPassword $(System.AccessToken) + -GPGExecutablePath ${{ parameters.GPGExecutablePath }} + -ShouldPublish:$${{parameters.ShouldPublish}} + -InformationAction Continue + + - ${{if eq(parameters.Target, 'AndroidDevFeed')}}: + - task: PowerShell@2 + displayName: 'Publish to Andriod Public Dev Feed' + inputs: + pwsh: true + workingDirectory: $(Agent.BuildDirectory) + filePath: ${{ parameters.JavaRepoRoot }}/eng/scripts/Publish-MavenPackages.ps1 + arguments: > + -ArtifactDirectory ${{ parameters.ArtifactDirectory }} + -GroupIDFilter "${{ parameters.GroupID }}" + -ArtifactIDFilter "${{ parameters.ArtifactID }}" + -RepositoryUrl https://pkgs.dev.azure.com/azure-sdk/public/_packaging/azure-sdk-for-android/maven/v1 + -RepositoryUsername nobody + -RepositoryPassword $(System.AccessToken) + -GPGExecutablePath ${{ parameters.GPGExecutablePath }} + -ShouldPublish:$${{parameters.ShouldPublish}} + -InformationAction Continue diff --git a/eng/pipelines/templates/steps/java-esrp-publishing.yml b/eng/pipelines/templates/steps/java-esrp-publishing.yml new file mode 100644 index 000000000000..f27f0a896487 --- /dev/null +++ b/eng/pipelines/templates/steps/java-esrp-publishing.yml @@ -0,0 +1,23 @@ +parameters: + # This is the flattened + FlattenedDirectory: not-specified + ShouldPublish: true + +steps: + - ${{if eq(parameters.ShouldPublish, 'true')}}: + - task: EsrpRelease@9 + displayName: 'Publish to ESRP' + inputs: + ConnectedServiceName: Azure SDK PME Managed Identity + Usemanagedidentity: true + DomainTenantId: 975f013f-7f24-47e8-a7d3-abc4752bf346 + ClientId: 5f81938c-2544-4f1f-9251-dd9de5b8a81b + KeyVaultName: kv-azuresdk-codesign + SignCertName: azure-sdk-esrp-release-certificate + Intent: 'PackageDistribution' + ContentType: 'Maven' + FolderLocation: ${{ parameters.FlattenedDirectory }} + Owners: ${{ coalesce(variables['Build.RequestedForEmail'], 'azuresdk@microsoft.com') }} + Approvers: ${{ coalesce(variables['Build.RequestedForEmail'], 'azuresdk@microsoft.com') }} + ServiceEndpointUrl: 'https://api.esrp.microsoft.com' + MainPublisher: 'ESRPRELPACMANTEST' diff --git a/eng/pipelines/templates/steps/java-publishing.yml b/eng/pipelines/templates/steps/java-publishing.yml deleted file mode 100644 index 040a58f7e363..000000000000 --- a/eng/pipelines/templates/steps/java-publishing.yml +++ /dev/null @@ -1,106 +0,0 @@ -parameters: - ArtifactDirectory: not-specified - OutputDirectory: not-specified - RepositoryUrl: not-specified - GroupID: - ArtifactID: - GPGExecutablePath: $(Pipeline.Workspace)/azure-sdk-build-tools/tools/gpg/bin/gpg.exe - JavaRepoRoot: $(Pipeline.Workspace)/azure-sdk-for-java - StageOnly: false - ShouldPublish: true - -steps: - - ${{if eq(parameters.Target, 'Burner')}}: - - task: PowerShell@2 - displayName: 'Publish to Burner Feed' - inputs: - pwsh: true - workingDirectory: $(Agent.BuildDirectory) - filePath: ${{ parameters.JavaRepoRoot }}/eng/scripts/Publish-MavenPackages.ps1 - arguments: > - -ArtifactDirectory ${{ parameters.ArtifactDirectory }} - -GroupIDFilter "${{ parameters.GroupID }}" - -ArtifactIDFilter "${{ parameters.ArtifactID }}" - -RepositoryUrl https://pkgs.dev.azure.com/azure-sdk/public/_packaging/azure-sdk-$(Build.BuildID)/maven/v1 - -RepositoryUsername nobody - -RepositoryPassword $(System.AccessToken) - -GPGExecutablePath ${{ parameters.GPGExecutablePath }} - -ShouldPublish:$${{parameters.ShouldPublish}} - -InformationAction Continue - - - ${{if eq(parameters.Target, 'JavaDevFeed')}}: - - task: PowerShell@2 - displayName: 'Publish to Java Dev Feed' - inputs: - pwsh: true - workingDirectory: $(Agent.BuildDirectory) - filePath: ${{ parameters.JavaRepoRoot }}/eng/scripts/Publish-MavenPackages.ps1 - arguments: > - -ArtifactDirectory ${{ parameters.ArtifactDirectory }} - -GroupIDFilter "${{ parameters.GroupID }}" - -ArtifactIDFilter "${{ parameters.ArtifactID }}" - -RepositoryUrl ${{ parameters.RepositoryUrl }} - -RepositoryUsername nobody - -RepositoryPassword $(System.AccessToken) - -GPGExecutablePath ${{ parameters.GPGExecutablePath }} - -ShouldPublish:$${{parameters.ShouldPublish}} - -InformationAction Continue - - - ${{if eq(parameters.Target, 'AndroidDevFeed')}}: - - task: PowerShell@2 - displayName: 'Publish to Andriod Public Dev Feed' - inputs: - pwsh: true - workingDirectory: $(Agent.BuildDirectory) - filePath: ${{ parameters.JavaRepoRoot }}/eng/scripts/Publish-MavenPackages.ps1 - arguments: > - -ArtifactDirectory ${{ parameters.ArtifactDirectory }} - -GroupIDFilter "${{ parameters.GroupID }}" - -ArtifactIDFilter "${{ parameters.ArtifactID }}" - -RepositoryUrl https://pkgs.dev.azure.com/azure-sdk/public/_packaging/azure-sdk-for-android/maven/v1 - -RepositoryUsername nobody - -RepositoryPassword $(System.AccessToken) - -GPGExecutablePath ${{ parameters.GPGExecutablePath }} - -ShouldPublish:$${{parameters.ShouldPublish}} - -InformationAction Continue - - - ${{if eq(parameters.Target, 'EsrpRelease')}}: - - task: PowerShell@2 - displayName: 'Gpg sign and hash packages' - inputs: - pwsh: true - workingDirectory: $(Agent.BuildDirectory) - filePath: ${{ parameters.JavaRepoRoot }}/eng/scripts/SignAndHash-MavenPackages.ps1 - arguments: > - -Path ${{ parameters.ArtifactDirectory }} - -DestinationPath ${{ parameters.OutputDirectory }} - -GroupIDFilter "${{ parameters.GroupID }}" - -ArtifactIDFilter "${{ parameters.ArtifactID }}" - -GPGExecutablePath ${{ parameters.GPGExecutablePath }} - -InformationAction Continue - - task: PowerShell@2 - displayName: 'Flatten output folder' - inputs: - pwsh: true - workingDirectory: $(Agent.BuildDirectory) - filePath: ${{ parameters.JavaRepoRoot }}/eng/scripts/Flatten-MavenPackageFolder.ps1 - arguments: > - -Path ${{ parameters.OutputDirectory }} - -InformationAction Continue - - ${{if and(eq(parameters.ShouldPublish, 'true'), ne(parameters.StageOnly, 'true'))}}: - - task: EsrpRelease@7 - displayName: 'Publish to ESRP' - inputs: - ConnectedServiceName: 'Azure SDK Engineering System' - ClientId: '5f81938c-2544-4f1f-9251-dd9de5b8a81b' - KeyVaultName: 'AzureSDKEngKeyVault' - AuthCertName: 'azure-sdk-esrp-release-auth-certificate' - SignCertName: 'azure-sdk-esrp-release-sign-certificate' - Intent: 'PackageDistribution' - ContentType: 'Maven' - FolderLocation: ${{ parameters.OutputDirectory }} - Owners: ${{ coalesce(variables['Build.RequestedForEmail'], 'azuresdk@microsoft.com') }} - Approvers: ${{ coalesce(variables['Build.RequestedForEmail'], 'azuresdk@microsoft.com') }} - ServiceEndpointUrl: 'https://api.esrp.microsoft.com' - MainPublisher: 'ESRPRELPACMANTEST' - DomainTenantId: '72f988bf-86f1-41af-91ab-2d7cd011db47' diff --git a/eng/scripts/Flatten-MavenPackageFolder.ps1 b/eng/scripts/Flatten-MavenPackageFolder.ps1 index 0448171c1738..73494df7192c 100644 --- a/eng/scripts/Flatten-MavenPackageFolder.ps1 +++ b/eng/scripts/Flatten-MavenPackageFolder.ps1 @@ -1,13 +1,24 @@ #Requires -Version 7 +# The SignedDirectory is the packages-esrp-gpg-signed directory. The contents of +# the SignedDirectory are copied to the FlattenedDirectory and then the directory +# is flattened. The FlattenedDirectory is only needed for ESRP signing's bulk +# release. The SignedDirectory will needed for feed publishing. param( - [Parameter(Mandatory=$true)][string]$Path + [Parameter(Mandatory=$true)][string]$SignedDirectory, + [Parameter(Mandatory=$true)][string]$FlattenedDirectory ) Set-StrictMode -Version 2.0 $ErrorActionPreference = "Stop" -$files = Get-ChildItem -Path $Path -Recurse -File -Force -ErrorAction Stop +$SignedDirectory = Resolve-Path $SignedDirectory +$FlattenedDirectory = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($FlattenedDirectory) + +Write-Host "Copying $SignedDirectory to $FlattenedDirectory to flatten" +Copy-Item -Path $SignedDirectory -Destination $FlattenedDirectory -Recurse + +$files = Get-ChildItem -Path $FlattenedDirectory -Recurse -File -Force -ErrorAction Stop $paths = @{} @@ -21,7 +32,7 @@ foreach($file in $files) { if($paths.Keys -contains $name) { Write-Error "Duplicate file name: $name`n $($paths[$name]) and $($file.FullName)" - Write-Error "Unable to flatten: $Path" + Write-Error "Unable to flatten: $FlattenedDirectory" exit 1 } @@ -31,11 +42,11 @@ foreach($file in $files) { # Move the files to the root of the directory. foreach($name in $paths.Keys) { $oldPath = $paths[$name] - $newPath = Join-Path -Path $Path -ChildPath $name + $newPath = Join-Path -Path $FlattenedDirectory -ChildPath $name Move-Item -Path $oldPath -Destination $newPath -Force -ErrorAction Stop } -$dirs = Get-ChildItem -Path $Path -Directory -Force -ErrorAction Stop +$dirs = Get-ChildItem -Path $FlattenedDirectory -Directory -Force -ErrorAction Stop # Remove all child directories. foreach($dir in $dirs) { diff --git a/eng/scripts/Language-Settings.ps1 b/eng/scripts/Language-Settings.ps1 index c3c5a4c4eb88..a4dfa0ca122b 100644 --- a/eng/scripts/Language-Settings.ps1 +++ b/eng/scripts/Language-Settings.ps1 @@ -13,14 +13,15 @@ $PackageRepositoryUri = "https://repo1.maven.org/maven2" # When getting all of the package properties, if Get-AllPackageInfoFromRepo exists # then it's called instead of Get-PkgPropsForEntireService. function Get-AllPackageInfoFromRepo([string]$serviceDirectory = $null) { - $SdkType = $Env:SdkType + + $SdkType = $Env:SDKTYPE if ($SdkType) { - Write-Host "SdkType env var was set to '$SdkType'" + Write-Verbose "SdkType env var was set to '$SdkType'" } else { $SdkType = "client" - Write-Host "SdkType env var was not set, default to 'client'" + Write-Verbose "SdkType env var was not set, default to 'client'" } - Write-Host "Processing SdkType=$SdkType" + Write-Verbose "Processing SdkType=$SdkType" $allPackageProps = @() $sdkRoot = Join-Path $RepoRoot "sdk" @@ -28,7 +29,7 @@ function Get-AllPackageInfoFromRepo([string]$serviceDirectory = $null) { if ($serviceDirectory) { $searchPath = Join-Path $sdkRoot $serviceDirectory - Write-Host "searchPath=$searchPath" + Write-Verbose "searchPath=$searchPath" [array]$ymlFiles = Get-ChildItem -Path $searchPath "ci*.yml" | Where-Object { $_.PSIsContainer -eq $false} } else { # The reason for the exclude folders are POM only releases (nothing is built) or @@ -56,7 +57,7 @@ function Get-AllPackageInfoFromRepo([string]$serviceDirectory = $null) { # 6a. If #5 has a match, create the PackageProp and add it to the list # 6b. If #5 doesn't have a match, then skip it. This is the case where it's either # an AdditionalModule or something from another track. - Write-Host "Processing $ymlFile" + Write-Verbose "Processing $ymlFile" $ymlFileContent = LoadFrom-Yaml $ymlFile $YmlFileSdkType = GetValueSafelyFrom-Yaml $ymlFileContent @("extends", "parameters", "SDKType") $ymlDir = Split-Path -Path $ymlFile -Parent @@ -65,7 +66,7 @@ function Get-AllPackageInfoFromRepo([string]$serviceDirectory = $null) { $YmlFileSdkType = "client" } if ($YmlFileSdkType -ne $SdkType) { - Write-Host "SdkType in yml file is '$YmlFileSdkType' which is not '$SdkType', skipping..." + Write-Verbose "SdkType in yml file is '$YmlFileSdkType' which is not '$SdkType', skipping..." continue } # ServiceDirectory @@ -125,17 +126,17 @@ function Get-AllPackageInfoFromRepo([string]$serviceDirectory = $null) { $xmlPomFile.Load($pomFile) if ($xmlPomFile.project.psobject.properties.name -notcontains "artifactId" -or !$xmlPomFile.project.artifactId) { - Write-Host "$pomFile doesn't have a defined artifactId so skipping this pom." + Write-Verbose "$pomFile doesn't have a defined artifactId so skipping this pom." continue } if ($xmlPomFile.project.psobject.properties.name -notcontains "version" -or !$xmlPomFile.project.version) { - Write-Host "$pomFile doesn't have a defined version so skipping this pom." + Write-Verbose "$pomFile doesn't have a defined version so skipping this pom." continue } if ($xmlPomFile.project.psobject.properties.name -notcontains "groupid" -or !$xmlPomFile.project.groupId) { - Write-Host "$pomFile doesn't have a defined groupId so skipping this pom." + Write-Verbose "$pomFile doesn't have a defined groupId so skipping this pom." continue } @@ -145,7 +146,7 @@ function Get-AllPackageInfoFromRepo([string]$serviceDirectory = $null) { $keyFromPom = "$($xmlPomFile.project.groupId):$($xmlPomFile.project.artifactId)" if (-not $ArtifactsHashSet.Contains($keyFromPom)) { - Write-Host "$ymlFile does not contain $($xmlPomFile.project.groupId):$($xmlPomFile.project.artifactId), skipping" + Write-Verbose "$ymlFile does not contain $($xmlPomFile.project.groupId):$($xmlPomFile.project.artifactId), skipping" continue } # At this point everything is valid @@ -193,6 +194,86 @@ function Get-AllPackageInfoFromRepo([string]$serviceDirectory = $null) { return $allPackageProps } +# Get-java-AdditionalValidationPackagesFromPackageSet is the implementation of the +# $AdditionalValidationPackagesFromPackageSetFn which is used +function Get-java-AdditionalValidationPackagesFromPackageSet { + param( + [Parameter(Mandatory=$true)] + $LocatedPackages, + [Parameter(Mandatory=$true)] + $diffObj, + [Parameter(Mandatory=$true)] + $AllPkgProps + ) + $uniqueResultSet = @() + + # this section will identify the list of packages that we should treat as + # "directly" changed for a given service level change. While that doesn't + # directly change a package within the service, I do believe we should directly include all + # packages WITHIN that service. This is because the service level file changes are likely to + # have an impact on the packages within that service. + $changedServices = @() + $targetedFiles = $diffObj.ChangedFiles + if ($diff.DeletedFiles) { + if (-not $targetedFiles) { + $targetedFiles = @() + } + $targetedFiles += $diff.DeletedFiles + } + + # The targetedFiles needs to filter out anything in the ExcludePaths + # otherwise it'll end up processing things below that it shouldn't be. + foreach ($excludePath in $diffObj.ExcludePaths) { + $targetedFiles = $targetedFiles | Where-Object { -not $_.StartsWith($excludePath) } + } + + if ($targetedFiles) { + foreach($file in $targetedFiles) { + $pathComponents = $file -split "/" + # Handle changes in the root of any sdk/. Unfortunately, changes + # in the root service directory require any and all libraries in that service directory, + # include those in a / to get added to the changed + # services. + if ($pathComponents.Length -eq 3 -and $pathComponents[0] -eq "sdk") { + $changedServices += $pathComponents[1] + } + + # For anything in the root of the sdk directory, or the repository root, just run template + if (($pathComponents.Length -eq 2 -and $pathComponents[0] -eq "sdk") -or + ($pathComponents.Length -eq 1)) { + $changedServices += "template" + } + } + # dedupe the changedServices list + $changedServices = $changedServices | Get-Unique + foreach ($changedService in $changedServices) { + # Because Java has libraries at the sdk/ and sdk// + # directories, the additional package lookup needs to for ci*.yml files where the ServiceDirectory + # equals the $changedService as well as ServiceDirectories that starts $changedService/, note the + # trailing slash is necessary. For example, if PR changes the ServiceDirectory foo and there + # exist ci.yml files with the service directories "foo/bar" and "foobar", we only want to match + # foo and foo/bar, not foobar hence the -eq $changedService and StartsWith("$changedService/") + $additionalPackages = $AllPkgProps | Where-Object { $_.ServiceDirectory -eq $changedService -or $_.ServiceDirectory.StartsWith("$changedService/")} + foreach ($pkg in $additionalPackages) { + if ($uniqueResultSet -notcontains $pkg -and $LocatedPackages -notcontains $pkg) { + # IncludedForValidation means that it's package that was indirectly included because it + # wasn't directly changed. For example, if someone changes a file in the root of sdk/core + # we add all of the core libraries that do not have direct changes as indirect packages. + $pkg.IncludedForValidation = $true + $uniqueResultSet += $pkg + } + } + } + } + + Write-Host "Returning additional packages for validation: $($uniqueResultSet.Count)" + foreach ($pkg in $uniqueResultSet) { + Write-Host " - $($pkg.Name)" + } + + return $uniqueResultSet +} + # Returns the maven (really sonatype) publish status of a package id and version. function IsMavenPackageVersionPublished($pkgId, $pkgVersion, $groupId) { @@ -382,8 +463,8 @@ function Get-java-GithubIoDocIndex() # Fetch out all package metadata from csv file. $metadata = Get-CSVMetadata -MetadataUri $MetadataUri # Leave the track 2 packages if multiple packages fetched out. - $clientPackages = $metadata | Where-Object { $_.GroupId -eq 'com.azure' } - $nonClientPackages = $metadata | Where-Object { $_.GroupId -ne 'com.azure' -and !$clientPackages.Package.Contains($_.Package) } + $clientPackages = $metadata | Where-Object { $_.GroupId -eq 'com.azure' -or $_.GroupId -eq 'com.azure.v2' } + $nonClientPackages = $metadata | Where-Object { $_.GroupId -ne 'com.azure' -and $_.GroupId -ne 'com.azure.v2' -and !$clientPackages.Package.Contains($_.Package) } $uniquePackages = $clientPackages + $nonClientPackages # Get the artifacts name from blob storage $artifacts = Get-BlobStorage-Artifacts ` @@ -474,7 +555,7 @@ function GetExistingPackageVersions ($PackageName, $GroupId=$null) $response = (Invoke-RestMethod -Method GET -Uri $Uri).response if($response.numFound -ne 0) { - $existingVersion = $response.docs.v + $existingVersion = @($response.docs.v) if ($existingVersion.Count -gt 0) { [Array]::Reverse($existingVersion) @@ -565,4 +646,3 @@ function Get-java-ApiviewStatusCheckRequirement($packageInfo) { } return $false } - diff --git a/eng/scripts/Stage-MavenPackageArtifacts.ps1 b/eng/scripts/Stage-MavenPackageArtifacts.ps1 index c8c64084c117..e5138fc45d22 100644 --- a/eng/scripts/Stage-MavenPackageArtifacts.ps1 +++ b/eng/scripts/Stage-MavenPackageArtifacts.ps1 @@ -1,7 +1,8 @@ param( [Parameter(Mandatory=$true)][string]$SourceDirectory, [Parameter(Mandatory=$true)][string]$TargetDirectory, - [Parameter(Mandatory=$true)][array]$Artifacts + [Parameter(Mandatory=$false)][array]$Artifacts, + [Parameter(Mandatory=$false)][string] $PackageInfoDir = $null ) $ErrorActionPreference = "Stop" @@ -11,6 +12,28 @@ Write-host "Target Directory is: $TargetDirectory" . $PSScriptRoot\MavenPackaging.ps1 +if ($Artifacts -eq $null) { + $Artifacts = @() +} + +if ($Artifacts.Count -eq 0) { + if (-not $PackageInfoDir -or (-not (Test-Path -Path $PackageInfoDir))) { + LogError "Artifacts list was empty and PackageInfoDir was null or incorrect." + exit(1) + } + Write-Host "Artifacts List was empty, getting Artifacts from PackageInfoDir=$PackageInfoDir" + [array]$packageInfoFiles = Get-ChildItem -Path $PackageInfoDir "*.json" + foreach($packageInfoFile in $packageInfoFiles) { + $packageInfoJson = Get-Content $packageInfoFile -Raw + $packageInfo = ConvertFrom-Json $packageInfoJson + $Artifacts += New-Object PSObject -Property @{ + groupId = $packageInfo.Group + name = $packageInfo.ArtifactName + } + + } +} + Write-Host "Searching for packages in: $SourceDirectory" $packageDetails = Get-MavenPackageDetails -ArtifactDirectory $SourceDirectory Write-Host "Found $($packageDetails.Count) packages in: $SourceDirectory" diff --git a/eng/scripts/TypeSpec-Compare-CurrentToCodegeneration.ps1 b/eng/scripts/TypeSpec-Compare-CurrentToCodegeneration.ps1 index 8fc41484070b..ba2997fab292 100644 --- a/eng/scripts/TypeSpec-Compare-CurrentToCodegeneration.ps1 +++ b/eng/scripts/TypeSpec-Compare-CurrentToCodegeneration.ps1 @@ -82,7 +82,8 @@ Verify no diff " # prevent warning related to EOL differences which triggers an exception for some reason -git -c core.safecrlf=false diff --ignore-space-at-eol --exit-code -- "*.java" ":(exclude)**/src/test/**" ":(exclude)**/src/samples/**" ":(exclude)**/src/main/**/implementation/**" +git -c core.safecrlf=false diff --ignore-space-at-eol --exit-code -- "*.java" ":(exclude)**/src/test/**" ": +(exclude)**/src/samples/**" ":(exclude)**/src/main/**/implementation/**" ":(exclude)**/src/main/**/resourcemanager/**/*Manager.java" if ($LastExitCode -ne 0) { $status = git status -s | Out-String diff --git a/eng/scripts/Verify-Required-Maven-Artifacts.ps1 b/eng/scripts/Verify-Required-Maven-Artifacts.ps1 index c936aab2254c..d3d1d4c85e8b 100644 --- a/eng/scripts/Verify-Required-Maven-Artifacts.ps1 +++ b/eng/scripts/Verify-Required-Maven-Artifacts.ps1 @@ -9,7 +9,8 @@ param( [Parameter(Mandatory=$true)][string]$BuildOutputDirectory, # ArtifactsList will be using ('${{ convertToJson(parameters.Artifacts) }}' | ConvertFrom-Json | Select-Object name, groupId) - [Parameter(Mandatory=$true)][array] $ArtifactsList + [Parameter(Mandatory=$false)][array] $ArtifactsList, + [Parameter(Mandatory=$false)][string] $PackageInfoDir = $null ) . "${PSScriptRoot}/../common/scripts/common.ps1" @@ -17,6 +18,28 @@ Write-Host "BuildOutputDirectory=$($BuildOutputDirectory)" Write-Host "BuildOutputDirectory contents" Get-ChildItem -Path $BuildOutputDirectory -Recurse -Name +if (-not $ArtifactsList) { + $ArtifactsList = @() +} + +if ($ArtifactsList.Count -eq 0) { + if (-not $PackageInfoDir -or (-not (Test-Path -Path $PackageInfoDir))) { + LogError "ArtifactsList was empty and PackageInfoDir was null or incorrect." + exit(1) + } + Write-Host "Artifacts List was empty, getting Artifacts from PackageInfoDir=$PackageInfoDir" + [array]$packageInfoFiles = Get-ChildItem -Path $PackageInfoDir "*.json" + foreach($packageInfoFile in $packageInfoFiles) { + $packageInfoJson = Get-Content $packageInfoFile -Raw + $packageInfo = ConvertFrom-Json $packageInfoJson + $ArtifactsList += New-Object PSObject -Property @{ + groupId = $packageInfo.Group + name = $packageInfo.ArtifactName + } + + } +} + Write-Host "" Write-Host "ArtifactsList:" $ArtifactsList | Format-Table -Property GroupId, Name | Out-String | Write-Host diff --git a/eng/scripts/generate_aggregate_pom.py b/eng/scripts/generate_aggregate_pom.py index e6b6e8d2c1bb..4fb546a20f88 100644 --- a/eng/scripts/generate_aggregate_pom.py +++ b/eng/scripts/generate_aggregate_pom.py @@ -22,10 +22,10 @@ from pom_helper import * # azure-client-sdk-parent valid parent POMs for Track 2 libraries. -valid_parents = ['com.azure:azure-client-sdk-parent', 'io.clientcore:clientcore-parent'] +valid_parents = ['com.azure:azure-client-sdk-parent', 'com.azure.v2:azure-client-sdk-parent', 'io.clientcore:clientcore-parent'] # List of parent POMs that should be retained as projects to create POM. -parent_pom_identifiers = ['com.azure:azure-sdk-parent', 'com.azure:azure-client-sdk-parent', 'com.azure:azure-perf-test-parent', 'io.clientcore:clientcore-parent'] +parent_pom_identifiers = ['com.azure:azure-sdk-parent', 'com.azure:azure-client-sdk-parent', 'com.azure.v2:azure-client-sdk-parent', 'com.azure:azure-perf-test-parent', 'io.clientcore:clientcore-parent'] include_groups = [] @@ -100,6 +100,7 @@ def create_aggregate_pom(project_list: str, groups: str, exclude_project_list: s if groups is None: include_groups.append('com.azure') + include_groups.append('com.azure.v2') include_groups.append('com.azure.spring') include_groups.append('com.azure.resourcemanager') include_groups.append('io.clientcore') diff --git a/eng/scripts/generate_from_source_pom.py b/eng/scripts/generate_from_source_pom.py index 2eecf8feee5a..f6281e5e85e3 100644 --- a/eng/scripts/generate_from_source_pom.py +++ b/eng/scripts/generate_from_source_pom.py @@ -26,6 +26,7 @@ import argparse from datetime import timedelta import os +import glob import time import json from typing import Dict, Iterable, Set @@ -36,10 +37,10 @@ # azure-client-sdk-parent, azure-perf-test-parent, spring-boot-starter-parent, and azure-spring-boot-test-parent are # valid parent POMs for Track 2 libraries. -valid_parents = ['com.azure:azure-client-sdk-parent', 'com.azure:azure-perf-test-parent', 'org.springframework.boot:spring-boot-starter-parent', 'com.azure.spring:azure-spring-boot-test-parent', 'com.azure.cosmos.spark:azure-cosmos-spark_3_2-12', 'io.clientcore:clientcore-parent'] +valid_parents = ['com.azure:azure-client-sdk-parent', 'com.azure.v2:azure-client-sdk-parent', 'com.azure:azure-perf-test-parent', 'org.springframework.boot:spring-boot-starter-parent', 'com.azure.spring:azure-spring-boot-test-parent', 'com.azure.cosmos.spark:azure-cosmos-spark_3_2-12', 'io.clientcore:clientcore-parent'] # List of parent POMs that should be retained as projects to create a full from source POM. -parent_pom_identifiers = ['com.azure:azure-sdk-parent', 'com.azure:azure-client-sdk-parent', 'com.azure:azure-perf-test-parent', 'com.azure.spring:azure-spring-boot-test-parent', 'io.clientcore:clientcore-parent'] +parent_pom_identifiers = ['com.azure:azure-sdk-parent', 'com.azure:azure-client-sdk-parent', 'com.azure.v2:azure-client-sdk-parent', 'com.azure:azure-perf-test-parent', 'com.azure.spring:azure-spring-boot-test-parent', 'io.clientcore:clientcore-parent'] # From this file get to the root path of the repo. root_path = os.path.normpath(os.path.abspath(__file__) + '/../../../') @@ -52,6 +53,15 @@ sdk_string = "/sdk/" +# Normally, this wouldn't be necessary but because sdk/core/ci.v2.yml exists it's necessary +def proj_path_has_yml(proj_path): + file_pattern = "ci*.yml" + matching_paths = glob.glob(file_pattern, root_dir=proj_path) + if matching_paths: + return True + else: + return False + # Function that creates the aggregate POM. def create_from_source_pom(artifacts_list: str, additional_modules_list: str, set_skip_linting_projects: str, match_any_version: bool): artifacts_list_identifiers = artifacts_list.split(',') @@ -113,12 +123,18 @@ def create_from_source_pom(artifacts_list: str, additional_modules_list: str, se # the directory path needs to be added to the sparse checkout, otherwise it's one # directory up. proj_path = os.path.normpath(root_path + p.directory_path ) - proj_path_with_yml = os.path.normpath(proj_path + "/ci.yml") - if os.path.exists(proj_path_with_yml): - sparse_checkout_directory = p.directory_path + if proj_path_has_yml(proj_path): + yml_directory = p.directory_path else: - sparse_checkout_directory = '/'.join(p.directory_path.split('/')[0:-1]) - + yml_directory = '/'.join(p.directory_path.split('/')[0:-1]) + + # This is temporary, the sparse checkout directories should be the same directory where the yml + # file lives but needs to be the sdk/. The reason being that there are directories + # whose ci.yml is in the library directory but there are dependencies on other directories in the + # service directory, outside of their library directory. ex. several communication libraries + # use sdk/communication/test-resources or sdk/clientcore/annotation-processor's ci.yml file + # needs sdk/clientcore/annotation-processor-test + sparse_checkout_directory = '/'.join(p.directory_path.split('/')[0:-1]) sparse_checkout_directories.add(sparse_checkout_directory) # The ServiceDirectories list should only ever contain the list of service @@ -127,8 +143,8 @@ def create_from_source_pom(artifacts_list: str, additional_modules_list: str, se # Sparse checkout directories can contain directories that aren't service directories. # (aka. /common). Any service directory will start with "/sdk/", everything else is # would be attributed to supporting libraries (ex. perf-test-core). - if sdk_string in sparse_checkout_directory: - service_directory = sparse_checkout_directory.replace(sdk_string, "") + if sdk_string in yml_directory: + service_directory = yml_directory.replace(sdk_string, "") service_directories.add(service_directory) # output the SparseCheckoutDirectories environment variable @@ -315,6 +331,8 @@ def project_uses_client_parent(project: Project, projects: Dict[str, Project]) - while project.parent_pom is not None: if project.parent_pom == 'com.azure:azure-client-sdk-parent': return True + if project.parent_pom == 'com.azure.v2:azure-client-sdk-parent': + return True if project.parent_pom == 'io.clientcore:clientcore-parent': return True project = projects.get(project.parent_pom, default_project) diff --git a/eng/versioning/external_dependencies.txt b/eng/versioning/external_dependencies.txt index 4d8b3ad22136..c9dbf7a17237 100644 --- a/eng/versioning/external_dependencies.txt +++ b/eng/versioning/external_dependencies.txt @@ -16,6 +16,7 @@ com.fasterxml.jackson.core:jackson-core;2.17.2 com.fasterxml.jackson.core:jackson-databind;2.17.2 com.fasterxml.jackson.dataformat:jackson-dataformat-avro;2.17.2 com.fasterxml.jackson.dataformat:jackson-dataformat-xml;2.17.2 +com.fasterxml.jackson.dataformat:jackson-dataformat-smile;2.17.2 com.fasterxml.jackson.datatype:jackson-datatype-jsr310;2.17.2 com.fasterxml.jackson.module:jackson-module-afterburner;2.17.2 com.fasterxml.jackson.module:jackson-module-blackbird;2.17.2 @@ -38,31 +39,29 @@ com.microsoft.azure:azure-functions-maven-plugin;1.30.0 com.microsoft.azure.functions:azure-functions-java-library;2.2.0 com.mysql:mysql-connector-j;9.0.0 com.squareup.okhttp3:okhttp;4.12.0 -com.squareup:javapoet;1.13.0 commons-codec:commons-codec;1.15 commons-net:commons-net;3.9.0 -io.clientcore.tools:annotation-processor;1.0.0-beta.1 io.cloudevents:cloudevents-api;2.2.0 io.cloudevents:cloudevents-core;2.2.0 io.fabric8:kubernetes-client;6.12.1 io.micrometer:micrometer-core;1.9.17 io.micrometer:micrometer-registry-azure-monitor;1.9.17 io.micrometer:micrometer-registry-graphite;1.9.17 -io.netty:netty-buffer;4.1.115.Final -io.netty:netty-common;4.1.115.Final -io.netty:netty-codec;4.1.115.Final -io.netty:netty-codec-http;4.1.115.Final -io.netty:netty-codec-http2;4.1.115.Final -io.netty:netty-handler;4.1.115.Final -io.netty:netty-handler-proxy;4.1.115.Final -io.netty:netty-tcnative-boringssl-static;2.0.69.Final -io.netty:netty-transport-native-epoll;4.1.115.Final -io.netty:netty-transport-native-unix-common;4.1.115.Final -io.netty:netty-transport-native-kqueue;4.1.115.Final +io.netty:netty-buffer;4.1.118.Final +io.netty:netty-common;4.1.118.Final +io.netty:netty-codec;4.1.118.Final +io.netty:netty-codec-http;4.1.118.Final +io.netty:netty-codec-http2;4.1.118.Final +io.netty:netty-handler;4.1.118.Final +io.netty:netty-handler-proxy;4.1.118.Final +io.netty:netty-tcnative-boringssl-static;2.0.70.Final +io.netty:netty-transport-native-epoll;4.1.118.Final +io.netty:netty-transport-native-unix-common;4.1.118.Final +io.netty:netty-transport-native-kqueue;4.1.118.Final io.projectreactor.netty:reactor-netty-http;1.0.48 io.projectreactor:reactor-core;3.4.41 -io.vertx:vertx-codegen;4.5.10 -io.vertx:vertx-core;4.5.10 +io.vertx:vertx-codegen;4.5.13 +io.vertx:vertx-core;4.5.13 javax.websocket:javax.websocket-api;1.1 org.apache.commons:commons-compress;1.26.0 org.apache.ant:ant;1.10.14 @@ -85,8 +84,9 @@ org.conscrypt:conscrypt-openjdk-uber;2.5.2 org.glassfish.tyrus:tyrus-client;1.16 org.openjfx:javafx-graphics;17.0.6 org.graalvm.buildtools:junit-platform-native;0.9.19 -org.graalvm.buildtools:native-maven-plugin;0.9.19 +org.graalvm.buildtools:native-maven-plugin;0.10.5 org.postgresql:postgresql;42.3.9 +org.projectlombok:lombok;1.18.34 org.slf4j:slf4j-api;1.7.36 org.slf4j:slf4j-nop;1.7.36 org.slf4j:slf4j-simple;1.7.36 @@ -95,10 +95,10 @@ io.lettuce:lettuce-core;6.4.0.RELEASE org.redisson:redisson;3.36.0 testdep_net.bytebuddy:byte-buddy;1.15.5 testdep_net.bytebuddy:byte-buddy-agent;1.15.5 +org.openrewrite.recipe:rewrite-recipe-bom;3.0.2 ## Spring boot dependency versions org.springframework.boot:spring-boot-maven-plugin;2.7.18 -org.springframework.boot:spring-boot-starter-test;2.7.18 org.springframework.boot:spring-boot-starter;2.7.18 org.springframework:spring-core;5.3.32 org.springframework.boot:spring-boot-starter-parent;2.7.18 @@ -113,22 +113,22 @@ com.microsoft.azure:azure-mgmt-graph-rbac;1.3.0 com.microsoft.azure:azure-mgmt-network;1.33.0 com.microsoft.azure:azure-mgmt-resources;1.3.0 com.microsoft.azure:azure-storage;8.0.0 -com.microsoft.azure:msal4j;1.17.2 +com.microsoft.azure:msal4j;1.19.1 com.microsoft.azure:msal4j-brokers;1.0.0 com.microsoft.azure:msal4j-persistence-extension;1.3.0 -io.opentelemetry:opentelemetry-api;1.43.0 -io.opentelemetry:opentelemetry-sdk;1.43.0 -io.opentelemetry:opentelemetry-sdk-metrics;1.43.0 -io.opentelemetry:opentelemetry-sdk-logs;1.43.0 -io.opentelemetry:opentelemetry-exporter-logging;1.43.0 -io.opentelemetry:opentelemetry-exporter-otlp;1.43.0 -io.opentelemetry:opentelemetry-sdk-testing;1.43.0 -io.opentelemetry:opentelemetry-sdk-extension-autoconfigure;1.43.0 -io.opentelemetry:opentelemetry-sdk-extension-autoconfigure-spi;1.43.0 -io.opentelemetry:opentelemetry-bom;1.43.0 -io.opentelemetry.instrumentation:opentelemetry-runtime-telemetry-java8;2.9.0-alpha -io.opentelemetry.instrumentation:opentelemetry-spring-boot-starter;2.9.0 -io.opentelemetry.instrumentation:opentelemetry-logback-appender-1.0;2.9.0-alpha +io.opentelemetry:opentelemetry-api;1.46.0 +io.opentelemetry:opentelemetry-sdk;1.46.0 +io.opentelemetry:opentelemetry-sdk-metrics;1.46.0 +io.opentelemetry:opentelemetry-sdk-logs;1.46.0 +io.opentelemetry:opentelemetry-exporter-logging;1.46.0 +io.opentelemetry:opentelemetry-exporter-otlp;1.46.0 +io.opentelemetry:opentelemetry-sdk-testing;1.46.0 +io.opentelemetry:opentelemetry-sdk-extension-autoconfigure;1.46.0 +io.opentelemetry:opentelemetry-sdk-extension-autoconfigure-spi;1.46.0 +io.opentelemetry:opentelemetry-bom;1.46.0 +io.opentelemetry.instrumentation:opentelemetry-runtime-telemetry-java8;2.12.0-alpha +io.opentelemetry.instrumentation:opentelemetry-spring-boot-starter;2.12.0 +io.opentelemetry.instrumentation:opentelemetry-logback-appender-1.0;2.12.0-alpha io.opentelemetry.semconv:opentelemetry-semconv-incubating;1.26.0-alpha io.projectreactor:reactor-test;3.4.41 io.github.hakky54:logcaptor;2.9.3 @@ -171,6 +171,7 @@ io.reactivex.rxjava2:rxjava;2.2.21 net.java.dev.jna:jna-platform;5.13.0 net.oneandone.reflections8:reflections8;0.11.7 net.jonathangiles.tools:dependencyChecker-maven-plugin;1.0.6 +net.bytebuddy:byte-buddy;1.14.10 org.apache.commons:commons-collections4;4.4 org.apache.commons:commons-text;1.10.0 org.apache.maven:maven-plugin-api;3.9.9 @@ -178,27 +179,27 @@ org.apache.maven:maven-project;2.2.1 org.apache.maven.plugin-tools:maven-plugin-annotations;3.15.0 org.apache.maven.plugins:maven-antrun-plugin;3.1.0 org.apache.maven.plugins:maven-assembly-plugin;3.7.1 -org.apache.maven.plugins:maven-checkstyle-plugin;3.5.0 +org.apache.maven.plugins:maven-checkstyle-plugin;3.6.0 org.apache.maven.plugins:maven-clean-plugin;3.4.0 org.apache.maven.plugins:maven-compiler-plugin;3.13.0 org.apache.maven.plugins:maven-enforcer-plugin;3.5.0 -org.apache.maven.plugins:maven-failsafe-plugin;3.5.1 +org.apache.maven.plugins:maven-failsafe-plugin;3.5.2 org.apache.maven.plugins:maven-help-plugin;3.5.0 org.apache.maven.plugins:maven-install-plugin;3.1.3 org.apache.maven.plugins:maven-jar-plugin;3.4.2 org.apache.maven.plugins:maven-javadoc-plugin;3.10.1 org.apache.maven.plugins:maven-jxr-plugin;3.5.0 org.apache.maven.plugins:maven-plugin-plugin;3.15.0 -org.apache.maven.plugins:maven-project-info-reports-plugin;3.7.0 +org.apache.maven.plugins:maven-project-info-reports-plugin;3.8.0 org.apache.maven.plugins:maven-release-plugin;3.1.1 org.apache.maven.plugins:maven-resources-plugin;3.3.1 org.apache.maven.plugins:maven-shade-plugin;3.6.0 org.apache.maven.plugins:maven-site-plugin;3.20.0 org.apache.maven.plugins:maven-source-plugin;3.3.1 -org.apache.maven.plugins:maven-surefire-plugin;3.5.1 +org.apache.maven.plugins:maven-surefire-plugin;3.5.2 org.codehaus.mojo:animal-sniffer-maven-plugin;1.24 org.codehaus.mojo:build-helper-maven-plugin;3.6.0 -org.codehaus.mojo:exec-maven-plugin;3.4.1 +org.codehaus.mojo:exec-maven-plugin;3.5.0 org.codehaus.mojo:xml-maven-plugin;1.1.0 org.eclipse.jetty:jetty-maven-plugin;9.4.33.v20201020 org.eclipse.m2e:lifecycle-mapping;1.0.0 @@ -207,11 +208,12 @@ org.jacoco:org.jacoco.agent;0.8.12 org.mockito:mockito-core;4.11.0 org.mockito:mockito-inline;4.11.0 org.moditect:moditect-maven-plugin;1.0.0.RC1 -org.ow2.asm:asm;9.7 +org.owasp:dependency-check-maven;11.1.1 +org.ow2.asm:asm;9.7.1 org.revapi:revapi;0.14.4 org.revapi:revapi-java;0.26.1 org.revapi:revapi-java-spi;0.23.6 -org.revapi:revapi-reporter-json;0.4.5 +org.revapi:revapi-reporter-json;0.5.0 org.revapi:revapi-maven-plugin;0.14.6 # External Dependency Exceptions @@ -220,6 +222,16 @@ org.revapi:revapi-maven-plugin;0.14.6 # Format; # _groupId:artifactId;dependency-version +# The OpenTelemetry exporter is replaced with the OpenTelemetry SDK Autoconfigure Distro +otel_exporter_deprecated_io.opentelemetry:opentelemetry-api;1.43.0 +otel_exporter_deprecated_io.opentelemetry:opentelemetry-sdk;1.43.0 +otel_exporter_deprecated_io.opentelemetry:opentelemetry-sdk-metrics;1.43.0 +otel_exporter_deprecated_io.opentelemetry:opentelemetry-sdk-logs;1.43.0 +otel_exporter_deprecated_io.opentelemetry:opentelemetry-sdk-extension-autoconfigure-spi;1.43.0 +otel_exporter_deprecated_io.opentelemetry:opentelemetry-sdk-extension-autoconfigure;1.43.0 +otel_exporter_deprecated_io.opentelemetry:opentelemetry-sdk-testing;1.43.0 +otel_exporter_deprecated_io.opentelemetry.semconv:opentelemetry-semconv-incubating;1.26.0-alpha + # This is a unique dependency as it is the only test-jar dependency in the # data track. It's also using a SNAPSHOT version which should be disallowed but there is # going to be some investigation necessary to find, at the very least, a newer version @@ -320,17 +332,17 @@ springboot3_com.github.spotbugs:spotbugs-maven-plugin;4.8.2.0 springboot3_com.google.code.findbugs:jsr305;3.0.2 springboot3_com.mysql:mysql-connector-j;9.1.0 springboot3_com.nimbusds:nimbus-jose-jwt;9.37.3 -springboot3_io.lettuce:lettuce-core;6.4.1.RELEASE -springboot3_io.micrometer:micrometer-core;1.14.2 -springboot3_io.netty:netty-buffer;4.1.116.Final -springboot3_io.netty:netty-codec-http;4.1.116.Final -springboot3_io.netty:netty-common;4.1.116.Final -springboot3_io.netty:netty-handler;4.1.116.Final -springboot3_io.netty:netty-transport-native-epoll;4.1.116.Final -springboot3_io.netty:netty-transport-native-kqueue;4.1.116.Final -springboot3_io.netty:netty-transport;4.1.116.Final -springboot3_io.projectreactor.netty:reactor-netty;1.2.1 -springboot3_io.projectreactor:reactor-test;3.7.1 +springboot3_io.lettuce:lettuce-core;6.4.2.RELEASE +springboot3_io.micrometer:micrometer-core;1.14.3 +springboot3_io.netty:netty-buffer;4.1.117.Final +springboot3_io.netty:netty-codec-http;4.1.117.Final +springboot3_io.netty:netty-common;4.1.117.Final +springboot3_io.netty:netty-handler;4.1.117.Final +springboot3_io.netty:netty-transport-native-epoll;4.1.117.Final +springboot3_io.netty:netty-transport-native-kqueue;4.1.117.Final +springboot3_io.netty:netty-transport;4.1.117.Final +springboot3_io.projectreactor.netty:reactor-netty;1.2.2 +springboot3_io.projectreactor:reactor-test;3.7.2 springboot3_jakarta.servlet:jakarta.servlet-api;6.0.0 springboot3_jakarta.validation:jakarta.validation-api;3.0.2 springboot3_javax.annotation:javax.annotation-api;1.3.2 @@ -353,58 +365,58 @@ springboot3_org.junit.jupiter:junit-jupiter;5.11.4 springboot3_org.junit.vintage:junit-vintage-engine;5.11.4 springboot3_org.messaginghub:pooled-jms;3.1.7 springboot3_org.mockito:mockito-core;5.14.2 -springboot3_org.postgresql:postgresql;42.7.4 +springboot3_org.postgresql:postgresql;42.7.5 springboot3_org.revapi:revapi-maven-plugin;0.14.6 springboot3_org.slf4j:slf4j-api;2.0.16 springboot3_org.slf4j:slf4j-simple;2.0.16 -springboot3_org.springframework.boot:spring-boot-actuator-autoconfigure;3.4.1 -springboot3_org.springframework.boot:spring-boot-actuator;3.4.1 -springboot3_org.springframework.boot:spring-boot-autoconfigure;3.4.1 -springboot3_org.springframework.boot:spring-boot-configuration-metadata;3.4.1 -springboot3_org.springframework.boot:spring-boot-configuration-processor;3.4.1 -springboot3_org.springframework.boot:spring-boot-docker-compose;3.4.1 -springboot3_org.springframework.boot:spring-boot-starter-actuator;3.4.1 -springboot3_org.springframework.boot:spring-boot-starter-data-jdbc;3.4.1 -springboot3_org.springframework.boot:spring-boot-starter-integration;3.4.1 -springboot3_org.springframework.boot:spring-boot-starter-parent;3.4.1 -springboot3_org.springframework.boot:spring-boot-starter-test;3.4.1 -springboot3_org.springframework.boot:spring-boot-starter-web;3.4.1 -springboot3_org.springframework.boot:spring-boot-starter;3.4.1 -springboot3_org.springframework.boot:spring-boot-test;3.4.1 -springboot3_org.springframework.boot:spring-boot-testcontainers;3.4.1 +springboot3_org.springframework.boot:spring-boot-actuator-autoconfigure;3.4.2 +springboot3_org.springframework.boot:spring-boot-actuator;3.4.2 +springboot3_org.springframework.boot:spring-boot-autoconfigure;3.4.2 +springboot3_org.springframework.boot:spring-boot-configuration-metadata;3.4.2 +springboot3_org.springframework.boot:spring-boot-configuration-processor;3.4.2 +springboot3_org.springframework.boot:spring-boot-docker-compose;3.4.2 +springboot3_org.springframework.boot:spring-boot-starter-actuator;3.4.2 +springboot3_org.springframework.boot:spring-boot-starter-data-jdbc;3.4.2 +springboot3_org.springframework.boot:spring-boot-starter-integration;3.4.2 +springboot3_org.springframework.boot:spring-boot-starter-parent;3.4.2 +springboot3_org.springframework.boot:spring-boot-starter-test;3.4.2 +springboot3_org.springframework.boot:spring-boot-starter-web;3.4.2 +springboot3_org.springframework.boot:spring-boot-starter;3.4.2 +springboot3_org.springframework.boot:spring-boot-test;3.4.2 +springboot3_org.springframework.boot:spring-boot-testcontainers;3.4.2 springboot3_org.springframework.cloud:spring-cloud-bus;4.2.0 springboot3_org.springframework.cloud:spring-cloud-context;4.2.0 springboot3_org.springframework.cloud:spring-cloud-starter-bootstrap;4.2.0 springboot3_org.springframework.cloud:spring-cloud-starter-stream-kafka;4.2.0 springboot3_org.springframework.cloud:spring-cloud-stream-test-binder;4.2.0 springboot3_org.springframework.cloud:spring-cloud-stream;4.2.0 -springboot3_org.springframework.data:spring-data-commons;3.4.1 -springboot3_org.springframework.data:spring-data-redis;3.4.1 +springboot3_org.springframework.data:spring-data-commons;3.4.2 +springboot3_org.springframework.data:spring-data-redis;3.4.2 springboot3_org.springframework.integration:spring-integration-core;6.4.1 -springboot3_org.springframework.kafka:spring-kafka;3.3.1 +springboot3_org.springframework.kafka:spring-kafka;3.3.2 springboot3_org.springframework.retry:spring-retry;2.0.11 springboot3_org.springframework.security:spring-security-config;6.4.2 springboot3_org.springframework.security:spring-security-oauth2-client;6.4.2 springboot3_org.springframework.security:spring-security-oauth2-jose;6.4.2 springboot3_org.springframework.security:spring-security-oauth2-resource-server;6.4.2 springboot3_org.springframework.security:spring-security-web;6.4.2 -springboot3_org.springframework:spring-beans;6.2.1 -springboot3_org.springframework:spring-context-support;6.2.1 -springboot3_org.springframework:spring-context;6.2.1 -springboot3_org.springframework:spring-core-test;6.2.1 -springboot3_org.springframework:spring-core;6.2.1 -springboot3_org.springframework:spring-expression;6.2.1 -springboot3_org.springframework:spring-jdbc;6.2.1 -springboot3_org.springframework:spring-jms;6.2.1 -springboot3_org.springframework:spring-messaging;6.2.1 -springboot3_org.springframework:spring-test;6.2.1 -springboot3_org.springframework:spring-tx;6.2.1 -springboot3_org.springframework:spring-web;6.2.1 -springboot3_org.springframework:spring-webmvc;6.2.1 +springboot3_org.springframework:spring-beans;6.2.2 +springboot3_org.springframework:spring-context-support;6.2.2 +springboot3_org.springframework:spring-context;6.2.2 +springboot3_org.springframework:spring-core-test;6.2.2 +springboot3_org.springframework:spring-core;6.2.2 +springboot3_org.springframework:spring-expression;6.2.2 +springboot3_org.springframework:spring-jdbc;6.2.2 +springboot3_org.springframework:spring-jms;6.2.2 +springboot3_org.springframework:spring-messaging;6.2.2 +springboot3_org.springframework:spring-test;6.2.2 +springboot3_org.springframework:spring-tx;6.2.2 +springboot3_org.springframework:spring-web;6.2.2 +springboot3_org.springframework:spring-webmvc;6.2.2 springboot3_org.testcontainers:junit-jupiter;1.20.4 springboot3_org.testcontainers:azure;1.20.4 # Used for Spring version updates -springboot3_org.springframework.boot:spring-boot-dependencies;3.4.1 +springboot3_org.springframework.boot:spring-boot-dependencies;3.4.2 springboot3_org.springframework.cloud:spring-cloud-dependencies;2024.0.0 # Java 7 support diff --git a/eng/versioning/pom_file_version_scanner.ps1 b/eng/versioning/pom_file_version_scanner.ps1 index 891796ab7f55..d638bbce7e4e 100644 --- a/eng/versioning/pom_file_version_scanner.ps1 +++ b/eng/versioning/pom_file_version_scanner.ps1 @@ -68,7 +68,7 @@ $StartTime = $(get-date) # This is the for the bannedDependencies include exceptions. All entries need to be of the # form groupId:artifactId:[version] which locks to a specific version. The exception # to this is the blanket, wildcard include for com.azure and com.microsoft.azure libraries. -$ComAzureAllowlistIncludes = ("com.azure:*", "com.azure.resourcemanager:*", "com.microsoft.azure:*", "com.azure.spring:*", "io.clientcore:*") +$ComAzureAllowlistIncludes = ("com.azure:*", "com.azure.v2:*", "com.azure.resourcemanager:*", "com.microsoft.azure:*", "com.azure.spring:*", "io.clientcore:*") function Join-With-NewLine([string]$msg, [string]$append) { diff --git a/eng/versioning/set_versions.py b/eng/versioning/set_versions.py index f16eb87557ee..c813b2a1560c 100644 --- a/eng/versioning/set_versions.py +++ b/eng/versioning/set_versions.py @@ -46,7 +46,7 @@ from utils import prerelease_version_regex_with_name # some things that should not be updated for devops builds, in the case where everything is being updated in one call -items_we_should_not_update = ['com.azure:azure-sdk-all', 'com.azure:azure-sdk-parent', 'com.azure:azure-client-sdk-parent', 'com.azure:azure-data-sdk-parent', 'com.azure:azure-perf-test-parent', 'com.azure:azure-code-customization-parent', 'io.clientcore:clientcore-parent'] +items_we_should_not_update = ['com.azure:azure-sdk-all', 'com.azure:azure-sdk-parent', 'com.azure:azure-client-sdk-parent', 'com.azure.v2:azure-client-sdk-parent', 'com.azure:azure-data-sdk-parent', 'com.azure:azure-perf-test-parent', 'com.azure:azure-code-customization-parent', 'io.clientcore:clientcore-parent'] # The regex string we want should be the anchored one since the entire string is what's being matched version_regex_named = re.compile(version_regex_str_with_names_anchored) diff --git a/eng/versioning/version_client.txt b/eng/versioning/version_client.txt index ff74e7f0200d..da5402dff32f 100644 --- a/eng/versioning/version_client.txt +++ b/eng/versioning/version_client.txt @@ -36,21 +36,21 @@ com.azure:azure-sdk-parent;1.6.0;1.6.0 com.azure:azure-client-sdk-parent;1.7.0;1.7.0 com.azure:azure-ai-anomalydetector;3.0.0-beta.5;3.0.0-beta.6 -com.azure:azure-ai-contentsafety;1.0.9;1.1.0-beta.1 -com.azure:azure-ai-documentintelligence;1.0.0-beta.4;1.0.0 +com.azure:azure-ai-contentsafety;1.0.10;1.1.0-beta.1 +com.azure:azure-ai-documentintelligence;1.0.0;1.1.0-beta.1 com.azure:azure-ai-documenttranslator;1.0.0-beta.1;1.0.0-beta.2 -com.azure:azure-ai-formrecognizer;4.1.12;4.2.0-beta.1 +com.azure:azure-ai-formrecognizer;4.1.13;4.2.0-beta.1 com.azure:azure-ai-formrecognizer-perf;1.0.0-beta.1;1.0.0-beta.1 -com.azure:azure-ai-inference;1.0.0-beta.2;1.0.0-beta.3 -com.azure:azure-ai-metricsadvisor;1.2.4;1.3.0-beta.1 +com.azure:azure-ai-inference;1.0.0-beta.4;1.0.0-beta.5 +com.azure:azure-ai-metricsadvisor;1.2.5;1.3.0-beta.1 com.azure:azure-ai-metricsadvisor-perf;1.0.0-beta.1;1.0.0-beta.1 -com.azure:azure-ai-openai;1.0.0-beta.13;1.0.0-beta.14 -com.azure:azure-ai-openai-assistants;1.0.0-beta.4;1.0.0-beta.5 +com.azure:azure-ai-openai;1.0.0-beta.14;1.0.0-beta.15 +com.azure:azure-ai-openai-assistants;1.0.0-beta.5;1.0.0-beta.6 com.azure:azure-ai-openai-realtime;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-ai-personalizer;1.0.0-beta.1;1.0.0-beta.2 -com.azure:azure-ai-textanalytics;5.5.4;5.6.0-beta.1 +com.azure:azure-ai-textanalytics;5.5.5;5.6.0-beta.1 com.azure:azure-ai-textanalytics-perf;1.0.0-beta.1;1.0.0-beta.1 -com.azure:azure-ai-translation-text;1.1.0;1.2.0-beta.1 +com.azure:azure-ai-translation-text;1.1.1;1.2.0-beta.1 com.azure:azure-ai-translation-document;1.0.0;1.1.0-beta.1 com.azure:azure-analytics-defender-easm;1.0.0-beta.1;1.0.0-beta.2 com.azure:azure-analytics-purview-datamap;1.0.0-beta.1;1.0.0-beta.2 @@ -59,143 +59,144 @@ com.azure:azure-analytics-purview-sharing;1.0.0-beta.2;1.0.0-beta.3 com.azure:azure-analytics-purview-administration;1.0.0-beta.1;1.0.0-beta.2 com.azure:azure-analytics-purview-workflow;1.0.0-beta.1;1.0.0-beta.2 com.azure:azure-analytics-synapse-accesscontrol;1.0.0-beta.4;1.0.0-beta.5 -com.azure:azure-analytics-synapse-artifacts;1.0.0-beta.15;1.0.0-beta.16 +com.azure:azure-analytics-synapse-artifacts;1.0.0-beta.16;1.0.0-beta.17 com.azure:azure-analytics-synapse-spark;1.0.0-beta.5;1.0.0-beta.6 com.azure:azure-analytics-synapse-managedprivateendpoints;1.0.0-beta.5;1.0.0-beta.6 com.azure:azure-analytics-synapse-monitoring;1.0.0-beta.4;1.0.0-beta.5 com.azure:azure-code-customization-parent;1.0.0-beta.1;1.0.0-beta.1 -com.azure:azure-communication-callautomation;1.3.1;1.4.0-beta.2 +com.azure:azure-communication-callautomation;1.3.2;1.4.0-beta.2 com.azure:azure-communication-callingserver;1.0.0-beta.4;1.0.0-beta.5 -com.azure:azure-communication-chat;1.5.7;1.6.0-beta.1 -com.azure:azure-communication-common;1.3.9;1.4.0-beta.1 +com.azure:azure-communication-chat;1.5.8;1.6.0-beta.1 +com.azure:azure-communication-common;1.3.10;1.4.0-beta.1 com.azure:azure-communication-common-perf;1.0.0-beta.1;1.0.0-beta.1 -com.azure:azure-communication-email;1.0.19;1.1.0-beta.2 -com.azure:azure-communication-identity;1.6.2;1.7.0-beta.1 -com.azure:azure-communication-jobrouter;1.1.10;2.0.0-beta.1 -com.azure:azure-communication-messages;1.1.1;1.2.0-beta.1 -com.azure:azure-communication-phonenumbers;1.1.19;1.2.0-beta.4 -com.azure:azure-communication-rooms;1.1.8;1.2.0-beta.1 -com.azure:azure-communication-sms;1.1.30;1.2.0-beta.1 +com.azure:azure-communication-email;1.0.20;1.1.0-beta.2 +com.azure:azure-communication-identity;1.6.3;1.7.0-beta.1 +com.azure:azure-communication-jobrouter;1.1.11;2.0.0-beta.1 +com.azure:azure-communication-messages;1.1.2;1.2.0-beta.2 +com.azure:azure-communication-phonenumbers;1.2.1;1.3.0-beta.1 +com.azure:azure-communication-rooms;1.1.9;1.2.0 +com.azure:azure-communication-sms;1.1.31;1.2.0-beta.1 com.azure:azure-compute-batch;1.0.0-beta.3;1.0.0-beta.4 -com.azure:azure-containers-containerregistry;1.2.14;1.3.0-beta.1 +com.azure:azure-containers-containerregistry;1.2.15;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.54.1;1.55.0-beta.1 -com.azure:azure-core-amqp;2.9.12;2.10.0-beta.1 +com.azure:azure-core;1.55.3;1.56.0-beta.1 +com.azure:azure-core-amqp;2.9.16;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.56;1.0.0-beta.57 -com.azure:azure-core-http-jdk-httpclient;1.0.0-beta.19;1.0.0-beta.20 -com.azure:azure-core-http-netty;1.15.7;1.16.0-beta.1 -com.azure:azure-core-http-okhttp;1.12.6;1.13.0-beta.1 -com.azure:azure-core-http-vertx;1.0.0-beta.24;1.0.0-beta.25 -com.azure:azure-core-management;1.15.6;1.16.0-beta.1 -com.azure:azure-core-metrics-opentelemetry;1.0.0-beta.25;1.0.0-beta.26 +com.azure:azure-core-experimental;1.0.0-beta.60;1.0.0-beta.61 +com.azure:azure-core-http-jdk-httpclient;1.0.3;1.1.0-beta.1 +com.azure:azure-core-http-netty;1.15.11;1.16.0-beta.1 +com.azure:azure-core-http-okhttp;1.12.10;1.13.0-beta.1 +com.azure:azure-core-http-vertx;1.0.3;1.1.0-beta.1 +com.azure:azure-core-management;1.17.0;1.18.0-beta.1 +com.azure:azure-core-metrics-opentelemetry;1.0.0-beta.29;1.0.0-beta.30 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.52;1.0.0-beta.53 +com.azure:azure-core-serializer-avro-apache;1.0.0-beta.56;1.0.0-beta.57 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.3.4;1.4.0-beta.1 -com.azure:azure-core-serializer-json-jackson;1.5.4;1.6.0-beta.1 -com.azure:azure-core-test;1.27.0-beta.4;1.27.0-beta.5 -com.azure:azure-core-tracing-opentelemetry;1.0.0-beta.52;1.0.0-beta.53 +com.azure:azure-core-serializer-json-gson;1.3.8;1.4.0-beta.1 +com.azure:azure-core-serializer-json-jackson;1.5.8;1.6.0-beta.1 +com.azure:azure-core-test;1.27.0-beta.8;1.27.0-beta.9 +com.azure:azure-core-tracing-opentelemetry;1.0.0-beta.56;1.0.0-beta.57 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.66.0;4.67.0-beta.1 +com.azure:azure-cosmos;4.67.0;4.68.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.17.0;2.18.0-beta.1 -com.azure.cosmos.spark:azure-cosmos-spark_3-1_2-12;4.36.0;4.37.0-beta.1 -com.azure.cosmos.spark:azure-cosmos-spark_3-2_2-12;4.36.0;4.37.0-beta.1 -com.azure.cosmos.spark:azure-cosmos-spark_3-3_2-12;4.36.0;4.37.0-beta.1 -com.azure.cosmos.spark:azure-cosmos-spark_3-4_2-12;4.36.0;4.37.0-beta.1 -com.azure.cosmos.spark:azure-cosmos-spark_3-5_2-12;4.36.0;4.37.0-beta.1 +com.azure:azure-cosmos-encryption;2.18.0;2.19.0-beta.1 +com.azure.cosmos.spark:azure-cosmos-spark_3-1_2-12;4.37.1;4.38.0-beta.1 +com.azure.cosmos.spark:azure-cosmos-spark_3-2_2-12;4.37.1;4.38.0-beta.1 +com.azure.cosmos.spark:azure-cosmos-spark_3-3_2-12;4.37.1;4.38.0-beta.1 +com.azure.cosmos.spark:azure-cosmos-spark_3-4_2-12;4.37.1;4.38.0-beta.1 +com.azure.cosmos.spark:azure-cosmos-spark_3-5_2-12;4.37.1;4.38.0-beta.1 com.azure.cosmos.spark:azure-cosmos-spark-account-data-resolver-sample;1.0.0-beta.1;1.0.0-beta.1 -com.azure:azure-cosmos-test;1.0.0-beta.9;1.0.0-beta.10 +com.azure:azure-cosmos-test;1.0.0-beta.11;1.0.0-beta.12 com.azure:azure-cosmos-tests;1.0.0-beta.1;1.0.0-beta.1 -com.azure.cosmos.kafka:azure-cosmos-kafka-connect;2.1.0;2.2.0-beta.1 -com.azure:azure-data-appconfiguration;1.7.3;1.8.0-beta.1 +com.azure.cosmos.kafka:azure-cosmos-kafka-connect;2.2.0;2.3.0-beta.1 +com.azure:azure-data-appconfiguration;1.7.4;1.8.0 com.azure:azure-data-appconfiguration-perf;1.0.0-beta.1;1.0.0-beta.1 -com.azure:azure-data-schemaregistry;1.5.2;1.6.0-beta.1 -com.azure:azure-data-schemaregistry-apacheavro;1.1.23;1.2.0-beta.3 +com.azure:azure-data-schemaregistry;1.5.3;1.6.0-beta.1 +com.azure:azure-data-schemaregistry-apacheavro;1.1.24;1.2.0-beta.3 com.azure:azure-data-schemaregistry-jsonschema;1.0.0;1.1.0-beta.1 -com.azure:azure-data-tables;12.5.0;12.6.0-beta.1 +com.azure:azure-data-tables;12.5.2;12.6.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.6;1.1.0-beta.1 -com.azure:azure-developer-loadtesting;1.0.19;1.0.20 -com.azure:azure-digitaltwins-core;1.4.0;1.5.0-beta.1 +com.azure:azure-developer-devcenter;1.0.7;1.1.0-beta.1 +com.azure:azure-developer-loadtesting;1.0.21;1.1.0-beta.1 +com.azure:azure-digitaltwins-core;1.4.1;1.5.0-beta.1 com.azure:azure-e2e;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-health-deidentification;1.0.0;1.0.0-beta.2 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;1.1.0-beta.1 -com.azure:azure-identity;1.15.0;1.16.0-beta.1 -com.azure:azure-identity-extensions;1.2.0;1.3.0-beta.1 -com.azure:azure-identity-broker;1.1.9;1.2.0-beta.1 +com.azure:azure-identity;1.15.4;1.16.0-beta.1 +com.azure:azure-identity-v2;2.0.0-beta.1;2.0.0-beta.1 +com.azure:azure-identity-extensions;1.2.1;1.3.0-beta.1 +com.azure:azure-identity-broker;1.1.13;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.24;1.1.0-beta.1 +com.azure:azure-iot-deviceupdate;1.0.25;1.1.0-beta.1 com.azure:azure-iot-modelsrepository;1.0.0-beta.1;1.0.0-beta.2 -com.azure:azure-json;1.3.0;1.4.0-beta.1 -com.azure:azure-json-gson;1.0.0-beta.3;1.0.0-beta.4 -com.azure:azure-json-reflect;1.0.0-beta.2;1.0.0-beta.3 +com.azure:azure-json;1.5.0;1.6.0-beta.1 com.azure:azure-maps-traffic;1.0.0-beta.1;1.0.0-beta.2 -com.azure:azure-maps-weather;1.0.0-beta.2;1.0.0-beta.3 +com.azure:azure-maps-weather;1.0.0-beta.3;1.0.0-beta.4 com.azure:azure-maps-timezone;1.0.0-beta.2;1.0.0-beta.3 com.azure:azure-maps-geolocation;1.0.0-beta.3;1.0.0-beta.4 com.azure:azure-maps-render;2.0.0-beta.2;2.0.0-beta.3 com.azure:azure-maps-route;1.0.0-beta.3;1.0.0-beta.4 com.azure:azure-maps-search;2.0.0-beta.2;2.0.0-beta.3 -com.azure:azure-messaging-eventgrid;4.27.0;4.28.0 -com.azure:azure-messaging-eventgrid-namespaces;1.1.1;1.2.0-beta.1 +com.azure:azure-messaging-eventgrid;4.29.0;4.30.0-beta.1 +com.azure:azure-messaging-eventgrid-systemevents;1.0.0-beta.1;1.0.0-beta.2 +com.azure:azure-messaging-eventgrid-namespaces;1.1.2;1.2.0-beta.1 com.azure:azure-messaging-eventgrid-cloudnative-cloudevents;1.0.0-beta.1;1.0.0-beta.2 -com.azure:azure-messaging-eventhubs;5.19.2;5.20.0-beta.1 -com.azure:azure-messaging-eventhubs-checkpointstore-blob;1.20.2;1.21.0-beta.1 +com.azure:azure-messaging-eventhubs;5.20.1;5.21.0-beta.2 +com.azure:azure-messaging-eventhubs-checkpointstore-blob;1.20.5;1.21.0-beta.2 com.azure:azure-messaging-eventhubs-checkpointstore-jedis;1.0.0-beta.3;1.0.0-beta.4 com.azure:azure-messaging-eventhubs-stress;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-messaging-eventhubs-track2-perf;1.0.0-beta.1;1.0.0-beta.1 -com.azure:azure-messaging-servicebus;7.17.8;7.18.0-beta.2 +com.azure:azure-messaging-servicebus;7.17.9;7.18.0-beta.2 com.azure:azure-messaging-servicebus-stress;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-messaging-servicebus-track2-perf;1.0.0-beta.1;1.0.0-beta.1 -com.azure:azure-messaging-webpubsub;1.3.3;1.4.0-beta.1 -com.azure:azure-messaging-webpubsub-client;1.0.9;1.1.0-beta.1 -com.azure:azure-mixedreality-authentication;1.2.30;1.3.0-beta.1 -com.azure:azure-mixedreality-remoterendering;1.1.35;1.2.0-beta.1 -com.azure:azure-monitor-opentelemetry-exporter;1.0.0-beta.31;1.0.0-beta.32 -com.azure:azure-monitor-opentelemetry-autoconfigure;1.0.0-beta.1;1.0.0-beta.1 -com.azure:azure-monitor-ingestion;1.2.7;1.3.0-beta.1 +com.azure:azure-messaging-webpubsub;1.4.0;1.5.0-beta.1 +com.azure:azure-messaging-webpubsub-client;1.1.0;1.2.0-beta.1 +com.azure:azure-mixedreality-authentication;1.2.31;1.3.0-beta.1 +com.azure:azure-mixedreality-remoterendering;1.1.36;1.2.0-beta.1 +com.azure:azure-monitor-opentelemetry-exporter;1.0.0-beta.32;1.0.0-beta.33 +com.azure:azure-monitor-opentelemetry-autoconfigure;1.0.0;1.1.0-beta.1 +com.azure:azure-monitor-ingestion;1.2.8;1.3.0-beta.1 com.azure:azure-monitor-ingestion-perf;1.0.0-beta.1;1.0.0-beta.1 -com.azure:azure-monitor-query;1.5.4;1.6.0-beta.1 +com.azure:azure-monitor-query;1.5.6;1.6.0-beta.1 com.azure:azure-monitor-query-perf;1.0.0-beta.1;1.0.0-beta.1 +com.azure:azure-openrewrite;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-perf-test-parent;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-quantum-jobs;1.0.0-beta.1;1.0.0-beta.2 -com.azure:azure-search-documents;11.7.4;11.8.0-beta.5 +com.azure:azure-search-documents;11.7.5;11.8.0-beta.6 com.azure:azure-search-perf;1.0.0-beta.1;1.0.0-beta.1 -com.azure:azure-security-attestation;1.1.30;1.2.0-beta.1 -com.azure:azure-security-confidentialledger;1.0.26;1.1.0-beta.1 -com.azure:azure-security-keyvault-administration;4.6.1;4.7.0-beta.1 -com.azure:azure-security-keyvault-certificates;4.7.1;4.8.0-beta.1 +com.azure:azure-security-attestation;1.1.31;1.2.0-beta.1 +com.azure:azure-security-confidentialledger;1.0.27;1.1.0-beta.1 +com.azure:azure-security-keyvault-administration;4.6.3;4.7.0-beta.1 +com.azure:azure-security-keyvault-certificates;4.7.3;4.8.0-beta.1 com.azure:azure-security-keyvault-jca;2.10.0;2.11.0-beta.1 com.azure:azure-security-test-keyvault-jca;1.0.0;1.0.0 -com.azure:azure-security-keyvault-keys;4.9.1;4.10.0-beta.1 -com.azure:azure-security-keyvault-secrets;4.9.1;4.10.0-beta.1 +com.azure:azure-security-keyvault-keys;4.9.3;4.10.0-beta.1 +com.azure:azure-security-keyvault-secrets;4.9.3;4.10.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 com.azure:azure-sdk-template-two;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-sdk-template-three;1.0.0-beta.1;1.0.0-beta.1 -com.azure:azure-storage-blob;12.29.0;12.30.0-beta.1 -com.azure:azure-storage-blob-batch;12.25.0;12.26.0-beta.1 -com.azure:azure-storage-blob-changefeed;12.0.0-beta.27;12.0.0-beta.28 -com.azure:azure-storage-blob-cryptography;12.28.0;12.29.0-beta.1 -com.azure:azure-storage-blob-nio;12.0.0-beta.28;12.0.0-beta.29 -com.azure:azure-storage-common;12.28.0;12.29.0-beta.1 -com.azure:azure-storage-file-share;12.25.1;12.26.0-beta.1 -com.azure:azure-storage-file-datalake;12.22.0;12.23.0-beta.1 -com.azure:azure-storage-internal-avro;12.14.0;12.15.0-beta.1 +com.azure:azure-storage-blob;12.29.1;12.30.0 +com.azure:azure-storage-blob-batch;12.25.1;12.26.0 +com.azure:azure-storage-blob-changefeed;12.0.0-beta.28;12.0.0-beta.29 +com.azure:azure-storage-blob-cryptography;12.28.1;12.29.0 +com.azure:azure-storage-blob-nio;12.0.0-beta.29;12.0.0-beta.30 +com.azure:azure-storage-common;12.28.1;12.29.0 +com.azure:azure-storage-file-share;12.25.2;12.26.0 +com.azure:azure-storage-file-datalake;12.22.1;12.23.0 +com.azure:azure-storage-internal-avro;12.14.1;12.15.0 com.azure:azure-storage-perf;1.0.0-beta.1;1.0.0-beta.1 -com.azure:azure-storage-queue;12.24.0;12.25.0-beta.1 +com.azure:azure-storage-queue;12.24.1;12.25.0 com.azure:azure-template-perf;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-template-stress;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-verticals-agrifood-farming;1.0.0-beta.3;1.0.0-beta.4 -com.azure:azure-xml;1.1.0;1.2.0-beta.1 +com.azure:azure-xml;1.2.0;1.3.0-beta.1 com.azure:perf-test-core;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-ai-vision-imageanalysis;1.0.0;1.1.0-beta.1 com.azure:identity-test-container;1.0.0-beta.1;1.0.0-beta.1 @@ -204,86 +205,87 @@ com.azure:identity-test-vm;1.0.0-beta.1;1.0.0-beta.1 com.azure:identity-test-webapp;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-ai-vision-face;1.0.0-beta.2;1.0.0-beta.3 com.azure.spring:azure-monitor-spring-native-test;1.0.0-beta.1;1.0.0-beta.1 -com.azure.spring:spring-cloud-azure-appconfiguration-config-web;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-appconfiguration-config;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-feature-management-web;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-feature-management;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-appconfiguration-config;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-dependencies;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-messaging-azure;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-messaging-azure-eventhubs;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-messaging-azure-servicebus;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-messaging-azure-storage-queue;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-integration-azure-core;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-integration-azure-eventhubs;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-integration-azure-servicebus;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-integration-azure-storage-queue;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-core;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-actuator-autoconfigure;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-actuator;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-autoconfigure;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-docker-compose;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-resourcemanager;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-service;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-active-directory;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-active-directory-b2c;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-actuator;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-appconfiguration;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-cosmos;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-data-cosmos;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-data-redis-lettuce;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-eventhubs;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-eventgrid;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-jdbc-mysql;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-jdbc-postgresql;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-keyvault;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-keyvault-certificates;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-keyvault-secrets;5.19.0;5.20.0-beta.1 +com.azure.spring:spring-cloud-azure-appconfiguration-config-web;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-appconfiguration-config;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-feature-management-web;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-feature-management;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-appconfiguration-config;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-dependencies;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-messaging-azure;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-messaging-azure-eventhubs;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-messaging-azure-servicebus;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-messaging-azure-storage-queue;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-integration-azure-core;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-integration-azure-eventhubs;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-integration-azure-servicebus;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-integration-azure-storage-queue;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-core;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-actuator-autoconfigure;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-actuator;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-autoconfigure;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-docker-compose;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-resourcemanager;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-service;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-active-directory;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-active-directory-b2c;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-actuator;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-appconfiguration;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-cosmos;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-data-cosmos;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-data-redis-lettuce;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-eventhubs;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-eventgrid;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-jdbc-mysql;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-jdbc-postgresql;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-keyvault;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-keyvault-certificates;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-keyvault-jca;5.21.0-beta.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-keyvault-secrets;5.20.1;5.21.0-beta.1 com.azure.spring:spring-cloud-azure-starter-monitor;1.0.0-beta.6;1.0.0-beta.7 -com.azure.spring:spring-cloud-azure-starter-servicebus-jms;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-servicebus;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-storage;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-storage-blob;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-storage-file-share;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-storage-queue;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-integration-eventhubs;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-integration-servicebus;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-integration-storage-queue;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-stream-eventhubs;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-starter-stream-servicebus;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-starter;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-stream-binder-eventhubs-core;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-stream-binder-eventhubs;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-stream-binder-servicebus-core;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-stream-binder-servicebus;5.19.0;5.20.0-beta.1 -com.azure.spring:spring-cloud-azure-testcontainers;5.19.0;5.20.0-beta.1 -com.azure:azure-spring-data-cosmos;5.19.0;5.20.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager;2.46.0;2.47.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-appplatform;2.46.0;2.47.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-appservice;2.46.0;2.47.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-authorization;2.46.0;2.47.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-cdn;2.46.0;2.47.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-compute;2.46.0;2.47.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-containerinstance;2.46.0;2.47.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-containerregistry;2.46.0;2.47.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-containerservice;2.46.0;2.47.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-cosmos;2.46.0;2.47.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-dns;2.46.0;2.47.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-eventhubs;2.46.0;2.47.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-keyvault;2.46.0;2.47.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-monitor;2.46.0;2.47.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-msi;2.46.0;2.47.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-network;2.46.0;2.47.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-servicebus-jms;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-servicebus;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-storage;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-storage-blob;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-storage-file-share;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-storage-queue;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-integration-eventhubs;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-integration-servicebus;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-integration-storage-queue;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-stream-eventhubs;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-starter-stream-servicebus;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-starter;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-stream-binder-eventhubs-core;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-stream-binder-eventhubs;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-stream-binder-servicebus-core;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-stream-binder-servicebus;5.20.1;5.21.0-beta.1 +com.azure.spring:spring-cloud-azure-testcontainers;5.20.1;5.21.0-beta.1 +com.azure:azure-spring-data-cosmos;5.20.1;5.21.0-beta.1 +com.azure.resourcemanager:azure-resourcemanager;2.48.0;2.49.0-beta.1 +com.azure.resourcemanager:azure-resourcemanager-appplatform;2.48.0;2.49.0-beta.1 +com.azure.resourcemanager:azure-resourcemanager-appservice;2.48.0;2.49.0-beta.1 +com.azure.resourcemanager:azure-resourcemanager-authorization;2.48.0;2.49.0-beta.1 +com.azure.resourcemanager:azure-resourcemanager-cdn;2.48.0;2.49.0-beta.1 +com.azure.resourcemanager:azure-resourcemanager-compute;2.48.0;2.49.0-beta.1 +com.azure.resourcemanager:azure-resourcemanager-containerinstance;2.48.0;2.49.0-beta.1 +com.azure.resourcemanager:azure-resourcemanager-containerregistry;2.48.0;2.49.0-beta.1 +com.azure.resourcemanager:azure-resourcemanager-containerservice;2.48.0;2.49.0-beta.1 +com.azure.resourcemanager:azure-resourcemanager-cosmos;2.48.0;2.49.0-beta.1 +com.azure.resourcemanager:azure-resourcemanager-dns;2.48.0;2.49.0-beta.1 +com.azure.resourcemanager:azure-resourcemanager-eventhubs;2.48.0;2.49.0-beta.1 +com.azure.resourcemanager:azure-resourcemanager-keyvault;2.48.0;2.49.0-beta.1 +com.azure.resourcemanager:azure-resourcemanager-monitor;2.48.0;2.49.0-beta.1 +com.azure.resourcemanager:azure-resourcemanager-msi;2.48.0;2.49.0-beta.1 +com.azure.resourcemanager:azure-resourcemanager-network;2.48.0;2.49.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-perf;1.0.0-beta.1;1.0.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-privatedns;2.46.0;2.47.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-resources;2.46.0;2.47.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-redis;2.46.0;2.47.0-beta.1 +com.azure.resourcemanager:azure-resourcemanager-privatedns;2.48.0;2.49.0-beta.1 +com.azure.resourcemanager:azure-resourcemanager-resources;2.48.0;2.49.0-beta.1 +com.azure.resourcemanager:azure-resourcemanager-redis;2.48.0;2.49.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-samples;2.0.0-beta.1;2.0.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-search;2.46.0;2.47.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-servicebus;2.46.0;2.47.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-sql;2.46.0;2.47.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-storage;2.46.0;2.47.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-trafficmanager;2.46.0;2.47.0-beta.1 +com.azure.resourcemanager:azure-resourcemanager-search;2.48.0;2.49.0-beta.1 +com.azure.resourcemanager:azure-resourcemanager-servicebus;2.48.0;2.49.0-beta.1 +com.azure.resourcemanager:azure-resourcemanager-sql;2.48.0;2.49.0-beta.1 +com.azure.resourcemanager:azure-resourcemanager-storage;2.48.0;2.49.0-beta.1 +com.azure.resourcemanager:azure-resourcemanager-trafficmanager;2.48.0;2.49.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-test;2.0.0-beta.1;2.0.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-mediaservices;2.3.0;2.4.0-beta.3 com.azure.resourcemanager:azure-resourcemanager-mysql;1.0.2;1.1.0-beta.1 @@ -293,13 +295,13 @@ com.azure.resourcemanager:azure-resourcemanager-sqlvirtualmachine;1.0.0-beta.5;1 com.azure.resourcemanager:azure-resourcemanager-relay;1.0.0-beta.3;1.1.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-costmanagement;1.0.0;1.1.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-recoveryservices;1.4.0;1.5.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-kusto;1.1.0;1.2.0-beta.1 +com.azure.resourcemanager:azure-resourcemanager-kusto;1.2.0;1.3.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-loganalytics;1.1.0;1.2.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-eventgrid;1.1.0;1.2.0-beta.8 com.azure.resourcemanager:azure-resourcemanager-healthbot;1.0.0;1.1.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-confluent;1.2.0;1.3.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-digitaltwins;1.3.0;1.4.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-netapp;1.5.1;1.6.0-beta.2 +com.azure.resourcemanager:azure-resourcemanager-netapp;1.6.0;1.7.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-storagecache;1.0.0;1.1.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-redisenterprise;2.0.0;2.1.0-beta.3 com.azure.resourcemanager:azure-resourcemanager-hybridkubernetes;1.0.0;1.1.0-beta.1 @@ -348,7 +350,7 @@ com.azure.resourcemanager:azure-resourcemanager-policyinsights;1.0.0;1.1.0-beta. com.azure.resourcemanager:azure-resourcemanager-support;1.1.0;1.2.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-subscription;1.0.0;1.1.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-powerbidedicated;1.0.0;1.1.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-applicationinsights;1.1.0;1.2.0-beta.1 +com.azure.resourcemanager:azure-resourcemanager-applicationinsights;1.1.0;1.2.0-beta.2 com.azure.resourcemanager:azure-resourcemanager-deploymentmanager;1.0.0-beta.2;1.0.0-beta.3 com.azure.resourcemanager:azure-resourcemanager-notificationhubs;1.0.0;1.1.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-marketplaceordering;1.0.0;1.1.0-beta.1 @@ -376,9 +378,9 @@ com.azure.resourcemanager:azure-resourcemanager-hybridnetwork;1.1.0;1.2.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-purview;1.0.0;1.1.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-mysqlflexibleserver;1.0.0-beta.6;1.1.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-baremetalinfrastructure;1.0.0;1.1.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-quota;1.0.0;1.1.0-beta.3 +com.azure.resourcemanager:azure-resourcemanager-quota;1.1.0;1.2.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-extendedlocation;1.0.0;1.1.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-logz;1.0.0-beta.3;1.0.0-beta.4 +com.azure.resourcemanager:azure-resourcemanager-logz;1.0.0-beta.4;1.0.0-beta.5 com.azure.resourcemanager:azure-resourcemanager-storagepool;1.0.0;1.1.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-dataprotection;1.3.0;1.4.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-desktopvirtualization;1.2.0;1.3.0-beta.1 @@ -408,14 +410,14 @@ com.azure.resourcemanager:azure-resourcemanager-fluidrelay;1.1.0;1.2.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-devcenter;1.0.0;1.1.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-connectedvmware;1.1.0;1.2.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-alertsmanagement;1.0.0-beta.2;1.0.0-beta.3 -com.azure.resourcemanager:azure-resourcemanager-nginx;1.0.0;1.1.0-beta.3 +com.azure.resourcemanager:azure-resourcemanager-nginx;1.0.0;1.1.0-beta.4 com.azure.resourcemanager:azure-resourcemanager-agrifood;1.0.0-beta.2;1.0.0-beta.3 com.azure.resourcemanager:azure-resourcemanager-devhub;1.0.0-beta.3;1.0.0-beta.4 com.azure.resourcemanager:azure-resourcemanager-elasticsan;1.1.0;1.2.0-beta.2 com.azure.resourcemanager:azure-resourcemanager-hybridcontainerservice;1.1.0;1.2.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-securitydevops;1.0.0-beta.1;1.0.0-beta.2 com.azure.resourcemanager:azure-resourcemanager-appcomplianceautomation;1.0.0;1.1.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-servicenetworking;1.0.0;1.1.0-beta.2 +com.azure.resourcemanager:azure-resourcemanager-servicenetworking;1.1.0;1.2.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-recoveryservicessiterecovery;1.2.0;1.3.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-billingbenefits;1.0.0-beta.2;1.0.0-beta.3 com.azure.resourcemanager:azure-resourcemanager-providerhub;1.1.0;1.2.0-beta.1 @@ -428,7 +430,7 @@ com.azure.resourcemanager:azure-resourcemanager-paloaltonetworks-ngfw;1.2.0;1.3. com.azure.resourcemanager:azure-resourcemanager-newrelicobservability;1.2.0;1.3.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-qumulo;1.1.0;1.2.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-selfhelp;1.0.0;1.1.0-beta.6 -com.azure.resourcemanager:azure-resourcemanager-networkcloud;1.0.0;1.1.0-beta.2 +com.azure.resourcemanager:azure-resourcemanager-networkcloud;1.1.0;1.2.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-cosmosdbforpostgresql;1.0.0;1.1.0-beta.3 com.azure.resourcemanager:azure-resourcemanager-managementgroups;1.0.0-beta.2;1.0.0-beta.3 com.azure.resourcemanager:azure-resourcemanager-managednetworkfabric;1.1.0;1.2.0-beta.1 @@ -439,17 +441,17 @@ com.azure.resourcemanager:azure-resourcemanager-sphere;1.1.0;1.2.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-defendereasm;1.0.0-beta.2;1.0.0-beta.3 com.azure.resourcemanager:azure-resourcemanager-hdinsight-containers;1.0.0-beta.3;1.0.0-beta.4 com.azure.resourcemanager:azure-resourcemanager-apicenter;1.1.0;1.2.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-hybridconnectivity;1.1.0;1.2.0-beta.1 +com.azure.resourcemanager:azure-resourcemanager-hybridconnectivity;1.1.0;1.2.0-beta.2 com.azure.resourcemanager:azure-resourcemanager-playwrighttesting;1.0.0;1.1.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-recoveryservicesdatareplication;1.0.0-beta.2;1.0.0-beta.3 -com.azure.resourcemanager:azure-resourcemanager-networkanalytics;1.0.0;1.1.0-beta.1 +com.azure.resourcemanager:azure-resourcemanager-networkanalytics;1.0.1;1.1.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-springappdiscovery;1.0.0-beta.2;1.0.0-beta.3 com.azure.resourcemanager:azure-resourcemanager-astro;1.0.0-beta.2;1.0.0-beta.3 com.azure.resourcemanager:azure-resourcemanager-workloadssapvirtualinstance;1.0.0-beta.1;1.0.0 com.azure.resourcemanager:azure-resourcemanager-largeinstance;1.0.0-beta.2;1.0.0-beta.3 com.azure.resourcemanager:azure-resourcemanager-migrationdiscoverysap;1.0.0-beta.2;1.0.0-beta.3 com.azure.resourcemanager:azure-resourcemanager-storageactions;1.0.0-beta.2;1.0.0-beta.3 -com.azure.resourcemanager:azure-resourcemanager-deviceregistry;1.0.0-beta.2;1.0.0-beta.3 +com.azure.resourcemanager:azure-resourcemanager-deviceregistry;1.0.0;1.1.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-standbypool;1.0.0;1.1.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-edgezones;1.0.0-beta.2;1.0.0-beta.3 com.azure.resourcemanager:azure-resourcemanager-devopsinfrastructure;1.0.0;1.1.0-beta.1 @@ -461,20 +463,30 @@ com.azure.resourcemanager:azure-resourcemanager-servicefabricmanagedclusters;1.0 com.azure.resourcemanager:azure-resourcemanager-healthdataaiservices;1.0.0;1.1.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-redhatopenshift;1.0.0-beta.1;1.0.0-beta.2 com.azure.resourcemanager:azure-resourcemanager-fabric;1.0.0;1.1.0-beta.1 -com.azure.resourcemanager:azure-resourcemanager-computeschedule;1.0.0-beta.1;1.0.0-beta.2 +com.azure.resourcemanager:azure-resourcemanager-computeschedule;1.0.0;1.1.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-trustedsigning;1.0.0-beta.1;1.0.0-beta.2 com.azure.resourcemanager:azure-resourcemanager-iotoperations;1.0.0;1.1.0-beta.1 com.azure.resourcemanager:azure-resourcemanager-containerorchestratorruntime;1.0.0-beta.1;1.0.0-beta.2 com.azure.resourcemanager:azure-resourcemanager-terraform;1.0.0-beta.1;1.0.0-beta.2 com.azure.resourcemanager:azure-resourcemanager-connectedcache;1.0.0-beta.1;1.0.0-beta.2 com.azure.resourcemanager:azure-resourcemanager-neonpostgres;1.0.0-beta.1;1.0.0-beta.2 +com.azure.resourcemanager:azure-resourcemanager-pineconevectordb;1.0.0-beta.1;1.0.0-beta.2 +com.azure.resourcemanager:azure-resourcemanager-impactreporting;1.0.0-beta.1;1.0.0-beta.2 +com.azure.resourcemanager:azure-resourcemanager-migration-assessment;1.0.0-beta.1;1.0.0-beta.2 +com.azure.resourcemanager:azure-resourcemanager-databasewatcher;1.0.0-beta.1;1.0.0-beta.2 com.azure.tools:azure-sdk-archetype;1.0.0;1.2.0-beta.1 com.azure.tools:azure-sdk-build-tool;1.0.0;1.1.0-beta.1 -io.clientcore:clientcore-parent;1.0.0-beta.1;1.0.0-beta.1 -io.clientcore:core;1.0.0-beta.1;1.0.0-beta.2 -io.clientcore:http-okhttp3;1.0.0-beta.1;1.0.0-beta.1 +com.azure.v2:azure-client-sdk-parent;2.0.0-beta.1;2.0.0-beta.1 +com.azure.v2:azure-core;2.0.0-beta.1;2.0.0-beta.1 +com.azure.v2:azure-core-test;2.0.0-beta.1;2.0.0-beta.1 +io.clientcore:clientcore-parent;1.0.0-beta.2;1.0.0-beta.3 +io.clientcore:core;1.0.0-beta.6;1.0.0-beta.7 +io.clientcore:http-okhttp3;1.0.0-beta.1;1.0.0-beta.2 io.clientcore:http-stress;1.0.0-beta.1;1.0.0-beta.1 io.clientcore:optional-dependency-tests;1.0.0-beta.1;1.0.0-beta.1 +io.clientcore:annotation-processor;1.0.0-beta.1;1.0.0-beta.1 +io.clientcore:annotation-processor-test;1.0.0-beta.1;1.0.0-beta.1 + # Unreleased dependencies: Copy the entry from above, prepend "unreleased_" and remove the current # version. Unreleased dependencies are only valid for dependency versions. @@ -484,8 +496,8 @@ io.clientcore:optional-dependency-tests;1.0.0-beta.1;1.0.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-monitor-opentelemetry-exporter;1.0.0-beta.31 -unreleased_com.azure:azure-monitor-opentelemetry-autoconfigure;1.0.0-beta.1 +unreleased_io.clientcore:core;1.0.0-beta.7 +unreleased_com.azure.v2:azure-core;2.0.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 diff --git a/pom.xml b/pom.xml index b2a53dd56d55..23a8bc15d30e 100644 --- a/pom.xml +++ b/pom.xml @@ -55,11 +55,13 @@ sdk/containerservicefleet sdk/contentsafety sdk/core + sdk/corev2 sdk/cosmos sdk/cosmosdbforpostgresql sdk/costmanagement sdk/customerinsights sdk/dashboard + sdk/databasewatcher sdk/databox sdk/databoxedge sdk/databricks @@ -114,6 +116,7 @@ sdk/hybridnetwork sdk/identity sdk/imagebuilder + sdk/impactreporting sdk/informaticadatamanagement sdk/iotcentral sdk/iotfirmwaredefense @@ -138,6 +141,7 @@ sdk/marketplaceordering sdk/mediaservices sdk/metricsadvisor + sdk/migration sdk/migrationdiscoverysap sdk/mixedreality sdk/mobilenetwork @@ -163,6 +167,7 @@ sdk/parents sdk/peering sdk/personalizer + sdk/pineconevectordb sdk/playwrighttesting sdk/policyinsights sdk/postgresql diff --git a/sdk/advisor/azure-resourcemanager-advisor/README.md b/sdk/advisor/azure-resourcemanager-advisor/README.md index db6425842fb3..f9b6e70404cc 100644 --- a/sdk/advisor/azure-resourcemanager-advisor/README.md +++ b/sdk/advisor/azure-resourcemanager-advisor/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-advisor - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fadvisor%2Fazure-resourcemanager-advisor%2FREADME.png) + diff --git a/sdk/advisor/azure-resourcemanager-advisor/pom.xml b/sdk/advisor/azure-resourcemanager-advisor/pom.xml index 4e148d7e85c3..4a8cf02522ce 100644 --- a/sdk/advisor/azure-resourcemanager-advisor/pom.xml +++ b/sdk/advisor/azure-resourcemanager-advisor/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/agrifood/azure-resourcemanager-agrifood/README.md b/sdk/agrifood/azure-resourcemanager-agrifood/README.md index 124f7b0ec850..6c4e7d7301da 100644 --- a/sdk/agrifood/azure-resourcemanager-agrifood/README.md +++ b/sdk/agrifood/azure-resourcemanager-agrifood/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-agrifood - 1.0.0-beta.2 + 1.0.0-beta.3 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fagrifood%2Fazure-resourcemanager-agrifood%2FREADME.png) + diff --git a/sdk/agrifood/azure-resourcemanager-agrifood/pom.xml b/sdk/agrifood/azure-resourcemanager-agrifood/pom.xml index 648eddad4d2f..19a00a791340 100644 --- a/sdk/agrifood/azure-resourcemanager-agrifood/pom.xml +++ b/sdk/agrifood/azure-resourcemanager-agrifood/pom.xml @@ -52,23 +52,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/agrifood/azure-verticals-agrifood-farming/README.md b/sdk/agrifood/azure-verticals-agrifood-farming/README.md index 1548c04f0172..f8bec96ece32 100644 --- a/sdk/agrifood/azure-verticals-agrifood-farming/README.md +++ b/sdk/agrifood/azure-verticals-agrifood-farming/README.md @@ -25,7 +25,7 @@ Use FarmBeats client library for Python to do the following. com.azure azure-verticals-agrifood-farming - 1.0.0-beta.3 + 1.0.0-beta.4 ``` [//]: # ({x-version-update-end}) @@ -47,7 +47,7 @@ To use the [DefaultAzureCredential][DefaultAzureCredential] provider shown below com.azure azure-identity - 1.14.2 + 1.15.3 ``` @@ -176,4 +176,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct](https://ope [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ [logging]: https://github.com/Azure/azure-sdk-for-java/wiki/Logging-in-Azure-SDK -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fagrifood%2Fazure-verticals-agrifood-farming%2FREADME.png) + diff --git a/sdk/agrifood/azure-verticals-agrifood-farming/pom.xml b/sdk/agrifood/azure-verticals-agrifood-farming/pom.xml index 4a783e8ee94f..38dfcc0c3ff2 100644 --- a/sdk/agrifood/azure-verticals-agrifood-farming/pom.xml +++ b/sdk/agrifood/azure-verticals-agrifood-farming/pom.xml @@ -47,36 +47,36 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-experimental - 1.0.0-beta.56 + 1.0.0-beta.60 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-core-serializer-json-jackson - 1.5.4 + 1.5.8 test diff --git a/sdk/ai/azure-ai-inference/CHANGELOG.md b/sdk/ai/azure-ai-inference/CHANGELOG.md index 14bf28ec3822..1d7e00dbd6ef 100644 --- a/sdk/ai/azure-ai-inference/CHANGELOG.md +++ b/sdk/ai/azure-ai-inference/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.0.0-beta.3 (Unreleased) +## 1.0.0-beta.5 (Unreleased) ### Features Added @@ -10,6 +10,23 @@ ### Other Changes +## 1.0.0-beta.4 (2025-03-14) + +### Bugs Fixed + +- #44517: Use ModelServiceVersion (api-version) of 2024-05-01-preview as default + +## 1.0.0-beta.3 (2025-02-20) + +### Breaking Changes +- Change ChatCompletionsResponseFormatJSON class name to ChatCompletionsResponseFormatJsonObject. + +### Features Added +- Add samples and tests for image embeddings. +- Add ChatCompletionsResponseFormatJsonSchema class for structured output in completions response. +- Add sample and test for Chat Completions with structured output +- Add "developer" chat role and ChatRequestDeveloperMessage to support new GPT models + ## 1.0.0-beta.2 (2024-10-03) ### Features Added diff --git a/sdk/ai/azure-ai-inference/README.md b/sdk/ai/azure-ai-inference/README.md index 13d7bfdddd96..a6835096350b 100644 --- a/sdk/ai/azure-ai-inference/README.md +++ b/sdk/ai/azure-ai-inference/README.md @@ -25,7 +25,7 @@ Various documentation is available to help you get started com.azure azure-ai-inference - 1.0.0-beta.2 + 1.0.0-beta.4 ``` [//]: # ({x-version-update-end}) @@ -67,7 +67,7 @@ Authentication with AAD requires some initial setup: com.azure azure-identity - 1.14.2 + 1.15.3 ``` [//]: # ({x-version-update-end}) @@ -288,4 +288,4 @@ For details on contributing to this repository, see the [contributing guide](htt [troubleshooting]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/openai/azure-ai-openai/TROUBLESHOOTING.md [wiki_identity]: https://learn.microsoft.com/azure/developer/java/sdk/identity -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fai%2Fazure-ai-inference%2FREADME.png) + diff --git a/sdk/ai/azure-ai-inference/assets.json b/sdk/ai/azure-ai-inference/assets.json index 5aa919d38ad8..3fbbc88d9294 100644 --- a/sdk/ai/azure-ai-inference/assets.json +++ b/sdk/ai/azure-ai-inference/assets.json @@ -2,5 +2,5 @@ "AssetsRepo" : "Azure/azure-sdk-assets", "AssetsRepoPrefixPath" : "java", "TagPrefix" : "java/ai/azure-ai-inference", - "Tag" : "java/ai/azure-ai-inference_47913ffcfa" + "Tag" : "java/ai/azure-ai-inference_36b486be14" } \ No newline at end of file diff --git a/sdk/ai/azure-ai-inference/customization/src/main/java/InferenceCustomizations.java b/sdk/ai/azure-ai-inference/customization/src/main/java/InferenceCustomizations.java index 088f3e38c582..4760628deece 100644 --- a/sdk/ai/azure-ai-inference/customization/src/main/java/InferenceCustomizations.java +++ b/sdk/ai/azure-ai-inference/customization/src/main/java/InferenceCustomizations.java @@ -2,7 +2,9 @@ import com.azure.autorest.customization.Customization; import com.azure.autorest.customization.LibraryCustomization; import com.azure.autorest.customization.PackageCustomization; +import com.azure.autorest.customization.MethodCustomization; import org.slf4j.Logger; +import com.github.javaparser.StaticJavaParser; import java.lang.reflect.Modifier; import java.util.Arrays; @@ -16,15 +18,36 @@ public class InferenceCustomizations extends Customization { @Override public void customize(LibraryCustomization customization, Logger logger) { // remove unused class (no reference to them, after partial-update) - customization.getRawEditor().removeFile("src/main/java/com/azure/ai/inference/implementation/models/CompleteOptions.java"); PackageCustomization implModels = customization.getPackage("com.azure.ai.inference.implementation.models"); ClassCustomization embedRequest1 = implModels.getClass("EmbedRequest1"); embedRequest1.rename("ImageEmbedRequest"); + PackageCustomization inferenceModels = customization.getPackage("com.azure.ai.inference.models"); + inferenceModels.getClass("ChatCompletionsOptions").customizeAst(ast -> { + ast.addImport("com.azure.ai.inference.implementation.accesshelpers.ChatCompletionsOptionsAccessHelper"); + + ast.getClassByName("ChatCompletionsOptions").ifPresent(clazz -> { + + // Add Accessor to ChatCompletionsOptions + clazz.setMembers(clazz.getMembers() + .addFirst(StaticJavaParser.parseBodyDeclaration(String.join("\n", "static {", + " ChatCompletionsOptionsAccessHelper.setAccessor(new ChatCompletionsOptionsAccessHelper.ChatCompletionsOptionsAccessor() {", + " @Override", + " public void setStream(ChatCompletionsOptions options, boolean stream) {", + " options.setStream(stream);", + " }", + " });", + "}")))); + }); + }); + PackageCustomization base = customization.getPackage("com.azure.ai.inference"); + ClassCustomization serviceVersion = base.getClass("ModelServiceVersion"); + serviceVersion.getMethod("getLatest") + .replaceBody("return V2024_05_01_PREVIEW;"); customizeChatCompletionsBaseClasses(customization, logger); } private void customizeChatCompletionsBaseClasses(LibraryCustomization customization, Logger logger) { - List classList = Arrays.asList("ChatCompletionsNamedToolSelection", "ChatCompletionsToolCall", "ChatCompletionsToolDefinition"); + List classList = Arrays.asList("ChatCompletionsNamedToolChoice", "ChatCompletionsToolCall", "ChatCompletionsToolDefinition"); for (String className : classList) { logger.info("Customizing the {} class", className); ClassCustomization namedToolSelectionClass = customization.getPackage("com.azure.ai.inference.models").getClass(className); diff --git a/sdk/ai/azure-ai-inference/pom.xml b/sdk/ai/azure-ai-inference/pom.xml index 842ce6eb68ab..bcd44d902e5c 100644 --- a/sdk/ai/azure-ai-inference/pom.xml +++ b/sdk/ai/azure-ai-inference/pom.xml @@ -14,7 +14,7 @@ com.azure azure-ai-inference - 1.0.0-beta.3 + 1.0.0-beta.5 jar Microsoft Azure SDK for Inference @@ -63,29 +63,29 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 com.azure azure-identity - 1.15.0 + 1.15.4 test @@ -97,19 +97,19 @@ com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.52 + 1.0.0-beta.56 test io.opentelemetry opentelemetry-sdk-extension-autoconfigure - 1.43.0 + 1.46.0 test io.opentelemetry opentelemetry-exporter-otlp - 1.43.0 + 1.46.0 test @@ -125,7 +125,7 @@ - io.opentelemetry:opentelemetry-exporter-otlp:[1.43.0] + io.opentelemetry:opentelemetry-exporter-otlp:[1.46.0] diff --git a/sdk/ai/azure-ai-inference/spotbugs-exclude.xml b/sdk/ai/azure-ai-inference/spotbugs-exclude.xml index cc6b4be8e351..1851bfe1b1f9 100644 --- a/sdk/ai/azure-ai-inference/spotbugs-exclude.xml +++ b/sdk/ai/azure-ai-inference/spotbugs-exclude.xml @@ -46,7 +46,7 @@ - + diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/ChatCompletionsAsyncClient.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/ChatCompletionsAsyncClient.java index f7ae795ad0f4..27a07946538b 100644 --- a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/ChatCompletionsAsyncClient.java +++ b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/ChatCompletionsAsyncClient.java @@ -164,12 +164,12 @@ private Mono> completeWithResponse(BinaryData completeReque * Returns information about the AI model. * The method makes a REST API call to the `/info` route on the given endpoint. *

Response Body Schema

- * + * *
      * {@code
      * {
      *     model_name: String (Required)
-     *     model_type: String(embeddings/image_generation/text_generation/image_embeddings/audio_generation/chat) (Required)
+     *     model_type: String(embeddings/image_generation/text_generation/image_embeddings/audio_generation/chat_completion) (Required)
      *     model_provider_name: String (Required)
      * }
      * }
diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/ChatCompletionsClient.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/ChatCompletionsClient.java
index 77671227e57c..6eb7d2787c15 100644
--- a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/ChatCompletionsClient.java
+++ b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/ChatCompletionsClient.java
@@ -163,12 +163,12 @@ public Response completeWithResponse(BinaryData completeRequest, Req
      * Returns information about the AI model.
      * The method makes a REST API call to the `/info` route on the given endpoint.
      * 

Response Body Schema

- * + * *
      * {@code
      * {
      *     model_name: String (Required)
-     *     model_type: String(embeddings/image_generation/text_generation/image_embeddings/audio_generation/chat) (Required)
+     *     model_type: String(embeddings/image_generation/text_generation/image_embeddings/audio_generation/chat_completion) (Required)
      *     model_provider_name: String (Required)
      * }
      * }
diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/EmbeddingsAsyncClient.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/EmbeddingsAsyncClient.java
index 652c4d207fa0..38c69d036fbc 100644
--- a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/EmbeddingsAsyncClient.java
+++ b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/EmbeddingsAsyncClient.java
@@ -83,6 +83,7 @@ public final class EmbeddingsAsyncClient {
      * 
      * {@code
      * {
+     *     id: String (Required)
      *     data (Required): [
      *          (Required){
      *             embedding: BinaryData (Required)
@@ -98,7 +99,7 @@ public final class EmbeddingsAsyncClient {
      * }
      * 
* - * @param embedRequest The embedRequest parameter. + * @param body request options to pass to the endpoint using embeddings path. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -111,8 +112,8 @@ public final class EmbeddingsAsyncClient { */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) - Mono> embedWithResponse(BinaryData embedRequest, RequestOptions requestOptions) { - return this.serviceClient.embedWithResponseAsync(embedRequest, requestOptions); + Mono> embedWithResponse(BinaryData body, RequestOptions requestOptions) { + return this.serviceClient.embedWithResponseAsync(body, requestOptions); } /** @@ -124,7 +125,7 @@ Mono> embedWithResponse(BinaryData embedRequest, RequestOpt * {@code * { * model_name: String (Required) - * model_type: String(embeddings/image_generation/text_generation/image_embeddings/audio_generation/chat) (Required) + * model_type: String(embeddings/image_generation/text_generation/image_embeddings/audio_generation/chat_completion) (Required) * model_provider_name: String (Required) * } * } diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/EmbeddingsClient.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/EmbeddingsClient.java index 7acec4c86e0f..d7406a0ba33a 100644 --- a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/EmbeddingsClient.java +++ b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/EmbeddingsClient.java @@ -81,6 +81,7 @@ public final class EmbeddingsClient { *
      * {@code
      * {
+     *     id: String (Required)
      *     data (Required): [
      *          (Required){
      *             embedding: BinaryData (Required)
@@ -96,7 +97,7 @@ public final class EmbeddingsClient {
      * }
      * 
* - * @param embedRequest The embedRequest parameter. + * @param body request options to pass to the endpoint using embeddings path. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -108,8 +109,8 @@ public final class EmbeddingsClient { */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) - Response embedWithResponse(BinaryData embedRequest, RequestOptions requestOptions) { - return this.serviceClient.embedWithResponse(embedRequest, requestOptions); + Response embedWithResponse(BinaryData body, RequestOptions requestOptions) { + return this.serviceClient.embedWithResponse(body, requestOptions); } /** @@ -121,7 +122,7 @@ Response embedWithResponse(BinaryData embedRequest, RequestOptions r * {@code * { * model_name: String (Required) - * model_type: String(embeddings/image_generation/text_generation/image_embeddings/audio_generation/chat) (Required) + * model_type: String(embeddings/image_generation/text_generation/image_embeddings/audio_generation/chat_completion) (Required) * model_provider_name: String (Required) * } * } diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/EmbeddingsClientBuilder.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/EmbeddingsClientBuilder.java index 47e2136b727c..f71af3a95c51 100644 --- a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/EmbeddingsClientBuilder.java +++ b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/EmbeddingsClientBuilder.java @@ -205,7 +205,7 @@ public EmbeddingsClientBuilder credential(TokenCredential tokenCredential) { * Sets auth domain scopes for client authentication. * * @param scopes domain scope to authenticate against. - * @return the ChatCompletionsClientBuilder. + * @return the EmbeddingsClientBuilder. */ public EmbeddingsClientBuilder scopes(String[] scopes) { this.scopes = scopes; diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/ImageEmbeddingsAsyncClient.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/ImageEmbeddingsAsyncClient.java index 4ecafd484b61..a6df9a2e45a5 100644 --- a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/ImageEmbeddingsAsyncClient.java +++ b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/ImageEmbeddingsAsyncClient.java @@ -5,11 +5,9 @@ import com.azure.ai.inference.implementation.ImageEmbeddingsClientImpl; import com.azure.ai.inference.implementation.models.ImageEmbedRequest; -import com.azure.ai.inference.models.EmbeddingEncodingFormat; -import com.azure.ai.inference.models.EmbeddingInput; -import com.azure.ai.inference.models.EmbeddingInputType; import com.azure.ai.inference.models.EmbeddingsResult; import com.azure.ai.inference.models.ExtraParameters; +import com.azure.ai.inference.models.ImageEmbeddingInput; import com.azure.ai.inference.models.ModelInfo; import com.azure.core.annotation.Generated; import com.azure.core.annotation.ReturnType; @@ -86,6 +84,7 @@ public final class ImageEmbeddingsAsyncClient { *
      * {@code
      * {
+     *     id: String (Required)
      *     data (Required): [
      *          (Required){
      *             embedding: BinaryData (Required)
@@ -101,7 +100,7 @@ public final class ImageEmbeddingsAsyncClient {
      * }
      * 
* - * @param embedRequest1 The embedRequest1 parameter. + * @param body request options to pass to the endpoint using images embeddings path. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -114,8 +113,8 @@ public final class ImageEmbeddingsAsyncClient { */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) - Mono> embedWithResponse(BinaryData embedRequest1, RequestOptions requestOptions) { - return this.serviceClient.embedWithResponseAsync(embedRequest1, requestOptions); + Mono> embedWithResponse(BinaryData body, RequestOptions requestOptions) { + return this.serviceClient.embedWithResponseAsync(body, requestOptions); } /** @@ -127,7 +126,7 @@ Mono> embedWithResponse(BinaryData embedRequest1, RequestOp * {@code * { * model_name: String (Required) - * model_type: String(embeddings/image_generation/text_generation/image_embeddings/audio_generation/chat) (Required) + * model_type: String(embeddings/image_generation/text_generation/image_embeddings/audio_generation/chat_completion) (Required) * model_provider_name: String (Required) * } * } @@ -148,11 +147,12 @@ Mono> getModelInfoWithResponse(RequestOptions requestOption } /** - * Return the embedding vectors for given images. - * The method makes a REST API call to the `/images/embeddings` route on the given endpoint. + * Return the embedding vectors for given text prompts. + * The method makes a REST API call to the `/embeddings` route on the given endpoint. * - * @param input Input image to embed. To embed multiple inputs in a single request, pass an array. - * The input must not exceed the max input tokens for the model. + * @param input Inputs, instances of ImageEmbeddingsInput. + * To embed multiple inputs in a single request, pass an array + * of strings or array of token arrays. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -160,17 +160,16 @@ Mono> getModelInfoWithResponse(RequestOptions requestOption * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return representation of the response data from an embeddings request. - * Embeddings measure the relatedness of text strings and are commonly used for search, clustering, + * Image embeddings measure the relatedness of images and are commonly used for search, clustering, * recommendations, and other similar scenarios on successful completion of {@link Mono}. */ - @Generated @ServiceMethod(returns = ReturnType.SINGLE) - Mono embed(List input) { + public Mono embed(List input) { // Generated convenience method for embedWithResponse RequestOptions requestOptions = new RequestOptions(); - ImageEmbedRequest embedRequest1Obj = new ImageEmbedRequest(input); - BinaryData embedRequest1 = BinaryData.fromObject(embedRequest1Obj); - return embedWithResponse(embedRequest1, requestOptions).flatMap(FluxUtil::toMono) + ImageEmbedRequest embedRequestObj = new ImageEmbedRequest(input); + BinaryData embedRequest = BinaryData.fromObject(embedRequestObj); + return embedWithResponse(embedRequest, requestOptions).flatMap(FluxUtil::toMono) .map(protocolMethodData -> protocolMethodData.toObject(EmbeddingsResult.class)); } @@ -198,20 +197,10 @@ Mono getModelInfo() { * Return the embedding vectors for given images. * The method makes a REST API call to the `/images/embeddings` route on the given endpoint. * - * @param input Input image to embed. To embed multiple inputs in a single request, pass an array. - * The input must not exceed the max input tokens for the model. + * @param body request options to pass to the endpoint using images embeddings path. * @param extraParams Controls what happens if extra parameters, undefined by the REST API, * are passed in the JSON request payload. * This sets the HTTP request header `extra-parameters`. - * @param dimensions Optional. The number of dimensions the resulting output embeddings should have. - * Passing null causes the model to use its default value. - * Returns a 422 error if the model doesn't support the value or parameter. - * @param encodingFormat Optional. The number of dimensions the resulting output embeddings should have. - * Passing null causes the model to use its default value. - * Returns a 422 error if the model doesn't support the value or parameter. - * @param inputType Optional. The type of the input. - * Returns a 422 error if the model doesn't support the value or parameter. - * @param model ID of the specific AI model to use, if more than one model is available on the endpoint. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -224,19 +213,37 @@ Mono getModelInfo() { */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) - Mono embed(List input, ExtraParameters extraParams, Integer dimensions, - EmbeddingEncodingFormat encodingFormat, EmbeddingInputType inputType, String model) { + Mono embed(ImageEmbedRequest body, ExtraParameters extraParams) { // Generated convenience method for embedWithResponse RequestOptions requestOptions = new RequestOptions(); - ImageEmbedRequest embedRequest1Obj = new ImageEmbedRequest(input).setDimensions(dimensions) - .setEncodingFormat(encodingFormat) - .setInputType(inputType) - .setModel(model); - BinaryData embedRequest1 = BinaryData.fromObject(embedRequest1Obj); if (extraParams != null) { requestOptions.setHeader(HttpHeaderName.fromString("extra-parameters"), extraParams.toString()); } - return embedWithResponse(embedRequest1, requestOptions).flatMap(FluxUtil::toMono) + return embedWithResponse(BinaryData.fromObject(body), requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(EmbeddingsResult.class)); + } + + /** + * Return the embedding vectors for given images. + * The method makes a REST API call to the `/images/embeddings` route on the given endpoint. + * + * @param body request options to pass to the endpoint using images embeddings path. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return representation of the response data from an embeddings request. + * Embeddings measure the relatedness of text strings and are commonly used for search, clustering, + * recommendations, and other similar scenarios on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + Mono embed(ImageEmbedRequest body) { + // Generated convenience method for embedWithResponse + RequestOptions requestOptions = new RequestOptions(); + return embedWithResponse(BinaryData.fromObject(body), requestOptions).flatMap(FluxUtil::toMono) .map(protocolMethodData -> protocolMethodData.toObject(EmbeddingsResult.class)); } } diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/ImageEmbeddingsClient.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/ImageEmbeddingsClient.java index 7f3cd6f5314f..49bce791e378 100644 --- a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/ImageEmbeddingsClient.java +++ b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/ImageEmbeddingsClient.java @@ -5,11 +5,9 @@ import com.azure.ai.inference.implementation.ImageEmbeddingsClientImpl; import com.azure.ai.inference.implementation.models.ImageEmbedRequest; -import com.azure.ai.inference.models.EmbeddingEncodingFormat; -import com.azure.ai.inference.models.EmbeddingInput; -import com.azure.ai.inference.models.EmbeddingInputType; import com.azure.ai.inference.models.EmbeddingsResult; import com.azure.ai.inference.models.ExtraParameters; +import com.azure.ai.inference.models.ImageEmbeddingInput; import com.azure.ai.inference.models.ModelInfo; import com.azure.core.annotation.Generated; import com.azure.core.annotation.ReturnType; @@ -84,6 +82,7 @@ public final class ImageEmbeddingsClient { *
      * {@code
      * {
+     *     id: String (Required)
      *     data (Required): [
      *          (Required){
      *             embedding: BinaryData (Required)
@@ -99,7 +98,7 @@ public final class ImageEmbeddingsClient {
      * }
      * 
* - * @param embedRequest1 The embedRequest1 parameter. + * @param body request options to pass to the endpoint using images embeddings path. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -111,8 +110,34 @@ public final class ImageEmbeddingsClient { */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) - Response embedWithResponse(BinaryData embedRequest1, RequestOptions requestOptions) { - return this.serviceClient.embedWithResponse(embedRequest1, requestOptions); + Response embedWithResponse(BinaryData body, RequestOptions requestOptions) { + return this.serviceClient.embedWithResponse(body, requestOptions); + } + + /** + * Return the embedding vectors for given text prompts. + * The method makes a REST API call to the `/embeddings` route on the given endpoint. + * + * @param inputs ImageEmbeddingInput instances to embed, encoded as a string or array of tokens. + * To embed multiple inputs in a single request, pass an array + * of strings or array of token arrays. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return representation of the response data from an embeddings request. + * Embeddings measure the relatedness of text strings and are commonly used for search, clustering, + * recommendations, and other similar scenarios. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public EmbeddingsResult embed(List inputs) { + // Generated convenience method for embedWithResponse + RequestOptions requestOptions = new RequestOptions(); + ImageEmbedRequest embedRequestObj = new ImageEmbedRequest(inputs); + BinaryData embedRequest = BinaryData.fromObject(embedRequestObj); + return embedWithResponse(embedRequest, requestOptions).getValue().toObject(EmbeddingsResult.class); } /** @@ -124,7 +149,7 @@ Response embedWithResponse(BinaryData embedRequest1, RequestOptions * {@code * { * model_name: String (Required) - * model_type: String(embeddings/image_generation/text_generation/image_embeddings/audio_generation/chat) (Required) + * model_type: String(embeddings/image_generation/text_generation/image_embeddings/audio_generation/chat_completion) (Required) * model_provider_name: String (Required) * } * } @@ -144,68 +169,59 @@ Response getModelInfoWithResponse(RequestOptions requestOptions) { } /** - * Return the embedding vectors for given images. - * The method makes a REST API call to the `/images/embeddings` route on the given endpoint. + * Returns information about the AI model. + * The method makes a REST API call to the `/info` route on the given endpoint. * - * @param input Input image to embed. To embed multiple inputs in a single request, pass an array. - * The input must not exceed the max input tokens for the model. - * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return representation of the response data from an embeddings request. - * Embeddings measure the relatedness of text strings and are commonly used for search, clustering, - * recommendations, and other similar scenarios. + * @return represents some basic information about the AI model. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) - EmbeddingsResult embed(List input) { - // Generated convenience method for embedWithResponse + ModelInfo getModelInfo() { + // Generated convenience method for getModelInfoWithResponse RequestOptions requestOptions = new RequestOptions(); - ImageEmbedRequest embedRequest1Obj = new ImageEmbedRequest(input); - BinaryData embedRequest1 = BinaryData.fromObject(embedRequest1Obj); - return embedWithResponse(embedRequest1, requestOptions).getValue().toObject(EmbeddingsResult.class); + return getModelInfoWithResponse(requestOptions).getValue().toObject(ModelInfo.class); } /** - * Returns information about the AI model. - * The method makes a REST API call to the `/info` route on the given endpoint. + * Return the embedding vectors for given images. + * The method makes a REST API call to the `/images/embeddings` route on the given endpoint. * + * @param body request options to pass to the endpoint using images embeddings path. + * @param extraParams Controls what happens if extra parameters, undefined by the REST API, + * are passed in the JSON request payload. + * This sets the HTTP request header `extra-parameters`. + * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents some basic information about the AI model. + * @return representation of the response data from an embeddings request. + * Embeddings measure the relatedness of text strings and are commonly used for search, clustering, + * recommendations, and other similar scenarios. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) - ModelInfo getModelInfo() { - // Generated convenience method for getModelInfoWithResponse + EmbeddingsResult embed(ImageEmbedRequest body, ExtraParameters extraParams) { + // Generated convenience method for embedWithResponse RequestOptions requestOptions = new RequestOptions(); - return getModelInfoWithResponse(requestOptions).getValue().toObject(ModelInfo.class); + if (extraParams != null) { + requestOptions.setHeader(HttpHeaderName.fromString("extra-parameters"), extraParams.toString()); + } + return embedWithResponse(BinaryData.fromObject(body), requestOptions).getValue() + .toObject(EmbeddingsResult.class); } /** * Return the embedding vectors for given images. * The method makes a REST API call to the `/images/embeddings` route on the given endpoint. * - * @param input Input image to embed. To embed multiple inputs in a single request, pass an array. - * The input must not exceed the max input tokens for the model. - * @param extraParams Controls what happens if extra parameters, undefined by the REST API, - * are passed in the JSON request payload. - * This sets the HTTP request header `extra-parameters`. - * @param dimensions Optional. The number of dimensions the resulting output embeddings should have. - * Passing null causes the model to use its default value. - * Returns a 422 error if the model doesn't support the value or parameter. - * @param encodingFormat Optional. The number of dimensions the resulting output embeddings should have. - * Passing null causes the model to use its default value. - * Returns a 422 error if the model doesn't support the value or parameter. - * @param inputType Optional. The type of the input. - * Returns a 422 error if the model doesn't support the value or parameter. - * @param model ID of the specific AI model to use, if more than one model is available on the endpoint. + * @param body request options to pass to the endpoint using images embeddings path. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -218,18 +234,10 @@ ModelInfo getModelInfo() { */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) - EmbeddingsResult embed(List input, ExtraParameters extraParams, Integer dimensions, - EmbeddingEncodingFormat encodingFormat, EmbeddingInputType inputType, String model) { + EmbeddingsResult embed(ImageEmbedRequest body) { // Generated convenience method for embedWithResponse RequestOptions requestOptions = new RequestOptions(); - ImageEmbedRequest embedRequest1Obj = new ImageEmbedRequest(input).setDimensions(dimensions) - .setEncodingFormat(encodingFormat) - .setInputType(inputType) - .setModel(model); - BinaryData embedRequest1 = BinaryData.fromObject(embedRequest1Obj); - if (extraParams != null) { - requestOptions.setHeader(HttpHeaderName.fromString("extra-parameters"), extraParams.toString()); - } - return embedWithResponse(embedRequest1, requestOptions).getValue().toObject(EmbeddingsResult.class); + return embedWithResponse(BinaryData.fromObject(body), requestOptions).getValue() + .toObject(EmbeddingsResult.class); } } diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/ImageEmbeddingsClientBuilder.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/ImageEmbeddingsClientBuilder.java index a9ea0a28beac..e77ba83f5d7b 100644 --- a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/ImageEmbeddingsClientBuilder.java +++ b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/ImageEmbeddingsClientBuilder.java @@ -65,6 +65,8 @@ public final class ImageEmbeddingsClientBuilder implements HttpTrait pipelinePolicies; + private String[] scopes = DEFAULT_SCOPES; + /** * Create an instance of the ImageEmbeddingsClientBuilder. */ @@ -267,6 +269,17 @@ public ImageEmbeddingsClientBuilder retryPolicy(RetryPolicy retryPolicy) { return this; } + /** + * Sets auth domain scopes for client authentication. + * + * @param scopes domain scope to authenticate against. + * @return the ImageEmbeddingsClientBuilder. + */ + public ImageEmbeddingsClientBuilder scopes(String[] scopes) { + this.scopes = scopes; + return this; + } + /** * Builds an instance of ImageEmbeddingsClientImpl with the provided parameters. * @@ -317,7 +330,7 @@ private HttpPipeline createHttpPipeline() { policies.add(new KeyCredentialPolicy("Authorization", keyCredential)); } if (tokenCredential != null) { - policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPES)); + policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, this.scopes)); } this.pipelinePolicies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/ModelServiceVersion.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/ModelServiceVersion.java index 269914beaec8..398e1893d764 100644 --- a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/ModelServiceVersion.java +++ b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/ModelServiceVersion.java @@ -13,7 +13,12 @@ public enum ModelServiceVersion implements ServiceVersion { /** * Enum value 2024-05-01-preview. */ - V2024_05_01_PREVIEW("2024-05-01-preview"); + V2024_05_01_PREVIEW("2024-05-01-preview"), + + /** + * Enum value 2024-08-01-preview. + */ + V2024_08_01_PREVIEW("2024-08-01-preview"); private final String version; diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/implementation/ChatCompletionsClientImpl.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/implementation/ChatCompletionsClientImpl.java index 6d104cd366f5..6a89faaedaea 100644 --- a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/implementation/ChatCompletionsClientImpl.java +++ b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/implementation/ChatCompletionsClientImpl.java @@ -155,7 +155,7 @@ public interface ChatCompletionsClientService { @UnexpectedResponseExceptionType(HttpResponseException.class) Mono> complete(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, - @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData completeRequest, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData body, RequestOptions requestOptions, Context context); @Post("/chat/completions") @@ -166,7 +166,7 @@ Mono> complete(@HostParam("endpoint") String endpoint, @UnexpectedResponseExceptionType(HttpResponseException.class) Response completeSync(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, - @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData completeRequest, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData body, RequestOptions requestOptions, Context context); @Get("/info") @@ -212,7 +212,7 @@ Response getModelInfoSync(@HostParam("endpoint") String endpoint, * { * messages (Required): [ * (Required){ - * role: String(system/user/assistant/tool) (Required) + * role: String(system/user/assistant/tool/developer) (Required) * } * ] * frequency_penalty: Double (Optional) @@ -265,7 +265,7 @@ Response getModelInfoSync(@HostParam("endpoint") String endpoint, * index: int (Required) * finish_reason: String(stop/length/content_filter/tool_calls) (Required) * message (Required): { - * role: String(system/user/assistant/tool) (Required) + * role: String(system/user/assistant/tool/developer) (Required) * content: String (Required) * tool_calls (Optional): [ * (Optional){ @@ -284,7 +284,7 @@ Response getModelInfoSync(@HostParam("endpoint") String endpoint, * } *
* - * @param completeRequest The completeRequest parameter. + * @param body request options to pass to the endpoint using complete path. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -295,12 +295,11 @@ Response getModelInfoSync(@HostParam("endpoint") String endpoint, * provided prompt data along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> completeWithResponseAsync(BinaryData completeRequest, - RequestOptions requestOptions) { + public Mono> completeWithResponseAsync(BinaryData body, RequestOptions requestOptions) { final String contentType = "application/json"; final String accept = "application/json"; return FluxUtil.withContext(context -> service.complete(this.getEndpoint(), - this.getServiceVersion().getVersion(), contentType, accept, completeRequest, requestOptions, context)); + this.getServiceVersion().getVersion(), contentType, accept, body, requestOptions, context)); } /** @@ -325,7 +324,7 @@ public Mono> completeWithResponseAsync(BinaryData completeR * { * messages (Required): [ * (Required){ - * role: String(system/user/assistant/tool) (Required) + * role: String(system/user/assistant/tool/developer) (Required) * } * ] * frequency_penalty: Double (Optional) @@ -378,7 +377,7 @@ public Mono> completeWithResponseAsync(BinaryData completeR * index: int (Required) * finish_reason: String(stop/length/content_filter/tool_calls) (Required) * message (Required): { - * role: String(system/user/assistant/tool) (Required) + * role: String(system/user/assistant/tool/developer) (Required) * content: String (Required) * tool_calls (Optional): [ * (Optional){ @@ -397,7 +396,7 @@ public Mono> completeWithResponseAsync(BinaryData completeR * } *
* - * @param completeRequest The completeRequest parameter. + * @param body request options to pass to the endpoint using complete path. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -408,11 +407,11 @@ public Mono> completeWithResponseAsync(BinaryData completeR * provided prompt data along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response completeWithResponse(BinaryData completeRequest, RequestOptions requestOptions) { + public Response completeWithResponse(BinaryData body, RequestOptions requestOptions) { final String contentType = "application/json"; final String accept = "application/json"; return service.completeSync(this.getEndpoint(), this.getServiceVersion().getVersion(), contentType, accept, - completeRequest, requestOptions, Context.NONE); + body, requestOptions, Context.NONE); } /** @@ -424,7 +423,7 @@ public Response completeWithResponse(BinaryData completeRequest, Req * {@code * { * model_name: String (Required) - * model_type: String(embeddings/image_generation/text_generation/image_embeddings/audio_generation/chat) (Required) + * model_type: String(embeddings/image_generation/text_generation/image_embeddings/audio_generation/chat_completion) (Required) * model_provider_name: String (Required) * } * } @@ -454,7 +453,7 @@ public Mono> getModelInfoWithResponseAsync(RequestOptions r * {@code * { * model_name: String (Required) - * model_type: String(embeddings/image_generation/text_generation/image_embeddings/audio_generation/chat) (Required) + * model_type: String(embeddings/image_generation/text_generation/image_embeddings/audio_generation/chat_completion) (Required) * model_provider_name: String (Required) * } * } diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/implementation/EmbeddingsClientImpl.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/implementation/EmbeddingsClientImpl.java index bd4e3a445921..3ff757182bbd 100644 --- a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/implementation/EmbeddingsClientImpl.java +++ b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/implementation/EmbeddingsClientImpl.java @@ -154,7 +154,7 @@ public interface EmbeddingsClientService { @UnexpectedResponseExceptionType(HttpResponseException.class) Mono> embed(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, - @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData embedRequest, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData body, RequestOptions requestOptions, Context context); @Post("/embeddings") @@ -165,7 +165,7 @@ Mono> embed(@HostParam("endpoint") String endpoint, @UnexpectedResponseExceptionType(HttpResponseException.class) Response embedSync(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, - @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData embedRequest, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData body, RequestOptions requestOptions, Context context); @Get("/info") @@ -226,6 +226,7 @@ Response getModelInfoSync(@HostParam("endpoint") String endpoint, *
      * {@code
      * {
+     *     id: String (Required)
      *     data (Required): [
      *          (Required){
      *             embedding: BinaryData (Required)
@@ -241,7 +242,7 @@ Response getModelInfoSync(@HostParam("endpoint") String endpoint,
      * }
      * 
* - * @param embedRequest The embedRequest parameter. + * @param body request options to pass to the endpoint using embeddings path. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -253,11 +254,11 @@ Response getModelInfoSync(@HostParam("endpoint") String endpoint, * {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> embedWithResponseAsync(BinaryData embedRequest, RequestOptions requestOptions) { + public Mono> embedWithResponseAsync(BinaryData body, RequestOptions requestOptions) { final String contentType = "application/json"; final String accept = "application/json"; return FluxUtil.withContext(context -> service.embed(this.getEndpoint(), this.getServiceVersion().getVersion(), - contentType, accept, embedRequest, requestOptions, context)); + contentType, accept, body, requestOptions, context)); } /** @@ -297,6 +298,7 @@ public Mono> embedWithResponseAsync(BinaryData embedRequest *
      * {@code
      * {
+     *     id: String (Required)
      *     data (Required): [
      *          (Required){
      *             embedding: BinaryData (Required)
@@ -312,7 +314,7 @@ public Mono> embedWithResponseAsync(BinaryData embedRequest
      * }
      * 
* - * @param embedRequest The embedRequest parameter. + * @param body request options to pass to the endpoint using embeddings path. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -323,11 +325,11 @@ public Mono> embedWithResponseAsync(BinaryData embedRequest * recommendations, and other similar scenarios along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response embedWithResponse(BinaryData embedRequest, RequestOptions requestOptions) { + public Response embedWithResponse(BinaryData body, RequestOptions requestOptions) { final String contentType = "application/json"; final String accept = "application/json"; - return service.embedSync(this.getEndpoint(), this.getServiceVersion().getVersion(), contentType, accept, - embedRequest, requestOptions, Context.NONE); + return service.embedSync(this.getEndpoint(), this.getServiceVersion().getVersion(), contentType, accept, body, + requestOptions, Context.NONE); } /** @@ -339,7 +341,7 @@ public Response embedWithResponse(BinaryData embedRequest, RequestOp * {@code * { * model_name: String (Required) - * model_type: String(embeddings/image_generation/text_generation/image_embeddings/audio_generation/chat) (Required) + * model_type: String(embeddings/image_generation/text_generation/image_embeddings/audio_generation/chat_completion) (Required) * model_provider_name: String (Required) * } * } @@ -369,7 +371,7 @@ public Mono> getModelInfoWithResponseAsync(RequestOptions r * {@code * { * model_name: String (Required) - * model_type: String(embeddings/image_generation/text_generation/image_embeddings/audio_generation/chat) (Required) + * model_type: String(embeddings/image_generation/text_generation/image_embeddings/audio_generation/chat_completion) (Required) * model_provider_name: String (Required) * } * } diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/implementation/ImageEmbeddingsClientImpl.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/implementation/ImageEmbeddingsClientImpl.java index 06c682f920c2..739594285376 100644 --- a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/implementation/ImageEmbeddingsClientImpl.java +++ b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/implementation/ImageEmbeddingsClientImpl.java @@ -155,7 +155,7 @@ public interface ImageEmbeddingsClientService { @UnexpectedResponseExceptionType(HttpResponseException.class) Mono> embed(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, - @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData embedRequest1, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData body, RequestOptions requestOptions, Context context); @Post("/images/embeddings") @@ -166,7 +166,7 @@ Mono> embed(@HostParam("endpoint") String endpoint, @UnexpectedResponseExceptionType(HttpResponseException.class) Response embedSync(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, - @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData embedRequest1, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData body, RequestOptions requestOptions, Context context); @Get("/info") @@ -230,6 +230,7 @@ Response getModelInfoSync(@HostParam("endpoint") String endpoint, *
      * {@code
      * {
+     *     id: String (Required)
      *     data (Required): [
      *          (Required){
      *             embedding: BinaryData (Required)
@@ -245,7 +246,7 @@ Response getModelInfoSync(@HostParam("endpoint") String endpoint,
      * }
      * 
* - * @param embedRequest1 The embedRequest1 parameter. + * @param body request options to pass to the endpoint using images embeddings path. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -257,11 +258,11 @@ Response getModelInfoSync(@HostParam("endpoint") String endpoint, * {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> embedWithResponseAsync(BinaryData embedRequest1, RequestOptions requestOptions) { + public Mono> embedWithResponseAsync(BinaryData body, RequestOptions requestOptions) { final String contentType = "application/json"; final String accept = "application/json"; return FluxUtil.withContext(context -> service.embed(this.getEndpoint(), this.getServiceVersion().getVersion(), - contentType, accept, embedRequest1, requestOptions, context)); + contentType, accept, body, requestOptions, context)); } /** @@ -304,6 +305,7 @@ public Mono> embedWithResponseAsync(BinaryData embedRequest *
      * {@code
      * {
+     *     id: String (Required)
      *     data (Required): [
      *          (Required){
      *             embedding: BinaryData (Required)
@@ -319,7 +321,7 @@ public Mono> embedWithResponseAsync(BinaryData embedRequest
      * }
      * 
* - * @param embedRequest1 The embedRequest1 parameter. + * @param body request options to pass to the endpoint using images embeddings path. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -330,11 +332,11 @@ public Mono> embedWithResponseAsync(BinaryData embedRequest * recommendations, and other similar scenarios along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response embedWithResponse(BinaryData embedRequest1, RequestOptions requestOptions) { + public Response embedWithResponse(BinaryData body, RequestOptions requestOptions) { final String contentType = "application/json"; final String accept = "application/json"; - return service.embedSync(this.getEndpoint(), this.getServiceVersion().getVersion(), contentType, accept, - embedRequest1, requestOptions, Context.NONE); + return service.embedSync(this.getEndpoint(), this.getServiceVersion().getVersion(), contentType, accept, body, + requestOptions, Context.NONE); } /** @@ -346,7 +348,7 @@ public Response embedWithResponse(BinaryData embedRequest1, RequestO * {@code * { * model_name: String (Required) - * model_type: String(embeddings/image_generation/text_generation/image_embeddings/audio_generation/chat) (Required) + * model_type: String(embeddings/image_generation/text_generation/image_embeddings/audio_generation/chat_completion) (Required) * model_provider_name: String (Required) * } * } @@ -376,7 +378,7 @@ public Mono> getModelInfoWithResponseAsync(RequestOptions r * {@code * { * model_name: String (Required) - * model_type: String(embeddings/image_generation/text_generation/image_embeddings/audio_generation/chat) (Required) + * model_type: String(embeddings/image_generation/text_generation/image_embeddings/audio_generation/chat_completion) (Required) * model_provider_name: String (Required) * } * } diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/implementation/models/ImageEmbedRequest.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/implementation/models/ImageEmbedRequest.java index dea09778466c..b5535023e2f5 100644 --- a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/implementation/models/ImageEmbedRequest.java +++ b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/implementation/models/ImageEmbedRequest.java @@ -4,8 +4,8 @@ package com.azure.ai.inference.implementation.models; import com.azure.ai.inference.models.EmbeddingEncodingFormat; -import com.azure.ai.inference.models.EmbeddingInput; import com.azure.ai.inference.models.EmbeddingInputType; +import com.azure.ai.inference.models.ImageEmbeddingInput; import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; import com.azure.core.util.BinaryData; @@ -29,7 +29,7 @@ public final class ImageEmbedRequest implements JsonSerializable input; + private final List input; /* * Optional. The number of dimensions the resulting output embeddings should have. @@ -72,7 +72,7 @@ public final class ImageEmbedRequest implements JsonSerializable input) { + public ImageEmbedRequest(List input) { this.input = input; } @@ -83,7 +83,7 @@ public ImageEmbedRequest(List input) { * @return the input value. */ @Generated - public List getInput() { + public List getInput() { return this.input; } @@ -245,7 +245,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static ImageEmbedRequest fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - List input = null; + List input = null; Integer dimensions = null; EmbeddingEncodingFormat encodingFormat = null; EmbeddingInputType inputType = null; @@ -255,7 +255,7 @@ public static ImageEmbedRequest fromJson(JsonReader jsonReader) throws IOExcepti String fieldName = reader.getFieldName(); reader.nextToken(); if ("input".equals(fieldName)) { - input = reader.readArray(reader1 -> EmbeddingInput.fromJson(reader1)); + input = reader.readArray(reader1 -> ImageEmbeddingInput.fromJson(reader1)); } else if ("dimensions".equals(fieldName)) { dimensions = reader.getNullable(JsonReader::getInt); } else if ("encoding_format".equals(fieldName)) { diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsFunctionToolSelection.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsFunctionToolSelection.java deleted file mode 100644 index 9db5a33e0b92..000000000000 --- a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsFunctionToolSelection.java +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.ai.inference.models; - -import com.azure.core.annotation.Generated; -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; - -/** - * A tool selection of a specific, named function tool that will limit chat completions to using the named function. - */ -@Immutable -public final class ChatCompletionsFunctionToolSelection - implements JsonSerializable { - - /* - * The name of the function that should be called. - */ - @Generated - private final String name; - - /** - * Creates an instance of ChatCompletionsFunctionToolSelection class. - * - * @param name the name value to set. - */ - @Generated - public ChatCompletionsFunctionToolSelection(String name) { - this.name = name; - } - - /** - * Get the name property: The name of the function that should be called. - * - * @return the name value. - */ - @Generated - 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/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsNamedFunctionToolSelection.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsNamedFunctionToolSelection.java deleted file mode 100644 index 8bd85b26b30c..000000000000 --- a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsNamedFunctionToolSelection.java +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.ai.inference.models; - -import com.azure.core.annotation.Generated; -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; - -/** - * A tool selection of a specific, named function tool that will limit chat completions to using the named function. - */ -@Immutable -public final class ChatCompletionsNamedFunctionToolSelection extends ChatCompletionsNamedToolSelection { - /* - * The object type. - */ - @Generated - private String type = "function"; - - /* - * The function that should be called. - */ - @Generated - private ChatCompletionsFunctionToolSelection function; - - /** - * Creates an instance of ChatCompletionsNamedFunctionToolSelection class. - * - * @param function the function value to set. - */ - @Generated - public ChatCompletionsNamedFunctionToolSelection(ChatCompletionsFunctionToolSelection function) { - super(function); - } - - /** - * Get the type property: The object type. - * - * @return the type value. - */ - @Generated - @Override - public String getType() { - return this.type; - } - - /** - * Get the function property: The function that should be called. - * - * @return the function value. - */ - @Generated - public ChatCompletionsFunctionToolSelection getFunction() { - return this.function; - } - - /** - * {@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/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsNamedToolChoice.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsNamedToolChoice.java new file mode 100644 index 000000000000..d8b43f29a025 --- /dev/null +++ b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsNamedToolChoice.java @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.inference.models; + +import com.azure.core.annotation.Generated; +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; + +/** + * A tool selection of a specific, named function tool that will limit chat completions to using the named function. + */ +@Immutable +public class ChatCompletionsNamedToolChoice implements JsonSerializable { + + /* + * The type of the tool. Currently, only `function` is supported. + */ + @Generated + private final String type = "function"; + + /* + * The function that should be called. + */ + @Generated + private final ChatCompletionsNamedToolChoiceFunction function; + + /** + * Creates an instance of ChatCompletionsNamedToolChoice class. + * + * @param function the function value to set. + */ + @Generated + public ChatCompletionsNamedToolChoice(ChatCompletionsNamedToolChoiceFunction function) { + this.function = function; + } + + /** + * Get the type property: The type of the tool. Currently, only `function` is supported. + * + * @return the type value. + */ + @Generated + public String getType() { + return this.type; + } + + /** + * Get the function property: The function that should be called. + * + * @return the function value. + */ + @Generated + public ChatCompletionsNamedToolChoiceFunction getFunction() { + return this.function; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type); + jsonWriter.writeJsonField("function", this.function); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatCompletionsNamedToolChoice from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatCompletionsNamedToolChoice 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 ChatCompletionsNamedToolChoice. + */ + @Generated + public static ChatCompletionsNamedToolChoice fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ChatCompletionsNamedToolChoiceFunction function = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("function".equals(fieldName)) { + function = ChatCompletionsNamedToolChoiceFunction.fromJson(reader); + } else { + reader.skipChildren(); + } + } + return new ChatCompletionsNamedToolChoice(function); + }); + } +} diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsNamedToolChoiceFunction.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsNamedToolChoiceFunction.java new file mode 100644 index 000000000000..24115a4bca04 --- /dev/null +++ b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsNamedToolChoiceFunction.java @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.inference.models; + +import com.azure.core.annotation.Generated; +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; + +/** + * A tool selection of a specific, named function tool that will limit chat completions to using the named function. + */ +@Immutable +public final class ChatCompletionsNamedToolChoiceFunction + implements JsonSerializable { + + /* + * The name of the function that should be called. + */ + @Generated + private final String name; + + /** + * Creates an instance of ChatCompletionsNamedToolChoiceFunction class. + * + * @param name the name value to set. + */ + @Generated + public ChatCompletionsNamedToolChoiceFunction(String name) { + this.name = name; + } + + /** + * Get the name property: The name of the function that should be called. + * + * @return the name value. + */ + @Generated + 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 ChatCompletionsNamedToolChoiceFunction from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatCompletionsNamedToolChoiceFunction 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 ChatCompletionsNamedToolChoiceFunction. + */ + @Generated + public static ChatCompletionsNamedToolChoiceFunction 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 ChatCompletionsNamedToolChoiceFunction(name); + }); + } +} diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsNamedToolSelection.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsNamedToolSelection.java deleted file mode 100644 index 3eb8ccaf531a..000000000000 --- a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsNamedToolSelection.java +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.ai.inference.models; - -import com.azure.core.annotation.Generated; -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; - -/** - * A tool selection of a specific, named function tool that will limit chat completions to using the named function. - */ -@Immutable -public class ChatCompletionsNamedToolSelection implements JsonSerializable { - - /* - * The type of the tool. Currently, only `function` is supported. - */ - @Generated - private final String type = "function"; - - /* - * The function that should be called. - */ - @Generated - private final ChatCompletionsFunctionToolSelection function; - - /** - * Creates an instance of ChatCompletionsNamedToolSelection class. - * - * @param function the function value to set. - */ - @Generated - public ChatCompletionsNamedToolSelection(ChatCompletionsFunctionToolSelection function) { - this.function = function; - } - - /** - * Get the type property: The type of the tool. Currently, only `function` is supported. - * - * @return the type value. - */ - @Generated - public String getType() { - return this.type; - } - - /** - * Get the function property: The function that should be called. - * - * @return the function value. - */ - @Generated - public ChatCompletionsFunctionToolSelection getFunction() { - return this.function; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("type", this.type); - jsonWriter.writeJsonField("function", this.function); - 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 IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the ChatCompletionsNamedToolSelection. - */ - @Generated - public static ChatCompletionsNamedToolSelection fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - ChatCompletionsFunctionToolSelection function = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - if ("function".equals(fieldName)) { - function = ChatCompletionsFunctionToolSelection.fromJson(reader); - } else { - reader.skipChildren(); - } - } - return new ChatCompletionsNamedToolSelection(function); - }); - } -} diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsOptions.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsOptions.java index d3a382d9e169..8f5bac952b09 100644 --- a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsOptions.java +++ b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsOptions.java @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) TypeSpec Code Generator. - package com.azure.ai.inference.models; import com.azure.ai.inference.implementation.accesshelpers.ChatCompletionsOptionsAccessHelper; @@ -12,24 +11,28 @@ import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; - import java.io.IOException; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; /** - * Options for complete API. + * The ChatCompletionsOptions model. */ @Fluent public final class ChatCompletionsOptions implements JsonSerializable { + static { ChatCompletionsOptionsAccessHelper .setAccessor(new ChatCompletionsOptionsAccessHelper.ChatCompletionsOptionsAccessor() { + @Override public void setStream(ChatCompletionsOptions options, boolean stream) { options.setStream(stream); } }); } + /* * The collection of context messages associated with this chat completions request. * Typical usage begins with a chat message for the System role that provides instructions for @@ -95,9 +98,19 @@ public void setStream(ChatCompletionsOptions options, boolean stream) { private Integer maxTokens; /* - * The format that the model must output. Use this to enable JSON mode instead of the default text mode. - * Note that to enable JSON mode, some AI models may also require you to instruct the model to produce JSON - * via a system or user message. + * An object specifying the format that the model must output. + * + * Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which ensures the model + * will match your supplied JSON schema. + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid + * JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system + * or user message. Without this, the model may generate an unending stream of whitespace until the generation + * reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message + * content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded + * `max_tokens` or the conversation exceeded the max context length. */ @Generated private ChatCompletionsResponseFormat responseFormat; @@ -109,7 +122,8 @@ public void setStream(ChatCompletionsOptions options, boolean stream) { private List stop; /* - * The available tool definitions that the chat completions request can use, including caller-defined functions. + * A list of tools the model may request to call. Currently, only functions are supported as a tool. The model + * may response with a function call request and provide the input arguments in JSON format for that function. */ @Generated private List tools; @@ -138,7 +152,6 @@ public void setStream(ChatCompletionsOptions options, boolean stream) { * are passed in the JSON request payload. * This sets the HTTP request header `extra-parameters`. */ - @Generated private ExtraParameters extraParams; /** @@ -340,10 +353,19 @@ public ChatCompletionsOptions setMaxTokens(Integer maxTokens) { } /** - * Get the responseFormat property: The format that the model must output. Use this to enable JSON mode instead of - * the default text mode. - * Note that to enable JSON mode, some AI models may also require you to instruct the model to produce JSON - * via a system or user message. + * Get the responseFormat property: An object specifying the format that the model must output. + * + * Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which ensures the model + * will match your supplied JSON schema. + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid + * JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system + * or user message. Without this, the model may generate an unending stream of whitespace until the generation + * reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message + * content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded + * `max_tokens` or the conversation exceeded the max context length. * * @return the responseFormat value. */ @@ -353,10 +375,19 @@ public ChatCompletionsResponseFormat getResponseFormat() { } /** - * Set the responseFormat property: The format that the model must output. Use this to enable JSON mode instead of - * the default text mode. - * Note that to enable JSON mode, some AI models may also require you to instruct the model to produce JSON - * via a system or user message. + * Set the responseFormat property: An object specifying the format that the model must output. + * + * Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which ensures the model + * will match your supplied JSON schema. + * + * Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid + * JSON. + * + * **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system + * or user message. Without this, the model may generate an unending stream of whitespace until the generation + * reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message + * content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded + * `max_tokens` or the conversation exceeded the max context length. * * @param responseFormat the responseFormat value to set. * @return the ChatCompletionsOptions object itself. @@ -367,6 +398,20 @@ public ChatCompletionsOptions setResponseFormat(ChatCompletionsResponseFormat re return this; } + /** + * Set the responseFormat to a given JSON schema: The format that the model must output. Use this to enable JSON + * mode instead of + * + * @param name the name of the schema. + * @param jsonSchema the JSON schema value to set. + * @return the ChatCompletionsOptions object itself. + */ + public ChatCompletionsOptions setJsonFormat(String name, Map jsonSchema) { + this.responseFormat = new ChatCompletionsResponseFormatJsonSchema( + new ChatCompletionsResponseFormatJsonSchemaDefinition(name, jsonSchema)); + return this; + } + /** * Get the stop property: A collection of textual sequences that will end completions generation. * @@ -390,8 +435,9 @@ public ChatCompletionsOptions setStop(List stop) { } /** - * Get the tools property: The available tool definitions that the chat completions request can use, including - * caller-defined functions. + * Get the tools property: A list of tools the model may request to call. Currently, only functions are supported as + * a tool. The model + * may response with a function call request and provide the input arguments in JSON format for that function. * * @return the tools value. */ @@ -401,8 +447,9 @@ public List getTools() { } /** - * Set the tools property: The available tool definitions that the chat completions request can use, including - * caller-defined functions. + * Set the tools property: A list of tools the model may request to call. Currently, only functions are supported as + * a tool. The model + * may response with a function call request and provide the input arguments in JSON format for that function. * * @param tools the tools value to set. * @return the ChatCompletionsOptions object itself. @@ -492,7 +539,6 @@ public ChatCompletionsOptions setModel(String model) { * * @return the extraParams value. */ - @Generated public ExtraParameters getExtraParams() { return this.extraParams; } @@ -505,7 +551,6 @@ public ExtraParameters getExtraParams() { * @param extraParams the extraParams value to set. * @return the ChatCompletionsOptions object itself. */ - @Generated public ChatCompletionsOptions setExtraParams(ExtraParameters extraParams) { this.extraParams = extraParams; return this; @@ -513,6 +558,7 @@ public ChatCompletionsOptions setExtraParams(ExtraParameters extraParams) { /** * {@inheritDoc} + * * @throws IOException If an error occurs while writing fields to the ChatCompletionsOptions instance. */ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @@ -548,66 +594,100 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { public static ChatCompletionsOptions fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { List messages = null; - Integer maxTokens = null; - Double temperature = null; - Double topP = null; - List stop = null; - Double presencePenalty = null; Double frequencyPenalty = null; Boolean stream = null; - String model = null; - Long seed = null; + Double presencePenalty = null; + Double temperature = null; + Double topP = null; + Integer maxTokens = null; ChatCompletionsResponseFormat responseFormat = null; + List stop = null; List tools = null; BinaryData toolChoice = null; + Long seed = null; + String model = null; + Map additionalProperties = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("messages".equals(fieldName)) { - messages = reader.readArray(ChatRequestMessage::fromJson); - } 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 ("stop".equals(fieldName)) { - stop = reader.readArray(JsonReader::getString); - } else if ("presence_penalty".equals(fieldName)) { - presencePenalty = reader.getNullable(JsonReader::getDouble); + messages = reader.readArray(reader1 -> ChatRequestMessage.fromJson(reader1)); } 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 ("seed".equals(fieldName)) { - seed = reader.getNullable(JsonReader::getLong); + } else if ("presence_penalty".equals(fieldName)) { + presencePenalty = reader.getNullable(JsonReader::getDouble); + } else if ("temperature".equals(fieldName)) { + temperature = reader.getNullable(JsonReader::getDouble); + } else if ("top_p".equals(fieldName)) { + topP = reader.getNullable(JsonReader::getDouble); + } else if ("max_tokens".equals(fieldName)) { + maxTokens = reader.getNullable(JsonReader::getInt); } else if ("response_format".equals(fieldName)) { responseFormat = ChatCompletionsResponseFormat.fromJson(reader); + } else if ("stop".equals(fieldName)) { + stop = reader.readArray(reader1 -> reader1.getString()); } else if ("tools".equals(fieldName)) { - tools = reader.readArray(ChatCompletionsToolDefinition::fromJson); + tools = reader.readArray(reader1 -> ChatCompletionsToolDefinition.fromJson(reader1)); } else if ("tool_choice".equals(fieldName)) { toolChoice = reader.getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped())); + } else if ("seed".equals(fieldName)) { + seed = reader.getNullable(JsonReader::getLong); + } else if ("model".equals(fieldName)) { + model = reader.getString(); } else { - reader.skipChildren(); + if (additionalProperties == null) { + additionalProperties = new LinkedHashMap<>(); + } + additionalProperties.put(fieldName, + reader.getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); } } ChatCompletionsOptions deserializedChatCompletionsOptions = new ChatCompletionsOptions(messages); - deserializedChatCompletionsOptions.maxTokens = maxTokens; - deserializedChatCompletionsOptions.temperature = temperature; - deserializedChatCompletionsOptions.topP = topP; - deserializedChatCompletionsOptions.stop = stop; - deserializedChatCompletionsOptions.presencePenalty = presencePenalty; deserializedChatCompletionsOptions.frequencyPenalty = frequencyPenalty; deserializedChatCompletionsOptions.stream = stream; - deserializedChatCompletionsOptions.model = model; - deserializedChatCompletionsOptions.seed = seed; + deserializedChatCompletionsOptions.presencePenalty = presencePenalty; + deserializedChatCompletionsOptions.temperature = temperature; + deserializedChatCompletionsOptions.topP = topP; + deserializedChatCompletionsOptions.maxTokens = maxTokens; deserializedChatCompletionsOptions.responseFormat = responseFormat; + deserializedChatCompletionsOptions.stop = stop; deserializedChatCompletionsOptions.tools = tools; deserializedChatCompletionsOptions.toolChoice = toolChoice; + deserializedChatCompletionsOptions.seed = seed; + deserializedChatCompletionsOptions.model = model; + deserializedChatCompletionsOptions.additionalProperties = additionalProperties; return deserializedChatCompletionsOptions; }); } + + /* + * The ChatCompletionsOptions model + */ + @Generated + private Map additionalProperties; + + /** + * Get the additionalProperties property: The ChatCompletionsOptions model. + * + * @return the additionalProperties value. + */ + @Generated + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + /** + * Set the additionalProperties property: The ChatCompletionsOptions model. + * + * @param additionalProperties the additionalProperties value to set. + * @return the ChatCompletionsOptions object itself. + */ + @Generated + public ChatCompletionsOptions setAdditionalProperties(Map additionalProperties) { + this.additionalProperties = additionalProperties; + return this; + } } diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsResponseFormat.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsResponseFormat.java index 984ba391e541..e3a9759f3330 100644 --- a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsResponseFormat.java +++ b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsResponseFormat.java @@ -82,7 +82,9 @@ public static ChatCompletionsResponseFormat fromJson(JsonReader jsonReader) thro if ("text".equals(discriminatorValue)) { return ChatCompletionsResponseFormatText.fromJson(readerToUse.reset()); } else if ("json_object".equals(discriminatorValue)) { - return ChatCompletionsResponseFormatJson.fromJson(readerToUse.reset()); + return ChatCompletionsResponseFormatJsonObject.fromJson(readerToUse.reset()); + } else if ("json_schema".equals(discriminatorValue)) { + return ChatCompletionsResponseFormatJsonSchema.fromJson(readerToUse.reset()); } else { return fromJsonKnownDiscriminator(readerToUse.reset()); } diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsResponseFormatJson.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsResponseFormatJson.java deleted file mode 100644 index 86db6bdbea4f..000000000000 --- a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsResponseFormatJson.java +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.ai.inference.models; - -import com.azure.core.annotation.Generated; -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; - -/** - * A response format for Chat Completions that restricts responses to emitting valid JSON objects. - * Note that to enable JSON mode, some AI models may also require you to instruct the model to produce JSON - * via a system or user message. - */ -@Immutable -public final class ChatCompletionsResponseFormatJson extends ChatCompletionsResponseFormat { - - /* - * The response format type to use for chat completions. - */ - @Generated - private String type = "json_object"; - - /** - * Creates an instance of ChatCompletionsResponseFormatJson class. - */ - @Generated - public ChatCompletionsResponseFormatJson() { - } - - /** - * Get the type property: The response format type to use for chat completions. - * - * @return the type value. - */ - @Generated - @Override - 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 ChatCompletionsResponseFormatJson from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of ChatCompletionsResponseFormatJson 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 ChatCompletionsResponseFormatJson. - */ - @Generated - public static ChatCompletionsResponseFormatJson fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - ChatCompletionsResponseFormatJson deserializedChatCompletionsResponseFormatJson - = new ChatCompletionsResponseFormatJson(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - if ("type".equals(fieldName)) { - deserializedChatCompletionsResponseFormatJson.type = reader.getString(); - } else { - reader.skipChildren(); - } - } - return deserializedChatCompletionsResponseFormatJson; - }); - } -} diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsResponseFormatJsonObject.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsResponseFormatJsonObject.java new file mode 100644 index 000000000000..bbf7092bfd23 --- /dev/null +++ b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsResponseFormatJsonObject.java @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.inference.models; + +import com.azure.core.annotation.Generated; +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; + +/** + * A response format for Chat Completions that restricts responses to emitting valid JSON objects. + * Note that to enable JSON mode, some AI models may also require you to instruct the model to produce JSON + * via a system or user message. + */ +@Immutable +public final class ChatCompletionsResponseFormatJsonObject extends ChatCompletionsResponseFormat { + + /* + * The response format type to use for chat completions. + */ + @Generated + private String type = "json_object"; + + /** + * Creates an instance of ChatCompletionsResponseFormatJsonObject class. + */ + @Generated + public ChatCompletionsResponseFormatJsonObject() { + } + + /** + * Get the type property: The response format type to use for chat completions. + * + * @return the type value. + */ + @Generated + @Override + 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 ChatCompletionsResponseFormatJsonObject from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatCompletionsResponseFormatJsonObject 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 ChatCompletionsResponseFormatJsonObject. + */ + @Generated + public static ChatCompletionsResponseFormatJsonObject fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ChatCompletionsResponseFormatJsonObject deserializedChatCompletionsResponseFormatJsonObject + = new ChatCompletionsResponseFormatJsonObject(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("type".equals(fieldName)) { + deserializedChatCompletionsResponseFormatJsonObject.type = reader.getString(); + } else { + reader.skipChildren(); + } + } + return deserializedChatCompletionsResponseFormatJsonObject; + }); + } +} diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsResponseFormatJsonSchema.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsResponseFormatJsonSchema.java new file mode 100644 index 000000000000..607d671b6439 --- /dev/null +++ b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsResponseFormatJsonSchema.java @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.inference.models; + +import com.azure.core.annotation.Generated; +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; + +/** + * A response format for Chat Completions that restricts responses to emitting valid JSON objects, with a + * JSON schema specified by the caller. + */ +@Immutable +public final class ChatCompletionsResponseFormatJsonSchema extends ChatCompletionsResponseFormat { + + /* + * The response format type to use for chat completions. + */ + @Generated + private String type = "json_schema"; + + /* + * The definition of the required JSON schema in the response, and associated metadata. + */ + @Generated + private final ChatCompletionsResponseFormatJsonSchemaDefinition jsonSchema; + + /** + * Creates an instance of ChatCompletionsResponseFormatJsonSchema class. + * + * @param jsonSchema the jsonSchema value to set. + */ + @Generated + public ChatCompletionsResponseFormatJsonSchema(ChatCompletionsResponseFormatJsonSchemaDefinition jsonSchema) { + this.jsonSchema = jsonSchema; + } + + /** + * Get the type property: The response format type to use for chat completions. + * + * @return the type value. + */ + @Generated + @Override + public String getType() { + return this.type; + } + + /** + * Get the jsonSchema property: The definition of the required JSON schema in the response, and associated metadata. + * + * @return the jsonSchema value. + */ + @Generated + public ChatCompletionsResponseFormatJsonSchemaDefinition getJsonSchema() { + return this.jsonSchema; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("json_schema", this.jsonSchema); + jsonWriter.writeStringField("type", this.type); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatCompletionsResponseFormatJsonSchema from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatCompletionsResponseFormatJsonSchema 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 ChatCompletionsResponseFormatJsonSchema. + */ + @Generated + public static ChatCompletionsResponseFormatJsonSchema fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ChatCompletionsResponseFormatJsonSchemaDefinition jsonSchema = null; + String type = "json_schema"; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("json_schema".equals(fieldName)) { + jsonSchema = ChatCompletionsResponseFormatJsonSchemaDefinition.fromJson(reader); + } else if ("type".equals(fieldName)) { + type = reader.getString(); + } else { + reader.skipChildren(); + } + } + ChatCompletionsResponseFormatJsonSchema deserializedChatCompletionsResponseFormatJsonSchema + = new ChatCompletionsResponseFormatJsonSchema(jsonSchema); + deserializedChatCompletionsResponseFormatJsonSchema.type = type; + return deserializedChatCompletionsResponseFormatJsonSchema; + }); + } +} diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsResponseFormatJsonSchemaDefinition.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsResponseFormatJsonSchemaDefinition.java new file mode 100644 index 000000000000..a78011ea77be --- /dev/null +++ b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsResponseFormatJsonSchemaDefinition.java @@ -0,0 +1,198 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.inference.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.util.BinaryData; +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.Map; + +/** + * Defines the response format for chat completions as JSON with a given schema. The AI model + * will need to adhere to this schema when generating completions. + */ +@Fluent +public final class ChatCompletionsResponseFormatJsonSchemaDefinition + implements JsonSerializable { + + /* + * A name that labels this JSON schema. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum + * length of 64. + */ + @Generated + private final String name; + + /* + * The definition of the JSON schema. See https://json-schema.org/overview/what-is-jsonschema. + * Note that AI models usually only support a subset of the keywords defined by JSON schema. Consult your AI model + * documentation + * to determine what is supported. + */ + @Generated + private final Map schema; + + /* + * A description of the response format, used by the AI model to determine how to generate responses in this format. + */ + @Generated + private String description; + + /* + * If set to true, the service will error out if the provided JSON schema contains keywords + * not supported by the AI model. An example of such keyword may be `maxLength` for JSON type `string`. + * If false, and the provided JSON schema contains keywords not supported + * by the AI model, the AI model will not error out. Instead it will ignore the unsupported keywords. + */ + @Generated + private Boolean strict; + + /** + * Creates an instance of ChatCompletionsResponseFormatJsonSchemaDefinition class. + * + * @param name the name value to set. + * @param schema the schema value to set. + */ + @Generated + public ChatCompletionsResponseFormatJsonSchemaDefinition(String name, Map schema) { + this.name = name; + this.schema = schema; + } + + /** + * Get the name property: A name that labels this JSON schema. Must be a-z, A-Z, 0-9, or contain underscores and + * dashes, with a maximum length of 64. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the schema property: The definition of the JSON schema. See + * https://json-schema.org/overview/what-is-jsonschema. + * Note that AI models usually only support a subset of the keywords defined by JSON schema. Consult your AI model + * documentation + * to determine what is supported. + * + * @return the schema value. + */ + @Generated + public Map getSchema() { + return this.schema; + } + + /** + * Get the description property: A description of the response format, used by the AI model to determine how to + * generate responses in this format. + * + * @return the description value. + */ + @Generated + public String getDescription() { + return this.description; + } + + /** + * Set the description property: A description of the response format, used by the AI model to determine how to + * generate responses in this format. + * + * @param description the description value to set. + * @return the ChatCompletionsResponseFormatJsonSchemaDefinition object itself. + */ + @Generated + public ChatCompletionsResponseFormatJsonSchemaDefinition setDescription(String description) { + this.description = description; + return this; + } + + /** + * Get the strict property: If set to true, the service will error out if the provided JSON schema contains keywords + * not supported by the AI model. An example of such keyword may be `maxLength` for JSON type `string`. + * If false, and the provided JSON schema contains keywords not supported + * by the AI model, the AI model will not error out. Instead it will ignore the unsupported keywords. + * + * @return the strict value. + */ + @Generated + public Boolean isStrict() { + return this.strict; + } + + /** + * Set the strict property: If set to true, the service will error out if the provided JSON schema contains keywords + * not supported by the AI model. An example of such keyword may be `maxLength` for JSON type `string`. + * If false, and the provided JSON schema contains keywords not supported + * by the AI model, the AI model will not error out. Instead it will ignore the unsupported keywords. + * + * @param strict the strict value to set. + * @return the ChatCompletionsResponseFormatJsonSchemaDefinition object itself. + */ + @Generated + public ChatCompletionsResponseFormatJsonSchemaDefinition setStrict(Boolean strict) { + this.strict = strict; + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeMapField("schema", this.schema, + (writer, element) -> writer.writeUntyped(element == null ? null : element.toObject(Object.class))); + jsonWriter.writeStringField("description", this.description); + jsonWriter.writeBooleanField("strict", this.strict); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatCompletionsResponseFormatJsonSchemaDefinition from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatCompletionsResponseFormatJsonSchemaDefinition 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 ChatCompletionsResponseFormatJsonSchemaDefinition. + */ + @Generated + public static ChatCompletionsResponseFormatJsonSchemaDefinition fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String name = null; + Map schema = null; + String description = null; + Boolean strict = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("name".equals(fieldName)) { + name = reader.getString(); + } else if ("schema".equals(fieldName)) { + schema = reader.readMap(reader1 -> reader1 + .getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); + } else if ("description".equals(fieldName)) { + description = reader.getString(); + } else if ("strict".equals(fieldName)) { + strict = reader.getNullable(JsonReader::getBoolean); + } else { + reader.skipChildren(); + } + } + ChatCompletionsResponseFormatJsonSchemaDefinition deserializedChatCompletionsResponseFormatJsonSchemaDefinition + = new ChatCompletionsResponseFormatJsonSchemaDefinition(name, schema); + deserializedChatCompletionsResponseFormatJsonSchemaDefinition.description = description; + deserializedChatCompletionsResponseFormatJsonSchemaDefinition.strict = strict; + return deserializedChatCompletionsResponseFormatJsonSchemaDefinition; + }); + } +} diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsToolChoicePreset.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsToolChoicePreset.java new file mode 100644 index 000000000000..e21aa21ad081 --- /dev/null +++ b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsToolChoicePreset.java @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.inference.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Represents a generic policy for how a chat completions tool may be selected. + */ +public final class ChatCompletionsToolChoicePreset extends ExpandableStringEnum { + + /** + * Specifies that the model may either use any of the tools provided in this chat completions request or + * instead return a standard chat completions response as if no tools were provided. + */ + @Generated + public static final ChatCompletionsToolChoicePreset AUTO = fromString("auto"); + + /** + * Specifies that the model should not respond with a tool call and should instead provide a standard chat + * completions response. Response content may still be influenced by the provided tool definitions. + */ + @Generated + public static final ChatCompletionsToolChoicePreset NONE = fromString("none"); + + /** + * Specifies that the model should respond with a call to one or more tools. + */ + @Generated + public static final ChatCompletionsToolChoicePreset REQUIRED = fromString("required"); + + /** + * Creates a new instance of ChatCompletionsToolChoicePreset value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public ChatCompletionsToolChoicePreset() { + } + + /** + * Creates or finds a ChatCompletionsToolChoicePreset from its string representation. + * + * @param name a name to look for. + * @return the corresponding ChatCompletionsToolChoicePreset. + */ + @Generated + public static ChatCompletionsToolChoicePreset fromString(String name) { + return fromString(name, ChatCompletionsToolChoicePreset.class); + } + + /** + * Gets known ChatCompletionsToolChoicePreset values. + * + * @return known ChatCompletionsToolChoicePreset values. + */ + @Generated + public static Collection values() { + return values(ChatCompletionsToolChoicePreset.class); + } +} diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsToolSelectionPreset.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsToolSelectionPreset.java deleted file mode 100644 index c67d318b47e1..000000000000 --- a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatCompletionsToolSelectionPreset.java +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.ai.inference.models; - -import com.azure.core.annotation.Generated; -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * Represents a generic policy for how a chat completions tool may be selected. - */ -public final class ChatCompletionsToolSelectionPreset extends ExpandableStringEnum { - - /** - * Specifies that the model may either use any of the tools provided in this chat completions request or - * instead return a standard chat completions response as if no tools were provided. - */ - @Generated - public static final ChatCompletionsToolSelectionPreset AUTO = fromString("auto"); - - /** - * Specifies that the model should not respond with a tool call and should instead provide a standard chat - * completions response. Response content may still be influenced by the provided tool definitions. - */ - @Generated - public static final ChatCompletionsToolSelectionPreset NONE = fromString("none"); - - /** - * Specifies that the model should respond with a call to one or more tools. - */ - @Generated - public static final ChatCompletionsToolSelectionPreset REQUIRED = fromString("required"); - - /** - * Creates a new instance of ChatCompletionsToolSelectionPreset value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Generated - @Deprecated - public ChatCompletionsToolSelectionPreset() { - } - - /** - * Creates or finds a ChatCompletionsToolSelectionPreset from its string representation. - * - * @param name a name to look for. - * @return the corresponding ChatCompletionsToolSelectionPreset. - */ - @Generated - public static ChatCompletionsToolSelectionPreset fromString(String name) { - return fromString(name, ChatCompletionsToolSelectionPreset.class); - } - - /** - * Gets known ChatCompletionsToolSelectionPreset values. - * - * @return known ChatCompletionsToolSelectionPreset values. - */ - @Generated - public static Collection values() { - return values(ChatCompletionsToolSelectionPreset.class); - } -} diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatRequestDeveloperMessage.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatRequestDeveloperMessage.java new file mode 100644 index 000000000000..971003bcb062 --- /dev/null +++ b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatRequestDeveloperMessage.java @@ -0,0 +1,107 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.inference.models; + +import com.azure.core.annotation.Generated; +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; + +/** + * A request chat message containing developer instructions that influence how the model will generate a chat + * completions + * response. Some AI models support a developer message instead of a system message. + */ +@Immutable +public final class ChatRequestDeveloperMessage extends ChatRequestMessage { + + /* + * The chat role associated with this message. + */ + @Generated + private ChatRole role = ChatRole.DEVELOPER; + + /* + * The contents of the developer message. + */ + @Generated + private final String content; + + /** + * Creates an instance of ChatRequestDeveloperMessage class. + * + * @param content the content value to set. + */ + @Generated + public ChatRequestDeveloperMessage(String content) { + this.content = content; + } + + /** + * Get the role property: The chat role associated with this message. + * + * @return the role value. + */ + @Generated + @Override + public ChatRole getRole() { + return this.role; + } + + /** + * Get the content property: The contents of the developer message. + * + * @return the content value. + */ + @Generated + public String getContent() { + return this.content; + } + + /** + * {@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()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatRequestDeveloperMessage from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatRequestDeveloperMessage 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 ChatRequestDeveloperMessage. + */ + @Generated + public static ChatRequestDeveloperMessage fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String content = null; + ChatRole role = ChatRole.DEVELOPER; + 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 { + reader.skipChildren(); + } + } + ChatRequestDeveloperMessage deserializedChatRequestDeveloperMessage + = new ChatRequestDeveloperMessage(content); + deserializedChatRequestDeveloperMessage.role = role; + return deserializedChatRequestDeveloperMessage; + }); + } +} diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatRequestMessage.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatRequestMessage.java index e6a9e1868b74..6c53e10404b5 100644 --- a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatRequestMessage.java +++ b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatRequestMessage.java @@ -79,6 +79,8 @@ public static ChatRequestMessage fromJson(JsonReader jsonReader) throws IOExcept // Use the discriminator value to determine which subtype should be deserialized. if ("system".equals(discriminatorValue)) { return ChatRequestSystemMessage.fromJson(readerToUse.reset()); + } else if ("developer".equals(discriminatorValue)) { + return ChatRequestDeveloperMessage.fromJson(readerToUse.reset()); } else if ("user".equals(discriminatorValue)) { return ChatRequestUserMessage.fromJson(readerToUse.reset()); } else if ("assistant".equals(discriminatorValue)) { diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatRequestToolMessage.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatRequestToolMessage.java index 16dca9ee729d..2f22977d8f1b 100644 --- a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatRequestToolMessage.java +++ b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatRequestToolMessage.java @@ -3,8 +3,8 @@ // Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.ai.inference.models; +import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; -import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; @@ -13,7 +13,7 @@ /** * A request chat message representing requested output from a configured tool. */ -@Immutable +@Fluent public final class ChatRequestToolMessage extends ChatRequestMessage { /* @@ -26,7 +26,7 @@ public final class ChatRequestToolMessage extends ChatRequestMessage { * The content of the message. */ @Generated - private final String content; + private String content; /* * The ID of the tool call resolved by the provided content. @@ -34,18 +34,6 @@ public final class ChatRequestToolMessage extends ChatRequestMessage { @Generated private final String toolCallId; - /** - * Creates an instance of ChatRequestToolMessage class. - * - * @param content the content value to set. - * @param toolCallId the toolCallId value to set. - */ - @Generated - public ChatRequestToolMessage(String content, String toolCallId) { - this.content = content; - this.toolCallId = toolCallId; - } - /** * Get the role property: The chat role associated with this message. * @@ -84,9 +72,9 @@ public String getToolCallId() { @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()); + jsonWriter.writeStringField("content", this.content); return jsonWriter.writeEndObject(); } @@ -99,28 +87,50 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @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; + String content = null; 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)) { + if ("tool_call_id".equals(fieldName)) { toolCallId = reader.getString(); } else if ("role".equals(fieldName)) { role = ChatRole.fromString(reader.getString()); + } else if ("content".equals(fieldName)) { + content = reader.getString(); } else { reader.skipChildren(); } } - ChatRequestToolMessage deserializedChatRequestToolMessage = new ChatRequestToolMessage(content, toolCallId); + ChatRequestToolMessage deserializedChatRequestToolMessage + = new ChatRequestToolMessage(toolCallId).setContent(content); deserializedChatRequestToolMessage.role = role; return deserializedChatRequestToolMessage; }); } + + /** + * Creates an instance of ChatRequestToolMessage class. + * + * @param toolCallId the toolCallId value to set. + */ + @Generated + public ChatRequestToolMessage(String toolCallId) { + this.toolCallId = toolCallId; + } + + /** + * Set the content property: The content of the message. + * + * @param content the content value to set. + * @return the ChatRequestToolMessage object itself. + */ + @Generated + public ChatRequestToolMessage setContent(String content) { + this.content = content; + return this; + } } diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatRole.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatRole.java index 10faab5bd750..2e8a1f4373db 100644 --- a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatRole.java +++ b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ChatRole.java @@ -66,4 +66,11 @@ public static ChatRole fromString(String name) { public static Collection values() { return values(ChatRole.class); } + + /** + * The role that instructs or sets the behavior of the assistant. Some AI models support this role instead of the + * 'system' role. + */ + @Generated + public static final ChatRole DEVELOPER = fromString("developer"); } diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/EmbeddingInputType.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/EmbeddingInputType.java index 2fbe119da216..c3c33976e136 100644 --- a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/EmbeddingInputType.java +++ b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/EmbeddingInputType.java @@ -13,19 +13,19 @@ public final class EmbeddingInputType extends ExpandableStringEnum { /** - * to do. + * Indicates the input is a general text input. */ @Generated public static final EmbeddingInputType TEXT = fromString("text"); /** - * to do. + * Indicates the input represents a search query to find the most relevant documents in your vector database. */ @Generated public static final EmbeddingInputType QUERY = fromString("query"); /** - * to do. + * Indicates the input represents a document that is stored in a vector database. */ @Generated public static final EmbeddingInputType DOCUMENT = fromString("document"); diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/EmbeddingsResult.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/EmbeddingsResult.java index 486fb8b128ab..c35121aa75a9 100644 --- a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/EmbeddingsResult.java +++ b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/EmbeddingsResult.java @@ -38,20 +38,6 @@ public final class EmbeddingsResult implements JsonSerializable data, EmbeddingsUsage usage, String model) { - this.data = data; - this.usage = usage; - this.model = model; - } - /** * Get the data property: Embedding values for the prompts submitted in the request. * @@ -89,6 +75,7 @@ public String getModel() { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("id", this.id); jsonWriter.writeArrayField("data", this.data, (writer, element) -> writer.writeJson(element)); jsonWriter.writeJsonField("usage", this.usage); jsonWriter.writeStringField("model", this.model); @@ -107,13 +94,16 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static EmbeddingsResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { + String id = null; List data = null; EmbeddingsUsage usage = null; String model = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("data".equals(fieldName)) { + if ("id".equals(fieldName)) { + id = reader.getString(); + } else if ("data".equals(fieldName)) { data = reader.readArray(reader1 -> EmbeddingItem.fromJson(reader1)); } else if ("usage".equals(fieldName)) { usage = EmbeddingsUsage.fromJson(reader); @@ -123,7 +113,39 @@ public static EmbeddingsResult fromJson(JsonReader jsonReader) throws IOExceptio reader.skipChildren(); } } - return new EmbeddingsResult(data, usage, model); + return new EmbeddingsResult(id, data, usage, model); }); } + + /* + * Unique identifier for the embeddings result. + */ + @Generated + private final String id; + + /** + * Creates an instance of EmbeddingsResult class. + * + * @param id the id value to set. + * @param data the data value to set. + * @param usage the usage value to set. + * @param model the model value to set. + */ + @Generated + private EmbeddingsResult(String id, List data, EmbeddingsUsage usage, String model) { + this.id = id; + this.data = data; + this.usage = usage; + this.model = model; + } + + /** + * Get the id property: Unique identifier for the embeddings result. + * + * @return the id value. + */ + @Generated + public String getId() { + return this.id; + } } diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ImageEmbeddingInput.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ImageEmbeddingInput.java new file mode 100644 index 000000000000..269cce4595a2 --- /dev/null +++ b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ImageEmbeddingInput.java @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.inference.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Base64; + +/** + * Represents an image with optional text. + */ +@Fluent +public final class ImageEmbeddingInput implements JsonSerializable { + + /* + * The input image encoded in base64 string as a data URL. Example: `data:image/{format};base64,{data}`. + */ + @Generated + private final String image; + + /* + * Optional. The text input to feed into the model (like DINO, CLIP). + * Returns a 422 error if the model doesn't support the value or parameter. + */ + @Generated + private String text; + + /** + * Creates an instance of ImageEmbeddingInput class. + * + * @param filePath path to the imageFile. + * @param imageFormatType format of the image + * @throws RuntimeException If an error occurs while reading the file or file not found. + */ + public ImageEmbeddingInput(Path filePath, String imageFormatType) { + try { + byte[] bytes = Files.readAllBytes(filePath); + String encodedFile = new String(Base64.getEncoder().encode(bytes), StandardCharsets.UTF_8); + String urlTemplate = "data:image/%s;base64,%s"; + this.image = String.format(urlTemplate, imageFormatType, encodedFile); + } catch (FileNotFoundException e) { + throw new RuntimeException("Local file not found.", e); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + /** + * Creates an instance of ImageEmbeddingInput class. + * + * @param image the image value to set. + */ + @Generated + public ImageEmbeddingInput(String image) { + this.image = image; + } + + /** + * Get the image property: The input image encoded in base64 string as a data URL. Example: + * `data:image/{format};base64,{data}`. + * + * @return the image value. + */ + @Generated + public String getImage() { + return this.image; + } + + /** + * Get the text property: Optional. The text input to feed into the model (like DINO, CLIP). + * Returns a 422 error if the model doesn't support the value or parameter. + * + * @return the text value. + */ + @Generated + public String getText() { + return this.text; + } + + /** + * Set the text property: Optional. The text input to feed into the model (like DINO, CLIP). + * Returns a 422 error if the model doesn't support the value or parameter. + * + * @param text the text value to set. + * @return the ImageEmbeddingInput object itself. + */ + @Generated + public ImageEmbeddingInput setText(String text) { + this.text = text; + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("image", this.image); + jsonWriter.writeStringField("text", this.text); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ImageEmbeddingInput from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ImageEmbeddingInput 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 ImageEmbeddingInput. + */ + @Generated + public static ImageEmbeddingInput fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String image = null; + String text = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("image".equals(fieldName)) { + image = reader.getString(); + } else if ("text".equals(fieldName)) { + text = reader.getString(); + } else { + reader.skipChildren(); + } + } + ImageEmbeddingInput deserializedImageEmbeddingInput = new ImageEmbeddingInput(image); + deserializedImageEmbeddingInput.text = text; + return deserializedImageEmbeddingInput; + }); + } +} diff --git a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ModelType.java b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ModelType.java index be9e52d19d3a..21950a99b797 100644 --- a/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ModelType.java +++ b/sdk/ai/azure-ai-inference/src/main/java/com/azure/ai/inference/models/ModelType.java @@ -13,41 +13,35 @@ public final class ModelType extends ExpandableStringEnum { /** - * Embeddings. + * A model capable of generating embeddings from a text. */ @Generated public static final ModelType EMBEDDINGS = fromString("embeddings"); /** - * Image generation. + * A model capable of generating images from an image and text description. */ @Generated public static final ModelType IMAGE_GENERATION = fromString("image_generation"); /** - * Text generation. + * A text generation model. */ @Generated public static final ModelType TEXT_GENERATION = fromString("text_generation"); /** - * Image embeddings. + * A model capable of generating embeddings from an image. */ @Generated public static final ModelType IMAGE_EMBEDDINGS = fromString("image_embeddings"); /** - * Audio generation. + * A text-to-audio generative model. */ @Generated public static final ModelType AUDIO_GENERATION = fromString("audio_generation"); - /** - * Chat completions. - */ - @Generated - public static final ModelType CHAT = fromString("chat"); - /** * Creates a new instance of ModelType value. * @@ -78,4 +72,10 @@ public static ModelType fromString(String name) { public static Collection values() { return values(ModelType.class); } + + /** + * A model capable of taking chat-formatted messages and generate responses. + */ + @Generated + public static final ModelType CHAT_COMPLETION = fromString("chat_completion"); } diff --git a/sdk/ai/azure-ai-inference/src/main/resources/META-INF/azure-ai-inference_apiview_properties.json b/sdk/ai/azure-ai-inference/src/main/resources/META-INF/azure-ai-inference_apiview_properties.json index 01ba4716738e..a471885c492c 100644 --- a/sdk/ai/azure-ai-inference/src/main/resources/META-INF/azure-ai-inference_apiview_properties.json +++ b/sdk/ai/azure-ai-inference/src/main/resources/META-INF/azure-ai-inference_apiview_properties.json @@ -34,26 +34,28 @@ "com.azure.ai.inference.ImageEmbeddingsClient.getModelInfo": "Customizations.Client3.getModelInfo", "com.azure.ai.inference.ImageEmbeddingsClient.getModelInfoWithResponse": "Customizations.Client3.getModelInfo", "com.azure.ai.inference.ImageEmbeddingsClientBuilder": "Customizations.Client3", - "com.azure.ai.inference.implementation.models.CompleteOptions": "null", - "com.azure.ai.inference.implementation.models.CompleteRequest": "Customizations.complete.Request.anonymous", "com.azure.ai.inference.implementation.models.EmbedRequest": "Customizations.embed.Request.anonymous", "com.azure.ai.inference.implementation.models.EmbedRequest1": "Customizations.embed.Request.anonymous", "com.azure.ai.inference.models.ChatChoice": "AI.Model.ChatChoice", "com.azure.ai.inference.models.ChatCompletions": "AI.Model.ChatCompletions", - "com.azure.ai.inference.models.ChatCompletionsFunctionToolSelection": "AI.Model.ChatCompletionsFunctionToolSelection", - "com.azure.ai.inference.models.ChatCompletionsNamedToolSelection": "AI.Model.ChatCompletionsNamedToolSelection", + "com.azure.ai.inference.models.ChatCompletionsNamedToolChoice": "AI.Model.ChatCompletionsNamedToolChoice", + "com.azure.ai.inference.models.ChatCompletionsNamedToolChoiceFunction": "AI.Model.ChatCompletionsNamedToolChoiceFunction", + "com.azure.ai.inference.models.ChatCompletionsOptions": "AI.Model.ChatCompletionsOptions", "com.azure.ai.inference.models.ChatCompletionsResponseFormat": "AI.Model.ChatCompletionsResponseFormat", - "com.azure.ai.inference.models.ChatCompletionsResponseFormatJson": "AI.Model.ChatCompletionsResponseFormatJSON", + "com.azure.ai.inference.models.ChatCompletionsResponseFormatJsonObject": "AI.Model.ChatCompletionsResponseFormatJsonObject", + "com.azure.ai.inference.models.ChatCompletionsResponseFormatJsonSchema": "AI.Model.ChatCompletionsResponseFormatJsonSchema", + "com.azure.ai.inference.models.ChatCompletionsResponseFormatJsonSchemaDefinition": "AI.Model.ChatCompletionsResponseFormatJsonSchemaDefinition", "com.azure.ai.inference.models.ChatCompletionsResponseFormatText": "AI.Model.ChatCompletionsResponseFormatText", "com.azure.ai.inference.models.ChatCompletionsToolCall": "AI.Model.ChatCompletionsToolCall", + "com.azure.ai.inference.models.ChatCompletionsToolChoicePreset": "AI.Model.ChatCompletionsToolChoicePreset", "com.azure.ai.inference.models.ChatCompletionsToolDefinition": "AI.Model.ChatCompletionsToolDefinition", - "com.azure.ai.inference.models.ChatCompletionsToolSelectionPreset": "AI.Model.ChatCompletionsToolSelectionPreset", "com.azure.ai.inference.models.ChatMessageContentItem": "AI.Model.ChatMessageContentItem", "com.azure.ai.inference.models.ChatMessageImageContentItem": "AI.Model.ChatMessageImageContentItem", "com.azure.ai.inference.models.ChatMessageImageDetailLevel": "AI.Model.ChatMessageImageDetailLevel", "com.azure.ai.inference.models.ChatMessageImageUrl": "AI.Model.ChatMessageImageUrl", "com.azure.ai.inference.models.ChatMessageTextContentItem": "AI.Model.ChatMessageTextContentItem", "com.azure.ai.inference.models.ChatRequestAssistantMessage": "AI.Model.ChatRequestAssistantMessage", + "com.azure.ai.inference.models.ChatRequestDeveloperMessage": "AI.Model.ChatRequestDeveloperMessage", "com.azure.ai.inference.models.ChatRequestMessage": "AI.Model.ChatRequestMessage", "com.azure.ai.inference.models.ChatRequestSystemMessage": "AI.Model.ChatRequestSystemMessage", "com.azure.ai.inference.models.ChatRequestToolMessage": "AI.Model.ChatRequestToolMessage", @@ -63,7 +65,6 @@ "com.azure.ai.inference.models.CompletionsFinishReason": "AI.Model.CompletionsFinishReason", "com.azure.ai.inference.models.CompletionsUsage": "AI.Model.CompletionsUsage", "com.azure.ai.inference.models.EmbeddingEncodingFormat": "AI.Model.EmbeddingEncodingFormat", - "com.azure.ai.inference.models.EmbeddingInput": "AI.Model.EmbeddingInput", "com.azure.ai.inference.models.EmbeddingInputType": "AI.Model.EmbeddingInputType", "com.azure.ai.inference.models.EmbeddingItem": "AI.Model.EmbeddingItem", "com.azure.ai.inference.models.EmbeddingsResult": "AI.Model.EmbeddingsResult", @@ -71,11 +72,8 @@ "com.azure.ai.inference.models.ExtraParameters": "AI.Model.ExtraParameters", "com.azure.ai.inference.models.FunctionCall": "AI.Model.FunctionCall", "com.azure.ai.inference.models.FunctionDefinition": "AI.Model.FunctionDefinition", + "com.azure.ai.inference.models.ImageEmbeddingInput": "AI.Model.ImageEmbeddingInput", "com.azure.ai.inference.models.ModelInfo": "AI.Model.ModelInfo", - "com.azure.ai.inference.models.ModelType": "AI.Model.ModelType", - "com.azure.ai.inference.models.StreamingChatChoiceUpdate": "AI.Model.StreamingChatChoiceUpdate", - "com.azure.ai.inference.models.StreamingChatCompletionsUpdate": "AI.Model.StreamingChatCompletionsUpdate", - "com.azure.ai.inference.models.StreamingChatResponseMessageUpdate": "AI.Model.StreamingChatResponseMessageUpdate", - "com.azure.ai.inference.models.StreamingChatResponseToolCallUpdate": "AI.Model.StreamingChatResponseToolCallUpdate" + "com.azure.ai.inference.models.ModelType": "AI.Model.ModelType" } } diff --git a/sdk/ai/azure-ai-inference/src/samples/java/com/azure/ai/inference/usage/ChatCompletionsToolCallSample.java b/sdk/ai/azure-ai-inference/src/samples/java/com/azure/ai/inference/usage/ChatCompletionsToolCallSample.java index 90c9d515dbc0..982e980671b2 100644 --- a/sdk/ai/azure-ai-inference/src/samples/java/com/azure/ai/inference/usage/ChatCompletionsToolCallSample.java +++ b/sdk/ai/azure-ai-inference/src/samples/java/com/azure/ai/inference/usage/ChatCompletionsToolCallSample.java @@ -98,7 +98,7 @@ private static List handleFunctionCallResponse(List inputList = new ArrayList<>(); + Path testFilePath = Paths.get(TEST_IMAGE_PATH); + inputList.add(new ImageEmbeddingInput(testFilePath, TEST_IMAGE_FORMAT)); + + client.embed(inputList).subscribe( + embeddings -> { + for (EmbeddingItem item : embeddings.getData()) { + System.out.printf("Index: %d.%n", item.getIndex()); + System.out.println("Embedding as list of floats: "); + for (Float embedding : item.getEmbeddingList()) { + System.out.printf("%f;", embedding); + } + } + EmbeddingsUsage usage = embeddings.getUsage(); + System.out.println(""); + System.out.printf( + "Usage: number of prompt token is %d and number of total tokens in request and response is %d.%n", + usage.getPromptTokens(), usage.getTotalTokens()); + }, + error -> System.err.println("There was an error getting embeddings." + error), + () -> System.out.println("Completed called getEmbeddings.")); + + // The .subscribe() creation and assignment is not a blocking call. For the purpose of this example, we sleep + // the thread so the program does not end before the send operation is complete. Using .block() instead of + // .subscribe() will turn this into a synchronous call. + TimeUnit.SECONDS.sleep(10); + + } +} diff --git a/sdk/ai/azure-ai-inference/src/samples/java/com/azure/ai/inference/usage/ImageEmbeddingsSample.java b/sdk/ai/azure-ai-inference/src/samples/java/com/azure/ai/inference/usage/ImageEmbeddingsSample.java new file mode 100644 index 000000000000..06d6fe0fea6c --- /dev/null +++ b/sdk/ai/azure-ai-inference/src/samples/java/com/azure/ai/inference/usage/ImageEmbeddingsSample.java @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.ai.inference.usage; + +import com.azure.ai.inference.ImageEmbeddingsClient; +import com.azure.ai.inference.ImageEmbeddingsClientBuilder; +import com.azure.ai.inference.models.EmbeddingsResult; +import com.azure.ai.inference.models.ImageEmbeddingInput; +import com.azure.ai.inference.models.EmbeddingItem; +import com.azure.core.credential.AzureKeyCredential; +import com.azure.core.util.Configuration; + +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; + +public final class ImageEmbeddingsSample { + private static final String TEST_IMAGE_PATH = "./src/samples/resources/sample-images/sample.png"; + private static final String TEST_IMAGE_FORMAT = "png"; + /** + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + String key = Configuration.getGlobalConfiguration().get("AZURE_IMAGE_EMBEDDINGS_KEY"); + String endpoint = Configuration.getGlobalConfiguration().get("IMAGE_EMBEDDINGS_MODEL_ENDPOINT"); + ImageEmbeddingsClient client = new ImageEmbeddingsClientBuilder() + .credential(new AzureKeyCredential(key)) + .endpoint(endpoint) + .buildClient(); + + List inputList = new ArrayList<>(); + Path testFilePath = Paths.get(TEST_IMAGE_PATH); + inputList.add(new ImageEmbeddingInput(testFilePath, TEST_IMAGE_FORMAT)); + + EmbeddingsResult embeddings = client.embed(inputList); + + for (EmbeddingItem item : embeddings.getData()) { + System.out.printf("Index: %d.%n", item.getIndex()); + for (Float embedding : item.getEmbeddingList()) { + System.out.printf("%f;", embedding); + } + } + } +} diff --git a/sdk/ai/azure-ai-inference/src/samples/java/com/azure/ai/inference/usage/StreamingToolCallSample.java b/sdk/ai/azure-ai-inference/src/samples/java/com/azure/ai/inference/usage/StreamingToolCallSample.java index fe3384ee028a..a88280e8e82a 100644 --- a/sdk/ai/azure-ai-inference/src/samples/java/com/azure/ai/inference/usage/StreamingToolCallSample.java +++ b/sdk/ai/azure-ai-inference/src/samples/java/com/azure/ai/inference/usage/StreamingToolCallSample.java @@ -122,7 +122,7 @@ public static void main(String[] args) { String functionCallResult = futureTemperature(parameters.locationName, parameters.date); // This message contains the information that will allow the LLM to resume the text generation - ChatRequestToolMessage toolRequestMessage = new ChatRequestToolMessage(functionCallResult, toolCallId); + ChatRequestToolMessage toolRequestMessage = new ChatRequestToolMessage(toolCallId).setContent(functionCallResult); List followUpMessages = Arrays.asList( // We add the original messages from the request chatMessages.get(0), diff --git a/sdk/ai/azure-ai-inference/src/samples/java/com/azure/ai/inference/usage/StructuredJsonChatSample.java b/sdk/ai/azure-ai-inference/src/samples/java/com/azure/ai/inference/usage/StructuredJsonChatSample.java new file mode 100644 index 000000000000..14a76117d32d --- /dev/null +++ b/sdk/ai/azure-ai-inference/src/samples/java/com/azure/ai/inference/usage/StructuredJsonChatSample.java @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.ai.inference.usage; + +import com.azure.ai.inference.ChatCompletionsClient; +import com.azure.ai.inference.ChatCompletionsClientBuilder; +import com.azure.ai.inference.ModelServiceVersion; +import com.azure.ai.inference.models.ChatCompletions; +import com.azure.ai.inference.models.ChatCompletionsOptions; +import com.azure.ai.inference.models.ChatRequestMessage; +import com.azure.ai.inference.models.ChatRequestSystemMessage; +import com.azure.ai.inference.models.ChatRequestUserMessage; +import com.azure.core.credential.AzureKeyCredential; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Configuration; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.HashMap; + +public final class StructuredJsonChatSample { + /** + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + String jsonSchema = "{ \"ingredients\": {" + + "\"type\": \"array\"," + + "\"items\": { \"type\": \"string\" } }," + + "\"steps\": { \"type\": \"array\", \"items\": {" + + "\"type\": \"object\", \"properties\": {" + + "\"ingredients\": {" + + "\"type\": \"array\"," + + "\"items\": {" + + "\"type\": \"string\"" + + "}" + + "}," + + "\"directions\": {" + + "\"type\": \"string\"" + + "}" + + "}" + + "}" + + "}," + + "\"prep_time\": {" + + "\"type\": \"string\"" + + "}," + + "\"bake_time\": {" + + "\"type\": \"string\"" + + "} }"; + + Map recipeSchema = new HashMap() {{ + put("type", BinaryData.fromString("\"object\"")); + put("properties", BinaryData.fromString(jsonSchema)); + put("required", BinaryData.fromString("[\"ingredients\", \"steps\", \"bake_time\"]")); + put("additionalProperties", BinaryData.fromString("false")); + }}; + + String key = Configuration.getGlobalConfiguration().get("AZURE_API_KEY"); + String endpoint = Configuration.getGlobalConfiguration().get("MODEL_ENDPOINT"); + + ChatCompletionsClient client = new ChatCompletionsClientBuilder() + .credential(new AzureKeyCredential(key)) + .endpoint(endpoint) + .serviceVersion(ModelServiceVersion.V2024_08_01_PREVIEW) + .buildClient(); + + List chatMessages = new ArrayList<>(); + chatMessages.add(new ChatRequestSystemMessage("You are a helpful assistant.")); + chatMessages.add(new ChatRequestUserMessage("Please give me directions and ingredients to bake a chocolate cake.")); + + ChatCompletionsOptions chatCompletionsOptions = new ChatCompletionsOptions(chatMessages).setJsonFormat("cakeBakingDirections", recipeSchema); + + ChatCompletions completions = client.complete(chatCompletionsOptions); + + System.out.printf("%s.%n", completions.getChoice().getMessage().getContent()); + } +} diff --git a/sdk/ai/azure-ai-inference/src/samples/java/com/azure/ai/inference/usage/TraceChatCompletionsToolCallSample.java b/sdk/ai/azure-ai-inference/src/samples/java/com/azure/ai/inference/usage/TraceChatCompletionsToolCallSample.java index cace3c7c8a72..d4dd98ec5767 100644 --- a/sdk/ai/azure-ai-inference/src/samples/java/com/azure/ai/inference/usage/TraceChatCompletionsToolCallSample.java +++ b/sdk/ai/azure-ai-inference/src/samples/java/com/azure/ai/inference/usage/TraceChatCompletionsToolCallSample.java @@ -191,7 +191,7 @@ private Optional tryInvoke(ChatCompletionsToolCall toolC } else { functionResponse = "Unavailable"; } - return Optional.of(new ChatRequestToolMessage(functionResponse, toolCall.getId())); + return Optional.of(new ChatRequestToolMessage(toolCall.getId()).setContent(functionResponse)); } return Optional.empty(); } @@ -248,7 +248,7 @@ private Optional tryInvoke(ChatCompletionsToolCall toolC } else { functionResponse = "Unavailable"; } - return Optional.of(new ChatRequestToolMessage(functionResponse, toolCall.getId())); + return Optional.of(new ChatRequestToolMessage(toolCall.getId()).setContent(functionResponse)); } return Optional.empty(); } diff --git a/sdk/ai/azure-ai-inference/src/samples/java/com/azure/ai/inference/usage/TraceStreamingChatCompletionsToolCallSample.java b/sdk/ai/azure-ai-inference/src/samples/java/com/azure/ai/inference/usage/TraceStreamingChatCompletionsToolCallSample.java index 367e696a463e..ac5df2320668 100644 --- a/sdk/ai/azure-ai-inference/src/samples/java/com/azure/ai/inference/usage/TraceStreamingChatCompletionsToolCallSample.java +++ b/sdk/ai/azure-ai-inference/src/samples/java/com/azure/ai/inference/usage/TraceStreamingChatCompletionsToolCallSample.java @@ -226,7 +226,7 @@ private Optional tryInvoke(ChatCompletionsToolCall toolC } else { functionResponse = "{\"error\": \"No flights found between the cities\"}"; } - return Optional.of(new ChatRequestToolMessage(functionResponse, toolCallId)); + return Optional.of(new ChatRequestToolMessage(toolCallId).setContent(functionResponse)); } return Optional.empty(); } diff --git a/sdk/ai/azure-ai-inference/src/test/java/com/azure/ai/inference/ChatCompletionsSyncClientTest.java b/sdk/ai/azure-ai-inference/src/test/java/com/azure/ai/inference/ChatCompletionsSyncClientTest.java index 3ce620fbe67d..88ed5f128435 100644 --- a/sdk/ai/azure-ai-inference/src/test/java/com/azure/ai/inference/ChatCompletionsSyncClientTest.java +++ b/sdk/ai/azure-ai-inference/src/test/java/com/azure/ai/inference/ChatCompletionsSyncClientTest.java @@ -32,10 +32,7 @@ import com.azure.core.util.ConfigurationBuilder; import com.azure.core.util.IterableStream; import com.azure.core.util.logging.ClientLogger; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; +import com.azure.json.*; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.context.Context; import io.opentelemetry.sdk.OpenTelemetrySdk; @@ -51,7 +48,9 @@ import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.stream.Collectors; @@ -61,6 +60,8 @@ import static com.azure.ai.inference.ChatCompletionClientTracerTest.assertNoChatEventsCaptured; import static com.azure.ai.inference.ChatCompletionClientTracerTest.getChatSpan; import static com.azure.ai.inference.TestUtils.DISPLAY_NAME_WITH_ARGUMENTS; +import static com.azure.ai.inference.TestUtils.TEST_IMAGE_PATH; +import static com.azure.ai.inference.TestUtils.TEST_IMAGE_FORMAT; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertSame; @@ -72,8 +73,6 @@ public class ChatCompletionsSyncClientTest extends ChatCompletionsClientTestBase private static final String FUNCTION_RETURN = "-7"; private static final String TEST_URL = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"; - private static final String TEST_IMAGE_PATH = "./src/samples/resources/sample-images/sample.png"; - private static final String TEST_IMAGE_FORMAT = "png"; private ChatCompletionsClientBuilder getBuilder(HttpClient httpClient) { return getChatCompletionsClientBuilder( @@ -84,6 +83,10 @@ private ChatCompletionsClient getChatCompletionsClient(HttpClient httpClient) { return getBuilder(httpClient).buildClient(); } + private ChatCompletionsClient getChatCompletionsClientForStructuredJSON(HttpClient httpClient) { + return getBuilder(httpClient).serviceVersion(ModelServiceVersion.V2024_08_01_PREVIEW).buildClient(); + } + private ChatCompletionsClient getChatCompletionsClientWithTracing(HttpClient httpClient, SpanProcessor spanProcessor, boolean captureContent) { final OpenTelemetryTracingOptions tracingOptions @@ -210,6 +213,38 @@ public void testGetCompletionsWithImageUrl(HttpClient httpClient) { assertCompletions(1, completions); } + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.inference.TestUtils#getTestParameters") + public void testGetCompletionsWithStructuredJSON(HttpClient httpClient) { + String jsonSchema = "{ \"ingredients\": {" + "\"type\": \"array\"," + "\"items\": { \"type\": \"string\" } }," + + "\"steps\": { \"type\": \"array\", \"items\": {" + "\"type\": \"object\", \"properties\": {" + + "\"ingredients\": {" + "\"type\": \"array\"," + "\"items\": {" + "\"type\": \"string\"" + "}" + "}," + + "\"directions\": {" + "\"type\": \"string\"" + "}" + "}" + "}" + "}," + "\"prep_time\": {" + + "\"type\": \"string\"" + "}," + "\"bake_time\": {" + "\"type\": \"string\"" + "} }"; + + Map recipeSchema = new HashMap() { + { + put("type", BinaryData.fromString("\"object\"")); + put("properties", BinaryData.fromString(jsonSchema)); + put("required", BinaryData.fromString("[\"ingredients\", \"steps\", \"bake_time\"]")); + put("additionalProperties", BinaryData.fromString("false")); + } + }; + client = getChatCompletionsClientForStructuredJSON(httpClient); + + List chatMessages = new ArrayList<>(); + chatMessages.add(new ChatRequestSystemMessage("You are a helpful assistant.")); + chatMessages + .add(new ChatRequestUserMessage("Please give me directions and ingredients to bake a chocolate cake.")); + + ChatCompletionsOptions chatCompletionsOptions + = new ChatCompletionsOptions(chatMessages).setJsonFormat("cakeBakingDirections", recipeSchema); + + ChatCompletions completions = client.complete(chatCompletionsOptions); + + assertCompletions(1, completions); + } + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.inference.TestUtils#getTestParameters") public void testGetCompletionsStreamWithFunctionCalls(HttpClient httpClient) { @@ -288,7 +323,8 @@ public void testGetCompletionsStreamWithFunctionCalls(HttpClient httpClient) { String functionCallResult = futureTemperature(parameters.locationName, parameters.date); // This message contains the information that will allow the LLM to resume the text generation - ChatRequestToolMessage toolRequestMessage = new ChatRequestToolMessage(functionCallResult, toolCallId); + ChatRequestToolMessage toolRequestMessage + = new ChatRequestToolMessage(toolCallId).setContent(functionCallResult); List followUpMessages = Arrays.asList( // We add the original messages from the request chatMessages.get(0), chatMessages.get(1), assistantRequestMessage, toolRequestMessage); diff --git a/sdk/ai/azure-ai-inference/src/test/java/com/azure/ai/inference/EmbeddingsClientTestBase.java b/sdk/ai/azure-ai-inference/src/test/java/com/azure/ai/inference/EmbeddingsClientTestBase.java index 702812ef536a..ee95be2c662a 100644 --- a/sdk/ai/azure-ai-inference/src/test/java/com/azure/ai/inference/EmbeddingsClientTestBase.java +++ b/sdk/ai/azure-ai-inference/src/test/java/com/azure/ai/inference/EmbeddingsClientTestBase.java @@ -19,14 +19,19 @@ import com.azure.core.util.Configuration; import org.junit.jupiter.api.Test; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Consumer; -import static com.azure.ai.inference.TestUtils.FAKE_API_KEY; +import static com.azure.ai.inference.TestUtils.*; import static org.junit.jupiter.api.Assertions.*; +import static com.azure.ai.inference.TestUtils.TEST_IMAGE_PATH; +import static com.azure.ai.inference.TestUtils.TEST_IMAGE_FORMAT; + public abstract class EmbeddingsClientTestBase extends TestProxyTestBase { protected EmbeddingsClient embeddingsClient; protected ImageEmbeddingsClient imageEmbeddingsClient; @@ -75,11 +80,13 @@ ImageEmbeddingsClientBuilder getImageEmbeddingsClientBuilder(HttpClient httpClie builder.endpoint("https://localhost:8080").credential(new AzureKeyCredential(FAKE_API_KEY)); } else if (testMode == TestMode.RECORD) { builder.addPolicy(interceptorManager.getRecordPolicy()) - .endpoint(Configuration.getGlobalConfiguration().get("EMBEDDINGS_MODEL_ENDPOINT")) - .credential(new AzureKeyCredential(Configuration.getGlobalConfiguration().get("AZURE_EMBEDDINGS_KEY"))); + .endpoint(Configuration.getGlobalConfiguration().get("IMAGE_EMBEDDINGS_MODEL_ENDPOINT")) + .credential( + new AzureKeyCredential(Configuration.getGlobalConfiguration().get("AZURE_IMAGE_EMBEDDINGS_KEY"))); } else { - builder.endpoint(Configuration.getGlobalConfiguration().get("EMBEDDINGS_MODEL_ENDPOINT")) - .credential(new AzureKeyCredential(Configuration.getGlobalConfiguration().get("AZURE_EMBEDDINGS_KEY"))); + builder.endpoint(Configuration.getGlobalConfiguration().get("IMAGE_EMBEDDINGS_MODEL_ENDPOINT")) + .credential( + new AzureKeyCredential(Configuration.getGlobalConfiguration().get("AZURE_IMAGE_EMBEDDINGS_KEY"))); } return builder; } @@ -106,6 +113,10 @@ void getEmbeddingsRunner(Consumer> testRunner) { testRunner.accept(getPrompts()); } + void getImageEmbeddingsRunner(Consumer> testRunner) { + testRunner.accept(getInputs()); + } + static void assertEmbeddings(EmbeddingsResult actual) { List data = actual.getData(); assertNotNull(data); @@ -125,4 +136,11 @@ private List getPrompts() { prompts.add("What's the best way to train a parrot?"); return prompts; } + + private List getInputs() { + Path testFilePath = Paths.get(TEST_IMAGE_PATH); + List inputList = new ArrayList<>(); + inputList.add(new ImageEmbeddingInput(testFilePath, TEST_IMAGE_FORMAT)); + return inputList; + } } diff --git a/sdk/ai/azure-ai-inference/src/test/java/com/azure/ai/inference/ImageEmbeddingsAsyncClientTest.java b/sdk/ai/azure-ai-inference/src/test/java/com/azure/ai/inference/ImageEmbeddingsAsyncClientTest.java new file mode 100644 index 000000000000..6f8766dfd92a --- /dev/null +++ b/sdk/ai/azure-ai-inference/src/test/java/com/azure/ai/inference/ImageEmbeddingsAsyncClientTest.java @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.inference; + +import com.azure.core.http.HttpClient; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import reactor.test.StepVerifier; + +import static com.azure.ai.inference.TestUtils.DISPLAY_NAME_WITH_ARGUMENTS; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +public class ImageEmbeddingsAsyncClientTest extends EmbeddingsClientTestBase { + private ImageEmbeddingsAsyncClient client; + + private ImageEmbeddingsAsyncClient getImageEmbeddingsAsyncClient(HttpClient httpClient) { + return getImageEmbeddingsClientBuilder( + interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) + .buildAsyncClient(); + } + + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.inference.TestUtils#getTestParameters") + public void testGetEmbeddings(HttpClient httpClient) { + client = getImageEmbeddingsAsyncClient(httpClient); + getImageEmbeddingsRunner((inputList) -> { + StepVerifier.create(client.embed(inputList)).assertNext(result -> { + assertNotNull(result.getUsage()); + assertEmbeddings(result); + }).verifyComplete(); + }); + } +} diff --git a/sdk/ai/azure-ai-inference/src/test/java/com/azure/ai/inference/ImageEmbeddingsSyncClientTest.java b/sdk/ai/azure-ai-inference/src/test/java/com/azure/ai/inference/ImageEmbeddingsSyncClientTest.java new file mode 100644 index 000000000000..dac6b35157f8 --- /dev/null +++ b/sdk/ai/azure-ai-inference/src/test/java/com/azure/ai/inference/ImageEmbeddingsSyncClientTest.java @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.inference; + +import com.azure.ai.inference.models.*; +import com.azure.core.http.HttpClient; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static com.azure.ai.inference.TestUtils.DISPLAY_NAME_WITH_ARGUMENTS; + +public class ImageEmbeddingsSyncClientTest extends EmbeddingsClientTestBase { + private ImageEmbeddingsClient client; + + private ImageEmbeddingsClient getImageEmbeddingsClient(HttpClient httpClient) { + return getImageEmbeddingsClientBuilder( + interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient).buildClient(); + } + + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.inference.TestUtils#getTestParameters") + public void testGetEmbeddings(HttpClient httpClient) { + client = getImageEmbeddingsClient(httpClient); + getImageEmbeddingsRunner((inputList) -> { + EmbeddingsResult result = client.embed(inputList); + assertEmbeddings(result); + }); + } + +} diff --git a/sdk/ai/azure-ai-inference/src/test/java/com/azure/ai/inference/TestUtils.java b/sdk/ai/azure-ai-inference/src/test/java/com/azure/ai/inference/TestUtils.java index ac5ced527df7..1ea00580fe05 100644 --- a/sdk/ai/azure-ai-inference/src/test/java/com/azure/ai/inference/TestUtils.java +++ b/sdk/ai/azure-ai-inference/src/test/java/com/azure/ai/inference/TestUtils.java @@ -15,6 +15,8 @@ public class TestUtils { static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; static final String FAKE_API_KEY = "fakeKeyPlaceholder"; + static final String TEST_IMAGE_PATH = "./src/samples/resources/sample-images/sample.png"; + static final String TEST_IMAGE_FORMAT = "png"; /** * Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} diff --git a/sdk/ai/azure-ai-inference/tsp-location.yaml b/sdk/ai/azure-ai-inference/tsp-location.yaml index b4f13dd78be3..87e875fdb0ff 100644 --- a/sdk/ai/azure-ai-inference/tsp-location.yaml +++ b/sdk/ai/azure-ai-inference/tsp-location.yaml @@ -1,4 +1,4 @@ -commit: 016b80ae90f5fabc1e572efabd3ecb1030d444c0 +commit: 8f5ad43ec297181e26d5c10f2ebbdc9ce636fd0c additionalDirectories: [] repo: Azure/azure-rest-api-specs directory: specification/ai/ModelClient diff --git a/sdk/alertsmanagement/azure-resourcemanager-alertsmanagement/README.md b/sdk/alertsmanagement/azure-resourcemanager-alertsmanagement/README.md index b17182628b61..5076998a7f1e 100644 --- a/sdk/alertsmanagement/azure-resourcemanager-alertsmanagement/README.md +++ b/sdk/alertsmanagement/azure-resourcemanager-alertsmanagement/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-alertsmanagement - 1.0.0-beta.2 + 1.0.0-beta.3 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Falertsmanagement%2Fazure-resourcemanager-alertsmanagement%2FREADME.png) + diff --git a/sdk/alertsmanagement/azure-resourcemanager-alertsmanagement/pom.xml b/sdk/alertsmanagement/azure-resourcemanager-alertsmanagement/pom.xml index 1220eb3d9b36..567613f477c8 100644 --- a/sdk/alertsmanagement/azure-resourcemanager-alertsmanagement/pom.xml +++ b/sdk/alertsmanagement/azure-resourcemanager-alertsmanagement/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/README.md b/sdk/anomalydetector/azure-ai-anomalydetector/README.md index 61687fd170f4..166af7a5f334 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/README.md +++ b/sdk/anomalydetector/azure-ai-anomalydetector/README.md @@ -23,7 +23,7 @@ For more information about creating the resource or how to get the location and com.azure azure-ai-anomalydetector - 3.0.0-beta.5 + 3.0.0-beta.6 ``` @@ -61,7 +61,7 @@ with the Azure SDK, please include the `azure-identity` package: com.azure azure-identity - 1.14.2 + 1.15.3 ``` @@ -241,4 +241,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][code_of_con [package]: https://central.sonatype.com/artifact/com.azure/azure-ai-anomalydetector [samples_readme]: https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/anomalydetector/azure-ai-anomalydetector/src/samples/README.md [logging]: https://github.com/Azure/azure-sdk-for-java/wiki/Logging-in-Azure-SDK -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fanomalydetector%2Fazure-ai-anomalydetector%2FREADME.png) + diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/pom.xml b/sdk/anomalydetector/azure-ai-anomalydetector/pom.xml index 96c84a317f44..87512c2f0866 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/pom.xml +++ b/sdk/anomalydetector/azure-ai-anomalydetector/pom.xml @@ -49,25 +49,25 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/apicenter/azure-resourcemanager-apicenter/README.md b/sdk/apicenter/azure-resourcemanager-apicenter/README.md index ef73f8838e72..651eae7b5027 100644 --- a/sdk/apicenter/azure-resourcemanager-apicenter/README.md +++ b/sdk/apicenter/azure-resourcemanager-apicenter/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-apicenter - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -108,4 +108,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fapicenter%2Fazure-resourcemanager-apicenter%2FREADME.png) + diff --git a/sdk/apicenter/azure-resourcemanager-apicenter/pom.xml b/sdk/apicenter/azure-resourcemanager-apicenter/pom.xml index 11e7f33b98cd..d298a5190604 100644 --- a/sdk/apicenter/azure-resourcemanager-apicenter/pom.xml +++ b/sdk/apicenter/azure-resourcemanager-apicenter/pom.xml @@ -51,29 +51,29 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/apimanagement/azure-resourcemanager-apimanagement/README.md b/sdk/apimanagement/azure-resourcemanager-apimanagement/README.md index 789cc12790d5..eb79dde88444 100644 --- a/sdk/apimanagement/azure-resourcemanager-apimanagement/README.md +++ b/sdk/apimanagement/azure-resourcemanager-apimanagement/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-apimanagement - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -112,4 +112,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fapimanagement%2Fazure-resourcemanager-apimanagement%2FREADME.png) + diff --git a/sdk/apimanagement/azure-resourcemanager-apimanagement/pom.xml b/sdk/apimanagement/azure-resourcemanager-apimanagement/pom.xml index 00204b74c572..12f729d00e43 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.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test @@ -91,7 +91,7 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/appcomplianceautomation/azure-resourcemanager-appcomplianceautomation/README.md b/sdk/appcomplianceautomation/azure-resourcemanager-appcomplianceautomation/README.md index 137018fb9503..1119b51b802e 100644 --- a/sdk/appcomplianceautomation/azure-resourcemanager-appcomplianceautomation/README.md +++ b/sdk/appcomplianceautomation/azure-resourcemanager-appcomplianceautomation/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-appcomplianceautomation - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fappcomplianceautomation%2Fazure-resourcemanager-appcomplianceautomation%2FREADME.png) + diff --git a/sdk/appcomplianceautomation/azure-resourcemanager-appcomplianceautomation/pom.xml b/sdk/appcomplianceautomation/azure-resourcemanager-appcomplianceautomation/pom.xml index 3ade13d01278..c3798981b941 100644 --- a/sdk/appcomplianceautomation/azure-resourcemanager-appcomplianceautomation/pom.xml +++ b/sdk/appcomplianceautomation/azure-resourcemanager-appcomplianceautomation/pom.xml @@ -50,28 +50,28 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/appconfiguration/azure-data-appconfiguration-perf/pom.xml b/sdk/appconfiguration/azure-data-appconfiguration-perf/pom.xml index b112bd455161..ed797e7894e3 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration-perf/pom.xml +++ b/sdk/appconfiguration/azure-data-appconfiguration-perf/pom.xml @@ -32,18 +32,18 @@ com.azure azure-data-appconfiguration - 1.8.0-beta.1 + 1.8.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 diff --git a/sdk/appconfiguration/azure-data-appconfiguration/CHANGELOG.md b/sdk/appconfiguration/azure-data-appconfiguration/CHANGELOG.md index 2280c4074741..b328c984c370 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/CHANGELOG.md +++ b/sdk/appconfiguration/azure-data-appconfiguration/CHANGELOG.md @@ -1,23 +1,40 @@ # Release History -## 1.8.0-beta.1 (Unreleased) +## 1.8.0 (2025-03-12) ### Features Added -### Breaking Changes +- Added support for specifying the token credential's Microsoft Entra audience when creating a client. -### Bugs Fixed +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core-http-netty` from `1.15.10` to version `1.15.11`. +- Upgraded `azure-json` from `1.4.0` to version `1.5.0`. +- Upgraded `azure-core` from `1.55.2` to version `1.55.3`. + +## 1.7.4 (2025-02-25) ### Other Changes +#### Dependency Updates + +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`. +- Upgraded `azure-json` from `1.3.0` to version `1.4.0`. +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. + + ## 1.7.3 (2024-12-04) ### Other Changes #### Dependency Updates + - Upgraded `azure-core` from `1.53.0` to version `1.54.1`. - Upgraded `azure-core-http-netty` from `1.15.5` to version `1.15.7`. + ## 1.7.2 (2024-10-27) ### Other Changes @@ -37,6 +54,7 @@ - Upgraded `azure-core-http-netty` from `1.15.3` to version `1.15.4`. - Upgraded `azure-core` from `1.51.0` to version `1.52.0`. + ## 1.7.0 (2024-08-07) ### Features Added diff --git a/sdk/appconfiguration/azure-data-appconfiguration/README.md b/sdk/appconfiguration/azure-data-appconfiguration/README.md index 6bfa7bcf63a8..c76ced0a26ba 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/README.md +++ b/sdk/appconfiguration/azure-data-appconfiguration/README.md @@ -56,7 +56,7 @@ add the direct dependency to your project as follows. com.azure azure-data-appconfiguration - 1.7.0 + 1.8.0 ``` [//]: # ({x-version-update-end}) @@ -80,7 +80,7 @@ az appconfig create --name --resource-group com.azure azure-data-appconfiguration - 1.8.0-beta.1 + 1.8.0 Microsoft Azure client library for App Configuration This package contains the Microsoft Azure App Configuration client library. @@ -54,29 +54,29 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationAsyncClient.java b/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationAsyncClient.java index 9e649fd36493..1fee78715b51 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationAsyncClient.java +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationAsyncClient.java @@ -71,7 +71,7 @@ * *

In order to interact with the App Configuration service you'll need to create an instance of the * {@link com.azure.data.appconfiguration.ConfigurationAsyncClient} class. To make this possible you'll need the - * connection string of the configuration store. Alternatively, you can use AAD authentication via + * connection string of the configuration store. Alternatively, you can use Entra authentication via * Azure Identity * to connect to the service.

*
    diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationClient.java b/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationClient.java index 850f3ff24d33..e09a97c5d6d9 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationClient.java +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationClient.java @@ -71,7 +71,7 @@ * *

    In order to interact with the App Configuration service you'll need to create an instance of the * {@link ConfigurationClient} class. To make this possible you'll need the connection - * string of the configuration store. Alternatively, you can use AAD authentication via + * string of the configuration store. Alternatively, you can use Entra authentication via * Azure Identity * to connect to the service.

    *
      diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationClientBuilder.java b/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationClientBuilder.java index 864f7402064d..79c0bb5c80f2 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationClientBuilder.java +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationClientBuilder.java @@ -43,6 +43,7 @@ import com.azure.data.appconfiguration.implementation.ConfigurationClientCredentials; import com.azure.data.appconfiguration.implementation.ConfigurationCredentialsPolicy; import com.azure.data.appconfiguration.implementation.SyncTokenPolicy; +import com.azure.data.appconfiguration.models.ConfigurationAudience; import java.net.MalformedURLException; import java.net.URL; @@ -144,6 +145,8 @@ public final class ConfigurationClientBuilder implements TokenCredentialTrait { + /** + * The Azure App Configuration service audience for China Cloud. + */ + public static final ConfigurationAudience AZURE_CHINA = fromString("https://appconfig.azure.cn"); + + /** + * The Azure App Configuration service audience for US Government Cloud. + */ + public static final ConfigurationAudience AZURE_GOVERNMENT = fromString("https://appconfig.azure.us"); + + /** + * The Azure App Configuration service audience for Public Cloud. + */ + public static final ConfigurationAudience AZURE_PUBLIC_CLOUD = fromString("https://appconfig.azure.com"); + + /** + * Creates a new instance of ConfigurationAudience value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public ConfigurationAudience() { + } + + /** + * Creates or finds a ConfigurationAudience from its string representation. + * + * @param name a name to look for. + * @return the corresponding ConfigurationAudience. + */ + public static ConfigurationAudience fromString(String name) { + return fromString(name, ConfigurationAudience.class); + } + + /** + * Gets known ConfigurationAudience values. + * + * @return known ConfigurationAudience values. + */ + public static Collection values() { + return values(ConfigurationAudience.class); + } +} diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/package-info.java b/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/package-info.java index f7445ef79b18..284c471a8cd7 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/package-info.java +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/package-info.java @@ -17,7 +17,7 @@ * *

      In order to interact with the App Configuration service you'll need to create an instance of the Configuration * Client class. To make this possible you'll need the connection string of the configuration store. Alternatively, - * you can use AAD authentication via + * you can use Entra authentication via * Azure Identity * to connect to the service.

      *
        diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/samples/README.md b/sdk/appconfiguration/azure-data-appconfiguration/src/samples/README.md index 400d3a9d381c..006a530a4932 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/src/samples/README.md +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/samples/README.md @@ -32,7 +32,7 @@ The following sections provide several code snippets covering some of the most c - [Set a configuration setting to read only][sample_read_only] - [Clear read only from a configuration setting][sample_read_only] - [Conditional request a configuration setting][sample_conditional_request] -- [AAD Authentication][sample_aad] +- [Entra Authentication][sample_entra_authentication] - [HTTP client with proxy option][proxy_option] - [Feature Flag configuration setting][sample_feature_flag_setting] - [Secret Reference configuration setting][sample_secret_reference_setting] @@ -65,10 +65,10 @@ This project welcomes contributions and suggestions. Find [more contributing][SD [sample_read_only]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/ReadOnlySample.java [sample_read_revision_history]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/ReadRevisionHistory.java [sample_read_revision_history_tags]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/ReadRevisionHistoryWIthTagsFilter.java -[sample_aad]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/AadAuthentication.java +[sample_entra_authentication]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/EntraIdAuthentication.java [sample_feature_flag_setting]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/FeatureFlagConfigurationSettingSample.java [sample_secret_reference_setting]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/SecretReferenceConfigurationSettingSample.java [sample_snapshot_CRU_usage]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/CreateSnapshot.java [sample_snapshot_create_with_tags]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/CreateSnapshotWithTagsFilter.java [sample_list_snapshots]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/ListSnapshots.java -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fappconfiguration%2Fazure-data-appconfiguration%2Fsrc%2Fsamples%2FREADME.png) + diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/EntraIdAuthentication.java b/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/EntraIdAuthentication.java new file mode 100644 index 000000000000..7511c12372bb --- /dev/null +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/EntraIdAuthentication.java @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.util.Configuration; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.identity.DefaultAzureCredential; +import com.azure.identity.DefaultAzureCredentialBuilder; + +/** + * Sample demonstrates how to use Entra token to build a configuration client. + */ +public class EntraIdAuthentication { + /** + * Sample for how to use Entra token Authentication. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The endpoint can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Overview" page. Looking for the "Endpoint" keyword. + String endpoint = Configuration.getGlobalConfiguration().get("AZ_CONFIG_ENDPOINT"); + + // Default token credential could be obtained from Identity service. + // It tries to create a valid credential in the following order: + // EnvironmentCredential + // ManagedIdentityCredential + // SharedTokenCacheCredential + // Fails if none of the credentials above could be created. + DefaultAzureCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); + + final ConfigurationClient client = new ConfigurationClientBuilder() + .credential(tokenCredential) // Entra authentication + .endpoint(endpoint) + .buildClient(); + + // Name of the key to add to the configuration service. + final String key = "hello"; + final String value = "world"; + + System.out.println("Beginning of synchronous sample..."); + + ConfigurationSetting setting = client.setConfigurationSetting(key, null, value); + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + + setting = client.getConfigurationSetting(key, null, null); + System.out.printf("[GetConfigurationSetting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + + setting = client.deleteConfigurationSetting(key, null); + System.out.printf("[DeleteConfigurationSetting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + + System.out.println("End of synchronous sample."); + } +} diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/ReadmeSamples.java b/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/ReadmeSamples.java index 5c03ce43ee30..83e41145e1be 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/ReadmeSamples.java +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/ReadmeSamples.java @@ -69,14 +69,14 @@ public void createAsyncClient() { // END: readme-sample-createAsyncClient } - public void aadAuthentication() { - // BEGIN: readme-sample-aadAuthentication + public void entraAuthentication() { + // BEGIN: readme-sample-entraAuthentication DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build(); ConfigurationClient configurationClient = new ConfigurationClientBuilder() .credential(credential) .endpoint(endpoint) .buildClient(); - // END: readme-sample-aadAuthentication + // END: readme-sample-entraAuthentication } public void sqlExample() { @@ -364,7 +364,7 @@ public void enableHttpLogging() { .buildClient(); // or DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build(); - ConfigurationClient configurationClientAad = new ConfigurationClientBuilder() + ConfigurationClient configurationClientEntraId = new ConfigurationClientBuilder() .credential(credential) .endpoint(endpoint) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/test/java/com/azure/data/appconfiguration/ConfigurationClientBuilderTest.java b/sdk/appconfiguration/azure-data-appconfiguration/src/test/java/com/azure/data/appconfiguration/ConfigurationClientBuilderTest.java index 11eafb605ce0..7712bff35a0a 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/src/test/java/com/azure/data/appconfiguration/ConfigurationClientBuilderTest.java +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/test/java/com/azure/data/appconfiguration/ConfigurationClientBuilderTest.java @@ -23,12 +23,15 @@ import com.azure.core.util.Header; import com.azure.data.appconfiguration.implementation.ClientConstants; import com.azure.data.appconfiguration.implementation.ConfigurationClientCredentials; +import com.azure.data.appconfiguration.models.ConfigurationAudience; import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.identity.DefaultAzureCredentialBuilder; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import reactor.core.publisher.Mono; +import java.lang.reflect.Method; import java.net.URI; import java.net.URISyntaxException; import java.time.Duration; @@ -146,7 +149,7 @@ public void invalidConnectionStringSegmentCount() { @Test @DoNotRecord - public void nullAADCredential() { + public void nullEntraCredential() { assertThrows(NullPointerException.class, () -> { final ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); builder.endpoint(ENDPOINT).credential(null).buildAsyncClient(); @@ -299,4 +302,74 @@ private static URI getURI(String endpointFormat, String namespace, String domain exception); } } + + @Test + @DoNotRecord + public void testGetUsGovScope() throws Exception { + ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); + Method method = ConfigurationClientBuilder.class.getDeclaredMethod("getDefaultScope", String.class); + method.setAccessible(true); + + String expectedScope = "https://appconfig.azure.us/.default"; + + String legacyEndpoint = "https://example1.azconfig.azure.us"; + String actualScope = (String) method.invoke(builder, legacyEndpoint); + assertEquals(expectedScope, actualScope); + + String endpoint = "https://example1.appconfig.azure.us"; + actualScope = (String) method.invoke(builder, endpoint); + assertEquals(expectedScope, actualScope); + } + + @Test + @DoNotRecord + public void testGetDefaultScope() throws Exception { + ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); + Method method = ConfigurationClientBuilder.class.getDeclaredMethod("getDefaultScope", String.class); + method.setAccessible(true); + + String expectedScope = "https://appconfig.azure.com/.default"; + + String legacyEndpoint = "https://example1.azconfig.azure.com"; + String actualScope = (String) method.invoke(builder, legacyEndpoint); + assertEquals(expectedScope, actualScope); + + String endpoint = "https://example1.appconfig.azure.com"; + actualScope = (String) method.invoke(builder, endpoint); + assertEquals(expectedScope, actualScope); + } + + @Test + @DoNotRecord + public void testGetChinaScope() throws Exception { + ConfigurationClientBuilder builder = new ConfigurationClientBuilder(); + Method method = ConfigurationClientBuilder.class.getDeclaredMethod("getDefaultScope", String.class); + method.setAccessible(true); + + String expectedScope = "https://appconfig.azure.cn/.default"; + + String legacyEndpoint = "https://example1.azconfig.azure.cn"; + String actualScope = (String) method.invoke(builder, legacyEndpoint); + assertEquals(expectedScope, actualScope); + + String endpoint = "https://example1.appconfig.azure.cn"; + actualScope = (String) method.invoke(builder, endpoint); + assertEquals(expectedScope, actualScope); + } + + @Test + @DoNotRecord + public void testUserDefinedScope() throws Exception { + String fakeEndpoint = "https://example1.azconfig.azure.com"; + ConfigurationClientBuilder builder + = new ConfigurationClientBuilder().endpoint("https://example1.azconfig.azure.com") + .credential(new DefaultAzureCredentialBuilder().build()) + .audience(ConfigurationAudience.AZURE_CHINA); + builder.buildClient(); + Method method = ConfigurationClientBuilder.class.getDeclaredMethod("getDefaultScope", String.class); + method.setAccessible(true); + + String actualScope = (String) method.invoke(builder, fakeEndpoint); + assertEquals(ConfigurationAudience.AZURE_CHINA + "/.default", actualScope); + } } diff --git a/sdk/appconfiguration/azure-resourcemanager-appconfiguration/README.md b/sdk/appconfiguration/azure-resourcemanager-appconfiguration/README.md index 771ab49267b7..b592b659c3f0 100644 --- a/sdk/appconfiguration/azure-resourcemanager-appconfiguration/README.md +++ b/sdk/appconfiguration/azure-resourcemanager-appconfiguration/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-appconfiguration - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fappconfiguration%2Fazure-resourcemanager-appconfiguration%2FREADME.png) + diff --git a/sdk/appconfiguration/azure-resourcemanager-appconfiguration/pom.xml b/sdk/appconfiguration/azure-resourcemanager-appconfiguration/pom.xml index 88f61e69f5bf..f5e83be1a1ff 100644 --- a/sdk/appconfiguration/azure-resourcemanager-appconfiguration/pom.xml +++ b/sdk/appconfiguration/azure-resourcemanager-appconfiguration/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/appcontainers/azure-resourcemanager-appcontainers/README.md b/sdk/appcontainers/azure-resourcemanager-appcontainers/README.md index 9d05f22b6128..3c7c1dc62405 100644 --- a/sdk/appcontainers/azure-resourcemanager-appcontainers/README.md +++ b/sdk/appcontainers/azure-resourcemanager-appcontainers/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-appcontainers - 1.1.0-beta.1 + 1.1.0-beta.2 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fappcontainers%2Fazure-resourcemanager-appcontainers%2FREADME.png) + diff --git a/sdk/appcontainers/azure-resourcemanager-appcontainers/pom.xml b/sdk/appcontainers/azure-resourcemanager-appcontainers/pom.xml index 310677329381..87a29ede6c70 100644 --- a/sdk/appcontainers/azure-resourcemanager-appcontainers/pom.xml +++ b/sdk/appcontainers/azure-resourcemanager-appcontainers/pom.xml @@ -51,29 +51,29 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-json - 1.3.0 + 1.5.0 diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/CHANGELOG.md b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/CHANGELOG.md index 0e135f5473ab..d896746fb3e3 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/CHANGELOG.md +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.2.0-beta.1 (Unreleased) +## 1.2.0-beta.2 (Unreleased) ### Features Added @@ -10,6 +10,81 @@ ### Other Changes +## 1.2.0-beta.1 (2025-02-18) + +- Azure Resource Manager ApplicationInsights client library for Java. This package contains Microsoft Azure SDK for ApplicationInsights Management SDK. Composite Swagger for Application Insights Management Client. Package tag package-2024-08-01. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). + +### Breaking Changes + +#### `models.MyWorkbooksListResult` was removed + +#### `models.MyWorkbookManagedIdentityType` was removed + +#### `models.MyWorkbook` was removed + +#### `models.MyWorkbookUserAssignedIdentities` was removed + +#### `models.MyWorkbookResource` was removed + +#### `models.MyWorkbookManagedIdentity` was removed + +#### `models.MyWorkbooks` was removed + +#### `models.MyWorkbook$UpdateStages` was removed + +#### `models.MyWorkbook$DefinitionStages` was removed + +#### `models.Kind` was removed + +#### `models.MyWorkbook$Update` was removed + +#### `models.MyWorkbook$Definition` was removed + +#### `models.ErrorDefinitionException` was removed + +#### `models.ErrorDefinition` was removed + +#### `ApplicationInsightsManager` was modified + +* `myWorkbooks()` was removed + +### Features Added + +* `models.ComponentLinkedStorageAccounts` was added + +* `models.ComponentLinkedStorageAccounts$Update` was added + +* `models.ComponentLinkedStorageAccounts$DefinitionStages` was added + +* `models.DeletedWorkbookResource` was added + +* `models.DeletedWorkbooks` was added + +* `models.ComponentLinkedStorageAccountsOperations` was added + +* `models.DeletedWorkbooksListResult` was added + +* `models.DeletedWorkbookErrorDefinitionException` was added + +* `models.ComponentLinkedStorageAccountsPatch` was added + +* `models.DeletedWorkbookInnerErrorTrace` was added + +* `models.StorageType` was added + +* `models.DeletedWorkbookErrorDefinition` was added + +* `models.DeletedWorkbook` was added + +* `models.ComponentLinkedStorageAccounts$Definition` was added + +* `models.ComponentLinkedStorageAccounts$UpdateStages` was added + +#### `ApplicationInsightsManager` was modified + +* `deletedWorkbooks()` was added +* `componentLinkedStorageAccountsOperations()` was added + ## 1.1.0 (2024-12-13) - Azure Resource Manager ApplicationInsights client library for Java. This package contains Microsoft Azure SDK for ApplicationInsights Management SDK. Composite Swagger for Application Insights Management Client. Package tag package-2022-06-15-java. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/README.md b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/README.md index 92aeefa55c61..cf8babd1affd 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/README.md +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/README.md @@ -2,7 +2,7 @@ Azure Resource Manager ApplicationInsights client library for Java. -This package contains Microsoft Azure SDK for ApplicationInsights Management SDK. Composite Swagger for Application Insights Management Client. Package tag package-2022-06-15-java. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). +This package contains Microsoft Azure SDK for ApplicationInsights Management SDK. Composite Swagger for Application Insights Management Client. Package tag package-2024-08-01. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). ## We'd love to hear your feedback @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-applicationinsights - 1.1.0 + 1.2.0-beta.2 ``` [//]: # ({x-version-update-end}) @@ -52,7 +52,7 @@ Azure subscription ID can be configured via `AZURE_SUBSCRIPTION_ID` environment Assuming the use of the `DefaultAzureCredential` credential class, the client can be authenticated using the following code: ```java -AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); +AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); @@ -60,7 +60,7 @@ ApplicationInsightsManager manager = ApplicationInsightsManager .authenticate(credential, profile); ``` -The sample code assumes global Azure. Please change `AzureEnvironment.AZURE` variable if otherwise. +The sample code assumes global Azure. Please change the `AzureCloud.AZURE_PUBLIC_CLOUD` variable if otherwise. See [Authentication][authenticate] for more options. @@ -117,5 +117,3 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [cg]: https://github.com/Azure/azure-sdk-for-java/blob/main/CONTRIBUTING.md [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ - -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fapplicationinsights%2Fazure-resourcemanager-applicationinsights%2FREADME.png) diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/SAMPLE.md b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/SAMPLE.md index 5ffd6e0ca48f..1d02c647db82 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/SAMPLE.md +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/SAMPLE.md @@ -35,6 +35,13 @@ - [Get](#componentfeaturecapabilities_get) +## ComponentLinkedStorageAccountsOperation + +- [CreateAndUpdate](#componentlinkedstorageaccountsoperation_createandupdate) +- [Delete](#componentlinkedstorageaccountsoperation_delete) +- [Get](#componentlinkedstorageaccountsoperation_get) +- [Update](#componentlinkedstorageaccountsoperation_update) + ## ComponentQuotaStatus - [Get](#componentquotastatus_get) @@ -50,6 +57,10 @@ - [Purge](#components_purge) - [UpdateTags](#components_updatetags) +## DeletedWorkbooks + +- [List](#deletedworkbooks_list) + ## ExportConfigurations - [Create](#exportconfigurations_create) @@ -70,15 +81,6 @@ - [Get](#livetoken_get) -## MyWorkbooks - -- [CreateOrUpdate](#myworkbooks_createorupdate) -- [Delete](#myworkbooks_delete) -- [GetByResourceGroup](#myworkbooks_getbyresourcegroup) -- [List](#myworkbooks_list) -- [ListByResourceGroup](#myworkbooks_listbyresourcegroup) -- [Update](#myworkbooks_update) - ## ProactiveDetectionConfigurations - [Get](#proactivedetectionconfigurations_get) @@ -571,6 +573,127 @@ public final class ComponentFeatureCapabilitiesGetSamples { } ``` +### ComponentLinkedStorageAccountsOperation_CreateAndUpdate + +```java +import com.azure.resourcemanager.applicationinsights.models.StorageType; + +/** + * Samples for ComponentLinkedStorageAccountsOperation CreateAndUpdate. + */ +public final class ComponentLinkedStorageAccountsOperationCreateAndUpdateSamples { + /* + * x-ms-original-file: + * specification/applicationinsights/resource-manager/Microsoft.Insights/preview/2020-03-01-preview/examples/ + * ComponentLinkedStorageAccountsCreateAndUpdate.json + */ + /** + * Sample code: ComponentLinkedStorageAccountsCreateAndUpdate. + * + * @param manager Entry point to ApplicationInsightsManager. + */ + public static void componentLinkedStorageAccountsCreateAndUpdate( + com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) { + manager.componentLinkedStorageAccountsOperations() + .define(StorageType.SERVICE_PROFILER) + .withExistingComponent("someResourceGroupName", "myComponent") + .withLinkedStorageAccount( + "/subscriptions/86dc51d3-92ed-4d7e-947a-775ea79b4918/resourceGroups/someResourceGroupName/providers/Microsoft.Storage/storageAccounts/storageaccountname") + .create(); + } +} +``` + +### ComponentLinkedStorageAccountsOperation_Delete + +```java +import com.azure.resourcemanager.applicationinsights.models.StorageType; + +/** + * Samples for ComponentLinkedStorageAccountsOperation Delete. + */ +public final class ComponentLinkedStorageAccountsOperationDeleteSamples { + /* + * x-ms-original-file: + * specification/applicationinsights/resource-manager/Microsoft.Insights/preview/2020-03-01-preview/examples/ + * ComponentLinkedStorageAccountsDelete.json + */ + /** + * Sample code: ComponentLinkedStorageAccountsDelete. + * + * @param manager Entry point to ApplicationInsightsManager. + */ + public static void componentLinkedStorageAccountsDelete( + com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) { + manager.componentLinkedStorageAccountsOperations() + .deleteWithResponse("someResourceGroupName", "myComponent", StorageType.SERVICE_PROFILER, + com.azure.core.util.Context.NONE); + } +} +``` + +### ComponentLinkedStorageAccountsOperation_Get + +```java +import com.azure.resourcemanager.applicationinsights.models.StorageType; + +/** + * Samples for ComponentLinkedStorageAccountsOperation Get. + */ +public final class ComponentLinkedStorageAccountsOperationGetSamples { + /* + * x-ms-original-file: + * specification/applicationinsights/resource-manager/Microsoft.Insights/preview/2020-03-01-preview/examples/ + * ComponentLinkedStorageAccountsGet.json + */ + /** + * Sample code: ComponentLinkedStorageAccountsGet. + * + * @param manager Entry point to ApplicationInsightsManager. + */ + public static void componentLinkedStorageAccountsGet( + com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) { + manager.componentLinkedStorageAccountsOperations() + .getWithResponse("someResourceGroupName", "myComponent", StorageType.SERVICE_PROFILER, + com.azure.core.util.Context.NONE); + } +} +``` + +### ComponentLinkedStorageAccountsOperation_Update + +```java +import com.azure.resourcemanager.applicationinsights.models.ComponentLinkedStorageAccounts; +import com.azure.resourcemanager.applicationinsights.models.StorageType; + +/** + * Samples for ComponentLinkedStorageAccountsOperation Update. + */ +public final class ComponentLinkedStorageAccountsOperationUpdateSamples { + /* + * x-ms-original-file: + * specification/applicationinsights/resource-manager/Microsoft.Insights/preview/2020-03-01-preview/examples/ + * ComponentLinkedStorageAccountsUpdate.json + */ + /** + * Sample code: ComponentLinkedStorageAccountsUpdate. + * + * @param manager Entry point to ApplicationInsightsManager. + */ + public static void componentLinkedStorageAccountsUpdate( + com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) { + ComponentLinkedStorageAccounts resource = manager.componentLinkedStorageAccountsOperations() + .getWithResponse("someResourceGroupName", "myComponent", StorageType.SERVICE_PROFILER, + com.azure.core.util.Context.NONE) + .getValue(); + resource.update() + .withLinkedStorageAccount( + "/subscriptions/86dc51d3-92ed-4d7e-947a-775ea79b4918/resourceGroups/someResourceGroupName/providers/Microsoft.Storage/storageAccounts/storageaccountname") + .apply(); + } +} +``` + ### ComponentQuotaStatus_Get ```java @@ -872,6 +995,31 @@ public final class ComponentsUpdateTagsSamples { } ``` +### DeletedWorkbooks_List + +```java + +/** + * Samples for DeletedWorkbooks List. + */ +public final class DeletedWorkbooksListSamples { + /* + * x-ms-original-file: + * specification/applicationinsights/resource-manager/Microsoft.Insights/preview/2024-02-01-preview/examples/ + * DeletedWorkbooksList.json + */ + /** + * Sample code: WorkbooksListSub. + * + * @param manager Entry point to ApplicationInsightsManager. + */ + public static void + workbooksListSub(com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) { + manager.deletedWorkbooks().list(null, null, com.azure.core.util.Context.NONE); + } +} +``` + ### ExportConfigurations_Create ```java @@ -1202,218 +1350,6 @@ public final class LiveTokenGetSamples { } ``` -### MyWorkbooks_CreateOrUpdate - -```java -import com.azure.resourcemanager.applicationinsights.models.Kind; - -/** - * Samples for MyWorkbooks CreateOrUpdate. - */ -public final class MyWorkbooksCreateOrUpdateSamples { - /* - * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2021-03-08/examples/MyWorkbookAdd. - * json - */ - /** - * Sample code: WorkbookAdd. - * - * @param manager Entry point to ApplicationInsightsManager. - */ - public static void workbookAdd(com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) { - manager.myWorkbooks() - .define("deadb33f-8bee-4d3b-a059-9be8dac93960") - .withRegion("west us") - .withExistingResourceGroup("my-resource-group") - .withName("deadb33f-8bee-4d3b-a059-9be8dac93960") - .withKind(Kind.USER) - .withDisplayName("Blah Blah Blah") - .withSerializedData( - "{\"version\":\"Notebook/1.0\",\"items\":[{\"type\":1,\"content\":\"{\"json\":\"## New workbook\\r\\n---\\r\\n\\r\\nWelcome to your new workbook. This area will display text formatted as markdown.\\r\\n\\r\\n\\r\\nWe've included a basic analytics query to get you started. Use the `Edit` button below each section to configure it or add more sections.\"}\",\"halfWidth\":null,\"conditionalVisibility\":null},{\"type\":3,\"content\":\"{\"version\":\"KqlItem/1.0\",\"query\":\"union withsource=TableName *\\n| summarize Count=count() by TableName\\n| render barchart\",\"showQuery\":false,\"size\":1,\"aggregation\":0,\"showAnnotations\":false}\",\"halfWidth\":null,\"conditionalVisibility\":null}],\"isLocked\":false}") - .withCategory("workbook") - .withSourceId( - "/subscriptions/00000000-0000-0000-0000-00000000/resourceGroups/MyGroup/providers/Microsoft.Web/sites/MyTestApp-CodeLens") - .create(); - } -} -``` - -### MyWorkbooks_Delete - -```java -/** - * Samples for MyWorkbooks Delete. - */ -public final class MyWorkbooksDeleteSamples { - /* - * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2021-03-08/examples/MyWorkbookDelete - * .json - */ - /** - * Sample code: WorkbookDelete. - * - * @param manager Entry point to ApplicationInsightsManager. - */ - public static void - workbookDelete(com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) { - manager.myWorkbooks() - .deleteByResourceGroupWithResponse("my-resource-group", "deadb33f-5e0d-4064-8ebb-1a4ed0313eb2", - com.azure.core.util.Context.NONE); - } -} -``` - -### MyWorkbooks_GetByResourceGroup - -```java -/** - * Samples for MyWorkbooks GetByResourceGroup. - */ -public final class MyWorkbooksGetByResourceGroupSamples { - /* - * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2021-03-08/examples/MyWorkbookGet. - * json - */ - /** - * Sample code: WorkbookGet. - * - * @param manager Entry point to ApplicationInsightsManager. - */ - public static void workbookGet(com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) { - manager.myWorkbooks() - .getByResourceGroupWithResponse("my-resource-group", "deadb33f-5e0d-4064-8ebb-1a4ed0313eb2", - com.azure.core.util.Context.NONE); - } -} -``` - -### MyWorkbooks_List - -```java -import com.azure.resourcemanager.applicationinsights.models.CategoryType; - -/** - * Samples for MyWorkbooks List. - */ -public final class MyWorkbooksListSamples { - /* - * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2021-03-08/examples/MyWorkbooksList. - * json - */ - /** - * Sample code: WorkbooksList. - * - * @param manager Entry point to ApplicationInsightsManager. - */ - public static void workbooksList(com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) { - manager.myWorkbooks().list(CategoryType.WORKBOOK, null, null, com.azure.core.util.Context.NONE); - } - - /* - * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2021-03-08/examples/MyWorkbooksList2 - * .json - */ - /** - * Sample code: WorkbooksList2. - * - * @param manager Entry point to ApplicationInsightsManager. - */ - public static void - workbooksList2(com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) { - manager.myWorkbooks().list(CategoryType.WORKBOOK, null, null, com.azure.core.util.Context.NONE); - } -} -``` - -### MyWorkbooks_ListByResourceGroup - -```java -import com.azure.resourcemanager.applicationinsights.models.CategoryType; - -/** - * Samples for MyWorkbooks ListByResourceGroup. - */ -public final class MyWorkbooksListByResourceGroupSamples { - /* - * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2021-03-08/examples/MyWorkbooksList. - * json - */ - /** - * Sample code: WorkbooksList. - * - * @param manager Entry point to ApplicationInsightsManager. - */ - public static void workbooksList(com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) { - manager.myWorkbooks() - .listByResourceGroup("my-resource-group", CategoryType.WORKBOOK, null, null, null, - com.azure.core.util.Context.NONE); - } - - /* - * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2021-03-08/examples/MyWorkbooksList2 - * .json - */ - /** - * Sample code: WorkbooksList2. - * - * @param manager Entry point to ApplicationInsightsManager. - */ - public static void - workbooksList2(com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) { - manager.myWorkbooks() - .listByResourceGroup("my-resource-group", CategoryType.WORKBOOK, null, null, null, - com.azure.core.util.Context.NONE); - } -} -``` - -### MyWorkbooks_Update - -```java -import com.azure.resourcemanager.applicationinsights.models.Kind; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbook; - -/** - * Samples for MyWorkbooks Update. - */ -public final class MyWorkbooksUpdateSamples { - /* - * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2021-03-08/examples/MyWorkbookUpdate - * .json - */ - /** - * Sample code: WorkbookUpdate. - * - * @param manager Entry point to ApplicationInsightsManager. - */ - public static void - workbookUpdate(com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) { - MyWorkbook resource = manager.myWorkbooks() - .getByResourceGroupWithResponse("my-resource-group", "deadb33f-5e0d-4064-8ebb-1a4ed0313eb2", - com.azure.core.util.Context.NONE) - .getValue(); - resource.update() - .withKind(Kind.USER) - .withDisplayName("Blah Blah Blah") - .withSerializedData( - "{\"version\":\"Notebook/1.0\",\"items\":[{\"type\":1,\"content\":\"{\"json\":\"## New workbook\\r\\n---\\r\\n\\r\\nWelcome to your new workbook. This area will display text formatted as markdown.\\r\\n\\r\\n\\r\\nWe've included a basic analytics query to get you started. Use the `Edit` button below each section to configure it or add more sections.\"}\",\"halfWidth\":null,\"conditionalVisibility\":null},{\"type\":3,\"content\":\"{\"version\":\"KqlItem/1.0\",\"query\":\"union withsource=TableName *\\n| summarize Count=count() by TableName\\n| render barchart\",\"showQuery\":false,\"size\":1,\"aggregation\":0,\"showAnnotations\":false}\",\"halfWidth\":null,\"conditionalVisibility\":null}],\"isLocked\":false}") - .withVersion("ME") - .withCategory("workbook") - .withSourceId( - "/subscriptions/00000000-0000-0000-0000-00000000/resourceGroups/MyGroup/providers/Microsoft.Web/sites/MyTestApp-CodeLens") - .apply(); - } -} -``` - ### ProactiveDetectionConfigurations_Get ```java @@ -2171,7 +2107,7 @@ import java.util.Map; public final class WorkbooksCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/ + * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2023-06-01/examples/ * WorkbookManagedAdd.json */ /** @@ -2205,7 +2141,7 @@ public final class WorkbooksCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/WorkbookAdd.json + * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2023-06-01/examples/WorkbookAdd.json */ /** * Sample code: WorkbookAdd. @@ -2252,7 +2188,7 @@ public final class WorkbooksCreateOrUpdateSamples { public final class WorkbooksDeleteSamples { /* * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/WorkbookDelete. + * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2023-06-01/examples/WorkbookDelete. * json */ /** @@ -2278,7 +2214,7 @@ public final class WorkbooksDeleteSamples { public final class WorkbooksGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/WorkbookGet1. + * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2023-06-01/examples/WorkbookGet1. * json */ /** @@ -2294,7 +2230,7 @@ public final class WorkbooksGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/ + * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2023-06-01/examples/ * WorkbookManagedGet.json */ /** @@ -2311,7 +2247,7 @@ public final class WorkbooksGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/WorkbookGet.json + * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2023-06-01/examples/WorkbookGet.json */ /** * Sample code: WorkbookGet. @@ -2337,7 +2273,7 @@ import com.azure.resourcemanager.applicationinsights.models.CategoryType; public final class WorkbooksListSamples { /* * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/WorkbooksListSub + * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2023-06-01/examples/WorkbooksListSub * .json */ /** @@ -2352,7 +2288,7 @@ public final class WorkbooksListSamples { /* * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/WorkbooksList2. + * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2023-06-01/examples/WorkbooksList2. * json */ /** @@ -2378,7 +2314,7 @@ import com.azure.resourcemanager.applicationinsights.models.CategoryType; public final class WorkbooksListByResourceGroupSamples { /* * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/ + * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2023-06-01/examples/ * WorkbooksManagedList.json */ /** @@ -2396,7 +2332,7 @@ public final class WorkbooksListByResourceGroupSamples { /* * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/WorkbooksList. + * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2023-06-01/examples/WorkbooksList. * json */ /** @@ -2422,7 +2358,7 @@ public final class WorkbooksListByResourceGroupSamples { public final class WorkbooksRevisionGetSamples { /* * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/ + * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2023-06-01/examples/ * WorkbookRevisionGet.json */ /** @@ -2448,7 +2384,7 @@ public final class WorkbooksRevisionGetSamples { public final class WorkbooksRevisionsListSamples { /* * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/ + * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2023-06-01/examples/ * WorkbookRevisionsList.json */ /** @@ -2476,7 +2412,7 @@ import com.azure.resourcemanager.applicationinsights.models.Workbook; public final class WorkbooksUpdateSamples { /* * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/WorkbookUpdate. + * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2023-06-01/examples/WorkbookUpdate. * json */ /** @@ -2498,7 +2434,7 @@ public final class WorkbooksUpdateSamples { /* * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/ + * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2023-06-01/examples/ * WorkbookManagedUpdate.json */ /** diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/pom.xml b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/pom.xml index 9f2ca2b107fc..434bfe637dcd 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/pom.xml +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/pom.xml @@ -14,11 +14,11 @@ com.azure.resourcemanager azure-resourcemanager-applicationinsights - 1.2.0-beta.1 + 1.2.0-beta.2 jar Microsoft Azure SDK for ApplicationInsights Management - This package contains Microsoft Azure SDK for ApplicationInsights Management SDK. For documentation on how to use this package, please see https://aka.ms/azsdk/java/mgmt. Composite Swagger for Application Insights Management Client. Package tag package-2022-06-15-java. + This package contains Microsoft Azure SDK for ApplicationInsights Management SDK. For documentation on how to use this package, please see https://aka.ms/azsdk/java/mgmt. Composite Swagger for Application Insights Management Client. Package tag package-2024-08-01. https://github.com/Azure/azure-sdk-for-java @@ -45,29 +45,30 @@ UTF-8 0 0 + true false com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test @@ -91,7 +92,7 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/ApplicationInsightsManager.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/ApplicationInsightsManager.java index 6fffe10b8c0a..ef037815398b 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/ApplicationInsightsManager.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/ApplicationInsightsManager.java @@ -22,6 +22,7 @@ import com.azure.core.http.policy.UserAgentPolicy; import com.azure.core.management.profile.AzureProfile; import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.applicationinsights.fluent.ApplicationInsightsManagementClient; import com.azure.resourcemanager.applicationinsights.implementation.AnalyticsItemsImpl; @@ -31,12 +32,13 @@ import com.azure.resourcemanager.applicationinsights.implementation.ComponentAvailableFeaturesImpl; import com.azure.resourcemanager.applicationinsights.implementation.ComponentCurrentBillingFeaturesImpl; import com.azure.resourcemanager.applicationinsights.implementation.ComponentFeatureCapabilitiesImpl; +import com.azure.resourcemanager.applicationinsights.implementation.ComponentLinkedStorageAccountsOperationsImpl; import com.azure.resourcemanager.applicationinsights.implementation.ComponentQuotaStatusImpl; import com.azure.resourcemanager.applicationinsights.implementation.ComponentsImpl; +import com.azure.resourcemanager.applicationinsights.implementation.DeletedWorkbooksImpl; import com.azure.resourcemanager.applicationinsights.implementation.ExportConfigurationsImpl; import com.azure.resourcemanager.applicationinsights.implementation.FavoritesImpl; import com.azure.resourcemanager.applicationinsights.implementation.LiveTokensImpl; -import com.azure.resourcemanager.applicationinsights.implementation.MyWorkbooksImpl; import com.azure.resourcemanager.applicationinsights.implementation.OperationsImpl; import com.azure.resourcemanager.applicationinsights.implementation.ProactiveDetectionConfigurationsImpl; import com.azure.resourcemanager.applicationinsights.implementation.WebTestLocationsImpl; @@ -50,12 +52,13 @@ import com.azure.resourcemanager.applicationinsights.models.ComponentAvailableFeatures; import com.azure.resourcemanager.applicationinsights.models.ComponentCurrentBillingFeatures; import com.azure.resourcemanager.applicationinsights.models.ComponentFeatureCapabilities; +import com.azure.resourcemanager.applicationinsights.models.ComponentLinkedStorageAccountsOperations; import com.azure.resourcemanager.applicationinsights.models.ComponentQuotaStatus; import com.azure.resourcemanager.applicationinsights.models.Components; +import com.azure.resourcemanager.applicationinsights.models.DeletedWorkbooks; import com.azure.resourcemanager.applicationinsights.models.ExportConfigurations; import com.azure.resourcemanager.applicationinsights.models.Favorites; import com.azure.resourcemanager.applicationinsights.models.LiveTokens; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbooks; import com.azure.resourcemanager.applicationinsights.models.Operations; import com.azure.resourcemanager.applicationinsights.models.ProactiveDetectionConfigurations; import com.azure.resourcemanager.applicationinsights.models.WebTestLocations; @@ -67,6 +70,7 @@ import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; @@ -107,12 +111,14 @@ public final class ApplicationInsightsManager { private WorkbookTemplates workbookTemplates; - private MyWorkbooks myWorkbooks; - private Workbooks workbooks; private LiveTokens liveTokens; + private ComponentLinkedStorageAccountsOperations componentLinkedStorageAccountsOperations; + + private DeletedWorkbooks deletedWorkbooks; + private final ApplicationInsightsManagementClient clientObject; private ApplicationInsightsManager(HttpPipeline httpPipeline, AzureProfile profile, Duration defaultPollInterval) { @@ -165,6 +171,9 @@ public static Configurable configure() { */ public static final class Configurable { private static final ClientLogger LOGGER = new ClientLogger(Configurable.class); + private static final String SDK_VERSION = "version"; + private static final Map PROPERTIES + = CoreUtils.getProperties("azure-resourcemanager-applicationinsights.properties"); private HttpClient httpClient; private HttpLogOptions httpLogOptions; @@ -272,12 +281,14 @@ public ApplicationInsightsManager authenticate(TokenCredential credential, Azure Objects.requireNonNull(credential, "'credential' cannot be null."); Objects.requireNonNull(profile, "'profile' cannot be null."); + String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); + StringBuilder userAgentBuilder = new StringBuilder(); userAgentBuilder.append("azsdk-java") .append("-") .append("com.azure.resourcemanager.applicationinsights") .append("/") - .append("1.1.0"); + .append(clientVersion); if (!Configuration.getGlobalConfiguration().get("AZURE_TELEMETRY_DISABLED", false)) { userAgentBuilder.append(" (") .append(Configuration.getGlobalConfiguration().get("java.version")) @@ -520,18 +531,6 @@ public WorkbookTemplates workbookTemplates() { return workbookTemplates; } - /** - * Gets the resource collection API of MyWorkbooks. It manages MyWorkbook. - * - * @return Resource collection API of MyWorkbooks. - */ - public MyWorkbooks myWorkbooks() { - if (this.myWorkbooks == null) { - this.myWorkbooks = new MyWorkbooksImpl(clientObject.getMyWorkbooks(), this); - } - return myWorkbooks; - } - /** * Gets the resource collection API of Workbooks. It manages Workbook. * @@ -556,6 +555,32 @@ public LiveTokens liveTokens() { return liveTokens; } + /** + * Gets the resource collection API of ComponentLinkedStorageAccountsOperations. It manages + * ComponentLinkedStorageAccounts. + * + * @return Resource collection API of ComponentLinkedStorageAccountsOperations. + */ + public ComponentLinkedStorageAccountsOperations componentLinkedStorageAccountsOperations() { + if (this.componentLinkedStorageAccountsOperations == null) { + this.componentLinkedStorageAccountsOperations = new ComponentLinkedStorageAccountsOperationsImpl( + clientObject.getComponentLinkedStorageAccountsOperations(), this); + } + return componentLinkedStorageAccountsOperations; + } + + /** + * Gets the resource collection API of DeletedWorkbooks. + * + * @return Resource collection API of DeletedWorkbooks. + */ + public DeletedWorkbooks deletedWorkbooks() { + if (this.deletedWorkbooks == null) { + this.deletedWorkbooks = new DeletedWorkbooksImpl(clientObject.getDeletedWorkbooks(), this); + } + return deletedWorkbooks; + } + /** * Gets wrapped service client ApplicationInsightsManagementClient providing direct access to the underlying * auto-generated API implementation, based on Azure REST API. diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/ApplicationInsightsManagementClient.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/ApplicationInsightsManagementClient.java index 4ef1517c09ca..e97e7ecefe1a 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/ApplicationInsightsManagementClient.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/ApplicationInsightsManagementClient.java @@ -151,13 +151,6 @@ public interface ApplicationInsightsManagementClient { */ WorkbookTemplatesClient getWorkbookTemplates(); - /** - * Gets the MyWorkbooksClient object to access its operations. - * - * @return the MyWorkbooksClient object. - */ - MyWorkbooksClient getMyWorkbooks(); - /** * Gets the WorkbooksClient object to access its operations. * @@ -171,4 +164,18 @@ public interface ApplicationInsightsManagementClient { * @return the LiveTokensClient object. */ LiveTokensClient getLiveTokens(); + + /** + * Gets the ComponentLinkedStorageAccountsOperationsClient object to access its operations. + * + * @return the ComponentLinkedStorageAccountsOperationsClient object. + */ + ComponentLinkedStorageAccountsOperationsClient getComponentLinkedStorageAccountsOperations(); + + /** + * Gets the DeletedWorkbooksClient object to access its operations. + * + * @return the DeletedWorkbooksClient object. + */ + DeletedWorkbooksClient getDeletedWorkbooks(); } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/ComponentLinkedStorageAccountsOperationsClient.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/ComponentLinkedStorageAccountsOperationsClient.java new file mode 100644 index 000000000000..063a8694a6ff --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/ComponentLinkedStorageAccountsOperationsClient.java @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.resourcemanager.applicationinsights.fluent.models.ComponentLinkedStorageAccountsInner; +import com.azure.resourcemanager.applicationinsights.models.ComponentLinkedStorageAccountsPatch; +import com.azure.resourcemanager.applicationinsights.models.StorageType; + +/** + * An instance of this class provides access to all the operations defined in + * ComponentLinkedStorageAccountsOperationsClient. + */ +public interface ComponentLinkedStorageAccountsOperationsClient { + /** + * Returns the current linked storage settings for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Application Insights component linked storage accounts along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceGroupName, String resourceName, + StorageType storageType, Context context); + + /** + * Returns the current linked storage settings for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Application Insights component linked storage accounts. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + ComponentLinkedStorageAccountsInner get(String resourceGroupName, String resourceName, StorageType storageType); + + /** + * Replace current linked storage account for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @param linkedStorageAccountsProperties Properties that need to be specified to update linked storage accounts for + * an Application Insights component. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Application Insights component linked storage accounts along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response createAndUpdateWithResponse(String resourceGroupName, + String resourceName, StorageType storageType, + ComponentLinkedStorageAccountsInner linkedStorageAccountsProperties, Context context); + + /** + * Replace current linked storage account for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @param linkedStorageAccountsProperties Properties that need to be specified to update linked storage accounts for + * an Application Insights component. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Application Insights component linked storage accounts. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + ComponentLinkedStorageAccountsInner createAndUpdate(String resourceGroupName, String resourceName, + StorageType storageType, ComponentLinkedStorageAccountsInner linkedStorageAccountsProperties); + + /** + * Update linked storage accounts for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @param linkedStorageAccountsProperties Properties that need to be specified to update a linked storage accounts + * for an Application Insights component. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Application Insights component linked storage accounts along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response updateWithResponse(String resourceGroupName, String resourceName, + StorageType storageType, ComponentLinkedStorageAccountsPatch linkedStorageAccountsProperties, Context context); + + /** + * Update linked storage accounts for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @param linkedStorageAccountsProperties Properties that need to be specified to update a linked storage accounts + * for an Application Insights component. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Application Insights component linked storage accounts. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + ComponentLinkedStorageAccountsInner update(String resourceGroupName, String resourceName, StorageType storageType, + ComponentLinkedStorageAccountsPatch linkedStorageAccountsProperties); + + /** + * Delete linked storage accounts for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response deleteWithResponse(String resourceGroupName, String resourceName, StorageType storageType, + Context context); + + /** + * Delete linked storage accounts for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void delete(String resourceGroupName, String resourceName, StorageType storageType); +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/DeletedWorkbooksClient.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/DeletedWorkbooksClient.java new file mode 100644 index 000000000000..c94029912c53 --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/DeletedWorkbooksClient.java @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.Context; +import com.azure.resourcemanager.applicationinsights.fluent.models.DeletedWorkbookInner; +import com.azure.resourcemanager.applicationinsights.models.CategoryType; +import java.util.List; + +/** + * An instance of this class provides access to all the operations defined in DeletedWorkbooksClient. + */ +public interface DeletedWorkbooksClient { + /** + * Get all recently deleted Workbooks in a specified subscription. + * + * @throws com.azure.resourcemanager.applicationinsights.models.DeletedWorkbookErrorDefinitionException thrown if + * the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return all recently deleted Workbooks in a specified subscription as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(); + + /** + * Get all recently deleted Workbooks in a specified subscription. + * + * @param category Category of workbook to return. + * @param tags Tags presents on each workbook returned. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.resourcemanager.applicationinsights.models.DeletedWorkbookErrorDefinitionException thrown if + * the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return all recently deleted Workbooks in a specified subscription as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(CategoryType category, List tags, Context context); +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/MyWorkbooksClient.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/MyWorkbooksClient.java deleted file mode 100644 index b1e8e8684a2a..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/MyWorkbooksClient.java +++ /dev/null @@ -1,212 +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.resourcemanager.applicationinsights.fluent; - -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.Response; -import com.azure.core.util.Context; -import com.azure.resourcemanager.applicationinsights.fluent.models.MyWorkbookInner; -import com.azure.resourcemanager.applicationinsights.models.CategoryType; -import java.util.List; - -/** - * An instance of this class provides access to all the operations defined in MyWorkbooksClient. - */ -public interface MyWorkbooksClient { - /** - * Get all private workbooks defined within a specified resource group and category. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param category Category of workbook to return. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.resourcemanager.applicationinsights.models.ErrorDefinitionException thrown if the request is - * rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all private workbooks defined within a specified resource group and category as paginated response with - * {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable listByResourceGroup(String resourceGroupName, CategoryType category); - - /** - * Get all private workbooks defined within a specified resource group and category. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param category Category of workbook to return. - * @param tags Tags presents on each workbook returned. - * @param sourceId Azure Resource Id that will fetch all linked workbooks. - * @param canFetchContent Flag indicating whether or not to return the full content for each applicable workbook. If - * false, only return summary content for workbooks. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.resourcemanager.applicationinsights.models.ErrorDefinitionException thrown if the request is - * rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all private workbooks defined within a specified resource group and category as paginated response with - * {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable listByResourceGroup(String resourceGroupName, CategoryType category, - List tags, String sourceId, Boolean canFetchContent, Context context); - - /** - * Get all private workbooks defined within a specified subscription and category. - * - * @param category Category of workbook to return. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.resourcemanager.applicationinsights.models.ErrorDefinitionException thrown if the request is - * rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all private workbooks defined within a specified subscription and category as paginated response with - * {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable list(CategoryType category); - - /** - * Get all private workbooks defined within a specified subscription and category. - * - * @param category Category of workbook to return. - * @param tags Tags presents on each workbook returned. - * @param canFetchContent Flag indicating whether or not to return the full content for each applicable workbook. If - * false, only return summary content for workbooks. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.resourcemanager.applicationinsights.models.ErrorDefinitionException thrown if the request is - * rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all private workbooks defined within a specified subscription and category as paginated response with - * {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable list(CategoryType category, List tags, Boolean canFetchContent, - Context context); - - /** - * Get a single private workbook by its resourceName. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.resourcemanager.applicationinsights.models.ErrorDefinitionException thrown if the request is - * rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a single private workbook by its resourceName along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - Response getByResourceGroupWithResponse(String resourceGroupName, String resourceName, - Context context); - - /** - * Get a single private workbook by its resourceName. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.resourcemanager.applicationinsights.models.ErrorDefinitionException thrown if the request is - * rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a single private workbook by its resourceName. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - MyWorkbookInner getByResourceGroup(String resourceGroupName, String resourceName); - - /** - * Delete a private workbook. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.resourcemanager.applicationinsights.models.ErrorDefinitionException thrown if the request is - * rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - Response deleteWithResponse(String resourceGroupName, String resourceName, Context context); - - /** - * Delete a private workbook. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.resourcemanager.applicationinsights.models.ErrorDefinitionException thrown if the request is - * rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - void delete(String resourceGroupName, String resourceName); - - /** - * Create a new private workbook. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @param workbookProperties Properties that need to be specified to create a new private workbook. - * @param sourceId Azure Resource Id that will fetch all linked workbooks. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.resourcemanager.applicationinsights.models.ErrorDefinitionException thrown if the request is - * rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return an Application Insights private workbook definition along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - Response createOrUpdateWithResponse(String resourceGroupName, String resourceName, - MyWorkbookInner workbookProperties, String sourceId, Context context); - - /** - * Create a new private workbook. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @param workbookProperties Properties that need to be specified to create a new private workbook. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.resourcemanager.applicationinsights.models.ErrorDefinitionException thrown if the request is - * rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return an Application Insights private workbook definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - MyWorkbookInner createOrUpdate(String resourceGroupName, String resourceName, MyWorkbookInner workbookProperties); - - /** - * Updates a private workbook that has already been added. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @param workbookProperties Properties that need to be specified to create a new private workbook. - * @param sourceId Azure Resource Id that will fetch all linked workbooks. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.resourcemanager.applicationinsights.models.ErrorDefinitionException thrown if the request is - * rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return an Application Insights private workbook definition along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - Response updateWithResponse(String resourceGroupName, String resourceName, - MyWorkbookInner workbookProperties, String sourceId, Context context); - - /** - * Updates a private workbook that has already been added. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @param workbookProperties Properties that need to be specified to create a new private workbook. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.resourcemanager.applicationinsights.models.ErrorDefinitionException thrown if the request is - * rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return an Application Insights private workbook definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - MyWorkbookInner update(String resourceGroupName, String resourceName, MyWorkbookInner workbookProperties); -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/WorkbooksClient.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/WorkbooksClient.java index 8c0b98e303f1..e9c78c0be394 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/WorkbooksClient.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/WorkbooksClient.java @@ -91,7 +91,7 @@ PagedIterable listByResourceGroup(String resourceGroupName, Categ * Get a single workbook by its resourceName. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param canFetchContent Flag indicating whether or not to return the full content for each applicable workbook. If * false, only return summary content for workbooks. * @param context The context to associate with this operation. @@ -109,7 +109,7 @@ Response getByResourceGroupWithResponse(String resourceGroupName, * Get a single workbook by its resourceName. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.applicationinsights.models.WorkbookErrorDefinitionException thrown if the * request is rejected by server. @@ -123,7 +123,7 @@ Response getByResourceGroupWithResponse(String resourceGroupName, * Delete a workbook. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.applicationinsights.models.WorkbookErrorDefinitionException thrown if the @@ -138,7 +138,7 @@ Response getByResourceGroupWithResponse(String resourceGroupName, * Delete a workbook. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.applicationinsights.models.WorkbookErrorDefinitionException thrown if the * request is rejected by server. @@ -151,7 +151,7 @@ Response getByResourceGroupWithResponse(String resourceGroupName, * Create a new workbook. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param workbookProperties Properties that need to be specified to create a new workbook. * @param sourceId Azure Resource Id that will fetch all linked workbooks. * @param context The context to associate with this operation. @@ -169,7 +169,7 @@ Response createOrUpdateWithResponse(String resourceGroupName, Str * Create a new workbook. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param workbookProperties Properties that need to be specified to create a new workbook. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.applicationinsights.models.WorkbookErrorDefinitionException thrown if the @@ -184,7 +184,7 @@ Response createOrUpdateWithResponse(String resourceGroupName, Str * Updates a workbook that has already been added. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param sourceId Azure Resource Id that will fetch all linked workbooks. * @param workbookUpdateParameters Properties that need to be specified to create a new workbook. * @param context The context to associate with this operation. @@ -202,7 +202,7 @@ Response updateWithResponse(String resourceGroupName, String reso * Updates a workbook that has already been added. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.applicationinsights.models.WorkbookErrorDefinitionException thrown if the * request is rejected by server. @@ -216,7 +216,7 @@ Response updateWithResponse(String resourceGroupName, String reso * Get the revisions for the workbook defined by its resourceName. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.applicationinsights.models.WorkbookErrorDefinitionException thrown if the * request is rejected by server. @@ -231,7 +231,7 @@ Response updateWithResponse(String resourceGroupName, String reso * Get the revisions for the workbook defined by its resourceName. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.applicationinsights.models.WorkbookErrorDefinitionException thrown if the @@ -247,7 +247,7 @@ Response updateWithResponse(String resourceGroupName, String reso * Get a single workbook revision defined by its revisionId. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param revisionId The id of the workbook's revision. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -264,7 +264,7 @@ Response revisionGetWithResponse(String resourceGroupName, String * Get a single workbook revision defined by its revisionId. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param revisionId The id of the workbook's revision. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.applicationinsights.models.WorkbookErrorDefinitionException thrown if the diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/models/ApplicationInsightsComponentProactiveDetectionConfigurationInner.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/models/ApplicationInsightsComponentProactiveDetectionConfigurationInner.java index 56fde977cf2d..529c4eadb4ec 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/models/ApplicationInsightsComponentProactiveDetectionConfigurationInner.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/models/ApplicationInsightsComponentProactiveDetectionConfigurationInner.java @@ -200,12 +200,12 @@ public void validate() { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeStringField("Name", this.name); - jsonWriter.writeBooleanField("Enabled", this.enabled); - jsonWriter.writeBooleanField("SendEmailsToSubscriptionOwners", this.sendEmailsToSubscriptionOwners); - jsonWriter.writeArrayField("CustomEmails", this.customEmails, (writer, element) -> writer.writeString(element)); - jsonWriter.writeStringField("LastUpdatedTime", this.lastUpdatedTime); - jsonWriter.writeJsonField("RuleDefinitions", this.ruleDefinitions); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeBooleanField("enabled", this.enabled); + jsonWriter.writeBooleanField("sendEmailsToSubscriptionOwners", this.sendEmailsToSubscriptionOwners); + jsonWriter.writeArrayField("customEmails", this.customEmails, (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("lastUpdatedTime", this.lastUpdatedTime); + jsonWriter.writeJsonField("ruleDefinitions", this.ruleDefinitions); return jsonWriter.writeEndObject(); } @@ -227,23 +227,23 @@ public static ApplicationInsightsComponentProactiveDetectionConfigurationInner f String fieldName = reader.getFieldName(); reader.nextToken(); - if ("Name".equals(fieldName)) { + if ("name".equals(fieldName)) { deserializedApplicationInsightsComponentProactiveDetectionConfigurationInner.name = reader.getString(); - } else if ("Enabled".equals(fieldName)) { + } else if ("enabled".equals(fieldName)) { deserializedApplicationInsightsComponentProactiveDetectionConfigurationInner.enabled = reader.getNullable(JsonReader::getBoolean); - } else if ("SendEmailsToSubscriptionOwners".equals(fieldName)) { + } else if ("sendEmailsToSubscriptionOwners".equals(fieldName)) { deserializedApplicationInsightsComponentProactiveDetectionConfigurationInner.sendEmailsToSubscriptionOwners = reader.getNullable(JsonReader::getBoolean); - } else if ("CustomEmails".equals(fieldName)) { + } else if ("customEmails".equals(fieldName)) { List customEmails = reader.readArray(reader1 -> reader1.getString()); deserializedApplicationInsightsComponentProactiveDetectionConfigurationInner.customEmails = customEmails; - } else if ("LastUpdatedTime".equals(fieldName)) { + } else if ("lastUpdatedTime".equals(fieldName)) { deserializedApplicationInsightsComponentProactiveDetectionConfigurationInner.lastUpdatedTime = reader.getString(); - } else if ("RuleDefinitions".equals(fieldName)) { + } else if ("ruleDefinitions".equals(fieldName)) { deserializedApplicationInsightsComponentProactiveDetectionConfigurationInner.ruleDefinitions = ApplicationInsightsComponentProactiveDetectionConfigurationRuleDefinitions.fromJson(reader); } else { diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/models/ComponentLinkedStorageAccountsInner.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/models/ComponentLinkedStorageAccountsInner.java new file mode 100644 index 000000000000..21645a9765a6 --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/models/ComponentLinkedStorageAccountsInner.java @@ -0,0 +1,162 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * An Application Insights component linked storage accounts. + */ +@Fluent +public final class ComponentLinkedStorageAccountsInner extends ProxyResource { + /* + * The properties of the linked storage accounts. + */ + private LinkedStorageAccountsProperties innerProperties; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of ComponentLinkedStorageAccountsInner class. + */ + public ComponentLinkedStorageAccountsInner() { + } + + /** + * Get the innerProperties property: The properties of the linked storage accounts. + * + * @return the innerProperties value. + */ + private LinkedStorageAccountsProperties innerProperties() { + return this.innerProperties; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Get the linkedStorageAccount property: Linked storage account resource ID. + * + * @return the linkedStorageAccount value. + */ + public String linkedStorageAccount() { + return this.innerProperties() == null ? null : this.innerProperties().linkedStorageAccount(); + } + + /** + * Set the linkedStorageAccount property: Linked storage account resource ID. + * + * @param linkedStorageAccount the linkedStorageAccount value to set. + * @return the ComponentLinkedStorageAccountsInner object itself. + */ + public ComponentLinkedStorageAccountsInner withLinkedStorageAccount(String linkedStorageAccount) { + if (this.innerProperties() == null) { + this.innerProperties = new LinkedStorageAccountsProperties(); + } + this.innerProperties().withLinkedStorageAccount(linkedStorageAccount); + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (innerProperties() != null) { + innerProperties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.innerProperties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ComponentLinkedStorageAccountsInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ComponentLinkedStorageAccountsInner 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 ComponentLinkedStorageAccountsInner. + */ + public static ComponentLinkedStorageAccountsInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ComponentLinkedStorageAccountsInner deserializedComponentLinkedStorageAccountsInner + = new ComponentLinkedStorageAccountsInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedComponentLinkedStorageAccountsInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedComponentLinkedStorageAccountsInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedComponentLinkedStorageAccountsInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedComponentLinkedStorageAccountsInner.innerProperties + = LinkedStorageAccountsProperties.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedComponentLinkedStorageAccountsInner; + }); + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/models/DeletedWorkbookInner.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/models/DeletedWorkbookInner.java new file mode 100644 index 000000000000..09eb5417b8ba --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/models/DeletedWorkbookInner.java @@ -0,0 +1,425 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.applicationinsights.models.DeletedWorkbookResource; +import com.azure.resourcemanager.applicationinsights.models.WorkbookSharedTypeKind; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; + +/** + * A workbook definition. + */ +@Fluent +public final class DeletedWorkbookInner extends DeletedWorkbookResource { + /* + * Metadata describing a workbook for an Azure resource. + */ + private DeletedWorkbookProperties innerProperties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of DeletedWorkbookInner class. + */ + public DeletedWorkbookInner() { + } + + /** + * Get the innerProperties property: Metadata describing a workbook for an Azure resource. + * + * @return the innerProperties value. + */ + private DeletedWorkbookProperties innerProperties() { + return this.innerProperties; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + @Override + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * {@inheritDoc} + */ + @Override + public DeletedWorkbookInner withKind(WorkbookSharedTypeKind kind) { + super.withKind(kind); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public DeletedWorkbookInner withEtag(String etag) { + super.withEtag(etag); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public DeletedWorkbookInner withLocation(String location) { + super.withLocation(location); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public DeletedWorkbookInner withTags(Map tags) { + super.withTags(tags); + return this; + } + + /** + * Get the displayName property: The user-defined name (display name) of the workbook. + * + * @return the displayName value. + */ + public String displayName() { + return this.innerProperties() == null ? null : this.innerProperties().displayName(); + } + + /** + * Set the displayName property: The user-defined name (display name) of the workbook. + * + * @param displayName the displayName value to set. + * @return the DeletedWorkbookInner object itself. + */ + public DeletedWorkbookInner withDisplayName(String displayName) { + if (this.innerProperties() == null) { + this.innerProperties = new DeletedWorkbookProperties(); + } + this.innerProperties().withDisplayName(displayName); + return this; + } + + /** + * Get the serializedData property: Configuration of this particular workbook. Configuration data is a string + * containing valid JSON. + * + * @return the serializedData value. + */ + public String serializedData() { + return this.innerProperties() == null ? null : this.innerProperties().serializedData(); + } + + /** + * Set the serializedData property: Configuration of this particular workbook. Configuration data is a string + * containing valid JSON. + * + * @param serializedData the serializedData value to set. + * @return the DeletedWorkbookInner object itself. + */ + public DeletedWorkbookInner withSerializedData(String serializedData) { + if (this.innerProperties() == null) { + this.innerProperties = new DeletedWorkbookProperties(); + } + this.innerProperties().withSerializedData(serializedData); + return this; + } + + /** + * Get the version property: Workbook schema version format, like 'Notebook/1.0', which should match the workbook in + * serializedData. + * + * @return the version value. + */ + public String version() { + return this.innerProperties() == null ? null : this.innerProperties().version(); + } + + /** + * Set the version property: Workbook schema version format, like 'Notebook/1.0', which should match the workbook in + * serializedData. + * + * @param version the version value to set. + * @return the DeletedWorkbookInner object itself. + */ + public DeletedWorkbookInner withVersion(String version) { + if (this.innerProperties() == null) { + this.innerProperties = new DeletedWorkbookProperties(); + } + this.innerProperties().withVersion(version); + return this; + } + + /** + * Get the timeModified property: Date and time in UTC of the last modification that was made to this workbook + * definition. + * + * @return the timeModified value. + */ + public OffsetDateTime timeModified() { + return this.innerProperties() == null ? null : this.innerProperties().timeModified(); + } + + /** + * Get the category property: Workbook category, as defined by the user at creation time. + * + * @return the category value. + */ + public String category() { + return this.innerProperties() == null ? null : this.innerProperties().category(); + } + + /** + * Set the category property: Workbook category, as defined by the user at creation time. + * + * @param category the category value to set. + * @return the DeletedWorkbookInner object itself. + */ + public DeletedWorkbookInner withCategory(String category) { + if (this.innerProperties() == null) { + this.innerProperties = new DeletedWorkbookProperties(); + } + this.innerProperties().withCategory(category); + return this; + } + + /** + * Get the tags property: Being deprecated, please use the other tags field. + * + * @return the tags value. + */ + public List tagsPropertiesTags() { + return this.innerProperties() == null ? null : this.innerProperties().tags(); + } + + /** + * Set the tags property: Being deprecated, please use the other tags field. + * + * @param tags the tags value to set. + * @return the DeletedWorkbookInner object itself. + */ + public DeletedWorkbookInner withTagsPropertiesTags(List tags) { + if (this.innerProperties() == null) { + this.innerProperties = new DeletedWorkbookProperties(); + } + this.innerProperties().withTags(tags); + return this; + } + + /** + * Get the userId property: Unique user id of the specific user that owns this workbook. + * + * @return the userId value. + */ + public String userId() { + return this.innerProperties() == null ? null : this.innerProperties().userId(); + } + + /** + * Get the sourceId property: ResourceId for a source resource. + * + * @return the sourceId value. + */ + public String sourceId() { + return this.innerProperties() == null ? null : this.innerProperties().sourceId(); + } + + /** + * Set the sourceId property: ResourceId for a source resource. + * + * @param sourceId the sourceId value to set. + * @return the DeletedWorkbookInner object itself. + */ + public DeletedWorkbookInner withSourceId(String sourceId) { + if (this.innerProperties() == null) { + this.innerProperties = new DeletedWorkbookProperties(); + } + this.innerProperties().withSourceId(sourceId); + return this; + } + + /** + * Get the storageUri property: The resourceId to the storage account when bring your own storage is used. + * + * @return the storageUri value. + */ + public String storageUri() { + return this.innerProperties() == null ? null : this.innerProperties().storageUri(); + } + + /** + * Set the storageUri property: The resourceId to the storage account when bring your own storage is used. + * + * @param storageUri the storageUri value to set. + * @return the DeletedWorkbookInner object itself. + */ + public DeletedWorkbookInner withStorageUri(String storageUri) { + if (this.innerProperties() == null) { + this.innerProperties = new DeletedWorkbookProperties(); + } + this.innerProperties().withStorageUri(storageUri); + return this; + } + + /** + * Get the description property: The description of the workbook. + * + * @return the description value. + */ + public String description() { + return this.innerProperties() == null ? null : this.innerProperties().description(); + } + + /** + * Set the description property: The description of the workbook. + * + * @param description the description value to set. + * @return the DeletedWorkbookInner object itself. + */ + public DeletedWorkbookInner withDescription(String description) { + if (this.innerProperties() == null) { + this.innerProperties = new DeletedWorkbookProperties(); + } + this.innerProperties().withDescription(description); + return this; + } + + /** + * Get the revision property: The unique revision id for this workbook definition. + * + * @return the revision value. + */ + public String revision() { + return this.innerProperties() == null ? null : this.innerProperties().revision(); + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + @Override + public void validate() { + if (innerProperties() != null) { + innerProperties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("location", location()); + jsonWriter.writeMapField("tags", tags(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("kind", kind() == null ? null : kind().toString()); + jsonWriter.writeStringField("etag", etag()); + jsonWriter.writeJsonField("properties", this.innerProperties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of DeletedWorkbookInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of DeletedWorkbookInner 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 DeletedWorkbookInner. + */ + public static DeletedWorkbookInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + DeletedWorkbookInner deserializedDeletedWorkbookInner = new DeletedWorkbookInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedDeletedWorkbookInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedDeletedWorkbookInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedDeletedWorkbookInner.type = reader.getString(); + } else if ("location".equals(fieldName)) { + deserializedDeletedWorkbookInner.withLocation(reader.getString()); + } else if ("tags".equals(fieldName)) { + Map tags = reader.readMap(reader1 -> reader1.getString()); + deserializedDeletedWorkbookInner.withTags(tags); + } else if ("kind".equals(fieldName)) { + deserializedDeletedWorkbookInner.withKind(WorkbookSharedTypeKind.fromString(reader.getString())); + } else if ("etag".equals(fieldName)) { + deserializedDeletedWorkbookInner.withEtag(reader.getString()); + } else if ("systemData".equals(fieldName)) { + deserializedDeletedWorkbookInner.systemData = SystemData.fromJson(reader); + } else if ("properties".equals(fieldName)) { + deserializedDeletedWorkbookInner.innerProperties = DeletedWorkbookProperties.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedDeletedWorkbookInner; + }); + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/models/DeletedWorkbookProperties.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/models/DeletedWorkbookProperties.java new file mode 100644 index 000000000000..fa4f0aface5b --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/models/DeletedWorkbookProperties.java @@ -0,0 +1,366 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; +import com.azure.core.util.logging.ClientLogger; +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.OffsetDateTime; +import java.util.List; + +/** + * Properties that contain a workbook. + */ +@Fluent +public final class DeletedWorkbookProperties implements JsonSerializable { + /* + * The user-defined name (display name) of the workbook. + */ + private String displayName; + + /* + * Configuration of this particular workbook. Configuration data is a string containing valid JSON + */ + private String serializedData; + + /* + * Workbook schema version format, like 'Notebook/1.0', which should match the workbook in serializedData + */ + private String version; + + /* + * Date and time in UTC of the last modification that was made to this workbook definition. + */ + private OffsetDateTime timeModified; + + /* + * Workbook category, as defined by the user at creation time. + */ + private String category; + + /* + * Being deprecated, please use the other tags field + */ + private List tags; + + /* + * Unique user id of the specific user that owns this workbook. + */ + private String userId; + + /* + * ResourceId for a source resource. + */ + private String sourceId; + + /* + * The resourceId to the storage account when bring your own storage is used + */ + private String storageUri; + + /* + * The description of the workbook. + */ + private String description; + + /* + * The unique revision id for this workbook definition + */ + private String revision; + + /** + * Creates an instance of DeletedWorkbookProperties class. + */ + public DeletedWorkbookProperties() { + } + + /** + * Get the displayName property: The user-defined name (display name) of the workbook. + * + * @return the displayName value. + */ + public String displayName() { + return this.displayName; + } + + /** + * Set the displayName property: The user-defined name (display name) of the workbook. + * + * @param displayName the displayName value to set. + * @return the DeletedWorkbookProperties object itself. + */ + public DeletedWorkbookProperties withDisplayName(String displayName) { + this.displayName = displayName; + return this; + } + + /** + * Get the serializedData property: Configuration of this particular workbook. Configuration data is a string + * containing valid JSON. + * + * @return the serializedData value. + */ + public String serializedData() { + return this.serializedData; + } + + /** + * Set the serializedData property: Configuration of this particular workbook. Configuration data is a string + * containing valid JSON. + * + * @param serializedData the serializedData value to set. + * @return the DeletedWorkbookProperties object itself. + */ + public DeletedWorkbookProperties withSerializedData(String serializedData) { + this.serializedData = serializedData; + return this; + } + + /** + * Get the version property: Workbook schema version format, like 'Notebook/1.0', which should match the workbook in + * serializedData. + * + * @return the version value. + */ + public String version() { + return this.version; + } + + /** + * Set the version property: Workbook schema version format, like 'Notebook/1.0', which should match the workbook in + * serializedData. + * + * @param version the version value to set. + * @return the DeletedWorkbookProperties object itself. + */ + public DeletedWorkbookProperties withVersion(String version) { + this.version = version; + return this; + } + + /** + * Get the timeModified property: Date and time in UTC of the last modification that was made to this workbook + * definition. + * + * @return the timeModified value. + */ + public OffsetDateTime timeModified() { + return this.timeModified; + } + + /** + * Get the category property: Workbook category, as defined by the user at creation time. + * + * @return the category value. + */ + public String category() { + return this.category; + } + + /** + * Set the category property: Workbook category, as defined by the user at creation time. + * + * @param category the category value to set. + * @return the DeletedWorkbookProperties object itself. + */ + public DeletedWorkbookProperties withCategory(String category) { + this.category = category; + return this; + } + + /** + * Get the tags property: Being deprecated, please use the other tags field. + * + * @return the tags value. + */ + public List tags() { + return this.tags; + } + + /** + * Set the tags property: Being deprecated, please use the other tags field. + * + * @param tags the tags value to set. + * @return the DeletedWorkbookProperties object itself. + */ + public DeletedWorkbookProperties withTags(List tags) { + this.tags = tags; + return this; + } + + /** + * Get the userId property: Unique user id of the specific user that owns this workbook. + * + * @return the userId value. + */ + public String userId() { + return this.userId; + } + + /** + * Get the sourceId property: ResourceId for a source resource. + * + * @return the sourceId value. + */ + public String sourceId() { + return this.sourceId; + } + + /** + * Set the sourceId property: ResourceId for a source resource. + * + * @param sourceId the sourceId value to set. + * @return the DeletedWorkbookProperties object itself. + */ + public DeletedWorkbookProperties withSourceId(String sourceId) { + this.sourceId = sourceId; + return this; + } + + /** + * Get the storageUri property: The resourceId to the storage account when bring your own storage is used. + * + * @return the storageUri value. + */ + public String storageUri() { + return this.storageUri; + } + + /** + * Set the storageUri property: The resourceId to the storage account when bring your own storage is used. + * + * @param storageUri the storageUri value to set. + * @return the DeletedWorkbookProperties object itself. + */ + public DeletedWorkbookProperties withStorageUri(String storageUri) { + this.storageUri = storageUri; + return this; + } + + /** + * Get the description property: The description of the workbook. + * + * @return the description value. + */ + public String description() { + return this.description; + } + + /** + * Set the description property: The description of the workbook. + * + * @param description the description value to set. + * @return the DeletedWorkbookProperties object itself. + */ + public DeletedWorkbookProperties withDescription(String description) { + this.description = description; + return this; + } + + /** + * Get the revision property: The unique revision id for this workbook definition. + * + * @return the revision value. + */ + public String revision() { + return this.revision; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (displayName() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property displayName in model DeletedWorkbookProperties")); + } + if (serializedData() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property serializedData in model DeletedWorkbookProperties")); + } + if (category() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property category in model DeletedWorkbookProperties")); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(DeletedWorkbookProperties.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("displayName", this.displayName); + jsonWriter.writeStringField("serializedData", this.serializedData); + jsonWriter.writeStringField("category", this.category); + jsonWriter.writeStringField("version", this.version); + jsonWriter.writeArrayField("tags", this.tags, (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("sourceId", this.sourceId); + jsonWriter.writeStringField("storageUri", this.storageUri); + jsonWriter.writeStringField("description", this.description); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of DeletedWorkbookProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of DeletedWorkbookProperties 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 DeletedWorkbookProperties. + */ + public static DeletedWorkbookProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + DeletedWorkbookProperties deserializedDeletedWorkbookProperties = new DeletedWorkbookProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("displayName".equals(fieldName)) { + deserializedDeletedWorkbookProperties.displayName = reader.getString(); + } else if ("serializedData".equals(fieldName)) { + deserializedDeletedWorkbookProperties.serializedData = reader.getString(); + } else if ("category".equals(fieldName)) { + deserializedDeletedWorkbookProperties.category = reader.getString(); + } else if ("version".equals(fieldName)) { + deserializedDeletedWorkbookProperties.version = reader.getString(); + } else if ("timeModified".equals(fieldName)) { + deserializedDeletedWorkbookProperties.timeModified = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("tags".equals(fieldName)) { + List tags = reader.readArray(reader1 -> reader1.getString()); + deserializedDeletedWorkbookProperties.tags = tags; + } else if ("userId".equals(fieldName)) { + deserializedDeletedWorkbookProperties.userId = reader.getString(); + } else if ("sourceId".equals(fieldName)) { + deserializedDeletedWorkbookProperties.sourceId = reader.getString(); + } else if ("storageUri".equals(fieldName)) { + deserializedDeletedWorkbookProperties.storageUri = reader.getString(); + } else if ("description".equals(fieldName)) { + deserializedDeletedWorkbookProperties.description = reader.getString(); + } else if ("revision".equals(fieldName)) { + deserializedDeletedWorkbookProperties.revision = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedDeletedWorkbookProperties; + }); + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/models/LinkedStorageAccountsProperties.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/models/LinkedStorageAccountsProperties.java new file mode 100644 index 000000000000..7bed63396e80 --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/models/LinkedStorageAccountsProperties.java @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.fluent.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; + +/** + * An Application Insights component linked storage account. + */ +@Fluent +public final class LinkedStorageAccountsProperties implements JsonSerializable { + /* + * Linked storage account resource ID + */ + private String linkedStorageAccount; + + /** + * Creates an instance of LinkedStorageAccountsProperties class. + */ + public LinkedStorageAccountsProperties() { + } + + /** + * Get the linkedStorageAccount property: Linked storage account resource ID. + * + * @return the linkedStorageAccount value. + */ + public String linkedStorageAccount() { + return this.linkedStorageAccount; + } + + /** + * Set the linkedStorageAccount property: Linked storage account resource ID. + * + * @param linkedStorageAccount the linkedStorageAccount value to set. + * @return the LinkedStorageAccountsProperties object itself. + */ + public LinkedStorageAccountsProperties withLinkedStorageAccount(String linkedStorageAccount) { + this.linkedStorageAccount = linkedStorageAccount; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("linkedStorageAccount", this.linkedStorageAccount); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of LinkedStorageAccountsProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of LinkedStorageAccountsProperties 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 LinkedStorageAccountsProperties. + */ + public static LinkedStorageAccountsProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + LinkedStorageAccountsProperties deserializedLinkedStorageAccountsProperties + = new LinkedStorageAccountsProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("linkedStorageAccount".equals(fieldName)) { + deserializedLinkedStorageAccountsProperties.linkedStorageAccount = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedLinkedStorageAccountsProperties; + }); + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/models/MyWorkbookInner.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/models/MyWorkbookInner.java deleted file mode 100644 index f5a7c6494f27..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/models/MyWorkbookInner.java +++ /dev/null @@ -1,409 +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.resourcemanager.applicationinsights.fluent.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.management.SystemData; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.resourcemanager.applicationinsights.models.Kind; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbookManagedIdentity; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbookResource; -import java.io.IOException; -import java.util.List; -import java.util.Map; - -/** - * An Application Insights private workbook definition. - */ -@Fluent -public final class MyWorkbookInner extends MyWorkbookResource { - /* - * The kind of workbook. Choices are user and shared. - */ - private Kind kind; - - /* - * Metadata describing a workbook for an Azure resource. - */ - private MyWorkbookProperties innerProperties; - - /* - * Metadata pertaining to creation and last modification of the resource. - */ - private SystemData systemData; - - /** - * Creates an instance of MyWorkbookInner class. - */ - public MyWorkbookInner() { - } - - /** - * Get the kind property: The kind of workbook. Choices are user and shared. - * - * @return the kind value. - */ - public Kind kind() { - return this.kind; - } - - /** - * Set the kind property: The kind of workbook. Choices are user and shared. - * - * @param kind the kind value to set. - * @return the MyWorkbookInner object itself. - */ - public MyWorkbookInner withKind(Kind kind) { - this.kind = kind; - return this; - } - - /** - * Get the innerProperties property: Metadata describing a workbook for an Azure resource. - * - * @return the innerProperties value. - */ - private MyWorkbookProperties innerProperties() { - return this.innerProperties; - } - - /** - * Get the systemData property: Metadata pertaining to creation and last modification of the resource. - * - * @return the systemData value. - */ - public SystemData systemData() { - return this.systemData; - } - - /** - * {@inheritDoc} - */ - @Override - public MyWorkbookInner withIdentity(MyWorkbookManagedIdentity identity) { - super.withIdentity(identity); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public MyWorkbookInner withId(String id) { - super.withId(id); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public MyWorkbookInner withName(String name) { - super.withName(name); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public MyWorkbookInner withType(String type) { - super.withType(type); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public MyWorkbookInner withEtag(Map etag) { - super.withEtag(etag); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public MyWorkbookInner withLocation(String location) { - super.withLocation(location); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public MyWorkbookInner withTags(Map tags) { - super.withTags(tags); - return this; - } - - /** - * Get the displayName property: The user-defined name of the private workbook. - * - * @return the displayName value. - */ - public String displayName() { - return this.innerProperties() == null ? null : this.innerProperties().displayName(); - } - - /** - * Set the displayName property: The user-defined name of the private workbook. - * - * @param displayName the displayName value to set. - * @return the MyWorkbookInner object itself. - */ - public MyWorkbookInner withDisplayName(String displayName) { - if (this.innerProperties() == null) { - this.innerProperties = new MyWorkbookProperties(); - } - this.innerProperties().withDisplayName(displayName); - return this; - } - - /** - * Get the serializedData property: Configuration of this particular private workbook. Configuration data is a - * string containing valid JSON. - * - * @return the serializedData value. - */ - public String serializedData() { - return this.innerProperties() == null ? null : this.innerProperties().serializedData(); - } - - /** - * Set the serializedData property: Configuration of this particular private workbook. Configuration data is a - * string containing valid JSON. - * - * @param serializedData the serializedData value to set. - * @return the MyWorkbookInner object itself. - */ - public MyWorkbookInner withSerializedData(String serializedData) { - if (this.innerProperties() == null) { - this.innerProperties = new MyWorkbookProperties(); - } - this.innerProperties().withSerializedData(serializedData); - return this; - } - - /** - * Get the version property: This instance's version of the data model. This can change as new features are added - * that can be marked private workbook. - * - * @return the version value. - */ - public String version() { - return this.innerProperties() == null ? null : this.innerProperties().version(); - } - - /** - * Set the version property: This instance's version of the data model. This can change as new features are added - * that can be marked private workbook. - * - * @param version the version value to set. - * @return the MyWorkbookInner object itself. - */ - public MyWorkbookInner withVersion(String version) { - if (this.innerProperties() == null) { - this.innerProperties = new MyWorkbookProperties(); - } - this.innerProperties().withVersion(version); - return this; - } - - /** - * Get the timeModified property: Date and time in UTC of the last modification that was made to this private - * workbook definition. - * - * @return the timeModified value. - */ - public String timeModified() { - return this.innerProperties() == null ? null : this.innerProperties().timeModified(); - } - - /** - * Get the category property: Workbook category, as defined by the user at creation time. - * - * @return the category value. - */ - public String category() { - return this.innerProperties() == null ? null : this.innerProperties().category(); - } - - /** - * Set the category property: Workbook category, as defined by the user at creation time. - * - * @param category the category value to set. - * @return the MyWorkbookInner object itself. - */ - public MyWorkbookInner withCategory(String category) { - if (this.innerProperties() == null) { - this.innerProperties = new MyWorkbookProperties(); - } - this.innerProperties().withCategory(category); - return this; - } - - /** - * Get the tags property: A list of 0 or more tags that are associated with this private workbook definition. - * - * @return the tags value. - */ - public List tagsPropertiesTags() { - return this.innerProperties() == null ? null : this.innerProperties().tags(); - } - - /** - * Set the tags property: A list of 0 or more tags that are associated with this private workbook definition. - * - * @param tags the tags value to set. - * @return the MyWorkbookInner object itself. - */ - public MyWorkbookInner withTagsPropertiesTags(List tags) { - if (this.innerProperties() == null) { - this.innerProperties = new MyWorkbookProperties(); - } - this.innerProperties().withTags(tags); - return this; - } - - /** - * Get the userId property: Unique user id of the specific user that owns this private workbook. - * - * @return the userId value. - */ - public String userId() { - return this.innerProperties() == null ? null : this.innerProperties().userId(); - } - - /** - * Get the sourceId property: Optional resourceId for a source resource. - * - * @return the sourceId value. - */ - public String sourceId() { - return this.innerProperties() == null ? null : this.innerProperties().sourceId(); - } - - /** - * Set the sourceId property: Optional resourceId for a source resource. - * - * @param sourceId the sourceId value to set. - * @return the MyWorkbookInner object itself. - */ - public MyWorkbookInner withSourceId(String sourceId) { - if (this.innerProperties() == null) { - this.innerProperties = new MyWorkbookProperties(); - } - this.innerProperties().withSourceId(sourceId); - return this; - } - - /** - * Get the storageUri property: BYOS Storage Account URI. - * - * @return the storageUri value. - */ - public String storageUri() { - return this.innerProperties() == null ? null : this.innerProperties().storageUri(); - } - - /** - * Set the storageUri property: BYOS Storage Account URI. - * - * @param storageUri the storageUri value to set. - * @return the MyWorkbookInner object itself. - */ - public MyWorkbookInner withStorageUri(String storageUri) { - if (this.innerProperties() == null) { - this.innerProperties = new MyWorkbookProperties(); - } - this.innerProperties().withStorageUri(storageUri); - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - @Override - public void validate() { - if (innerProperties() != null) { - innerProperties().validate(); - } - if (identity() != null) { - identity().validate(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("location", location()); - jsonWriter.writeMapField("tags", tags(), (writer, element) -> writer.writeString(element)); - jsonWriter.writeJsonField("identity", identity()); - jsonWriter.writeStringField("id", id()); - jsonWriter.writeStringField("name", name()); - jsonWriter.writeStringField("type", type()); - jsonWriter.writeMapField("etag", etag(), (writer, element) -> writer.writeString(element)); - jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString()); - jsonWriter.writeJsonField("properties", this.innerProperties); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of MyWorkbookInner from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of MyWorkbookInner 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 MyWorkbookInner. - */ - public static MyWorkbookInner fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - MyWorkbookInner deserializedMyWorkbookInner = new MyWorkbookInner(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("location".equals(fieldName)) { - deserializedMyWorkbookInner.withLocation(reader.getString()); - } else if ("tags".equals(fieldName)) { - Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedMyWorkbookInner.withTags(tags); - } else if ("identity".equals(fieldName)) { - deserializedMyWorkbookInner.withIdentity(MyWorkbookManagedIdentity.fromJson(reader)); - } else if ("id".equals(fieldName)) { - deserializedMyWorkbookInner.withId(reader.getString()); - } else if ("name".equals(fieldName)) { - deserializedMyWorkbookInner.withName(reader.getString()); - } else if ("type".equals(fieldName)) { - deserializedMyWorkbookInner.withType(reader.getString()); - } else if ("etag".equals(fieldName)) { - Map etag = reader.readMap(reader1 -> reader1.getString()); - deserializedMyWorkbookInner.withEtag(etag); - } else if ("kind".equals(fieldName)) { - deserializedMyWorkbookInner.kind = Kind.fromString(reader.getString()); - } else if ("properties".equals(fieldName)) { - deserializedMyWorkbookInner.innerProperties = MyWorkbookProperties.fromJson(reader); - } else if ("systemData".equals(fieldName)) { - deserializedMyWorkbookInner.systemData = SystemData.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedMyWorkbookInner; - }); - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/models/MyWorkbookProperties.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/models/MyWorkbookProperties.java deleted file mode 100644 index 344c82805f14..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/fluent/models/MyWorkbookProperties.java +++ /dev/null @@ -1,319 +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.resourcemanager.applicationinsights.fluent.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.util.logging.ClientLogger; -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; - -/** - * Properties that contain a private workbook. - */ -@Fluent -public final class MyWorkbookProperties implements JsonSerializable { - /* - * The user-defined name of the private workbook. - */ - private String displayName; - - /* - * Configuration of this particular private workbook. Configuration data is a string containing valid JSON - */ - private String serializedData; - - /* - * This instance's version of the data model. This can change as new features are added that can be marked private - * workbook. - */ - private String version; - - /* - * Date and time in UTC of the last modification that was made to this private workbook definition. - */ - private String timeModified; - - /* - * Workbook category, as defined by the user at creation time. - */ - private String category; - - /* - * A list of 0 or more tags that are associated with this private workbook definition - */ - private List tags; - - /* - * Unique user id of the specific user that owns this private workbook. - */ - private String userId; - - /* - * Optional resourceId for a source resource. - */ - private String sourceId; - - /* - * BYOS Storage Account URI - */ - private String storageUri; - - /** - * Creates an instance of MyWorkbookProperties class. - */ - public MyWorkbookProperties() { - } - - /** - * Get the displayName property: The user-defined name of the private workbook. - * - * @return the displayName value. - */ - public String displayName() { - return this.displayName; - } - - /** - * Set the displayName property: The user-defined name of the private workbook. - * - * @param displayName the displayName value to set. - * @return the MyWorkbookProperties object itself. - */ - public MyWorkbookProperties withDisplayName(String displayName) { - this.displayName = displayName; - return this; - } - - /** - * Get the serializedData property: Configuration of this particular private workbook. Configuration data is a - * string containing valid JSON. - * - * @return the serializedData value. - */ - public String serializedData() { - return this.serializedData; - } - - /** - * Set the serializedData property: Configuration of this particular private workbook. Configuration data is a - * string containing valid JSON. - * - * @param serializedData the serializedData value to set. - * @return the MyWorkbookProperties object itself. - */ - public MyWorkbookProperties withSerializedData(String serializedData) { - this.serializedData = serializedData; - return this; - } - - /** - * Get the version property: This instance's version of the data model. This can change as new features are added - * that can be marked private workbook. - * - * @return the version value. - */ - public String version() { - return this.version; - } - - /** - * Set the version property: This instance's version of the data model. This can change as new features are added - * that can be marked private workbook. - * - * @param version the version value to set. - * @return the MyWorkbookProperties object itself. - */ - public MyWorkbookProperties withVersion(String version) { - this.version = version; - return this; - } - - /** - * Get the timeModified property: Date and time in UTC of the last modification that was made to this private - * workbook definition. - * - * @return the timeModified value. - */ - public String timeModified() { - return this.timeModified; - } - - /** - * Get the category property: Workbook category, as defined by the user at creation time. - * - * @return the category value. - */ - public String category() { - return this.category; - } - - /** - * Set the category property: Workbook category, as defined by the user at creation time. - * - * @param category the category value to set. - * @return the MyWorkbookProperties object itself. - */ - public MyWorkbookProperties withCategory(String category) { - this.category = category; - return this; - } - - /** - * Get the tags property: A list of 0 or more tags that are associated with this private workbook definition. - * - * @return the tags value. - */ - public List tags() { - return this.tags; - } - - /** - * Set the tags property: A list of 0 or more tags that are associated with this private workbook definition. - * - * @param tags the tags value to set. - * @return the MyWorkbookProperties object itself. - */ - public MyWorkbookProperties withTags(List tags) { - this.tags = tags; - return this; - } - - /** - * Get the userId property: Unique user id of the specific user that owns this private workbook. - * - * @return the userId value. - */ - public String userId() { - return this.userId; - } - - /** - * Get the sourceId property: Optional resourceId for a source resource. - * - * @return the sourceId value. - */ - public String sourceId() { - return this.sourceId; - } - - /** - * Set the sourceId property: Optional resourceId for a source resource. - * - * @param sourceId the sourceId value to set. - * @return the MyWorkbookProperties object itself. - */ - public MyWorkbookProperties withSourceId(String sourceId) { - this.sourceId = sourceId; - return this; - } - - /** - * Get the storageUri property: BYOS Storage Account URI. - * - * @return the storageUri value. - */ - public String storageUri() { - return this.storageUri; - } - - /** - * Set the storageUri property: BYOS Storage Account URI. - * - * @param storageUri the storageUri value to set. - * @return the MyWorkbookProperties object itself. - */ - public MyWorkbookProperties withStorageUri(String storageUri) { - this.storageUri = storageUri; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (displayName() == null) { - throw LOGGER.atError() - .log(new IllegalArgumentException( - "Missing required property displayName in model MyWorkbookProperties")); - } - if (serializedData() == null) { - throw LOGGER.atError() - .log(new IllegalArgumentException( - "Missing required property serializedData in model MyWorkbookProperties")); - } - if (category() == null) { - throw LOGGER.atError() - .log(new IllegalArgumentException("Missing required property category in model MyWorkbookProperties")); - } - } - - private static final ClientLogger LOGGER = new ClientLogger(MyWorkbookProperties.class); - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("displayName", this.displayName); - jsonWriter.writeStringField("serializedData", this.serializedData); - jsonWriter.writeStringField("category", this.category); - jsonWriter.writeStringField("version", this.version); - jsonWriter.writeArrayField("tags", this.tags, (writer, element) -> writer.writeString(element)); - jsonWriter.writeStringField("sourceId", this.sourceId); - jsonWriter.writeStringField("storageUri", this.storageUri); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of MyWorkbookProperties from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of MyWorkbookProperties 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 MyWorkbookProperties. - */ - public static MyWorkbookProperties fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - MyWorkbookProperties deserializedMyWorkbookProperties = new MyWorkbookProperties(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("displayName".equals(fieldName)) { - deserializedMyWorkbookProperties.displayName = reader.getString(); - } else if ("serializedData".equals(fieldName)) { - deserializedMyWorkbookProperties.serializedData = reader.getString(); - } else if ("category".equals(fieldName)) { - deserializedMyWorkbookProperties.category = reader.getString(); - } else if ("version".equals(fieldName)) { - deserializedMyWorkbookProperties.version = reader.getString(); - } else if ("timeModified".equals(fieldName)) { - deserializedMyWorkbookProperties.timeModified = reader.getString(); - } else if ("tags".equals(fieldName)) { - List tags = reader.readArray(reader1 -> reader1.getString()); - deserializedMyWorkbookProperties.tags = tags; - } else if ("userId".equals(fieldName)) { - deserializedMyWorkbookProperties.userId = reader.getString(); - } else if ("sourceId".equals(fieldName)) { - deserializedMyWorkbookProperties.sourceId = reader.getString(); - } else if ("storageUri".equals(fieldName)) { - deserializedMyWorkbookProperties.storageUri = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedMyWorkbookProperties; - }); - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/ApplicationInsightsManagementClientImpl.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/ApplicationInsightsManagementClientImpl.java index e6a761bfc326..1dbd4e2df68e 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/ApplicationInsightsManagementClientImpl.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/ApplicationInsightsManagementClientImpl.java @@ -30,12 +30,13 @@ import com.azure.resourcemanager.applicationinsights.fluent.ComponentAvailableFeaturesClient; import com.azure.resourcemanager.applicationinsights.fluent.ComponentCurrentBillingFeaturesClient; import com.azure.resourcemanager.applicationinsights.fluent.ComponentFeatureCapabilitiesClient; +import com.azure.resourcemanager.applicationinsights.fluent.ComponentLinkedStorageAccountsOperationsClient; import com.azure.resourcemanager.applicationinsights.fluent.ComponentQuotaStatusClient; import com.azure.resourcemanager.applicationinsights.fluent.ComponentsClient; +import com.azure.resourcemanager.applicationinsights.fluent.DeletedWorkbooksClient; import com.azure.resourcemanager.applicationinsights.fluent.ExportConfigurationsClient; import com.azure.resourcemanager.applicationinsights.fluent.FavoritesClient; import com.azure.resourcemanager.applicationinsights.fluent.LiveTokensClient; -import com.azure.resourcemanager.applicationinsights.fluent.MyWorkbooksClient; import com.azure.resourcemanager.applicationinsights.fluent.OperationsClient; import com.azure.resourcemanager.applicationinsights.fluent.ProactiveDetectionConfigurationsClient; import com.azure.resourcemanager.applicationinsights.fluent.WebTestLocationsClient; @@ -351,20 +352,6 @@ public WorkbookTemplatesClient getWorkbookTemplates() { return this.workbookTemplates; } - /** - * The MyWorkbooksClient object to access its operations. - */ - private final MyWorkbooksClient myWorkbooks; - - /** - * Gets the MyWorkbooksClient object to access its operations. - * - * @return the MyWorkbooksClient object. - */ - public MyWorkbooksClient getMyWorkbooks() { - return this.myWorkbooks; - } - /** * The WorkbooksClient object to access its operations. */ @@ -393,6 +380,34 @@ public LiveTokensClient getLiveTokens() { return this.liveTokens; } + /** + * The ComponentLinkedStorageAccountsOperationsClient object to access its operations. + */ + private final ComponentLinkedStorageAccountsOperationsClient componentLinkedStorageAccountsOperations; + + /** + * Gets the ComponentLinkedStorageAccountsOperationsClient object to access its operations. + * + * @return the ComponentLinkedStorageAccountsOperationsClient object. + */ + public ComponentLinkedStorageAccountsOperationsClient getComponentLinkedStorageAccountsOperations() { + return this.componentLinkedStorageAccountsOperations; + } + + /** + * The DeletedWorkbooksClient object to access its operations. + */ + private final DeletedWorkbooksClient deletedWorkbooks; + + /** + * Gets the DeletedWorkbooksClient object to access its operations. + * + * @return the DeletedWorkbooksClient object. + */ + public DeletedWorkbooksClient getDeletedWorkbooks() { + return this.deletedWorkbooks; + } + /** * Initializes an instance of ApplicationInsightsManagementClient client. * @@ -426,9 +441,10 @@ public LiveTokensClient getLiveTokens() { this.analyticsItems = new AnalyticsItemsClientImpl(this); this.operations = new OperationsClientImpl(this); this.workbookTemplates = new WorkbookTemplatesClientImpl(this); - this.myWorkbooks = new MyWorkbooksClientImpl(this); this.workbooks = new WorkbooksClientImpl(this); this.liveTokens = new LiveTokensClientImpl(this); + this.componentLinkedStorageAccountsOperations = new ComponentLinkedStorageAccountsOperationsClientImpl(this); + this.deletedWorkbooks = new DeletedWorkbooksClientImpl(this); } /** diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/ComponentLinkedStorageAccountsImpl.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/ComponentLinkedStorageAccountsImpl.java new file mode 100644 index 000000000000..0cc408da97b9 --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/ComponentLinkedStorageAccountsImpl.java @@ -0,0 +1,146 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.implementation; + +import com.azure.core.util.Context; +import com.azure.resourcemanager.applicationinsights.fluent.models.ComponentLinkedStorageAccountsInner; +import com.azure.resourcemanager.applicationinsights.models.ComponentLinkedStorageAccounts; +import com.azure.resourcemanager.applicationinsights.models.ComponentLinkedStorageAccountsPatch; +import com.azure.resourcemanager.applicationinsights.models.StorageType; + +public final class ComponentLinkedStorageAccountsImpl implements ComponentLinkedStorageAccounts, + ComponentLinkedStorageAccounts.Definition, ComponentLinkedStorageAccounts.Update { + private ComponentLinkedStorageAccountsInner innerObject; + + private final com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager serviceManager; + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public String linkedStorageAccount() { + return this.innerModel().linkedStorageAccount(); + } + + public String resourceGroupName() { + return resourceGroupName; + } + + public ComponentLinkedStorageAccountsInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager() { + return this.serviceManager; + } + + private String resourceGroupName; + + private String resourceName; + + private StorageType storageType; + + private ComponentLinkedStorageAccountsPatch updateLinkedStorageAccountsProperties; + + public ComponentLinkedStorageAccountsImpl withExistingComponent(String resourceGroupName, String resourceName) { + this.resourceGroupName = resourceGroupName; + this.resourceName = resourceName; + return this; + } + + public ComponentLinkedStorageAccounts create() { + this.innerObject = serviceManager.serviceClient() + .getComponentLinkedStorageAccountsOperations() + .createAndUpdateWithResponse(resourceGroupName, resourceName, storageType, this.innerModel(), Context.NONE) + .getValue(); + return this; + } + + public ComponentLinkedStorageAccounts create(Context context) { + this.innerObject = serviceManager.serviceClient() + .getComponentLinkedStorageAccountsOperations() + .createAndUpdateWithResponse(resourceGroupName, resourceName, storageType, this.innerModel(), context) + .getValue(); + return this; + } + + ComponentLinkedStorageAccountsImpl(StorageType name, + com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager serviceManager) { + this.innerObject = new ComponentLinkedStorageAccountsInner(); + this.serviceManager = serviceManager; + this.storageType = name; + } + + public ComponentLinkedStorageAccountsImpl update() { + this.updateLinkedStorageAccountsProperties = new ComponentLinkedStorageAccountsPatch(); + return this; + } + + public ComponentLinkedStorageAccounts apply() { + this.innerObject = serviceManager.serviceClient() + .getComponentLinkedStorageAccountsOperations() + .updateWithResponse(resourceGroupName, resourceName, storageType, updateLinkedStorageAccountsProperties, + Context.NONE) + .getValue(); + return this; + } + + public ComponentLinkedStorageAccounts apply(Context context) { + this.innerObject = serviceManager.serviceClient() + .getComponentLinkedStorageAccountsOperations() + .updateWithResponse(resourceGroupName, resourceName, storageType, updateLinkedStorageAccountsProperties, + context) + .getValue(); + return this; + } + + ComponentLinkedStorageAccountsImpl(ComponentLinkedStorageAccountsInner innerObject, + com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + this.resourceGroupName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "resourceGroups"); + this.resourceName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "components"); + this.storageType = StorageType + .fromString(ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "linkedStorageAccounts")); + } + + public ComponentLinkedStorageAccounts refresh() { + this.innerObject = serviceManager.serviceClient() + .getComponentLinkedStorageAccountsOperations() + .getWithResponse(resourceGroupName, resourceName, storageType, Context.NONE) + .getValue(); + return this; + } + + public ComponentLinkedStorageAccounts refresh(Context context) { + this.innerObject = serviceManager.serviceClient() + .getComponentLinkedStorageAccountsOperations() + .getWithResponse(resourceGroupName, resourceName, storageType, context) + .getValue(); + return this; + } + + public ComponentLinkedStorageAccountsImpl withLinkedStorageAccount(String linkedStorageAccount) { + if (isInCreateMode()) { + this.innerModel().withLinkedStorageAccount(linkedStorageAccount); + return this; + } else { + this.updateLinkedStorageAccountsProperties.withLinkedStorageAccount(linkedStorageAccount); + return this; + } + } + + private boolean isInCreateMode() { + return this.innerModel().id() == null; + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/ComponentLinkedStorageAccountsOperationsClientImpl.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/ComponentLinkedStorageAccountsOperationsClientImpl.java new file mode 100644 index 000000000000..9149b7318810 --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/ComponentLinkedStorageAccountsOperationsClientImpl.java @@ -0,0 +1,701 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.Patch; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Put; +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.management.exception.ManagementException; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.resourcemanager.applicationinsights.fluent.ComponentLinkedStorageAccountsOperationsClient; +import com.azure.resourcemanager.applicationinsights.fluent.models.ComponentLinkedStorageAccountsInner; +import com.azure.resourcemanager.applicationinsights.models.ComponentLinkedStorageAccountsPatch; +import com.azure.resourcemanager.applicationinsights.models.StorageType; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in + * ComponentLinkedStorageAccountsOperationsClient. + */ +public final class ComponentLinkedStorageAccountsOperationsClientImpl + implements ComponentLinkedStorageAccountsOperationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final ComponentLinkedStorageAccountsOperationsService service; + + /** + * The service client containing this operation class. + */ + private final ApplicationInsightsManagementClientImpl client; + + /** + * Initializes an instance of ComponentLinkedStorageAccountsOperationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + ComponentLinkedStorageAccountsOperationsClientImpl(ApplicationInsightsManagementClientImpl client) { + this.service = RestProxy.create(ComponentLinkedStorageAccountsOperationsService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for + * ApplicationInsightsManagementClientComponentLinkedStorageAccountsOperations to be used by the proxy service to + * perform REST calls. + */ + @Host("{$host}") + @ServiceInterface(name = "ApplicationInsightsM") + public interface ComponentLinkedStorageAccountsOperationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{resourceName}/linkedStorageAccounts/{storageType}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("$host") String endpoint, + @PathParam("resourceGroupName") String resourceGroupName, @QueryParam("api-version") String apiVersion, + @PathParam("subscriptionId") String subscriptionId, @PathParam("resourceName") String resourceName, + @PathParam("storageType") StorageType storageType, @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Put("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{resourceName}/linkedStorageAccounts/{storageType}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> createAndUpdate(@HostParam("$host") String endpoint, + @PathParam("resourceGroupName") String resourceGroupName, @QueryParam("api-version") String apiVersion, + @PathParam("subscriptionId") String subscriptionId, @PathParam("resourceName") String resourceName, + @PathParam("storageType") StorageType storageType, + @BodyParam("application/json") ComponentLinkedStorageAccountsInner linkedStorageAccountsProperties, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Patch("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{resourceName}/linkedStorageAccounts/{storageType}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> update(@HostParam("$host") String endpoint, + @PathParam("resourceGroupName") String resourceGroupName, @QueryParam("api-version") String apiVersion, + @PathParam("subscriptionId") String subscriptionId, @PathParam("resourceName") String resourceName, + @PathParam("storageType") StorageType storageType, + @BodyParam("application/json") ComponentLinkedStorageAccountsPatch linkedStorageAccountsProperties, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Delete("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{resourceName}/linkedStorageAccounts/{storageType}") + @ExpectedResponses({ 200, 204 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> delete(@HostParam("$host") String endpoint, + @PathParam("resourceGroupName") String resourceGroupName, @QueryParam("api-version") String apiVersion, + @PathParam("subscriptionId") String subscriptionId, @PathParam("resourceName") String resourceName, + @PathParam("storageType") StorageType storageType, @HeaderParam("Accept") String accept, Context context); + } + + /** + * Returns the current linked storage settings for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Application Insights component linked storage accounts along with {@link Response} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, + String resourceName, StorageType storageType) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceName == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); + } + if (storageType == null) { + return Mono.error(new IllegalArgumentException("Parameter storageType is required and cannot be null.")); + } + final String apiVersion = "2020-03-01-preview"; + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), resourceGroupName, apiVersion, + this.client.getSubscriptionId(), resourceName, storageType, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Returns the current linked storage settings for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Application Insights component linked storage accounts along with {@link Response} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, + String resourceName, StorageType storageType, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceName == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); + } + if (storageType == null) { + return Mono.error(new IllegalArgumentException("Parameter storageType is required and cannot be null.")); + } + final String apiVersion = "2020-03-01-preview"; + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), resourceGroupName, apiVersion, this.client.getSubscriptionId(), + resourceName, storageType, accept, context); + } + + /** + * Returns the current linked storage settings for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Application Insights component linked storage accounts on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceGroupName, String resourceName, + StorageType storageType) { + return getWithResponseAsync(resourceGroupName, resourceName, storageType) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Returns the current linked storage settings for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Application Insights component linked storage accounts along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceGroupName, String resourceName, + StorageType storageType, Context context) { + return getWithResponseAsync(resourceGroupName, resourceName, storageType, context).block(); + } + + /** + * Returns the current linked storage settings for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Application Insights component linked storage accounts. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public ComponentLinkedStorageAccountsInner get(String resourceGroupName, String resourceName, + StorageType storageType) { + return getWithResponse(resourceGroupName, resourceName, storageType, Context.NONE).getValue(); + } + + /** + * Replace current linked storage account for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @param linkedStorageAccountsProperties Properties that need to be specified to update linked storage accounts for + * an Application Insights component. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Application Insights component linked storage accounts along with {@link Response} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> createAndUpdateWithResponseAsync( + String resourceGroupName, String resourceName, StorageType storageType, + ComponentLinkedStorageAccountsInner linkedStorageAccountsProperties) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceName == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); + } + if (storageType == null) { + return Mono.error(new IllegalArgumentException("Parameter storageType is required and cannot be null.")); + } + if (linkedStorageAccountsProperties == null) { + return Mono.error(new IllegalArgumentException( + "Parameter linkedStorageAccountsProperties is required and cannot be null.")); + } else { + linkedStorageAccountsProperties.validate(); + } + final String apiVersion = "2020-03-01-preview"; + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.createAndUpdate(this.client.getEndpoint(), resourceGroupName, apiVersion, + this.client.getSubscriptionId(), resourceName, storageType, linkedStorageAccountsProperties, accept, + context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Replace current linked storage account for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @param linkedStorageAccountsProperties Properties that need to be specified to update linked storage accounts for + * an Application Insights component. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Application Insights component linked storage accounts along with {@link Response} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> createAndUpdateWithResponseAsync( + String resourceGroupName, String resourceName, StorageType storageType, + ComponentLinkedStorageAccountsInner linkedStorageAccountsProperties, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceName == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); + } + if (storageType == null) { + return Mono.error(new IllegalArgumentException("Parameter storageType is required and cannot be null.")); + } + if (linkedStorageAccountsProperties == null) { + return Mono.error(new IllegalArgumentException( + "Parameter linkedStorageAccountsProperties is required and cannot be null.")); + } else { + linkedStorageAccountsProperties.validate(); + } + final String apiVersion = "2020-03-01-preview"; + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.createAndUpdate(this.client.getEndpoint(), resourceGroupName, apiVersion, + this.client.getSubscriptionId(), resourceName, storageType, linkedStorageAccountsProperties, accept, + context); + } + + /** + * Replace current linked storage account for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @param linkedStorageAccountsProperties Properties that need to be specified to update linked storage accounts for + * an Application Insights component. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Application Insights component linked storage accounts on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createAndUpdateAsync(String resourceGroupName, + String resourceName, StorageType storageType, + ComponentLinkedStorageAccountsInner linkedStorageAccountsProperties) { + return createAndUpdateWithResponseAsync(resourceGroupName, resourceName, storageType, + linkedStorageAccountsProperties).flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Replace current linked storage account for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @param linkedStorageAccountsProperties Properties that need to be specified to update linked storage accounts for + * an Application Insights component. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Application Insights component linked storage accounts along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createAndUpdateWithResponse(String resourceGroupName, + String resourceName, StorageType storageType, + ComponentLinkedStorageAccountsInner linkedStorageAccountsProperties, Context context) { + return createAndUpdateWithResponseAsync(resourceGroupName, resourceName, storageType, + linkedStorageAccountsProperties, context).block(); + } + + /** + * Replace current linked storage account for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @param linkedStorageAccountsProperties Properties that need to be specified to update linked storage accounts for + * an Application Insights component. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Application Insights component linked storage accounts. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public ComponentLinkedStorageAccountsInner createAndUpdate(String resourceGroupName, String resourceName, + StorageType storageType, ComponentLinkedStorageAccountsInner linkedStorageAccountsProperties) { + return createAndUpdateWithResponse(resourceGroupName, resourceName, storageType, + linkedStorageAccountsProperties, Context.NONE).getValue(); + } + + /** + * Update linked storage accounts for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @param linkedStorageAccountsProperties Properties that need to be specified to update a linked storage accounts + * for an Application Insights component. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Application Insights component linked storage accounts along with {@link Response} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> updateWithResponseAsync(String resourceGroupName, + String resourceName, StorageType storageType, + ComponentLinkedStorageAccountsPatch linkedStorageAccountsProperties) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceName == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); + } + if (storageType == null) { + return Mono.error(new IllegalArgumentException("Parameter storageType is required and cannot be null.")); + } + if (linkedStorageAccountsProperties == null) { + return Mono.error(new IllegalArgumentException( + "Parameter linkedStorageAccountsProperties is required and cannot be null.")); + } else { + linkedStorageAccountsProperties.validate(); + } + final String apiVersion = "2020-03-01-preview"; + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.update(this.client.getEndpoint(), resourceGroupName, apiVersion, + this.client.getSubscriptionId(), resourceName, storageType, linkedStorageAccountsProperties, accept, + context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Update linked storage accounts for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @param linkedStorageAccountsProperties Properties that need to be specified to update a linked storage accounts + * for an Application Insights component. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Application Insights component linked storage accounts along with {@link Response} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> updateWithResponseAsync(String resourceGroupName, + String resourceName, StorageType storageType, + ComponentLinkedStorageAccountsPatch linkedStorageAccountsProperties, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceName == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); + } + if (storageType == null) { + return Mono.error(new IllegalArgumentException("Parameter storageType is required and cannot be null.")); + } + if (linkedStorageAccountsProperties == null) { + return Mono.error(new IllegalArgumentException( + "Parameter linkedStorageAccountsProperties is required and cannot be null.")); + } else { + linkedStorageAccountsProperties.validate(); + } + final String apiVersion = "2020-03-01-preview"; + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.update(this.client.getEndpoint(), resourceGroupName, apiVersion, this.client.getSubscriptionId(), + resourceName, storageType, linkedStorageAccountsProperties, accept, context); + } + + /** + * Update linked storage accounts for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @param linkedStorageAccountsProperties Properties that need to be specified to update a linked storage accounts + * for an Application Insights component. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Application Insights component linked storage accounts on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono updateAsync(String resourceGroupName, String resourceName, + StorageType storageType, ComponentLinkedStorageAccountsPatch linkedStorageAccountsProperties) { + return updateWithResponseAsync(resourceGroupName, resourceName, storageType, linkedStorageAccountsProperties) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Update linked storage accounts for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @param linkedStorageAccountsProperties Properties that need to be specified to update a linked storage accounts + * for an Application Insights component. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Application Insights component linked storage accounts along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response updateWithResponse(String resourceGroupName, + String resourceName, StorageType storageType, + ComponentLinkedStorageAccountsPatch linkedStorageAccountsProperties, Context context) { + return updateWithResponseAsync(resourceGroupName, resourceName, storageType, linkedStorageAccountsProperties, + context).block(); + } + + /** + * Update linked storage accounts for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @param linkedStorageAccountsProperties Properties that need to be specified to update a linked storage accounts + * for an Application Insights component. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Application Insights component linked storage accounts. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public ComponentLinkedStorageAccountsInner update(String resourceGroupName, String resourceName, + StorageType storageType, ComponentLinkedStorageAccountsPatch linkedStorageAccountsProperties) { + return updateWithResponse(resourceGroupName, resourceName, storageType, linkedStorageAccountsProperties, + Context.NONE).getValue(); + } + + /** + * Delete linked storage accounts for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String resourceName, + StorageType storageType) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceName == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); + } + if (storageType == null) { + return Mono.error(new IllegalArgumentException("Parameter storageType is required and cannot be null.")); + } + final String apiVersion = "2020-03-01-preview"; + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.delete(this.client.getEndpoint(), resourceGroupName, apiVersion, + this.client.getSubscriptionId(), resourceName, storageType, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Delete linked storage accounts for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String resourceName, + StorageType storageType, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceName == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); + } + if (storageType == null) { + return Mono.error(new IllegalArgumentException("Parameter storageType is required and cannot be null.")); + } + final String apiVersion = "2020-03-01-preview"; + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.delete(this.client.getEndpoint(), resourceGroupName, apiVersion, this.client.getSubscriptionId(), + resourceName, storageType, accept, context); + } + + /** + * Delete linked storage accounts for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono deleteAsync(String resourceGroupName, String resourceName, StorageType storageType) { + return deleteWithResponseAsync(resourceGroupName, resourceName, storageType).flatMap(ignored -> Mono.empty()); + } + + /** + * Delete linked storage accounts for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String resourceGroupName, String resourceName, StorageType storageType, + Context context) { + return deleteWithResponseAsync(resourceGroupName, resourceName, storageType, context).block(); + } + + /** + * Delete linked storage accounts for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String resourceGroupName, String resourceName, StorageType storageType) { + deleteWithResponse(resourceGroupName, resourceName, storageType, Context.NONE); + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/ComponentLinkedStorageAccountsOperationsImpl.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/ComponentLinkedStorageAccountsOperationsImpl.java new file mode 100644 index 000000000000..5ea29b91b337 --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/ComponentLinkedStorageAccountsOperationsImpl.java @@ -0,0 +1,152 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.implementation; + +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.applicationinsights.fluent.ComponentLinkedStorageAccountsOperationsClient; +import com.azure.resourcemanager.applicationinsights.fluent.models.ComponentLinkedStorageAccountsInner; +import com.azure.resourcemanager.applicationinsights.models.ComponentLinkedStorageAccounts; +import com.azure.resourcemanager.applicationinsights.models.ComponentLinkedStorageAccountsOperations; +import com.azure.resourcemanager.applicationinsights.models.StorageType; + +public final class ComponentLinkedStorageAccountsOperationsImpl implements ComponentLinkedStorageAccountsOperations { + private static final ClientLogger LOGGER = new ClientLogger(ComponentLinkedStorageAccountsOperationsImpl.class); + + private final ComponentLinkedStorageAccountsOperationsClient innerClient; + + private final com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager serviceManager; + + public ComponentLinkedStorageAccountsOperationsImpl(ComponentLinkedStorageAccountsOperationsClient innerClient, + com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public Response getWithResponse(String resourceGroupName, String resourceName, + StorageType storageType, Context context) { + Response inner + = this.serviceClient().getWithResponse(resourceGroupName, resourceName, storageType, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new ComponentLinkedStorageAccountsImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public ComponentLinkedStorageAccounts get(String resourceGroupName, String resourceName, StorageType storageType) { + ComponentLinkedStorageAccountsInner inner + = this.serviceClient().get(resourceGroupName, resourceName, storageType); + if (inner != null) { + return new ComponentLinkedStorageAccountsImpl(inner, this.manager()); + } else { + return null; + } + } + + public Response deleteWithResponse(String resourceGroupName, String resourceName, StorageType storageType, + Context context) { + return this.serviceClient().deleteWithResponse(resourceGroupName, resourceName, storageType, context); + } + + public void delete(String resourceGroupName, String resourceName, StorageType storageType) { + this.serviceClient().delete(resourceGroupName, resourceName, storageType); + } + + public ComponentLinkedStorageAccounts getById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String resourceName = ResourceManagerUtils.getValueFromIdByName(id, "components"); + if (resourceName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'components'.", id))); + } + String storageTypeLocal = ResourceManagerUtils.getValueFromIdByName(id, "linkedStorageAccounts"); + if (storageTypeLocal == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'linkedStorageAccounts'.", id))); + } + StorageType storageType = StorageType.fromString(storageTypeLocal); + return this.getWithResponse(resourceGroupName, resourceName, storageType, Context.NONE).getValue(); + } + + public Response getByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String resourceName = ResourceManagerUtils.getValueFromIdByName(id, "components"); + if (resourceName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'components'.", id))); + } + String storageTypeLocal = ResourceManagerUtils.getValueFromIdByName(id, "linkedStorageAccounts"); + if (storageTypeLocal == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'linkedStorageAccounts'.", id))); + } + StorageType storageType = StorageType.fromString(storageTypeLocal); + return this.getWithResponse(resourceGroupName, resourceName, storageType, context); + } + + public void deleteById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String resourceName = ResourceManagerUtils.getValueFromIdByName(id, "components"); + if (resourceName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'components'.", id))); + } + String storageTypeLocal = ResourceManagerUtils.getValueFromIdByName(id, "linkedStorageAccounts"); + if (storageTypeLocal == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'linkedStorageAccounts'.", id))); + } + StorageType storageType = StorageType.fromString(storageTypeLocal); + this.deleteWithResponse(resourceGroupName, resourceName, storageType, Context.NONE); + } + + public Response deleteByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String resourceName = ResourceManagerUtils.getValueFromIdByName(id, "components"); + if (resourceName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'components'.", id))); + } + String storageTypeLocal = ResourceManagerUtils.getValueFromIdByName(id, "linkedStorageAccounts"); + if (storageTypeLocal == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'linkedStorageAccounts'.", id))); + } + StorageType storageType = StorageType.fromString(storageTypeLocal); + return this.deleteWithResponse(resourceGroupName, resourceName, storageType, context); + } + + private ComponentLinkedStorageAccountsOperationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager() { + return this.serviceManager; + } + + public ComponentLinkedStorageAccountsImpl define(StorageType name) { + return new ComponentLinkedStorageAccountsImpl(name, this.manager()); + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/DeletedWorkbookImpl.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/DeletedWorkbookImpl.java new file mode 100644 index 000000000000..7edceb7de842 --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/DeletedWorkbookImpl.java @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.implementation; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.applicationinsights.fluent.models.DeletedWorkbookInner; +import com.azure.resourcemanager.applicationinsights.models.DeletedWorkbook; +import com.azure.resourcemanager.applicationinsights.models.WorkbookSharedTypeKind; +import java.time.OffsetDateTime; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +public final class DeletedWorkbookImpl implements DeletedWorkbook { + private DeletedWorkbookInner innerObject; + + private final com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager serviceManager; + + DeletedWorkbookImpl(DeletedWorkbookInner innerObject, + com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public String location() { + return this.innerModel().location(); + } + + public Map tags() { + Map inner = this.innerModel().tags(); + if (inner != null) { + return Collections.unmodifiableMap(inner); + } else { + return Collections.emptyMap(); + } + } + + public WorkbookSharedTypeKind kind() { + return this.innerModel().kind(); + } + + public String etag() { + return this.innerModel().etag(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public String displayName() { + return this.innerModel().displayName(); + } + + public String serializedData() { + return this.innerModel().serializedData(); + } + + public String version() { + return this.innerModel().version(); + } + + public OffsetDateTime timeModified() { + return this.innerModel().timeModified(); + } + + public String category() { + return this.innerModel().category(); + } + + public List tagsPropertiesTags() { + List inner = this.innerModel().tagsPropertiesTags(); + if (inner != null) { + return Collections.unmodifiableList(inner); + } else { + return Collections.emptyList(); + } + } + + public String userId() { + return this.innerModel().userId(); + } + + public String sourceId() { + return this.innerModel().sourceId(); + } + + public String storageUri() { + return this.innerModel().storageUri(); + } + + public String description() { + return this.innerModel().description(); + } + + public String revision() { + return this.innerModel().revision(); + } + + public DeletedWorkbookInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/DeletedWorkbooksClientImpl.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/DeletedWorkbooksClientImpl.java new file mode 100644 index 000000000000..29a846f1c57d --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/DeletedWorkbooksClientImpl.java @@ -0,0 +1,294 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.implementation; + +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +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 com.azure.resourcemanager.applicationinsights.fluent.DeletedWorkbooksClient; +import com.azure.resourcemanager.applicationinsights.fluent.models.DeletedWorkbookInner; +import com.azure.resourcemanager.applicationinsights.models.CategoryType; +import com.azure.resourcemanager.applicationinsights.models.DeletedWorkbookErrorDefinitionException; +import com.azure.resourcemanager.applicationinsights.models.DeletedWorkbooksListResult; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in DeletedWorkbooksClient. + */ +public final class DeletedWorkbooksClientImpl implements DeletedWorkbooksClient { + /** + * The proxy service used to perform REST calls. + */ + private final DeletedWorkbooksService service; + + /** + * The service client containing this operation class. + */ + private final ApplicationInsightsManagementClientImpl client; + + /** + * Initializes an instance of DeletedWorkbooksClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + DeletedWorkbooksClientImpl(ApplicationInsightsManagementClientImpl client) { + this.service + = RestProxy.create(DeletedWorkbooksService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for ApplicationInsightsManagementClientDeletedWorkbooks to be used by the + * proxy service to perform REST calls. + */ + @Host("{$host}") + @ServiceInterface(name = "ApplicationInsightsM") + public interface DeletedWorkbooksService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/providers/Microsoft.Insights/deletedWorkbooks") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(DeletedWorkbookErrorDefinitionException.class) + Mono> list(@HostParam("$host") String endpoint, + @PathParam("subscriptionId") String subscriptionId, @QueryParam("category") CategoryType category, + @QueryParam("tags") String tags, @QueryParam("api-version") String apiVersion, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(DeletedWorkbookErrorDefinitionException.class) + Mono> listBySubscriptionNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * Get all recently deleted Workbooks in a specified subscription. + * + * @param category Category of workbook to return. + * @param tags Tags presents on each workbook returned. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws DeletedWorkbookErrorDefinitionException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return all recently deleted Workbooks in a specified subscription along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync(CategoryType category, List tags) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + final String apiVersion = "2024-02-01-preview"; + final String accept = "application/json"; + String tagsConverted = (tags == null) + ? null + : tags.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")); + return FluxUtil + .withContext(context -> service.list(this.client.getEndpoint(), this.client.getSubscriptionId(), category, + tagsConverted, apiVersion, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get all recently deleted Workbooks in a specified subscription. + * + * @param category Category of workbook to return. + * @param tags Tags presents on each workbook returned. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws DeletedWorkbookErrorDefinitionException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return all recently deleted Workbooks in a specified subscription along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync(CategoryType category, List tags, + Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + final String apiVersion = "2024-02-01-preview"; + final String accept = "application/json"; + String tagsConverted = (tags == null) + ? null + : tags.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")); + context = this.client.mergeContext(context); + return service + .list(this.client.getEndpoint(), this.client.getSubscriptionId(), category, tagsConverted, apiVersion, + accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * Get all recently deleted Workbooks in a specified subscription. + * + * @param category Category of workbook to return. + * @param tags Tags presents on each workbook returned. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws DeletedWorkbookErrorDefinitionException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return all recently deleted Workbooks in a specified subscription as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync(CategoryType category, List tags) { + return new PagedFlux<>(() -> listSinglePageAsync(category, tags), + nextLink -> listBySubscriptionNextSinglePageAsync(nextLink)); + } + + /** + * Get all recently deleted Workbooks in a specified subscription. + * + * @throws DeletedWorkbookErrorDefinitionException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return all recently deleted Workbooks in a specified subscription as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync() { + final CategoryType category = null; + final List tags = null; + return new PagedFlux<>(() -> listSinglePageAsync(category, tags), + nextLink -> listBySubscriptionNextSinglePageAsync(nextLink)); + } + + /** + * Get all recently deleted Workbooks in a specified subscription. + * + * @param category Category of workbook to return. + * @param tags Tags presents on each workbook returned. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws DeletedWorkbookErrorDefinitionException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return all recently deleted Workbooks in a specified subscription as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync(CategoryType category, List tags, Context context) { + return new PagedFlux<>(() -> listSinglePageAsync(category, tags, context), + nextLink -> listBySubscriptionNextSinglePageAsync(nextLink, context)); + } + + /** + * Get all recently deleted Workbooks in a specified subscription. + * + * @throws DeletedWorkbookErrorDefinitionException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return all recently deleted Workbooks in a specified subscription as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list() { + final CategoryType category = null; + final List tags = null; + return new PagedIterable<>(listAsync(category, tags)); + } + + /** + * Get all recently deleted Workbooks in a specified subscription. + * + * @param category Category of workbook to return. + * @param tags Tags presents on each workbook returned. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws DeletedWorkbookErrorDefinitionException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return all recently deleted Workbooks in a specified subscription as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(CategoryType category, List tags, Context context) { + return new PagedIterable<>(listAsync(category, tags, context)); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws DeletedWorkbookErrorDefinitionException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return workbook list result along with {@link PagedResponse} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySubscriptionNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws DeletedWorkbookErrorDefinitionException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return workbook list result along with {@link PagedResponse} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySubscriptionNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/DeletedWorkbooksImpl.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/DeletedWorkbooksImpl.java new file mode 100644 index 000000000000..03f377018a6f --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/DeletedWorkbooksImpl.java @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.applicationinsights.fluent.DeletedWorkbooksClient; +import com.azure.resourcemanager.applicationinsights.fluent.models.DeletedWorkbookInner; +import com.azure.resourcemanager.applicationinsights.models.CategoryType; +import com.azure.resourcemanager.applicationinsights.models.DeletedWorkbook; +import com.azure.resourcemanager.applicationinsights.models.DeletedWorkbooks; +import java.util.List; + +public final class DeletedWorkbooksImpl implements DeletedWorkbooks { + private static final ClientLogger LOGGER = new ClientLogger(DeletedWorkbooksImpl.class); + + private final DeletedWorkbooksClient innerClient; + + private final com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager serviceManager; + + public DeletedWorkbooksImpl(DeletedWorkbooksClient innerClient, + com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public PagedIterable list() { + PagedIterable inner = this.serviceClient().list(); + return ResourceManagerUtils.mapPage(inner, inner1 -> new DeletedWorkbookImpl(inner1, this.manager())); + } + + public PagedIterable list(CategoryType category, List tags, Context context) { + PagedIterable inner = this.serviceClient().list(category, tags, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new DeletedWorkbookImpl(inner1, this.manager())); + } + + private DeletedWorkbooksClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/MyWorkbookImpl.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/MyWorkbookImpl.java deleted file mode 100644 index fec18f6e236a..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/MyWorkbookImpl.java +++ /dev/null @@ -1,301 +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.resourcemanager.applicationinsights.implementation; - -import com.azure.core.management.Region; -import com.azure.core.management.SystemData; -import com.azure.core.util.Context; -import com.azure.resourcemanager.applicationinsights.fluent.models.MyWorkbookInner; -import com.azure.resourcemanager.applicationinsights.models.Kind; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbook; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbookManagedIdentity; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -public final class MyWorkbookImpl implements MyWorkbook, MyWorkbook.Definition, MyWorkbook.Update { - private MyWorkbookInner innerObject; - - private final com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager serviceManager; - - public String location() { - return this.innerModel().location(); - } - - public Map tags() { - Map inner = this.innerModel().tags(); - if (inner != null) { - return Collections.unmodifiableMap(inner); - } else { - return Collections.emptyMap(); - } - } - - public MyWorkbookManagedIdentity identity() { - return this.innerModel().identity(); - } - - public String id() { - return this.innerModel().id(); - } - - public String name() { - return this.innerModel().name(); - } - - public String type() { - return this.innerModel().type(); - } - - public Map etag() { - Map inner = this.innerModel().etag(); - if (inner != null) { - return Collections.unmodifiableMap(inner); - } else { - return Collections.emptyMap(); - } - } - - public Kind kind() { - return this.innerModel().kind(); - } - - public SystemData systemData() { - return this.innerModel().systemData(); - } - - public String displayName() { - return this.innerModel().displayName(); - } - - public String serializedData() { - return this.innerModel().serializedData(); - } - - public String version() { - return this.innerModel().version(); - } - - public String timeModified() { - return this.innerModel().timeModified(); - } - - public String category() { - return this.innerModel().category(); - } - - public List tagsPropertiesTags() { - List inner = this.innerModel().tagsPropertiesTags(); - if (inner != null) { - return Collections.unmodifiableList(inner); - } else { - return Collections.emptyList(); - } - } - - public String userId() { - return this.innerModel().userId(); - } - - public String sourceId() { - return this.innerModel().sourceId(); - } - - public String storageUri() { - return this.innerModel().storageUri(); - } - - public Region region() { - return Region.fromName(this.regionName()); - } - - public String regionName() { - return this.location(); - } - - public String resourceGroupName() { - return resourceGroupName; - } - - public MyWorkbookInner innerModel() { - return this.innerObject; - } - - private com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager() { - return this.serviceManager; - } - - private String resourceGroupName; - - private String resourceName; - - private String createSourceId; - - private String updateSourceId; - - public MyWorkbookImpl withExistingResourceGroup(String resourceGroupName) { - this.resourceGroupName = resourceGroupName; - return this; - } - - public MyWorkbook create() { - this.innerObject = serviceManager.serviceClient() - .getMyWorkbooks() - .createOrUpdateWithResponse(resourceGroupName, resourceName, this.innerModel(), createSourceId, - Context.NONE) - .getValue(); - return this; - } - - public MyWorkbook create(Context context) { - this.innerObject = serviceManager.serviceClient() - .getMyWorkbooks() - .createOrUpdateWithResponse(resourceGroupName, resourceName, this.innerModel(), createSourceId, context) - .getValue(); - return this; - } - - MyWorkbookImpl(String name, - com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager serviceManager) { - this.innerObject = new MyWorkbookInner(); - this.serviceManager = serviceManager; - this.resourceName = name; - this.createSourceId = null; - } - - public MyWorkbookImpl update() { - this.updateSourceId = null; - return this; - } - - public MyWorkbook apply() { - this.innerObject = serviceManager.serviceClient() - .getMyWorkbooks() - .updateWithResponse(resourceGroupName, resourceName, this.innerModel(), updateSourceId, Context.NONE) - .getValue(); - return this; - } - - public MyWorkbook apply(Context context) { - this.innerObject = serviceManager.serviceClient() - .getMyWorkbooks() - .updateWithResponse(resourceGroupName, resourceName, this.innerModel(), updateSourceId, context) - .getValue(); - return this; - } - - MyWorkbookImpl(MyWorkbookInner innerObject, - com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager serviceManager) { - this.innerObject = innerObject; - this.serviceManager = serviceManager; - this.resourceGroupName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "resourceGroups"); - this.resourceName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "myWorkbooks"); - } - - public MyWorkbook refresh() { - this.innerObject = serviceManager.serviceClient() - .getMyWorkbooks() - .getByResourceGroupWithResponse(resourceGroupName, resourceName, Context.NONE) - .getValue(); - return this; - } - - public MyWorkbook refresh(Context context) { - this.innerObject = serviceManager.serviceClient() - .getMyWorkbooks() - .getByResourceGroupWithResponse(resourceGroupName, resourceName, context) - .getValue(); - return this; - } - - public MyWorkbookImpl withRegion(Region location) { - this.innerModel().withLocation(location.toString()); - return this; - } - - public MyWorkbookImpl withRegion(String location) { - this.innerModel().withLocation(location); - return this; - } - - public MyWorkbookImpl withTags(Map tags) { - this.innerModel().withTags(tags); - return this; - } - - public MyWorkbookImpl withIdentity(MyWorkbookManagedIdentity identity) { - this.innerModel().withIdentity(identity); - return this; - } - - public MyWorkbookImpl withName(String name) { - this.innerModel().withName(name); - return this; - } - - public MyWorkbookImpl withType(String type) { - this.innerModel().withType(type); - return this; - } - - public MyWorkbookImpl withEtag(Map etag) { - this.innerModel().withEtag(etag); - return this; - } - - public MyWorkbookImpl withKind(Kind kind) { - this.innerModel().withKind(kind); - return this; - } - - public MyWorkbookImpl withDisplayName(String displayName) { - this.innerModel().withDisplayName(displayName); - return this; - } - - public MyWorkbookImpl withSerializedData(String serializedData) { - this.innerModel().withSerializedData(serializedData); - return this; - } - - public MyWorkbookImpl withVersion(String version) { - this.innerModel().withVersion(version); - return this; - } - - public MyWorkbookImpl withCategory(String category) { - this.innerModel().withCategory(category); - return this; - } - - public MyWorkbookImpl withTagsPropertiesTags(List tagsPropertiesTags) { - this.innerModel().withTagsPropertiesTags(tagsPropertiesTags); - return this; - } - - public MyWorkbookImpl withSourceId(String sourceId) { - this.innerModel().withSourceId(sourceId); - return this; - } - - public MyWorkbookImpl withStorageUri(String storageUri) { - this.innerModel().withStorageUri(storageUri); - return this; - } - - public MyWorkbookImpl withSourceIdParameter(String sourceId) { - if (isInCreateMode()) { - this.createSourceId = sourceId; - return this; - } else { - this.updateSourceId = sourceId; - return this; - } - } - - private boolean isInCreateMode() { - return this.innerModel().id() == null; - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/MyWorkbooksClientImpl.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/MyWorkbooksClientImpl.java deleted file mode 100644 index d5c74b802dfc..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/MyWorkbooksClientImpl.java +++ /dev/null @@ -1,1177 +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.resourcemanager.applicationinsights.implementation; - -import com.azure.core.annotation.BodyParam; -import com.azure.core.annotation.Delete; -import com.azure.core.annotation.ExpectedResponses; -import com.azure.core.annotation.Get; -import com.azure.core.annotation.HeaderParam; -import com.azure.core.annotation.Headers; -import com.azure.core.annotation.Host; -import com.azure.core.annotation.HostParam; -import com.azure.core.annotation.Patch; -import com.azure.core.annotation.PathParam; -import com.azure.core.annotation.Put; -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.PagedFlux; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.PagedResponse; -import com.azure.core.http.rest.PagedResponseBase; -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 com.azure.resourcemanager.applicationinsights.fluent.MyWorkbooksClient; -import com.azure.resourcemanager.applicationinsights.fluent.models.MyWorkbookInner; -import com.azure.resourcemanager.applicationinsights.models.CategoryType; -import com.azure.resourcemanager.applicationinsights.models.ErrorDefinitionException; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbooksListResult; -import java.util.List; -import java.util.Objects; -import java.util.stream.Collectors; -import reactor.core.publisher.Mono; - -/** - * An instance of this class provides access to all the operations defined in MyWorkbooksClient. - */ -public final class MyWorkbooksClientImpl implements MyWorkbooksClient { - /** - * The proxy service used to perform REST calls. - */ - private final MyWorkbooksService service; - - /** - * The service client containing this operation class. - */ - private final ApplicationInsightsManagementClientImpl client; - - /** - * Initializes an instance of MyWorkbooksClientImpl. - * - * @param client the instance of the service client containing this operation class. - */ - MyWorkbooksClientImpl(ApplicationInsightsManagementClientImpl client) { - this.service - = RestProxy.create(MyWorkbooksService.class, client.getHttpPipeline(), client.getSerializerAdapter()); - this.client = client; - } - - /** - * The interface defining all the services for ApplicationInsightsManagementClientMyWorkbooks to be used by the - * proxy service to perform REST calls. - */ - @Host("{$host}") - @ServiceInterface(name = "ApplicationInsightsM") - public interface MyWorkbooksService { - @Headers({ "Content-Type: application/json" }) - @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/myWorkbooks") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorDefinitionException.class) - Mono> listByResourceGroup(@HostParam("$host") String endpoint, - @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, @QueryParam("category") CategoryType category, - @QueryParam("tags") String tags, @QueryParam("sourceId") String sourceId, - @QueryParam("canFetchContent") Boolean canFetchContent, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Headers({ "Content-Type: application/json" }) - @Get("/subscriptions/{subscriptionId}/providers/Microsoft.Insights/myWorkbooks") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorDefinitionException.class) - Mono> list(@HostParam("$host") String endpoint, - @PathParam("subscriptionId") String subscriptionId, @QueryParam("category") CategoryType category, - @QueryParam("tags") String tags, @QueryParam("canFetchContent") Boolean canFetchContent, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Headers({ "Content-Type: application/json" }) - @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/myWorkbooks/{resourceName}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorDefinitionException.class) - Mono> getByResourceGroup(@HostParam("$host") String endpoint, - @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, @PathParam("resourceName") String resourceName, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Headers({ "Content-Type: application/json" }) - @Delete("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/myWorkbooks/{resourceName}") - @ExpectedResponses({ 200, 204 }) - @UnexpectedResponseExceptionType(ErrorDefinitionException.class) - Mono> delete(@HostParam("$host") String endpoint, - @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, @PathParam("resourceName") String resourceName, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Headers({ "Content-Type: application/json" }) - @Put("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/myWorkbooks/{resourceName}") - @ExpectedResponses({ 200, 201 }) - @UnexpectedResponseExceptionType(ErrorDefinitionException.class) - Mono> createOrUpdate(@HostParam("$host") String endpoint, - @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, @PathParam("resourceName") String resourceName, - @QueryParam("sourceId") String sourceId, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") MyWorkbookInner workbookProperties, @HeaderParam("Accept") String accept, - Context context); - - @Headers({ "Content-Type: application/json" }) - @Patch("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/myWorkbooks/{resourceName}") - @ExpectedResponses({ 201 }) - @UnexpectedResponseExceptionType(ErrorDefinitionException.class) - Mono> update(@HostParam("$host") String endpoint, - @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, @PathParam("resourceName") String resourceName, - @QueryParam("sourceId") String sourceId, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") MyWorkbookInner workbookProperties, @HeaderParam("Accept") String accept, - Context context); - - @Headers({ "Content-Type: application/json" }) - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorDefinitionException.class) - Mono> listByResourceGroupNext( - @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, - @HeaderParam("Accept") String accept, Context context); - - @Headers({ "Content-Type: application/json" }) - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorDefinitionException.class) - Mono> listBySubscriptionNext( - @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, - @HeaderParam("Accept") String accept, Context context); - } - - /** - * Get all private workbooks defined within a specified resource group and category. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param category Category of workbook to return. - * @param tags Tags presents on each workbook returned. - * @param sourceId Azure Resource Id that will fetch all linked workbooks. - * @param canFetchContent Flag indicating whether or not to return the full content for each applicable workbook. If - * false, only return summary content for workbooks. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all private workbooks defined within a specified resource group and category along with - * {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listByResourceGroupSinglePageAsync(String resourceGroupName, - CategoryType category, List tags, String sourceId, Boolean canFetchContent) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (category == null) { - return Mono.error(new IllegalArgumentException("Parameter category is required and cannot be null.")); - } - final String apiVersion = "2021-03-08"; - final String accept = "application/json"; - String tagsConverted = (tags == null) - ? null - : tags.stream() - .map(paramItemValue -> Objects.toString(paramItemValue, "")) - .collect(Collectors.joining(",")); - return FluxUtil - .withContext( - context -> service.listByResourceGroup(this.client.getEndpoint(), this.client.getSubscriptionId(), - resourceGroupName, category, tagsConverted, sourceId, canFetchContent, apiVersion, accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), - res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Get all private workbooks defined within a specified resource group and category. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param category Category of workbook to return. - * @param tags Tags presents on each workbook returned. - * @param sourceId Azure Resource Id that will fetch all linked workbooks. - * @param canFetchContent Flag indicating whether or not to return the full content for each applicable workbook. If - * false, only return summary content for workbooks. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all private workbooks defined within a specified resource group and category along with - * {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listByResourceGroupSinglePageAsync(String resourceGroupName, - CategoryType category, List tags, String sourceId, Boolean canFetchContent, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (category == null) { - return Mono.error(new IllegalArgumentException("Parameter category is required and cannot be null.")); - } - final String apiVersion = "2021-03-08"; - final String accept = "application/json"; - String tagsConverted = (tags == null) - ? null - : tags.stream() - .map(paramItemValue -> Objects.toString(paramItemValue, "")) - .collect(Collectors.joining(",")); - context = this.client.mergeContext(context); - return service - .listByResourceGroup(this.client.getEndpoint(), this.client.getSubscriptionId(), resourceGroupName, - category, tagsConverted, sourceId, canFetchContent, apiVersion, accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } - - /** - * Get all private workbooks defined within a specified resource group and category. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param category Category of workbook to return. - * @param tags Tags presents on each workbook returned. - * @param sourceId Azure Resource Id that will fetch all linked workbooks. - * @param canFetchContent Flag indicating whether or not to return the full content for each applicable workbook. If - * false, only return summary content for workbooks. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all private workbooks defined within a specified resource group and category as paginated response with - * {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listByResourceGroupAsync(String resourceGroupName, CategoryType category, - List tags, String sourceId, Boolean canFetchContent) { - return new PagedFlux<>( - () -> listByResourceGroupSinglePageAsync(resourceGroupName, category, tags, sourceId, canFetchContent), - nextLink -> listByResourceGroupNextSinglePageAsync(nextLink)); - } - - /** - * Get all private workbooks defined within a specified resource group and category. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param category Category of workbook to return. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all private workbooks defined within a specified resource group and category as paginated response with - * {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listByResourceGroupAsync(String resourceGroupName, CategoryType category) { - final List tags = null; - final String sourceId = null; - final Boolean canFetchContent = null; - return new PagedFlux<>( - () -> listByResourceGroupSinglePageAsync(resourceGroupName, category, tags, sourceId, canFetchContent), - nextLink -> listByResourceGroupNextSinglePageAsync(nextLink)); - } - - /** - * Get all private workbooks defined within a specified resource group and category. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param category Category of workbook to return. - * @param tags Tags presents on each workbook returned. - * @param sourceId Azure Resource Id that will fetch all linked workbooks. - * @param canFetchContent Flag indicating whether or not to return the full content for each applicable workbook. If - * false, only return summary content for workbooks. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all private workbooks defined within a specified resource group and category as paginated response with - * {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listByResourceGroupAsync(String resourceGroupName, CategoryType category, - List tags, String sourceId, Boolean canFetchContent, Context context) { - return new PagedFlux<>(() -> listByResourceGroupSinglePageAsync(resourceGroupName, category, tags, sourceId, - canFetchContent, context), nextLink -> listByResourceGroupNextSinglePageAsync(nextLink, context)); - } - - /** - * Get all private workbooks defined within a specified resource group and category. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param category Category of workbook to return. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all private workbooks defined within a specified resource group and category as paginated response with - * {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listByResourceGroup(String resourceGroupName, CategoryType category) { - final List tags = null; - final String sourceId = null; - final Boolean canFetchContent = null; - return new PagedIterable<>( - listByResourceGroupAsync(resourceGroupName, category, tags, sourceId, canFetchContent)); - } - - /** - * Get all private workbooks defined within a specified resource group and category. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param category Category of workbook to return. - * @param tags Tags presents on each workbook returned. - * @param sourceId Azure Resource Id that will fetch all linked workbooks. - * @param canFetchContent Flag indicating whether or not to return the full content for each applicable workbook. If - * false, only return summary content for workbooks. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all private workbooks defined within a specified resource group and category as paginated response with - * {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listByResourceGroup(String resourceGroupName, CategoryType category, - List tags, String sourceId, Boolean canFetchContent, Context context) { - return new PagedIterable<>( - listByResourceGroupAsync(resourceGroupName, category, tags, sourceId, canFetchContent, context)); - } - - /** - * Get all private workbooks defined within a specified subscription and category. - * - * @param category Category of workbook to return. - * @param tags Tags presents on each workbook returned. - * @param canFetchContent Flag indicating whether or not to return the full content for each applicable workbook. If - * false, only return summary content for workbooks. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all private workbooks defined within a specified subscription and category along with - * {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listSinglePageAsync(CategoryType category, List tags, - Boolean canFetchContent) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (category == null) { - return Mono.error(new IllegalArgumentException("Parameter category is required and cannot be null.")); - } - final String apiVersion = "2021-03-08"; - final String accept = "application/json"; - String tagsConverted = (tags == null) - ? null - : tags.stream() - .map(paramItemValue -> Objects.toString(paramItemValue, "")) - .collect(Collectors.joining(",")); - return FluxUtil - .withContext(context -> service.list(this.client.getEndpoint(), this.client.getSubscriptionId(), category, - tagsConverted, canFetchContent, apiVersion, accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), - res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Get all private workbooks defined within a specified subscription and category. - * - * @param category Category of workbook to return. - * @param tags Tags presents on each workbook returned. - * @param canFetchContent Flag indicating whether or not to return the full content for each applicable workbook. If - * false, only return summary content for workbooks. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all private workbooks defined within a specified subscription and category along with - * {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listSinglePageAsync(CategoryType category, List tags, - Boolean canFetchContent, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (category == null) { - return Mono.error(new IllegalArgumentException("Parameter category is required and cannot be null.")); - } - final String apiVersion = "2021-03-08"; - final String accept = "application/json"; - String tagsConverted = (tags == null) - ? null - : tags.stream() - .map(paramItemValue -> Objects.toString(paramItemValue, "")) - .collect(Collectors.joining(",")); - context = this.client.mergeContext(context); - return service - .list(this.client.getEndpoint(), this.client.getSubscriptionId(), category, tagsConverted, canFetchContent, - apiVersion, accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } - - /** - * Get all private workbooks defined within a specified subscription and category. - * - * @param category Category of workbook to return. - * @param tags Tags presents on each workbook returned. - * @param canFetchContent Flag indicating whether or not to return the full content for each applicable workbook. If - * false, only return summary content for workbooks. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all private workbooks defined within a specified subscription and category as paginated response with - * {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listAsync(CategoryType category, List tags, Boolean canFetchContent) { - return new PagedFlux<>(() -> listSinglePageAsync(category, tags, canFetchContent), - nextLink -> listBySubscriptionNextSinglePageAsync(nextLink)); - } - - /** - * Get all private workbooks defined within a specified subscription and category. - * - * @param category Category of workbook to return. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all private workbooks defined within a specified subscription and category as paginated response with - * {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listAsync(CategoryType category) { - final List tags = null; - final Boolean canFetchContent = null; - return new PagedFlux<>(() -> listSinglePageAsync(category, tags, canFetchContent), - nextLink -> listBySubscriptionNextSinglePageAsync(nextLink)); - } - - /** - * Get all private workbooks defined within a specified subscription and category. - * - * @param category Category of workbook to return. - * @param tags Tags presents on each workbook returned. - * @param canFetchContent Flag indicating whether or not to return the full content for each applicable workbook. If - * false, only return summary content for workbooks. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all private workbooks defined within a specified subscription and category as paginated response with - * {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listAsync(CategoryType category, List tags, Boolean canFetchContent, - Context context) { - return new PagedFlux<>(() -> listSinglePageAsync(category, tags, canFetchContent, context), - nextLink -> listBySubscriptionNextSinglePageAsync(nextLink, context)); - } - - /** - * Get all private workbooks defined within a specified subscription and category. - * - * @param category Category of workbook to return. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all private workbooks defined within a specified subscription and category as paginated response with - * {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list(CategoryType category) { - final List tags = null; - final Boolean canFetchContent = null; - return new PagedIterable<>(listAsync(category, tags, canFetchContent)); - } - - /** - * Get all private workbooks defined within a specified subscription and category. - * - * @param category Category of workbook to return. - * @param tags Tags presents on each workbook returned. - * @param canFetchContent Flag indicating whether or not to return the full content for each applicable workbook. If - * false, only return summary content for workbooks. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all private workbooks defined within a specified subscription and category as paginated response with - * {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list(CategoryType category, List tags, Boolean canFetchContent, - Context context) { - return new PagedIterable<>(listAsync(category, tags, canFetchContent, context)); - } - - /** - * Get a single private workbook by its resourceName. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a single private workbook by its resourceName along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> getByResourceGroupWithResponseAsync(String resourceGroupName, - String resourceName) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (resourceName == null) { - return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); - } - final String apiVersion = "2021-03-08"; - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.getByResourceGroup(this.client.getEndpoint(), - this.client.getSubscriptionId(), resourceGroupName, resourceName, apiVersion, accept, context)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Get a single private workbook by its resourceName. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a single private workbook by its resourceName along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> getByResourceGroupWithResponseAsync(String resourceGroupName, - String resourceName, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (resourceName == null) { - return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); - } - final String apiVersion = "2021-03-08"; - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.getByResourceGroup(this.client.getEndpoint(), this.client.getSubscriptionId(), resourceGroupName, - resourceName, apiVersion, accept, context); - } - - /** - * Get a single private workbook by its resourceName. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a single private workbook by its resourceName on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono getByResourceGroupAsync(String resourceGroupName, String resourceName) { - return getByResourceGroupWithResponseAsync(resourceGroupName, resourceName) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Get a single private workbook by its resourceName. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a single private workbook by its resourceName along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getByResourceGroupWithResponse(String resourceGroupName, String resourceName, - Context context) { - return getByResourceGroupWithResponseAsync(resourceGroupName, resourceName, context).block(); - } - - /** - * Get a single private workbook by its resourceName. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a single private workbook by its resourceName. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public MyWorkbookInner getByResourceGroup(String resourceGroupName, String resourceName) { - return getByResourceGroupWithResponse(resourceGroupName, resourceName, Context.NONE).getValue(); - } - - /** - * Delete a private workbook. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> deleteWithResponseAsync(String resourceGroupName, String resourceName) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (resourceName == null) { - return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); - } - final String apiVersion = "2021-03-08"; - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.delete(this.client.getEndpoint(), this.client.getSubscriptionId(), - resourceGroupName, resourceName, apiVersion, accept, context)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Delete a private workbook. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> deleteWithResponseAsync(String resourceGroupName, String resourceName, - Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (resourceName == null) { - return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); - } - final String apiVersion = "2021-03-08"; - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.delete(this.client.getEndpoint(), this.client.getSubscriptionId(), resourceGroupName, - resourceName, apiVersion, accept, context); - } - - /** - * Delete a private workbook. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono deleteAsync(String resourceGroupName, String resourceName) { - return deleteWithResponseAsync(resourceGroupName, resourceName).flatMap(ignored -> Mono.empty()); - } - - /** - * Delete a private workbook. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteWithResponse(String resourceGroupName, String resourceName, Context context) { - return deleteWithResponseAsync(resourceGroupName, resourceName, context).block(); - } - - /** - * Delete a private workbook. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void delete(String resourceGroupName, String resourceName) { - deleteWithResponse(resourceGroupName, resourceName, Context.NONE); - } - - /** - * Create a new private workbook. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @param workbookProperties Properties that need to be specified to create a new private workbook. - * @param sourceId Azure Resource Id that will fetch all linked workbooks. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return an Application Insights private workbook definition along with {@link Response} on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> createOrUpdateWithResponseAsync(String resourceGroupName, - String resourceName, MyWorkbookInner workbookProperties, String sourceId) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (resourceName == null) { - return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); - } - if (workbookProperties == null) { - return Mono - .error(new IllegalArgumentException("Parameter workbookProperties is required and cannot be null.")); - } else { - workbookProperties.validate(); - } - final String apiVersion = "2021-03-08"; - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.createOrUpdate(this.client.getEndpoint(), this.client.getSubscriptionId(), - resourceGroupName, resourceName, sourceId, apiVersion, workbookProperties, accept, context)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Create a new private workbook. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @param workbookProperties Properties that need to be specified to create a new private workbook. - * @param sourceId Azure Resource Id that will fetch all linked workbooks. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return an Application Insights private workbook definition along with {@link Response} on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> createOrUpdateWithResponseAsync(String resourceGroupName, - String resourceName, MyWorkbookInner workbookProperties, String sourceId, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (resourceName == null) { - return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); - } - if (workbookProperties == null) { - return Mono - .error(new IllegalArgumentException("Parameter workbookProperties is required and cannot be null.")); - } else { - workbookProperties.validate(); - } - final String apiVersion = "2021-03-08"; - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.createOrUpdate(this.client.getEndpoint(), this.client.getSubscriptionId(), resourceGroupName, - resourceName, sourceId, apiVersion, workbookProperties, accept, context); - } - - /** - * Create a new private workbook. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @param workbookProperties Properties that need to be specified to create a new private workbook. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return an Application Insights private workbook definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono createOrUpdateAsync(String resourceGroupName, String resourceName, - MyWorkbookInner workbookProperties) { - final String sourceId = null; - return createOrUpdateWithResponseAsync(resourceGroupName, resourceName, workbookProperties, sourceId) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Create a new private workbook. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @param workbookProperties Properties that need to be specified to create a new private workbook. - * @param sourceId Azure Resource Id that will fetch all linked workbooks. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return an Application Insights private workbook definition along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createOrUpdateWithResponse(String resourceGroupName, String resourceName, - MyWorkbookInner workbookProperties, String sourceId, Context context) { - return createOrUpdateWithResponseAsync(resourceGroupName, resourceName, workbookProperties, sourceId, context) - .block(); - } - - /** - * Create a new private workbook. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @param workbookProperties Properties that need to be specified to create a new private workbook. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return an Application Insights private workbook definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public MyWorkbookInner createOrUpdate(String resourceGroupName, String resourceName, - MyWorkbookInner workbookProperties) { - final String sourceId = null; - return createOrUpdateWithResponse(resourceGroupName, resourceName, workbookProperties, sourceId, Context.NONE) - .getValue(); - } - - /** - * Updates a private workbook that has already been added. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @param workbookProperties Properties that need to be specified to create a new private workbook. - * @param sourceId Azure Resource Id that will fetch all linked workbooks. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return an Application Insights private workbook definition along with {@link Response} on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> updateWithResponseAsync(String resourceGroupName, String resourceName, - MyWorkbookInner workbookProperties, String sourceId) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (resourceName == null) { - return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); - } - if (workbookProperties == null) { - return Mono - .error(new IllegalArgumentException("Parameter workbookProperties is required and cannot be null.")); - } else { - workbookProperties.validate(); - } - final String apiVersion = "2021-03-08"; - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.update(this.client.getEndpoint(), this.client.getSubscriptionId(), - resourceGroupName, resourceName, sourceId, apiVersion, workbookProperties, accept, context)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Updates a private workbook that has already been added. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @param workbookProperties Properties that need to be specified to create a new private workbook. - * @param sourceId Azure Resource Id that will fetch all linked workbooks. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return an Application Insights private workbook definition along with {@link Response} on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> updateWithResponseAsync(String resourceGroupName, String resourceName, - MyWorkbookInner workbookProperties, String sourceId, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (resourceName == null) { - return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); - } - if (workbookProperties == null) { - return Mono - .error(new IllegalArgumentException("Parameter workbookProperties is required and cannot be null.")); - } else { - workbookProperties.validate(); - } - final String apiVersion = "2021-03-08"; - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.update(this.client.getEndpoint(), this.client.getSubscriptionId(), resourceGroupName, - resourceName, sourceId, apiVersion, workbookProperties, accept, context); - } - - /** - * Updates a private workbook that has already been added. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @param workbookProperties Properties that need to be specified to create a new private workbook. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return an Application Insights private workbook definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono updateAsync(String resourceGroupName, String resourceName, - MyWorkbookInner workbookProperties) { - final String sourceId = null; - return updateWithResponseAsync(resourceGroupName, resourceName, workbookProperties, sourceId) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Updates a private workbook that has already been added. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @param workbookProperties Properties that need to be specified to create a new private workbook. - * @param sourceId Azure Resource Id that will fetch all linked workbooks. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return an Application Insights private workbook definition along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response updateWithResponse(String resourceGroupName, String resourceName, - MyWorkbookInner workbookProperties, String sourceId, Context context) { - return updateWithResponseAsync(resourceGroupName, resourceName, workbookProperties, sourceId, context).block(); - } - - /** - * Updates a private workbook that has already been added. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @param workbookProperties Properties that need to be specified to create a new private workbook. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return an Application Insights private workbook definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public MyWorkbookInner update(String resourceGroupName, String resourceName, MyWorkbookInner workbookProperties) { - final String sourceId = null; - return updateWithResponse(resourceGroupName, resourceName, workbookProperties, sourceId, Context.NONE) - .getValue(); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return workbook list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listByResourceGroupNextSinglePageAsync(String nextLink) { - if (nextLink == null) { - return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - } - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext( - context -> service.listByResourceGroupNext(nextLink, this.client.getEndpoint(), accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), - res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return workbook list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listByResourceGroupNextSinglePageAsync(String nextLink, - Context context) { - if (nextLink == null) { - return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - } - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.listByResourceGroupNext(nextLink, this.client.getEndpoint(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return workbook list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listBySubscriptionNextSinglePageAsync(String nextLink) { - if (nextLink == null) { - return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - } - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext( - context -> service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), - res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorDefinitionException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return workbook list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listBySubscriptionNextSinglePageAsync(String nextLink, - Context context) { - if (nextLink == null) { - return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - } - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/MyWorkbooksImpl.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/MyWorkbooksImpl.java deleted file mode 100644 index 33265f3e3b48..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/MyWorkbooksImpl.java +++ /dev/null @@ -1,152 +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.resourcemanager.applicationinsights.implementation; - -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.SimpleResponse; -import com.azure.core.util.Context; -import com.azure.core.util.logging.ClientLogger; -import com.azure.resourcemanager.applicationinsights.fluent.MyWorkbooksClient; -import com.azure.resourcemanager.applicationinsights.fluent.models.MyWorkbookInner; -import com.azure.resourcemanager.applicationinsights.models.CategoryType; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbook; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbooks; -import java.util.List; - -public final class MyWorkbooksImpl implements MyWorkbooks { - private static final ClientLogger LOGGER = new ClientLogger(MyWorkbooksImpl.class); - - private final MyWorkbooksClient innerClient; - - private final com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager serviceManager; - - public MyWorkbooksImpl(MyWorkbooksClient innerClient, - com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager serviceManager) { - this.innerClient = innerClient; - this.serviceManager = serviceManager; - } - - public PagedIterable listByResourceGroup(String resourceGroupName, CategoryType category) { - PagedIterable inner = this.serviceClient().listByResourceGroup(resourceGroupName, category); - return ResourceManagerUtils.mapPage(inner, inner1 -> new MyWorkbookImpl(inner1, this.manager())); - } - - public PagedIterable listByResourceGroup(String resourceGroupName, CategoryType category, - List tags, String sourceId, Boolean canFetchContent, Context context) { - PagedIterable inner = this.serviceClient() - .listByResourceGroup(resourceGroupName, category, tags, sourceId, canFetchContent, context); - return ResourceManagerUtils.mapPage(inner, inner1 -> new MyWorkbookImpl(inner1, this.manager())); - } - - public PagedIterable list(CategoryType category) { - PagedIterable inner = this.serviceClient().list(category); - return ResourceManagerUtils.mapPage(inner, inner1 -> new MyWorkbookImpl(inner1, this.manager())); - } - - public PagedIterable list(CategoryType category, List tags, Boolean canFetchContent, - Context context) { - PagedIterable inner = this.serviceClient().list(category, tags, canFetchContent, context); - return ResourceManagerUtils.mapPage(inner, inner1 -> new MyWorkbookImpl(inner1, this.manager())); - } - - public Response getByResourceGroupWithResponse(String resourceGroupName, String resourceName, - Context context) { - Response inner - = this.serviceClient().getByResourceGroupWithResponse(resourceGroupName, resourceName, context); - if (inner != null) { - return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), - new MyWorkbookImpl(inner.getValue(), this.manager())); - } else { - return null; - } - } - - public MyWorkbook getByResourceGroup(String resourceGroupName, String resourceName) { - MyWorkbookInner inner = this.serviceClient().getByResourceGroup(resourceGroupName, resourceName); - if (inner != null) { - return new MyWorkbookImpl(inner, this.manager()); - } else { - return null; - } - } - - public Response deleteByResourceGroupWithResponse(String resourceGroupName, String resourceName, - Context context) { - return this.serviceClient().deleteWithResponse(resourceGroupName, resourceName, context); - } - - public void deleteByResourceGroup(String resourceGroupName, String resourceName) { - this.serviceClient().delete(resourceGroupName, resourceName); - } - - public MyWorkbook getById(String id) { - String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); - if (resourceGroupName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); - } - String resourceName = ResourceManagerUtils.getValueFromIdByName(id, "myWorkbooks"); - if (resourceName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'myWorkbooks'.", id))); - } - return this.getByResourceGroupWithResponse(resourceGroupName, resourceName, Context.NONE).getValue(); - } - - public Response getByIdWithResponse(String id, Context context) { - String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); - if (resourceGroupName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); - } - String resourceName = ResourceManagerUtils.getValueFromIdByName(id, "myWorkbooks"); - if (resourceName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'myWorkbooks'.", id))); - } - return this.getByResourceGroupWithResponse(resourceGroupName, resourceName, context); - } - - public void deleteById(String id) { - String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); - if (resourceGroupName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); - } - String resourceName = ResourceManagerUtils.getValueFromIdByName(id, "myWorkbooks"); - if (resourceName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'myWorkbooks'.", id))); - } - this.deleteByResourceGroupWithResponse(resourceGroupName, resourceName, Context.NONE); - } - - public Response deleteByIdWithResponse(String id, Context context) { - String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); - if (resourceGroupName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); - } - String resourceName = ResourceManagerUtils.getValueFromIdByName(id, "myWorkbooks"); - if (resourceName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'myWorkbooks'.", id))); - } - return this.deleteByResourceGroupWithResponse(resourceGroupName, resourceName, context); - } - - private MyWorkbooksClient serviceClient() { - return this.innerClient; - } - - private com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager() { - return this.serviceManager; - } - - public MyWorkbookImpl define(String name) { - return new MyWorkbookImpl(name, this.manager()); - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/WorkbooksClientImpl.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/WorkbooksClientImpl.java index efd09dd082dc..a0437093ad8e 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/WorkbooksClientImpl.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/implementation/WorkbooksClientImpl.java @@ -203,7 +203,7 @@ private Mono> listSinglePageAsync(CategoryType cate if (category == null) { return Mono.error(new IllegalArgumentException("Parameter category is required and cannot be null.")); } - final String apiVersion = "2022-04-01"; + final String apiVersion = "2023-06-01"; final String accept = "application/json"; String tagsConverted = (tags == null) ? null @@ -246,7 +246,7 @@ private Mono> listSinglePageAsync(CategoryType cate if (category == null) { return Mono.error(new IllegalArgumentException("Parameter category is required and cannot be null.")); } - final String apiVersion = "2022-04-01"; + final String apiVersion = "2023-06-01"; final String accept = "application/json"; String tagsConverted = (tags == null) ? null @@ -389,7 +389,7 @@ private Mono> listByResourceGroupSinglePageAsync(St if (category == null) { return Mono.error(new IllegalArgumentException("Parameter category is required and cannot be null.")); } - final String apiVersion = "2022-04-01"; + final String apiVersion = "2023-06-01"; final String accept = "application/json"; String tagsConverted = (tags == null) ? null @@ -439,7 +439,7 @@ private Mono> listByResourceGroupSinglePageAsync(St if (category == null) { return Mono.error(new IllegalArgumentException("Parameter category is required and cannot be null.")); } - final String apiVersion = "2022-04-01"; + final String apiVersion = "2023-06-01"; final String accept = "application/json"; String tagsConverted = (tags == null) ? null @@ -568,7 +568,7 @@ public PagedIterable listByResourceGroup(String resourceGroupName * Get a single workbook by its resourceName. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param canFetchContent Flag indicating whether or not to return the full content for each applicable workbook. If * false, only return summary content for workbooks. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -595,7 +595,7 @@ private Mono> getByResourceGroupWithResponseAsync(String if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2022-04-01"; + final String apiVersion = "2023-06-01"; final String accept = "application/json"; return FluxUtil .withContext( @@ -608,7 +608,7 @@ private Mono> getByResourceGroupWithResponseAsync(String * Get a single workbook by its resourceName. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param canFetchContent Flag indicating whether or not to return the full content for each applicable workbook. If * false, only return summary content for workbooks. * @param context The context to associate with this operation. @@ -636,7 +636,7 @@ private Mono> getByResourceGroupWithResponseAsync(String if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2022-04-01"; + final String apiVersion = "2023-06-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.getByResourceGroup(this.client.getEndpoint(), this.client.getSubscriptionId(), resourceGroupName, @@ -647,7 +647,7 @@ private Mono> getByResourceGroupWithResponseAsync(String * Get a single workbook by its resourceName. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws WorkbookErrorDefinitionException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -664,7 +664,7 @@ private Mono getByResourceGroupAsync(String resourceGroupName, St * Get a single workbook by its resourceName. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param canFetchContent Flag indicating whether or not to return the full content for each applicable workbook. If * false, only return summary content for workbooks. * @param context The context to associate with this operation. @@ -683,7 +683,7 @@ public Response getByResourceGroupWithResponse(String resourceGro * Get a single workbook by its resourceName. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws WorkbookErrorDefinitionException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -700,7 +700,7 @@ public WorkbookInner getByResourceGroup(String resourceGroupName, String resourc * Delete a workbook. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws WorkbookErrorDefinitionException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -723,7 +723,7 @@ private Mono> deleteWithResponseAsync(String resourceGroupName, S if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2022-04-01"; + final String apiVersion = "2023-06-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.delete(this.client.getEndpoint(), this.client.getSubscriptionId(), @@ -735,7 +735,7 @@ private Mono> deleteWithResponseAsync(String resourceGroupName, S * Delete a workbook. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws WorkbookErrorDefinitionException thrown if the request is rejected by server. @@ -760,7 +760,7 @@ private Mono> deleteWithResponseAsync(String resourceGroupName, S if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2022-04-01"; + final String apiVersion = "2023-06-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.delete(this.client.getEndpoint(), this.client.getSubscriptionId(), resourceGroupName, @@ -771,7 +771,7 @@ private Mono> deleteWithResponseAsync(String resourceGroupName, S * Delete a workbook. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws WorkbookErrorDefinitionException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -786,7 +786,7 @@ private Mono deleteAsync(String resourceGroupName, String resourceName) { * Delete a workbook. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws WorkbookErrorDefinitionException thrown if the request is rejected by server. @@ -802,7 +802,7 @@ public Response deleteWithResponse(String resourceGroupName, String resour * Delete a workbook. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws WorkbookErrorDefinitionException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -816,7 +816,7 @@ public void delete(String resourceGroupName, String resourceName) { * Create a new workbook. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param workbookProperties Properties that need to be specified to create a new workbook. * @param sourceId Azure Resource Id that will fetch all linked workbooks. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -848,7 +848,7 @@ private Mono> createOrUpdateWithResponseAsync(String res } else { workbookProperties.validate(); } - final String apiVersion = "2022-04-01"; + final String apiVersion = "2023-06-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.createOrUpdate(this.client.getEndpoint(), this.client.getSubscriptionId(), @@ -860,7 +860,7 @@ private Mono> createOrUpdateWithResponseAsync(String res * Create a new workbook. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param workbookProperties Properties that need to be specified to create a new workbook. * @param sourceId Azure Resource Id that will fetch all linked workbooks. * @param context The context to associate with this operation. @@ -893,7 +893,7 @@ private Mono> createOrUpdateWithResponseAsync(String res } else { workbookProperties.validate(); } - final String apiVersion = "2022-04-01"; + final String apiVersion = "2023-06-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.createOrUpdate(this.client.getEndpoint(), this.client.getSubscriptionId(), resourceGroupName, @@ -904,7 +904,7 @@ private Mono> createOrUpdateWithResponseAsync(String res * Create a new workbook. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param workbookProperties Properties that need to be specified to create a new workbook. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws WorkbookErrorDefinitionException thrown if the request is rejected by server. @@ -923,7 +923,7 @@ private Mono createOrUpdateAsync(String resourceGroupName, String * Create a new workbook. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param workbookProperties Properties that need to be specified to create a new workbook. * @param sourceId Azure Resource Id that will fetch all linked workbooks. * @param context The context to associate with this operation. @@ -943,7 +943,7 @@ public Response createOrUpdateWithResponse(String resourceGroupNa * Create a new workbook. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param workbookProperties Properties that need to be specified to create a new workbook. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws WorkbookErrorDefinitionException thrown if the request is rejected by server. @@ -962,7 +962,7 @@ public WorkbookInner createOrUpdate(String resourceGroupName, String resourceNam * Updates a workbook that has already been added. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param sourceId Azure Resource Id that will fetch all linked workbooks. * @param workbookUpdateParameters Properties that need to be specified to create a new workbook. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -991,7 +991,7 @@ private Mono> updateWithResponseAsync(String resourceGro if (workbookUpdateParameters != null) { workbookUpdateParameters.validate(); } - final String apiVersion = "2022-04-01"; + final String apiVersion = "2023-06-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.update(this.client.getEndpoint(), this.client.getSubscriptionId(), @@ -1003,7 +1003,7 @@ private Mono> updateWithResponseAsync(String resourceGro * Updates a workbook that has already been added. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param sourceId Azure Resource Id that will fetch all linked workbooks. * @param workbookUpdateParameters Properties that need to be specified to create a new workbook. * @param context The context to associate with this operation. @@ -1033,7 +1033,7 @@ private Mono> updateWithResponseAsync(String resourceGro if (workbookUpdateParameters != null) { workbookUpdateParameters.validate(); } - final String apiVersion = "2022-04-01"; + final String apiVersion = "2023-06-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.update(this.client.getEndpoint(), this.client.getSubscriptionId(), resourceGroupName, @@ -1044,7 +1044,7 @@ private Mono> updateWithResponseAsync(String resourceGro * Updates a workbook that has already been added. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws WorkbookErrorDefinitionException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -1062,7 +1062,7 @@ private Mono updateAsync(String resourceGroupName, String resourc * Updates a workbook that has already been added. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param sourceId Azure Resource Id that will fetch all linked workbooks. * @param workbookUpdateParameters Properties that need to be specified to create a new workbook. * @param context The context to associate with this operation. @@ -1082,7 +1082,7 @@ public Response updateWithResponse(String resourceGroupName, Stri * Updates a workbook that has already been added. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws WorkbookErrorDefinitionException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -1100,7 +1100,7 @@ public WorkbookInner update(String resourceGroupName, String resourceName) { * Get the revisions for the workbook defined by its resourceName. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws WorkbookErrorDefinitionException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -1125,7 +1125,7 @@ private Mono> revisionsListSinglePageAsync(String r if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2022-04-01"; + final String apiVersion = "2023-06-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.revisionsList(this.client.getEndpoint(), this.client.getSubscriptionId(), @@ -1139,7 +1139,7 @@ private Mono> revisionsListSinglePageAsync(String r * Get the revisions for the workbook defined by its resourceName. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws WorkbookErrorDefinitionException thrown if the request is rejected by server. @@ -1165,7 +1165,7 @@ private Mono> revisionsListSinglePageAsync(String r if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2022-04-01"; + final String apiVersion = "2023-06-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service @@ -1179,7 +1179,7 @@ private Mono> revisionsListSinglePageAsync(String r * Get the revisions for the workbook defined by its resourceName. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws WorkbookErrorDefinitionException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -1195,7 +1195,7 @@ private PagedFlux revisionsListAsync(String resourceGroupName, St * Get the revisions for the workbook defined by its resourceName. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws WorkbookErrorDefinitionException thrown if the request is rejected by server. @@ -1213,7 +1213,7 @@ private PagedFlux revisionsListAsync(String resourceGroupName, St * Get the revisions for the workbook defined by its resourceName. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws WorkbookErrorDefinitionException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -1229,7 +1229,7 @@ public PagedIterable revisionsList(String resourceGroupName, Stri * Get the revisions for the workbook defined by its resourceName. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws WorkbookErrorDefinitionException thrown if the request is rejected by server. @@ -1246,7 +1246,7 @@ public PagedIterable revisionsList(String resourceGroupName, Stri * Get a single workbook revision defined by its revisionId. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param revisionId The id of the workbook's revision. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws WorkbookErrorDefinitionException thrown if the request is rejected by server. @@ -1275,7 +1275,7 @@ private Mono> revisionGetWithResponseAsync(String resour if (revisionId == null) { return Mono.error(new IllegalArgumentException("Parameter revisionId is required and cannot be null.")); } - final String apiVersion = "2022-04-01"; + final String apiVersion = "2023-06-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.revisionGet(this.client.getEndpoint(), this.client.getSubscriptionId(), @@ -1287,7 +1287,7 @@ private Mono> revisionGetWithResponseAsync(String resour * Get a single workbook revision defined by its revisionId. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param revisionId The id of the workbook's revision. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -1317,7 +1317,7 @@ private Mono> revisionGetWithResponseAsync(String resour if (revisionId == null) { return Mono.error(new IllegalArgumentException("Parameter revisionId is required and cannot be null.")); } - final String apiVersion = "2022-04-01"; + final String apiVersion = "2023-06-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.revisionGet(this.client.getEndpoint(), this.client.getSubscriptionId(), resourceGroupName, @@ -1328,7 +1328,7 @@ private Mono> revisionGetWithResponseAsync(String resour * Get a single workbook revision defined by its revisionId. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param revisionId The id of the workbook's revision. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws WorkbookErrorDefinitionException thrown if the request is rejected by server. @@ -1345,7 +1345,7 @@ private Mono revisionGetAsync(String resourceGroupName, String re * Get a single workbook revision defined by its revisionId. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param revisionId The id of the workbook's revision. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -1363,7 +1363,7 @@ public Response revisionGetWithResponse(String resourceGroupName, * Get a single workbook revision defined by its revisionId. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param revisionId The id of the workbook's revision. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws WorkbookErrorDefinitionException thrown if the request is rejected by server. diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/ComponentLinkedStorageAccounts.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/ComponentLinkedStorageAccounts.java new file mode 100644 index 000000000000..5677b25036dd --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/ComponentLinkedStorageAccounts.java @@ -0,0 +1,182 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.models; + +import com.azure.core.util.Context; +import com.azure.resourcemanager.applicationinsights.fluent.models.ComponentLinkedStorageAccountsInner; + +/** + * An immutable client-side representation of ComponentLinkedStorageAccounts. + */ +public interface ComponentLinkedStorageAccounts { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the linkedStorageAccount property: Linked storage account resource ID. + * + * @return the linkedStorageAccount value. + */ + String linkedStorageAccount(); + + /** + * Gets the name of the resource group. + * + * @return the name of the resource group. + */ + String resourceGroupName(); + + /** + * Gets the inner com.azure.resourcemanager.applicationinsights.fluent.models.ComponentLinkedStorageAccountsInner + * object. + * + * @return the inner object. + */ + ComponentLinkedStorageAccountsInner innerModel(); + + /** + * The entirety of the ComponentLinkedStorageAccounts definition. + */ + interface Definition + extends DefinitionStages.Blank, DefinitionStages.WithParentResource, DefinitionStages.WithCreate { + } + + /** + * The ComponentLinkedStorageAccounts definition stages. + */ + interface DefinitionStages { + /** + * The first stage of the ComponentLinkedStorageAccounts definition. + */ + interface Blank extends WithParentResource { + } + + /** + * The stage of the ComponentLinkedStorageAccounts definition allowing to specify parent resource. + */ + interface WithParentResource { + /** + * Specifies resourceGroupName, resourceName. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @return the next definition stage. + */ + WithCreate withExistingComponent(String resourceGroupName, String resourceName); + } + + /** + * The stage of the ComponentLinkedStorageAccounts definition which contains all the minimum required properties + * for the resource to be created, but also allows for any other optional properties to be specified. + */ + interface WithCreate extends DefinitionStages.WithLinkedStorageAccount { + /** + * Executes the create request. + * + * @return the created resource. + */ + ComponentLinkedStorageAccounts create(); + + /** + * Executes the create request. + * + * @param context The context to associate with this operation. + * @return the created resource. + */ + ComponentLinkedStorageAccounts create(Context context); + } + + /** + * The stage of the ComponentLinkedStorageAccounts definition allowing to specify linkedStorageAccount. + */ + interface WithLinkedStorageAccount { + /** + * Specifies the linkedStorageAccount property: Linked storage account resource ID. + * + * @param linkedStorageAccount Linked storage account resource ID. + * @return the next definition stage. + */ + WithCreate withLinkedStorageAccount(String linkedStorageAccount); + } + } + + /** + * Begins update for the ComponentLinkedStorageAccounts resource. + * + * @return the stage of resource update. + */ + ComponentLinkedStorageAccounts.Update update(); + + /** + * The template for ComponentLinkedStorageAccounts update. + */ + interface Update extends UpdateStages.WithLinkedStorageAccount { + /** + * Executes the update request. + * + * @return the updated resource. + */ + ComponentLinkedStorageAccounts apply(); + + /** + * Executes the update request. + * + * @param context The context to associate with this operation. + * @return the updated resource. + */ + ComponentLinkedStorageAccounts apply(Context context); + } + + /** + * The ComponentLinkedStorageAccounts update stages. + */ + interface UpdateStages { + /** + * The stage of the ComponentLinkedStorageAccounts update allowing to specify linkedStorageAccount. + */ + interface WithLinkedStorageAccount { + /** + * Specifies the linkedStorageAccount property: Linked storage account resource ID. + * + * @param linkedStorageAccount Linked storage account resource ID. + * @return the next definition stage. + */ + Update withLinkedStorageAccount(String linkedStorageAccount); + } + } + + /** + * Refreshes the resource to sync with Azure. + * + * @return the refreshed resource. + */ + ComponentLinkedStorageAccounts refresh(); + + /** + * Refreshes the resource to sync with Azure. + * + * @param context The context to associate with this operation. + * @return the refreshed resource. + */ + ComponentLinkedStorageAccounts refresh(Context context); +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/ComponentLinkedStorageAccountsOperations.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/ComponentLinkedStorageAccountsOperations.java new file mode 100644 index 000000000000..711d7a8e2313 --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/ComponentLinkedStorageAccountsOperations.java @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.models; + +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of ComponentLinkedStorageAccountsOperations. + */ +public interface ComponentLinkedStorageAccountsOperations { + /** + * Returns the current linked storage settings for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Application Insights component linked storage accounts along with {@link Response}. + */ + Response getWithResponse(String resourceGroupName, String resourceName, + StorageType storageType, Context context); + + /** + * Returns the current linked storage settings for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Application Insights component linked storage accounts. + */ + ComponentLinkedStorageAccounts get(String resourceGroupName, String resourceName, StorageType storageType); + + /** + * Delete linked storage accounts for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteWithResponse(String resourceGroupName, String resourceName, StorageType storageType, + Context context); + + /** + * Delete linked storage accounts for an Application Insights component. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param resourceName The name of the Application Insights component resource. + * @param storageType The type of the Application Insights component data source for the linked storage account. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void delete(String resourceGroupName, String resourceName, StorageType storageType); + + /** + * Returns the current linked storage settings for an Application Insights component. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Application Insights component linked storage accounts along with {@link Response}. + */ + ComponentLinkedStorageAccounts getById(String id); + + /** + * Returns the current linked storage settings for an Application Insights component. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Application Insights component linked storage accounts along with {@link Response}. + */ + Response getByIdWithResponse(String id, Context context); + + /** + * Delete linked storage accounts for an Application Insights component. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteById(String id); + + /** + * Delete linked storage accounts for an Application Insights component. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteByIdWithResponse(String id, Context context); + + /** + * Begins definition for a new ComponentLinkedStorageAccounts resource. + * + * @param name resource name. + * @return the first stage of the new ComponentLinkedStorageAccounts definition. + */ + ComponentLinkedStorageAccounts.DefinitionStages.Blank define(StorageType name); +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/ComponentLinkedStorageAccountsPatch.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/ComponentLinkedStorageAccountsPatch.java new file mode 100644 index 000000000000..ecd3b8e3e896 --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/ComponentLinkedStorageAccountsPatch.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. + +package com.azure.resourcemanager.applicationinsights.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.resourcemanager.applicationinsights.fluent.models.LinkedStorageAccountsProperties; +import java.io.IOException; + +/** + * An Application Insights component linked storage accounts patch. + */ +@Fluent +public final class ComponentLinkedStorageAccountsPatch + implements JsonSerializable { + /* + * The properties of the linked storage accounts. + */ + private LinkedStorageAccountsProperties innerProperties; + + /** + * Creates an instance of ComponentLinkedStorageAccountsPatch class. + */ + public ComponentLinkedStorageAccountsPatch() { + } + + /** + * Get the innerProperties property: The properties of the linked storage accounts. + * + * @return the innerProperties value. + */ + private LinkedStorageAccountsProperties innerProperties() { + return this.innerProperties; + } + + /** + * Get the linkedStorageAccount property: Linked storage account resource ID. + * + * @return the linkedStorageAccount value. + */ + public String linkedStorageAccount() { + return this.innerProperties() == null ? null : this.innerProperties().linkedStorageAccount(); + } + + /** + * Set the linkedStorageAccount property: Linked storage account resource ID. + * + * @param linkedStorageAccount the linkedStorageAccount value to set. + * @return the ComponentLinkedStorageAccountsPatch object itself. + */ + public ComponentLinkedStorageAccountsPatch withLinkedStorageAccount(String linkedStorageAccount) { + if (this.innerProperties() == null) { + this.innerProperties = new LinkedStorageAccountsProperties(); + } + this.innerProperties().withLinkedStorageAccount(linkedStorageAccount); + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (innerProperties() != null) { + innerProperties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.innerProperties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ComponentLinkedStorageAccountsPatch from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ComponentLinkedStorageAccountsPatch 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 ComponentLinkedStorageAccountsPatch. + */ + public static ComponentLinkedStorageAccountsPatch fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ComponentLinkedStorageAccountsPatch deserializedComponentLinkedStorageAccountsPatch + = new ComponentLinkedStorageAccountsPatch(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("properties".equals(fieldName)) { + deserializedComponentLinkedStorageAccountsPatch.innerProperties + = LinkedStorageAccountsProperties.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedComponentLinkedStorageAccountsPatch; + }); + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/DeletedWorkbook.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/DeletedWorkbook.java new file mode 100644 index 000000000000..a9609cc8134d --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/DeletedWorkbook.java @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.models; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.applicationinsights.fluent.models.DeletedWorkbookInner; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; + +/** + * An immutable client-side representation of DeletedWorkbook. + */ +public interface DeletedWorkbook { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the location property: The geo-location where the resource lives. + * + * @return the location value. + */ + String location(); + + /** + * Gets the tags property: Resource tags. + * + * @return the tags value. + */ + Map tags(); + + /** + * Gets the kind property: The kind of workbook. Only valid value is shared. + * + * @return the kind value. + */ + WorkbookSharedTypeKind kind(); + + /** + * Gets the etag property: Resource etag. + * + * @return the etag value. + */ + String etag(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the displayName property: The user-defined name (display name) of the workbook. + * + * @return the displayName value. + */ + String displayName(); + + /** + * Gets the serializedData property: Configuration of this particular workbook. Configuration data is a string + * containing valid JSON. + * + * @return the serializedData value. + */ + String serializedData(); + + /** + * Gets the version property: Workbook schema version format, like 'Notebook/1.0', which should match the workbook + * in serializedData. + * + * @return the version value. + */ + String version(); + + /** + * Gets the timeModified property: Date and time in UTC of the last modification that was made to this workbook + * definition. + * + * @return the timeModified value. + */ + OffsetDateTime timeModified(); + + /** + * Gets the category property: Workbook category, as defined by the user at creation time. + * + * @return the category value. + */ + String category(); + + /** + * Gets the tagsPropertiesTags property: Being deprecated, please use the other tags field. + * + * @return the tagsPropertiesTags value. + */ + List tagsPropertiesTags(); + + /** + * Gets the userId property: Unique user id of the specific user that owns this workbook. + * + * @return the userId value. + */ + String userId(); + + /** + * Gets the sourceId property: ResourceId for a source resource. + * + * @return the sourceId value. + */ + String sourceId(); + + /** + * Gets the storageUri property: The resourceId to the storage account when bring your own storage is used. + * + * @return the storageUri value. + */ + String storageUri(); + + /** + * Gets the description property: The description of the workbook. + * + * @return the description value. + */ + String description(); + + /** + * Gets the revision property: The unique revision id for this workbook definition. + * + * @return the revision value. + */ + String revision(); + + /** + * Gets the inner com.azure.resourcemanager.applicationinsights.fluent.models.DeletedWorkbookInner object. + * + * @return the inner object. + */ + DeletedWorkbookInner innerModel(); +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/DeletedWorkbookErrorDefinition.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/DeletedWorkbookErrorDefinition.java new file mode 100644 index 000000000000..dd1f778187d1 --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/DeletedWorkbookErrorDefinition.java @@ -0,0 +1,193 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.management.exception.AdditionalInfo; +import com.azure.core.management.exception.ManagementError; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.List; + +/** + * Error response. + */ +@Immutable +public final class DeletedWorkbookErrorDefinition extends ManagementError { + /* + * Internal error details. + */ + private DeletedWorkbookInnerErrorTrace innererror; + + /* + * Additional info for the error. + */ + private List additionalInfo; + + /* + * Details for the error. + */ + private List details; + + /* + * The target of the error. + */ + private String target; + + /* + * The error message parsed from the body of the http error response. + */ + private String message; + + /* + * The error code parsed from the body of the http error response. + */ + private String code; + + /** + * Creates an instance of DeletedWorkbookErrorDefinition class. + */ + public DeletedWorkbookErrorDefinition() { + } + + /** + * Get the innererror property: Internal error details. + * + * @return the innererror value. + */ + public DeletedWorkbookInnerErrorTrace getInnererror() { + return this.innererror; + } + + /** + * Get the additionalInfo property: Additional info for the error. + * + * @return the additionalInfo value. + */ + @Override + public List getAdditionalInfo() { + return this.additionalInfo; + } + + /** + * Get the details property: Details for the error. + * + * @return the details value. + */ + @Override + public List getDetails() { + return this.details; + } + + /** + * Get the target property: The target of the error. + * + * @return the target value. + */ + @Override + public String getTarget() { + return this.target; + } + + /** + * Get the message property: The error message parsed from the body of the http error response. + * + * @return the message value. + */ + @Override + public String getMessage() { + return this.message; + } + + /** + * Get the code property: The error code parsed from the body of the http error response. + * + * @return the code value. + */ + @Override + public String getCode() { + return this.code; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (getInnererror() != null) { + getInnererror().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of DeletedWorkbookErrorDefinition from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of DeletedWorkbookErrorDefinition 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 DeletedWorkbookErrorDefinition. + */ + public static DeletedWorkbookErrorDefinition fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + JsonReader bufferedReader = reader.bufferObject(); + bufferedReader.nextToken(); + while (bufferedReader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = bufferedReader.getFieldName(); + bufferedReader.nextToken(); + + if ("error".equals(fieldName)) { + return readManagementError(bufferedReader); + } else { + bufferedReader.skipChildren(); + } + } + return readManagementError(bufferedReader.reset()); + }); + } + + private static DeletedWorkbookErrorDefinition readManagementError(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + DeletedWorkbookErrorDefinition deserializedDeletedWorkbookErrorDefinition + = new DeletedWorkbookErrorDefinition(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("code".equals(fieldName)) { + deserializedDeletedWorkbookErrorDefinition.code = reader.getString(); + } else if ("message".equals(fieldName)) { + deserializedDeletedWorkbookErrorDefinition.message = reader.getString(); + } else if ("target".equals(fieldName)) { + deserializedDeletedWorkbookErrorDefinition.target = reader.getString(); + } else if ("details".equals(fieldName)) { + List details = reader.readArray(reader1 -> ManagementError.fromJson(reader1)); + deserializedDeletedWorkbookErrorDefinition.details = details; + } else if ("additionalInfo".equals(fieldName)) { + List additionalInfo = reader.readArray(reader1 -> AdditionalInfo.fromJson(reader1)); + deserializedDeletedWorkbookErrorDefinition.additionalInfo = additionalInfo; + } else if ("innererror".equals(fieldName)) { + deserializedDeletedWorkbookErrorDefinition.innererror + = DeletedWorkbookInnerErrorTrace.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedDeletedWorkbookErrorDefinition; + }); + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/DeletedWorkbookErrorDefinitionException.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/DeletedWorkbookErrorDefinitionException.java new file mode 100644 index 000000000000..b00cee75f584 --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/DeletedWorkbookErrorDefinitionException.java @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.models; + +import com.azure.core.http.HttpResponse; +import com.azure.core.management.exception.ManagementException; + +/** + * Exception thrown for an invalid response with DeletedWorkbookErrorDefinition information. + */ +public final class DeletedWorkbookErrorDefinitionException extends ManagementException { + /** + * Initializes a new instance of the DeletedWorkbookErrorDefinitionException class. + * + * @param message the exception message or the response content if a message is not available. + * @param response the HTTP response. + */ + public DeletedWorkbookErrorDefinitionException(String message, HttpResponse response) { + super(message, response); + } + + /** + * Initializes a new instance of the DeletedWorkbookErrorDefinitionException 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 DeletedWorkbookErrorDefinitionException(String message, HttpResponse response, + DeletedWorkbookErrorDefinition value) { + super(message, response, value); + } + + /** + * {@inheritDoc} + */ + @Override + public DeletedWorkbookErrorDefinition getValue() { + return (DeletedWorkbookErrorDefinition) super.getValue(); + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/DeletedWorkbookInnerErrorTrace.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/DeletedWorkbookInnerErrorTrace.java new file mode 100644 index 000000000000..3ee2439da535 --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/DeletedWorkbookInnerErrorTrace.java @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.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; +import java.util.List; + +/** + * Error details. + */ +@Immutable +public final class DeletedWorkbookInnerErrorTrace implements JsonSerializable { + /* + * detailed error trace + */ + private List trace; + + /** + * Creates an instance of DeletedWorkbookInnerErrorTrace class. + */ + public DeletedWorkbookInnerErrorTrace() { + } + + /** + * Get the trace property: detailed error trace. + * + * @return the trace value. + */ + public List trace() { + return this.trace; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of DeletedWorkbookInnerErrorTrace from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of DeletedWorkbookInnerErrorTrace 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 DeletedWorkbookInnerErrorTrace. + */ + public static DeletedWorkbookInnerErrorTrace fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + DeletedWorkbookInnerErrorTrace deserializedDeletedWorkbookInnerErrorTrace + = new DeletedWorkbookInnerErrorTrace(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("trace".equals(fieldName)) { + List trace = reader.readArray(reader1 -> reader1.getString()); + deserializedDeletedWorkbookInnerErrorTrace.trace = trace; + } else { + reader.skipChildren(); + } + } + + return deserializedDeletedWorkbookInnerErrorTrace; + }); + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/DeletedWorkbookResource.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/DeletedWorkbookResource.java new file mode 100644 index 000000000000..fa5b778dd59c --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/DeletedWorkbookResource.java @@ -0,0 +1,227 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.Resource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.Map; + +/** + * An azure resource object. + */ +@Fluent +public class DeletedWorkbookResource extends Resource { + /* + * The kind of workbook. Only valid value is shared. + */ + private WorkbookSharedTypeKind kind; + + /* + * Resource etag + */ + private String etag; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of DeletedWorkbookResource class. + */ + public DeletedWorkbookResource() { + } + + /** + * Get the kind property: The kind of workbook. Only valid value is shared. + * + * @return the kind value. + */ + public WorkbookSharedTypeKind kind() { + return this.kind; + } + + /** + * Set the kind property: The kind of workbook. Only valid value is shared. + * + * @param kind the kind value to set. + * @return the DeletedWorkbookResource object itself. + */ + public DeletedWorkbookResource withKind(WorkbookSharedTypeKind kind) { + this.kind = kind; + return this; + } + + /** + * Get the etag property: Resource etag. + * + * @return the etag value. + */ + public String etag() { + return this.etag; + } + + /** + * Set the etag property: Resource etag. + * + * @param etag the etag value to set. + * @return the DeletedWorkbookResource object itself. + */ + public DeletedWorkbookResource withEtag(String etag) { + this.etag = etag; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Set the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @param systemData the systemData value to set. + * @return the DeletedWorkbookResource object itself. + */ + DeletedWorkbookResource withSystemData(SystemData systemData) { + this.systemData = systemData; + return this; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * {@inheritDoc} + */ + @Override + public DeletedWorkbookResource withLocation(String location) { + super.withLocation(location); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public DeletedWorkbookResource withTags(Map tags) { + super.withTags(tags); + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("location", location()); + jsonWriter.writeMapField("tags", tags(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString()); + jsonWriter.writeStringField("etag", this.etag); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of DeletedWorkbookResource from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of DeletedWorkbookResource 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 DeletedWorkbookResource. + */ + public static DeletedWorkbookResource fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + DeletedWorkbookResource deserializedDeletedWorkbookResource = new DeletedWorkbookResource(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedDeletedWorkbookResource.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedDeletedWorkbookResource.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedDeletedWorkbookResource.type = reader.getString(); + } else if ("location".equals(fieldName)) { + deserializedDeletedWorkbookResource.withLocation(reader.getString()); + } else if ("tags".equals(fieldName)) { + Map tags = reader.readMap(reader1 -> reader1.getString()); + deserializedDeletedWorkbookResource.withTags(tags); + } else if ("kind".equals(fieldName)) { + deserializedDeletedWorkbookResource.kind = WorkbookSharedTypeKind.fromString(reader.getString()); + } else if ("etag".equals(fieldName)) { + deserializedDeletedWorkbookResource.etag = reader.getString(); + } else if ("systemData".equals(fieldName)) { + deserializedDeletedWorkbookResource.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedDeletedWorkbookResource; + }); + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/DeletedWorkbooks.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/DeletedWorkbooks.java new file mode 100644 index 000000000000..ba04d34ca255 --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/DeletedWorkbooks.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.resourcemanager.applicationinsights.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.Context; +import java.util.List; + +/** + * Resource collection API of DeletedWorkbooks. + */ +public interface DeletedWorkbooks { + /** + * Get all recently deleted Workbooks in a specified subscription. + * + * @throws com.azure.resourcemanager.applicationinsights.models.DeletedWorkbookErrorDefinitionException thrown if + * the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return all recently deleted Workbooks in a specified subscription as paginated response with + * {@link PagedIterable}. + */ + PagedIterable list(); + + /** + * Get all recently deleted Workbooks in a specified subscription. + * + * @param category Category of workbook to return. + * @param tags Tags presents on each workbook returned. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.resourcemanager.applicationinsights.models.DeletedWorkbookErrorDefinitionException thrown if + * the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return all recently deleted Workbooks in a specified subscription as paginated response with + * {@link PagedIterable}. + */ + PagedIterable list(CategoryType category, List tags, Context context); +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/DeletedWorkbooksListResult.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/DeletedWorkbooksListResult.java new file mode 100644 index 000000000000..1718575580a4 --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/DeletedWorkbooksListResult.java @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.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.resourcemanager.applicationinsights.fluent.models.DeletedWorkbookInner; +import java.io.IOException; +import java.util.List; + +/** + * Workbook list result. + */ +@Fluent +public final class DeletedWorkbooksListResult implements JsonSerializable { + /* + * An array of workbooks. + */ + private List value; + + /* + * The nextLink property. + */ + private String nextLink; + + /** + * Creates an instance of DeletedWorkbooksListResult class. + */ + public DeletedWorkbooksListResult() { + } + + /** + * Get the value property: An array of workbooks. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Get the nextLink property: The nextLink property. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The nextLink property. + * + * @param nextLink the nextLink value to set. + * @return the DeletedWorkbooksListResult object itself. + */ + public DeletedWorkbooksListResult withNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() != null) { + value().forEach(e -> e.validate()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of DeletedWorkbooksListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of DeletedWorkbooksListResult 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 DeletedWorkbooksListResult. + */ + public static DeletedWorkbooksListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + DeletedWorkbooksListResult deserializedDeletedWorkbooksListResult = new DeletedWorkbooksListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> DeletedWorkbookInner.fromJson(reader1)); + deserializedDeletedWorkbooksListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedDeletedWorkbooksListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedDeletedWorkbooksListResult; + }); + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/ErrorDefinition.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/ErrorDefinition.java deleted file mode 100644 index 043e7d5a64c2..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/ErrorDefinition.java +++ /dev/null @@ -1,188 +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.resourcemanager.applicationinsights.models; - -import com.azure.core.annotation.Immutable; -import com.azure.core.management.exception.AdditionalInfo; -import com.azure.core.management.exception.ManagementError; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.List; - -/** - * Error response. - */ -@Immutable -public final class ErrorDefinition extends ManagementError { - /* - * Internal error details. - */ - private Object innererror; - - /* - * Additional info for the error. - */ - private List additionalInfo; - - /* - * Details for the error. - */ - private List details; - - /* - * The target of the error. - */ - private String target; - - /* - * The error message parsed from the body of the http error response. - */ - private String message; - - /* - * The error code parsed from the body of the http error response. - */ - private String code; - - /** - * Creates an instance of ErrorDefinition class. - */ - public ErrorDefinition() { - } - - /** - * Get the innererror property: Internal error details. - * - * @return the innererror value. - */ - public Object getInnererror() { - return this.innererror; - } - - /** - * Get the additionalInfo property: Additional info for the error. - * - * @return the additionalInfo value. - */ - @Override - public List getAdditionalInfo() { - return this.additionalInfo; - } - - /** - * Get the details property: Details for the error. - * - * @return the details value. - */ - @Override - public List getDetails() { - return this.details; - } - - /** - * Get the target property: The target of the error. - * - * @return the target value. - */ - @Override - public String getTarget() { - return this.target; - } - - /** - * Get the message property: The error message parsed from the body of the http error response. - * - * @return the message value. - */ - @Override - public String getMessage() { - return this.message; - } - - /** - * Get the code property: The error code parsed from the body of the http error response. - * - * @return the code value. - */ - @Override - public String getCode() { - return this.code; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of ErrorDefinition from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of ErrorDefinition 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 ErrorDefinition. - */ - public static ErrorDefinition fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - JsonReader bufferedReader = reader.bufferObject(); - bufferedReader.nextToken(); - while (bufferedReader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = bufferedReader.getFieldName(); - bufferedReader.nextToken(); - - if ("error".equals(fieldName)) { - return readManagementError(bufferedReader); - } else { - bufferedReader.skipChildren(); - } - } - return readManagementError(bufferedReader.reset()); - }); - } - - private static ErrorDefinition readManagementError(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - ErrorDefinition deserializedErrorDefinition = new ErrorDefinition(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("code".equals(fieldName)) { - deserializedErrorDefinition.code = reader.getString(); - } else if ("message".equals(fieldName)) { - deserializedErrorDefinition.message = reader.getString(); - } else if ("target".equals(fieldName)) { - deserializedErrorDefinition.target = reader.getString(); - } else if ("details".equals(fieldName)) { - List details = reader.readArray(reader1 -> ManagementError.fromJson(reader1)); - deserializedErrorDefinition.details = details; - } else if ("additionalInfo".equals(fieldName)) { - List additionalInfo = reader.readArray(reader1 -> AdditionalInfo.fromJson(reader1)); - deserializedErrorDefinition.additionalInfo = additionalInfo; - } else if ("innererror".equals(fieldName)) { - deserializedErrorDefinition.innererror = reader.readUntyped(); - } else { - reader.skipChildren(); - } - } - - return deserializedErrorDefinition; - }); - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/ErrorDefinitionException.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/ErrorDefinitionException.java deleted file mode 100644 index 1cf5dc461db0..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/ErrorDefinitionException.java +++ /dev/null @@ -1,42 +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.resourcemanager.applicationinsights.models; - -import com.azure.core.http.HttpResponse; -import com.azure.core.management.exception.ManagementException; - -/** - * Exception thrown for an invalid response with ErrorDefinition information. - */ -public final class ErrorDefinitionException extends ManagementException { - /** - * Initializes a new instance of the ErrorDefinitionException class. - * - * @param message the exception message or the response content if a message is not available. - * @param response the HTTP response. - */ - public ErrorDefinitionException(String message, HttpResponse response) { - super(message, response); - } - - /** - * Initializes a new instance of the ErrorDefinitionException 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 ErrorDefinitionException(String message, HttpResponse response, ErrorDefinition value) { - super(message, response, value); - } - - /** - * {@inheritDoc} - */ - @Override - public ErrorDefinition getValue() { - return (ErrorDefinition) super.getValue(); - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/Kind.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/Kind.java deleted file mode 100644 index 74121386d396..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/Kind.java +++ /dev/null @@ -1,51 +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.resourcemanager.applicationinsights.models; - -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * The kind of workbook. Choices are user and shared. - */ -public final class Kind extends ExpandableStringEnum { - /** - * Static value user for Kind. - */ - public static final Kind USER = fromString("user"); - - /** - * Static value shared for Kind. - */ - public static final Kind SHARED = fromString("shared"); - - /** - * Creates a new instance of Kind value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Deprecated - public Kind() { - } - - /** - * Creates or finds a Kind from its string representation. - * - * @param name a name to look for. - * @return the corresponding Kind. - */ - public static Kind fromString(String name) { - return fromString(name, Kind.class); - } - - /** - * Gets known Kind values. - * - * @return known Kind values. - */ - public static Collection values() { - return values(Kind.class); - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/MyWorkbook.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/MyWorkbook.java deleted file mode 100644 index 29061efd542a..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/MyWorkbook.java +++ /dev/null @@ -1,652 +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.resourcemanager.applicationinsights.models; - -import com.azure.core.management.Region; -import com.azure.core.management.SystemData; -import com.azure.core.util.Context; -import com.azure.resourcemanager.applicationinsights.fluent.models.MyWorkbookInner; -import java.util.List; -import java.util.Map; - -/** - * An immutable client-side representation of MyWorkbook. - */ -public interface MyWorkbook { - /** - * Gets the location property: The geo-location where the resource lives. - * - * @return the location value. - */ - String location(); - - /** - * Gets the tags property: Resource tags. - * - * @return the tags value. - */ - Map tags(); - - /** - * Gets the identity property: Identity used for BYOS. - * - * @return the identity value. - */ - MyWorkbookManagedIdentity identity(); - - /** - * Gets the id property: Azure resource Id. - * - * @return the id value. - */ - String id(); - - /** - * Gets the name property: Azure resource name. - * - * @return the name value. - */ - String name(); - - /** - * Gets the type property: Azure resource type. - * - * @return the type value. - */ - String type(); - - /** - * Gets the etag property: Resource etag. - * - * @return the etag value. - */ - Map etag(); - - /** - * Gets the kind property: The kind of workbook. Choices are user and shared. - * - * @return the kind value. - */ - Kind kind(); - - /** - * Gets the systemData property: Metadata pertaining to creation and last modification of the resource. - * - * @return the systemData value. - */ - SystemData systemData(); - - /** - * Gets the displayName property: The user-defined name of the private workbook. - * - * @return the displayName value. - */ - String displayName(); - - /** - * Gets the serializedData property: Configuration of this particular private workbook. Configuration data is a - * string containing valid JSON. - * - * @return the serializedData value. - */ - String serializedData(); - - /** - * Gets the version property: This instance's version of the data model. This can change as new features are added - * that can be marked private workbook. - * - * @return the version value. - */ - String version(); - - /** - * Gets the timeModified property: Date and time in UTC of the last modification that was made to this private - * workbook definition. - * - * @return the timeModified value. - */ - String timeModified(); - - /** - * Gets the category property: Workbook category, as defined by the user at creation time. - * - * @return the category value. - */ - String category(); - - /** - * Gets the tagsPropertiesTags property: A list of 0 or more tags that are associated with this private workbook - * definition. - * - * @return the tagsPropertiesTags value. - */ - List tagsPropertiesTags(); - - /** - * Gets the userId property: Unique user id of the specific user that owns this private workbook. - * - * @return the userId value. - */ - String userId(); - - /** - * Gets the sourceId property: Optional resourceId for a source resource. - * - * @return the sourceId value. - */ - String sourceId(); - - /** - * Gets the storageUri property: BYOS Storage Account URI. - * - * @return the storageUri value. - */ - String storageUri(); - - /** - * Gets the region of the resource. - * - * @return the region of the resource. - */ - Region region(); - - /** - * Gets the name of the resource region. - * - * @return the name of the resource region. - */ - String regionName(); - - /** - * Gets the name of the resource group. - * - * @return the name of the resource group. - */ - String resourceGroupName(); - - /** - * Gets the inner com.azure.resourcemanager.applicationinsights.fluent.models.MyWorkbookInner object. - * - * @return the inner object. - */ - MyWorkbookInner innerModel(); - - /** - * The entirety of the MyWorkbook definition. - */ - interface Definition extends DefinitionStages.Blank, DefinitionStages.WithLocation, - DefinitionStages.WithResourceGroup, DefinitionStages.WithCreate { - } - - /** - * The MyWorkbook definition stages. - */ - interface DefinitionStages { - /** - * The first stage of the MyWorkbook definition. - */ - interface Blank extends WithLocation { - } - - /** - * The stage of the MyWorkbook definition allowing to specify location. - */ - interface WithLocation { - /** - * Specifies the region for the resource. - * - * @param location The geo-location where the resource lives. - * @return the next definition stage. - */ - WithResourceGroup withRegion(Region location); - - /** - * Specifies the region for the resource. - * - * @param location The geo-location where the resource lives. - * @return the next definition stage. - */ - WithResourceGroup withRegion(String location); - } - - /** - * The stage of the MyWorkbook definition allowing to specify parent resource. - */ - interface WithResourceGroup { - /** - * Specifies resourceGroupName. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @return the next definition stage. - */ - WithCreate withExistingResourceGroup(String resourceGroupName); - } - - /** - * The stage of the MyWorkbook definition which contains all the minimum required properties for the resource to - * be created, but also allows for any other optional properties to be specified. - */ - interface WithCreate extends DefinitionStages.WithTags, DefinitionStages.WithIdentity, - DefinitionStages.WithName, DefinitionStages.WithType, DefinitionStages.WithEtag, DefinitionStages.WithKind, - DefinitionStages.WithDisplayName, DefinitionStages.WithSerializedData, DefinitionStages.WithVersion, - DefinitionStages.WithCategory, DefinitionStages.WithTagsPropertiesTags, DefinitionStages.WithSourceId, - DefinitionStages.WithStorageUri, DefinitionStages.WithSourceIdParameter { - /** - * Executes the create request. - * - * @return the created resource. - */ - MyWorkbook create(); - - /** - * Executes the create request. - * - * @param context The context to associate with this operation. - * @return the created resource. - */ - MyWorkbook create(Context context); - } - - /** - * The stage of the MyWorkbook definition allowing to specify tags. - */ - interface WithTags { - /** - * Specifies the tags property: Resource tags.. - * - * @param tags Resource tags. - * @return the next definition stage. - */ - WithCreate withTags(Map tags); - } - - /** - * The stage of the MyWorkbook definition allowing to specify identity. - */ - interface WithIdentity { - /** - * Specifies the identity property: Identity used for BYOS. - * - * @param identity Identity used for BYOS. - * @return the next definition stage. - */ - WithCreate withIdentity(MyWorkbookManagedIdentity identity); - } - - /** - * The stage of the MyWorkbook definition allowing to specify name. - */ - interface WithName { - /** - * Specifies the name property: Azure resource name. - * - * @param name Azure resource name. - * @return the next definition stage. - */ - WithCreate withName(String name); - } - - /** - * The stage of the MyWorkbook definition allowing to specify type. - */ - interface WithType { - /** - * Specifies the type property: Azure resource type. - * - * @param type Azure resource type. - * @return the next definition stage. - */ - WithCreate withType(String type); - } - - /** - * The stage of the MyWorkbook definition allowing to specify etag. - */ - interface WithEtag { - /** - * Specifies the etag property: Resource etag. - * - * @param etag Resource etag. - * @return the next definition stage. - */ - WithCreate withEtag(Map etag); - } - - /** - * The stage of the MyWorkbook definition allowing to specify kind. - */ - interface WithKind { - /** - * Specifies the kind property: The kind of workbook. Choices are user and shared.. - * - * @param kind The kind of workbook. Choices are user and shared. - * @return the next definition stage. - */ - WithCreate withKind(Kind kind); - } - - /** - * The stage of the MyWorkbook definition allowing to specify displayName. - */ - interface WithDisplayName { - /** - * Specifies the displayName property: The user-defined name of the private workbook.. - * - * @param displayName The user-defined name of the private workbook. - * @return the next definition stage. - */ - WithCreate withDisplayName(String displayName); - } - - /** - * The stage of the MyWorkbook definition allowing to specify serializedData. - */ - interface WithSerializedData { - /** - * Specifies the serializedData property: Configuration of this particular private workbook. Configuration - * data is a string containing valid JSON. - * - * @param serializedData Configuration of this particular private workbook. Configuration data is a string - * containing valid JSON. - * @return the next definition stage. - */ - WithCreate withSerializedData(String serializedData); - } - - /** - * The stage of the MyWorkbook definition allowing to specify version. - */ - interface WithVersion { - /** - * Specifies the version property: This instance's version of the data model. This can change as new - * features are added that can be marked private workbook.. - * - * @param version This instance's version of the data model. This can change as new features are added that - * can be marked private workbook. - * @return the next definition stage. - */ - WithCreate withVersion(String version); - } - - /** - * The stage of the MyWorkbook definition allowing to specify category. - */ - interface WithCategory { - /** - * Specifies the category property: Workbook category, as defined by the user at creation time.. - * - * @param category Workbook category, as defined by the user at creation time. - * @return the next definition stage. - */ - WithCreate withCategory(String category); - } - - /** - * The stage of the MyWorkbook definition allowing to specify tagsPropertiesTags. - */ - interface WithTagsPropertiesTags { - /** - * Specifies the tagsPropertiesTags property: A list of 0 or more tags that are associated with this private - * workbook definition. - * - * @param tagsPropertiesTags A list of 0 or more tags that are associated with this private workbook - * definition. - * @return the next definition stage. - */ - WithCreate withTagsPropertiesTags(List tagsPropertiesTags); - } - - /** - * The stage of the MyWorkbook definition allowing to specify sourceId. - */ - interface WithSourceId { - /** - * Specifies the sourceId property: Optional resourceId for a source resource.. - * - * @param sourceId Optional resourceId for a source resource. - * @return the next definition stage. - */ - WithCreate withSourceId(String sourceId); - } - - /** - * The stage of the MyWorkbook definition allowing to specify storageUri. - */ - interface WithStorageUri { - /** - * Specifies the storageUri property: BYOS Storage Account URI. - * - * @param storageUri BYOS Storage Account URI. - * @return the next definition stage. - */ - WithCreate withStorageUri(String storageUri); - } - - /** - * The stage of the MyWorkbook definition allowing to specify sourceId. - */ - interface WithSourceIdParameter { - /** - * Specifies the sourceId property: Azure Resource Id that will fetch all linked workbooks.. - * - * @param sourceId Azure Resource Id that will fetch all linked workbooks. - * @return the next definition stage. - */ - WithCreate withSourceIdParameter(String sourceId); - } - } - - /** - * Begins update for the MyWorkbook resource. - * - * @return the stage of resource update. - */ - MyWorkbook.Update update(); - - /** - * The template for MyWorkbook update. - */ - interface Update extends UpdateStages.WithTags, UpdateStages.WithIdentity, UpdateStages.WithEtag, - UpdateStages.WithKind, UpdateStages.WithDisplayName, UpdateStages.WithSerializedData, UpdateStages.WithVersion, - UpdateStages.WithCategory, UpdateStages.WithTagsPropertiesTags, UpdateStages.WithSourceId, - UpdateStages.WithStorageUri, UpdateStages.WithSourceIdParameter { - /** - * Executes the update request. - * - * @return the updated resource. - */ - MyWorkbook apply(); - - /** - * Executes the update request. - * - * @param context The context to associate with this operation. - * @return the updated resource. - */ - MyWorkbook apply(Context context); - } - - /** - * The MyWorkbook update stages. - */ - interface UpdateStages { - /** - * The stage of the MyWorkbook update allowing to specify tags. - */ - interface WithTags { - /** - * Specifies the tags property: Resource tags.. - * - * @param tags Resource tags. - * @return the next definition stage. - */ - Update withTags(Map tags); - } - - /** - * The stage of the MyWorkbook update allowing to specify identity. - */ - interface WithIdentity { - /** - * Specifies the identity property: Identity used for BYOS. - * - * @param identity Identity used for BYOS. - * @return the next definition stage. - */ - Update withIdentity(MyWorkbookManagedIdentity identity); - } - - /** - * The stage of the MyWorkbook update allowing to specify etag. - */ - interface WithEtag { - /** - * Specifies the etag property: Resource etag. - * - * @param etag Resource etag. - * @return the next definition stage. - */ - Update withEtag(Map etag); - } - - /** - * The stage of the MyWorkbook update allowing to specify kind. - */ - interface WithKind { - /** - * Specifies the kind property: The kind of workbook. Choices are user and shared.. - * - * @param kind The kind of workbook. Choices are user and shared. - * @return the next definition stage. - */ - Update withKind(Kind kind); - } - - /** - * The stage of the MyWorkbook update allowing to specify displayName. - */ - interface WithDisplayName { - /** - * Specifies the displayName property: The user-defined name of the private workbook.. - * - * @param displayName The user-defined name of the private workbook. - * @return the next definition stage. - */ - Update withDisplayName(String displayName); - } - - /** - * The stage of the MyWorkbook update allowing to specify serializedData. - */ - interface WithSerializedData { - /** - * Specifies the serializedData property: Configuration of this particular private workbook. Configuration - * data is a string containing valid JSON. - * - * @param serializedData Configuration of this particular private workbook. Configuration data is a string - * containing valid JSON. - * @return the next definition stage. - */ - Update withSerializedData(String serializedData); - } - - /** - * The stage of the MyWorkbook update allowing to specify version. - */ - interface WithVersion { - /** - * Specifies the version property: This instance's version of the data model. This can change as new - * features are added that can be marked private workbook.. - * - * @param version This instance's version of the data model. This can change as new features are added that - * can be marked private workbook. - * @return the next definition stage. - */ - Update withVersion(String version); - } - - /** - * The stage of the MyWorkbook update allowing to specify category. - */ - interface WithCategory { - /** - * Specifies the category property: Workbook category, as defined by the user at creation time.. - * - * @param category Workbook category, as defined by the user at creation time. - * @return the next definition stage. - */ - Update withCategory(String category); - } - - /** - * The stage of the MyWorkbook update allowing to specify tagsPropertiesTags. - */ - interface WithTagsPropertiesTags { - /** - * Specifies the tagsPropertiesTags property: A list of 0 or more tags that are associated with this private - * workbook definition. - * - * @param tagsPropertiesTags A list of 0 or more tags that are associated with this private workbook - * definition. - * @return the next definition stage. - */ - Update withTagsPropertiesTags(List tagsPropertiesTags); - } - - /** - * The stage of the MyWorkbook update allowing to specify sourceId. - */ - interface WithSourceId { - /** - * Specifies the sourceId property: Optional resourceId for a source resource.. - * - * @param sourceId Optional resourceId for a source resource. - * @return the next definition stage. - */ - Update withSourceId(String sourceId); - } - - /** - * The stage of the MyWorkbook update allowing to specify storageUri. - */ - interface WithStorageUri { - /** - * Specifies the storageUri property: BYOS Storage Account URI. - * - * @param storageUri BYOS Storage Account URI. - * @return the next definition stage. - */ - Update withStorageUri(String storageUri); - } - - /** - * The stage of the MyWorkbook update allowing to specify sourceId. - */ - interface WithSourceIdParameter { - /** - * Specifies the sourceId property: Azure Resource Id that will fetch all linked workbooks.. - * - * @param sourceId Azure Resource Id that will fetch all linked workbooks. - * @return the next definition stage. - */ - Update withSourceIdParameter(String sourceId); - } - } - - /** - * Refreshes the resource to sync with Azure. - * - * @return the refreshed resource. - */ - MyWorkbook refresh(); - - /** - * Refreshes the resource to sync with Azure. - * - * @param context The context to associate with this operation. - * @return the refreshed resource. - */ - MyWorkbook refresh(Context context); -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/MyWorkbookManagedIdentity.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/MyWorkbookManagedIdentity.java deleted file mode 100644 index 69bf0ed27b04..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/MyWorkbookManagedIdentity.java +++ /dev/null @@ -1,127 +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.resourcemanager.applicationinsights.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; - -/** - * Customer Managed Identity. - */ -@Fluent -public final class MyWorkbookManagedIdentity implements JsonSerializable { - /* - * Customer Managed Identity - */ - private MyWorkbookUserAssignedIdentities userAssignedIdentities; - - /* - * The identity type. - */ - private MyWorkbookManagedIdentityType type; - - /** - * Creates an instance of MyWorkbookManagedIdentity class. - */ - public MyWorkbookManagedIdentity() { - } - - /** - * Get the userAssignedIdentities property: Customer Managed Identity. - * - * @return the userAssignedIdentities value. - */ - public MyWorkbookUserAssignedIdentities userAssignedIdentities() { - return this.userAssignedIdentities; - } - - /** - * Set the userAssignedIdentities property: Customer Managed Identity. - * - * @param userAssignedIdentities the userAssignedIdentities value to set. - * @return the MyWorkbookManagedIdentity object itself. - */ - public MyWorkbookManagedIdentity - withUserAssignedIdentities(MyWorkbookUserAssignedIdentities userAssignedIdentities) { - this.userAssignedIdentities = userAssignedIdentities; - return this; - } - - /** - * Get the type property: The identity type. - * - * @return the type value. - */ - public MyWorkbookManagedIdentityType type() { - return this.type; - } - - /** - * Set the type property: The identity type. - * - * @param type the type value to set. - * @return the MyWorkbookManagedIdentity object itself. - */ - public MyWorkbookManagedIdentity withType(MyWorkbookManagedIdentityType type) { - this.type = type; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (userAssignedIdentities() != null) { - userAssignedIdentities().validate(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeJsonField("userAssignedIdentities", this.userAssignedIdentities); - jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of MyWorkbookManagedIdentity from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of MyWorkbookManagedIdentity 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 MyWorkbookManagedIdentity. - */ - public static MyWorkbookManagedIdentity fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - MyWorkbookManagedIdentity deserializedMyWorkbookManagedIdentity = new MyWorkbookManagedIdentity(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("userAssignedIdentities".equals(fieldName)) { - deserializedMyWorkbookManagedIdentity.userAssignedIdentities - = MyWorkbookUserAssignedIdentities.fromJson(reader); - } else if ("type".equals(fieldName)) { - deserializedMyWorkbookManagedIdentity.type - = MyWorkbookManagedIdentityType.fromString(reader.getString()); - } else { - reader.skipChildren(); - } - } - - return deserializedMyWorkbookManagedIdentity; - }); - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/MyWorkbookManagedIdentityType.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/MyWorkbookManagedIdentityType.java deleted file mode 100644 index 7dd2eb8a66bb..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/MyWorkbookManagedIdentityType.java +++ /dev/null @@ -1,51 +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.resourcemanager.applicationinsights.models; - -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * The identity type. - */ -public final class MyWorkbookManagedIdentityType extends ExpandableStringEnum { - /** - * Static value UserAssigned for MyWorkbookManagedIdentityType. - */ - public static final MyWorkbookManagedIdentityType USER_ASSIGNED = fromString("UserAssigned"); - - /** - * Static value None for MyWorkbookManagedIdentityType. - */ - public static final MyWorkbookManagedIdentityType NONE = fromString("None"); - - /** - * Creates a new instance of MyWorkbookManagedIdentityType value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Deprecated - public MyWorkbookManagedIdentityType() { - } - - /** - * Creates or finds a MyWorkbookManagedIdentityType from its string representation. - * - * @param name a name to look for. - * @return the corresponding MyWorkbookManagedIdentityType. - */ - public static MyWorkbookManagedIdentityType fromString(String name) { - return fromString(name, MyWorkbookManagedIdentityType.class); - } - - /** - * Gets known MyWorkbookManagedIdentityType values. - * - * @return known MyWorkbookManagedIdentityType values. - */ - public static Collection values() { - return values(MyWorkbookManagedIdentityType.class); - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/MyWorkbookResource.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/MyWorkbookResource.java deleted file mode 100644 index 52b30ea04c33..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/MyWorkbookResource.java +++ /dev/null @@ -1,236 +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.resourcemanager.applicationinsights.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.management.Resource; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.Map; - -/** - * An azure resource object. - */ -@Fluent -public class MyWorkbookResource extends Resource { - /* - * Identity used for BYOS - */ - private MyWorkbookManagedIdentity identity; - - /* - * Azure resource Id - */ - private String id; - - /* - * Azure resource name - */ - private String name; - - /* - * Azure resource type - */ - private String type; - - /* - * Resource etag - */ - private Map etag; - - /** - * Creates an instance of MyWorkbookResource class. - */ - public MyWorkbookResource() { - } - - /** - * Get the identity property: Identity used for BYOS. - * - * @return the identity value. - */ - public MyWorkbookManagedIdentity identity() { - return this.identity; - } - - /** - * Set the identity property: Identity used for BYOS. - * - * @param identity the identity value to set. - * @return the MyWorkbookResource object itself. - */ - public MyWorkbookResource withIdentity(MyWorkbookManagedIdentity identity) { - this.identity = identity; - return this; - } - - /** - * Get the id property: Azure resource Id. - * - * @return the id value. - */ - public String id() { - return this.id; - } - - /** - * Set the id property: Azure resource Id. - * - * @param id the id value to set. - * @return the MyWorkbookResource object itself. - */ - public MyWorkbookResource withId(String id) { - this.id = id; - return this; - } - - /** - * Get the name property: Azure resource name. - * - * @return the name value. - */ - public String name() { - return this.name; - } - - /** - * Set the name property: Azure resource name. - * - * @param name the name value to set. - * @return the MyWorkbookResource object itself. - */ - public MyWorkbookResource withName(String name) { - this.name = name; - return this; - } - - /** - * Get the type property: Azure resource type. - * - * @return the type value. - */ - public String type() { - return this.type; - } - - /** - * Set the type property: Azure resource type. - * - * @param type the type value to set. - * @return the MyWorkbookResource object itself. - */ - public MyWorkbookResource withType(String type) { - this.type = type; - return this; - } - - /** - * Get the etag property: Resource etag. - * - * @return the etag value. - */ - public Map etag() { - return this.etag; - } - - /** - * Set the etag property: Resource etag. - * - * @param etag the etag value to set. - * @return the MyWorkbookResource object itself. - */ - public MyWorkbookResource withEtag(Map etag) { - this.etag = etag; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public MyWorkbookResource withLocation(String location) { - super.withLocation(location); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public MyWorkbookResource withTags(Map tags) { - super.withTags(tags); - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (identity() != null) { - identity().validate(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("location", location()); - jsonWriter.writeMapField("tags", tags(), (writer, element) -> writer.writeString(element)); - jsonWriter.writeJsonField("identity", this.identity); - jsonWriter.writeStringField("id", this.id); - jsonWriter.writeStringField("name", this.name); - jsonWriter.writeStringField("type", this.type); - jsonWriter.writeMapField("etag", this.etag, (writer, element) -> writer.writeString(element)); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of MyWorkbookResource from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of MyWorkbookResource 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 MyWorkbookResource. - */ - public static MyWorkbookResource fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - MyWorkbookResource deserializedMyWorkbookResource = new MyWorkbookResource(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("location".equals(fieldName)) { - deserializedMyWorkbookResource.withLocation(reader.getString()); - } else if ("tags".equals(fieldName)) { - Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedMyWorkbookResource.withTags(tags); - } else if ("identity".equals(fieldName)) { - deserializedMyWorkbookResource.identity = MyWorkbookManagedIdentity.fromJson(reader); - } else if ("id".equals(fieldName)) { - deserializedMyWorkbookResource.id = reader.getString(); - } else if ("name".equals(fieldName)) { - deserializedMyWorkbookResource.name = reader.getString(); - } else if ("type".equals(fieldName)) { - deserializedMyWorkbookResource.type = reader.getString(); - } else if ("etag".equals(fieldName)) { - Map etag = reader.readMap(reader1 -> reader1.getString()); - deserializedMyWorkbookResource.etag = etag; - } else { - reader.skipChildren(); - } - } - - return deserializedMyWorkbookResource; - }); - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/MyWorkbookUserAssignedIdentities.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/MyWorkbookUserAssignedIdentities.java deleted file mode 100644 index 151e85a8cdbd..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/MyWorkbookUserAssignedIdentities.java +++ /dev/null @@ -1,98 +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.resourcemanager.applicationinsights.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; - -/** - * Customer Managed Identity. - */ -@Immutable -public final class MyWorkbookUserAssignedIdentities implements JsonSerializable { - /* - * The principal ID of resource identity. - */ - private String principalId; - - /* - * The tenant ID of resource. - */ - private String tenantId; - - /** - * Creates an instance of MyWorkbookUserAssignedIdentities class. - */ - public MyWorkbookUserAssignedIdentities() { - } - - /** - * Get the principalId property: The principal ID of resource identity. - * - * @return the principalId value. - */ - public String principalId() { - return this.principalId; - } - - /** - * Get the tenantId property: The tenant ID of resource. - * - * @return the tenantId value. - */ - public String tenantId() { - return this.tenantId; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of MyWorkbookUserAssignedIdentities from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of MyWorkbookUserAssignedIdentities 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 MyWorkbookUserAssignedIdentities. - */ - public static MyWorkbookUserAssignedIdentities fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - MyWorkbookUserAssignedIdentities deserializedMyWorkbookUserAssignedIdentities - = new MyWorkbookUserAssignedIdentities(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("principalId".equals(fieldName)) { - deserializedMyWorkbookUserAssignedIdentities.principalId = reader.getString(); - } else if ("tenantId".equals(fieldName)) { - deserializedMyWorkbookUserAssignedIdentities.tenantId = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedMyWorkbookUserAssignedIdentities; - }); - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/MyWorkbooks.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/MyWorkbooks.java deleted file mode 100644 index 3e2736ee51ff..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/MyWorkbooks.java +++ /dev/null @@ -1,189 +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.resourcemanager.applicationinsights.models; - -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.Response; -import com.azure.core.util.Context; -import java.util.List; - -/** - * Resource collection API of MyWorkbooks. - */ -public interface MyWorkbooks { - /** - * Get all private workbooks defined within a specified resource group and category. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param category Category of workbook to return. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.resourcemanager.applicationinsights.models.ErrorDefinitionException thrown if the request is - * rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all private workbooks defined within a specified resource group and category as paginated response with - * {@link PagedIterable}. - */ - PagedIterable listByResourceGroup(String resourceGroupName, CategoryType category); - - /** - * Get all private workbooks defined within a specified resource group and category. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param category Category of workbook to return. - * @param tags Tags presents on each workbook returned. - * @param sourceId Azure Resource Id that will fetch all linked workbooks. - * @param canFetchContent Flag indicating whether or not to return the full content for each applicable workbook. If - * false, only return summary content for workbooks. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.resourcemanager.applicationinsights.models.ErrorDefinitionException thrown if the request is - * rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all private workbooks defined within a specified resource group and category as paginated response with - * {@link PagedIterable}. - */ - PagedIterable listByResourceGroup(String resourceGroupName, CategoryType category, List tags, - String sourceId, Boolean canFetchContent, Context context); - - /** - * Get all private workbooks defined within a specified subscription and category. - * - * @param category Category of workbook to return. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.resourcemanager.applicationinsights.models.ErrorDefinitionException thrown if the request is - * rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all private workbooks defined within a specified subscription and category as paginated response with - * {@link PagedIterable}. - */ - PagedIterable list(CategoryType category); - - /** - * Get all private workbooks defined within a specified subscription and category. - * - * @param category Category of workbook to return. - * @param tags Tags presents on each workbook returned. - * @param canFetchContent Flag indicating whether or not to return the full content for each applicable workbook. If - * false, only return summary content for workbooks. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.resourcemanager.applicationinsights.models.ErrorDefinitionException thrown if the request is - * rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all private workbooks defined within a specified subscription and category as paginated response with - * {@link PagedIterable}. - */ - PagedIterable list(CategoryType category, List tags, Boolean canFetchContent, Context context); - - /** - * Get a single private workbook by its resourceName. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.resourcemanager.applicationinsights.models.ErrorDefinitionException thrown if the request is - * rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a single private workbook by its resourceName along with {@link Response}. - */ - Response getByResourceGroupWithResponse(String resourceGroupName, String resourceName, Context context); - - /** - * Get a single private workbook by its resourceName. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.resourcemanager.applicationinsights.models.ErrorDefinitionException thrown if the request is - * rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a single private workbook by its resourceName. - */ - MyWorkbook getByResourceGroup(String resourceGroupName, String resourceName); - - /** - * Delete a private workbook. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.resourcemanager.applicationinsights.models.ErrorDefinitionException thrown if the request is - * rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response}. - */ - Response deleteByResourceGroupWithResponse(String resourceGroupName, String resourceName, Context context); - - /** - * Delete a private workbook. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the Application Insights component resource. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.resourcemanager.applicationinsights.models.ErrorDefinitionException thrown if the request is - * rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - void deleteByResourceGroup(String resourceGroupName, String resourceName); - - /** - * Get a single private workbook by its resourceName. - * - * @param id the resource ID. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.resourcemanager.applicationinsights.models.ErrorDefinitionException thrown if the request is - * rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a single private workbook by its resourceName along with {@link Response}. - */ - MyWorkbook getById(String id); - - /** - * Get a single private workbook by its resourceName. - * - * @param id the resource ID. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.resourcemanager.applicationinsights.models.ErrorDefinitionException thrown if the request is - * rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a single private workbook by its resourceName along with {@link Response}. - */ - Response getByIdWithResponse(String id, Context context); - - /** - * Delete a private workbook. - * - * @param id the resource ID. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.resourcemanager.applicationinsights.models.ErrorDefinitionException thrown if the request is - * rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - void deleteById(String id); - - /** - * Delete a private workbook. - * - * @param id the resource ID. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.resourcemanager.applicationinsights.models.ErrorDefinitionException thrown if the request is - * rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response}. - */ - Response deleteByIdWithResponse(String id, Context context); - - /** - * Begins definition for a new MyWorkbook resource. - * - * @param name resource name. - * @return the first stage of the new MyWorkbook definition. - */ - MyWorkbook.DefinitionStages.Blank define(String name); -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/MyWorkbooksListResult.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/MyWorkbooksListResult.java deleted file mode 100644 index 4633efcb9c9a..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/MyWorkbooksListResult.java +++ /dev/null @@ -1,115 +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.resourcemanager.applicationinsights.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.resourcemanager.applicationinsights.fluent.models.MyWorkbookInner; -import java.io.IOException; -import java.util.List; - -/** - * Workbook list result. - */ -@Fluent -public final class MyWorkbooksListResult implements JsonSerializable { - /* - * An array of private workbooks. - */ - private List value; - - /* - * The nextLink property. - */ - private String nextLink; - - /** - * Creates an instance of MyWorkbooksListResult class. - */ - public MyWorkbooksListResult() { - } - - /** - * Get the value property: An array of private workbooks. - * - * @return the value value. - */ - public List value() { - return this.value; - } - - /** - * Get the nextLink property: The nextLink property. - * - * @return the nextLink value. - */ - public String nextLink() { - return this.nextLink; - } - - /** - * Set the nextLink property: The nextLink property. - * - * @param nextLink the nextLink value to set. - * @return the MyWorkbooksListResult object itself. - */ - public MyWorkbooksListResult withNextLink(String nextLink) { - this.nextLink = nextLink; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (value() != null) { - value().forEach(e -> e.validate()); - } - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("nextLink", this.nextLink); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of MyWorkbooksListResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of MyWorkbooksListResult 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 MyWorkbooksListResult. - */ - public static MyWorkbooksListResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - MyWorkbooksListResult deserializedMyWorkbooksListResult = new MyWorkbooksListResult(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - List value = reader.readArray(reader1 -> MyWorkbookInner.fromJson(reader1)); - deserializedMyWorkbooksListResult.value = value; - } else if ("nextLink".equals(fieldName)) { - deserializedMyWorkbooksListResult.nextLink = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedMyWorkbooksListResult; - }); - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/StorageType.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/StorageType.java new file mode 100644 index 000000000000..7435dbea0b8d --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/StorageType.java @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for StorageType. + */ +public final class StorageType extends ExpandableStringEnum { + /** + * Static value ServiceProfiler for StorageType. + */ + public static final StorageType SERVICE_PROFILER = fromString("ServiceProfiler"); + + /** + * Creates a new instance of StorageType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public StorageType() { + } + + /** + * Creates or finds a StorageType from its string representation. + * + * @param name a name to look for. + * @return the corresponding StorageType. + */ + public static StorageType fromString(String name) { + return fromString(name, StorageType.class); + } + + /** + * Gets known StorageType values. + * + * @return known StorageType values. + */ + public static Collection values() { + return values(StorageType.class); + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/Workbooks.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/Workbooks.java index 1e5c6e6ba996..c2539ad6ce30 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/Workbooks.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/Workbooks.java @@ -81,7 +81,7 @@ PagedIterable listByResourceGroup(String resourceGroupName, CategoryTy * Get a single workbook by its resourceName. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param canFetchContent Flag indicating whether or not to return the full content for each applicable workbook. If * false, only return summary content for workbooks. * @param context The context to associate with this operation. @@ -98,7 +98,7 @@ Response getByResourceGroupWithResponse(String resourceGroupName, Stri * Get a single workbook by its resourceName. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.applicationinsights.models.WorkbookErrorDefinitionException thrown if the * request is rejected by server. @@ -111,7 +111,7 @@ Response getByResourceGroupWithResponse(String resourceGroupName, Stri * Delete a workbook. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.applicationinsights.models.WorkbookErrorDefinitionException thrown if the @@ -125,7 +125,7 @@ Response getByResourceGroupWithResponse(String resourceGroupName, Stri * Delete a workbook. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.applicationinsights.models.WorkbookErrorDefinitionException thrown if the * request is rejected by server. @@ -137,7 +137,7 @@ Response getByResourceGroupWithResponse(String resourceGroupName, Stri * Get the revisions for the workbook defined by its resourceName. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.applicationinsights.models.WorkbookErrorDefinitionException thrown if the * request is rejected by server. @@ -151,7 +151,7 @@ Response getByResourceGroupWithResponse(String resourceGroupName, Stri * Get the revisions for the workbook defined by its resourceName. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.applicationinsights.models.WorkbookErrorDefinitionException thrown if the @@ -166,7 +166,7 @@ Response getByResourceGroupWithResponse(String resourceGroupName, Stri * Get a single workbook revision defined by its revisionId. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param revisionId The id of the workbook's revision. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -182,7 +182,7 @@ Response revisionGetWithResponse(String resourceGroupName, String reso * Get a single workbook revision defined by its revisionId. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param resourceName The name of the resource. + * @param resourceName The name of the workbook resource. The value must be an UUID. * @param revisionId The id of the workbook's revision. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.applicationinsights.models.WorkbookErrorDefinitionException thrown if the diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-applicationinsights/proxy-config.json b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-applicationinsights/proxy-config.json index 6db56fbbcbf8..675d5b7d0c6d 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-applicationinsights/proxy-config.json +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-applicationinsights/proxy-config.json @@ -1 +1 @@ -[["com.azure.resourcemanager.applicationinsights.implementation.AnalyticsItemsClientImpl$AnalyticsItemsService"],["com.azure.resourcemanager.applicationinsights.implementation.AnnotationsClientImpl$AnnotationsService"],["com.azure.resourcemanager.applicationinsights.implementation.ApiKeysClientImpl$ApiKeysService"],["com.azure.resourcemanager.applicationinsights.implementation.ComponentAvailableFeaturesClientImpl$ComponentAvailableFeaturesService"],["com.azure.resourcemanager.applicationinsights.implementation.ComponentCurrentBillingFeaturesClientImpl$ComponentCurrentBillingFeaturesService"],["com.azure.resourcemanager.applicationinsights.implementation.ComponentFeatureCapabilitiesClientImpl$ComponentFeatureCapabilitiesService"],["com.azure.resourcemanager.applicationinsights.implementation.ComponentQuotaStatusClientImpl$ComponentQuotaStatusService"],["com.azure.resourcemanager.applicationinsights.implementation.ComponentsClientImpl$ComponentsService"],["com.azure.resourcemanager.applicationinsights.implementation.ExportConfigurationsClientImpl$ExportConfigurationsService"],["com.azure.resourcemanager.applicationinsights.implementation.FavoritesClientImpl$FavoritesService"],["com.azure.resourcemanager.applicationinsights.implementation.LiveTokensClientImpl$LiveTokensService"],["com.azure.resourcemanager.applicationinsights.implementation.MyWorkbooksClientImpl$MyWorkbooksService"],["com.azure.resourcemanager.applicationinsights.implementation.OperationsClientImpl$OperationsService"],["com.azure.resourcemanager.applicationinsights.implementation.ProactiveDetectionConfigurationsClientImpl$ProactiveDetectionConfigurationsService"],["com.azure.resourcemanager.applicationinsights.implementation.WebTestLocationsClientImpl$WebTestLocationsService"],["com.azure.resourcemanager.applicationinsights.implementation.WebTestsClientImpl$WebTestsService"],["com.azure.resourcemanager.applicationinsights.implementation.WorkItemConfigurationsClientImpl$WorkItemConfigurationsService"],["com.azure.resourcemanager.applicationinsights.implementation.WorkbookTemplatesClientImpl$WorkbookTemplatesService"],["com.azure.resourcemanager.applicationinsights.implementation.WorkbooksClientImpl$WorkbooksService"]] \ No newline at end of file +[["com.azure.resourcemanager.applicationinsights.implementation.AnalyticsItemsClientImpl$AnalyticsItemsService"],["com.azure.resourcemanager.applicationinsights.implementation.AnnotationsClientImpl$AnnotationsService"],["com.azure.resourcemanager.applicationinsights.implementation.ApiKeysClientImpl$ApiKeysService"],["com.azure.resourcemanager.applicationinsights.implementation.ComponentAvailableFeaturesClientImpl$ComponentAvailableFeaturesService"],["com.azure.resourcemanager.applicationinsights.implementation.ComponentCurrentBillingFeaturesClientImpl$ComponentCurrentBillingFeaturesService"],["com.azure.resourcemanager.applicationinsights.implementation.ComponentFeatureCapabilitiesClientImpl$ComponentFeatureCapabilitiesService"],["com.azure.resourcemanager.applicationinsights.implementation.ComponentLinkedStorageAccountsOperationsClientImpl$ComponentLinkedStorageAccountsOperationsService"],["com.azure.resourcemanager.applicationinsights.implementation.ComponentQuotaStatusClientImpl$ComponentQuotaStatusService"],["com.azure.resourcemanager.applicationinsights.implementation.ComponentsClientImpl$ComponentsService"],["com.azure.resourcemanager.applicationinsights.implementation.DeletedWorkbooksClientImpl$DeletedWorkbooksService"],["com.azure.resourcemanager.applicationinsights.implementation.ExportConfigurationsClientImpl$ExportConfigurationsService"],["com.azure.resourcemanager.applicationinsights.implementation.FavoritesClientImpl$FavoritesService"],["com.azure.resourcemanager.applicationinsights.implementation.LiveTokensClientImpl$LiveTokensService"],["com.azure.resourcemanager.applicationinsights.implementation.OperationsClientImpl$OperationsService"],["com.azure.resourcemanager.applicationinsights.implementation.ProactiveDetectionConfigurationsClientImpl$ProactiveDetectionConfigurationsService"],["com.azure.resourcemanager.applicationinsights.implementation.WebTestLocationsClientImpl$WebTestLocationsService"],["com.azure.resourcemanager.applicationinsights.implementation.WebTestsClientImpl$WebTestsService"],["com.azure.resourcemanager.applicationinsights.implementation.WorkItemConfigurationsClientImpl$WorkItemConfigurationsService"],["com.azure.resourcemanager.applicationinsights.implementation.WorkbookTemplatesClientImpl$WorkbookTemplatesService"],["com.azure.resourcemanager.applicationinsights.implementation.WorkbooksClientImpl$WorkbooksService"]] \ No newline at end of file diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-applicationinsights/reflect-config.json b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-applicationinsights/reflect-config.json index 505343e25335..69a533961c22 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-applicationinsights/reflect-config.json +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-applicationinsights/reflect-config.json @@ -1 +1 @@ -[{"name":"com.azure.resourcemanager.applicationinsights.models.AnnotationError","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.applicationinsights.models.AnnotationErrorException","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.applicationinsights.models.ErrorDefinition","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.applicationinsights.models.ErrorDefinitionException","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.applicationinsights.models.InnerError","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.applicationinsights.models.WorkItemConfigurationError","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.applicationinsights.models.WorkItemConfigurationErrorException","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.applicationinsights.models.WorkbookErrorDefinition","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.applicationinsights.models.WorkbookErrorDefinitionException","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.applicationinsights.models.WorkbookInnerErrorTrace","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true}] \ No newline at end of file +[{"name":"com.azure.resourcemanager.applicationinsights.models.AnnotationError","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.applicationinsights.models.AnnotationErrorException","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.applicationinsights.models.DeletedWorkbookErrorDefinition","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.applicationinsights.models.DeletedWorkbookErrorDefinitionException","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.applicationinsights.models.DeletedWorkbookInnerErrorTrace","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.applicationinsights.models.InnerError","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.applicationinsights.models.WorkItemConfigurationError","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.applicationinsights.models.WorkItemConfigurationErrorException","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.applicationinsights.models.WorkbookErrorDefinition","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.applicationinsights.models.WorkbookErrorDefinitionException","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.applicationinsights.models.WorkbookInnerErrorTrace","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true}] \ No newline at end of file diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/resources/azure-resourcemanager-applicationinsights.properties b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/resources/azure-resourcemanager-applicationinsights.properties new file mode 100644 index 000000000000..defbd48204e4 --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/resources/azure-resourcemanager-applicationinsights.properties @@ -0,0 +1 @@ +version=${project.version} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/ComponentLinkedStorageAccountsOperationCreateAndUpdateSamples.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/ComponentLinkedStorageAccountsOperationCreateAndUpdateSamples.java new file mode 100644 index 000000000000..9a6eccd77785 --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/ComponentLinkedStorageAccountsOperationCreateAndUpdateSamples.java @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.generated; + +import com.azure.resourcemanager.applicationinsights.models.StorageType; + +/** + * Samples for ComponentLinkedStorageAccountsOperation CreateAndUpdate. + */ +public final class ComponentLinkedStorageAccountsOperationCreateAndUpdateSamples { + /* + * x-ms-original-file: + * specification/applicationinsights/resource-manager/Microsoft.Insights/preview/2020-03-01-preview/examples/ + * ComponentLinkedStorageAccountsCreateAndUpdate.json + */ + /** + * Sample code: ComponentLinkedStorageAccountsCreateAndUpdate. + * + * @param manager Entry point to ApplicationInsightsManager. + */ + public static void componentLinkedStorageAccountsCreateAndUpdate( + com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) { + manager.componentLinkedStorageAccountsOperations() + .define(StorageType.SERVICE_PROFILER) + .withExistingComponent("someResourceGroupName", "myComponent") + .withLinkedStorageAccount( + "/subscriptions/86dc51d3-92ed-4d7e-947a-775ea79b4918/resourceGroups/someResourceGroupName/providers/Microsoft.Storage/storageAccounts/storageaccountname") + .create(); + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/ComponentLinkedStorageAccountsOperationDeleteSamples.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/ComponentLinkedStorageAccountsOperationDeleteSamples.java new file mode 100644 index 000000000000..019797766753 --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/ComponentLinkedStorageAccountsOperationDeleteSamples.java @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.generated; + +import com.azure.resourcemanager.applicationinsights.models.StorageType; + +/** + * Samples for ComponentLinkedStorageAccountsOperation Delete. + */ +public final class ComponentLinkedStorageAccountsOperationDeleteSamples { + /* + * x-ms-original-file: + * specification/applicationinsights/resource-manager/Microsoft.Insights/preview/2020-03-01-preview/examples/ + * ComponentLinkedStorageAccountsDelete.json + */ + /** + * Sample code: ComponentLinkedStorageAccountsDelete. + * + * @param manager Entry point to ApplicationInsightsManager. + */ + public static void componentLinkedStorageAccountsDelete( + com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) { + manager.componentLinkedStorageAccountsOperations() + .deleteWithResponse("someResourceGroupName", "myComponent", StorageType.SERVICE_PROFILER, + com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/ComponentLinkedStorageAccountsOperationGetSamples.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/ComponentLinkedStorageAccountsOperationGetSamples.java new file mode 100644 index 000000000000..1fa7323ecfae --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/ComponentLinkedStorageAccountsOperationGetSamples.java @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.generated; + +import com.azure.resourcemanager.applicationinsights.models.StorageType; + +/** + * Samples for ComponentLinkedStorageAccountsOperation Get. + */ +public final class ComponentLinkedStorageAccountsOperationGetSamples { + /* + * x-ms-original-file: + * specification/applicationinsights/resource-manager/Microsoft.Insights/preview/2020-03-01-preview/examples/ + * ComponentLinkedStorageAccountsGet.json + */ + /** + * Sample code: ComponentLinkedStorageAccountsGet. + * + * @param manager Entry point to ApplicationInsightsManager. + */ + public static void componentLinkedStorageAccountsGet( + com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) { + manager.componentLinkedStorageAccountsOperations() + .getWithResponse("someResourceGroupName", "myComponent", StorageType.SERVICE_PROFILER, + com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/ComponentLinkedStorageAccountsOperationUpdateSamples.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/ComponentLinkedStorageAccountsOperationUpdateSamples.java new file mode 100644 index 000000000000..7c8219dc863c --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/ComponentLinkedStorageAccountsOperationUpdateSamples.java @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.generated; + +import com.azure.resourcemanager.applicationinsights.models.ComponentLinkedStorageAccounts; +import com.azure.resourcemanager.applicationinsights.models.StorageType; + +/** + * Samples for ComponentLinkedStorageAccountsOperation Update. + */ +public final class ComponentLinkedStorageAccountsOperationUpdateSamples { + /* + * x-ms-original-file: + * specification/applicationinsights/resource-manager/Microsoft.Insights/preview/2020-03-01-preview/examples/ + * ComponentLinkedStorageAccountsUpdate.json + */ + /** + * Sample code: ComponentLinkedStorageAccountsUpdate. + * + * @param manager Entry point to ApplicationInsightsManager. + */ + public static void componentLinkedStorageAccountsUpdate( + com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) { + ComponentLinkedStorageAccounts resource = manager.componentLinkedStorageAccountsOperations() + .getWithResponse("someResourceGroupName", "myComponent", StorageType.SERVICE_PROFILER, + com.azure.core.util.Context.NONE) + .getValue(); + resource.update() + .withLinkedStorageAccount( + "/subscriptions/86dc51d3-92ed-4d7e-947a-775ea79b4918/resourceGroups/someResourceGroupName/providers/Microsoft.Storage/storageAccounts/storageaccountname") + .apply(); + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/DeletedWorkbooksListSamples.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/DeletedWorkbooksListSamples.java new file mode 100644 index 000000000000..4a02c5ab775c --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/DeletedWorkbooksListSamples.java @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.generated; + +/** + * Samples for DeletedWorkbooks List. + */ +public final class DeletedWorkbooksListSamples { + /* + * x-ms-original-file: + * specification/applicationinsights/resource-manager/Microsoft.Insights/preview/2024-02-01-preview/examples/ + * DeletedWorkbooksList.json + */ + /** + * Sample code: WorkbooksListSub. + * + * @param manager Entry point to ApplicationInsightsManager. + */ + public static void + workbooksListSub(com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) { + manager.deletedWorkbooks().list(null, null, com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksCreateOrUpdateSamples.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksCreateOrUpdateSamples.java deleted file mode 100644 index 16e516fe4a4a..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksCreateOrUpdateSamples.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.resourcemanager.applicationinsights.generated; - -import com.azure.resourcemanager.applicationinsights.models.Kind; - -/** - * Samples for MyWorkbooks CreateOrUpdate. - */ -public final class MyWorkbooksCreateOrUpdateSamples { - /* - * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2021-03-08/examples/MyWorkbookAdd. - * json - */ - /** - * Sample code: WorkbookAdd. - * - * @param manager Entry point to ApplicationInsightsManager. - */ - public static void workbookAdd(com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) { - manager.myWorkbooks() - .define("deadb33f-8bee-4d3b-a059-9be8dac93960") - .withRegion("west us") - .withExistingResourceGroup("my-resource-group") - .withName("deadb33f-8bee-4d3b-a059-9be8dac93960") - .withKind(Kind.USER) - .withDisplayName("Blah Blah Blah") - .withSerializedData( - "{\"version\":\"Notebook/1.0\",\"items\":[{\"type\":1,\"content\":\"{\"json\":\"## New workbook\\r\\n---\\r\\n\\r\\nWelcome to your new workbook. This area will display text formatted as markdown.\\r\\n\\r\\n\\r\\nWe've included a basic analytics query to get you started. Use the `Edit` button below each section to configure it or add more sections.\"}\",\"halfWidth\":null,\"conditionalVisibility\":null},{\"type\":3,\"content\":\"{\"version\":\"KqlItem/1.0\",\"query\":\"union withsource=TableName *\\n| summarize Count=count() by TableName\\n| render barchart\",\"showQuery\":false,\"size\":1,\"aggregation\":0,\"showAnnotations\":false}\",\"halfWidth\":null,\"conditionalVisibility\":null}],\"isLocked\":false}") - .withCategory("workbook") - .withSourceId( - "/subscriptions/00000000-0000-0000-0000-00000000/resourceGroups/MyGroup/providers/Microsoft.Web/sites/MyTestApp-CodeLens") - .create(); - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksDeleteSamples.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksDeleteSamples.java deleted file mode 100644 index 9c6c17014435..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksDeleteSamples.java +++ /dev/null @@ -1,27 +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.resourcemanager.applicationinsights.generated; - -/** - * Samples for MyWorkbooks Delete. - */ -public final class MyWorkbooksDeleteSamples { - /* - * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2021-03-08/examples/MyWorkbookDelete - * .json - */ - /** - * Sample code: WorkbookDelete. - * - * @param manager Entry point to ApplicationInsightsManager. - */ - public static void - workbookDelete(com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) { - manager.myWorkbooks() - .deleteByResourceGroupWithResponse("my-resource-group", "deadb33f-5e0d-4064-8ebb-1a4ed0313eb2", - com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksGetByResourceGroupSamples.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksGetByResourceGroupSamples.java deleted file mode 100644 index 6d057a0d42e1..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksGetByResourceGroupSamples.java +++ /dev/null @@ -1,26 +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.resourcemanager.applicationinsights.generated; - -/** - * Samples for MyWorkbooks GetByResourceGroup. - */ -public final class MyWorkbooksGetByResourceGroupSamples { - /* - * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2021-03-08/examples/MyWorkbookGet. - * json - */ - /** - * Sample code: WorkbookGet. - * - * @param manager Entry point to ApplicationInsightsManager. - */ - public static void workbookGet(com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) { - manager.myWorkbooks() - .getByResourceGroupWithResponse("my-resource-group", "deadb33f-5e0d-4064-8ebb-1a4ed0313eb2", - com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksListByResourceGroupSamples.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksListByResourceGroupSamples.java deleted file mode 100644 index c0faf4dce20a..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksListByResourceGroupSamples.java +++ /dev/null @@ -1,45 +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.resourcemanager.applicationinsights.generated; - -import com.azure.resourcemanager.applicationinsights.models.CategoryType; - -/** - * Samples for MyWorkbooks ListByResourceGroup. - */ -public final class MyWorkbooksListByResourceGroupSamples { - /* - * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2021-03-08/examples/MyWorkbooksList. - * json - */ - /** - * Sample code: WorkbooksList. - * - * @param manager Entry point to ApplicationInsightsManager. - */ - public static void workbooksList(com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) { - manager.myWorkbooks() - .listByResourceGroup("my-resource-group", CategoryType.WORKBOOK, null, null, null, - com.azure.core.util.Context.NONE); - } - - /* - * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2021-03-08/examples/MyWorkbooksList2 - * .json - */ - /** - * Sample code: WorkbooksList2. - * - * @param manager Entry point to ApplicationInsightsManager. - */ - public static void - workbooksList2(com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) { - manager.myWorkbooks() - .listByResourceGroup("my-resource-group", CategoryType.WORKBOOK, null, null, null, - com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksListSamples.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksListSamples.java deleted file mode 100644 index f8c2243df07a..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksListSamples.java +++ /dev/null @@ -1,41 +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.resourcemanager.applicationinsights.generated; - -import com.azure.resourcemanager.applicationinsights.models.CategoryType; - -/** - * Samples for MyWorkbooks List. - */ -public final class MyWorkbooksListSamples { - /* - * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2021-03-08/examples/MyWorkbooksList. - * json - */ - /** - * Sample code: WorkbooksList. - * - * @param manager Entry point to ApplicationInsightsManager. - */ - public static void workbooksList(com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) { - manager.myWorkbooks().list(CategoryType.WORKBOOK, null, null, com.azure.core.util.Context.NONE); - } - - /* - * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2021-03-08/examples/MyWorkbooksList2 - * .json - */ - /** - * Sample code: WorkbooksList2. - * - * @param manager Entry point to ApplicationInsightsManager. - */ - public static void - workbooksList2(com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) { - manager.myWorkbooks().list(CategoryType.WORKBOOK, null, null, com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksUpdateSamples.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksUpdateSamples.java deleted file mode 100644 index 645008cb0ec9..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksUpdateSamples.java +++ /dev/null @@ -1,41 +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.resourcemanager.applicationinsights.generated; - -import com.azure.resourcemanager.applicationinsights.models.Kind; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbook; - -/** - * Samples for MyWorkbooks Update. - */ -public final class MyWorkbooksUpdateSamples { - /* - * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2021-03-08/examples/MyWorkbookUpdate - * .json - */ - /** - * Sample code: WorkbookUpdate. - * - * @param manager Entry point to ApplicationInsightsManager. - */ - public static void - workbookUpdate(com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) { - MyWorkbook resource = manager.myWorkbooks() - .getByResourceGroupWithResponse("my-resource-group", "deadb33f-5e0d-4064-8ebb-1a4ed0313eb2", - com.azure.core.util.Context.NONE) - .getValue(); - resource.update() - .withKind(Kind.USER) - .withDisplayName("Blah Blah Blah") - .withSerializedData( - "{\"version\":\"Notebook/1.0\",\"items\":[{\"type\":1,\"content\":\"{\"json\":\"## New workbook\\r\\n---\\r\\n\\r\\nWelcome to your new workbook. This area will display text formatted as markdown.\\r\\n\\r\\n\\r\\nWe've included a basic analytics query to get you started. Use the `Edit` button below each section to configure it or add more sections.\"}\",\"halfWidth\":null,\"conditionalVisibility\":null},{\"type\":3,\"content\":\"{\"version\":\"KqlItem/1.0\",\"query\":\"union withsource=TableName *\\n| summarize Count=count() by TableName\\n| render barchart\",\"showQuery\":false,\"size\":1,\"aggregation\":0,\"showAnnotations\":false}\",\"halfWidth\":null,\"conditionalVisibility\":null}],\"isLocked\":false}") - .withVersion("ME") - .withCategory("workbook") - .withSourceId( - "/subscriptions/00000000-0000-0000-0000-00000000/resourceGroups/MyGroup/providers/Microsoft.Web/sites/MyTestApp-CodeLens") - .apply(); - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksCreateOrUpdateSamples.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksCreateOrUpdateSamples.java index 2f6a926d6cd4..9840adbfadc1 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksCreateOrUpdateSamples.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksCreateOrUpdateSamples.java @@ -17,7 +17,7 @@ public final class WorkbooksCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/ + * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2023-06-01/examples/ * WorkbookManagedAdd.json */ /** @@ -51,7 +51,7 @@ public final class WorkbooksCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/WorkbookAdd.json + * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2023-06-01/examples/WorkbookAdd.json */ /** * Sample code: WorkbookAdd. diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksDeleteSamples.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksDeleteSamples.java index 549153b87195..b373a85683ce 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksDeleteSamples.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksDeleteSamples.java @@ -10,7 +10,7 @@ public final class WorkbooksDeleteSamples { /* * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/WorkbookDelete. + * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2023-06-01/examples/WorkbookDelete. * json */ /** diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksGetByResourceGroupSamples.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksGetByResourceGroupSamples.java index 517073c53656..fac1df282bff 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksGetByResourceGroupSamples.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksGetByResourceGroupSamples.java @@ -10,7 +10,7 @@ public final class WorkbooksGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/WorkbookGet1. + * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2023-06-01/examples/WorkbookGet1. * json */ /** @@ -26,7 +26,7 @@ public static void workbookGet1(com.azure.resourcemanager.applicationinsights.Ap /* * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/ + * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2023-06-01/examples/ * WorkbookManagedGet.json */ /** @@ -43,7 +43,7 @@ public static void workbookGet1(com.azure.resourcemanager.applicationinsights.Ap /* * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/WorkbookGet.json + * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2023-06-01/examples/WorkbookGet.json */ /** * Sample code: WorkbookGet. diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksListByResourceGroupSamples.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksListByResourceGroupSamples.java index baef446264b2..c6cd5a84dad2 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksListByResourceGroupSamples.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksListByResourceGroupSamples.java @@ -12,7 +12,7 @@ public final class WorkbooksListByResourceGroupSamples { /* * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/ + * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2023-06-01/examples/ * WorkbooksManagedList.json */ /** @@ -30,7 +30,7 @@ public final class WorkbooksListByResourceGroupSamples { /* * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/WorkbooksList. + * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2023-06-01/examples/WorkbooksList. * json */ /** diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksListSamples.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksListSamples.java index 68cdc3617348..719ee4c0759e 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksListSamples.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksListSamples.java @@ -12,7 +12,7 @@ public final class WorkbooksListSamples { /* * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/WorkbooksListSub + * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2023-06-01/examples/WorkbooksListSub * .json */ /** @@ -27,7 +27,7 @@ public final class WorkbooksListSamples { /* * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/WorkbooksList2. + * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2023-06-01/examples/WorkbooksList2. * json */ /** diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksRevisionGetSamples.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksRevisionGetSamples.java index 45acb3890c34..029bb1887014 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksRevisionGetSamples.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksRevisionGetSamples.java @@ -10,7 +10,7 @@ public final class WorkbooksRevisionGetSamples { /* * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/ + * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2023-06-01/examples/ * WorkbookRevisionGet.json */ /** diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksRevisionsListSamples.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksRevisionsListSamples.java index ec49f727f4f2..1f302665b563 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksRevisionsListSamples.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksRevisionsListSamples.java @@ -10,7 +10,7 @@ public final class WorkbooksRevisionsListSamples { /* * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/ + * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2023-06-01/examples/ * WorkbookRevisionsList.json */ /** diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksUpdateSamples.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksUpdateSamples.java index 182dd3f0568a..5e2605e238fb 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksUpdateSamples.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/samples/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksUpdateSamples.java @@ -12,7 +12,7 @@ public final class WorkbooksUpdateSamples { /* * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/WorkbookUpdate. + * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2023-06-01/examples/WorkbookUpdate. * json */ /** @@ -34,7 +34,7 @@ public final class WorkbooksUpdateSamples { /* * x-ms-original-file: - * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2022-04-01/examples/ + * specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2023-06-01/examples/ * WorkbookManagedUpdate.json */ /** diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnalyticsItemsDeleteWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnalyticsItemsDeleteWithResponseMockTests.java index 2dc937f543d4..dc99c3d7feda 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnalyticsItemsDeleteWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnalyticsItemsDeleteWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.models.ItemScopePath; @@ -26,10 +26,10 @@ public void testDeleteWithResponse() throws Exception { ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); manager.analyticsItems() - .deleteWithResponse("mr", "ddoui", ItemScopePath.MYANALYTICS_ITEMS, "mowaziynknlqwzdv", "iwhxqszdtmaajq", + .deleteWithResponse("exfdeqvhpsylk", "shk", ItemScopePath.MYANALYTICS_ITEMS, "f", "bmxzjrgywwpg", com.azure.core.util.Context.NONE); } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnalyticsItemsGetWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnalyticsItemsGetWithResponseMockTests.java index bf26bb34b59c..9c0ab61ac2aa 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnalyticsItemsGetWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnalyticsItemsGetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.models.ApplicationInsightsComponentAnalyticsItem; @@ -24,25 +24,25 @@ public final class AnalyticsItemsGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"Id\":\"syrq\",\"Name\":\"jqhden\",\"Content\":\"ulkpakd\",\"Version\":\"fmjnnawtqa\",\"Scope\":\"user\",\"Type\":\"function\",\"TimeCreated\":\"p\",\"TimeModified\":\"qoweyirdhl\",\"Properties\":{\"functionAlias\":\"gwflq\"}}"; + = "{\"Id\":\"ihebwtsw\",\"Name\":\"uwfmduragegizvc\",\"Content\":\"elisdjub\",\"Version\":\"bqigkx\",\"Scope\":\"user\",\"Type\":\"recent\",\"TimeCreated\":\"akgacyrcmjdm\",\"TimeModified\":\"of\",\"Properties\":{\"functionAlias\":\"uhrylniofr\"}}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); ApplicationInsightsComponentAnalyticsItem response = manager.analyticsItems() - .getWithResponse("qtobaxkjeyt", "nlb", ItemScopePath.MYANALYTICS_ITEMS, "kwr", "snkq", + .getWithResponse("fdbxiqxeiiqbim", "tmwwi", ItemScopePath.ANALYTICS_ITEMS, "ehfqpofvwbc", "lembnkbwvqvxkdi", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("syrq", response.id()); - Assertions.assertEquals("jqhden", response.name()); - Assertions.assertEquals("ulkpakd", response.content()); + Assertions.assertEquals("ihebwtsw", response.id()); + Assertions.assertEquals("uwfmduragegizvc", response.name()); + Assertions.assertEquals("elisdjub", response.content()); Assertions.assertEquals(ItemScope.USER, response.scope()); - Assertions.assertEquals(ItemType.FUNCTION, response.type()); - Assertions.assertEquals("gwflq", response.properties().functionAlias()); + Assertions.assertEquals(ItemType.RECENT, response.type()); + Assertions.assertEquals("uhrylniofr", response.properties().functionAlias()); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnalyticsItemsListWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnalyticsItemsListWithResponseMockTests.java index bfade7d41fd2..30f569a1e149 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnalyticsItemsListWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnalyticsItemsListWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.models.ApplicationInsightsComponentAnalyticsItem; @@ -26,25 +26,25 @@ public final class AnalyticsItemsListWithResponseMockTests { @Test public void testListWithResponse() throws Exception { String responseStr - = "[{\"Id\":\"inwjizcilngh\",\"Name\":\"h\",\"Content\":\"jtbxqmuluxlx\",\"Version\":\"vnersbycucrw\",\"Scope\":\"shared\",\"Type\":\"recent\",\"TimeCreated\":\"ebrqbsmswziqgfuh\",\"TimeModified\":\"zruswh\",\"Properties\":{\"functionAlias\":\"zznvfbyc\"}},{\"Id\":\"xjww\",\"Name\":\"z\",\"Content\":\"mwmxqhndvnoamld\",\"Version\":\"haohdjhhflzokxc\",\"Scope\":\"user\",\"Type\":\"recent\",\"TimeCreated\":\"jetagltsxoatft\",\"TimeModified\":\"pnpbswveflocc\",\"Properties\":{\"functionAlias\":\"ozihmipgawt\"}},{\"Id\":\"pkyjcxcjxgrytfm\",\"Name\":\"ycilrmcaykggnox\",\"Content\":\"t\",\"Version\":\"sxwpndfcpfnznthj\",\"Scope\":\"user\",\"Type\":\"query\",\"TimeCreated\":\"srxuzvoam\",\"TimeModified\":\"cqiosmgbza\",\"Properties\":{\"functionAlias\":\"qdlyrtl\"}},{\"Id\":\"ap\",\"Name\":\"tz\",\"Content\":\"tbhjmznnbsoqe\",\"Version\":\"larvlagunbtg\",\"Scope\":\"shared\",\"Type\":\"none\",\"TimeCreated\":\"bmhyreeudz\",\"TimeModified\":\"vbpdqmjxlyyzglgo\",\"Properties\":{\"functionAlias\":\"lmjjyuo\"}}]"; + = "[{\"Id\":\"honqjujeickpz\",\"Name\":\"p\",\"Content\":\"mxelnwcltyjed\",\"Version\":\"xm\",\"Scope\":\"shared\",\"Type\":\"recent\",\"TimeCreated\":\"cazuaw\",\"TimeModified\":\"z\",\"Properties\":{\"functionAlias\":\"amwabzxrvxcushsp\"}},{\"Id\":\"ivmxyasfl\",\"Name\":\"sgzwywakoihknsm\",\"Content\":\"lmljhlnymzotq\",\"Version\":\"yuzcbmqqvxmvw\",\"Scope\":\"shared\",\"Type\":\"query\",\"TimeCreated\":\"onsupeujlz\",\"TimeModified\":\"hcvsqltnzoi\",\"Properties\":{\"functionAlias\":\"xgnxfyqonmpqoxwd\"}}]"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); List response = manager.analyticsItems() - .listWithResponse("uwc", "b", ItemScopePath.MYANALYTICS_ITEMS, ItemScope.USER, ItemTypeParameter.NONE, - false, com.azure.core.util.Context.NONE) + .listWithResponse("wjutifdwfmv", "gorqjbttzh", ItemScopePath.MYANALYTICS_ITEMS, ItemScope.SHARED, + ItemTypeParameter.QUERY, false, com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("inwjizcilngh", response.get(0).id()); - Assertions.assertEquals("h", response.get(0).name()); - Assertions.assertEquals("jtbxqmuluxlx", response.get(0).content()); + Assertions.assertEquals("honqjujeickpz", response.get(0).id()); + Assertions.assertEquals("p", response.get(0).name()); + Assertions.assertEquals("mxelnwcltyjed", response.get(0).content()); Assertions.assertEquals(ItemScope.SHARED, response.get(0).scope()); Assertions.assertEquals(ItemType.RECENT, response.get(0).type()); - Assertions.assertEquals("zznvfbyc", response.get(0).properties().functionAlias()); + Assertions.assertEquals("amwabzxrvxcushsp", response.get(0).properties().functionAlias()); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnalyticsItemsPutWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnalyticsItemsPutWithResponseMockTests.java index 652f05aae87e..5c5767b572e0 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnalyticsItemsPutWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnalyticsItemsPutWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.fluent.models.ApplicationInsightsComponentAnalyticsItemInner; @@ -26,32 +26,33 @@ public final class AnalyticsItemsPutWithResponseMockTests { @Test public void testPutWithResponse() throws Exception { String responseStr - = "{\"Id\":\"bydpizqaclnapxb\",\"Name\":\"gn\",\"Content\":\"j\",\"Version\":\"fsmfcttuxuuyi\",\"Scope\":\"shared\",\"Type\":\"function\",\"TimeCreated\":\"quvre\",\"TimeModified\":\"rnjhvsujztczytqj\",\"Properties\":{\"functionAlias\":\"auunfprnjletlx\"}}"; + = "{\"Id\":\"w\",\"Name\":\"wl\",\"Content\":\"jwetnpsihcla\",\"Version\":\"va\",\"Scope\":\"shared\",\"Type\":\"recent\",\"TimeCreated\":\"qqwzt\",\"TimeModified\":\"w\",\"Properties\":{\"functionAlias\":\"hcxwaxfewzjk\"}}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); - ApplicationInsightsComponentAnalyticsItem response = manager.analyticsItems() - .putWithResponse("mpizru", "n", ItemScopePath.MYANALYTICS_ITEMS, - new ApplicationInsightsComponentAnalyticsItemInner().withId("pxiwf") - .withName("gjsaasiixtm") - .withContent("jvkviirhgfgrws") - .withScope(ItemScope.SHARED) - .withType(ItemType.RECENT) - .withProperties( - new ApplicationInsightsComponentAnalyticsItemProperties().withFunctionAlias("gozxw")), - true, com.azure.core.util.Context.NONE) - .getValue(); + ApplicationInsightsComponentAnalyticsItem response + = manager.analyticsItems() + .putWithResponse("gbzjedmstkv", "l", ItemScopePath.MYANALYTICS_ITEMS, + new ApplicationInsightsComponentAnalyticsItemInner().withId("c") + .withName("iznk") + .withContent("f") + .withScope(ItemScope.SHARED) + .withType(ItemType.QUERY) + .withProperties(new ApplicationInsightsComponentAnalyticsItemProperties() + .withFunctionAlias("pfbcunezzcez")), + true, com.azure.core.util.Context.NONE) + .getValue(); - Assertions.assertEquals("bydpizqaclnapxb", response.id()); - Assertions.assertEquals("gn", response.name()); - Assertions.assertEquals("j", response.content()); + Assertions.assertEquals("w", response.id()); + Assertions.assertEquals("wl", response.name()); + Assertions.assertEquals("jwetnpsihcla", response.content()); Assertions.assertEquals(ItemScope.SHARED, response.scope()); - Assertions.assertEquals(ItemType.FUNCTION, response.type()); - Assertions.assertEquals("auunfprnjletlx", response.properties().functionAlias()); + Assertions.assertEquals(ItemType.RECENT, response.type()); + Assertions.assertEquals("hcxwaxfewzjk", response.properties().functionAlias()); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnnotationsCreateWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnnotationsCreateWithResponseMockTests.java index 7d0473de81e8..cd69f931ad94 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnnotationsCreateWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnnotationsCreateWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.fluent.models.AnnotationInner; @@ -23,31 +23,31 @@ public final class AnnotationsCreateWithResponseMockTests { @Test public void testCreateWithResponse() throws Exception { String responseStr - = "[{\"AnnotationName\":\"rqemvvhmxt\",\"Category\":\"jfutacoebj\",\"EventTime\":\"2021-04-28T14:16:46Z\",\"Id\":\"cjznmwcpmg\",\"Properties\":\"adraufactkahzo\",\"RelatedAnnotation\":\"jjziuxxpsh\"}]"; + = "[{\"AnnotationName\":\"nnrwrbiork\",\"Category\":\"lywjhh\",\"EventTime\":\"2021-11-16T09:40:09Z\",\"Id\":\"xmsivfomiloxggdu\",\"Properties\":\"q\",\"RelatedAnnotation\":\"ieuzaofjchvcyyy\"},{\"AnnotationName\":\"gdotcubiipuipwo\",\"Category\":\"nmacj\",\"EventTime\":\"2021-08-08T02:00:14Z\",\"Id\":\"zshq\",\"Properties\":\"impevf\",\"RelatedAnnotation\":\"b\"}]"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); List response = manager.annotations() - .createWithResponse("iqtqzfavyvnq", "ybar", - new AnnotationInner().withAnnotationName("uayjkqa") - .withCategory("gzslesjcbhernnti") - .withEventTime(OffsetDateTime.parse("2021-09-10T03:49:52Z")) - .withId("cv") - .withProperties("uwrbehwagoh") - .withRelatedAnnotation("f"), + .createWithResponse("nnbj", "rxgibbd", + new AnnotationInner().withAnnotationName("confozauors") + .withCategory("okwbqplh") + .withEventTime(OffsetDateTime.parse("2021-05-19T05:27:01Z")) + .withId("uepzl") + .withProperties("hw") + .withRelatedAnnotation("oldweyuqdu"), com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("rqemvvhmxt", response.get(0).annotationName()); - Assertions.assertEquals("jfutacoebj", response.get(0).category()); - Assertions.assertEquals(OffsetDateTime.parse("2021-04-28T14:16:46Z"), response.get(0).eventTime()); - Assertions.assertEquals("cjznmwcpmg", response.get(0).id()); - Assertions.assertEquals("adraufactkahzo", response.get(0).properties()); - Assertions.assertEquals("jjziuxxpsh", response.get(0).relatedAnnotation()); + Assertions.assertEquals("nnrwrbiork", response.get(0).annotationName()); + Assertions.assertEquals("lywjhh", response.get(0).category()); + Assertions.assertEquals(OffsetDateTime.parse("2021-11-16T09:40:09Z"), response.get(0).eventTime()); + Assertions.assertEquals("xmsivfomiloxggdu", response.get(0).id()); + Assertions.assertEquals("q", response.get(0).properties()); + Assertions.assertEquals("ieuzaofjchvcyyy", response.get(0).relatedAnnotation()); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnnotationsDeleteWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnnotationsDeleteWithResponseMockTests.java index d59cbc1e5249..f2f1122192e3 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnnotationsDeleteWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnnotationsDeleteWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import java.nio.charset.StandardCharsets; @@ -25,9 +25,10 @@ public void testDeleteWithResponse() throws Exception { ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); - manager.annotations().deleteWithResponse("eekulfgslqubkwd", "enr", "sutujba", com.azure.core.util.Context.NONE); + manager.annotations() + .deleteWithResponse("rrilbywdxsmic", "wrwfscjfnyns", "qujizdvo", com.azure.core.util.Context.NONE); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnnotationsGetWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnnotationsGetWithResponseMockTests.java index fcec3f4c78ee..bcfc55cfc851 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnnotationsGetWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnnotationsGetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.models.Annotation; @@ -22,24 +22,24 @@ public final class AnnotationsGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "[{\"AnnotationName\":\"dxpgpqchiszepnnb\",\"Category\":\"rxgibbd\",\"EventTime\":\"2021-01-14T17:21:41Z\",\"Id\":\"nfo\",\"Properties\":\"uors\",\"RelatedAnnotation\":\"okwbqplh\"},{\"AnnotationName\":\"nuuepzlrp\",\"Category\":\"zsoldwey\",\"EventTime\":\"2021-03-15T18:22:51Z\",\"Id\":\"vmnnrw\",\"Properties\":\"i\",\"RelatedAnnotation\":\"ktalywjhhgdnhxms\"},{\"AnnotationName\":\"fomiloxgg\",\"Category\":\"fi\",\"EventTime\":\"2021-01-17T17:19:37Z\",\"Id\":\"euzaof\",\"Properties\":\"hvcyyysfg\",\"RelatedAnnotation\":\"tcubiipuipwoqonm\"}]"; + = "[{\"AnnotationName\":\"ksbpimlqoljx\",\"Category\":\"gxxlxsffgcvizq\",\"EventTime\":\"2021-03-28T18:15:03Z\",\"Id\":\"vwlyoup\",\"Properties\":\"fbkjubdyhgkfmi\",\"RelatedAnnotation\":\"g\"},{\"AnnotationName\":\"zfttsttktlahb\",\"Category\":\"ctxtgzukxi\",\"EventTime\":\"2021-11-11T23:01:44Z\",\"Id\":\"tg\",\"Properties\":\"q\",\"RelatedAnnotation\":\"rnxrxcpj\"}]"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); List response = manager.annotations() - .getWithResponse("pjuohminyfl", "orwmduvwpklv", "w", com.azure.core.util.Context.NONE) + .getWithResponse("ytibyow", "blgyavutpthj", "xoi", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("dxpgpqchiszepnnb", response.get(0).annotationName()); - Assertions.assertEquals("rxgibbd", response.get(0).category()); - Assertions.assertEquals(OffsetDateTime.parse("2021-01-14T17:21:41Z"), response.get(0).eventTime()); - Assertions.assertEquals("nfo", response.get(0).id()); - Assertions.assertEquals("uors", response.get(0).properties()); - Assertions.assertEquals("okwbqplh", response.get(0).relatedAnnotation()); + Assertions.assertEquals("ksbpimlqoljx", response.get(0).annotationName()); + Assertions.assertEquals("gxxlxsffgcvizq", response.get(0).category()); + Assertions.assertEquals(OffsetDateTime.parse("2021-03-28T18:15:03Z"), response.get(0).eventTime()); + Assertions.assertEquals("vwlyoup", response.get(0).id()); + Assertions.assertEquals("fbkjubdyhgkfmi", response.get(0).properties()); + Assertions.assertEquals("g", response.get(0).relatedAnnotation()); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnnotationsListMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnnotationsListMockTests.java index 67318b1b3870..1dde03b6f743 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnnotationsListMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/AnnotationsListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.models.Annotation; @@ -22,23 +22,23 @@ public final class AnnotationsListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"AnnotationName\":\"kxtrq\",\"Category\":\"smlmbtxhwgfwsrta\",\"EventTime\":\"2021-07-10T14:18:40Z\",\"Id\":\"zbrhubskhudyg\",\"Properties\":\"okkqfqjbvleo\",\"RelatedAnnotation\":\"ml\"}]}"; + = "{\"value\":[{\"AnnotationName\":\"sutujba\",\"Category\":\"juohminyflnorw\",\"EventTime\":\"2021-02-09T18:43:47Z\",\"Id\":\"wpklvxw\",\"Properties\":\"gdxpg\",\"RelatedAnnotation\":\"chisze\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.annotations() - .list("ktst", "dxeclzedqbcvh", "lhpl", "dqkdlwwqfbu", com.azure.core.util.Context.NONE); + .list("adraufactkahzo", "ajjziuxxpshne", "kulfg", "lqubkwdlen", com.azure.core.util.Context.NONE); - Assertions.assertEquals("kxtrq", response.iterator().next().annotationName()); - Assertions.assertEquals("smlmbtxhwgfwsrta", response.iterator().next().category()); - Assertions.assertEquals(OffsetDateTime.parse("2021-07-10T14:18:40Z"), response.iterator().next().eventTime()); - Assertions.assertEquals("zbrhubskhudyg", response.iterator().next().id()); - Assertions.assertEquals("okkqfqjbvleo", response.iterator().next().properties()); - Assertions.assertEquals("ml", response.iterator().next().relatedAnnotation()); + Assertions.assertEquals("sutujba", response.iterator().next().annotationName()); + Assertions.assertEquals("juohminyflnorw", response.iterator().next().category()); + Assertions.assertEquals(OffsetDateTime.parse("2021-02-09T18:43:47Z"), response.iterator().next().eventTime()); + Assertions.assertEquals("wpklvxw", response.iterator().next().id()); + Assertions.assertEquals("gdxpg", response.iterator().next().properties()); + Assertions.assertEquals("chisze", response.iterator().next().relatedAnnotation()); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ApplicationInsightsComponentProactiveDetectionConfigurationInnerTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ApplicationInsightsComponentProactiveDetectionConfigurationInnerTests.java index 245b1a7428b4..6993344ad9e3 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ApplicationInsightsComponentProactiveDetectionConfigurationInnerTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ApplicationInsightsComponentProactiveDetectionConfigurationInnerTests.java @@ -14,7 +14,7 @@ public final class ApplicationInsightsComponentProactiveDetectionConfigurationIn @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ApplicationInsightsComponentProactiveDetectionConfigurationInner model = BinaryData.fromString( - "{\"Name\":\"kdkexxp\",\"Enabled\":false,\"SendEmailsToSubscriptionOwners\":true,\"CustomEmails\":[\"c\"],\"LastUpdatedTime\":\"pg\",\"RuleDefinitions\":{\"Name\":\"ocjjxhvpmouexh\",\"DisplayName\":\"xibqeojnx\",\"Description\":\"zvddntwndeicbtwn\",\"HelpUrl\":\"aoqvuh\",\"IsHidden\":true,\"IsEnabledByDefault\":false,\"IsInPreview\":false,\"SupportsEmailNotifications\":true}}") + "{\"name\":\"kdkexxp\",\"enabled\":false,\"sendEmailsToSubscriptionOwners\":true,\"customEmails\":[\"c\"],\"lastUpdatedTime\":\"pg\",\"ruleDefinitions\":{\"Name\":\"ocjjxhvpmouexh\",\"DisplayName\":\"xibqeojnx\",\"Description\":\"zvddntwndeicbtwn\",\"HelpUrl\":\"aoqvuh\",\"IsHidden\":true,\"IsEnabledByDefault\":false,\"IsInPreview\":false,\"SupportsEmailNotifications\":true}}") .toObject(ApplicationInsightsComponentProactiveDetectionConfigurationInner.class); Assertions.assertEquals("kdkexxp", model.name()); Assertions.assertEquals(false, model.enabled()); diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentAvailableFeaturesGetWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentAvailableFeaturesGetWithResponseMockTests.java index 22bbf578bca8..6ce854fb0da2 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentAvailableFeaturesGetWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentAvailableFeaturesGetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.models.ApplicationInsightsComponentAvailableFeatures; @@ -20,17 +20,17 @@ public final class ComponentAvailableFeaturesGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"Result\":[{\"FeatureName\":\"qgnjdgkynscli\",\"MeterId\":\"zvhxnk\",\"MeterRateFrequency\":\"tkubotppn\",\"ResouceId\":\"xz\",\"IsHidden\":true,\"Capabilities\":[{\"Name\":\"bbc\",\"Description\":\"qagt\",\"Value\":\"dhlfkqojpykvgt\",\"Unit\":\"cnifm\",\"MeterId\":\"sdymbrn\",\"MeterRateFrequency\":\"u\"},{\"Name\":\"prafwgckhoc\",\"Description\":\"d\",\"Value\":\"fwafqrouda\",\"Unit\":\"avehhrvkbunzo\",\"MeterId\":\"dhcxgkmoy\",\"MeterRateFrequency\":\"dyuib\"}],\"Title\":\"fdn\",\"IsMainFeature\":true,\"SupportedAddonFeatures\":\"vfvfcj\"},{\"FeatureName\":\"eoisrvhmgor\",\"MeterId\":\"ukiscvwmzhw\",\"MeterRateFrequency\":\"efaxvxilc\",\"ResouceId\":\"gnhnzeyq\",\"IsHidden\":true,\"Capabilities\":[{\"Name\":\"qlqhycavodg\",\"Description\":\"dbeesmie\",\"Value\":\"lrariaawiu\",\"Unit\":\"ydwqfbylyrf\",\"MeterId\":\"agt\",\"MeterRateFrequency\":\"jocqwogfnzjvusf\"},{\"Name\":\"dmozu\",\"Description\":\"lfsbtkadpysow\",\"Value\":\"tgkbugrjqctojc\",\"Unit\":\"sofieypefojyqd\",\"MeterId\":\"u\",\"MeterRateFrequency\":\"cp\"},{\"Name\":\"wkhihihlhzdsqt\",\"Description\":\"s\",\"Value\":\"nowc\",\"Unit\":\"fgmvecactxmwo\",\"MeterId\":\"yowc\",\"MeterRateFrequency\":\"qovekqvgqou\"}],\"Title\":\"fzmpjwyivq\",\"IsMainFeature\":false,\"SupportedAddonFeatures\":\"cvhrfsp\"},{\"FeatureName\":\"agr\",\"MeterId\":\"ikteusqczkvyk\",\"MeterRateFrequency\":\"ubyjaffmmf\",\"ResouceId\":\"cqc\",\"IsHidden\":false,\"Capabilities\":[{\"Name\":\"brta\",\"Description\":\"etttwgdslqxihhr\",\"Value\":\"oi\",\"Unit\":\"seypxiutcxapz\",\"MeterId\":\"rpetogebjoxsl\",\"MeterRateFrequency\":\"nhl\"},{\"Name\":\"rqnkkzjcjbtr\",\"Description\":\"ehvvib\",\"Value\":\"jj\",\"Unit\":\"oqbeitpkxzt\",\"MeterId\":\"ob\",\"MeterRateFrequency\":\"ft\"},{\"Name\":\"gfcwqmpimaqxzhem\",\"Description\":\"h\",\"Value\":\"uj\",\"Unit\":\"t\",\"MeterId\":\"ozzwculkba\",\"MeterRateFrequency\":\"fajnjwltlwtjjguk\"}],\"Title\":\"lhsnvkcdmx\",\"IsMainFeature\":true,\"SupportedAddonFeatures\":\"aimlnwiaaom\"},{\"FeatureName\":\"weazul\",\"MeterId\":\"ethwwnpjhlfz\",\"MeterRateFrequency\":\"pchwa\",\"ResouceId\":\"bousn\",\"IsHidden\":true,\"Capabilities\":[{\"Name\":\"wetwlyxgncxykxh\",\"Description\":\"h\",\"Value\":\"mmbcxfhbcp\",\"Unit\":\"xvxcjzhq\",\"MeterId\":\"xfpxtgqscja\",\"MeterRateFrequency\":\"t\"},{\"Name\":\"hdqazkmtgguwp\",\"Description\":\"r\",\"Value\":\"civmmg\",\"Unit\":\"cf\",\"MeterId\":\"rxgkne\",\"MeterRateFrequency\":\"yinzqodfvpgs\"},{\"Name\":\"xgsg\",\"Description\":\"fgzdjtxvz\",\"Value\":\"bqvgaqv\",\"Unit\":\"a\",\"MeterId\":\"qusrdvetnws\",\"MeterRateFrequency\":\"utnw\"},{\"Name\":\"uycvuzhyrmewip\",\"Description\":\"ekdxuku\",\"Value\":\"sjjxundxgketw\",\"Unit\":\"hzjhf\",\"MeterId\":\"hvvmuvgpmun\",\"MeterRateFrequency\":\"sx\"}],\"Title\":\"hfbuzjyihsasbhud\",\"IsMainFeature\":true,\"SupportedAddonFeatures\":\"yue\"}]}"; + = "{\"Result\":[{\"FeatureName\":\"fukiscvwmzhw\",\"MeterId\":\"efaxvxilc\",\"MeterRateFrequency\":\"gnhnzeyq\",\"ResouceId\":\"jjfzqlqhycavo\",\"IsHidden\":true,\"Capabilities\":[{\"Name\":\"ee\",\"Description\":\"ieknl\",\"Value\":\"riaa\",\"Unit\":\"uagydwqfbylyrf\",\"MeterId\":\"agt\",\"MeterRateFrequency\":\"jocqwogfnzjvusf\"},{\"Name\":\"dmozu\",\"Description\":\"lfsbtkadpysow\",\"Value\":\"tgkbugrjqctojc\",\"Unit\":\"sofieypefojyqd\",\"MeterId\":\"u\",\"MeterRateFrequency\":\"cp\"}],\"Title\":\"wkhihihlhzdsqt\",\"IsMainFeature\":false,\"SupportedAddonFeatures\":\"gnowcjhfgmveca\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); ApplicationInsightsComponentAvailableFeatures response = manager.componentAvailableFeatures() - .getWithResponse("o", "krsgsgb", com.azure.core.util.Context.NONE) + .getWithResponse("ydvfvfcjnae", "isrvhm", com.azure.core.util.Context.NONE) .getValue(); } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentCurrentBillingFeaturesGetWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentCurrentBillingFeaturesGetWithResponseMockTests.java index c74b5ffed675..fd5de177b2d7 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentCurrentBillingFeaturesGetWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentCurrentBillingFeaturesGetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.models.ApplicationInsightsComponentBillingFeatures; @@ -21,23 +21,23 @@ public final class ComponentCurrentBillingFeaturesGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"DataVolumeCap\":{\"Cap\":39.890907,\"ResetTime\":1058689711,\"WarningThreshold\":698504930,\"StopSendNotificationWhenHitThreshold\":false,\"StopSendNotificationWhenHitCap\":true,\"MaxHistoryCap\":53.721916},\"CurrentBillingFeatures\":[\"twkuziycs\",\"evufuztck\",\"yhjtqedcgzu\"]}"; + = "{\"DataVolumeCap\":{\"Cap\":92.44658,\"ResetTime\":520694685,\"WarningThreshold\":1829917026,\"StopSendNotificationWhenHitThreshold\":true,\"StopSendNotificationWhenHitCap\":true,\"MaxHistoryCap\":53.99011},\"CurrentBillingFeatures\":[\"jazysdzhezwwvaiq\"]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); ApplicationInsightsComponentBillingFeatures response = manager.componentCurrentBillingFeatures() - .getWithResponse("est", "jlxr", com.azure.core.util.Context.NONE) + .getWithResponse("khyawfvjlboxqv", "jlmxhomdynhd", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals(39.890907F, response.dataVolumeCap().cap()); - Assertions.assertEquals(698504930, response.dataVolumeCap().warningThreshold()); - Assertions.assertEquals(false, response.dataVolumeCap().stopSendNotificationWhenHitThreshold()); + Assertions.assertEquals(92.44658F, response.dataVolumeCap().cap()); + Assertions.assertEquals(1829917026, response.dataVolumeCap().warningThreshold()); + Assertions.assertEquals(true, response.dataVolumeCap().stopSendNotificationWhenHitThreshold()); Assertions.assertEquals(true, response.dataVolumeCap().stopSendNotificationWhenHitCap()); - Assertions.assertEquals("twkuziycs", response.currentBillingFeatures().get(0)); + Assertions.assertEquals("jazysdzhezwwvaiq", response.currentBillingFeatures().get(0)); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentCurrentBillingFeaturesUpdateWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentCurrentBillingFeaturesUpdateWithResponseMockTests.java index 4c2adb80a835..d34093a354e9 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentCurrentBillingFeaturesUpdateWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentCurrentBillingFeaturesUpdateWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.fluent.models.ApplicationInsightsComponentBillingFeaturesInner; @@ -24,30 +24,30 @@ public final class ComponentCurrentBillingFeaturesUpdateWithResponseMockTests { @Test public void testUpdateWithResponse() throws Exception { String responseStr - = "{\"DataVolumeCap\":{\"Cap\":2.3994863,\"ResetTime\":1221508981,\"WarningThreshold\":1691117977,\"StopSendNotificationWhenHitThreshold\":false,\"StopSendNotificationWhenHitCap\":true,\"MaxHistoryCap\":48.674965},\"CurrentBillingFeatures\":[\"ld\",\"x\",\"bf\"]}"; + = "{\"DataVolumeCap\":{\"Cap\":6.710392,\"ResetTime\":1752603485,\"WarningThreshold\":41953991,\"StopSendNotificationWhenHitThreshold\":true,\"StopSendNotificationWhenHitCap\":false,\"MaxHistoryCap\":25.37542},\"CurrentBillingFeatures\":[\"i\",\"hzvhxnkomtkubo\"]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); ApplicationInsightsComponentBillingFeatures response = manager.componentCurrentBillingFeatures() - .updateWithResponse("wmmrq", "zrrjvpgly", + .updateWithResponse("uvvfonkp", "hqyikvy", new ApplicationInsightsComponentBillingFeaturesInner() - .withDataVolumeCap(new ApplicationInsightsComponentDataVolumeCap().withCap(21.610325F) - .withWarningThreshold(829546152) + .withDataVolumeCap(new ApplicationInsightsComponentDataVolumeCap().withCap(71.17668F) + .withWarningThreshold(1578594338) .withStopSendNotificationWhenHitThreshold(true) - .withStopSendNotificationWhenHitCap(false)) - .withCurrentBillingFeatures(Arrays.asList("utnwytpzdmovzvf", "aawzqadfl", "z", "riglaec")), + .withStopSendNotificationWhenHitCap(true)) + .withCurrentBillingFeatures(Arrays.asList("jfybvpoekrsgsgb")), com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals(2.3994863F, response.dataVolumeCap().cap()); - Assertions.assertEquals(1691117977, response.dataVolumeCap().warningThreshold()); - Assertions.assertEquals(false, response.dataVolumeCap().stopSendNotificationWhenHitThreshold()); - Assertions.assertEquals(true, response.dataVolumeCap().stopSendNotificationWhenHitCap()); - Assertions.assertEquals("ld", response.currentBillingFeatures().get(0)); + Assertions.assertEquals(6.710392F, response.dataVolumeCap().cap()); + Assertions.assertEquals(41953991, response.dataVolumeCap().warningThreshold()); + Assertions.assertEquals(true, response.dataVolumeCap().stopSendNotificationWhenHitThreshold()); + Assertions.assertEquals(false, response.dataVolumeCap().stopSendNotificationWhenHitCap()); + Assertions.assertEquals("i", response.currentBillingFeatures().get(0)); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentFeatureCapabilitiesGetWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentFeatureCapabilitiesGetWithResponseMockTests.java index 43a3e8339356..c2ba3889a6b4 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentFeatureCapabilitiesGetWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentFeatureCapabilitiesGetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.models.ApplicationInsightsComponentFeatureCapabilities; @@ -20,17 +20,17 @@ public final class ComponentFeatureCapabilitiesGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"SupportExportData\":false,\"BurstThrottlePolicy\":\"auzzptjazysd\",\"MetadataClass\":\"ezwwv\",\"LiveStreamMetrics\":true,\"ApplicationMap\":false,\"WorkItemIntegration\":true,\"PowerBIIntegration\":false,\"OpenSchema\":false,\"ProactiveDetection\":false,\"AnalyticsIntegration\":false,\"MultipleStepWebTest\":true,\"ApiAccessLevel\":\"vyl\",\"TrackingType\":\"yavluwmncstt\",\"DailyCap\":49.36264,\"DailyCapResetTime\":93.52877,\"ThrottleRate\":59.016396}"; + = "{\"SupportExportData\":false,\"BurstThrottlePolicy\":\"hocxvdfffwafqrou\",\"MetadataClass\":\"spave\",\"LiveStreamMetrics\":false,\"ApplicationMap\":false,\"WorkItemIntegration\":false,\"PowerBIIntegration\":false,\"OpenSchema\":false,\"ProactiveDetection\":true,\"AnalyticsIntegration\":true,\"MultipleStepWebTest\":true,\"ApiAccessLevel\":\"moy\",\"TrackingType\":\"dyuib\",\"DailyCap\":13.8623295,\"DailyCapResetTime\":64.25693,\"ThrottleRate\":39.80005}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); ApplicationInsightsComponentFeatureCapabilities response = manager.componentFeatureCapabilities() - .getWithResponse("xhom", "ynhdwdigum", com.azure.core.util.Context.NONE) + .getWithResponse("brn", "suxmpraf", com.azure.core.util.Context.NONE) .getValue(); } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentLinkedStorageAccountsInnerTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentLinkedStorageAccountsInnerTests.java new file mode 100644 index 000000000000..af4df875e897 --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentLinkedStorageAccountsInnerTests.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.applicationinsights.fluent.models.ComponentLinkedStorageAccountsInner; +import org.junit.jupiter.api.Assertions; + +public final class ComponentLinkedStorageAccountsInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + ComponentLinkedStorageAccountsInner model = BinaryData.fromString( + "{\"properties\":{\"linkedStorageAccount\":\"okixrjqcir\"},\"id\":\"zpfrla\",\"name\":\"szrnwo\",\"type\":\"indfpwpjyl\"}") + .toObject(ComponentLinkedStorageAccountsInner.class); + Assertions.assertEquals("okixrjqcir", model.linkedStorageAccount()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + ComponentLinkedStorageAccountsInner model + = new ComponentLinkedStorageAccountsInner().withLinkedStorageAccount("okixrjqcir"); + model = BinaryData.fromObject(model).toObject(ComponentLinkedStorageAccountsInner.class); + Assertions.assertEquals("okixrjqcir", model.linkedStorageAccount()); + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentLinkedStorageAccountsOperationsCreateAndUpdateWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentLinkedStorageAccountsOperationsCreateAndUpdateWithResponseMockTests.java new file mode 100644 index 000000000000..0a51183d2af8 --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentLinkedStorageAccountsOperationsCreateAndUpdateWithResponseMockTests.java @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; +import com.azure.resourcemanager.applicationinsights.models.ComponentLinkedStorageAccounts; +import com.azure.resourcemanager.applicationinsights.models.StorageType; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class ComponentLinkedStorageAccountsOperationsCreateAndUpdateWithResponseMockTests { + @Test + public void testCreateAndUpdateWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"linkedStorageAccount\":\"gjc\"},\"id\":\"gguxhemlwyw\",\"name\":\"eeczgfbu\",\"type\":\"klelssxb\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + ApplicationInsightsManager manager = ApplicationInsightsManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + ComponentLinkedStorageAccounts response = manager.componentLinkedStorageAccountsOperations() + .define(StorageType.SERVICE_PROFILER) + .withExistingComponent("ytwvczcswkacve", "yfdvlvhbwrnfxtgd") + .withLinkedStorageAccount("hehnmnaoya") + .create(); + + Assertions.assertEquals("gjc", response.linkedStorageAccount()); + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentLinkedStorageAccountsOperationsDeleteWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentLinkedStorageAccountsOperationsDeleteWithResponseMockTests.java new file mode 100644 index 000000000000..539b78d21811 --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentLinkedStorageAccountsOperationsDeleteWithResponseMockTests.java @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; +import com.azure.resourcemanager.applicationinsights.models.StorageType; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class ComponentLinkedStorageAccountsOperationsDeleteWithResponseMockTests { + @Test + public void testDeleteWithResponse() throws Exception { + String responseStr = "{}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + ApplicationInsightsManager manager = ApplicationInsightsManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + manager.componentLinkedStorageAccountsOperations() + .deleteWithResponse("aztb", "snsqowxwcoml", StorageType.SERVICE_PROFILER, com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentLinkedStorageAccountsOperationsGetWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentLinkedStorageAccountsOperationsGetWithResponseMockTests.java new file mode 100644 index 000000000000..780e1d173e61 --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentLinkedStorageAccountsOperationsGetWithResponseMockTests.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.resourcemanager.applicationinsights.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; +import com.azure.resourcemanager.applicationinsights.models.ComponentLinkedStorageAccounts; +import com.azure.resourcemanager.applicationinsights.models.StorageType; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class ComponentLinkedStorageAccountsOperationsGetWithResponseMockTests { + @Test + public void testGetWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"linkedStorageAccount\":\"rhpw\"},\"id\":\"gddeimaw\",\"name\":\"o\",\"type\":\"gkkumuikjcj\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + ApplicationInsightsManager manager = ApplicationInsightsManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + ComponentLinkedStorageAccounts response = manager.componentLinkedStorageAccountsOperations() + .getWithResponse("rkmdyom", "xfbvfb", StorageType.SERVICE_PROFILER, com.azure.core.util.Context.NONE) + .getValue(); + + Assertions.assertEquals("rhpw", response.linkedStorageAccount()); + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentLinkedStorageAccountsPatchTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentLinkedStorageAccountsPatchTests.java new file mode 100644 index 000000000000..a98534cdc16f --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentLinkedStorageAccountsPatchTests.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.applicationinsights.models.ComponentLinkedStorageAccountsPatch; +import org.junit.jupiter.api.Assertions; + +public final class ComponentLinkedStorageAccountsPatchTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + ComponentLinkedStorageAccountsPatch model + = BinaryData.fromString("{\"properties\":{\"linkedStorageAccount\":\"bgofeljag\"}}") + .toObject(ComponentLinkedStorageAccountsPatch.class); + Assertions.assertEquals("bgofeljag", model.linkedStorageAccount()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + ComponentLinkedStorageAccountsPatch model + = new ComponentLinkedStorageAccountsPatch().withLinkedStorageAccount("bgofeljag"); + model = BinaryData.fromObject(model).toObject(ComponentLinkedStorageAccountsPatch.class); + Assertions.assertEquals("bgofeljag", model.linkedStorageAccount()); + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentQuotaStatusGetWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentQuotaStatusGetWithResponseMockTests.java index bc79cb4fb21e..9018d8ed8554 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentQuotaStatusGetWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentQuotaStatusGetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.models.ApplicationInsightsComponentQuotaStatus; @@ -19,17 +19,17 @@ public final class ComponentQuotaStatusGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { - String responseStr = "{\"AppId\":\"hya\",\"ShouldBeThrottled\":true,\"ExpirationTime\":\"lboxqvkjl\"}"; + String responseStr = "{\"AppId\":\"lfkqojpy\",\"ShouldBeThrottled\":false,\"ExpirationTime\":\"rdcnifmzzsdy\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); ApplicationInsightsComponentQuotaStatus response = manager.componentQuotaStatus() - .getWithResponse("rclnpkc", "ayzri", com.azure.core.util.Context.NONE) + .getWithResponse("ppnvdxz", "hihfrbbcevqagtlt", com.azure.core.util.Context.NONE) .getValue(); } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentsDeleteByResourceGroupWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentsDeleteByResourceGroupWithResponseMockTests.java index d99493c35deb..6526c7a7b404 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentsDeleteByResourceGroupWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentsDeleteByResourceGroupWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import java.nio.charset.StandardCharsets; @@ -25,10 +25,10 @@ public void testDeleteWithResponse() throws Exception { ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); manager.components() - .deleteByResourceGroupWithResponse("esutrgjupauutpw", "qhih", com.azure.core.util.Context.NONE); + .deleteByResourceGroupWithResponse("ojmsvpkjprvkwc", "zqljyxgtczh", com.azure.core.util.Context.NONE); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentsGetPurgeStatusWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentsGetPurgeStatusWithResponseMockTests.java index f9333c6e4b8f..9e3d792993d1 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentsGetPurgeStatusWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ComponentsGetPurgeStatusWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.models.ComponentPurgeStatusResponse; @@ -28,10 +28,10 @@ public void testGetPurgeStatusWithResponse() throws Exception { ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); ComponentPurgeStatusResponse response = manager.components() - .getPurgeStatusWithResponse("o", "ejwcwwqiok", "ssxmojms", com.azure.core.util.Context.NONE) + .getPurgeStatusWithResponse("qjbvleorfmlu", "qtqzfavyv", "qqybarye", com.azure.core.util.Context.NONE) .getValue(); Assertions.assertEquals(PurgeState.PENDING, response.status()); diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/DeletedWorkbookInnerErrorTraceTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/DeletedWorkbookInnerErrorTraceTests.java new file mode 100644 index 000000000000..b1db778f7fde --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/DeletedWorkbookInnerErrorTraceTests.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.applicationinsights.models.DeletedWorkbookInnerErrorTrace; + +public final class DeletedWorkbookInnerErrorTraceTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + DeletedWorkbookInnerErrorTrace model + = BinaryData.fromString("{\"trace\":[\"nbaeqphchqn\"]}").toObject(DeletedWorkbookInnerErrorTrace.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + DeletedWorkbookInnerErrorTrace model = new DeletedWorkbookInnerErrorTrace(); + model = BinaryData.fromObject(model).toObject(DeletedWorkbookInnerErrorTrace.class); + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/DeletedWorkbookInnerTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/DeletedWorkbookInnerTests.java new file mode 100644 index 000000000000..ffc09ae1994f --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/DeletedWorkbookInnerTests.java @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.applicationinsights.fluent.models.DeletedWorkbookInner; +import com.azure.resourcemanager.applicationinsights.models.WorkbookSharedTypeKind; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Assertions; + +public final class DeletedWorkbookInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + DeletedWorkbookInner model = BinaryData.fromString( + "{\"properties\":{\"displayName\":\"cbihwqk\",\"serializedData\":\"fdntwjchrdgoih\",\"version\":\"mwctondzjluudfd\",\"timeModified\":\"2021-09-17T07:55:34Z\",\"category\":\"gytsbwtovv\",\"tags\":[\"einqf\",\"ufxqknpirgnepttw\",\"msniffc\"],\"userId\":\"qnrojlpijnkrxfrd\",\"sourceId\":\"c\",\"storageUri\":\"tizzronasxif\",\"description\":\"zq\",\"revision\":\"hftwesgog\"},\"kind\":\"shared\",\"etag\":\"nnxk\",\"location\":\"gnyhmossxkkg\",\"tags\":{\"hqxvcxgfrpdsofbs\":\"rghxjb\",\"z\":\"rnsvbuswd\",\"rtkfawnopq\":\"ybycnunvj\",\"x\":\"ikyzirtxdy\"},\"id\":\"ejnt\",\"name\":\"sewgioilqukr\",\"type\":\"dxtqmieoxo\"}") + .toObject(DeletedWorkbookInner.class); + Assertions.assertEquals("gnyhmossxkkg", model.location()); + Assertions.assertEquals("rghxjb", model.tags().get("hqxvcxgfrpdsofbs")); + Assertions.assertEquals(WorkbookSharedTypeKind.SHARED, model.kind()); + Assertions.assertEquals("nnxk", model.etag()); + Assertions.assertEquals("cbihwqk", model.displayName()); + Assertions.assertEquals("fdntwjchrdgoih", model.serializedData()); + Assertions.assertEquals("mwctondzjluudfd", model.version()); + Assertions.assertEquals("gytsbwtovv", model.category()); + Assertions.assertEquals("einqf", model.tagsPropertiesTags().get(0)); + Assertions.assertEquals("c", model.sourceId()); + Assertions.assertEquals("tizzronasxif", model.storageUri()); + Assertions.assertEquals("zq", model.description()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + DeletedWorkbookInner model = new DeletedWorkbookInner().withLocation("gnyhmossxkkg") + .withTags( + mapOf("hqxvcxgfrpdsofbs", "rghxjb", "z", "rnsvbuswd", "rtkfawnopq", "ybycnunvj", "x", "ikyzirtxdy")) + .withKind(WorkbookSharedTypeKind.SHARED) + .withEtag("nnxk") + .withDisplayName("cbihwqk") + .withSerializedData("fdntwjchrdgoih") + .withVersion("mwctondzjluudfd") + .withCategory("gytsbwtovv") + .withTagsPropertiesTags(Arrays.asList("einqf", "ufxqknpirgnepttw", "msniffc")) + .withSourceId("c") + .withStorageUri("tizzronasxif") + .withDescription("zq"); + model = BinaryData.fromObject(model).toObject(DeletedWorkbookInner.class); + Assertions.assertEquals("gnyhmossxkkg", model.location()); + Assertions.assertEquals("rghxjb", model.tags().get("hqxvcxgfrpdsofbs")); + Assertions.assertEquals(WorkbookSharedTypeKind.SHARED, model.kind()); + Assertions.assertEquals("nnxk", model.etag()); + Assertions.assertEquals("cbihwqk", model.displayName()); + Assertions.assertEquals("fdntwjchrdgoih", model.serializedData()); + Assertions.assertEquals("mwctondzjluudfd", model.version()); + Assertions.assertEquals("gytsbwtovv", model.category()); + Assertions.assertEquals("einqf", model.tagsPropertiesTags().get(0)); + Assertions.assertEquals("c", model.sourceId()); + Assertions.assertEquals("tizzronasxif", model.storageUri()); + Assertions.assertEquals("zq", model.description()); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/DeletedWorkbookPropertiesTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/DeletedWorkbookPropertiesTests.java new file mode 100644 index 000000000000..28d5a960d1de --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/DeletedWorkbookPropertiesTests.java @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.applicationinsights.fluent.models.DeletedWorkbookProperties; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class DeletedWorkbookPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + DeletedWorkbookProperties model = BinaryData.fromString( + "{\"displayName\":\"ggufhyaomtb\",\"serializedData\":\"hhavgrvkffovjz\",\"version\":\"jbibg\",\"timeModified\":\"2021-05-29T05:16:16Z\",\"category\":\"xumvfcluyovw\",\"tags\":[\"kfezzxscyhwz\",\"g\",\"rujbzbomvzzbtdc\",\"vp\"],\"userId\":\"yujviylwdshfssn\",\"sourceId\":\"gy\",\"storageUri\":\"rymsgaojfmw\",\"description\":\"otmrfhir\",\"revision\":\"ymoxoftpipiwyczu\"}") + .toObject(DeletedWorkbookProperties.class); + Assertions.assertEquals("ggufhyaomtb", model.displayName()); + Assertions.assertEquals("hhavgrvkffovjz", model.serializedData()); + Assertions.assertEquals("jbibg", model.version()); + Assertions.assertEquals("xumvfcluyovw", model.category()); + Assertions.assertEquals("kfezzxscyhwz", model.tags().get(0)); + Assertions.assertEquals("gy", model.sourceId()); + Assertions.assertEquals("rymsgaojfmw", model.storageUri()); + Assertions.assertEquals("otmrfhir", model.description()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + DeletedWorkbookProperties model = new DeletedWorkbookProperties().withDisplayName("ggufhyaomtb") + .withSerializedData("hhavgrvkffovjz") + .withVersion("jbibg") + .withCategory("xumvfcluyovw") + .withTags(Arrays.asList("kfezzxscyhwz", "g", "rujbzbomvzzbtdc", "vp")) + .withSourceId("gy") + .withStorageUri("rymsgaojfmw") + .withDescription("otmrfhir"); + model = BinaryData.fromObject(model).toObject(DeletedWorkbookProperties.class); + Assertions.assertEquals("ggufhyaomtb", model.displayName()); + Assertions.assertEquals("hhavgrvkffovjz", model.serializedData()); + Assertions.assertEquals("jbibg", model.version()); + Assertions.assertEquals("xumvfcluyovw", model.category()); + Assertions.assertEquals("kfezzxscyhwz", model.tags().get(0)); + Assertions.assertEquals("gy", model.sourceId()); + Assertions.assertEquals("rymsgaojfmw", model.storageUri()); + Assertions.assertEquals("otmrfhir", model.description()); + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/DeletedWorkbookResourceTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/DeletedWorkbookResourceTests.java new file mode 100644 index 000000000000..33e507439b5f --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/DeletedWorkbookResourceTests.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.applicationinsights.models.DeletedWorkbookResource; +import com.azure.resourcemanager.applicationinsights.models.WorkbookSharedTypeKind; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Assertions; + +public final class DeletedWorkbookResourceTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + DeletedWorkbookResource model = BinaryData.fromString( + "{\"kind\":\"shared\",\"etag\":\"pqjlihhyusps\",\"location\":\"sdvlmfwdgzxulucv\",\"tags\":{\"zvxurisjnhny\":\"rsre\",\"hu\":\"xifqjzgxm\",\"cesutrgjupauut\":\"lw\",\"qg\":\"woqhihe\"},\"id\":\"zpnfqntcypsxj\",\"name\":\"foimwkslircizjxv\",\"type\":\"dfcea\"}") + .toObject(DeletedWorkbookResource.class); + Assertions.assertEquals("sdvlmfwdgzxulucv", model.location()); + Assertions.assertEquals("rsre", model.tags().get("zvxurisjnhny")); + Assertions.assertEquals(WorkbookSharedTypeKind.SHARED, model.kind()); + Assertions.assertEquals("pqjlihhyusps", model.etag()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + DeletedWorkbookResource model = new DeletedWorkbookResource().withLocation("sdvlmfwdgzxulucv") + .withTags(mapOf("zvxurisjnhny", "rsre", "hu", "xifqjzgxm", "cesutrgjupauut", "lw", "qg", "woqhihe")) + .withKind(WorkbookSharedTypeKind.SHARED) + .withEtag("pqjlihhyusps"); + model = BinaryData.fromObject(model).toObject(DeletedWorkbookResource.class); + Assertions.assertEquals("sdvlmfwdgzxulucv", model.location()); + Assertions.assertEquals("rsre", model.tags().get("zvxurisjnhny")); + Assertions.assertEquals(WorkbookSharedTypeKind.SHARED, model.kind()); + Assertions.assertEquals("pqjlihhyusps", model.etag()); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/DeletedWorkbooksListMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/DeletedWorkbooksListMockTests.java new file mode 100644 index 000000000000..1aae5180b947 --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/DeletedWorkbooksListMockTests.java @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; +import com.azure.resourcemanager.applicationinsights.models.CategoryType; +import com.azure.resourcemanager.applicationinsights.models.DeletedWorkbook; +import com.azure.resourcemanager.applicationinsights.models.WorkbookSharedTypeKind; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class DeletedWorkbooksListMockTests { + @Test + public void testList() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"displayName\":\"zujksrlsmdes\",\"serializedData\":\"plpvm\",\"version\":\"doewbidyvt\",\"timeModified\":\"2021-03-16T10:14:22Z\",\"category\":\"xvgpiude\",\"tags\":[\"sxze\",\"paxwkufyk\"],\"userId\":\"uhxep\",\"sourceId\":\"utznabaobns\",\"storageUri\":\"jdjltymkmvgui\",\"description\":\"wartspphkixkykxd\",\"revision\":\"j\"},\"kind\":\"shared\",\"etag\":\"ucfx\",\"location\":\"kkflrmymyincqlhr\",\"tags\":{\"iiiovgqcgxuugq\":\"sl\",\"e\":\"ctotiowlx\",\"wphqlkccuzgygqw\":\"dptjgwdtgukranb\",\"lwgniiprglvawu\":\"hoi\"},\"id\":\"z\",\"name\":\"ufypiv\",\"type\":\"sbbjpmcu\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + ApplicationInsightsManager manager = ApplicationInsightsManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response + = manager.deletedWorkbooks().list(CategoryType.TSG, Arrays.asList("c"), com.azure.core.util.Context.NONE); + + Assertions.assertEquals("kkflrmymyincqlhr", response.iterator().next().location()); + Assertions.assertEquals("sl", response.iterator().next().tags().get("iiiovgqcgxuugq")); + Assertions.assertEquals(WorkbookSharedTypeKind.SHARED, response.iterator().next().kind()); + Assertions.assertEquals("ucfx", response.iterator().next().etag()); + Assertions.assertEquals("zujksrlsmdes", response.iterator().next().displayName()); + Assertions.assertEquals("plpvm", response.iterator().next().serializedData()); + Assertions.assertEquals("doewbidyvt", response.iterator().next().version()); + Assertions.assertEquals("xvgpiude", response.iterator().next().category()); + Assertions.assertEquals("sxze", response.iterator().next().tagsPropertiesTags().get(0)); + Assertions.assertEquals("utznabaobns", response.iterator().next().sourceId()); + Assertions.assertEquals("jdjltymkmvgui", response.iterator().next().storageUri()); + Assertions.assertEquals("wartspphkixkykxd", response.iterator().next().description()); + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/DeletedWorkbooksListResultTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/DeletedWorkbooksListResultTests.java new file mode 100644 index 000000000000..61d4830614a2 --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/DeletedWorkbooksListResultTests.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.applicationinsights.models.DeletedWorkbooksListResult; +import org.junit.jupiter.api.Assertions; + +public final class DeletedWorkbooksListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + DeletedWorkbooksListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"displayName\":\"hldvriii\",\"serializedData\":\"jnalghf\",\"version\":\"tvsexsowuel\",\"timeModified\":\"2021-11-06T19:32:24Z\",\"category\":\"hahhxvrhmzkwpj\",\"tags\":[\"spughftqsxhq\",\"ujxukndxd\",\"grjguufzd\",\"syqtfi\"],\"userId\":\"hbotzingamvppho\",\"sourceId\":\"qzudphq\",\"storageUri\":\"vdkfwynwcvtbvk\",\"description\":\"hmtnvy\",\"revision\":\"atkzwpcnpw\"},\"kind\":\"shared\",\"etag\":\"esgvvsccyaj\",\"location\":\"qfhwyg\",\"tags\":{\"semdwzrmu\":\"dnkfx\",\"qvpsvuoymg\":\"apfcqdpsq\",\"rypqlmfeo\":\"celve\"},\"id\":\"erqwkyhkobopg\",\"name\":\"edkowepbqpcrfk\",\"type\":\"wccsnjvcdwxlpqek\"},{\"properties\":{\"displayName\":\"nkhtjsyingw\",\"serializedData\":\"qatmtdhtmdvy\",\"version\":\"ikdgszywkbir\",\"timeModified\":\"2021-03-20T05:32:50Z\",\"category\":\"zh\",\"tags\":[\"joqrvqqaatj\"],\"userId\":\"rv\",\"sourceId\":\"upmfiibfg\",\"storageUri\":\"ioolvrwxkvtkkgll\",\"description\":\"jygvjayvbl\",\"revision\":\"vkzuhbxvvyhgso\"},\"kind\":\"shared\",\"etag\":\"qufegxuvwzfbn\",\"location\":\"mctlpdngitv\",\"tags\":{\"jejveg\":\"hrixkwmy\",\"eaxhcexdrrvqahqk\":\"hbpnaixexccbd\",\"hyjsvfycx\":\"htpwij\",\"t\":\"bfvoowvrv\"},\"id\":\"jqppyostronzmy\",\"name\":\"gfipnsxk\",\"type\":\"cwaekrrjre\"},{\"properties\":{\"displayName\":\"xt\",\"serializedData\":\"gumhjglikkxws\",\"version\":\"lbqpvuzlmvfelf\",\"timeModified\":\"2021-11-09T20:34:51Z\",\"category\":\"plcrpwjxeznoig\",\"tags\":[\"jwmwkpnbs\",\"zejjoqk\",\"gfhsxttaugzxn\",\"aa\"],\"userId\":\"xdtnkdmkqjjlw\",\"sourceId\":\"nvrk\",\"storageUri\":\"ou\",\"description\":\"bre\",\"revision\":\"aays\"},\"kind\":\"shared\",\"etag\":\"qtnqtt\",\"location\":\"lwfffi\",\"tags\":{\"tmmjihyeozph\":\"jpqqmted\",\"qncygupkvi\":\"wau\",\"hfstotxhojujbyp\":\"mdscwxqupev\",\"xyfwnylrcool\":\"lmcuvhixb\"},\"id\":\"ttpkiwkkbnujrywv\",\"name\":\"y\",\"type\":\"bfpncurdo\"}],\"nextLink\":\"iithtywu\"}") + .toObject(DeletedWorkbooksListResult.class); + Assertions.assertEquals("iithtywu", model.nextLink()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + DeletedWorkbooksListResult model = new DeletedWorkbooksListResult().withNextLink("iithtywu"); + model = BinaryData.fromObject(model).toObject(DeletedWorkbooksListResult.class); + Assertions.assertEquals("iithtywu", model.nextLink()); + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/FavoritesAddWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/FavoritesAddWithResponseMockTests.java index e8e74ee430ad..576148ec91a5 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/FavoritesAddWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/FavoritesAddWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.fluent.models.ApplicationInsightsComponentFavoriteInner; @@ -24,35 +24,35 @@ public final class FavoritesAddWithResponseMockTests { @Test public void testAddWithResponse() throws Exception { String responseStr - = "{\"Name\":\"cohdx\",\"Config\":\"lm\",\"Version\":\"uapcvhdbevwqqxe\",\"FavoriteId\":\"ko\",\"FavoriteType\":\"user\",\"SourceType\":\"nkfkbgbzb\",\"TimeModified\":\"xeqoc\",\"Tags\":[\"ygvkzqkjj\",\"okbzef\",\"zrxcczurt\"],\"Category\":\"ipqxbkwvzgnzv\",\"IsGeneratedFromTemplate\":false,\"UserId\":\"d\"}"; + = "{\"Name\":\"uodxesza\",\"Config\":\"elawumu\",\"Version\":\"lzkwrrwoy\",\"FavoriteId\":\"ucwyhahno\",\"FavoriteType\":\"user\",\"SourceType\":\"ywuhpsvfuur\",\"TimeModified\":\"lwexxwl\",\"Tags\":[\"iexzsrzpge\",\"q\",\"yb\",\"wwpgdakchzyvlixq\"],\"Category\":\"kcxk\",\"IsGeneratedFromTemplate\":false,\"UserId\":\"xmysuxswqrntv\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); ApplicationInsightsComponentFavorite response = manager.favorites() - .addWithResponse("gyyprotwy", "undmbx", "ugcmjkavlgorb", - new ApplicationInsightsComponentFavoriteInner().withName("tp") - .withConfig("tzfjltf") - .withVersion("zcyjtot") + .addWithResponse("jtszcof", "zehtdhgb", "k", + new ApplicationInsightsComponentFavoriteInner().withName("eljeamurvzmlovua") + .withConfig("shcxlpmjerbdk") + .withVersion("vidizozsdb") .withFavoriteType(FavoriteType.USER) - .withSourceType("zq") - .withTags(Arrays.asList("dsvqwt", "mkyi", "cysihs")) - .withCategory("cw") - .withIsGeneratedFromTemplate(false), + .withSourceType("n") + .withTags(Arrays.asList("v", "qjctzenkeif", "zhmkdasvflyh", "xcudchxgsr")) + .withCategory("ldforobwj") + .withIsGeneratedFromTemplate(true), com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("cohdx", response.name()); - Assertions.assertEquals("lm", response.config()); - Assertions.assertEquals("uapcvhdbevwqqxe", response.version()); + Assertions.assertEquals("uodxesza", response.name()); + Assertions.assertEquals("elawumu", response.config()); + Assertions.assertEquals("lzkwrrwoy", response.version()); Assertions.assertEquals(FavoriteType.USER, response.favoriteType()); - Assertions.assertEquals("nkfkbgbzb", response.sourceType()); - Assertions.assertEquals("ygvkzqkjj", response.tags().get(0)); - Assertions.assertEquals("ipqxbkwvzgnzv", response.category()); + Assertions.assertEquals("ywuhpsvfuur", response.sourceType()); + Assertions.assertEquals("iexzsrzpge", response.tags().get(0)); + Assertions.assertEquals("kcxk", response.category()); Assertions.assertEquals(false, response.isGeneratedFromTemplate()); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/FavoritesDeleteWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/FavoritesDeleteWithResponseMockTests.java index 29caa17a9ee0..26f8946c5726 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/FavoritesDeleteWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/FavoritesDeleteWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import java.nio.charset.StandardCharsets; @@ -25,10 +25,9 @@ public void testDeleteWithResponse() throws Exception { ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); - manager.favorites() - .deleteWithResponse("igjkskyrio", "vzidsxwaab", "mifrygznmma", com.azure.core.util.Context.NONE); + manager.favorites().deleteWithResponse("i", "etnluankrrfx", "eebtijvacvb", com.azure.core.util.Context.NONE); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/FavoritesGetWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/FavoritesGetWithResponseMockTests.java index 0632b08168e6..b8df033892f2 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/FavoritesGetWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/FavoritesGetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.models.ApplicationInsightsComponentFavorite; @@ -22,26 +22,26 @@ public final class FavoritesGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"Name\":\"ebtijvacvbmqzbqq\",\"Config\":\"aj\",\"Version\":\"wxacevehj\",\"FavoriteId\":\"yxoaf\",\"FavoriteType\":\"shared\",\"SourceType\":\"lt\",\"TimeModified\":\"eyl\",\"Tags\":[\"fgvxirpghriypoqe\",\"hlqhykprlpy\",\"nuciqdsmexiit\",\"fuxtyasiibmiybnn\"],\"Category\":\"tgnljhnmgixhcmav\",\"IsGeneratedFromTemplate\":false,\"UserId\":\"udorh\"}"; + = "{\"Name\":\"heioqa\",\"Config\":\"v\",\"Version\":\"ufuqyrx\",\"FavoriteId\":\"lcgqlsismj\",\"FavoriteType\":\"shared\",\"SourceType\":\"dgamquhiosrsj\",\"TimeModified\":\"vfcdisyirn\",\"Tags\":[\"czexrxzbujrtrhqv\"],\"Category\":\"evkh\",\"IsGeneratedFromTemplate\":true,\"UserId\":\"zonzlrpiqywnc\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); ApplicationInsightsComponentFavorite response = manager.favorites() - .getWithResponse("bgomfgbegl", "gleohi", "etnluankrrfx", com.azure.core.util.Context.NONE) + .getWithResponse("zaapmudqmeqwi", "pibudqwyxebeybpm", "znrtffyaqit", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("ebtijvacvbmqzbqq", response.name()); - Assertions.assertEquals("aj", response.config()); - Assertions.assertEquals("wxacevehj", response.version()); + Assertions.assertEquals("heioqa", response.name()); + Assertions.assertEquals("v", response.config()); + Assertions.assertEquals("ufuqyrx", response.version()); Assertions.assertEquals(FavoriteType.SHARED, response.favoriteType()); - Assertions.assertEquals("lt", response.sourceType()); - Assertions.assertEquals("fgvxirpghriypoqe", response.tags().get(0)); - Assertions.assertEquals("tgnljhnmgixhcmav", response.category()); - Assertions.assertEquals(false, response.isGeneratedFromTemplate()); + Assertions.assertEquals("dgamquhiosrsj", response.sourceType()); + Assertions.assertEquals("czexrxzbujrtrhqv", response.tags().get(0)); + Assertions.assertEquals("evkh", response.category()); + Assertions.assertEquals(true, response.isGeneratedFromTemplate()); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/FavoritesListWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/FavoritesListWithResponseMockTests.java index cd728a651c77..09aff4620508 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/FavoritesListWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/FavoritesListWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.models.ApplicationInsightsComponentFavorite; @@ -25,27 +25,27 @@ public final class FavoritesListWithResponseMockTests { @Test public void testListWithResponse() throws Exception { String responseStr - = "[{\"Name\":\"cxkjibnxmysuxswq\",\"Config\":\"tvlwijpsttexoq\",\"Version\":\"wcyyufmhruncu\",\"FavoriteId\":\"qspkcdqzhlctd\",\"FavoriteType\":\"user\",\"SourceType\":\"ndy\",\"TimeModified\":\"chrqb\",\"Tags\":[\"rcgegydcwboxjum\"],\"Category\":\"qoli\",\"IsGeneratedFromTemplate\":true,\"UserId\":\"iouaubrjt\"},{\"Name\":\"qxfuojrngif\",\"Config\":\"z\",\"Version\":\"sccbiuimzd\",\"FavoriteId\":\"jdfqwmkyoqufdvr\",\"FavoriteType\":\"shared\",\"SourceType\":\"zojhpctfnmd\",\"TimeModified\":\"tngfdgugeyzihgr\",\"Tags\":[\"i\"],\"Category\":\"bsnmfpph\",\"IsGeneratedFromTemplate\":false,\"UserId\":\"vyhyhsgzfc\"}]"; + = "[{\"Name\":\"g\",\"Config\":\"whryvycytdcl\",\"Version\":\"ccknfnwmbtmvp\",\"FavoriteId\":\"jdhttzaefedxi\",\"FavoriteType\":\"user\",\"SourceType\":\"phkmcrjdqnsdfz\",\"TimeModified\":\"gtgkylkdghr\",\"Tags\":[\"utlwxezwzhok\",\"bwnhhtql\",\"ehgpp\",\"pifhpfeoajvgcxtx\"],\"Category\":\"sheafid\",\"IsGeneratedFromTemplate\":true,\"UserId\":\"sr\"},{\"Name\":\"mks\",\"Config\":\"h\",\"Version\":\"ftxfkf\",\"FavoriteId\":\"gpr\",\"FavoriteType\":\"user\",\"SourceType\":\"llu\",\"TimeModified\":\"iqtgdqoh\",\"Tags\":[\"sldrizetpwbral\",\"libph\",\"qzmiza\",\"a\"],\"Category\":\"nkjpdnjzha\",\"IsGeneratedFromTemplate\":false,\"UserId\":\"hjlmu\"},{\"Name\":\"xprimrsop\",\"Config\":\"ecj\",\"Version\":\"islstv\",\"FavoriteId\":\"ylw\",\"FavoriteType\":\"shared\",\"SourceType\":\"umweoohguufuzboy\",\"TimeModified\":\"thwtzol\",\"Tags\":[\"mwmdxmebwjscjpa\",\"lxveabfqx\",\"mwmqtibx\"],\"Category\":\"jddtvqct\",\"IsGeneratedFromTemplate\":false,\"UserId\":\"jaeukmrsieekpn\"}]"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); List response = manager.favorites() - .listWithResponse("xzsrzpge", "q", FavoriteType.SHARED, FavoriteSourceType.RETENTION, true, - Arrays.asList("wwpgdakchzyvlixq"), com.azure.core.util.Context.NONE) + .listWithResponse("roylaxxu", "cdisd", FavoriteType.SHARED, FavoriteSourceType.RETENTION, true, + Arrays.asList("b"), com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("cxkjibnxmysuxswq", response.get(0).name()); - Assertions.assertEquals("tvlwijpsttexoq", response.get(0).config()); - Assertions.assertEquals("wcyyufmhruncu", response.get(0).version()); + Assertions.assertEquals("g", response.get(0).name()); + Assertions.assertEquals("whryvycytdcl", response.get(0).config()); + Assertions.assertEquals("ccknfnwmbtmvp", response.get(0).version()); Assertions.assertEquals(FavoriteType.USER, response.get(0).favoriteType()); - Assertions.assertEquals("ndy", response.get(0).sourceType()); - Assertions.assertEquals("rcgegydcwboxjum", response.get(0).tags().get(0)); - Assertions.assertEquals("qoli", response.get(0).category()); + Assertions.assertEquals("phkmcrjdqnsdfz", response.get(0).sourceType()); + Assertions.assertEquals("utlwxezwzhok", response.get(0).tags().get(0)); + Assertions.assertEquals("sheafid", response.get(0).category()); Assertions.assertEquals(true, response.get(0).isGeneratedFromTemplate()); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/FavoritesUpdateWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/FavoritesUpdateWithResponseMockTests.java index 7a6286d3b016..69e3ebd856a2 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/FavoritesUpdateWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/FavoritesUpdateWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.fluent.models.ApplicationInsightsComponentFavoriteInner; @@ -24,35 +24,35 @@ public final class FavoritesUpdateWithResponseMockTests { @Test public void testUpdateWithResponse() throws Exception { String responseStr - = "{\"Name\":\"wpwyawbz\",\"Config\":\"qbucljgkyexaoguy\",\"Version\":\"p\",\"FavoriteId\":\"sdaultxij\",\"FavoriteType\":\"shared\",\"SourceType\":\"qwazlnqnmcjngzq\",\"TimeModified\":\"xtbjwgnyfusfzsv\",\"Tags\":[\"kzhajqglcfhm\",\"rqryxynqn\",\"rd\",\"sovwxznptgoeiyb\"],\"Category\":\"bp\",\"IsGeneratedFromTemplate\":false,\"UserId\":\"slkvntjl\"}"; + = "{\"Name\":\"ruzslzoj\",\"Config\":\"ctfnmdxotng\",\"Version\":\"gugey\",\"FavoriteId\":\"hgrky\",\"FavoriteType\":\"shared\",\"SourceType\":\"bsnmfpph\",\"TimeModified\":\"eevy\",\"Tags\":[\"sgzfczbg\"],\"Category\":\"fgbegl\",\"IsGeneratedFromTemplate\":true,\"UserId\":\"o\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); ApplicationInsightsComponentFavorite response = manager.favorites() - .updateWithResponse("xzmqpnodawop", "hewjptmcgsbost", "eln", - new ApplicationInsightsComponentFavoriteInner().withName("atutmzlbiojlvfhr") - .withConfig("pn") - .withVersion("vcwwyyurmochppr") + .updateWithResponse("wijpsttexoqqpwc", "yufmhruncuwmq", "pkcdqzhlct", + new ApplicationInsightsComponentFavoriteInner().withName("unqndyfpchrqb") + .withConfig("jrcg") + .withVersion("ydcwboxjumv") .withFavoriteType(FavoriteType.SHARED) - .withSourceType("kpbz") - .withTags(Arrays.asList("nwieholewjw", "uubw", "fqsfa")) - .withCategory("qtferrqwexjkmf") + .withSourceType("ubrjtl") + .withTags(Arrays.asList("l", "z")) + .withCategory("sccbiuimzd") .withIsGeneratedFromTemplate(true), com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("wpwyawbz", response.name()); - Assertions.assertEquals("qbucljgkyexaoguy", response.config()); - Assertions.assertEquals("p", response.version()); + Assertions.assertEquals("ruzslzoj", response.name()); + Assertions.assertEquals("ctfnmdxotng", response.config()); + Assertions.assertEquals("gugey", response.version()); Assertions.assertEquals(FavoriteType.SHARED, response.favoriteType()); - Assertions.assertEquals("qwazlnqnmcjngzq", response.sourceType()); - Assertions.assertEquals("kzhajqglcfhm", response.tags().get(0)); - Assertions.assertEquals("bp", response.category()); - Assertions.assertEquals(false, response.isGeneratedFromTemplate()); + Assertions.assertEquals("bsnmfpph", response.sourceType()); + Assertions.assertEquals("sgzfczbg", response.tags().get(0)); + Assertions.assertEquals("fgbegl", response.category()); + Assertions.assertEquals(true, response.isGeneratedFromTemplate()); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/LinkedStorageAccountsPropertiesTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/LinkedStorageAccountsPropertiesTests.java new file mode 100644 index 000000000000..d2f42b3f9191 --- /dev/null +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/LinkedStorageAccountsPropertiesTests.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.applicationinsights.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.applicationinsights.fluent.models.LinkedStorageAccountsProperties; +import org.junit.jupiter.api.Assertions; + +public final class LinkedStorageAccountsPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + LinkedStorageAccountsProperties model = BinaryData.fromString("{\"linkedStorageAccount\":\"tlhflsjcdhszf\"}") + .toObject(LinkedStorageAccountsProperties.class); + Assertions.assertEquals("tlhflsjcdhszf", model.linkedStorageAccount()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + LinkedStorageAccountsProperties model + = new LinkedStorageAccountsProperties().withLinkedStorageAccount("tlhflsjcdhszf"); + model = BinaryData.fromObject(model).toObject(LinkedStorageAccountsProperties.class); + Assertions.assertEquals("tlhflsjcdhszf", model.linkedStorageAccount()); + } +} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ManagedServiceIdentityTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ManagedServiceIdentityTests.java index 6b09274eb3ca..cfa5fe6bfbd5 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ManagedServiceIdentityTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ManagedServiceIdentityTests.java @@ -16,17 +16,17 @@ public final class ManagedServiceIdentityTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ManagedServiceIdentity model = BinaryData.fromString( - "{\"principalId\":\"a03734f7-cb3e-4a19-9e15-f9de5f63a780\",\"tenantId\":\"70c8b475-1c46-4f9c-a311-7edddac8b6ef\",\"type\":\"None\",\"userAssignedIdentities\":{\"fdlwg\":{\"principalId\":\"5c9244fc-9de5-40e3-8191-ce0649d73c3d\",\"clientId\":\"33ae1bcc-8d38-49ac-a3ec-1ea5c7cd2c99\"}}}") + "{\"principalId\":\"f94f7f78-8bc0-49ee-95bb-364091325d95\",\"tenantId\":\"5074633e-6bd1-48e1-bc7f-7a81ab0f681a\",\"type\":\"SystemAssigned\",\"userAssignedIdentities\":{\"ykhevxccedcpnmdy\":{\"principalId\":\"07b1cc53-97ea-4a81-bbf1-e18b4e51d4ba\",\"clientId\":\"72109b87-89c6-405b-9324-23373ca46d9c\"}}}") .toObject(ManagedServiceIdentity.class); - Assertions.assertEquals(ManagedServiceIdentityType.NONE, model.type()); + Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_ASSIGNED, model.type()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - ManagedServiceIdentity model = new ManagedServiceIdentity().withType(ManagedServiceIdentityType.NONE) - .withUserAssignedIdentities(mapOf("fdlwg", new UserAssignedIdentity())); + ManagedServiceIdentity model = new ManagedServiceIdentity().withType(ManagedServiceIdentityType.SYSTEM_ASSIGNED) + .withUserAssignedIdentities(mapOf("ykhevxccedcpnmdy", new UserAssignedIdentity())); model = BinaryData.fromObject(model).toObject(ManagedServiceIdentity.class); - Assertions.assertEquals(ManagedServiceIdentityType.NONE, model.type()); + Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_ASSIGNED, model.type()); } // Use "Map.of" if available diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbookInnerTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbookInnerTests.java deleted file mode 100644 index aaa93628454e..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbookInnerTests.java +++ /dev/null @@ -1,89 +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.resourcemanager.applicationinsights.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.applicationinsights.fluent.models.MyWorkbookInner; -import com.azure.resourcemanager.applicationinsights.models.Kind; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbookManagedIdentity; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbookManagedIdentityType; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbookUserAssignedIdentities; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import org.junit.jupiter.api.Assertions; - -public final class MyWorkbookInnerTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - MyWorkbookInner model = BinaryData.fromString( - "{\"kind\":\"shared\",\"properties\":{\"displayName\":\"z\",\"serializedData\":\"cmrvexzt\",\"version\":\"t\",\"timeModified\":\"sfraoyzko\",\"category\":\"wtl\",\"tags\":[\"ux\",\"wqaldsyu\",\"ximerqfobwyznk\",\"ykutwpf\"],\"userId\":\"a\",\"sourceId\":\"hrskdsnfd\",\"storageUri\":\"oakgtdlmkkzev\"},\"identity\":{\"userAssignedIdentities\":{\"principalId\":\"pusdstt\",\"tenantId\":\"ogvbbejdcngq\"},\"type\":\"UserAssigned\"},\"id\":\"rgzdwmsweyp\",\"name\":\"w\",\"type\":\"xggicccnxqhuexmk\",\"etag\":{\"hziuiefozbhdms\":\"inrfdwoyu\",\"zqhof\":\"l\"},\"location\":\"rmaequ\",\"tags\":{\"z\":\"xicslfao\",\"kaivwit\":\"iyylhalnswhccsp\",\"bwemhairs\":\"scywuggwoluhc\"}}") - .toObject(MyWorkbookInner.class); - Assertions.assertEquals("rmaequ", model.location()); - Assertions.assertEquals("xicslfao", model.tags().get("z")); - Assertions.assertEquals(MyWorkbookManagedIdentityType.USER_ASSIGNED, model.identity().type()); - Assertions.assertEquals("rgzdwmsweyp", model.id()); - Assertions.assertEquals("w", model.name()); - Assertions.assertEquals("xggicccnxqhuexmk", model.type()); - Assertions.assertEquals("inrfdwoyu", model.etag().get("hziuiefozbhdms")); - Assertions.assertEquals(Kind.SHARED, model.kind()); - Assertions.assertEquals("z", model.displayName()); - Assertions.assertEquals("cmrvexzt", model.serializedData()); - Assertions.assertEquals("t", model.version()); - Assertions.assertEquals("wtl", model.category()); - Assertions.assertEquals("ux", model.tagsPropertiesTags().get(0)); - Assertions.assertEquals("hrskdsnfd", model.sourceId()); - Assertions.assertEquals("oakgtdlmkkzev", model.storageUri()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - MyWorkbookInner model = new MyWorkbookInner().withLocation("rmaequ") - .withTags(mapOf("z", "xicslfao", "kaivwit", "iyylhalnswhccsp", "bwemhairs", "scywuggwoluhc")) - .withIdentity( - new MyWorkbookManagedIdentity().withUserAssignedIdentities(new MyWorkbookUserAssignedIdentities()) - .withType(MyWorkbookManagedIdentityType.USER_ASSIGNED)) - .withId("rgzdwmsweyp") - .withName("w") - .withType("xggicccnxqhuexmk") - .withEtag(mapOf("hziuiefozbhdms", "inrfdwoyu", "zqhof", "l")) - .withKind(Kind.SHARED) - .withDisplayName("z") - .withSerializedData("cmrvexzt") - .withVersion("t") - .withCategory("wtl") - .withTagsPropertiesTags(Arrays.asList("ux", "wqaldsyu", "ximerqfobwyznk", "ykutwpf")) - .withSourceId("hrskdsnfd") - .withStorageUri("oakgtdlmkkzev"); - model = BinaryData.fromObject(model).toObject(MyWorkbookInner.class); - Assertions.assertEquals("rmaequ", model.location()); - Assertions.assertEquals("xicslfao", model.tags().get("z")); - Assertions.assertEquals(MyWorkbookManagedIdentityType.USER_ASSIGNED, model.identity().type()); - Assertions.assertEquals("rgzdwmsweyp", model.id()); - Assertions.assertEquals("w", model.name()); - Assertions.assertEquals("xggicccnxqhuexmk", model.type()); - Assertions.assertEquals("inrfdwoyu", model.etag().get("hziuiefozbhdms")); - Assertions.assertEquals(Kind.SHARED, model.kind()); - Assertions.assertEquals("z", model.displayName()); - Assertions.assertEquals("cmrvexzt", model.serializedData()); - Assertions.assertEquals("t", model.version()); - Assertions.assertEquals("wtl", model.category()); - Assertions.assertEquals("ux", model.tagsPropertiesTags().get(0)); - Assertions.assertEquals("hrskdsnfd", model.sourceId()); - Assertions.assertEquals("oakgtdlmkkzev", model.storageUri()); - } - - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbookManagedIdentityTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbookManagedIdentityTests.java deleted file mode 100644 index 308f6454f1b4..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbookManagedIdentityTests.java +++ /dev/null @@ -1,30 +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.resourcemanager.applicationinsights.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbookManagedIdentity; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbookManagedIdentityType; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbookUserAssignedIdentities; -import org.junit.jupiter.api.Assertions; - -public final class MyWorkbookManagedIdentityTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - MyWorkbookManagedIdentity model = BinaryData.fromString( - "{\"userAssignedIdentities\":{\"principalId\":\"tawfsdjpvkvp\",\"tenantId\":\"xbkzbzkdvncj\"},\"type\":\"None\"}") - .toObject(MyWorkbookManagedIdentity.class); - Assertions.assertEquals(MyWorkbookManagedIdentityType.NONE, model.type()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - MyWorkbookManagedIdentity model - = new MyWorkbookManagedIdentity().withUserAssignedIdentities(new MyWorkbookUserAssignedIdentities()) - .withType(MyWorkbookManagedIdentityType.NONE); - model = BinaryData.fromObject(model).toObject(MyWorkbookManagedIdentity.class); - Assertions.assertEquals(MyWorkbookManagedIdentityType.NONE, model.type()); - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbookPropertiesTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbookPropertiesTests.java deleted file mode 100644 index b496796a9331..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbookPropertiesTests.java +++ /dev/null @@ -1,45 +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.resourcemanager.applicationinsights.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.applicationinsights.fluent.models.MyWorkbookProperties; -import java.util.Arrays; -import org.junit.jupiter.api.Assertions; - -public final class MyWorkbookPropertiesTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - MyWorkbookProperties model = BinaryData.fromString( - "{\"displayName\":\"tlstvlzywem\",\"serializedData\":\"zrncsdt\",\"version\":\"u\",\"timeModified\":\"ypbsfgytguslfead\",\"category\":\"ygqukyhejh\",\"tags\":[\"xgfpelolppv\"],\"userId\":\"r\",\"sourceId\":\"vu\",\"storageUri\":\"raehtwdwrft\"}") - .toObject(MyWorkbookProperties.class); - Assertions.assertEquals("tlstvlzywem", model.displayName()); - Assertions.assertEquals("zrncsdt", model.serializedData()); - Assertions.assertEquals("u", model.version()); - Assertions.assertEquals("ygqukyhejh", model.category()); - Assertions.assertEquals("xgfpelolppv", model.tags().get(0)); - Assertions.assertEquals("vu", model.sourceId()); - Assertions.assertEquals("raehtwdwrft", model.storageUri()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - MyWorkbookProperties model = new MyWorkbookProperties().withDisplayName("tlstvlzywem") - .withSerializedData("zrncsdt") - .withVersion("u") - .withCategory("ygqukyhejh") - .withTags(Arrays.asList("xgfpelolppv")) - .withSourceId("vu") - .withStorageUri("raehtwdwrft"); - model = BinaryData.fromObject(model).toObject(MyWorkbookProperties.class); - Assertions.assertEquals("tlstvlzywem", model.displayName()); - Assertions.assertEquals("zrncsdt", model.serializedData()); - Assertions.assertEquals("u", model.version()); - Assertions.assertEquals("ygqukyhejh", model.category()); - Assertions.assertEquals("xgfpelolppv", model.tags().get(0)); - Assertions.assertEquals("vu", model.sourceId()); - Assertions.assertEquals("raehtwdwrft", model.storageUri()); - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbookResourceTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbookResourceTests.java deleted file mode 100644 index e9d0a782bc17..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbookResourceTests.java +++ /dev/null @@ -1,63 +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.resourcemanager.applicationinsights.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbookManagedIdentity; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbookManagedIdentityType; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbookResource; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbookUserAssignedIdentities; -import java.util.HashMap; -import java.util.Map; -import org.junit.jupiter.api.Assertions; - -public final class MyWorkbookResourceTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - MyWorkbookResource model = BinaryData.fromString( - "{\"identity\":{\"userAssignedIdentities\":{\"principalId\":\"yrcdlbhshfwprac\",\"tenantId\":\"wity\"},\"type\":\"None\"},\"id\":\"pjorwkqnyhg\",\"name\":\"ij\",\"type\":\"jivfxzsjabib\",\"etag\":{\"vfgbvfvpdboda\":\"qunyowxwlmdjr\"},\"location\":\"izsjqlhkrr\",\"tags\":{\"p\":\"eibq\",\"ndzwmkrefa\":\"kghv\"}}") - .toObject(MyWorkbookResource.class); - Assertions.assertEquals("izsjqlhkrr", model.location()); - Assertions.assertEquals("eibq", model.tags().get("p")); - Assertions.assertEquals(MyWorkbookManagedIdentityType.NONE, model.identity().type()); - Assertions.assertEquals("pjorwkqnyhg", model.id()); - Assertions.assertEquals("ij", model.name()); - Assertions.assertEquals("jivfxzsjabib", model.type()); - Assertions.assertEquals("qunyowxwlmdjr", model.etag().get("vfgbvfvpdboda")); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - MyWorkbookResource model = new MyWorkbookResource().withLocation("izsjqlhkrr") - .withTags(mapOf("p", "eibq", "ndzwmkrefa", "kghv")) - .withIdentity( - new MyWorkbookManagedIdentity().withUserAssignedIdentities(new MyWorkbookUserAssignedIdentities()) - .withType(MyWorkbookManagedIdentityType.NONE)) - .withId("pjorwkqnyhg") - .withName("ij") - .withType("jivfxzsjabib") - .withEtag(mapOf("vfgbvfvpdboda", "qunyowxwlmdjr")); - model = BinaryData.fromObject(model).toObject(MyWorkbookResource.class); - Assertions.assertEquals("izsjqlhkrr", model.location()); - Assertions.assertEquals("eibq", model.tags().get("p")); - Assertions.assertEquals(MyWorkbookManagedIdentityType.NONE, model.identity().type()); - Assertions.assertEquals("pjorwkqnyhg", model.id()); - Assertions.assertEquals("ij", model.name()); - Assertions.assertEquals("jivfxzsjabib", model.type()); - Assertions.assertEquals("qunyowxwlmdjr", model.etag().get("vfgbvfvpdboda")); - } - - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbookUserAssignedIdentitiesTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbookUserAssignedIdentitiesTests.java deleted file mode 100644 index 41e2e5cd55ec..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbookUserAssignedIdentitiesTests.java +++ /dev/null @@ -1,23 +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.resourcemanager.applicationinsights.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbookUserAssignedIdentities; - -public final class MyWorkbookUserAssignedIdentitiesTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - MyWorkbookUserAssignedIdentities model - = BinaryData.fromString("{\"principalId\":\"urgkakmokzhjjk\",\"tenantId\":\"fhmouwq\"}") - .toObject(MyWorkbookUserAssignedIdentities.class); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - MyWorkbookUserAssignedIdentities model = new MyWorkbookUserAssignedIdentities(); - model = BinaryData.fromObject(model).toObject(MyWorkbookUserAssignedIdentities.class); - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksCreateOrUpdateWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksCreateOrUpdateWithResponseMockTests.java deleted file mode 100644 index c325a5c60ccd..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksCreateOrUpdateWithResponseMockTests.java +++ /dev/null @@ -1,90 +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.resourcemanager.applicationinsights.generated; - -import com.azure.core.credential.AccessToken; -import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.profile.AzureProfile; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; -import com.azure.resourcemanager.applicationinsights.models.Kind; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbook; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbookManagedIdentity; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbookManagedIdentityType; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbookUserAssignedIdentities; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -public final class MyWorkbooksCreateOrUpdateWithResponseMockTests { - @Test - public void testCreateOrUpdateWithResponse() throws Exception { - String responseStr - = "{\"kind\":\"user\",\"properties\":{\"displayName\":\"inuqtljq\",\"serializedData\":\"bbpihehcecy\",\"version\":\"rqbrjbbmpxdlvyk\",\"timeModified\":\"e\",\"category\":\"crse\",\"tags\":[\"ksghudgzhxogjgg\",\"voujkxibdafhrk\"],\"userId\":\"yomkxfbvfbhdy\",\"sourceId\":\"hpwpgddeimawzovg\",\"storageUri\":\"um\"},\"identity\":{\"userAssignedIdentities\":{\"principalId\":\"jcazt\",\"tenantId\":\"snsqowxwcoml\"},\"type\":\"None\"},\"id\":\"ukklelss\",\"name\":\"blycsxzujksr\",\"type\":\"smdesqplpvmjcd\",\"etag\":{\"nkcoeqswankltyt\":\"mnaoy\"},\"location\":\"hdroznnh\",\"tags\":{\"sggux\":\"ktgj\",\"ywaeeczgf\":\"eml\"}}"; - - HttpClient httpClient - = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); - ApplicationInsightsManager manager = ApplicationInsightsManager.configure() - .withHttpClient(httpClient) - .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); - - MyWorkbook response = manager.myWorkbooks() - .define("rrkolawjmjs") - .withRegion("zhzmtksjci") - .withExistingResourceGroup("tgvgzp") - .withTags(mapOf("htomflrytswfp", "gsxcdgljplkeua", "skw", "mdgycxn", "shhkvpedw", "qjjyslurl")) - .withIdentity( - new MyWorkbookManagedIdentity().withUserAssignedIdentities(new MyWorkbookUserAssignedIdentities()) - .withType(MyWorkbookManagedIdentityType.NONE)) - .withName("wwsko") - .withType("dcbrwimuvq") - .withEtag(mapOf("afiqgeaarbgjekg", "pxy", "mzegjon", "klbyulidwcw", "rwgdnqzbrfks", "hj")) - .withKind(Kind.SHARED) - .withDisplayName("kcdxfzzzw") - .withSerializedData("jafi") - .withVersion("hguynuchlgmltxdw") - .withCategory("ln") - .withTagsPropertiesTags(Arrays.asList("jzfpafolpymwamx")) - .withSourceId("dphtv") - .withStorageUri("lajv") - .withSourceIdParameter("josovyrrl") - .create(); - - Assertions.assertEquals("hdroznnh", response.location()); - Assertions.assertEquals("ktgj", response.tags().get("sggux")); - Assertions.assertEquals(MyWorkbookManagedIdentityType.NONE, response.identity().type()); - Assertions.assertEquals("ukklelss", response.id()); - Assertions.assertEquals("blycsxzujksr", response.name()); - Assertions.assertEquals("smdesqplpvmjcd", response.type()); - Assertions.assertEquals("mnaoy", response.etag().get("nkcoeqswankltyt")); - Assertions.assertEquals(Kind.USER, response.kind()); - Assertions.assertEquals("inuqtljq", response.displayName()); - Assertions.assertEquals("bbpihehcecy", response.serializedData()); - Assertions.assertEquals("rqbrjbbmpxdlvyk", response.version()); - Assertions.assertEquals("crse", response.category()); - Assertions.assertEquals("ksghudgzhxogjgg", response.tagsPropertiesTags().get(0)); - Assertions.assertEquals("hpwpgddeimawzovg", response.sourceId()); - Assertions.assertEquals("um", response.storageUri()); - } - - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksDeleteByResourceGroupWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksDeleteByResourceGroupWithResponseMockTests.java deleted file mode 100644 index e31bda038739..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksDeleteByResourceGroupWithResponseMockTests.java +++ /dev/null @@ -1,34 +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.resourcemanager.applicationinsights.generated; - -import com.azure.core.credential.AccessToken; -import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.profile.AzureProfile; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -public final class MyWorkbooksDeleteByResourceGroupWithResponseMockTests { - @Test - public void testDeleteWithResponse() throws Exception { - String responseStr = "{}"; - - HttpClient httpClient - = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); - ApplicationInsightsManager manager = ApplicationInsightsManager.configure() - .withHttpClient(httpClient) - .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); - - manager.myWorkbooks() - .deleteByResourceGroupWithResponse("yjuzkdb", "zolxrzvhqjwtr", com.azure.core.util.Context.NONE); - - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksGetByResourceGroupWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksGetByResourceGroupWithResponseMockTests.java deleted file mode 100644 index a630d6e15e44..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksGetByResourceGroupWithResponseMockTests.java +++ /dev/null @@ -1,55 +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.resourcemanager.applicationinsights.generated; - -import com.azure.core.credential.AccessToken; -import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.profile.AzureProfile; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; -import com.azure.resourcemanager.applicationinsights.models.Kind; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbook; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbookManagedIdentityType; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -public final class MyWorkbooksGetByResourceGroupWithResponseMockTests { - @Test - public void testGetByResourceGroupWithResponse() throws Exception { - String responseStr - = "{\"kind\":\"user\",\"properties\":{\"displayName\":\"uic\",\"serializedData\":\"hvtrrmhwrbfdpyf\",\"version\":\"bhvjglr\",\"timeModified\":\"uyzlw\",\"category\":\"hmem\",\"tags\":[\"clutnpqme\"],\"userId\":\"zjkmmykyujxs\",\"sourceId\":\"hsrrryejylmbkz\",\"storageUri\":\"nigrfihotjewl\"},\"identity\":{\"userAssignedIdentities\":{\"principalId\":\"jgnrefqyhqoto\",\"tenantId\":\"iqakydiwfbr\"},\"type\":\"None\"},\"id\":\"jpu\",\"name\":\"yjucejikzoeo\",\"type\":\"vtzejetjklnti\",\"etag\":{\"fpubntnbatz\":\"ulbmoichdlp\",\"ttcjuhplrvkmjc\":\"iqsowsaaelc\",\"vkyylizrzbjpsf\":\"mjvlgfgg\"},\"location\":\"sfuztlvtmv\",\"tags\":{\"dqlvhukoveof\":\"w\",\"lkujrllfojui\":\"zrvjfnmjmvlwyzgi\"}}"; - - HttpClient httpClient - = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); - ApplicationInsightsManager manager = ApplicationInsightsManager.configure() - .withHttpClient(httpClient) - .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); - - MyWorkbook response = manager.myWorkbooks() - .getByResourceGroupWithResponse("lhikcyychunsj", "pjrtws", com.azure.core.util.Context.NONE) - .getValue(); - - Assertions.assertEquals("sfuztlvtmv", response.location()); - Assertions.assertEquals("w", response.tags().get("dqlvhukoveof")); - Assertions.assertEquals(MyWorkbookManagedIdentityType.NONE, response.identity().type()); - Assertions.assertEquals("jpu", response.id()); - Assertions.assertEquals("yjucejikzoeo", response.name()); - Assertions.assertEquals("vtzejetjklnti", response.type()); - Assertions.assertEquals("ulbmoichdlp", response.etag().get("fpubntnbatz")); - Assertions.assertEquals(Kind.USER, response.kind()); - Assertions.assertEquals("uic", response.displayName()); - Assertions.assertEquals("hvtrrmhwrbfdpyf", response.serializedData()); - Assertions.assertEquals("bhvjglr", response.version()); - Assertions.assertEquals("hmem", response.category()); - Assertions.assertEquals("clutnpqme", response.tagsPropertiesTags().get(0)); - Assertions.assertEquals("hsrrryejylmbkz", response.sourceId()); - Assertions.assertEquals("nigrfihotjewl", response.storageUri()); - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksListByResourceGroupMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksListByResourceGroupMockTests.java deleted file mode 100644 index 2da3ea951b89..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksListByResourceGroupMockTests.java +++ /dev/null @@ -1,58 +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.resourcemanager.applicationinsights.generated; - -import com.azure.core.credential.AccessToken; -import com.azure.core.http.HttpClient; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.profile.AzureProfile; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; -import com.azure.resourcemanager.applicationinsights.models.CategoryType; -import com.azure.resourcemanager.applicationinsights.models.Kind; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbook; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbookManagedIdentityType; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import java.util.Arrays; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -public final class MyWorkbooksListByResourceGroupMockTests { - @Test - public void testListByResourceGroup() throws Exception { - String responseStr - = "{\"value\":[{\"kind\":\"shared\",\"properties\":{\"displayName\":\"htuevrhrljy\",\"serializedData\":\"ogwxhnsduugwb\",\"version\":\"e\",\"timeModified\":\"fqkfuarenl\",\"category\":\"hhtklnvnafvvkyfe\",\"tags\":[\"jboslcqxypok\"],\"userId\":\"minqcym\",\"sourceId\":\"ngnbdxxew\",\"storageUri\":\"invudbch\"},\"identity\":{\"userAssignedIdentities\":{\"principalId\":\"qecrqctmxx\",\"tenantId\":\"ddm\"},\"type\":\"None\"},\"id\":\"ybww\",\"name\":\"bdvibidmhmwffpl\",\"type\":\"muvapc\",\"etag\":{\"rxklobdxnazpmk\":\"uxvnsasbcrymodi\",\"vfxzopjh\":\"lmv\",\"d\":\"zxlioh\"},\"location\":\"dtfgxqbawpcbb\",\"tags\":{\"zb\":\"cyknapqofyuicd\"}}]}"; - - HttpClient httpClient - = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); - ApplicationInsightsManager manager = ApplicationInsightsManager.configure() - .withHttpClient(httpClient) - .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); - - PagedIterable response = manager.myWorkbooks() - .listByResourceGroup("zoyw", CategoryType.RETENTION, Arrays.asList("hpdulon"), "acn", true, - com.azure.core.util.Context.NONE); - - Assertions.assertEquals("dtfgxqbawpcbb", response.iterator().next().location()); - Assertions.assertEquals("cyknapqofyuicd", response.iterator().next().tags().get("zb")); - Assertions.assertEquals(MyWorkbookManagedIdentityType.NONE, response.iterator().next().identity().type()); - Assertions.assertEquals("ybww", response.iterator().next().id()); - Assertions.assertEquals("bdvibidmhmwffpl", response.iterator().next().name()); - Assertions.assertEquals("muvapc", response.iterator().next().type()); - Assertions.assertEquals("uxvnsasbcrymodi", response.iterator().next().etag().get("rxklobdxnazpmk")); - Assertions.assertEquals(Kind.SHARED, response.iterator().next().kind()); - Assertions.assertEquals("htuevrhrljy", response.iterator().next().displayName()); - Assertions.assertEquals("ogwxhnsduugwb", response.iterator().next().serializedData()); - Assertions.assertEquals("e", response.iterator().next().version()); - Assertions.assertEquals("hhtklnvnafvvkyfe", response.iterator().next().category()); - Assertions.assertEquals("jboslcqxypok", response.iterator().next().tagsPropertiesTags().get(0)); - Assertions.assertEquals("ngnbdxxew", response.iterator().next().sourceId()); - Assertions.assertEquals("invudbch", response.iterator().next().storageUri()); - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksListMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksListMockTests.java deleted file mode 100644 index 157d77a003b5..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksListMockTests.java +++ /dev/null @@ -1,58 +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.resourcemanager.applicationinsights.generated; - -import com.azure.core.credential.AccessToken; -import com.azure.core.http.HttpClient; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.profile.AzureProfile; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; -import com.azure.resourcemanager.applicationinsights.models.CategoryType; -import com.azure.resourcemanager.applicationinsights.models.Kind; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbook; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbookManagedIdentityType; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import java.util.Arrays; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -public final class MyWorkbooksListMockTests { - @Test - public void testList() throws Exception { - String responseStr - = "{\"value\":[{\"kind\":\"shared\",\"properties\":{\"displayName\":\"k\",\"serializedData\":\"haim\",\"version\":\"iroqbosh\",\"timeModified\":\"a\",\"category\":\"apyyrmfsvbpavbo\",\"tags\":[\"pdbwnupgahxkum\",\"sjcaacfdmmcpugm\",\"hqepvufhbzehewh\",\"qhnlbqnbld\"],\"userId\":\"aclgschorimk\",\"sourceId\":\"r\",\"storageUri\":\"oucs\"},\"identity\":{\"userAssignedIdentities\":{\"principalId\":\"uviyfcaabeo\",\"tenantId\":\"bh\"},\"type\":\"UserAssigned\"},\"id\":\"wndyqleallk\",\"name\":\"mtkhlowkxxpvbr\",\"type\":\"fjmzsyzfho\",\"etag\":{\"ksaoafcluqvox\":\"wgfstmhqykizm\"},\"location\":\"ycjimryvwgcwwpbm\",\"tags\":{\"wefohecbvo\":\"esyds\"}}]}"; - - HttpClient httpClient - = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); - ApplicationInsightsManager manager = ApplicationInsightsManager.configure() - .withHttpClient(httpClient) - .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); - - PagedIterable response = manager.myWorkbooks() - .list(CategoryType.RETENTION, Arrays.asList("crrvweyo"), false, com.azure.core.util.Context.NONE); - - Assertions.assertEquals("ycjimryvwgcwwpbm", response.iterator().next().location()); - Assertions.assertEquals("esyds", response.iterator().next().tags().get("wefohecbvo")); - Assertions.assertEquals(MyWorkbookManagedIdentityType.USER_ASSIGNED, - response.iterator().next().identity().type()); - Assertions.assertEquals("wndyqleallk", response.iterator().next().id()); - Assertions.assertEquals("mtkhlowkxxpvbr", response.iterator().next().name()); - Assertions.assertEquals("fjmzsyzfho", response.iterator().next().type()); - Assertions.assertEquals("wgfstmhqykizm", response.iterator().next().etag().get("ksaoafcluqvox")); - Assertions.assertEquals(Kind.SHARED, response.iterator().next().kind()); - Assertions.assertEquals("k", response.iterator().next().displayName()); - Assertions.assertEquals("haim", response.iterator().next().serializedData()); - Assertions.assertEquals("iroqbosh", response.iterator().next().version()); - Assertions.assertEquals("apyyrmfsvbpavbo", response.iterator().next().category()); - Assertions.assertEquals("pdbwnupgahxkum", response.iterator().next().tagsPropertiesTags().get(0)); - Assertions.assertEquals("r", response.iterator().next().sourceId()); - Assertions.assertEquals("oucs", response.iterator().next().storageUri()); - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksListResultTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksListResultTests.java deleted file mode 100644 index f8e4cc98598b..000000000000 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/MyWorkbooksListResultTests.java +++ /dev/null @@ -1,26 +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.resourcemanager.applicationinsights.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.applicationinsights.models.MyWorkbooksListResult; -import org.junit.jupiter.api.Assertions; - -public final class MyWorkbooksListResultTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - MyWorkbooksListResult model = BinaryData.fromString( - "{\"value\":[{\"kind\":\"user\",\"properties\":{\"displayName\":\"yqagvrvm\",\"serializedData\":\"pkukghi\",\"version\":\"blxgwimf\",\"timeModified\":\"hfjx\",\"category\":\"mszkkfo\",\"tags\":[\"yfkzik\",\"jawneaiv\",\"wczelpci\"],\"userId\":\"lsfeaenwabfatkld\",\"sourceId\":\"bjhwuaan\",\"storageUri\":\"jos\"},\"identity\":{\"userAssignedIdentities\":{\"principalId\":\"l\",\"tenantId\":\"rvxaglrvimjwosy\"},\"type\":\"UserAssigned\"},\"id\":\"rw\",\"name\":\"yc\",\"type\":\"duhpk\",\"etag\":{\"fatpxllrxcyjmoa\":\"db\"},\"location\":\"su\",\"tags\":{\"wdmjsjqbjhhyx\":\"m\"}},{\"kind\":\"user\",\"properties\":{\"displayName\":\"mareqnajxqugj\",\"serializedData\":\"ky\",\"version\":\"beddgssofw\",\"timeModified\":\"zqalkrmnjijpx\",\"category\":\"cqqudf\",\"tags\":[\"xbaaabjyv\",\"yffimrzrtuzqogs\",\"xnevfdnwn\",\"mewzsyyc\"],\"userId\":\"zsoibjudpfrxtr\",\"sourceId\":\"zvaytdwkqbr\",\"storageUri\":\"bpaxhexiilivpdt\"},\"identity\":{\"userAssignedIdentities\":{\"principalId\":\"d\",\"tenantId\":\"axoruzfgsquy\"},\"type\":\"UserAssigned\"},\"id\":\"dxrbuukzcle\",\"name\":\"yhmlwpaztzp\",\"type\":\"fn\",\"etag\":{\"oo\":\"kniod\",\"ujhemmsbvdkcrodt\":\"bw\"},\"location\":\"infwjlfltkacjve\",\"tags\":{\"kfpagao\":\"lfoakg\",\"jnsjervtiagxsd\":\"pulpqblylsyxk\",\"beyvpnqicvinvkjj\":\"zuempsbzkf\"}},{\"kind\":\"shared\",\"properties\":{\"displayName\":\"yfzqwhxxbu\",\"serializedData\":\"qa\",\"version\":\"feqztppriol\",\"timeModified\":\"rjaltolmncw\",\"category\":\"obqwcsdbnwdcfh\",\"tags\":[\"dpfuvg\",\"sbjjc\",\"nvxbvt\",\"udutnco\"],\"userId\":\"r\",\"sourceId\":\"qtvcofudflvkgj\",\"storageUri\":\"gdknnqv\"},\"identity\":{\"userAssignedIdentities\":{\"principalId\":\"n\",\"tenantId\":\"rudsg\"},\"type\":\"UserAssigned\"},\"id\":\"oxciqopidoamcio\",\"name\":\"hkh\",\"type\":\"zxkhnzbonlwnto\",\"etag\":{\"kif\":\"xwabmqoe\"},\"location\":\"vtpuqujmqlgk\",\"tags\":{\"ongbjcnt\":\"ndo\",\"ojvdcpzfoqo\":\"jitcjedftwwaez\",\"ybxarzgszu\":\"i\"}}],\"nextLink\":\"okdwb\"}") - .toObject(MyWorkbooksListResult.class); - Assertions.assertEquals("okdwb", model.nextLink()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - MyWorkbooksListResult model = new MyWorkbooksListResult().withNextLink("okdwb"); - model = BinaryData.fromObject(model).toObject(MyWorkbooksListResult.class); - Assertions.assertEquals("okdwb", model.nextLink()); - } -} diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ProactiveDetectionConfigurationsGetWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ProactiveDetectionConfigurationsGetWithResponseMockTests.java index 83b428ce0065..53c8d52a2784 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ProactiveDetectionConfigurationsGetWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ProactiveDetectionConfigurationsGetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.models.ApplicationInsightsComponentProactiveDetectionConfiguration; @@ -21,31 +21,31 @@ public final class ProactiveDetectionConfigurationsGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"Name\":\"sckdlp\",\"Enabled\":true,\"SendEmailsToSubscriptionOwners\":true,\"CustomEmails\":[\"a\",\"lc\"],\"LastUpdatedTime\":\"wmdboxdfgsftuf\",\"RuleDefinitions\":{\"Name\":\"rjlnacgcck\",\"DisplayName\":\"hxkizvytnrzv\",\"Description\":\"jraaeranokqguk\",\"HelpUrl\":\"qnvb\",\"IsHidden\":true,\"IsEnabledByDefault\":false,\"IsInPreview\":true,\"SupportsEmailNotifications\":false}}"; + = "{\"name\":\"gncxykxhdj\",\"enabled\":false,\"sendEmailsToSubscriptionOwners\":true,\"customEmails\":[\"x\",\"h\",\"cporxvxcjz\"],\"lastUpdatedTime\":\"izxfpxt\",\"ruleDefinitions\":{\"Name\":\"cja\",\"DisplayName\":\"t\",\"Description\":\"hdqazkmtgguwp\",\"HelpUrl\":\"r\",\"IsHidden\":false,\"IsEnabledByDefault\":true,\"IsInPreview\":true,\"SupportsEmailNotifications\":false}}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); ApplicationInsightsComponentProactiveDetectionConfiguration response = manager.proactiveDetectionConfigurations() - .getWithResponse("vodhtn", "irudh", "m", com.azure.core.util.Context.NONE) + .getWithResponse("fb", "usnfepgfewet", "l", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("sckdlp", response.name()); - Assertions.assertEquals(true, response.enabled()); + Assertions.assertEquals("gncxykxhdj", response.name()); + Assertions.assertEquals(false, response.enabled()); Assertions.assertEquals(true, response.sendEmailsToSubscriptionOwners()); - Assertions.assertEquals("a", response.customEmails().get(0)); - Assertions.assertEquals("wmdboxdfgsftuf", response.lastUpdatedTime()); - Assertions.assertEquals("rjlnacgcck", response.ruleDefinitions().name()); - Assertions.assertEquals("hxkizvytnrzv", response.ruleDefinitions().displayName()); - Assertions.assertEquals("jraaeranokqguk", response.ruleDefinitions().description()); - Assertions.assertEquals("qnvb", response.ruleDefinitions().helpUrl()); - Assertions.assertEquals(true, response.ruleDefinitions().isHidden()); - Assertions.assertEquals(false, response.ruleDefinitions().isEnabledByDefault()); + Assertions.assertEquals("x", response.customEmails().get(0)); + Assertions.assertEquals("izxfpxt", response.lastUpdatedTime()); + Assertions.assertEquals("cja", response.ruleDefinitions().name()); + Assertions.assertEquals("t", response.ruleDefinitions().displayName()); + Assertions.assertEquals("hdqazkmtgguwp", response.ruleDefinitions().description()); + Assertions.assertEquals("r", response.ruleDefinitions().helpUrl()); + Assertions.assertEquals(false, response.ruleDefinitions().isHidden()); + Assertions.assertEquals(true, response.ruleDefinitions().isEnabledByDefault()); Assertions.assertEquals(true, response.ruleDefinitions().isInPreview()); Assertions.assertEquals(false, response.ruleDefinitions().supportsEmailNotifications()); } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ProactiveDetectionConfigurationsListWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ProactiveDetectionConfigurationsListWithResponseMockTests.java index d95ee327af1d..7dd585f26202 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ProactiveDetectionConfigurationsListWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ProactiveDetectionConfigurationsListWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.models.ApplicationInsightsComponentProactiveDetectionConfiguration; @@ -22,32 +22,32 @@ public final class ProactiveDetectionConfigurationsListWithResponseMockTests { @Test public void testListWithResponse() throws Exception { String responseStr - = "[{\"Name\":\"zgtila\",\"Enabled\":true,\"SendEmailsToSubscriptionOwners\":false,\"CustomEmails\":[\"yvi\",\"ouwivkxoyzunbixx\",\"ti\"],\"LastUpdatedTime\":\"cpwpg\",\"RuleDefinitions\":{\"Name\":\"civtsoxfrkenxp\",\"DisplayName\":\"yefrpmpdnqqska\",\"Description\":\"oqvm\",\"HelpUrl\":\"npqfrtqlkzmeg\",\"IsHidden\":true,\"IsEnabledByDefault\":false,\"IsInPreview\":false,\"SupportsEmailNotifications\":true}},{\"Name\":\"qdrfegcealzxwhc\",\"Enabled\":false,\"SendEmailsToSubscriptionOwners\":false,\"CustomEmails\":[\"qhlwigdivbkbxgo\",\"fajuwas\",\"vdaeyyguxakjsq\",\"hzbezkgi\"],\"LastUpdatedTime\":\"idxas\",\"RuleDefinitions\":{\"Name\":\"dyvvjskgfmocwahp\",\"DisplayName\":\"atjeaahh\",\"Description\":\"hhnakzybbj\",\"HelpUrl\":\"dj\",\"IsHidden\":false,\"IsEnabledByDefault\":true,\"IsInPreview\":true,\"SupportsEmailNotifications\":false}},{\"Name\":\"vblbjednljlageua\",\"Enabled\":false,\"SendEmailsToSubscriptionOwners\":true,\"CustomEmails\":[\"jbnkpp\",\"ynenlsvxeizz\"],\"LastUpdatedTime\":\"klnsrmffey\",\"RuleDefinitions\":{\"Name\":\"ktp\",\"DisplayName\":\"merteeammxqiek\",\"Description\":\"zddrt\",\"HelpUrl\":\"doj\",\"IsHidden\":false,\"IsEnabledByDefault\":false,\"IsInPreview\":false,\"SupportsEmailNotifications\":true}},{\"Name\":\"eesvecu\",\"Enabled\":false,\"SendEmailsToSubscriptionOwners\":false,\"CustomEmails\":[\"uwprtujwsawd\"],\"LastUpdatedTime\":\"ibabxvititvtzeex\",\"RuleDefinitions\":{\"Name\":\"xtfglecdmdqb\",\"DisplayName\":\"ypq\",\"Description\":\"sfj\",\"HelpUrl\":\"b\",\"IsHidden\":false,\"IsEnabledByDefault\":false,\"IsInPreview\":false,\"SupportsEmailNotifications\":true}}]"; + = "[{\"name\":\"wifzmp\",\"enabled\":true,\"sendEmailsToSubscriptionOwners\":true,\"customEmails\":[\"kfxcvhrfs\"],\"lastUpdatedTime\":\"uagrttikteusqc\",\"ruleDefinitions\":{\"Name\":\"yklxubyjaffmmfbl\",\"DisplayName\":\"cuubgq\",\"Description\":\"rtalmet\",\"HelpUrl\":\"wgdsl\",\"IsHidden\":false,\"IsEnabledByDefault\":false,\"IsInPreview\":false,\"SupportsEmailNotifications\":false}},{\"name\":\"z\",\"enabled\":true,\"sendEmailsToSubscriptionOwners\":false,\"customEmails\":[\"utcxapzhy\"],\"lastUpdatedTime\":\"etoge\",\"ruleDefinitions\":{\"Name\":\"xslhvnhlabrqnkk\",\"DisplayName\":\"cjbtrgaehvvib\",\"Description\":\"jj\",\"HelpUrl\":\"oqbeitpkxzt\",\"IsHidden\":false,\"IsEnabledByDefault\":false,\"IsInPreview\":false,\"SupportsEmailNotifications\":false}},{\"name\":\"gfcwqmpimaqxzhem\",\"enabled\":false,\"sendEmailsToSubscriptionOwners\":true,\"customEmails\":[\"swtwkozzwc\",\"lkb\",\"wpfaj\"],\"lastUpdatedTime\":\"wltlwtjjguktalh\",\"ruleDefinitions\":{\"Name\":\"kcdmxzrpoaimln\",\"DisplayName\":\"aaomylweazu\",\"Description\":\"sethwwn\",\"HelpUrl\":\"hlf\",\"IsHidden\":false,\"IsEnabledByDefault\":false,\"IsInPreview\":true,\"SupportsEmailNotifications\":true}}]"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); List response = manager.proactiveDetectionConfigurations() - .listWithResponse("slynsqyrpfoo", "rlttymsjnygqdnfw", com.azure.core.util.Context.NONE) + .listWithResponse("txmwoteyow", "luqovekqvg", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("zgtila", response.get(0).name()); + Assertions.assertEquals("wifzmp", response.get(0).name()); Assertions.assertEquals(true, response.get(0).enabled()); - Assertions.assertEquals(false, response.get(0).sendEmailsToSubscriptionOwners()); - Assertions.assertEquals("yvi", response.get(0).customEmails().get(0)); - Assertions.assertEquals("cpwpg", response.get(0).lastUpdatedTime()); - Assertions.assertEquals("civtsoxfrkenxp", response.get(0).ruleDefinitions().name()); - Assertions.assertEquals("yefrpmpdnqqska", response.get(0).ruleDefinitions().displayName()); - Assertions.assertEquals("oqvm", response.get(0).ruleDefinitions().description()); - Assertions.assertEquals("npqfrtqlkzmeg", response.get(0).ruleDefinitions().helpUrl()); - Assertions.assertEquals(true, response.get(0).ruleDefinitions().isHidden()); + Assertions.assertEquals(true, response.get(0).sendEmailsToSubscriptionOwners()); + Assertions.assertEquals("kfxcvhrfs", response.get(0).customEmails().get(0)); + Assertions.assertEquals("uagrttikteusqc", response.get(0).lastUpdatedTime()); + Assertions.assertEquals("yklxubyjaffmmfbl", response.get(0).ruleDefinitions().name()); + Assertions.assertEquals("cuubgq", response.get(0).ruleDefinitions().displayName()); + Assertions.assertEquals("rtalmet", response.get(0).ruleDefinitions().description()); + Assertions.assertEquals("wgdsl", response.get(0).ruleDefinitions().helpUrl()); + Assertions.assertEquals(false, response.get(0).ruleDefinitions().isHidden()); Assertions.assertEquals(false, response.get(0).ruleDefinitions().isEnabledByDefault()); Assertions.assertEquals(false, response.get(0).ruleDefinitions().isInPreview()); - Assertions.assertEquals(true, response.get(0).ruleDefinitions().supportsEmailNotifications()); + Assertions.assertEquals(false, response.get(0).ruleDefinitions().supportsEmailNotifications()); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ProactiveDetectionConfigurationsUpdateWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ProactiveDetectionConfigurationsUpdateWithResponseMockTests.java index 8ffa96d858f5..02f428d0a6c2 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ProactiveDetectionConfigurationsUpdateWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/ProactiveDetectionConfigurationsUpdateWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.fluent.models.ApplicationInsightsComponentProactiveDetectionConfigurationInner; @@ -24,47 +24,48 @@ public final class ProactiveDetectionConfigurationsUpdateWithResponseMockTests { @Test public void testUpdateWithResponse() throws Exception { String responseStr - = "{\"Name\":\"fidltug\",\"Enabled\":true,\"SendEmailsToSubscriptionOwners\":false,\"CustomEmails\":[\"sjhoiftxfkfwegpr\",\"ptil\",\"ucb\"],\"LastUpdatedTime\":\"tgdqohmcwsldriz\",\"RuleDefinitions\":{\"Name\":\"wbralllibphbqzm\",\"DisplayName\":\"aka\",\"Description\":\"nkjpdnjzha\",\"HelpUrl\":\"ylhjlm\",\"IsHidden\":false,\"IsEnabledByDefault\":false,\"IsInPreview\":true,\"SupportsEmailNotifications\":true}}"; + = "{\"name\":\"zjyi\",\"enabled\":false,\"sendEmailsToSubscriptionOwners\":false,\"customEmails\":[\"dyp\",\"hyuemslyn\",\"qyrp\"],\"lastUpdatedTime\":\"obrltt\",\"ruleDefinitions\":{\"Name\":\"jnygq\",\"DisplayName\":\"fwqzdz\",\"Description\":\"ilaxhn\",\"HelpUrl\":\"qlyvijo\",\"IsHidden\":false,\"IsEnabledByDefault\":true,\"IsInPreview\":true,\"SupportsEmailNotifications\":false}}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); - ApplicationInsightsComponentProactiveDetectionConfiguration response = manager - .proactiveDetectionConfigurations() - .updateWithResponse("cdisd", "sfjbjsvg", "rwhryvycytd", - new ApplicationInsightsComponentProactiveDetectionConfigurationInner().withName("xgccknfnw") - .withEnabled(true) - .withSendEmailsToSubscriptionOwners(true) - .withCustomEmails(Arrays.asList("vjdhttzaefedxih", "hrphkmcrjdqn", "dfzpbgtgkylkdg")) - .withLastUpdatedTime("jeuut") - .withRuleDefinitions( - new ApplicationInsightsComponentProactiveDetectionConfigurationRuleDefinitions().withName("ez") - .withDisplayName("hokvbwnh") - .withDescription("qlgehg") - .withHelpUrl("ipifhpfeoajvg") - .withIsHidden(true) - .withIsEnabledByDefault(true) - .withIsInPreview(false) - .withSupportsEmailNotifications(true)), - com.azure.core.util.Context.NONE) - .getValue(); + ApplicationInsightsComponentProactiveDetectionConfiguration response + = manager.proactiveDetectionConfigurations() + .updateWithResponse("f", "fiwrxgkn", "uvyinzqodfvpgs", + new ApplicationInsightsComponentProactiveDetectionConfigurationInner().withName("xgsg") + .withEnabled(true) + .withSendEmailsToSubscriptionOwners(true) + .withCustomEmails(Arrays.asList("tx", "zflbqvg", "qvlgafcqusrdvetn", "sdtutnwlduyc")) + .withLastUpdatedTime("zhyrmewipmve") + .withRuleDefinitions( + new ApplicationInsightsComponentProactiveDetectionConfigurationRuleDefinitions() + .withName("ukuqgsj") + .withDisplayName("undxgketw") + .withDescription("hzjhf") + .withHelpUrl("hvvmuvgpmun") + .withIsHidden(false) + .withIsEnabledByDefault(false) + .withIsInPreview(true) + .withSupportsEmailNotifications(false)), + com.azure.core.util.Context.NONE) + .getValue(); - Assertions.assertEquals("fidltug", response.name()); - Assertions.assertEquals(true, response.enabled()); + Assertions.assertEquals("zjyi", response.name()); + Assertions.assertEquals(false, response.enabled()); Assertions.assertEquals(false, response.sendEmailsToSubscriptionOwners()); - Assertions.assertEquals("sjhoiftxfkfwegpr", response.customEmails().get(0)); - Assertions.assertEquals("tgdqohmcwsldriz", response.lastUpdatedTime()); - Assertions.assertEquals("wbralllibphbqzm", response.ruleDefinitions().name()); - Assertions.assertEquals("aka", response.ruleDefinitions().displayName()); - Assertions.assertEquals("nkjpdnjzha", response.ruleDefinitions().description()); - Assertions.assertEquals("ylhjlm", response.ruleDefinitions().helpUrl()); + Assertions.assertEquals("dyp", response.customEmails().get(0)); + Assertions.assertEquals("obrltt", response.lastUpdatedTime()); + Assertions.assertEquals("jnygq", response.ruleDefinitions().name()); + Assertions.assertEquals("fwqzdz", response.ruleDefinitions().displayName()); + Assertions.assertEquals("ilaxhn", response.ruleDefinitions().description()); + Assertions.assertEquals("qlyvijo", response.ruleDefinitions().helpUrl()); Assertions.assertEquals(false, response.ruleDefinitions().isHidden()); - Assertions.assertEquals(false, response.ruleDefinitions().isEnabledByDefault()); + Assertions.assertEquals(true, response.ruleDefinitions().isEnabledByDefault()); Assertions.assertEquals(true, response.ruleDefinitions().isInPreview()); - Assertions.assertEquals(true, response.ruleDefinitions().supportsEmailNotifications()); + Assertions.assertEquals(false, response.ruleDefinitions().supportsEmailNotifications()); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/UserAssignedIdentityTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/UserAssignedIdentityTests.java index 3ad442558d93..e461cc7e79ce 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/UserAssignedIdentityTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/UserAssignedIdentityTests.java @@ -11,7 +11,7 @@ public final class UserAssignedIdentityTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { UserAssignedIdentity model = BinaryData.fromString( - "{\"principalId\":\"2ee8ecb3-1605-472f-929a-3f0f45fe9757\",\"clientId\":\"b8cf1408-b11f-4f77-b76c-776de5d7e2dc\"}") + "{\"principalId\":\"d44380d0-fd31-4716-bc00-15e8af057d28\",\"clientId\":\"8b906726-c480-4f46-a13c-012510983543\"}") .toObject(UserAssignedIdentity.class); } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WebTestLocationsListMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WebTestLocationsListMockTests.java index 38f60796fc8a..0a293bb60e73 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WebTestLocationsListMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WebTestLocationsListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.models.ApplicationInsightsComponentWebTestLocation; @@ -20,17 +20,17 @@ public final class WebTestLocationsListMockTests { @Test public void testList() throws Exception { - String responseStr = "{\"value\":[{\"DisplayName\":\"xieixynllxec\",\"Tag\":\"rojphslhcawjutif\"}]}"; + String responseStr = "{\"value\":[{\"DisplayName\":\"oqltfae\",\"Tag\":\"inmfgvxirp\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response - = manager.webTestLocations().list("ri", "kzobgopxlhsln", com.azure.core.util.Context.NONE); + = manager.webTestLocations().list("qzbqqxlajrnwxa", "evehjkuyxoaf", com.azure.core.util.Context.NONE); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WebTestsDeleteByResourceGroupWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WebTestsDeleteByResourceGroupWithResponseMockTests.java index 2f47a821dce8..8f099c7bc5dc 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WebTestsDeleteByResourceGroupWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WebTestsDeleteByResourceGroupWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import java.nio.charset.StandardCharsets; @@ -25,9 +25,10 @@ public void testDeleteWithResponse() throws Exception { ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); - manager.webTests().deleteByResourceGroupWithResponse("iiqbi", "htmwwinh", com.azure.core.util.Context.NONE); + manager.webTests() + .deleteByResourceGroupWithResponse("rtle", "pqxbkwvzgnzvdf", com.azure.core.util.Context.NONE); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkItemConfigurationsCreateWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkItemConfigurationsCreateWithResponseMockTests.java index 3e444c5d10f3..bee9d94916de 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkItemConfigurationsCreateWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkItemConfigurationsCreateWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.models.WorkItemConfiguration; @@ -24,29 +24,30 @@ public final class WorkItemConfigurationsCreateWithResponseMockTests { @Test public void testCreateWithResponse() throws Exception { String responseStr - = "{\"ConnectorId\":\"yxeb\",\"ConfigDisplayName\":\"bpmzzn\",\"IsDefault\":false,\"Id\":\"yaqitmhheioqaqhv\",\"ConfigProperties\":\"ufuqyrx\"}"; + = "{\"ConnectorId\":\"dyvvjskgfmocwahp\",\"ConfigDisplayName\":\"atjeaahh\",\"IsDefault\":true,\"Id\":\"na\",\"ConfigProperties\":\"ybbjjidjksyx\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); WorkItemConfiguration response = manager.workItemConfigurations() - .createWithResponse("xveabf", "xnmwmqtibxyijddt", - new WorkItemCreateConfiguration().withConnectorId("cttadi") - .withConnectorDataConfiguration("eukmr") - .withValidateOnly(false) - .withWorkItemProperties(mapOf("igpibud", "pndzaapmudqmeq")), + .createWithResponse("pqfrtqlkz", "egnitg", + new WorkItemCreateConfiguration().withConnectorId("xlzyqd") + .withConnectorDataConfiguration("eg") + .withValidateOnly(true) + .withWorkItemProperties(mapOf("ansym", "xwh", "omfaj", "yqhlwigdivbkbx", "xakjsqzhzb", + "wasqvdaeyyg", "asi", "zkgimsid")), com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("yxeb", response.connectorId()); - Assertions.assertEquals("bpmzzn", response.configDisplayName()); - Assertions.assertEquals(false, response.isDefault()); - Assertions.assertEquals("yaqitmhheioqaqhv", response.id()); - Assertions.assertEquals("ufuqyrx", response.configProperties()); + Assertions.assertEquals("dyvvjskgfmocwahp", response.connectorId()); + Assertions.assertEquals("atjeaahh", response.configDisplayName()); + Assertions.assertEquals(true, response.isDefault()); + Assertions.assertEquals("na", response.id()); + Assertions.assertEquals("ybbjjidjksyx", response.configProperties()); } // Use "Map.of" if available diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkItemConfigurationsDeleteWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkItemConfigurationsDeleteWithResponseMockTests.java index 57a4ba53ac70..b48e9d14a5b2 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkItemConfigurationsDeleteWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkItemConfigurationsDeleteWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import java.nio.charset.StandardCharsets; @@ -25,10 +25,10 @@ public void testDeleteWithResponse() throws Exception { ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); manager.workItemConfigurations() - .deleteWithResponse("khgn", "nzonzl", "piqywnc", com.azure.core.util.Context.NONE); + .deleteWithResponse("merteeammxqiek", "kzddrtkgdojbmxva", "refdee", com.azure.core.util.Context.NONE); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkItemConfigurationsGetDefaultWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkItemConfigurationsGetDefaultWithResponseMockTests.java index afdd7754b489..8ad609eaa53f 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkItemConfigurationsGetDefaultWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkItemConfigurationsGetDefaultWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.models.WorkItemConfiguration; @@ -21,23 +21,23 @@ public final class WorkItemConfigurationsGetDefaultWithResponseMockTests { @Test public void testGetDefaultWithResponse() throws Exception { String responseStr - = "{\"ConnectorId\":\"vfcdisyirn\",\"ConfigDisplayName\":\"hcz\",\"IsDefault\":false,\"Id\":\"zbujrt\",\"ConfigProperties\":\"qvwre\"}"; + = "{\"ConnectorId\":\"mjbnk\",\"ConfigDisplayName\":\"xynenl\",\"IsDefault\":false,\"Id\":\"izzgwkln\",\"ConfigProperties\":\"mffeycxcktpi\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); WorkItemConfiguration response = manager.workItemConfigurations() - .getDefaultWithResponse("dlcgqlsismjqfr", "dgamquhiosrsj", com.azure.core.util.Context.NONE) + .getDefaultWithResponse("yxvxevblbjed", "ljlageuaulxu", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("vfcdisyirn", response.connectorId()); - Assertions.assertEquals("hcz", response.configDisplayName()); + Assertions.assertEquals("mjbnk", response.connectorId()); + Assertions.assertEquals("xynenl", response.configDisplayName()); Assertions.assertEquals(false, response.isDefault()); - Assertions.assertEquals("zbujrt", response.id()); - Assertions.assertEquals("qvwre", response.configProperties()); + Assertions.assertEquals("izzgwkln", response.id()); + Assertions.assertEquals("mffeycxcktpi", response.configProperties()); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkItemConfigurationsGetItemWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkItemConfigurationsGetItemWithResponseMockTests.java index 4d2cb1c094b6..6b4d7ac75d58 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkItemConfigurationsGetItemWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkItemConfigurationsGetItemWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.models.WorkItemConfiguration; @@ -21,23 +21,23 @@ public final class WorkItemConfigurationsGetItemWithResponseMockTests { @Test public void testGetItemWithResponse() throws Exception { String responseStr - = "{\"ConnectorId\":\"eljeamurvzmlovua\",\"ConfigDisplayName\":\"shcxlpmjerbdk\",\"IsDefault\":true,\"Id\":\"di\",\"ConfigProperties\":\"zsdbccxjmon\"}"; + = "{\"ConnectorId\":\"sawddjibabxvi\",\"ConfigDisplayName\":\"tvtzeexavoxtfg\",\"IsDefault\":false,\"Id\":\"m\",\"ConfigProperties\":\"bwpypqtgsfjacb\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); WorkItemConfiguration response = manager.workItemConfigurations() - .getItemWithResponse("jtszcof", "zehtdhgb", "k", com.azure.core.util.Context.NONE) + .getItemWithResponse("vecuijpx", "xs", "wprtu", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("eljeamurvzmlovua", response.connectorId()); - Assertions.assertEquals("shcxlpmjerbdk", response.configDisplayName()); - Assertions.assertEquals(true, response.isDefault()); - Assertions.assertEquals("di", response.id()); - Assertions.assertEquals("zsdbccxjmon", response.configProperties()); + Assertions.assertEquals("sawddjibabxvi", response.connectorId()); + Assertions.assertEquals("tvtzeexavoxtfg", response.configDisplayName()); + Assertions.assertEquals(false, response.isDefault()); + Assertions.assertEquals("m", response.id()); + Assertions.assertEquals("bwpypqtgsfjacb", response.configProperties()); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkItemConfigurationsListMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkItemConfigurationsListMockTests.java index 02be717499ac..9a4932ff8964 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkItemConfigurationsListMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkItemConfigurationsListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.models.WorkItemConfiguration; @@ -22,22 +22,22 @@ public final class WorkItemConfigurationsListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"ConnectorId\":\"aumweoohguufu\",\"ConfigDisplayName\":\"oyjathwtzol\",\"IsDefault\":true,\"Id\":\"wm\",\"ConfigProperties\":\"mebwjscjpah\"}]}"; + = "{\"value\":[{\"ConnectorId\":\"clrcivtsox\",\"ConfigDisplayName\":\"kenx\",\"IsDefault\":true,\"Id\":\"efrp\",\"ConfigProperties\":\"dnqqskawaoqvmmb\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response - = manager.workItemConfigurations().list("sopteecj", "eislstvasylwx", com.azure.core.util.Context.NONE); + = manager.workItemConfigurations().list("un", "ixxrtikvcpw", com.azure.core.util.Context.NONE); - Assertions.assertEquals("aumweoohguufu", response.iterator().next().connectorId()); - Assertions.assertEquals("oyjathwtzol", response.iterator().next().configDisplayName()); + Assertions.assertEquals("clrcivtsox", response.iterator().next().connectorId()); + Assertions.assertEquals("kenx", response.iterator().next().configDisplayName()); Assertions.assertEquals(true, response.iterator().next().isDefault()); - Assertions.assertEquals("wm", response.iterator().next().id()); - Assertions.assertEquals("mebwjscjpah", response.iterator().next().configProperties()); + Assertions.assertEquals("efrp", response.iterator().next().id()); + Assertions.assertEquals("dnqqskawaoqvmmb", response.iterator().next().configProperties()); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkItemConfigurationsUpdateItemWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkItemConfigurationsUpdateItemWithResponseMockTests.java index 864926aded99..06f8d9ef1d09 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkItemConfigurationsUpdateItemWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkItemConfigurationsUpdateItemWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.models.WorkItemConfiguration; @@ -24,29 +24,29 @@ public final class WorkItemConfigurationsUpdateItemWithResponseMockTests { @Test public void testUpdateItemWithResponse() throws Exception { String responseStr - = "{\"ConnectorId\":\"btuodxeszabbel\",\"ConfigDisplayName\":\"umuaslzkwrrwoycq\",\"IsDefault\":false,\"Id\":\"hahnomdrkywuhps\",\"ConfigProperties\":\"uurutlwexxwlalni\"}"; + = "{\"ConnectorId\":\"nhxk\",\"ConfigDisplayName\":\"v\",\"IsDefault\":true,\"Id\":\"zvulj\",\"ConfigProperties\":\"aeranokqgukkjqnv\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); WorkItemConfiguration response = manager.workItemConfigurations() - .updateItemWithResponse("dgnwncypuuwwlt", "uqj", "tzenk", - new WorkItemCreateConfiguration().withConnectorId("fzzhmkdasv") - .withConnectorDataConfiguration("yhbxcudchxgs") - .withValidateOnly(true) - .withWorkItemProperties(mapOf("zbfhfovvac", "forobwjlv")), + .updateItemWithResponse("lhhxudbxvodhtnsi", "ud", "z", + new WorkItemCreateConfiguration().withConnectorId("es") + .withConnectorDataConfiguration("dlpagzrcxfail") + .withValidateOnly(false) + .withWorkItemProperties(mapOf("lnacgcc", "dboxdfgsftufqobr")), com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("btuodxeszabbel", response.connectorId()); - Assertions.assertEquals("umuaslzkwrrwoycq", response.configDisplayName()); - Assertions.assertEquals(false, response.isDefault()); - Assertions.assertEquals("hahnomdrkywuhps", response.id()); - Assertions.assertEquals("uurutlwexxwlalni", response.configProperties()); + Assertions.assertEquals("nhxk", response.connectorId()); + Assertions.assertEquals("v", response.configDisplayName()); + Assertions.assertEquals(true, response.isDefault()); + Assertions.assertEquals("zvulj", response.id()); + Assertions.assertEquals("aeranokqgukkjqnv", response.configProperties()); } // Use "Map.of" if available diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookInnerErrorTraceTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookInnerErrorTraceTests.java index dae587939e24..90b33909669d 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookInnerErrorTraceTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookInnerErrorTraceTests.java @@ -11,7 +11,8 @@ public final class WorkbookInnerErrorTraceTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { WorkbookInnerErrorTrace model - = BinaryData.fromString("{\"trace\":[\"pij\",\"k\",\"xfrdd\"]}").toObject(WorkbookInnerErrorTrace.class); + = BinaryData.fromString("{\"trace\":[\"izsjqlhkrr\",\"bdeibqipqk\",\"hvxndzwmkrefajpj\",\"rwkq\"]}") + .toObject(WorkbookInnerErrorTrace.class); } @org.junit.jupiter.api.Test diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookInnerTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookInnerTests.java index f42538e4c738..73dc7c0f8220 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookInnerTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookInnerTests.java @@ -19,54 +19,53 @@ public final class WorkbookInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { WorkbookInner model = BinaryData.fromString( - "{\"properties\":{\"displayName\":\"vrwxkv\",\"serializedData\":\"kkgll\",\"version\":\"jygvjayvbl\",\"timeModified\":\"2021-09-27T02:30:31Z\",\"category\":\"k\",\"tags\":[\"bxvvyhg\",\"opbyrqufegxu\",\"wz\",\"bnhlmc\"],\"userId\":\"p\",\"sourceId\":\"gitvg\",\"storageUri\":\"hrixkwmy\",\"description\":\"ejvegrhbpnaixex\",\"revision\":\"b\"},\"identity\":{\"principalId\":\"52a01c84-7666-4043-a36f-0d31de1a7b16\",\"tenantId\":\"c0ab3f8b-e6d8-4002-bb4e-cb3206f00edd\",\"type\":\"UserAssigned\",\"userAssignedIdentities\":{\"rrvqa\":{\"principalId\":\"17e592ea-b953-4395-bba4-c63237236532\",\"clientId\":\"06178f40-e6aa-4c6f-a0f9-025ada22e502\"},\"ghtpw\":{\"principalId\":\"689221d0-9fb5-43ae-86ab-3d041c0f168a\",\"clientId\":\"e1ff3a19-dbed-4660-abf9-3a13b385a9c0\"},\"hyjsvfycx\":{\"principalId\":\"10d3c851-e59b-4d54-9d2f-ab1f24611522\",\"clientId\":\"70e43266-ce10-4962-af2f-f44e8feb98f3\"}}},\"kind\":\"shared\",\"etag\":\"oowvrv\",\"location\":\"t\",\"tags\":{\"pnsxkmcwaek\":\"ppyostronzmyhgf\"},\"id\":\"rjreafxts\",\"name\":\"umh\",\"type\":\"glikkxwslolb\"}") + "{\"properties\":{\"displayName\":\"etaebu\",\"serializedData\":\"u\",\"version\":\"movsmzlxwabmqoe\",\"timeModified\":\"2021-08-18T18:08:28Z\",\"category\":\"frvtpuqu\",\"tags\":[\"lgkfbt\",\"doaon\"],\"userId\":\"jcntuj\",\"sourceId\":\"c\",\"storageUri\":\"df\",\"description\":\"waezkojvd\",\"revision\":\"zfoqouicybxar\"},\"identity\":{\"principalId\":\"893ebfbf-d4b3-4a1e-8482-7de0e5ae3930\",\"tenantId\":\"abe292d4-0ee8-4a96-bdd1-e344cdd99ad4\",\"type\":\"SystemAssigned\",\"userAssignedIdentities\":{\"q\":{\"principalId\":\"dc7ad656-3f61-4a5c-89db-fb0b770ff554\",\"clientId\":\"51c0109a-576a-4290-a2ee-cb31fb4f9793\"}}},\"kind\":\"shared\",\"etag\":\"oamciodh\",\"location\":\"haz\",\"tags\":{\"onlwntoeg\":\"nz\",\"mrv\":\"kdwbwhkszz\"},\"id\":\"xztvbtqgsfraoyzk\",\"name\":\"owtlmnguxawqald\",\"type\":\"yuuximerqfobwyzn\"}") .toObject(WorkbookInner.class); - Assertions.assertEquals("t", model.location()); - Assertions.assertEquals("ppyostronzmyhgf", model.tags().get("pnsxkmcwaek")); - Assertions.assertEquals(ManagedServiceIdentityType.USER_ASSIGNED, model.identity().type()); + Assertions.assertEquals("haz", model.location()); + Assertions.assertEquals("nz", model.tags().get("onlwntoeg")); + Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_ASSIGNED, model.identity().type()); Assertions.assertEquals(WorkbookSharedTypeKind.SHARED, model.kind()); - Assertions.assertEquals("oowvrv", model.etag()); - Assertions.assertEquals("vrwxkv", model.displayName()); - Assertions.assertEquals("kkgll", model.serializedData()); - Assertions.assertEquals("jygvjayvbl", model.version()); - Assertions.assertEquals("k", model.category()); - Assertions.assertEquals("bxvvyhg", model.tagsPropertiesTags().get(0)); - Assertions.assertEquals("gitvg", model.sourceId()); - Assertions.assertEquals("hrixkwmy", model.storageUri()); - Assertions.assertEquals("ejvegrhbpnaixex", model.description()); + Assertions.assertEquals("oamciodh", model.etag()); + Assertions.assertEquals("etaebu", model.displayName()); + Assertions.assertEquals("u", model.serializedData()); + Assertions.assertEquals("movsmzlxwabmqoe", model.version()); + Assertions.assertEquals("frvtpuqu", model.category()); + Assertions.assertEquals("lgkfbt", model.tagsPropertiesTags().get(0)); + Assertions.assertEquals("c", model.sourceId()); + Assertions.assertEquals("df", model.storageUri()); + Assertions.assertEquals("waezkojvd", model.description()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - WorkbookInner model = new WorkbookInner().withLocation("t") - .withTags(mapOf("pnsxkmcwaek", "ppyostronzmyhgf")) - .withIdentity(new WorkbookResourceIdentity().withType(ManagedServiceIdentityType.USER_ASSIGNED) - .withUserAssignedIdentities(mapOf("rrvqa", new UserAssignedIdentity(), "ghtpw", - new UserAssignedIdentity(), "hyjsvfycx", new UserAssignedIdentity()))) + WorkbookInner model = new WorkbookInner().withLocation("haz") + .withTags(mapOf("onlwntoeg", "nz", "mrv", "kdwbwhkszz")) + .withIdentity(new WorkbookResourceIdentity().withType(ManagedServiceIdentityType.SYSTEM_ASSIGNED) + .withUserAssignedIdentities(mapOf("q", new UserAssignedIdentity()))) .withKind(WorkbookSharedTypeKind.SHARED) - .withEtag("oowvrv") - .withDisplayName("vrwxkv") - .withSerializedData("kkgll") - .withVersion("jygvjayvbl") - .withCategory("k") - .withTagsPropertiesTags(Arrays.asList("bxvvyhg", "opbyrqufegxu", "wz", "bnhlmc")) - .withSourceId("gitvg") - .withStorageUri("hrixkwmy") - .withDescription("ejvegrhbpnaixex"); + .withEtag("oamciodh") + .withDisplayName("etaebu") + .withSerializedData("u") + .withVersion("movsmzlxwabmqoe") + .withCategory("frvtpuqu") + .withTagsPropertiesTags(Arrays.asList("lgkfbt", "doaon")) + .withSourceId("c") + .withStorageUri("df") + .withDescription("waezkojvd"); model = BinaryData.fromObject(model).toObject(WorkbookInner.class); - Assertions.assertEquals("t", model.location()); - Assertions.assertEquals("ppyostronzmyhgf", model.tags().get("pnsxkmcwaek")); - Assertions.assertEquals(ManagedServiceIdentityType.USER_ASSIGNED, model.identity().type()); + Assertions.assertEquals("haz", model.location()); + Assertions.assertEquals("nz", model.tags().get("onlwntoeg")); + Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_ASSIGNED, model.identity().type()); Assertions.assertEquals(WorkbookSharedTypeKind.SHARED, model.kind()); - Assertions.assertEquals("oowvrv", model.etag()); - Assertions.assertEquals("vrwxkv", model.displayName()); - Assertions.assertEquals("kkgll", model.serializedData()); - Assertions.assertEquals("jygvjayvbl", model.version()); - Assertions.assertEquals("k", model.category()); - Assertions.assertEquals("bxvvyhg", model.tagsPropertiesTags().get(0)); - Assertions.assertEquals("gitvg", model.sourceId()); - Assertions.assertEquals("hrixkwmy", model.storageUri()); - Assertions.assertEquals("ejvegrhbpnaixex", model.description()); + Assertions.assertEquals("oamciodh", model.etag()); + Assertions.assertEquals("etaebu", model.displayName()); + Assertions.assertEquals("u", model.serializedData()); + Assertions.assertEquals("movsmzlxwabmqoe", model.version()); + Assertions.assertEquals("frvtpuqu", model.category()); + Assertions.assertEquals("lgkfbt", model.tagsPropertiesTags().get(0)); + Assertions.assertEquals("c", model.sourceId()); + Assertions.assertEquals("df", model.storageUri()); + Assertions.assertEquals("waezkojvd", model.description()); } // Use "Map.of" if available diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookPropertiesTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookPropertiesTests.java index 3aa3cc1f9460..c525db5a1836 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookPropertiesTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookPropertiesTests.java @@ -13,36 +13,36 @@ public final class WorkbookPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { WorkbookProperties model = BinaryData.fromString( - "{\"displayName\":\"pvuzlmv\",\"serializedData\":\"elfk\",\"version\":\"plcrpwjxeznoig\",\"timeModified\":\"2021-05-13T00:39:55Z\",\"category\":\"jwmwkpnbs\",\"tags\":[\"jjoqkagf\",\"sxtta\",\"gzxnfaazpxdtnk\",\"mkqjj\"],\"userId\":\"uenvrkp\",\"sourceId\":\"uaibrebqaaysj\",\"storageUri\":\"xqtnq\",\"description\":\"ezl\",\"revision\":\"ffiakp\"}") + "{\"displayName\":\"bykutw\",\"serializedData\":\"fhpagmhrskdsnf\",\"version\":\"doakgtdlmkkzevdl\",\"timeModified\":\"2021-08-26T23:11Z\",\"category\":\"pusdstt\",\"tags\":[\"gvbbejdcng\",\"qmoa\",\"ufgmjzrwrdg\"],\"userId\":\"wae\",\"sourceId\":\"uzkopbminrfd\",\"storageUri\":\"yuhhziu\",\"description\":\"fozbhdmsmlmzqhof\",\"revision\":\"maequiahxicslfa\"}") .toObject(WorkbookProperties.class); - Assertions.assertEquals("pvuzlmv", model.displayName()); - Assertions.assertEquals("elfk", model.serializedData()); - Assertions.assertEquals("plcrpwjxeznoig", model.version()); - Assertions.assertEquals("jwmwkpnbs", model.category()); - Assertions.assertEquals("jjoqkagf", model.tags().get(0)); - Assertions.assertEquals("uaibrebqaaysj", model.sourceId()); - Assertions.assertEquals("xqtnq", model.storageUri()); - Assertions.assertEquals("ezl", model.description()); + Assertions.assertEquals("bykutw", model.displayName()); + Assertions.assertEquals("fhpagmhrskdsnf", model.serializedData()); + Assertions.assertEquals("doakgtdlmkkzevdl", model.version()); + Assertions.assertEquals("pusdstt", model.category()); + Assertions.assertEquals("gvbbejdcng", model.tags().get(0)); + Assertions.assertEquals("uzkopbminrfd", model.sourceId()); + Assertions.assertEquals("yuhhziu", model.storageUri()); + Assertions.assertEquals("fozbhdmsmlmzqhof", model.description()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - WorkbookProperties model = new WorkbookProperties().withDisplayName("pvuzlmv") - .withSerializedData("elfk") - .withVersion("plcrpwjxeznoig") - .withCategory("jwmwkpnbs") - .withTags(Arrays.asList("jjoqkagf", "sxtta", "gzxnfaazpxdtnk", "mkqjj")) - .withSourceId("uaibrebqaaysj") - .withStorageUri("xqtnq") - .withDescription("ezl"); + WorkbookProperties model = new WorkbookProperties().withDisplayName("bykutw") + .withSerializedData("fhpagmhrskdsnf") + .withVersion("doakgtdlmkkzevdl") + .withCategory("pusdstt") + .withTags(Arrays.asList("gvbbejdcng", "qmoa", "ufgmjzrwrdg")) + .withSourceId("uzkopbminrfd") + .withStorageUri("yuhhziu") + .withDescription("fozbhdmsmlmzqhof"); model = BinaryData.fromObject(model).toObject(WorkbookProperties.class); - Assertions.assertEquals("pvuzlmv", model.displayName()); - Assertions.assertEquals("elfk", model.serializedData()); - Assertions.assertEquals("plcrpwjxeznoig", model.version()); - Assertions.assertEquals("jwmwkpnbs", model.category()); - Assertions.assertEquals("jjoqkagf", model.tags().get(0)); - Assertions.assertEquals("uaibrebqaaysj", model.sourceId()); - Assertions.assertEquals("xqtnq", model.storageUri()); - Assertions.assertEquals("ezl", model.description()); + Assertions.assertEquals("bykutw", model.displayName()); + Assertions.assertEquals("fhpagmhrskdsnf", model.serializedData()); + Assertions.assertEquals("doakgtdlmkkzevdl", model.version()); + Assertions.assertEquals("pusdstt", model.category()); + Assertions.assertEquals("gvbbejdcng", model.tags().get(0)); + Assertions.assertEquals("uzkopbminrfd", model.sourceId()); + Assertions.assertEquals("yuhhziu", model.storageUri()); + Assertions.assertEquals("fozbhdmsmlmzqhof", model.description()); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookPropertiesUpdateParametersTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookPropertiesUpdateParametersTests.java index 365f70517122..8d05f1ab07b1 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookPropertiesUpdateParametersTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookPropertiesUpdateParametersTests.java @@ -13,30 +13,31 @@ public final class WorkbookPropertiesUpdateParametersTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { WorkbookPropertiesUpdateParameters model = BinaryData.fromString( - "{\"displayName\":\"ydxtqm\",\"serializedData\":\"ox\",\"category\":\"ggufhyaomtb\",\"tags\":[\"avgrvkffovjz\",\"pjbi\"],\"description\":\"jmfxumvf\",\"revision\":\"uyovw\"}") + "{\"displayName\":\"eyebizikayuhql\",\"serializedData\":\"bs\",\"category\":\"bqwrvtldgm\",\"tags\":[\"vm\",\"ipaslthaqfxssmwu\",\"wbdsr\",\"zpdrhneu\"],\"description\":\"wqkdwytisibi\",\"revision\":\"gpikpzimejza\"}") .toObject(WorkbookPropertiesUpdateParameters.class); - Assertions.assertEquals("ydxtqm", model.displayName()); - Assertions.assertEquals("ox", model.serializedData()); - Assertions.assertEquals("ggufhyaomtb", model.category()); - Assertions.assertEquals("avgrvkffovjz", model.tags().get(0)); - Assertions.assertEquals("jmfxumvf", model.description()); - Assertions.assertEquals("uyovw", model.revision()); + Assertions.assertEquals("eyebizikayuhql", model.displayName()); + Assertions.assertEquals("bs", model.serializedData()); + Assertions.assertEquals("bqwrvtldgm", model.category()); + Assertions.assertEquals("vm", model.tags().get(0)); + Assertions.assertEquals("wqkdwytisibi", model.description()); + Assertions.assertEquals("gpikpzimejza", model.revision()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - WorkbookPropertiesUpdateParameters model = new WorkbookPropertiesUpdateParameters().withDisplayName("ydxtqm") - .withSerializedData("ox") - .withCategory("ggufhyaomtb") - .withTags(Arrays.asList("avgrvkffovjz", "pjbi")) - .withDescription("jmfxumvf") - .withRevision("uyovw"); + WorkbookPropertiesUpdateParameters model + = new WorkbookPropertiesUpdateParameters().withDisplayName("eyebizikayuhql") + .withSerializedData("bs") + .withCategory("bqwrvtldgm") + .withTags(Arrays.asList("vm", "ipaslthaqfxssmwu", "wbdsr", "zpdrhneu")) + .withDescription("wqkdwytisibi") + .withRevision("gpikpzimejza"); model = BinaryData.fromObject(model).toObject(WorkbookPropertiesUpdateParameters.class); - Assertions.assertEquals("ydxtqm", model.displayName()); - Assertions.assertEquals("ox", model.serializedData()); - Assertions.assertEquals("ggufhyaomtb", model.category()); - Assertions.assertEquals("avgrvkffovjz", model.tags().get(0)); - Assertions.assertEquals("jmfxumvf", model.description()); - Assertions.assertEquals("uyovw", model.revision()); + Assertions.assertEquals("eyebizikayuhql", model.displayName()); + Assertions.assertEquals("bs", model.serializedData()); + Assertions.assertEquals("bqwrvtldgm", model.category()); + Assertions.assertEquals("vm", model.tags().get(0)); + Assertions.assertEquals("wqkdwytisibi", model.description()); + Assertions.assertEquals("gpikpzimejza", model.revision()); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookResourceIdentityTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookResourceIdentityTests.java index 29562445b1bd..bdc0f5229b16 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookResourceIdentityTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookResourceIdentityTests.java @@ -16,7 +16,7 @@ public final class WorkbookResourceIdentityTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { WorkbookResourceIdentity model = BinaryData.fromString( - "{\"principalId\":\"11c2862b-40d5-43d5-a494-97afaad0bb54\",\"tenantId\":\"87055720-f751-43ec-ad4a-8671b93c4840\",\"type\":\"SystemAssigned,UserAssigned\",\"userAssignedIdentities\":{\"nfdn\":{\"principalId\":\"74132bb2-6b04-484c-91f1-712c0d291dff\",\"clientId\":\"0b7d0cd2-155f-4193-8ee4-eddfe3665bed\"},\"chrdgoihxumwcto\":{\"principalId\":\"513106af-a598-417c-bfde-4e29e05d5220\",\"clientId\":\"da475381-4f67-4aed-a3e1-ed0973d15f35\"}}}") + "{\"principalId\":\"45619ec4-7293-45c1-87ff-088cb1fa4499\",\"tenantId\":\"9b125bbd-432a-428c-9b86-a11cb3ec3fb2\",\"type\":\"SystemAssigned,UserAssigned\",\"userAssignedIdentities\":{\"raehtwdwrft\":{\"principalId\":\"2e5ca98f-75fe-4bcc-a40b-7cf75db91542\",\"clientId\":\"6977fdcf-f34d-4aa3-a6a9-6d799d95aa1e\"},\"byrcdlbhshfwp\":{\"principalId\":\"29445cb0-9b77-4754-9bc3-d1bec0812758\",\"clientId\":\"749a11f0-74fb-4ff2-8f25-8aabda0bf062\"}}}") .toObject(WorkbookResourceIdentity.class); Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, model.type()); } @@ -26,7 +26,7 @@ public void testSerialize() throws Exception { WorkbookResourceIdentity model = new WorkbookResourceIdentity().withType(ManagedServiceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED) .withUserAssignedIdentities( - mapOf("nfdn", new UserAssignedIdentity(), "chrdgoihxumwcto", new UserAssignedIdentity())); + mapOf("raehtwdwrft", new UserAssignedIdentity(), "byrcdlbhshfwp", new UserAssignedIdentity())); model = BinaryData.fromObject(model).toObject(WorkbookResourceIdentity.class); Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, model.type()); } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookResourceTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookResourceTests.java index 4668e0faca5a..7f0137190ffb 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookResourceTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookResourceTests.java @@ -18,33 +18,31 @@ public final class WorkbookResourceTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { WorkbookResource model = BinaryData.fromString( - "{\"identity\":{\"principalId\":\"ffc3fd0a-b0ab-419a-b66c-a4f3599a248a\",\"tenantId\":\"c4ded780-aac6-4067-b0aa-2ed81a3a17f9\",\"type\":\"None\",\"userAssignedIdentities\":{\"tmmjihyeozph\":{\"principalId\":\"c353e8eb-a8ee-47f1-9558-5981fd99bf30\",\"clientId\":\"3d116020-6909-40fe-b79f-7c830e7bf74c\"},\"uyqncygupkvipmd\":{\"principalId\":\"a65e6d26-ff07-43c2-a66a-763f522c1db1\",\"clientId\":\"1884e2a7-250a-4de1-bf20-f7e4bddd7fc4\"},\"xqupevzhf\":{\"principalId\":\"8dd97920-f0ce-4ef9-86c2-a8d86a8ed1ed\",\"clientId\":\"78a2588c-f63d-4254-b7c3-c4c0d19ec431\"},\"txhojujb\":{\"principalId\":\"af289ddd-cb9f-4e84-aaab-8814469f73d6\",\"clientId\":\"8d61e937-ab1e-4726-b2db-71b33b74db26\"}}},\"kind\":\"shared\",\"etag\":\"mc\",\"location\":\"vhixbjxy\",\"tags\":{\"coolsttpkiwkkb\":\"yl\"},\"id\":\"ujrywvtyl\",\"name\":\"fpncurdo\",\"type\":\"wiithtywub\"}") + "{\"identity\":{\"principalId\":\"e770d48c-db47-4403-b216-818a292b766a\",\"tenantId\":\"9b606586-35cb-44a7-86f9-43cfe3a8f023\",\"type\":\"SystemAssigned,UserAssigned\",\"userAssignedIdentities\":{\"alnswhccsphk\":{\"principalId\":\"ddb0172c-723a-40d7-b193-6f3bab193a1c\",\"clientId\":\"7c8aceca-509d-4ad3-9293-5dabeaeb8f0f\"},\"witqscywuggwoluh\":{\"principalId\":\"21402738-76ad-45fd-b5ca-6a0cba734760\",\"clientId\":\"f615bc15-807d-4ccb-8468-201cc3de66f3\"},\"wem\":{\"principalId\":\"2e82b5ad-16be-46b4-9aaf-7db6ab205fd8\",\"clientId\":\"429aa4d0-bc59-46e5-9fc2-2d7373308d7c\"}}},\"kind\":\"shared\",\"etag\":\"sbrgz\",\"location\":\"wmsweypqwd\",\"tags\":{\"qhuexm\":\"icccn\",\"ncsdtclusiyp\":\"ttlstvlzywemhz\",\"ygqukyhejh\":\"sfgytguslfead\"},\"id\":\"isxgfp\",\"name\":\"lolp\",\"type\":\"vk\"}") .toObject(WorkbookResource.class); - Assertions.assertEquals("vhixbjxy", model.location()); - Assertions.assertEquals("yl", model.tags().get("coolsttpkiwkkb")); - Assertions.assertEquals(ManagedServiceIdentityType.NONE, model.identity().type()); + Assertions.assertEquals("wmsweypqwd", model.location()); + Assertions.assertEquals("icccn", model.tags().get("qhuexm")); + Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, model.identity().type()); Assertions.assertEquals(WorkbookSharedTypeKind.SHARED, model.kind()); - Assertions.assertEquals("mc", model.etag()); + Assertions.assertEquals("sbrgz", model.etag()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - WorkbookResource model - = new WorkbookResource().withLocation("vhixbjxy") - .withTags(mapOf("coolsttpkiwkkb", "yl")) - .withIdentity( - new WorkbookResourceIdentity().withType(ManagedServiceIdentityType.NONE) - .withUserAssignedIdentities(mapOf("tmmjihyeozph", new UserAssignedIdentity(), "uyqncygupkvipmd", - new UserAssignedIdentity(), "xqupevzhf", new UserAssignedIdentity(), "txhojujb", - new UserAssignedIdentity()))) - .withKind(WorkbookSharedTypeKind.SHARED) - .withEtag("mc"); + WorkbookResource model = new WorkbookResource().withLocation("wmsweypqwd") + .withTags(mapOf("qhuexm", "icccn", "ncsdtclusiyp", "ttlstvlzywemhz", "ygqukyhejh", "sfgytguslfead")) + .withIdentity( + new WorkbookResourceIdentity().withType(ManagedServiceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED) + .withUserAssignedIdentities(mapOf("alnswhccsphk", new UserAssignedIdentity(), "witqscywuggwoluh", + new UserAssignedIdentity(), "wem", new UserAssignedIdentity()))) + .withKind(WorkbookSharedTypeKind.SHARED) + .withEtag("sbrgz"); model = BinaryData.fromObject(model).toObject(WorkbookResource.class); - Assertions.assertEquals("vhixbjxy", model.location()); - Assertions.assertEquals("yl", model.tags().get("coolsttpkiwkkb")); - Assertions.assertEquals(ManagedServiceIdentityType.NONE, model.identity().type()); + Assertions.assertEquals("wmsweypqwd", model.location()); + Assertions.assertEquals("icccn", model.tags().get("qhuexm")); + Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, model.identity().type()); Assertions.assertEquals(WorkbookSharedTypeKind.SHARED, model.kind()); - Assertions.assertEquals("mc", model.etag()); + Assertions.assertEquals("sbrgz", model.etag()); } // Use "Map.of" if available diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookTemplatesCreateOrUpdateWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookTemplatesCreateOrUpdateWithResponseMockTests.java index 152e9b34988d..aa9060259f4e 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookTemplatesCreateOrUpdateWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookTemplatesCreateOrUpdateWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.models.WorkbookTemplate; @@ -26,80 +26,72 @@ public final class WorkbookTemplatesCreateOrUpdateWithResponseMockTests { @Test public void testCreateOrUpdateWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"priority\":378655951,\"author\":\"hhlkyqltqsrogtu\",\"templateData\":\"datakffdjktsys\",\"galleries\":[{\"name\":\"vclglxnfuij\",\"category\":\"busqogsfi\",\"type\":\"yi\",\"order\":2036577427,\"resourceType\":\"arujt\"},{\"name\":\"qxfzyjqttvwk\",\"category\":\"hjpenuygbq\",\"type\":\"qekewvnqvcd\",\"order\":1408895656,\"resourceType\":\"ucmfdj\"},{\"name\":\"laxpunj\",\"category\":\"kczvvita\",\"type\":\"xmfcsserxhtv\",\"order\":817459269,\"resourceType\":\"lwntsjgqrs\"}],\"localized\":{\"trwahzj\":[{\"templateData\":\"datauuybnchrsz\",\"galleries\":[{},{},{}]},{\"templateData\":\"datauelyetndn\",\"galleries\":[{},{}]},{\"templateData\":\"dataggagfln\",\"galleries\":[{},{}]}]}},\"location\":\"ucftbyrp\",\"tags\":{\"lsnoxaxmqeqalh\":\"hkpigqfusuckzmkw\",\"svkhgbv\":\"jnhgwydyyn\",\"arfdlpukhpyrnei\":\"ta\"},\"id\":\"jcpeogkhnmg\",\"name\":\"ro\",\"type\":\"xddbhfhpfpaz\"}"; + = "{\"properties\":{\"priority\":125495169,\"author\":\"xoe\",\"templateData\":\"dataqinjipnwjf\",\"galleries\":[{\"name\":\"lafcbahh\",\"category\":\"pofoi\",\"type\":\"w\",\"order\":1217605698,\"resourceType\":\"kmkkholvdnd\"},{\"name\":\"auo\",\"category\":\"huartv\",\"type\":\"ukyefchnmnahmnxh\",\"order\":1852256635,\"resourceType\":\"irwrwe\"},{\"name\":\"xffi\",\"category\":\"xwrsnew\",\"type\":\"zqvbubqm\",\"order\":584332320,\"resourceType\":\"ycxhxzgaztta\"},{\"name\":\"idvmfqhppubo\",\"category\":\"epdfgkmtdherng\",\"type\":\"c\",\"order\":2083850408,\"resourceType\":\"okqtobk\"}],\"localized\":{\"nnfhyetefypo\":[{\"templateData\":\"datash\",\"galleries\":[{},{},{},{}]},{\"templateData\":\"datapnulaiywzej\",\"galleries\":[{}]},{\"templateData\":\"datalwkojpllndnpdw\",\"galleries\":[{},{},{},{}]},{\"templateData\":\"datafgf\",\"galleries\":[{},{},{}]}]}},\"location\":\"octfjgtixrjvzuyt\",\"tags\":{\"bauiropi\":\"lmuowo\",\"n\":\"nszonwpngaj\"},\"id\":\"ixjawrtm\",\"name\":\"fjmyccxlzhco\",\"type\":\"ovne\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); WorkbookTemplate response = manager.workbookTemplates() - .define("obkauxofsh") - .withRegion("xdfzantkw") - .withExistingResourceGroup("uahokq") - .withTags( - mapOf("ac", "yamlbnse", "m", "jvpilguooqja", "hrtdtpdelq", "itgueiookjbs", "vcjkgd", "cslmotoebnfxo")) - .withPriority(1507125195) - .withAuthor("nulaiywzejywhsl") - .withTemplateData("datakoj") + .define("vxlx") + .withRegion("gfabuiyjibuzphdu") + .withExistingResourceGroup("rxmunjdxvgln") + .withTags(mapOf("oxgjiuqhibt", "iknp", "pqwjedm", "z")) + .withPriority(46101784) + .withAuthor("ivbgkcv") + .withTemplateData("datahpzvuqdflvoniyp") .withGalleries(Arrays.asList( - new WorkbookTemplateGallery().withName("ndnpdwrpqafgfug") - .withCategory("n") - .withType("yetefyp") - .withOrder(1953030957) - .withResourceType("tfjgt"), - new WorkbookTemplateGallery().withName("rjvzuyt") - .withCategory("mlmuowol") - .withType("uir") - .withOrder(110888706) - .withResourceType("nszonwpngaj"))) - .withLocalized(mapOf("henlusfnr", + new WorkbookTemplateGallery().withName("bcpzgpxtivh") + .withCategory("nidibgqjxg") + .withType("r") + .withOrder(406558372) + .withResourceType("fgpikqm"), + new WorkbookTemplateGallery().withName("ao") + .withCategory("rmzvupo") + .withType("zdfuydzvkfvxcnqm") + .withOrder(547334197) + .withResourceType("wokmvkhlggd"), + new WorkbookTemplateGallery().withName("em") + .withCategory("kzsz") + .withType("iwtglxxhljfpg") + .withOrder(1130709728) + .withResourceType("mnzhrgmqg"), + new WorkbookTemplateGallery().withName("x") + .withCategory("qcbfrmbodths") + .withType("gvriibakclac") + .withOrder(1812641051) + .withResourceType("xousxauzl"))) + .withLocalized(mapOf("hnykz", Arrays.asList( - new WorkbookTemplateLocalizedGallery().withTemplateData("datajawrtmjfjmyc") - .withGalleries(Arrays.asList(new WorkbookTemplateGallery(), new WorkbookTemplateGallery(), - new WorkbookTemplateGallery())), - new WorkbookTemplateLocalizedGallery() - .withTemplateData("datahcoxov") - .withGalleries(Arrays.asList(new WorkbookTemplateGallery(), new WorkbookTemplateGallery()))), - "sfuughtuqfecjx", - Arrays.asList( - new WorkbookTemplateLocalizedGallery().withTemplateData("dataxtxrdcqtjvidt") + new WorkbookTemplateLocalizedGallery().withTemplateData("datawohqfzizvu") .withGalleries(Arrays.asList(new WorkbookTemplateGallery())), - new WorkbookTemplateLocalizedGallery().withTemplateData("datauslvyjtcvuwkasi") - .withGalleries(Arrays.asList(new WorkbookTemplateGallery(), new WorkbookTemplateGallery()))), - "jbaqehgpdoh", - Arrays.asList( - new WorkbookTemplateLocalizedGallery().withTemplateData("datatuhxuicb") - .withGalleries(Arrays.asList(new WorkbookTemplateGallery(), new WorkbookTemplateGallery(), - new WorkbookTemplateGallery(), new WorkbookTemplateGallery())), - new WorkbookTemplateLocalizedGallery().withTemplateData("datarswnjlxuzrhwp") + new WorkbookTemplateLocalizedGallery().withTemplateData("datajsvthnwpzteko") + .withGalleries(Arrays.asList(new WorkbookTemplateGallery())), + new WorkbookTemplateLocalizedGallery().withTemplateData("databiattgplucfotan") .withGalleries(Arrays.asList(new WorkbookTemplateGallery(), new WorkbookTemplateGallery(), - new WorkbookTemplateGallery(), new WorkbookTemplateGallery()))), - "zeqyjleziun", + new WorkbookTemplateGallery()))), + "k", Arrays.asList( - new WorkbookTemplateLocalizedGallery().withTemplateData("dataatucoigebxncn") - .withGalleries(Arrays.asList(new WorkbookTemplateGallery(), new WorkbookTemplateGallery())), - new WorkbookTemplateLocalizedGallery().withTemplateData("databnwgfmxj") - .withGalleries(Arrays.asList(new WorkbookTemplateGallery())), - new WorkbookTemplateLocalizedGallery().withTemplateData("datajbgdlfgtdysnaquf") + new WorkbookTemplateLocalizedGallery().withTemplateData("dataswvxwlmzqwmv") .withGalleries(Arrays.asList(new WorkbookTemplateGallery(), new WorkbookTemplateGallery(), - new WorkbookTemplateGallery())), - new WorkbookTemplateLocalizedGallery().withTemplateData("datatqhamzjrw") + new WorkbookTemplateGallery(), new WorkbookTemplateGallery())), + new WorkbookTemplateLocalizedGallery().withTemplateData("datamxmcuqudtcvclxy") .withGalleries(Arrays.asList(new WorkbookTemplateGallery(), new WorkbookTemplateGallery(), new WorkbookTemplateGallery(), new WorkbookTemplateGallery()))))) .create(); - Assertions.assertEquals("ucftbyrp", response.location()); - Assertions.assertEquals("hkpigqfusuckzmkw", response.tags().get("lsnoxaxmqeqalh")); - Assertions.assertEquals(378655951, response.priority()); - Assertions.assertEquals("hhlkyqltqsrogtu", response.author()); - Assertions.assertEquals("vclglxnfuij", response.galleries().get(0).name()); - Assertions.assertEquals("busqogsfi", response.galleries().get(0).category()); - Assertions.assertEquals("yi", response.galleries().get(0).type()); - Assertions.assertEquals(2036577427, response.galleries().get(0).order()); - Assertions.assertEquals("arujt", response.galleries().get(0).resourceType()); + Assertions.assertEquals("octfjgtixrjvzuyt", response.location()); + Assertions.assertEquals("lmuowo", response.tags().get("bauiropi")); + Assertions.assertEquals(125495169, response.priority()); + Assertions.assertEquals("xoe", response.author()); + Assertions.assertEquals("lafcbahh", response.galleries().get(0).name()); + Assertions.assertEquals("pofoi", response.galleries().get(0).category()); + Assertions.assertEquals("w", response.galleries().get(0).type()); + Assertions.assertEquals(1217605698, response.galleries().get(0).order()); + Assertions.assertEquals("kmkkholvdnd", response.galleries().get(0).resourceType()); } // Use "Map.of" if available diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookTemplatesDeleteByResourceGroupWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookTemplatesDeleteByResourceGroupWithResponseMockTests.java index 82d1e5ed16fb..e7b3631c0c8d 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookTemplatesDeleteByResourceGroupWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookTemplatesDeleteByResourceGroupWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import java.nio.charset.StandardCharsets; @@ -25,9 +25,10 @@ public void testDeleteWithResponse() throws Exception { ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); - manager.workbookTemplates().deleteByResourceGroupWithResponse("herngb", "c", com.azure.core.util.Context.NONE); + manager.workbookTemplates() + .deleteByResourceGroupWithResponse("yjpmspbpssdfppyo", "tieyujtvczkcny", com.azure.core.util.Context.NONE); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookTemplatesGetByResourceGroupWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookTemplatesGetByResourceGroupWithResponseMockTests.java index ce0c2384069f..adf17a7eb4a2 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookTemplatesGetByResourceGroupWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookTemplatesGetByResourceGroupWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.models.WorkbookTemplate; @@ -21,27 +21,27 @@ public final class WorkbookTemplatesGetByResourceGroupWithResponseMockTests { @Test public void testGetByResourceGroupWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"priority\":456926110,\"author\":\"cfotangcfhnykzcu\",\"templateData\":\"dataswvxwlmzqwmv\",\"galleries\":[{\"name\":\"jmxmcuqud\",\"category\":\"vclx\",\"type\":\"pdkvg\",\"order\":1567015685,\"resourceType\":\"iyji\"},{\"name\":\"zphdugneiknp\",\"category\":\"xgjiuqh\",\"type\":\"tozipqwj\",\"order\":775560662,\"resourceType\":\"rrxxgewpktvq\"}],\"localized\":{\"foiyjwpfilk\":[{\"templateData\":\"datapzoyhlfbcg\",\"galleries\":[{},{}]},{\"templateData\":\"dataoxoebqi\",\"galleries\":[{},{}]},{\"templateData\":\"datanwjfu\",\"galleries\":[{},{}]},{\"templateData\":\"datafcbahhp\",\"galleries\":[{},{}]}]}},\"location\":\"kkholvdndvia\",\"tags\":{\"iukyefchnmna\":\"phuartv\",\"xffi\":\"mnxhkxjqirwrweo\",\"rsnewmozqvbubqma\":\"hx\"},\"id\":\"hsycxhxzgaz\",\"name\":\"taboidvmf\",\"type\":\"hppubowsepdfgkmt\"}"; + = "{\"properties\":{\"priority\":341362078,\"author\":\"dqmjxly\",\"templateData\":\"datazg\",\"galleries\":[{\"name\":\"uwt\",\"category\":\"jjyuojqtobax\",\"type\":\"eytu\",\"order\":1073974691,\"resourceType\":\"jkwrusnkq\"},{\"name\":\"syrq\",\"category\":\"jqhden\",\"type\":\"ulkpakd\",\"order\":466096532,\"resourceType\":\"jnnawtqa\"}],\"localized\":{\"sdp\":[{\"templateData\":\"datakpggqoweyi\",\"galleries\":[{},{}]},{\"templateData\":\"dataisngwflqqmpizru\",\"galleries\":[{},{}]},{\"templateData\":\"dataxpxiwfcngjs\",\"galleries\":[{}]},{\"templateData\":\"dataixtmkzjvkviirhgf\",\"galleries\":[{},{},{}]}],\"bglbyvict\":[{\"templateData\":\"datat\",\"galleries\":[{}]}],\"bydpizqaclnapxb\":[{\"templateData\":\"datarxkjzwrgxffmshk\",\"galleries\":[{},{},{},{}]},{\"templateData\":\"datagozxw\",\"galleries\":[{}]}],\"smfcttuxuuyilfl\":[{\"templateData\":\"datanugj\",\"galleries\":[{},{},{},{}]}]}},\"location\":\"oiquvrehmrnjhvs\",\"tags\":{\"uunfprnjletlxsm\":\"tczytqjtwh\",\"nlqwzdvpiwhx\":\"pddouifamowaziyn\"},\"id\":\"szdtmaajquh\",\"name\":\"xylrjvmtygjbmz\",\"type\":\"ospspshckf\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); WorkbookTemplate response = manager.workbookTemplates() - .getByResourceGroupWithResponse("mmkjsvthnwpztek", "vmribiat", com.azure.core.util.Context.NONE) + .getByResourceGroupWithResponse("tgfebwln", "mhyreeudz", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("kkholvdndvia", response.location()); - Assertions.assertEquals("phuartv", response.tags().get("iukyefchnmna")); - Assertions.assertEquals(456926110, response.priority()); - Assertions.assertEquals("cfotangcfhnykzcu", response.author()); - Assertions.assertEquals("jmxmcuqud", response.galleries().get(0).name()); - Assertions.assertEquals("vclx", response.galleries().get(0).category()); - Assertions.assertEquals("pdkvg", response.galleries().get(0).type()); - Assertions.assertEquals(1567015685, response.galleries().get(0).order()); - Assertions.assertEquals("iyji", response.galleries().get(0).resourceType()); + Assertions.assertEquals("oiquvrehmrnjhvs", response.location()); + Assertions.assertEquals("tczytqjtwh", response.tags().get("uunfprnjletlxsm")); + Assertions.assertEquals(341362078, response.priority()); + Assertions.assertEquals("dqmjxly", response.author()); + Assertions.assertEquals("uwt", response.galleries().get(0).name()); + Assertions.assertEquals("jjyuojqtobax", response.galleries().get(0).category()); + Assertions.assertEquals("eytu", response.galleries().get(0).type()); + Assertions.assertEquals(1073974691, response.galleries().get(0).order()); + Assertions.assertEquals("jkwrusnkq", response.galleries().get(0).resourceType()); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookTemplatesListByResourceGroupMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookTemplatesListByResourceGroupMockTests.java index 0d4ba294b09d..e09ec9e43e5c 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookTemplatesListByResourceGroupMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookTemplatesListByResourceGroupMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.models.WorkbookTemplate; @@ -22,26 +22,26 @@ public final class WorkbookTemplatesListByResourceGroupMockTests { @Test public void testListByResourceGroup() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"priority\":1529964299,\"author\":\"ty\",\"templateData\":\"datajbmzyospspsh\",\"galleries\":[{\"name\":\"kyjpmspbps\",\"category\":\"fppyogtieyujtvcz\",\"type\":\"n\",\"order\":845990154,\"resourceType\":\"munjdxvglnkvx\"},{\"name\":\"paglqivbgk\",\"category\":\"khpzvuqdflv\",\"type\":\"iypfp\",\"order\":38455799,\"resourceType\":\"zgp\"}],\"localized\":{\"gpnrhgov\":[{\"templateData\":\"dataj\",\"galleries\":[{},{},{}]},{\"templateData\":\"dataibg\",\"galleries\":[{},{}]}],\"mzvupor\":[{\"templateData\":\"dataik\",\"galleries\":[{}]},{\"templateData\":\"dataao\",\"galleries\":[{},{}]}],\"tglxx\":[{\"templateData\":\"datafuyd\",\"galleries\":[{},{}]},{\"templateData\":\"datavxcnqmxqps\",\"galleries\":[{},{}]},{\"templateData\":\"datavkhlggdhbemz\",\"galleries\":[{},{},{}]},{\"templateData\":\"datazu\",\"galleries\":[{},{}]}]}},\"location\":\"ljfp\",\"tags\":{\"vpqcb\":\"crmnzhrgmqgjs\",\"s\":\"rmbodt\"},\"id\":\"qgvriibakcla\",\"name\":\"jfrnxousxauzlwv\",\"type\":\"gmwohqfzizvu\"}]}"; + = "{\"value\":[{\"properties\":{\"priority\":835008707,\"author\":\"jgicgaao\",\"templateData\":\"datapttaqutd\",\"galleries\":[{\"name\":\"mxswvruunzz\",\"category\":\"ehkfkimrtixok\",\"type\":\"qyinl\",\"order\":980930736,\"resourceType\":\"qwhix\"},{\"name\":\"nstshi\",\"category\":\"gvelfc\",\"type\":\"uccbirdsvuw\",\"order\":228727125,\"resourceType\":\"egstmninwjizci\"},{\"name\":\"ghgshejjtbxqmu\",\"category\":\"xlxqzvn\",\"type\":\"sbycucrwnamikz\",\"order\":401745323,\"resourceType\":\"bsmswziqgf\"},{\"name\":\"okzrus\",\"category\":\"vhczznvfby\",\"type\":\"sxjwwixz\",\"order\":1659306080,\"resourceType\":\"mxqhndvnoamldse\"}],\"localized\":{\"g\":[{\"templateData\":\"datajhhflzokxcoxpel\",\"galleries\":[{}]},{\"templateData\":\"dataagltsxoa\",\"galleries\":[{},{}]}],\"aykggnoxu\":[{\"templateData\":\"datapbswvefloccsrm\",\"galleries\":[{},{},{},{}]},{\"templateData\":\"datam\",\"galleries\":[{}]},{\"templateData\":\"datawtxxpkyjcx\",\"galleries\":[{},{}]},{\"templateData\":\"datarytfmpcycil\",\"galleries\":[{},{},{}]}],\"fnznth\":[{\"templateData\":\"dataksxwpnd\",\"galleries\":[{},{},{}]}]}},\"location\":\"twk\",\"tags\":{\"tcqiosmg\":\"srxuzvoam\",\"xqdlyrtltlapr\":\"zah\",\"atbhjmznn\":\"tz\"},\"id\":\"s\",\"name\":\"qeqala\",\"type\":\"vlagun\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response - = manager.workbookTemplates().listByResourceGroup("huxy", com.azure.core.util.Context.NONE); + = manager.workbookTemplates().listByResourceGroup("xs", com.azure.core.util.Context.NONE); - Assertions.assertEquals("ljfp", response.iterator().next().location()); - Assertions.assertEquals("crmnzhrgmqgjs", response.iterator().next().tags().get("vpqcb")); - Assertions.assertEquals(1529964299, response.iterator().next().priority()); - Assertions.assertEquals("ty", response.iterator().next().author()); - Assertions.assertEquals("kyjpmspbps", response.iterator().next().galleries().get(0).name()); - Assertions.assertEquals("fppyogtieyujtvcz", response.iterator().next().galleries().get(0).category()); - Assertions.assertEquals("n", response.iterator().next().galleries().get(0).type()); - Assertions.assertEquals(845990154, response.iterator().next().galleries().get(0).order()); - Assertions.assertEquals("munjdxvglnkvx", response.iterator().next().galleries().get(0).resourceType()); + Assertions.assertEquals("twk", response.iterator().next().location()); + Assertions.assertEquals("srxuzvoam", response.iterator().next().tags().get("tcqiosmg")); + Assertions.assertEquals(835008707, response.iterator().next().priority()); + Assertions.assertEquals("jgicgaao", response.iterator().next().author()); + Assertions.assertEquals("mxswvruunzz", response.iterator().next().galleries().get(0).name()); + Assertions.assertEquals("ehkfkimrtixok", response.iterator().next().galleries().get(0).category()); + Assertions.assertEquals("qyinl", response.iterator().next().galleries().get(0).type()); + Assertions.assertEquals(980930736, response.iterator().next().galleries().get(0).order()); + Assertions.assertEquals("qwhix", response.iterator().next().galleries().get(0).resourceType()); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookUpdateParametersTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookUpdateParametersTests.java index 934c1211ca69..ea70363ddd0b 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookUpdateParametersTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbookUpdateParametersTests.java @@ -16,37 +16,37 @@ public final class WorkbookUpdateParametersTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { WorkbookUpdateParameters model = BinaryData.fromString( - "{\"kind\":\"shared\",\"tags\":{\"hftwesgog\":\"izzronasxiftozqy\",\"sxkkg\":\"zhonnxkrlgnyhmo\",\"rghxjb\":\"h\"},\"properties\":{\"displayName\":\"xvcxgfrpdsofbshr\",\"serializedData\":\"vbuswd\",\"category\":\"yybyc\",\"tags\":[\"vj\",\"rtkfawnopq\",\"ikyzirtxdy\"],\"description\":\"zejntps\",\"revision\":\"gioilqu\"}}") + "{\"kind\":\"shared\",\"tags\":{\"jivfxzsjabib\":\"ij\"},\"properties\":{\"displayName\":\"tawfsdjpvkvp\",\"serializedData\":\"xbkzbzkdvncj\",\"category\":\"udurgkakmokz\",\"tags\":[\"klff\"],\"description\":\"ouw\",\"revision\":\"gzrf\"}}") .toObject(WorkbookUpdateParameters.class); Assertions.assertEquals(WorkbookUpdateSharedTypeKind.SHARED, model.kind()); - Assertions.assertEquals("izzronasxiftozqy", model.tags().get("hftwesgog")); - Assertions.assertEquals("xvcxgfrpdsofbshr", model.displayName()); - Assertions.assertEquals("vbuswd", model.serializedData()); - Assertions.assertEquals("yybyc", model.category()); - Assertions.assertEquals("vj", model.tagsPropertiesTags().get(0)); - Assertions.assertEquals("zejntps", model.description()); - Assertions.assertEquals("gioilqu", model.revision()); + Assertions.assertEquals("ij", model.tags().get("jivfxzsjabib")); + Assertions.assertEquals("tawfsdjpvkvp", model.displayName()); + Assertions.assertEquals("xbkzbzkdvncj", model.serializedData()); + Assertions.assertEquals("udurgkakmokz", model.category()); + Assertions.assertEquals("klff", model.tagsPropertiesTags().get(0)); + Assertions.assertEquals("ouw", model.description()); + Assertions.assertEquals("gzrf", model.revision()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { WorkbookUpdateParameters model = new WorkbookUpdateParameters().withKind(WorkbookUpdateSharedTypeKind.SHARED) - .withTags(mapOf("hftwesgog", "izzronasxiftozqy", "sxkkg", "zhonnxkrlgnyhmo", "rghxjb", "h")) - .withDisplayName("xvcxgfrpdsofbshr") - .withSerializedData("vbuswd") - .withCategory("yybyc") - .withTagsPropertiesTags(Arrays.asList("vj", "rtkfawnopq", "ikyzirtxdy")) - .withDescription("zejntps") - .withRevision("gioilqu"); + .withTags(mapOf("jivfxzsjabib", "ij")) + .withDisplayName("tawfsdjpvkvp") + .withSerializedData("xbkzbzkdvncj") + .withCategory("udurgkakmokz") + .withTagsPropertiesTags(Arrays.asList("klff")) + .withDescription("ouw") + .withRevision("gzrf"); model = BinaryData.fromObject(model).toObject(WorkbookUpdateParameters.class); Assertions.assertEquals(WorkbookUpdateSharedTypeKind.SHARED, model.kind()); - Assertions.assertEquals("izzronasxiftozqy", model.tags().get("hftwesgog")); - Assertions.assertEquals("xvcxgfrpdsofbshr", model.displayName()); - Assertions.assertEquals("vbuswd", model.serializedData()); - Assertions.assertEquals("yybyc", model.category()); - Assertions.assertEquals("vj", model.tagsPropertiesTags().get(0)); - Assertions.assertEquals("zejntps", model.description()); - Assertions.assertEquals("gioilqu", model.revision()); + Assertions.assertEquals("ij", model.tags().get("jivfxzsjabib")); + Assertions.assertEquals("tawfsdjpvkvp", model.displayName()); + Assertions.assertEquals("xbkzbzkdvncj", model.serializedData()); + Assertions.assertEquals("udurgkakmokz", model.category()); + Assertions.assertEquals("klff", model.tagsPropertiesTags().get(0)); + Assertions.assertEquals("ouw", model.description()); + Assertions.assertEquals("gzrf", model.revision()); } // Use "Map.of" if available diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksCreateOrUpdateWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksCreateOrUpdateWithResponseMockTests.java index 6bfd92080440..4e4a854c2e2b 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksCreateOrUpdateWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksCreateOrUpdateWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.models.ManagedServiceIdentityType; @@ -28,49 +28,48 @@ public final class WorkbooksCreateOrUpdateWithResponseMockTests { @Test public void testCreateOrUpdateWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"displayName\":\"hhulrtywikdm\",\"serializedData\":\"lakuflgbhgauacd\",\"version\":\"mxu\",\"timeModified\":\"2021-09-01T23:44:15Z\",\"category\":\"ryjqgdkf\",\"tags\":[\"oeoq\"],\"userId\":\"jhvefgwbmqjchnt\",\"sourceId\":\"faymxbulpz\",\"storageUri\":\"lbm\",\"description\":\"yojwyvfkmbtsu\",\"revision\":\"xsgxjcmmzrrs\"},\"identity\":{\"principalId\":\"630f0243-a6d6-4063-a8da-439cda7c1f57\",\"tenantId\":\"d3d3e4bf-1970-49e2-845d-56fad0d83651\",\"type\":\"None\",\"userAssignedIdentities\":{\"xqw\":{\"principalId\":\"e92d249a-f907-4d46-b0c7-386de1e27720\",\"clientId\":\"3682fbdd-1adc-4545-a6e8-b06a1a1fce97\"},\"ffjxcjrmmuabwib\":{\"principalId\":\"2fd8057d-9d5b-45f4-8b58-a9f3467b81e6\",\"clientId\":\"a7bef691-4c8b-428d-8bf5-c9f38e7a357f\"},\"gjonmcy\":{\"principalId\":\"fcde5d9d-2abf-4665-8fe1-68fd99255288\",\"clientId\":\"9c7820d1-ed9d-496b-9568-90f08cb4c39a\"},\"y\":{\"principalId\":\"a4782e1c-25d6-42e7-8751-562433ff4fc4\",\"clientId\":\"c297b5b1-91b4-4858-944b-111b50e935e7\"}}},\"kind\":\"shared\",\"etag\":\"wine\",\"location\":\"fvfkak\",\"tags\":{\"evboclzhzjknyuxg\":\"dt\",\"mrdixtreki\":\"ttxpnrupza\"},\"id\":\"swyskbruffg\",\"name\":\"lukkutvlxhrpqhvm\",\"type\":\"lcouqehbhbcdszir\"}"; + = "{\"properties\":{\"displayName\":\"updwv\",\"serializedData\":\"phcnzqtpj\",\"version\":\"qrhvthlaiwdcxsml\",\"timeModified\":\"2021-01-22T01:05:07Z\",\"category\":\"zdtxetlgyd\",\"tags\":[\"vlnnpx\",\"b\",\"fiqgeaar\",\"gjekglklby\"],\"userId\":\"idwcwvmzegjon\",\"sourceId\":\"jirwgdnqzbrfk\",\"storageUri\":\"zhzmtksjci\",\"description\":\"igsxcdgljplk\",\"revision\":\"acht\"},\"identity\":{\"principalId\":\"5420b6a0-b1a4-40a3-9a0f-660be42f4720\",\"tenantId\":\"6e5361f3-18d5-4cdc-9733-d17f968264f5\",\"type\":\"SystemAssigned\",\"userAssignedIdentities\":{\"pfmdgycx\":{\"principalId\":\"51ceafc5-a288-46d2-94b8-28361e8ed140\",\"clientId\":\"26493be9-d5d4-4e21-81ff-a68a469a8c67\"},\"kwhqj\":{\"principalId\":\"ce046ff9-e6ff-4fe2-a76a-f1d3a7fc5dc3\",\"clientId\":\"48330939-ec9a-4611-acdf-1dba6c953ee5\"}}},\"kind\":\"shared\",\"etag\":\"urlpshh\",\"location\":\"vpedwqslsrh\",\"tags\":{\"imuvqejosovyrrl\":\"vwwskondcbr\",\"sinuqtljqobbpih\":\"a\"},\"id\":\"hcecybmrqbr\",\"name\":\"bbmpxdlvykfre\",\"type\":\"crse\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); Workbook response = manager.workbooks() - .define("wdogiyetesyp") - .withRegion("jp") - .withExistingResourceGroup("vhnqo") - .withTags(mapOf("haep", "s")) + .define("gfggcvkyylizrzbj") + .withRegion("chl") + .withExistingResourceGroup("uhplrvkmjcwmjv") + .withTags(mapOf("hmoz", "txd", "ns", "sgzv", "fpafolpymwamxq", "nj")) .withIdentity(new WorkbookResourceIdentity().withType(ManagedServiceIdentityType.SYSTEM_ASSIGNED) - .withUserAssignedIdentities( - mapOf("ehuwaoa", new UserAssignedIdentity(), "icq", new UserAssignedIdentity()))) + .withUserAssignedIdentities(mapOf("rokcdxfzzzwyjaf", new UserAssignedIdentity()))) .withKind(WorkbookSharedTypeKind.SHARED) - .withEtag("stacsjvhrweftkwq") - .withDisplayName("dbztjhqtfbov") - .withSerializedData("ynkbwetnju") - .withVersion("sprkzyaupiac") - .withCategory("afbwqroohtuovmao") - .withTagsPropertiesTags(Arrays.asList("jtumgh", "hpv", "cmslclblyjxltbs")) - .withSourceId("uupb") - .withStorageUri("qccydrtceukdq") - .withDescription("yihztgeqmg") - .withSourceIdParameter("c") + .withEtag("guyn") + .withDisplayName("fxsfuztlvtmv") + .withSerializedData("gbwidqlvh") + .withVersion("oveofizrvjfnmj") + .withCategory("wyzgiblkuj") + .withTagsPropertiesTags(Arrays.asList("fojuidjpuuyj", "c", "jikzoeovvtzej")) + .withSourceId("k") + .withStorageUri("qzolxrzvhqjw") + .withDescription("htgv") + .withSourceIdParameter("jchcsrlzknmzla") .create(); - Assertions.assertEquals("fvfkak", response.location()); - Assertions.assertEquals("dt", response.tags().get("evboclzhzjknyuxg")); - Assertions.assertEquals(ManagedServiceIdentityType.NONE, response.identity().type()); + Assertions.assertEquals("vpedwqslsrh", response.location()); + Assertions.assertEquals("vwwskondcbr", response.tags().get("imuvqejosovyrrl")); + Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_ASSIGNED, response.identity().type()); Assertions.assertEquals(WorkbookSharedTypeKind.SHARED, response.kind()); - Assertions.assertEquals("wine", response.etag()); - Assertions.assertEquals("hhulrtywikdm", response.displayName()); - Assertions.assertEquals("lakuflgbhgauacd", response.serializedData()); - Assertions.assertEquals("mxu", response.version()); - Assertions.assertEquals("ryjqgdkf", response.category()); - Assertions.assertEquals("oeoq", response.tagsPropertiesTags().get(0)); - Assertions.assertEquals("faymxbulpz", response.sourceId()); - Assertions.assertEquals("lbm", response.storageUri()); - Assertions.assertEquals("yojwyvfkmbtsu", response.description()); + Assertions.assertEquals("urlpshh", response.etag()); + Assertions.assertEquals("updwv", response.displayName()); + Assertions.assertEquals("phcnzqtpj", response.serializedData()); + Assertions.assertEquals("qrhvthlaiwdcxsml", response.version()); + Assertions.assertEquals("zdtxetlgyd", response.category()); + Assertions.assertEquals("vlnnpx", response.tagsPropertiesTags().get(0)); + Assertions.assertEquals("jirwgdnqzbrfk", response.sourceId()); + Assertions.assertEquals("zhzmtksjci", response.storageUri()); + Assertions.assertEquals("igsxcdgljplk", response.description()); } // Use "Map.of" if available diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksDeleteByResourceGroupWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksDeleteByResourceGroupWithResponseMockTests.java index c0122f7134e9..b6573a062611 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksDeleteByResourceGroupWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksDeleteByResourceGroupWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import java.nio.charset.StandardCharsets; @@ -25,10 +25,9 @@ public void testDeleteWithResponse() throws Exception { ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); - manager.workbooks() - .deleteByResourceGroupWithResponse("hdbvqvwzkjop", "beonrlkwzdq", com.azure.core.util.Context.NONE); + manager.workbooks().deleteByResourceGroupWithResponse("yuicdhzbdy", "wwgbdv", com.azure.core.util.Context.NONE); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksGetByResourceGroupWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksGetByResourceGroupWithResponseMockTests.java index dd073d2f7a56..6b5b14258eb8 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksGetByResourceGroupWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksGetByResourceGroupWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.models.ManagedServiceIdentityType; @@ -23,31 +23,31 @@ public final class WorkbooksGetByResourceGroupWithResponseMockTests { @Test public void testGetByResourceGroupWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"displayName\":\"luzvxnq\",\"serializedData\":\"hrpq\",\"version\":\"fwmkoisqcssffxui\",\"timeModified\":\"2021-01-13T07:46:02Z\",\"category\":\"ypobkdqzr\",\"tags\":[\"ylollgtrczzydmxz\",\"ijpvuaurkihc\",\"rldefxrdcox\"],\"userId\":\"kkjanurnnqbnqbp\",\"sourceId\":\"xqltgrd\",\"storageUri\":\"ypxrx\",\"description\":\"fihwu\",\"revision\":\"ctafsrbxrblm\"},\"identity\":{\"principalId\":\"e1a5eb0d-e78a-4fd4-8774-b3fe585ce490\",\"tenantId\":\"67718c9b-1653-4426-ada5-ede361e54be6\",\"type\":\"SystemAssigned,UserAssigned\",\"userAssignedIdentities\":{\"xwqagnepzw\":{\"principalId\":\"c73a2dd2-36c6-4275-a845-2cd1f445ee5c\",\"clientId\":\"de1271e9-9548-48bc-be4f-bc085c7b2e0c\"},\"sbs\":{\"principalId\":\"44a175d1-12db-4a01-b5c6-552ed9579799\",\"clientId\":\"9e547658-4ea1-4d55-9f37-d90ca4da1626\"},\"qagwwrxaomz\":{\"principalId\":\"5c2dddc0-8508-4cad-9181-d25aca7d146a\",\"clientId\":\"7c02e422-28e6-46e6-9866-785c98e894c2\"},\"lrrcz\":{\"principalId\":\"606bc49a-7f99-4b2b-bbcc-b90c07fceb45\",\"clientId\":\"64f0cb12-280d-4b81-90ec-27cbd38d141c\"}}},\"kind\":\"shared\",\"etag\":\"hltnjadhqoawjq\",\"location\":\"yueayfbpcmsp\",\"tags\":{\"mbscbbx\":\"rrueqthwmg\",\"d\":\"gdhxi\"},\"id\":\"opedbwdpyqyybxub\",\"name\":\"dnafcbqwre\",\"type\":\"jelaqacigele\"}"; + = "{\"properties\":{\"displayName\":\"ywjxh\",\"serializedData\":\"dulontacn\",\"version\":\"w\",\"timeModified\":\"2021-05-26T23:48:10Z\",\"category\":\"tuevrh\",\"tags\":[\"yoogw\",\"hnsduugwbsreur\"],\"userId\":\"kfuarenlv\",\"sourceId\":\"tklnvnafvvkyfed\",\"storageUri\":\"jboslcqxypok\",\"description\":\"minqcym\",\"revision\":\"ngnbdxxew\"},\"identity\":{\"principalId\":\"ad4e7204-64e6-4648-9c14-082d8dc0277b\",\"tenantId\":\"c19391a2-d7ae-4427-bcb5-07cba6004bd6\",\"type\":\"UserAssigned\",\"userAssignedIdentities\":{\"aqdtvqecrqctmxxd\":{\"principalId\":\"2936ca4b-f7f4-4c4e-9302-66d85e964e6f\",\"clientId\":\"95e830b7-ebf0-49e9-8883-01c93b9abf91\"},\"mflhuytxzvtznapx\":{\"principalId\":\"e846e066-e560-4fbf-863f-29842c63abd0\",\"clientId\":\"8a7aec75-128c-41b1-9b31-d2e611958345\"}}},\"kind\":\"shared\",\"etag\":\"o\",\"location\":\"voxczytpr\",\"tags\":{\"rrrouuxvnsa\":\"vroevytlyo\",\"lobdxna\":\"bcrymodizrx\",\"op\":\"pmkmlmvevfx\",\"hrdd\":\"hbzxli\"},\"id\":\"tfgxqbawpcb\",\"name\":\"nzqcy\",\"type\":\"napqo\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); Workbook response = manager.workbooks() - .getByResourceGroupWithResponse("lhkgmnsghp", "ycphdrwjjkhvyo", false, com.azure.core.util.Context.NONE) + .getByResourceGroupWithResponse("ro", "xddbhfhpfpaz", false, com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("yueayfbpcmsp", response.location()); - Assertions.assertEquals("rrueqthwmg", response.tags().get("mbscbbx")); - Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, response.identity().type()); + Assertions.assertEquals("voxczytpr", response.location()); + Assertions.assertEquals("vroevytlyo", response.tags().get("rrrouuxvnsa")); + Assertions.assertEquals(ManagedServiceIdentityType.USER_ASSIGNED, response.identity().type()); Assertions.assertEquals(WorkbookSharedTypeKind.SHARED, response.kind()); - Assertions.assertEquals("hltnjadhqoawjq", response.etag()); - Assertions.assertEquals("luzvxnq", response.displayName()); - Assertions.assertEquals("hrpq", response.serializedData()); - Assertions.assertEquals("fwmkoisqcssffxui", response.version()); - Assertions.assertEquals("ypobkdqzr", response.category()); - Assertions.assertEquals("ylollgtrczzydmxz", response.tagsPropertiesTags().get(0)); - Assertions.assertEquals("xqltgrd", response.sourceId()); - Assertions.assertEquals("ypxrx", response.storageUri()); - Assertions.assertEquals("fihwu", response.description()); + Assertions.assertEquals("o", response.etag()); + Assertions.assertEquals("ywjxh", response.displayName()); + Assertions.assertEquals("dulontacn", response.serializedData()); + Assertions.assertEquals("w", response.version()); + Assertions.assertEquals("tuevrh", response.category()); + Assertions.assertEquals("yoogw", response.tagsPropertiesTags().get(0)); + Assertions.assertEquals("tklnvnafvvkyfed", response.sourceId()); + Assertions.assertEquals("jboslcqxypok", response.storageUri()); + Assertions.assertEquals("minqcym", response.description()); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksListByResourceGroupMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksListByResourceGroupMockTests.java index db4f87568210..b53123c0edaf 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksListByResourceGroupMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksListByResourceGroupMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.models.CategoryType; @@ -26,32 +26,32 @@ public final class WorkbooksListByResourceGroupMockTests { @Test public void testListByResourceGroup() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"displayName\":\"rbqgvgov\",\"serializedData\":\"bbttefjo\",\"version\":\"ssqyzqedik\",\"timeModified\":\"2021-01-29T08:56:47Z\",\"category\":\"db\",\"tags\":[\"rjgeih\",\"qlggwfi\",\"zcxmjpbyep\",\"mgtvlj\"],\"userId\":\"cmyfqipgxhnpo\",\"sourceId\":\"qwcabvnui\",\"storageUri\":\"ey\",\"description\":\"wlpaugmrmfjlrxwt\",\"revision\":\"ukhfkvc\"},\"identity\":{\"principalId\":\"b75f9a38-52d8-4d2e-8536-ae2d170af33e\",\"tenantId\":\"da67e59d-0fa9-4591-bbd1-ac752fdbabbd\",\"type\":\"SystemAssigned,UserAssigned\",\"userAssignedIdentities\":{\"xjw\":{\"principalId\":\"f831091f-a47e-482f-859e-c345ace1f6f7\",\"clientId\":\"91552447-a684-4d6c-a8b7-cf5c14dc0a45\"}}},\"kind\":\"shared\",\"etag\":\"dwc\",\"location\":\"yeew\",\"tags\":{\"mguaml\":\"qbpsmg\",\"lzgaufcshhvnew\":\"dlrgms\"},\"id\":\"nxkympqanxrjk\",\"name\":\"xtwbta\",\"type\":\"ypnyghshxc\"}]}"; + = "{\"value\":[{\"properties\":{\"displayName\":\"jtkbusqogsfika\",\"serializedData\":\"ians\",\"version\":\"rujtjiqxfzyjq\",\"timeModified\":\"2021-03-02T08:22:49Z\",\"category\":\"wkpqhjpenuygbq\",\"tags\":[\"ekewvnqvcdlguauc\",\"f\",\"jwnlax\"],\"userId\":\"njqikcz\",\"sourceId\":\"itacgxmfcsserx\",\"storageUri\":\"vs\",\"description\":\"hlwntsjgq\",\"revision\":\"xypruuuy\"},\"identity\":{\"principalId\":\"749a0e50-8342-4e86-ba67-e486b5fba43c\",\"tenantId\":\"f7b81241-a42a-44e8-bb8c-44ae5d1edeb0\",\"type\":\"SystemAssigned,UserAssigned\",\"userAssignedIdentities\":{\"yuel\":{\"principalId\":\"1e51a447-d8b0-426f-bd6c-a1a9bfca6656\",\"clientId\":\"8f7ce043-05bd-4879-9da4-2f567d2fdbc0\"},\"ndnbfqy\":{\"principalId\":\"347685c1-cfef-4a51-8350-5adf69a923d8\",\"clientId\":\"85750f12-72b2-4671-a27c-48dfca061678\"},\"g\":{\"principalId\":\"18c0426d-dad8-4661-8822-d998f2f1095d\",\"clientId\":\"2a908a3e-c553-4d0d-a247-f047ffb57fa9\"},\"lgmtrwahzjmucf\":{\"principalId\":\"7d6abbeb-9edf-4fb8-a9ba-22cba46317ef\",\"clientId\":\"3604a5aa-ed52-4af8-b4d3-67f715947eb6\"}}},\"kind\":\"shared\",\"etag\":\"plrohkpigq\",\"location\":\"usuckzmkwklsno\",\"tags\":{\"lhhjnh\":\"mqeq\",\"yynfsvkhgbv\":\"wy\"},\"id\":\"ta\",\"name\":\"arfdlpukhpyrnei\",\"type\":\"jcpeogkhnmg\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.workbooks() - .listByResourceGroup("ufypiv", CategoryType.TSG, Arrays.asList("bbjpmcubkmif"), "xxkubvphavp", false, + .listByResourceGroup("djk", CategoryType.RETENTION, Arrays.asList("ysidfvclgl"), "n", false, com.azure.core.util.Context.NONE); - Assertions.assertEquals("yeew", response.iterator().next().location()); - Assertions.assertEquals("qbpsmg", response.iterator().next().tags().get("mguaml")); + Assertions.assertEquals("usuckzmkwklsno", response.iterator().next().location()); + Assertions.assertEquals("mqeq", response.iterator().next().tags().get("lhhjnh")); Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, response.iterator().next().identity().type()); Assertions.assertEquals(WorkbookSharedTypeKind.SHARED, response.iterator().next().kind()); - Assertions.assertEquals("dwc", response.iterator().next().etag()); - Assertions.assertEquals("rbqgvgov", response.iterator().next().displayName()); - Assertions.assertEquals("bbttefjo", response.iterator().next().serializedData()); - Assertions.assertEquals("ssqyzqedik", response.iterator().next().version()); - Assertions.assertEquals("db", response.iterator().next().category()); - Assertions.assertEquals("rjgeih", response.iterator().next().tagsPropertiesTags().get(0)); - Assertions.assertEquals("qwcabvnui", response.iterator().next().sourceId()); - Assertions.assertEquals("ey", response.iterator().next().storageUri()); - Assertions.assertEquals("wlpaugmrmfjlrxwt", response.iterator().next().description()); + Assertions.assertEquals("plrohkpigq", response.iterator().next().etag()); + Assertions.assertEquals("jtkbusqogsfika", response.iterator().next().displayName()); + Assertions.assertEquals("ians", response.iterator().next().serializedData()); + Assertions.assertEquals("rujtjiqxfzyjq", response.iterator().next().version()); + Assertions.assertEquals("wkpqhjpenuygbq", response.iterator().next().category()); + Assertions.assertEquals("ekewvnqvcdlguauc", response.iterator().next().tagsPropertiesTags().get(0)); + Assertions.assertEquals("itacgxmfcsserx", response.iterator().next().sourceId()); + Assertions.assertEquals("vs", response.iterator().next().storageUri()); + Assertions.assertEquals("hlwntsjgq", response.iterator().next().description()); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksListMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksListMockTests.java index 7c13fb42b546..dce21279d9a6 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksListMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.models.CategoryType; @@ -26,31 +26,30 @@ public final class WorkbooksListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"displayName\":\"vteo\",\"serializedData\":\"xvgpiude\",\"version\":\"fsxzecp\",\"timeModified\":\"2021-08-01T08:13:49Z\",\"category\":\"kufykhvu\",\"tags\":[\"pmru\",\"znabaobns\"],\"userId\":\"jdjltymkmvgui\",\"sourceId\":\"wartspphkixkykxd\",\"storageUri\":\"j\",\"description\":\"mmuc\",\"revision\":\"hikkflrmy\"},\"identity\":{\"principalId\":\"3b96fff9-8aad-45c1-9a73-a3396d157d6d\",\"tenantId\":\"8bfb2f14-561f-4ef9-bc5c-412c0c3ee993\",\"type\":\"SystemAssigned\",\"userAssignedIdentities\":{\"s\":{\"principalId\":\"30d0dd1d-8155-4089-82da-4e6fc1e7c745\",\"clientId\":\"784ea102-100d-4048-99a8-d17cf1b74108\"}}},\"kind\":\"shared\",\"etag\":\"iiiovgqcgxuugq\",\"location\":\"ctotiowlx\",\"tags\":{\"wphqlkccuzgygqw\":\"dptjgwdtgukranb\"},\"id\":\"hoi\",\"name\":\"lwgniiprglvawu\",\"type\":\"z\"}]}"; + = "{\"value\":[{\"properties\":{\"displayName\":\"jxtxrdc\",\"serializedData\":\"tjvidt\",\"version\":\"epu\",\"timeModified\":\"2021-12-03T10:50:59Z\",\"category\":\"yjtcvuwk\",\"tags\":[\"zies\",\"uughtuqfecjxeyg\",\"uhxu\",\"cbuewmrswnjlxuz\"],\"userId\":\"wpusxjbaqehg\",\"sourceId\":\"ohzjqatucoigeb\",\"storageUri\":\"cnwfepbnwgfmxjg\",\"description\":\"bjb\",\"revision\":\"lfgtdysnaquflqbc\"},\"identity\":{\"principalId\":\"d353c0f3-f613-4cf0-9acb-e7de16316fa9\",\"tenantId\":\"f21f4a78-a22a-4134-b0f7-ee97aaee1923\",\"type\":\"UserAssigned\",\"userAssignedIdentities\":{\"kqzeqyjleziunjx\":{\"principalId\":\"099c8d1a-fcc8-4386-a945-9df5bc57e423\",\"clientId\":\"44c0eda2-0352-4d6d-9b12-c670eed3d8ee\"}}},\"kind\":\"shared\",\"etag\":\"ntkwcegy\",\"location\":\"mlbnseq\",\"tags\":{\"m\":\"jvpilguooqja\",\"hrtdtpdelq\":\"itgueiookjbs\",\"vcjkgd\":\"cslmotoebnfxo\",\"vcopex\":\"razftxejwabmdujt\"},\"id\":\"m\",\"name\":\"urbuhhlkyqltq\",\"type\":\"rogtuwkf\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.workbooks() - .list(CategoryType.RETENTION, Arrays.asList("wb"), false, com.azure.core.util.Context.NONE); + .list(CategoryType.PERFORMANCE, Arrays.asList("enlusfn"), true, com.azure.core.util.Context.NONE); - Assertions.assertEquals("ctotiowlx", response.iterator().next().location()); - Assertions.assertEquals("dptjgwdtgukranb", response.iterator().next().tags().get("wphqlkccuzgygqw")); - Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_ASSIGNED, - response.iterator().next().identity().type()); + Assertions.assertEquals("mlbnseq", response.iterator().next().location()); + Assertions.assertEquals("jvpilguooqja", response.iterator().next().tags().get("m")); + Assertions.assertEquals(ManagedServiceIdentityType.USER_ASSIGNED, response.iterator().next().identity().type()); Assertions.assertEquals(WorkbookSharedTypeKind.SHARED, response.iterator().next().kind()); - Assertions.assertEquals("iiiovgqcgxuugq", response.iterator().next().etag()); - Assertions.assertEquals("vteo", response.iterator().next().displayName()); - Assertions.assertEquals("xvgpiude", response.iterator().next().serializedData()); - Assertions.assertEquals("fsxzecp", response.iterator().next().version()); - Assertions.assertEquals("kufykhvu", response.iterator().next().category()); - Assertions.assertEquals("pmru", response.iterator().next().tagsPropertiesTags().get(0)); - Assertions.assertEquals("wartspphkixkykxd", response.iterator().next().sourceId()); - Assertions.assertEquals("j", response.iterator().next().storageUri()); - Assertions.assertEquals("mmuc", response.iterator().next().description()); + Assertions.assertEquals("ntkwcegy", response.iterator().next().etag()); + Assertions.assertEquals("jxtxrdc", response.iterator().next().displayName()); + Assertions.assertEquals("tjvidt", response.iterator().next().serializedData()); + Assertions.assertEquals("epu", response.iterator().next().version()); + Assertions.assertEquals("yjtcvuwk", response.iterator().next().category()); + Assertions.assertEquals("zies", response.iterator().next().tagsPropertiesTags().get(0)); + Assertions.assertEquals("ohzjqatucoigeb", response.iterator().next().sourceId()); + Assertions.assertEquals("cnwfepbnwgfmxjg", response.iterator().next().storageUri()); + Assertions.assertEquals("bjb", response.iterator().next().description()); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksListResultTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksListResultTests.java index 3c4837cdecc1..e127b4c1a1b9 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksListResultTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksListResultTests.java @@ -12,15 +12,15 @@ public final class WorkbooksListResultTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { WorkbooksListResult model = BinaryData.fromString( - "{\"value\":[{\"properties\":{\"displayName\":\"bs\",\"serializedData\":\"bbqwrvtldg\",\"version\":\"pgvmpipaslthaqfx\",\"timeModified\":\"2021-05-16T20:33:06Z\",\"category\":\"wutwbdsre\",\"tags\":[\"rhneuyowq\",\"d\",\"ytisibir\"],\"userId\":\"pikpz\",\"sourceId\":\"ejzanlfz\",\"storageUri\":\"av\",\"description\":\"bzonok\",\"revision\":\"rjqc\"},\"identity\":{\"principalId\":\"a6d94d75-676b-4a99-b899-cacce4364154\",\"tenantId\":\"32720fa2-71c4-4016-8b5c-9b73344a4c01\",\"type\":\"None\",\"userAssignedIdentities\":{\"szrnwo\":{\"principalId\":\"7fd8bfac-af5f-4121-80a0-787c19de2d6e\",\"clientId\":\"7abbd956-12c6-481d-81a4-3eaf7cc4ea59\"},\"dfpwpjylwbtlhfls\":{\"principalId\":\"c06df4e8-5705-4752-a8fe-8442f7aa56f6\",\"clientId\":\"49bfa0fb-b1bf-435d-b37a-51dbbf69ec78\"}}},\"kind\":\"shared\",\"etag\":\"szfjvfbgofelja\",\"location\":\"rqmq\",\"tags\":{\"nalghfkvtvsexso\":\"vriiio\",\"wpjgwws\":\"ueluqhhahhxvrhmz\",\"qxujxukndxd\":\"ughftqsx\"},\"id\":\"grjguufzd\",\"name\":\"syqtfi\",\"type\":\"whbotzingamv\"},{\"properties\":{\"displayName\":\"ho\",\"serializedData\":\"zqzudph\",\"version\":\"mvdk\",\"timeModified\":\"2021-09-19T23:00:24Z\",\"category\":\"nwcvtbvkayhmtnv\",\"tags\":[\"atkzwpcnpw\",\"cjaesgvvs\",\"cyajguqf\"],\"userId\":\"ygz\",\"sourceId\":\"dnkfx\",\"storageUri\":\"emdwzrmuhapfc\",\"description\":\"psqxq\",\"revision\":\"svuo\"},\"identity\":{\"principalId\":\"d8085a25-8e29-41c0-93a5-fb08b5aec828\",\"tenantId\":\"58872ed7-463e-4d24-b2b5-a9744921e61f\",\"type\":\"UserAssigned\",\"userAssignedIdentities\":{\"rypqlmfeo\":{\"principalId\":\"e2155e14-4176-4679-8af3-22caf40e0923\",\"clientId\":\"be342783-5987-4e75-8884-d1e6ebdd383a\"},\"qwkyhkobop\":{\"principalId\":\"84b51ba7-fb51-433a-8703-022be4eade05\",\"clientId\":\"37cfb861-39da-4da5-8109-3e903b22178f\"},\"dkow\":{\"principalId\":\"03895bd1-1eba-4ca3-a878-84921c34df68\",\"clientId\":\"cf5c6748-b846-4f6a-ad23-db87b79a7e68\"}}},\"kind\":\"shared\",\"etag\":\"pc\",\"location\":\"fkbw\",\"tags\":{\"dw\":\"njv\",\"nkhtjsyingw\":\"lpqekf\",\"gikdgsz\":\"qatmtdhtmdvy\",\"birryuzhl\":\"w\"},\"id\":\"kj\",\"name\":\"qrvqq\",\"type\":\"atjinrvgoupmfiib\"}],\"nextLink\":\"gjio\"}") + "{\"value\":[{\"properties\":{\"displayName\":\"xg\",\"serializedData\":\"qagvrvm\",\"version\":\"k\",\"timeModified\":\"2021-11-21T22:35:24Z\",\"category\":\"himdbl\",\"tags\":[\"imfnjhfjx\"],\"userId\":\"szkkfoqre\",\"sourceId\":\"kzikfjawneaivxwc\",\"storageUri\":\"lpcirelsf\",\"description\":\"enwabfatk\",\"revision\":\"dxbjhwuaanozj\"},\"identity\":{\"principalId\":\"e24eadb2-f0de-41db-8521-8875c41e87f5\",\"tenantId\":\"cc76053a-5f5a-4453-a846-99c932b9a6d3\",\"type\":\"SystemAssigned\",\"userAssignedIdentities\":{\"rvxaglrvimjwosy\":{\"principalId\":\"4fd27780-eeb0-4705-b659-81f015da191c\",\"clientId\":\"80536d96-559c-4b79-a1dd-adb0c12c0dc1\"}}},\"kind\":\"shared\",\"etag\":\"cskfcktqumiekk\",\"location\":\"zzikhlyfjhdg\",\"tags\":{\"eqidbqfatpx\":\"ebdunyg\",\"cyjmoadsuvarmy\":\"lr\",\"hhyxxrw\":\"dmjsjqb\"},\"id\":\"yc\",\"name\":\"duhpk\",\"type\":\"kgymareqnajxqug\"},{\"properties\":{\"displayName\":\"ky\",\"serializedData\":\"ubeddg\",\"version\":\"ofwq\",\"timeModified\":\"2021-05-03T03:51:25Z\",\"category\":\"alkrmn\",\"tags\":[\"pxacqqudfn\",\"yxbaaabjyvayf\"],\"userId\":\"m\",\"sourceId\":\"rtuzqogs\",\"storageUri\":\"nevfdnw\",\"description\":\"mewzsyyc\",\"revision\":\"zsoibjudpfrxtr\"},\"identity\":{\"principalId\":\"46c14d90-34b7-4c6f-93cc-6cef27d46cf7\",\"tenantId\":\"f5032c27-ba01-41ba-84df-a03f2d049ac1\",\"type\":\"None\",\"userAssignedIdentities\":{\"qbrqubpaxhexiili\":{\"principalId\":\"c1399ab0-0c9a-45c8-8486-7ceb0a8f0f9d\",\"clientId\":\"9f3438ab-c2f6-4aa9-9711-06190befa9f1\"},\"tiirqtdqoa\":{\"principalId\":\"07677274-1671-4159-941b-559ca28ce77b\",\"clientId\":\"8bcfc51e-6013-43cb-8e49-b37928a4d20a\"}}},\"kind\":\"shared\",\"etag\":\"zfgs\",\"location\":\"uyfxrxxleptramxj\",\"tags\":{\"tdooaoj\":\"lwnwxuqlcvydyp\",\"nuj\":\"niodkooeb\",\"odtji\":\"emmsbvdkc\"},\"id\":\"fw\",\"name\":\"lfltka\",\"type\":\"jvefkdlfoakggkfp\"},{\"properties\":{\"displayName\":\"ao\",\"serializedData\":\"pulpqblylsyxk\",\"version\":\"nsj\",\"timeModified\":\"2021-01-29T11:24:17Z\",\"category\":\"tiagx\",\"tags\":[\"zuempsbzkf\"],\"userId\":\"eyvpnqicvinvkj\",\"sourceId\":\"dxrbuukzcle\",\"storageUri\":\"hmlwpaztzpo\",\"description\":\"cckwyfzqwhxxbu\",\"revision\":\"a\"},\"identity\":{\"principalId\":\"9d09d0d3-7921-4f9e-9a25-bb89aa70dc60\",\"tenantId\":\"85a196f1-3b6c-4104-97fe-e37cc8fe442d\",\"type\":\"SystemAssigned,UserAssigned\",\"userAssignedIdentities\":{\"iolxor\":{\"principalId\":\"36644ca3-1b33-4359-b298-1ff59eb0261d\",\"clientId\":\"94cdaa27-19f6-4ac9-81be-8bf3cb62e755\"},\"tolmncwsobqw\":{\"principalId\":\"763700aa-7cc1-4374-9057-53d6f059c3d8\",\"clientId\":\"7c268c96-4a58-4d7f-8a2d-d08fbb3fac9f\"}}},\"kind\":\"shared\",\"etag\":\"nwdcfhu\",\"location\":\"qdpfuvglsbjjca\",\"tags\":{\"xqtvcofu\":\"bvtvudutncormr\",\"vkg\":\"f\"},\"id\":\"u\",\"name\":\"gdknnqv\",\"type\":\"aznqntoru\"}],\"nextLink\":\"gsahmkycgrauw\"}") .toObject(WorkbooksListResult.class); - Assertions.assertEquals("gjio", model.nextLink()); + Assertions.assertEquals("gsahmkycgrauw", model.nextLink()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - WorkbooksListResult model = new WorkbooksListResult().withNextLink("gjio"); + WorkbooksListResult model = new WorkbooksListResult().withNextLink("gsahmkycgrauw"); model = BinaryData.fromObject(model).toObject(WorkbooksListResult.class); - Assertions.assertEquals("gjio", model.nextLink()); + Assertions.assertEquals("gsahmkycgrauw", model.nextLink()); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksRevisionGetWithResponseMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksRevisionGetWithResponseMockTests.java index 66b20b53e21e..324f1ac78205 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksRevisionGetWithResponseMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksRevisionGetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.models.ManagedServiceIdentityType; @@ -23,31 +23,31 @@ public final class WorkbooksRevisionGetWithResponseMockTests { @Test public void testRevisionGetWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"displayName\":\"exwhcb\",\"serializedData\":\"pibkephuu\",\"version\":\"rctat\",\"timeModified\":\"2021-04-07T20:43:54Z\",\"category\":\"ntqpbr\",\"tags\":[\"rduczkgofxyfs\",\"uc\",\"crrpcjttbstvje\",\"qnrmvvfko\"],\"userId\":\"lghktuidvrm\",\"sourceId\":\"lpdwwexymzvlazi\",\"storageUri\":\"hpwvqsgnyyuu\",\"description\":\"vensrpm\",\"revision\":\"yvpkpatlbijpzgsk\"},\"identity\":{\"principalId\":\"4d373b1d-8bc8-4481-9731-e3262f33d701\",\"tenantId\":\"865f3774-a021-4c34-bd09-e2a4b4cee2f2\",\"type\":\"None\",\"userAssignedIdentities\":{\"nbnxwcdomm\":{\"principalId\":\"6ba1a65e-5077-4270-afe5-39518ec8a185\",\"clientId\":\"0d8c9701-c4b4-4b7c-8f93-c9d89a8cb783\"},\"qa\":{\"principalId\":\"0466c49f-e2a3-42e9-a76c-41df47a5c87a\",\"clientId\":\"1e162506-214b-44db-9ff0-61071cc46839\"},\"gbrt\":{\"principalId\":\"bf00012f-4500-47e8-9d85-50b69850a0fc\",\"clientId\":\"0e0b5701-76c2-4397-98e9-2aa2344ae94f\"}}},\"kind\":\"shared\",\"etag\":\"clkiexhajl\",\"location\":\"n\",\"tags\":{\"ygbpvnwswmt\":\"qfyuttd\",\"ctwwgzw\":\"k\",\"og\":\"jlmec\"},\"id\":\"gzyvnee\",\"name\":\"aifghtmoqqt\",\"type\":\"ffhzbkrkjjjavfq\"}"; + = "{\"properties\":{\"displayName\":\"w\",\"serializedData\":\"sydsxwefohe\",\"version\":\"vopwndyqleallk\",\"timeModified\":\"2021-10-09T13:48:10Z\",\"category\":\"khlowkxxpv\",\"tags\":[\"fjmzsyzfho\",\"lhikcyychunsj\",\"pjrtws\",\"hv\"],\"userId\":\"icphvtrrmhw\",\"sourceId\":\"fdpyflubh\",\"storageUri\":\"glrocuy\",\"description\":\"whhmemhooc\",\"revision\":\"tnpqmemczjk\"},\"identity\":{\"principalId\":\"fd649e2c-ed47-4f19-ad77-bec2f4570ae7\",\"tenantId\":\"9b620f9a-3527-40b2-a7c0-c65f965d3ae2\",\"type\":\"UserAssigned\",\"userAssignedIdentities\":{\"lhsrrry\":{\"principalId\":\"ca812142-37d6-470f-bb15-630954b9a9c2\",\"clientId\":\"4bdc2101-776e-4e98-8177-ffc6c242dde6\"},\"lmbkzu\":{\"principalId\":\"d7a3d2c7-9951-41a6-99c6-46c01d4a8fe7\",\"clientId\":\"5f0c6387-9659-432e-bdb0-ffa816c850ea\"}}},\"kind\":\"shared\",\"etag\":\"rfih\",\"location\":\"tjewlpxuzzj\",\"tags\":{\"iwfbrkwpzdqtvhcs\":\"efqyhqotoihiqaky\",\"ietgbebjfu\":\"odaqaxsi\"},\"id\":\"bmoichd\",\"name\":\"pnfpubntnbat\",\"type\":\"viqsowsaaelcattc\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); Workbook response = manager.workbooks() - .revisionGetWithResponse("eksgbuxantuygd", "gaqi", "irpiwrqofulopmj", com.azure.core.util.Context.NONE) + .revisionGetWithResponse("d", "saoafcluqvox", "ycjimryvwgcwwpbm", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("n", response.location()); - Assertions.assertEquals("qfyuttd", response.tags().get("ygbpvnwswmt")); - Assertions.assertEquals(ManagedServiceIdentityType.NONE, response.identity().type()); + Assertions.assertEquals("tjewlpxuzzj", response.location()); + Assertions.assertEquals("efqyhqotoihiqaky", response.tags().get("iwfbrkwpzdqtvhcs")); + Assertions.assertEquals(ManagedServiceIdentityType.USER_ASSIGNED, response.identity().type()); Assertions.assertEquals(WorkbookSharedTypeKind.SHARED, response.kind()); - Assertions.assertEquals("clkiexhajl", response.etag()); - Assertions.assertEquals("exwhcb", response.displayName()); - Assertions.assertEquals("pibkephuu", response.serializedData()); - Assertions.assertEquals("rctat", response.version()); - Assertions.assertEquals("ntqpbr", response.category()); - Assertions.assertEquals("rduczkgofxyfs", response.tagsPropertiesTags().get(0)); - Assertions.assertEquals("lpdwwexymzvlazi", response.sourceId()); - Assertions.assertEquals("hpwvqsgnyyuu", response.storageUri()); - Assertions.assertEquals("vensrpm", response.description()); + Assertions.assertEquals("rfih", response.etag()); + Assertions.assertEquals("w", response.displayName()); + Assertions.assertEquals("sydsxwefohe", response.serializedData()); + Assertions.assertEquals("vopwndyqleallk", response.version()); + Assertions.assertEquals("khlowkxxpv", response.category()); + Assertions.assertEquals("fjmzsyzfho", response.tagsPropertiesTags().get(0)); + Assertions.assertEquals("fdpyflubh", response.sourceId()); + Assertions.assertEquals("glrocuy", response.storageUri()); + Assertions.assertEquals("whhmemhooc", response.description()); } } diff --git a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksRevisionsListMockTests.java b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksRevisionsListMockTests.java index 7f041b0e9f5f..f9f727bddd51 100644 --- a/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksRevisionsListMockTests.java +++ b/sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/test/java/com/azure/resourcemanager/applicationinsights/generated/WorkbooksRevisionsListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager; import com.azure.resourcemanager.applicationinsights.models.ManagedServiceIdentityType; @@ -24,31 +24,30 @@ public final class WorkbooksRevisionsListMockTests { @Test public void testRevisionsList() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"displayName\":\"rttzrazisgykiu\",\"serializedData\":\"mvanbwzo\",\"version\":\"nrxxbsojklin\",\"timeModified\":\"2021-08-26T06:41:34Z\",\"category\":\"ptysprq\",\"tags\":[\"zxojpslsv\",\"g\",\"liufiqwoyxq\",\"apcohhouc\"],\"userId\":\"q\",\"sourceId\":\"xcxzrzdcgdzben\",\"storageUri\":\"bcawetz\",\"description\":\"dtjwfljhznamt\",\"revision\":\"tmzwcjjn\"},\"identity\":{\"principalId\":\"ca4ba807-768e-4c90-8920-0b1300e5e8c2\",\"tenantId\":\"120bda1c-b888-46c4-91f8-2254cb3bb414\",\"type\":\"SystemAssigned,UserAssigned\",\"userAssignedIdentities\":{\"bgatzu\":{\"principalId\":\"80acaa0b-08db-47bc-ab48-32b83298c0bc\",\"clientId\":\"e38bd376-09e5-4184-966a-4bd9d3240c5f\"},\"xngre\":{\"principalId\":\"5a6c8f44-1ed8-4246-be9f-33b8d30e4c80\",\"clientId\":\"73bbb562-5758-4a3e-926d-a68110cf1e89\"}}},\"kind\":\"shared\",\"etag\":\"ahttzlswvajqfut\",\"location\":\"x\",\"tags\":{\"aohcmbuocn\":\"zasunwqrjzfrgq\",\"hmbpyryxamebly\":\"r\",\"kmrocxne\":\"yvk\",\"mtodl\":\"v\"},\"id\":\"pyapucygvoav\",\"name\":\"unssxlghieegjl\",\"type\":\"vvpa\"}]}"; + = "{\"value\":[{\"properties\":{\"displayName\":\"ck\",\"serializedData\":\"crrvweyo\",\"version\":\"yyukphaimmo\",\"timeModified\":\"2021-05-07T05:38:47Z\",\"category\":\"qboshbra\",\"tags\":[\"yyrmfsvbp\",\"vbopfppdbwnu\"],\"userId\":\"ahxku\",\"sourceId\":\"sjcaacfdmmcpugm\",\"storageUri\":\"qepvufhbzeh\",\"description\":\"hoqhnl\",\"revision\":\"nbldxeaclgschori\"},\"identity\":{\"principalId\":\"8196fa64-6240-44a6-934f-6dcd6d0d3549\",\"tenantId\":\"2bc9acb0-1e0f-422b-a93d-8ff5465f2646\",\"type\":\"UserAssigned\",\"userAssignedIdentities\":{\"s\":{\"principalId\":\"45706b23-e6aa-4d17-8464-206c8cf29cec\",\"clientId\":\"7a12fff2-b95f-4214-b0f7-05f20d4efa44\"}}},\"kind\":\"shared\",\"etag\":\"puviyfcaabe\",\"location\":\"lhbhl\",\"tags\":{\"sfar\":\"xuqibsxtkcudf\"},\"id\":\"siowlkjxnqpv\",\"name\":\"gf\",\"type\":\"tmhqykiz\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); ApplicationInsightsManager manager = ApplicationInsightsManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response - = manager.workbooks().revisionsList("bxcea", "xcptsoqfyiaseqc", com.azure.core.util.Context.NONE); + = manager.workbooks().revisionsList("bid", "hmwffplfmuv", com.azure.core.util.Context.NONE); - Assertions.assertEquals("x", response.iterator().next().location()); - Assertions.assertEquals("zasunwqrjzfrgq", response.iterator().next().tags().get("aohcmbuocn")); - Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, - response.iterator().next().identity().type()); + Assertions.assertEquals("lhbhl", response.iterator().next().location()); + Assertions.assertEquals("xuqibsxtkcudf", response.iterator().next().tags().get("sfar")); + Assertions.assertEquals(ManagedServiceIdentityType.USER_ASSIGNED, response.iterator().next().identity().type()); Assertions.assertEquals(WorkbookSharedTypeKind.SHARED, response.iterator().next().kind()); - Assertions.assertEquals("ahttzlswvajqfut", response.iterator().next().etag()); - Assertions.assertEquals("rttzrazisgykiu", response.iterator().next().displayName()); - Assertions.assertEquals("mvanbwzo", response.iterator().next().serializedData()); - Assertions.assertEquals("nrxxbsojklin", response.iterator().next().version()); - Assertions.assertEquals("ptysprq", response.iterator().next().category()); - Assertions.assertEquals("zxojpslsv", response.iterator().next().tagsPropertiesTags().get(0)); - Assertions.assertEquals("xcxzrzdcgdzben", response.iterator().next().sourceId()); - Assertions.assertEquals("bcawetz", response.iterator().next().storageUri()); - Assertions.assertEquals("dtjwfljhznamt", response.iterator().next().description()); + Assertions.assertEquals("puviyfcaabe", response.iterator().next().etag()); + Assertions.assertEquals("ck", response.iterator().next().displayName()); + Assertions.assertEquals("crrvweyo", response.iterator().next().serializedData()); + Assertions.assertEquals("yyukphaimmo", response.iterator().next().version()); + Assertions.assertEquals("qboshbra", response.iterator().next().category()); + Assertions.assertEquals("yyrmfsvbp", response.iterator().next().tagsPropertiesTags().get(0)); + Assertions.assertEquals("sjcaacfdmmcpugm", response.iterator().next().sourceId()); + Assertions.assertEquals("qepvufhbzeh", response.iterator().next().storageUri()); + Assertions.assertEquals("hoqhnl", response.iterator().next().description()); } } diff --git a/sdk/astro/azure-resourcemanager-astro/README.md b/sdk/astro/azure-resourcemanager-astro/README.md index e409c261521a..f726b9df6cb3 100644 --- a/sdk/astro/azure-resourcemanager-astro/README.md +++ b/sdk/astro/azure-resourcemanager-astro/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-astro - 1.0.0-beta.2 + 1.0.0-beta.3 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fastro%2Fazure-resourcemanager-astro%2FREADME.png) + diff --git a/sdk/astro/azure-resourcemanager-astro/pom.xml b/sdk/astro/azure-resourcemanager-astro/pom.xml index 20a0f920099c..6059e31e6506 100644 --- a/sdk/astro/azure-resourcemanager-astro/pom.xml +++ b/sdk/astro/azure-resourcemanager-astro/pom.xml @@ -52,23 +52,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/attestation/azure-resourcemanager-attestation/README.md b/sdk/attestation/azure-resourcemanager-attestation/README.md index 74b4f148647e..0b746171d5bf 100644 --- a/sdk/attestation/azure-resourcemanager-attestation/README.md +++ b/sdk/attestation/azure-resourcemanager-attestation/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-attestation - 1.0.0-beta.3 + 1.0.0-beta.4 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fattestation%2Fazure-resourcemanager-attestation%2FREADME.png) + diff --git a/sdk/attestation/azure-resourcemanager-attestation/pom.xml b/sdk/attestation/azure-resourcemanager-attestation/pom.xml index 1fc415a53597..fedf8dde7088 100644 --- a/sdk/attestation/azure-resourcemanager-attestation/pom.xml +++ b/sdk/attestation/azure-resourcemanager-attestation/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/attestation/azure-security-attestation/CHANGELOG.md b/sdk/attestation/azure-security-attestation/CHANGELOG.md index 2d8373d47608..0f219ee08c6d 100644 --- a/sdk/attestation/azure-security-attestation/CHANGELOG.md +++ b/sdk/attestation/azure-security-attestation/CHANGELOG.md @@ -9,10 +9,15 @@ - Added `TpmAttestationResult.java` to make the attestTpm return type more consistency. - Changed `attestTpm` parameter from String to Binary Data -### Bugs Fixed +## 1.1.31 (2025-02-25) ### Other Changes +#### Dependency Updates + +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. + + ## 1.1.30 (2024-12-04) ### Other Changes diff --git a/sdk/attestation/azure-security-attestation/README.md b/sdk/attestation/azure-security-attestation/README.md index a54a203b1c4e..484f9d7da0c5 100644 --- a/sdk/attestation/azure-security-attestation/README.md +++ b/sdk/attestation/azure-security-attestation/README.md @@ -52,7 +52,7 @@ add the direct dependency to your project as follows. com.azure azure-security-attestation - 1.1.15 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -331,4 +331,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][microsoft_c [http_clients_wiki]: https://learn.microsoft.com/azure/developer/java/sdk/http-client-pipeline#http-clients [microsoft_code_of_conduct]: https://opensource.microsoft.com/codeofconduct/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fattestation%2Fazure-security-attestation%2FREADME.png) + diff --git a/sdk/attestation/azure-security-attestation/pom.xml b/sdk/attestation/azure-security-attestation/pom.xml index 0fa16b0787de..8fa1a084e68e 100644 --- a/sdk/attestation/azure-security-attestation/pom.xml +++ b/sdk/attestation/azure-security-attestation/pom.xml @@ -48,12 +48,12 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.nimbusds @@ -73,37 +73,37 @@ com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.52 + 1.0.0-beta.56 test io.opentelemetry opentelemetry-api - 1.43.0 + 1.46.0 test io.opentelemetry opentelemetry-exporter-logging - 1.43.0 + 1.46.0 test io.opentelemetry opentelemetry-sdk - 1.43.0 + 1.46.0 test com.azure azure-identity - 1.15.0 + 1.15.4 test @@ -125,9 +125,9 @@ com.nimbusds:nimbus-jose-jwt:[9.37.3] - io.opentelemetry:opentelemetry-api:[1.43.0] - io.opentelemetry:opentelemetry-sdk:[1.43.0] - io.opentelemetry:opentelemetry-exporter-logging:[1.43.0] + io.opentelemetry:opentelemetry-api:[1.46.0] + io.opentelemetry:opentelemetry-sdk:[1.46.0] + io.opentelemetry:opentelemetry-exporter-logging:[1.46.0] diff --git a/sdk/automanage/azure-resourcemanager-automanage/README.md b/sdk/automanage/azure-resourcemanager-automanage/README.md index 504a8c0f84d9..2aa779be3774 100644 --- a/sdk/automanage/azure-resourcemanager-automanage/README.md +++ b/sdk/automanage/azure-resourcemanager-automanage/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-automanage - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fautomanage%2Fazure-resourcemanager-automanage%2FREADME.png) + diff --git a/sdk/automanage/azure-resourcemanager-automanage/pom.xml b/sdk/automanage/azure-resourcemanager-automanage/pom.xml index 37e35c0e443f..209fe7abfd0f 100644 --- a/sdk/automanage/azure-resourcemanager-automanage/pom.xml +++ b/sdk/automanage/azure-resourcemanager-automanage/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/automation/azure-resourcemanager-automation/README.md b/sdk/automation/azure-resourcemanager-automation/README.md index 2f12c5af7280..546260a0abbb 100644 --- a/sdk/automation/azure-resourcemanager-automation/README.md +++ b/sdk/automation/azure-resourcemanager-automation/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-automation - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fautomation%2Fazure-resourcemanager-automation%2FREADME.png) + diff --git a/sdk/automation/azure-resourcemanager-automation/pom.xml b/sdk/automation/azure-resourcemanager-automation/pom.xml index b5226af764ae..7ba65a3e814e 100644 --- a/sdk/automation/azure-resourcemanager-automation/pom.xml +++ b/sdk/automation/azure-resourcemanager-automation/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/avs/azure-resourcemanager-avs/README.md b/sdk/avs/azure-resourcemanager-avs/README.md index e68d9cf268fc..416361b2a4c2 100644 --- a/sdk/avs/azure-resourcemanager-avs/README.md +++ b/sdk/avs/azure-resourcemanager-avs/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-avs - 1.2.0 + 1.3.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -112,4 +112,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Favs%2Fazure-resourcemanager-avs%2FREADME.png) + diff --git a/sdk/avs/azure-resourcemanager-avs/pom.xml b/sdk/avs/azure-resourcemanager-avs/pom.xml index 3f355f1db16d..64125d137665 100644 --- a/sdk/avs/azure-resourcemanager-avs/pom.xml +++ b/sdk/avs/azure-resourcemanager-avs/pom.xml @@ -51,34 +51,34 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/azureadexternalidentities/azure-resourcemanager-azureadexternalidentities/pom.xml b/sdk/azureadexternalidentities/azure-resourcemanager-azureadexternalidentities/pom.xml index 2dec9813f3d1..ac2fff90829e 100644 --- a/sdk/azureadexternalidentities/azure-resourcemanager-azureadexternalidentities/pom.xml +++ b/sdk/azureadexternalidentities/azure-resourcemanager-azureadexternalidentities/pom.xml @@ -45,12 +45,12 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 diff --git a/sdk/azurearcdata/azure-resourcemanager-azurearcdata/README.md b/sdk/azurearcdata/azure-resourcemanager-azurearcdata/README.md index 03119f18e86a..6e7fb13ca5e6 100644 --- a/sdk/azurearcdata/azure-resourcemanager-azurearcdata/README.md +++ b/sdk/azurearcdata/azure-resourcemanager-azurearcdata/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-azurearcdata - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fazurearcdata%2Fazure-resourcemanager-azurearcdata%2FREADME.png) + diff --git a/sdk/azurearcdata/azure-resourcemanager-azurearcdata/pom.xml b/sdk/azurearcdata/azure-resourcemanager-azurearcdata/pom.xml index d99b0eb446ec..8a74f635317e 100644 --- a/sdk/azurearcdata/azure-resourcemanager-azurearcdata/pom.xml +++ b/sdk/azurearcdata/azure-resourcemanager-azurearcdata/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/azurestack/azure-resourcemanager-azurestack/README.md b/sdk/azurestack/azure-resourcemanager-azurestack/README.md index 395a7d2bf885..6587a1e720b7 100644 --- a/sdk/azurestack/azure-resourcemanager-azurestack/README.md +++ b/sdk/azurestack/azure-resourcemanager-azurestack/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-azurestack - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fazurestack%2Fazure-resourcemanager-azurestack%2FREADME.png) + diff --git a/sdk/azurestack/azure-resourcemanager-azurestack/pom.xml b/sdk/azurestack/azure-resourcemanager-azurestack/pom.xml index 9f17cc448d16..14ffb6fb941d 100644 --- a/sdk/azurestack/azure-resourcemanager-azurestack/pom.xml +++ b/sdk/azurestack/azure-resourcemanager-azurestack/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/azurestackhci/azure-resourcemanager-azurestackhci/README.md b/sdk/azurestackhci/azure-resourcemanager-azurestackhci/README.md index 1084ff088247..7db00378283c 100644 --- a/sdk/azurestackhci/azure-resourcemanager-azurestackhci/README.md +++ b/sdk/azurestackhci/azure-resourcemanager-azurestackhci/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-azurestackhci - 1.0.0-beta.5 + 1.0.0-beta.6 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fazurestackhci%2Fazure-resourcemanager-azurestackhci%2FREADME.png) + diff --git a/sdk/azurestackhci/azure-resourcemanager-azurestackhci/pom.xml b/sdk/azurestackhci/azure-resourcemanager-azurestackhci/pom.xml index 488cce53b45b..83788be0cd08 100644 --- a/sdk/azurestackhci/azure-resourcemanager-azurestackhci/pom.xml +++ b/sdk/azurestackhci/azure-resourcemanager-azurestackhci/pom.xml @@ -51,28 +51,28 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/baremetalinfrastructure/azure-resourcemanager-baremetalinfrastructure/README.md b/sdk/baremetalinfrastructure/azure-resourcemanager-baremetalinfrastructure/README.md index 8d57415ceba6..5757ee390b9d 100644 --- a/sdk/baremetalinfrastructure/azure-resourcemanager-baremetalinfrastructure/README.md +++ b/sdk/baremetalinfrastructure/azure-resourcemanager-baremetalinfrastructure/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-baremetalinfrastructure - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fbaremetalinfrastructure%2Fazure-resourcemanager-baremetalinfrastructure%2FREADME.png) + diff --git a/sdk/baremetalinfrastructure/azure-resourcemanager-baremetalinfrastructure/pom.xml b/sdk/baremetalinfrastructure/azure-resourcemanager-baremetalinfrastructure/pom.xml index b8a38910db38..017551b164f7 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.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/batch/azure-compute-batch/README.md b/sdk/batch/azure-compute-batch/README.md index a133e740d3d6..390ad9d9e0bf 100644 --- a/sdk/batch/azure-compute-batch/README.md +++ b/sdk/batch/azure-compute-batch/README.md @@ -26,7 +26,7 @@ Various documentation is available to help you get started com.azure azure-compute-batch - 1.0.0-beta.3 + 1.0.0-beta.4 ``` diff --git a/sdk/batch/azure-compute-batch/pom.xml b/sdk/batch/azure-compute-batch/pom.xml index 943166e70236..58fe73550c78 100644 --- a/sdk/batch/azure-compute-batch/pom.xml +++ b/sdk/batch/azure-compute-batch/pom.xml @@ -59,41 +59,41 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager - 2.46.0 + 2.48.0 test com.azure azure-storage-blob - 12.29.0 + 12.29.1 test diff --git a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/BatchAsyncClient.java b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/BatchAsyncClient.java index b103107415a8..76110430d096 100644 --- a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/BatchAsyncClient.java +++ b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/BatchAsyncClient.java @@ -3500,7 +3500,7 @@ public Mono> getApplicationWithResponse(String applicationI * last aggregation interval currently available. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-account-usage-metrics. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-account-usage-metrics. * * You can add these to a request with {@link RequestOptions#addQueryParam} *

        Response Body Schema

        @@ -4202,7 +4202,7 @@ public Mono> createPoolWithResponse(BinaryData pool, RequestOptio * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-pools. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-pools. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -7616,7 +7616,7 @@ public Mono> removeNodesWithResponse(String poolId, BinaryData pa * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. * * You can add these to a request with {@link RequestOptions#addQueryParam} *

        Response Body Schema

        @@ -7748,7 +7748,7 @@ PagedFlux listSupportedImages(RequestOptions requestOptions) { * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. * * You can add these to a request with {@link RequestOptions#addQueryParam} *

        Response Body Schema

        @@ -11733,7 +11733,7 @@ public Mono> createJobWithResponse(BinaryData job, RequestOptions * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -12657,7 +12657,7 @@ PagedFlux listJobs(RequestOptions requestOptions) { * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs-in-a-job-schedule. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs-in-a-job-schedule. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -13591,7 +13591,7 @@ PagedFlux listJobsFromSchedule(String jobScheduleId, RequestOptions * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-preparation-and-release-status. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-preparation-and-release-status. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * @@ -18219,7 +18219,7 @@ public Mono> createJobScheduleWithResponse(BinaryData jobSchedule * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-schedules. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-schedules. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -19491,7 +19491,7 @@ public Mono> createTaskWithResponse(String jobId, BinaryData task * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-tasks. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-tasks. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -22236,7 +22236,7 @@ public Mono> getTaskFilePropertiesWithResponse(String jobId, Stri * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-task-files. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-task-files. * recursiveBooleanNoWhether to list children of the Task directory. This * parameter can be used in * combination with the filter parameter to list specific type of files. @@ -22253,7 +22253,7 @@ public Mono> getTaskFilePropertiesWithResponse(String jobId, Stri * properties (Optional): { * creationTime: OffsetDateTime (Optional) * lastModified: OffsetDateTime (Required) - * contentLength: String (Required) + * contentLength: long (Required) * contentType: String (Optional) * fileMode: String (Optional) * } @@ -23351,7 +23351,7 @@ public Mono> uploadNodeLogsWithResponse(String poolId, Stri * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-nodes-in-a-pool. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-nodes-in-a-pool. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * @@ -24419,7 +24419,7 @@ public Mono> getNodeFilePropertiesWithResponse(String poolId, Str * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-compute-node-files. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-compute-node-files. * recursiveBooleanNoWhether to list children of a directory. * * You can add these to a request with {@link RequestOptions#addQueryParam} @@ -24434,7 +24434,7 @@ public Mono> getNodeFilePropertiesWithResponse(String poolId, Str * properties (Optional): { * creationTime: OffsetDateTime (Optional) * lastModified: OffsetDateTime (Required) - * contentLength: String (Required) + * contentLength: long (Required) * contentType: String (Optional) * fileMode: String (Optional) * } @@ -28011,7 +28011,7 @@ PagedFlux listApplicationsInternal(Integer timeOutInSeconds) { * before the current time. If not specified this defaults to the end time of the * last aggregation interval currently available. * @param filter An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-account-usage-metrics. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-account-usage-metrics. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -28060,7 +28060,7 @@ PagedFlux listPoolUsageMetricsInternal(Integer timeOutInS * @param timeOutInSeconds The maximum time that the server can spend processing the request, in seconds. The * default is 30 seconds. If the value is larger than 30, the default will be used instead.". * @param filter An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-pools. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-pools. * @param select An OData $select clause. * @param expand An OData $expand clause. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -28118,7 +28118,7 @@ PagedFlux listPoolsInternal(Integer timeOutInSeconds, String filter, * @param timeOutInSeconds The maximum time that the server can spend processing the request, in seconds. The * default is 30 seconds. If the value is larger than 30, the default will be used instead.". * @param filter An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -28162,7 +28162,7 @@ PagedFlux listSupportedImagesInternal(Integer timeOutInSeco * @param timeOutInSeconds The maximum time that the server can spend processing the request, in seconds. The * default is 30 seconds. If the value is larger than 30, the default will be used instead.". * @param filter An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -28204,7 +28204,7 @@ PagedFlux listPoolNodeCountsInternal(Integer timeOutInSecon * @param timeOutInSeconds The maximum time that the server can spend processing the request, in seconds. The * default is 30 seconds. If the value is larger than 30, the default will be used instead.". * @param filter An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs. * @param select An OData $select clause. * @param expand An OData $expand clause. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -28263,7 +28263,7 @@ PagedFlux listJobsInternal(Integer timeOutInSeconds, String filter, Li * @param timeOutInSeconds The maximum time that the server can spend processing the request, in seconds. The * default is 30 seconds. If the value is larger than 30, the default will be used instead.". * @param filter An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs-in-a-job-schedule. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs-in-a-job-schedule. * @param select An OData $select clause. * @param expand An OData $expand clause. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -28330,7 +28330,7 @@ PagedFlux listJobsFromScheduleInternal(String jobScheduleId, Integer t * @param timeOutInSeconds The maximum time that the server can spend processing the request, in seconds. The * default is 30 seconds. If the value is larger than 30, the default will be used instead.". * @param filter An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-preparation-and-release-status. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-preparation-and-release-status. * @param select An OData $select clause. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. @@ -28382,7 +28382,7 @@ PagedFlux listJobPreparationAndReleaseT * @param timeOutInSeconds The maximum time that the server can spend processing the request, in seconds. The * default is 30 seconds. If the value is larger than 30, the default will be used instead.". * @param filter An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-schedules. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-schedules. * @param select An OData $select clause. * @param expand An OData $expand clause. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -28445,7 +28445,7 @@ PagedFlux listJobSchedulesInternal(Integer timeOutInSeconds, S * @param timeOutInSeconds The maximum time that the server can spend processing the request, in seconds. The * default is 30 seconds. If the value is larger than 30, the default will be used instead.". * @param filter An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-tasks. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-tasks. * @param select An OData $select clause. * @param expand An OData $expand clause. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -28505,7 +28505,7 @@ PagedFlux listTasksInternal(String jobId, Integer timeOutInSeconds, S * @param timeOutInSeconds The maximum time that the server can spend processing the request, in seconds. The * default is 30 seconds. If the value is larger than 30, the default will be used instead.". * @param filter An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-task-files. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-task-files. * @param recursive Whether to list children of the Task directory. This parameter can be used in * combination with the filter parameter to list specific type of files. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -28554,7 +28554,7 @@ PagedFlux listTaskFilesInternal(String jobId, String taskId, Inte * @param timeOutInSeconds The maximum time that the server can spend processing the request, in seconds. The * default is 30 seconds. If the value is larger than 30, the default will be used instead.". * @param filter An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-nodes-in-a-pool. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-nodes-in-a-pool. * @param select An OData $select clause. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. @@ -28654,7 +28654,7 @@ PagedFlux listNodeExtensionsInternal(String poolId, String * @param timeOutInSeconds The maximum time that the server can spend processing the request, in seconds. The * default is 30 seconds. If the value is larger than 30, the default will be used instead.". * @param filter An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-compute-node-files. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-compute-node-files. * @param recursive Whether to list children of a directory. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. diff --git a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/BatchClient.java b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/BatchClient.java index 389abeacfd3a..0d2a2a1e2c74 100644 --- a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/BatchClient.java +++ b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/BatchClient.java @@ -3346,7 +3346,7 @@ public Response getApplicationWithResponse(String applicationId, Req * last aggregation interval currently available. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-account-usage-metrics. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-account-usage-metrics. * * You can add these to a request with {@link RequestOptions#addQueryParam} *

        Response Body Schema

        @@ -4050,7 +4050,7 @@ public Response createPoolWithResponse(BinaryData pool, RequestOptions req * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-pools. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-pools. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -7456,7 +7456,7 @@ public Response removeNodesWithResponse(String poolId, BinaryData paramete * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. * * You can add these to a request with {@link RequestOptions#addQueryParam} *

        Response Body Schema

        @@ -7590,7 +7590,7 @@ PagedIterable listSupportedImages(RequestOptions requestOptions) { * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. * * You can add these to a request with {@link RequestOptions#addQueryParam} *

        Response Body Schema

        @@ -11575,7 +11575,7 @@ public Response createJobWithResponse(BinaryData job, RequestOptions reque * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -12499,7 +12499,7 @@ PagedIterable listJobs(RequestOptions requestOptions) { * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs-in-a-job-schedule. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs-in-a-job-schedule. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -13433,7 +13433,7 @@ PagedIterable listJobsFromSchedule(String jobScheduleId, RequestOpti * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-preparation-and-release-status. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-preparation-and-release-status. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * @@ -18056,7 +18056,7 @@ public Response createJobScheduleWithResponse(BinaryData jobSchedule, Requ * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-schedules. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-schedules. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -19328,7 +19328,7 @@ public Response createTaskWithResponse(String jobId, BinaryData task, Requ * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-tasks. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-tasks. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -22067,7 +22067,7 @@ public Response getTaskFilePropertiesWithResponse(String jobId, String tas * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-task-files. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-task-files. * recursiveBooleanNoWhether to list children of the Task directory. This * parameter can be used in * combination with the filter parameter to list specific type of files. @@ -22084,7 +22084,7 @@ public Response getTaskFilePropertiesWithResponse(String jobId, String tas * properties (Optional): { * creationTime: OffsetDateTime (Optional) * lastModified: OffsetDateTime (Required) - * contentLength: String (Required) + * contentLength: long (Required) * contentType: String (Optional) * fileMode: String (Optional) * } @@ -23175,7 +23175,7 @@ public Response uploadNodeLogsWithResponse(String poolId, String nod * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-nodes-in-a-pool. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-nodes-in-a-pool. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * @@ -24239,7 +24239,7 @@ public Response getNodeFilePropertiesWithResponse(String poolId, String no * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-compute-node-files. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-compute-node-files. * recursiveBooleanNoWhether to list children of a directory. * * You can add these to a request with {@link RequestOptions#addQueryParam} @@ -24254,7 +24254,7 @@ public Response getNodeFilePropertiesWithResponse(String poolId, String no * properties (Optional): { * creationTime: OffsetDateTime (Optional) * lastModified: OffsetDateTime (Required) - * contentLength: String (Required) + * contentLength: long (Required) * contentType: String (Optional) * fileMode: String (Optional) * } @@ -27583,7 +27583,7 @@ PagedIterable listApplicationsInternal(Integer timeOutInSecond * before the current time. If not specified this defaults to the end time of the * last aggregation interval currently available. * @param filter An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-account-usage-metrics. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-account-usage-metrics. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -27621,7 +27621,7 @@ PagedIterable listPoolUsageMetricsInternal(Integer timeOu * @param timeOutInSeconds The maximum time that the server can spend processing the request, in seconds. The * default is 30 seconds. If the value is larger than 30, the default will be used instead.". * @param filter An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-pools. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-pools. * @param select An OData $select clause. * @param expand An OData $expand clause. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -27668,7 +27668,7 @@ PagedIterable listPoolsInternal(Integer timeOutInSeconds, String filt * @param timeOutInSeconds The maximum time that the server can spend processing the request, in seconds. The * default is 30 seconds. If the value is larger than 30, the default will be used instead.". * @param filter An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -27701,7 +27701,7 @@ PagedIterable listSupportedImagesInternal(Integer timeOutIn * @param timeOutInSeconds The maximum time that the server can spend processing the request, in seconds. The * default is 30 seconds. If the value is larger than 30, the default will be used instead.". * @param filter An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -27732,7 +27732,7 @@ PagedIterable listPoolNodeCountsInternal(Integer timeOutInS * @param timeOutInSeconds The maximum time that the server can spend processing the request, in seconds. The * default is 30 seconds. If the value is larger than 30, the default will be used instead.". * @param filter An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs. * @param select An OData $select clause. * @param expand An OData $expand clause. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -27780,7 +27780,7 @@ PagedIterable listJobsInternal(Integer timeOutInSeconds, String filter * @param timeOutInSeconds The maximum time that the server can spend processing the request, in seconds. The * default is 30 seconds. If the value is larger than 30, the default will be used instead.". * @param filter An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs-in-a-job-schedule. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs-in-a-job-schedule. * @param select An OData $select clause. * @param expand An OData $expand clause. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -27836,7 +27836,7 @@ PagedIterable listJobsFromScheduleInternal(String jobScheduleId, Integ * @param timeOutInSeconds The maximum time that the server can spend processing the request, in seconds. The * default is 30 seconds. If the value is larger than 30, the default will be used instead.". * @param filter An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-preparation-and-release-status. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-preparation-and-release-status. * @param select An OData $select clause. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. @@ -27876,7 +27876,7 @@ PagedIterable listJobPreparationAndRele * @param timeOutInSeconds The maximum time that the server can spend processing the request, in seconds. The * default is 30 seconds. If the value is larger than 30, the default will be used instead.". * @param filter An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-schedules. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-schedules. * @param select An OData $select clause. * @param expand An OData $expand clause. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -27928,7 +27928,7 @@ PagedIterable listJobSchedulesInternal(Integer timeOutInSecond * @param timeOutInSeconds The maximum time that the server can spend processing the request, in seconds. The * default is 30 seconds. If the value is larger than 30, the default will be used instead.". * @param filter An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-tasks. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-tasks. * @param select An OData $select clause. * @param expand An OData $expand clause. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -27977,7 +27977,7 @@ PagedIterable listTasksInternal(String jobId, Integer timeOutInSecond * @param timeOutInSeconds The maximum time that the server can spend processing the request, in seconds. The * default is 30 seconds. If the value is larger than 30, the default will be used instead.". * @param filter An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-task-files. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-task-files. * @param recursive Whether to list children of the Task directory. This parameter can be used in * combination with the filter parameter to list specific type of files. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -28015,7 +28015,7 @@ PagedIterable listTaskFilesInternal(String jobId, String taskId, * @param timeOutInSeconds The maximum time that the server can spend processing the request, in seconds. The * default is 30 seconds. If the value is larger than 30, the default will be used instead.". * @param filter An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-nodes-in-a-pool. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-nodes-in-a-pool. * @param select An OData $select clause. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. @@ -28093,7 +28093,7 @@ PagedIterable listNodeExtensionsInternal(String poolId, St * @param timeOutInSeconds The maximum time that the server can spend processing the request, in seconds. The * default is 30 seconds. If the value is larger than 30, the default will be used instead.". * @param filter An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-compute-node-files. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-compute-node-files. * @param recursive Whether to list children of a directory. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. diff --git a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/implementation/BatchClientImpl.java b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/implementation/BatchClientImpl.java index 98254cb687e5..cef43df9ee2c 100644 --- a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/implementation/BatchClientImpl.java +++ b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/implementation/BatchClientImpl.java @@ -2400,7 +2400,7 @@ public Response getApplicationInternalWithResponse(String applicatio * last aggregation interval currently available. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-account-usage-metrics. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-account-usage-metrics. * * You can add these to a request with {@link RequestOptions#addQueryParam} *

        Response Body Schema

        @@ -2465,7 +2465,7 @@ private Mono> listPoolUsageMetricsInternalSinglePageAs * last aggregation interval currently available. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-account-usage-metrics. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-account-usage-metrics. * * You can add these to a request with {@link RequestOptions#addQueryParam} *

        Response Body Schema

        @@ -2548,7 +2548,7 @@ public PagedFlux listPoolUsageMetricsInternalAsync(RequestOptions re * last aggregation interval currently available. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-account-usage-metrics. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-account-usage-metrics. * * You can add these to a request with {@link RequestOptions#addQueryParam} *

        Response Body Schema

        @@ -2611,7 +2611,7 @@ private PagedResponse listPoolUsageMetricsInternalSinglePage(Request * last aggregation interval currently available. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-account-usage-metrics. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-account-usage-metrics. * * You can add these to a request with {@link RequestOptions#addQueryParam} *

        Response Body Schema

        @@ -3281,7 +3281,7 @@ public Response createPoolInternalWithResponse(BinaryData pool, RequestOpt * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-pools. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-pools. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -3659,7 +3659,7 @@ private Mono> listPoolsInternalSinglePageAsync(Request * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-pools. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-pools. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -4055,7 +4055,7 @@ public PagedFlux listPoolsInternalAsync(RequestOptions requestOption * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-pools. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-pools. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -4431,7 +4431,7 @@ private PagedResponse listPoolsInternalSinglePage(RequestOptions req * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-pools. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-pools. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -7410,7 +7410,7 @@ public Response removeNodesInternalWithResponse(String poolId, BinaryData * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. * * You can add these to a request with {@link RequestOptions#addQueryParam} *

        Response Body Schema

        @@ -7471,7 +7471,7 @@ private Mono> listSupportedImagesInternalSinglePageAsy * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. * * You can add these to a request with {@link RequestOptions#addQueryParam} *

        Response Body Schema

        @@ -7550,7 +7550,7 @@ public PagedFlux listSupportedImagesInternalAsync(RequestOptions req * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. * * You can add these to a request with {@link RequestOptions#addQueryParam} *

        Response Body Schema

        @@ -7609,7 +7609,7 @@ private PagedResponse listSupportedImagesInternalSinglePage(RequestO * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. * * You can add these to a request with {@link RequestOptions#addQueryParam} *

        Response Body Schema

        @@ -7691,7 +7691,7 @@ public PagedIterable listSupportedImagesInternal(RequestOptions requ * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. * * You can add these to a request with {@link RequestOptions#addQueryParam} *

        Response Body Schema

        @@ -7758,7 +7758,7 @@ private Mono> listPoolNodeCountsInternalSinglePageAsyn * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. * * You can add these to a request with {@link RequestOptions#addQueryParam} *

        Response Body Schema

        @@ -7843,7 +7843,7 @@ public PagedFlux listPoolNodeCountsInternalAsync(RequestOptions requ * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. * * You can add these to a request with {@link RequestOptions#addQueryParam} *

        Response Body Schema

        @@ -7908,7 +7908,7 @@ private PagedResponse listPoolNodeCountsInternalSinglePage(RequestOp * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-support-images. * * You can add these to a request with {@link RequestOptions#addQueryParam} *

        Response Body Schema

        @@ -11932,7 +11932,7 @@ public Response createJobInternalWithResponse(BinaryData job, RequestOptio * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -12391,7 +12391,7 @@ private Mono> listJobsInternalSinglePageAsync(RequestO * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -12868,7 +12868,7 @@ public PagedFlux listJobsInternalAsync(RequestOptions requestOptions * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -13325,7 +13325,7 @@ private PagedResponse listJobsInternalSinglePage(RequestOptions requ * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -13802,7 +13802,7 @@ public PagedIterable listJobsInternal(RequestOptions requestOptions) * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs-in-a-job-schedule. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs-in-a-job-schedule. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -14263,7 +14263,7 @@ private Mono> listJobsFromScheduleInternalSinglePageAs * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs-in-a-job-schedule. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs-in-a-job-schedule. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -14742,7 +14742,7 @@ public PagedFlux listJobsFromScheduleInternalAsync(String jobSchedul * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs-in-a-job-schedule. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs-in-a-job-schedule. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -15201,7 +15201,7 @@ private PagedResponse listJobsFromScheduleInternalSinglePage(String * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs-in-a-job-schedule. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs-in-a-job-schedule. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -15687,7 +15687,7 @@ public PagedIterable listJobsFromScheduleInternal(String jobSchedule * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-preparation-and-release-status. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-preparation-and-release-status. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * @@ -15784,7 +15784,7 @@ private Mono> listJobPreparationAndReleaseTaskStatusIn * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-preparation-and-release-status. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-preparation-and-release-status. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * @@ -15900,7 +15900,7 @@ public PagedFlux listJobPreparationAndReleaseTaskStatusInternalAsync * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-preparation-and-release-status. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-preparation-and-release-status. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * @@ -15996,7 +15996,7 @@ private PagedResponse listJobPreparationAndReleaseTaskStatusInternal * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-preparation-and-release-status. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-preparation-and-release-status. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * @@ -20397,7 +20397,7 @@ public Response createJobScheduleInternalWithResponse(BinaryData jobSchedu * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-schedules. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-schedules. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -20859,7 +20859,7 @@ private Mono> listJobSchedulesInternalSinglePageAsync( * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-schedules. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-schedules. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -21339,7 +21339,7 @@ public PagedFlux listJobSchedulesInternalAsync(RequestOptions reques * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-schedules. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-schedules. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -21799,7 +21799,7 @@ private PagedResponse listJobSchedulesInternalSinglePage(RequestOpti * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-schedules. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-schedules. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -22618,7 +22618,7 @@ public Response createTaskInternalWithResponse(String jobId, BinaryData ta * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-tasks. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-tasks. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -22853,7 +22853,7 @@ private Mono> listTasksInternalSinglePageAsync(String * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-tasks. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-tasks. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -23105,7 +23105,7 @@ public PagedFlux listTasksInternalAsync(String jobId, RequestOptions * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-tasks. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-tasks. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -23337,7 +23337,7 @@ private PagedResponse listTasksInternalSinglePage(String jobId, Requ * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-tasks. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-tasks. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * $expandList<String>NoAn OData $expand clause. In the form of "," @@ -25919,7 +25919,7 @@ public Response getTaskFilePropertiesInternalWithResponse(String jobId, St * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-task-files. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-task-files. * recursiveBooleanNoWhether to list children of the Task directory. This * parameter can be used in * combination with the filter parameter to list specific type of files. @@ -25936,7 +25936,7 @@ public Response getTaskFilePropertiesInternalWithResponse(String jobId, St * properties (Optional): { * creationTime: OffsetDateTime (Optional) * lastModified: OffsetDateTime (Required) - * contentLength: String (Required) + * contentLength: long (Required) * contentType: String (Optional) * fileMode: String (Optional) * } @@ -25979,7 +25979,7 @@ private Mono> listTaskFilesInternalSinglePageAsync(Str * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-task-files. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-task-files. * recursiveBooleanNoWhether to list children of the Task directory. This * parameter can be used in * combination with the filter parameter to list specific type of files. @@ -25996,7 +25996,7 @@ private Mono> listTaskFilesInternalSinglePageAsync(Str * properties (Optional): { * creationTime: OffsetDateTime (Optional) * lastModified: OffsetDateTime (Required) - * contentLength: String (Required) + * contentLength: long (Required) * contentType: String (Optional) * fileMode: String (Optional) * } @@ -26058,7 +26058,7 @@ public PagedFlux listTaskFilesInternalAsync(String jobId, String tas * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-task-files. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-task-files. * recursiveBooleanNoWhether to list children of the Task directory. This * parameter can be used in * combination with the filter parameter to list specific type of files. @@ -26075,7 +26075,7 @@ public PagedFlux listTaskFilesInternalAsync(String jobId, String tas * properties (Optional): { * creationTime: OffsetDateTime (Optional) * lastModified: OffsetDateTime (Required) - * contentLength: String (Required) + * contentLength: long (Required) * contentType: String (Optional) * fileMode: String (Optional) * } @@ -26117,7 +26117,7 @@ private PagedResponse listTaskFilesInternalSinglePage(String jobId, * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-task-files. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-task-files. * recursiveBooleanNoWhether to list children of the Task directory. This * parameter can be used in * combination with the filter parameter to list specific type of files. @@ -26134,7 +26134,7 @@ private PagedResponse listTaskFilesInternalSinglePage(String jobId, * properties (Optional): { * creationTime: OffsetDateTime (Optional) * lastModified: OffsetDateTime (Required) - * contentLength: String (Required) + * contentLength: long (Required) * contentType: String (Optional) * fileMode: String (Optional) * } @@ -27605,7 +27605,7 @@ public Response uploadNodeLogsInternalWithResponse(String poolId, St * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-nodes-in-a-pool. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-nodes-in-a-pool. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * @@ -27800,7 +27800,7 @@ private Mono> listNodesInternalSinglePageAsync(String * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-nodes-in-a-pool. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-nodes-in-a-pool. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * @@ -28012,7 +28012,7 @@ public PagedFlux listNodesInternalAsync(String poolId, RequestOption * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-nodes-in-a-pool. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-nodes-in-a-pool. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * @@ -28204,7 +28204,7 @@ private PagedResponse listNodesInternalSinglePage(String poolId, Req * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-nodes-in-a-pool. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-nodes-in-a-pool. * $selectList<String>NoAn OData $select clause. In the form of "," * separated string. * @@ -29181,7 +29181,7 @@ public Response getNodeFilePropertiesInternalWithResponse(String poolId, S * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-compute-node-files. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-compute-node-files. * recursiveBooleanNoWhether to list children of a directory. * * You can add these to a request with {@link RequestOptions#addQueryParam} @@ -29196,7 +29196,7 @@ public Response getNodeFilePropertiesInternalWithResponse(String poolId, S * properties (Optional): { * creationTime: OffsetDateTime (Optional) * lastModified: OffsetDateTime (Required) - * contentLength: String (Required) + * contentLength: long (Required) * contentType: String (Optional) * fileMode: String (Optional) * } @@ -29239,7 +29239,7 @@ private Mono> listNodeFilesInternalSinglePageAsync(Str * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-compute-node-files. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-compute-node-files. * recursiveBooleanNoWhether to list children of a directory. * * You can add these to a request with {@link RequestOptions#addQueryParam} @@ -29254,7 +29254,7 @@ private Mono> listNodeFilesInternalSinglePageAsync(Str * properties (Optional): { * creationTime: OffsetDateTime (Optional) * lastModified: OffsetDateTime (Required) - * contentLength: String (Required) + * contentLength: long (Required) * contentType: String (Optional) * fileMode: String (Optional) * } @@ -29316,7 +29316,7 @@ public PagedFlux listNodeFilesInternalAsync(String poolId, String no * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-compute-node-files. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-compute-node-files. * recursiveBooleanNoWhether to list children of a directory. * * You can add these to a request with {@link RequestOptions#addQueryParam} @@ -29331,7 +29331,7 @@ public PagedFlux listNodeFilesInternalAsync(String poolId, String no * properties (Optional): { * creationTime: OffsetDateTime (Optional) * lastModified: OffsetDateTime (Required) - * contentLength: String (Required) + * contentLength: long (Required) * contentType: String (Optional) * fileMode: String (Optional) * } @@ -29373,7 +29373,7 @@ private PagedResponse listNodeFilesInternalSinglePage(String poolId, * applications can be returned. * $filterStringNoAn OData $filter clause. For more information on constructing * this filter, see - * https://docs.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-compute-node-files. + * https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-compute-node-files. * recursiveBooleanNoWhether to list children of a directory. * * You can add these to a request with {@link RequestOptions#addQueryParam} @@ -29388,7 +29388,7 @@ private PagedResponse listNodeFilesInternalSinglePage(String poolId, * properties (Optional): { * creationTime: OffsetDateTime (Optional) * lastModified: OffsetDateTime (Required) - * contentLength: String (Required) + * contentLength: long (Required) * contentType: String (Optional) * fileMode: String (Optional) * } @@ -33892,7 +33892,7 @@ private PagedResponse listSubTasksInternalNextSinglePage(String next * properties (Optional): { * creationTime: OffsetDateTime (Optional) * lastModified: OffsetDateTime (Required) - * contentLength: String (Required) + * contentLength: long (Required) * contentType: String (Optional) * fileMode: String (Optional) * } @@ -33934,7 +33934,7 @@ private Mono> listTaskFilesInternalNextSinglePageAsync * properties (Optional): { * creationTime: OffsetDateTime (Optional) * lastModified: OffsetDateTime (Required) - * contentLength: String (Required) + * contentLength: long (Required) * contentType: String (Optional) * fileMode: String (Optional) * } @@ -34463,7 +34463,7 @@ private PagedResponse listNodeExtensionsInternalNextSinglePage(Strin * properties (Optional): { * creationTime: OffsetDateTime (Optional) * lastModified: OffsetDateTime (Required) - * contentLength: String (Required) + * contentLength: long (Required) * contentType: String (Optional) * fileMode: String (Optional) * } @@ -34505,7 +34505,7 @@ private Mono> listNodeFilesInternalNextSinglePageAsync * properties (Optional): { * creationTime: OffsetDateTime (Optional) * lastModified: OffsetDateTime (Required) - * contentLength: String (Required) + * contentLength: long (Required) * contentType: String (Optional) * fileMode: String (Optional) * } diff --git a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchJobManagerTask.java b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchJobManagerTask.java index df86a647e95d..d313349e0011 100644 --- a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchJobManagerTask.java +++ b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchJobManagerTask.java @@ -60,7 +60,7 @@ public final class BatchJobManagerTask implements JsonSerializable { String url = null; OffsetDateTime startTime = null; @@ -355,13 +356,13 @@ public static BatchJobScheduleStatistics fromJson(JsonReader jsonReader) throws Duration userCpuTime = null; Duration kernelCpuTime = null; Duration wallClockTime = null; - long readIOps = 0L; - long writeIOps = 0L; + long readIOps = Long.parseLong("0"); + long writeIOps = Long.parseLong("0"); double readIOGiB = 0.0; double writeIOGiB = 0.0; - long numSucceededTasks = 0L; - long numFailedTasks = 0L; - long numTaskRetries = 0L; + long numSucceededTasks = Long.parseLong("0"); + long numFailedTasks = Long.parseLong("0"); + long numTaskRetries = Long.parseLong("0"); Duration waitTime = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); @@ -381,78 +382,19 @@ public static BatchJobScheduleStatistics fromJson(JsonReader jsonReader) throws } else if ("wallClockTime".equals(fieldName)) { wallClockTime = reader.getNullable(nonNullReader -> Duration.parse(nonNullReader.getString())); } else if ("readIOps".equals(fieldName)) { - if (reader.currentToken() == JsonToken.STRING) { - String readIOpsStr = reader.getString(); - try { - readIOps = Long.parseLong(readIOpsStr); - } catch (NumberFormatException e) { - throw new IOException("Expected numeric readIOps, but found: " + readIOpsStr, e); - } - } else if (reader.currentToken() == JsonToken.NUMBER) { - readIOps = reader.getLong(); - } else { - throw new IOException("Expected readIOps to be a number or string, but found other type"); - } + readIOps = reader.getNullable(nonNullReader -> Long.parseLong(nonNullReader.getString())); } else if ("writeIOps".equals(fieldName)) { - if (reader.currentToken() == JsonToken.STRING) { - String writeIOpsStr = reader.getString(); - try { - writeIOps = Long.parseLong(writeIOpsStr); - } catch (NumberFormatException e) { - throw new IOException("Expected numeric writeIOps, but found: " + writeIOpsStr, e); - } - } else if (reader.currentToken() == JsonToken.NUMBER) { - writeIOps = reader.getLong(); - } else { - throw new IOException("Expected writeIOps to be a number or string, but found other type"); - } + writeIOps = reader.getNullable(nonNullReader -> Long.parseLong(nonNullReader.getString())); } else if ("readIOGiB".equals(fieldName)) { readIOGiB = reader.getDouble(); } else if ("writeIOGiB".equals(fieldName)) { writeIOGiB = reader.getDouble(); } else if ("numSucceededTasks".equals(fieldName)) { - if (reader.currentToken() == JsonToken.STRING) { - String numSucceededTasksStr = reader.getString(); - try { - numSucceededTasks = Long.parseLong(numSucceededTasksStr); - } catch (NumberFormatException e) { - throw new IOException( - "Expected numeric numSucceededTasks, but found: " + numSucceededTasksStr, e); - } - } else if (reader.currentToken() == JsonToken.NUMBER) { - numSucceededTasks = reader.getLong(); - } else { - throw new IOException( - "Expected numSucceededTasks to be a number or string, but found other type"); - } + numSucceededTasks = reader.getNullable(nonNullReader -> Long.parseLong(nonNullReader.getString())); } else if ("numFailedTasks".equals(fieldName)) { - if (reader.currentToken() == JsonToken.STRING) { - String numFailedTasksStr = reader.getString(); - try { - numFailedTasks = Long.parseLong(numFailedTasksStr); - } catch (NumberFormatException e) { - throw new IOException("Expected numeric numFailedTasks, but found: " + numFailedTasksStr, - e); - } - } else if (reader.currentToken() == JsonToken.NUMBER) { - numFailedTasks = reader.getLong(); - } else { - throw new IOException("Expected numFailedTasks to be a number or string, but found other type"); - } + numFailedTasks = reader.getNullable(nonNullReader -> Long.parseLong(nonNullReader.getString())); } else if ("numTaskRetries".equals(fieldName)) { - if (reader.currentToken() == JsonToken.STRING) { - String numTaskRetriesStr = reader.getString(); - try { - numTaskRetries = Long.parseLong(numTaskRetriesStr); - } catch (NumberFormatException e) { - throw new IOException("Expected numeric numTaskRetries, but found: " + numTaskRetriesStr, - e); - } - } else if (reader.currentToken() == JsonToken.NUMBER) { - numTaskRetries = reader.getLong(); - } else { - throw new IOException("Expected numTaskRetries to be a number or string, but found other type"); - } + numTaskRetries = reader.getNullable(nonNullReader -> Long.parseLong(nonNullReader.getString())); } else if ("waitTime".equals(fieldName)) { waitTime = reader.getNullable(nonNullReader -> Duration.parse(nonNullReader.getString())); } else { diff --git a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchJobStatistics.java b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchJobStatistics.java index 0b6b18a86d58..a77e896db09e 100644 --- a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchJobStatistics.java +++ b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchJobStatistics.java @@ -14,6 +14,7 @@ import java.time.Duration; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; +import java.util.Objects; /** * Resource usage statistics for a Job. @@ -319,13 +320,13 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStringField("userCPUTime", CoreUtils.durationToStringWithDays(this.userCpuTime)); jsonWriter.writeStringField("kernelCPUTime", CoreUtils.durationToStringWithDays(this.kernelCpuTime)); jsonWriter.writeStringField("wallClockTime", CoreUtils.durationToStringWithDays(this.wallClockTime)); - jsonWriter.writeLongField("readIOps", this.readIOps); - jsonWriter.writeLongField("writeIOps", this.writeIOps); + jsonWriter.writeStringField("readIOps", Objects.toString(this.readIOps, null)); + jsonWriter.writeStringField("writeIOps", Objects.toString(this.writeIOps, null)); jsonWriter.writeDoubleField("readIOGiB", this.readIOGiB); jsonWriter.writeDoubleField("writeIOGiB", this.writeIOGiB); - jsonWriter.writeLongField("numSucceededTasks", this.numSucceededTasks); - jsonWriter.writeLongField("numFailedTasks", this.numFailedTasks); - jsonWriter.writeLongField("numTaskRetries", this.numTaskRetries); + jsonWriter.writeStringField("numSucceededTasks", Objects.toString(this.numSucceededTasks, null)); + jsonWriter.writeStringField("numFailedTasks", Objects.toString(this.numFailedTasks, null)); + jsonWriter.writeStringField("numTaskRetries", Objects.toString(this.numTaskRetries, null)); jsonWriter.writeStringField("waitTime", CoreUtils.durationToStringWithDays(this.waitTime)); return jsonWriter.writeEndObject(); } @@ -339,8 +340,8 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the BatchJobStatistics. */ + @Generated public static BatchJobStatistics fromJson(JsonReader jsonReader) throws IOException { - // TODO: Re-add @Generated tag here and re-generate SDK once the 2024-05-01 Batch Service API is released return jsonReader.readObject(reader -> { String url = null; OffsetDateTime startTime = null; @@ -348,13 +349,13 @@ public static BatchJobStatistics fromJson(JsonReader jsonReader) throws IOExcept Duration userCpuTime = null; Duration kernelCpuTime = null; Duration wallClockTime = null; - long readIOps = 0L; - long writeIOps = 0L; + long readIOps = Long.parseLong("0"); + long writeIOps = Long.parseLong("0"); double readIOGiB = 0.0; double writeIOGiB = 0.0; - long numSucceededTasks = 0L; - long numFailedTasks = 0L; - long numTaskRetries = 0L; + long numSucceededTasks = Long.parseLong("0"); + long numFailedTasks = Long.parseLong("0"); + long numTaskRetries = Long.parseLong("0"); Duration waitTime = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); @@ -374,78 +375,19 @@ public static BatchJobStatistics fromJson(JsonReader jsonReader) throws IOExcept } else if ("wallClockTime".equals(fieldName)) { wallClockTime = reader.getNullable(nonNullReader -> Duration.parse(nonNullReader.getString())); } else if ("readIOps".equals(fieldName)) { - if (reader.currentToken() == JsonToken.STRING) { - String readIOpsStr = reader.getString(); - try { - readIOps = Long.parseLong(readIOpsStr); - } catch (NumberFormatException e) { - throw new IOException("Expected numeric readIOps, but found: " + readIOpsStr, e); - } - } else if (reader.currentToken() == JsonToken.NUMBER) { - readIOps = reader.getLong(); - } else { - throw new IOException("Expected readIOps to be a number or string, but found other type"); - } + readIOps = reader.getNullable(nonNullReader -> Long.parseLong(nonNullReader.getString())); } else if ("writeIOps".equals(fieldName)) { - if (reader.currentToken() == JsonToken.STRING) { - String writeIOpsStr = reader.getString(); - try { - writeIOps = Long.parseLong(writeIOpsStr); - } catch (NumberFormatException e) { - throw new IOException("Expected numeric writeIOps, but found: " + writeIOpsStr, e); - } - } else if (reader.currentToken() == JsonToken.NUMBER) { - writeIOps = reader.getLong(); - } else { - throw new IOException("Expected writeIOps to be a number or string, but found other type"); - } + writeIOps = reader.getNullable(nonNullReader -> Long.parseLong(nonNullReader.getString())); } else if ("readIOGiB".equals(fieldName)) { readIOGiB = reader.getDouble(); } else if ("writeIOGiB".equals(fieldName)) { writeIOGiB = reader.getDouble(); } else if ("numSucceededTasks".equals(fieldName)) { - if (reader.currentToken() == JsonToken.STRING) { - String numSucceededTasksStr = reader.getString(); - try { - numSucceededTasks = Long.parseLong(numSucceededTasksStr); - } catch (NumberFormatException e) { - throw new IOException( - "Expected numeric numSucceededTasks, but found: " + numSucceededTasksStr, e); - } - } else if (reader.currentToken() == JsonToken.NUMBER) { - numSucceededTasks = reader.getLong(); - } else { - throw new IOException( - "Expected numSucceededTasks to be a number or string, but found other type"); - } + numSucceededTasks = reader.getNullable(nonNullReader -> Long.parseLong(nonNullReader.getString())); } else if ("numFailedTasks".equals(fieldName)) { - if (reader.currentToken() == JsonToken.STRING) { - String numFailedTasksStr = reader.getString(); - try { - numFailedTasks = Long.parseLong(numFailedTasksStr); - } catch (NumberFormatException e) { - throw new IOException("Expected numeric numFailedTasks, but found: " + numFailedTasksStr, - e); - } - } else if (reader.currentToken() == JsonToken.NUMBER) { - numFailedTasks = reader.getLong(); - } else { - throw new IOException("Expected numFailedTasks to be a number or string, but found other type"); - } + numFailedTasks = reader.getNullable(nonNullReader -> Long.parseLong(nonNullReader.getString())); } else if ("numTaskRetries".equals(fieldName)) { - if (reader.currentToken() == JsonToken.STRING) { - String numTaskRetriesStr = reader.getString(); - try { - numTaskRetries = Long.parseLong(numTaskRetriesStr); - } catch (NumberFormatException e) { - throw new IOException("Expected numeric numTaskRetries, but found: " + numTaskRetriesStr, - e); - } - } else if (reader.currentToken() == JsonToken.NUMBER) { - numTaskRetries = reader.getLong(); - } else { - throw new IOException("Expected numTaskRetries to be a number or string, but found other type"); - } + numTaskRetries = reader.getNullable(nonNullReader -> Long.parseLong(nonNullReader.getString())); } else if ("waitTime".equals(fieldName)) { waitTime = reader.getNullable(nonNullReader -> Duration.parse(nonNullReader.getString())); } else { diff --git a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchNode.java b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchNode.java index 0873a4954dba..dca45fc1ade6 100644 --- a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchNode.java +++ b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchNode.java @@ -89,7 +89,7 @@ public final class BatchNode implements JsonSerializable { /* * The size of the virtual machine hosting the Compute Node. For information about available sizes of virtual * machines in Pools, see Choose a VM size for Compute Nodes in an Azure Batch Pool - * (https://docs.microsoft.com/azure/batch/batch-pool-vm-sizes). + * (https://learn.microsoft.com/azure/batch/batch-pool-vm-sizes). */ @Generated private String vmSize; @@ -284,7 +284,7 @@ public String getAffinityId() { /** * Get the vmSize property: The size of the virtual machine hosting the Compute Node. For information about * available sizes of virtual machines in Pools, see Choose a VM size for Compute Nodes in an Azure Batch Pool - * (https://docs.microsoft.com/azure/batch/batch-pool-vm-sizes). + * (https://learn.microsoft.com/azure/batch/batch-pool-vm-sizes). * * @return the vmSize value. */ diff --git a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchPool.java b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchPool.java index dc8544bf61c8..561b2e0a4e53 100644 --- a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchPool.java +++ b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchPool.java @@ -92,11 +92,9 @@ public final class BatchPool implements JsonSerializable { /* * The size of virtual machines in the Pool. All virtual machines in a Pool are the same size. For information about - * available VM sizes, see Sizes for Virtual Machines (Linux) - * (https://azure.microsoft.com/documentation/articles/virtual-machines-linux-sizes/) or Sizes for Virtual Machines - * (Windows) (https://azure.microsoft.com/documentation/articles/virtual-machines-windows-sizes/). Batch supports - * all Azure VM sizes except STANDARD_A0 and those with premium storage (STANDARD_GS, STANDARD_DS, and STANDARD_DSV2 - * series). + * available VM sizes, see Sizes for Virtual Machines in Azure + * (https://learn.microsoft.com/azure/virtual-machines/sizes/overview). Batch supports all Azure VM sizes except + * STANDARD_A0 and those with premium storage (STANDARD_GS, STANDARD_DS, and STANDARD_DSV2 series). */ @Generated private String vmSize; @@ -382,11 +380,9 @@ public OffsetDateTime getAllocationStateTransitionTime() { /** * Get the vmSize property: The size of virtual machines in the Pool. All virtual machines in a Pool are the same - * size. For information about available VM sizes, see Sizes for Virtual Machines (Linux) - * (https://azure.microsoft.com/documentation/articles/virtual-machines-linux-sizes/) or Sizes for Virtual Machines - * (Windows) (https://azure.microsoft.com/documentation/articles/virtual-machines-windows-sizes/). Batch supports - * all Azure VM sizes except STANDARD_A0 and those with premium storage (STANDARD_GS, STANDARD_DS, and STANDARD_DSV2 - * series). + * size. For information about available VM sizes, see Sizes for Virtual Machines in Azure + * (https://learn.microsoft.com/azure/virtual-machines/sizes/overview). Batch supports all Azure VM sizes except + * STANDARD_A0 and those with premium storage (STANDARD_GS, STANDARD_DS, and STANDARD_DSV2 series). * * @return the vmSize value. */ diff --git a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchPoolCreateContent.java b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchPoolCreateContent.java index 5f86fce4baa4..8a5bcd16cef3 100644 --- a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchPoolCreateContent.java +++ b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchPoolCreateContent.java @@ -40,11 +40,9 @@ public final class BatchPoolCreateContent implements JsonSerializable { OffsetDateTime startTime = null; OffsetDateTime lastUpdateTime = null; @@ -315,8 +316,8 @@ public static BatchPoolResourceStatistics fromJson(JsonReader jsonReader) throws double peakMemoryGiB = 0.0; double avgDiskGiB = 0.0; double peakDiskGiB = 0.0; - long diskReadIOps = 0L; - long diskWriteIOps = 0L; + long diskReadIOps = Long.parseLong("0"); + long diskWriteIOps = Long.parseLong("0"); double diskReadGiB = 0.0; double diskWriteGiB = 0.0; double networkReadGiB = 0.0; @@ -341,31 +342,9 @@ public static BatchPoolResourceStatistics fromJson(JsonReader jsonReader) throws } else if ("peakDiskGiB".equals(fieldName)) { peakDiskGiB = reader.getDouble(); } else if ("diskReadIOps".equals(fieldName)) { - if (reader.currentToken() == JsonToken.STRING) { - String diskReadIOpsStr = reader.getString(); - try { - diskReadIOps = Long.parseLong(diskReadIOpsStr); - } catch (NumberFormatException e) { - throw new IOException("Expected numeric diskReadIOps, but found: " + diskReadIOpsStr, e); - } - } else if (reader.currentToken() == JsonToken.NUMBER) { - diskReadIOps = reader.getLong(); - } else { - throw new IOException("Expected diskReadIOps to be a number or string, but found other type"); - } + diskReadIOps = reader.getNullable(nonNullReader -> Long.parseLong(nonNullReader.getString())); } else if ("diskWriteIOps".equals(fieldName)) { - if (reader.currentToken() == JsonToken.STRING) { - String diskWriteIOpsStr = reader.getString(); - try { - diskWriteIOps = Long.parseLong(diskWriteIOpsStr); - } catch (NumberFormatException e) { - throw new IOException("Expected numeric diskWriteIOps, but found: " + diskWriteIOpsStr, e); - } - } else if (reader.currentToken() == JsonToken.NUMBER) { - diskWriteIOps = reader.getLong(); - } else { - throw new IOException("Expected diskWriteIOps to be a number or string, but found other type"); - } + diskWriteIOps = reader.getNullable(nonNullReader -> Long.parseLong(nonNullReader.getString())); } else if ("diskReadGiB".equals(fieldName)) { diskReadGiB = reader.getDouble(); } else if ("diskWriteGiB".equals(fieldName)) { diff --git a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchPoolSpecification.java b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchPoolSpecification.java index 0f1baa30836e..166e64deb77a 100644 --- a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchPoolSpecification.java +++ b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchPoolSpecification.java @@ -30,7 +30,7 @@ public final class BatchPoolSpecification implements JsonSerializable
        This field can be updated only when the + * (https://learn.microsoft.com/azure/batch/batch-pool-vm-sizes).

        This field can be updated only when the * pool is empty. */ @Generated @@ -372,7 +372,7 @@ public BatchPoolUpdateContent setDisplayName(String displayName) { /** * Get the vmSize property: The size of virtual machines in the Pool. For information about available sizes of * virtual machines in Pools, see Choose a VM size for Compute Nodes in an Azure Batch Pool - * (https://docs.microsoft.com/azure/batch/batch-pool-vm-sizes).<br /><br />This field can be updated + * (https://learn.microsoft.com/azure/batch/batch-pool-vm-sizes).<br /><br />This field can be updated * only when the pool is empty. * * @return the vmSize value. @@ -385,7 +385,7 @@ public String getVmSize() { /** * Set the vmSize property: The size of virtual machines in the Pool. For information about available sizes of * virtual machines in Pools, see Choose a VM size for Compute Nodes in an Azure Batch Pool - * (https://docs.microsoft.com/azure/batch/batch-pool-vm-sizes).<br /><br />This field can be updated + * (https://learn.microsoft.com/azure/batch/batch-pool-vm-sizes).<br /><br />This field can be updated * only when the pool is empty. * * @param vmSize the vmSize value to set. diff --git a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchPoolUsageMetrics.java b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchPoolUsageMetrics.java index e29a8f28e153..75ac633f03cc 100644 --- a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchPoolUsageMetrics.java +++ b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchPoolUsageMetrics.java @@ -41,7 +41,7 @@ public final class BatchPoolUsageMetrics implements JsonSerializable { * features, you should invoke the shell in the command line, for example using "cmd /c MyCommand" in Windows or * "/bin/sh -c MyCommand" in Linux. If the command line refers to file paths, it should use a relative path * (relative to the Task working directory), or use the Batch provided environment variable - * (https://docs.microsoft.com/azure/batch/batch-compute-node-environment-variables). + * (https://learn.microsoft.com/azure/batch/batch-compute-node-environment-variables). */ @Generated private final String commandLine; @@ -114,7 +114,7 @@ public BatchStartTask(String commandLine) { * advantage of such features, you should invoke the shell in the command line, for example using "cmd /c MyCommand" * in Windows or "/bin/sh -c MyCommand" in Linux. If the command line refers to file paths, it should use a relative * path (relative to the Task working directory), or use the Batch provided environment variable - * (https://docs.microsoft.com/azure/batch/batch-compute-node-environment-variables). + * (https://learn.microsoft.com/azure/batch/batch-compute-node-environment-variables). * * @return the commandLine value. */ diff --git a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchTask.java b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchTask.java index 1f5a0c92f91c..2ee7fe240325 100644 --- a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchTask.java +++ b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchTask.java @@ -106,7 +106,7 @@ public final class BatchTask implements JsonSerializable { * expansion. If you want to take advantage of such features, you should invoke the shell in the command line, for * example using "cmd /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux. If the command line refers to * file paths, it should use a relative path (relative to the Task working directory), or use the Batch provided - * environment variable (https://docs.microsoft.com/azure/batch/batch-compute-node-environment-variables). + * environment variable (https://learn.microsoft.com/azure/batch/batch-compute-node-environment-variables). */ @Generated private String commandLine; @@ -360,7 +360,7 @@ public OffsetDateTime getPreviousStateTransitionTime() { * shell in the command line, for example using "cmd /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux. If * the command line refers to file paths, it should use a relative path (relative to the Task working directory), or * use the Batch provided environment variable - * (https://docs.microsoft.com/azure/batch/batch-compute-node-environment-variables). + * (https://learn.microsoft.com/azure/batch/batch-compute-node-environment-variables). * * @return the commandLine value. */ diff --git a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchTaskCreateContent.java b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchTaskCreateContent.java index c5617cb875d2..2266856b8488 100644 --- a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchTaskCreateContent.java +++ b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/BatchTaskCreateContent.java @@ -46,7 +46,7 @@ public final class BatchTaskCreateContent implements JsonSerializable { String url = null; OffsetDateTime startTime = null; @@ -283,8 +284,8 @@ public static BatchTaskStatistics fromJson(JsonReader jsonReader) throws IOExcep Duration userCpuTime = null; Duration kernelCpuTime = null; Duration wallClockTime = null; - long readIOps = 0L; - long writeIOps = 0L; + long readIOps = Long.parseLong("0"); + long writeIOps = Long.parseLong("0"); double readIOGiB = 0.0; double writeIOGiB = 0.0; Duration waitTime = null; @@ -306,31 +307,9 @@ public static BatchTaskStatistics fromJson(JsonReader jsonReader) throws IOExcep } else if ("wallClockTime".equals(fieldName)) { wallClockTime = reader.getNullable(nonNullReader -> Duration.parse(nonNullReader.getString())); } else if ("readIOps".equals(fieldName)) { - if (reader.currentToken() == JsonToken.STRING) { - String readIOpsStr = reader.getString(); - try { - readIOps = Long.parseLong(readIOpsStr); - } catch (NumberFormatException e) { - throw new IOException("Expected numeric readIOps, but found: " + readIOpsStr, e); - } - } else if (reader.currentToken() == JsonToken.NUMBER) { - readIOps = reader.getLong(); - } else { - throw new IOException("Expected readIOps to be a number or string, but found other type"); - } + readIOps = reader.getNullable(nonNullReader -> Long.parseLong(nonNullReader.getString())); } else if ("writeIOps".equals(fieldName)) { - if (reader.currentToken() == JsonToken.STRING) { - String writeIOpsStr = reader.getString(); - try { - writeIOps = Long.parseLong(writeIOpsStr); - } catch (NumberFormatException e) { - throw new IOException("Expected numeric writeIOps, but found: " + writeIOpsStr, e); - } - } else if (reader.currentToken() == JsonToken.NUMBER) { - writeIOps = reader.getLong(); - } else { - throw new IOException("Expected writeIOps to be a number or string, but found other type"); - } + writeIOps = reader.getNullable(nonNullReader -> Long.parseLong(nonNullReader.getString())); } else if ("readIOGiB".equals(fieldName)) { readIOGiB = reader.getDouble(); } else if ("writeIOGiB".equals(fieldName)) { diff --git a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/DiffDiskPlacement.java b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/DiffDiskPlacement.java index b58f79b064d1..afcd7d0c0724 100644 --- a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/DiffDiskPlacement.java +++ b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/DiffDiskPlacement.java @@ -12,8 +12,8 @@ * property can be used by user in the request to choose which location the operating system should be in. e.g., cache * disk space for Ephemeral OS disk provisioning. For more information on Ephemeral OS disk size requirements, please * refer to Ephemeral OS disk size requirements for Windows VMs at - * https://docs.microsoft.com/azure/virtual-machines/windows/ephemeral-os-disks#size-requirements and Linux VMs at - * https://docs.microsoft.com/azure/virtual-machines/linux/ephemeral-os-disks#size-requirements. + * https://learn.microsoft.com/azure/virtual-machines/windows/ephemeral-os-disks#size-requirements and Linux VMs at + * https://learn.microsoft.com/azure/virtual-machines/linux/ephemeral-os-disks#size-requirements. */ public final class DiffDiskPlacement extends ExpandableStringEnum { diff --git a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/DiffDiskSettings.java b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/DiffDiskSettings.java index e88eeba062cb..67c91ff91c4d 100644 --- a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/DiffDiskSettings.java +++ b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/DiffDiskSettings.java @@ -22,8 +22,8 @@ public final class DiffDiskSettings implements JsonSerializable { /* * The length of the file. - * TODO: Temporary workaround to get contentLength to be a long instead of string. Re-add @Generated tag and - * regenerate once we have a more permanent solution from SDK team. */ + @Generated private final long contentLength; /* @@ -76,9 +77,8 @@ public OffsetDateTime getLastModified() { * * @return the contentLength value. */ + @Generated public long getContentLength() { - // TODO: Temporary workaround to get contentLength to be a long instead of string. Re-add @Generated tag and - // regenerate once we have a more permanent solution from SDK team. return this.contentLength; } @@ -106,14 +106,13 @@ public String getFileMode() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - // TODO: Temporary workaround to get contentLength to be a long instead of string. Re-add @Generated tag and - // regenerate once we have a more permanent solution from SDK team. jsonWriter.writeStartObject(); jsonWriter.writeStringField("lastModified", this.lastModified == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.lastModified)); - jsonWriter.writeLongField("contentLength", this.contentLength); + jsonWriter.writeStringField("contentLength", Objects.toString(this.contentLength, null)); jsonWriter.writeStringField("creationTime", this.creationTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.creationTime)); jsonWriter.writeStringField("contentType", this.contentType); @@ -130,12 +129,11 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the FileProperties. */ + @Generated public static FileProperties fromJson(JsonReader jsonReader) throws IOException { - // TODO: Temporary workaround to get contentLength to be a long instead of string. Re-add @Generated tag and - // regenerate once we have a more permanent solution from SDK team. return jsonReader.readObject(reader -> { OffsetDateTime lastModified = null; - long contentLength = 0L; + long contentLength = Long.parseLong("0"); OffsetDateTime creationTime = null; String contentType = null; String fileMode = null; @@ -143,22 +141,13 @@ public static FileProperties fromJson(JsonReader jsonReader) throws IOException String fieldName = reader.getFieldName(); reader.nextToken(); if ("lastModified".equals(fieldName)) { - lastModified = reader.getNullable(nonNullReader -> OffsetDateTime.parse(nonNullReader.getString())); + lastModified = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); } else if ("contentLength".equals(fieldName)) { - if (reader.currentToken() == JsonToken.STRING) { - String contentLengthStr = reader.getString(); - try { - contentLength = Long.parseLong(contentLengthStr); - } catch (NumberFormatException e) { - throw new IOException("Expected numeric contentLength, but found: " + contentLengthStr, e); - } - } else if (reader.currentToken() == JsonToken.NUMBER) { - contentLength = reader.getLong(); - } else { - throw new IOException("Expected contentLength to be a number or string, but found other type"); - } + contentLength = reader.getNullable(nonNullReader -> Long.parseLong(nonNullReader.getString())); } else if ("creationTime".equals(fieldName)) { - creationTime = reader.getNullable(nonNullReader -> OffsetDateTime.parse(nonNullReader.getString())); + creationTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); } else if ("contentType".equals(fieldName)) { contentType = reader.getString(); } else if ("fileMode".equals(fieldName)) { @@ -181,9 +170,8 @@ public static FileProperties fromJson(JsonReader jsonReader) throws IOException * @param lastModified the lastModified value to set. * @param contentLength the contentLength value to set. */ + @Generated private FileProperties(OffsetDateTime lastModified, long contentLength) { - // TODO: Temporary workaround to get contentLength to be a long instead of string. Re-add @Generated tag and - // regenerate once we have a more permanent solution from SDK team. this.lastModified = lastModified; this.contentLength = contentLength; } diff --git a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/ImageReference.java b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/ImageReference.java index 4163d59212fe..7715935052b7 100644 --- a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/ImageReference.java +++ b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/ImageReference.java @@ -55,7 +55,7 @@ public final class ImageReference implements JsonSerializable { * region and must be in the same subscription as the Azure Batch account. If the image version is not specified in * the imageId, the latest version will be used. For information about the firewall settings for the Batch Compute * Node agent to communicate with the Batch service see - * https://docs.microsoft.com/azure/batch/nodes-and-pools#virtual-network-vnet-and-firewall-configuration. + * https://learn.microsoft.com/azure/batch/nodes-and-pools#virtual-network-vnet-and-firewall-configuration. */ @Generated private String virtualMachineImageId; @@ -181,7 +181,7 @@ public ImageReference setVersion(String version) { * subscription as the Azure Batch account. If the image version is not specified in the imageId, the latest version * will be used. For information about the firewall settings for the Batch Compute Node agent to communicate with * the Batch service see - * https://docs.microsoft.com/azure/batch/nodes-and-pools#virtual-network-vnet-and-firewall-configuration. + * https://learn.microsoft.com/azure/batch/nodes-and-pools#virtual-network-vnet-and-firewall-configuration. * * @return the virtualMachineImageId value. */ @@ -201,7 +201,7 @@ public String getVirtualMachineImageId() { * subscription as the Azure Batch account. If the image version is not specified in the imageId, the latest version * will be used. For information about the firewall settings for the Batch Compute Node agent to communicate with * the Batch service see - * https://docs.microsoft.com/azure/batch/nodes-and-pools#virtual-network-vnet-and-firewall-configuration. + * https://learn.microsoft.com/azure/batch/nodes-and-pools#virtual-network-vnet-and-firewall-configuration. * * @param virtualMachineImageId the virtualMachineImageId value to set. * @return the ImageReference object itself. diff --git a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/NetworkConfiguration.java b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/NetworkConfiguration.java index 4e8c88eaa5fd..cf4b4765a8e7 100644 --- a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/NetworkConfiguration.java +++ b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/NetworkConfiguration.java @@ -32,7 +32,7 @@ public final class NetworkConfiguration implements JsonSerializable uploadHeaders; @@ -129,7 +129,7 @@ public OutputFileBlobContainerDestination setIdentityReference(BatchNodeIdentity /** * Get the uploadHeaders property: A list of name-value pairs for headers to be used in uploading output files. * These headers will be specified when uploading files to Azure Storage. Official document on allowed headers when - * uploading blobs: https://docs.microsoft.com/rest/api/storageservices/put-blob#request-headers-all-blob-types. + * uploading blobs: https://learn.microsoft.com/rest/api/storageservices/put-blob#request-headers-all-blob-types. * * @return the uploadHeaders value. */ @@ -141,7 +141,7 @@ public List getUploadHeaders() { /** * Set the uploadHeaders property: A list of name-value pairs for headers to be used in uploading output files. * These headers will be specified when uploading files to Azure Storage. Official document on allowed headers when - * uploading blobs: https://docs.microsoft.com/rest/api/storageservices/put-blob#request-headers-all-blob-types. + * uploading blobs: https://learn.microsoft.com/rest/api/storageservices/put-blob#request-headers-all-blob-types. * * @param uploadHeaders the uploadHeaders value to set. * @return the OutputFileBlobContainerDestination object itself. diff --git a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/VirtualMachineConfiguration.java b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/VirtualMachineConfiguration.java index 81628e511d42..8908fdff8a64 100644 --- a/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/VirtualMachineConfiguration.java +++ b/sdk/batch/azure-compute-batch/src/main/java/com/azure/compute/batch/models/VirtualMachineConfiguration.java @@ -50,8 +50,9 @@ public final class VirtualMachineConfiguration implements JsonSerializable getDataDisks() { * attached, each attached disk is empty. When the Compute Node is removed from the Pool, the disk and all data * associated with it is also deleted. The disk is not formatted after being attached, it must be formatted before * use - for more information see - * https://docs.microsoft.com/azure/virtual-machines/linux/classic/attach-disk#initialize-a-new-data-disk-in-linux + * https://learn.microsoft.com/azure/virtual-machines/linux/classic/attach-disk#initialize-a-new-data-disk-in-linux * and - * https://docs.microsoft.com/azure/virtual-machines/windows/attach-disk-ps#add-an-empty-data-disk-to-a-virtual-machine. + * https://learn.microsoft.com/azure/virtual-machines/windows/attach-disk-ps#add-an-empty-data-disk-to-a-virtual-machine. * * @param dataDisks the dataDisks value to set. * @return the VirtualMachineConfiguration object itself. diff --git a/sdk/batch/azure-compute-batch/src/test/java/com/azure/compute/batch/PoolTests.java b/sdk/batch/azure-compute-batch/src/test/java/com/azure/compute/batch/PoolTests.java index ae59c4654642..89f45cd50299 100644 --- a/sdk/batch/azure-compute-batch/src/test/java/com/azure/compute/batch/PoolTests.java +++ b/sdk/batch/azure-compute-batch/src/test/java/com/azure/compute/batch/PoolTests.java @@ -320,9 +320,9 @@ public void canCreatePoolWithConfidentialVM() throws Exception { if (!poolExists(batchClient, poolId)) { // Define the image reference - ImageReference imageReference = new ImageReference().setPublisher("Canonical") - .setOffer("0001-com-ubuntu-server-jammy") - .setSku("22_04-lts"); + ImageReference imageReference = new ImageReference().setPublisher("microsoftwindowsserver") + .setOffer("windowsserver") + .setSku("2022-datacenter-smalldisk-g2"); // Set the security profile for the Confidential VM SecurityProfile securityProfile = new SecurityProfile(true, SecurityTypes.CONFIDENTIAL_VM, @@ -339,7 +339,7 @@ public void canCreatePoolWithConfidentialVM() throws Exception { // Define the virtual machine configuration VirtualMachineConfiguration vmConfiguration - = new VirtualMachineConfiguration(imageReference, "batch.node.ubuntu 22.04") + = new VirtualMachineConfiguration(imageReference, "batch.node.windows amd64") .setSecurityProfile(securityProfile) .setOsDisk(osDisk); diff --git a/sdk/batch/azure-compute-batch/tsp-location.yaml b/sdk/batch/azure-compute-batch/tsp-location.yaml index 46d833a29d40..6a6113283454 100644 --- a/sdk/batch/azure-compute-batch/tsp-location.yaml +++ b/sdk/batch/azure-compute-batch/tsp-location.yaml @@ -1,4 +1,4 @@ directory: specification/batch/Azure.Batch -commit: 85ed8fc06e19c902c95b531cbd8a643428d5f28d +commit: a0dc6346cd1f771c60765ade7ee86e476f24aa18 repo: Azure/azure-rest-api-specs cleanup: false diff --git a/sdk/batch/azure-resourcemanager-batch/README.md b/sdk/batch/azure-resourcemanager-batch/README.md index b6f41f3f0377..92c941f90905 100644 --- a/sdk/batch/azure-resourcemanager-batch/README.md +++ b/sdk/batch/azure-resourcemanager-batch/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-batch - 2.0.0 + 2.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -133,4 +133,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fbatch%2Fazure-resourcemanager-batch%2FREADME.png) + diff --git a/sdk/batch/azure-resourcemanager-batch/pom.xml b/sdk/batch/azure-resourcemanager-batch/pom.xml index f07a454e11f1..6d923dc9769b 100644 --- a/sdk/batch/azure-resourcemanager-batch/pom.xml +++ b/sdk/batch/azure-resourcemanager-batch/pom.xml @@ -50,34 +50,34 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-storage - 2.46.0 + 2.48.0 test diff --git a/sdk/batch/microsoft-azure-batch/README.md b/sdk/batch/microsoft-azure-batch/README.md index 848b235e789d..c2ac974f9ac1 100644 --- a/sdk/batch/microsoft-azure-batch/README.md +++ b/sdk/batch/microsoft-azure-batch/README.md @@ -142,4 +142,4 @@ All tests are run from the `sdk/batch` directory. They can be run either on the This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fbatch%2Fmicrosoft-azure-batch%2FREADME.png) + diff --git a/sdk/batch/microsoft-azure-batch/pom.xml b/sdk/batch/microsoft-azure-batch/pom.xml index 099462bb93cf..5ef329a0c989 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.54.1 + 1.55.3 test @@ -193,7 +193,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 false diff --git a/sdk/billing/azure-resourcemanager-billing/README.md b/sdk/billing/azure-resourcemanager-billing/README.md index 23eec9a88bbf..216541da39d8 100644 --- a/sdk/billing/azure-resourcemanager-billing/README.md +++ b/sdk/billing/azure-resourcemanager-billing/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-billing - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fbilling%2Fazure-resourcemanager-billing%2FREADME.png) + diff --git a/sdk/billing/azure-resourcemanager-billing/pom.xml b/sdk/billing/azure-resourcemanager-billing/pom.xml index 9342ab0836d5..f43ed317ada5 100644 --- a/sdk/billing/azure-resourcemanager-billing/pom.xml +++ b/sdk/billing/azure-resourcemanager-billing/pom.xml @@ -50,28 +50,28 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/billingbenefits/azure-resourcemanager-billingbenefits/README.md b/sdk/billingbenefits/azure-resourcemanager-billingbenefits/README.md index 98754df8cae0..63fa8153e0ee 100644 --- a/sdk/billingbenefits/azure-resourcemanager-billingbenefits/README.md +++ b/sdk/billingbenefits/azure-resourcemanager-billingbenefits/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-billingbenefits - 1.0.0-beta.2 + 1.0.0-beta.3 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fbillingbenefits%2Fazure-resourcemanager-billingbenefits%2FREADME.png) + diff --git a/sdk/billingbenefits/azure-resourcemanager-billingbenefits/pom.xml b/sdk/billingbenefits/azure-resourcemanager-billingbenefits/pom.xml index a1917f3d2504..c2aae77b5652 100644 --- a/sdk/billingbenefits/azure-resourcemanager-billingbenefits/pom.xml +++ b/sdk/billingbenefits/azure-resourcemanager-billingbenefits/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/boms/azure-sdk-bom/CHANGELOG.md b/sdk/boms/azure-sdk-bom/CHANGELOG.md index a9784c992ad1..1abd3d9a1c83 100644 --- a/sdk/boms/azure-sdk-bom/CHANGELOG.md +++ b/sdk/boms/azure-sdk-bom/CHANGELOG.md @@ -1,5 +1,20 @@ # Release History +## 1.2.32 (2025-03-06) + +### Dependency Updates + +- Updated Azure SDK dependency versions to the latest releases. + +## 1.2.31 (2025-01-28) + +### Dependency Updates + +- Added a new library entry to the BOM: + - [azure-ai-documentintelligence](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/documentintelligence/azure-ai-documentintelligence/README.md) + +- Updated Azure SDK dependency versions to the latest releases. + ## 1.2.30 (2024-12-04) ### Dependency Updates @@ -24,7 +39,7 @@ - Added new library entries to the BOM: - `azure-data-schemaregistry-jsonschema` - - `azure-health-deidentification` + - `azure-health-insights-radiologyinsights` - Updated Azure SDK dependency versions to the latest releases. diff --git a/sdk/boms/azure-sdk-bom/README.md b/sdk/boms/azure-sdk-bom/README.md index 43f5790070d3..847ee7049c35 100644 --- a/sdk/boms/azure-sdk-bom/README.md +++ b/sdk/boms/azure-sdk-bom/README.md @@ -21,7 +21,7 @@ result in all dependencies being included in your project. com.azure azure-sdk-bom - 1.2.30 + 1.2.32 pom import diff --git a/sdk/boms/azure-sdk-bom/pom.xml b/sdk/boms/azure-sdk-bom/pom.xml index d6c10f2871da..2431229888a2 100644 --- a/sdk/boms/azure-sdk-bom/pom.xml +++ b/sdk/boms/azure-sdk-bom/pom.xml @@ -2,7 +2,7 @@ 4.0.0 com.azure azure-sdk-bom - 1.2.30 + 1.2.32 pom Azure Java SDK BOM (Bill of Materials) Azure Java SDK BOM (Bill of Materials) @@ -38,22 +38,27 @@ com.azure azure-ai-contentsafety - 1.0.9 + 1.0.10 com.azure azure-ai-formrecognizer - 4.1.12 + 4.1.13 + + + com.azure + azure-ai-documentintelligence + 1.0.0 com.azure azure-ai-metricsadvisor - 1.2.4 + 1.2.5 com.azure azure-ai-textanalytics - 5.5.4 + 5.5.5 com.azure @@ -63,122 +68,132 @@ com.azure azure-ai-translation-text - 1.1.0 + 1.1.1 com.azure azure-communication-callautomation - 1.3.1 + 1.3.2 com.azure azure-communication-chat - 1.5.7 + 1.5.8 com.azure azure-communication-common - 1.3.9 + 1.3.10 com.azure azure-communication-email - 1.0.19 + 1.0.20 com.azure azure-communication-identity - 1.6.2 + 1.6.3 com.azure azure-communication-jobrouter - 1.1.10 + 1.1.11 com.azure azure-communication-messages - 1.1.1 + 1.1.2 com.azure azure-communication-phonenumbers - 1.1.19 + 1.2.1 com.azure azure-communication-rooms - 1.1.8 + 1.1.9 com.azure azure-communication-sms - 1.1.30 + 1.1.31 com.azure azure-containers-containerregistry - 1.2.14 + 1.2.15 com.azure azure-core - 1.54.1 + 1.55.2 com.azure azure-core-amqp - 2.9.12 + 2.9.15 + + + com.azure + azure-core-http-jdk-httpclient + 1.0.2 com.azure azure-core-http-netty - 1.15.7 + 1.15.10 com.azure azure-core-http-okhttp - 1.12.6 + 1.12.9 + + + com.azure + azure-core-http-vertx + 1.0.2 com.azure azure-core-management - 1.15.6 + 1.16.2 com.azure azure-core-serializer-json-gson - 1.3.4 + 1.3.7 com.azure azure-core-serializer-json-jackson - 1.5.4 + 1.5.7 com.azure azure-cosmos - 4.65.0 + 4.67.0 com.azure azure-cosmos-encryption - 2.16.0 + 2.18.0 com.azure azure-data-appconfiguration - 1.7.3 + 1.7.4 com.azure azure-data-schemaregistry - 1.5.2 + 1.5.3 com.azure azure-data-schemaregistry-apacheavro - 1.1.23 + 1.1.24 com.azure @@ -188,132 +203,127 @@ com.azure azure-data-tables - 12.5.0 + 12.5.2 com.azure azure-developer-devcenter - 1.0.6 + 1.0.7 com.azure azure-developer-loadtesting - 1.0.19 + 1.0.21 com.azure azure-digitaltwins-core - 1.4.0 - - - com.azure - azure-health-deidentification - 1.0.0 + 1.4.1 com.azure azure-identity - 1.14.2 + 1.15.3 com.azure azure-identity-broker - 1.1.8 + 1.1.12 com.azure azure-identity-extensions - 1.1.22 + 1.2.1 com.azure azure-iot-deviceupdate - 1.0.24 + 1.0.25 com.azure azure-json - 1.3.0 + 1.4.0 com.azure azure-messaging-eventgrid - 4.27.0 + 4.29.0 com.azure azure-messaging-eventgrid-namespaces - 1.1.1 + 1.1.2 com.azure azure-messaging-eventhubs - 5.19.2 + 5.20.1 com.azure azure-messaging-eventhubs-checkpointstore-blob - 1.20.2 + 1.20.5 com.azure azure-messaging-servicebus - 7.17.7 + 7.17.9 com.azure azure-messaging-webpubsub - 1.3.3 + 1.4.0 com.azure azure-messaging-webpubsub-client - 1.0.9 + 1.1.0 com.azure azure-mixedreality-authentication - 1.2.30 + 1.2.31 com.azure azure-mixedreality-remoterendering - 1.1.35 + 1.1.36 com.azure azure-monitor-ingestion - 1.2.7 + 1.2.8 com.azure azure-monitor-query - 1.5.4 + 1.5.6 com.azure azure-search-documents - 11.7.4 + 11.7.5 com.azure azure-security-attestation - 1.1.30 + 1.1.31 com.azure azure-security-confidentialledger - 1.0.26 + 1.0.27 com.azure azure-security-keyvault-administration - 4.6.1 + 4.6.3 com.azure azure-security-keyvault-certificates - 4.7.1 + 4.7.3 com.azure @@ -323,63 +333,68 @@ com.azure azure-security-keyvault-keys - 4.9.1 + 4.9.3 com.azure azure-security-keyvault-secrets - 4.9.1 + 4.9.3 com.azure azure-storage-blob - 12.29.0 + 12.29.1 com.azure azure-storage-blob-batch - 12.25.0 + 12.25.1 com.azure azure-storage-blob-cryptography - 12.28.0 + 12.28.1 com.azure azure-storage-common - 12.28.0 + 12.28.1 com.azure azure-storage-file-datalake - 12.22.0 + 12.22.1 com.azure azure-storage-file-share - 12.25.0 + 12.25.2 com.azure azure-storage-internal-avro - 12.14.0 + 12.14.1 com.azure azure-storage-queue - 12.24.0 + 12.24.1 com.azure azure-xml - 1.1.0 + 1.2.0 com.azure azure-ai-vision-imageanalysis 1.0.0 + + com.azure + azure-health-insights-radiologyinsights + 1.0.0 + diff --git a/sdk/boms/azure-sdk-template-bom/pom.xml b/sdk/boms/azure-sdk-template-bom/pom.xml index 38941e2061c7..e15bb63652ee 100644 --- a/sdk/boms/azure-sdk-template-bom/pom.xml +++ b/sdk/boms/azure-sdk-template-bom/pom.xml @@ -5,7 +5,7 @@ 4.0.0 com.azure azure-sdk-template-bom - 1.0.0-beta.6 + 1.0.0-beta.9 pom Azure Java SDK Template BOM (Bill of Materials) BOM used for testing the release pipeline and nothing else. diff --git a/sdk/boms/ci.yml b/sdk/boms/ci.yml index 93b7b62c7847..a0507cd582ca 100644 --- a/sdk/boms/ci.yml +++ b/sdk/boms/ci.yml @@ -8,7 +8,7 @@ parameters: - name: release_azuresdkbom displayName: 'azure-sdk-bom' type: boolean - default: true + default: false - name: release_springcloudazuredependencies displayName: 'spring-cloud-azure-dependencies' type: boolean @@ -28,10 +28,10 @@ extends: safeName: azuresdkbom releaseInBatch: ${{ parameters.release_azuresdkbom }} - name: spring-cloud-azure-dependencies - groupID: com.azure.spring + groupId: com.azure.spring safeName: springcloudazuredependencies releaseInBatch: ${{ parameters.release_springcloudazuredependencies }} - name: azure-sdk-template-bom - groupID: com.azure + groupId: com.azure safeName: azuresdktemplatebom releaseInBatch: ${{ parameters.release_azuresdktemplatebom }} diff --git a/sdk/boms/spring-cloud-azure-dependencies/pom.xml b/sdk/boms/spring-cloud-azure-dependencies/pom.xml index f03f77eee5f7..030f74d1b74b 100644 --- a/sdk/boms/spring-cloud-azure-dependencies/pom.xml +++ b/sdk/boms/spring-cloud-azure-dependencies/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-dependencies - 5.20.0-beta.1 + 5.21.0-beta.1 pom Spring Cloud Azure Dependencies @@ -53,14 +53,14 @@ com.azure azure-sdk-bom - 1.2.30 + 1.2.31 pom import com.azure.resourcemanager azure-resourcemanager - 2.46.0 + 2.48.0 @@ -194,6 +194,11 @@ spring-cloud-azure-starter-keyvault ${project.version} + + com.azure.spring + spring-cloud-azure-starter-keyvault-jca + ${project.version} + com.azure.spring spring-cloud-azure-starter-keyvault-secrets diff --git a/sdk/botservice/azure-resourcemanager-botservice/README.md b/sdk/botservice/azure-resourcemanager-botservice/README.md index 21fda7aafbab..ca0974fcdc78 100644 --- a/sdk/botservice/azure-resourcemanager-botservice/README.md +++ b/sdk/botservice/azure-resourcemanager-botservice/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-botservice - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fbotservice%2Fazure-resourcemanager-botservice%2FREADME.png) + diff --git a/sdk/botservice/azure-resourcemanager-botservice/pom.xml b/sdk/botservice/azure-resourcemanager-botservice/pom.xml index 289955f73b72..28dc7a4a69f2 100644 --- a/sdk/botservice/azure-resourcemanager-botservice/pom.xml +++ b/sdk/botservice/azure-resourcemanager-botservice/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/changeanalysis/azure-resourcemanager-changeanalysis/README.md b/sdk/changeanalysis/azure-resourcemanager-changeanalysis/README.md index 00576550d3b1..77b16d3e76c1 100644 --- a/sdk/changeanalysis/azure-resourcemanager-changeanalysis/README.md +++ b/sdk/changeanalysis/azure-resourcemanager-changeanalysis/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-changeanalysis - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -105,4 +105,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fchangeanalysis%2Fazure-resourcemanager-changeanalysis%2FREADME.png) + diff --git a/sdk/changeanalysis/azure-resourcemanager-changeanalysis/pom.xml b/sdk/changeanalysis/azure-resourcemanager-changeanalysis/pom.xml index a415941c576e..c01419806dda 100644 --- a/sdk/changeanalysis/azure-resourcemanager-changeanalysis/pom.xml +++ b/sdk/changeanalysis/azure-resourcemanager-changeanalysis/pom.xml @@ -51,29 +51,29 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/chaos/azure-resourcemanager-chaos/README.md b/sdk/chaos/azure-resourcemanager-chaos/README.md index a140203fe8be..1b2aa4d6ed2b 100644 --- a/sdk/chaos/azure-resourcemanager-chaos/README.md +++ b/sdk/chaos/azure-resourcemanager-chaos/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-chaos - 1.2.0 + 1.3.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -114,4 +114,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fchaos%2Fazure-resourcemanager-chaos%2FREADME.png) + diff --git a/sdk/chaos/azure-resourcemanager-chaos/pom.xml b/sdk/chaos/azure-resourcemanager-chaos/pom.xml index 635a2294d58c..f97a45febf6e 100644 --- a/sdk/chaos/azure-resourcemanager-chaos/pom.xml +++ b/sdk/chaos/azure-resourcemanager-chaos/pom.xml @@ -52,23 +52,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test @@ -92,13 +92,13 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test com.azure.resourcemanager azure-resourcemanager-keyvault - 2.46.0 + 2.48.0 test diff --git a/sdk/clientcore/annotation-processor-test/CHANGELOG.md b/sdk/clientcore/annotation-processor-test/CHANGELOG.md new file mode 100644 index 000000000000..4144f75694a0 --- /dev/null +++ b/sdk/clientcore/annotation-processor-test/CHANGELOG.md @@ -0,0 +1,3 @@ +# Release History + +## 1.0.0-beta.1 (Unreleased) diff --git a/sdk/clientcore/annotation-processor-test/README.md b/sdk/clientcore/annotation-processor-test/README.md new file mode 100644 index 000000000000..eebaa7a81499 --- /dev/null +++ b/sdk/clientcore/annotation-processor-test/README.md @@ -0,0 +1,19 @@ +# Core Tests shared library for Java + +Tests that validate annotation-processor features of generating Service Interface Implementation for the Core library. + +## Getting started + +## Key concepts + +## Examples + +## Troubleshooting + +## Next steps + +## Contributing + + + + diff --git a/sdk/clientcore/annotation-processor-test/pom.xml b/sdk/clientcore/annotation-processor-test/pom.xml new file mode 100644 index 000000000000..cc893e52ebee --- /dev/null +++ b/sdk/clientcore/annotation-processor-test/pom.xml @@ -0,0 +1,177 @@ + + + 4.0.0 + + io.clientcore + clientcore-parent + 1.0.0-beta.3 + ../../parents/clientcore-parent + + + io.clientcore + annotation-processor-test + 1.0.0-beta.1 + + Java Core library tests for annotation-processor features. + Tests that validate features of the annotation-processor tooling. + https://github.com/Azure/azure-sdk-for-java + + + + The MIT License (MIT) + http://opensource.org/licenses/MIT + repo + + + + + https://github.com/Azure/azure-sdk-for-java + scm:git:https://github.com/Azure/azure-sdk-for-java.git + scm:git:https://github.com/Azure/azure-sdk-for-java.git + + + + UTF-8 + true + true + true + true + true + all,-missing + + --add-exports io.clientcore.core/io.clientcore.core.implementation.http=ALL-UNNAMED + --add-exports io.clientcore.core/io.clientcore.core.implementation.http.serializer=ALL-UNNAMED + --add-exports io.clientcore.core/io.clientcore.core.implementation.utils=ALL-UNNAMED + + --add-opens io.clientcore.http.okhttp3/io.clientcore.http.okhttp3=ALL-UNNAMED + + + + + + io.clientcore + core + 1.0.0-beta.7 + + + io.clientcore + http-okhttp3 + 1.0.0-beta.2 + + + + + io.clientcore + core + 1.0.0-beta.7 + test-jar + test + + + org.eclipse.jetty + jetty-server + 9.4.56.v20240826 + test + + + org.eclipse.jetty + jetty-servlet + 9.4.56.v20240826 + test + + + org.junit.jupiter + junit-jupiter-api + 5.11.2 + test + + + org.junit.jupiter + junit-jupiter-engine + 5.11.2 + test + + + org.junit.jupiter + junit-jupiter-params + 5.11.2 + test + + + + + + + ${project.build.directory}/generated-sources + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.13.0 + + + run-annotation-processing + generate-sources + + compile + + + + 11 + only + ${project.build.directory}/generated-sources/ + + + io.clientcore + annotation-processor + 1.0.0-beta.1 + + + + io.clientcore.annotation.processor.AnnotationProcessor + + + + -Xlint:-options + + + + + + + + io.clientcore + annotation-processor + 1.0.0-beta.1 + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.6.0 + + + add-generated-sources + generate-sources + + add-source + + + + ${basedir}/target/generated-sources + + + + + + + + diff --git a/sdk/clientcore/annotation-processor-test/src/main/java/io/clientcore/annotation/processor/test/MockHttpResponse.java b/sdk/clientcore/annotation-processor-test/src/main/java/io/clientcore/annotation/processor/test/MockHttpResponse.java new file mode 100644 index 000000000000..40a4368a6ee2 --- /dev/null +++ b/sdk/clientcore/annotation-processor-test/src/main/java/io/clientcore/annotation/processor/test/MockHttpResponse.java @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.annotation.processor.test; + +import io.clientcore.core.http.models.HttpHeaders; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.models.binarydata.BinaryData; + +/** + * A mock implementation of {@link Response} that can be used for testing. + */ +public class MockHttpResponse extends Response { + + /** + * Creates an HTTP response associated with a {@code request}, returns the {@code statusCode}, and has an empty + * response body. + * + * @param request HttpRequest associated with the response. + * @param statusCode Status code of the response. + */ + public MockHttpResponse(HttpRequest request, int statusCode) { + this(request, statusCode, BinaryData.empty()); + } + + /** + * Creates an HTTP response associated with a {@code request}, returns the {@code statusCode}, and response body of + * {@code bodyBytes}. + * + * @param request HttpRequest associated with the response. + * @param statusCode Status code of the response. + * @param body Contents of the response. + */ + public MockHttpResponse(HttpRequest request, int statusCode, BinaryData body) { + this(request, statusCode, new HttpHeaders(), body); + } + + /** + * Creates an HTTP response associated with a {@code request}, returns the {@code statusCode}, contains the + * {@code headers}, and response body of {@code bodyBytes}. + * + * @param request HttpRequest associated with the response. + * @param statusCode Status code of the response. + * @param headers HttpHeaders of the response. + * @param body Contents of the response. + */ + public MockHttpResponse(HttpRequest request, int statusCode, HttpHeaders headers, BinaryData body) { + super(request, statusCode, headers, body); + } + +} diff --git a/sdk/clientcore/annotation-processor-test/src/main/java/io/clientcore/annotation/processor/test/TestInterfaceServiceVersion.java b/sdk/clientcore/annotation-processor-test/src/main/java/io/clientcore/annotation/processor/test/TestInterfaceServiceVersion.java new file mode 100644 index 000000000000..cde597ef50e2 --- /dev/null +++ b/sdk/clientcore/annotation-processor-test/src/main/java/io/clientcore/annotation/processor/test/TestInterfaceServiceVersion.java @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.annotation.processor.test; + +import io.clientcore.core.http.models.ServiceVersion; + +/** + * Service version of OpenAIClient. + */ +public enum TestInterfaceServiceVersion implements ServiceVersion { + /** + * Enum value 2022-12-01. + */ + V_TEST_VALUE("test-value"); + + private final String version; + + TestInterfaceServiceVersion(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 TestInterfaceServiceVersion}. + */ + public static TestInterfaceServiceVersion getLatest() { + return V_TEST_VALUE; + } +} diff --git a/sdk/clientcore/annotation-processor-test/src/main/java/io/clientcore/annotation/processor/test/implementation/TestInterfaceClientImpl.java b/sdk/clientcore/annotation-processor-test/src/main/java/io/clientcore/annotation/processor/test/implementation/TestInterfaceClientImpl.java new file mode 100644 index 000000000000..30684a4915f2 --- /dev/null +++ b/sdk/clientcore/annotation-processor-test/src/main/java/io/clientcore/annotation/processor/test/implementation/TestInterfaceClientImpl.java @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.annotation.processor.test.implementation; + +import io.clientcore.annotation.processor.test.implementation.models.Foo; +import io.clientcore.annotation.processor.test.implementation.models.FooListResult; +import io.clientcore.annotation.processor.test.implementation.models.HttpBinJSON; +import io.clientcore.core.annotations.ServiceInterface; +import io.clientcore.core.http.annotations.BodyParam; +import io.clientcore.core.http.annotations.HeaderParam; +import io.clientcore.core.http.annotations.HostParam; +import io.clientcore.core.http.annotations.HttpRequestInformation; +import io.clientcore.core.http.annotations.PathParam; +import io.clientcore.core.http.annotations.QueryParam; +import io.clientcore.core.http.annotations.UnexpectedResponseExceptionDetail; +import io.clientcore.core.http.models.HttpMethod; +import io.clientcore.core.http.models.RequestOptions; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.http.pipeline.HttpPipeline; +import io.clientcore.core.implementation.http.ContentType; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.serialization.ObjectSerializer; +import java.io.InputStream; +import java.lang.reflect.InvocationTargetException; +import java.nio.ByteBuffer; +import java.util.List; + +/** + * Initializes a new instance of the TestInterfaceClient type. + */ +public final class TestInterfaceClientImpl { + + @ServiceInterface(name = "myService") + public interface TestInterfaceClientService { + static TestInterfaceClientService getNewInstance(HttpPipeline pipeline, ObjectSerializer serializer) { + if (pipeline == null) { + throw new IllegalArgumentException("pipeline cannot be null"); + } + try { + Class clazz = Class.forName("io.clientcore.annotation.processor.test.implementation.TestInterfaceClientServiceImpl"); + return (TestInterfaceClientService) clazz + .getMethod("getNewInstance", HttpPipeline.class, ObjectSerializer.class) + .invoke(null, pipeline, serializer); + } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException + | InvocationTargetException e) { + throw new RuntimeException(e); + } + } + + @HttpRequestInformation(method = HttpMethod.POST, path = "my/uri/path", expectedStatusCodes = { 200 }) + Response testMethod(@BodyParam("application/octet-stream") ByteBuffer request, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Content-Length") Long contentLength); + + @HttpRequestInformation(method = HttpMethod.POST, path = "my/uri/path", expectedStatusCodes = { 200 }) + Response testMethod(@BodyParam("application/octet-stream") BinaryData data, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Content-Length") Long contentLength); + + @HttpRequestInformation(method = HttpMethod.GET, path = "{nextLink}", expectedStatusCodes = { 200 }) + Response testListNext(@PathParam(value = "nextLink", encoded = true) String nextLink); + + @HttpRequestInformation(method = HttpMethod.GET, path = "my/uri/path", expectedStatusCodes = { 200 }) + Void testMethodReturnsVoid(); + + @HttpRequestInformation(method = HttpMethod.HEAD, path = "my/uri/path", expectedStatusCodes = { 200 }) + void testHeadMethod(); + + + @HttpRequestInformation(method = HttpMethod.HEAD, path = "my/uri/path", expectedStatusCodes = { 200, 207 }) + boolean testBooleanHeadMethod(); + + @HttpRequestInformation(method = HttpMethod.GET, path = "my/uri/path", expectedStatusCodes = { 200 }) + Response testMethodReturnsResponseVoid(); + + @HttpRequestInformation(method = HttpMethod.GET, path = "my/uri/path", expectedStatusCodes = { 200 }) + Response testDownload(); + + @HttpRequestInformation(method = HttpMethod.GET, path = "/kv/{key}", expectedStatusCodes = { 200 }) + @UnexpectedResponseExceptionDetail(exceptionBodyClass = Error.class) + Response getFoo(@PathParam("key") String key, @QueryParam("label") String label, + @HeaderParam("Sync-Token") String syncToken); + + @HttpRequestInformation(method = HttpMethod.DELETE, path = "/kv/{key}", expectedStatusCodes = { 204, 404 }) + Response deleteFoo(@PathParam("key") String key, @QueryParam("label") String label, + @HeaderParam("Sync-Token") String syncToken); + + + @HttpRequestInformation(method = HttpMethod.GET, path = "foos", expectedStatusCodes = { 200 }) + Response listFooListResult(@HostParam("uri") String uri, RequestOptions requestOptions); + + @HttpRequestInformation(method = HttpMethod.GET, path = "{nextLink}", expectedStatusCodes = { 200 }) + Response listNextFooListResult(@PathParam(value = "nextLink", encoded = true) String nextLink, + RequestOptions requestOptions); + + @HttpRequestInformation(method = HttpMethod.GET, path = "foos", expectedStatusCodes = { 200 }) + Response> listFoo(@HostParam("uri") String uri, @QueryParam(value = "tags", multipleQueryParams = true) List tags, RequestOptions requestOptions); + + @HttpRequestInformation(method = HttpMethod.GET, path = "{nextLink}", expectedStatusCodes = { 200 }) + Response> listNextFoo(@PathParam(value = "nextLink", encoded = true) String nextLink, + RequestOptions requestOptions); + // HttpClientTests + // Need to add RequestOptions to specify ResponseBodyMode, which is otherwise provided by convenience methods + @SuppressWarnings({ "unchecked", "cast" }) + @HttpRequestInformation(method = HttpMethod.PUT, path = "put", expectedStatusCodes = {200}) + default HttpBinJSON putConvenience(String uri, int putBody, RequestOptions options) { + return putResponse(uri, putBody, options).getValue(); + } + + @HttpRequestInformation(method = HttpMethod.PUT, path = "put", expectedStatusCodes = { 200 }) + Response putResponse(@HostParam("uri") String uri, + @BodyParam(ContentType.APPLICATION_OCTET_STREAM) int putBody, RequestOptions options); + + @HttpRequestInformation(method = HttpMethod.POST, path = "stream", expectedStatusCodes = { 200 }) + default HttpBinJSON postStreamConvenience(@HostParam("uri") String uri, + @BodyParam(ContentType.APPLICATION_OCTET_STREAM) int putBody, RequestOptions options) { + return postStreamResponse(uri, putBody, options).getValue(); + } + + @HttpRequestInformation(method = HttpMethod.POST, path = "stream", expectedStatusCodes = { 200 }) + Response postStreamResponse(@HostParam("uri") String uri, + @BodyParam(ContentType.APPLICATION_OCTET_STREAM) int putBody, RequestOptions options); + + // Service 1 + @HttpRequestInformation(method = HttpMethod.GET, path = "bytes/100", expectedStatusCodes = {200}) + byte[] getByteArray(@HostParam("uri") String uri); + + // Service 2 + @HttpRequestInformation(method = HttpMethod.GET, path = "bytes/{numberOfBytes}", expectedStatusCodes = { 200 }) + byte[] getByteArray(@HostParam("scheme") String scheme, @HostParam("hostName") String hostName, + @PathParam("numberOfBytes") int numberOfBytes); + + // Service 3 + @HttpRequestInformation(method = HttpMethod.GET, path = "bytes/100", expectedStatusCodes = { 200 }) + void getNothing(@HostParam("uri") String uri); + } +} diff --git a/sdk/clientcore/annotation-processor-test/src/main/java/io/clientcore/annotation/processor/test/implementation/models/Foo.java b/sdk/clientcore/annotation-processor-test/src/main/java/io/clientcore/annotation/processor/test/implementation/models/Foo.java new file mode 100644 index 000000000000..16f87fb7c865 --- /dev/null +++ b/sdk/clientcore/annotation-processor-test/src/main/java/io/clientcore/annotation/processor/test/implementation/models/Foo.java @@ -0,0 +1,131 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.annotation.processor.test.implementation.models; + +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonSerializable; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.serialization.json.JsonWriter; + +import java.io.IOException; +import java.util.List; +import java.util.Map; + +/** + * Class for testing serialization. + */ +public class Foo implements JsonSerializable { + private String bar; + private List baz; + private Map qux; + private String moreProps; + private Integer empty; + private Map additionalProperties; + + public String bar() { + return bar; + } + + public void bar(String bar) { + this.bar = bar; + } + + public List baz() { + return baz; + } + + public void baz(List baz) { + this.baz = baz; + } + + public Map qux() { + return qux; + } + + public void qux(Map qux) { + this.qux = qux; + } + + public String moreProps() { + return moreProps; + } + + public void moreProps(String moreProps) { + this.moreProps = moreProps; + } + + public Integer empty() { + return empty; + } + + public void empty(Integer empty) { + this.empty = empty; + } + + public Map additionalProperties() { + return additionalProperties; + } + + public void additionalProperties(Map additionalProperties) { + this.additionalProperties = additionalProperties; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + + jsonWriter.writeStringField("bar", bar); + + if (baz != null) { + jsonWriter.writeArrayField("baz", baz, JsonWriter::writeString); + } + + if (qux != null) { + jsonWriter.writeMapField("qux", qux, JsonWriter::writeString); + } + + jsonWriter.writeStringField("moreProps", moreProps); + + if (empty != null) { + jsonWriter.writeIntField("empty", empty); + } + + if (additionalProperties != null) { + jsonWriter.writeMapField("additionalProperties", additionalProperties, JsonWriter::writeUntyped); + } + + jsonWriter.writeEndObject(); + + return jsonWriter; + } + + public static Foo fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Foo foo = new Foo(); + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("bar".equals(fieldName)) { + foo.bar(reader.getString()); + } else if ("baz".equals(fieldName)) { + foo.baz(reader.readArray(JsonReader::getString)); + } else if ("qux".equals(fieldName)) { + foo.qux(reader.readMap(JsonReader::getString)); + } else if ("moreProps".equals(fieldName)) { + foo.moreProps(reader.getString()); + } else if ("empty".equals(fieldName)) { + foo.empty(reader.getInt()); + } else if ("additionalProperties".equals(fieldName)) { + foo.additionalProperties(reader.readMap(JsonReader::readUntyped)); + } else { + reader.skipChildren(); + } + } + + return foo; + }); + } +} diff --git a/sdk/clientcore/annotation-processor-test/src/main/java/io/clientcore/annotation/processor/test/implementation/models/FooListResult.java b/sdk/clientcore/annotation-processor-test/src/main/java/io/clientcore/annotation/processor/test/implementation/models/FooListResult.java new file mode 100644 index 000000000000..466afb271839 --- /dev/null +++ b/sdk/clientcore/annotation-processor-test/src/main/java/io/clientcore/annotation/processor/test/implementation/models/FooListResult.java @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.annotation.processor.test.implementation.models; + +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonSerializable; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.serialization.json.JsonWriter; + +import java.io.IOException; +import java.util.List; + +/** + * The result of a list request. + */ +public final class FooListResult implements JsonSerializable { + /* + * The collection value. + */ + private List items; + + /* + * The URI that can be used to request the next set of paged results. + */ + private String nextLink; + + /** + * Creates an instance of FooListResult class. + */ + public FooListResult() { + } + + /** + * Get the items property: The collection value. + * + * @return the items value. + */ + public List getItems() { + return this.items; + } + + /** + * Set the items property: The collection value. + * + * @param items the items value to set. + * @return the FooListResult object itself. + */ + public FooListResult setItems(List items) { + this.items = items; + return this; + } + + /** + * Get the nextLink property: The URI that can be used to request the next set of paged results. + * + * @return the nextLink value. + */ + public String getNextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The URI that can be used to request the next set of paged results. + * + * @param nextLink the nextLink value to set. + * @return the FooListResult object itself. + */ + public FooListResult setNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("items", this.items, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("@nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of FooListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of FooListResult 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 FooListResult. + */ + public static FooListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + FooListResult deserializedFooListResult = new FooListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("items".equals(fieldName)) { + List items = reader.readArray(reader1 -> Foo.fromJson(reader1)); + deserializedFooListResult.items = items; + } else if ("@nextLink".equals(fieldName)) { + deserializedFooListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedFooListResult; + }); + } +} diff --git a/sdk/clientcore/annotation-processor-test/src/main/java/io/clientcore/annotation/processor/test/implementation/models/HttpBinJSON.java b/sdk/clientcore/annotation-processor-test/src/main/java/io/clientcore/annotation/processor/test/implementation/models/HttpBinJSON.java new file mode 100644 index 000000000000..0350cb81ab9f --- /dev/null +++ b/sdk/clientcore/annotation-processor-test/src/main/java/io/clientcore/annotation/processor/test/implementation/models/HttpBinJSON.java @@ -0,0 +1,179 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.annotation.processor.test.implementation.models; + +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonSerializable; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.serialization.json.JsonWriter; + +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + * Maps to the JSON return values from http://httpbin.org. + */ +public class HttpBinJSON implements JsonSerializable { + private String uri; + private Map> headers; + private Object data; + private Map> queryParams; + + /** + * Gets the URI associated with this request. + * + * @return he URI associated with the request. + */ + public String uri() { + return uri; + } + + /** + * Sets the URI associated with this request. + * + * @param uri The URI associated with the request. + */ + public HttpBinJSON uri(String uri) { + this.uri = uri; + + return this; + } + + /** + * Gets the response headers. + * + * @return The response headers. + */ + public Map> headers() { + return headers; + } + + /** + * Sets the response headers. + * + * @param headers The response headers. + */ + public HttpBinJSON headers(Map> headers) { + this.headers = headers; + + return this; + } + + /** + * Gets the response body. + * + * @return The response body. + */ + public Object data() { + return data; + } + + /** + * Sets the response body. + * + * @param data The response body. + */ + public HttpBinJSON data(Object data) { + this.data = data; + + return this; + } + + /** + * Gets the response headers. + * + * @return The response headers. + */ + public Map> queryParams() { + return queryParams; + } + + /** + * Sets the response headers. + * + * @param queryParams The response headers. + */ + public HttpBinJSON queryParams(Map> queryParams) { + this.queryParams = queryParams; + + return this; + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + + if (other == null || getClass() != other.getClass()) { + return false; + } + + HttpBinJSON binJson = (HttpBinJSON) other; + + return Objects.equals(uri, binJson.uri) && Objects.equals(headers, ((HttpBinJSON) other).headers); + } + + @Override + public int hashCode() { + return Objects.hash(uri, headers); + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("uri", uri); + jsonWriter.writeMapField("headers", headers, + (headerWriter, headerList) -> headerWriter.writeArray(headerList, JsonWriter::writeString)); + jsonWriter.writeUntypedField("data", data); + jsonWriter.writeMapField("queryParams", queryParams, + (paramWriter, paramList) -> paramWriter.writeArray(paramList, JsonWriter::writeString)); + + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of HttpBinJSON from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of HttpBinJSON 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 HttpBinJSON. + * @throws IllegalStateException If any of the required properties to create HttpBinJSON aren't found. + */ + public static HttpBinJSON fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + HttpBinJSON httpBinJSON = new HttpBinJSON(); + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + // Example of case-insensitive names and where serialization named don't match field names. + if ("uri".equalsIgnoreCase(fieldName)) { + httpBinJSON.uri = reader.getString(); + } else if ("headers".equalsIgnoreCase(fieldName)) { + // Pass the JsonReader to another JsonSerializable to read the inner object. + httpBinJSON.headers = reader.readMap(headerReader -> headerReader.readArray(JsonReader::getString)); + } else if ("data".equalsIgnoreCase(fieldName)) { + httpBinJSON.data = reader.readUntyped(); + } else if ("queryParams".equalsIgnoreCase(fieldName)) { + // Pass the JsonReader to another JsonSerializable to read the inner object. + httpBinJSON.queryParams + = reader.readMap(paramReader -> paramReader.readArray(JsonReader::getString)); + } else { + reader.skipChildren(); + } + } + + return httpBinJSON; + }); + } + + public String getHeaderValue(String name) { + return headers == null ? null : headers.containsKey(name) ? headers.get(name).get(0) : null; + } +} diff --git a/sdk/clientcore/annotation-processor-test/src/main/java/io/clientcore/annotation/processor/test/implementation/package-info.java b/sdk/clientcore/annotation-processor-test/src/main/java/io/clientcore/annotation/processor/test/implementation/package-info.java new file mode 100644 index 000000000000..401b9baf6796 --- /dev/null +++ b/sdk/clientcore/annotation-processor-test/src/main/java/io/clientcore/annotation/processor/test/implementation/package-info.java @@ -0,0 +1,4 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.annotation.processor.test.implementation; diff --git a/sdk/clientcore/annotation-processor-test/src/main/java/io/clientcore/annotation/processor/test/package-info.java b/sdk/clientcore/annotation-processor-test/src/main/java/io/clientcore/annotation/processor/test/package-info.java new file mode 100644 index 000000000000..0fdd68e56f53 --- /dev/null +++ b/sdk/clientcore/annotation-processor-test/src/main/java/io/clientcore/annotation/processor/test/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing the implementation of the code generation. + */ +package io.clientcore.annotation.processor.test; diff --git a/sdk/clientcore/annotation-processor-test/src/main/java/module-info.java b/sdk/clientcore/annotation-processor-test/src/main/java/module-info.java new file mode 100644 index 000000000000..2c305c5bd83a --- /dev/null +++ b/sdk/clientcore/annotation-processor-test/src/main/java/module-info.java @@ -0,0 +1,7 @@ +module annotation.processor.test { + requires transitive io.clientcore.core; + requires io.clientcore.http.okhttp3; + + // TODO: refactor Foo class to implement JsonSerializable + exports io.clientcore.annotation.processor.test.implementation.models to io.clientcore.core; +} diff --git a/sdk/clientcore/annotation-processor-test/src/test/java/io/clientcore/annotation/processor/test/LocalHttpClient.java b/sdk/clientcore/annotation-processor-test/src/test/java/io/clientcore/annotation/processor/test/LocalHttpClient.java new file mode 100644 index 000000000000..ce0c00ea7059 --- /dev/null +++ b/sdk/clientcore/annotation-processor-test/src/test/java/io/clientcore/annotation/processor/test/LocalHttpClient.java @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.annotation.processor.test; + +import io.clientcore.core.http.client.HttpClient; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpHeaders; +import io.clientcore.core.http.models.HttpMethod; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.models.binarydata.BinaryData; + +import java.io.IOException; + +/** + * A mock implementation of {@link HttpClient} that allows for testing the {@link HttpRequest} sent to it. + */ +public final class LocalHttpClient implements HttpClient { + private volatile HttpRequest lastHttpRequest; + volatile boolean closeCalledOnResponse; + + @Override + public Response send(HttpRequest request) { + lastHttpRequest = request; + boolean success = request.getUri().getPath().equals("/my/uri/path"); + + if (request.getHttpMethod().equals(HttpMethod.POST)) { + success &= "application/json".equals(request.getHeaders().getValue(HttpHeaderName.CONTENT_TYPE)); + } else { + success &= request.getHttpMethod().equals(HttpMethod.GET) + || request.getHttpMethod().equals(HttpMethod.HEAD); + } + + return new Response(request, success ? 200 : 400, new HttpHeaders(), BinaryData.empty()) { + @Override + public void close() throws IOException { + closeCalledOnResponse = true; + + super.close(); + } + }; + } + + public HttpRequest getLastHttpRequest() { + return lastHttpRequest; + } +} diff --git a/sdk/clientcore/annotation-processor-test/src/test/java/io/clientcore/annotation/processor/test/PagingOperationTests.java b/sdk/clientcore/annotation-processor-test/src/test/java/io/clientcore/annotation/processor/test/PagingOperationTests.java new file mode 100644 index 000000000000..1fe3498c3d16 --- /dev/null +++ b/sdk/clientcore/annotation-processor-test/src/test/java/io/clientcore/annotation/processor/test/PagingOperationTests.java @@ -0,0 +1,164 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.annotation.processor.test; + +import io.clientcore.annotation.processor.test.implementation.TestInterfaceClientImpl.TestInterfaceClientService; +import io.clientcore.annotation.processor.test.implementation.models.Foo; +import io.clientcore.annotation.processor.test.implementation.models.FooListResult; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpHeaders; +import io.clientcore.core.http.models.HttpMethod; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.RequestOptions; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.http.models.ResponseBodyMode; +import io.clientcore.core.http.paging.PagedIterable; +import io.clientcore.core.http.paging.PagedResponse; +import io.clientcore.core.http.pipeline.HttpPipeline; +import io.clientcore.core.http.pipeline.HttpPipelineBuilder; +import io.clientcore.core.models.binarydata.BinaryData; +import org.junit.jupiter.api.Test; + +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * Test class for verifying the deserialization of paged responses and their handling in code generation. + */ +public class PagingOperationTests { + private static final BinaryData FIRST_PAGE_RESPONSE = BinaryData.fromString("[{\"bar\":\"hello.world\",\"baz\":[\"hello\",\"hello.world\"],\"qux\":{\"a.b\":\"c.d\",\"bar.a\":\"ttyy\",\"bar.b\":\"uuzz\",\"hello\":\"world\"}}]"); + private static final BinaryData NEXTLINK_RESPONSE = BinaryData.fromString("[{\"bar\":\"hello.world2\",\"additionalProperties\":{\"bar\":\"baz\",\"a.b\":\"c.d\",\"properties.bar\":\"barbar\"}}]"); + + /** + * Verifies that a response containing a List is correctly handled when returning a List. + */ + @Test + public void testListFoo() { + String uri = "https://example.com"; + String firstPageUri = uri + "/foos"; + String nextLinkUri = uri + "/foos?page=2"; + RequestOptions requestOptions = new RequestOptions().setResponseBodyMode(ResponseBodyMode.DESERIALIZE); + HttpPipeline pipeline = new HttpPipelineBuilder() + .httpClient(request -> { + String requestUri = request.getUri().toString(); + request.setRequestOptions(requestOptions); + if (firstPageUri.equals(requestUri)) { + return createMockResponse(request, FIRST_PAGE_RESPONSE, nextLinkUri); + } else if (nextLinkUri.equals(requestUri)) { + return createMockResponse(request, NEXTLINK_RESPONSE, null); + } + + return new MockHttpResponse(request, 404); + }) + .build(); + TestInterfaceClientService testInterface = TestInterfaceClientService.getNewInstance(pipeline, null); + + // Retrieve initial response + Response> initialResponse = testInterface.listFoo(uri, null, RequestOptions.none()); + + List fooFirstPageResponse = initialResponse.getValue(); + assertNotNull(fooFirstPageResponse); + assertNotNull(fooFirstPageResponse.get(0).bar()); + + // Convert List response to PagedResponse + PagedResponse firstPage = toPagedResponse(initialResponse, null); + + PagedIterable pagedIterable = new PagedIterable<>( + pagingOptions -> firstPage, // First page + (pagingOptions, nextLink) -> { + Response> nextResponse = testInterface.listNextFoo(nextLink, RequestOptions.none()); + return toPagedResponse(nextResponse, nextLink); + } + ); + + assertNotNull(pagedIterable); + Set allItems = pagedIterable.stream().collect(Collectors.toSet()); + assertEquals(1, allItems.size()); + } + + @Test + public void testListFooListResult() { + String uri = "https://example.com"; + String firstPageUri = uri + "/foos"; + String nextLinkUri = uri + "/foos?page=2"; + RequestOptions requestOptions = new RequestOptions().setResponseBodyMode(ResponseBodyMode.DESERIALIZE); + HttpPipeline pipeline = new HttpPipelineBuilder() + .httpClient(request -> { + String requestUri = request.getUri().toString(); + request.setRequestOptions(requestOptions); + if (firstPageUri.equals(requestUri)) { + return createMockResponse(request, BinaryData.fromString( + "{\"items\":[{\"bar\":\"hello.world\",\"baz\":[\"hello\",\"hello.world\"],\"qux\":{\"a" + + ".b\":\"c.d\"," + + "\"bar.a\":\"ttyy\",\"bar.b\":\"uuzz\",\"hello\":\"world\"}}], \"nextLink\":\"" + nextLinkUri + "\"}"), + nextLinkUri); + } else if (nextLinkUri.equals(requestUri)) { + return createMockResponse(request, BinaryData.fromString( + "{\"items\":[{\"bar\":\"hello.world2\",\"additionalProperties\":{\"bar\":\"baz\",\"a" + + ".b\":\"c.d\",\"properties.bar\":\"barbar\"}}]"), + null); + } + return new MockHttpResponse(request, 404); + }) + .build(); + + TestInterfaceClientService testInterface = TestInterfaceClientService.getNewInstance(pipeline, null); + + // Fetch the first page + PagedIterable pagedIterable = new PagedIterable<>( + pagingOptions -> toPagedResponse(testInterface.listFooListResult(uri, RequestOptions.none()), nextLinkUri), + (pagingOptions, nextLink) -> toPagedResponse(testInterface.listNextFooListResult(nextLink, RequestOptions.none()), null) + ); + + assertNotNull(pagedIterable); + Set allItems = pagedIterable.stream().collect(Collectors.toSet()); + assertEquals(1, allItems.size()); + } + + /** + * Creates a mock HTTP response with JSON body and optional nextLink header. + */ + private MockHttpResponse createMockResponse(HttpRequest request, BinaryData jsonBody, String nextLink) { + HttpHeaders headers = new HttpHeaders(); + if (nextLink != null) { + headers.set(HttpHeaderName.fromString("nextLink"), nextLink); + } + + return new MockHttpResponse(request, 200, headers, jsonBody); + } + + /** + * Converts a Response to a PagedResponse. + * Supports both Response and Response>. + */ + @SuppressWarnings({ "unchecked", "cast" }) + private PagedResponse toPagedResponse(Response response, String nextLink) { + if (response == null || response.getValue() == null) { + return new PagedResponse<>( + response != null ? response.getRequest() : new HttpRequest().setMethod(HttpMethod.GET).setUri("https://example.com"), + 200, + response != null ? response.getHeaders() : new HttpHeaders(), + Collections.emptyList() // Return an empty list when null + ); + } + + List items; + if (response.getValue() instanceof FooListResult) { + items = ((FooListResult) response.getValue()).getItems(); // Extract list from FooListResult + nextLink = ((FooListResult) response.getValue()).getNextLink(); + } else if (response.getValue() instanceof List) { + items = (List) response.getValue(); // Directly use the List + } else { + throw new IllegalArgumentException("Unsupported response type: " + response.getValue().getClass().getName()); + } + + return new PagedResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), items, + nextLink, null, null, null, null); + } +} diff --git a/sdk/clientcore/annotation-processor-test/src/test/java/io/clientcore/annotation/processor/test/RestProxyTests.java b/sdk/clientcore/annotation-processor-test/src/test/java/io/clientcore/annotation/processor/test/RestProxyTests.java new file mode 100644 index 000000000000..d135be662257 --- /dev/null +++ b/sdk/clientcore/annotation-processor-test/src/test/java/io/clientcore/annotation/processor/test/RestProxyTests.java @@ -0,0 +1,162 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.annotation.processor.test; + +import io.clientcore.annotation.processor.test.implementation.TestInterfaceClientImpl; +import io.clientcore.core.http.client.HttpClient; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.http.pipeline.HttpPipeline; +import io.clientcore.core.http.pipeline.HttpPipelineBuilder; +import io.clientcore.core.implementation.http.ContentType; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.serialization.json.JsonSerializer; +import org.junit.jupiter.api.Named; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Tests for RestProxy functionality using code generated by the annotation processor. + */ +public class RestProxyTests { + + @Test + public void contentTypeHeaderPriorityOverBodyParamAnnotationTest() throws IOException { + HttpClient client = new LocalHttpClient(); + HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(client).build(); + + TestInterfaceClientImpl.TestInterfaceClientService testInterface = + TestInterfaceClientImpl.TestInterfaceClientService.getNewInstance(pipeline, + new JsonSerializer()); + byte[] bytes = "hello".getBytes(); + try (Response response + = testInterface.testMethod(ByteBuffer.wrap(bytes), "application/json", (long) bytes.length)) { + assertEquals(200, response.getStatusCode()); + } + } + + // TODO (vcolin7): Re-enable this test if we ever compose HttpResponse into a stream Response type. + /*@Test + public void streamResponseShouldHaveHttpResponseReference() { + LocalHttpClient client = new LocalHttpClient(); + HttpPipeline pipeline = new HttpPipelineBuilder() + .httpClient(client) + .build(); + TestInterfaceClientImpl.TestInterfaceClientService testInterface = + TestInterfaceClientImpl.TestInterfaceClientService.getNewInstance(pipeline, new JsonSerializer()); + StreamResponse streamResponse = testInterface.testDownload(); + + streamResponse.close(); + + // This indirectly tests that StreamResponse has HttpResponse reference. + assertTrue(client.closeCalledOnResponse); + }*/ + + @ParameterizedTest + @MethodSource("knownLengthBinaryDataIsPassthroughArgumentProvider") + public void knownLengthBinaryDataIsPassthrough(BinaryData data, long contentLength) { + LocalHttpClient client = new LocalHttpClient(); + HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(client).build(); + + TestInterfaceClientImpl.TestInterfaceClientService testInterface = + TestInterfaceClientImpl.TestInterfaceClientService.getNewInstance(pipeline, new JsonSerializer()); + Response response = testInterface.testMethod(data, "application/json", contentLength); + + assertEquals(200, response.getStatusCode()); + assertSame(data, client.getLastHttpRequest().getBody()); + } + + private static Stream knownLengthBinaryDataIsPassthroughArgumentProvider() throws Exception { + String string = "hello"; + byte[] bytes = string.getBytes(); + Path file = Files.createTempFile("knownLengthBinaryDataIsPassthroughArgumentProvider", null); + + file.toFile().deleteOnExit(); + + Files.write(file, bytes); + + return Stream.of(Arguments.of(Named.of("bytes", BinaryData.fromBytes(bytes)), bytes.length), + Arguments.of(Named.of("string", BinaryData.fromString(string)), bytes.length), + Arguments.of(Named.of("file", BinaryData.fromFile(file)), bytes.length), Arguments + .of(Named.of("serializable", BinaryData.fromObject(bytes)), BinaryData.fromObject(bytes).getLength())); + } + + @ParameterizedTest + @MethodSource("doesNotChangeBinaryDataContentTypeDataProvider") + public void doesNotChangeBinaryDataContentType(BinaryData data, long contentLength) { + LocalHttpClient client = new LocalHttpClient(); + HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(client).build(); + Class expectedContentClazz = data.getClass(); + + TestInterfaceClientImpl.TestInterfaceClientService testInterface = + TestInterfaceClientImpl.TestInterfaceClientService.getNewInstance(pipeline, new JsonSerializer()); + Response response = testInterface.testMethod(data, ContentType.APPLICATION_JSON, contentLength); + + assertEquals(200, response.getStatusCode()); + + Class actualContentClazz = client.getLastHttpRequest().getBody().getClass(); + + assertEquals(expectedContentClazz, actualContentClazz); + } + + @Test + public void voidReturningApiClosesResponse() { + LocalHttpClient client = new LocalHttpClient(); + HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(client).build(); + + TestInterfaceClientImpl.TestInterfaceClientService testInterface = + TestInterfaceClientImpl.TestInterfaceClientService.getNewInstance(pipeline, new JsonSerializer()); + + testInterface.testMethodReturnsVoid(); + + assertTrue(client.closeCalledOnResponse); + } + + private static Stream doesNotChangeBinaryDataContentTypeDataProvider() throws Exception { + String string = "hello"; + byte[] bytes = string.getBytes(); + Path file = Files.createTempFile("doesNotChangeBinaryDataContentTypeDataProvider", null); + + file.toFile().deleteOnExit(); + + Files.write(file, bytes); + ByteArrayInputStream stream = new ByteArrayInputStream(bytes); + + return Stream.of(Arguments.of(Named.of("bytes", BinaryData.fromBytes(bytes)), bytes.length), + Arguments.of(Named.of("string", BinaryData.fromString(string)), bytes.length), + Arguments.of(Named.of("file", BinaryData.fromFile(file)), bytes.length), + Arguments.of(Named.of("stream", BinaryData.fromStream(stream, (long) bytes.length)), bytes.length), + Arguments.of(Named.of("serializable", BinaryData.fromObject(bytes)), + BinaryData.fromObject(bytes).getLength())); + } + + + @Test + public void doesNotChangeEncodedPath() throws IOException { + String nextLinkUri + = "https://management.somecloud.com:443/subscriptions/000/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss1/virtualMachines?api-version=2021-11-01&$skiptoken=Mzk4YzFjMzMtM2IwMC00OWViLWI2NGYtNjg4ZTRmZGQ1Nzc2IS9TdWJzY3JpcHRpb25zL2VjMGFhNWY3LTllNzgtNDBjOS04NWNkLTUzNWM2MzA1YjM4MC9SZXNvdXJjZUdyb3Vwcy9SRy1XRUlEWFUtVk1TUy9WTVNjYWxlU2V0cy9WTVNTMS9WTXMvNzc="; + HttpPipeline pipeline = new HttpPipelineBuilder().httpClient((request) -> { + assertEquals(nextLinkUri, request.getUri().toString()); + + return new MockHttpResponse(null, 200); + }).build(); + + TestInterfaceClientImpl.TestInterfaceClientService testInterface = + TestInterfaceClientImpl.TestInterfaceClientService.getNewInstance(pipeline, new JsonSerializer()); + + testInterface.testListNext(nextLinkUri).close(); + } +} diff --git a/sdk/clientcore/annotation-processor-test/src/test/java/io/clientcore/annotation/processor/test/TestInterfaceGenerationTests.java b/sdk/clientcore/annotation-processor-test/src/test/java/io/clientcore/annotation/processor/test/TestInterfaceGenerationTests.java new file mode 100644 index 000000000000..f022d2e74747 --- /dev/null +++ b/sdk/clientcore/annotation-processor-test/src/test/java/io/clientcore/annotation/processor/test/TestInterfaceGenerationTests.java @@ -0,0 +1,222 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.annotation.processor.test; + +import io.clientcore.annotation.processor.test.implementation.TestInterfaceClientImpl; +import io.clientcore.annotation.processor.test.implementation.models.Foo; +import io.clientcore.annotation.processor.test.implementation.models.HttpBinJSON; +import io.clientcore.core.http.client.HttpClient; +import io.clientcore.core.http.models.RequestOptions; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.http.models.ResponseBodyMode; +import io.clientcore.core.http.pipeline.HttpPipeline; +import io.clientcore.core.http.pipeline.HttpPipelineBuilder; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.shared.HttpClientTestsServer; +import io.clientcore.core.shared.LocalTestServer; +import io.clientcore.http.okhttp3.OkHttpHttpClientProvider; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +import static io.clientcore.core.http.models.ResponseBodyMode.BUFFER; +import static io.clientcore.core.http.models.ResponseBodyMode.DESERIALIZE; +import static io.clientcore.core.http.models.ResponseBodyMode.IGNORE; +import static io.clientcore.core.http.models.ResponseBodyMode.STREAM; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +public class TestInterfaceGenerationTests { + private static LocalTestServer server; + @BeforeAll + public static void startTestServer() { + server = HttpClientTestsServer.getHttpClientTestsServer(); + + server.start(); + } + + @AfterAll + public static void stopTestServer() { + if (server != null) { + server.stop(); + } + } + + @Test + public void testGetNewInstance() { + HttpClient client = new LocalHttpClient(); + HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(client).build(); + + TestInterfaceClientImpl.TestInterfaceClientService testInterface = + TestInterfaceClientImpl.TestInterfaceClientService.getNewInstance(pipeline, null); + assertNotNull(testInterface); + } + + @Test + public void testGetFoo() { + String wireValue + = + "{\"bar\":\"hello.world\",\"baz\":[\"hello\",\"hello.world\"],\"qux\":{\"a.b\":\"c.d\",\"bar.a\":\"ttyy\",\"bar.b\":\"uuzz\",\"hello\":\"world\"},\"additionalProperties\":{\"bar\":\"baz\",\"a.b\":\"c.d\",\"properties.bar\":\"barbar\"}}"; + + HttpPipeline pipeline = new HttpPipelineBuilder().httpClient((request) -> { + // what is the default response body mode? + request.setRequestOptions(new RequestOptions().setResponseBodyMode(ResponseBodyMode.DESERIALIZE)); + return new MockHttpResponse(request, 200, + BinaryData.fromString(wireValue)); + }).build(); + + TestInterfaceClientImpl.TestInterfaceClientService testInterface = + TestInterfaceClientImpl.TestInterfaceClientService.getNewInstance(pipeline, null); + assertNotNull(testInterface); + + // test getFoo method + Response response = testInterface.getFoo("key", "label", "sync-token-value"); + assertNotNull(response); + assertEquals(200, response.getStatusCode()); + + Foo foo = response.getValue(); + assertNotNull(foo); + assertEquals("hello.world", foo.bar()); + assertEquals(4, foo.qux().size()); + assertNotNull(foo.additionalProperties()); + assertEquals("baz", foo.additionalProperties().get("bar")); + assertEquals("c.d", foo.additionalProperties().get("a.b")); + assertEquals("barbar", foo.additionalProperties().get("properties.bar")); + } + + @Test + public void bodyIsEmptyWhenIgnoreBodyIsSet() throws IOException { + HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(getHttpClient()).build(); + + TestInterfaceClientImpl.TestInterfaceClientService testInterface = + TestInterfaceClientImpl.TestInterfaceClientService.getNewInstance(pipeline, null); + assertNotNull(testInterface); + RequestOptions requestOptions = new RequestOptions().setResponseBodyMode(IGNORE); + HttpBinJSON httpBinJSON = testInterface.putConvenience(getServerUri(false), 42, requestOptions); + + assertNull(httpBinJSON); + + try (Response response = testInterface.putResponse(getServerUri(false), 42, requestOptions)) { + assertNull(response.getValue()); + } + } + + @Test + public void bodyIsEmptyWhenIgnoreBodyIsSetForStreamResponse() throws IOException { + HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(getHttpClient()).build(); + TestInterfaceClientImpl.TestInterfaceClientService testInterface = + TestInterfaceClientImpl.TestInterfaceClientService.getNewInstance(pipeline, null); + assertNotNull(testInterface); + RequestOptions requestOptions = new RequestOptions().setResponseBodyMode(IGNORE); + HttpBinJSON httpBinJSON = testInterface.postStreamConvenience(getServerUri(false), 42, requestOptions); + + assertNull(httpBinJSON); + + try ( + Response response = testInterface.postStreamResponse(getServerUri(false), 42, requestOptions)) { + assertNull(response.getValue()); + } + } + + // TODO (alzimmer): How do we handle streaming? + @Test + public void bodyIsStreamedWhenResponseBodyModeIndicatesIt() throws IOException { + HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(getHttpClient()).build(); + TestInterfaceClientImpl.TestInterfaceClientService testInterface = + TestInterfaceClientImpl.TestInterfaceClientService.getNewInstance(pipeline, null); + assertNotNull(testInterface); + RequestOptions requestOptions = new RequestOptions().setResponseBodyMode(STREAM); + + try ( + Response response = testInterface.postStreamResponse(getServerUri(false), 42, requestOptions)) { + assertNotNull(response.getValue()); + } + } + + @Test + public void bodyIsBufferedWhenResponseBodyModeIndicatesIt() throws IOException { + HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(getHttpClient()).build(); + TestInterfaceClientImpl.TestInterfaceClientService testInterface = + TestInterfaceClientImpl.TestInterfaceClientService.getNewInstance(pipeline, null); + assertNotNull(testInterface); + RequestOptions requestOptions = new RequestOptions().setResponseBodyMode(BUFFER); + HttpBinJSON httpBinJSON = testInterface.postStreamConvenience(getServerUri(false), 42, requestOptions); + + assertNotNull(httpBinJSON); + + try ( + Response response = testInterface.postStreamResponse(getServerUri(false), 42, requestOptions)) { + assertNotNull(response.getValue()); + } + } + + @Test + public void bodyIsDeserializedWhenResponseBodyModeIndicatesIt() throws IOException { + HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(getHttpClient()).build(); + TestInterfaceClientImpl.TestInterfaceClientService testInterface = + TestInterfaceClientImpl.TestInterfaceClientService.getNewInstance(pipeline, null); + assertNotNull(testInterface); + RequestOptions requestOptions = new RequestOptions().setResponseBodyMode(DESERIALIZE); + HttpBinJSON httpBinJSON = testInterface.postStreamConvenience(getServerUri(false), 42, requestOptions); + + assertNotNull(httpBinJSON); + + try (Response response = testInterface.postStreamResponse(getServerUri(false), 42, requestOptions)) { + assertNotNull(response.getValue()); + } + } + + @Test + public void requestWithByteArrayReturnType() { + HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(getHttpClient()).build(); + TestInterfaceClientImpl.TestInterfaceClientService testInterface = + TestInterfaceClientImpl.TestInterfaceClientService.getNewInstance(pipeline, null); + final byte[] result = testInterface.getByteArray(getServerUri(false)); + + assertNotNull(result); + assertEquals(100, result.length); + } + + /** + * Tests that the response body is correctly returned as a byte array. + */ + @Test + @Disabled("Disabled until we confirm the behavior of the HostParam annotation") + public void requestWithByteArrayReturnTypeAndParameterizedHostAndPath() { + //https://github.com/Azure/azure-sdk-for-java/issues/44298 + HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(getHttpClient()).build(); + TestInterfaceClientImpl.TestInterfaceClientService testInterface = + TestInterfaceClientImpl.TestInterfaceClientService.getNewInstance(pipeline, null); + final byte[] result + = testInterface.getByteArray("http", "localhost:" + server.getHttpPort(), 100); + + assertNotNull(result); + assertEquals(result.length, 100); + } + + /** + * Tests that a response with no return type is correctly handled. + */ + @Test + public void getRequestWithNoReturn() { + HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(getHttpClient()).build(); + TestInterfaceClientImpl.TestInterfaceClientService testInterface = + TestInterfaceClientImpl.TestInterfaceClientService.getNewInstance(pipeline, null); + assertDoesNotThrow(() -> testInterface.getNothing(getServerUri(false))); + } + + private HttpClient getHttpClient() { + return new OkHttpHttpClientProvider().getSharedInstance(); + } + + private String getServerUri(boolean secure) { + return secure ? server.getHttpsUri() : server.getHttpUri(); + } + +} diff --git a/sdk/clientcore/annotation-processor/CHANGELOG.md b/sdk/clientcore/annotation-processor/CHANGELOG.md new file mode 100644 index 000000000000..b165b2598908 --- /dev/null +++ b/sdk/clientcore/annotation-processor/CHANGELOG.md @@ -0,0 +1,8 @@ +# Release History + +## 1.0.0-beta.1 ((2025-03-10) + +### Features Added + +- Initial release. Please see the README and wiki for more information. + This package includes annotation-processing code for constructing service layer implementations for Java client libraries. diff --git a/sdk/clientcore/annotation-processor/README.md b/sdk/clientcore/annotation-processor/README.md new file mode 100644 index 000000000000..5cdda5ddf9b1 --- /dev/null +++ b/sdk/clientcore/annotation-processor/README.md @@ -0,0 +1,138 @@ +# Client Core Compile-Time Annotation Processor + +The client-core annotation processor for introducing compile-time code generation for libraries based on client core +>Note: This project is for experimentation and exploring new ideas that may or may not make it into a supported GA release. + +## Usage + +1. Add the below plugin configuration to your `pom.xml`: + ```xml + + + org.apache.maven.plugins + maven-compiler-plugin + 3.13.0 + + + run-annotation-processing + generate-sources + + compile + + + + 1.8 + 1.8 + 8 + only + ${project.build.directory}/generated-sources/ + + + io.clientcore + annotation-processor + 1.0.0-beta.1 + + + + io.clientcore.annotation.processor.AnnotationProcessor + + + + -Xlint:-options + + + + + + + + io.clientcore + annotation-processor + 1.0.0-beta.1 + + + + + ``` +2. Annotate your interfaces with `@ServiceInterface`, `@HttpRequestInformation` and + `@UnexpectedResponseExceptionDetail` such annotations: + ```java + @ServiceInterface(name = "ExampleClient", host = "{endpoint}/example") + public interface ExampleService { + @HttpRequestInformation(method = HttpMethod.GET, path = "/user/{userId}", expectedStatusCodes = { 200 }) + @UnexpectedResponseExceptionDetail(exceptionTypeName = "CLIENT_AUTHENTICATION", statusCode = { 401 }) + @UnexpectedResponseExceptionDetail(exceptionTypeName = "RESOURCE_NOT_FOUND", statusCode = { 404 }) + @UnexpectedResponseExceptionDetail(exceptionTypeName = "RESOURCE_MODIFIED", statusCode = { 409 }) + User getUser(@PathParam("userId") String userId); + } + ``` + +3. `mvn clean install annotation-processor/pom.xml` followed by `mvn clean compile` your project and the plugin + will generate an implementation of the annotated interface in the `target/generated-sources` directory. + ```java + public class ExampleServiceImpl implements ExampleService { + private static final ClientLogger LOGGER = new ClientLogger(TestInterfaceClientService.class); + + private final HttpPipeline defaultPipeline; + + private final ObjectSerializer serializer; + + public ExampleServiceImpl(HttpPipeline defaultPipeline, ObjectSerializer serializer) { + this.defaultPipeline = defaultPipeline; + this.serializer = serializer == null ? new JsonSerializer() : serializer; + } + + public static ExampleService getNewInstance(HttpPipeline pipeline, ObjectSerializer serializer) { + return new ExampleServiceImpl(pipeline, serializer); + } + + public HttpPipeline getPipeline() { + return defaultPipeline; + } + + public Response getUser(String userId, Context context) { + return getUser(endpoint, apiVersion, userId, context); + } + + @Override + private Response getUser(String endpoint, String apiVersion, String userId, Context context) { + HttpPipeline pipeline = this.getPipeline(); + String host = endpoint + "/example/users/" + userId + "?api-version=" + apiVersion; + + // create the request + HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, host); + + // set the headers + HttpHeaders headers = new HttpHeaders(); + httpRequest.setHeaders(headers); + + // add RequestOptions to the request + httpRequest.setRequestOptions(requestOptions); + + // set the body content if present + + // send the request through the pipeline + Response networkResponse = pipeline.send(httpRequest); + + final int responseCode = networkResponse.getStatusCode(); + boolean expectedResponse = responseCode == 200; + if (!expectedResponse) { + throw new RuntimeException("Unexpected response code: " + responseCode); + } + ResponseBodyMode responseBodyMode = ResponseBodyMode.IGNORE; + if (requestOptions != null) { + responseBodyMode = requestOptions.getResponseBodyMode(); + } + if (responseBodyMode == ResponseBodyMode.DESERIALIZE) { + BinaryData responseBody = response.getBody(); + HttpResponseAccessHelper.setValue((HttpResponse) response, responseBody); + } else { + BinaryData responseBody = response.getBody(); + HttpResponseAccessHelper.setBodyDeserializer((HttpResponse) response, (body) -> responseBody); + } + return (Response) response; + } + } + ``` +This implementation eliminates reflection and integrates directly with your HTTP client infrastructure. + diff --git a/sdk/clientcore/annotation-processor/checkstyle-suppressions.xml b/sdk/clientcore/annotation-processor/checkstyle-suppressions.xml new file mode 100644 index 000000000000..2a9ea7d735e4 --- /dev/null +++ b/sdk/clientcore/annotation-processor/checkstyle-suppressions.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/sdk/clientcore/annotation-processor/ci.yml b/sdk/clientcore/annotation-processor/ci.yml new file mode 100644 index 000000000000..44ed49dbfd73 --- /dev/null +++ b/sdk/clientcore/annotation-processor/ci.yml @@ -0,0 +1,45 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. + +trigger: + branches: + include: + - main + - hotfix/* + - release/* + paths: + include: + - sdk/clientcore/annotation-processor/ + exclude: + - sdk/clientcore/annotation-processor/pom.xml + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/clientcore/annotation-processor/ + exclude: + - sdk/clientcore/annotation-processor/pom.xml + +parameters: +- name: release_clientcoreannotationprocessor + displayName: 'annotation-processor' + type: boolean + default: true + +extends: + template: /eng/pipelines/templates/stages/archetype-sdk-client.yml + parameters: + ServiceDirectory: clientcore/annotation-processor + Artifacts: + - name: annotation-processor + groupId: io.clientcore + safeName: annotationprocessor + releaseInBatch: ${{ parameters.release_clientcoreannotationprocessor }} + AdditionalModules: + - name: annotation-processor-test + groupId: io.clientcore diff --git a/sdk/clientcore/annotation-processor/pom.xml b/sdk/clientcore/annotation-processor/pom.xml new file mode 100644 index 000000000000..3b44a47f5d6e --- /dev/null +++ b/sdk/clientcore/annotation-processor/pom.xml @@ -0,0 +1,156 @@ + + + 4.0.0 + + io.clientcore + annotation-processor + jar + 1.0.0-beta.1 + + Client Core Compile-Time Annotation Processor + The client-core annotation processor for introducing compile-time code generation for libraries based on client core + https://github.com/azure/azure-sdk-for-java + + Microsoft Corporation + http://microsoft.com + + + + io.clientcore + clientcore-parent + 1.0.0-beta.3 + ../../parents/clientcore-parent + + + + + The MIT License (MIT) + http://opensource.org/licenses/MIT + repo + + + + + + microsoft + Microsoft Corporation + + + + + + + ossrh + Sonatype Snapshots + https://oss.sonatype.org/content/repositories/snapshots/ + default + + true + daily + + + + + + + ossrh + Sonatype Snapshots + https://oss.sonatype.org/content/repositories/snapshots/ + default + + true + always + + + + + + + ossrh + Sonatype Snapshots + https://oss.sonatype.org/content/repositories/snapshots/ + true + default + + + azure-java-build-docs + ${site.url}/site/ + + + + + GitHub + ${issues.url} + + + + https://github.com/Azure/azure-sdk-for-java + scm:git:https://github.com/Azure/azure-sdk-for-java.git + + HEAD + + + + UTF-8 + https://azuresdkartifacts.blob.core.windows.net/azure-sdk-for-java + checkstyle-suppressions.xml + spotbugs-exclude.xml + true + + + + + com.github.javaparser + javaparser-core + 3.26.2 + + + io.clientcore + core + 1.0.0-beta.7 + + + + + org.junit.jupiter + junit-jupiter-api + 5.11.2 + test + + + org.junit.jupiter + junit-jupiter-params + 5.11.2 + test + + + + + + + src/main/resources + true + + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.5.0 + + + + + com.github.javaparser:javaparser-core:[3.26.2] + + + + + + + + + diff --git a/sdk/clientcore/annotation-processor/spotbugs-exclude.xml b/sdk/clientcore/annotation-processor/spotbugs-exclude.xml new file mode 100644 index 000000000000..240129526ffc --- /dev/null +++ b/sdk/clientcore/annotation-processor/spotbugs-exclude.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + diff --git a/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/AnnotationProcessor.java b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/AnnotationProcessor.java new file mode 100644 index 000000000000..de7c86cf32e2 --- /dev/null +++ b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/AnnotationProcessor.java @@ -0,0 +1,217 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.annotation.processor; + +import io.clientcore.annotation.processor.models.HttpRequestContext; +import io.clientcore.annotation.processor.models.Substitution; +import io.clientcore.annotation.processor.models.TemplateInput; +import io.clientcore.annotation.processor.templating.TemplateProcessor; +import io.clientcore.annotation.processor.utils.PathBuilder; +import io.clientcore.core.annotations.ServiceInterface; +import io.clientcore.core.http.annotations.BodyParam; +import io.clientcore.core.http.annotations.HeaderParam; +import io.clientcore.core.http.annotations.HostParam; +import io.clientcore.core.http.annotations.HttpRequestInformation; +import io.clientcore.core.http.annotations.PathParam; +import io.clientcore.core.http.annotations.QueryParam; +import io.clientcore.core.http.annotations.UnexpectedResponseExceptionDetail; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpMethod; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.http.pipeline.HttpPipeline; +import io.clientcore.core.models.binarydata.BinaryData; + +import javax.annotation.processing.AbstractProcessor; +import javax.annotation.processing.RoundEnvironment; +import javax.annotation.processing.SupportedAnnotationTypes; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.Element; +import javax.lang.model.element.ElementKind; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.TypeElement; +import javax.lang.model.element.VariableElement; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * Annotation processor that generates client code based on annotated interfaces. + */ +@SupportedAnnotationTypes("io.clientcore.core.annotations.*") +public class AnnotationProcessor extends AbstractProcessor { + + /** + * Creates a new instance of the AnnotationProcessor. + */ + public AnnotationProcessor() { + } + + @Override + public SourceVersion getSupportedSourceVersion() { + return SourceVersion.latest(); + } + + @Override + public boolean process(Set annotations, RoundEnvironment roundEnv) { + // We iterate through each interface annotated with @ServiceInterface separately. + // This outer for-loop is not strictly necessary, as we only have one annotation that we care about + // (@ServiceInterface), but we'll leave it here for now + annotations.stream() + .map(roundEnv::getElementsAnnotatedWith) + .flatMap(Set::stream) + .filter(element -> element.getKind().isInterface()) + .forEach(element -> { + if (element.getAnnotation(ServiceInterface.class) != null) { + this.processServiceInterface(element); + } + }); + + return true; + } + + private void processServiceInterface(Element serviceInterface) { + if (serviceInterface == null || serviceInterface.getKind() != ElementKind.INTERFACE) { + throw new IllegalArgumentException("Invalid service interface provided."); + } + + TemplateInput templateInput = new TemplateInput(); + + // Determine the fully qualified name (FQN) and package name + final String serviceInterfaceFQN = serviceInterface.asType().toString(); + int lastDot = serviceInterfaceFQN.lastIndexOf('.'); + String packageName = (lastDot > 0) ? serviceInterfaceFQN.substring(0, lastDot) : "default.generated"; + + final String serviceInterfaceShortName = serviceInterfaceFQN.substring(lastDot + 1); + final String serviceInterfaceImplFQN = serviceInterfaceFQN + "Impl"; + final String serviceInterfaceImplShortName = serviceInterfaceImplFQN.substring(lastDot + 1); + + templateInput.setPackageName(packageName); + templateInput.setServiceInterfaceFQN(serviceInterfaceFQN); + templateInput.setServiceInterfaceShortName(serviceInterfaceShortName); + templateInput.setServiceInterfaceImplShortName(serviceInterfaceImplShortName); + + // Read the ServiceInterface.host() value from annotations + ServiceInterface annotation = serviceInterface.getAnnotation(ServiceInterface.class); + if (annotation != null && annotation.host() != null) { + templateInput.setHost(annotation.host()); + } + + // Add all required imports + addImports(templateInput); + + // Collect methods annotated with @HttpRequestInformation + List httpRequestMethods = serviceInterface.getEnclosedElements() + .stream() + .filter(element -> element.getKind() == ElementKind.METHOD) + .filter(element -> element.getAnnotation(HttpRequestInformation.class) != null) + .map(ExecutableElement.class::cast) + .collect(Collectors.toList()); + + // Generate HTTP request contexts + templateInput.setHttpRequestContexts(httpRequestMethods.stream() + .map(e -> createHttpRequestContext(e, templateInput)) + .filter(Objects::nonNull) // Exclude null contexts + .collect(Collectors.toList())); + + // Set UnexpectedResponseExceptionDetails + templateInput.setUnexpectedResponseExceptionDetails(httpRequestMethods.stream() + .map(e -> e.getAnnotation(UnexpectedResponseExceptionDetail.class)) + .filter(Objects::nonNull) // Exclude null annotations + .collect(Collectors.toList())); + + // Process the template + TemplateProcessor.getInstance().process(templateInput, processingEnv); + + // Additional formatting or logging if necessary + } + + private void addImports(TemplateInput templateInput) { + templateInput.addImport(BinaryData.class.getName()); + templateInput.addImport(HttpPipeline.class.getName()); + templateInput.addImport(HttpHeaderName.class.getName()); + templateInput.addImport(HttpMethod.class.getName()); + templateInput.addImport(HttpRequest.class.getName()); + templateInput.addImport(Response.class.getName()); + templateInput.addImport(Void.class.getName()); + } + + private HttpRequestContext createHttpRequestContext(ExecutableElement requestMethod, TemplateInput templateInput) { + HttpRequestContext method = new HttpRequestContext(); + method.setHost(templateInput.getHost()); + method.setMethodName(requestMethod.getSimpleName().toString()); + method.setIsConvenience(requestMethod.isDefault()); + + // Extract @HttpRequestInformation annotation details + final HttpRequestInformation httpRequestInfo = requestMethod.getAnnotation(HttpRequestInformation.class); + method.setPath(httpRequestInfo.path()); + method.setHttpMethod(httpRequestInfo.method()); + method.setExpectedStatusCodes(httpRequestInfo.expectedStatusCodes()); + + // Add return type as an import + setReturnTypeForMethod(method, requestMethod, templateInput); + boolean isEncoded = false; + // Process parameters + for (VariableElement param : requestMethod.getParameters()) { + // Cache annotations for each parameter + HostParam hostParam = param.getAnnotation(HostParam.class); + PathParam pathParam = param.getAnnotation(PathParam.class); + HeaderParam headerParam = param.getAnnotation(HeaderParam.class); + QueryParam queryParam = param.getAnnotation(QueryParam.class); + BodyParam bodyParam = param.getAnnotation(BodyParam.class); + + // Switch based on annotations + if (hostParam != null) { + method.addSubstitution( + new Substitution(hostParam.value(), param.getSimpleName().toString(), hostParam.encoded())); + } else if (pathParam != null) { + if (pathParam.encoded()) { + isEncoded = true; + } + method.addSubstitution( + new Substitution(pathParam.value(), param.getSimpleName().toString(), pathParam.encoded())); + } else if (headerParam != null) { + method.addHeader(headerParam.value(), param.getSimpleName().toString()); + } else if (queryParam != null) { + method.addQueryParam(queryParam.value(), param.getSimpleName().toString()); + // TODO: Add support for multipleQueryParams and encoded handling + } else if (bodyParam != null) { + method.setBody(new HttpRequestContext.Body(bodyParam.value(), param.asType().toString(), + param.getSimpleName().toString())); + } + + // Add parameter details to method context + String shortParamName = templateInput.addImport(param.asType()); + method.addParameter(new HttpRequestContext.MethodParameter(param.asType(), shortParamName, + param.getSimpleName().toString())); + } + + // Pre-compute host substitutions + method.setHost(getHost(templateInput, method, isEncoded)); + + return method; + } + + private void setReturnTypeForMethod(HttpRequestContext method, ExecutableElement requestMethod, + TemplateInput templateInput) { + method.setMethodReturnType(requestMethod.getReturnType()); + } + + private static String getHost(TemplateInput templateInput, HttpRequestContext method, boolean isEncoded) { + String rawHost; + if (isEncoded) { + rawHost = method.getPath(); + } else { + String host = templateInput.getHost(); + String path = method.getPath(); + if (!host.endsWith("/") && !path.startsWith("/")) { + rawHost = host + "/" + path; + } else { + rawHost = host + path; + } + } + return PathBuilder.buildPath(rawHost, method); + } +} diff --git a/sdk/clientcore/tools/annotation-processor/src/main/java/io/clientcore/tools/codegen/exceptions/MissingSubstitutionException.java b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/exceptions/MissingSubstitutionException.java similarity index 89% rename from sdk/clientcore/tools/annotation-processor/src/main/java/io/clientcore/tools/codegen/exceptions/MissingSubstitutionException.java rename to sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/exceptions/MissingSubstitutionException.java index 112b101e9570..0678e3fafe86 100644 --- a/sdk/clientcore/tools/annotation-processor/src/main/java/io/clientcore/tools/codegen/exceptions/MissingSubstitutionException.java +++ b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/exceptions/MissingSubstitutionException.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.tools.codegen.exceptions; +package io.clientcore.annotation.processor.exceptions; /** * Exception thrown when a substitution is missing from the template. diff --git a/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/exceptions/package-info.java b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/exceptions/package-info.java new file mode 100644 index 000000000000..95c08ab487f2 --- /dev/null +++ b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/exceptions/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing exceptions for the annotation processor. + */ +package io.clientcore.annotation.processor.exceptions; diff --git a/sdk/clientcore/tools/annotation-processor/src/main/java/io/clientcore/tools/codegen/models/HttpRequestContext.java b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/models/HttpRequestContext.java similarity index 88% rename from sdk/clientcore/tools/annotation-processor/src/main/java/io/clientcore/tools/codegen/models/HttpRequestContext.java rename to sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/models/HttpRequestContext.java index d6d18b110d6a..c4d9263f50d2 100644 --- a/sdk/clientcore/tools/annotation-processor/src/main/java/io/clientcore/tools/codegen/models/HttpRequestContext.java +++ b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/models/HttpRequestContext.java @@ -1,17 +1,16 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.tools.codegen.models; +package io.clientcore.annotation.processor.models; import io.clientcore.core.http.models.HttpMethod; - -import javax.lang.model.type.TypeMirror; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import javax.lang.model.type.TypeMirror; /** * Represents the context of an HTTP request, including its configuration, parameters, headers, and other details. @@ -20,9 +19,10 @@ public final class HttpRequestContext { // Request Configuration private String methodName; - private String methodReturnType; + private TypeMirror methodReturnType; private final List parameters; private HttpMethod httpMethod; + private boolean isConvenience; // This comes from the @Host annotation that is applied to the entire service interface, it will likely have one // or more substitutions in it, which will be replaced with the appropriate parameter values annotated with @HostParam. @@ -75,7 +75,7 @@ public void setMethodName(String methodName) { * * @return the method return type. */ - public String getMethodReturnType() { + public TypeMirror getMethodReturnType() { return methodReturnType; } @@ -84,7 +84,7 @@ public String getMethodReturnType() { * * @param methodReturnType the method return type to set. */ - public void setMethodReturnType(String methodReturnType) { + public void setMethodReturnType(TypeMirror methodReturnType) { this.methodReturnType = methodReturnType; } @@ -172,7 +172,7 @@ public Map getHeaders() { /** * Adds a header. * - * @param key the header key. + * @param key the header key. * @param value the header value. */ public void addHeader(String key, String value) { @@ -191,7 +191,7 @@ public Map getQueryParams() { /** * Adds a query parameter. * - * @param key the query parameter key. + * @param key the query parameter key. * @param value the query parameter value. * @throws IllegalArgumentException if a duplicate query parameter is added. */ @@ -210,7 +210,8 @@ public void addQueryParam(String key, String value) { */ public void addSubstitution(Substitution substitution) { if (substitutions.containsKey(substitution.getParameterName())) { - throw new IllegalArgumentException("Cannot add duplicate substitution for parameter '" + substitution.getParameterName() + "'"); + throw new IllegalArgumentException( + "Cannot add duplicate substitution for parameter '" + substitution.getParameterName() + "'"); } substitutions.put(substitution.getParameterName(), substitution); } @@ -264,6 +265,22 @@ public List getExpectedStatusCodes() { return Arrays.stream(expectedStatusCodes).boxed().collect(Collectors.toList()); } + /** + * Gets the boolean to true if the provided method is a default method + * @return the boolean to true if the provided method is a default method + */ + public boolean isConvenience() { + return isConvenience; + } + + /** + * Sets the boolean to true if the provided method is a default method + * @param isConvenience the provided method is a default method + */ + public void setIsConvenience(boolean isConvenience) { + this.isConvenience = isConvenience; + } + /** * Represents a method parameter. */ @@ -275,9 +292,9 @@ public static class MethodParameter { /** * Constructs a new MethodParameter. * - * @param type the type of the parameter. + * @param type the type of the parameter. * @param shortTypeName the short type name of the parameter. - * @param name the name of the parameter. + * @param name the name of the parameter. */ public MethodParameter(TypeMirror type, String shortTypeName, String name) { this.type = type; @@ -330,7 +347,7 @@ public static class Body { /** * Constructs a new Body. * - * @param contentType the content type. + * @param contentType the content type. * @param parameterType the parameter type. * @param parameterName the parameter name. */ diff --git a/sdk/clientcore/tools/annotation-processor/src/main/java/io/clientcore/tools/codegen/models/Substitution.java b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/models/Substitution.java similarity index 89% rename from sdk/clientcore/tools/annotation-processor/src/main/java/io/clientcore/tools/codegen/models/Substitution.java rename to sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/models/Substitution.java index adb282d06ed9..1f5925f94d4b 100644 --- a/sdk/clientcore/tools/annotation-processor/src/main/java/io/clientcore/tools/codegen/models/Substitution.java +++ b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/models/Substitution.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.tools.codegen.models; +package io.clientcore.annotation.processor.models; /** * A Substitution is a value that can be used to replace placeholder values in a URL. Placeholders look like: @@ -45,6 +45,11 @@ public String getParameterName() { return parameterName; } + /** + * Get the variable name that will be used to replace the placeholder in the target URL. + * + * @return The name of the variable that will be used to replace the placeholder in the target URL. + */ public String getParameterVariableName() { return parameterVariableName; } diff --git a/sdk/clientcore/tools/annotation-processor/src/main/java/io/clientcore/tools/codegen/models/TemplateInput.java b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/models/TemplateInput.java similarity index 77% rename from sdk/clientcore/tools/annotation-processor/src/main/java/io/clientcore/tools/codegen/models/TemplateInput.java rename to sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/models/TemplateInput.java index b40d9c0b0aa6..e592c4b41f10 100644 --- a/sdk/clientcore/tools/annotation-processor/src/main/java/io/clientcore/tools/codegen/models/TemplateInput.java +++ b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/models/TemplateInput.java @@ -1,9 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.tools.codegen.models; +package io.clientcore.annotation.processor.models; + +import com.github.javaparser.StaticJavaParser; +import com.github.javaparser.ast.type.Type; +import io.clientcore.core.http.annotations.UnexpectedResponseExceptionDetail; -import io.clientcore.core.http.annotation.UnexpectedResponseExceptionDetail; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; @@ -11,11 +14,19 @@ import java.util.List; import java.util.Map; import java.util.TreeMap; +import java.util.stream.Collectors; /** * Represents the input required for generating a template. */ public class TemplateInput { + + /** + * Initializes a new instance of the {@link TemplateInput} class. + */ + public TemplateInput() { + } + // A map of fully-qualified class names to their short names private final Map imports = new TreeMap<>(); @@ -148,21 +159,31 @@ public String addImport(TypeMirror type) { String shortName = null; if (type.getKind().isPrimitive()) { - shortName = toShortName(longName); - imports.put(longName, shortName); + return longName; } else if (imports.containsKey(type.toString())) { shortName = imports.get(longName); } else if (type.getKind() == TypeKind.DECLARED) { // Check if this type is a generic type, and if it is, recursively check the type arguments - TypeElement typeElement = (TypeElement) ((DeclaredType) type).asElement(); - List typeArguments = ((DeclaredType) type).getTypeArguments(); + DeclaredType declaredType = (DeclaredType) type; + TypeElement typeElement = (TypeElement) declaredType.asElement(); + + String rawType = typeElement.getQualifiedName().toString(); + String shortRawType = toShortName(rawType); // Convert raw type to short name + imports.put(rawType, shortRawType); // Store the mapping for future reference + + // Process generics recursively + List typeArguments = declaredType.getTypeArguments(); if (typeArguments != null && !typeArguments.isEmpty()) { - longName = typeElement.getQualifiedName().toString(); - shortName = toShortName(typeElement.getQualifiedName().toString()); - imports.put(longName, shortName); + List genericTypes = typeArguments.stream() + .map(arg -> StaticJavaParser.parseType(addImport(arg))) // Recursively get short names for generic types + .collect(Collectors.toList()); + Type parsedRawType = StaticJavaParser.parseType(shortRawType); + com.github.javaparser.ast.type.ClassOrInterfaceType classOrInterfaceType + = new com.github.javaparser.ast.type.ClassOrInterfaceType(null, parsedRawType.toString()); + classOrInterfaceType.setTypeArguments(genericTypes.toArray(new Type[0])); + shortName = classOrInterfaceType.toString(); } else { - shortName = toShortName(longName); - imports.put(longName, shortName); + shortName = shortRawType; } } @@ -219,7 +240,8 @@ public List getUnexpectedResponseExceptionDet * * @param unexpectedResponseExceptionDetails the list of unexpected response exception details to set. */ - public void setUnexpectedResponseExceptionDetails(List unexpectedResponseExceptionDetails) { + public void setUnexpectedResponseExceptionDetails( + List unexpectedResponseExceptionDetails) { this.unexpectedResponseExceptionDetails = unexpectedResponseExceptionDetails; } } diff --git a/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/models/package-info.java b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/models/package-info.java new file mode 100644 index 000000000000..2476c67f64a3 --- /dev/null +++ b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/models/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing the models used in the annotation processor. + */ +package io.clientcore.annotation.processor.models; diff --git a/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/package-info.java b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/package-info.java new file mode 100644 index 000000000000..55568961e64a --- /dev/null +++ b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing the implementation of the annotation processor. + */ +package io.clientcore.annotation.processor; diff --git a/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/templating/JavaParserTemplateProcessor.java b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/templating/JavaParserTemplateProcessor.java new file mode 100644 index 000000000000..99317c3e4b43 --- /dev/null +++ b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/templating/JavaParserTemplateProcessor.java @@ -0,0 +1,498 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.annotation.processor.templating; + +import com.github.javaparser.StaticJavaParser; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.VariableDeclarator; +import com.github.javaparser.ast.comments.LineComment; +import com.github.javaparser.ast.expr.ArrayInitializerExpr; +import com.github.javaparser.ast.expr.MethodCallExpr; +import com.github.javaparser.ast.expr.Name; +import com.github.javaparser.ast.expr.NameExpr; +import com.github.javaparser.ast.expr.SingleMemberAnnotationExpr; +import com.github.javaparser.ast.expr.StringLiteralExpr; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.ExpressionStmt; +import com.github.javaparser.ast.stmt.ReturnStmt; +import com.github.javaparser.ast.stmt.Statement; +import io.clientcore.annotation.processor.models.HttpRequestContext; +import io.clientcore.annotation.processor.models.TemplateInput; +import io.clientcore.annotation.processor.utils.TypeConverter; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpMethod; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.RequestOptions; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.http.models.ResponseBodyMode; +import io.clientcore.core.http.pipeline.HttpPipeline; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.serialization.ObjectSerializer; +import io.clientcore.core.serialization.json.JsonSerializer; + +import javax.annotation.processing.ProcessingEnvironment; +import javax.lang.model.type.TypeMirror; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.io.Writer; +import java.lang.reflect.Field; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.nio.ByteBuffer; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +import static io.clientcore.annotation.processor.utils.ResponseBodyModeGeneration.generateResponseHandling; + +/** + * This class generates the implementation of the service interface. + */ +public class JavaParserTemplateProcessor implements TemplateProcessor { + private static final String APPLICATION_JSON = "application/json"; + private static final String APPLICATION_OCTET_STREAM = "application/octet-stream"; + + private static final Map LOWERCASE_HEADER_TO_HTTPHEADENAME_CONSTANT; + + static { + LOWERCASE_HEADER_TO_HTTPHEADENAME_CONSTANT = new HashMap<>(); + for (Field field : HttpHeaderName.class.getDeclaredFields()) { + // Only inspect public static final fields (aka, constants) + if (!java.lang.reflect.Modifier.isPublic(field.getModifiers()) + || !java.lang.reflect.Modifier.isStatic(field.getModifiers()) + || !java.lang.reflect.Modifier.isFinal(field.getModifiers())) { + continue; + } + + String constantName = field.getName(); + HttpHeaderName httpHeaderName = null; + try { + httpHeaderName = (HttpHeaderName) field.get(null); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + + LOWERCASE_HEADER_TO_HTTPHEADENAME_CONSTANT.put(httpHeaderName.getCaseInsensitiveName(), constantName); + } + } + + /** + * Initializes a new instance of the {@link JavaParserTemplateProcessor} class. + */ + public JavaParserTemplateProcessor() { + } + + private final CompilationUnit compilationUnit = new CompilationUnit(); + private ClassOrInterfaceDeclaration classBuilder; + + @Override + public void process(TemplateInput templateInput, ProcessingEnvironment processingEnv) { + String packageName = templateInput.getPackageName(); + // Remove the last part of the package name to avoid clash with class name + packageName = packageName.substring(0, packageName.lastIndexOf('.')); + String serviceInterfaceImplShortName = templateInput.getServiceInterfaceImplShortName(); + String serviceInterfaceShortName = templateInput.getServiceInterfaceShortName(); + + addImports(templateInput); + addOrphanComments(); + setPackageDeclaration(packageName); + createClass(serviceInterfaceImplShortName, serviceInterfaceShortName, templateInput); + + try (Writer fileWriter = processingEnv.getFiler() + .createSourceFile(packageName + "." + serviceInterfaceImplShortName) + .openWriter()) { + fileWriter.write(compilationUnit.toString()); + fileWriter.flush(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + void addImports(TemplateInput templateInput) { + templateInput.getImports().keySet().forEach(compilationUnit::addImport); + } + + void addOrphanComments() { + compilationUnit.addOrphanComment(new LineComment("Copyright (c) Microsoft Corporation. All rights reserved.")); + compilationUnit.addOrphanComment(new LineComment("Licensed under the MIT License.")); + } + + void setPackageDeclaration(String packageName) { + compilationUnit.setPackageDeclaration(packageName); + } + + void createClass(String serviceInterfaceImplShortName, String serviceInterfaceShortName, + TemplateInput templateInput) { + classBuilder = compilationUnit.addClass(serviceInterfaceImplShortName, Modifier.Keyword.PUBLIC); + + String serviceInterfacePackage = templateInput.getServiceInterfaceFQN() + .substring(0, templateInput.getServiceInterfaceFQN().lastIndexOf('.')); + compilationUnit.addImport(serviceInterfacePackage + "." + serviceInterfaceShortName); + classBuilder.addImplementedType(serviceInterfaceShortName); + + configureLoggerField(classBuilder.addField("ClientLogger", "LOGGER", Modifier.Keyword.PRIVATE, + Modifier.Keyword.STATIC, Modifier.Keyword.FINAL), serviceInterfaceShortName); + + classBuilder.addField(HttpPipeline.class, "defaultPipeline", Modifier.Keyword.PRIVATE, Modifier.Keyword.FINAL); + classBuilder.addField(ObjectSerializer.class, "serializer", Modifier.Keyword.PRIVATE, Modifier.Keyword.FINAL); + + compilationUnit.addImport(JsonSerializer.class); + classBuilder.addConstructor(Modifier.Keyword.PRIVATE) + .addParameter(HttpPipeline.class, "defaultPipeline") + .addParameter(ObjectSerializer.class, "serializer") + .setBody(StaticJavaParser.parseBlock( + "{ this.defaultPipeline = defaultPipeline; this.serializer = serializer == null ? new JsonSerializer() : serializer; }")); + + classBuilder.addMethod("getNewInstance", Modifier.Keyword.PUBLIC, Modifier.Keyword.STATIC) + .setType(serviceInterfaceShortName) + .addParameter(HttpPipeline.class, "pipeline") + .addParameter(ObjectSerializer.class, "serializer") + .setBody(StaticJavaParser + .parseBlock("{ return new " + serviceInterfaceImplShortName + "(pipeline, serializer); }")) + .setJavadocComment("Creates an instance of " + serviceInterfaceShortName + + " that is capable of sending requests to the service.\n" + + "@param pipeline The HTTP pipeline to use for sending requests.\n" + + "@param serializer The serializer to use for serializing and deserializing request and response bodies.\n" + + "@return An instance of `" + serviceInterfaceShortName + "`;"); + + configurePipelineMethod(classBuilder.addMethod("getPipeline", Modifier.Keyword.PRIVATE)); + + for (HttpRequestContext method : templateInput.getHttpRequestContexts()) { + if (!method.isConvenience()) { + configureInternalMethod(classBuilder.addMethod(method.getMethodName(), Modifier.Keyword.PUBLIC), + method); + } + } + + addDeserializeHelperMethod( + classBuilder.addMethod("decodeNetworkResponse", Modifier.Keyword.PRIVATE, Modifier.Keyword.STATIC)); + addDefaultResponseHandlingMethod( + classBuilder.addMethod("getOrDefaultResponseBodyMode", Modifier.Keyword.PRIVATE, Modifier.Keyword.STATIC)); + } + + /** + * Get the compilation unit + * @return the compilation unit + */ + CompilationUnit getCompilationUnit() { + return this.compilationUnit; + } + + private void addDefaultResponseHandlingMethod(MethodDeclaration defaultResponseHandlingMethod) { + defaultResponseHandlingMethod.setType(ResponseBodyMode.class) + .addParameter(RequestOptions.class, "requestOptions"); + defaultResponseHandlingMethod + .setJavadocComment("Retrieve the ResponseBodyMode from RequestOptions or use the default " + + "ResponseBodyMode.BUFFER.\n" + "@param requestOptions the request options set on the HttpRequest\n" + + "@return the ResponseBodyMode from RequestOptions or ResponseBodyMode.BUFFER"); + defaultResponseHandlingMethod.setBody(StaticJavaParser.parseBlock("{ ResponseBodyMode responseBodyMode;" + + " if (requestOptions != null && requestOptions.getResponseBodyMode() != null) {" + + " responseBodyMode = requestOptions.getResponseBodyMode();" + " } else {" + + " responseBodyMode = ResponseBodyMode.BUFFER;" + " }" + " return responseBodyMode; }")); + + } + + private void addDeserializeHelperMethod(MethodDeclaration deserializeHelperMethod) { + deserializeHelperMethod.setType("Object") + .addParameter("BinaryData", "data") + .addParameter(ObjectSerializer.class, "serializer") + .addParameter("ParameterizedType", "returnType"); + deserializeHelperMethod.tryAddImportToParentCompilationUnit(IOException.class); + deserializeHelperMethod.tryAddImportToParentCompilationUnit(UncheckedIOException.class); + deserializeHelperMethod.tryAddImportToParentCompilationUnit(ParameterizedType.class); + deserializeHelperMethod.tryAddImportToParentCompilationUnit(Type.class); + deserializeHelperMethod.tryAddImportToParentCompilationUnit(List.class); + deserializeHelperMethod + .setJavadocComment("Decodes the body of an {@link Response} into the type returned by the called API.\n" + + "@param data The BinaryData to decode.\n" + "@param serializer The serializer to use.\n" + + "@param returnType The type of the ParameterizedType return value.\n" + "@return The decoded value.\n" + + "@throws IOException If the deserialization fails."); + + deserializeHelperMethod.setBody(new BlockStmt() + .addStatement(StaticJavaParser.parseStatement("if (data == null) { return null; }")) + .addStatement(StaticJavaParser + .parseStatement("try { if (List.class.isAssignableFrom((Class) returnType.getRawType())) { " + + " return serializer.deserializeFromBytes(data.toBytes(), returnType); } " + + "Type token = returnType.getRawType(); if (Response.class.isAssignableFrom((Class) token)) { " + + " token = returnType.getActualTypeArguments()[0]; } " + + "return serializer.deserializeFromBytes(data.toBytes(), token); } catch (IOException e) { " + + " throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); }"))); + + } + + // Pattern for all field and method creation is to mutate the passed declaration. + // This pattern allows for addition of imports to be done in these methods using + // 'tryAddImportToParentCompilationUnit', as that method follows the chain of parent nodes to add the import to the + // creating CompilationUnit (if it exists). + // + // So, instead of needing a bunch of 'CompilationUnit.addImport' calls before creating the class, fields, and + // methods contained by source file, we can add the imports as we create the methods. This works as declarations + // will look for a parent node, in this case a ClassOrInterfaceDeclaration, and then look for the parent node of + // that (the CompilationUnit) to add the import to. + + void configureLoggerField(FieldDeclaration field, String serviceInterfaceShortName) { + field.tryAddImportToParentCompilationUnit(ClientLogger.class); + field.setModifiers(Modifier.Keyword.PRIVATE, Modifier.Keyword.STATIC, Modifier.Keyword.FINAL) + .setVariables(new NodeList<>(new VariableDeclarator().setType("ClientLogger") + .setName("LOGGER") + .setInitializer("new ClientLogger(" + serviceInterfaceShortName + ".class)"))); + } + + void configurePipelineMethod(MethodDeclaration pipelineMethod) { + pipelineMethod.tryAddImportToParentCompilationUnit(HttpPipeline.class); + pipelineMethod.setName("getPipeline") + .setModifiers(Modifier.Keyword.PRIVATE) + .setType(HttpPipeline.class) + .setBody(new BlockStmt().addStatement(new ReturnStmt("defaultPipeline"))); + } + + /** + * Configures the request with the body content and content type. + * + * @param body The method builder to add the statements to + * @param parameterType The type of the parameter + * @param contentType The content type of the request + * @param parameterName The name of the parameter + * @param isContentTypeSetInHeaders Whether the content type is set in the headers + */ + void configureBodyContentType(BlockStmt body, String parameterType, String contentType, String parameterName, + boolean isContentTypeSetInHeaders) { + if (parameterType == null) { + // No body content to set + body.addStatement( + StaticJavaParser.parseStatement("httpRequest.getHeaders().set(HttpHeaderName.CONTENT_LENGTH, \"0\");")); + } else { + + if (contentType == null || contentType.isEmpty()) { + // TODO (alzimmer): Why is String octet-stream? + if ("byte[]".equals(parameterType) || "String".equals(parameterType)) { + contentType = APPLICATION_OCTET_STREAM; + } else { + contentType = APPLICATION_JSON; + } + } + // Set the content type header if it is not already set in the headers + if (!isContentTypeSetInHeaders) { + body.addStatement(StaticJavaParser.parseStatement( + "httpRequest.getHeaders().set(HttpHeaderName.CONTENT_TYPE, \"" + contentType + "\");")); + } + if ("io.clientcore.core.models.binarydata.BinaryData".equals(parameterType)) { + body.tryAddImportToParentCompilationUnit(BinaryData.class); + body.addStatement( + StaticJavaParser.parseStatement("BinaryData binaryData = (BinaryData) " + parameterName + ";")); + body.addStatement(StaticJavaParser.parseStatement("if (binaryData.getLength() != null) {" + + "httpRequest.getHeaders().set(HttpHeaderName.CONTENT_LENGTH, String.valueOf(binaryData.getLength()));" + + "httpRequest.setBody(binaryData); }")); + return; + } + + boolean isJson = false; + final String[] contentTypeParts = contentType.split(";"); + + for (final String contentTypePart : contentTypeParts) { + if (contentTypePart.trim().equalsIgnoreCase(APPLICATION_JSON)) { + isJson = true; + + break; + } + } + updateRequestWithBodyContent(body, isJson, parameterType, parameterName); + } + } + + private void configureInternalMethod(MethodDeclaration internalMethod, HttpRequestContext method) { + // TODO (alzimmer): For now throw @SuppressWarnings({"unchecked", "cast"}) on generated methods while we + // improve / fix the generated code to no longer need it. + internalMethod.setName(method.getMethodName()) + .addAnnotation(new SingleMemberAnnotationExpr(new Name("SuppressWarnings"), + new ArrayInitializerExpr( + new NodeList<>(new StringLiteralExpr("unchecked"), new StringLiteralExpr("cast"))))) + .addMarkerAnnotation(Override.class) + .setType(TypeConverter.getAstType(method.getMethodReturnType())); + + for (HttpRequestContext.MethodParameter parameter : method.getParameters()) { + internalMethod.addParameter(new com.github.javaparser.ast.body.Parameter( + StaticJavaParser.parseType(parameter.getShortTypeName()), parameter.getName())); + } + + BlockStmt body = internalMethod.getBody().get(); + body.addStatement(StaticJavaParser.parseStatement("HttpPipeline pipeline = this.getPipeline();")); + + initializeHttpRequest(body, method); + addHeadersToRequest(body, method); + addRequestBody(body, method); + addRequestOptionsToRequestIfPresent(body, method); + finalizeHttpRequest(body, method.getMethodReturnType(), method); + + internalMethod.setBody(body); + } + + private void addRequestOptionsToRequestIfPresent(BlockStmt body, HttpRequestContext method) { + // Check if any parameter in the method is of type RequestOptions + boolean hasRequestOptions = method.getParameters() + .stream() + .anyMatch(parameter -> "options".equals(parameter.getName()) + && "RequestOptions".equals(parameter.getShortTypeName())); + + if (hasRequestOptions) { + // Create a statement for setting request options + ExpressionStmt statement = new ExpressionStmt(new MethodCallExpr(new NameExpr("httpRequest"), + "setRequestOptions", NodeList.nodeList(new NameExpr("options")))); + + statement.setComment(new LineComment("\n Set the Request Options")); + body.addStatement(statement); + } + + } + + // Helper methods + private void initializeHttpRequest(BlockStmt body, HttpRequestContext method) { + body.tryAddImportToParentCompilationUnit(HttpRequest.class); + body.tryAddImportToParentCompilationUnit(HttpMethod.class); + + // Fix for use the URI passed to the method, if provided + boolean useProvidedUri = method.getParameters() + .stream() + .anyMatch(parameter -> "uri".equals(parameter.getName()) && "String".equals(parameter.getShortTypeName())); + + if (useProvidedUri) { + body.addStatement( + StaticJavaParser.parseStatement("String host = uri + \"/\" + \"" + method.getPath() + "\";")); + } else { + body.addStatement(StaticJavaParser.parseStatement("String host = " + method.getHost() + ";")); + } + + Statement statement + = StaticJavaParser.parseStatement("HttpRequest httpRequest = new HttpRequest().setMethod(HttpMethod." + + method.getHttpMethod() + ").setUri(host);"); + + statement.setLineComment("\n Create the HTTP request"); + body.addStatement(statement); + } + + private void addHeadersToRequest(BlockStmt body, HttpRequestContext method) { + if (method.getHeaders().isEmpty()) { + return; + } + + body.tryAddImportToParentCompilationUnit(HttpHeaderName.class); + + for (Map.Entry header : method.getHeaders().entrySet()) { + boolean isStringType = method.getParameters() + .stream() + .anyMatch(parameter -> parameter.getName().equals(header.getValue()) + && "String".equals(parameter.getShortTypeName())); + String value = isStringType ? header.getValue() : "String.valueOf(" + header.getValue() + ")"; + + String constantName + = LOWERCASE_HEADER_TO_HTTPHEADENAME_CONSTANT.get(header.getKey().toLowerCase(Locale.ROOT)); + if (constantName != null) { + body.addStatement(StaticJavaParser.parseStatement( + "httpRequest.getHeaders().add(HttpHeaderName." + constantName + ", " + value + ");")); + } else { + body.addStatement( + StaticJavaParser.parseStatement("httpRequest.getHeaders().add(HttpHeaderName.fromString(\"" + + header.getKey() + "\"), " + value + ");")); + } + } + } + + private void addRequestBody(BlockStmt body, HttpRequestContext method) { + int index = body.getStatements().size(); + + HttpRequestContext.Body requestBody = method.getBody(); + boolean isContentTypeSetInHeaders + = method.getParameters().stream().anyMatch(parameter -> parameter.getName().equals("contentType")); + + if (requestBody != null) { + configureBodyContentType(body, requestBody.getParameterType(), requestBody.getContentType(), + requestBody.getParameterName(), isContentTypeSetInHeaders); + } else { + body.addStatement( + StaticJavaParser.parseStatement("httpRequest.getHeaders().set(HttpHeaderName.CONTENT_LENGTH, \"0\");")); + } + body.getStatements().get(index).setLineComment("\n Set the request body"); + } + + private void finalizeHttpRequest(BlockStmt body, TypeMirror returnTypeName, HttpRequestContext method) { + body.tryAddImportToParentCompilationUnit(Response.class); + + Statement statement + = StaticJavaParser.parseStatement("Response networkResponse = pipeline.send(httpRequest);"); + statement.setLineComment("\n Send the request through the pipeline"); + body.addStatement(statement); + + if (!method.getExpectedStatusCodes().isEmpty()) { + validateResponseStatus(body, method); + } + + generateResponseHandling(body, returnTypeName, method); + } + + private void validateResponseStatus(BlockStmt body, HttpRequestContext method) { + if (method.getExpectedStatusCodes().isEmpty()) { + return; + } + + body.addStatement(StaticJavaParser.parseStatement("int responseCode = networkResponse.getStatusCode();")); + String expectedResponseCheck; + if (method.getExpectedStatusCodes().size() == 1) { + expectedResponseCheck = "responseCode == " + method.getExpectedStatusCodes().get(0) + ";"; + } else { + String statusCodes = method.getExpectedStatusCodes() + .stream() + .map(code -> "responseCode == " + code) + .collect(Collectors.joining(" || ")); + expectedResponseCheck = "(" + statusCodes + ");"; + } + body.addStatement(StaticJavaParser.parseStatement("boolean expectedResponse = " + expectedResponseCheck)); + + body.tryAddImportToParentCompilationUnit(RuntimeException.class); + body.addStatement(StaticJavaParser.parseStatement("if (!expectedResponse) {" + + " throw new RuntimeException(\"Unexpected response code: \" + responseCode); }")); + } + + private void updateRequestWithBodyContent(BlockStmt body, boolean isJson, String parameterType, + String parameterName) { + if (parameterType == null) { + return; + } + if (isJson) { + body.addStatement(StaticJavaParser + .parseStatement("httpRequest.setBody(BinaryData.fromObject(" + parameterName + ", serializer));")); + } else if ("byte[]".equals(parameterType)) { + body.addStatement(StaticJavaParser + .parseStatement("httpRequest.setBody(BinaryData.fromBytes((byte[]) " + parameterName + "));")); + } else if ("String".equals(parameterType)) { + body.addStatement(StaticJavaParser + .parseStatement("httpRequest.setBody(BinaryData.fromString((String) " + parameterName + "));")); + } else if ("ByteBuffer".equals(parameterType)) { + // TODO: confirm behavior + //if (((ByteBuffer) bodyContentObject).hasArray()) { + // methodBuilder + // .addStatement("httpRequest.setBody($T.fromBytes(((ByteBuffer) $L).array()))", BinaryData.class, parameterName); + //} else { + // byte[] array = new byte[((ByteBuffer) bodyContentObject).remaining()]; + // + // ((ByteBuffer) bodyContentObject).get(array); + // methodBuilder + // .addStatement("httpRequest.setBody($T.fromBytes($L))", BinaryData.class, array); + //} + body.tryAddImportToParentCompilationUnit(ByteBuffer.class); + body.addStatement(StaticJavaParser.parseStatement( + "httpRequest.setBody(BinaryData.fromBytes(((ByteBuffer) " + parameterName + ").array()));")); + } else { + body.addStatement(StaticJavaParser + .parseStatement("httpRequest.setBody(BinaryData.fromObject(" + parameterName + ", serializer));")); + } + } +} diff --git a/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/templating/TemplateProcessor.java b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/templating/TemplateProcessor.java new file mode 100644 index 000000000000..2445cbc5cce3 --- /dev/null +++ b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/templating/TemplateProcessor.java @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.annotation.processor.templating; + +import io.clientcore.annotation.processor.models.TemplateInput; + +import javax.annotation.processing.ProcessingEnvironment; + +/** + * Interface for processing templates. + */ +public interface TemplateProcessor { + + /** + * Returns an instance of the TemplateProcessor. + * + * @return a new instance of JavaPoetTemplateProcessor + */ + static TemplateProcessor getInstance() { + return new JavaParserTemplateProcessor(); + } + + /** + * Processes the given template input using the provided processing environment. + * + * @param templateInput the input data for the template + * @param processingEnv the environment used for processing + */ + void process(TemplateInput templateInput, ProcessingEnvironment processingEnv); +} diff --git a/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/templating/package-info.java b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/templating/package-info.java new file mode 100644 index 000000000000..145cc3f3c6b1 --- /dev/null +++ b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/templating/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing the implementation of the templating. + */ +package io.clientcore.annotation.processor.templating; diff --git a/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/utils/PathBuilder.java b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/utils/PathBuilder.java new file mode 100644 index 000000000000..8c3eade358b7 --- /dev/null +++ b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/utils/PathBuilder.java @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.annotation.processor.utils; + +import io.clientcore.annotation.processor.exceptions.MissingSubstitutionException; +import io.clientcore.annotation.processor.models.HttpRequestContext; +import io.clientcore.annotation.processor.models.Substitution; + +import java.util.Objects; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * This class is responsible for building the path of the request URL by replacing the placeholders with the actual + */ +public final class PathBuilder { + // this class takes a 'raw host' string that contains {} delimited parameters, and needs to convert it into a + // Java string concatenation that can be used in the generated code. For example, the raw host string: + // https://{endpoint}/keys/{path1} + // would be converted into: + // "https://" + endpointParam + "/keys/" + pathValue + // Note that query parameters may also exist, and should be appended to the end of the URL string using + // a Map containing key-value pairs. + // Note that the 'endpoint' parameter is special - it is always the first parameter, and is always a host parameter. + /** + * Builds the path of the request URL by replacing the placeholders with the actual values. + * @param rawHost The raw host string that contains {} delimited parameters. + * @param method The HttpRequestContext object that contains the method's configuration, parameters, headers, and other details. + * @return The path of the request URL with the placeholders replaced with the actual values. + * @throws NullPointerException If the method is null. + * @throws MissingSubstitutionException If a substitution is missing for a placeholder in the raw host string. + * @throws IllegalArgumentException If the query parameter key or value is empty. + */ + public static String buildPath(String rawHost, HttpRequestContext method) { + if (method == null) { + throw new NullPointerException("method cannot be null"); + } + + boolean hasQueryParams = !method.getQueryParams().isEmpty(); + + // Pattern for substitution placeholders + Pattern pattern = Pattern.compile("\\{(.+?)}"); + Matcher matcher = pattern.matcher(rawHost); + StringBuffer buffer = new StringBuffer(); + + while (matcher.find()) { + String paramName = matcher.group(1); + Substitution substitution = method.getSubstitution(paramName); + + if (substitution != null) { + String substitutionValue = substitution.getParameterVariableName(); + String replacementValue = substitutionValue != null ? Objects.toString(substitutionValue, "null") : ""; + + matcher.appendReplacement(buffer, ""); + if (buffer.length() != 0) { + buffer.append("\" + "); + } + buffer.append(replacementValue).append(" + \""); + } else { + throw new MissingSubstitutionException( + "Could not find substitution for '" + paramName + "' in method '" + method.getMethodName() + "'"); + } + } + + matcher.appendTail(buffer); + + if (hasQueryParams) { + buffer.append("?"); + + method.getQueryParams().forEach((key, value) -> { + // Only append if both key and value are non-null and non-empty + + if (key == null || key.isEmpty()) { + throw new IllegalArgumentException("Query parameter key must not be null or empty"); + } + + if (value != null && !value.isEmpty()) { + buffer.append(key).append("=\" + ").append(value).append(" + \"&"); + } + }); + + // Remove the trailing '&' if present + if (buffer.length() > 0 && buffer.charAt(buffer.length() - 1) == '&') { + buffer.setLength(buffer.length() - 1); + } + + // Remove the trailing '?' if no valid query parameters were appended + if (buffer.length() > 0 && buffer.charAt(buffer.length() - 1) == '?') { + buffer.setLength(buffer.length() - 1); + } + } + + // Ensure the output is properly quoted + if (buffer.charAt(0) != '"' && !rawHost.startsWith("{")) { + buffer.insert(0, '"'); + } + + if (buffer.charAt(buffer.length() - 1) != '"' && !rawHost.endsWith("}")) { + buffer.append('"'); + } + + // Clean unnecessary `+ ""` in the buffer + String result = buffer.toString().replaceAll(" \\+ \"\"", ""); + + // Remove trailing ' + ' if it exists + if (result.endsWith(" + ")) { + result = result.substring(0, result.length() - 3); + } + + // Remove trailing ' + "' if it exists + if (result.endsWith(" + \"")) { + result = result.substring(0, result.length() - 4); + } + + // Check for missing or incorrect braces + long openingBracesCount = rawHost.chars().filter(ch -> ch == '{').count(); + long closingBracesCount = rawHost.chars().filter(ch -> ch == '}').count(); + + if (openingBracesCount != closingBracesCount) { + throw new MissingSubstitutionException("Mismatched braces in raw host: " + rawHost); + } + + return result; + } + + private PathBuilder() { + } +} diff --git a/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/utils/ResponseBodyModeGeneration.java b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/utils/ResponseBodyModeGeneration.java new file mode 100644 index 000000000000..9198fbd29ac6 --- /dev/null +++ b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/utils/ResponseBodyModeGeneration.java @@ -0,0 +1,234 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.annotation.processor.utils; + +import com.github.javaparser.StaticJavaParser; +import com.github.javaparser.ast.expr.CastExpr; +import com.github.javaparser.ast.expr.NameExpr; +import com.github.javaparser.ast.stmt.BlockStmt; +import com.github.javaparser.ast.stmt.ReturnStmt; +import io.clientcore.annotation.processor.models.HttpRequestContext; +import io.clientcore.core.http.models.HttpMethod; +import io.clientcore.core.http.models.RequestOptions; +import io.clientcore.core.http.models.ResponseBodyMode; +import io.clientcore.core.implementation.TypeUtil; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.utils.CoreUtils; + +import javax.lang.model.element.TypeElement; +import javax.lang.model.type.DeclaredType; +import javax.lang.model.type.PrimitiveType; +import javax.lang.model.type.TypeKind; +import javax.lang.model.type.TypeMirror; +import javax.lang.model.util.SimpleTypeVisitor8; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.util.List; + +/** + * Utility class to generate response body mode assignment and response handling based on the response body mode. + */ +public final class ResponseBodyModeGeneration { + + /** + * Generates response body mode assignment based on request options and return type. + * + * @param body the method builder to append generated code. + */ + public static void generateResponseBodyMode(BlockStmt body) { + body.tryAddImportToParentCompilationUnit(ResponseBodyMode.class); + body.tryAddImportToParentCompilationUnit(RequestOptions.class); + body.addStatement(StaticJavaParser.parseStatement( + "ResponseBodyMode responseBodyMode = getOrDefaultResponseBodyMode" + "(httpRequest.getRequestOptions());")); + } + + /** + * Handles deserialization response mode logic. + * + * @param body the method builder to append generated code. + * @param returnType the return type of the method. + * @param entityType the entity type of the method. + * @param method The Http method request context + */ + public static void handleResponseBody(BlockStmt body, TypeMirror returnType, java.lang.reflect.Type entityType, + HttpRequestContext method) { + body.tryAddImportToParentCompilationUnit(ResponseBodyMode.class); + + String typeCast = entityType.toString(); + if (method.getHttpMethod() == HttpMethod.HEAD + && (TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.TYPE) + || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { + body.addStatement("Object result = (responseStatusCode / 100) == 2"); + typeCast = "Boolean"; + } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { + body.addStatement("byte[] responseBodyBytes = responseBody != null ? responseBody.toBytes() : null;"); + + // TODO: Add support for Base64Uri + // if (returnValueWireType == Base64Uri.class) { + // responseBodyBytes = new Base64Uri(responseBodyBytes).decodedBytes(); + // } + + body.addStatement( + "Object result = responseBodyBytes != null ? (responseBodyBytes.length == 0 ? null : responseBodyBytes) : null;"); + typeCast = "byte[]"; + } else if (TypeUtil.isTypeOrSubTypeOf(entityType, InputStream.class)) { + body.addStatement(StaticJavaParser.parseStatement("BinaryData responseBody = response.getValue();")); + body.addStatement("Object result = responseBody.toStream();"); + typeCast = "InputStream"; + } else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) { + // BinaryData + // + // The raw response is directly used to create an instance of BinaryData which then provides + // different methods to read the response. The reading of the response is delayed until BinaryData + // is read and depending on which format the content is converted into, the response is not necessarily + // fully copied into memory resulting in lesser overall memory usage. + body.addStatement("Object result = networkResponse.getValue();"); + typeCast = "BinaryData"; + } else if (returnType instanceof DeclaredType) { + DeclaredType declaredType = (DeclaredType) returnType; + TypeElement typeElement = (TypeElement) declaredType.asElement(); + body.tryAddImportToParentCompilationUnit(CoreUtils.class); + + // Ensure type arguments exist before accessing them + if (!declaredType.getTypeArguments().isEmpty()) { + TypeMirror firstGenericType = declaredType.getTypeArguments().get(0); + + if (firstGenericType instanceof DeclaredType) { + DeclaredType genericDeclaredType = (DeclaredType) firstGenericType; + TypeElement genericTypeElement = (TypeElement) genericDeclaredType.asElement(); + + typeCast = genericTypeElement.getSimpleName().toString(); + body.findCompilationUnit() + .ifPresent(compilationUnit -> compilationUnit + .addImport(genericTypeElement.getQualifiedName().toString())); + + // Check if it's specifically a List + if (genericTypeElement.getQualifiedName().contentEquals(List.class.getCanonicalName())) { + if (!genericDeclaredType.getTypeArguments().isEmpty()) { + TypeMirror innerType = genericDeclaredType.getTypeArguments().get(0); + body.addStatement("ParameterizedType returnType = CoreUtils.createParameterizedType(" + + genericTypeElement.getSimpleName() + ".class, " + innerType + ".class);"); + } + } else { + String genericType = declaredType.getTypeArguments().get(0).toString(); + body.addStatement("ParameterizedType returnType = CoreUtils.createParameterizedType(" + + typeElement.getSimpleName() + ".class, " + genericType + ".class);"); + } + } + } + body.addStatement( + "Object result = decodeNetworkResponse(networkResponse.getValue(), serializer, returnType);"); + } + + body.addStatement(StaticJavaParser.parseStatement("return new Response<>(" + + "networkResponse.getRequest(), responseCode, networkResponse.getHeaders(), (" + typeCast + ") result);")); + } + + /** + * Handles the generation of the complete response processing flow based on the return type. + * + * @param body the method builder to append generated code. + * @param returnType the return type of the method. + * @param method whether request options are used. + */ + public static void generateResponseHandling(BlockStmt body, TypeMirror returnType, HttpRequestContext method) { + java.lang.reflect.Type bodyType = null; + + if (returnType.getKind() == TypeKind.VOID) { + closeResponse(body); + } else if (returnType.toString().equals("java.lang.Void")) { + closeResponse(body); + body.addStatement(new ReturnStmt("null")); + } else if (TypeConverter.isResponseType(returnType)) { + bodyType = TypeConverter.getEntityType(returnType); + if (returnType.toString().contains("Void")) { + closeResponse(body); + body.addStatement(StaticJavaParser.parseStatement("return new Response<>(" + + "networkResponse.getRequest(), responseCode, networkResponse.getHeaders(), null);")); + } else { + // If this type has type arguments, then we look at the last one to determine if it expects a body + generateResponseBodyMode(body); + handleResponseBody(body, returnType, bodyType, method); + createResponseIfNecessary(body); + } + } else { + if (returnType.getKind().isPrimitive()) { + bodyType = returnType.accept(new SimpleTypeVisitor8() { + @Override + public java.lang.reflect.Type visitPrimitive(PrimitiveType t, Void p) { + return TypeConverter.getPrimitiveClass(t); + } + }, null); + } else if (returnType.getKind() == TypeKind.ARRAY) { + bodyType = TypeConverter.getEntityType(returnType); + } + handleRestResponseReturnType(body, returnType, bodyType, method); + if (!returnType.getKind().isPrimitive() && returnType.getKind() != TypeKind.ARRAY) { + closeResponse(body); + CastExpr castExpr + = new CastExpr(StaticJavaParser.parseType(returnType.toString()), new NameExpr("result")); + + // Add the cast statement to the method body + body.addStatement(new ReturnStmt(castExpr)); + } + } + } + + private static void closeResponse(BlockStmt body) { + body.tryAddImportToParentCompilationUnit(IOException.class); + body.tryAddImportToParentCompilationUnit(UncheckedIOException.class); + + body.addStatement(StaticJavaParser.parseStatement("try { networkResponse.close(); }" + + "catch (IOException e) { throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); }")); + } + + /** + * Adds a return statement for response handling when necessary. + * + * @param body the method builder to append generated code. + */ + public static void createResponseIfNecessary(BlockStmt body) { + if (body.getStatements().get(body.getStatements().size() - 1).toString().contains("return")) { + return; + } + body.addStatement(StaticJavaParser.parseStatement("return response;")); + } + + /** + * Handles different response processing modes based on the return type and method. + * + * @param body the method builder to append generated code. + * @param returnTypeName the return type of the method. + * @param entityType the entity type of the method. + * @param method the HttpMethod context + */ + public static void handleRestResponseReturnType(BlockStmt body, TypeMirror returnTypeName, + java.lang.reflect.Type entityType, HttpRequestContext method) { + body.tryAddImportToParentCompilationUnit(BinaryData.class); + if (method.getHttpMethod() == HttpMethod.HEAD + && (TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.TYPE) + || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { + closeResponse(body); + body.addStatement(new ReturnStmt("expectedResponse")); + } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { + body.addStatement(StaticJavaParser.parseStatement("BinaryData responseBody = networkResponse.getValue();")); + body.addStatement(StaticJavaParser + .parseStatement("byte[] responseBodyBytes = responseBody != null ? responseBody.toBytes() : null;")); + body.addStatement(StaticJavaParser.parseStatement( + "return responseBodyBytes != null ? (responseBodyBytes.length == 0 ? null : responseBodyBytes) : null;")); + } else if (TypeUtil.isTypeOrSubTypeOf(entityType, InputStream.class)) { + body.addStatement(StaticJavaParser.parseStatement("BinaryData responseBody = networkResponse.getValue();")); + body.addStatement(StaticJavaParser.parseStatement("return responseBody.toStream();")); + } else if (TypeUtil.isTypeOrSubTypeOf(entityType, BinaryData.class)) { + body.addStatement(StaticJavaParser.parseStatement("BinaryData responseBody = networkResponse.getValue();")); + closeResponse(body); + } else { + handleResponseBody(body, returnTypeName, entityType, method); + } + } + + private ResponseBodyModeGeneration() { + } +} diff --git a/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/utils/TypeConverter.java b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/utils/TypeConverter.java new file mode 100644 index 000000000000..b20133365a40 --- /dev/null +++ b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/utils/TypeConverter.java @@ -0,0 +1,246 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.annotation.processor.utils; + +import com.github.javaparser.StaticJavaParser; +import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.type.ClassOrInterfaceType; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.implementation.TypeUtil; + +import javax.lang.model.element.TypeElement; +import javax.lang.model.type.ArrayType; +import javax.lang.model.type.DeclaredType; +import javax.lang.model.type.TypeMirror; +import java.lang.reflect.Type; +import java.util.List; +import java.util.stream.Collectors; + +/** + * Utility class for converting JavaParser AST types to Java reflection types. + */ +public final class TypeConverter { + + /** + * Converts JavaParser's AST Type to java.lang.reflect.Type. + * Supports primitives, generic types, and void types. + * + * @param typeMirror the type to convert + * @return the corresponding Java reflection type + * @throws IllegalArgumentException if the type is unsupported + */ + public static Type toReflectType(TypeMirror typeMirror) { + switch (typeMirror.getKind()) { + case DECLARED: + return handleDeclaredType(typeMirror); + + case BOOLEAN: + case BYTE: + case CHAR: + case DOUBLE: + case FLOAT: + case INT: + case LONG: + case SHORT: + return getPrimitiveClass(typeMirror); + + case VOID: + return void.class; + + case ARRAY: + return handleArrayType(typeMirror); + + default: + throw new IllegalArgumentException("Unsupported type: " + typeMirror); + } + } + + /** + * Gets the primitive class for a given PrimitiveType. + * + * @param type the PrimitiveType to convert + * @return the corresponding primitive class + */ + public static Class getPrimitiveClass(TypeMirror type) { + switch (type.getKind()) { + case BOOLEAN: + return boolean.class; + + case BYTE: + return byte.class; + + case CHAR: + return char.class; + + case DOUBLE: + return double.class; + + case FLOAT: + return float.class; + + case INT: + return int.class; + + case LONG: + return long.class; + + case SHORT: + return short.class; + + case VOID: + return void.class; + + default: + return Object.class; + } + } + + /** + * Gets the entity type for a given AST type. + * + * @param returnType the AST type to convert + * @return the corresponding Java reflection type + */ + public static Type getEntityType(TypeMirror returnType) { + switch (returnType.getKind()) { + case ARRAY: + return handleArrayType(returnType); + + case BOOLEAN: + case BYTE: + case CHAR: + case DOUBLE: + case FLOAT: + case INT: + case LONG: + case SHORT: + // Convert JavaParser's PrimitiveType to Java Reflection Type + return getPrimitiveClass(returnType); + + case DECLARED: + return handleDeclaredType(returnType); + + default: + return Object.class; // Fallback for unknown types + } + } + + /** + * Checks if the given return type is a Response type. + * + * @param returnType the return type to check + * @return true if the return type is a Response type, false otherwise + */ + public static boolean isResponseType(TypeMirror returnType) { + if (returnType instanceof DeclaredType) { + DeclaredType declaredType = (DeclaredType) returnType; + TypeElement typeElement = (TypeElement) declaredType.asElement(); + return typeElement.getQualifiedName().contentEquals(Response.class.getCanonicalName()); + } + return false; + } + + /** + * Converts a DeclaredType to a ClassOrInterfaceType with type arguments. + * + * @param returnType the DeclaredType to convert + * @return the corresponding ClassOrInterfaceType + * @throws IllegalArgumentException if the type is unsupported + */ + public static com.github.javaparser.ast.type.Type getAstType(TypeMirror returnType) { + switch (returnType.getKind()) { + case VOID: + return StaticJavaParser.parseType("void"); + + case BOOLEAN: + return StaticJavaParser.parseType("boolean"); + + case BYTE: + return StaticJavaParser.parseType("byte"); + + case SHORT: + return StaticJavaParser.parseType("short"); + + case INT: + return StaticJavaParser.parseType("int"); + + case LONG: + return StaticJavaParser.parseType("long"); + + case CHAR: + return StaticJavaParser.parseType("char"); + + case FLOAT: + return StaticJavaParser.parseType("float"); + + case DOUBLE: + return StaticJavaParser.parseType("double"); + + case ARRAY: + if (returnType instanceof ArrayType) { + ArrayType arrayType = (ArrayType) returnType; + return StaticJavaParser.parseType(getAstType(arrayType.getComponentType()).toString() + "[]"); + } else { + return StaticJavaParser.parseType("Object[]"); // Fallback + } + case DECLARED: + // converting DeclaredType to ClassOrInterfaceType with type arguments + if (returnType instanceof DeclaredType) { + DeclaredType declaredType = (DeclaredType) returnType; + TypeElement typeElement = (TypeElement) declaredType.asElement(); + ClassOrInterfaceType astType + = new ClassOrInterfaceType(null, typeElement.getSimpleName().toString()); + if (!declaredType.getTypeArguments().isEmpty()) { + List typeArguments = declaredType.getTypeArguments() + .stream() + .map(TypeConverter::getAstType) + .collect(Collectors.toList()); + NodeList nodeListTypeArguments + = new NodeList<>(typeArguments); + astType.setTypeArguments(nodeListTypeArguments); + } + return astType; + } else { + return StaticJavaParser.parseType("Object"); // Fallback + } + + default: + throw new IllegalArgumentException("Unsupported return type: " + returnType); + } + } + + static java.lang.reflect.Type handleArrayType(TypeMirror type) { + if (type instanceof ArrayType) { + ArrayType arrayType = (ArrayType) type; + java.lang.reflect.Type componentType = toReflectType(arrayType.getComponentType()); + return java.lang.reflect.Array.newInstance((Class) componentType, 0).getClass(); + } + return Object.class; + } + + static java.lang.reflect.Type handleDeclaredType(TypeMirror declaredType) { + if (declaredType instanceof ClassOrInterfaceType) { + ClassOrInterfaceType classType = (ClassOrInterfaceType) declaredType; + + // Ensure type arguments exist before accessing them + if (classType.getTypeArguments().isPresent()) { + NodeList typeArguments = classType.getTypeArguments().get(); + + if (!typeArguments.isEmpty()) { + com.github.javaparser.ast.type.Type innerType = typeArguments.get(0); // First generic type (e.g., List or Foo) + return TypeUtil.createParameterizedType(innerType.toString().getClass()); + } else { + // No generic type on this RestResponse subtype, so we go up to parent + return TypeConverter.toReflectType(declaredType); + } + + } + } + return Object.class; // Fallback + } + + // Private constructor + private TypeConverter() { + } +} diff --git a/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/utils/package-info.java b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/utils/package-info.java new file mode 100644 index 000000000000..ddfa09cb7b2a --- /dev/null +++ b/sdk/clientcore/annotation-processor/src/main/java/io/clientcore/annotation/processor/utils/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing utility classes for the annotation processor. + */ +package io.clientcore.annotation.processor.utils; diff --git a/sdk/clientcore/annotation-processor/src/main/resources/META-INF/maven/services/javax.annotation.processing.Processor b/sdk/clientcore/annotation-processor/src/main/resources/META-INF/maven/services/javax.annotation.processing.Processor new file mode 100644 index 000000000000..e38a84e9ceac --- /dev/null +++ b/sdk/clientcore/annotation-processor/src/main/resources/META-INF/maven/services/javax.annotation.processing.Processor @@ -0,0 +1 @@ +io.clientcore.annotation.processor.AnnotationProcessor diff --git a/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/mocks/MockDeclaredType.java b/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/mocks/MockDeclaredType.java new file mode 100644 index 000000000000..21eb8f07893a --- /dev/null +++ b/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/mocks/MockDeclaredType.java @@ -0,0 +1,180 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.annotation.processor.mocks; + +import javax.lang.model.element.AnnotationMirror; +import javax.lang.model.element.Element; +import javax.lang.model.element.ElementKind; +import javax.lang.model.element.ElementVisitor; +import javax.lang.model.element.Modifier; +import javax.lang.model.element.Name; +import javax.lang.model.element.NestingKind; +import javax.lang.model.element.TypeElement; +import javax.lang.model.element.TypeParameterElement; +import javax.lang.model.type.DeclaredType; +import javax.lang.model.type.TypeKind; +import javax.lang.model.type.TypeMirror; +import java.lang.annotation.Annotation; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +/** + * Mock implementation of {@link DeclaredType}. + */ +public class MockDeclaredType extends MockTypeMirror implements DeclaredType { + private final String qualifiedName; + + /** + * Creates a mock {@link DeclaredType}. + * + * @param kind the {@link DeclaredType} + * @param toString the {@link DeclaredType#toString()} value + */ + public MockDeclaredType(TypeKind kind, String toString) { + super(kind, toString); + this.qualifiedName = toString; + } + + @Override + public Element asElement() { + return new TypeElement() { + @Override + public List getEnclosedElements() { + return Collections.emptyList(); + } + + @Override + public List getAnnotationMirrors() { + return Collections.emptyList(); + } + + @Override + public A getAnnotation(Class annotationType) { + return null; + } + + @SuppressWarnings("unchecked") + @Override + public A[] getAnnotationsByType(Class annotationType) { + return (A[]) java.lang.reflect.Array.newInstance(annotationType, 0); + } + + @Override + public R accept(ElementVisitor v, P p) { + return null; + } + + @Override + public NestingKind getNestingKind() { + return NestingKind.TOP_LEVEL; + } + + @Override + public Name getQualifiedName() { + return new Name() { + @Override + public int length() { + return qualifiedName.length(); + } + + @Override + public char charAt(int index) { + return qualifiedName.charAt(index); + } + + @Override + public CharSequence subSequence(int start, int end) { + return qualifiedName.subSequence(start, end); + } + + @Override + public boolean contentEquals(CharSequence cs) { + return qualifiedName.contentEquals(cs); + } + + @Override + public String toString() { + return qualifiedName; + } + }; + } + + @Override + public TypeMirror asType() { + return MockDeclaredType.this; + } + + @Override + public ElementKind getKind() { + return ElementKind.CLASS; + } + + @Override + public Set getModifiers() { + return Collections.singleton(Modifier.PUBLIC); + } + + @Override + public Name getSimpleName() { + return new Name() { + @Override + public boolean contentEquals(CharSequence cs) { + return qualifiedName.contentEquals(cs); + } + + @Override + public int length() { + return qualifiedName.length(); + } + + @Override + public char charAt(int index) { + return qualifiedName.charAt(index); + } + + @Override + public CharSequence subSequence(int start, int end) { + return qualifiedName.subSequence(start, end); + } + + @Override + public String toString() { + return qualifiedName; + } + }; + } + + @Override + public TypeMirror getSuperclass() { + return null; + } + + @Override + public List getInterfaces() { + return Collections.emptyList(); + } + + @Override + public List getTypeParameters() { + return Collections.emptyList(); + } + + @Override + public Element getEnclosingElement() { + return null; + } + }; + } + + @Override + public TypeMirror getEnclosingType() { + return null; + } + + @Override + public List getTypeArguments() { + return Collections.emptyList(); + } + +} diff --git a/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/mocks/MockFiler.java b/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/mocks/MockFiler.java new file mode 100644 index 000000000000..7908f6c81498 --- /dev/null +++ b/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/mocks/MockFiler.java @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.annotation.processor.mocks; + +import javax.annotation.processing.Filer; +import javax.lang.model.element.Element; +import javax.tools.FileObject; +import javax.tools.JavaFileManager; +import javax.tools.JavaFileObject; +import java.io.IOException; + +/** + * Mock implementation of {@link Filer} for testing purposes. + */ +public class MockFiler implements Filer { + private final JavaFileObject sourceFile; + + /** + * Creates an instance of {@link MockFiler}. + * + * @param sourceFile The source file to be used in the mock. + */ + public MockFiler(JavaFileObject sourceFile) { + this.sourceFile = sourceFile; + } + + @Override + public JavaFileObject createSourceFile(CharSequence name, Element... originatingElements) throws IOException { + return sourceFile; + } + + @Override + public JavaFileObject createClassFile(CharSequence name, Element... originatingElements) throws IOException { + return null; + } + + @Override + public FileObject createResource(JavaFileManager.Location location, CharSequence moduleAndPkg, + CharSequence relativeName, Element... originatingElements) throws IOException { + return null; + } + + @Override + public FileObject getResource(JavaFileManager.Location location, CharSequence moduleAndPkg, + CharSequence relativeName) throws IOException { + return null; + } +} diff --git a/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/mocks/MockJavaFileObject.java b/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/mocks/MockJavaFileObject.java new file mode 100644 index 000000000000..4c31e2610ed3 --- /dev/null +++ b/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/mocks/MockJavaFileObject.java @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.annotation.processor.mocks; + +import javax.lang.model.element.Modifier; +import javax.lang.model.element.NestingKind; +import javax.tools.JavaFileObject; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Reader; +import java.io.StringWriter; +import java.io.Writer; +import java.net.URI; + +/** + * Mock implementation of {@link JavaFileObject}. + */ +public class MockJavaFileObject implements JavaFileObject { + /** + * Creates an instance of {@link JavaFileObject}. + */ + public MockJavaFileObject() { + } + + @Override + public Kind getKind() { + return null; + } + + @Override + public boolean isNameCompatible(String simpleName, Kind kind) { + return false; + } + + @Override + public NestingKind getNestingKind() { + return null; + } + + @Override + public Modifier getAccessLevel() { + return null; + } + + @Override + public URI toUri() { + return null; + } + + @Override + public String getName() { + return ""; + } + + @Override + public InputStream openInputStream() throws IOException { + return null; + } + + @Override + public OutputStream openOutputStream() throws IOException { + return null; + } + + @Override + public Reader openReader(boolean ignoreEncodingErrors) throws IOException { + return null; + } + + @Override + public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { + return null; + } + + @Override + public Writer openWriter() throws IOException { + return new StringWriter(); + } + + @Override + public long getLastModified() { + return 0; + } + + @Override + public boolean delete() { + return false; + } +} diff --git a/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/mocks/MockProcessingEnvironment.java b/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/mocks/MockProcessingEnvironment.java new file mode 100644 index 000000000000..02ed493f4e09 --- /dev/null +++ b/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/mocks/MockProcessingEnvironment.java @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.annotation.processor.mocks; + +import javax.annotation.processing.Filer; +import javax.annotation.processing.Messager; +import javax.annotation.processing.ProcessingEnvironment; +import javax.lang.model.SourceVersion; +import javax.lang.model.util.Elements; +import javax.lang.model.util.Types; +import java.util.Collections; +import java.util.Locale; +import java.util.Map; + +/** + * Mock implementation of {@link ProcessingEnvironment}. + */ +public class MockProcessingEnvironment implements ProcessingEnvironment { + private final Filer filer; + private int getFilerCount = 0; + + /** + * Creates a new instance of {@link MockProcessingEnvironment}. + * + * @param filer The {@link Filer} to return from {@link #getFiler()}. + */ + public MockProcessingEnvironment(Filer filer) { + this.filer = filer; + } + + @Override + public Map getOptions() { + return Collections.emptyMap(); + } + + @Override + public Messager getMessager() { + return null; + } + + @Override + public Filer getFiler() { + getFilerCount++; + return filer; + } + + /** + * Returns the number of times {@link #getFiler()} was called. + * + * @return The number of times {@link #getFiler()} was called. + */ + public int getGetFilerCount() { + return getFilerCount; + } + + @Override + public Elements getElementUtils() { + return null; + } + + @Override + public Types getTypeUtils() { + return null; + } + + @Override + public SourceVersion getSourceVersion() { + return null; + } + + @Override + public Locale getLocale() { + return null; + } +} diff --git a/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/mocks/MockTemplateInput.java b/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/mocks/MockTemplateInput.java new file mode 100644 index 000000000000..8f782d11fe77 --- /dev/null +++ b/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/mocks/MockTemplateInput.java @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.annotation.processor.mocks; + +import io.clientcore.annotation.processor.models.HttpRequestContext; +import io.clientcore.annotation.processor.models.TemplateInput; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +public class MockTemplateInput extends TemplateInput { + + @Override + public String getPackageName() { + return "com.azure.v2.dummy.implementation.DummyClientImpl"; + } + + @Override + public String getServiceInterfaceImplShortName() { + return "DummyServiceImpl"; + } + + @Override + public String getServiceInterfaceShortName() { + return "DummyService"; + } + + @Override + public String getServiceInterfaceFQN() { + return "com.azure.v2.dummy.implementation.DummyClientImpl.DummyService"; + } + + @Override + public Map getImports() { + return Collections.emptyMap(); + } + + @Override + public List getHttpRequestContexts() { + return Collections.emptyList(); + } +} diff --git a/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/mocks/MockTypeMirror.java b/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/mocks/MockTypeMirror.java new file mode 100644 index 000000000000..6d2e764015c8 --- /dev/null +++ b/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/mocks/MockTypeMirror.java @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.annotation.processor.mocks; + +import javax.lang.model.element.AnnotationMirror; +import javax.lang.model.type.TypeKind; +import javax.lang.model.type.TypeMirror; +import javax.lang.model.type.TypeVisitor; +import java.lang.annotation.Annotation; +import java.lang.reflect.Array; +import java.util.Collections; +import java.util.List; + +/** + * Mock implementation of {@link TypeMirror}. + */ +public class MockTypeMirror implements TypeMirror { + private final TypeKind kind; + private final String toString; + + /** + * Creates a mock {@link TypeMirror}. + * + * @param kind the {@link TypeKind} + * @param toString the {@link TypeMirror#toString()} value + */ + public MockTypeMirror(TypeKind kind, String toString) { + this.kind = kind; + this.toString = toString; + } + + @Override + public TypeKind getKind() { + return kind; + } + + @Override + public List getAnnotationMirrors() { + return Collections.emptyList(); + } + + @Override + public A getAnnotation(Class annotationType) { + return null; + } + + @SuppressWarnings("unchecked") + @Override + public A[] getAnnotationsByType(Class annotationType) { + return (A[]) Array.newInstance(annotationType, 0); + } + + @Override + public R accept(TypeVisitor v, P p) { + return null; + } + + @Override + public String toString() { + return toString; + } +} diff --git a/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/models/TemplateInputTest.java b/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/models/TemplateInputTest.java new file mode 100644 index 000000000000..316d2f3fe7c2 --- /dev/null +++ b/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/models/TemplateInputTest.java @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.annotation.processor.models; + +import io.clientcore.annotation.processor.mocks.MockDeclaredType; +import io.clientcore.annotation.processor.mocks.MockTypeMirror; +import io.clientcore.core.http.annotations.UnexpectedResponseExceptionDetail; +import org.junit.jupiter.api.Test; + +import javax.lang.model.type.DeclaredType; +import javax.lang.model.type.TypeKind; +import javax.lang.model.type.TypeMirror; +import java.lang.annotation.Annotation; +import java.util.Collections; +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.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Tests for the {@link TemplateInput} class. + */ +public class TemplateInputTest { + + @Test + void getHostReturnsCorrectHost() { + TemplateInput templateInput = new TemplateInput(); + templateInput.setHost("localhost"); + assertEquals("localhost", templateInput.getHost()); + } + + @Test + void setHostUpdatesHost() { + TemplateInput templateInput = new TemplateInput(); + templateInput.setHost("127.0.0.1"); + assertEquals("127.0.0.1", templateInput.getHost()); + } + + @Test + void addImportAddsValidImport() { + TemplateInput templateInput = new TemplateInput(); + String shortName = templateInput.addImport("java.util.List"); + assertEquals("List", shortName); + assertTrue(templateInput.getImports().containsKey("java.util.List")); + } + + @Test + void addImportIgnoresNullImport() { + TemplateInput templateInput = new TemplateInput(); + String shortName = templateInput.addImport((String) null); + assertNull(shortName); + assertTrue(templateInput.getImports().isEmpty()); + } + + @Test + void addImportIgnoresEmptyImport() { + TemplateInput templateInput = new TemplateInput(); + String shortName = templateInput.addImport(""); + assertNull(shortName); + assertTrue(templateInput.getImports().isEmpty()); + } + + @Test + void addImportTypeMirrorAddsValidImport() { + TemplateInput templateInput = new TemplateInput(); + DeclaredType declaredType = new MockDeclaredType(TypeKind.DECLARED, "java.util.Map"); + String shortName = templateInput.addImport(declaredType); + assertEquals("Map", shortName); + assertTrue(templateInput.getImports().containsKey("java.util.Map")); + } + + @Test + void addImportTypeMirrorHandlesPrimitiveType() { + TemplateInput templateInput = new TemplateInput(); + TypeMirror typeMirror = new MockTypeMirror(TypeKind.INT, "int"); + String shortName = templateInput.addImport(typeMirror); + assertEquals("int", shortName); + assertFalse(templateInput.getImports().containsKey("int")); + } + + @Test + void setAndGetServiceInterfaceFQN() { + TemplateInput templateInput = new TemplateInput(); + templateInput.setServiceInterfaceFQN("com.example.Service"); + assertEquals("com.example.Service", templateInput.getServiceInterfaceFQN()); + } + + @Test + void setAndGetUnexpectedResponseExceptionDetails() { + TemplateInput templateInput = new TemplateInput(); + List details + = Collections.singletonList(new MockUnexpectedResponseExceptionDetail()); + templateInput.setUnexpectedResponseExceptionDetails(details); + assertEquals(details, templateInput.getUnexpectedResponseExceptionDetails()); + } + + private static final class MockUnexpectedResponseExceptionDetail implements UnexpectedResponseExceptionDetail { + @Override + public int[] statusCode() { + return new int[0]; + } + + @Override + public Class exceptionBodyClass() { + return String.class; + } + + @Override + public Class annotationType() { + return UnexpectedResponseExceptionDetail.class; + } + } +} diff --git a/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/templating/BodyContentTypeProcessorTest.java b/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/templating/BodyContentTypeProcessorTest.java new file mode 100644 index 000000000000..51c1f71d2a6d --- /dev/null +++ b/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/templating/BodyContentTypeProcessorTest.java @@ -0,0 +1,169 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.annotation.processor.templating; + +import com.github.javaparser.ast.stmt.BlockStmt; +import io.clientcore.annotation.processor.models.HttpRequestContext; +import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class BodyContentTypeProcessorTest { + private JavaParserTemplateProcessor processor; + + @BeforeEach + public void setup() { + processor = new JavaParserTemplateProcessor(); + } + + /** + * Test for the method configureBodyContentType + */ + @Test + public void bodyParamAnnotationPriorityOverContentTypeHeaderTest() { + // Create a new HttpRequestContext + HttpRequestContext context = new HttpRequestContext(); + byte[] bytes = "hello".getBytes(StandardCharsets.UTF_8); + + // Set the body + // BodyParam annotation is set to "application/octet-stream" + context.setBody(new HttpRequestContext.Body("application/octet-stream", "ByteBuffer", "request")); + + // Add headers + // Content-Type header is set to "application/json" + context.addHeader("Content-Type", "application/json"); + context.addHeader("Content-Length", String.valueOf((long) bytes.length)); + HttpRequestContext.Body requestBody = context.getBody(); + + BlockStmt body = new BlockStmt(); + processor.configureBodyContentType(body, requestBody.getParameterType(), requestBody.getContentType(), + requestBody.getParameterName(), false); + + // Expected output + String expectedOutput = "httpRequest.setBody(BinaryData.fromBytes(((ByteBuffer) request).array()));"; + + // Actual output + String actualOutput = body.toString(); + + assertTrue(actualOutput.contains(expectedOutput)); + // Verify headers in a separate test request content type header is set to application/octet-stream + + } + + @ParameterizedTest + @MethodSource("knownParameterTypesProvider") + public void testConfigureRequestWithBodyAndParameterType(HttpRequestContext.Body requestBody, + String expectedOutput) { + BlockStmt body = new BlockStmt(); + processor.configureBodyContentType(body, requestBody.getParameterType(), requestBody.getContentType(), + requestBody.getParameterName(), false); + + // Actual output + String actualOutput = body.toString(); + assertTrue(actualOutput.contains(expectedOutput), + "Expected output to contain: " + expectedOutput + " Actual output: " + actualOutput); + } + + @ParameterizedTest + @MethodSource("knownContentTypesProvider") + public void testconfigureBodyContentType(String parameterType, String expectedContentType) { + // Create a new HttpRequestContext + HttpRequestContext context = new HttpRequestContext(); + + // Set the body without specifying ContentType + context.setBody(new HttpRequestContext.Body(null, parameterType, "request")); + + BlockStmt body = new BlockStmt(); + processor.configureBodyContentType(body, context.getBody().getParameterType(), + context.getBody().getContentType(), context.getBody().getParameterName(), false); + + // Expected output + String expectedOutput = "httpRequest.getHeaders().set(HttpHeaderName.CONTENT_TYPE, " + expectedContentType; + + // Actual output + String actualOutput = body.toString(); + + assertTrue(actualOutput.contains(expectedOutput), + "Expected output to contain: " + expectedOutput + " Actual output: " + actualOutput); + } + + @Test + public void contentTypeHeaderPriorityOverBodyParamAnnotationTest() { + // Create a new HttpRequestContext + HttpRequestContext context = new HttpRequestContext(); + byte[] bytes = "hello".getBytes(StandardCharsets.UTF_8); + + // Set the body + // BodyParam annotation is set to "application/octet-stream" + context.setBody(new HttpRequestContext.Body("application/octet-stream", "ByteBuffer", "request")); + + // Add headers + // Content-Type header is set to "application/json" + context.addHeader("Content-Type", "application/json"); + context.addHeader("Content-Length", String.valueOf((long) bytes.length)); + HttpRequestContext.Body requestBody = context.getBody(); + + BlockStmt body = new BlockStmt(); + processor.configureBodyContentType(body, requestBody.getParameterType(), requestBody.getContentType(), + requestBody.getParameterName(), true); + + // Expected output + String expectedOutput = "httpRequest.setBody(BinaryData.fromBytes(((ByteBuffer) request).array()));"; + + // Actual output + String actualOutput = body.toString(); + + assertTrue(actualOutput.contains(expectedOutput)); + // Verify headers in a separate test request content type header is set to application/octet-stream + } + + private static Stream knownContentTypesProvider() { + return Stream.of(Arguments.of("byte[]", "\"application/octet-stream\""), + Arguments.of("String", "\"application/octet-stream\""), Arguments.of("BinaryData", "\"application/json\""), + Arguments.of("Object", "\"application/json\""), Arguments.of("ByteBuffer", "\"application/json\"")); + } + + private static Stream knownParameterTypesProvider() { + return Stream.of( + // scenario for isJson = true and parameterType == "ByteBuffer" + Arguments.of(new HttpRequestContext.Body(null, "ByteBuffer", "request"), + "httpRequest.setBody(BinaryData.fromObject(request, serializer));"), + Arguments.of(new HttpRequestContext.Body("application/octet-stream", "BinaryData", "request"), + "httpRequest.setBody(BinaryData.fromObject(request, serializer));"), + Arguments.of(new HttpRequestContext.Body("application/json", "BinaryData", "request"), + "httpRequest.setBody(BinaryData.fromObject(request, serializer));"), + Arguments.of(new HttpRequestContext.Body("application/json", "serializable", "request"), + "httpRequest.setBody(BinaryData.fromObject(request, serializer))"), + Arguments.of(new HttpRequestContext.Body("application/octet-stream", "byte[]", "request"), + "httpRequest.setBody(BinaryData.fromBytes((byte[]) request))"), + Arguments.of(new HttpRequestContext.Body("application/octet-stream", "String", "request"), + "httpRequest.setBody(BinaryData.fromString((String) request))"), + Arguments.of(new HttpRequestContext.Body("application/octet-stream", "ByteBuffer", "request"), + "httpRequest.setBody(BinaryData.fromBytes(((ByteBuffer) request).array()))"), + Arguments.of(new HttpRequestContext.Body("application/octet-stream", "Object", "request"), + "httpRequest.setBody(BinaryData.fromObject(request, serializer))"), + // scenario for isJson = false and parameterType == "String" + Arguments.of(new HttpRequestContext.Body("text/html", "String", "request"), + "httpRequest.setBody(BinaryData.fromString((String) request));"), + // scenario for isJson = false and parameterType == "ByteBuffer" + Arguments.of(new HttpRequestContext.Body("text/html", "ByteBuffer", "request"), + "httpRequest.setBody(BinaryData.fromBytes(((ByteBuffer) request).array()));"), + // scenario for parameterType = null + Arguments.of(new HttpRequestContext.Body("application/json", null, "request"), + "httpRequest.getHeaders().set(HttpHeaderName.CONTENT_LENGTH, \"0\");"), + // scenario for parameterType == "byte[]" + Arguments.of(new HttpRequestContext.Body("application/octet-stream", "byte[]", "request"), + "httpRequest.setBody(BinaryData.fromBytes((byte[]) request));"), + // Add scenario for parameterType == "String" + Arguments.of(new HttpRequestContext.Body("application/octet-stream", "String", "request"), + "httpRequest.setBody(BinaryData.fromString((String) request));")); + } +} diff --git a/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/templating/HttpPipelineBuilderMethodTest.java b/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/templating/HttpPipelineBuilderMethodTest.java new file mode 100644 index 000000000000..b0adbe42597b --- /dev/null +++ b/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/templating/HttpPipelineBuilderMethodTest.java @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.annotation.processor.templating; + +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.body.FieldDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import io.clientcore.annotation.processor.mocks.MockFiler; +import io.clientcore.annotation.processor.mocks.MockJavaFileObject; +import io.clientcore.annotation.processor.mocks.MockProcessingEnvironment; +import io.clientcore.annotation.processor.models.TemplateInput; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import javax.annotation.processing.Filer; +import javax.tools.JavaFileObject; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/* + * Tests for builder/helper methods generated in ServiceClientImpl class. + */ +public class HttpPipelineBuilderMethodTest { + + private static final String PACKAGE_NAME = "com.example.ExampleClientImpl"; + private static final String SERVICE_INTERFACE_SHORT_NAME = getExampleClientServiceImpl(); + private final JavaParserTemplateProcessor processor = new JavaParserTemplateProcessor(); + private TemplateInput templateInput; + + @BeforeEach + public void setUp() { + templateInput = new TemplateInput(); + templateInput.setPackageName(PACKAGE_NAME); + templateInput.setServiceInterfaceImplShortName(SERVICE_INTERFACE_SHORT_NAME); + templateInput.setServiceInterfaceFQN("com.example.ExampleClientService"); + templateInput.setServiceInterfaceShortName("ExampleClientService"); + templateInput.setHttpRequestContexts(Collections.emptyList()); + } + + private static String getExampleClientServiceImpl() { + return "ExampleClientServiceImpl"; + } + + @Test + public void testProcess() { + JavaFileObject filerSourceFile = new MockJavaFileObject(); + Filer filer = new MockFiler(filerSourceFile); + MockProcessingEnvironment processingEnv = new MockProcessingEnvironment(filer); + + processor.process(templateInput, processingEnv); + + // Verify that the JavaFile.writeTo was called + assertEquals(1, processingEnv.getGetFilerCount(), + "Expected getFiler to be called once, but was called " + processingEnv.getGetFilerCount() + " times"); + } + + @Test + public void testGetPipelineMethod() { + MethodDeclaration method = new MethodDeclaration(); + processor.configurePipelineMethod(method); + assertEquals("getPipeline", method.getNameAsString()); + assertEquals(Modifier.privateModifier(), method.getModifiers().iterator().next()); + assertEquals("HttpPipeline", method.getTypeAsString()); + } + + @Test + public void testLoggerFieldGeneration() { + FieldDeclaration loggerField = new FieldDeclaration(); + processor.configureLoggerField(loggerField, SERVICE_INTERFACE_SHORT_NAME); + assertEquals( + new HashSet<>( + Arrays.asList(Modifier.privateModifier(), Modifier.staticModifier(), Modifier.finalModifier())), + new HashSet<>(loggerField.getModifiers())); + assertEquals("ClientLogger", loggerField.getVariable(0).getTypeAsString()); + assertEquals("LOGGER", loggerField.getVariable(0).getNameAsString()); + + String expected = "new ClientLogger(ExampleClientServiceImpl.class)"; + String actual = loggerField.getVariable(0).getInitializer().get().toString(); + assertTrue(actual.contains(expected), "Expected to contain: " + expected + " Actual: " + actual); + } +} diff --git a/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/templating/ServiceInterfaceGenerationTest.java b/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/templating/ServiceInterfaceGenerationTest.java new file mode 100644 index 000000000000..91da13d26ba6 --- /dev/null +++ b/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/templating/ServiceInterfaceGenerationTest.java @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.annotation.processor.templating; + +import io.clientcore.annotation.processor.mocks.MockFiler; +import io.clientcore.annotation.processor.mocks.MockJavaFileObject; +import io.clientcore.annotation.processor.mocks.MockProcessingEnvironment; +import io.clientcore.annotation.processor.mocks.MockTemplateInput; +import io.clientcore.annotation.processor.models.TemplateInput; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import javax.annotation.processing.Filer; +import javax.annotation.processing.ProcessingEnvironment; +import javax.tools.JavaFileObject; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class ServiceInterfaceGenerationTest { + + private JavaParserTemplateProcessor processor; + private TemplateInput templateInput = new MockTemplateInput(); + private ProcessingEnvironment processingEnv; + + @BeforeEach + public void setUp() { + processor = new JavaParserTemplateProcessor(); + JavaFileObject filerSourceFile = new MockJavaFileObject(); + Filer filer = new MockFiler(filerSourceFile); + processingEnv = new MockProcessingEnvironment(filer); + } + + @Test + public void testProcessPackageName() { + processor.process(templateInput, processingEnv); + assertEquals("com.azure.v2.dummy.implementation", + processor.getCompilationUnit().getPackageDeclaration().get().getNameAsString()); + } + + @Test + public void testProcessServiceInterfaceFQN() { + processor.process(templateInput, processingEnv); + assertEquals(templateInput.getServiceInterfaceFQN(), + processor.getCompilationUnit().getPackageDeclaration().get().getNameAsString() + ".DummyClientImpl." + + templateInput.getServiceInterfaceShortName()); + } + + @Test + public void testAddImports() { + processor.addImports(templateInput); + assertEquals(0, processor.getCompilationUnit().getImports().size()); + } + + @Test + public void testAddOrphanComments() { + processor.addOrphanComments(); + assertEquals(2, processor.getCompilationUnit().getOrphanComments().size()); + } + + @Test + public void testSetPackageDeclaration() { + processor.setPackageDeclaration("com.example.service"); + assertEquals("com.example.service", + processor.getCompilationUnit().getPackageDeclaration().get().getNameAsString()); + } + + @Test + public void testCreateClass() { + processor.createClass("ServiceImpl", "Service", templateInput); + assertEquals("ServiceImpl", processor.getCompilationUnit().getTypes().get(0).getNameAsString()); + } +} diff --git a/sdk/clientcore/tools/annotation-processor/src/test/java/io/clientcore/tools/codegen/utils/PathBuilderTest.java b/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/utils/PathBuilderTest.java similarity index 82% rename from sdk/clientcore/tools/annotation-processor/src/test/java/io/clientcore/tools/codegen/utils/PathBuilderTest.java rename to sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/utils/PathBuilderTest.java index 21c4d9bd7d11..39748ce3e1fb 100644 --- a/sdk/clientcore/tools/annotation-processor/src/test/java/io/clientcore/tools/codegen/utils/PathBuilderTest.java +++ b/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/utils/PathBuilderTest.java @@ -1,11 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.tools.codegen.utils; +package io.clientcore.annotation.processor.utils; -import io.clientcore.tools.codegen.exceptions.MissingSubstitutionException; -import io.clientcore.tools.codegen.models.HttpRequestContext; -import io.clientcore.tools.codegen.models.Substitution; +import io.clientcore.annotation.processor.exceptions.MissingSubstitutionException; +import io.clientcore.annotation.processor.models.HttpRequestContext; +import io.clientcore.annotation.processor.models.Substitution; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -49,7 +49,7 @@ public void buildsPathWithEmptySubstitutions() { context.addSubstitution(new Substitution("endpoint", "myEndpoint")); try { - String result = PathBuilder.buildPath("https://{endpoint}/keys/{path1}", context); + PathBuilder.buildPath("https://{endpoint}/keys/{path1}", context); } catch (MissingSubstitutionException e) { assertEquals("Could not find substitution for 'path1' in method 'null'", e.getMessage()); } @@ -58,7 +58,7 @@ public void buildsPathWithEmptySubstitutions() { @Test public void buildsPathWithNullSubstitutions() { try { - String result = PathBuilder.buildPath("https://{endpoint}/keys/{path1}", null); + PathBuilder.buildPath("https://{endpoint}/keys/{path1}", null); } catch (NullPointerException e) { assertEquals("method cannot be null", e.getMessage()); } @@ -82,7 +82,8 @@ public void buildsPathWithMultipleQueryParameters() { context.addQueryParam("key2", "value2"); context.addQueryParam("key3", "value3"); String result = PathBuilder.buildPath("https://{endpoint}/keys", context); - assertEquals("\"https://\" + myEndpoint + \"/keys?key1=\" + value1 + \"&key2=\" + value2 + \"&key3=\" + value3", result); + assertEquals("\"https://\" + myEndpoint + \"/keys?key1=\" + value1 + \"&key2=\" + value2 + \"&key3=\" + value3", + result); } @Test @@ -121,7 +122,8 @@ public void buildsPathWithMultipleSameQueryParameters() { public void buildsPathWithClashingSubstitutionNames() { HttpRequestContext context = new HttpRequestContext(); context.addSubstitution(new Substitution("endpoint", "myEndpoint")); - assertThrows(IllegalArgumentException.class, () -> context.addSubstitution(new Substitution("endpoint", "myEndpoint2"))); + assertThrows(IllegalArgumentException.class, + () -> context.addSubstitution(new Substitution("endpoint", "myEndpoint2"))); } @Test @@ -134,14 +136,17 @@ public void buildsPathWithMultipleSubstitutionsAndQueryParameters() { context.addQueryParam("key2", "value2"); context.addQueryParam("key3", "value3"); String result = PathBuilder.buildPath("https://{endpoint}/keys/{path1}/{path2}", context); - assertEquals("\"https://\" + myEndpoint + \"/keys/\" + myPath + \"/\" + myPath2 + \"?key1=\" + value1 + \"&key2=\" + value2 + \"&key3=\" + value3", result); + assertEquals( + "\"https://\" + myEndpoint + \"/keys/\" + myPath + \"/\" + myPath2 + \"?key1=\" + value1 + \"&key2=\" + value2 + \"&key3=\" + value3", + result); } @Test public void buildsPathWithMissingSubstitution() { HttpRequestContext context = new HttpRequestContext(); context.addSubstitution(new Substitution("endpoint", "myEndpoint")); - assertThrows(MissingSubstitutionException.class, () -> PathBuilder.buildPath("https://{endpoint}/keys/{path1}", context)); + assertThrows(MissingSubstitutionException.class, + () -> PathBuilder.buildPath("https://{endpoint}/keys/{path1}", context)); } @Test @@ -149,7 +154,8 @@ public void buildsPathWithMissingQueryParameter() { HttpRequestContext context = new HttpRequestContext(); context.addSubstitution(new Substitution("endpoint", "myEndpoint")); context.addQueryParam("key1", "value1"); - assertThrows(MissingSubstitutionException.class, () -> PathBuilder.buildPath("https://{endpoint}/keys?key2={value2}", context)); + assertThrows(MissingSubstitutionException.class, + () -> PathBuilder.buildPath("https://{endpoint}/keys?key2={value2}", context)); } @Test @@ -160,14 +166,6 @@ public void buildsPathWithEmptySubstitutionValue() { assertEquals("\"https://\" + + \"/keys\"", result); } - @Test - public void buildsPathWithEmptyQueryParameterValue() { - HttpRequestContext context = new HttpRequestContext(); - context.addSubstitution(new Substitution("endpoint", "myEndpoint")); - context.addQueryParam("key1", ""); - assertThrows(IllegalArgumentException.class, () -> PathBuilder.buildPath("https://{endpoint}/keys", context)); - } - @Test public void buildsPathWithSubstitutionNotSurroundedBySlashes() { HttpRequestContext context = new HttpRequestContext(); @@ -328,7 +326,8 @@ public void buildsPathWithMultipleSubstitutionsFollowedByDifferentCharacters() { context.addSubstitution(new Substitution("path2", "myPath2")); context.addSubstitution(new Substitution("path3", "myPath3")); String result = PathBuilder.buildPath("https://{endpoint}*1a{path1}\u00A9 {path2}/keys/{path3}", context); - assertEquals("\"https://\" + myEndpoint + \"*1a\" + myPath1 + \"\u00A9 \" + myPath2 + \"/keys/\" + myPath3", result); + assertEquals("\"https://\" + myEndpoint + \"*1a\" + myPath1 + \"\u00A9 \" + myPath2 + \"/keys/\" + myPath3", + result); } @Test @@ -344,7 +343,8 @@ public void buildsPathWithNestedSubstitutions() { HttpRequestContext context = new HttpRequestContext(); context.addSubstitution(new Substitution("endpoint", "myEndpoint")); context.addSubstitution(new Substitution("path", "myPath")); - assertThrows(MissingSubstitutionException.class, () -> PathBuilder.buildPath("https://{{endpoint}/keys/{path}", context)); + assertThrows(MissingSubstitutionException.class, + () -> PathBuilder.buildPath("https://{{endpoint}/keys/{path}", context)); } @Test @@ -352,7 +352,8 @@ public void buildsPathWithMissingClosingBrace() { HttpRequestContext context = new HttpRequestContext(); context.addSubstitution(new Substitution("endpoint", "myEndpoint")); context.addSubstitution(new Substitution("path", "myPath")); - assertThrows(MissingSubstitutionException.class, () -> PathBuilder.buildPath("https://{endpoint/keys/{path}", context)); + assertThrows(MissingSubstitutionException.class, + () -> PathBuilder.buildPath("https://{endpoint/keys/{path}", context)); } @Test @@ -360,35 +361,40 @@ public void buildsPathWithMissingOpeningBrace() { HttpRequestContext context = new HttpRequestContext(); context.addSubstitution(new Substitution("endpoint", "myEndpoint")); context.addSubstitution(new Substitution("path", "myPath")); - assertThrows(MissingSubstitutionException.class, () -> PathBuilder.buildPath("https://endpoint}/keys/{path}", context)); + assertThrows(MissingSubstitutionException.class, + () -> PathBuilder.buildPath("https://endpoint}/keys/{path}", context)); } @Test public void buildsPathWithSubstitutionContainingOpeningBrace() { HttpRequestContext context = new HttpRequestContext(); context.addSubstitution(new Substitution("endpoint{", "myEndpoint")); - assertThrows(MissingSubstitutionException.class, () -> PathBuilder.buildPath("https://{endpoint{/keys", context)); + assertThrows(MissingSubstitutionException.class, + () -> PathBuilder.buildPath("https://{endpoint{/keys", context)); } @Test public void buildsPathWithSubstitutionContainingClosingBrace() { HttpRequestContext context = new HttpRequestContext(); context.addSubstitution(new Substitution("endpoint}", "myEndpoint")); - assertThrows(MissingSubstitutionException.class, () -> PathBuilder.buildPath("https://{endpoint}/keys", context)); + assertThrows(MissingSubstitutionException.class, + () -> PathBuilder.buildPath("https://{endpoint}/keys", context)); } @Test public void buildsPathWithSubstitutionContainingBothBraces() { HttpRequestContext context = new HttpRequestContext(); context.addSubstitution(new Substitution("endpoint{}", "myEndpoint")); - assertThrows(MissingSubstitutionException.class, () -> PathBuilder.buildPath("https://{endpoint{}}/keys", context)); + assertThrows(MissingSubstitutionException.class, + () -> PathBuilder.buildPath("https://{endpoint{}}/keys", context)); } @Test public void buildsPathWithSubstitutionContainingMultipleBraces() { HttpRequestContext context = new HttpRequestContext(); context.addSubstitution(new Substitution("endpoint{{}}", "myEndpoint")); - assertThrows(MissingSubstitutionException.class, () -> PathBuilder.buildPath("https://{endpoint{{}}}/keys", context)); + assertThrows(MissingSubstitutionException.class, + () -> PathBuilder.buildPath("https://{endpoint{{}}}/keys", context)); } @Test @@ -429,13 +435,50 @@ public void buildsPathWithoutProtocolWithSubstitutionsAndQueryParameters() { // TODO: Currently, the context adds subsitition using the parameter name as key so i // Is this a valid case? -// @Test -// public void buildsPathWithHostAndPathUsingSameSubstitutionName() { -// HttpRequestContext context = new HttpRequestContext(); -// context.addSubstitution(new Substitution("sub1", "hostSub1")); -// context.addSubstitution(new Substitution("sub1", "pathSub1")); -// -// String result = PathBuilder.buildPath("https://{sub1}.host.com/keys/{sub1}", context); -// assertEquals("\"https://\" + hostSub1 + \".host.com/keys/\" + pathSub1", result); -// } + // @Test + // public void buildsPathWithHostAndPathUsingSameSubstitutionName() { + // HttpRequestContext context = new HttpRequestContext(); + // context.addSubstitution(new Substitution("sub1", "hostSub1")); + // context.addSubstitution(new Substitution("sub1", "pathSub1")); + // + // String result = PathBuilder.buildPath("https://{sub1}.host.com/keys/{sub1}", context); + // assertEquals("\"https://\" + hostSub1 + \".host.com/keys/\" + pathSub1", result); + // } + + @Test + public void buildsPathWithEmptyQueryParameterKey() { + HttpRequestContext context = new HttpRequestContext(); + context.addSubstitution(new Substitution("endpoint", "myEndpoint")); + context.addQueryParam("", "value1"); + assertThrows(IllegalArgumentException.class, () -> PathBuilder.buildPath("https://{endpoint}/keys", context)); + } + + @Test + public void buildsPathWithNullQueryParameterValue() { + HttpRequestContext context = new HttpRequestContext(); + context.addSubstitution(new Substitution("endpoint", "myEndpoint")); + context.addQueryParam("key1", null); + String result = PathBuilder.buildPath("https://{endpoint}/keys", context); + assertEquals("\"https://\" + myEndpoint + \"/keys\"", result); + } + + @Test + public void buildsPathWithNullQueryParameterKey() { + HttpRequestContext context = new HttpRequestContext(); + context.addSubstitution(new Substitution("endpoint", "myEndpoint")); + context.addQueryParam(null, "value1"); + assertThrows(IllegalArgumentException.class, () -> PathBuilder.buildPath("https://{endpoint}/keys", context)); + } + + @Test + public void buildsPathWithMixedQueryParameters() { + HttpRequestContext context = new HttpRequestContext(); + context.addSubstitution(new Substitution("endpoint", "myEndpoint")); + context.addQueryParam("key1", "value1"); + context.addQueryParam("key2", null); + context.addQueryParam("key3", ""); + context.addQueryParam("key4", "value4"); + String result = PathBuilder.buildPath("https://{endpoint}/keys", context); + assertEquals("\"https://\" + myEndpoint + \"/keys?key1=\" + value1 + \"&key4=\" + value4", result); + } } diff --git a/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/utils/ResponseBodyModeGenerationTest.java b/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/utils/ResponseBodyModeGenerationTest.java new file mode 100644 index 000000000000..b078bacb4dc0 --- /dev/null +++ b/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/utils/ResponseBodyModeGenerationTest.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.annotation.processor.utils; + +import com.github.javaparser.ast.stmt.BlockStmt; +import io.clientcore.annotation.processor.mocks.MockDeclaredType; +import io.clientcore.annotation.processor.models.HttpRequestContext; +import io.clientcore.core.http.models.HttpMethod; +import org.junit.jupiter.api.Test; + +import javax.lang.model.type.TypeKind; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * This class tests ResponseBodyModeGeneration methods. + */ +public class ResponseBodyModeGenerationTest { + + @Test + void generateResponseBodyModeWithRequestOptions() { + BlockStmt body = new BlockStmt(); + ResponseBodyModeGeneration.generateResponseBodyMode(body); + assertTrue(body.toString() + .contains( + "ResponseBodyMode responseBodyMode = getOrDefaultResponseBodyMode(httpRequest.getRequestOptions());")); + } + + @Test + void generateResponseBodyModeWithoutRequestOptions() { + BlockStmt body = new BlockStmt(); + ResponseBodyModeGeneration.generateResponseBodyMode(body); + assertTrue(body.toString() + .contains( + "ResponseBodyMode responseBodyMode = getOrDefaultResponseBodyMode(httpRequest.getRequestOptions());")); + } + + @Test + void generateResponseHandlingWithVoidReturnType() { + BlockStmt body = new BlockStmt(); + HttpRequestContext context = new HttpRequestContext(); + context.setHttpMethod(HttpMethod.DELETE); + MockDeclaredType returnType = new MockDeclaredType(TypeKind.VOID, "void"); + context.setMethodReturnType(returnType); + ResponseBodyModeGeneration.generateResponseHandling(body, returnType, context); + assertFalse(body.toString().contains("return")); + } +} diff --git a/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/utils/TypeConverterTest.java b/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/utils/TypeConverterTest.java new file mode 100644 index 000000000000..fbae0d040493 --- /dev/null +++ b/sdk/clientcore/annotation-processor/src/test/java/io/clientcore/annotation/processor/utils/TypeConverterTest.java @@ -0,0 +1,210 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.annotation.processor.utils; + +import io.clientcore.annotation.processor.mocks.MockDeclaredType; +import io.clientcore.annotation.processor.mocks.MockTypeMirror; +import org.junit.jupiter.api.Test; + +import javax.lang.model.element.AnnotationMirror; +import javax.lang.model.type.ArrayType; +import javax.lang.model.type.DeclaredType; +import javax.lang.model.type.PrimitiveType; +import javax.lang.model.type.TypeKind; +import javax.lang.model.type.TypeMirror; +import javax.lang.model.type.TypeVisitor; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.util.Collections; +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.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class TypeConverterTest { + + @Test + public void toReflectTypePrimitiveBoolean() { + TypeMirror type = mockPrimitiveType(TypeKind.BOOLEAN); + Type result = TypeConverter.toReflectType(type); + assertEquals(boolean.class, result); + } + + @Test + public void toReflectTypePrimitiveInt() { + TypeMirror type = mockPrimitiveType(TypeKind.INT); + Type result = TypeConverter.toReflectType(type); + assertEquals(int.class, result); + } + + @Test + public void toReflectTypeVoid() { + TypeMirror type = mockPrimitiveType(TypeKind.VOID); + Type result = TypeConverter.toReflectType(type); + assertEquals(void.class, result); + } + + @Test + public void toReflectTypeArray() { + TypeMirror componentType = mockPrimitiveType(TypeKind.INT); + ArrayType arrayType = mockArrayType(componentType); + + Type result = TypeConverter.toReflectType(arrayType); + assertEquals("int[]", result.getTypeName()); + } + + @Test + public void toReflectTypeDeclaredType() { + DeclaredType declaredType = new MockDeclaredType(TypeKind.DECLARED, "java.util.List"); + Type result = TypeConverter.toReflectType(declaredType); + assertNotNull(result); + } + + @Test + public void getPrimitiveClassPrimitiveLong() { + TypeMirror type = mockPrimitiveType(TypeKind.LONG); + Class result = TypeConverter.getPrimitiveClass(type); + assertEquals(long.class, result); + } + + @Test + public void getEntityTypePrimitiveFloat() { + TypeMirror type = mockPrimitiveType(TypeKind.FLOAT); + Type result = TypeConverter.getEntityType(type); + assertEquals(float.class, result); + } + + @Test + public void isResponseTypeResponseType() { + DeclaredType responseType = new MockDeclaredType(TypeKind.DECLARED, "io.clientcore.core.http.models.Response"); + boolean result = TypeConverter.isResponseType(responseType); + assertTrue(result); + } + + @Test + public void isResponseTypeNonResponseType() { + DeclaredType declaredType = new MockDeclaredType(TypeKind.ARRAY, "java.util.List"); + boolean result = TypeConverter.isResponseType(declaredType); + assertFalse(result); + } + + @Test + public void getAstTypePrimitiveDouble() { + TypeMirror type = mockPrimitiveType(TypeKind.DOUBLE); + com.github.javaparser.ast.type.Type result = TypeConverter.getAstType(type); + assertEquals("double", result.toString()); + } + + @Test + public void getAstTypeArray() { + TypeMirror componentType = new MockDeclaredType(TypeKind.DECLARED, "java.lang.String"); + ArrayType arrayType = mockArrayType(componentType); + com.github.javaparser.ast.type.Type result = TypeConverter.getAstType(arrayType); + assertEquals("java.lang.String[]", result.toString()); + } + + @Test + public void getAstTypeDeclaredType() { + DeclaredType declaredType = new MockDeclaredType(TypeKind.DECLARED, "java.util.List"); + com.github.javaparser.ast.type.Type result = TypeConverter.getAstType(declaredType); + assertTrue(result.toString().contains("java.util.List")); + } + + @Test + public void handleArrayType() { + ArrayType arrayType = mockArrayType(mockPrimitiveType(TypeKind.INT)); + Type result = TypeConverter.handleArrayType(arrayType); + assertTrue(result instanceof Class); + assertTrue(((Class) result).isArray()); + } + + @Test + public void handleDeclaredType() { + DeclaredType declaredType = new MockDeclaredType(TypeKind.DECLARED, "java.util.List"); + Type result = TypeConverter.handleDeclaredType(declaredType); + assertNotNull(result); + } + + @Test + public void handleDeclaredTypeGeneric() { + DeclaredType declaredType = new MockDeclaredType(TypeKind.DECLARED, "java.util.Map"); + Type result = TypeConverter.handleDeclaredType(declaredType); + assertNotNull(result); + } + + @Test + public void toReflectTypeUnsupportedType() { + TypeMirror unsupportedType = new MockTypeMirror(TypeKind.NONE, null); + IllegalArgumentException exception + = assertThrows(IllegalArgumentException.class, () -> TypeConverter.toReflectType(unsupportedType)); + assertEquals("Unsupported type: " + unsupportedType, exception.getMessage()); + } + + static PrimitiveType mockPrimitiveType(TypeKind kind) { + return new PrimitiveType() { + @Override + public TypeKind getKind() { + return kind; + } + + @Override + public List getAnnotationMirrors() { + return Collections.emptyList(); + } + + @Override + public A getAnnotation(Class annotationType) { + return null; + } + + @Override + @SuppressWarnings("unchecked") + public A[] getAnnotationsByType(Class annotationType) { + return (A[]) java.lang.reflect.Array.newInstance(annotationType, 0); + } + + @Override + public R accept(TypeVisitor v, P p) { + return null; + } + }; + } + + static ArrayType mockArrayType(TypeMirror componentType) { + return new ArrayType() { + @Override + public List getAnnotationMirrors() { + return Collections.emptyList(); + } + + @Override + public A getAnnotation(Class annotationType) { + return null; + } + + @SuppressWarnings("unchecked") + public A[] getAnnotationsByType(Class annotationType) { + return (A[]) java.lang.reflect.Array.newInstance(annotationType, 0); + } + + @Override + public TypeMirror getComponentType() { + return componentType; + } + + @Override + public TypeKind getKind() { + return TypeKind.ARRAY; + } + + @Override + public R accept(TypeVisitor v, P p) { + return null; + } + }; + } +} diff --git a/sdk/clientcore/ci.yml b/sdk/clientcore/ci.yml index 9089ac38c77f..77a55c8ef885 100644 --- a/sdk/clientcore/ci.yml +++ b/sdk/clientcore/ci.yml @@ -9,6 +9,8 @@ trigger: paths: include: - sdk/clientcore/ + exclude: + - sdk/clientcore/annotation-processor/ pr: branches: @@ -20,6 +22,8 @@ pr: paths: include: - sdk/clientcore/ + exclude: + - sdk/clientcore/annotation-processor/ parameters: - name: release_core @@ -46,6 +50,8 @@ extends: groupId: io.clientcore safeName: core releaseInBatch: ${{ parameters.release_core }} + triggeringPaths: + - /sdk/parents/clientcore-parent - name: http-okhttp3 groupId: io.clientcore safeName: httpokhttp3 diff --git a/sdk/clientcore/core/CHANGELOG.md b/sdk/clientcore/core/CHANGELOG.md index 60846ec429e5..c3f1e2b7f885 100644 --- a/sdk/clientcore/core/CHANGELOG.md +++ b/sdk/clientcore/core/CHANGELOG.md @@ -1,5 +1,54 @@ # Release History +## 1.0.0-beta.7 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + +## 1.0.0-beta.6 (2025-03-10) + +### Breaking Changes + +- `JsonNumber` previously would use `float` when the floating point number was small enough to fit in `float` but it + now aligns behavior with `JsonReader.readUntyped()` where `double` will be the smallest floating point type used. + This aligns with floating point number behavior in Java where `double` is the default if no type is specified. +- Support for special numeric `INF`, `-INF`, and `+INF` values have been removed to align with behaviors of `Float` + and `Double` in Java where only the `Infinity` variants are supported. + +### Bugs Fixed + +- `JsonReader.readUntyped()` had incomplete support for untyped numerics. Numerics too large for `double` and `long` are + now supported and a bug where exponents were not being parsed correctly is fixed. + +## 1.0.0-beta.5 (2025-02-14) + +### Features Added +- Support for deserialization of list of `JsonSerializable` types [#44208](https://github.com/Azure/azure-sdk-for-java/pull/44208) + +### Breaking Changes +- API updates to refactor packages and remove unused APIs [#44210](https://github.com/Azure/azure-sdk-for-java/pull/44210) + +## 1.0.0-beta.4 (2025-02-13) + +### Features Added +- Introduced Union Type [#43778](https://github.com/Azure/azure-sdk-for-java/pull/43778) +- Added support for convenience APIs for generic instrumentation plumbing when no special conventions defined [#44006](https://github.com/Azure/azure-sdk-for-java/pull/44006) +- Added metrics support and reporting http request duration in instrumentation policy [#43957](https://github.com/Azure/azure-sdk-for-java/pull/43957) + +### Breaking Changes +- Streamline APIs used when creating an HttpPipeline using HttpPipelineBuilder to help guide users through creating a high quality HttpPipeline. [#43504](https://github.com/Azure/azure-sdk-for-java/pull/43504) + +## 1.0.0-beta.3 (2025-01-27) + +### Breaking Changes +- Downgraded clientcore baseline from Java 17 to Java 8. +- Updated clientcore into a multi-release JAR. The Java 8 version of the JAR will be used for Java 8-16, and the Java 17 version of the JAR will be used for Java 17+. + ## 1.0.0-beta.2 (2025-01-17) ### Features Added diff --git a/sdk/clientcore/core/README.md b/sdk/clientcore/core/README.md index 4b7aa148155a..ad84e6b23625 100644 --- a/sdk/clientcore/core/README.md +++ b/sdk/clientcore/core/README.md @@ -25,7 +25,7 @@ add the direct dependency to your project as follows. io.clientcore core - 1.0.0-beta.2 + 1.0.0-beta.6 ``` [//]: # ({x-version-update-end}) @@ -67,7 +67,7 @@ could be called indefinitely returning the same integer without error until `nex forward. `JsonReader` allows for type conversion between JSON types, such as trying to convert a JSON string to a number or vice -versa, and for commonly used nonstandard JSON values, such as `NaN`, `INF`, `-INF`, `Infinity`, and `-Infinity`. +versa, and for commonly used nonstandard JSON values, such as `NaN`, `Infinity`, `+Infinity`, and `-Infinity`. `JsonReader` doesn't take ownership of the JSON input source and therefore doesn't close any resources if the JSON is provided using an `InputStream` or `Reader`. @@ -84,7 +84,7 @@ and objects, APIs for writing JSON. `JsonWriter` is provided to allow for any un such as Jackson or GSON, as long as the implementation passes the tests provided by the package's test-jar (`JsonWriterContractTests`). -`JsonWriter` allows for commonly used nonstandard JSON values, such as `NaN`, `INF`, `-INF`, `Infinity`, and +`JsonWriter` allows for commonly used nonstandard JSON values, such as `NaN`, `Infinity`, `+Infinity`, and `-Infinity`, to be written using `writeNumberField` or `writeRawValue`. `JsonWriter` doesn't write null `byte[]`, `Boolean`, `Number`, or `String` values when written as a field, @@ -115,7 +115,7 @@ by this package if an implementation isn't found on the classpath. #### JsonOptions `JsonOptions` contains configurations that must be respected by all implementations of `JsonReader`s and `JsonWriter`s. -At this time, there's only one configuration for determining whether non-numeric numbers, `NaN`, `INF`, `-INF`, `Infinity`, +At this time, there's only one configuration for determining whether non-numeric numbers, `NaN`, `Infinity`, `+Infinity`, and `-Infinity` are supported in JSON reading and writing with a default setting of `true`, that non-numeric numbers are allowed. diff --git a/sdk/clientcore/core/checkstyle-suppressions.xml b/sdk/clientcore/core/checkstyle-suppressions.xml index 88e7a72d28fe..cb5fea8744a3 100644 --- a/sdk/clientcore/core/checkstyle-suppressions.xml +++ b/sdk/clientcore/core/checkstyle-suppressions.xml @@ -3,34 +3,32 @@ - + - - - + + + - - - + - - + - + + + - - + - + diff --git a/sdk/clientcore/core/pom.xml b/sdk/clientcore/core/pom.xml index a145023a8871..2672805816f1 100644 --- a/sdk/clientcore/core/pom.xml +++ b/sdk/clientcore/core/pom.xml @@ -8,14 +8,14 @@ io.clientcore clientcore-parent - 1.0.0-beta.1 + 1.0.0-beta.3 ../../parents/clientcore-parent io.clientcore core jar - 1.0.0-beta.2 + 1.0.0-beta.7 Core Library for building Java client libraries for accessing web services. This library contains core types for building Java client libraries for accessing web services. @@ -37,28 +37,27 @@ UTF-8 - 0.50 - 0.50 + 0.70 + 0.65 - --add-opens io.clientcore.core/io.clientcore.core.annotation=ALL-UNNAMED - --add-opens io.clientcore.core/io.clientcore.core.credential=ALL-UNNAMED + --add-opens io.clientcore.core/io.clientcore.core.annotations=ALL-UNNAMED + --add-opens io.clientcore.core/io.clientcore.core.credentials=ALL-UNNAMED --add-opens io.clientcore.core/io.clientcore.core.http=ALL-UNNAMED - --add-opens io.clientcore.core/io.clientcore.core.http.annotation=ALL-UNNAMED + --add-opens io.clientcore.core/io.clientcore.core.http.annotations=ALL-UNNAMED --add-opens io.clientcore.core/io.clientcore.core.http.client=ALL-UNNAMED - --add-opens io.clientcore.core/io.clientcore.core.http.exception=ALL-UNNAMED + --add-opens io.clientcore.core/io.clientcore.core.http.exceptions=ALL-UNNAMED --add-opens io.clientcore.core/io.clientcore.core.http.models=ALL-UNNAMED --add-opens io.clientcore.core/io.clientcore.core.http.pipeline=ALL-UNNAMED --add-opens io.clientcore.core/io.clientcore.core.implementation=ALL-UNNAMED --add-opens io.clientcore.core/io.clientcore.core.implementation.http=ALL-UNNAMED --add-opens io.clientcore.core/io.clientcore.core.implementation.http.rest=ALL-UNNAMED --add-opens io.clientcore.core/io.clientcore.core.implementation.http.serializer=ALL-UNNAMED - --add-opens io.clientcore.core/io.clientcore.core.implementation.util=ALL-UNNAMED + --add-opens io.clientcore.core/io.clientcore.core.implementation.utils=ALL-UNNAMED --add-opens io.clientcore.core/io.clientcore.core.models=ALL-UNNAMED --add-opens io.clientcore.core/io.clientcore.core.shared=ALL-UNNAMED - --add-opens io.clientcore.core/io.clientcore.core.util=ALL-UNNAMED - --add-opens io.clientcore.core/io.clientcore.core.util.configuration=ALL-UNNAMED - --add-opens io.clientcore.core/io.clientcore.core.util.serializer=ALL-UNNAMED + --add-opens io.clientcore.core/io.clientcore.core.utils=ALL-UNNAMED + --add-opens io.clientcore.core/io.clientcore.core.utils.configuration=ALL-UNNAMED --add-reads io.clientcore.core=ALL-UNNAMED @@ -139,6 +138,18 @@ test-jar + + + default-jar + package + + + + true + + + + @@ -161,7 +172,7 @@ org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 @@ -197,6 +208,38 @@ + + java12-plus + + [12,) + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.13.0 + + + java12-plus-mr + + compile + + + 12 + + ${project.basedir}/src/main/java12 + + true + + + + + + + + jmh-benchmark diff --git a/sdk/clientcore/core/spotbugs-exclude.xml b/sdk/clientcore/core/spotbugs-exclude.xml index a94ed75f922d..bdba21aa15ae 100644 --- a/sdk/clientcore/core/spotbugs-exclude.xml +++ b/sdk/clientcore/core/spotbugs-exclude.xml @@ -13,11 +13,16 @@ - + + + - + + + + @@ -26,90 +31,94 @@ - - - - - - - - + + + + + + + + + + + + + + + - - - - - + + + + - - - - - + + - - - - - - - - - - + + + - - + - - - - + + + + + + + + + - + + + + + - + - + - - + + - + @@ -117,23 +126,24 @@ - - + + + + + + + - - - - + - - + @@ -149,7 +159,7 @@ - + @@ -167,10 +177,14 @@ - + + + + + @@ -189,16 +203,19 @@ - - + + + + + @@ -218,7 +235,9 @@ - + + + @@ -230,62 +249,82 @@ - + + + + + - - + + + + + + + + + + + - + - - - - + + - + - - - - - - + + + + + + + - + + + + + - + + + + + - + @@ -302,7 +341,7 @@ - + @@ -334,13 +373,17 @@ + + + + - - + + @@ -356,16 +399,28 @@ + + + + + + + + + + + + - + + - + - - + @@ -378,12 +433,12 @@ - - - - - - + + + + + + @@ -396,22 +451,10 @@ - + - - - - - - - - - - - - diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/annotation/Metadata.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/annotation/Metadata.java deleted file mode 100644 index 8e5669c04d1c..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/annotation/Metadata.java +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.annotation; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.CONSTRUCTOR; -import static java.lang.annotation.ElementType.FIELD; -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.SOURCE; - -/** - * Annotation that defines the characteristics of a class. - */ -@Retention(SOURCE) -@Target({ TYPE, METHOD, CONSTRUCTOR, FIELD }) -public @interface Metadata { - /** - * The conditions that apply to the annotated class. - * - * @return The conditions that apply to the annotated class. - */ - TypeConditions[] conditions() default { }; - - /** - * Indicates whether the class was automatically generated. - * - * @return {@code true} if the class is automatically generated, {@code false} otherwise. - */ - boolean generated() default false; -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/annotation/TypeConditions.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/annotation/TypeConditions.java deleted file mode 100644 index 2353f761f79b..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/annotation/TypeConditions.java +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.annotation; - -/** - * Enum that defines the conditions that can be applied to a class. - */ -public enum TypeConditions { - /** - * Indicates that a class is expected to provide a fluent API to end users. If a class is marked as this, checks can - * be made to ensure all APIs meet this expectation. Similarly, classes that are not marked as fluent should not - * have fluent APIs. - */ - FLUENT, - - /** - * Indicates that a class is immutable. If a class is marked as this, checks can be made to ensure all fields in - * the class are final. - */ - IMMUTABLE -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/annotation/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/annotation/package-info.java deleted file mode 100644 index 672105f711be..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/annotation/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - * Package containing annotations for client side classes and methods. - */ -package io.clientcore.core.annotation; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/annotations/Metadata.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/annotations/Metadata.java new file mode 100644 index 000000000000..7b14e78e2d8e --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/annotations/Metadata.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.annotations; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.CONSTRUCTOR; +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.SOURCE; + +/** + * Annotation that defines the characteristics of a class. + */ +@Retention(SOURCE) +@Target({ TYPE, METHOD, CONSTRUCTOR, FIELD }) +public @interface Metadata { + /** + * The properties that apply to the annotated class. + * + * @return The properties that apply to the annotated class. + */ + MetadataProperties[] properties() default { }; +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/annotations/MetadataProperties.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/annotations/MetadataProperties.java new file mode 100644 index 000000000000..b1feb8af4f77 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/annotations/MetadataProperties.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.annotations; + +/** + * Enum that defines the conditions that can be applied to a class. + */ +public enum MetadataProperties { + /** + * Indicates that a class is expected to provide a fluent API to end users. If a class is marked as this, checks can + * be made to ensure all APIs meet this expectation. Similarly, classes that are not marked as fluent should not + * have fluent APIs. + */ + FLUENT, + + /** + * Indicates that a class is immutable. If a class is marked as this, checks can be made to ensure all fields in + * the class are final. + */ + IMMUTABLE, + + /** + * Indicates that a class is generated and will be overwritten by the code generator if modified. + */ + GENERATED +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/annotation/ReturnType.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/annotations/ReturnType.java similarity index 76% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/annotation/ReturnType.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/annotations/ReturnType.java index f16f0626e76e..a512985d1093 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/annotation/ReturnType.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/annotations/ReturnType.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.annotation; +package io.clientcore.core.annotations; /** * Enumeration of return types used with {@link ServiceMethod} annotation to indicate if a method is expected to return @@ -21,5 +21,10 @@ public enum ReturnType { /** * Server Sent Event operation return type. */ - SERVER_SENT_EVENT + SERVER_SENT_EVENT, + + /** + * Long-running operation return type. + */ + LONG_RUNNING_OPERATION; } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/annotation/ServiceClient.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/annotations/ServiceClient.java similarity index 96% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/annotation/ServiceClient.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/annotations/ServiceClient.java index e7244266e3dd..594ce477070c 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/annotation/ServiceClient.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/annotations/ServiceClient.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.annotation; +package io.clientcore.core.annotations; import java.lang.annotation.Retention; import java.lang.annotation.Target; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/annotation/ServiceClientBuilder.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/annotations/ServiceClientBuilder.java similarity index 94% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/annotation/ServiceClientBuilder.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/annotations/ServiceClientBuilder.java index 78d8f7648d9e..a7159dbed68d 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/annotation/ServiceClientBuilder.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/annotations/ServiceClientBuilder.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.annotation; +package io.clientcore.core.annotations; import java.lang.annotation.Retention; import java.lang.annotation.Target; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/annotation/ServiceInterface.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/annotations/ServiceInterface.java similarity index 94% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/annotation/ServiceInterface.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/annotations/ServiceInterface.java index 493ffacc18c7..8e6e4b83a234 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/annotation/ServiceInterface.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/annotations/ServiceInterface.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.annotation; +package io.clientcore.core.annotations; -import io.clientcore.core.http.annotation.HostParam; +import io.clientcore.core.http.annotations.HostParam; import java.lang.annotation.Retention; import java.lang.annotation.Target; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/annotation/ServiceMethod.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/annotations/ServiceMethod.java similarity index 94% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/annotation/ServiceMethod.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/annotations/ServiceMethod.java index 835734668348..b73e07c2c247 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/annotation/ServiceMethod.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/annotations/ServiceMethod.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.annotation; +package io.clientcore.core.annotations; import java.lang.annotation.Retention; import java.lang.annotation.Target; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/annotations/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/annotations/package-info.java new file mode 100644 index 000000000000..844543bb25ab --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/annotations/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing annotations for client side classes and methods. + */ +package io.clientcore.core.annotations; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/credential/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/credential/package-info.java deleted file mode 100644 index bfda6982f67a..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/credential/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - * Package containing basic credential classes for authentication purposes. - */ -package io.clientcore.core.credential; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/credential/KeyCredential.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/credentials/KeyCredential.java similarity index 90% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/credential/KeyCredential.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/credentials/KeyCredential.java index 3f1ccc8a8e84..4ded847c326f 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/credential/KeyCredential.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/credentials/KeyCredential.java @@ -1,8 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.credential; +package io.clientcore.core.credentials; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; import io.clientcore.core.instrumentation.logging.ClientLogger; import java.util.Objects; @@ -10,6 +12,7 @@ /** * Represents a credential that uses a key to authenticate. */ +@Metadata(properties = MetadataProperties.FLUENT) public class KeyCredential { // KeyCredential is a commonly used credential type, use a static logger. private static final ClientLogger LOGGER = new ClientLogger(KeyCredential.class); diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/credentials/NamedKey.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/credentials/NamedKey.java new file mode 100644 index 000000000000..4f4513104925 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/credentials/NamedKey.java @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.credentials; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; + +/** + * Represents a credential bag containing the key and the name of the key. + * + * @see NamedKeyCredential + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public final class NamedKey { + private final String name; + private final String key; + + NamedKey(String name, String key) { + this.name = name; + this.key = key; + } + + /** + * Retrieves the key. + * + * @return The key. + */ + public String getKey() { + return key; + } + + /** + * Retrieves the name associated with the key. + * + * @return The name of the key. + */ + public String getName() { + return name; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/credentials/NamedKeyCredential.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/credentials/NamedKeyCredential.java new file mode 100644 index 000000000000..4ced3a06f7d7 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/credentials/NamedKeyCredential.java @@ -0,0 +1,102 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.credentials; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.instrumentation.logging.ClientLogger; + +import java.util.Objects; + +/** + *

        + * The {@link NamedKeyCredential} is used to authenticate and authorize requests made to services. + * It is specifically designed for scenarios where you need to authenticate using a key with a name identifier + * associated with it. + *

        + * + *

        + * A key is a unique identifier or token that is associated with a specific user or application. It serves as a + * simple form of authentication to ensure that only authorized clients can access the protected resources or APIs. + * This authentication is commonly used for accessing certain services. Each service may have its own specific way of + * using API keys, but the general concept remains the same. + *

        + * + *

        + * The {@link NamedKeyCredential} can be created for keys which have a name + * identifier associated with them. + *

        + * + *

        + * Code Samples + *

        + * + *

        + * Create a named credential for a service specific sas key. + *

        + * + * + *
        + * // Create a named credential for a service.
        + * NamedKeyCredential namedKeyCredential = new NamedKeyCredential("SERVICE-KEY-NAME", "SERVICE-KEY");
        + * 
        + * + * + * @see io.clientcore.core.credentials + */ +@Metadata(properties = MetadataProperties.FLUENT) +public final class NamedKeyCredential { + // NamedKeyCredential is a commonly used credential type, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(NamedKeyCredential.class); + + private volatile NamedKey credentials; + + /** + * Creates a credential with specified {@code name} that authorizes request with the given {@code key}. + * + * @param name The name of the key credential. + * @param key The key used to authorize requests. + * @throws NullPointerException If {@code key} or {@code name} is {@code null}. + * @throws IllegalArgumentException If {@code key} or {@code name} is an empty string. + */ + public NamedKeyCredential(String name, String key) { + validateInputParameters(name, key); + this.credentials = new NamedKey(name, key); + } + + /** + * Retrieves the {@link NamedKey} containing the name and key associated with this credential. + * + * @return The {@link NamedKey} containing the name and key . + */ + public NamedKey getNamedKey() { + return this.credentials; + } + + /** + * Rotates the {@code name} and {@code key} associated to this credential. + * + * @param name The new name of the key credential. + * @param key The new key to be associated with this credential. + * @return The updated {@code NamedKeyCredential} object. + * @throws NullPointerException If {@code key} or {@code name} is {@code null}. + * @throws IllegalArgumentException If {@code key} or {@code name} is an empty string. + */ + public NamedKeyCredential update(String name, String key) { + validateInputParameters(name, key); + this.credentials = new NamedKey(name, key); + return this; + } + + private void validateInputParameters(String name, String key) { + Objects.requireNonNull(name, "'name' cannot be null."); + Objects.requireNonNull(key, "'key' cannot be null."); + if (name.isEmpty()) { + throw LOGGER.logThrowableAsError(new IllegalArgumentException("'name' cannot be empty.")); + } + if (key.isEmpty()) { + throw LOGGER.logThrowableAsError(new IllegalArgumentException("'key' cannot be empty.")); + } + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/credentials/oauth/AccessToken.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/credentials/oauth/AccessToken.java new file mode 100644 index 000000000000..981306a8c5a7 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/credentials/oauth/AccessToken.java @@ -0,0 +1,118 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.credentials.oauth; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; + +import java.time.OffsetDateTime; + +/** + *

        + * Represents an immutable access token with a token string and an expiration time. + *

        + * + *

        + * Access Tokens are obtained through the authentication process, where the user or application presents valid + * credentials (either a secret or a managed identity) to the authentication source. + * The authentication source then verifies the credentials and issues an Access Token, which is a time-limited token + * that grants access to the requested resource. + *

        + * + *

        + * Once an Access Token is obtained, it can be included in the Authorization header of HTTP requests to + * authenticate and authorize requests. + *

        + * + * @see io.clientcore.core.credentials + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public class AccessToken { + private final String token; + private final OffsetDateTime expiresAt; + private final OffsetDateTime refreshAt; + private final AccessTokenType tokenType; + + /** + * Creates an access token instance. + * Defaults to {@link AccessTokenType#BEARER} for {@code tokenType}. + * + * @param token the token string. + * @param expiresAt the expiration time. + */ + public AccessToken(String token, OffsetDateTime expiresAt) { + this(token, expiresAt, null, AccessTokenType.BEARER); + } + + /** + * Creates an access token instance. + * Defaults to {@link AccessTokenType#BEARER} for {@code tokenType}. + * + * @param token the token string. + * @param expiresAt the expiration time. + * @param refreshAt the next token refresh time. + */ + public AccessToken(String token, OffsetDateTime expiresAt, OffsetDateTime refreshAt) { + this(token, expiresAt, refreshAt, AccessTokenType.BEARER); + } + + /** + * Creates an access token instance. + * + * @param token the token string. + * @param expiresAt the expiration time. + * @param refreshAt the next token refresh time. + * @param tokenType the type of token. + */ + public AccessToken(String token, OffsetDateTime expiresAt, OffsetDateTime refreshAt, AccessTokenType tokenType) { + this.token = token; + this.expiresAt = expiresAt; + this.refreshAt = refreshAt; + this.tokenType = tokenType; + } + + /** + * Gets the token. + * + * @return The token. + */ + public String getToken() { + return token; + } + + /** + * Gets the time when the token expires, in UTC. + * + * @return The time when the token expires, in UTC. + */ + public OffsetDateTime getExpiresAt() { + return expiresAt; + } + + /** + * Gets the time when the token should refresh next, in UTC. + * @return The time when the token should refresh next, in UTC. + */ + public OffsetDateTime getRefreshAt() { + return refreshAt; + } + + /** + * Whether the token has expired. + * + * @return Whether the token has expired. + */ + public boolean isExpired() { + return OffsetDateTime.now().isAfter(expiresAt); + } + + /** + * Gets the token type. + * + * @return The {@link AccessTokenType} representing the Token Type. + */ + public AccessTokenType getTokenType() { + return tokenType; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/credentials/oauth/AccessTokenType.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/credentials/oauth/AccessTokenType.java new file mode 100644 index 000000000000..4493e7771881 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/credentials/oauth/AccessTokenType.java @@ -0,0 +1,108 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.credentials.oauth; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.utils.ExpandableEnum; + +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Represents Access Token types. + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public final class AccessTokenType implements ExpandableEnum { + private static final Map VALUES = new ConcurrentHashMap<>(); + private final String caseSensitive; + private final String caseInsensitive; + + private AccessTokenType(String name) { + this.caseSensitive = name; + this.caseInsensitive = name.toLowerCase(); + } + + @Override + public String getValue() { + return caseSensitive; + } + + /** + * Gets the {@link AccessTokenType} based on the name passed into {@link #fromString(String)}. + * + * @return The token type based on the construction of this {@link AccessTokenType}. + */ + public String getCaseSensitiveName() { + return toString(); + } + + /** + * Gets the {@link AccessTokenType} lower cased. + * + * @return The {@link AccessTokenType} lower cased. + */ + public String getCaseInsensitiveName() { + return caseInsensitive; + } + + /** + * Creates or finds a {@link AccessTokenType} for the passed {@code name}. + * + *

        {@code null} will be returned if {@code name} is {@code null}.

        + * + * @param name A name to look for. + * + * @return The corresponding {@link AccessTokenType} of the provided name, or {@code null} if {@code name} was + * {@code null}. + */ + public static AccessTokenType fromString(String name) { + if (name == null) { + return null; + } + + AccessTokenType accessTokenType = VALUES.get(name); + + if (accessTokenType != null) { + return accessTokenType; + } + + return VALUES.computeIfAbsent(name, AccessTokenType::new); + } + + @Override + public String toString() { + return caseSensitive; + } + + @Override + public int hashCode() { + return caseInsensitive.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + + if (!(obj instanceof AccessTokenType)) { + return false; + } + + AccessTokenType other = (AccessTokenType) obj; + return Objects.equals(caseInsensitive, other.caseInsensitive); + } + + /** + * The Bearer token type. + */ + public static final AccessTokenType BEARER = fromString("Bearer"); + + /** + * The Pop token type. + */ + public static final AccessTokenType POP = fromString("Pop"); +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/credentials/oauth/OAuthTokenCredential.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/credentials/oauth/OAuthTokenCredential.java new file mode 100644 index 000000000000..8d6dad01a64a --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/credentials/oauth/OAuthTokenCredential.java @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.credentials.oauth; + +/** + *

        + * OAuth Token Credential interface serves as a fundamental component for managing and providing access tokens. + *

        + * + *

        + * The {@link OAuthTokenCredential} interface, offers an API to retrieve an access token that can be used for + * bearer token authentication. The scopes parameter specified as part of {@link OAuthTokenRequestContext} represents + * the resources or permissions required for the token. + *

        + * + *

        + * By utilizing the OAuth Token Provider interface, you can abstract the authentication logic away from your + * application code. This allows for flexibility in choosing authentication mechanisms and simplifies the management + * of access tokens, including token caching and refreshing. + *

        + * + * @see io.clientcore.core.credentials + */ +@FunctionalInterface +public interface OAuthTokenCredential { + + /** + * Get a token for a given resource/audience. + * + * @param request the details of the token request + * @return The Access Token + */ + AccessToken getToken(OAuthTokenRequestContext request); +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/credentials/oauth/OAuthTokenRequestContext.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/credentials/oauth/OAuthTokenRequestContext.java new file mode 100644 index 000000000000..2b96eef2358c --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/credentials/oauth/OAuthTokenRequestContext.java @@ -0,0 +1,152 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.credentials.oauth; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.utils.CoreUtils; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + *

        + * The {@link OAuthTokenRequestContext} is a class used to provide additional information and context when requesting an + * access token from an authentication source. It allows you to customize the token request and specify additional + * parameters, such as scopes, claims, or authentication options. + *

        + * + *

        + * Here's a high-level overview of how you can use the {@link OAuthTokenRequestContext}: + *

        + * + *
          + *
        1. Create an instance of the {@link OAuthTokenRequestContext} class and configure the required properties. + * The {@link OAuthTokenRequestContext} class allows you to specify the scopes or resources for which you want to request + * an access token, as well as any additional properties.
        2. + * + *
        3. The authentication client or mechanism will handle the token request options and return an access token that can + * be used to authenticate.
        4. + *
        + * + * @see io.clientcore.core.credentials + */ +@Metadata(properties = MetadataProperties.FLUENT) +public class OAuthTokenRequestContext { + private static final ClientLogger LOGGER = new ClientLogger(OAuthTokenRequestContext.class); + + private List scopes; + private Map params; + + /** + * Creates a token request instance. + */ + public OAuthTokenRequestContext() { + } + + /** + * Gets the scopes required for the token. + * @return the scopes required for the token + */ + public List getScopes() { + if (CoreUtils.isNullOrEmpty(scopes)) { + return Collections.emptyList(); + } + return scopes; + } + + /** + * Sets the scopes required for the token. + * @param scopes the scopes required for the token + * @return the OAuthTokenRequestContext itself + */ + public OAuthTokenRequestContext setScopes(List scopes) { + Objects.requireNonNull(scopes, "'scopes' cannot be null."); + this.scopes = scopes; + return this; + } + + /** + * Adds one or more scopes to the request scopes. + * @param scopes one or more scopes to add + * @return the OAuthTokenRequestProperties itself + * @throws NullPointerException If scopes is null. + * @throws IllegalArgumentException if empty scopes list is provided. + * @throws IllegalArgumentException If empty or null scopes are provided as part of the parameters. + */ + public OAuthTokenRequestContext addScopes(String... scopes) { + Objects.requireNonNull(scopes, "'scopes' cannot be null."); + + if (scopes.length == 0) { + throw LOGGER.logThrowableAsError(new IllegalArgumentException("At least one scope must be provided.")); + } + + for (String scope : scopes) { + if (CoreUtils.isNullOrEmpty(scope)) { + throw LOGGER + .logThrowableAsError(new IllegalArgumentException("Scopes cannot contain null or empty values.")); + } + } + + if (this.scopes == null) { + this.scopes = new ArrayList<>(); + } + this.scopes.addAll(Arrays.asList(scopes)); + return this; + } + + /** + * Gets the additional parameters required for the token. + * @return the parameters required for the token + */ + public Map getParams() { + if (CoreUtils.isNullOrEmpty(params)) { + return Collections.emptyMap(); + } + return this.params; + } + + /** + * Sets the additional parameters required for the token. + * + * @param params the additional parameters + * @return the OAuthTokenRequestContext itself + * @throws NullPointerException If params is null. + */ + public OAuthTokenRequestContext setParams(Map params) { + Objects.requireNonNull(params, "'params' cannot be null"); + this.params = params; + return this; + } + + /** + * Sets the additional parameter required for the token. + * + * @param key the key + * @param value the value + * @return the OAuthTokenRequestContext itself + * @throws IllegalArgumentException if key and/or value parameters are null. + */ + public OAuthTokenRequestContext setParam(String key, String value) { + if (CoreUtils.isNullOrEmpty(key)) { + throw LOGGER.logThrowableAsError(new IllegalArgumentException("Parameter 'key' cannot be null or empty")); + } + + if (CoreUtils.isNullOrEmpty(value)) { + throw LOGGER.logThrowableAsError(new IllegalArgumentException("Parameter 'value' cannot be null or empty")); + } + + if (this.params == null) { + this.params = new HashMap<>(); + } + this.params.put(key, value); + return this; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/credentials/oauth/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/credentials/oauth/package-info.java new file mode 100644 index 000000000000..af06f61ed3aa --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/credentials/oauth/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing OAuth credential classes for authentication purposes. + */ +package io.clientcore.core.credentials.oauth; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/credentials/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/credentials/package-info.java new file mode 100644 index 000000000000..df95af8ec7ea --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/credentials/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing basic credential classes for authentication purposes. + */ +package io.clientcore.core.credentials; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/RestProxy.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/RestProxy.java index 09d16040a12f..0af069adaf9c 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/RestProxy.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/RestProxy.java @@ -8,9 +8,9 @@ import io.clientcore.core.implementation.http.rest.RestProxyImpl; import io.clientcore.core.implementation.http.rest.SwaggerInterfaceParser; import io.clientcore.core.implementation.http.rest.SwaggerMethodParser; -import io.clientcore.core.implementation.util.JsonSerializer; -import io.clientcore.core.util.serializer.ObjectSerializer; -import io.clientcore.core.implementation.util.XmlSerializer; +import io.clientcore.core.serialization.json.JsonSerializer; +import io.clientcore.core.serialization.ObjectSerializer; +import io.clientcore.core.serialization.xml.XmlSerializer; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; @@ -19,8 +19,7 @@ /** * Type to create a proxy implementation for an interface describing REST API methods. *

        - * RestProxy can create proxy implementations for interfaces with methods that return deserialized Java objects as well - * as asynchronous Single objects that resolve to a deserialized Java object. + * RestProxy can create proxy implementations for interfaces with methods that return deserialized Java objects. */ public final class RestProxy implements InvocationHandler { private final SwaggerInterfaceParser interfaceParser; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/package-info.java deleted file mode 100644 index e874b3db52c0..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - * Package containing annotations for HTTP-related classes and methods. - */ -package io.clientcore.core.http.annotation; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/BodyParam.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/BodyParam.java similarity index 98% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/BodyParam.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/BodyParam.java index f715e5eee8b1..c5b5fbc1e254 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/BodyParam.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/BodyParam.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.http.annotation; +package io.clientcore.core.http.annotations; import java.lang.annotation.Retention; import java.lang.annotation.Target; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/FormParam.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/FormParam.java similarity index 97% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/FormParam.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/FormParam.java index 69d68e52c744..3ad06ff53d34 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/FormParam.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/FormParam.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.http.annotation; +package io.clientcore.core.http.annotations; import java.lang.annotation.Retention; import java.lang.annotation.Target; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/HeaderCollection.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/HeaderCollection.java similarity index 93% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/HeaderCollection.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/HeaderCollection.java index 19431cc584f5..6d4bb7f0bf94 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/HeaderCollection.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/HeaderCollection.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.http.annotation; +package io.clientcore.core.http.annotations; import java.lang.annotation.Retention; import java.lang.annotation.Target; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/HeaderParam.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/HeaderParam.java similarity index 98% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/HeaderParam.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/HeaderParam.java index 994f9edfb630..9615f809c0e7 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/HeaderParam.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/HeaderParam.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.http.annotation; +package io.clientcore.core.http.annotations; import java.lang.annotation.Retention; import java.lang.annotation.Target; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/HostParam.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/HostParam.java similarity index 96% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/HostParam.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/HostParam.java index 1cdb37f32c0d..c988d3814951 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/HostParam.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/HostParam.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.http.annotation; +package io.clientcore.core.http.annotations; -import io.clientcore.core.annotation.ServiceInterface; +import io.clientcore.core.annotations.ServiceInterface; import java.lang.annotation.Retention; import java.lang.annotation.Target; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/HttpRequestInformation.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/HttpRequestInformation.java similarity index 97% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/HttpRequestInformation.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/HttpRequestInformation.java index 3d9253d5b1c0..8e44349cc4f9 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/HttpRequestInformation.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/HttpRequestInformation.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.http.annotation; +package io.clientcore.core.http.annotations; import io.clientcore.core.http.models.HttpMethod; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/PathParam.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/PathParam.java similarity index 98% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/PathParam.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/PathParam.java index 30f0698b6b28..c4629fab5247 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/PathParam.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/PathParam.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.http.annotation; +package io.clientcore.core.http.annotations; import java.lang.annotation.Retention; import java.lang.annotation.Target; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/QueryParam.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/QueryParam.java similarity index 99% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/QueryParam.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/QueryParam.java index 3651b69c37d3..8ded27339b4d 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/QueryParam.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/QueryParam.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.http.annotation; +package io.clientcore.core.http.annotations; import java.lang.annotation.Retention; import java.lang.annotation.Target; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/UnexpectedResponseExceptionDetail.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/UnexpectedResponseExceptionDetail.java similarity index 80% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/UnexpectedResponseExceptionDetail.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/UnexpectedResponseExceptionDetail.java index da3430fa135a..da229d228b4b 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/UnexpectedResponseExceptionDetail.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/UnexpectedResponseExceptionDetail.java @@ -1,10 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.http.annotation; +package io.clientcore.core.http.annotations; -import io.clientcore.core.http.exception.HttpExceptionType; -import io.clientcore.core.http.exception.HttpResponseException; +import io.clientcore.core.http.models.HttpResponseException; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; @@ -14,9 +13,8 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; /** - * The {@link HttpExceptionType} that is thrown or returned when one of the status codes is returned from a REST API. Multiple - * annotations can be used. When no codes are listed that exception is always thrown or returned if it is reached - * during evaluation, this should be treated as a default case. If no default case is annotated the fall through + * Multiple annotations can be used. When no codes are listed that exception is always thrown or returned if it is + * reached during evaluation, this should be treated as a default case. If no default case is annotated the fall through * exception is {@link HttpResponseException}. * *

        Example:

        @@ -56,14 +54,6 @@ @Target(METHOD) @Repeatable(UnexpectedResponseExceptionDetails.class) public @interface UnexpectedResponseExceptionDetail { - /** - * The name of the {@link HttpExceptionType} of an {@link HttpResponseException} that should be thrown/returned when - * the API returns an unrecognized status code. - * - * @return The {@link HttpExceptionType} that should be thrown/returned, represented as a {@link String}. - */ - String exceptionTypeName() default ""; - /** * HTTP status codes which trigger the {@link HttpResponseException} to be thrown or returned. If no status codes * are listed the exception is always thrown or returned. diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/UnexpectedResponseExceptionDetails.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/UnexpectedResponseExceptionDetails.java similarity index 95% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/UnexpectedResponseExceptionDetails.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/UnexpectedResponseExceptionDetails.java index a65c7bf86e81..4f49f59dfd2f 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotation/UnexpectedResponseExceptionDetails.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/UnexpectedResponseExceptionDetails.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.http.annotation; +package io.clientcore.core.http.annotations; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/package-info.java new file mode 100644 index 000000000000..556208f6fd21 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/annotations/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing annotations for HTTP-related classes and methods. + */ +package io.clientcore.core.http.annotations; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/DefaultHttpClient.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/DefaultHttpClient.java deleted file mode 100644 index d408eb0dab41..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/DefaultHttpClient.java +++ /dev/null @@ -1,231 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.http.client; - -import io.clientcore.core.http.client.implementation.InputStreamTimeoutResponseSubscriber; -import io.clientcore.core.http.client.implementation.JdkHttpRequest; -import io.clientcore.core.http.client.implementation.JdkHttpResponse; -import io.clientcore.core.http.models.HttpHeaderName; -import io.clientcore.core.http.models.HttpHeaders; -import io.clientcore.core.http.models.HttpRequest; -import io.clientcore.core.http.models.RequestOptions; -import io.clientcore.core.http.models.Response; -import io.clientcore.core.http.models.ResponseBodyMode; -import io.clientcore.core.http.models.ServerSentEventListener; -import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.util.ServerSentEventUtils; -import io.clientcore.core.util.ServerSentResult; -import io.clientcore.core.util.binarydata.BinaryData; - -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.http.HttpResponse; -import java.time.Duration; -import java.util.Set; -import java.util.function.Function; -import java.util.function.Supplier; - -import static io.clientcore.core.http.client.implementation.JdkHttpUtils.fromJdkHttpHeaders; -import static io.clientcore.core.http.models.ContentType.APPLICATION_OCTET_STREAM; -import static io.clientcore.core.http.models.HttpMethod.HEAD; -import static io.clientcore.core.http.models.ResponseBodyMode.BUFFER; -import static io.clientcore.core.http.models.ResponseBodyMode.IGNORE; -import static io.clientcore.core.http.models.ResponseBodyMode.STREAM; -import static io.clientcore.core.util.ServerSentEventUtils.attemptRetry; -import static io.clientcore.core.util.ServerSentEventUtils.isTextEventStreamContentType; -import static io.clientcore.core.util.ServerSentEventUtils.processTextEventStream; - -/** - * HttpClient implementation using {@link HttpURLConnection} to send requests and receive responses. - */ -class DefaultHttpClient implements HttpClient { - private static final ClientLogger LOGGER = new ClientLogger(DefaultHttpClient.class); - - private final Set restrictedHeaders; - private final Duration writeTimeout; - private final Duration responseTimeout; - private final Duration readTimeout; - private final boolean hasReadTimeout; - - final java.net.http.HttpClient jdkHttpClient; - - DefaultHttpClient(java.net.http.HttpClient httpClient, Set restrictedHeaders, Duration writeTimeout, - Duration responseTimeout, Duration readTimeout) { - this.jdkHttpClient = httpClient; - - this.restrictedHeaders = restrictedHeaders; - LOGGER.atVerbose().addKeyValue("headers", restrictedHeaders).log("Effective restricted headers."); - - // Set the write and response timeouts to null if they are negative or zero. - // The writeTimeout is used with 'Flux.timeout(Duration)' which uses thread switching, always. When the timeout - // is zero or negative it's treated as an infinite timeout. So, setting this to null will prevent that thread - // switching with the same runtime behavior. - this.writeTimeout - = (writeTimeout != null && !writeTimeout.isNegative() && !writeTimeout.isZero()) ? writeTimeout : null; - - // The responseTimeout is used by JDK 'HttpRequest.timeout()' which will throw an exception when the timeout - // is non-null and is zero or negative. We treat zero or negative as an infinite timeout, so reset to null to - // prevent the exception from being thrown and have the behavior we want. - this.responseTimeout = (responseTimeout != null && !responseTimeout.isNegative() && !responseTimeout.isZero()) - ? responseTimeout - : null; - this.readTimeout = readTimeout; - this.hasReadTimeout = readTimeout != null && !readTimeout.isNegative() && !readTimeout.isZero(); - } - - @Override - public Response send(HttpRequest request) throws IOException { - java.net.http.HttpRequest jdkRequest = toJdkHttpRequest(request); - try { - // JDK HttpClient works differently than OkHttp and HttpUrlConnection where the response body handling has - // to be determined when the request is being sent, rather than being something that can be determined after - // the response has been received. Given that, we'll always consume the response body as an InputStream and - // after receiving it we'll handle ignoring, buffering, or streaming appropriately based on either the - // Content-Type header or the response body mode. - java.net.http.HttpResponse.BodyHandler bodyHandler - = getResponseHandler(hasReadTimeout, readTimeout, - java.net.http.HttpResponse.BodyHandlers::ofInputStream, InputStreamTimeoutResponseSubscriber::new); - - java.net.http.HttpResponse jdKResponse = jdkHttpClient.send(jdkRequest, bodyHandler); - return toResponse(request, jdKResponse); - } catch (InterruptedException e) { - throw LOGGER.logThrowableAsError(new RuntimeException(e)); - } - } - - /** - * Converts the given clientcore request to the JDK HttpRequest type. - * - * @param request the clientcore request - * @return the HttpRequest - */ - private java.net.http.HttpRequest toJdkHttpRequest(HttpRequest request) { - return new JdkHttpRequest(request, restrictedHeaders, LOGGER, writeTimeout, responseTimeout); - } - - /** - * Gets the response body handler based on whether a read timeout is configured. - *

        - * When a read timeout is configured our custom handler is used that tracks the time taken between each read - * operation to pull the body from the network. If a timeout isn't configured the built-in JDK handler is used. - * - * @param hasReadTimeout Flag indicating if a read timeout is configured. - * @param readTimeout The configured read timeout. - * @param jdkBodyHandler The JDK body handler to use when no read timeout is configured. - * @param timeoutSubscriber The supplier for the custom body subscriber to use when a read timeout is configured. - * @return The response body handler to use. - * @param The type of the response body. - */ - private static java.net.http.HttpResponse.BodyHandler getResponseHandler(boolean hasReadTimeout, - Duration readTimeout, Supplier> jdkBodyHandler, - Function> timeoutSubscriber) { - return hasReadTimeout ? responseInfo -> timeoutSubscriber.apply(readTimeout.toMillis()) : jdkBodyHandler.get(); - } - - private Response toResponse(HttpRequest request, java.net.http.HttpResponse response) - throws IOException { - HttpHeaders coreHeaders = fromJdkHttpHeaders(response.headers()); - ServerSentResult serverSentResult = null; - - String contentType = coreHeaders.getValue(HttpHeaderName.CONTENT_TYPE); - if (ServerSentEventUtils.isTextEventStreamContentType(contentType)) { - ServerSentEventListener listener = request.getServerSentEventListener(); - if (listener != null) { - serverSentResult = processTextEventStream(response.body(), listener); - - if (serverSentResult.getException() != null) { - // If an exception occurred while processing the text event stream, emit listener onError. - listener.onError(serverSentResult.getException()); - } - - // If an error occurred or we want to reconnect - if (!Thread.currentThread().isInterrupted() && attemptRetry(serverSentResult, request)) { - return this.send(request); - } - } else { - throw LOGGER.logThrowableAsError(new RuntimeException(ServerSentEventUtils.NO_LISTENER_ERROR_MESSAGE)); - } - } - - return processResponse(request, response, serverSentResult, coreHeaders, contentType); - } - - private Response processResponse(HttpRequest request, java.net.http.HttpResponse response, - ServerSentResult serverSentResult, HttpHeaders coreHeaders, String contentType) throws IOException { - RequestOptions options = request.getRequestOptions(); - ResponseBodyMode responseBodyMode = null; - - if (options != null) { - responseBodyMode = options.getResponseBodyMode(); - } - - responseBodyMode = getResponseBodyMode(request, contentType, responseBodyMode); - - BinaryData body = null; - - switch (responseBodyMode) { - case IGNORE: - response.body().close(); - - break; - - case STREAM: - if (isTextEventStreamContentType(contentType)) { - body = createBodyFromServerSentResult(serverSentResult); - } else { - body = BinaryData.fromStream(response.body()); - } - - break; - - case BUFFER: - case DESERIALIZE: - // Deserialization will occur at a later point in HttpResponseBodyDecoder. - if (isTextEventStreamContentType(contentType)) { - body = createBodyFromServerSentResult(serverSentResult); - } else { - body = createBodyFromResponse(response); - } - break; - - default: - body = createBodyFromResponse(response); - break; - - } - - return new JdkHttpResponse(request, response.statusCode(), coreHeaders, - body == null ? BinaryData.empty() : body); - } - - private static ResponseBodyMode getResponseBodyMode(HttpRequest request, String contentType, - ResponseBodyMode responseBodyMode) { - if (responseBodyMode == null) { - if (request.getHttpMethod() == HEAD) { - responseBodyMode = IGNORE; - } else if (contentType != null - && APPLICATION_OCTET_STREAM.regionMatches(true, 0, contentType, 0, APPLICATION_OCTET_STREAM.length())) { - - responseBodyMode = STREAM; - } else { - responseBodyMode = BUFFER; - } - } - return responseBodyMode; - } - - private BinaryData createBodyFromServerSentResult(ServerSentResult serverSentResult) { - String bodyContent = (serverSentResult != null && serverSentResult.getData() != null) - ? String.join("\n", serverSentResult.getData()) - : ""; - return BinaryData.fromString(bodyContent); - } - - private BinaryData createBodyFromResponse(HttpResponse response) throws IOException { - try (InputStream responseBody = response.body()) { // Use try-with-resources to close the stream. - return BinaryData.fromBytes(responseBody.readAllBytes()); - } - } -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/DefaultHttpClientBuilder.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/DefaultHttpClientBuilder.java deleted file mode 100644 index 2a0a2dc99b1a..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/DefaultHttpClientBuilder.java +++ /dev/null @@ -1,367 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.http.client; - -import io.clientcore.core.http.client.implementation.JdkHttpClientProxySelector; -import io.clientcore.core.http.models.ProxyOptions; -import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.util.SharedExecutorService; -import io.clientcore.core.util.configuration.Configuration; - -import javax.net.ssl.SSLContext; -import java.io.IOException; -import java.io.Reader; -import java.net.Authenticator; -import java.net.PasswordAuthentication; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.time.Duration; -import java.util.Collections; -import java.util.HashSet; -import java.util.Locale; -import java.util.Objects; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.Executor; - -import static io.clientcore.core.http.client.implementation.JdkHttpUtils.getDefaultTimeoutFromEnvironment; -import static io.clientcore.core.util.configuration.Configuration.PROPERTY_REQUEST_CONNECT_TIMEOUT; -import static io.clientcore.core.util.configuration.Configuration.PROPERTY_REQUEST_READ_TIMEOUT; -import static io.clientcore.core.util.configuration.Configuration.PROPERTY_REQUEST_RESPONSE_TIMEOUT; -import static io.clientcore.core.util.configuration.Configuration.PROPERTY_REQUEST_WRITE_TIMEOUT; - -/** - * Builder to configure and build an instance of the core {@link HttpClient} type using the JDK - * HttpURLConnection, first introduced in JDK 1.1. - */ -public class DefaultHttpClientBuilder { - private static final ClientLogger LOGGER = new ClientLogger(DefaultHttpClientBuilder.class); - - private static final Duration MINIMUM_TIMEOUT = Duration.ofMillis(1); - private static final Duration DEFAULT_CONNECTION_TIMEOUT; - private static final Duration DEFAULT_WRITE_TIMEOUT; - private static final Duration DEFAULT_RESPONSE_TIMEOUT; - private static final Duration DEFAULT_READ_TIMEOUT; - - private static final String JAVA_HOME = System.getProperty("java.home"); - private static final String JDK_HTTPCLIENT_ALLOW_RESTRICTED_HEADERS = "jdk.httpclient.allowRestrictedHeaders"; - - // These headers are restricted by default in native JDK12 HttpClient. - // These headers can be whitelisted by setting jdk.httpclient.allowRestrictedHeaders - // property in the network properties file: 'JAVA_HOME/conf/net.properties' - // e.g. white listing 'host' header. - // - // jdk.httpclient.allowRestrictedHeaders=host - // Also see - https://bugs.openjdk.java.net/browse/JDK-8213189 - static final Set DEFAULT_RESTRICTED_HEADERS; - - static { - Configuration configuration = Configuration.getGlobalConfiguration(); - - DEFAULT_CONNECTION_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_REQUEST_CONNECT_TIMEOUT, - Duration.ofSeconds(10), LOGGER); - DEFAULT_WRITE_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_REQUEST_WRITE_TIMEOUT, - Duration.ofSeconds(60), LOGGER); - DEFAULT_RESPONSE_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_REQUEST_RESPONSE_TIMEOUT, - Duration.ofSeconds(60), LOGGER); - DEFAULT_READ_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_REQUEST_READ_TIMEOUT, - Duration.ofSeconds(60), LOGGER); - - DEFAULT_RESTRICTED_HEADERS = Set.of("connection", "content-length", "expect", "host", "upgrade"); - } - - private java.net.http.HttpClient.Builder httpClientBuilder; - private ProxyOptions proxyOptions; - private Configuration configuration; - private Executor executor; - private SSLContext sslContext; - - private Duration connectionTimeout; - private Duration writeTimeout; - private Duration responseTimeout; - private Duration readTimeout; - - /** - * Creates DefaultHttpClientBuilder. - */ - public DefaultHttpClientBuilder() { - this.executor = SharedExecutorService.getInstance(); - } - - /** - * Creates DefaultHttpClientBuilder from the builder of an existing {@link java.net.http.HttpClient.Builder}. - * - * @param httpClientBuilder the HttpClient builder to use - * @throws NullPointerException if {@code httpClientBuilder} is null - */ - public DefaultHttpClientBuilder(java.net.http.HttpClient.Builder httpClientBuilder) { - this.httpClientBuilder = Objects.requireNonNull(httpClientBuilder, "'httpClientBuilder' cannot be null."); - } - - /** - * Sets the executor to be used for asynchronous and dependent tasks. This cannot be null. - *

        - * If this method is not invoked prior to {@link #build() building}, handling for a default will be based on whether - * the builder was created with the default constructor or the constructor that accepts an existing - * {@link java.net.http.HttpClient.Builder}. If the default constructor was used, the default executor will be - * {@link SharedExecutorService#getInstance()}. If the constructor that accepts an existing - * {@link java.net.http.HttpClient.Builder} was used, the executor from the existing builder will be used. - * - * @param executor the executor to be used for asynchronous and dependent tasks - * @return the updated {@link DefaultHttpClientBuilder} object - * @throws NullPointerException if {@code executor} is null - */ - public DefaultHttpClientBuilder executor(Executor executor) { - this.executor = Objects.requireNonNull(executor, "executor can not be null"); - return this; - } - - /** - * Sets the connection timeout. - * - *

        Code Samples

        - * - * - *
        -     * HttpClient client = new DefaultHttpClientBuilder()
        -     *         .connectionTimeout(Duration.ofSeconds(250)) // connection timeout of 250 seconds
        -     *         .build();
        -     * 
        - * - * - * The default connection timeout is 10 seconds. - * - * @param connectionTimeout the connection timeout - * @return the updated {@link DefaultHttpClientBuilder} object - */ - public DefaultHttpClientBuilder connectionTimeout(Duration connectionTimeout) { - // setConnectionTimeout can be null - this.connectionTimeout = connectionTimeout; - return this; - } - - /** - * Sets the writing timeout for a request to be sent. - *

        - * The writing timeout does not apply to the entire request but to the request being sent over the wire. For example - * a request body which emits {@code 10} {@code 8KB} buffers will trigger {@code 10} write operations, the last - * write tracker will update when each operation completes and the outbound buffer will be periodically checked to - * determine if it is still draining. - *

        - * If {@code writeTimeout} is null either {@link Configuration#PROPERTY_REQUEST_WRITE_TIMEOUT} or a 60-second - * timeout will be used, if it is a {@link Duration} less than or equal to zero then no write timeout will be - * applied. When applying the timeout the greatest of one millisecond and the value of {@code writeTimeout} will be - * used. - * - * @param writeTimeout Write operation timeout duration. - * @return The updated {@link DefaultHttpClientBuilder} object. - */ - public DefaultHttpClientBuilder writeTimeout(Duration writeTimeout) { - this.writeTimeout = writeTimeout; - return this; - } - - /** - * Sets the response timeout duration used when waiting for a server to reply. - *

        - * The response timeout begins once the request write completes and finishes once the first response read is - * triggered when the server response is received. - *

        - * If {@code responseTimeout} is null either {@link Configuration#PROPERTY_REQUEST_RESPONSE_TIMEOUT} or a - * 60-second timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout will be - * applied to the response. When applying the timeout the greatest of one millisecond and the value of {@code - * responseTimeout} will be used. - * - * @param responseTimeout Response timeout duration. - * @return The updated {@link DefaultHttpClientBuilder} object. - */ - public DefaultHttpClientBuilder responseTimeout(Duration responseTimeout) { - this.responseTimeout = responseTimeout; - return this; - } - - /** - * Sets the read timeout duration used when reading the server response. - *

        - * The read timeout begins once the first response read is triggered after the server response is received. This - * timeout triggers periodically but won't fire its operation if another read operation has completed between when - * the timeout is triggered and completes. - *

        - * If {@code readTimeout} is null or {@link Configuration#PROPERTY_REQUEST_READ_TIMEOUT} or a 60-second - * timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout period will be - * applied to response read. When applying the timeout the greatest of one millisecond and the value of {@code - * readTimeout} will be used. - * - * @param readTimeout Read timeout duration. - * @return The updated {@link DefaultHttpClientBuilder} object. - */ - public DefaultHttpClientBuilder readTimeout(Duration readTimeout) { - this.readTimeout = readTimeout; - return this; - } - - /** - * Sets the proxy. - * - *

        Code Samples

        - * - * - *
        -     * final String proxyHost = "<proxy-host>"; // e.g. localhost
        -     * final int proxyPort = 9999; // Proxy port
        -     * ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP,
        -     *     new InetSocketAddress(proxyHost, proxyPort));
        -     * HttpClient client = new DefaultHttpClientBuilder()
        -     *     .proxy(proxyOptions)
        -     *     .build();
        -     * 
        - * - * - * @param proxyOptions The proxy configuration to use. - * @return the updated {@link DefaultHttpClientBuilder} object - * @throws NullPointerException If {@code proxyOptions} is not null and the proxy type or address is not set. - */ - public DefaultHttpClientBuilder proxy(ProxyOptions proxyOptions) { - if (proxyOptions != null) { - Objects.requireNonNull(proxyOptions.getType(), "Proxy type is required."); - Objects.requireNonNull(proxyOptions.getAddress(), "Proxy address is required."); - } - - // proxyOptions can be null - this.proxyOptions = proxyOptions; - return this; - } - - /** - * Sets the {@link SSLContext} to be used when opening secure connections. - * - * @param sslContext The SSL context to be used. - * @return The updated {@link DefaultHttpClientBuilder} object. - */ - public DefaultHttpClientBuilder sslContext(SSLContext sslContext) { - this.sslContext = sslContext; - return this; - } - - /** - * Sets the configuration store that is used during construction of the HTTP client. - * - * @param configuration The configuration store used to - * @return The updated {@link DefaultHttpClientBuilder} object. - */ - public DefaultHttpClientBuilder configuration(Configuration configuration) { - this.configuration = configuration; - return this; - } - - /** - * Build a HttpClient with current configurations. - * - * @return a {@link HttpClient}. - */ - public HttpClient build() { - java.net.http.HttpClient.Builder httpClientBuilder - = this.httpClientBuilder == null ? java.net.http.HttpClient.newBuilder() : this.httpClientBuilder; - - // Client Core JDK http client supports HTTP 1.1 by default. - httpClientBuilder.version(java.net.http.HttpClient.Version.HTTP_1_1); - - httpClientBuilder = httpClientBuilder.connectTimeout(getTimeout(connectionTimeout, DEFAULT_CONNECTION_TIMEOUT)); - - Duration writeTimeout = getTimeout(this.writeTimeout, DEFAULT_WRITE_TIMEOUT); - Duration responseTimeout = getTimeout(this.responseTimeout, DEFAULT_RESPONSE_TIMEOUT); - Duration readTimeout = getTimeout(this.readTimeout, DEFAULT_READ_TIMEOUT); - - Configuration buildConfiguration - = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; - - ProxyOptions buildProxyOptions - = (proxyOptions == null) ? ProxyOptions.fromConfiguration(buildConfiguration) : proxyOptions; - - if (executor != null) { - httpClientBuilder.executor(executor); - } - - if (sslContext != null) { - httpClientBuilder.sslContext(sslContext); - } - - if (buildProxyOptions != null) { - httpClientBuilder - = httpClientBuilder.proxy(new JdkHttpClientProxySelector(buildProxyOptions.getType().toProxyType(), - buildProxyOptions.getAddress(), buildProxyOptions.getNonProxyHosts())); - - if (buildProxyOptions.getUsername() != null) { - httpClientBuilder.authenticator( - new ProxyAuthenticator(buildProxyOptions.getUsername(), buildProxyOptions.getPassword())); - } - } - - return new DefaultHttpClient(httpClientBuilder.build(), Collections.unmodifiableSet(getRestrictedHeaders()), - writeTimeout, responseTimeout, readTimeout); - } - - Set getRestrictedHeaders() { - // Compute the effective restricted headers by removing the allowed headers from default restricted headers - Set restrictedHeaders = new HashSet<>(DEFAULT_RESTRICTED_HEADERS); - removeAllowedHeaders(restrictedHeaders); - return restrictedHeaders; - } - - private void removeAllowedHeaders(Set restrictedHeaders) { - Properties properties = getNetworkProperties(); - String[] allowRestrictedHeadersNetProperties - = properties.getProperty(JDK_HTTPCLIENT_ALLOW_RESTRICTED_HEADERS, "").split(","); - - // Read all allowed restricted headers from configuration - Configuration config = (this.configuration == null) ? Configuration.getGlobalConfiguration() : configuration; - String[] allowRestrictedHeadersSystemProperties - = config.get(JDK_HTTPCLIENT_ALLOW_RESTRICTED_HEADERS, "").split(","); - - // Combine the set of all allowed restricted headers from both sources - for (String header : allowRestrictedHeadersSystemProperties) { - restrictedHeaders.remove(header.trim().toLowerCase(Locale.ROOT)); - } - - for (String header : allowRestrictedHeadersNetProperties) { - restrictedHeaders.remove(header.trim().toLowerCase(Locale.ROOT)); - } - } - - Properties getNetworkProperties() { - // Read all allowed restricted headers from JAVA_HOME/conf/net.properties - Path path = Paths.get(JAVA_HOME, "conf", "net.properties"); - Properties properties = new Properties(); - try (Reader reader = Files.newBufferedReader(path)) { - properties.load(reader); - } catch (IOException e) { - LOGGER.atWarning().addKeyValue("path", path).log("Cannot read net properties.", e); - } - return properties; - } - - private static class ProxyAuthenticator extends Authenticator { - private final String userName; - private final String password; - - ProxyAuthenticator(String userName, String password) { - this.userName = userName; - this.password = password; - } - - @Override - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(this.userName, password.toCharArray()); - } - } - - private static Duration getTimeout(Duration configuredTimeout, Duration defaultTimeout) { - if (configuredTimeout == null) { - return defaultTimeout; - } - - return configuredTimeout.compareTo(MINIMUM_TIMEOUT) < 0 ? MINIMUM_TIMEOUT : configuredTimeout; - } -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/DefaultHttpClientProvider.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/DefaultHttpClientProvider.java deleted file mode 100644 index c1d502e85c83..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/DefaultHttpClientProvider.java +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package io.clientcore.core.http.client; - -/** - * An {@link HttpClientProvider} that provides an implementation of HttpClient based on the default {@link HttpClient}. - */ -public class DefaultHttpClientProvider extends HttpClientProvider { - // Enum Singleton Pattern - private enum GlobalDefaultHttpClient { - HTTP_CLIENT(new DefaultHttpClientBuilder().build()); - - private final HttpClient httpClient; - - GlobalDefaultHttpClient(HttpClient httpClient) { - this.httpClient = httpClient; - } - - private HttpClient getHttpClient() { - return httpClient; - } - } - - /** - * Creates a new instance of {@link DefaultHttpClientProvider}. - */ - public DefaultHttpClientProvider() { - } - - @Override - public HttpClient getNewInstance() { - return new DefaultHttpClientBuilder().build(); - } - - @Override - public HttpClient getSharedInstance() { - return GlobalDefaultHttpClient.HTTP_CLIENT.getHttpClient(); - } -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/HttpClient.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/HttpClient.java index 3de633ad942e..0aea548c3c42 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/HttpClient.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/HttpClient.java @@ -5,6 +5,8 @@ import io.clientcore.core.http.models.HttpRequest; import io.clientcore.core.http.models.Response; +import io.clientcore.core.implementation.http.client.GlobalJdkHttpClient; +import io.clientcore.core.models.binarydata.BinaryData; import java.io.IOException; @@ -13,13 +15,13 @@ */ public interface HttpClient { /** - * Sends the provided request synchronously with contextual information. + * Sends the provided request with contextual information. * * @param request The HTTP request to send. * @return The response. * @throws IOException If an I/O error occurs during sending the request or receiving the response. */ - Response send(HttpRequest request) throws IOException; + Response send(HttpRequest request) throws IOException; /** * Get a new instance of the {@link HttpClient} that the {@link HttpClientProvider} loaded from the classpath is @@ -33,7 +35,7 @@ public interface HttpClient { */ static HttpClient getNewInstance() { return HttpClientProvider.getProviders() - .create(HttpClientProvider::getNewInstance, () -> new DefaultHttpClientBuilder().build(), null); + .create(HttpClientProvider::getNewInstance, () -> new JdkHttpClientBuilder().build(), null); } /** @@ -48,6 +50,6 @@ static HttpClient getNewInstance() { */ static HttpClient getSharedInstance() { return HttpClientProvider.getProviders() - .create(HttpClientProvider::getSharedInstance, new DefaultHttpClientProvider()::getSharedInstance, null); + .create(HttpClientProvider::getSharedInstance, GlobalJdkHttpClient.HTTP_CLIENT::getHttpClient, null); } } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/HttpClientProvider.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/HttpClientProvider.java index dcaf2b8c6361..3a608f7d3dfc 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/HttpClientProvider.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/HttpClientProvider.java @@ -3,8 +3,8 @@ package io.clientcore.core.http.client; -import io.clientcore.core.implementation.util.Providers; -import io.clientcore.core.util.configuration.Configuration; +import io.clientcore.core.implementation.utils.Providers; +import io.clientcore.core.utils.configuration.Configuration; /** * An interface to be implemented by any core plugin that wishes to provide an alternate {@link HttpClient} @@ -42,7 +42,7 @@ public HttpClientProvider() { static Providers getProviders() { if (providers == null) { providers = new Providers<>(HttpClientProvider.class, - Configuration.getGlobalConfiguration().get(Configuration.PROPERTY_HTTP_CLIENT_IMPLEMENTATION), + Configuration.getGlobalConfiguration().get(Configuration.HTTP_CLIENT_IMPLEMENTATION), NO_DEFAULT_PROVIDER_MESSAGE); } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/JdkHttpClientBuilder.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/JdkHttpClientBuilder.java new file mode 100644 index 000000000000..89babfae4375 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/JdkHttpClientBuilder.java @@ -0,0 +1,194 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.http.client; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.http.models.ProxyOptions; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.utils.SharedExecutorService; +import io.clientcore.core.utils.configuration.Configuration; + +import javax.net.ssl.SSLContext; +import java.time.Duration; +import java.util.concurrent.Executor; + +/** + * Builder to configure and build an instance of the JDK {@code HttpClient} introduced in Java 11. + *

        + * Due to the JDK preventing some headers from being sent on requests, Java 12 is required to create an instance of this + * {@link HttpClient} implementation. + *

        + * This class leverages multi-release JAR functionality. If the JDK version is 11 or lower, this class will throw an + * {@link UnsupportedOperationException} when any method is invoked. This same issue will also happen if the application + * using this functionality is running Java 12 or later but doesn't have {@code Multi-Release: true} in its + * {@code META-INF/MANIFEST.MF} file. + */ +@Metadata(properties = MetadataProperties.FLUENT) +public class JdkHttpClientBuilder { + private static final ClientLogger LOGGER = new ClientLogger(JdkHttpClientBuilder.class); + + private static final String ERROR_MESSAGE = "It is recommended that libraries be deployed on the latest LTS " + + "version of Java, however the Java client will support down to Java 8. In the case where the client is to " + + "operate on Java versions below Java 11, it is required to include additional dependencies. Usage of " + + "DefaultHttpClient is only available when using Java 12 or higher. For support with Java 11 or lower, " + + "include a dependency on io.clientcore:http-okhttp3."; + + /** + * Creates JdkHttpClientBuilder. + */ + public JdkHttpClientBuilder() { + throw LOGGER.logThrowableAsError(new UnsupportedOperationException(ERROR_MESSAGE)); + } + + /** + * Sets the executor to be used for asynchronous and dependent tasks. This cannot be null. + *

        + * If this method is not invoked prior to {@link #build() building}, handling for a default will be based on whether + * the builder was created with the default constructor or the constructor that accepts an existing + * {@code HttpClient.Builder}. If the default constructor was used, the default executor will be + * {@link SharedExecutorService#getInstance()}. If the constructor that accepts an existing + * {@code HttpClient.Builder} was used, the executor from the existing builder will be used. + * + * @param executor the executor to be used for asynchronous and dependent tasks + * @return the updated {@link JdkHttpClientBuilder} object + * @throws NullPointerException if {@code executor} is null + */ + public JdkHttpClientBuilder executor(Executor executor) { + throw LOGGER.logThrowableAsError(new UnsupportedOperationException(ERROR_MESSAGE)); + } + + /** + * Sets the connection timeout. + * + *

        Code Samples

        + * + * + *
        +     * HttpClient client = new JdkHttpClientBuilder()
        +     *         .connectionTimeout(Duration.ofSeconds(250)) // connection timeout of 250 seconds
        +     *         .build();
        +     * 
        + * + * + * The default connection timeout is 10 seconds. + * + * @param connectionTimeout the connection timeout + * @return the updated {@link JdkHttpClientBuilder} object + */ + public JdkHttpClientBuilder connectionTimeout(Duration connectionTimeout) { + throw LOGGER.logThrowableAsError(new UnsupportedOperationException(ERROR_MESSAGE)); + } + + /** + * Sets the writing timeout for a request to be sent. + *

        + * The writing timeout does not apply to the entire request but to the request being sent over the wire. For example + * a request body which emits {@code 10} {@code 8KB} buffers will trigger {@code 10} write operations, the last + * write tracker will update when each operation completes and the outbound buffer will be periodically checked to + * determine if it is still draining. + *

        + * If {@code writeTimeout} is null either {@link Configuration#REQUEST_WRITE_TIMEOUT_IN_MS} or a 60-second + * timeout will be used, if it is a {@link Duration} less than or equal to zero then no write timeout will be + * applied. When applying the timeout the greatest of one millisecond and the value of {@code writeTimeout} will be + * used. + * + * @param writeTimeout Write operation timeout duration. + * @return The updated {@link JdkHttpClientBuilder} object. + */ + public JdkHttpClientBuilder writeTimeout(Duration writeTimeout) { + throw LOGGER.logThrowableAsError(new UnsupportedOperationException(ERROR_MESSAGE)); + } + + /** + * Sets the response timeout duration used when waiting for a server to reply. + *

        + * The response timeout begins once the request write completes and finishes once the first response read is + * triggered when the server response is received. + *

        + * If {@code responseTimeout} is null either {@link Configuration#REQUEST_RESPONSE_TIMEOUT_IN_MS} or a + * 60-second timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout will be + * applied to the response. When applying the timeout the greatest of one millisecond and the value of {@code + * responseTimeout} will be used. + * + * @param responseTimeout Response timeout duration. + * @return The updated {@link JdkHttpClientBuilder} object. + */ + public JdkHttpClientBuilder responseTimeout(Duration responseTimeout) { + throw LOGGER.logThrowableAsError(new UnsupportedOperationException(ERROR_MESSAGE)); + } + + /** + * Sets the read timeout duration used when reading the server response. + *

        + * The read timeout begins once the first response read is triggered after the server response is received. This + * timeout triggers periodically but won't fire its operation if another read operation has completed between when + * the timeout is triggered and completes. + *

        + * If {@code readTimeout} is null or {@link Configuration#REQUEST_READ_TIMEOUT_IN_MS} or a 60-second + * timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout period will be + * applied to response read. When applying the timeout the greatest of one millisecond and the value of {@code + * readTimeout} will be used. + * + * @param readTimeout Read timeout duration. + * @return The updated {@link JdkHttpClientBuilder} object. + */ + public JdkHttpClientBuilder readTimeout(Duration readTimeout) { + throw LOGGER.logThrowableAsError(new UnsupportedOperationException(ERROR_MESSAGE)); + } + + /** + * Sets the proxy. + * + *

        Code Samples

        + * + * + *
        +     * final String proxyHost = "<proxy-host>"; // e.g. localhost
        +     * final int proxyPort = 9999; // Proxy port
        +     * ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP,
        +     *     new InetSocketAddress(proxyHost, proxyPort));
        +     * HttpClient client = new JdkHttpClientBuilder()
        +     *     .proxy(proxyOptions)
        +     *     .build();
        +     * 
        + * + * + * @param proxyOptions The proxy configuration to use. + * @return the updated {@link JdkHttpClientBuilder} object + * @throws NullPointerException If {@code proxyOptions} is not null and the proxy type or address is not set. + */ + public JdkHttpClientBuilder proxy(ProxyOptions proxyOptions) { + throw LOGGER.logThrowableAsError(new UnsupportedOperationException(ERROR_MESSAGE)); + } + + /** + * Sets the {@link SSLContext} to be used when opening secure connections. + * + * @param sslContext The SSL context to be used. + * @return The updated {@link JdkHttpClientBuilder} object. + */ + public JdkHttpClientBuilder sslContext(SSLContext sslContext) { + throw LOGGER.logThrowableAsError(new UnsupportedOperationException(ERROR_MESSAGE)); + } + + /** + * Sets the configuration store that is used during construction of the HTTP client. + * + * @param configuration The configuration store used to + * @return The updated {@link JdkHttpClientBuilder} object. + */ + public JdkHttpClientBuilder configuration(Configuration configuration) { + throw LOGGER.logThrowableAsError(new UnsupportedOperationException(ERROR_MESSAGE)); + } + + /** + * Build a HttpClient with current configurations. + * + * @return a {@link HttpClient}. + */ + public HttpClient build() { + throw LOGGER.logThrowableAsError(new UnsupportedOperationException(ERROR_MESSAGE)); + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/implementation/JdkHttpResponse.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/implementation/JdkHttpResponse.java deleted file mode 100644 index 29e1f1f69a13..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/implementation/JdkHttpResponse.java +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.http.client.implementation; - -import io.clientcore.core.http.models.HttpHeaders; -import io.clientcore.core.http.models.HttpRequest; -import io.clientcore.core.http.models.HttpResponse; -import io.clientcore.core.util.binarydata.BinaryData; - -/** - * Base response class for JDK with implementations for response metadata. - */ -public final class JdkHttpResponse extends HttpResponse { - private final BinaryData body; - - /** - * Creates an instance of {@link JdkHttpResponse}. - * - * @param request the request which resulted in this response. - * @param statusCode the status code of the response. - * @param headers the headers of the response. - * @param body the response body. - */ - public JdkHttpResponse(final HttpRequest request, int statusCode, HttpHeaders headers, BinaryData body) { - super(request, statusCode, headers, null); - this.body = body; - } - - @Override - public BinaryData getBody() { - if (body == null) { - if (super.getValue() == null) { - return BinaryData.empty(); - } else { - return super.getValue(); - } - } - - return body; - } -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/implementation/JdkHttpUtils.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/implementation/JdkHttpUtils.java deleted file mode 100644 index 3ad9cb165f13..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/implementation/JdkHttpUtils.java +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package io.clientcore.core.http.client.implementation; - -import io.clientcore.core.http.models.HttpHeaderName; -import io.clientcore.core.http.models.HttpHeaders; -import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.util.SharedExecutorService; -import io.clientcore.core.util.configuration.Configuration; - -import java.nio.ByteBuffer; -import java.time.Duration; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; - -/** - * Utility class for JDK HttpClient. - */ -public final class JdkHttpUtils { - /** - * Converts the given JDK Http headers to clientcore Http header. - * - * @param headers the JDK Http headers - * @return the clientcore Http headers - */ - public static HttpHeaders fromJdkHttpHeaders(java.net.http.HttpHeaders headers) { - final HttpHeaders httpHeaders = new HttpHeaders((int) (headers.map().size() / 0.75F)); - - for (Map.Entry> kvp : headers.map().entrySet()) { - List value = kvp.getValue(); - if (value != null && !value.isEmpty()) { - httpHeaders.set(HttpHeaderName.fromString(kvp.getKey()), kvp.getValue()); - } - } - - return httpHeaders; - } - - /** - * Gets the size of the given list of ByteBuffers. - *

        - * If the size of buffers is greater than {@link Integer#MAX_VALUE} an {@link IllegalStateException} will be thrown. - * This is done as this is used to create a {@code byte[]} and this could result in an integer overflow. - * - * @param buffers The list of ByteBuffers to get the size of. - * @return The size of the buffers. - * @throws IllegalStateException If the size of the buffers is greater than {@link Integer#MAX_VALUE}. - */ - public static int getSizeOfBuffers(List buffers) { - long size = 0; - for (ByteBuffer buffer : buffers) { - size += buffer.remaining(); - - if (size > Integer.MAX_VALUE) { - throw new IllegalStateException("The size of the buffers is greater than Integer.MAX_VALUE."); - } - } - - return (int) size; - } - - /** - * Schedules a timeout task to be executed after the given timeout. - * - * @param task The task to be executed. - * @param timeoutMillis The timeout in milliseconds. - * @return The scheduled future for the task. - */ - public static ScheduledFuture scheduleTimeoutTask(Runnable task, long timeoutMillis) { - return SharedExecutorService.getInstance().schedule(task, timeoutMillis, TimeUnit.MILLISECONDS); - } - - /** - * Attempts to load an environment configured default timeout. - *

        - * If the environment default timeout isn't configured, {@code defaultTimeout} will be returned. If the environment - * default timeout is a string that isn't parseable by {@link Long#parseLong(String)}, {@code defaultTimeout} will - * be returned. If the environment default timeout is less than 0, {@link Duration#ZERO} will be returned indicated - * that there is no timeout period. - * - * @param configuration The environment configurations. - * @param timeoutPropertyName The default timeout property name. - * @param defaultTimeout The fallback timeout to be used. - * @param logger A {@link ClientLogger} to log exceptions. - * @return Either the environment configured default timeout, {@code defaultTimeoutMillis}, or 0. - */ - public static Duration getDefaultTimeoutFromEnvironment(Configuration configuration, String timeoutPropertyName, - Duration defaultTimeout, ClientLogger logger) { - String environmentTimeout = configuration.get(timeoutPropertyName); - - // Environment wasn't configured with the timeout property. - if (environmentTimeout == null || environmentTimeout.isEmpty()) { - return defaultTimeout; - } - - try { - long timeoutMillis = Long.parseLong(environmentTimeout); - if (timeoutMillis < 0) { - logger.atVerbose() - .addKeyValue(timeoutPropertyName, timeoutMillis) - .log("Negative timeout values are not allowed. Using 'Duration.ZERO' to indicate no timeout."); - return Duration.ZERO; - } - - return Duration.ofMillis(timeoutMillis); - } catch (NumberFormatException ex) { - logger.atInfo() - .addKeyValue(timeoutPropertyName, environmentTimeout) - .addKeyValue("defaultTimeout", defaultTimeout) - .log("Timeout is not valid number. Using default value.", ex); - - return defaultTimeout; - } - } - - private JdkHttpUtils() { - } -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/implementation/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/implementation/package-info.java deleted file mode 100644 index c2f7150d899c..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/implementation/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - * Package containing implementation classes used by the JDK-backed Client Core HTTP client. - */ -package io.clientcore.core.http.client.implementation; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/exception/HttpExceptionType.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/exception/HttpExceptionType.java deleted file mode 100644 index a1a3e42b28d3..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/exception/HttpExceptionType.java +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.http.exception; - -import io.clientcore.core.util.ExpandableEnum; - -import java.util.Collection; -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Represents exception types for HTTP requests and responses. - */ -public final class HttpExceptionType implements ExpandableEnum { - private static final Map VALUES = new ConcurrentHashMap<>(); - - private final String caseSensitive; - private final String caseInsensitive; - - private HttpExceptionType(String name) { - this.caseSensitive = name; - this.caseInsensitive = name.toLowerCase(); - } - - @Override - public String getValue() { - return caseSensitive; - } - - /** - * Gets all known {@link HttpExceptionType} values. - * - * @return The known {@link HttpExceptionType} values. - */ - public static Collection values() { - return VALUES.values(); - } - - /** - * Creates or finds a {@link HttpExceptionType} for the passed {@code name}. - * - *

        {@code null} will be returned if {@code name} is {@code null}.

        - * - * @param name A name to look for. - * - * @return The corresponding {@link HttpExceptionType} of the provided name, or {@code null} if {@code name} was - * {@code null}. - */ - public static HttpExceptionType fromString(String name) { - if (name == null) { - return null; - } - - HttpExceptionType exceptionType = VALUES.get(name); - - if (exceptionType != null) { - return exceptionType; - } - - return VALUES.computeIfAbsent(name, HttpExceptionType::new); - } - - @Override - public String toString() { - return caseSensitive; - } - - @Override - public int hashCode() { - return caseInsensitive.hashCode(); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if (!(obj instanceof HttpExceptionType)) { - return false; - } - - HttpExceptionType other = (HttpExceptionType) obj; - - return Objects.equals(caseInsensitive, other.caseInsensitive); - } - - /** - * The exception thrown when failing to authenticate the HTTP request with status code of {@code 4XX}, typically - * {@code 401 Unauthorized}. - * - *

        A runtime exception indicating request authorization failure caused by one of the following scenarios:

        - *
          - *
        • A client did not send the required authorization credentials to access the requested resource, i.e. - * Authorization HTTP header is missing in the request
        • - *
        • If the request contains the HTTP Authorization header, then the exception indicates that authorization - * has been refused for the credentials contained in the request header.
        • - *
        - */ - public static final HttpExceptionType CLIENT_AUTHENTICATION = fromString("CLIENT_AUTHENTICATION"); - - /** - * The exception thrown when the HTTP request tried to create an already existing resource and received a status - * code {@code 4XX}, typically {@code 412 Conflict}. - */ - public static final HttpExceptionType RESOURCE_EXISTS = fromString("RESOURCE_EXISTS"); - - /** - * The exception thrown for invalid resource modification with status code of {@code 4XX}, typically - * {@code 409 Conflict}. - */ - public static final HttpExceptionType RESOURCE_MODIFIED = fromString("RESOURCE_MODIFIED"); - - /** - * The exception thrown when receiving an error response with status code {@code 412 response} (for update) or - * {@code 404 Not Found} (for get/post). - */ - public static final HttpExceptionType RESOURCE_NOT_FOUND = fromString("RESOURCE_NOT_FOUND"); - - /** - * This exception thrown when an HTTP request has reached the maximum number of redirect attempts with a status code - * of {@code 3XX}. - */ - public static final HttpExceptionType TOO_MANY_REDIRECTS = fromString("TOO_MANY_REDIRECTS"); -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/exception/HttpResponseException.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/exception/HttpResponseException.java deleted file mode 100644 index b05b0f369b69..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/exception/HttpResponseException.java +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.http.exception; - -import io.clientcore.core.http.models.Response; - -/** - * The exception thrown when an unsuccessful response is received with http status code (e.g. {@code 3XX}, {@code 4XX}, - * {@code 5XX}) from the service request. - */ -public class HttpResponseException extends RuntimeException { - /** - * The HTTP response value. - */ - private final Object value; - - /** - * Information about the associated HTTP response. - */ - private final Response response; - - /** - * The type of the exception. - */ - private final HttpExceptionType type; - - /** - * Initializes a new instance of the HttpResponseException class. - * - * @param message The exception message. - * @param response The {@link Response} received that is associated to the exception. - * @param type The {@link HttpExceptionType type} of the exception. - * @param value The deserialized response value. - */ - public HttpResponseException(final String message, final Response response, final HttpExceptionType type, - final Object value) { - super(message); - - this.value = value; - this.response = response; - this.type = type; - } - - /** - * Initializes a new instance of the HttpResponseException class. - * - * @param message The exception message. - * @param response The {@link Response} received that is associated to the exception. - * @param type The {@link HttpExceptionType type} of the exception. - * @param cause The {@link Throwable} which caused the creation of this exception. - */ - public HttpResponseException(final String message, final Response response, final HttpExceptionType type, - final Throwable cause) { - super(message, cause); - - this.value = null; - this.response = response; - this.type = type; - } - - /** - * Initializes a new instance of the HttpResponseException class. - * - * @param message The exception message. - * @param response The {@link Response} received that is associated to the exception. - * @param type The {@link HttpExceptionType type} of the exception. - * @param value The deserialized response value. - * @param cause The {@link Throwable} which caused the creation of this exception. - * @param enableSuppression Whether suppression is enabled or disabled. - * @param writableStackTrace Whether the exception stack trace will be filled in. - */ - public HttpResponseException(final String message, final Response response, final HttpExceptionType type, - final Object value, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - - this.value = value; - this.response = response; - this.type = type; - } - - /** - * Gets the {@link Response} received that is associated to the exception. - * - * @return The {@link Response} received that is associated to the exception. - */ - public Response getResponse() { - return response; - } - - /** - * Gets the deserialized HTTP response value. - * - * @return The deserialized HTTP response value. - */ - public Object getValue() { - return value; - } - - /** - * Gets the {@link HttpExceptionType type} of the exception. - * - * @return The {@link HttpExceptionType type} of the exception. - */ - public HttpExceptionType getType() { - return type; - } -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/exception/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/exception/package-info.java deleted file mode 100644 index 013048ecdde7..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/exception/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - * Package containing core HTTP exception classes. - */ -package io.clientcore.core.http.exception; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/ETag.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/ETag.java new file mode 100644 index 000000000000..95abdaf621fc --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/ETag.java @@ -0,0 +1,112 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.http.models; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.instrumentation.logging.ClientLogger; + +import java.util.Objects; + +/** + * This class represents an HTTP ETag. An ETag value could be strong or weak ETag. + * For more information, check out
        Wikipedia's HTTP ETag. + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public final class ETag { + private static final ClientLogger LOGGER = new ClientLogger(ETag.class); + + static final String WEAK_ETAG_PREFIX_QUOTE = "W/\""; + static final String ASTERISK = "*"; + + /** + * An ETag with value {@code *}, which represents any resource. + */ + public static final ETag ALL = new ETag(ASTERISK); + private static final ETag NULL = new ETag(null); + + private final String eTag; + + /** + * Creates a new instance of {@link ETag}. + * + * @param eTag The HTTP entity tag string value. + */ + private ETag(String eTag) { + this.eTag = eTag; + } + + /** + * Creates a new instance of {@link ETag}. + *

        + * This method will validate that the {@code eTag} is a valid ETag value. Valid ETag values are as follows: + *

          + *
        • {@code *}, representing the special value {@link #ALL}
        • + *
        • String value beginning and ending with {@code "}, representing a normal ETag
        • + *
        • String value beginning with {@code W/"} and ending with {@code "}, representing a weak ETag
        • + *
        + * + * If {@code eTag} is null a special null valued ETag will be returned. If the {@code eTag} doesn't meet any of the + * valid ETag values an {@link IllegalArgumentException} will be thrown. + * + * @param eTag The HTTP entity tag string value. + * @return A new instance of {@link ETag}. + * @throws IllegalArgumentException If the {@code eTag} is not a valid ETag value. + */ + public static ETag fromString(String eTag) { + // If the value is null or "*", create the ETag. + if (eTag == null) { + return NULL; + } else if (ASTERISK.equals(eTag)) { + return ALL; + } + + boolean endsWithQuote = eTag.charAt(eTag.length() - 1) == '"'; + boolean startsWithQuote = eTag.charAt(0) == '"'; + boolean startsWithWeakETagPrefix = eTag.startsWith(WEAK_ETAG_PREFIX_QUOTE); + if (!endsWithQuote || (!startsWithQuote && !startsWithWeakETagPrefix)) { + throw LOGGER.atError() + .addKeyValue("ETag", eTag) + .log(new IllegalArgumentException( + "The ETag should be null, '*', be wrapped in quotes, or be wrapped " + "in quotes prefixed by W/")); + } + + return new ETag(eTag); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + + if (!(o instanceof ETag)) { + return false; + } + + return Objects.equals(eTag, ((ETag) o).eTag); + } + + @Override + public int hashCode() { + return Objects.hashCode(eTag); + } + + @Override + public String toString() { + return eTag; + } + + /** + * Checks if the {@code eTag} a valid ETag value. Valid ETags show below, + * - The special character, '*'. + * - A strong ETag, which the value is wrapped in quotes, ex, "12345". + * - A weak ETag, which value is wrapped in quotes and prefixed by "W/", ex, W/"12345". + * + * @param eTag ETag string value. + */ + private void checkValidETag(String eTag) { + + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpHeader.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpHeader.java index 474e02bc7a4f..a164429ad9bc 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpHeader.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpHeader.java @@ -3,14 +3,17 @@ package io.clientcore.core.http.models; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.utils.CoreUtils; + import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; -import static io.clientcore.core.implementation.util.ImplUtils.isNullOrEmpty; -import static io.clientcore.core.implementation.util.ImplUtils.stringJoin; +import static io.clientcore.core.utils.CoreUtils.isNullOrEmpty; /** * Represents a single header to be set on a request. @@ -18,7 +21,8 @@ * If multiple header values are added to a request with the same name (case-insensitive), then the values will be * appended at the end of the same {@link HttpHeader} with commas separating them. */ -public class HttpHeader { +@Metadata(properties = MetadataProperties.FLUENT) +public final class HttpHeader { private static final String[] EMPTY_HEADER_ARRAY = new String[0]; private final HttpHeaderName name; @@ -159,29 +163,6 @@ public void addValue(String value) { CACHED_STRING_VALUE_UPDATER.set(this, null); } - /** - * Add a new value to the end of the Header. - * - * @param values the value to add - */ - public void addValues(List values) { - if (isNullOrEmpty(values)) { - return; - } - - if (this.value == null && this.values == null) { - this.values = new ArrayList<>(values); - return; - } else if (this.values == null) { - this.values = new ArrayList<>(values.size() + 1); - values.add(this.value); - this.value = null; - } - - this.values.addAll(values); - CACHED_STRING_VALUE_UPDATER.set(this, null); - } - /** * Gets the String representation of the header. * @@ -200,6 +181,6 @@ public String toString() { } private void checkCachedStringValue() { - CACHED_STRING_VALUE_UPDATER.compareAndSet(this, null, stringJoin(",", values)); + CACHED_STRING_VALUE_UPDATER.compareAndSet(this, null, CoreUtils.stringJoin(",", values)); } } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpHeaderName.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpHeaderName.java index 361cd07bae42..ead89cf69c36 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpHeaderName.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpHeaderName.java @@ -3,9 +3,10 @@ package io.clientcore.core.http.models; -import io.clientcore.core.util.ExpandableEnum; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.utils.ExpandableEnum; -import java.util.Collection; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; @@ -14,6 +15,7 @@ * Represents common header names. */ @SuppressWarnings("unused") +@Metadata(properties = MetadataProperties.IMMUTABLE) public final class HttpHeaderName implements ExpandableEnum { private static final Map VALUES = new ConcurrentHashMap<>(); private final String caseSensitive; @@ -62,24 +64,9 @@ public static HttpHeaderName fromString(String name) { return null; } - HttpHeaderName httpHeaderName = VALUES.get(name); - - if (httpHeaderName != null) { - return httpHeaderName; - } - return VALUES.computeIfAbsent(name, HttpHeaderName::new); } - /** - * Gets all known {@link HttpHeaderName} values. - * - * @return The known {@link HttpHeaderName} values. - */ - public static Collection values() { - return VALUES.values(); - } - @Override public String toString() { return caseSensitive; @@ -286,11 +273,6 @@ public boolean equals(Object obj) { */ public static final HttpHeaderName HOST = fromString("Host"); - /** - * {@code HTTP2-Settings}/{@code http2-settings} - */ - public static final HttpHeaderName HTTP2_SETTINGS = fromString("HTTP2-Settings"); - /** * {@code If-Match}/{@code if-match} */ diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpHeaders.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpHeaders.java index d087f1569bd7..331d05980441 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpHeaders.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpHeaders.java @@ -3,20 +3,22 @@ package io.clientcore.core.http.models; -import java.util.Collections; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; + import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; -import static io.clientcore.core.implementation.util.ImplUtils.isNullOrEmpty; +import static io.clientcore.core.utils.CoreUtils.isNullOrEmpty; /** * A collection of {@link HttpHeaders} on a request or response. */ -public class HttpHeaders implements Iterable { +@Metadata(properties = MetadataProperties.FLUENT) +public class HttpHeaders { /** * This map is a case-insensitive key (i.e. lower-cased), but the returned {@link HttpHeader} key will be as-provided to * us. @@ -106,7 +108,7 @@ public HttpHeaders add(HttpHeaderName name, String value) { * @param values The values of the {@link HttpHeader}. * @return The updated {@link HttpHeaders} object. */ - public HttpHeaders add(HttpHeaderName name, List values) { + private HttpHeaders add(HttpHeaderName name, List values) { if (name == null || isNullOrEmpty(values)) { return this; } @@ -115,7 +117,9 @@ public HttpHeaders add(HttpHeaderName name, List values) { if (header == null) { return new HttpHeader(name, values); } else { - header.addValues(values); + for (String value : values) { + header.addValue(value); + } return header; } }); @@ -126,9 +130,8 @@ public HttpHeaders add(HttpHeaderName name, List values) { /** * Adds all the provided {@link HttpHeaders} into this {@link HttpHeaders} instance. * - *

        This is the equivalent to calling - * {@code headers.forEach(header -> add(header.getName(), header.getValuesList())} and therefore the behavior is as - * specified in {@link #add(HttpHeaderName, List)}.

        + *

        This is the equivalent to calling {@code headers.forEach(header -> add(header)} and therefore the behavior is + * as specified in {@link #add(HttpHeader)}.

        * *

        If {@code headers} is {@code null} this is a no-op.

        * @@ -266,37 +269,6 @@ public List getValues(HttpHeaderName name) { return header == null ? null : header.getValues(); } - /** - * Returns a copy of the {@link HttpHeaders} as an unmodifiable {@link Map} representation of the state of the - * {@link HttpHeaders} at the time of the {@code toMap} call. This map will not change as the underlying {@link HttpHeaders} - * change, and nor will modifying the key or values contained in the map have any effect on the state of the - * {@link HttpHeaders}. - * - *

        Note that there may be performance implications of using {@link Map} APIs on the returned {@link Map}. It is - * highly recommended that users prefer to use alternate APIs present on the {@link HttpHeaders} class, over using APIs - * present on the returned {@link Map} class. For example, use the {@link #get(HttpHeaderName)} API, rather than - * {@code headers.toMap().get(name)}.

        - * - * @return The {@link HttpHeaders} in a copied and unmodifiable form. - */ - public Map toMap() { - final Map result = new HashMap<>(); - - for (final HttpHeader header : headers.values()) { - result.put(header.getName().getCaseInsensitiveName(), header.getValue()); - } - - return Collections.unmodifiableMap(result); - } - - /** - * {@inheritDoc} - */ - @Override - public Iterator iterator() { - return headers.values().iterator(); - } - /** * Get a {@link Stream} representation of the {@link HttpHeader} values in this instance. * diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpLogOptions.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpLogOptions.java deleted file mode 100644 index 1814586f3779..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpLogOptions.java +++ /dev/null @@ -1,234 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.http.models; - -import io.clientcore.core.util.configuration.Configuration; - -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Objects; -import java.util.Set; - -import static io.clientcore.core.util.configuration.Configuration.getGlobalConfiguration; - -/** - * The log configurations for HTTP messages. - */ -public final class HttpLogOptions { - private HttpLogDetailLevel logLevel; - private Set allowedHeaderNames; - private Set allowedQueryParamNames; - private static final List DEFAULT_HEADERS_ALLOWLIST - = Arrays.asList(HttpHeaderName.TRACEPARENT, HttpHeaderName.ACCEPT, HttpHeaderName.CACHE_CONTROL, - HttpHeaderName.CONNECTION, HttpHeaderName.CONTENT_LENGTH, HttpHeaderName.CONTENT_TYPE, HttpHeaderName.DATE, - HttpHeaderName.ETAG, HttpHeaderName.EXPIRES, HttpHeaderName.IF_MATCH, HttpHeaderName.IF_MODIFIED_SINCE, - HttpHeaderName.IF_NONE_MATCH, HttpHeaderName.IF_UNMODIFIED_SINCE, HttpHeaderName.LAST_MODIFIED, - HttpHeaderName.PRAGMA, HttpHeaderName.RETRY_AFTER, HttpHeaderName.SERVER, HttpHeaderName.TRANSFER_ENCODING, - HttpHeaderName.USER_AGENT, HttpHeaderName.WWW_AUTHENTICATE); - - private static final List DEFAULT_QUERY_PARAMS_ALLOWLIST = Collections.singletonList("api-version"); - - /** - * Creates a new instance that does not log any information about HTTP requests or responses. - */ - public HttpLogOptions() { - logLevel = HttpLogDetailLevel.ENVIRONMENT_HTTP_LOG_DETAIL_LEVEL; - allowedHeaderNames = new HashSet<>(DEFAULT_HEADERS_ALLOWLIST); - allowedQueryParamNames = new HashSet<>(DEFAULT_QUERY_PARAMS_ALLOWLIST); - } - - /** - * Gets the level of detail to log on HTTP messages. - * - * @return The {@link HttpLogDetailLevel}. - */ - public HttpLogDetailLevel getLogLevel() { - return logLevel; - } - - /** - * Sets the level of detail to log on Http messages. - * - *

        If logLevel is not provided, default value of {@link HttpLogDetailLevel#NONE} is set.

        - * - * @param logLevel The {@link HttpLogDetailLevel}. - * - * @return The updated HttpLogOptions object. - */ - public HttpLogOptions setLogLevel(final HttpLogDetailLevel logLevel) { - this.logLevel = logLevel == null ? HttpLogDetailLevel.NONE : logLevel; - - return this; - } - - /** - * Gets the allowed headers that should be logged. - * - * @return The list of allowed headers. - */ - public Set getAllowedHeaderNames() { - return Collections.unmodifiableSet(allowedHeaderNames); - } - - /** - * Sets the given allowed headers that should be logged. - * - *

        - * This method sets the provided header names to be the allowed header names which will be logged for all HTTP - * requests and responses, overwriting any previously configured headers. Additionally, users can use - * {@link HttpLogOptions#addAllowedHeaderName(HttpHeaderName)} or {@link HttpLogOptions#getAllowedHeaderNames()} to add or - * remove more headers names to the existing set of allowed header names. - *

        - * - * @param allowedHeaderNames The list of allowed header names from the user. - * - * @return The updated HttpLogOptions object. - */ - public HttpLogOptions setAllowedHeaderNames(final Set allowedHeaderNames) { - this.allowedHeaderNames = allowedHeaderNames == null ? new HashSet<>() : allowedHeaderNames; - - return this; - } - - /** - * Sets the given allowed header to the default header set that should be logged. - * - * @param allowedHeaderName The allowed header name from the user. - * - * @return The updated HttpLogOptions object. - * - * @throws NullPointerException If {@code allowedHeaderName} is {@code null}. - */ - public HttpLogOptions addAllowedHeaderName(final HttpHeaderName allowedHeaderName) { - Objects.requireNonNull(allowedHeaderName); - this.allowedHeaderNames.add(allowedHeaderName); - - return this; - } - - /** - * Gets the allowed query parameters. - * - * @return The list of allowed query parameters. - */ - public Set getAllowedQueryParamNames() { - return Collections.unmodifiableSet(allowedQueryParamNames); - } - - /** - * Sets the given allowed query params to be displayed in the logging info. - * - * @param allowedQueryParamNames The list of allowed query params from the user. - * - * @return The updated HttpLogOptions object. - */ - public HttpLogOptions setAllowedQueryParamNames(final Set allowedQueryParamNames) { - this.allowedQueryParamNames = allowedQueryParamNames == null ? new HashSet<>() : allowedQueryParamNames; - - return this; - } - - /** - * Sets the given allowed query param that should be logged. - * - * @param allowedQueryParamName The allowed query param name from the user. - * - * @return The updated HttpLogOptions object. - * - * @throws NullPointerException If {@code allowedQueryParamName} is {@code null}. - */ - public HttpLogOptions addAllowedQueryParamName(final String allowedQueryParamName) { - this.allowedQueryParamNames.add(allowedQueryParamName); - return this; - } - - /** - * The level of detail to log on HTTP messages. - */ - public enum HttpLogDetailLevel { - /** - * Logging is turned off. - */ - NONE, - - /** - * Logs only URIs, HTTP methods, and time to finish the request. - */ - BASIC, - - /** - * Logs everything in BASIC, plus all allowed request and response headers. - */ - HEADERS, - - /** - * 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. - */ - BODY, - - /** - * Logs everything in HEADERS and BODY. - */ - BODY_AND_HEADERS; - - static final String BASIC_VALUE = "basic"; - static final String HEADERS_VALUE = "headers"; - static final String BODY_VALUE = "body"; - static final String BODY_AND_HEADERS_VALUE = "body_and_headers"; - static final String BODYANDHEADERS_VALUE = "bodyandheaders"; - static final HttpLogDetailLevel ENVIRONMENT_HTTP_LOG_DETAIL_LEVEL = fromConfiguration(getGlobalConfiguration()); - - static HttpLogDetailLevel fromConfiguration(Configuration configuration) { - String detailLevel = configuration.get(Configuration.PROPERTY_HTTP_LOG_DETAIL_LEVEL, "none"); - - HttpLogDetailLevel logDetailLevel; - - if (BASIC_VALUE.equalsIgnoreCase(detailLevel)) { - logDetailLevel = BASIC; - } else if (HEADERS_VALUE.equalsIgnoreCase(detailLevel)) { - logDetailLevel = HEADERS; - } else if (BODY_VALUE.equalsIgnoreCase(detailLevel)) { - logDetailLevel = BODY; - } else if (BODY_AND_HEADERS_VALUE.equalsIgnoreCase(detailLevel) - || BODYANDHEADERS_VALUE.equalsIgnoreCase(detailLevel)) { - - logDetailLevel = BODY_AND_HEADERS; - } else { - logDetailLevel = NONE; - } - - return logDetailLevel; - } - - /** - * Whether a URI should be logged. - * - * @return Whether a URI should be logged. - */ - public boolean shouldLogUri() { - return this != NONE; - } - - /** - * Whether headers should be logged. - * - * @return Whether headers should be logged. - */ - public boolean shouldLogHeaders() { - return this == HEADERS || this == BODY_AND_HEADERS; - } - - /** - * Whether a body should be logged. - * - * @return Whether a body should be logged. - */ - public boolean shouldLogBody() { - return this == BODY || this == BODY_AND_HEADERS; - } - } -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpMatchConditions.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpMatchConditions.java new file mode 100644 index 000000000000..b95a5a87b46d --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpMatchConditions.java @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.http.models; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; + +/** + *

        Specifies HTTP options for conditional requests based on ETag matching.

        + * + *

        This class encapsulates the ETag conditions that can be used in a request, such as If-Match and If-None-Match.

        + * + *

        This class is useful when you want to create an HTTP request with conditional headers based on ETag matching. For example, + * you can use it to create a GET request that only retrieves the resource if it has not been modified (based on the ETag), or a + * PUT request that only updates the resource if it has not been modified by another client (based on the ETag).

        + * + * @see HttpRequest + */ +@Metadata(properties = MetadataProperties.FLUENT) +public class HttpMatchConditions { + private String ifMatch; + private String ifNoneMatch; + + /** + * Creates a new instance of {@link HttpMatchConditions}. + */ + public HttpMatchConditions() { + } + + /** + * Gets the ETag that resources must match. + * + * @return The ETag that resources must match. + */ + public String getIfMatch() { + return ifMatch; + } + + /** + * Optionally limit requests to resources that match the passed ETag. + * + * @param ifMatch ETag that resources must match. + * @return The updated MatchConditions object. + */ + public HttpMatchConditions setIfMatch(String ifMatch) { + this.ifMatch = ifMatch; + return this; + } + + /** + * Gets the ETag that resources must not match. + * + * @return The ETag that resources must not match. + */ + public String getIfNoneMatch() { + return ifNoneMatch; + } + + /** + * Optionally limit requests to resources that do not match the passed ETag. + * + * @param ifNoneMatch ETag that resources must not match. + * @return The updated MatchConditions object. + */ + public HttpMatchConditions setIfNoneMatch(String ifNoneMatch) { + this.ifNoneMatch = ifNoneMatch; + return this; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpRange.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpRange.java new file mode 100644 index 000000000000..fd2c0e78cb83 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpRange.java @@ -0,0 +1,118 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.http.models; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.instrumentation.logging.ClientLogger; + +import java.util.Objects; + +/** + *

        Represents a range of bytes within an HTTP resource.

        + * + *

        This class encapsulates a range of bytes that can be requested from an HTTP resource. The range starts at the + * {@link #getOffset()} inclusively and ends at {@link #getOffset()} + {@link #getLength()} exclusively, or offset + length - 1.

        + * + *

        If {@link #getLength()} is unspecified or null, the range extends to the end of the HTTP resource.

        + * + *

        This class is useful when you want to request a specific range of bytes from an HTTP resource, such as a part of a file. + * For example, you can use it to download a part of a file, to resume a download, or to stream a video from a specific point.

        + * + * @see HttpRequest + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public final class HttpRange { + // HttpRange can be a highly used, short-lived class, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(HttpRange.class); + + private final long offset; + private final Long length; + + /** + * Creates an instance of {@link HttpRange}. + *

        + * This creates a range which has an unbounded length starting at the specified {@code offset}. + * + * @param offset The offset to begin the range. + * @throws IllegalArgumentException If {@code offset} is less than 0. + */ + public HttpRange(long offset) { + this(offset, null); + } + + /** + * Creates an instance of {@link HttpRange}. + * + * @param offset The offset to begin the range. + * @param length The length of the range. + * @throws IllegalArgumentException If {@code offset} is less than 0 or {@code length} is non-null and is less than + * or equal to 0. + */ + public HttpRange(long offset, Long length) { + if (offset < 0) { + throw LOGGER.logThrowableAsError(new IllegalArgumentException("'offset' cannot be less than 0.")); + } + + if (length != null && length <= 0) { + throw LOGGER + .logThrowableAsError(new IllegalArgumentException("'length' cannot be equal to or less than 0.")); + } + + this.offset = offset; + this.length = length; + } + + /** + * Gets the offset of the range. + * + * @return Offset of the range. + */ + public long getOffset() { + return offset; + } + + /** + * Gets the length of the range. + *

        + * If the length is null the range continues to the end of the HTTP resource. + * + * @return Length of the range or null if range continues to the end of the HTTP resource. + */ + public Long getLength() { + return length; + } + + @Override + public int hashCode() { + return Objects.hash(offset, length); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof HttpRange)) { + return false; + } + + if (obj == this) { + return true; + } + + HttpRange other = (HttpRange) obj; + return other.offset == this.offset && Objects.equals(other.length, this.length); + } + + /** + * Gets the string representation of the range. + *

        + * If length is null the returned string will be {@code "bytes=-"}, if length is not null the returned + * string will be {@code "bytes=-"}. + * + * @return The string representation of the range. + */ + @Override + public String toString() { + return (length == null) ? "bytes=" + offset + "-" : "bytes=" + offset + "-" + (offset + length - 1); + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpRequest.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpRequest.java index c94e3f4e8d71..4896c8a3c10f 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpRequest.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpRequest.java @@ -3,22 +3,22 @@ package io.clientcore.core.http.models; -import io.clientcore.core.annotation.Metadata; +import io.clientcore.core.annotations.Metadata; import io.clientcore.core.implementation.http.HttpRequestAccessHelper; import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.util.binarydata.BinaryData; +import io.clientcore.core.models.binarydata.BinaryData; import java.net.URI; import java.net.URISyntaxException; import java.util.Objects; -import static io.clientcore.core.annotation.TypeConditions.FLUENT; +import static io.clientcore.core.annotations.MetadataProperties.FLUENT; /** * The outgoing HTTP request. This class provides ways to construct it with an {@link HttpMethod}, {@link URI}, * {@link HttpHeader} and request body. */ -@Metadata(conditions = FLUENT) +@Metadata(properties = FLUENT) public class HttpRequest { // HttpRequest is a highly used, short-lived class, use a static logger. private static final ClientLogger LOGGER = new ClientLogger(HttpRequest.class); @@ -47,31 +47,8 @@ public HttpRequest setTryCount(HttpRequest httpRequest, int tryCount) { /** * Create a new {@link HttpRequest} instance. - * - * @param httpMethod The request {@link HttpMethod}. - * @param uri The target address to send the request to as a {@link URI}. - * @throws NullPointerException if {@code uri} is {@code null}. */ - public HttpRequest(HttpMethod httpMethod, URI uri) { - this.httpMethod = Objects.requireNonNull(httpMethod, "'httpMethod' cannot be null"); - this.uri = Objects.requireNonNull(uri, "'uri' cannot be null"); - this.headers = new HttpHeaders(); - this.requestOptions = RequestOptions.none(); - } - - /** - * Create a new {@link HttpRequest} instance. - * - * @param httpMethod The request {@link HttpMethod}. - * @param uri The target address to send the request to. - * @throws NullPointerException if {@code uri} is {@code null}. - * @throws IllegalArgumentException If {@code uri} cannot be parsed into a valid {@link URI}. - */ - public HttpRequest(HttpMethod httpMethod, String uri) { - this.httpMethod = Objects.requireNonNull(httpMethod, "'httpMethod' cannot be null"); - - setUri(uri); - + public HttpRequest() { this.headers = new HttpHeaders(); this.requestOptions = RequestOptions.none(); } @@ -92,9 +69,8 @@ public HttpMethod getHttpMethod() { * @return The updated {@link HttpRequest}. * @throws NullPointerException if {@code httpMethod} is {@code null}. */ - public HttpRequest setHttpMethod(HttpMethod httpMethod) { + public HttpRequest setMethod(HttpMethod httpMethod) { this.httpMethod = Objects.requireNonNull(httpMethod, "'httpMethod' cannot be null"); - return this; } @@ -116,7 +92,6 @@ public URI getUri() { */ public HttpRequest setUri(URI uri) { this.uri = Objects.requireNonNull(uri, "'uri' cannot be null"); - return this; } @@ -155,7 +130,6 @@ public HttpHeaders getHeaders() { */ public HttpRequest setHeaders(HttpHeaders headers) { this.headers = headers; - return this; } @@ -207,7 +181,6 @@ public RequestOptions getRequestOptions() { */ public HttpRequest setRequestOptions(RequestOptions requestOptions) { this.requestOptions = requestOptions; - return this; } @@ -228,7 +201,6 @@ public ServerSentEventListener getServerSentEventListener() { */ public HttpRequest setServerSentEventListener(ServerSentEventListener serverSentEventListener) { this.serverSentEventListener = serverSentEventListener; - return this; } @@ -251,7 +223,6 @@ private int getTryCount() { */ private HttpRequest setTryCount(int tryCount) { this.tryCount = tryCount; - return this; } } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpRequestConditions.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpRequestConditions.java new file mode 100644 index 000000000000..612f7e76512c --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpRequestConditions.java @@ -0,0 +1,102 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.http.models; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; + +import java.time.OffsetDateTime; + +/** + *

        Specifies HTTP options for conditional requests based on modification time and ETag matching.

        + * + *

        This class extends {@link HttpMatchConditions} and adds conditions based on the modification time of the resource. + * It encapsulates conditions such as If-Modified-Since and If-Unmodified-Since, in addition to If-Match and + * If-None-Match from {@link HttpMatchConditions}.

        + * + *

        This class is useful when you want to create an HTTP request with conditional headers based on the modification + * time of the resource and ETag matching. For example, you can use it to create a GET request that only retrieves the + * resource if it has been modified since a specific time, or a PUT request that only updates the resource if it + * has not been modified by another client since a specific time.

        + * + * @see HttpMatchConditions + * @see OffsetDateTime + */ +@Metadata(properties = MetadataProperties.FLUENT) +public class HttpRequestConditions extends HttpMatchConditions { + private OffsetDateTime ifModifiedSince; + private OffsetDateTime ifUnmodifiedSince; + + /** + * Creates a new instance of {@link HttpRequestConditions}. + */ + public HttpRequestConditions() { + } + + /** + * Optionally limit requests to resources that match the passed ETag. + * + * @param ifMatch ETag that resources must match. + * @return The updated ResourceConditions object. + */ + @Override + public HttpRequestConditions setIfMatch(String ifMatch) { + super.setIfMatch(ifMatch); + return this; + } + + /** + * Optionally limit requests to resources that do not match the passed ETag. + * + * @param ifNoneMatch ETag that resources must not match. + * @return The updated ResourceConditions object. + */ + @Override + public HttpRequestConditions setIfNoneMatch(String ifNoneMatch) { + super.setIfNoneMatch(ifNoneMatch); + return this; + } + + /** + * Gets the {@link OffsetDateTime datetime} that resources must have been modified since. + * + * @return The datetime that resources must have been modified since. + */ + public OffsetDateTime getIfModifiedSince() { + return ifModifiedSince; + } + + /** + * Optionally limit requests to resources that have only been modified since the passed + * {@link OffsetDateTime datetime}. + * + * @param ifModifiedSince The datetime that resources must have been modified since. + * @return The updated ResourceConditions object. + */ + public HttpRequestConditions setIfModifiedSince(OffsetDateTime ifModifiedSince) { + this.ifModifiedSince = ifModifiedSince; + return this; + } + + /** + * Gets the {@link OffsetDateTime datetime} that resources must have remained unmodified since. + * + * @return The datetime that resources must have remained unmodified since. + */ + public OffsetDateTime getIfUnmodifiedSince() { + return ifUnmodifiedSince; + } + + /** + * Optionally limit requests to resources that have remained unmodified since the passed + * {@link OffsetDateTime datetime}. + * + * @param ifUnmodifiedSince The datetime that resources must have remained unmodified since. + * @return The updated ResourceConditions object. + */ + public HttpRequestConditions setIfUnmodifiedSince(OffsetDateTime ifUnmodifiedSince) { + this.ifUnmodifiedSince = ifUnmodifiedSince; + return this; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpResponse.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpResponse.java deleted file mode 100644 index 7236e288eeb4..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpResponse.java +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.http.models; - -import io.clientcore.core.implementation.http.HttpResponseAccessHelper; -import io.clientcore.core.util.binarydata.BinaryData; - -import java.io.IOException; -import java.util.function.Function; - -/** - * The response of an {@link HttpRequest}. - * - * @param The type of the response value. - */ -public class HttpResponse implements Response { - private boolean isValueDeserialized = false; - - static { - HttpResponseAccessHelper.setAccessor(new HttpResponseAccessHelper.HttpResponseAccessor() { - @Override - public HttpResponse setValue(HttpResponse httpResponse, Object value) { - return httpResponse.setValue(value); - } - - @Override - public HttpResponse setBody(HttpResponse httpResponse, BinaryData body) { - return httpResponse.setBody(body); - } - - @Override - public HttpResponse setBodyDeserializer(HttpResponse httpResponse, - Function bodyDeserializer) { - return httpResponse.setBodyDeserializer(bodyDeserializer); - } - }); - } - - private final HttpHeaders headers; - private final HttpRequest request; - private final int statusCode; - - private BinaryData body; - private T value; - - private Function bodyDeserializer; - - /** - * Creates an instance of {@link HttpResponse}. - * - * @param request The {@link HttpRequest} that resulted in this {@link HttpResponse}. - * @param statusCode The response status code. - * @param headers The response {@link HttpHeaders}. - * @param value The response body. - */ - public HttpResponse(HttpRequest request, int statusCode, HttpHeaders headers, T value) { - this.request = request; - this.statusCode = statusCode; - this.headers = headers; - - if (value != null) { - this.value = value; - this.isValueDeserialized = true; - } - } - - /** - * Get all response {@link HttpHeaders}. - * - * @return The response {@link HttpHeaders}. - */ - public final HttpHeaders getHeaders() { - return headers; - } - - /** - * Gets the {@link HttpRequest request} which resulted in this response. - * - * @return The {@link HttpRequest request} which resulted in this response. - */ - public final HttpRequest getRequest() { - return request; - } - - /** - * Get the response status code. - * - * @return The response status code. - */ - public final int getStatusCode() { - return statusCode; - } - - /** - * Gets the value of this response. - * - * @return The value of this response. - */ - @SuppressWarnings("unchecked") - public T getValue() { - if (!isValueDeserialized && bodyDeserializer != null) { - // Deserialize the value - value = (T) bodyDeserializer.apply(getBody()); - - this.isValueDeserialized = true; - } - - return value; - } - - /** - * Gets the {@link BinaryData} that represents the body of the response. - * - * @return The {@link BinaryData} containing the response body. - */ - public BinaryData getBody() { - if (body == null) { - if (value == null) { - body = BinaryData.empty(); - } else if (value instanceof BinaryData) { - body = (BinaryData) value; - } else { - body = BinaryData.fromObject(value); - } - } - - return body; - } - - /** - * Sets the value of this response. - * - * @param value The value. - */ - @SuppressWarnings("unchecked") - private HttpResponse setValue(Object value) { - this.value = (T) value; - - return this; - } - - /** - * Sets the body of this response. - * - * @param body The body. - */ - private HttpResponse setBody(BinaryData body) { - this.body = body; - - return this; - } - - /** - * Sets the body deserializer for this response. - * - * @param bodyDeserializer The body deserializer. - */ - private HttpResponse setBodyDeserializer(Function bodyDeserializer) { - this.bodyDeserializer = bodyDeserializer; - - return this; - } - - @Override - public void close() throws IOException { - BinaryData body = getBody(); - if (body != null) { - body.close(); - } - } -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpResponseException.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpResponseException.java new file mode 100644 index 000000000000..f498e185ceed --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpResponseException.java @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.http.models; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.models.binarydata.BinaryData; + +/** + * The exception thrown when an unsuccessful response is received with http status code (e.g. {@code 3XX}, {@code 4XX}, + * {@code 5XX}) from the service request. + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public class HttpResponseException extends RuntimeException { + /** + * The HTTP response value. + */ + private final Object value; + + /** + * Information about the associated HTTP response. + */ + private final Response response; + + /** + * Initializes a new instance of the HttpResponseException class. + * + * @param message The exception message. + * @param response The {@link Response} received that is associated to the exception. + * @param value The deserialized response value. + */ + public HttpResponseException(final String message, final Response response, final Object value) { + super(message); + + this.value = value; + this.response = response; + } + + /** + * Initializes a new instance of the HttpResponseException class. + * + * @param message The exception message. + * @param response The {@link Response} received that is associated to the exception. + * @param cause The {@link Throwable} which caused the creation of this exception. + */ + public HttpResponseException(final String message, final Response response, final Throwable cause) { + super(message, cause); + + this.value = null; + this.response = response; + } + + /** + * Gets the {@link Response} received that is associated to the exception. + * + * @return The {@link Response} received that is associated to the exception. + */ + public Response getResponse() { + return response; + } + + /** + * Gets the deserialized HTTP response value. + * + * @return The deserialized HTTP response value. + */ + public Object getValue() { + return value; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/PagedResponse.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/PagedResponse.java deleted file mode 100644 index 80488a0c34fa..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/PagedResponse.java +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.http.models; - -import io.clientcore.core.util.binarydata.BinaryData; - -import java.io.IOException; -import java.util.List; - -/** - * Response of a REST API that returns page. - * - * @see Response - * - * @param The type of items in the page. - */ -public final class PagedResponse implements Response> { - - private final HttpRequest request; - private final int statusCode; - private final HttpHeaders headers; - private final BinaryData body; - - private final List items; - private final String continuationToken; - private final String nextLink; - private final String previousLink; - private final String firstLink; - private final String lastLink; - - /** - * Creates a new instance of the PagedResponse type. - * - * @param request The HttpRequest that was sent to the service whose response resulted in this response. - * @param statusCode The status code from the response. - * @param headers The headers from the response. - * @param body The body from the response. - * @param items The items returned from the service within the response. - */ - public PagedResponse(HttpRequest request, int statusCode, HttpHeaders headers, BinaryData body, List items) { - this(request, statusCode, headers, body, items, null, null, null, null, null); - } - - /** - * Creates a new instance of the PagedResponse type. - * - * @param request The HttpRequest that was sent to the service whose response resulted in this response. - * @param statusCode The status code from the response. - * @param headers The headers from the response. - * @param body The body from the response. - * @param items The items returned from the service within the response. - * @param continuationToken The continuation token returned from the service, to enable future requests to pick up - * from the same place in the paged iteration. - * @param nextLink The next page link returned from the service. - * @param previousLink The previous page link returned from the service. - * @param firstLink The first page link returned from the service. - * @param lastLink The last page link returned from the service. - */ - public PagedResponse(HttpRequest request, int statusCode, HttpHeaders headers, BinaryData body, List items, - String continuationToken, String nextLink, String previousLink, String firstLink, String lastLink) { - this.request = request; - this.statusCode = statusCode; - this.headers = headers; - this.body = body; - this.items = items; - this.continuationToken = continuationToken; - this.nextLink = nextLink; - this.previousLink = previousLink; - this.firstLink = firstLink; - this.lastLink = lastLink; - } - - /** - * Gets the continuation token. - * - * @return The continuation token, or null if there isn't a next page. - */ - public String getContinuationToken() { - return continuationToken; - } - - /** - * Gets the link to the next page. - * - * @return The next page link, or null if there isn't a next page. - */ - public String getNextLink() { - return nextLink; - } - - /** - * Gets the link to the previous page. - * - * @return The previous page link, or null if there isn't a previous page. - */ - public String getPreviousLink() { - return previousLink; - } - - /** - * Gets the link to the first page. - * - * @return The first page link - */ - public String getFirstLink() { - return firstLink; - } - - /** - * Gets the link to the last page. - * - * @return The last page link - */ - public String getLastLink() { - return lastLink; - } - - /** - * {@inheritDoc} - */ - @Override - public int getStatusCode() { - return statusCode; - } - - /** - * {@inheritDoc} - */ - @Override - public HttpHeaders getHeaders() { - return headers; - } - - /** - * {@inheritDoc} - */ - @Override - public HttpRequest getRequest() { - return request; - } - - /** - * {@inheritDoc} - */ - @Override - public List getValue() { - return items; - } - - /** - * {@inheritDoc} - */ - @Override - public BinaryData getBody() { - return body; - } - - /** - * {@inheritDoc} - */ - @Override - public void close() throws IOException { - if (body != null) { - body.close(); - } - } -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/ProxyOptions.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/ProxyOptions.java index 40f4ebbfcb83..032034d1cddd 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/ProxyOptions.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/ProxyOptions.java @@ -3,13 +3,13 @@ package io.clientcore.core.http.models; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.util.auth.BasicChallengeHandler; -import io.clientcore.core.util.auth.ChallengeHandler; -import io.clientcore.core.util.auth.DigestChallengeHandler; -import io.clientcore.core.util.configuration.Configuration; -import io.clientcore.core.util.configuration.ConfigurationProperty; -import io.clientcore.core.util.configuration.ConfigurationPropertyBuilder; +import io.clientcore.core.utils.BasicChallengeHandler; +import io.clientcore.core.utils.ChallengeHandler; +import io.clientcore.core.utils.DigestChallengeHandler; +import io.clientcore.core.utils.configuration.Configuration; import java.io.UnsupportedEncodingException; import java.net.InetSocketAddress; @@ -23,12 +23,13 @@ import java.util.regex.PatternSyntaxException; import static io.clientcore.core.implementation.instrumentation.AttributeKeys.URL_FULL_KEY; -import static io.clientcore.core.implementation.util.ImplUtils.isNullOrEmpty; +import static io.clientcore.core.utils.CoreUtils.isNullOrEmpty; /** * This represents proxy configuration to be used in http clients. */ -public class ProxyOptions { +@Metadata(properties = MetadataProperties.FLUENT) +public final class ProxyOptions { private static final ClientLogger LOGGER = new ClientLogger(ProxyOptions.class); private static final String INVALID_PROXY_URI = "URI is invalid and is being ignored."; @@ -66,29 +67,6 @@ public class ProxyOptions { private static final Pattern UNESCAPED_PERIOD = Pattern.compile("(? NON_PROXY_PROPERTY - = ConfigurationPropertyBuilder.ofString(ConfigurationProperties.HTTP_PROXY_NON_PROXY_HOSTS) - .shared(true) - .logValue(true) - .build(); - private static final ConfigurationProperty HOST_PROPERTY - = ConfigurationPropertyBuilder.ofString(ConfigurationProperties.HTTP_PROXY_HOST) - .shared(true) - .logValue(true) - .build(); - private static final ConfigurationProperty PORT_PROPERTY - = ConfigurationPropertyBuilder.ofInteger(ConfigurationProperties.HTTP_PROXY_PORT) - .shared(true) - .defaultValue(DEFAULT_HTTPS_PORT) - .build(); - private static final ConfigurationProperty USER_PROPERTY - = ConfigurationPropertyBuilder.ofString(ConfigurationProperties.HTTP_PROXY_USER) - .shared(true) - .logValue(true) - .build(); - private static final ConfigurationProperty PASSWORD_PROPERTY - = ConfigurationPropertyBuilder.ofString(ConfigurationProperties.HTTP_PROXY_PASSWORD).shared(true).build(); - private final InetSocketAddress address; private final Type type; private String username; @@ -260,14 +238,13 @@ private static ProxyOptions attemptToLoadProxy(Configuration configuration, bool // System proxy configuration is only possible through system properties. // Only use system proxies when the prerequisite property is 'true'. if (Boolean.parseBoolean(configuration.get(JAVA_SYSTEM_PROXY_PREREQUISITE))) { - proxyOptions - = attemptToLoadSystemProxy(configuration, createUnresolved, Configuration.PROPERTY_HTTPS_PROXY); + proxyOptions = attemptToLoadSystemProxy(configuration, createUnresolved, Configuration.HTTPS_PROXY); if (proxyOptions != null) { LOGGER.atVerbose().log("Using proxy created from HTTPS_PROXY environment variable."); return proxyOptions; } - proxyOptions = attemptToLoadSystemProxy(configuration, createUnresolved, Configuration.PROPERTY_HTTP_PROXY); + proxyOptions = attemptToLoadSystemProxy(configuration, createUnresolved, Configuration.HTTP_PROXY); if (proxyOptions != null) { LOGGER.atVerbose().log("Using proxy created from HTTP_PROXY environment variable."); return proxyOptions; @@ -320,7 +297,7 @@ private static ProxyOptions attemptToLoadSystemProxy(Configuration configuration ProxyOptions proxyOptions = new ProxyOptions(Type.HTTP, socketAddress); - String nonProxyHostsString = configuration.get(Configuration.PROPERTY_NO_PROXY); + String nonProxyHostsString = configuration.get(Configuration.NO_PROXY); if (!isNullOrEmpty(nonProxyHostsString)) { proxyOptions.nonProxyHosts = sanitizeNoProxy(nonProxyHostsString); @@ -379,17 +356,18 @@ private static ProxyOptions attemptToLoadJavaProxy(Configuration configuration, } private static ProxyOptions attemptToLoadSdkProxy(Configuration configuration, boolean createUnresolved) { - String host = configuration.get(HOST_PROPERTY); + String host = configuration.get(ConfigurationProperties.HTTP_PROXY_HOST); // No proxy configuration setup. if (isNullOrEmpty(host)) { return null; } - int port = configuration.get(PORT_PROPERTY); - String nonProxyHostsString = configuration.get(NON_PROXY_PROPERTY); - String username = configuration.get(USER_PROPERTY); - String password = configuration.get(PASSWORD_PROPERTY); + String portConfig = configuration.get(ConfigurationProperties.HTTP_PROXY_PORT); + int port = (portConfig == null) ? DEFAULT_HTTPS_PORT : Integer.parseInt(portConfig); + String nonProxyHostsString = configuration.get(ConfigurationProperties.HTTP_PROXY_NON_PROXY_HOSTS); + String username = configuration.get(ConfigurationProperties.HTTP_PROXY_USER); + String password = configuration.get(ConfigurationProperties.HTTP_PROXY_PASSWORD); return createOptions(host, port, nonProxyHostsString, username, password, createUnresolved); } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/RequestOptions.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/RequestOptions.java index 19f9bd7e1ca5..f1b895fa1d20 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/RequestOptions.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/RequestOptions.java @@ -3,13 +3,16 @@ package io.clientcore.core.http.models; -import io.clientcore.core.http.annotation.QueryParam; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.http.annotations.QueryParam; import io.clientcore.core.http.client.HttpClient; import io.clientcore.core.implementation.http.rest.UriEscapers; import io.clientcore.core.instrumentation.InstrumentationContext; import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.util.Context; -import io.clientcore.core.util.binarydata.BinaryData; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.utils.Context; +import io.clientcore.core.utils.ProgressReporter; import java.util.Objects; import java.util.function.Consumer; @@ -103,12 +106,13 @@ * .addRequestCallback(request -> request * // may already be set if request is created from a client * .setUri("https://petstore.example.com/pet") - * .setHttpMethod(HttpMethod.POST) + * .setMethod(HttpMethod.POST) * .setBody(requestBodyData) * .getHeaders().set(HttpHeaderName.CONTENT_TYPE, "application/json")); * * */ +@Metadata(properties = MetadataProperties.FLUENT) public final class RequestOptions { // RequestOptions is a highly used, short-lived class, use a static logger. private static final ClientLogger LOGGER = new ClientLogger(RequestOptions.class); @@ -121,6 +125,7 @@ public final class RequestOptions { private boolean locked; private ClientLogger logger; private InstrumentationContext instrumentationContext; + private ProgressReporter progressReporter; /** * Creates a new instance of {@link RequestOptions}. @@ -174,17 +179,13 @@ public ClientLogger getLogger() { * otherwise a new header will be created.

        * * @param header The header key. - * * @return The updated {@link RequestOptions} object. - * + * @throws NullPointerException If {@code header} is null. * @throws IllegalStateException if this instance is obtained by calling {@link RequestOptions#none()}. */ public RequestOptions addHeader(HttpHeader header) { - if (locked) { - throw LOGGER.logThrowableAsError( - new IllegalStateException("This instance of RequestOptions is immutable. Cannot add header.")); - } - + checkLocked("Cannot add header."); + Objects.requireNonNull(header, "'header' cannot be null."); this.requestCallback = this.requestCallback.andThen(request -> request.getHeaders().add(header)); return this; @@ -197,17 +198,11 @@ public RequestOptions addHeader(HttpHeader header) { * * @param header The header key. * @param value The header value. - * * @return The updated {@link RequestOptions} object. - * * @throws IllegalStateException if this instance is obtained by calling {@link RequestOptions#none()}. */ public RequestOptions setHeader(HttpHeaderName header, String value) { - if (locked) { - throw LOGGER.logThrowableAsError( - new IllegalStateException("This instance of RequestOptions is immutable. Cannot set header.")); - } - + checkLocked("Cannot set header."); this.requestCallback = this.requestCallback.andThen(request -> request.getHeaders().set(header, value)); return this; @@ -219,9 +214,7 @@ public RequestOptions setHeader(HttpHeaderName header, String value) { * * @param parameterName The name of the query parameter. * @param value The value of the query parameter. - * * @return The updated {@link RequestOptions} object. - * * @throws IllegalStateException if this instance is obtained by calling {@link RequestOptions#none()}. */ public RequestOptions addQueryParam(String parameterName, String value) { @@ -236,17 +229,11 @@ public RequestOptions addQueryParam(String parameterName, String value) { * @param parameterName The name of the query parameter. * @param value The value of the query parameter. * @param encoded Whether this query parameter is already encoded. - * * @return The updated {@link RequestOptions} object. - * * @throws IllegalStateException if this instance is obtained by calling {@link RequestOptions#none()}. */ public RequestOptions addQueryParam(String parameterName, String value, boolean encoded) { - if (locked) { - throw LOGGER.logThrowableAsError( - new IllegalStateException("This instance of RequestOptions is immutable. Cannot add query param.")); - } - + checkLocked("Cannot add query param."); this.requestCallback = this.requestCallback.andThen(request -> { String uri = request.getUri().toString(); String encodedParameterName = encoded ? parameterName : UriEscapers.QUERY_ESCAPER.escape(parameterName); @@ -263,20 +250,13 @@ public RequestOptions addQueryParam(String parameterName, String value, boolean * modifications made on a {@link RequestOptions} object are applied in order on the request. * * @param requestCallback The request callback. - * * @return The updated {@link RequestOptions} object. - * - * @throws NullPointerException If {@code requestCallback} is {@code null}. + * @throws NullPointerException If {@code requestCallback} is null. * @throws IllegalStateException if this instance is obtained by calling {@link RequestOptions#none()}. */ public RequestOptions addRequestCallback(Consumer requestCallback) { - if (locked) { - throw LOGGER.logThrowableAsError(new IllegalStateException( - "This instance of RequestOptions is immutable. Cannot add request callback.")); - } - + checkLocked("Cannot add request callback."); Objects.requireNonNull(requestCallback, "'requestCallback' cannot be null."); - this.requestCallback = this.requestCallback.andThen(requestCallback); return this; @@ -286,20 +266,13 @@ public RequestOptions addRequestCallback(Consumer requestCallback) * Sets the body to send as part of the {@link HttpRequest}. * * @param requestBody the request body data - * * @return The updated {@link RequestOptions} object. - * * @throws NullPointerException If {@code requestBody} is {@code null}. * @throws IllegalStateException if this instance is obtained by calling {@link RequestOptions#none()}. */ public RequestOptions setBody(BinaryData requestBody) { - if (locked) { - throw LOGGER.logThrowableAsError( - new IllegalStateException("This instance of RequestOptions is immutable. Cannot set body.")); - } - + checkLocked("Cannot set body."); Objects.requireNonNull(requestBody, "'requestBody' cannot be null."); - this.requestCallback = this.requestCallback.andThen(request -> request.setBody(requestBody)); return this; @@ -309,42 +282,16 @@ public RequestOptions setBody(BinaryData requestBody) { * Sets the additional context on the request that is passed during the service call. * * @param context Additional context that is passed during the service call. - * * @return The updated {@link RequestOptions} object. - * * @throws IllegalStateException if this instance is obtained by calling {@link RequestOptions#none()}. */ public RequestOptions setContext(Context context) { - if (locked) { - throw LOGGER.logThrowableAsError( - new IllegalStateException("This instance of RequestOptions is immutable. Cannot set context.")); - } - + checkLocked("Cannot set context."); this.context = context; return this; } - /** - * Adds a key-value pair to the request context associated with this request. - * - * @param key The key to add to the context. - * @param value The value to add to the context. - * @return The updated {@link RequestOptions} object. - * - * @see #setContext(Context) - */ - public RequestOptions putContext(Object key, Object value) { - if (locked) { - throw LOGGER.logThrowableAsError( - new IllegalStateException("This instance of RequestOptions is immutable. Cannot set context.")); - } - - this.context = this.context.put(key, value); - - return this; - } - /** * Sets the configuration indicating how the body of the resulting HTTP response should be handled. If {@code null}, * the response body will be handled based on the content type of the response. @@ -353,17 +300,11 @@ public RequestOptions putContext(Object key, Object value) { * * @param responseBodyMode The configuration indicating how the body of the resulting HTTP response should be * handled. - * * @return The updated {@link RequestOptions} object. - * * @throws IllegalStateException if this instance is obtained by calling {@link RequestOptions#none()}. */ public RequestOptions setResponseBodyMode(ResponseBodyMode responseBodyMode) { - if (locked) { - throw LOGGER.logThrowableAsError(new IllegalStateException( - "This instance of RequestOptions is immutable. Cannot set response body mode.")); - } - + checkLocked("Cannot set response body mode."); this.responseBodyMode = responseBodyMode; return this; @@ -373,17 +314,11 @@ public RequestOptions setResponseBodyMode(ResponseBodyMode responseBodyMode) { * Sets the {@link ClientLogger} used to log the request and response. * * @param logger The {@link ClientLogger} used to log the request and response. - * * @return The updated {@link RequestOptions} object. - * * @throws IllegalStateException if this instance is obtained by calling {@link RequestOptions#none()}. */ public RequestOptions setLogger(ClientLogger logger) { - if (locked) { - throw LOGGER.logThrowableAsError( - new IllegalStateException("This instance of RequestOptions is immutable. Cannot set logger.")); - } - + checkLocked("Cannot set logger."); this.logger = logger; return this; @@ -424,19 +359,43 @@ public InstrumentationContext getInstrumentationContext() { * Sets the {@link InstrumentationContext} used to instrument the request. * * @param instrumentationContext The {@link InstrumentationContext} used to instrument the request. - * * @return The updated {@link RequestOptions} object. - * * @throws IllegalStateException if this instance is obtained by calling {@link RequestOptions#none()}. */ public RequestOptions setInstrumentationContext(InstrumentationContext instrumentationContext) { - if (locked) { - throw LOGGER.logThrowableAsError(new IllegalStateException( - "This instance of RequestOptions is immutable. Cannot set instrumentation context.")); - } - + checkLocked("Cannot set instrumentation context."); this.instrumentationContext = instrumentationContext; return this; } + + /** + * Gets the {@link ProgressReporter} used to track progress of I/O operations of the request. + * + * @return The {@link ProgressReporter} used to track progress of I/O operations of the request. + */ + public ProgressReporter getProgressReporter() { + return progressReporter; + } + + /** + * Sets the {@link ProgressReporter} used to track progress of I/O operations of the request. + * + * @param progressReporter The {@link ProgressReporter} used to track progress of I/O operations of the request. + * @return The updated {@link RequestOptions} object. + * @throws IllegalStateException if this instance is obtained by calling {@link RequestOptions#none()}. + */ + public RequestOptions setProgressReporter(ProgressReporter progressReporter) { + checkLocked("Cannot set progress reporter."); + this.progressReporter = progressReporter; + + return this; + } + + private void checkLocked(String setterMessage) { + if (locked) { + throw LOGGER.logThrowableAsError( + new IllegalStateException("This instance of RequestOptions is immutable. " + setterMessage)); + } + } } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/Response.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/Response.java index 1e32fe207cbe..f8c8a0eed7f1 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/Response.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/Response.java @@ -3,63 +3,80 @@ package io.clientcore.core.http.models; -import io.clientcore.core.util.binarydata.BinaryData; - import java.io.Closeable; +import java.io.IOException; /** * REST response with a strongly-typed content specified. * * @param The deserialized type of the response content, available from {@link #getValue()}. */ -public interface Response extends Closeable { +public class Response implements Closeable { + private final HttpHeaders headers; + private final HttpRequest request; + private final int statusCode; + private final T value; + + /** + * Creates an instance of {@link Response}. + * + * @param request The {@link HttpRequest} that resulted in this {@link Response}. + * @param statusCode The response status code. + * @param headers The response {@link HttpHeaders}. + * @param value The deserialized value of the response. + */ + public Response(HttpRequest request, int statusCode, HttpHeaders headers, T value) { + this.request = request; + this.statusCode = statusCode; + this.headers = headers; + this.value = value; + } + /** * Gets the response status code. * * @return The status code of the response. */ - int getStatusCode(); + public final int getStatusCode() { + return statusCode; + } /** * Gets the headers from the response. * * @return The response headers. */ - HttpHeaders getHeaders(); + public final HttpHeaders getHeaders() { + return headers; + } /** * Gets the request which resulted in this response. * * @return The request. */ - HttpRequest getRequest(); + public final HttpRequest getRequest() { + return request; + } /** * Gets the deserialized value of this response. * * @return The deserialized value of this response. */ - T getValue(); - - /** - * Gets the {@link BinaryData} that represents the raw body of the response. - * - * @return The {@link BinaryData} containing the response body. - */ - BinaryData getBody(); + public T getValue() { + return value; + } /** - * A static method that creates a default {@link Response} implementation. - * - * @param The deserialized type of the response content, available from {@link #getValue()}. - * @param request The request which resulted in this response. - * @param statusCode The response status code. - * @param headers The response headers. - * @param value The deserialized value of the response. + * If {@link #getValue()} is a {@link Closeable} type, this method will close it. * - * @return A default {@link Response} implementation. + * @throws IOException If an error occurs while closing the response. */ - static Response create(HttpRequest request, int statusCode, HttpHeaders headers, T value) { - return new HttpResponse<>(request, statusCode, headers, value); + @Override + public void close() throws IOException { + if (value instanceof Closeable) { + ((Closeable) value).close(); + } } } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/ServerSentEvent.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/ServerSentEvent.java index b0362881b244..18e1ef64eeac 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/ServerSentEvent.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/ServerSentEvent.java @@ -3,7 +3,9 @@ package io.clientcore.core.http.models; -import io.clientcore.core.implementation.util.ServerSentEventHelper; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.implementation.utils.ServerSentEventHelper; import java.time.Duration; import java.util.List; @@ -12,6 +14,7 @@ * Represents the SSE response from the server on event stream interpretation * here. */ +@Metadata(properties = MetadataProperties.FLUENT) public final class ServerSentEvent { private String id; private String event; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/PagedIterable.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/paging/PagedIterable.java similarity index 97% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/PagedIterable.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/http/paging/PagedIterable.java index 3425ad51289d..49965893c172 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/PagedIterable.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/paging/PagedIterable.java @@ -1,8 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.http.models; +package io.clientcore.core.http.paging; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; import io.clientcore.core.instrumentation.logging.ClientLogger; import java.util.Iterator; @@ -18,6 +20,7 @@ * * @param The type of items in the page. */ +@Metadata(properties = MetadataProperties.IMMUTABLE) public final class PagedIterable implements Iterable { private final Function> pageRetriever; @@ -126,7 +129,7 @@ private String getNextLink() { } private Iterable iterableByItemInternal(PagingOptions pagingOptions) { - return () -> new PagedIterator<>(pageRetriever, pagingOptions) { + return () -> new PagedIterator(pageRetriever, pagingOptions) { private Iterator nextPage; private Iterator currentPage; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/paging/PagedResponse.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/paging/PagedResponse.java new file mode 100644 index 000000000000..172dc803f401 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/paging/PagedResponse.java @@ -0,0 +1,108 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.http.paging; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.http.models.HttpHeaders; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; + +import java.util.List; + +/** + * Response of a REST API that returns page. + * + * @param The type of items in the page. + * @see Response + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public final class PagedResponse extends Response> { + private final String continuationToken; + private final String nextLink; + private final String previousLink; + private final String firstLink; + private final String lastLink; + + /** + * Creates a new instance of the PagedResponse type. + * + * @param request The HttpRequest that was sent to the service whose response resulted in this response. + * @param statusCode The status code from the response. + * @param headers The headers from the response. + * @param items The items returned from the service within the response. + */ + public PagedResponse(HttpRequest request, int statusCode, HttpHeaders headers, List items) { + this(request, statusCode, headers, items, null, null, null, null, null); + } + + /** + * Creates a new instance of the PagedResponse type. + * + * @param request The HttpRequest that was sent to the service whose response resulted in this response. + * @param statusCode The status code from the response. + * @param headers The headers from the response. + * @param items The items returned from the service within the response. + * @param continuationToken The continuation token returned from the service, to enable future requests to pick up + * from the same place in the paged iteration. + * @param nextLink The next page link returned from the service. + * @param previousLink The previous page link returned from the service. + * @param firstLink The first page link returned from the service. + * @param lastLink The last page link returned from the service. + */ + public PagedResponse(HttpRequest request, int statusCode, HttpHeaders headers, List items, + String continuationToken, String nextLink, String previousLink, String firstLink, String lastLink) { + super(request, statusCode, headers, items); + this.continuationToken = continuationToken; + this.nextLink = nextLink; + this.previousLink = previousLink; + this.firstLink = firstLink; + this.lastLink = lastLink; + } + + /** + * Gets the continuation token. + * + * @return The continuation token, or null if there isn't a next page. + */ + public String getContinuationToken() { + return continuationToken; + } + + /** + * Gets the link to the next page. + * + * @return The next page link, or null if there isn't a next page. + */ + public String getNextLink() { + return nextLink; + } + + /** + * Gets the link to the previous page. + * + * @return The previous page link, or null if there isn't a previous page. + */ + public String getPreviousLink() { + return previousLink; + } + + /** + * Gets the link to the first page. + * + * @return The first page link + */ + public String getFirstLink() { + return firstLink; + } + + /** + * Gets the link to the last page. + * + * @return The last page link + */ + public String getLastLink() { + return lastLink; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/PagingOptions.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/paging/PagingOptions.java similarity index 91% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/PagingOptions.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/http/paging/PagingOptions.java index 41e64c309902..5b2adc9bdbd4 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/PagingOptions.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/paging/PagingOptions.java @@ -1,11 +1,15 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.http.models; +package io.clientcore.core.http.paging; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; /** * The paging options for the pageable operation. */ +@Metadata(properties = MetadataProperties.FLUENT) public final class PagingOptions { private Long offset; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/paging/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/paging/package-info.java new file mode 100644 index 000000000000..663088765026 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/paging/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * This package contains classes for HTTP pagination. + */ +package io.clientcore.core.http.paging; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/AddHeadersPolicy.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/AddHeadersPolicy.java new file mode 100644 index 000000000000..86744c662960 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/AddHeadersPolicy.java @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.http.pipeline; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.http.models.HttpHeaders; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.models.binarydata.BinaryData; + +/** + *

        The {@code AddHeadersPolicy} class is an implementation of the {@link HttpPipelinePolicy} interface. This policy + * is used to add a set of headers to all outgoing HTTP requests.

        + * + *

        This class is useful when there are certain headers that should be included in all requests. For example, you + * might want to include a "User-Agent" header in all requests to identify your application, or a "Content-Type" header + * to specify the format of the request body.

        + * + *

        Code sample:

        + * + *

        In this example, the {@code AddHeadersPolicy} is created from the specified headers. The policy can be added to + * the pipeline and the requests sent will include the headers specified in the {@code AddHeadersPolicy}.

        + * + * + *
        + * HttpHeaders headers = new HttpHeaders();
        + * headers.set(HttpHeaderName.USER_AGENT, "MyApp/1.0");
        + * headers.set(HttpHeaderName.CONTENT_TYPE, "application/json");
        + *
        + * AddHeadersPolicy policy = new AddHeadersPolicy(headers);
        + * 
        + * + * + * @see io.clientcore.core.http.pipeline + * @see HttpPipelinePolicy + * @see HttpPipeline + * @see HttpRequest + * @see Response + * @see HttpHeaders + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public class AddHeadersPolicy implements HttpPipelinePolicy { + private final HttpHeaders headers; + + /** + * Creates a AddHeadersPolicy. + * + * @param headers The headers to add to outgoing requests. + */ + public AddHeadersPolicy(HttpHeaders headers) { + this.headers = headers; + } + + private static void setHeaders(HttpHeaders requestHeaders, HttpHeaders policyHeaders) { + requestHeaders.addAll(policyHeaders); + } + + @Override + public Response process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { + setHeaders(httpRequest.getHeaders(), headers); + + return next.process(); + } + + @Override + public final HttpPipelinePosition getPipelinePosition() { + return HttpPipelinePosition.AFTER_RETRY; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpCredentialPolicy.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpCredentialPolicy.java new file mode 100644 index 000000000000..95697de5be4a --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpCredentialPolicy.java @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.http.pipeline; + +/** + * This class is exactly the same as {@link HttpPipelinePolicy} but exists to provide a standard parent class for all + * credential policies and to differentiate them from other forms of {@link HttpPipelinePolicy}s. + */ +public abstract class HttpCredentialPolicy implements HttpPipelinePolicy { + /** + * Creates an instance of {@link HttpCredentialPolicy}. + */ + public HttpCredentialPolicy() { + } + + @Override + public final HttpPipelinePosition getPipelinePosition() { + return HttpPipelinePosition.AUTHENTICATION; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpInstrumentationOptions.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpInstrumentationOptions.java new file mode 100644 index 000000000000..4f11ecff8edf --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpInstrumentationOptions.java @@ -0,0 +1,341 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.http.pipeline; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.instrumentation.InstrumentationOptions; +import io.clientcore.core.utils.configuration.Configuration; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; + +/** + * Configuration options for HTTP instrumentation. + *

        + * The instrumentation emits distributed traces following OpenTelemetry HTTP semantic conventions + * and, when enabled, detailed HTTP logs. + *

        + * The following information is recorded on distributed traces: + *

          + *
        • Request method, URI. The URI is sanitized based on allowed query parameters configurable with {@link #setAllowedQueryParamNames(Set)} and {@link #addAllowedQueryParamName(String)}
        • + *
        • Response status code
        • + *
        • Error details if the request fails
        • + *
        • Time it takes to receive response
        • + *
        • Correlation identifiers
        • + *
        + * + The following information is recorded on detailed HTTP logs: + *
          + *
        • Request method, URI, and body size. URI is sanitized based on allowed query parameters configurable with {@link #setAllowedQueryParamNames(Set)} and {@link #addAllowedQueryParamName(String)}
        • + *
        • Response status code and body size
        • + *
        • Request and response headers from allow-list configured via {@link #setAllowedHeaderNames(Set)} and {@link #addAllowedHeaderName(HttpHeaderName)}.
        • + *
        • Error details if the request fails
        • + *
        • Time it takes to receive response
        • + *
        • Correlation identifiers
        • + *
        • When content logging is enabled via {@link HttpLogLevel#BODY_AND_HEADERS}: request and response body, and time-to-last-byte
        • + *
        + * + * Client libraries auto-discover global OpenTelemetry SDK instance configured by the java agent or + * in the application code. Just create a client instance as usual as shown in the following code snippet: + * + *

        Clients auto-discover global OpenTelemetry

        + * + * + *
        + *
        + * AutoConfiguredOpenTelemetrySdk.initialize();
        + *
        + * SampleClient client = new SampleClientBuilder().build();
        + *
        + * // this call will be traced using OpenTelemetry SDK initialized globally
        + * client.clientCall();
        + *
        + * 
        + * + *

        + * + * Alternatively, application developers can pass OpenTelemetry SDK instance explicitly to the client libraries. + * + *

        Pass configured OpenTelemetry instance explicitly

        + * + * + *
        + *
        + * OpenTelemetry openTelemetry = AutoConfiguredOpenTelemetrySdk.initialize().getOpenTelemetrySdk();
        + * HttpInstrumentationOptions instrumentationOptions = new HttpInstrumentationOptions()
        + *     .setTelemetryProvider(openTelemetry);
        + *
        + * SampleClient client = new SampleClientBuilder().instrumentationOptions(instrumentationOptions).build();
        + *
        + * // this call will be traced using OpenTelemetry SDK provided explicitly
        + * client.clientCall();
        + *
        + * 
        + * + */ +@Metadata(properties = MetadataProperties.FLUENT) +public final class HttpInstrumentationOptions extends InstrumentationOptions { + private HttpLogLevel logLevel; + private boolean isRedactedHeaderNamesLoggingEnabled; + private Set allowedHeaderNames; + private Set allowedQueryParamNames; + private static final List DEFAULT_HEADERS_ALLOWLIST + = Arrays.asList(HttpHeaderName.TRACEPARENT, HttpHeaderName.ACCEPT, HttpHeaderName.CACHE_CONTROL, + HttpHeaderName.CONNECTION, HttpHeaderName.CONTENT_LENGTH, HttpHeaderName.CONTENT_TYPE, HttpHeaderName.DATE, + HttpHeaderName.ETAG, HttpHeaderName.EXPIRES, HttpHeaderName.IF_MATCH, HttpHeaderName.IF_MODIFIED_SINCE, + HttpHeaderName.IF_NONE_MATCH, HttpHeaderName.IF_UNMODIFIED_SINCE, HttpHeaderName.LAST_MODIFIED, + HttpHeaderName.PRAGMA, HttpHeaderName.RETRY_AFTER, HttpHeaderName.SERVER, HttpHeaderName.TRANSFER_ENCODING, + HttpHeaderName.USER_AGENT, HttpHeaderName.WWW_AUTHENTICATE); + + static final HttpLogLevel ENVIRONMENT_HTTP_LOG_LEVEL + = HttpLogLevel.fromConfiguration(Configuration.getGlobalConfiguration()); + private static final List DEFAULT_QUERY_PARAMS_ALLOWLIST = Collections.singletonList("api-version"); + + /** + * Creates a new instance using default options: + *
          + *
        • HTTP logging is disabled.
        • + *
        • Distributed tracing is enabled.
        • + *
        + */ + public HttpInstrumentationOptions() { + super(); + logLevel = ENVIRONMENT_HTTP_LOG_LEVEL; + isRedactedHeaderNamesLoggingEnabled = true; + allowedHeaderNames = new HashSet<>(DEFAULT_HEADERS_ALLOWLIST); + allowedQueryParamNames = new HashSet<>(DEFAULT_QUERY_PARAMS_ALLOWLIST); + } + + /** + * Gets the level for HTTP request logs. Default is {@link HttpLogLevel#NONE}. + *

        + * When HTTP logging is disabled, basic information about the request and response is still recorded + * on distributed tracing spans. + * + * @return The {@link HttpLogLevel}. + */ + public HttpLogLevel getHttpLogLevel() { + return logLevel; + } + + /** + * Flag indicating whether HTTP request and response header values are added to the logs + * when their name is not explicitly allowed via {@link HttpInstrumentationOptions#setAllowedHeaderNames(Set)} or + * {@link HttpInstrumentationOptions#addAllowedHeaderName(HttpHeaderName)}. + * True by default. + * + * @return True if redacted header names logging is enabled, false otherwise. + */ + public boolean isRedactedHeaderNamesLoggingEnabled() { + return isRedactedHeaderNamesLoggingEnabled; + } + + /** + * Enables or disables logging of redacted header names. + * @param redactedHeaderNamesLoggingEnabled True to enable logging of redacted header names, false otherwise. + * Default is true. + * @return The updated {@link HttpInstrumentationOptions} object. + */ + public HttpInstrumentationOptions setRedactedHeaderNamesLoggingEnabled(boolean redactedHeaderNamesLoggingEnabled) { + isRedactedHeaderNamesLoggingEnabled = redactedHeaderNamesLoggingEnabled; + return this; + } + + /** + * Sets the level for HTTP request logs. + * Default is {@link HttpLogLevel#NONE}. + * + * @param logLevel The {@link HttpLogLevel}. + * + * @return The updated {@link HttpInstrumentationOptions} object. + */ + public HttpInstrumentationOptions setHttpLogLevel(HttpLogLevel logLevel) { + this.logLevel = logLevel; + return this; + } + + /** + * Gets the allowed headers that should be logged when they appear on the request or response. + * + * @return The list of allowed headers. + */ + public Set getAllowedHeaderNames() { + return Collections.unmodifiableSet(allowedHeaderNames); + } + + /** + * Sets the given allowed headers that should be logged. + * Note: headers are not recorded on traces. + * + *

        + * This method sets the provided header names to be the allowed header names which will be logged for all HTTP + * requests and responses, overwriting any previously configured headers. Additionally, users can use + * {@link HttpInstrumentationOptions#addAllowedHeaderName(HttpHeaderName)} or {@link HttpInstrumentationOptions#getAllowedHeaderNames()} to add or + * remove more headers names to the existing set of allowed header names. + *

        + * + * @param allowedHeaderNames The list of allowed header names from the user. + * + * @return The updated HttpLogOptions object. + */ + public HttpInstrumentationOptions setAllowedHeaderNames(final Set allowedHeaderNames) { + this.allowedHeaderNames = allowedHeaderNames == null ? new HashSet<>() : new HashSet<>(allowedHeaderNames); + + return this; + } + + /** + * Sets the given allowed header to the default header set that should be logged when they appear on the request or response. + *

        + * Note: headers are not recorded on traces. + * + * @param allowedHeaderName The allowed header name from the user. + * + * @return The updated HttpLogOptions object. + * + * @throws NullPointerException If {@code allowedHeaderName} is {@code null}. + */ + public HttpInstrumentationOptions addAllowedHeaderName(final HttpHeaderName allowedHeaderName) { + Objects.requireNonNull(allowedHeaderName); + this.allowedHeaderNames.add(allowedHeaderName); + + return this; + } + + /** + * Gets the allowed query parameters. + * + * @return The list of allowed query parameters. + */ + public Set getAllowedQueryParamNames() { + return Collections.unmodifiableSet(allowedQueryParamNames); + } + + /** + * Sets the given allowed query params to be recorded on logs and traces. + * + * @param allowedQueryParamNames The list of allowed query params from the user. + * + * @return The updated {@code allowedQueryParamName} object. + */ + public HttpInstrumentationOptions setAllowedQueryParamNames(final Set allowedQueryParamNames) { + this.allowedQueryParamNames + = allowedQueryParamNames == null ? new HashSet<>() : new HashSet<>(allowedQueryParamNames); + + return this; + } + + /** + * Sets the given allowed query param that can be recorded on logs and traces. + * + * @param allowedQueryParamName The allowed query param name from the user. + * + * @return The updated {@link HttpInstrumentationOptions} object. + * + * @throws NullPointerException If {@code allowedQueryParamName} is {@code null}. + */ + public HttpInstrumentationOptions addAllowedQueryParamName(final String allowedQueryParamName) { + this.allowedQueryParamNames.add(allowedQueryParamName); + return this; + } + + @Override + public HttpInstrumentationOptions setTracingEnabled(boolean isTracingEnabled) { + super.setTracingEnabled(isTracingEnabled); + return this; + } + + @Override + public HttpInstrumentationOptions setMetricsEnabled(boolean isMetricsEnabled) { + super.setMetricsEnabled(isMetricsEnabled); + return this; + } + + @Override + public HttpInstrumentationOptions setTelemetryProvider(Object telemetryProvider) { + super.setTelemetryProvider(telemetryProvider); + return this; + } + + /** + * The level for HTTP request logs. + */ + public enum HttpLogLevel { + /** + * HTTP logging is turned off. + */ + NONE, + + /** + * Enables logging the following information on detailed HTTP logs + *

          + *
        • Request method, URI, and body size. URI is sanitized based on allowed query parameters configurable with {@link #setAllowedQueryParamNames(Set)} and {@link #addAllowedQueryParamName(String)}
        • + *
        • Response status code and body size
        • + *
        • Request and response headers from allow-list configured via {@link #setAllowedHeaderNames(Set)} and {@link #addAllowedHeaderName(HttpHeaderName)}.
        • + *
        • Error details if the request fails
        • + *
        • Time it takes to receive response
        • + *
        • Correlation identifiers
        • + *
        + */ + HEADERS, + + /** + * Enables logging the following information on detailed HTTP logs + *
          + *
        • Request method, URI, and body size. URI is sanitized based on allowed query parameters configurable with {@link #setAllowedQueryParamNames(Set)} and {@link #addAllowedQueryParamName(String)}
        • + *
        • Response status code and body size
        • + *
        • Error details if the request fails
        • + *
        • Time it takes to receive response
        • + *
        • Correlation identifiers
        • + *
        • Request and response bodies
        • + *
        • Time-to-last-byte
        • + *
        + * + *

        + * The request and response body will be buffered into memory even if it is never consumed by an application, possibly impacting + * performance. + *

        + * Body is not logged (and not buffered) for requests and responses where the content length is not known or greater than 16KB. + */ + BODY, + + /** + * Enables logging everything in {@link #HEADERS} and {@link #BODY}. + * + *

        + * The request and response body will be buffered into memory even if it is never consumed by an application, possibly impacting + * performance. + *

        + * Body is not logged (and not buffered) for requests and responses where the content length is not known or greater than 16KB. + */ + BODY_AND_HEADERS; + + private static final String HEADERS_VALUE = "headers"; + private static final String BODY_VALUE = "body"; + private static final String BODY_AND_HEADERS_VALUE = "body_and_headers"; + + static HttpLogLevel fromConfiguration(Configuration configuration) { + String logLevel = configuration.get(Configuration.HTTP_LOG_LEVEL); + if (logLevel == null) { + logLevel = configuration.get("http.log.level"); + } + + if (HEADERS_VALUE.equalsIgnoreCase(logLevel)) { + return HEADERS; + } else if (BODY_VALUE.equalsIgnoreCase(logLevel)) { + return BODY; + } else if (BODY_AND_HEADERS_VALUE.equalsIgnoreCase(logLevel)) { + return BODY_AND_HEADERS; + } else { + return NONE; + } + } + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpInstrumentationPolicy.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpInstrumentationPolicy.java index 679d30246ee7..73826776bd47 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpInstrumentationPolicy.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpInstrumentationPolicy.java @@ -3,12 +3,11 @@ package io.clientcore.core.http.pipeline; -import io.clientcore.core.http.models.HttpHeader; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; import io.clientcore.core.http.models.HttpHeaderName; import io.clientcore.core.http.models.HttpHeaders; -import io.clientcore.core.http.models.HttpLogOptions; import io.clientcore.core.http.models.HttpRequest; -import io.clientcore.core.http.models.HttpResponse; import io.clientcore.core.http.models.RequestOptions; import io.clientcore.core.http.models.Response; import io.clientcore.core.implementation.http.HttpRequestAccessHelper; @@ -16,28 +15,35 @@ import io.clientcore.core.instrumentation.Instrumentation; import io.clientcore.core.instrumentation.InstrumentationContext; import io.clientcore.core.instrumentation.LibraryInstrumentationOptions; -import io.clientcore.core.instrumentation.InstrumentationOptions; -import io.clientcore.core.instrumentation.tracing.SpanBuilder; -import io.clientcore.core.instrumentation.tracing.TracingScope; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.instrumentation.logging.LogLevel; +import io.clientcore.core.instrumentation.logging.LoggingEvent; +import io.clientcore.core.instrumentation.metrics.DoubleHistogram; +import io.clientcore.core.instrumentation.metrics.Meter; import io.clientcore.core.instrumentation.tracing.Span; +import io.clientcore.core.instrumentation.tracing.SpanBuilder; import io.clientcore.core.instrumentation.tracing.TraceContextPropagator; import io.clientcore.core.instrumentation.tracing.TraceContextSetter; import io.clientcore.core.instrumentation.tracing.Tracer; -import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.util.binarydata.BinaryData; +import io.clientcore.core.instrumentation.tracing.TracingScope; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.utils.CoreUtils; import java.io.IOException; import java.io.InputStream; +import java.util.Arrays; import java.util.Collections; +import java.util.HashMap; +import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.function.Consumer; import java.util.stream.Collectors; -import java.net.URI; import static io.clientcore.core.implementation.UrlRedactionUtil.getRedactedUri; +import static io.clientcore.core.implementation.instrumentation.AttributeKeys.ERROR_TYPE_KEY; import static io.clientcore.core.implementation.instrumentation.AttributeKeys.HTTP_REQUEST_BODY_CONTENT_KEY; import static io.clientcore.core.implementation.instrumentation.AttributeKeys.HTTP_REQUEST_BODY_SIZE_KEY; import static io.clientcore.core.implementation.instrumentation.AttributeKeys.HTTP_REQUEST_DURATION_KEY; @@ -53,9 +59,9 @@ import static io.clientcore.core.implementation.instrumentation.AttributeKeys.SERVER_PORT_KEY; import static io.clientcore.core.implementation.instrumentation.AttributeKeys.URL_FULL_KEY; import static io.clientcore.core.implementation.instrumentation.AttributeKeys.USER_AGENT_ORIGINAL_KEY; +import static io.clientcore.core.implementation.instrumentation.InstrumentationUtils.getServerPort; import static io.clientcore.core.implementation.instrumentation.LoggingEventNames.HTTP_REQUEST_EVENT_NAME; import static io.clientcore.core.implementation.instrumentation.LoggingEventNames.HTTP_RESPONSE_EVENT_NAME; -import static io.clientcore.core.implementation.util.ImplUtils.isNullOrEmpty; import static io.clientcore.core.instrumentation.tracing.SpanKind.CLIENT; /** @@ -65,11 +71,11 @@ *

        * It propagates context to the downstream service following W3C Trace Context specification. *

        - * The {@link HttpInstrumentationPolicy} should be added to the HTTP pipeline by client libraries. It should be added after - * {@link HttpRetryPolicy} and {@link HttpRedirectPolicy} so that it's executed on each try or redirect and logging happens - * in the scope of the span. + * The {@link HttpInstrumentationPolicy} should be added to the HTTP pipeline by client libraries. It should be added + * after {@link HttpRetryPolicy} and {@link HttpRedirectPolicy} so that it's executed on each try or redirect and + * logging happens in the scope of the span. *

        - * The policy supports basic customizations using {@link InstrumentationOptions} and {@link HttpLogOptions}. + * The policy supports basic customizations using {@link HttpInstrumentationOptions}. *

        * If your client library needs a different approach to distributed tracing, * you can create a custom policy and use it instead of the {@link HttpInstrumentationPolicy}. If you want to enrich instrumentation @@ -77,66 +83,71 @@ * so that it's executed in the scope of the span created by the {@link HttpInstrumentationPolicy}. * *

        Configure instrumentation policy:

        - * + * *
          *
          * HttpPipeline pipeline = new HttpPipelineBuilder()
        - *     .policies(
        - *         new HttpRetryPolicy(),
        - *         new HttpInstrumentationPolicy(instrumentationOptions, logOptions))
        + *     .addPolicy(new HttpRetryPolicy())
        + *     .addPolicy(new HttpInstrumentationPolicy(instrumentationOptions))
          *     .build();
          *
          * 
        - * + * * *

        Customize instrumentation policy:

        - * + * *
          *
          * // You can configure URL sanitization to include additional query parameters to preserve
          * // in `url.full` attribute.
        - * HttpLogOptions logOptions = new HttpLogOptions();
        - * logOptions.addAllowedQueryParamName("documentId");
        + * HttpInstrumentationOptions instrumentationOptions = new HttpInstrumentationOptions();
        + * instrumentationOptions.addAllowedQueryParamName("documentId");
          *
          * HttpPipeline pipeline = new HttpPipelineBuilder()
        - *     .policies(
        - *         new HttpRetryPolicy(),
        - *         new HttpInstrumentationPolicy(instrumentationOptions, logOptions))
        + *     .addPolicy(new HttpRetryPolicy())
        + *     .addPolicy(new HttpInstrumentationPolicy(instrumentationOptions))
          *     .build();
          *
          * 
        - * + * * *

        Enrich HTTP spans with additional attributes:

        - * + * *
          *
        - * HttpPipelinePolicy enrichingPolicy = (request, next) -> {
        - *     Span span = request.getRequestOptions() == null
        - *         ? Span.noop()
        - *         : request.getRequestOptions().getInstrumentationContext().getSpan();
        - *     if (span.isRecording()) {
        - *         span.setAttribute("custom.request.id", request.getHeaders().getValue(CUSTOM_REQUEST_ID));
        + * HttpPipelinePolicy enrichingPolicy = new HttpPipelinePolicy() {
        + *     @Override
        + *     public Response<BinaryData> process(HttpRequest request, HttpPipelineNextPolicy next) {
        + *         Span span = request.getRequestOptions() == null
        + *             ? Span.noop()
        + *             : request.getRequestOptions().getInstrumentationContext().getSpan();
        + *         if (span.isRecording()) {
        + *             span.setAttribute("custom.request.id", request.getHeaders().getValue(CUSTOM_REQUEST_ID));
        + *         }
        + *
        + *         return next.process();
          *     }
          *
        - *     return next.process();
        + *     @Override
        + *     public HttpPipelinePosition getPipelinePosition() {
        + *         return HttpPipelinePosition.AFTER_INSTRUMENTATION;
        + *     }
          * };
          *
          * HttpPipeline pipeline = new HttpPipelineBuilder()
        - *     .policies(
        - *         new HttpRetryPolicy(),
        - *         new HttpInstrumentationPolicy(instrumentationOptions, logOptions),
        - *         enrichingPolicy)
        + *     .addPolicy(new HttpRetryPolicy())
        + *     .addPolicy(new HttpInstrumentationPolicy(instrumentationOptions))
        + *     .addPolicy(enrichingPolicy)
          *     .build();
          *
        - *
          * 
        - * + * * */ +@Metadata(properties = MetadataProperties.IMMUTABLE) public final class HttpInstrumentationPolicy implements HttpPipelinePolicy { private static final ClientLogger LOGGER = new ClientLogger(HttpInstrumentationPolicy.class); - private static final HttpLogOptions DEFAULT_LOG_OPTIONS = new HttpLogOptions(); + private static final HttpInstrumentationOptions DEFAULT_OPTIONS = new HttpInstrumentationOptions(); private static final String LIBRARY_NAME; private static final String LIBRARY_VERSION; private static final LibraryInstrumentationOptions LIBRARY_OPTIONS; @@ -162,34 +173,60 @@ public final class HttpInstrumentationPolicy implements HttpPipelinePolicy { private static final int MAX_BODY_LOG_SIZE = 1024 * 16; private static final String REDACTED_PLACEHOLDER = "REDACTED"; + // HTTP request duration metric is formally defined in the OpenTelemetry Semantic Conventions: + // https://github.com/open-telemetry/semantic-conventions/blob/main/docs/http/http-metrics.md#metric-httpclientrequestduration + private static final String REQUEST_DURATION_METRIC_NAME = "http.client.request.duration"; + private static final String REQUEST_DURATION_METRIC_DESCRIPTION = "Duration of HTTP client requests"; + private static final String REQUEST_DURATION_METRIC_UNIT = "s"; + // the histogram boundaries are optimized for typical HTTP request durations and could be customized by users on + // the OTel side. These are the defaults documented in the OpenTelemetry Semantic Conventions (link above). + private static final List REQUEST_DURATION_BOUNDARIES_ADVICE = Collections.unmodifiableList( + Arrays.asList(0.005d, 0.01d, 0.025d, 0.05d, 0.075d, 0.1d, 0.25d, 0.5d, 0.75d, 1d, 2.5d, 5d, 7.5d, 10d)); + // request log level is low (verbose) since almost all request details are also // captured on the response log. - private static final ClientLogger.LogLevel HTTP_REQUEST_LOG_LEVEL = ClientLogger.LogLevel.VERBOSE; - private static final ClientLogger.LogLevel HTTP_RESPONSE_LOG_LEVEL = ClientLogger.LogLevel.INFORMATIONAL; + private static final LogLevel HTTP_REQUEST_LOG_LEVEL = LogLevel.VERBOSE; + private static final LogLevel HTTP_RESPONSE_LOG_LEVEL = LogLevel.INFORMATIONAL; private final Tracer tracer; + private final Meter meter; + private final boolean isTracingEnabled; + private final boolean isMetricsEnabled; + private final Instrumentation instrumentation; + private final DoubleHistogram httpRequestDuration; private final TraceContextPropagator traceContextPropagator; private final Set allowedQueryParameterNames; - private final HttpLogOptions.HttpLogDetailLevel httpLogDetailLevel; private final Set allowedHeaderNames; + private final boolean isLoggingEnabled; + private final boolean isContentLoggingEnabled; + private final boolean isRedactedHeadersLoggingEnabled; /** * Creates a new instrumentation policy. * @param instrumentationOptions Application telemetry options. - * @param logOptions Http log options. TODO: we should merge this with telemetry options. */ - public HttpInstrumentationPolicy(InstrumentationOptions instrumentationOptions, HttpLogOptions logOptions) { - Instrumentation instrumentation = Instrumentation.create(instrumentationOptions, LIBRARY_OPTIONS); + public HttpInstrumentationPolicy(HttpInstrumentationOptions instrumentationOptions) { + this.instrumentation = Instrumentation.create(instrumentationOptions, LIBRARY_OPTIONS); this.tracer = instrumentation.getTracer(); + this.meter = instrumentation.getMeter(); + this.httpRequestDuration = meter.createDoubleHistogram(REQUEST_DURATION_METRIC_NAME, + REQUEST_DURATION_METRIC_DESCRIPTION, REQUEST_DURATION_METRIC_UNIT, REQUEST_DURATION_BOUNDARIES_ADVICE); this.traceContextPropagator = instrumentation.getW3CTraceContextPropagator(); - HttpLogOptions logOptionsToUse = logOptions == null ? DEFAULT_LOG_OPTIONS : logOptions; - this.httpLogDetailLevel = logOptionsToUse.getLogLevel(); - this.allowedHeaderNames = logOptionsToUse.getAllowedHeaderNames(); - this.allowedQueryParameterNames = logOptionsToUse.getAllowedQueryParamNames() + HttpInstrumentationOptions optionsToUse + = instrumentationOptions == null ? DEFAULT_OPTIONS : instrumentationOptions; + this.isLoggingEnabled = optionsToUse.getHttpLogLevel() != HttpInstrumentationOptions.HttpLogLevel.NONE; + this.isContentLoggingEnabled = optionsToUse.getHttpLogLevel() == HttpInstrumentationOptions.HttpLogLevel.BODY + || optionsToUse.getHttpLogLevel() == HttpInstrumentationOptions.HttpLogLevel.BODY_AND_HEADERS; + this.isRedactedHeadersLoggingEnabled = optionsToUse.isRedactedHeaderNamesLoggingEnabled(); + this.allowedHeaderNames = optionsToUse.getAllowedHeaderNames(); + this.allowedQueryParameterNames = optionsToUse.getAllowedQueryParamNames() .stream() .map(queryParamName -> queryParamName.toLowerCase(Locale.ROOT)) .collect(Collectors.toSet()); + + this.isTracingEnabled = tracer.isEnabled(); + this.isMetricsEnabled = meter.isEnabled(); } /** @@ -197,41 +234,42 @@ public HttpInstrumentationPolicy(InstrumentationOptions instrumentationOption */ @SuppressWarnings("try") @Override - public Response process(HttpRequest request, HttpPipelineNextPolicy next) { - boolean isTracingEnabled = tracer.isEnabled(); - if (!isTracingEnabled && httpLogDetailLevel == HttpLogOptions.HttpLogDetailLevel.NONE) { + public Response process(HttpRequest request, HttpPipelineNextPolicy next) { + if (!isTracingEnabled && !isLoggingEnabled && !isMetricsEnabled) { return next.process(); } ClientLogger logger = getLogger(request); final long startNs = System.nanoTime(); - String redactedUrl = getRedactedUri(request.getUri(), allowedQueryParameterNames); - int tryCount = HttpRequestAccessHelper.getTryCount(request); + final String redactedUrl = getRedactedUri(request.getUri(), allowedQueryParameterNames); + final int tryCount = HttpRequestAccessHelper.getTryCount(request); final long requestContentLength = getContentLength(logger, request.getBody(), request.getHeaders(), true); - InstrumentationContext instrumentationContext - = request.getRequestOptions() == null ? null : request.getRequestOptions().getInstrumentationContext(); - Span span = Span.noop(); - if (isTracingEnabled) { - if (request.getRequestOptions() == null || request.getRequestOptions() == RequestOptions.none()) { - request.setRequestOptions(new RequestOptions()); - } - - span = startHttpSpan(request, redactedUrl, instrumentationContext); - instrumentationContext = span.getInstrumentationContext(); - request.getRequestOptions().setInstrumentationContext(instrumentationContext); + Map metricAttributes = isMetricsEnabled ? new HashMap<>(8) : null; + if (request.getRequestOptions() == null || request.getRequestOptions() == RequestOptions.none()) { + request.setRequestOptions(new RequestOptions()); } - // even if tracing is disabled, we could have a valid context to propagate - // if it was provided by the application explicitly. - if (instrumentationContext != null && instrumentationContext.isValid()) { - traceContextPropagator.inject(instrumentationContext, request.getHeaders(), SETTER); + InstrumentationContext parentContext = request.getRequestOptions().getInstrumentationContext(); + + SpanBuilder spanBuilder = tracer.spanBuilder(request.getHttpMethod().toString(), CLIENT, parentContext); + setStartAttributes(request, redactedUrl, spanBuilder, metricAttributes); + Span span = spanBuilder.startSpan(); + + InstrumentationContext context + = span.getInstrumentationContext().isValid() ? span.getInstrumentationContext() : parentContext; + + if (context != null && context.isValid()) { + request.getRequestOptions().setInstrumentationContext(context); + // even if tracing is disabled, we could have a valid context to propagate + // if it was provided by the application explicitly. + traceContextPropagator.inject(context, request.getHeaders(), SETTER); } - logRequest(logger, request, startNs, requestContentLength, redactedUrl, tryCount, instrumentationContext); + logRequest(logger, request, startNs, requestContentLength, redactedUrl, tryCount, context); try (TracingScope scope = span.makeCurrent()) { - Response response = next.process(); + Response response = next.process(); if (response == null) { LOGGER.atError() @@ -244,75 +282,90 @@ public Response process(HttpRequest request, HttpPipelineNextPolicy next) { return null; } - addDetails(request, response, tryCount, span); - response = logResponse(logger, response, startNs, requestContentLength, redactedUrl, tryCount, - instrumentationContext); + addDetails(request, response.getStatusCode(), tryCount, span, metricAttributes); + response = logResponse(logger, response, startNs, requestContentLength, redactedUrl, tryCount, context); span.end(); return response; } catch (RuntimeException t) { - span.end(unwrap(t)); - // TODO (limolkova) test otel scope still covers this + Throwable cause = unwrap(t); + if (metricAttributes != null) { + metricAttributes.put(ERROR_TYPE_KEY, cause.getClass().getCanonicalName()); + } + span.end(cause); throw logException(logger, request, null, t, startNs, null, requestContentLength, redactedUrl, tryCount, - instrumentationContext); + context); + } finally { + if (isMetricsEnabled) { + httpRequestDuration.record((System.nanoTime() - startNs) / 1_000_000_000.0, + instrumentation.createAttributes(metricAttributes), context); + } } } - private Span startHttpSpan(HttpRequest request, String sanitizedUrl, InstrumentationContext context) { - SpanBuilder spanBuilder = tracer.spanBuilder(request.getHttpMethod().toString(), CLIENT, context) - .setAttribute(HTTP_REQUEST_METHOD_KEY, request.getHttpMethod().toString()) - .setAttribute(URL_FULL_KEY, sanitizedUrl) - .setAttribute(SERVER_ADDRESS_KEY, request.getUri().getHost()); - maybeSetServerPort(spanBuilder, request.getUri()); - return spanBuilder.startSpan(); - } + private void setStartAttributes(HttpRequest request, String sanitizedUrl, SpanBuilder spanBuilder, + Map metricAttributes) { + if (!isTracingEnabled && !isMetricsEnabled) { + return; + } - /** - * Does the best effort to capture the server port with minimum perf overhead. - * If port is not set, we check scheme for "http" and "https" (case-sensitive). - * If scheme is not one of those, we don't set the port. - * - * @param spanBuilder span builder - * @param uri request URI - */ - private static void maybeSetServerPort(SpanBuilder spanBuilder, URI uri) { - int port = uri.getPort(); - if (port != -1) { - spanBuilder.setAttribute(SERVER_PORT_KEY, port); - } else { - switch (uri.getScheme()) { - case "http": - spanBuilder.setAttribute(SERVER_PORT_KEY, 80); - break; - - case "https": - spanBuilder.setAttribute(SERVER_PORT_KEY, 443); - break; - - default: - break; + int port = getServerPort(request.getUri()); + if (isTracingEnabled) { + spanBuilder.setAttribute(HTTP_REQUEST_METHOD_KEY, request.getHttpMethod().toString()) + .setAttribute(URL_FULL_KEY, sanitizedUrl) + .setAttribute(SERVER_ADDRESS_KEY, request.getUri().getHost()); + + if (port > 0) { + spanBuilder.setAttribute(SERVER_PORT_KEY, port); + } + } + + if (isMetricsEnabled) { + metricAttributes.put(HTTP_REQUEST_METHOD_KEY, request.getHttpMethod().toString()); + metricAttributes.put(SERVER_ADDRESS_KEY, request.getUri().getHost()); + if (port > 0) { + metricAttributes.put(SERVER_PORT_KEY, port); } } } - private void addDetails(HttpRequest request, Response response, int tryCount, Span span) { - if (!span.isRecording()) { + private void addDetails(HttpRequest request, int statusCode, int tryCount, Span span, + Map metricAttributes) { + if (!span.isRecording() && !isMetricsEnabled) { return; } - span.setAttribute(HTTP_RESPONSE_STATUS_CODE_KEY, (long) response.getStatusCode()); - - if (tryCount > 0) { - span.setAttribute(HTTP_REQUEST_RESEND_COUNT_KEY, (long) tryCount); + String error = null; + if (statusCode >= 400) { + error = String.valueOf(statusCode); } - String userAgent = request.getHeaders().getValue(HttpHeaderName.USER_AGENT); - if (userAgent != null) { - span.setAttribute(USER_AGENT_ORIGINAL_KEY, userAgent); + if (span.isRecording()) { + span.setAttribute(HTTP_RESPONSE_STATUS_CODE_KEY, (long) statusCode); + + if (tryCount > 0) { + span.setAttribute(HTTP_REQUEST_RESEND_COUNT_KEY, (long) tryCount); + } + + String userAgent = request.getHeaders().getValue(HttpHeaderName.USER_AGENT); + if (userAgent != null) { + span.setAttribute(USER_AGENT_ORIGINAL_KEY, userAgent); + } + + if (error != null) { + span.setError(error); + } } - if (response.getStatusCode() >= 400) { - span.setError(String.valueOf(response.getStatusCode())); + if (isMetricsEnabled) { + if (statusCode > 0) { + metricAttributes.put(HTTP_RESPONSE_STATUS_CODE_KEY, statusCode); + } + + if (error != null) { + metricAttributes.put(ERROR_TYPE_KEY, error); + } } + // TODO (lmolkova) url.template and experimental features } @@ -354,8 +407,8 @@ private static Map getProperties(String propertiesFileName) { private void logRequest(ClientLogger logger, HttpRequest request, long startNanoTime, long requestContentLength, String redactedUrl, int tryCount, InstrumentationContext context) { - ClientLogger.LoggingEvent logBuilder = logger.atLevel(HTTP_REQUEST_LOG_LEVEL); - if (!logBuilder.isEnabled() || httpLogDetailLevel == HttpLogOptions.HttpLogDetailLevel.NONE) { + LoggingEvent logBuilder = logger.atLevel(HTTP_REQUEST_LOG_LEVEL); + if (!logBuilder.isEnabled() || !isLoggingEnabled) { return; } @@ -368,7 +421,7 @@ private void logRequest(ClientLogger logger, HttpRequest request, long startNano addHeadersToLogMessage(request.getHeaders(), logBuilder); - if (httpLogDetailLevel.shouldLogBody() && canLogBody(request.getBody())) { + if (isContentLoggingEnabled && canLogBody(request.getBody())) { try { BinaryData bufferedBody = request.getBody().toReplayableBinaryData(); request.setBody(bufferedBody); @@ -383,10 +436,10 @@ private void logRequest(ClientLogger logger, HttpRequest request, long startNano logBuilder.log(); } - private Response logResponse(ClientLogger logger, Response response, long startNanoTime, + private Response logResponse(ClientLogger logger, Response response, long startNanoTime, long requestContentLength, String redactedUrl, int tryCount, InstrumentationContext context) { - ClientLogger.LoggingEvent logBuilder = logger.atLevel(HTTP_RESPONSE_LOG_LEVEL); - if (httpLogDetailLevel == HttpLogOptions.HttpLogDetailLevel.NONE) { + LoggingEvent logBuilder = logger.atLevel(HTTP_RESPONSE_LOG_LEVEL); + if (!isLoggingEnabled) { return response; } @@ -403,13 +456,13 @@ private Response logResponse(ClientLogger logger, Response response, long .addKeyValue(HTTP_RESPONSE_STATUS_CODE_KEY, response.getStatusCode()) .addKeyValue(HTTP_REQUEST_BODY_SIZE_KEY, requestContentLength) .addKeyValue(HTTP_RESPONSE_BODY_SIZE_KEY, - getContentLength(logger, response.getBody(), response.getHeaders(), false)); + getContentLength(logger, response.getValue(), response.getHeaders(), false)); addHeadersToLogMessage(response.getHeaders(), logBuilder); } - if (httpLogDetailLevel.shouldLogBody() && canLogBody(response.getBody())) { - return new LoggingHttpResponse<>(response, content -> { + if (isContentLoggingEnabled && canLogBody(response.getValue())) { + return new LoggingHttpResponse(response, content -> { if (logBuilder.isEnabled()) { logBuilder.addKeyValue(HTTP_RESPONSE_BODY_CONTENT_KEY, content.toString()) .addKeyValue(HTTP_REQUEST_DURATION_KEY, getDurationMs(startNanoTime, System.nanoTime())) @@ -426,12 +479,12 @@ private Response logResponse(ClientLogger logger, Response response, long return response; } - private T logException(ClientLogger logger, HttpRequest request, Response response, - T throwable, long startNanoTime, Long responseStartNanoTime, long requestContentLength, String redactedUrl, - int tryCount, InstrumentationContext context) { + private T logException(ClientLogger logger, HttpRequest request, + Response response, T throwable, long startNanoTime, Long responseStartNanoTime, + long requestContentLength, String redactedUrl, int tryCount, InstrumentationContext context) { - ClientLogger.LoggingEvent log = logger.atLevel(ClientLogger.LogLevel.WARNING); - if (!log.isEnabled() || httpLogDetailLevel == HttpLogOptions.HttpLogDetailLevel.NONE) { + LoggingEvent log = logger.atLevel(LogLevel.WARNING); + if (!log.isEnabled() || !isLoggingEnabled) { return throwable; } @@ -446,7 +499,7 @@ private T logException(ClientLogger logger, HttpRequest re if (response != null) { addHeadersToLogMessage(response.getHeaders(), log); log.addKeyValue(HTTP_RESPONSE_BODY_SIZE_KEY, - getContentLength(logger, response.getBody(), response.getHeaders(), false)) + getContentLength(logger, response.getValue(), response.getHeaders(), false)) .addKeyValue(HTTP_RESPONSE_STATUS_CODE_KEY, response.getStatusCode()); if (responseStartNanoTime != null) { @@ -483,14 +536,15 @@ private static boolean canLogBody(BinaryData data) { * @param headers HTTP headers on the request or response. * @param logBuilder Log message builder. */ - private void addHeadersToLogMessage(HttpHeaders headers, ClientLogger.LoggingEvent logBuilder) { - if (httpLogDetailLevel.shouldLogHeaders()) { - for (HttpHeader header : headers) { - HttpHeaderName headerName = header.getName(); - String headerValue = allowedHeaderNames.contains(headerName) ? header.getValue() : REDACTED_PLACEHOLDER; - logBuilder.addKeyValue(headerName.toString(), headerValue); + private void addHeadersToLogMessage(HttpHeaders headers, LoggingEvent logBuilder) { + headers.stream().forEach(header -> { + HttpHeaderName headerName = header.getName(); + if (allowedHeaderNames.contains(headerName)) { + logBuilder.addKeyValue(headerName.toString(), header.getValue()); + } else if (isRedactedHeadersLoggingEnabled) { + logBuilder.addKeyValue(headerName.toString(), REDACTED_PLACEHOLDER); } - } + }); } /** @@ -517,7 +571,7 @@ private static long getContentLength(ClientLogger logger, BinaryData body, HttpH String contentLengthString = headers.getValue(HttpHeaderName.CONTENT_LENGTH); - if (isNullOrEmpty(contentLengthString)) { + if (CoreUtils.isNullOrEmpty(contentLengthString)) { return contentLength; } @@ -534,24 +588,24 @@ private static long getContentLength(ClientLogger logger, BinaryData body, HttpH return contentLength; } - private static final class LoggingHttpResponse extends HttpResponse { + private static final class LoggingHttpResponse extends Response { private final Consumer onContent; private final Consumer onException; private final BinaryData originalBody; private BinaryData bufferedBody; - private LoggingHttpResponse(Response actualResponse, Consumer onContent, + private LoggingHttpResponse(Response actualResponse, Consumer onContent, Consumer onException) { super(actualResponse.getRequest(), actualResponse.getStatusCode(), actualResponse.getHeaders(), actualResponse.getValue()); this.onContent = onContent; this.onException = onException; - this.originalBody = actualResponse.getBody(); + this.originalBody = actualResponse.getValue(); } @Override - public BinaryData getBody() { + public BinaryData getValue() { if (bufferedBody != null) { return bufferedBody; } @@ -570,7 +624,7 @@ public BinaryData getBody() { @Override public void close() throws IOException { if (bufferedBody == null) { - getBody(); + getValue(); } if (bufferedBody != null) { bufferedBody.close(); @@ -578,4 +632,9 @@ public void close() throws IOException { originalBody.close(); } } + + @Override + public HttpPipelinePosition getPipelinePosition() { + return HttpPipelinePosition.INSTRUMENTATION; + } } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpPipeline.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpPipeline.java index 88761eab0224..d9d40f7ca3b0 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpPipeline.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpPipeline.java @@ -3,10 +3,13 @@ package io.clientcore.core.http.pipeline; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; import io.clientcore.core.http.client.HttpClient; import io.clientcore.core.http.models.HttpRequest; import io.clientcore.core.http.models.Response; import io.clientcore.core.implementation.http.HttpPipelineCallState; +import io.clientcore.core.models.binarydata.BinaryData; import java.util.Collections; import java.util.List; @@ -20,6 +23,7 @@ * * @see HttpPipelinePolicy */ +@Metadata(properties = MetadataProperties.IMMUTABLE) public final class HttpPipeline { private final HttpClient httpClient; private final List pipelinePolicies; @@ -66,7 +70,7 @@ public HttpClient getHttpClient() { * * @return An {@link Response}. */ - public Response send(HttpRequest request) { + public Response send(HttpRequest request) { HttpPipelineNextPolicy next = new HttpPipelineNextPolicy(new HttpPipelineCallState(this, request)); return next.process(); diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpPipelineBuilder.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpPipelineBuilder.java index 64765cb3d3cc..b2d8bf3f4d4b 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpPipelineBuilder.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpPipelineBuilder.java @@ -3,12 +3,16 @@ package io.clientcore.core.http.pipeline; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; import io.clientcore.core.http.client.HttpClient; -import io.clientcore.core.util.configuration.Configuration; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.utils.configuration.Configuration; import java.util.ArrayList; -import java.util.Arrays; +import java.util.LinkedList; import java.util.List; +import java.util.Objects; /** * This class provides a fluent builder API to help aid the configuration and instantiation of the {@link HttpPipeline}, @@ -33,16 +37,28 @@ *
          * HttpPipeline pipeline = new HttpPipelineBuilder()
          *     .httpClient(HttpClient.getNewInstance())
        - *     .policies(new HttpRetryPolicy())
        + *     .addPolicy(new HttpRetryPolicy())
          *     .build();
          * 
        * * * @see HttpPipeline */ +@Metadata(properties = MetadataProperties.FLUENT) public class HttpPipelineBuilder { + private static final ClientLogger LOGGER = new ClientLogger(HttpPipelineBuilder.class); + private HttpClient httpClient; - private List pipelinePolicies; + + private final LinkedList beforeRedirect = new LinkedList<>(); + private HttpRedirectPolicy redirectPolicy; + private final LinkedList betweenRedirectAndRetry = new LinkedList<>(); + private HttpRetryPolicy retryPolicy; + private final LinkedList betweenRetryAndAuthentication = new LinkedList<>(); + private HttpCredentialPolicy credentialPolicy; + private final LinkedList betweenAuthenticationAndInstrumentation = new LinkedList<>(); + private HttpInstrumentationPolicy instrumentationPolicy; + private final LinkedList afterInstrumentation = new LinkedList<>(); /** * Creates a new instance of HttpPipelineBuilder that can configure options for the {@link HttpPipeline} before @@ -60,13 +76,38 @@ public HttpPipelineBuilder() { * @return A HttpPipeline with the options set from the builder. */ public HttpPipeline build() { - List policies = (pipelinePolicies == null) ? new ArrayList<>() : pipelinePolicies; + List policies = new ArrayList<>(beforeRedirect); + + if (redirectPolicy != null) { + policies.add(redirectPolicy); + } + + policies.addAll(betweenRedirectAndRetry); + + if (retryPolicy != null) { + policies.add(retryPolicy); + } + + policies.addAll(betweenRetryAndAuthentication); + + if (credentialPolicy != null) { + policies.add(credentialPolicy); + } + + policies.addAll(betweenAuthenticationAndInstrumentation); + + if (instrumentationPolicy != null) { + policies.add(instrumentationPolicy); + } + + policies.addAll(afterInstrumentation); + HttpClient client; if (httpClient != null) { client = httpClient; } else { - if (Configuration.getGlobalConfiguration().get("ENABLE_HTTP_CLIENT_SHARING", Boolean.TRUE)) { + if (Boolean.parseBoolean(Configuration.getGlobalConfiguration().get("AZURE_HTTP_CLIENT_SHARING"))) { client = HttpClient.getSharedInstance(); } else { client = HttpClient.getNewInstance(); @@ -80,7 +121,6 @@ public HttpPipeline build() { * Sets the HttpClient that the pipeline will use to send requests. * * @param httpClient The HttpClient the pipeline will use when sending requests. - * * @return The updated HttpPipelineBuilder object. */ public HttpPipelineBuilder httpClient(HttpClient httpClient) { @@ -90,20 +130,82 @@ public HttpPipelineBuilder httpClient(HttpClient httpClient) { } /** - * Adds {@link HttpPipelinePolicy policies} to the set of policies that the pipeline will use when sending - * requests. - * - * @param policies Policies to add to the policy set. + * Adds an {@link HttpPipelinePolicy} to the builder. + *

        + * The {@code policy} passed will be positioned based on {@link HttpPipelinePolicy#getPipelinePosition()}. If the + * {@link HttpPipelinePosition} is null an {@link IllegalArgumentException} will be thrown. + *

        + * If the {@code policy} is one of the pillar policies ({@link HttpRedirectPolicy}, {@link HttpRetryPolicy}, + * {@link HttpCredentialPolicy}, or {@link HttpInstrumentationPolicy}) the {@link HttpPipelinePosition} will be ignored + * as those policies are positioned in a specific location within the pipeline. If a duplicate pillar policy is + * added (for example two {@link HttpRetryPolicy}) the last one added will be used and a message will be logged. * + * @param policy The policy to add to the pipeline. * @return The updated HttpPipelineBuilder object. */ - public HttpPipelineBuilder policies(HttpPipelinePolicy... policies) { - if (pipelinePolicies == null) { - pipelinePolicies = new ArrayList<>(); + public HttpPipelineBuilder addPolicy(HttpPipelinePolicy policy) { + Objects.requireNonNull(policy, "'policy' cannot be null."); + + if (tryAddPillar(policy)) { + return this; } - this.pipelinePolicies.addAll(Arrays.asList(policies)); + HttpPipelinePosition order = policy.getPipelinePosition(); + if (order == null) { + throw LOGGER.atError() + .addKeyValue("policyType", policy.getClass()) + .log("Policy order cannot be null.", new IllegalArgumentException("Policy order cannot be null.")); + } + + if (order == HttpPipelinePosition.BEFORE_REDIRECT) { + beforeRedirect.add(policy); + } else if (order == HttpPipelinePosition.AFTER_REDIRECT) { + betweenRedirectAndRetry.add(policy); + } else if (order == HttpPipelinePosition.AFTER_RETRY) { + betweenRetryAndAuthentication.add(policy); + } else if (order == HttpPipelinePosition.AFTER_AUTHENTICATION) { + betweenAuthenticationAndInstrumentation.add(policy); + } else if (order == HttpPipelinePosition.AFTER_INSTRUMENTATION) { + afterInstrumentation.add(policy); + } else { + throw LOGGER.atError() + .addKeyValue("policyType", policy.getClass()) + .addKeyValue("order", order) + .log("Unknown policy order.", new IllegalArgumentException("Unknown policy order.")); + } return this; } + + private boolean tryAddPillar(HttpPipelinePolicy policy) { + HttpPipelinePolicy previous = null; + boolean added = false; + + HttpPipelinePosition order = policy.getPipelinePosition(); + if (order == HttpPipelinePosition.REDIRECT) { + previous = redirectPolicy; + redirectPolicy = (HttpRedirectPolicy) policy; + added = true; + } else if (order == HttpPipelinePosition.RETRY) { + previous = retryPolicy; + retryPolicy = (HttpRetryPolicy) policy; + added = true; + } else if (order == HttpPipelinePosition.AUTHENTICATION) { + previous = credentialPolicy; + credentialPolicy = (HttpCredentialPolicy) policy; + added = true; + } else if (order == HttpPipelinePosition.INSTRUMENTATION) { + previous = instrumentationPolicy; + instrumentationPolicy = (HttpInstrumentationPolicy) policy; + added = true; + } + + if (previous != null) { + LOGGER.atWarning() + .addKeyValue("policyType", previous.getClass().getSimpleName()) + .log("A pillar policy was replaced in the pipeline."); + } + + return added; + } } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpPipelineNextPolicy.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpPipelineNextPolicy.java index ed070bd50991..f6ddb045cb31 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpPipelineNextPolicy.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpPipelineNextPolicy.java @@ -3,9 +3,12 @@ package io.clientcore.core.http.pipeline; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; import io.clientcore.core.http.models.Response; import io.clientcore.core.implementation.http.HttpPipelineCallState; import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.models.binarydata.BinaryData; import java.io.IOException; import java.io.UncheckedIOException; @@ -13,6 +16,7 @@ /** * A type that invokes next policy in the pipeline. */ +@Metadata(properties = MetadataProperties.IMMUTABLE) public class HttpPipelineNextPolicy { private static final ClientLogger LOGGER = new ClientLogger(HttpPipelineNextPolicy.class); @@ -33,7 +37,7 @@ public class HttpPipelineNextPolicy { * @return The response. * @throws UncheckedIOException If an error occurs when sending the request or receiving the response. */ - public Response process() { + public Response process() { HttpPipelinePolicy nextPolicy = state.getNextPolicy(); if (nextPolicy == null) { @@ -50,13 +54,13 @@ public Response process() { } /** - * Creates a new instance of this instance. + * Copies the current state of the {@link HttpPipelineNextPolicy}. + *

        + * This method must be used when a re-request is made in the pipeline. * * @return A new instance of this next pipeline policy. */ - @SuppressWarnings("MethodDoesntCallSuperMethod") - @Override - public HttpPipelineNextPolicy clone() { - return new HttpPipelineNextPolicy(this.state.clone()); + public HttpPipelineNextPolicy copy() { + return new HttpPipelineNextPolicy(this.state.copy()); } } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpPipelinePolicy.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpPipelinePolicy.java index 0b2e37ac8d26..822922e2384a 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpPipelinePolicy.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpPipelinePolicy.java @@ -5,6 +5,7 @@ import io.clientcore.core.http.models.HttpRequest; import io.clientcore.core.http.models.Response; +import io.clientcore.core.models.binarydata.BinaryData; /** * A policy within the {@link HttpPipeline}. @@ -14,12 +15,27 @@ @FunctionalInterface public interface HttpPipelinePolicy { /** - * Processes the provided HTTP request and invokes the next policy synchronously. + * Processes the provided HTTP request and invokes the next policy. * * @param httpRequest The HTTP request. * @param next The next policy to invoke. + * @return The {@link Response} from the next policy or the HTTP client if there are no more policies. + */ + Response process(HttpRequest httpRequest, HttpPipelineNextPolicy next); + + /** + * Gets the position in the {@link HttpPipelineBuilder} the policy will be placed when added. + *

        + * Policy position does not need to be unique. When multiple polices with the same {@link HttpPipelinePosition} are + * added they will be handled based on the documentation of {@link HttpPipelinePosition}. + *

        + * By default, this method returns {@link HttpPipelinePosition#AFTER_RETRY}. + *

        + * If this method returns null, an exception will be thrown when it is added to the {@link HttpPipelineBuilder}. * - * @return A publisher that initiates the request upon subscription and emits a response on completion. + * @return The position of this policy. */ - Response process(HttpRequest httpRequest, HttpPipelineNextPolicy next); + default HttpPipelinePosition getPipelinePosition() { + return HttpPipelinePosition.AFTER_RETRY; + } } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpPipelinePosition.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpPipelinePosition.java new file mode 100644 index 000000000000..9d7093c348c6 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpPipelinePosition.java @@ -0,0 +1,155 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.http.pipeline; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.utils.ExpandableEnum; + +/** + * Enum representing where in an {@link HttpPipeline} a given {@link HttpPipelinePolicy} is positioned when added to an + * {@link HttpPipelineBuilder}. + *

        + * By default, policies are added at {@link #AFTER_RETRY} with the assumption of + * {@link HttpPipelinePolicy policies} are idempotent and may need to be updated each time a network request is sent + * (each try) and may mutate the results of authentication policies. + *

        + * HttpPipelinePosition ensures that the creation of an {@link HttpPipeline} follows a strict positioning of policies. + * Here is a visual representation of the order of policies in an {@link HttpPipeline}: + *

        + *     +------------------------+
        + *     |    Before redirect     |
        + *     +------------------------+
        + *     |    Redirect Policy     |
        + *     +------------------------+
        + *     |     After redirect     |
        + *     +------------------------+
        + *     |      Retry Policy      |
        + *     +------------------------+
        + *     |      After retry       |
        + *     +------------------------+
        + *     | Authentication Policy  |
        + *     +------------------------+
        + *     |  After authentication  |
        + *     +------------------------+
        + *     | Instrumentation Policy |
        + *     +------------------------+
        + *     | After instrumentation  |
        + *     +------------------------+
        + * 
        + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public final class HttpPipelinePosition implements ExpandableEnum { + private final int value; + + private HttpPipelinePosition(Integer value) { + this.value = value; + } + + @Override + public Integer getValue() { + return value; + } + + /** + * The policy will be position before the {@link HttpRedirectPolicy}. + *

        + * If multiple {@link HttpPipelinePolicy policies} are added with this position, the first added will be the furthest + * before the {@link HttpRedirectPolicy} and the last added will be the closest. Or, visually: + *

        +     *     +------------------+
        +     *     | 1st added Before |
        +     *     +------------------+
        +     *     | 2nd added Before |
        +     *     +------------------+
        +     *     | 3rd added Before |
        +     *     +------------------+
        +     *     | Redirect Policy  |
        +     *     +------------------+
        +     * 
        + */ + public static final HttpPipelinePosition BEFORE_REDIRECT = new HttpPipelinePosition(1000); + + /** + * The policy will be position after the {@link HttpRedirectPolicy}. + *

        + * If multiple {@link HttpPipelinePolicy policies} are added with this position, they will be executed in the order + * they were added after the {@link HttpRedirectPolicy}. Or, visually: + *

        +     *     +-----------------+
        +     *     | Redirect Policy |
        +     *     +-----------------+
        +     *     | 1st added after |
        +     *     +-----------------+
        +     *     | 2nd added after |
        +     *     +-----------------+
        +     *     | 3rd added after |
        +     *     +-----------------+
        +     * 
        + */ + public static final HttpPipelinePosition AFTER_REDIRECT = new HttpPipelinePosition(3000); + + /** + * The policy will be position after the {@link HttpRetryPolicy}. + *

        + * If multiple {@link HttpPipelinePolicy policies} are added with this position, they will be executed in the order + * they were added after the {@link HttpRetryPolicy}. Or, visually: + *

        +     *     +---------------------+
        +     *     |    Retry Policy     |
        +     *     +---------------------+
        +     *     |   1st added after   |
        +     *     +---------------------+
        +     *     |   2nd added after   |
        +     *     +---------------------+
        +     *     |   3rd added after   |
        +     *     +---------------------+
        +     * 
        + */ + public static final HttpPipelinePosition AFTER_RETRY = new HttpPipelinePosition(5000); + + /** + * The policy will be position after the {@link HttpCredentialPolicy}. + *

        + * If multiple {@link HttpPipelinePolicy policies} are added with this position, they will be executed in the order + * they were added after the {@link HttpCredentialPolicy}. Or, visually: + *

        +     *     +-----------------------+
        +     *     | Authentication Policy |
        +     *     +-----------------------+
        +     *     |    1st added after    |
        +     *     +-----------------------+
        +     *     |    2nd added after    |
        +     *     +-----------------------+
        +     *     |    3rd added after    |
        +     *     +-----------------------+
        +     * 
        + */ + public static final HttpPipelinePosition AFTER_AUTHENTICATION = new HttpPipelinePosition(7000); + + /** + * The policy will be position after the {@link HttpInstrumentationPolicy}. + *

        + * If multiple {@link HttpPipelinePolicy policies} are added with this position, they will be executed in the order + * they were added after {@link HttpInstrumentationPolicy}. Or, visually: + *

        +     *     +------------------------+
        +     *     | Instrumentation Policy |
        +     *     +------------------------+
        +     *     |    1st added After     |
        +     *     +------------------------+
        +     *     |    2nd added After     |
        +     *     +------------------------+
        +     *     |    3rd added After     |
        +     *     +------------------------+
        +     * 
        + */ + public static final HttpPipelinePosition AFTER_INSTRUMENTATION = new HttpPipelinePosition(9000); + + // Package-private HttpPipelinePosition constants for pillar policies. + static final HttpPipelinePosition REDIRECT = new HttpPipelinePosition(2000); + static final HttpPipelinePosition RETRY = new HttpPipelinePosition(4000); + static final HttpPipelinePosition AUTHENTICATION = new HttpPipelinePosition(6000); + static final HttpPipelinePosition INSTRUMENTATION = new HttpPipelinePosition(8000); + +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpRedirectCondition.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpRedirectCondition.java new file mode 100644 index 000000000000..f6c2c53d3131 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpRedirectCondition.java @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.http.pipeline; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.models.binarydata.BinaryData; + +import java.util.Collections; +import java.util.Set; + +/** + * Information about the request that failed, used to determine whether a redirect should be attempted. + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public final class HttpRedirectCondition { + private final Response response; + private final Set redirectedUris; + private final int tryCount; + + /** + * Creates a new should redirect request object + * + * @param response The HTTP response of the request that failed. + * @param tryCount The number of tries that have been attempted. + * @param redirectedUris The set of URIs that have been attempted redirect. + */ + HttpRedirectCondition(Response response, int tryCount, Set redirectedUris) { + this.response = response; + this.tryCount = tryCount; + this.redirectedUris = redirectedUris == null ? Collections.emptySet() : redirectedUris; + } + + /** + * Gets the HTTP response of the request that failed. + *

        + * This may be null if the request failed with a throwable and no response was received. + * + * @return The HTTP response of the request that failed. + */ + public Response getResponse() { + return response; + } + + /** + * Gets the number of tries that have been attempted. + * + * @return The number of tries that have been attempted. + */ + public int getTryCount() { + return tryCount; + } + + /** + * Gets the unmodifiable set of uris that have been attempted redirect. + * + * @return The unmodifiable list of exceptions that have been attempted redirect. + */ + public Set getRedirectedUris() { + return redirectedUris; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpRedirectOptions.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpRedirectOptions.java similarity index 84% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpRedirectOptions.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpRedirectOptions.java index 9769a05ec5fd..48bb103e4808 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpRedirectOptions.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpRedirectOptions.java @@ -1,9 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.http.models; +package io.clientcore.core.http.pipeline; -import io.clientcore.core.http.pipeline.HttpRequestRedirectCondition; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpMethod; +import io.clientcore.core.http.models.Response; import io.clientcore.core.instrumentation.logging.ClientLogger; import java.util.EnumSet; @@ -12,12 +16,13 @@ /** * Options to configure the redirect policy's behavior. */ +@Metadata(properties = MetadataProperties.FLUENT) public final class HttpRedirectOptions { private static final ClientLogger LOGGER = new ClientLogger(HttpRedirectOptions.class); private final int maxAttempts; private final EnumSet allowedRedirectHttpMethods; private final HttpHeaderName locationHeader; - private Predicate shouldRedirectCondition; + private Predicate shouldRedirectCondition; /** * Creates an instance of {@link HttpRedirectOptions}. @@ -53,7 +58,7 @@ public int getMaxAttempts() { * * @return The predicate that determines if a redirect should be attempted. */ - public Predicate getShouldRedirectCondition() { + public Predicate getShouldRedirectCondition() { return shouldRedirectCondition; } @@ -66,8 +71,7 @@ public Predicate getShouldRedirectCondition() { * {@link Response}. * @return The updated {@link HttpRedirectOptions} object. */ - public HttpRedirectOptions - setShouldRedirectCondition(Predicate shouldRedirectCondition) { + public HttpRedirectOptions setShouldRedirectCondition(Predicate shouldRedirectCondition) { this.shouldRedirectCondition = shouldRedirectCondition; return this; } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpRedirectPolicy.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpRedirectPolicy.java index fbd3e84b3171..84008b8fd417 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpRedirectPolicy.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpRedirectPolicy.java @@ -3,13 +3,16 @@ package io.clientcore.core.http.pipeline; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; import io.clientcore.core.http.models.HttpHeaderName; import io.clientcore.core.http.models.HttpMethod; -import io.clientcore.core.http.models.HttpRedirectOptions; import io.clientcore.core.http.models.HttpRequest; import io.clientcore.core.http.models.Response; import io.clientcore.core.instrumentation.InstrumentationContext; import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.instrumentation.logging.LoggingEvent; +import io.clientcore.core.models.binarydata.BinaryData; import java.io.IOException; import java.io.UncheckedIOException; @@ -34,16 +37,18 @@ * A {@link HttpPipelinePolicy} that redirects a {@link HttpRequest} when an HTTP Redirect is received as a * {@link Response response}. */ +@Metadata(properties = MetadataProperties.IMMUTABLE) public final class HttpRedirectPolicy implements HttpPipelinePolicy { private static final ClientLogger LOGGER = new ClientLogger(HttpRedirectPolicy.class); private final int maxAttempts; - private final Predicate shouldRedirectCondition; + private final Predicate shouldRedirectCondition; private static final int DEFAULT_MAX_REDIRECT_ATTEMPTS = 3; private static final EnumSet DEFAULT_REDIRECT_ALLOWED_METHODS = EnumSet.of(HttpMethod.GET, HttpMethod.HEAD); private static final int PERMANENT_REDIRECT_STATUS_CODE = 308; private static final int TEMPORARY_REDIRECT_STATUS_CODE = 307; + private final EnumSet allowedRedirectHttpMethods; private final HttpHeaderName locationHeader; @@ -80,7 +85,7 @@ public HttpRedirectPolicy(HttpRedirectOptions redirectOptions) { } @Override - public Response process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { + public Response process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { // Reset the attemptedRedirectUris for each individual request. InstrumentationContext instrumentationContext = httpRequest.getRequestOptions() == null ? null @@ -90,19 +95,24 @@ public Response process(HttpRequest httpRequest, HttpPipelineNextPolicy next) return attemptRedirect(logger, next, 0, new LinkedHashSet<>(), instrumentationContext); } + @Override + public HttpPipelinePosition getPipelinePosition() { + return HttpPipelinePosition.REDIRECT; + } + /** * Function to process through the HTTP Response received in the pipeline and redirect sending the request with a * new redirect URI. */ - private Response attemptRedirect(ClientLogger logger, final HttpPipelineNextPolicy next, + private Response attemptRedirect(ClientLogger logger, final HttpPipelineNextPolicy next, final int redirectAttempt, LinkedHashSet attemptedRedirectUris, InstrumentationContext instrumentationContext) { // Make sure the context is not modified during redirect, except for the URI - Response response = next.clone().process(); + Response response = next.copy().process(); - HttpRequestRedirectCondition requestRedirectCondition - = new HttpRequestRedirectCondition(response, redirectAttempt, attemptedRedirectUris); + HttpRedirectCondition requestRedirectCondition + = new HttpRedirectCondition(response, redirectAttempt, attemptedRedirectUris); if ((shouldRedirectCondition != null && shouldRedirectCondition.test(requestRedirectCondition)) || (shouldRedirectCondition == null @@ -114,9 +124,9 @@ && defaultShouldAttemptRedirect(logger, requestRedirectCondition, instrumentatio return response; } - private boolean defaultShouldAttemptRedirect(ClientLogger logger, - HttpRequestRedirectCondition requestRedirectCondition, InstrumentationContext context) { - Response response = requestRedirectCondition.getResponse(); + private boolean defaultShouldAttemptRedirect(ClientLogger logger, HttpRedirectCondition requestRedirectCondition, + InstrumentationContext context) { + Response response = requestRedirectCondition.getResponse(); int tryCount = requestRedirectCondition.getTryCount(); Set attemptedRedirectUris = requestRedirectCondition.getRedirectedUris(); String redirectUri = response.getHeaders().getValue(this.locationHeader); @@ -180,7 +190,7 @@ private void createRedirectRequest(Response redirectResponse) { private void logRedirect(ClientLogger logger, boolean lastAttempt, String redirectUri, int tryCount, HttpMethod method, String message, InstrumentationContext context) { - ClientLogger.LoggingEvent log = lastAttempt ? logger.atWarning() : logger.atVerbose(); + LoggingEvent log = lastAttempt ? logger.atWarning() : logger.atVerbose(); if (log.isEnabled()) { log.addKeyValue(HTTP_REQUEST_RESEND_COUNT_KEY, tryCount) .addKeyValue(RETRY_MAX_ATTEMPT_COUNT_KEY, maxAttempts) diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpRequestRedirectCondition.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpRequestRedirectCondition.java deleted file mode 100644 index e7881fe73e38..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpRequestRedirectCondition.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.http.pipeline; - -import io.clientcore.core.http.models.Response; - -import java.util.Collections; -import java.util.Set; - -/** - * Information about the request that failed, used to determine whether a redirect should be attempted. - */ -public final class HttpRequestRedirectCondition { - private final Response response; - private final Set redirectedUris; - private final int tryCount; - - /** - * Creates a new should redirect request object - * - * @param response The HTTP response of the request that failed. - * @param tryCount The number of tries that have been attempted. - * @param redirectedUris The set of URIs that have been attempted redirect. - */ - HttpRequestRedirectCondition(Response response, int tryCount, Set redirectedUris) { - this.response = response; - this.tryCount = tryCount; - this.redirectedUris = redirectedUris == null ? Collections.emptySet() : redirectedUris; - } - - /** - * Gets the HTTP response of the request that failed. - *

        - * This may be null if the request failed with a throwable and no response was received. - * - * @return The HTTP response of the request that failed. - */ - public Response getResponse() { - return response; - } - - /** - * Gets the number of tries that have been attempted. - * - * @return The number of tries that have been attempted. - */ - public int getTryCount() { - return tryCount; - } - - /** - * Gets the unmodifiable set of uris that have been attempted redirect. - * - * @return The unmodifiable list of exceptions that have been attempted redirect. - */ - public Set getRedirectedUris() { - return redirectedUris; - } -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpRequestRetryCondition.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpRequestRetryCondition.java deleted file mode 100644 index ac664f8c5037..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpRequestRetryCondition.java +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.http.pipeline; - -import io.clientcore.core.http.models.Response; - -import java.util.Collections; -import java.util.List; - -/** - * Information about the request that failed, used to determine whether a retry should be attempted. - */ -public final class HttpRequestRetryCondition { - private final Response response; - private final Exception exception; - private final int tryCount; - private final List retriedExceptions; - - /** - * Creates a new ShouldRetryInfo object. - * - * @param response The HTTP response of the request that failed. - * @param exception The exception of the request that failed. - * @param tryCount The number of tries that have been already attempted. - * @param retriedExceptions The list of exceptions that have been encountered during retries. - */ - HttpRequestRetryCondition(Response response, Exception exception, int tryCount, - List retriedExceptions) { - this.response = response; - this.exception = exception; - this.tryCount = tryCount; - this.retriedExceptions - = retriedExceptions == null ? Collections.emptyList() : Collections.unmodifiableList(retriedExceptions); - } - - /** - * Gets the HTTP response of the request that failed. - *

        - * This may be null if the request failed with a throwable and no response was received. - * - * @return The HTTP response of the request that failed. - */ - public Response getResponse() { - return response; - } - - /** - * Gets the exception of the request that failed. - * - * @return The throwable of the request that failed. - */ - public Exception getException() { - return exception; - } - - /** - * Gets the number of tries that have been attempted. - * - * @return The number of tries that have been attempted. - */ - public int getTryCount() { - return tryCount; - } - - /** - * Gets the unmodifiable list of exceptions that have been encountered during retries. - * - * @return The unmodifiable list of exceptions that have been encountered during retries. - */ - public List getRetriedExceptions() { - return retriedExceptions; - } -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpRetryCondition.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpRetryCondition.java new file mode 100644 index 000000000000..0d90bb81c6f3 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpRetryCondition.java @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.http.pipeline; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.models.binarydata.BinaryData; + +import java.util.Collections; +import java.util.List; + +/** + * Information about the request that failed, used to determine whether a retry should be attempted. + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public final class HttpRetryCondition { + private final Response response; + private final Exception exception; + private final int tryCount; + private final List retriedExceptions; + + /** + * Creates a new ShouldRetryInfo object. + * + * @param response The HTTP response of the request that failed. + * @param exception The exception of the request that failed. + * @param tryCount The number of tries that have been already attempted. + * @param retriedExceptions The list of exceptions that have been encountered during retries. + */ + HttpRetryCondition(Response response, Exception exception, int tryCount, + List retriedExceptions) { + this.response = response; + this.exception = exception; + this.tryCount = tryCount; + this.retriedExceptions + = retriedExceptions == null ? Collections.emptyList() : Collections.unmodifiableList(retriedExceptions); + } + + /** + * Gets the HTTP response of the request that failed. + *

        + * This may be null if the request failed with a throwable and no response was received. + * + * @return The HTTP response of the request that failed. + */ + public Response getResponse() { + return response; + } + + /** + * Gets the exception of the request that failed. + * + * @return The throwable of the request that failed. + */ + public Exception getException() { + return exception; + } + + /** + * Gets the number of tries that have been attempted. + * + * @return The number of tries that have been attempted. + */ + public int getTryCount() { + return tryCount; + } + + /** + * Gets the unmodifiable list of exceptions that have been encountered during retries. + * + * @return The unmodifiable list of exceptions that have been encountered during retries. + */ + public List getRetriedExceptions() { + return retriedExceptions; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpRetryOptions.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpRetryOptions.java similarity index 91% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpRetryOptions.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpRetryOptions.java index 5f1d30cc4e53..70c6f3a93808 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/HttpRetryOptions.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpRetryOptions.java @@ -1,9 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.http.models; +package io.clientcore.core.http.pipeline; -import io.clientcore.core.http.pipeline.HttpRequestRetryCondition; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.http.models.HttpHeaders; +import io.clientcore.core.http.models.Response; import io.clientcore.core.instrumentation.logging.ClientLogger; import java.time.Duration; @@ -14,13 +17,14 @@ /** * Options to configure the retry policy's behavior. */ +@Metadata(properties = MetadataProperties.FLUENT) public final class HttpRetryOptions { private static final ClientLogger LOGGER = new ClientLogger(HttpRetryOptions.class); private final int maxRetries; private final Duration baseDelay; private final Duration maxDelay; private final Duration fixedDelay; - private Predicate shouldRetryCondition; + private Predicate shouldRetryCondition; private Function delayFromHeaders; /** @@ -103,7 +107,7 @@ public Duration getFixedDelay() { * * @return The predicate that determines if a retry should be attempted. */ - public Predicate getShouldRetryCondition() { + public Predicate getShouldRetryCondition() { return shouldRetryCondition; } @@ -117,7 +121,7 @@ public Predicate getShouldRetryCondition() { * {@link Response}. * @return The updated {@link HttpRetryOptions} object. */ - public HttpRetryOptions setShouldRetryCondition(Predicate shouldRetryCondition) { + public HttpRetryOptions setShouldRetryCondition(Predicate shouldRetryCondition) { this.shouldRetryCondition = shouldRetryCondition; return this; } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpRetryPolicy.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpRetryPolicy.java index 398ae3857a39..a69788622d38 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpRetryPolicy.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/HttpRetryPolicy.java @@ -3,21 +3,28 @@ package io.clientcore.core.http.pipeline; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.http.models.HttpHeaderName; import io.clientcore.core.http.models.HttpHeaders; import io.clientcore.core.http.models.HttpRequest; -import io.clientcore.core.http.models.HttpRetryOptions; import io.clientcore.core.http.models.Response; import io.clientcore.core.implementation.http.HttpRequestAccessHelper; -import io.clientcore.core.implementation.util.ImplUtils; import io.clientcore.core.instrumentation.InstrumentationContext; import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.util.configuration.Configuration; +import io.clientcore.core.instrumentation.logging.LoggingEvent; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.utils.CoreUtils; +import io.clientcore.core.utils.DateTimeRfc1123; +import io.clientcore.core.utils.configuration.Configuration; import java.io.IOException; import java.io.UncheckedIOException; import java.net.HttpURLConnection; +import java.time.DateTimeException; import java.time.Duration; import java.time.OffsetDateTime; +import java.time.temporal.ChronoUnit; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; @@ -28,16 +35,16 @@ import static io.clientcore.core.implementation.instrumentation.AttributeKeys.HTTP_REQUEST_RESEND_COUNT_KEY; import static io.clientcore.core.implementation.instrumentation.AttributeKeys.RETRY_DELAY_KEY; -import static io.clientcore.core.implementation.instrumentation.AttributeKeys.RETRY_WAS_LAST_ATTEMPT_KEY; import static io.clientcore.core.implementation.instrumentation.AttributeKeys.RETRY_MAX_ATTEMPT_COUNT_KEY; +import static io.clientcore.core.implementation.instrumentation.AttributeKeys.RETRY_WAS_LAST_ATTEMPT_KEY; import static io.clientcore.core.implementation.instrumentation.LoggingEventNames.HTTP_RETRY_EVENT_NAME; -import static io.clientcore.core.implementation.util.ImplUtils.isNullOrEmpty; -import static io.clientcore.core.util.configuration.Configuration.PROPERTY_REQUEST_RETRY_COUNT; +import static io.clientcore.core.utils.configuration.Configuration.MAX_RETRY_ATTEMPTS; /** * A pipeline policy that retries when a recoverable HTTP error or exception occurs. */ -public class HttpRetryPolicy implements HttpPipelinePolicy { +@Metadata(properties = MetadataProperties.IMMUTABLE) +public final class HttpRetryPolicy implements HttpPipelinePolicy { // RetryPolicy is a commonly used policy, use a static logger. private static final ClientLogger LOGGER = new ClientLogger(HttpRetryPolicy.class); private final int maxRetries; @@ -45,17 +52,22 @@ public class HttpRetryPolicy implements HttpPipelinePolicy { private final Duration baseDelay; private final Duration maxDelay; private final Duration fixedDelay; - private final Predicate shouldRetryCondition; + private final Predicate shouldRetryCondition; private static final int DEFAULT_MAX_RETRIES; private static final Duration DEFAULT_BASE_DELAY = Duration.ofMillis(800); private static final Duration DEFAULT_MAX_DELAY = Duration.ofSeconds(8); private static final double JITTER_FACTOR = 0.05; + /** + * HTTP response status code for {@code Too Many Requests}. + */ + private static final int HTTP_STATUS_TOO_MANY_REQUESTS = 429; + static { - String envDefaultMaxRetries = Configuration.getGlobalConfiguration().get(PROPERTY_REQUEST_RETRY_COUNT); + String envDefaultMaxRetries = Configuration.getGlobalConfiguration().get(MAX_RETRY_ATTEMPTS); int defaultMaxRetries = 3; - if (!isNullOrEmpty(envDefaultMaxRetries)) { + if (!CoreUtils.isNullOrEmpty(envDefaultMaxRetries)) { try { defaultMaxRetries = Integer.parseInt(envDefaultMaxRetries); if (defaultMaxRetries < 0) { @@ -63,7 +75,7 @@ public class HttpRetryPolicy implements HttpPipelinePolicy { } } catch (NumberFormatException ignored) { LOGGER.atVerbose() - .addKeyValue("property", PROPERTY_REQUEST_RETRY_COUNT) + .addKeyValue("property", MAX_RETRY_ATTEMPTS) .log("Invalid property value. Using 3 retries as the maximum."); } } @@ -106,7 +118,7 @@ public HttpRetryPolicy(HttpRetryOptions retryOptions) { * {@code retryAfterHeader} is not null. */ HttpRetryPolicy(Duration baseDelay, Duration maxDelay, Duration fixedDelay, int maxRetries, - Function delayFromHeaders, Predicate shouldRetryCondition) { + Function delayFromHeaders, Predicate shouldRetryCondition) { if (fixedDelay == null && baseDelay == null) { this.baseDelay = DEFAULT_BASE_DELAY; this.maxDelay = DEFAULT_MAX_DELAY; @@ -121,16 +133,21 @@ public HttpRetryPolicy(HttpRetryOptions retryOptions) { } @Override - public Response process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { + public Response process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { return attempt(httpRequest, next, 0, null); } + @Override + public HttpPipelinePosition getPipelinePosition() { + return HttpPipelinePosition.RETRY; + } + /* * Determines the delay duration that should be waited before retrying using the well-known retry headers. */ private Duration getWellKnownRetryDelay(HttpHeaders responseHeaders, int tryCount, Supplier nowSupplier) { - Duration retryDelay = ImplUtils.getRetryAfterFromHeaders(responseHeaders, nowSupplier); + Duration retryDelay = getRetryAfterFromHeaders(responseHeaders, nowSupplier); if (retryDelay != null) { return retryDelay; } @@ -139,8 +156,8 @@ private Duration getWellKnownRetryDelay(HttpHeaders responseHeaders, int tryCoun return calculateRetryDelay(tryCount); } - private Response attempt(final HttpRequest httpRequest, final HttpPipelineNextPolicy next, final int tryCount, - final List suppressed) { + private Response attempt(final HttpRequest httpRequest, final HttpPipelineNextPolicy next, + final int tryCount, final List suppressed) { // the tryCount is updated by the caller and represents the number of attempts made so far. // It can be used by the policies during the process call. @@ -150,11 +167,11 @@ private Response attempt(final HttpRequest httpRequest, final HttpPipelineNex ? null : httpRequest.getRequestOptions().getInstrumentationContext(); - Response response; + Response response; ClientLogger logger = getLogger(httpRequest); try { - response = next.clone().process(); + response = next.copy().process(); } catch (RuntimeException err) { if (shouldRetryException(err, tryCount, suppressed)) { @@ -227,7 +244,7 @@ private Response attempt(final HttpRequest httpRequest, final HttpPipelineNex /* * Determines the delay duration that should be waited before retrying. */ - private Duration determineDelayDuration(Response response, int tryCount, + private Duration determineDelayDuration(Response response, int tryCount, Function delayFromHeaders) { // If the retry after header hasn't been configured, attempt to look up the well-known headers. if (delayFromHeaders == null) { @@ -243,15 +260,14 @@ private Duration determineDelayDuration(Response response, int tryCount, return calculateRetryDelay(tryCount); } - private boolean shouldRetryResponse(Response response, int tryCount, List retriedExceptions) { + private boolean shouldRetryResponse(Response response, int tryCount, + List retriedExceptions) { if (shouldRetryCondition != null) { return tryCount < maxRetries - && shouldRetryCondition - .test(new HttpRequestRetryCondition(response, null, tryCount, retriedExceptions)); + && shouldRetryCondition.test(new HttpRetryCondition(response, null, tryCount, retriedExceptions)); } else { return tryCount < maxRetries - && defaultShouldRetryCondition( - new HttpRequestRetryCondition(response, null, tryCount, retriedExceptions)); + && defaultShouldRetryCondition(new HttpRetryCondition(response, null, tryCount, retriedExceptions)); } } @@ -263,8 +279,7 @@ private boolean shouldRetryException(Exception exception, int tryCount, List= HttpURLConnection.HTTP_INTERNAL_ERROR && code != HttpURLConnection.HTTP_NOT_IMPLEMENTED && code != HttpURLConnection.HTTP_VERSION)); } else { - return requestRetryCondition.getException() instanceof Exception; + return requestRetryCondition.getException() != null; } } @@ -340,4 +356,78 @@ private ClientLogger getLogger(HttpRequest httpRequest) { return logger == null ? LOGGER : logger; } + + // TODO (alzimmer): This cannot exist in ClientCore as 'x-ms-*' headers are using the Microsoft header extension + // prefix. We'll probably want to allow HttpRetryPolicy to configure which headers it looks for when determining + // backoff. + private static final HttpHeaderName RETRY_AFTER_MS_HEADER = HttpHeaderName.fromString("retry-after-ms"); + private static final HttpHeaderName X_MS_RETRY_AFTER_MS_HEADER = HttpHeaderName.fromString("x-ms-retry-after-ms"); + + /** + * Attempts to extract a retry after duration from a given set of {@link HttpHeaders}. + *

        + * This searches for the well-known retry after headers {@code Retry-After}, {@code retry-after-ms}, and + * {@code x-ms-retry-after-ms}. + *

        + * If no well-known headers are found null will be returned. + * + * @param headers The set of headers to search for a well-known retry after header. + * @param nowSupplier A supplier for the current time used when {@code Retry-After} is using relative retry after + * time. + * @return The retry after duration if a well-known retry after header was found, otherwise null. + */ + private static Duration getRetryAfterFromHeaders(HttpHeaders headers, Supplier nowSupplier) { + // Found 'x-ms-retry-after-ms' header, use a Duration of milliseconds based on the value. + Duration retryDelay = tryGetRetryDelay(headers, X_MS_RETRY_AFTER_MS_HEADER, HttpRetryPolicy::tryGetDelayMillis); + if (retryDelay != null) { + return retryDelay; + } + + // Found 'retry-after-ms' header, use a Duration of milliseconds based on the value. + retryDelay = tryGetRetryDelay(headers, RETRY_AFTER_MS_HEADER, HttpRetryPolicy::tryGetDelayMillis); + if (retryDelay != null) { + return retryDelay; + } + + // Found 'Retry-After' header. First, attempt to resolve it as a Duration of seconds. If that fails, then + // attempt to resolve it as an HTTP date (RFC1123). + retryDelay = tryGetRetryDelay(headers, HttpHeaderName.RETRY_AFTER, + headerValue -> tryParseLongOrDateTime(headerValue, nowSupplier)); + + // Either the retry delay will have been found or it'll be null, null indicates no retry after. + return retryDelay; + } + + private static Duration tryGetRetryDelay(HttpHeaders headers, HttpHeaderName headerName, + Function delayParser) { + String headerValue = headers.getValue(headerName); + + return CoreUtils.isNullOrEmpty(headerValue) ? null : delayParser.apply(headerValue); + } + + private static Duration tryGetDelayMillis(String value) { + long delayMillis = tryParseLong(value); + return (delayMillis >= 0) ? Duration.ofMillis(delayMillis) : null; + } + + private static Duration tryParseLongOrDateTime(String value, Supplier nowSupplier) { + long delaySeconds; + try { + OffsetDateTime retryAfter = new DateTimeRfc1123(value).getDateTime(); + + delaySeconds = nowSupplier.get().until(retryAfter, ChronoUnit.SECONDS); + } catch (DateTimeException ex) { + delaySeconds = tryParseLong(value); + } + + return (delaySeconds >= 0) ? Duration.ofSeconds(delaySeconds) : null; + } + + private static long tryParseLong(String value) { + try { + return Long.parseLong(value); + } catch (NumberFormatException ex) { + return -1; + } + } } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/KeyCredentialPolicy.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/KeyCredentialPolicy.java index e8ef08f96ddf..11564d697c03 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/KeyCredentialPolicy.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/KeyCredentialPolicy.java @@ -3,12 +3,15 @@ package io.clientcore.core.http.pipeline; -import io.clientcore.core.credential.KeyCredential; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.credentials.KeyCredential; import io.clientcore.core.http.models.HttpHeaderName; import io.clientcore.core.http.models.HttpHeaders; import io.clientcore.core.http.models.HttpRequest; import io.clientcore.core.http.models.Response; import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.models.binarydata.BinaryData; import java.util.Objects; @@ -18,7 +21,8 @@ *

        Requests sent with this pipeline policy are required to use {@code HTTPS}. If the request isn't using {@code HTTPS} * an exception will be thrown to prevent leaking the key.

        */ -public class KeyCredentialPolicy implements HttpPipelinePolicy { +@Metadata(properties = MetadataProperties.IMMUTABLE) +public class KeyCredentialPolicy extends HttpCredentialPolicy { private static final ClientLogger LOGGER = new ClientLogger(KeyCredentialPolicy.class); private final HttpHeaderName name; private final KeyCredential credential; @@ -71,7 +75,7 @@ private static HttpHeaderName validateName(String name) { } @Override - public Response process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { + public Response process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { setCredential(httpRequest.getHeaders()); return next.process(); } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/OAuthBearerTokenAuthenticationPolicy.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/OAuthBearerTokenAuthenticationPolicy.java new file mode 100644 index 000000000000..00c1c1fc9551 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/OAuthBearerTokenAuthenticationPolicy.java @@ -0,0 +1,118 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.http.pipeline; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.credentials.oauth.AccessToken; +import io.clientcore.core.credentials.oauth.OAuthTokenCredential; +import io.clientcore.core.credentials.oauth.OAuthTokenRequestContext; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.models.binarydata.BinaryData; + +import java.io.IOException; +import java.util.Objects; + +/** + *

        The {@code OAuthBearerTokenAuthenticationPolicy} class is an implementation of the + * {@link HttpCredentialPolicy}. This policy uses a {@link io.clientcore.core.credentials.oauth.OAuthTokenCredential} + * to authenticate the request with a bearer token.

        + * + *

        This class is useful when you need to authorize requests with a bearer token. It ensures that the + * requests are sent over HTTPS to prevent the token from being leaked.

        + * + * @see io.clientcore.core.credentials.oauth.OAuthTokenCredential + * @see HttpPipelinePolicy + * @see HttpPipeline + * @see HttpRequest + * @see Response + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public class OAuthBearerTokenAuthenticationPolicy extends HttpCredentialPolicy { + private static final ClientLogger LOGGER = new ClientLogger(OAuthBearerTokenAuthenticationPolicy.class); + private static final String BEARER = "Bearer"; + + private final String[] scopes; + private final OAuthTokenCredential credential; + + /** + * Creates BearerTokenAuthenticationPolicy. + * + * @param credential the token credential to authenticate the request + * @param scopes the scopes of authentication the credential should get token for + */ + public OAuthBearerTokenAuthenticationPolicy(OAuthTokenCredential credential, String... scopes) { + Objects.requireNonNull(credential); + this.credential = credential; + this.scopes = scopes; + } + + /** + * Executed before sending the initial request and authenticates the request. + * + * @param httpRequest The request context. + */ + public void authorizeRequest(HttpRequest httpRequest) { + setAuthorizationHeader(httpRequest, new OAuthTokenRequestContext().addScopes(scopes)); + } + + /** + * Authorizes the request with the bearer token acquired using the specified {@code tokenRequestContext} + * + * @param request the HTTP request. + * @param tokenRequestContext the token request context to be used for token acquisition. + */ + protected void setAuthorizationHeader(HttpRequest request, OAuthTokenRequestContext tokenRequestContext) { + AccessToken token = credential.getToken(tokenRequestContext); + request.getHeaders().set(HttpHeaderName.AUTHORIZATION, BEARER + " " + token); + } + + @Override + public Response process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { + if (!"https".equals(httpRequest.getUri().getScheme())) { + throw LOGGER.logThrowableAsError( + new RuntimeException("Token credentials require a URL using the HTTPS protocol scheme")); + } + + HttpPipelineNextPolicy nextPolicy = next.copy(); + + authorizeRequest(httpRequest); + Response httpResponse = next.process(); + String authHeader = httpResponse.getHeaders().getValue(HttpHeaderName.WWW_AUTHENTICATE); + if (httpResponse.getStatusCode() == 401 && authHeader != null) { + if (authorizeRequestOnChallenge(httpRequest, httpResponse)) { + // body needs to be closed or read to the end to release the connection + try { + httpResponse.close(); + } catch (IOException e) { + throw LOGGER.logThrowableAsError(new RuntimeException(e)); + } + return nextPolicy.process(); + } else { + return httpResponse; + } + } + return httpResponse; + } + + /** + * Handles the authentication challenge in the event a 401 response with a WWW-Authenticate authentication challenge + * header is received after the initial request and returns appropriate {@link OAuthTokenRequestContext} to be + * used for re-authentication. + * + *

        + * The default implementation doesn't handle challenges. You can override and your implementation as needed. + *

        + * + * @param httpRequest The http request. + * @param response The Http Response containing the authentication challenge header. + * @return A boolean indicating if the request was authorized again via re-authentication + */ + public boolean authorizeRequestOnChallenge(HttpRequest httpRequest, Response response) { + return false; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/RequestIdPolicy.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/RequestIdPolicy.java new file mode 100644 index 000000000000..3da613b64c39 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/RequestIdPolicy.java @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.http.pipeline; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpHeaders; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.utils.CoreUtils; + +import java.util.Objects; + +/** + * The {@link RequestIdPolicy} class is an implementation of the {@link HttpPipelinePolicy} interface. This policy is + * used to add a unique identifier to each {@link HttpRequest} in the form of a UUID in the request header. + *

        + * The request id is set in the request header specified by {@code requestIdHeaderName}. If the request already + * contains a value for the request id header, it will not be overwritten. + *

        + * This class is useful when you need to track HTTP requests for debugging or auditing purposes. It allows you to + * specify a custom header name for the request id. + * + *

        Code sample:

        + * + *

        In this example, a {@link RequestIdPolicy} is created with a custom header name. Once added to the pipeline + * requests will have their request id set in the 'request-id' header by the {@link RequestIdPolicy}.

        + * + * + *
        + * RequestIdPolicy policy = new RequestIdPolicy(HttpHeaderName.fromString("my-request-id"));
        + * 
        + * + * + * @see io.clientcore.core.http.pipeline + * @see HttpPipelinePolicy + * @see HttpPipeline + * @see HttpRequest + * @see Response + * @see HttpHeaders + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public class RequestIdPolicy implements HttpPipelinePolicy { + private final HttpHeaderName requestIdHeaderName; + + /** + * Creates {@link RequestIdPolicy} with provided {@code requestIdHeaderName}. + * + * @param requestIdHeaderName to be used to set in {@link HttpRequest}. + * @throws NullPointerException if {@code requestIdHeaderName} is null. + */ + public RequestIdPolicy(HttpHeaderName requestIdHeaderName) { + this.requestIdHeaderName = Objects.requireNonNull(requestIdHeaderName, "requestIdHeaderName can not be null."); + } + + private static void setRequestIdHeader(HttpRequest request, HttpHeaderName requestIdHeaderName) { + HttpHeaders headers = request.getHeaders(); + String requestId = headers.getValue(requestIdHeaderName); + if (requestId == null) { + headers.set(requestIdHeaderName, CoreUtils.randomUuid().toString()); + } + } + + @Override + public Response process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { + setRequestIdHeader(httpRequest, requestIdHeaderName); + return next.process(); + } + + @Override + public final HttpPipelinePosition getPipelinePosition() { + return HttpPipelinePosition.BEFORE_REDIRECT; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/SetDatePolicy.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/SetDatePolicy.java new file mode 100644 index 000000000000..35a5262d0409 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/SetDatePolicy.java @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.http.pipeline; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.utils.DateTimeRfc1123; + +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.Locale; + +/** + *

        The {@code AddDatePolicy} class is an implementation of the {@link HttpPipelinePolicy} interface. This policy is + * used to add a "Date" header in RFC 1123 format when sending an HTTP request.

        + * + * @see io.clientcore.core.http.pipeline + * @see HttpPipelinePolicy + * @see HttpPipeline + * @see HttpRequest + * @see Response + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public class SetDatePolicy implements HttpPipelinePolicy { + private static final DateTimeFormatter FORMATTER + = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'").withZone(ZoneOffset.UTC).withLocale(Locale.US); + + /** + * Creates a new instance of {@link SetDatePolicy}. + */ + public SetDatePolicy() { + } + + @Override + public Response process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { + OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC); + try { + httpRequest.getHeaders().set(HttpHeaderName.DATE, DateTimeRfc1123.toRfc1123String(now)); + } catch (IllegalArgumentException ignored) { + httpRequest.getHeaders().set(HttpHeaderName.DATE, FORMATTER.format(now)); + } + return next.process(); + } + + @Override + public final HttpPipelinePosition getPipelinePosition() { + return HttpPipelinePosition.AFTER_RETRY; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/UserAgentPolicy.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/UserAgentPolicy.java new file mode 100644 index 000000000000..f4f6cf99d440 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/http/pipeline/UserAgentPolicy.java @@ -0,0 +1,148 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.http.pipeline; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.utils.CoreUtils; +import io.clientcore.core.utils.configuration.Configuration; + +/** + * The {@link UserAgentPolicy} class is an implementation of the {@link HttpPipelinePolicy} interface. This policy is + * used to add a "User-Agent" header to each {@code HttpRequest}. + *

        + * If the {@code User-Agent} header is already present in the request, it will not be overwritten. + *

        + * This class is useful when you need to add a specific "User-Agent" header for all requests in a pipeline. It ensures + * that the "User-Agent" header is set correctly for each request. The "User-Agent" header is used to provide the server + * with information about the software used by the client. + * + *

        Code sample:

        + * + *

        In this example, a {@code UserAgentPolicy} is created with a "User-Agent" header value of "MyApp/1.0". + * Once added to the pipeline, requests will have their "User-Agent" header set to "MyApp/1.0" by the + * {@code UserAgentPolicy}.

        + * + * + *
        + * UserAgentPolicy policy = new UserAgentPolicy("MyApp/1.0");
        + * 
        + * + * + * @see io.clientcore.core.http.pipeline + * @see HttpPipelinePolicy + * @see HttpPipeline + * @see HttpRequest + * @see Response + * @see HttpHeaderName + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public class UserAgentPolicy implements HttpPipelinePolicy { + private final String userAgent; + + /** + * Creates a {@link UserAgentPolicy} with a default user agent string. + */ + public UserAgentPolicy() { + this(null); + } + + /** + * Creates a UserAgentPolicy with {@code userAgent} as the header value. If {@code userAgent} is {@code null}, then + * the default user agent value is used. + * + * @param userAgent The user agent string to add to request headers. + */ + public UserAgentPolicy(String userAgent) { + if (userAgent != null) { + this.userAgent = userAgent; + } else { + this.userAgent = DEFAULT_USER_AGENT_HEADER; + } + } + + /** + * Creates a UserAgentPolicy with the {@code sdkName} and {@code sdkVersion} in the User-Agent header value. + * + * @param applicationId User specified application Id. + * @param sdkName Name of the client library. + * @param sdkVersion Version of the client library. + */ + public UserAgentPolicy(String applicationId, String sdkName, String sdkVersion) { + this.userAgent = toUserAgentString(applicationId, sdkName, sdkVersion); + } + + @Override + public Response process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { + httpRequest.getHeaders().set(HttpHeaderName.USER_AGENT, userAgent); + return next.process(); + } + + @Override + public final HttpPipelinePosition getPipelinePosition() { + return HttpPipelinePosition.BEFORE_REDIRECT; + } + + private static final int MAX_APPLICATION_ID_LENGTH = 24; + private static final String INVALID_APPLICATION_ID_LENGTH + = "'applicationId' length cannot be greater than " + MAX_APPLICATION_ID_LENGTH; + private static final String INVALID_APPLICATION_ID_SPACE = "'applicationId' cannot contain spaces."; + + /** + * Default {@code UserAgent} header. + */ + static final String DEFAULT_USER_AGENT_HEADER = "sdk-java"; + + /** + * Return user agent string for the given sdk name and version. + * + * @param applicationId Name of the application. + * @param sdkName Name of the SDK. + * @param sdkVersion Version of the SDK. + * @return User agent string as specified in design guidelines. + * + * @throws IllegalArgumentException If {@code applicationId} contains spaces or is larger than 24 characters in + * length. + */ + private static String toUserAgentString(String applicationId, String sdkName, String sdkVersion) { + StringBuilder userAgentBuilder = new StringBuilder(); + + if (!CoreUtils.isNullOrEmpty(applicationId)) { + if (applicationId.length() > MAX_APPLICATION_ID_LENGTH) { + throw new IllegalArgumentException(INVALID_APPLICATION_ID_LENGTH); + } else if (applicationId.contains(" ")) { + throw new IllegalArgumentException(INVALID_APPLICATION_ID_SPACE); + } else { + userAgentBuilder.append(applicationId).append(" "); + } + } + + // Add the required default User-Agent string. + userAgentBuilder.append(DEFAULT_USER_AGENT_HEADER).append("-").append(sdkName).append("/").append(sdkVersion); + appendPlatformInfo(userAgentBuilder); + + return userAgentBuilder.toString(); + } + + /** + * Appends the platform information telemetry to the User-Agent header. + */ + private static void appendPlatformInfo(StringBuilder stringBuilder) { + String javaVersion = Configuration.getGlobalConfiguration().get("java.version"); + String osName = Configuration.getGlobalConfiguration().get("os.name"); + String osVersion = Configuration.getGlobalConfiguration().get("os.version"); + + stringBuilder.append(" (") + .append(javaVersion) + .append("; ") + .append(osName) + .append("; ") + .append(osVersion) + .append(")"); + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/ConstructorReflectiveInvoker.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/ConstructorReflectiveInvoker.java new file mode 100644 index 000000000000..cb2271eea5d2 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/ConstructorReflectiveInvoker.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.implementation; + +import java.lang.reflect.Constructor; +import static io.clientcore.core.implementation.MethodHandleReflectiveInvoker.createFinalArgs; + +/** + * {@link Constructor}-based implementation of {@link ReflectiveInvoker}. + */ +final class ConstructorReflectiveInvoker implements ReflectiveInvoker { + private final Constructor constructor; + + ConstructorReflectiveInvoker(Constructor constructor) { + this.constructor = constructor; + } + + @Override + public Object invokeStatic(Object... args) throws Exception { + return constructor.newInstance(args); + } + + @Override + public Object invokeWithArguments(Object target, Object... args) throws Exception { + return constructor.newInstance(createFinalArgs(args)); + } + + @Override + public Object invoke() throws Exception { + return constructor.newInstance(); + } + + @Override + public Object invoke(Object argOrTarget) throws Exception { + return constructor.newInstance(argOrTarget); + } + + @Override + public Object invoke(Object argOrTarget, Object arg1) throws Exception { + return constructor.newInstance(argOrTarget, arg1); + } + + @Override + public Object invoke(Object argOrTarget, Object arg1, Object arg2) throws Exception { + return constructor.newInstance(argOrTarget, arg1, arg2); + } + + @Override + public Object invoke(Object argOrTarget, Object arg1, Object arg2, Object arg3) throws Exception { + return constructor.newInstance(argOrTarget, arg1, arg2, arg3); + } + + @Override + public int getParameterCount() { + return constructor.getParameterCount(); + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/GenericParameterizedType.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/GenericParameterizedType.java new file mode 100644 index 000000000000..32523a90ce31 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/GenericParameterizedType.java @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.implementation; + +import io.clientcore.core.instrumentation.logging.ClientLogger; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.Arrays; +import java.util.Objects; +import java.util.stream.Collectors; + +/** + * A {@link ParameterizedType} implementation that allows for reference type arguments. + */ +public final class GenericParameterizedType implements ParameterizedType { + private static final ClientLogger LOGGER = new ClientLogger(GenericParameterizedType.class); + + private final Class raw; + private final Type[] args; + private String cachedToString; + + /** + * Creates a new instance of {@link GenericParameterizedType}. + * + * @param raw The raw type. + * @param args The type arguments. + */ + public GenericParameterizedType(Class raw, Type... args) { + this.raw = raw; + + if (args == null) { + throw LOGGER.logThrowableAsError(new IllegalArgumentException("args cannot be null")); + } + + Type[] argsCopy = new Type[args.length]; + for (int i = 0; i < args.length; i++) { + if (args[i] == null) { + throw LOGGER.logThrowableAsError( + new IllegalArgumentException("args cannot contain null: null value in index " + i)); + } + argsCopy[i] = args[i]; + } + this.args = argsCopy; + } + + @Override + public Type[] getActualTypeArguments() { + return args; + } + + @Override + public Type getRawType() { + return raw; + } + + @Override + public Type getOwnerType() { + return null; + } + + @Override + public String toString() { + if (cachedToString == null) { + cachedToString = raw.getTypeName() + "<" + + Arrays.stream(args).map(Type::getTypeName).collect(Collectors.joining(", ")) + ">"; + } + return cachedToString; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + GenericParameterizedType that = (GenericParameterizedType) o; + return Objects.equals(raw, that.raw) && Objects.deepEquals(args, that.args); + } + + @Override + public int hashCode() { + return Objects.hash(raw, Arrays.hashCode(args)); + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/MethodReflectiveInvoker.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/MethodReflectiveInvoker.java new file mode 100644 index 000000000000..2326aa0bb04a --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/MethodReflectiveInvoker.java @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.implementation; + +import java.lang.reflect.Method; + +/** + * {@link Method}-based implementation of {@link ReflectiveInvoker}. + */ +final class MethodReflectiveInvoker implements ReflectiveInvoker { + private final Method method; + + MethodReflectiveInvoker(Method method) { + this.method = method; + } + + @Override + public Object invokeStatic(Object... args) throws Exception { + return method.invoke(null, args); + } + + @Override + public Object invokeWithArguments(Object target, Object... args) throws Exception { + return method.invoke(target, args); + } + + @Override + public Object invoke() throws Exception { + return method.invoke(null); + } + + @Override + public Object invoke(Object argOrTarget) throws Exception { + return method.invoke(argOrTarget); + } + + @Override + public Object invoke(Object argOrTarget, Object arg1) throws Exception { + return method.invoke(argOrTarget, arg1); + } + + @Override + public Object invoke(Object argOrTarget, Object arg1, Object arg2) throws Exception { + return method.invoke(argOrTarget, arg1, arg2); + } + + @Override + public Object invoke(Object argOrTarget, Object arg1, Object arg2, Object arg3) throws Exception { + return method.invoke(argOrTarget, arg1, arg2, arg3); + } + + @Override + public int getParameterCount() { + return method.getParameterCount(); + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/ReflectionSerializable.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/ReflectionSerializable.java index 5230abb36db6..0810e129ad44 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/ReflectionSerializable.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/ReflectionSerializable.java @@ -4,7 +4,6 @@ package io.clientcore.core.implementation; import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.serialization.json.JsonProviders; import io.clientcore.core.serialization.json.JsonReader; import io.clientcore.core.serialization.json.JsonSerializable; import io.clientcore.core.serialization.json.JsonWriter; @@ -76,7 +75,7 @@ public static String serializeJsonSerializableToString(JsonSerializable jsonS private static T serializeJsonSerializableWithReturn(JsonSerializable jsonSerializable, Function returner) throws IOException { try (AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(); - JsonWriter jsonWriter = JsonProviders.createWriter(outputStream)) { + JsonWriter jsonWriter = JsonWriter.toStream(outputStream)) { jsonWriter.writeJson(jsonSerializable).flush(); return returner.apply(outputStream); @@ -92,7 +91,7 @@ private static T serializeJsonSerializableWithReturn(JsonSerializable jso */ public static void serializeJsonSerializableIntoOutputStream(JsonSerializable jsonSerializable, OutputStream outputStream) throws IOException { - try (JsonWriter jsonWriter = JsonProviders.createWriter(outputStream)) { + try (JsonWriter jsonWriter = JsonWriter.toStream(outputStream)) { jsonWriter.writeJson(jsonSerializable).flush(); } } @@ -119,7 +118,7 @@ public static Object deserializeAsJsonSerializable(Class jsonSerializable, by } }); - try (JsonReader jsonReader = JsonProviders.createReader(json)) { + try (JsonReader jsonReader = JsonReader.fromBytes(json)) { return readJson.invokeStatic(jsonReader); } catch (Throwable e) { if (e instanceof IOException) { diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/ReflectionUtils.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/ReflectionUtils.java index b9dfba5f30af..4ebe2e541ff1 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/ReflectionUtils.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/ReflectionUtils.java @@ -13,7 +13,23 @@ */ public abstract class ReflectionUtils { private static final ClientLogger LOGGER = new ClientLogger(ReflectionUtils.class); - private static final ReflectionUtilsApi INSTANCE = new ReflectionUtilsMethodHandle(); + private static final ReflectionUtilsApi INSTANCE; + + static { + ReflectionUtilsApi instance; + try { + LOGGER.atVerbose().log("Attempting to use java.lang.invoke package to handle reflection."); + instance = new ReflectionUtilsMethodHandle(); + LOGGER.atVerbose().log("Successfully used java.lang.invoke package to handle reflection."); + } catch (LinkageError ignored) { + LOGGER.atVerbose() + .log("Failed to use java.lang.invoke package to handle reflection. Falling back to " + + "java.lang.reflect package to handle reflection."); + instance = new ReflectionUtilsClassic(); + LOGGER.atVerbose().log("Successfully used java.lang.reflect package to handle reflection."); + } + INSTANCE = instance; + } /** * Creates an {@link ReflectiveInvoker} instance that will invoke a {@link Method}. @@ -114,6 +130,15 @@ public static ReflectiveInvoker getConstructorInvoker(Class targetClass, Cons return INSTANCE.getConstructorInvoker(targetClass, constructor, scopeToClientCore); } + /** + * Determines whether a Java 9+ module-based implementation of {@link ReflectionUtilsApi} is being used. + * + * @return Whether a Java 9+ module-based implementation of {@link ReflectionUtilsApi} is being used. + */ + public static boolean isModuleBased() { + return INSTANCE.isModuleBased(); + } + /** * Creates a dummy {@link ReflectiveInvoker} that will always return null. Used for scenarios where an {@link ReflectiveInvoker} is * needed as an identifier but will never be used. diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/ReflectionUtilsApi.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/ReflectionUtilsApi.java index d7f413a28d5d..f0948c0ed9d1 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/ReflectionUtilsApi.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/ReflectionUtilsApi.java @@ -62,4 +62,11 @@ ReflectiveInvoker getMethodInvoker(Class targetClass, Method method, boolean */ ReflectiveInvoker getConstructorInvoker(Class targetClass, Constructor constructor, boolean scopeToGenericCore) throws Exception; + + /** + * Indicates whether the {@link ReflectionUtilsApi} instance uses Java 9+ modules. + * + * @return Whether the {@link ReflectionUtilsApi} instance uses Java 9+ modules. + */ + boolean isModuleBased(); } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/ReflectionUtilsClassic.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/ReflectionUtilsClassic.java new file mode 100644 index 000000000000..05845f1040fa --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/ReflectionUtilsClassic.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.implementation; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; + +/** + * Implementation for {@link ReflectionUtilsApi} using {@code java.lang.reflect} to handle reflectively invoking APIs. + */ +final class ReflectionUtilsClassic implements ReflectionUtilsApi { + @Override + public ReflectiveInvoker getMethodInvoker(Class targetClass, Method method, boolean scopeToGenericCore) { + return new MethodReflectiveInvoker(method); + } + + @Override + public ReflectiveInvoker getConstructorInvoker(Class targetClass, Constructor constructor, + boolean scopeToGenericCore) { + return new ConstructorReflectiveInvoker(constructor); + } + + @Override + public boolean isModuleBased() { + return false; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/ReflectionUtilsMethodHandle.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/ReflectionUtilsMethodHandle.java index 239cc97793ac..497638b32d6f 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/ReflectionUtilsMethodHandle.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/ReflectionUtilsMethodHandle.java @@ -2,33 +2,120 @@ // Licensed under the MIT License. package io.clientcore.core.implementation; +import io.clientcore.core.instrumentation.logging.ClientLogger; + +import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; import java.lang.reflect.Constructor; import java.lang.reflect.Method; /** * Implementation for {@link ReflectionUtilsApi} using {@code java.lang.invoke} to handle reflectively invoking APIs. */ +@SuppressWarnings("deprecation") final class ReflectionUtilsMethodHandle implements ReflectionUtilsApi { - private static final Module CORE_MODULE = ReflectionUtilsMethodHandle.class.getModule(); - private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup(); + private static final ClientLogger LOGGER = new ClientLogger(ReflectionUtilsMethodHandle.class); + private static final boolean MODULE_BASED; + + private static final MethodHandle CLASS_GET_MODULE_METHOD_HANDLE; + private static final MethodHandle MODULE_IS_NAMED_METHOD_HANDLE; + private static final MethodHandle MODULE_ADD_READS_METHOD_HANDLE; + private static final MethodHandle METHOD_HANDLES_PRIVATE_LOOKUP_IN_METHOD_HANDLE; + private static final MethodHandle MODULE_IS_OPEN_UNCONDITIONALLY_METHOD_HANDLE; + private static final MethodHandle MODULE_IS_OPEN_TO_OTHER_MODULE_METHOD_HANDLE; + + private static final MethodHandles.Lookup LOOKUP; + private static final Object CORE_MODULE; + + private static final MethodHandle JDK_INTERNAL_PRIVATE_LOOKUP_IN_CONSTRUCTOR; + + static { + boolean moduleBased = false; + MethodHandle classGetModule = null; + MethodHandle moduleIsNamed = null; + MethodHandle moduleAddReads = null; + MethodHandle methodHandlesPrivateLookupIn = null; + MethodHandle moduleIsOpenUnconditionally = null; + MethodHandle moduleIsOpenToOtherModule = null; + + MethodHandles.Lookup lookup = MethodHandles.lookup(); + Object coreModule = null; + + MethodHandle jdkInternalPrivateLookupInConstructor = null; + + try { + Class moduleClass = Class.forName("java.lang.Module"); + classGetModule = lookup.unreflect(Class.class.getDeclaredMethod("getModule")); + moduleIsNamed = lookup.unreflect(moduleClass.getDeclaredMethod("isNamed")); + moduleAddReads = lookup.unreflect(moduleClass.getDeclaredMethod("addReads", moduleClass)); + methodHandlesPrivateLookupIn = lookup.findStatic(MethodHandles.class, "privateLookupIn", + MethodType.methodType(MethodHandles.Lookup.class, Class.class, MethodHandles.Lookup.class)); + moduleIsOpenUnconditionally = lookup.unreflect(moduleClass.getDeclaredMethod("isOpen", String.class)); + moduleIsOpenToOtherModule + = lookup.unreflect(moduleClass.getDeclaredMethod("isOpen", String.class, moduleClass)); + + coreModule = classGetModule.invokeWithArguments(ReflectionUtils.class); + moduleBased = true; + } catch (Throwable throwable) { + if (throwable instanceof Error) { + throw (Error) throwable; + } else { + LOGGER.atInfo() + .log("Unable to create MethodHandles to use Java 9+ MethodHandles.privateLookupIn. Will " + + "attempt to fallback to using the package-private constructor.", throwable); + } + } + + if (!moduleBased) { + try { + Constructor privateLookupInConstructor + = MethodHandles.Lookup.class.getDeclaredConstructor(Class.class); + + if (!privateLookupInConstructor.isAccessible()) { + privateLookupInConstructor.setAccessible(true); + } + + jdkInternalPrivateLookupInConstructor = lookup.unreflectConstructor(privateLookupInConstructor); + } catch (ReflectiveOperationException ex) { + throw LOGGER.logThrowableAsError( + new RuntimeException("Unable to use package-private MethodHandles.Lookup constructor.", ex)); + } + } + + MODULE_BASED = moduleBased; + CLASS_GET_MODULE_METHOD_HANDLE = classGetModule; + MODULE_IS_NAMED_METHOD_HANDLE = moduleIsNamed; + MODULE_ADD_READS_METHOD_HANDLE = moduleAddReads; + METHOD_HANDLES_PRIVATE_LOOKUP_IN_METHOD_HANDLE = methodHandlesPrivateLookupIn; + MODULE_IS_OPEN_UNCONDITIONALLY_METHOD_HANDLE = moduleIsOpenUnconditionally; + MODULE_IS_OPEN_TO_OTHER_MODULE_METHOD_HANDLE = moduleIsOpenToOtherModule; + LOOKUP = lookup; + CORE_MODULE = coreModule; + JDK_INTERNAL_PRIVATE_LOOKUP_IN_CONSTRUCTOR = jdkInternalPrivateLookupInConstructor; + } @Override - public ReflectiveInvoker getMethodInvoker(Class targetClass, Method method, boolean scopeToGenericCore) + public ReflectiveInvoker getMethodInvoker(Class targetClass, Method method, boolean scopeToClientCore) throws Exception { - MethodHandles.Lookup lookup = getLookupToUse(targetClass, scopeToGenericCore); + MethodHandles.Lookup lookup = getLookupToUse(targetClass, scopeToClientCore); return new MethodHandleReflectiveInvoker(lookup.unreflect(method)); } @Override public ReflectiveInvoker getConstructorInvoker(Class targetClass, Constructor constructor, - boolean scopeToGenericCore) throws Exception { - MethodHandles.Lookup lookup = getLookupToUse(targetClass, scopeToGenericCore); + boolean scopeToClientCore) throws Exception { + MethodHandles.Lookup lookup = getLookupToUse(targetClass, scopeToClientCore); return new MethodHandleReflectiveInvoker(lookup.unreflectConstructor(constructor)); } + @Override + public boolean isModuleBased() { + return MODULE_BASED; + } + /** * Gets the {@link MethodHandles.Lookup} to use when performing reflective operations. *

        @@ -41,43 +128,50 @@ public ReflectiveInvoker getConstructorInvoker(Class targetClass, Constructor * {@code targetClass}. * * @param targetClass The {@link Class} that will need to be reflectively accessed. - * @param scopeToGenericCore Whether to scope the {@link MethodHandles.Lookup} to {@code io.clientcore.core} if Java 9+ + * @param scopeToClientCore Whether to scope the {@link MethodHandles.Lookup} to {@code io.clientcore.core} if Java 9+ * modules is being used. * @return The {@link MethodHandles.Lookup} that will allow {@code io.clientcore.core} to access the * {@code targetClass} reflectively. * @throws Exception If the underlying reflective calls throw an exception. */ - private static MethodHandles.Lookup getLookupToUse(Class targetClass, boolean scopeToGenericCore) + private static MethodHandles.Lookup getLookupToUse(Class targetClass, boolean scopeToClientCore) throws Exception { try { - if (!scopeToGenericCore) { - return MethodHandles.publicLookup(); - } + if (MODULE_BASED) { + if (!scopeToClientCore) { + return MethodHandles.publicLookup(); + } - Module responseModule = targetClass.getModule(); + Object responseModule = CLASS_GET_MODULE_METHOD_HANDLE.invoke(targetClass); - // The unnamed module is opened unconditionally, have Core read it and use a private proxy lookup to - // enable all lookup scenarios. - if (!responseModule.isNamed()) { - CORE_MODULE.addReads(responseModule); - return performSafePrivateLookupIn(targetClass); - } + // The unnamed module is opened unconditionally, have Core read it and use a private proxy lookup to + // enable all lookup scenarios. + if (!(boolean) MODULE_IS_NAMED_METHOD_HANDLE.invoke(responseModule)) { + MODULE_ADD_READS_METHOD_HANDLE.invokeWithArguments(CORE_MODULE, responseModule); + return performSafePrivateLookupIn(targetClass); + } - // If the response module is the Core module return the Core private lookup. - if (responseModule == CORE_MODULE) { - return LOOKUP; - } + // If the response module is the Core module return the Core private lookup. + if (responseModule == CORE_MODULE) { + return LOOKUP; + } - // Next check if the target class module is opened either unconditionally or to Core's module. If so, - // also use a private proxy lookup to enable all lookup scenarios. - String packageName = targetClass.getPackage().getName(); - if (responseModule.isOpen(packageName) || responseModule.isOpen(packageName, CORE_MODULE)) { - CORE_MODULE.addReads(responseModule); - return performSafePrivateLookupIn(targetClass); - } + // Next check if the target class module is opened either unconditionally or to Core's module. If so, + // also use a private proxy lookup to enable all lookup scenarios. + String packageName = targetClass.getPackage().getName(); + if ((boolean) MODULE_IS_OPEN_UNCONDITIONALLY_METHOD_HANDLE.invokeWithArguments(responseModule, + packageName) + || (boolean) MODULE_IS_OPEN_TO_OTHER_MODULE_METHOD_HANDLE.invokeWithArguments(responseModule, + packageName, CORE_MODULE)) { + MODULE_ADD_READS_METHOD_HANDLE.invokeWithArguments(CORE_MODULE, responseModule); + return performSafePrivateLookupIn(targetClass); + } - // Otherwise, return the public lookup as there are no specialty ways to access the other module. - return MethodHandles.publicLookup(); + // Otherwise, return the public lookup as there are no specialty ways to access the other module. + return MethodHandles.publicLookup(); + } else { + return (MethodHandles.Lookup) JDK_INTERNAL_PRIVATE_LOOKUP_IN_CONSTRUCTOR.invoke(targetClass); + } } catch (Throwable throwable) { // invoke(Class targetClass, boolean } private static MethodHandles.Lookup performSafePrivateLookupIn(Class targetClass) throws Throwable { - return MethodHandles.privateLookupIn(targetClass, LOOKUP); + // MethodHandles::privateLookupIn() throws SecurityException if denied by the security manager + return (MethodHandles.Lookup) METHOD_HANDLES_PRIVATE_LOOKUP_IN_METHOD_HANDLE.invokeExact(targetClass, LOOKUP); } } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/UrlRedactionUtil.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/UrlRedactionUtil.java index ad309692634f..34dff56531d7 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/UrlRedactionUtil.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/UrlRedactionUtil.java @@ -3,7 +3,7 @@ package io.clientcore.core.implementation; -import io.clientcore.core.implementation.util.ImplUtils; +import io.clientcore.core.implementation.utils.ImplUtils; import java.net.URI; import java.util.Locale; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/ContentType.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/ContentType.java similarity index 94% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/ContentType.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/ContentType.java index ecbe00187270..b505e3250f5d 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/models/ContentType.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/ContentType.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.http.models; +package io.clientcore.core.implementation.http; /** * The different values that commonly used for Content-Type header. diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/HttpPipelineCallState.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/HttpPipelineCallState.java index ac170c03597a..3861ac351e6f 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/HttpPipelineCallState.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/HttpPipelineCallState.java @@ -11,7 +11,7 @@ /** * Represents a class responsible for maintaining information related to request-specific context and pipeline data. */ -public class HttpPipelineCallState implements Cloneable { +public class HttpPipelineCallState { private static final ClientLogger LOGGER = new ClientLogger(HttpPipelineCallState.class); private final HttpPipeline pipeline; private final HttpRequest httpRequest; @@ -76,12 +76,17 @@ public HttpRequest getHttpRequest() { return this.httpRequest; } - @SuppressWarnings("MethodDoesntCallSuperMethod") - @Override - public HttpPipelineCallState clone() { - HttpPipelineCallState cloned = new HttpPipelineCallState(this.pipeline, this.httpRequest); - cloned.currentPolicyIndex = this.currentPolicyIndex; + /** + * Copies the current state of the {@link HttpPipelineCallState}. + *

        + * This method must be used when a re-request is made in the pipeline. + * + * @return A new instance of this pipeline call state. + */ + public HttpPipelineCallState copy() { + HttpPipelineCallState copy = new HttpPipelineCallState(this.pipeline, this.httpRequest); + copy.currentPolicyIndex = this.currentPolicyIndex; - return cloned; + return copy; } } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/HttpResponseAccessHelper.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/HttpResponseAccessHelper.java deleted file mode 100644 index 1ae0883f0859..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/HttpResponseAccessHelper.java +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.implementation.http; - -import io.clientcore.core.http.models.HttpResponse; -import io.clientcore.core.util.binarydata.BinaryData; - -import java.util.function.Function; - -/** - * This class is used to access internal methods on {@link HttpResponse}. - */ -public final class HttpResponseAccessHelper { - private static HttpResponseAccessor accessor; - - /** - * Type defining the methods to access the internal methods on {@link HttpResponse}. - */ - public interface HttpResponseAccessor { - /** - * Sets a {@link HttpResponse}'s value. - * - * @param httpResponse The {@link HttpResponse} to set the value of. - * @param value The {@link Object value} to set. - * - * @return The modified {@link HttpResponse}. - */ - HttpResponse setValue(HttpResponse httpResponse, Object value); - - /** - * Sets a {@link HttpResponse}'s body. - * - * @param httpResponse The {@link HttpResponse} to set the body of. - * @param body The {@link BinaryData body} to set. - * - * @return The modified {@link HttpResponse}. - */ - HttpResponse setBody(HttpResponse httpResponse, BinaryData body); - - /** - * Sets a function to deserialize the body of an {@link HttpResponse}. - * - * @param httpResponse The {@link HttpResponse} to set the body deserializer of. - * @param bodyDeserializer The function that will deserialize the body of the response. - * - * @return The modified {@link HttpResponse}. - */ - HttpResponse setBodyDeserializer(HttpResponse httpResponse, - Function bodyDeserializer); - } - - /** - * Sets a {@link HttpResponse}'s {@link Object value}. - * - * @param httpResponse The {@link HttpResponse} to set the value of. - * @param value The {@link Object value} to set. - * - * @return The modified {@link HttpResponse}. - */ - public static HttpResponse setValue(HttpResponse httpResponse, Object value) { - return accessor.setValue(httpResponse, value); - } - - /** - * Sets a {@link HttpResponse}'s {@link BinaryData body}. - * - * @param httpResponse The {@link HttpResponse} to set the body of. - * @param body The {@link BinaryData body} to set. - * - * @return The modified {@link HttpResponse}. - */ - public static HttpResponse setBody(HttpResponse httpResponse, BinaryData body) { - return accessor.setBody(httpResponse, body); - } - - /** - * Sets a function to deserialize the body of an {@link HttpResponse}. - * - * @param httpResponse The {@link HttpResponse} to set the body deserializer of. - * @param bodyDeserializer The function that will deserialize the body of the response. - * - * @return The modified {@link HttpResponse}. - */ - public static HttpResponse setBodyDeserializer(HttpResponse httpResponse, - Function bodyDeserializer) { - return accessor.setBodyDeserializer(httpResponse, bodyDeserializer); - } - - /** - * Sets the {@link HttpResponseAccessor}. - * - * @param accessor The {@link HttpResponseAccessor}. - */ - public static void setAccessor(HttpResponseAccessor accessor) { - HttpResponseAccessHelper.accessor = accessor; - } - - private HttpResponseAccessHelper() { - } -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/UnexpectedExceptionInformation.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/UnexpectedExceptionInformation.java index 9e14e4bf6f86..b2c8deb70cd4 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/UnexpectedExceptionInformation.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/UnexpectedExceptionInformation.java @@ -3,25 +3,20 @@ package io.clientcore.core.implementation.http; -import io.clientcore.core.http.exception.HttpExceptionType; - /** * Contains the information needed to generate an exception type to be thrown or returned when a REST API returns an * error status code. */ public class UnexpectedExceptionInformation { private final Class exceptionBodyClass; - private final HttpExceptionType exceptionType; /** * Creates an {@link UnexpectedExceptionInformation} object with the given exception type and expected response * body. * - * @param exceptionType The type of exception to be thrown. * @param exceptionBodyClass The expected response body class. */ - public UnexpectedExceptionInformation(HttpExceptionType exceptionType, Class exceptionBodyClass) { - this.exceptionType = exceptionType; + public UnexpectedExceptionInformation(Class exceptionBodyClass) { this.exceptionBodyClass = exceptionBodyClass == null ? Object.class : exceptionBodyClass; } @@ -33,13 +28,4 @@ public UnexpectedExceptionInformation(HttpExceptionType exceptionType, Class public Class getExceptionBodyClass() { return exceptionBodyClass; } - - /** - * Get the exception type. - * - * @return The exception type. - */ - public HttpExceptionType getExceptionType() { - return exceptionType; - } } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/client/GlobalJdkHttpClient.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/client/GlobalJdkHttpClient.java new file mode 100644 index 000000000000..eb3b54cb98e3 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/client/GlobalJdkHttpClient.java @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.implementation.http.client; + +import io.clientcore.core.http.client.HttpClient; +import io.clientcore.core.http.client.JdkHttpClientBuilder; + +/** + * An enum containing the global {@link JdkHttpClient}. + */ +public enum GlobalJdkHttpClient { + HTTP_CLIENT(new JdkHttpClientBuilder().build()); + + private final HttpClient httpClient; + + GlobalJdkHttpClient(HttpClient httpClient) { + this.httpClient = httpClient; + } + + /** + * Get the global {@link JdkHttpClient} instance. + * + * @return The global {@link JdkHttpClient} instance. + */ + public HttpClient getHttpClient() { + return httpClient; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/client/JdkHttpClient.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/client/JdkHttpClient.java new file mode 100644 index 000000000000..673695dbeae4 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/client/JdkHttpClient.java @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.implementation.http.client; + +import io.clientcore.core.http.client.HttpClient; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.models.binarydata.BinaryData; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.time.Duration; +import java.util.Set; + +/** + * HttpClient implementation using {@link HttpURLConnection} to send requests and receive responses. + */ +public final class JdkHttpClient implements HttpClient { + private static final ClientLogger LOGGER = new ClientLogger(JdkHttpClient.class); + + private static final String ERROR_MESSAGE = "It is recommended that libraries be deployed on the latest LTS " + + "version of Java, however the Java client will support down to Java 8. In the case where the client is to " + + "operate on Java versions below Java 11, it is required to include additional dependencies. Usage of " + + "DefaultHttpClient is only available when using Java 12 or higher. For support with Java 11 or lower, " + + "include a dependency on io.clientcore:http-okhttp3."; + + /** + * Creates an instance of DefaultHttpClient. + * + * @param httpClient The wrapped http client. + * @param restrictedHeaders The set of headers that are restricted from being set by the user. + * @param writeTimeout The write timeout. + * @param responseTimeout The response timeout. + * @param readTimeout The read timeout. + * @throws UnsupportedOperationException if the client is not running on Java 12 or higher. + */ + public JdkHttpClient(Object httpClient, Set restrictedHeaders, Duration writeTimeout, + Duration responseTimeout, Duration readTimeout) { + throw LOGGER.logThrowableAsError(new UnsupportedOperationException(ERROR_MESSAGE)); + } + + @Override + public Response send(HttpRequest request) throws IOException { + throw LOGGER.logThrowableAsError(new UnsupportedOperationException(ERROR_MESSAGE)); + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/client/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/client/package-info.java new file mode 100644 index 000000000000..7feebd67dcd9 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/client/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing the HTTP client implementations. + */ +package io.clientcore.core.implementation.http.client; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/rest/PercentEscaper.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/rest/PercentEscaper.java index 566def922c83..4c09008732d0 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/rest/PercentEscaper.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/rest/PercentEscaper.java @@ -7,7 +7,7 @@ import java.util.Arrays; -import static io.clientcore.core.implementation.util.ImplUtils.isNullOrEmpty; +import static io.clientcore.core.utils.CoreUtils.isNullOrEmpty; /** * An escaper that escapes URI data through percent encoding. diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/rest/ResponseExceptionConstructorCache.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/rest/ResponseExceptionConstructorCache.java index 2a6c4ff9d13f..35b221bdc4ae 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/rest/ResponseExceptionConstructorCache.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/rest/ResponseExceptionConstructorCache.java @@ -3,7 +3,7 @@ package io.clientcore.core.implementation.http.rest; -import io.clientcore.core.http.exception.HttpResponseException; +import io.clientcore.core.http.models.HttpResponseException; import io.clientcore.core.http.models.Response; import io.clientcore.core.implementation.ReflectiveInvoker; import io.clientcore.core.instrumentation.logging.ClientLogger; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/rest/RestProxyImpl.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/rest/RestProxyImpl.java index 4399f4992c04..0156bbe23e78 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/rest/RestProxyImpl.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/rest/RestProxyImpl.java @@ -3,14 +3,11 @@ package io.clientcore.core.implementation.http.rest; -import io.clientcore.core.http.exception.HttpExceptionType; -import io.clientcore.core.http.exception.HttpResponseException; -import io.clientcore.core.http.models.ContentType; import io.clientcore.core.http.models.HttpHeaderName; import io.clientcore.core.http.models.HttpHeaders; import io.clientcore.core.http.models.HttpMethod; import io.clientcore.core.http.models.HttpRequest; -import io.clientcore.core.http.models.HttpResponse; +import io.clientcore.core.http.models.HttpResponseException; import io.clientcore.core.http.models.RequestOptions; import io.clientcore.core.http.models.Response; import io.clientcore.core.http.models.ResponseBodyMode; @@ -18,18 +15,18 @@ import io.clientcore.core.implementation.ReflectionSerializable; import io.clientcore.core.implementation.ReflectiveInvoker; import io.clientcore.core.implementation.TypeUtil; -import io.clientcore.core.implementation.http.HttpResponseAccessHelper; +import io.clientcore.core.implementation.http.ContentType; import io.clientcore.core.implementation.http.UnexpectedExceptionInformation; import io.clientcore.core.implementation.http.serializer.CompositeSerializer; import io.clientcore.core.implementation.http.serializer.MalformedValueException; -import io.clientcore.core.implementation.util.Base64Uri; -import io.clientcore.core.implementation.util.ImplUtils; -import io.clientcore.core.implementation.util.UriBuilder; import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.util.binarydata.BinaryData; -import io.clientcore.core.util.binarydata.InputStreamBinaryData; -import io.clientcore.core.util.serializer.ObjectSerializer; -import io.clientcore.core.util.serializer.SerializationFormat; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.models.binarydata.InputStreamBinaryData; +import io.clientcore.core.serialization.ObjectSerializer; +import io.clientcore.core.serialization.SerializationFormat; +import io.clientcore.core.utils.Base64Uri; +import io.clientcore.core.utils.CoreUtils; +import io.clientcore.core.utils.UriBuilder; import java.io.IOException; import java.io.InputStream; @@ -41,7 +38,6 @@ import java.nio.charset.StandardCharsets; import java.util.Arrays; -import static io.clientcore.core.http.models.ResponseBodyMode.DESERIALIZE; import static io.clientcore.core.implementation.http.serializer.HttpResponseBodyDecoder.decodeByteArray; public class RestProxyImpl { @@ -96,7 +92,7 @@ public final Object invoke(Object proxy, RequestOptions options, SwaggerMethodPa request.setBody(RestProxyImpl.validateLength(request)); } - final Response response = httpPipeline.send(request); + final Response response = httpPipeline.send(request); return handleRestReturnType(response, methodParser, methodParser.getReturnType(), serializer); } catch (IOException e) { @@ -204,8 +200,8 @@ private static HttpRequest createHttpRequest(SwaggerMethodParser methodParser, C methodParser.setEncodedQueryParameters(args, uriBuilder, serializer); final URI uri = uriBuilder.toUri(); - final HttpRequest request - = configRequest(new HttpRequest(methodParser.getHttpMethod(), uri), methodParser, serializer, args); + final HttpRequest request = configRequest(new HttpRequest().setMethod(methodParser.getHttpMethod()).setUri(uri), + methodParser, serializer, args); // Headers from Swagger method arguments always take precedence over inferred headers from body types HttpHeaders httpHeaders = request.getHeaders(); @@ -271,8 +267,8 @@ private static HttpRequest configRequest(HttpRequest request, SwaggerMethodParse } /** - * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has 'disallowed status - * code' OR (2) emits provided response if it's status code ia allowed. + * Throws an exception if the provided response {@code decodedResponse} has 'disallowed status code' OR returns a + * response that has 'allowed status code'. * *

        'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser or is in the int[] * of additional allowed status codes.

        @@ -282,7 +278,7 @@ private static HttpRequest configRequest(HttpRequest request, SwaggerMethodParse * the HTTP request. * @return The decodedResponse. */ - private static Response ensureExpectedStatus(Response response, SwaggerMethodParser methodParser, + private static Response ensureExpectedStatus(Response response, SwaggerMethodParser methodParser, CompositeSerializer serializer) { int responseStatusCode = response.getStatusCode(); @@ -292,14 +288,14 @@ private static Response ensureExpectedStatus(Response response, SwaggerMet } // Otherwise, the response wasn't successful and the error object needs to be parsed. - if (response.getBody() == null || response.getBody().toBytes().length == 0) { + if (response.getValue() == null || response.getValue().toBytes().length == 0) { // No body, create an exception response with an empty body. throw instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), response, null, null); } else { // Create an exception response containing the decoded response body. throw instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), response, - response.getBody(), decodeByteArray(response.getBody(), response, serializer, methodParser)); + response.getValue(), decodeByteArray(response.getValue(), response, serializer, methodParser)); } } @@ -313,8 +309,8 @@ private static Response ensureExpectedStatus(Response response, SwaggerMet * @return The {@link HttpResponseException} created from the provided details. */ private static HttpResponseException instantiateUnexpectedException( - UnexpectedExceptionInformation unexpectedExceptionInformation, Response response, BinaryData responseBody, - Object responseDecodedBody) { + UnexpectedExceptionInformation unexpectedExceptionInformation, Response response, + BinaryData responseBody, Object responseDecodedBody) { StringBuilder exceptionMessage = new StringBuilder("Status code ").append(response.getStatusCode()).append(", "); @@ -339,16 +335,13 @@ private static HttpResponseException instantiateUnexpectedException( || responseDecodedBody instanceof MalformedValueException || responseDecodedBody instanceof IllegalStateException) { - return new HttpResponseException(exceptionMessage.toString(), response, null, - (Throwable) responseDecodedBody); + return new HttpResponseException(exceptionMessage.toString(), response, (Throwable) responseDecodedBody); } - HttpExceptionType exceptionType = unexpectedExceptionInformation.getExceptionType(); - - return new HttpResponseException(exceptionMessage.toString(), response, exceptionType, responseDecodedBody); + return new HttpResponseException(exceptionMessage.toString(), response, responseDecodedBody); } - private static Object handleRestResponseReturnType(Response response, SwaggerMethodParser methodParser, + private static Object handleRestResponseReturnType(Response response, SwaggerMethodParser methodParser, Type entityType, CompositeSerializer serializer) { if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { final Type bodyType = TypeUtil.getRestResponseBodyType(entityType); @@ -360,7 +353,7 @@ private static Object handleRestResponseReturnType(Response response, Swagger throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); } - return createResponseIfNecessary(response, entityType, null); + return new Response(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); } else { ResponseBodyMode responseBodyMode = null; RequestOptions requestOptions = response.getRequest().getRequestOptions(); @@ -369,26 +362,14 @@ private static Object handleRestResponseReturnType(Response response, Swagger responseBodyMode = requestOptions.getResponseBodyMode(); } - if (responseBodyMode == DESERIALIZE) { - HttpResponseAccessHelper.setValue((HttpResponse) response, - handleResponseBody(response, methodParser, bodyType, response.getBody(), serializer)); - } else { - HttpResponseAccessHelper.setBodyDeserializer((HttpResponse) response, - (body) -> handleResponseBody(response, methodParser, bodyType, body, serializer)); - } - - Response responseToReturn = createResponseIfNecessary(response, entityType, response.getBody()); - - if (responseToReturn == null) { - return createResponseIfNecessary(response, entityType, null); - } - - return responseToReturn; + // TODO (alzimmer): Need a way to support deferred deserialization. + return new Response<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), + handleResponseBody(response, methodParser, bodyType, response.getValue(), serializer)); } } else { // When not handling a Response subtype, we need to eagerly read the response body to construct the correct // return type. - return handleResponseBody(response, methodParser, entityType, response.getBody(), serializer); + return handleResponseBody(response, methodParser, entityType, response.getValue(), serializer); } } @@ -414,8 +395,8 @@ private static Response createResponseIfNecessary(Response response, Type } } - private static Object handleResponseBody(Response response, SwaggerMethodParser methodParser, Type entityType, - BinaryData responseBody, CompositeSerializer serializer) { + private static Object handleResponseBody(Response response, SwaggerMethodParser methodParser, + Type entityType, BinaryData responseBody, CompositeSerializer serializer) { final int responseStatusCode = response.getStatusCode(); final HttpMethod httpMethod = methodParser.getHttpMethod(); final Type returnValueWireType = methodParser.getReturnValueWireType(); @@ -459,8 +440,8 @@ private static Object handleResponseBody(Response response, SwaggerMethodPars * @param returnType The type of value that will be returned. * @return The deserialized result. */ - private static Object handleRestReturnType(Response response, SwaggerMethodParser methodParser, Type returnType, - CompositeSerializer serializer) { + private static Object handleRestReturnType(Response response, SwaggerMethodParser methodParser, + Type returnType, CompositeSerializer serializer) { final Response expectedResponse = ensureExpectedStatus(response, methodParser, serializer); final Object result; @@ -531,7 +512,7 @@ public static SerializationFormat serializationFormatFromContentType(HttpHeaders } String contentType = headers.getValue(HttpHeaderName.CONTENT_TYPE); - if (ImplUtils.isNullOrEmpty(contentType)) { + if (CoreUtils.isNullOrEmpty(contentType)) { // When in doubt, JSON! return SerializationFormat.JSON; } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/rest/SwaggerInterfaceParser.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/rest/SwaggerInterfaceParser.java index b68e67dea561..3ec74964785b 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/rest/SwaggerInterfaceParser.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/rest/SwaggerInterfaceParser.java @@ -3,7 +3,7 @@ package io.clientcore.core.implementation.http.rest; -import io.clientcore.core.annotation.ServiceInterface; +import io.clientcore.core.annotations.ServiceInterface; import java.lang.reflect.Method; import java.util.Map; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/rest/SwaggerMethodParser.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/rest/SwaggerMethodParser.java index cd9d9a59a828..4aea4fce5ef3 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/rest/SwaggerMethodParser.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/rest/SwaggerMethodParser.java @@ -4,16 +4,15 @@ package io.clientcore.core.implementation.http.rest; import io.clientcore.core.http.RestProxy; -import io.clientcore.core.http.annotation.BodyParam; -import io.clientcore.core.http.annotation.FormParam; -import io.clientcore.core.http.annotation.HeaderParam; -import io.clientcore.core.http.annotation.HostParam; -import io.clientcore.core.http.annotation.HttpRequestInformation; -import io.clientcore.core.http.annotation.PathParam; -import io.clientcore.core.http.annotation.QueryParam; -import io.clientcore.core.http.annotation.UnexpectedResponseExceptionDetail; -import io.clientcore.core.http.exception.HttpExceptionType; -import io.clientcore.core.http.models.ContentType; +import io.clientcore.core.http.annotations.BodyParam; +import io.clientcore.core.http.annotations.FormParam; +import io.clientcore.core.http.annotations.HeaderParam; +import io.clientcore.core.http.annotations.HostParam; +import io.clientcore.core.http.annotations.HttpRequestInformation; +import io.clientcore.core.http.annotations.PathParam; +import io.clientcore.core.http.annotations.QueryParam; +import io.clientcore.core.http.annotations.UnexpectedResponseExceptionDetail; +import io.clientcore.core.implementation.http.ContentType; import io.clientcore.core.http.models.HttpHeaderName; import io.clientcore.core.http.models.HttpHeaders; import io.clientcore.core.http.models.HttpMethod; @@ -25,13 +24,13 @@ import io.clientcore.core.implementation.http.UnexpectedExceptionInformation; import io.clientcore.core.implementation.http.serializer.CompositeSerializer; import io.clientcore.core.implementation.http.serializer.HttpResponseDecodeData; -import io.clientcore.core.implementation.util.Base64Uri; -import io.clientcore.core.implementation.util.DateTimeRfc1123; -import io.clientcore.core.implementation.util.UriBuilder; import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.util.ExpandableEnum; -import io.clientcore.core.util.binarydata.BinaryData; -import io.clientcore.core.util.serializer.SerializationFormat; +import io.clientcore.core.utils.Base64Uri; +import io.clientcore.core.utils.DateTimeRfc1123; +import io.clientcore.core.utils.ExpandableEnum; +import io.clientcore.core.utils.UriBuilder; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.serialization.SerializationFormat; import java.io.IOException; import java.io.InputStream; @@ -57,7 +56,7 @@ import java.util.stream.Collectors; import static io.clientcore.core.implementation.TypeUtil.typeImplementsInterface; -import static io.clientcore.core.implementation.util.ImplUtils.isNullOrEmpty; +import static io.clientcore.core.utils.CoreUtils.isNullOrEmpty; /** * This class contains the metadata of a {@link Method} contained in a Swagger interface used to make REST API calls in @@ -71,7 +70,7 @@ public class SwaggerMethodParser implements HttpResponseDecodeData { // to search the raw value on each call. private final String rawHost; private final String fullyQualifiedMethodName; - private final ClientLogger methodLogger; + private final ClientLogger logger; private final HttpMethod httpMethod; private final String relativePath; private final Map> queryParams = new LinkedHashMap<>(); @@ -109,7 +108,7 @@ public SwaggerMethodParser(Method swaggerMethod) { this.rawHost = interfaceParser.getHost(); final Class swaggerInterface = swaggerMethod.getDeclaringClass(); fullyQualifiedMethodName = swaggerInterface.getName() + "." + swaggerMethod.getName(); - methodLogger = new ClientLogger(fullyQualifiedMethodName); + logger = new ClientLogger(fullyQualifiedMethodName); if (!swaggerMethod.isAnnotationPresent(HttpRequestInformation.class)) { // Should this also check whether there are multiple HTTP method annotations as well? @@ -308,7 +307,7 @@ public String getFullyQualifiedMethodName() { * @return The {@link ClientLogger} that will be used to log during the request and response. */ public ClientLogger getMethodLogger() { - return methodLogger; + return logger; } /** @@ -727,9 +726,8 @@ private Map processUnexpectedResponseEx HashMap exceptionHashMap = new HashMap<>(); for (UnexpectedResponseExceptionDetail exceptionAnnotation : unexpectedResponseExceptionDetails) { - UnexpectedExceptionInformation exception = new UnexpectedExceptionInformation( - HttpExceptionType.fromString(exceptionAnnotation.exceptionTypeName()), - exceptionAnnotation.exceptionBodyClass()); + UnexpectedExceptionInformation exception + = new UnexpectedExceptionInformation(exceptionAnnotation.exceptionBodyClass()); if (exceptionAnnotation.statusCode().length == 0) { defaultException = exception; @@ -741,7 +739,7 @@ private Map processUnexpectedResponseEx } if (defaultException == null) { - defaultException = new UnexpectedExceptionInformation(null, null); + defaultException = new UnexpectedExceptionInformation(null); } return exceptionHashMap; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/serializer/CompositeSerializer.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/serializer/CompositeSerializer.java index 87289f3c6dbe..0f3f24a02a28 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/serializer/CompositeSerializer.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/serializer/CompositeSerializer.java @@ -3,8 +3,8 @@ package io.clientcore.core.implementation.http.serializer; import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.util.serializer.ObjectSerializer; -import io.clientcore.core.util.serializer.SerializationFormat; +import io.clientcore.core.serialization.ObjectSerializer; +import io.clientcore.core.serialization.SerializationFormat; import java.io.IOException; import java.io.InputStream; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/serializer/HttpResponseBodyDecoder.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/serializer/HttpResponseBodyDecoder.java index b517fc59c78b..a6a6fde948a8 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/serializer/HttpResponseBodyDecoder.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/serializer/HttpResponseBodyDecoder.java @@ -3,17 +3,17 @@ package io.clientcore.core.implementation.http.serializer; -import io.clientcore.core.http.annotation.HttpRequestInformation; -import io.clientcore.core.http.exception.HttpResponseException; +import io.clientcore.core.http.annotations.HttpRequestInformation; import io.clientcore.core.http.models.HttpMethod; +import io.clientcore.core.http.models.HttpResponseException; import io.clientcore.core.http.models.Response; import io.clientcore.core.implementation.TypeUtil; import io.clientcore.core.implementation.http.rest.RestProxyImpl; -import io.clientcore.core.implementation.util.Base64Uri; -import io.clientcore.core.implementation.util.DateTimeRfc1123; import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.util.binarydata.BinaryData; -import io.clientcore.core.util.serializer.SerializationFormat; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.serialization.SerializationFormat; +import io.clientcore.core.utils.Base64Uri; +import io.clientcore.core.utils.DateTimeRfc1123; import java.io.IOException; import java.lang.reflect.InvocationTargetException; @@ -46,7 +46,7 @@ public final class HttpResponseBodyDecoder { * @throws HttpResponseException If the body cannot be decoded. * @throws RuntimeException If the body cannot be decoded. */ - public static Object decodeByteArray(BinaryData body, Response response, CompositeSerializer serializer, + public static Object decodeByteArray(BinaryData body, Response response, CompositeSerializer serializer, HttpResponseDecodeData decodeData) { ensureRequestSet(response); @@ -90,13 +90,13 @@ public static Object decodeByteArray(BinaryData body, Response response, Comp } try { - return deserializeBody(body == null ? response.getBody() : body, + return deserializeBody(body == null ? response.getValue() : body, extractEntityTypeFromReturnType(decodeData), decodeData.getReturnValueWireType(), RestProxyImpl.serializationFormatFromContentType(response.getHeaders()), serializer); } catch (MalformedValueException e) { - throw new HttpResponseException("HTTP response has a malformed body.", response, null, e); + throw new HttpResponseException("HTTP response has a malformed body.", response, e); } catch (IOException e) { - throw new HttpResponseException("Deserialization failed.", response, null, e); + throw new HttpResponseException("Deserialization failed.", response, e); } } } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/serializer/HttpResponseDecodeData.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/serializer/HttpResponseDecodeData.java index 26c5cc5db92a..3a5fa8dd16c2 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/serializer/HttpResponseDecodeData.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/http/serializer/HttpResponseDecodeData.java @@ -3,7 +3,7 @@ package io.clientcore.core.implementation.http.serializer; -import io.clientcore.core.http.exception.HttpResponseException; +import io.clientcore.core.http.models.HttpResponseException; import io.clientcore.core.implementation.http.UnexpectedExceptionInformation; import io.clientcore.core.implementation.http.rest.SwaggerMethodParser; @@ -69,7 +69,7 @@ default Type getReturnValueWireType() { * @return The {@link UnexpectedExceptionInformation} to generate an exception to throw or return. */ default UnexpectedExceptionInformation getUnexpectedException(int code) { - return new UnexpectedExceptionInformation(null, null); + return new UnexpectedExceptionInformation(null); } /** diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/AttributeKeys.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/AttributeKeys.java index e04b0f6d01f1..5cd617be8d30 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/AttributeKeys.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/AttributeKeys.java @@ -148,6 +148,13 @@ public final class AttributeKeys { */ public static final String HTTP_RESPONSE_BODY_CONTENT_KEY = "http.request.body.content"; + /** + * Key representing operation name. The value should be a string. + * When instrumenting client libraries, it should be language-agnostic operation name provided in typespec + * or swagger. + */ + public static final String OPERATION_NAME_KEY = "operation.name"; + /** * Key representing maximum number of redirects or retries. It's reported when the number of redirects or retries * was exhausted. diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/DefaultLogger.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/DefaultLogger.java index df717ff5a92b..4283d2d4679e 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/DefaultLogger.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/DefaultLogger.java @@ -3,9 +3,8 @@ package io.clientcore.core.implementation.instrumentation; -import io.clientcore.core.implementation.util.EnvironmentConfiguration; -import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.util.configuration.Configuration; +import io.clientcore.core.instrumentation.logging.LogLevel; +import io.clientcore.core.utils.configuration.Configuration; import java.io.PrintStream; import java.io.PrintWriter; @@ -14,8 +13,6 @@ import java.time.LocalDateTime; import java.time.temporal.ChronoField; -import static io.clientcore.core.instrumentation.logging.ClientLogger.LogLevel; - /** * This class is an internal implementation of slf4j logger. */ @@ -64,7 +61,7 @@ public DefaultLogger(String className) { * @param logLocation The location to log the messages. * @param logLevel The log level supported by the logger. */ - public DefaultLogger(String className, PrintStream logLocation, ClientLogger.LogLevel logLevel) { + public DefaultLogger(String className, PrintStream logLocation, LogLevel logLevel) { this.classPath = className; this.logLocation = logLocation; this.level = logLevel; @@ -219,7 +216,6 @@ private static void zeroPad(int value, byte[] bytes, int index) { private static LogLevel fromEnvironment() { // LogLevel is so basic, we can't use configuration to read it (since Configuration needs to log too) - String level = EnvironmentConfiguration.getGlobalConfiguration().get(Configuration.PROPERTY_LOG_LEVEL); - return LogLevel.fromString(level); + return LogLevel.fromString(Configuration.getGlobalConfiguration().get(Configuration.LOG_LEVEL)); } } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/InstrumentationUtils.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/InstrumentationUtils.java new file mode 100644 index 000000000000..e3c9ceed3a84 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/InstrumentationUtils.java @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.implementation.instrumentation; + +import io.clientcore.core.instrumentation.LibraryInstrumentationOptions; +import io.clientcore.core.instrumentation.metrics.DoubleHistogram; +import io.clientcore.core.instrumentation.metrics.Meter; + +import java.net.URI; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +/** + * Utility class for instrumentation. + */ +public final class InstrumentationUtils { + // Histogram boundaries are optimized for common latency ranges (in seconds). They are + // provided as advice at metric creation time and could be overriden by the user application via + // OTel configuration. + // TODO (limolkova): document client core metric conventions along with logical operation histogram boundaries. + private static final List DURATION_BOUNDARIES_ADVICE = Collections.unmodifiableList( + Arrays.asList(0.005d, 0.01d, 0.025d, 0.05d, 0.075d, 0.1d, 0.25d, 0.5d, 0.75d, 1d, 2.5d, 5d, 7.5d, 10d)); + + public static final LibraryInstrumentationOptions UNKNOWN_LIBRARY_OPTIONS + = new LibraryInstrumentationOptions("unknown"); + + /** + * Creates a new {@link DoubleHistogram} for measuring the duration of client operations. + * @param libraryName the name of the library - corresponds to artifact id and does not include group id + * @param meter the meter to use for creating the histogram + * @return a new {@link DoubleHistogram} for measuring the duration of client operations + */ + public static DoubleHistogram createOperationDurationHistogram(String libraryName, Meter meter) { + if (meter.isEnabled() && libraryName != null) { + String metricDescription = "Duration of client operation"; + String metricName = libraryName.replace("-", ".") + ".client.operation.duration"; + return meter.createDoubleHistogram(metricName, metricDescription, "s", DURATION_BOUNDARIES_ADVICE); + } + + return NoopMeter.NOOP_LONG_HISTOGRAM; + } + + /** + * Does the best effort to capture the server port with minimum perf overhead. + * If port is not set, we check scheme for "http" and "https" (case-sensitive). + * If scheme is not one of those, returns -1. + * + * @param uri request URI + * @return server port + */ + public static int getServerPort(URI uri) { + int port = uri.getPort(); + if (port == -1) { + switch (uri.getScheme()) { + case "http": + return 80; + + case "https": + return 443; + + default: + break; + } + } + return port; + } + + private InstrumentationUtils() { + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/NoopAttributes.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/NoopAttributes.java new file mode 100644 index 000000000000..705d42f9d71a --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/NoopAttributes.java @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.implementation.instrumentation; + +import io.clientcore.core.instrumentation.InstrumentationAttributes; + +import java.util.Objects; + +/** + * Noop implementation of {@link InstrumentationAttributes}. + */ +public final class NoopAttributes implements InstrumentationAttributes { + public static final NoopAttributes INSTANCE = new NoopAttributes(); + + /** + * {@inheritDoc} + */ + @Override + public InstrumentationAttributes put(String key, Object value) { + Objects.requireNonNull(key, "'key' cannot be null."); + Objects.requireNonNull(value, "'value' cannot be null."); + + return this; + } + + private NoopAttributes() { + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/NoopInstrumentationContext.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/NoopInstrumentationContext.java new file mode 100644 index 000000000000..05b5a6229b7f --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/NoopInstrumentationContext.java @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.implementation.instrumentation; + +import io.clientcore.core.instrumentation.InstrumentationContext; +import io.clientcore.core.instrumentation.tracing.Span; + +/** + * No-op implementation of {@link InstrumentationContext}. + */ +public final class NoopInstrumentationContext implements InstrumentationContext { + public static final NoopInstrumentationContext INSTANCE = new NoopInstrumentationContext(); + + private NoopInstrumentationContext() { + } + + @Override + public String getTraceId() { + return null; + } + + @Override + public String getSpanId() { + return null; + } + + @Override + public String getTraceFlags() { + return null; + } + + @Override + public boolean isValid() { + return false; + } + + @Override + public Span getSpan() { + return Span.noop(); + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/NoopMeter.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/NoopMeter.java new file mode 100644 index 000000000000..b611c81b1368 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/NoopMeter.java @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.implementation.instrumentation; + +import io.clientcore.core.instrumentation.InstrumentationAttributes; +import io.clientcore.core.instrumentation.InstrumentationContext; +import io.clientcore.core.instrumentation.metrics.DoubleHistogram; +import io.clientcore.core.instrumentation.metrics.LongCounter; +import io.clientcore.core.instrumentation.metrics.Meter; + +import java.util.List; +import java.util.Objects; + +/** + * {@inheritDoc} + */ +public final class NoopMeter implements Meter { + public static final Meter INSTANCE = new NoopMeter(); + public static final DoubleHistogram NOOP_LONG_HISTOGRAM = new DoubleHistogram() { + @Override + public void record(double value, InstrumentationAttributes attributes, InstrumentationContext context) { + Objects.requireNonNull(attributes, "'attributes' cannot be null."); + } + + @Override + public boolean isEnabled() { + return false; + } + }; + + private static final LongCounter NOOP_LONG_COUNTER = new LongCounter() { + @Override + public void add(long value, InstrumentationAttributes attributes, InstrumentationContext context) { + Objects.requireNonNull(attributes, "'attributes' cannot be null."); + } + + @Override + public boolean isEnabled() { + return false; + } + }; + + private NoopMeter() { + } + + /** + * {@inheritDoc} + */ + @Override + public DoubleHistogram createDoubleHistogram(String name, String description, String unit, + List bucketBoundaries) { + Objects.requireNonNull(name, "'name' cannot be null."); + Objects.requireNonNull(description, "'description' cannot be null."); + Objects.requireNonNull(unit, "'unit' cannot be null."); + return NOOP_LONG_HISTOGRAM; + } + + /** + * {@inheritDoc} + */ + @Override + public LongCounter createLongCounter(String name, String description, String unit) { + Objects.requireNonNull(name, "'name' cannot be null."); + Objects.requireNonNull(description, "'description' cannot be null."); + Objects.requireNonNull(unit, "'unit' cannot be null."); + return NOOP_LONG_COUNTER; + } + + /** + * {@inheritDoc} + */ + @Override + public LongCounter createLongUpDownCounter(String name, String description, String unit) { + Objects.requireNonNull(name, "'name' cannot be null."); + Objects.requireNonNull(description, "'description' cannot be null."); + Objects.requireNonNull(unit, "'unit' cannot be null."); + return NOOP_LONG_COUNTER; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isEnabled() { + return false; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/Slf4jLoggerShim.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/Slf4jLoggerShim.java index 7d7074724d37..74ab8cc1125d 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/Slf4jLoggerShim.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/Slf4jLoggerShim.java @@ -5,12 +5,12 @@ import io.clientcore.core.implementation.ReflectionUtils; import io.clientcore.core.implementation.ReflectiveInvoker; -import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.instrumentation.logging.LogLevel; -import static io.clientcore.core.instrumentation.logging.ClientLogger.LogLevel.ERROR; -import static io.clientcore.core.instrumentation.logging.ClientLogger.LogLevel.INFORMATIONAL; -import static io.clientcore.core.instrumentation.logging.ClientLogger.LogLevel.VERBOSE; -import static io.clientcore.core.instrumentation.logging.ClientLogger.LogLevel.WARNING; +import static io.clientcore.core.instrumentation.logging.LogLevel.ERROR; +import static io.clientcore.core.instrumentation.logging.LogLevel.INFORMATIONAL; +import static io.clientcore.core.instrumentation.logging.LogLevel.VERBOSE; +import static io.clientcore.core.instrumentation.logging.LogLevel.WARNING; public class Slf4jLoggerShim { private static final DefaultLogger DEFAULT_LOGGER = new DefaultLogger(Slf4jLoggerShim.class); @@ -146,7 +146,7 @@ private Slf4jLoggerShim(String className, DefaultLogger defaultLogger) { this.isErrorEnabledForDefault = defaultLogger.isEnabled(ERROR); } - public boolean canLogAtLevel(ClientLogger.LogLevel logLevel) { + public boolean canLogAtLevel(LogLevel logLevel) { if (logLevel == null) { return false; } @@ -171,7 +171,7 @@ public boolean canLogAtLevel(ClientLogger.LogLevel logLevel) { } } - public void performLogging(ClientLogger.LogLevel logLevel, String message, Throwable throwable) { + public void performLogging(LogLevel logLevel, String message, Throwable throwable) { if (!canLogAtLevel(logLevel)) { return; } @@ -241,7 +241,7 @@ static Object createLogger(String className) { } } - private static void writeSlf4jDisabledError(ClientLogger.LogLevel level, String message, Throwable throwable) { + private static void writeSlf4jDisabledError(LogLevel level, String message, Throwable throwable) { if (!slf4jErrorLogged) { slf4jErrorLogged = true; DEFAULT_LOGGER.log(level, String.format("[DefaultLogger]: %s. SLF4J logging will be disabled.", message), diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/fallback/FallbackAttributes.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/fallback/FallbackAttributes.java new file mode 100644 index 000000000000..a3f68e916497 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/fallback/FallbackAttributes.java @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.implementation.instrumentation.fallback; + +import io.clientcore.core.instrumentation.InstrumentationAttributes; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +class FallbackAttributes implements InstrumentationAttributes { + private final Map attributes; + + FallbackAttributes(Map attributes) { + if (attributes == null) { + this.attributes = Collections.emptyMap(); + return; + } + + for (Map.Entry entry : attributes.entrySet()) { + Objects.requireNonNull(entry.getKey(), "attribute key cannot be null."); + Objects.requireNonNull(entry.getValue(), "attribute value cannot be null."); + } + this.attributes = Collections.unmodifiableMap(attributes); + } + + @Override + public InstrumentationAttributes put(String key, Object value) { + Objects.requireNonNull(key, "'key' cannot be null."); + Objects.requireNonNull(value, "'value' cannot be null."); + + Map newAttributes = new HashMap<>((int) ((attributes.size() + 1) * 1.5)); + newAttributes.putAll(attributes); + newAttributes.put(key, value); + return new FallbackAttributes(newAttributes); + } + + Map getAttributes() { + return attributes; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/fallback/FallbackInstrumentation.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/fallback/FallbackInstrumentation.java index 109398c9efbd..e052f6bfb6b3 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/fallback/FallbackInstrumentation.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/fallback/FallbackInstrumentation.java @@ -3,32 +3,59 @@ package io.clientcore.core.implementation.instrumentation.fallback; +import io.clientcore.core.http.models.RequestOptions; +import io.clientcore.core.implementation.instrumentation.LibraryInstrumentationOptionsAccessHelper; +import io.clientcore.core.implementation.instrumentation.NoopMeter; import io.clientcore.core.instrumentation.Instrumentation; +import io.clientcore.core.instrumentation.InstrumentationAttributes; import io.clientcore.core.instrumentation.InstrumentationContext; import io.clientcore.core.instrumentation.InstrumentationOptions; import io.clientcore.core.instrumentation.LibraryInstrumentationOptions; +import io.clientcore.core.instrumentation.metrics.Meter; +import io.clientcore.core.instrumentation.tracing.Span; +import io.clientcore.core.instrumentation.tracing.SpanBuilder; +import io.clientcore.core.instrumentation.tracing.SpanKind; import io.clientcore.core.instrumentation.tracing.TraceContextPropagator; import io.clientcore.core.instrumentation.tracing.Tracer; +import io.clientcore.core.instrumentation.tracing.TracingScope; + +import java.util.Map; +import java.util.Objects; +import java.util.function.Function; + +import static io.clientcore.core.implementation.instrumentation.AttributeKeys.SERVER_ADDRESS_KEY; +import static io.clientcore.core.implementation.instrumentation.AttributeKeys.SERVER_PORT_KEY; +import static io.clientcore.core.implementation.instrumentation.InstrumentationUtils.UNKNOWN_LIBRARY_OPTIONS; /** * Fallback implementation of {@link Instrumentation} which implements basic correlation and context propagation * and, when enabled, records traces as logs. */ public class FallbackInstrumentation implements Instrumentation { - public static final FallbackInstrumentation DEFAULT_INSTANCE = new FallbackInstrumentation(null, null); + public static final FallbackInstrumentation DEFAULT_INSTANCE + = new FallbackInstrumentation(null, UNKNOWN_LIBRARY_OPTIONS, null, -1); - private final InstrumentationOptions instrumentationOptions; - private final LibraryInstrumentationOptions libraryOptions; + private final boolean allowNestedSpans; + private final boolean isTracingEnabled; + private final FallbackTracer tracer; + private final String serviceHost; + private final int servicePort; /** * Creates a new instance of {@link FallbackInstrumentation}. * @param instrumentationOptions the application instrumentation options * @param libraryOptions the library instrumentation options + * @param host the service host + * @param port the service port */ - public FallbackInstrumentation(InstrumentationOptions instrumentationOptions, - LibraryInstrumentationOptions libraryOptions) { - this.instrumentationOptions = instrumentationOptions; - this.libraryOptions = libraryOptions; + public FallbackInstrumentation(InstrumentationOptions instrumentationOptions, + LibraryInstrumentationOptions libraryOptions, String host, int port) { + this.allowNestedSpans = libraryOptions != null + && LibraryInstrumentationOptionsAccessHelper.isSpanSuppressionDisabled(libraryOptions); + this.isTracingEnabled = instrumentationOptions == null || instrumentationOptions.isTracingEnabled(); + this.tracer = new FallbackTracer(instrumentationOptions, libraryOptions); + this.serviceHost = host; + this.servicePort = port; } /** @@ -36,7 +63,27 @@ public FallbackInstrumentation(InstrumentationOptions instrumentationOptions, */ @Override public Tracer getTracer() { - return new FallbackTracer(instrumentationOptions, libraryOptions); + return tracer; + } + + /** + * {@inheritDoc} + */ + @Override + public Meter getMeter() { + // We don't provide fallback metrics support. This might change in the future. + // Some challenges: + // - metric aggregation is complicated + // - having metrics reported in logs is not very useful + return NoopMeter.INSTANCE; + } + + /** + * {@inheritDoc} + */ + @Override + public InstrumentationAttributes createAttributes(Map attributes) { + return new FallbackAttributes(attributes); } /** @@ -47,6 +94,47 @@ public TraceContextPropagator getW3CTraceContextPropagator() { return FallbackContextPropagator.W3C_TRACE_CONTEXT_PROPAGATOR; } + @Override + public TResponse instrumentWithResponse(String operationName, RequestOptions requestOptions, + Function operation) { + Objects.requireNonNull(operationName, "'operationName' cannot be null"); + Objects.requireNonNull(operation, "'operation' cannot be null"); + + if (!shouldInstrument(SpanKind.CLIENT, + requestOptions == null ? null : requestOptions.getInstrumentationContext())) { + return operation.apply(requestOptions); + } + + if (requestOptions == null || requestOptions == RequestOptions.none()) { + requestOptions = new RequestOptions(); + } + + SpanBuilder builder + = tracer.spanBuilder(operationName, SpanKind.CLIENT, requestOptions.getInstrumentationContext()) + .setAttribute(SERVER_ADDRESS_KEY, serviceHost); + + if (servicePort > 0) { + builder.setAttribute(SERVER_PORT_KEY, servicePort); + } + + Span span = builder.startSpan(); + if (span.getInstrumentationContext().isValid()) { + requestOptions.setInstrumentationContext(span.getInstrumentationContext()); + } + + TracingScope scope = span.makeCurrent(); + try { + TResponse response = operation.apply(requestOptions); + span.end(); + return response; + } catch (RuntimeException t) { + span.end(t); + throw t; + } finally { + scope.close(); + } + } + /** * Creates a new instance of {@link InstrumentationContext} from the given object. * It recognizes {@link FallbackSpanContext}, {@link FallbackSpan}, and generic {@link InstrumentationContext} @@ -64,4 +152,32 @@ public InstrumentationContext createInstrumentationContext(T context) { return FallbackSpanContext.INVALID; } } + + private boolean shouldInstrument(SpanKind spanKind, InstrumentationContext context) { + if (!isTracingEnabled) { + return false; + } + + if (allowNestedSpans) { + return true; + } + + return spanKind != tryGetSpanKind(context); + } + + /** + * Retrieves the span kind from the given context if and only if the context is a {@link FallbackSpanContext} + * i.e. was created by this instrumentation. + * @param context the context to get the span kind from + * @return the span kind or {@code null} if the context is not recognized + */ + private SpanKind tryGetSpanKind(InstrumentationContext context) { + if (context instanceof FallbackSpanContext) { + Span span = context.getSpan(); + if (span instanceof FallbackSpan) { + return ((FallbackSpan) span).getSpanKind(); + } + } + return null; + } } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/fallback/FallbackSpan.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/fallback/FallbackSpan.java index 33c420b31876..934f142f2ce2 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/fallback/FallbackSpan.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/fallback/FallbackSpan.java @@ -4,8 +4,9 @@ package io.clientcore.core.implementation.instrumentation.fallback; import io.clientcore.core.instrumentation.InstrumentationContext; -import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.instrumentation.logging.LoggingEvent; import io.clientcore.core.instrumentation.tracing.Span; +import io.clientcore.core.instrumentation.tracing.SpanKind; import io.clientcore.core.instrumentation.tracing.TracingScope; import static io.clientcore.core.implementation.instrumentation.AttributeKeys.ERROR_TYPE_KEY; @@ -15,14 +16,16 @@ import static io.clientcore.core.implementation.instrumentation.LoggingEventNames.SPAN_ENDED_EVENT_NAME; final class FallbackSpan implements Span { - private final ClientLogger.LoggingEvent log; + private final LoggingEvent log; private final long startTime; private final FallbackSpanContext spanContext; + private final SpanKind kind; private String errorType; - FallbackSpan(ClientLogger.LoggingEvent log, FallbackSpanContext parentSpanContext, boolean isRecording) { + FallbackSpan(LoggingEvent log, SpanKind spanKind, FallbackSpanContext parentSpanContext, boolean isRecording) { this.log = log; this.startTime = isRecording ? System.nanoTime() : 0; + this.kind = spanKind; this.spanContext = FallbackSpanContext.fromParent(parentSpanContext, isRecording, this); if (log != null && log.isEnabled()) { this.log.addKeyValue(TRACE_ID_KEY, spanContext.getTraceId()) @@ -74,7 +77,11 @@ public void end(Throwable error) { } log.setEventName(SPAN_ENDED_EVENT_NAME); - log.log(null); + log.log(); + } + + public SpanKind getSpanKind() { + return kind; } /** diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/fallback/FallbackSpanBuilder.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/fallback/FallbackSpanBuilder.java index b2e67a3a5abc..3ccf6b67e9a0 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/fallback/FallbackSpanBuilder.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/fallback/FallbackSpanBuilder.java @@ -3,29 +3,36 @@ package io.clientcore.core.implementation.instrumentation.fallback; +import io.clientcore.core.instrumentation.InstrumentationAttributes; import io.clientcore.core.instrumentation.InstrumentationContext; import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.instrumentation.logging.LoggingEvent; import io.clientcore.core.instrumentation.tracing.Span; import io.clientcore.core.instrumentation.tracing.SpanBuilder; import io.clientcore.core.instrumentation.tracing.SpanKind; +import java.util.Map; + import static io.clientcore.core.implementation.instrumentation.AttributeKeys.SPAN_KIND_KEY; import static io.clientcore.core.implementation.instrumentation.AttributeKeys.SPAN_NAME_KEY; import static io.clientcore.core.implementation.instrumentation.AttributeKeys.SPAN_PARENT_ID_KEY; final class FallbackSpanBuilder implements SpanBuilder { static final FallbackSpanBuilder NOOP = new FallbackSpanBuilder(); - private final ClientLogger.LoggingEvent log; + private final LoggingEvent log; private final FallbackSpanContext parentSpanContext; + private final SpanKind spanKind; private FallbackSpanBuilder() { this.log = null; this.parentSpanContext = FallbackSpanContext.INVALID; + this.spanKind = null; } FallbackSpanBuilder(ClientLogger logger, String spanName, SpanKind spanKind, InstrumentationContext instrumentationContext) { this.parentSpanContext = FallbackSpanContext.fromInstrumentationContext(instrumentationContext); + this.spanKind = spanKind; this.log = logger.atVerbose(); if (log.isEnabled()) { log.addKeyValue(SPAN_NAME_KEY, spanName).addKeyValue(SPAN_KIND_KEY, spanKind.name()); @@ -46,13 +53,26 @@ public SpanBuilder setAttribute(String key, Object value) { return this; } + /** + * {@inheritDoc} + */ + @Override + public SpanBuilder setAllAttributes(InstrumentationAttributes attributes) { + if (log != null && attributes instanceof FallbackAttributes) { + for (Map.Entry entry : ((FallbackAttributes) attributes).getAttributes().entrySet()) { + log.addKeyValue(entry.getKey(), entry.getValue()); + } + } + return this; + } + /** * {@inheritDoc} */ @Override public Span startSpan() { if (log != null) { - return new FallbackSpan(log, parentSpanContext, log.isEnabled()); + return new FallbackSpan(log, spanKind, parentSpanContext, log.isEnabled()); } return Span.noop(); diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/fallback/FallbackTracer.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/fallback/FallbackTracer.java index 006d86ebeacf..15ac5def63ad 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/fallback/FallbackTracer.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/fallback/FallbackTracer.java @@ -19,15 +19,15 @@ final class FallbackTracer implements Tracer { private final boolean isEnabled; private final ClientLogger logger; - FallbackTracer(InstrumentationOptions instrumentationOptions, LibraryInstrumentationOptions libraryOptions) { + FallbackTracer(InstrumentationOptions instrumentationOptions, LibraryInstrumentationOptions libraryOptions) { // TODO (limolkova): do we need additional config to enable fallback tracing? Or maybe we enable it only if logs are enabled? this.isEnabled = instrumentationOptions == null || instrumentationOptions.isTracingEnabled(); this.logger = isEnabled ? getLogger(instrumentationOptions, libraryOptions) : LOGGER; } - private static ClientLogger getLogger(InstrumentationOptions instrumentationOptions, + private static ClientLogger getLogger(InstrumentationOptions instrumentationOptions, LibraryInstrumentationOptions libraryOptions) { - Object providedLogger = instrumentationOptions == null ? null : instrumentationOptions.getProvider(); + Object providedLogger = instrumentationOptions == null ? null : instrumentationOptions.getTelemetryProvider(); if (providedLogger instanceof ClientLogger) { return (ClientLogger) providedLogger; } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/OTelAttributeKey.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/OTelAttributeKey.java index d6facac4803a..b8a6b6f59f6f 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/OTelAttributeKey.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/OTelAttributeKey.java @@ -63,6 +63,10 @@ public static Object getKey(String key, Object value) { return CREATE_LONG_KEY_INVOKER.invoke(key); } else if (value instanceof Double) { return CREATE_DOUBLE_KEY_INVOKER.invoke(key); + } else if (value instanceof Float) { + return CREATE_DOUBLE_KEY_INVOKER.invoke(key); + } else if (value == null) { + return CREATE_STRING_KEY_INVOKER.invoke(key); } else { LOGGER.atVerbose() .addKeyValue("key", key) @@ -86,6 +90,10 @@ public static Object castAttributeValue(Object value) { return ((Integer) value).longValue(); } + if (value instanceof Float) { + return ((Float) value).doubleValue(); + } + return value; } } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/OTelAttributes.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/OTelAttributes.java new file mode 100644 index 000000000000..892da7ba3c8d --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/OTelAttributes.java @@ -0,0 +1,128 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.implementation.instrumentation.otel; + +import io.clientcore.core.implementation.ReflectiveInvoker; +import io.clientcore.core.implementation.instrumentation.NoopAttributes; +import io.clientcore.core.instrumentation.InstrumentationAttributes; +import io.clientcore.core.instrumentation.logging.ClientLogger; + +import java.util.Map; +import java.util.Objects; + +import static io.clientcore.core.implementation.ReflectionUtils.getMethodInvoker; +import static io.clientcore.core.implementation.instrumentation.otel.OTelAttributeKey.castAttributeValue; +import static io.clientcore.core.implementation.instrumentation.otel.OTelAttributeKey.getKey; +import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.ATTRIBUTES_BUILDER_CLASS; +import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.ATTRIBUTES_CLASS; +import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.ATTRIBUTE_KEY_CLASS; + +/** + * A class that wraps the OpenTelemetry attributes builder. + */ +public final class OTelAttributes implements InstrumentationAttributes { + private static final ClientLogger LOGGER = new ClientLogger(OTelAttributes.class); + private static final FallbackInvoker ATTRIBUTES_BUILDER_INVOKER; + private static final FallbackInvoker PUT_INVOKER; + private static final FallbackInvoker BUILD_INVOKER; + private static final FallbackInvoker TO_BUILD_INVOKER; + private static final OTelAttributes EMPTY_INSTANCE; + + static { + ReflectiveInvoker attributesBuilderInvoker = null; + ReflectiveInvoker putInvoker = null; + ReflectiveInvoker buildInvoker = null; + ReflectiveInvoker toBuildInvoker = null; + Object emptyInstance = null; + + try { + attributesBuilderInvoker = getMethodInvoker(ATTRIBUTES_CLASS, ATTRIBUTES_CLASS.getMethod("builder")); + putInvoker = getMethodInvoker(ATTRIBUTES_BUILDER_CLASS, + ATTRIBUTES_BUILDER_CLASS.getMethod("put", ATTRIBUTE_KEY_CLASS, Object.class)); + buildInvoker = getMethodInvoker(ATTRIBUTES_BUILDER_CLASS, ATTRIBUTES_BUILDER_CLASS.getMethod("build")); + + toBuildInvoker = getMethodInvoker(ATTRIBUTES_CLASS, ATTRIBUTES_CLASS.getMethod("toBuilder")); + ReflectiveInvoker emptyInvoker = getMethodInvoker(ATTRIBUTES_CLASS, ATTRIBUTES_CLASS.getMethod("empty")); + emptyInstance = emptyInvoker.invoke(); + } catch (Throwable t) { + OTelInitializer.initError(LOGGER, t); + } + + ATTRIBUTES_BUILDER_INVOKER = new FallbackInvoker(attributesBuilderInvoker, LOGGER); + PUT_INVOKER = new FallbackInvoker(putInvoker, LOGGER); + BUILD_INVOKER = new FallbackInvoker(buildInvoker, LOGGER); + TO_BUILD_INVOKER = new FallbackInvoker(toBuildInvoker, LOGGER); + EMPTY_INSTANCE = new OTelAttributes(emptyInstance); + } + + private final Object otelAttributes; + + /** + * Creates a new instance of OpenTelemetry attributes or noops if OpenTelemetry is not initialized. + * + * @param attributes The attributes to initialize the builder with. + * @return The OpenTelemetry attributes. + */ + public static InstrumentationAttributes create(Map attributes) { + if (attributes == null) { + return EMPTY_INSTANCE; + } + + Object attributesBuilder = ATTRIBUTES_BUILDER_INVOKER.invoke(); + if (attributesBuilder == null) { + return NoopAttributes.INSTANCE; + } + + for (Map.Entry kvp : attributes.entrySet()) { + String key = kvp.getKey(); + Object value = kvp.getValue(); + Objects.requireNonNull(key, "attribute key cannot be null."); + Objects.requireNonNull(value, "attribute value cannot be null."); + Object otelKey = getKey(key, value); + PUT_INVOKER.invoke(attributesBuilder, otelKey, castAttributeValue(value)); + } + + return new OTelAttributes(BUILD_INVOKER.invoke(attributesBuilder)); + } + + private OTelAttributes(Object otelAttributes) { + this.otelAttributes = otelAttributes; + } + + /** + * Builds new instance of OpenTelemetry attributes. + * + * @return The OpenTelemetry attributes. + */ + public Object getOTelAttributes() { + return otelAttributes; + } + + /** + * {@inheritDoc} + */ + @Override + public InstrumentationAttributes put(String key, Object value) { + Objects.requireNonNull(key, "'key' cannot be null."); + Objects.requireNonNull(value, "'value' cannot be null."); + if (isEnabled()) { + Object attributesBuilder = TO_BUILD_INVOKER.invoke(otelAttributes); + if (attributesBuilder == null) { + return NoopAttributes.INSTANCE; + } + + Object otelKey = getKey(key, value); + if (otelKey != null) { + PUT_INVOKER.invoke(attributesBuilder, otelKey, castAttributeValue(value)); + } + + return new OTelAttributes(BUILD_INVOKER.invoke(attributesBuilder)); + } + return NoopAttributes.INSTANCE; + } + + private boolean isEnabled() { + return otelAttributes != null && OTelInitializer.isInitialized(); + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelContext.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/OTelContext.java similarity index 78% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelContext.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/OTelContext.java index bfe298ea4f13..c2cac4e393fe 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelContext.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/OTelContext.java @@ -1,11 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.implementation.instrumentation.otel.tracing; +package io.clientcore.core.implementation.instrumentation.otel; import io.clientcore.core.implementation.ReflectiveInvoker; -import io.clientcore.core.implementation.instrumentation.otel.FallbackInvoker; -import io.clientcore.core.implementation.instrumentation.otel.OTelInitializer; +import io.clientcore.core.implementation.instrumentation.otel.tracing.OTelSpan; +import io.clientcore.core.implementation.instrumentation.otel.tracing.OTelSpanContext; import io.clientcore.core.instrumentation.InstrumentationContext; import io.clientcore.core.instrumentation.tracing.TracingScope; import io.clientcore.core.instrumentation.logging.ClientLogger; @@ -14,7 +14,10 @@ import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.CONTEXT_CLASS; import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.CONTEXT_KEY_CLASS; -class OTelContext { +/** + * This class provides access to the OpenTelemetry context. + */ +public class OTelContext { private static final ClientLogger LOGGER = new ClientLogger(OTelContext.class); private static final TracingScope NOOP_SCOPE = () -> { }; @@ -67,27 +70,45 @@ class OTelContext { CLIENT_CORE_SPAN_CONTEXT_KEY = clientCoreSpanContextKey; } - static Object getCurrent() { + /** + * Get the current OpenTelemetry context. + * @return the current OpenTelemetry context + */ + public static Object getCurrent() { Object currentContext = CURRENT_INVOKER.invoke(); assert CONTEXT_CLASS.isInstance(currentContext); return currentContext; } - static AutoCloseable makeCurrent(Object context) { - assert CONTEXT_CLASS.isInstance(context); + /** + * Make the given context the current context. + * + * @param context the context + * @return an AutoCloseable that will restore the previous context when closed + */ + public static AutoCloseable makeCurrent(Object context) { Object scope = MAKE_CURRENT_INVOKER.invoke(context); assert scope instanceof AutoCloseable; return (AutoCloseable) scope; } - static Object markCoreSpan(Object context, OTelSpan span) { - assert CONTEXT_CLASS.isInstance(context); + /** + * Mark the given context with the given core span. + * @param context the context + * @param span the core span + * @return the updated context + */ + public static Object markCoreSpan(Object context, OTelSpan span) { Object updatedContext = WITH_INVOKER.invoke(context, CLIENT_CORE_SPAN_CONTEXT_KEY, span); return updatedContext == null ? context : updatedContext; } - static OTelSpan getClientCoreSpan(Object context) { - assert CONTEXT_CLASS.isInstance(context); + /** + * Get the core span from the given context. + * @param context the context + * @return the core span + */ + public static OTelSpan getClientCoreSpan(Object context) { Object clientCoreSpan = GET_INVOKER.invoke(context, CLIENT_CORE_SPAN_CONTEXT_KEY); assert clientCoreSpan == null || clientCoreSpan instanceof OTelSpan; return (OTelSpan) clientCoreSpan; @@ -99,7 +120,7 @@ static OTelSpan getClientCoreSpan(Object context) { * @param context the context * @return the OpenTelemetry context */ - static Object fromInstrumentationContext(InstrumentationContext context) { + public static Object fromInstrumentationContext(InstrumentationContext context) { if (context instanceof OTelSpanContext) { Object otelContext = ((OTelSpanContext) context).getOtelContext(); if (otelContext != null) { diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/OTelInitializer.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/OTelInitializer.java index 3e9b02871bd6..06e8e14f6309 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/OTelInitializer.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/OTelInitializer.java @@ -22,6 +22,17 @@ public final class OTelInitializer { public static final Class OTEL_CLASS; public static final Class GLOBAL_OTEL_CLASS; + public static final Class DOUBLE_HISTOGRAM_CLASS; + public static final Class DOUBLE_HISTOGRAM_BUILDER_CLASS; + public static final Class LONG_COUNTER_CLASS; + public static final Class LONG_COUNTER_BUILDER_CLASS; + public static final Class LONG_UP_DOWN_COUNTER_CLASS; + public static final Class LONG_UP_DOWN_COUNTER_BUILDER_CLASS; + + public static final Class METER_CLASS; + public static final Class METER_BUILDER_CLASS; + public static final Class METER_PROVIDER_CLASS; + public static final Class SCOPE_CLASS; public static final Class SPAN_BUILDER_CLASS; public static final Class SPAN_CONTEXT_CLASS; @@ -56,6 +67,17 @@ public final class OTelInitializer { Class otelClass = null; Class globalOtelClass = null; + Class doubleHistogramClass = null; + Class doubleHistogramBuilderClass = null; + + Class longCounterClass = null; + Class longCounterBuilderClass = null; + Class longUpDownCounterClass = null; + Class longUpDownCounterBuilderClass = null; + Class meterClass = null; + Class meterBuilderClass = null; + Class meterProviderClass = null; + Class scopeClass = null; Class spanClass = null; Class spanBuilderClass = null; @@ -90,6 +112,22 @@ public final class OTelInitializer { otelClass = Class.forName("io.opentelemetry.api.OpenTelemetry", true, classLoader); globalOtelClass = Class.forName("io.opentelemetry.api.GlobalOpenTelemetry", true, classLoader); + doubleHistogramClass = Class.forName("io.opentelemetry.api.metrics.DoubleHistogram", true, classLoader); + doubleHistogramBuilderClass + = Class.forName("io.opentelemetry.api.metrics.DoubleHistogramBuilder", true, classLoader); + + longCounterClass = Class.forName("io.opentelemetry.api.metrics.LongCounter", true, classLoader); + longCounterBuilderClass + = Class.forName("io.opentelemetry.api.metrics.LongCounterBuilder", true, classLoader); + + longUpDownCounterClass = Class.forName("io.opentelemetry.api.metrics.LongUpDownCounter", true, classLoader); + longUpDownCounterBuilderClass + = Class.forName("io.opentelemetry.api.metrics.LongUpDownCounterBuilder", true, classLoader); + + meterClass = Class.forName("io.opentelemetry.api.metrics.Meter", true, classLoader); + meterBuilderClass = Class.forName("io.opentelemetry.api.metrics.MeterBuilder", true, classLoader); + meterProviderClass = Class.forName("io.opentelemetry.api.metrics.MeterProvider", true, classLoader); + scopeClass = Class.forName("io.opentelemetry.context.Scope", true, classLoader); spanClass = Class.forName("io.opentelemetry.api.trace.Span", true, classLoader); @@ -128,6 +166,19 @@ public final class OTelInitializer { OTEL_CLASS = otelClass; GLOBAL_OTEL_CLASS = globalOtelClass; + DOUBLE_HISTOGRAM_CLASS = doubleHistogramClass; + DOUBLE_HISTOGRAM_BUILDER_CLASS = doubleHistogramBuilderClass; + + LONG_COUNTER_CLASS = longCounterClass; + LONG_COUNTER_BUILDER_CLASS = longCounterBuilderClass; + + LONG_UP_DOWN_COUNTER_CLASS = longUpDownCounterClass; + LONG_UP_DOWN_COUNTER_BUILDER_CLASS = longUpDownCounterBuilderClass; + + METER_CLASS = meterClass; + METER_BUILDER_CLASS = meterBuilderClass; + METER_PROVIDER_CLASS = meterProviderClass; + SCOPE_CLASS = scopeClass; SPAN_CLASS = spanClass; SPAN_BUILDER_CLASS = spanBuilderClass; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/OTelInstrumentation.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/OTelInstrumentation.java index 38783b3bf6bc..06959c6b2553 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/OTelInstrumentation.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/OTelInstrumentation.java @@ -3,20 +3,43 @@ package io.clientcore.core.implementation.instrumentation.otel; +import io.clientcore.core.http.models.RequestOptions; import io.clientcore.core.implementation.ReflectiveInvoker; +import io.clientcore.core.implementation.instrumentation.LibraryInstrumentationOptionsAccessHelper; +import io.clientcore.core.implementation.instrumentation.NoopAttributes; +import io.clientcore.core.implementation.instrumentation.NoopMeter; +import io.clientcore.core.implementation.instrumentation.otel.metrics.OTelMeter; import io.clientcore.core.implementation.instrumentation.otel.tracing.OTelSpan; import io.clientcore.core.implementation.instrumentation.otel.tracing.OTelSpanContext; import io.clientcore.core.implementation.instrumentation.otel.tracing.OTelTraceContextPropagator; import io.clientcore.core.implementation.instrumentation.otel.tracing.OTelTracer; import io.clientcore.core.instrumentation.Instrumentation; +import io.clientcore.core.instrumentation.InstrumentationAttributes; import io.clientcore.core.instrumentation.InstrumentationContext; import io.clientcore.core.instrumentation.LibraryInstrumentationOptions; import io.clientcore.core.instrumentation.InstrumentationOptions; +import io.clientcore.core.instrumentation.metrics.DoubleHistogram; +import io.clientcore.core.instrumentation.metrics.Meter; +import io.clientcore.core.instrumentation.tracing.Span; +import io.clientcore.core.instrumentation.tracing.SpanKind; import io.clientcore.core.instrumentation.tracing.TraceContextPropagator; import io.clientcore.core.instrumentation.tracing.Tracer; import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.instrumentation.tracing.TracingScope; + +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; import static io.clientcore.core.implementation.ReflectionUtils.getMethodInvoker; +import static io.clientcore.core.implementation.instrumentation.AttributeKeys.ERROR_TYPE_KEY; +import static io.clientcore.core.implementation.instrumentation.AttributeKeys.OPERATION_NAME_KEY; +import static io.clientcore.core.implementation.instrumentation.AttributeKeys.SERVER_ADDRESS_KEY; +import static io.clientcore.core.implementation.instrumentation.AttributeKeys.SERVER_PORT_KEY; +import static io.clientcore.core.implementation.instrumentation.InstrumentationUtils.UNKNOWN_LIBRARY_OPTIONS; +import static io.clientcore.core.implementation.instrumentation.InstrumentationUtils.createOperationDurationHistogram; import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.CONTEXT_CLASS; import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.GLOBAL_OTEL_CLASS; import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.OTEL_CLASS; @@ -29,14 +52,17 @@ * A {@link Instrumentation} implementation that uses OpenTelemetry. */ public class OTelInstrumentation implements Instrumentation { - private static final FallbackInvoker GET_PROVIDER_INVOKER; + private static final FallbackInvoker GET_TRACER_PROVIDER_INVOKER; + private static final FallbackInvoker GET_METER_PROVIDER_INVOKER; private static final FallbackInvoker GET_GLOBAL_OTEL_INVOKER; private static final Object NOOP_PROVIDER; private static final OTelTraceContextPropagator W3C_PROPAGATOR_INSTANCE; private static final ClientLogger LOGGER = new ClientLogger(OTelInstrumentation.class); + static { - ReflectiveInvoker getProviderInvoker = null; + ReflectiveInvoker getTracerProviderInvoker = null; + ReflectiveInvoker getMeterProviderInvoker = null; ReflectiveInvoker getGlobalOtelInvoker = null; Object noopProvider = null; @@ -44,7 +70,8 @@ public class OTelInstrumentation implements Instrumentation { if (OTelInitializer.isInitialized()) { try { - getProviderInvoker = getMethodInvoker(OTEL_CLASS, OTEL_CLASS.getMethod("getTracerProvider")); + getTracerProviderInvoker = getMethodInvoker(OTEL_CLASS, OTEL_CLASS.getMethod("getTracerProvider")); + getMeterProviderInvoker = getMethodInvoker(OTEL_CLASS, OTEL_CLASS.getMethod("getMeterProvider")); getGlobalOtelInvoker = getMethodInvoker(GLOBAL_OTEL_CLASS, GLOBAL_OTEL_CLASS.getMethod("get")); ReflectiveInvoker noopProviderInvoker @@ -60,27 +87,38 @@ public class OTelInstrumentation implements Instrumentation { } } - GET_PROVIDER_INVOKER = new FallbackInvoker(getProviderInvoker, LOGGER); + GET_TRACER_PROVIDER_INVOKER = new FallbackInvoker(getTracerProviderInvoker, LOGGER); + GET_METER_PROVIDER_INVOKER = new FallbackInvoker(getMeterProviderInvoker, LOGGER); GET_GLOBAL_OTEL_INVOKER = new FallbackInvoker(getGlobalOtelInvoker, LOGGER); NOOP_PROVIDER = noopProvider; W3C_PROPAGATOR_INSTANCE = new OTelTraceContextPropagator(w3cPropagatorInstance); } - public static final OTelInstrumentation DEFAULT_INSTANCE = new OTelInstrumentation(null, null); - private final Object otelInstance; - private final LibraryInstrumentationOptions libraryOptions; + public static final OTelInstrumentation DEFAULT_INSTANCE + = new OTelInstrumentation(null, UNKNOWN_LIBRARY_OPTIONS, null, -1); + private final boolean isTracingEnabled; + private final boolean isMetricsEnabled; + private final boolean allowNestedSpans; + private final DoubleHistogram callDurationMetric; + private final Tracer tracer; + private final Meter meter; + private final String host; + private final int port; + private final Map commonAttributesCache = new ConcurrentHashMap<>(); /** * Creates a new instance of {@link OTelInstrumentation}. * * @param applicationOptions the application options * @param libraryOptions the library options + * @param host the service host + * @param port the service port */ - public OTelInstrumentation(InstrumentationOptions applicationOptions, - LibraryInstrumentationOptions libraryOptions) { - Object explicitOTel = applicationOptions == null ? null : applicationOptions.getProvider(); + public OTelInstrumentation(InstrumentationOptions applicationOptions, LibraryInstrumentationOptions libraryOptions, + String host, int port) { + Object explicitOTel = applicationOptions == null ? null : applicationOptions.getTelemetryProvider(); if (explicitOTel != null && !OTEL_CLASS.isInstance(explicitOTel)) { throw LOGGER.atError() .addKeyValue("expectedProvider", OTEL_CLASS.getName()) @@ -89,9 +127,18 @@ public OTelInstrumentation(InstrumentationOptions applicationOptions, new IllegalArgumentException("Telemetry provider is not an instance of " + OTEL_CLASS.getName())); } - this.otelInstance = explicitOTel; - this.libraryOptions = libraryOptions; + Object otelInstance = explicitOTel != null ? explicitOTel : GET_GLOBAL_OTEL_INVOKER.invoke(); this.isTracingEnabled = applicationOptions == null || applicationOptions.isTracingEnabled(); + this.isMetricsEnabled = applicationOptions == null || applicationOptions.isMetricsEnabled(); + this.allowNestedSpans = libraryOptions != null + && LibraryInstrumentationOptionsAccessHelper.isSpanSuppressionDisabled(libraryOptions); + + this.tracer = createTracer(isTracingEnabled, libraryOptions, otelInstance); + this.meter = createMeter(isMetricsEnabled, libraryOptions, otelInstance); + this.callDurationMetric + = createOperationDurationHistogram(libraryOptions == null ? null : libraryOptions.getLibraryName(), meter); + this.host = host; + this.port = port; } /** @@ -99,8 +146,18 @@ public OTelInstrumentation(InstrumentationOptions applicationOptions, */ @Override public Tracer getTracer() { + return tracer; + } + + @Override + public Meter getMeter() { + return meter; + } + + private static Tracer createTracer(boolean isTracingEnabled, LibraryInstrumentationOptions libraryOptions, + Object otelInstance) { if (isTracingEnabled && OTelInitializer.isInitialized()) { - Object otelTracerProvider = GET_PROVIDER_INVOKER.invoke(getOtelInstance()); + Object otelTracerProvider = GET_TRACER_PROVIDER_INVOKER.invoke(otelInstance); if (otelTracerProvider != null && otelTracerProvider != NOOP_PROVIDER) { return new OTelTracer(otelTracerProvider, libraryOptions); @@ -110,6 +167,24 @@ public Tracer getTracer() { return OTelTracer.NOOP; } + private static Meter createMeter(boolean isMetricsEnabled, LibraryInstrumentationOptions libraryOptions, + Object otelInstance) { + if (isMetricsEnabled && OTelInitializer.isInitialized()) { + Object otelMeterProvider = GET_METER_PROVIDER_INVOKER.invoke(otelInstance); + + if (otelMeterProvider != null && otelMeterProvider != NOOP_PROVIDER) { + return new OTelMeter(otelMeterProvider, libraryOptions); + } + } + + return NoopMeter.INSTANCE; + } + + @Override + public InstrumentationAttributes createAttributes(Map attributes) { + return OTelInitializer.isInitialized() ? OTelAttributes.create(attributes) : NoopAttributes.INSTANCE; + } + /** * {@inheritDoc} */ @@ -141,11 +216,92 @@ public InstrumentationContext createInstrumentationContext(T context) { } return OTelSpanContext.getInvalid(); + } + @Override + public TResponse instrumentWithResponse(String operationName, RequestOptions requestOptions, + Function operation) { + Objects.requireNonNull(operationName, "'operationName' cannot be null"); + Objects.requireNonNull(operation, "'operation' cannot be null"); + + if (!shouldInstrument(SpanKind.CLIENT, + requestOptions == null ? null : requestOptions.getInstrumentationContext())) { + return operation.apply(requestOptions); + } + + if (requestOptions == null || requestOptions == RequestOptions.none()) { + requestOptions = new RequestOptions(); + } + + long startTimeNs = callDurationMetric.isEnabled() ? System.nanoTime() : 0; + InstrumentationAttributes commonAttributes = getOrCreateCommonAttributes(operationName); + Span span = tracer.spanBuilder(operationName, SpanKind.CLIENT, requestOptions.getInstrumentationContext()) + .setAllAttributes(commonAttributes) + .startSpan(); + + TracingScope scope = span.makeCurrent(); + RuntimeException error = null; + try { + if (span.getInstrumentationContext().isValid()) { + requestOptions.setInstrumentationContext(span.getInstrumentationContext()); + } + return operation.apply(requestOptions); + } catch (RuntimeException t) { + error = t; + throw t; + } finally { + if (callDurationMetric.isEnabled()) { + InstrumentationAttributes attributes = error == null + ? commonAttributes + : commonAttributes.put(ERROR_TYPE_KEY, error.getClass().getCanonicalName()); + callDurationMetric.record((System.nanoTime() - startTimeNs) / 1e9, attributes, + requestOptions.getInstrumentationContext()); + } + span.end(error); + scope.close(); + } + } + + private InstrumentationAttributes getOrCreateCommonAttributes(String operationName) { + return commonAttributesCache.computeIfAbsent(operationName, name -> { + Map attributeMap = new HashMap<>(4); + attributeMap.put(OPERATION_NAME_KEY, operationName); + if (host != null) { + attributeMap.put(SERVER_ADDRESS_KEY, host); + if (port > 0) { + attributeMap.put(SERVER_PORT_KEY, port); + } + } + + return createAttributes(attributeMap); + }); } - private Object getOtelInstance() { - // not caching global to prevent caching instance that was not setup yet at the start time. - return otelInstance != null ? otelInstance : GET_GLOBAL_OTEL_INVOKER.invoke(); + private boolean shouldInstrument(SpanKind spanKind, InstrumentationContext context) { + if (!isTracingEnabled && !isMetricsEnabled) { + return false; + } + + if (allowNestedSpans) { + return true; + } + + return spanKind != tryGetSpanKind(context); + } + + /** + * Retrieves the span kind from the given context if and only if the context is a {@link OTelSpanContext} + * i.e. was created by this instrumentation. + * @param context the context to get the span kind from + * @return the span kind or {@code null} if the context is not recognized + */ + private static SpanKind tryGetSpanKind(InstrumentationContext context) { + if (context instanceof OTelSpanContext) { + Span span = context.getSpan(); + if (span instanceof OTelSpan) { + return ((OTelSpan) span).getSpanKind(); + } + } + return null; } } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/metrics/OTelDoubleHistogram.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/metrics/OTelDoubleHistogram.java new file mode 100644 index 000000000000..91d9f074271f --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/metrics/OTelDoubleHistogram.java @@ -0,0 +1,110 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.implementation.instrumentation.otel.metrics; + +import io.clientcore.core.implementation.ReflectiveInvoker; +import io.clientcore.core.implementation.instrumentation.otel.FallbackInvoker; +import io.clientcore.core.implementation.instrumentation.otel.OTelAttributes; +import io.clientcore.core.implementation.instrumentation.otel.OTelContext; +import io.clientcore.core.implementation.instrumentation.otel.OTelInitializer; +import io.clientcore.core.instrumentation.InstrumentationAttributes; +import io.clientcore.core.instrumentation.InstrumentationContext; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.instrumentation.metrics.DoubleHistogram; + +import java.util.List; +import java.util.Objects; + +import static io.clientcore.core.implementation.ReflectionUtils.getMethodInvoker; +import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.ATTRIBUTES_CLASS; +import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.CONTEXT_CLASS; +import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.DOUBLE_HISTOGRAM_BUILDER_CLASS; +import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.DOUBLE_HISTOGRAM_CLASS; +import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.METER_CLASS; + +final class OTelDoubleHistogram implements DoubleHistogram { + private static final DoubleHistogram NOOP = new OTelDoubleHistogram(null); + private static final ClientLogger LOGGER = new ClientLogger(OTelDoubleHistogram.class); + private static final FallbackInvoker RECORD_INVOKER; + private static final FallbackInvoker HISTOGRAM_BUILDER_INVOKER; + private static final FallbackInvoker SET_DESCRIPTION_INVOKER; + private static final FallbackInvoker SET_UNIT_INVOKER; + private static final FallbackInvoker BUILD_INVOKER; + private static final FallbackInvoker SET_EXPLICIT_BUCKET_BOUNDARIES_INVOKER; + + private final Object otelHistogram; + + static { + ReflectiveInvoker recordInvoker = null; + ReflectiveInvoker histogramBuilderInvoker = null; + ReflectiveInvoker setDescriptionInvoker = null; + ReflectiveInvoker setUnitInvoker = null; + ReflectiveInvoker buildInvoker = null; + ReflectiveInvoker setExplicitBucketBoundariesInvoker = null; + + if (OTelInitializer.isInitialized()) { + try { + histogramBuilderInvoker + = getMethodInvoker(METER_CLASS, METER_CLASS.getMethod("histogramBuilder", String.class)); + + setDescriptionInvoker = getMethodInvoker(DOUBLE_HISTOGRAM_BUILDER_CLASS, + DOUBLE_HISTOGRAM_BUILDER_CLASS.getMethod("setDescription", String.class)); + + setUnitInvoker = getMethodInvoker(DOUBLE_HISTOGRAM_BUILDER_CLASS, + DOUBLE_HISTOGRAM_BUILDER_CLASS.getMethod("setUnit", String.class)); + + buildInvoker = getMethodInvoker(DOUBLE_HISTOGRAM_BUILDER_CLASS, + DOUBLE_HISTOGRAM_BUILDER_CLASS.getMethod("build")); + + recordInvoker = getMethodInvoker(DOUBLE_HISTOGRAM_CLASS, + DOUBLE_HISTOGRAM_CLASS.getMethod("record", double.class, ATTRIBUTES_CLASS, CONTEXT_CLASS)); + + setExplicitBucketBoundariesInvoker = getMethodInvoker(DOUBLE_HISTOGRAM_BUILDER_CLASS, + DOUBLE_HISTOGRAM_BUILDER_CLASS.getMethod("setExplicitBucketBoundariesAdvice", List.class)); + } catch (Throwable t) { + OTelInitializer.initError(LOGGER, t); + } + } + + HISTOGRAM_BUILDER_INVOKER = new FallbackInvoker(histogramBuilderInvoker, LOGGER); + SET_DESCRIPTION_INVOKER = new FallbackInvoker(setDescriptionInvoker, LOGGER); + SET_UNIT_INVOKER = new FallbackInvoker(setUnitInvoker, LOGGER); + BUILD_INVOKER = new FallbackInvoker(buildInvoker, LOGGER); + RECORD_INVOKER = new FallbackInvoker(recordInvoker, LOGGER); + SET_EXPLICIT_BUCKET_BOUNDARIES_INVOKER = new FallbackInvoker(setExplicitBucketBoundariesInvoker, LOGGER); + } + + private OTelDoubleHistogram(Object otelHistogram) { + this.otelHistogram = otelHistogram; + } + + public static DoubleHistogram create(Object otelMeter, String name, String description, String unit, + List bucketBoundaries) { + if (otelMeter == null || !OTelInitializer.isInitialized()) { + return NOOP; + } + + Object histogramBuilder = HISTOGRAM_BUILDER_INVOKER.invoke(otelMeter, name); + SET_DESCRIPTION_INVOKER.invoke(histogramBuilder, description); + SET_UNIT_INVOKER.invoke(histogramBuilder, unit); + if (bucketBoundaries != null) { + SET_EXPLICIT_BUCKET_BOUNDARIES_INVOKER.invoke(histogramBuilder, bucketBoundaries); + } + return new OTelDoubleHistogram(BUILD_INVOKER.invoke(histogramBuilder)); + } + + @Override + public void record(double value, InstrumentationAttributes attributes, InstrumentationContext context) { + Objects.requireNonNull(attributes, "'attributes' cannot be null."); + if (isEnabled() && attributes instanceof OTelAttributes) { + RECORD_INVOKER.invoke(otelHistogram, value, ((OTelAttributes) attributes).getOTelAttributes(), + OTelContext.fromInstrumentationContext(context)); + } + } + + @Override + public boolean isEnabled() { + return otelHistogram != null && OTelInitializer.isInitialized(); + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/metrics/OTelLongCounter.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/metrics/OTelLongCounter.java new file mode 100644 index 000000000000..b17b300faf7a --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/metrics/OTelLongCounter.java @@ -0,0 +1,103 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.implementation.instrumentation.otel.metrics; + +import io.clientcore.core.implementation.ReflectiveInvoker; +import io.clientcore.core.implementation.instrumentation.otel.FallbackInvoker; +import io.clientcore.core.implementation.instrumentation.otel.OTelAttributes; +import io.clientcore.core.implementation.instrumentation.otel.OTelContext; +import io.clientcore.core.implementation.instrumentation.otel.OTelInitializer; +import io.clientcore.core.instrumentation.InstrumentationAttributes; +import io.clientcore.core.instrumentation.InstrumentationContext; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.instrumentation.metrics.LongCounter; + +import java.util.Objects; + +import static io.clientcore.core.implementation.ReflectionUtils.getMethodInvoker; +import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.ATTRIBUTES_CLASS; +import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.CONTEXT_CLASS; +import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.LONG_COUNTER_BUILDER_CLASS; +import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.LONG_COUNTER_CLASS; +import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.METER_CLASS; + +final class OTelLongCounter implements LongCounter { + private static final LongCounter NOOP = new OTelLongCounter(null); + private static final ClientLogger LOGGER = new ClientLogger(OTelLongCounter.class); + private static final FallbackInvoker ADD_INVOKER; + private static final FallbackInvoker LONG_COUNTER_BUILDER_INVOKER; + private static final FallbackInvoker SET_DESCRIPTION_INVOKER; + private static final FallbackInvoker SET_UNIT_INVOKER; + private static final FallbackInvoker BUILD_INVOKER; + + private final Object otelCounter; + + static { + ReflectiveInvoker addInvoker = null; + ReflectiveInvoker longCounterBuilderInvoker = null; + ReflectiveInvoker setDescriptionInvoker = null; + ReflectiveInvoker setUnitInvoker = null; + ReflectiveInvoker buildInvoker = null; + + if (OTelInitializer.isInitialized()) { + try { + longCounterBuilderInvoker + = getMethodInvoker(METER_CLASS, METER_CLASS.getMethod("counterBuilder", String.class)); + + setDescriptionInvoker = getMethodInvoker(LONG_COUNTER_BUILDER_CLASS, + LONG_COUNTER_BUILDER_CLASS.getMethod("setDescription", String.class)); + + setUnitInvoker = getMethodInvoker(LONG_COUNTER_BUILDER_CLASS, + LONG_COUNTER_BUILDER_CLASS.getMethod("setUnit", String.class)); + + buildInvoker + = getMethodInvoker(LONG_COUNTER_BUILDER_CLASS, LONG_COUNTER_BUILDER_CLASS.getMethod("build")); + + addInvoker = getMethodInvoker(LONG_COUNTER_CLASS, + LONG_COUNTER_CLASS.getMethod("add", long.class, ATTRIBUTES_CLASS, CONTEXT_CLASS)); + } catch (Throwable t) { + OTelInitializer.initError(LOGGER, t); + } + } + + LONG_COUNTER_BUILDER_INVOKER = new FallbackInvoker(longCounterBuilderInvoker, LOGGER); + SET_DESCRIPTION_INVOKER = new FallbackInvoker(setDescriptionInvoker, LOGGER); + SET_UNIT_INVOKER = new FallbackInvoker(setUnitInvoker, LOGGER); + BUILD_INVOKER = new FallbackInvoker(buildInvoker, LOGGER); + ADD_INVOKER = new FallbackInvoker(addInvoker, LOGGER); + } + + private OTelLongCounter(Object otelCounter) { + this.otelCounter = otelCounter; + } + + public static LongCounter create(Object otelMeter, String name, String description, String unit) { + if (otelMeter == null || !OTelInitializer.isInitialized()) { + return NOOP; + } + + Object counterBuilder = LONG_COUNTER_BUILDER_INVOKER.invoke(otelMeter, name); + SET_DESCRIPTION_INVOKER.invoke(counterBuilder, description); + + if (!Objects.isNull(unit)) { + SET_UNIT_INVOKER.invoke(counterBuilder, unit); + } + + return new OTelLongCounter(BUILD_INVOKER.invoke(counterBuilder)); + } + + @Override + public void add(long value, InstrumentationAttributes attributes, InstrumentationContext context) { + Objects.requireNonNull(attributes, "'attributes' cannot be null."); + if (isEnabled() && attributes instanceof OTelAttributes) { + ADD_INVOKER.invoke(otelCounter, value, ((OTelAttributes) attributes).getOTelAttributes(), + OTelContext.fromInstrumentationContext(context)); + } + } + + @Override + public boolean isEnabled() { + return otelCounter != null && OTelInitializer.isInitialized(); + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/metrics/OTelLongUpDownCounter.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/metrics/OTelLongUpDownCounter.java new file mode 100644 index 000000000000..949e0f5288b8 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/metrics/OTelLongUpDownCounter.java @@ -0,0 +1,103 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.implementation.instrumentation.otel.metrics; + +import io.clientcore.core.implementation.ReflectiveInvoker; +import io.clientcore.core.implementation.instrumentation.otel.FallbackInvoker; +import io.clientcore.core.implementation.instrumentation.otel.OTelAttributes; +import io.clientcore.core.implementation.instrumentation.otel.OTelContext; +import io.clientcore.core.implementation.instrumentation.otel.OTelInitializer; +import io.clientcore.core.instrumentation.InstrumentationAttributes; +import io.clientcore.core.instrumentation.InstrumentationContext; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.instrumentation.metrics.LongCounter; + +import java.util.Objects; + +import static io.clientcore.core.implementation.ReflectionUtils.getMethodInvoker; +import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.ATTRIBUTES_CLASS; +import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.CONTEXT_CLASS; +import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.LONG_UP_DOWN_COUNTER_BUILDER_CLASS; +import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.LONG_UP_DOWN_COUNTER_CLASS; +import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.METER_CLASS; + +final class OTelLongUpDownCounter implements LongCounter { + private static final LongCounter NOOP = new OTelLongUpDownCounter(null); + private static final ClientLogger LOGGER = new ClientLogger(OTelLongUpDownCounter.class); + private static final FallbackInvoker ADD_INVOKER; + private static final FallbackInvoker UP_DOWN_COUNTER_BUILDER_INVOKER; + private static final FallbackInvoker SET_DESCRIPTION_INVOKER; + private static final FallbackInvoker SET_UNIT_INVOKER; + private static final FallbackInvoker BUILD_INVOKER; + + private final Object otelCounter; + + static { + ReflectiveInvoker addInvoker = null; + ReflectiveInvoker upDownBuilderInvoker = null; + ReflectiveInvoker setDescriptionInvoker = null; + ReflectiveInvoker setUnitInvoker = null; + ReflectiveInvoker buildInvoker = null; + + if (OTelInitializer.isInitialized()) { + try { + upDownBuilderInvoker + = getMethodInvoker(METER_CLASS, METER_CLASS.getMethod("upDownCounterBuilder", String.class)); + + setDescriptionInvoker = getMethodInvoker(LONG_UP_DOWN_COUNTER_BUILDER_CLASS, + LONG_UP_DOWN_COUNTER_BUILDER_CLASS.getMethod("setDescription", String.class)); + + setUnitInvoker = getMethodInvoker(LONG_UP_DOWN_COUNTER_BUILDER_CLASS, + LONG_UP_DOWN_COUNTER_BUILDER_CLASS.getMethod("setUnit", String.class)); + + buildInvoker = getMethodInvoker(LONG_UP_DOWN_COUNTER_BUILDER_CLASS, + LONG_UP_DOWN_COUNTER_BUILDER_CLASS.getMethod("build")); + + addInvoker = getMethodInvoker(LONG_UP_DOWN_COUNTER_CLASS, + LONG_UP_DOWN_COUNTER_CLASS.getMethod("add", long.class, ATTRIBUTES_CLASS, CONTEXT_CLASS)); + } catch (Throwable t) { + OTelInitializer.initError(LOGGER, t); + } + } + + UP_DOWN_COUNTER_BUILDER_INVOKER = new FallbackInvoker(upDownBuilderInvoker, LOGGER); + SET_DESCRIPTION_INVOKER = new FallbackInvoker(setDescriptionInvoker, LOGGER); + SET_UNIT_INVOKER = new FallbackInvoker(setUnitInvoker, LOGGER); + BUILD_INVOKER = new FallbackInvoker(buildInvoker, LOGGER); + ADD_INVOKER = new FallbackInvoker(addInvoker, LOGGER); + } + + private OTelLongUpDownCounter(Object otelCounter) { + this.otelCounter = otelCounter; + } + + public static LongCounter create(Object otelMeter, String name, String description, String unit) { + if (otelMeter == null || !OTelInitializer.isInitialized()) { + return NOOP; + } + + Object counterBuilder = UP_DOWN_COUNTER_BUILDER_INVOKER.invoke(otelMeter, name); + SET_DESCRIPTION_INVOKER.invoke(counterBuilder, description); + + if (!Objects.isNull(unit)) { + SET_UNIT_INVOKER.invoke(counterBuilder, unit); + } + + return new OTelLongUpDownCounter(BUILD_INVOKER.invoke(counterBuilder)); + } + + @Override + public void add(long value, InstrumentationAttributes attributes, InstrumentationContext context) { + Objects.requireNonNull(attributes, "'attributes' cannot be null."); + if (isEnabled() && attributes instanceof OTelAttributes) { + ADD_INVOKER.invoke(otelCounter, value, ((OTelAttributes) attributes).getOTelAttributes(), + OTelContext.fromInstrumentationContext(context)); + } + } + + @Override + public boolean isEnabled() { + return otelCounter != null && OTelInitializer.isInitialized(); + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/metrics/OTelMeter.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/metrics/OTelMeter.java new file mode 100644 index 000000000000..aef750314452 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/metrics/OTelMeter.java @@ -0,0 +1,122 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.implementation.instrumentation.otel.metrics; + +import io.clientcore.core.implementation.ReflectiveInvoker; +import io.clientcore.core.implementation.instrumentation.NoopMeter; +import io.clientcore.core.implementation.instrumentation.otel.FallbackInvoker; +import io.clientcore.core.implementation.instrumentation.otel.OTelInitializer; +import io.clientcore.core.instrumentation.LibraryInstrumentationOptions; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.instrumentation.metrics.DoubleHistogram; +import io.clientcore.core.instrumentation.metrics.LongCounter; +import io.clientcore.core.instrumentation.metrics.Meter; + +import java.util.List; +import java.util.Objects; + +import static io.clientcore.core.implementation.ReflectionUtils.getMethodInvoker; +import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.METER_BUILDER_CLASS; +import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.METER_PROVIDER_CLASS; + +/** + * A class that wraps the OpenTelemetry meter. + */ +public class OTelMeter implements Meter { + private static final ClientLogger LOGGER = new ClientLogger(OTelMeter.class); + private static final FallbackInvoker SET_INSTRUMENTATION_VERSION_INVOKER; + private static final FallbackInvoker BUILD_INVOKER; + private static final FallbackInvoker SET_SCHEMA_URL_INVOKER; + private static final FallbackInvoker GET_METER_BUILDER_INVOKER; + + static { + ReflectiveInvoker setInstrumentationVersionInvoker = null; + ReflectiveInvoker buildInvoker = null; + ReflectiveInvoker setSchemaUrlInvoker = null; + ReflectiveInvoker getMeterBuilderInvoker = null; + + if (OTelInitializer.isInitialized()) { + try { + setInstrumentationVersionInvoker = getMethodInvoker(METER_BUILDER_CLASS, + METER_BUILDER_CLASS.getMethod("setInstrumentationVersion", String.class)); + + setSchemaUrlInvoker = getMethodInvoker(METER_BUILDER_CLASS, + METER_BUILDER_CLASS.getMethod("setSchemaUrl", String.class)); + + buildInvoker = getMethodInvoker(METER_BUILDER_CLASS, METER_BUILDER_CLASS.getMethod("build")); + + getMeterBuilderInvoker = getMethodInvoker(METER_PROVIDER_CLASS, + METER_PROVIDER_CLASS.getMethod("meterBuilder", String.class)); + } catch (Throwable t) { + OTelInitializer.initError(LOGGER, t); + } + } + + SET_INSTRUMENTATION_VERSION_INVOKER = new FallbackInvoker(setInstrumentationVersionInvoker, LOGGER); + SET_SCHEMA_URL_INVOKER = new FallbackInvoker(setSchemaUrlInvoker, LOGGER); + BUILD_INVOKER = new FallbackInvoker(buildInvoker, NoopMeter.INSTANCE, LOGGER); + GET_METER_BUILDER_INVOKER = new FallbackInvoker(getMeterBuilderInvoker, LOGGER); + } + + private final Object otelMeter; + + /** + * Creates a new instance of OTelMeter. + * + * @param otelMeterProvider The OpenTelemetry meter provider. + * @param libraryOptions The library options. + */ + public OTelMeter(Object otelMeterProvider, LibraryInstrumentationOptions libraryOptions) { + Object meterBuilder = GET_METER_BUILDER_INVOKER.invoke(otelMeterProvider, libraryOptions.getLibraryName()); + if (meterBuilder != null) { + SET_INSTRUMENTATION_VERSION_INVOKER.invoke(meterBuilder, libraryOptions.getLibraryVersion()); + SET_SCHEMA_URL_INVOKER.invoke(meterBuilder, libraryOptions.getSchemaUrl()); + this.otelMeter = BUILD_INVOKER.invoke(meterBuilder); + } else { + this.otelMeter = null; + } + } + + /** + * {@inheritDoc} + */ + @Override + public DoubleHistogram createDoubleHistogram(String name, String description, String unit, + List bucketBoundaries) { + Objects.requireNonNull(name, "'name' cannot be null."); + Objects.requireNonNull(description, "'description' cannot be null."); + Objects.requireNonNull(unit, "'unit' cannot be null."); + return OTelDoubleHistogram.create(otelMeter, name, description, unit, bucketBoundaries); + } + + /** + * {@inheritDoc} + */ + @Override + public LongCounter createLongCounter(String name, String description, String unit) { + Objects.requireNonNull(name, "'name' cannot be null."); + Objects.requireNonNull(description, "'description' cannot be null."); + Objects.requireNonNull(unit, "'unit' cannot be null."); + return OTelLongCounter.create(otelMeter, name, description, unit); + } + + /** + * {@inheritDoc} + */ + @Override + public LongCounter createLongUpDownCounter(String name, String description, String unit) { + Objects.requireNonNull(name, "'name' cannot be null."); + Objects.requireNonNull(description, "'description' cannot be null."); + Objects.requireNonNull(unit, "'unit' cannot be null."); + return OTelLongUpDownCounter.create(otelMeter, name, description, unit); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isEnabled() { + return otelMeter != null && OTelInitializer.isInitialized(); + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/metrics/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/metrics/package-info.java new file mode 100644 index 000000000000..29e35681eb2e --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/metrics/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * This package contains the implementation of the OpenTelemetry metrics. + */ +package io.clientcore.core.implementation.instrumentation.otel.metrics; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelSpan.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelSpan.java index 48ca484fee58..eb251b70c558 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelSpan.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelSpan.java @@ -6,6 +6,7 @@ import io.clientcore.core.implementation.ReflectiveInvoker; import io.clientcore.core.implementation.instrumentation.otel.FallbackInvoker; import io.clientcore.core.implementation.instrumentation.otel.OTelAttributeKey; +import io.clientcore.core.implementation.instrumentation.otel.OTelContext; import io.clientcore.core.implementation.instrumentation.otel.OTelInitializer; import io.clientcore.core.instrumentation.InstrumentationContext; import io.clientcore.core.instrumentation.tracing.TracingScope; @@ -13,8 +14,6 @@ import io.clientcore.core.instrumentation.tracing.SpanKind; import io.clientcore.core.instrumentation.logging.ClientLogger; -import java.util.Objects; - import static io.clientcore.core.implementation.ReflectionUtils.getMethodInvoker; import static io.clientcore.core.implementation.instrumentation.AttributeKeys.ERROR_TYPE_KEY; import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.ATTRIBUTE_KEY_CLASS; @@ -22,7 +21,7 @@ import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.SPAN_CLASS; import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.SPAN_CONTEXT_CLASS; import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.STATUS_CODE_CLASS; -import static io.clientcore.core.implementation.instrumentation.otel.tracing.OTelContext.markCoreSpan; +import static io.clientcore.core.implementation.instrumentation.otel.OTelContext.markCoreSpan; import static io.clientcore.core.implementation.instrumentation.otel.tracing.OTelSpanContext.INVALID_OTEL_SPAN_CONTEXT; /** @@ -132,8 +131,10 @@ private OTelSpan(Object otelSpan, Object otelContext) { @Override public OTelSpan setAttribute(String key, Object value) { if (isInitialized() && isRecording) { - SET_ATTRIBUTE_INVOKER.invoke(otelSpan, OTelAttributeKey.getKey(key, value), - OTelAttributeKey.castAttributeValue(value)); + Object otelKey = OTelAttributeKey.getKey(key, value); + if (otelKey != null) { + SET_ATTRIBUTE_INVOKER.invoke(otelSpan, otelKey, OTelAttributeKey.castAttributeValue(value)); + } } return this; @@ -153,7 +154,6 @@ public Span setError(String errorType) { */ @Override public void end(Throwable throwable) { - Objects.requireNonNull(throwable, "'throwable' cannot be null"); endSpan(throwable); } @@ -196,7 +196,11 @@ public InstrumentationContext getInstrumentationContext() { return spanContext; } - SpanKind getSpanKind() { + /** + * Gets the span kind. + * @return the span kind + */ + public SpanKind getSpanKind() { return spanKind; } @@ -229,13 +233,13 @@ static Object fromOTelContext(Object otelContext) { return span; } - static Object wrapSpanContext(Object otelSpanContext) { - assert SPAN_CONTEXT_CLASS.isInstance(otelSpanContext); - - Object propagatingSpan = WRAP_INVOKER.invoke(otelSpanContext); - assert SPAN_CLASS.isInstance(propagatingSpan); - - return propagatingSpan; + /** + * Wraps an OpenTelemetry span context in a propagating span. + * @param otelSpanContext the OpenTelemetry span context + * @return the propagating span + */ + public static Object wrapSpanContext(Object otelSpanContext) { + return WRAP_INVOKER.invoke(otelSpanContext); } static Object getSpanContext(Object otelSpan) { @@ -247,7 +251,13 @@ static Object getSpanContext(Object otelSpan) { return spanContext; } - static Object storeInContext(Object otelSpan, Object otelContext) { + /** + * Stores the given span in the given context. + * @param otelSpan the OpenTelemetry span + * @param otelContext the OpenTelemetry context + * @return the updated context + */ + public static Object storeInContext(Object otelSpan, Object otelContext) { Object updatedContext = STORE_IN_CONTEXT_INVOKER.invoke(otelSpan, otelContext); return updatedContext != null ? updatedContext : otelContext; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelSpanBuilder.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelSpanBuilder.java index 0dcf0e53e8a5..868e50a23ce5 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelSpanBuilder.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelSpanBuilder.java @@ -6,7 +6,10 @@ import io.clientcore.core.implementation.ReflectiveInvoker; import io.clientcore.core.implementation.instrumentation.otel.FallbackInvoker; import io.clientcore.core.implementation.instrumentation.LibraryInstrumentationOptionsAccessHelper; +import io.clientcore.core.implementation.instrumentation.otel.OTelAttributes; +import io.clientcore.core.implementation.instrumentation.otel.OTelContext; import io.clientcore.core.implementation.instrumentation.otel.OTelInitializer; +import io.clientcore.core.instrumentation.InstrumentationAttributes; import io.clientcore.core.instrumentation.InstrumentationContext; import io.clientcore.core.instrumentation.LibraryInstrumentationOptions; import io.clientcore.core.instrumentation.tracing.Span; @@ -17,6 +20,7 @@ import static io.clientcore.core.implementation.ReflectionUtils.getMethodInvoker; import static io.clientcore.core.implementation.instrumentation.otel.OTelAttributeKey.castAttributeValue; import static io.clientcore.core.implementation.instrumentation.otel.OTelAttributeKey.getKey; +import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.ATTRIBUTES_CLASS; import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.ATTRIBUTE_KEY_CLASS; import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.CONTEXT_CLASS; import static io.clientcore.core.implementation.instrumentation.otel.OTelInitializer.SPAN_BUILDER_CLASS; @@ -34,6 +38,7 @@ public class OTelSpanBuilder implements SpanBuilder { private static final FallbackInvoker SET_ATTRIBUTE_INVOKER; private static final FallbackInvoker SET_SPAN_KIND_INVOKER; private static final FallbackInvoker START_SPAN_INVOKER; + private static final FallbackInvoker SET_ALL_ATTRIBUTES_INVOKER; private static final Object INTERNAL_KIND; private static final Object SERVER_KIND; private static final Object CLIENT_KIND; @@ -50,6 +55,7 @@ public class OTelSpanBuilder implements SpanBuilder { ReflectiveInvoker setAttributeInvoker = null; ReflectiveInvoker setSpanKindInvoker = null; ReflectiveInvoker startSpanInvoker = null; + ReflectiveInvoker setAllAttributesInvoker = null; Object internalKind = null; Object serverKind = null; @@ -69,6 +75,8 @@ public class OTelSpanBuilder implements SpanBuilder { SPAN_BUILDER_CLASS.getMethod("setSpanKind", SPAN_KIND_CLASS)); startSpanInvoker = getMethodInvoker(SPAN_BUILDER_CLASS, SPAN_BUILDER_CLASS.getMethod("startSpan")); + setAllAttributesInvoker = getMethodInvoker(SPAN_BUILDER_CLASS, + SPAN_BUILDER_CLASS.getMethod("setAllAttributes", ATTRIBUTES_CLASS)); internalKind = SPAN_KIND_CLASS.getField("INTERNAL").get(null); serverKind = SPAN_KIND_CLASS.getField("SERVER").get(null); @@ -84,6 +92,7 @@ public class OTelSpanBuilder implements SpanBuilder { SET_ATTRIBUTE_INVOKER = new FallbackInvoker(setAttributeInvoker, LOGGER); SET_SPAN_KIND_INVOKER = new FallbackInvoker(setSpanKindInvoker, LOGGER); START_SPAN_INVOKER = new FallbackInvoker(startSpanInvoker, OTelSpan.NOOP_SPAN.getOtelSpan(), LOGGER); + SET_ALL_ATTRIBUTES_INVOKER = new FallbackInvoker(setAllAttributesInvoker, LOGGER); INTERNAL_KIND = internalKind; SERVER_KIND = serverKind; CLIENT_KIND = clientKind; @@ -107,7 +116,22 @@ public class OTelSpanBuilder implements SpanBuilder { @Override public SpanBuilder setAttribute(String key, Object value) { if (isInitialized()) { - SET_ATTRIBUTE_INVOKER.invoke(otelSpanBuilder, getKey(key, value), castAttributeValue(value)); + Object otelKey = getKey(key, value); + if (otelKey != null) { + SET_ATTRIBUTE_INVOKER.invoke(otelSpanBuilder, otelKey, castAttributeValue(value)); + } + } + + return this; + } + + @Override + public SpanBuilder setAllAttributes(InstrumentationAttributes attributes) { + if (isInitialized() && attributes instanceof OTelAttributes) { + Object otelAttributes = ((OTelAttributes) attributes).getOTelAttributes(); + if (otelAttributes != null) { + SET_ALL_ATTRIBUTES_INVOKER.invoke(otelSpanBuilder, otelAttributes); + } } return this; @@ -120,11 +144,17 @@ public SpanBuilder setAttribute(String key, Object value) { public Span startSpan() { if (isInitialized()) { Object otelParentContext = OTelContext.fromInstrumentationContext(context); - SET_PARENT_INVOKER.invoke(otelSpanBuilder, otelParentContext); - SET_SPAN_KIND_INVOKER.invoke(otelSpanBuilder, toOtelSpanKind(spanKind)); - Object otelSpan = shouldSuppress(otelParentContext) - ? OTelSpan.createPropagatingSpan(otelParentContext) - : START_SPAN_INVOKER.invoke(otelSpanBuilder); + OTelSpan parentSpan = OTelContext.getClientCoreSpan(otelParentContext); + SpanKind parentKind = parentSpan == null ? null : parentSpan.getSpanKind(); + Object otelSpan; + if (suppressNestedSpans && parentKind == spanKind) { + otelSpan = OTelSpan.createPropagatingSpan(otelParentContext); + } else { + SET_PARENT_INVOKER.invoke(otelSpanBuilder, otelParentContext); + SET_SPAN_KIND_INVOKER.invoke(otelSpanBuilder, toOtelSpanKind(spanKind)); + otelSpan = START_SPAN_INVOKER.invoke(otelSpanBuilder); + } + if (otelSpan != null) { return new OTelSpan(otelSpan, otelParentContext, this.spanKind); } @@ -133,15 +163,6 @@ public Span startSpan() { return OTelSpan.NOOP_SPAN; } - private boolean shouldSuppress(Object parentContext) { - if (suppressNestedSpans && (this.spanKind == SpanKind.CLIENT || this.spanKind == SpanKind.INTERNAL)) { - OTelSpan span = OTelContext.getClientCoreSpan(parentContext); - return span != null && (span.getSpanKind() == SpanKind.INTERNAL || span.getSpanKind() == SpanKind.CLIENT); - } - - return false; - } - private Object toOtelSpanKind(SpanKind spanKind) { switch (spanKind) { case SERVER: diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelSpanContext.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelSpanContext.java index 83370ede4105..ea2ca41650d4 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelSpanContext.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelSpanContext.java @@ -5,6 +5,7 @@ import io.clientcore.core.implementation.ReflectiveInvoker; import io.clientcore.core.implementation.instrumentation.otel.FallbackInvoker; +import io.clientcore.core.implementation.instrumentation.otel.OTelContext; import io.clientcore.core.implementation.instrumentation.otel.OTelInitializer; import io.clientcore.core.instrumentation.InstrumentationContext; import io.clientcore.core.instrumentation.logging.ClientLogger; @@ -197,7 +198,12 @@ public Span getSpan() { return Span.noop(); } - Object getOtelContext() { + /** + * Gets the OpenTelemetry context. + * + * @return The OpenTelemetry context. + */ + public Object getOtelContext() { return otelContext; } @@ -205,7 +211,13 @@ Object getOtelSpanContext() { return otelSpanContext; } - static Object toOTelSpanContext(InstrumentationContext context) { + /** + * Converts the given {@link InstrumentationContext} to an OpenTelemetry {@code SpanContext}. + * + * @param context The {@link InstrumentationContext} to convert. + * @return The OpenTelemetry {@code SpanContext}. + */ + public static Object toOTelSpanContext(InstrumentationContext context) { if (context instanceof OTelSpanContext) { return ((OTelSpanContext) context).otelSpanContext; } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelTraceContextPropagator.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelTraceContextPropagator.java index c4d328545879..ce4695606e4e 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelTraceContextPropagator.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelTraceContextPropagator.java @@ -5,6 +5,7 @@ import io.clientcore.core.implementation.ReflectiveInvoker; import io.clientcore.core.implementation.instrumentation.otel.FallbackInvoker; +import io.clientcore.core.implementation.instrumentation.otel.OTelContext; import io.clientcore.core.implementation.instrumentation.otel.OTelInitializer; import io.clientcore.core.instrumentation.InstrumentationContext; import io.clientcore.core.instrumentation.tracing.TraceContextGetter; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/Base64Util.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/Base64Util.java deleted file mode 100644 index 701ff23f0ac5..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/Base64Util.java +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.implementation.util; - -import java.util.Base64; - -/** - * Utility type exposing Base64 encoding and decoding methods. - */ -public final class Base64Util { - /** - * Encodes a byte array to base64. - * @param src the byte array to encode - * @return the base64 encoded bytes - */ - public static byte[] encode(byte[] src) { - return src == null ? null : Base64.getEncoder().encode(src); - } - - /** - * Encodes a byte array to base64 URI format. - * @param src the byte array to encode - * @return the base64 URI encoded bytes - */ - public static byte[] encodeURIWithoutPadding(byte[] src) { - return src == null ? null : Base64.getUrlEncoder().withoutPadding().encode(src); - } - - /** - * Encodes a byte array to a base 64 string. - * @param src the byte array to encode - * @return the base64 encoded string - */ - public static String encodeToString(byte[] src) { - return src == null ? null : Base64.getEncoder().encodeToString(src); - } - - /** - * Decodes a base64 encoded byte array. - * @param encoded the byte array to decode - * @return the decoded byte array - */ - public static byte[] decode(byte[] encoded) { - return encoded == null ? null : Base64.getDecoder().decode(encoded); - } - - /** - * Decodes a byte array in base64 URI format. - * @param src the byte array to decode - * @return the decoded byte array - */ - public static byte[] decodeURI(byte[] src) { - return src == null ? null : Base64.getUrlDecoder().decode(src); - } - - /** - * Decodes a base64 encoded string. - * @param encoded the string to decode - * @return the decoded byte array - */ - public static byte[] decodeString(String encoded) { - return encoded == null ? null : Base64.getDecoder().decode(encoded); - } - - // Private Ctr - private Base64Util() { - } -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/EnvironmentConfiguration.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/EnvironmentConfiguration.java deleted file mode 100644 index 11518a325817..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/EnvironmentConfiguration.java +++ /dev/null @@ -1,227 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.implementation.util; - -import io.clientcore.core.util.configuration.Configuration; -import io.clientcore.core.util.configuration.ConfigurationSource; - -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - * Contains environment (system properties and environment variables) configuration information that is - * used during construction of client libraries. - */ -public class EnvironmentConfiguration { - /* - * Configurations that are loaded into the global configuration store when the application starts. - */ - private static final Set DEFAULT_CONFIGURATIONS - = new HashSet<>(Arrays.asList(Configuration.PROPERTY_HTTP_PROXY, Configuration.PROPERTY_HTTPS_PROXY, - Configuration.PROPERTY_LOG_LEVEL, Configuration.PROPERTY_HTTP_LOG_DETAIL_LEVEL, - Configuration.PROPERTY_REQUEST_RETRY_COUNT, Configuration.PROPERTY_REQUEST_CONNECT_TIMEOUT, - Configuration.PROPERTY_REQUEST_WRITE_TIMEOUT, Configuration.PROPERTY_REQUEST_RESPONSE_TIMEOUT, - Configuration.PROPERTY_REQUEST_READ_TIMEOUT)); - - private static final EnvironmentConfiguration GLOBAL_CONFIGURATION = new EnvironmentConfiguration(); - - private final ConcurrentMap explicitConfigurations; - private final ConcurrentMap> envConfigurations; - private final ConcurrentMap> sysPropertiesConfigurations; - - /** - * Constructs a configuration containing the known SDK properties constants. - */ - private EnvironmentConfiguration() { - this(EnvironmentVariablesConfigurationSource.GLOBAL_SOURCE, path -> Collections.emptyMap()); - } - - /** - * Clones original configuration. - * - * @param original The original configuration to clone. - */ - public EnvironmentConfiguration(EnvironmentConfiguration original) { - this.explicitConfigurations = new ConcurrentHashMap<>(original.explicitConfigurations); - this.envConfigurations = new ConcurrentHashMap<>(original.envConfigurations); - this.sysPropertiesConfigurations = new ConcurrentHashMap<>(original.sysPropertiesConfigurations); - } - - /** - * Constructs a configuration containing mocked environment. Use this constructor for testing. - * - * @param environmentConfigurationSource The mocked environment configuration source. - * @param systemPropertiesConfigurationSource The mocked system properties configuration source. - */ - public EnvironmentConfiguration(ConfigurationSource systemPropertiesConfigurationSource, - ConfigurationSource environmentConfigurationSource) { - this.explicitConfigurations = new ConcurrentHashMap<>(); - - if (environmentConfigurationSource == null) { - environmentConfigurationSource = EnvironmentVariablesConfigurationSource.GLOBAL_SOURCE; - } - - Map fromEnvironment = environmentConfigurationSource.getProperties(null); - Objects.requireNonNull(fromEnvironment, "'environmentConfigurationSource.getProperties(null)' can't be null"); - - this.envConfigurations = new ConcurrentHashMap<>(fromEnvironment.size()); - for (Map.Entry config : fromEnvironment.entrySet()) { - this.envConfigurations.put(config.getKey(), Optional.ofNullable(config.getValue())); - } - - if (systemPropertiesConfigurationSource == null) { - this.sysPropertiesConfigurations = new ConcurrentHashMap<>(); - } else { - Map fromSystemProperties = systemPropertiesConfigurationSource.getProperties(null); - Objects.requireNonNull(fromSystemProperties, - "'systemPropertiesConfigurationSource.getProperties(null)' can't be null"); - this.sysPropertiesConfigurations = new ConcurrentHashMap<>(fromSystemProperties.size()); - for (Map.Entry config : fromSystemProperties.entrySet()) { - this.sysPropertiesConfigurations.put(config.getKey(), Optional.ofNullable(config.getValue())); - } - } - } - - /** - * Gets the global environment configuration. - * - * @return The global environment configuration. - */ - public static EnvironmentConfiguration getGlobalConfiguration() { - return GLOBAL_CONFIGURATION; - } - - /** - * Gets the value of the environment variable. - *

        - * This method first checks the values previously loaded from the environment, if the configuration is found there - * it will be returned. Otherwise, this will attempt to load the value from the environment. - * - * @param name Name of the configuration. - * @return Value of the configuration if found, otherwise null. - */ - public String getEnvironmentVariable(String name) { - return getOrLoad(name, envConfigurations, false); - } - - /** - * Gets the value of the system property. - *

        - * This method first checks the values previously loaded from the environment, if the configuration is found there - * it will be returned. Otherwise, this will attempt to load the value from the environment. - * - * @param name Name of the configuration. - * @return Value of the configuration if found, otherwise null. - */ - public String getSystemProperty(String name) { - return getOrLoad(name, sysPropertiesConfigurations, true); - } - - /** - * Gets the value of the configuration. - *

        - * This method first checks the values previously loaded from the environment, if the configuration is found there - * it will be returned. Otherwise, this will attempt to load the value from the environment. - * - * @param name Name of the configuration. - * @return Value of the configuration if found, otherwise null. - */ - public String get(String name) { - String value = explicitConfigurations.get(name); - if (value != null) { - return value; - } - - value = getSystemProperty(name); - if (value != null) { - return value; - } - - return getEnvironmentVariable(name); - } - - /* - * Attempts to get the value of the configuration from the configuration store, if the value isn't found then it - * attempts to load it from the runtime parameters then the environment variables. - * - * If no configuration is found null is returned. - * - * @param name Configuration property name. - * @return The configuration value from either the configuration store, runtime parameters, or environment - * variable, in that order, if found, otherwise null. - */ - private String getOrLoad(String name, ConcurrentMap> configurations, - boolean loadFromSystemProperties) { - Optional value = configurations.get(name); - if (value != null) { - return value.orElse(null); - } - - String envValue = loadFromSystemProperties ? loadFromProperties(name) : loadFromEnvironment(name); - configurations.put(name, Optional.ofNullable(envValue)); - return envValue; - } - - /** - * Adds a configuration with the given value. - *

        - * This will overwrite the previous configuration value if it existed. - * - * @param name Name of the configuration. - * @param value Value of the configuration. - * @return The updated Configuration object. - */ - public EnvironmentConfiguration put(String name, String value) { - explicitConfigurations.put(name, value); - return this; - } - - /** - * Removes the configuration. - *

        - * This returns the value of the configuration if it previously existed. - * - * @param name Name of the configuration. - * @return The configuration if it previously existed, otherwise null. - */ - public String remove(String name) { - return explicitConfigurations.remove(name); - } - - private String loadFromEnvironment(String name) { - return System.getenv(name); - } - - private String loadFromProperties(String name) { - return System.getProperty(name); - } - - public static final class EnvironmentVariablesConfigurationSource implements ConfigurationSource { - public static final ConfigurationSource GLOBAL_SOURCE = new EnvironmentVariablesConfigurationSource(); - Map configurations; - - private EnvironmentVariablesConfigurationSource() { - configurations = new HashMap<>(); - for (String config : DEFAULT_CONFIGURATIONS) { - String value = System.getenv(config); - if (value != null) { - configurations.put(config, value); - } - } - } - - @Override - public Map getProperties(String ignored) { - return configurations; - } - } -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/ImplUtils.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/ImplUtils.java deleted file mode 100644 index dd88ef33f2bd..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/ImplUtils.java +++ /dev/null @@ -1,635 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.implementation.util; - -import io.clientcore.core.http.models.HttpHeaderName; -import io.clientcore.core.http.models.HttpHeaders; -import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.util.configuration.Configuration; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.net.URI; -import java.nio.ByteBuffer; -import java.nio.charset.Charset; -import java.nio.charset.IllegalCharsetNameException; -import java.nio.charset.StandardCharsets; -import java.nio.charset.UnsupportedCharsetException; -import java.time.DateTimeException; -import java.time.Duration; -import java.time.OffsetDateTime; -import java.time.temporal.ChronoUnit; -import java.util.AbstractMap; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Objects; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.function.Function; -import java.util.function.Supplier; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Utility class containing implementation specific methods. - */ -public final class ImplUtils { - private static final HttpHeaderName RETRY_AFTER_MS_HEADER = HttpHeaderName.fromString("retry-after-ms"); - private static final HttpHeaderName X_MS_RETRY_AFTER_MS_HEADER = HttpHeaderName.fromString("x-ms-retry-after-ms"); - private static final Charset UTF_32BE = Charset.forName("UTF-32BE"); - private static final Charset UTF_32LE = Charset.forName("UTF-32LE"); - private static final byte ZERO = (byte) 0x00; - private static final byte BB = (byte) 0xBB; - private static final byte BF = (byte) 0xBF; - private static final byte EF = (byte) 0xEF; - private static final byte FE = (byte) 0xFE; - private static final byte FF = (byte) 0xFF; - private static final Pattern CHARSET_PATTERN = Pattern.compile("charset=(\\S+)\\b", Pattern.CASE_INSENSITIVE); - - /** - * Default sanitizer for a value, where it is simply replaced with "REDACTED". - */ - public static final Function DEFAULT_SANITIZER = value -> "REDACTED"; - - private ImplUtils() { - // Exists only to defeat instantiation. - } - - /** - * Checks if the array is null or empty. - * - * @param array Array being checked for nullness or emptiness. - * - * @return True if the array is null or empty, false otherwise. - */ - public static boolean isNullOrEmpty(Object[] array) { - return array == null || array.length == 0; - } - - /** - * Checks if the collection is null or empty. - * - * @param collection Collection being checked for nullness or emptiness. - * - * @return True if the collection is null or empty, false otherwise. - */ - public static boolean isNullOrEmpty(Collection collection) { - return collection == null || collection.isEmpty(); - } - - /** - * Checks if the map is null or empty. - * - * @param map Map being checked for nullness or emptiness. - * - * @return True if the map is null or empty, false otherwise. - */ - public static boolean isNullOrEmpty(Map map) { - return map == null || map.isEmpty(); - } - - /** - * Checks if the character sequence is null or empty. - * - * @param charSequence Character sequence being checked for nullness or emptiness. - * - * @return True if the character sequence is null or empty, false otherwise. - */ - public static boolean isNullOrEmpty(CharSequence charSequence) { - return charSequence == null || charSequence.isEmpty(); - } - - /** - * Optimized version of {@link String#join(CharSequence, Iterable)} when the {@code values} has a small set of - * object. - * - * @param delimiter Delimiter between the values. - * @param values The values to join. - * - * @return The {@code values} joined delimited by the {@code delimiter}. - * - * @throws NullPointerException If {@code delimiter} or {@code values} is null. - */ - public static String stringJoin(String delimiter, List values) { - Objects.requireNonNull(delimiter, "'delimiter' cannot be null."); - Objects.requireNonNull(values, "'values' cannot be null."); - - int count = values.size(); - - switch (count) { - case 0: - return ""; - - case 1: - return values.get(0); - - case 2: - return values.get(0) + delimiter + values.get(1); - - case 3: - return values.get(0) + delimiter + values.get(1) + delimiter + values.get(2); - - case 4: - return values.get(0) + delimiter + values.get(1) + delimiter + values.get(2) + delimiter - + values.get(3); - - case 5: - return values.get(0) + delimiter + values.get(1) + delimiter + values.get(2) + delimiter + values.get(3) - + delimiter + values.get(4); - - case 6: - return values.get(0) + delimiter + values.get(1) + delimiter + values.get(2) + delimiter + values.get(3) - + delimiter + values.get(4) + delimiter + values.get(5); - - case 7: - return values.get(0) + delimiter + values.get(1) + delimiter + values.get(2) + delimiter + values.get(3) - + delimiter + values.get(4) + delimiter + values.get(5) + delimiter + values.get(6); - - case 8: - return values.get(0) + delimiter + values.get(1) + delimiter + values.get(2) + delimiter + values.get(3) - + delimiter + values.get(4) + delimiter + values.get(5) + delimiter + values.get(6) + delimiter - + values.get(7); - - case 9: - return values.get(0) + delimiter + values.get(1) + delimiter + values.get(2) + delimiter + values.get(3) - + delimiter + values.get(4) + delimiter + values.get(5) + delimiter + values.get(6) + delimiter - + values.get(7) + delimiter + values.get(8); - - case 10: - return values.get(0) + delimiter + values.get(1) + delimiter + values.get(2) + delimiter + values.get(3) - + delimiter + values.get(4) + delimiter + values.get(5) + delimiter + values.get(6) + delimiter - + values.get(7) + delimiter + values.get(8) + delimiter + values.get(9); - - default: - return String.join(delimiter, values); - } - } - - /** - * Attempts to extract a retry after duration from a given set of {@link HttpHeaders}. - *

        - * This searches for the well-known retry after headers {@code Retry-After}, {@code retry-after-ms}, and - * {@code x-ms-retry-after-ms}. - *

        - * If no well-known headers are found null will be returned. - * - * @param headers The set of headers to search for a well-known retry after header. - * @param nowSupplier A supplier for the current time used when {@code Retry-After} is using relative retry after - * time. - * @return The retry after duration if a well-known retry after header was found, otherwise null. - */ - public static Duration getRetryAfterFromHeaders(HttpHeaders headers, Supplier nowSupplier) { - // Found 'x-ms-retry-after-ms' header, use a Duration of milliseconds based on the value. - Duration retryDelay = tryGetRetryDelay(headers, X_MS_RETRY_AFTER_MS_HEADER, ImplUtils::tryGetDelayMillis); - if (retryDelay != null) { - return retryDelay; - } - - // Found 'retry-after-ms' header, use a Duration of milliseconds based on the value. - retryDelay = tryGetRetryDelay(headers, RETRY_AFTER_MS_HEADER, ImplUtils::tryGetDelayMillis); - if (retryDelay != null) { - return retryDelay; - } - - // Found 'Retry-After' header. First, attempt to resolve it as a Duration of seconds. If that fails, then - // attempt to resolve it as an HTTP date (RFC1123). - retryDelay = tryGetRetryDelay(headers, HttpHeaderName.RETRY_AFTER, - headerValue -> tryParseLongOrDateTime(headerValue, nowSupplier)); - - // Either the retry delay will have been found or it'll be null, null indicates no retry after. - return retryDelay; - } - - private static Duration tryGetRetryDelay(HttpHeaders headers, HttpHeaderName headerName, - Function delayParser) { - String headerValue = headers.getValue(headerName); - - return isNullOrEmpty(headerValue) ? null : delayParser.apply(headerValue); - } - - private static Duration tryGetDelayMillis(String value) { - long delayMillis = tryParseLong(value); - return (delayMillis >= 0) ? Duration.ofMillis(delayMillis) : null; - } - - private static Duration tryParseLongOrDateTime(String value, Supplier nowSupplier) { - long delaySeconds; - try { - OffsetDateTime retryAfter = new DateTimeRfc1123(value).getDateTime(); - - delaySeconds = nowSupplier.get().until(retryAfter, ChronoUnit.SECONDS); - } catch (DateTimeException ex) { - delaySeconds = tryParseLong(value); - } - - return (delaySeconds >= 0) ? Duration.ofSeconds(delaySeconds) : null; - } - - private static long tryParseLong(String value) { - try { - return Long.parseLong(value); - } catch (NumberFormatException ex) { - return -1; - } - } - - /** - * Writes a {@link ByteBuffer} into an {@link OutputStream}. - *

        - * This method provides writing optimization based on the type of {@link ByteBuffer} and {@link OutputStream} - * passed. For example, if the {@link ByteBuffer} has a backing {@code byte[]} this method will access that directly - * to write to the {@code stream} instead of buffering the contents of the {@link ByteBuffer} into a temporary - * buffer. - * - * @param buffer The {@link ByteBuffer} to write into the {@code stream}. - * @param stream The {@link OutputStream} where the {@code buffer} will be written. - * @throws IOException If an I/O occurs while writing the {@code buffer} into the {@code stream}. - */ - public static void writeByteBufferToStream(ByteBuffer buffer, OutputStream stream) throws IOException { - // First check if the buffer has a backing byte[]. The backing byte[] can be accessed directly and written - // without an additional buffering byte[]. - if (buffer.hasArray()) { - // Write the byte[] from the current view position to the length remaining in the view. - stream.write(buffer.array(), buffer.position(), buffer.remaining()); - - // Update the position of the ByteBuffer to treat this the same as getting from the buffer. - buffer.position(buffer.position() + buffer.remaining()); - return; - } - - // Next begin checking for specific instances of OutputStream that may provide better writing options for - // direct ByteBuffers. - if (stream instanceof FileOutputStream) { - FileOutputStream fileOutputStream = (FileOutputStream) stream; - - // Writing to the FileChannel directly may provide native optimizations for moving the OS managed memory - // into the file. - // Write will move both the OutputStream's and ByteBuffer's position so there is no need to perform - // additional updates that are required when using the backing array. - fileOutputStream.getChannel().write(buffer); - return; - } - - // All optimizations have been exhausted, fallback to buffering write. - stream.write(byteBufferToArray(buffer)); - } - - /** - * Gets the content of the provided ByteBuffer as a byte array. This method will create a new byte array even if the - * ByteBuffer can have optionally backing array. - * - * @param byteBuffer the byte buffer - * @return the byte array - */ - public static byte[] byteBufferToArray(ByteBuffer byteBuffer) { - int length = byteBuffer.remaining(); - byte[] byteArray = new byte[length]; - byteBuffer.get(byteArray); - return byteArray; - } - - /** - * Utility method for parsing a {@link URI} into a {@link UriBuilder}. - * - * @param uri The URI being parsed. - * @param includeQuery Whether the query string should be excluded. - * @return The UriBuilder that represents the parsed URI. - */ - public static UriBuilder parseUri(URI uri, boolean includeQuery) { - final UriBuilder result = new UriBuilder(); - - if (uri != null) { - final String scheme = uri.getScheme(); - if (scheme != null && !scheme.isEmpty()) { - result.setScheme(scheme); - } - - final String host = uri.getHost(); - if (host != null && !host.isEmpty()) { - result.setHost(host); - } - - final int port = uri.getPort(); - if (port != -1) { - result.setPort(port); - } - - final String path = uri.getPath(); - if (path != null && !path.isEmpty()) { - result.setPath(path); - } - - final String query = uri.getQuery(); - if (query != null && !query.isEmpty() && includeQuery) { - result.setQuery(query); - } - } - - return result; - } - - public static final class QueryParameterIterable implements Iterable> { - private final String queryParameters; - - public QueryParameterIterable(String queryParameters) { - this.queryParameters = queryParameters; - } - - @Override - public Iterator> iterator() { - return new QueryParameterIterator(queryParameters); - } - } - - public static final class QueryParameterIterator implements Iterator> { - private final String queryParameters; - private final int queryParametersLength; - - private boolean done = false; - private int position; - - public QueryParameterIterator(String queryParameters) { - this.queryParameters = queryParameters; - this.queryParametersLength = queryParameters.length(); - - // If the URI query begins with '?' the first possible start of a query parameter key is the - // second character in the query. - position = (queryParameters.startsWith("?")) ? 1 : 0; - } - - @Override - public boolean hasNext() { - return !done; - } - - @Override - public Map.Entry next() { - if (done) { - throw new NoSuchElementException(); - } - - int nextPosition = position; - char c; - while (nextPosition < queryParametersLength) { - // Next position can either be '=' or '&' as a query parameter may not have a '=', ex 'key&key2=value'. - c = queryParameters.charAt(nextPosition); - if (c == '=') { - break; - } else if (c == '&') { - String key = queryParameters.substring(position, nextPosition); - - // Position is set to nextPosition + 1 to skip over the '&' - position = nextPosition + 1; - - return new AbstractMap.SimpleImmutableEntry<>(key, ""); - } - - nextPosition++; - } - - if (nextPosition == queryParametersLength) { - // Query parameters completed. - done = true; - return new AbstractMap.SimpleImmutableEntry<>(queryParameters.substring(position), ""); - } - - String key = queryParameters.substring(position, nextPosition); - - // Position is set to nextPosition + 1 to skip over the '=' - position = nextPosition + 1; - - nextPosition = queryParameters.indexOf('&', position); - - String value = null; - if (nextPosition == -1) { - // This was the last key-value pair in the query parameters 'https://example.com?param=done' - done = true; - value = queryParameters.substring(position); - } else { - value = queryParameters.substring(position, nextPosition); - // Position is set to nextPosition + 1 to skip over the '&' - position = nextPosition + 1; - } - - return new AbstractMap.SimpleImmutableEntry<>(key, value); - } - } - - /** - * Attempts to convert a byte stream into the properly encoded String. - *

        - * This utility method will attempt to find the encoding for the String in this order. - *

          - *
        1. Find the byte order mark in the byte array.
        2. - *
        3. Find the charset in the {@code contentType} header.
        4. - *
        5. Default to {@code UTF-8}.
        6. - *
        - * - * @param bytes The byte array. - * @param offset The starting offset in the byte array. - * @param count The number of bytes to process in the byte array. - * @param contentType The {@code Content-Type} header value. - * @return A string representation of the byte encoded to the found encoding, or null if {@code bytes} is null. - */ - public static String bomAwareToString(byte[] bytes, int offset, int count, String contentType) { - if (bytes == null) { - return null; - } - - if (count >= 3 && bytes[offset] == EF && bytes[offset + 1] == BB && bytes[offset + 2] == BF) { - return new String(bytes, 3, bytes.length - 3, StandardCharsets.UTF_8); - } else if (count >= 4 - && bytes[offset] == ZERO - && bytes[offset + 1] == ZERO - && bytes[offset + 2] == FE - && bytes[offset + 3] == FF) { - return new String(bytes, 4, bytes.length - 4, UTF_32BE); - } else if (count >= 4 - && bytes[offset] == FF - && bytes[offset + 1] == FE - && bytes[offset + 2] == ZERO - && bytes[offset + 3] == ZERO) { - return new String(bytes, 4, bytes.length - 4, UTF_32LE); - } else if (count >= 2 && bytes[offset] == FE && bytes[offset + 1] == FF) { - return new String(bytes, 2, bytes.length - 2, StandardCharsets.UTF_16BE); - } else if (count >= 2 && bytes[offset] == FF && bytes[offset + 1] == FE) { - return new String(bytes, 2, bytes.length - 2, StandardCharsets.UTF_16LE); - } else { - /* - * Attempt to retrieve the default charset from the 'Content-Encoding' header, if the value isn't - * present or invalid fallback to 'UTF-8' for the default charset. - */ - if (!isNullOrEmpty(contentType)) { - try { - Matcher charsetMatcher = CHARSET_PATTERN.matcher(contentType); - if (charsetMatcher.find()) { - return new String(bytes, offset, count, Charset.forName(charsetMatcher.group(1))); - } else { - return new String(bytes, offset, count, StandardCharsets.UTF_8); - } - } catch (IllegalCharsetNameException | UnsupportedCharsetException ex) { - return new String(bytes, offset, count, StandardCharsets.UTF_8); - } - } else { - return new String(bytes, offset, count, StandardCharsets.UTF_8); - } - } - } - - /** - * Gets either the system property or environment variable configuration for the passed environment. - *

        - * The system property is checked first, then the environment variable. If neither are found, null is returned. - * - * @param environmentConfiguration The environment to search. - * @param systemProperty The system property name. - * @param envVar The environment variable name. - * @param valueSanitizer The function to sanitize the value. - * @param logger The logger to log the property retrieval. - * @return The value of the property if found, otherwise null. - */ - public static String getFromEnvironment(EnvironmentConfiguration environmentConfiguration, String systemProperty, - String envVar, Function valueSanitizer, ClientLogger logger) { - if (systemProperty != null) { - final String value = environmentConfiguration.getSystemProperty(systemProperty); - if (value != null) { - logger.atVerbose() - .addKeyValue("systemProperty", systemProperty) - .addKeyValue("value", () -> valueSanitizer.apply(value)) - .log("Got property from system property."); - return value; - } - } - - if (envVar != null) { - final String value = environmentConfiguration.getEnvironmentVariable(envVar); - if (value != null) { - logger.atVerbose() - .addKeyValue("envVar", envVar) - .addKeyValue("value", () -> valueSanitizer.apply(value)) - .log("Got property from environment variable."); - return value; - } - } - - return null; - } - - /** - * Creates a {@link Thread} that will shut down the passed {@link ExecutorService} when ran. - *

        - * There are two phases to shut down, each will use half of the shutdown timeout. The first phase uses - * {@link ExecutorService#shutdown()} and awaits termination. If the executor does not terminate within half the - * timeout, the second phase will use {@link ExecutorService#shutdownNow()} and await termination. - * - * @param executorService The {@link ExecutorService} to shut down. - * @param shutdownTimeout The maximum time to wait for the executor to shut down. - * @return The {@link Thread} that will shut down the executor when ran. - */ - public static Thread createExecutorServiceShutdownThread(ExecutorService executorService, - Duration shutdownTimeout) { - long timeoutNanos = shutdownTimeout.toNanos(); - return new Thread(() -> { - try { - executorService.shutdown(); - if (!executorService.awaitTermination(timeoutNanos / 2, TimeUnit.NANOSECONDS)) { - executorService.shutdownNow(); - executorService.awaitTermination(timeoutNanos / 2, TimeUnit.NANOSECONDS); - } - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - executorService.shutdown(); - } - }); - } - - /** - * 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 CORE_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 CORE_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 ImplUtils is used within Configuration code and if this was done in - * the static constructor for ImplUtils it would cause a circular dependency, potentially causing a deadlock. - * Since this is in a static holder class, it will only be loaded when ImplUtils accesses it, which won't happen - * until ImplUtils is loaded. - */ - private static final class ShutdownHookAccessHelperHolder { - private static boolean shutdownHookAccessHelper; - - static { - shutdownHookAccessHelper = Boolean - .parseBoolean(Configuration.getGlobalConfiguration().get("CORE_ENABLE_SHUTDOWN_HOOK_WITH_PRIVILEGE")); - } - } - - static boolean isShutdownHookAccessHelper() { - return ShutdownHookAccessHelperHolder.shutdownHookAccessHelper; - } - - static void setShutdownHookAccessHelper(boolean shutdownHookAccessHelper) { - ShutdownHookAccessHelperHolder.shutdownHookAccessHelper = shutdownHookAccessHelper; - } -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/JsonSerializer.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/JsonSerializer.java deleted file mode 100644 index b9db02e6a314..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/JsonSerializer.java +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.implementation.util; - -import io.clientcore.core.implementation.TypeUtil; -import io.clientcore.core.serialization.json.JsonProviders; -import io.clientcore.core.serialization.json.JsonReader; -import io.clientcore.core.serialization.json.JsonSerializable; -import io.clientcore.core.serialization.json.JsonWriter; -import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.util.serializer.ObjectSerializer; -import io.clientcore.core.util.serializer.SerializationFormat; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Type; - -/** - * Class providing basic JSON serialization and deserialization methods. - *

        - * The implementation of this class is based on the usage of {@link JsonReader} and {@link JsonWriter}. - *

        - * The deserialization methods only work with primitive types, simple list and map collections, and models implementing - * {@link JsonSerializable}. Or, in code terms, types that are producible calling {@link JsonReader#readUntyped()} or - * provide a static factory method {@code fromJson(JsonReader)}. - *

        - * The serialization methods will work with any value but for complex types that don't implement - * {@link JsonSerializable} they will serialize the object using the type's {@code toString()} method. - */ -public class JsonSerializer implements ObjectSerializer { - private static final ClientLogger LOGGER = new ClientLogger(JsonSerializer.class); - - /** - * Creates an instance of the {@link JsonSerializer}. - */ - public JsonSerializer() { - } - - /** - * Reads a JSON byte array into its object representation. - * - * @param bytes The JSON byte array. - * @param type {@link Type} representing the object. - * @param Type of the object. - * @return The object represented by the deserialized JSON byte array. - * @throws IOException If the deserialization fails. - */ - @SuppressWarnings("unchecked") - @Override - public T deserializeFromBytes(byte[] bytes, Type type) throws IOException { - try (JsonReader jsonReader = JsonProviders.createReader(bytes)) { - if (type instanceof Class && JsonSerializable.class.isAssignableFrom(TypeUtil.getRawClass(type))) { - Class clazz = (Class) type; - - return (T) clazz.getMethod("fromJson", JsonReader.class).invoke(null, jsonReader); - } else { - return (T) jsonReader.readUntyped(); - } - } catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException e) { - throw LOGGER.logThrowableAsError(new RuntimeException(e)); - } - } - - /** - * Reads a JSON stream into its object representation. - * - * @param stream JSON stream. - * @param type {@link Type} representing the object. - * @param Type of the object. - * @return The object represented by the deserialized JSON stream. - * @throws IOException If the deserialization fails. - */ - @SuppressWarnings("unchecked") - @Override - public T deserializeFromStream(InputStream stream, Type type) throws IOException { - try (JsonReader jsonReader = JsonProviders.createReader(stream)) { - if (type instanceof Class && JsonSerializable.class.isAssignableFrom(TypeUtil.getRawClass(type))) { - Class clazz = (Class) type; - - return (T) clazz.getMethod("fromJson", JsonReader.class).invoke(null, jsonReader); - } else { - return (T) jsonReader.readUntyped(); - } - } catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException e) { - throw LOGGER.logThrowableAsError(new RuntimeException(e)); - } - } - - /** - * Converts the object into a JSON byte array. - * - * @param value The object. - * @return The JSON binary representation of the serialized object. - * @throws IOException If the serialization fails. - */ - @Override - public byte[] serializeToBytes(Object value) throws IOException { - if (value == null) { - return null; - } - - if (value instanceof JsonSerializable) { - return ((JsonSerializable) value).toJsonBytes(); - } - - try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - JsonWriter jsonWriter = JsonProviders.createWriter(byteArrayOutputStream)) { - - jsonWriter.writeUntyped(value); - jsonWriter.flush(); - - return byteArrayOutputStream.toByteArray(); - } - } - - /** - * Writes an object's JSON representation into a stream. - * - * @param stream {@link OutputStream} where the object's JSON representation will be written. - * @param value The object to serialize. - * @throws IOException If the serialization fails. - */ - @Override - public void serializeToStream(OutputStream stream, Object value) throws IOException { - if (value == null) { - return; - } - - try (JsonWriter jsonWriter = JsonProviders.createWriter(stream)) { - jsonWriter.writeUntyped(value); - } - } - - @Override - public final boolean supportsFormat(SerializationFormat format) { - return format == SerializationFormat.JSON; - } -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/UriToken.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/UriToken.java deleted file mode 100644 index ed8fffec398f..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/UriToken.java +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.implementation.util; - -class UriToken { - private final String text; - private final UriTokenType type; - - UriToken(String text, UriTokenType type) { - this.text = text; - this.type = type; - } - - String text() { - return text; - } - - UriTokenType type() { - return type; - } - - @Override - public boolean equals(Object rhs) { - return rhs instanceof UriToken && equals((UriToken) rhs); - } - - public boolean equals(UriToken rhs) { - return rhs != null && text.equals(rhs.text) && type == rhs.type; - } - - @Override - public String toString() { - return "\"" + text + "\" (" + type + ")"; - } - - @Override - public int hashCode() { - return (text == null ? 0 : text.hashCode()) ^ type.hashCode(); - } - - static UriToken scheme(String text) { - return new UriToken(text, UriTokenType.SCHEME); - } - - static UriToken host(String text) { - return new UriToken(text, UriTokenType.HOST); - } - - static UriToken port(String text) { - return new UriToken(text, UriTokenType.PORT); - } - - static UriToken path(String text) { - return new UriToken(text, UriTokenType.PATH); - } - - static UriToken query(String text) { - return new UriToken(text, UriTokenType.QUERY); - } -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/UriTokenType.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/UriTokenType.java deleted file mode 100644 index cc3e1b997216..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/UriTokenType.java +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.implementation.util; - -enum UriTokenType { - SCHEME, - - HOST, - - PORT, - - PATH, - - QUERY, -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/UriTokenizerState.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/UriTokenizerState.java deleted file mode 100644 index 722138963e47..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/UriTokenizerState.java +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.implementation.util; - -enum UriTokenizerState { - SCHEME, - - SCHEME_OR_HOST, - - HOST, - - PORT, - - PATH, - - QUERY, - - DONE -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/package-info.java deleted file mode 100644 index ddfa2b3c1399..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - * Package containing implementation-specific utility APIs that should not be used by end-users. - */ -package io.clientcore.core.implementation.util; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/AuthenticateChallengeParser.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/AuthenticateChallengeParser.java new file mode 100644 index 000000000000..35ed17e6445e --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/AuthenticateChallengeParser.java @@ -0,0 +1,529 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.implementation.utils; + +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.utils.AuthenticateChallenge; + +import java.util.AbstractMap; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.function.Predicate; + +/** + * Parses a {@link HttpHeaderName#WWW_AUTHENTICATE} or {@link HttpHeaderName#PROXY_AUTHENTICATE} header value into the + * pieces required to create one or more {@link AuthenticateChallenge}. + */ +public final class AuthenticateChallengeParser { + private static final ClientLogger LOGGER = new ClientLogger(AuthenticateChallengeParser.class); + + private static final boolean[] VALID_TOKEN_CHARS = new boolean[128]; + private static final boolean[] VALID_TOKEN68_CHARS = new boolean[128]; + + static { + // Setup VALID_TOKEN68_CHARS first as it is mostly a subset of VALID_TCHARS. + // The only exception is that token68 allows '/', set that after copying. + // This is also excluding the '=' character as that is only allowed at the end of a token68 and will be handled + // externally to this lookup table. + Arrays.fill(VALID_TOKEN68_CHARS, '0', '9' + 1, true); + Arrays.fill(VALID_TOKEN68_CHARS, 'A', 'Z' + 1, true); + Arrays.fill(VALID_TOKEN68_CHARS, 'a', 'z' + 1, true); + VALID_TOKEN68_CHARS['-'] = true; + VALID_TOKEN68_CHARS['.'] = true; + VALID_TOKEN68_CHARS['_'] = true; + VALID_TOKEN68_CHARS['~'] = true; + VALID_TOKEN68_CHARS['+'] = true; + + System.arraycopy(VALID_TOKEN68_CHARS, 0, VALID_TOKEN_CHARS, 0, 128); + VALID_TOKEN_CHARS['!'] = true; + VALID_TOKEN_CHARS['#'] = true; + VALID_TOKEN_CHARS['$'] = true; + VALID_TOKEN_CHARS['%'] = true; + VALID_TOKEN_CHARS['&'] = true; + VALID_TOKEN_CHARS['\''] = true; + VALID_TOKEN_CHARS['*'] = true; + VALID_TOKEN_CHARS['^'] = true; + VALID_TOKEN_CHARS['`'] = true; + VALID_TOKEN_CHARS['|'] = true; + + VALID_TOKEN68_CHARS['/'] = true; + } + + private final String challenge; + private final int challengeLength; + + private State state = State.BEGINNING; + private int currentIndex; + private AuthenticateChallengeToken token; + + /** + * Creates an instance of AuthenticateChallengeParser. + * + * @param challenge The challenge to parse. + */ + public AuthenticateChallengeParser(String challenge) { + this.challenge = Objects.requireNonNull(challenge, "challenge cannot be null."); + this.challengeLength = challenge.length(); + this.currentIndex = 0; + + // WWW-Authenticate and Proxy-Authenticate use the form: + // + // *( "," OWS ) challenge *( OWS "," [ OWS challenge ] ) + // + // Which means the header may begin with any number of ',', SP (U+0020 / ' '), and HTAB (U+0009 / '\t') + // characters. Skip those characters. + while (currentIndex < challengeLength) { + char currentCharacter = challenge.charAt(currentIndex); + if (currentCharacter != ',' && currentCharacter != ' ' && currentCharacter != '\t') { + break; + } + + currentIndex++; + } + } + + /** + * Parses the authenticate header into a list of {@link AuthenticateChallenge}. + * + * @return A list of {@link AuthenticateChallenge}. + * @throws IllegalArgumentException If the authenticate header is malformed. + */ + public List parse() { + // At a high-level the authenticate headers take the form of: + // WWW-Authenticate: , , ... + // Proxy-Authenticate: , , ... + // + // At a more technical level, which this method will parse the format (using ABNF) is: + // + // authenticate-header = 1#challenge (at lease one challenge, delimited by ',' and optional spaces) + // challenge = auth-scheme [ 1*SP ( token68 / #auth-param ) ] (may contain a token68 or 0 or more auth-params) + // auth-scheme = token + // auth-param = token BWS "=" BWS ( token / quoted-string ) + // token68 = 1*( ALPHA / DIGIT / - / . / _ / ~ / + / '/' ) *"=" + // quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE + // qdtext = HTAB / SP / ! / '#' - '[' / ']' - '~' / obs-text + // quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + // obs-text = U+0080 - U+00FF (extended ASCII) + // token = 1*( tchar ) + // tchar = ALPHA / DIGIT / ! / # / $ / % / & / ' / * / + / - / . / ^ / _ / ` / | / ~ + // VCHAR = U+0021 - U+007E (! - ~, or all printable ASCII characters except space and delete) + // + // BWS is optional spaces (SP / HTAB) that exists for historical reasons and should be handled during parsing + // but must not be generated. + // + // All information above is taken from RFC 7230 and RFC 7235. + // https://www.rfc-editor.org/rfc/rfc7230 + // https://www.rfc-editor.org/rfc/rfc7235 + // + // WWW-Authenticate and Proxy-Authenticate use the form: + // + // *( "," OWS ) challenge *( OWS "," [ OWS challenge ] ) + // + // Which means the header may begin with any number of ',', SP (U+0020 / ' '), and HTAB (U+0009 / '\t') + // characters. Skip those characters. + // + // Then replacing 'challenge' with its definition it becomes: + // + // *( "," OWS ) auth-scheme [ 1*SP ( token68 / #auth-param ) ] + // *( OWS "," [ OWS auth-scheme [ 1*SP ( token68 / #auth-param ) ] ] ) + // + // Where the auth-scheme and token68 / auth-params are separated by SP characters only. The logic for parsing + // will be the following: + // + // 1. Skip any leading spaces and commas. + // 2. Split the authenticate header into chunks delimited by commas that aren't within a quoted string. + // 3. Remove any leading or trailing OWS (optional spaces) from each chunk. + // 4. Process each chunk, keeping track of the current state of the parser, using the following logic: + // + // I. If it's the first chunk being processed it must contain a scheme. Optionally, that chunk may also include + // a token68 or an auth-param after the scheme separated by SP characters. If the first chunk isn't a scheme, + // an IllegalArgumentException will be thrown. + // II. Subsequent chunks will use the following logic: + // i. If the chunk contains unquoted SP characters separating token characters (or roughly the equivalent for + // valid token68 characters), then the chunk is a new challenge scheme. + // ii. If the chunk contains equal signs, then the chunk is either a token68 or an auth-param. Determine + // which one based on where the equal signs are, if the equal signs are the trailing characters of the + // chunk it's a token68 otherwise it's an auth-param. + // III. If the chunk is a token68 or an auth-param, then add it to the current challenge. + // i. If the current challenge already contains a token68 then any subsequent token68 or auth-params will + // throw an IllegalArgumentException. + // IV. Once a new challenge scheme is found, the previous challenge is added to the list and state is reset. + List authenticateChallenges = new ArrayList<>(); + + String scheme = null; + String token68 = null; + Map parameters = null; + + while (next()) { + if (token.scheme != null) { + // This piece contained a scheme. + // This is either the first scheme or a new scheme, handle it appropriately. + if (scheme != null) { + // This is a new scheme, add the previous challenge to the list. + authenticateChallenges.add(createChallenge(scheme, token68, parameters)); + parameters = null; + token68 = null; + } + + scheme = token.scheme; + } else if (token.token68 != null) { + if (scheme == null) { + throw LOGGER.atError() + .addKeyValue("challenge", challenge) + .log(new IllegalArgumentException("Challenge had token68 before scheme.")); + } else if (token68 != null) { + throw LOGGER.atError() + .addKeyValue("challenge", challenge) + .log(new IllegalArgumentException("Challenge had multiple token68s.")); + } + + token68 = token.token68; + } else if (token.authParam != null) { + if (scheme == null) { + throw LOGGER.atError() + .addKeyValue("challenge", challenge) + .log(new IllegalArgumentException("Challenge had auth-param before scheme.")); + } + + if (parameters == null) { + parameters = new LinkedHashMap<>(); + } + + if (parameters.put(token.authParam.getKey(), token.authParam.getValue()) != null) { + throw LOGGER.atError() + .addKeyValue("challenge", challenge) + .log(new IllegalArgumentException("Challenge had duplicate auth-param.")); + } + } + } + + if (scheme != null) { + authenticateChallenges.add(createChallenge(scheme, token68, parameters)); + } + + return authenticateChallenges; + } + + private AuthenticateChallenge createChallenge(String scheme, String token68, Map parameters) { + if (token68 == null && parameters == null) { + return new AuthenticateChallenge(scheme); + } else if (token68 == null) { + return new AuthenticateChallenge(scheme, parameters); + } else if (parameters == null) { + return new AuthenticateChallenge(scheme, token68); + } + + throw LOGGER.atError() + .addKeyValue("challenge", challenge) + .log(new IllegalArgumentException("Challenge had both token68 and auth-params.")); + } + + boolean next() { + if (currentIndex >= challengeLength) { + return false; + } + + if (state == State.BEGINNING) { + handleBeginning(); + } else if (state == State.SCHEME) { + handleScheme(); + } else if (state == State.CHALLENGE_SEPARATOR) { + handleChallenge(); + } + + return true; + } + + private char iterateUntil(Predicate until) { + while (currentIndex < challengeLength) { + char c = challenge.charAt(currentIndex); + if (until.test(c)) { + return c; + } + + currentIndex++; + } + + return '\0'; + } + + private char iterateUntilNextNonSpace() { + currentIndex++; + return iterateUntil(c -> c != ' ' && c != '\t'); + } + + private char iterateUntilEqualsSpaceOrComma() { + return iterateUntil(c -> c == '=' || c == ' ' || c == ','); + } + + private void handleBeginning() { + // If the state is BEGINNING, then the next token must be a scheme. + // Beginning state is the state before any characters have been processed (except leading spaces and commas). + // The only valid characters in this case are one or more token characters followed by one of spaces or comma. + int start = currentIndex; + char c = iterateUntil(c1 -> c1 == ' ' || c1 == '\t' || c1 == ','); + + token = handleSchemeToken(start, currentIndex, c, false); + } + + private AuthenticateChallengeToken handleSchemeToken(int schemeStartInclusive, int schemeEndExclusive, + char currentChar, boolean alreadyInNextState) { + String scheme = challenge.substring(schemeStartInclusive, schemeEndExclusive); + if (!isValidToken(scheme)) { + throw LOGGER.atError() + .addKeyValue("challenge", challenge) + .addKeyValue("scheme", scheme) + .log(new IllegalArgumentException("Scheme contained an invalid character.")); + } + + // Iterate until the next non-space character, unless the scheme terminated with a comma. + currentChar = (alreadyInNextState || currentChar == ',') ? currentChar : iterateUntilNextNonSpace(); + if (currentIndex < challengeLength && currentChar == ',') { + // The next character is a comma, update the state to CHALLENGE_SEPARATOR and continue. + // This is important as SCHEME indicates that the next token is either a token68 or an auth-param. + // CHALLENGE_SEPARATOR indicates that the next token can be anything. + state = State.CHALLENGE_SEPARATOR; + iterateUntilNextNonSpace(); // Iterate to the first character in the challenge piece. + } else { + state = State.SCHEME; + } + + return new AuthenticateChallengeToken(scheme, null, null); + } + + private void handleScheme() { + // If the state is SCHEME, then the next token must be a token68 or an auth-param. + // Search until a comma, space, or equal sign is found. + // If a comma is found or the end of challenge reached the current token is a token68 as auth-param requires an + // equal sign whereas token68 those are optional padding. + // If a space is found, the current token could be either an auth-param or a token68. Iterate until the next + // non-space is found or the end of challenge is reached. If a comma is found or end of challenge reached then + // it's a token68, if an equal sign is found then it's an auth-param, if anything else is found it's an error. + // If an equal sign is found, check if there are equal signs until a space, comma, or end of challenge, then + // it's a token68, otherwise it's an auth-param. + int start = currentIndex; // This start will never have leading space. + char c = iterateUntilEqualsSpaceOrComma(); + + if (c == ',' || currentIndex == challengeLength) { + // As stated above, must be a token68. + token = new AuthenticateChallengeToken(null, validateToken68(challenge, start, currentIndex), null); + } else if (c == ' ') { + int token68OrParamKeyEnd = currentIndex; + c = iterateUntilNextNonSpace(); + if (c != '=' && c != ',' && currentIndex < challengeLength) { + // The next character is neither a comma nor an equal sign, throw an exception. + throw LOGGER.atError() + .addKeyValue("challenge", challenge) + .log(new IllegalArgumentException( + "Challenge had more than one token68 or auth-param in the same comma separator.")); + } + + if (c == ',' || currentIndex == challengeLength) { + String token68 = validateToken68(challenge, start, currentIndex); + token = new AuthenticateChallengeToken(null, token68, null); + } else { + createAuthParamToken(start, token68OrParamKeyEnd, iterateUntilNextNonSpace()); + } + } else { + int equalsIndex = currentIndex; + + // If the equals index is the last character or the next character is another equal sign, then it's a + // token68. + if (currentIndex + 1 == challengeLength || challenge.charAt(currentIndex + 1) == '=') { + // Two equal signs in a row, must be a token68. + c = iterateUntil(c1 -> c1 != '='); + token = new AuthenticateChallengeToken(null, validateToken68(challenge, start, currentIndex), null); + } else { + // Otherwise check what the next non-space character is after the equals sign. If it's a comma or end of + // challenge then it's a token68, otherwise it's an auth-param. + c = iterateUntilNextNonSpace(); + if (c == ',' || currentIndex == challengeLength) { + // It's a token68. + token = new AuthenticateChallengeToken(null, validateToken68(challenge, start, equalsIndex + 1), + null); + } else { + // It's a challenge parameter. + c = createAuthParamToken(start, equalsIndex, c); + } + } + + // If the character following the last equal sign isn't a comma or end of challenge, there is an error. + c = (c == ',' || currentIndex == challengeLength) ? c : iterateUntilNextNonSpace(); + if (currentIndex < challengeLength && c != ',') { + throw LOGGER.atError() + .addKeyValue("challenge", challenge) + .log(new IllegalArgumentException( + "Challenge had more than one token68 or auth-param in the same comma separator.")); + } + } + + // Update state to the next state, which is CHALLENGE_SEPARATOR and skip over the comma. + state = State.CHALLENGE_SEPARATOR; + iterateUntilNextNonSpace(); + } + + private char createAuthParamToken(int keyStartInclusive, int keyEndExclusive, char currentChar) { + String authParamKey = challenge.substring(keyStartInclusive, keyEndExclusive); + if (!isValidToken(authParamKey)) { + throw LOGGER.atError() + .addKeyValue("challenge", challenge) + .addKeyValue("authParamKey", authParamKey) + .log(new IllegalArgumentException("Auth-param key contained an invalid character.")); + } + + int start = currentIndex; + String authParamValue; + if (currentChar == '"') { + // Iterate until the next character, which is either the start of a quoted-string or another '"' denoting an + // empty quoted-string. + currentIndex++; + start++; + + // Iterate until a closing double quote which isn't escaped by a backslash. + currentChar = iterateUntil(c1 -> c1 == '"' && challenge.charAt(currentIndex - 1) != '\\'); + if (currentChar != '"') { + // Only time this should happen is reaching the end of the challenge. + throw LOGGER.atError() + .addKeyValue("challenge", challenge) + .log(new IllegalArgumentException("Quoted-string was not terminated with a double quote.")); + } + + authParamValue = challenge.substring(start, currentIndex).replace("\\\\", ""); + } else { + // Handle as a token. + currentChar = iterateUntil(c1 -> c1 == ' ' || c1 == '\t' || c1 == ','); + authParamValue = challenge.substring(start, currentIndex); + if (!isValidToken(authParamValue)) { + throw LOGGER.atError() + .addKeyValue("challenge", challenge) + .addKeyValue("authParamValue", authParamValue) + .log(new IllegalArgumentException("Auth-param value contained an invalid character.")); + } + } + + // Iterate until the next non-space character. + currentChar = (currentChar == ',') ? currentChar : iterateUntilNextNonSpace(); + + // After the scheme only a single token68 or auth-param is allowed. If after any trailing spaces the next + // character isn't a comma throw an exception. + if (currentIndex < challengeLength && currentChar != ',') { + throw LOGGER.atError() + .addKeyValue("challenge", challenge) + .log(new IllegalArgumentException( + "Challenge had more than one token68 or auth-param in the same comma separator.")); + } + + token = new AuthenticateChallengeToken(null, null, new AbstractMap.SimpleEntry<>(authParamKey, authParamValue)); + return currentChar; + } + + private void handleChallenge() { + // If the state is CHALLENGE_SEPARATOR, then the next token can be either new challenge scheme or an auth-param. + // Skip any leading spaces. + // Search until an equal sign, comma, space, or end of challenge is found. + // If a comma is found or the end of challenge reached the current token is a scheme without any auth-params or + // a token68. + // If an equal sign is found, then the current token is an auth-param as that isn't allowed in a scheme. + // If a space is found search for the next non-space character. If it's an equal sign then it's an auth-param, + // otherwise this is the beginning of a new scheme. + int start = currentIndex; + + char c = iterateUntil(c1 -> c1 == ' ' || c1 == '\t' || c1 == ',' || c1 == '='); + + if (c == ',' || currentIndex == challengeLength) { + // Scheme without any auth-params or a token68. + // handleSchemeToken will set the state to SCHEME or CHALLENGE_START based on the next character. + token = handleSchemeToken(start, currentIndex, c, true); + } else if (c == '=') { + // Auth-param for the challenge currently being parsed. + createAuthParamToken(start, currentIndex, iterateUntilNextNonSpace()); + state = State.CHALLENGE_SEPARATOR; + iterateUntilNextNonSpace(); + } else { + // Can either be a new scheme or an auth-param based on the next non-space character. + int end = currentIndex; // This end will either be the new scheme end or the auth-param key end. + c = iterateUntilNextNonSpace(); + if (c == '=') { + // Auth-param for the challenge currently being parsed. + createAuthParamToken(start, end, iterateUntilNextNonSpace()); + state = State.CHALLENGE_SEPARATOR; + iterateUntilNextNonSpace(); + } else { + // New scheme. + token = handleSchemeToken(start, end, c, true); + } + } + } + + private static boolean isValidTokenCharacter(char c) { + // token = 1*( ALPHA / DIGIT / ! / # / $ / % / & / ' / * / + / - / . / ^ / _ / ` / | / ~ ) + return c < 128 && VALID_TOKEN_CHARS[c]; + } + + private static boolean isValidToken(String token) { + for (int i = 0; i < token.length(); i++) { + char c = token.charAt(i); + if (!isValidTokenCharacter(c)) { + return false; + } + } + + return true; + } + + private static boolean isValidToken68Character(char c) { + // token68 = 1*( ALPHA / DIGIT / - / . / _ / ~ / + / '/' ) *"=" + return c < 128 && VALID_TOKEN68_CHARS[c]; + } + + private static String validateToken68(String challenge, int start, int end) { + for (int i = start; i < end; i++) { + char c = challenge.charAt(i); + if (c == '=') { + // From this point onwards the only valid character is '='. + i++; + while (i < end) { + c = challenge.charAt(i); + if (c != '=') { + throw LOGGER.atError() + .addKeyValue("challenge", challenge) + .addKeyValue("token68", challenge.substring(start, end)) + .addKeyValue("character", c) + .log(new IllegalArgumentException("Token68 contained invalid character.")); + } + + i++; + } + } else if (!isValidToken68Character(c)) { + throw LOGGER.atError() + .addKeyValue("challenge", challenge) + .addKeyValue("token68", challenge.substring(start, end)) + .addKeyValue("character", c) + .log(new IllegalArgumentException("Token68 contained invalid character.")); + } + } + + return challenge.substring(start, end); + } + + private enum State { + BEGINNING, CHALLENGE_SEPARATOR, SCHEME + } + + private static class AuthenticateChallengeToken { + final String scheme; + final String token68; + final Map.Entry authParam; + + AuthenticateChallengeToken(String scheme, String token68, Map.Entry authParam) { + this.scheme = scheme; + this.token68 = token68; + this.authParam = authParam; + } + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/ImplUtils.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/ImplUtils.java new file mode 100644 index 000000000000..1146d4d19c20 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/ImplUtils.java @@ -0,0 +1,467 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.implementation.utils; + +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.utils.CoreUtils; +import io.clientcore.core.utils.configuration.Configuration; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.nio.charset.IllegalCharsetNameException; +import java.nio.charset.StandardCharsets; +import java.nio.charset.UnsupportedCharsetException; +import java.time.Duration; +import java.util.AbstractMap; +import java.util.Iterator; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Utility class containing implementation specific methods. + */ +public final class ImplUtils { + private static final ClientLogger LOGGER = new ClientLogger(ImplUtils.class); + + private static final Charset UTF_32BE = Charset.forName("UTF-32BE"); + private static final Charset UTF_32LE = Charset.forName("UTF-32LE"); + private static final byte ZERO = (byte) 0x00; + private static final byte BB = (byte) 0xBB; + private static final byte BF = (byte) 0xBF; + private static final byte EF = (byte) 0xEF; + private static final byte FE = (byte) 0xFE; + private static final byte FF = (byte) 0xFF; + private static final Pattern CHARSET_PATTERN = Pattern.compile("charset=(\\S+)\\b", Pattern.CASE_INSENSITIVE); + + private static final Duration DEFAULT_HTTP_CONNECT_TIMEOUT; + private static final Duration DEFAULT_HTTP_WRITE_TIMEOUT; + private static final Duration DEFAULT_HTTP_RESPONSE_TIMEOUT; + private static final Duration DEFAULT_HTTP_READ_TIMEOUT; + + static { + Configuration configuration = Configuration.getGlobalConfiguration(); + DEFAULT_HTTP_CONNECT_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, + Configuration.REQUEST_CONNECT_TIMEOUT_IN_MS, Duration.ofSeconds(10), LOGGER); + DEFAULT_HTTP_WRITE_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, + Configuration.REQUEST_WRITE_TIMEOUT_IN_MS, Duration.ofSeconds(60), LOGGER); + DEFAULT_HTTP_RESPONSE_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, + Configuration.REQUEST_RESPONSE_TIMEOUT_IN_MS, Duration.ofSeconds(60), LOGGER); + DEFAULT_HTTP_READ_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, + Configuration.REQUEST_READ_TIMEOUT_IN_MS, Duration.ofSeconds(60), LOGGER); + } + + private ImplUtils() { + // Exists only to defeat instantiation. + } + + /** + * Attempts to load an environment configured default timeout. + *

        + * If the environment default timeout isn't configured, {@code defaultTimeout} will be returned. If the environment + * default timeout is a string that isn't parseable by {@link Long#parseLong(String)}, {@code defaultTimeout} will + * be returned. If the environment default timeout is less than 0, {@link Duration#ZERO} will be returned indicated + * that there is no timeout period. + * + * @param configuration The environment configurations. + * @param timeoutPropertyName The default timeout property name. + * @param defaultTimeout The fallback timeout to be used. + * @param logger A {@link ClientLogger} to log exceptions. + * @return Either the environment configured default timeout, {@code defaultTimeoutMillis}, or 0. + */ + public static Duration getDefaultTimeoutFromEnvironment(Configuration configuration, String timeoutPropertyName, + Duration defaultTimeout, ClientLogger logger) { + String environmentTimeout = configuration.get(timeoutPropertyName); + + // Environment wasn't configured with the timeout property. + if (environmentTimeout == null || environmentTimeout.isEmpty()) { + return defaultTimeout; + } + + try { + long timeoutMillis = Long.parseLong(environmentTimeout); + if (timeoutMillis < 0) { + logger.atVerbose() + .addKeyValue(timeoutPropertyName, timeoutMillis) + .log("Negative timeout values are not allowed. Using 'Duration.ZERO' to indicate no timeout."); + return Duration.ZERO; + } + + return Duration.ofMillis(timeoutMillis); + } catch (NumberFormatException ex) { + logger.atInfo() + .addKeyValue(timeoutPropertyName, environmentTimeout) + .addKeyValue("defaultTimeout", defaultTimeout) + .log("Timeout is not valid number. Using default value.", ex); + + return defaultTimeout; + } + } + + /** + * Writes a {@link ByteBuffer} into an {@link OutputStream}. + *

        + * This method provides writing optimization based on the type of {@link ByteBuffer} and {@link OutputStream} + * passed. For example, if the {@link ByteBuffer} has a backing {@code byte[]} this method will access that directly + * to write to the {@code stream} instead of buffering the contents of the {@link ByteBuffer} into a temporary + * buffer. + * + * @param buffer The {@link ByteBuffer} to write into the {@code stream}. + * @param stream The {@link OutputStream} where the {@code buffer} will be written. + * @throws IOException If an I/O occurs while writing the {@code buffer} into the {@code stream}. + */ + public static void writeByteBufferToStream(ByteBuffer buffer, OutputStream stream) throws IOException { + // First check if the buffer has a backing byte[]. The backing byte[] can be accessed directly and written + // without an additional buffering byte[]. + if (buffer.hasArray()) { + // Write the byte[] from the current view position to the length remaining in the view. + stream.write(buffer.array(), buffer.position(), buffer.remaining()); + + // Update the position of the ByteBuffer to treat this the same as getting from the buffer. + buffer.position(buffer.position() + buffer.remaining()); + return; + } + + // Next begin checking for specific instances of OutputStream that may provide better writing options for + // direct ByteBuffers. + if (stream instanceof FileOutputStream) { + FileOutputStream fileOutputStream = (FileOutputStream) stream; + + // Writing to the FileChannel directly may provide native optimizations for moving the OS managed memory + // into the file. + // Write will move both the OutputStream's and ByteBuffer's position so there is no need to perform + // additional updates that are required when using the backing array. + fileOutputStream.getChannel().write(buffer); + return; + } + + // All optimizations have been exhausted, fallback to buffering write. + stream.write(byteBufferToArray(buffer)); + } + + /** + * Gets the content of the provided ByteBuffer as a byte array. This method will create a new byte array even if the + * ByteBuffer can have optionally backing array. + * + * @param byteBuffer the byte buffer + * @return the byte array + */ + public static byte[] byteBufferToArray(ByteBuffer byteBuffer) { + int length = byteBuffer.remaining(); + byte[] byteArray = new byte[length]; + byteBuffer.get(byteArray); + return byteArray; + } + + public static final class QueryParameterIterable implements Iterable> { + private final String queryParameters; + + public QueryParameterIterable(String queryParameters) { + this.queryParameters = queryParameters; + } + + @Override + public Iterator> iterator() { + return new QueryParameterIterator(queryParameters); + } + } + + public static final class QueryParameterIterator implements Iterator> { + private final String queryParameters; + private final int queryParametersLength; + + private boolean done; + private int position; + + public QueryParameterIterator(String queryParameters) { + this.queryParameters = queryParameters; + this.done = CoreUtils.isNullOrEmpty(queryParameters); + + if (done) { + this.position = 0; + this.queryParametersLength = 0; + } else { + this.queryParametersLength = queryParameters.length(); + + // If the URI query begins with '?' the first possible start of a query parameter key is the + // second character in the query. + position = (queryParameters.startsWith("?")) ? 1 : 0; + } + } + + @Override + public boolean hasNext() { + return !done; + } + + @Override + public Map.Entry next() { + if (done) { + throw new NoSuchElementException(); + } + + int nextPosition = position; + char c; + while (nextPosition < queryParametersLength) { + // Next position can either be '=' or '&' as a query parameter may not have a '=', ex 'key&key2=value'. + c = queryParameters.charAt(nextPosition); + if (c == '=') { + break; + } else if (c == '&') { + String key = queryParameters.substring(position, nextPosition); + + // Position is set to nextPosition + 1 to skip over the '&' + position = nextPosition + 1; + + return new AbstractMap.SimpleImmutableEntry<>(key, ""); + } + + nextPosition++; + } + + if (nextPosition == queryParametersLength) { + // Query parameters completed. + done = true; + return new AbstractMap.SimpleImmutableEntry<>(queryParameters.substring(position), ""); + } + + String key = queryParameters.substring(position, nextPosition); + + // Position is set to nextPosition + 1 to skip over the '=' + position = nextPosition + 1; + + nextPosition = queryParameters.indexOf('&', position); + + String value = null; + if (nextPosition == -1) { + // This was the last key-value pair in the query parameters 'https://example.com?param=done' + done = true; + value = queryParameters.substring(position); + } else { + value = queryParameters.substring(position, nextPosition); + // Position is set to nextPosition + 1 to skip over the '&' + position = nextPosition + 1; + } + + return new AbstractMap.SimpleImmutableEntry<>(key, value); + } + } + + /** + * Attempts to convert a byte stream into the properly encoded String. + *

        + * This utility method will attempt to find the encoding for the String in this order. + *

          + *
        1. Find the byte order mark in the byte array.
        2. + *
        3. Find the charset in the {@code contentType} header.
        4. + *
        5. Default to {@code UTF-8}.
        6. + *
        + * + * @param bytes The byte array. + * @param offset The starting offset in the byte array. + * @param count The number of bytes to process in the byte array. + * @param contentType The {@code Content-Type} header value. + * @return A string representation of the byte encoded to the found encoding, or null if {@code bytes} is null. + */ + public static String bomAwareToString(byte[] bytes, int offset, int count, String contentType) { + if (bytes == null) { + return null; + } + + if (count >= 3 && bytes[offset] == EF && bytes[offset + 1] == BB && bytes[offset + 2] == BF) { + return new String(bytes, 3, bytes.length - 3, StandardCharsets.UTF_8); + } else if (count >= 4 + && bytes[offset] == ZERO + && bytes[offset + 1] == ZERO + && bytes[offset + 2] == FE + && bytes[offset + 3] == FF) { + return new String(bytes, 4, bytes.length - 4, UTF_32BE); + } else if (count >= 4 + && bytes[offset] == FF + && bytes[offset + 1] == FE + && bytes[offset + 2] == ZERO + && bytes[offset + 3] == ZERO) { + return new String(bytes, 4, bytes.length - 4, UTF_32LE); + } else if (count >= 2 && bytes[offset] == FE && bytes[offset + 1] == FF) { + return new String(bytes, 2, bytes.length - 2, StandardCharsets.UTF_16BE); + } else if (count >= 2 && bytes[offset] == FF && bytes[offset + 1] == FE) { + return new String(bytes, 2, bytes.length - 2, StandardCharsets.UTF_16LE); + } else { + /* + * Attempt to retrieve the default charset from the 'Content-Encoding' header, if the value isn't + * present or invalid fallback to 'UTF-8' for the default charset. + */ + if (!CoreUtils.isNullOrEmpty(contentType)) { + try { + Matcher charsetMatcher = CHARSET_PATTERN.matcher(contentType); + if (charsetMatcher.find()) { + return new String(bytes, offset, count, Charset.forName(charsetMatcher.group(1))); + } else { + return new String(bytes, offset, count, StandardCharsets.UTF_8); + } + } catch (IllegalCharsetNameException | UnsupportedCharsetException ex) { + return new String(bytes, offset, count, StandardCharsets.UTF_8); + } + } else { + return new String(bytes, offset, count, StandardCharsets.UTF_8); + } + } + } + + /** + * Creates a {@link Thread} that will shut down the passed {@link ExecutorService} when ran. + *

        + * There are two phases to shut down, each will use half of the shutdown timeout. The first phase uses + * {@link ExecutorService#shutdown()} and awaits termination. If the executor does not terminate within half the + * timeout, the second phase will use {@link ExecutorService#shutdownNow()} and await termination. + * + * @param executorService The {@link ExecutorService} to shut down. + * @param shutdownTimeout The maximum time to wait for the executor to shut down. + * @return The {@link Thread} that will shut down the executor when ran. + */ + public static Thread createExecutorServiceShutdownThread(ExecutorService executorService, + Duration shutdownTimeout) { + long timeoutNanos = shutdownTimeout.toNanos(); + return new Thread(() -> { + try { + executorService.shutdown(); + if (!executorService.awaitTermination(timeoutNanos / 2, TimeUnit.NANOSECONDS)) { + executorService.shutdownNow(); + executorService.awaitTermination(timeoutNanos / 2, TimeUnit.NANOSECONDS); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + executorService.shutdown(); + } + }); + } + + /** + * 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 CORE_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 CORE_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 ImplUtils is used within Configuration code and if this was done in + * the static constructor for ImplUtils it would cause a circular dependency, potentially causing a deadlock. + * Since this is in a static holder class, it will only be loaded when ImplUtils accesses it, which won't happen + * until ImplUtils is loaded. + */ + private static final class ShutdownHookAccessHelperHolder { + private static boolean shutdownHookAccessHelper; + + static { + shutdownHookAccessHelper = Boolean + .parseBoolean(Configuration.getGlobalConfiguration().get("CORE_ENABLE_SHUTDOWN_HOOK_WITH_PRIVILEGE")); + } + } + + static boolean isShutdownHookAccessHelper() { + return ShutdownHookAccessHelperHolder.shutdownHookAccessHelper; + } + + static void setShutdownHookAccessHelper(boolean shutdownHookAccessHelper) { + ShutdownHookAccessHelperHolder.shutdownHookAccessHelper = shutdownHookAccessHelper; + } + + /** + * Gets the default connect timeout. + * + * @return The default connect timeout. + */ + public static Duration getDefaultHttpConnectTimeout() { + return DEFAULT_HTTP_CONNECT_TIMEOUT; + } + + /** + * Gets the default write timeout. + * + * @return The default write timeout. + */ + public static Duration getDefaultHttpWriteTimeout() { + return DEFAULT_HTTP_WRITE_TIMEOUT; + } + + /** + * Gets the default response timeout. + * + * @return The default response timeout. + */ + public static Duration getDefaultHttpResponseTimeout() { + return DEFAULT_HTTP_RESPONSE_TIMEOUT; + } + + /** + * Gets the default read timeout. + * + * @return The default read timeout. + */ + public static Duration getDefaultHttpReadTimeout() { + return DEFAULT_HTTP_READ_TIMEOUT; + } + +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/InternalContext.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/InternalContext.java similarity index 98% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/InternalContext.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/InternalContext.java index a0f0a10d89e4..6b44368a3dd5 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/InternalContext.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/InternalContext.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.implementation.util; +package io.clientcore.core.implementation.utils; import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.util.Context; +import io.clientcore.core.utils.Context; import java.util.Map; import java.util.Objects; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/InternalContext0.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/InternalContext0.java similarity index 93% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/InternalContext0.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/InternalContext0.java index abb78bff1190..7f46e6d858c7 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/InternalContext0.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/InternalContext0.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.implementation.util; +package io.clientcore.core.implementation.utils; /** * An {@link InternalContext} implementation that holds no data. diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/InternalContext1.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/InternalContext1.java similarity index 94% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/InternalContext1.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/InternalContext1.java index 85eb435d3ee0..e5008b523fc7 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/InternalContext1.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/InternalContext1.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.implementation.util; +package io.clientcore.core.implementation.utils; import java.util.Objects; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/InternalContext2.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/InternalContext2.java similarity index 95% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/InternalContext2.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/InternalContext2.java index 65597b7bdbd9..448be8a84b98 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/InternalContext2.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/InternalContext2.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.implementation.util; +package io.clientcore.core.implementation.utils; import java.util.Objects; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/InternalContext3.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/InternalContext3.java similarity index 96% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/InternalContext3.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/InternalContext3.java index 8094a53c49d0..6a793025cf0d 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/InternalContext3.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/InternalContext3.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.implementation.util; +package io.clientcore.core.implementation.utils; import java.util.Objects; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/InternalContext4.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/InternalContext4.java similarity index 97% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/InternalContext4.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/InternalContext4.java index 9c4ec3a2f570..6025bf5b1dc7 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/InternalContext4.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/InternalContext4.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.implementation.util; +package io.clientcore.core.implementation.utils; import java.util.Objects; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/InternalContextN.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/InternalContextN.java similarity index 98% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/InternalContextN.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/InternalContextN.java index f6ca447f51d8..c9173734d57a 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/InternalContextN.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/InternalContextN.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.implementation.util; +package io.clientcore.core.implementation.utils; import java.util.Arrays; import java.util.Objects; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/IterableOfByteBuffersInputStream.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/IterableOfByteBuffersInputStream.java similarity index 97% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/IterableOfByteBuffersInputStream.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/IterableOfByteBuffersInputStream.java index 6dec5c014fde..ae18bc668979 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/IterableOfByteBuffersInputStream.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/IterableOfByteBuffersInputStream.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.implementation.util; +package io.clientcore.core.implementation.utils; import java.io.IOException; import java.io.InputStream; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/Option.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/Option.java new file mode 100644 index 000000000000..a333e140c1b5 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/Option.java @@ -0,0 +1,138 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.implementation.utils; + +import io.clientcore.core.instrumentation.logging.ClientLogger; + +import java.util.NoSuchElementException; +import java.util.Objects; + +/** + * The Option type to describe tri-state. Every Option instance is in one of the three states: a state representing a + * non-null-value, null-value, or no-value. + * + * @param The value type. + */ +public final class Option { + private static final ClientLogger LOGGER = new ClientLogger(Option.class); + private static final Option UNINITIALIZED = new Option<>(); + private static final Option EMPTY = new Option<>(null); + private final boolean isInitialized; + private final T value; + + /** + * Returns an {@link Option} with the specified null-value or non-null-value. + * + * @param The value type. + * @param value the value. + * @return an {@link Option} with the value present. + */ + public static Option of(T value) { + return value == null ? empty() : new Option<>(value); + } + + /** + * Returns an {@link Option} with null-value. + *

        + * {@code Option.empty()} is a syntactic sugar for {@code Option.of(null)}. + *

        + * + * @param The value type. + * @return an {@link Option} with a null-value. + */ + public static Option empty() { + @SuppressWarnings("unchecked") + Option empty = (Option) EMPTY; + return empty; + } + + /** + * Returns an {@link Option} instance with no-value. + * + * @param Type of the non-existent value. + * @return An Option type with no-value. + */ + public static Option uninitialized() { + @SuppressWarnings("unchecked") + Option uninitialized = (Option) UNINITIALIZED; + return uninitialized; + } + + /** + * Return {@code true} if this instance is initialized with a null-value or non-null-value, otherwise {@code + * false}. + * + * @return {@code true} if a value has been initialized, otherwise {@code false} + */ + public boolean isInitialized() { + return this.isInitialized; + } + + /** + * Gets the value in the {@link Option}. + * + * @return The {@code null} (null-value) or non-null-value that the {@link Option} is initialized with. + * @throws NoSuchElementException thrown if the {@link Option} is in no-value state. + */ + public T getValue() { + if (!this.isInitialized) { + throw LOGGER.logThrowableAsError(new NoSuchElementException("No value initialized")); + } + return this.value; + } + + /** + * Indicates whether some other object is "equal to" this Option. The other object is considered equal if: + *
          + *
        • it is also an {@code Option} and; + *
        • both instances are not initialized or; + *
        • both instances are initialized and values are "equal to" each other via {@code equals()}. + *
        + * + * @param obj an object to be tested for equality + * @return {code true} if the other object is "equal to" this object otherwise {@code false} + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!(obj instanceof Option)) { + return false; + } + Option other = (Option) obj; + if (this.isInitialized ^ other.isInitialized) { + // one is 'initialized' and the other one is not. + return false; + } + // both are 'initialized' or 'not-initialized'. + return Objects.equals(value, other.value); + } + + /** + * Returns hash code of the value this Option is initialized with or -1 if in uninitialized state. + *

        + * The value 0 will be returned when initialized with {@code null}. + *

        + * + * @return hash code of the value this Option is initialized with or -1 if in uninitialized state. + */ + @Override + public int hashCode() { + if (!this.isInitialized) { + return -1; + } + return Objects.hashCode(value); + } + + private Option() { + this.isInitialized = false; + this.value = null; + } + + private Option(T value) { + this.isInitialized = true; + this.value = value; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/Providers.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/Providers.java similarity index 97% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/Providers.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/Providers.java index 51806137e62e..f523e3d6c051 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/Providers.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/Providers.java @@ -1,8 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.implementation.util; +package io.clientcore.core.implementation.utils; import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.utils.CoreUtils; import java.util.HashMap; import java.util.Iterator; @@ -76,7 +77,7 @@ public Providers(Class providerClass, String defaultImplementationNam this.defaultProvider = defaultProvider; this.defaultProviderName = defaultProviderName; this.defaultImplementation = defaultImplementationName; - this.noDefaultImplementation = ImplUtils.isNullOrEmpty(defaultImplementation); + this.noDefaultImplementation = CoreUtils.isNullOrEmpty(defaultImplementation); this.noProviderMessage = noProviderErrorMessage; } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/QueryParameter.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/QueryParameter.java similarity index 92% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/QueryParameter.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/QueryParameter.java index 7510df5a10f6..80b304767caf 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/QueryParameter.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/QueryParameter.java @@ -1,7 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.implementation.util; +package io.clientcore.core.implementation.utils; + +import io.clientcore.core.utils.CoreUtils; import java.util.ArrayList; import java.util.Collections; @@ -9,8 +11,7 @@ import java.util.Objects; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; -import static io.clientcore.core.implementation.util.ImplUtils.isNullOrEmpty; -import static io.clientcore.core.implementation.util.ImplUtils.stringJoin; +import static io.clientcore.core.utils.CoreUtils.isNullOrEmpty; /** * Represents a single parameter to be added to a query string. @@ -18,7 +19,7 @@ * If multiple values are added to a query string with the same name (case-insensitive), then the values will be * appended at the end of the same {@link QueryParameter} with commas separating them. */ -class QueryParameter { +public final class QueryParameter { private static final String[] EMPTY_QUERY_PARAMETER_ARRAY = new String[0]; private final String name; @@ -44,7 +45,7 @@ class QueryParameter { * * @throws NullPointerException if {@code name} is null. */ - QueryParameter(String name, String value) { + public QueryParameter(String name, String value) { Objects.requireNonNull(name, "'name' cannot be null."); this.name = name; this.value = value; @@ -58,7 +59,7 @@ class QueryParameter { * * @throws NullPointerException if {@code name} or {@code values} are null. */ - QueryParameter(String name, List values) { + public QueryParameter(String name, List values) { Objects.requireNonNull(name, "'name' cannot be null."); Objects.requireNonNull(values, "'values' cannot be null"); this.name = name; @@ -164,6 +165,6 @@ public String toString() { } private void checkCachedStringValue() { - CACHED_STRING_VALUE_UPDATER.compareAndSet(this, null, stringJoin(",", values)); + CACHED_STRING_VALUE_UPDATER.compareAndSet(this, null, CoreUtils.stringJoin(",", values)); } } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/ServerSentEventHelper.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/ServerSentEventHelper.java similarity index 97% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/ServerSentEventHelper.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/ServerSentEventHelper.java index 722537a74bfc..47bed55fe3f0 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/ServerSentEventHelper.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/ServerSentEventHelper.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.implementation.util; +package io.clientcore.core.implementation.utils; import io.clientcore.core.http.models.ServerSentEvent; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/SliceInputStream.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/SliceInputStream.java similarity index 98% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/SliceInputStream.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/SliceInputStream.java index d2d94091cd4d..fb61b14e106a 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/SliceInputStream.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/SliceInputStream.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.implementation.util; +package io.clientcore.core.implementation.utils; import io.clientcore.core.instrumentation.logging.ClientLogger; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/StreamUtil.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/StreamUtil.java similarity index 98% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/StreamUtil.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/StreamUtil.java index bcf0be2856e4..a4fec02f20f8 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/StreamUtil.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/StreamUtil.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.implementation.util; +package io.clientcore.core.implementation.utils; import io.clientcore.core.instrumentation.logging.ClientLogger; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/UriToken.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/UriToken.java new file mode 100644 index 000000000000..fb2b8d263dc5 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/UriToken.java @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.implementation.utils; + +import java.util.Objects; + +/** + * Represents a token during {@link java.net.URI} parsing. + */ +public final class UriToken { + private final String text; + private final UriTokenType type; + + /** + * Creates a new UriToken object with the specified text and type. + * + * @param text The text of the token. + * @param type The type of the token. + */ + public UriToken(String text, UriTokenType type) { + this.text = text; + this.type = type; + } + + /** + * Gets the text of the token. + * + * @return The text of the token. + */ + public String text() { + return text; + } + + /** + * Gets the type of the token. + * + * @return The type of the token. + */ + public UriTokenType type() { + return type; + } + + @Override + public boolean equals(Object rhs) { + if (rhs == this) { + return true; + } + + if (!(rhs instanceof UriToken)) { + return false; + } + + UriToken other = (UriToken) rhs; + return type == other.type && Objects.equals(text, other.text); + } + + @Override + public String toString() { + return "\"" + text + "\" (" + type + ")"; + } + + @Override + public int hashCode() { + return (text == null ? 0 : text.hashCode()) ^ type.hashCode(); + } + + static UriToken scheme(String text) { + return new UriToken(text, UriTokenType.SCHEME); + } + + static UriToken host(String text) { + return new UriToken(text, UriTokenType.HOST); + } + + static UriToken port(String text) { + return new UriToken(text, UriTokenType.PORT); + } + + static UriToken path(String text) { + return new UriToken(text, UriTokenType.PATH); + } + + static UriToken query(String text) { + return new UriToken(text, UriTokenType.QUERY); + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/UriTokenType.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/UriTokenType.java new file mode 100644 index 000000000000..4c2b476c667e --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/UriTokenType.java @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.implementation.utils; + +/** + * Represents the type of token in a URI. + */ +public enum UriTokenType { + SCHEME, + + HOST, + + PORT, + + PATH, + + QUERY, +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/UriTokenizer.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/UriTokenizer.java similarity index 90% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/UriTokenizer.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/UriTokenizer.java index 5d98021a74f6..8e96da923a8d 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/UriTokenizer.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/UriTokenizer.java @@ -1,20 +1,25 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.implementation.util; +package io.clientcore.core.implementation.utils; -class UriTokenizer { +/** + * Represents a URI parser. + */ +public final class UriTokenizer { private final String text; private final int textLength; private UriTokenizerState state; private int currentIndex; private UriToken currentToken; - UriTokenizer(String text) { - this(text, UriTokenizerState.SCHEME_OR_HOST); - } - - UriTokenizer(String text, UriTokenizerState state) { + /** + * Creates a new UriTokenizer object with the specified text and state. + * + * @param text The text to tokenize. + * @param state The state of the tokenizer. + */ + public UriTokenizer(String text, UriTokenizerState state) { this.text = text; this.textLength = (text == null ? 0 : text.length()); this.state = state; @@ -50,11 +55,22 @@ private boolean peekMatchesSchemeSeparator(boolean step) { return false; } - UriToken current() { + /** + * Gets the current token. + * + * @return The current token. + */ + public UriToken current() { return currentToken; } - boolean next() { + /** + * Advances the tokenizer to the next token. + * + * @return {@code true} if the tokenizer advanced to the next token; {@code false} if the tokenizer has reached the + * end of the text. + */ + public boolean next() { if (!hasCurrentCharacter()) { currentToken = null; } else { diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/UriTokenizerState.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/UriTokenizerState.java new file mode 100644 index 000000000000..963ea1239d1f --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/UriTokenizerState.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.implementation.utils; + +/** + * Represents the state of the {@link UriTokenizer}. + */ +public enum UriTokenizerState { + SCHEME, + + SCHEME_OR_HOST, + + HOST, + + PORT, + + PATH, + + QUERY, + + DONE +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/package-info.java new file mode 100644 index 000000000000..abe576ee04dd --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/utils/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing implementation-specific utility APIs that should not be used by end-users. + */ +package io.clientcore.core.implementation.utils; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/Instrumentation.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/Instrumentation.java index c1de07959f73..f14737a18c9c 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/Instrumentation.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/Instrumentation.java @@ -3,44 +3,105 @@ package io.clientcore.core.instrumentation; +import io.clientcore.core.http.models.RequestOptions; import io.clientcore.core.implementation.instrumentation.fallback.FallbackInstrumentation; import io.clientcore.core.implementation.instrumentation.otel.OTelInitializer; import io.clientcore.core.implementation.instrumentation.otel.OTelInstrumentation; +import io.clientcore.core.instrumentation.metrics.Meter; import io.clientcore.core.instrumentation.tracing.TraceContextPropagator; import io.clientcore.core.instrumentation.tracing.Tracer; +import java.net.URI; +import java.util.Map; import java.util.Objects; +import java.util.function.Consumer; +import java.util.function.Function; + +import static io.clientcore.core.implementation.instrumentation.InstrumentationUtils.getServerPort; /** * A container that can resolve observability provider and its components. Only OpenTelemetry is supported. */ public interface Instrumentation { /** - * Gets the tracer. + * Gets or creates the tracer associated with this instrumentation instance. *

        * Tracer lifetime should usually match the client lifetime. Avoid creating new tracers for each request. * *

        This method is intended to be used by client libraries. Application developers * should use OpenTelemetry API directly

        * - * + * *
              *
              * LibraryInstrumentationOptions libraryOptions = new LibraryInstrumentationOptions("sample")
              *     .setLibraryVersion("1.0.0")
              *     .setSchemaUrl("https://opentelemetry.io/schemas/1.29.0");
              *
        -     * InstrumentationOptions<?> instrumentationOptions = new InstrumentationOptions<>();
        +     * InstrumentationOptions instrumentationOptions = new InstrumentationOptions();
        +     * Instrumentation instrumentation = Instrumentation.create(instrumentationOptions, libraryOptions);
              *
        -     * Tracer tracer = Instrumentation.create(instrumentationOptions, libraryOptions).getTracer();
        +     * Tracer tracer = instrumentation.getTracer();
              *
              * 
        - * + * * * @return The tracer. */ Tracer getTracer(); + /** + * Gets or creates the meter associated with this instrumentation instance. + *

        + * Meter lifetime should usually match the client lifetime. Avoid creating new meters for each request. + * + *

        This method is intended to be used by client libraries. Application developers + * should use OpenTelemetry API directly

        + * + * + *
        +     *
        +     * LibraryInstrumentationOptions libraryOptions = new LibraryInstrumentationOptions("sample")
        +     *     .setLibraryVersion("1.0.0")
        +     *     .setSchemaUrl("https://opentelemetry.io/schemas/1.29.0");
        +     *
        +     * InstrumentationOptions instrumentationOptions = new InstrumentationOptions();
        +     * Instrumentation instrumentation = Instrumentation.create(instrumentationOptions, libraryOptions);
        +     * Meter meter = instrumentation.getMeter();
        +     *
        +     * 
        + * + * + * @return The meter. + */ + Meter getMeter(); + + /** + * Converts the given attributes into the implementation-specific attributes. + * Reuse created attributes when possible between operations to avoid unnecessary overhead. + * + *

        This method is intended to be used by client libraries. Application developers + * should use OpenTelemetry API directly

        + * + *
        +     * LibraryInstrumentationOptions libraryOptions = new LibraryInstrumentationOptions("sample")
        +     *     .setLibraryVersion("1.0.0")
        +     *     .setSchemaUrl("https://opentelemetry.io/schemas/1.29.0");
        +     *
        +     * InstrumentationOptions instrumentationOptions = new InstrumentationOptions();
        +     *
        +     * Instrumentation instrumentation = Instrumentation.create(instrumentationOptions, libraryOptions);
        +     * InstrumentationAttributes attributes = instrumentation
        +     *     .createAttributes(Collections.singletonMap("key1", "value1"));
        +     *
        +     * 
        + * + * + * @param attributes Attributes to convert to implementation-specific attributes. + * @return The implementation-specific attributes instance. + */ + InstrumentationAttributes createAttributes(Map attributes); + /** * Gets the implementation of W3C Trace Context propagator. * @@ -51,6 +112,52 @@ public interface Instrumentation { */ TraceContextPropagator getW3CTraceContextPropagator(); + /** + * Instruments a client call which includes distributed tracing and duration metric. + * Created span becomes current and is used to correlate all telemetry reported under it such as other spans, logs, or metrics exemplars. + *

        + * The method updates the {@link RequestOptions} object with the instrumentation context that should be used for the call. + * + *

        +     * return instrumentation.instrumentWithResponse("Sample.download", options, this::downloadImpl);
        +     * 
        + * + * + * @param operationName the name of the operation, it should be fully-qualified, language-agnostic method definition name such as TypeSpec's crossLanguageDefinitionId + * or OpenAPI operationId. + * @param requestOptions the initial request options. + * @param operation the operation to instrument. Note: the operation is executed in the scope of the instrumentation and should use updated request options passed to it. + * @param the type of the response. + * @return the response. + * @throws RuntimeException if the call throws a runtime exception. + */ + TResponse instrumentWithResponse(String operationName, RequestOptions requestOptions, + Function operation); + + /** + * Instruments a client call which includes distributed tracing and duration metric. + * Created span becomes current and is used to correlate all telemetry reported under it such as other spans, logs, or metrics exemplars. + *

        + * The method updates the {@link RequestOptions} object with the instrumentation context that should be used for the call. + * + *

        +     * instrumentation.instrument("Sample.create", options, this::createImpl);
        +     * 
        + * + * + * @param operationName the name of the operation, it should be fully-qualified, language-agnostic method definition name such as TypeSpec's crossLanguageDefinitionId + * or OpenAPI operationId. + * @param requestOptions the initial request options. + * @param operation the operation to instrument. Note: the operation is executed in the scope of the instrumentation and should use updated request options passed to it. + * @throws RuntimeException if the call throws a runtime exception. + */ + default void instrument(String operationName, RequestOptions requestOptions, Consumer operation) { + instrumentWithResponse(operationName, requestOptions, options -> { + operation.accept(options); + return null; + }); + } + /** * Gets the singleton instance of the resolved telemetry provider. * @@ -61,22 +168,28 @@ public interface Instrumentation { * @param libraryOptions Library-specific telemetry collection options. * @return The instance of telemetry provider implementation. */ - static Instrumentation create(InstrumentationOptions applicationOptions, + static Instrumentation create(InstrumentationOptions applicationOptions, LibraryInstrumentationOptions libraryOptions) { Objects.requireNonNull(libraryOptions, "'libraryOptions' cannot be null"); + + String host = null; + int port = -1; + if (libraryOptions.getEndpoint() != null) { + URI uri = URI.create(libraryOptions.getEndpoint()); + host = uri.getHost(); + port = getServerPort(uri); + } + if (OTelInitializer.isInitialized()) { - return new OTelInstrumentation(applicationOptions, libraryOptions); + return new OTelInstrumentation(applicationOptions, libraryOptions, host, port); } else { - return new FallbackInstrumentation(applicationOptions, libraryOptions); + return new FallbackInstrumentation(applicationOptions, libraryOptions, host, port); } } /** * Retrieves the instrumentation context from the given context. The type of the context is determined by the * instrumentation implementation. - *

        - * When using OpenTelemetry, the context can be a {@code io.opentelemetry.api.trace.Span}, {@code io.opentelemetry.api.trace.SpanContext}, - * {@code io.opentelemetry.context.Context} or any implementation of {@link InstrumentationContext}. * *

              *
        @@ -86,17 +199,20 @@ static Instrumentation create(InstrumentationOptions applicationOptions,
              *     .setInstrumentationContext(new MyInstrumentationContext("e4eaaaf2d48f4bf3b299a8a2a2a77ad7", "5e0c63257de34c56"));
              *
              * // run on another thread
        -     * client.clientCall(options);
        +     * client.downloadContent(options);
              *
              * 
        * - * + *

        + * When using OpenTelemetry, the context can be a {@code io.opentelemetry.api.trace.Span}, {@code io.opentelemetry.api.trace.SpanContext}, + * {@code io.opentelemetry.context.Context} or any implementation of {@link InstrumentationContext}. * *

              *
              * Tracer tracer = GlobalOpenTelemetry.getTracer("sample");
              * Span span = tracer.spanBuilder("my-operation")
              *     .startSpan();
        +     *
              * SampleClient client = new SampleClientBuilder().build();
              *
              * // Propagating context implicitly is preferred way in synchronous code.
        diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/InstrumentationAttributes.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/InstrumentationAttributes.java
        new file mode 100644
        index 000000000000..84a0264a9e3d
        --- /dev/null
        +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/InstrumentationAttributes.java
        @@ -0,0 +1,17 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +
        +package io.clientcore.core.instrumentation;
        +
        +/**
        + * Represents a collection of attributes that can be used to augment telemetry.
        + */
        +public interface InstrumentationAttributes {
        +    /**
        +     * Creates a new instance of attributes containing original and new attribute .
        +     * @param key The key.
        +     * @param value The value.
        +     * @return A new instance of attributes containing original and new attribute.
        +     */
        +    InstrumentationAttributes put(String key, Object value);
        +}
        diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/InstrumentationOptions.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/InstrumentationOptions.java
        index 230f6068ce4a..a5141641949a 100644
        --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/InstrumentationOptions.java
        +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/InstrumentationOptions.java
        @@ -3,6 +3,8 @@
         
         package io.clientcore.core.instrumentation;
         
        +import io.clientcore.core.annotations.Metadata;
        +import io.clientcore.core.annotations.MetadataProperties;
         import io.clientcore.core.http.pipeline.HttpInstrumentationPolicy;
         
         /**
        @@ -13,12 +15,12 @@
          * Library should use them on all instance of {@link io.clientcore.core.instrumentation.tracing.Tracer}
          * it creates and, if it sets up {@link HttpInstrumentationPolicy}, it should pass
          * {@link InstrumentationOptions} to the policy.
        - *
        - * @param  The type of the provider. Only {@code io.opentelemetry.api.OpenTelemetry} is supported.
          */
        -public class InstrumentationOptions {
        +@Metadata(properties = MetadataProperties.FLUENT)
        +public class InstrumentationOptions {
             private boolean isTracingEnabled = true;
        -    private T provider = null;
        +    private boolean isMetricsEnabled = true;
        +    private Object telemetryProvider = null;
         
             /**
              * Enables or disables distributed tracing. Distributed tracing is enabled by default when
        @@ -29,7 +31,7 @@ public class InstrumentationOptions {
              * 
              * 
              *
        -     * InstrumentationOptions<?> instrumentationOptions = new InstrumentationOptions<>()
        +     * HttpInstrumentationOptions instrumentationOptions = new HttpInstrumentationOptions()
              *     .setTracingEnabled(false);
              *
              * SampleClient client = new SampleClientBuilder().instrumentationOptions(instrumentationOptions).build();
        @@ -41,14 +43,39 @@ public class InstrumentationOptions {
              * @param isTracingEnabled true to enable distributed tracing, false to disable.
              * @return The updated {@link InstrumentationOptions} object.
              */
        -    public InstrumentationOptions setTracingEnabled(boolean isTracingEnabled) {
        +    public InstrumentationOptions setTracingEnabled(boolean isTracingEnabled) {
                 this.isTracingEnabled = isTracingEnabled;
                 return this;
             }
         
             /**
        -     * Sets the provider to use for telemetry. Only {@code io.opentelemetry.api.OpenTelemetry} and
        -     * derived classes are supported.
        +     * Enables or disables metrics. Metrics are enabled by default when OpenTelemetry is found on the
        +     * classpath and is configured to export metrics.
        +     *
        +     * 

        Disable metrics on a specific client instance

        + * + * + *
        +     *
        +     * HttpInstrumentationOptions instrumentationOptions = new HttpInstrumentationOptions()
        +     *     .setMetricsEnabled(false);
        +     *
        +     * SampleClient client = new SampleClientBuilder().instrumentationOptions(instrumentationOptions).build();
        +     * client.clientCall();
        +     *
        +     * 
        + * + * @param isMetricsEnabled true to enable metrics, false to disable. + * @return The updated {@link InstrumentationOptions} object. + */ + public InstrumentationOptions setMetricsEnabled(boolean isMetricsEnabled) { + this.isMetricsEnabled = isMetricsEnabled; + return this; + } + + /** + * Sets the telemetry provider. Only {@code io.opentelemetry.api.OpenTelemetry} and + * derived classes are currently supported. *

        * * When provider is not passed explicitly, clients will attempt to use global OpenTelemetry instance. @@ -58,21 +85,23 @@ public InstrumentationOptions setTracingEnabled(boolean isTracingEnabled) { * *

              *
        -     * OpenTelemetry openTelemetry =  AutoConfiguredOpenTelemetrySdk.initialize().getOpenTelemetrySdk();
        -     * InstrumentationOptions<OpenTelemetry> instrumentationOptions = new InstrumentationOptions<OpenTelemetry>()
        -     *     .setProvider(openTelemetry);
        +     * OpenTelemetry openTelemetry = AutoConfiguredOpenTelemetrySdk.initialize().getOpenTelemetrySdk();
        +     * HttpInstrumentationOptions instrumentationOptions = new HttpInstrumentationOptions()
        +     *     .setTelemetryProvider(openTelemetry);
              *
              * SampleClient client = new SampleClientBuilder().instrumentationOptions(instrumentationOptions).build();
        +     *
        +     * // this call will be traced using OpenTelemetry SDK provided explicitly
              * client.clientCall();
              *
              * 
        * * - * @param provider The provider to use for telemetry. + * @param telemetryProvider The provider to use for telemetry. * @return The updated {@link InstrumentationOptions} object. */ - public InstrumentationOptions setProvider(T provider) { - this.provider = provider; + public InstrumentationOptions setTelemetryProvider(Object telemetryProvider) { + this.telemetryProvider = telemetryProvider; return this; } @@ -85,13 +114,22 @@ public boolean isTracingEnabled() { return isTracingEnabled; } + /** + * Returns true if metrics are enabled, false otherwise. + * + * @return true if metrics are enabled, false otherwise. + */ + public boolean isMetricsEnabled() { + return isMetricsEnabled; + } + /** * Returns the telemetry provider. * * @return The telemetry provider instance. */ - public T getProvider() { - return provider; + public Object getTelemetryProvider() { + return telemetryProvider; } /** diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/LibraryInstrumentationOptions.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/LibraryInstrumentationOptions.java index d7e4393a4306..c3ed05f322bd 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/LibraryInstrumentationOptions.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/LibraryInstrumentationOptions.java @@ -3,6 +3,8 @@ package io.clientcore.core.instrumentation; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; import io.clientcore.core.implementation.instrumentation.LibraryInstrumentationOptionsAccessHelper; import java.util.Objects; @@ -17,17 +19,19 @@ * Schema URL describes telemetry schema and version. *

        * If your client library adds any attributes (links, events, etc.) to the spans, - * these properties SHOULD follow specific version of OpenTelemetry Semantic Conventions. - * And provide the corresponding schema URL. + * these properties SHOULD follow specific version of OpenTelemetry Semantic Conventions + * and provide the corresponding schema URI. *

        * The {@link LibraryInstrumentationOptions} are usually static and shared across all instances of the client. * Application developers are not expected to change them. */ +@Metadata(properties = MetadataProperties.FLUENT) public final class LibraryInstrumentationOptions { private final String libraryName; private String libraryVersion; private String schemaUrl; private boolean disableSpanSuppression; + private String serviceEndpoint; static { LibraryInstrumentationOptionsAccessHelper @@ -76,6 +80,17 @@ public LibraryInstrumentationOptions setSchemaUrl(String schemaUrl) { return this; } + /** + * Sets the service endpoint. + * + * @param endpoint The service endpoint. + * @return The updated {@link LibraryInstrumentationOptions} object. + */ + public LibraryInstrumentationOptions setEndpoint(String endpoint) { + this.serviceEndpoint = endpoint; + return this; + } + /** * Gets the client library name. * @@ -104,6 +119,15 @@ public String getSchemaUrl() { return schemaUrl; } + /** + * Gets the service endpoint. + * + * @return The service endpoint. + */ + public String getEndpoint() { + return serviceEndpoint; + } + LibraryInstrumentationOptions disableSpanSuppression(boolean disableSpanSuppression) { this.disableSpanSuppression = disableSpanSuppression; return this; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/logging/ClientLogger.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/logging/ClientLogger.java index 5974d6708f06..c62ef2c84965 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/logging/ClientLogger.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/logging/ClientLogger.java @@ -3,33 +3,16 @@ package io.clientcore.core.instrumentation.logging; -import io.clientcore.core.annotation.Metadata; -import io.clientcore.core.implementation.AccessibleByteArrayOutputStream; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; import io.clientcore.core.implementation.instrumentation.Slf4jLoggerShim; import io.clientcore.core.implementation.instrumentation.DefaultLogger; -import io.clientcore.core.instrumentation.InstrumentationContext; -import io.clientcore.core.serialization.json.JsonWriter; -import io.clientcore.core.serialization.json.implementation.DefaultJsonWriter; -import io.clientcore.core.util.configuration.Configuration; +import io.clientcore.core.utils.configuration.Configuration; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.charset.StandardCharsets; import java.nio.file.InvalidPathException; import java.util.Collections; -import java.util.HashMap; -import java.util.Locale; import java.util.Map; import java.util.Objects; -import java.util.function.Supplier; - -import static io.clientcore.core.annotation.TypeConditions.FLUENT; -import static io.clientcore.core.implementation.instrumentation.AttributeKeys.EVENT_NAME_KEY; -import static io.clientcore.core.implementation.instrumentation.AttributeKeys.EXCEPTION_MESSAGE_KEY; -import static io.clientcore.core.implementation.instrumentation.AttributeKeys.EXCEPTION_STACKTRACE_KEY; -import static io.clientcore.core.implementation.instrumentation.AttributeKeys.EXCEPTION_TYPE_KEY; -import static io.clientcore.core.implementation.instrumentation.AttributeKeys.SPAN_ID_KEY; -import static io.clientcore.core.implementation.instrumentation.AttributeKeys.TRACE_ID_KEY; /** * This is a fluent logger helper class that wraps an SLF4J Logger (if available) or a default implementation of the @@ -40,13 +23,14 @@ * logged.

        * *

        A minimum logging level threshold is determined by the - * {@link Configuration#PROPERTY_LOG_LEVEL LOG_LEVEL} environment configuration. By default logging is + * {@link Configuration#LOG_LEVEL LOG_LEVEL} environment configuration. By default logging is * disabled.

        * *

        The logger is capable of producing json-formatted messages enriched with key value pairs. * Context can be provided in the constructor and populated on every message or added per each log record.

        * @see Configuration */ +@Metadata(properties = MetadataProperties.IMMUTABLE) public class ClientLogger { private final Slf4jLoggerShim logger; private final Map globalContext; @@ -254,8 +238,7 @@ public LoggingEvent atVerbose() { * * *
        -     * ClientLogger.LogLevel level = response.getStatusCode() == 200
        -     *     ? ClientLogger.LogLevel.INFORMATIONAL : ClientLogger.LogLevel.WARNING;
        +     * LogLevel level = response.getStatusCode() == 200 ? LogLevel.INFORMATIONAL : LogLevel.WARNING;
              * logger.atLevel(level)
              *     .addKeyValue("key", "value")
              *     .log("message");
        @@ -279,403 +262,4 @@ private static String getClassPathFromClassName(String className) {
                 }
             }
         
        -    /**
        -     * This class provides fluent API to write logs using {@link ClientLogger} and
        -     * enrich them with additional context.
        -     *
        -     * 

        Code samples

        - * - *

        Logging event with context.

        - * - * - *
        -     * logger.atInfo()
        -     *     .addKeyValue("key1", "value1")
        -     *     .addKeyValue("key2", true)
        -     *     .addKeyValue("key3", this::getName)
        -     *     .log("A structured log message.");
        -     * 
        - * - */ - @Metadata(conditions = FLUENT) - public static final class LoggingEvent { - private static final LoggingEvent NOOP = new LoggingEvent(null, null, null, false); - - private final Slf4jLoggerShim logger; - private final LogLevel level; - private final Map globalPairs; - private final boolean isEnabled; - private Map keyValuePairs; - private String eventName; - private InstrumentationContext context = null; - - /** - * Creates {@code LoggingEvent} for provided level and {@link ClientLogger}. - * If level is disabled, returns no-op instance. - */ - static LoggingEvent create(Slf4jLoggerShim logger, LogLevel level, Map globalContext) { - if (logger.canLogAtLevel(level)) { - return new LoggingEvent(logger, level, globalContext, true); - } - - return NOOP; - } - - private LoggingEvent(Slf4jLoggerShim logger, LogLevel level, Map globalContext, - boolean isEnabled) { - this.logger = logger; - this.level = level; - this.isEnabled = isEnabled; - this.globalPairs = globalContext; - } - - /** - * Returns true if this logging event will be logged. - * - * @return true if this logging event will be logged. - */ - public boolean isEnabled() { - return isEnabled; - } - - /** - * Adds key with String value pair to the context of current log being created. - * - *

        Code samples

        - * - *

        Adding string value to logging event context.

        - * - * - *
        -         * logger.atInfo()
        -         *     .addKeyValue("key", "value")
        -         *     .addKeyValue("hello", name)
        -         *     .log("A structured log message.");
        -         * 
        - * - * - * @param key String key. - * @param value String value. - * @return The updated {@code LoggingEvent} object. - */ - public LoggingEvent addKeyValue(String key, String value) { - if (this.isEnabled) { - addKeyValueInternal(key, value); - } - - return this; - } - - /** - * Adds key with Object value to the context of current log being created. - * If logging is enabled at given level, and object is not null, uses {@code value.toString()} to - * serialize object. - * - *

        Code samples

        - * - *

        Adding string value to logging event context.

        - * - * - *
        -         * logger.atVerbose()
        -         *     // equivalent to addKeyValue("key", () -> new LoggableObject("string representation").toString()
        -         *     .addKeyValue("key", new LoggableObject("string representation"))
        -         *     .log("A structured log message.");
        -         * 
        - * - * - * @param key String key. - * @param value Object value. - * @return The updated {@code LoggingEvent} object. - */ - public LoggingEvent addKeyValue(String key, Object value) { - if (this.isEnabled) { - addKeyValueInternal(key, value); - } - - return this; - } - - /** - * Adds a key with a boolean value to the context of the current log being created. - * - * @param key Key to associate the provided {@code value} with. - * @param value The boolean value. - * @return The updated {@link LoggingEvent} object. - */ - public LoggingEvent addKeyValue(String key, boolean value) { - if (this.isEnabled) { - addKeyValueInternal(key, value); - } - return this; - } - - /** - * Adds key with long value to the context of current log event being created. - * - *

        Code samples

        - * - *

        Adding a long value to the logging event context.

        - * - * - *
        -         * logger.atVerbose()
        -         *     .addKeyValue("key", 1L)
        -         *     .log("A structured log message.");
        -         * 
        - * - * - * @param key Key to associate the provided {@code value} with. - * @param value The long value. - * @return The updated {@link LoggingEvent} object. - */ - public LoggingEvent addKeyValue(String key, long value) { - if (this.isEnabled) { - addKeyValueInternal(key, value); - } - return this; - } - - /** - * Adds key with String value supplier to the context of current log event being created. - * - * @param key String key. - * @param valueSupplier String value supplier function. - * @return The updated {@code LoggingEvent} object. - */ - public LoggingEvent addKeyValue(String key, Supplier valueSupplier) { - if (this.isEnabled && valueSupplier != null) { - this.addKeyValue(key, valueSupplier.get()); - } - return this; - } - - /** - * Sets operation context on the log event being created. - * It's used to correlate logs between each other and with other telemetry items. - * - * @param context operation context. - * @return The updated {@code LoggingEventBuilder} object. - */ - public LoggingEvent setInstrumentationContext(InstrumentationContext context) { - this.context = context; - return this; - } - - /** - * Sets the event name for the current log event. The event name is used to query all logs - * that describe the same event. It must not contain any dynamic parts. - * - * @param eventName The name of the event. - * @return The updated {@code LoggingEvent} object. - */ - public LoggingEvent setEventName(String eventName) { - this.eventName = eventName; - return this; - } - - /** - * Logs event annotated with context. - * Logs event with context. - */ - public void log() { - log(null); - } - - /** - * Logs message annotated with context. - * - * @param message log message. - */ - public void log(String message) { - if (this.isEnabled) { - logger.performLogging(level, getMessageWithContext(message), null); - } - } - - /** - * Logs message annotated with context. - * - * @param message log message. - * @param throwable {@link Throwable} for the message. - * @param Type of the Throwable being logged. - * - * @return The passed {@link Throwable}. - */ - public T log(String message, T throwable) { - if (this.isEnabled) { - boolean isDebugEnabled = logger.canLogAtLevel(LogLevel.VERBOSE); - if (throwable != null) { - addKeyValueInternal(EXCEPTION_TYPE_KEY, throwable.getClass().getCanonicalName()); - addKeyValueInternal(EXCEPTION_MESSAGE_KEY, throwable.getMessage()); - if (isDebugEnabled) { - StringBuilder stackTrace = new StringBuilder(); - DefaultLogger.appendThrowable(stackTrace, throwable); - addKeyValue(EXCEPTION_STACKTRACE_KEY, stackTrace.toString()); - } - } - logger.performLogging(level, getMessageWithContext(message), isDebugEnabled ? throwable : null); - } - return throwable; - } - - private String getMessageWithContext(String message) { - if (this.context != null && this.context.isValid()) { - // TODO (limolkova) we can set context from implicit current span - // we should also support OTel as a logging provider and avoid adding redundant - // traceId and spanId to the logs - - addKeyValue(TRACE_ID_KEY, context.getTraceId()); - addKeyValue(SPAN_ID_KEY, context.getSpanId()); - } - - int pairsCount - = (keyValuePairs == null ? 0 : keyValuePairs.size()) + (globalPairs == null ? 0 : globalPairs.size()); - - int messageLength = message == null ? 0 : message.length(); - int speculatedSize = 20 + pairsCount * 20 + messageLength; - try (AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(speculatedSize); - JsonWriter jsonWriter = DefaultJsonWriter.toStream(outputStream, null)) { - jsonWriter.writeStartObject(); - - if (message != null) { - jsonWriter.writeStringField("message", message); - } - - if (globalPairs != null) { - for (Map.Entry kvp : globalPairs.entrySet()) { - jsonWriter.writeUntypedField(kvp.getKey(), kvp.getValue()); - } - } - - if (keyValuePairs != null) { - for (Map.Entry kvp : keyValuePairs.entrySet()) { - jsonWriter.writeUntypedField(kvp.getKey(), kvp.getValue()); - } - } - - if (eventName != null) { - jsonWriter.writeStringField(EVENT_NAME_KEY, eventName); - } - - jsonWriter.writeEndObject().flush(); - - return outputStream.toString(StandardCharsets.UTF_8); - } catch (IOException ex) { - throw new UncheckedIOException(ex); - } - } - - private void addKeyValueInternal(String key, Object value) { - if (this.keyValuePairs == null) { - this.keyValuePairs = new HashMap<>(); - } - - this.keyValuePairs.put(key, value); - } - } - - /** - * Enum which represent logging levels used. - */ - public enum LogLevel { - /** - * Indicates that no log level is set. - */ - NOTSET(0, "0", "notSet"), - - /** - * Indicates that log level is at verbose level. - */ - VERBOSE(1, "1", "verbose", "debug"), - - /** - * Indicates that log level is at information level. - */ - INFORMATIONAL(2, "2", "info", "information", "informational"), - - /** - * Indicates that log level is at warning level. - */ - WARNING(3, "3", "warn", "warning"), - - /** - * Indicates that log level is at error level. - */ - ERROR(4, "4", "err", "error"); - - private final int numericValue; - private final String[] allowedLogLevelVariables; - private static final HashMap LOG_LEVEL_STRING_MAPPER = new HashMap<>(); - private final String caseSensitive; - - static { - for (LogLevel logLevel : LogLevel.values()) { - for (String val : logLevel.allowedLogLevelVariables) { - LOG_LEVEL_STRING_MAPPER.put(val, logLevel); - } - } - } - - LogLevel(int numericValue, String... allowedLogLevelVariables) { - this.numericValue = numericValue; - this.allowedLogLevelVariables = allowedLogLevelVariables; - this.caseSensitive = allowedLogLevelVariables[0]; - } - - /** - * Converts the log level into a numeric representation used for comparisons. - * - * @return The numeric representation of the log level. - */ - private int getLevelCode() { - return numericValue; - } - - /** - * Compares the passed log level with the configured log level and returns true if the passed log level is greater - * @param level The log level to compare. - * @param configuredLevel The configured log level. - * @return True if the passed log level is greater or equal to the configured log level, false otherwise. - */ - public static boolean isGreaterOrEqual(LogLevel level, LogLevel configuredLevel) { - return level.getLevelCode() >= configuredLevel.getLevelCode(); - } - - /** - * Converts the passed log level string to the corresponding {@link LogLevel}. - * - * @param logLevelVal The log level value which needs to convert - * @return The LogLevel Enum if pass in the valid string. - * The valid strings for {@link LogLevel} are: - *
          - *
        • VERBOSE: "verbose", "debug"
        • - *
        • INFO: "info", "information", "informational"
        • - *
        • WARNING: "warn", "warning"
        • - *
        • ERROR: "err", "error"
        • - *
        - * Returns NOT_SET if null is passed in. - * @throws IllegalArgumentException if the log level value is invalid. - */ - public static LogLevel fromString(String logLevelVal) { - if (logLevelVal == null) { - return LogLevel.NOTSET; - } - String caseInsensitiveLogLevel = logLevelVal.toLowerCase(Locale.ROOT); - if (!LOG_LEVEL_STRING_MAPPER.containsKey(caseInsensitiveLogLevel)) { - throw new IllegalArgumentException( - "We currently do not support the log level you set. LogLevel: " + logLevelVal); - } - return LOG_LEVEL_STRING_MAPPER.get(caseInsensitiveLogLevel); - } - - /** - * Converts the log level to a string representation. - * - * @return The string representation of the log level. - */ - public String toString() { - return caseSensitive; - } - } } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/logging/LogLevel.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/logging/LogLevel.java new file mode 100644 index 000000000000..add00edac22a --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/logging/LogLevel.java @@ -0,0 +1,114 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.instrumentation.logging; + +import java.util.HashMap; +import java.util.Locale; + +/** + * Enum which represent logging levels used. + */ +public enum LogLevel { + /** + * Indicates that there no log level is set. + */ + NOTSET(0, "0", "notSet"), + + /** + * Indicates that the log level is at verbose level. + */ + VERBOSE(1, "1", "verbose", "debug"), + + /** + * Indicates that the log level is at information level. + */ + INFORMATIONAL(2, "2", "info", "information", "informational"), + + /** + * Indicates that the log level is at warning level. + */ + WARNING(3, "3", "warn", "warning"), + + /** + * Indicates that the log level is at error level. + */ + ERROR(4, "4", "err", "error"); + + private final int numericValue; + private final String[] allowedLogLevelVariables; + private static final HashMap LOG_LEVEL_STRING_MAPPER + = new HashMap<>(); + private final String caseSensitive; + + static { + for (io.clientcore.core.instrumentation.logging.LogLevel logLevel : io.clientcore.core.instrumentation.logging.LogLevel + .values()) { + for (String val : logLevel.allowedLogLevelVariables) { + LOG_LEVEL_STRING_MAPPER.put(val, logLevel); + } + } + } + + LogLevel(int numericValue, String... allowedLogLevelVariables) { + this.numericValue = numericValue; + this.allowedLogLevelVariables = allowedLogLevelVariables; + this.caseSensitive = allowedLogLevelVariables[0]; + } + + /** + * Converts the log level into a numeric representation used for comparisons. + * + * @return The numeric representation of the log level. + */ + private int getLevelCode() { + return numericValue; + } + + /** + * Compares the passed log level with the configured log level and returns true if the passed log level is greater + * + * @param level The log level to compare. + * @param configuredLevel The configured log level. + * @return True if the passed log level is greater or equal to the configured log level, false otherwise. + */ + public static boolean isGreaterOrEqual(io.clientcore.core.instrumentation.logging.LogLevel level, + io.clientcore.core.instrumentation.logging.LogLevel configuredLevel) { + return level.getLevelCode() >= configuredLevel.getLevelCode(); + } + + /** + * Converts the passed log level string to the corresponding {@link io.clientcore.core.instrumentation.logging.LogLevel}. + * + * @param logLevelVal The log level value which needs to convert + * @return The LogLevel Enum if pass in the valid string. + * The valid strings for {@link io.clientcore.core.instrumentation.logging.LogLevel} are: + *
          + *
        • VERBOSE: "verbose", "debug"
        • + *
        • INFO: "info", "information", "informational"
        • + *
        • WARNING: "warn", "warning"
        • + *
        • ERROR: "err", "error"
        • + *
        + * Returns NOT_SET if null is passed in. + * @throws IllegalArgumentException if the log level value is invalid. + */ + public static io.clientcore.core.instrumentation.logging.LogLevel fromString(String logLevelVal) { + if (logLevelVal == null) { + return io.clientcore.core.instrumentation.logging.LogLevel.NOTSET; + } + String caseInsensitiveLogLevel = logLevelVal.toLowerCase(Locale.ROOT); + if (!LOG_LEVEL_STRING_MAPPER.containsKey(caseInsensitiveLogLevel)) { + throw new IllegalArgumentException( + "We currently do not support the log level you set. LogLevel: " + logLevelVal); + } + return LOG_LEVEL_STRING_MAPPER.get(caseInsensitiveLogLevel); + } + + /** + * Converts the log level to a string representation. + * + * @return The string representation of the log level. + */ + public String toString() { + return caseSensitive; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/logging/LoggingEvent.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/logging/LoggingEvent.java new file mode 100644 index 000000000000..f716aaece74c --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/logging/LoggingEvent.java @@ -0,0 +1,348 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.instrumentation.logging; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.implementation.AccessibleByteArrayOutputStream; +import io.clientcore.core.implementation.instrumentation.DefaultLogger; +import io.clientcore.core.implementation.instrumentation.Slf4jLoggerShim; +import io.clientcore.core.instrumentation.InstrumentationContext; +import io.clientcore.core.serialization.json.JsonWriter; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Supplier; + +import static io.clientcore.core.annotations.MetadataProperties.FLUENT; +import static io.clientcore.core.implementation.instrumentation.AttributeKeys.EVENT_NAME_KEY; +import static io.clientcore.core.implementation.instrumentation.AttributeKeys.EXCEPTION_MESSAGE_KEY; +import static io.clientcore.core.implementation.instrumentation.AttributeKeys.EXCEPTION_STACKTRACE_KEY; +import static io.clientcore.core.implementation.instrumentation.AttributeKeys.EXCEPTION_TYPE_KEY; +import static io.clientcore.core.implementation.instrumentation.AttributeKeys.SPAN_ID_KEY; +import static io.clientcore.core.implementation.instrumentation.AttributeKeys.TRACE_ID_KEY; + +/** + * This class provides fluent API to write logs using {@link ClientLogger} and + * enrich them with additional context. + * + *

        Code samples

        + * + *

        Logging event with context.

        + * + * + *
        + * logger.atInfo()
        + *     .addKeyValue("key1", "value1")
        + *     .addKeyValue("key2", true)
        + *     .addKeyValue("key3", this::getName)
        + *     .log("A structured log message.");
        + * 
        + * + */ +@Metadata(properties = FLUENT) +public final class LoggingEvent { + private static final LoggingEvent NOOP = new LoggingEvent(null, null, null, false); + + private final Slf4jLoggerShim logger; + private final LogLevel level; + private final Map globalPairs; + private final boolean isEnabled; + private Map keyValuePairs; + private String eventName; + private InstrumentationContext context = null; + + /** + * Creates {@code LoggingEvent} for provided level and {@link ClientLogger}. + * If level is disabled, returns no-op instance. + */ + static LoggingEvent create(Slf4jLoggerShim logger, LogLevel level, Map globalContext) { + if (logger.canLogAtLevel(level)) { + return new LoggingEvent(logger, level, globalContext, true); + } + + return NOOP; + } + + private LoggingEvent(Slf4jLoggerShim logger, LogLevel level, Map globalContext, boolean isEnabled) { + this.logger = logger; + this.level = level; + this.isEnabled = isEnabled; + this.globalPairs = globalContext; + } + + /** + * Returns true if this logging event will be logged. + * + * @return true if this logging event will be logged. + */ + public boolean isEnabled() { + return isEnabled; + } + + /** + * Adds key with String value pair to the context of current log being created. + * + *

        Code samples

        + * + *

        Adding string value to logging event context.

        + * + * + *
        +     * logger.atInfo()
        +     *     .addKeyValue("key", "value")
        +     *     .addKeyValue("hello", name)
        +     *     .log("A structured log message.");
        +     * 
        + * + * + * @param key String key. + * @param value String value. + * @return The updated {@code LoggingEvent} object. + */ + public LoggingEvent addKeyValue(String key, String value) { + if (this.isEnabled) { + addKeyValueInternal(key, value); + } + + return this; + } + + /** + * Adds key with Object value to the context of current log being created. + * If logging is enabled at given level, and object is not null, uses {@code value.toString()} to + * serialize object. + * + *

        Code samples

        + * + *

        Adding string value to logging event context.

        + * + * + *
        +     * logger.atVerbose()
        +     *     // equivalent to addKeyValue("key", () -> new LoggableObject("string representation").toString()
        +     *     .addKeyValue("key", new LoggableObject("string representation"))
        +     *     .log("A structured log message.");
        +     * 
        + * + * + * @param key String key. + * @param value Object value. + * @return The updated {@code LoggingEvent} object. + */ + public LoggingEvent addKeyValue(String key, Object value) { + if (this.isEnabled) { + addKeyValueInternal(key, value); + } + + return this; + } + + /** + * Adds a key with a boolean value to the context of the current log being created. + * + * @param key Key to associate the provided {@code value} with. + * @param value The boolean value. + * @return The updated {@link LoggingEvent} object. + */ + public LoggingEvent addKeyValue(String key, boolean value) { + if (this.isEnabled) { + addKeyValueInternal(key, value); + } + return this; + } + + /** + * Adds key with long value to the context of current log event being created. + * + *

        Code samples

        + * + *

        Adding a long value to the logging event context.

        + * + * + *
        +     * logger.atVerbose()
        +     *     .addKeyValue("key", 1L)
        +     *     .log("A structured log message.");
        +     * 
        + * + * + * @param key Key to associate the provided {@code value} with. + * @param value The long value. + * @return The updated {@link LoggingEvent} object. + */ + public LoggingEvent addKeyValue(String key, long value) { + if (this.isEnabled) { + addKeyValueInternal(key, value); + } + return this; + } + + /** + * Adds key with String value supplier to the context of current log event being created. + * + * @param key String key. + * @param valueSupplier String value supplier function. + * @return The updated {@code LoggingEvent} object. + */ + public LoggingEvent addKeyValue(String key, Supplier valueSupplier) { + if (this.isEnabled && valueSupplier != null) { + this.addKeyValue(key, valueSupplier.get()); + } + return this; + } + + /** + * Sets operation context on the log event being created. + * It's used to correlate logs between each other and with other telemetry items. + * + * @param context operation context. + * @return The updated {@code LoggingEventBuilder} object. + */ + public LoggingEvent setInstrumentationContext(InstrumentationContext context) { + this.context = context; + return this; + } + + /** + * Sets the event name for the current log event. The event name is used to query all logs + * that describe the same event. It must not contain any dynamic parts. + * + * @param eventName The name of the event. + * @return The updated {@code LoggingEvent} object. + */ + public LoggingEvent setEventName(String eventName) { + this.eventName = eventName; + return this; + } + + /** + * Logs event annotated with context. + * Logs event with context. + */ + public void log() { + log((String) null); + } + + /** + * Logs message annotated with context. + * + * @param message log message. + */ + public void log(String message) { + if (this.isEnabled) { + logger.performLogging(level, getMessageWithContext(message), null); + } + } + + /** + * Logs with a message supplier annotated with context. + *

        + * If the message supplier is null, the message will be null. + *

        + * If the {@link LoggingEvent} is not {@link #isEnabled() enabled} this will be a no-op and the supplier won't be + * called. + *

        + * This method is preferred if the message is expensive to create and may not be logged. + * + * @param message log message. + */ + public void log(Supplier message) { + if (this.isEnabled) { + logger.performLogging(level, getMessageWithContext(message.get()), null); + } + } + + /** + * Logs throwable annotated with context. + * + * @param throwable {@link Throwable} for the message. + * @param Type of the Throwable being logged. + * @return The passed {@link Throwable}. + */ + public T log(T throwable) { + return log(null, throwable); + } + + /** + * Logs message annotated with context. + * + * @param message log message. + * @param throwable {@link Throwable} for the message. + * @param Type of the Throwable being logged. + * @return The passed {@link Throwable}. + */ + public T log(String message, T throwable) { + if (this.isEnabled) { + boolean isDebugEnabled = logger.canLogAtLevel(LogLevel.VERBOSE); + if (throwable != null) { + addKeyValueInternal(EXCEPTION_TYPE_KEY, throwable.getClass().getCanonicalName()); + addKeyValueInternal(EXCEPTION_MESSAGE_KEY, throwable.getMessage()); + if (isDebugEnabled) { + StringBuilder stackTrace = new StringBuilder(); + DefaultLogger.appendThrowable(stackTrace, throwable); + addKeyValue(EXCEPTION_STACKTRACE_KEY, stackTrace.toString()); + } + } + logger.performLogging(level, getMessageWithContext(message), isDebugEnabled ? throwable : null); + } + return throwable; + } + + private String getMessageWithContext(String message) { + if (this.context != null && this.context.isValid()) { + // TODO (limolkova) we can set context from implicit current span + // we should also support OTel as a logging provider and avoid adding redundant + // traceId and spanId to the logs + + addKeyValue(TRACE_ID_KEY, context.getTraceId()); + addKeyValue(SPAN_ID_KEY, context.getSpanId()); + } + + int pairsCount + = (keyValuePairs == null ? 0 : keyValuePairs.size()) + (globalPairs == null ? 0 : globalPairs.size()); + + int messageLength = message == null ? 0 : message.length(); + int speculatedSize = 20 + pairsCount * 20 + messageLength; + try (AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(speculatedSize); + JsonWriter jsonWriter = JsonWriter.toStream(outputStream)) { + jsonWriter.writeStartObject(); + + if (message != null) { + jsonWriter.writeStringField("message", message); + } + + if (globalPairs != null) { + for (Map.Entry kvp : globalPairs.entrySet()) { + jsonWriter.writeUntypedField(kvp.getKey(), kvp.getValue()); + } + } + + if (keyValuePairs != null) { + for (Map.Entry kvp : keyValuePairs.entrySet()) { + jsonWriter.writeUntypedField(kvp.getKey(), kvp.getValue()); + } + } + + if (eventName != null) { + jsonWriter.writeStringField(EVENT_NAME_KEY, eventName); + } + + jsonWriter.writeEndObject().flush(); + + return outputStream.toString(StandardCharsets.UTF_8); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + } + + private void addKeyValueInternal(String key, Object value) { + if (this.keyValuePairs == null) { + this.keyValuePairs = new HashMap<>(); + } + + this.keyValuePairs.put(key, value); + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/metrics/DoubleHistogram.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/metrics/DoubleHistogram.java new file mode 100644 index 000000000000..7744911d32ea --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/metrics/DoubleHistogram.java @@ -0,0 +1,67 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.instrumentation.metrics; + +import io.clientcore.core.instrumentation.InstrumentationAttributes; +import io.clientcore.core.instrumentation.InstrumentationContext; + +/** + * Represents a histogram metric that can be used to record distribution of {@code double} values. + *

        This interface is intended to be used by client libraries only. Application developers should use OpenTelemetry API directly

        + */ +public interface DoubleHistogram { + /** + * Creates histogram instrument allowing to record distribution of a double value values. + * Histograms should be used for latency or other measurements where distribution of values is important and values are + * statistically bounded. + *

        + * See Histogram definition + * and conventions for more details. + *

        + * Avoid creating new histograms for each request. Histogram lifetime should usually match the client lifetime. + * + *

        +     *
        +     * List<Double> bucketBoundariesAdvice = Collections.unmodifiableList(Arrays.asList(0.005d, 0.01d, 0.025d, 0.05d, 0.075d,
        +     *     0.1d, 0.25d, 0.5d, 0.75d, 1d, 2.5d, 5d, 7.5d, 10d));
        +     * DoubleHistogram histogram = meter.createDoubleHistogram("contoso.sample.client.operation.duration",
        +     *     "s",
        +     *     "Contoso sample client operation duration", bucketBoundariesAdvice);
        +     * InstrumentationAttributes successAttributes  = instrumentation.createAttributes(
        +     *     Collections.singletonMap("operation.name", "{operationName}"));
        +     *
        +     * long startTime = System.nanoTime();
        +     * String errorType = null;
        +     *
        +     * try {
        +     *     performOperation();
        +     * } catch (Throwable t) {
        +     *     // make sure to report any exceptions including unchecked ones.
        +     *     errorType = getCause(t).getClass().getCanonicalName();
        +     *     throw t;
        +     * } finally {
        +     *     InstrumentationAttributes attributes = errorType == null
        +     *         ? successAttributes
        +     *         : successAttributes.put("error.type", errorType);
        +     *
        +     *     histogram.record((System.nanoTime() - startTime) / 1e9, attributes, null);
        +     * }
        +     *
        +     * 
        + * + * + * @param value The amount of the measurement. + * @param attributes Collection of attributes representing metric dimensions. + * @param context The explicit context to associate with this measurement. + */ + void record(double value, InstrumentationAttributes attributes, InstrumentationContext context); + + /** + * Flag indicating if metric implementation is detected and functional, use it to minimize performance impact associated with metrics, + * e.g. measuring latency. + * + * @return {@code true} if enabled, {@code false} otherwise + */ + boolean isEnabled(); +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/metrics/LongCounter.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/metrics/LongCounter.java new file mode 100644 index 000000000000..6c1a33d13430 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/metrics/LongCounter.java @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.instrumentation.metrics; + +import io.clientcore.core.instrumentation.InstrumentationAttributes; +import io.clientcore.core.instrumentation.InstrumentationContext; + +/** + * Represents a counter metric that can be used to record {@code long} values. + * + *

        This interface is intended to be used by client libraries only. Application developers should use OpenTelemetry API directly

        + *

        + * Counters can be monotonic or non-monotonic. Monotonic counters are cumulative and can only increase over time. + * Use {@link Meter#createLongCounter(String, String, String)} to create counters that can only go up, such as number of sent messages or created connections. + * See Counter definition for more details. + * + *

        + * LongCounter counter = meter.createLongCounter("sample.client.sent.messages",
        + *     "Number of messages sent by the client library",
        + *     "{message}");
        + * InstrumentationAttributes successAttributes  = instrumentation.createAttributes(
        + *     Collections.singletonMap("operation.name", "sendBatch"));
        + * String errorType = null;
        + * try {
        + *     sendBatch(batch);
        + * } catch (Throwable t) {
        + *     // make sure to report any exceptions including unchecked ones.
        + *     errorType = getCause(t).getClass().getCanonicalName();
        + *     throw t;
        + * } finally {
        + *     InstrumentationAttributes attributes = errorType == null
        + *         ? successAttributes
        + *         : successAttributes.put("error.type", errorType);
        + *
        + *     counter.add(batch.size(), attributes, null);
        + * }
        + *
        + * 
        + * + *

        + * Use {@link Meter#createLongUpDownCounter(String, String, String)} to create counters that can go down, + * such as number of active connections or queue size. + *

        + * See UpDownCounter definition for more details. + * + *

        + * LongCounter counter = meter.createLongCounter("sample.client.sent.messages",
        + *     "Number of messages sent by the client library",
        + *     "{message}");
        + * InstrumentationAttributes successAttributes  = instrumentation.createAttributes(
        + *     Collections.singletonMap("operation.name", "sendBatch"));
        + * String errorType = null;
        + * try {
        + *     sendBatch(batch);
        + * } catch (Throwable t) {
        + *     // make sure to report any exceptions including unchecked ones.
        + *     errorType = getCause(t).getClass().getCanonicalName();
        + *     throw t;
        + * } finally {
        + *     InstrumentationAttributes attributes = errorType == null
        + *         ? successAttributes
        + *         : successAttributes.put("error.type", errorType);
        + *
        + *     counter.add(batch.size(), attributes, null);
        + * }
        + *
        + * 
        + * + * + */ +public interface LongCounter { + /** + * Records a value with a set of attributes. + * + * @param value The amount of the measurement. + * @param attributes Collection of attributes representing metric dimensions. + * @param context The explicit context to associate with this measurement. + */ + void add(long value, InstrumentationAttributes attributes, InstrumentationContext context); + + /** + * Flag indicating if metric implementation is detected and functional, use it to minimize performance impact associated with metrics, + * e.g. measuring latency. + * + * @return {@code true} if enabled, {@code false} otherwise + */ + boolean isEnabled(); +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/metrics/Meter.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/metrics/Meter.java new file mode 100644 index 000000000000..acac2e71b0c0 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/metrics/Meter.java @@ -0,0 +1,141 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.instrumentation.metrics; + +import java.util.List; + +/** + * Represents a meter - a component that creates instruments. + *

        This interface is intended to be used by client libraries only. Application developers should use OpenTelemetry API directly

        + */ +public interface Meter { + /** + * Creates histogram instrument allowing to record distribution of a double value values. + * Histograms should be used for latency or other measurements where distribution of values is important and values are + * statistically bounded. + *

        + * See Histogram definition + * and conventions for more details. + *

        + * Avoid creating new histograms for each request. Histogram lifetime should usually match the client lifetime. + * + *

        +     *
        +     * List<Double> bucketBoundariesAdvice = Collections.unmodifiableList(Arrays.asList(0.005d, 0.01d, 0.025d, 0.05d, 0.075d,
        +     *     0.1d, 0.25d, 0.5d, 0.75d, 1d, 2.5d, 5d, 7.5d, 10d));
        +     * DoubleHistogram histogram = meter.createDoubleHistogram("contoso.sample.client.operation.duration",
        +     *     "s",
        +     *     "Contoso sample client operation duration", bucketBoundariesAdvice);
        +     * InstrumentationAttributes successAttributes  = instrumentation.createAttributes(
        +     *     Collections.singletonMap("operation.name", "{operationName}"));
        +     *
        +     * long startTime = System.nanoTime();
        +     * String errorType = null;
        +     *
        +     * try {
        +     *     performOperation();
        +     * } catch (Throwable t) {
        +     *     // make sure to report any exceptions including unchecked ones.
        +     *     errorType = getCause(t).getClass().getCanonicalName();
        +     *     throw t;
        +     * } finally {
        +     *     InstrumentationAttributes attributes = errorType == null
        +     *         ? successAttributes
        +     *         : successAttributes.put("error.type", errorType);
        +     *
        +     *     histogram.record((System.nanoTime() - startTime) / 1e9, attributes, null);
        +     * }
        +     *
        +     * 
        + * + * + * @param name short histogram name following naming conventions. Required + * @param description free-form text describing the instrument. Required + * @param unit optional unit of measurement following units conventions. Required + * @param bucketBoundaries list of bucket boundaries for the histogram. Optional + * @return new instance of {@link DoubleHistogram} + * @throws NullPointerException if name or description is null. + */ + DoubleHistogram createDoubleHistogram(String name, String description, String unit, List bucketBoundaries); + + /** + * Creates Counter instrument that is used to record incrementing values, such as number of sent messages or created + * connections. + *

        + * Use {@link Meter#createLongUpDownCounter(String, String, String)} for counters that can go down, + * such as number of active connections or queue size. + *

        + * See Counter definition for more details. + * + *

        +     * LongCounter counter = meter.createLongCounter("sample.client.sent.messages",
        +     *     "Number of messages sent by the client library",
        +     *     "{message}");
        +     * InstrumentationAttributes successAttributes  = instrumentation.createAttributes(
        +     *     Collections.singletonMap("operation.name", "sendBatch"));
        +     * String errorType = null;
        +     * try {
        +     *     sendBatch(batch);
        +     * } catch (Throwable t) {
        +     *     // make sure to report any exceptions including unchecked ones.
        +     *     errorType = getCause(t).getClass().getCanonicalName();
        +     *     throw t;
        +     * } finally {
        +     *     InstrumentationAttributes attributes = errorType == null
        +     *         ? successAttributes
        +     *         : successAttributes.put("error.type", errorType);
        +     *
        +     *     counter.add(batch.size(), attributes, null);
        +     * }
        +     *
        +     * 
        + * + * + * @param name short counter name following naming conventions + * @param description free-form text describing the counter + * @param unit optional unit of measurement following units conventions + * @return new instance of {@link LongCounter} + * @throws NullPointerException if name or description is null. + */ + LongCounter createLongCounter(String name, String description, String unit); + + /** + * Creates UpDownCounter instrument that is used to record values that can go up or down, such as number of active + * connections or queue size. + *

        + * Use {@link Meter#createLongCounter(String, String, String)} for counters that can only go up, + * such as number of sent messages or created connections. + * See UpDownCounter definition for more details. + * + *

        +     * LongCounter upDownCounter = meter.createLongUpDownCounter("sample.client.operation.active",
        +     *     "Number of operations in progress",
        +     *     "{operation}");
        +     * InstrumentationAttributes successAttributes  = instrumentation.createAttributes(
        +     *     Collections.singletonMap("operation.name", "sendBatch"));
        +     * try {
        +     *     upDownCounter.add(1, successAttributes, null);
        +     *     performOperation();
        +     * } finally {
        +     *     upDownCounter.add(-1, successAttributes, null);
        +     * }
        +     *
        +     * 
        + * + * + * @param name short counter name following naming conventions + * @param description free-form text describing the counter + * @param unit optional unit of measurement following units conventions + * @return new instance of {@link LongCounter} + * @throws NullPointerException if name or description is null. + */ + LongCounter createLongUpDownCounter(String name, String description, String unit); + + /** + * Checks if Meter implementation was found, and it's enabled. + * + * @return true if Meter is enabled, false otherwise. + */ + boolean isEnabled(); +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/metrics/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/metrics/package-info.java new file mode 100644 index 000000000000..8e1d8933d70f --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/metrics/package-info.java @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing core metrics primitives to be used by client libraries. + *

        + * + * Classes in this package are intended to be used by client libraries only. Application developers + * should use OpenTelemetry API directly + */ +package io.clientcore.core.instrumentation.metrics; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/package-info.java index 63fa95b9eba6..e813bf623a70 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/package-info.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/package-info.java @@ -27,6 +27,8 @@ * AutoConfiguredOpenTelemetrySdk.initialize(); * * SampleClient client = new SampleClientBuilder().build(); + * + * // this call will be traced using OpenTelemetry SDK initialized globally * client.clientCall(); * *

        @@ -40,11 +42,13 @@ * *
          *
        - * OpenTelemetry openTelemetry =  AutoConfiguredOpenTelemetrySdk.initialize().getOpenTelemetrySdk();
        - * InstrumentationOptions<OpenTelemetry> instrumentationOptions = new InstrumentationOptions<OpenTelemetry>()
        - *     .setProvider(openTelemetry);
        + * OpenTelemetry openTelemetry = AutoConfiguredOpenTelemetrySdk.initialize().getOpenTelemetrySdk();
        + * HttpInstrumentationOptions instrumentationOptions = new HttpInstrumentationOptions()
        + *     .setTelemetryProvider(openTelemetry);
          *
          * SampleClient client = new SampleClientBuilder().instrumentationOptions(instrumentationOptions).build();
        + *
        + * // this call will be traced using OpenTelemetry SDK provided explicitly
          * client.clientCall();
          *
          * 
        @@ -79,7 +83,7 @@ * Implicit context propagation works best in synchronous code. Implicit context propagation may not work in * asynchronous scenarios depending on the async framework used by the application, implementation details, * and OpenTelemetry instrumentation's used. - * + *

        * When writing asynchronous code, it's recommended to use explicit context propagation. * *

        Pass context explicitly to correlate them with library telemetry in async code

        @@ -90,6 +94,7 @@ * Tracer tracer = GlobalOpenTelemetry.getTracer("sample"); * Span span = tracer.spanBuilder("my-operation") * .startSpan(); + * * SampleClient client = new SampleClientBuilder().build(); * * // Propagating context implicitly is preferred way in synchronous code. diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/tracing/NoopInstrumentationContext.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/tracing/NoopInstrumentationContext.java deleted file mode 100644 index 98938a193094..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/tracing/NoopInstrumentationContext.java +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.instrumentation.tracing; - -import io.clientcore.core.instrumentation.InstrumentationContext; - -final class NoopInstrumentationContext implements InstrumentationContext { - public static final NoopInstrumentationContext INSTANCE = new NoopInstrumentationContext(); - - private NoopInstrumentationContext() { - } - - @Override - public String getTraceId() { - return null; - } - - @Override - public String getSpanId() { - return null; - } - - @Override - public String getTraceFlags() { - return null; - } - - @Override - public boolean isValid() { - return false; - } - - @Override - public Span getSpan() { - return Span.noop(); - } -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/tracing/NoopSpan.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/tracing/NoopSpan.java index 8ec976b911b7..ed64989430a7 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/tracing/NoopSpan.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/tracing/NoopSpan.java @@ -3,6 +3,7 @@ package io.clientcore.core.instrumentation.tracing; +import io.clientcore.core.implementation.instrumentation.NoopInstrumentationContext; import io.clientcore.core.instrumentation.InstrumentationContext; final class NoopSpan implements Span { diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/tracing/SpanBuilder.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/tracing/SpanBuilder.java index 0671a2d31721..ee118c107f9b 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/tracing/SpanBuilder.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/tracing/SpanBuilder.java @@ -3,6 +3,8 @@ package io.clientcore.core.instrumentation.tracing; +import io.clientcore.core.instrumentation.InstrumentationAttributes; + /** * Represents a span builder. *

        This interface is intended to be used by client libraries only. Application developers should use OpenTelemetry API directly

        @@ -25,6 +27,18 @@ public interface SpanBuilder { */ SpanBuilder setAttribute(String key, Object value); + /** + * Sets attributes on the span builder. + *

        + * Attributes added on span builder are used to make sampling decisions, + * and if the span is sampled, they are added to the resulting span. + *

        + * When adding attributes, make sure to follow OpenTelemetry semantic conventions + * @param attributes The attributes to set. + * @return Updated {@link SpanBuilder} object. + */ + SpanBuilder setAllAttributes(InstrumentationAttributes attributes); + /** * Starts the span. * diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/tracing/Tracer.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/tracing/Tracer.java index 577dd3dc3aac..9bd30c56d860 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/tracing/Tracer.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/instrumentation/tracing/Tracer.java @@ -17,10 +17,11 @@ public interface Tracer { *

        * *

        Basic tracing instrumentation for a service method:

        - * + * *
              *
        -     * Span span = tracer.spanBuilder("{operationName}", SpanKind.CLIENT, null)
        +     * InstrumentationContext context = requestOptions == null ? null : requestOptions.getInstrumentationContext();
        +     * Span span = tracer.spanBuilder("{operationName}", SpanKind.CLIENT, context)
              *     .startSpan();
              *
              * // we'll propagate context implicitly using span.makeCurrent() as shown later.
        @@ -33,10 +34,11 @@ public interface Tracer {
              * }
              *
              * try (TracingScope scope = span.makeCurrent()) {
        -     *     clientCall(requestOptions);
        +     *     Response<?> response = clientCall(requestOptions);
        +     *     response.close();
              * } catch (Throwable t) {
              *     // make sure to report any exceptions including unchecked ones.
        -     *     span.end(t);
        +     *     span.end(getCause(t));
              *     throw t;
              * } finally {
              *     // NOTE: closing the scope does not end the span, span should be ended explicitly.
        @@ -44,10 +46,10 @@ public interface Tracer {
              * }
              *
              * 
        - * + * * *

        Adding attributes to spans:

        - * + * *
              *
              * Span sendSpan = tracer.spanBuilder("send {queue-name}", SpanKind.PRODUCER, null)
        @@ -63,7 +65,8 @@ public interface Tracer {
              *         sendSpan.setAttribute("messaging.message.id", "{message-id}");
              *     }
              *
        -     *     clientCall(requestOptions);
        +     *     Response<?> response = clientCall(requestOptions);
        +     *     response.close();
              * } catch (Throwable t) {
              *     sendSpan.end(t);
              *     throw t;
        @@ -72,7 +75,7 @@ public interface Tracer {
              * }
              *
              * 
        - * + * * * @param spanName The name of the span. * @param spanKind The kind of the span. diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/CloudEvent.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/CloudEvent.java new file mode 100644 index 000000000000..48a2347181e1 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/CloudEvent.java @@ -0,0 +1,675 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonSerializable; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.serialization.json.JsonWriter; +import io.clientcore.core.utils.CoreUtils; + +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +/** + * Represents the CloudEvent conforming to the 1.0 schema defined by the + * Cloud Native Computing Foundation. + * + *

        + * CloudEvents is a specification for describing event data in common formats to provide interoperability across + * services, platforms and systems. + *

        + *

        + * Depending on your scenario, you can either use the constructor + * {@link #CloudEvent(String, String, BinaryData, CloudEventDataFormat, String)} to create a CloudEvent, or use the + * factory method {@link #fromString(String)} to deserialize CloudEvent instances from a Json String representation of + * CloudEvents. + *

        + * + *

        + * If you have the data payload of a CloudEvent and want to send it out, use the constructor + * {@link #CloudEvent(String, String, BinaryData, CloudEventDataFormat, String)} to create it. Then you can serialize + * the CloudEvent into its Json String representation and send it. + *

        + * + *

        + * Create CloudEvent Samples + *

        + * + *
        + * // Use BinaryData.fromBytes() to create data in format CloudEventDataFormat.BYTES
        + * byte[] exampleBytes = "Hello World".getBytes(StandardCharsets.UTF_8);
        + * CloudEvent cloudEvent = new CloudEvent("/cloudevents/example/source", "Example.EventType",
        + *     BinaryData.fromBytes(exampleBytes), CloudEventDataFormat.BYTES, "application/octet-stream");
        + *
        + * // Use BinaryData.fromObject() to create CloudEvent data in format CloudEventDataFormat.JSON
        + * // From a model class
        + * User user = new User("Stephen", "James");
        + * CloudEvent cloudEventDataObject = new CloudEvent("/cloudevents/example/source", "Example.EventType",
        + *     BinaryData.fromObject(user), CloudEventDataFormat.JSON, "application/json");
        + *
        + * // From a String
        + * CloudEvent cloudEventDataStr = new CloudEvent("/cloudevents/example/source", "Example.EventType",
        + *     BinaryData.fromObject("Hello World"), CloudEventDataFormat.JSON, "text/plain");
        + *
        + * // From an Integer
        + * CloudEvent cloudEventDataInt = new CloudEvent("/cloudevents/example/source", "Example.EventType",
        + *     BinaryData.fromObject(1), CloudEventDataFormat.JSON, "int");
        + *
        + * // From a Boolean
        + * CloudEvent cloudEventDataBool = new CloudEvent("/cloudevents/example/source", "Example.EventType",
        + *     BinaryData.fromObject(true), CloudEventDataFormat.JSON, "bool");
        + *
        + * // From null
        + * CloudEvent cloudEventDataNull = new CloudEvent("/cloudevents/example/source", "Example.EventType",
        + *     BinaryData.fromObject(null), CloudEventDataFormat.JSON, "null");
        + *
        + * // Use BinaryData.fromString() if you have a Json String for the CloudEvent data.
        + * String jsonStringForData = "\"Hello World\"";  // A json String.
        + * CloudEvent cloudEventDataJsonStr = new CloudEvent("/cloudevents/example/source", "Example.EventType",
        + *     BinaryData.fromString(jsonStringForData), CloudEventDataFormat.JSON, "text/plain");
        + * 
        + * + * + *

        + * On the contrary, if you receive CloudEvents and have the Json string representation of one or more of + * CloudEvents, use {@link #fromString(String)} to deserialize them from the Json string. + *

        + * + *

        + * Deserialize CloudEvent Samples + *

        + * + *
        + * List<CloudEvent> cloudEventList = CloudEvent.fromString(cloudEventJsonString);
        + * CloudEvent cloudEvent = cloudEventList.get(0);
        + * BinaryData cloudEventData = cloudEvent.getData();
        + *
        + * byte[] bytesValue = cloudEventData.toBytes();  // If data payload is in bytes (data_base64 is not null).
        + * User objectValue = cloudEventData.toObject(User.class);  // If data payload is a User object.
        + * int intValue = cloudEventData.toObject(Integer.class);  // If data payload is an int.
        + * boolean boolValue = cloudEventData.toObject(Boolean.class);  // If data payload is boolean.
        + * String stringValue = cloudEventData.toObject(String.class);  // If data payload is String.
        + * String jsonStringValue = cloudEventData.toString();  // The data payload represented in Json String.
        + * 
        + * + */ +@Metadata(properties = MetadataProperties.FLUENT) +public final class CloudEvent implements JsonSerializable { + private static final String SPEC_VERSION = "1.0"; + + private static final ClientLogger LOGGER = new ClientLogger(CloudEvent.class); + private static final Set RESERVED_ATTRIBUTE_NAMES = new HashSet<>(Arrays.asList("specversion", "id", + "source", "type", "datacontenttype", "dataschema", "subject", "time", "data", "data_base64")); + + private static final String ILLEGAL_ATTRIBUTE_NAME_MESSAGE = "Extension attribute 'name' must have only lower-case " + + "alphanumeric characters and not be one of the CloudEvent reserved attribute names: " + + String.join(", ", RESERVED_ATTRIBUTE_NAMES); + + /* + * An identifier for the event. The combination of id and source must be + * unique for each distinct event. + */ + private String id; + + /* + * Identifies the context in which an event happened. The combination of id + * and source must be unique for each distinct event. + */ + private String source; + + /* + * Event data specific to the event type. This is internal only for data serialization. + */ + private String data; + + /* + * Event data specific to the event type, encoded as a base64 string. This is internal only for + * data_base64 serialization. + */ + private String dataBase64; + + /* + * Type of event related to the originating occurrence. + */ + private String type; + + /* + * The time (in UTC) the event was generated, in RFC3339 format. + */ + private OffsetDateTime time; + + /* + * The version of the CloudEvents specification which the event uses. + */ + private String specVersion; + + /* + * Identifies the schema that data adheres to. + */ + private String dataSchema; + + /* + * Content type of data value. + */ + private String dataContentType; + + /* + * This describes the subject of the event in the context of the event + * producer (identified by source). + */ + private String subject; + + private Map extensionAttributes; + + /* + * Cache serialized data for getData() + */ + private BinaryData binaryData; + + /** + * Create an instance of {@link CloudEvent}. + * + *

        {@code source}, {@code type}, {@code id}, and {@code specversion} are required attributes according to the + * CNCF CloudEvent spec. + * You must set the {@code source} and {@code type} when using this constructor. For convenience, {@code id} and + * {@code specversion} are automatically assigned. You can change the {@code id} by using {@link #setId(String)} + * after you create a CloudEvent. But you can not change {@code specversion} because this class is specifically for + * CloudEvent 1.0 schema.

        + * + *

        For the CloudEvent data payload, this constructor accepts {@code data} of {@link BinaryData} as the + * CloudEvent payload. The {@code data} can be created from objects of type String, bytes, boolean, null, array or + * other types. A CloudEvent will be serialized to its Json String representation to be sent out. Use param + * {@code format} to indicate whether the {@code data} will be serialized as bytes, or Json. When + * {@link CloudEventDataFormat#BYTES} is used, the data payload will be serialized to base64 bytes and stored in + * attribute data_base64 of the CloudEvent's Json representation. When {@link CloudEventDataFormat#JSON} is + * used, the data payload will be serialized as Json data and stored in attribute data of the CloudEvent's + * Json representation.

        + * + *

        Create CloudEvent Samples

        + * + *
        +     * // Use BinaryData.fromBytes() to create data in format CloudEventDataFormat.BYTES
        +     * byte[] exampleBytes = "Hello World".getBytes(StandardCharsets.UTF_8);
        +     * CloudEvent cloudEvent = new CloudEvent("/cloudevents/example/source", "Example.EventType",
        +     *     BinaryData.fromBytes(exampleBytes), CloudEventDataFormat.BYTES, "application/octet-stream");
        +     *
        +     * // Use BinaryData.fromObject() to create CloudEvent data in format CloudEventDataFormat.JSON
        +     * // From a model class
        +     * User user = new User("Stephen", "James");
        +     * CloudEvent cloudEventDataObject = new CloudEvent("/cloudevents/example/source", "Example.EventType",
        +     *     BinaryData.fromObject(user), CloudEventDataFormat.JSON, "application/json");
        +     *
        +     * // From a String
        +     * CloudEvent cloudEventDataStr = new CloudEvent("/cloudevents/example/source", "Example.EventType",
        +     *     BinaryData.fromObject("Hello World"), CloudEventDataFormat.JSON, "text/plain");
        +     *
        +     * // From an Integer
        +     * CloudEvent cloudEventDataInt = new CloudEvent("/cloudevents/example/source", "Example.EventType",
        +     *     BinaryData.fromObject(1), CloudEventDataFormat.JSON, "int");
        +     *
        +     * // From a Boolean
        +     * CloudEvent cloudEventDataBool = new CloudEvent("/cloudevents/example/source", "Example.EventType",
        +     *     BinaryData.fromObject(true), CloudEventDataFormat.JSON, "bool");
        +     *
        +     * // From null
        +     * CloudEvent cloudEventDataNull = new CloudEvent("/cloudevents/example/source", "Example.EventType",
        +     *     BinaryData.fromObject(null), CloudEventDataFormat.JSON, "null");
        +     *
        +     * // Use BinaryData.fromString() if you have a Json String for the CloudEvent data.
        +     * String jsonStringForData = "\"Hello World\"";  // A json String.
        +     * CloudEvent cloudEventDataJsonStr = new CloudEvent("/cloudevents/example/source", "Example.EventType",
        +     *     BinaryData.fromString(jsonStringForData), CloudEventDataFormat.JSON, "text/plain");
        +     * 
        + * + * + * @param source Identifies the context in which an event happened. The combination of id and source must be unique + * for each distinct event. + * @param type Type of event related to the originating occurrence. + * @param data A {@link BinaryData} that wraps the original data, which can be a String, byte[], or model class. + * @param format Set to {@link CloudEventDataFormat#BYTES} to serialize the data to base64 format, or + * {@link CloudEventDataFormat#JSON} to serialize the data to JSON value. + * @param dataContentType The content type of the data. It has no impact on how the data is serialized but tells the + * event subscriber how to use the data. Typically, the value is of MIME types such as "application/json", + * "text/plain", "text/xml", "avro/binary", etc. It can be null. + * @throws NullPointerException If source or type is null or format is null while data isn't null. + * @throws IllegalArgumentException if format is {@link CloudEventDataFormat#JSON} but the data isn't in a correct + * JSON format. + */ + public CloudEvent(String source, String type, BinaryData data, CloudEventDataFormat format, + String dataContentType) { + this.source = Objects.requireNonNull(source, "'source' cannot be null."); + this.type = Objects.requireNonNull(type, "'type' cannot be null."); + + if (data != null) { + Objects.requireNonNull(format, "'format' cannot be null when 'data' isn't null."); + if (CloudEventDataFormat.BYTES == format) { + this.dataBase64 = Base64.getEncoder().encodeToString(data.toBytes()); + } else { + try (JsonReader jsonReader = JsonReader.fromBytes(data.toBytes())) { + JsonToken token = jsonReader.nextToken(); + if (token == JsonToken.START_OBJECT || token == JsonToken.START_ARRAY) { + this.data = jsonReader.readChildren(); + } else if (token == JsonToken.STRING) { + this.data = "\"" + jsonReader.getString() + "\""; + } else { + this.data = jsonReader.getString(); + } + } catch (IOException e) { + throw LOGGER + .logThrowableAsError(new IllegalArgumentException("'data' isn't in valid Json format", e)); + } + } + } + + this.dataContentType = dataContentType; + this.id = CoreUtils.randomUuid().toString(); + this.specVersion = CloudEvent.SPEC_VERSION; + this.binaryData = data; + this.time = OffsetDateTime.now(ZoneOffset.UTC); + } + + private CloudEvent() { + // for deserialization + } + + /** + * Deserialize {@link CloudEvent} JSON string representation that has one CloudEvent object or an array of + * CloudEvent objects into a list of CloudEvents, and validate whether any CloudEvents have null {@code id}, + * {@code source}, or {@code type}. If you want to skip this validation, use {@link #fromString(String, boolean)}. + * + *

        Deserialize CloudEvent Samples

        + * + *
        +     * List<CloudEvent> cloudEventList = CloudEvent.fromString(cloudEventJsonString);
        +     * CloudEvent cloudEvent = cloudEventList.get(0);
        +     * BinaryData cloudEventData = cloudEvent.getData();
        +     *
        +     * byte[] bytesValue = cloudEventData.toBytes();  // If data payload is in bytes (data_base64 is not null).
        +     * User objectValue = cloudEventData.toObject(User.class);  // If data payload is a User object.
        +     * int intValue = cloudEventData.toObject(Integer.class);  // If data payload is an int.
        +     * boolean boolValue = cloudEventData.toObject(Boolean.class);  // If data payload is boolean.
        +     * String stringValue = cloudEventData.toObject(String.class);  // If data payload is String.
        +     * String jsonStringValue = cloudEventData.toString();  // The data payload represented in Json String.
        +     * 
        + * + * + * @param cloudEventsJson the JSON payload containing one or more events. + * @return all the events in the payload deserialized as {@link CloudEvent CloudEvents}. + * @throws NullPointerException if cloudEventsJson is null. + * @throws IllegalArgumentException if the input parameter isn't a correct JSON string for a CloudEvent or an array + * of CloudEvents, or any deserialized CloudEvents have null {@code id}, {@code source}, or {@code type}. + */ + public static List fromString(String cloudEventsJson) { + return fromString(cloudEventsJson, false); + } + + /** + * Deserialize {@link CloudEvent CloudEvents} JSON string representation that has one CloudEvent object or an array + * of CloudEvent objects into a list of CloudEvents. + * + * @param cloudEventsJson the JSON payload containing one or more events. + * @param skipValidation set to true if you'd like to skip the validation for the deserialized CloudEvents. A valid + * CloudEvent should have 'id', 'source' and 'type' not null. + * @return all the events in the payload deserialized as {@link CloudEvent CloudEvents}. + * @throws NullPointerException if cloudEventsJson is null. + * @throws IllegalArgumentException if the input parameter isn't a JSON string for a CloudEvent or an array of + * CloudEvents, or skipValidation is false and any CloudEvents have null id', 'source', or 'type'. + */ + public static List fromString(String cloudEventsJson, boolean skipValidation) { + Objects.requireNonNull(cloudEventsJson, "'cloudEventsJson' cannot be null"); + + List cloudEvents; + try (JsonReader jsonReader = JsonReader.fromString(cloudEventsJson)) { + JsonToken arrayOrObjectCheckToken = jsonReader.nextToken(); + if (arrayOrObjectCheckToken == JsonToken.START_OBJECT) { + cloudEvents = new ArrayList<>(1); + cloudEvents.add(jsonReader.readObject(CloudEvent::fromJson)); + } else if (arrayOrObjectCheckToken == JsonToken.START_ARRAY) { + cloudEvents = jsonReader.readArray(CloudEvent::fromJson); + } else if (arrayOrObjectCheckToken == JsonToken.NULL) { + return null; + } else { + throw LOGGER.logThrowableAsError(new IllegalArgumentException("JSON string started at an invalid state " + + "for reading a single instance or an array of CloudEvents. Starting token was: " + + arrayOrObjectCheckToken)); + } + } catch (IOException ex) { + throw LOGGER.logThrowableAsError(new IllegalArgumentException(ex)); + } + + if (skipValidation || cloudEvents == null) { + return cloudEvents; + } + + for (int i = 0; i < cloudEvents.size(); i++) { + CloudEvent event = cloudEvents.get(i); + if (event.getId() == null || event.getSource() == null || event.getType() == null) { + List nullAttributes = new ArrayList<>(); + if (event.getId() == null) { + nullAttributes.add("'id'"); + } + if (event.getSource() == null) { + nullAttributes.add("'source'"); + } + if (event.getType() == null) { + nullAttributes.add("'type'"); + } + throw LOGGER.logThrowableAsError(new IllegalArgumentException("'id', 'source' and 'type' are mandatory " + + "attributes for a CloudEvent according to the spec. This JSON string doesn't have " + + String.join(", ", nullAttributes) + " for the object at index " + i + ". Please make " + + "sure the input Json string has the required attributes or use " + + "CloudEvent.fromString(cloudEventsJson, true) to skip the null check.")); + } + } + + return cloudEvents; + } + + /** + * Get the id of the cloud event. + * + * @return the id. + */ + public String getId() { + return this.id; + } + + /** + * Set a custom id. Note that a random id is already set by default. + * + * @param id the id to set. + * @return the cloud event itself. + * @throws NullPointerException if id is null. + * @throws IllegalArgumentException if id is empty. + */ + public CloudEvent setId(String id) { + Objects.requireNonNull(id, "'id' cannot be null"); + if (id.isEmpty()) { + throw LOGGER.logThrowableAsError(new IllegalArgumentException("'id' cannot be empty")); + } + this.id = id; + return this; + } + + /** + * Get the source of the event. + * + * @return the source. + */ + public String getSource() { + return this.source; + } + + /** + * Get the data associated with this event as a {@link BinaryData}, which has API to deserialize the data into a + * String, an Object, or a byte[]. + * + * @return A {@link BinaryData} that wraps the event's data payload. + */ + public BinaryData getData() { + if (this.binaryData == null) { + if (this.data != null) { + this.binaryData = BinaryData.fromString(this.data); + } else if (this.dataBase64 != null) { + this.binaryData = BinaryData.fromBytes(Base64.getDecoder().decode(this.dataBase64)); + } + } + return this.binaryData; + } + + /** + * Get the type of event, e.g. "Contoso.Items.ItemReceived". + * + * @return the type of the event. + */ + public String getType() { + return this.type; + } + + /** + * Get the time associated with the occurrence of the event. + * + * @return the event time, or null if the time is not set. + */ + public OffsetDateTime getTime() { + return this.time; + } + + /** + * Set the time associated with the occurrence of the event. + *

        + * At creation, the time is set to the current UTC time. It can be unset by setting it to null. + * + * @param time the time to set. + * @return the cloud event itself. + */ + public CloudEvent setTime(OffsetDateTime time) { + this.time = time; + return this; + } + + /** + * Get the content MIME type that the data is in. + * + * @return the content type the data is in, or null it is not set. + */ + public String getDataContentType() { + return this.dataContentType; + } + + /** + * Get the schema that the data adheres to. + * + * @return a URI of the data schema, or null if it is not set. + */ + public String getDataSchema() { + return this.dataSchema; + } + + /** + * Set the schema that the data adheres to. + * + * @param dataSchema a String identifying the schema of the data. The CNCF CloudEvent spec dataschema is + * defined as a URI. For compatibility with legacy system, this class accepts any String. But for interoperability, + * you should use a URI format string. + * @return the cloud event itself. + */ + public CloudEvent setDataSchema(String dataSchema) { + this.dataSchema = dataSchema; + return this; + } + + /** + * Get the subject associated with this event. + * + * @return the subject, or null if it is not set. + */ + public String getSubject() { + return this.subject; + } + + /** + * Set the subject of the event. + * + * @param subject the subject to set. + * @return the cloud event itself. + */ + public CloudEvent setSubject(String subject) { + this.subject = subject; + return this; + } + + /** + * Get a map of the additional user-defined attributes associated with this event. + * + * @return an unmodifiable map of the extension attributes. + */ + public Map getExtensionAttributes() { + return this.extensionAttributes == null + ? Collections.emptyMap() + : Collections.unmodifiableMap(this.extensionAttributes); + } + + /** + * Add/Overwrite a single extension attribute to the cloud event. + * + * @param name the name of the attribute. It must contain only lower-case alphanumeric characters and not be any + * CloudEvent reserved attribute names. + * @param value the value to associate with the name. + * @return the cloud event itself. + * @throws NullPointerException if name or value is null. + * @throws IllegalArgumentException if name format isn't correct. + */ + public CloudEvent addExtensionAttribute(String name, Object value) { + Objects.requireNonNull(name, "'name' cannot be null."); + Objects.requireNonNull(value, "'value' cannot be null."); + if (!validateAttributeName(name)) { + throw LOGGER.logThrowableAsError(new IllegalArgumentException(ILLEGAL_ATTRIBUTE_NAME_MESSAGE)); + } + if (this.extensionAttributes == null) { + this.extensionAttributes = new HashMap<>(); + } + this.extensionAttributes.put(name, value); + return this; + } + + /** + * Get the spec version. Users don't need to access it because it's always 1.0. Make it package level to test + * deserialization. + * + * @return The spec version. + */ + String getSpecVersion() { + return this.specVersion; + } + + /** + * Set the spec version. Users don't need to access it because it's always 1.0. Make it package level to test + * serialization. + * + * @return the cloud event itself. + */ + CloudEvent setSpecVersion(String specVersion) { + this.specVersion = specVersion; + return this; + } + + private static boolean validateAttributeName(String name) { + if (RESERVED_ATTRIBUTE_NAMES.contains(name)) { + return false; + } + for (int i = 0; i < name.length(); i++) { + char c = name.charAt(i); + if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))) { + return false; + } + } + return true; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject().writeStringField("id", id).writeStringField("source", source); + + if (dataBase64 != null) { + jsonWriter.writeStringField("data_base64", dataBase64); + } else if (data != null) { + jsonWriter.writeRawField("data", data); + } else { + jsonWriter.writeNullField("data"); + } + + jsonWriter.writeStringField("type", type); + + if (time != null) { + jsonWriter.writeStringField("time", time.toString()); + } + + jsonWriter.writeStringField("specversion", specVersion) + .writeStringField("dataschema", dataSchema) + .writeStringField("datacontenttype", dataContentType) + .writeStringField("subject", subject); + + if (!CoreUtils.isNullOrEmpty(extensionAttributes)) { + for (Map.Entry extensionAttribute : extensionAttributes.entrySet()) { + jsonWriter.writeUntypedField(String.valueOf(extensionAttribute.getKey()), + extensionAttribute.getValue()); + } + } + + return jsonWriter.writeEndObject(); + } + + /** + * Reads a JSON stream into a {@link CloudEvent}. + * + * @param jsonReader The {@link JsonReader} being read. + * @return The {@link CloudEvent} that the JSON stream represented, or null if it pointed to JSON null. + * @throws IOException If a {@link CloudEvent} fails to be read from the {@code jsonReader}. + */ + public static CloudEvent fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CloudEvent cloudEvent = new CloudEvent(); + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + JsonToken token = reader.nextToken(); + + if ("id".equals(fieldName)) { + cloudEvent.id = reader.getString(); + } else if ("source".equals(fieldName)) { + cloudEvent.source = reader.getString(); + } else if ("data".equals(fieldName)) { + if (token == JsonToken.START_OBJECT || token == JsonToken.START_ARRAY) { + cloudEvent.data = jsonReader.readChildren(); + } else if (token == JsonToken.STRING) { + cloudEvent.data = "\"" + jsonReader.getRawText() + "\""; + } else { + cloudEvent.data = jsonReader.getString(); + } + } else if ("data_base64".equals(fieldName)) { + cloudEvent.dataBase64 = reader.getString(); + } else if ("type".equals(fieldName)) { + cloudEvent.type = reader.getString(); + } else if ("time".equals(fieldName)) { + cloudEvent.time = reader.getNullable(r -> OffsetDateTime.parse(r.getString())); + } else if ("specversion".equals(fieldName)) { + cloudEvent.specVersion = reader.getString(); + } else if ("dataschema".equals(fieldName)) { + cloudEvent.dataSchema = reader.getString(); + } else if ("datacontenttype".equals(fieldName)) { + cloudEvent.dataContentType = reader.getString(); + } else if ("subject".equals(fieldName)) { + cloudEvent.subject = reader.getString(); + } else { + if (cloudEvent.extensionAttributes == null) { + cloudEvent.extensionAttributes = new LinkedHashMap<>(); + } + + cloudEvent.extensionAttributes.put(fieldName, reader.readUntyped()); + } + } + + return cloudEvent; + }); + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/CloudEventDataFormat.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/CloudEventDataFormat.java new file mode 100644 index 000000000000..41f534c0a445 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/CloudEventDataFormat.java @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.utils.ExpandableEnum; + +/** + * Representation of the data format for a {@link CloudEvent}. + *

        + * When constructing a {@link CloudEvent} this is passed to determine the serialized format of the event's data. + * If {@link #BYTES} is used the data will be stored as a Base64 encoded string, + * otherwise it will be stored as a JSON serialized object. + * + * @see CloudEvent#CloudEvent(String, String, BinaryData, CloudEventDataFormat, String) + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public final class CloudEventDataFormat implements ExpandableEnum { + private final String value; + + private CloudEventDataFormat(String value) { + this.value = value; + } + + /** + * Bytes format. + */ + public static final CloudEventDataFormat BYTES = new CloudEventDataFormat("BYTES"); + + /** + * JSON format. + */ + public static final CloudEventDataFormat JSON = new CloudEventDataFormat("JSON"); + + @Override + public String getValue() { + return value; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/ServerSentResult.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/ServerSentResult.java new file mode 100644 index 000000000000..916015472d4c --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/ServerSentResult.java @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; + +import java.io.IOException; +import java.time.Duration; +import java.util.List; + +/** + * Class to hold the result for a retry of an ServerSentEvent content type request. + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public final class ServerSentResult { + private final String lastEventId; + private final Duration retryAfter; + private final IOException ioException; + private final List data; + + /** + * Creates a new instance of the {@link ServerSentResult} class. + * + * @param exception The exception that occurred during the request. + * @param lastEventId The last event id from the text event stream. + * @param retryAfter The retry time duration. + * @param data The accumulated event data from the text event stream. + */ + public ServerSentResult(IOException exception, String lastEventId, Duration retryAfter, List data) { + this.ioException = exception; + this.lastEventId = lastEventId; + this.retryAfter = retryAfter; + this.data = data; + } + + /** + * Get the accumulated event data from the text event stream. + * + * @return The accumulated event data from the text event stream. + */ + public List getData() { + return data; + } + + /** + * Get the exception that occurred during the request. + * + * @return The exception that occurred during the request. + */ + public IOException getException() { + return ioException; + } + + /** + * Get the last event id from the text event stream. + * + * @return The last event id from the text event stream. + */ + public String getLastEventId() { + return lastEventId; + } + + /** + * Get the retry time duration. + * + * @return The retry time duration. + */ + public Duration getRetryAfter() { + return retryAfter; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/binarydata/BinaryData.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/binarydata/BinaryData.java similarity index 95% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/util/binarydata/BinaryData.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/models/binarydata/BinaryData.java index d8805abe1d31..461a233c222d 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/binarydata/BinaryData.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/binarydata/BinaryData.java @@ -1,11 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.util.binarydata; +package io.clientcore.core.models.binarydata; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.serialization.json.JsonSerializer; +import io.clientcore.core.serialization.ObjectSerializer; import io.clientcore.core.serialization.json.JsonWriter; -import io.clientcore.core.implementation.util.JsonSerializer; -import io.clientcore.core.util.serializer.ObjectSerializer; import java.io.Closeable; import java.io.IOException; @@ -113,6 +115,7 @@ * @see ObjectSerializer * @see More about serialization */ +@Metadata(properties = MetadataProperties.IMMUTABLE) public abstract class BinaryData implements Closeable { private static final BinaryData EMPTY = BinaryData.fromBytes(new byte[0]); @@ -258,7 +261,7 @@ public static BinaryData fromBytes(byte[] data) { * @return A {@link BinaryData} representing the {@link ByteBuffer}. * @throws NullPointerException If {@code data} is null. */ - public static BinaryData fromByteBuffer(ByteBuffer data) { + static BinaryData fromByteBuffer(ByteBuffer data) { return new ByteBufferBinaryData(data); } @@ -285,13 +288,16 @@ public static BinaryData fromByteBuffer(ByteBuffer data) { * @param data The {@link List} of {@link ByteBuffer} that {@link BinaryData} will represent. * @return A {@link BinaryData} representing the {@link List} of {@link ByteBuffer}. */ - public static BinaryData fromListByteBuffer(List data) { + static BinaryData fromListByteBuffer(List data) { return new ListByteBufferBinaryData(data); } /** * Creates an instance of {@link BinaryData} by serializing the {@link Object} using the default - * {@link ObjectSerializer}. + * {@link ObjectSerializer} used internally by ClientCore. + *

        + * If the internal serializer is not suitable for your use case, you can provide your own {@link ObjectSerializer} + * using {@link #fromObject(Object, ObjectSerializer)}. * *

        Creating an instance from an Object

        * @@ -329,7 +335,7 @@ public static BinaryData fromObject(Object data) { * final Person data = new Person().setName("John"); * * // Provide your custom serializer or use the provided serializers. - * final ObjectSerializer serializer = new MyJsonSerializer(); // Replace this with your Serializer + * final JsonSerializer serializer = new MyJsonSerializer(); // Replace this with your Serializer * BinaryData binaryData = BinaryData.fromObject(data, serializer); * * System.out.println(binaryData.toString()); @@ -467,8 +473,8 @@ public static BinaryData fromFile(Path file, Long position, Long length, int chu * *

        This method returns a reference to the underlying byte array. Modifying the contents of the returned byte * array may change the content of this BinaryData instance. If the content source of this BinaryData instance is - * a file, an {@link InputStream}, or a {@code Flux} the source is not modified. To safely update the - * byte array, it is recommended to make a copy of the contents first.

        + * a file or an {@link InputStream} the source is not modified. To safely update the byte array, it is recommended + * to make a copy of the contents first.

        * *

        If the {@link BinaryData} is larger than the maximum size allowed for a {@code byte[]} this will throw an * {@link IllegalStateException}.

        @@ -494,9 +500,12 @@ public static BinaryData fromFile(Path file, Long position, Long length, int chu /** * Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the default - * {@link ObjectSerializer}. Each time this method is called, the content is deserialized and a new instance of type - * {@code T} is returned. So, calling this method repeatedly to convert the underlying data source into the same - * type is not recommended. + * {@link ObjectSerializer} used internally by ClientCore. Each time this method is called, the content is + * deserialized and a new instance of type {@code T} is returned. So, calling this method repeatedly to convert the + * underlying data source into the same type is not recommended. + *

        + * If the internal serializer is not suitable for your use case, you can provide your own {@link ObjectSerializer} + * using {@link #toObject(Type, ObjectSerializer)}. * *

        The type, represented by {@link Type}, can either be a generic or non-generic type. If the type is generic * create a {@link ParameterizedType}, if the type is non-generic use a {@link Class}.

        @@ -585,7 +594,7 @@ public T toObject(Type type) throws IOException { * final Person data = new Person().setName("John"); * * // Provide your custom serializer or use the provided serializers. - * final ObjectSerializer serializer = new MyJsonSerializer(); // Replace this with your Serializer + * final JsonSerializer serializer = new MyJsonSerializer(); // Replace this with your Serializer * BinaryData binaryData = BinaryData.fromObject(data, serializer); * * Person person = binaryData.toObject(Person.class, serializer); @@ -604,7 +613,7 @@ public T toObject(Type type) throws IOException { * personList.add(person1); * personList.add(person2); * - * final ObjectSerializer serializer = new MyJsonSerializer(); // Replace this with your Serializer + * final JsonSerializer serializer = new MyJsonSerializer(); // Replace this with your Serializer * BinaryData binaryData = BinaryData.fromObject(personList, serializer); * * // Creation of the ParameterizedType could be replaced with a utility method that returns a Type based on the diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/binarydata/ByteArrayBinaryData.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/binarydata/ByteArrayBinaryData.java similarity index 88% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/util/binarydata/ByteArrayBinaryData.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/models/binarydata/ByteArrayBinaryData.java index 422df034db78..16ccecfb2776 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/binarydata/ByteArrayBinaryData.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/binarydata/ByteArrayBinaryData.java @@ -1,10 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.util.binarydata; +package io.clientcore.core.models.binarydata; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; import io.clientcore.core.serialization.json.JsonWriter; -import io.clientcore.core.util.serializer.ObjectSerializer; +import io.clientcore.core.serialization.ObjectSerializer; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -17,6 +19,7 @@ /** * A {@link BinaryData} implementation backed by a byte array. */ +@Metadata(properties = MetadataProperties.IMMUTABLE) public final class ByteArrayBinaryData extends BinaryData { private final byte[] content; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/binarydata/ByteBufferBinaryData.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/binarydata/ByteBufferBinaryData.java similarity index 86% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/util/binarydata/ByteBufferBinaryData.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/models/binarydata/ByteBufferBinaryData.java index 10a2d5cc7905..ae810c09aa2f 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/binarydata/ByteBufferBinaryData.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/binarydata/ByteBufferBinaryData.java @@ -1,11 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.util.binarydata; +package io.clientcore.core.models.binarydata; -import io.clientcore.core.implementation.util.ImplUtils; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.implementation.utils.ImplUtils; import io.clientcore.core.serialization.json.JsonWriter; -import io.clientcore.core.util.serializer.ObjectSerializer; +import io.clientcore.core.serialization.ObjectSerializer; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -20,7 +22,8 @@ /** * A {@link BinaryData} implementation backed by a {@link ByteBuffer}. */ -public final class ByteBufferBinaryData extends BinaryData { +@Metadata(properties = MetadataProperties.IMMUTABLE) +final class ByteBufferBinaryData extends BinaryData { private final ByteBuffer content; private volatile byte[] bytes; @@ -33,7 +36,7 @@ public final class ByteBufferBinaryData extends BinaryData { * @param content The {@link ByteBuffer} content. * @throws NullPointerException If {@code content} is null. */ - public ByteBufferBinaryData(ByteBuffer content) { + ByteBufferBinaryData(ByteBuffer content) { this.content = Objects.requireNonNull(content, "'content' cannot be null."); } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/binarydata/FileBinaryData.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/binarydata/FileBinaryData.java similarity index 96% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/util/binarydata/FileBinaryData.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/models/binarydata/FileBinaryData.java index 4b3dfe28af94..ed63b9c250ef 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/binarydata/FileBinaryData.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/binarydata/FileBinaryData.java @@ -1,12 +1,14 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.util.binarydata; +package io.clientcore.core.models.binarydata; -import io.clientcore.core.implementation.util.SliceInputStream; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.implementation.utils.SliceInputStream; import io.clientcore.core.serialization.json.JsonWriter; import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.util.serializer.ObjectSerializer; +import io.clientcore.core.serialization.ObjectSerializer; import java.io.BufferedInputStream; import java.io.FileInputStream; @@ -30,6 +32,7 @@ /** * A {@link BinaryData} implementation backed by a file. */ +@Metadata(properties = MetadataProperties.IMMUTABLE) public class FileBinaryData extends BinaryData { private static final ClientLogger LOGGER = new ClientLogger(FileBinaryData.class); private final Path file; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/binarydata/InputStreamBinaryData.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/binarydata/InputStreamBinaryData.java similarity index 94% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/util/binarydata/InputStreamBinaryData.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/models/binarydata/InputStreamBinaryData.java index ee30aea3f0dd..3155863e6edd 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/binarydata/InputStreamBinaryData.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/binarydata/InputStreamBinaryData.java @@ -1,15 +1,17 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.util.binarydata; +package io.clientcore.core.models.binarydata; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; import io.clientcore.core.implementation.AccessibleByteArrayOutputStream; -import io.clientcore.core.implementation.util.ImplUtils; -import io.clientcore.core.implementation.util.IterableOfByteBuffersInputStream; -import io.clientcore.core.implementation.util.StreamUtil; +import io.clientcore.core.implementation.utils.ImplUtils; +import io.clientcore.core.implementation.utils.IterableOfByteBuffersInputStream; +import io.clientcore.core.implementation.utils.StreamUtil; import io.clientcore.core.serialization.json.JsonWriter; import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.util.serializer.ObjectSerializer; +import io.clientcore.core.serialization.ObjectSerializer; import java.io.IOException; import java.io.InputStream; @@ -27,6 +29,7 @@ /** * A {@link BinaryData} implementation backed by an {@link InputStream}. */ +@Metadata(properties = MetadataProperties.IMMUTABLE) public final class InputStreamBinaryData extends BinaryData { private static final ClientLogger LOGGER = new ClientLogger(InputStreamBinaryData.class); private static final int INITIAL_BUFFER_CHUNK_SIZE = 8 * 1024; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/binarydata/ListByteBufferBinaryData.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/binarydata/ListByteBufferBinaryData.java similarity index 88% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/util/binarydata/ListByteBufferBinaryData.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/models/binarydata/ListByteBufferBinaryData.java index 4938c053e0fd..10f12f6ff380 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/binarydata/ListByteBufferBinaryData.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/binarydata/ListByteBufferBinaryData.java @@ -1,13 +1,15 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.util.binarydata; +package io.clientcore.core.models.binarydata; -import io.clientcore.core.implementation.util.ImplUtils; -import io.clientcore.core.implementation.util.IterableOfByteBuffersInputStream; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.implementation.utils.ImplUtils; +import io.clientcore.core.implementation.utils.IterableOfByteBuffersInputStream; import io.clientcore.core.serialization.json.JsonWriter; import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.util.serializer.ObjectSerializer; +import io.clientcore.core.serialization.ObjectSerializer; import java.io.IOException; import java.io.InputStream; @@ -24,7 +26,8 @@ /** * A {@link BinaryData} implementation backed by a {@link List} of {@link ByteBuffer}. */ -public final class ListByteBufferBinaryData extends BinaryData { +@Metadata(properties = MetadataProperties.IMMUTABLE) +final class ListByteBufferBinaryData extends BinaryData { private static final ClientLogger LOGGER = new ClientLogger(ListByteBufferBinaryData.class); private final List content; @@ -41,7 +44,7 @@ public final class ListByteBufferBinaryData extends BinaryData { * @param content The {@link List} of {@link ByteBuffer} content. * @throws NullPointerException If {@code content} is null. */ - public ListByteBufferBinaryData(List content) { + ListByteBufferBinaryData(List content) { this.content = Objects.requireNonNull(content, "'content' cannot be null."); } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/binarydata/SerializableBinaryData.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/binarydata/SerializableBinaryData.java similarity index 92% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/util/binarydata/SerializableBinaryData.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/models/binarydata/SerializableBinaryData.java index 3853ceb5da31..31a276c4ba31 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/binarydata/SerializableBinaryData.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/binarydata/SerializableBinaryData.java @@ -1,11 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.util.binarydata; +package io.clientcore.core.models.binarydata; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; import io.clientcore.core.serialization.json.JsonWriter; import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.util.serializer.ObjectSerializer; +import io.clientcore.core.serialization.ObjectSerializer; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -20,6 +22,7 @@ /** * A {@link BinaryData} implementation backed by a serializable object. */ +@Metadata(properties = MetadataProperties.IMMUTABLE) public final class SerializableBinaryData extends BinaryData { private static final ClientLogger LOGGER = new ClientLogger(SerializableBinaryData.class); diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/binarydata/StringBinaryData.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/binarydata/StringBinaryData.java similarity index 90% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/util/binarydata/StringBinaryData.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/models/binarydata/StringBinaryData.java index 0ff4ca016473..d55ea41446ee 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/binarydata/StringBinaryData.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/binarydata/StringBinaryData.java @@ -1,10 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.util.binarydata; +package io.clientcore.core.models.binarydata; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; import io.clientcore.core.serialization.json.JsonWriter; -import io.clientcore.core.util.serializer.ObjectSerializer; +import io.clientcore.core.serialization.ObjectSerializer; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -18,6 +20,7 @@ /** * A {@link BinaryData} implementation backed by a String. */ +@Metadata(properties = MetadataProperties.IMMUTABLE) public final class StringBinaryData extends BinaryData { private final String content; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/binarydata/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/binarydata/package-info.java new file mode 100644 index 000000000000..d1b14f18845a --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/binarydata/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Provides classes for working with binary data. + */ +package io.clientcore.core.models.binarydata; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoArray.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoArray.java new file mode 100644 index 000000000000..88305dce535d --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoArray.java @@ -0,0 +1,174 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models.geo; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.instrumentation.logging.ClientLogger; + +import java.util.AbstractList; +import java.util.Collection; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.function.Predicate; +import java.util.function.UnaryOperator; + +/** + *

        Represents a read-only list of geometry coordinates.

        + * + *

        This class encapsulates a list of geometry coordinates and provides methods to access these coordinates. + * The coordinates can be of any type {@code T}.

        + * + * @param The type of geometry coordinates. + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +final class GeoArray extends AbstractList { + private static final String NO_MUTATION_MESSAGE = "GeoArray cannot be mutated."; + // GeoArray is a commonly used model, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(GeoArray.class); + + private final Object container; + + GeoArray(Object container) { + this.container = container; + } + + @Override + @SuppressWarnings("unchecked") + public T get(int index) { + if (container instanceof List) { + return (T) ((List) container).get(index); + } else if (container instanceof GeoPointCollection) { + return (T) ((GeoPointCollection) container).getPoints().get(index).getCoordinates(); + } else if (container instanceof GeoLineStringCollection) { + return (T) ((GeoLineStringCollection) container).getLines().get(index).getCoordinates(); + } else if (container instanceof GeoPolygon) { + return (T) ((GeoPolygon) container).getRings().get(index).getCoordinates(); + } else if (container instanceof GeoPolygonCollection) { + return (T) ((GeoPolygonCollection) container).getPolygons().get(index).getCoordinates(); + } else { + throw LOGGER.logThrowableAsError(new IllegalStateException()); + } + } + + @Override + public int size() { + if (container instanceof List) { + return ((List) container).size(); + } else if (container instanceof GeoPointCollection) { + return ((GeoPointCollection) container).getPoints().size(); + } else if (container instanceof GeoLineStringCollection) { + return ((GeoLineStringCollection) container).getLines().size(); + } else if (container instanceof GeoPolygon) { + return ((GeoPolygon) container).getRings().size(); + } else if (container instanceof GeoPolygonCollection) { + return ((GeoPolygonCollection) container).getPolygons().size(); + } else { + throw LOGGER.logThrowableAsError(new IllegalStateException()); + } + } + + /** + * Throws {@link UnsupportedOperationException} as GeoArray doesn't support mutation. + * + * @param o The object that would be removed. + * @return Throws an exception. + * @throws UnsupportedOperationException GeoArray doesn't support mutation. + */ + @Override + public boolean remove(Object o) { + throw LOGGER.logThrowableAsError(new UnsupportedOperationException(NO_MUTATION_MESSAGE)); + } + + /** + * Throws {@link UnsupportedOperationException} as GeoArray doesn't support mutation. + * + * @param c The collection of elements that would be removed. + * @return Throws an exception. + * @throws UnsupportedOperationException GeoArray doesn't support mutation. + */ + @Override + public boolean removeAll(Collection c) { + throw LOGGER.logThrowableAsError(new UnsupportedOperationException(NO_MUTATION_MESSAGE)); + } + + /** + * Throws {@link UnsupportedOperationException} as GeoArray doesn't support mutation. + * + * @param c The collection of elements that would be retained. + * @return Throws an exception. + * @throws UnsupportedOperationException GeoArray doesn't support mutation. + */ + @Override + public boolean retainAll(Collection c) { + throw LOGGER.logThrowableAsError(new UnsupportedOperationException(NO_MUTATION_MESSAGE)); + } + + /** + * Throws {@link UnsupportedOperationException} as GeoArray doesn't support mutation. + * + * @param operator The operator that determines which elements would be replaced. + * @throws UnsupportedOperationException GeoArray doesn't support mutation. + */ + @Override + public void replaceAll(UnaryOperator operator) { + throw LOGGER.logThrowableAsError(new UnsupportedOperationException(NO_MUTATION_MESSAGE)); + } + + /** + * Throws {@link UnsupportedOperationException} as GeoArray doesn't support mutation. + * + * @param c The comparator that determines sort order. + * @throws UnsupportedOperationException GeoArray doesn't support mutation. + */ + @Override + public void sort(Comparator c) { + throw LOGGER.logThrowableAsError(new UnsupportedOperationException(NO_MUTATION_MESSAGE)); + } + + /** + * Throws {@link UnsupportedOperationException} as GeoArray doesn't support mutation. + * + * @param filter The predicate that determines which elements would be removed. + * @return Throws an exception. + * @throws UnsupportedOperationException GeoArray doesn't support mutation. + */ + @Override + public boolean removeIf(Predicate filter) { + throw LOGGER.logThrowableAsError(new UnsupportedOperationException(NO_MUTATION_MESSAGE)); + } + + /** + * Throws {@link UnsupportedOperationException} as GeoArray doesn't support mutation. + * + * @param fromIndex The index where the sub list would begin. + * @param toIndex The index where the sub list would end. + * @return Throws an exception. + * @throws UnsupportedOperationException GeoArray doesn't support mutation. + */ + @Override + public List subList(int fromIndex, int toIndex) { + throw LOGGER.logThrowableAsError(new UnsupportedOperationException("GeoArray does not support sub lists.")); + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof GeoArray)) { + return false; + } + + if (this == o) { + return true; + } + + GeoArray other = (GeoArray) o; + return Objects.equals(container, other.container); + } + + @Override + public int hashCode() { + return Objects.hashCode(container); + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoBoundingBox.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoBoundingBox.java new file mode 100644 index 000000000000..691711a36e42 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoBoundingBox.java @@ -0,0 +1,270 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models.geo; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonSerializable; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.serialization.json.JsonWriter; + +import java.io.IOException; +import java.util.List; +import java.util.Objects; + +/** + * Represents a geometric bounding box. + * + *

        This class encapsulates a bounding box defined by west, south, east, and north coordinates, and optionally + * minimum and maximum altitude. It provides methods to access these properties.

        + * + *

        This class is useful when you want to work with a bounding box in a geographic context. For example, you can use + * it to define the area of interest for a map view, or to specify the spatial extent of a geographic dataset.

        + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public final class GeoBoundingBox implements JsonSerializable { + // GeoBoundingBox is a commonly used model, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(GeoBoundingBox.class); + + private final double west; + private final double south; + private final double east; + private final double north; + + private final Double minAltitude; + private final Double maxAltitude; + + /** + * Constructs a bounding box. + * + * @param west West longitudinal boundary. + * @param south South latitudinal boundary. + * @param east East longitudinal boundary. + * @param north North latitudinal boundary. + */ + public GeoBoundingBox(double west, double south, double east, double north) { + this(west, south, east, north, null, null, null); + } + + /** + * Constructs a bounding box. + * + * @param west West longitudinal boundary. + * @param south South latitudinal boundary. + * @param east East longitudinal boundary. + * @param north North latitudinal boundary. + * @param minAltitude Minimum altitude boundary. + * @param maxAltitude Maximum altitude boundary. + */ + public GeoBoundingBox(double west, double south, double east, double north, double minAltitude, + double maxAltitude) { + this(west, south, east, north, minAltitude, maxAltitude, null); + } + + /* + * This constructor allows the one above to require both min altitude and max altitude to be non-null. + */ + private GeoBoundingBox(double west, double south, double east, double north, Double minAltitude, Double maxAltitude, + String ignored) { + this.west = west; + this.south = south; + this.east = east; + this.north = north; + this.minAltitude = minAltitude; + this.maxAltitude = maxAltitude; + } + + /** + * The west longitudinal boundary of the bounding box. + * + * @return The west longitudinal boundary. + */ + public double getWest() { + return west; + } + + /** + * The south latitudinal boundary of the bounding box. + * + * @return The south latitudinal boundary. + */ + public double getSouth() { + return south; + } + + /** + * The east longitudinal boundary of the bounding box. + * + * @return The east longitudinal boundary. + */ + public double getEast() { + return east; + } + + /** + * The north latitudinal boundary of the bounding box. + * + * @return The north latitudinal boundary. + */ + public double getNorth() { + return north; + } + + /** + * The minimum altitude boundary of the bounding box. + * + * @return The minimum altitude boundary. + */ + public Double getMinAltitude() { + return minAltitude; + } + + /** + * The maximum altitude boundary of the bounding box. + * + * @return The maximum altitude boundary. + */ + public Double getMaxAltitude() { + return maxAltitude; + } + + @Override + public int hashCode() { + return Objects.hash(west, south, east, north, minAltitude, maxAltitude); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof GeoBoundingBox)) { + return false; + } + + if (this == obj) { + return true; + } + + GeoBoundingBox other = (GeoBoundingBox) obj; + return Double.compare(west, other.west) == 0 + && Double.compare(south, other.south) == 0 + && Double.compare(east, other.east) == 0 + && Double.compare(north, other.north) == 0 + && Objects.equals(minAltitude, other.minAltitude) + && Objects.equals(maxAltitude, other.maxAltitude); + } + + /** + * Accesses the coordinates of the {@link GeoBoundingBox} as if it were in a JSON representation. + * + * @param i Index to access. + * @return The double value of the index. + * @throws IndexOutOfBoundsException If the {@link GeoBoundingBox} doesn't have altitude coordinates and {@code i} + * is greater than {@code 3} or {@link GeoBoundingBox} has altitude coordinates and {@code i} is greater than + */ + double get(int i) { + if (minAltitude != null && maxAltitude != null) { + switch (i) { + case 0: + return west; + + case 1: + return south; + + case 2: + return minAltitude; + + case 3: + return east; + + case 4: + return north; + + case 5: + return maxAltitude; + + default: + throw LOGGER.logThrowableAsWarning(new IndexOutOfBoundsException("Index out of range: " + i)); + } + } else { + switch (i) { + case 0: + return west; + + case 1: + return south; + + case 2: + return east; + + case 3: + return north; + + default: + throw LOGGER.logThrowableAsWarning(new IndexOutOfBoundsException("Index out of range: " + i)); + } + } + } + + @Override + public String toString() { + return (minAltitude != null && maxAltitude != null) + ? String.format("[%s, %s, %s, %s, %s, %s]", west, south, minAltitude, east, north, maxAltitude) + : String.format("[%s, %s, %s, %s]", west, south, east, north); + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartArray().writeDouble(west).writeDouble(south); + + if (minAltitude != null) { + jsonWriter.writeDouble(minAltitude); + } + + jsonWriter.writeDouble(east).writeDouble(north); + + if (maxAltitude != null) { + jsonWriter.writeDouble(maxAltitude); + } + + return jsonWriter.writeEndArray(); + } + + /** + * Reads a JSON stream into a {@link GeoBoundingBox}. + * + * @param jsonReader The {@link JsonReader} being read. + * @return The {@link GeoBoundingBox} that the JSON stream represented, or null if it pointed to JSON null. + * @throws IllegalStateException If the {@link GeoBoundingBox} doesn't have four or six positions in the array. + * @throws IOException If a {@link GeoBoundingBox} fails to be read from the {@code jsonReader}. + */ + public static GeoBoundingBox fromJson(JsonReader jsonReader) throws IOException { + List coordinates = jsonReader.readArray(reader -> { + if (reader.currentToken() == JsonToken.NUMBER) { + return reader.getDouble(); + } else { + return null; + } + }); + + if (coordinates == null) { + return null; + } + + int coordinateCount = coordinates.size(); + if (coordinateCount != 4 && coordinateCount != 6) { + throw LOGGER + .logThrowableAsError(new IllegalStateException("Only 2 or 3 dimension bounding boxes are supported.")); + } + + double west = coordinates.get(0).doubleValue(); + double south = coordinates.get(1).doubleValue(); + double east = coordinates.get((coordinateCount == 6) ? 3 : 2).doubleValue(); + double north = coordinates.get((coordinateCount == 6) ? 4 : 3).doubleValue(); + Double minAltitude = (coordinateCount == 6) ? coordinates.get(2).doubleValue() : null; + Double maxAltitude = (coordinateCount == 6) ? coordinates.get(5).doubleValue() : null; + + return new GeoBoundingBox(west, south, east, north, minAltitude, maxAltitude, null); + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoCollection.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoCollection.java new file mode 100644 index 000000000000..29dbba485c5b --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoCollection.java @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models.geo; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.serialization.json.JsonWriter; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + *

        Represents a heterogeneous collection of {@link GeoObject GeoObjects}.

        + * + *

        This class encapsulates a list of geometry objects and provides methods to access these objects. + * The objects can be of any type that extends {@link GeoObject}.

        + * + *

        This class is useful when you want to work with a collection of geometry objects in a read-only manner. For + * example, you can use it to represent a complex geographic feature that is composed of multiple simple geographic + * features.

        + * + * @see GeoObject + * @see GeoBoundingBox + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public final class GeoCollection extends GeoObject { + private final List geometries; + + /** + * Constructs a {@link GeoCollection}. + * + * @param geometries The geometries in the collection. + * @throws NullPointerException If {@code geometries} is {@code null}. + */ + public GeoCollection(List geometries) { + this(geometries, null, null); + } + + /** + * Constructs a {@link GeoCollection}. + * + * @param geometries The geometries in the collection. + * @param boundingBox Bounding box for the {@link GeoCollection}. + * @param customProperties Additional properties of the {@link GeoCollection}. + * @throws NullPointerException If {@code geometries} is {@code null}. + */ + public GeoCollection(List geometries, GeoBoundingBox boundingBox, Map customProperties) { + super(boundingBox, customProperties); + Objects.requireNonNull(geometries, "'geometries' cannot be null."); + this.geometries = Collections.unmodifiableList(new ArrayList<>(geometries)); + } + + /** + * Unmodifiable representation of the {@link GeoObject geometries} contained in this collection. + * + * @return An unmodifiable representation of the {@link GeoObject geometries} in this collection. + */ + public List getGeometries() { + return geometries; + } + + @Override + public GeoObjectType getType() { + return GeoObjectType.GEOMETRY_COLLECTION; + } + + @Override + public int hashCode() { + return Objects.hash(geometries, super.hashCode()); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof GeoCollection)) { + return false; + } + + if (this == obj) { + return true; + } + + GeoCollection other = (GeoCollection) obj; + return super.equals(other) && Objects.equals(geometries, other.geometries); + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject() + .writeStringField("type", GeoObjectType.GEOMETRY_COLLECTION.toString()) + .writeArrayField("geometries", geometries, JsonWriter::writeJson) + .writeJsonField("bbox", getBoundingBox()); + + return writeCustomProperties(jsonWriter).writeEndObject(); + } + + /** + * Reads a JSON stream into a {@link GeoCollection}. + * + * @param jsonReader The {@link JsonReader} being read. + * @return The {@link GeoCollection} that the JSON stream represented, or null if it pointed to JSON null. + * @throws IllegalStateException If the {@code type} node exists and isn't equal to {@code GeometryCollection}. + * @throws IOException If a {@link GeoCollection} fails to be read from the {@code jsonReader}. + */ + public static GeoCollection fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + List geometries = null; + boolean geometriesFound = false; + GeoBoundingBox boundingBox = null; + Map customProperties = null; + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("type".equals(fieldName)) { + String type = reader.getString(); + if (!GeoObjectType.GEOMETRY_COLLECTION.toString().equals(type)) { + throw new IllegalStateException("'type' was expected to be non-null and equal to " + + "'GeometryCollection'. The found 'type' was '" + type + "'."); + } + } else if ("geometries".equals(fieldName)) { + geometriesFound = true; + geometries = reader.readArray(GeoObject::fromJson); + } else if ("bbox".equals(fieldName)) { + boundingBox = GeoBoundingBox.fromJson(reader); + } else { + if (customProperties == null) { + customProperties = new LinkedHashMap<>(); + } + + customProperties.put(fieldName, reader.readUntyped()); + } + } + + if (!geometriesFound) { + throw new IllegalStateException("Required property 'geometries' wasn't found."); + } + + return new GeoCollection(geometries, boundingBox, customProperties); + }); + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoLineString.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoLineString.java new file mode 100644 index 000000000000..6389137fdff6 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoLineString.java @@ -0,0 +1,146 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models.geo; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.serialization.json.JsonWriter; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + *

        Represents a geometric line string.

        + * + *

        This class encapsulates a list of {@link GeoPosition} instances that form a line string. A line string is a + * curve with linear interpolation between points.

        + * + *

        This class is useful when you want to work with a line string in a geographic context. For example, you can use + * it to represent a route on a map or the shape of a geographic feature.

        + * + *

        Note: A line string requires at least 2 coordinates.

        + * + * @see GeoPosition + * @see GeoObject + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public final class GeoLineString extends GeoObject { + private final GeoArray coordinates; + + /** + * Constructs a geometric line. + * + * @param positions Geometric positions that define the line. + * @throws NullPointerException If {@code positions} is {@code null}. + */ + public GeoLineString(List positions) { + this(positions, null, null); + } + + /** + * Constructs a geometric line. + * + * @param positions Geometric positions that define the line. + * @param boundingBox Bounding box for the line. + * @param customProperties Additional properties of the geometric line. + * @throws NullPointerException If {@code positions} is {@code null}. + */ + public GeoLineString(List positions, GeoBoundingBox boundingBox, + Map customProperties) { + super(boundingBox, customProperties); + + Objects.requireNonNull(positions, "'positions' cannot be null."); + this.coordinates = new GeoArray<>(new ArrayList<>(positions)); + } + + /** + * Unmodifiable representation of the {@link GeoPosition geometric positions} representing this line. + * + * @return An unmodifiable representation of the {@link GeoPosition geometric positions} representing this line. + */ + public List getCoordinates() { + return coordinates; + } + + @Override + public GeoObjectType getType() { + return GeoObjectType.LINE_STRING; + } + + @Override + public int hashCode() { + return Objects.hash(coordinates, super.hashCode()); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof GeoLineString)) { + return false; + } + + if (this == obj) { + return true; + } + + GeoLineString other = (GeoLineString) obj; + return super.equals(other) && Objects.equals(coordinates, other.coordinates); + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject() + .writeStringField("type", GeoObjectType.LINE_STRING.toString()) + .writeArrayField("coordinates", getCoordinates(), JsonWriter::writeJson) + .writeJsonField("bbox", getBoundingBox()); + + return writeCustomProperties(jsonWriter).writeEndObject(); + } + + /** + * Reads a JSON stream into a {@link GeoLineString}. + * + * @param jsonReader The {@link JsonReader} being read. + * @return The {@link GeoLineString} that the JSON stream represented, or null if it pointed to JSON null. + * @throws IllegalStateException If the {@code type} node exists and isn't equal to {@code LineString}. + * @throws IOException If a {@link GeoLineString} fails to be read from the {@code jsonReader}. + */ + public static GeoLineString fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + List coordinates = null; + GeoBoundingBox boundingBox = null; + Map customProperties = null; + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("type".equals(fieldName)) { + String type = reader.getString(); + if (!GeoObjectType.LINE_STRING.toString().equals(type)) { + throw new IllegalStateException("'type' was expected to be non-null and equal to 'LineString'. " + + "The found 'type' was '" + type + "'."); + } + } else if ("coordinates".equals(fieldName)) { + coordinates = reader.readArray(GeoPosition::fromJson); + } else if ("bbox".equals(fieldName)) { + boundingBox = GeoBoundingBox.fromJson(reader); + } else { + if (customProperties == null) { + customProperties = new LinkedHashMap<>(); + } + + customProperties.put(fieldName, reader.readUntyped()); + } + } + + return new GeoLineString(coordinates, boundingBox, customProperties); + }); + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoLineStringCollection.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoLineStringCollection.java new file mode 100644 index 000000000000..0578d4a13302 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoLineStringCollection.java @@ -0,0 +1,165 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models.geo; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.serialization.json.JsonWriter; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + *

        Represents a collection of {@link GeoLineString GeoLineStrings}.

        + * + *

        This class encapsulates a list of {@link GeoLineString} instances that form a collection of lines. Each line + * string is a curve with linear interpolation between points.

        + * + *

        This class is useful when you want to work with a collection of line strings in a geographic context. + * For example, you can use it to represent a complex route on a map that is composed of multiple line strings.

        + * + *

        Note: A line string collection requires at least 2 coordinates for each line string.

        + * + * @see GeoLineString + * @see GeoObject + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public final class GeoLineStringCollection extends GeoObject { + private final List lines; + + /** + * Constructs a {@link GeoLineStringCollection}. + * + * @param lines The geometric lines that define the multi-line. + * @throws NullPointerException If {@code lines} is {@code null}. + */ + public GeoLineStringCollection(List lines) { + this(lines, null, null); + } + + /** + * Constructs a {@link GeoLineStringCollection}. + * + * @param lines The geometric lines that define the multi-line. + * @param boundingBox Bounding box for the multi-line. + * @param customProperties Additional properties of the multi-line. + * @throws NullPointerException If {@code lines} is {@code null}. + */ + public GeoLineStringCollection(List lines, GeoBoundingBox boundingBox, + Map customProperties) { + super(boundingBox, customProperties); + + Objects.requireNonNull(lines, "'lines' cannot be null."); + + this.lines = Collections.unmodifiableList(new ArrayList<>(lines)); + } + + /** + * Unmodifiable representation of the {@link GeoLineString geometric lines} representing this multi-line. + * + * @return An unmodifiable representation of the {@link GeoLineString geometric lines} representing this multi-line. + */ + public List getLines() { + return lines; + } + + /** + * Unmodifiable representation of the {@link GeoPosition geometric positions} representing this multi-line. + * + * @return An unmodifiable representation of the {@link GeoPosition geometric positions} representing this + * multi-line. + */ + GeoArray> getCoordinates() { + return new GeoArray<>(this); + } + + @Override + public GeoObjectType getType() { + return GeoObjectType.MULTI_LINE_STRING; + } + + @Override + public int hashCode() { + return Objects.hash(lines, super.hashCode()); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof GeoLineStringCollection)) { + return false; + } + + if (this == obj) { + return true; + } + + GeoLineStringCollection other = (GeoLineStringCollection) obj; + + return super.equals(obj) && Objects.equals(lines, other.lines); + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject() + .writeStringField("type", GeoObjectType.MULTI_LINE_STRING.toString()) + .writeArrayField("coordinates", lines, + (writer, geoLineString) -> writer.writeArray(geoLineString.getCoordinates(), JsonWriter::writeJson)) + .writeJsonField("bbox", getBoundingBox()); + + return writeCustomProperties(jsonWriter).writeEndObject(); + } + + /** + * Reads a JSON stream into a {@link GeoLineStringCollection}. + * + * @param jsonReader The {@link JsonReader} being read. + * @return The {@link GeoLineStringCollection} that the JSON stream represented, or null if it pointed to JSON null. + * @throws IllegalStateException If the {@code type} node exists and isn't equal to {@code MultiLineString}. + * @throws IOException If a {@link GeoLineStringCollection} fails to be read from the {@code jsonReader}. + */ + public static GeoLineStringCollection fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + List lines = null; + GeoBoundingBox boundingBox = null; + Map customProperties = null; + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("type".equals(fieldName)) { + String type = reader.getString(); + if (!GeoObjectType.MULTI_LINE_STRING.toString().equals(type)) { + throw new IllegalStateException("'type' was expected to be non-null and equal to " + + "'MultiLineString'. The found 'type' was '" + type + "'."); + } + } else if ("coordinates".equals(fieldName)) { + List> positionList + = reader.readArray(reader2 -> reader2.readArray(GeoPosition::fromJson)); + lines = new ArrayList<>(positionList.size()); + for (List positions : positionList) { + lines.add(new GeoLineString(positions)); + } + } else if ("bbox".equals(fieldName)) { + boundingBox = GeoBoundingBox.fromJson(reader); + } else { + if (customProperties == null) { + customProperties = new LinkedHashMap<>(); + } + + customProperties.put(fieldName, reader.readUntyped()); + } + } + + return new GeoLineStringCollection(lines, boundingBox, customProperties); + }); + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoLinearRing.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoLinearRing.java new file mode 100644 index 000000000000..f3f950a29ee0 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoLinearRing.java @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models.geo; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonSerializable; +import io.clientcore.core.serialization.json.JsonWriter; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + *

        Represents a linear ring that is part of a {@link GeoPolygon}.

        + * + *

        This class encapsulates a list of {@link GeoPosition} instances that form a closed loop, which is a component + * of a {@link GeoPolygon}. The first and last positions of the loop are the same, forming a closed ring.

        + * + *

        This class is useful when you want to work with a linear ring in a geographic context. For example, you can + * use it to define the boundary of a geographic area in a {@link GeoPolygon}.

        + * + *

        Note: A linear ring requires at least 4 coordinates, and the first and last coordinates must be the same.

        + * + * @see GeoPosition + * @see GeoPolygon + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public final class GeoLinearRing implements JsonSerializable { + // GeoLinearRing is a commonly used model class, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(GeoLinearRing.class); + + private final GeoArray coordinates; + + /** + * Constructs a new linear ring with the passed coordinates. + * + * @param coordinates The coordinates of the linear ring. + * @throws NullPointerException If {@code coordinates} is null. + * @throws IllegalArgumentException If {@code coordinates} has less than 4 elements or the first and last elements + * aren't equivalent. + */ + public GeoLinearRing(List coordinates) { + Objects.requireNonNull(coordinates, "'coordinates' cannot be null."); + + int size = coordinates.size(); + if (size < 4) { + throw LOGGER + .logThrowableAsError(new IllegalArgumentException("A linear ring requires at least 4 coordinates.")); + } + + if (!Objects.equals(coordinates.get(0), coordinates.get(size - 1))) { + throw LOGGER.logThrowableAsError( + new IllegalArgumentException("The first and last coordinates of a linear ring must be equivalent.")); + } + + this.coordinates = new GeoArray<>(new ArrayList<>(coordinates)); + } + + /** + * Unmodifiable representation of the {@link GeoPosition geometric positions} representing this linear ring. + * + * @return An unmodifiable representation of the {@link GeoPosition geometric positions} representing this linear + * ring. + */ + public List getCoordinates() { + return coordinates; + } + + @Override + public int hashCode() { + return coordinates.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof GeoLinearRing)) { + return false; + } + + if (this == obj) { + return true; + } + + GeoLinearRing other = (GeoLinearRing) obj; + return Objects.equals(coordinates, other.coordinates); + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeArray(getCoordinates(), JsonWriter::writeJson); + } + + /** + * Reads a JSON stream into a {@link GeoLinearRing}. + * + * @param jsonReader The {@link JsonReader} being read. + * @return The {@link GeoLinearRing} that the JSON stream represented, or null if it pointed to JSON null. + * @throws IOException If a {@link GeoLinearRing} fails to be read from the {@code jsonReader}. + */ + public static GeoLinearRing fromJson(JsonReader jsonReader) throws IOException { + List coordinates = jsonReader.readArray(GeoPosition::fromJson); + if (coordinates == null) { + return null; + } + + return new GeoLinearRing(coordinates); + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoObject.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoObject.java new file mode 100644 index 000000000000..827f35114c7e --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoObject.java @@ -0,0 +1,178 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models.geo; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonSerializable; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.serialization.json.JsonWriter; +import io.clientcore.core.utils.CoreUtils; + +import java.io.IOException; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +/** + * Represents an abstract geometric object in GeoJSON format. + * + *

        This class encapsulates the common properties of a geometric object, including the bounding box and additional + * custom properties. It provides methods to access these properties.

        + * + * @see GeoBoundingBox + * @see GeoPosition + * @see GeoPoint + * @see GeoLineString + * @see GeoPolygon + * @see GeoPointCollection + * @see GeoLineStringCollection + * @see GeoPolygonCollection + * @see GeoCollection + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public abstract class GeoObject implements JsonSerializable { + private final GeoBoundingBox boundingBox; + private final Map customProperties; + + /** + * Creates a {@link GeoObject} instance. + * + * @param boundingBox Optional bounding box of the {@link GeoObject}. + * @param customProperties Optional additional properties to associate to the {@link GeoObject}. + */ + protected GeoObject(GeoBoundingBox boundingBox, Map customProperties) { + this.boundingBox = boundingBox; + + if (customProperties == null) { + this.customProperties = null; + } else { + this.customProperties = Collections.unmodifiableMap(new HashMap<>(customProperties)); + } + } + + /** + * Gets the GeoJSON type for this object. + * + * @return The GeoJSON type for this object. + */ + public abstract GeoObjectType getType(); + + /** + * Bounding box for this {@link GeoObject}. + * + * @return The bounding box for this {@link GeoObject}. + */ + public final GeoBoundingBox getBoundingBox() { + return boundingBox; + } + + /** + * Additional properties about this {@link GeoObject}. + * + * @return An unmodifiable representation of the additional properties associated with this {@link GeoObject}. + */ + public final Map getCustomProperties() { + return customProperties; + } + + @Override + public int hashCode() { + return Objects.hash(boundingBox, customProperties); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof GeoObject)) { + return false; + } + + if (this == obj) { + return true; + } + + GeoObject other = (GeoObject) obj; + + return Objects.equals(boundingBox, other.boundingBox) + && Objects.equals(customProperties, other.customProperties); + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject().writeJsonField("bbox", getBoundingBox()); + + Map customProperties = getCustomProperties(); + if (!CoreUtils.isNullOrEmpty(customProperties)) { + jsonWriter.writeMap(customProperties, JsonWriter::writeUntyped); + } + + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of {@link GeoObject} from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of {@link GeoObject} 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 {@link GeoObject}. + */ + public static GeoObject 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 ("type".equals(fieldName)) { + discriminatorValue = readerToUse.getString(); + break; + } else { + readerToUse.skipChildren(); + } + } + + if (discriminatorValue != null) { + readerToUse = readerToUse.reset(); + } + + // Use the discriminator value to determine which subtype should be deserialized. + if ("Point".equals(discriminatorValue)) { + return GeoPoint.fromJson(readerToUse); + } else if ("MultiPoint".equals(discriminatorValue)) { + return GeoPointCollection.fromJson(readerToUse); + } else if ("Polygon".equals(discriminatorValue)) { + return GeoPolygon.fromJson(readerToUse); + } else if ("MultiPolygon".equals(discriminatorValue)) { + return GeoPolygonCollection.fromJson(readerToUse); + } else if ("LineString".equals(discriminatorValue)) { + return GeoLineString.fromJson(readerToUse); + } else if ("MultiLineString".equals(discriminatorValue)) { + return GeoLineStringCollection.fromJson(readerToUse); + } else if ("GeometryCollection".equals(discriminatorValue)) { + return GeoCollection.fromJson(readerToUse); + } else { + throw new IllegalStateException("Discriminator field 'type' didn't match one of the expected values " + + "'Point', 'MultiPoint', 'Polygon', 'MultiPolygon', 'LineString', 'MultiLineString', or " + + "'GeometryCollection'. It was: '" + discriminatorValue + "'."); + } + }); + } + + JsonWriter writeCustomProperties(JsonWriter jsonWriter) throws IOException { + if (!CoreUtils.isNullOrEmpty(customProperties)) { + for (Map.Entry entry : customProperties.entrySet()) { + jsonWriter.writeUntypedField(String.valueOf(entry.getKey()), entry.getValue()); + } + } + + return jsonWriter; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoObjectType.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoObjectType.java new file mode 100644 index 000000000000..e9ff37f15f8c --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoObjectType.java @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models.geo; + +import io.clientcore.core.utils.ExpandableEnum; + +import java.util.Objects; + +/** + *

        Represents the type of GeoJSON object.

        + * + *

        This class encapsulates the type of GeoJSON object. It provides constants for the different types of + * GeoJSON objects, such as {@link #POINT}, {@link #MULTI_POINT}, {@link #POLYGON}, {@link #MULTI_POLYGON}, + * {@link #LINE_STRING}, {@link #MULTI_LINE_STRING}, and {@link #GEOMETRY_COLLECTION}.

        + * + *

        This class is useful when you want to work with GeoJSON objects and need to specify or check the type of + * GeoJSON object.

        + * + * @see ExpandableEnum + */ +public final class GeoObjectType implements ExpandableEnum { + private final String value; + + private GeoObjectType(String value) { + this.value = value; + } + + /** + * GeoJSON point. + */ + public static final GeoObjectType POINT = new GeoObjectType("Point"); + + /** + * GeoJSON multi-point. + */ + public static final GeoObjectType MULTI_POINT = new GeoObjectType("MultiPoint"); + + /** + * GeoJSON polygon. + */ + public static final GeoObjectType POLYGON = new GeoObjectType("Polygon"); + + /** + * GeoJSON multi-polygon. + */ + public static final GeoObjectType MULTI_POLYGON = new GeoObjectType("MultiPolygon"); + + /** + * GeoJSON line string. + */ + public static final GeoObjectType LINE_STRING = new GeoObjectType("LineString"); + + /** + * GeoJSON multi-line string. + */ + public static final GeoObjectType MULTI_LINE_STRING = new GeoObjectType("MultiLineString"); + + /** + * GeoJSON geometry collection. + */ + public static final GeoObjectType GEOMETRY_COLLECTION = new GeoObjectType("GeometryCollection"); + + @Override + public String getValue() { + return value; + } + + @Override + public String toString() { + return value; + } + + @Override + public int hashCode() { + return Objects.hash(value); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof GeoObjectType)) { + return false; + } + + if (this == obj) { + return true; + } + + GeoObjectType other = (GeoObjectType) obj; + return Objects.equals(value, other.value); + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoPoint.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoPoint.java new file mode 100644 index 000000000000..9838833d8319 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoPoint.java @@ -0,0 +1,164 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models.geo; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.serialization.json.JsonWriter; + +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; + +/** + *

        Represents a geometric point in GeoJSON format.

        + * + *

        This class encapsulates a point defined by a {@link GeoPosition} which includes the longitude, latitude, and + * optionally the altitude of the point.

        + * + * @see GeoPosition + * @see GeoObject + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public final class GeoPoint extends GeoObject { + private final GeoPosition coordinates; + + /** + * Constructs a {@link GeoPoint}. + * + * @param longitude The longitudinal position of the point. + * @param latitude The latitudinal position of the point. + */ + public GeoPoint(double longitude, double latitude) { + this(longitude, latitude, null); + } + + /** + * Constructs a {@link GeoPoint}. + * + * @param longitude The longitudinal position of the point. + * @param latitude The latitudinal position of the point. + * @param altitude The altitude of the point. + */ + public GeoPoint(double longitude, double latitude, Double altitude) { + this(new GeoPosition(longitude, latitude, altitude)); + } + + /** + * Constructs a geometric point. + * + * @param position The {@link GeoPosition geometric position} of the point. + * @throws NullPointerException If {@code position} is {@code null}. + */ + public GeoPoint(GeoPosition position) { + this(position, null, null); + } + + /** + * Constructs a geometric point. + * + * @param position The {@link GeoPosition geometric position} of the point. + * @param boundingBox Bounding box for the point. + * @param customProperties Additional properties of the geometric point. + * @throws NullPointerException If {@code position} is {@code null}. + */ + public GeoPoint(GeoPosition position, GeoBoundingBox boundingBox, Map customProperties) { + super(boundingBox, customProperties); + this.coordinates = Objects.requireNonNull(position, "'position' cannot be null."); + } + + /** + * The {@link GeoPosition geometric position} of the point. + * + * @return The {@link GeoPosition geometric position} of the point. + */ + public GeoPosition getCoordinates() { + return coordinates; + } + + @Override + public GeoObjectType getType() { + return GeoObjectType.POINT; + } + + @Override + public int hashCode() { + return Objects.hash(coordinates, super.hashCode()); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof GeoPoint)) { + return false; + } + + if (this == obj) { + return true; + } + + GeoPoint other = (GeoPoint) obj; + + return super.equals(obj) && Objects.equals(coordinates, other.coordinates); + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject() + .writeStringField("type", GeoObjectType.POINT.toString()) + .writeJsonField("coordinates", coordinates) + .writeJsonField("bbox", getBoundingBox()); + + return writeCustomProperties(jsonWriter).writeEndObject(); + } + + /** + * Reads a JSON stream into a {@link GeoPoint}. + * + * @param jsonReader The {@link JsonReader} being read. + * @return The {@link GeoPoint} that the JSON stream represented, or null if it pointed to JSON null. + * @throws IllegalStateException If the {@code type} node exists and isn't equal to {@code Point}. + * @throws IOException If a {@link GeoPoint} fails to be read from the {@code jsonReader}. + */ + public static GeoPoint fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + GeoPosition position = null; + boolean positionFound = false; + GeoBoundingBox boundingBox = null; + Map customProperties = null; + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("type".equals(fieldName)) { + String type = reader.getString(); + if (!GeoObjectType.POINT.toString().equals(type)) { + throw new IllegalStateException("'type' was expected to be non-null and equal to 'Point'. The " + + "found 'type' was '" + type + "'."); + } + } else if ("coordinates".equals(fieldName)) { + positionFound = true; + position = GeoPosition.fromJson(reader); + } else if ("bbox".equals(fieldName)) { + boundingBox = GeoBoundingBox.fromJson(reader); + } else { + if (customProperties == null) { + customProperties = new LinkedHashMap<>(); + } + + customProperties.put(fieldName, reader.readUntyped()); + } + } + + if (!positionFound) { + throw new IllegalStateException("Required property 'coordinates' wasn't found."); + } + + return new GeoPoint(position, boundingBox, customProperties); + }); + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoPointCollection.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoPointCollection.java new file mode 100644 index 000000000000..82527d70c978 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoPointCollection.java @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models.geo; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.serialization.json.JsonWriter; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + *

        Represents a collection of {@link GeoPoint GeoPoints} in GeoJSON format.

        + * + *

        This class encapsulates a list of {@link GeoPoint} instances that form a collection of points. Each point is + * defined by a {@link GeoPosition} which includes the longitude, latitude, and optionally the altitude.

        + * + *

        Note:A point collection requires at least 2 coordinates for each point.

        + * + * @see GeoPoint + * @see GeoPosition + * @see GeoObject + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public final class GeoPointCollection extends GeoObject { + private final List points; + + /** + * Constructs a {@link GeoPointCollection}. + * + * @param points The points that define the multi-point. + * @throws NullPointerException If {@code points} is {@code null}. + */ + public GeoPointCollection(List points) { + this(points, null, null); + } + + /** + * Constructs a {@link GeoPointCollection}. + * + * @param points The points that define the multi-point. + * @param boundingBox Bounding box for the multi-point. + * @param customProperties Additional properties of the multi-point. + * @throws NullPointerException If {@code points} is {@code null}. + */ + public GeoPointCollection(List points, GeoBoundingBox boundingBox, Map customProperties) { + super(boundingBox, customProperties); + + Objects.requireNonNull(points, "'points' cannot be null."); + this.points = Collections.unmodifiableList(new ArrayList<>(points)); + } + + /** + * Unmodifiable representation of the {@link GeoPoint geometric points} representing this multi-point. + * + * @return An unmodifiable representation of the {@link GeoPoint geometric points} representing this multi-point. + */ + public List getPoints() { + return points; + } + + /** + * Unmodifiable representation of the {@link GeoPosition geometric positions} representing this multi-point. + * + * @return An unmodifiable representation of the {@link GeoPosition geometric positions} representing this + * multi-point. + */ + GeoArray getCoordinates() { + return new GeoArray<>(this); + } + + @Override + public GeoObjectType getType() { + return GeoObjectType.MULTI_POINT; + } + + @Override + public int hashCode() { + return Objects.hash(points, super.hashCode()); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof GeoPointCollection)) { + return false; + } + + if (this == obj) { + return true; + } + + GeoPointCollection other = (GeoPointCollection) obj; + + return super.equals(obj) && Objects.equals(points, other.points); + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject() + .writeStringField("type", GeoObjectType.MULTI_POINT.toString()) + .writeArrayField("coordinates", points, (writer, geoPoint) -> geoPoint.getCoordinates().toJson(writer)) + .writeJsonField("bbox", getBoundingBox()); + + return writeCustomProperties(jsonWriter).writeEndObject(); + } + + /** + * Reads a JSON stream into a {@link GeoPointCollection}. + * + * @param jsonReader The {@link JsonReader} being read. + * @return The {@link GeoPointCollection} that the JSON stream represented, or null if it pointed to JSON null. + * @throws IllegalStateException If the {@code type} node exists and isn't equal to {@code MultiPoint}. + * @throws IOException If a {@link GeoPointCollection} fails to be read from the {@code jsonReader}. + */ + public static GeoPointCollection fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + List points = null; + GeoBoundingBox boundingBox = null; + Map customProperties = null; + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("type".equals(fieldName)) { + String type = reader.getString(); + if (!GeoObjectType.MULTI_POINT.toString().equals(type)) { + throw new IllegalStateException("'type' was expected to be non-null and equal to 'MultiPoint'. " + + "The found 'type' was '" + type + "'."); + } + } else if ("coordinates".equals(fieldName)) { + List positions = reader.readArray(GeoPosition::fromJson); + points = new ArrayList<>(positions.size()); + for (GeoPosition position : positions) { + points.add(new GeoPoint(position)); + } + } else if ("bbox".equals(fieldName)) { + boundingBox = GeoBoundingBox.fromJson(reader); + } else { + if (customProperties == null) { + customProperties = new LinkedHashMap<>(); + } + + customProperties.put(fieldName, reader.readUntyped()); + } + } + + return new GeoPointCollection(points, boundingBox, customProperties); + }); + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoPolygon.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoPolygon.java new file mode 100644 index 000000000000..26be12360fec --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoPolygon.java @@ -0,0 +1,190 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models.geo; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.serialization.json.JsonWriter; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + *

        Represents a geometric polygon in GeoJSON format.

        + * + *

        This class encapsulates a polygon defined by a list of {@link GeoLinearRing} instances. Each ring represents a + * closed loop of coordinates forming the boundary of the polygon.

        + * + *

        This class is useful when you want to work with a polygon in a geographic context. For example, you can use it + * to represent a geographic area on a map.

        + * + *

        Note: A polygon requires at least one ring, and each ring requires at least 4 coordinates + * (with the first and last coordinates being the same to form a closed loop).

        + * + * @see GeoLinearRing + * @see GeoPosition + * @see GeoObject + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public final class GeoPolygon extends GeoObject { + private final List rings; + + /** + * Constructs a geometric polygon. + * + * @param ring The {@link GeoLinearRing ring} that defines the polygon. + * @throws NullPointerException If {@code ring} is {@code null}. + */ + public GeoPolygon(GeoLinearRing ring) { + this(ring, null, null); + } + + /** + * Constructs a geometric polygon. + * + * @param ring The {@link GeoLinearRing ring} that defines the polygon. + * @param boundingBox Bounding box for the polygon. + * @param customProperties Additional properties of the polygon. + * @throws NullPointerException If {@code ring} is {@code null}. + */ + public GeoPolygon(GeoLinearRing ring, GeoBoundingBox boundingBox, Map customProperties) { + this(Collections.singletonList(Objects.requireNonNull(ring, "'ring' cannot be null.")), boundingBox, + customProperties); + } + + /** + * Constructs a geometric polygon. + * + * @param rings The {@link GeoLinearRing rings} that define the polygon. + * @throws NullPointerException If {@code rings} is {@code null}. + */ + public GeoPolygon(List rings) { + this(rings, null, null); + } + + /** + * Constructs a geometric polygon. + * + * @param rings The {@link GeoLinearRing rings} that define the polygon. + * @param boundingBox Bounding box for the polygon. + * @param customProperties Additional properties of the polygon. + * @throws NullPointerException If {@code rings} is {@code null}. + */ + public GeoPolygon(List rings, GeoBoundingBox boundingBox, Map customProperties) { + super(boundingBox, customProperties); + + Objects.requireNonNull(rings, "'rings' cannot be null."); + this.rings = Collections.unmodifiableList(new ArrayList<>(rings)); + } + + /** + * Unmodifiable representation of the {@link GeoLinearRing geometric rings} representing this polygon. + * + * @return An unmodifiable representation of the {@link GeoLinearRing geometric rings} representing this polygon. + */ + public List getRings() { + return rings; + } + + /** + * Gets the outer ring of the polygon. + * + * @return Outer ring of the polygon. + */ + public GeoLinearRing getOuterRing() { + return rings.get(0); + } + + /** + * Unmodifiable representation of the {@link GeoPosition geometric positions} representing this polygon. + * + * @return Unmodifiable representation of the {@link GeoPosition geometric positions} representing this polygon. + */ + GeoArray> getCoordinates() { + return new GeoArray<>(this); + } + + @Override + public GeoObjectType getType() { + return GeoObjectType.POLYGON; + } + + @Override + public int hashCode() { + return Objects.hash(rings, super.hashCode()); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof GeoPolygon)) { + return false; + } + + if (this == obj) { + return true; + } + + GeoPolygon other = (GeoPolygon) obj; + + return super.equals(obj) && Objects.equals(rings, other.rings); + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject() + .writeStringField("type", GeoObjectType.POLYGON.toString()) + .writeArrayField("coordinates", getRings(), JsonWriter::writeJson) + .writeJsonField("bbox", getBoundingBox()); + + return writeCustomProperties(jsonWriter).writeEndObject(); + } + + /** + * Reads a JSON stream into a {@link GeoPolygon}. + * + * @param jsonReader The {@link JsonReader} being read. + * @return The {@link GeoPolygon} that the JSON stream represented, or null if it pointed to JSON null. + * @throws IllegalStateException If the {@code type} node exists and isn't equal to {@code Polygon}. + * @throws IOException If a {@link GeoPolygon} fails to be read from the {@code jsonReader}. + */ + public static GeoPolygon fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + List rings = null; + GeoBoundingBox boundingBox = null; + Map customProperties = null; + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("type".equals(fieldName)) { + String type = reader.getString(); + if (!GeoObjectType.POLYGON.toString().equals(type)) { + throw new IllegalStateException("'type' was expected to be non-null and equal to 'Polygon'. " + + "The found 'type' was '" + type + "'."); + } + } else if ("coordinates".equals(fieldName)) { + rings = reader.readArray(GeoLinearRing::fromJson); + } else if ("bbox".equals(fieldName)) { + boundingBox = GeoBoundingBox.fromJson(reader); + } else { + if (customProperties == null) { + customProperties = new LinkedHashMap<>(); + } + + customProperties.put(fieldName, reader.readUntyped()); + } + } + + return new GeoPolygon(rings, boundingBox, customProperties); + }); + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoPolygonCollection.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoPolygonCollection.java new file mode 100644 index 000000000000..cb0887e2480f --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoPolygonCollection.java @@ -0,0 +1,168 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models.geo; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.serialization.json.JsonWriter; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + *

        Represents a collection of {@link GeoPolygon GeoPolygons} in GeoJSON format.

        + * + *

        This class encapsulates a list of {@link GeoPolygon} instances that form a collection of polygons. Each polygon + * is defined by a list of {@link GeoLinearRing} instances that form the boundary of the polygon.

        + * + *

        This class is useful when you want to work with a collection of polygons in a geographic context. For example, + * you can use it to represent a complex geographic area on a map that is composed of multiple polygons.

        + * + *

        Note: A polygon collection requires at least one ring for each polygon, and each ring requires at least + * 4 coordinates (with the first and last coordinates being the same to form a closed loop).

        + * + * @see GeoPolygon + * @see GeoLinearRing + * @see GeoPosition + * @see GeoObject + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public final class GeoPolygonCollection extends GeoObject { + private final List polygons; + + /** + * Constructs a {@link GeoPolygonCollection}. + * + * @param polygons The polygons that define the multi-polygon. + * @throws NullPointerException If {@code polygons} is {@code null}. + */ + public GeoPolygonCollection(List polygons) { + this(polygons, null, null); + } + + /** + * Constructs a {@link GeoPolygonCollection}. + * + * @param polygons The polygons that define the multi-polygon. + * @param boundingBox Bounding box for the multi-polygon. + * @param customProperties Additional properties of the multi-polygon. + * @throws NullPointerException If {@code polygons} is {@code null}. + */ + public GeoPolygonCollection(List polygons, GeoBoundingBox boundingBox, + Map customProperties) { + super(boundingBox, customProperties); + + Objects.requireNonNull(polygons, "'polygons' cannot be null."); + this.polygons = Collections.unmodifiableList(new ArrayList<>(polygons)); + } + + /** + * Unmodifiable representation of the {@link GeoPolygon geometric polygons} representing this multi-polygon. + * + * @return An unmodifiable representation of the {@link GeoPolygon geometric polygons} representing this + * multi-polygon. + */ + public List getPolygons() { + return polygons; + } + + /** + * Unmodifiable representation of the {@link GeoPosition geometric positions} representing this multi-polygon. + * + * @return An unmodifiable representation of the {@link GeoPosition geometric positions} representing this + * multi-polygon. + */ + GeoArray>> getCoordinates() { + return new GeoArray<>(this); + } + + @Override + public GeoObjectType getType() { + return GeoObjectType.MULTI_POLYGON; + } + + @Override + public int hashCode() { + return Objects.hash(polygons, super.hashCode()); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof GeoPolygonCollection)) { + return false; + } + + if (this == obj) { + return true; + } + + GeoPolygonCollection other = (GeoPolygonCollection) obj; + + return super.equals(obj) && Objects.equals(polygons, other.polygons); + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject() + .writeStringField("type", GeoObjectType.MULTI_POLYGON.toString()) + .writeArrayField("coordinates", polygons, + (writer, geoPolygon) -> writer.writeArray(geoPolygon.getRings(), JsonWriter::writeJson)) + .writeJsonField("bbox", getBoundingBox()); + + return writeCustomProperties(jsonWriter).writeEndObject(); + } + + /** + * Reads a JSON stream into a {@link GeoPolygonCollection}. + * + * @param jsonReader The {@link JsonReader} being read. + * @return The {@link GeoPolygonCollection} that the JSON stream represented, or null if it pointed to JSON null. + * @throws IllegalStateException If the {@code type} node exists and isn't equal to {@code MultiPolygon}. + * @throws IOException If a {@link GeoPolygonCollection} fails to be read from the {@code jsonReader}. + */ + public static GeoPolygonCollection fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + List polygons = null; + GeoBoundingBox boundingBox = null; + Map customProperties = null; + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("type".equals(fieldName)) { + String type = reader.getString(); + if (!GeoObjectType.MULTI_POLYGON.toString().equals(type)) { + throw new IllegalStateException("'type' was expected to be non-null and equal to " + + "'MultiPolygon'. The found 'type' was '" + type + "'."); + } + } else if ("coordinates".equals(fieldName)) { + List> polygonRings + = reader.readArray(polygon -> polygon.readArray(GeoLinearRing::fromJson)); + polygons = new ArrayList<>(polygonRings.size()); + for (List rings : polygonRings) { + polygons.add(new GeoPolygon(rings)); + } + } else if ("bbox".equals(fieldName)) { + boundingBox = GeoBoundingBox.fromJson(reader); + } else { + if (customProperties == null) { + customProperties = new LinkedHashMap<>(); + } + + customProperties.put(fieldName, reader.readUntyped()); + } + } + + return new GeoPolygonCollection(polygons, boundingBox, customProperties); + }); + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoPosition.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoPosition.java new file mode 100644 index 000000000000..8decb9b4c3cb --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/GeoPosition.java @@ -0,0 +1,220 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models.geo; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonSerializable; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.serialization.json.JsonWriter; + +import java.io.IOException; +import java.util.List; +import java.util.Objects; + +/** + *

        Represents a geographic position in GeoJSON format.

        + * + *

        This class encapsulates a geographic position defined by longitude, latitude, and optionally altitude. It + * provides methods to access these properties.

        + * + *

        This class is useful when you want to work with a geographic position in a geographic context. For example, + * you can use it to represent a location on a map or a point in a geographic dataset.

        + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public final class GeoPosition implements JsonSerializable { + // GeoPosition is a commonly used model, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(GeoPosition.class); + + private final double longitude; + private final double latitude; + + private final Double altitude; + + /** + * Constructs a geo position. + * + * @param longitude Longitudinal position. + * @param latitude Latitudinal position. + */ + public GeoPosition(double longitude, double latitude) { + this(longitude, latitude, null); + } + + /** + * Constructs a geo position. + * + * @param longitude Longitudinal position. + * @param latitude Latitudinal position. + * @param altitude Altitude position. + */ + public GeoPosition(double longitude, double latitude, Double altitude) { + this.longitude = longitude; + this.latitude = latitude; + this.altitude = altitude; + } + + /** + * The longitudinal position of the geometric position. + * + * @return The longitudinal position. + */ + public double getLongitude() { + return longitude; + } + + /** + * The latitudinal position of the geometric position. + * + * @return The latitudinal position. + */ + public double getLatitude() { + return latitude; + } + + /** + * The altitude of the geometric position. + * + * @return The altitude. + */ + public Double getAltitude() { + return altitude; + } + + /** + * Gets the number of coordinates used to compose the position. + *

        + * This will return either 2 or 3 depending on whether {@link #getAltitude() altitude is set}. + * + * @return The number of coordinates used to compose the position. + */ + public int count() { + return (altitude == null) ? 2 : 3; + } + + /** + * Array accessor for the coordinates of this position. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
        Operation result mapping
        IndexResult
        0{@link #getLongitude() Longitude}
        1{@link #getLatitude() Latitude}
        2{@link #getAltitude() Altitude} if non-null, otherwise {@link IndexOutOfBoundsException}
        3+{@link IndexOutOfBoundsException}
        + * + * @param index Coordinate index to access. + * @return The coordinate value for the index. + * @throws IndexOutOfBoundsException If {@code index} is equal to or greater than {@link #count()}. + */ + double get(int index) { + switch (index) { + case 0: + return longitude; + + case 1: + return latitude; + + case 2: + if (altitude == null) { + throw LOGGER.logThrowableAsError(new IndexOutOfBoundsException("Index out of range: " + index)); + } + + return altitude; + + default: + throw LOGGER.logThrowableAsError(new IndexOutOfBoundsException("Index out of range: " + index)); + } + } + + @Override + public int hashCode() { + return Objects.hash(longitude, latitude, altitude); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof GeoPosition)) { + return false; + } + + if (obj == this) { + return true; + } + + GeoPosition other = (GeoPosition) obj; + return Double.compare(longitude, other.longitude) == 0 + && Double.compare(latitude, other.latitude) == 0 + && Objects.equals(altitude, other.altitude); + } + + @Override + public String toString() { + return (altitude != null) + ? String.format("[%s, %s, %s]", longitude, latitude, altitude) + : String.format("[%s, %s]", longitude, latitude); + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartArray().writeDouble(longitude).writeDouble(latitude); + + if (altitude != null) { + jsonWriter.writeDouble(altitude); + } + + return jsonWriter.writeEndArray(); + } + + /** + * Reads a JSON stream into a {@link GeoPosition}. + * + * @param jsonReader The {@link JsonReader} being read. + * @return The {@link GeoPosition} that the JSON stream represented, or null if it pointed to JSON null. + * @throws IllegalStateException If the {@link GeoPosition} has less than two or more than three positions in the + * array. + * @throws IOException If a {@link GeoPosition} fails to be read from the {@code jsonReader}. + */ + public static GeoPosition fromJson(JsonReader jsonReader) throws IOException { + List coordinates = jsonReader.readArray(reader -> { + if (reader.currentToken() == JsonToken.NUMBER) { + return reader.getDouble(); + } else { + return null; + } + }); + + if (coordinates == null) { + return null; + } + + int coordinateCount = coordinates.size(); + if (coordinateCount < 2 || coordinateCount > 3) { + throw LOGGER.logThrowableAsError(new IllegalStateException("Only 2 or 3 element coordinates supported.")); + } + + double longitude = coordinates.get(0).doubleValue(); + double latitude = coordinates.get(1).doubleValue(); + Double altitude = (coordinateCount == 3) ? coordinates.get(2).doubleValue() : null; + + return new GeoPosition(longitude, latitude, altitude); + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/package-info.java new file mode 100644 index 000000000000..4ceb6af95f51 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/geo/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * This package contains classes for geo-related models. + */ +package io.clientcore.core.models.geo; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/package-info.java new file mode 100644 index 000000000000..ff14a0e63724 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing the models used in the ClientCore SDK. + */ +package io.clientcore.core.models; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/traits/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/models/traits/package-info.java deleted file mode 100644 index c2738721e8da..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/traits/package-info.java +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - * This package contains interfaces that represent common cross-cutting aspects of functionality offered by libraries in - * the SDK. Each interface is referred to as a 'trait', and classes that implement the interface are said to have that - * trait. - * - *

        The particular focus of traits in the SDK is to enable higher-level libraries the ability to more abstractly - * configure client libraries as part of their builders, prior to the client itself being instantiated. By doing this, - * these high-level libraries are able to reason about functionality more simply. It is important to appreciate that - * despite the availability of these cross-cutting traits, there is no promise that configuration of each builder can - * simply be a matter of providing the same arguments for all builders! Each builder must be configured appropriately - * for its requirements, or else runtime failures may occur when the builder is asked to create the associated client. - *

        - */ -package io.clientcore.core.models.traits; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/ObjectSerializer.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/ObjectSerializer.java new file mode 100644 index 000000000000..a7dd8c151382 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/ObjectSerializer.java @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.serialization; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.reflect.Type; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.nio.channels.WritableByteChannel; + +/** + * Generic interface covering serializing and deserialization objects. + */ +public interface ObjectSerializer { + /** + * Reads a byte array into its object representation. + * + * @param data The byte array. + * @param type {@link Type} representing the object. + * @param Type of the object. + * @return The object represented by the deserialized byte array. + * @throws IOException If the deserialization fails. + */ + T deserializeFromBytes(byte[] data, Type type) throws IOException; + + /** + * Reads a stream into its object representation. + * + * @param stream {@link InputStream} of data. + * @param type {@link Type} representing the object. + * @param Type of the object. + * @return The object represented by the deserialized stream. + * @throws IOException If the deserialization fails. + */ + T deserializeFromStream(InputStream stream, Type type) throws IOException; + + /** + * Reads a channel into its object representation. + * + * @param channel {@link ReadableByteChannel} of data. + * @param type {@link Type} representing the object. + * @param Type of the object. + * @return The object represented by the deserialized channel. + * @throws IOException If the deserialization fails. + */ + default T deserializeFromChannel(ReadableByteChannel channel, Type type) throws IOException { + return deserializeFromStream(Channels.newInputStream(channel), type); + } + + /** + * Serializes an object into a byte array. + * + * @param value The object to serialize. + * @return The binary representation of the serialized object. + * @throws IOException If the serialization fails. + */ + byte[] serializeToBytes(Object value) throws IOException; + + /** + * Serializes and writes an object into a provided stream. + * + * @param stream {@link OutputStream} where the serialized object will be written. + * @param value The object to serialize. + * @throws IOException If the serialization fails. + */ + void serializeToStream(OutputStream stream, Object value) throws IOException; + + /** + * Serializes and writes an object into a provided channel. + * + * @param channel {@link WritableByteChannel} where the serialized object will be written. + * @param value The object to serialize. + * @throws IOException If the serialization fails. + */ + default void serializeToChannel(WritableByteChannel channel, Object value) throws IOException { + serializeToStream(Channels.newOutputStream(channel), value); + } + + /** + * Indicates whether the given implementation of {@link ObjectSerializer} supports the provided format. + *

        + * An implementation of {@link ObjectSerializer} may support multiple formats, such as JSON and XML. + *

        + * A check for support should be made before attempting to serialize or deserialize an object. + * + * @param format The format to check support for. + * @return Whether the format is supported. + */ + boolean supportsFormat(SerializationFormat format); +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/serializer/SerializationFormat.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/SerializationFormat.java similarity index 89% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/util/serializer/SerializationFormat.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/SerializationFormat.java index f24d91ee1725..82f9c68ef8cd 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/serializer/SerializationFormat.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/SerializationFormat.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.util.serializer; +package io.clientcore.core.serialization; /** * Represents serialization formats. diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/JsonOptions.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/JsonOptions.java index e60504ae3be4..894d49573a0f 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/JsonOptions.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/JsonOptions.java @@ -3,16 +3,17 @@ package io.clientcore.core.serialization.json; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; + /** * Contains configuration options for creating a {@link JsonReader} or {@link JsonWriter}. * * @see io.clientcore.core.serialization.json - * @see JsonProvider - * @see JsonProviders */ +@Metadata(properties = MetadataProperties.FLUENT) public final class JsonOptions { - private boolean nonNumericNumbersSupported = true; private boolean isJsoncSupported; /** @@ -21,30 +22,6 @@ public final class JsonOptions { public JsonOptions() { } - /** - * Whether non-numeric numbers such as {@code NaN} and {@code INF} and {@code -INF} are supported. - *

        - * By default, this is configured to true. - * - * @return Whether non-numeric numbers are supported. - */ - public boolean isNonNumericNumbersSupported() { - return nonNumericNumbersSupported; - } - - /** - * Sets whether non-numeric numbers such as {@code NaN} and {@code INF} and {@code -INF} are supported. - *

        - * By default, this is configured to true. - * - * @param nonNumericNumbersSupported Whether non-numeric numbers are supported. - * @return The updated JsonOptions object. - */ - public JsonOptions setNonNumericNumbersSupported(boolean nonNumericNumbersSupported) { - this.nonNumericNumbersSupported = nonNumericNumbersSupported; - return this; - } - /** * Whether JSONC (JSON with comments) is supported. * By default, this is configured to false. diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/JsonProvider.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/JsonProvider.java deleted file mode 100644 index ce5dd861fdd2..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/JsonProvider.java +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.serialization.json; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; -import java.io.Writer; - -/** - * An interface to be implemented by any core plugin that wishes to provide an alternate {@link JsonReader} or - * {@link JsonWriter} implementation. - * - * @see io.clientcore.core.serialization.json - * @see JsonReader - * @see JsonWriter - */ -public interface JsonProvider { - - /** - * Creates an instance of {@link JsonReader} that reads a {@code byte[]}. - * - * @param json The JSON represented as a {@code byte[]}. - * @param options {@link JsonOptions} to configure the creation of the {@link JsonReader}. - * @return A new instance of {@link JsonReader}. - * @throws NullPointerException If {@code json} or {@code options} is null. - * @throws IOException If a {@link JsonReader} cannot be instantiated. - */ - JsonReader createReader(byte[] json, JsonOptions options) throws IOException; - - /** - * Creates an instance of {@link JsonReader} that reads a {@link String}. - * - * @param json The JSON represented as a {@link String}. - * @param options {@link JsonOptions} to configure the creation of the {@link JsonReader}. - * @return A new instance of {@link JsonReader}. - * @throws NullPointerException If {@code json} or {@code options} is null. - * @throws IOException If a {@link JsonReader} cannot be instantiated. - */ - JsonReader createReader(String json, JsonOptions options) throws IOException; - - /** - * Creates an instance of {@link JsonReader} that reads a {@link InputStream}. - * - * @param json The JSON represented as a {@link InputStream}. - * @param options {@link JsonOptions} to configure the creation of the {@link JsonReader}. - * @return A new instance of {@link JsonReader}. - * @throws NullPointerException If {@code json} or {@code options} is null. - * @throws IOException If a {@link JsonReader} cannot be instantiated. - */ - JsonReader createReader(InputStream json, JsonOptions options) throws IOException; - - /** - * Creates an instance of {@link JsonReader} that reads a {@link Reader}. - * - * @param json The JSON represented as a {@link Reader}. - * @param options {@link JsonOptions} to configure the creation of the {@link JsonReader}. - * @return A new instance of {@link JsonReader}. - * @throws NullPointerException If {@code json} or {@code options} is null. - * @throws IOException If a {@link JsonReader} cannot be instantiated. - */ - JsonReader createReader(Reader json, JsonOptions options) throws IOException; - - /** - * Creates an instance of {@link JsonWriter} that writes to an {@link OutputStream}. - * - * @param json The JSON represented as an {@link OutputStream}. - * @param options {@link JsonOptions} to configure the creation of the {@link JsonWriter}. - * @return A new instance of {@link JsonWriter}. - * @throws NullPointerException If {@code json} or {@code options} is null. - * @throws IOException If a {@link JsonReader} cannot be instantiated. - */ - JsonWriter createWriter(OutputStream json, JsonOptions options) throws IOException; - - /** - * Creates an instance of {@link JsonWriter} that writes to an {@link Writer}. - * - * @param json The JSON represented as an {@link Writer}. - * @param options {@link JsonOptions} to configure the creation of the {@link JsonWriter}. - * @return A new instance of {@link JsonWriter}. - * @throws NullPointerException If {@code json} or {@code options} is null. - * @throws IOException If a {@link JsonReader} cannot be instantiated. - */ - JsonWriter createWriter(Writer json, JsonOptions options) throws IOException; -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/JsonProviders.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/JsonProviders.java deleted file mode 100644 index 7b5d21cc8a2c..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/JsonProviders.java +++ /dev/null @@ -1,245 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.serialization.json; - -import io.clientcore.core.serialization.json.implementation.DefaultJsonProvider; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.ServiceLoader; - -/** - * Utility class for {@link JsonProvider} that will use the implementation of {@link JsonProvider} found on the - * classpath to create instances of {@link JsonReader} or {@link JsonWriter}. - *

        - * If no implementation of {@link JsonProvider} is found on the classpath a default implementation provided by this - * library will be used. - *

        - * At this time, additional implementations of {@link JsonProvider} found on the classpath after the first will cause - * an {@link IllegalStateException} to be thrown. Ensure the implementation that should be used is the only one listed - * in {@code META-INF/services/io.clientcore.core.serialization.json.JsonProvider} of your JAR. - * - * @see io.clientcore.core.serialization.json - * @see JsonProvider - * @see JsonReader - * @see JsonWriter - */ -public final class JsonProviders { - private static final JsonOptions DEFAULT_OPTIONS = new JsonOptions(); - private static final JsonProvider JSON_PROVIDER; - - static { - // Use as classloader to load provider-configuration files and provider classes the classloader - // that loaded this class. In most cases this will be the System classloader. - // But this choice here provides additional flexibility in managed environments that control - // classloading differently (OSGi, Spring and others) and don't depend on the - // System classloader to load HttpClientProvider classes. - ServiceLoader serviceLoader - = ServiceLoader.load(JsonProvider.class, JsonProvider.class.getClassLoader()); - // Use the first provider found in the service loader iterator. - List implementationNames = new ArrayList<>(); - Iterator it = serviceLoader.iterator(); - if (it.hasNext()) { - JsonProvider implementation = it.next(); - implementationNames.add(implementation.getClass().getName()); - JSON_PROVIDER = implementation; - } else { - JSON_PROVIDER = new DefaultJsonProvider(); - } - - while (it.hasNext()) { - // For now, ignore other implementations found. - JsonProvider implementation = it.next(); - implementationNames.add(implementation.getClass().getName()); - } - - if (implementationNames.size() > 1) { - throw new IllegalStateException( - "More than one implementation of 'io.clientcore.core.serialization.json.JsonProvider' was found on the " - + "classpath. At this time 'core' only supports one implementation being on the classpath. Remove " - + "all implementations, except the one that should be used during runtime, from " - + "'META-INF/services/io.clientcore.core.serialization.json.JsonProvider'. Found implementations " - + "were: " + String.join(", ", implementationNames)); - } - } - - private JsonProviders() { - // no-op - } - - /** - * Creates an instance of {@link JsonReader} that reads a {@code byte[]}. - *

        - * If a provider could not be found on the classpath this will use the default implementation, effectively the - * equivalent to {@link #createReader(byte[], JsonOptions) createReader(json, new JsonOptions())}. - * - * @param json The JSON represented as a {@code byte[]}. - * @return A new instance of {@link JsonReader}. - * @throws NullPointerException If {@code json} is null. - * @throws IOException If a {@link JsonReader} cannot be instantiated. - */ - public static JsonReader createReader(byte[] json) throws IOException { - return createReader(json, DEFAULT_OPTIONS); - } - - /** - * Creates an instance of {@link JsonReader} that reads a {@code byte[]}. - * - * @param json The JSON represented as a {@code byte[]}. - * @param options {@link JsonOptions} to configure the creation of the {@link JsonReader}. - * @return A new instance of {@link JsonReader}. - * @throws NullPointerException If {@code json} or {@code options} is null. - * @throws IOException If a {@link JsonReader} cannot be instantiated. - */ - public static JsonReader createReader(byte[] json, JsonOptions options) throws IOException { - return JSON_PROVIDER.createReader(json, options); - } - - /** - * Creates an instance of {@link JsonReader} that reads a {@link String}. - *

        - * If a provider could not be found on the classpath this will use the default implementation, effectively the - * equivalent to {@link #createReader(String, JsonOptions) createReader(json, new JsonOptions())}. - * - * @param json The JSON represented as a {@link String}. - * @return A new instance of {@link JsonReader}. - * @throws NullPointerException If {@code json} is null. - * @throws IOException If a {@link JsonReader} cannot be instantiated. - */ - public static JsonReader createReader(String json) throws IOException { - return createReader(json, DEFAULT_OPTIONS); - } - - /** - * Creates an instance of {@link JsonReader} that reads a {@link String}. - * - * @param json The JSON represented as a {@link String}. - * @param options {@link JsonOptions} to configure the creation of the {@link JsonReader}. - * @return A new instance of {@link JsonReader}. - * @throws NullPointerException If {@code json} or {@code options} is null. - * @throws IOException If a {@link JsonReader} cannot be instantiated. - */ - public static JsonReader createReader(String json, JsonOptions options) throws IOException { - return JSON_PROVIDER.createReader(json, options); - } - - /** - * Creates an instance of {@link JsonReader} that reads a {@link InputStream}. - *

        - * If a provider could not be found on the classpath this will use the default implementation, effectively the - * equivalent to - * {@link #createReader(InputStream, JsonOptions) createReader(json, new JsonOptions())}. - * - * @param json The JSON represented as a {@link InputStream}. - * @return A new instance of {@link JsonReader}. - * @throws NullPointerException If {@code json} is null. - * @throws IOException If a {@link JsonReader} cannot be instantiated. - */ - public static JsonReader createReader(InputStream json) throws IOException { - return createReader(json, DEFAULT_OPTIONS); - } - - /** - * Creates an instance of {@link JsonReader} that reads a {@link InputStream}. - * - * @param json The JSON represented as a {@link InputStream}. - * @param options {@link JsonOptions} to configure the creation of the {@link JsonReader}. - * @return A new instance of {@link JsonReader}. - * @throws NullPointerException If {@code json} or {@code options} is null. - * @throws IOException If a {@link JsonReader} cannot be instantiated. - */ - public static JsonReader createReader(InputStream json, JsonOptions options) throws IOException { - return JSON_PROVIDER.createReader(json, options); - } - - /** - * Creates an instance of {@link JsonReader} that reads a {@link Reader}. - *

        - * If a provider could not be found on the classpath this will use the default implementation, effectively the - * equivalent to {@link #createReader(Reader, JsonOptions) createReader(json, new JsonOptions())}. - * - * @param json The JSON represented as a {@link Reader}. - * @return A new instance of {@link JsonReader}. - * @throws NullPointerException If {@code json} is null. - * @throws IOException If a {@link JsonReader} cannot be instantiated. - */ - public static JsonReader createReader(Reader json) throws IOException { - return createReader(json, DEFAULT_OPTIONS); - } - - /** - * Creates an instance of {@link JsonReader} that reads a {@link Reader}. - * - * @param json The JSON represented as a {@link Reader}. - * @param options {@link JsonOptions} to configure the creation of the {@link JsonReader}. - * @return A new instance of {@link JsonReader}. - * @throws NullPointerException If {@code json} or {@code options} is null. - * @throws IOException If a {@link JsonReader} cannot be instantiated. - */ - public static JsonReader createReader(Reader json, JsonOptions options) throws IOException { - return JSON_PROVIDER.createReader(json, options); - } - - /** - * Creates an instance of {@link JsonWriter} that writes to an {@link OutputStream}. - *

        - * If a provider could not be found on the classpath this will use the default implementation, effectively the - * equivalent to {@link #createWriter(OutputStream, JsonOptions) createWriter(json, new JsonOptions())}. - * - * @param json The JSON represented as an {@link OutputStream}. - * @return A new instance of {@link JsonWriter}. - * @throws NullPointerException If {@code json} is null. - * @throws IOException If a {@link JsonWriter} cannot be instantiated. - */ - public static JsonWriter createWriter(OutputStream json) throws IOException { - return createWriter(json, DEFAULT_OPTIONS); - } - - /** - * Creates an instance of {@link JsonWriter} that writes to an {@link OutputStream}. - * - * @param json The JSON represented as an {@link OutputStream}. - * @param options {@link JsonOptions} to configure the creation of the {@link JsonWriter}. - * @return A new instance of {@link JsonWriter}. - * @throws NullPointerException If {@code json} or {@code options} is null. - * @throws IOException If a {@link JsonWriter} cannot be instantiated. - */ - public static JsonWriter createWriter(OutputStream json, JsonOptions options) throws IOException { - return JSON_PROVIDER.createWriter(json, options); - } - - /** - * Creates an instance of {@link JsonWriter} that writes to an {@link Writer}. - *

        - * If a provider could not be found on the classpath this will use the default implementation, effectively the - * equivalent to {@link #createWriter(Writer, JsonOptions) createWriter(json, new JsonOptions())}. - * - * @param json The JSON represented as an {@link Writer}. - * @return A new instance of {@link JsonWriter}. - * @throws NullPointerException If {@code json} is null. - * @throws IOException If a {@link JsonWriter} cannot be instantiated. - */ - public static JsonWriter createWriter(Writer json) throws IOException { - return createWriter(json, DEFAULT_OPTIONS); - } - - /** - * Creates an instance of {@link JsonWriter} that writes to an {@link Writer}. - * - * @param json The JSON represented as an {@link Writer}. - * @param options {@link JsonOptions} to configure the creation of the {@link JsonWriter}. - * @return A new instance of {@link JsonWriter}. - * @throws NullPointerException If {@code json} or {@code options} is null. - * @throws IOException If a {@link JsonWriter} cannot be instantiated. - */ - public static JsonWriter createWriter(Writer json, JsonOptions options) throws IOException { - return JSON_PROVIDER.createWriter(json, options); - } -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/JsonReader.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/JsonReader.java index 768000108fb8..639052fa27ff 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/JsonReader.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/JsonReader.java @@ -3,10 +3,21 @@ package io.clientcore.core.serialization.json; +import io.clientcore.core.serialization.json.implementation.JsonUtils; +import io.clientcore.core.serialization.json.implementation.jackson.core.JsonFactory; +import io.clientcore.core.serialization.json.implementation.jackson.core.JsonParser; import io.clientcore.core.serialization.json.implementation.jackson.core.io.JsonStringEncoder; +import io.clientcore.core.utils.IOExceptionCheckedFunction; +import java.io.ByteArrayInputStream; import java.io.Closeable; import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StringReader; +import java.math.BigDecimal; +import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Base64; @@ -19,18 +30,141 @@ /** * Reads a JSON value as a stream of tokens. *

        - * Instances of {@link JsonReader} are created using an instance of {@link JsonProvider} or using the utility methods - * in {@link JsonProviders}. + * Instances of {@link JsonReader} are created using the factory methods on this type. * * @see io.clientcore.core.serialization.json - * @see JsonProvider - * @see JsonProviders */ -public abstract class JsonReader implements Closeable { +public final class JsonReader implements Closeable { + private static final JsonFactory FACTORY = new JsonFactory(); + + private final JsonParser parser; + private final Reader jsonReader; + private final boolean resetSupported; + private final boolean jsoncSupported; + + private JsonToken currentToken; + + private JsonReader(JsonParser parser, boolean resetSupported, Reader jsonReader, JsonOptions options) { + this.parser = parser; + + if (options != null) { + this.parser.configure(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS, true) + .configure(JsonParser.Feature.ALLOW_COMMENTS, options.isJsoncSupported()); + this.jsoncSupported = options.isJsoncSupported(); + } else { + this.parser.configure(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS, true); + this.jsoncSupported = false; + } + this.resetSupported = resetSupported; + this.jsonReader = jsonReader; + } + + private JsonReader(JsonParser parser, boolean resetSupported, Reader jsonReader, boolean jsoncSupported) { + this.parser = parser.configure(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS, true) + .configure(JsonParser.Feature.ALLOW_COMMENTS, jsoncSupported); + this.resetSupported = resetSupported; + this.jsonReader = jsonReader; + this.jsoncSupported = jsoncSupported; + } + + /** + * Constructs an instance of {@link JsonReader} from a {@code byte[]}. + *

        + * Calls {@link #fromBytes(byte[], JsonOptions)} with {@code options} set to null. + * + * @param json JSON {@code byte[]}. + * @return An instance of {@link JsonReader}. + * @throws IOException If a {@link JsonReader} could not be constructed from the JSON {@code byte[]}. + */ + public static JsonReader fromBytes(byte[] json) throws IOException { + return fromStream(new ByteArrayInputStream(json), null); + } + + /** + * Constructs an instance of {@link JsonReader} from a {@code byte[]}. + * + * @param json JSON {@code byte[]}. + * @param options {@link JsonOptions} to configure the creation of the {@link JsonWriter}. + * @return An instance of {@link JsonReader}. + * @throws IOException If a {@link JsonReader} could not be constructed from the JSON {@code byte[]}. + */ + public static JsonReader fromBytes(byte[] json, JsonOptions options) throws IOException { + return fromStream(new ByteArrayInputStream(json), options); + } + + /** + * Constructs an instance of {@link JsonReader} from a String. + *

        + * Calls {@link #fromString(String, JsonOptions)} with {@code options} set to null. + * + * @param json JSON String. + * @return An instance of {@link JsonReader}. + * @throws IOException If a {@link JsonReader} could not be constructed from the JSON String. + */ + public static JsonReader fromString(String json) throws IOException { + return fromReader(new StringReader(json), null); + } + + /** + * Constructs an instance of {@link JsonReader} from a String. + * + * @param json JSON String. + * @param options {@link JsonOptions} to configure the creation of the {@link JsonWriter}. + * @return An instance of {@link JsonReader}. + * @throws IOException If a {@link JsonReader} could not be constructed from the JSON String. + */ + public static JsonReader fromString(String json, JsonOptions options) throws IOException { + return fromReader(new StringReader(json), options); + } + + /** + * Constructs an instance of {@link JsonReader} from an {@link InputStream}. + *

        + * Calls {@link #fromStream(InputStream, JsonOptions)} with {@code options} set to null. + * + * @param json JSON {@link InputStream}. + * @return An instance of {@link JsonReader}. + * @throws IOException If a {@link JsonReader} could not be constructed from the JSON {@link InputStream}. + */ + public static JsonReader fromStream(InputStream json) throws IOException { + return fromReader(new InputStreamReader(json), null); + } + + /** + * Constructs an instance of {@link JsonReader} from an {@link InputStream}. + * + * @param json JSON {@link InputStream}. + * @param options {@link JsonOptions} to configure the creation of the {@link JsonWriter}. + * @return An instance of {@link JsonReader}. + * @throws IOException If a {@link JsonReader} could not be constructed from the JSON {@link InputStream}. + */ + public static JsonReader fromStream(InputStream json, JsonOptions options) throws IOException { + return fromReader(new InputStreamReader(json), options); + } + + /** + * Constructs an instance of {@link JsonReader} from a {@link Reader}. + *

        + * Calls {@link #fromReader(Reader, JsonOptions)} with {@code options} set to null. + * + * @param reader JSON {@link Reader}. + * @return An instance of {@link JsonReader}. + * @throws IOException If a {@link JsonReader} could not be constructed from the JSON {@link Reader}. + */ + public static JsonReader fromReader(Reader reader) throws IOException { + return fromReader(reader, null); + } + /** - * Creates an instance of {@link JsonReader}. + * Constructs an instance of {@link JsonReader} from a {@link Reader}. + * + * @param reader JSON {@link Reader}. + * @param options {@link JsonOptions} to configure the creation of the {@link JsonWriter}. + * @return An instance of {@link JsonReader}. + * @throws IOException If a {@link JsonReader} could not be constructed from the JSON {@link Reader}. */ - public JsonReader() { + public static JsonReader fromReader(Reader reader, JsonOptions options) throws IOException { + return new JsonReader(FACTORY.createParser(reader), reader.markSupported(), reader, options); } /** @@ -41,7 +175,9 @@ public JsonReader() { * * @return The {@link JsonToken} that the reader currently points, or null if the reader isn't pointing to a token. */ - public abstract JsonToken currentToken(); + public JsonToken currentToken() { + return currentToken; + } /** * Iterates to and returns the next {@link JsonToken} in the JSON encoded value. @@ -51,7 +187,10 @@ public JsonReader() { * @return The next {@link JsonToken} in the JSON encoded value, or null if reading completes. * @throws IOException If the next token cannot be determined. */ - public abstract JsonToken nextToken() throws IOException; + public JsonToken nextToken() throws IOException { + currentToken = mapToken(parser.nextToken(), currentToken); + return currentToken; + } /** * Closes the JSON stream. @@ -59,14 +198,16 @@ public JsonReader() { * @throws IOException If the underlying content store fails to close. */ @Override - public abstract void close() throws IOException; + public void close() throws IOException { + parser.close(); + } /** * Whether the {@link #currentToken()} is {@link JsonToken#START_ARRAY} or {@link JsonToken#START_OBJECT}. * * @return Whether the {@link #currentToken()} is {@link JsonToken#START_ARRAY} or {@link JsonToken#START_OBJECT}. */ - public final boolean isStartArrayOrObject() { + public boolean isStartArrayOrObject() { return isStartArrayOrObject(currentToken()); } @@ -79,7 +220,7 @@ private static boolean isStartArrayOrObject(JsonToken token) { * * @return Whether the {@link #currentToken()} is {@link JsonToken#END_ARRAY} or {@link JsonToken#END_OBJECT}. */ - public final boolean isEndArrayOrObject() { + public boolean isEndArrayOrObject() { return isEndArrayOrObject(currentToken()); } @@ -101,20 +242,28 @@ private static boolean isEndArrayOrObject(JsonToken token) { * {@link JsonToken#NULL}. * @throws IOException If the next value cannot be read as binary. */ - public abstract byte[] getBinary() throws IOException; + public byte[] getBinary() throws IOException { + if (currentToken() == JsonToken.NULL) { + return null; + } else { + return parser.getBinaryValue(); + } + } /** * Gets the boolean value if the reader is currently pointing to a {@link JsonToken#BOOLEAN} token. *

        * If the reader is pointing to any other token type an {@link IllegalStateException} will be thrown. *

        - * If {@link Boolean} should be read use {@link #getNullable(ReadValueCallback)}. + * If {@link Boolean} should be read use {@link #getNullable(IOExceptionCheckedFunction)}. * * @return The boolean value based on the {@link JsonToken#BOOLEAN}. * @throws IllegalStateException If the reader isn't pointing to {@link JsonToken#BOOLEAN}. * @throws IOException If the next value cannot be read as a boolean. */ - public abstract boolean getBoolean() throws IOException; + public boolean getBoolean() throws IOException { + return parser.getBooleanValue(); + } /** * Gets the float value if the reader is currently pointing to a {@link JsonToken#NUMBER} or @@ -125,7 +274,7 @@ private static boolean isEndArrayOrObject(JsonToken token) { *

        * All other {@link JsonToken} types will throw an {@link IllegalStateException}. *

        - * If {@link Float} should be read use {@link #getNullable(ReadValueCallback)}. + * If {@link Float} should be read use {@link #getNullable(IOExceptionCheckedFunction)}. * * @return The float value based on the current token. * @throws NumberFormatException If the current token is a {@link JsonToken#STRING} and cannot be converted to a @@ -133,7 +282,9 @@ private static boolean isEndArrayOrObject(JsonToken token) { * @throws IllegalStateException If the current token isn't a {@link JsonToken#NUMBER} or {@link JsonToken#STRING}. * @throws IOException If the next value cannot be read as a float. */ - public abstract float getFloat() throws IOException; + public float getFloat() throws IOException { + return parser.getFloatValue(); + } /** * Gets the double value if the reader is currently pointing to a {@link JsonToken#NUMBER} or @@ -144,7 +295,7 @@ private static boolean isEndArrayOrObject(JsonToken token) { *

        * All other {@link JsonToken} types will throw an {@link IllegalStateException}. *

        - * If {@link Double} should be read use {@link #getNullable(ReadValueCallback)}. + * If {@link Double} should be read use {@link #getNullable(IOExceptionCheckedFunction)}. * * @return The double value based on the current token. * @throws NumberFormatException If the current token is a {@link JsonToken#STRING} and cannot be converted to a @@ -152,7 +303,9 @@ private static boolean isEndArrayOrObject(JsonToken token) { * @throws IllegalStateException If the current token isn't a {@link JsonToken#NUMBER} or {@link JsonToken#STRING}. * @throws IOException If the next value cannot be read as a double. */ - public abstract double getDouble() throws IOException; + public double getDouble() throws IOException { + return parser.getDoubleValue(); + } /** * Gets the int value if the reader is currently pointing to a {@link JsonToken#NUMBER} or @@ -163,7 +316,7 @@ private static boolean isEndArrayOrObject(JsonToken token) { *

        * All other {@link JsonToken} types will throw an {@link IllegalStateException}. *

        - * If {@link Integer} should be read use {@link #getNullable(ReadValueCallback)}. + * If {@link Integer} should be read use {@link #getNullable(IOExceptionCheckedFunction)}. * * @return The int value based on the current token. * @throws NumberFormatException If the current token is a {@link JsonToken#STRING} and cannot be converted to an @@ -171,7 +324,9 @@ private static boolean isEndArrayOrObject(JsonToken token) { * @throws IllegalStateException If the current token isn't a {@link JsonToken#NUMBER} or {@link JsonToken#STRING}. * @throws IOException If the next value cannot be read as an int. */ - public abstract int getInt() throws IOException; + public int getInt() throws IOException { + return parser.getIntValue(); + } /** * Gets the long value if the reader is currently pointing to a {@link JsonToken#NUMBER} or @@ -182,7 +337,7 @@ private static boolean isEndArrayOrObject(JsonToken token) { *

        * All other {@link JsonToken} types will throw an {@link IllegalStateException}. *

        - * If {@link Long} should be read use {@link #getNullable(ReadValueCallback)}. + * If {@link Long} should be read use {@link #getNullable(IOExceptionCheckedFunction)}. * * @return The long value based on the current token. * @throws NumberFormatException If the current token is a {@link JsonToken#STRING} and cannot be converted to a @@ -190,7 +345,9 @@ private static boolean isEndArrayOrObject(JsonToken token) { * @throws IllegalStateException If the current token isn't a {@link JsonToken#NUMBER} or {@link JsonToken#STRING}. * @throws IOException If the next value cannot be read as a long. */ - public abstract long getLong() throws IOException; + public long getLong() throws IOException { + return parser.getLongValue(); + } /** * Gets the String value if the reader is currently pointing to a {@link JsonToken#BOOLEAN}, {@link JsonToken#NULL}, @@ -206,7 +363,9 @@ private static boolean isEndArrayOrObject(JsonToken token) { * {@link JsonToken#NUMBER}, or {@link JsonToken#STRING}. * @throws IOException If the next value cannot be read as a String. */ - public abstract String getString() throws IOException; + public String getString() throws IOException { + return parser.getValueAsString(); + } /** * Gets the field name if the reader is currently pointing to a {@link JsonToken#FIELD_NAME}. @@ -217,7 +376,9 @@ private static boolean isEndArrayOrObject(JsonToken token) { * @throws IllegalStateException If the current token isn't a {@link JsonToken#FIELD_NAME}. * @throws IOException If the next value cannot be read as a field name. */ - public abstract String getFieldName() throws IOException; + public String getFieldName() throws IOException { + return parser.getCurrentName(); + } /** * Convenience method to read a nullable type. @@ -232,8 +393,8 @@ private static boolean isEndArrayOrObject(JsonToken token) { * {@code nonNullGetter}. * @throws IOException If the next value cannot be read as a nullable. */ - public final T getNullable(ReadValueCallback nonNullGetter) throws IOException { - return currentToken() == JsonToken.NULL ? null : nonNullGetter.read(this); + public T getNullable(IOExceptionCheckedFunction nonNullGetter) throws IOException { + return currentToken() == JsonToken.NULL ? null : nonNullGetter.apply(this); } /** @@ -244,7 +405,9 @@ public final T getNullable(ReadValueCallback nonNullGetter) t * * @throws IOException If the children cannot be skipped. */ - public abstract void skipChildren() throws IOException; + public void skipChildren() throws IOException { + parser.skipChildren(); + } /** * Reads and returns the current JSON object the {@link JsonReader} is pointing to. This will mutate the current @@ -264,14 +427,26 @@ public final T getNullable(ReadValueCallback nonNullGetter) t * {@link JsonToken#FIELD_NAME} followed by {@link JsonToken#START_OBJECT} * @throws IOException If the child object cannot be buffered. */ - public abstract JsonReader bufferObject() throws IOException; + public JsonReader bufferObject() throws IOException { + JsonToken currentToken = currentToken(); + if (currentToken == JsonToken.START_OBJECT || currentToken == JsonToken.FIELD_NAME) { + Reader jsonReader = new StringReader(readRemainingFieldsAsJsonObject()); + return new JsonReader(FACTORY.createParser(jsonReader), jsonReader.markSupported(), jsonReader, + jsoncSupported); + } else { + throw new IllegalStateException("Cannot buffer a JSON object from a non-object, non-field name " + + "starting location. Starting location: " + currentToken()); + } + } /** * Indicates whether the {@link JsonReader} supports {@link #reset() resetting}. * * @return Whether {@link #reset()} is supported. */ - public abstract boolean isResetSupported(); + public boolean isResetSupported() { + return resetSupported; + } /** * Creates a new {@link JsonReader} reset to the beginning of the JSON stream. @@ -283,7 +458,14 @@ public final T getNullable(ReadValueCallback nonNullGetter) t * @throws IllegalStateException If resetting isn't supported by the current JsonReader. * @throws IOException If the {@link JsonReader} cannot be reset. */ - public abstract JsonReader reset() throws IOException; + public JsonReader reset() throws IOException { + if (!resetSupported) { + throw new IllegalStateException("'reset' isn't supported by this JsonReader."); + } + + jsonReader.reset(); + return new JsonReader(FACTORY.createParser(jsonReader), true, jsonReader, jsoncSupported); + } /** * Recursively reads the JSON token sub-stream if the current token is either {@link JsonToken#START_ARRAY} or @@ -295,7 +477,7 @@ public final T getNullable(ReadValueCallback nonNullGetter) t * @return The raw textual value of the JSON token sub-stream. * @throws IOException If the children cannot be read. */ - public final String readChildren() throws IOException { + public String readChildren() throws IOException { return readInternal(new StringBuilder(), true, false).toString(); } @@ -310,7 +492,7 @@ public final String readChildren() throws IOException { * @throws NullPointerException If {@code buffer} is null. * @throws IOException If the children cannot be read. */ - public final void readChildren(StringBuilder buffer) throws IOException { + public void readChildren(StringBuilder buffer) throws IOException { readInternal(buffer, true, false); } @@ -327,7 +509,7 @@ public final void readChildren(StringBuilder buffer) throws IOException { * @return The raw textual value of the remaining JSON fields. * @throws IOException If the remaining JSON fields cannot be read. */ - public final String readRemainingFieldsAsJsonObject() throws IOException { + public String readRemainingFieldsAsJsonObject() throws IOException { return readInternal(new StringBuilder(), false, true).toString(); } @@ -345,7 +527,7 @@ public final String readRemainingFieldsAsJsonObject() throws IOException { * @throws NullPointerException If {@code buffer} is null. * @throws IOException If the remaining JSON fields cannot be read. */ - public final void readRemainingFieldsAsJsonObject(StringBuilder buffer) throws IOException { + public void readRemainingFieldsAsJsonObject(StringBuilder buffer) throws IOException { readInternal(buffer, false, true); } @@ -440,8 +622,8 @@ private void appendJson(StringBuilder buffer, JsonToken token) throws IOExceptio * Once the JSON stream is prepared for object reading this will get the next token and pass this {@link JsonReader} * into the {@code objectReaderFunc} to handle reading the object. *

        - * If a JSON array should be read use {@link #readArray(ReadValueCallback)} or if a JSON map should be read use - * {@link #readMap(ReadValueCallback)}. + * If a JSON array should be read use {@link #readArray(IOExceptionCheckedFunction)} or if a JSON map should be read use + * {@link #readMap(IOExceptionCheckedFunction)}. * * @param objectReaderFunc Function that reads each value of the key-value pair. * @param The value element type. @@ -449,7 +631,7 @@ private void appendJson(StringBuilder buffer, JsonToken token) throws IOExceptio * @throws IllegalStateException If the token isn't {@link JsonToken#START_OBJECT}, {@link JsonToken#NULL}, or null. * @throws IOException If the object cannot be read. */ - public final T readObject(ReadValueCallback objectReaderFunc) throws IOException { + public T readObject(IOExceptionCheckedFunction objectReaderFunc) throws IOException { return readMapOrObject(objectReaderFunc, false); } @@ -464,8 +646,8 @@ public final T readObject(ReadValueCallback objectReaderFunc) * {@link JsonReader} into the {@code elementReaderFunc} to handle reading the element of the array. If the array * has no elements an empty list will be returned. *

        - * If a JSON object should be read use {@link #readObject(ReadValueCallback)} or if a JSON map should be read use - * {@link #readMap(ReadValueCallback)}. + * If a JSON object should be read use {@link #readObject(IOExceptionCheckedFunction)} or if a JSON map should be read use + * {@link #readMap(IOExceptionCheckedFunction)}. * * @param elementReaderFunc Function that reads each element of the array. * @param The array element type. @@ -473,7 +655,7 @@ public final T readObject(ReadValueCallback objectReaderFunc) * @throws IllegalStateException If the token isn't {@link JsonToken#START_ARRAY}, {@link JsonToken#NULL}, or null. * @throws IOException If the array cannot be read. */ - public final List readArray(ReadValueCallback elementReaderFunc) throws IOException { + public List readArray(IOExceptionCheckedFunction elementReaderFunc) throws IOException { JsonToken currentToken = currentToken(); if (currentToken == null) { currentToken = nextToken(); @@ -489,7 +671,7 @@ public final List readArray(ReadValueCallback elementReade List array = new LinkedList<>(); while (nextToken() != JsonToken.END_ARRAY) { - array.add(elementReaderFunc.read(this)); + array.add(elementReaderFunc.apply(this)); } return array; @@ -506,8 +688,8 @@ public final List readArray(ReadValueCallback elementReade * the key then get the next token after that and pass this {@link JsonReader} into the {@code valueReaderFunc} to * handle reading the value of the key-value pair. If the object has no elements an empty map will be returned. *

        - * If a JSON object should be read use {@link #readObject(ReadValueCallback)} or if a JSON array should be read use - * {@link #readArray(ReadValueCallback)}. + * If a JSON object should be read use {@link #readObject(IOExceptionCheckedFunction)} or if a JSON array should be read use + * {@link #readArray(IOExceptionCheckedFunction)}. * * @param valueReaderFunc Function that reads each value of the key-value pair. * @param The value element type. @@ -515,7 +697,7 @@ public final List readArray(ReadValueCallback elementReade * @throws IllegalStateException If the token isn't {@link JsonToken#START_OBJECT}, {@link JsonToken#NULL}, or null. * @throws IOException If the map cannot be read. */ - public final Map readMap(ReadValueCallback valueReaderFunc) throws IOException { + public Map readMap(IOExceptionCheckedFunction valueReaderFunc) throws IOException { return readMapOrObject(reader -> { Map map = new LinkedHashMap<>(); @@ -523,14 +705,15 @@ public final Map readMap(ReadValueCallback valueRe String fieldName = getFieldName(); nextToken(); - map.put(fieldName, valueReaderFunc.read(this)); + map.put(fieldName, valueReaderFunc.apply(this)); } return map; }, true); } - private T readMapOrObject(ReadValueCallback valueReaderFunc, boolean isMap) throws IOException { + private T readMapOrObject(IOExceptionCheckedFunction valueReaderFunc, boolean isMap) + throws IOException { JsonToken currentToken = currentToken(); if (currentToken == null) { currentToken = nextToken(); @@ -546,7 +729,7 @@ private T readMapOrObject(ReadValueCallback valueReaderFunc, throw new IllegalStateException("Unexpected token to begin " + type + " deserialization: " + currentToken); } - return valueReaderFunc.read(this); + return valueReaderFunc.apply(this); } /** @@ -564,8 +747,8 @@ private T readMapOrObject(ReadValueCallback valueReaderFunc, *

          *
        • null if the starting token is null or {@link JsonToken#NULL}
        • *
        • true or false if the starting token is {@link JsonToken#BOOLEAN}
        • - *
        • One of int, long, float, or double is the starting token is {@link JsonToken#NUMBER}, the smallest - * containing value will be used if the number is an integer
        • + *
        • One of int, long, {@link BigInteger}, double, or {@link BigDecimal} if the starting token is + * {@link JsonToken#NUMBER}, the smallest containing value will be used
        • *
        • An array of untyped elements if the starting point is {@link JsonToken#START_ARRAY}
        • *
        • A map of String-untyped value if the starting point is {@link JsonToken#START_OBJECT}
        • *
        @@ -575,7 +758,7 @@ private T readMapOrObject(ReadValueCallback valueReaderFunc, * {@link JsonToken#END_OBJECT}, or {@link JsonToken#FIELD_NAME} or if the untyped object is deeply nested. * @throws IOException If the untyped cannot be read. */ - public final Object readUntyped() throws IOException { + public Object readUntyped() throws IOException { JsonToken token = currentToken(); if (token == null) { token = nextToken(); @@ -601,26 +784,7 @@ private Object readUntypedHelper(int depth) throws IOException { } else if (token == JsonToken.BOOLEAN) { return getBoolean(); } else if (token == JsonToken.NUMBER) { - String numberText = getText(); - - if ("INF".equals(numberText) - || "Infinity".equals(numberText) - || "-INF".equals(numberText) - || "-Infinity".equals(numberText) - || "NaN".equals(numberText)) { - // Return special Double values as text as not all implementations of JsonReader may be able to handle - // them as Doubles when parsing generically. - return numberText; - } else if (numberText.contains(".")) { - // Unlike integers always use Double to prevent floating point rounding issues. - return Double.parseDouble(numberText); - } else { - try { - return Integer.parseInt(numberText); - } catch (NumberFormatException ex) { - return Long.parseLong(numberText); - } - } + return JsonUtils.parseNumber(getText()); } else if (token == JsonToken.STRING) { return getString(); } else if (token == JsonToken.START_ARRAY) { @@ -672,7 +836,7 @@ private Object readUntypedHelper(int depth) throws IOException { * @throws IllegalStateException If the current token is null. * @throws IOException If the text cannot be read. */ - public final String getText() throws IOException { + public String getText() throws IOException { return getTextInternal(false); } @@ -747,4 +911,54 @@ private String getTextInternal(boolean raw) throws IOException { return ""; // Should never reach this point. } } + + /* + * Maps the Jackson Core JsonToken to the core JsonToken. + * + * core doesn't support the EMBEDDED_OBJECT or NOT_AVAILABLE Jackson Core JsonTokens, but those should only be + * returned by specialty implementations that aren't used. + */ + private static JsonToken mapToken( + io.clientcore.core.serialization.json.implementation.jackson.core.JsonToken nextToken, JsonToken currentToken) { + // Special case for when currentToken is called after instantiating the JsonReader. + if (nextToken == null && currentToken == null) { + return null; + } else if (nextToken == null) { + return JsonToken.END_DOCUMENT; + } + + switch (nextToken) { + case START_OBJECT: + return JsonToken.START_OBJECT; + + case END_OBJECT: + return JsonToken.END_OBJECT; + + case START_ARRAY: + return JsonToken.START_ARRAY; + + case END_ARRAY: + return JsonToken.END_ARRAY; + + case FIELD_NAME: + return JsonToken.FIELD_NAME; + + case VALUE_STRING: + return JsonToken.STRING; + + case VALUE_NUMBER_INT: + case VALUE_NUMBER_FLOAT: + return JsonToken.NUMBER; + + case VALUE_TRUE: + case VALUE_FALSE: + return JsonToken.BOOLEAN; + + case VALUE_NULL: + return JsonToken.NULL; + + default: + throw new IllegalStateException("Unsupported token type: '" + nextToken + "'."); + } + } } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/JsonSerializable.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/JsonSerializable.java index c37c93779265..0f626da07327 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/JsonSerializable.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/JsonSerializable.java @@ -50,7 +50,7 @@ public interface JsonSerializable> { * @throws IOException If the object fails to be written to the {@code outputStream}. */ default void toJson(OutputStream outputStream) throws IOException { - try (JsonWriter jsonWriter = JsonProviders.createWriter(outputStream)) { + try (JsonWriter jsonWriter = JsonWriter.toStream(outputStream)) { toJson(jsonWriter).flush(); } } @@ -62,7 +62,7 @@ default void toJson(OutputStream outputStream) throws IOException { * @throws IOException If the object fails to be written to the {@code writer}. */ default void toJson(Writer writer) throws IOException { - try (JsonWriter jsonWriter = JsonProviders.createWriter(writer)) { + try (JsonWriter jsonWriter = JsonWriter.toWriter(writer)) { toJson(jsonWriter).flush(); } } @@ -75,7 +75,7 @@ default void toJson(Writer writer) throws IOException { */ default String toJsonString() throws IOException { StringBuilderWriter writer = new StringBuilderWriter(); - try (JsonWriter jsonWriter = JsonProviders.createWriter(writer)) { + try (JsonWriter jsonWriter = JsonWriter.toWriter(writer)) { toJson(jsonWriter).flush(); return writer.toString(); } @@ -89,7 +89,7 @@ default String toJsonString() throws IOException { */ default byte[] toJsonBytes() throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - try (JsonWriter jsonWriter = JsonProviders.createWriter(outputStream)) { + try (JsonWriter jsonWriter = JsonWriter.toStream(outputStream)) { toJson(jsonWriter).flush(); return outputStream.toByteArray(); } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/JsonSerializer.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/JsonSerializer.java new file mode 100644 index 000000000000..8fc96d9b8518 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/JsonSerializer.java @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.serialization.json; + +import io.clientcore.core.implementation.TypeUtil; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.serialization.ObjectSerializer; +import io.clientcore.core.serialization.SerializationFormat; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.List; + +/** + * Class providing basic JSON serialization and deserialization methods. + *

        + * The implementation of this class is based on the usage of {@link JsonReader} and {@link JsonWriter}. + *

        + * The deserialization methods only work with primitive types, simple list and map collections, and models implementing + * {@link JsonSerializable}. Or, in code terms, types that are producible calling {@link JsonReader#readUntyped()} or + * provide a static factory method {@code fromJson(JsonReader)}. + *

        + * The serialization methods will work with any value but for complex types that don't implement + * {@link JsonSerializable} they will serialize the object using the type's {@code toString()} method. + */ +public class JsonSerializer implements ObjectSerializer { + private static final ClientLogger LOGGER = new ClientLogger(JsonSerializer.class); + + /** + * Creates an instance of the {@link JsonSerializer}. + */ + public JsonSerializer() { + } + + /** + * Reads a JSON byte array into its object representation. + * + * @param bytes The JSON byte array. + * @param type {@link Type} representing the object. + * @param Type of the object. + * @return The object represented by the deserialized JSON byte array. + * @throws IOException If the deserialization fails. + */ + @SuppressWarnings("unchecked") + @Override + public T deserializeFromBytes(byte[] bytes, Type type) throws IOException { + try (JsonReader jsonReader = JsonReader.fromBytes(bytes)) { + if (type instanceof ParameterizedType && List.class.isAssignableFrom(TypeUtil.getRawClass(type))) { + ParameterizedType parameterizedType = (ParameterizedType) type; + Type listElementType = parameterizedType.getActualTypeArguments()[0]; + if (listElementType instanceof Class + && JsonSerializable.class.isAssignableFrom(TypeUtil.getRawClass(listElementType))) { + List list = jsonReader.readArray(arrayReader -> { + Type actualTypeArgument = parameterizedType.getActualTypeArguments()[0]; + Class clazz = (Class) actualTypeArgument; + try { + return clazz.getMethod("fromJson", JsonReader.class).invoke(null, arrayReader); + } catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException e) { + throw LOGGER.logThrowableAsError(new RuntimeException(e)); + } + }); + return (T) list; + } + } else if (type instanceof Class + && JsonSerializable.class.isAssignableFrom(TypeUtil.getRawClass(type))) { + Class clazz = (Class) type; + + return (T) clazz.getMethod("fromJson", JsonReader.class).invoke(null, jsonReader); + } + return (T) jsonReader.readUntyped(); + } catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException e) { + throw LOGGER.logThrowableAsError(new RuntimeException(e)); + } + } + + /** + * Reads a JSON stream into its object representation. + * + * @param stream JSON stream. + * @param type {@link Type} representing the object. + * @param Type of the object. + * @return The object represented by the deserialized JSON stream. + * @throws IOException If the deserialization fails. + */ + @SuppressWarnings("unchecked") + @Override + public T deserializeFromStream(InputStream stream, Type type) throws IOException { + try (JsonReader jsonReader = JsonReader.fromStream(stream)) { + if (type instanceof Class && JsonSerializable.class.isAssignableFrom(TypeUtil.getRawClass(type))) { + Class clazz = (Class) type; + + return (T) clazz.getMethod("fromJson", JsonReader.class).invoke(null, jsonReader); + } else { + return (T) jsonReader.readUntyped(); + } + } catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException e) { + throw LOGGER.logThrowableAsError(new RuntimeException(e)); + } + } + + /** + * Converts the object into a JSON byte array. + * + * @param value The object. + * @return The JSON binary representation of the serialized object. + * @throws IOException If the serialization fails. + */ + @Override + public byte[] serializeToBytes(Object value) throws IOException { + if (value == null) { + return null; + } + + if (value instanceof JsonSerializable) { + return ((JsonSerializable) value).toJsonBytes(); + } + + try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + JsonWriter jsonWriter = JsonWriter.toStream(byteArrayOutputStream)) { + + jsonWriter.writeUntyped(value); + jsonWriter.flush(); + + return byteArrayOutputStream.toByteArray(); + } + } + + /** + * Writes an object's JSON representation into a stream. + * + * @param stream {@link OutputStream} where the object's JSON representation will be written. + * @param value The object to serialize. + * @throws IOException If the serialization fails. + */ + @Override + public void serializeToStream(OutputStream stream, Object value) throws IOException { + if (value == null) { + return; + } + + try (JsonWriter jsonWriter = JsonWriter.toStream(stream)) { + jsonWriter.writeUntyped(value); + } + } + + @Override + public final boolean supportsFormat(SerializationFormat format) { + return format == SerializationFormat.JSON; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/JsonWriteContext.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/JsonWriteContext.java index c77bbb4a0742..47cf5c0e718f 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/JsonWriteContext.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/JsonWriteContext.java @@ -3,6 +3,9 @@ package io.clientcore.core.serialization.json; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; + /** * Context of JSON handling. *

        @@ -11,6 +14,7 @@ * * @see JsonWriter */ +@Metadata(properties = MetadataProperties.FLUENT) public final class JsonWriteContext { /** * Initial writing context. diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/JsonWriter.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/JsonWriter.java index ac99a6262d67..cafcb7d130e9 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/JsonWriter.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/JsonWriter.java @@ -3,8 +3,15 @@ package io.clientcore.core.serialization.json; +import io.clientcore.core.serialization.json.implementation.jackson.core.JsonFactory; +import io.clientcore.core.serialization.json.implementation.jackson.core.JsonGenerator; +import io.clientcore.core.utils.IOExceptionCheckedBiConsumer; + import java.io.Closeable; import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.Writer; import java.util.Arrays; import java.util.Map; import java.util.Objects; @@ -12,19 +19,93 @@ /** * Writes a JSON value as a stream of tokens. *

        - * Instances of {@link JsonWriter} are created using an instance of {@link JsonProvider} or using the utility methods - * in {@link JsonProviders}. + * Instances of {@link JsonWriter} are created using factory method on this class. * * @see io.clientcore.core.serialization.json - * @see JsonProvider - * @see JsonProviders */ @SuppressWarnings("resource") -public abstract class JsonWriter implements Closeable { +public final class JsonWriter implements Closeable { + private static final JsonFactory FACTORY = new JsonFactory(); + + private final JsonGenerator generator; + + // Initial state is always root. + private JsonWriteContext context = JsonWriteContext.ROOT; + /** * Creates an instance of {@link JsonWriter}. */ - public JsonWriter() { + private JsonWriter(JsonGenerator generator, JsonOptions options) { + this.generator = generator; + this.generator.configure(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS, true); + } + + /** + * Creates a {@link JsonWriter} that writes the given {@link OutputStream}. + *

        + * The passed {@link OutputStream} won't be closed when {@link #close()} is called as the {@link JsonWriter} isn't + * the owner of the stream. + *

        + * This will call {@link #toStream(OutputStream, JsonOptions)} with null {@link JsonOptions}. + * + * @param json The {@link OutputStream} that will be written. + * @return An instance of {@link JsonWriter}. + * @throws NullPointerException If {@code json} is null. + * @throws IOException If a {@link JsonWriter} could not be constructed from the {@link OutputStream}. + */ + public static JsonWriter toStream(OutputStream json) throws IOException { + return toStream(json, null); + } + + /** + * Creates a {@link JsonWriter} that writes the given {@link OutputStream}. + *

        + * The passed {@link OutputStream} won't be closed when {@link #close()} is called as the {@link JsonWriter} + * isn't the owner of the stream. + * + * @param json The {@link OutputStream} that will be written. + * @param options {@link JsonOptions} to configure the creation of the {@link JsonWriter}. + * @return An instance of {@link JsonWriter}. + * @throws NullPointerException If {@code json} is null. + * @throws IOException If a {@link JsonWriter} could not be constructed from the {@link OutputStream}. + */ + public static JsonWriter toStream(OutputStream json, JsonOptions options) throws IOException { + Objects.requireNonNull(json, "'json' cannot be null."); + return new JsonWriter(FACTORY.createGenerator(new OutputStreamWriter(json)), options); + } + + /** + * Creates a {@link JsonWriter} that writes the given {@link Writer}. + *

        + * The passed {@link Writer} won't be closed when {@link #close()} is called as the {@link JsonWriter} isn't + * the owner of the stream. + *

        + * This will call {@link #toWriter(Writer, JsonOptions)} with null {@link JsonOptions}. + * + * @param json The {@link Writer} that will be written. + * @return An instance of {@link JsonWriter}. + * @throws NullPointerException If {@code json} is null. + * @throws IOException If a {@link JsonWriter} could not be constructed from the {@link Writer}. + */ + public static JsonWriter toWriter(Writer json) throws IOException { + return toWriter(json, null); + } + + /** + * Creates a {@link JsonWriter} that writes the given {@link Writer}. + *

        + * The passed {@link Writer} won't be closed when {@link #close()} is called as the {@link JsonWriter} isn't + * the owner of the stream. + * + * @param json The {@link Writer} that will be written. + * @param options {@link JsonOptions} to configure the creation of the {@link JsonWriter}. + * @return An instance of {@link JsonWriter}. + * @throws NullPointerException If {@code json} is null. + * @throws IOException If a {@link JsonWriter} could not be constructed from the {@link Writer}. + */ + public static JsonWriter toWriter(Writer json, JsonOptions options) throws IOException { + Objects.requireNonNull(json, "'json' cannot be null."); + return new JsonWriter(FACTORY.createGenerator(json), options); } /** @@ -36,7 +117,9 @@ public JsonWriter() { * * @return The current writing context. */ - public abstract JsonWriteContext getWriteContext(); + public JsonWriteContext getWriteContext() { + return context; + } /** * Closes the JSON stream. @@ -51,7 +134,15 @@ public JsonWriter() { * @throws IOException If the underlying content store fails to close. */ @Override - public abstract void close() throws IOException; + public void close() throws IOException { + if (context != JsonWriteContext.COMPLETED) { + throw new IllegalStateException("Writing of the JSON object must be completed before the writer can be " + + "closed. Current writing state is '" + context.getWriteState() + "'."); + } + + generator.flush(); + generator.close(); + } /** * Flushes any un-flushed content written to this writer. @@ -61,7 +152,10 @@ public JsonWriter() { * @return The flushed JsonWriter object. * @throws IOException If the underlying content fails to flush. */ - public abstract JsonWriter flush() throws IOException; + public JsonWriter flush() throws IOException { + generator.flush(); + return this; + } /** * Writes a JSON start object ({@code {}). @@ -69,7 +163,13 @@ public JsonWriter() { * @return The updated JsonWriter object. * @throws IOException If JSON start object fails to be written. */ - public abstract JsonWriter writeStartObject() throws IOException; + public JsonWriter writeStartObject() throws IOException { + context.validateToken(JsonToken.START_OBJECT); + generator.writeStartObject(); + + context = context.updateContext(JsonToken.START_OBJECT); + return this; + } /** * Writes a JSON start object ({@code {}) with a preceding field name. @@ -82,7 +182,7 @@ public JsonWriter() { * @throws NullPointerException If {@code fieldName} is null. * @throws IOException If either {@code fieldName} or JSON start object fails to be written. */ - public final JsonWriter writeStartObject(String fieldName) throws IOException { + public JsonWriter writeStartObject(String fieldName) throws IOException { Objects.requireNonNull(fieldName, "'fieldName' cannot be null."); return writeFieldName(fieldName).writeStartObject(); @@ -96,7 +196,13 @@ public final JsonWriter writeStartObject(String fieldName) throws IOException { * @return The updated JsonWriter object. * @throws IOException If JSON end object fails to be written. */ - public abstract JsonWriter writeEndObject() throws IOException; + public JsonWriter writeEndObject() throws IOException { + context.validateToken(JsonToken.END_OBJECT); + generator.writeEndObject(); + + context = context.updateContext(JsonToken.END_OBJECT); + return this; + } /** * Writes a JSON start array ({@code [}). @@ -104,7 +210,13 @@ public final JsonWriter writeStartObject(String fieldName) throws IOException { * @return The updated JsonWriter object. * @throws IOException If JSON start array fails to be written. */ - public abstract JsonWriter writeStartArray() throws IOException; + public JsonWriter writeStartArray() throws IOException { + context.validateToken(JsonToken.START_ARRAY); + generator.writeStartArray(); + + context = context.updateContext(JsonToken.START_ARRAY); + return this; + } /** * Writes a JSON start array ({@code [}) with a preceding field name. @@ -117,7 +229,7 @@ public final JsonWriter writeStartObject(String fieldName) throws IOException { * @throws NullPointerException If {@code fieldName} is null. * @throws IOException If either {@code fieldName} or JSON start array fails to be written. */ - public final JsonWriter writeStartArray(String fieldName) throws IOException { + public JsonWriter writeStartArray(String fieldName) throws IOException { Objects.requireNonNull(fieldName, "'fieldName' cannot be null."); return writeFieldName(fieldName).writeStartArray(); @@ -129,7 +241,13 @@ public final JsonWriter writeStartArray(String fieldName) throws IOException { * @return The updated JsonWriter object. * @throws IOException If JSON end array fails to be written. */ - public abstract JsonWriter writeEndArray() throws IOException; + public JsonWriter writeEndArray() throws IOException { + context.validateToken(JsonToken.END_ARRAY); + generator.writeEndArray(); + + context = context.updateContext(JsonToken.END_ARRAY); + return this; + } /** * Writes a JSON field name ({@code "fieldName":}). @@ -139,7 +257,15 @@ public final JsonWriter writeStartArray(String fieldName) throws IOException { * @throws NullPointerException If {@code fieldName} is null. * @throws IOException If {@code fieldName} fails to be written. */ - public abstract JsonWriter writeFieldName(String fieldName) throws IOException; + public JsonWriter writeFieldName(String fieldName) throws IOException { + Objects.requireNonNull(fieldName, "'fieldName' cannot be null."); + + context.validateToken(JsonToken.FIELD_NAME); + generator.writeFieldName(fieldName); + + context = context.updateContext(JsonToken.FIELD_NAME); + return this; + } /** * Writes a {@link JsonSerializable} object. @@ -153,7 +279,7 @@ public final JsonWriter writeStartArray(String fieldName) throws IOException { * @return The updated JsonWriter object. * @throws IOException If the {@link JsonSerializable} fails to be written. */ - public final JsonWriter writeJson(JsonSerializable value) throws IOException { + public JsonWriter writeJson(JsonSerializable value) throws IOException { return (value == null) ? this : value.toJson(this); } @@ -164,12 +290,12 @@ public final JsonWriter writeJson(JsonSerializable value) throws IOException * {@code elementWriterFunc} and finishing by writing the end array ({@code ]}). *

        * If an element in the array is null, {@link JsonToken#NULL} will be written for that element. If null elements - * should be excluded from serialization use {@link #writeArray(Object[], WriteValueCallback, boolean)} and pass + * should be excluded from serialization use {@link #writeArray(Object[], IOExceptionCheckedBiConsumer, boolean)} and pass * true for {@code skipNullElements}. *

        * If {@code array} is null {@link JsonToken#NULL} will be written. *

        - * This API is used instead of {@link #writeArrayField(String, Object[], WriteValueCallback)} when the value + * This API is used instead of {@link #writeArrayField(String, Object[], IOExceptionCheckedBiConsumer)} when the value * needs to be written to the root of the JSON value, as an element in an array, or after a call to * {@link #writeFieldName(String)}. * @@ -180,7 +306,7 @@ public final JsonWriter writeJson(JsonSerializable value) throws IOException * @throws NullPointerException If {@code elementWriterFunc} is null. * @throws IOException If the JSON array fails to be written, either the start or end array or an element write. */ - public final JsonWriter writeArray(T[] array, WriteValueCallback elementWriterFunc) + public JsonWriter writeArray(T[] array, IOExceptionCheckedBiConsumer elementWriterFunc) throws IOException { return writeArray(array, elementWriterFunc, false); } @@ -197,7 +323,7 @@ public final JsonWriter writeArray(T[] array, WriteValueCallback * If {@code array} is null {@link JsonToken#NULL} will be written. *

        - * This API is used instead of {@link #writeArrayField(String, Object[], WriteValueCallback, boolean)} when the + * This API is used instead of {@link #writeArrayField(String, Object[], IOExceptionCheckedBiConsumer, boolean)} when the * value needs to be written to the root of the JSON value, as an element in an array, or after a call to * {@link #writeFieldName(String)}. * @@ -209,7 +335,7 @@ public final JsonWriter writeArray(T[] array, WriteValueCallback JsonWriter writeArray(T[] array, WriteValueCallback elementWriterFunc, + public JsonWriter writeArray(T[] array, IOExceptionCheckedBiConsumer elementWriterFunc, boolean skipNullElements) throws IOException { Objects.requireNonNull(elementWriterFunc, "'elementWriterFunc' cannot be null."); @@ -227,12 +353,12 @@ public JsonWriter writeArray(T[] array, WriteValueCallback el * {@code elementWriterFunc} and finishing by writing the end array ({@code ]}). *

        * If an element in the array is null, {@link JsonToken#NULL} will be written for that element. If null elements - * should be excluded from serialization use {@link #writeArray(Iterable, WriteValueCallback, boolean)} and pass + * should be excluded from serialization use {@link #writeArray(Iterable, IOExceptionCheckedBiConsumer, boolean)} and pass * true for {@code skipNullElements}. *

        * If {@code array} is null {@link JsonToken#NULL} will be written. *

        - * This API is used instead of {@link #writeArrayField(String, Iterable, WriteValueCallback)} when the value + * This API is used instead of {@link #writeArrayField(String, Iterable, IOExceptionCheckedBiConsumer)} when the value * needs to be written to the root of the JSON value, as an element in an array, or after a call to * {@link #writeFieldName(String)}. * @@ -243,7 +369,7 @@ public JsonWriter writeArray(T[] array, WriteValueCallback el * @throws NullPointerException If {@code elementWriterFunc} is null. * @throws IOException If the JSON array fails to be written, either the start or end array or an element write. */ - public final JsonWriter writeArray(Iterable array, WriteValueCallback elementWriterFunc) + public JsonWriter writeArray(Iterable array, IOExceptionCheckedBiConsumer elementWriterFunc) throws IOException { return writeArray(array, elementWriterFunc, false); } @@ -260,7 +386,7 @@ public final JsonWriter writeArray(Iterable array, WriteValueCallback * If {@code array} is null {@link JsonToken#NULL} will be written. *

        - * This API is used instead of {@link #writeArrayField(String, Iterable, WriteValueCallback, boolean)} when the + * This API is used instead of {@link #writeArrayField(String, Iterable, IOExceptionCheckedBiConsumer, boolean)} when the * value needs to be written to the root of the JSON value, as an element in an array, or after a call to * {@link #writeFieldName(String)}. * @@ -272,7 +398,7 @@ public final JsonWriter writeArray(Iterable array, WriteValueCallback JsonWriter writeArray(Iterable array, WriteValueCallback elementWriterFunc, + public JsonWriter writeArray(Iterable array, IOExceptionCheckedBiConsumer elementWriterFunc, boolean skipNullElements) throws IOException { Objects.requireNonNull(elementWriterFunc, "'elementWriterFunc' cannot be null."); @@ -283,7 +409,7 @@ public JsonWriter writeArray(Iterable array, WriteValueCallback JsonWriter writeArrayInternal(Iterable array, WriteValueCallback func, + private JsonWriter writeArrayInternal(Iterable array, IOExceptionCheckedBiConsumer func, String fieldName, boolean skipNullElements) throws IOException { if (fieldName == null) { writeStartArray(); @@ -299,7 +425,7 @@ private JsonWriter writeArrayInternal(Iterable array, WriteValueCallback< writeNull(); } else { - func.write(this, element); + func.accept(this, element); } } @@ -318,7 +444,7 @@ private JsonWriter writeArrayInternal(Iterable array, WriteValueCallback< *

        * If {@code map} is null {@link JsonToken#NULL} will be written. *

        - * This API is used instead of {@link #writeMapField(String, Map, WriteValueCallback)} when the value needs to be + * This API is used instead of {@link #writeMapField(String, Map, IOExceptionCheckedBiConsumer)} when the value needs to be * written to the root of the JSON value, as an element in an array, or after a call to * {@link #writeFieldName(String)}. * @@ -329,7 +455,7 @@ private JsonWriter writeArrayInternal(Iterable array, WriteValueCallback< * @throws NullPointerException If {@code valueWriterFunc} is null or any key in the map is null. * @throws IOException If the JSON map fails to be written, either the start or end object or a key or value write. */ - public final JsonWriter writeMap(Map map, WriteValueCallback valueWriterFunc) + public JsonWriter writeMap(Map map, IOExceptionCheckedBiConsumer valueWriterFunc) throws IOException { return writeMap(map, valueWriterFunc, false); } @@ -346,7 +472,7 @@ public final JsonWriter writeMap(Map map, WriteValueCallback * If {@code map} is null {@link JsonToken#NULL} will be written. *

        - * This API is used instead of {@link #writeMapField(String, Map, WriteValueCallback, boolean)} when the value needs + * This API is used instead of {@link #writeMapField(String, Map, IOExceptionCheckedBiConsumer, boolean)} when the value needs * to be written to the root of the JSON value, as an element in an array, or after a call to * {@link #writeFieldName(String)}. * @@ -358,7 +484,7 @@ public final JsonWriter writeMap(Map map, WriteValueCallback JsonWriter writeMap(Map map, WriteValueCallback valueWriterFunc, + public JsonWriter writeMap(Map map, IOExceptionCheckedBiConsumer valueWriterFunc, boolean skipNullValues) throws IOException { Objects.requireNonNull(valueWriterFunc, "'valueWriterFunc' cannot be null."); @@ -370,7 +496,7 @@ public JsonWriter writeMap(Map map, WriteValueCallback JsonWriter writeMapInternal(String fieldName, Map map, - WriteValueCallback valueWriterFunc, boolean skipNullValues) throws IOException { + IOExceptionCheckedBiConsumer valueWriterFunc, boolean skipNullValues) throws IOException { if (fieldName == null) { writeStartObject(); } else { @@ -392,7 +518,7 @@ private JsonWriter writeMapInternal(String fieldName, Map map, writeNull(); } else { // Write the value. - valueWriterFunc.write(this, value); + valueWriterFunc.accept(this, value); } } @@ -411,7 +537,17 @@ private JsonWriter writeMapInternal(String fieldName, Map map, * @return The updated JsonWriter object. * @throws IOException If the binary {@code value} fails to be written. */ - public abstract JsonWriter writeBinary(byte[] value) throws IOException; + public JsonWriter writeBinary(byte[] value) throws IOException { + context.validateToken(JsonToken.STRING); + if (value == null) { + generator.writeNull(); + } else { + generator.writeBinary(value); + } + + context = context.updateContext(JsonToken.STRING); + return this; + } /** * Writes a JSON boolean value ({@code true} or {@code false}). @@ -425,7 +561,13 @@ private JsonWriter writeMapInternal(String fieldName, Map map, * @return The updated JsonWriter object. * @throws IOException If the boolean {@code value} fails to be written. */ - public abstract JsonWriter writeBoolean(boolean value) throws IOException; + public JsonWriter writeBoolean(boolean value) throws IOException { + context.validateToken(JsonToken.BOOLEAN); + generator.writeBoolean(value); + + context = context.updateContext(JsonToken.BOOLEAN); + return this; + } /** * Writes a nullable JSON boolean value ({@code true}, {@code false}, or {@code null}). @@ -441,7 +583,7 @@ private JsonWriter writeMapInternal(String fieldName, Map map, * @return The updated JsonWriter object. * @throws IOException If the Boolean {@code value} fails to be written. */ - public final JsonWriter writeBoolean(Boolean value) throws IOException { + public JsonWriter writeBoolean(Boolean value) throws IOException { return (value == null) ? writeNull() : writeBoolean(value.booleanValue()); } @@ -457,7 +599,13 @@ public final JsonWriter writeBoolean(Boolean value) throws IOException { * @return The updated JsonWriter object. * @throws IOException If the double {@code value} fails to be written. */ - public abstract JsonWriter writeDouble(double value) throws IOException; + public JsonWriter writeDouble(double value) throws IOException { + context.validateToken(JsonToken.NUMBER); + generator.writeNumber(value); + + context = context.updateContext(JsonToken.NUMBER); + return this; + } /** * Writes a JSON float value. @@ -471,7 +619,13 @@ public final JsonWriter writeBoolean(Boolean value) throws IOException { * @return The updated JsonWriter object. * @throws IOException If the float {@code value} fails to be written. */ - public abstract JsonWriter writeFloat(float value) throws IOException; + public JsonWriter writeFloat(float value) throws IOException { + context.validateToken(JsonToken.NUMBER); + generator.writeNumber(value); + + context = context.updateContext(JsonToken.NUMBER); + return this; + } /** * Writes a JSON int value. @@ -485,7 +639,13 @@ public final JsonWriter writeBoolean(Boolean value) throws IOException { * @return The updated JsonWriter object. * @throws IOException If the int {@code value} fails to be written. */ - public abstract JsonWriter writeInt(int value) throws IOException; + public JsonWriter writeInt(int value) throws IOException { + context.validateToken(JsonToken.NUMBER); + generator.writeNumber(value); + + context = context.updateContext(JsonToken.NUMBER); + return this; + } /** * Writes a JSON long value. @@ -499,7 +659,13 @@ public final JsonWriter writeBoolean(Boolean value) throws IOException { * @return The updated JsonWriter object. * @throws IOException If the long {@code value} fails to be written. */ - public abstract JsonWriter writeLong(long value) throws IOException; + public JsonWriter writeLong(long value) throws IOException { + context.validateToken(JsonToken.NUMBER); + generator.writeNumber(value); + + context = context.updateContext(JsonToken.NUMBER); + return this; + } /** * Writes a JSON null. @@ -510,7 +676,13 @@ public final JsonWriter writeBoolean(Boolean value) throws IOException { * @return The updated JsonWriter object. * @throws IOException If a JSON null fails to be written. */ - public abstract JsonWriter writeNull() throws IOException; + public JsonWriter writeNull() throws IOException { + context.validateToken(JsonToken.NULL); + generator.writeNull(); + + context = context.updateContext(JsonToken.NULL); + return this; + } /** * Writes a nullable JSON number value. @@ -524,7 +696,7 @@ public final JsonWriter writeBoolean(Boolean value) throws IOException { * @return The updated JsonWriter object. * @throws IOException If the Number {@code value} fails to be written. */ - public final JsonWriter writeNumber(Number value) throws IOException { + public JsonWriter writeNumber(Number value) throws IOException { if (value == null) { return writeNull(); } else if (value instanceof Byte || value instanceof Short || value instanceof Integer) { @@ -552,7 +724,13 @@ public final JsonWriter writeNumber(Number value) throws IOException { * @return The updated JsonWriter object. * @throws IOException If the String {@code value} fails to be written. */ - public abstract JsonWriter writeString(String value) throws IOException; + public JsonWriter writeString(String value) throws IOException { + context.validateToken(JsonToken.STRING); + generator.writeString(value); + + context = context.updateContext(JsonToken.STRING); + return this; + } /** * Writes the passed value literally without any additional handling. @@ -569,7 +747,15 @@ public final JsonWriter writeNumber(Number value) throws IOException { * @throws NullPointerException If {@code value} is null. * @throws IOException If the raw {@code value} fails to be written. */ - public abstract JsonWriter writeRawValue(String value) throws IOException; + public JsonWriter writeRawValue(String value) throws IOException { + Objects.requireNonNull(value, "'value' cannot be null."); + + context.validateToken(JsonToken.STRING); + generator.writeRawValue(value); + + context = context.updateContext(JsonToken.STRING); + return this; + } /** * Writes a nullable JSON field. @@ -586,8 +772,8 @@ public final JsonWriter writeNumber(Number value) throws IOException { * @throws NullPointerException If {@code fieldName} or {@code writerFunc} is null. * @throws IOException If the {@code fieldName} or the {@code nullable} fails to be written. */ - public final JsonWriter writeNullableField(String fieldName, T nullable, - WriteValueCallback writerFunc) throws IOException { + public JsonWriter writeNullableField(String fieldName, T nullable, + IOExceptionCheckedBiConsumer writerFunc) throws IOException { Objects.requireNonNull(fieldName, "'fieldName' cannot be null."); Objects.requireNonNull(writerFunc, "'writerFunc' cannot be null."); @@ -595,7 +781,7 @@ public final JsonWriter writeNullableField(String fieldName, T nullable, return writeNullField(fieldName); } - writerFunc.write(writeFieldName(fieldName), nullable); + writerFunc.accept(writeFieldName(fieldName), nullable); return this; } @@ -606,7 +792,7 @@ public final JsonWriter writeNullableField(String fieldName, T nullable, * to a JSON object. *

        * The field is only written when {@code value} isn't null, if a null field needs to be written use - * {@link #writeNullableField(String, Object, WriteValueCallback)}. + * {@link #writeNullableField(String, Object, IOExceptionCheckedBiConsumer)}. * * @param fieldName The field name. * @param value {@link JsonSerializable} object to write. @@ -614,7 +800,7 @@ public final JsonWriter writeNullableField(String fieldName, T nullable, * @throws NullPointerException If {@code fieldName} is null. * @throws IOException If the {@code fieldName} or the {@link JsonSerializable} fails to be written. */ - public final JsonWriter writeJsonField(String fieldName, JsonSerializable value) throws IOException { + public JsonWriter writeJsonField(String fieldName, JsonSerializable value) throws IOException { Objects.requireNonNull(fieldName, "'fieldName' cannot be null."); return (value == null) ? this : value.toJson(writeFieldName(fieldName)); @@ -627,13 +813,13 @@ public final JsonWriter writeJsonField(String fieldName, JsonSerializable val * using the {@code elementWriterFunc} and finishing by writing the end array ({@code ]}). *

        * If an element in the array is null, {@link JsonToken#NULL} will be written for that element. If null elements - * should be excluded from serialization use {@link #writeArrayField(String, Object[], WriteValueCallback, boolean)} + * should be excluded from serialization use {@link #writeArrayField(String, Object[], IOExceptionCheckedBiConsumer, boolean)} * and pass true for {@code skipNullElements}. *

        * The field is only written when {@code value} isn't null, if a null field needs to be written use - * {@link #writeNullableField(String, Object, WriteValueCallback)}. + * {@link #writeNullableField(String, Object, IOExceptionCheckedBiConsumer)}. *

        - * Combines {@link #writeFieldName(String)} and {@link #writeArray(Object[], WriteValueCallback)} to simplify + * Combines {@link #writeFieldName(String)} and {@link #writeArray(Object[], IOExceptionCheckedBiConsumer)} to simplify * adding a key-value to a JSON object. * * @param fieldName The field name. @@ -645,8 +831,8 @@ public final JsonWriter writeJsonField(String fieldName, JsonSerializable val * @throws IOException If the {@code fieldName} or the JSON array fails to be written, either JSON start or end * array or the element write. */ - public final JsonWriter writeArrayField(String fieldName, T[] array, - WriteValueCallback elementWriterFunc) throws IOException { + public JsonWriter writeArrayField(String fieldName, T[] array, + IOExceptionCheckedBiConsumer elementWriterFunc) throws IOException { return writeArrayField(fieldName, array, elementWriterFunc, false); } @@ -661,9 +847,9 @@ public final JsonWriter writeArrayField(String fieldName, T[] array, * serialization. *

        * The field is only written when {@code value} isn't null, if a null field needs to be written use - * {@link #writeNullableField(String, Object, WriteValueCallback)}. + * {@link #writeNullableField(String, Object, IOExceptionCheckedBiConsumer)}. *

        - * Combines {@link #writeFieldName(String)} and {@link #writeArray(Object[], WriteValueCallback, boolean)} to + * Combines {@link #writeFieldName(String)} and {@link #writeArray(Object[], IOExceptionCheckedBiConsumer, boolean)} to * simplify adding a key-value to a JSON object. * * @param fieldName The field name. @@ -677,7 +863,7 @@ public final JsonWriter writeArrayField(String fieldName, T[] array, * array or the element write. */ public JsonWriter writeArrayField(String fieldName, T[] array, - WriteValueCallback elementWriterFunc, boolean skipNullElements) throws IOException { + IOExceptionCheckedBiConsumer elementWriterFunc, boolean skipNullElements) throws IOException { Objects.requireNonNull(fieldName, "'fieldName' cannot be null."); Objects.requireNonNull(elementWriterFunc, "'elementWriterFunc' cannot be null."); @@ -695,13 +881,13 @@ public JsonWriter writeArrayField(String fieldName, T[] array, * using the {@code elementWriterFunc} and finishing by writing the end array ({@code ]}). *

        * If an element in the array is null, {@link JsonToken#NULL} will be written for that element. If null elements - * should be excluded from serialization use {@link #writeArrayField(String, Iterable, WriteValueCallback, boolean)} + * should be excluded from serialization use {@link #writeArrayField(String, Iterable, IOExceptionCheckedBiConsumer, boolean)} * and pass true for {@code skipNullElements}. *

        * The field is only written when {@code value} isn't null, if a null field needs to be written use - * {@link #writeNullableField(String, Object, WriteValueCallback)}. + * {@link #writeNullableField(String, Object, IOExceptionCheckedBiConsumer)}. *

        - * Combines {@link #writeFieldName(String)} and {@link #writeArray(Iterable, WriteValueCallback)} to simplify + * Combines {@link #writeFieldName(String)} and {@link #writeArray(Iterable, IOExceptionCheckedBiConsumer)} to simplify * adding a key-value to a JSON object. * * @param fieldName The field name. @@ -713,8 +899,8 @@ public JsonWriter writeArrayField(String fieldName, T[] array, * @throws IOException If the {@code fieldName} or the JSON array fails to be written, either JSON start or end * array or the element write. */ - public final JsonWriter writeArrayField(String fieldName, Iterable array, - WriteValueCallback elementWriterFunc) throws IOException { + public JsonWriter writeArrayField(String fieldName, Iterable array, + IOExceptionCheckedBiConsumer elementWriterFunc) throws IOException { return writeArrayField(fieldName, array, elementWriterFunc, false); } @@ -729,9 +915,9 @@ public final JsonWriter writeArrayField(String fieldName, Iterable array, * serialization. *

        * The field is only written when {@code value} isn't null, if a null field needs to be written use - * {@link #writeNullableField(String, Object, WriteValueCallback)}. + * {@link #writeNullableField(String, Object, IOExceptionCheckedBiConsumer)}. *

        - * Combines {@link #writeFieldName(String)} and {@link #writeArray(Iterable, WriteValueCallback, boolean)} to + * Combines {@link #writeFieldName(String)} and {@link #writeArray(Iterable, IOExceptionCheckedBiConsumer, boolean)} to * simplify adding a key-value to a JSON object. * * @param fieldName The field name. @@ -745,7 +931,7 @@ public final JsonWriter writeArrayField(String fieldName, Iterable array, * array or the element write. */ public JsonWriter writeArrayField(String fieldName, Iterable array, - WriteValueCallback elementWriterFunc, boolean skipNullElements) throws IOException { + IOExceptionCheckedBiConsumer elementWriterFunc, boolean skipNullElements) throws IOException { Objects.requireNonNull(fieldName, "'fieldName' cannot be null."); Objects.requireNonNull(elementWriterFunc, "'elementWriterFunc' cannot be null."); @@ -767,9 +953,9 @@ public JsonWriter writeArrayField(String fieldName, Iterable array, * of the null value is determined by {@code valueWriterFunc}. *

        * The field is only written when {@code value} isn't null, if a null field needs to be written use - * {@link #writeNullableField(String, Object, WriteValueCallback)}. + * {@link #writeNullableField(String, Object, IOExceptionCheckedBiConsumer)}. *

        - * Combines {@link #writeFieldName(String)} and {@link #writeMap(Map, WriteValueCallback)} to simplify adding a + * Combines {@link #writeFieldName(String)} and {@link #writeMap(Map, IOExceptionCheckedBiConsumer)} to simplify adding a * key-value to a JSON object. * * @param fieldName The field name. @@ -782,8 +968,8 @@ public JsonWriter writeArrayField(String fieldName, Iterable array, * @throws IOException If the {@code fieldName} or the JSON map fails to be written, either JSON start or end object * or the key or value write. */ - public final JsonWriter writeMapField(String fieldName, Map map, - WriteValueCallback valueWriterFunc) throws IOException { + public JsonWriter writeMapField(String fieldName, Map map, + IOExceptionCheckedBiConsumer valueWriterFunc) throws IOException { return writeMapField(fieldName, map, valueWriterFunc, false); } @@ -798,9 +984,9 @@ public final JsonWriter writeMapField(String fieldName, Map map, * values, such as {@link #writeJson(JsonSerializable)}, {@link JsonToken#NULL} will be written for that value. *

        * The field is only written when {@code value} isn't null, if a null field needs to be written use - * {@link #writeNullableField(String, Object, WriteValueCallback)}. + * {@link #writeNullableField(String, Object, IOExceptionCheckedBiConsumer)}. *

        - * Combines {@link #writeFieldName(String)} and {@link #writeMap(Map, WriteValueCallback, boolean)} to simplify + * Combines {@link #writeFieldName(String)} and {@link #writeMap(Map, IOExceptionCheckedBiConsumer, boolean)} to simplify * adding a key-value to a JSON object. * * @param fieldName The field name. @@ -815,7 +1001,7 @@ public final JsonWriter writeMapField(String fieldName, Map map, * or the key or value write. */ public JsonWriter writeMapField(String fieldName, Map map, - WriteValueCallback valueWriterFunc, boolean skipNullValues) throws IOException { + IOExceptionCheckedBiConsumer valueWriterFunc, boolean skipNullValues) throws IOException { Objects.requireNonNull(fieldName, "'fieldName' cannot be null."); Objects.requireNonNull(valueWriterFunc, "'valueWriterFunc' cannot be null."); @@ -833,7 +1019,7 @@ public JsonWriter writeMapField(String fieldName, Map map, * JSON object. *

        * The field is only written when {@code value} isn't null, if a null field needs to be written use - * {@link #writeNullableField(String, Object, WriteValueCallback)}. + * {@link #writeNullableField(String, Object, IOExceptionCheckedBiConsumer)}. * * @param fieldName The field name. * @param value Binary value to write. @@ -841,7 +1027,7 @@ public JsonWriter writeMapField(String fieldName, Map map, * @throws NullPointerException If {@code fieldName} is null. * @throws IOException If either the {@code fieldName} or binary {@code value} fails to be written. */ - public final JsonWriter writeBinaryField(String fieldName, byte[] value) throws IOException { + public JsonWriter writeBinaryField(String fieldName, byte[] value) throws IOException { Objects.requireNonNull(fieldName, "'fieldName' cannot be null."); if (value == null) { @@ -863,7 +1049,7 @@ public final JsonWriter writeBinaryField(String fieldName, byte[] value) throws * @throws NullPointerException If {@code fieldName} is null. * @throws IOException If either the {@code fieldName} or boolean {@code value} fails to be written. */ - public final JsonWriter writeBooleanField(String fieldName, boolean value) throws IOException { + public JsonWriter writeBooleanField(String fieldName, boolean value) throws IOException { Objects.requireNonNull(fieldName, "'fieldName' cannot be null."); return writeFieldName(fieldName).writeBoolean(value); @@ -876,7 +1062,7 @@ public final JsonWriter writeBooleanField(String fieldName, boolean value) throw * JSON object. *

        * The field is only written when {@code value} isn't null, if a null field needs to be written use - * {@link #writeNullableField(String, Object, WriteValueCallback)}. + * {@link #writeNullableField(String, Object, IOExceptionCheckedBiConsumer)}. * * @param fieldName The field name. * @param value Boolean value to write. @@ -884,7 +1070,7 @@ public final JsonWriter writeBooleanField(String fieldName, boolean value) throw * @throws NullPointerException If {@code fieldName} is null. * @throws IOException If either the {@code fieldName} or Boolean {@code value} fails to be written. */ - public final JsonWriter writeBooleanField(String fieldName, Boolean value) throws IOException { + public JsonWriter writeBooleanField(String fieldName, Boolean value) throws IOException { Objects.requireNonNull(fieldName, "'fieldName' cannot be null."); return (value == null) ? this : writeBooleanField(fieldName, value.booleanValue()); @@ -902,7 +1088,7 @@ public final JsonWriter writeBooleanField(String fieldName, Boolean value) throw * @throws NullPointerException If {@code fieldName} is null. * @throws IOException If either the {@code fieldName} or double {@code value} fails to be written. */ - public final JsonWriter writeDoubleField(String fieldName, double value) throws IOException { + public JsonWriter writeDoubleField(String fieldName, double value) throws IOException { Objects.requireNonNull(fieldName, "'fieldName' cannot be null."); return writeFieldName(fieldName).writeDouble(value); @@ -920,7 +1106,7 @@ public final JsonWriter writeDoubleField(String fieldName, double value) throws * @throws NullPointerException If {@code fieldName} is null. * @throws IOException If either the {@code fieldName} or float {@code value} fails to be written. */ - public final JsonWriter writeFloatField(String fieldName, float value) throws IOException { + public JsonWriter writeFloatField(String fieldName, float value) throws IOException { Objects.requireNonNull(fieldName, "'fieldName' cannot be null."); return writeFieldName(fieldName).writeFloat(value); @@ -938,7 +1124,7 @@ public final JsonWriter writeFloatField(String fieldName, float value) throws IO * @throws NullPointerException If {@code fieldName} is null. * @throws IOException If either the {@code fieldName} or int {@code value} fails to be written. */ - public final JsonWriter writeIntField(String fieldName, int value) throws IOException { + public JsonWriter writeIntField(String fieldName, int value) throws IOException { Objects.requireNonNull(fieldName, "'fieldName' cannot be null."); return writeFieldName(fieldName).writeInt(value); @@ -956,7 +1142,7 @@ public final JsonWriter writeIntField(String fieldName, int value) throws IOExce * @throws NullPointerException If {@code fieldName} is null. * @throws IOException If either the {@code fieldName} or long {@code value} fails to be written. */ - public final JsonWriter writeLongField(String fieldName, long value) throws IOException { + public JsonWriter writeLongField(String fieldName, long value) throws IOException { Objects.requireNonNull(fieldName, "'fieldName' cannot be null."); return writeFieldName(fieldName).writeLong(value); @@ -973,7 +1159,7 @@ public final JsonWriter writeLongField(String fieldName, long value) throws IOEx * @throws NullPointerException If {@code fieldName} is null. * @throws IOException If either the {@code fieldName} or JSON null fails to be written. */ - public final JsonWriter writeNullField(String fieldName) throws IOException { + public JsonWriter writeNullField(String fieldName) throws IOException { Objects.requireNonNull(fieldName, "'fieldName' cannot be null."); return writeFieldName(fieldName).writeNull(); @@ -986,7 +1172,7 @@ public final JsonWriter writeNullField(String fieldName) throws IOException { * JSON object. *

        * The field is only written when {@code value} isn't null, if a null field needs to be written use - * {@link #writeNullableField(String, Object, WriteValueCallback)}. + * {@link #writeNullableField(String, Object, IOExceptionCheckedBiConsumer)}. * * @param fieldName The field name. * @param value Number value to write. @@ -994,7 +1180,7 @@ public final JsonWriter writeNullField(String fieldName) throws IOException { * @throws NullPointerException If {@code fieldName} is null. * @throws IOException If either the {@code fieldName} or Number {@code value} fails to be written. */ - public final JsonWriter writeNumberField(String fieldName, Number value) throws IOException { + public JsonWriter writeNumberField(String fieldName, Number value) throws IOException { Objects.requireNonNull(fieldName, "'fieldName' cannot be null."); if (value == null) { return this; @@ -1010,7 +1196,7 @@ public final JsonWriter writeNumberField(String fieldName, Number value) throws * JSON object. *

        * The field is only written when {@code value} isn't null, if a null field needs to be written use - * {@link #writeNullableField(String, Object, WriteValueCallback)}. + * {@link #writeNullableField(String, Object, IOExceptionCheckedBiConsumer)}. * * @param fieldName The field name. * @param value String value to write. @@ -1018,7 +1204,7 @@ public final JsonWriter writeNumberField(String fieldName, Number value) throws * @throws NullPointerException If {@code fieldName} is null. * @throws IOException If either the {@code fieldName} or String {@code value} fails to be written. */ - public final JsonWriter writeStringField(String fieldName, String value) throws IOException { + public JsonWriter writeStringField(String fieldName, String value) throws IOException { Objects.requireNonNull(fieldName, "'fieldName' cannot be null."); if (value == null) { @@ -1044,7 +1230,7 @@ public final JsonWriter writeStringField(String fieldName, String value) throws * @throws NullPointerException If {@code fieldName} or {@code value} is null. * @throws IOException If either the {@code fieldName} or raw {@code value} fails to be written. */ - public final JsonWriter writeRawField(String fieldName, String value) throws IOException { + public JsonWriter writeRawField(String fieldName, String value) throws IOException { Objects.requireNonNull(fieldName, "'fieldName' cannot be null."); Objects.requireNonNull(value, "'value' cannot be null."); diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/ReadValueCallback.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/ReadValueCallback.java deleted file mode 100644 index 77a96b88ff92..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/ReadValueCallback.java +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.serialization.json; - -import java.io.IOException; - -/** - * A callback used when reading a JSON value, such as {@link JsonReader#readArray(ReadValueCallback)}. - * - * @param Input type of the callback. - * @param Output type of the callback. - * - * @see JsonReader - */ -@FunctionalInterface -public interface ReadValueCallback { - /** - * Applies the read callback to the {@code input}. - * - * @param input Input to the callback. - * @return The output of the callback. - * @throws IOException If an I/O error occurs during the callback. - */ - R read(T input) throws IOException; -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/WriteValueCallback.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/WriteValueCallback.java deleted file mode 100644 index c185df59927b..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/WriteValueCallback.java +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.serialization.json; - -import java.io.IOException; - -/** - * A callback used when writing a JSON value, such as {@link JsonWriter#writeArray(Object[], WriteValueCallback)}. - * - * @param First type of the callback. - * @param Second type of the callback. - * - * @see JsonWriter - */ -@FunctionalInterface -public interface WriteValueCallback { - /** - * Applies the write callback to {@code input1} and {@code input2}. - * - * @param input1 First type of the callback. - * @param input2 Second type of the callback. - * @throws IOException If an I/O error occurs during the callback. - */ - void write(T input1, U input2) throws IOException; -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/implementation/DefaultJsonProvider.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/implementation/DefaultJsonProvider.java deleted file mode 100644 index 4612181e3a35..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/implementation/DefaultJsonProvider.java +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.serialization.json.implementation; - -import io.clientcore.core.serialization.json.JsonOptions; -import io.clientcore.core.serialization.json.JsonProvider; -import io.clientcore.core.serialization.json.JsonReader; -import io.clientcore.core.serialization.json.JsonWriter; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; -import java.io.Writer; - -/** - * Default {@link JsonProvider} implementation. - */ -public final class DefaultJsonProvider implements JsonProvider { - private static final String JSON_READER_EXCEPTION - = "Both 'json' and 'options' must be passed as non-null to create an instance of JsonReader."; - - private static final String JSON_WRITER_EXCEPTION - = "Both 'json' and 'options' must be passed as non-null to create an instance of JsonWriter."; - - @Override - public JsonReader createReader(byte[] json, JsonOptions options) throws IOException { - validate(json, options, JSON_READER_EXCEPTION); - - return DefaultJsonReader.fromBytes(json, options); - } - - @Override - public JsonReader createReader(String json, JsonOptions options) throws IOException { - validate(json, options, JSON_READER_EXCEPTION); - - return DefaultJsonReader.fromString(json, options); - } - - @Override - public JsonReader createReader(InputStream json, JsonOptions options) throws IOException { - validate(json, options, JSON_READER_EXCEPTION); - - return DefaultJsonReader.fromStream(json, options); - } - - @Override - public JsonReader createReader(Reader json, JsonOptions options) throws IOException { - validate(json, options, JSON_READER_EXCEPTION); - - return DefaultJsonReader.fromReader(json, options); - } - - @Override - public JsonWriter createWriter(OutputStream json, JsonOptions options) throws IOException { - validate(json, options, JSON_WRITER_EXCEPTION); - - return DefaultJsonWriter.toStream(json, options); - } - - @Override - public JsonWriter createWriter(Writer json, JsonOptions options) throws IOException { - validate(json, options, JSON_WRITER_EXCEPTION); - - return DefaultJsonWriter.toWriter(json, options); - } - - private static void validate(Object json, JsonOptions options, String exceptionMessage) { - if (json == null || options == null) { - throw new NullPointerException(exceptionMessage); - } - } -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/implementation/DefaultJsonReader.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/implementation/DefaultJsonReader.java deleted file mode 100644 index 9ed8a1aed9f8..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/implementation/DefaultJsonReader.java +++ /dev/null @@ -1,252 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.serialization.json.implementation; - -import io.clientcore.core.serialization.json.JsonOptions; -import io.clientcore.core.serialization.json.JsonReader; -import io.clientcore.core.serialization.json.JsonToken; -import io.clientcore.core.serialization.json.JsonWriter; -import io.clientcore.core.serialization.json.implementation.jackson.core.JsonFactory; -import io.clientcore.core.serialization.json.implementation.jackson.core.JsonParser; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringReader; - -/** - * Default {@link JsonReader} implementation. - */ -public final class DefaultJsonReader extends JsonReader { - private static final JsonFactory FACTORY = new JsonFactory(); - - private final JsonParser parser; - private final Reader jsonReader; - private final boolean resetSupported; - private final boolean nonNumericNumbersSupported; - private final boolean jsoncSupported; - - private JsonToken currentToken; - - /** - * Constructs an instance of {@link JsonReader} from a {@code byte[]}. - * - * @param json JSON {@code byte[]}. - * @param options {@link JsonOptions} to configure the creation of the {@link JsonWriter}. - * @return An instance of {@link JsonReader}. - * @throws IOException If a {@link JsonReader} could not be constructed from the JSON {@code byte[]}. - */ - public static JsonReader fromBytes(byte[] json, JsonOptions options) throws IOException { - return fromStream(new ByteArrayInputStream(json), options); - } - - /** - * Constructs an instance of {@link JsonReader} from a String. - * - * @param json JSON String. - * @param options {@link JsonOptions} to configure the creation of the {@link JsonWriter}. - * @return An instance of {@link JsonReader}. - * @throws IOException If a {@link JsonReader} could not be constructed from the JSON String. - */ - public static JsonReader fromString(String json, JsonOptions options) throws IOException { - return fromReader(new StringReader(json), options); - } - - /** - * Constructs an instance of {@link JsonReader} from an {@link InputStream}. - * - * @param json JSON {@link InputStream}. - * @param options {@link JsonOptions} to configure the creation of the {@link JsonWriter}. - * @return An instance of {@link JsonReader}. - * @throws IOException If a {@link JsonReader} could not be constructed from the JSON {@link InputStream}. - */ - public static JsonReader fromStream(InputStream json, JsonOptions options) throws IOException { - return fromReader(new InputStreamReader(json), options); - } - - /** - * Constructs an instance of {@link DefaultJsonReader} from a {@link Reader}. - * - * @param reader JSON {@link Reader}. - * @param options {@link JsonOptions} to configure the creation of the {@link JsonWriter}. - * @return An instance of {@link DefaultJsonReader}. - * @throws IOException If a {@link DefaultJsonReader} could not be constructed from the JSON {@link Reader}. - */ - public static JsonReader fromReader(Reader reader, JsonOptions options) throws IOException { - return new DefaultJsonReader(FACTORY.createParser(reader), reader.markSupported(), reader, options); - } - - private DefaultJsonReader(JsonParser parser, boolean resetSupported, Reader jsonReader, JsonOptions options) { - this.parser = parser; - - if (options != null) { - this.parser.configure(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS, options.isNonNumericNumbersSupported()) - .configure(JsonParser.Feature.ALLOW_COMMENTS, options.isJsoncSupported()); - this.nonNumericNumbersSupported = options.isNonNumericNumbersSupported(); - this.jsoncSupported = options.isJsoncSupported(); - } else { - this.parser.configure(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS, true); - this.nonNumericNumbersSupported = true; - this.jsoncSupported = false; - } - this.resetSupported = resetSupported; - this.jsonReader = jsonReader; - } - - private DefaultJsonReader(JsonParser parser, boolean resetSupported, Reader jsonReader, - boolean nonNumericNumbersSupported, boolean jsoncSupported) { - this.parser = parser.configure(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS, nonNumericNumbersSupported) - .configure(JsonParser.Feature.ALLOW_COMMENTS, jsoncSupported); - this.resetSupported = resetSupported; - this.jsonReader = jsonReader; - this.nonNumericNumbersSupported = nonNumericNumbersSupported; - this.jsoncSupported = jsoncSupported; - } - - @Override - public JsonToken currentToken() { - return currentToken; - } - - @Override - public JsonToken nextToken() throws IOException { - currentToken = mapToken(parser.nextToken(), currentToken); - return currentToken; - } - - @Override - public byte[] getBinary() throws IOException { - if (currentToken() == JsonToken.NULL) { - return null; - } else { - return parser.getBinaryValue(); - } - } - - @Override - public boolean getBoolean() throws IOException { - return parser.getBooleanValue(); - } - - @Override - public double getDouble() throws IOException { - return parser.getDoubleValue(); - } - - @Override - public float getFloat() throws IOException { - return parser.getFloatValue(); - } - - @Override - public int getInt() throws IOException { - return parser.getIntValue(); - } - - @Override - public long getLong() throws IOException { - return parser.getLongValue(); - } - - @Override - public String getString() throws IOException { - return parser.getValueAsString(); - } - - @Override - public String getFieldName() throws IOException { - return parser.getCurrentName(); - } - - @Override - public void skipChildren() throws IOException { - parser.skipChildren(); - } - - @Override - public JsonReader bufferObject() throws IOException { - JsonToken currentToken = currentToken(); - if (currentToken == JsonToken.START_OBJECT || currentToken == JsonToken.FIELD_NAME) { - Reader jsonReader = new StringReader(readRemainingFieldsAsJsonObject()); - return new DefaultJsonReader(FACTORY.createParser(jsonReader), jsonReader.markSupported(), jsonReader, - nonNumericNumbersSupported, jsoncSupported); - } else { - throw new IllegalStateException("Cannot buffer a JSON object from a non-object, non-field name " - + "starting location. Starting location: " + currentToken()); - } - } - - @Override - public boolean isResetSupported() { - return resetSupported; - } - - @Override - public JsonReader reset() throws IOException { - if (!resetSupported) { - throw new IllegalStateException("'reset' isn't supported by this JsonReader."); - } - - jsonReader.reset(); - return new DefaultJsonReader(FACTORY.createParser(jsonReader), true, jsonReader, nonNumericNumbersSupported, - jsoncSupported); - } - - @Override - public void close() throws IOException { - parser.close(); - } - - /* - * Maps the Jackson Core JsonToken to the core JsonToken. - * - * core doesn't support the EMBEDDED_OBJECT or NOT_AVAILABLE Jackson Core JsonTokens, but those should only be - * returned by specialty implementations that aren't used. - */ - private static JsonToken mapToken( - io.clientcore.core.serialization.json.implementation.jackson.core.JsonToken nextToken, JsonToken currentToken) { - // Special case for when currentToken is called after instantiating the JsonReader. - if (nextToken == null && currentToken == null) { - return null; - } else if (nextToken == null) { - return JsonToken.END_DOCUMENT; - } - - switch (nextToken) { - case START_OBJECT: - return JsonToken.START_OBJECT; - - case END_OBJECT: - return JsonToken.END_OBJECT; - - case START_ARRAY: - return JsonToken.START_ARRAY; - - case END_ARRAY: - return JsonToken.END_ARRAY; - - case FIELD_NAME: - return JsonToken.FIELD_NAME; - - case VALUE_STRING: - return JsonToken.STRING; - - case VALUE_NUMBER_INT: - case VALUE_NUMBER_FLOAT: - return JsonToken.NUMBER; - - case VALUE_TRUE: - case VALUE_FALSE: - return JsonToken.BOOLEAN; - - case VALUE_NULL: - return JsonToken.NULL; - - default: - throw new IllegalStateException("Unsupported token type: '" + nextToken + "'."); - } - } -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/implementation/DefaultJsonWriter.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/implementation/DefaultJsonWriter.java deleted file mode 100644 index 95aef5d9b631..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/implementation/DefaultJsonWriter.java +++ /dev/null @@ -1,229 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.serialization.json.implementation; - -import io.clientcore.core.serialization.json.JsonOptions; -import io.clientcore.core.serialization.json.JsonToken; -import io.clientcore.core.serialization.json.JsonWriteContext; -import io.clientcore.core.serialization.json.JsonWriter; -import io.clientcore.core.serialization.json.implementation.jackson.core.JsonFactory; -import io.clientcore.core.serialization.json.implementation.jackson.core.JsonGenerator; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.util.Objects; - -/** - * Default {@link JsonWriter} implementation. - */ -public final class DefaultJsonWriter extends JsonWriter { - private static final JsonFactory FACTORY = new JsonFactory(); - - private final JsonGenerator generator; - - // Initial state is always root. - private JsonWriteContext context = JsonWriteContext.ROOT; - - /** - * Creates a {@link DefaultJsonWriter} that writes the given {@link OutputStream}. - *

        - * The passed {@link OutputStream} won't be closed when {@link #close()} is called as the {@link DefaultJsonWriter} - * isn't the owner of the stream. - * - * @param json The {@link OutputStream} that will be written. - * @param options {@link JsonOptions} to configure the creation of the {@link JsonWriter}. - * @return An instance of {@link DefaultJsonWriter}. - * @throws NullPointerException If {@code json} is null. - * @throws IOException If a {@link DefaultJsonWriter} could not be constructed from the {@link OutputStream}. - */ - public static JsonWriter toStream(OutputStream json, JsonOptions options) throws IOException { - Objects.requireNonNull(json, "'json' cannot be null."); - return new DefaultJsonWriter(FACTORY.createGenerator(new OutputStreamWriter(json)), options); - } - - /** - * Creates a {@link DefaultJsonWriter} that writes the given {@link Writer}. - *

        - * The passed {@link Writer} won't be closed when {@link #close()} is called as the {@link DefaultJsonWriter} isn't - * the owner of the stream. - * - * @param json The {@link Writer} that will be written. - * @param options {@link JsonOptions} to configure the creation of the {@link JsonWriter}. - * @return An instance of {@link DefaultJsonWriter}. - * @throws NullPointerException If {@code json} is null. - * @throws IOException If a {@link DefaultJsonWriter} could not be constructed from the {@link Writer}. - */ - public static JsonWriter toWriter(Writer json, JsonOptions options) throws IOException { - Objects.requireNonNull(json, "'json' cannot be null."); - return new DefaultJsonWriter(FACTORY.createGenerator(json), options); - } - - private DefaultJsonWriter(JsonGenerator generator, JsonOptions options) { - this.generator = generator; - if (options != null) { - this.generator.configure(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS, - options.isNonNumericNumbersSupported()); - } else { - this.generator.configure(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS, true); - } - } - - @Override - public JsonWriter flush() throws IOException { - generator.flush(); - return this; - } - - @Override - public JsonWriter writeStartObject() throws IOException { - context.validateToken(JsonToken.START_OBJECT); - generator.writeStartObject(); - - context = context.updateContext(JsonToken.START_OBJECT); - return this; - } - - @Override - public JsonWriter writeEndObject() throws IOException { - context.validateToken(JsonToken.END_OBJECT); - generator.writeEndObject(); - - context = context.updateContext(JsonToken.END_OBJECT); - return this; - } - - @Override - public JsonWriter writeStartArray() throws IOException { - context.validateToken(JsonToken.START_ARRAY); - generator.writeStartArray(); - - context = context.updateContext(JsonToken.START_ARRAY); - return this; - } - - @Override - public JsonWriter writeEndArray() throws IOException { - context.validateToken(JsonToken.END_ARRAY); - generator.writeEndArray(); - - context = context.updateContext(JsonToken.END_ARRAY); - return this; - } - - @Override - public JsonWriter writeFieldName(String fieldName) throws IOException { - Objects.requireNonNull(fieldName, "'fieldName' cannot be null."); - - context.validateToken(JsonToken.FIELD_NAME); - generator.writeFieldName(fieldName); - - context = context.updateContext(JsonToken.FIELD_NAME); - return this; - } - - @Override - public JsonWriter writeBinary(byte[] value) throws IOException { - context.validateToken(JsonToken.STRING); - if (value == null) { - generator.writeNull(); - } else { - generator.writeBinary(value); - } - - context = context.updateContext(JsonToken.STRING); - return this; - } - - @Override - public JsonWriter writeBoolean(boolean value) throws IOException { - context.validateToken(JsonToken.BOOLEAN); - generator.writeBoolean(value); - - context = context.updateContext(JsonToken.BOOLEAN); - return this; - } - - @Override - public JsonWriter writeDouble(double value) throws IOException { - context.validateToken(JsonToken.NUMBER); - generator.writeNumber(value); - - context = context.updateContext(JsonToken.NUMBER); - return this; - } - - @Override - public JsonWriter writeFloat(float value) throws IOException { - context.validateToken(JsonToken.NUMBER); - generator.writeNumber(value); - - context = context.updateContext(JsonToken.NUMBER); - return this; - } - - @Override - public JsonWriter writeInt(int value) throws IOException { - context.validateToken(JsonToken.NUMBER); - generator.writeNumber(value); - - context = context.updateContext(JsonToken.NUMBER); - return this; - } - - @Override - public JsonWriter writeLong(long value) throws IOException { - context.validateToken(JsonToken.NUMBER); - generator.writeNumber(value); - - context = context.updateContext(JsonToken.NUMBER); - return this; - } - - @Override - public JsonWriter writeNull() throws IOException { - context.validateToken(JsonToken.NULL); - generator.writeNull(); - - context = context.updateContext(JsonToken.NULL); - return this; - } - - @Override - public JsonWriter writeString(String value) throws IOException { - context.validateToken(JsonToken.STRING); - generator.writeString(value); - - context = context.updateContext(JsonToken.STRING); - return this; - } - - @Override - public JsonWriter writeRawValue(String value) throws IOException { - Objects.requireNonNull(value, "'value' cannot be null."); - - context.validateToken(JsonToken.STRING); - generator.writeRawValue(value); - - context = context.updateContext(JsonToken.STRING); - return this; - } - - @Override - public JsonWriteContext getWriteContext() { - return context; - } - - @Override - public void close() throws IOException { - if (context != JsonWriteContext.COMPLETED) { - throw new IllegalStateException("Writing of the JSON object must be completed before the writer can be " - + "closed. Current writing state is '" + context.getWriteState() + "'."); - } - - generator.flush(); - generator.close(); - } -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/implementation/JsonUtils.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/implementation/JsonUtils.java new file mode 100644 index 000000000000..028b2bd3c0e4 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/implementation/JsonUtils.java @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.serialization.json.implementation; + +import java.math.BigDecimal; +import java.math.BigInteger; + +/** + * Utility class containing helper methods for serialization. + */ +public final class JsonUtils { + /** + * Parses a number from a string. + *

        + * Callers to this method should ensure that the number string isn't null or empty before calling this method. + *

        + * For integer numbers, this method will return the smallest number type that can represent the number. Where + * {@link Integer} is preferred over {@link Long} and {@link Long} is preferred over {@link BigInteger}. + *

        + * For floating point numbers, {@link Double} will be preferred but {@link BigDecimal} will be used if the number + * is too large to fit in a {@link Double}. + *

        + * Unlike the JSON specification, this method will handle the special floating point representations + * ({@code NaN}, {@code Infinity}, etc) and will return a {@link Double} for those values. + * + * @param numberString The string representation of the number. + * @return The number represented by the string. + * @throws NumberFormatException If the string is not a valid number. + */ + public static Number parseNumber(String numberString) { + int length = numberString.length(); + + // Use the length of the number and checks for special values to determine if the number is a special + // floating point representation. + // The special floating point representations are: NaN, Infinity, +Infinity, and -Infinity. + // These will be returned using Double. + if (length == 3 && "NaN".equals(numberString)) { + return Double.NaN; + } else if (length == 8 && "Infinity".equals(numberString)) { + return Double.POSITIVE_INFINITY; + } else if (length == 9) { + if ("+Infinity".equals(numberString)) { + return Double.POSITIVE_INFINITY; + } else if ("-Infinity".equals(numberString)) { + return Double.NEGATIVE_INFINITY; + } + } + + boolean floatingPoint = false; + for (int i = 0; i < length; i++) { + char c = numberString.charAt(i); + if (c == '.' || c == 'e' || c == 'E') { + floatingPoint = true; + break; + } + } + + return floatingPoint ? handleFloatingPoint(numberString) : handleInteger(numberString); + } + + private static Number handleFloatingPoint(String value) { + // Floating point parsing will return Infinity if the String value is larger than what can be contained by + // the numeric type. Check if the String contains the Infinity representation to know when to scale up the + // numeric type. + // Additionally, due to the handling of values that can't fit into the numeric type, the only time floating + // point parsing will throw is when the string value is invalid. + double d = Double.parseDouble(value); + if (!Double.isInfinite(d)) { + return d; + } + + return new BigDecimal(value); + } + + private static Number handleInteger(String value) { + try { + return Integer.parseInt(value); + } catch (NumberFormatException failedInteger) { + try { + return Long.parseLong(value); + } catch (NumberFormatException failedLong) { + failedLong.addSuppressed(failedInteger); + try { + return new BigInteger(value); + } catch (NumberFormatException failedBigDecimal) { + failedBigDecimal.addSuppressed(failedLong); + throw failedBigDecimal; + } + } + } + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/implementation/jackson/core/JsonParser.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/implementation/jackson/core/JsonParser.java index b645df30fd0b..02bb7205c40b 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/implementation/jackson/core/JsonParser.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/implementation/jackson/core/JsonParser.java @@ -56,8 +56,8 @@ public enum Feature { * (see section 3.2.4.1, Lexical Representation) * allows (tokens are quoted contents, not including quotes): *

          - *
        • "INF" (for positive infinity), as well as alias of "Infinity" - *
        • "-INF" (for negative infinity), alias "-Infinity" + *
        • "Infinity" (for positive infinity) + *
        • "-Infinity" (for negative infinity) *
        • "NaN" (for other not-a-numbers, like result of division by zero) *
        *

        diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/implementation/jackson/core/base/ParserMinimalBase.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/implementation/jackson/core/base/ParserMinimalBase.java index 8ad3f909cb40..baef182e5dc4 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/implementation/jackson/core/base/ParserMinimalBase.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/implementation/jackson/core/base/ParserMinimalBase.java @@ -1113,7 +1113,7 @@ protected void _throwUnquotedSpace(int i, String ctxtDesc) throws JsonParseExcep */ protected String _validJsonValueList() { if (Feature.ALLOW_NON_NUMERIC_NUMBERS.enabledIn(_features)) { - return "(JSON String, Number (or 'NaN'/'INF'/'+INF'), Array, Object or token 'null', 'true' or 'false')"; + return "(JSON String, Number (or 'NaN'/'Infinity'/'+Infinity'/'-Infinity'), Array, Object or token 'null', 'true' or 'false')"; } return "(JSON String, Number, Array, Object or token 'null', 'true' or 'false')"; } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/implementation/jackson/core/json/ReaderBasedJsonParser.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/implementation/jackson/core/json/ReaderBasedJsonParser.java index a61702b92393..72561049bea6 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/implementation/jackson/core/json/ReaderBasedJsonParser.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/implementation/jackson/core/json/ReaderBasedJsonParser.java @@ -792,15 +792,7 @@ protected JsonToken _handleInvalidNumberStart(int ch, boolean negative) throws I } } ch = _inputBuffer[_inputPtr++]; - if (ch == 'N') { - String match = negative ? "-INF" : "+INF"; - _matchToken(match, 3); - if (Feature.ALLOW_NON_NUMERIC_NUMBERS.enabledIn(_features)) { - return resetAsNaN(match, negative ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY); - } - _reportError( - "Non-standard token '" + match + "': enable JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS to allow"); - } else if (ch == 'n') { + if (ch == 'n') { String match = negative ? "-Infinity" : "+Infinity"; _matchToken(match, 3); if (Feature.ALLOW_NON_NUMERIC_NUMBERS.enabledIn(_features)) { diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonArray.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonArray.java index e6dbdaf6c1e4..1b30689070a5 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonArray.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonArray.java @@ -3,7 +3,8 @@ package io.clientcore.core.serialization.json.models; -import io.clientcore.core.serialization.json.JsonProviders; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; import io.clientcore.core.serialization.json.JsonReader; import io.clientcore.core.serialization.json.JsonToken; import io.clientcore.core.serialization.json.JsonWriter; @@ -17,6 +18,7 @@ /** * Model representing a JSON array. */ +@Metadata(properties = MetadataProperties.FLUENT) public final class JsonArray extends JsonElement { private final List elements; @@ -290,7 +292,7 @@ public static JsonArray fromJson(JsonReader jsonReader) throws IOException { public String toJsonString() throws IOException { // TODO (alzimmer): This could be cached and reset each time the array is mutated. StringBuilderWriter writer = new StringBuilderWriter(); - try (JsonWriter jsonWriter = JsonProviders.createWriter(writer)) { + try (JsonWriter jsonWriter = JsonWriter.toWriter(writer)) { toJson(jsonWriter).flush(); return writer.toString(); } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonBoolean.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonBoolean.java index ac3338f73967..cbb1b01b5b21 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonBoolean.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonBoolean.java @@ -3,6 +3,8 @@ package io.clientcore.core.serialization.json.models; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; import io.clientcore.core.serialization.json.JsonReader; import io.clientcore.core.serialization.json.JsonToken; import io.clientcore.core.serialization.json.JsonWriter; @@ -12,6 +14,7 @@ /** * Model representing a JSON boolean value. */ +@Metadata(properties = MetadataProperties.IMMUTABLE) public final class JsonBoolean extends JsonElement { private static final JsonBoolean TRUE = new JsonBoolean(true); private static final JsonBoolean FALSE = new JsonBoolean(false); diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonElement.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonElement.java index 32cb975c1e64..a54673566758 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonElement.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonElement.java @@ -42,7 +42,7 @@ public JsonElement() { * @throws IOException If an error occurs while deserializing the JSON element. * @throws IllegalStateException If the current token is not a valid JSON token. */ - static JsonElement fromJson(JsonReader jsonReader) throws IOException { + public static JsonElement fromJson(JsonReader jsonReader) throws IOException { JsonToken token = jsonReader.currentToken(); if (token == null) { token = jsonReader.nextToken(); diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonNull.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonNull.java index 2a28b447da5a..6d245444c663 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonNull.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonNull.java @@ -3,6 +3,8 @@ package io.clientcore.core.serialization.json.models; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; import io.clientcore.core.serialization.json.JsonReader; import io.clientcore.core.serialization.json.JsonToken; import io.clientcore.core.serialization.json.JsonWriter; @@ -12,6 +14,7 @@ /** * Model representing a JSON null value. */ +@Metadata(properties = MetadataProperties.IMMUTABLE) public final class JsonNull extends JsonElement { private static final JsonNull INSTANCE = new JsonNull(); diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonNumber.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonNumber.java index 050184c4b42e..7f72cd56d395 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonNumber.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonNumber.java @@ -3,10 +3,13 @@ package io.clientcore.core.serialization.json.models; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; import io.clientcore.core.serialization.json.JsonReader; import io.clientcore.core.serialization.json.JsonToken; import io.clientcore.core.serialization.json.JsonWriter; import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.serialization.json.implementation.JsonUtils; import java.io.IOException; import java.math.BigDecimal; @@ -16,6 +19,7 @@ /** * Class representing the JSON number type */ +@Metadata(properties = MetadataProperties.IMMUTABLE) public final class JsonNumber extends JsonElement { private static final ClientLogger LOGGER = new ClientLogger(JsonNumber.class); @@ -32,76 +36,20 @@ public final class JsonNumber extends JsonElement { * ({@code .}) or an exponent ({@code e} or {@code E}), the string will be parsed as a floating point number, * otherwise it will be parsed as an integer. *

        - * Parsing attempts to use the smallest container that can represent the number. For floating points it'll attempt - * to use {@link Float#parseFloat(String)}, if that fails it'll use {@link Double#parseDouble(String)}, and finally - * if that fails it'll use {@link BigDecimal#BigDecimal(String)}. For integers it'll attempt to use - * {@link Integer#parseInt(String)}, if that fails it'll use {@link Long#parseLong(String)}, and finally if that - * fails it'll use {@link BigInteger#BigInteger(String)}. + * For integer numbers, this method will return the smallest number type that can represent the number. Where + * {@link Integer} is preferred over {@link Long} and {@link Long} is preferred over {@link BigInteger}. + *

        + * For floating point numbers, {@link Double} will be preferred but {@link BigDecimal} will be used if the number + * is too large to fit in a {@link Double}. *

        * If the string is one of the special floating point representations ({@code NaN}, {@code Infinity}, etc), then - * the value will be represented using {@link Float}. + * the value will be represented using {@link Double}. * * @param value The string-based numeric value the JsonNumber will represent. * @throws NumberFormatException If the string is not a valid number. */ JsonNumber(String value) throws IllegalArgumentException { - int length = value.length(); - boolean floatingPoint = false; - boolean infinity = value.contains("Infinity"); - if (infinity) { - // Use Double.parseDouble to handle Infinity. - this.value = Double.parseDouble(value); - return; - } - - for (int i = 0; i < length; i++) { - char c = value.charAt(i); - if (c == '.' || c == 'e' || c == 'E') { - floatingPoint = true; - break; - } - } - - this.value = floatingPoint ? handleFloatingPoint(value) : handleInteger(value); - } - - private static Number handleFloatingPoint(String value) { - // Floating point parsing will return Infinity if the String value is larger than what can be contained by - // the numeric type. Check if the String contains the Infinity representation to know when to scale up the - // numeric type. - // Additionally, due to the handling of values that can't fit into the numeric type, the only time floating - // point parsing will throw is when the string value is invalid. - float f = Float.parseFloat(value); - - // If the float wasn't infinite, return it. - if (!Float.isInfinite(f)) { - return f; - } - - double d = Double.parseDouble(value); - if (!Double.isInfinite(d)) { - return d; - } - - return new BigDecimal(value); - } - - private static Number handleInteger(String value) { - try { - return Integer.parseInt(value); - } catch (NumberFormatException failedInteger) { - try { - return Long.parseLong(value); - } catch (NumberFormatException failedLong) { - failedLong.addSuppressed(failedInteger); - try { - return new BigInteger(value); - } catch (NumberFormatException failedBigDecimal) { - failedBigDecimal.addSuppressed(failedLong); - throw LOGGER.logThrowableAsError(failedBigDecimal); - } - } - } + this.value = JsonUtils.parseNumber(value); } /** @@ -150,9 +98,14 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * {@link IllegalStateException} will be thrown. Otherwise, a JSON number representing the numeric value will be * created and returned. *

        - * The {@link JsonNumber} returned will have a {@link JsonNumber#getValue()} that is the smallest type that can - * represent the numeric value. Numeric types used are {@link Integer}, {@link Long}, {@link BigInteger}, - * {@link Float}, {@link Double}, and {@link BigDecimal}. + * For integer numbers, this method will return the smallest number type that can represent the number. Where + * {@link Integer} is preferred over {@link Long} and {@link Long} is preferred over {@link BigInteger}. + *

        + * For floating point numbers, {@link Double} will be preferred but {@link BigDecimal} will be used if the number + * is too large to fit in a {@link Double}. + *

        + * If the string is one of the special floating point representations ({@code NaN}, {@code Infinity}, etc), then + * the value will be represented using {@link Double}. * * @param jsonReader The JsonReader to deserialize from. * @return The deserialized JSON number. diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonObject.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonObject.java index 359a35061403..ab8cb9dd3983 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonObject.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonObject.java @@ -3,7 +3,8 @@ package io.clientcore.core.serialization.json.models; -import io.clientcore.core.serialization.json.JsonProviders; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; import io.clientcore.core.serialization.json.JsonReader; import io.clientcore.core.serialization.json.JsonToken; import io.clientcore.core.serialization.json.JsonWriter; @@ -17,6 +18,7 @@ /** * Class representing the JSON object type. */ +@Metadata(properties = MetadataProperties.FLUENT) public final class JsonObject extends JsonElement { private final Map properties; @@ -172,7 +174,7 @@ public static JsonObject fromJson(JsonReader jsonReader) throws IOException { public String toJsonString() throws IOException { // TODO (alzimmer): This could be cached and reset each time the array is mutated. StringBuilderWriter writer = new StringBuilderWriter(); - try (JsonWriter jsonWriter = JsonProviders.createWriter(writer)) { + try (JsonWriter jsonWriter = JsonWriter.toWriter(writer)) { toJson(jsonWriter).flush(); return writer.toString(); } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonPatchDocument.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonPatchDocument.java new file mode 100644 index 000000000000..970b64752ae9 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonPatchDocument.java @@ -0,0 +1,522 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.serialization.json.models; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.serialization.json.JsonSerializer; +import io.clientcore.core.implementation.utils.Option; +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonSerializable; +import io.clientcore.core.serialization.json.JsonWriter; +import io.clientcore.core.utils.CoreUtils; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + *

        Represents a JSON Patch document.

        + * + *

        This class encapsulates a list of {@link JsonPatchOperation} instances that form a JSON Patch document. + * It provides methods to add various types of operations (add, replace, copy, move, remove, test) to the document.

        + * + *

        Each operation in the document is represented by a {@link JsonPatchOperation} instance, which encapsulates the + * operation kind, path, and optional from and value.

        + * + *

        This class is useful when you want to create a JSON Patch document to express a sequence of operations to + * apply to a JSON document.

        + * + * @see JsonPatchOperation + * @see JsonPatchOperationKind + */ +@Metadata(properties = MetadataProperties.FLUENT) +public final class JsonPatchDocument implements JsonSerializable { + private final JsonSerializer serializer; + private final List operations; + + /** + * Creates a new JSON Patch document. + */ + public JsonPatchDocument() { + this(null); + } + + /** + * Creates a new JSON Patch document. + * + * @param serializer The {@link JsonSerializer} that will be used to serialize patch operation values. + * @throws NullPointerException If {@code serializer} is null. + */ + public JsonPatchDocument(JsonSerializer serializer) { + this.operations = new ArrayList<>(); + this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null."); + } + + /** + * Gets a representation of the {@link JsonPatchOperation JSON patch operations} in this JSON patch document. + *

        + * Modifications to the returned list won't mutate the operations in the document. + * + * @return The JSON patch operations in this JSON patch document. + */ + List getOperations() { + return new ArrayList<>(operations); + } + + /** + * Appends an "add" operation to this JSON Patch document. + *

        + * If the {@code path} doesn't exist a new member is added to the object. If the {@code path} does exist the + * previous value is replaced. If the {@code path} specifies an array index the value is inserted at the specified. + *

        + * See JSON Patch Add for more information. + * + *

        Code Samples

        + * + * + *
        +     * /*
        +     *  * Add an object member to the JSON document { "foo" : "bar" } to get the JSON document
        +     *  * { "bar": "foo", "foo": "bar" }.
        +     *  */
        +     * jsonPatchDocument.appendAdd("/bar", "foo");
        +     *
        +     * /*
        +     *  * Add an array element to the JSON document { "foo": [ "fizz", "fizzbuzz" ] } to get the JSON document
        +     *  * { "foo": [ "fizz", "buzz", "fizzbuzz" ] }.
        +     *  */
        +     * jsonPatchDocument.appendAdd("/foo/1", "buzz");
        +     *
        +     * /*
        +     *  * Add a nested member to the JSON document { "foo": "bar" } to get the JSON document
        +     *  * { "foo": "bar", "child": { "grandchild": { } } }.
        +     *  */
        +     * jsonPatchDocument.appendAdd("/child", Collections.singletonMap("grandchild", Collections.emptyMap()));
        +     *
        +     * /*
        +     *  * Add an array element to the JSON document { "foo": [ "fizz", "buzz" ] } to get the JSON document
        +     *  * { "foo": [ "fizz", "buzz", "fizzbuzz" ] }.
        +     *  */
        +     * jsonPatchDocument.appendAdd("/foo/-", "fizzbuzz");
        +     * 
        + * + * + * @param path The path to apply the addition. + * @param value The value that will be serialized and added to the path. + * @return The updated JsonPatchDocument object. + * @throws NullPointerException If {@code path} is null. + * @throws IOException If an error occurred while the value was being serialized. + */ + public JsonPatchDocument appendAdd(String path, Object value) throws IOException { + return appendAddInternal(path, serializeValue(value)); + } + + /** + * Appends an "add" operation to this JSON Patch document. + *

        + * If the {@code path} doesn't exist a new member is added to the object. If the {@code path} does exist the + * previous value is replaced. If the {@code path} specifies an array index the value is inserted at the specified. + *

        + * See JSON Patch Add for more information. + * + *

        Code Samples

        + * + * + *
        +     * /*
        +     *  * Add an object member to the JSON document { "foo" : "bar" } to get the JSON document
        +     *  * { "bar": "foo", "foo": "bar" }.
        +     *  */
        +     * jsonPatchDocument.appendAddRaw("/bar", "\"foo\"");
        +     *
        +     * /*
        +     *  * Add an array element to the JSON document { "foo": [ "fizz", "fizzbuzz" ] } to get the JSON document
        +     *  * { "foo": [ "fizz", "buzz", "fizzbuzz" ] }.
        +     *  */
        +     * jsonPatchDocument.appendAddRaw("/foo/1", "\"buzz\"");
        +     *
        +     * /*
        +     *  * Add a nested member to the JSON document { "foo": "bar" } to get the JSON document
        +     *  * { "foo": "bar", "child": { "grandchild": { } } }.
        +     *  */
        +     * jsonPatchDocument.appendAddRaw("/child", "\"child\": { \"grandchild\": { } }");
        +     *
        +     * /*
        +     *  * Add an array element to the JSON document { "foo": [ "fizz", "buzz" ] } to get the JSON document
        +     *  * { "foo": [ "fizz", "buzz", "fizzbuzz" ] }.
        +     *  */
        +     * jsonPatchDocument.appendAddRaw("/foo/-", "\"fizzbuzz\"");
        +     * 
        + * + * + * @param path The path to apply the addition. + * @param rawJson The raw JSON value that will be added to the path. + * @return The updated JsonPatchDocument object. + * @throws NullPointerException If {@code path} is null. + */ + public JsonPatchDocument appendAddRaw(String path, String rawJson) { + return appendAddInternal(path, Option.of(rawJson)); + } + + private JsonPatchDocument appendAddInternal(String path, Option rawJsonOption) { + Objects.requireNonNull(path, "'path' cannot be null."); + + return appendOperation(JsonPatchOperationKind.ADD, null, path, rawJsonOption); + } + + /** + * Appends a "replace" operation to this JSON Patch document. + *

        + * See JSON Patch replace for more information. + * + *

        Code Samples

        + * + * + *
        +     * /*
        +     *  * Replace an object member in the JSON document { "bar": "qux", "foo": "bar" } to get the JSON document
        +     *  * { "bar": "foo", "foo": "bar" }.
        +     *  */
        +     * jsonPatchDocument.appendReplace("/bar", "foo");
        +     *
        +     * /*
        +     *  * Replace an object member in the JSON document { "foo": "fizz" } to get the JSON document
        +     *  * { "foo": [ "fizz", "buzz", "fizzbuzz" ]  }.
        +     *  */
        +     * jsonPatchDocument.appendReplace("/foo", new String[] {"fizz", "buzz", "fizzbuzz"});
        +     *
        +     * /*
        +     *  * Given the JSON document { "foo": "bar" } the following is an example of an invalid replace operation as the
        +     *  * target path doesn't exist in the document.
        +     *  */
        +     * jsonPatchDocument.appendReplace("/baz", "foo");
        +     * 
        + * + * + * @param path The path to replace. + * @param value The value will be serialized and used as the replacement. + * @return The updated JsonPatchDocument object. + * @throws NullPointerException If {@code path} is null. + * @throws IOException If an error occurred while the value was being serialized. + */ + public JsonPatchDocument appendReplace(String path, Object value) throws IOException { + return appendReplaceInternal(path, serializeValue(value)); + } + + /** + * Appends a "replace" operation to this JSON Patch document. + *

        + * See JSON Patch replace for more information. + * + *

        Code Samples

        + * + * + *
        +     * /*
        +     *  * Replace an object member in the JSON document { "bar": "qux", "foo": "bar" } to get the JSON document
        +     *  * { "bar": "foo", "foo": "bar" }.
        +     *  */
        +     * jsonPatchDocument.appendReplaceRaw("/bar", "\"foo\"");
        +     *
        +     * /*
        +     *  * Replace an object member in the JSON document { "foo": "fizz" } to get the JSON document
        +     *  * { "foo": [ "fizz", "buzz", "fizzbuzz" ]  }.
        +     *  */
        +     * jsonPatchDocument.appendReplaceRaw("/foo", "[ \"fizz\", \"buzz\", \"fizzbuzz\" ]");
        +     *
        +     * /*
        +     *  * Given the JSON document { "foo": "bar" } the following is an example of an invalid replace operation as the
        +     *  * target path doesn't exist in the document.
        +     *  */
        +     * jsonPatchDocument.appendReplaceRaw("/baz", "\"foo\"");
        +     * 
        + * + * + * @param path The path to replace. + * @param rawJson The raw JSON value that will be used as the replacement. + * @return The updated JsonPatchDocument object. + * @throws NullPointerException If {@code path} is null. + */ + public JsonPatchDocument appendReplaceRaw(String path, String rawJson) { + return appendReplaceInternal(path, Option.of(rawJson)); + } + + private JsonPatchDocument appendReplaceInternal(String path, Option rawJsonOption) { + Objects.requireNonNull(path, "'path' cannot be null."); + + return appendOperation(JsonPatchOperationKind.REPLACE, null, path, rawJsonOption); + } + + /** + * Appends a "copy" operation to this JSON Patch document. + *

        + * See JSON Patch copy for more information. + * + *

        Code Samples

        + * + * + *
        +     * /*
        +     *  * Copy an object member in the JSON document { "foo": "bar" } to get the JSON document
        +     *  * { "foo": "bar", "copy": "bar" }.
        +     *  */
        +     * jsonPatchDocument.appendCopy("/foo", "/copy");
        +     *
        +     * /*
        +     *  * Copy an object member in the JSON document { "foo": { "bar": "baz" } } to get the JSON document
        +     *  * { "foo": { "bar": "baz" }, "bar": "baz" }.
        +     *  */
        +     * jsonPatchDocument.appendCopy("/foo/bar", "/bar");
        +     *
        +     * /*
        +     *  * Given the JSON document { "foo": "bar" } the following is an example of an invalid copy operation as the
        +     *  * target from doesn't exist in the document.
        +     *  */
        +     * jsonPatchDocument.appendCopy("/baz", "/fizz");
        +     * 
        + * + * + * @param from The path to copy from. + * @param path The path to copy to. + * @return The updated JsonPatchDocument object. + * @throws NullPointerException If {@code from} or {@code path} is null. + */ + public JsonPatchDocument appendCopy(String from, String path) { + Objects.requireNonNull(from, "'from' cannot be null."); + Objects.requireNonNull(path, "'path' cannot be null."); + + return appendOperation(JsonPatchOperationKind.COPY, from, path, Option.uninitialized()); + } + + /** + * Appends a "move" operation to this JSON Patch document. + *

        + * For the operation to be successful {@code path} cannot be a child node of {@code from}. + *

        + * See JSON Patch move for more information. + * + *

        Code Samples

        + * + * + *
        +     * /*
        +     *  * Move an object member in the JSON document { "foo": "bar", "bar": "foo" } to get the JSON document
        +     *  * { "bar": "bar" }.
        +     *  */
        +     * jsonPatchDocument.appendMove("/foo", "/bar");
        +     *
        +     * /*
        +     *  * Move an object member in the JSON document { "foo": { "bar": "baz" } } to get the JSON document
        +     *  * { "foo": "baz" }.
        +     *  */
        +     * jsonPatchDocument.appendMove("/foo/bar", "/foo");
        +     *
        +     * /*
        +     *  * Given the JSON document { "foo": { "bar": "baz" } } the following is an example of an invalid move operation
        +     *  * as the target path is a child of the target from.
        +     *  */
        +     * jsonPatchDocument.appendMove("/foo", "/foo/bar");
        +     *
        +     * /*
        +     *  * Given the JSON document { "foo": "bar" } the following is an example of an invalid move operation as the
        +     *  * target from doesn't exist in the document.
        +     *  */
        +     * jsonPatchDocument.appendMove("/baz", "/fizz");
        +     * 
        + * + * + * @param from The path to move from. + * @param path The path to move to. + * @return The updated JsonPatchDocument object. + * @throws NullPointerException If {@code from} or {@code path} is null. + */ + public JsonPatchDocument appendMove(String from, String path) { + Objects.requireNonNull(from, "'from' cannot be null."); + Objects.requireNonNull(path, "'path' cannot be null."); + + return appendOperation(JsonPatchOperationKind.MOVE, from, path, Option.uninitialized()); + } + + /** + * Appends a "remove" operation to this JSON Patch document. + *

        + * See JSON Patch remove for more information. + * + *

        Code Samples

        + * + * + *
        +     * /*
        +     *  * Remove an object member in the JSON document { "foo": "bar", "bar": "foo" } to get the JSON document
        +     *  * { "foo": "bar" }.
        +     *  */
        +     * jsonPatchDocument.appendRemove("/bar");
        +     *
        +     * /*
        +     *  * Remove an object member in the JSON document { "foo": { "bar": "baz" } } to get the JSON document
        +     *  * { "foo": { } }.
        +     *  */
        +     * jsonPatchDocument.appendRemove("/foo/bar");
        +     *
        +     * /*
        +     *  * Given the JSON document { "foo": "bar" } the following is an example of an invalid remove operation as the
        +     *  * target from doesn't exist in the document.
        +     *  */
        +     * jsonPatchDocument.appendRemove("/baz");
        +     * 
        + * + * + * @param path The path to remove. + * @return The updated JsonPatchDocument object. + * @throws NullPointerException If {@code path} is null. + */ + public JsonPatchDocument appendRemove(String path) { + Objects.requireNonNull(path, "'path' cannot be null."); + + return appendOperation(JsonPatchOperationKind.REMOVE, null, path, Option.uninitialized()); + } + + /** + * Appends a "test" operation to this JSON Patch document. + *

        + * See JSON Patch test for more information. + * + *

        Code Samples

        + * + * + *
        +     * /*
        +     *  * Test an object member in the JSON document { "foo": "bar" } to get a successful operation.
        +     *  */
        +     * jsonPatchDocument.appendTest("/foo", "bar");
        +     *
        +     * /*
        +     *  * Test an object member in the JSON document { "foo": "bar" } to get a unsuccessful operation.
        +     *  */
        +     * jsonPatchDocument.appendTest("/foo", 42);
        +     *
        +     * /*
        +     *  * Given the JSON document { "foo": "bar" } the following is an example of an unsuccessful test operation as
        +     *  * the target path doesn't exist in the document.
        +     *  */
        +     * jsonPatchDocument.appendTest("/baz", "bar");
        +     * 
        + * + * + * @param path The path to test. + * @param value The value that will be serialized and used to test against. + * @return The updated JsonPatchDocument object. + * @throws NullPointerException If {@code path} is null. + * @throws IOException If an error occurred while the value was being serialized. + */ + public JsonPatchDocument appendTest(String path, Object value) throws IOException { + return appendTestInternal(path, serializeValue(value)); + } + + /** + * Appends a "test" operation to this JSON Patch document. + *

        + * See JSON Patch test for more information. + * + *

        Code Samples

        + * + * + *
        +     * /*
        +     *  * Test an object member in the JSON document { "foo": "bar" } to get a successful operation.
        +     *  */
        +     * jsonPatchDocument.appendTestRaw("/foo", "\"bar\"");
        +     *
        +     * /*
        +     *  * Test an object member in the JSON document { "foo": "bar" } to get a unsuccessful operation.
        +     *  */
        +     * jsonPatchDocument.appendTestRaw("/foo", "42");
        +     *
        +     * /*
        +     *  * Given the JSON document { "foo": "bar" } the following is an example of an unsuccessful test operation as
        +     *  * the target path doesn't exist in the document.
        +     *  */
        +     * jsonPatchDocument.appendTestRaw("/baz", "\"bar\"");
        +     * 
        + * + * + * @param path The path to test. + * @param rawJson The raw JSON value that will be used to test against. + * @return The updated JsonPatchDocument object. + * @throws NullPointerException If {@code path} is null. + */ + public JsonPatchDocument appendTestRaw(String path, String rawJson) { + return appendTestInternal(path, Option.of(rawJson)); + } + + private JsonPatchDocument appendTestInternal(String path, Option rawJsonOption) { + Objects.requireNonNull(path, "'path' cannot be null."); + + return appendOperation(JsonPatchOperationKind.TEST, null, path, rawJsonOption); + } + + private Option serializeValue(Object value) throws IOException { + if (value == null) { + return Option.empty(); + } + + byte[] bytes = serializer.serializeToBytes(value); + + return Option.of(new String(bytes, StandardCharsets.UTF_8)); + } + + private JsonPatchDocument appendOperation(JsonPatchOperationKind operationKind, String from, String path, + Option optionalValue) { + operations.add(new JsonPatchOperation(operationKind, from, path, optionalValue)); + return this; + } + + /** + * Gets a formatted JSON string representation of this JSON Patch document. + * + * @return The formatted JSON String representing this JSON Patch document. + */ + @Override + public String toString() { + StringBuilder builder = new StringBuilder("["); + + for (int i = 0; i < operations.size(); i++) { + if (i > 0) { + builder.append(","); + } + + operations.get(i).buildString(builder); + } + + return builder.append("]").toString(); + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return (CoreUtils.isNullOrEmpty(operations)) + ? jsonWriter + : jsonWriter.writeArray(operations, JsonWriter::writeJson); + } + + /** + * Reads a JSON stream into a {@link JsonPatchDocument}. + * + * @param jsonReader The {@link JsonReader} being read. + * @return The {@link JsonPatchDocument} that the JSON stream represented, or null if it pointed to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If a {@link JsonPatchDocument} fails to be read from the {@code jsonReader}. + */ + public static JsonPatchDocument fromJson(JsonReader jsonReader) throws IOException { + List operations = jsonReader.readArray(JsonPatchOperation::fromJson); + JsonPatchDocument document = new JsonPatchDocument(); + if (operations != null) { + document.operations.addAll(operations); + } + + return document; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonPatchOperation.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonPatchOperation.java new file mode 100644 index 000000000000..3e4bc5ca7d24 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonPatchOperation.java @@ -0,0 +1,191 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.serialization.json.models; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.implementation.utils.Option; +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonSerializable; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.serialization.json.JsonWriter; + +import java.io.IOException; +import java.util.Objects; +import java.util.Optional; + +/** + *

        Represents a JSON Patch operation.

        + * + *

        This class encapsulates a single operation in a JSON Patch document. Each operation is defined by its kind + * (add, replace, remove, etc.), a path pointing to the location within the target JSON document, an optional + * 'from' path for copy and move operations, and an optional value.

        + * + *

        This class is useful when you want to create a JSON Patch operation to be included in a JSON Patch document. + * For example, you can use it to represent an operation that adds a new property to a JSON object, replaces the + * value of a property, or removes a property.

        + * + * @see JsonPatchOperationKind + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +final class JsonPatchOperation implements JsonSerializable { + private final JsonPatchOperationKind op; + private final String from; + private final String path; + private final Option value; + + /** + * Creates a JSON Patch operation. + *

        + * When {@code optionalValue} is null the value won't be included in the JSON request, use {@link Optional#empty()} + * to indicate a JSON null. + * + * @param op The kind of operation. + * @param from Optional from target path. + * @param path Operation target path. + * @param value Optional value. + */ + JsonPatchOperation(JsonPatchOperationKind op, String from, String path, Option value) { + this.op = op; + this.from = from; + this.path = path; + this.value = value; + } + + /** + * Gets the operation kind. + * + * @return The kind of operation. + */ + JsonPatchOperationKind getOp() { + return op; + } + + /** + * Gets the operation from target path. + * + * @return The operation from target path. + */ + String getFrom() { + return from; + } + + /** + * Gets the operation target path. + * + * @return The operation target path. + */ + String getPath() { + return path; + } + + /** + * Gets the operation value. + *

        + * If the operation doesn't take a value {@link Option#uninitialized()} will be returned. + * + * @return The operation value. + */ + Option getValue() { + return value; + } + + @Override + public int hashCode() { + return Objects.hash(op.toString(), from, path, (value == null) ? null : value.getValue()); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof JsonPatchOperation)) { + return false; + } + + if (this == obj) { + return true; + } + + JsonPatchOperation other = (JsonPatchOperation) obj; + return Objects.equals(op, other.op) + && Objects.equals(from, other.from) + && Objects.equals(path, other.path) + && Objects.equals(value, other.value); + } + + @Override + public String toString() { + return buildString(new StringBuilder()).toString(); + } + + StringBuilder buildString(StringBuilder builder) { + builder.append("{\"op\":\"").append(op.toString()).append("\""); + + if (from != null) { + builder.append(",\"from\":\"").append(from).append("\""); + } + + builder.append(",\"path\":\"").append(path).append("\""); + + if (value.isInitialized()) { + builder.append(",\"value\":").append(value.getValue()); + } + + return builder.append("}"); + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject() + .writeStringField("op", op.toString()) + .writeStringField("from", from) + .writeStringField("path", path); + + if (value.isInitialized()) { + String valueString = value.getValue(); + if (valueString == null) { + jsonWriter.writeNullField("value"); + } else { + jsonWriter.writeRawField("value", value.getValue()); + } + } + + return jsonWriter.writeEndObject(); + } + + /** + * Reads a JSON stream into a {@link JsonPatchOperation}. + * + * @param jsonReader The {@link JsonReader} being read. + * @return The {@link JsonPatchOperation} that the JSON stream represented, or null if it pointed to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If a {@link JsonPatchOperation} fails to be read from the {@code jsonReader}. + */ + public static JsonPatchOperation fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + JsonPatchOperationKind op = null; + String from = null; + String path = null; + Option value = Option.uninitialized(); + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("op".equals(fieldName)) { + op = JsonPatchOperationKind.fromString(reader.getString()); + } else if ("from".equals(fieldName)) { + from = reader.getString(); + } else if ("path".equals(fieldName)) { + path = reader.getString(); + } else if ("value".equals(fieldName)) { + value = Option.of(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return new JsonPatchOperation(op, from, path, value); + }); + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonPatchOperationKind.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonPatchOperationKind.java new file mode 100644 index 000000000000..acbfc4fe5a53 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonPatchOperationKind.java @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.serialization.json.models; + +/** + *

        Represents the kind of operation in a JSON Patch document.

        + * + *

        This enum encapsulates the kinds of operations that can be included in a JSON Patch document, such as + * {@link #ADD}, {@link #REMOVE}, {@link #REPLACE}, {@link #MOVE}, {@link #COPY}, and {@link #TEST}.

        + * + *

        This enum also provides a {@link #fromString(String)} method to create or get a JsonPatchOperationKind from its string representation, + * and a {@link #toString()} method to get the string representation of the operation kind.

        + * + *

        Note: The operation kinds are defined by the JSON Patch specification (RFC 6902).

        + */ +enum JsonPatchOperationKind { + /** + * Add operation. + */ + ADD("add"), + + /** + * Remove operation. + */ + REMOVE("remove"), + + /** + * Replace operation. + */ + REPLACE("replace"), + + /** + * Move operation. + */ + MOVE("move"), + + /** + * Copy operation. + */ + COPY("copy"), + + /** + * Test operation. + */ + TEST("test"); + + private final String op; + + JsonPatchOperationKind(String op) { + this.op = op; + } + + static JsonPatchOperationKind fromString(String op) { + if (op == null) { + return null; + } + + for (JsonPatchOperationKind kind : values()) { + if (kind.op.equals(op)) { + return kind; + } + } + + return null; + } + + /** + * Gets the string representation of the JSON patch operation kind. + * + * @return The string representation of the JSON patch operation kind. + */ + public String toString() { + return op; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonString.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonString.java index 09f0a8564d25..5eb6c22601fd 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonString.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/models/JsonString.java @@ -3,6 +3,8 @@ package io.clientcore.core.serialization.json.models; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; import io.clientcore.core.serialization.json.JsonReader; import io.clientcore.core.serialization.json.JsonToken; import io.clientcore.core.serialization.json.JsonWriter; @@ -13,6 +15,7 @@ /** * Class representing the JSON string type */ +@Metadata(properties = MetadataProperties.IMMUTABLE) public final class JsonString extends JsonElement { private final String value; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/package-info.java index 5d4598413f6e..1b779afbb16a 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/package-info.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/json/package-info.java @@ -387,19 +387,7 @@ * JSON, and as with {@link io.clientcore.core.serialization.json.JsonReader}, it contains both abstract methods for implementations to * implement and final methods for commonly shared logic that builds on the abstract methods. Both types implement * {@link java.io.Closeable} and should be used in try-with-resources blocks to ensure any resources created by - * the implementations are cleaned up once JSON reading or writing is complete. Both types are used by the - * {@link io.clientcore.core.serialization.json.JsonProvider} service provider interface which is used to create instances of - * {@link io.clientcore.core.serialization.json.JsonReader} and {@link io.clientcore.core.serialization.json.JsonWriter} implementations.

        - * - * - *

        {@link io.clientcore.core.serialization.json.JsonProviders} is a utility class that handles finding {@link io.clientcore.core.serialization.json.JsonProvider} - * implementations on the classpath and should be the default way to create instances of - * {@link io.clientcore.core.serialization.json.JsonReader} and {@link io.clientcore.core.serialization.json.JsonWriter}. As mentioned earlier, the Client Core JSON - * package provides a default implementation allowing for the library to be used stand-alone. - * {@link io.clientcore.core.serialization.json.JsonReader} can be created from {@code byte[]}, {@link java.lang.String}, - * {@link java.io.InputStream}, and {@link java.io.Reader} sources, {@link io.clientcore.core.serialization.json.JsonWriter} can be created - * from {@link java.io.OutputStream} and {@link java.io.Writer} sources. No matter the source the functionality will be - * the same, the options exist to provide the best convenience and performance by reducing type translations. + * the implementations are cleaned up once JSON reading or writing is complete.

        * *

        Sample: Reading a JSON byte[]

        * @@ -409,7 +397,7 @@ * byte[] json = ("{\"memoryInBytes\":10000000000,\"clockSpeedInHertz\":4800000000," * + "\"manufacturer\":\"Memory Corp\",\"errorCorrecting\":true}").getBytes(StandardCharsets.UTF_8); * - * try (JsonReader jsonReader = JsonProviders.createReader(json)) { + * try (JsonReader jsonReader = JsonReader.fromBytes(json)) { * return ComputerMemory.fromJson(jsonReader); * } *
        @@ -422,7 +410,7 @@ * String json = "{\"cores\":16,\"threads\":32,\"manufacturer\":\"Processor Corp\"," * + "\"clockSpeedInHertz\":5000000000,\"releaseDate\":null}"; * - * try (JsonReader jsonReader = JsonProviders.createReader(json)) { + * try (JsonReader jsonReader = JsonReader.fromString(json)) { * return ComputerProcessor.fromJson(jsonReader); * } *
        @@ -440,7 +428,7 @@ * + "\"AcceleratedNetwork\":true,\"CloudProvider\":\"SomeCloud\",\"Available\":true}") * .getBytes(StandardCharsets.UTF_8)); * - * try (JsonReader jsonReader = JsonProviders.createReader(json)) { + * try (JsonReader jsonReader = JsonReader.fromStream(json)) { * return VmStatistics.fromJson(jsonReader); * } * @@ -456,7 +444,7 @@ * + "\"manufacturer\":\"Memory Corp\",\"errorCorrecting\":true},\"AcceleratedNetwork\":true," * + "\"CloudProvider\":\"SomeCloud\",\"Available\":true}"); * - * try (JsonReader jsonReader = JsonProviders.createReader(json)) { + * try (JsonReader jsonReader = JsonReader.fromReader(json)) { * return VmStatistics.fromJson(jsonReader); * } * @@ -481,7 +469,7 @@ * .setAdditionalProperties(additionalVmProperties); * * ByteArrayOutputStream json = new ByteArrayOutputStream(); - * try (JsonWriter jsonWriter = JsonProviders.createWriter(json)) { + * try (JsonWriter jsonWriter = JsonWriter.toStream(json)) { * // JsonWriter automatically flushes on close. * vmStatistics.toJson(jsonWriter); * } @@ -513,7 +501,7 @@ * .setAdditionalProperties(additionalVmProperties); * * Writer json = new StringWriter(); - * try (JsonWriter jsonWriter = JsonProviders.createWriter(json)) { + * try (JsonWriter jsonWriter = JsonWriter.toWriter(json)) { * // JsonWriter automatically flushes on close. * vmStatistics.toJson(jsonWriter); * } @@ -529,7 +517,5 @@ * @see io.clientcore.core.serialization.json.JsonSerializable * @see io.clientcore.core.serialization.json.JsonReader * @see io.clientcore.core.serialization.json.JsonWriter - * @see io.clientcore.core.serialization.json.JsonProvider - * @see io.clientcore.core.serialization.json.JsonProviders */ package io.clientcore.core.serialization.json; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/package-info.java new file mode 100644 index 000000000000..159875b667b5 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing interfaces describing serialization and deserialization contract. + */ +package io.clientcore.core.serialization; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/XmlSerializer.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/xml/XmlSerializer.java similarity index 94% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/XmlSerializer.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/xml/XmlSerializer.java index b50c7d89550f..3f661aa98bdc 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/XmlSerializer.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/xml/XmlSerializer.java @@ -1,15 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.implementation.util; +package io.clientcore.core.serialization.xml; import io.clientcore.core.implementation.TypeUtil; -import io.clientcore.core.serialization.xml.XmlReader; -import io.clientcore.core.serialization.xml.XmlSerializable; -import io.clientcore.core.serialization.xml.XmlWriter; import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.util.serializer.ObjectSerializer; -import io.clientcore.core.util.serializer.SerializationFormat; +import io.clientcore.core.serialization.ObjectSerializer; +import io.clientcore.core.serialization.SerializationFormat; import javax.xml.stream.XMLStreamException; import java.io.ByteArrayOutputStream; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/xml/implementation/aalto/out/OutputElement.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/xml/implementation/aalto/out/OutputElement.java index 6c8fd71d4acb..661700733b05 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/xml/implementation/aalto/out/OutputElement.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/serialization/xml/implementation/aalto/out/OutputElement.java @@ -242,7 +242,7 @@ public Iterator getPrefixes(String uri, NamespaceContext rootNsContext) // Note: it's quite difficult to properly resolve masking if (rootNsContext != null) { - Iterator it = rootNsContext.getPrefixes(uri); + Iterator it = getPrefixes(rootNsContext, uri); while (it.hasNext()) { String prefix = it.next(); if (prefix.isEmpty()) { // default NS already checked @@ -263,6 +263,14 @@ public Iterator getPrefixes(String uri, NamespaceContext rootNsContext) return l.iterator(); } + // In Java 8 NamespaceContext.getPrefixes returns Iterator, not Iterator, which is why this method exists + // with a warnings suppression for the unchecked cast. In later versions of Java it returns Iterator, so + // when we upgrade the baseline off Java 8 this method can be removed and the call can be done inline again. + @SuppressWarnings("unchecked") + private static Iterator getPrefixes(NamespaceContext context, String uri) { + return context.getPrefixes(uri); + } + /** * Method similar to {@link #getPrefix}, but one that will not accept * the default namespace, only an explicit one. Usually used when diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/traits/ConfigurationTrait.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/traits/ConfigurationTrait.java similarity index 75% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/models/traits/ConfigurationTrait.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/traits/ConfigurationTrait.java index 573905e3307c..e0f518d9024f 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/traits/ConfigurationTrait.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/traits/ConfigurationTrait.java @@ -1,17 +1,17 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.models.traits; +package io.clientcore.core.traits; -import io.clientcore.core.util.configuration.Configuration; +import io.clientcore.core.utils.configuration.Configuration; /** - * A {@link io.clientcore.core.models.traits trait} providing a consistent interface for setting {@link Configuration}. + * A {@link io.clientcore.core.traits trait} providing a consistent interface for setting {@link Configuration}. * * @param The concrete type that implements the trait. This is required so that fluent operations can continue to * return the concrete type, rather than the trait type. * - * @see io.clientcore.core.models.traits + * @see io.clientcore.core.traits * @see Configuration */ public interface ConfigurationTrait> { diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/traits/EndpointTrait.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/traits/EndpointTrait.java similarity index 80% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/models/traits/EndpointTrait.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/traits/EndpointTrait.java index 94b3be4c04e2..9408661a34a0 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/traits/EndpointTrait.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/traits/EndpointTrait.java @@ -1,15 +1,15 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.models.traits; +package io.clientcore.core.traits; /** - * A {@link io.clientcore.core.models.traits trait} providing a consistent interface for setting service endpoints. + * A {@link io.clientcore.core.traits trait} providing a consistent interface for setting service endpoints. * * @param The concrete type that implements the trait. This is required so that fluent operations can continue to * return the concrete type, rather than the trait type. * - * @see io.clientcore.core.models.traits + * @see io.clientcore.core.traits */ public interface EndpointTrait> { /** diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/traits/HttpTrait.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/traits/HttpTrait.java similarity index 82% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/models/traits/HttpTrait.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/traits/HttpTrait.java index b18fd73229f5..5b151a8470e8 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/traits/HttpTrait.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/traits/HttpTrait.java @@ -1,17 +1,17 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.models.traits; +package io.clientcore.core.traits; import io.clientcore.core.http.client.HttpClient; -import io.clientcore.core.http.models.HttpLogOptions; -import io.clientcore.core.http.models.HttpRedirectOptions; -import io.clientcore.core.http.models.HttpRetryOptions; +import io.clientcore.core.http.pipeline.HttpInstrumentationOptions; +import io.clientcore.core.http.pipeline.HttpRedirectOptions; +import io.clientcore.core.http.pipeline.HttpRetryOptions; import io.clientcore.core.http.pipeline.HttpPipeline; import io.clientcore.core.http.pipeline.HttpPipelinePolicy; /** - * A {@link io.clientcore.core.models.traits trait} providing a consistent interface for configuration of HTTP-specific + * A {@link io.clientcore.core.traits trait} providing a consistent interface for configuration of HTTP-specific * settings. Refer to the * HTTP clients and pipelines documentation for more * details on proper usage and configuration of HTTP clients. @@ -26,11 +26,11 @@ * @param The concrete type that implements the trait. This is required so that fluent operations can continue to * return the concrete type, rather than the trait type. * - * @see io.clientcore.core.models.traits + * @see io.clientcore.core.traits * @see HttpClient * @see HttpPipeline * @see HttpPipelinePolicy - * @see HttpLogOptions + * @see HttpInstrumentationOptions * @see HttpRetryOptions * @see HttpRedirectOptions */ @@ -106,9 +106,21 @@ public interface HttpTrait> { T httpRetryOptions(HttpRetryOptions retryOptions); /** - * 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 HttpLogOptions.HttpLogDetailLevel#NONE} - * is set. + * Sets the {@link HttpInstrumentationOptions instrumentation configuration} to use when recording telemetry about HTTP + * requests sent to the service and responses received from it. + *

        + * By default, when instrumentation options are not provided (explicitly or via environment variables), the following + * defaults are used: + *

          + *
        • Detailed HTTP logging about requests and responses is disabled
        • + *
        • Distributed tracing is enabled. If OpenTelemetry is found on the classpath, HTTP requests are + * captured as OpenTelemetry spans. + * If OpenTelemetry is not found on the classpath, the same information is captured in logs. + * HTTP request spans contain basic information about the request, such as the HTTP method, URL, status code and + * duration. + * See {@link io.clientcore.core.http.pipeline.HttpInstrumentationPolicy} for + * the details.
        • + *
        * *

        Note: It is important to understand the precedence order of the {@link HttpTrait} APIs. In * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and @@ -117,13 +129,13 @@ public interface HttpTrait> { * 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. + * @param instrumentationOptions The {@link HttpInstrumentationOptions configuration} to use when recording telemetry about HTTP + * requests sent to the service and responses received from it. * * @return Returns the same concrete type with the appropriate properties updated, to allow for fluent chaining of * operations. */ - T httpLogOptions(HttpLogOptions logOptions); + T httpInstrumentationOptions(HttpInstrumentationOptions instrumentationOptions); /** * Sets the {@link HttpRedirectOptions} for all the requests made through the client. diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/traits/KeyCredentialTrait.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/traits/KeyCredentialTrait.java similarity index 81% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/models/traits/KeyCredentialTrait.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/traits/KeyCredentialTrait.java index b7db940021c2..83826a6eacc2 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/traits/KeyCredentialTrait.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/traits/KeyCredentialTrait.java @@ -1,12 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.models.traits; +package io.clientcore.core.traits; -import io.clientcore.core.credential.KeyCredential; +import io.clientcore.core.credentials.KeyCredential; /** - * A {@link io.clientcore.core.models.traits trait} providing a consistent interface for setting {@link KeyCredential}. + * A {@link io.clientcore.core.traits trait} providing a consistent interface for setting {@link KeyCredential}. * Refer to the * identity and authentication documentation for more details on * proper usage of the {@link KeyCredential} type. @@ -14,7 +14,7 @@ * @param The concrete type that implements the trait. This is required so that fluent operations can continue to * return the concrete type, rather than the trait type. * - * @see io.clientcore.core.models.traits + * @see io.clientcore.core.traits * @see KeyCredential */ public interface KeyCredentialTrait> { diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/traits/NamedKeyCredentialTrait.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/traits/NamedKeyCredentialTrait.java new file mode 100644 index 000000000000..773222e9a696 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/traits/NamedKeyCredentialTrait.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.traits; + +import io.clientcore.core.credentials.NamedKeyCredential; + +/** + * An {@link io.clientcore.core.traits SDK for Java trait} providing a consistent interface for setting + * {@link NamedKeyCredential}. + * + * @param The concrete type that implements the trait. This is required so that fluent operations can continue + * to return the concrete type, rather than the trait type. + * @see io.clientcore.core.traits + * @see NamedKeyCredential + */ +public interface NamedKeyCredentialTrait> { + /** + * Sets the {@link NamedKeyCredential} used for authentication. + * + * @param credential the {@link NamedKeyCredential} to be used for authentication. + * @return Returns the same concrete type with the appropriate properties updated, to allow for fluent chaining of + * operations. + */ + T credential(NamedKeyCredential credential); +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/traits/ProxyTrait.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/traits/ProxyTrait.java similarity index 82% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/models/traits/ProxyTrait.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/traits/ProxyTrait.java index 7d17ae3311e8..cc843b0cf624 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/models/traits/ProxyTrait.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/traits/ProxyTrait.java @@ -1,19 +1,19 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.models.traits; +package io.clientcore.core.traits; import io.clientcore.core.http.client.HttpClient; import io.clientcore.core.http.models.ProxyOptions; /** - * A {@link io.clientcore.core.models.traits trait} providing a consistent interface for configuration of proxy-specific + * A {@link io.clientcore.core.traits trait} providing a consistent interface for configuration of proxy-specific * settings. * * @param The concrete type that implements the trait. This is required so that fluent operations can continue to * return the concrete type, rather than the trait type. * - * @see io.clientcore.core.models.traits + * @see io.clientcore.core.traits * @see ProxyOptions */ public interface ProxyTrait> { diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/traits/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/traits/package-info.java new file mode 100644 index 000000000000..79a3617f9b09 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/traits/package-info.java @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * This package contains interfaces that represent common cross-cutting aspects of functionality offered by libraries in + * the SDK. Each interface is referred to as a 'trait', and classes that implement the interface are said to have that + * trait. + * + *

        The particular focus of traits in the SDK is to enable higher-level libraries the ability to more abstractly + * configure client libraries as part of their builders, prior to the client itself being instantiated. By doing this, + * these high-level libraries are able to reason about functionality more simply. It is important to appreciate that + * despite the availability of these cross-cutting traits, there is no promise that configuration of each builder can + * simply be a matter of providing the same arguments for all builders! Each builder must be configured appropriately + * for its requirements, or else runtime failures may occur when the builder is asked to create the associated client. + *

        + */ +package io.clientcore.core.traits; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/ServerSentResult.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/util/ServerSentResult.java deleted file mode 100644 index fae256b1a872..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/ServerSentResult.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.util; - -import java.io.IOException; -import java.time.Duration; -import java.util.List; - -/** - * Class to hold the result for a retry of an ServerSentEvent content type request. - */ -public final class ServerSentResult { - private final String lastEventId; - private final Duration retryAfter; - private final IOException ioException; - private final List data; - - ServerSentResult(IOException exception, String lastEventId, Duration retryAfter, List data) { - this.ioException = exception; - this.lastEventId = lastEventId; - this.retryAfter = retryAfter; - this.data = data; - } - - /** - * Get the accumulated event data from the text event stream. - * @return The accumulated event data from the text event stream. - */ - public List getData() { - return data; - } - - /** - * Get the exception that occurred during the request. - * @return The exception that occurred during the request. - */ - public IOException getException() { - return ioException; - } - - /** - * Get the last event id from the text event stream. - * @return The last event id from the text event stream. - */ - public String getLastEventId() { - return lastEventId; - } - - /** - * Get the retry time duration. - * @return The retry time duration. - */ - public Duration getRetryAfter() { - return retryAfter; - } -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/auth/BasicChallengeHandler.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/util/auth/BasicChallengeHandler.java deleted file mode 100644 index f1a2afb3163e..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/auth/BasicChallengeHandler.java +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.util.auth; - -import io.clientcore.core.http.models.HttpHeaderName; -import io.clientcore.core.http.models.HttpRequest; -import io.clientcore.core.http.models.Response; - -import java.nio.charset.StandardCharsets; -import java.util.Base64; - -import static io.clientcore.core.util.auth.AuthUtils.BASIC; - -/** - * Handles basic authentication challenges. - * This class implements the `ChallengeHandler` interface and provides - * functionality to handle HTTP Basic Authentication challenges. - */ -public class BasicChallengeHandler implements ChallengeHandler { - - private final String authHeader; - - /** - * Constructs a `BasicChallengeHandler` with the specified username and password. - * - * @param username The username for basic authentication. - * @param password The password for basic authentication. - */ - public BasicChallengeHandler(String username, String password) { - String token = username + ":" + password; - this.authHeader = "Basic " + Base64.getEncoder().encodeToString(token.getBytes(StandardCharsets.UTF_8)); - } - - @Override - public void handleChallenge(HttpRequest request, Response response, boolean isProxy) { - if (canHandle(response, isProxy)) { - synchronized (request.getHeaders()) { - HttpHeaderName headerName = isProxy ? HttpHeaderName.PROXY_AUTHORIZATION : HttpHeaderName.AUTHORIZATION; - // Check if the appropriate Authorization header is already present - if (request.getHeaders().getValue(headerName) == null) { - request.getHeaders().add(headerName, authHeader); - } - } - } - } - - @Override - public boolean canHandle(Response response, boolean isProxy) { - String authHeader; - if (response.getHeaders() != null) { - HttpHeaderName authHeaderName - = isProxy ? HttpHeaderName.PROXY_AUTHENTICATE : HttpHeaderName.WWW_AUTHENTICATE; - authHeader = response.getHeaders().getValue(authHeaderName); - - if (authHeader != null) { - // Split by commas to handle multiple authentication methods in the header. - String[] challenges = authHeader.split(","); - for (String challenge : challenges) { - if (challenge.trim().regionMatches(true, 0, BASIC, 0, BASIC.length())) { - return true; - } - } - } - } - return false; - } -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/auth/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/util/auth/package-info.java deleted file mode 100644 index 3b86a9adab37..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/auth/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - * Package containing core auth related classes. - */ -package io.clientcore.core.util.auth; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/binarydata/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/util/binarydata/package-info.java deleted file mode 100644 index 3f5c3a920b4d..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/binarydata/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - * Provides classes for working with binary data. - */ -package io.clientcore.core.util.binarydata; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/configuration/Configuration.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/util/configuration/Configuration.java deleted file mode 100644 index 6e749a54c3c9..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/configuration/Configuration.java +++ /dev/null @@ -1,460 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.util.configuration; - -import io.clientcore.core.http.client.HttpClient; -import io.clientcore.core.http.client.HttpClientProvider; -import io.clientcore.core.implementation.util.EnvironmentConfiguration; -import io.clientcore.core.implementation.util.ImplUtils; -import io.clientcore.core.instrumentation.logging.ClientLogger; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.function.Function; - -import static io.clientcore.core.implementation.util.ImplUtils.isNullOrEmpty; - -/** - * Contains configuration information that is used during construction of client libraries. - * - * - *
        - * Configuration configuration = new ConfigurationBuilder(new SampleSource(properties))
        - *     .root("my.sdk")
        - *     .buildSection("client-name");
        - *
        - * ConfigurationProperty<String> proxyHostnameProperty = ConfigurationPropertyBuilder.ofString("http.proxy.hostname")
        - *     .shared(true)
        - *     .build();
        - * System.out.println(configuration.get(proxyHostnameProperty));
        - * 
        - * - */ -public class Configuration { - // Default properties - these are what we read from the environment - /** - * URI of the proxy for HTTP connections. - */ - public static final String PROPERTY_HTTP_PROXY = "HTTP_PROXY"; - - /** - * URI of the proxy for HTTPS connections. - */ - public static final String PROPERTY_HTTPS_PROXY = "HTTPS_PROXY"; - - /** - * A list of hosts or CIDR to not use proxy HTTP/HTTPS connections through. - */ - public static final String PROPERTY_NO_PROXY = "NO_PROXY"; - - /** - * Enables logging by setting a log level. - */ - public static final String PROPERTY_LOG_LEVEL = "LOG_LEVEL"; - - /** - * Enables HTTP request/response logging by setting an HTTP log detail level. - */ - public static final String PROPERTY_HTTP_LOG_DETAIL_LEVEL = "HTTP_LOG_DETAIL_LEVEL"; - - /** - * Sets the default number of times a request will be retried, if it passes the conditions for retrying, before it - * fails. - */ - public static final String PROPERTY_REQUEST_RETRY_COUNT = "REQUEST_RETRY_COUNT"; - - /** - * Sets the default timeout, in milliseconds, for a request to connect to the remote host. - *

        - * If the configured value is equal to or less than 0 no timeout will be applied. - */ - public static final String PROPERTY_REQUEST_CONNECT_TIMEOUT = "REQUEST_CONNECT_TIMEOUT"; - - /** - * Sets the default timeout interval, in milliseconds, allowed between each byte written by a request. - *

        - * If the configured value is equal to or less than 0 no timeout will be applied. - */ - public static final String PROPERTY_REQUEST_WRITE_TIMEOUT = "REQUEST_WRITE_TIMEOUT"; - - /** - * Sets the default timeout, in milliseconds, for a request to receive a response from the remote host. - *

        - * If the configured value is equal to or less than 0 no timeout will be applied. - */ - public static final String PROPERTY_REQUEST_RESPONSE_TIMEOUT = "REQUEST_RESPONSE_TIMEOUT"; - - /** - * Sets the default timeout interval, in milliseconds, allowed between each byte read in a response. - *

        - * If the configured value is equal to or less than 0 no timeout will be applied. - */ - public static final String PROPERTY_REQUEST_READ_TIMEOUT = "REQUEST_READ_TIMEOUT"; - - /** - * Sets the name of the {@link HttpClientProvider} implementation that should be used to construct instances of - * {@link HttpClient}. - *

        - * The name must be the full class name, ex {@code io.clientcore.http.okhttp3.OkHttpHttpClientProvider} and not - * {@code OkHttpHttpClientProvider}, to disambiguate multiple providers with the same name but from different - * packages. - *

        - * If the value isn't set or is an empty string the first {@link HttpClientProvider} resolved by - * {@link java.util.ServiceLoader} will be used to create an instance of {@link HttpClient}. If the value is set - * and doesn't match any {@link HttpClientProvider} resolved by {@link java.util.ServiceLoader} an - * {@link IllegalStateException} will be thrown when attempting to create an instance of {@link HttpClient}. - */ - public static final String PROPERTY_HTTP_CLIENT_IMPLEMENTATION = "HTTP_CLIENT_IMPLEMENTATION"; - - /* - * Gets the global configuration shared by all client libraries. - */ - private static final Configuration GLOBAL_CONFIGURATION - = new Configuration(Collections.emptyMap(), EnvironmentConfiguration.getGlobalConfiguration(), null, null); - - private static final ClientLogger LOGGER = new ClientLogger(Configuration.class); - - private final EnvironmentConfiguration environmentConfiguration; - private final Map configurations; - private final String path; - private final Configuration sharedConfiguration; - private final boolean isEmpty; - - /** - * Constructs a configuration containing the known properties constants. Use {@link ConfigurationBuilder} to - * create instance of {@link Configuration}. - * - * @param configurationSource Configuration property source. - * @param environmentConfiguration instance of {@link EnvironmentConfiguration} to mock environment for testing. - * @param path Absolute path of current configuration section for logging and diagnostics purposes. - * @param sharedConfiguration Instance of shared {@link Configuration} section to retrieve shared properties. - */ - Configuration(ConfigurationSource configurationSource, EnvironmentConfiguration environmentConfiguration, - String path, Configuration sharedConfiguration) { - this(readConfigurations(configurationSource, path), environmentConfiguration, path, sharedConfiguration); - } - - /** - * Constructs a configuration containing the known properties constants. Use {@link ConfigurationBuilder} to - * create instance of {@link Configuration}. - * - * @param configurations map of all properties. - * @param environmentConfiguration instance of {@link EnvironmentConfiguration} to mock environment for testing. - * @param path Absolute path of current configuration section for logging and diagnostics purposes. - * @param sharedConfiguration Instance of shared {@link Configuration} section to retrieve shared properties. - */ - private Configuration(Map configurations, EnvironmentConfiguration environmentConfiguration, - String path, Configuration sharedConfiguration) { - this.configurations = configurations; - this.isEmpty = configurations.isEmpty(); - this.environmentConfiguration - = Objects.requireNonNull(environmentConfiguration, "'environmentConfiguration' cannot be null"); - this.path = path; - this.sharedConfiguration = sharedConfiguration; - } - - /** - * Gets the global configuration store shared by all client libraries. - * - * @return The global configuration store. - */ - public static Configuration getGlobalConfiguration() { - return GLOBAL_CONFIGURATION; - } - - /** - * Gets the value of system property or environment variable. Use {@link Configuration#get(ConfigurationProperty)} - * overload to get explicit configuration or environment configuration from specific source. - * - *

        - * This method first checks the values previously loaded from the environment, if the configuration is found there - * it will be returned. Otherwise, this will attempt to load the value from the environment. - * - * @param name Name of the configuration. - * @return Value of the configuration if found, otherwise null. - */ - public String get(String name) { - return environmentConfiguration.get(name); - } - - /** - * Gets the value of system property or environment variable converted to given primitive {@code T} using - * corresponding {@code parse} method on this type. - * - * Use {@link Configuration#get(ConfigurationProperty)} overload to get explicit configuration or environment - * configuration from specific source. - * - *

        - * This method first checks the values previously loaded from the environment, if the configuration is found there - * it will be returned. Otherwise, this will attempt to load the value from the environment. - *

        - * If no configuration is found, the {@code defaultValue} is returned. - * - *

        Following types are supported:

        - *
          - *
        • {@link Byte}
        • - *
        • {@link Short}
        • - *
        • {@link Integer}
        • - *
        • {@link Long}
        • - *
        • {@link Float}
        • - *
        • {@link Double}
        • - *
        • {@link Boolean}
        • - *
        - * - * @param name Name of the configuration. - * @param defaultValue Value to return if the configuration isn't found. - * @param Type that the configuration is converted to if found. - * @return The converted configuration if found, otherwise the default value is returned. - */ - public T get(String name, T defaultValue) { - return convertToPrimitiveOrDefault(get(name), defaultValue); - } - - /** - * Gets the value of system property or environment variable and converts it with the {@code converter}. - *

        - * This method first checks the values previously loaded from the environment, if the configuration is found there - * it will be returned. Otherwise, this will attempt to load the value from the environment. - *

        - * If no configuration is found the {@code converter} won't be called and null will be returned. - * - * @param name Name of the configuration. - * @param converter Converter used to map the configuration to {@code T}. - * @param Type that the configuration is converted to if found. - * @return The converted configuration if found, otherwise null. - */ - public T get(String name, Function converter) { - Objects.requireNonNull(converter, "'converter' can't be null"); - return converter.apply(get(name)); - } - - /** - * Determines if the system property or environment variable is defined. - *

        - * Use {@link Configuration#contains(ConfigurationProperty)} overload to get explicit configuration or environment - * configuration from specific source. - * - *

        - * This only checks against values previously loaded into the Configuration object, this won't inspect the - * environment for containing the value. - * - * @param name Name of the configuration. - * @return True if the configuration exists, otherwise false. - */ - public boolean contains(String name) { - return get(name) != null; - } - - /** - * Checks if configuration contains the property. If property can be shared between clients, checks this - * {@code Configuration} and falls back to shared section. If property has aliases, system property or environment - * variable defined, checks them as well. - *

        - * Value is not validated. - * - * @param property instance. - * @return true if property is available, false otherwise. - */ - public boolean contains(ConfigurationProperty property) { - Objects.requireNonNull(property, "'property' can't be null"); - return getWithFallback(property) != null; - } - - /** - * Gets property value from all available sources in the following order: - * - *

          - *
        • Explicit configuration from given {@link ConfigurationSource} by property name
        • - *
        • Explicit configuration by property aliases in the order they were provided in {@link ConfigurationProperty}
        • - *
        • Explicit configuration by property name in the shared section (if {@link ConfigurationProperty} is shared)
        • - *
        • Explicit configuration by property aliases in the shared section (if {@link ConfigurationProperty} is shared)
        • - *
        • System property (if set)
        • - *
        • Environment variable (if set)
        • - *
        - * - *

        - * Property value is converted to specified type. If property value is missing and not required, default value is - * returned. - * - * - *

        -     * ConfigurationProperty<String> property = ConfigurationPropertyBuilder.ofString("http.proxy.hostname")
        -     *     .shared(true)
        -     *     .logValue(true)
        -     *     .systemPropertyName("http.proxyHost")
        -     *     .build();
        -     *
        -     * // attempts to get local `my.sdk.<client-name>.http.proxy.host` property and falls back to
        -     * // shared my.sdk.http.proxy.port
        -     * System.out.println(configuration.get(property));
        -     * 
        - * - * - * @param property instance. - * @param Type that the configuration is converted to if found. - * @return The value of the property if it exists, otherwise the default value of the property. - * @throws NullPointerException when property instance is null. - * @throws IllegalArgumentException when required property is missing. - * @throws RuntimeException when property value conversion (and validation) throws. - */ - public T get(ConfigurationProperty property) { - Objects.requireNonNull(property, "'property' cannot be null"); - String value = getWithFallback(property); - - if (value == null) { - if (property.isRequired()) { - throw LOGGER.atError() - .addKeyValue("name", property.getName()) - .addKeyValue("path", path) - .log(null, new IllegalArgumentException("Missing required property.")); - } - return property.getDefaultValue(); - } - - try { - return property.getConverter().apply(value); - } catch (RuntimeException ex) { - throw LOGGER.atError() - .addKeyValue("name", property.getName()) - .addKeyValue("path", path) - .addKeyValue("value", property.getValueSanitizer().apply(value)) - .log(null, ex); - } - } - - private String getLocalProperty(String name, Iterable aliases, Function valueSanitizer) { - if (this.isEmpty) { - return null; - } - - final String value = configurations.get(name); - if (value != null) { - LOGGER.atVerbose() - .addKeyValue("name", name) - .addKeyValue("path", path) - .addKeyValue("value", () -> valueSanitizer.apply(value)) - .log("Got property value by name."); - - return value; - } - - for (String alias : aliases) { - final String valueByAlias = configurations.get(alias); - if (valueByAlias != null) { - LOGGER.atVerbose() - .addKeyValue("name", name) - .addKeyValue("path", path) - .addKeyValue("alias", alias) - .addKeyValue("value", () -> valueSanitizer.apply(valueByAlias)) - .log("Got property value by alias."); - return valueByAlias; - } - } - - return null; - } - - private String getWithFallback(ConfigurationProperty property) { - String name = property.getName(); - if (!isNullOrEmpty(name)) { - String value = getLocalProperty(name, property.getAliases(), property.getValueSanitizer()); - if (value != null) { - return value; - } - - if (property.isShared() && sharedConfiguration != null) { - value = sharedConfiguration.getLocalProperty(name, property.getAliases(), property.getValueSanitizer()); - if (value != null) { - return value; - } - } - } - return getFromEnvironment(property.getSystemPropertyName(), property.getEnvironmentVariableName(), - property.getValueSanitizer()); - } - - private String getFromEnvironment(String systemProperty, String envVar, Function valueSanitizer) { - return ImplUtils.getFromEnvironment(environmentConfiguration, systemProperty, envVar, valueSanitizer, LOGGER); - } - - private static Map readConfigurations(ConfigurationSource source, String path) { - Objects.requireNonNull(source, "'source' cannot be null"); - Map configs = source.getProperties(path); - - if (configs == null || configs.isEmpty()) { - return Collections.emptyMap(); - } - - Map props = new HashMap<>(); - - for (Map.Entry prop : configs.entrySet()) { - String key = isNullOrEmpty(path) ? prop.getKey() : prop.getKey().substring(path.length() + 1); - String value = prop.getValue(); - - LOGGER.atVerbose().addKeyValue("name", prop.getKey()).log("Got property from configuration source."); - - if (key != null && value != null) { - props.put(key, value); - } else { - LOGGER.atWarning().addKeyValue("name", prop.getKey()).log("Key or value is null, property is ignored."); - } - } - - return props; - } - - /** - * Attempts to convert the configuration value to given primitive {@code T} using corresponding {@code parse} method - * on this type. - * - *

        Following types are supported:

        - *
          - *
        • {@link Byte}
        • - *
        • {@link Short}
        • - *
        • {@link Integer}
        • - *
        • {@link Long}
        • - *
        • {@link Float}
        • - *
        • {@link Double}
        • - *
        • {@link Boolean}
        • - *
        - * - * If the value is null or empty then the default value is returned. - * - * @param value Configuration value retrieved from the map. - * @param defaultValue Default value to return if the configuration value is null or empty. - * @param Generic type that the value is converted to if not null or empty. - * @return The converted configuration, if null or empty the default value. - */ - @SuppressWarnings("unchecked") - private static T convertToPrimitiveOrDefault(String value, T defaultValue) { - // Value is null or empty, return the default. - if (isNullOrEmpty(value)) { - return defaultValue; - } - - // Check the default value's type to determine how it needs to be converted. - Object convertedValue; - if (defaultValue instanceof Byte) { - convertedValue = Byte.parseByte(value); - } else if (defaultValue instanceof Short) { - convertedValue = Short.parseShort(value); - } else if (defaultValue instanceof Integer) { - convertedValue = Integer.parseInt(value); - } else if (defaultValue instanceof Long) { - convertedValue = Long.parseLong(value); - } else if (defaultValue instanceof Float) { - convertedValue = Float.parseFloat(value); - } else if (defaultValue instanceof Double) { - convertedValue = Double.parseDouble(value); - } else if (defaultValue instanceof Boolean) { - convertedValue = Boolean.parseBoolean(value); - } else { - convertedValue = value; - } - - return (T) convertedValue; - } -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/configuration/ConfigurationBuilder.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/util/configuration/ConfigurationBuilder.java deleted file mode 100644 index 20f487aed48d..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/configuration/ConfigurationBuilder.java +++ /dev/null @@ -1,270 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.util.configuration; - -import io.clientcore.core.annotation.Metadata; -import io.clientcore.core.implementation.util.EnvironmentConfiguration; -import io.clientcore.core.instrumentation.logging.ClientLogger; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; - -import static io.clientcore.core.annotation.TypeConditions.FLUENT; -import static io.clientcore.core.implementation.util.ImplUtils.isNullOrEmpty; - -/** - * Builds {@link Configuration} with external source. - */ -@Metadata(conditions = FLUENT) -public final class ConfigurationBuilder { - private static final ClientLogger LOGGER = new ClientLogger(ConfigurationBuilder.class); - private final MutableConfigurationSource mutableSource; - private final EnvironmentConfiguration environmentConfiguration; - private String rootPath; - private Configuration sharedConfiguration; - - /** - * Creates {@code ConfigurationBuilder}. - * - * - *
        -     * configuration = new ConfigurationBuilder()
        -     *     .putProperty("my.sdk.client-name.connection-string", "...")
        -     *     .root("my.sdk")
        -     *     .buildSection("client-name");
        -     *
        -     * ConfigurationProperty<String> connectionStringProperty = ConfigurationPropertyBuilder.ofString("connection-string")
        -     *     .build();
        -     *
        -     * System.out.println(configuration.get(connectionStringProperty));
        -     * 
        - * - */ - public ConfigurationBuilder() { - this.mutableSource = new MutableConfigurationSource(); - this.environmentConfiguration = EnvironmentConfiguration.getGlobalConfiguration(); - } - - /** - * Creates {@code ConfigurationBuilder} with configuration source. - * - * - *
        -     * Configuration configuration = new ConfigurationBuilder(new SampleSource(properties))
        -     *     .root("my.sdk")
        -     *     .buildSection("client-name");
        -     *
        -     * ConfigurationProperty<String> proxyHostnameProperty = ConfigurationPropertyBuilder.ofString("http.proxy.hostname")
        -     *     .shared(true)
        -     *     .build();
        -     * System.out.println(configuration.get(proxyHostnameProperty));
        -     * 
        - * - * - * @param source Custom {@link ConfigurationSource} containing known SDK configuration properties. - */ - public ConfigurationBuilder(ConfigurationSource source) { - this.mutableSource = new MutableConfigurationSource(Objects.requireNonNull(source, "'source' cannot be null")); - this.environmentConfiguration = EnvironmentConfiguration.getGlobalConfiguration(); - } - - /** - * Creates {@code ConfigurationBuilder} with configuration sources for explicit configuration, system properties and - * environment configuration sources. Use this constructor to customize known system properties and environment - * variables retrieval. - * - * @param source Custom {@link ConfigurationSource} containing known configuration properties - * @param systemPropertiesConfigurationSource {@link ConfigurationSource} containing known system properties. - * @param environmentConfigurationSource {@link ConfigurationSource} containing known environment variables. - */ - public ConfigurationBuilder(ConfigurationSource source, ConfigurationSource systemPropertiesConfigurationSource, - ConfigurationSource environmentConfigurationSource) { - Objects.requireNonNull(source, "'source' cannot be null"); - Objects.requireNonNull(systemPropertiesConfigurationSource, - "'systemPropertiesConfigurationSource' cannot be null"); - Objects.requireNonNull(environmentConfigurationSource, "'environmentConfigurationSource' cannot be null"); - this.mutableSource = new MutableConfigurationSource(source); - this.environmentConfiguration - = new EnvironmentConfiguration(systemPropertiesConfigurationSource, environmentConfigurationSource); - } - - /** - * Adds property to the configuration source. In case the source already contains property with the same name, the - * value will be overwritten with the new value passed. - * - * - *
        -     * configuration = new ConfigurationBuilder()
        -     *     .putProperty("my.sdk.client-name.connection-string", "...")
        -     *     .root("my.sdk")
        -     *     .buildSection("client-name");
        -     *
        -     * ConfigurationProperty<String> connectionStringProperty = ConfigurationPropertyBuilder.ofString("connection-string")
        -     *     .build();
        -     *
        -     * System.out.println(configuration.get(connectionStringProperty));
        -     * 
        - * - * - * @param name Property name. - * @param value Property value. - * @return {@code ConfigurationBuilder} instance for chaining. - */ - public ConfigurationBuilder putProperty(String name, String value) { - Objects.requireNonNull(name, "'name' cannot be null."); - Objects.requireNonNull(value, "'value' cannot be null."); - - mutableSource.put(name, value); - sharedConfiguration = null; - return this; - } - - /** - * Sets path to root configuration properties where shared SDK properties are defined. When local per-client - * property is missing, {@link Configuration} falls back to shared properties. - * - * - *
        -     * Configuration configuration = new ConfigurationBuilder(new SampleSource(properties))
        -     *     .root("my.sdk")
        -     *     .buildSection("client-name");
        -     *
        -     * ConfigurationProperty<String> proxyHostnameProperty = ConfigurationPropertyBuilder.ofString("http.proxy.hostname")
        -     *     .shared(true)
        -     *     .build();
        -     * System.out.println(configuration.get(proxyHostnameProperty));
        -     * 
        - * - * - * @param rootPath absolute root path, can be {@code null}. - * @return {@code ConfigurationBuilder} instance for chaining. - */ - public ConfigurationBuilder root(String rootPath) { - this.rootPath = rootPath; - this.sharedConfiguration = null; - return this; - } - - /** - * Builds root {@link Configuration} section. Use it for shared properties only. To read client-specific - * configuration, use {@link ConfigurationBuilder#buildSection(String)} which can read per-client and shared - * properties. - * - * - *
        -     * // Builds shared Configuration only.
        -     * Configuration sharedConfiguration = new ConfigurationBuilder(new SampleSource(properties))
        -     *     .root("my.sdk")
        -     *     .build();
        -     * 
        - * - * - * @return Root {@link Configuration} with shared properties. - */ - public Configuration build() { - if (sharedConfiguration == null) { - // defaults can be reused to get different client sections. - sharedConfiguration = new Configuration(mutableSource, environmentConfiguration, rootPath, null); - } - - return sharedConfiguration; - } - - /** - * Builds {@link Configuration} section that supports retrieving properties from client-specific section with - * fallback to root section for properties that can be shared between clients. - * - * - *
        -     * // Builds Configuration for <client-name> with fallback to shared properties.
        -     * configuration = new ConfigurationBuilder(new SampleSource(properties))
        -     *     .root("my.sdk")
        -     *     .buildSection("client-name");
        -     * 
        - * - * - * @param path relative path from {@link ConfigurationBuilder#root(String)} to client section. - * @return Client {@link Configuration} capable of reading client-specific and shared properties. - */ - public Configuration buildSection(String path) { - Objects.requireNonNull(path, "'path' cannot be null"); - if (sharedConfiguration == null) { - // sharedConfiguration can be reused to build different client sections. - sharedConfiguration = new Configuration(mutableSource, environmentConfiguration, rootPath, null); - } - - String absolutePath = getAbsolutePath(rootPath, path); - return new Configuration(mutableSource, environmentConfiguration, absolutePath, sharedConfiguration); - } - - private static String getAbsolutePath(String root, String relative) { - if (isNullOrEmpty(root)) { - return relative; - } - - return root + "." + relative; - } - - private static final class MutableConfigurationSource implements ConfigurationSource { - - private final ConfigurationSource originalSource; - private Map additionalConfigurations; - - private MutableConfigurationSource() { - this(null); - } - - private MutableConfigurationSource(ConfigurationSource originalSource) { - this.originalSource = originalSource; - this.additionalConfigurations = null; - } - - MutableConfigurationSource put(String key, String value) { - if (additionalConfigurations == null) { - additionalConfigurations = new HashMap<>(); - } - - if (additionalConfigurations.containsKey(key)) { - LOGGER.atWarning() - .addKeyValue("name", key) - .log("Property with the same name already exists, value will be overwritten."); - } - - additionalConfigurations.put(key, value); - - return this; - } - - @Override - public Map getProperties(String source) { - Map original - = originalSource == null ? Collections.emptyMap() : originalSource.getProperties(source); - if (additionalConfigurations == null) { - return original; - } - - Map allConfigurations = new HashMap<>(original); - for (Map.Entry prop : additionalConfigurations.entrySet()) { - if (allConfigurations.containsKey(prop.getKey())) { - LOGGER.atWarning() - .addKeyValue("name", prop.getKey()) - .log("Property with the same name already exists, value will be overwritten."); - } - - if (hasPrefix(prop.getKey(), source)) { - allConfigurations.put(prop.getKey(), prop.getValue()); - } - } - - return allConfigurations; - } - - private static boolean hasPrefix(String key, String prefix) { - return prefix == null - || key.startsWith(prefix) && key.length() > prefix.length() && key.charAt(prefix.length()) == '.'; - } - } -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/configuration/ConfigurationProperty.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/util/configuration/ConfigurationProperty.java deleted file mode 100644 index 48531bf47cf1..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/configuration/ConfigurationProperty.java +++ /dev/null @@ -1,138 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.util.configuration; - -import io.clientcore.core.implementation.util.ImplUtils; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.function.Function; - -/** - * Represents configuration property. - * - * @param Type of property value. - */ -public final class ConfigurationProperty { - private final String name; - private final List aliases; - private final String environmentVariable; - private final String systemProperty; - private final Function converter; - private final Function valueSanitizer; - private final T defaultValue; - private final boolean isShared; - private final boolean isRequired; - - /** - * Creates configuration property. - * - * @param name full name (including relative path) of the property. - * @param defaultValue default value. - * @param isRequired indicates required property for validation purposes - * @param converter converts String property value to property type and performs validation. - * @param isShared indicates property that can be specified in per-client and root sections. - * @param environmentVariable environment variables the property can be represented with. Can be null. - * @param systemProperty system property the property can be represented with. Can be null. - * @param aliases list of alternative names of the property. Can be null. - * @param valueSanitizer sanitizes property value for logging purposes. - */ - ConfigurationProperty(String name, T defaultValue, boolean isRequired, Function converter, - boolean isShared, String environmentVariable, String systemProperty, String[] aliases, - Function valueSanitizer) { - this.name = Objects.requireNonNull(name, "'name' cannot be null"); - this.converter = Objects.requireNonNull(converter, "'converter' cannot be null"); - this.environmentVariable = environmentVariable; - this.systemProperty = systemProperty; - this.aliases = aliases == null ? Collections.emptyList() : Arrays.asList(aliases); - this.defaultValue = defaultValue; - this.isRequired = isRequired; - this.isShared = isShared; - this.valueSanitizer = valueSanitizer == null ? ImplUtils.DEFAULT_SANITIZER : valueSanitizer; - } - - /** - * Returns true if property can be shared between clients and {@link Configuration#get(ConfigurationProperty)} - * should look for it in per-client and root sections. - * - * @return flag indicating if the property is shared. - */ - public boolean isShared() { - return isShared; - } - - /** - * Returns property value sanitizer that is used to securely log property value. - * - * @return function that sanitizes property value. - */ - public Function getValueSanitizer() { - return valueSanitizer; - } - - /** - * Returns true if property is required, used for validation purposes. - * - * @return flag indicating if the property is required. - */ - public boolean isRequired() { - return isRequired; - } - - /** - * Gets full property name including relative path to it. - * - * @return property name. - */ - public String getName() { - return name; - } - - /** - * Gets converter for property value. - * - * @return property value converter. - */ - public Function getConverter() { - return converter; - } - - /** - * Gets property default value to be used when property is missing in the configuration. - * - * @return default value. - */ - public T getDefaultValue() { - return defaultValue; - } - - /** - * Gets property aliases - alternative names property can have. - * - * @return array of name aliases. - */ - public Iterable getAliases() { - return aliases; - } - - /** - * Gets name of environment variables this property can be configured with. - * - * @return environment variable name. - */ - public String getEnvironmentVariableName() { - return environmentVariable; - } - - /** - * Gets name of system property this property can be configured with. - * - * @return system property name. - */ - public String getSystemPropertyName() { - return systemProperty; - } -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/configuration/ConfigurationPropertyBuilder.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/util/configuration/ConfigurationPropertyBuilder.java deleted file mode 100644 index 0de4e5913dbd..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/configuration/ConfigurationPropertyBuilder.java +++ /dev/null @@ -1,262 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.util.configuration; - -import java.time.Duration; -import java.util.Objects; -import java.util.function.Function; - -/** - * Builds configuration property. - * - * @param The property value type. - */ -public final class ConfigurationPropertyBuilder { - private static final String[] EMPTY_ARRAY = new String[0]; - private static final Function PERMIT_VALUE_SANITIZER = (value) -> value; - private static final Function CONFIGURATION_PROPERTY_BOOLEAN_CONVERTER = Boolean::valueOf; - private static final Function CONFIGURATION_PROPERTY_DURATION_CONVERTER = (value) -> { - long timeoutMillis = Long.parseLong(value); - if (timeoutMillis < 0) { - throw new IllegalArgumentException("Duration can't be negative"); - } - - return Duration.ofMillis(timeoutMillis); - }; - - private static final Function CONFIGURATION_PROPERTY_INTEGER_CONVERTER = Integer::valueOf; - private static final Function CONFIGURATION_PROPERTY_STRING_CONVERTER = Function.identity(); - - private final String name; - private final Function converter; - - private String[] aliases = EMPTY_ARRAY; - - private String environmentVariableName; - private String systemPropertyName; - private T defaultValue; - private boolean shared; - private Function valueSanitizer; - private boolean required; - - /** - * Creates default {@link ConfigurationPropertyBuilder}. String property values are redacted in logs by default. If - * property value does not contain sensitive information, use {@link ConfigurationPropertyBuilder#logValue} to - * enable logging. - * - * - *
        -     * ConfigurationProperty<String> property = ConfigurationPropertyBuilder.ofString("http.proxy.hostname")
        -     *     .shared(true)
        -     *     .logValue(true)
        -     *     .systemPropertyName("http.proxyHost")
        -     *     .build();
        -     *
        -     * // attempts to get local `my.sdk.<client-name>.http.proxy.host` property and falls back to
        -     * // shared my.sdk.http.proxy.port
        -     * System.out.println(configuration.get(property));
        -     * 
        - * - * - * @param name property name. - * @return instance of {@link ConfigurationPropertyBuilder}. - */ - public static ConfigurationPropertyBuilder ofString(String name) { - return new ConfigurationPropertyBuilder<>(name, CONFIGURATION_PROPERTY_STRING_CONVERTER); - } - - /** - * Creates {@link ConfigurationPropertyBuilder} configured to log property value and parse value using - * {@link Integer#valueOf(String)}, proxying {@link NumberFormatException} exception. - * - * - *
        -     * ConfigurationProperty<Integer> integerProperty = ConfigurationPropertyBuilder.ofInteger("retry-count")
        -     *     .build();
        -     * System.out.println(configuration.get(integerProperty));
        -     * 
        - * - * - * @param name property name. - * @return instance of {@link ConfigurationPropertyBuilder}. - */ - public static ConfigurationPropertyBuilder ofInteger(String name) { - return new ConfigurationPropertyBuilder<>(name, CONFIGURATION_PROPERTY_INTEGER_CONVERTER).logValue(true); - } - - /** - * Creates {@link ConfigurationPropertyBuilder} configured to log property value and parses value as long number of - * milliseconds, proxying {@link NumberFormatException} exception. - * - * - *
        -     * ConfigurationProperty<Duration> timeoutProperty = ConfigurationPropertyBuilder.ofDuration("timeout")
        -     *     .build();
        -     * System.out.println(configuration.get(timeoutProperty));
        -     * 
        - * - * - * @param name property name. - * @return instance of {@link ConfigurationPropertyBuilder}. - */ - public static ConfigurationPropertyBuilder ofDuration(String name) { - return new ConfigurationPropertyBuilder<>(name, CONFIGURATION_PROPERTY_DURATION_CONVERTER).logValue(true); - } - - /** - * Creates {@link ConfigurationPropertyBuilder} configured to log property value and parse value using - * {@link Boolean#parseBoolean(String)}. - * - * - *
        -     * ConfigurationProperty<Boolean> booleanProperty = ConfigurationPropertyBuilder.ofBoolean("is-enabled")
        -     *     .build();
        -     * System.out.println(configuration.get(booleanProperty));
        -     * 
        - * - * - * @param name property name. - * @return instance of {@link ConfigurationPropertyBuilder}. - */ - public static ConfigurationPropertyBuilder ofBoolean(String name) { - return new ConfigurationPropertyBuilder<>(name, CONFIGURATION_PROPERTY_BOOLEAN_CONVERTER).logValue(true); - } - - /** - * Constructs {@code ConfigurationPropertyBuilder} instance. - * - * - *
        -     * ConfigurationProperty<SampleEnumProperty> modeProperty =
        -     *     new ConfigurationPropertyBuilder<>("mode", SampleEnumProperty::fromString)
        -     *         .logValue(true)
        -     *         .defaultValue(SampleEnumProperty.MODE_1)
        -     *         .build();
        -     * System.out.println(configuration.get(modeProperty));
        -     * 
        - * - * - * @param name name of the property. - * @param converter Converter used to map the configuration to {@code T}. - */ - public ConfigurationPropertyBuilder(String name, Function converter) { - this.name = Objects.requireNonNull(name, "'name' cannot be null"); - this.converter = Objects.requireNonNull(converter, "'converter' cannot be null"); - } - - /** - * Sets default property value. {@code null} by default. - * - * @param defaultValue value to be returned by {@link Configuration#get(ConfigurationProperty)} if the property - * isn't found. - * @return the updated ConfigurationPropertyBuilder object. - */ - public ConfigurationPropertyBuilder defaultValue(T defaultValue) { - this.defaultValue = defaultValue; - return this; - } - - /** - * Sets flag indicating that property can be provided in the shared configuration section in addition to - * client-specific configuration section. Default is {@code false}, indicating that property can only be provided in - * local configuration. - * - * @param shared If set to {@code true}, {@link Configuration#get(ConfigurationProperty)} will attempt to retrieve - * property from local configuration and fall back to shared section, when local property is missing. Otherwise, - * only local configuration will be checked. - * @return the updated ConfigurationPropertyBuilder object. - */ - public ConfigurationPropertyBuilder shared(boolean shared) { - this.shared = shared; - return this; - } - - /** - * Sets flag indicating if property value can be logged. Default is {@code false}, indicating that property value - * should not be logged. When and if retrieving of corresponding configuration property is logged, - * {@link Configuration} will use "redacted" string instead of property value. If flag is set to {@code true}, value - * is populated on the logs as is. - * - * @param logValue If set to {@code true}, {@link Configuration#get(ConfigurationProperty)} will log property value, - * Otherwise, value is redacted. - * @return the updated ConfigurationPropertyBuilder object. - */ - public ConfigurationPropertyBuilder logValue(boolean logValue) { - if (logValue) { - this.valueSanitizer = PERMIT_VALUE_SANITIZER; - } - - return this; - } - - /** - * Sets flag indicating if property is required. Default is {@code false}, indicating that property is optional. - * - * @param required If set to {@code true}, {@link Configuration#get(ConfigurationProperty)} will throw when property - * is not found. - * @return the updated ConfigurationPropertyBuilder object. - */ - public ConfigurationPropertyBuilder required(boolean required) { - this.required = required; - return this; - } - - /** - * Sets one or more alias for property. {@link Configuration#get(ConfigurationProperty)} attempts to retrieve - * property by name first and only then tries to retrieve properties by alias in the order aliases are provided. - * - * @param aliases one or more alias for the property name. - * @return the updated ConfigurationPropertyBuilder object. - */ - public ConfigurationPropertyBuilder aliases(String... aliases) { - this.aliases = aliases; - return this; - } - - /** - * Sets environment variable name that can represent this property if explicit configuration is not set. - * - *

        - * When property value is not found by {@code name} or {@code alias}, - * {@link Configuration#get(ConfigurationProperty)} falls back to system properties and environment variables. - *

        - * When environment variable (or system property) is not set, {@link Configuration#get(ConfigurationProperty)} does - * not attempt to read environment configuration. - * - * @param environmentVariableName environment variable name. - * @return the updated ConfigurationPropertyBuilder object. - */ - public ConfigurationPropertyBuilder environmentVariableName(String environmentVariableName) { - this.environmentVariableName = environmentVariableName; - return this; - } - - /** - * Sets system property name that can represent this property if explicit configuration is not set. - * - *

        - * When property value is not found by {@code name} or {@code alias}, - * {@link Configuration#get(ConfigurationProperty)} falls back to system properties and environment variables. - *

        - * When environment variable (or system property) is not set, {@link Configuration#get(ConfigurationProperty)} does - * not attempt to read environment configuration. - * - * @param systemPropertyName one or more environment variable (or system property). - * @return the updated ConfigurationPropertyBuilder object. - */ - public ConfigurationPropertyBuilder systemPropertyName(String systemPropertyName) { - this.systemPropertyName = systemPropertyName; - return this; - } - - /** - * Builds configuration property instance. - * - * @return {@link ConfigurationProperty} instance. - */ - public ConfigurationProperty build() { - return new ConfigurationProperty<>(name, defaultValue, required, converter, shared, environmentVariableName, - systemPropertyName, aliases, valueSanitizer); - } -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/configuration/ConfigurationSource.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/util/configuration/ConfigurationSource.java deleted file mode 100644 index 1d0887ed3060..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/configuration/ConfigurationSource.java +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.util.configuration; - -import java.util.Map; - -/** - * Configuration property source which provides configuration values from a specific place. Samples may include - * properties file supported by frameworks or other source. - * - * Note that environment configuration (environment variables and system properties) are supported by default and - * don't need a source implementation. - */ -@FunctionalInterface -public interface ConfigurationSource { - /** - * Returns all properties (name and value) which names start with given path. - * Null (or empty) path indicate that all properties should be returned. - * - * Example: - *

        - * With following configuration properties: - *

          - *
        • sdk.foo = 1
        • - *
        • sdk.bar.baz = 2
        • - *
        - * - *

        - * {@link ConfigurationSource} implementation must the following behavior: - *

          - *
        • {@code getProperties(null} must return both properties
        • - *
        • {@code getProperties("sdk")} must return both properties
        • - *
        • {@code getProperties("sdk.foo")} must return {"sdk.foo", "1"}
        • - *
        • {@code getProperties("sdk.ba")} must return empty map
        • - *
        - * - * @param source property name prefix - * @return Map of properties under given path. - */ - Map getProperties(String source); -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/configuration/NoopConfiguration.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/util/configuration/NoopConfiguration.java deleted file mode 100644 index 49d638041faa..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/configuration/NoopConfiguration.java +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package io.clientcore.core.util.configuration; - -import io.clientcore.core.implementation.util.EnvironmentConfiguration; - -import java.util.function.Function; - -/* - * Noop Configuration used to opt out of using global configurations when constructing client libraries. - */ -class NoopConfiguration extends Configuration { - - /** - * Constructs a configuration containing the known properties constants. Use {@link ConfigurationBuilder} to create - * instance of {@link Configuration}. - * - * @param configurationSource Configuration property source. - * @param environmentConfiguration instance of {@link EnvironmentConfiguration} to mock environment for testing. - * @param path Absolute path of current configuration section for logging and diagnostics purposes. - * @param sharedConfiguration Instance of shared {@link Configuration} section to retrieve shared properties. - */ - NoopConfiguration(ConfigurationSource configurationSource, EnvironmentConfiguration environmentConfiguration, - String path, Configuration sharedConfiguration) { - super(configurationSource, environmentConfiguration, path, sharedConfiguration); - } - - @Override - public String get(String name) { - return null; - } - - @Override - public T get(String name, T defaultValue) { - return defaultValue; - } - - @Override - public T get(String name, Function converter) { - return null; - } - - @Override - public boolean contains(String name) { - return false; - } -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/configuration/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/util/configuration/package-info.java deleted file mode 100644 index 742fe8174a58..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/configuration/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - * Package containing interfaces describing configuration information that is used during construction of client - * libraries. - */ -package io.clientcore.core.util.configuration; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/util/package-info.java deleted file mode 100644 index 68f73cb1ca92..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - * Package containing core utility classes. - */ -package io.clientcore.core.util; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/serializer/ObjectSerializer.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/util/serializer/ObjectSerializer.java deleted file mode 100644 index d9320d7b6acf..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/serializer/ObjectSerializer.java +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.util.serializer; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.reflect.Type; - -/** - * Generic interface covering serializing and deserialization objects. - */ -public interface ObjectSerializer { - /** - * Reads a byte array into its object representation. - * - * @param data The byte array. - * @param type {@link Type} representing the object. - * @param Type of the object. - * @return The object represented by the deserialized byte array. - * @throws IOException If the deserialization fails. - */ - T deserializeFromBytes(byte[] data, Type type) throws IOException; - - /** - * Reads a stream into its object representation. - * - * @param stream {@link InputStream} of data. - * @param type {@link Type} representing the object. - * @param Type of the object. - * @return The object represented by the deserialized stream. - * @throws IOException If the deserialization fails. - */ - T deserializeFromStream(InputStream stream, Type type) throws IOException; - - /** - * Serializes an object into a byte array. - * - * @param value The object to serialize. - * @return The binary representation of the serialized object. - * @throws IOException If the serialization fails. - */ - byte[] serializeToBytes(Object value) throws IOException; - - /** - * Serializes and writes an object into a provided stream. - * - * @param stream {@link OutputStream} where the serialized object will be written. - * @param value The object to serialize. - * @throws IOException If the serialization fails. - */ - void serializeToStream(OutputStream stream, Object value) throws IOException; - - /** - * Indicates whether the given implementation of {@link ObjectSerializer} supports the provided format. - *

        - * An implementation of {@link ObjectSerializer} may support multiple formats, such as JSON and XML. - *

        - * A check for support should be made before attempting to serialize or deserialize an object. - * - * @param format The format to check support for. - * @return Whether the format is supported. - */ - boolean supportsFormat(SerializationFormat format); -} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/serializer/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/util/serializer/package-info.java deleted file mode 100644 index c811c51eaa65..000000000000 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/serializer/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - * Package containing interfaces describing serialization and deserialization contract. - */ -package io.clientcore.core.util.serializer; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/auth/AuthUtils.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/AuthUtils.java similarity index 81% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/util/auth/AuthUtils.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/utils/AuthUtils.java index e4d520d1a5ec..003f0cfb68b9 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/auth/AuthUtils.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/AuthUtils.java @@ -1,11 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.util.auth; +package io.clientcore.core.utils; import io.clientcore.core.http.models.HttpHeaderName; import io.clientcore.core.http.models.HttpHeaders; -import io.clientcore.core.implementation.util.ImplUtils; +import io.clientcore.core.implementation.utils.AuthenticateChallengeParser; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; @@ -20,6 +20,8 @@ import java.util.function.Function; import java.util.stream.Collectors; +import static io.clientcore.core.utils.CoreUtils.isNullOrEmpty; + /** * Utility class for handling various authentication-related operations. */ @@ -27,45 +29,75 @@ public final class AuthUtils { /** * Suffix used for session-based algorithms. */ - public static final String SESS = "-SESS"; + static final String SESS = "-SESS"; /** * MD5 hashing algorithm. */ - public static final String MD5 = "MD5"; + static final String MD5 = "MD5"; /** * SHA-512-256 hashing algorithm. */ - public static final String SHA_512_256 = "SHA-512-256"; + static final String SHA_512_256 = "SHA-512-256"; /** * Key for the algorithm parameter in authentication headers. */ - public static final String ALGORITHM = "algorithm"; + static final String ALGORITHM = "algorithm"; /** * Key for the next nonce parameter in authentication headers. */ - public static final String NEXT_NONCE = "nextnonce"; + static final String NEXT_NONCE = "nextnonce"; /** * Basic authentication scheme. */ - public static final String BASIC = "Basic"; + static final String BASIC = "Basic"; /** * Digest authentication scheme. */ - public static final String DIGEST = "Digest"; + static final String DIGEST = "Digest"; private AuthUtils() { // Utility class should not be instantiated } /** - * Calculates the 'HA1' hex string when using an algorithm that isn't a '-sess' variant. + * Processes an authenticate header, such as {@link HttpHeaderName#WWW_AUTHENTICATE} or + * {@link HttpHeaderName#PROXY_AUTHENTICATE}, into a list of {@link AuthenticateChallenge}. + *

        + * If the {@code authenticateHeader} is null or empty an empty list will be returned. + *

        + * This method will parse the authenticate header as plainly as possible, meaning no casing will be changed on the + * scheme and no decoding will be done on the parameters. The only processing done is removal of quotes around + * parameter values and backslashes escaping values. Ex, {@code "va\"lue"} will be parsed as {@code va"lue}. + *

        + * In addition to processing as plainly as possible, this method will not validate the authenticate header, it will + * only parse it. Though, if the authenticate header has syntax errors an {@link IllegalStateException} will be + * thrown. + *

        + * A list of {@link AuthenticateChallenge} will be returned as it is valid for multiple authenticate challenges to + * use the same scheme, therefore a map cannot be used as the scheme would be the key and only one challenge would + * be stored. * + * @param authenticateHeader The authenticate header to be parsed. + * @return A list of authenticate challenges. + * @throws IllegalArgumentException If the {@code authenticateHeader} has syntax errors. + */ + public static List parseAuthenticateHeader(String authenticateHeader) { + if (isNullOrEmpty(authenticateHeader)) { + return Collections.emptyList(); + } + + return new AuthenticateChallengeParser(authenticateHeader).parse(); + } + + /** + * Calculates the 'HA1' hex string when using an algorithm that isn't a '-sess' variant. + *

        * This performs the following operations: * - Create the digest of (username + ":" + realm + ":" password). * - Return the resulting bytes as a hex string. @@ -76,7 +108,7 @@ private AuthUtils() { * @param password The password. * @return The HA1 hex string. */ - public static String calculateHa1NoSess(Function digestFunction, String username, String realm, + static String calculateHa1NoSess(Function digestFunction, String username, String realm, String password) { return bytesToHexString( digestFunction.apply((username + ":" + realm + ":" + password).getBytes(StandardCharsets.UTF_8))); @@ -84,7 +116,7 @@ public static String calculateHa1NoSess(Function digestFunction, /** * Calculates the 'HA1' hex string when using a '-sess' algorithm variant. - * + *

        * This performs the following operations: * - Create the digest of (username + ":" + realm + ":" password). * - Convert the resulting bytes to a hex string, aliased as userPassHex. @@ -99,7 +131,7 @@ public static String calculateHa1NoSess(Function digestFunction, * @param cnonce The client-specified nonce. * @return The HA1 hex string. */ - public static String calculateHa1Sess(Function digestFunction, String username, String realm, + static String calculateHa1Sess(Function digestFunction, String username, String realm, String password, String nonce, String cnonce) { String ha1NoSess = calculateHa1NoSess(digestFunction, username, realm, password); @@ -109,7 +141,7 @@ public static String calculateHa1Sess(Function digestFunction, S /** * Calculates the 'HA2' hex string when using 'qop=auth' or the qop is unknown. - * + *

        * This performs the following operations: * - Create the digest of (httpMethod + ":" + uri). * - Return the resulting bytes as a hex string. @@ -119,20 +151,19 @@ public static String calculateHa1Sess(Function digestFunction, S * @param uri The request URI. * @return The HA2 hex string. */ - public static String calculateHa2AuthQopOrEmpty(Function digestFunction, String httpMethod, - String uri) { + static String calculateHa2AuthQopOrEmpty(Function digestFunction, String httpMethod, String uri) { return bytesToHexString(digestFunction.apply((httpMethod + ":" + uri).getBytes(StandardCharsets.UTF_8))); } /** * Calculates the 'HA2' hex string when using 'qop=auth-int'. - * + *

        * This performs the following operations: * - Create the digest of (requestEntityBody). * - Convert the resulting bytes to a hex string, aliased as bodyHex. * - Create the digest of (httpMethod + ":" + uri + ":" bodyHex). * - Return the resulting bytes as a hex string. - * + *

        * The request entity body is the unmodified body of the request. Using 'qop=auth-int' requires the request body to * be replay-able, this is why 'auth' is preferred instead of auth-int as this cannot be guaranteed. In addition to * the body being replay-able this runs into risks when the body is very large and potentially consuming large @@ -144,7 +175,7 @@ public static String calculateHa2AuthQopOrEmpty(Function digestF * @param requestEntityBody The request entity body. * @return The HA2 hex string. */ - public static String calculateHa2AuthIntQop(Function digestFunction, String httpMethod, String uri, + static String calculateHa2AuthIntQop(Function digestFunction, String httpMethod, String uri, byte[] requestEntityBody) { String bodyHex = bytesToHexString(digestFunction.apply(requestEntityBody)); @@ -154,7 +185,7 @@ public static String calculateHa2AuthIntQop(Function digestFunct /** * Calculates the 'response' hex string when qop is unknown. - * + *

        * This performs the following operations: * - Create the digest of (ha1 + ":" + nonce + ":" + ha2). * - Return the resulting bytes as a hex string. @@ -165,18 +196,18 @@ public static String calculateHa2AuthIntQop(Function digestFunct * @param ha2 The HA2 hex string. * @return The response hex string. */ - public static String calculateResponseUnknownQop(Function digestFunction, String ha1, String nonce, + static String calculateResponseUnknownQop(Function digestFunction, String ha1, String nonce, String ha2) { return bytesToHexString(digestFunction.apply((ha1 + ":" + nonce + ":" + ha2).getBytes(StandardCharsets.UTF_8))); } /** * Calculates the 'response' hex string when 'qop=auth' or 'qop=auth-int'. - * + *

        * This performs the following operations: * - Create the digest of (ha1 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + ha2). * - Return the resulting byes as a hex string. - * + *

        * nc, nonce count, is represented in a hexadecimal format. * * @param digestFunction The function to compute the digest. @@ -188,8 +219,8 @@ public static String calculateResponseUnknownQop(Function digest * @param ha2 The HA2 hex string. * @return The response hex string. */ - public static String calculateResponseKnownQop(Function digestFunction, String ha1, String nonce, - int nc, String cnonce, String qop, String ha2) { + static String calculateResponseKnownQop(Function digestFunction, String ha1, String nonce, int nc, + String cnonce, String qop, String ha2) { String zeroPadNc = String.format("%08X", nc); return bytesToHexString( @@ -205,7 +236,7 @@ public static String calculateResponseKnownQop(Function digestFu * @param realm The authentication realm. * @return The hashed username value. */ - public static String calculateUserhash(Function digestFunction, String username, String realm) { + static String calculateUserhash(Function digestFunction, String username, String realm) { return bytesToHexString(digestFunction.apply((username + ":" + realm).getBytes(StandardCharsets.UTF_8))); } @@ -215,7 +246,7 @@ public static String calculateUserhash(Function digestFunction, * @param algorithm The algorithm name. * @return The digest function, or null if the algorithm is not supported. */ - public static Function getDigestFunction(String algorithm) { + static Function getDigestFunction(String algorithm) { if (algorithm.toUpperCase(Locale.ROOT).endsWith(SESS)) { algorithm = algorithm.substring(0, algorithm.length() - SESS.length()); } @@ -243,7 +274,7 @@ public static Function getDigestFunction(String algorithm) { * @param bytes The byte array to convert. * @return The hex string representation of the byte array. */ - public static String bytesToHexString(byte[] bytes) { + static String bytesToHexString(byte[] bytes) { StringBuilder hexString = new StringBuilder(bytes.length * 2); for (byte b : bytes) { String hex = Integer.toHexString(0xFF & b); @@ -261,7 +292,7 @@ public static String bytesToHexString(byte[] bytes) { * @param authenticationInfoMap The map containing key-value pairs from the Authentication-Info header. * @return The next nonce value if present, otherwise null. */ - public static String processAuthenticationInfoHeader(Map authenticationInfoMap) { + static String processAuthenticationInfoHeader(Map authenticationInfoMap) { if (authenticationInfoMap == null || authenticationInfoMap.isEmpty()) { return null; } @@ -308,7 +339,7 @@ public static Map parseAuthenticationOrAuthorizationHeader(Strin * @param headers The HTTP headers containing the challenges. * @return A map of challenges partitioned by their algorithm. */ - public static Map>> partitionByChallengeType(HttpHeaders headers) { + static Map>> partitionByChallengeType(HttpHeaders headers) { // Extract the challenges from the headers, specifically the "Proxy-Authenticate" or "WWW-Authenticate" headers List> challenges = extractAllChallenges(headers); @@ -320,35 +351,13 @@ public static Map>> partitionByChallengeType(Ht })); } - /** - * Checks if the character sequence is null or empty. - * - * @param charSequence Character sequence being checked for nullness or emptiness. - * - * @return True if the character sequence is null or empty, false otherwise. - */ - public static boolean isNullOrEmpty(CharSequence charSequence) { - return charSequence == null || charSequence.length() == 0; - } - - /** - * Checks if the map is null or empty. - * - * @param map Map being checked for nullness or emptiness. - * - * @return True if the map is null or empty, false otherwise. - */ - public static boolean isNullOrEmpty(Map map) { - return map == null || map.isEmpty(); - } - /** * Parses challenges from the provided {@link HttpHeaders}. * * @param headers The {@link HttpHeaders} that may contain challenge information. * @return A list of parsed challenges as Map. */ - public static List> parseChallenges(HttpHeaders headers) { + static List> parseChallenges(HttpHeaders headers) { List authenticateHeaders = new ArrayList<>(); if (headers.getValue(HttpHeaderName.WWW_AUTHENTICATE) != null) { @@ -376,7 +385,7 @@ public static List> parseChallenges(HttpHeaders headers) { * @param headers The HTTP headers containing the challenges. * @return A list of parsed challenges as Map. */ - public static List> extractAllChallenges(HttpHeaders headers) { + static List> extractAllChallenges(HttpHeaders headers) { // Extract challenges from all relevant header fields List> challenges = new ArrayList<>(); @@ -397,7 +406,7 @@ public static List> extractAllChallenges(HttpHeaders headers * @param challengeHeader The header value containing the challenge. * @return The parsed challenge as a Map. */ - public static Map parseChallenge(String challengeHeader) { + static Map parseChallenge(String challengeHeader) { Map challengeMap = new HashMap<>(); // Split the challenge into scheme and parameters. @@ -444,7 +453,7 @@ public static Map parseChallenge(String challengeHeader) { * @param key The key whose value needs to be extracted. * @return The extracted value, or null if the key is not found. */ - public static String extractValue(String authHeader, String key) { + static String extractValue(String authHeader, String key) { if (authHeader == null || !authHeader.startsWith("Digest")) { return null; } @@ -484,8 +493,8 @@ public static String extractValue(String authHeader, String key) { * @param userhash Whether the username is hashed. * @return The constructed Authorization/Proxy-Authorization header value. */ - public static String buildAuthorizationHeader(String username, String realm, String uri, String algorithm, - String nonce, int nc, String cnonce, String qop, String response, String opaque, boolean userhash) { + static String buildAuthorizationHeader(String username, String realm, String uri, String algorithm, String nonce, + int nc, String cnonce, String qop, String response, String opaque, boolean userhash) { StringBuilder authorizationBuilder = new StringBuilder(512); authorizationBuilder.append(DIGEST + " ") @@ -505,19 +514,19 @@ public static String buildAuthorizationHeader(String username, String realm, Str .append(response) .append("\""); - if (!ImplUtils.isNullOrEmpty(algorithm)) { + if (!CoreUtils.isNullOrEmpty(algorithm)) { authorizationBuilder.append(", algorithm=").append(algorithm); } - if (!ImplUtils.isNullOrEmpty(cnonce)) { + if (!CoreUtils.isNullOrEmpty(cnonce)) { authorizationBuilder.append(", cnonce=\"").append(cnonce).append("\""); } - if (!ImplUtils.isNullOrEmpty(opaque)) { + if (!CoreUtils.isNullOrEmpty(opaque)) { authorizationBuilder.append(", opaque=\"").append(opaque).append("\""); } - if (!ImplUtils.isNullOrEmpty(qop)) { + if (!CoreUtils.isNullOrEmpty(qop)) { authorizationBuilder.append(", qop=").append(qop); authorizationBuilder.append(", nc=").append(java.lang.String.format("%08X", nc)); } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/AuthenticateChallenge.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/AuthenticateChallenge.java new file mode 100644 index 000000000000..14d148f964e5 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/AuthenticateChallenge.java @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.utils; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.instrumentation.logging.ClientLogger; + +import java.util.Collections; +import java.util.Map; + +/** + * An authenticate challenge. + *

        + * This challenge can be from any source, but will primarily be from parsing {@link HttpHeaderName#WWW_AUTHENTICATE} or + * {@link HttpHeaderName#PROXY_AUTHENTICATE} headers using {@link AuthUtils#parseAuthenticateHeader(String)}. + *

        + * Some challenge information may be optional, meaning the getters may return null or an empty collection. + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public final class AuthenticateChallenge { + private static final ClientLogger LOGGER = new ClientLogger(AuthenticateChallenge.class); + + private final String scheme; + private final Map parameters; + private final String token68; + + /** + * Creates an instance of the AuthenticateChallenge. + * + * @param scheme The scheme of the challenge. + * @throws IllegalArgumentException If the scheme is null or empty. + */ + public AuthenticateChallenge(String scheme) { + this(scheme, Collections.emptyMap(), null); + } + + /** + * Creates an instance of the AuthenticateChallenge. + * + * @param scheme The scheme of the challenge. + * @param token68 The token68 of the challenge. + * @throws IllegalArgumentException If the scheme is null or empty. + */ + public AuthenticateChallenge(String scheme, String token68) { + this(scheme, Collections.emptyMap(), token68); + } + + /** + * Creates an instance of the AuthenticateChallenge. + * + * @param scheme The scheme of the challenge. + * @param parameters The parameters of the challenge. + * @throws IllegalArgumentException If the scheme is null or empty. + */ + public AuthenticateChallenge(String scheme, Map parameters) { + this(scheme, parameters, null); + } + + AuthenticateChallenge(String scheme, Map parameters, String token68) { + if (scheme == null || scheme.isEmpty()) { + throw LOGGER.logThrowableAsError(new IllegalArgumentException("scheme cannot be null or empty.")); + } + + this.scheme = scheme; + this.parameters = Collections.unmodifiableMap(parameters); + this.token68 = token68; + } + + /** + * Gets the scheme of the challenge. + * + * @return The scheme of the challenge. + */ + public String getScheme() { + return scheme; + } + + /** + * Gets the parameters of the challenge as a read-only map. + *

        + * This map will be empty if the challenge does not have any parameters. + * + * @return The parameters of the challenge. + */ + public Map getParameters() { + return parameters; + } + + /** + * Gets the token68 of the challenge. + *

        + * This may be null if the challenge does not have a token68. + * + * @return The token68 of the challenge, or null if the challenge does not have a token68. + */ + public String getToken68() { + return token68; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/Base64Uri.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/Base64Uri.java similarity index 84% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/Base64Uri.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/utils/Base64Uri.java index 6240b3d68995..c95b6235eb03 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/Base64Uri.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/Base64Uri.java @@ -1,12 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.implementation.util; +package io.clientcore.core.utils; import java.nio.charset.StandardCharsets; import java.util.Arrays; +import java.util.Base64; -import static io.clientcore.core.implementation.util.ImplUtils.isNullOrEmpty; +import static io.clientcore.core.utils.CoreUtils.isNullOrEmpty; /** * Encodes and decodes using Base64 URI encoding. @@ -77,10 +78,19 @@ public static Base64Uri encode(byte[] bytes) { if (bytes == null) { return new Base64Uri((String) null); } else { - return new Base64Uri(Base64Util.encodeURIWithoutPadding(bytes)); + return new Base64Uri(encodeURIWithoutPadding(bytes)); } } + /** + * Encodes a byte array to base64 URI format. + * @param src the byte array to encode + * @return the base64 URI encoded bytes + */ + private static byte[] encodeURIWithoutPadding(byte[] src) { + return src == null ? null : Base64.getUrlEncoder().withoutPadding().encode(src); + } + /** * Returns the underlying encoded byte array. * @@ -91,11 +101,7 @@ public byte[] encodedBytes() { return null; } - byte[] copy = new byte[bytes.length]; - - System.arraycopy(bytes, 0, copy, 0, bytes.length); - - return copy; + return CoreUtils.arrayCopy(bytes); } /** @@ -108,7 +114,7 @@ public byte[] decodedBytes() { return null; } - return Base64Util.decodeURI(bytes); + return Base64.getUrlDecoder().decode(bytes); } @Override diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/BasicChallengeHandler.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/BasicChallengeHandler.java new file mode 100644 index 000000000000..39875ee2f436 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/BasicChallengeHandler.java @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.utils; + +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.models.binarydata.BinaryData; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.List; + +import static io.clientcore.core.utils.AuthUtils.BASIC; + +/** + * Handles basic authentication challenges. + * This class implements the `ChallengeHandler` interface and provides + * functionality to handle HTTP Basic Authentication challenges. + */ +public class BasicChallengeHandler implements ChallengeHandler { + + private final String authHeader; + + /** + * Constructs a `BasicChallengeHandler` with the specified username and password. + * + * @param username The username for basic authentication. + * @param password The password for basic authentication. + */ + public BasicChallengeHandler(String username, String password) { + String token = username + ":" + password; + this.authHeader = "Basic " + Base64.getEncoder().encodeToString(token.getBytes(StandardCharsets.UTF_8)); + } + + @Override + public void handleChallenge(HttpRequest request, Response response, boolean isProxy) { + if (canHandle(response, isProxy)) { + synchronized (request.getHeaders()) { + HttpHeaderName headerName = isProxy ? HttpHeaderName.PROXY_AUTHORIZATION : HttpHeaderName.AUTHORIZATION; + // Check if the appropriate Authorization header is already present + if (request.getHeaders().getValue(headerName) == null) { + request.getHeaders().add(headerName, authHeader); + } + } + } + } + + @Override + public boolean canHandle(Response response, boolean isProxy) { + if (response.getHeaders() != null) { + HttpHeaderName authHeaderName + = isProxy ? HttpHeaderName.PROXY_AUTHENTICATE : HttpHeaderName.WWW_AUTHENTICATE; + String authHeader = response.getHeaders().getValue(authHeaderName); + + if (authHeader != null) { + // Parse the authenticate header into AuthenticateChallenges, then check if any use scheme 'Basic'. + List challenges = AuthUtils.parseAuthenticateHeader(authHeader); + for (AuthenticateChallenge challenge : challenges) { + if (BASIC.equalsIgnoreCase(challenge.getScheme())) { + return true; + } + } + } + } + return false; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/auth/ChallengeHandler.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/ChallengeHandler.java similarity index 84% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/util/auth/ChallengeHandler.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/utils/ChallengeHandler.java index 1a3735fdcc9f..c3b0278de5f8 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/auth/ChallengeHandler.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/ChallengeHandler.java @@ -1,10 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.util.auth; +package io.clientcore.core.utils; import io.clientcore.core.http.models.HttpRequest; import io.clientcore.core.http.models.Response; +import io.clientcore.core.models.binarydata.BinaryData; import java.util.Arrays; @@ -19,7 +20,7 @@ public interface ChallengeHandler { * @param response The HTTP response containing the authentication challenge. * @param isProxy Indicates if the challenge is for a proxy. */ - void handleChallenge(HttpRequest request, Response response, boolean isProxy); + void handleChallenge(HttpRequest request, Response response, boolean isProxy); /** * Validate if this ChallengeHandler can handle the provided challenge @@ -29,7 +30,7 @@ public interface ChallengeHandler { * @param isProxy boolean indicating if it is a proxy challenge handler. * @return boolean indicating if the challenge can be handled. */ - boolean canHandle(Response response, boolean isProxy); + boolean canHandle(Response response, boolean isProxy); /** * Factory method for creating composite handlers. diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/ClientOptions.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/ClientOptions.java new file mode 100644 index 000000000000..c60b6c0b4d83 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/ClientOptions.java @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.utils; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.http.pipeline.UserAgentPolicy; +import io.clientcore.core.instrumentation.InstrumentationOptions; +import io.clientcore.core.instrumentation.logging.ClientLogger; + +/** + * General configuration options for clients. + */ +@Metadata(properties = MetadataProperties.FLUENT) +public class ClientOptions { + private static final String INVALID_APPLICATION_ID_SPACE = "'applicationId' cannot contain spaces."; + + // ClientOptions is a commonly used class, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(ClientOptions.class); + + private String applicationId; + private InstrumentationOptions instrumentationOptions; + + /** + * Creates a new instance of {@link ClientOptions}. + */ + public ClientOptions() { + } + + /** + * Gets the application ID. + *

        + * The {@code applicationId} is used to configure {@link UserAgentPolicy} for telemetry/monitoring purposes. + * + * @return The application ID. + */ + public String getApplicationId() { + return applicationId; + } + + /** + * Sets the application ID. + *

        + * The {@code applicationId} is used to configure {@link UserAgentPolicy} for telemetry/monitoring purposes. + * + *

        Code Samples

        + * + *

        Create ClientOptions with application ID 'myApplicationId'

        + * + * + *
        +     * ClientOptions clientOptions = new ClientOptions()
        +     *     .setApplicationId("myApplicationId");
        +     * 
        + * + * + * @param applicationId The application ID. + * @return The updated ClientOptions object. + * @throws IllegalArgumentException If {@code applicationId} contains spaces. + */ + public ClientOptions setApplicationId(String applicationId) { + if (!CoreUtils.isNullOrEmpty(applicationId)) { + if (applicationId.contains(" ")) { + throw LOGGER.logThrowableAsError(new IllegalArgumentException(INVALID_APPLICATION_ID_SPACE)); + } + } + + this.applicationId = applicationId; + return this; + } + + /** + * Sets the {@link InstrumentationOptions} that are used to apply instrumentation to the client. + * + * @param instrumentationOptions instance of {@link InstrumentationOptions} to set. + * @return The updated {@link ClientOptions} object. + */ + public ClientOptions setInstrumentationOptions(InstrumentationOptions instrumentationOptions) { + this.instrumentationOptions = instrumentationOptions; + return this; + } + + /** + * Gets the {@link InstrumentationOptions} that are used to apply instrumentation to the client. + * + * @return The {@link InstrumentationOptions} that are used to apply instrumentation to the client. + */ + public InstrumentationOptions getInstrumentationOptions() { + return instrumentationOptions; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/auth/CompositeChallengeHandler.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/CompositeChallengeHandler.java similarity index 86% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/util/auth/CompositeChallengeHandler.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/utils/CompositeChallengeHandler.java index 2dfd99822358..fd655f8bd8e9 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/auth/CompositeChallengeHandler.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/CompositeChallengeHandler.java @@ -1,10 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.util.auth; +package io.clientcore.core.utils; import io.clientcore.core.http.models.HttpRequest; import io.clientcore.core.http.models.Response; import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.models.binarydata.BinaryData; import java.util.List; @@ -18,7 +19,7 @@ final class CompositeChallengeHandler implements ChallengeHandler { } @Override - public boolean canHandle(Response response, boolean isProxy) { + public boolean canHandle(Response response, boolean isProxy) { for (ChallengeHandler handler : challengeHandlers) { if (handler.canHandle(response, isProxy)) { return true; @@ -28,7 +29,7 @@ public boolean canHandle(Response response, boolean isProxy) { } @Override - public void handleChallenge(HttpRequest request, Response response, boolean isProxy) { + public void handleChallenge(HttpRequest request, Response response, boolean isProxy) { // First, try to handle with DigestChallengeHandler, giving it priority for (ChallengeHandler handler : challengeHandlers) { if (handler.canHandle(response, isProxy) && handler instanceof DigestChallengeHandler) { diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/Context.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/Context.java similarity index 95% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/util/Context.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/utils/Context.java index b126a11d0839..785fe59a64d1 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/Context.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/Context.java @@ -1,15 +1,15 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.util; +package io.clientcore.core.utils; -import io.clientcore.core.annotation.Metadata; -import io.clientcore.core.implementation.util.InternalContext; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.implementation.utils.InternalContext; import io.clientcore.core.instrumentation.logging.ClientLogger; import java.util.Map; -import static io.clientcore.core.annotation.TypeConditions.IMMUTABLE; +import static io.clientcore.core.annotations.MetadataProperties.IMMUTABLE; /** * {@code Context} offers a means of passing arbitrary data (key-value pairs). @@ -19,7 +19,7 @@ * The old value will still exist within the Context but if you don't have a reference to a previous state it won't be * accessible. */ -@Metadata(conditions = IMMUTABLE) +@Metadata(properties = IMMUTABLE) public final class Context { // Context is a highly used, short-lived class, use a static logger. private static final ClientLogger LOGGER = new ClientLogger(Context.class); diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/CoreUtils.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/CoreUtils.java new file mode 100644 index 000000000000..1717d034e107 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/CoreUtils.java @@ -0,0 +1,378 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.utils; + +import io.clientcore.core.instrumentation.logging.ClientLogger; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.time.DateTimeException; +import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.time.temporal.TemporalAccessor; +import java.time.temporal.TemporalQueries; +import java.time.temporal.TemporalQuery; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Properties; +import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +/** + * Utility class containing shared code for the SDK. + */ +public final class CoreUtils { + private static final ClientLogger LOGGER = new ClientLogger(CoreUtils.class); + + private static final char[] LOWERCASE_HEX_CHARACTERS = "0123456789abcdef".toCharArray(); + + // Used to check if the ISO8601 date time doesn't have a colon in the offset. + private static final Pattern ISO8601_COLONLESS_OFFSET = Pattern.compile("([+-][0-9]{2})([0-9]{2})(?=\\[|$)"); + + /** + * Checks if the array is null or empty. + * + * @param array Array being checked for nullness or emptiness. + * @return True if the array is null or empty, false otherwise. + */ + public static boolean isNullOrEmpty(Object[] array) { + return array == null || array.length == 0; + } + + /** + * Checks if the collection is null or empty. + * + * @param collection Collection being checked for nullness or emptiness. + * @return True if the collection is null or empty, false otherwise. + */ + public static boolean isNullOrEmpty(Collection collection) { + return collection == null || collection.isEmpty(); + } + + /** + * Checks if the map is null or empty. + * + * @param map Map being checked for nullness or emptiness. + * @return True if the map is null or empty, false otherwise. + */ + public static boolean isNullOrEmpty(Map map) { + return map == null || map.isEmpty(); + } + + /** + * Checks if the character sequence is null or empty. + * + * @param charSequence Character sequence being checked for nullness or emptiness. + * @return True if the character sequence is null or empty, false otherwise. + */ + public static boolean isNullOrEmpty(CharSequence charSequence) { + return charSequence == null || charSequence.length() == 0; + } + + /** + * Creates a copy of the source byte array. + * + * @param source Array to make copy of + * @return A copy of the array, or null if source was null. + */ + public static byte[] arrayCopy(byte[] source) { + if (source == null) { + return null; + } + + return Arrays.copyOf(source, source.length); + } + + /** + * Creates a copy of the source int array. + * + * @param source Array to make copy of + * @return A copy of the array, or null if source was null. + */ + public static int[] arrayCopy(int[] source) { + if (source == null) { + return null; + } + + return Arrays.copyOf(source, source.length); + } + + /** + * Creates a copy of the source array. + * + * @param source Array being copied. + * @param Generic representing the type of the source array. + * @return A copy of the array or null if source was null. + */ + public static T[] arrayCopy(T[] source) { + if (source == null) { + return null; + } + + return Arrays.copyOf(source, source.length); + } + + /** + * Creates a type 4 (pseudo randomly generated) UUID. + *

        + * The {@link UUID} is generated using a non-cryptographically strong pseudo random number generator. + * + * @return A randomly generated {@link UUID}. + */ + public static UUID randomUuid() { + return randomUuid(ThreadLocalRandom.current().nextLong(), ThreadLocalRandom.current().nextLong()); + } + + static UUID randomUuid(long msb, long lsb) { + msb &= 0xffffffffffff0fffL; // Clear the UUID version. + msb |= 0x0000000000004000L; // Set the UUID version to 4. + lsb &= 0x3fffffffffffffffL; // Clear the variant. + lsb |= 0x8000000000000000L; // Set the variant to IETF. + + // Use new UUID(long, long) instead of UUID.randomUUID as UUID.randomUUID may be blocking. + // For environments using Reactor's BlockHound this will raise an exception if called in non-blocking threads. + return new UUID(msb, lsb); + } + + /** + * Helper method that returns an immutable {@link Map} of properties defined in {@code propertiesFileName}. + * + * @param propertiesFileName The file name defining the properties. + * @return an immutable {@link Map}. + */ + public static Map getProperties(String propertiesFileName) { + try (InputStream inputStream = CoreUtils.class.getClassLoader().getResourceAsStream(propertiesFileName)) { + if (inputStream != null) { + Properties properties = new Properties(); + properties.load(inputStream); + return Collections.unmodifiableMap(properties.entrySet() + .stream() + .collect(Collectors.toMap(entry -> (String) entry.getKey(), entry -> (String) entry.getValue()))); + } + } catch (IOException ex) { + LOGGER.atWarning().log("Failed to get properties from " + propertiesFileName, ex); + } + + return Collections.emptyMap(); + } + + /** + * Converts a byte array into a hex string. + * + *

        The hex string returned uses characters {@code 0123456789abcdef}, if uppercase {@code ABCDEF} is required the + * returned string will need to be {@link String#toUpperCase() uppercased}.

        + * + *

        If {@code bytes} is null, null will be returned. If {@code bytes} was an empty array an empty string is + * returned.

        + * + * @param bytes The byte array to convert into a hex string. + * @return A hex string representing the {@code bytes} that were passed, or null if {@code bytes} were null. + */ + public static String bytesToHexString(byte[] bytes) { + if (bytes == null) { + return null; + } + + if (bytes.length == 0) { + return ""; + } + + // Hex uses 4 bits, converting a byte to hex will double its size. + char[] hexString = new char[bytes.length * 2]; + + for (int i = 0; i < bytes.length; i++) { + // Convert the byte into an integer, masking all but the last 8 bits (the byte). + int b = bytes[i] & 0xFF; + + // Shift 4 times to the right to get the leading 4 bits and get the corresponding hex character. + hexString[i * 2] = LOWERCASE_HEX_CHARACTERS[b >>> 4]; + + // Mask all but the last 4 bits and get the corresponding hex character. + hexString[i * 2 + 1] = LOWERCASE_HEX_CHARACTERS[b & 0x0F]; + } + + return new String(hexString); + } + + /** + * Extracts the size from a {@code Content-Range} header. + *

        + * The {@code Content-Range} header can take the following forms: + * + *

          + *
        • {@code -/}
        • + *
        • {@code -/}*
        • + *
        • {@code }*{@code /}
        • + *
        + * + * If the {@code } is represented by * this method will return -1. + *

        + * If {@code contentRange} is null a {@link NullPointerException} will be thrown, if it doesn't contain a size + * segment ({@code /} or /*) an {@link IllegalArgumentException} will be thrown. + * + * @param contentRange The {@code Content-Range} header to extract the size from. + * @return The size contained in the {@code Content-Range}, or -1 if the size was *. + * @throws NullPointerException If {@code contentRange} is null. + * @throws IllegalArgumentException If {@code contentRange} doesn't contain a {@code } segment. + * @throws NumberFormatException If the {@code } segment of the {@code contentRange} isn't a valid number. + */ + public static long extractSizeFromContentRange(String contentRange) { + Objects.requireNonNull(contentRange, "Cannot extract length from null 'contentRange'."); + int index = contentRange.indexOf('/'); + + if (index == -1) { + // No size segment. + throw LOGGER.logThrowableAsError(new IllegalArgumentException("The Content-Range header wasn't properly " + + "formatted and didn't contain a '/size' segment. The 'contentRange' was: " + contentRange)); + } + + String sizeString = contentRange.substring(index + 1).trim(); + if ("*".equals(sizeString)) { + // Size unknown to the Content-Range header. + return -1; + } + + return Long.parseLong(sizeString); + } + + /** + * Parses a string into an {@link OffsetDateTime}. + *

        + * If {@code dateString} is null, null will be returned. + *

        + * This method attempts to parse the {@code dateString} using + * {@link DateTimeFormatter#parseBest(CharSequence, TemporalQuery[])}. This will use + * {@link OffsetDateTime#from(TemporalAccessor)} as the first attempt and will fall back to + * {@link LocalDateTime#from(TemporalAccessor)} with setting the offset as {@link ZoneOffset#UTC}. + * + * @param dateString The string to parse into an {@link OffsetDateTime}. + * @return The parsed {@link OffsetDateTime}, or null if {@code dateString} was null. + * @throws DateTimeException If the {@code dateString} cannot be parsed by either + * {@link OffsetDateTime#from(TemporalAccessor)} or {@link LocalDateTime#from(TemporalAccessor)}. + */ + public static OffsetDateTime parseBestOffsetDateTime(String dateString) { + if (dateString == null) { + return null; + } + + Matcher matcher = ISO8601_COLONLESS_OFFSET.matcher(dateString); + if (matcher.find()) { + dateString = dateString.substring(0, matcher.start()) + matcher.group(1) + ":" + matcher.group(2) + + dateString.substring(matcher.start() + 5); + } + + TemporalAccessor temporal + = DateTimeFormatter.ISO_DATE_TIME.parseBest(dateString, OffsetDateTime::from, LocalDateTime::from); + + if (temporal.query(TemporalQueries.offset()) == null) { + return LocalDateTime.from(temporal).atOffset(ZoneOffset.UTC); + } else { + return OffsetDateTime.from(temporal); + } + } + + /** + * Helper method to create an instance of {@link ParameterizedType}. + * @param rawType The raw type. + * @param typeArguments The type arguments. + * @return The instance of {@link ParameterizedType}. + */ + public static ParameterizedType createParameterizedType(Type rawType, Type... typeArguments) { + return new ParameterizedType() { + @Override + public Type[] getActualTypeArguments() { + return typeArguments; + } + + @Override + public Type getRawType() { + return rawType; + } + + @Override + public Type getOwnerType() { + return null; + } + }; + } + + /** + * Optimized version of {@link String#join(CharSequence, Iterable)} when the {@code values} has a small set of + * object. + * + * @param delimiter Delimiter between the values. + * @param values The values to join. + * + * @return The {@code values} joined delimited by the {@code delimiter}. + * + * @throws NullPointerException If {@code delimiter} or {@code values} is null. + */ + public static String stringJoin(String delimiter, List values) { + Objects.requireNonNull(delimiter, "'delimiter' cannot be null."); + Objects.requireNonNull(values, "'values' cannot be null."); + + int count = values.size(); + + switch (count) { + case 0: + return ""; + + case 1: + return values.get(0); + + case 2: + return values.get(0) + delimiter + values.get(1); + + case 3: + return values.get(0) + delimiter + values.get(1) + delimiter + values.get(2); + + case 4: + return values.get(0) + delimiter + values.get(1) + delimiter + values.get(2) + delimiter + + values.get(3); + + case 5: + return values.get(0) + delimiter + values.get(1) + delimiter + values.get(2) + delimiter + values.get(3) + + delimiter + values.get(4); + + case 6: + return values.get(0) + delimiter + values.get(1) + delimiter + values.get(2) + delimiter + values.get(3) + + delimiter + values.get(4) + delimiter + values.get(5); + + case 7: + return values.get(0) + delimiter + values.get(1) + delimiter + values.get(2) + delimiter + values.get(3) + + delimiter + values.get(4) + delimiter + values.get(5) + delimiter + values.get(6); + + case 8: + return values.get(0) + delimiter + values.get(1) + delimiter + values.get(2) + delimiter + values.get(3) + + delimiter + values.get(4) + delimiter + values.get(5) + delimiter + values.get(6) + delimiter + + values.get(7); + + case 9: + return values.get(0) + delimiter + values.get(1) + delimiter + values.get(2) + delimiter + values.get(3) + + delimiter + values.get(4) + delimiter + values.get(5) + delimiter + values.get(6) + delimiter + + values.get(7) + delimiter + values.get(8); + + case 10: + return values.get(0) + delimiter + values.get(1) + delimiter + values.get(2) + delimiter + values.get(3) + + delimiter + values.get(4) + delimiter + values.get(5) + delimiter + values.get(6) + delimiter + + values.get(7) + delimiter + values.get(8) + delimiter + values.get(9); + + default: + return String.join(delimiter, values); + } + } + + private CoreUtils() { + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/DateTimeRfc1123.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/DateTimeRfc1123.java similarity index 82% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/DateTimeRfc1123.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/utils/DateTimeRfc1123.java index 247dbf5577a5..cec1e4c669b1 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/DateTimeRfc1123.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/DateTimeRfc1123.java @@ -1,8 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.implementation.util; +package io.clientcore.core.utils; +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; import io.clientcore.core.instrumentation.logging.ClientLogger; import java.nio.charset.StandardCharsets; @@ -14,11 +16,14 @@ import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; -import static io.clientcore.core.implementation.util.ImplUtils.isNullOrEmpty; +import static io.clientcore.core.utils.CoreUtils.isNullOrEmpty; /** * Wrapper over java.time.OffsetDateTime used for specifying RFC1123 format during serialization and deserialization. + *

        + * This only supports the format {@code EEE, dd MMM yyyy HH:mm:ss GMT}. */ +@Metadata(properties = MetadataProperties.IMMUTABLE) public final class DateTimeRfc1123 { private static final ClientLogger LOGGER = new ClientLogger(DateTimeRfc1123.class); @@ -79,6 +84,10 @@ static DateTimeRfc1123 fromString(final String date) { * {@code date}. */ private static OffsetDateTime parse(final String date) { + if (date.length() != 29 || !date.endsWith("GMT")) { + throw LOGGER.logThrowableAsError(new DateTimeException("Invalid date time: " + date)); + } + try { return OffsetDateTime.of(LocalDateTime.of(parseInt(date, 12, 16), // year parseMonth(date), // month @@ -130,69 +139,47 @@ private static int parseInt(final String date, final int beginIndex, final int e * {@code date}. */ private static Month parseMonth(final CharSequence date) { - switch (date.charAt(8)) { - case 'J': - // Jan, Jun, Jul - switch (date.charAt(9)) { - case 'a': - return Month.JANUARY; - - case 'u': - switch (date.charAt(10)) { - case 'n': - return Month.JUNE; - - case 'l': - return Month.JULY; - - default: - throw LOGGER.logThrowableAsError(new IllegalArgumentException("Unknown month " + date)); - } - default: - throw LOGGER.logThrowableAsError(new IllegalArgumentException("Unknown month " + date)); - } - case 'F': - return Month.FEBRUARY; - - case 'M': - // Mar, May - switch (date.charAt(10)) { - case 'r': - return Month.MARCH; - - case 'y': - return Month.MAY; - - default: - throw LOGGER.logThrowableAsError(new IllegalArgumentException("Unknown month " + date)); - } - case 'A': - // Apr, Aug - switch (date.charAt(10)) { - case 'r': - return Month.APRIL; - - case 'g': - return Month.AUGUST; - - default: - throw LOGGER.logThrowableAsError(new IllegalArgumentException("Unknown month " + date)); + char charAt8 = date.charAt(8); + if (charAt8 == 'J') { + // Jan, Jun, Jul + char charAt9 = date.charAt(9); + if (charAt9 == 'a' && date.charAt(10) == 'n') { + return Month.JANUARY; + } else if (charAt9 == 'u') { + char charAt10 = date.charAt(10); + if (charAt10 == 'n') { + return Month.JUNE; + } else if (charAt10 == 'l') { + return Month.JULY; } - case 'S': - return Month.SEPTEMBER; - - case 'O': - return Month.OCTOBER; - - case 'N': - return Month.NOVEMBER; - - case 'D': - return Month.DECEMBER; - - default: - throw LOGGER.logThrowableAsError(new IllegalArgumentException("Unknown month " + date)); + } + } else if (charAt8 == 'F' && date.charAt(9) == 'e' && date.charAt(10) == 'b') { + return Month.FEBRUARY; + } else if (charAt8 == 'M' && date.charAt(9) == 'a') { + char charAt10 = date.charAt(10); + if (charAt10 == 'r') { + return Month.MARCH; + } else if (charAt10 == 'y') { + return Month.MAY; + } + } else if (charAt8 == 'A') { + char charAt9 = date.charAt(9); + if (charAt9 == 'p' && date.charAt(10) == 'r') { + return Month.APRIL; + } else if (charAt9 == 'u' && date.charAt(10) == 'g') { + return Month.AUGUST; + } + } else if (charAt8 == 'S' && date.charAt(9) == 'e' && date.charAt(10) == 'p') { + return Month.SEPTEMBER; + } else if (charAt8 == 'O' && date.charAt(9) == 'c' && date.charAt(10) == 't') { + return Month.OCTOBER; + } else if (charAt8 == 'N' && date.charAt(9) == 'o' && date.charAt(10) == 'v') { + return Month.NOVEMBER; + } else if (charAt8 == 'D' && date.charAt(9) == 'e' && date.charAt(10) == 'c') { + return Month.DECEMBER; } + + throw LOGGER.logThrowableAsError(new IllegalArgumentException("Unknown month " + date)); } /** diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/auth/DigestChallengeHandler.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/DigestChallengeHandler.java similarity index 80% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/util/auth/DigestChallengeHandler.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/utils/DigestChallengeHandler.java index a2c050d684ee..2fb2c8d06ea3 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/auth/DigestChallengeHandler.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/DigestChallengeHandler.java @@ -1,12 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.util.auth; +package io.clientcore.core.utils; import io.clientcore.core.http.models.HttpHeaderName; import io.clientcore.core.http.models.HttpRequest; import io.clientcore.core.http.models.Response; -import io.clientcore.core.util.binarydata.BinaryData; +import io.clientcore.core.models.binarydata.BinaryData; import java.security.SecureRandom; import java.util.HashMap; @@ -17,22 +17,22 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; -import static io.clientcore.core.util.auth.AuthUtils.DIGEST; -import static io.clientcore.core.util.auth.AuthUtils.MD5; -import static io.clientcore.core.util.auth.AuthUtils.SESS; -import static io.clientcore.core.util.auth.AuthUtils.SHA_512_256; -import static io.clientcore.core.util.auth.AuthUtils.buildAuthorizationHeader; -import static io.clientcore.core.util.auth.AuthUtils.bytesToHexString; -import static io.clientcore.core.util.auth.AuthUtils.calculateHa1NoSess; -import static io.clientcore.core.util.auth.AuthUtils.calculateHa1Sess; -import static io.clientcore.core.util.auth.AuthUtils.calculateHa2AuthIntQop; -import static io.clientcore.core.util.auth.AuthUtils.calculateHa2AuthQopOrEmpty; -import static io.clientcore.core.util.auth.AuthUtils.calculateResponseKnownQop; -import static io.clientcore.core.util.auth.AuthUtils.calculateResponseUnknownQop; -import static io.clientcore.core.util.auth.AuthUtils.calculateUserhash; -import static io.clientcore.core.util.auth.AuthUtils.extractValue; -import static io.clientcore.core.util.auth.AuthUtils.getDigestFunction; -import static io.clientcore.core.util.auth.AuthUtils.partitionByChallengeType; +import static io.clientcore.core.utils.AuthUtils.DIGEST; +import static io.clientcore.core.utils.AuthUtils.MD5; +import static io.clientcore.core.utils.AuthUtils.SESS; +import static io.clientcore.core.utils.AuthUtils.SHA_512_256; +import static io.clientcore.core.utils.AuthUtils.buildAuthorizationHeader; +import static io.clientcore.core.utils.AuthUtils.bytesToHexString; +import static io.clientcore.core.utils.AuthUtils.calculateHa1NoSess; +import static io.clientcore.core.utils.AuthUtils.calculateHa1Sess; +import static io.clientcore.core.utils.AuthUtils.calculateHa2AuthIntQop; +import static io.clientcore.core.utils.AuthUtils.calculateHa2AuthQopOrEmpty; +import static io.clientcore.core.utils.AuthUtils.calculateResponseKnownQop; +import static io.clientcore.core.utils.AuthUtils.calculateResponseUnknownQop; +import static io.clientcore.core.utils.AuthUtils.calculateUserhash; +import static io.clientcore.core.utils.AuthUtils.extractValue; +import static io.clientcore.core.utils.AuthUtils.getDigestFunction; +import static io.clientcore.core.utils.AuthUtils.partitionByChallengeType; /** * Handles Digest authentication challenges. @@ -80,7 +80,7 @@ public DigestChallengeHandler(String username, String password) { } @Override - public void handleChallenge(HttpRequest request, Response response, boolean isProxy) { + public void handleChallenge(HttpRequest request, Response response, boolean isProxy) { if (!canHandle(response, isProxy)) { return; } @@ -107,7 +107,7 @@ public void handleChallenge(HttpRequest request, Response response, boolean i // Generate Digest Authorization header String digestAuthHeader = generateDigestAuthHeader(request.getHttpMethod().name(), - request.getUri().toString(), algorithm, digestFunction, response.getBody()); + request.getUri().toString(), algorithm, digestFunction, response.getValue()); synchronized (request.getHeaders()) { HttpHeaderName headerName = isProxy ? HttpHeaderName.PROXY_AUTHORIZATION : HttpHeaderName.AUTHORIZATION; @@ -117,18 +117,17 @@ public void handleChallenge(HttpRequest request, Response response, boolean i } @Override - public boolean canHandle(Response response, boolean isProxy) { - String authHeader; + public boolean canHandle(Response response, boolean isProxy) { if (response.getHeaders() != null) { HttpHeaderName authHeaderName = isProxy ? HttpHeaderName.PROXY_AUTHENTICATE : HttpHeaderName.WWW_AUTHENTICATE; - authHeader = response.getHeaders().getValue(authHeaderName); + String authHeader = response.getHeaders().getValue(authHeaderName); if (authHeader != null) { - // Split by commas to handle multiple authentication methods in the header. - String[] challenges = authHeader.split(","); - for (String challenge : challenges) { - if (challenge.trim().regionMatches(true, 0, DIGEST, 0, DIGEST.length())) { + // Parse the authenticate header into AuthenticateChallenges, then check if any use scheme 'Digest'. + List challenges = AuthUtils.parseAuthenticateHeader(authHeader); + for (AuthenticateChallenge challenge : challenges) { + if (DIGEST.equalsIgnoreCase(challenge.getScheme())) { return true; } } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/ExpandableEnum.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/ExpandableEnum.java similarity index 88% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/util/ExpandableEnum.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/utils/ExpandableEnum.java index 4dfea214c71f..e80cc3589821 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/ExpandableEnum.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/ExpandableEnum.java @@ -1,13 +1,14 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.util; +package io.clientcore.core.utils; /** * Interface for expandable enums. * * @param The type of objects to be listed in the expandable enum. */ +@FunctionalInterface public interface ExpandableEnum { /** * Returns the value represented by this expandable enum instance. diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/IOExceptionCheckedBiConsumer.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/IOExceptionCheckedBiConsumer.java new file mode 100644 index 000000000000..98cc05018ea3 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/IOExceptionCheckedBiConsumer.java @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.utils; + +import io.clientcore.core.serialization.json.JsonWriter; + +import java.io.IOException; + +/** + * A bi-consumer checked with {@link IOException}. + * + * @param First type of the bi-consumer. + * @param Second type of the bi-consumer. + * + * @see JsonWriter + */ +@FunctionalInterface +public interface IOExceptionCheckedBiConsumer { + /** + * Applies the inputs to the bi-consumer. + * + * @param input1 First type of the bi-consumer. + * @param input2 Second type of the bi-consumer. + * @throws IOException If an I/O error occurs during consumption. + */ + void accept(T input1, U input2) throws IOException; +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/IOExceptionCheckedFunction.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/IOExceptionCheckedFunction.java new file mode 100644 index 000000000000..e47f2a48a95c --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/IOExceptionCheckedFunction.java @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.utils; + +import java.io.IOException; + +/** + * A function that is checked with {@link IOException}. + * + * @param Input type of the function. + * @param Output type of the function. + */ +@FunctionalInterface +public interface IOExceptionCheckedFunction { + /** + * Applies the function to the {@code input}. + * + * @param input Input to the function. + * @return The output of the function. + * @throws IOException If an I/O error occurs during the function call. + */ + R apply(T input) throws IOException; +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/ProgressReporter.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/ProgressReporter.java new file mode 100644 index 000000000000..1fa2e0376377 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/ProgressReporter.java @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.utils; + +import java.util.Objects; +import java.util.concurrent.atomic.AtomicLongFieldUpdater; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; +import java.util.function.LongConsumer; + +/** + * {@link ProgressReporter} offers a convenient way to add progress tracking to I/O operations. + *

        + * The {@link ProgressReporter} can be used to track a single operation as well as the progress of complex operations + * that involve multiple sub-operations. In the latter case {@link ProgressReporter} forms a tree where child nodes + * track the progress of sub-operations and report to the parent which in turn aggregates the total progress. The + * reporting tree can have arbitrary level of nesting. + */ +public final class ProgressReporter { + + private final LongConsumer progressListener; + private final Lock listenerLock; + private final ProgressReporter parent; + + private static final AtomicLongFieldUpdater PROGRESS_ATOMIC_UPDATER + = AtomicLongFieldUpdater.newUpdater(ProgressReporter.class, "progress"); + private volatile long progress; + + /** + * Creates top level {@link ProgressReporter}. + *

        + * Only top level {@link ProgressReporter} can have a {@link LongConsumer}. + * + * @param progressListener The {@link LongConsumer} to be notified about progress. + * @throws NullPointerException If {@code progressListener} is null. + */ + private ProgressReporter(LongConsumer progressListener) { + this.progressListener = Objects.requireNonNull(progressListener, "'progressListener' must not be null"); + this.listenerLock = new ReentrantLock(); + this.parent = null; + } + + /** + * Creates child {@link ProgressReporter}. It tracks its own progress and reports to parent. + * + * @param parent The parent {@link ProgressReporter}. Must not be null. + * @throws NullPointerException If {@code parent} is null. + */ + private ProgressReporter(ProgressReporter parent) { + this.parent = Objects.requireNonNull(parent, "'parent' must not be null"); + this.progressListener = null; + this.listenerLock = null; + } + + /** + * Creates a {@link ProgressReporter} that notifies a {@link LongConsumer} about progress. + * + * @param progressListener The {@link LongConsumer} to be notified about progress. Must not be null. + * @return A new {@link ProgressReporter} instance. + * @throws NullPointerException If {@code progressReceiver} is null. + */ + public static ProgressReporter withProgressListener(LongConsumer progressListener) { + return new ProgressReporter(progressListener); + } + + /** + * Creates a child {@link ProgressReporter} that can be used to track sub-progress when the tracked activity spans + * across concurrent processes. The child {@link ProgressReporter} notifies parent about progress and the parent + * notifies the {@link LongConsumer}. + * + * @return The child {@link ProgressReporter}. + */ + public ProgressReporter createChild() { + return new ProgressReporter(this); + } + + /** + * Resets progress to zero and notifies. + *

        + * If this is the root {@link ProgressReporter} the attached {@link LongConsumer} is notified. Otherwise, already + * accumulated progress is subtracted from the parent {@link ProgressReporter}'s progress. + *

        + */ + public void reset() { + try { + if (listenerLock != null) { + listenerLock.lock(); + } + long accumulated = PROGRESS_ATOMIC_UPDATER.getAndSet(this, 0L); + if (parent != null) { + parent.reportProgress(-1L * accumulated); + } + if (progressListener != null) { + progressListener.accept(0L); + } + } finally { + if (listenerLock != null) { + listenerLock.unlock(); + } + } + } + + /** + * Accumulates the provided {@code progress} and notifies. + *

        + * If this is the root {@link ProgressReporter} the attached {@link LongConsumer} is notified about accumulated + * progress. Otherwise, the provided {@code progress} is reported to the parent {@link ProgressReporter}. + * + * @param progress The number to be accumulated. + */ + public void reportProgress(long progress) { + try { + if (listenerLock != null) { + listenerLock.lock(); + } + long totalProgress = PROGRESS_ATOMIC_UPDATER.addAndGet(this, progress); + if (parent != null) { + parent.reportProgress(progress); + } + if (progressListener != null) { + progressListener.accept(totalProgress); + } + } finally { + if (listenerLock != null) { + listenerLock.unlock(); + } + } + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/ServerSentEventUtils.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/ServerSentEventUtils.java similarity index 94% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/util/ServerSentEventUtils.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/utils/ServerSentEventUtils.java index 86b08ed19d10..ae37c2c9adc2 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/ServerSentEventUtils.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/ServerSentEventUtils.java @@ -1,14 +1,15 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.util; +package io.clientcore.core.utils; -import io.clientcore.core.http.models.ContentType; +import io.clientcore.core.implementation.http.ContentType; import io.clientcore.core.http.models.HttpHeaderName; import io.clientcore.core.http.models.HttpRequest; import io.clientcore.core.http.models.ServerSentEvent; import io.clientcore.core.http.models.ServerSentEventListener; -import io.clientcore.core.implementation.util.ServerSentEventHelper; +import io.clientcore.core.implementation.utils.ServerSentEventHelper; +import io.clientcore.core.models.ServerSentResult; import java.io.BufferedReader; import java.io.IOException; @@ -27,12 +28,6 @@ public final class ServerSentEventUtils { private static final String DEFAULT_EVENT = "message"; private static final HttpHeaderName LAST_EVENT_ID = HttpHeaderName.fromString("Last-Event-Id"); - /** - * Error message for when no {@link ServerSentEventListener} is attached to the {@link HttpRequest}. - */ - public static final String NO_LISTENER_ERROR_MESSAGE - = "No ServerSentEventListener attached to HttpRequest to handle the text/event-stream response"; - private ServerSentEventUtils() { } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/SharedExecutorService.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/SharedExecutorService.java similarity index 98% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/util/SharedExecutorService.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/utils/SharedExecutorService.java index 5f9680e2063e..cbe572f14da4 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/util/SharedExecutorService.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/SharedExecutorService.java @@ -1,13 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.util; +package io.clientcore.core.utils; import io.clientcore.core.implementation.ReflectionUtils; import io.clientcore.core.implementation.ReflectiveInvoker; -import io.clientcore.core.implementation.util.EnvironmentConfiguration; -import io.clientcore.core.implementation.util.ImplUtils; +import io.clientcore.core.implementation.utils.ImplUtils; import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.utils.configuration.Configuration; import java.time.Duration; import java.util.Collection; @@ -80,8 +80,7 @@ public final class SharedExecutorService implements ScheduledExecutorService { private static T getConfig(String systemProperty, String envVar, Function converter, T defaultValue) { - String foundValue = ImplUtils.getFromEnvironment(EnvironmentConfiguration.getGlobalConfiguration(), - systemProperty, envVar, ImplUtils.DEFAULT_SANITIZER, LOGGER); + String foundValue = Configuration.getGlobalConfiguration().get(systemProperty, envVar); if (foundValue == null) { LOGGER.atVerbose() diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/Union.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/Union.java new file mode 100644 index 000000000000..c63d8f6f485a --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/Union.java @@ -0,0 +1,357 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.utils; + +import io.clientcore.core.implementation.GenericParameterizedType; +import io.clientcore.core.instrumentation.logging.ClientLogger; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.function.Consumer; + +/** + * A class that represents a union of types. A type that is one of a finite set of sum types. + * This class is used to represent a union of types in a type-safe manner. + * + *

        Create an instance

        + * + * + *
        + * Union union = Union.ofTypes(String.class, Integer.class);
        + * 
        + * + * + *

        Create an instance from primitives

        + * + * + *
        + * Union unionPrimitives = Union.ofTypes(int.class, double.class);
        + * 
        + * + * + *

        Create an instance from collections

        + * + * + *
        + * // GenericParameterizedType is a non-public helper class that allows us to specify a generic type with
        + * // a class and a type. User can define any similar class to achieve the same functionality.
        + * Union unionCollections = Union.ofTypes(
        + *     new GenericParameterizedType(List.class, String.class),
        + *     new GenericParameterizedType(List.class, Integer.class));
        + * 
        + * + * + *

        Consume the value of the Union if it is of the expected type

        + * + * + *
        + * Union union = Union.ofTypes(String.class, Integer.class);
        + * union.setValue("Hello");
        + * Object value = union.getValue();
        + * // we can write an if-else block to consume the value in Java 8+, or switch pattern match in Java 17+
        + * if (value instanceof String) {
        + *     String s = (String) value;
        + *     System.out.println("String value: " + s);
        + * } else if (value instanceof Integer) {
        + *     Integer i = (Integer) value;
        + *     System.out.println("Integer value: " + i);
        + * } else {
        + *     throw new IllegalArgumentException("Unknown type: " + union.getCurrentType().getTypeName());
        + * }
        + * 
        + * + * + * or + * + * + *
        + * Union union = Union.ofTypes(String.class, Integer.class);
        + * union.setValue("Hello");
        + * union.tryConsume(
        + *     v -> System.out.println("String value: " + v), String.class);
        + * union.tryConsume(
        + *     v -> System.out.println("Integer value: " + v), Integer.class);
        + * 
        + * + * + */ +public final class Union { + private static final ClientLogger LOGGER = new ClientLogger(Union.class); + + private final List types; + private Object value; + private Type currentType; + + private Union(Type... types) { + if (types == null || types.length == 0) { + throw LOGGER.logThrowableAsError(new IllegalArgumentException("types cannot be null or empty")); + } + + ArrayList typeCopy = new ArrayList<>(types.length); + for (int i = 0; i < types.length; i++) { + final Type currentType = types[i]; + if (currentType == null) { + throw LOGGER.logThrowableAsError( + new IllegalArgumentException("types cannot contain null values: null value in index " + i)); + } else if (!(currentType instanceof Class || currentType instanceof ParameterizedType)) { + throw LOGGER.logThrowableAsError(new IllegalArgumentException( + String.format("types must be of type Class or ParameterizedType: type name is %s in index %d.", + currentType.getTypeName(), i))); + } + + typeCopy.add(types[i]); + } + this.types = Collections.unmodifiableList(typeCopy); + } + + /** + * Creates a new instance of {@link Union} with the provided types. + *

        + * Currently, the types can be of type {@link Class} or {@link ParameterizedType}. If the type is a {@link Class}, + * it represents a simple type. If the type is a {@link ParameterizedType}, it represents a generic type. + * For example, {@code List} would be represented as {@code new GenericParameterizedType(List.class, String.class)}. + *

        + * + * It throws {@link IllegalArgumentException} if: + *
          + *
        • value is not of one of the types in the union,
        • + *
        • value is null,
        • + *
        • types array is null or empty,
        • + *
        • types array contains a null value,
        • + *
        • types array contains a type that is not of type {@link Class} or {@link ParameterizedType}.
        • + *
        + * + * @param types The types of the union. + * @return A new instance of {@link Union}. + */ + public static Union ofTypes(Type... types) { + return new Union(types); + } + + /** + * Sets the value of the union. A new updated immutable union is returned. + * + * @param value The value of the union. + * @return A new updated immutable union. + * @throws IllegalArgumentException If the value is not of one of the types in the union. + */ + @SuppressWarnings("unchecked") + public Union setValue(Object value) { + if (value == null) { + this.value = null; + return this; + } + + for (Type type : types) { + if (isInstanceOfType(value, type) || isPrimitiveTypeMatch(value, type)) { + this.value = value; + this.currentType = type; + return this; + } + } + + throw LOGGER.logThrowableAsError(new IllegalArgumentException("Invalid type: " + value.getClass().getName())); + } + + /** + * Gets the type of the value. + * + * @return The type of the value. + */ + public Type getCurrentType() { + return currentType; + } + + /** + * Gets the types of the union. The types are unmodifiable. + * + * @return The types of the union. + */ + public List getSupportedTypes() { + return types; + } + + /** + * Gets the value of the union. + * + * @return The value of the union. + * @param The type of the value. + */ + @SuppressWarnings("unchecked") + public T getValue() { + return (T) value; + } + + /** + * Gets the value of the union if it is of the expected type. + * + * @param clazz The expected type of the value. + * @return The value of the union. + * @param The expected type of the value. + */ + @SuppressWarnings("unchecked") + public T getValue(Class clazz) { + if (clazz == currentType) { + return (T) value; + } + + if (clazz.isInstance(value)) { + return clazz.cast(value); + } + if (isPrimitiveTypeMatch(value, clazz)) { + return (T) value; + } + throw LOGGER.logThrowableAsError(new IllegalArgumentException("Value is not of type: " + clazz.getName())); + } + + /** + * Gets the value of the union if it is of the expected type. + * + * @param clazz The expected type of the value. + * @param genericTypes The generic types of the expected type. + * + * @return The value of the union. + * @param The expected type of the value. + */ + public T getValue(Class clazz, Class... genericTypes) { + return getValue(new GenericParameterizedType(clazz, genericTypes)); + } + + /** + * Gets the value of the union if it is of the expected type. + * + * @param type The expected type of the value. + * + * @return The value of the union. + * @param The expected type of the value. + */ + @SuppressWarnings("unchecked") + public T getValue(Type type) { + if (type == currentType) { + return (T) value; + } + + if (isInstanceOfType(value, type)) { + return (T) value; + } + throw LOGGER.logThrowableAsError(new IllegalArgumentException("Value is not of type: " + type.getTypeName())); + } + + /** + * This method is used to consume the value of the Union if it is of the expected type. + * + * @param consumer A consumer that will consume the value of the Union if it is of the expected type. + * @param clazz The expected type of the value. + * @return Returns true if the value was consumable by the consumer, and false if it was not. + * @param The value type expected by the consumer. + */ + @SuppressWarnings("unchecked") + public boolean tryConsume(Consumer consumer, Class clazz) { + if (clazz == currentType) { + consumer.accept((T) value); + return true; + } + + if (isInstanceOfType(value, clazz)) { + consumer.accept(clazz.cast(value)); + return true; + } + + if (isPrimitiveTypeMatch(value, clazz)) { + consumer.accept((T) value); + return true; + } + return false; + } + + /** + * This method is used to consume the value of the Union if it is of the expected type. + * + * @param consumer A consumer that will consume the value of the Union if it is of the expected type. + * @param clazz The expected type of the value. + * @param genericTypes A var-args representation of generic types that are expected by the consumer, for example, + * List<String> would be represented as
        List.class, String.class
        . + * @return Returns true if the value was consumable by the consumer, and false if it was not. + * @param The value type expected by the consumer. + */ + public boolean tryConsume(Consumer consumer, Class clazz, Class... genericTypes) { + return tryConsume(consumer, new GenericParameterizedType(clazz, genericTypes)); + } + + /** + * This method is used to consume the value of the Union if it is of the expected type. + * + * @param consumer A consumer that will consume the value of the Union if it is of the expected type. + * @param type The expected type of the value. + * @return Returns true if the value was consumable by the consumer, and false if it was not. + * @param The value type expected by the consumer. + */ + @SuppressWarnings("unchecked") + public boolean tryConsume(Consumer consumer, ParameterizedType type) { + if (type == currentType) { + consumer.accept((T) value); + return true; + } + + if (isInstanceOfType(value, type)) { + consumer.accept((T) value); + return true; + } + return false; + } + + @Override + public String toString() { + return value == null + ? "Union{types=" + types + ", value=null" + "}" + : "Union{types=" + types + ", type=" + (currentType == null ? null : currentType.getTypeName()) + ", value=" + + value + "}"; + } + + private boolean isInstanceOfType(Object value, Type type) { + if (value == null) { + return false; + } + + if (type instanceof ParameterizedType) { + ParameterizedType pType = (ParameterizedType) type; + if (pType.getRawType() instanceof Class && ((Class) pType.getRawType()).isInstance(value)) { + Type[] actualTypeArguments = pType.getActualTypeArguments(); + if (value instanceof Collection) { + Collection collection = (Collection) value; + return collection.stream() + .allMatch(element -> element != null + && Arrays.stream(actualTypeArguments).anyMatch(arg -> isInstanceOfType(element, arg))); + } + } + } else if (type instanceof Class) { + return ((Class) type).isInstance(value); + } + return false; + } + + private boolean isPrimitiveTypeMatch(Object value, Type type) { + if (type instanceof Class) { + Class clazz = (Class) type; + if (clazz.isPrimitive()) { + if ((clazz == int.class && value instanceof Integer) + || (clazz == long.class && value instanceof Long) + || (clazz == float.class && value instanceof Float) + || (clazz == double.class && value instanceof Double) + || (clazz == boolean.class && value instanceof Boolean) + || (clazz == byte.class && value instanceof Byte) + || (clazz == char.class && value instanceof Character) + || (clazz == short.class && value instanceof Short)) { + return true; + } + } + } + return false; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/UriBuilder.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/UriBuilder.java similarity index 84% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/UriBuilder.java rename to sdk/clientcore/core/src/main/java/io/clientcore/core/utils/UriBuilder.java index 96f08637f66d..805ca6e533bf 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/implementation/util/UriBuilder.java +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/UriBuilder.java @@ -1,25 +1,33 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.implementation.util; +package io.clientcore.core.utils; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.implementation.utils.ImplUtils; +import io.clientcore.core.implementation.utils.QueryParameter; +import io.clientcore.core.implementation.utils.UriToken; +import io.clientcore.core.implementation.utils.UriTokenType; +import io.clientcore.core.implementation.utils.UriTokenizer; +import io.clientcore.core.implementation.utils.UriTokenizerState; import java.net.URI; import java.net.URISyntaxException; -import java.util.AbstractMap; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import java.util.NoSuchElementException; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; -import static io.clientcore.core.implementation.util.ImplUtils.isNullOrEmpty; +import static io.clientcore.core.utils.CoreUtils.isNullOrEmpty; /** * A builder class that is used to create URIs. */ +@Metadata(properties = MetadataProperties.FLUENT) public final class UriBuilder { private static final Map PARSED_URIS = new ConcurrentHashMap<>(); private static final int MAX_CACHE_SIZE = 10000; @@ -427,7 +435,7 @@ public static UriBuilder parse(String uri) { * @return The UriBuilder that was parsed from the URI object. */ public static UriBuilder parse(URI uri) { - return parseUri(uri, true); + return parse(uri, true); } /** @@ -437,7 +445,7 @@ public static UriBuilder parse(URI uri) { * @param includeQuery Whether the query string should be excluded. * @return The UriBuilder that represents the parsed URI. */ - private static UriBuilder parseUri(URI uri, boolean includeQuery) { + public static UriBuilder parse(URI uri, boolean includeQuery) { final UriBuilder result = new UriBuilder(); if (uri != null) { @@ -513,80 +521,6 @@ private void initializeQuery() { private static Iterator> parseQueryParameters(String queryParameters) { return (isNullOrEmpty(queryParameters)) ? Collections.emptyIterator() - : new QueryParameterIterator(queryParameters); - } - - private static final class QueryParameterIterator implements Iterator> { - private final String queryParameters; - private final int queryParametersLength; - - private boolean done = false; - private int position; - - QueryParameterIterator(String queryParameters) { - this.queryParameters = queryParameters; - this.queryParametersLength = queryParameters.length(); - - // If the URI query begins with '?' the first possible start of a query parameter key is the - // second character in the query. - position = (queryParameters.startsWith("?")) ? 1 : 0; - } - - @Override - public boolean hasNext() { - return !done; - } - - @Override - public Map.Entry next() { - if (done) { - throw new NoSuchElementException(); - } - - int nextPosition = position; - char c; - while (nextPosition < queryParametersLength) { - // Next position can either be '=' or '&' as a query parameter may not have a '=', ex 'key&key2=value'. - c = queryParameters.charAt(nextPosition); - if (c == '=') { - break; - } else if (c == '&') { - String key = queryParameters.substring(position, nextPosition); - - // Position is set to nextPosition + 1 to skip over the '&' - position = nextPosition + 1; - - return new AbstractMap.SimpleImmutableEntry<>(key, ""); - } - - nextPosition++; - } - - if (nextPosition == queryParametersLength) { - // Query parameters completed. - done = true; - return new AbstractMap.SimpleImmutableEntry<>(queryParameters.substring(position), ""); - } - - String key = queryParameters.substring(position, nextPosition); - - // Position is set to nextPosition + 1 to skip over the '=' - position = nextPosition + 1; - - nextPosition = queryParameters.indexOf('&', position); - - String value = null; - if (nextPosition == -1) { - // This was the last key-value pair in the query parameters 'https://example.com?param=done' - done = true; - value = queryParameters.substring(position); - } else { - value = queryParameters.substring(position, nextPosition); - // Position is set to nextPosition + 1 to skip over the '&' - position = nextPosition + 1; - } - - return new AbstractMap.SimpleImmutableEntry<>(key, value); - } + : new ImplUtils.QueryParameterIterator(queryParameters); } } diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/configuration/Configuration.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/configuration/Configuration.java new file mode 100644 index 000000000000..5c13e48a2466 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/configuration/Configuration.java @@ -0,0 +1,207 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.utils.configuration; + +import io.clientcore.core.http.client.HttpClient; +import io.clientcore.core.http.client.HttpClientProvider; + +import java.util.Arrays; +import java.util.List; + +/** + * Contains configuration information that is used during construction of client libraries. + */ +public final class Configuration { + // Default properties - these are what we read from the environment + /** + * URI of the proxy for HTTP connections. + */ + public static final String HTTP_PROXY = "HTTP_PROXY"; + + /** + * URI of the proxy for HTTPS connections. + */ + public static final String HTTPS_PROXY = "HTTPS_PROXY"; + + /** + * A list of hosts or CIDR to not use proxy HTTP/HTTPS connections through. + */ + public static final String NO_PROXY = "NO_PROXY"; + + /** + * Enables logging by setting a log level. + */ + public static final String LOG_LEVEL = "LOG_LEVEL"; + + /** + * Enables HTTP request/response logging by setting an HTTP log level. + */ + public static final String HTTP_LOG_LEVEL = "HTTP_LOG_LEVEL"; + + /** + * Sets the default number of times a request will be retried, if it passes the conditions for retrying, before it + * fails. + */ + public static final String MAX_RETRY_ATTEMPTS = "MAX_RETRY_ATTEMPTS"; + + /** + * Sets the default timeout, in milliseconds, for a request to connect to the remote host. + *

        + * If the configured value is equal to or less than 0 no timeout will be applied. + */ + public static final String REQUEST_CONNECT_TIMEOUT_IN_MS = "REQUEST_CONNECT_TIMEOUT_IN_MS"; + + /** + * Sets the default timeout interval, in milliseconds, allowed between each byte written by a request. + *

        + * If the configured value is equal to or less than 0 no timeout will be applied. + */ + public static final String REQUEST_WRITE_TIMEOUT_IN_MS = "REQUEST_WRITE_TIMEOUT_IN_MS"; + + /** + * Sets the default timeout, in milliseconds, for a request to receive a response from the remote host. + *

        + * If the configured value is equal to or less than 0 no timeout will be applied. + */ + public static final String REQUEST_RESPONSE_TIMEOUT_IN_MS = "REQUEST_RESPONSE_TIMEOUT_IN_MS"; + + /** + * Sets the default timeout interval, in milliseconds, allowed between each byte read in a response. + *

        + * If the configured value is equal to or less than 0 no timeout will be applied. + */ + public static final String REQUEST_READ_TIMEOUT_IN_MS = "REQUEST_READ_TIMEOUT_IN_MS"; + + /** + * Sets the name of the {@link HttpClientProvider} implementation that should be used to construct instances of + * {@link HttpClient}. + *

        + * The name must be the full class name, ex {@code io.clientcore.http.okhttp3.OkHttpHttpClientProvider} and not + * {@code OkHttpHttpClientProvider}, to disambiguate multiple providers with the same name but from different + * packages. + *

        + * If the value isn't set or is an empty string the first {@link HttpClientProvider} resolved by + * {@link java.util.ServiceLoader} will be used to create an instance of {@link HttpClient}. If the value is set + * and doesn't match any {@link HttpClientProvider} resolved by {@link java.util.ServiceLoader} an + * {@link IllegalStateException} will be thrown when attempting to create an instance of {@link HttpClient}. + */ + public static final String HTTP_CLIENT_IMPLEMENTATION = "HTTP_CLIENT_IMPLEMENTATION"; + + /* + * The global configuration shared by all client libraries. + */ + private static final Configuration GLOBAL_CONFIGURATION + = new Configuration(new SystemPropertiesConfigurationSource(), new EnvironmentVariableConfigurationSource()); + + /* + * The configuration that never returns any configuration values. + */ + private static final Configuration NONE = new Configuration(); + + private final List sources; + + /** + * Creates an instance of {@link Configuration} with the given {@link ConfigurationSource}. + *

        + * The {@code sources} will be queried in the order they are provided. + *

        + * If no {@code sources} are provided all calls to get configurations will return null. + * + * @param sources The configuration sources to use. + */ + public Configuration(ConfigurationSource... sources) { + if (sources == null || sources.length == 0) { + this.sources = null; + } else { + this.sources = Arrays.asList(Arrays.copyOf(sources, sources.length)); + } + } + + /** + * Gets the global configuration store shared by all client libraries. + *

        + * The global configuration comprises two sources, queried in this order: + *

          + *
        1. System properties
        2. + *
        3. Environment variables
        4. + *
        + * + * + * @return The global configuration store. + */ + public static Configuration getGlobalConfiguration() { + return GLOBAL_CONFIGURATION; + } + + /** + * Gets the configuration store that never returns configuration values. + * + * @return The configuration store that never returns configuration values. + */ + public static Configuration none() { + return NONE; + } + + /** + * Gets the configuration value associated with {@code name}. + *

        + * If {@code name} is null, null will be returned. + * + * @param name Name of the configuration. + * @return Value of the configuration if found, otherwise null. + */ + public String get(String name) { + if (sources == null || name == null) { + return null; + } + + return getInternal(name); + } + + /** + * Gets the configuration value associated with {@code name}. + *

        + * If {@code name} is null, it will be ignored and {@code aliases} will be used. Any null aliases will be ignored. + * + * @param name Name of the configuration. + * @param aliases Aliases of the configuration. + * @return Value of the configuration if found, otherwise null. + */ + public String get(String name, String... aliases) { + if (sources == null) { + return null; + } + + String value = getInternal(name); + if (value != null) { + return value; + } + + if (aliases != null) { + for (String alias : aliases) { + value = getInternal(alias); + if (value != null) { + return value; + } + } + } + + return null; + } + + private String getInternal(String name) { + if (name == null) { + return null; + } + + for (ConfigurationSource source : sources) { + String value = source.getProperty(name); + if (value != null) { + return value; + } + } + + return null; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/configuration/ConfigurationSource.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/configuration/ConfigurationSource.java new file mode 100644 index 000000000000..8c8695deaa51 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/configuration/ConfigurationSource.java @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.utils.configuration; + +/** + * Configuration property source which provides configuration values from a specific place. Samples may include + * properties file supported by frameworks or other source. + */ +public interface ConfigurationSource { + /** + * Gets the property with the given {@code name}. If the property doesn't exist this will return null. + *

        + * Example: + *

        + * With following configuration properties: + *

          + *
        • foo = 1
        • + *
        • bar = 2
        • + *
        + *

        + * {@link ConfigurationSource} implementation must the following behavior: + *

          + *
        • {@code getProperty(null} throws {@link NullPointerException}
        • + *
        • {@code getProperties("foo")} must return {@code 1}
        • + *
        • {@code getProperties("bar")} must return {@code 2}
        • + *
        • {@code getProperties("baz")} must return null
        • + *
        + * + * @param name Name of the property. + * @return The value of the property or null if the property doesn't exist. + * @throws NullPointerException If {@code name} is null. + */ + String getProperty(String name); + + /** + * Flag indicating whether the configuration source is mutable. + *

        + * If the configuration source is mutable, {@link Configuration} instances using this source won't cache the values + * and will always call {@link #getProperty(String)} to get the value. + * + * @return Whether the configuration source is mutable. + */ + boolean isMutable(); +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/configuration/EnvironmentVariableConfigurationSource.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/configuration/EnvironmentVariableConfigurationSource.java new file mode 100644 index 000000000000..909e2deab717 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/configuration/EnvironmentVariableConfigurationSource.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.utils.configuration; + +import java.util.Objects; + +/** + * Implementation of {@link Configuration} that reads configuration values from {@link System#getenv(String)}. + */ +public final class EnvironmentVariableConfigurationSource implements ConfigurationSource { + /** + * Creates an instance of {@link EnvironmentVariableConfigurationSource}. + */ + public EnvironmentVariableConfigurationSource() { + } + + @Override + public String getProperty(String name) { + Objects.requireNonNull(name, "'name' cannot be null."); + return System.getenv(name); + } + + @Override + public boolean isMutable() { + return false; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/configuration/SystemPropertiesConfigurationSource.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/configuration/SystemPropertiesConfigurationSource.java new file mode 100644 index 000000000000..2df8ac37874f --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/configuration/SystemPropertiesConfigurationSource.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.utils.configuration; + +import java.util.Objects; + +/** + * Implementation of {@link Configuration} that reads configuration values from {@link System#getProperty(String)}. + */ +public final class SystemPropertiesConfigurationSource implements ConfigurationSource { + /** + * Creates an instance of {@link SystemPropertiesConfigurationSource}. + */ + public SystemPropertiesConfigurationSource() { + } + + @Override + public String getProperty(String name) { + Objects.requireNonNull(name, "'name' cannot be null."); + return System.getProperty(name); + } + + @Override + public boolean isMutable() { + return true; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/configuration/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/configuration/package-info.java new file mode 100644 index 000000000000..04081acda815 --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/configuration/package-info.java @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing interfaces describing configuration information that is used during construction of client + * libraries. + */ +package io.clientcore.core.utils.configuration; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/package-info.java b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/package-info.java new file mode 100644 index 000000000000..ab3fd2295dce --- /dev/null +++ b/sdk/clientcore/core/src/main/java/io/clientcore/core/utils/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing core utility classes. + */ +package io.clientcore.core.utils; diff --git a/sdk/clientcore/core/src/main/java/module-info.java b/sdk/clientcore/core/src/main/java/module-info.java index dee608a9a5b6..90f014263a82 100644 --- a/sdk/clientcore/core/src/main/java/module-info.java +++ b/sdk/clientcore/core/src/main/java/module-info.java @@ -8,32 +8,33 @@ requires transitive java.xml; requires java.net.http; + requires jdk.httpserver; // public API surface area - exports io.clientcore.core.annotation; - exports io.clientcore.core.credential; + exports io.clientcore.core.annotations; + exports io.clientcore.core.credentials; + exports io.clientcore.core.credentials.oauth; exports io.clientcore.core.http; - exports io.clientcore.core.http.annotation; + exports io.clientcore.core.http.annotations; exports io.clientcore.core.http.client; - exports io.clientcore.core.http.exception; exports io.clientcore.core.http.models; + exports io.clientcore.core.http.paging; exports io.clientcore.core.http.pipeline; - exports io.clientcore.core.models.traits; - exports io.clientcore.core.serialization.json; - exports io.clientcore.core.serialization.xml; - exports io.clientcore.core.util; - exports io.clientcore.core.util.binarydata; - exports io.clientcore.core.util.configuration; - exports io.clientcore.core.util.serializer; - exports io.clientcore.core.util.auth; exports io.clientcore.core.instrumentation; - exports io.clientcore.core.instrumentation.tracing; exports io.clientcore.core.instrumentation.logging; + exports io.clientcore.core.instrumentation.metrics; + exports io.clientcore.core.instrumentation.tracing; + exports io.clientcore.core.models; + exports io.clientcore.core.models.binarydata; + exports io.clientcore.core.models.geo; + exports io.clientcore.core.serialization; + exports io.clientcore.core.serialization.json; + exports io.clientcore.core.serialization.json.models; + exports io.clientcore.core.serialization.xml; + exports io.clientcore.core.traits; + exports io.clientcore.core.utils; + exports io.clientcore.core.utils.configuration; + exports io.clientcore.core.implementation.http; uses io.clientcore.core.http.client.HttpClientProvider; - - provides io.clientcore.core.http.client.HttpClientProvider - with io.clientcore.core.http.client.DefaultHttpClientProvider; - - uses io.clientcore.core.serialization.json.JsonProvider; } diff --git a/sdk/clientcore/core/src/main/java12/io/clientcore/core/http/client/JdkHttpClientBuilder.java b/sdk/clientcore/core/src/main/java12/io/clientcore/core/http/client/JdkHttpClientBuilder.java new file mode 100644 index 000000000000..f83c43917219 --- /dev/null +++ b/sdk/clientcore/core/src/main/java12/io/clientcore/core/http/client/JdkHttpClientBuilder.java @@ -0,0 +1,346 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.http.client; + +import io.clientcore.core.http.models.ProxyOptions; +import io.clientcore.core.implementation.http.client.JdkHttpClient; +import io.clientcore.core.implementation.http.client.JdkHttpClientProxySelector; +import io.clientcore.core.implementation.utils.ImplUtils; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.utils.SharedExecutorService; +import io.clientcore.core.utils.configuration.Configuration; + +import javax.net.ssl.SSLContext; +import java.io.IOException; +import java.io.Reader; +import java.net.Authenticator; +import java.net.PasswordAuthentication; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.time.Duration; +import java.util.Collections; +import java.util.HashSet; +import java.util.Locale; +import java.util.Objects; +import java.util.Properties; +import java.util.Set; +import java.util.concurrent.Executor; + +/** + * Builder to configure and build an instance of the JDK {@code HttpClient} introduced in Java 11. + *

        + * Due to the JDK preventing some headers from being sent on requests, Java 12 is required to create an instance of this + * {@link HttpClient} implementation. + *

        + * This class leverages multi-release JAR functionality. If the JDK version is 11 or lower, this class will throw an + * {@link UnsupportedOperationException} when any method is invoked. This same issue will also happen if the application + * using this functionality is running Java 12 or later but doesn't have {@code Multi-Release: true} in its + * {@code META-INF/MANIFEST.MF} file. + */ +public class JdkHttpClientBuilder { + private static final ClientLogger LOGGER = new ClientLogger(JdkHttpClientBuilder.class); + + private static final Duration MINIMUM_TIMEOUT = Duration.ofMillis(1); + private static final Duration DEFAULT_CONNECTION_TIMEOUT = ImplUtils.getDefaultHttpConnectTimeout(); + private static final Duration DEFAULT_WRITE_TIMEOUT = ImplUtils.getDefaultHttpWriteTimeout(); + private static final Duration DEFAULT_RESPONSE_TIMEOUT = ImplUtils.getDefaultHttpResponseTimeout(); + private static final Duration DEFAULT_READ_TIMEOUT = ImplUtils.getDefaultHttpReadTimeout(); + + private static final String JAVA_HOME = System.getProperty("java.home"); + private static final String JDK_HTTPCLIENT_ALLOW_RESTRICTED_HEADERS = "jdk.httpclient.allowRestrictedHeaders"; + + // These headers are restricted by default in native JDK12 HttpClient. + // These headers can be whitelisted by setting jdk.httpclient.allowRestrictedHeaders + // property in the network properties file: 'JAVA_HOME/conf/net.properties' + // e.g. white listing 'host' header. + // + // jdk.httpclient.allowRestrictedHeaders=host + // Also see - https://bugs.openjdk.java.net/browse/JDK-8213189 + static final Set DEFAULT_RESTRICTED_HEADERS + = Set.of("connection", "content-length", "expect", "host", "upgrade"); + + private ProxyOptions proxyOptions; + private Configuration configuration; + private Executor executor; + private SSLContext sslContext; + + private Duration connectionTimeout; + private Duration writeTimeout; + private Duration responseTimeout; + private Duration readTimeout; + + /** + * Creates DefaultHttpClientBuilder. + */ + public JdkHttpClientBuilder() { + this.executor = SharedExecutorService.getInstance(); + } + + /** + * Sets the executor to be used for asynchronous and dependent tasks. This cannot be null. + *

        + * If this method is not invoked prior to {@link #build() building}, handling for a default will be based on whether + * the builder was created with the default constructor or the constructor that accepts an existing + * {@link java.net.http.HttpClient.Builder}. If the default constructor was used, the default executor will be + * {@link SharedExecutorService#getInstance()}. If the constructor that accepts an existing + * {@link java.net.http.HttpClient.Builder} was used, the executor from the existing builder will be used. + * + * @param executor the executor to be used for asynchronous and dependent tasks + * @return the updated {@link JdkHttpClientBuilder} object + * @throws NullPointerException if {@code executor} is null + */ + public JdkHttpClientBuilder executor(Executor executor) { + this.executor = Objects.requireNonNull(executor, "executor can not be null"); + return this; + } + + /** + * Sets the connection timeout. + * + *

        Code Samples

        + * + * + *
        +     * HttpClient client = new DefaultHttpClientBuilder()
        +     *         .connectionTimeout(Duration.ofSeconds(250)) // connection timeout of 250 seconds
        +     *         .build();
        +     * 
        + * + * + * The default connection timeout is 10 seconds. + * + * @param connectionTimeout the connection timeout + * @return the updated {@link JdkHttpClientBuilder} object + */ + public JdkHttpClientBuilder connectionTimeout(Duration connectionTimeout) { + // setConnectionTimeout can be null + this.connectionTimeout = connectionTimeout; + return this; + } + + /** + * Sets the writing timeout for a request to be sent. + *

        + * The writing timeout does not apply to the entire request but to the request being sent over the wire. For example + * a request body which emits {@code 10} {@code 8KB} buffers will trigger {@code 10} write operations, the last + * write tracker will update when each operation completes and the outbound buffer will be periodically checked to + * determine if it is still draining. + *

        + * If {@code writeTimeout} is null either {@link Configuration#REQUEST_WRITE_TIMEOUT_IN_MS} or a 60-second + * timeout will be used, if it is a {@link Duration} less than or equal to zero then no write timeout will be + * applied. When applying the timeout the greatest of one millisecond and the value of {@code writeTimeout} will be + * used. + * + * @param writeTimeout Write operation timeout duration. + * @return The updated {@link JdkHttpClientBuilder} object. + */ + public JdkHttpClientBuilder writeTimeout(Duration writeTimeout) { + this.writeTimeout = writeTimeout; + return this; + } + + /** + * Sets the response timeout duration used when waiting for a server to reply. + *

        + * The response timeout begins once the request write completes and finishes once the first response read is + * triggered when the server response is received. + *

        + * If {@code responseTimeout} is null either {@link Configuration#REQUEST_RESPONSE_TIMEOUT_IN_MS} or a + * 60-second timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout will be + * applied to the response. When applying the timeout the greatest of one millisecond and the value of {@code + * responseTimeout} will be used. + * + * @param responseTimeout Response timeout duration. + * @return The updated {@link JdkHttpClientBuilder} object. + */ + public JdkHttpClientBuilder responseTimeout(Duration responseTimeout) { + this.responseTimeout = responseTimeout; + return this; + } + + /** + * Sets the read timeout duration used when reading the server response. + *

        + * The read timeout begins once the first response read is triggered after the server response is received. This + * timeout triggers periodically but won't fire its operation if another read operation has completed between when + * the timeout is triggered and completes. + *

        + * If {@code readTimeout} is null or {@link Configuration#REQUEST_READ_TIMEOUT_IN_MS} or a 60-second + * timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout period will be + * applied to response read. When applying the timeout the greatest of one millisecond and the value of {@code + * readTimeout} will be used. + * + * @param readTimeout Read timeout duration. + * @return The updated {@link JdkHttpClientBuilder} object. + */ + public JdkHttpClientBuilder readTimeout(Duration readTimeout) { + this.readTimeout = readTimeout; + return this; + } + + /** + * Sets the proxy. + * + *

        Code Samples

        + * + * + *
        +     * final String proxyHost = "<proxy-host>"; // e.g. localhost
        +     * final int proxyPort = 9999; // Proxy port
        +     * ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP,
        +     *     new InetSocketAddress(proxyHost, proxyPort));
        +     * HttpClient client = new DefaultHttpClientBuilder()
        +     *     .proxy(proxyOptions)
        +     *     .build();
        +     * 
        + * + * + * @param proxyOptions The proxy configuration to use. + * @return the updated {@link JdkHttpClientBuilder} object + * @throws NullPointerException If {@code proxyOptions} is not null and the proxy type or address is not set. + */ + public JdkHttpClientBuilder proxy(ProxyOptions proxyOptions) { + if (proxyOptions != null) { + Objects.requireNonNull(proxyOptions.getType(), "Proxy type is required."); + Objects.requireNonNull(proxyOptions.getAddress(), "Proxy address is required."); + } + + // proxyOptions can be null + this.proxyOptions = proxyOptions; + return this; + } + + /** + * Sets the {@link SSLContext} to be used when opening secure connections. + * + * @param sslContext The SSL context to be used. + * @return The updated {@link JdkHttpClientBuilder} object. + */ + public JdkHttpClientBuilder sslContext(SSLContext sslContext) { + this.sslContext = sslContext; + return this; + } + + /** + * Sets the configuration store that is used during construction of the HTTP client. + * + * @param configuration The configuration store used to + * @return The updated {@link JdkHttpClientBuilder} object. + */ + public JdkHttpClientBuilder configuration(Configuration configuration) { + this.configuration = configuration; + return this; + } + + /** + * Build a HttpClient with current configurations. + * + * @return a {@link HttpClient}. + */ + public HttpClient build() { + java.net.http.HttpClient.Builder httpClientBuilder = java.net.http.HttpClient.newBuilder(); + + // Client Core JDK http client supports HTTP 1.1 by default. + httpClientBuilder.version(java.net.http.HttpClient.Version.HTTP_1_1); + + httpClientBuilder = httpClientBuilder.connectTimeout(getTimeout(connectionTimeout, DEFAULT_CONNECTION_TIMEOUT)); + + Duration writeTimeout = getTimeout(this.writeTimeout, DEFAULT_WRITE_TIMEOUT); + Duration responseTimeout = getTimeout(this.responseTimeout, DEFAULT_RESPONSE_TIMEOUT); + Duration readTimeout = getTimeout(this.readTimeout, DEFAULT_READ_TIMEOUT); + + Configuration buildConfiguration + = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; + + ProxyOptions buildProxyOptions + = (proxyOptions == null) ? ProxyOptions.fromConfiguration(buildConfiguration) : proxyOptions; + + if (executor != null) { + httpClientBuilder.executor(executor); + } + + if (sslContext != null) { + httpClientBuilder.sslContext(sslContext); + } + + if (buildProxyOptions != null) { + httpClientBuilder + = httpClientBuilder.proxy(new JdkHttpClientProxySelector(buildProxyOptions.getType().toProxyType(), + buildProxyOptions.getAddress(), buildProxyOptions.getNonProxyHosts())); + + if (buildProxyOptions.getUsername() != null) { + httpClientBuilder.authenticator( + new ProxyAuthenticator(buildProxyOptions.getUsername(), buildProxyOptions.getPassword())); + } + } + + return new JdkHttpClient(httpClientBuilder.build(), Collections.unmodifiableSet(getRestrictedHeaders()), + writeTimeout, responseTimeout, readTimeout); + } + + Set getRestrictedHeaders() { + // Compute the effective restricted headers by removing the allowed headers from default restricted headers + Set restrictedHeaders = new HashSet<>(DEFAULT_RESTRICTED_HEADERS); + removeAllowedHeaders(restrictedHeaders); + return restrictedHeaders; + } + + private void removeAllowedHeaders(Set restrictedHeaders) { + Properties properties = getNetworkProperties(); + String[] allowRestrictedHeadersNetProperties + = properties.getProperty(JDK_HTTPCLIENT_ALLOW_RESTRICTED_HEADERS, "").split(","); + + // Read all allowed restricted headers from configuration + Configuration config = (this.configuration == null) ? Configuration.getGlobalConfiguration() : configuration; + String allowRestrictedHeadersSystemPropertiesConfig = config.get(JDK_HTTPCLIENT_ALLOW_RESTRICTED_HEADERS); + String[] allowRestrictedHeadersSystemProperties = (allowRestrictedHeadersSystemPropertiesConfig == null) + ? new String[0] + : allowRestrictedHeadersSystemPropertiesConfig.split(","); + + // Combine the set of all allowed restricted headers from both sources + for (String header : allowRestrictedHeadersSystemProperties) { + restrictedHeaders.remove(header.trim().toLowerCase(Locale.ROOT)); + } + + for (String header : allowRestrictedHeadersNetProperties) { + restrictedHeaders.remove(header.trim().toLowerCase(Locale.ROOT)); + } + } + + Properties getNetworkProperties() { + // Read all allowed restricted headers from JAVA_HOME/conf/net.properties + Path path = Paths.get(JAVA_HOME, "conf", "net.properties"); + Properties properties = new Properties(); + try (Reader reader = Files.newBufferedReader(path)) { + properties.load(reader); + } catch (IOException e) { + LOGGER.atWarning().addKeyValue("path", path).log("Cannot read net properties.", e); + } + return properties; + } + + private static class ProxyAuthenticator extends Authenticator { + private final String userName; + private final String password; + + ProxyAuthenticator(String userName, String password) { + this.userName = userName; + this.password = password; + } + + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(this.userName, password.toCharArray()); + } + } + + private static Duration getTimeout(Duration configuredTimeout, Duration defaultTimeout) { + if (configuredTimeout == null) { + return defaultTimeout; + } + + return configuredTimeout.compareTo(MINIMUM_TIMEOUT) < 0 ? MINIMUM_TIMEOUT : configuredTimeout; + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/implementation/BodyPublisherUtils.java b/sdk/clientcore/core/src/main/java12/io/clientcore/core/implementation/http/client/BodyPublisherUtils.java similarity index 84% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/implementation/BodyPublisherUtils.java rename to sdk/clientcore/core/src/main/java12/io/clientcore/core/implementation/http/client/BodyPublisherUtils.java index 794b38073b12..e5e46f0f66d0 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/implementation/BodyPublisherUtils.java +++ b/sdk/clientcore/core/src/main/java12/io/clientcore/core/implementation/http/client/BodyPublisherUtils.java @@ -1,13 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.http.client.implementation; +package io.clientcore.core.implementation.http.client; import io.clientcore.core.http.models.HttpHeaderName; -import io.clientcore.core.util.binarydata.BinaryData; -import io.clientcore.core.util.binarydata.ByteArrayBinaryData; -import io.clientcore.core.util.binarydata.SerializableBinaryData; -import io.clientcore.core.util.binarydata.StringBinaryData; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.models.binarydata.ByteArrayBinaryData; +import io.clientcore.core.models.binarydata.SerializableBinaryData; +import io.clientcore.core.models.binarydata.StringBinaryData; import java.net.http.HttpRequest; import java.time.Duration; @@ -18,7 +18,7 @@ /** * Utility class for BodyPublisher. */ -public final class BodyPublisherUtils { +final class BodyPublisherUtils { private BodyPublisherUtils() { } @@ -30,7 +30,7 @@ private BodyPublisherUtils() { * @param writeTimeout write timeout * @return the request BodyPublisher */ - public static HttpRequest.BodyPublisher toBodyPublisher(io.clientcore.core.http.models.HttpRequest request, + static HttpRequest.BodyPublisher toBodyPublisher(io.clientcore.core.http.models.HttpRequest request, Duration writeTimeout) { // TODO (alzimmer): Handle write timeouts. BinaryData body = request.getBody(); diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/implementation/HeaderFilteringMap.java b/sdk/clientcore/core/src/main/java12/io/clientcore/core/implementation/http/client/HeaderFilteringMap.java similarity index 96% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/implementation/HeaderFilteringMap.java rename to sdk/clientcore/core/src/main/java12/io/clientcore/core/implementation/http/client/HeaderFilteringMap.java index 9e0916d4aa9a..2125d3bd49f8 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/implementation/HeaderFilteringMap.java +++ b/sdk/clientcore/core/src/main/java12/io/clientcore/core/implementation/http/client/HeaderFilteringMap.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.http.client.implementation; +package io.clientcore.core.implementation.http.client; import io.clientcore.core.http.models.HttpHeaders; import io.clientcore.core.instrumentation.logging.ClientLogger; @@ -47,7 +47,7 @@ public Set>> entrySet() { @Override public void forEach(BiConsumer> action) { - headers.forEach(header -> { + headers.stream().forEach(header -> { if (restrictedHeaders.contains(header.getName().getCaseInsensitiveName())) { logger.atWarning() .addKeyValue("headerName", header.getName()) diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/implementation/InputStreamTimeoutResponseSubscriber.java b/sdk/clientcore/core/src/main/java12/io/clientcore/core/implementation/http/client/InputStreamTimeoutResponseSubscriber.java similarity index 98% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/implementation/InputStreamTimeoutResponseSubscriber.java rename to sdk/clientcore/core/src/main/java12/io/clientcore/core/implementation/http/client/InputStreamTimeoutResponseSubscriber.java index 080dfde20510..1300b106d426 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/implementation/InputStreamTimeoutResponseSubscriber.java +++ b/sdk/clientcore/core/src/main/java12/io/clientcore/core/implementation/http/client/InputStreamTimeoutResponseSubscriber.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.http.client.implementation; +package io.clientcore.core.implementation.http.client; import java.io.IOException; import java.io.InputStream; @@ -27,7 +27,7 @@ * emitted by the subscription. This is needed to offer better reliability when reading the response in cases where the * server is either slow to respond or the connection has dropped without a signal from the server. */ -public final class InputStreamTimeoutResponseSubscriber extends InputStream +final class InputStreamTimeoutResponseSubscriber extends InputStream implements HttpResponse.BodySubscriber { // Sentinel values to indicate completion. private static final ByteBuffer LAST_BUFFER = ByteBuffer.wrap(new byte[0]); @@ -53,7 +53,7 @@ public final class InputStreamTimeoutResponseSubscriber extends InputStream * * @param readTimeout The timeout for reading each value emitted by the subscription. */ - public InputStreamTimeoutResponseSubscriber(long readTimeout) { + InputStreamTimeoutResponseSubscriber(long readTimeout) { // Use a queue size of 2 to allow for the in-process list of buffers and the sentinel value. // onComplete happens after onNext which will result in two items in the queue. // All other states are invalid if there are more than two items in the queue. diff --git a/sdk/clientcore/core/src/main/java12/io/clientcore/core/implementation/http/client/JdkHttpClient.java b/sdk/clientcore/core/src/main/java12/io/clientcore/core/implementation/http/client/JdkHttpClient.java new file mode 100644 index 000000000000..d1da55db2b7a --- /dev/null +++ b/sdk/clientcore/core/src/main/java12/io/clientcore/core/implementation/http/client/JdkHttpClient.java @@ -0,0 +1,234 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.implementation.http.client; + +import io.clientcore.core.http.client.HttpClient; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpHeaders; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.RequestOptions; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.http.models.ResponseBodyMode; +import io.clientcore.core.http.models.ServerSentEventListener; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.utils.ServerSentEventUtils; +import io.clientcore.core.models.ServerSentResult; +import io.clientcore.core.models.binarydata.BinaryData; + +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Supplier; + +import static io.clientcore.core.http.models.HttpMethod.HEAD; +import static io.clientcore.core.http.models.ResponseBodyMode.BUFFER; +import static io.clientcore.core.http.models.ResponseBodyMode.IGNORE; +import static io.clientcore.core.http.models.ResponseBodyMode.STREAM; +import static io.clientcore.core.implementation.http.ContentType.APPLICATION_OCTET_STREAM; +import static io.clientcore.core.implementation.http.client.JdkHttpUtils.fromJdkHttpHeaders; +import static io.clientcore.core.utils.ServerSentEventUtils.attemptRetry; +import static io.clientcore.core.utils.ServerSentEventUtils.isTextEventStreamContentType; +import static io.clientcore.core.utils.ServerSentEventUtils.processTextEventStream; + +/** + * HttpClient implementation using {@link HttpURLConnection} to send requests and receive responses. + */ +public final class JdkHttpClient implements HttpClient { + private static final ClientLogger LOGGER = new ClientLogger(JdkHttpClient.class); + + /** + * Error message for when no {@link ServerSentEventListener} is attached to the {@link HttpRequest}. + */ + private static final String NO_LISTENER_ERROR_MESSAGE + = "No ServerSentEventListener attached to HttpRequest to handle the text/event-stream response"; + + private final Set restrictedHeaders; + private final Duration writeTimeout; + private final Duration responseTimeout; + private final Duration readTimeout; + private final boolean hasReadTimeout; + + final java.net.http.HttpClient jdkHttpClient; + + public JdkHttpClient(java.net.http.HttpClient httpClient, Set restrictedHeaders, Duration writeTimeout, + Duration responseTimeout, Duration readTimeout) { + this.jdkHttpClient = httpClient; + + this.restrictedHeaders = restrictedHeaders; + LOGGER.atVerbose().addKeyValue("headers", restrictedHeaders).log("Effective restricted headers."); + + // Set the write and response timeouts to null if they are negative or zero. + // The writeTimeout is used with 'Flux.timeout(Duration)' which uses thread switching, always. When the timeout + // is zero or negative it's treated as an infinite timeout. So, setting this to null will prevent that thread + // switching with the same runtime behavior. + this.writeTimeout + = (writeTimeout != null && !writeTimeout.isNegative() && !writeTimeout.isZero()) ? writeTimeout : null; + + // The responseTimeout is used by JDK 'HttpRequest.timeout()' which will throw an exception when the timeout + // is non-null and is zero or negative. We treat zero or negative as an infinite timeout, so reset to null to + // prevent the exception from being thrown and have the behavior we want. + this.responseTimeout = (responseTimeout != null && !responseTimeout.isNegative() && !responseTimeout.isZero()) + ? responseTimeout + : null; + this.readTimeout = readTimeout; + this.hasReadTimeout = readTimeout != null && !readTimeout.isNegative() && !readTimeout.isZero(); + } + + @Override + public Response send(HttpRequest request) throws IOException { + java.net.http.HttpRequest jdkRequest = toJdkHttpRequest(request); + try { + // JDK HttpClient works differently than OkHttp and HttpUrlConnection where the response body handling has + // to be determined when the request is being sent, rather than being something that can be determined after + // the response has been received. Given that, we'll always consume the response body as an InputStream and + // after receiving it we'll handle ignoring, buffering, or streaming appropriately based on either the + // Content-Type header or the response body mode. + java.net.http.HttpResponse.BodyHandler bodyHandler + = getResponseHandler(hasReadTimeout, readTimeout, + java.net.http.HttpResponse.BodyHandlers::ofInputStream, InputStreamTimeoutResponseSubscriber::new); + + java.net.http.HttpResponse jdKResponse = jdkHttpClient.send(jdkRequest, bodyHandler); + return toResponse(request, jdKResponse); + } catch (InterruptedException e) { + throw LOGGER.logThrowableAsError(new RuntimeException(e)); + } + } + + /** + * Converts the given clientcore request to the JDK HttpRequest type. + * + * @param request the clientcore request + * @return the HttpRequest + */ + private java.net.http.HttpRequest toJdkHttpRequest(HttpRequest request) { + return new JdkHttpRequest(request, restrictedHeaders, LOGGER, writeTimeout, responseTimeout); + } + + /** + * Gets the response body handler based on whether a read timeout is configured. + *

        + * When a read timeout is configured our custom handler is used that tracks the time taken between each read + * operation to pull the body from the network. If a timeout isn't configured the built-in JDK handler is used. + * + * @param hasReadTimeout Flag indicating if a read timeout is configured. + * @param readTimeout The configured read timeout. + * @param jdkBodyHandler The JDK body handler to use when no read timeout is configured. + * @param timeoutSubscriber The supplier for the custom body subscriber to use when a read timeout is configured. + * @return The response body handler to use. + * @param The type of the response body. + */ + private static java.net.http.HttpResponse.BodyHandler getResponseHandler(boolean hasReadTimeout, + Duration readTimeout, Supplier> jdkBodyHandler, + Function> timeoutSubscriber) { + return hasReadTimeout ? responseInfo -> timeoutSubscriber.apply(readTimeout.toMillis()) : jdkBodyHandler.get(); + } + + private Response toResponse(HttpRequest request, java.net.http.HttpResponse response) + throws IOException { + HttpHeaders coreHeaders = fromJdkHttpHeaders(response.headers()); + ServerSentResult serverSentResult = null; + + String contentType = coreHeaders.getValue(HttpHeaderName.CONTENT_TYPE); + if (ServerSentEventUtils.isTextEventStreamContentType(contentType)) { + ServerSentEventListener listener = request.getServerSentEventListener(); + if (listener != null) { + serverSentResult = processTextEventStream(response.body(), listener); + + if (serverSentResult.getException() != null) { + // If an exception occurred while processing the text event stream, emit listener onError. + listener.onError(serverSentResult.getException()); + } + + // If an error occurred or we want to reconnect + if (!Thread.currentThread().isInterrupted() && attemptRetry(serverSentResult, request)) { + return this.send(request); + } + } else { + throw LOGGER.logThrowableAsError(new RuntimeException(NO_LISTENER_ERROR_MESSAGE)); + } + } + + return processResponse(request, response, serverSentResult, coreHeaders, contentType); + } + + private Response processResponse(HttpRequest request, java.net.http.HttpResponse response, + ServerSentResult serverSentResult, HttpHeaders coreHeaders, String contentType) throws IOException { + RequestOptions options = request.getRequestOptions(); + ResponseBodyMode responseBodyMode = null; + + if (options != null) { + responseBodyMode = options.getResponseBodyMode(); + } + + responseBodyMode = getResponseBodyMode(request, contentType, responseBodyMode); + + BinaryData body = null; + + switch (responseBodyMode) { + case IGNORE: + response.body().close(); + + break; + + case STREAM: + if (isTextEventStreamContentType(contentType)) { + body = createBodyFromServerSentResult(serverSentResult); + } else { + body = BinaryData.fromStream(response.body()); + } + + break; + + case BUFFER: + case DESERIALIZE: + // Deserialization will occur at a later point in HttpResponseBodyDecoder. + if (isTextEventStreamContentType(contentType)) { + body = createBodyFromServerSentResult(serverSentResult); + } else { + body = createBodyFromResponse(response); + } + break; + + default: + body = createBodyFromResponse(response); + break; + + } + + return new Response<>(request, response.statusCode(), coreHeaders, body == null ? BinaryData.empty() : body); + } + + private static ResponseBodyMode getResponseBodyMode(HttpRequest request, String contentType, + ResponseBodyMode responseBodyMode) { + if (responseBodyMode == null) { + if (request.getHttpMethod() == HEAD) { + responseBodyMode = IGNORE; + } else if (contentType != null + && APPLICATION_OCTET_STREAM.regionMatches(true, 0, contentType, 0, APPLICATION_OCTET_STREAM.length())) { + + responseBodyMode = STREAM; + } else { + responseBodyMode = BUFFER; + } + } + return responseBodyMode; + } + + private BinaryData createBodyFromServerSentResult(ServerSentResult serverSentResult) { + String bodyContent = (serverSentResult != null && serverSentResult.getData() != null) + ? String.join("\n", serverSentResult.getData()) + : ""; + return BinaryData.fromString(bodyContent); + } + + private BinaryData createBodyFromResponse(HttpResponse response) throws IOException { + try (InputStream responseBody = response.body()) { // Use try-with-resources to close the stream. + return BinaryData.fromBytes(responseBody.readAllBytes()); + } + } +} diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/implementation/JdkHttpClientProxySelector.java b/sdk/clientcore/core/src/main/java12/io/clientcore/core/implementation/http/client/JdkHttpClientProxySelector.java similarity index 97% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/implementation/JdkHttpClientProxySelector.java rename to sdk/clientcore/core/src/main/java12/io/clientcore/core/implementation/http/client/JdkHttpClientProxySelector.java index 455d20e676cf..b337c02f2f62 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/implementation/JdkHttpClientProxySelector.java +++ b/sdk/clientcore/core/src/main/java12/io/clientcore/core/implementation/http/client/JdkHttpClientProxySelector.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.http.client.implementation; +package io.clientcore.core.implementation.http.client; import java.io.IOException; import java.net.Proxy; diff --git a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/implementation/JdkHttpRequest.java b/sdk/clientcore/core/src/main/java12/io/clientcore/core/implementation/http/client/JdkHttpRequest.java similarity index 92% rename from sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/implementation/JdkHttpRequest.java rename to sdk/clientcore/core/src/main/java12/io/clientcore/core/implementation/http/client/JdkHttpRequest.java index 8f5769b39920..3078d763ff53 100644 --- a/sdk/clientcore/core/src/main/java/io/clientcore/core/http/client/implementation/JdkHttpRequest.java +++ b/sdk/clientcore/core/src/main/java12/io/clientcore/core/implementation/http/client/JdkHttpRequest.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.http.client.implementation; +package io.clientcore.core.implementation.http.client; import io.clientcore.core.http.models.HttpMethod; import io.clientcore.core.instrumentation.logging.ClientLogger; @@ -24,7 +24,7 @@ * us to set all headers at once. And given that the headers are backed by a {@link TreeMap} it reduces the number of * String comparisons performed. */ -public final class JdkHttpRequest extends HttpRequest { +final class JdkHttpRequest extends HttpRequest { private final BodyPublisher bodyPublisher; private final String method; private final URI uri; @@ -40,7 +40,7 @@ public final class JdkHttpRequest extends HttpRequest { * @param writeTimeout The write timeout of the request. * @param responseTimeout The response timeout of the request. */ - public JdkHttpRequest(io.clientcore.core.http.models.HttpRequest coreRequest, Set restrictedHeaders, + JdkHttpRequest(io.clientcore.core.http.models.HttpRequest coreRequest, Set restrictedHeaders, ClientLogger logger, Duration writeTimeout, Duration responseTimeout) { HttpMethod method = coreRequest.getHttpMethod(); diff --git a/sdk/clientcore/core/src/main/java12/io/clientcore/core/implementation/http/client/JdkHttpUtils.java b/sdk/clientcore/core/src/main/java12/io/clientcore/core/implementation/http/client/JdkHttpUtils.java new file mode 100644 index 000000000000..c01cb27c8ca8 --- /dev/null +++ b/sdk/clientcore/core/src/main/java12/io/clientcore/core/implementation/http/client/JdkHttpUtils.java @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.implementation.http.client; + +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpHeaders; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.utils.SharedExecutorService; +import io.clientcore.core.utils.configuration.Configuration; + +import java.nio.ByteBuffer; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +/** + * Utility class for JDK HttpClient. + */ +public final class JdkHttpUtils { + /** + * Converts the given JDK Http headers to clientcore Http header. + * + * @param headers the JDK Http headers + * @return the clientcore Http headers + */ + static HttpHeaders fromJdkHttpHeaders(java.net.http.HttpHeaders headers) { + final HttpHeaders httpHeaders = new HttpHeaders((int) (headers.map().size() / 0.75F)); + + for (Map.Entry> kvp : headers.map().entrySet()) { + List value = kvp.getValue(); + if (value != null && !value.isEmpty()) { + httpHeaders.set(HttpHeaderName.fromString(kvp.getKey()), kvp.getValue()); + } + } + + return httpHeaders; + } + + /** + * Gets the size of the given list of ByteBuffers. + *

        + * If the size of buffers is greater than {@link Integer#MAX_VALUE} an {@link IllegalStateException} will be thrown. + * This is done as this is used to create a {@code byte[]} and this could result in an integer overflow. + * + * @param buffers The list of ByteBuffers to get the size of. + * @return The size of the buffers. + * @throws IllegalStateException If the size of the buffers is greater than {@link Integer#MAX_VALUE}. + */ + static int getSizeOfBuffers(List buffers) { + long size = 0; + for (ByteBuffer buffer : buffers) { + size += buffer.remaining(); + + if (size > Integer.MAX_VALUE) { + throw new IllegalStateException("The size of the buffers is greater than Integer.MAX_VALUE."); + } + } + + return (int) size; + } + + /** + * Schedules a timeout task to be executed after the given timeout. + * + * @param task The task to be executed. + * @param timeoutMillis The timeout in milliseconds. + * @return The scheduled future for the task. + */ + static ScheduledFuture scheduleTimeoutTask(Runnable task, long timeoutMillis) { + return SharedExecutorService.getInstance().schedule(task, timeoutMillis, TimeUnit.MILLISECONDS); + } + + private JdkHttpUtils() { + } +} diff --git a/sdk/clientcore/core/src/main/java12/io/clientcore/core/implementation/http/client/package-info.java b/sdk/clientcore/core/src/main/java12/io/clientcore/core/implementation/http/client/package-info.java new file mode 100644 index 000000000000..7feebd67dcd9 --- /dev/null +++ b/sdk/clientcore/core/src/main/java12/io/clientcore/core/implementation/http/client/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing the HTTP client implementations. + */ +package io.clientcore.core.implementation.http.client; diff --git a/sdk/clientcore/core/src/main/resources/META-INF/native-image.io.clientcore.core/native-image.properties b/sdk/clientcore/core/src/main/resources/META-INF/native-image.io.clientcore.core/native-image.properties index 2298920b7620..e037782549ee 100644 --- a/sdk/clientcore/core/src/main/resources/META-INF/native-image.io.clientcore.core/native-image.properties +++ b/sdk/clientcore/core/src/main/resources/META-INF/native-image.io.clientcore.core/native-image.properties @@ -17,10 +17,10 @@ Args=\ org.slf4j.MDC,\ org.slf4j.LoggerFactory,\ org.slf4j.impl.StaticLoggerBinder,\ - io.clientcore.core.util.ClientLogger.LogLevel,\ io.clientcore.core.util.Configuration,\ io.clientcore.core.util.implementation.ImplUtils,\ - io.clientcore.core.util.ClientLogger.LoggingEvent,\ + io.clientcore.core.instrumentation.logging.ClientLogger.LogLevel,\ + io.clientcore.core.instrumentation.logging.ClientLogger.LoggingEvent,\ diff --git a/sdk/clientcore/core/src/main/resources/META-INF/services/io.clientcore.core.http.client.HttpClientProvider b/sdk/clientcore/core/src/main/resources/META-INF/services/io.clientcore.core.http.client.HttpClientProvider deleted file mode 100644 index 2285f70f5ae9..000000000000 --- a/sdk/clientcore/core/src/main/resources/META-INF/services/io.clientcore.core.http.client.HttpClientProvider +++ /dev/null @@ -1 +0,0 @@ -io.clientcore.core.http.client.DefaultHttpClientProvider diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/credentials/NamedKeyCredentialJavadocCodeSnippets.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/credentials/NamedKeyCredentialJavadocCodeSnippets.java new file mode 100644 index 000000000000..af0ccbb9af13 --- /dev/null +++ b/sdk/clientcore/core/src/samples/java/io/clientcore/core/credentials/NamedKeyCredentialJavadocCodeSnippets.java @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.credentials; + +/** + * Code snippets for {@link NamedKeyCredential}. + */ +public final class NamedKeyCredentialJavadocCodeSnippets { + public void namedKeyCredentialClassJavadocExample() { + // BEGIN: io.clientcore.core.credential.NamedKeyCredential.constructor + // Create a named credential for a service. + NamedKeyCredential namedKeyCredential = new NamedKeyCredential("SERVICE-KEY-NAME", "SERVICE-KEY"); + // END: io.clientcore.core.credential.NamedKeyCredential.constructor + } +} diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/http/HttpPipelineBuilderJavaDocCodeSnippets.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/http/HttpPipelineBuilderJavaDocCodeSnippets.java index ce2254b17ad3..ddbe9856f87a 100644 --- a/sdk/clientcore/core/src/samples/java/io/clientcore/core/http/HttpPipelineBuilderJavaDocCodeSnippets.java +++ b/sdk/clientcore/core/src/samples/java/io/clientcore/core/http/HttpPipelineBuilderJavaDocCodeSnippets.java @@ -22,7 +22,7 @@ public void defaultHttpClientWithRetryPolicyBuild() { // BEGIN: io.clientcore.core.http.HttpPipelineBuilder.defaultHttpClientWithRetryPolicy HttpPipeline pipeline = new HttpPipelineBuilder() .httpClient(HttpClient.getNewInstance()) - .policies(new HttpRetryPolicy()) + .addPolicy(new HttpRetryPolicy()) .build(); // END: io.clientcore.core.http.HttpPipelineBuilder.defaultHttpClientWithRetryPolicy } diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/http/annotation/AnnotationJavadocCodesnippets.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/http/annotation/AnnotationJavadocCodesnippets.java index 8dd561ced821..7f685f634dcc 100644 --- a/sdk/clientcore/core/src/samples/java/io/clientcore/core/http/annotation/AnnotationJavadocCodesnippets.java +++ b/sdk/clientcore/core/src/samples/java/io/clientcore/core/http/annotation/AnnotationJavadocCodesnippets.java @@ -3,7 +3,15 @@ package io.clientcore.core.http.annotation; -import io.clientcore.core.annotation.ServiceInterface; +import io.clientcore.core.annotations.ServiceInterface; +import io.clientcore.core.http.annotations.BodyParam; +import io.clientcore.core.http.annotations.FormParam; +import io.clientcore.core.http.annotations.HeaderParam; +import io.clientcore.core.http.annotations.HostParam; +import io.clientcore.core.http.annotations.HttpRequestInformation; +import io.clientcore.core.http.annotations.PathParam; +import io.clientcore.core.http.annotations.QueryParam; +import io.clientcore.core.http.annotations.UnexpectedResponseExceptionDetail; import io.clientcore.core.http.models.HttpMethod; import io.clientcore.core.http.models.Response; diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/http/client/DefaultHttpClientBuilderJavaDocCodeSnippets.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/http/client/DefaultHttpClientBuilderJavaDocCodeSnippets.java deleted file mode 100644 index dcdc2fa9ef57..000000000000 --- a/sdk/clientcore/core/src/samples/java/io/clientcore/core/http/client/DefaultHttpClientBuilderJavaDocCodeSnippets.java +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.http.client; - -import io.clientcore.core.http.models.ProxyOptions; - -import java.net.InetSocketAddress; -import java.time.Duration; - -/** - * Code snippets for {@link DefaultHttpClientBuilder} - */ -@SuppressWarnings("unused") -public class DefaultHttpClientBuilderJavaDocCodeSnippets { - /** - * Code snippet for simple http client instantiation. - */ - public void simpleInstantiation() { - // BEGIN: io.clientcore.core.http.client.instantiation-simple - HttpClient client = new DefaultHttpClientBuilder() - .build(); - // END: io.clientcore.core.http.client.instantiation-simple - } - - public void proxySample() { - // BEGIN: io.clientcore.core.http.client.DefaultHttpClientBuilder.proxy#ProxyOptions - final String proxyHost = ""; // e.g. localhost - final int proxyPort = 9999; // Proxy port - ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, - new InetSocketAddress(proxyHost, proxyPort)); - HttpClient client = new DefaultHttpClientBuilder() - .proxy(proxyOptions) - .build(); - // END: io.clientcore.core.http.client.DefaultHttpClientBuilder.proxy#ProxyOptions - } - - public void proxyBasicAuthenticationSample() { - - // BEGIN: io.clientcore.core.http.client.DefaultHttpClientBuilder#setProxyAuthenticator - final String proxyHost = ""; // e.g. localhost - final int proxyPort = 9999; // Proxy port - final String proxyUser = ""; - final String proxyPassword = ""; - // - ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, - new InetSocketAddress(proxyHost, proxyPort)); - proxyOptions = proxyOptions.setCredentials(proxyUser, proxyPassword); - HttpClient client = new DefaultHttpClientBuilder() - .proxy(proxyOptions) - .build(); - // END: io.clientcore.core.http.client.DefaultHttpClientBuilder#setProxyAuthenticator - - } - - public void connectionTimeoutSample() { - - // BEGIN: io.clientcore.core.http.client.DefaultHttpClientBuilder.connectionTimeout#Duration - HttpClient client = new DefaultHttpClientBuilder() - .connectionTimeout(Duration.ofSeconds(250)) // connection timeout of 250 seconds - .build(); - // END: io.clientcore.core.http.client.DefaultHttpClientBuilder.connectionTimeout#Duration - - } -} diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/http/client/JdkHttpClientBuilderJavaDocCodeSnippets.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/http/client/JdkHttpClientBuilderJavaDocCodeSnippets.java new file mode 100644 index 000000000000..6cc288367df6 --- /dev/null +++ b/sdk/clientcore/core/src/samples/java/io/clientcore/core/http/client/JdkHttpClientBuilderJavaDocCodeSnippets.java @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.http.client; + +import io.clientcore.core.http.models.ProxyOptions; + +import java.net.InetSocketAddress; +import java.time.Duration; + +/** + * Code snippets for {@link JdkHttpClientBuilder} + */ +@SuppressWarnings("unused") +public class JdkHttpClientBuilderJavaDocCodeSnippets { + /** + * Code snippet for simple http client instantiation. + */ + public void simpleInstantiation() { + // BEGIN: io.clientcore.core.http.client.instantiation-simple + HttpClient client = new JdkHttpClientBuilder() + .build(); + // END: io.clientcore.core.http.client.instantiation-simple + } + + public void proxySample() { + // BEGIN: io.clientcore.core.http.client.JdkHttpClientBuilder.proxy#ProxyOptions + final String proxyHost = ""; // e.g. localhost + final int proxyPort = 9999; // Proxy port + ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, + new InetSocketAddress(proxyHost, proxyPort)); + HttpClient client = new JdkHttpClientBuilder() + .proxy(proxyOptions) + .build(); + // END: io.clientcore.core.http.client.JdkHttpClientBuilder.proxy#ProxyOptions + } + + public void proxyBasicAuthenticationSample() { + + // BEGIN: io.clientcore.core.http.client.JdkHttpClientBuilder#setProxyAuthenticator + final String proxyHost = ""; // e.g. localhost + final int proxyPort = 9999; // Proxy port + final String proxyUser = ""; + final String proxyPassword = ""; + // + ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, + new InetSocketAddress(proxyHost, proxyPort)); + proxyOptions = proxyOptions.setCredentials(proxyUser, proxyPassword); + HttpClient client = new JdkHttpClientBuilder() + .proxy(proxyOptions) + .build(); + // END: io.clientcore.core.http.client.JdkHttpClientBuilder#setProxyAuthenticator + + } + + public void connectionTimeoutSample() { + + // BEGIN: io.clientcore.core.http.client.JdkHttpClientBuilder.connectionTimeout#Duration + HttpClient client = new JdkHttpClientBuilder() + .connectionTimeout(Duration.ofSeconds(250)) // connection timeout of 250 seconds + .build(); + // END: io.clientcore.core.http.client.JdkHttpClientBuilder.connectionTimeout#Duration + + } +} diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/http/models/RequestOptionsJavaDocCodeSnippets.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/http/models/RequestOptionsJavaDocCodeSnippets.java index 834c9645e9f2..7bad5b6d8f31 100644 --- a/sdk/clientcore/core/src/samples/java/io/clientcore/core/http/models/RequestOptionsJavaDocCodeSnippets.java +++ b/sdk/clientcore/core/src/samples/java/io/clientcore/core/http/models/RequestOptionsJavaDocCodeSnippets.java @@ -3,9 +3,9 @@ package io.clientcore.core.http.models; +import io.clientcore.core.models.binarydata.BinaryData; import io.clientcore.core.serialization.json.models.JsonArray; import io.clientcore.core.serialization.json.models.JsonObject; -import io.clientcore.core.util.binarydata.BinaryData; /** * JavaDoc code snippets for {@link RequestOptions}. @@ -59,7 +59,7 @@ public RequestOptions setJsonRequestBodyInRequestOptions() { .addRequestCallback(request -> request // may already be set if request is created from a client .setUri("https://petstore.example.com/pet") - .setHttpMethod(HttpMethod.POST) + .setMethod(HttpMethod.POST) .setBody(requestBodyData) .getHeaders().set(HttpHeaderName.CONTENT_TYPE, "application/json")); // END: io.clientcore.core.http.rest.requestoptions.postrequest diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/http/pipeline/AddHeadersPolicyJavadocCodeSnippets.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/http/pipeline/AddHeadersPolicyJavadocCodeSnippets.java new file mode 100644 index 000000000000..d9e09d23aa4e --- /dev/null +++ b/sdk/clientcore/core/src/samples/java/io/clientcore/core/http/pipeline/AddHeadersPolicyJavadocCodeSnippets.java @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.http.pipeline; + +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpHeaders; + +/** + * Code snippets for {@link AddHeadersPolicy}. + */ +public final class AddHeadersPolicyJavadocCodeSnippets { + public void createAddHeaderPolicy() { + // BEGIN: io.clientcore.core.http.pipeline.AddHeaderPolicy.constructor + HttpHeaders headers = new HttpHeaders(); + headers.set(HttpHeaderName.USER_AGENT, "MyApp/1.0"); + headers.set(HttpHeaderName.CONTENT_TYPE, "application/json"); + + AddHeadersPolicy policy = new AddHeadersPolicy(headers); + // END: io.clientcore.core.http.pipeline.AddHeaderPolicy.constructor + } +} diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/http/pipeline/SetRequestIdPolicyJavadocCodeSnippets.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/http/pipeline/SetRequestIdPolicyJavadocCodeSnippets.java new file mode 100644 index 000000000000..506cdf020120 --- /dev/null +++ b/sdk/clientcore/core/src/samples/java/io/clientcore/core/http/pipeline/SetRequestIdPolicyJavadocCodeSnippets.java @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.http.pipeline; + +import io.clientcore.core.http.models.HttpHeaderName; + +/** + * Code snippets for {@link RequestIdPolicy}. + */ +public final class SetRequestIdPolicyJavadocCodeSnippets { + public void overrideRequestIdHeaderName() { + // BEGIN: io.clientcore.core.http.pipeline.SetRequestIdPolicy.constructor + RequestIdPolicy policy = new RequestIdPolicy(HttpHeaderName.fromString("my-request-id")); + // END: io.clientcore.core.http.pipeline.SetRequestIdPolicy.constructor + } +} diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/http/pipeline/SetUserAgentPolicyJavadocCodeSnippets.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/http/pipeline/SetUserAgentPolicyJavadocCodeSnippets.java new file mode 100644 index 000000000000..437b594f91e5 --- /dev/null +++ b/sdk/clientcore/core/src/samples/java/io/clientcore/core/http/pipeline/SetUserAgentPolicyJavadocCodeSnippets.java @@ -0,0 +1,14 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.http.pipeline; + +/** + * Code snippets for {@link UserAgentPolicy}. + */ +public final class SetUserAgentPolicyJavadocCodeSnippets { + public void createUserAgentPolicy() { + // BEGIN: io.clientcore.core.http.pipeline.SetUserAgentPolicy.constructor + UserAgentPolicy policy = new UserAgentPolicy("MyApp/1.0"); + // END: io.clientcore.core.http.pipeline.SetUserAgentPolicy.constructor + } +} diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/instrumentation/SampleClient.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/instrumentation/SampleClient.java new file mode 100644 index 000000000000..fd7354fc6198 --- /dev/null +++ b/sdk/clientcore/core/src/samples/java/io/clientcore/core/instrumentation/SampleClient.java @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.instrumentation; + +import io.clientcore.core.http.models.HttpMethod; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.RequestOptions; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.http.pipeline.HttpPipeline; + +class SampleClient { + private final HttpPipeline httpPipeline; + private final String endpoint; + private final Instrumentation instrumentation; + + SampleClient(InstrumentationOptions instrumentationOptions, HttpPipeline httpPipeline, String endpoint) { + this.httpPipeline = httpPipeline; + this.endpoint = endpoint; + LibraryInstrumentationOptions libraryOptions = new LibraryInstrumentationOptions("contoso-sample").setEndpoint(endpoint); + this.instrumentation = Instrumentation.create(instrumentationOptions, libraryOptions); + } + + public Response downloadContent() { + return this.downloadContent(null); + } + + public Response downloadContent(RequestOptions options) { + // BEGIN: io.clientcore.core.instrumentation.instrumentwithresponse + return instrumentation.instrumentWithResponse("Sample.download", options, this::downloadImpl); + // END: io.clientcore.core.instrumentation.instrumentwithresponse + } + + public void create(RequestOptions options) { + // BEGIN: io.clientcore.core.instrumentation.instrument + instrumentation.instrument("Sample.create", options, this::createImpl); + // END: io.clientcore.core.instrumentation.instrument + } + + public Response createWithResponse(RequestOptions options) { + return instrumentation.instrumentWithResponse("create", options, this::createWithResponseImpl); + } + + private Response downloadImpl(RequestOptions options) { + return httpPipeline.send(new HttpRequest().setMethod(HttpMethod.GET).setUri(endpoint).setRequestOptions(options)); + } + + private Response createWithResponseImpl(RequestOptions options) { + return httpPipeline.send(new HttpRequest().setMethod(HttpMethod.POST).setUri(endpoint).setRequestOptions(options)); + } + + private void createImpl(RequestOptions options) { + httpPipeline.send(new HttpRequest().setMethod(HttpMethod.POST).setUri(endpoint).setRequestOptions(options)); + } +} diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/instrumentation/SampleClientBuilder.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/instrumentation/SampleClientBuilder.java new file mode 100644 index 000000000000..166e98893548 --- /dev/null +++ b/sdk/clientcore/core/src/samples/java/io/clientcore/core/instrumentation/SampleClientBuilder.java @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.instrumentation; + +import io.clientcore.core.http.pipeline.HttpInstrumentationOptions; +import io.clientcore.core.http.pipeline.HttpInstrumentationPolicy; +import io.clientcore.core.http.pipeline.HttpPipeline; +import io.clientcore.core.http.pipeline.HttpPipelineBuilder; + +class SampleClientBuilder { + private HttpInstrumentationOptions instrumentationOptions; + + public SampleClientBuilder instrumentationOptions(HttpInstrumentationOptions instrumentationOptions) { + this.instrumentationOptions = instrumentationOptions; + return this; + } + + public SampleClient build() { + HttpPipeline pipeline = new HttpPipelineBuilder() + .addPolicy(new HttpInstrumentationPolicy(instrumentationOptions)) + .build(); + return new SampleClient(instrumentationOptions, pipeline, "https://example.com"); + } +} diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/instrumentation/TelemetryForLibraryDevelopersJavaDocCodeSnippets.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/instrumentation/TelemetryForLibraryDevelopersJavaDocCodeSnippets.java new file mode 100644 index 000000000000..534cb2ffd98a --- /dev/null +++ b/sdk/clientcore/core/src/samples/java/io/clientcore/core/instrumentation/TelemetryForLibraryDevelopersJavaDocCodeSnippets.java @@ -0,0 +1,395 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.instrumentation; + +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.RequestOptions; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.http.pipeline.HttpInstrumentationOptions; +import io.clientcore.core.http.pipeline.HttpInstrumentationPolicy; +import io.clientcore.core.http.pipeline.HttpPipeline; +import io.clientcore.core.http.pipeline.HttpPipelineBuilder; +import io.clientcore.core.http.pipeline.HttpPipelineNextPolicy; +import io.clientcore.core.http.pipeline.HttpPipelinePolicy; +import io.clientcore.core.http.pipeline.HttpPipelinePosition; +import io.clientcore.core.http.pipeline.HttpRetryPolicy; +import io.clientcore.core.instrumentation.metrics.DoubleHistogram; +import io.clientcore.core.instrumentation.metrics.LongCounter; +import io.clientcore.core.instrumentation.metrics.Meter; +import io.clientcore.core.instrumentation.tracing.Span; +import io.clientcore.core.instrumentation.tracing.SpanKind; +import io.clientcore.core.instrumentation.tracing.Tracer; +import io.clientcore.core.instrumentation.tracing.TracingScope; +import io.clientcore.core.models.binarydata.BinaryData; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +/** + * THESE CODE SNIPPETS ARE INTENDED FOR CLIENT LIBRARY DEVELOPERS ONLY. + *

        + * + * Application developers are expected to use OpenTelemetry API directly. + * Check out {@code TelemetryJavaDocCodeSnippets} for application-level samples. + */ +public class TelemetryForLibraryDevelopersJavaDocCodeSnippets { + private static final HttpHeaderName CUSTOM_REQUEST_ID = HttpHeaderName.fromString("custom-request-id"); + + public void getTracer() { + + // BEGIN: io.clientcore.core.instrumentation.gettracer + + LibraryInstrumentationOptions libraryOptions = new LibraryInstrumentationOptions("sample") + .setLibraryVersion("1.0.0") + .setSchemaUrl("https://opentelemetry.io/schemas/1.29.0"); + + InstrumentationOptions instrumentationOptions = new InstrumentationOptions(); + Instrumentation instrumentation = Instrumentation.create(instrumentationOptions, libraryOptions); + + Tracer tracer = instrumentation.getTracer(); + + // END: io.clientcore.core.instrumentation.gettracer + } + + public void getMeter() { + // BEGIN: io.clientcore.core.instrumentation.getmeter + + LibraryInstrumentationOptions libraryOptions = new LibraryInstrumentationOptions("sample") + .setLibraryVersion("1.0.0") + .setSchemaUrl("https://opentelemetry.io/schemas/1.29.0"); + + InstrumentationOptions instrumentationOptions = new InstrumentationOptions(); + Instrumentation instrumentation = Instrumentation.create(instrumentationOptions, libraryOptions); + Meter meter = instrumentation.getMeter(); + + // END: io.clientcore.core.instrumentation.getmeter + } + + public void histogram() { + LibraryInstrumentationOptions libraryOptions = new LibraryInstrumentationOptions("sample") + .setLibraryVersion("1.0.0") + .setSchemaUrl("https://opentelemetry.io/schemas/1.29.0"); + + InstrumentationOptions instrumentationOptions = new InstrumentationOptions(); + Instrumentation instrumentation = Instrumentation.create(instrumentationOptions, libraryOptions); + Meter meter = instrumentation.getMeter(); + + // BEGIN: io.clientcore.core.instrumentation.histogram + + List bucketBoundariesAdvice = Collections.unmodifiableList(Arrays.asList(0.005d, 0.01d, 0.025d, 0.05d, 0.075d, + 0.1d, 0.25d, 0.5d, 0.75d, 1d, 2.5d, 5d, 7.5d, 10d)); + DoubleHistogram histogram = meter.createDoubleHistogram("contoso.sample.client.operation.duration", + "s", + "Contoso sample client operation duration", bucketBoundariesAdvice); + InstrumentationAttributes successAttributes = instrumentation.createAttributes( + Collections.singletonMap("operation.name", "{operationName}")); + + long startTime = System.nanoTime(); + String errorType = null; + + try { + performOperation(); + } catch (Throwable t) { + // make sure to report any exceptions including unchecked ones. + errorType = getCause(t).getClass().getCanonicalName(); + throw t; + } finally { + InstrumentationAttributes attributes = errorType == null + ? successAttributes + : successAttributes.put("error.type", errorType); + + histogram.record((System.nanoTime() - startTime) / 1e9, attributes, null); + } + + // END: io.clientcore.core.instrumentation.histogram + } + + public void counter() { + LibraryInstrumentationOptions libraryOptions = new LibraryInstrumentationOptions("sample") + .setLibraryVersion("1.0.0") + .setSchemaUrl("https://opentelemetry.io/schemas/1.29.0"); + + InstrumentationOptions instrumentationOptions = new InstrumentationOptions(); + Instrumentation instrumentation = Instrumentation.create(instrumentationOptions, libraryOptions); + Meter meter = instrumentation.getMeter(); + + List batch = new ArrayList<>(); + + // BEGIN: io.clientcore.core.instrumentation.counter + LongCounter counter = meter.createLongCounter("sample.client.sent.messages", + "Number of messages sent by the client library", + "{message}"); + InstrumentationAttributes successAttributes = instrumentation.createAttributes( + Collections.singletonMap("operation.name", "sendBatch")); + String errorType = null; + try { + sendBatch(batch); + } catch (Throwable t) { + // make sure to report any exceptions including unchecked ones. + errorType = getCause(t).getClass().getCanonicalName(); + throw t; + } finally { + InstrumentationAttributes attributes = errorType == null + ? successAttributes + : successAttributes.put("error.type", errorType); + + counter.add(batch.size(), attributes, null); + } + + // END: io.clientcore.core.instrumentation.counter + } + + public void upDownCounter() { + LibraryInstrumentationOptions libraryOptions = new LibraryInstrumentationOptions("sample") + .setLibraryVersion("1.0.0") + .setEndpoint("https://example.com") + .setSchemaUrl("https://opentelemetry.io/schemas/1.29.0"); + + InstrumentationOptions instrumentationOptions = new InstrumentationOptions(); + Instrumentation instrumentation = Instrumentation.create(instrumentationOptions, libraryOptions); + Meter meter = instrumentation.getMeter(); + + // BEGIN: io.clientcore.core.instrumentation.updowncounter + LongCounter upDownCounter = meter.createLongUpDownCounter("sample.client.operation.active", + "Number of operations in progress", + "{operation}"); + InstrumentationAttributes successAttributes = instrumentation.createAttributes( + Collections.singletonMap("operation.name", "sendBatch")); + try { + upDownCounter.add(1, successAttributes, null); + performOperation(); + } finally { + upDownCounter.add(-1, successAttributes, null); + } + + // END: io.clientcore.core.instrumentation.updowncounter + } + + public void createAttributes() { + // BEGIN: io.clientcore.core.instrumentation.createattributes + LibraryInstrumentationOptions libraryOptions = new LibraryInstrumentationOptions("sample") + .setLibraryVersion("1.0.0") + .setSchemaUrl("https://opentelemetry.io/schemas/1.29.0"); + + InstrumentationOptions instrumentationOptions = new InstrumentationOptions(); + + Instrumentation instrumentation = Instrumentation.create(instrumentationOptions, libraryOptions); + InstrumentationAttributes attributes = instrumentation + .createAttributes(Collections.singletonMap("key1", "value1")); + + // END: io.clientcore.core.instrumentation.createattributes + } + + /** + * This example shows minimal distributed tracing instrumentation. + */ + @SuppressWarnings("try") + public void traceCall() throws IOException { + LibraryInstrumentationOptions libraryOptions = new LibraryInstrumentationOptions("sample") + .setLibraryVersion("1.0.0") + .setSchemaUrl("https://opentelemetry.io/schemas/1.29.0") + .setEndpoint("https://example.com"); + + Tracer tracer = Instrumentation.create(null, libraryOptions).getTracer(); + RequestOptions requestOptions = null; + + // BEGIN: io.clientcore.core.instrumentation.tracecall + + InstrumentationContext context = requestOptions == null ? null : requestOptions.getInstrumentationContext(); + Span span = tracer.spanBuilder("{operationName}", SpanKind.CLIENT, context) + .startSpan(); + + // we'll propagate context implicitly using span.makeCurrent() as shown later. + // Libraries that write async code should propagate context explicitly in addition to implicit propagation. + if (tracer.isEnabled()) { + if (requestOptions == null) { + requestOptions = new RequestOptions(); + } + requestOptions.setInstrumentationContext(span.getInstrumentationContext()); + } + + try (TracingScope scope = span.makeCurrent()) { + Response response = clientCall(requestOptions); + response.close(); + } catch (Throwable t) { + // make sure to report any exceptions including unchecked ones. + span.end(getCause(t)); + throw t; + } finally { + // NOTE: closing the scope does not end the span, span should be ended explicitly. + span.end(); + } + + // END: io.clientcore.core.instrumentation.tracecall + } + + /** + * This example shows how to use generic operation instrumentation to trace call and record duration metric + */ + public void instrumentCallWithMetricsAndTraces() { + LibraryInstrumentationOptions libraryOptions = new LibraryInstrumentationOptions("sample") + .setLibraryVersion("1.0.0") + .setSchemaUrl("https://opentelemetry.io/schemas/1.29.0") + .setEndpoint("https://example.com"); + Instrumentation instrumentation = Instrumentation.create(null, libraryOptions); + + RequestOptions requestOptions = null; + + // BEGIN: io.clientcore.core.instrumentation.operation + + instrumentation.instrument("downloadContent", requestOptions, this::clientCall); + + // END: io.clientcore.core.instrumentation.operation + } + + /** + * This example shows how to enrich spans create by generic operation instrumentation with additional attributes. + * Note: metrics enrichment is not supported yet. + */ + public void enrichOperationInstrumentation() { + LibraryInstrumentationOptions libraryOptions = new LibraryInstrumentationOptions("sample") + .setLibraryVersion("1.0.0") + .setSchemaUrl("https://opentelemetry.io/schemas/1.29.0") + .setEndpoint("https://example.com"); + Instrumentation instrumentation = Instrumentation.create(null, libraryOptions); + RequestOptions requestOptions = null; + + // BEGIN: io.clientcore.core.instrumentation.enrich + instrumentation.instrumentWithResponse("downloadContent", requestOptions, updatedOptions -> { + Span span = updatedOptions.getInstrumentationContext().getSpan(); + if (span.isRecording()) { + span.setAttribute("sample.content.id", "{content-id}"); + } + + return clientCall(updatedOptions); + }); + + // END: io.clientcore.core.instrumentation.enrich + } + + private Throwable getCause(Throwable t) { + while (t.getCause() != null) { + t = t.getCause(); + } + return t; + } + + /** + * This example shows full distributed tracing instrumentation that adds attributes. + */ + @SuppressWarnings("try") + public void traceWithAttributes() throws IOException { + LibraryInstrumentationOptions libraryOptions = new LibraryInstrumentationOptions("sample") + .setLibraryVersion("1.0.0") + .setSchemaUrl("https://opentelemetry.io/schemas/1.29.0") + .setEndpoint("https://example.com"); + + Tracer tracer = Instrumentation.create(null, libraryOptions).getTracer(); + RequestOptions requestOptions = null; + + // BEGIN: io.clientcore.core.instrumentation.tracewithattributes + + Span sendSpan = tracer.spanBuilder("send {queue-name}", SpanKind.PRODUCER, null) + // Some of the attributes should be provided at the start time (as documented in semantic conventions) - + // they can be used by client apps to sample spans. + .setAttribute("messaging.system", "servicebus") + .setAttribute("messaging.destination.name", "{queue-name}") + .setAttribute("messaging.operations.name", "send") + .startSpan(); + + try (TracingScope scope = sendSpan.makeCurrent()) { + if (sendSpan.isRecording()) { + sendSpan.setAttribute("messaging.message.id", "{message-id}"); + } + + Response response = clientCall(requestOptions); + response.close(); + } catch (Throwable t) { + sendSpan.end(t); + throw t; + } finally { + sendSpan.end(); + } + + // END: io.clientcore.core.instrumentation.tracewithattributes + } + + public void configureInstrumentationPolicy() { + HttpInstrumentationOptions instrumentationOptions = new HttpInstrumentationOptions(); + + // BEGIN: io.clientcore.core.instrumentation.instrumentationpolicy + + HttpPipeline pipeline = new HttpPipelineBuilder() + .addPolicy(new HttpRetryPolicy()) + .addPolicy(new HttpInstrumentationPolicy(instrumentationOptions)) + .build(); + + // END: io.clientcore.core.instrumentation.instrumentationpolicy + } + + public void customizeInstrumentationPolicy() { + // BEGIN: io.clientcore.core.instrumentation.customizeinstrumentationpolicy + + // You can configure URL sanitization to include additional query parameters to preserve + // in `url.full` attribute. + HttpInstrumentationOptions instrumentationOptions = new HttpInstrumentationOptions(); + instrumentationOptions.addAllowedQueryParamName("documentId"); + + HttpPipeline pipeline = new HttpPipelineBuilder() + .addPolicy(new HttpRetryPolicy()) + .addPolicy(new HttpInstrumentationPolicy(instrumentationOptions)) + .build(); + + // END: io.clientcore.core.instrumentation.customizeinstrumentationpolicy + } + + public void enrichInstrumentationPolicySpans() { + HttpInstrumentationOptions instrumentationOptions = new HttpInstrumentationOptions(); + + // BEGIN: io.clientcore.core.instrumentation.enrichhttpspans + + HttpPipelinePolicy enrichingPolicy = new HttpPipelinePolicy() { + @Override + public Response process(HttpRequest request, HttpPipelineNextPolicy next) { + Span span = request.getRequestOptions() == null + ? Span.noop() + : request.getRequestOptions().getInstrumentationContext().getSpan(); + if (span.isRecording()) { + span.setAttribute("custom.request.id", request.getHeaders().getValue(CUSTOM_REQUEST_ID)); + } + + return next.process(); + } + + @Override + public HttpPipelinePosition getPipelinePosition() { + return HttpPipelinePosition.AFTER_INSTRUMENTATION; + } + }; + + HttpPipeline pipeline = new HttpPipelineBuilder() + .addPolicy(new HttpRetryPolicy()) + .addPolicy(new HttpInstrumentationPolicy(instrumentationOptions)) + .addPolicy(enrichingPolicy) + .build(); + + // END: io.clientcore.core.instrumentation.enrichhttpspans + } + + + private void performOperation() { + } + + private Response clientCall(RequestOptions options) { + return null; + } + + private void sendBatch(List messages) { + + } +} diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/instrumentation/TelemetryJavaDocCodeSnippets.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/instrumentation/TelemetryJavaDocCodeSnippets.java index 11779e0bbf1b..48ed19ccd839 100644 --- a/sdk/clientcore/core/src/samples/java/io/clientcore/core/instrumentation/TelemetryJavaDocCodeSnippets.java +++ b/sdk/clientcore/core/src/samples/java/io/clientcore/core/instrumentation/TelemetryJavaDocCodeSnippets.java @@ -3,20 +3,10 @@ package io.clientcore.core.instrumentation; -import io.clientcore.core.http.models.HttpMethod; -import io.clientcore.core.http.models.HttpRequest; import io.clientcore.core.http.models.RequestOptions; -import io.clientcore.core.http.models.Response; -import io.clientcore.core.http.pipeline.HttpInstrumentationPolicy; -import io.clientcore.core.http.pipeline.HttpPipeline; -import io.clientcore.core.http.pipeline.HttpPipelineBuilder; +import io.clientcore.core.http.pipeline.HttpInstrumentationOptions; import io.clientcore.core.instrumentation.logging.ClientLogger; import io.clientcore.core.instrumentation.tracing.Span; -import io.clientcore.core.instrumentation.tracing.SpanKind; -import io.clientcore.core.instrumentation.tracing.TracingScope; - -import java.io.IOException; -import java.io.UncheckedIOException; /** * Application developers that don't have OpenTelemetry on the classpath @@ -45,7 +35,7 @@ public void fallbackTracing() { // BEGIN: io.clientcore.core.telemetry.fallback.tracing SampleClient client = new SampleClientBuilder().build(); - client.clientCall(); + client.downloadContent(); // END: io.clientcore.core.telemetry.fallback.tracing } @@ -59,11 +49,11 @@ public void useCustomLogger() { ClientLogger logger = new ClientLogger("sample-client-traces"); - InstrumentationOptions instrumentationOptions = new InstrumentationOptions() - .setProvider(logger); + HttpInstrumentationOptions instrumentationOptions = new HttpInstrumentationOptions() + .setTelemetryProvider(logger); SampleClient client = new SampleClientBuilder().instrumentationOptions(instrumentationOptions).build(); - client.clientCall(); + client.downloadContent(); // END: io.clientcore.core.telemetry.usecustomlogger } @@ -75,15 +65,31 @@ public void useCustomLogger() { public void disableDistributedTracing() { // BEGIN: io.clientcore.core.telemetry.fallback.disabledistributedtracing - InstrumentationOptions instrumentationOptions = new InstrumentationOptions<>() + HttpInstrumentationOptions instrumentationOptions = new HttpInstrumentationOptions() .setTracingEnabled(false); SampleClient client = new SampleClientBuilder().instrumentationOptions(instrumentationOptions).build(); - client.clientCall(); + client.downloadContent(); // END: io.clientcore.core.telemetry.fallback.disabledistributedtracing } + /** + * This code snippet shows how to disable metrics + * for a specific instance of client. + */ + public void disableMetrics() { + // BEGIN: io.clientcore.core.telemetry.fallback.disablemetrics + + HttpInstrumentationOptions instrumentationOptions = new HttpInstrumentationOptions() + .setMetricsEnabled(false); + + SampleClient client = new SampleClientBuilder().instrumentationOptions(instrumentationOptions).build(); + client.downloadContent(); + + // END: io.clientcore.core.telemetry.fallback.disablemetrics + } + /** * This code snippet shows how to assign custom traceId and spanId to the client call. */ @@ -96,7 +102,7 @@ public void correlationWithExplicitContext() { .setInstrumentationContext(new MyInstrumentationContext("e4eaaaf2d48f4bf3b299a8a2a2a77ad7", "5e0c63257de34c56")); // run on another thread - client.clientCall(options); + client.downloadContent(options); // END: io.clientcore.core.telemetry.fallback.correlationwithexplicitcontext } @@ -135,62 +141,4 @@ public Span getSpan() { return Span.noop(); } } - - static class SampleClientBuilder { - private InstrumentationOptions instrumentationOptions; - // TODO (limolkova): do we need InstrumnetationTrait? - public SampleClientBuilder instrumentationOptions(InstrumentationOptions instrumentationOptions) { - this.instrumentationOptions = instrumentationOptions; - return this; - } - - public SampleClient build() { - return new SampleClient(instrumentationOptions, new HttpPipelineBuilder() - .policies(new HttpInstrumentationPolicy(instrumentationOptions, null)) - .build()); - } - } - - static class SampleClient { - private final static LibraryInstrumentationOptions LIBRARY_OPTIONS = new LibraryInstrumentationOptions("sample"); - private final HttpPipeline httpPipeline; - private final io.clientcore.core.instrumentation.tracing.Tracer tracer; - - SampleClient(InstrumentationOptions instrumentationOptions, HttpPipeline httpPipeline) { - this.httpPipeline = httpPipeline; - this.tracer = Instrumentation.create(instrumentationOptions, LIBRARY_OPTIONS).getTracer(); - } - - public void clientCall() { - this.clientCall(null); - } - - @SuppressWarnings("try") - public void clientCall(RequestOptions options) { - Span span = tracer.spanBuilder("clientCall", SpanKind.CLIENT, options.getInstrumentationContext()) - .startSpan(); - - if (options == null) { - options = new RequestOptions(); - } - - options.setInstrumentationContext(span.getInstrumentationContext()); - - try (TracingScope scope = span.makeCurrent()) { - Response response = httpPipeline.send(new HttpRequest(HttpMethod.GET, "https://example.com")); - response.close(); - span.end(); - } catch (Throwable t) { - span.end(t); - - if (t instanceof IOException) { - throw new UncheckedIOException((IOException) t); - } else if (t instanceof RuntimeException) { - throw (RuntimeException) t; - } else { - throw new RuntimeException(t); - } - } - } - } } diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/instrumentation/TracingForLibraryDevelopersJavaDocCodeSnippets.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/instrumentation/TracingForLibraryDevelopersJavaDocCodeSnippets.java deleted file mode 100644 index 5d294a02fa72..000000000000 --- a/sdk/clientcore/core/src/samples/java/io/clientcore/core/instrumentation/TracingForLibraryDevelopersJavaDocCodeSnippets.java +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.instrumentation; - -import io.clientcore.core.http.models.HttpHeaderName; -import io.clientcore.core.http.models.HttpLogOptions; -import io.clientcore.core.http.models.RequestOptions; -import io.clientcore.core.http.pipeline.HttpInstrumentationPolicy; -import io.clientcore.core.http.pipeline.HttpPipeline; -import io.clientcore.core.http.pipeline.HttpPipelineBuilder; -import io.clientcore.core.http.pipeline.HttpPipelinePolicy; -import io.clientcore.core.http.pipeline.HttpRetryPolicy; -import io.clientcore.core.instrumentation.tracing.Span; -import io.clientcore.core.instrumentation.tracing.SpanKind; -import io.clientcore.core.instrumentation.tracing.Tracer; -import io.clientcore.core.instrumentation.tracing.TracingScope; - -/** - * THESE CODE SNIPPETS ARE INTENDED FOR CLIENT LIBRARY DEVELOPERS ONLY. - *

        - * - * Application developers are expected to use OpenTelemetry API directly. - * Check out {@code TelemetryJavaDocCodeSnippets} for application-level samples. - */ -public class TracingForLibraryDevelopersJavaDocCodeSnippets { - private static final LibraryInstrumentationOptions LIBRARY_OPTIONS = new LibraryInstrumentationOptions("sample") - .setLibraryVersion("1.0.0") - .setSchemaUrl("https://opentelemetry.io/schemas/1.29.0"); - private static final HttpHeaderName CUSTOM_REQUEST_ID = HttpHeaderName.fromString("custom-request-id"); - - public void createTracer() { - - // BEGIN: io.clientcore.core.telemetry.tracing.createtracer - - LibraryInstrumentationOptions libraryOptions = new LibraryInstrumentationOptions("sample") - .setLibraryVersion("1.0.0") - .setSchemaUrl("https://opentelemetry.io/schemas/1.29.0"); - - InstrumentationOptions instrumentationOptions = new InstrumentationOptions<>(); - - Tracer tracer = Instrumentation.create(instrumentationOptions, libraryOptions).getTracer(); - - // END: io.clientcore.core.telemetry.tracing.createtracer - } - - /** - * This example shows minimal distributed tracing instrumentation. - */ - @SuppressWarnings("try") - public void traceCall() { - - Tracer tracer = Instrumentation.create(null, LIBRARY_OPTIONS).getTracer(); - RequestOptions requestOptions = null; - - // BEGIN: io.clientcore.core.telemetry.tracing.tracecall - - Span span = tracer.spanBuilder("{operationName}", SpanKind.CLIENT, null) - .startSpan(); - - // we'll propagate context implicitly using span.makeCurrent() as shown later. - // Libraries that write async code should propagate context explicitly in addition to implicit propagation. - if (tracer.isEnabled()) { - if (requestOptions == null) { - requestOptions = new RequestOptions(); - } - requestOptions.setInstrumentationContext(span.getInstrumentationContext()); - } - - try (TracingScope scope = span.makeCurrent()) { - clientCall(requestOptions); - } catch (Throwable t) { - // make sure to report any exceptions including unchecked ones. - span.end(t); - throw t; - } finally { - // NOTE: closing the scope does not end the span, span should be ended explicitly. - span.end(); - } - - // END: io.clientcore.core.telemetry.tracing.tracecall - } - - /** - * This example shows full distributed tracing instrumentation that adds attributes. - */ - @SuppressWarnings("try") - public void traceWithAttributes() { - - Tracer tracer = Instrumentation.create(null, LIBRARY_OPTIONS).getTracer(); - RequestOptions requestOptions = null; - - // BEGIN: io.clientcore.core.telemetry.tracing.tracewithattributes - - Span sendSpan = tracer.spanBuilder("send {queue-name}", SpanKind.PRODUCER, null) - // Some of the attributes should be provided at the start time (as documented in semantic conventions) - - // they can be used by client apps to sample spans. - .setAttribute("messaging.system", "servicebus") - .setAttribute("messaging.destination.name", "{queue-name}") - .setAttribute("messaging.operations.name", "send") - .startSpan(); - - try (TracingScope scope = sendSpan.makeCurrent()) { - if (sendSpan.isRecording()) { - sendSpan.setAttribute("messaging.message.id", "{message-id}"); - } - - clientCall(requestOptions); - } catch (Throwable t) { - sendSpan.end(t); - throw t; - } finally { - sendSpan.end(); - } - - // END: io.clientcore.core.telemetry.tracing.tracewithattributes - } - - public void configureInstrumentationPolicy() { - InstrumentationOptions instrumentationOptions = new InstrumentationOptions<>(); - HttpLogOptions logOptions = new HttpLogOptions(); - - // BEGIN: io.clientcore.core.telemetry.tracing.instrumentationpolicy - - HttpPipeline pipeline = new HttpPipelineBuilder() - .policies( - new HttpRetryPolicy(), - new HttpInstrumentationPolicy(instrumentationOptions, logOptions)) - .build(); - - // END: io.clientcore.core.telemetry.tracing.instrumentationpolicy - } - - public void customizeInstrumentationPolicy() { - InstrumentationOptions instrumentationOptions = new InstrumentationOptions<>(); - - // BEGIN: io.clientcore.core.telemetry.tracing.customizeinstrumentationpolicy - - // You can configure URL sanitization to include additional query parameters to preserve - // in `url.full` attribute. - HttpLogOptions logOptions = new HttpLogOptions(); - logOptions.addAllowedQueryParamName("documentId"); - - HttpPipeline pipeline = new HttpPipelineBuilder() - .policies( - new HttpRetryPolicy(), - new HttpInstrumentationPolicy(instrumentationOptions, logOptions)) - .build(); - - // END: io.clientcore.core.telemetry.tracing.customizeinstrumentationpolicy - } - - public void enrichInstrumentationPolicySpans() { - InstrumentationOptions instrumentationOptions = new InstrumentationOptions<>(); - HttpLogOptions logOptions = new HttpLogOptions(); - - // BEGIN: io.clientcore.core.telemetry.tracing.enrichhttpspans - - HttpPipelinePolicy enrichingPolicy = (request, next) -> { - Span span = request.getRequestOptions() == null - ? Span.noop() - : request.getRequestOptions().getInstrumentationContext().getSpan(); - if (span.isRecording()) { - span.setAttribute("custom.request.id", request.getHeaders().getValue(CUSTOM_REQUEST_ID)); - } - - return next.process(); - }; - - HttpPipeline pipeline = new HttpPipelineBuilder() - .policies( - new HttpRetryPolicy(), - new HttpInstrumentationPolicy(instrumentationOptions, logOptions), - enrichingPolicy) - .build(); - - - // END: io.clientcore.core.telemetry.tracing.enrichhttpspans - } - - private void clientCall(RequestOptions options) { - } -} diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/models/CloudEventJavaDocCodeSnippet.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/models/CloudEventJavaDocCodeSnippet.java new file mode 100644 index 000000000000..43b60e593c7a --- /dev/null +++ b/sdk/clientcore/core/src/samples/java/io/clientcore/core/models/CloudEventJavaDocCodeSnippet.java @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models; + +import io.clientcore.core.models.binarydata.BinaryData; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.List; + +public class CloudEventJavaDocCodeSnippet { + private static class User { + private final String firstName; + private final String lastName; + + User(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + } + + public void createCloudEvent() { + // BEGIN: io.clientcore.core.models.CloudEvent#constructor + // Use BinaryData.fromBytes() to create data in format CloudEventDataFormat.BYTES + byte[] exampleBytes = "Hello World".getBytes(StandardCharsets.UTF_8); + CloudEvent cloudEvent = new CloudEvent("/cloudevents/example/source", "Example.EventType", + BinaryData.fromBytes(exampleBytes), CloudEventDataFormat.BYTES, "application/octet-stream"); + + // Use BinaryData.fromObject() to create CloudEvent data in format CloudEventDataFormat.JSON + // From a model class + User user = new User("Stephen", "James"); + CloudEvent cloudEventDataObject = new CloudEvent("/cloudevents/example/source", "Example.EventType", + BinaryData.fromObject(user), CloudEventDataFormat.JSON, "application/json"); + + // From a String + CloudEvent cloudEventDataStr = new CloudEvent("/cloudevents/example/source", "Example.EventType", + BinaryData.fromObject("Hello World"), CloudEventDataFormat.JSON, "text/plain"); + + // From an Integer + CloudEvent cloudEventDataInt = new CloudEvent("/cloudevents/example/source", "Example.EventType", + BinaryData.fromObject(1), CloudEventDataFormat.JSON, "int"); + + // From a Boolean + CloudEvent cloudEventDataBool = new CloudEvent("/cloudevents/example/source", "Example.EventType", + BinaryData.fromObject(true), CloudEventDataFormat.JSON, "bool"); + + // From null + CloudEvent cloudEventDataNull = new CloudEvent("/cloudevents/example/source", "Example.EventType", + BinaryData.fromObject(null), CloudEventDataFormat.JSON, "null"); + + // Use BinaryData.fromString() if you have a Json String for the CloudEvent data. + String jsonStringForData = "\"Hello World\""; // A json String. + CloudEvent cloudEventDataJsonStr = new CloudEvent("/cloudevents/example/source", "Example.EventType", + BinaryData.fromString(jsonStringForData), CloudEventDataFormat.JSON, "text/plain"); + // END: io.clientcore.core.models.CloudEvent#constructor + } + + public void fromJsonStringWithDataJson() throws IOException { + String cloudEventJsonString = ""; + + // BEGIN: io.clientcore.core.models.CloudEvent.fromString + List cloudEventList = CloudEvent.fromString(cloudEventJsonString); + CloudEvent cloudEvent = cloudEventList.get(0); + BinaryData cloudEventData = cloudEvent.getData(); + + byte[] bytesValue = cloudEventData.toBytes(); // If data payload is in bytes (data_base64 is not null). + User objectValue = cloudEventData.toObject(User.class); // If data payload is a User object. + int intValue = cloudEventData.toObject(Integer.class); // If data payload is an int. + boolean boolValue = cloudEventData.toObject(Boolean.class); // If data payload is boolean. + String stringValue = cloudEventData.toObject(String.class); // If data payload is String. + String jsonStringValue = cloudEventData.toString(); // The data payload represented in Json String. + // END: io.clientcore.core.models.CloudEvent.fromString + } +} diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/models/ContextJavaDocCodeSnippets.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/models/ContextJavaDocCodeSnippets.java index 6b48c5e194de..3889436fa071 100644 --- a/sdk/clientcore/core/src/samples/java/io/clientcore/core/models/ContextJavaDocCodeSnippets.java +++ b/sdk/clientcore/core/src/samples/java/io/clientcore/core/models/ContextJavaDocCodeSnippets.java @@ -3,7 +3,7 @@ package io.clientcore.core.models; -import io.clientcore.core.util.Context; +import io.clientcore.core.utils.Context; /** * Code snippets for {@link Context} diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/models/BinaryDataJavaDocCodeSnippet.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/models/binarydata/BinaryDataJavaDocCodeSnippet.java similarity index 96% rename from sdk/clientcore/core/src/samples/java/io/clientcore/core/models/BinaryDataJavaDocCodeSnippet.java rename to sdk/clientcore/core/src/samples/java/io/clientcore/core/models/binarydata/BinaryDataJavaDocCodeSnippet.java index 69fb89b4ed97..bdd6c17f2ff5 100644 --- a/sdk/clientcore/core/src/samples/java/io/clientcore/core/models/BinaryDataJavaDocCodeSnippet.java +++ b/sdk/clientcore/core/src/samples/java/io/clientcore/core/models/binarydata/BinaryDataJavaDocCodeSnippet.java @@ -1,12 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.models; +package io.clientcore.core.models.binarydata; import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.util.binarydata.BinaryData; -import io.clientcore.core.implementation.util.JsonSerializer; -import io.clientcore.core.util.serializer.ObjectSerializer; +import io.clientcore.core.models.Person; +import io.clientcore.core.serialization.ObjectSerializer; +import io.clientcore.core.serialization.json.JsonSerializer; import java.io.ByteArrayInputStream; import java.io.File; @@ -171,7 +171,7 @@ public void fromObjectObjectSerializer() { final Person data = new Person().setName("John"); // Provide your custom serializer or use the provided serializers. - final ObjectSerializer serializer = new MyJsonSerializer(); // Replace this with your Serializer + final JsonSerializer serializer = new MyJsonSerializer(); // Replace this with your Serializer BinaryData binaryData = BinaryData.fromObject(data, serializer); System.out.println(binaryData.toString()); @@ -242,7 +242,7 @@ public void toObjectTypeObjectSerializer() throws IOException { final Person data = new Person().setName("John"); // Provide your custom serializer or use the provided serializers. - final ObjectSerializer serializer = new MyJsonSerializer(); // Replace this with your Serializer + final JsonSerializer serializer = new MyJsonSerializer(); // Replace this with your Serializer BinaryData binaryData = BinaryData.fromObject(data, serializer); Person person = binaryData.toObject(Person.class, serializer); @@ -262,7 +262,7 @@ public void toObjectTypeObjectSerializerWithGenerics() throws IOException { personList.add(person1); personList.add(person2); - final ObjectSerializer serializer = new MyJsonSerializer(); // Replace this with your Serializer + final JsonSerializer serializer = new MyJsonSerializer(); // Replace this with your Serializer BinaryData binaryData = BinaryData.fromObject(personList, serializer); // Creation of the ParameterizedType could be replaced with a utility method that returns a Type based on the diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/serialization/json/codesnippets/ReadingJsonExamples.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/serialization/json/codesnippets/ReadingJsonExamples.java index 58e9139a67dc..6063d1407916 100644 --- a/sdk/clientcore/core/src/samples/java/io/clientcore/core/serialization/json/codesnippets/ReadingJsonExamples.java +++ b/sdk/clientcore/core/src/samples/java/io/clientcore/core/serialization/json/codesnippets/ReadingJsonExamples.java @@ -3,7 +3,6 @@ package io.clientcore.core.serialization.json.codesnippets; -import io.clientcore.core.serialization.json.JsonProviders; import io.clientcore.core.serialization.json.JsonReader; import java.io.ByteArrayInputStream; @@ -20,7 +19,7 @@ public ComputerMemory readJsonByteArray() throws IOException { byte[] json = ("{\"memoryInBytes\":10000000000,\"clockSpeedInHertz\":4800000000," + "\"manufacturer\":\"Memory Corp\",\"errorCorrecting\":true}").getBytes(StandardCharsets.UTF_8); - try (JsonReader jsonReader = JsonProviders.createReader(json)) { + try (JsonReader jsonReader = JsonReader.fromBytes(json)) { return ComputerMemory.fromJson(jsonReader); } // END: io.clientcore.core.serialization.json.JsonReader.readJsonByteArray @@ -31,7 +30,7 @@ public ComputerProcessor readJsonString() throws IOException { String json = "{\"cores\":16,\"threads\":32,\"manufacturer\":\"Processor Corp\"," + "\"clockSpeedInHertz\":5000000000,\"releaseDate\":null}"; - try (JsonReader jsonReader = JsonProviders.createReader(json)) { + try (JsonReader jsonReader = JsonReader.fromString(json)) { return ComputerProcessor.fromJson(jsonReader); } // END: io.clientcore.core.serialization.json.JsonReader.readJsonString @@ -47,7 +46,7 @@ public VmStatistics readJsonInputStream() throws IOException { + "\"AcceleratedNetwork\":true,\"CloudProvider\":\"SomeCloud\",\"Available\":true}") .getBytes(StandardCharsets.UTF_8)); - try (JsonReader jsonReader = JsonProviders.createReader(json)) { + try (JsonReader jsonReader = JsonReader.fromStream(json)) { return VmStatistics.fromJson(jsonReader); } // END: io.clientcore.core.serialization.json.JsonReader.readJsonInputStream @@ -61,7 +60,7 @@ public VmStatistics readJsonReader() throws IOException { + "\"manufacturer\":\"Memory Corp\",\"errorCorrecting\":true},\"AcceleratedNetwork\":true," + "\"CloudProvider\":\"SomeCloud\",\"Available\":true}"); - try (JsonReader jsonReader = JsonProviders.createReader(json)) { + try (JsonReader jsonReader = JsonReader.fromReader(json)) { return VmStatistics.fromJson(jsonReader); } // END: io.clientcore.core.serialization.json.JsonReader.readJsonReader diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/serialization/json/codesnippets/WritingJsonExamples.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/serialization/json/codesnippets/WritingJsonExamples.java index 57b449cd9e04..13ac8d72e0b6 100644 --- a/sdk/clientcore/core/src/samples/java/io/clientcore/core/serialization/json/codesnippets/WritingJsonExamples.java +++ b/sdk/clientcore/core/src/samples/java/io/clientcore/core/serialization/json/codesnippets/WritingJsonExamples.java @@ -3,7 +3,6 @@ package io.clientcore.core.serialization.json.codesnippets; -import io.clientcore.core.serialization.json.JsonProviders; import io.clientcore.core.serialization.json.JsonWriter; import java.io.ByteArrayOutputStream; @@ -32,7 +31,7 @@ public void writeJsonOutputStream() throws IOException { .setAdditionalProperties(additionalVmProperties); ByteArrayOutputStream json = new ByteArrayOutputStream(); - try (JsonWriter jsonWriter = JsonProviders.createWriter(json)) { + try (JsonWriter jsonWriter = JsonWriter.toStream(json)) { // JsonWriter automatically flushes on close. vmStatistics.toJson(jsonWriter); } @@ -62,7 +61,7 @@ public void writeJsonWriter() throws IOException { .setAdditionalProperties(additionalVmProperties); Writer json = new StringWriter(); - try (JsonWriter jsonWriter = JsonProviders.createWriter(json)) { + try (JsonWriter jsonWriter = JsonWriter.toWriter(json)) { // JsonWriter automatically flushes on close. vmStatistics.toJson(jsonWriter); } diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/serialization/json/models/JsonPatchDocumentJavadocCodeSnippets.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/serialization/json/models/JsonPatchDocumentJavadocCodeSnippets.java new file mode 100644 index 000000000000..1e2c83ec64cb --- /dev/null +++ b/sdk/clientcore/core/src/samples/java/io/clientcore/core/serialization/json/models/JsonPatchDocumentJavadocCodeSnippets.java @@ -0,0 +1,259 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.serialization.json.models; + +import java.io.IOException; +import java.util.Collections; + +/** + * Code snippets for {@link JsonPatchDocument}. + */ +public final class JsonPatchDocumentJavadocCodeSnippets { + /** + * Codesnippets for {@link JsonPatchDocument#appendAdd(String, Object)}. + */ + public void appendAdd() throws IOException { + JsonPatchDocument jsonPatchDocument = new JsonPatchDocument(); + // BEGIN: io.clientcore.core.serialization.json.models.JsonPatchDocument.appendAdd#String-Object + /* + * Add an object member to the JSON document { "foo" : "bar" } to get the JSON document + * { "bar": "foo", "foo": "bar" }. + */ + jsonPatchDocument.appendAdd("/bar", "foo"); + + /* + * Add an array element to the JSON document { "foo": [ "fizz", "fizzbuzz" ] } to get the JSON document + * { "foo": [ "fizz", "buzz", "fizzbuzz" ] }. + */ + jsonPatchDocument.appendAdd("/foo/1", "buzz"); + + /* + * Add a nested member to the JSON document { "foo": "bar" } to get the JSON document + * { "foo": "bar", "child": { "grandchild": { } } }. + */ + jsonPatchDocument.appendAdd("/child", Collections.singletonMap("grandchild", Collections.emptyMap())); + + /* + * Add an array element to the JSON document { "foo": [ "fizz", "buzz" ] } to get the JSON document + * { "foo": [ "fizz", "buzz", "fizzbuzz" ] }. + */ + jsonPatchDocument.appendAdd("/foo/-", "fizzbuzz"); + // END: io.clientcore.core.serialization.json.models.JsonPatchDocument.appendAdd#String-Object + } + + /** + * Codesnippets for {@link JsonPatchDocument#appendAddRaw(String, String)}. + */ + public void appendAddRaw() { + JsonPatchDocument jsonPatchDocument = new JsonPatchDocument(); + // BEGIN: io.clientcore.core.serialization.json.models.JsonPatchDocument.appendAddRaw#String-String + /* + * Add an object member to the JSON document { "foo" : "bar" } to get the JSON document + * { "bar": "foo", "foo": "bar" }. + */ + jsonPatchDocument.appendAddRaw("/bar", "\"foo\""); + + /* + * Add an array element to the JSON document { "foo": [ "fizz", "fizzbuzz" ] } to get the JSON document + * { "foo": [ "fizz", "buzz", "fizzbuzz" ] }. + */ + jsonPatchDocument.appendAddRaw("/foo/1", "\"buzz\""); + + /* + * Add a nested member to the JSON document { "foo": "bar" } to get the JSON document + * { "foo": "bar", "child": { "grandchild": { } } }. + */ + jsonPatchDocument.appendAddRaw("/child", "\"child\": { \"grandchild\": { } }"); + + /* + * Add an array element to the JSON document { "foo": [ "fizz", "buzz" ] } to get the JSON document + * { "foo": [ "fizz", "buzz", "fizzbuzz" ] }. + */ + jsonPatchDocument.appendAddRaw("/foo/-", "\"fizzbuzz\""); + // END: io.clientcore.core.serialization.json.models.JsonPatchDocument.appendAddRaw#String-String + } + + /** + * Codesnippets for {@link JsonPatchDocument#appendReplace(String, Object)}. + */ + public void appendReplace() throws IOException { + JsonPatchDocument jsonPatchDocument = new JsonPatchDocument(); + // BEGIN: io.clientcore.core.serialization.json.models.JsonPatchDocument.appendReplace#String-Object + /* + * Replace an object member in the JSON document { "bar": "qux", "foo": "bar" } to get the JSON document + * { "bar": "foo", "foo": "bar" }. + */ + jsonPatchDocument.appendReplace("/bar", "foo"); + + /* + * Replace an object member in the JSON document { "foo": "fizz" } to get the JSON document + * { "foo": [ "fizz", "buzz", "fizzbuzz" ] }. + */ + jsonPatchDocument.appendReplace("/foo", new String[] {"fizz", "buzz", "fizzbuzz"}); + + /* + * Given the JSON document { "foo": "bar" } the following is an example of an invalid replace operation as the + * target path doesn't exist in the document. + */ + jsonPatchDocument.appendReplace("/baz", "foo"); + // END: io.clientcore.core.serialization.json.models.JsonPatchDocument.appendReplace#String-Object + } + + /** + * Codesnippets for {@link JsonPatchDocument#appendReplaceRaw(String, String)}. + */ + public void appendReplaceRaw() { + JsonPatchDocument jsonPatchDocument = new JsonPatchDocument(); + // BEGIN: io.clientcore.core.serialization.json.models.JsonPatchDocument.appendReplaceRaw#String-String + /* + * Replace an object member in the JSON document { "bar": "qux", "foo": "bar" } to get the JSON document + * { "bar": "foo", "foo": "bar" }. + */ + jsonPatchDocument.appendReplaceRaw("/bar", "\"foo\""); + + /* + * Replace an object member in the JSON document { "foo": "fizz" } to get the JSON document + * { "foo": [ "fizz", "buzz", "fizzbuzz" ] }. + */ + jsonPatchDocument.appendReplaceRaw("/foo", "[ \"fizz\", \"buzz\", \"fizzbuzz\" ]"); + + /* + * Given the JSON document { "foo": "bar" } the following is an example of an invalid replace operation as the + * target path doesn't exist in the document. + */ + jsonPatchDocument.appendReplaceRaw("/baz", "\"foo\""); + // END: io.clientcore.core.serialization.json.models.JsonPatchDocument.appendReplaceRaw#String-String + } + + /** + * Codesnippets for {@link JsonPatchDocument#appendCopy(String, String)}. + */ + public void appendCopy() { + JsonPatchDocument jsonPatchDocument = new JsonPatchDocument(); + // BEGIN: io.clientcore.core.serialization.json.models.JsonPatchDocument.appendCopy#String-String + /* + * Copy an object member in the JSON document { "foo": "bar" } to get the JSON document + * { "foo": "bar", "copy": "bar" }. + */ + jsonPatchDocument.appendCopy("/foo", "/copy"); + + /* + * Copy an object member in the JSON document { "foo": { "bar": "baz" } } to get the JSON document + * { "foo": { "bar": "baz" }, "bar": "baz" }. + */ + jsonPatchDocument.appendCopy("/foo/bar", "/bar"); + + /* + * Given the JSON document { "foo": "bar" } the following is an example of an invalid copy operation as the + * target from doesn't exist in the document. + */ + jsonPatchDocument.appendCopy("/baz", "/fizz"); + // END: io.clientcore.core.serialization.json.models.JsonPatchDocument.appendCopy#String-String + } + + /** + * Codesnippets for {@link JsonPatchDocument#appendMove(String, String)}. + */ + public void appendMove() { + JsonPatchDocument jsonPatchDocument = new JsonPatchDocument(); + // BEGIN: io.clientcore.core.serialization.json.models.JsonPatchDocument.appendMove#String-String + /* + * Move an object member in the JSON document { "foo": "bar", "bar": "foo" } to get the JSON document + * { "bar": "bar" }. + */ + jsonPatchDocument.appendMove("/foo", "/bar"); + + /* + * Move an object member in the JSON document { "foo": { "bar": "baz" } } to get the JSON document + * { "foo": "baz" }. + */ + jsonPatchDocument.appendMove("/foo/bar", "/foo"); + + /* + * Given the JSON document { "foo": { "bar": "baz" } } the following is an example of an invalid move operation + * as the target path is a child of the target from. + */ + jsonPatchDocument.appendMove("/foo", "/foo/bar"); + + /* + * Given the JSON document { "foo": "bar" } the following is an example of an invalid move operation as the + * target from doesn't exist in the document. + */ + jsonPatchDocument.appendMove("/baz", "/fizz"); + // END: io.clientcore.core.serialization.json.models.JsonPatchDocument.appendMove#String-String + } + + /** + * Codesnippets for {@link JsonPatchDocument#appendRemove(String)}. + */ + public void appendRemove() { + JsonPatchDocument jsonPatchDocument = new JsonPatchDocument(); + // BEGIN: io.clientcore.core.serialization.json.models.JsonPatchDocument.appendRemove#String + /* + * Remove an object member in the JSON document { "foo": "bar", "bar": "foo" } to get the JSON document + * { "foo": "bar" }. + */ + jsonPatchDocument.appendRemove("/bar"); + + /* + * Remove an object member in the JSON document { "foo": { "bar": "baz" } } to get the JSON document + * { "foo": { } }. + */ + jsonPatchDocument.appendRemove("/foo/bar"); + + /* + * Given the JSON document { "foo": "bar" } the following is an example of an invalid remove operation as the + * target from doesn't exist in the document. + */ + jsonPatchDocument.appendRemove("/baz"); + // END: io.clientcore.core.serialization.json.models.JsonPatchDocument.appendRemove#String + } + + /** + * Codesnippets for {@link JsonPatchDocument#appendTest(String, Object)}. + */ + public void appendTest() throws IOException { + JsonPatchDocument jsonPatchDocument = new JsonPatchDocument(); + // BEGIN: io.clientcore.core.serialization.json.models.JsonPatchDocument.appendTest#String-Object + /* + * Test an object member in the JSON document { "foo": "bar" } to get a successful operation. + */ + jsonPatchDocument.appendTest("/foo", "bar"); + + /* + * Test an object member in the JSON document { "foo": "bar" } to get a unsuccessful operation. + */ + jsonPatchDocument.appendTest("/foo", 42); + + /* + * Given the JSON document { "foo": "bar" } the following is an example of an unsuccessful test operation as + * the target path doesn't exist in the document. + */ + jsonPatchDocument.appendTest("/baz", "bar"); + // END: io.clientcore.core.serialization.json.models.JsonPatchDocument.appendTest#String-Object + } + + /** + * Codesnippets for {@link JsonPatchDocument#appendTestRaw(String, String)}. + */ + public void appendTestRaw() { + JsonPatchDocument jsonPatchDocument = new JsonPatchDocument(); + // BEGIN: io.clientcore.core.serialization.json.models.JsonPatchDocument.appendTestRaw#String-String + /* + * Test an object member in the JSON document { "foo": "bar" } to get a successful operation. + */ + jsonPatchDocument.appendTestRaw("/foo", "\"bar\""); + + /* + * Test an object member in the JSON document { "foo": "bar" } to get a unsuccessful operation. + */ + jsonPatchDocument.appendTestRaw("/foo", "42"); + + /* + * Given the JSON document { "foo": "bar" } the following is an example of an unsuccessful test operation as + * the target path doesn't exist in the document. + */ + jsonPatchDocument.appendTestRaw("/baz", "\"bar\""); + // END: io.clientcore.core.serialization.json.models.JsonPatchDocument.appendTestRaw#String-String + } +} diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/util/ConfigurationJavaDocCodeSnippet.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/util/ConfigurationJavaDocCodeSnippet.java deleted file mode 100644 index 839b3e61f1a5..000000000000 --- a/sdk/clientcore/core/src/samples/java/io/clientcore/core/util/ConfigurationJavaDocCodeSnippet.java +++ /dev/null @@ -1,215 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.util; - -import io.clientcore.core.util.configuration.Configuration; -import io.clientcore.core.util.configuration.ConfigurationBuilder; -import io.clientcore.core.util.configuration.ConfigurationProperty; -import io.clientcore.core.util.configuration.ConfigurationPropertyBuilder; -import io.clientcore.core.util.configuration.ConfigurationSource; - -import java.time.Duration; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.ConcurrentHashMap; -import java.util.stream.Collectors; - -/** - * Codesnippets for {@link Configuration} - */ -public class ConfigurationJavaDocCodeSnippet { - public static final class SampleSource implements ConfigurationSource { - private final Map configurations; - - public SampleSource(Map configurations) { - this.configurations = Collections.unmodifiableMap(configurations); - } - - @Override - public Map getProperties(String path) { - if (path == null) { - return configurations; - } - - return configurations.entrySet().stream() - .filter(prop -> prop.getKey().startsWith(path + ".")) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - } - } - - /** - * Codesnippets for {@link ConfigurationBuilder}. - */ - public void configurationBuilderUsage() { - Map properties = new HashMap<>(); - properties.put("my.sdk.client-name.http.proxy.port", "8080"); - properties.put("my.sdk.http.proxy.hostname", " proxyHostnameProperty = ConfigurationPropertyBuilder.ofString("http.proxy.hostname") - .shared(true) - .build(); - System.out.println(configuration.get(proxyHostnameProperty)); - // END: io.clientcore.core.util.Configuration - - // BEGIN: io.clientcore.core.util.ConfigurationBuilder#putProperty - configuration = new ConfigurationBuilder() - .putProperty("my.sdk.client-name.connection-string", "...") - .root("my.sdk") - .buildSection("client-name"); - - ConfigurationProperty connectionStringProperty = ConfigurationPropertyBuilder.ofString("connection-string") - .build(); - - System.out.println(configuration.get(connectionStringProperty)); - // END: io.clientcore.core.util.ConfigurationBuilder#putProperty - - // BEGIN: io.clientcore.core.util.ConfigurationBuilder#buildSection - // Builds Configuration for with fallback to shared properties. - configuration = new ConfigurationBuilder(new SampleSource(properties)) - .root("my.sdk") - .buildSection("client-name"); - // END: io.clientcore.core.util.ConfigurationBuilder#buildSection - - // BEGIN: io.clientcore.core.util.ConfigurationBuilder#build - // Builds shared Configuration only. - Configuration sharedConfiguration = new ConfigurationBuilder(new SampleSource(properties)) - .root("my.sdk") - .build(); - // END: io.clientcore.core.util.ConfigurationBuilder#build - } - - /** - * Codesnippets for {@link Configuration}. - */ - public void configurationUsage() { - Map properties = new HashMap<>(); - properties.put("my.sdk..http.proxy.port", "8080"); - properties.put("my.sdk.http.proxy.hostname", ""); - - // BEGIN: io.clientcore.core.util.Configuration.get#ConfigurationProperty - ConfigurationProperty property = ConfigurationPropertyBuilder.ofString("http.proxy.hostname") - .shared(true) - .logValue(true) - .systemPropertyName("http.proxyHost") - .build(); - - // attempts to get local `my.sdk..http.proxy.host` property and falls back to - // shared my.sdk.http.proxy.port - System.out.println(configuration.get(property)); - // END: io.clientcore.core.util.Configuration.get#ConfigurationProperty - } - - /** - * Codesnippets for {@link ConfigurationProperty}. - */ - public void configurationPropertyUsage() { - Map properties = new HashMap<>(); - properties.put("my.sdk.sample.timeout", "1000"); - properties.put("my.sdk.sample.retry-count", "3"); - properties.put("my.sdk.sample.is-enabled", "true"); - properties.put("my.sdk.sample.mode", "mode1"); - - Configuration configuration = new ConfigurationBuilder(new SampleSource(properties)) - .root("my.sdk") - .buildSection("sample"); - - // BEGIN: io.clientcore.core.util.ConfigurationPropertyBuilder.ofDuration - ConfigurationProperty timeoutProperty = ConfigurationPropertyBuilder.ofDuration("timeout") - .build(); - System.out.println(configuration.get(timeoutProperty)); - // END: io.clientcore.core.util.ConfigurationPropertyBuilder.ofDuration - - // BEGIN: io.clientcore.core.util.ConfigurationPropertyBuilder - ConfigurationProperty modeProperty = - new ConfigurationPropertyBuilder<>("mode", SampleEnumProperty::fromString) - .logValue(true) - .defaultValue(SampleEnumProperty.MODE_1) - .build(); - System.out.println(configuration.get(modeProperty)); - // END: io.clientcore.core.util.ConfigurationPropertyBuilder - - // BEGIN: io.clientcore.core.util.ConfigurationPropertyBuilder.ofBoolean - ConfigurationProperty booleanProperty = ConfigurationPropertyBuilder.ofBoolean("is-enabled") - .build(); - System.out.println(configuration.get(booleanProperty)); - // END: io.clientcore.core.util.ConfigurationPropertyBuilder.ofBoolean - - // BEGIN: io.clientcore.core.util.ConfigurationPropertyBuilder.ofInteger - ConfigurationProperty integerProperty = ConfigurationPropertyBuilder.ofInteger("retry-count") - .build(); - System.out.println(configuration.get(integerProperty)); - // END: io.clientcore.core.util.ConfigurationPropertyBuilder.ofInteger - } - - public static final class SampleEnumProperty implements ExpandableEnum { - private static final Map VALUES = new ConcurrentHashMap<>(); - - private final String value; - - private SampleEnumProperty(String value) { - this.value = value; - } - - @Override - public String getValue() { - return value; - } - - public static final SampleEnumProperty MODE_1 = fromString("mode1"); - public static final SampleEnumProperty MODE_2 = fromString("mode2"); - - public static SampleEnumProperty fromString(String str) { - if (str == null) { - return null; - } - - SampleEnumProperty sampleEnumProperty = VALUES.get(str); - - if (sampleEnumProperty != null) { - return sampleEnumProperty; - } - - return VALUES.computeIfAbsent(str, SampleEnumProperty::new); - } - - @Override - public int hashCode() { - return Objects.hash(SampleEnumProperty.class, value); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if (!(obj instanceof SampleEnumProperty)) { - return false; - } - - SampleEnumProperty other = (SampleEnumProperty) obj; - return Objects.equals(value, other.value); - } - - @Override - public String toString() { - return value; - } - } -} diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/util/ClientLoggerJavaDocCodeSnippets.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/utils/ClientLoggerJavaDocCodeSnippets.java similarity index 96% rename from sdk/clientcore/core/src/samples/java/io/clientcore/core/util/ClientLoggerJavaDocCodeSnippets.java rename to sdk/clientcore/core/src/samples/java/io/clientcore/core/utils/ClientLoggerJavaDocCodeSnippets.java index d3d64fa2097a..a4ef7a1cfde9 100644 --- a/sdk/clientcore/core/src/samples/java/io/clientcore/core/util/ClientLoggerJavaDocCodeSnippets.java +++ b/sdk/clientcore/core/src/samples/java/io/clientcore/core/utils/ClientLoggerJavaDocCodeSnippets.java @@ -1,10 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.util; +package io.clientcore.core.utils; import io.clientcore.core.http.models.Response; import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.instrumentation.logging.LogLevel; import java.io.File; import java.io.IOException; @@ -127,8 +128,7 @@ public void loggingSnippets() { Response response = getResponse(); // BEGIN: io.clientcore.core.util.logging.clientlogger.atLevel - ClientLogger.LogLevel level = response.getStatusCode() == 200 - ? ClientLogger.LogLevel.INFORMATIONAL : ClientLogger.LogLevel.WARNING; + LogLevel level = response.getStatusCode() == 200 ? LogLevel.INFORMATIONAL : LogLevel.WARNING; logger.atLevel(level) .addKeyValue("key", "value") .log("message"); @@ -157,7 +157,7 @@ public void loggingSnippets() { } private Response getResponse() { - return Response.create(null, 200, null, null); + return new Response<>(null, 200, null, null); } /** diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/utils/ClientOptionsJavadocCodeSnippets.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/utils/ClientOptionsJavadocCodeSnippets.java new file mode 100644 index 000000000000..91d5865346eb --- /dev/null +++ b/sdk/clientcore/core/src/samples/java/io/clientcore/core/utils/ClientOptionsJavadocCodeSnippets.java @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.utils; + +/** + * Code snippets for {@link ClientOptions}. + */ +public final class ClientOptionsJavadocCodeSnippets { + /** + * Codesnippets for {@link ClientOptions#setApplicationId(String)}. + */ + public void setApplicationId() { + // BEGIN: io.clientcore.core.util.ClientOptions.setApplicationId#String + ClientOptions clientOptions = new ClientOptions() + .setApplicationId("myApplicationId"); + // END: io.clientcore.core.util.ClientOptions.setApplicationId#String + } +} diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/utils/ConfigurationJavaDocCodeSnippet.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/utils/ConfigurationJavaDocCodeSnippet.java new file mode 100644 index 000000000000..c96adfce859c --- /dev/null +++ b/sdk/clientcore/core/src/samples/java/io/clientcore/core/utils/ConfigurationJavaDocCodeSnippet.java @@ -0,0 +1,12 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.utils; + +import io.clientcore.core.utils.configuration.Configuration; + +/** + * Codesnippets for {@link Configuration} + */ +public class ConfigurationJavaDocCodeSnippet { +} diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/utils/union/BasicUnion.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/utils/union/BasicUnion.java new file mode 100644 index 000000000000..5fd28b9ce209 --- /dev/null +++ b/sdk/clientcore/core/src/samples/java/io/clientcore/core/utils/union/BasicUnion.java @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.utils.union; + +import io.clientcore.core.utils.Union; + +// This is a simple example of how to use the Union type. It allows for multiple types to be stored in a single +// property, and provides methods to consume the value based on its type. +public class BasicUnion { + public static void main(String[] args) { + Union union = Union.ofTypes(String.class, Integer.class, Double.class); + + // This union allows for String, Integer, and Double types + union.setValue("Hello"); + + // we can (attempt to) exhaustively consume the union using a switch statement... + handleUnion(union); + + // ... or we can pass in lambda expressions to consume the union for the types we care about + union.tryConsume(v -> System.out.println("String value from lambda: " + v), String.class); + + // ... or we can just get the value to the type we expect it to be using the getValue methods + String value = union.getValue(); + System.out.println("Value (from getValue()): " + value); + + value = union.getValue(String.class); + System.out.println("Value (from getValue(Class cls)): " + value); + + // Of course, this union supports Integer and Double types as well: + union.setValue(123); + handleUnion(union); + union.setValue(3.14); + handleUnion(union); + + // This will throw an IllegalArgumentException, as the union does not support the type Long + try { + union.setValue(123L); + } catch (IllegalArgumentException e) { + System.out.println("Caught exception: " + e.getMessage()); + } + } + + private static void handleUnion(Union union) { + // we can write an if-else block to consume the value in Java 8+, or switch pattern match in Java 17+ + Object value = union.getValue(); + if (value instanceof String) { + String s = (String) value; + System.out.println("String value from if-else: " + s); + } else if (value instanceof Integer) { + Integer i = (Integer) value; + System.out.println("Integer value from if-else: " + i); + } else if (value instanceof Double) { + Double d = (Double) value; + System.out.println("Double value from if-else: " + d); + } else { + throw new IllegalArgumentException("Unknown type: " + union.getCurrentType().getTypeName()); + } + } +} diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/utils/union/GenericModelType.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/utils/union/GenericModelType.java new file mode 100644 index 000000000000..c66d90544669 --- /dev/null +++ b/sdk/clientcore/core/src/samples/java/io/clientcore/core/utils/union/GenericModelType.java @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.utils.union; + +import io.clientcore.core.implementation.GenericParameterizedType; +import io.clientcore.core.utils.Union; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.Arrays; +import java.util.List; + +// This is an example of a Model class that uses the Union type to allow for multiple types to be stored in a single +// property, with the additional complexity that the types are all generic types (in this case, List, List, +// and List). +public class GenericModelType { + // We specify that the Union type can be one of three types: List, List, or List. + private Union prop = Union.ofTypes( + // GenericParameterizedType is a non-public helper class that allows us to specify a generic type with + // a class and a type. User can define any similar class to achieve the same functionality. + new GenericParameterizedType(List.class, String.class), + new GenericParameterizedType(List.class, Integer.class), + new GenericParameterizedType(List.class, Float.class)); + + // we give access to the Union type, so that the value can be modified and retrieved. + public Union getProp() { + return prop; + } + + // but our setter methods need to have more complex names, to differentiate them at runtime. + public GenericModelType setPropAsStrings(List strValues) { + prop.setValue(strValues); + return this; + } + public GenericModelType setPropAsIntegers(List intValues) { + prop.setValue(intValues); + return this; + } + public GenericModelType setPropAsFloats(List floatValues) { + prop.setValue(floatValues); + return this; + } + + public static void main(String[] args) { + GenericModelType model = new GenericModelType(); + model.setPropAsStrings(Arrays.asList("Hello", "World")); + + // in this case, it isn't possible to switch over the values easily (as we could in the ModelType class), as the + // types are all List types (and we would need to inspect the values inside the list to be sure). Instead, we + // can use the tryConsume method to consume the value if it is of the expected type. + List types = model.getProp().getSupportedTypes(); + for (Type type : types) { + if (type instanceof ParameterizedType) { + ParameterizedType parameterizedType = (ParameterizedType) type; + if (parameterizedType.getRawType() == List.class) { + Type actualType = parameterizedType.getActualTypeArguments()[0]; + if (actualType == String.class) { + model.getProp().tryConsume(strings -> System.out.println("Strings: " + strings), List.class, String.class); + break; + } else if (actualType == Integer.class) { + model.getProp().tryConsume(integers -> System.out.println("Integers: " + integers), List.class, Integer.class); + break; + } else if (actualType == Float.class) { + model.getProp().tryConsume(floats -> System.out.println("Floats: " + floats), List.class, Float.class); + break; + } + } + } + } + + // or, we can use the returned boolean value to determine if the value was consumed + if (model.getProp().tryConsume(integers -> System.out.println("Integers: " + integers), List.class, Integer.class)) { + System.out.println("Consumed as Integers"); + } else if (model.getProp().tryConsume(strings -> System.out.println("Strings: " + strings), List.class, String.class)) { + System.out.println("consumed as Strings"); + } else if (model.getProp().tryConsume(floats -> System.out.println("Floats: " + floats), List.class, Float.class)) { + System.out.println("consumed as Floats"); + } else { + System.out.println("Not consumed as Integers, Strings, Floats"); + } + } +} diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/utils/union/ModelType.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/utils/union/ModelType.java new file mode 100644 index 000000000000..c0d31d0a5a53 --- /dev/null +++ b/sdk/clientcore/core/src/samples/java/io/clientcore/core/utils/union/ModelType.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.utils.union; + +import io.clientcore.core.utils.Union; + +// This is an example of a Model class that uses the Union type to allow for multiple types to be stored in a single +// property. This is useful when you have a property that can be one of a few types, but you want to ensure that the +// types are known at compile time, and that you can easily switch on the type of the value. +public class ModelType { + private Union prop = Union.ofTypes(String.class, Integer.class, Double.class); + + public Union getProp() { + return prop; + } + + // In this case, because all three values of the Union type are distinct, we can have three setter methods to + // modify the Union in a type-safe way. If the types were not distinct, we would need to use a single setter method + // that took an Object type, and then rely on the Union type to ensure that the value was of the correct type. + // This would be the case (as we see in GenericModelType) where there are multiple types of the same class, such as + // List, List, and List. + public ModelType setProp(String str) { + prop.setValue(str); + return this; + } + public ModelType setProp(Integer integer) { + prop.setValue(integer); + return this; + } + public ModelType setProp(Double dbl) { + prop.setValue(dbl); + return this; + } + + public static void main(String[] args) { + ModelType modelType = new ModelType(); + modelType.setProp(23); + + // we can just call the getValue(Class cls) method to get the value as the type we expect it to be + System.out.println(modelType.getProp().getValue(Integer.class)); + + // or we can use the tryConsume method + modelType.getProp().tryConsume(v -> System.out.println("Value from lambda: " + v), Integer.class); + + // or we can write an if-else block to consume the value in Java 8+, or switch pattern match in Java 17+ + Object value = modelType.getProp().getValue(); + if (value instanceof String) { + String s = (String) value; + System.out.println("String value from if-else: " + s); + } else if (value instanceof Integer) { + Integer i = (Integer) value; + System.out.println("Integer value from if-else: " + i); + } else if (value instanceof Double) { + Double d = (Double) value; + System.out.println("Double value from if-else: " + d); + } else { + throw new IllegalArgumentException("Unknown type: " + modelType.getProp().getCurrentType().getTypeName()); + } + } +} diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/utils/union/NestedUnion.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/utils/union/NestedUnion.java new file mode 100644 index 000000000000..7c7ee47b088d --- /dev/null +++ b/sdk/clientcore/core/src/samples/java/io/clientcore/core/utils/union/NestedUnion.java @@ -0,0 +1,68 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.utils.union; + +import io.clientcore.core.implementation.GenericParameterizedType; +import io.clientcore.core.utils.Union; + +import java.util.Arrays; +import java.util.List; + +/** + * This is an example of a model class A that uses the Union type to allow for nested union type to be stored in a single + * property. + */ +public class NestedUnion { + public static void main(String[] args) { + NestedClassB nestedClassB = new NestedClassB(); + nestedClassB.setProp(Arrays.asList(1, 2, 3)); + System.out.println("Current Type of Nested Class B: " + nestedClassB.getProp().getCurrentType()); + System.out.println("Value from Nested Class B: " + + nestedClassB.getProp().getValue(new GenericParameterizedType(List.class, Integer.class))); + + ClassA outerClassA = new ClassA(); + outerClassA.setProp(nestedClassB); + NestedClassB nestedClassBFromA = outerClassA.getProp().getValue(NestedClassB.class); + System.out.println("Current Type of Nested Class B from Class A: " + nestedClassBFromA.getProp().getCurrentType()); + System.out.println("Value of Nested Class B from Class A: " + + nestedClassBFromA.getProp().getValue(new GenericParameterizedType(List.class, Integer.class))); + } + + private static class ClassA { + Union prop = Union.ofTypes(String.class, NestedClassB.class); + + public Union getProp() { + return prop; + } + + public ClassA setProp(String str) { + prop.setValue(str); + return this; + } + + // Nested Class B contains a Union type property. + public ClassA setProp(NestedClassB b) { + prop.setValue(b); + return this; + } + } + + private static class NestedClassB { + Union prop = Union.ofTypes(String.class, new GenericParameterizedType(List.class, Integer.class)); + + public Union getProp() { + return prop; + } + + public NestedClassB setProp(String str) { + prop.setValue(str); + return this; + } + + public NestedClassB setProp(List intList) { + prop.setValue(intList); + return this; + } + } +} diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/utils/union/PrimitiveUnionType.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/utils/union/PrimitiveUnionType.java new file mode 100644 index 000000000000..8f4d723a4d21 --- /dev/null +++ b/sdk/clientcore/core/src/samples/java/io/clientcore/core/utils/union/PrimitiveUnionType.java @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.utils.union; + + +import io.clientcore.core.utils.Union; + +// This is an example of a Model class that uses the Union type to allow for multiple types to be stored in a single +// property. This is useful when you have a property that can be one of a few types, but you want to ensure that the +// types are known at compile time, and that you can easily switch on the type of the value. +public class PrimitiveUnionType { + private Union prop = Union.ofTypes(int.class, float.class, double.class); + + public Union getProp() { + return prop; + } + + // In this case, because all three values of the Union type are distinct, we can have three setter methods to + // modify the Union in a type-safe way. If the types were not distinct, we would need to use a single setter method + // that took an Object type, and then rely on the Union type to ensure that the value was of the correct type. + // This would be the case (as we see in GenericModelType) where there are multiple types of the same class, such as + // List, List, and List. + public PrimitiveUnionType setProp(int i) { + prop.setValue(i); + return this; + } + public PrimitiveUnionType setProp(float f) { + prop.setValue(f); + return this; + } + public PrimitiveUnionType setProp(double d) { + prop.setValue(d); + return this; + } + + public static void main(String[] args) { + PrimitiveUnionType modelType = new PrimitiveUnionType(); + modelType.setProp(23); + System.out.println(modelType.getProp().getCurrentType()); + + // we can just call the getValue(Class cls) method to get the value as the type we expect it to be + System.out.println(modelType.getProp().getValue(int.class)); + + // or we can use the tryConsume method + modelType.getProp().tryConsume(v -> System.out.println("Value from lambda: " + v), int.class); + + // or we can write an if-else block to consume the value in Java 8+, or switch pattern match in Java 17+ + // but the switch expression doesn't work directly - we need to rely on the autoboxing to save us (Integer works, int doesn't) + Object value = modelType.getProp().getValue(); + if (value instanceof String) { + String s = (String) value; + System.out.println("String value from if-else: " + s); + } else if (value instanceof Integer) { + Integer i = (Integer) value; + System.out.println("Integer value from if-else: " + i); + } else if (value instanceof Double) { + Double d = (Double) value; + System.out.println("Double value from if-else: " + d); + } else { + throw new IllegalArgumentException("Unknown type: " + modelType.getProp().getCurrentType().getTypeName()); + } + } +} diff --git a/sdk/clientcore/core/src/samples/java/io/clientcore/core/utils/union/codesnippets/UnionJavaDocCodeSnippets.java b/sdk/clientcore/core/src/samples/java/io/clientcore/core/utils/union/codesnippets/UnionJavaDocCodeSnippets.java new file mode 100644 index 000000000000..e9f525172221 --- /dev/null +++ b/sdk/clientcore/core/src/samples/java/io/clientcore/core/utils/union/codesnippets/UnionJavaDocCodeSnippets.java @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.utils.union.codesnippets; + +import io.clientcore.core.implementation.GenericParameterizedType; +import io.clientcore.core.utils.Union; +import org.junit.jupiter.api.Test; + +import java.util.List; + +public class UnionJavaDocCodeSnippets { + + @Test + public void unionCreation() { + // BEGIN: io.clientcore.core.util.union.UnionJavaDocCodeSnippetsBasic + Union union = Union.ofTypes(String.class, Integer.class); + // END: io.clientcore.core.util.union.UnionJavaDocCodeSnippetsBasic + + // BEGIN: io.clientcore.core.util.union.UnionJavaDocCodeSnippetsPrimitiveType + Union unionPrimitives = Union.ofTypes(int.class, double.class); + // END: io.clientcore.core.util.union.UnionJavaDocCodeSnippetsPrimitiveType + + // BEGIN: io.clientcore.core.util.union.UnionJavaDocCodeSnippetsCollectionType + // GenericParameterizedType is a non-public helper class that allows us to specify a generic type with + // a class and a type. User can define any similar class to achieve the same functionality. + Union unionCollections = Union.ofTypes( + new GenericParameterizedType(List.class, String.class), + new GenericParameterizedType(List.class, Integer.class)); + // END: io.clientcore.core.util.union.UnionJavaDocCodeSnippetsCollectionType + } + + @Test + public void unionConsumeIfElseStatement() { + // BEGIN: io.clientcore.core.util.union.UnionJavaDocCodeSnippetsIfElseStatement + Union union = Union.ofTypes(String.class, Integer.class); + union.setValue("Hello"); + Object value = union.getValue(); + // we can write an if-else block to consume the value in Java 8+, or switch pattern match in Java 17+ + if (value instanceof String) { + String s = (String) value; + System.out.println("String value: " + s); + } else if (value instanceof Integer) { + Integer i = (Integer) value; + System.out.println("Integer value: " + i); + } else { + throw new IllegalArgumentException("Unknown type: " + union.getCurrentType().getTypeName()); + } + // END: io.clientcore.core.util.union.UnionJavaDocCodeSnippetsIfElseStatement + } + + @Test + public void unionConsumeLambda() { + // BEGIN: io.clientcore.core.util.union.UnionJavaDocCodeSnippetsLambda + Union union = Union.ofTypes(String.class, Integer.class); + union.setValue("Hello"); + union.tryConsume( + v -> System.out.println("String value: " + v), String.class); + union.tryConsume( + v -> System.out.println("Integer value: " + v), Integer.class); + // END: io.clientcore.core.util.union.UnionJavaDocCodeSnippetsLambda + } + +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/credential/CredentialsTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/credential/CredentialsTests.java deleted file mode 100644 index 11b2059da6ad..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/credential/CredentialsTests.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.credential; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtensionContext; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.ArgumentsProvider; -import org.junit.jupiter.params.provider.ArgumentsSource; - -import java.util.stream.Stream; - -public class CredentialsTests { - - private static final String DUMMY_NAME = "Dummy-Name"; - private static final String DUMMY_VALUE = "DummyValue"; - - static class InvalidInputsArgumentProvider implements ArgumentsProvider { - - InvalidInputsArgumentProvider() { - } - - @Override - public Stream provideArguments(ExtensionContext context) { - return Stream.of(Arguments.of(null, NullPointerException.class), - Arguments.of(null, NullPointerException.class), Arguments.of("", IllegalArgumentException.class), - Arguments.of("", IllegalArgumentException.class), Arguments.of("", IllegalArgumentException.class)); - } - } - - @ParameterizedTest - @ArgumentsSource(InvalidInputsArgumentProvider.class) - public void keyCredentialsInvalidArgumentTest(String key, Class exceptionType) { - Assertions.assertThrows(exceptionType, () -> new KeyCredential(key)); - } - - @Test - public void keyCredentialValueTest() { - KeyCredential keyCredential = new KeyCredential(DUMMY_VALUE); - - Assertions.assertEquals(DUMMY_VALUE, keyCredential.getKey()); - } - - @Test - public void keyCredentialUpdateTest() { - KeyCredential keyCredential = new KeyCredential(DUMMY_NAME); - - String expectedValue = "NewValue"; - - keyCredential.update(expectedValue); - - Assertions.assertEquals(expectedValue, keyCredential.getKey()); - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/credentials/KeyCredentialTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/credentials/KeyCredentialTests.java new file mode 100644 index 000000000000..5bf1d18908cb --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/credentials/KeyCredentialTests.java @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.credentials; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +/** + * Unit tests for {@link KeyCredential}. + */ +public class KeyCredentialTests { + private static final String DUMMY_VALUE = "DummyValue"; + + @ParameterizedTest + @MethodSource("keyCredentialsInvalidArgumentTestSupplier") + public void keyCredentialsInvalidArgumentTest(String key, Class exceptionType) { + Assertions.assertThrows(exceptionType, () -> new KeyCredential(key)); + } + + private static Stream keyCredentialsInvalidArgumentTestSupplier() { + return Stream.of(Arguments.of(null, NullPointerException.class), + Arguments.of("", IllegalArgumentException.class)); + } + + @Test + public void keyCredentialValueTest() { + KeyCredential keyCredential = new KeyCredential(DUMMY_VALUE); + + Assertions.assertEquals(DUMMY_VALUE, keyCredential.getKey()); + } + + @Test + public void keyCredentialUpdateTest() { + KeyCredential keyCredential = new KeyCredential(DUMMY_VALUE); + + String expectedValue = "NewValue"; + keyCredential.update(expectedValue); + + Assertions.assertEquals(expectedValue, keyCredential.getKey()); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/credentials/NamedKeyCredentialTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/credentials/NamedKeyCredentialTests.java new file mode 100644 index 000000000000..c7680522cc76 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/credentials/NamedKeyCredentialTests.java @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.credentials; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +/** + * Unit tests for {@link NamedKeyCredential}. + */ +public class NamedKeyCredentialTests { + private static final String DUMMY_NAME = "Dummy-Name"; + private static final String DUMMY_VALUE = "DummyValue"; + + @ParameterizedTest + @MethodSource("namedKeyCredentialsInvalidArgumentTestSupplier") + public void namedKeyCredentialsInvalidArgumentTest(String name, String key, Class exceptionType) { + Assertions.assertThrows(exceptionType, () -> new NamedKeyCredential(name, key)); + } + + @ParameterizedTest + @MethodSource("namedKeyCredentialsInvalidArgumentTestSupplier") + public void namedKeyCredentialInvalidUpdateTest(String name, String key, Class exceptionType) { + Assertions.assertThrows(exceptionType, () -> new NamedKeyCredential(DUMMY_NAME, DUMMY_VALUE).update(name, key)); + } + + private static Stream namedKeyCredentialsInvalidArgumentTestSupplier() { + return Stream.of(Arguments.of(null, "key", NullPointerException.class), + Arguments.of("name", null, NullPointerException.class), + Arguments.of("", "key", IllegalArgumentException.class), + Arguments.of("name", "", IllegalArgumentException.class)); + } + + @Test + public void keyCredentialValueTest() { + NamedKeyCredential keyCredential = new NamedKeyCredential(DUMMY_NAME, DUMMY_VALUE); + + Assertions.assertEquals(DUMMY_NAME, keyCredential.getNamedKey().getName()); + Assertions.assertEquals(DUMMY_VALUE, keyCredential.getNamedKey().getKey()); + } + + @Test + public void keyCredentialUpdateTest() { + NamedKeyCredential keyCredential = new NamedKeyCredential(DUMMY_NAME, DUMMY_VALUE); + + String expectedName = "New-Name"; + String expectedValue = "NewValue"; + keyCredential.update(expectedName, expectedValue); + + Assertions.assertEquals(expectedName, keyCredential.getNamedKey().getName()); + Assertions.assertEquals(expectedValue, keyCredential.getNamedKey().getKey()); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/FooListResult.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/FooListResult.java new file mode 100644 index 000000000000..b93e55888000 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/FooListResult.java @@ -0,0 +1,114 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.http; + +import io.clientcore.core.implementation.serializer.Foo; +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonSerializable; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.serialization.json.JsonWriter; + +import java.io.IOException; +import java.util.List; + +/** + * The result of a list request. + */ +public final class FooListResult implements JsonSerializable { + /* + * The collection value. + */ + private List items; + + /* + * The URI that can be used to request the next set of paged results. + */ + private String nextLink; + + /** + * Creates an instance of FooListResult class. + */ + public FooListResult() { + } + + /** + * Get the items property: The collection value. + * + * @return the items value. + */ + public List getItems() { + return this.items; + } + + /** + * Set the items property: The collection value. + * + * @param items the items value to set. + * @return the FooListResult object itself. + */ + public FooListResult setItems(List items) { + this.items = items; + return this; + } + + /** + * Get the nextLink property: The URI that can be used to request the next set of paged results. + * + * @return the nextLink value. + */ + public String getNextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The URI that can be used to request the next set of paged results. + * + * @param nextLink the nextLink value to set. + * @return the FooListResult object itself. + */ + public FooListResult setNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("items", this.items, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("@nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of FooListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of FooListResult 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 FooListResult. + */ + public static FooListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + FooListResult deserializedFooListResult = new FooListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("items".equals(fieldName)) { + List items = reader.readArray(reader1 -> Foo.fromJson(reader1)); + deserializedFooListResult.items = items; + } else if ("@nextLink".equals(fieldName)) { + deserializedFooListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedFooListResult; + }); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/MockHttpResponse.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/MockHttpResponse.java index 8aba648b66e5..4858be00fd73 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/MockHttpResponse.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/MockHttpResponse.java @@ -5,13 +5,12 @@ import io.clientcore.core.http.models.HttpHeaders; import io.clientcore.core.http.models.HttpRequest; -import io.clientcore.core.http.models.HttpResponse; -import io.clientcore.core.util.binarydata.BinaryData; -import io.clientcore.core.implementation.util.JsonSerializer; -import io.clientcore.core.util.serializer.ObjectSerializer; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.serialization.json.JsonSerializer; -public class MockHttpResponse extends HttpResponse { - private static final ObjectSerializer SERIALIZER = new JsonSerializer(); +public class MockHttpResponse extends Response { + private static final JsonSerializer SERIALIZER = new JsonSerializer(); /** * Creates an HTTP response associated with a {@code request}, returns the {@code statusCode}, and has an empty diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/NoOpHttpClient.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/NoOpHttpClient.java deleted file mode 100644 index 2874f6363064..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/NoOpHttpClient.java +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.http; - -import io.clientcore.core.http.client.HttpClient; -import io.clientcore.core.http.models.HttpHeaders; -import io.clientcore.core.http.models.HttpRequest; -import io.clientcore.core.http.models.HttpResponse; -import io.clientcore.core.http.models.Response; - -public class NoOpHttpClient implements HttpClient { - @Override - public Response send(HttpRequest request) { - return new HttpResponse<>(request, 200, new HttpHeaders(), null); // No-op - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/RestProxyResponseConstructionBenchmark.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/RestProxyResponseConstructionBenchmark.java index aaced88f062b..fa741294d037 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/RestProxyResponseConstructionBenchmark.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/RestProxyResponseConstructionBenchmark.java @@ -6,7 +6,6 @@ import io.clientcore.core.http.models.HttpHeaders; import io.clientcore.core.http.models.HttpMethod; import io.clientcore.core.http.models.HttpRequest; -import io.clientcore.core.http.models.HttpResponse; import io.clientcore.core.http.models.Response; import io.clientcore.core.implementation.ReflectiveInvoker; import io.clientcore.core.implementation.TypeUtil; @@ -38,11 +37,12 @@ public class RestProxyResponseConstructionBenchmark { private static final ResponseConstructorsCache CONSTRUCTORS_CACHE = new ResponseConstructorsCache(); - private static final HttpRequest REQUEST = new HttpRequest(HttpMethod.GET, "https://example.com"); + private static final HttpRequest REQUEST + = new HttpRequest().setMethod(HttpMethod.GET).setUri("https://example.com"); private static final HttpHeaders HEADERS = new HttpHeaders(); private static final Class> RESPONSE_TYPE = (Class>) TypeUtil - .getRawClass(TypeUtil.createParameterizedType(HttpResponse.class, Object.class, String.class)); + .getRawClass(TypeUtil.createParameterizedType(Response.class, Object.class, String.class)); /** * Benchmarks creating a {@link Response} type using the constructor directly when possible (types outside the scope @@ -52,7 +52,7 @@ public class RestProxyResponseConstructionBenchmark { */ @Benchmark public void directConstruction(Blackhole blackhole) { - blackhole.consume(new HttpResponse<>(REQUEST, 200, HEADERS, "value")); + blackhole.consume(new Response<>(REQUEST, 200, HEADERS, "value")); } /** diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/RestProxySpecialParametersBenchmark.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/RestProxySpecialParametersBenchmark.java index 235124d10d07..b358efca73b9 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/RestProxySpecialParametersBenchmark.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/RestProxySpecialParametersBenchmark.java @@ -4,7 +4,7 @@ package io.clientcore.core.http; import io.clientcore.core.http.models.RequestOptions; -import io.clientcore.core.util.Context; +import io.clientcore.core.utils.Context; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; @@ -18,7 +18,7 @@ import java.util.concurrent.TimeUnit; -import static io.clientcore.core.util.TestUtils.findFirstOfType; +import static io.clientcore.core.utils.TestUtils.findFirstOfType; /** * Benchmarks retrieving the special parameters {@link Context} and {@link RequestOptions}. diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/RestProxyTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/RestProxyTests.java index 814063ec25fc..9f99d8b80ae0 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/RestProxyTests.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/RestProxyTests.java @@ -3,21 +3,29 @@ package io.clientcore.core.http; -import io.clientcore.core.annotation.ServiceInterface; -import io.clientcore.core.http.annotation.BodyParam; -import io.clientcore.core.http.annotation.HeaderParam; -import io.clientcore.core.http.annotation.HttpRequestInformation; -import io.clientcore.core.http.annotation.PathParam; +import io.clientcore.core.annotations.ServiceInterface; +import io.clientcore.core.http.annotations.BodyParam; +import io.clientcore.core.http.annotations.HeaderParam; +import io.clientcore.core.http.annotations.HostParam; +import io.clientcore.core.http.annotations.HttpRequestInformation; +import io.clientcore.core.http.annotations.PathParam; import io.clientcore.core.http.client.HttpClient; -import io.clientcore.core.http.models.ContentType; import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpHeaders; import io.clientcore.core.http.models.HttpMethod; import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.RequestOptions; import io.clientcore.core.http.models.Response; +import io.clientcore.core.http.models.ResponseBodyMode; +import io.clientcore.core.http.paging.PagedIterable; +import io.clientcore.core.http.paging.PagedResponse; import io.clientcore.core.http.pipeline.HttpPipeline; import io.clientcore.core.http.pipeline.HttpPipelineBuilder; -import io.clientcore.core.util.binarydata.BinaryData; -import io.clientcore.core.implementation.util.JsonSerializer; +import io.clientcore.core.implementation.http.ContentType; +import io.clientcore.core.implementation.serializer.Foo; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.serialization.json.JsonSerializer; +import io.clientcore.core.utils.Context; import org.junit.jupiter.api.Named; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -30,9 +38,14 @@ import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Path; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -40,6 +53,11 @@ * Tests {@link RestProxy}. */ public class RestProxyTests { + private static final String FIRST_PAGE_RESPONSE + = "[{\"bar\":\"hello.world\",\"baz\":[\"hello\",\"hello.world\"],\"qux\":{\"a.b\":\"c.d\",\"bar.a\":\"ttyy\",\"bar.b\":\"uuzz\",\"hello\":\"world\"}}]"; + private static final String NEXTLINK_RESPONSE + = "[{\"bar\":\"hello.world2\",\"additionalProperties\":{\"bar\":\"baz\",\"a.b\":\"c.d\",\"properties.bar\":\"barbar\"}}]"; + @ServiceInterface(name = "myService", host = "https://somecloud.com") interface TestInterface { @HttpRequestInformation(method = HttpMethod.POST, path = "my/uri/path", expectedStatusCodes = { 200 }) @@ -64,6 +82,21 @@ Response testMethod(@BodyParam("application/octet-stream") BinaryData data @HttpRequestInformation(method = HttpMethod.GET, path = "my/uri/path", expectedStatusCodes = { 200 }) Response testDownload(); + + @HttpRequestInformation(method = HttpMethod.GET, path = "foos", expectedStatusCodes = { 200 }) + Response listFooListResult(@HostParam("uri") String uri, RequestOptions requestOptions, + Context context); + + @HttpRequestInformation(method = HttpMethod.GET, path = "{nextLink}", expectedStatusCodes = { 200 }) + Response listNextFooListResult(@PathParam(value = "nextLink", encoded = true) String nextLink, + RequestOptions requestOptions, Context context); + + @HttpRequestInformation(method = HttpMethod.GET, path = "foos", expectedStatusCodes = { 200 }) + Response> listFoo(@HostParam("uri") String uri, RequestOptions requestOptions, Context context); + + @HttpRequestInformation(method = HttpMethod.GET, path = "{nextLink}", expectedStatusCodes = { 200 }) + Response> listNextFoo(@PathParam(value = "nextLink", encoded = true) String nextLink, + RequestOptions requestOptions, Context context); } @Test @@ -175,7 +208,7 @@ private static final class LocalHttpClient implements HttpClient { private volatile boolean closeCalledOnResponse; @Override - public Response send(HttpRequest request) { + public Response send(HttpRequest request) { lastHttpRequest = request; boolean success = request.getUri().getPath().equals("/my/uri/path"); @@ -186,7 +219,7 @@ public Response send(HttpRequest request) { || request.getHttpMethod().equals(HttpMethod.HEAD); } - return new MockHttpResponse(request, success ? 200 : 400) { + return new Response(request, success ? 200 : 400, new HttpHeaders(), BinaryData.empty()) { @Override public void close() throws IOException { closeCalledOnResponse = true; @@ -208,11 +241,137 @@ public void doesNotChangeEncodedPath() throws IOException { HttpPipeline pipeline = new HttpPipelineBuilder().httpClient((request) -> { assertEquals(nextLinkUri, request.getUri().toString()); - return new MockHttpResponse(null, 200); + return new Response<>(null, 200, new HttpHeaders(), BinaryData.empty()); }).build(); TestInterface testInterface = RestProxy.create(TestInterface.class, pipeline, new JsonSerializer()); testInterface.testListNext(nextLinkUri).close(); } + + @Test + public void testListFooListResult() { + String uri = "https://somecloud.com"; + String firstPageUri = uri + "/foos"; + String nextLinkUri = uri + "/foos?page=2"; + RequestOptions requestOptions = new RequestOptions().setResponseBodyMode(ResponseBodyMode.DESERIALIZE); + HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(request -> { + String requestUri = request.getUri().toString(); + request.setRequestOptions(requestOptions); + if (firstPageUri.equals(requestUri)) { + return createMockResponse(request, + BinaryData.fromString( + "{\"items\":[{\"bar\":\"hello.world\",\"baz\":[\"hello\",\"hello.world\"],\"qux\":{\"a" + + ".b\":\"c.d\"," + + "\"bar.a\":\"ttyy\",\"bar.b\":\"uuzz\",\"hello\":\"world\"}}], \"nextLink\":\"" + + nextLinkUri + "\"}"), + nextLinkUri); + } else if (nextLinkUri.equals(requestUri)) { + return createMockResponse(request, + BinaryData.fromString( + "{\"items\":[{\"bar\":\"hello.world2\",\"additionalProperties\":{\"bar\":\"baz\",\"a" + + ".b\":\"c.d\",\"properties.bar\":\"barbar\"}}]"), + null); + } + return new Response<>(request, 404, new HttpHeaders(), BinaryData.empty()); + }).build(); + + TestInterface testInterface = RestProxy.create(TestInterface.class, pipeline, new JsonSerializer()); + + // Fetch the first page + PagedIterable pagedIterable = new PagedIterable<>( + pagingOptions -> toPagedResponse( + testInterface.listFooListResult(uri, RequestOptions.none(), Context.none()), null), + (pagingOptions, nextLink) -> toPagedResponse( + testInterface.listNextFooListResult(nextLink, RequestOptions.none(), Context.none()), nextLink)); + + assertNotNull(pagedIterable); + Set allItems = pagedIterable.stream().collect(Collectors.toSet()); + assertEquals(1, allItems.size()); + } + + /** + * Creates a mock HTTP response with JSON body and optional nextLink header. + */ + private Response createMockResponse(HttpRequest request, BinaryData jsonBody, String nextLink) { + HttpHeaders headers = new HttpHeaders(); + if (nextLink != null) { + headers.set(HttpHeaderName.fromString("nextLink"), nextLink); + } + + return new Response<>(request, 200, headers, jsonBody); + } + + /** + * Tests that a response with List is correctly handled with a paging wrapper. + */ + @Test + public void testListFoo() { + String uri = "https://somecloud.com"; + String firstPageUri = uri + "/foos"; + String nextLinkUri = uri + "/foos?page=2"; + RequestOptions requestOptions = new RequestOptions().setResponseBodyMode(ResponseBodyMode.DESERIALIZE); + HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(request -> { + String requestUri = request.getUri().toString(); + request.setRequestOptions(requestOptions); + if (firstPageUri.equals(requestUri)) { + return createMockResponse(request, BinaryData.fromString(FIRST_PAGE_RESPONSE), nextLinkUri); + } else if (nextLinkUri.equals(requestUri)) { + return createMockResponse(request, BinaryData.fromString(NEXTLINK_RESPONSE), null); + } + + return new Response<>(request, 404, new HttpHeaders(), BinaryData.empty()); + }).build(); + TestInterface testInterface = RestProxy.create(TestInterface.class, pipeline, new JsonSerializer()); + + // Retrieve initial response + Response> initialResponse = testInterface.listFoo(uri, RequestOptions.none(), Context.none()); + + List fooFirstPageResponse = initialResponse.getValue(); + assertNotNull(fooFirstPageResponse); + assertNotNull(fooFirstPageResponse.get(0).bar()); + + // Convert List response to PagedResponse + PagedResponse firstPage = toPagedResponse(initialResponse, null); + + PagedIterable pagedIterable = new PagedIterable<>(pagingOptions -> firstPage, // First page + (pagingOptions, nextLink) -> { + Response> nextResponse + = testInterface.listNextFoo(nextLink, RequestOptions.none(), Context.none()); + return toPagedResponse(nextResponse, nextLink); + }); + + assertNotNull(pagedIterable); + Set allItems = pagedIterable.stream().collect(Collectors.toSet()); + assertEquals(1, allItems.size()); + } + + /** + * Converts a Response<T> to a PagedResponse<Foo>. + * Supports both Response<FooListResult> and Response<List<Foo>>. + */ + @SuppressWarnings({ "unchecked", "cast" }) + private PagedResponse toPagedResponse(Response response, String nextLink) { + if (response == null || response.getValue() == null) { + return new PagedResponse<>( + response != null + ? response.getRequest() + : new HttpRequest().setMethod(HttpMethod.GET).setUri("https://somecloud.com"), + 200, response != null ? response.getHeaders() : new HttpHeaders(), Collections.emptyList()); // Return an empty list when null + } + + List items; + if (response.getValue() instanceof FooListResult) { + items = ((FooListResult) response.getValue()).getItems(); // Extract list from FooListResult + nextLink = ((FooListResult) response.getValue()).getNextLink(); + } else if (response.getValue() instanceof List) { + items = (List) response.getValue(); // Directly use the List + } else { + throw new IllegalArgumentException( + "Unsupported response type: " + response.getValue().getClass().getName()); + } + + return new PagedResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), items, + nextLink, null, null, null, null); + } } diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/client/DefaultHttpClientBuilderTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/client/DefaultHttpClientBuilderTests.java deleted file mode 100644 index 504f137c0e5f..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/client/DefaultHttpClientBuilderTests.java +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.http.client; - -import io.clientcore.core.http.models.HttpMethod; -import io.clientcore.core.http.models.HttpRequest; -import io.clientcore.core.http.models.ProxyOptions; -import io.clientcore.core.http.models.Response; -import io.clientcore.core.shared.LocalTestServer; -import io.clientcore.core.shared.TestConfigurationSource; -import io.clientcore.core.util.configuration.Configuration; -import io.clientcore.core.util.configuration.ConfigurationBuilder; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import javax.servlet.ServletException; -import java.io.IOException; -import java.net.InetSocketAddress; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; - -/** - * Tests {@link DefaultHttpClientBuilder}. - */ -public class DefaultHttpClientBuilderTests { - private static final String PROXY_USERNAME = "foo"; - private static final String PROXY_PASSWORD = "bar"; - private static final String PROXY_USER_INFO = PROXY_USERNAME + ":" + PROXY_PASSWORD + "@"; - private static final String SERVICE_ENDPOINT = "/default"; - private static final TestConfigurationSource EMPTY_SOURCE = new TestConfigurationSource(); - - private static LocalTestServer server; - private static SimpleBasicAuthHttpProxyServer proxyServer; - private static SimpleBasicAuthHttpProxyServer.ProxyEndpoint proxyEndpoint; - - @BeforeAll - public static void startTestServer() { - server = new LocalTestServer((req, resp, requestBody) -> { - if ("GET".equalsIgnoreCase(req.getMethod()) && SERVICE_ENDPOINT.equals(req.getServletPath())) { - resp.setStatus(200); - } else { - throw new ServletException("Unexpected request: " + req.getMethod() + " " + req.getServletPath()); - } - }); - - server.start(); - - proxyServer = new SimpleBasicAuthHttpProxyServer(PROXY_USERNAME, PROXY_PASSWORD, SERVICE_ENDPOINT); - proxyEndpoint = proxyServer.start(); - } - - @AfterAll - public static void stopTestServer() { - if (server != null) { - server.stop(); - } - - if (proxyServer != null) { - proxyServer.shutdown(); - } - } - - @Test - public void buildWithHttpProxy() throws IOException { - ProxyOptions clientProxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, - new InetSocketAddress(proxyEndpoint.getHost(), proxyEndpoint.getPort())).setCredentials(PROXY_USERNAME, - PROXY_PASSWORD); - - HttpClient httpClient = new DefaultHttpClientBuilder().proxy(clientProxyOptions).build(); - - final String serviceUri = "http://localhost:80" + SERVICE_ENDPOINT; - - try (Response response = httpClient.send(new HttpRequest(HttpMethod.GET, serviceUri))) { - assertEquals(200, response.getStatusCode()); - } - } - - @Test - public void buildWithHttpProxyFromEnvConfiguration() throws IOException { - Configuration configuration = new ConfigurationBuilder(EMPTY_SOURCE, EMPTY_SOURCE, - new TestConfigurationSource() - .put(Configuration.PROPERTY_HTTP_PROXY, - "http://" + PROXY_USER_INFO + proxyEndpoint.getHost() + ":" + proxyEndpoint.getPort()) - .put("java.net.useSystemProxies", "true")).build(); - - HttpClient httpClient = new DefaultHttpClientBuilder().configuration(configuration).build(); - - final String serviceUri = "http://localhost:80" + SERVICE_ENDPOINT; - - try (Response response = httpClient.send(new HttpRequest(HttpMethod.GET, serviceUri))) { - assertEquals(200, response.getStatusCode()); - } - } - - @Test - public void buildWithHttpProxyFromExplicitConfiguration() throws IOException { - Configuration configuration - = new ConfigurationBuilder().putProperty("http.proxy.hostname", proxyEndpoint.getHost()) - .putProperty("http.proxy.port", String.valueOf(proxyEndpoint.getPort())) - .putProperty("http.proxy.username", PROXY_USERNAME) - .putProperty("http.proxy.password", PROXY_PASSWORD) - .build(); - - HttpClient httpClient = new DefaultHttpClientBuilder().configuration(configuration).build(); - - final String serviceUri = "http://localhost:80" + SERVICE_ENDPOINT; - - try (Response response = httpClient.send(new HttpRequest(HttpMethod.GET, serviceUri))) { - assertEquals(200, response.getStatusCode()); - } - } - - @Test - public void buildWithNullProxyAddress() { - ProxyOptions mockPoxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, null); - assertThrows(NullPointerException.class, () -> new DefaultHttpClientBuilder().proxy(mockPoxyOptions)); - } - - @Test - public void buildWithNullProxyType() { - ProxyOptions mockPoxyOptions - = new ProxyOptions(null, new InetSocketAddress(proxyEndpoint.getHost(), proxyEndpoint.getPort())); - assertThrows(NullPointerException.class, () -> new DefaultHttpClientBuilder().proxy(mockPoxyOptions)); - } - - @Test - public void buildWithoutProxyAuthentication() throws IOException { - ProxyOptions clientProxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, - new InetSocketAddress(proxyEndpoint.getHost(), proxyEndpoint.getPort())); - - HttpClient httpClient = new DefaultHttpClientBuilder().proxy(clientProxyOptions).build(); - - final String serviceUri = "http://localhost:80" + SERVICE_ENDPOINT; - - try (Response response = httpClient.send(new HttpRequest(HttpMethod.GET, serviceUri))) { - assertNotNull(response); - } - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/client/DefaultHttpClientTest.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/client/DefaultHttpClientTest.java deleted file mode 100644 index e03a945adc77..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/client/DefaultHttpClientTest.java +++ /dev/null @@ -1,297 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.http.client; - -import io.clientcore.core.http.models.ContentType; -import io.clientcore.core.http.models.HttpHeader; -import io.clientcore.core.http.models.HttpHeaderName; -import io.clientcore.core.http.models.HttpHeaders; -import io.clientcore.core.http.models.HttpMethod; -import io.clientcore.core.http.models.HttpRequest; -import io.clientcore.core.http.models.RequestOptions; -import io.clientcore.core.http.models.Response; -import io.clientcore.core.shared.InsecureTrustManager; -import io.clientcore.core.shared.LocalTestServer; -import io.clientcore.core.util.Context; -import io.clientcore.core.util.TestUtils; -import io.clientcore.core.util.binarydata.BinaryData; -import org.conscrypt.Conscrypt; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.servlet.ServletException; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.charset.StandardCharsets; -import java.security.GeneralSecurityException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.ForkJoinPool; -import java.util.concurrent.TimeUnit; - -import static io.clientcore.core.util.TestUtils.assertArraysEqual; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@Execution(ExecutionMode.SAME_THREAD) -public class DefaultHttpClientTest { - static final String RETURN_HEADERS_AS_IS_PATH = "/returnHeadersAsIs"; - private static final byte[] SHORT_BODY = "hi there".getBytes(StandardCharsets.UTF_8); - private static final byte[] LONG_BODY = createLongBody(); - private static LocalTestServer server; - private static final String SSE_RESPONSE = "/serversentevent"; - - @BeforeAll - public static void startTestServer() { - server = new LocalTestServer((req, resp, requestBody) -> { - String path = req.getServletPath(); - boolean get = "GET".equalsIgnoreCase(req.getMethod()); - boolean post = "POST".equalsIgnoreCase(req.getMethod()); - boolean put = "PUT".equalsIgnoreCase(req.getMethod()); - - if (get && "/short".equals(path)) { - resp.setContentType("application/octet-stream"); - resp.setContentLength(SHORT_BODY.length); - resp.getOutputStream().write(SHORT_BODY); - } else if (get && "/long".equals(path)) { - resp.setContentType("application/octet-stream"); - resp.setContentLength(LONG_BODY.length); - resp.getOutputStream().write(LONG_BODY); - } else if (get && "/error".equals(path)) { - resp.setStatus(500); - resp.setContentLength(5); - resp.getOutputStream().write("error".getBytes(StandardCharsets.UTF_8)); - } else if (post && "/shortPost".equals(path)) { - resp.setContentType("application/octet-stream"); - resp.setContentLength(SHORT_BODY.length); - resp.getOutputStream().write(SHORT_BODY); - } else if (get && RETURN_HEADERS_AS_IS_PATH.equals(path)) { - List headerNames = Collections.list(req.getHeaderNames()); - headerNames.forEach(headerName -> { - List headerValues = Collections.list(req.getHeaders(headerName)); - headerValues.forEach(headerValue -> resp.addHeader(headerName, headerValue)); - }); - } else if (get && "/empty".equals(path)) { - resp.setContentType("application/octet-stream"); - resp.setContentLength(0); - } else if (get && "/connectionClose".equals(path)) { - resp.getHttpChannel().getConnection().close(); - } else if (get && SSE_RESPONSE.equals(path)) { - if (req.getHeader("Last-Event-Id") != null) { - sendSSELastEventIdResponse(resp); - } else { - sendSSEResponseWithRetry(resp); - } - } else if (post && SSE_RESPONSE.equals(path)) { - sendSSEResponseWithDataOnly(resp); - } else if (put && SSE_RESPONSE.equals(path)) { - resp.addHeader("Content-Type", ContentType.TEXT_EVENT_STREAM); - resp.setStatus(200); - resp.getOutputStream().write(("msg hello world \n\n").getBytes()); - resp.flushBuffer(); - } else { - throw new ServletException("Unexpected request " + req.getMethod() + " " + path); - } - }); - - server.start(); - } - - private static void sendSSEResponseWithDataOnly(org.eclipse.jetty.server.Response resp) throws IOException { - resp.addHeader("Content-Type", ContentType.TEXT_EVENT_STREAM); - resp.getOutputStream().write(("data: YHOO\ndata: +2\ndata: 10\n\n").getBytes()); - resp.flushBuffer(); - } - - private static String addServerSentEventWithRetry() { - return ": test stream\ndata: first event\nid: 1\nretry: 100\n\n" - + "data: This is the second message, it\ndata: has two lines.\nid: 2\n\ndata: third event"; - } - - private static void sendSSEResponseWithRetry(org.eclipse.jetty.server.Response resp) throws IOException { - resp.addHeader("Content-Type", ContentType.TEXT_EVENT_STREAM); - resp.getOutputStream().write(addServerSentEventWithRetry().getBytes()); - resp.flushBuffer(); - } - - private static String addServerSentEventLast() { - return "data: This is the second message, it\ndata: has two lines.\nid: 2\n\ndata: third event"; - } - - private static void sendSSELastEventIdResponse(org.eclipse.jetty.server.Response resp) throws IOException { - resp.addHeader("Content-Type", ContentType.TEXT_EVENT_STREAM); - resp.getOutputStream().write(addServerSentEventLast().getBytes()); - resp.flushBuffer(); - } - - @AfterAll - public static void stopTestServer() { - if (server != null) { - server.stop(); - } - } - - @Test - public void testFlowableWhenServerReturnsBodyAndNoErrorsWhenHttp500Returned() throws IOException { - HttpClient client = new DefaultHttpClientBuilder().build(); - - try (Response response = doRequest(client, "/error")) { - assertEquals(500, response.getStatusCode()); - - String responseBodyAsString = response.getBody().toString(); - - assertTrue(responseBodyAsString.contains("error")); - } - - } - - @Test - public void testConcurrentRequests() throws InterruptedException { - int numRequests = 100; // 100 = 1GB of data read - HttpClient client = new DefaultHttpClientBuilder().build(); - - ForkJoinPool pool = new ForkJoinPool(); - List> requests = new ArrayList<>(numRequests); - for (int i = 0; i < numRequests; i++) { - requests.add(() -> { - try (Response response = doRequest(client, "/long")) { - byte[] body = response.getBody().toBytes(); - assertArraysEqual(LONG_BODY, body); - return null; - } - }); - } - - pool.invokeAll(requests); - pool.shutdown(); - assertTrue(pool.awaitTermination(60, TimeUnit.SECONDS)); - } - - @Test - public void validateHeadersReturnAsIs() throws IOException { - HttpClient client = new DefaultHttpClientBuilder().build(); - - HttpHeaderName singleValueHeaderName = HttpHeaderName.fromString("singleValue"); - final String singleValueHeaderValue = "value"; - - HttpHeaderName multiValueHeaderName = HttpHeaderName.fromString("Multi-value"); - final List multiValueHeaderValue = Arrays.asList("value1", "value2"); - - HttpHeaders headers = new HttpHeaders().set(singleValueHeaderName, singleValueHeaderValue) - .set(multiValueHeaderName, multiValueHeaderValue); - - try (Response response = client - .send(new HttpRequest(HttpMethod.GET, uri(server, RETURN_HEADERS_AS_IS_PATH)).setHeaders(headers))) { - assertEquals(200, response.getStatusCode()); - - HttpHeaders responseHeaders = response.getHeaders(); - HttpHeader singleValueHeader = responseHeaders.get(singleValueHeaderName); - - assertEquals(singleValueHeaderName.getCaseInsensitiveName(), singleValueHeader.getName().toString()); - assertEquals(singleValueHeaderValue, singleValueHeader.getValue()); - - HttpHeader multiValueHeader = responseHeaders.get(multiValueHeaderName); - - assertEquals(multiValueHeaderName.getCaseInsensitiveName(), multiValueHeader.getName().toString()); - assertEquals(multiValueHeaderValue.size(), multiValueHeader.getValues().size()); - assertTrue(multiValueHeaderValue.containsAll(multiValueHeader.getValues())); - } - } - - @Test - public void testBufferedResponse() throws IOException { - HttpClient client = new DefaultHttpClientBuilder().build(); - - try (Response response = getResponse(client, "/short", Context.none())) { - assertArraysEqual(SHORT_BODY, response.getBody().toBytes()); - } - } - - @Test - public void testEmptyBufferResponse() throws IOException { - HttpClient client = new DefaultHttpClientBuilder().build(); - - try (Response response = getResponse(client, "/empty", Context.none())) { - assertEquals(0L, response.getBody().toBytes().length); - } - } - - @Test - public void testRequestBodyPost() throws IOException { - HttpClient client = new DefaultHttpClientBuilder().build(); - String contentChunk = "abcdefgh"; - int repetitions = 1000; - HttpRequest request = new HttpRequest(HttpMethod.POST, uri(server, "/shortPost")); - request.getHeaders() - .set(HttpHeaderName.CONTENT_LENGTH, String.valueOf(contentChunk.length() * (repetitions + 1))); - request.setBody(BinaryData.fromString(contentChunk)); - - try (Response response = client.send(request)) { - assertArraysEqual(SHORT_BODY, response.getBody().toBytes()); - } - } - - @Test - public void testCustomSslSocketFactory() throws IOException, GeneralSecurityException { - SSLContext sslContext = SSLContext.getInstance("TLSv1.2", Conscrypt.newProvider()); - - // Initialize the SSL context with a trust manager that trusts all certificates. - sslContext.init(null, new TrustManager[] { new InsecureTrustManager() }, null); - - HttpClient httpClient = new DefaultHttpClientBuilder().sslContext(sslContext).build(); - - try (Response response = httpClient.send(new HttpRequest(HttpMethod.GET, httpsUri(server, "/short")))) { - TestUtils.assertArraysEqual(SHORT_BODY, response.getBody().toBytes()); - } - } - - private static Response getResponse(HttpClient client, String path, Context context) throws IOException { - HttpRequest request = new HttpRequest(HttpMethod.GET, uri(server, path)) - .setRequestOptions(new RequestOptions().setContext(context)); - - return client.send(request); - } - - static URI uri(LocalTestServer server, String path) { - try { - return new URI(server.getHttpUri() + path); - } catch (URISyntaxException e) { - throw new RuntimeException(e); - } - } - - static URI httpsUri(LocalTestServer server, String path) { - try { - return new URI(server.getHttpsUri() + path); - } catch (URISyntaxException e) { - throw new RuntimeException(e); - } - } - - private static byte[] createLongBody() { - byte[] duplicateBytes = "abcdefghijk".getBytes(StandardCharsets.UTF_8); - byte[] longBody = new byte[duplicateBytes.length * 100000]; - - for (int i = 0; i < 100000; i++) { - System.arraycopy(duplicateBytes, 0, longBody, i * duplicateBytes.length, duplicateBytes.length); - } - - return longBody; - } - - private static Response doRequest(HttpClient client, String path) throws IOException { - HttpRequest request = new HttpRequest(HttpMethod.GET, uri(server, path)); - - return client.send(request); - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/client/DefaultHttpClientTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/client/DefaultHttpClientTests.java deleted file mode 100644 index fdadb4163705..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/client/DefaultHttpClientTests.java +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.http.client; - -import io.clientcore.core.shared.HttpClientTests; -import io.clientcore.core.shared.HttpClientTestsServer; -import io.clientcore.core.shared.LocalTestServer; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; - -public class DefaultHttpClientTests extends HttpClientTests { - private static LocalTestServer server; - - @BeforeAll - public static void startTestServer() { - server = HttpClientTestsServer.getHttpClientTestsServer(); - server.start(); - } - - @AfterAll - public static void stopTestServer() { - if (server != null) { - server.stop(); - } - } - - @Override - protected HttpClient getHttpClient() { - return new DefaultHttpClientProvider().getSharedInstance(); - } - - @Override - protected String getServerUri(boolean secure) { - return secure ? server.getHttpsUri() : server.getHttpUri(); - } - - @Override - protected int getPort() { - return server.getHttpPort(); - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/client/HttpClientProvidersTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/client/HttpClientProvidersTests.java deleted file mode 100644 index 4612970c9865..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/client/HttpClientProvidersTests.java +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.http.client; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertInstanceOf; - -public class HttpClientProvidersTests { - @Test - public void testNoProvider() { - HttpClient httpClient = HttpClient.getSharedInstance(); - - assertInstanceOf(DefaultHttpClient.class, httpClient); - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/client/JdkHttpClientBuilderIT.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/client/JdkHttpClientBuilderIT.java new file mode 100644 index 000000000000..74e90c124a54 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/client/JdkHttpClientBuilderIT.java @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.http.client; + +import io.clientcore.core.http.models.HttpMethod; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.ProxyOptions; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.shared.LocalTestServer; +import io.clientcore.core.shared.TestConfigurationSource; +import io.clientcore.core.utils.configuration.Configuration; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledForJreRange; +import org.junit.jupiter.api.condition.JRE; + +import javax.servlet.ServletException; +import java.io.IOException; +import java.net.InetSocketAddress; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * Tests {@link JdkHttpClientBuilder}. + *

        + * Now that the default HttpClient, and related code, are using multi-release JARs this must be an integration test as + * the full JAR must be available to use the multi-release code. + */ +@DisabledForJreRange(max = JRE.JAVA_11) +public class JdkHttpClientBuilderIT { + private static final String PROXY_USERNAME = "foo"; + private static final String PROXY_PASSWORD = "bar"; + private static final String PROXY_USER_INFO = PROXY_USERNAME + ":" + PROXY_PASSWORD + "@"; + private static final String SERVICE_ENDPOINT = "/default"; + private static final TestConfigurationSource EMPTY_SOURCE = new TestConfigurationSource(); + + private static LocalTestServer server; + private static SimpleBasicAuthHttpProxyServer proxyServer; + private static SimpleBasicAuthHttpProxyServer.ProxyEndpoint proxyEndpoint; + + @BeforeAll + public static void startTestServer() { + server = new LocalTestServer((req, resp, requestBody) -> { + if ("GET".equalsIgnoreCase(req.getMethod()) && SERVICE_ENDPOINT.equals(req.getServletPath())) { + resp.setStatus(200); + } else { + throw new ServletException("Unexpected request: " + req.getMethod() + " " + req.getServletPath()); + } + }); + + server.start(); + + proxyServer = new SimpleBasicAuthHttpProxyServer(PROXY_USERNAME, PROXY_PASSWORD, SERVICE_ENDPOINT); + proxyEndpoint = proxyServer.start(); + } + + @AfterAll + public static void stopTestServer() { + if (server != null) { + server.stop(); + } + + if (proxyServer != null) { + proxyServer.shutdown(); + } + } + + @Test + public void buildWithHttpProxy() throws IOException { + ProxyOptions clientProxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, + new InetSocketAddress(proxyEndpoint.getHost(), proxyEndpoint.getPort())).setCredentials(PROXY_USERNAME, + PROXY_PASSWORD); + + HttpClient httpClient = new JdkHttpClientBuilder().proxy(clientProxyOptions).build(); + + final String serviceUri = "http://localhost:80" + SERVICE_ENDPOINT; + + try (Response response = httpClient.send(new HttpRequest().setMethod(HttpMethod.GET).setUri(serviceUri))) { + assertEquals(200, response.getStatusCode()); + } + } + + @Test + public void buildWithHttpProxyFromEnvConfiguration() throws IOException { + Configuration configuration = new Configuration(new TestConfigurationSource() + .put(Configuration.HTTP_PROXY, + "http://" + PROXY_USER_INFO + proxyEndpoint.getHost() + ":" + proxyEndpoint.getPort()) + .put("java.net.useSystemProxies", "true")); + + HttpClient httpClient = new JdkHttpClientBuilder().configuration(configuration).build(); + + final String serviceUri = "http://localhost:80" + SERVICE_ENDPOINT; + + try (Response response = httpClient.send(new HttpRequest().setMethod(HttpMethod.GET).setUri(serviceUri))) { + assertEquals(200, response.getStatusCode()); + } + } + + @Test + public void buildWithNullProxyAddress() { + ProxyOptions mockPoxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, null); + assertThrows(NullPointerException.class, () -> new JdkHttpClientBuilder().proxy(mockPoxyOptions)); + } + + @Test + public void buildWithNullProxyType() { + ProxyOptions mockPoxyOptions + = new ProxyOptions(null, new InetSocketAddress(proxyEndpoint.getHost(), proxyEndpoint.getPort())); + assertThrows(NullPointerException.class, () -> new JdkHttpClientBuilder().proxy(mockPoxyOptions)); + } + + @Test + public void buildWithoutProxyAuthentication() throws IOException { + ProxyOptions clientProxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, + new InetSocketAddress(proxyEndpoint.getHost(), proxyEndpoint.getPort())); + + HttpClient httpClient = new JdkHttpClientBuilder().proxy(clientProxyOptions).build(); + + final String serviceUri = "http://localhost:80" + SERVICE_ENDPOINT; + + try (Response response = httpClient.send(new HttpRequest().setMethod(HttpMethod.GET).setUri(serviceUri))) { + assertNotNull(response); + } + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/ETagTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/ETagTests.java new file mode 100644 index 000000000000..30f6b1c4008e --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/ETagTests.java @@ -0,0 +1,68 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.http.models; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * Tests {@link ETag}. + */ +public class ETagTests { + private static final String ETAG_CONTENT = "12345"; + private static final String QUOTE_STRING = "\""; + + @Test + public void validETag() { + // Valid Strong ETag + String strongETagExpect = QUOTE_STRING + ETAG_CONTENT + QUOTE_STRING; + ETag strongETag = ETag.fromString(strongETagExpect); + assertEquals(strongETagExpect, strongETag.toString()); + // Valid Weak ETag + String weakETagExpect = ETag.WEAK_ETAG_PREFIX_QUOTE + ETAG_CONTENT + QUOTE_STRING; + ETag weakETag = ETag.fromString(weakETagExpect); + assertEquals(weakETagExpect, weakETag.toString()); + // All * ETag + String allETags = ETag.ASTERISK; + ETag asterisk = ETag.fromString(allETags); + assertEquals(allETags, asterisk.toString()); + assertEquals(allETags, ETag.ALL.toString()); + assertSame(ETag.ALL, asterisk); + } + + @Test + public void invalidETag() { + // Invalid Strong ETag + String strongETagExpect = QUOTE_STRING + ETAG_CONTENT; + assertThrows(IllegalArgumentException.class, () -> ETag.fromString(strongETagExpect)); + // Valid Weak ETag + String weakETagExpect = ETag.WEAK_ETAG_PREFIX_QUOTE + ETAG_CONTENT; + assertThrows(IllegalArgumentException.class, () -> ETag.fromString(weakETagExpect)); + } + + @Test + public void equalsTest() { + ETag validStrongETag = ETag.fromString(QUOTE_STRING + ETAG_CONTENT + QUOTE_STRING); + assertNotEquals(null, validStrongETag); + + ETag nullETag = ETag.fromString(null); + assertSame(nullETag, ETag.fromString(null)); + assertNotEquals(nullETag, validStrongETag); + + ETag validStrongETagCopy = ETag.fromString(QUOTE_STRING + ETAG_CONTENT + QUOTE_STRING); + assertEquals(validStrongETag, validStrongETagCopy); + } + + @Test + public void hashCodeTest() { + ETag nullETag = ETag.fromString(null); + ETag validStrongETag = ETag.fromString(QUOTE_STRING + ETAG_CONTENT + QUOTE_STRING); + assertEquals(0, nullETag.hashCode()); + assertNotEquals(0, validStrongETag.hashCode()); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/HttpHeadersTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/HttpHeadersTests.java new file mode 100644 index 000000000000..4cea99f916a9 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/HttpHeadersTests.java @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.http.models; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertLinesMatch; + +public class HttpHeadersTests { + private static final HttpHeaderName A = HttpHeaderName.fromString("a"); + + @ParameterizedTest + @MethodSource("testAddSupplier") + public void testAdd(HttpHeaders initialHeaders, HttpHeaderName keyToSet, String valueToSet, + List expectedValues) { + initialHeaders.add(keyToSet, valueToSet); + + assertLinesMatch(expectedValues, initialHeaders.getValues(keyToSet)); + } + + private static Stream testAddSupplier() { + return Stream.of( + // Empty HttpHeaders will add the value. + Arguments.of(new HttpHeaders(), A, "b", Collections.singletonList("b")), + + // Non-empty HttpHeaders will add to the previous value. + Arguments.of(new HttpHeaders().set(A, "b"), A, "c", Arrays.asList("b", "c")), + + // Non-empty HttpHeaders will do nothing when previously set and the value is null. + Arguments.of(new HttpHeaders().set(A, "b"), A, null, Collections.singletonList("b")), + + // HttpHeaders is case-insensitive. + Arguments.of(new HttpHeaders().set(A, "b"), A, "c", Arrays.asList("b", "c"))); + } + + @ParameterizedTest + @MethodSource("testSetSupplier") + public void testSet(HttpHeaders initialHeaders, HttpHeaderName keyToSet, String valueToSet, String expectedValue) { + initialHeaders.set(keyToSet, valueToSet); + + assertEquals(expectedValue, initialHeaders.getValue(keyToSet)); + } + + private static Stream testSetSupplier() { + return Stream.of( + // Empty HttpHeaders will set the value. + Arguments.of(new HttpHeaders(), A, "b", "b"), + + // Non-empty HttpHeaders will override the previously set value. + Arguments.of(new HttpHeaders().set(A, "b"), A, "c", "c"), + + // Non-empty HttpHeaders will remove the previously set value when null. + Arguments.of(new HttpHeaders().set(A, "b"), A, null, null), + + // HttpHeaders is case-insensitive. + Arguments.of(new HttpHeaders().set(A, "b"), A, "c", "c")); + } + + @Test + public void testToStringShouldBeRepresentingKeyEqualSignValue() { + final HttpHeaders headers = new HttpHeaders(); + headers.set(HttpHeaderName.fromString("key1"), "value1"); + headers.set(HttpHeaderName.fromString("key2"), "value2"); + headers.set(HttpHeaderName.fromString("key3"), "value3"); + + assertEquals("key1:value1, key2:value2, key3:value3", headers.toString()); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/HttpRangeTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/HttpRangeTests.java new file mode 100644 index 000000000000..b6cdb8b18cde --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/HttpRangeTests.java @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.http.models; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * Tests {@link HttpRange}. + */ +public class HttpRangeTests { + @ParameterizedTest + @MethodSource("equalsTestSupplier") + public void equalsTest(long offset, Long length, HttpRange expected) { + assertEquals(expected.getOffset(), offset); + assertEquals(expected.getLength(), length); + assertEquals(expected, new HttpRange(offset, length)); + } + + private static Stream equalsTestSupplier() { + return Stream.of(Arguments.of(0, null, new HttpRange(0)), Arguments.of(0, null, new HttpRange(0, null)), + Arguments.of(0, 10L, new HttpRange(0, 10L))); + } + + @ParameterizedTest + @MethodSource("toStringTestSupplier") + public void toStringTest(HttpRange range, String expected) { + assertEquals(expected, range.toString()); + } + + private static Stream toStringTestSupplier() { + return Stream.of(Arguments.of(new HttpRange(0), "bytes=0-"), Arguments.of(new HttpRange(0, null), "bytes=0-"), + Arguments.of(new HttpRange(0, 10L), "bytes=0-9"), Arguments.of(new HttpRange(10, 10L), "bytes=10-19")); + } + + @ParameterizedTest + @MethodSource("invalidRangeSupplier") + public void invalidRange(long offset, Long length) { + assertThrows(IllegalArgumentException.class, () -> new HttpRange(offset, length)); + } + + private static Stream invalidRangeSupplier() { + return Stream.of(Arguments.of(-1, null), Arguments.of(0, -1L)); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/HttpRequestTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/HttpRequestTests.java index 0020e2a47d1d..4aa486bce4f6 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/HttpRequestTests.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/HttpRequestTests.java @@ -3,7 +3,7 @@ package io.clientcore.core.http.models; -import io.clientcore.core.util.binarydata.BinaryData; +import io.clientcore.core.models.binarydata.BinaryData; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -14,7 +14,7 @@ import java.nio.charset.StandardCharsets; import java.util.stream.Stream; -import static io.clientcore.core.util.TestUtils.assertArraysEqual; +import static io.clientcore.core.utils.TestUtils.assertArraysEqual; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; @@ -26,7 +26,8 @@ public class HttpRequestTests { @Test public void constructor() { - final HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://request.uri")); + final HttpRequest request + = new HttpRequest().setMethod(HttpMethod.POST).setUri(URI.create("http://request.uri")); assertEquals(HttpMethod.POST, request.getHttpMethod()); assertEquals(URI.create("http://request.uri"), request.getUri()); @@ -37,7 +38,7 @@ public void constructor() { public void constructorWithHeaders() { final HttpHeaders headers = new HttpHeaders(); final HttpRequest request - = new HttpRequest(HttpMethod.POST, URI.create("http://request.uri")).setHeaders(headers); + = new HttpRequest().setMethod(HttpMethod.POST).setUri(URI.create("http://request.uri")).setHeaders(headers); assertEquals(HttpMethod.POST, request.getHttpMethod()); assertEquals(URI.create("http://request.uri"), request.getUri()); @@ -49,7 +50,8 @@ public void constructorWithHeaders() { @MethodSource("getBinaryDataBodyVariants") public void constructorWithBinaryDataBody(BinaryData data, Long expectedContentLength) { - final HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://request.uri")).setBody(data); + final HttpRequest request + = new HttpRequest().setMethod(HttpMethod.POST).setUri(URI.create("http://request.uri")).setBody(data); assertEquals(HttpMethod.POST, request.getHttpMethod()); assertEquals(URI.create("http://request.uri"), request.getUri()); @@ -67,7 +69,7 @@ public void constructorWithBinaryDataBody(BinaryData data, Long expectedContentL @ParameterizedTest(name = "[{index}] {displayName}") // BinaryData.toString would trigger buffering. @MethodSource("getBinaryDataBodyVariants") public void testSetBodyAsBinaryData(BinaryData data, Long expectedContentLength) { - final HttpRequest request = new HttpRequest(HttpMethod.POST, "http://request.uri"); + final HttpRequest request = new HttpRequest().setMethod(HttpMethod.POST).setUri("http://request.uri"); request.setBody(data); @@ -83,7 +85,7 @@ public void testSetBodyAsBinaryData(BinaryData data, Long expectedContentLength) @Test public void testSetBodyAsString() { - final HttpRequest request = new HttpRequest(HttpMethod.POST, "http://request.uri"); + final HttpRequest request = new HttpRequest().setMethod(HttpMethod.POST).setUri("http://request.uri"); request.setBody(BinaryData.fromString(BODY)); @@ -94,7 +96,7 @@ public void testSetBodyAsString() { @Test public void testSetBodyAsByteArray() { - final HttpRequest request = new HttpRequest(HttpMethod.POST, "http://request.uri"); + final HttpRequest request = new HttpRequest().setMethod(HttpMethod.POST).setUri("http://request.uri"); request.setBody(BinaryData.fromBytes(BODY_BYTES)); diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/HttpResponseTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/HttpResponseTests.java deleted file mode 100644 index a2b5e8e0e307..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/HttpResponseTests.java +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.http.models; - -import io.clientcore.core.implementation.http.HttpResponseAccessHelper; -import io.clientcore.core.util.binarydata.BinaryData; -import org.junit.jupiter.api.Test; - -import java.io.IOException; -import java.util.concurrent.atomic.AtomicBoolean; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class HttpResponseTests { - private static final int STATUS_CODE = 200; - private static final HttpHeaders HEADERS = new HttpHeaders().add(HttpHeaderName.CONTENT_TYPE, "application/text"); - private static final String VALUE = "Response body"; - private static final BinaryData BODY = BinaryData.fromString(VALUE); - private static final HttpRequest HTTP_REQUEST; - - static { - HTTP_REQUEST = new HttpRequest(HttpMethod.POST, "http://request.uri"); - } - - @Test - public void constructor() throws IOException { - try (HttpResponse response = new HttpResponse<>(HTTP_REQUEST, STATUS_CODE, HEADERS, VALUE)) { - assertEquals(HTTP_REQUEST, response.getRequest()); - assertEquals(STATUS_CODE, response.getStatusCode()); - assertEquals(HEADERS, response.getHeaders()); - assertEquals(VALUE, response.getValue()); - assertNotNull(response.getBody()); - assertNotEquals(0, response.getBody().toBytes().length); // Non-empty body. - } - } - - @Test - public void constructorWithNullValue() throws IOException { - try (HttpResponse response = new HttpResponse<>(HTTP_REQUEST, STATUS_CODE, HEADERS, null)) { - assertEquals(HTTP_REQUEST, response.getRequest()); - assertEquals(STATUS_CODE, response.getStatusCode()); - assertEquals(HEADERS, response.getHeaders()); - assertNull(response.getValue()); - assertNotNull(response.getBody()); - assertEquals(0, response.getBody().toBytes().length); // Empty body. - } - } - - @Test - public void constructorWithNullValueAndBodySet() throws IOException { - try (HttpResponse response = new HttpResponse<>(HTTP_REQUEST, STATUS_CODE, HEADERS, null)) { - assertEquals(HTTP_REQUEST, response.getRequest()); - assertEquals(STATUS_CODE, response.getStatusCode()); - assertEquals(HEADERS, response.getHeaders()); - - HttpResponseAccessHelper.setBody(response, BODY); - - // No body deserializer means we don't use the body and the value does not get populated. - assertNull(response.getValue()); - assertEquals(BODY, response.getBody()); - } - } - - @Test - public void constructorWithNullValueBodySetAndBodyDeserializer() throws IOException { - try (HttpResponse response = new HttpResponse<>(HTTP_REQUEST, STATUS_CODE, HEADERS, null)) { - assertEquals(HTTP_REQUEST, response.getRequest()); - assertEquals(STATUS_CODE, response.getStatusCode()); - assertEquals(HEADERS, response.getHeaders()); - assertNull(response.getValue()); // null value. - - AtomicBoolean wasBodyDeserialized = new AtomicBoolean(false); - - HttpResponseAccessHelper.setBody(response, BODY); - HttpResponseAccessHelper.setBodyDeserializer(response, binaryData -> { - wasBodyDeserialized.set(true); - - return binaryData.toString(); - }); - - assertFalse(wasBodyDeserialized.get()); - assertEquals(VALUE, response.getValue()); // Value got deserialized from body. - assertTrue(wasBodyDeserialized.get()); - } - } - - @Test - public void constructorWithValueDoesNotDeserializeBody() throws IOException { - try (HttpResponse response = new HttpResponse<>(HTTP_REQUEST, STATUS_CODE, HEADERS, VALUE)) { - assertEquals(HTTP_REQUEST, response.getRequest()); - assertEquals(STATUS_CODE, response.getStatusCode()); - assertEquals(HEADERS, response.getHeaders()); - - AtomicBoolean wasBodyDeserialized = new AtomicBoolean(false); - - HttpResponseAccessHelper.setBody(response, BODY); - HttpResponseAccessHelper.setBodyDeserializer(response, binaryData -> { - wasBodyDeserialized.set(true); - - return binaryData.toString(); - }); - - assertEquals(VALUE, response.getValue()); // Return value passed to constructor, deserializer is not called. - assertFalse(wasBodyDeserialized.get()); - } - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/PagedIterableTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/PagedIterableTests.java index 6b801a1e6c92..007318a981f4 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/PagedIterableTests.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/PagedIterableTests.java @@ -3,7 +3,9 @@ package io.clientcore.core.http.models; -import io.clientcore.core.util.binarydata.BinaryData; +import io.clientcore.core.http.paging.PagedIterable; +import io.clientcore.core.http.paging.PagedResponse; +import io.clientcore.core.http.paging.PagingOptions; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -12,6 +14,7 @@ import org.opentest4j.AssertionFailedError; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; @@ -25,8 +28,7 @@ public class PagedIterableTests { private final HttpHeaders httpHeaders = new HttpHeaders(); - private final HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, "http://localhost"); - private final BinaryData responseBody = BinaryData.empty(); + private final HttpRequest httpRequest = new HttpRequest().setMethod(HttpMethod.GET).setUri("http://localhost"); // tests with mocked PagedResponse private List> pagedResponses; @@ -77,12 +79,12 @@ public void iterateByT(int numberOfPages) { public void iterateResponseContainsEmptyArray() { pagedResponses = new ArrayList<>(3); // second page is empty but has nextLink - pagedResponses.add(new PagedResponse<>(httpRequest, 200, httpHeaders, responseBody, List.of(0, 1, 2), null, "1", - null, null, null)); - pagedResponses.add(new PagedResponse<>(httpRequest, 200, httpHeaders, responseBody, Collections.emptyList(), - null, "2", null, null, null)); - pagedResponses.add(new PagedResponse<>(httpRequest, 200, httpHeaders, responseBody, List.of(3, 4), null, null, - null, null, null)); + pagedResponses.add( + new PagedResponse<>(httpRequest, 200, httpHeaders, Arrays.asList(0, 1, 2), null, "1", null, null, null)); + pagedResponses.add( + new PagedResponse<>(httpRequest, 200, httpHeaders, Collections.emptyList(), null, "2", null, null, null)); + pagedResponses + .add(new PagedResponse<>(httpRequest, 200, httpHeaders, Arrays.asList(3, 4), null, null, null, null, null)); PagedIterable pagedIterable = new PagedIterable<>(pagingOptions -> pagedResponses.isEmpty() ? null : pagedResponses.get(0), @@ -108,7 +110,7 @@ private void createPagedResponse(int numberOfPages) { private PagedResponse createPagedResponse(HttpRequest httpRequest, HttpHeaders headers, int numberOfPages, Function> valueSupplier, int i) { - return new PagedResponse<>(httpRequest, 200, headers, responseBody, valueSupplier.apply(i), null, + return new PagedResponse<>(httpRequest, 200, headers, valueSupplier.apply(i), null, (i < numberOfPages - 1) ? String.valueOf(i + 1) : null, null, null, null); } @@ -266,42 +268,40 @@ private PagedIterable list() { private PagedResponse listSinglePage(PagingOptions pagingOptions) { Response res = listSync(pagingOptions); - return new PagedResponse<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getBody(), - res.getValue().getItems(), res.getValue().getContinuationToken(), res.getValue().getNextLink(), null, null, - null); + return new PagedResponse<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().getItems(), + res.getValue().getContinuationToken(), res.getValue().getNextLink(), null, null, null); } private PagedResponse listNextSinglePage(PagingOptions pagingOptions, String nextLink) { Response res = (nextLink == null) ? listSync(pagingOptions) : listNextSync(nextLink); - return new PagedResponse<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getBody(), - res.getValue().getItems(), res.getValue().getContinuationToken(), res.getValue().getNextLink(), null, null, - null); + return new PagedResponse<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().getItems(), + res.getValue().getContinuationToken(), res.getValue().getNextLink(), null, null, null); } private Response listSync(PagingOptions pagingOptions) { ++pagingStatistics.numberOfPageRetrievals; // mock request on first page if (pagingStatistics.totalPages == 0) { - return new HttpResponse<>(httpRequest, 200, httpHeaders, new TodoPage(Collections.emptyList(), null, null)); + return new Response<>(httpRequest, 200, httpHeaders, new TodoPage(Collections.emptyList(), null, null)); } else { switch (nextPageMode) { case NEXT_LINK: { // first page - return new HttpResponse<>(httpRequest, 200, httpHeaders, + return new Response<>(httpRequest, 200, httpHeaders, new TodoPage(createTodoItemList(0), null, "1")); } case CONTINUATION_TOKEN: { if (pagingOptions.getContinuationToken() == null) { // first page - return new HttpResponse<>(httpRequest, 200, httpHeaders, + return new Response<>(httpRequest, 200, httpHeaders, new TodoPage(createTodoItemList(0), "1", null)); } else { int pageIndex = Integer.parseInt(pagingOptions.getContinuationToken()); int nextPageIndex = pageIndex + 1; String newContinuationToken = nextPageIndex >= pagingStatistics.totalPages ? null : String.valueOf(nextPageIndex); - return new HttpResponse<>(httpRequest, 200, httpHeaders, + return new Response<>(httpRequest, 200, httpHeaders, new TodoPage(createTodoItemList(pageIndex), newContinuationToken, null)); } } @@ -318,7 +318,7 @@ private Response listNextSync(String nextLink) { int pageIndex = Integer.parseInt(nextLink); int nextPageIndex = pageIndex + 1; String newNextLink = nextPageIndex >= pagingStatistics.totalPages ? null : String.valueOf(nextPageIndex); - return new HttpResponse<>(httpRequest, 200, httpHeaders, + return new Response<>(httpRequest, 200, httpHeaders, new TodoPage(createTodoItemList(pageIndex), null, newNextLink)); } diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/PagedResponseTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/PagedResponseTests.java index 0834d6ffd4ab..d3f32973ebe4 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/PagedResponseTests.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/PagedResponseTests.java @@ -3,21 +3,22 @@ package io.clientcore.core.http.models; -import io.clientcore.core.util.binarydata.BinaryData; +import io.clientcore.core.http.paging.PagedResponse; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.io.IOException; +import java.util.Collections; import java.util.List; public class PagedResponseTests { @Test public void testPagedResponseRequired() { - final HttpRequest mockHttpRequest = new HttpRequest(HttpMethod.GET, "https://endpoint"); + final HttpRequest mockHttpRequest = new HttpRequest().setMethod(HttpMethod.GET).setUri("https://endpoint"); final int statusCode = 200; final HttpHeaders mockHttpHeaders = new HttpHeaders(); - final List mockValue = List.of(new Object()); + final List mockValue = Collections.singletonList(new Object()); final String continuationToken = "continuation_token"; final String nextLink = "https://next_link"; @@ -25,9 +26,9 @@ public void testPagedResponseRequired() { final String firstLink = "https://first_link"; final String lastLink = "https://last_link"; - try (BinaryData mockData = BinaryData.fromString("{\"value\":[{}]}")) { + try { try (PagedResponse pagedResponse - = new PagedResponse<>(mockHttpRequest, statusCode, mockHttpHeaders, mockData, mockValue)) { + = new PagedResponse<>(mockHttpRequest, statusCode, mockHttpHeaders, mockValue)) { Assertions.assertEquals(mockHttpRequest, pagedResponse.getRequest()); Assertions.assertEquals(statusCode, pagedResponse.getStatusCode()); Assertions.assertEquals(mockHttpHeaders, pagedResponse.getHeaders()); @@ -35,7 +36,7 @@ public void testPagedResponseRequired() { } try (PagedResponse pagedResponse = new PagedResponse<>(mockHttpRequest, statusCode, mockHttpHeaders, - mockData, mockValue, continuationToken, nextLink, previousLink, firstLink, lastLink)) { + mockValue, continuationToken, nextLink, previousLink, firstLink, lastLink)) { Assertions.assertEquals(mockHttpRequest, pagedResponse.getRequest()); Assertions.assertEquals(statusCode, pagedResponse.getStatusCode()); Assertions.assertEquals(mockHttpHeaders, pagedResponse.getHeaders()); diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/PagingOptionsTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/PagingOptionsTests.java index dfece73cb6f3..353071612cbc 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/PagingOptionsTests.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/PagingOptionsTests.java @@ -3,6 +3,7 @@ package io.clientcore.core.http.models; +import io.clientcore.core.http.paging.PagingOptions; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/ProxyOptionsTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/ProxyOptionsTests.java new file mode 100644 index 000000000000..133dc0f4bebd --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/models/ProxyOptionsTests.java @@ -0,0 +1,512 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.http.models; + +import io.clientcore.core.shared.TestConfigurationSource; +import io.clientcore.core.utils.CoreUtils; +import io.clientcore.core.utils.configuration.Configuration; +import io.clientcore.core.utils.configuration.ConfigurationSource; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.net.InetSocketAddress; +import java.net.Proxy; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; +import java.util.stream.Stream; + +import static io.clientcore.core.http.models.ProxyOptions.fromConfiguration; +import static java.util.regex.Pattern.compile; +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.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * This class tests {@link ProxyOptions}. + */ +public class ProxyOptionsTests { + private static final String HTTPS = "https"; + private static final String HTTP = "http"; + + private static final String PROXY_HOST = "localhost"; + private static final String FAKE_PROXY_USER_PLACEHOLDER = "fakeProxyUserPlaceholder"; + private static final String FAKE_PROXY_PASSWORD_PLACEHOLDER = "fakeProxyPasswordPlaceholder"; + private static final String NON_PROXY_HOSTS = "notlocalhost"; + + private static final String JAVA_SYSTEM_PROXY_PREREQUISITE = "java.net.useSystemProxies"; + private static final String JAVA_NON_PROXY_HOSTS = "http.nonProxyHosts"; + + private static final String JAVA_HTTPS_PROXY_HOST = "https.proxyHost"; + private static final String JAVA_HTTPS_PROXY_PORT = "https.proxyPort"; + private static final String JAVA_HTTPS_PROXY_USER = "https.proxyUser"; + private static final String JAVA_HTTPS_PROXY_PASSWORD = "https.proxyPassword"; + + private static final String JAVA_HTTP_PROXY_HOST = "http.proxyHost"; + private static final String JAVA_HTTP_PROXY_PORT = "http.proxyPort"; + private static final String JAVA_HTTP_PROXY_USER = "http.proxyUser"; + private static final String JAVA_HTTP_PROXY_PASSWORD = "http.proxyPassword"; + + private static final String AZURE_HTTPS_PROXY_HOST_ONLY = String.format("%s://%s", HTTPS, PROXY_HOST); + private static final String AZURE_HTTP_PROXY_HOST_ONLY = String.format("%s://%s", HTTP, PROXY_HOST); + + private static final String AZURE_HTTPS_PROXY_WITH_USERNAME + = String.format("%s://%s@%s", HTTPS, FAKE_PROXY_USER_PLACEHOLDER, PROXY_HOST); + private static final String AZURE_HTTP_PROXY_WITH_USERNAME + = String.format("%s://%s@%s", HTTP, FAKE_PROXY_USER_PLACEHOLDER, PROXY_HOST); + + private static final String AZURE_HTTPS_PROXY_WITH_USER_AND_PASS = String.format("%s://%s:%s@%s", HTTPS, + FAKE_PROXY_USER_PLACEHOLDER, FAKE_PROXY_PASSWORD_PLACEHOLDER, PROXY_HOST); + private static final String AZURE_HTTP_PROXY_WITH_USER_AND_PASS = String.format("%s://%s:%s@%s", HTTP, + FAKE_PROXY_USER_PLACEHOLDER, FAKE_PROXY_PASSWORD_PLACEHOLDER, PROXY_HOST); + private static final ConfigurationSource EMPTY_SOURCE = new TestConfigurationSource(); + + /** + * Tests that loading a basic configuration from the environment works. + */ + @ParameterizedTest + @MethodSource("loadFromEnvironmentSupplier") + public void loadFromEnvironment(Configuration configuration, String expectedHost, int expectedPort, + String expectedUsername, String expectedPassword, String expectedNonProxyHosts) { + ProxyOptions proxyOptions = fromConfiguration(configuration); + + assertNotNull(proxyOptions); + assertFalse(proxyOptions.getAddress().isUnresolved()); + assertEquals(expectedHost, proxyOptions.getAddress().getHostName()); + assertEquals(expectedPort, proxyOptions.getAddress().getPort()); + assertEquals(expectedUsername, proxyOptions.getUsername()); + assertEquals(expectedPassword, proxyOptions.getPassword()); + assertEquals(expectedNonProxyHosts, proxyOptions.getNonProxyHosts()); + } + + /** + * Tests that loading a basic configuration form the environment works and does not resolve the proxy when {@code + * resolveProxy} is false. + */ + @ParameterizedTest + @MethodSource("loadFromEnvironmentSupplier") + public void loadFromEnvironmentUnresolved(Configuration configuration, String expectedHost, int expectedPort, + String expectedUsername, String expectedPassword, String expectedNonProxyHosts) { + ProxyOptions proxyOptions = fromConfiguration(configuration, true); + + assertNotNull(proxyOptions); + assertTrue(proxyOptions.getAddress().isUnresolved()); + assertEquals(expectedHost, proxyOptions.getAddress().getHostName()); + assertEquals(expectedPort, proxyOptions.getAddress().getPort()); + assertEquals(expectedUsername, proxyOptions.getUsername()); + assertEquals(expectedPassword, proxyOptions.getPassword()); + assertEquals(expectedNonProxyHosts, proxyOptions.getNonProxyHosts()); + } + + @ParameterizedTest + @MethodSource("loadFromExplicitConfigurationSupplier") + public void loadFromExplicitConfiguration(Configuration configuration, String expectedHost, int expectedPort, + String expectedUsername, String expectedPassword, String expectedNonProxyHosts) { + ProxyOptions proxyOptions = fromConfiguration(configuration); + + assertNotNull(proxyOptions); + assertFalse(proxyOptions.getAddress().isUnresolved()); + assertEquals(expectedHost, proxyOptions.getAddress().getHostName()); + assertEquals(expectedPort, proxyOptions.getAddress().getPort()); + assertEquals(expectedUsername, proxyOptions.getUsername()); + assertEquals(expectedPassword, proxyOptions.getPassword()); + assertEquals(expectedNonProxyHosts, proxyOptions.getNonProxyHosts()); + } + + @ParameterizedTest + @MethodSource("loadFromExplicitConfigurationSupplier") + public void loadFromExplicitUnresolved(Configuration configuration, String expectedHost, int expectedPort, + String expectedUsername, String expectedPassword, String expectedNonProxyHosts) { + ProxyOptions proxyOptions = fromConfiguration(configuration, true); + + assertNotNull(proxyOptions); + assertTrue(proxyOptions.getAddress().isUnresolved()); + assertEquals(expectedHost, proxyOptions.getAddress().getHostName()); + assertEquals(expectedPort, proxyOptions.getAddress().getPort()); + assertEquals(expectedUsername, proxyOptions.getUsername()); + assertEquals(expectedPassword, proxyOptions.getPassword()); + assertEquals(expectedNonProxyHosts, proxyOptions.getNonProxyHosts()); + } + + @Test + public void mixedExplicitAndEnvironmentConfigurationIsNotSupported() { + Configuration configuration = new Configuration(new TestConfigurationSource().put("https.proxyHost", "ignored") + .put("https.proxyPort", "42") + .put("http.proxy.username", FAKE_PROXY_USER_PLACEHOLDER) + .put("http.proxy.password", FAKE_PROXY_PASSWORD_PLACEHOLDER) + .put("http.proxy.hostname", PROXY_HOST)); + + ProxyOptions proxyOptions = fromConfiguration(configuration, true); + + assertNotNull(proxyOptions); + assertTrue(proxyOptions.getAddress().isUnresolved()); + assertEquals(Proxy.Type.HTTP, proxyOptions.getType().toProxyType()); + assertEquals(PROXY_HOST, proxyOptions.getAddress().getHostName()); + assertEquals(443, proxyOptions.getAddress().getPort()); + assertEquals(FAKE_PROXY_USER_PLACEHOLDER, proxyOptions.getUsername()); + assertEquals(FAKE_PROXY_PASSWORD_PLACEHOLDER, proxyOptions.getPassword()); + } + + // @Test + // public void systemPropertiesConfigurationWithPutProperty() { + // Configuration configuration = new ConfigurationBuilder().putProperty("https.proxyHost", PROXY_HOST) + // .putProperty("https.proxyPort", "8080") + // .putProperty("https.proxyUser", FAKE_PROXY_USER_PLACEHOLDER) + // .putProperty("https.proxyPassword", FAKE_PROXY_PASSWORD_PLACEHOLDER) + // .build(); + // + // ProxyOptions proxyOptions = fromConfiguration(configuration, true); + // + // assertNotNull(proxyOptions); + // assertEquals(PROXY_HOST, proxyOptions.getAddress().getHostString()); + // assertEquals(8080, proxyOptions.getAddress().getPort()); + // assertEquals(FAKE_PROXY_USER_PLACEHOLDER, proxyOptions.getUsername()); + // assertEquals(FAKE_PROXY_PASSWORD_PLACEHOLDER, proxyOptions.getPassword()); + // } + + @ParameterizedTest + @NullSource + public void defaultHttpPortNull(String port) { + TestConfigurationSource configurationSource + = new TestConfigurationSource().put("http.proxy.hostname", PROXY_HOST) + .put("http.proxy.username", FAKE_PROXY_USER_PLACEHOLDER) + .put("http.proxy.password", FAKE_PROXY_PASSWORD_PLACEHOLDER); + + if (port != null) { + configurationSource.put("http.proxy.port", port); + } + + ProxyOptions proxyOptions = fromConfiguration(new Configuration(configurationSource)); + + assertNotNull(proxyOptions); + assertEquals(443, proxyOptions.getAddress().getPort()); + } + + @ParameterizedTest + @ValueSource(strings = { "", " ", "not-an-int" }) + public void invalidHttpPortExplicitConfigThrows(String port) { + Configuration configuration + = new Configuration(new TestConfigurationSource().put("http.proxy.hostname", PROXY_HOST) + .put("http.proxy.username", FAKE_PROXY_USER_PLACEHOLDER) + .put("http.proxy.password", FAKE_PROXY_PASSWORD_PLACEHOLDER) + .put("http.proxy.port", port)); + + assertThrows(NumberFormatException.class, () -> fromConfiguration(configuration)); + } + + @ParameterizedTest + @ValueSource(strings = { "", " ", "not-an-int" }) + public void invalidHttpsPortEnvironmentConfigDefault(String port) { + ConfigurationSource systemProps + = new TestConfigurationSource().put("https.proxyHost", PROXY_HOST).put("https.proxyPort", port); + + Configuration configuration = new Configuration(EMPTY_SOURCE, systemProps, EMPTY_SOURCE); + + ProxyOptions proxyOptions = fromConfiguration(configuration); + + assertNotNull(proxyOptions); + assertEquals(443, proxyOptions.getAddress().getPort()); + } + + @ParameterizedTest + @ValueSource(strings = { " ", "not-an-int" }) + public void invalidHttpPortEnvironmentConfigDefault(String port) { + ConfigurationSource systemProps + = new TestConfigurationSource().put("http.proxyHost", PROXY_HOST).put("http.proxyPort", port); + + Configuration configuration = new Configuration(EMPTY_SOURCE, systemProps, EMPTY_SOURCE); + + ProxyOptions proxyOptions = fromConfiguration(configuration); + + assertNotNull(proxyOptions); + assertEquals(80, proxyOptions.getAddress().getPort()); + } + + private static Stream loadFromEnvironmentSupplier() { + return Stream.of( + // Basic Azure HTTPS proxy. + Arguments.of( + setJavaSystemProxyPrerequisiteToTrue( + new TestConfigurationSource().put(Configuration.HTTPS_PROXY, AZURE_HTTPS_PROXY_HOST_ONLY)), + PROXY_HOST, 443, null, null, null), + + // Username only Azure HTTPS proxy. + Arguments.of( + setJavaSystemProxyPrerequisiteToTrue( + new TestConfigurationSource().put(Configuration.HTTPS_PROXY, AZURE_HTTPS_PROXY_WITH_USERNAME)), + PROXY_HOST, 443, null, null, null), + + // Complete Azure HTTPS proxy. + Arguments.of( + setJavaSystemProxyPrerequisiteToTrue( + new TestConfigurationSource().put(Configuration.HTTPS_PROXY, AZURE_HTTPS_PROXY_WITH_USER_AND_PASS)), + PROXY_HOST, 443, FAKE_PROXY_USER_PLACEHOLDER, FAKE_PROXY_PASSWORD_PLACEHOLDER, null), + + // Azure HTTPS proxy with non-proxying hosts. + Arguments.of( + setJavaSystemProxyPrerequisiteToTrue( + new TestConfigurationSource().put(Configuration.HTTPS_PROXY, AZURE_HTTPS_PROXY_HOST_ONLY) + .put(Configuration.NO_PROXY, NON_PROXY_HOSTS)), + PROXY_HOST, 443, null, null, "(" + NON_PROXY_HOSTS + ")"), + + // Basic Azure HTTP proxy. + Arguments.of( + setJavaSystemProxyPrerequisiteToTrue( + new TestConfigurationSource().put(Configuration.HTTP_PROXY, AZURE_HTTP_PROXY_HOST_ONLY)), + PROXY_HOST, 80, null, null, null), + + // Username only Azure HTTP proxy. + Arguments.of( + setJavaSystemProxyPrerequisiteToTrue( + new TestConfigurationSource().put(Configuration.HTTP_PROXY, AZURE_HTTP_PROXY_WITH_USERNAME)), + PROXY_HOST, 80, null, null, null), + + // Complete Azure HTTP proxy. + Arguments.of( + setJavaSystemProxyPrerequisiteToTrue( + new TestConfigurationSource().put(Configuration.HTTP_PROXY, AZURE_HTTP_PROXY_WITH_USER_AND_PASS)), + PROXY_HOST, 80, FAKE_PROXY_USER_PLACEHOLDER, FAKE_PROXY_PASSWORD_PLACEHOLDER, null), + + // Azure HTTP proxy with non-proxying hosts. + Arguments.of( + setJavaSystemProxyPrerequisiteToTrue( + new TestConfigurationSource().put(Configuration.HTTP_PROXY, AZURE_HTTP_PROXY_HOST_ONLY) + .put(Configuration.NO_PROXY, NON_PROXY_HOSTS)), + PROXY_HOST, 80, null, null, "(" + NON_PROXY_HOSTS + ")"), + + /* + * Setting up tests for loading the Java environment proxy configurations takes additional work as each + * piece of the proxy configuration is a separate environment value. The non-proxy hosts will be checked + * against the global environment value when it is not being set by the configuration passed by the test + * as this value may be setup by the JVM. + */ + + // Basic Java HTTPS proxy. + Arguments.of(createJavaEnvConfiguration(443, null, null, null, true), PROXY_HOST, 443, null, null, null), + + // Username only Java HTTPS proxy. + Arguments.of(createJavaEnvConfiguration(443, FAKE_PROXY_USER_PLACEHOLDER, null, null, true), PROXY_HOST, + 443, null, null, null), + + // Complete Java HTTPS proxy. + Arguments.of(createJavaEnvConfiguration(443, FAKE_PROXY_USER_PLACEHOLDER, FAKE_PROXY_PASSWORD_PLACEHOLDER, + null, true), PROXY_HOST, 443, FAKE_PROXY_USER_PLACEHOLDER, FAKE_PROXY_PASSWORD_PLACEHOLDER, null), + + // Java HTTPS proxy with non-proxying hosts. + Arguments.of(createJavaEnvConfiguration(443, null, null, NON_PROXY_HOSTS, true), PROXY_HOST, 443, null, + null, "(" + NON_PROXY_HOSTS + ")"), + + // Basic Java HTTP proxy. + Arguments.of(createJavaEnvConfiguration(80, null, null, null, false), PROXY_HOST, 80, null, null, null), + + // Username only Java HTTP proxy. + Arguments.of(createJavaEnvConfiguration(80, FAKE_PROXY_USER_PLACEHOLDER, null, null, false), PROXY_HOST, 80, + null, null, null), + + // Complete Java HTTP proxy. + Arguments.of(createJavaEnvConfiguration(80, FAKE_PROXY_USER_PLACEHOLDER, FAKE_PROXY_PASSWORD_PLACEHOLDER, + null, false), PROXY_HOST, 80, FAKE_PROXY_USER_PLACEHOLDER, FAKE_PROXY_PASSWORD_PLACEHOLDER, null), + + // Java HTTP proxy with non-proxying hosts. + Arguments.of(createJavaEnvConfiguration(80, null, null, NON_PROXY_HOSTS, false), PROXY_HOST, 80, null, null, + "(" + NON_PROXY_HOSTS + ")")); + } + + private static Stream loadFromExplicitConfigurationSupplier() { + return Stream.of( + /* + * Setting up tests for loading the Java exokicit proxy configurations takes additional work as each + * piece of the proxy configuration is a separate environment value. The non-proxy hosts will be checked + * against the global environment value when it is not being set by the configuration passed by the test + * as this value may be setup by the JVM. + */ + + // Basic Java HTTPS proxy. + Arguments.of(createExplicitConfiguration(443, null, null, null), PROXY_HOST, 443, null, null, null), + + // Username only Java HTTPS proxy. + Arguments.of(createExplicitConfiguration(443, FAKE_PROXY_USER_PLACEHOLDER, null, null), PROXY_HOST, 443, + null, null, null), + + // Complete Java HTTPS proxy. + Arguments.of( + createExplicitConfiguration(443, FAKE_PROXY_USER_PLACEHOLDER, FAKE_PROXY_PASSWORD_PLACEHOLDER, null), + PROXY_HOST, 443, FAKE_PROXY_USER_PLACEHOLDER, FAKE_PROXY_PASSWORD_PLACEHOLDER, null), + + // Java HTTPS proxy with non-proxying hosts. + Arguments.of(createExplicitConfiguration(443, null, null, NON_PROXY_HOSTS), PROXY_HOST, 443, null, null, + "(" + NON_PROXY_HOSTS + ")")); + } + + // /** + // * Tests that passing {@link Configuration#NONE} into {@link ProxyOptions#fromConfiguration(Configuration)} will + // * return null/ + // */ + // @Test + // public void loadFromEnvironmentThrowsWhenPassedConfigurationNone() { + // assertNull(fromConfiguration(Configuration.NONE)); + // assertNull(fromConfiguration(Configuration.NONE, true)); + // } + + /** + * Tests that when Java system proxies will only be used if {@code java.net.useSystemProxies} is {@code true}. + */ + @ParameterizedTest + @MethodSource("systemProxiesRequireUseSystemProxiesSupplier") + public void systemProxiesRequireUseSystemProxies(Configuration configuration) { + assertNull(fromConfiguration(configuration)); + assertNull(fromConfiguration(configuration, true)); + } + + private static Stream systemProxiesRequireUseSystemProxiesSupplier() { + ConfigurationSource envVarHttpsSource + = new TestConfigurationSource().put(Configuration.HTTPS_PROXY, AZURE_HTTPS_PROXY_HOST_ONLY) + .put(JAVA_NON_PROXY_HOSTS, null); + ConfigurationSource envVarHttpSource + = new TestConfigurationSource().put(Configuration.HTTP_PROXY, AZURE_HTTP_PROXY_HOST_ONLY) + .put(JAVA_NON_PROXY_HOSTS, null); + + return Stream.of( + // Java HTTPS configuration without 'java.net.useSystemProxies' set. + Arguments.of(new Configuration(EMPTY_SOURCE, EMPTY_SOURCE, envVarHttpsSource)), + + // Java HTTP configuration without 'java.net.useSystemProxies' set. + Arguments.of(new Configuration(EMPTY_SOURCE, EMPTY_SOURCE, envVarHttpSource))); + } + + private static Configuration createJavaEnvConfiguration(int port, String username, String password, + String nonProxyHosts, boolean isHttps) { + TestConfigurationSource testSource = new TestConfigurationSource().put(JAVA_NON_PROXY_HOSTS, nonProxyHosts); + + if (isHttps) { + testSource.put(JAVA_HTTPS_PROXY_HOST, PROXY_HOST) + .put(JAVA_HTTPS_PROXY_PORT, String.valueOf(port)) + .put(JAVA_HTTPS_PROXY_USER, username) + .put(JAVA_HTTPS_PROXY_PASSWORD, password); + } else { + testSource.put(JAVA_HTTP_PROXY_HOST, PROXY_HOST) + .put(JAVA_HTTP_PROXY_PORT, String.valueOf(port)) + .put(JAVA_HTTP_PROXY_USER, username) + .put(JAVA_HTTP_PROXY_PASSWORD, password); + } + + return new Configuration(EMPTY_SOURCE, testSource, EMPTY_SOURCE); + } + + private static Configuration createExplicitConfiguration(int port, String username, String password, + String nonProxyHosts) { + TestConfigurationSource explicitSource = new TestConfigurationSource() + .put("http.proxy.non-proxy-hosts", CoreUtils.isNullOrEmpty(nonProxyHosts) ? "" : nonProxyHosts) + .put("http.proxy.hostname", PROXY_HOST) + .put("http.proxy.port", String.valueOf(port)) + .put("http.proxy.username", username) + .put("http.proxy.password", password); + + return new Configuration(explicitSource, EMPTY_SOURCE, EMPTY_SOURCE); + } + + @ParameterizedTest + @MethodSource("nonProxyHostsSupplier") + @Execution(ExecutionMode.SAME_THREAD) + public void nonProxyHosts(Pattern pattern, String host, boolean expected) { + assertEquals(expected, pattern.matcher(host).find(), + () -> String.format("Expected Pattern '%s' to match '%s'.", pattern.pattern(), host)); + } + + private static Stream nonProxyHostsSupplier() { + String javaNonProxyHosts = String.join("|", "localhost", "127.0.0.1", "*.prod.linkedin.com", + "*.azure.linkedin.com", "*.blob.core.windows.net"); + String noProxyNonProxyHosts = String.join(",", "localhost", "127.0.0.1", ".*.prod.linkedin.com", + ".azure.linkedin.com", "*.blob.core.windows.net"); + + /* + * This emulates loading a Java formatted proxy. + */ + TestConfigurationSource sysPropSource = new TestConfigurationSource().put("http.proxyHost", "localhost") + .put("http.proxyPort", "7777") + .put("http.nonProxyHosts", javaNonProxyHosts); + Configuration javaProxyConfiguration = new Configuration(EMPTY_SOURCE, sysPropSource, EMPTY_SOURCE); + + Pattern javaProxyConfigurationPattern + = compile(fromConfiguration(javaProxyConfiguration).getNonProxyHosts(), Pattern.CASE_INSENSITIVE); + + /* + * This emulates loading an environment formatted proxy. + */ + TestConfigurationSource envSource + = new TestConfigurationSource().put(Configuration.HTTPS_PROXY, "http://localhost:7777") + .put(Configuration.NO_PROXY, noProxyNonProxyHosts); + Configuration environmentProxyConfiguration = setJavaSystemProxyPrerequisiteToTrue(envSource); + + Pattern environmentProxyConfigurationPattern + = compile(fromConfiguration(environmentProxyConfiguration).getNonProxyHosts(), Pattern.CASE_INSENSITIVE); + + /* + * This emulates configuring a proxy in code using the expected Java formatted proxy. + */ + ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("localhost", 7777)) + .setNonProxyHosts(javaNonProxyHosts); + + Pattern codeProxyPattern = compile(proxyOptions.getNonProxyHosts(), Pattern.CASE_INSENSITIVE); + + Pattern[] patterns + = new Pattern[] { javaProxyConfigurationPattern, environmentProxyConfigurationPattern, codeProxyPattern }; + + String[] expectedMatchHosts = new String[] { + "localhost", + "127.0.0.1", + "azp.prod.linkedin.com", + "azp.azure.linkedin.com", + "azp.blob.core.windows.net" }; + + String[] expectedNonMatchHosts = new String[] { + "example.com", + "portal.azure.com", + "linkedin.com", + "127a0b0c1", + "azpaprodblinkedinccom", + "azpaazureblinkedinccom", + "azpablobbcorecwindowsdnet" }; + + List argumentsList = new ArrayList<>(); + for (Pattern pattern : patterns) { + for (String expectedMatchHost : expectedMatchHosts) { + argumentsList.add(Arguments.arguments(pattern, expectedMatchHost, true)); + } + + for (String expectedNonMatchHost : expectedNonMatchHosts) { + argumentsList.add(Arguments.arguments(pattern, expectedNonMatchHost, false)); + } + } + + return argumentsList.stream(); + } + + @Test + public void sanitizeNoProxyDoesNotSplitEscapedCommas() { + String noProxy = "noproxy\\,withescapedcomma"; + + assertEquals("(" + noProxy + ")", ProxyOptions.sanitizeNoProxy(noProxy)); + } + + @Test + public void sanitizeJavaHttpNonProxyHostsDoesNotSplitEscapedPipes() { + String nonProxyHosts = "nonproxyhosts\\|withescapedpipe"; + + assertEquals("(" + nonProxyHosts + ")", ProxyOptions.sanitizeNoProxy(nonProxyHosts)); + } + + private static Configuration setJavaSystemProxyPrerequisiteToTrue(TestConfigurationSource source) { + return new Configuration(EMPTY_SOURCE, EMPTY_SOURCE, source.put(JAVA_SYSTEM_PROXY_PREREQUISITE, "true")); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/HttpInstrumentationLoggingTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/HttpInstrumentationLoggingTests.java index f66fbf73974c..286e8eb10de3 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/HttpInstrumentationLoggingTests.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/HttpInstrumentationLoggingTests.java @@ -3,22 +3,18 @@ package io.clientcore.core.http.pipeline; -import io.clientcore.core.http.MockHttpResponse; -import io.clientcore.core.http.models.HttpHeader; import io.clientcore.core.http.models.HttpHeaderName; import io.clientcore.core.http.models.HttpHeaders; -import io.clientcore.core.http.models.HttpLogOptions; import io.clientcore.core.http.models.HttpMethod; import io.clientcore.core.http.models.HttpRequest; -import io.clientcore.core.http.models.HttpRetryOptions; import io.clientcore.core.http.models.RequestOptions; import io.clientcore.core.http.models.Response; import io.clientcore.core.implementation.AccessibleByteArrayOutputStream; import io.clientcore.core.implementation.http.HttpRequestAccessHelper; import io.clientcore.core.instrumentation.InstrumentationContext; -import io.clientcore.core.instrumentation.InstrumentationOptions; import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.util.binarydata.BinaryData; +import io.clientcore.core.instrumentation.logging.LogLevel; +import io.clientcore.core.models.binarydata.BinaryData; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; @@ -56,10 +52,11 @@ public class HttpInstrumentationLoggingTests { private static final String URI = "https://example.com?param=value&api-version=42"; private static final String REDACTED_URI = "https://example.com?param=REDACTED&api-version=42"; - private static final Set DEFAULT_ALLOWED_QUERY_PARAMS = new HttpLogOptions().getAllowedQueryParamNames(); - private static final Set DEFAULT_ALLOWED_HEADERS = new HttpLogOptions().getAllowedHeaderNames(); + private static final Set DEFAULT_ALLOWED_QUERY_PARAMS + = new HttpInstrumentationOptions().getAllowedQueryParamNames(); + private static final Set DEFAULT_ALLOWED_HEADERS + = new HttpInstrumentationOptions().getAllowedHeaderNames(); private static final HttpHeaderName CUSTOM_REQUEST_ID = HttpHeaderName.fromString("custom-request-id"); - private static final InstrumentationOptions DEFAULT_INSTRUMENTATION_OPTIONS = null; private final AccessibleByteArrayOutputStream logCaptureStream; @@ -69,13 +66,12 @@ public HttpInstrumentationLoggingTests() { @ParameterizedTest @MethodSource("disabledHttpLoggingSource") - public void testDisabledHttpLogging(ClientLogger.LogLevel logLevel, HttpLogOptions.HttpLogDetailLevel httpLogLevel) + public void testDisabledHttpLogging(LogLevel logLevel, HttpInstrumentationOptions.HttpLogLevel detailLevel) throws IOException { ClientLogger logger = setupLogLevelAndGetLogger(logLevel, logCaptureStream); - HttpPipeline pipeline - = createPipeline(DEFAULT_INSTRUMENTATION_OPTIONS, new HttpLogOptions().setLogLevel(httpLogLevel)); - HttpRequest request = new HttpRequest(HttpMethod.GET, URI); + HttpPipeline pipeline = createPipeline(new HttpInstrumentationOptions().setHttpLogLevel(detailLevel)); + HttpRequest request = new HttpRequest().setMethod(HttpMethod.GET).setUri(URI); request.setRequestOptions(new RequestOptions().setLogger(logger)); pipeline.send(request).close(); @@ -84,21 +80,21 @@ public void testDisabledHttpLogging(ClientLogger.LogLevel logLevel, HttpLogOptio } public static Stream disabledHttpLoggingSource() { - return Stream.of(Arguments.of(ClientLogger.LogLevel.VERBOSE, HttpLogOptions.HttpLogDetailLevel.NONE), - Arguments.of(ClientLogger.LogLevel.WARNING, HttpLogOptions.HttpLogDetailLevel.BASIC), - Arguments.of(ClientLogger.LogLevel.WARNING, HttpLogOptions.HttpLogDetailLevel.HEADERS), - Arguments.of(ClientLogger.LogLevel.WARNING, HttpLogOptions.HttpLogDetailLevel.BODY), - Arguments.of(ClientLogger.LogLevel.WARNING, HttpLogOptions.HttpLogDetailLevel.BODY_AND_HEADERS)); + return Stream.of(Arguments.of(LogLevel.VERBOSE, HttpInstrumentationOptions.HttpLogLevel.NONE), + Arguments.of(LogLevel.WARNING, HttpInstrumentationOptions.HttpLogLevel.HEADERS), + Arguments.of(LogLevel.WARNING, HttpInstrumentationOptions.HttpLogLevel.BODY), + Arguments.of(LogLevel.WARNING, HttpInstrumentationOptions.HttpLogLevel.BODY_AND_HEADERS)); } @ParameterizedTest @MethodSource("allowQueryParamSource") public void testBasicHttpLogging(Set allowedParams, String expectedUri) throws IOException { - ClientLogger logger = setupLogLevelAndGetLogger(ClientLogger.LogLevel.VERBOSE, logCaptureStream); - HttpLogOptions options = new HttpLogOptions().setLogLevel(HttpLogOptions.HttpLogDetailLevel.BASIC) - .setAllowedQueryParamNames(allowedParams); + ClientLogger logger = setupLogLevelAndGetLogger(LogLevel.VERBOSE, logCaptureStream); + HttpInstrumentationOptions options + = new HttpInstrumentationOptions().setHttpLogLevel(HttpInstrumentationOptions.HttpLogLevel.HEADERS) + .setAllowedQueryParamNames(allowedParams); - HttpPipeline pipeline = createPipeline(DEFAULT_INSTRUMENTATION_OPTIONS, options); + HttpPipeline pipeline = createPipeline(options); HttpRequest request = createRequest(HttpMethod.GET, URI, logger); Response response = pipeline.send(request); @@ -108,19 +104,51 @@ public void testBasicHttpLogging(Set allowedParams, String expectedUri) assertEquals(2, logMessages.size()); assertRequestLog(logMessages.get(0), expectedUri, request, null, 0); - assertEquals(7, logMessages.get(0).size()); + assertEquals(10, logMessages.get(0).size()); + assertEquals("REDACTED", logMessages.get(0).get("Authorization")); + assertEquals("application/json", logMessages.get(0).get("Content-Type")); assertResponseLog(logMessages.get(1), expectedUri, response, 0); - assertEquals(11, logMessages.get(1).size()); + assertEquals(14, logMessages.get(1).size()); + assertEquals("13", logMessages.get(1).get("Content-Length")); + assertEquals("application/text", logMessages.get(1).get("Content-Type")); + assertEquals("REDACTED", logMessages.get(1).get("not-safe-to-log")); + } + + @Test + public void testBasicHttpLoggingNoRedactedHeaders() throws IOException { + ClientLogger logger = setupLogLevelAndGetLogger(LogLevel.VERBOSE, logCaptureStream); + HttpInstrumentationOptions options + = new HttpInstrumentationOptions().setHttpLogLevel(HttpInstrumentationOptions.HttpLogLevel.HEADERS) + .setRedactedHeaderNamesLoggingEnabled(false); + + HttpPipeline pipeline = createPipeline(options); + + HttpRequest request = createRequest(HttpMethod.GET, URI, logger); + Response response = pipeline.send(request); + response.close(); + + List> logMessages = parseLogMessages(logCaptureStream); + assertEquals(2, logMessages.size()); + + assertRequestLog(logMessages.get(0), request); + assertEquals(9, logMessages.get(0).size()); + assertEquals("application/json", logMessages.get(0).get("Content-Type")); + + assertResponseLog(logMessages.get(1), response); + assertEquals(13, logMessages.get(1).size()); + assertEquals("13", logMessages.get(1).get("Content-Length")); + assertEquals("application/text", logMessages.get(1).get("Content-Type")); } @Test public void testHttpLoggingTracingDisabled() throws IOException { - ClientLogger logger = setupLogLevelAndGetLogger(ClientLogger.LogLevel.VERBOSE, logCaptureStream); - InstrumentationOptions instrumentationOptions = new InstrumentationOptions<>().setTracingEnabled(false); - HttpLogOptions logOptions = new HttpLogOptions().setLogLevel(HttpLogOptions.HttpLogDetailLevel.BASIC); + ClientLogger logger = setupLogLevelAndGetLogger(LogLevel.VERBOSE, logCaptureStream); - HttpPipeline pipeline = createPipeline(instrumentationOptions, logOptions); + HttpInstrumentationOptions options = new HttpInstrumentationOptions().setTracingEnabled(false) + .setHttpLogLevel(HttpInstrumentationOptions.HttpLogLevel.HEADERS) + .setRedactedHeaderNamesLoggingEnabled(false); + HttpPipeline pipeline = createPipeline(options); HttpRequest request = createRequest(HttpMethod.GET, URI, logger); Response response = pipeline.send(request); @@ -130,19 +158,19 @@ public void testHttpLoggingTracingDisabled() throws IOException { assertEquals(2, logMessages.size()); assertRequestLog(logMessages.get(0), request); - assertEquals(5, logMessages.get(0).size()); + assertEquals(6, logMessages.get(0).size()); assertResponseLog(logMessages.get(1), response); - assertEquals(9, logMessages.get(1).size()); + assertEquals(11, logMessages.get(1).size()); } @Test public void testHttpLoggingTracingDisabledCustomContext() throws IOException { - ClientLogger logger = setupLogLevelAndGetLogger(ClientLogger.LogLevel.VERBOSE, logCaptureStream); - InstrumentationOptions instrumentationOptions = new InstrumentationOptions<>().setTracingEnabled(false); - HttpLogOptions logOptions = new HttpLogOptions().setLogLevel(HttpLogOptions.HttpLogDetailLevel.BASIC); + ClientLogger logger = setupLogLevelAndGetLogger(LogLevel.VERBOSE, logCaptureStream); + HttpInstrumentationOptions options = new HttpInstrumentationOptions().setTracingEnabled(false) + .setHttpLogLevel(HttpInstrumentationOptions.HttpLogLevel.HEADERS); - HttpPipeline pipeline = createPipeline(instrumentationOptions, logOptions); + HttpPipeline pipeline = createPipeline(options); InstrumentationContext instrumentationContext = createInstrumentationContext("1234567890abcdef1234567890abcdef", "1234567890abcdef"); @@ -155,18 +183,19 @@ public void testHttpLoggingTracingDisabledCustomContext() throws IOException { assertEquals(2, logMessages.size()); assertRequestLog(logMessages.get(0), request); - assertEquals(7, logMessages.get(0).size()); + assertEquals(10, logMessages.get(0).size()); assertResponseLog(logMessages.get(1), response); - assertEquals(11, logMessages.get(1).size()); + assertEquals(14, logMessages.get(1).size()); } @Test public void testTryCount() throws IOException { - ClientLogger logger = setupLogLevelAndGetLogger(ClientLogger.LogLevel.VERBOSE, logCaptureStream); - HttpLogOptions options = new HttpLogOptions().setLogLevel(HttpLogOptions.HttpLogDetailLevel.BASIC); + ClientLogger logger = setupLogLevelAndGetLogger(LogLevel.VERBOSE, logCaptureStream); + HttpInstrumentationOptions options + = new HttpInstrumentationOptions().setHttpLogLevel(HttpInstrumentationOptions.HttpLogLevel.HEADERS); - HttpPipeline pipeline = createPipeline(DEFAULT_INSTRUMENTATION_OPTIONS, options); + HttpPipeline pipeline = createPipeline(options); HttpRequest request = createRequest(HttpMethod.GET, URI, logger); HttpRequestAccessHelper.setTryCount(request, 42); @@ -182,12 +211,13 @@ public void testTryCount() throws IOException { @ParameterizedTest @MethodSource("testExceptionSeverity") - public void testConnectionException(ClientLogger.LogLevel level, boolean expectExceptionLog) { + public void testConnectionException(LogLevel level, boolean expectExceptionLog) { ClientLogger logger = setupLogLevelAndGetLogger(level, logCaptureStream); - HttpLogOptions options = new HttpLogOptions().setLogLevel(HttpLogOptions.HttpLogDetailLevel.HEADERS); + HttpInstrumentationOptions options + = new HttpInstrumentationOptions().setHttpLogLevel(HttpInstrumentationOptions.HttpLogLevel.HEADERS); RuntimeException expectedException = new RuntimeException("socket error"); - HttpPipeline pipeline = createPipeline(DEFAULT_INSTRUMENTATION_OPTIONS, options, request -> { + HttpPipeline pipeline = createPipeline(options, request -> { throw expectedException; }); @@ -205,14 +235,15 @@ public void testConnectionException(ClientLogger.LogLevel level, boolean expectE @ParameterizedTest @MethodSource("testExceptionSeverity") - public void testRequestBodyException(ClientLogger.LogLevel level, boolean expectExceptionLog) { + public void testRequestBodyException(LogLevel level, boolean expectExceptionLog) { ClientLogger logger = setupLogLevelAndGetLogger(level, logCaptureStream); - HttpLogOptions options = new HttpLogOptions().setLogLevel(HttpLogOptions.HttpLogDetailLevel.BODY); + HttpInstrumentationOptions options = new HttpInstrumentationOptions() + .setHttpLogLevel(HttpInstrumentationOptions.HttpLogLevel.BODY_AND_HEADERS); IOException expectedException = new IOException("socket error"); TestStream requestStream = new TestStream(1024, expectedException); BinaryData requestBody = BinaryData.fromStream(requestStream, 1024L); - HttpPipeline pipeline = createPipeline(DEFAULT_INSTRUMENTATION_OPTIONS, options); + HttpPipeline pipeline = createPipeline(options); HttpRequest request = createRequest(HttpMethod.POST, URI, logger); request.setBody(requestBody); @@ -229,19 +260,20 @@ public void testRequestBodyException(ClientLogger.LogLevel level, boolean expect @ParameterizedTest @MethodSource("testExceptionSeverity") - public void testResponseBodyException(ClientLogger.LogLevel level, boolean expectExceptionLog) { + public void testResponseBodyException(LogLevel level, boolean expectExceptionLog) { ClientLogger logger = setupLogLevelAndGetLogger(level, logCaptureStream); - HttpLogOptions options = new HttpLogOptions().setLogLevel(HttpLogOptions.HttpLogDetailLevel.BODY); + HttpInstrumentationOptions options = new HttpInstrumentationOptions() + .setHttpLogLevel(HttpInstrumentationOptions.HttpLogLevel.BODY_AND_HEADERS); IOException expectedException = new IOException("socket error"); TestStream responseStream = new TestStream(1024, expectedException); - HttpPipeline pipeline = createPipeline(DEFAULT_INSTRUMENTATION_OPTIONS, options, - request -> new MockHttpResponse(request, 200, BinaryData.fromStream(responseStream, 1024L))); + HttpPipeline pipeline = createPipeline(options, + request -> new Response<>(request, 200, new HttpHeaders(), BinaryData.fromStream(responseStream, 1024L))); HttpRequest request = createRequest(HttpMethod.GET, URI, logger); - Response response = pipeline.send(request); - assertThrows(RuntimeException.class, () -> response.getBody().toString()); + Response response = pipeline.send(request); + assertThrows(RuntimeException.class, () -> response.getValue().toBytes()); List> logMessages = parseLogMessages(logCaptureStream); if (!expectExceptionLog) { @@ -253,11 +285,12 @@ public void testResponseBodyException(ClientLogger.LogLevel level, boolean expec @Test public void testResponseBodyLoggingOnClose() throws IOException { - ClientLogger logger = setupLogLevelAndGetLogger(ClientLogger.LogLevel.INFORMATIONAL, logCaptureStream); - HttpLogOptions options = new HttpLogOptions().setLogLevel(HttpLogOptions.HttpLogDetailLevel.BODY); + ClientLogger logger = setupLogLevelAndGetLogger(LogLevel.INFORMATIONAL, logCaptureStream); + HttpInstrumentationOptions options = new HttpInstrumentationOptions() + .setHttpLogLevel(HttpInstrumentationOptions.HttpLogLevel.BODY_AND_HEADERS); - HttpPipeline pipeline = createPipeline(DEFAULT_INSTRUMENTATION_OPTIONS, options, - request -> new MockHttpResponse(request, 200, BinaryData.fromString("Response body"))); + HttpPipeline pipeline = createPipeline(options, + request -> new Response<>(request, 200, new HttpHeaders(), BinaryData.fromString("Response body"))); HttpRequest request = createRequest(HttpMethod.GET, URI, logger); @@ -272,18 +305,19 @@ public void testResponseBodyLoggingOnClose() throws IOException { @Test public void testResponseBodyRequestedMultipleTimes() { - ClientLogger logger = setupLogLevelAndGetLogger(ClientLogger.LogLevel.INFORMATIONAL, logCaptureStream); - HttpLogOptions options = new HttpLogOptions().setLogLevel(HttpLogOptions.HttpLogDetailLevel.BODY); + ClientLogger logger = setupLogLevelAndGetLogger(LogLevel.INFORMATIONAL, logCaptureStream); + HttpInstrumentationOptions options = new HttpInstrumentationOptions() + .setHttpLogLevel(HttpInstrumentationOptions.HttpLogLevel.BODY_AND_HEADERS); - HttpPipeline pipeline = createPipeline(DEFAULT_INSTRUMENTATION_OPTIONS, options, - request -> new MockHttpResponse(request, 200, BinaryData.fromString("Response body"))); + HttpPipeline pipeline = createPipeline(options, + request -> new Response<>(request, 200, new HttpHeaders(), BinaryData.fromString("Response body"))); HttpRequest request = createRequest(HttpMethod.GET, URI, logger); - Response response = pipeline.send(request); + Response response = pipeline.send(request); for (int i = 0; i < 3; i++) { - BinaryData data = response.getBody(); + BinaryData data = response.getValue(); assertEquals(1, parseLogMessages(logCaptureStream).size()); assertEquals("Response body", data.toString()); } @@ -292,11 +326,12 @@ public void testResponseBodyRequestedMultipleTimes() { @ParameterizedTest @MethodSource("allowQueryParamSource") public void testBasicHttpLoggingRequestOff(Set allowedParams, String expectedUri) throws IOException { - ClientLogger logger = setupLogLevelAndGetLogger(ClientLogger.LogLevel.INFORMATIONAL, logCaptureStream); - HttpLogOptions options = new HttpLogOptions().setLogLevel(HttpLogOptions.HttpLogDetailLevel.BASIC) - .setAllowedQueryParamNames(allowedParams); + ClientLogger logger = setupLogLevelAndGetLogger(LogLevel.INFORMATIONAL, logCaptureStream); + HttpInstrumentationOptions options + = new HttpInstrumentationOptions().setHttpLogLevel(HttpInstrumentationOptions.HttpLogLevel.HEADERS) + .setAllowedQueryParamNames(allowedParams); - HttpPipeline pipeline = createPipeline(DEFAULT_INSTRUMENTATION_OPTIONS, options); + HttpPipeline pipeline = createPipeline(options); HttpRequest request = createRequest(HttpMethod.POST, URI, logger); Response response = pipeline.send(request); @@ -306,17 +341,18 @@ public void testBasicHttpLoggingRequestOff(Set allowedParams, String exp assertEquals(1, logMessages.size()); assertResponseLog(logMessages.get(0), expectedUri, response, 0); - assertEquals(11, logMessages.get(0).size()); + assertEquals(14, logMessages.get(0).size()); } @ParameterizedTest @MethodSource("allowedHeaders") public void testHeadersHttpLogging(Set allowedHeaders) throws IOException { - ClientLogger logger = setupLogLevelAndGetLogger(ClientLogger.LogLevel.VERBOSE, logCaptureStream); - HttpLogOptions options = new HttpLogOptions().setLogLevel(HttpLogOptions.HttpLogDetailLevel.HEADERS) - .setAllowedHeaderNames(allowedHeaders); + ClientLogger logger = setupLogLevelAndGetLogger(LogLevel.VERBOSE, logCaptureStream); + HttpInstrumentationOptions options + = new HttpInstrumentationOptions().setHttpLogLevel(HttpInstrumentationOptions.HttpLogLevel.HEADERS) + .setAllowedHeaderNames(allowedHeaders); - HttpPipeline pipeline = createPipeline(DEFAULT_INSTRUMENTATION_OPTIONS, options); + HttpPipeline pipeline = createPipeline(options); HttpRequest request = createRequest(HttpMethod.GET, URI, logger); request.getHeaders().set(CUSTOM_REQUEST_ID, "12345"); @@ -328,40 +364,41 @@ public void testHeadersHttpLogging(Set allowedHeaders) throws IO Map requestLog = logMessages.get(0); assertRequestLog(requestLog, request); - for (HttpHeader header : request.getHeaders()) { + request.getHeaders().stream().forEach(header -> { if (allowedHeaders.contains(header.getName())) { assertEquals(header.getValue(), requestLog.get(header.getName().toString())); } else { assertEquals("REDACTED", requestLog.get(header.getName().toString())); } - } + }); Map responseLog = logMessages.get(1); assertResponseLog(responseLog, response); - for (HttpHeader header : response.getHeaders()) { + response.getHeaders().stream().forEach(header -> { if (allowedHeaders.contains(header.getName())) { assertEquals(header.getValue(), responseLog.get(header.getName().toString())); } else { assertEquals("REDACTED", responseLog.get(header.getName().toString())); } - } + }); } @Test public void testStringBodyLogging() throws IOException { - ClientLogger logger = setupLogLevelAndGetLogger(ClientLogger.LogLevel.VERBOSE, logCaptureStream); - HttpLogOptions options = new HttpLogOptions().setLogLevel(HttpLogOptions.HttpLogDetailLevel.BODY); + ClientLogger logger = setupLogLevelAndGetLogger(LogLevel.VERBOSE, logCaptureStream); + HttpInstrumentationOptions options = new HttpInstrumentationOptions() + .setHttpLogLevel(HttpInstrumentationOptions.HttpLogLevel.BODY_AND_HEADERS); - HttpPipeline pipeline = createPipeline(DEFAULT_INSTRUMENTATION_OPTIONS, options, - request -> new MockHttpResponse(request, 200, BinaryData.fromString("Response body"))); + HttpPipeline pipeline = createPipeline(options, + request -> new Response<>(request, 200, new HttpHeaders(), BinaryData.fromString("Response body"))); HttpRequest request = createRequest(HttpMethod.PUT, URI, logger); request.setBody(BinaryData.fromString("Request body")); - Response response = pipeline.send(request); + Response response = pipeline.send(request); response.close(); - assertEquals("Response body", response.getBody().toString()); + assertEquals("Response body", response.getValue().toString()); List> logMessages = parseLogMessages(logCaptureStream); assertEquals(2, logMessages.size()); @@ -377,15 +414,15 @@ public void testStringBodyLogging() throws IOException { @Test public void testStreamBodyLogging() { - ClientLogger logger = setupLogLevelAndGetLogger(ClientLogger.LogLevel.VERBOSE, logCaptureStream); - HttpLogOptions options = new HttpLogOptions().setLogLevel(HttpLogOptions.HttpLogDetailLevel.BODY); + ClientLogger logger = setupLogLevelAndGetLogger(LogLevel.VERBOSE, logCaptureStream); + HttpInstrumentationOptions options = new HttpInstrumentationOptions() + .setHttpLogLevel(HttpInstrumentationOptions.HttpLogLevel.BODY_AND_HEADERS); BinaryData responseBody = BinaryData.fromString("Response body"); TestStream responseStream = new TestStream(responseBody); - HttpPipeline pipeline - = createPipeline(DEFAULT_INSTRUMENTATION_OPTIONS, options, request -> new MockHttpResponse(request, 200, - BinaryData.fromStream(responseStream, responseBody.getLength()))); + HttpPipeline pipeline = createPipeline(options, request -> new Response<>(request, 200, new HttpHeaders(), + BinaryData.fromStream(responseStream, responseBody.getLength()))); BinaryData requestBody = BinaryData.fromString("Request body"); TestStream requestStream = new TestStream(requestBody); @@ -393,11 +430,11 @@ public void testStreamBodyLogging() { request.setBody(BinaryData.fromStream(requestStream, requestBody.getLength())); assertFalse(request.getBody().isReplayable()); - Response response = pipeline.send(request); + Response response = pipeline.send(request); assertTrue(request.getBody().isReplayable()); - assertTrue(response.getBody().isReplayable()); + assertTrue(response.getValue().isReplayable()); - assertEquals("Response body", response.getBody().toString()); + assertEquals("Response body", response.getValue().toString()); List> logMessages = parseLogMessages(logCaptureStream); assertEquals(2, logMessages.size()); @@ -416,13 +453,14 @@ public void testStreamBodyLogging() { @Test public void testHugeBodyNotLogged() throws IOException { - ClientLogger logger = setupLogLevelAndGetLogger(ClientLogger.LogLevel.VERBOSE, logCaptureStream); - HttpLogOptions options = new HttpLogOptions().setLogLevel(HttpLogOptions.HttpLogDetailLevel.BODY); + ClientLogger logger = setupLogLevelAndGetLogger(LogLevel.VERBOSE, logCaptureStream); + HttpInstrumentationOptions options = new HttpInstrumentationOptions() + .setHttpLogLevel(HttpInstrumentationOptions.HttpLogLevel.BODY_AND_HEADERS); TestStream requestStream = new TestStream(1024 * 1024); TestStream responseStream = new TestStream(1024 * 1024); - HttpPipeline pipeline = createPipeline(DEFAULT_INSTRUMENTATION_OPTIONS, options, - request -> new MockHttpResponse(request, 200, BinaryData.fromStream(responseStream, (long) 1024 * 1024))); + HttpPipeline pipeline = createPipeline(options, request -> new Response<>(request, 200, new HttpHeaders(), + BinaryData.fromStream(responseStream, (long) 1024 * 1024))); HttpRequest request = createRequest(HttpMethod.PUT, URI, logger); @@ -447,13 +485,14 @@ public void testHugeBodyNotLogged() throws IOException { @Test public void testBodyWithUnknownLengthNotLogged() throws IOException { - ClientLogger logger = setupLogLevelAndGetLogger(ClientLogger.LogLevel.VERBOSE, logCaptureStream); - HttpLogOptions options = new HttpLogOptions().setLogLevel(HttpLogOptions.HttpLogDetailLevel.BODY); + ClientLogger logger = setupLogLevelAndGetLogger(LogLevel.VERBOSE, logCaptureStream); + HttpInstrumentationOptions options = new HttpInstrumentationOptions() + .setHttpLogLevel(HttpInstrumentationOptions.HttpLogLevel.BODY_AND_HEADERS); TestStream requestStream = new TestStream(1024); TestStream responseStream = new TestStream(1024); - HttpPipeline pipeline = createPipeline(DEFAULT_INSTRUMENTATION_OPTIONS, options, - request -> new MockHttpResponse(request, 200, BinaryData.fromStream(responseStream))); + HttpPipeline pipeline = createPipeline(options, + request -> new Response<>(request, 200, new HttpHeaders(), BinaryData.fromStream(responseStream))); HttpRequest request = createRequest(HttpMethod.PUT, URI, logger); request.getHeaders().set(HttpHeaderName.CONTENT_LENGTH, "1024"); @@ -481,13 +520,14 @@ public void testBodyWithUnknownLengthNotLogged() throws IOException { @Test public void tracingWithRetriesException() throws IOException { AtomicInteger count = new AtomicInteger(0); - ClientLogger logger = setupLogLevelAndGetLogger(ClientLogger.LogLevel.VERBOSE, logCaptureStream); - HttpLogOptions options = new HttpLogOptions().setLogLevel(HttpLogOptions.HttpLogDetailLevel.BASIC); + ClientLogger logger = setupLogLevelAndGetLogger(LogLevel.VERBOSE, logCaptureStream); + HttpInstrumentationOptions options = new HttpInstrumentationOptions() + .setHttpLogLevel(HttpInstrumentationOptions.HttpLogLevel.BODY_AND_HEADERS); AtomicReference firstTryContext = new AtomicReference<>(); UnknownHostException expectedException = new UnknownHostException("test exception"); - HttpPipeline pipeline = new HttpPipelineBuilder() - .policies(new HttpRetryPolicy(), new HttpInstrumentationPolicy(DEFAULT_INSTRUMENTATION_OPTIONS, options)) + HttpPipeline pipeline = new HttpPipelineBuilder().addPolicy(new HttpRetryPolicy()) + .addPolicy(new HttpInstrumentationPolicy(options)) .httpClient(request -> { assertEquals(traceparent(request.getRequestOptions().getInstrumentationContext()), request.getHeaders().get(TRACEPARENT).getValue()); @@ -495,7 +535,7 @@ public void tracingWithRetriesException() throws IOException { firstTryContext.set(request.getRequestOptions().getInstrumentationContext()); throw expectedException; } else { - return new MockHttpResponse(request, 200); + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); } }) .build(); @@ -521,19 +561,20 @@ public void tracingWithRetriesException() throws IOException { @Test public void tracingWithRetriesStatusCode() throws IOException { AtomicInteger count = new AtomicInteger(0); - ClientLogger logger = setupLogLevelAndGetLogger(ClientLogger.LogLevel.VERBOSE, logCaptureStream); - HttpLogOptions options = new HttpLogOptions().setLogLevel(HttpLogOptions.HttpLogDetailLevel.BASIC); + ClientLogger logger = setupLogLevelAndGetLogger(LogLevel.VERBOSE, logCaptureStream); + HttpInstrumentationOptions options = new HttpInstrumentationOptions() + .setHttpLogLevel(HttpInstrumentationOptions.HttpLogLevel.BODY_AND_HEADERS); AtomicReference firstTryContext = new AtomicReference<>(); - HttpPipeline pipeline = new HttpPipelineBuilder() - .policies(new HttpRetryPolicy(), new HttpInstrumentationPolicy(DEFAULT_INSTRUMENTATION_OPTIONS, options)) + HttpPipeline pipeline = new HttpPipelineBuilder().addPolicy(new HttpRetryPolicy()) + .addPolicy(new HttpInstrumentationPolicy(options)) .httpClient(request -> { if (count.getAndIncrement() == 0) { firstTryContext.set(request.getRequestOptions().getInstrumentationContext()); - return new MockHttpResponse(request, 500); + return new Response<>(request, 500, new HttpHeaders(), BinaryData.empty()); } else { - return new MockHttpResponse(request, 200); + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); } }) .build(); @@ -553,15 +594,15 @@ public void tracingWithRetriesStatusCode() throws IOException { @ParameterizedTest @MethodSource("logLevels") - public void retryPolicyLoggingRetriesExhausted(ClientLogger.LogLevel logLevel, boolean expectRetryingLogs, + public void retryPolicyLoggingRetriesExhausted(LogLevel logLevel, boolean expectRetryingLogs, boolean expectExhaustedLog) throws IOException { ClientLogger logger = setupLogLevelAndGetLogger(logLevel, logCaptureStream); int maxRetries = 3; HttpRetryOptions retryOptions = new HttpRetryOptions(maxRetries, Duration.ofMillis(5)); - HttpPipeline pipeline = new HttpPipelineBuilder().policies(new HttpRetryPolicy(retryOptions)) - .httpClient(request -> new MockHttpResponse(request, 500)) + HttpPipeline pipeline = new HttpPipelineBuilder().addPolicy(new HttpRetryPolicy(retryOptions)) + .httpClient(request -> new Response<>(request, 500, new HttpHeaders(), BinaryData.empty())) .build(); InstrumentationContext parentContext = createRandomInstrumentationContext(); @@ -593,21 +634,22 @@ public void retryPolicyLoggingRetriesExhausted(ClientLogger.LogLevel logLevel, b @Test public void tracingWithRedirects() throws IOException { AtomicInteger count = new AtomicInteger(0); - ClientLogger logger = setupLogLevelAndGetLogger(ClientLogger.LogLevel.VERBOSE, logCaptureStream); - HttpLogOptions options = new HttpLogOptions().setLogLevel(HttpLogOptions.HttpLogDetailLevel.BASIC); + ClientLogger logger = setupLogLevelAndGetLogger(LogLevel.VERBOSE, logCaptureStream); + HttpInstrumentationOptions options = new HttpInstrumentationOptions() + .setHttpLogLevel(HttpInstrumentationOptions.HttpLogLevel.BODY_AND_HEADERS); AtomicReference firstRedirectContext = new AtomicReference<>(); - HttpPipeline pipeline = new HttpPipelineBuilder() - .policies(new HttpRedirectPolicy(), new HttpInstrumentationPolicy(DEFAULT_INSTRUMENTATION_OPTIONS, options)) + HttpPipeline pipeline = new HttpPipelineBuilder().addPolicy(new HttpRedirectPolicy()) + .addPolicy(new HttpInstrumentationPolicy(options)) .httpClient(request -> { if (count.getAndIncrement() == 0) { firstRedirectContext.set(request.getRequestOptions().getInstrumentationContext()); HttpHeaders httpHeaders = new HttpHeaders().set(HttpHeaderName.LOCATION, "http://redirecthost/" + count.get() + "?param=value&api-version=42"); - return new MockHttpResponse(request, 302, httpHeaders); + return new Response<>(request, 302, httpHeaders, BinaryData.empty()); } else { - return new MockHttpResponse(request, 200); + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); } }) .build(); @@ -631,11 +673,11 @@ public void tracingWithRedirects() throws IOException { @Test public void redirectLoggingMethodNotSupported() throws IOException { AtomicInteger count = new AtomicInteger(0); - ClientLogger logger = setupLogLevelAndGetLogger(ClientLogger.LogLevel.VERBOSE, logCaptureStream); - HttpPipeline pipeline = new HttpPipelineBuilder().policies(new HttpRedirectPolicy()).httpClient(request -> { + ClientLogger logger = setupLogLevelAndGetLogger(LogLevel.VERBOSE, logCaptureStream); + HttpPipeline pipeline = new HttpPipelineBuilder().addPolicy(new HttpRedirectPolicy()).httpClient(request -> { count.getAndIncrement(); HttpHeaders httpHeaders = new HttpHeaders().set(HttpHeaderName.LOCATION, "http://redirecthost/"); - return new MockHttpResponse(request, 302, httpHeaders); + return new Response<>(request, 302, httpHeaders, BinaryData.empty()); }).build(); InstrumentationContext parentContext = createRandomInstrumentationContext(); @@ -654,11 +696,11 @@ public void redirectLoggingMethodNotSupported() throws IOException { @Test public void redirectToTheSameUri() throws IOException { AtomicInteger count = new AtomicInteger(0); - ClientLogger logger = setupLogLevelAndGetLogger(ClientLogger.LogLevel.VERBOSE, logCaptureStream); - HttpPipeline pipeline = new HttpPipelineBuilder().policies(new HttpRedirectPolicy()).httpClient(request -> { + ClientLogger logger = setupLogLevelAndGetLogger(LogLevel.VERBOSE, logCaptureStream); + HttpPipeline pipeline = new HttpPipelineBuilder().addPolicy(new HttpRedirectPolicy()).httpClient(request -> { count.getAndIncrement(); HttpHeaders httpHeaders = new HttpHeaders().set(HttpHeaderName.LOCATION, "http://redirecthost/"); - return new MockHttpResponse(request, 302, httpHeaders); + return new Response<>(request, 302, httpHeaders, BinaryData.empty()); }).build(); InstrumentationContext parentContext = createRandomInstrumentationContext(); @@ -678,12 +720,12 @@ public void redirectToTheSameUri() throws IOException { @Test public void redirectAttemptsExhausted() throws IOException { AtomicInteger count = new AtomicInteger(0); - ClientLogger logger = setupLogLevelAndGetLogger(ClientLogger.LogLevel.VERBOSE, logCaptureStream); - HttpPipeline pipeline = new HttpPipelineBuilder().policies(new HttpRedirectPolicy()).httpClient(request -> { + ClientLogger logger = setupLogLevelAndGetLogger(LogLevel.VERBOSE, logCaptureStream); + HttpPipeline pipeline = new HttpPipelineBuilder().addPolicy(new HttpRedirectPolicy()).httpClient(request -> { count.getAndIncrement(); HttpHeaders httpHeaders = new HttpHeaders().set(HttpHeaderName.LOCATION, "http://redirecthost/" + count.get()); - return new MockHttpResponse(request, 302, httpHeaders); + return new Response<>(request, 302, httpHeaders, BinaryData.empty()); }).build(); InstrumentationContext parentContext = createRandomInstrumentationContext(); @@ -702,10 +744,8 @@ public void redirectAttemptsExhausted() throws IOException { } public static Stream logLevels() { - return Stream.of(Arguments.of(ClientLogger.LogLevel.ERROR, false, false), - Arguments.of(ClientLogger.LogLevel.WARNING, false, true), - Arguments.of(ClientLogger.LogLevel.INFORMATIONAL, false, true), - Arguments.of(ClientLogger.LogLevel.VERBOSE, true, true)); + return Stream.of(Arguments.of(LogLevel.ERROR, false, false), Arguments.of(LogLevel.WARNING, false, true), + Arguments.of(LogLevel.INFORMATIONAL, false, true), Arguments.of(LogLevel.VERBOSE, true, true)); } public static Stream allowQueryParamSource() { @@ -729,8 +769,8 @@ public static Stream> allowedHeaders() { } public static Stream testExceptionSeverity() { - return Stream.of(Arguments.of(ClientLogger.LogLevel.INFORMATIONAL, true), - Arguments.of(ClientLogger.LogLevel.WARNING, true), Arguments.of(ClientLogger.LogLevel.ERROR, false)); + return Stream.of(Arguments.of(LogLevel.INFORMATIONAL, true), Arguments.of(LogLevel.WARNING, true), + Arguments.of(LogLevel.ERROR, false)); } private static class TestStream extends InputStream { @@ -935,18 +975,24 @@ private void assertExceptionLog(Map log, String expectedUri, Htt assertTraceContext(log, context); } - private HttpPipeline createPipeline(InstrumentationOptions instrumentationOptions, HttpLogOptions options) { - return createPipeline(instrumentationOptions, options, request -> { + private HttpPipeline createPipeline(HttpInstrumentationOptions instrumentationOptions) { + return createPipeline(instrumentationOptions, request -> { if (request.getBody() != null) { request.getBody().toString(); } - return new MockHttpResponse(request, 200, BinaryData.fromString("Hello, world!")); + BinaryData responseBody = BinaryData.fromString("Hello, world!"); + Response response = new Response<>(request, 200, new HttpHeaders(), responseBody); + response.getHeaders() + .set(HttpHeaderName.CONTENT_TYPE, "application/text") + .set(HttpHeaderName.CONTENT_LENGTH, responseBody.getLength().toString()) + .set(HttpHeaderName.fromString("not-safe-to-log"), "12345"); + return response; }); } - private HttpPipeline createPipeline(InstrumentationOptions instrumentationOptions, HttpLogOptions options, - Function> httpClient) { - return new HttpPipelineBuilder().policies(new HttpInstrumentationPolicy(instrumentationOptions, options)) + private HttpPipeline createPipeline(HttpInstrumentationOptions instrumentationOptions, + Function> httpClient) { + return new HttpPipelineBuilder().addPolicy(new HttpInstrumentationPolicy(instrumentationOptions)) .httpClient(httpClient::apply) .build(); } @@ -957,7 +1003,7 @@ private HttpRequest createRequest(HttpMethod method, String url, ClientLogger lo private HttpRequest createRequest(HttpMethod method, String url, ClientLogger logger, InstrumentationContext context) { - HttpRequest request = new HttpRequest(method, url); + HttpRequest request = new HttpRequest().setMethod(method).setUri(url); request.getHeaders().set(HttpHeaderName.CONTENT_TYPE, "application/json"); request.getHeaders().set(HttpHeaderName.AUTHORIZATION, "Bearer {token}"); request.setRequestOptions(new RequestOptions().setLogger(logger).setInstrumentationContext(context)); diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/HttpInstrumentationPolicyFallbackTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/HttpInstrumentationPolicyFallbackTests.java index 2417835db52f..003007d188ff 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/HttpInstrumentationPolicyFallbackTests.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/HttpInstrumentationPolicyFallbackTests.java @@ -3,13 +3,12 @@ package io.clientcore.core.http.pipeline; -import io.clientcore.core.http.MockHttpResponse; import io.clientcore.core.http.models.HttpHeaderName; -import io.clientcore.core.http.models.HttpLogOptions; +import io.clientcore.core.http.models.HttpHeaders; import io.clientcore.core.http.models.HttpMethod; import io.clientcore.core.http.models.HttpRequest; import io.clientcore.core.http.models.Response; -import io.clientcore.core.instrumentation.InstrumentationOptions; +import io.clientcore.core.models.binarydata.BinaryData; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -22,22 +21,22 @@ import static org.junit.jupiter.api.Assertions.assertNull; public class HttpInstrumentationPolicyFallbackTests { - private static final InstrumentationOptions OPTIONS = new InstrumentationOptions<>(); - private static final InstrumentationOptions DISABLED_TRACING_OPTIONS - = new InstrumentationOptions<>().setTracingEnabled(false); - private static final HttpLogOptions ENABLED_HTTP_LOG_OPTIONS - = new HttpLogOptions().setLogLevel(HttpLogOptions.HttpLogDetailLevel.HEADERS); private static final HttpHeaderName TRACESTATE = HttpHeaderName.fromString("tracestate"); @Test public void simpleRequestTracingDisabled() throws IOException { - HttpPipeline pipeline = new HttpPipelineBuilder() - .policies(new HttpInstrumentationPolicy(DISABLED_TRACING_OPTIONS, ENABLED_HTTP_LOG_OPTIONS)) - .httpClient(request -> new MockHttpResponse(request, 200)) - .build(); + HttpInstrumentationOptions tracingOffLoggingOnOptions + = new HttpInstrumentationOptions().setTracingEnabled(false) + .setHttpLogLevel(HttpInstrumentationOptions.HttpLogLevel.HEADERS); + + HttpPipeline pipeline + = new HttpPipelineBuilder().addPolicy(new HttpInstrumentationPolicy(tracingOffLoggingOnOptions)) + .httpClient(request -> new Response<>(request, 200, new HttpHeaders(), BinaryData.empty())) + .build(); // should not throw - try (Response response = pipeline.send(new HttpRequest(HttpMethod.GET, "https://localhost/"))) { + try (Response response + = pipeline.send(new HttpRequest().setMethod(HttpMethod.GET).setUri("https://localhost/"))) { assertEquals(200, response.getStatusCode()); assertNull(response.getRequest().getHeaders().get(TRACESTATE)); assertNull(response.getRequest().getHeaders().get(TRACEPARENT)); @@ -47,13 +46,17 @@ public void simpleRequestTracingDisabled() throws IOException { @ParameterizedTest @ValueSource(ints = { 200, 201, 206, 302, 400, 404, 500, 503 }) public void simpleRequestTracingEnabled(int statusCode) throws IOException { + HttpInstrumentationOptions tracingOnLoggingOnOptions + = new HttpInstrumentationOptions().setHttpLogLevel(HttpInstrumentationOptions.HttpLogLevel.HEADERS); + HttpPipeline pipeline - = new HttpPipelineBuilder().policies(new HttpInstrumentationPolicy(OPTIONS, ENABLED_HTTP_LOG_OPTIONS)) - .httpClient(request -> new MockHttpResponse(request, statusCode)) + = new HttpPipelineBuilder().addPolicy(new HttpInstrumentationPolicy(tracingOnLoggingOnOptions)) + .httpClient(request -> new Response<>(request, statusCode, new HttpHeaders(), BinaryData.empty())) .build(); // should not throw - try (Response response = pipeline.send(new HttpRequest(HttpMethod.GET, "https://localhost/"))) { + try (Response response + = pipeline.send(new HttpRequest().setMethod(HttpMethod.GET).setUri("https://localhost/"))) { assertEquals(statusCode, response.getStatusCode()); assertNull(response.getRequest().getHeaders().get(TRACESTATE)); assertNotNull(response.getRequest().getHeaders().get(TRACEPARENT)); diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/HttpPipelinePolicyTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/HttpPipelinePolicyTests.java index fcd0b1edc9b3..a1cb1447fde1 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/HttpPipelinePolicyTests.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/HttpPipelinePolicyTests.java @@ -3,13 +3,12 @@ package io.clientcore.core.http.pipeline; -import io.clientcore.core.http.NoOpHttpClient; import io.clientcore.core.http.client.HttpClient; import io.clientcore.core.http.models.HttpHeaders; import io.clientcore.core.http.models.HttpMethod; import io.clientcore.core.http.models.HttpRequest; -import io.clientcore.core.http.models.HttpResponse; import io.clientcore.core.http.models.Response; +import io.clientcore.core.models.binarydata.BinaryData; import org.junit.jupiter.api.Test; import java.io.IOException; @@ -24,9 +23,12 @@ public void verifySend() throws IOException { SyncPolicy policy2 = new SyncPolicy(); HttpPipeline pipeline - = new HttpPipelineBuilder().httpClient(new NoOpHttpClient()).policies(policy1, policy2).build(); + = new HttpPipelineBuilder().httpClient(request -> new Response<>(request, 200, new HttpHeaders(), null)) + .addPolicy(policy1) + .addPolicy(policy2) + .build(); - pipeline.send(new HttpRequest(HttpMethod.GET, "http://localhost/")).close(); + pipeline.send(new HttpRequest().setMethod(HttpMethod.GET).setUri("http://localhost/")).close(); assertEquals(1, policy1.syncCalls.get()); assertEquals(1, policy2.syncCalls.get()); @@ -36,11 +38,12 @@ public void verifySend() throws IOException { public void defaultImplementationShouldCallRightStack() throws IOException { DefaultImplementationSyncPolicy policyWithDefaultSyncImplementation = new DefaultImplementationSyncPolicy(); - HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(new NoOpHttpClient()) - .policies(policyWithDefaultSyncImplementation) - .build(); + HttpPipeline pipeline + = new HttpPipelineBuilder().httpClient(request -> new Response<>(request, 200, new HttpHeaders(), null)) + .addPolicy(policyWithDefaultSyncImplementation) + .build(); - pipeline.send(new HttpRequest(HttpMethod.GET, "http://localhost/")).close(); + pipeline.send(new HttpRequest().setMethod(HttpMethod.GET).setUri("http://localhost/")).close(); assertEquals(1, policyWithDefaultSyncImplementation.syncCalls.get()); assertEquals(1, policyWithDefaultSyncImplementation.syncCalls.get()); @@ -52,7 +55,7 @@ public void defaultImplementationShouldCallRightStack() throws IOException { @Test public void doesNotThrowThatThreadIsNonBlocking() throws IOException { SyncPolicy policy1 = new SyncPolicy(); - HttpPipelinePolicy badPolicy1 = (httpRequest, next) -> { + HttpPipelinePolicy badPolicy1 = (ignored, next) -> { try { Thread.sleep(10); } catch (InterruptedException e) { @@ -62,7 +65,7 @@ public void doesNotThrowThatThreadIsNonBlocking() throws IOException { return next.process(); }; - HttpPipelinePolicy badPolicy2 = (httpRequest, next) -> { + HttpPipelinePolicy badPolicy2 = (ignored, next) -> { try { Thread.sleep(10); } catch (InterruptedException e) { @@ -78,20 +81,23 @@ public void doesNotThrowThatThreadIsNonBlocking() throws IOException { } catch (InterruptedException e) { throw new RuntimeException(e); } - return new HttpResponse<>(request, 200, new HttpHeaders(), null); + return new Response<>(request, 200, new HttpHeaders(), null); }; - HttpPipeline pipeline - = new HttpPipelineBuilder().httpClient(badClient).policies(policy1, badPolicy1, badPolicy2).build(); + HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(badClient) + .addPolicy(policy1) + .addPolicy(badPolicy1) + .addPolicy(badPolicy2) + .build(); - pipeline.send(new HttpRequest(HttpMethod.GET, "http://localhost/")).close(); + pipeline.send(new HttpRequest().setMethod(HttpMethod.GET).setUri("http://localhost/")).close(); } private static class SyncPolicy implements HttpPipelinePolicy { final AtomicInteger syncCalls = new AtomicInteger(); @Override - public Response process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { + public Response process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { syncCalls.incrementAndGet(); return next.process(); @@ -102,7 +108,7 @@ private static class DefaultImplementationSyncPolicy implements HttpPipelinePoli final AtomicInteger syncCalls = new AtomicInteger(); @Override - public Response process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { + public Response process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { syncCalls.incrementAndGet(); return next.process(); diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/HttpPipelineTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/HttpPipelineTests.java index 02ae8cc61826..7c0e387b9455 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/HttpPipelineTests.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/HttpPipelineTests.java @@ -3,11 +3,11 @@ package io.clientcore.core.http.pipeline; -import io.clientcore.core.http.MockHttpResponse; -import io.clientcore.core.http.NoOpHttpClient; +import io.clientcore.core.http.models.HttpHeaders; import io.clientcore.core.http.models.HttpMethod; import io.clientcore.core.http.models.HttpRequest; import io.clientcore.core.http.models.Response; +import io.clientcore.core.models.binarydata.BinaryData; import org.junit.jupiter.api.Test; import java.net.URI; @@ -18,13 +18,7 @@ public class HttpPipelineTests { @Test public void constructorWithNoArguments() { - HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(new NoOpHttpClient() { - @Override - public Response send(HttpRequest request) { - // do nothing - return null; - } - }).build(); + HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(request -> null).build(); assertEquals(0, pipeline.getPolicies().size()); assertNotNull(pipeline.getHttpClient()); @@ -33,13 +27,7 @@ public Response send(HttpRequest request) { @Test public void withRequestPolicy() { HttpPipeline pipeline - = new HttpPipelineBuilder().policies(new HttpRetryPolicy()).httpClient(new NoOpHttpClient() { - @Override - public Response send(HttpRequest request) { - // do nothing - return null; - } - }).build(); + = new HttpPipelineBuilder().addPolicy(new HttpRetryPolicy()).httpClient(request -> null).build(); assertEquals(1, pipeline.getPolicies().size()); assertEquals(HttpRetryPolicy.class, pipeline.getPolicies().get(0).getClass()); @@ -49,13 +37,7 @@ public Response send(HttpRequest request) { @Test public void withRequestOptions() { HttpPipeline pipeline - = new HttpPipelineBuilder().policies(new HttpRetryPolicy()).httpClient(new NoOpHttpClient() { - @Override - public Response send(HttpRequest request) { - // do nothing - return null; - } - }).build(); + = new HttpPipelineBuilder().addPolicy(new HttpRetryPolicy()).httpClient(request -> null).build(); assertNotNull(pipeline.getHttpClient()); } @@ -64,17 +46,15 @@ public Response send(HttpRequest request) { public void withNoRequestPolicies() { final HttpMethod expectedHttpMethod = HttpMethod.GET; final URI expectedUri = URI.create("http://my.site.com"); - final HttpPipeline httpPipeline = new HttpPipelineBuilder().httpClient(new NoOpHttpClient() { - @Override - public Response send(HttpRequest request) { - assertEquals(0, request.getHeaders().getSize()); - assertEquals(expectedHttpMethod, request.getHttpMethod()); - assertEquals(expectedUri, request.getUri()); - - return new MockHttpResponse(request, 200); - } + final HttpPipeline httpPipeline = new HttpPipelineBuilder().httpClient(request -> { + assertEquals(0, request.getHeaders().getSize()); + assertEquals(expectedHttpMethod, request.getHttpMethod()); + assertEquals(expectedUri, request.getUri()); + + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); }).build(); - final Response response = httpPipeline.send(new HttpRequest(expectedHttpMethod, expectedUri)); + final Response response + = httpPipeline.send(new HttpRequest().setMethod(expectedHttpMethod).setUri(expectedUri)); assertNotNull(response); assertEquals(200, response.getStatusCode()); @@ -84,17 +64,15 @@ public Response send(HttpRequest request) { public void sendWithPolicies() { final HttpMethod expectedHttpMethod = HttpMethod.GET; final URI expectedUri = URI.create("http://my.site.com"); - final HttpPipeline httpPipeline = new HttpPipelineBuilder().httpClient(new NoOpHttpClient() { - @Override - public Response send(HttpRequest request) { - assertEquals(0, request.getHeaders().getSize()); - assertEquals(expectedHttpMethod, request.getHttpMethod()); - assertEquals(expectedUri, request.getUri()); - - return new MockHttpResponse(request, 200); - } + final HttpPipeline httpPipeline = new HttpPipelineBuilder().httpClient(request -> { + assertEquals(0, request.getHeaders().getSize()); + assertEquals(expectedHttpMethod, request.getHttpMethod()); + assertEquals(expectedUri, request.getUri()); + + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); }).build(); - final Response response = httpPipeline.send(new HttpRequest(expectedHttpMethod, expectedUri)); + final Response response + = httpPipeline.send(new HttpRequest().setMethod(expectedHttpMethod).setUri(expectedUri)); assertNotNull(response); assertEquals(200, response.getStatusCode()); diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/KeyCredentialPolicyTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/KeyCredentialPolicyTests.java index 70c2704e9a34..b0c09e5836ee 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/KeyCredentialPolicyTests.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/KeyCredentialPolicyTests.java @@ -3,7 +3,7 @@ package io.clientcore.core.http.pipeline; -import io.clientcore.core.credential.KeyCredential; +import io.clientcore.core.credentials.KeyCredential; import io.clientcore.core.http.models.HttpHeaderName; import io.clientcore.core.http.models.HttpHeaders; import org.junit.jupiter.params.ParameterizedTest; diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/RedirectPolicyTest.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/RedirectPolicyTest.java index 4b71d2181611..4163c2fd6313 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/RedirectPolicyTest.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/RedirectPolicyTest.java @@ -3,15 +3,13 @@ package io.clientcore.core.http.pipeline; -import io.clientcore.core.http.MockHttpResponse; -import io.clientcore.core.http.NoOpHttpClient; import io.clientcore.core.http.client.HttpClient; import io.clientcore.core.http.models.HttpHeaderName; import io.clientcore.core.http.models.HttpHeaders; import io.clientcore.core.http.models.HttpMethod; -import io.clientcore.core.http.models.HttpRedirectOptions; import io.clientcore.core.http.models.HttpRequest; import io.clientcore.core.http.models.Response; +import io.clientcore.core.models.binarydata.BinaryData; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -31,16 +29,13 @@ public class RedirectPolicyTest { @Test public void noRedirectPolicyTest() throws Exception { - final HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(new NoOpHttpClient() { - @Override - public Response send(HttpRequest request) { - if (request.getUri().toString().equals("http://localhost/")) { - HttpHeaders httpHeader - = new HttpHeaders().set(HttpHeaderName.fromString("Location"), "http://redirecthost/"); - return new MockHttpResponse(request, 308, httpHeader); - } else { - return new MockHttpResponse(request, 200); - } + final HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(request -> { + if (request.getUri().toString().equals("http://localhost/")) { + HttpHeaders httpHeader + = new HttpHeaders().set(HttpHeaderName.fromString("Location"), "http://redirecthost/"); + return new Response<>(request, 308, httpHeader, BinaryData.empty()); + } else { + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); } }).build(); @@ -57,14 +52,14 @@ public void defaultRedirectExpectedStatusCodes(int statusCode) throws Exception HttpHeaders httpHeader = new HttpHeaders().set(HttpHeaderName.LOCATION, "http://redirecthost/") .set(HttpHeaderName.AUTHORIZATION, "12345"); - return new MockHttpResponse(request, statusCode, httpHeader); + return new Response<>(request, statusCode, httpHeader, BinaryData.empty()); } else { - return new MockHttpResponse(request, 200); + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); } }); HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(httpClient) - .policies(new HttpRedirectPolicy(DEFAULT_REDIRECT_STRATEGY)) + .addPolicy(new HttpRedirectPolicy(DEFAULT_REDIRECT_STRATEGY)) .build(); try (Response response = sendRequest(pipeline, HttpMethod.GET)) { @@ -82,11 +77,11 @@ public void redirectForNAttempts() throws Exception { requestCount[0]++; - return new MockHttpResponse(request, 308, httpHeader); + return new Response<>(request, 308, httpHeader, BinaryData.empty()); }); HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(httpClient) - .policies( + .addPolicy( new HttpRedirectPolicy(new HttpRedirectOptions(5, HttpHeaderName.LOCATION, EnumSet.of(HttpMethod.GET)))) .build(); @@ -102,14 +97,14 @@ public void redirectNonAllowedMethodTest() throws Exception { if (request.getUri().toString().equals("http://localhost/")) { HttpHeaders httpHeader = new HttpHeaders().set(HttpHeaderName.LOCATION, "http://redirecthost/"); - return new MockHttpResponse(request, 308, httpHeader); + return new Response<>(request, 308, httpHeader, BinaryData.empty()); } else { - return new MockHttpResponse(request, 200); + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); } }); HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(httpClient) - .policies(new HttpRedirectPolicy( + .addPolicy(new HttpRedirectPolicy( new HttpRedirectOptions(5, HttpHeaderName.LOCATION, EnumSet.of(HttpMethod.GET, HttpMethod.HEAD)))) .build(); @@ -126,14 +121,14 @@ public void redirectAllowedStatusCodesTest() throws Exception { if (request.getUri().toString().equals("http://localhost/")) { HttpHeaders httpHeader = new HttpHeaders().set(HttpHeaderName.LOCATION, "http://redirecthost/"); - return new MockHttpResponse(request, 308, httpHeader); + return new Response<>(request, 308, httpHeader, BinaryData.empty()); } else { - return new MockHttpResponse(request, 200); + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); } }); HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(httpClient) - .policies(new HttpRedirectPolicy(DEFAULT_REDIRECT_STRATEGY)) + .addPolicy(new HttpRedirectPolicy(DEFAULT_REDIRECT_STRATEGY)) .build(); try (Response response = sendRequest(pipeline, HttpMethod.GET)) { @@ -148,18 +143,18 @@ public void alreadyAttemptedUrisTest() throws Exception { if (request.getUri().toString().equals("http://localhost/")) { HttpHeaders httpHeader = new HttpHeaders().set(HttpHeaderName.LOCATION, "http://redirecthost/"); - return new MockHttpResponse(request, 308, httpHeader); + return new Response<>(request, 308, httpHeader, BinaryData.empty()); } else if (request.getUri().toString().equals("http://redirecthost/")) { HttpHeaders httpHeader = new HttpHeaders().set(HttpHeaderName.LOCATION, "http://redirecthost/"); - return new MockHttpResponse(request, 308, httpHeader); + return new Response<>(request, 308, httpHeader, BinaryData.empty()); } else { - return new MockHttpResponse(request, 200); + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); } }); HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(httpClient) - .policies(new HttpRedirectPolicy(DEFAULT_REDIRECT_STRATEGY)) + .addPolicy(new HttpRedirectPolicy(DEFAULT_REDIRECT_STRATEGY)) .build(); try (Response response = sendRequest(pipeline, HttpMethod.GET)) { @@ -177,11 +172,11 @@ public void redirectForProvidedHeader() throws Exception { requestCount[0]++; - return new MockHttpResponse(request, 308, httpHeader); + return new Response<>(request, 308, httpHeader, BinaryData.empty()); }); HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(httpClient) - .policies(new HttpRedirectPolicy(new HttpRedirectOptions(5, HttpHeaderName.fromString("Location1"), null))) + .addPolicy(new HttpRedirectPolicy(new HttpRedirectOptions(5, HttpHeaderName.fromString("Location1"), null))) .build(); try (Response response = sendRequest(pipeline, HttpMethod.GET)) { @@ -199,27 +194,27 @@ public void redirectForProvidedMethods() throws Exception { HttpHeaders httpHeader = new HttpHeaders().set(HttpHeaderName.LOCATION, "http://redirecthost/" + requestCount[0]++); - request.setHttpMethod(HttpMethod.PUT); + request.setMethod(HttpMethod.PUT); requestCount[0]++; - return new MockHttpResponse(request, 308, httpHeader); + return new Response<>(request, 308, httpHeader, BinaryData.empty()); } else if (request.getUri().toString().equals("http://redirecthost/" + requestCount[0]) && requestCount[0] == 2) { HttpHeaders httpHeader = new HttpHeaders().set(HttpHeaderName.LOCATION, "http://redirecthost/" + requestCount[0]++); - request.setHttpMethod(HttpMethod.POST); + request.setMethod(HttpMethod.POST); - return new MockHttpResponse(request, 308, httpHeader); + return new Response<>(request, 308, httpHeader, BinaryData.empty()); } else { - return new MockHttpResponse(request, 200); + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); } }); HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(httpClient) - .policies(new HttpRedirectPolicy(new HttpRedirectOptions(5, null, allowedMethods))) + .addPolicy(new HttpRedirectPolicy(new HttpRedirectOptions(5, null, allowedMethods))) .build(); try (Response response = sendRequest(pipeline, HttpMethod.GET)) { @@ -232,14 +227,14 @@ public void redirectForProvidedMethods() throws Exception { public void nullRedirectUriTest() throws Exception { RecordingHttpClient httpClient = new RecordingHttpClient(request -> { if (request.getUri().toString().equals("http://localhost/")) { - return new MockHttpResponse(request, 308); + return new Response<>(request, 308, new HttpHeaders(), BinaryData.empty()); } else { - return new MockHttpResponse(request, 200); + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); } }); HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(httpClient) - .policies(new HttpRedirectPolicy(DEFAULT_REDIRECT_STRATEGY)) + .addPolicy(new HttpRedirectPolicy(DEFAULT_REDIRECT_STRATEGY)) .build(); try (Response response = sendRequest(pipeline, HttpMethod.GET)) { @@ -254,14 +249,14 @@ public void redirectForMultipleRequests() throws Exception { if (request.getUri().toString().equals("http://localhost/")) { HttpHeaders httpHeader = new HttpHeaders().set(HttpHeaderName.LOCATION, "http://redirecthost/"); - return new MockHttpResponse(request, 308, httpHeader); + return new Response<>(request, 308, httpHeader, BinaryData.empty()); } else { - return new MockHttpResponse(request, 200); + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); } }); HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(httpClient) - .policies(new HttpRedirectPolicy(DEFAULT_REDIRECT_STRATEGY)) + .addPolicy(new HttpRedirectPolicy(DEFAULT_REDIRECT_STRATEGY)) .build(); try (Response response1 = sendRequest(pipeline, HttpMethod.GET)) { @@ -277,16 +272,13 @@ public void redirectForMultipleRequests() throws Exception { @Test public void nonRedirectRequest() throws Exception { - final HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(new NoOpHttpClient() { - @Override - public Response send(HttpRequest request) { - if (request.getUri().toString().equals("http://localhost/")) { - return new MockHttpResponse(request, 401); - } else { - return new MockHttpResponse(request, 200); - } + final HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(request -> { + if (request.getUri().toString().equals("http://localhost/")) { + return new Response<>(request, 401, new HttpHeaders(), BinaryData.empty()); + } else { + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); } - }).policies(new HttpRedirectPolicy(DEFAULT_REDIRECT_STRATEGY)).build(); + }).addPolicy(new HttpRedirectPolicy(DEFAULT_REDIRECT_STRATEGY)).build(); try (Response response = sendRequest(pipeline, HttpMethod.GET)) { assertEquals(401, response.getStatusCode()); @@ -300,14 +292,14 @@ public void defaultRedirectAuthorizationHeaderCleared() throws Exception { HttpHeaders httpHeader = new HttpHeaders().set(HttpHeaderName.LOCATION, "http://redirecthost/") .set(HttpHeaderName.AUTHORIZATION, "12345"); - return new MockHttpResponse(request, 308, httpHeader); + return new Response<>(request, 308, httpHeader, BinaryData.empty()); } else { - return new MockHttpResponse(request, 200); + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); } }); HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(httpClient) - .policies(new HttpRedirectPolicy(DEFAULT_REDIRECT_STRATEGY)) + .addPolicy(new HttpRedirectPolicy(DEFAULT_REDIRECT_STRATEGY)) .build(); try (Response response = sendRequest(pipeline, HttpMethod.GET)) { @@ -326,36 +318,37 @@ public void redirectOptionsCanConfigureStatusCodeRedirectLogic() throws IOExcept AtomicInteger attemptCount = new AtomicInteger(); HttpPipeline pipeline - = new HttpPipelineBuilder().policies(new HttpRedirectPolicy(httpRedirectOptions)).httpClient(request -> { + = new HttpPipelineBuilder().addPolicy(new HttpRedirectPolicy(httpRedirectOptions)).httpClient(request -> { int count = attemptCount.getAndIncrement(); if (count == 0) { - return new MockHttpResponse(request, 429, - new HttpHeaders().add(HttpHeaderName.LOCATION, "http://localhost.com")); + return new Response<>(request, 429, + new HttpHeaders().add(HttpHeaderName.LOCATION, "http://localhost.com"), BinaryData.empty()); } else { - return new MockHttpResponse(request, 200); + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); } }).build(); - try (Response response = pipeline.send(new HttpRequest(HttpMethod.GET, "http://localhost/"))) { + try (Response response + = pipeline.send(new HttpRequest().setMethod(HttpMethod.GET).setUri("http://localhost/"))) { assertEquals(200, response.getStatusCode()); assertEquals(2, attemptCount.get()); } } private Response sendRequest(HttpPipeline pipeline, HttpMethod httpMethod) { - return pipeline.send(new HttpRequest(httpMethod, URI.create("http://localhost/"))); + return pipeline.send(new HttpRequest().setMethod(httpMethod).setUri(URI.create("http://localhost/"))); } static class RecordingHttpClient implements HttpClient { private final AtomicInteger count = new AtomicInteger(); - private final Function> handler; + private final Function> handler; - RecordingHttpClient(Function> handler) { + RecordingHttpClient(Function> handler) { this.handler = handler; } @Override - public Response send(HttpRequest httpRequest) { + public Response send(HttpRequest httpRequest) { count.getAndIncrement(); return handler.apply(httpRequest); diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/RequestIdPolicyTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/RequestIdPolicyTests.java new file mode 100644 index 000000000000..7d97ff0e2ec3 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/RequestIdPolicyTests.java @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.http.pipeline; + +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpHeaders; +import io.clientcore.core.http.models.HttpMethod; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.models.binarydata.BinaryData; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.time.Duration; +import java.util.concurrent.atomic.AtomicReference; + +public class RequestIdPolicyTests { + private static final HttpHeaderName REQUEST_ID_HEADER = HttpHeaderName.fromString("request-id"); + + @Test + public void newRequestIdForEachCall() throws IOException { + AtomicReference previousRequestId = new AtomicReference<>(); + HttpPipeline pipeline + = new HttpPipelineBuilder().addPolicy(new RequestIdPolicy(REQUEST_ID_HEADER)).httpClient(request -> { + String lastRequestId = previousRequestId.get(); + if (lastRequestId != null) { + String newRequestId = request.getHeaders().getValue(REQUEST_ID_HEADER); + Assertions.assertNotNull(newRequestId); + Assertions.assertNotEquals(newRequestId, lastRequestId); + } + + String newRequestId = request.getHeaders().getValue(REQUEST_ID_HEADER); + previousRequestId.set(newRequestId); + if (newRequestId == null) { + Assertions.fail(); + } + + return new Response<>(request, 500, new HttpHeaders(), BinaryData.empty()); + }).build(); + + try (Response response + = pipeline.send(new HttpRequest().setMethod(HttpMethod.GET).setUri("https://test.com"))) { + Assertions.assertEquals(500, response.getStatusCode()); + } + + try (Response response + = pipeline.send(new HttpRequest().setMethod(HttpMethod.GET).setUri("https://test.com"))) { + Assertions.assertEquals(500, response.getStatusCode()); + } + } + + @Test + public void sameRequestIdForRetry() throws IOException { + AtomicReference previousRequestId = new AtomicReference<>(); + HttpPipeline pipeline + = new HttpPipelineBuilder().addPolicy(new HttpRetryPolicy(new HttpRetryOptions(3, Duration.ofSeconds(0)))) + .addPolicy(new RequestIdPolicy(REQUEST_ID_HEADER)) + .httpClient(request -> { + String lastRequestId = previousRequestId.get(); + if (lastRequestId != null) { + String newRequestId = request.getHeaders().getValue(REQUEST_ID_HEADER); + Assertions.assertNotNull(newRequestId); + Assertions.assertEquals(newRequestId, lastRequestId); + } + + String newRequestId = request.getHeaders().getValue(REQUEST_ID_HEADER); + previousRequestId.set(newRequestId); + if (newRequestId == null) { + Assertions.fail(); + } + + return new Response<>(request, 500, new HttpHeaders(), BinaryData.empty()); + }) + .build(); + + try (Response response + = pipeline.send(new HttpRequest().setMethod(HttpMethod.GET).setUri("https://test.com"))) { + Assertions.assertEquals(500, response.getStatusCode()); + } + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/RetryPolicyTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/RetryPolicyTests.java index 93399703b634..9c1aa8a110b4 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/RetryPolicyTests.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/RetryPolicyTests.java @@ -3,16 +3,14 @@ package io.clientcore.core.http.pipeline; -import io.clientcore.core.http.MockHttpResponse; -import io.clientcore.core.http.NoOpHttpClient; import io.clientcore.core.http.client.HttpClient; import io.clientcore.core.http.models.HttpHeaderName; import io.clientcore.core.http.models.HttpHeaders; import io.clientcore.core.http.models.HttpMethod; import io.clientcore.core.http.models.HttpRequest; -import io.clientcore.core.http.models.HttpRetryOptions; import io.clientcore.core.http.models.Response; -import io.clientcore.core.implementation.util.DateTimeRfc1123; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.utils.DateTimeRfc1123; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -45,22 +43,18 @@ public class RetryPolicyTests { @ValueSource(ints = { 408, 500, 502, 503 }) public void defaultRetryPolicyRetriesExpectedErrorCodes(int returnCode) throws IOException { AtomicInteger attemptCount = new AtomicInteger(); - HttpPipeline pipeline - = new HttpPipelineBuilder().policies(new HttpRetryPolicy()).httpClient(new NoOpHttpClient() { - @Override - public Response send(HttpRequest request) { - int count = attemptCount.getAndIncrement(); - - if (count == 0) { - return new MockHttpResponse(request, returnCode); - } else if (count == 1) { - return new MockHttpResponse(request, 200); - } else { - // Too many requests have been made. - return new MockHttpResponse(request, 400); - } - } - }).build(); + HttpPipeline pipeline = new HttpPipelineBuilder().addPolicy(new HttpRetryPolicy()).httpClient(request -> { + int count = attemptCount.getAndIncrement(); + + if (count == 0) { + return new Response<>(request, returnCode, new HttpHeaders(), BinaryData.empty()); + } else if (count == 1) { + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); + } else { + // Too many requests have been made. + return new Response<>(request, 400, new HttpHeaders(), BinaryData.empty()); + } + }).build(); try (Response response = sendRequest(pipeline)) { assertEquals(200, response.getStatusCode()); @@ -71,20 +65,15 @@ public Response send(HttpRequest request) { @ValueSource(ints = { 400, 401, 402, 403, 404, 409, 412, 501, 505 }) public void defaultRetryPolicyDoesntRetryOnErrorCodes(int returnCode) throws IOException { AtomicInteger attemptCount = new AtomicInteger(); - HttpPipeline pipeline - = new HttpPipelineBuilder().policies(new HttpRetryPolicy()).httpClient(new NoOpHttpClient() { + HttpPipeline pipeline = new HttpPipelineBuilder().addPolicy(new HttpRetryPolicy()).httpClient(request -> { + int count = attemptCount.getAndIncrement(); - @Override - public Response send(HttpRequest request) { - int count = attemptCount.getAndIncrement(); - - if (count == 0) { - return new MockHttpResponse(request, returnCode); - } else { - return new MockHttpResponse(request, 200); - } - } - }).build(); + if (count == 0) { + return new Response<>(request, returnCode, new HttpHeaders(), BinaryData.empty()); + } else { + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); + } + }).build(); try (Response response = sendRequest(pipeline)) { assertEquals(returnCode, response.getStatusCode()); @@ -94,23 +83,19 @@ public Response send(HttpRequest request) { @Test public void defaultRetryPolicyRetriesIOException() throws IOException { AtomicInteger attemptCount = new AtomicInteger(); - HttpPipeline pipeline - = new HttpPipelineBuilder().policies(new HttpRetryPolicy()).httpClient(new NoOpHttpClient() { - @Override - public Response send(HttpRequest request) { - int count = attemptCount.getAndIncrement(); - - if (count == 0) { - try { - throw new IOException(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } else { - return new MockHttpResponse(request, 200); - } + HttpPipeline pipeline = new HttpPipelineBuilder().addPolicy(new HttpRetryPolicy()).httpClient(request -> { + int count = attemptCount.getAndIncrement(); + + if (count == 0) { + try { + throw new IOException(); + } catch (IOException e) { + throw new RuntimeException(e); } - }).build(); + } else { + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); + } + }).build(); try (Response response = sendRequest(pipeline)) { assertEquals(200, response.getStatusCode()); @@ -122,14 +107,10 @@ public Response send(HttpRequest request) { public void customRetryPolicyCanDetermineRetryStatusCodes(HttpRetryOptions retryOptions, int[] statusCodes, int expectedStatusCode) throws IOException { AtomicInteger attempt = new AtomicInteger(); - HttpPipeline pipeline - = new HttpPipelineBuilder().policies(new HttpRetryPolicy(retryOptions)).httpClient(new NoOpHttpClient() { - - @Override - public Response send(HttpRequest request) { - return new MockHttpResponse(request, statusCodes[attempt.getAndIncrement()]); - } - }).build(); + HttpPipeline pipeline = new HttpPipelineBuilder().addPolicy(new HttpRetryPolicy(retryOptions)) + .httpClient(request -> new Response<>(request, statusCodes[attempt.getAndIncrement()], new HttpHeaders(), + BinaryData.empty())) + .build(); try (Response response = sendRequest(pipeline)) { assertEquals(expectedStatusCode, response.getStatusCode()); @@ -139,15 +120,15 @@ public Response send(HttpRequest request) { @Test public void retryMax() throws IOException { final int maxRetries = 5; - final HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(new NoOpHttpClient() { + final HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(new HttpClient() { int count = -1; @Override - public Response send(HttpRequest request) { + public Response send(HttpRequest request) { Assertions.assertTrue(count++ < maxRetries); - return new MockHttpResponse(request, 500); + return new Response<>(request, 500, new HttpHeaders(), BinaryData.empty()); } - }).policies(new HttpRetryPolicy(new HttpRetryOptions(5, Duration.ofMillis(1)))).build(); + }).addPolicy(new HttpRetryPolicy(new HttpRetryOptions(5, Duration.ofMillis(1)))).build(); try (Response response = sendRequest(pipeline)) { assertEquals(500, response.getStatusCode()); @@ -158,7 +139,7 @@ public Response send(HttpRequest request) { public void fixedDelayRetry() throws IOException { final int maxRetries = 5; final long delayMillis = 500; - final HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(new NoOpHttpClient() { + final HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(new HttpClient() { int count = -1; long previousAttemptMadeAt = -1; @@ -173,11 +154,11 @@ private void beforeSendingRequest() { } @Override - public Response send(HttpRequest request) { + public Response send(HttpRequest request) { beforeSendingRequest(); - return new MockHttpResponse(request, 500); + return new Response<>(request, 500, new HttpHeaders(), BinaryData.empty()); } - }).policies(new HttpRetryPolicy(new HttpRetryOptions(5, Duration.ofMillis(delayMillis)))).build(); + }).addPolicy(new HttpRetryPolicy(new HttpRetryOptions(5, Duration.ofMillis(delayMillis)))).build(); try (Response response = sendRequest(pipeline)) { assertEquals(500, response.getStatusCode()); @@ -191,7 +172,7 @@ public void exponentialDelayRetry() throws IOException { final long maxDelayMillis = 1000; HttpRetryOptions exponentialBackoff = new HttpRetryOptions(5, Duration.ofMillis(baseDelayMillis), Duration.ofMillis(maxDelayMillis)); - final HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(new NoOpHttpClient() { + final HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(new HttpClient() { int count = -1; long previousAttemptMadeAt = -1; @@ -209,12 +190,12 @@ private void beforeSendingRequest() { } @Override - public Response send(HttpRequest request) { + public Response send(HttpRequest request) { beforeSendingRequest(); - return new MockHttpResponse(request, 503); + return new Response<>(request, 503, new HttpHeaders(), BinaryData.empty()); } - }).policies(new HttpRetryPolicy(exponentialBackoff)).build(); + }).addPolicy(new HttpRetryPolicy(exponentialBackoff)).build(); try (Response response = sendRequest(pipeline)) { assertEquals(503, response.getStatusCode()); @@ -224,18 +205,19 @@ public Response send(HttpRequest request) { @Test public void retryConsumesBody() throws IOException { AtomicInteger closeCalls = new AtomicInteger(); - Response closeTrackingHttpResponse = new MockHttpResponse(null, 503, new HttpHeaders()) { - @Override - public void close() throws IOException { - closeCalls.incrementAndGet(); - super.close(); - } - }; + Response closeTrackingHttpResponse + = new Response(null, 503, new HttpHeaders(), BinaryData.empty()) { + @Override + public void close() throws IOException { + closeCalls.incrementAndGet(); + super.close(); + } + }; HttpClient httpClient = request -> closeTrackingHttpResponse; final HttpPipeline pipeline - = new HttpPipelineBuilder().policies(new HttpRetryPolicy(new HttpRetryOptions(2, Duration.ofMillis(1)))) + = new HttpPipelineBuilder().addPolicy(new HttpRetryPolicy(new HttpRetryOptions(2, Duration.ofMillis(1)))) .httpClient(httpClient) .build(); @@ -253,7 +235,7 @@ public void propagatingExceptionHasOtherErrorsAsSuppressedExceptions() { }; final HttpPipeline pipeline - = new HttpPipelineBuilder().policies(new HttpRetryPolicy(new HttpRetryOptions(2, Duration.ofMillis(1)))) + = new HttpPipelineBuilder().addPolicy(new HttpRetryPolicy(new HttpRetryOptions(2, Duration.ofMillis(1)))) .httpClient(httpClient) .build(); @@ -284,16 +266,17 @@ public void retryWellKnownRetryHeaders(HttpHeaders responseHeaders) throws IOExc AtomicInteger attemptCount = new AtomicInteger(); HttpPipeline pipeline - = new HttpPipelineBuilder().policies(new HttpRetryPolicy(retryOptions)).httpClient(request -> { + = new HttpPipelineBuilder().addPolicy(new HttpRetryPolicy(retryOptions)).httpClient(request -> { int count = attemptCount.getAndIncrement(); if (count == 0) { - return new MockHttpResponse(request, 503, responseHeaders); + return new Response<>(request, 503, responseHeaders, BinaryData.empty()); } else { - return new MockHttpResponse(request, 200); + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); } }).build(); - try (Response response = pipeline.send(new HttpRequest(HttpMethod.GET, "http://localhost/"))) { + try (Response response + = pipeline.send(new HttpRequest().setMethod(HttpMethod.GET).setUri("http://localhost/"))) { assertEquals(200, response.getStatusCode()); assertEquals(2, attemptCount.get()); } @@ -307,16 +290,17 @@ public void retryOptionsCanConfigureHttpResponseRetryLogic() throws IOException AtomicInteger attemptCount = new AtomicInteger(); HttpPipeline pipeline - = new HttpPipelineBuilder().policies(new HttpRetryPolicy(retryOptions)).httpClient(request -> { + = new HttpPipelineBuilder().addPolicy(new HttpRetryPolicy(retryOptions)).httpClient(request -> { int count = attemptCount.getAndIncrement(); if (count == 0) { - return new MockHttpResponse(request, 503); + return new Response<>(request, 503, new HttpHeaders(), BinaryData.empty()); } else { - return new MockHttpResponse(request, 200); + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); } }).build(); - try (Response response = pipeline.send(new HttpRequest(HttpMethod.GET, "http://localhost/"))) { + try (Response response + = pipeline.send(new HttpRequest().setMethod(HttpMethod.GET).setUri("http://localhost/"))) { assertEquals(503, response.getStatusCode()); assertEquals(1, attemptCount.get()); } @@ -330,17 +314,17 @@ public void retryOptionsCanConfigureThrowableRetryLogic() { AtomicInteger attemptCount = new AtomicInteger(); HttpPipeline pipeline - = new HttpPipelineBuilder().policies(new HttpRetryPolicy(retryOptions)).httpClient(request -> { + = new HttpPipelineBuilder().addPolicy(new HttpRetryPolicy(retryOptions)).httpClient(request -> { int count = attemptCount.getAndIncrement(); if (count == 0) { throw new UncheckedIOException(new IOException()); } else { - return new MockHttpResponse(request, 200); + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); } }).build(); assertThrows(UncheckedIOException.class, - () -> pipeline.send(new HttpRequest(HttpMethod.GET, "http://localhost/")).close()); + () -> pipeline.send(new HttpRequest().setMethod(HttpMethod.GET).setUri("http://localhost/")).close()); } @Test @@ -353,16 +337,17 @@ public void retryOptionsCanConfigureRetryHeaders() throws IOException { AtomicInteger attemptCount = new AtomicInteger(); HttpPipeline pipeline - = new HttpPipelineBuilder().policies(new HttpRetryPolicy(retryOptions)).httpClient(request -> { + = new HttpPipelineBuilder().addPolicy(new HttpRetryPolicy(retryOptions)).httpClient(request -> { int count = attemptCount.getAndIncrement(); if (count == 0) { - return new MockHttpResponse(request, 503, headers); + return new Response<>(request, 503, headers, BinaryData.empty()); } else { - return new MockHttpResponse(request, 200); + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); } }).build(); - try (Response response = pipeline.send(new HttpRequest(HttpMethod.GET, "http://localhost/"))) { + try (Response response + = pipeline.send(new HttpRequest().setMethod(HttpMethod.GET).setUri("http://localhost/"))) { assertEquals(200, response.getStatusCode()); assertEquals(2, attemptCount.get()); } @@ -386,7 +371,7 @@ static Stream customRetryPolicyCanDetermineRetryStatusCodesSupplier() } static Response sendRequest(HttpPipeline pipeline) { - return pipeline.send(new HttpRequest(HttpMethod.GET, "http://localhost/")); + return pipeline.send(new HttpRequest().setMethod(HttpMethod.GET).setUri("http://localhost/")); } static HttpRetryOptions createStatusCodeRetryStrategy(int... retriableErrorCodes) { diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/SetDatePolicyTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/SetDatePolicyTests.java new file mode 100644 index 000000000000..bbf3f7092ff1 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/SetDatePolicyTests.java @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.http.pipeline; + +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpHeaders; +import io.clientcore.core.http.models.HttpMethod; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.models.binarydata.BinaryData; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.time.Duration; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +/** + * Unit tests for {@link SetDatePolicy}. + */ +public class SetDatePolicyTests { + @Test + public void dateIsRefreshedOnRetry() throws IOException { + try (Response response + = getPipeline().send(new HttpRequest().setMethod(HttpMethod.GET).setUri("https://azure.com"))) { + assertEquals(200, response.getStatusCode()); + } + } + + private static HttpPipeline getPipeline() { + AtomicReference firstDate = new AtomicReference<>(); + + return new HttpPipelineBuilder().addPolicy(new HttpRetryPolicy(new HttpRetryOptions(1, Duration.ofSeconds(2)))) + .addPolicy(new SetDatePolicy()) + .httpClient(request -> { + String date = request.getHeaders().getValue(HttpHeaderName.DATE); + if (!firstDate.compareAndSet(null, date)) { + assertNotEquals(firstDate.get(), date); + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); + } else { + return new Response<>(request, 429, new HttpHeaders(), BinaryData.empty()); + } + }) + .build(); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/SetUserAgentPolicyTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/SetUserAgentPolicyTests.java new file mode 100644 index 000000000000..b65d389e9faa --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/http/pipeline/SetUserAgentPolicyTests.java @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.http.pipeline; + +import io.clientcore.core.http.client.HttpClient; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpHeaders; +import io.clientcore.core.http.models.HttpMethod; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.utils.configuration.Configuration; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.time.Duration; +import java.util.function.Consumer; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Contains tests for {@link UserAgentPolicy}. + */ +public class SetUserAgentPolicyTests { + @ParameterizedTest(name = "{displayName} [{index}]") + @MethodSource("userAgentAndExpectedSupplier") + public void validateUserAgentPolicyHandling(UserAgentPolicy userAgentPolicy, String expected) throws IOException { + HttpPipeline pipeline = new HttpPipelineBuilder() + .httpClient(new ValidationHttpClient( + request -> assertEquals(expected, request.getHeaders().getValue(HttpHeaderName.USER_AGENT)))) + .addPolicy(userAgentPolicy) + .build(); + + try (Response response + = pipeline.send(new HttpRequest().setMethod(HttpMethod.GET).setUri("http://localhost"))) { + assertEquals(200, response.getStatusCode()); + } + } + + /** + * Tests that applying the {@link UserAgentPolicy} after a {@link HttpRetryPolicy} doesn't result in the + * User-Agent header being applied multiple times. + */ + @ParameterizedTest(name = "{displayName} [{index}]") + @MethodSource("userAgentAndExpectedSupplier") + public void userAgentPolicyAfterRetryPolicy(UserAgentPolicy userAgentPolicy, String expected) throws IOException { + HttpPipeline pipeline = new HttpPipelineBuilder() + .httpClient(new RetryValidationHttpClient( + request -> assertEquals(expected, request.getHeaders().getValue(HttpHeaderName.USER_AGENT)))) + .addPolicy(new HttpRetryPolicy(new HttpRetryOptions(5, Duration.ofMillis(10)))) + .addPolicy(userAgentPolicy) + .build(); + + try (Response response + = pipeline.send(new HttpRequest().setMethod(HttpMethod.GET).setUri("http://localhost"))) { + assertEquals(200, response.getStatusCode()); + } + } + + /** + * Tests that applying multiple {@link UserAgentPolicy} doesn't result in the User-Agent header being applied + * multiple times. + */ + @ParameterizedTest(name = "{displayName} [{index}]") + @MethodSource("userAgentAndExpectedSupplier") + public void multipleUserAgentPolicies(UserAgentPolicy userAgentPolicy, String expected) throws IOException { + HttpPipeline pipeline = new HttpPipelineBuilder() + .httpClient(new ValidationHttpClient( + request -> assertEquals(expected, request.getHeaders().getValue(HttpHeaderName.USER_AGENT)))) + .addPolicy(userAgentPolicy) + .addPolicy(userAgentPolicy) + .build(); + + try (Response response + = pipeline.send(new HttpRequest().setMethod(HttpMethod.GET).setUri("http://localhost"))) { + assertEquals(200, response.getStatusCode()); + } + } + + private static Stream userAgentAndExpectedSupplier() { + String defaultUserAgent = UserAgentPolicy.DEFAULT_USER_AGENT_HEADER; + String sdkName = "sdkName"; + String sdkVersion = "sdkVersion"; + String baseUserAgent = String.format("%s-%s/%s", defaultUserAgent, sdkName, sdkVersion); + String applicationId = "applicationId"; + String platformInfo = String.format("%s; %s; %s", Configuration.getGlobalConfiguration().get("java.version"), + Configuration.getGlobalConfiguration().get("os.name"), + Configuration.getGlobalConfiguration().get("os.version")); + + return Stream.of( + // Tests using the default User-Agent + Arguments.of(new UserAgentPolicy(), defaultUserAgent), + + // Tests using a simple custom User-Agent + Arguments.of(new UserAgentPolicy("AutoRest-Java"), "AutoRest-Java"), + + // Tests using SDK name and version with platform information and without application ID + Arguments.of(new UserAgentPolicy(null, sdkName, sdkVersion), + String.format("%s (%s)", baseUserAgent, platformInfo)), + + // Tests using SDK name and version with platform information and application ID + Arguments.of(new UserAgentPolicy(applicationId, sdkName, sdkVersion), + String.format("%s %s (%s)", applicationId, baseUserAgent, platformInfo))); + } + + /* + * Simple helper class which implements {@link HttpClient} and applies a validation method to the request sent + * by the client. + */ + private static class ValidationHttpClient implements HttpClient { + private final Consumer validator; + + ValidationHttpClient(Consumer validator) { + this.validator = validator; + } + + @Override + public Response send(HttpRequest request) { + validator.accept(request); + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); + } + } + + private static class RetryValidationHttpClient implements HttpClient { + private final Consumer validator; + private int retryCount = 0; + + RetryValidationHttpClient(Consumer validator) { + this.validator = validator; + } + + @Override + public Response send(HttpRequest request) throws IOException { + if (retryCount < 5) { + retryCount++; + throw new IOException("Activating retry policy"); + } + + validator.accept(request); + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); + } + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/client/HttpClientProvidersIT.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/client/HttpClientProvidersIT.java new file mode 100644 index 000000000000..13d2e38b0cec --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/client/HttpClientProvidersIT.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.implementation.http.client; + +import io.clientcore.core.http.client.HttpClient; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledForJreRange; +import org.junit.jupiter.api.condition.JRE; + +import static org.junit.jupiter.api.Assertions.assertInstanceOf; + +/** + * Tests for the {@link HttpClient} class. + *

        + * Now that the default HttpClient, and related code, are using multi-release JARs this must be an integration test as + * the full JAR must be available to use the multi-release code. + */ +@DisabledForJreRange(max = JRE.JAVA_11) +public class HttpClientProvidersIT { + @Test + public void testNoProvider() { + HttpClient httpClient = HttpClient.getSharedInstance(); + + assertInstanceOf(JdkHttpClient.class, httpClient); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/client/JdkHttpClientIT.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/client/JdkHttpClientIT.java new file mode 100644 index 000000000000..ac2b57e73269 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/client/JdkHttpClientIT.java @@ -0,0 +1,303 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.implementation.http.client; + +import io.clientcore.core.http.client.HttpClient; +import io.clientcore.core.http.client.JdkHttpClientBuilder; +import io.clientcore.core.http.models.HttpHeader; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpHeaders; +import io.clientcore.core.http.models.HttpMethod; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.RequestOptions; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.implementation.http.ContentType; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.shared.InsecureTrustManager; +import io.clientcore.core.shared.LocalTestServer; +import io.clientcore.core.utils.Context; +import io.clientcore.core.utils.TestUtils; +import org.conscrypt.Conscrypt; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledForJreRange; +import org.junit.jupiter.api.condition.JRE; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.servlet.ServletException; +import java.io.IOException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.TimeUnit; + +import static io.clientcore.core.utils.TestUtils.assertArraysEqual; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Tests for {@link JdkHttpClient}. + *

        + * Now that the default HttpClient, and related code, are using multi-release JARs this must be an integration test as + * the full JAR must be available to use the multi-release code. + */ +@DisabledForJreRange(max = JRE.JAVA_11) +@Execution(ExecutionMode.SAME_THREAD) +public class JdkHttpClientIT { + static final String RETURN_HEADERS_AS_IS_PATH = "/returnHeadersAsIs"; + private static final byte[] SHORT_BODY = "hi there".getBytes(StandardCharsets.UTF_8); + private static final byte[] LONG_BODY = createLongBody(); + private static LocalTestServer server; + private static final String SSE_RESPONSE = "/serversentevent"; + + @BeforeAll + public static void startTestServer() { + server = new LocalTestServer((req, resp, requestBody) -> { + String path = req.getServletPath(); + boolean get = "GET".equalsIgnoreCase(req.getMethod()); + boolean post = "POST".equalsIgnoreCase(req.getMethod()); + boolean put = "PUT".equalsIgnoreCase(req.getMethod()); + + if (get && "/short".equals(path)) { + resp.setContentType("application/octet-stream"); + resp.setContentLength(SHORT_BODY.length); + resp.getOutputStream().write(SHORT_BODY); + } else if (get && "/long".equals(path)) { + resp.setContentType("application/octet-stream"); + resp.setContentLength(LONG_BODY.length); + resp.getOutputStream().write(LONG_BODY); + } else if (get && "/error".equals(path)) { + resp.setStatus(500); + resp.setContentLength(5); + resp.getOutputStream().write("error".getBytes(StandardCharsets.UTF_8)); + } else if (post && "/shortPost".equals(path)) { + resp.setContentType("application/octet-stream"); + resp.setContentLength(SHORT_BODY.length); + resp.getOutputStream().write(SHORT_BODY); + } else if (get && RETURN_HEADERS_AS_IS_PATH.equals(path)) { + List headerNames = Collections.list(req.getHeaderNames()); + headerNames.forEach(headerName -> { + List headerValues = Collections.list(req.getHeaders(headerName)); + headerValues.forEach(headerValue -> resp.addHeader(headerName, headerValue)); + }); + } else if (get && "/empty".equals(path)) { + resp.setContentType("application/octet-stream"); + resp.setContentLength(0); + } else if (get && "/connectionClose".equals(path)) { + resp.getHttpChannel().getConnection().close(); + } else if (get && SSE_RESPONSE.equals(path)) { + if (req.getHeader("Last-Event-Id") != null) { + sendSSELastEventIdResponse(resp); + } else { + sendSSEResponseWithRetry(resp); + } + } else if (post && SSE_RESPONSE.equals(path)) { + sendSSEResponseWithDataOnly(resp); + } else if (put && SSE_RESPONSE.equals(path)) { + resp.addHeader("Content-Type", ContentType.TEXT_EVENT_STREAM); + resp.setStatus(200); + resp.getOutputStream().write(("msg hello world \n\n").getBytes()); + resp.flushBuffer(); + } else { + throw new ServletException("Unexpected request " + req.getMethod() + " " + path); + } + }); + + server.start(); + } + + private static void sendSSEResponseWithDataOnly(org.eclipse.jetty.server.Response resp) throws IOException { + resp.addHeader("Content-Type", ContentType.TEXT_EVENT_STREAM); + resp.getOutputStream().write(("data: YHOO\ndata: +2\ndata: 10\n\n").getBytes()); + resp.flushBuffer(); + } + + private static String addServerSentEventWithRetry() { + return ": test stream\ndata: first event\nid: 1\nretry: 100\n\n" + + "data: This is the second message, it\ndata: has two lines.\nid: 2\n\ndata: third event"; + } + + private static void sendSSEResponseWithRetry(org.eclipse.jetty.server.Response resp) throws IOException { + resp.addHeader("Content-Type", ContentType.TEXT_EVENT_STREAM); + resp.getOutputStream().write(addServerSentEventWithRetry().getBytes()); + resp.flushBuffer(); + } + + private static String addServerSentEventLast() { + return "data: This is the second message, it\ndata: has two lines.\nid: 2\n\ndata: third event"; + } + + private static void sendSSELastEventIdResponse(org.eclipse.jetty.server.Response resp) throws IOException { + resp.addHeader("Content-Type", ContentType.TEXT_EVENT_STREAM); + resp.getOutputStream().write(addServerSentEventLast().getBytes()); + resp.flushBuffer(); + } + + @AfterAll + public static void stopTestServer() { + if (server != null) { + server.stop(); + } + } + + @Test + public void testFlowableWhenServerReturnsBodyAndNoErrorsWhenHttp500Returned() throws IOException { + HttpClient client = new JdkHttpClientBuilder().build(); + + try (Response response = doRequest(client, "/error")) { + assertEquals(500, response.getStatusCode()); + + String responseBodyAsString = response.getValue().toString(); + + assertTrue(responseBodyAsString.contains("error")); + } + + } + + @Test + public void testConcurrentRequests() throws InterruptedException { + int numRequests = 100; // 100 = 1GB of data read + HttpClient client = new JdkHttpClientBuilder().build(); + + ForkJoinPool pool = new ForkJoinPool(); + List> requests = new ArrayList<>(numRequests); + for (int i = 0; i < numRequests; i++) { + requests.add(() -> { + try (Response response = doRequest(client, "/long")) { + byte[] body = response.getValue().toBytes(); + assertArraysEqual(LONG_BODY, body); + return null; + } + }); + } + + pool.invokeAll(requests); + pool.shutdown(); + assertTrue(pool.awaitTermination(60, TimeUnit.SECONDS)); + } + + @Test + public void validateHeadersReturnAsIs() throws IOException { + HttpClient client = new JdkHttpClientBuilder().build(); + + HttpHeaderName singleValueHeaderName = HttpHeaderName.fromString("singleValue"); + final String singleValueHeaderValue = "value"; + + HttpHeaderName multiValueHeaderName = HttpHeaderName.fromString("Multi-value"); + final List multiValueHeaderValue = Arrays.asList("value1", "value2"); + + HttpHeaders headers = new HttpHeaders().set(singleValueHeaderName, singleValueHeaderValue) + .set(multiValueHeaderName, multiValueHeaderValue); + + try (Response response = client.send(new HttpRequest().setMethod(HttpMethod.GET) + .setUri(uri(server, RETURN_HEADERS_AS_IS_PATH)) + .setHeaders(headers))) { + assertEquals(200, response.getStatusCode()); + + HttpHeaders responseHeaders = response.getHeaders(); + HttpHeader singleValueHeader = responseHeaders.get(singleValueHeaderName); + + assertEquals(singleValueHeaderName.getCaseInsensitiveName(), singleValueHeader.getName().toString()); + assertEquals(singleValueHeaderValue, singleValueHeader.getValue()); + + HttpHeader multiValueHeader = responseHeaders.get(multiValueHeaderName); + + assertEquals(multiValueHeaderName.getCaseInsensitiveName(), multiValueHeader.getName().toString()); + assertEquals(multiValueHeaderValue.size(), multiValueHeader.getValues().size()); + assertTrue(multiValueHeaderValue.containsAll(multiValueHeader.getValues())); + } + } + + @Test + public void testBufferedResponse() throws IOException { + HttpClient client = new JdkHttpClientBuilder().build(); + + try (Response response = getResponse(client, "/short", Context.none())) { + assertArraysEqual(SHORT_BODY, response.getValue().toBytes()); + } + } + + @Test + public void testEmptyBufferResponse() throws IOException { + HttpClient client = new JdkHttpClientBuilder().build(); + + try (Response response = getResponse(client, "/empty", Context.none())) { + assertEquals(0L, response.getValue().toBytes().length); + } + } + + @Test + public void testRequestBodyPost() throws IOException { + HttpClient client = new JdkHttpClientBuilder().build(); + String contentChunk = "abcdefgh"; + int repetitions = 1000; + HttpRequest request = new HttpRequest().setMethod(HttpMethod.POST).setUri(uri(server, "/shortPost")); + request.getHeaders() + .set(HttpHeaderName.CONTENT_LENGTH, String.valueOf(contentChunk.length() * (repetitions + 1))); + request.setBody(BinaryData.fromString(contentChunk)); + + try (Response response = client.send(request)) { + assertArraysEqual(SHORT_BODY, response.getValue().toBytes()); + } + } + + @Test + public void testCustomSslSocketFactory() throws IOException, GeneralSecurityException { + SSLContext sslContext = SSLContext.getInstance("TLSv1.2", Conscrypt.newProvider()); + + // Initialize the SSL context with a trust manager that trusts all certificates. + sslContext.init(null, new TrustManager[] { new InsecureTrustManager() }, null); + + HttpClient httpClient = new JdkHttpClientBuilder().sslContext(sslContext).build(); + + try (Response response + = httpClient.send(new HttpRequest().setMethod(HttpMethod.GET).setUri(httpsUri(server, "/short")))) { + TestUtils.assertArraysEqual(SHORT_BODY, response.getValue().toBytes()); + } + } + + private static Response getResponse(HttpClient client, String path, Context context) + throws IOException { + HttpRequest request = new HttpRequest().setMethod(HttpMethod.GET) + .setUri(uri(server, path)) + .setRequestOptions(new RequestOptions().setContext(context)); + + return client.send(request); + } + + static URI uri(LocalTestServer server, String path) { + return URI.create(server.getHttpUri() + path); + } + + static URI httpsUri(LocalTestServer server, String path) { + return URI.create(server.getHttpsUri() + path); + } + + private static byte[] createLongBody() { + byte[] duplicateBytes = "abcdefghijk".getBytes(StandardCharsets.UTF_8); + byte[] longBody = new byte[duplicateBytes.length * 100000]; + + for (int i = 0; i < 100000; i++) { + System.arraycopy(duplicateBytes, 0, longBody, i * duplicateBytes.length, duplicateBytes.length); + } + + return longBody; + } + + private static Response doRequest(HttpClient client, String path) throws IOException { + HttpRequest request = new HttpRequest().setMethod(HttpMethod.GET).setUri(uri(server, path)); + + return client.send(request); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/client/JdkHttpClientTestsIT.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/client/JdkHttpClientTestsIT.java new file mode 100644 index 000000000000..e67cea3de466 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/client/JdkHttpClientTestsIT.java @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.implementation.http.client; + +import io.clientcore.core.http.client.HttpClient; +import io.clientcore.core.shared.HttpClientTests; +import io.clientcore.core.shared.HttpClientTestsServer; +import io.clientcore.core.shared.LocalTestServer; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.condition.DisabledForJreRange; +import org.junit.jupiter.api.condition.JRE; + +/** + * Tests for the {@link JdkHttpClient} class. + *

        + * Now that the default HttpClient, and related code, are using multi-release JARs this must be an integration test as + * the full JAR must be available to use the multi-release code. + */ +@DisabledForJreRange(max = JRE.JAVA_11) +public class JdkHttpClientTestsIT extends HttpClientTests { + private static LocalTestServer server; + + @BeforeAll + public static void startTestServer() { + server = HttpClientTestsServer.getHttpClientTestsServer(); + server.start(); + } + + @AfterAll + public static void stopTestServer() { + if (server != null) { + server.stop(); + } + } + + @Override + protected HttpClient getHttpClient() { + return GlobalJdkHttpClient.HTTP_CLIENT.getHttpClient(); + } + + @Override + protected String getServerUri(boolean secure) { + return secure ? server.getHttpsUri() : server.getHttpUri(); + } + + @Override + protected int getPort() { + return server.getHttpPort(); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/LengthValidatingInputStreamTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/LengthValidatingInputStreamTests.java index 031e441e7c6a..487bffcd2013 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/LengthValidatingInputStreamTests.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/LengthValidatingInputStreamTests.java @@ -10,10 +10,10 @@ import java.io.ByteArrayInputStream; import java.io.InputStream; -import static io.clientcore.core.util.TestUtils.assertArraysEqual; -import static io.clientcore.core.util.TestUtils.fillArray; -import static io.clientcore.core.util.TestUtils.readStream; -import static io.clientcore.core.util.TestUtils.readStreamByteByByte; +import static io.clientcore.core.utils.TestUtils.assertArraysEqual; +import static io.clientcore.core.utils.TestUtils.fillArray; +import static io.clientcore.core.utils.TestUtils.readStream; +import static io.clientcore.core.utils.TestUtils.readStreamByteByByte; import static org.junit.jupiter.api.Assertions.assertThrows; /** diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/RequestOptionsTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/RequestOptionsTests.java index a526554d1d8d..a8d5ffaf3565 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/RequestOptionsTests.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/RequestOptionsTests.java @@ -9,7 +9,7 @@ import io.clientcore.core.http.models.HttpMethod; import io.clientcore.core.http.models.HttpRequest; import io.clientcore.core.http.models.RequestOptions; -import io.clientcore.core.util.binarydata.BinaryData; +import io.clientcore.core.models.binarydata.BinaryData; import org.junit.jupiter.api.Test; import java.net.URI; @@ -23,7 +23,8 @@ public class RequestOptionsTests { @Test public void addQueryParam() { - final HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://request.uri")); + final HttpRequest request + = new HttpRequest().setMethod(HttpMethod.POST).setUri(URI.create("http://request.uri")); RequestOptions options = new RequestOptions().addQueryParam("foo", "bar").addQueryParam("$skipToken", "1"); @@ -34,7 +35,8 @@ public void addQueryParam() { @Test public void addHeader() { - final HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://request.uri")); + final HttpRequest request + = new HttpRequest().setMethod(HttpMethod.POST).setUri(URI.create("http://request.uri")); RequestOptions options = new RequestOptions().addHeader(new HttpHeader(X_MS_FOO, "bar")) .addHeader(new HttpHeader(HttpHeaderName.CONTENT_TYPE, "application/json")); @@ -47,7 +49,8 @@ public void addHeader() { @Test public void setBody() { - final HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://request.uri")); + final HttpRequest request + = new HttpRequest().setMethod(HttpMethod.POST).setUri(URI.create("http://request.uri")); String expected = "{\"id\":\"123\"}"; @@ -62,10 +65,11 @@ public void setBody() { @Test public void addRequestCallback() { - final HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://request.uri")); + final HttpRequest request + = new HttpRequest().setMethod(HttpMethod.POST).setUri(URI.create("http://request.uri")); RequestOptions options = new RequestOptions().addHeader(new HttpHeader(X_MS_FOO, "bar")) - .addRequestCallback(r -> r.setHttpMethod(HttpMethod.GET)) + .addRequestCallback(r -> r.setMethod(HttpMethod.GET)) .addRequestCallback(r -> r.setUri("https://request.uri")) .addQueryParam("$skipToken", "1") .addRequestCallback(r -> r.getHeaders().set(X_MS_FOO, "baz")); diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/ResponseConstructorsCacheBenchMarkTestData.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/ResponseConstructorsCacheBenchMarkTestData.java index 07445e1ac15b..6d56dc42e6f0 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/ResponseConstructorsCacheBenchMarkTestData.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/ResponseConstructorsCacheBenchMarkTestData.java @@ -3,17 +3,14 @@ package io.clientcore.core.implementation.http.rest; -import io.clientcore.core.http.MockHttpResponse; import io.clientcore.core.http.models.HttpHeaderName; import io.clientcore.core.http.models.HttpHeaders; import io.clientcore.core.http.models.HttpMethod; import io.clientcore.core.http.models.HttpRequest; -import io.clientcore.core.http.models.HttpResponse; import io.clientcore.core.http.models.Response; -import io.clientcore.core.implementation.util.UriBuilder; -import io.clientcore.core.util.binarydata.BinaryData; -import io.clientcore.core.implementation.util.JsonSerializer; -import io.clientcore.core.util.serializer.ObjectSerializer; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.serialization.json.JsonSerializer; +import io.clientcore.core.utils.UriBuilder; import java.io.IOException; import java.io.UncheckedIOException; @@ -51,14 +48,14 @@ public String getCustomHdr() { } // 1. final VoidResponse (Ctr_args: 3) - public static final class VoidResponse extends HttpResponse { + public static final class VoidResponse extends Response { VoidResponse(HttpRequest request, int statusCode, HttpHeaders headers, Void value) { super(request, statusCode, headers, value); } } // 2. HttpResponse Type (Ctr_args: 4) - public static final class FooSimpleResponse extends HttpResponse { + public static final class FooSimpleResponse extends Response { FooSimpleResponse(HttpRequest request, int statusCode, HttpHeaders headers, Foo value) { super(request, statusCode, headers, value); } @@ -71,8 +68,8 @@ public interface FooService { FooSimpleResponse getFooSimpleResponse(); } - private static final ObjectSerializer SERIALIZER = new JsonSerializer(); - private static final HttpRequest HTTP_REQUEST = new HttpRequest(HttpMethod.GET, createUri()); + private static final JsonSerializer SERIALIZER = new JsonSerializer(); + private static final HttpRequest HTTP_REQUEST = new HttpRequest().setMethod(HttpMethod.GET).setUri(createUri()); private static final HttpHeaderName HELLO = HttpHeaderName.fromString("hello"); private static final HttpHeaders RESPONSE_HEADERS = new HttpHeaders().set(HELLO, "world"); private static final int RESPONSE_STATUS_CODE = 200; @@ -80,9 +77,9 @@ public interface FooService { private static final byte[] FOO_BYTE_ARRAY = asJsonByteArray(FOO); // MOCK RESPONSES private static final Response VOID_RESPONSE - = new MockHttpResponse(HTTP_REQUEST, RESPONSE_STATUS_CODE, RESPONSE_HEADERS, null); - private static final Response FOO_RESPONSE = new MockHttpResponse(HTTP_REQUEST, RESPONSE_STATUS_CODE, - RESPONSE_HEADERS, BinaryData.fromBytes(FOO_BYTE_ARRAY)); + = new Response<>(HTTP_REQUEST, RESPONSE_STATUS_CODE, RESPONSE_HEADERS, null); + private static final Response FOO_RESPONSE + = new Response<>(HTTP_REQUEST, RESPONSE_STATUS_CODE, RESPONSE_HEADERS, BinaryData.fromBytes(FOO_BYTE_ARRAY)); // ARRAY HOLDING TEST DATA private final Input[] inputs; diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/RestProxyImplTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/RestProxyImplTests.java index 692d6d36f80f..f3c9978b78fa 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/RestProxyImplTests.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/RestProxyImplTests.java @@ -3,22 +3,22 @@ package io.clientcore.core.implementation.http.rest; -import io.clientcore.core.annotation.ServiceInterface; -import io.clientcore.core.http.MockHttpResponse; +import io.clientcore.core.annotations.ServiceInterface; import io.clientcore.core.http.RestProxy; -import io.clientcore.core.http.annotation.BodyParam; -import io.clientcore.core.http.annotation.HeaderParam; -import io.clientcore.core.http.annotation.HttpRequestInformation; +import io.clientcore.core.http.annotations.BodyParam; +import io.clientcore.core.http.annotations.HeaderParam; +import io.clientcore.core.http.annotations.HttpRequestInformation; import io.clientcore.core.http.client.HttpClient; import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpHeaders; import io.clientcore.core.http.models.HttpMethod; import io.clientcore.core.http.models.HttpRequest; import io.clientcore.core.http.models.Response; import io.clientcore.core.http.pipeline.HttpPipeline; import io.clientcore.core.http.pipeline.HttpPipelineBuilder; -import io.clientcore.core.implementation.util.JsonSerializer; -import io.clientcore.core.util.Context; -import io.clientcore.core.util.binarydata.BinaryData; +import io.clientcore.core.serialization.json.JsonSerializer; +import io.clientcore.core.utils.Context; +import io.clientcore.core.models.binarydata.BinaryData; import org.junit.jupiter.api.Named; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -33,7 +33,7 @@ import java.nio.file.Path; import java.util.stream.Stream; -import static io.clientcore.core.util.TestUtils.assertArraysEqual; +import static io.clientcore.core.utils.TestUtils.assertArraysEqual; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; @@ -86,7 +86,7 @@ private static final class LocalHttpClient implements HttpClient { private volatile boolean lastResponseClosed; @Override - public Response send(HttpRequest request) { + public Response send(HttpRequest request) { boolean success = request.getUri().getPath().equals("/my/uri/path"); if (request.getHttpMethod().equals(HttpMethod.POST)) { @@ -95,7 +95,7 @@ public Response send(HttpRequest request) { success &= request.getHttpMethod().equals(HttpMethod.GET); } - return new MockHttpResponse(request, success ? 200 : 400) { + return new Response(request, success ? 200 : 400, new HttpHeaders(), BinaryData.empty()) { @Override public void close() throws IOException { lastResponseClosed = true; @@ -121,7 +121,7 @@ public static Stream expectedBodyLengthDataProvider() throws Exceptio @Test public void emptyRequestBody() { - HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, "http://localhost"); + HttpRequest httpRequest = new HttpRequest().setMethod(HttpMethod.GET).setUri("http://localhost"); assertNull(RestProxyImpl.validateLength(httpRequest)); } @@ -150,8 +150,9 @@ public static Stream unexpectedBodyLengthTooLargeDataProvider() throw @Test public void multipleToBytesToCheckBodyLength() { - HttpRequest httpRequest - = new HttpRequest(HttpMethod.GET, "http://localhost").setBody(BinaryData.fromBytes(EXPECTED)); + HttpRequest httpRequest = new HttpRequest().setMethod(HttpMethod.GET) + .setUri("http://localhost") + .setBody(BinaryData.fromBytes(EXPECTED)); httpRequest.getHeaders().set(HttpHeaderName.CONTENT_LENGTH, String.valueOf(EXPECTED.length)); BinaryData binaryData = RestProxyImpl.validateLength(httpRequest); @@ -178,7 +179,7 @@ private static Stream dataProvider(int contentLength) throws Exceptio } private static HttpRequest createHttpRequest(String uri, BinaryData body, int contentLength) { - HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, uri).setBody(body); + HttpRequest httpRequest = new HttpRequest().setMethod(HttpMethod.GET).setUri(uri).setBody(body); httpRequest.getHeaders().set(HttpHeaderName.CONTENT_LENGTH, String.valueOf(contentLength)); return httpRequest; } @@ -186,7 +187,8 @@ private static HttpRequest createHttpRequest(String uri, BinaryData body, int co @Test public void userProvidedLengthShouldNotBeTrustedTooLarge() throws IOException { try (InputStream byteArrayInputStream = new ByteArrayInputStream(EXPECTED)) { - HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, "http://localhost") + HttpRequest httpRequest = new HttpRequest().setMethod(HttpMethod.GET) + .setUri("http://localhost") .setBody(BinaryData.fromStream(byteArrayInputStream, EXPECTED.length - 1L)); httpRequest.getHeaders().set(HttpHeaderName.CONTENT_LENGTH, String.valueOf(EXPECTED.length - 1L)); @@ -200,7 +202,8 @@ public void userProvidedLengthShouldNotBeTrustedTooLarge() throws IOException { @Test public void userProvidedLengthShouldNotBeTrustedTooSmall() throws IOException { try (InputStream byteArrayInputStream = new ByteArrayInputStream(EXPECTED)) { - HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, "http://localhost") + HttpRequest httpRequest = new HttpRequest().setMethod(HttpMethod.GET) + .setUri("http://localhost") .setBody(BinaryData.fromStream(byteArrayInputStream, EXPECTED.length + 1L)); httpRequest.getHeaders().set(HttpHeaderName.CONTENT_LENGTH, String.valueOf(EXPECTED.length + 1L)); @@ -215,7 +218,8 @@ public void userProvidedLengthShouldNotBeTrustedTooSmall() throws IOException { @Test public void expectedBodyLength() throws IOException { try (InputStream byteArrayInputStream = new ByteArrayInputStream(EXPECTED)) { - HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, "http://localhost") + HttpRequest httpRequest = new HttpRequest().setMethod(HttpMethod.GET) + .setUri("http://localhost") .setBody(BinaryData.fromStream(byteArrayInputStream, (long) EXPECTED.length)); httpRequest.getHeaders().set(HttpHeaderName.CONTENT_LENGTH, String.valueOf(EXPECTED.length)); diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/RestProxyXmlSerializableTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/RestProxyXmlSerializableTests.java index 113e8621084c..76a1a22f7764 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/RestProxyXmlSerializableTests.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/RestProxyXmlSerializableTests.java @@ -3,18 +3,19 @@ package io.clientcore.core.implementation.http.rest; -import io.clientcore.core.annotation.ServiceInterface; -import io.clientcore.core.http.MockHttpResponse; +import io.clientcore.core.annotations.ServiceInterface; import io.clientcore.core.http.RestProxy; -import io.clientcore.core.http.annotation.BodyParam; -import io.clientcore.core.http.annotation.HttpRequestInformation; +import io.clientcore.core.http.annotations.BodyParam; +import io.clientcore.core.http.annotations.HttpRequestInformation; import io.clientcore.core.http.models.HttpHeaderName; import io.clientcore.core.http.models.HttpHeaders; import io.clientcore.core.http.models.HttpMethod; +import io.clientcore.core.http.models.Response; import io.clientcore.core.http.pipeline.HttpPipeline; import io.clientcore.core.http.pipeline.HttpPipelineBuilder; +import io.clientcore.core.models.binarydata.BinaryData; import io.clientcore.core.serialization.xml.XmlSerializable; -import io.clientcore.core.util.binarydata.StringBinaryData; +import io.clientcore.core.models.binarydata.StringBinaryData; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -68,7 +69,7 @@ private static void sendXmlShared(BiConsumer(request, 200, new HttpHeaders(), BinaryData.empty()); }).build(); SimpleXmlSerializableProxy proxy = RestProxy.create(SimpleXmlSerializableProxy.class, pipeline); @@ -82,7 +83,7 @@ public void getXml(String contentType) { + "1010"; HttpPipeline pipeline = new HttpPipelineBuilder() - .httpClient(request -> new MockHttpResponse(request, 200, + .httpClient(request -> new Response<>(request, 200, new HttpHeaders().set(HttpHeaderName.CONTENT_TYPE, contentType), new StringBinaryData(response))) .build(); @@ -103,7 +104,7 @@ public void getInvalidXml(String contentType) { + ""; HttpPipeline pipeline = new HttpPipelineBuilder() - .httpClient(request -> new MockHttpResponse(request, 200, + .httpClient(request -> new Response<>(request, 200, new HttpHeaders().set(HttpHeaderName.CONTENT_TYPE, contentType), new StringBinaryData(response))) .build(); diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/SimpleXmlSerializable.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/SimpleXmlSerializable.java index 8e84dea99d8f..bc39086c6639 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/SimpleXmlSerializable.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/SimpleXmlSerializable.java @@ -3,11 +3,11 @@ package io.clientcore.core.implementation.http.rest; -import io.clientcore.core.implementation.util.ImplUtils; import io.clientcore.core.serialization.xml.XmlReader; import io.clientcore.core.serialization.xml.XmlSerializable; import io.clientcore.core.serialization.xml.XmlToken; import io.clientcore.core.serialization.xml.XmlWriter; +import io.clientcore.core.utils.CoreUtils; import javax.xml.stream.XMLStreamException; import java.util.Objects; @@ -35,7 +35,7 @@ public XmlWriter toXml(XmlWriter xmlWriter) throws XMLStreamException { @Override public XmlWriter toXml(XmlWriter xmlWriter, String rootElementName) throws XMLStreamException { - rootElementName = ImplUtils.isNullOrEmpty(rootElementName) ? "SimpleXml" : rootElementName; + rootElementName = CoreUtils.isNullOrEmpty(rootElementName) ? "SimpleXml" : rootElementName; xmlWriter.writeStartElement(rootElementName); xmlWriter.writeBooleanAttribute("boolean", aBooleanAsAttribute); @@ -52,7 +52,7 @@ public static SimpleXmlSerializable fromXml(XmlReader xmlReader) throws XMLStrea } public static SimpleXmlSerializable fromXml(XmlReader xmlReader, String rootElementName) throws XMLStreamException { - rootElementName = ImplUtils.isNullOrEmpty(rootElementName) ? "SimpleXml" : rootElementName; + rootElementName = CoreUtils.isNullOrEmpty(rootElementName) ? "SimpleXml" : rootElementName; return xmlReader.readObject(rootElementName, reader -> { boolean aBooleanAsAttribute = xmlReader.getBooleanAttribute(null, "boolean"); double aDecimalAsAttribute = xmlReader.getDoubleAttribute(null, "decimal"); diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/SwaggerInterfaceParserTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/SwaggerInterfaceParserTests.java index b5247bb8e9c4..813c96e84cc1 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/SwaggerInterfaceParserTests.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/SwaggerInterfaceParserTests.java @@ -3,8 +3,8 @@ package io.clientcore.core.implementation.http.rest; -import io.clientcore.core.annotation.ServiceInterface; -import io.clientcore.core.http.annotation.HttpRequestInformation; +import io.clientcore.core.annotations.ServiceInterface; +import io.clientcore.core.http.annotations.HttpRequestInformation; import io.clientcore.core.http.models.HttpMethod; import org.junit.jupiter.api.Test; diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/SwaggerMethodParserTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/SwaggerMethodParserTests.java index ee1564058c23..f3803673a6ac 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/SwaggerMethodParserTests.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/http/rest/SwaggerMethodParserTests.java @@ -3,32 +3,30 @@ package io.clientcore.core.implementation.http.rest; -import io.clientcore.core.annotation.ServiceInterface; -import io.clientcore.core.http.annotation.BodyParam; -import io.clientcore.core.http.annotation.FormParam; -import io.clientcore.core.http.annotation.HeaderParam; -import io.clientcore.core.http.annotation.HostParam; -import io.clientcore.core.http.annotation.HttpRequestInformation; -import io.clientcore.core.http.annotation.PathParam; -import io.clientcore.core.http.annotation.QueryParam; -import io.clientcore.core.http.annotation.UnexpectedResponseExceptionDetail; -import io.clientcore.core.http.exception.HttpExceptionType; +import io.clientcore.core.annotations.ServiceInterface; +import io.clientcore.core.http.annotations.BodyParam; +import io.clientcore.core.http.annotations.FormParam; +import io.clientcore.core.http.annotations.HeaderParam; +import io.clientcore.core.http.annotations.HostParam; +import io.clientcore.core.http.annotations.HttpRequestInformation; +import io.clientcore.core.http.annotations.PathParam; +import io.clientcore.core.http.annotations.QueryParam; +import io.clientcore.core.http.annotations.UnexpectedResponseExceptionDetail; import io.clientcore.core.http.models.HttpHeader; import io.clientcore.core.http.models.HttpHeaderName; import io.clientcore.core.http.models.HttpHeaders; import io.clientcore.core.http.models.HttpMethod; -import io.clientcore.core.http.models.HttpResponse; import io.clientcore.core.http.models.RequestOptions; import io.clientcore.core.http.models.Response; import io.clientcore.core.implementation.TypeUtil; import io.clientcore.core.implementation.http.serializer.CompositeSerializer; -import io.clientcore.core.implementation.util.Base64Uri; -import io.clientcore.core.implementation.util.DateTimeRfc1123; -import io.clientcore.core.implementation.util.UriBuilder; import io.clientcore.core.models.SimpleClass; -import io.clientcore.core.util.Context; -import io.clientcore.core.util.binarydata.BinaryData; -import io.clientcore.core.implementation.util.JsonSerializer; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.serialization.json.JsonSerializer; +import io.clientcore.core.utils.Base64Uri; +import io.clientcore.core.utils.Context; +import io.clientcore.core.utils.DateTimeRfc1123; +import io.clientcore.core.utils.UriBuilder; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -46,12 +44,13 @@ import java.util.Arrays; import java.util.Collections; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Stream; -import static io.clientcore.core.http.models.ContentType.APPLICATION_JSON; -import static io.clientcore.core.http.models.ContentType.APPLICATION_X_WWW_FORM_URLENCODED; +import static io.clientcore.core.implementation.http.ContentType.APPLICATION_JSON; +import static io.clientcore.core.implementation.http.ContentType.APPLICATION_X_WWW_FORM_URLENCODED; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -187,9 +186,9 @@ public void headers(Method method, HttpHeaders expectedHeaders) { HttpHeaders actual = new HttpHeaders(); swaggerMethodParser.setHeaders(null, actual, DEFAULT_SERIALIZER); - for (HttpHeader header : actual) { + actual.stream().forEach(header -> { assertEquals(expectedHeaders.getValue(header.getName()), header.getValue()); - } + }); } private static Stream headersSupplier() throws NoSuchMethodException { @@ -398,9 +397,9 @@ public void headerSubstitution(Method method, Object[] arguments, Map { assertEquals(expectedHeaders.get(header.getName()), header.getValue()); - } + }); } private static Stream headerSubstitutionSupplier() throws NoSuchMethodException { @@ -414,9 +413,9 @@ private static Stream headerSubstitutionSupplier() throws NoSuchMetho Map expectedSimpleHeadersMap = Collections.singletonMap(HttpHeaderName.fromString("x-ms-meta-key"), "value"); - Map complexHeaderMap = new HttpHeaders().set(HttpHeaderName.fromString("key1"), (String) null) - .set(HttpHeaderName.fromString("key2"), "value2") - .toMap(); + Map complexHeaderMap = new LinkedHashMap<>(); + complexHeaderMap.put("key1", null); + complexHeaderMap.put("key2", "value2"); Map expectedComplexHeaderMap = Collections.singletonMap(HttpHeaderName.fromString("x-ms-meta-key2"), "value2"); @@ -594,21 +593,22 @@ interface UnexpectedStatusCodeMethods { void noUnexpectedStatusCodes(); @HttpRequestInformation(method = HttpMethod.GET, path = "test") - @UnexpectedResponseExceptionDetail(exceptionTypeName = "RESOURCE_NOT_FOUND", statusCode = { 400, 404 }) + @UnexpectedResponseExceptionDetail(statusCode = { 400, 404 }, exceptionBodyClass = String.class) void notFoundStatusCode(); @HttpRequestInformation(method = HttpMethod.GET, path = "test") - @UnexpectedResponseExceptionDetail(exceptionTypeName = "RESOURCE_NOT_FOUND", statusCode = { 400, 404 }) - @UnexpectedResponseExceptionDetail(exceptionTypeName = "RESOURCE_MODIFIED") + @UnexpectedResponseExceptionDetail(statusCode = { 400, 404 }, exceptionBodyClass = String.class) + @UnexpectedResponseExceptionDetail(exceptionBodyClass = Object.class) void customDefault(); } @ParameterizedTest @MethodSource("unexpectedStatusCodeSupplier") - public void unexpectedStatusCode(Method method, int statusCode, HttpExceptionType expectedExceptionType) { + public void unexpectedStatusCode(Method method, int statusCode, Class expectedExceptionBodyClass) { SwaggerMethodParser swaggerMethodParser = new SwaggerMethodParser(method); - assertEquals(expectedExceptionType, swaggerMethodParser.getUnexpectedException(statusCode).getExceptionType()); + assertEquals(expectedExceptionBodyClass, + swaggerMethodParser.getUnexpectedException(statusCode).getExceptionBodyClass()); } private static Stream unexpectedStatusCodeSupplier() throws NoSuchMethodException { @@ -617,14 +617,12 @@ private static Stream unexpectedStatusCodeSupplier() throws NoSuchMet Method notFoundStatusCode = clazz.getDeclaredMethod("notFoundStatusCode"); Method customDefault = clazz.getDeclaredMethod("customDefault"); - return Stream.of(Arguments.of(noUnexpectedStatusCodes, 500, null), - Arguments.of(noUnexpectedStatusCodes, 400, null), Arguments.of(noUnexpectedStatusCodes, 404, null), - Arguments.of(notFoundStatusCode, 500, null), - Arguments.of(notFoundStatusCode, 400, HttpExceptionType.RESOURCE_NOT_FOUND), - Arguments.of(notFoundStatusCode, 404, HttpExceptionType.RESOURCE_NOT_FOUND), - Arguments.of(customDefault, 500, HttpExceptionType.RESOURCE_MODIFIED), - Arguments.of(customDefault, 400, HttpExceptionType.RESOURCE_NOT_FOUND), - Arguments.of(customDefault, 404, HttpExceptionType.RESOURCE_NOT_FOUND)); + return Stream.of(Arguments.of(noUnexpectedStatusCodes, 500, Object.class), + Arguments.of(noUnexpectedStatusCodes, 400, Object.class), + Arguments.of(noUnexpectedStatusCodes, 404, Object.class), + Arguments.of(notFoundStatusCode, 500, Object.class), Arguments.of(notFoundStatusCode, 400, String.class), + Arguments.of(notFoundStatusCode, 404, String.class), Arguments.of(customDefault, 500, Object.class), + Arguments.of(customDefault, 400, String.class), Arguments.of(customDefault, 404, String.class)); } @ParameterizedTest @@ -636,62 +634,60 @@ public void isReturnTypeDecodable(Type returnType, boolean expected) { } private static Stream isReturnTypeDecodableSupplier() { - return returnTypeSupplierForDecodable(true, false, false); + return returnTypeSupplierForDecodable(); } - private static Stream returnTypeSupplierForDecodable(boolean nonBinaryTypeStatus, - boolean binaryTypeStatus, boolean voidTypeStatus) { + private static Stream returnTypeSupplierForDecodable() { return Stream.of( // Unknown response type can't be determined to be decodable. Arguments.of(null, false), // BinaryData, Byte arrays, ByteBuffers, InputStream, and voids aren't decodable. - Arguments.of(BinaryData.class, binaryTypeStatus), + Arguments.of(BinaryData.class, false), - Arguments.of(byte[].class, binaryTypeStatus), + Arguments.of(byte[].class, false), // Both ByteBuffer and subtypes shouldn't be decodable. - Arguments.of(ByteBuffer.class, binaryTypeStatus), Arguments.of(MappedByteBuffer.class, binaryTypeStatus), + Arguments.of(ByteBuffer.class, false), Arguments.of(MappedByteBuffer.class, false), // Both InputSteam and subtypes shouldn't be decodable. - Arguments.of(InputStream.class, binaryTypeStatus), Arguments.of(FileInputStream.class, binaryTypeStatus), + Arguments.of(InputStream.class, false), Arguments.of(FileInputStream.class, false), - Arguments.of(void.class, voidTypeStatus), Arguments.of(Void.class, voidTypeStatus), - Arguments.of(Void.TYPE, voidTypeStatus), + Arguments.of(void.class, false), Arguments.of(Void.class, false), Arguments.of(Void.TYPE, false), // Other POJO types are decodable. - Arguments.of(SimpleClass.class, nonBinaryTypeStatus), + Arguments.of(SimpleClass.class, true), // In addition to the direct types, reactive and Response generic types should be handled. // Response generics. // If the raw type is Response it should check the first, and only, generic type. - Arguments.of(createParameterizedResponse(BinaryData.class), binaryTypeStatus), - Arguments.of(createParameterizedResponse(byte[].class), binaryTypeStatus), - Arguments.of(createParameterizedResponse(ByteBuffer.class), binaryTypeStatus), - Arguments.of(createParameterizedResponse(MappedByteBuffer.class), binaryTypeStatus), - Arguments.of(createParameterizedResponse(InputStream.class), binaryTypeStatus), - Arguments.of(createParameterizedResponse(FileInputStream.class), binaryTypeStatus), - Arguments.of(createParameterizedResponse(void.class), voidTypeStatus), - Arguments.of(createParameterizedResponse(Void.class), voidTypeStatus), - Arguments.of(createParameterizedResponse(Void.TYPE), voidTypeStatus), - Arguments.of(createParameterizedResponse(SimpleClass.class), nonBinaryTypeStatus), + Arguments.of(createParameterizedResponse(BinaryData.class), false), + Arguments.of(createParameterizedResponse(byte[].class), false), + Arguments.of(createParameterizedResponse(ByteBuffer.class), false), + Arguments.of(createParameterizedResponse(MappedByteBuffer.class), false), + Arguments.of(createParameterizedResponse(InputStream.class), false), + Arguments.of(createParameterizedResponse(FileInputStream.class), false), + Arguments.of(createParameterizedResponse(void.class), false), + Arguments.of(createParameterizedResponse(Void.class), false), + Arguments.of(createParameterizedResponse(Void.TYPE), false), + Arguments.of(createParameterizedResponse(SimpleClass.class), true), // Custom implementations of Response. - Arguments.of(VoidResponse.class, voidTypeStatus), Arguments.of(StringResponse.class, nonBinaryTypeStatus)); + Arguments.of(VoidResponse.class, false), Arguments.of(StringResponse.class, true)); } private static ParameterizedType createParameterizedResponse(Type genericType) { return TypeUtil.createParameterizedType(Response.class, genericType); } - private static final class VoidResponse extends HttpResponse { + private static final class VoidResponse extends Response { VoidResponse(Response response, Void value) { super(response.getRequest(), response.getStatusCode(), response.getHeaders(), value); } } - private static final class StringResponse extends HttpResponse { + private static final class StringResponse extends Response { StringResponse(Response response, String value) { super(response.getRequest(), response.getStatusCode(), response.getHeaders(), value); } diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/fallback/FallbackInstrumentationTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/fallback/FallbackInstrumentationTests.java index 84a301a12564..a2f965699f89 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/fallback/FallbackInstrumentationTests.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/fallback/FallbackInstrumentationTests.java @@ -5,16 +5,21 @@ import io.clientcore.core.implementation.AccessibleByteArrayOutputStream; import io.clientcore.core.instrumentation.Instrumentation; +import io.clientcore.core.instrumentation.InstrumentationAttributes; import io.clientcore.core.instrumentation.InstrumentationContext; import io.clientcore.core.instrumentation.InstrumentationOptions; import io.clientcore.core.instrumentation.LibraryInstrumentationOptions; import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.instrumentation.logging.LogLevel; +import io.clientcore.core.instrumentation.metrics.DoubleHistogram; +import io.clientcore.core.instrumentation.metrics.LongCounter; +import io.clientcore.core.instrumentation.metrics.Meter; import io.clientcore.core.instrumentation.tracing.Span; import io.clientcore.core.instrumentation.tracing.TraceContextGetter; import io.clientcore.core.instrumentation.tracing.TraceContextPropagator; import io.clientcore.core.instrumentation.tracing.Tracer; import io.clientcore.core.instrumentation.tracing.TracingScope; -import io.clientcore.core.util.Context; +import io.clientcore.core.utils.Context; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -23,6 +28,7 @@ import java.io.IOException; import java.time.Duration; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -56,17 +62,18 @@ public class FallbackInstrumentationTests { private static final Instrumentation DEFAULT_INSTRUMENTATION = Instrumentation.create(null, DEFAULT_LIB_OPTIONS); private final AccessibleByteArrayOutputStream logCaptureStream; - private static final TraceContextGetter> GETTER = new TraceContextGetter<>() { - @Override - public Iterable keys(Map carrier) { - return carrier.keySet(); - } + private static final TraceContextGetter> GETTER + = new TraceContextGetter>() { + @Override + public Iterable keys(Map carrier) { + return carrier.keySet(); + } - @Override - public String get(Map carrier, String key) { - return carrier.get(key); - } - }; + @Override + public String get(Map carrier, String key) { + return carrier.get(key); + } + }; public FallbackInstrumentationTests() { logCaptureStream = new AccessibleByteArrayOutputStream(); @@ -324,7 +331,7 @@ public static Stream instrumentationContextSource() { @Test @SuppressWarnings("try") public void basicTracingDisabledTests() { - InstrumentationOptions options = new InstrumentationOptions<>().setTracingEnabled(false); + InstrumentationOptions options = new InstrumentationOptions().setTracingEnabled(false); Instrumentation instrumentation = Instrumentation.create(options, DEFAULT_LIB_OPTIONS); Tracer tracer = instrumentation.getTracer(); @@ -354,22 +361,23 @@ public void basicTracingDisabledTests() { @Test public void createTracerUnknownProvider() { // should not throw - InstrumentationOptions options = new InstrumentationOptions<>().setProvider("this is not a valid provider"); - Tracer tracer = Instrumentation.create(options, DEFAULT_LIB_OPTIONS).getTracer(); + InstrumentationOptions options + = new InstrumentationOptions().setTelemetryProvider("this is not a valid provider"); + Instrumentation instrumentation = Instrumentation.create(options, DEFAULT_LIB_OPTIONS); + Tracer tracer = instrumentation.getTracer(); assertTrue(tracer.isEnabled()); } @Test public void createInstrumentationBadOptions() { - assertThrows(NullPointerException.class, - () -> Instrumentation.create(new InstrumentationOptions<>(), null).getTracer()); + assertThrows(NullPointerException.class, () -> Instrumentation.create(new InstrumentationOptions(), null)); } @ParameterizedTest @MethodSource("logLevels") - public void basicTracingLogsLevel(ClientLogger.LogLevel logLevel, boolean expectLogs) { + public void basicTracingLogsLevel(LogLevel logLevel, boolean expectLogs) { ClientLogger logger = setupLogLevelAndGetLogger(logLevel, logCaptureStream); - InstrumentationOptions options = new InstrumentationOptions<>().setProvider(logger); + InstrumentationOptions options = new InstrumentationOptions().setTelemetryProvider(logger); Instrumentation instrumentation = Instrumentation.create(options, DEFAULT_LIB_OPTIONS); Tracer tracer = instrumentation.getTracer(); @@ -384,17 +392,47 @@ public void basicTracingLogsLevel(ClientLogger.LogLevel logLevel, boolean expect } } + @Test + public void testSetAllAttributes() { + Map start = new HashMap<>(); + start.put("string", "value"); + start.put("int", 42); + start.put("double", 0.42); + start.put("float", 4.2f); + start.put("boolean", true); + start.put("long", Long.MAX_VALUE); + + ClientLogger logger = setupLogLevelAndGetLogger(LogLevel.VERBOSE, logCaptureStream); + InstrumentationOptions options = new InstrumentationOptions().setTelemetryProvider(logger); + InstrumentationAttributes startAttributes = DEFAULT_INSTRUMENTATION.createAttributes(start); + Instrumentation instrumentation = Instrumentation.create(options, DEFAULT_LIB_OPTIONS); + Tracer tracer = instrumentation.getTracer(); + + Span span = tracer.spanBuilder("test-span", INTERNAL, null).setAllAttributes(startAttributes).startSpan(); + span.end(); + + List> logMessages = parseLogMessages(logCaptureStream); + + assertEquals(1, logMessages.size()); + Map loggedSpan = logMessages.get(0); + assertEquals(12, loggedSpan.size()); + assertEquals("value", loggedSpan.get("string")); + assertEquals(42, loggedSpan.get("int")); + assertEquals(Long.MAX_VALUE, loggedSpan.get("long")); + assertEquals(0.42, loggedSpan.get("double")); + assertEquals(4.2d, (Double) loggedSpan.get("float"), 0.1); + assertEquals(true, loggedSpan.get("boolean")); + } + public static Stream logLevels() { - return Stream.of(Arguments.of(ClientLogger.LogLevel.ERROR, false), - Arguments.of(ClientLogger.LogLevel.WARNING, false), - Arguments.of(ClientLogger.LogLevel.INFORMATIONAL, false), - Arguments.of(ClientLogger.LogLevel.VERBOSE, true)); + return Stream.of(Arguments.of(LogLevel.ERROR, false), Arguments.of(LogLevel.WARNING, false), + Arguments.of(LogLevel.INFORMATIONAL, false), Arguments.of(LogLevel.VERBOSE, true)); } @Test public void basicTracingLogsEnabled() { - ClientLogger logger = setupLogLevelAndGetLogger(ClientLogger.LogLevel.VERBOSE, logCaptureStream); - InstrumentationOptions options = new InstrumentationOptions<>().setProvider(logger); + ClientLogger logger = setupLogLevelAndGetLogger(LogLevel.VERBOSE, logCaptureStream); + InstrumentationOptions options = new InstrumentationOptions().setTelemetryProvider(logger); Instrumentation instrumentation = Instrumentation.create(options, DEFAULT_LIB_OPTIONS); Tracer tracer = instrumentation.getTracer(); @@ -421,8 +459,8 @@ public void basicTracingLogsEnabled() { @Test public void tracingWithAttributesLogsEnabled() { - ClientLogger logger = setupLogLevelAndGetLogger(ClientLogger.LogLevel.VERBOSE, logCaptureStream); - InstrumentationOptions options = new InstrumentationOptions<>().setProvider(logger); + ClientLogger logger = setupLogLevelAndGetLogger(LogLevel.VERBOSE, logCaptureStream); + InstrumentationOptions options = new InstrumentationOptions().setTelemetryProvider(logger); Tracer tracer = Instrumentation.create(options, DEFAULT_LIB_OPTIONS).getTracer(); Span span = tracer.spanBuilder("test-span", PRODUCER, null) @@ -459,8 +497,8 @@ public void tracingWithAttributesLogsEnabled() { @Test public void tracingWithExceptionLogsEnabled() { - ClientLogger logger = setupLogLevelAndGetLogger(ClientLogger.LogLevel.VERBOSE, logCaptureStream); - InstrumentationOptions options = new InstrumentationOptions<>().setProvider(logger); + ClientLogger logger = setupLogLevelAndGetLogger(LogLevel.VERBOSE, logCaptureStream); + InstrumentationOptions options = new InstrumentationOptions().setTelemetryProvider(logger); Tracer tracer = Instrumentation.create(options, DEFAULT_LIB_OPTIONS).getTracer(); Span span = tracer.spanBuilder("test-span", SERVER, null).startSpan(); @@ -477,8 +515,8 @@ public void tracingWithExceptionLogsEnabled() { @Test public void tracingLogsEnabledParent() { - ClientLogger logger = setupLogLevelAndGetLogger(ClientLogger.LogLevel.VERBOSE, logCaptureStream); - InstrumentationOptions options = new InstrumentationOptions<>().setProvider(logger); + ClientLogger logger = setupLogLevelAndGetLogger(LogLevel.VERBOSE, logCaptureStream); + InstrumentationOptions options = new InstrumentationOptions().setTelemetryProvider(logger); Tracer tracer = Instrumentation.create(options, DEFAULT_LIB_OPTIONS).getTracer(); Span parent = tracer.spanBuilder("parent", CONSUMER, null).startSpan(); @@ -531,6 +569,165 @@ public void testCreateInstrumentationContextNotSupported(Object context) { assertSame(Span.noop(), fromNull.getSpan()); } + @Test + public void testCreateMeterAndInstruments() { + Meter meter = DEFAULT_INSTRUMENTATION.getMeter(); + assertFalse(meter.isEnabled()); + + InstrumentationAttributes attributes = DEFAULT_INSTRUMENTATION.createAttributes(Collections.emptyMap()); + DoubleHistogram histogram = meter.createDoubleHistogram("test", "description", "1", null); + histogram.record(42.0, attributes, null); + assertFalse(histogram.isEnabled()); + + LongCounter counter = meter.createLongCounter("test", "description", "1"); + counter.add(42, attributes, null); + assertFalse(counter.isEnabled()); + + LongCounter upDownCounter = meter.createLongUpDownCounter("test", "description", "1"); + upDownCounter.add(42, attributes, null); + assertFalse(upDownCounter.isEnabled()); + } + + @Test + public void testInvalidParams() { + Meter meter = DEFAULT_INSTRUMENTATION.getMeter(); + + assertThrows(NullPointerException.class, () -> meter.createDoubleHistogram("test", null, "1", null)); + assertThrows(NullPointerException.class, () -> meter.createLongCounter("test", null, "1")); + assertThrows(NullPointerException.class, () -> meter.createLongUpDownCounter("test", null, "1")); + assertThrows(NullPointerException.class, () -> meter.createDoubleHistogram(null, "description", "1", null)); + assertThrows(NullPointerException.class, () -> meter.createLongCounter(null, "description", "1")); + assertThrows(NullPointerException.class, () -> meter.createLongUpDownCounter(null, "description", "1")); + assertThrows(NullPointerException.class, () -> meter.createDoubleHistogram("test", "description", null, null)); + assertThrows(NullPointerException.class, () -> meter.createLongCounter("test", "description", null)); + assertThrows(NullPointerException.class, () -> meter.createLongUpDownCounter("test", "description", null)); + + DoubleHistogram histogram = meter.createDoubleHistogram("test", "description", "1", null); + assertThrows(NullPointerException.class, () -> histogram.record(42.0, null, null)); + + LongCounter counter = meter.createLongCounter("test", "description", "1"); + assertThrows(NullPointerException.class, () -> counter.add(42, null, null)); + + LongCounter upDownCounter = meter.createLongUpDownCounter("test", "description", "1"); + assertThrows(NullPointerException.class, () -> upDownCounter.add(42, null, null)); + } + + @Test + public void testGetAttributes() { + InstrumentationAttributes attributes = DEFAULT_INSTRUMENTATION.createAttributes(Collections.emptyMap()); + assertNotNull(attributes); + + // does not throw + attributes.put("key", "value1"); + attributes.put("key", "value2"); + DEFAULT_INSTRUMENTATION.createAttributes(null); + } + + @Test + public void testAttributesInvalidParams() { + assertThrows(NullPointerException.class, + () -> DEFAULT_INSTRUMENTATION.createAttributes(Collections.singletonMap(null, "value"))); + assertThrows(NullPointerException.class, + () -> DEFAULT_INSTRUMENTATION.createAttributes(Collections.singletonMap("key", null))); + InstrumentationAttributes attributes = DEFAULT_INSTRUMENTATION.createAttributes(null); + assertThrows(NullPointerException.class, () -> attributes.put(null, "value")); + assertThrows(NullPointerException.class, () -> attributes.put("key", null)); + } + + @Test + public void testCreateAttributes() { + Instrumentation instrumentation = Instrumentation.create(null, DEFAULT_LIB_OPTIONS); + InstrumentationAttributes attributes = instrumentation.createAttributes(Collections.emptyMap()); + assertInstanceOf(FallbackAttributes.class, attributes); + + // does not throw + attributes.put("key", "value1"); + attributes.put("key", "value2"); + instrumentation.createAttributes(null); + } + + @Test + public void testAttributes() { + Instrumentation instrumentation = Instrumentation.create(null, DEFAULT_LIB_OPTIONS); + Map start = new HashMap<>(); + start.put("string", "value"); + start.put("int", 42); + start.put("double", 0.42); + start.put("float", 4.2f); + start.put("boolean", true); + start.put("long", 420L); + + InstrumentationAttributes attributes = instrumentation.createAttributes(start); + assertInstanceOf(FallbackAttributes.class, attributes); + + Map attrs = ((FallbackAttributes) attributes).getAttributes(); + assertEquals(6, attrs.size()); + assertEquals("value", attrs.get("string")); + assertEquals(42, attrs.get("int")); + assertEquals(420L, attrs.get("long")); + assertEquals(0.42, attrs.get("double")); + assertEquals(4.2f, (Float) attrs.get("float"), 0.1); + assertEquals(true, attrs.get("boolean")); + + InstrumentationAttributes attributes2 = attributes.put("string2", "value2"); + + assertNotSame(attributes, attributes2); + assertNull(attrs.get("string2")); + assertEquals(6, attrs.size()); + + attributes2 = attributes2.put("int2", 24) + .put("double2", 0.24) + .put("float2", 2.4f) + .put("boolean2", false) + .put("long2", 240L); + + attrs = ((FallbackAttributes) attributes2).getAttributes(); + assertEquals(12, attrs.size()); + assertEquals("value2", attrs.get("string2")); + assertEquals(24, attrs.get("int2")); + assertEquals(240L, attrs.get("long2")); + assertEquals(0.24, attrs.get("double2")); + assertEquals(2.4f, (Float) attrs.get("float2"), 0.1); + assertEquals(false, attrs.get("boolean2")); + } + + @Test + public void testDuplicates() { + Instrumentation instrumentation = Instrumentation.create(null, DEFAULT_LIB_OPTIONS); + Map start = new HashMap<>(); + start.put("string", "value1"); + start.put("string", "value2"); + + InstrumentationAttributes attributes + = instrumentation.createAttributes(start).put("string", "value3").put("string", "value4"); + + Map attrs = ((FallbackAttributes) attributes).getAttributes(); + assertEquals(1, attrs.size()); + assertEquals("value4", attrs.get("string")); + } + + /*@Test + public void testSuppression() { + Instrumentation instrumentation = Instrumentation.create(null, DEFAULT_LIB_OPTIONS, null); + assertTrue(instrumentation.shouldInstrument(CLIENT, null)); + + Tracer tracer = instrumentation.getTracer(); + Span span = tracer.spanBuilder("test", CLIENT, null).startSpan(); + + assertFalse(instrumentation.shouldInstrument(CLIENT, span.getInstrumentationContext())); + assertTrue(instrumentation.shouldInstrument(INTERNAL, span.getInstrumentationContext())); + assertTrue(instrumentation.shouldInstrument(CONSUMER, span.getInstrumentationContext())); + assertTrue(instrumentation.shouldInstrument(PRODUCER, span.getInstrumentationContext())); + assertTrue(instrumentation.shouldInstrument(SERVER, span.getInstrumentationContext())); + } + + @Test + public void testSuppressionTracingDisabled() { + InstrumentationOptions options = new InstrumentationOptions().setTracingEnabled(false); + + assertFalse(Instrumentation.create(options, DEFAULT_LIB_OPTIONS, null).shouldInstrument(CLIENT, null)); + }*/ + public static Stream notSupportedContexts() { return Stream.of(null, new Object(), "this is not a valid context", Context.none(), Context.of("key", "value")); } diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/fallback/FallbackTracingBenchmarks.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/fallback/FallbackTracingBenchmarks.java index 821c2bda69fc..470584e4b400 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/fallback/FallbackTracingBenchmarks.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/fallback/FallbackTracingBenchmarks.java @@ -8,6 +8,7 @@ import io.clientcore.core.instrumentation.LibraryInstrumentationOptions; import io.clientcore.core.instrumentation.logging.ClientLogger; import io.clientcore.core.instrumentation.logging.InstrumentationTestUtils; +import io.clientcore.core.instrumentation.logging.LogLevel; import io.clientcore.core.instrumentation.tracing.Span; import io.clientcore.core.instrumentation.tracing.SpanKind; import io.clientcore.core.instrumentation.tracing.Tracer; @@ -44,19 +45,18 @@ public class FallbackTracingBenchmarks { public void setupOtel() { LibraryInstrumentationOptions libraryOptions = new LibraryInstrumentationOptions("test"); fallbackTracerDisabled - = Instrumentation.create(new InstrumentationOptions<>().setTracingEnabled(false), libraryOptions) - .getTracer(); + = Instrumentation.create(new InstrumentationOptions().setTracingEnabled(false), libraryOptions).getTracer(); ClientLogger loggerDisabled - = InstrumentationTestUtils.setupLogLevelAndGetLogger(ClientLogger.LogLevel.WARNING, new NoopStream()); + = InstrumentationTestUtils.setupLogLevelAndGetLogger(LogLevel.WARNING, new NoopStream()); fallbackTracerEnabledNoLogs - = Instrumentation.create(new InstrumentationOptions<>().setProvider(loggerDisabled), libraryOptions) + = Instrumentation.create(new InstrumentationOptions().setTelemetryProvider(loggerDisabled), libraryOptions) .getTracer(); ClientLogger loggerEnabled - = InstrumentationTestUtils.setupLogLevelAndGetLogger(ClientLogger.LogLevel.INFORMATIONAL, new NoopStream()); + = InstrumentationTestUtils.setupLogLevelAndGetLogger(LogLevel.INFORMATIONAL, new NoopStream()); fallbackTracerEnabledWithLogs - = Instrumentation.create(new InstrumentationOptions<>().setProvider(loggerEnabled), libraryOptions) + = Instrumentation.create(new InstrumentationOptions().setTelemetryProvider(loggerEnabled), libraryOptions) .getTracer(); } diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/OTelAttributeKeyTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/OTelAttributeKeyTests.java new file mode 100644 index 000000000000..5ff9757a88c3 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/OTelAttributeKeyTests.java @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.implementation.instrumentation.otel; + +import org.junit.jupiter.api.Test; + +import java.util.Collections; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +/** + * Unit tests for the OTelAttributeKey class when OpenTelemetry isn't on the classpath. + */ +public class OTelAttributeKeyTests { + @Test + public void getKeyReturnsNull() { + // This value would normally throw an exception if OTel is on the classpath. + assertDoesNotThrow(() -> OTelAttributeKey.getKey("key", Collections.singletonList(1L))); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/OTelAttributesTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/OTelAttributesTests.java new file mode 100644 index 000000000000..286e91c26b59 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/OTelAttributesTests.java @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.implementation.instrumentation.otel; + +import io.clientcore.core.implementation.instrumentation.NoopAttributes; +import io.clientcore.core.instrumentation.InstrumentationAttributes; +import org.junit.jupiter.api.Test; + +import java.util.Collections; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +/** + * Unit tests for the OTelAttributes class when OpenTelemetry isn't on the classpath. + */ +public class OTelAttributesTests { + @Test + public void createWithInvalidValue() { + // This value would normally throw an exception if OTel is on the classpath. + assertDoesNotThrow(() -> OTelAttributes.create(Collections.singletonMap(null, null))); + } + + @Test + public void createWithNull() { + InstrumentationAttributes attributes = assertDoesNotThrow(() -> OTelAttributes.create(null)); + OTelAttributes oTelAttributes = assertInstanceOf(OTelAttributes.class, attributes); + assertNull(oTelAttributes.getOTelAttributes()); + } + + @Test + public void putReturnsNoop() { + assertSame(NoopAttributes.INSTANCE, OTelAttributes.create(null).put("key", "value")); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/OTelContextTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/OTelContextTests.java new file mode 100644 index 000000000000..ab85e85b9e8e --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/OTelContextTests.java @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.implementation.instrumentation.otel; + +/** + * Unit tests for the OTelContext class when OpenTelemetry isn't on the classpath. + */ +public class OTelContextTests { +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/OTelInstrumentationTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/OTelInstrumentationTests.java new file mode 100644 index 000000000000..6c780338ae9c --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/OTelInstrumentationTests.java @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.implementation.instrumentation.otel; + +/** + * Unit tests for the OTelInstrumentation class when OpenTelemetry isn't on the classpath. + */ +public class OTelInstrumentationTests { +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/metrics/OTelDoubleHistogramTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/metrics/OTelDoubleHistogramTests.java new file mode 100644 index 000000000000..c82497192ea1 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/metrics/OTelDoubleHistogramTests.java @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.implementation.instrumentation.otel.metrics; + +/** + * Unit tests for the OTelDoubleHistogram class when OpenTelemetry isn't on the classpath. + */ +public class OTelDoubleHistogramTests { +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/metrics/OTelLongCounterTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/metrics/OTelLongCounterTests.java new file mode 100644 index 000000000000..e9f330428228 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/metrics/OTelLongCounterTests.java @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.implementation.instrumentation.otel.metrics; + +/** + * Unit tests for the OTelLongCounter class when OpenTelemetry isn't on the classpath. + */ +public class OTelLongCounterTests { +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/metrics/OTelLongUpDownCounterTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/metrics/OTelLongUpDownCounterTests.java new file mode 100644 index 000000000000..f94d40e46720 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/metrics/OTelLongUpDownCounterTests.java @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.implementation.instrumentation.otel.metrics; + +/** + * Unit tests for the OTelLongUpDownCounter class when OpenTelemetry isn't on the classpath. + */ +public class OTelLongUpDownCounterTests { +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/metrics/OTelMeterTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/metrics/OTelMeterTests.java new file mode 100644 index 000000000000..021b7e2603d7 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/metrics/OTelMeterTests.java @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.implementation.instrumentation.otel.metrics; + +/** + * Unit tests for the OTelMeter class when OpenTelemetry isn't on the classpath. + */ +public class OTelMeterTests { +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelSpanBuilderTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelSpanBuilderTests.java new file mode 100644 index 000000000000..ccc91523e45c --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelSpanBuilderTests.java @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.implementation.instrumentation.otel.tracing; + +/** + * Unit tests for the OTelSpanBuilder class when OpenTelemetry isn't on the classpath. + */ +public class OTelSpanBuilderTests { +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelSpanContextTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelSpanContextTests.java new file mode 100644 index 000000000000..344efc18d5dd --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelSpanContextTests.java @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.implementation.instrumentation.otel.tracing; + +/** + * Unit tests for the OTelSpanContext class when OpenTelemetry isn't on the classpath. + */ +public class OTelSpanContextTests { +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelSpanTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelSpanTests.java new file mode 100644 index 000000000000..f45de040b774 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelSpanTests.java @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.implementation.instrumentation.otel.tracing; + +/** + * Unit tests for the OTelSpan class when OpenTelemetry isn't on the classpath. + */ +public class OTelSpanTests { +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelTraceContextPropagatorTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelTraceContextPropagatorTests.java new file mode 100644 index 000000000000..8db952d9ddd1 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelTraceContextPropagatorTests.java @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.implementation.instrumentation.otel.tracing; + +/** + * Unit tests for the OTelTraceContextPropagator class when OpenTelemetry isn't on the classpath. + */ +public class OTelTraceContextPropagatorTests { +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelTracerTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelTracerTests.java new file mode 100644 index 000000000000..068aab234428 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/instrumentation/otel/tracing/OTelTracerTests.java @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.implementation.instrumentation.otel.tracing; + +/** + * Unit tests for the OTelTracer class when OpenTelemetry isn't on the classpath. + */ +public class OTelTracerTests { +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/serializer/AdditionalPropertiesSerializerTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/serializer/AdditionalPropertiesSerializerTests.java index a836051b3174..aed2e8f4e234 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/serializer/AdditionalPropertiesSerializerTests.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/serializer/AdditionalPropertiesSerializerTests.java @@ -3,7 +3,7 @@ package io.clientcore.core.implementation.serializer; -import io.clientcore.core.implementation.util.JsonSerializer; +import io.clientcore.core.serialization.json.JsonSerializer; import org.junit.jupiter.api.Test; import java.io.IOException; diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/serializer/BinaryDataSerializationTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/serializer/BinaryDataSerializationTests.java index 4567bc58bc70..35489263ed57 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/serializer/BinaryDataSerializationTests.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/serializer/BinaryDataSerializationTests.java @@ -3,13 +3,12 @@ package io.clientcore.core.implementation.serializer; +import io.clientcore.core.models.binarydata.BinaryData; import io.clientcore.core.serialization.json.JsonReader; import io.clientcore.core.serialization.json.JsonSerializable; +import io.clientcore.core.serialization.json.JsonSerializer; import io.clientcore.core.serialization.json.JsonToken; import io.clientcore.core.serialization.json.JsonWriter; -import io.clientcore.core.util.binarydata.BinaryData; -import io.clientcore.core.implementation.util.JsonSerializer; -import io.clientcore.core.util.serializer.ObjectSerializer; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import org.junit.jupiter.params.ParameterizedTest; @@ -34,7 +33,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class BinaryDataSerializationTests { - private static final ObjectSerializer SERIALIZER = new JsonSerializer(); + private static final JsonSerializer SERIALIZER = new JsonSerializer(); private static final byte[] HELLO_BYTES = "hello".getBytes(StandardCharsets.UTF_8); private static final String BASE64_HELLO_BYTES = Base64.getEncoder().encodeToString(HELLO_BYTES); private static final SimplePojo SIMPLE_POJO = new SimplePojo().setString("hello").setNumber(3.14).setBool(true); diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/serializer/HttpResponseBodyDecoderTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/serializer/HttpResponseBodyDecoderTests.java index 0c191616f4bb..cd50f27738eb 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/serializer/HttpResponseBodyDecoderTests.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/serializer/HttpResponseBodyDecoderTests.java @@ -3,21 +3,21 @@ package io.clientcore.core.implementation.serializer; -import io.clientcore.core.http.MockHttpResponse; import io.clientcore.core.http.MockHttpResponseDecodeData; -import io.clientcore.core.http.exception.HttpExceptionType; -import io.clientcore.core.http.exception.HttpResponseException; +import io.clientcore.core.http.models.HttpHeaders; import io.clientcore.core.http.models.HttpMethod; import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.HttpResponseException; import io.clientcore.core.http.models.Response; import io.clientcore.core.implementation.http.UnexpectedExceptionInformation; import io.clientcore.core.implementation.http.serializer.CompositeSerializer; import io.clientcore.core.implementation.http.serializer.HttpResponseBodyDecoder; import io.clientcore.core.implementation.http.serializer.HttpResponseDecodeData; -import io.clientcore.core.implementation.util.Base64Uri; -import io.clientcore.core.implementation.util.DateTimeRfc1123; -import io.clientcore.core.util.binarydata.BinaryData; -import io.clientcore.core.implementation.util.JsonSerializer; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.serialization.json.JsonSerializer; +import io.clientcore.core.utils.Base64Uri; +import io.clientcore.core.utils.CoreUtils; +import io.clientcore.core.utils.DateTimeRfc1123; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -35,7 +35,7 @@ import java.util.Map; import java.util.stream.Stream; -import static io.clientcore.core.util.TestUtils.assertArraysEqual; +import static io.clientcore.core.utils.TestUtils.assertArraysEqual; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNull; @@ -47,12 +47,14 @@ public class HttpResponseBodyDecoderTests { private static final CompositeSerializer SERIALIZER = new CompositeSerializer(Arrays.asList(new JsonSerializer())); - private static final HttpRequest GET_REQUEST = new HttpRequest(HttpMethod.GET, "https://localhost"); - private static final HttpRequest HEAD_REQUEST = new HttpRequest(HttpMethod.HEAD, "https://localhost"); + private static final HttpRequest GET_REQUEST + = new HttpRequest().setMethod(HttpMethod.GET).setUri("https://localhost"); + private static final HttpRequest HEAD_REQUEST + = new HttpRequest().setMethod(HttpMethod.HEAD).setUri("https://localhost"); @ParameterizedTest @MethodSource("invalidHttpResponseSupplier") - public void invalidHttpResponse(Response response) { + public void invalidHttpResponse(Response response) { assertThrows(NullPointerException.class, () -> HttpResponseBodyDecoder.decodeByteArray(null, response, null, null)); @@ -61,17 +63,17 @@ public void invalidHttpResponse(Response response) { private static Stream invalidHttpResponseSupplier() { return Stream.of( // Null response. - Arguments.of((Response) null), + Arguments.of((Response) null), // Response without a request. - Arguments.of(new MockHttpResponse(null, 200))); + Arguments.of(new Response<>(null, 200, new HttpHeaders(), BinaryData.empty()))); } @ParameterizedTest @MethodSource("errorResponseSupplier") - public void errorResponse(Response response, HttpResponseDecodeData decodeData, boolean isEmpty, + public void errorResponse(Response response, HttpResponseDecodeData decodeData, boolean isEmpty, Object expected) { - BinaryData body = response.getBody(); + BinaryData body = response.getValue(); HttpResponseBodyDecoder.decodeByteArray(body, response, SERIALIZER, decodeData); if (!isEmpty) { @@ -80,15 +82,16 @@ public void errorResponse(Response response, HttpResponseDecodeData decodeDat } private static Stream errorResponseSupplier() { - UnexpectedExceptionInformation exceptionInformation - = new MockUnexpectedExceptionInformation(null, String.class); + UnexpectedExceptionInformation exceptionInformation = new MockUnexpectedExceptionInformation(String.class); HttpResponseDecodeData noExpectedStatusCodes = new MockHttpResponseDecodeData(exceptionInformation); HttpResponseDecodeData expectedStatusCodes = new MockHttpResponseDecodeData(202, exceptionInformation); - Response emptyResponse = new MockHttpResponse(GET_REQUEST, 300, (Object) null); - Response response = new MockHttpResponse(GET_REQUEST, 300, "expected"); - Response wrongGoodResponse = new MockHttpResponse(GET_REQUEST, 200, "good response"); + Response emptyResponse = new Response<>(GET_REQUEST, 300, new HttpHeaders(), null); + Response response + = new Response<>(GET_REQUEST, 300, new HttpHeaders(), BinaryData.fromObject("expected")); + Response wrongGoodResponse + = new Response<>(GET_REQUEST, 200, new HttpHeaders(), BinaryData.fromObject("good response")); return Stream.of(Arguments.of(emptyResponse, noExpectedStatusCodes, true, null), Arguments.of(emptyResponse, expectedStatusCodes, true, null), @@ -107,9 +110,9 @@ public T deserializeFromBytes(byte[] bytes, Type type) { })); HttpResponseDecodeData noExpectedStatusCodes - = new MockHttpResponseDecodeData(new UnexpectedExceptionInformation(null, null)); + = new MockHttpResponseDecodeData(new UnexpectedExceptionInformation(null)); - Response response = new MockHttpResponse(GET_REQUEST, 300); + Response response = new Response<>(GET_REQUEST, 300, new HttpHeaders(), BinaryData.empty()); assertInstanceOf(UncheckedIOException.class, HttpResponseBodyDecoder.decodeByteArray(null, response, ioExceptionThrower, noExpectedStatusCodes)); @@ -119,14 +122,14 @@ public T deserializeFromBytes(byte[] bytes, Type type) { public void headRequestReturnsEmpty() { HttpResponseDecodeData decodeData = new MockHttpResponseDecodeData(200); - Response response = new MockHttpResponse(HEAD_REQUEST, 200); + Response response = new Response<>(HEAD_REQUEST, 200, new HttpHeaders(), BinaryData.empty()); assertNull(HttpResponseBodyDecoder.decodeByteArray(null, response, SERIALIZER, decodeData)); } @ParameterizedTest @MethodSource("nonDecodableResponseSupplier") public void nonDecodableResponse(HttpResponseDecodeData decodeData) { - Response response = new MockHttpResponse(GET_REQUEST, 200); + Response response = new Response<>(GET_REQUEST, 200, new HttpHeaders(), BinaryData.empty()); assertNull(HttpResponseBodyDecoder.decodeByteArray(null, response, SERIALIZER, decodeData)); } @@ -135,11 +138,11 @@ private static Stream nonDecodableResponseSupplier() { // Types that will cause a response to be non decodable. HttpResponseDecodeData nullReturnType = new MockHttpResponseDecodeData(200, null, false); - ParameterizedType voidTypeResponse = mockParameterizedType(Response.class, int.class, Void.TYPE); + ParameterizedType voidTypeResponse = CoreUtils.createParameterizedType(Response.class, Void.TYPE); HttpResponseDecodeData voidTypeResponseReturnType = new MockHttpResponseDecodeData(200, voidTypeResponse, false); - ParameterizedType voidClassResponse = mockParameterizedType(Response.class, int.class, void.class); + ParameterizedType voidClassResponse = CoreUtils.createParameterizedType(Response.class, void.class); HttpResponseDecodeData voidClassResponseReturnType = new MockHttpResponseDecodeData(200, voidClassResponse, false); @@ -149,7 +152,7 @@ private static Stream nonDecodableResponseSupplier() { @Test public void emptyResponseReturnsNull() { - Response response = new MockHttpResponse(GET_REQUEST, 200, (Object) null); + Response response = new Response<>(GET_REQUEST, 200, new HttpHeaders(), null); HttpResponseDecodeData decodeData = new MockHttpResponseDecodeData(200, String.class, true); @@ -158,8 +161,8 @@ public void emptyResponseReturnsNull() { @ParameterizedTest @MethodSource("decodableResponseSupplier") - public void decodableResponse(Response response, HttpResponseDecodeData decodeData, Object expected) { - BinaryData body = response.getBody(); + public void decodableResponse(Response response, HttpResponseDecodeData decodeData, Object expected) { + BinaryData body = response.getValue(); Object actual = HttpResponseBodyDecoder.decodeByteArray(body, response, SERIALIZER, decodeData); assertEquals(expected, actual); @@ -167,33 +170,39 @@ public void decodableResponse(Response response, HttpResponseDecodeData decod private static Stream decodableResponseSupplier() { HttpResponseDecodeData stringDecodeData = new MockHttpResponseDecodeData(200, String.class, String.class, true); - Response stringResponse = new MockHttpResponse(GET_REQUEST, 200, "hello"); + Response stringResponse + = new Response<>(GET_REQUEST, 200, new HttpHeaders(), BinaryData.fromObject("hello")); HttpResponseDecodeData offsetDateTimeDecodeData = new MockHttpResponseDecodeData(200, OffsetDateTime.class, OffsetDateTime.class, true); OffsetDateTime offsetDateTimeNow = OffsetDateTime.now(ZoneOffset.UTC); - Response offsetDateTimeResponse = new MockHttpResponse(GET_REQUEST, 200, offsetDateTimeNow); + Response offsetDateTimeResponse + = new Response<>(GET_REQUEST, 200, new HttpHeaders(), BinaryData.fromObject(offsetDateTimeNow)); HttpResponseDecodeData dateTimeRfc1123DecodeData = new MockHttpResponseDecodeData(200, OffsetDateTime.class, DateTimeRfc1123.class, true); DateTimeRfc1123 dateTimeRfc1123Now = new DateTimeRfc1123(offsetDateTimeNow); - Response dateTimeRfc1123Response = new MockHttpResponse(GET_REQUEST, 200, dateTimeRfc1123Now); + Response dateTimeRfc1123Response + = new Response<>(GET_REQUEST, 200, new HttpHeaders(), BinaryData.fromObject(dateTimeRfc1123Now)); HttpResponseDecodeData unixTimeDecodeData = new MockHttpResponseDecodeData(200, OffsetDateTime.class, OffsetDateTime.class, true); - Response unixTimeResponse = new MockHttpResponse(GET_REQUEST, 200, offsetDateTimeNow); + Response unixTimeResponse + = new Response<>(GET_REQUEST, 200, new HttpHeaders(), BinaryData.fromObject(offsetDateTimeNow)); - ParameterizedType stringList = mockParameterizedType(List.class, String.class); + ParameterizedType stringList = CoreUtils.createParameterizedType(List.class, String.class); HttpResponseDecodeData stringListDecodeData = new MockHttpResponseDecodeData(200, stringList, String.class, true); List list = Arrays.asList("hello", "world"); - Response stringListResponse = new MockHttpResponse(GET_REQUEST, 200, list); + Response stringListResponse + = new Response<>(GET_REQUEST, 200, new HttpHeaders(), BinaryData.fromObject(list)); - ParameterizedType mapStringString = mockParameterizedType(Map.class, String.class, String.class); + ParameterizedType mapStringString = CoreUtils.createParameterizedType(Map.class, String.class, String.class); HttpResponseDecodeData mapStringStringDecodeData = new MockHttpResponseDecodeData(200, mapStringString, String.class, true); Map map = Collections.singletonMap("hello", "world"); - Response mapStringStringResponse = new MockHttpResponse(GET_REQUEST, 200, map); + Response mapStringStringResponse + = new Response<>(GET_REQUEST, 200, new HttpHeaders(), BinaryData.fromObject(map)); return Stream.of(Arguments.of(stringResponse, stringDecodeData, "hello"), Arguments.of(offsetDateTimeResponse, offsetDateTimeDecodeData, offsetDateTimeNow), @@ -206,15 +215,15 @@ private static Stream decodableResponseSupplier() { @Test public void decodeListBase64UriResponse() { - ParameterizedType parameterizedType = mockParameterizedType(List.class, byte[].class); + ParameterizedType parameterizedType = CoreUtils.createParameterizedType(List.class, byte[].class); HttpResponseDecodeData decodeData = new MockHttpResponseDecodeData(200, parameterizedType, Base64Uri.class, true); List base64Uris = Arrays.asList(new Base64Uri("base"), new Base64Uri("64")); - Response response = new MockHttpResponse(GET_REQUEST, 200, base64Uris); + Response response + = new Response<>(GET_REQUEST, 200, new HttpHeaders(), BinaryData.fromObject(base64Uris)); - BinaryData body = response.getBody(); - Object actual = HttpResponseBodyDecoder.decodeByteArray(body, response, SERIALIZER, decodeData); + Object actual = HttpResponseBodyDecoder.decodeByteArray(null, response, SERIALIZER, decodeData); assertInstanceOf(List.class, actual); @@ -228,7 +237,7 @@ public void decodeListBase64UriResponse() { @Test public void malformedBodyReturnsError() throws IOException { - try (Response response = new MockHttpResponse(GET_REQUEST, 200, (Object) null)) { + try (Response response = new Response<>(GET_REQUEST, 200, new HttpHeaders(), null)) { HttpResponseDecodeData decodeData = new MockHttpResponseDecodeData(200, String.class, String.class, true); assertThrows(HttpResponseException.class, () -> HttpResponseBodyDecoder @@ -243,18 +252,18 @@ public void decodeType(Response response, HttpResponseDecodeData data, Type e } private static Stream decodeTypeSupplier() { - Response badResponse = new MockHttpResponse(GET_REQUEST, 400); - Response headResponse = new MockHttpResponse(HEAD_REQUEST, 200); - Response getResponse = new MockHttpResponse(GET_REQUEST, 200); + Response badResponse = new Response<>(GET_REQUEST, 400, new HttpHeaders(), BinaryData.empty()); + Response headResponse = new Response<>(HEAD_REQUEST, 200, new HttpHeaders(), BinaryData.empty()); + Response getResponse = new Response<>(GET_REQUEST, 200, new HttpHeaders(), BinaryData.empty()); HttpResponseDecodeData badResponseData - = new MockHttpResponseDecodeData(-1, new UnexpectedExceptionInformation(null, null)); + = new MockHttpResponseDecodeData(-1, new UnexpectedExceptionInformation(null)); HttpResponseDecodeData nonDecodable = new MockHttpResponseDecodeData(200, void.class, false); HttpResponseDecodeData stringReturn = new MockHttpResponseDecodeData(200, String.class, true); - ParameterizedType responseString = mockParameterizedType(Response.class, String.class); + ParameterizedType responseString = CoreUtils.createParameterizedType(Response.class, String.class); HttpResponseDecodeData responseStringReturn = new MockHttpResponseDecodeData(200, responseString, true); HttpResponseDecodeData headDecodeData = new MockHttpResponseDecodeData(200, null, false); @@ -264,44 +273,17 @@ private static Stream decodeTypeSupplier() { Arguments.of(getResponse, responseStringReturn, String.class)); } - private static ParameterizedType mockParameterizedType(Type rawType, Type... actualTypeArguments) { - return new ParameterizedType() { - @Override - public Type[] getActualTypeArguments() { - return actualTypeArguments; - } - - @Override - public Type getRawType() { - return rawType; - } - - @Override - public Type getOwnerType() { - return null; - } - }; - } - private static final class MockUnexpectedExceptionInformation extends UnexpectedExceptionInformation { private final Class exceptionBodyType; /** * Creates an UnexpectedExceptionInformation object with the given exception type and expected response body. - * - * @param exceptionType Exception type to be thrown. */ - MockUnexpectedExceptionInformation(HttpExceptionType exceptionType, Class exceptionBodyType) { - super(exceptionType, null); - + MockUnexpectedExceptionInformation(Class exceptionBodyType) { + super(null); this.exceptionBodyType = exceptionBodyType; } - @Override - public HttpExceptionType getExceptionType() { - return super.getExceptionType(); - } - @Override public Class getExceptionBodyClass() { return exceptionBodyType; diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/serializer/JsonSerializableEndToEndTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/serializer/JsonSerializableEndToEndTests.java index 873822db4013..c3012db96aac 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/serializer/JsonSerializableEndToEndTests.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/serializer/JsonSerializableEndToEndTests.java @@ -5,10 +5,9 @@ import io.clientcore.core.serialization.json.JsonReader; import io.clientcore.core.serialization.json.JsonSerializable; +import io.clientcore.core.serialization.json.JsonSerializer; import io.clientcore.core.serialization.json.JsonToken; import io.clientcore.core.serialization.json.JsonWriter; -import io.clientcore.core.implementation.util.JsonSerializer; -import io.clientcore.core.util.serializer.ObjectSerializer; import org.junit.jupiter.api.Test; import java.io.IOException; @@ -20,7 +19,7 @@ * Tests that the {@link JsonSerializer} is able to handle deserializing and serializing {@link JsonSerializable}. */ public class JsonSerializableEndToEndTests { - private static final ObjectSerializer SERIALIZER = new JsonSerializer(); + private static final JsonSerializer SERIALIZER = new JsonSerializer(); @Test public void serialization() throws IOException { diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/utils/ImplUtilsTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/utils/ImplUtilsTests.java new file mode 100644 index 000000000000..c77f26f97954 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/implementation/utils/ImplUtilsTests.java @@ -0,0 +1,214 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.implementation.utils; + +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.shared.TestConfigurationSource; +import io.clientcore.core.utils.CoreUtilsTests; +import io.clientcore.core.utils.configuration.Configuration; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.AbstractMap; +import java.util.Iterator; +import java.util.Map; +import java.util.stream.Stream; + +import static io.clientcore.core.utils.TestUtils.assertArraysEqual; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +/** + * Unit tests for {@link ImplUtils}. + */ +public class ImplUtilsTests { + private static final byte[] BYTES = "Hello world!".getBytes(StandardCharsets.UTF_8); + + private static final byte[] UTF_8_BOM = { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF }; + private static final byte[] UTF_16BE_BOM = { (byte) 0xFE, (byte) 0xFF }; + private static final byte[] UTF_16LE_BOM = { (byte) 0xFF, (byte) 0xFE }; + private static final byte[] UTF_32BE_BOM = { (byte) 0x00, (byte) 0x00, (byte) 0xFE, (byte) 0xFF }; + private static final byte[] UTF_32LE_BOM = { (byte) 0xFF, (byte) 0xFE, (byte) 0x00, (byte) 0x00 }; + + private static final String TIMEOUT_PROPERTY_NAME = "TIMEOUT_PROPERTY_NAME"; + + @ParameterizedTest + @MethodSource("bomAwareToStringSupplier") + public void bomAwareToString(byte[] bytes, String contentType, String expected) { + assertEquals(expected, ImplUtils.bomAwareToString(bytes, 0, bytes.length, contentType)); + } + + private static Stream bomAwareToStringSupplier() { + return Stream.of( + // no content type returns UTF-8 + Arguments.of(BYTES, null, new String(BYTES, StandardCharsets.UTF_8)), + + // no content type returns UTF-8 + Arguments.of(BYTES, "application/text", new String(BYTES, StandardCharsets.UTF_8)), + + // charset=UTF-16E returns UTF-16E + Arguments.of(BYTES, "charset=UTF-16BE", new String(BYTES, StandardCharsets.UTF_16BE)), + + // invalid charset returns UTF-8 + Arguments.of(BYTES, "charset=invalid", new String(BYTES, StandardCharsets.UTF_8)), + + // UTF-8 BOM returns UTF-8 + Arguments.of(addBom(UTF_8_BOM), null, new String(BYTES, StandardCharsets.UTF_8)), + + // UTF-16BE BOM returns UTF-16BE + Arguments.of(addBom(UTF_16BE_BOM), null, new String(BYTES, StandardCharsets.UTF_16BE)), + + // UTF-16LE BOM returns UTF-16LE + Arguments.of(addBom(UTF_16LE_BOM), null, new String(BYTES, StandardCharsets.UTF_16LE)), + + // UTF-32BE BOM returns UTF-32BE + Arguments.of(addBom(UTF_32BE_BOM), null, new String(BYTES, Charset.forName("UTF-32BE"))), + + // UTF-32LE BOM returns UTF-32LE + Arguments.of(addBom(UTF_32LE_BOM), null, new String(BYTES, Charset.forName("UTF-32LE"))), + + // BOM preferred over charset + Arguments.of(addBom(UTF_8_BOM), "charset=UTF-8", new String(BYTES, StandardCharsets.UTF_8)), + Arguments.of(addBom(UTF_8_BOM), "charset=UTF-16BE", new String(BYTES, StandardCharsets.UTF_8))); + } + + private static byte[] addBom(byte[] arr1) { + byte[] mergedArray = new byte[arr1.length + BYTES.length]; + + System.arraycopy(arr1, 0, mergedArray, 0, arr1.length); + System.arraycopy(BYTES, 0, mergedArray, arr1.length, BYTES.length); + + return mergedArray; + } + + @ParameterizedTest + @MethodSource("getDefaultTimeoutFromEnvironmentSupplier") + public void getDefaultTimeoutFromEnvironmentTests(Configuration configuration, Duration defaultTimeout, + ClientLogger logger, Duration expectedTimeout) { + assertEquals(expectedTimeout, + ImplUtils.getDefaultTimeoutFromEnvironment(configuration, TIMEOUT_PROPERTY_NAME, defaultTimeout, logger)); + } + + private static Stream getDefaultTimeoutFromEnvironmentSupplier() { + ClientLogger logger = new ClientLogger(CoreUtilsTests.class); + + return Stream.of( + // Configuration has an empty string timeout property configured. + Arguments.of(new Configuration(new TestConfigurationSource().put(TIMEOUT_PROPERTY_NAME, "")), + Duration.ofMillis(10000), logger, Duration.ofMillis(10000)), + + // Configuration has a value that isn't a valid number. + Arguments.of(new Configuration(new TestConfigurationSource().put(TIMEOUT_PROPERTY_NAME, "ten")), + Duration.ofMillis(10000), logger, Duration.ofMillis(10000)), + + // Configuration has a negative value. + Arguments.of(new Configuration(new TestConfigurationSource().put(TIMEOUT_PROPERTY_NAME, "-10")), + Duration.ofMillis(10000), logger, Duration.ZERO), + + // Configuration has a zero value. + Arguments.of(new Configuration(new TestConfigurationSource().put(TIMEOUT_PROPERTY_NAME, "0")), + Duration.ofMillis(10000), logger, Duration.ZERO), + + // Configuration has a positive value. + Arguments.of(new Configuration(new TestConfigurationSource().put(TIMEOUT_PROPERTY_NAME, "42")), + Duration.ofMillis(10000), logger, Duration.ofMillis(42))); + } + + @Test + public void parseNullQueryParameters() { + assertFalse(new ImplUtils.QueryParameterIterator(null).hasNext()); + } + + @Test + public void parseEmptyQueryParameters() { + assertFalse(new ImplUtils.QueryParameterIterator("").hasNext()); + } + + @ParameterizedTest + @ValueSource(strings = { "key=value", "?key=value" }) + public void parseSimpleQueryParameter(String queryParameters) { + Iterator> iterator = new ImplUtils.QueryParameterIterator(queryParameters); + + assertEquals(new AbstractMap.SimpleImmutableEntry<>("key", "value"), iterator.next()); + assertFalse(iterator.hasNext()); + } + + @ParameterizedTest + @ValueSource(strings = { "key=", "?key=" }) + public void parseSimpleEmptyValueQueryParameter(String queryParameters) { + Iterator> iterator = new ImplUtils.QueryParameterIterator(queryParameters); + + assertEquals(new AbstractMap.SimpleImmutableEntry<>("key", ""), iterator.next()); + assertFalse(iterator.hasNext()); + } + + @ParameterizedTest + @ValueSource(strings = { "key", "?key" }) + public void parseSimpleKeyOnlyQueryParameter(String queryParameters) { + Iterator> iterator = new ImplUtils.QueryParameterIterator(queryParameters); + + assertEquals(new AbstractMap.SimpleImmutableEntry<>("key", ""), iterator.next()); + assertFalse(iterator.hasNext()); + } + + @ParameterizedTest + @ValueSource(strings = { "key=value&key2=", "key=value&key2", "?key=value&key2=", "?key=value&key2" }) + public void parseQueryParameterLastParameterEmpty(String queryParameters) { + Iterator> iterator = new ImplUtils.QueryParameterIterator(queryParameters); + + assertEquals(new AbstractMap.SimpleImmutableEntry<>("key", "value"), iterator.next()); + assertEquals(new AbstractMap.SimpleImmutableEntry<>("key2", ""), iterator.next()); + assertFalse(iterator.hasNext()); + } + + @ParameterizedTest + @ValueSource(strings = { "key=&key2=value2", "key&key2=value2", "?key=&key2=value2", "?key&key2=value2" }) + public void parseQueryParameterFirstParameterEmpty(String queryParameters) { + Iterator> iterator = new ImplUtils.QueryParameterIterator(queryParameters); + + assertEquals(new AbstractMap.SimpleImmutableEntry<>("key", ""), iterator.next()); + assertEquals(new AbstractMap.SimpleImmutableEntry<>("key2", "value2"), iterator.next()); + assertFalse(iterator.hasNext()); + } + + @ParameterizedTest + @ValueSource( + strings = { + "key=value&key2=&key3=value3", + "?key=value&key2=&key3=value3", + "key=value&key2&key3=value3", + "?key=value&key2&key3=value3", }) + public void parseQueryParameterMiddleParameterEmpty(String queryParameters) { + Iterator> iterator = new ImplUtils.QueryParameterIterator(queryParameters); + + assertEquals(new AbstractMap.SimpleImmutableEntry<>("key", "value"), iterator.next()); + assertEquals(new AbstractMap.SimpleImmutableEntry<>("key2", ""), iterator.next()); + assertEquals(new AbstractMap.SimpleImmutableEntry<>("key3", "value3"), iterator.next()); + assertFalse(iterator.hasNext()); + } + + @ParameterizedTest + @MethodSource("byteBufferToArraySupplier") + public void byteBufferToArray(ByteBuffer buffer, byte[] expected) { + assertArraysEqual(expected, ImplUtils.byteBufferToArray(buffer)); + } + + private static Stream byteBufferToArraySupplier() { + return Stream.of( + // empty buffer returns empty array + Arguments.of(ByteBuffer.allocate(0), new byte[0]), + + // non-empty buffer returns byte array + Arguments.of(ByteBuffer.wrap(BYTES), BYTES), + + // direct buffer + Arguments.of(ByteBuffer.allocateDirect(BYTES.length).put(BYTES).position(0), BYTES)); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/instrumentation/logging/ClientLoggerTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/instrumentation/logging/ClientLoggerTests.java index e5c1162ac44e..1e0e74c85221 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/instrumentation/logging/ClientLoggerTests.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/instrumentation/logging/ClientLoggerTests.java @@ -6,10 +6,7 @@ import io.clientcore.core.implementation.AccessibleByteArrayOutputStream; import io.clientcore.core.implementation.instrumentation.DefaultLogger; import io.clientcore.core.instrumentation.InstrumentationContext; -import io.clientcore.core.serialization.json.JsonOptions; -import io.clientcore.core.serialization.json.JsonProviders; import io.clientcore.core.serialization.json.JsonReader; -import io.clientcore.core.instrumentation.logging.ClientLogger.LogLevel; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -250,13 +247,13 @@ public void logWithNewLine() { public void logWithNullSupplier(LogLevel logLevel) { ClientLogger logger = setupLogLevelAndGetLogger(logLevel); if (logLevel.equals(LogLevel.ERROR)) { - logger.atError().log(null); + logger.atError().log(); } else if (logLevel.equals(LogLevel.WARNING)) { - logger.atWarning().log(null); + logger.atWarning().log(); } else if (logLevel.equals(LogLevel.INFORMATIONAL)) { - logger.atInfo().log(null); + logger.atInfo().log(); } else if (logLevel.equals(LogLevel.VERBOSE)) { - logger.atVerbose().log(null); + logger.atVerbose().log(); } else { throw new IllegalArgumentException("Unknown log level: " + logLevel); } @@ -440,7 +437,7 @@ public void logWithGlobalContextMessageSupplier(LogLevel logLevelToConfigure) { public void logWithContextNullMessage() { ClientLogger logger = setupLogLevelAndGetLogger(LogLevel.VERBOSE); - logger.atVerbose().addKeyValue("connectionId", "foo").addKeyValue("linkName", true).log(null); + logger.atVerbose().addKeyValue("connectionId", "foo").addKeyValue("linkName", true).log(); Map expectedMessage = new HashMap<>(); expectedMessage.put("connectionId", "foo"); @@ -503,7 +500,7 @@ public void logWithGlobalContextIsEscaped() { public void logWithContextNullSupplier() { ClientLogger logger = setupLogLevelAndGetLogger(LogLevel.INFORMATIONAL); - logger.atError().addKeyValue("connectionId", "foo").addKeyValue("linkName", (String) null).log(null); + logger.atError().addKeyValue("connectionId", "foo").addKeyValue("linkName", (String) null).log(); Map expectedMessage = new HashMap<>(); expectedMessage.put("connectionId", "foo"); @@ -1111,7 +1108,7 @@ public String toString() { } private Map fromJson(String str) { - try (JsonReader reader = JsonProviders.createReader(str, new JsonOptions())) { + try (JsonReader reader = JsonReader.fromString(str)) { return reader.readMap(JsonReader::readUntyped); } catch (IOException e) { throw new UncheckedIOException(e); diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/instrumentation/logging/InstrumentationTestUtils.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/instrumentation/logging/InstrumentationTestUtils.java index 7ec1c2edbad5..a809e3690bee 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/instrumentation/logging/InstrumentationTestUtils.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/instrumentation/logging/InstrumentationTestUtils.java @@ -7,19 +7,20 @@ import io.clientcore.core.implementation.instrumentation.DefaultLogger; import io.clientcore.core.instrumentation.InstrumentationContext; import io.clientcore.core.instrumentation.tracing.Span; -import io.clientcore.core.serialization.json.JsonOptions; -import io.clientcore.core.serialization.json.JsonProviders; import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.utils.CoreUtils; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; +import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.UUID; +import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -35,8 +36,7 @@ public static void assertValidTraceId(String traceId) { assertTrue(traceId.matches("[0-9a-f]{32}")); } - public static ClientLogger setupLogLevelAndGetLogger(ClientLogger.LogLevel logLevelToSet, - OutputStream logCaptureStream) { + public static ClientLogger setupLogLevelAndGetLogger(LogLevel logLevelToSet, OutputStream logCaptureStream) { DefaultLogger logger = new DefaultLogger(ClientLogger.class.getName(), new PrintStream(logCaptureStream), logLevelToSet); @@ -45,13 +45,19 @@ public static ClientLogger setupLogLevelAndGetLogger(ClientLogger.LogLevel logLe public static List> parseLogMessages(AccessibleByteArrayOutputStream logCaptureStream) { String fullLog = logCaptureStream.toString(StandardCharsets.UTF_8); - return fullLog.lines().map(InstrumentationTestUtils::parseLogLine).toList(); + // Changing this from String.lines() has a slight runtime difference where lines() won't have any output if the + // String is empty where as String.split("\\R") will have an empty string in the array. + // Filter out any empty lines. + return Arrays.stream(fullLog.split("\\R")) + .filter(line -> !CoreUtils.isNullOrEmpty(line)) // Filter out empty lines + .map(InstrumentationTestUtils::parseLogLine) + .collect(Collectors.toList()); } private static Map parseLogLine(String logLine) { String messageJson = logLine.substring(logLine.indexOf(" - ") + 3); System.out.println(messageJson); - try (JsonReader reader = JsonProviders.createReader(messageJson, new JsonOptions())) { + try (JsonReader reader = JsonReader.fromString(messageJson)) { return reader.readMap(JsonReader::readUntyped); } catch (IOException e) { throw new UncheckedIOException(e); diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/models/CloudEventTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/CloudEventTests.java new file mode 100644 index 000000000000..2c7a69ad630a --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/CloudEventTests.java @@ -0,0 +1,495 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models; + +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonSerializable; +import io.clientcore.core.serialization.json.JsonSerializer; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.serialization.json.JsonWriter; +import io.clientcore.core.serialization.json.models.JsonArray; +import io.clientcore.core.serialization.json.models.JsonElement; +import io.clientcore.core.serialization.json.models.JsonObject; +import io.clientcore.core.utils.CoreUtils; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import static io.clientcore.core.utils.TestUtils.assertArraysEqual; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +public class CloudEventTests { + private static final JsonSerializer SERIALIZER = new JsonSerializer(); + private static final Type MAP_STRING_OBJECT + = CoreUtils.createParameterizedType(Map.class, String.class, Object.class); + + @Test + public void testRoundTripCloudEvents() throws IOException { + final String cloudEventJson = getTestPayloadFromFile("CloudEventDifferentDataTypes.json"); + final CloudEvent cloudEvent = CloudEvent.fromString(cloudEventJson).get(0); + final Map map = new LinkedHashMap<>(); + map.put("str", "str value"); + map.put("number", 1.3); + map.put("integer", 1); + map.put("bool", true); + map.put("null", null); + map.put("array", Arrays.asList(1, 2, 3)); + map.put("object", Collections.singletonMap("okey", "ovalue")); + + // Check if deserialized CloudEvent has the correct properties. + assertNotNull(cloudEvent); + assertEquals("/testresource", cloudEvent.getSource()); + assertEquals("Microsoft.MockPublisher.TestEvent", cloudEvent.getType()); + assertEquals(OffsetDateTime.parse("2020-07-21T18:41:31.166Z"), cloudEvent.getTime()); + assertEquals("9ddf9b10-fe3d-4a16-94bc-c0298924ded1", cloudEvent.getId()); + assertEquals("1.0", cloudEvent.getSpecVersion()); + assertEquals("testsubject", cloudEvent.getSubject()); + assertEquals("/testschema", cloudEvent.getDataSchema()); + assertEquals("application/json", cloudEvent.getDataContentType()); + assertEquals(map, cloudEvent.getData().toObject(Map.class, SERIALIZER)); + + final String serialized = cloudEvent.toJsonString(); + + // Check if the original map matches the raw deserialized JsonNode from the serialized String + assertMapAndJsonNode(map, serialized); + + // Check if the original CloudEvent matches the deserialized CloudEvent from the serialized String + final CloudEvent cloudEvent2 = CloudEvent.fromString(serialized).get(0); + assertEquals("/testresource", cloudEvent2.getSource()); + assertEquals("Microsoft.MockPublisher.TestEvent", cloudEvent2.getType()); + assertEquals(OffsetDateTime.parse("2020-07-21T18:41:31.166Z"), cloudEvent2.getTime()); + assertEquals("9ddf9b10-fe3d-4a16-94bc-c0298924ded1", cloudEvent2.getId()); + assertEquals("1.0", cloudEvent2.getSpecVersion()); + assertEquals("testsubject", cloudEvent2.getSubject()); + assertEquals("/testschema", cloudEvent2.getDataSchema()); + assertEquals("application/json", cloudEvent2.getDataContentType()); + + final BinaryData data2 = cloudEvent.getData(); + final Map deserializedData2 = data2.toObject(MAP_STRING_OBJECT, SERIALIZER); + + // Check if the original map matches the deserialized data map from the serialized String + assertEquals(map, deserializedData2); + } + + @Test + public void deserializeCloudEventsFailValidation() throws IOException { + final String cloudEventJson = getTestPayloadFromFile("CloudEventNoType.json"); + assertThrows(IllegalArgumentException.class, () -> { + CloudEvent.fromString(cloudEventJson); + }); + } + + @Test + public void deserializeCloudEventsSkipValidation() throws IOException { + final String cloudEventJson = getTestPayloadFromFile("CloudEventNoType.json"); + assertDoesNotThrow(() -> { + CloudEvent.fromString(cloudEventJson, true); + }); + } + + @Test + public void deserializeCloudEventWithoutArrayBrackets() throws IOException { + final String cloudEventJson = getTestPayloadFromFile("CloudEventNoArray.json"); + + final List events = CloudEvent.fromString(cloudEventJson); + + assertNotNull(events); + assertEquals(1, events.size()); + + final ContosoItemReceivedEventData data + = events.get(0).getData().toObject(ContosoItemReceivedEventData.class, SERIALIZER); + assertNotNull(data); + + assertEquals("512d38b6-c7b8-40c8-89fe-f46f9e9622b6", data.getItemSku()); + + final Map additionalProperties = events.get(0).getExtensionAttributes(); + + assertNotNull(additionalProperties); + assertTrue(additionalProperties.containsKey("foo")); + assertEquals("bar", additionalProperties.get("foo")); + } + + @Test + public void deserializeCloudEventWithNullData() throws IOException { + final String cloudEventJson = getTestPayloadFromFile("CloudEventNullData.json"); + + final List events = CloudEvent.fromString(cloudEventJson); + + assertNotNull(events); + assertEquals(1, events.size()); + + assertNull(events.get(0).getData()); + } + + @Test + public void deserializeCloudEventWithBinaryData() throws IOException { + final String cloudEventJson = getTestPayloadFromFile("CloudEventBinaryData.json"); + final List events = CloudEvent.fromString(cloudEventJson); + + assertNotNull(events); + assertEquals(1, events.size()); + + final byte[] eventData = events.get(0).getData().toBytes(); + + assertNotNull(eventData); + + assertArraysEqual(Base64.getDecoder().decode("c2FtcGxlYmluYXJ5ZGF0YQ=="), eventData); + } + + @Test + public void deserializeCloudEventJsonData() throws IOException { + final String cloudEventJson = getTestPayloadFromFile("CloudEventJsonData.json"); + + final List events = CloudEvent.fromString(cloudEventJson); + + assertNotNull(events); + assertEquals(1, events.size()); + + final ContosoItemReceivedEventData data + = events.get(0).getData().toObject(ContosoItemReceivedEventData.class, SERIALIZER); + assertNotNull(data); + + assertEquals("512d38b6-c7b8-40c8-89fe-f46f9e9622b6", data.getItemSku()); + + final Map additionalProperties = events.get(0).getExtensionAttributes(); + + assertNotNull(additionalProperties); + assertTrue(additionalProperties.containsKey("foo")); + assertEquals("bar", additionalProperties.get("foo")); + } + + @Test + public void deserializeCloudEventXmlData() throws IOException { + final String cloudEventJson = getTestPayloadFromFile("CloudEventXmlData.json"); + + final List events = CloudEvent.fromString(cloudEventJson); + + assertNotNull(events); + assertEquals(1, events.size()); + + assertEquals(5, events.get(0).getExtensionAttributes().get("comexampleothervalue")); + + final String xmlData = events.get(0).getData().toObject(String.class, SERIALIZER); + + assertEquals("", xmlData); + } + + @Test + public void serializeByteData() throws IOException { + final String dataPayload = "AAA"; + final BinaryData binaryData = BinaryData.fromBytes(dataPayload.getBytes(StandardCharsets.UTF_8)); + final CloudEvent cloudEvent + = new CloudEvent("/testSource", "CloudEvent.Test", binaryData, CloudEventDataFormat.BYTES, "bytes") + .setDataSchema("/testSchema") + .setSubject("testSubject") + .setTime(OffsetDateTime.now()) + .setSpecVersion("1.0") + .addExtensionAttribute("foo", "value"); + + final String serializedString = cloudEvent.toJsonString(); + final CloudEvent deserializedCloudEvent = CloudEvent.fromString(serializedString).get(0); + assertEquals(cloudEvent.getData().toString(), deserializedCloudEvent.getData().toString()); + assertEquals(dataPayload, cloudEvent.getData().toString()); + compareCloudEventContent(cloudEvent, deserializedCloudEvent); + } + + @Test + public void serializeJsonData() throws IOException { + final Map mapData = new LinkedHashMap<>(); + mapData.put("Field1", "Value1"); + mapData.put("Field2", "Value2"); + + final BinaryData binaryData = BinaryData.fromObject(mapData, SERIALIZER); + final CloudEvent cloudEvent = new CloudEvent("/testSource", "CloudEvent.Test", binaryData, + CloudEventDataFormat.JSON, "application/json").setDataSchema("/testSchema") + .setSubject("testSubject") + .setTime(OffsetDateTime.now()) + .setSpecVersion("1.0") + .addExtensionAttribute("foo", "value"); + + final String serializedString = cloudEvent.toJsonString(); + final CloudEvent deserializedCloudEvent = CloudEvent.fromString(serializedString).get(0); + assertEquals(mapData, deserializedCloudEvent.getData().toObject(MAP_STRING_OBJECT, SERIALIZER)); + compareCloudEventContent(cloudEvent, deserializedCloudEvent); + } + + @ParameterizedTest + @MethodSource("primitiveDataValues") + public void serializePrimitiveData(Object dataValue) throws IOException { + final BinaryData binaryData = BinaryData.fromObject(dataValue, SERIALIZER); + final CloudEvent cloudEvent = new CloudEvent("/testSource", "CloudEvent.Test", binaryData, + CloudEventDataFormat.JSON, "application/json").setDataSchema("/testSchema") + .setSubject("testSubject") + .setTime(OffsetDateTime.now()) + .setSpecVersion("1.0"); + + final String serializedString = cloudEvent.toJsonString(); + try (JsonReader jsonReader = JsonReader.fromString(serializedString)) { + // check the "data" value of the serialized String + final JsonElement jsonNode = JsonElement.fromJson(jsonReader).asObject().getProperty("data"); + if (jsonNode.isNumber()) { + assertEquals(dataValue, jsonNode.asNumber().getValue()); + } else if (jsonNode.isBoolean()) { + assertEquals(dataValue, jsonNode.asBoolean().getValue()); + } else if (jsonNode.isString()) { + assertEquals(dataValue, jsonNode.asString().getValue()); + } else { + fail("Wrong JsonNode type. The serialized String might be wrong."); + } + + // Deserialized the serialized String and check back the CloudEvent.getData() + final CloudEvent deserializedCloudEvent = CloudEvent.fromString(serializedString).get(0); + assertEquals(dataValue, deserializedCloudEvent.getData().toObject(dataValue.getClass(), SERIALIZER)); + compareCloudEventContent(cloudEvent, deserializedCloudEvent); + } + } + + private static Stream primitiveDataValues() { + return Stream.of(Arguments.of("str"), Arguments.of(1), Arguments.of(1.1), Arguments.of(true), + Arguments.of(false)); + } + + @Test + public void serializeStringDataAsObject() throws IOException { + final String dataPayload = "AAA"; + final BinaryData binaryData = BinaryData.fromObject(dataPayload, SERIALIZER); + final CloudEvent cloudEvent = new CloudEvent("/testSource", "CloudEvent.Test", binaryData, + CloudEventDataFormat.JSON, "application/json").setDataSchema("/testSchema") + .setSubject("testSubject") + .setTime(OffsetDateTime.now()) + .setSpecVersion("1.0") + .addExtensionAttribute("foo", "value"); + + final String serializedString = cloudEvent.toJsonString(); + final CloudEvent deserializedCloudEvent = CloudEvent.fromString(serializedString).get(0); + assertEquals(dataPayload, deserializedCloudEvent.getData().toObject(String.class, SERIALIZER)); + compareCloudEventContent(cloudEvent, deserializedCloudEvent); + } + + @Test + public void serializeStringDataNonJsonLiteral() { + final String dataPayload = "AAA"; + final BinaryData binaryData = BinaryData.fromString(dataPayload); + assertThrows(IllegalArgumentException.class, () -> { + new CloudEvent("/testSource", "CloudEvent.Test", binaryData, CloudEventDataFormat.JSON, "application/json") + .setDataSchema("/testSchema") + .setSubject("testSubject") + .setTime(OffsetDateTime.now()) + .setSpecVersion("1.0") + .addExtensionAttribute("foo", "value"); + }); + } + + @Test + public void serializeStringDataJsonLiteral() throws IOException { + final BinaryData binaryData = BinaryData.fromString("{\"foo\":\"value\"}"); + final CloudEvent cloudEvent = new CloudEvent("/testSource", "CloudEvent.Test", binaryData, + CloudEventDataFormat.JSON, "application/json").setDataSchema("/testSchema") + .setSubject("testSubject") + .setTime(OffsetDateTime.now()) + .setSpecVersion("1.0") + .addExtensionAttribute("foo", "value"); + + final String serializedString = cloudEvent.toJsonString(); + final CloudEvent deserializedCloudEvent = CloudEvent.fromString(serializedString).get(0); + assertEquals("{\"foo\":\"value\"}", deserializedCloudEvent.getData().toString()); + final Map deserializedMap + = deserializedCloudEvent.getData().toObject(MAP_STRING_OBJECT, SERIALIZER); + assertEquals("value", deserializedMap.get("foo")); + compareCloudEventContent(cloudEvent, deserializedCloudEvent); + } + + @Test + public void serializeNullBinaryData() throws IOException { + final CloudEvent cloudEvent + = new CloudEvent("/testSource", "CloudEvent.Test", null, CloudEventDataFormat.JSON, "application/json") + .setDataSchema("/testSchema") + .setSubject("testSubject") + .setTime(OffsetDateTime.now()) + .setSpecVersion("1.0") + .addExtensionAttribute("foo", "value"); + + final String serializedString = cloudEvent.toJsonString(); + final CloudEvent deserializedCloudEvent = CloudEvent.fromString(serializedString).get(0); + assertNull(deserializedCloudEvent.getData()); + assertEquals("value", deserializedCloudEvent.getExtensionAttributes().get("foo")); + compareCloudEventContent(cloudEvent, deserializedCloudEvent); + } + + @Test + public void serializeBinaryDataFromNull() throws IOException { + final CloudEvent cloudEvent + = new CloudEvent("/testSource", "CloudEvent.Test", null, CloudEventDataFormat.JSON, "application/json") + .setDataSchema("/testSchema") + .setSubject("testSubject") + .setTime(OffsetDateTime.now()) + .setSpecVersion("1.0") + .addExtensionAttribute("foo", "value"); + + final String serializedString = cloudEvent.toJsonString(); + final CloudEvent deserializedCloudEvent = CloudEvent.fromString(serializedString).get(0); + assertNull(deserializedCloudEvent.getData()); + assertEquals("value", deserializedCloudEvent.getExtensionAttributes().get("foo")); + compareCloudEventContent(cloudEvent, deserializedCloudEvent); + } + + @ParameterizedTest + @MethodSource("addAttributeIllegalArgumentTestData") + public void addAttributeIllegalArgument(String attributeName, Object value) { + assertThrows(IllegalArgumentException.class, () -> { + new CloudEvent("/testsrouce", "testtype", BinaryData.fromObject("str", SERIALIZER), + CloudEventDataFormat.JSON, "application/json").addExtensionAttribute(attributeName, value); + }); + } + + private static Stream addAttributeIllegalArgumentTestData() { + return Stream.of(Arguments.of("a_b", "value"), Arguments.of("Ab", 1)); + } + + @ParameterizedTest + @MethodSource("addAttributeNullPointerTestData") + public void addAttributeNullPointer(String attributeName, Object value) { + assertThrows(NullPointerException.class, () -> { + new CloudEvent("/testsrouce", "testtype", BinaryData.fromObject("str", SERIALIZER), + CloudEventDataFormat.JSON, "application/json").addExtensionAttribute(attributeName, value); + }); + } + + private static Stream addAttributeNullPointerTestData() { + return Stream.of(Arguments.of(null, "value"), Arguments.of("name", null)); + } + + @Test + public void addAttribute() { + assertDoesNotThrow(() -> { + new CloudEvent("/testsrouce", "testtype", BinaryData.fromObject("str", SERIALIZER), + CloudEventDataFormat.JSON, "application/json").addExtensionAttribute("name", "value"); + }); + } + + @Test + public void eventsHaveATime() { + CloudEvent event = new CloudEvent("/source", "type", BinaryData.fromObject("data", SERIALIZER), + CloudEventDataFormat.JSON, "application/json"); + assertNotNull(event.getTime()); + } + + @Test + public void eventsCanHaveTimeUnset() { + CloudEvent event = new CloudEvent("/source", "type", BinaryData.fromObject("data", SERIALIZER), + CloudEventDataFormat.JSON, "application/json").setTime(null); + assertNull(event.getTime()); + } + + private String getTestPayloadFromFile(String fileName) throws IOException { + final ClassLoader classLoader = getClass().getClassLoader(); + try (InputStream inputStream = classLoader.getResourceAsStream("CloudEvent/" + fileName)) { + final byte[] bytes = new byte[inputStream.available()]; + inputStream.read(bytes); + return new String(bytes); + } + } + + private void compareCloudEventContent(CloudEvent cloudEvent, CloudEvent deserializedCloudEvent) { + assertEquals(cloudEvent.getSpecVersion(), deserializedCloudEvent.getSpecVersion()); + assertEquals(cloudEvent.getDataSchema(), deserializedCloudEvent.getDataSchema()); + assertEquals(cloudEvent.getDataContentType(), deserializedCloudEvent.getDataContentType()); + assertEquals(cloudEvent.getId(), deserializedCloudEvent.getId()); + assertEquals(cloudEvent.getExtensionAttributes(), deserializedCloudEvent.getExtensionAttributes()); + assertEquals(cloudEvent.getSource(), deserializedCloudEvent.getSource()); + assertEquals(cloudEvent.getSubject(), deserializedCloudEvent.getSubject()); + assertEquals(cloudEvent.getTime().toInstant(), deserializedCloudEvent.getTime().toInstant()); + assertEquals(cloudEvent.getType(), deserializedCloudEvent.getType()); + } + + private void assertMapAndJsonNode(Map map, String jsonString) throws IOException { + try (JsonReader jsonReader = JsonReader.fromString(jsonString)) { + JsonObject object = JsonObject.fromJson(jsonReader); + assertMapAndJsonNode(map, object.getProperty("data")); + } + } + + @SuppressWarnings("unchecked") + private void assertMapAndJsonNode(Map map, JsonElement jsonNode) { + map.forEach((key, value) -> { + if (value instanceof Map) { + assertMapAndJsonNode((Map) map.get(key), jsonNode.asObject().getProperty(key)); + } else if (value instanceof String) { + assertEquals(value, jsonNode.asObject().getProperty(key).asString().getValue()); + } else if (value instanceof Boolean) { + assertEquals(value, jsonNode.asObject().getProperty(key).asBoolean().getValue()); + } else if (value instanceof Integer || value instanceof Double) { + assertEquals(value, jsonNode.asObject().getProperty(key).asNumber().getValue()); + } else if (value instanceof List) { + List elements = (List) value; + JsonArray arrayNode = jsonNode.asObject().getProperty(key).asArray(); + for (int i = 0; i < elements.size(); i++) { + assertEquals(elements.get(i), arrayNode.getElement(i).asNumber().getValue()); + } + } + }); + } + + public static class ContosoItemReceivedEventData implements JsonSerializable { + private String itemSku; + private String itemUri; + + public String getItemSku() { + return this.itemSku; + } + + public String getItemUri() { + return this.itemUri; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject() + .writeStringField("itemSku", this.itemSku) + .writeStringField("itemUri", this.itemUri) + .writeEndObject(); + } + + public static ContosoItemReceivedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ContosoItemReceivedEventData eventData = new ContosoItemReceivedEventData(); + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + + if ("itemSku".equals(fieldName)) { + eventData.itemSku = reader.getString(); + } else if ("itemUri".equals(fieldName)) { + eventData.itemUri = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return eventData; + }); + } + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/models/HttpBinHeaders.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/HttpBinHeaders.java index 43205e180aa6..b8df2e97a226 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/models/HttpBinHeaders.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/HttpBinHeaders.java @@ -3,7 +3,7 @@ package io.clientcore.core.models; -import io.clientcore.core.implementation.util.DateTimeRfc1123; +import io.clientcore.core.utils.DateTimeRfc1123; import io.clientcore.core.serialization.json.JsonReader; import io.clientcore.core.serialization.json.JsonSerializable; import io.clientcore.core.serialization.json.JsonToken; diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/models/binarydata/BinaryDataTest.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/binarydata/BinaryDataTest.java new file mode 100644 index 000000000000..2902f0ac6d52 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/binarydata/BinaryDataTest.java @@ -0,0 +1,638 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models.binarydata; + +import io.clientcore.core.implementation.utils.IterableOfByteBuffersInputStream; +import io.clientcore.core.models.MockFile; +import io.clientcore.core.models.MockPath; +import io.clientcore.core.models.Person; +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonSerializable; +import io.clientcore.core.serialization.json.JsonSerializer; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.serialization.json.JsonWriter; +import org.junit.jupiter.api.Named; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.io.ByteArrayInputStream; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.nio.ReadOnlyBufferException; +import java.nio.channels.FileChannel; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.UUID; +import java.util.function.Supplier; +import java.util.stream.Stream; + +import static io.clientcore.core.utils.TestUtils.assertArraysEqual; +import static io.clientcore.core.utils.TestUtils.fillArray; +import static io.clientcore.core.utils.TestUtils.readStream; +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.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Test class for {@link BinaryData}. + */ +public class BinaryDataTest { + private static final JsonSerializer SERIALIZER = new JsonSerializer(); + private static final byte[] RANDOM_DATA; + + static { + RANDOM_DATA = new byte[1024 * 1024]; // 1 MB + + fillArray(RANDOM_DATA); + } + + @Test + public void fromCustomObject() throws IOException { + // Arrange + final Person actualValue = new Person().setName("John Doe").setAge(50); + final Person expectedValue = new Person().setName("John Doe").setAge(50); + + // Act + final BinaryData data = BinaryData.fromObject(actualValue, SERIALIZER); + + // Assert + assertEquals(expectedValue, data.toObject(expectedValue.getClass(), SERIALIZER)); + } + + @Test + public void fromDouble() throws IOException { + // Arrange + final Double actualValue = Double.valueOf("10.1"); + final Double expectedValue = Double.valueOf("10.1"); + + // Act + final BinaryData data = BinaryData.fromObject(actualValue, SERIALIZER); + + // Assert + assertEquals(expectedValue, data.toObject(expectedValue.getClass(), SERIALIZER)); + } + + @Test + public void anyTypeToByteArray() { + // Assert + final Person actualValue = new Person().setName("John Doe").setAge(50); + final byte[] expectedValue = "{\"name\":\"John Doe\",\"age\":50}".getBytes(StandardCharsets.UTF_8); + + // Act + final BinaryData data = BinaryData.fromObject(actualValue, SERIALIZER); + + // Assert + assertArraysEqual(expectedValue, data.toBytes()); + } + + @Test + public void createFromString() { + // Arrange + final String expected = "Doe"; + + // Act + final BinaryData data = BinaryData.fromString(expected); + + // Assert + assertArraysEqual(expected.getBytes(), data.toBytes()); + assertEquals(expected, data.toString()); + } + + @Test + public void createFromByteArray() { + // Arrange + final byte[] expected = "Doe".getBytes(StandardCharsets.UTF_8); + + // Act + final BinaryData data = BinaryData.fromBytes(expected); + + // Assert + assertArraysEqual(expected, data.toBytes()); + } + + @Test + public void createFromNullStream() { + assertThrows(NullPointerException.class, () -> BinaryData.fromStream(null)); + } + + @Test + public void createFromNullByteArray() { + assertThrows(NullPointerException.class, () -> BinaryData.fromBytes(null)); + } + + @Test + public void createFromNullObject() { + BinaryData binaryData = BinaryData.fromObject(null, SERIALIZER); + + assertNull(binaryData.toBytes()); + assertNull(binaryData.getLength()); + } + + @Test + public void createFromNullFile() { + assertThrows(NullPointerException.class, () -> BinaryData.fromFile(null)); + } + + @Test + public void createFromStream() { + // Arrange + final byte[] expected = "Doe".getBytes(StandardCharsets.UTF_8); + + // Act + BinaryData data = BinaryData.fromStream(new ByteArrayInputStream(expected)); + + // Assert + assertArraysEqual(expected, data.toBytes()); + } + + @Test + public void createFromEmptyStream() { + // Arrange + final byte[] expected = "".getBytes(); + + // Act + BinaryData data = BinaryData.fromStream(new ByteArrayInputStream(expected)); + + // Assert + assertArraysEqual(expected, data.toBytes()); + } + + @Test + public void createFromEmptyString() { + // Arrange + final String expected = ""; + + // Act + final BinaryData data = BinaryData.fromString(expected); + + // Assert + assertArraysEqual(expected.getBytes(), data.toBytes()); + assertEquals(expected, data.toString()); + } + + @Test + public void createFromEmptyByteArray() { + // Arrange + final byte[] expected = new byte[0]; + + // Act + final BinaryData data = BinaryData.fromBytes(expected); + + // Assert + assertArraysEqual(expected, data.toBytes()); + } + + @Test + public void createFromNullString() { + // Arrange + final String expected = null; + + // Arrange & Act + assertThrows(NullPointerException.class, () -> BinaryData.fromString(expected)); + } + + // @Test + // public void createFromListByteBuffer() { + // final byte[] data = "Doe".getBytes(StandardCharsets.UTF_8); + // final List list = Arrays.asList(ByteBuffer.wrap(data), ByteBuffer.wrap(data)); + // final byte[] expected = "DoeDoe".getBytes(StandardCharsets.UTF_8); + // + // BinaryData binaryData = BinaryData.fromListByteBuffer(list); + // + // assertArraysEqual(expected, binaryData.toBytes()); + // } + + @Test + public void toReadOnlyByteBufferThrowsOnMutation() { + BinaryData binaryData = BinaryData.fromString("Hello"); + + assertThrows(ReadOnlyBufferException.class, () -> binaryData.toByteBuffer().put((byte) 0)); + } + + @Test + public void fromCustomObjectWithDefaultSerializer() throws IOException { + // Arrange + final Person actualValue = new Person().setName("John Doe").setAge(50); + final Person expectedValue = new Person().setName("John Doe").setAge(50); + + // Act + final BinaryData data = BinaryData.fromObject(actualValue); + + // Assert + assertEquals(expectedValue, data.toObject(expectedValue.getClass())); + } + + @Test + public void fromDoubleWithDefaultSerializer() throws IOException { + // Arrange + final Double actualValue = Double.valueOf("10.1"); + final Double expectedValue = Double.valueOf("10.1"); + + // Act + final BinaryData data = BinaryData.fromObject(actualValue); + + // Assert + assertEquals(expectedValue, data.toObject(expectedValue.getClass())); + } + + @Test + public void anyTypeToByteArrayWithDefaultSerializer() { + // Assert + final Person actualValue = new Person().setName("John Doe").setAge(50); + final byte[] expectedValue = "{\"name\":\"John Doe\",\"age\":50}".getBytes(StandardCharsets.UTF_8); + + // Act + final BinaryData data = BinaryData.fromObject(actualValue); + + // Assert + assertArraysEqual(expectedValue, data.toBytes()); + } + + @Test + public void testFromFile() throws Exception { + Path file = Files.createTempFile("binaryDataFromFile" + UUID.randomUUID(), ".txt"); + + file.toFile().deleteOnExit(); + + Files.write(file, "The quick brown fox jumps over the lazy dog".getBytes(StandardCharsets.UTF_8)); + + BinaryData data = BinaryData.fromFile(file); + + assertEquals("The quick brown fox jumps over the lazy dog", data.toString()); + } + + @Test + public void testFromLargeFileStream() throws Exception { + int chunkSize = 1024 * 1024; // 1 MB + long numberOfChunks = 2200L; // 2200 MB total + + MockFile mockFile + = new MockFile("binaryDataFromFile" + UUID.randomUUID() + ".txt", RANDOM_DATA, numberOfChunks * chunkSize); + FileBinaryData fileContent = new MockFileBinaryData(new MockPath(mockFile), 32768, null, null); + + try (InputStream is = fileContent.toStream()) { + // Read and validate in chunks to optimize validation compared to byte-by-byte checking. + byte[] buffer = new byte[4096]; + long totalRead = 0; + int read; + int idx = 0; + + while ((read = is.read(buffer)) >= 0) { + totalRead += read; + + // This may look a bit odd but ByteBuffer has array-based comparison optimizations that aren't available + // in Arrays until Java 9+. Wrapping the bytes chunk that was expected to be read and the read range + // will allow for many bytes to be validated at once instead of byte-by-byte. + assertEquals(ByteBuffer.wrap(RANDOM_DATA, idx, read), ByteBuffer.wrap(buffer, 0, read)); + + idx = (idx + read) % chunkSize; + } + + assertEquals((long) chunkSize * numberOfChunks, totalRead); + } + } + + @ParameterizedTest + @ValueSource(ints = { 10, 113, 1024, 1024 + 113, 10 * 1024 * 1024 + 13 }) + public void testFromFileSegment(int size) throws Exception { + int leftPadding = 10 * 1024 + 13; + int rightPadding = 10 * 1024 + 27; + byte[] fullFile = new byte[size + leftPadding + rightPadding]; + + fillArray(fullFile); + + MockFile mockFile + = new MockFile("binaryDataFromFileSegment" + UUID.randomUUID() + ".txt", fullFile, fullFile.length); + FileBinaryData fileContent + = new MockFileBinaryData(new MockPath(mockFile), 8192, (long) leftPadding, (long) size); + + assertEquals(size, fileContent.getLength()); + + byte[] actualBytes = fileContent.toBytes(); + + assertArraysEqual(fullFile, leftPadding, size, actualBytes, actualBytes.length); + + actualBytes = new byte[size]; + + try (InputStream is = fileContent.toStream()) { + int totalRead = 0; + int nRead; + byte[] buffer = new byte[4096]; + + while ((nRead = is.read(buffer, 0, buffer.length)) != -1) { + System.arraycopy(buffer, 0, actualBytes, totalRead, nRead); + + totalRead += nRead; + } + } + + assertArraysEqual(fullFile, leftPadding, size, actualBytes, actualBytes.length); + } + + @ParameterizedTest + @MethodSource("createNonRetryableBinaryData") + public void testNonReplayableContentTypes(Supplier binaryDataSupplier) throws IOException { + assertFalse(binaryDataSupplier.get().isReplayable()); + + BinaryData data = binaryDataSupplier.get(); + byte[] firstStreamConsumption = readStream(data.toStream()); + byte[] secondStreamConsumption = readStream(data.toStream()); + + // Either flux or stream consumption is not replayable. + assertFalse(Arrays.equals(firstStreamConsumption, secondStreamConsumption)); + } + + public static Stream createNonRetryableBinaryData() { + byte[] bytes = new byte[1024]; + + fillArray(bytes); + + return Stream.of( + Arguments.of(Named.named("stream", + (Supplier) () -> BinaryData.fromStream(new ByteArrayInputStream(bytes)))), + Arguments.of(Named.named("byte array stream", + (Supplier) () -> BinaryData.fromStream(new ByteArrayInputStream(bytes), null)))); + } + + @ParameterizedTest + @MethodSource("createRetryableBinaryData") + public void testReplayableContentTypes(Supplier binaryDataSupplier, byte[] expectedBytes) + throws IOException { + + assertTrue(binaryDataSupplier.get().isReplayable()); + + // Check toStream consumption + BinaryData data = binaryDataSupplier.get(); + byte[] firstConsumption = readStream(data.toStream()); + byte[] secondConsumption = readStream(data.toStream()); + assertArraysEqual(firstConsumption, secondConsumption); + assertArraysEqual(expectedBytes, firstConsumption); + + // Check toByteBuffer consumption + data = binaryDataSupplier.get(); + firstConsumption = readByteBuffer(data.toByteBuffer()); + secondConsumption = readByteBuffer(data.toByteBuffer()); + assertArraysEqual(firstConsumption, secondConsumption); + assertArraysEqual(expectedBytes, firstConsumption); + + // Check toBytes consumption + data = binaryDataSupplier.get(); + firstConsumption = data.toBytes(); + secondConsumption = data.toBytes(); + assertArraysEqual(firstConsumption, secondConsumption); + assertArraysEqual(expectedBytes, firstConsumption); + + // Check that attempt to make repeatable returns itself. + data = binaryDataSupplier.get(); + BinaryData clone = data.toReplayableBinaryData(); + assertSame(data, clone); + } + + public static Stream createRetryableBinaryData() throws IOException { + byte[] bytes = new byte[1024]; + fillArray(bytes); + + MockFile mockFile = new MockFile("binaryDataFromFile" + UUID.randomUUID() + ".txt", bytes, 1024); + + return Stream.of( + Arguments.of(Named.named("bytes", (Supplier) () -> BinaryData.fromBytes(bytes)), + Named.named("expected bytes", bytes)), + Arguments.of(Named.named("string", (Supplier) () -> BinaryData.fromString("test string")), + Named.named("expected bytes", "test string".getBytes(StandardCharsets.UTF_8))), + Arguments.of(Named.named("object", (Supplier) () -> BinaryData.fromObject("\"test string\"")), + Named.named("expected bytes", BinaryData.SERIALIZER.serializeToBytes("\"test string\""))), + Arguments.of( + Named.named("file", (Supplier) () -> new MockFileBinaryData(new MockPath(mockFile))), + Named.named("expected bytes", bytes)), + // Arguments.of( + // Named.named("byte buffer", + // (Supplier) () -> BinaryData.fromByteBuffer(ByteBuffer.wrap(bytes))), + // Named.named("expected bytes", bytes)), + Arguments.of( + Named.named("byte array stream", (Supplier) () -> BinaryData + .fromStream(new ByteArrayInputStream(bytes), (long) bytes.length)), + Named.named("expected bytes", bytes))); + } + + @Test + public void testMakeSmallMarkableStreamReplayable() throws IOException { + byte[] bytes = new byte[1024]; + fillArray(bytes); + + // Delegate to testReplayableContentTypes to assert accessors replayability + testReplayableContentTypes( + () -> BinaryData.fromStream(new ByteArrayInputStream(bytes), (long) bytes.length).toReplayableBinaryData(), + bytes); + + // When using markable stream + ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); + assertSame(byteArrayInputStream, + BinaryData.fromStream(byteArrayInputStream, (long) bytes.length).toReplayableBinaryData().toStream()); + } + + @Test + public void testMakeUnknownLengthMarkableStreamReplayable() throws IOException { + byte[] bytes = new byte[1024]; + fillArray(bytes); + + // Delegate to testReplayableContentTypes to assert accessors replayability + testReplayableContentTypes( + () -> BinaryData.fromStream(new ByteArrayInputStream(bytes)).toReplayableBinaryData(), bytes); + + // When using markable stream + ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); + assertNotSame(byteArrayInputStream, + BinaryData.fromStream(byteArrayInputStream).toReplayableBinaryData().toStream()); + + // Check that buffering happened. This is part assumes implementation. + assertInstanceOf(IterableOfByteBuffersInputStream.class, + BinaryData.fromStream(byteArrayInputStream).toReplayableBinaryData().toStream()); + } + + @ParameterizedTest + // Try various sizes. That hit MIN and MAX buffers size in the InputStreamContent + @ValueSource( + ints = { + 10, + 1024, + 8 * 1024 - 1, + 8 * 1024 + 113, + 4 * 1024 * 1024 + 117, + 8 * 1024 * 1024, + 8 * 1024 * 1024 + 117, + 64 * 1024 * 1024 + 117 }) + public void testCanBufferNotMarkableStreams(int size) throws IOException { + byte[] bytes = new byte[size]; + fillArray(bytes); + + MockFile mockFile = new MockFile("binaryDataFromFile" + UUID.randomUUID() + ".txt", bytes, size); + + // Delegate to testReplayableContentTypes to assert accessors replayability + // with unknown length + testReplayableContentTypes(() -> new MockFileBinaryData(new MockPath(mockFile)).toReplayableBinaryData(), + bytes); + + // with known length + testReplayableContentTypes(() -> new MockFileBinaryData(new MockPath(mockFile), 8192, null, (long) bytes.length) + .toReplayableBinaryData(), bytes); + + // When using markable stream + FileInputStream fileInputStream = new MockFileInputStream(mockFile); + assertFalse(fileInputStream.markSupported()); + assertNotSame(fileInputStream, BinaryData.fromStream(fileInputStream).toReplayableBinaryData().toStream()); + + // Check that buffering happened. This is part assumes implementation. + assertInstanceOf(IterableOfByteBuffersInputStream.class, + BinaryData.fromStream(fileInputStream).toReplayableBinaryData().toStream()); + } + + /** + * On Windows {@link FileChannel#map(FileChannel.MapMode, long, long)} can block file deletion until buffer is + * reclaimed by GC. https://bugs.java.com/bugdatabase/view_bug.do?bug_id=4715154 + */ + @Test + public void binaryDataFromFileToBytesDoesNotBlockDelete() throws IOException { + byte[] bytes = new byte[10240]; + fillArray(bytes); + Path tempFile = Files.createTempFile("deletionTest", null); + tempFile.toFile().deleteOnExit(); + Files.write(tempFile, bytes); + + // create and consume flux. + BinaryData.fromFile(tempFile).toBytes(); + + // immediate delete should succeed. + assertTrue(tempFile.toFile().delete()); + } + + @Test + public void binaryDataAsPropertySerialization() throws IOException { + BinaryDataAsProperty binaryDataAsProperty = new BinaryDataAsProperty() + .setProperty(BinaryData.fromObject(new BinaryDataPropertyClass().setTest("test"))); + String expectedJson = "{\"property\":{\"test\":\"test\"}}"; + String actualJson = new String(new JsonSerializer().serializeToBytes(binaryDataAsProperty)); + + assertEquals(expectedJson, actualJson); + } + + @Test + public void binaryDataAsPropertyDeserialization() throws IOException { + BinaryDataAsProperty expected = new BinaryDataAsProperty() + .setProperty(BinaryData.fromObject(new BinaryDataPropertyClass().setTest("test"))); + String json = "{\"property\":{\"test\":\"test\"}}"; + BinaryDataAsProperty actual + = new JsonSerializer().deserializeFromBytes(json.getBytes(), BinaryDataAsProperty.class); + + assertEquals(expected.getProperty().toString(), actual.getProperty().toString()); + } + + public static final class BinaryDataAsProperty implements JsonSerializable { + private BinaryData property; + + public BinaryData getProperty() { + return property; + } + + public BinaryDataAsProperty setProperty(BinaryData property) { + this.property = property; + + return this; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + + BinaryDataPropertyClass binaryDataPropertyClass + = property.toObject(BinaryDataPropertyClass.class, SERIALIZER); + + jsonWriter.writeJsonField("property", binaryDataPropertyClass); + jsonWriter.writeEndObject(); + + return jsonWriter; + } + + public static BinaryDataAsProperty fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + BinaryDataAsProperty binaryDataAsProperty = new BinaryDataAsProperty(); + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("property".equals(fieldName)) { + binaryDataAsProperty.setProperty(BinaryData.fromObject(reader.readUntyped())); + } else { + reader.skipChildren(); + } + } + + return binaryDataAsProperty; + }); + } + } + + public static final class BinaryDataPropertyClass implements JsonSerializable { + private String test; + + public String getTest() { + return test; + } + + public BinaryDataPropertyClass setTest(String test) { + this.test = test; + + return this; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("test", test); + jsonWriter.writeEndObject(); + + return jsonWriter; + } + + public static BinaryDataPropertyClass fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + BinaryDataPropertyClass binaryDataPropertyClass = new BinaryDataPropertyClass(); + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("test".equals(fieldName)) { + binaryDataPropertyClass.setTest(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return binaryDataPropertyClass; + }); + } + } + + private static byte[] readByteBuffer(ByteBuffer buffer) { + // Simplified implementation good enough for testing. + byte[] result = new byte[buffer.remaining()]; + + buffer.get(result); + + return result; + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/util/binarydata/MockFileBinaryData.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/binarydata/MockFileBinaryData.java similarity index 97% rename from sdk/clientcore/core/src/test/java/io/clientcore/core/util/binarydata/MockFileBinaryData.java rename to sdk/clientcore/core/src/test/java/io/clientcore/core/models/binarydata/MockFileBinaryData.java index 64de77451b5d..87330809f00e 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/util/binarydata/MockFileBinaryData.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/binarydata/MockFileBinaryData.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.util.binarydata; +package io.clientcore.core.models.binarydata; import io.clientcore.core.models.MockPath; diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/util/binarydata/MockFileInputStream.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/binarydata/MockFileInputStream.java similarity index 98% rename from sdk/clientcore/core/src/test/java/io/clientcore/core/util/binarydata/MockFileInputStream.java rename to sdk/clientcore/core/src/test/java/io/clientcore/core/models/binarydata/MockFileInputStream.java index 729604c3c298..e4f007c1282e 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/util/binarydata/MockFileInputStream.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/binarydata/MockFileInputStream.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.util.binarydata; +package io.clientcore.core.models.binarydata; import io.clientcore.core.models.MockFile; diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoArrayTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoArrayTests.java new file mode 100644 index 000000000000..85dd79d29935 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoArrayTests.java @@ -0,0 +1,192 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models.geo; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * Tests {@link GeoArray}. + */ +public class GeoArrayTests { + @Test + public void pointCoordinates() { + GeoPoint point = new GeoPoint(1, 2); + + assertEquals(2, point.getCoordinates().count()); + assertEquals(1, point.getCoordinates().get(0)); + assertEquals(2, point.getCoordinates().get(1)); + assertThrows(IndexOutOfBoundsException.class, () -> point.getCoordinates().get(2)); + } + + @Test + public void pointCoordinatesWithAltitude() { + GeoPoint point = new GeoPoint(1, 2, 3D); + + assertEquals(3, point.getCoordinates().count()); + assertEquals(1, point.getCoordinates().get(0)); + assertEquals(2, point.getCoordinates().get(1)); + assertEquals(3, point.getCoordinates().get(2)); + } + + @Test + public void pointCollectionCoordinates() { + GeoPointCollection pointCollection + = new GeoPointCollection(Arrays.asList(new GeoPoint(1, 2), new GeoPoint(3, 4))); + + assertEquals(2, pointCollection.getCoordinates().size()); + + assertEquals(1, pointCollection.getCoordinates().get(0).get(0)); + assertEquals(2, pointCollection.getCoordinates().get(0).get(1)); + + assertEquals(3, pointCollection.getCoordinates().get(1).get(0)); + assertEquals(4, pointCollection.getCoordinates().get(1).get(1)); + } + + @Test + public void lineCoordinates() { + GeoLineString line + = new GeoLineString(Arrays.asList(new GeoPosition(1, 2), new GeoPosition(3, 4), new GeoPosition(5, 6))); + + assertEquals(3, line.getCoordinates().size()); + + assertEquals(1, line.getCoordinates().get(0).get(0)); + assertEquals(2, line.getCoordinates().get(0).get(1)); + + assertEquals(3, line.getCoordinates().get(1).get(0)); + assertEquals(4, line.getCoordinates().get(1).get(1)); + + assertEquals(5, line.getCoordinates().get(2).get(0)); + assertEquals(6, line.getCoordinates().get(2).get(1)); + } + + @Test + public void lineCollectionCoordinates() { + GeoLineStringCollection lineCollection = new GeoLineStringCollection( + Arrays.asList(new GeoLineString(Arrays.asList(new GeoPosition(1, 2), new GeoPosition(3, 4))), + new GeoLineString(Arrays.asList(new GeoPosition(5, 6), new GeoPosition(7, 8))))); + + assertEquals(2, lineCollection.getCoordinates().size()); + + assertEquals(1, lineCollection.getCoordinates().get(0).get(0).get(0)); + assertEquals(2, lineCollection.getCoordinates().get(0).get(0).get(1)); + + assertEquals(3, lineCollection.getCoordinates().get(0).get(1).get(0)); + assertEquals(4, lineCollection.getCoordinates().get(0).get(1).get(1)); + + assertEquals(5, lineCollection.getCoordinates().get(1).get(0).get(0)); + assertEquals(6, lineCollection.getCoordinates().get(1).get(0).get(1)); + + assertEquals(7, lineCollection.getCoordinates().get(1).get(1).get(0)); + assertEquals(8, lineCollection.getCoordinates().get(1).get(1).get(1)); + } + + @Test + public void polygonCoordinates() { + GeoPolygon polygon = new GeoPolygon(Arrays.asList( + new GeoLinearRing(Arrays.asList(new GeoPosition(1, 1), new GeoPosition(1, 2), new GeoPosition(2, 2), + new GeoPosition(1, 1))), + new GeoLinearRing(Arrays.asList(new GeoPosition(5, 5), new GeoPosition(5, 6), new GeoPosition(6, 6), + new GeoPosition(5, 5))))); + + assertEquals(2, polygon.getCoordinates().size()); + + assertEquals(1, polygon.getCoordinates().get(0).get(0).get(0)); + assertEquals(1, polygon.getCoordinates().get(0).get(0).get(1)); + + assertEquals(1, polygon.getCoordinates().get(0).get(1).get(0)); + assertEquals(2, polygon.getCoordinates().get(0).get(1).get(1)); + + assertEquals(2, polygon.getCoordinates().get(0).get(2).get(0)); + assertEquals(2, polygon.getCoordinates().get(0).get(2).get(1)); + + assertEquals(1, polygon.getCoordinates().get(0).get(3).get(0)); + assertEquals(1, polygon.getCoordinates().get(0).get(3).get(1)); + + assertEquals(5, polygon.getCoordinates().get(1).get(0).get(0)); + assertEquals(5, polygon.getCoordinates().get(1).get(0).get(1)); + + assertEquals(5, polygon.getCoordinates().get(1).get(1).get(0)); + assertEquals(6, polygon.getCoordinates().get(1).get(1).get(1)); + + assertEquals(6, polygon.getCoordinates().get(1).get(2).get(0)); + assertEquals(6, polygon.getCoordinates().get(1).get(2).get(1)); + + assertEquals(5, polygon.getCoordinates().get(1).get(3).get(0)); + assertEquals(5, polygon.getCoordinates().get(1).get(3).get(1)); + } + + @Test + public void polygonCollectionCoordinates() { + GeoPolygonCollection polygonCollection = new GeoPolygonCollection(Arrays.asList( + new GeoPolygon(Arrays.asList( + new GeoLinearRing(Arrays.asList(new GeoPosition(1, 1), new GeoPosition(1, 2), new GeoPosition(2, 2), + new GeoPosition(1, 1))), + new GeoLinearRing(Arrays.asList(new GeoPosition(5, 5), new GeoPosition(5, 6), new GeoPosition(6, 6), + new GeoPosition(5, 5))))), + new GeoPolygon(Arrays.asList( + new GeoLinearRing(Arrays.asList(new GeoPosition(9, 9), new GeoPosition(9, 10), new GeoPosition(10, 10), + new GeoPosition(9, 9))), + new GeoLinearRing(Arrays.asList(new GeoPosition(13, 13), new GeoPosition(13, 14), + new GeoPosition(14, 14), new GeoPosition(13, 13))))))); + + assertEquals(2, polygonCollection.getCoordinates().size()); + + GeoArray> polygonCoordinates = polygonCollection.getCoordinates().get(0); + + assertEquals(1, polygonCoordinates.get(0).get(0).get(0)); + assertEquals(1, polygonCoordinates.get(0).get(0).get(0)); + + assertEquals(1, polygonCoordinates.get(0).get(1).get(0)); + assertEquals(2, polygonCoordinates.get(0).get(1).get(1)); + + assertEquals(2, polygonCoordinates.get(0).get(2).get(0)); + assertEquals(2, polygonCoordinates.get(0).get(2).get(1)); + + assertEquals(1, polygonCoordinates.get(0).get(3).get(0)); + assertEquals(1, polygonCoordinates.get(0).get(3).get(1)); + + assertEquals(5, polygonCoordinates.get(1).get(0).get(0)); + assertEquals(5, polygonCoordinates.get(1).get(0).get(1)); + + assertEquals(5, polygonCoordinates.get(1).get(1).get(0)); + assertEquals(6, polygonCoordinates.get(1).get(1).get(1)); + + assertEquals(6, polygonCoordinates.get(1).get(2).get(0)); + assertEquals(6, polygonCoordinates.get(1).get(2).get(1)); + + assertEquals(5, polygonCoordinates.get(1).get(3).get(0)); + assertEquals(5, polygonCoordinates.get(1).get(3).get(1)); + + polygonCoordinates = polygonCollection.getCoordinates().get(1); + + assertEquals(9, polygonCoordinates.get(0).get(0).get(0)); + assertEquals(9, polygonCoordinates.get(0).get(0).get(1)); + + assertEquals(9, polygonCoordinates.get(0).get(1).get(0)); + assertEquals(10, polygonCoordinates.get(0).get(1).get(1)); + + assertEquals(10, polygonCoordinates.get(0).get(2).get(0)); + assertEquals(10, polygonCoordinates.get(0).get(2).get(1)); + + assertEquals(9, polygonCoordinates.get(0).get(3).get(0)); + assertEquals(9, polygonCoordinates.get(0).get(3).get(1)); + + assertEquals(13, polygonCoordinates.get(1).get(0).get(0)); + assertEquals(13, polygonCoordinates.get(1).get(0).get(1)); + + assertEquals(13, polygonCoordinates.get(1).get(1).get(0)); + assertEquals(14, polygonCoordinates.get(1).get(1).get(1)); + + assertEquals(14, polygonCoordinates.get(1).get(2).get(0)); + assertEquals(14, polygonCoordinates.get(1).get(2).get(1)); + + assertEquals(13, polygonCoordinates.get(1).get(3).get(0)); + assertEquals(13, polygonCoordinates.get(1).get(3).get(1)); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoBoundingBoxTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoBoundingBoxTests.java new file mode 100644 index 000000000000..45f206b877d7 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoBoundingBoxTests.java @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models.geo; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static io.clientcore.core.models.geo.GeoTestHelpers.MT_RAINIER_BOUNDING_BOX; +import static io.clientcore.core.models.geo.GeoTestHelpers.PIKES_PLACE_BOUNDING_BOX; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Tests {@link GeoBoundingBox}. + */ +public class GeoBoundingBoxTests { + @Test + public void simpleConstructor() { + double expectedWest = -180; + double expectedSouth = -90; + double expectedEast = 180; + double expectedNorth = 90; + + GeoBoundingBox boundingBox = new GeoBoundingBox(expectedWest, expectedSouth, expectedEast, expectedNorth); + + assertEquals(expectedWest, boundingBox.getWest()); + assertEquals(expectedSouth, boundingBox.getSouth()); + assertEquals(expectedEast, boundingBox.getEast()); + assertEquals(expectedNorth, boundingBox.getNorth()); + + Assertions.assertNull(boundingBox.getMinAltitude()); + Assertions.assertNull(boundingBox.getMaxAltitude()); + } + + @Test + public void complexConstructor() { + double expectedWest = -180; + double expectedSouth = -90; + double expectedEast = 180; + double expectedNorth = 90; + double expectedMinAltitude = -1000; + double expectedMaxAltitude = 1000; + + GeoBoundingBox boundingBox = new GeoBoundingBox(expectedWest, expectedSouth, expectedEast, expectedNorth, + expectedMinAltitude, expectedMaxAltitude); + + assertEquals(expectedWest, boundingBox.getWest()); + assertEquals(expectedSouth, boundingBox.getSouth()); + assertEquals(expectedEast, boundingBox.getEast()); + assertEquals(expectedNorth, boundingBox.getNorth()); + assertEquals(expectedMinAltitude, boundingBox.getMinAltitude()); + assertEquals(expectedMaxAltitude, boundingBox.getMaxAltitude()); + } + + @Test + public void constructorDoesNotValidate() { + double expectedWest = -200; + double expectedSouth = -100; + double expectedEast = 200; + double expectedNorth = 100; + + GeoBoundingBox boundingBox = new GeoBoundingBox(expectedWest, expectedSouth, expectedEast, expectedNorth); + + assertEquals(expectedWest, boundingBox.getWest()); + assertEquals(expectedSouth, boundingBox.getSouth()); + assertEquals(expectedEast, boundingBox.getEast()); + assertEquals(expectedNorth, boundingBox.getNorth()); + } + + @ParameterizedTest + @MethodSource("equalsSupplier") + public void geoBoundingBoxEquals(GeoBoundingBox boundingBox, Object obj, boolean expected) { + assertEquals(expected, boundingBox.equals(obj)); + } + + private static Stream equalsSupplier() { + GeoBoundingBox pikePlaceBoundingBox = PIKES_PLACE_BOUNDING_BOX.get(); + GeoBoundingBox mtRainierBoundingBox = MT_RAINIER_BOUNDING_BOX.get(); + + return Stream.of( + // Other is null. + Arguments.of(pikePlaceBoundingBox, null, false), + + // Other isn't instance of type. + Arguments.of(pikePlaceBoundingBox, 1, false), + + // Other is itself. + Arguments.of(pikePlaceBoundingBox, pikePlaceBoundingBox, true), + Arguments.of(mtRainierBoundingBox, mtRainierBoundingBox, true), + + // Other is a different value. + Arguments.of(pikePlaceBoundingBox, mtRainierBoundingBox, false), + Arguments.of(mtRainierBoundingBox, pikePlaceBoundingBox, false), + + // Other is the same value. + Arguments.of(pikePlaceBoundingBox, PIKES_PLACE_BOUNDING_BOX.get(), true), + Arguments.of(mtRainierBoundingBox, MT_RAINIER_BOUNDING_BOX.get(), true)); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoCollectionTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoCollectionTests.java new file mode 100644 index 000000000000..b0ced452e9ba --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoCollectionTests.java @@ -0,0 +1,107 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models.geo; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import static io.clientcore.core.models.geo.GeoTestHelpers.RECTANGLE_LINE; +import static io.clientcore.core.models.geo.GeoTestHelpers.RECTANGLE_POLYGON; +import static io.clientcore.core.models.geo.GeoTestHelpers.SQUARE_LINE; +import static io.clientcore.core.models.geo.GeoTestHelpers.SQUARE_POLYGON; +import static io.clientcore.core.models.geo.GeoTestHelpers.TRIANGLE_LINE; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +/** + * Tests {@link GeoCollection}. + */ +public class GeoCollectionTests { + @Test + public void nullGeometriesThrows() { + Assertions.assertThrows(NullPointerException.class, () -> new GeoCollection(null)); + } + + @Test + public void simpleConstructor() { + List geometries = Arrays.asList(SQUARE_LINE.get(), SQUARE_POLYGON.get()); + + GeoCollection collection = new GeoCollection(geometries); + + assertEquals(geometries, collection.getGeometries()); + + Assertions.assertNull(collection.getBoundingBox()); + Assertions.assertNull(collection.getCustomProperties()); + } + + @Test + public void complexConstructor() { + List geometries = Arrays.asList(SQUARE_LINE.get(), SQUARE_POLYGON.get()); + GeoBoundingBox boundingBox = new GeoBoundingBox(0, 0, 1, 1); + Map properties = Collections.singletonMap("key", "value"); + + GeoCollection collection = new GeoCollection(geometries, boundingBox, properties); + + assertEquals(geometries, collection.getGeometries()); + assertEquals(boundingBox, collection.getBoundingBox()); + assertEquals(properties, collection.getCustomProperties()); + } + + @Test + public void constructorCopiesGeometries() { + List geometries = new ArrayList<>(); + geometries.add(SQUARE_LINE.get()); + geometries.add(SQUARE_POLYGON.get()); + + GeoCollection collection = new GeoCollection(geometries); + assertEquals(geometries, collection.getGeometries()); + + geometries.add(TRIANGLE_LINE.get()); + assertNotEquals(geometries, collection.getGeometries()); + } + + @ParameterizedTest + @MethodSource("equalsSupplier") + public void collectionGeometriesEquals(GeoCollection collection, Object obj, boolean expected) { + assertEquals(expected, collection.equals(obj)); + } + + private static Stream equalsSupplier() { + List geometries = Arrays.asList(SQUARE_LINE.get(), SQUARE_POLYGON.get()); + List geometries1 = Arrays.asList(RECTANGLE_LINE.get(), RECTANGLE_POLYGON.get()); + + GeoBoundingBox boundingBox = new GeoBoundingBox(0, 0, 2, 2); + Map properties = Collections.singletonMap("key", "value"); + + GeoCollection collection = new GeoCollection(geometries); + GeoCollection collection1 = new GeoCollection(geometries1, boundingBox, properties); + + return Stream.of( + // Other is null. + Arguments.of(collection, null, false), + + // Other isn't instance of type. + Arguments.of(collection, 1, false), + + // Other is itself. + Arguments.of(collection, collection, true), Arguments.of(collection1, collection1, true), + + // Other is a different value. + Arguments.of(collection, collection1, false), Arguments.of(collection1, collection, false), + + // Other is the same value. + Arguments.of(collection, new GeoCollection(geometries), true), + Arguments.of(collection1, new GeoCollection(geometries1, boundingBox, properties), true)); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoJsonDeserializerTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoJsonDeserializerTests.java new file mode 100644 index 000000000000..f2016054b0c1 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoJsonDeserializerTests.java @@ -0,0 +1,194 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models.geo; + +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.utils.IOExceptionCheckedFunction; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.BiFunction; +import java.util.stream.Stream; + +/** + * Tests GeoJson deserialization. + */ +public class GeoJsonDeserializerTests { + @Test + public void jsonWithoutTypeThrows() { + String missingType = "{\"coordinates\":[0,0]}"; + Assertions.assertThrows(IllegalStateException.class, () -> deserialize(missingType, GeoObject::fromJson)); + } + + @Test + public void jsonWithoutCoordinatesThrows() { + String missingCoordinates = "{\"type\":\"Point\"}"; + Assertions.assertThrows(IllegalStateException.class, () -> deserialize(missingCoordinates, GeoPoint::fromJson)); + } + + @Test + public void unknownGeoTypeThrows() { + String unknownType = "{\"type\":\"Custom\",\"coordinates\":[0,0]}"; + Assertions.assertThrows(IllegalStateException.class, () -> deserialize(unknownType, GeoObject::fromJson)); + } + + @ParameterizedTest + @ValueSource( + strings = { "{\"type\":\"Point\",\"coordinates\":[1]}", "{\"type\":\"Point\",\"coordinates\":[4,4,4,4]}" }) + public void invalidCoordinateCountThrows(String invalidCoordinateCount) { + Assertions.assertThrows(IllegalStateException.class, + () -> deserialize(invalidCoordinateCount, GeoPoint::fromJson)); + } + + @ParameterizedTest + @ValueSource( + strings = { + "{\"type\":\"Point\",\"coordinates\":[0,0],\"bbox\":[2,2]}", + "{\"type\":\"Point\",\"coordinates\":[0,0],\"bbox\":[8,8,8,8,8,8,8,8]}" }) + public void invalidBoundBoxThrows(String invalidBoundBox) { + Assertions.assertThrows(IllegalStateException.class, () -> deserialize(invalidBoundBox, GeoPoint::fromJson)); + } + + @Test + public void collectionWithoutGeometriesThrows() { + String invalidCollection = "{\"type\":\"GeometryCollection\"}"; + Assertions.assertThrows(IllegalStateException.class, + () -> deserialize(invalidCollection, GeoCollection::fromJson)); + } + + @ParameterizedTest + @MethodSource("deserializeSupplier") + public void deserialize(String json, IOExceptionCheckedFunction deserializer, + T expectedGeo) throws IOException { + Assertions.assertEquals(expectedGeo, deserialize(json, deserializer)); + } + + private static T deserialize(String json, IOExceptionCheckedFunction deserializer) + throws IOException { + try (JsonReader jsonReader = JsonReader.fromString(json)) { + return deserializer.apply(jsonReader); + } + } + + private static Stream deserializeSupplier() { + GeoBoundingBox boundingBox = new GeoBoundingBox(0, 0, 1, 1, 0D, 1D); + Map simpleProperties = Collections.singletonMap("key", "value"); + Map arrayProperties = Collections.singletonMap("text", Arrays.asList("hello", "world")); + + Map crs = new HashMap<>(); + crs.put("type", "name"); + crs.put("properties", Collections.singletonMap("name", "EPSG:432")); + Map objectProperties = Collections.singletonMap("crs", crs); + + BiFunction, GeoPoint> pointSupplier + = (box, properties) -> new GeoPoint(new GeoPosition(0, 0, 0D), box, properties); + + List positions = Arrays.asList(new GeoPosition(0, 0, 1D), new GeoPosition(1, 1, 1D)); + BiFunction, GeoLineString> lineSupplier + = (box, properties) -> new GeoLineString(positions, box, properties); + + List rings = Collections.singletonList(new GeoLinearRing(Arrays.asList(new GeoPosition(0, 0, 1D), + new GeoPosition(0, 1, 1D), new GeoPosition(1, 1, 1D), new GeoPosition(0, 0, 1D)))); + BiFunction, GeoPolygon> polygonSupplier + = (box, properties) -> new GeoPolygon(rings, box, properties); + + BiFunction, GeoPointCollection> multiPointSupplier + = (box, properties) -> new GeoPointCollection( + Arrays.asList(pointSupplier.apply(null, null), pointSupplier.apply(null, null)), box, properties); + + BiFunction, GeoLineStringCollection> multiLineSupplier + = (box, properties) -> new GeoLineStringCollection( + Arrays.asList(lineSupplier.apply(null, null), lineSupplier.apply(null, null)), box, properties); + + BiFunction, GeoPolygonCollection> multiPolygonSupplier + = (box, properties) -> new GeoPolygonCollection( + Arrays.asList(polygonSupplier.apply(null, null), polygonSupplier.apply(null, null)), box, properties); + + BiFunction, GeoCollection> collectionSupplier + = (box, properties) -> new GeoCollection(Arrays.asList(pointSupplier.apply(null, null), + multiLineSupplier.apply(box, properties), polygonSupplier.apply(box, properties)), box, properties); + + return Stream.of( + // GeoPoint + Arguments.of(deserializerArgumentSupplier(null, null, pointSupplier, GeoPoint::fromJson)), + Arguments + .of(deserializerArgumentSupplier(boundingBox, simpleProperties, pointSupplier, GeoPoint::fromJson)), + Arguments.of(deserializerArgumentSupplier(boundingBox, arrayProperties, pointSupplier, GeoPoint::fromJson)), + Arguments + .of(deserializerArgumentSupplier(boundingBox, objectProperties, pointSupplier, GeoPoint::fromJson)), + + // GeoLine + Arguments.of(deserializerArgumentSupplier(null, null, lineSupplier, GeoLineString::fromJson)), + Arguments + .of(deserializerArgumentSupplier(boundingBox, simpleProperties, lineSupplier, GeoLineString::fromJson)), + Arguments + .of(deserializerArgumentSupplier(boundingBox, arrayProperties, lineSupplier, GeoLineString::fromJson)), + Arguments + .of(deserializerArgumentSupplier(boundingBox, objectProperties, lineSupplier, GeoLineString::fromJson)), + + // GeoPolygon + Arguments.of(deserializerArgumentSupplier(null, null, polygonSupplier, GeoPolygon::fromJson)), + Arguments + .of(deserializerArgumentSupplier(boundingBox, simpleProperties, polygonSupplier, GeoPolygon::fromJson)), + Arguments + .of(deserializerArgumentSupplier(boundingBox, arrayProperties, polygonSupplier, GeoPolygon::fromJson)), + Arguments + .of(deserializerArgumentSupplier(boundingBox, objectProperties, polygonSupplier, GeoPolygon::fromJson)), + + // GeoPointCollection + Arguments.of(deserializerArgumentSupplier(null, null, multiPointSupplier, GeoPointCollection::fromJson)), + Arguments.of(deserializerArgumentSupplier(boundingBox, simpleProperties, multiPointSupplier, + GeoPointCollection::fromJson)), + Arguments.of(deserializerArgumentSupplier(boundingBox, arrayProperties, multiPointSupplier, + GeoPointCollection::fromJson)), + Arguments.of(deserializerArgumentSupplier(boundingBox, objectProperties, multiPointSupplier, + GeoPointCollection::fromJson)), + + // GeoLineCollection + Arguments + .of(deserializerArgumentSupplier(null, null, multiLineSupplier, GeoLineStringCollection::fromJson)), + Arguments.of(deserializerArgumentSupplier(boundingBox, simpleProperties, multiLineSupplier, + GeoLineStringCollection::fromJson)), + Arguments.of(deserializerArgumentSupplier(boundingBox, arrayProperties, multiLineSupplier, + GeoLineStringCollection::fromJson)), + Arguments.of(deserializerArgumentSupplier(boundingBox, objectProperties, multiLineSupplier, + GeoLineStringCollection::fromJson)), + + // GeoPolygonCollection + Arguments + .of(deserializerArgumentSupplier(null, null, multiPolygonSupplier, GeoPolygonCollection::fromJson)), + Arguments.of(deserializerArgumentSupplier(boundingBox, simpleProperties, multiPolygonSupplier, + GeoPolygonCollection::fromJson)), + Arguments.of(deserializerArgumentSupplier(boundingBox, arrayProperties, multiPolygonSupplier, + GeoPolygonCollection::fromJson)), + Arguments.of(deserializerArgumentSupplier(boundingBox, objectProperties, multiPolygonSupplier, + GeoPolygonCollection::fromJson)), + + // GeoCollection + Arguments.of(deserializerArgumentSupplier(null, null, collectionSupplier, GeoCollection::fromJson)), + Arguments.of(deserializerArgumentSupplier(boundingBox, simpleProperties, collectionSupplier, + GeoCollection::fromJson)), + Arguments.of(deserializerArgumentSupplier(boundingBox, arrayProperties, collectionSupplier, + GeoCollection::fromJson)), + Arguments.of(deserializerArgumentSupplier(boundingBox, objectProperties, collectionSupplier, + GeoCollection::fromJson))); + } + + private static Object[] deserializerArgumentSupplier(GeoBoundingBox boundingBox, + Map properties, BiFunction, T> geoSupplier, + IOExceptionCheckedFunction deserializer) { + T geoObject = geoSupplier.apply(boundingBox, properties); + return new Object[] { GeoSerializationTestHelpers.geoToJson(geoObject), deserializer, geoObject }; + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoJsonSerializerTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoJsonSerializerTests.java new file mode 100644 index 000000000000..11d8f973c450 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoJsonSerializerTests.java @@ -0,0 +1,122 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models.geo; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.BiFunction; +import java.util.stream.Stream; + +/** + * Tests GeoJson serialization. + */ +public class GeoJsonSerializerTests { + @ParameterizedTest + @MethodSource("serializeSupplier") + @Execution(ExecutionMode.SAME_THREAD) + public void serialize(T geo, String expectedJson) throws IOException { + Assertions.assertEquals(expectedJson, geo.toJsonString()); + } + + private static Stream serializeSupplier() { + GeoBoundingBox boundingBox = new GeoBoundingBox(0, 0, 1, 1, 0D, 1D); + Map simpleProperties = Collections.singletonMap("key", "value"); + Map arrayProperties = Collections.singletonMap("text", Arrays.asList("hello", "world")); + + Map crs = new HashMap<>(); + crs.put("type", "name"); + crs.put("properties", Collections.singletonMap("name", "EPSG:432")); + Map objectProperties = Collections.singletonMap("crs", crs); + + BiFunction, GeoPoint> pointSupplier + = (box, properties) -> new GeoPoint(new GeoPosition(0, 0, 0D), box, properties); + + List positions = Arrays.asList(new GeoPosition(0, 0, 1D), new GeoPosition(1, 1, 1D)); + BiFunction, GeoLineString> lineSupplier + = (box, properties) -> new GeoLineString(positions, box, properties); + + List rings = Collections.singletonList(new GeoLinearRing(Arrays.asList(new GeoPosition(0, 0, 1D), + new GeoPosition(0, 1, 1D), new GeoPosition(1, 1, 1D), new GeoPosition(0, 0, 1D)))); + BiFunction, GeoPolygon> polygonSupplier + = (box, properties) -> new GeoPolygon(rings, box, properties); + + BiFunction, GeoPointCollection> multiPointSupplier + = (box, properties) -> new GeoPointCollection( + Arrays.asList(pointSupplier.apply(null, null), pointSupplier.apply(box, properties)), box, properties); + + BiFunction, GeoLineStringCollection> multiLineSupplier + = (box, properties) -> new GeoLineStringCollection( + Arrays.asList(lineSupplier.apply(null, null), lineSupplier.apply(box, properties)), box, properties); + + BiFunction, GeoPolygonCollection> multiPolygonSupplier + = (box, properties) -> new GeoPolygonCollection( + Arrays.asList(polygonSupplier.apply(null, null), polygonSupplier.apply(box, properties)), box, + properties); + + BiFunction, GeoCollection> collectionSupplier + = (box, properties) -> new GeoCollection( + Arrays.asList(pointSupplier.apply(null, null), multiPointSupplier.apply(box, properties)), box, + properties); + + return Stream.of( + // GeoPoint + Arguments.of(serializerArgumentSupplier(null, null, pointSupplier)), + Arguments.of(serializerArgumentSupplier(boundingBox, simpleProperties, pointSupplier)), + Arguments.of(serializerArgumentSupplier(boundingBox, arrayProperties, pointSupplier)), + Arguments.of(serializerArgumentSupplier(boundingBox, objectProperties, pointSupplier)), + + // GeoLine + Arguments.of(serializerArgumentSupplier(null, null, lineSupplier)), + Arguments.of(serializerArgumentSupplier(boundingBox, simpleProperties, lineSupplier)), + Arguments.of(serializerArgumentSupplier(boundingBox, arrayProperties, lineSupplier)), + Arguments.of(serializerArgumentSupplier(boundingBox, objectProperties, lineSupplier)), + + // GeoPolygon + Arguments.of(serializerArgumentSupplier(null, null, polygonSupplier)), + Arguments.of(serializerArgumentSupplier(boundingBox, simpleProperties, polygonSupplier)), + Arguments.of(serializerArgumentSupplier(boundingBox, arrayProperties, polygonSupplier)), + Arguments.of(serializerArgumentSupplier(boundingBox, objectProperties, polygonSupplier)), + + // GeoPointCollection + Arguments.of(serializerArgumentSupplier(null, null, multiPointSupplier)), + Arguments.of(serializerArgumentSupplier(boundingBox, simpleProperties, multiPointSupplier)), + Arguments.of(serializerArgumentSupplier(boundingBox, arrayProperties, multiPointSupplier)), + Arguments.of(serializerArgumentSupplier(boundingBox, objectProperties, multiPointSupplier)), + + // GeoLineCollection + Arguments.of(serializerArgumentSupplier(null, null, multiLineSupplier)), + Arguments.of(serializerArgumentSupplier(boundingBox, simpleProperties, multiLineSupplier)), + Arguments.of(serializerArgumentSupplier(boundingBox, arrayProperties, multiLineSupplier)), + Arguments.of(serializerArgumentSupplier(boundingBox, objectProperties, multiLineSupplier)), + + // GeoPolygonCollection + Arguments.of(serializerArgumentSupplier(null, null, multiPolygonSupplier)), + Arguments.of(serializerArgumentSupplier(boundingBox, simpleProperties, multiPolygonSupplier)), + Arguments.of(serializerArgumentSupplier(boundingBox, arrayProperties, multiPolygonSupplier)), + Arguments.of(serializerArgumentSupplier(boundingBox, objectProperties, multiPolygonSupplier)), + + // GeoCollection + Arguments.of(serializerArgumentSupplier(null, null, collectionSupplier)), + Arguments.of(serializerArgumentSupplier(boundingBox, simpleProperties, collectionSupplier)), + Arguments.of(serializerArgumentSupplier(boundingBox, arrayProperties, collectionSupplier)), + Arguments.of(serializerArgumentSupplier(boundingBox, objectProperties, collectionSupplier))); + } + + private static Object[] serializerArgumentSupplier(GeoBoundingBox boundingBox, Map properties, + BiFunction, ? extends GeoObject> geoSupplier) { + GeoObject geoObject = geoSupplier.apply(boundingBox, properties); + return new Object[] { geoObject, GeoSerializationTestHelpers.geoToJson(geoObject) }; + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoLineStringCollectionTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoLineStringCollectionTests.java new file mode 100644 index 000000000000..3bf711b7c9a2 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoLineStringCollectionTests.java @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models.geo; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import static io.clientcore.core.models.geo.GeoTestHelpers.RECTANGLE_LINE; +import static io.clientcore.core.models.geo.GeoTestHelpers.SQUARE_LINE; +import static io.clientcore.core.models.geo.GeoTestHelpers.TRIANGLE_LINE; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +/** + * Tests {@link GeoLineStringCollection}. + */ +public class GeoLineStringCollectionTests { + @Test + public void nullLinesThrows() { + Assertions.assertThrows(NullPointerException.class, () -> new GeoLineStringCollection(null)); + } + + @Test + public void simpleConstructor() { + List expectedLines = Arrays.asList(SQUARE_LINE.get(), TRIANGLE_LINE.get()); + + GeoLineStringCollection multiLine = new GeoLineStringCollection(expectedLines); + + assertEquals(expectedLines, multiLine.getLines()); + + Assertions.assertNull(multiLine.getBoundingBox()); + Assertions.assertNull(multiLine.getCustomProperties()); + } + + @Test + public void complexConstructor() { + List expectedLines = Arrays.asList(SQUARE_LINE.get(), TRIANGLE_LINE.get()); + + GeoBoundingBox boundingBox = new GeoBoundingBox(0, 0, 1, 1); + Map properties = Collections.singletonMap("key", "value"); + + GeoLineStringCollection multiLine = new GeoLineStringCollection(expectedLines, boundingBox, properties); + + assertEquals(expectedLines, multiLine.getLines()); + assertEquals(boundingBox, multiLine.getBoundingBox()); + assertEquals(properties, multiLine.getCustomProperties()); + } + + @Test + public void constructorCopiesLines() { + List expectedLines = new ArrayList<>(); + expectedLines.add(SQUARE_LINE.get()); + expectedLines.add(TRIANGLE_LINE.get()); + + GeoLineStringCollection multiLine = new GeoLineStringCollection(expectedLines); + assertEquals(expectedLines, multiLine.getLines()); + + expectedLines.add(RECTANGLE_LINE.get()); + assertNotEquals(expectedLines, multiLine.getLines()); + } + + @ParameterizedTest + @MethodSource("equalsSupplier") + public void multiLineGeometriesEqual(GeoLineStringCollection multiLine, Object obj, boolean expected) { + assertEquals(expected, multiLine.equals(obj)); + } + + private static Stream equalsSupplier() { + List lines = Arrays.asList(SQUARE_LINE.get(), RECTANGLE_LINE.get()); + List lines1 = Arrays.asList(SQUARE_LINE.get(), TRIANGLE_LINE.get()); + + GeoBoundingBox boundingBox = new GeoBoundingBox(0, 0, 1, 1); + Map properties = Collections.singletonMap("key", "value"); + + GeoLineStringCollection multiLine = new GeoLineStringCollection(lines); + GeoLineStringCollection multiLine1 = new GeoLineStringCollection(lines1, boundingBox, properties); + + return Stream.of( + // Other is null. + Arguments.of(multiLine, null, false), + + // Other isn't instance of type. + Arguments.of(multiLine, 1, false), + + // Other is itself. + Arguments.of(multiLine, multiLine, true), Arguments.of(multiLine1, multiLine1, true), + + // Other is a different value. + Arguments.of(multiLine, multiLine1, false), Arguments.of(multiLine1, multiLine, false), + + // Other is the same value. + Arguments.of(multiLine, new GeoLineStringCollection(lines), true), + Arguments.of(multiLine1, new GeoLineStringCollection(lines1, boundingBox, properties), true)); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoLineStringTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoLineStringTests.java new file mode 100644 index 000000000000..8074c6af2d42 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoLineStringTests.java @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models.geo; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +/** + * Tests {@link GeoLineString}. + */ +public class GeoLineStringTests { + @Test + public void nullPositionsThrows() { + Assertions.assertThrows(NullPointerException.class, () -> new GeoLineString(null)); + } + + @Test + public void simpleConstructor() { + GeoArray expectedPositions + = new GeoArray<>(Arrays.asList(new GeoPosition(0, 0), new GeoPosition(0, 1))); + + GeoLineString line = new GeoLineString(expectedPositions); + + assertEquals(expectedPositions, line.getCoordinates()); + + Assertions.assertNull(line.getBoundingBox()); + Assertions.assertNull(line.getCustomProperties()); + } + + @Test + public void complexConstructor() { + GeoArray expectedPositions + = new GeoArray<>(Arrays.asList(new GeoPosition(0, 0), new GeoPosition(0, 1))); + GeoBoundingBox expectedBoundingBox = new GeoBoundingBox(0, 0, 1, 1); + Map expectedProperties = Collections.singletonMap("key", "value"); + + GeoLineString line = new GeoLineString(expectedPositions, expectedBoundingBox, expectedProperties); + + assertEquals(expectedPositions, line.getCoordinates()); + assertEquals(expectedBoundingBox, line.getBoundingBox()); + assertEquals(expectedProperties, line.getCustomProperties()); + } + + @Test + public void constructorCopiesPositions() { + List expectedPositions = new ArrayList<>(); + expectedPositions.add(new GeoPosition(0, 0)); + expectedPositions.add(new GeoPosition(0, 1)); + + GeoLineString line = new GeoLineString(expectedPositions); + assertEquals(new GeoArray<>(expectedPositions), line.getCoordinates()); + + expectedPositions.add(new GeoPosition(1, 1)); + assertNotEquals(new GeoArray<>(expectedPositions), line.getCoordinates()); + } + + @ParameterizedTest + @MethodSource("equalsSupplier") + public void lineGeometriesEqual(GeoLineString line, Object obj, boolean expected) { + assertEquals(expected, line.equals(obj)); + } + + private static Stream equalsSupplier() { + List positions = Arrays.asList(new GeoPosition(0, 0), new GeoPosition(0, 1)); + List positions1 = Arrays.asList(new GeoPosition(0, 0), new GeoPosition(1, 1)); + + GeoBoundingBox boundingBox = new GeoBoundingBox(0, 0, 1, 1); + Map properties = Collections.singletonMap("key", "value"); + + GeoLineString line = new GeoLineString(positions); + GeoLineString line1 = new GeoLineString(positions1, boundingBox, properties); + + return Stream.of( + // Other is null. + Arguments.of(line, null, false), + + // Other isn't instance of type. + Arguments.of(line, 1, false), + + // Other is itself. + Arguments.of(line, line, true), Arguments.of(line1, line1, true), + + // Other is a different value. + Arguments.of(line, line1, false), Arguments.of(line1, line, false), + + // Other is the same value. + Arguments.of(line, new GeoLineString(positions), true), + Arguments.of(line1, new GeoLineString(positions1, boundingBox, properties), true)); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoObjectTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoObjectTests.java new file mode 100644 index 000000000000..b7786543103e --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoObjectTests.java @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models.geo; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +/** + * Tests {@link GeoObject}. + */ +public class GeoObjectTests { + @Test + public void defaultGeo() { + GeoObject geoObject = new ConcreteGeoObject(null, null); + + Assertions.assertNull(geoObject.getCustomProperties()); + Assertions.assertNull(geoObject.getBoundingBox()); + } + + @Test + public void geoObjectCopiesPropertiesToUnmodifiableMap() { + Map properties = new HashMap<>(); + properties.put("key", "value"); + + GeoObject geoObject = new ConcreteGeoObject(null, properties); + + assertEquals(properties, geoObject.getCustomProperties()); + + properties.put("key2", "value2"); + assertNotEquals(properties, geoObject.getCustomProperties()); + + Assertions.assertThrows(UnsupportedOperationException.class, + () -> geoObject.getCustomProperties().put("key2", "value2")); + } + + @ParameterizedTest + @MethodSource("equalsSupplier") + public void geometriesEqual(GeoObject geoObject, Object obj, boolean expected) { + assertEquals(expected, geoObject.equals(obj)); + } + + private static Stream equalsSupplier() { + GeoObject geoObject = new ConcreteGeoObject(null, null); + GeoObject geoObject1 = new ConcreteGeoObject(null, Collections.singletonMap("key", "value")); + + return Stream.of( + // Other is null. + Arguments.of(geoObject, null, false), + + // Other isn't instance of type. + Arguments.of(geoObject, 1, false), + + // Other is itself. + Arguments.of(geoObject, geoObject, true), Arguments.of(geoObject1, geoObject1, true), + + // Other is a different value. + Arguments.of(geoObject, geoObject1, false), Arguments.of(geoObject1, geoObject, false), + + // Other is the same value. + Arguments.of(geoObject, new ConcreteGeoObject(null, null), true), + Arguments.of(geoObject1, new ConcreteGeoObject(null, Collections.singletonMap("key", "value")), true)); + } + + private static final class ConcreteGeoObject extends GeoObject { + ConcreteGeoObject(GeoBoundingBox boundingBox, Map properties) { + super(boundingBox, properties); + } + + @Override + public GeoObjectType getType() { + return null; + } + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoPointCollectionTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoPointCollectionTests.java new file mode 100644 index 000000000000..4025a120361a --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoPointCollectionTests.java @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models.geo; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +/** + * Tests {@link GeoPointCollectionTests}. + */ +public class GeoPointCollectionTests { + @Test + public void nullPointsThrows() { + Assertions.assertThrows(NullPointerException.class, () -> new GeoPointCollection(null)); + } + + @Test + public void simpleConstructor() { + List points = Arrays.asList(new GeoPoint(new GeoPosition(0, 0)), new GeoPoint(new GeoPosition(1, 1))); + + GeoPointCollection multiPoint = new GeoPointCollection(points); + + assertEquals(points, multiPoint.getPoints()); + + Assertions.assertNull(multiPoint.getBoundingBox()); + Assertions.assertNull(multiPoint.getCustomProperties()); + } + + @Test + public void complexConstructor() { + List points = Arrays.asList(new GeoPoint(new GeoPosition(0, 0)), new GeoPoint(new GeoPosition(1, 1))); + + GeoBoundingBox boundingBox = new GeoBoundingBox(0, 0, 1, 1); + Map properties = Collections.singletonMap("key", "value"); + + GeoPointCollection multiPoint = new GeoPointCollection(points, boundingBox, properties); + + assertEquals(points, multiPoint.getPoints()); + assertEquals(boundingBox, multiPoint.getBoundingBox()); + assertEquals(properties, multiPoint.getCustomProperties()); + } + + @Test + public void constructorCopiesPoints() { + List points = new ArrayList<>(); + points.add(new GeoPoint(new GeoPosition(0, 0))); + points.add(new GeoPoint(new GeoPosition(1, 1))); + + GeoPointCollection multiPoint = new GeoPointCollection(points); + assertEquals(points, multiPoint.getPoints()); + + points.add(new GeoPoint(new GeoPosition(0, 1))); + assertNotEquals(points, multiPoint.getPoints()); + } + + @ParameterizedTest + @MethodSource("equalsSupplier") + public void multiPointGeometriesEquals(GeoPointCollection multiPoint, Object obj, boolean expected) { + assertEquals(expected, multiPoint.equals(obj)); + } + + private static Stream equalsSupplier() { + List points = Arrays.asList(new GeoPoint(new GeoPosition(0, 0)), new GeoPoint(new GeoPosition(1, 1))); + + List points1 + = Arrays.asList(new GeoPoint(new GeoPosition(0, 0)), new GeoPoint(new GeoPosition(0, 1))); + + GeoBoundingBox boundingBox = new GeoBoundingBox(0, 0, 1, 1); + Map properties = Collections.singletonMap("key", "value"); + + GeoPointCollection multiPoint = new GeoPointCollection(points); + GeoPointCollection multiPoint1 = new GeoPointCollection(points1, boundingBox, properties); + + return Stream.of( + // Other is null. + Arguments.of(multiPoint, null, false), + + // Other isn't instance of type. + Arguments.of(multiPoint, 1, false), + + // Other is itself. + Arguments.of(multiPoint, multiPoint, true), Arguments.of(multiPoint1, multiPoint1, true), + + // Other is a different value. + Arguments.of(multiPoint, multiPoint1, false), Arguments.of(multiPoint1, multiPoint, false), + + // Other is the same value. + Arguments.of(multiPoint, new GeoPointCollection(points), true), + Arguments.of(multiPoint1, new GeoPointCollection(points1, boundingBox, properties), true)); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoPointTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoPointTests.java new file mode 100644 index 000000000000..42e52b6c9bec --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoPointTests.java @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models.geo; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.Collections; +import java.util.Map; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Tests {@link GeoPoint}. + */ +public class GeoPointTests { + @Test + public void nullPositionThrows() { + Assertions.assertThrows(NullPointerException.class, () -> new GeoPoint(null)); + } + + @Test + public void simpleConstructor() { + GeoPosition position = new GeoPosition(0, 0); + + GeoPoint point = new GeoPoint(position); + + assertEquals(position, point.getCoordinates()); + + Assertions.assertNull(point.getBoundingBox()); + Assertions.assertNull(point.getCustomProperties()); + } + + @Test + public void complexConstructor() { + GeoPosition position = new GeoPosition(0, 0); + GeoBoundingBox boundingBox = new GeoBoundingBox(0, 0, 1, 1); + Map properties = Collections.singletonMap("key", "value"); + + GeoPoint point = new GeoPoint(position, boundingBox, properties); + + assertEquals(position, point.getCoordinates()); + assertEquals(boundingBox, point.getBoundingBox()); + assertEquals(properties, point.getCustomProperties()); + } + + @ParameterizedTest + @MethodSource("equalsSupplier") + public void pointGeometriesEquals(GeoPoint point, Object obj, boolean expected) { + assertEquals(expected, point.equals(obj)); + } + + private static Stream equalsSupplier() { + GeoPosition position = new GeoPosition(0, 0); + GeoPosition position1 = new GeoPosition(1, 1); + + GeoBoundingBox boundingBox = new GeoBoundingBox(0, 0, 1, 1); + Map properties = Collections.singletonMap("key", "value"); + + GeoPoint point = new GeoPoint(position); + GeoPoint point1 = new GeoPoint(position1, boundingBox, properties); + + return Stream.of( + // Other is null. + Arguments.of(point, null, false), + + // Other isn't instance of type. + Arguments.of(point, 1, false), + + // Other is itself. + Arguments.of(point, point, true), Arguments.of(point1, point1, true), + + // Other is a different value. + Arguments.of(point, point1, false), Arguments.of(point1, point, false), + + // Other is the same value. + Arguments.of(point, new GeoPoint(position), true), + Arguments.of(point1, new GeoPoint(position1, boundingBox, properties), true)); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoPolygonCollectionTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoPolygonCollectionTests.java new file mode 100644 index 000000000000..d69b625971b5 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoPolygonCollectionTests.java @@ -0,0 +1,107 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models.geo; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import static io.clientcore.core.models.geo.GeoTestHelpers.RECTANGLE_POLYGON; +import static io.clientcore.core.models.geo.GeoTestHelpers.SQUARE_POLYGON; +import static io.clientcore.core.models.geo.GeoTestHelpers.TRIANGLE_POLYGON; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +/** + * Tests {@link GeoPolygonCollection}. + */ +public class GeoPolygonCollectionTests { + @Test + public void nullPolygonsThrows() { + Assertions.assertThrows(NullPointerException.class, () -> new GeoPolygonCollection(null)); + } + + @Test + public void simpleConstructor() { + List polygons = Arrays.asList(TRIANGLE_POLYGON.get(), SQUARE_POLYGON.get()); + + GeoPolygonCollection multiPolygon = new GeoPolygonCollection(polygons); + + assertEquals(polygons, multiPolygon.getPolygons()); + + Assertions.assertNull(multiPolygon.getBoundingBox()); + Assertions.assertNull(multiPolygon.getCustomProperties()); + } + + @Test + public void complexConstructor() { + List polygons = Arrays.asList(TRIANGLE_POLYGON.get(), SQUARE_POLYGON.get()); + + GeoBoundingBox boundingBox = new GeoBoundingBox(0, 0, 1, 1); + Map properties = Collections.singletonMap("key", "value"); + + GeoPolygonCollection multiPolygon = new GeoPolygonCollection(polygons, boundingBox, properties); + + assertEquals(polygons, multiPolygon.getPolygons()); + assertEquals(boundingBox, multiPolygon.getBoundingBox()); + assertEquals(properties, multiPolygon.getCustomProperties()); + } + + @Test + public void constructorCopiesPolygons() { + List polygons = new ArrayList<>(); + polygons.add(TRIANGLE_POLYGON.get()); + polygons.add(SQUARE_POLYGON.get()); + + GeoPolygonCollection multiPolygon = new GeoPolygonCollection(polygons); + assertEquals(polygons, multiPolygon.getPolygons()); + + polygons.add(RECTANGLE_POLYGON.get()); + + assertNotEquals(polygons, multiPolygon.getPolygons()); + } + + @ParameterizedTest + @MethodSource("equalsSupplier") + public void multiPolygonGeometriesEquals(GeoPolygonCollection multiPolygon, Object obj, boolean expected) { + assertEquals(expected, multiPolygon.equals(obj)); + } + + private static Stream equalsSupplier() { + List polygons = Arrays.asList(TRIANGLE_POLYGON.get(), SQUARE_POLYGON.get()); + List polygons1 = Arrays.asList(TRIANGLE_POLYGON.get(), RECTANGLE_POLYGON.get()); + + GeoBoundingBox boundingBox = new GeoBoundingBox(0, 0, 2, 2); + Map properties = Collections.singletonMap("key", "value"); + + GeoPolygonCollection multiPolygon = new GeoPolygonCollection(polygons); + GeoPolygonCollection multiPolygon1 = new GeoPolygonCollection(polygons1, boundingBox, properties); + + return Stream.of( + // Other is null. + Arguments.of(multiPolygon, null, false), + + // Other isn't instance of type. + Arguments.of(multiPolygon, 1, false), + + // Other is itself. + Arguments.of(multiPolygon, multiPolygon, true), Arguments.of(multiPolygon1, multiPolygon1, true), + + // Other is a different value. + Arguments.of(multiPolygon, multiPolygon1, false), Arguments.of(multiPolygon1, multiPolygon, false), + + // Other is the same value. + Arguments.of(multiPolygon, new GeoPolygonCollection(polygons), true), + Arguments.of(multiPolygon1, new GeoPolygonCollection(polygons1, boundingBox, properties), true)); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoPolygonTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoPolygonTests.java new file mode 100644 index 000000000000..34ab67e877cd --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoPolygonTests.java @@ -0,0 +1,100 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models.geo; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +/** + * Tests {@link GeoPolygon}. + */ +public class GeoPolygonTests { + @Test + public void nullRingsThrows() { + Assertions.assertThrows(NullPointerException.class, () -> new GeoPolygon((GeoLinearRing) null)); + } + + @Test + public void simpleConstructor() { + List rings = Collections.singletonList(new GeoLinearRing(GeoTestHelpers.SQUARE_LINE_POSITIONS)); + + GeoPolygon polygon = new GeoPolygon(new GeoLinearRing(GeoTestHelpers.SQUARE_LINE.get().getCoordinates())); + + assertEquals(rings, polygon.getRings()); + + Assertions.assertNull(polygon.getBoundingBox()); + Assertions.assertNull(polygon.getCustomProperties()); + } + + @Test + public void complexConstructor() { + List rings = Collections.singletonList(new GeoLinearRing(GeoTestHelpers.SQUARE_LINE_POSITIONS)); + GeoBoundingBox boundingBox = new GeoBoundingBox(0, 0, 1, 1); + Map properties = Collections.singletonMap("key", "value"); + + GeoPolygon polygon = new GeoPolygon(rings, boundingBox, properties); + + assertEquals(rings, polygon.getRings()); + assertEquals(boundingBox, polygon.getBoundingBox()); + assertEquals(properties, polygon.getCustomProperties()); + } + + @Test + public void constructorCopiesRings() { + List rings = new ArrayList<>(); + rings.add(new GeoLinearRing(GeoTestHelpers.SQUARE_LINE_POSITIONS)); + + GeoPolygon polygon = new GeoPolygon(rings); + assertEquals(rings, polygon.getRings()); + + rings.add(new GeoLinearRing(GeoTestHelpers.TRIANGLE_LINE_POSITIONS)); + assertNotEquals(rings, polygon.getRings()); + } + + @ParameterizedTest + @MethodSource("equalsSupplier") + public void polygonGeometriesEquals(GeoPolygon polygon, Object obj, boolean expected) { + assertEquals(expected, polygon.equals(obj)); + } + + private static Stream equalsSupplier() { + GeoLinearRing squareLine = new GeoLinearRing(GeoTestHelpers.SQUARE_LINE_POSITIONS); + GeoLinearRing triangleLine = new GeoLinearRing(GeoTestHelpers.TRIANGLE_LINE_POSITIONS); + + GeoBoundingBox boundingBox = new GeoBoundingBox(0, 0, 1, 1); + Map properties = Collections.singletonMap("key", "value"); + + GeoPolygon polygon = new GeoPolygon(squareLine); + GeoPolygon polygon1 = new GeoPolygon(triangleLine, boundingBox, properties); + + return Stream.of( + // Other is null. + Arguments.of(polygon, null, false), + + // Other isn't instance of type. + Arguments.of(polygon, 1, false), + + // Other is itself. + Arguments.of(polygon, polygon, true), Arguments.of(polygon1, polygon1, true), + + // Other is a different value. + Arguments.of(polygon, polygon1, false), Arguments.of(polygon1, polygon, false), + + // Other is the same value. + Arguments.of(polygon, new GeoPolygon(squareLine), true), + Arguments.of(polygon1, new GeoPolygon(triangleLine, boundingBox, properties), true)); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoPositionTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoPositionTests.java new file mode 100644 index 000000000000..eefae26141ae --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoPositionTests.java @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models.geo; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static io.clientcore.core.models.geo.GeoTestHelpers.MT_RAINIER_POSITION; +import static io.clientcore.core.models.geo.GeoTestHelpers.PIKES_PLACE_POSITION; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class GeoPositionTests { + @Test + public void simpleConstructor() { + double expectedLongitude = -180; + double expectedLatitude = -90; + + GeoPosition position = new GeoPosition(expectedLongitude, expectedLatitude); + + assertEquals(expectedLongitude, position.getLongitude()); + assertEquals(expectedLatitude, position.getLatitude()); + + Assertions.assertNull(position.getAltitude()); + } + + @Test + public void complexConstructor() { + double expectedLongitude = -180; + double expectedLatitude = -90; + double expectedAltitude = 1000; + + GeoPosition position = new GeoPosition(expectedLongitude, expectedLatitude, expectedAltitude); + + assertEquals(expectedLongitude, position.getLongitude()); + assertEquals(expectedLatitude, position.getLatitude()); + assertEquals(expectedAltitude, position.getAltitude()); + } + + @Test + public void constructorDoesNotValidate() { + double expectedLongitude = -200; + double expectedLatitude = -100; + + GeoPosition position = new GeoPosition(expectedLongitude, expectedLatitude); + + assertEquals(expectedLongitude, position.getLongitude()); + assertEquals(expectedLatitude, position.getLatitude()); + } + + @ParameterizedTest + @MethodSource("equalsSupplier") + public void geoPositionEquals(GeoPosition position, Object obj, boolean expected) { + assertEquals(expected, position.equals(obj)); + } + + private static Stream equalsSupplier() { + GeoPosition pikePlacePosition = PIKES_PLACE_POSITION.get(); + GeoPosition mtRainierPosition = MT_RAINIER_POSITION.get(); + + return Stream.of( + // Other is null. + Arguments.of(pikePlacePosition, null, false), + + // Other isn't instance of type. + Arguments.of(pikePlacePosition, 1, false), + + // Other is itself. + Arguments.of(pikePlacePosition, pikePlacePosition, true), + Arguments.of(mtRainierPosition, mtRainierPosition, true), + + // Other is a different value. + Arguments.of(pikePlacePosition, mtRainierPosition, false), + Arguments.of(mtRainierPosition, pikePlacePosition, false), + + // Other is the same value. + Arguments.of(pikePlacePosition, PIKES_PLACE_POSITION.get(), true), + Arguments.of(mtRainierPosition, MT_RAINIER_POSITION.get(), true)); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoSerializationTestHelpers.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoSerializationTestHelpers.java new file mode 100644 index 000000000000..5ec335f20ab6 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoSerializationTestHelpers.java @@ -0,0 +1,260 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models.geo; + +import io.clientcore.core.serialization.json.JsonWriter; +import io.clientcore.core.serialization.json.implementation.StringBuilderWriter; +import io.clientcore.core.utils.CoreUtils; + +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * Test helpers for {@link GeoJsonDeserializerTests} and {@link GeoJsonSerializerTests}. + */ +public class GeoSerializationTestHelpers { + static String geoToJson(GeoObject geoObject) { + if (geoObject instanceof GeoPoint) { + return pointToJson((GeoPoint) geoObject); + } else if (geoObject instanceof GeoLineString) { + return lineToJson((GeoLineString) geoObject); + } else if (geoObject instanceof GeoPolygon) { + return polygonToJson((GeoPolygon) geoObject); + } else if (geoObject instanceof GeoPointCollection) { + return multiPointToJson((GeoPointCollection) geoObject); + } else if (geoObject instanceof GeoLineStringCollection) { + return multiLineToJson((GeoLineStringCollection) geoObject); + } else if (geoObject instanceof GeoPolygonCollection) { + return multiPolygonToJson((GeoPolygonCollection) geoObject); + } else if (geoObject instanceof GeoCollection) { + return collectionToJson((GeoCollection) geoObject); + } else { + throw new IllegalStateException("Unknown geo type."); + } + } + + private static String pointToJson(GeoPoint point) { + StringBuilder builder = new StringBuilder("{"); + addType(GeoObjectType.POINT, builder); + + builder.append(",\"coordinates\":"); + addPosition(point.getCoordinates(), builder); + + addAdditionalProperties(point, builder); + + builder.append("}"); + + return builder.toString(); + } + + private static String lineToJson(GeoLineString line) { + StringBuilder builder = new StringBuilder("{"); + addType(GeoObjectType.LINE_STRING, builder); + + builder.append(",\"coordinates\":"); + addLine(line.getCoordinates(), builder); + + addAdditionalProperties(line, builder); + + builder.append("}"); + + return builder.toString(); + } + + private static String polygonToJson(GeoPolygon polygon) { + StringBuilder builder = new StringBuilder("{"); + addType(GeoObjectType.POLYGON, builder); + + builder.append(",\"coordinates\":"); + addPolygon(polygon.getRings(), builder); + + addAdditionalProperties(polygon, builder); + + builder.append("}"); + + return builder.toString(); + } + + private static String multiPointToJson(GeoPointCollection multiPoint) { + StringBuilder builder = new StringBuilder("{"); + addType(GeoObjectType.MULTI_POINT, builder); + + builder.append(",\"coordinates\":"); + addLine(multiPoint.getPoints().stream().map(GeoPoint::getCoordinates).collect(Collectors.toList()), builder); + + addAdditionalProperties(multiPoint, builder); + + builder.append("}"); + + return builder.toString(); + + } + + private static String multiLineToJson(GeoLineStringCollection multiLine) { + StringBuilder builder = new StringBuilder("{"); + addType(GeoObjectType.MULTI_LINE_STRING, builder); + + builder.append(",\"coordinates\":["); + for (int i = 0; i < multiLine.getLines().size(); i++) { + if (i > 0) { + builder.append(","); + } + + addLine(multiLine.getLines().get(i).getCoordinates(), builder); + } + + builder.append("]"); + + addAdditionalProperties(multiLine, builder); + + builder.append("}"); + + return builder.toString(); + } + + private static String multiPolygonToJson(GeoPolygonCollection multiPolygon) { + StringBuilder builder = new StringBuilder("{"); + addType(GeoObjectType.MULTI_POLYGON, builder); + + builder.append(",\"coordinates\":["); + + for (int i = 0; i < multiPolygon.getPolygons().size(); i++) { + if (i > 0) { + builder.append(","); + } + + addPolygon(multiPolygon.getPolygons().get(i).getRings(), builder); + } + + builder.append("]"); + + addAdditionalProperties(multiPolygon, builder); + + builder.append("}"); + + return builder.toString(); + } + + private static String collectionToJson(GeoCollection collection) { + StringBuilder builder = new StringBuilder("{"); + addType(GeoObjectType.GEOMETRY_COLLECTION, builder); + + builder.append(",\"geometries\":["); + + for (int i = 0; i < collection.getGeometries().size(); i++) { + if (i > 0) { + builder.append(","); + } + + builder.append(geoToJson(collection.getGeometries().get(i))); + } + + builder.append("]"); + + addAdditionalProperties(collection, builder); + + builder.append("}"); + + return builder.toString(); + } + + private static void addType(GeoObjectType type, StringBuilder builder) { + builder.append("\"type\":\"").append(type.getValue()).append("\""); + } + + private static void addPosition(GeoPosition position, StringBuilder builder) { + builder.append("[").append(position.getLongitude()).append(",").append(position.getLatitude()); + + Double altitude = position.getAltitude(); + if (altitude != null) { + builder.append(",").append(altitude); + } + + builder.append("]"); + } + + private static void addLine(List positions, StringBuilder builder) { + builder.append("["); + + for (int i = 0; i < positions.size(); i++) { + if (i > 0) { + builder.append(","); + } + + addPosition(positions.get(i), builder); + } + + builder.append("]"); + } + + private static void addPolygon(List rings, StringBuilder builder) { + builder.append("["); + + for (int i = 0; i < rings.size(); i++) { + if (i > 0) { + builder.append(","); + } + + addLine(rings.get(i).getCoordinates(), builder); + } + + builder.append("]"); + } + + private static void addAdditionalProperties(GeoObject geoObject, StringBuilder builder) { + addBoundingBox(geoObject.getBoundingBox(), builder); + addProperties(geoObject.getCustomProperties(), builder); + } + + private static void addBoundingBox(GeoBoundingBox boundingBox, StringBuilder builder) { + if (boundingBox == null) { + return; + } + + builder.append(",\"bbox\":[") + .append(boundingBox.getWest()) + .append(",") + .append(boundingBox.getSouth()) + .append(","); + + Double minAltitude = boundingBox.getMinAltitude(); + if (minAltitude != null) { + builder.append(minAltitude).append(","); + } + + builder.append(boundingBox.getEast()).append(",").append(boundingBox.getNorth()); + + Double maxAltitude = boundingBox.getMaxAltitude(); + if (maxAltitude != null) { + builder.append(",").append(maxAltitude); + } + + builder.append("]"); + } + + private static void addProperties(Map properties, StringBuilder builder) { + if (CoreUtils.isNullOrEmpty(properties)) { + return; + } + + try { + for (Map.Entry property : properties.entrySet()) { + if (builder.length() > 0) { + builder.append(","); + } + + builder.append("\"").append(property.getKey()).append("\":"); + + StringBuilderWriter writer = new StringBuilderWriter(builder); + try (JsonWriter jsonWriter = JsonWriter.toWriter(writer)) { + jsonWriter.writeUntyped(property.getValue()); + } + } + } catch (IOException ex) { + throw new RuntimeException(ex); + } + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoTestHelpers.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoTestHelpers.java new file mode 100644 index 000000000000..5427f4838ff2 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/models/geo/GeoTestHelpers.java @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.models.geo; + +import java.util.Arrays; +import java.util.List; +import java.util.function.Supplier; + +/** + * Helper methods when running geo tests. + */ +public class GeoTestHelpers { + public static final Supplier PIKES_PLACE_POSITION = () -> new GeoPosition(-122.342148, 47.609657); + + public static final Supplier PIKES_PLACE_BOUNDING_BOX + = () -> new GeoBoundingBox(-122.349408, 47.604448, -122.334368, 47.610870); + + public static final Supplier MT_RAINIER_POSITION + = () -> new GeoPosition(-121.726906, 46.879967, 4392D); + + public static final Supplier MT_RAINIER_BOUNDING_BOX + = () -> new GeoBoundingBox(-121.993999, 46.713820, -121.528334, 47.035690, 0D, 4500D); + + public static final List TRIANGLE_LINE_POSITIONS + = Arrays.asList(new GeoPosition(0, 0), new GeoPosition(1, 1), new GeoPosition(0, 1), new GeoPosition(0, 0)); + + public static final Supplier TRIANGLE_LINE = () -> new GeoLineString(TRIANGLE_LINE_POSITIONS); + + public static final Supplier TRIANGLE_POLYGON + = () -> new GeoPolygon(new GeoLinearRing(TRIANGLE_LINE_POSITIONS)); + + public static final List SQUARE_LINE_POSITIONS = Arrays.asList(new GeoPosition(0, 0), + new GeoPosition(0, 1), new GeoPosition(1, 1), new GeoPosition(1, 0), new GeoPosition(0, 0)); + + public static final Supplier SQUARE_LINE = () -> new GeoLineString(SQUARE_LINE_POSITIONS); + + public static final Supplier SQUARE_POLYGON + = () -> new GeoPolygon(new GeoLinearRing(SQUARE_LINE_POSITIONS)); + + public static final List RECTANGLE_LINE_POSITIONS = Arrays.asList(new GeoPosition(0, 0), + new GeoPosition(0, 2), new GeoPosition(1, 2), new GeoPosition(1, 0), new GeoPosition(0, 0)); + + public static final Supplier RECTANGLE_LINE = () -> new GeoLineString(RECTANGLE_LINE_POSITIONS); + + public static final Supplier RECTANGLE_POLYGON + = () -> new GeoPolygon(new GeoLinearRing(RECTANGLE_LINE_POSITIONS)); +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/JsonProvidersTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/JsonProvidersTests.java deleted file mode 100644 index 576e48c07d94..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/JsonProvidersTests.java +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.serialization.json; - -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; -import java.io.StringReader; -import java.io.StringWriter; -import java.io.Writer; -import java.lang.invoke.MethodHandles; -import java.lang.reflect.Method; -import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertThrows; - -/** - * Tests {@link JsonProviders}. - */ -public class JsonProvidersTests { - private static final MethodHandles.Lookup PUBLIC_LOOKUP = MethodHandles.publicLookup(); - - @ParameterizedTest - @MethodSource("nullJsonSupplier") - public void nullJsonThrowsNullPointerException(Method creator, boolean useOptions) { - if (useOptions) { - assertThrows(NullPointerException.class, - () -> PUBLIC_LOOKUP.unreflect(creator).invokeWithArguments(null, new JsonOptions())); - } else { - assertThrows(NullPointerException.class, - () -> PUBLIC_LOOKUP.unreflect(creator).invokeWithArguments((Object) null)); - } - } - - private static Stream nullJsonSupplier() throws NoSuchMethodException { - return Stream.of(Arguments.of(JsonProviders.class.getDeclaredMethod("createReader", byte[].class), false), - Arguments.of(JsonProviders.class.getDeclaredMethod("createReader", byte[].class, JsonOptions.class), true), - Arguments.of(JsonProviders.class.getDeclaredMethod("createReader", String.class), false), - Arguments.of(JsonProviders.class.getDeclaredMethod("createReader", String.class, JsonOptions.class), true), - Arguments.of(JsonProviders.class.getDeclaredMethod("createReader", InputStream.class), false), - Arguments.of(JsonProviders.class.getDeclaredMethod("createReader", InputStream.class, JsonOptions.class), - true), - Arguments.of(JsonProviders.class.getDeclaredMethod("createReader", Reader.class), false), - Arguments.of(JsonProviders.class.getDeclaredMethod("createReader", Reader.class, JsonOptions.class), true), - Arguments.of(JsonProviders.class.getDeclaredMethod("createWriter", OutputStream.class), false), - Arguments.of(JsonProviders.class.getDeclaredMethod("createWriter", OutputStream.class, JsonOptions.class), - true), - Arguments.of(JsonProviders.class.getDeclaredMethod("createWriter", Writer.class), false), - Arguments.of(JsonProviders.class.getDeclaredMethod("createWriter", Writer.class, JsonOptions.class), true)); - } - - @ParameterizedTest - @MethodSource("nonNullJsonSupplier") - public void nullJsonOptionsThrowsNullPointerException(Method creator, T json, boolean useOptions) { - if (useOptions) { - assertThrows(NullPointerException.class, - () -> PUBLIC_LOOKUP.unreflect(creator).invokeWithArguments(json, null)); - } else { - assertDoesNotThrow(() -> PUBLIC_LOOKUP.unreflect(creator).invokeWithArguments(json)); - } - } - - @ParameterizedTest - @MethodSource("nonNullJsonSupplier") - public void canCreate(Method creator, T json, boolean useOptions) { - if (useOptions) { - assertDoesNotThrow(() -> PUBLIC_LOOKUP.unreflect(creator).invokeWithArguments(json, new JsonOptions())); - } else { - assertDoesNotThrow(() -> PUBLIC_LOOKUP.unreflect(creator).invokeWithArguments(json)); - } - } - - private static Stream nonNullJsonSupplier() throws NoSuchMethodException { - return Stream.of( - Arguments.of(JsonProviders.class.getDeclaredMethod("createReader", byte[].class), new byte[0], false), - Arguments.of(JsonProviders.class.getDeclaredMethod("createReader", byte[].class, JsonOptions.class), - new byte[0], true), - Arguments.of(JsonProviders.class.getDeclaredMethod("createReader", String.class), "", false), - Arguments.of(JsonProviders.class.getDeclaredMethod("createReader", String.class, JsonOptions.class), "", - true), - Arguments.of(JsonProviders.class.getDeclaredMethod("createReader", InputStream.class), - new ByteArrayInputStream(new byte[0]), false), - Arguments.of(JsonProviders.class.getDeclaredMethod("createReader", InputStream.class, JsonOptions.class), - new ByteArrayInputStream(new byte[0]), true), - Arguments.of(JsonProviders.class.getDeclaredMethod("createReader", Reader.class), new StringReader(""), - false), - Arguments.of(JsonProviders.class.getDeclaredMethod("createReader", Reader.class, JsonOptions.class), - new StringReader(""), true), - Arguments.of(JsonProviders.class.getDeclaredMethod("createWriter", OutputStream.class), - new ByteArrayOutputStream(), false), - Arguments.of(JsonProviders.class.getDeclaredMethod("createWriter", OutputStream.class, JsonOptions.class), - new ByteArrayOutputStream(), true), - Arguments.of(JsonProviders.class.getDeclaredMethod("createWriter", Writer.class), new StringWriter(), - false), - Arguments.of(JsonProviders.class.getDeclaredMethod("createWriter", Writer.class, JsonOptions.class), - new StringWriter(), true)); - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/JsonReaderTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/JsonReaderTests.java new file mode 100644 index 000000000000..8d77fb5444c7 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/JsonReaderTests.java @@ -0,0 +1,830 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.serialization.json; + +import io.clientcore.core.utils.IOExceptionCheckedFunction; +import org.junit.jupiter.api.Named; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.Consumer; +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.assertIterableEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * Tests {@link JsonReader}. + */ +public class JsonReaderTests { + private static final String JSON_WITH_COMMENTS = "{ // single line comment\n\"single-line\":\"comment\",\n/*\n" + + "multi-line comment\n*/\n\"multi-line\":\"comment\"}"; + + @ParameterizedTest + @MethodSource("basicOperationsSupplier") + public void basicOperations(String json, T expectedValue, IOExceptionCheckedFunction function) + throws IOException { + readAndValidate(json, function, actual -> assertEquals(expectedValue, actual)); + } + + private static Stream basicOperationsSupplier() { + UUID uuid = UUID.randomUUID(); + return Stream.of( + // Value handling. + + // Boolean + Arguments.of("false", false, read(JsonReader::getBoolean)), + Arguments.of("true", true, read(JsonReader::getBoolean)), + Arguments.of("null", null, read(reader -> reader.getNullable(JsonReader::getBoolean))), + + // Double + Arguments.of("-42.0", -42D, read(JsonReader::getDouble)), + Arguments.of("-42", -42D, read(JsonReader::getDouble)), + Arguments.of("42.0", 42D, read(JsonReader::getDouble)), + Arguments.of("42", 42D, read(JsonReader::getDouble)), + Arguments.of("null", null, read(reader -> reader.getNullable(JsonReader::getDouble))), + + // Float + Arguments.of("-42.0", -42F, read(JsonReader::getFloat)), + Arguments.of("-42", -42F, read(JsonReader::getFloat)), + Arguments.of("42.0", 42F, read(JsonReader::getFloat)), Arguments.of("42", 42F, read(JsonReader::getFloat)), + Arguments.of("null", null, read(reader -> reader.getNullable(JsonReader::getFloat))), + + // Integer + Arguments.of("-42", -42, read(JsonReader::getInt)), Arguments.of("42", 42, read(JsonReader::getInt)), + Arguments.of("null", null, read(reader -> reader.getNullable(JsonReader::getInt))), + + // Long + Arguments.of("-42", -42L, read(JsonReader::getLong)), Arguments.of("42", 42L, read(JsonReader::getLong)), + Arguments.of("null", null, read(reader -> reader.getNullable(JsonReader::getLong))), + + // String + Arguments.of("null", null, read(JsonReader::getString)), + Arguments.of("\"\"", "", read(JsonReader::getString)), + Arguments.of("\"hello\"", "hello", read(JsonReader::getString)), + + // Nullable + Arguments.of("\"" + uuid + "\"", uuid, + read(reader -> reader.getNullable(reader1 -> UUID.fromString(reader1.getString()))))); + } + + // Byte arrays can't use Object.equals as they'll be compared by memory location instead of value equality. + @ParameterizedTest + @MethodSource("binaryOperationsSupplier") + public void binaryOperations(String json, byte[] expectedValue, + IOExceptionCheckedFunction function) throws IOException { + readAndValidate(json, function, actual -> assertArrayEquals(expectedValue, actual)); + } + + private static Stream binaryOperationsSupplier() { + return Stream.of( + // Binary + Arguments.of("null", null, read(JsonReader::getBinary)), + Arguments.of("\"\"", new byte[0], read(JsonReader::getBinary)), + Arguments.of("\"" + Base64.getEncoder().encodeToString("Hello".getBytes(StandardCharsets.UTF_8)) + "\"", + "Hello".getBytes(StandardCharsets.UTF_8), read(JsonReader::getBinary))); + } + + @Test + public void emptyObject() throws IOException { + String json = "{}"; + try (JsonReader reader = JsonReader.fromString(json)) { + + assertJsonReaderStructInitialization(reader, JsonToken.START_OBJECT); + + while (reader.nextToken() != JsonToken.END_OBJECT) { + fail("Empty object shouldn't have any non-END_OBJECT JsonTokens but found: " + reader.currentToken()); + } + } + } + + @Test + public void emptyArray() throws IOException { + String json = "[]"; + try (JsonReader reader = JsonReader.fromString(json)) { + + assertJsonReaderStructInitialization(reader, JsonToken.START_ARRAY); + + while (reader.nextToken() != JsonToken.END_ARRAY) { + fail("Empty array shouldn't have any non-END_ARRAY JsonTokens but found: " + reader.currentToken()); + } + } + } + + @Test + public void simpleObject() throws IOException { + String json + = "{\"stringProperty\":\"string\",\"nullProperty\":null,\"integerProperty\":10,\"floatProperty\":10.0,\"booleanProperty\":true}"; + try (JsonReader reader = JsonReader.fromString(json)) { + + assertJsonReaderStructInitialization(reader, JsonToken.START_OBJECT); + + String stringProperty = null; + boolean hasNullProperty = false; + int integerProperty = 0; + float floatProperty = 0.0F; + boolean booleanProperty = false; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("stringProperty".equals(fieldName)) { + stringProperty = reader.getString(); + } else if ("nullProperty".equals(fieldName)) { + hasNullProperty = true; + } else if ("integerProperty".equals(fieldName)) { + integerProperty = reader.getInt(); + } else if ("floatProperty".equals(fieldName)) { + floatProperty = reader.getFloat(); + } else if ("booleanProperty".equals(fieldName)) { + booleanProperty = reader.getBoolean(); + } else { + fail("Unknown property name: '" + fieldName + "'"); + } + } + + assertEquals("string", stringProperty); + assertTrue(hasNullProperty, "Didn't find the expected 'nullProperty'."); + assertEquals(10, integerProperty); + assertEquals(10.0F, floatProperty); + assertEquals(true, booleanProperty); + } + } + + @Test + public void arrayOfBasicTypesInJsonRoot() throws IOException { + String json = "[\"string\",null,10,10.0,true]"; + try (JsonReader reader = JsonReader.fromString(json)) { + + assertJsonReaderStructInitialization(reader, JsonToken.START_ARRAY); + + Object[] jsonArray = new Object[5]; + int jsonArrayIndex = 0; + while (reader.nextToken() != JsonToken.END_ARRAY) { + jsonArray[jsonArrayIndex++] = reader.readUntyped(); + } + + assertEquals("string", jsonArray[0]); + assertNull(jsonArray[1]); + assertEquals(10, jsonArray[2]); + assertEquals(10.0D, jsonArray[3]); + assertEquals(true, jsonArray[4]); + } + } + + @ParameterizedTest + @MethodSource("objectWithInnerObjectSupplier") + public void objectWithInnerObject(String json) throws IOException { + try (JsonReader reader = JsonReader.fromString(json)) { + + assertJsonReaderStructInitialization(reader, JsonToken.START_OBJECT); + + String stringProperty = null; + boolean hasNullProperty = false; + int integerProperty = 0; + float floatProperty = 0.0F; + boolean booleanProperty = false; + String innerStringProperty = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("stringProperty".equals(fieldName)) { + stringProperty = reader.getString(); + } else if ("nullProperty".equals(fieldName)) { + hasNullProperty = true; + } else if ("integerProperty".equals(fieldName)) { + integerProperty = reader.getInt(); + } else if ("floatProperty".equals(fieldName)) { + floatProperty = reader.getFloat(); + } else if ("booleanProperty".equals(fieldName)) { + booleanProperty = reader.getBoolean(); + } else if ("innerObject".equals(fieldName)) { + assertEquals(JsonToken.START_OBJECT, reader.currentToken()); + while (reader.nextToken() != JsonToken.END_OBJECT) { + fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("innerStringProperty".equals(fieldName)) { + innerStringProperty = reader.getString(); + } else { + fail("Unknown property name: '" + fieldName + "'"); + } + } + } else { + fail("Unknown property name: '" + fieldName + "'"); + } + } + + assertEquals("string", stringProperty); + assertTrue(hasNullProperty, "Didn't find the expected 'nullProperty'."); + assertEquals(10, integerProperty); + assertEquals(10.0F, floatProperty); + assertEquals(true, booleanProperty); + assertEquals("innerString", innerStringProperty); + } + } + + private static Stream objectWithInnerObjectSupplier() { + return Stream.of( + Arguments.of(Named.of("objectWithInnerObjectAsFirstProperty", + "{\"innerObject\":{\"innerStringProperty\":\"innerString\"},\"stringProperty\":\"string\"," + + "\"nullProperty\":null,\"integerProperty\":10,\"floatProperty\":10.0,\"booleanProperty\":true}")), + + Arguments.of(Named.of("objectWithInnerObjectAsMiddleProperty", + "{\"stringProperty\":\"string\",\"nullProperty\":null,\"integerProperty\":10," + + "\"innerObject\":{\"innerStringProperty\":\"innerString\"},\"floatProperty\":10.0," + + "\"booleanProperty\":true}")), + + Arguments.of(Named.of("objectWithInnerObjectAsLastProperty", + "{\"stringProperty\":\"string\",\"nullProperty\":null,\"integerProperty\":10,\"floatProperty\":10.0," + + "\"booleanProperty\":true,\"innerObject\":{\"innerStringProperty\":\"innerString\"}}"))); + } + + @ParameterizedTest + @MethodSource("objectWithInnerArraySupplier") + public void objectWithInnerArray(String json) throws IOException { + try (JsonReader reader = JsonReader.fromString(json)) { + + assertJsonReaderStructInitialization(reader, JsonToken.START_OBJECT); + + String stringProperty = null; + boolean hasNullProperty = false; + int integerProperty = 0; + float floatProperty = 0.0F; + boolean booleanProperty = false; + String innerStringProperty = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("stringProperty".equals(fieldName)) { + stringProperty = reader.getString(); + } else if ("nullProperty".equals(fieldName)) { + hasNullProperty = true; + } else if ("integerProperty".equals(fieldName)) { + integerProperty = reader.getInt(); + } else if ("floatProperty".equals(fieldName)) { + floatProperty = reader.getFloat(); + } else if ("booleanProperty".equals(fieldName)) { + booleanProperty = reader.getBoolean(); + } else if ("innerArray".equals(fieldName)) { + assertEquals(JsonToken.START_ARRAY, reader.currentToken()); + while (reader.nextToken() != JsonToken.END_ARRAY) { + if (innerStringProperty != null) { + fail("Only expected one value in the inner array but found more."); + } + innerStringProperty = reader.getString(); + } + } else { + fail("Unknown property name: '" + fieldName + "'"); + } + } + + assertEquals("string", stringProperty); + assertTrue(hasNullProperty, "Didn't find the expected 'nullProperty'."); + assertEquals(10, integerProperty); + assertEquals(10.0F, floatProperty); + assertEquals(true, booleanProperty); + assertEquals("innerString", innerStringProperty); + } + } + + private static Stream objectWithInnerArraySupplier() { + return Stream.of( + Arguments.of(Named.of("objectWithInnerArrayAsFirstProperty", + "{\"innerArray\":[\"innerString\"],\"stringProperty\":\"string\",\"nullProperty\":null," + + "\"integerProperty\":10,\"floatProperty\":10.0,\"booleanProperty\":true}")), + + Arguments.of(Named.of("objectWithInnerArrayAsMiddleProperty", + "{\"stringProperty\":\"string\",\"nullProperty\":null,\"integerProperty\":10," + + "\"innerArray\":[\"innerString\"],\"floatProperty\":10.0,\"booleanProperty\":true}")), + + Arguments.of(Named.of("objectWithInnerArrayAsLastProperty", + "{\"stringProperty\":\"string\",\"nullProperty\":null,\"integerProperty\":10,\"floatProperty\":10.0," + + "\"booleanProperty\":true,\"innerArray\":[\"innerString\"]}"))); + } + + @ParameterizedTest + @MethodSource("arrayWithInnerArraySupplier") + public void arrayWithInnerArray(String json) throws IOException { + try (JsonReader reader = JsonReader.fromString(json)) { + + assertJsonReaderStructInitialization(reader, JsonToken.START_ARRAY); + + Object[] jsonArray = new Object[6]; + int jsonArrayIndex = 0; + while (reader.nextToken() != JsonToken.END_ARRAY) { + if (reader.currentToken() == JsonToken.START_ARRAY) { + while (reader.nextToken() != JsonToken.END_ARRAY) { + if (jsonArray[5] != null) { + fail("Only expected one value in the inner array but found more."); + } + + jsonArray[5] = reader.getString(); + } + } else { + jsonArray[jsonArrayIndex++] = reader.readUntyped(); + } + } + + assertEquals("string", jsonArray[0]); + assertNull(jsonArray[1]); + assertEquals(10, jsonArray[2]); + assertEquals(10.0D, jsonArray[3]); + assertEquals(true, jsonArray[4]); + assertEquals("innerString", jsonArray[5]); + } + } + + private static Stream arrayWithInnerArraySupplier() { + return Stream.of( + Arguments + .of(Named.of("arrayWithInnerArrayAsFirstProperty", "[[\"innerString\"],\"string\",null,10,10.0,true]")), + + Arguments.of( + Named.of("arrayWithInnerArrayAsMiddleProperty", "[\"string\",null,10,[\"innerString\"],10.0,true]")), + + Arguments + .of(Named.of("arrayWithInnerArrayAsLastProperty", "[\"string\",null,10,10.0,true,[\"innerString\"]]"))); + } + + @ParameterizedTest + @MethodSource("arrayWithInnerObjectSupplier") + public void arrayWithInnerObject(String json) throws IOException { + try (JsonReader reader = JsonReader.fromString(json)) { + + assertJsonReaderStructInitialization(reader, JsonToken.START_ARRAY); + + Object[] jsonArray = new Object[6]; + int jsonArrayIndex = 0; + while (reader.nextToken() != JsonToken.END_ARRAY) { + if (reader.currentToken() == JsonToken.START_OBJECT) { + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("innerStringProperty".equals(fieldName)) { + jsonArray[5] = reader.getString(); + } else { + fail("Unknown property name: '" + fieldName + "'"); + } + } + } else { + jsonArray[jsonArrayIndex++] = reader.readUntyped(); + } + } + + assertEquals("string", jsonArray[0]); + assertNull(jsonArray[1]); + assertEquals(10, jsonArray[2]); + assertEquals(10.0D, jsonArray[3]); + assertEquals(true, jsonArray[4]); + assertEquals("innerString", jsonArray[5]); + } + } + + private static Stream arrayWithInnerObjectSupplier() { + return Stream.of( + Arguments.of(Named.of("arrayWithInnerObjectAsFirstProperty", + "[{\"innerStringProperty\":\"innerString\"},\"string\",null,10,10.0,true]")), + + Arguments.of(Named.of("arrayWithInnerObjectAsMiddleProperty", + "[\"string\",null,10,{\"innerStringProperty\":\"innerString\"},10.0,true]")), + + Arguments.of(Named.of("arrayWithInnerObjectAsLastProperty", + "[\"string\",null,10,10.0,true,{\"innerStringProperty\":\"innerString\"}]"))); + } + + @ParameterizedTest + @MethodSource("readUntypedSimpleSupplier") + public void readUntypedSimple(String json, int nextCount, Object expected) throws IOException { + try (JsonReader reader = JsonReader.fromString(json)) { + for (int i = 0; i < nextCount; i++) { + reader.nextToken(); + } + + Object actual = reader.readUntyped(); + assertEquals(expected, actual); + } + + } + + private static Stream readUntypedSimpleSupplier() { + return Stream.of(Arguments.of("null", 1, null), Arguments.of("true", 1, true), Arguments.of("false", 1, false), + Arguments.of("3.14", 1, 3.14), Arguments.of("NaN", 1, Double.NaN), + Arguments.of("-Infinity", 1, Double.NEGATIVE_INFINITY), + Arguments.of("Infinity", 1, Double.POSITIVE_INFINITY), Arguments.of("42", 1, 42), + Arguments.of("420000000000", 1, 420000000000L), Arguments.of("\"hello\"", 1, "hello")); + } + + @SuppressWarnings("unchecked") + @ParameterizedTest + @MethodSource("readUntypedArraySupplier") + public void readUntypedArray(String json, int nextCount, List expected) throws IOException { + try (JsonReader reader = JsonReader.fromString(json)) { + for (int i = 0; i < nextCount; i++) { + reader.nextToken(); + } + + List actual = (List) reader.readUntyped(); + assertIterableEquals(expected, actual); + } + + } + + private static Stream readUntypedArraySupplier() { + return Stream.of(Arguments.of("[]", 1, new ArrayList<>()), + Arguments.of("[42,true,\"hello\"]", 1, Arrays.asList(42, true, "hello"))); + } + + @SuppressWarnings("unchecked") + @ParameterizedTest + @MethodSource("readUntypedObjectSupplier") + public void readUntypedObject(String json, int nextCount, Map expected) throws IOException { + try (JsonReader reader = JsonReader.fromString(json)) { + for (int i = 0; i < nextCount; i++) { + reader.nextToken(); + } + + Map actual = (Map) reader.readUntyped(); + assertEquals(expected.size(), actual.size()); + for (Map.Entry expectedKvp : expected.entrySet()) { + assertTrue(actual.containsKey(expectedKvp.getKey())); + assertEquals(expectedKvp.getValue(), actual.get(expectedKvp.getKey())); + } + } + } + + private static Stream readUntypedObjectSupplier() { + Map complexExpected = new LinkedHashMap<>(); + complexExpected.put("field1", 42); + complexExpected.put("field2", true); + complexExpected.put("field3", "hello"); + + return Stream.of(Arguments.of("{}", 1, new LinkedHashMap<>()), + Arguments.of("{\"field1\":42,\"field2\":true,\"field3\":\"hello\"}", 1, complexExpected)); + } + + @ParameterizedTest + @MethodSource("readUntypedIllegalStartSupplier") + public void readUntypedIllegalStart(String json, int nextCount) throws IOException { + try (JsonReader reader = JsonReader.fromString(json)) { + for (int i = 0; i < nextCount; i++) { + reader.nextToken(); + } + + assertThrows(IllegalStateException.class, reader::readUntyped); + } + } + + private static Stream readUntypedIllegalStartSupplier() { + return Stream.of(Arguments.of("{}", 2), Arguments.of("[]", 2), Arguments.of("{\"field\":\"value\"}", 2)); + } + + @Test + public void readUntypedPreventsStackOverflow() throws IOException { + // At 1000 levels of nesting readUntyped will throw an exception. + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < 1001; i++) { + builder.append("{\"field\":"); + } + + builder.append("null"); + + for (int i = 0; i < 1001; i++) { + builder.append('}'); + } + + String deeplyNestJson = builder.toString(); + + try (JsonReader reader = JsonReader.fromString(deeplyNestJson)) { + reader.nextToken(); + assertThrows(IllegalStateException.class, reader::readUntyped); + } + } + + @ParameterizedTest + @MethodSource("bufferObjectSupplier") + public void bufferObject(String json, int nextCount) throws IOException { + try (JsonReader reader = JsonReader.fromString(json)) { + + for (int i = 0; i < nextCount; i++) { + reader.nextToken(); + } + + JsonReader buffer = reader.bufferObject(); + TestData testData = TestData.fromJson(buffer); + + assertEquals("test", testData.getTest()); + } + } + + private static Stream bufferObjectSupplier() { + return Stream.of(Arguments.of("{\"test\":\"test\"}", 1), + Arguments.of("{\"outerfield\":{\"test\":\"test\"}}", 3)); + } + + @ParameterizedTest + @MethodSource("bufferObjectIllegalStateSupplier") + public void bufferObjectIllegalState(String json, int nextCount) throws IOException { + try (JsonReader reader = JsonReader.fromString(json)) { + + for (int i = 0; i < nextCount; i++) { + reader.nextToken(); + } + + assertThrows(IllegalStateException.class, reader::bufferObject); + } + } + + private static Stream bufferObjectIllegalStateSupplier() { + return Stream.of(Arguments.of("[]", 1), Arguments.of("12", 1), Arguments.of("null", 1), Arguments.of("true", 1), + Arguments.of("\"hello\"", 1), Arguments.of("{\"outerfield\": 12}", 3), + Arguments.of("{\"outerfield\": null}", 3), Arguments.of("{\"outerfield\": true}", 3), + Arguments.of("{\"outerfield\": \"hello\"}", 3)); + } + + @ParameterizedTest + @MethodSource("bufferHandlesEncodedTextSupplier") + public void bufferHandlesEncodedText(String json) throws IOException { + try (JsonReader reader = JsonReader.fromString(json)) { + reader.nextToken(); // Initiate reading. + + String buffered = reader.readRemainingFieldsAsJsonObject(); + + assertEquals(json, buffered); + } + } + + private static Stream bufferHandlesEncodedTextSupplier() { + return Stream.of("{\"encoded\\\"fieldname\":42}", "{\"fieldname\":\"encoded\\\"value\"}", + "{\"encoded\\\"fieldname\":\"andencoded\\\"value\"}"); + } + + @Test + public void getTextOnUninitializedReadThrowsIllegalStateException() throws IOException { + try (JsonReader reader = JsonReader.fromString("{}")) { + assertThrows(IllegalStateException.class, reader::getText); + } + } + + @ParameterizedTest + @MethodSource("getTextSupplier") + public void getToken(String json, int nextTokens, String expected) throws IOException { + try (JsonReader reader = JsonReader.fromString(json)) { + for (int i = 0; i < nextTokens; i++) { + reader.nextToken(); + } + + assertEquals(expected, reader.getText()); + } + } + + private static Stream getTextSupplier() { + return Stream.of(Arguments.of("{}", 1, "{"), Arguments.of("{}", 2, "}"), + + Arguments.of("[]", 1, "["), Arguments.of("[]", 2, "]"), + + Arguments.of("{\"field\":\"value\"}", 2, "field"), + Arguments.of("{\"\\\"field\\\"\":\"value\"}", 2, "\"field\""), + + Arguments.of("{\"field\":\"value\"}", 3, "value"), + Arguments.of("{\"field\":\"\\\"value\\\"\"}", 3, "\"value\""), Arguments.of("{\"field\":42}", 3, "42"), + Arguments.of("{\"field\":42.0}", 3, "42.0"), Arguments.of("{\"field\":true}", 3, "true"), + Arguments.of("{\"field\":false}", 3, "false"), Arguments.of("{\"field\":null}", 3, "null")); + } + + @ParameterizedTest + @MethodSource("getRawTextSupplier") + public void getRawToken(String json, int nextTokens, String expected) throws IOException { + try (JsonReader reader = JsonReader.fromString(json)) { + for (int i = 0; i < nextTokens; i++) { + reader.nextToken(); + } + + assertEquals(expected, reader.getRawText()); + } + } + + private static Stream getRawTextSupplier() { + return Stream.of(Arguments.of("{}", 1, "{"), Arguments.of("{}", 2, "}"), + + Arguments.of("[]", 1, "["), Arguments.of("[]", 2, "]"), + + Arguments.of("{\"field\":\"value\"}", 2, "field"), + Arguments.of("{\"\\\"field\\\"\":\"value\"}", 2, "\\\"field\\\""), + + Arguments.of("{\"field\":\"value\"}", 3, "value"), + Arguments.of("{\"field\":\"\\\"value\\\"\"}", 3, "\\\"value\\\""), Arguments.of("{\"field\":42}", 3, "42"), + Arguments.of("{\"field\":42.0}", 3, "42.0"), Arguments.of("{\"field\":true}", 3, "true"), + Arguments.of("{\"field\":false}", 3, "false"), Arguments.of("{\"field\":null}", 3, "null")); + } + + @ParameterizedTest + @MethodSource("isJsonStructSupplier") + public void isJsonStruct(String json, int nextTokens, boolean isStart, boolean expected) throws IOException { + try (JsonReader reader = JsonReader.fromString(json)) { + for (int i = 0; i < nextTokens; i++) { + reader.nextToken(); + } + + assertEquals(expected, isStart ? reader.isStartArrayOrObject() : reader.isEndArrayOrObject()); + } + } + + private static Stream isJsonStructSupplier() { + return Stream.of(Arguments.of("{}", 1, true, true), Arguments.of("{}", 1, false, false), + Arguments.of("{}", 2, true, false), Arguments.of("{}", 2, false, true), + + Arguments.of("[]", 1, true, true), Arguments.of("[]", 1, false, false), Arguments.of("[]", 2, true, false), + Arguments.of("[]", 2, false, true), + + Arguments.of("{\"field\":\"value\"}", 2, true, false), + Arguments.of("{\"field\":\"value\"}", 2, false, false), + + Arguments.of("{\"field\":\"value\"}", 3, true, false), + Arguments.of("{\"field\":\"value\"}", 3, false, false), Arguments.of("{\"field\":42}", 3, true, false), + Arguments.of("{\"field\":42}", 3, false, false), Arguments.of("{\"field\":42.0}", 3, true, false), + Arguments.of("{\"field\":42.0}", 3, false, false), Arguments.of("{\"field\":true}", 3, true, false), + Arguments.of("{\"field\":true}", 3, false, false), Arguments.of("{\"field\":false}", 3, true, false), + Arguments.of("{\"field\":false}", 3, false, false), Arguments.of("{\"field\":null}", 3, true, false), + Arguments.of("{\"field\":null}", 3, false, false)); + } + + @Test + public void readArrayNonStartArrayTokenThrowsIllegalStateException() { + assertThrows(IllegalStateException.class, () -> JsonReader.fromString("{}").readArray(JsonReader::readUntyped)); + } + + @ParameterizedTest + @MethodSource("readArraySupplier") + public void readArray(String json, IOExceptionCheckedFunction> read, List expected) + throws IOException { + readAndValidate(json, read, actual -> { + if (expected == null) { + assertNull(actual); + } else { + assertEquals(expected.size(), actual.size()); + for (int i = 0; i < expected.size(); i++) { + assertEquals(expected.get(i), actual.get(i)); + } + } + }); + } + + private static Stream readArraySupplier() { + IOExceptionCheckedFunction> reader = read(r -> r.readArray(JsonReader::readUntyped)); + return Stream.of(Arguments.of("null", reader, null), Arguments.of("[]", reader, Collections.emptyList()), + Arguments.of("[10]", reader, Collections.singletonList(10)), + Arguments.of("[true,10,10.0,\"hello\"]", reader, Arrays.asList(true, 10, 10.0D, "hello"))); + } + + @Test + public void readMapNonStartObjectTokenThrowsIllegalStateException() { + assertThrows(IllegalStateException.class, () -> JsonReader.fromString("[]").readMap(JsonReader::readUntyped)); + } + + @ParameterizedTest + @MethodSource("readMapSupplier") + public void readMap(String json, IOExceptionCheckedFunction> read, + Map expected) throws IOException { + readAndValidate(json, read, actual -> { + if (expected == null) { + assertNull(actual); + } else { + assertEquals(expected.size(), actual.size()); + for (String expectedKey : expected.keySet()) { + assertTrue(actual.containsKey(expectedKey)); + assertEquals(expected.get(expectedKey), actual.get(expectedKey)); + } + } + }); + } + + @Test + public void readJsonc() throws IOException { + + try (JsonReader jsonReader + = JsonReader.fromString(JSON_WITH_COMMENTS, new JsonOptions().setJsoncSupported(true))) { + jsonReader.nextToken(); + String outputJson = jsonReader.readChildren(); + assertNotNull(outputJson); + } + } + + @Test + public void readJsoncFails() throws IOException { + assertThrows(IOException.class, () -> { + try (JsonReader jsonReader = JsonReader.fromString(JSON_WITH_COMMENTS)) { + jsonReader.nextToken(); + String outputJson = jsonReader.readChildren(); + assertNotNull(outputJson); + } + }); + } + + @ParameterizedTest + @MethodSource("readUntypedExponentNumbersSupplier") + public void readUntypedExponentNumbers(String numberString, Number expected) throws IOException { + readAndValidate(numberString, JsonReader::readUntyped, actual -> assertEquals(expected, actual)); + } + + private static Stream readUntypedExponentNumbersSupplier() { + return Stream.of(Arguments.of("1e-1", 0.1D), Arguments.of("1E-1", 0.1D), Arguments.of("1e+1", 10D), + Arguments.of("1E+1", 10D), Arguments.of("1e-01", 0.1D), Arguments.of("1E-01", 0.1D), + Arguments.of("1e+01", 10D), Arguments.of("1E+01", 10D), Arguments.of("1e0", 1D), Arguments.of("1E0", 1D), + + Arguments.of("Infinity", Double.POSITIVE_INFINITY), Arguments.of("+Infinity", Double.POSITIVE_INFINITY), + Arguments.of("-Infinity", Double.NEGATIVE_INFINITY), Arguments.of("NaN", Double.NaN)); + } + + private static Stream readMapSupplier() { + IOExceptionCheckedFunction> reader + = read(r -> r.readMap(JsonReader::readUntyped)); + Map map = new LinkedHashMap<>(); + map.put("boolean", true); + map.put("int", 42); + map.put("decimal", 42.0D); + map.put("string", "hello"); + + return Stream.of(Arguments.of("null", reader, null), Arguments.of("{}", reader, Collections.emptyMap()), + Arguments.of("{\"boolean\":true,\"int\":42,\"decimal\":42.0,\"string\":\"hello\"}", reader, map)); + } + + private static void assertJsonReaderStructInitialization(JsonReader reader, JsonToken expectedInitialToken) + throws IOException { + assertNull(reader.currentToken()); + reader.nextToken(); + + assertEquals(expectedInitialToken, reader.currentToken()); + } + + private static IOExceptionCheckedFunction read(IOExceptionCheckedFunction func) { + return func; + } + + private void readAndValidate(String json, IOExceptionCheckedFunction read, Consumer validate) + throws IOException { + try (JsonReader reader = JsonReader.fromString(json)) { + reader.nextToken(); // Initialize the JsonReader for reading. + validate.accept(read.apply(reader)); + } + } + + private static final class TestData implements JsonSerializable { + private String test; + + public String getTest() { + return test; + } + + public TestData setTest(String test) { + this.test = test; + return this; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject().writeStringField("test", test).writeEndObject(); + } + + public static TestData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + TestData result = new TestData(); + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("test".equals(fieldName)) { + result.setTest(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return result; + }); + } + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/JsonWriterTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/JsonWriterTests.java new file mode 100644 index 000000000000..64e48558fc2a --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/JsonWriterTests.java @@ -0,0 +1,756 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.serialization.json; + +import io.clientcore.core.serialization.json.implementation.StringBuilderWriter; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * Tests {@link JsonWriter}. + */ +public class JsonWriterTests { + private final StringBuilderWriter stringBuilderWriter = new StringBuilderWriter(); + + @ParameterizedTest + @MethodSource("basicOperationsSupplier") + public void basicOperations(IOExceptionConsumer operation, String expectedJson) throws IOException { + writeAndValidate(operation, expectedJson); + } + + private static Stream basicOperationsSupplier() { + return Stream.of( + // Object start and end. + Arguments.of(write(JsonWriter::writeStartObject), "{"), + + // End object has to have start object written before it. + Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeEndObject()), "{}"), + + // Array start and end. + Arguments.of(write(JsonWriter::writeStartArray), "["), + + // End array has to have start array written before it. + Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeEndArray()), "[]"), + + // Field name has to happening in an object. + Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject() + .writeFieldName("fieldName") + .writeString("value") + .writeEndObject()), "{\"fieldName\":\"value\"}"), + + // Value handling. + + // Binary + Arguments.of(write(jsonWriter -> jsonWriter.writeBinary(null)), "null"), + Arguments.of(write(jsonWriter -> jsonWriter.writeBinary(new byte[0])), "\"\""), + Arguments.of(write(jsonWriter -> jsonWriter.writeBinary("Hello".getBytes(StandardCharsets.UTF_8))), + "\"" + Base64.getEncoder().encodeToString("Hello".getBytes(StandardCharsets.UTF_8)) + "\""), + + // Boolean + Arguments.of(write(jsonWriter -> jsonWriter.writeBoolean(true)), "true"), + Arguments.of(write(jsonWriter -> jsonWriter.writeBoolean(false)), "false"), + Arguments.of(write(jsonWriter -> jsonWriter.writeBoolean(null)), "null"), + Arguments.of(write(jsonWriter -> jsonWriter.writeBoolean(Boolean.TRUE)), "true"), + + // Double + Arguments.of(write(jsonWriter -> jsonWriter.writeDouble(-42D)), "-42.0"), + Arguments.of(write(jsonWriter -> jsonWriter.writeDouble(-42.0D)), "-42.0"), + Arguments.of(write(jsonWriter -> jsonWriter.writeDouble(42D)), "42.0"), + Arguments.of(write(jsonWriter -> jsonWriter.writeDouble(42.0D)), "42.0"), + + // Float + Arguments.of(write(jsonWriter -> jsonWriter.writeFloat(-42F)), "-42.0"), + Arguments.of(write(jsonWriter -> jsonWriter.writeFloat(-42.0F)), "-42.0"), + Arguments.of(write(jsonWriter -> jsonWriter.writeFloat(42F)), "42.0"), + Arguments.of(write(jsonWriter -> jsonWriter.writeFloat(42.0F)), "42.0"), + + // Integer + Arguments.of(write(jsonWriter -> jsonWriter.writeInt(42)), "42"), + Arguments.of(write(jsonWriter -> jsonWriter.writeInt(-42)), "-42"), + + // Long + Arguments.of(write(jsonWriter -> jsonWriter.writeLong(42L)), "42"), + Arguments.of(write(jsonWriter -> jsonWriter.writeLong(-42L)), "-42"), + + // Null + Arguments.of(write(JsonWriter::writeNull), "null"), + + // Number + Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(null)), "null"), + Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(-42D)), "-42.0"), + Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(-42.0D)), "-42.0"), + Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(42D)), "42.0"), + Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(42.0D)), "42.0"), + Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(-42F)), "-42.0"), + Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(-42.0F)), "-42.0"), + Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(42F)), "42.0"), + Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(42.0F)), "42.0"), + Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(42)), "42"), + Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(-42)), "-42"), + Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(42L)), "42"), + Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(-42L)), "-42"), + Arguments.of(write(jsonWriter -> jsonWriter.writeNumber((byte) 42)), "42"), + Arguments.of(write(jsonWriter -> jsonWriter.writeNumber((short) 42)), "42"), + Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(new AtomicInteger(-42))), "-42"), + Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(new AtomicInteger(42))), "42"), + Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(new AtomicLong(-42L))), "-42"), + Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(new AtomicLong(42L))), "42"), + + // String + Arguments.of(write(jsonWriter -> jsonWriter.writeString(null)), "null"), + Arguments.of(write(jsonWriter -> jsonWriter.writeString("")), "\"\""), + Arguments.of(write(jsonWriter -> jsonWriter.writeString("null")), "\"null\""), + + // Raw + Arguments.of(write(jsonWriter -> jsonWriter.writeRawValue("\"string\"")), "\"string\""), + Arguments.of(write(jsonWriter -> jsonWriter.writeRawValue("42")), "42"), + Arguments.of(write(jsonWriter -> jsonWriter.writeRawValue("42.0")), "42.0"), + Arguments.of(write(jsonWriter -> jsonWriter.writeRawValue("true")), "true"), + Arguments.of(write(jsonWriter -> jsonWriter.writeRawValue("false")), "false"), + Arguments.of(write(jsonWriter -> jsonWriter.writeRawValue("null")), "null"), + Arguments.of(write(jsonWriter -> jsonWriter.writeRawValue("[]")), "[]"), + Arguments.of(write(jsonWriter -> jsonWriter.writeRawValue("[null]")), "[null]"), + Arguments.of(write(jsonWriter -> jsonWriter.writeRawValue("{}")), "{}"), + Arguments.of(write(jsonWriter -> jsonWriter.writeRawValue("{null}")), "{null}"), + + // Field name and value. + // Binary + Arguments.of(writeField(jsonWriter -> jsonWriter.writeBinaryField("field", null)), "{}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeBinaryField("field", new byte[0])), + "{\"field\":\"\"}"), + Arguments.of( + writeField( + jsonWriter -> jsonWriter.writeBinaryField("field", "Hello".getBytes(StandardCharsets.UTF_8))), + "{\"field\":\"" + Base64.getEncoder().encodeToString("Hello".getBytes(StandardCharsets.UTF_8)) + "\"}"), + + // Boolean + Arguments.of(writeField(jsonWriter -> jsonWriter.writeBooleanField("field", true)), "{\"field\":true}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeBooleanField("field", false)), "{\"field\":false}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeBooleanField("field", null)), "{}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeBooleanField("field", Boolean.TRUE)), + "{\"field\":true}"), + + // Double + Arguments.of(writeField(jsonWriter -> jsonWriter.writeDoubleField("field", -42D)), "{\"field\":-42.0}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeDoubleField("field", -42.0D)), "{\"field\":-42.0}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeDoubleField("field", 42D)), "{\"field\":42.0}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeDoubleField("field", 42.0D)), "{\"field\":42.0}"), + + // Float + Arguments.of(writeField(jsonWriter -> jsonWriter.writeFloatField("field", -42F)), "{\"field\":-42.0}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeFloatField("field", -42.0F)), "{\"field\":-42.0}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeFloatField("field", 42F)), "{\"field\":42.0}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeFloatField("field", 42.0F)), "{\"field\":42.0}"), + + // Integer + Arguments.of(writeField(jsonWriter -> jsonWriter.writeIntField("field", 42)), "{\"field\":42}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeIntField("field", -42)), "{\"field\":-42}"), + + // Long + Arguments.of(writeField(jsonWriter -> jsonWriter.writeLongField("field", 42L)), "{\"field\":42}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeLongField("field", -42L)), "{\"field\":-42}"), + + // Null + Arguments.of(writeField(jsonWriter -> jsonWriter.writeNullField("field")), "{\"field\":null}"), + + // Number + Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", null)), "{}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", -42D)), "{\"field\":-42.0}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", -42.0D)), "{\"field\":-42.0}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", 42D)), "{\"field\":42.0}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", 42.0D)), "{\"field\":42.0}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", -42F)), "{\"field\":-42.0}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", -42.0F)), "{\"field\":-42.0}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", 42F)), "{\"field\":42.0}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", 42.0F)), "{\"field\":42.0}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", 42)), "{\"field\":42}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", -42)), "{\"field\":-42}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", 42L)), "{\"field\":42}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", -42L)), "{\"field\":-42}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", new AtomicInteger(42))), + "{\"field\":42}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", new AtomicInteger(-42))), + "{\"field\":-42}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", new AtomicLong(42L))), + "{\"field\":42}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", new AtomicLong(-42L))), + "{\"field\":-42}"), + + // String + Arguments.of(writeField(jsonWriter -> jsonWriter.writeStringField("field", null)), "{}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeStringField("field", "")), "{\"field\":\"\"}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeStringField("field", "null")), + "{\"field\":\"null\"}"), + + // Raw + Arguments.of(writeField(jsonWriter -> jsonWriter.writeRawField("field", "\"string\"")), + "{\"field\":\"string\"}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeRawField("field", "42")), "{\"field\":42}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeRawField("field", "42.0")), "{\"field\":42.0}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeRawField("field", "true")), "{\"field\":true}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeRawField("field", "false")), "{\"field\":false}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeRawField("field", "null")), "{\"field\":null}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeRawField("field", "[]")), "{\"field\":[]}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeRawField("field", "[null]")), "{\"field\":[null]}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeRawField("field", "{}")), "{\"field\":{}}"), + Arguments.of(writeField(jsonWriter -> jsonWriter.writeRawField("field", "{null}")), "{\"field\":{null}}")); + } + + @ParameterizedTest + @MethodSource("basicExceptionsSupplier") + public void basicExceptions(IOExceptionConsumer operation, + Class expectedException) { + assertThrows(expectedException, () -> operation.accept(JsonWriter.toWriter(stringBuilderWriter))); + } + + private static Stream basicExceptionsSupplier() { + return Stream.of( + // IllegalStateException will be thrown if the write operation isn't allowed based on the current writing + // context. + + // Root allows start array, start object, and field value, so end array, end object, field name, and + // field name and value will throw an exception. + Arguments.of(write(JsonWriter::writeEndArray), IllegalStateException.class), + Arguments.of(write(JsonWriter::writeEndObject), IllegalStateException.class), + Arguments.of(write(jsonWriter -> jsonWriter.writeFieldName("fieldName")), IllegalStateException.class), + Arguments.of(write(jsonWriter -> jsonWriter.writeStringField("fieldName", "fieldValue")), + IllegalStateException.class), + + // Start object allows start object, end object, field name, and field name and value, so start array, end + // array, and simple value will throw an exception. + Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeStartArray()), + IllegalStateException.class), + Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeEndArray()), + IllegalStateException.class), + Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeInt(0)), IllegalStateException.class), + + // Start array allows start array, end array, start object, and simple value, so end object, field name, + // and field name and value will throw an exception. + Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeEndObject()), + IllegalStateException.class), + Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeFieldName("fieldName")), + IllegalStateException.class), + Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeIntField("fieldName", 0)), + IllegalStateException.class), + + // Field value allows start array, start object, and simple value, so end array, end object, field name, + // and field name and value will throw an exception. + Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeFieldName("fieldName").writeEndArray()), + IllegalStateException.class), + Arguments.of( + write(jsonWriter -> jsonWriter.writeStartObject().writeFieldName("fieldName").writeEndObject()), + IllegalStateException.class), + Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject() + .writeFieldName("fieldName") + .writeFieldName("anotherFieldName")), IllegalStateException.class), + Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject() + .writeFieldName("fieldName") + .writeIntField("anotherFieldName", 0)), IllegalStateException.class), + + // Completed doesn't allow any additional writing operations. + Arguments.of(write(jsonWriter -> jsonWriter.writeInt(0).writeStartArray()), IllegalStateException.class), + Arguments.of(write(jsonWriter -> jsonWriter.writeInt(0).writeEndArray()), IllegalStateException.class), + Arguments.of(write(jsonWriter -> jsonWriter.writeInt(0).writeStartObject()), IllegalStateException.class), + Arguments.of(write(jsonWriter -> jsonWriter.writeInt(0).writeEndObject()), IllegalStateException.class), + Arguments.of(write(jsonWriter -> jsonWriter.writeInt(0).writeFieldName("fieldName")), + IllegalStateException.class), + Arguments.of(write(jsonWriter -> jsonWriter.writeInt(0).writeInt(0)), IllegalStateException.class), + Arguments.of(write(jsonWriter -> jsonWriter.writeInt(0).writeIntField("fieldName", 0)), + IllegalStateException.class), + + // Closing the writer on any state other than completed throws exceptions. + Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().close()), IllegalStateException.class), + + Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().close()), IllegalStateException.class), + + Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeFieldName("fieldName").close()), + IllegalStateException.class)); + } + + @ParameterizedTest + @MethodSource("basicWriteStateSupplier") + public void basicWriteState(IOExceptionConsumer operation, JsonWriteState expectedState) + throws IOException { + // Don't close the writer in this test as it will throw an exception about being in an illegal state when + // closing. + JsonWriter writer = JsonWriter.toWriter(stringBuilderWriter); + assertDoesNotThrow(() -> operation.accept(writer)); + assertEquals(expectedState, writer.getWriteContext().getWriteState()); + } + + private static Stream basicWriteStateSupplier() { + return Stream.of( + // Initial state is root. + Arguments.of(write(jsonWriter -> { + }), JsonWriteState.ROOT), + + // Starting an object enters OBJECT state. + Arguments.of(write(JsonWriter::writeStartObject), JsonWriteState.OBJECT), + + // Starting an array enters ARRAY state. + Arguments.of(write(JsonWriter::writeStartArray), JsonWriteState.ARRAY), + + // Writing a simple value at ROOT enters COMPLETED state. + Arguments.of(write(jsonWriter -> jsonWriter.writeBinary(null)), JsonWriteState.COMPLETED), + Arguments.of(write(jsonWriter -> jsonWriter.writeBoolean(true)), JsonWriteState.COMPLETED), + Arguments.of(write(jsonWriter -> jsonWriter.writeDouble(0.0D)), JsonWriteState.COMPLETED), + Arguments.of(write(jsonWriter -> jsonWriter.writeFloat(0.0F)), JsonWriteState.COMPLETED), + Arguments.of(write(jsonWriter -> jsonWriter.writeInt(0)), JsonWriteState.COMPLETED), + Arguments.of(write(jsonWriter -> jsonWriter.writeLong(0L)), JsonWriteState.COMPLETED), + Arguments.of(write(JsonWriter::writeNull), JsonWriteState.COMPLETED), + Arguments.of(write(jsonWriter -> jsonWriter.writeString(null)), JsonWriteState.COMPLETED), + Arguments.of(write(jsonWriter -> jsonWriter.writeRawValue("\"\"")), JsonWriteState.COMPLETED), + + // Writing a value into an array maintains ARRAY state. + Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeBinary(null)), JsonWriteState.ARRAY), + Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeBoolean(true)), JsonWriteState.ARRAY), + Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeDouble(0.0D)), JsonWriteState.ARRAY), + Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeFloat(0.0F)), JsonWriteState.ARRAY), + Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeInt(0)), JsonWriteState.ARRAY), + Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeLong(0L)), JsonWriteState.ARRAY), + Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeNull()), JsonWriteState.ARRAY), + Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeString(null)), JsonWriteState.ARRAY), + Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeRawValue("\"\"")), JsonWriteState.ARRAY), + + // Ending an object at ROOT enters COMPLETED state. + Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeEndObject()), JsonWriteState.COMPLETED), + + // Ending an array at ROOT enters COMPLETED state. + Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeEndArray()), JsonWriteState.COMPLETED), + + // Writing an object in an array enters OBJECT state. + Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeStartObject()), JsonWriteState.OBJECT), + + // Writing an array in an array maintains ARRAY state. + Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeStartArray()), JsonWriteState.ARRAY), + + // Closing an array contained in an array maintains ARRAY state. + Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeStartArray().writeEndArray()), + JsonWriteState.ARRAY), + + // Writing a field name in an object enters FIELD_VALUE state. + Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeFieldName("fieldName")), + JsonWriteState.FIELD), + + // Writing a field and value maintains OBJECT state. + Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeBinaryField("fieldName", null)), + JsonWriteState.OBJECT), + Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeBooleanField("fieldName", true)), + JsonWriteState.OBJECT), + Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeDoubleField("fieldName", 0.0D)), + JsonWriteState.OBJECT), + Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeFloatField("fieldName", 0.0F)), + JsonWriteState.OBJECT), + Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeIntField("fieldName", 0)), + JsonWriteState.OBJECT), + Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeLongField("fieldName", 0L)), + JsonWriteState.OBJECT), + Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeNullField("fieldName")), + JsonWriteState.OBJECT), + Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeStringField("fieldName", null)), + JsonWriteState.OBJECT), + Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeRawField("fieldName", "\"\"")), + JsonWriteState.OBJECT), + + // Starting an object in FIELD_VALUE enters OBJECT state. + Arguments.of( + write(jsonWriter -> jsonWriter.writeStartObject().writeFieldName("fieldName").writeStartObject()), + JsonWriteState.OBJECT), + + // Starting an array in FIELD_VALUE enters ARRAY state. + Arguments.of( + write(jsonWriter -> jsonWriter.writeStartObject().writeFieldName("fieldName").writeStartArray()), + JsonWriteState.ARRAY), + + // Closing an object that is a field value enters OBJECT state. + Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject() + .writeFieldName("fieldName") + .writeStartObject() + .writeEndObject()), JsonWriteState.OBJECT), + + // Closing an array that is a field value enters OBJECT state. + Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject() + .writeFieldName("fieldName") + .writeStartArray() + .writeEndArray()), JsonWriteState.OBJECT)); + } + + @ParameterizedTest + @MethodSource("nullPointerExceptionsSupplier") + public void nullPointerExceptions(IOExceptionConsumer consumer) { + assertThrows(NullPointerException.class, () -> consumer.accept(JsonWriter.toWriter(stringBuilderWriter))); + } + + private static Stream> nullPointerExceptionsSupplier() { + return Stream.of(write(jsonWriter -> jsonWriter.writeStartObject(null)), + write(jsonWriter -> jsonWriter.writeStartArray(null)), write(jsonWriter -> jsonWriter.writeFieldName(null)), + write(jsonWriter -> jsonWriter.writeArray((Object[]) null, null)), + write(jsonWriter -> jsonWriter.writeArray(Collections.emptyList(), null)), + write(jsonWriter -> jsonWriter.writeMap(null, null)), write(jsonWriter -> jsonWriter.writeRawValue(null)), + + write(jsonWriter -> jsonWriter.writeNullableField(null, null, JsonWriter::writeUntyped)), + write(jsonWriter -> jsonWriter.writeNullableField("field", null, null)), + write(jsonWriter -> jsonWriter.writeJsonField(null, null)), + write(jsonWriter -> jsonWriter.writeArrayField(null, (Object[]) null, JsonWriter::writeUntyped)), + write(jsonWriter -> jsonWriter.writeArrayField("field", (Object[]) null, null)), + write(jsonWriter -> jsonWriter.writeArrayField(null, Collections.emptyList(), JsonWriter::writeUntyped)), + write(jsonWriter -> jsonWriter.writeArrayField("field", (List) null, null)), + write(jsonWriter -> jsonWriter.writeMapField(null, null, JsonWriter::writeUntyped)), + write(jsonWriter -> jsonWriter.writeMapField("field", null, null)), + + write(jsonWriter -> jsonWriter.writeBinaryField(null, null)), + write(jsonWriter -> jsonWriter.writeBooleanField(null, false)), + write(jsonWriter -> jsonWriter.writeBooleanField(null, null)), + write(jsonWriter -> jsonWriter.writeDoubleField(null, 0.0D)), + write(jsonWriter -> jsonWriter.writeFloatField(null, 0.0F)), + write(jsonWriter -> jsonWriter.writeIntField(null, 0)), + write(jsonWriter -> jsonWriter.writeLongField(null, 0L)), + write(jsonWriter -> jsonWriter.writeNullField(null)), + write(jsonWriter -> jsonWriter.writeNumberField(null, null)), + write(jsonWriter -> jsonWriter.writeStringField(null, null)), + write(jsonWriter -> jsonWriter.writeRawField(null, "0")), + write(jsonWriter -> jsonWriter.writeRawField("field", null)), + write(jsonWriter -> jsonWriter.writeUntypedField(null, null))); + } + + @Test + public void writeStartObjectNullFieldName() { + assertThrows(NullPointerException.class, () -> JsonWriter.toWriter(stringBuilderWriter).writeStartObject(null)); + } + + @Test + public void writeStartObjectWithFieldName() throws IOException { + writeAndValidate(writeField(writer -> writer.writeStartObject("objectWithFieldName").writeEndObject()), + "{\"objectWithFieldName\":{}}"); + } + + @Test + public void writeStartArrayNullFieldName() { + assertThrows(NullPointerException.class, () -> JsonWriter.toWriter(stringBuilderWriter).writeStartArray(null)); + } + + @Test + public void writeStartArrayWithFieldName() throws IOException { + writeAndValidate(writeField(writer -> writer.writeStartArray("arrayWithFieldName").writeEndArray()), + "{\"arrayWithFieldName\":[]}"); + } + + @Test + public void writeJsonFieldNullFieldNameThrowsNullPointerException() { + assertThrows(NullPointerException.class, + () -> JsonWriter.toWriter(stringBuilderWriter).writeJsonField(null, null)); + } + + @ParameterizedTest + @MethodSource("writeJsonSupplier") + public void writeJson(IOExceptionConsumer write, String expected) throws IOException { + writeAndValidate(write, expected); + } + + private static Stream writeJsonSupplier() { + SimpleSerializable serializable = new SimpleSerializable(true, 42, 42.0, "hello"); + return Stream.of(Arguments.of(write(writer -> writer.writeJson(null)), ""), + Arguments.of(write(writer -> writer.writeJson(serializable)), + "{\"boolean\":true,\"int\":42,\"decimal\":42.0,\"string\":\"hello\"}"), + Arguments.of(writeField(writer -> writer.writeJsonField("field", null)), "{}"), + Arguments.of(writeField(writer -> writer.writeJsonField("field", serializable)), + "{\"field\":{\"boolean\":true,\"int\":42,\"decimal\":42.0,\"string\":\"hello\"}}")); + } + + @Test + public void writeArrayThrowsNullPointerException() { + assertThrows(NullPointerException.class, + () -> JsonWriter.toWriter(stringBuilderWriter).writeArray(new Object[0], null)); + assertThrows(NullPointerException.class, + () -> JsonWriter.toWriter(stringBuilderWriter).writeArray(Collections.emptyList(), null)); + + assertThrows(NullPointerException.class, + () -> JsonWriter.toWriter(stringBuilderWriter).writeArrayField(null, new Object[0], null)); + assertThrows(NullPointerException.class, + () -> JsonWriter.toWriter(stringBuilderWriter).writeArrayField(null, Collections.emptyList(), null)); + + assertThrows(NullPointerException.class, + () -> JsonWriter.toWriter(stringBuilderWriter).writeArrayField("field", new Object[0], null)); + assertThrows(NullPointerException.class, + () -> JsonWriter.toWriter(stringBuilderWriter).writeArrayField("field", Collections.emptyList(), null)); + } + + @ParameterizedTest + @MethodSource("writeArraySupplier") + public void writeArray(IOExceptionConsumer write, String expected) throws IOException { + writeAndValidate(write, expected); + } + + private static Stream writeArraySupplier() { + Object[] array = new Object[] { true, 42, 42.0, "hello" }; + String expected = "[true,42,42.0,\"hello\"]"; + return Stream.of( + Arguments.of(write(writer -> writer.writeArray((Object[]) null, JsonWriter::writeUntyped)), "null"), + Arguments.of(write(writer -> writer.writeArray(new Object[0], JsonWriter::writeUntyped)), "[]"), + Arguments.of(write(writer -> writer.writeArray(array, JsonWriter::writeUntyped)), expected), + + Arguments.of(write(writer -> writer.writeArray((List) null, JsonWriter::writeUntyped)), "null"), + Arguments.of(write(writer -> writer.writeArray(Collections.emptyList(), JsonWriter::writeUntyped)), "[]"), + Arguments.of(write(writer -> writer.writeArray(Arrays.asList(array), JsonWriter::writeUntyped)), expected), + + Arguments.of(write(writer -> writer.writeArrayField("field", (Object[]) null, JsonWriter::writeUntyped)), + ""), + Arguments.of(writeField(writer -> writer.writeArrayField("field", new Object[0], JsonWriter::writeUntyped)), + "{\"field\":[]}"), + Arguments.of(writeField(writer -> writer.writeArrayField("field", array, JsonWriter::writeUntyped)), + "{\"field\":" + expected + "}"), + + Arguments.of( + write(writer -> writer.writeArrayField("field", (List) null, JsonWriter::writeUntyped)), ""), + Arguments.of( + writeField( + writer -> writer.writeArrayField("field", Collections.emptyList(), JsonWriter::writeUntyped)), + "{\"field\":[]}"), + Arguments.of(writeField(writer -> writer.writeArray(Arrays.asList(array), JsonWriter::writeUntyped)), + "{\"field\":" + expected + "}")); + } + + @Test + public void writeMapThrowsNullPointerException() { + assertThrows(NullPointerException.class, + () -> JsonWriter.toWriter(stringBuilderWriter).writeMap(Collections.emptyMap(), null)); + assertThrows(NullPointerException.class, + () -> JsonWriter.toWriter(stringBuilderWriter).writeMapField(null, Collections.emptyMap(), null)); + assertThrows(NullPointerException.class, + () -> JsonWriter.toWriter(stringBuilderWriter).writeMapField("field", Collections.emptyMap(), null)); + } + + @ParameterizedTest + @MethodSource("writeMapSupplier") + public void writeMap(IOExceptionConsumer write, String expected) throws IOException { + writeAndValidate(write, expected); + } + + private static Stream writeMapSupplier() { + Map map = new LinkedHashMap<>(); + map.put("boolean", true); + map.put("int", 42); + map.put("decimal", 42.0D); + map.put("string", "hello"); + String expected = "{\"boolean\":true,\"int\":42,\"decimal\":42.0,\"string\":\"hello\"}"; + + return Stream.of(Arguments.of(write(writer -> writer.writeMap(null, JsonWriter::writeUntyped)), "null"), + Arguments.of(write(writer -> writer.writeMap(Collections.emptyMap(), JsonWriter::writeUntyped)), "{}"), + Arguments.of(write(writer -> writer.writeMap(map, JsonWriter::writeUntyped)), expected), + + Arguments.of(write(writer -> writer.writeMapField("field", null, JsonWriter::writeUntyped)), ""), + Arguments.of( + writeField(writer -> writer.writeMapField("field", Collections.emptyMap(), JsonWriter::writeUntyped)), + "{\"field\":{}}"), + Arguments.of(writeField(writer -> writer.writeMapField("field", map, JsonWriter::writeUntyped)), + "{\"field\":" + expected + "}")); + } + + @ParameterizedTest + @MethodSource("writeUntypedSupplier") + public void writeUntyped(Object value, String expectedJson) throws IOException { + writeAndValidate(writer -> writer.writeUntyped(value), expectedJson); + } + + @ParameterizedTest + @MethodSource("writeUntypedSupplier") + public void writeUntypedField(Object value, String expectedUntypedJson) throws IOException { + writeAndValidate(writeField(writer -> writer.writeUntypedField("untyped", value)), + "{\"untyped\":" + expectedUntypedJson + "}"); + } + + private static Stream writeUntypedSupplier() { + byte[] bytes = new byte[] { 0, 1, 2, 3 }; + UUID uuid = UUID.randomUUID(); + + return Stream.of(Arguments.of(null, "null"), Arguments.of((short) 42, "42"), Arguments.of(42, "42"), + Arguments.of(42L, "42"), Arguments.of(42.0F, "42.0"), Arguments.of(42.0D, "42.0"), + Arguments.of(true, "true"), Arguments.of(bytes, "\"" + Base64.getEncoder().encodeToString(bytes) + "\""), + Arguments.of("hello", "\"hello\""), Arguments.of('h', "\"h\""), + Arguments.of(new SimpleSerializable(true, 42, 42.0D, "hello"), + "{\"boolean\":true,\"int\":42,\"decimal\":42.0,\"string\":\"hello\"}"), + Arguments.of(new Object[0], "[]"), + Arguments.of(new Object[] { null, 42, 42.0, true, "hello", 'h' }, "[null,42,42.0,true,\"hello\",\"h\"]"), + Arguments.of(Collections.emptyList(), "[]"), + Arguments.of(Arrays.asList(null, 42, 42.0, true, "hello", 'h'), "[null,42,42.0,true,\"hello\",\"h\"]"), + Arguments.of(Collections.singletonMap("hello", "json"), "{\"hello\":\"json\"}"), + Arguments.of(new Object(), "{}"), Arguments.of(uuid, "\"" + uuid + "\"")); + } + + @Test + public void writeNullableNullWriterFuncThrowsNullPointerException() { + assertThrows(NullPointerException.class, + () -> JsonWriter.toWriter(stringBuilderWriter).writeNullableField("field", null, null)); + } + + @Test + public void writeNullableFieldNullValueWritesJsonNull() throws IOException { + writeAndValidate(writeField(writer -> writer.writeNullableField("field", null, JsonWriter::writeUntyped)), + "{\"field\":null}"); + } + + @Test + public void writeNullableFieldNonNullValueWritesJsonField() throws IOException { + writeAndValidate(writer -> writer.writeStartObject() + .writeNullableField("field", "hello", JsonWriter::writeString) + .writeEndObject(), "{\"field\":\"hello\"}"); + } + + @ParameterizedTest + @MethodSource("arrayMethodsWriteNullValueSupplier") + public void arrayMethodsWriteNullValue(IOExceptionConsumer write, String expected) throws IOException { + writeAndValidate(write, expected); + } + + private static Stream arrayMethodsWriteNullValueSupplier() { + List list = new ArrayList<>(); + list.add("hello"); + list.add(null); + list.add("world"); + + String[] array = new String[] { "hello", null, "world" }; + + String expectedJson = "[\"hello\",null,\"world\"]"; + String expectedFieldJson = "{\"field\":" + expectedJson + "}"; + + return Stream.of(Arguments.of(write(writer -> writer.writeArray(list, JsonWriter::writeString)), expectedJson), + Arguments.of(write(writer -> writer.writeArray(list, JsonWriter::writeString, false)), expectedJson), + Arguments.of(write(writer -> writer.writeArray(array, JsonWriter::writeString)), expectedJson), + Arguments.of(write(writer -> writer.writeArray(array, JsonWriter::writeString, false)), expectedJson), + Arguments.of(writeField(writer -> writer.writeArrayField("field", list, JsonWriter::writeString)), + expectedFieldJson), + Arguments.of(writeField(writer -> writer.writeArrayField("field", list, JsonWriter::writeString, false)), + expectedFieldJson), + Arguments.of(writeField(writer -> writer.writeArrayField("field", array, JsonWriter::writeString)), + expectedFieldJson), + Arguments.of(writeField(writer -> writer.writeArrayField("field", array, JsonWriter::writeString, false)), + expectedFieldJson)); + } + + @ParameterizedTest + @MethodSource("arrayMethodsSkipNullValueSupplier") + public void arrayMethodsSkipNullValue(IOExceptionConsumer write, String expected) throws IOException { + writeAndValidate(write, expected); + } + + private static Stream arrayMethodsSkipNullValueSupplier() { + List list = new ArrayList<>(); + list.add("hello"); + list.add(null); + list.add("world"); + + String[] array = new String[] { "hello", null, "world" }; + + String expectedJson = "[\"hello\",\"world\"]"; + String expectedFieldJson = "{\"field\":" + expectedJson + "}"; + + return Stream.of( + Arguments.of(write(writer -> writer.writeArray(list, JsonWriter::writeString, true)), expectedJson), + Arguments.of(write(writer -> writer.writeArray(array, JsonWriter::writeString, true)), expectedJson), + Arguments.of(writeField(writer -> writer.writeArrayField("field", list, JsonWriter::writeString, true)), + expectedFieldJson), + Arguments.of(writeField(writer -> writer.writeArrayField("field", array, JsonWriter::writeString, true)), + expectedFieldJson)); + } + + @ParameterizedTest + @MethodSource("mapMethodsWriteNullValueSupplier") + public void mapMethodsWriteNullValue(IOExceptionConsumer write, String expected) throws IOException { + writeAndValidate(write, expected); + } + + private static Stream mapMethodsWriteNullValueSupplier() { + Map map = new LinkedHashMap<>(); + map.put("hello", "world"); + map.put("null", null); + + String expectedJson = "{\"hello\":\"world\",\"null\":null}"; + String expectedFieldJson = "{\"field\":" + expectedJson + "}"; + + return Stream.of(Arguments.of(write(writer -> writer.writeMap(map, JsonWriter::writeString)), expectedJson), + Arguments.of(write(writer -> writer.writeMap(map, JsonWriter::writeString, false)), expectedJson), + Arguments.of(writeField(writer -> writer.writeMapField("field", map, JsonWriter::writeString)), + expectedFieldJson), + Arguments.of(writeField(writer -> writer.writeMapField("field", map, JsonWriter::writeString, false)), + expectedFieldJson)); + } + + @ParameterizedTest + @MethodSource("mapMethodsSkipNullValueSupplier") + public void mapMethodsSkipNullValue(IOExceptionConsumer write, String expected) throws IOException { + writeAndValidate(write, expected); + } + + private static Stream mapMethodsSkipNullValueSupplier() { + Map map = new LinkedHashMap<>(); + map.put("hello", "world"); + map.put("null", null); + + String expectedJson = "{\"hello\":\"world\"}"; + String expectedFieldJson = "{\"field\":" + expectedJson + "}"; + + return Stream.of( + Arguments.of(write(writer -> writer.writeMap(map, JsonWriter::writeString, true)), expectedJson), + Arguments.of(writeField(writer -> writer.writeMapField("field", map, JsonWriter::writeString, true)), + expectedFieldJson)); + } + + private void writeAndValidate(IOExceptionConsumer write, String expected) throws IOException { + try (JsonWriter writer = JsonWriter.toWriter(stringBuilderWriter)) { + write.accept(writer); + writer.flush(); + + assertEquals(expected, stringBuilderWriter.toString()); + } catch (IllegalStateException ignored) { + // Ignore IllegalStateException if JsonWriter is closed in an invalid state. + } + } + + private static IOExceptionConsumer write(IOExceptionConsumer callback) { + return callback; + } + + private static IOExceptionConsumer writeField(IOExceptionConsumer callback) { + return writer -> { + writer.writeStartObject(); + callback.accept(writer); + writer.writeEndObject(); + }; + } + + /** + * Interface that aids in testing methods that throw IOExceptions. + * + * @param The type of the input to the operation. + */ + public interface IOExceptionConsumer { + /** + * Performs this operation on the given argument. + * + * @param t The input argument + * @throws IOException If an I/O error occurs + */ + void accept(T t) throws IOException; + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/SimpleSerializable.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/SimpleSerializable.java similarity index 92% rename from sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/SimpleSerializable.java rename to sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/SimpleSerializable.java index 23b81a39495f..9e43422f4429 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/SimpleSerializable.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/SimpleSerializable.java @@ -1,12 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.serialization.json.contract; - -import io.clientcore.core.serialization.json.JsonReader; -import io.clientcore.core.serialization.json.JsonSerializable; -import io.clientcore.core.serialization.json.JsonToken; -import io.clientcore.core.serialization.json.JsonWriter; +package io.clientcore.core.serialization.json; import java.io.IOException; import java.util.Objects; diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/JsonProviderContractTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/JsonProviderContractTests.java deleted file mode 100644 index 7393a9efe048..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/JsonProviderContractTests.java +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.serialization.json.contract; - -import io.clientcore.core.serialization.json.JsonOptions; -import io.clientcore.core.serialization.json.JsonProvider; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; -import java.io.StringReader; -import java.io.StringWriter; -import java.io.Writer; -import java.lang.invoke.MethodHandles; -import java.lang.reflect.Method; -import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertThrows; - -/** - * Tests the contract of {@link JsonProvider}. - *

        - * All implementations of {@link JsonProvider} must create a subclass of this test class and pass all tests as they're - * written to be considered an acceptable implementation. - */ -public abstract class JsonProviderContractTests { - private static final MethodHandles.Lookup PUBLIC_LOOKUP = MethodHandles.publicLookup(); - - /** - * Creates an instance {@link JsonProvider} that will be used by a test. - * - * @return The {@link JsonProvider} that a test will use. - */ - protected abstract JsonProvider getJsonProvider(); - - @ParameterizedTest - @MethodSource("nullJsonSupplier") - public void nullJsonThrowsNullPointerException(Method creator) { - assertThrows(NullPointerException.class, - () -> PUBLIC_LOOKUP.unreflect(creator).invokeWithArguments(getJsonProvider(), null, new JsonOptions())); - } - - private static Stream nullJsonSupplier() throws NoSuchMethodException { - return Stream.of(JsonProvider.class.getDeclaredMethod("createReader", byte[].class, JsonOptions.class), - JsonProvider.class.getDeclaredMethod("createReader", String.class, JsonOptions.class), - JsonProvider.class.getDeclaredMethod("createReader", InputStream.class, JsonOptions.class), - JsonProvider.class.getDeclaredMethod("createReader", Reader.class, JsonOptions.class), - JsonProvider.class.getDeclaredMethod("createWriter", OutputStream.class, JsonOptions.class), - JsonProvider.class.getDeclaredMethod("createWriter", Writer.class, JsonOptions.class)); - } - - @ParameterizedTest - @MethodSource("nonNullJsonSupplier") - public void nullJsonOptionsThrowsNullPointerException(Method creator, T json) { - assertThrows(NullPointerException.class, - () -> PUBLIC_LOOKUP.unreflect(creator).invokeWithArguments(getJsonProvider(), json, null)); - } - - @ParameterizedTest - @MethodSource("nonNullJsonSupplier") - public void canCreate(Method creator, T json) { - assertDoesNotThrow( - () -> PUBLIC_LOOKUP.unreflect(creator).invokeWithArguments(getJsonProvider(), json, new JsonOptions())); - } - - private static Stream nonNullJsonSupplier() throws NoSuchMethodException { - return Stream.of( - Arguments.of(JsonProvider.class.getDeclaredMethod("createReader", byte[].class, JsonOptions.class), - new byte[0]), - Arguments.of(JsonProvider.class.getDeclaredMethod("createReader", String.class, JsonOptions.class), ""), - Arguments.of(JsonProvider.class.getDeclaredMethod("createReader", InputStream.class, JsonOptions.class), - new ByteArrayInputStream(new byte[0])), - Arguments.of(JsonProvider.class.getDeclaredMethod("createReader", Reader.class, JsonOptions.class), - new StringReader("")), - Arguments.of(JsonProvider.class.getDeclaredMethod("createWriter", OutputStream.class, JsonOptions.class), - new ByteArrayOutputStream()), - Arguments.of(JsonProvider.class.getDeclaredMethod("createWriter", Writer.class, JsonOptions.class), - new StringWriter())); - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/JsonReaderContractTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/JsonReaderContractTests.java deleted file mode 100644 index 871abc22419e..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/JsonReaderContractTests.java +++ /dev/null @@ -1,804 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.serialization.json.contract; - -import io.clientcore.core.serialization.json.JsonReader; -import io.clientcore.core.serialization.json.JsonSerializable; -import io.clientcore.core.serialization.json.JsonToken; -import io.clientcore.core.serialization.json.JsonWriter; -import io.clientcore.core.serialization.json.ReadValueCallback; -import org.junit.jupiter.api.Named; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Base64; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.function.Consumer; -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.assertIterableEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -/** - * Tests the contract of {@link JsonReader}. - *

        - * All implementations of {@link JsonReader} must create a subclass of this test class and pass all tests as they're - * written to be considered an acceptable implementation. - *

        - * Each test will only create a single instance of {@link JsonReader} to simplify the usage of - * {@link #getJsonReader(String)}. - */ -public abstract class JsonReaderContractTests { - /** - * Creates an instance of {@link JsonReader} that will be used by a test. - * - * @param json The JSON to be read. - * @return The {@link JsonReader} that a test will use. - */ - protected abstract JsonReader getJsonReader(String json) throws IOException; - - @ParameterizedTest - @MethodSource("basicOperationsSupplier") - public void basicOperations(String json, T expectedValue, ReadValueCallback function) - throws IOException { - readAndValidate(json, function, actual -> assertEquals(expectedValue, actual)); - } - - private static Stream basicOperationsSupplier() { - UUID uuid = UUID.randomUUID(); - return Stream.of( - // Value handling. - - // Boolean - Arguments.of("false", false, read(JsonReader::getBoolean)), - Arguments.of("true", true, read(JsonReader::getBoolean)), - Arguments.of("null", null, read(reader -> reader.getNullable(JsonReader::getBoolean))), - - // Double - Arguments.of("-42.0", -42D, read(JsonReader::getDouble)), - Arguments.of("-42", -42D, read(JsonReader::getDouble)), - Arguments.of("42.0", 42D, read(JsonReader::getDouble)), - Arguments.of("42", 42D, read(JsonReader::getDouble)), - Arguments.of("null", null, read(reader -> reader.getNullable(JsonReader::getDouble))), - - // Float - Arguments.of("-42.0", -42F, read(JsonReader::getFloat)), - Arguments.of("-42", -42F, read(JsonReader::getFloat)), - Arguments.of("42.0", 42F, read(JsonReader::getFloat)), Arguments.of("42", 42F, read(JsonReader::getFloat)), - Arguments.of("null", null, read(reader -> reader.getNullable(JsonReader::getFloat))), - - // Integer - Arguments.of("-42", -42, read(JsonReader::getInt)), Arguments.of("42", 42, read(JsonReader::getInt)), - Arguments.of("null", null, read(reader -> reader.getNullable(JsonReader::getInt))), - - // Long - Arguments.of("-42", -42L, read(JsonReader::getLong)), Arguments.of("42", 42L, read(JsonReader::getLong)), - Arguments.of("null", null, read(reader -> reader.getNullable(JsonReader::getLong))), - - // String - Arguments.of("null", null, read(JsonReader::getString)), - Arguments.of("\"\"", "", read(JsonReader::getString)), - Arguments.of("\"hello\"", "hello", read(JsonReader::getString)), - - // Nullable - Arguments.of("\"" + uuid + "\"", uuid, - read(reader -> reader.getNullable(reader1 -> UUID.fromString(reader1.getString()))))); - } - - // Byte arrays can't use Object.equals as they'll be compared by memory location instead of value equality. - @ParameterizedTest - @MethodSource("binaryOperationsSupplier") - public void binaryOperations(String json, byte[] expectedValue, ReadValueCallback function) - throws IOException { - readAndValidate(json, function, actual -> assertArrayEquals(expectedValue, actual)); - } - - private static Stream binaryOperationsSupplier() { - return Stream.of( - // Binary - Arguments.of("null", null, read(JsonReader::getBinary)), - Arguments.of("\"\"", new byte[0], read(JsonReader::getBinary)), - Arguments.of("\"" + Base64.getEncoder().encodeToString("Hello".getBytes(StandardCharsets.UTF_8)) + "\"", - "Hello".getBytes(StandardCharsets.UTF_8), read(JsonReader::getBinary))); - } - - @Test - public void emptyObject() throws IOException { - String json = "{}"; - try (JsonReader reader = getJsonReader(json)) { - - assertJsonReaderStructInitialization(reader, JsonToken.START_OBJECT); - - while (reader.nextToken() != JsonToken.END_OBJECT) { - fail("Empty object shouldn't have any non-END_OBJECT JsonTokens but found: " + reader.currentToken()); - } - } - } - - @Test - public void emptyArray() throws IOException { - String json = "[]"; - try (JsonReader reader = getJsonReader(json)) { - - assertJsonReaderStructInitialization(reader, JsonToken.START_ARRAY); - - while (reader.nextToken() != JsonToken.END_ARRAY) { - fail("Empty array shouldn't have any non-END_ARRAY JsonTokens but found: " + reader.currentToken()); - } - } - } - - @Test - public void simpleObject() throws IOException { - String json - = "{\"stringProperty\":\"string\",\"nullProperty\":null,\"integerProperty\":10,\"floatProperty\":10.0,\"booleanProperty\":true}"; - try (JsonReader reader = getJsonReader(json)) { - - assertJsonReaderStructInitialization(reader, JsonToken.START_OBJECT); - - String stringProperty = null; - boolean hasNullProperty = false; - int integerProperty = 0; - float floatProperty = 0.0F; - boolean booleanProperty = false; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("stringProperty".equals(fieldName)) { - stringProperty = reader.getString(); - } else if ("nullProperty".equals(fieldName)) { - hasNullProperty = true; - } else if ("integerProperty".equals(fieldName)) { - integerProperty = reader.getInt(); - } else if ("floatProperty".equals(fieldName)) { - floatProperty = reader.getFloat(); - } else if ("booleanProperty".equals(fieldName)) { - booleanProperty = reader.getBoolean(); - } else { - fail("Unknown property name: '" + fieldName + "'"); - } - } - - assertEquals("string", stringProperty); - assertTrue(hasNullProperty, "Didn't find the expected 'nullProperty'."); - assertEquals(10, integerProperty); - assertEquals(10.0F, floatProperty); - assertEquals(true, booleanProperty); - } - } - - @Test - public void arrayOfBasicTypesInJsonRoot() throws IOException { - String json = "[\"string\",null,10,10.0,true]"; - try (JsonReader reader = getJsonReader(json)) { - - assertJsonReaderStructInitialization(reader, JsonToken.START_ARRAY); - - Object[] jsonArray = new Object[5]; - int jsonArrayIndex = 0; - while (reader.nextToken() != JsonToken.END_ARRAY) { - jsonArray[jsonArrayIndex++] = reader.readUntyped(); - } - - assertEquals("string", jsonArray[0]); - assertNull(jsonArray[1]); - assertEquals(10, jsonArray[2]); - assertEquals(10.0D, jsonArray[3]); - assertEquals(true, jsonArray[4]); - } - } - - @ParameterizedTest - @MethodSource("objectWithInnerObjectSupplier") - public void objectWithInnerObject(String json) throws IOException { - try (JsonReader reader = getJsonReader(json)) { - - assertJsonReaderStructInitialization(reader, JsonToken.START_OBJECT); - - String stringProperty = null; - boolean hasNullProperty = false; - int integerProperty = 0; - float floatProperty = 0.0F; - boolean booleanProperty = false; - String innerStringProperty = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("stringProperty".equals(fieldName)) { - stringProperty = reader.getString(); - } else if ("nullProperty".equals(fieldName)) { - hasNullProperty = true; - } else if ("integerProperty".equals(fieldName)) { - integerProperty = reader.getInt(); - } else if ("floatProperty".equals(fieldName)) { - floatProperty = reader.getFloat(); - } else if ("booleanProperty".equals(fieldName)) { - booleanProperty = reader.getBoolean(); - } else if ("innerObject".equals(fieldName)) { - assertEquals(JsonToken.START_OBJECT, reader.currentToken()); - while (reader.nextToken() != JsonToken.END_OBJECT) { - fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("innerStringProperty".equals(fieldName)) { - innerStringProperty = reader.getString(); - } else { - fail("Unknown property name: '" + fieldName + "'"); - } - } - } else { - fail("Unknown property name: '" + fieldName + "'"); - } - } - - assertEquals("string", stringProperty); - assertTrue(hasNullProperty, "Didn't find the expected 'nullProperty'."); - assertEquals(10, integerProperty); - assertEquals(10.0F, floatProperty); - assertEquals(true, booleanProperty); - assertEquals("innerString", innerStringProperty); - } - } - - private static Stream objectWithInnerObjectSupplier() { - return Stream.of( - Arguments.of(Named.of("objectWithInnerObjectAsFirstProperty", - "{\"innerObject\":{\"innerStringProperty\":\"innerString\"},\"stringProperty\":\"string\"," - + "\"nullProperty\":null,\"integerProperty\":10,\"floatProperty\":10.0,\"booleanProperty\":true}")), - - Arguments.of(Named.of("objectWithInnerObjectAsMiddleProperty", - "{\"stringProperty\":\"string\",\"nullProperty\":null,\"integerProperty\":10," - + "\"innerObject\":{\"innerStringProperty\":\"innerString\"},\"floatProperty\":10.0," - + "\"booleanProperty\":true}")), - - Arguments.of(Named.of("objectWithInnerObjectAsLastProperty", - "{\"stringProperty\":\"string\",\"nullProperty\":null,\"integerProperty\":10,\"floatProperty\":10.0," - + "\"booleanProperty\":true,\"innerObject\":{\"innerStringProperty\":\"innerString\"}}"))); - } - - @ParameterizedTest - @MethodSource("objectWithInnerArraySupplier") - public void objectWithInnerArray(String json) throws IOException { - try (JsonReader reader = getJsonReader(json)) { - - assertJsonReaderStructInitialization(reader, JsonToken.START_OBJECT); - - String stringProperty = null; - boolean hasNullProperty = false; - int integerProperty = 0; - float floatProperty = 0.0F; - boolean booleanProperty = false; - String innerStringProperty = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("stringProperty".equals(fieldName)) { - stringProperty = reader.getString(); - } else if ("nullProperty".equals(fieldName)) { - hasNullProperty = true; - } else if ("integerProperty".equals(fieldName)) { - integerProperty = reader.getInt(); - } else if ("floatProperty".equals(fieldName)) { - floatProperty = reader.getFloat(); - } else if ("booleanProperty".equals(fieldName)) { - booleanProperty = reader.getBoolean(); - } else if ("innerArray".equals(fieldName)) { - assertEquals(JsonToken.START_ARRAY, reader.currentToken()); - while (reader.nextToken() != JsonToken.END_ARRAY) { - if (innerStringProperty != null) { - fail("Only expected one value in the inner array but found more."); - } - innerStringProperty = reader.getString(); - } - } else { - fail("Unknown property name: '" + fieldName + "'"); - } - } - - assertEquals("string", stringProperty); - assertTrue(hasNullProperty, "Didn't find the expected 'nullProperty'."); - assertEquals(10, integerProperty); - assertEquals(10.0F, floatProperty); - assertEquals(true, booleanProperty); - assertEquals("innerString", innerStringProperty); - } - } - - private static Stream objectWithInnerArraySupplier() { - return Stream.of( - Arguments.of(Named.of("objectWithInnerArrayAsFirstProperty", - "{\"innerArray\":[\"innerString\"],\"stringProperty\":\"string\",\"nullProperty\":null," - + "\"integerProperty\":10,\"floatProperty\":10.0,\"booleanProperty\":true}")), - - Arguments.of(Named.of("objectWithInnerArrayAsMiddleProperty", - "{\"stringProperty\":\"string\",\"nullProperty\":null,\"integerProperty\":10," - + "\"innerArray\":[\"innerString\"],\"floatProperty\":10.0,\"booleanProperty\":true}")), - - Arguments.of(Named.of("objectWithInnerArrayAsLastProperty", - "{\"stringProperty\":\"string\",\"nullProperty\":null,\"integerProperty\":10,\"floatProperty\":10.0," - + "\"booleanProperty\":true,\"innerArray\":[\"innerString\"]}"))); - } - - @ParameterizedTest - @MethodSource("arrayWithInnerArraySupplier") - public void arrayWithInnerArray(String json) throws IOException { - try (JsonReader reader = getJsonReader(json)) { - - assertJsonReaderStructInitialization(reader, JsonToken.START_ARRAY); - - Object[] jsonArray = new Object[6]; - int jsonArrayIndex = 0; - while (reader.nextToken() != JsonToken.END_ARRAY) { - if (reader.currentToken() == JsonToken.START_ARRAY) { - while (reader.nextToken() != JsonToken.END_ARRAY) { - if (jsonArray[5] != null) { - fail("Only expected one value in the inner array but found more."); - } - - jsonArray[5] = reader.getString(); - } - } else { - jsonArray[jsonArrayIndex++] = reader.readUntyped(); - } - } - - assertEquals("string", jsonArray[0]); - assertNull(jsonArray[1]); - assertEquals(10, jsonArray[2]); - assertEquals(10.0D, jsonArray[3]); - assertEquals(true, jsonArray[4]); - assertEquals("innerString", jsonArray[5]); - } - } - - private static Stream arrayWithInnerArraySupplier() { - return Stream.of( - Arguments - .of(Named.of("arrayWithInnerArrayAsFirstProperty", "[[\"innerString\"],\"string\",null,10,10.0,true]")), - - Arguments.of( - Named.of("arrayWithInnerArrayAsMiddleProperty", "[\"string\",null,10,[\"innerString\"],10.0,true]")), - - Arguments - .of(Named.of("arrayWithInnerArrayAsLastProperty", "[\"string\",null,10,10.0,true,[\"innerString\"]]"))); - } - - @ParameterizedTest - @MethodSource("arrayWithInnerObjectSupplier") - public void arrayWithInnerObject(String json) throws IOException { - try (JsonReader reader = getJsonReader(json)) { - - assertJsonReaderStructInitialization(reader, JsonToken.START_ARRAY); - - Object[] jsonArray = new Object[6]; - int jsonArrayIndex = 0; - while (reader.nextToken() != JsonToken.END_ARRAY) { - if (reader.currentToken() == JsonToken.START_OBJECT) { - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("innerStringProperty".equals(fieldName)) { - jsonArray[5] = reader.getString(); - } else { - fail("Unknown property name: '" + fieldName + "'"); - } - } - } else { - jsonArray[jsonArrayIndex++] = reader.readUntyped(); - } - } - - assertEquals("string", jsonArray[0]); - assertNull(jsonArray[1]); - assertEquals(10, jsonArray[2]); - assertEquals(10.0D, jsonArray[3]); - assertEquals(true, jsonArray[4]); - assertEquals("innerString", jsonArray[5]); - } - } - - private static Stream arrayWithInnerObjectSupplier() { - return Stream.of( - Arguments.of(Named.of("arrayWithInnerObjectAsFirstProperty", - "[{\"innerStringProperty\":\"innerString\"},\"string\",null,10,10.0,true]")), - - Arguments.of(Named.of("arrayWithInnerObjectAsMiddleProperty", - "[\"string\",null,10,{\"innerStringProperty\":\"innerString\"},10.0,true]")), - - Arguments.of(Named.of("arrayWithInnerObjectAsLastProperty", - "[\"string\",null,10,10.0,true,{\"innerStringProperty\":\"innerString\"}]"))); - } - - @ParameterizedTest - @MethodSource("readUntypedSimpleSupplier") - public void readUntypedSimple(String json, int nextCount, Object expected) throws IOException { - try (JsonReader reader = getJsonReader(json)) { - for (int i = 0; i < nextCount; i++) { - reader.nextToken(); - } - - Object actual = reader.readUntyped(); - assertEquals(expected, actual); - } - - } - - private static Stream readUntypedSimpleSupplier() { - return Stream.of(Arguments.of("null", 1, null), Arguments.of("true", 1, true), Arguments.of("false", 1, false), - Arguments.of("3.14", 1, 3.14), Arguments.of("NaN", 1, String.valueOf(Double.NaN)), - Arguments.of("-Infinity", 1, String.valueOf(Double.NEGATIVE_INFINITY)), - Arguments.of("Infinity", 1, String.valueOf(Double.POSITIVE_INFINITY)), Arguments.of("42", 1, 42), - Arguments.of("420000000000", 1, 420000000000L), Arguments.of("\"hello\"", 1, "hello")); - } - - @SuppressWarnings("unchecked") - @ParameterizedTest - @MethodSource("readUntypedArraySupplier") - public void readUntypedArray(String json, int nextCount, List expected) throws IOException { - try (JsonReader reader = getJsonReader(json)) { - for (int i = 0; i < nextCount; i++) { - reader.nextToken(); - } - - List actual = (List) reader.readUntyped(); - assertIterableEquals(expected, actual); - } - - } - - private static Stream readUntypedArraySupplier() { - return Stream.of(Arguments.of("[]", 1, new ArrayList<>()), - Arguments.of("[42,true,\"hello\"]", 1, Arrays.asList(42, true, "hello"))); - } - - @SuppressWarnings("unchecked") - @ParameterizedTest - @MethodSource("readUntypedObjectSupplier") - public void readUntypedObject(String json, int nextCount, Map expected) throws IOException { - try (JsonReader reader = getJsonReader(json)) { - for (int i = 0; i < nextCount; i++) { - reader.nextToken(); - } - - Map actual = (Map) reader.readUntyped(); - assertEquals(expected.size(), actual.size()); - for (Map.Entry expectedKvp : expected.entrySet()) { - assertTrue(actual.containsKey(expectedKvp.getKey())); - assertEquals(expectedKvp.getValue(), actual.get(expectedKvp.getKey())); - } - } - } - - private static Stream readUntypedObjectSupplier() { - Map complexExpected = new LinkedHashMap<>(); - complexExpected.put("field1", 42); - complexExpected.put("field2", true); - complexExpected.put("field3", "hello"); - - return Stream.of(Arguments.of("{}", 1, new LinkedHashMap<>()), - Arguments.of("{\"field1\":42,\"field2\":true,\"field3\":\"hello\"}", 1, complexExpected)); - } - - @ParameterizedTest - @MethodSource("readUntypedIllegalStartSupplier") - public void readUntypedIllegalStart(String json, int nextCount) throws IOException { - try (JsonReader reader = getJsonReader(json)) { - for (int i = 0; i < nextCount; i++) { - reader.nextToken(); - } - - assertThrows(IllegalStateException.class, reader::readUntyped); - } - } - - private static Stream readUntypedIllegalStartSupplier() { - return Stream.of(Arguments.of("{}", 2), Arguments.of("[]", 2), Arguments.of("{\"field\":\"value\"}", 2)); - } - - @Test - public void readUntypedPreventsStackOverflow() throws IOException { - // At 1000 levels of nesting readUntyped will throw an exception. - StringBuilder builder = new StringBuilder(); - for (int i = 0; i < 1001; i++) { - builder.append("{\"field\":"); - } - - builder.append("null"); - - for (int i = 0; i < 1001; i++) { - builder.append('}'); - } - - String deeplyNestJson = builder.toString(); - - try (JsonReader reader = getJsonReader(deeplyNestJson)) { - reader.nextToken(); - assertThrows(IllegalStateException.class, reader::readUntyped); - } - } - - @ParameterizedTest - @MethodSource("bufferObjectSupplier") - public void bufferObject(String json, int nextCount) throws IOException { - JsonReader reader = getJsonReader(json); - - for (int i = 0; i < nextCount; i++) { - reader.nextToken(); - } - - JsonReader buffer = reader.bufferObject(); - TestData testData = TestData.fromJson(buffer); - - assertEquals("test", testData.getTest()); - } - - private static Stream bufferObjectSupplier() { - return Stream.of(Arguments.of("{\"test\":\"test\"}", 1), - Arguments.of("{\"outerfield\":{\"test\":\"test\"}}", 3)); - } - - @ParameterizedTest - @MethodSource("bufferObjectIllegalStateSupplier") - public void bufferObjectIllegalState(String json, int nextCount) throws IOException { - JsonReader reader = getJsonReader(json); - - for (int i = 0; i < nextCount; i++) { - reader.nextToken(); - } - - assertThrows(IllegalStateException.class, reader::bufferObject); - } - - private static Stream bufferObjectIllegalStateSupplier() { - return Stream.of(Arguments.of("[]", 1), Arguments.of("12", 1), Arguments.of("null", 1), Arguments.of("true", 1), - Arguments.of("\"hello\"", 1), Arguments.of("{\"outerfield\": 12}", 3), - Arguments.of("{\"outerfield\": null}", 3), Arguments.of("{\"outerfield\": true}", 3), - Arguments.of("{\"outerfield\": \"hello\"}", 3)); - } - - @ParameterizedTest - @MethodSource("bufferHandlesEncodedTextSupplier") - public void bufferHandlesEncodedText(String json) throws IOException { - try (JsonReader reader = getJsonReader(json)) { - reader.nextToken(); // Initiate reading. - - String buffered = reader.readRemainingFieldsAsJsonObject(); - - assertEquals(json, buffered); - } - } - - private static Stream bufferHandlesEncodedTextSupplier() { - return Stream.of("{\"encoded\\\"fieldname\":42}", "{\"fieldname\":\"encoded\\\"value\"}", - "{\"encoded\\\"fieldname\":\"andencoded\\\"value\"}"); - } - - @Test - public void getTextOnUninitializedReadThrowsIllegalStateException() throws IOException { - try (JsonReader reader = getJsonReader("{}")) { - assertThrows(IllegalStateException.class, reader::getText); - } - } - - @ParameterizedTest - @MethodSource("getTextSupplier") - public void getToken(String json, int nextTokens, String expected) throws IOException { - try (JsonReader reader = getJsonReader(json)) { - for (int i = 0; i < nextTokens; i++) { - reader.nextToken(); - } - - assertEquals(expected, reader.getText()); - } - } - - private static Stream getTextSupplier() { - return Stream.of(Arguments.of("{}", 1, "{"), Arguments.of("{}", 2, "}"), - - Arguments.of("[]", 1, "["), Arguments.of("[]", 2, "]"), - - Arguments.of("{\"field\":\"value\"}", 2, "field"), - Arguments.of("{\"\\\"field\\\"\":\"value\"}", 2, "\"field\""), - - Arguments.of("{\"field\":\"value\"}", 3, "value"), - Arguments.of("{\"field\":\"\\\"value\\\"\"}", 3, "\"value\""), Arguments.of("{\"field\":42}", 3, "42"), - Arguments.of("{\"field\":42.0}", 3, "42.0"), Arguments.of("{\"field\":true}", 3, "true"), - Arguments.of("{\"field\":false}", 3, "false"), Arguments.of("{\"field\":null}", 3, "null")); - } - - @ParameterizedTest - @MethodSource("getRawTextSupplier") - public void getRawToken(String json, int nextTokens, String expected) throws IOException { - try (JsonReader reader = getJsonReader(json)) { - for (int i = 0; i < nextTokens; i++) { - reader.nextToken(); - } - - assertEquals(expected, reader.getRawText()); - } - } - - private static Stream getRawTextSupplier() { - return Stream.of(Arguments.of("{}", 1, "{"), Arguments.of("{}", 2, "}"), - - Arguments.of("[]", 1, "["), Arguments.of("[]", 2, "]"), - - Arguments.of("{\"field\":\"value\"}", 2, "field"), - Arguments.of("{\"\\\"field\\\"\":\"value\"}", 2, "\\\"field\\\""), - - Arguments.of("{\"field\":\"value\"}", 3, "value"), - Arguments.of("{\"field\":\"\\\"value\\\"\"}", 3, "\\\"value\\\""), Arguments.of("{\"field\":42}", 3, "42"), - Arguments.of("{\"field\":42.0}", 3, "42.0"), Arguments.of("{\"field\":true}", 3, "true"), - Arguments.of("{\"field\":false}", 3, "false"), Arguments.of("{\"field\":null}", 3, "null")); - } - - @ParameterizedTest - @MethodSource("isJsonStructSupplier") - public void isJsonStruct(String json, int nextTokens, boolean isStart, boolean expected) throws IOException { - try (JsonReader reader = getJsonReader(json)) { - for (int i = 0; i < nextTokens; i++) { - reader.nextToken(); - } - - assertEquals(expected, isStart ? reader.isStartArrayOrObject() : reader.isEndArrayOrObject()); - } - } - - private static Stream isJsonStructSupplier() { - return Stream.of(Arguments.of("{}", 1, true, true), Arguments.of("{}", 1, false, false), - Arguments.of("{}", 2, true, false), Arguments.of("{}", 2, false, true), - - Arguments.of("[]", 1, true, true), Arguments.of("[]", 1, false, false), Arguments.of("[]", 2, true, false), - Arguments.of("[]", 2, false, true), - - Arguments.of("{\"field\":\"value\"}", 2, true, false), - Arguments.of("{\"field\":\"value\"}", 2, false, false), - - Arguments.of("{\"field\":\"value\"}", 3, true, false), - Arguments.of("{\"field\":\"value\"}", 3, false, false), Arguments.of("{\"field\":42}", 3, true, false), - Arguments.of("{\"field\":42}", 3, false, false), Arguments.of("{\"field\":42.0}", 3, true, false), - Arguments.of("{\"field\":42.0}", 3, false, false), Arguments.of("{\"field\":true}", 3, true, false), - Arguments.of("{\"field\":true}", 3, false, false), Arguments.of("{\"field\":false}", 3, true, false), - Arguments.of("{\"field\":false}", 3, false, false), Arguments.of("{\"field\":null}", 3, true, false), - Arguments.of("{\"field\":null}", 3, false, false)); - } - - @Test - public void readArrayNonStartArrayTokenThrowsIllegalStateException() { - assertThrows(IllegalStateException.class, () -> getJsonReader("{}").readArray(JsonReader::readUntyped)); - } - - @ParameterizedTest - @MethodSource("readArraySupplier") - public void readArray(String json, ReadValueCallback> read, List expected) - throws IOException { - readAndValidate(json, read, actual -> { - if (expected == null) { - assertNull(actual); - } else { - assertEquals(expected.size(), actual.size()); - for (int i = 0; i < expected.size(); i++) { - assertEquals(expected.get(i), actual.get(i)); - } - } - }); - } - - private static Stream readArraySupplier() { - ReadValueCallback> reader = read(r -> r.readArray(JsonReader::readUntyped)); - return Stream.of(Arguments.of("null", reader, null), Arguments.of("[]", reader, Collections.emptyList()), - Arguments.of("[10]", reader, Collections.singletonList(10)), - Arguments.of("[true,10,10.0,\"hello\"]", reader, Arrays.asList(true, 10, 10.0D, "hello"))); - } - - @Test - public void readMapNonStartObjectTokenThrowsIllegalStateException() { - assertThrows(IllegalStateException.class, () -> getJsonReader("[]").readMap(JsonReader::readUntyped)); - } - - @ParameterizedTest - @MethodSource("readMapSupplier") - public void readMap(String json, ReadValueCallback> read, - Map expected) throws IOException { - readAndValidate(json, read, actual -> { - if (expected == null) { - assertNull(actual); - } else { - assertEquals(expected.size(), actual.size()); - for (String expectedKey : expected.keySet()) { - assertTrue(actual.containsKey(expectedKey)); - assertEquals(expected.get(expectedKey), actual.get(expectedKey)); - } - } - }); - } - - private static Stream readMapSupplier() { - ReadValueCallback> reader = read(r -> r.readMap(JsonReader::readUntyped)); - Map map = new LinkedHashMap<>(); - map.put("boolean", true); - map.put("int", 42); - map.put("decimal", 42.0D); - map.put("string", "hello"); - - return Stream.of(Arguments.of("null", reader, null), Arguments.of("{}", reader, Collections.emptyMap()), - Arguments.of("{\"boolean\":true,\"int\":42,\"decimal\":42.0,\"string\":\"hello\"}", reader, map)); - } - - private static void assertJsonReaderStructInitialization(JsonReader reader, JsonToken expectedInitialToken) - throws IOException { - assertNull(reader.currentToken()); - reader.nextToken(); - - assertEquals(expectedInitialToken, reader.currentToken()); - } - - private static ReadValueCallback read(ReadValueCallback func) { - return func; - } - - private void readAndValidate(String json, ReadValueCallback read, Consumer validate) - throws IOException { - try (JsonReader reader = getJsonReader(json)) { - reader.nextToken(); // Initialize the JsonReader for reading. - validate.accept(read.read(reader)); - } - } - - private static final class TestData implements JsonSerializable { - private String test; - - public String getTest() { - return test; - } - - public TestData setTest(String test) { - this.test = test; - return this; - } - - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return jsonWriter.writeStartObject().writeStringField("test", test).writeEndObject(); - } - - public static TestData fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - TestData result = new TestData(); - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("test".equals(fieldName)) { - result.setTest(reader.getString()); - } else { - reader.skipChildren(); - } - } - - return result; - }); - } - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/JsonWriterContractTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/JsonWriterContractTests.java deleted file mode 100644 index f197509d8708..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/JsonWriterContractTests.java +++ /dev/null @@ -1,767 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.serialization.json.contract; - -import io.clientcore.core.serialization.json.JsonWriteState; -import io.clientcore.core.serialization.json.JsonWriter; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Base64; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -/** - * Tests the contract of {@link JsonWriter}. - *

        - * All implementations of {@link JsonWriter} must create a subclass of this test class and pass all tests as they're - * written to be considered an acceptable implementation. - *

        - * Each test will only create a single instance of {@link JsonWriter} to simplify usage of {@link #getJsonWriter()} and - * {@link #getJsonWriterContents()}. - */ -public abstract class JsonWriterContractTests { - /** - * Creates an instance of {@link JsonWriter} that will be used by a test. - * - * @return The {@link JsonWriter} that a test will use. - */ - public abstract JsonWriter getJsonWriter(); - - /** - * Converts the content written to a {@link JsonWriter} during testing to a string representation. - * - * @return The contents of a {@link JsonWriter} converted to a string. - */ - public abstract String getJsonWriterContents(); - - @ParameterizedTest - @MethodSource("basicOperationsSupplier") - public void basicOperations(IOExceptionConsumer operation, String expectedJson) throws IOException { - writeAndValidate(operation, expectedJson); - } - - private static Stream basicOperationsSupplier() { - return Stream.of( - // Object start and end. - Arguments.of(write(JsonWriter::writeStartObject), "{"), - - // End object has to have start object written before it. - Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeEndObject()), "{}"), - - // Array start and end. - Arguments.of(write(JsonWriter::writeStartArray), "["), - - // End array has to have start array written before it. - Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeEndArray()), "[]"), - - // Field name has to happening in an object. - Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject() - .writeFieldName("fieldName") - .writeString("value") - .writeEndObject()), "{\"fieldName\":\"value\"}"), - - // Value handling. - - // Binary - Arguments.of(write(jsonWriter -> jsonWriter.writeBinary(null)), "null"), - Arguments.of(write(jsonWriter -> jsonWriter.writeBinary(new byte[0])), "\"\""), - Arguments.of(write(jsonWriter -> jsonWriter.writeBinary("Hello".getBytes(StandardCharsets.UTF_8))), - "\"" + Base64.getEncoder().encodeToString("Hello".getBytes(StandardCharsets.UTF_8)) + "\""), - - // Boolean - Arguments.of(write(jsonWriter -> jsonWriter.writeBoolean(true)), "true"), - Arguments.of(write(jsonWriter -> jsonWriter.writeBoolean(false)), "false"), - Arguments.of(write(jsonWriter -> jsonWriter.writeBoolean(null)), "null"), - Arguments.of(write(jsonWriter -> jsonWriter.writeBoolean(Boolean.TRUE)), "true"), - - // Double - Arguments.of(write(jsonWriter -> jsonWriter.writeDouble(-42D)), "-42.0"), - Arguments.of(write(jsonWriter -> jsonWriter.writeDouble(-42.0D)), "-42.0"), - Arguments.of(write(jsonWriter -> jsonWriter.writeDouble(42D)), "42.0"), - Arguments.of(write(jsonWriter -> jsonWriter.writeDouble(42.0D)), "42.0"), - - // Float - Arguments.of(write(jsonWriter -> jsonWriter.writeFloat(-42F)), "-42.0"), - Arguments.of(write(jsonWriter -> jsonWriter.writeFloat(-42.0F)), "-42.0"), - Arguments.of(write(jsonWriter -> jsonWriter.writeFloat(42F)), "42.0"), - Arguments.of(write(jsonWriter -> jsonWriter.writeFloat(42.0F)), "42.0"), - - // Integer - Arguments.of(write(jsonWriter -> jsonWriter.writeInt(42)), "42"), - Arguments.of(write(jsonWriter -> jsonWriter.writeInt(-42)), "-42"), - - // Long - Arguments.of(write(jsonWriter -> jsonWriter.writeLong(42L)), "42"), - Arguments.of(write(jsonWriter -> jsonWriter.writeLong(-42L)), "-42"), - - // Null - Arguments.of(write(JsonWriter::writeNull), "null"), - - // Number - Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(null)), "null"), - Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(-42D)), "-42.0"), - Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(-42.0D)), "-42.0"), - Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(42D)), "42.0"), - Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(42.0D)), "42.0"), - Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(-42F)), "-42.0"), - Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(-42.0F)), "-42.0"), - Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(42F)), "42.0"), - Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(42.0F)), "42.0"), - Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(42)), "42"), - Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(-42)), "-42"), - Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(42L)), "42"), - Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(-42L)), "-42"), - Arguments.of(write(jsonWriter -> jsonWriter.writeNumber((byte) 42)), "42"), - Arguments.of(write(jsonWriter -> jsonWriter.writeNumber((short) 42)), "42"), - Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(new AtomicInteger(-42))), "-42"), - Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(new AtomicInteger(42))), "42"), - Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(new AtomicLong(-42L))), "-42"), - Arguments.of(write(jsonWriter -> jsonWriter.writeNumber(new AtomicLong(42L))), "42"), - - // String - Arguments.of(write(jsonWriter -> jsonWriter.writeString(null)), "null"), - Arguments.of(write(jsonWriter -> jsonWriter.writeString("")), "\"\""), - Arguments.of(write(jsonWriter -> jsonWriter.writeString("null")), "\"null\""), - - // Raw - Arguments.of(write(jsonWriter -> jsonWriter.writeRawValue("\"string\"")), "\"string\""), - Arguments.of(write(jsonWriter -> jsonWriter.writeRawValue("42")), "42"), - Arguments.of(write(jsonWriter -> jsonWriter.writeRawValue("42.0")), "42.0"), - Arguments.of(write(jsonWriter -> jsonWriter.writeRawValue("true")), "true"), - Arguments.of(write(jsonWriter -> jsonWriter.writeRawValue("false")), "false"), - Arguments.of(write(jsonWriter -> jsonWriter.writeRawValue("null")), "null"), - Arguments.of(write(jsonWriter -> jsonWriter.writeRawValue("[]")), "[]"), - Arguments.of(write(jsonWriter -> jsonWriter.writeRawValue("[null]")), "[null]"), - Arguments.of(write(jsonWriter -> jsonWriter.writeRawValue("{}")), "{}"), - Arguments.of(write(jsonWriter -> jsonWriter.writeRawValue("{null}")), "{null}"), - - // Field name and value. - // Binary - Arguments.of(writeField(jsonWriter -> jsonWriter.writeBinaryField("field", null)), "{}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeBinaryField("field", new byte[0])), - "{\"field\":\"\"}"), - Arguments.of( - writeField( - jsonWriter -> jsonWriter.writeBinaryField("field", "Hello".getBytes(StandardCharsets.UTF_8))), - "{\"field\":\"" + Base64.getEncoder().encodeToString("Hello".getBytes(StandardCharsets.UTF_8)) + "\"}"), - - // Boolean - Arguments.of(writeField(jsonWriter -> jsonWriter.writeBooleanField("field", true)), "{\"field\":true}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeBooleanField("field", false)), "{\"field\":false}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeBooleanField("field", null)), "{}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeBooleanField("field", Boolean.TRUE)), - "{\"field\":true}"), - - // Double - Arguments.of(writeField(jsonWriter -> jsonWriter.writeDoubleField("field", -42D)), "{\"field\":-42.0}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeDoubleField("field", -42.0D)), "{\"field\":-42.0}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeDoubleField("field", 42D)), "{\"field\":42.0}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeDoubleField("field", 42.0D)), "{\"field\":42.0}"), - - // Float - Arguments.of(writeField(jsonWriter -> jsonWriter.writeFloatField("field", -42F)), "{\"field\":-42.0}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeFloatField("field", -42.0F)), "{\"field\":-42.0}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeFloatField("field", 42F)), "{\"field\":42.0}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeFloatField("field", 42.0F)), "{\"field\":42.0}"), - - // Integer - Arguments.of(writeField(jsonWriter -> jsonWriter.writeIntField("field", 42)), "{\"field\":42}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeIntField("field", -42)), "{\"field\":-42}"), - - // Long - Arguments.of(writeField(jsonWriter -> jsonWriter.writeLongField("field", 42L)), "{\"field\":42}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeLongField("field", -42L)), "{\"field\":-42}"), - - // Null - Arguments.of(writeField(jsonWriter -> jsonWriter.writeNullField("field")), "{\"field\":null}"), - - // Number - Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", null)), "{}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", -42D)), "{\"field\":-42.0}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", -42.0D)), "{\"field\":-42.0}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", 42D)), "{\"field\":42.0}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", 42.0D)), "{\"field\":42.0}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", -42F)), "{\"field\":-42.0}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", -42.0F)), "{\"field\":-42.0}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", 42F)), "{\"field\":42.0}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", 42.0F)), "{\"field\":42.0}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", 42)), "{\"field\":42}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", -42)), "{\"field\":-42}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", 42L)), "{\"field\":42}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", -42L)), "{\"field\":-42}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", new AtomicInteger(42))), - "{\"field\":42}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", new AtomicInteger(-42))), - "{\"field\":-42}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", new AtomicLong(42L))), - "{\"field\":42}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeNumberField("field", new AtomicLong(-42L))), - "{\"field\":-42}"), - - // String - Arguments.of(writeField(jsonWriter -> jsonWriter.writeStringField("field", null)), "{}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeStringField("field", "")), "{\"field\":\"\"}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeStringField("field", "null")), - "{\"field\":\"null\"}"), - - // Raw - Arguments.of(writeField(jsonWriter -> jsonWriter.writeRawField("field", "\"string\"")), - "{\"field\":\"string\"}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeRawField("field", "42")), "{\"field\":42}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeRawField("field", "42.0")), "{\"field\":42.0}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeRawField("field", "true")), "{\"field\":true}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeRawField("field", "false")), "{\"field\":false}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeRawField("field", "null")), "{\"field\":null}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeRawField("field", "[]")), "{\"field\":[]}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeRawField("field", "[null]")), "{\"field\":[null]}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeRawField("field", "{}")), "{\"field\":{}}"), - Arguments.of(writeField(jsonWriter -> jsonWriter.writeRawField("field", "{null}")), "{\"field\":{null}}")); - } - - @ParameterizedTest - @MethodSource("basicExceptionsSupplier") - public void basicExceptions(IOExceptionConsumer operation, - Class expectedException) { - assertThrows(expectedException, () -> operation.accept(getJsonWriter())); - } - - private static Stream basicExceptionsSupplier() { - return Stream.of( - // IllegalStateException will be thrown if the write operation isn't allowed based on the current writing - // context. - - // Root allows start array, start object, and field value, so end array, end object, field name, and - // field name and value will throw an exception. - Arguments.of(write(JsonWriter::writeEndArray), IllegalStateException.class), - Arguments.of(write(JsonWriter::writeEndObject), IllegalStateException.class), - Arguments.of(write(jsonWriter -> jsonWriter.writeFieldName("fieldName")), IllegalStateException.class), - Arguments.of(write(jsonWriter -> jsonWriter.writeStringField("fieldName", "fieldValue")), - IllegalStateException.class), - - // Start object allows start object, end object, field name, and field name and value, so start array, end - // array, and simple value will throw an exception. - Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeStartArray()), - IllegalStateException.class), - Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeEndArray()), - IllegalStateException.class), - Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeInt(0)), IllegalStateException.class), - - // Start array allows start array, end array, start object, and simple value, so end object, field name, - // and field name and value will throw an exception. - Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeEndObject()), - IllegalStateException.class), - Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeFieldName("fieldName")), - IllegalStateException.class), - Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeIntField("fieldName", 0)), - IllegalStateException.class), - - // Field value allows start array, start object, and simple value, so end array, end object, field name, - // and field name and value will throw an exception. - Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeFieldName("fieldName").writeEndArray()), - IllegalStateException.class), - Arguments.of( - write(jsonWriter -> jsonWriter.writeStartObject().writeFieldName("fieldName").writeEndObject()), - IllegalStateException.class), - Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject() - .writeFieldName("fieldName") - .writeFieldName("anotherFieldName")), IllegalStateException.class), - Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject() - .writeFieldName("fieldName") - .writeIntField("anotherFieldName", 0)), IllegalStateException.class), - - // Completed doesn't allow any additional writing operations. - Arguments.of(write(jsonWriter -> jsonWriter.writeInt(0).writeStartArray()), IllegalStateException.class), - Arguments.of(write(jsonWriter -> jsonWriter.writeInt(0).writeEndArray()), IllegalStateException.class), - Arguments.of(write(jsonWriter -> jsonWriter.writeInt(0).writeStartObject()), IllegalStateException.class), - Arguments.of(write(jsonWriter -> jsonWriter.writeInt(0).writeEndObject()), IllegalStateException.class), - Arguments.of(write(jsonWriter -> jsonWriter.writeInt(0).writeFieldName("fieldName")), - IllegalStateException.class), - Arguments.of(write(jsonWriter -> jsonWriter.writeInt(0).writeInt(0)), IllegalStateException.class), - Arguments.of(write(jsonWriter -> jsonWriter.writeInt(0).writeIntField("fieldName", 0)), - IllegalStateException.class), - - // Closing the writer on any state other than completed throws exceptions. - Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().close()), IllegalStateException.class), - - Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().close()), IllegalStateException.class), - - Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeFieldName("fieldName").close()), - IllegalStateException.class)); - } - - @ParameterizedTest - @MethodSource("basicWriteStateSupplier") - public void basicWriteState(IOExceptionConsumer operation, JsonWriteState expectedState) { - JsonWriter writer = getJsonWriter(); - - assertDoesNotThrow(() -> operation.accept(writer)); - - assertEquals(expectedState, writer.getWriteContext().getWriteState()); - } - - private static Stream basicWriteStateSupplier() { - return Stream.of( - // Initial state is root. - Arguments.of(write(jsonWriter -> { - }), JsonWriteState.ROOT), - - // Starting an object enters OBJECT state. - Arguments.of(write(JsonWriter::writeStartObject), JsonWriteState.OBJECT), - - // Starting an array enters ARRAY state. - Arguments.of(write(JsonWriter::writeStartArray), JsonWriteState.ARRAY), - - // Writing a simple value at ROOT enters COMPLETED state. - Arguments.of(write(jsonWriter -> jsonWriter.writeBinary(null)), JsonWriteState.COMPLETED), - Arguments.of(write(jsonWriter -> jsonWriter.writeBoolean(true)), JsonWriteState.COMPLETED), - Arguments.of(write(jsonWriter -> jsonWriter.writeDouble(0.0D)), JsonWriteState.COMPLETED), - Arguments.of(write(jsonWriter -> jsonWriter.writeFloat(0.0F)), JsonWriteState.COMPLETED), - Arguments.of(write(jsonWriter -> jsonWriter.writeInt(0)), JsonWriteState.COMPLETED), - Arguments.of(write(jsonWriter -> jsonWriter.writeLong(0L)), JsonWriteState.COMPLETED), - Arguments.of(write(JsonWriter::writeNull), JsonWriteState.COMPLETED), - Arguments.of(write(jsonWriter -> jsonWriter.writeString(null)), JsonWriteState.COMPLETED), - Arguments.of(write(jsonWriter -> jsonWriter.writeRawValue("\"\"")), JsonWriteState.COMPLETED), - - // Writing a value into an array maintains ARRAY state. - Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeBinary(null)), JsonWriteState.ARRAY), - Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeBoolean(true)), JsonWriteState.ARRAY), - Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeDouble(0.0D)), JsonWriteState.ARRAY), - Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeFloat(0.0F)), JsonWriteState.ARRAY), - Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeInt(0)), JsonWriteState.ARRAY), - Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeLong(0L)), JsonWriteState.ARRAY), - Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeNull()), JsonWriteState.ARRAY), - Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeString(null)), JsonWriteState.ARRAY), - Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeRawValue("\"\"")), JsonWriteState.ARRAY), - - // Ending an object at ROOT enters COMPLETED state. - Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeEndObject()), JsonWriteState.COMPLETED), - - // Ending an array at ROOT enters COMPLETED state. - Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeEndArray()), JsonWriteState.COMPLETED), - - // Writing an object in an array enters OBJECT state. - Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeStartObject()), JsonWriteState.OBJECT), - - // Writing an array in an array maintains ARRAY state. - Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeStartArray()), JsonWriteState.ARRAY), - - // Closing an array contained in an array maintains ARRAY state. - Arguments.of(write(jsonWriter -> jsonWriter.writeStartArray().writeStartArray().writeEndArray()), - JsonWriteState.ARRAY), - - // Writing a field name in an object enters FIELD_VALUE state. - Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeFieldName("fieldName")), - JsonWriteState.FIELD), - - // Writing a field and value maintains OBJECT state. - Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeBinaryField("fieldName", null)), - JsonWriteState.OBJECT), - Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeBooleanField("fieldName", true)), - JsonWriteState.OBJECT), - Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeDoubleField("fieldName", 0.0D)), - JsonWriteState.OBJECT), - Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeFloatField("fieldName", 0.0F)), - JsonWriteState.OBJECT), - Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeIntField("fieldName", 0)), - JsonWriteState.OBJECT), - Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeLongField("fieldName", 0L)), - JsonWriteState.OBJECT), - Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeNullField("fieldName")), - JsonWriteState.OBJECT), - Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeStringField("fieldName", null)), - JsonWriteState.OBJECT), - Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject().writeRawField("fieldName", "\"\"")), - JsonWriteState.OBJECT), - - // Starting an object in FIELD_VALUE enters OBJECT state. - Arguments.of( - write(jsonWriter -> jsonWriter.writeStartObject().writeFieldName("fieldName").writeStartObject()), - JsonWriteState.OBJECT), - - // Starting an array in FIELD_VALUE enters ARRAY state. - Arguments.of( - write(jsonWriter -> jsonWriter.writeStartObject().writeFieldName("fieldName").writeStartArray()), - JsonWriteState.ARRAY), - - // Closing an object that is a field value enters OBJECT state. - Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject() - .writeFieldName("fieldName") - .writeStartObject() - .writeEndObject()), JsonWriteState.OBJECT), - - // Closing an array that is a field value enters OBJECT state. - Arguments.of(write(jsonWriter -> jsonWriter.writeStartObject() - .writeFieldName("fieldName") - .writeStartArray() - .writeEndArray()), JsonWriteState.OBJECT)); - } - - @ParameterizedTest - @MethodSource("nullPointerExceptionsSupplier") - public void nullPointerExceptions(IOExceptionConsumer consumer) { - assertThrows(NullPointerException.class, () -> consumer.accept(getJsonWriter())); - } - - private static Stream> nullPointerExceptionsSupplier() { - return Stream.of(write(jsonWriter -> jsonWriter.writeStartObject(null)), - write(jsonWriter -> jsonWriter.writeStartArray(null)), write(jsonWriter -> jsonWriter.writeFieldName(null)), - write(jsonWriter -> jsonWriter.writeArray((Object[]) null, null)), - write(jsonWriter -> jsonWriter.writeArray(Collections.emptyList(), null)), - write(jsonWriter -> jsonWriter.writeMap(null, null)), write(jsonWriter -> jsonWriter.writeRawValue(null)), - - write(jsonWriter -> jsonWriter.writeNullableField(null, null, JsonWriter::writeUntyped)), - write(jsonWriter -> jsonWriter.writeNullableField("field", null, null)), - write(jsonWriter -> jsonWriter.writeJsonField(null, null)), - write(jsonWriter -> jsonWriter.writeArrayField(null, (Object[]) null, JsonWriter::writeUntyped)), - write(jsonWriter -> jsonWriter.writeArrayField("field", (Object[]) null, null)), - write(jsonWriter -> jsonWriter.writeArrayField(null, Collections.emptyList(), JsonWriter::writeUntyped)), - write(jsonWriter -> jsonWriter.writeArrayField("field", (List) null, null)), - write(jsonWriter -> jsonWriter.writeMapField(null, null, JsonWriter::writeUntyped)), - write(jsonWriter -> jsonWriter.writeMapField("field", null, null)), - - write(jsonWriter -> jsonWriter.writeBinaryField(null, null)), - write(jsonWriter -> jsonWriter.writeBooleanField(null, false)), - write(jsonWriter -> jsonWriter.writeBooleanField(null, null)), - write(jsonWriter -> jsonWriter.writeDoubleField(null, 0.0D)), - write(jsonWriter -> jsonWriter.writeFloatField(null, 0.0F)), - write(jsonWriter -> jsonWriter.writeIntField(null, 0)), - write(jsonWriter -> jsonWriter.writeLongField(null, 0L)), - write(jsonWriter -> jsonWriter.writeNullField(null)), - write(jsonWriter -> jsonWriter.writeNumberField(null, null)), - write(jsonWriter -> jsonWriter.writeStringField(null, null)), - write(jsonWriter -> jsonWriter.writeRawField(null, "0")), - write(jsonWriter -> jsonWriter.writeRawField("field", null)), - write(jsonWriter -> jsonWriter.writeUntypedField(null, null))); - } - - @Test - public void writeStartObjectNullFieldName() { - assertThrows(NullPointerException.class, () -> getJsonWriter().writeStartObject(null)); - } - - @Test - public void writeStartObjectWithFieldName() throws IOException { - writeAndValidate(writeField(writer -> writer.writeStartObject("objectWithFieldName").writeEndObject()), - "{\"objectWithFieldName\":{}}"); - } - - @Test - public void writeStartArrayNullFieldName() { - assertThrows(NullPointerException.class, () -> getJsonWriter().writeStartArray(null)); - } - - @Test - public void writeStartArrayWithFieldName() throws IOException { - writeAndValidate(writeField(writer -> writer.writeStartArray("arrayWithFieldName").writeEndArray()), - "{\"arrayWithFieldName\":[]}"); - } - - @Test - public void writeJsonFieldNullFieldNameThrowsNullPointerException() { - assertThrows(NullPointerException.class, () -> getJsonWriter().writeJsonField(null, null)); - } - - @ParameterizedTest - @MethodSource("writeJsonSupplier") - public void writeJson(IOExceptionConsumer write, String expected) throws IOException { - writeAndValidate(write, expected); - } - - private static Stream writeJsonSupplier() { - SimpleSerializable serializable = new SimpleSerializable(true, 42, 42.0, "hello"); - return Stream.of(Arguments.of(write(writer -> writer.writeJson(null)), ""), - Arguments.of(write(writer -> writer.writeJson(serializable)), - "{\"boolean\":true,\"int\":42,\"decimal\":42.0,\"string\":\"hello\"}"), - Arguments.of(writeField(writer -> writer.writeJsonField("field", null)), "{}"), - Arguments.of(writeField(writer -> writer.writeJsonField("field", serializable)), - "{\"field\":{\"boolean\":true,\"int\":42,\"decimal\":42.0,\"string\":\"hello\"}}")); - } - - @Test - public void writeArrayThrowsNullPointerException() { - assertThrows(NullPointerException.class, () -> getJsonWriter().writeArray(new Object[0], null)); - assertThrows(NullPointerException.class, () -> getJsonWriter().writeArray(Collections.emptyList(), null)); - - assertThrows(NullPointerException.class, () -> getJsonWriter().writeArrayField(null, new Object[0], null)); - assertThrows(NullPointerException.class, - () -> getJsonWriter().writeArrayField(null, Collections.emptyList(), null)); - - assertThrows(NullPointerException.class, () -> getJsonWriter().writeArrayField("field", new Object[0], null)); - assertThrows(NullPointerException.class, - () -> getJsonWriter().writeArrayField("field", Collections.emptyList(), null)); - } - - @ParameterizedTest - @MethodSource("writeArraySupplier") - public void writeArray(IOExceptionConsumer write, String expected) throws IOException { - writeAndValidate(write, expected); - } - - private static Stream writeArraySupplier() { - Object[] array = new Object[] { true, 42, 42.0, "hello" }; - String expected = "[true,42,42.0,\"hello\"]"; - return Stream.of( - Arguments.of(write(writer -> writer.writeArray((Object[]) null, JsonWriter::writeUntyped)), "null"), - Arguments.of(write(writer -> writer.writeArray(new Object[0], JsonWriter::writeUntyped)), "[]"), - Arguments.of(write(writer -> writer.writeArray(array, JsonWriter::writeUntyped)), expected), - - Arguments.of(write(writer -> writer.writeArray((List) null, JsonWriter::writeUntyped)), "null"), - Arguments.of(write(writer -> writer.writeArray(Collections.emptyList(), JsonWriter::writeUntyped)), "[]"), - Arguments.of(write(writer -> writer.writeArray(Arrays.asList(array), JsonWriter::writeUntyped)), expected), - - Arguments.of(write(writer -> writer.writeArrayField("field", (Object[]) null, JsonWriter::writeUntyped)), - ""), - Arguments.of(writeField(writer -> writer.writeArrayField("field", new Object[0], JsonWriter::writeUntyped)), - "{\"field\":[]}"), - Arguments.of(writeField(writer -> writer.writeArrayField("field", array, JsonWriter::writeUntyped)), - "{\"field\":" + expected + "}"), - - Arguments.of( - write(writer -> writer.writeArrayField("field", (List) null, JsonWriter::writeUntyped)), ""), - Arguments.of( - writeField( - writer -> writer.writeArrayField("field", Collections.emptyList(), JsonWriter::writeUntyped)), - "{\"field\":[]}"), - Arguments.of(writeField(writer -> writer.writeArray(Arrays.asList(array), JsonWriter::writeUntyped)), - "{\"field\":" + expected + "}")); - } - - @Test - public void writeMapThrowsNullPointerException() { - assertThrows(NullPointerException.class, () -> getJsonWriter().writeMap(Collections.emptyMap(), null)); - assertThrows(NullPointerException.class, - () -> getJsonWriter().writeMapField(null, Collections.emptyMap(), null)); - assertThrows(NullPointerException.class, - () -> getJsonWriter().writeMapField("field", Collections.emptyMap(), null)); - } - - @ParameterizedTest - @MethodSource("writeMapSupplier") - public void writeMap(IOExceptionConsumer write, String expected) throws IOException { - writeAndValidate(write, expected); - } - - private static Stream writeMapSupplier() { - Map map = new LinkedHashMap<>(); - map.put("boolean", true); - map.put("int", 42); - map.put("decimal", 42.0D); - map.put("string", "hello"); - String expected = "{\"boolean\":true,\"int\":42,\"decimal\":42.0,\"string\":\"hello\"}"; - - return Stream.of(Arguments.of(write(writer -> writer.writeMap(null, JsonWriter::writeUntyped)), "null"), - Arguments.of(write(writer -> writer.writeMap(Collections.emptyMap(), JsonWriter::writeUntyped)), "{}"), - Arguments.of(write(writer -> writer.writeMap(map, JsonWriter::writeUntyped)), expected), - - Arguments.of(write(writer -> writer.writeMapField("field", null, JsonWriter::writeUntyped)), ""), - Arguments.of( - writeField(writer -> writer.writeMapField("field", Collections.emptyMap(), JsonWriter::writeUntyped)), - "{\"field\":{}}"), - Arguments.of(writeField(writer -> writer.writeMapField("field", map, JsonWriter::writeUntyped)), - "{\"field\":" + expected + "}")); - } - - @ParameterizedTest - @MethodSource("writeUntypedSupplier") - public void writeUntyped(Object value, String expectedJson) throws IOException { - writeAndValidate(writer -> writer.writeUntyped(value), expectedJson); - } - - @ParameterizedTest - @MethodSource("writeUntypedSupplier") - public void writeUntypedField(Object value, String expectedUntypedJson) throws IOException { - writeAndValidate(writeField(writer -> writer.writeUntypedField("untyped", value)), - "{\"untyped\":" + expectedUntypedJson + "}"); - } - - private static Stream writeUntypedSupplier() { - byte[] bytes = new byte[] { 0, 1, 2, 3 }; - UUID uuid = UUID.randomUUID(); - - return Stream.of(Arguments.of(null, "null"), Arguments.of((short) 42, "42"), Arguments.of(42, "42"), - Arguments.of(42L, "42"), Arguments.of(42.0F, "42.0"), Arguments.of(42.0D, "42.0"), - Arguments.of(true, "true"), Arguments.of(bytes, "\"" + Base64.getEncoder().encodeToString(bytes) + "\""), - Arguments.of("hello", "\"hello\""), Arguments.of('h', "\"h\""), - Arguments.of(new SimpleSerializable(true, 42, 42.0D, "hello"), - "{\"boolean\":true,\"int\":42,\"decimal\":42.0,\"string\":\"hello\"}"), - Arguments.of(new Object[0], "[]"), - Arguments.of(new Object[] { null, 42, 42.0, true, "hello", 'h' }, "[null,42,42.0,true,\"hello\",\"h\"]"), - Arguments.of(Collections.emptyList(), "[]"), - Arguments.of(Arrays.asList(null, 42, 42.0, true, "hello", 'h'), "[null,42,42.0,true,\"hello\",\"h\"]"), - Arguments.of(Collections.singletonMap("hello", "json"), "{\"hello\":\"json\"}"), - Arguments.of(new Object(), "{}"), Arguments.of(uuid, "\"" + uuid + "\"")); - } - - @Test - public void writeNullableNullWriterFuncThrowsNullPointerException() { - assertThrows(NullPointerException.class, () -> getJsonWriter().writeNullableField("field", null, null)); - } - - @Test - public void writeNullableFieldNullValueWritesJsonNull() throws IOException { - writeAndValidate(writeField(writer -> writer.writeNullableField("field", null, JsonWriter::writeUntyped)), - "{\"field\":null}"); - } - - @Test - public void writeNullableFieldNonNullValueWritesJsonField() throws IOException { - writeAndValidate(writer -> writer.writeStartObject() - .writeNullableField("field", "hello", JsonWriter::writeString) - .writeEndObject(), "{\"field\":\"hello\"}"); - } - - @ParameterizedTest - @MethodSource("arrayMethodsWriteNullValueSupplier") - public void arrayMethodsWriteNullValue(IOExceptionConsumer write, String expected) throws IOException { - writeAndValidate(write, expected); - } - - private static Stream arrayMethodsWriteNullValueSupplier() { - List list = new ArrayList<>(); - list.add("hello"); - list.add(null); - list.add("world"); - - String[] array = new String[] { "hello", null, "world" }; - - String expectedJson = "[\"hello\",null,\"world\"]"; - String expectedFieldJson = "{\"field\":" + expectedJson + "}"; - - return Stream.of(Arguments.of(write(writer -> writer.writeArray(list, JsonWriter::writeString)), expectedJson), - Arguments.of(write(writer -> writer.writeArray(list, JsonWriter::writeString, false)), expectedJson), - Arguments.of(write(writer -> writer.writeArray(array, JsonWriter::writeString)), expectedJson), - Arguments.of(write(writer -> writer.writeArray(array, JsonWriter::writeString, false)), expectedJson), - Arguments.of(writeField(writer -> writer.writeArrayField("field", list, JsonWriter::writeString)), - expectedFieldJson), - Arguments.of(writeField(writer -> writer.writeArrayField("field", list, JsonWriter::writeString, false)), - expectedFieldJson), - Arguments.of(writeField(writer -> writer.writeArrayField("field", array, JsonWriter::writeString)), - expectedFieldJson), - Arguments.of(writeField(writer -> writer.writeArrayField("field", array, JsonWriter::writeString, false)), - expectedFieldJson)); - } - - @ParameterizedTest - @MethodSource("arrayMethodsSkipNullValueSupplier") - public void arrayMethodsSkipNullValue(IOExceptionConsumer write, String expected) throws IOException { - writeAndValidate(write, expected); - } - - private static Stream arrayMethodsSkipNullValueSupplier() { - List list = new ArrayList<>(); - list.add("hello"); - list.add(null); - list.add("world"); - - String[] array = new String[] { "hello", null, "world" }; - - String expectedJson = "[\"hello\",\"world\"]"; - String expectedFieldJson = "{\"field\":" + expectedJson + "}"; - - return Stream.of( - Arguments.of(write(writer -> writer.writeArray(list, JsonWriter::writeString, true)), expectedJson), - Arguments.of(write(writer -> writer.writeArray(array, JsonWriter::writeString, true)), expectedJson), - Arguments.of(writeField(writer -> writer.writeArrayField("field", list, JsonWriter::writeString, true)), - expectedFieldJson), - Arguments.of(writeField(writer -> writer.writeArrayField("field", array, JsonWriter::writeString, true)), - expectedFieldJson)); - } - - @ParameterizedTest - @MethodSource("mapMethodsWriteNullValueSupplier") - public void mapMethodsWriteNullValue(IOExceptionConsumer write, String expected) throws IOException { - writeAndValidate(write, expected); - } - - private static Stream mapMethodsWriteNullValueSupplier() { - Map map = new LinkedHashMap<>(); - map.put("hello", "world"); - map.put("null", null); - - String expectedJson = "{\"hello\":\"world\",\"null\":null}"; - String expectedFieldJson = "{\"field\":" + expectedJson + "}"; - - return Stream.of(Arguments.of(write(writer -> writer.writeMap(map, JsonWriter::writeString)), expectedJson), - Arguments.of(write(writer -> writer.writeMap(map, JsonWriter::writeString, false)), expectedJson), - Arguments.of(writeField(writer -> writer.writeMapField("field", map, JsonWriter::writeString)), - expectedFieldJson), - Arguments.of(writeField(writer -> writer.writeMapField("field", map, JsonWriter::writeString, false)), - expectedFieldJson)); - } - - @ParameterizedTest - @MethodSource("mapMethodsSkipNullValueSupplier") - public void mapMethodsSkipNullValue(IOExceptionConsumer write, String expected) throws IOException { - writeAndValidate(write, expected); - } - - private static Stream mapMethodsSkipNullValueSupplier() { - Map map = new LinkedHashMap<>(); - map.put("hello", "world"); - map.put("null", null); - - String expectedJson = "{\"hello\":\"world\"}"; - String expectedFieldJson = "{\"field\":" + expectedJson + "}"; - - return Stream.of( - Arguments.of(write(writer -> writer.writeMap(map, JsonWriter::writeString, true)), expectedJson), - Arguments.of(writeField(writer -> writer.writeMapField("field", map, JsonWriter::writeString, true)), - expectedFieldJson)); - } - - private void writeAndValidate(IOExceptionConsumer write, String expected) throws IOException { - try (JsonWriter writer = getJsonWriter()) { - write.accept(writer); - writer.flush(); - - assertEquals(expected, getJsonWriterContents()); - } catch (IllegalStateException ignored) { - // Ignore IllegalStateException if JsonWriter is closed in an invalid state. - } - } - - private static IOExceptionConsumer write(IOExceptionConsumer callback) { - return callback; - } - - private static IOExceptionConsumer writeField(IOExceptionConsumer callback) { - return writer -> { - writer.writeStartObject(); - callback.accept(writer); - writer.writeEndObject(); - }; - } - - /** - * Interface that aids in testing methods that throw IOExceptions. - * - * @param The type of the input to the operation. - */ - public interface IOExceptionConsumer { - /** - * Performs this operation on the given argument. - * - * @param t The input argument - * @throws IOException If an I/O error occurs - */ - void accept(T t) throws IOException; - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/models/JsonArrayContractTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/models/JsonArrayContractTests.java deleted file mode 100644 index fab936d10867..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/models/JsonArrayContractTests.java +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package io.clientcore.core.serialization.json.contract.models; - -import io.clientcore.core.serialization.json.JsonOptions; -import io.clientcore.core.serialization.json.JsonProvider; -import io.clientcore.core.serialization.json.JsonReader; -import io.clientcore.core.serialization.json.JsonWriter; -import io.clientcore.core.serialization.json.implementation.StringBuilderWriter; -import io.clientcore.core.serialization.json.models.JsonArray; -import io.clientcore.core.serialization.json.models.JsonBoolean; -import io.clientcore.core.serialization.json.models.JsonElement; -import io.clientcore.core.serialization.json.models.JsonNull; -import io.clientcore.core.serialization.json.models.JsonNumber; -import io.clientcore.core.serialization.json.models.JsonString; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; - -import java.io.IOException; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * Tests the contract of {@link JsonArray}. - *

        - * All implementations of {@link JsonProvider} must create a subclass of this test class and pass all tests as they're - * written to be considered an acceptable implementation. - */ -public abstract class JsonArrayContractTests { - /** - * Creates an instance {@link JsonProvider} that will be used by a test. - * - * @return The {@link JsonProvider} that a test will use. - */ - protected abstract JsonProvider getJsonProvider(); - - @Test - public void kindCheck() { - JsonElement element = new JsonArray(); - assertTrue(element.isArray()); - assertFalse(element.isObject()); - assertFalse(element.isString()); - assertFalse(element.isNumber()); - assertFalse(element.isBoolean()); - assertFalse(element.isNull()); - } - - @Test - public void emptyArrayFromJson() throws IOException { - String json = "[]"; - try (JsonReader reader = getJsonProvider().createReader(json, new JsonOptions())) { - JsonArray jsonArray = JsonArray.fromJson(reader); - assertEquals(0, jsonArray.size()); - } - } - - @Test - public void arrayOfBasicTypesFromJson() throws IOException { - String json = "[\"string\",null,10,10.0,true]"; - try (JsonReader reader = getJsonProvider().createReader(json, new JsonOptions())) { - JsonArray jsonArray = JsonArray.fromJson(reader); - - JsonElement stringElement = jsonArray.getElement(0); - assertTrue(stringElement.isString()); - assertEquals("\"string\"", stringElement.toJsonString()); - - JsonElement nullElement = jsonArray.getElement(1); - assertTrue(nullElement.isNull()); - - JsonElement intElement = jsonArray.getElement(2); - assertTrue(intElement.isNumber()); - assertEquals("10", intElement.toJsonString()); - - JsonElement doubleElement = jsonArray.getElement(3); - assertTrue(doubleElement.isNumber()); - assertEquals("10.0", doubleElement.toJsonString()); - - JsonElement booleanElement = jsonArray.getElement(4); - assertTrue(booleanElement.isBoolean()); - assertEquals("true", booleanElement.toJsonString()); - } - } - - @Test - public void emptyArrayToJson() throws IOException { - JsonArray jsonArray = new JsonArray(); - assertEquals(0, jsonArray.size()); - - try (StringBuilderWriter writer = new StringBuilderWriter(); - JsonWriter jsonWriter = getJsonProvider().createWriter(writer, new JsonOptions())) { - jsonArray.toJson(jsonWriter); - jsonWriter.flush(); - - assertEquals("[]", writer.toString()); - } - } - - @Test - public void arrayOfBasicTypesToJson() throws IOException { - JsonArray jsonArray = new JsonArray().addElement(new JsonString("string")) - .addElement(JsonNull.getInstance()) - .addElement(new JsonNumber(10)) - .addElement(new JsonNumber(10.0D)) - .addElement(JsonBoolean.getInstance(true)); - - assertEquals(5, jsonArray.size()); - - try (StringBuilderWriter writer = new StringBuilderWriter(); - JsonWriter jsonWriter = getJsonProvider().createWriter(writer, new JsonOptions())) { - jsonArray.toJson(jsonWriter); - jsonWriter.flush(); - - assertEquals("[\"string\",null,10,10.0,true]", writer.toString()); - } - } - - @ParameterizedTest - @ValueSource(strings = { "true", "null", "10", "10.0", "\"hello\"", "{}" }) - public void invalidFromJsonStartingPoints(String json) throws IOException { - try (JsonReader reader = getJsonProvider().createReader(json, new JsonOptions())) { - assertThrows(IllegalStateException.class, () -> JsonArray.fromJson(reader)); - } - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/models/JsonBooleanContractTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/models/JsonBooleanContractTests.java deleted file mode 100644 index 9ff07b387ca3..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/models/JsonBooleanContractTests.java +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package io.clientcore.core.serialization.json.contract.models; - -import io.clientcore.core.serialization.json.JsonOptions; -import io.clientcore.core.serialization.json.JsonProvider; -import io.clientcore.core.serialization.json.JsonReader; -import io.clientcore.core.serialization.json.JsonWriter; -import io.clientcore.core.serialization.json.implementation.StringBuilderWriter; -import io.clientcore.core.serialization.json.models.JsonBoolean; -import io.clientcore.core.serialization.json.models.JsonElement; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; - -import java.io.IOException; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * Tests the contract of {@link JsonBoolean}. - *

        - * All implementations of {@link JsonProvider} must create a subclass of this test class and pass all tests as they're - * written to be considered an acceptable implementation. - */ -public abstract class JsonBooleanContractTests { - /** - * Creates an instance {@link JsonProvider} that will be used by a test. - * - * @return The {@link JsonProvider} that a test will use. - */ - protected abstract JsonProvider getJsonProvider(); - - @Test - public void kindCheck() { - JsonElement element = JsonBoolean.getInstance(true); - assertTrue(element.isBoolean()); - assertFalse(element.isArray()); - assertFalse(element.isObject()); - assertFalse(element.isString()); - assertFalse(element.isNumber()); - assertFalse(element.isNull()); - } - - @ParameterizedTest - @ValueSource(strings = { "true", "false" }) - public void fromJson(String json) throws IOException { - try (JsonReader reader = getJsonProvider().createReader(json, new JsonOptions())) { - JsonBoolean jsonBoolean = JsonBoolean.fromJson(reader); - assertEquals(json, jsonBoolean.toJsonString()); - if ("true".equals(json)) { - assertTrue(jsonBoolean.getValue()); - assertSame(JsonBoolean.getInstance(true), jsonBoolean); - } else { - assertFalse(jsonBoolean.getValue()); - assertSame(JsonBoolean.getInstance(false), jsonBoolean); - } - } - } - - @ParameterizedTest - @ValueSource(booleans = { true, false }) - public void toJson(boolean value) throws IOException { - JsonBoolean jsonBoolean = JsonBoolean.getInstance(value); - try (StringBuilderWriter writer = new StringBuilderWriter()) { - try (JsonWriter jsonWriter = getJsonProvider().createWriter(writer, new JsonOptions())) { - jsonBoolean.toJson(jsonWriter); - } - assertEquals(Boolean.toString(value), writer.toString()); - } - } - - @ParameterizedTest - @ValueSource(strings = { "null", "10", "10.0", "\"hello\"", "[]", "{}" }) - public void invalidFromJsonStartingPoints(String json) throws IOException { - try (JsonReader reader = getJsonProvider().createReader(json, new JsonOptions())) { - assertThrows(IllegalStateException.class, () -> JsonBoolean.fromJson(reader)); - } - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/models/JsonElementContractTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/models/JsonElementContractTests.java deleted file mode 100644 index c8e695b81904..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/models/JsonElementContractTests.java +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package io.clientcore.core.serialization.json.contract.models; - -import io.clientcore.core.serialization.json.JsonProvider; -import io.clientcore.core.serialization.json.models.JsonElement; - -/** - * Tests the contract of {@link JsonElement}. - *

        - * All implementations of {@link JsonProvider} must create a subclass of this test class and pass all tests as they're - * written to be considered an acceptable implementation. - */ -public abstract class JsonElementContractTests { - /** - * Creates an instance {@link JsonProvider} that will be used by a test. - * - * @return The {@link JsonProvider} that a test will use. - */ - protected abstract JsonProvider getJsonProvider(); -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/models/JsonNullContractTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/models/JsonNullContractTests.java deleted file mode 100644 index a9b7f0fc20f3..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/models/JsonNullContractTests.java +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package io.clientcore.core.serialization.json.contract.models; - -import io.clientcore.core.serialization.json.JsonOptions; -import io.clientcore.core.serialization.json.JsonProvider; -import io.clientcore.core.serialization.json.JsonReader; -import io.clientcore.core.serialization.json.JsonWriter; -import io.clientcore.core.serialization.json.implementation.StringBuilderWriter; -import io.clientcore.core.serialization.json.models.JsonElement; -import io.clientcore.core.serialization.json.models.JsonNull; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; - -import java.io.IOException; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * Tests the contract of {@link JsonNull}. - *

        - * All implementations of {@link JsonProvider} must create a subclass of this test class and pass all tests as they're - * written to be considered an acceptable implementation. - */ -public abstract class JsonNullContractTests { - /** - * Creates an instance {@link JsonProvider} that will be used by a test. - * - * @return The {@link JsonProvider} that a test will use. - */ - protected abstract JsonProvider getJsonProvider(); - - @Test - public void kindCheck() { - JsonElement element = JsonNull.getInstance(); - assertTrue(element.isNull()); - assertFalse(element.isArray()); - assertFalse(element.isObject()); - assertFalse(element.isString()); - assertFalse(element.isNumber()); - assertFalse(element.isBoolean()); - } - - @Test - public void fromJson() throws IOException { - try (JsonReader reader = getJsonProvider().createReader("null", new JsonOptions())) { - JsonNull jsonNull = JsonNull.fromJson(reader); - assertEquals("null", jsonNull.toJsonString()); - assertSame(JsonNull.getInstance(), jsonNull); - } - } - - @Test - public void toJson() throws IOException { - JsonNull jsonNull = JsonNull.getInstance(); - try (StringBuilderWriter writer = new StringBuilderWriter()) { - try (JsonWriter jsonWriter = getJsonProvider().createWriter(writer, new JsonOptions())) { - jsonNull.toJson(jsonWriter); - } - assertEquals("null", writer.toString()); - } - } - - @ParameterizedTest - @ValueSource(strings = { "true", "10", "10.0", "\"hello\"", "[]", "{}" }) - public void invalidFromJsonStartingPoints(String json) throws IOException { - try (JsonReader reader = getJsonProvider().createReader(json, new JsonOptions())) { - assertThrows(IllegalStateException.class, () -> JsonNull.fromJson(reader)); - } - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/models/JsonNumberContractTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/models/JsonNumberContractTests.java deleted file mode 100644 index b7a5bb097a2c..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/models/JsonNumberContractTests.java +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package io.clientcore.core.serialization.json.contract.models; - -import io.clientcore.core.serialization.json.JsonOptions; -import io.clientcore.core.serialization.json.JsonProvider; -import io.clientcore.core.serialization.json.JsonReader; -import io.clientcore.core.serialization.json.JsonWriter; -import io.clientcore.core.serialization.json.implementation.StringBuilderWriter; -import io.clientcore.core.serialization.json.models.JsonElement; -import io.clientcore.core.serialization.json.models.JsonNumber; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; -import org.junit.jupiter.params.provider.ValueSource; - -import java.io.IOException; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.text.ParseException; -import java.util.stream.Stream; - -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.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * Tests the contract of {@link JsonNumber}. - *

        - * All implementations of {@link JsonProvider} must create a subclass of this test class and pass all tests as they're - * written to be considered an acceptable implementation. - */ -public abstract class JsonNumberContractTests { - /** - * Creates an instance {@link JsonProvider} that will be used by a test. - * - * @return The {@link JsonProvider} that a test will use. - */ - protected abstract JsonProvider getJsonProvider(); - - @Test - public void kindCheck() { - JsonElement element = new JsonNumber(0); - assertTrue(element.isNumber()); - assertFalse(element.isArray()); - assertFalse(element.isObject()); - assertFalse(element.isString()); - assertFalse(element.isBoolean()); - assertFalse(element.isNull()); - } - - @ParameterizedTest - @MethodSource("fromJsonSupplier") - public void fromJson(String json, Number number) throws IOException, ParseException { - try (JsonReader reader = getJsonProvider().createReader(json, new JsonOptions())) { - JsonNumber jsonNumber = JsonNumber.fromJson(reader); - if (number instanceof BigInteger) { - BigInteger jsonBigInteger = assertInstanceOf(BigInteger.class, jsonNumber.getValue()); - assertEquals(0, ((BigInteger) number).compareTo(jsonBigInteger)); - } else if (number instanceof BigDecimal) { - BigDecimal jsonBigDecimal = assertInstanceOf(BigDecimal.class, jsonNumber.getValue()); - assertEquals(0, ((BigDecimal) number).compareTo(jsonBigDecimal)); - } else { - assertEquals(number, jsonNumber.getValue()); - } - } - } - - private static Stream fromJsonSupplier() { - return Stream.of(Arguments.of("0", 0), Arguments.of("-1", -1), Arguments.of("10000000000", 10000000000L), - Arguments.of("-10000000000", -10000000000L), - Arguments.of("100000000000000000000", new BigInteger("100000000000000000000")), - Arguments.of("-100000000000000000000", new BigInteger("-100000000000000000000")), Arguments.of("0.0", 0.0F), - Arguments.of("-1.0", -1.0F), Arguments.of("1E6", 1E6F), Arguments.of("-1E6", -1E6F), - Arguments.of("1.0E6", 1E6F), Arguments.of("-1.0E6", -1E6F), Arguments.of("1e6", 1E6F), - Arguments.of("-1e6", -1E6F), Arguments.of("1.0e6", 1E6F), Arguments.of("-1.0e6", -1E6F), - Arguments.of("1E39", 1E39D), Arguments.of("-1E39", -1E39D), Arguments.of("1.0E39", 1E39D), - Arguments.of("-1.0E39", -1E39D), Arguments.of("1e39", 1E39D), Arguments.of("-1e39", -1E39D), - Arguments.of("1.0e39", 1E39D), Arguments.of("-1.0e39", -1E39D), - Arguments.of("1E309", new BigDecimal("1E309")), Arguments.of("-1E309", new BigDecimal("-1E309")), - Arguments.of("1.0E309", new BigDecimal("1E309")), Arguments.of("-1.0E309", new BigDecimal("-1E309")), - Arguments.of("1e309", new BigDecimal("1E309")), Arguments.of("-1e309", new BigDecimal("-1E309")), - Arguments.of("1.0e309", new BigDecimal("1E309")), Arguments.of("-1.0e309", new BigDecimal("-1E309")), - Arguments.of("Infinity", Double.POSITIVE_INFINITY), Arguments.of("-Infinity", Double.NEGATIVE_INFINITY)); - } - - @ParameterizedTest - @MethodSource("toJsonSupplier") - public void toJson(Number value) throws IOException { - JsonNumber jsonNumber = new JsonNumber(value); - try (StringBuilderWriter writer = new StringBuilderWriter()) { - try (JsonWriter jsonWriter = getJsonProvider().createWriter(writer, new JsonOptions())) { - jsonNumber.toJson(jsonWriter); - } - assertEquals(String.valueOf(value), writer.toString()); - } - } - - private static Stream toJsonSupplier() { - return Stream.of(0, -1, 0.0, -1.0, 1E6, -1E6, 1.0E6, -1.0E6); - } - - @ParameterizedTest - @ValueSource(strings = { "true", "null", "\"hello\"", "[]", "{}" }) - public void invalidFromJsonStartingPoints(String json) throws IOException { - try (JsonReader reader = getJsonProvider().createReader(json, new JsonOptions())) { - assertThrows(IllegalStateException.class, () -> JsonNumber.fromJson(reader)); - } - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/models/JsonObjectContractTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/models/JsonObjectContractTests.java deleted file mode 100644 index 43d9931c1cc4..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/models/JsonObjectContractTests.java +++ /dev/null @@ -1,138 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package io.clientcore.core.serialization.json.contract.models; - -import io.clientcore.core.serialization.json.JsonOptions; -import io.clientcore.core.serialization.json.JsonProvider; -import io.clientcore.core.serialization.json.JsonReader; -import io.clientcore.core.serialization.json.JsonWriter; -import io.clientcore.core.serialization.json.implementation.StringBuilderWriter; -import io.clientcore.core.serialization.json.models.JsonBoolean; -import io.clientcore.core.serialization.json.models.JsonElement; -import io.clientcore.core.serialization.json.models.JsonNull; -import io.clientcore.core.serialization.json.models.JsonNumber; -import io.clientcore.core.serialization.json.models.JsonObject; -import io.clientcore.core.serialization.json.models.JsonString; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; - -import java.io.IOException; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * Tests the contract of {@link JsonObject}. - *

        - * All implementations of {@link JsonProvider} must create a subclass of this test class and pass all tests as they're - * written to be considered an acceptable implementation. - */ -public abstract class JsonObjectContractTests { - /** - * Creates an instance {@link JsonProvider} that will be used by a test. - * - * @return The {@link JsonProvider} that a test will use. - */ - protected abstract JsonProvider getJsonProvider(); - - @Test - public void kindCheck() { - JsonElement element = new JsonObject(); - assertTrue(element.isObject()); - assertFalse(element.isArray()); - assertFalse(element.isNumber()); - assertFalse(element.isString()); - assertFalse(element.isBoolean()); - assertFalse(element.isNull()); - } - - @Test - public void emptyObjectFromJson() throws IOException { - String json = "{}"; - try (JsonReader reader = getJsonProvider().createReader(json, new JsonOptions())) { - JsonObject jsonObject = JsonObject.fromJson(reader); - assertEquals(0, jsonObject.size()); - } - } - - @Test - public void objectOfBasicTypesFromJson() throws IOException { - String json = "{\"string\":\"string\",\"null\":null,\"integer\":10,\"float\":10.0,\"boolean\":true}"; - try (JsonReader reader = getJsonProvider().createReader(json, new JsonOptions())) { - JsonObject jsonObject = JsonObject.fromJson(reader); - assertEquals(5, jsonObject.size()); - - JsonElement stringElement = jsonObject.getProperty("string"); - assertTrue(stringElement.isString()); - assertEquals("\"string\"", stringElement.toJsonString()); - - JsonElement nullElement = jsonObject.getProperty("null"); - assertTrue(nullElement.isNull()); - - JsonElement intElement = jsonObject.getProperty("integer"); - assertTrue(intElement.isNumber()); - assertEquals("10", intElement.toJsonString()); - - JsonElement doubleElement = jsonObject.getProperty("float"); - assertTrue(doubleElement.isNumber()); - assertEquals("10.0", doubleElement.toJsonString()); - - JsonElement booleanElement = jsonObject.getProperty("boolean"); - assertTrue(booleanElement.isBoolean()); - assertEquals("true", booleanElement.toJsonString()); - - assertEquals(json, jsonObject.toJsonString()); - - assertEquals("\"string\"", jsonObject.removeProperty("string").toJsonString()); - assertEquals(4, jsonObject.size()); - assertNull(jsonObject.removeProperty("string")); - assertEquals("{\"null\":null,\"integer\":10,\"float\":10.0,\"boolean\":true}", jsonObject.toJsonString()); - } - } - - @Test - public void emptyObjectToJson() throws IOException { - JsonObject jsonObject = new JsonObject(); - assertEquals(0, jsonObject.size()); - - try (StringBuilderWriter writer = new StringBuilderWriter(); - JsonWriter jsonWriter = getJsonProvider().createWriter(writer, new JsonOptions())) { - jsonObject.toJson(jsonWriter); - jsonWriter.flush(); - - assertEquals("{}", writer.toString()); - } - } - - @Test - public void objectOfBasicTypesToJson() throws IOException { - JsonObject jsonObject = new JsonObject().setProperty("string", new JsonString("string")) - .setProperty("null", JsonNull.getInstance()) - .setProperty("integer", new JsonNumber(10)) - .setProperty("float", new JsonNumber(10.0D)) - .setProperty("boolean", JsonBoolean.getInstance(true)); - - assertEquals(5, jsonObject.size()); - - try (StringBuilderWriter writer = new StringBuilderWriter(); - JsonWriter jsonWriter = getJsonProvider().createWriter(writer, new JsonOptions())) { - jsonObject.toJson(jsonWriter); - jsonWriter.flush(); - - assertEquals("{\"string\":\"string\",\"null\":null,\"integer\":10,\"float\":10.0,\"boolean\":true}", - writer.toString()); - } - } - - @ParameterizedTest - @ValueSource(strings = { "true", "null", "1", "1.0", "\"hello\"", "[]" }) - public void invalidFromJsonStartingPoints(String json) throws IOException { - try (JsonReader reader = getJsonProvider().createReader(json, new JsonOptions())) { - assertThrows(IllegalStateException.class, () -> JsonObject.fromJson(reader)); - } - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/models/JsonStringContractTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/models/JsonStringContractTests.java deleted file mode 100644 index 9ad215c5e782..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/contract/models/JsonStringContractTests.java +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package io.clientcore.core.serialization.json.contract.models; - -import io.clientcore.core.serialization.json.JsonOptions; -import io.clientcore.core.serialization.json.JsonProvider; -import io.clientcore.core.serialization.json.JsonReader; -import io.clientcore.core.serialization.json.JsonWriter; -import io.clientcore.core.serialization.json.implementation.StringBuilderWriter; -import io.clientcore.core.serialization.json.models.JsonElement; -import io.clientcore.core.serialization.json.models.JsonString; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; - -import java.io.IOException; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * Tests the contract of {@link JsonString}. - *

        - * All implementations of {@link JsonProvider} must create a subclass of this test class and pass all tests as they're - * written to be considered an acceptable implementation. - */ -public abstract class JsonStringContractTests { - /** - * Creates an instance {@link JsonProvider} that will be used by a test. - * - * @return The {@link JsonProvider} that a test will use. - */ - protected abstract JsonProvider getJsonProvider(); - - @Test - public void kindCheck() { - JsonElement element = new JsonString(""); - assertTrue(element.isString()); - assertFalse(element.isArray()); - assertFalse(element.isObject()); - assertFalse(element.isNumber()); - assertFalse(element.isBoolean()); - assertFalse(element.isNull()); - } - - @ParameterizedTest - @ValueSource(strings = { "\"\"", "\"hello\"" }) - public void fromJson(String json) throws IOException { - try (JsonReader reader = getJsonProvider().createReader(json, new JsonOptions())) { - JsonString jsonString = JsonString.fromJson(reader); - assertEquals(json, jsonString.toJsonString()); - assertEquals(json.substring(1, json.length() - 1), jsonString.getValue()); - } - } - - @Test - public void toJsonStringCachesValue() throws IOException { - JsonString jsonString = new JsonString("hello"); - String json = jsonString.toJsonString(); - assertEquals("\"hello\"", json); - assertSame(json, jsonString.toJsonString()); - } - - @ParameterizedTest - @ValueSource(strings = { "", "hello" }) - public void toJson(String value) throws IOException { - JsonString jsonString = new JsonString(value); - try (StringBuilderWriter writer = new StringBuilderWriter()) { - try (JsonWriter jsonWriter = getJsonProvider().createWriter(writer, new JsonOptions())) { - jsonString.toJson(jsonWriter); - } - assertEquals("\"" + value + "\"", writer.toString()); - } - } - - @ParameterizedTest - @ValueSource(strings = { "true", "null", "1", "1.0", "[]", "{}" }) - public void invalidFromJsonStartingPoints(String json) throws IOException { - try (JsonReader reader = getJsonProvider().createReader(json, new JsonOptions())) { - assertThrows(IllegalStateException.class, () -> JsonString.fromJson(reader)); - } - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/DefaultJsonProviderContractTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/DefaultJsonProviderContractTests.java deleted file mode 100644 index 61a852fb0b3a..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/DefaultJsonProviderContractTests.java +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.serialization.json.implementation; - -import io.clientcore.core.serialization.json.JsonProvider; -import io.clientcore.core.serialization.json.contract.JsonProviderContractTests; - -/** - * Tests {@link DefaultJsonProvider} against the contract required by {@link JsonProvider}. - */ -public class DefaultJsonProviderContractTests extends JsonProviderContractTests { - @Override - protected JsonProvider getJsonProvider() { - return new DefaultJsonProvider(); - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/DefaultJsonReaderContractTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/DefaultJsonReaderContractTests.java deleted file mode 100644 index 7011dbb640bb..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/DefaultJsonReaderContractTests.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.serialization.json.implementation; - -import io.clientcore.core.serialization.json.JsonOptions; -import io.clientcore.core.serialization.json.JsonReader; -import io.clientcore.core.serialization.json.contract.JsonReaderContractTests; -import io.clientcore.core.serialization.json.implementation.jackson.core.JsonParseException; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; - -import java.io.IOException; - -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; - -/** - * Tests {@link DefaultJsonReader} against the contract required by {@link JsonReader}. - */ -public class DefaultJsonReaderContractTests extends JsonReaderContractTests { - private JsonReader reader; - String jsonWithComments = "{ // single line comment\n \"single-line\": \"comment\",\n /*\n" - + " multi-line comment\n */\n \"multi-line\": \"comment\"}"; - - @Override - public JsonReader getJsonReader(String json) throws IOException { - this.reader = DefaultJsonReader.fromString(json, new JsonOptions()); - return reader; - } - - @AfterEach - public void afterEach() throws IOException { - if (reader != null) { - reader.close(); - } - } - - @Test - public void readJsonc() throws IOException { - - try (JsonReader jsonReader - = DefaultJsonReader.fromString(jsonWithComments, new JsonOptions().setJsoncSupported(true))) { - jsonReader.nextToken(); - String outputJson = jsonReader.readChildren(); - assertNotNull(outputJson); - } - } - - @Test - public void readJsoncFails() throws IOException { - assertThrows(JsonParseException.class, () -> { - try (JsonReader jsonReader = getJsonReader(jsonWithComments)) { - jsonReader.nextToken(); - String outputJson = jsonReader.readChildren(); - assertNotNull(outputJson); - } - }); - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/DefaultJsonWriterContractTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/DefaultJsonWriterContractTests.java deleted file mode 100644 index c1a12d741e43..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/DefaultJsonWriterContractTests.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.serialization.json.implementation; - -import io.clientcore.core.serialization.json.JsonOptions; -import io.clientcore.core.serialization.json.JsonWriter; -import io.clientcore.core.serialization.json.contract.JsonWriterContractTests; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.charset.StandardCharsets; - -/** - * Tests {@link DefaultJsonWriter} against the contract required by {@link JsonWriter}. - */ -public class DefaultJsonWriterContractTests extends JsonWriterContractTests { - private ByteArrayOutputStream outputStream; - private JsonWriter writer; - - @BeforeEach - public void beforeEach() throws IOException { - this.outputStream = new ByteArrayOutputStream(); - this.writer = DefaultJsonWriter.toStream(outputStream, new JsonOptions()); - } - - @AfterEach - public void afterEach() throws IOException { - if (writer != null) { - try { - writer.close(); - } catch (IllegalStateException ignored) { - // Closing the JsonWriter may throw an IllegalStateException if the current writing state isn't valid - // for closing, ignore it in test. - } - } - } - - @Override - public JsonWriter getJsonWriter() { - return writer; - } - - @Override - public String getJsonWriterContents() { - try { - writer.flush(); - return outputStream.toString(StandardCharsets.UTF_8.name()); - } catch (IOException e) { - throw new RuntimeException(e); - } - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/models/DefaultJsonArrayContractTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/models/DefaultJsonArrayContractTests.java deleted file mode 100644 index 027b418e2177..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/models/DefaultJsonArrayContractTests.java +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package io.clientcore.core.serialization.json.implementation.models; - -import io.clientcore.core.serialization.json.JsonProvider; -import io.clientcore.core.serialization.json.implementation.DefaultJsonProvider; -import io.clientcore.core.serialization.json.contract.models.JsonArrayContractTests; - -public class DefaultJsonArrayContractTests extends JsonArrayContractTests { - @Override - protected JsonProvider getJsonProvider() { - return new DefaultJsonProvider(); - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/models/DefaultJsonBooleanContractTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/models/DefaultJsonBooleanContractTests.java deleted file mode 100644 index 24e9a8232947..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/models/DefaultJsonBooleanContractTests.java +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package io.clientcore.core.serialization.json.implementation.models; - -import io.clientcore.core.serialization.json.JsonProvider; -import io.clientcore.core.serialization.json.implementation.DefaultJsonProvider; -import io.clientcore.core.serialization.json.contract.models.JsonBooleanContractTests; - -public class DefaultJsonBooleanContractTests extends JsonBooleanContractTests { - @Override - protected JsonProvider getJsonProvider() { - return new DefaultJsonProvider(); - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/models/DefaultJsonElementContractTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/models/DefaultJsonElementContractTests.java deleted file mode 100644 index edad1d31b9ce..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/models/DefaultJsonElementContractTests.java +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package io.clientcore.core.serialization.json.implementation.models; - -import io.clientcore.core.serialization.json.JsonProvider; -import io.clientcore.core.serialization.json.implementation.DefaultJsonProvider; -import io.clientcore.core.serialization.json.contract.models.JsonElementContractTests; - -public class DefaultJsonElementContractTests extends JsonElementContractTests { - @Override - protected JsonProvider getJsonProvider() { - return new DefaultJsonProvider(); - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/models/DefaultJsonNullContractTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/models/DefaultJsonNullContractTests.java deleted file mode 100644 index f271b35ee28d..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/models/DefaultJsonNullContractTests.java +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package io.clientcore.core.serialization.json.implementation.models; - -import io.clientcore.core.serialization.json.JsonProvider; -import io.clientcore.core.serialization.json.implementation.DefaultJsonProvider; -import io.clientcore.core.serialization.json.contract.models.JsonNullContractTests; - -public class DefaultJsonNullContractTests extends JsonNullContractTests { - @Override - protected JsonProvider getJsonProvider() { - return new DefaultJsonProvider(); - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/models/DefaultJsonNumberContractTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/models/DefaultJsonNumberContractTests.java deleted file mode 100644 index 4f0fbaa5f6de..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/models/DefaultJsonNumberContractTests.java +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package io.clientcore.core.serialization.json.implementation.models; - -import io.clientcore.core.serialization.json.JsonProvider; -import io.clientcore.core.serialization.json.implementation.DefaultJsonProvider; -import io.clientcore.core.serialization.json.contract.models.JsonNumberContractTests; - -public class DefaultJsonNumberContractTests extends JsonNumberContractTests { - @Override - protected JsonProvider getJsonProvider() { - return new DefaultJsonProvider(); - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/models/DefaultJsonObjectContractTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/models/DefaultJsonObjectContractTests.java deleted file mode 100644 index 260ac0884313..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/models/DefaultJsonObjectContractTests.java +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package io.clientcore.core.serialization.json.implementation.models; - -import io.clientcore.core.serialization.json.JsonProvider; -import io.clientcore.core.serialization.json.implementation.DefaultJsonProvider; -import io.clientcore.core.serialization.json.contract.models.JsonObjectContractTests; - -public class DefaultJsonObjectContractTests extends JsonObjectContractTests { - @Override - protected JsonProvider getJsonProvider() { - return new DefaultJsonProvider(); - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/models/DefaultJsonStringContractTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/models/DefaultJsonStringContractTests.java deleted file mode 100644 index c3e7309d545a..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/implementation/models/DefaultJsonStringContractTests.java +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package io.clientcore.core.serialization.json.implementation.models; - -import io.clientcore.core.serialization.json.JsonProvider; -import io.clientcore.core.serialization.json.implementation.DefaultJsonProvider; -import io.clientcore.core.serialization.json.contract.models.JsonStringContractTests; - -public class DefaultJsonStringContractTests extends JsonStringContractTests { - @Override - protected JsonProvider getJsonProvider() { - return new DefaultJsonProvider(); - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/models/JsonArrayTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/models/JsonArrayTests.java new file mode 100644 index 000000000000..04797a096001 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/models/JsonArrayTests.java @@ -0,0 +1,110 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.serialization.json.models; + +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonWriter; +import io.clientcore.core.serialization.json.implementation.StringBuilderWriter; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Tests {@link JsonArray}. + */ +public class JsonArrayTests { + @Test + public void kindCheck() { + JsonElement element = new JsonArray(); + assertTrue(element.isArray()); + assertFalse(element.isObject()); + assertFalse(element.isString()); + assertFalse(element.isNumber()); + assertFalse(element.isBoolean()); + assertFalse(element.isNull()); + } + + @Test + public void emptyArrayFromJson() throws IOException { + String json = "[]"; + try (JsonReader reader = JsonReader.fromString(json)) { + JsonArray jsonArray = JsonArray.fromJson(reader); + assertEquals(0, jsonArray.size()); + } + } + + @Test + public void arrayOfBasicTypesFromJson() throws IOException { + String json = "[\"string\",null,10,10.0,true]"; + try (JsonReader reader = JsonReader.fromString(json)) { + JsonArray jsonArray = JsonArray.fromJson(reader); + + JsonElement stringElement = jsonArray.getElement(0); + assertTrue(stringElement.isString()); + assertEquals("\"string\"", stringElement.toJsonString()); + + JsonElement nullElement = jsonArray.getElement(1); + assertTrue(nullElement.isNull()); + + JsonElement intElement = jsonArray.getElement(2); + assertTrue(intElement.isNumber()); + assertEquals("10", intElement.toJsonString()); + + JsonElement doubleElement = jsonArray.getElement(3); + assertTrue(doubleElement.isNumber()); + assertEquals("10.0", doubleElement.toJsonString()); + + JsonElement booleanElement = jsonArray.getElement(4); + assertTrue(booleanElement.isBoolean()); + assertEquals("true", booleanElement.toJsonString()); + } + } + + @Test + public void emptyArrayToJson() throws IOException { + JsonArray jsonArray = new JsonArray(); + assertEquals(0, jsonArray.size()); + + try (StringBuilderWriter writer = new StringBuilderWriter(); + JsonWriter jsonWriter = JsonWriter.toWriter(writer)) { + jsonArray.toJson(jsonWriter); + jsonWriter.flush(); + + assertEquals("[]", writer.toString()); + } + } + + @Test + public void arrayOfBasicTypesToJson() throws IOException { + JsonArray jsonArray = new JsonArray().addElement(new JsonString("string")) + .addElement(JsonNull.getInstance()) + .addElement(new JsonNumber(10)) + .addElement(new JsonNumber(10.0D)) + .addElement(JsonBoolean.getInstance(true)); + + assertEquals(5, jsonArray.size()); + + try (StringBuilderWriter writer = new StringBuilderWriter(); + JsonWriter jsonWriter = JsonWriter.toWriter(writer)) { + jsonArray.toJson(jsonWriter); + jsonWriter.flush(); + + assertEquals("[\"string\",null,10,10.0,true]", writer.toString()); + } + } + + @ParameterizedTest + @ValueSource(strings = { "true", "null", "10", "10.0", "\"hello\"", "{}" }) + public void invalidFromJsonStartingPoints(String json) throws IOException { + try (JsonReader reader = JsonReader.fromString(json)) { + assertThrows(IllegalStateException.class, () -> JsonArray.fromJson(reader)); + } + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/models/JsonBooleanTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/models/JsonBooleanTests.java new file mode 100644 index 000000000000..32f20cf902d3 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/models/JsonBooleanTests.java @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.serialization.json.models; + +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonWriter; +import io.clientcore.core.serialization.json.implementation.StringBuilderWriter; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Tests {@link JsonBoolean}. + */ +public class JsonBooleanTests { + @Test + public void kindCheck() { + JsonElement element = JsonBoolean.getInstance(true); + assertTrue(element.isBoolean()); + assertFalse(element.isArray()); + assertFalse(element.isObject()); + assertFalse(element.isString()); + assertFalse(element.isNumber()); + assertFalse(element.isNull()); + } + + @ParameterizedTest + @ValueSource(strings = { "true", "false" }) + public void fromJson(String json) throws IOException { + try (JsonReader reader = JsonReader.fromString(json)) { + JsonBoolean jsonBoolean = JsonBoolean.fromJson(reader); + assertEquals(json, jsonBoolean.toJsonString()); + if ("true".equals(json)) { + assertTrue(jsonBoolean.getValue()); + assertSame(JsonBoolean.getInstance(true), jsonBoolean); + } else { + assertFalse(jsonBoolean.getValue()); + assertSame(JsonBoolean.getInstance(false), jsonBoolean); + } + } + } + + @ParameterizedTest + @ValueSource(booleans = { true, false }) + public void toJson(boolean value) throws IOException { + JsonBoolean jsonBoolean = JsonBoolean.getInstance(value); + try (StringBuilderWriter writer = new StringBuilderWriter()) { + try (JsonWriter jsonWriter = JsonWriter.toWriter(writer)) { + jsonBoolean.toJson(jsonWriter); + } + assertEquals(Boolean.toString(value), writer.toString()); + } + } + + @ParameterizedTest + @ValueSource(strings = { "null", "10", "10.0", "\"hello\"", "[]", "{}" }) + public void invalidFromJsonStartingPoints(String json) throws IOException { + try (JsonReader reader = JsonReader.fromString(json)) { + assertThrows(IllegalStateException.class, () -> JsonBoolean.fromJson(reader)); + } + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/models/JsonNullTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/models/JsonNullTests.java new file mode 100644 index 000000000000..42952b8195d0 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/models/JsonNullTests.java @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.serialization.json.models; + +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonWriter; +import io.clientcore.core.serialization.json.implementation.StringBuilderWriter; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Tests {@link JsonNull}. + */ +public class JsonNullTests { + @Test + public void kindCheck() { + JsonElement element = JsonNull.getInstance(); + assertTrue(element.isNull()); + assertFalse(element.isArray()); + assertFalse(element.isObject()); + assertFalse(element.isString()); + assertFalse(element.isNumber()); + assertFalse(element.isBoolean()); + } + + @Test + public void fromJson() throws IOException { + try (JsonReader reader = JsonReader.fromString("null")) { + JsonNull jsonNull = JsonNull.fromJson(reader); + assertEquals("null", jsonNull.toJsonString()); + assertSame(JsonNull.getInstance(), jsonNull); + } + } + + @Test + public void toJson() throws IOException { + JsonNull jsonNull = JsonNull.getInstance(); + try (StringBuilderWriter writer = new StringBuilderWriter()) { + try (JsonWriter jsonWriter = JsonWriter.toWriter(writer)) { + jsonNull.toJson(jsonWriter); + } + assertEquals("null", writer.toString()); + } + } + + @ParameterizedTest + @ValueSource(strings = { "true", "10", "10.0", "\"hello\"", "[]", "{}" }) + public void invalidFromJsonStartingPoints(String json) throws IOException { + try (JsonReader reader = JsonReader.fromString(json)) { + assertThrows(IllegalStateException.class, () -> JsonNull.fromJson(reader)); + } + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/models/JsonNumberTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/models/JsonNumberTests.java new file mode 100644 index 000000000000..2141126c2b5a --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/models/JsonNumberTests.java @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.serialization.json.models; + +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonWriter; +import io.clientcore.core.serialization.json.implementation.StringBuilderWriter; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.io.IOException; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.text.ParseException; +import java.util.stream.Stream; + +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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Tests {@link JsonNumber}. + */ +public class JsonNumberTests { + @Test + public void kindCheck() { + JsonElement element = new JsonNumber(0); + assertTrue(element.isNumber()); + assertFalse(element.isArray()); + assertFalse(element.isObject()); + assertFalse(element.isString()); + assertFalse(element.isBoolean()); + assertFalse(element.isNull()); + } + + @ParameterizedTest + @MethodSource("fromJsonSupplier") + public void fromJson(String json, Number number) throws IOException, ParseException { + try (JsonReader reader = JsonReader.fromString(json)) { + JsonNumber jsonNumber = JsonNumber.fromJson(reader); + if (number instanceof BigInteger) { + BigInteger jsonBigInteger = assertInstanceOf(BigInteger.class, jsonNumber.getValue()); + assertEquals(0, ((BigInteger) number).compareTo(jsonBigInteger)); + } else if (number instanceof BigDecimal) { + BigDecimal jsonBigDecimal = assertInstanceOf(BigDecimal.class, jsonNumber.getValue()); + assertEquals(0, ((BigDecimal) number).compareTo(jsonBigDecimal)); + } else { + assertEquals(number, jsonNumber.getValue()); + } + } + } + + private static Stream fromJsonSupplier() { + return Stream.of(Arguments.of("0", 0), Arguments.of("-1", -1), Arguments.of("10000000000", 10000000000L), + Arguments.of("-10000000000", -10000000000L), + Arguments.of("100000000000000000000", new BigInteger("100000000000000000000")), + Arguments.of("-100000000000000000000", new BigInteger("-100000000000000000000")), Arguments.of("0.0", 0.0D), + Arguments.of("-1.0", -1.0D), Arguments.of("1E6", 1E6D), Arguments.of("-1E6", -1E6D), + Arguments.of("1.0E6", 1E6D), Arguments.of("-1.0E6", -1E6D), Arguments.of("1e6", 1E6D), + Arguments.of("-1e6", -1E6D), Arguments.of("1.0e6", 1E6D), Arguments.of("-1.0e6", -1E6D), + Arguments.of("1E39", 1E39D), Arguments.of("-1E39", -1E39D), Arguments.of("1.0E39", 1E39D), + Arguments.of("-1.0E39", -1E39D), Arguments.of("1e39", 1E39D), Arguments.of("-1e39", -1E39D), + Arguments.of("1.0e39", 1E39D), Arguments.of("-1.0e39", -1E39D), + Arguments.of("1E309", new BigDecimal("1E309")), Arguments.of("-1E309", new BigDecimal("-1E309")), + Arguments.of("1.0E309", new BigDecimal("1E309")), Arguments.of("-1.0E309", new BigDecimal("-1E309")), + Arguments.of("1e309", new BigDecimal("1E309")), Arguments.of("-1e309", new BigDecimal("-1E309")), + Arguments.of("1.0e309", new BigDecimal("1E309")), Arguments.of("-1.0e309", new BigDecimal("-1E309")), + Arguments.of("Infinity", Double.POSITIVE_INFINITY), Arguments.of("-Infinity", Double.NEGATIVE_INFINITY)); + } + + @ParameterizedTest + @MethodSource("toJsonSupplier") + public void toJson(Number value) throws IOException { + JsonNumber jsonNumber = new JsonNumber(value); + try (StringBuilderWriter writer = new StringBuilderWriter()) { + try (JsonWriter jsonWriter = JsonWriter.toWriter(writer)) { + jsonNumber.toJson(jsonWriter); + } + assertEquals(String.valueOf(value), writer.toString()); + } + } + + private static Stream toJsonSupplier() { + return Stream.of(0, -1, 0.0, -1.0, 1E6, -1E6, 1.0E6, -1.0E6); + } + + @ParameterizedTest + @ValueSource(strings = { "true", "null", "\"hello\"", "[]", "{}" }) + public void invalidFromJsonStartingPoints(String json) throws IOException { + try (JsonReader reader = JsonReader.fromString(json)) { + assertThrows(IllegalStateException.class, () -> JsonNumber.fromJson(reader)); + } + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/models/JsonObjectTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/models/JsonObjectTests.java new file mode 100644 index 000000000000..c1ca1bdc6100 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/models/JsonObjectTests.java @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.serialization.json.models; + +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonWriter; +import io.clientcore.core.serialization.json.implementation.StringBuilderWriter; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Tests {@link JsonObject}. + */ +public class JsonObjectTests { + @Test + public void kindCheck() { + JsonElement element = new JsonObject(); + assertTrue(element.isObject()); + assertFalse(element.isArray()); + assertFalse(element.isNumber()); + assertFalse(element.isString()); + assertFalse(element.isBoolean()); + assertFalse(element.isNull()); + } + + @Test + public void emptyObjectFromJson() throws IOException { + String json = "{}"; + try (JsonReader reader = JsonReader.fromString(json)) { + JsonObject jsonObject = JsonObject.fromJson(reader); + assertEquals(0, jsonObject.size()); + } + } + + @Test + public void objectOfBasicTypesFromJson() throws IOException { + String json = "{\"string\":\"string\",\"null\":null,\"integer\":10,\"float\":10.0,\"boolean\":true}"; + try (JsonReader reader = JsonReader.fromString(json)) { + JsonObject jsonObject = JsonObject.fromJson(reader); + assertEquals(5, jsonObject.size()); + + JsonElement stringElement = jsonObject.getProperty("string"); + assertTrue(stringElement.isString()); + assertEquals("\"string\"", stringElement.toJsonString()); + + JsonElement nullElement = jsonObject.getProperty("null"); + assertTrue(nullElement.isNull()); + + JsonElement intElement = jsonObject.getProperty("integer"); + assertTrue(intElement.isNumber()); + assertEquals("10", intElement.toJsonString()); + + JsonElement doubleElement = jsonObject.getProperty("float"); + assertTrue(doubleElement.isNumber()); + assertEquals("10.0", doubleElement.toJsonString()); + + JsonElement booleanElement = jsonObject.getProperty("boolean"); + assertTrue(booleanElement.isBoolean()); + assertEquals("true", booleanElement.toJsonString()); + + assertEquals(json, jsonObject.toJsonString()); + + assertEquals("\"string\"", jsonObject.removeProperty("string").toJsonString()); + assertEquals(4, jsonObject.size()); + assertNull(jsonObject.removeProperty("string")); + assertEquals("{\"null\":null,\"integer\":10,\"float\":10.0,\"boolean\":true}", jsonObject.toJsonString()); + } + } + + @Test + public void emptyObjectToJson() throws IOException { + JsonObject jsonObject = new JsonObject(); + assertEquals(0, jsonObject.size()); + + try (StringBuilderWriter writer = new StringBuilderWriter(); + JsonWriter jsonWriter = JsonWriter.toWriter(writer)) { + jsonObject.toJson(jsonWriter); + jsonWriter.flush(); + + assertEquals("{}", writer.toString()); + } + } + + @Test + public void objectOfBasicTypesToJson() throws IOException { + JsonObject jsonObject = new JsonObject().setProperty("string", new JsonString("string")) + .setProperty("null", JsonNull.getInstance()) + .setProperty("integer", new JsonNumber(10)) + .setProperty("float", new JsonNumber(10.0D)) + .setProperty("boolean", JsonBoolean.getInstance(true)); + + assertEquals(5, jsonObject.size()); + + try (StringBuilderWriter writer = new StringBuilderWriter(); + JsonWriter jsonWriter = JsonWriter.toWriter(writer)) { + jsonObject.toJson(jsonWriter); + jsonWriter.flush(); + + assertEquals("{\"string\":\"string\",\"null\":null,\"integer\":10,\"float\":10.0,\"boolean\":true}", + writer.toString()); + } + } + + @ParameterizedTest + @ValueSource(strings = { "true", "null", "1", "1.0", "\"hello\"", "[]" }) + public void invalidFromJsonStartingPoints(String json) throws IOException { + try (JsonReader reader = JsonReader.fromString(json)) { + assertThrows(IllegalStateException.class, () -> JsonObject.fromJson(reader)); + } + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/models/JsonPatchDocumentTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/models/JsonPatchDocumentTests.java new file mode 100644 index 000000000000..dc43214eb15b --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/models/JsonPatchDocumentTests.java @@ -0,0 +1,205 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.serialization.json.models; + +import io.clientcore.core.serialization.json.JsonSerializer; +import org.junit.jupiter.api.function.Executable; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.util.Collections; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * Tests {@link JsonPatchDocument}. + */ +public class JsonPatchDocumentTests { + private static final JsonSerializer JSON_SERIALIZER = new JsonSerializer(); + + @ParameterizedTest + @MethodSource("formattingSupplier") + public void toStringTest(JsonPatchDocument document, String expected) { + assertEquals(expected, document.toString()); + } + + @ParameterizedTest + @MethodSource("formattingSupplier") + public void jsonifyDocument(JsonPatchDocument document, String expected) throws IOException { + assertEquals(expected, document.toJsonString().replace(" ", "")); + } + + @ParameterizedTest + @MethodSource("formattingSupplier") + public void jsonifyOperations(JsonPatchDocument document, String expected) throws IOException { + assertEquals(expected, document.toJsonString().replace(" ", "")); + } + + private static Stream formattingSupplier() throws IOException { + JsonPatchDocument complexDocument = newDocument().appendTest("/a/b/c", "foo") + .appendRemove("/a/b/c") + .appendAdd("/a/b/c", new String[] { "foo", "bar" }) + .appendReplace("/a/b/c", 42) + .appendMove("/a/b/c", "/a/b/d") + .appendCopy("/a/b/d", "/a/b/e"); + + JsonPatchDocument complexDocumentRaw = newDocument().appendTestRaw("/a/b/c", "\"foo\"") + .appendRemove("/a/b/c") + .appendAddRaw("/a/b/c", "[\"foo\",\"bar\"]") + .appendReplaceRaw("/a/b/c", "42") + .appendMove("/a/b/c", "/a/b/d") + .appendCopy("/a/b/d", "/a/b/e"); + + String complexExpected = "[" + "{\"op\":\"test\",\"path\":\"/a/b/c\",\"value\":\"foo\"}," + + "{\"op\":\"remove\",\"path\":\"/a/b/c\"}," + + "{\"op\":\"add\",\"path\":\"/a/b/c\",\"value\":[\"foo\",\"bar\"]}," + + "{\"op\":\"replace\",\"path\":\"/a/b/c\",\"value\":42}," + + "{\"op\":\"move\",\"from\":\"/a/b/c\",\"path\":\"/a/b/d\"}," + + "{\"op\":\"copy\",\"from\":\"/a/b/d\",\"path\":\"/a/b/e\"}" + "]"; + + return Stream.of( + Arguments.of(newDocument().appendAdd("/baz", "qux"), + constructExpectedOperation("add", null, "/baz", "qux")), + + Arguments.of(newDocument().appendAdd("/foo/1", "qux"), + constructExpectedOperation("add", null, "/foo/1", "qux")), + + Arguments.of( + newDocument().appendAdd("/child", Collections.singletonMap("grandchild", Collections.emptyMap())), + constructExpectedOperation("add", null, "/child", "{\"grandchild\":{}}", false)), + + Arguments.of(newDocument().appendAdd("/foo/-", new String[] { "abc", "def" }), + constructExpectedOperation("add", null, "/foo/-", "[\"abc\",\"def\"]", false)), + + Arguments.of(newDocument().appendAddRaw("/baz", "\"qux\""), + constructExpectedOperation("add", null, "/baz", "qux")), + + Arguments.of(newDocument().appendAddRaw("/foo/1", "\"qux\""), + constructExpectedOperation("add", null, "/foo/1", "qux")), + + Arguments.of(newDocument().appendAddRaw("/child", "{\"grandchild\":{}}"), + constructExpectedOperation("add", null, "/child", "{\"grandchild\":{}}", false)), + + Arguments.of(newDocument().appendAddRaw("/foo/-", "[\"abc\",\"def\"]"), + constructExpectedOperation("add", null, "/foo/-", "[\"abc\",\"def\"]", false)), + + Arguments.of(newDocument().appendReplace("/bar", "foo"), + constructExpectedOperation("replace", null, "/bar", "foo")), + + Arguments.of(newDocument().appendReplace("/foo", new String[] { "fizz", "buzz", "fizzbuzz" }), + constructExpectedOperation("replace", null, "/foo", "[\"fizz\",\"buzz\",\"fizzbuzz\"]", false)), + + Arguments.of(newDocument().appendReplace("/baz", "foo"), + constructExpectedOperation("replace", null, "/baz", "foo")), + + Arguments.of(newDocument().appendReplaceRaw("/bar", "\"foo\""), + constructExpectedOperation("replace", null, "/bar", "foo")), + + Arguments.of(newDocument().appendReplaceRaw("/foo", "[\"fizz\",\"buzz\",\"fizzbuzz\"]"), + constructExpectedOperation("replace", null, "/foo", "[\"fizz\",\"buzz\",\"fizzbuzz\"]", false)), + + Arguments.of(newDocument().appendReplaceRaw("/baz", "\"foo\""), + constructExpectedOperation("replace", null, "/baz", "foo")), + + Arguments.of(newDocument().appendCopy("/foo", "/copy"), + constructExpectedOperation("copy", "/foo", "/copy", null)), + + Arguments.of(newDocument().appendCopy("/foo/bar", "/bar"), + constructExpectedOperation("copy", "/foo/bar", "/bar", null)), + + Arguments.of(newDocument().appendCopy("/baz", "/fizz"), + constructExpectedOperation("copy", "/baz", "/fizz", null)), + + Arguments.of(newDocument().appendMove("/foo", "/bar"), + constructExpectedOperation("move", "/foo", "/bar", null)), + + Arguments.of(newDocument().appendMove("/foo/bar", "/foo"), + constructExpectedOperation("move", "/foo/bar", "/foo", null)), + + Arguments.of(newDocument().appendMove("/foo", "/foo/bar"), + constructExpectedOperation("move", "/foo", "/foo/bar", null)), + + Arguments.of(newDocument().appendMove("/baz", "/fizz"), + constructExpectedOperation("move", "/baz", "/fizz", null)), + + Arguments.of(newDocument().appendRemove("/bar"), constructExpectedOperation("remove", null, "/bar", null)), + + Arguments.of(newDocument().appendRemove("/foo/bar"), + constructExpectedOperation("remove", null, "/foo/bar", null)), + + Arguments.of(newDocument().appendRemove("/baz"), constructExpectedOperation("remove", null, "/baz", null)), + + Arguments.of(newDocument().appendTest("/foo", "bar"), + constructExpectedOperation("test", null, "/foo", "bar")), + + Arguments.of(newDocument().appendTest("/foo", 42), + constructExpectedOperation("test", null, "/foo", "42", false)), + + Arguments.of(newDocument().appendTest("/baz", "bar"), + constructExpectedOperation("test", null, "/baz", "bar")), + + Arguments.of(newDocument().appendTestRaw("/foo", "\"bar\""), + constructExpectedOperation("test", null, "/foo", "bar")), + + Arguments.of(newDocument().appendTestRaw("/foo", "42"), + constructExpectedOperation("test", null, "/foo", "42", false)), + + Arguments.of(newDocument().appendTestRaw("/baz", "\"bar\""), + constructExpectedOperation("test", null, "/baz", "bar")), + + Arguments.of(complexDocument, complexExpected), + + Arguments.of(complexDocumentRaw, complexExpected)); + } + + private static String constructExpectedOperation(String op, String from, String path, String value) { + return constructExpectedOperation(op, from, path, value, true); + } + + private static String constructExpectedOperation(String op, String from, String path, String value, + boolean quoteValue) { + StringBuilder builder = new StringBuilder("[{\"op\":\"").append(op).append("\""); + + if (from != null) { + builder.append(",\"from\":\"").append(from).append("\""); + } + + builder.append(",\"path\":\"").append(path).append("\""); + + if (value != null) { + builder.append(",\"value\":").append(quoteValue ? "\"" : "").append(value).append(quoteValue ? "\"" : ""); + } + + return builder.append("}]").toString(); + } + + @ParameterizedTest + @MethodSource("invalidArgumentSupplier") + public void invalidArgument(Executable runnable) { + assertThrows(NullPointerException.class, runnable); + } + + private static Stream invalidArgumentSupplier() { + JsonPatchDocument document = newDocument(); + return Stream.of(() -> document.appendAdd(null, "\"bar\""), + + () -> document.appendReplace(null, "\"bar\""), + + () -> document.appendCopy(null, "\"bar\""), () -> document.appendCopy("/foo", null), + + () -> document.appendMove(null, "\"bar\""), () -> document.appendMove("/foo", null), + + () -> document.appendRemove(null), + + () -> document.appendTest(null, "\"bar\"")); + } + + private static JsonPatchDocument newDocument() { + return new JsonPatchDocument(JSON_SERIALIZER); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/models/JsonStringTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/models/JsonStringTests.java new file mode 100644 index 000000000000..ea0b56c1ce4a --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/serialization/json/models/JsonStringTests.java @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.serialization.json.models; + +import io.clientcore.core.serialization.json.JsonOptions; +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonWriter; +import io.clientcore.core.serialization.json.implementation.StringBuilderWriter; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Tests {@link JsonString}. + */ +public class JsonStringTests { + @Test + public void kindCheck() { + JsonElement element = new JsonString(""); + assertTrue(element.isString()); + assertFalse(element.isArray()); + assertFalse(element.isObject()); + assertFalse(element.isNumber()); + assertFalse(element.isBoolean()); + assertFalse(element.isNull()); + } + + @ParameterizedTest + @ValueSource(strings = { "\"\"", "\"hello\"" }) + public void fromJson(String json) throws IOException { + try (JsonReader reader = JsonReader.fromString(json)) { + JsonString jsonString = JsonString.fromJson(reader); + assertEquals(json, jsonString.toJsonString()); + assertEquals(json.substring(1, json.length() - 1), jsonString.getValue()); + } + } + + @Test + public void toJsonStringCachesValue() throws IOException { + JsonString jsonString = new JsonString("hello"); + String json = jsonString.toJsonString(); + assertEquals("\"hello\"", json); + assertSame(json, jsonString.toJsonString()); + } + + @ParameterizedTest + @ValueSource(strings = { "", "hello" }) + public void toJson(String value) throws IOException { + JsonString jsonString = new JsonString(value); + try (StringBuilderWriter writer = new StringBuilderWriter()) { + try (JsonWriter jsonWriter = JsonWriter.toWriter(writer)) { + jsonString.toJson(jsonWriter); + } + assertEquals("\"" + value + "\"", writer.toString()); + } + } + + @ParameterizedTest + @ValueSource(strings = { "true", "null", "1", "1.0", "[]", "{}" }) + public void invalidFromJsonStartingPoints(String json) throws IOException { + try (JsonReader reader = JsonReader.fromString(json, new JsonOptions())) { + assertThrows(IllegalStateException.class, () -> JsonString.fromJson(reader)); + } + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/shared/HttpClientTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/shared/HttpClientTests.java index 5fab3a5472d6..b46df0c3722d 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/shared/HttpClientTests.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/shared/HttpClientTests.java @@ -3,42 +3,39 @@ package io.clientcore.core.shared; -import io.clientcore.core.annotation.ServiceInterface; +import io.clientcore.core.annotations.ServiceInterface; import io.clientcore.core.http.RestProxy; -import io.clientcore.core.http.annotation.BodyParam; -import io.clientcore.core.http.annotation.HeaderParam; -import io.clientcore.core.http.annotation.HostParam; -import io.clientcore.core.http.annotation.HttpRequestInformation; -import io.clientcore.core.http.annotation.PathParam; -import io.clientcore.core.http.annotation.QueryParam; -import io.clientcore.core.http.annotation.UnexpectedResponseExceptionDetail; +import io.clientcore.core.http.annotations.BodyParam; +import io.clientcore.core.http.annotations.HeaderParam; +import io.clientcore.core.http.annotations.HostParam; +import io.clientcore.core.http.annotations.HttpRequestInformation; +import io.clientcore.core.http.annotations.PathParam; +import io.clientcore.core.http.annotations.QueryParam; +import io.clientcore.core.http.annotations.UnexpectedResponseExceptionDetail; import io.clientcore.core.http.client.HttpClient; -import io.clientcore.core.http.exception.HttpResponseException; -import io.clientcore.core.http.models.ContentType; import io.clientcore.core.http.models.HttpHeader; import io.clientcore.core.http.models.HttpHeaderName; import io.clientcore.core.http.models.HttpHeaders; -import io.clientcore.core.http.models.HttpLogOptions; import io.clientcore.core.http.models.HttpMethod; import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.HttpResponseException; import io.clientcore.core.http.models.RequestOptions; import io.clientcore.core.http.models.Response; import io.clientcore.core.http.models.ResponseBodyMode; import io.clientcore.core.http.models.ServerSentEvent; import io.clientcore.core.http.models.ServerSentEventListener; +import io.clientcore.core.http.pipeline.HttpInstrumentationOptions; +import io.clientcore.core.http.pipeline.HttpInstrumentationPolicy; import io.clientcore.core.http.pipeline.HttpPipeline; import io.clientcore.core.http.pipeline.HttpPipelineBuilder; -import io.clientcore.core.http.pipeline.HttpInstrumentationPolicy; -import io.clientcore.core.implementation.util.UriBuilder; +import io.clientcore.core.implementation.http.ContentType; import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.util.Context; -import io.clientcore.core.util.binarydata.BinaryData; -import io.clientcore.core.util.binarydata.ByteArrayBinaryData; -import io.clientcore.core.util.binarydata.ByteBufferBinaryData; -import io.clientcore.core.util.binarydata.InputStreamBinaryData; -import io.clientcore.core.implementation.util.JsonSerializer; -import io.clientcore.core.util.serializer.ObjectSerializer; -import io.clientcore.core.util.serializer.SerializationFormat; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.serialization.ObjectSerializer; +import io.clientcore.core.serialization.SerializationFormat; +import io.clientcore.core.serialization.json.JsonSerializer; +import io.clientcore.core.utils.Context; +import io.clientcore.core.utils.UriBuilder; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Named; import org.junit.jupiter.api.Test; @@ -79,7 +76,7 @@ import static io.clientcore.core.http.models.ResponseBodyMode.DESERIALIZE; import static io.clientcore.core.http.models.ResponseBodyMode.IGNORE; import static io.clientcore.core.http.models.ResponseBodyMode.STREAM; -import static io.clientcore.core.implementation.util.ImplUtils.bomAwareToString; +import static io.clientcore.core.implementation.utils.ImplUtils.bomAwareToString; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -262,11 +259,12 @@ public void bomWithDifferentHeader() throws IOException { @Test public void canAccessResponseBody() throws IOException { BinaryData requestBody = BinaryData.fromString("test body"); - HttpRequest request = new HttpRequest(HttpMethod.PUT, getRequestUri(ECHO_RESPONSE)).setBody(requestBody); + HttpRequest request + = new HttpRequest().setMethod(HttpMethod.PUT).setUri(getRequestUri(ECHO_RESPONSE)).setBody(requestBody); - try (Response response = getHttpClient().send(request)) { - assertEquals(requestBody.toString(), response.getBody().toString()); - assertArrayEquals(requestBody.toBytes(), response.getBody().toBytes()); + try (Response response = getHttpClient().send(request)) { + assertEquals(requestBody.toString(), response.getValue().toString()); + assertArrayEquals(requestBody.toBytes(), response.getValue().toBytes()); } } @@ -276,22 +274,18 @@ public void canAccessResponseBody() throws IOException { @Test public void bufferedResponseCanBeReadMultipleTimes() throws IOException { BinaryData requestBody = BinaryData.fromString("test body"); - HttpRequest request = new HttpRequest(HttpMethod.PUT, getRequestUri(ECHO_RESPONSE)).setBody(requestBody) + HttpRequest request = new HttpRequest().setMethod(HttpMethod.PUT) + .setUri(getRequestUri(ECHO_RESPONSE)) + .setBody(requestBody) .setRequestOptions(new RequestOptions().setResponseBodyMode(DESERIALIZE)); - try (Response response = getHttpClient().send(request)) { + try (Response response = getHttpClient().send(request)) { // Read response twice using all accessors. - assertEquals(requestBody.toString(), response.getBody().toString()); - assertEquals(requestBody.toString(), response.getBody().toString()); - - assertArrayEquals(requestBody.toBytes(), response.getBody().toBytes()); - assertArrayEquals(requestBody.toBytes(), response.getBody().toBytes()); + assertEquals(requestBody.toString(), response.getValue().toString()); + assertEquals(requestBody.toString(), response.getValue().toString()); - assertArrayEquals(requestBody.toBytes(), response.getBody().toBytes()); - assertArrayEquals(requestBody.toBytes(), response.getBody().toBytes()); - - assertArrayEquals(requestBody.toBytes(), response.getBody().toBytes()); - assertArrayEquals(requestBody.toBytes(), response.getBody().toBytes()); + assertArrayEquals(requestBody.toBytes(), response.getValue().toBytes()); + assertArrayEquals(requestBody.toBytes(), response.getValue().toBytes()); } } @@ -304,10 +298,11 @@ public void bufferedResponseCanBeReadMultipleTimes() throws IOException { @ParameterizedTest @MethodSource("getBinaryDataBodyVariants") public void canSendBinaryData(BinaryData requestBody, byte[] expectedResponseBody) throws IOException { - HttpRequest request = new HttpRequest(HttpMethod.PUT, getRequestUri(ECHO_RESPONSE)).setBody(requestBody); + HttpRequest request + = new HttpRequest().setMethod(HttpMethod.PUT).setUri(getRequestUri(ECHO_RESPONSE)).setBody(requestBody); - try (Response response = getHttpClient().send(request)) { - assertArrayEquals(expectedResponseBody, response.getBody().toBytes()); + try (Response response = getHttpClient().send(request)) { + assertArrayEquals(expectedResponseBody, response.getValue().toBytes()); } } @@ -387,8 +382,9 @@ private static Stream getBinaryDataBodyVariants() { } private byte[] sendRequest(String requestPath) throws IOException { - try (Response response = getHttpClient().send(new HttpRequest(HttpMethod.GET, getRequestUri(requestPath)))) { - return response.getBody().toBytes(); + try (Response response + = getHttpClient().send(new HttpRequest().setMethod(HttpMethod.GET).setUri(getRequestUri(requestPath)))) { + return response.getValue().toBytes(); } } @@ -1385,7 +1381,7 @@ public void service20GetVoidResponseBuffersBody() { assertNotNull(response); assertEquals(200, response.getStatusCode()); - assertNotEquals(0, response.getBody().getLength()); + assertNull(response.getValue()); } @Test @@ -1445,8 +1441,6 @@ interface DownloadService { public void simpleDownloadTest(Context context) throws IOException { Response response = createService(DownloadService.class).getBytes(getRequestUri(), context); - assertTrue(response.getBody() instanceof InputStreamBinaryData); - InputStream inputStream = response.getValue(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); @@ -1456,8 +1450,6 @@ public void simpleDownloadTest(Context context) throws IOException { Response otherResponse = createService(DownloadService.class).getBytes(getRequestUri(), context); - assertTrue(otherResponse.getBody() instanceof InputStreamBinaryData); - InputStream otherInputStream = otherResponse.getValue(); ByteArrayOutputStream otherByteArrayOutputStream = new ByteArrayOutputStream(); @@ -1492,8 +1484,8 @@ public void binaryDataUploadTest() throws Exception { // Order in which policies applied will be the order in which they added to builder final HttpPipeline httpPipeline = new HttpPipelineBuilder().httpClient(httpClient) - .policies(new HttpInstrumentationPolicy(null, - new HttpLogOptions().setLogLevel(HttpLogOptions.HttpLogDetailLevel.BODY_AND_HEADERS))) + .addPolicy(new HttpInstrumentationPolicy(new HttpInstrumentationOptions() + .setHttpLogLevel(HttpInstrumentationOptions.HttpLogLevel.BODY_AND_HEADERS))) .build(); Response response @@ -1753,8 +1745,8 @@ public void canRecognizeServerSentEvent() throws IOException { try (Response response = service.post(getServerUri(isSecure()), requestBody, sse -> assertEquals(expected, sse.getData()), null)) { - assertNotNull(response.getBody()); - assertNotEquals(0, response.getBody().getLength()); + assertNotNull(response.getValue()); + assertNotEquals(0, response.getValue().getLength()); assertNotNull(response.getValue()); assertEquals(String.join("\n", expected), response.getValue().toString()); } @@ -1829,8 +1821,8 @@ public void bodyIsDeserializedForServerSentEventType(String responseMode) throws try (Response response = service.post(getServerUri(isSecure()), BinaryData.empty(), sse -> assertEquals(expected, sse.getData()), requestOptions)) { - assertNotNull(response.getBody()); - assertNotEquals(0, response.getBody().getLength()); + assertNotNull(response.getValue()); + assertNotEquals(0, response.getValue().getLength()); assertNotNull(response.getValue()); assertEquals(String.join("\n", expected), response.getValue().toString()); } @@ -1884,8 +1876,6 @@ public void bodyIsPresentWhenNoBodyHandlingOptionIsSet() throws IOException { assertNotNull(httpBinJSON); try (Response response = service.putResponse(getServerUri(isSecure()), 42, null)) { - assertNotNull(response.getBody()); - assertNotEquals(0, response.getBody().getLength()); assertNotNull(response.getValue()); } } @@ -1899,8 +1889,6 @@ public void bodyIsEmptyWhenIgnoreBodyIsSet() throws IOException { assertNull(httpBinJSON); try (Response response = service.putResponse(getServerUri(isSecure()), 42, requestOptions)) { - assertNotNull(response.getBody()); - assertEquals(0, response.getBody().getLength()); assertNull(response.getValue()); } } @@ -1915,8 +1903,6 @@ public void bodyIsEmptyWhenIgnoreBodyIsSetForStreamResponse() throws IOException try ( Response response = service.postStreamResponse(getServerUri(isSecure()), 42, requestOptions)) { - assertNotNull(response.getBody()); - assertEquals(0, response.getBody().getLength()); assertNull(response.getValue()); } } @@ -1925,13 +1911,6 @@ public void bodyIsEmptyWhenIgnoreBodyIsSetForStreamResponse() throws IOException public void bodyIsStreamedWhenResponseBodyModeIndicatesIt() throws IOException { Service30 service = createService(Service30.class); RequestOptions requestOptions = new RequestOptions().setResponseBodyMode(STREAM); - - try ( - Response response = service.postStreamResponse(getServerUri(isSecure()), 42, requestOptions)) { - assertNotNull(response.getBody()); - assertNotEquals(0, response.getBody().getLength()); - assertTrue(response.getBody() instanceof InputStreamBinaryData); - } } @Test @@ -1941,14 +1920,6 @@ public void bodyIsBufferedWhenResponseBodyModeIndicatesIt() throws IOException { HttpBinJSON httpBinJSON = service.postStream(getServerUri(isSecure()), 42, requestOptions); assertNotNull(httpBinJSON); - - try ( - Response response = service.postStreamResponse(getServerUri(isSecure()), 42, requestOptions)) { - assertNotNull(response.getBody()); - assertNotEquals(0, response.getBody().getLength()); - assertTrue(response.getBody() instanceof ByteArrayBinaryData - || response.getBody() instanceof ByteBufferBinaryData); - } } @Test @@ -1961,8 +1932,6 @@ public void bodyIsDeserializedWhenResponseBodyModeIndicatesIt() throws IOExcepti try ( Response response = service.postStreamResponse(getServerUri(isSecure()), 42, requestOptions)) { - assertNotNull(response.getBody()); - assertNotEquals(0, response.getBody().getLength()); assertNotNull(response.getValue()); } } diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/shared/HttpClientTestsServer.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/shared/HttpClientTestsServer.java index 1cb4e36a64d1..2b5743a9edb7 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/shared/HttpClientTestsServer.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/shared/HttpClientTestsServer.java @@ -4,10 +4,9 @@ package io.clientcore.core.shared; import io.clientcore.core.http.client.HttpClient; -import io.clientcore.core.http.models.ContentType; -import io.clientcore.core.implementation.util.DateTimeRfc1123; -import io.clientcore.core.implementation.util.JsonSerializer; -import io.clientcore.core.util.serializer.ObjectSerializer; +import io.clientcore.core.implementation.http.ContentType; +import io.clientcore.core.serialization.json.JsonSerializer; +import io.clientcore.core.utils.DateTimeRfc1123; import org.eclipse.jetty.server.Response; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; @@ -29,14 +28,14 @@ import java.util.Map; import java.util.concurrent.ThreadLocalRandom; -import static io.clientcore.core.implementation.util.ImplUtils.isNullOrEmpty; +import static io.clientcore.core.utils.CoreUtils.isNullOrEmpty; /** * Server used when running {@link HttpClient tests}. */ @Execution(ExecutionMode.SAME_THREAD) public class HttpClientTestsServer { - private static final ObjectSerializer SERIALIZER = new JsonSerializer(); + private static final JsonSerializer SERIALIZER = new JsonSerializer(); private static final String PLAIN_RESPONSE = "/plainBytesNoHeader"; private static final String HEADER_RESPONSE = "/plainBytesWithHeader"; private static final String INVALID_HEADER_RESPONSE = "/plainBytesInvalidHeader"; diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/shared/TestConfigurationSource.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/shared/TestConfigurationSource.java index 51ae8a2c66a4..f84d79b44696 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/shared/TestConfigurationSource.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/shared/TestConfigurationSource.java @@ -3,14 +3,14 @@ package io.clientcore.core.shared; -import io.clientcore.core.util.configuration.ConfigurationSource; +import io.clientcore.core.utils.configuration.ConfigurationSource; import java.util.HashMap; import java.util.Map; -import java.util.stream.Collectors; +import java.util.Objects; public class TestConfigurationSource implements ConfigurationSource { - private Map testData; + private final Map testData; public TestConfigurationSource() { this.testData = new HashMap<>(); @@ -22,13 +22,13 @@ public TestConfigurationSource put(String key, String value) { } @Override - public Map getProperties(String path) { - if (path == null) { - return testData; - } - return testData.entrySet() - .stream() - .filter(prop -> prop.getKey().startsWith(path + ".")) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + public String getProperty(String name) { + Objects.requireNonNull(name, "'name' cannot be null."); + return testData.get(name); + } + + @Override + public boolean isMutable() { + return true; } } diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/util/TestUtils.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/util/TestUtils.java deleted file mode 100644 index 27b0cbdbf125..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/util/TestUtils.java +++ /dev/null @@ -1,204 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.util; - -import io.clientcore.core.implementation.AccessibleByteArrayOutputStream; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.ByteBuffer; -import java.security.SecureRandom; -import java.util.Arrays; -import java.util.Objects; - -import static io.clientcore.core.implementation.util.ImplUtils.isNullOrEmpty; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; - -/** - * Utility methods for testing {@code core}. - */ -public final class TestUtils { - private static final byte[] BYTES; - private static final int BYTES_LENGTH; - - static { - BYTES = new byte[1024 * 1024]; - - new SecureRandom().nextBytes(BYTES); - - BYTES_LENGTH = BYTES.length; - } - - /** - * Asserts that two arrays are equal in an optimized way when they are equal (common case). - * - * @param expected Expected array. - * @param actual Actual array. - */ - public static void assertArraysEqual(byte[] expected, byte[] actual) { - assertArraysEqual(expected, 0, expected.length, actual, actual.length); - } - - /** - * Asserts that two arrays are equal in an optimized way when they are equal (common case). - * - * @param expected Expected array. - * @param expectedOffset Offset to begin comparing in the expected array. - * @param expectedLength Amount of bytes to compare in the expected array. - * @param actual Actual array. - */ - public static void assertArraysEqual(byte[] expected, int expectedOffset, int expectedLength, byte[] actual) { - assertArraysEqual(expected, expectedOffset, expectedLength, actual, actual.length); - } - - /** - * Asserts that two arrays are equal in an optimized way when they are equal (common case). - * - * @param expected Expected array. - * @param expectedOffset Offset to begin comparing in the expected array. - * @param expectedLength Amount of bytes to compare in the expected array. - * @param actual Actual array. - * @param actualLength Amount of bytes to compare in the actual array. - */ - public static void assertArraysEqual(byte[] expected, int expectedOffset, int expectedLength, byte[] actual, - int actualLength) { - - if (!Objects.equals(ByteBuffer.wrap(expected, expectedOffset, expectedLength), - ByteBuffer.wrap(actual, 0, actualLength))) { - - assertArrayEquals(Arrays.copyOfRange(expected, expectedOffset, expectedOffset + expectedLength), - Arrays.copyOfRange(actual, 0, actualLength)); - } - } - - /** - * Fills the passed byte array with random bytes. - * - * @param array The array to fill. - */ - public static void fillArray(byte[] array) { - int size = array.length; - int count = size / BYTES_LENGTH; - int remainder = size % BYTES_LENGTH; - - for (int i = 0; i < count; i++) { - System.arraycopy(BYTES, 0, array, i * BYTES_LENGTH, BYTES_LENGTH); - } - - if (remainder > 0) { - System.arraycopy(BYTES, 0, array, count * BYTES_LENGTH, remainder); - } - } - - /** - * Reads an {@link InputStream} to completion returning its contents, using a read buffer. - * - * @param stream The stream to read. - * - * @return The byte array representing its contents. - * - * @throws IOException If an error happens during reading. - */ - public static byte[] readStream(InputStream stream) throws IOException { - return readStream(stream, 8 * 1024); - } - - /** - * Reads an {@link InputStream} to completion returning its contents, using a read buffer. - * - * @param stream The stream to read. - * @param bufferSize The size of the read buffer. - * - * @return The byte array representing its contents. - * - * @throws IOException If an error happens during reading. - */ - public static byte[] readStream(InputStream stream, int bufferSize) throws IOException { - AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(); - byte[] buffer = new byte[bufferSize]; - int length; - - while ((length = stream.read(buffer)) != -1) { - outputStream.write(buffer, 0, length); - } - - return outputStream.toByteArray(); - } - - /** - * Reads an {@link InputStream} to completion returning its contents, reading byte by byte. - * - * @param stream The stream to read. - * - * @return The byte array representing its contents. - * - * @throws IOException If an error happens during reading. - */ - public static byte[] readStreamByteByByte(InputStream stream) throws IOException { - AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(); - byte[] buffer = new byte[8192]; - int bufferPosition = 0; - int tmp; - - while ((tmp = stream.read()) != -1) { - if (bufferPosition >= 8192) { - outputStream.write(buffer); - bufferPosition = 0; - } - - buffer[bufferPosition++] = (byte) tmp; - } - - if (bufferPosition > 0) { - outputStream.write(buffer, 0, bufferPosition); - } - - return outputStream.toByteArray(); - } - - private TestUtils() { - } - - /** - * Creates a copy of the source byte array. - * - * @param source Array to make copy of. - * - * @return A copy of the array, or null if source was null. - */ - public static byte[] cloneByteArray(byte[] source) { - if (source == null) { - return null; - } - - byte[] copy = new byte[source.length]; - - System.arraycopy(source, 0, copy, 0, source.length); - - return copy; - } - - /** - * Returns the first instance of the given class from an array of Objects. - * - * @param args Array of objects to search through to find the first instance of the given `clazz` type. - * @param clazz The type trying to be found. - * @param Generic type - * - * @return The first object of the desired type, otherwise null. - */ - public static T findFirstOfType(Object[] args, Class clazz) { - if (isNullOrEmpty(args)) { - return null; - } - - for (Object arg : args) { - if (clazz.isInstance(arg)) { - return clazz.cast(arg); - } - } - - return null; - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/util/binarydata/BinaryDataTest.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/util/binarydata/BinaryDataTest.java deleted file mode 100644 index 3dfe3ef8cbdc..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/util/binarydata/BinaryDataTest.java +++ /dev/null @@ -1,640 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.util.binarydata; - -import io.clientcore.core.implementation.util.IterableOfByteBuffersInputStream; -import io.clientcore.core.models.MockFile; -import io.clientcore.core.models.MockPath; -import io.clientcore.core.models.Person; -import io.clientcore.core.serialization.json.JsonReader; -import io.clientcore.core.serialization.json.JsonSerializable; -import io.clientcore.core.serialization.json.JsonToken; -import io.clientcore.core.serialization.json.JsonWriter; -import io.clientcore.core.implementation.util.JsonSerializer; -import io.clientcore.core.util.serializer.ObjectSerializer; -import org.junit.jupiter.api.Named; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; -import org.junit.jupiter.params.provider.ValueSource; - -import java.io.ByteArrayInputStream; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.ByteBuffer; -import java.nio.ReadOnlyBufferException; -import java.nio.channels.FileChannel; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Arrays; -import java.util.List; -import java.util.UUID; -import java.util.function.Supplier; -import java.util.stream.Stream; - -import static io.clientcore.core.util.TestUtils.assertArraysEqual; -import static io.clientcore.core.util.TestUtils.fillArray; -import static io.clientcore.core.util.TestUtils.readStream; -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.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * Test class for {@link BinaryData}. - */ -public class BinaryDataTest { - private static final ObjectSerializer SERIALIZER = new JsonSerializer(); - private static final byte[] RANDOM_DATA; - - static { - RANDOM_DATA = new byte[1024 * 1024]; // 1 MB - - fillArray(RANDOM_DATA); - } - - @Test - public void fromCustomObject() throws IOException { - // Arrange - final Person actualValue = new Person().setName("John Doe").setAge(50); - final Person expectedValue = new Person().setName("John Doe").setAge(50); - - // Act - final BinaryData data = BinaryData.fromObject(actualValue, SERIALIZER); - - // Assert - assertEquals(expectedValue, data.toObject(expectedValue.getClass(), SERIALIZER)); - } - - @Test - public void fromDouble() throws IOException { - // Arrange - final Double actualValue = Double.valueOf("10.1"); - final Double expectedValue = Double.valueOf("10.1"); - - // Act - final BinaryData data = BinaryData.fromObject(actualValue, SERIALIZER); - - // Assert - assertEquals(expectedValue, data.toObject(expectedValue.getClass(), SERIALIZER)); - } - - @Test - public void anyTypeToByteArray() { - // Assert - final Person actualValue = new Person().setName("John Doe").setAge(50); - final byte[] expectedValue = "{\"name\":\"John Doe\",\"age\":50}".getBytes(StandardCharsets.UTF_8); - - // Act - final BinaryData data = BinaryData.fromObject(actualValue, SERIALIZER); - - // Assert - assertArraysEqual(expectedValue, data.toBytes()); - } - - @Test - public void createFromString() { - // Arrange - final String expected = "Doe"; - - // Act - final BinaryData data = BinaryData.fromString(expected); - - // Assert - assertArraysEqual(expected.getBytes(), data.toBytes()); - assertEquals(expected, data.toString()); - } - - @Test - public void createFromByteArray() { - // Arrange - final byte[] expected = "Doe".getBytes(StandardCharsets.UTF_8); - - // Act - final BinaryData data = BinaryData.fromBytes(expected); - - // Assert - assertArraysEqual(expected, data.toBytes()); - } - - @Test - public void createFromNullStream() { - assertThrows(NullPointerException.class, () -> BinaryData.fromStream(null)); - } - - @Test - public void createFromNullByteArray() { - assertThrows(NullPointerException.class, () -> BinaryData.fromBytes(null)); - } - - @Test - public void createFromNullObject() { - BinaryData binaryData = BinaryData.fromObject(null, SERIALIZER); - - assertNull(binaryData.toBytes()); - assertNull(binaryData.getLength()); - } - - @Test - public void createFromNullFile() { - assertThrows(NullPointerException.class, () -> BinaryData.fromFile(null)); - } - - @Test - public void createFromStream() { - // Arrange - final byte[] expected = "Doe".getBytes(StandardCharsets.UTF_8); - - // Act - BinaryData data = BinaryData.fromStream(new ByteArrayInputStream(expected)); - - // Assert - assertArraysEqual(expected, data.toBytes()); - } - - @Test - public void createFromEmptyStream() { - // Arrange - final byte[] expected = "".getBytes(); - - // Act - BinaryData data = BinaryData.fromStream(new ByteArrayInputStream(expected)); - - // Assert - assertArraysEqual(expected, data.toBytes()); - } - - @Test - public void createFromEmptyString() { - // Arrange - final String expected = ""; - - // Act - final BinaryData data = BinaryData.fromString(expected); - - // Assert - assertArraysEqual(expected.getBytes(), data.toBytes()); - assertEquals(expected, data.toString()); - } - - @Test - public void createFromEmptyByteArray() { - // Arrange - final byte[] expected = new byte[0]; - - // Act - final BinaryData data = BinaryData.fromBytes(expected); - - // Assert - assertArraysEqual(expected, data.toBytes()); - } - - @Test - public void createFromNullString() { - // Arrange - final String expected = null; - - // Arrange & Act - assertThrows(NullPointerException.class, () -> BinaryData.fromString(expected)); - } - - @Test - public void createFromListByteBuffer() { - final byte[] data = "Doe".getBytes(StandardCharsets.UTF_8); - final List list = Arrays.asList(ByteBuffer.wrap(data), ByteBuffer.wrap(data)); - final byte[] expected = "DoeDoe".getBytes(StandardCharsets.UTF_8); - - BinaryData binaryData = BinaryData.fromListByteBuffer(list); - - assertArraysEqual(expected, binaryData.toBytes()); - } - - @Test - public void toReadOnlyByteBufferThrowsOnMutation() { - BinaryData binaryData = BinaryData.fromString("Hello"); - - assertThrows(ReadOnlyBufferException.class, () -> binaryData.toByteBuffer().put((byte) 0)); - } - - @Test - public void fromCustomObjectWithDefaultSerializer() throws IOException { - // Arrange - final Person actualValue = new Person().setName("John Doe").setAge(50); - final Person expectedValue = new Person().setName("John Doe").setAge(50); - - // Act - final BinaryData data = BinaryData.fromObject(actualValue); - - // Assert - assertEquals(expectedValue, data.toObject(expectedValue.getClass())); - } - - @Test - public void fromDoubleWithDefaultSerializer() throws IOException { - // Arrange - final Double actualValue = Double.valueOf("10.1"); - final Double expectedValue = Double.valueOf("10.1"); - - // Act - final BinaryData data = BinaryData.fromObject(actualValue); - - // Assert - assertEquals(expectedValue, data.toObject(expectedValue.getClass())); - } - - @Test - public void anyTypeToByteArrayWithDefaultSerializer() { - // Assert - final Person actualValue = new Person().setName("John Doe").setAge(50); - final byte[] expectedValue = "{\"name\":\"John Doe\",\"age\":50}".getBytes(StandardCharsets.UTF_8); - - // Act - final BinaryData data = BinaryData.fromObject(actualValue); - - // Assert - assertArraysEqual(expectedValue, data.toBytes()); - } - - @Test - public void testFromFile() throws Exception { - Path file = Files.createTempFile("binaryDataFromFile" + UUID.randomUUID(), ".txt"); - - file.toFile().deleteOnExit(); - - Files.write(file, "The quick brown fox jumps over the lazy dog".getBytes(StandardCharsets.UTF_8)); - - BinaryData data = BinaryData.fromFile(file); - - assertEquals("The quick brown fox jumps over the lazy dog", data.toString()); - } - - @Test - public void testFromLargeFileStream() throws Exception { - int chunkSize = 1024 * 1024; // 1 MB - long numberOfChunks = 2200L; // 2200 MB total - - MockFile mockFile - = new MockFile("binaryDataFromFile" + UUID.randomUUID() + ".txt", RANDOM_DATA, numberOfChunks * chunkSize); - FileBinaryData fileContent = new MockFileBinaryData(new MockPath(mockFile), 32768, null, null); - - try (InputStream is = fileContent.toStream()) { - // Read and validate in chunks to optimize validation compared to byte-by-byte checking. - byte[] buffer = new byte[4096]; - long totalRead = 0; - int read; - int idx = 0; - - while ((read = is.read(buffer)) >= 0) { - totalRead += read; - - // This may look a bit odd but ByteBuffer has array-based comparison optimizations that aren't available - // in Arrays until Java 9+. Wrapping the bytes chunk that was expected to be read and the read range - // will allow for many bytes to be validated at once instead of byte-by-byte. - assertEquals(ByteBuffer.wrap(RANDOM_DATA, idx, read), ByteBuffer.wrap(buffer, 0, read)); - - idx = (idx + read) % chunkSize; - } - - assertEquals((long) chunkSize * numberOfChunks, totalRead); - } - } - - @ParameterizedTest - @ValueSource(ints = { 10, 113, 1024, 1024 + 113, 10 * 1024 * 1024 + 13 }) - public void testFromFileSegment(int size) throws Exception { - int leftPadding = 10 * 1024 + 13; - int rightPadding = 10 * 1024 + 27; - byte[] fullFile = new byte[size + leftPadding + rightPadding]; - - fillArray(fullFile); - - MockFile mockFile - = new MockFile("binaryDataFromFileSegment" + UUID.randomUUID() + ".txt", fullFile, fullFile.length); - FileBinaryData fileContent - = new MockFileBinaryData(new MockPath(mockFile), 8192, (long) leftPadding, (long) size); - - assertEquals(size, fileContent.getLength()); - - byte[] actualBytes = fileContent.toBytes(); - - assertArraysEqual(fullFile, leftPadding, size, actualBytes, actualBytes.length); - - actualBytes = new byte[size]; - - try (InputStream is = fileContent.toStream()) { - int totalRead = 0; - int nRead; - byte[] buffer = new byte[4096]; - - while ((nRead = is.read(buffer, 0, buffer.length)) != -1) { - System.arraycopy(buffer, 0, actualBytes, totalRead, nRead); - - totalRead += nRead; - } - } - - assertArraysEqual(fullFile, leftPadding, size, actualBytes, actualBytes.length); - } - - @ParameterizedTest - @MethodSource("createNonRetryableBinaryData") - public void testNonReplayableContentTypes(Supplier binaryDataSupplier) throws IOException { - assertFalse(binaryDataSupplier.get().isReplayable()); - - BinaryData data = binaryDataSupplier.get(); - byte[] firstStreamConsumption = readStream(data.toStream()); - byte[] secondStreamConsumption = readStream(data.toStream()); - - // Either flux or stream consumption is not replayable. - assertFalse(Arrays.equals(firstStreamConsumption, secondStreamConsumption)); - } - - public static Stream createNonRetryableBinaryData() { - byte[] bytes = new byte[1024]; - - fillArray(bytes); - - return Stream.of( - Arguments.of(Named.named("stream", - (Supplier) () -> BinaryData.fromStream(new ByteArrayInputStream(bytes)))), - Arguments.of(Named.named("byte array stream", - (Supplier) () -> BinaryData.fromStream(new ByteArrayInputStream(bytes), null)))); - } - - @ParameterizedTest - @MethodSource("createRetryableBinaryData") - public void testReplayableContentTypes(Supplier binaryDataSupplier, byte[] expectedBytes) - throws IOException { - - assertTrue(binaryDataSupplier.get().isReplayable()); - - // Check toStream consumption - BinaryData data = binaryDataSupplier.get(); - byte[] firstConsumption = readStream(data.toStream()); - byte[] secondConsumption = readStream(data.toStream()); - assertArraysEqual(firstConsumption, secondConsumption); - assertArraysEqual(expectedBytes, firstConsumption); - - // Check toByteBuffer consumption - data = binaryDataSupplier.get(); - firstConsumption = readByteBuffer(data.toByteBuffer()); - secondConsumption = readByteBuffer(data.toByteBuffer()); - assertArraysEqual(firstConsumption, secondConsumption); - assertArraysEqual(expectedBytes, firstConsumption); - - // Check toBytes consumption - data = binaryDataSupplier.get(); - firstConsumption = data.toBytes(); - secondConsumption = data.toBytes(); - assertArraysEqual(firstConsumption, secondConsumption); - assertArraysEqual(expectedBytes, firstConsumption); - - // Check that attempt to make repeatable returns itself. - data = binaryDataSupplier.get(); - BinaryData clone = data.toReplayableBinaryData(); - assertSame(data, clone); - } - - public static Stream createRetryableBinaryData() throws IOException { - byte[] bytes = new byte[1024]; - fillArray(bytes); - - MockFile mockFile = new MockFile("binaryDataFromFile" + UUID.randomUUID() + ".txt", bytes, 1024); - - return Stream.of( - Arguments.of(Named.named("bytes", (Supplier) () -> BinaryData.fromBytes(bytes)), - Named.named("expected bytes", bytes)), - Arguments.of(Named.named("string", (Supplier) () -> BinaryData.fromString("test string")), - Named.named("expected bytes", "test string".getBytes(StandardCharsets.UTF_8))), - Arguments.of(Named.named("object", (Supplier) () -> BinaryData.fromObject("\"test string\"")), - Named.named("expected bytes", BinaryData.SERIALIZER.serializeToBytes("\"test string\""))), - Arguments.of( - Named.named("file", (Supplier) () -> new MockFileBinaryData(new MockPath(mockFile))), - Named.named("expected bytes", bytes)), - Arguments.of( - Named.named("byte buffer", - (Supplier) () -> BinaryData.fromByteBuffer(ByteBuffer.wrap(bytes))), - Named.named("expected bytes", bytes)), - Arguments.of( - Named.named("byte array stream", (Supplier) () -> BinaryData - .fromStream(new ByteArrayInputStream(bytes), (long) bytes.length)), - Named.named("expected bytes", bytes))); - } - - @Test - public void testMakeSmallMarkableStreamReplayable() throws IOException { - byte[] bytes = new byte[1024]; - fillArray(bytes); - - // Delegate to testReplayableContentTypes to assert accessors replayability - testReplayableContentTypes( - () -> BinaryData.fromStream(new ByteArrayInputStream(bytes), (long) bytes.length).toReplayableBinaryData(), - bytes); - - // When using markable stream - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); - assertSame(byteArrayInputStream, - BinaryData.fromStream(byteArrayInputStream, (long) bytes.length).toReplayableBinaryData().toStream()); - } - - @Test - public void testMakeUnknownLengthMarkableStreamReplayable() throws IOException { - byte[] bytes = new byte[1024]; - fillArray(bytes); - - // Delegate to testReplayableContentTypes to assert accessors replayability - testReplayableContentTypes( - () -> BinaryData.fromStream(new ByteArrayInputStream(bytes)).toReplayableBinaryData(), bytes); - - // When using markable stream - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); - assertNotSame(byteArrayInputStream, - BinaryData.fromStream(byteArrayInputStream).toReplayableBinaryData().toStream()); - - // Check that buffering happened. This is part assumes implementation. - assertInstanceOf(IterableOfByteBuffersInputStream.class, - BinaryData.fromStream(byteArrayInputStream).toReplayableBinaryData().toStream()); - } - - @ParameterizedTest - // Try various sizes. That hit MIN and MAX buffers size in the InputStreamContent - @ValueSource( - ints = { - 10, - 1024, - 8 * 1024 - 1, - 8 * 1024 + 113, - 4 * 1024 * 1024 + 117, - 8 * 1024 * 1024, - 8 * 1024 * 1024 + 117, - 64 * 1024 * 1024 + 117 }) - public void testCanBufferNotMarkableStreams(int size) throws IOException { - byte[] bytes = new byte[size]; - fillArray(bytes); - - MockFile mockFile = new MockFile("binaryDataFromFile" + UUID.randomUUID() + ".txt", bytes, size); - - // Delegate to testReplayableContentTypes to assert accessors replayability - // with unknown length - testReplayableContentTypes(() -> new MockFileBinaryData(new MockPath(mockFile)).toReplayableBinaryData(), - bytes); - - // with known length - testReplayableContentTypes(() -> new MockFileBinaryData(new MockPath(mockFile), 8192, null, (long) bytes.length) - .toReplayableBinaryData(), bytes); - - // When using markable stream - FileInputStream fileInputStream = new MockFileInputStream(mockFile); - assertFalse(fileInputStream.markSupported()); - assertNotSame(fileInputStream, BinaryData.fromStream(fileInputStream).toReplayableBinaryData().toStream()); - - // Check that buffering happened. This is part assumes implementation. - assertInstanceOf(IterableOfByteBuffersInputStream.class, - BinaryData.fromStream(fileInputStream).toReplayableBinaryData().toStream()); - } - - /** - * On Windows {@link FileChannel#map(FileChannel.MapMode, long, long)} can block file deletion until buffer is - * reclaimed by GC. https://bugs.java.com/bugdatabase/view_bug.do?bug_id=4715154 - */ - @Test - public void binaryDataFromFileToBytesDoesNotBlockDelete() throws IOException { - byte[] bytes = new byte[10240]; - fillArray(bytes); - Path tempFile = Files.createTempFile("deletionTest", null); - tempFile.toFile().deleteOnExit(); - Files.write(tempFile, bytes); - - // create and consume flux. - BinaryData.fromFile(tempFile).toBytes(); - - // immediate delete should succeed. - assertTrue(tempFile.toFile().delete()); - } - - @Test - public void binaryDataAsPropertySerialization() throws IOException { - BinaryDataAsProperty binaryDataAsProperty = new BinaryDataAsProperty() - .setProperty(BinaryData.fromObject(new BinaryDataPropertyClass().setTest("test"))); - String expectedJson = "{\"property\":{\"test\":\"test\"}}"; - String actualJson = new String(new JsonSerializer().serializeToBytes(binaryDataAsProperty)); - - assertEquals(expectedJson, actualJson); - } - - @Test - public void binaryDataAsPropertyDeserialization() throws IOException { - BinaryDataAsProperty expected = new BinaryDataAsProperty() - .setProperty(BinaryData.fromObject(new BinaryDataPropertyClass().setTest("test"))); - String json = "{\"property\":{\"test\":\"test\"}}"; - BinaryDataAsProperty actual - = new JsonSerializer().deserializeFromBytes(json.getBytes(), BinaryDataAsProperty.class); - - assertEquals(expected.getProperty().toString(), actual.getProperty().toString()); - } - - public static final class BinaryDataAsProperty implements JsonSerializable { - private BinaryData property; - - public BinaryData getProperty() { - return property; - } - - public BinaryDataAsProperty setProperty(BinaryData property) { - this.property = property; - - return this; - } - - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - - BinaryDataPropertyClass binaryDataPropertyClass - = property.toObject(BinaryDataPropertyClass.class, SERIALIZER); - - jsonWriter.writeJsonField("property", binaryDataPropertyClass); - jsonWriter.writeEndObject(); - - return jsonWriter; - } - - public static BinaryDataAsProperty fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - BinaryDataAsProperty binaryDataAsProperty = new BinaryDataAsProperty(); - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("property".equals(fieldName)) { - binaryDataAsProperty.setProperty(BinaryData.fromObject(reader.readUntyped())); - } else { - reader.skipChildren(); - } - } - - return binaryDataAsProperty; - }); - } - } - - public static final class BinaryDataPropertyClass implements JsonSerializable { - private String test; - - public String getTest() { - return test; - } - - public BinaryDataPropertyClass setTest(String test) { - this.test = test; - - return this; - } - - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("test", test); - jsonWriter.writeEndObject(); - - return jsonWriter; - } - - public static BinaryDataPropertyClass fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - BinaryDataPropertyClass binaryDataPropertyClass = new BinaryDataPropertyClass(); - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("test".equals(fieldName)) { - binaryDataPropertyClass.setTest(reader.getString()); - } else { - reader.skipChildren(); - } - } - - return binaryDataPropertyClass; - }); - } - } - - private static byte[] readByteBuffer(ByteBuffer buffer) { - // Simplified implementation good enough for testing. - byte[] result = new byte[buffer.remaining()]; - - buffer.get(result); - - return result; - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/util/serializer/JsonSerializerTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/util/serializer/JsonSerializerTests.java deleted file mode 100644 index 9371a7f081c7..000000000000 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/util/serializer/JsonSerializerTests.java +++ /dev/null @@ -1,272 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.core.util.serializer; - -import io.clientcore.core.http.exception.HttpExceptionType; -import io.clientcore.core.http.models.HttpMethod; -import io.clientcore.core.implementation.AccessibleByteArrayOutputStream; -import io.clientcore.core.implementation.util.JsonSerializer; -import io.clientcore.core.models.SimpleClass; -import io.clientcore.core.serialization.json.JsonReader; -import io.clientcore.core.serialization.json.JsonSerializable; -import io.clientcore.core.serialization.json.JsonToken; -import io.clientcore.core.serialization.json.JsonWriter; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.InvocationTargetException; -import java.net.URI; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Stream; - -import static io.clientcore.core.util.TestUtils.assertArraysEqual; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; - -public class JsonSerializerTests { - private static final ObjectSerializer SERIALIZER = new JsonSerializer(); - - @Test - public void mapWithEmptyKeyAndNullValue() throws IOException { - final MapHolder mapHolder = new MapHolder(); - - mapHolder.map(new HashMap<>()); - mapHolder.map().put("", null); - - assertEquals("{\"map\":{\"\":null}}", new String(SERIALIZER.serializeToBytes(mapHolder))); - } - - @Test - public void mapWithEmptyKeyAndEmptyValue() throws IOException { - final MapHolder mapHolder = new MapHolder(); - - mapHolder.map = new HashMap<>(); - mapHolder.map.put("", ""); - - assertEquals("{\"map\":{\"\":\"\"}}", new String(SERIALIZER.serializeToBytes(mapHolder))); - } - - private static class MapHolder implements JsonSerializable { - private Map map = new HashMap<>(); - - public Map map() { - return map; - } - - public void map(Map map) { - this.map = map; - } - - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return jsonWriter.writeStartObject() - .writeMapField("map", this.map, JsonWriter::writeString) - .writeEndObject(); - } - - public static MapHolder fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - MapHolder mapHolder = new MapHolder(); - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("map".equals(fieldName)) { - mapHolder.map = reader.readMap(JsonReader::getString); - } else { - reader.skipChildren(); - } - } - - return mapHolder; - }); - } - } - - @ParameterizedTest - @MethodSource("deserializeJsonSupplier") - public void deserializeJson(String json, DateTimeWrapper expected) throws IOException { - DateTimeWrapper actual = new JsonSerializer().deserializeFromBytes(json.getBytes(), DateTimeWrapper.class); - - assertEquals(expected.getOffsetDateTime(), actual.getOffsetDateTime()); - } - - private static Stream deserializeJsonSupplier() { - final String jsonFormatDate = "{\"OffsetDateTime\":\"%s\"}"; - DateTimeWrapper minValue - = new DateTimeWrapper().setOffsetDateTime(OffsetDateTime.of(1, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC)); - DateTimeWrapper unixEpoch - = new DateTimeWrapper().setOffsetDateTime(OffsetDateTime.of(1970, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC)); - - return Stream.of(Arguments.of(String.format(jsonFormatDate, "0001-01-01T00:00:00Z"), minValue), - Arguments.of(String.format(jsonFormatDate, "1970-01-01T00:00:00Z"), unixEpoch)); - } - - public static class DateTimeWrapper implements JsonSerializable { - private OffsetDateTime offsetDateTime; - - public DateTimeWrapper setOffsetDateTime(OffsetDateTime offsetDateTime) { - this.offsetDateTime = offsetDateTime; - - return this; - } - - public OffsetDateTime getOffsetDateTime() { - return offsetDateTime; - } - - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("OffsetDateTime", offsetDateTime.toString()) - .writeEndObject(); - } - - public static DateTimeWrapper fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - DateTimeWrapper dateTimeWrapper = new DateTimeWrapper(); - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("OffsetDateTime".equals(fieldName)) { - dateTimeWrapper.offsetDateTime = OffsetDateTime.parse(reader.getString()); - } else { - reader.skipChildren(); - } - } - - return dateTimeWrapper; - }); - } - } - - @ParameterizedTest - @MethodSource("textSerializationSupplier") - public void textToStringSerialization(Object value, String expected) throws IOException { - if (expected == null) { - assertNull(value); - } else { - assertEquals(expected, new String(SERIALIZER.serializeToBytes(value))); - } - } - - @ParameterizedTest - @MethodSource("textSerializationSupplier") - public void textToBytesSerialization(Object value, String expected) throws IOException { - byte[] actual = SERIALIZER.serializeToBytes(value); - - if (expected == null) { - assertNull(actual); - } else { - assertEquals(expected, new String(actual, StandardCharsets.UTF_8)); - } - } - - @ParameterizedTest - @MethodSource("textSerializationSupplier") - public void textToOutputStreamSerialization(Object value, String expected) throws IOException { - AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(); - SERIALIZER.serializeToStream(outputStream, value); - - if (expected == null) { - assertEquals(0, outputStream.count()); - } else { - assertEquals(expected, outputStream.toString(StandardCharsets.UTF_8)); - } - } - - private static Stream textSerializationSupplier() { - Map map = Collections.singletonMap("key", "value"); - - return Stream.of(Arguments.of(1, "1"), Arguments.of(1L, "1"), Arguments.of(1.0F, "1.0"), - Arguments.of(1.0D, "1.0"), Arguments.of("1", "\"1\""), Arguments.of(HttpMethod.GET, "\"GET\""), - Arguments.of(HttpExceptionType.RESOURCE_MODIFIED, "\"RESOURCE_MODIFIED\""), - Arguments.of(HttpExceptionType.fromString(null), null), Arguments.of(map, "{\"key\":\"value\"}"), - Arguments.of(null, null)); - } - - @ParameterizedTest - @MethodSource("bytesDeserializationSupplier") - public void stringToTextDeserialization(byte[] stringBytes, Class type, Object expected) throws IOException { - Object actual = SERIALIZER.deserializeFromBytes(stringBytes, type); - - if (type == byte[].class) { - assertArraysEqual((byte[]) expected, (byte[]) actual); - } else { - assertEquals(expected, actual); - } - } - - @ParameterizedTest - @MethodSource("bytesDeserializationSupplier") - public void bytesToTextDeserialization(byte[] bytes, Class type, Object expected) throws IOException { - Object actual = SERIALIZER.deserializeFromBytes(bytes, type); - - if (type == byte[].class) { - assertArraysEqual((byte[]) expected, (byte[]) actual); - } else { - assertEquals(expected, actual); - } - } - - @ParameterizedTest - @MethodSource("bytesDeserializationSupplier") - public void inputStreamToTextDeserialization(byte[] inputStreamBytes, Class type, Object expected) - throws IOException { - Object actual = SERIALIZER.deserializeFromStream(new ByteArrayInputStream(inputStreamBytes), type); - - if (type == byte[].class) { - assertArraysEqual((byte[]) expected, (byte[]) actual); - } else { - assertEquals(expected, actual); - } - } - - private static Stream bytesDeserializationSupplier() { - return Stream.of(Arguments.of("\"hello\"".getBytes(StandardCharsets.UTF_8), String.class, "hello"), - Arguments.of("1".getBytes(StandardCharsets.UTF_8), Integer.class, 1), - Arguments.of("1000000000000".getBytes(StandardCharsets.UTF_8), Long.class, 1000000000000L), - Arguments.of("1.0".getBytes(StandardCharsets.UTF_8), Double.class, 1.0D), - Arguments.of("true".getBytes(StandardCharsets.UTF_8), Boolean.class, true)); - } - - @ParameterizedTest - @MethodSource("unsupportedDeserializationSupplier") - public void unsupportedTextTypesDeserialization(Class unsupportedType, - Class exceptionType) { - assertThrows(exceptionType, () -> { - try { - SERIALIZER.deserializeFromBytes(":////".getBytes(), unsupportedType); - } catch (RuntimeException e) { - throw e.getCause(); - } - }); - } - - private static Stream unsupportedDeserializationSupplier() { - return Stream.of(Arguments.of(InputStream.class, IOException.class), - // Thrown when the String cannot be parsed by core - Arguments.of(SimpleClass.class, InvocationTargetException.class), - // Thrown when the class doesn't have a fromJson method - Arguments.of(URL.class, IOException.class), - // Thrown when the String cannot be parsed by core - Arguments.of(URI.class, IOException.class) // Thrown when the String cannot be parsed by core - ); - } -} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/AuthUtilsTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/AuthUtilsTests.java new file mode 100644 index 000000000000..bd11ff1a5b69 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/AuthUtilsTests.java @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.utils; + +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import static java.util.Collections.emptyList; +import static java.util.Collections.singletonList; +import static java.util.Collections.singletonMap; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * Unit tests for {@link AuthUtils}. + */ +public class AuthUtilsTests { + @ParameterizedTest + @MethodSource("validParseAuthenticateHeaderSupplier") + @Execution(ExecutionMode.SAME_THREAD) + public void validParseAuthenticateHeader(String authenticationHeader, List expected) { + List actual = AuthUtils.parseAuthenticateHeader(authenticationHeader); + + assertEquals(expected.size(), actual.size()); + for (int i = 0; i < expected.size(); i++) { + assertEquals(expected.get(i).getScheme(), actual.get(i).getScheme()); + assertEquals(expected.get(i).getParameters(), actual.get(i).getParameters()); + assertEquals(expected.get(i).getToken68(), actual.get(i).getToken68()); + } + } + + private static Stream validParseAuthenticateHeaderSupplier() { + Map digestParams = new LinkedHashMap<>(); + digestParams.put("nonce", "123"); + digestParams.put("opaque", "123"); + digestParams.put("qop", "123"); + digestParams.put("algorithm", "SHA-256"); + + return Stream.of(Arguments.of(null, emptyList()), Arguments.of("", emptyList()), + Arguments.of("Basic", singletonList(new AuthenticateChallenge("Basic"))), + Arguments.of("Basic realm=\"test\"", + singletonList(new AuthenticateChallenge("Basic", singletonMap("realm", "test")))), + Arguments.of("Custom ABkd856gkslw-._~+/=", + singletonList(new AuthenticateChallenge("Custom", "ABkd856gkslw-._~+/="))), + Arguments.of("Digest nonce = \"123\", opaque=\"123\", qop=\"123\", algorithm=SHA-256", + singletonList(new AuthenticateChallenge("Digest", digestParams))), + Arguments.of("Digest nonce = \"123\", opaque=\"123\", qop=\"123\", algorithm=SHA-256, Basic realm=\"test\"", + Arrays.asList(new AuthenticateChallenge("Digest", digestParams), + new AuthenticateChallenge("Basic", singletonMap("realm", "test")))), + Arguments.of("Basic realm=\"test\", Basic realm=\"test2\"", + Arrays.asList(new AuthenticateChallenge("Basic", singletonMap("realm", "test")), + new AuthenticateChallenge("Basic", singletonMap("realm", "test2")))), + Arguments.of(" , ,, ,, Basic realm=\"test\"", + singletonList(new AuthenticateChallenge("Basic", singletonMap("realm", "test")))), + Arguments.of("Custom1,Custom2", + Arrays.asList(new AuthenticateChallenge("Custom1"), new AuthenticateChallenge("Custom2")))); + } + + @ParameterizedTest + @MethodSource("invalidParseAuthenticateHeaderSupplier") + @Execution(ExecutionMode.SAME_THREAD) + public void invalidParseAuthenticateHeader(String authenticationHeader) { + assertThrows(IllegalArgumentException.class, () -> AuthUtils.parseAuthenticateHeader(authenticationHeader)); + } + + private static Stream invalidParseAuthenticateHeaderSupplier() { + return Stream.of("ABkd856gkslw-._~+/=", // token68 without scheme + "realm=\"test\"", // auth-param without scheme + "Custom ABkd856gkslw-._~+/, ABkd856gkslw-._~+/", // multiple token68s + "Custom ABkd856gkslw-._~+/, realm=\"test\"", // token68 and auth-param + "Custom realm=\"test\", ABkd856gkslw-._~+/", // auth-param and token68 + "Custom/", // scheme with invalid character + "Custom ABkd856gkslw-._~+/!", // token68 with invalid character + "Custom realm=test/", // auth-param with invalid character + "Custom realm=test realm2=test2", // missing comma between auth-params + "Custom realm=\"", // missing closing quote for auth-param + "Custom realm=123, realm=456", // duplicate auth-param + "realm=123" // missing scheme + ); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/util/auth/AuthorizationChallengeHandlerTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/AuthorizationChallengeHandlerTests.java similarity index 79% rename from sdk/clientcore/core/src/test/java/io/clientcore/core/util/auth/AuthorizationChallengeHandlerTests.java rename to sdk/clientcore/core/src/test/java/io/clientcore/core/utils/AuthorizationChallengeHandlerTests.java index 7b8e04cfff82..1f8185234341 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/util/auth/AuthorizationChallengeHandlerTests.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/AuthorizationChallengeHandlerTests.java @@ -1,15 +1,14 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.util.auth; +package io.clientcore.core.utils; import io.clientcore.core.http.models.HttpHeaderName; import io.clientcore.core.http.models.HttpHeaders; import io.clientcore.core.http.models.HttpMethod; import io.clientcore.core.http.models.HttpRequest; -import io.clientcore.core.http.models.HttpResponse; -import io.clientcore.core.implementation.util.UriBuilder; -import io.clientcore.core.util.binarydata.BinaryData; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.models.binarydata.BinaryData; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -53,7 +52,7 @@ public class AuthorizationChallengeHandlerTests { private static final String DEFAULT_PASSWORD = "Circle Of Life"; private static final String EXPECTED_BASIC = "Basic " + Base64.getEncoder() .encodeToString(String.format("%s:%s", DEFAULT_USERNAME, DEFAULT_PASSWORD).getBytes(StandardCharsets.UTF_8)); - private static final HttpRequest HTTP_REQUEST = new HttpRequest(HttpMethod.GET, createUri()); + private static final HttpRequest HTTP_REQUEST = new HttpRequest().setMethod(HttpMethod.GET).setUri(createUri()); private static final BinaryData ENTITY_BODY = BinaryData.fromBytes(new byte[0]); private static final String BASIC_REALM_EXAMPLE = "Basic realm=\"example\""; @@ -66,7 +65,7 @@ public void handleBasic() { HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaderName.WWW_AUTHENTICATE, BASIC_REALM_EXAMPLE); - basicHandler.handleChallenge(HTTP_REQUEST, new HttpResponse<>(HTTP_REQUEST, 200, headers, null), false); + basicHandler.handleChallenge(HTTP_REQUEST, new Response<>(HTTP_REQUEST, 200, headers, null), false); assertEquals(EXPECTED_BASIC, HTTP_REQUEST.getHeaders().getValue(HttpHeaderName.AUTHORIZATION)); } @@ -81,15 +80,14 @@ public void pipelineBasic() { headers.add(HttpHeaderName.WWW_AUTHENTICATE, BASIC_REALM_EXAMPLE); // Handle initial challenge - basicHandler.handleChallenge(HTTP_REQUEST, new HttpResponse<>(HTTP_REQUEST, 200, headers, null), false); + basicHandler.handleChallenge(HTTP_REQUEST, new Response<>(HTTP_REQUEST, 200, headers, null), false); // Validate the initial authorization header assertEquals(EXPECTED_BASIC, HTTP_REQUEST.getHeaders().getValue(HttpHeaderName.AUTHORIZATION)); // Simulate a subsequent request to validate pipelining - HttpRequest subsequentRequest = new HttpRequest(HttpMethod.GET, createUri()); - basicHandler.handleChallenge(subsequentRequest, new HttpResponse<>(subsequentRequest, 200, headers, null), - false); + HttpRequest subsequentRequest = new HttpRequest().setMethod(HttpMethod.GET).setUri(createUri()); + basicHandler.handleChallenge(subsequentRequest, new Response<>(subsequentRequest, 200, headers, null), false); // Validate the authorization header in the subsequent request assertEquals(EXPECTED_BASIC, subsequentRequest.getHeaders().getValue(HttpHeaderName.AUTHORIZATION)); @@ -104,10 +102,10 @@ public void pipelineBasicWithoutInitialHandleFails() { BasicChallengeHandler basicHandler = new BasicChallengeHandler(DEFAULT_USERNAME, DEFAULT_PASSWORD); // Simulate a subsequent request to validate pipelining without initial handling - HttpRequest subsequentRequest = new HttpRequest(HttpMethod.GET, createUri()); + HttpRequest subsequentRequest = new HttpRequest().setMethod(HttpMethod.GET).setUri(createUri()); // Handle challenge with no previous challenge (lastChallenge is null) - basicHandler.handleChallenge(subsequentRequest, new HttpResponse<>(subsequentRequest, 200, null, null), false); + basicHandler.handleChallenge(subsequentRequest, new Response<>(subsequentRequest, 200, null, null), false); // Validate that the authorization header is null in the subsequent request assertNull(subsequentRequest.getHeaders().getValue(HttpHeaderName.AUTHORIZATION)); @@ -123,9 +121,9 @@ public void md5DigestAuthorization() { String expectedResponse = "6629fae49393a05397450978507c4ef1"; String uri = "/dir/index.html"; - HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, uri); - HttpResponse httpResponse - = createChallengeResponse("testrealm@host.com", "auth", Collections.singletonList("MD5"), + HttpRequest httpRequest = new HttpRequest().setMethod(HttpMethod.GET).setUri(uri); + Response httpResponse + = createDigestChallengeResponse("testrealm@host.com", "auth", Collections.singletonList("MD5"), "dcd98b7102dd2f0e8b11d0f600bfb0c093", "5ccc069c403ebaf9f0171e9517f40e41", null, ENTITY_BODY); digestChallengeHandler.handleChallenge(httpRequest, httpResponse, false); @@ -143,10 +141,10 @@ public void pipelineDigest() { String expectedResponse = "6629fae49393a05397450978507c4ef1"; String uri = "/dir/index.html"; - HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, uri); + HttpRequest httpRequest = new HttpRequest().setMethod(HttpMethod.GET).setUri(uri); - HttpResponse httpResponse - = createChallengeResponse("testrealm@host.com", "auth", Collections.singletonList("MD5"), + Response httpResponse + = createDigestChallengeResponse("testrealm@host.com", "auth", Collections.singletonList("MD5"), "dcd98b7102dd2f0e8b11d0f600bfb0c093", "5ccc069c403ebaf9f0171e9517f40e41", null, ENTITY_BODY); // Handle the initial challenge @@ -157,7 +155,7 @@ public void pipelineDigest() { assertNotNull(authHeader); // Simulate a subsequent request to validate pipelining - HttpRequest subsequentRequest = new HttpRequest(HttpMethod.GET, uri); + HttpRequest subsequentRequest = new HttpRequest().setMethod(HttpMethod.GET).setUri(uri); digestChallengeHandler.handleChallenge(subsequentRequest, httpResponse, false); // Validate that the nonce count is incremented @@ -181,9 +179,9 @@ public void pipelineDigestWithoutInitialHandleFails() { // Simulate a subsequent request to validate pipelining without initial handling // i.e has not been initialized with the necessary challenge information (like nonce, realm, etc.) - HttpRequest subsequentRequest = new HttpRequest(HttpMethod.GET, "/dir/index.html"); - digestChallengeHandler.handleChallenge(subsequentRequest, - new HttpResponse<>(subsequentRequest, 200, null, null), false); + HttpRequest subsequentRequest = new HttpRequest().setMethod(HttpMethod.GET).setUri("/dir/index.html"); + digestChallengeHandler.handleChallenge(subsequentRequest, new Response<>(subsequentRequest, 200, null, null), + false); // Validate that the authorization header is null in the subsequent request assertNull(subsequentRequest.getHeaders().getValue(HttpHeaderName.AUTHORIZATION)); @@ -199,9 +197,9 @@ public void sha256DigestAuthorization() { String expectedResponse = "753927fa0e85d155564e2e272a28d1802ca10daf4496794697cf8db5856cb6c1"; String uri = "/dir/index.html"; - HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, uri); + HttpRequest httpRequest = new HttpRequest().setMethod(HttpMethod.GET).setUri(uri); - HttpResponse httpResponse = createChallengeResponse("http-auth@example.org", "auth", + Response httpResponse = createDigestChallengeResponse("http-auth@example.org", "auth", Collections.singletonList("SHA-256"), "7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v", "FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS", null, ENTITY_BODY); @@ -220,9 +218,9 @@ public void preferSha256OverMd5DigestAuthorization() { String expectedResponse = "753927fa0e85d155564e2e272a28d1802ca10daf4496794697cf8db5856cb6c1"; String uri = "/dir/index.html"; - HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, uri); + HttpRequest httpRequest = new HttpRequest().setMethod(HttpMethod.GET).setUri(uri); - HttpResponse challengeResponse = createChallengeResponse("http-auth@example.org", "auth", + Response challengeResponse = createDigestChallengeResponse("http-auth@example.org", "auth", Arrays.asList("MD5", "SHA-256"), "7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v", "FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS", null, ENTITY_BODY); digestChallengeHandler.handleChallenge(httpRequest, challengeResponse, false); @@ -240,9 +238,9 @@ public void digestAuthorizationDefaultAlgorithmIsMd5() { String expectedResponse = "6629fae49393a05397450978507c4ef1"; String uri = "/dir/index.html"; - HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, uri); + HttpRequest httpRequest = new HttpRequest().setMethod(HttpMethod.GET).setUri(uri); - HttpResponse challengeResponse = createChallengeResponse("testrealm@host.com", "auth", null, + Response challengeResponse = createDigestChallengeResponse("testrealm@host.com", "auth", null, "dcd98b7102dd2f0e8b11d0f600bfb0c093", "5ccc069c403ebaf9f0171e9517f40e41", null, ENTITY_BODY); digestChallengeHandler.handleChallenge(httpRequest, challengeResponse, false); @@ -262,9 +260,9 @@ public void userHashDigestAuthorization() { String expectedResponse = "ae66e67d6b427bd3f120414a82e4acff38e8ecd9101d6c861229025f607a79dd"; String expectedUsername = "488869477bf257147b804c45308cd62ac4e25eb717b12b298c79e62dcea254ec"; String uri = "/doe.json"; - HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, uri); + HttpRequest httpRequest = new HttpRequest().setMethod(HttpMethod.GET).setUri(uri); - HttpResponse challengeResponse = createChallengeResponse("api@example.org", "auth", + Response challengeResponse = createDigestChallengeResponse("api@example.org", "auth", Collections.singletonList("SHA-512-256"), "5TsQWLVdgBdmrQ0XsxbDODV+57QdFR34I9HAbC/RVvkK", "HRPCssKJSGjCrkzDg8OhwpzCiGPChXYjwrI2QmXDnsOS", true, ENTITY_BODY); @@ -286,10 +284,10 @@ public void unknownQop() { String expectedResponse = "670fd8c2df070c60b045671b8b24ff02"; String method = HttpMethod.GET.toString(); String uri = "/dir/index.html"; - HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, uri); + HttpRequest httpRequest = new HttpRequest().setMethod(HttpMethod.GET).setUri(uri); - HttpResponse challengeResponse - = createChallengeResponse("testrealm@host.com", "unknownQop", Collections.singletonList("MD5"), + Response challengeResponse + = createDigestChallengeResponse("testrealm@host.com", "unknownQop", Collections.singletonList("MD5"), "dcd98b7102dd2f0e8b11d0f600bfb0c093", "5ccc069c403ebaf9f0171e9517f40e41", null, ENTITY_BODY); digestChallengeHandler.handleChallenge(httpRequest, challengeResponse, false); @@ -308,9 +306,9 @@ public void md5DigestWithAuthInt() { String expectedResponse = "f7b13069066cfdda58d5accbc02a6b98"; String uri = "/dir/index.html"; - HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, uri); + HttpRequest httpRequest = new HttpRequest().setMethod(HttpMethod.GET).setUri(uri); - HttpResponse challengeResponse = createChallengeResponse("testrealm@host.com", "auth-int", + Response challengeResponse = createDigestChallengeResponse("testrealm@host.com", "auth-int", Collections.singletonList("MD5"), "dcd98b7102dd2f0e8b11d0f600bfb0c093", "5ccc069c403ebaf9f0171e9517f40e41", null, BinaryData.fromBytes("Hello World!".getBytes(StandardCharsets.UTF_8))); @@ -330,10 +328,10 @@ public void md5DigestWithSessAlgorithm() { String expectedResponse = "4726bc10c33fa6cb357eb27807b1cce8"; String method = HttpMethod.GET.toString(); String uri = "/dir/index.html"; - HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, uri); + HttpRequest httpRequest = new HttpRequest().setMethod(HttpMethod.GET).setUri(uri); - HttpResponse challengeResponse - = createChallengeResponse("testrealm@host.com", "", Collections.singletonList("MD5-sess"), + Response challengeResponse + = createDigestChallengeResponse("testrealm@host.com", "", Collections.singletonList("MD5-sess"), "dcd98b7102dd2f0e8b11d0f600bfb0c093", "5ccc069c403ebaf9f0171e9517f40e41", null, ENTITY_BODY); digestChallengeHandler.handleChallenge(httpRequest, challengeResponse, false); @@ -350,10 +348,10 @@ public void unsupportedAlgorithmReturnsNull() { DigestChallengeHandler digestChallengeHandler = new DigestChallengeHandler(DEFAULT_USERNAME, DEFAULT_PASSWORD); String uri = "/dir/index.html"; - HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, uri); + HttpRequest httpRequest = new HttpRequest().setMethod(HttpMethod.GET).setUri(uri); - HttpResponse challengeResponse = createChallengeResponse("realm", "auth", Collections.singletonList("SHA3"), - "nonce", "opaque", null, ENTITY_BODY); + Response challengeResponse = createDigestChallengeResponse("realm", "auth", + Collections.singletonList("SHA3"), "nonce", "opaque", null, ENTITY_BODY); digestChallengeHandler.handleChallenge(httpRequest, challengeResponse, false); assertNull(httpRequest.getHeaders().getValue(HttpHeaderName.AUTHORIZATION)); @@ -368,9 +366,9 @@ public void unknownAlgorithmIsSkipped() { DigestChallengeHandler digestChallengeHandler = new DigestChallengeHandler(DEFAULT_USERNAME, DEFAULT_PASSWORD); String uri = "/dir/index.html"; - HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, uri); + HttpRequest httpRequest = new HttpRequest().setMethod(HttpMethod.GET).setUri(uri); - HttpResponse challengeResponse = createChallengeResponse("realm", "auth", + Response challengeResponse = createDigestChallengeResponse("realm", "auth", Collections.singletonList("SHA9000"), "nonce", "opaque", null, BinaryData.fromBytes(new byte[0])); digestChallengeHandler.handleChallenge(httpRequest, challengeResponse, false); assertNull(httpRequest.getHeaders().getValue(HttpHeaderName.AUTHORIZATION)); @@ -388,10 +386,10 @@ public void consumeAuthenticationInfoHeader() { String uri = "/dir/index.html"; String nonce = "dcd98b7102dd2f0e8b11d0f600bfb0c093"; - HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, uri); + HttpRequest httpRequest = new HttpRequest().setMethod(HttpMethod.GET).setUri(uri); - HttpResponse challengeResponse = createChallengeResponse("realm", "auth", Collections.singletonList("MD5"), - nonce, "opaque", null, BinaryData.fromBytes(new byte[0])); + Response challengeResponse = createDigestChallengeResponse("realm", "auth", + Collections.singletonList("MD5"), nonce, "opaque", null, BinaryData.fromBytes(new byte[0])); digestChallengeHandler.handleChallenge(httpRequest, challengeResponse, false); @@ -408,11 +406,11 @@ public void consumeAuthenticationInfoHeader() { lastChallenge.get().put(NONCE, nextNonceReturned); } - HttpResponse challengeResponseWithNextNonce = createChallengeResponse("realm", "auth", + Response challengeResponseWithNextNonce = createDigestChallengeResponse("realm", "auth", Collections.singletonList("MD5"), nextNonceReturned, "opaque", null, BinaryData.fromBytes(new byte[0])); // Simulate a subsequent request to validate the updated nonce - HttpRequest subsequentRequest = new HttpRequest(HttpMethod.GET, uri); + HttpRequest subsequentRequest = new HttpRequest().setMethod(HttpMethod.GET).setUri(uri); digestChallengeHandler.handleChallenge(subsequentRequest, challengeResponseWithNextNonce, false); // Validate that the nonce has been updated @@ -435,8 +433,8 @@ public void consumingNullOrEmptyAuthenticationInfoHeadersDoesNotUpdate(Map challengeResponse = createChallengeResponse("testrealm@host.com", "auth", + HttpRequest httpRequest = new HttpRequest().setMethod(HttpMethod.GET).setUri(uri); + Response challengeResponse = createDigestChallengeResponse("testrealm@host.com", "auth", Collections.singletonList("MD5"), nonce, "5ccc069c403ebaf9f0171e9517f40e41", null, ENTITY_BODY); // Simulate handling the first challenge @@ -498,8 +496,8 @@ public void handleBasicProxyChallenge() { HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaderName.PROXY_AUTHENTICATE, BASIC_REALM_EXAMPLE); - HttpRequest proxyRequest = new HttpRequest(HttpMethod.GET, createUri()); - basicHandler.handleChallenge(proxyRequest, new HttpResponse<>(proxyRequest, 200, headers, null), true); + HttpRequest proxyRequest = new HttpRequest().setMethod(HttpMethod.GET).setUri(createUri()); + basicHandler.handleChallenge(proxyRequest, new Response<>(proxyRequest, 200, headers, null), true); assertEquals(EXPECTED_BASIC, proxyRequest.getHeaders().getValue(HttpHeaderName.PROXY_AUTHORIZATION)); } @@ -511,8 +509,8 @@ public void handleDigestProxyChallenge() { headers.add(HttpHeaderName.PROXY_AUTHENTICATE, "Digest realm=\"example\", nonce=\"dcd98b7102dd2f0e8b11d0f600bfb0c093\""); - HttpRequest proxyRequest = new HttpRequest(HttpMethod.GET, createUri()); - digestHandler.handleChallenge(proxyRequest, new HttpResponse<>(proxyRequest, 200, headers, null), true); + HttpRequest proxyRequest = new HttpRequest().setMethod(HttpMethod.GET).setUri(createUri()); + digestHandler.handleChallenge(proxyRequest, new Response<>(proxyRequest, 200, headers, null), true); assertNotNull(proxyRequest.getHeaders().getValue(HttpHeaderName.PROXY_AUTHORIZATION)); } @@ -537,29 +535,43 @@ private static Stream parseAuthenticationOrAuthorizationHeaderSupplie Arguments.of("nc=00000001, nextnonce=\"" + nextNonce + "\"", 2, expectedMultiMap)); } - private static HttpResponse createChallengeResponse(String realm, String qop, List algorithmList, - String nonce, String opaque, Boolean userhash, BinaryData entityBody) { - Map challenge = new HashMap<>(); - - challenge.put(REALM, realm); - challenge.put(QOP, qop); - challenge.put(NONCE, nonce); - challenge.put(OPAQUE, opaque); - - if (algorithmList != null) { - for (String algorithm : algorithmList) { - challenge.put(ALGORITHM, algorithm); - } - } + private static Response createDigestChallengeResponse(String realm, String qop, + List algorithmList, String nonce, String opaque, Boolean userhash, BinaryData entityBody) { + StringBuilder challengeBuilder = new StringBuilder("Digest ").append(REALM) + .append("=\"") + .append(realm) + .append("\", ") + .append(QOP) + .append("=\"") + .append(qop) + .append("\", ") + .append(NONCE) + .append("=\"") + .append(nonce) + .append("\", ") + .append(OPAQUE) + .append("=\"") + .append(opaque) + .append("\""); if (userhash != null) { - challenge.put(USERHASH, String.valueOf(userhash)); + challengeBuilder.append(", ").append(USERHASH).append('=').append(userhash); } HttpHeaders headers = new HttpHeaders(); - headers.set(HttpHeaderName.WWW_AUTHENTICATE, "Digest " + challenge); + if (CoreUtils.isNullOrEmpty(algorithmList)) { + // If the algorithm list is null or empty, add the authenticate challenge to the headers. + headers.set(HttpHeaderName.WWW_AUTHENTICATE, challengeBuilder.toString()); + } else { + // If the algorithm list has values, add an authenticate challenge header per algorithm. + // This follows the RFC spec. + for (String algorithm : algorithmList) { + String algorithmChallenge = challengeBuilder + ", " + ALGORITHM + '=' + algorithm; + headers.set(HttpHeaderName.WWW_AUTHENTICATE, algorithmChallenge); + } + } - return new HttpResponse<>(HTTP_REQUEST, 401, headers, entityBody); + return new Response<>(HTTP_REQUEST, 401, headers, entityBody); } private String extractValue(String authHeader, String key) { diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/Base64UriTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/Base64UriTests.java new file mode 100644 index 000000000000..a0df0415c78c --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/Base64UriTests.java @@ -0,0 +1,127 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.utils; + +import org.junit.jupiter.api.Test; + +import static io.clientcore.core.utils.TestUtils.assertArraysEqual; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +public class Base64UriTests { + @Test + public void constructorWithNullBytes() { + final Base64Uri base64Uri = new Base64Uri((byte[]) null); + assertNull(base64Uri.encodedBytes()); + assertNull(base64Uri.decodedBytes()); + assertEmptyString(base64Uri.toString()); + } + + @Test + public void constructorWithEmptyBytes() { + final Base64Uri base64Uri = new Base64Uri(new byte[0]); + assertArraysEqual(new byte[0], base64Uri.encodedBytes()); + assertArraysEqual(new byte[0], base64Uri.decodedBytes()); + assertEquals("", base64Uri.toString()); + } + + @Test + public void constructorWithNonEmptyBytes() { + final Base64Uri base64Uri + = new Base64Uri(new byte[] { 65, 65, 69, 67, 65, 119, 81, 70, 66, 103, 99, 73, 67, 81 }); + assertArraysEqual(new byte[] { 65, 65, 69, 67, 65, 119, 81, 70, 66, 103, 99, 73, 67, 81 }, + base64Uri.encodedBytes()); + assertArraysEqual(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, base64Uri.decodedBytes()); + assertEquals("AAECAwQFBgcICQ", base64Uri.toString()); + } + + @Test + public void constructorWithNullString() { + final Base64Uri base64Uri = new Base64Uri((String) null); + assertNull(base64Uri.encodedBytes()); + assertNull(base64Uri.decodedBytes()); + assertEmptyString(base64Uri.toString()); + } + + @Test + public void constructorWithEmptyString() { + final Base64Uri base64Uri = new Base64Uri(""); + assertArraysEqual(new byte[0], base64Uri.encodedBytes()); + assertArraysEqual(new byte[0], base64Uri.decodedBytes()); + assertEquals("", base64Uri.toString()); + } + + @Test + public void constructorWithEmptyDoubleQuotedString() { + final Base64Uri base64Uri = new Base64Uri("\"\""); + assertArraysEqual(new byte[0], base64Uri.encodedBytes()); + assertArraysEqual(new byte[0], base64Uri.decodedBytes()); + assertEquals("", base64Uri.toString()); + } + + @Test + public void constructorWithEmptySingleQuotedString() { + final Base64Uri base64Uri = new Base64Uri("\'\'"); + assertArraysEqual(new byte[0], base64Uri.encodedBytes()); + assertArraysEqual(new byte[0], base64Uri.decodedBytes()); + assertEquals("", base64Uri.toString()); + } + + @Test + public void constructorWithNonEmptyString() { + final Base64Uri base64Uri = new Base64Uri("AAECAwQFBgcICQ"); + assertArraysEqual(new byte[] { 65, 65, 69, 67, 65, 119, 81, 70, 66, 103, 99, 73, 67, 81 }, + base64Uri.encodedBytes()); + assertArraysEqual(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, base64Uri.decodedBytes()); + assertEquals("AAECAwQFBgcICQ", base64Uri.toString()); + } + + @Test + public void constructorWithNonEmptyDoubleQuotedString() { + final Base64Uri base64Uri = new Base64Uri("\"AAECAwQFBgcICQ\""); + assertArraysEqual(new byte[] { 65, 65, 69, 67, 65, 119, 81, 70, 66, 103, 99, 73, 67, 81 }, + base64Uri.encodedBytes()); + assertArraysEqual(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, base64Uri.decodedBytes()); + assertEquals("AAECAwQFBgcICQ", base64Uri.toString()); + } + + @Test + public void constructorWithNonEmptySingleQuotedString() { + final Base64Uri base64Uri = new Base64Uri("\'AAECAwQFBgcICQ\'"); + assertArraysEqual(new byte[] { 65, 65, 69, 67, 65, 119, 81, 70, 66, 103, 99, 73, 67, 81 }, + base64Uri.encodedBytes()); + assertArraysEqual(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, base64Uri.decodedBytes()); + assertEquals("AAECAwQFBgcICQ", base64Uri.toString()); + } + + @Test + public void encodeWithNullBytes() { + final Base64Uri base64Uri = Base64Uri.encode(null); + assertNull(base64Uri.encodedBytes()); + assertNull(base64Uri.decodedBytes()); + assertEmptyString(base64Uri.toString()); + } + + @Test + public void encodeWithEmptyBytes() { + final Base64Uri base64Uri = Base64Uri.encode(new byte[0]); + assertArraysEqual(new byte[0], base64Uri.encodedBytes()); + assertArraysEqual(new byte[0], base64Uri.decodedBytes()); + assertEquals("", base64Uri.toString()); + } + + @Test + public void encodeWithNonEmptyBytes() { + final Base64Uri base64Uri = Base64Uri.encode(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }); + assertArraysEqual(new byte[] { 65, 65, 69, 67, 65, 119, 81, 70, 66, 103, 99, 73, 67, 81 }, + base64Uri.encodedBytes()); + assertArraysEqual(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, base64Uri.decodedBytes()); + assertEquals("AAECAwQFBgcICQ", base64Uri.toString()); + } + + private static void assertEmptyString(String input) { + assertEquals("", input); + } + +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/util/auth/CompositeChallengeHandlerTest.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/CompositeChallengeHandlerTest.java similarity index 92% rename from sdk/clientcore/core/src/test/java/io/clientcore/core/util/auth/CompositeChallengeHandlerTest.java rename to sdk/clientcore/core/src/test/java/io/clientcore/core/utils/CompositeChallengeHandlerTest.java index 2973cc0c6d6c..e99b7045cdd3 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/util/auth/CompositeChallengeHandlerTest.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/CompositeChallengeHandlerTest.java @@ -1,10 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.util.auth; +package io.clientcore.core.utils; import io.clientcore.core.http.models.HttpRequest; import io.clientcore.core.http.models.Response; +import io.clientcore.core.models.binarydata.BinaryData; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -12,7 +13,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; /** - * Tests for {@link ChallengeHandler.CompositeChallengeHandler}. + * Tests for {@link CompositeChallengeHandler}. */ public class CompositeChallengeHandlerTest { @ParameterizedTest @@ -69,12 +70,12 @@ private static final class MockHandler implements ChallengeHandler { } @Override - public boolean canHandle(Response response, boolean isProxy) { + public boolean canHandle(Response response, boolean isProxy) { return canHandle; } @Override - public void handleChallenge(HttpRequest request, Response response, boolean isProxy) { + public void handleChallenge(HttpRequest request, Response response, boolean isProxy) { handleChallengeCount++; if (handleChallengeThrows) { throw new IllegalStateException("Should not be called"); diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/ContextTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/ContextTests.java new file mode 100644 index 000000000000..807cd38185cb --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/ContextTests.java @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.utils; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Supplier; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * Tests {@link Context} + */ +public class ContextTests { + @Test + public void simpleContext() { + Context context = Context.of("key", "value"); + + assertEquals("value", context.get("key")); + assertNull(context.get("fakeKey")); + } + + @ParameterizedTest + @MethodSource("keysCannotBeNullSupplier") + public void keysCannotBeNull(Supplier contextSupplier) { + assertThrows(NullPointerException.class, contextSupplier::get); + } + + private static Stream> keysCannotBeNullSupplier() { + return Stream.of( + // One key-value pair + () -> Context.of(null, null), + + // Two key-value pairs + () -> Context.of(null, null, "key", null), () -> Context.of("key", null, null, null), + + // Three key-value pairs + () -> Context.of(null, null, "key", null, "key", null), + () -> Context.of("key", null, null, null, "key", null), + () -> Context.of("key", null, "key", null, null, null), + + // Four key-value pairs + () -> Context.of(null, null, "key", null, "key", null, "key", null), + () -> Context.of("key", null, null, null, "key", null, "key", null), + () -> Context.of("key", null, "key", null, null, null, "key", null), + () -> Context.of("key", null, "key", null, "key", null, null, null), + + // Null map + () -> Context.of(null), + + // Map with null key + () -> Context.of(Collections.singletonMap(null, null))); + } + + @ParameterizedTest + @MethodSource("addDataSupplier") + public void addData(String key, String value, String expectedOriginalValue) { + Context context = Context.of("key", "value").put(key, value); + + assertEquals(value, context.get(key)); + assertEquals(expectedOriginalValue, context.get("key")); + } + + private static Stream addDataSupplier() { + return Stream.of( + // Adding with same key overwrites value. + Arguments.of("key", "newValue", "newValue"), Arguments.of("key", "", ""), + + // New values. + Arguments.of("key2", "newValue", "value"), Arguments.of("key2", "", "value")); + } + + @Test + public void putKeyCannotBeNull() { + assertThrows(NullPointerException.class, () -> { + Context context = Context.of("key", "value").put(null, null); + }); + } + + @Test + public void putValueCanBeNull() { + Context context = Context.none().put("key", null); + + assertNull(context.get("key")); + } + + @Test + public void of() { + Context context = Context.of(Collections.singletonMap("key", "value")); + + assertEquals("value", context.get("key")); + + Map complexValues = new HashMap<>(); + complexValues.put("key", "value"); + complexValues.put("key2", "value2"); + context = Context.of(complexValues); + + assertEquals("value", context.get("key")); + assertEquals("value2", context.get("key2")); + } + + @Test + public void getValueKeyCannotBeNull() { + assertThrows(NullPointerException.class, () -> Context.none().get(null)); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/CoreUtilsTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/CoreUtilsTests.java new file mode 100644 index 000000000000..1715b9787774 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/CoreUtilsTests.java @@ -0,0 +1,286 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.utils; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Stream; + +import static java.util.Collections.singletonList; +import static java.util.Collections.singletonMap; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Unit tests for {@link CoreUtils}. + */ +public class CoreUtilsTests { + private static final SecureRandom RANDOM = new SecureRandom(); + + @ParameterizedTest + @MethodSource("arrayIsNullOrEmptySupplier") + public void arrayIsNullOrEmpty(Object[] array, boolean expected) { + assertEquals(expected, CoreUtils.isNullOrEmpty(array)); + } + + private static Stream arrayIsNullOrEmptySupplier() { + return Stream.of(Arguments.of(null, true), Arguments.of(new Object[0], true), + Arguments.of(new Object[] { 1 }, false)); + } + + @ParameterizedTest + @MethodSource("collectionIsNullOrEmptySupplier") + public void collectionIsNullOrEmpty(Collection collection, boolean expected) { + assertEquals(expected, CoreUtils.isNullOrEmpty(collection)); + } + + private static Stream collectionIsNullOrEmptySupplier() { + return Stream.of(Arguments.of(null, true), Arguments.of(new ArrayList<>(), true), + Arguments.of(singletonList(1), false)); + } + + @ParameterizedTest + @MethodSource("mapIsNullOrEmptySupplier") + public void mapIsNullOrEmpty(Map map, boolean expected) { + assertEquals(expected, CoreUtils.isNullOrEmpty(map)); + } + + private static Stream mapIsNullOrEmptySupplier() { + return Stream.of(Arguments.of(null, true), Arguments.of(new HashMap<>(), true), + Arguments.of(singletonMap("key", "value"), false)); + } + + @ParameterizedTest + @MethodSource("stringIsNullOrEmptySupplier") + public void stringIsNullOrEmpty(String string, boolean expected) { + assertEquals(expected, CoreUtils.isNullOrEmpty(string)); + } + + private static Stream stringIsNullOrEmptySupplier() { + return Stream.of(Arguments.of(null, true), Arguments.of("", true), Arguments.of(" ", false), + Arguments.of("foo", false)); + } + + @ParameterizedTest + @MethodSource("byteArrayArrayCopySupplier") + public void byteArrayArrayCopy(byte[] byteArray) { + assertArrayEquals(byteArray, CoreUtils.arrayCopy(byteArray)); + } + + private static Stream byteArrayArrayCopySupplier() { + return Stream.of(null, new byte[0], "1234567890".getBytes(StandardCharsets.UTF_8)); + } + + @Test + public void testProperties() { + assertNotNull(CoreUtils.getProperties("core.properties").get("version")); + assertNotNull(CoreUtils.getProperties("core.properties").get("name")); + assertTrue( + CoreUtils.getProperties("core.properties").get("version").matches("\\d+\\.\\d+\\.\\d+(-beta\\.\\d+)?")); + } + + @Test + public void testMissingProperties() { + assertNotNull(CoreUtils.getProperties("foo.properties")); + assertTrue(CoreUtils.getProperties("foo.properties").isEmpty()); + assertNull(CoreUtils.getProperties("azure-core.properties").get("foo")); + } + + @ParameterizedTest + @MethodSource("arrayCopyIntArraySupplier") + public void arrayCopyIntArray(int[] intArray, int[] expected) { + assertArrayEquals(expected, CoreUtils.arrayCopy(intArray)); + } + + private static Stream arrayCopyIntArraySupplier() { + return Stream.of(Arguments.of(null, null), Arguments.of(new int[0], new int[0]), + Arguments.of(new int[] { 1, 2, 3 }, new int[] { 1, 2, 3 })); + } + + @ParameterizedTest + @MethodSource("arrayCopyGenericArraySupplier") + public void arrayCopyGenericArray(T[] genericArray, T[] expected) { + assertArrayEquals(expected, CoreUtils.arrayCopy(genericArray)); + } + + private static Stream arrayCopyGenericArraySupplier() { + return Stream.of(Arguments.of(null, null), Arguments.of(new String[0], new String[0]), + Arguments.of(new String[] { "1", "2", "3" }, new String[] { "1", "2", "3" })); + } + + @ParameterizedTest + @MethodSource("isNullOrEmptyCollectionSupplier") + public void isNullOrEmptyCollection(Collection collection, boolean expected) { + assertEquals(expected, CoreUtils.isNullOrEmpty(collection)); + } + + private static Stream isNullOrEmptyCollectionSupplier() { + return Stream.of(Arguments.of(null, true), Arguments.of(new ArrayList<>(), true), + Arguments.of(singletonList(1), false)); + } + + @ParameterizedTest + @MethodSource("bytesToHexSupplier") + public void bytesToHex(byte[] bytes, String expectedHex) { + assertEquals(expectedHex, CoreUtils.bytesToHexString(bytes)); + } + + private static Stream bytesToHexSupplier() { + return Stream.of(Arguments.of(null, null), Arguments.of(new byte[0], ""), + Arguments.of("1234567890".getBytes(StandardCharsets.UTF_8), "31323334353637383930")); + } + + @ParameterizedTest + @MethodSource("contentRangeSizeExtractionSupplier") + public void contentRangeSizeExtraction(String contentRange, long expectedSize) { + assertEquals(expectedSize, CoreUtils.extractSizeFromContentRange(contentRange)); + } + + private static Stream contentRangeSizeExtractionSupplier() { + return Stream.of(Arguments.of("0-1023/1024", 1024), Arguments.of("0-1023/*", -1)); + } + + @ParameterizedTest + @MethodSource("invalidContentRangeSizeExtractionSupplier") + public void invalidContentRangeSizeExtraction(String contentRange, Class expectedException) { + assertThrows(expectedException, () -> CoreUtils.extractSizeFromContentRange(contentRange)); + } + + private static Stream invalidContentRangeSizeExtractionSupplier() { + return Stream.of(Arguments.of(null, NullPointerException.class), + Arguments.of("", IllegalArgumentException.class), + Arguments.of("0-1023/notanumber", NumberFormatException.class)); + } + + @Test + public void randomUuidIsCorrectlyType4() { + long msb = RANDOM.nextLong(); + long lsb = RANDOM.nextLong(); + + byte[] bytes = new byte[16]; + + long msbToBytes = msb; + long lsbToBytes = lsb; + for (int i = 15; i >= 8; i--) { + bytes[i] = (byte) (lsbToBytes & 0xff); + lsbToBytes >>= 8; + } + for (int i = 7; i >= 0; i--) { + bytes[i] = (byte) (msbToBytes & 0xff); + msbToBytes >>= 8; + } + + // Generate type 4 UUID using Java's built-in handling. + bytes[6] &= 0x0f; /* clear version */ + bytes[6] |= 0x40; /* set to version 4 */ + bytes[8] &= 0x3f; /* clear variant */ + bytes[8] |= (byte) 0x80; /* set to IETF variant */ + long msbForJava = 0; + long lsbForJava = 0; + for (int i = 0; i < 8; i++) { + msbForJava = (msbForJava << 8) | (bytes[i] & 0xff); + } + for (int i = 8; i < 16; i++) { + lsbForJava = (lsbForJava << 8) | (bytes[i] & 0xff); + } + + assertEquals(new UUID(msbForJava, lsbForJava), CoreUtils.randomUuid(msb, lsb)); + } + + @Test + public void futureCompletesBeforeTimeout() { + try { + AtomicBoolean completed = new AtomicBoolean(false); + Future future = SharedExecutorService.getInstance().submit(() -> { + Thread.sleep(10); + completed.set(true); + return null; + }); + + future.get(5000, TimeUnit.MILLISECONDS); + + assertTrue(completed.get()); + } catch (InterruptedException | ExecutionException | TimeoutException e) { + throw new RuntimeException(e); + } + } + + @ParameterizedTest + @MethodSource("parseBestOffsetDateTimeSupplier") + public void parseBestOffsetDateTime(String dateTime, OffsetDateTime expected) { + assertEquals(expected, CoreUtils.parseBestOffsetDateTime(dateTime)); + } + + private static Stream parseBestOffsetDateTimeSupplier() { + return Stream.of(Arguments.of(null, null), + Arguments.of("2023-09-26T18:32:05Z", OffsetDateTime.of(2023, 9, 26, 18, 32, 5, 0, ZoneOffset.UTC)), + Arguments.of("2023-09-26T18:32:05+00:00", OffsetDateTime.of(2023, 9, 26, 18, 32, 5, 0, ZoneOffset.UTC)), + Arguments.of("2023-09-26T18:32:05+0000", OffsetDateTime.of(2023, 9, 26, 18, 32, 5, 0, ZoneOffset.UTC)), + Arguments.of("2023-09-26T18:32:05", OffsetDateTime.of(2023, 9, 26, 18, 32, 5, 0, ZoneOffset.UTC))); + } + + @Test + public void parseBestNoColonInTimezoneOffset() { + OffsetDateTime parsed = CoreUtils.parseBestOffsetDateTime("2023-09-26T18:32:05+0000"); + assertEquals(2023, parsed.getYear()); + assertEquals(9, parsed.getMonthValue()); + assertEquals(26, parsed.getDayOfMonth()); + assertEquals(18, parsed.getHour()); + assertEquals(32, parsed.getMinute()); + assertEquals(5, parsed.getSecond()); + assertEquals(0, parsed.getOffset().getTotalSeconds()); + } + + @ParameterizedTest + @MethodSource("stringJoinSupplier") + public void stringJoin(String delimiter, List strings, String expected) { + assertEquals(expected, CoreUtils.stringJoin(delimiter, strings)); + } + + private static Stream stringJoinSupplier() { + return Stream.of(Arguments.of(",", new ArrayList<>(), ""), Arguments.of(",", singletonList("red"), "red"), + Arguments.of(",", Arrays.asList("red", "blue"), "red,blue"), + Arguments.of(",", Arrays.asList("red", "blue", "yellow"), "red,blue,yellow"), + Arguments.of(",", Arrays.asList("red", "blue", "yellow", "green"), "red,blue,yellow,green"), + Arguments.of(",", Arrays.asList("red", "blue", "yellow", "green", "orange"), + "red,blue,yellow,green,orange"), + Arguments.of(",", Arrays.asList("red", "blue", "yellow", "green", "orange", "purple"), + "red,blue,yellow,green,orange,purple"), + Arguments.of(",", Arrays.asList("red", "blue", "yellow", "green", "orange", "purple", "brown"), + "red,blue,yellow,green,orange,purple,brown"), + Arguments.of(",", Arrays.asList("red", "blue", "yellow", "green", "orange", "purple", "brown", "indigo"), + "red,blue,yellow,green,orange,purple,brown,indigo"), + Arguments.of(",", + Arrays.asList("red", "blue", "yellow", "green", "orange", "purple", "brown", "indigo", "violet"), + "red,blue,yellow,green,orange,purple,brown,indigo,violet"), + Arguments.of(",", + Arrays.asList("red", "blue", "yellow", "green", "orange", "purple", "brown", "indigo", "violet", + "black"), + "red,blue,yellow,green,orange,purple,brown,indigo,violet,black"), + Arguments.of(",", Arrays.asList("red", "blue", "yellow", "green", "orange", "purple", "brown", "indigo", + "violet", "black", "white"), "red,blue,yellow,green,orange,purple,brown,indigo,violet,black,white")); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/DateTimeRfc1123Tests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/DateTimeRfc1123Tests.java new file mode 100644 index 000000000000..84d1853aff6b --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/DateTimeRfc1123Tests.java @@ -0,0 +1,158 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package io.clientcore.core.utils; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.time.DateTimeException; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeFormatterBuilder; +import java.time.format.SignStyle; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Stream; + +import static java.time.temporal.ChronoField.DAY_OF_MONTH; +import static java.time.temporal.ChronoField.DAY_OF_WEEK; +import static java.time.temporal.ChronoField.HOUR_OF_DAY; +import static java.time.temporal.ChronoField.MINUTE_OF_HOUR; +import static java.time.temporal.ChronoField.MONTH_OF_YEAR; +import static java.time.temporal.ChronoField.SECOND_OF_MINUTE; +import static java.time.temporal.ChronoField.YEAR; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * Unit tests for {@link DateTimeRfc1123}. + */ +public class DateTimeRfc1123Tests { + private static final DateTimeFormatter FORMATTER; + + // Need to custom create the DateTimeFormatter for RFC1123 as Java supports the obsolete ANSI C variant which + // allows one or two numbers in the day of month. + static { + Map dow = new HashMap<>(); + dow.put(1L, "Mon"); + dow.put(2L, "Tue"); + dow.put(3L, "Wed"); + dow.put(4L, "Thu"); + dow.put(5L, "Fri"); + dow.put(6L, "Sat"); + dow.put(7L, "Sun"); + Map moy = new HashMap<>(); + moy.put(1L, "Jan"); + moy.put(2L, "Feb"); + moy.put(3L, "Mar"); + moy.put(4L, "Apr"); + moy.put(5L, "May"); + moy.put(6L, "Jun"); + moy.put(7L, "Jul"); + moy.put(8L, "Aug"); + moy.put(9L, "Sep"); + moy.put(10L, "Oct"); + moy.put(11L, "Nov"); + moy.put(12L, "Dec"); + FORMATTER = new DateTimeFormatterBuilder().parseCaseInsensitive() + .parseLenient() + .optionalStart() + .appendText(DAY_OF_WEEK, dow) + .appendLiteral(", ") + .optionalEnd() + .appendValue(DAY_OF_MONTH, 2, 2, SignStyle.NOT_NEGATIVE) + .appendLiteral(' ') + .appendText(MONTH_OF_YEAR, moy) + .appendLiteral(' ') + .appendValue(YEAR, 4) // 2 digit year not handled + .appendLiteral(' ') + .appendValue(HOUR_OF_DAY, 2) + .appendLiteral(':') + .appendValue(MINUTE_OF_HOUR, 2) + .optionalStart() + .appendLiteral(':') + .appendValue(SECOND_OF_MINUTE, 2) + .optionalEnd() + .appendLiteral(" GMT") + .toFormatter(Locale.getDefault(Locale.Category.FORMAT)); + } + + @Test + public void nullDateTimeStringReturnsNull() { + assertNull(DateTimeRfc1123.fromString(null)); + } + + @Test + public void emptyDateTimeStringReturnsNull() { + assertNull(DateTimeRfc1123.fromString("")); + } + + @ParameterizedTest + @MethodSource("validDateTimeSupplier") + public void validParseDateTime(OffsetDateTime expected) { + assertEquals(expected, DateTimeRfc1123.fromString(FORMATTER.format(expected)).getDateTime()); + } + + @ParameterizedTest + @MethodSource("validDateTimeSupplier") + public void validFormatDateTime(OffsetDateTime expected) { + assertEquals(FORMATTER.format(expected), DateTimeRfc1123.toRfc1123String(expected)); + } + + private static Stream validDateTimeSupplier() { + // Each one of these dates is a different month and uses different years, days, hours, minutes, seconds + // to ensure that the parsing is correct. + OffsetDateTime january = OffsetDateTime.of(1, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); + OffsetDateTime february = OffsetDateTime.of(10, 2, 2, 2, 5, 5, 0, ZoneOffset.UTC); + OffsetDateTime march = OffsetDateTime.of(100, 3, 4, 4, 10, 10, 0, ZoneOffset.UTC); + OffsetDateTime april = OffsetDateTime.of(1000, 4, 6, 6, 15, 15, 0, ZoneOffset.UTC); + OffsetDateTime may = OffsetDateTime.of(1970, 5, 8, 8, 20, 20, 0, ZoneOffset.UTC); + OffsetDateTime june = OffsetDateTime.of(2000, 6, 10, 10, 25, 25, 0, ZoneOffset.UTC); + OffsetDateTime july = OffsetDateTime.of(2010, 7, 12, 12, 30, 30, 0, ZoneOffset.UTC); + OffsetDateTime august = OffsetDateTime.of(2020, 8, 14, 14, 35, 35, 0, ZoneOffset.UTC); + OffsetDateTime september = OffsetDateTime.of(2030, 9, 16, 16, 40, 40, 0, ZoneOffset.UTC); + OffsetDateTime october = OffsetDateTime.of(2040, 10, 18, 18, 45, 45, 0, ZoneOffset.UTC); + OffsetDateTime november = OffsetDateTime.of(2050, 11, 20, 20, 50, 50, 0, ZoneOffset.UTC); + OffsetDateTime december = OffsetDateTime.of(2060, 12, 22, 22, 59, 59, 0, ZoneOffset.UTC); + + return Stream.of(january, february, march, april, may, june, july, august, september, october, november, + december); + } + + @ParameterizedTest + @MethodSource("invalidDateStringSupplier") + public void invalidDateTimeStringThrowsException(String dateTimeString) { + assertThrows(DateTimeException.class, () -> DateTimeRfc1123.fromString(dateTimeString)); + } + + private static Stream invalidDateStringSupplier() { + // Day of the week is ignored when parsing. + return Stream.of("Wed, ab Jan 2021 01:01:01 GMT", // Day of month isn't numeric + "Wed, 99 Jan 2021 01:01:01 GMT", // Day of month isn't in range + "Wed, 01 Jan abcd 01:01:01 GMT", // Year isn't numeric + "Wed, 01 Jan 2021 ab:01:01 GMT", // Hour isn't numeric + "Wed, 01 Jan 2021 25:01:01 GMT", // Hour isn't in range + "Wed, 01 Jan 2021 01:ab:01 GMT", // Minute isn't numeric + "Wed, 01 Jan 2021 01:61:01 GMT", // Minute isn't in range + "Wed, 01 Jan 2021 01:01:ab GMT", // Second isn't numeric + "Wed, 01 Jan 2021 01:01:61 GMT", // Second isn't in range + "Wed, 01 Jan 2021 01:01:01", // Missing GMT + "Wed, 01 Jan 2021 01:01:01 GMT GMT", // Extra GMT + "Wed, 01 Jab 2021 01:01:01 GMT", // Invalid month + "Wed, 01 Juk 2021 01:01:01 GMT", // Invalid month + "Wed, 01 Fed 2021 01:01:01 GMT", // Invalid month + "Wed, 01 Nay 2021 01:01:01 GMT", // Invalid month + "Wed, 01 Mae 2021 01:01:01 GMT", // Invalid month + "Wed, 01 Apo 2021 01:01:01 GMT", // Invalid month + "Wed, 01 Auh 2021 01:01:01 GMT", // Invalid month + "Wed, 01 Seo 2021 01:01:01 GMT", // Invalid month + "Wed, 01 Ocr 2021 01:01:01 GMT", // Invalid month + "Wed, 01 Nob 2021 01:01:01 GMT", // Invalid month + "Wed, 01 Dev 2021 01:01:01 GMT" // Invalid month + ); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/ProgressReporterTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/ProgressReporterTests.java new file mode 100644 index 000000000000..d9904615b214 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/ProgressReporterTests.java @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.utils; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.Future; +import java.util.function.LongConsumer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; + +public class ProgressReporterTests { + + private final ListProgressListener listener = new ListProgressListener(); + + @Test + public void listenerMustNotBeNull() { + assertThrows(NullPointerException.class, () -> ProgressReporter.withProgressListener(null)); + } + + @Test + public void whenNothingHappens() { + ProgressReporter progressReporter = ProgressReporter.withProgressListener(listener); + + assertEquals(Collections.emptyList(), listener.getProgresses()); + } + + @Test + public void canReportProgress() { + ProgressReporter progressReporter = ProgressReporter.withProgressListener(listener); + + progressReporter.reportProgress(1); + progressReporter.reportProgress(3); + progressReporter.reportProgress(5); + + assertEquals(Arrays.asList(1L, 4L, 9L), listener.getProgresses()); + } + + @Test + public void canResetProgress() { + ProgressReporter progressReporter = ProgressReporter.withProgressListener(listener); + + progressReporter.reportProgress(5); + progressReporter.reset(); + + assertEquals(Arrays.asList(5L, 0L), listener.getProgresses()); + } + + @Test + public void canResetProgressInTheMiddle() { + ProgressReporter progressReporter = ProgressReporter.withProgressListener(listener); + + progressReporter.reportProgress(5); + progressReporter.reset(); + progressReporter.reportProgress(4); + + assertEquals(Arrays.asList(5L, 0L, 4L), listener.getProgresses()); + } + + @Test + public void childrenCanReportProgress() { + ProgressReporter progressReporter = ProgressReporter.withProgressListener(listener); + ProgressReporter child1 = progressReporter.createChild(); + ProgressReporter child2 = progressReporter.createChild(); + + progressReporter.reportProgress(1); + child1.reportProgress(7); + progressReporter.reportProgress(3); + child2.reportProgress(11); + progressReporter.reportProgress(5); + + assertEquals(Arrays.asList(1L, 8L, 11L, 22L, 27L), listener.getProgresses()); + } + + @Test + public void childrenCanResetProgress() { + ProgressReporter progressReporter = ProgressReporter.withProgressListener(listener); + ProgressReporter child1 = progressReporter.createChild(); + ProgressReporter child2 = progressReporter.createChild(); + + progressReporter.reportProgress(1); + child1.reportProgress(7); + child1.reset(); + progressReporter.reportProgress(3); + child2.reportProgress(11); + progressReporter.reportProgress(5); + child2.reset(); + + assertEquals(Arrays.asList(1L, 8L, 1L, 4L, 15L, 20L, 9L), listener.getProgresses()); + } + + @Test + public void testConcurrentReporting() throws ExecutionException, InterruptedException { + ProgressReporter progressReporter = ProgressReporter.withProgressListener(listener); + + ForkJoinPool pool = new ForkJoinPool(10); + try { + List> tasks = new ArrayList<>(); + for (int i = 0; i < 100; i++) { + tasks.add(() -> { + ProgressReporter child = progressReporter.createChild(); + child.reportProgress(1L); + child.reportProgress(3L); + child.reportProgress(5L); + child.reportProgress(7L); + child.reportProgress(11L); + return null; + }); + } + + List> asyncs = pool.invokeAll(tasks); + for (Future async : asyncs) { + async.get(); + } + } finally { + pool.shutdown(); + } + + List progresses = listener.getProgresses(); + assertEquals(2700L, progresses.get(progresses.size() - 1)); + for (int i = 0; i < progresses.size() - 1; i++) { + if (progresses.get(i + 1) <= progresses.get(i)) { + fail("Progresses are not in raising order. progress[" + (i + 1) + "]=" + progresses.get(i + 1) + + " progress[" + i + "]=" + progresses.get(i)); + } + } + } + + private static class ListProgressListener implements LongConsumer { + private final List progresses = Collections.synchronizedList(new ArrayList<>()); + + @Override + public void accept(long value) { + progresses.add(value); + } + + public List getProgresses() { + return Collections.unmodifiableList(progresses); + } + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/TestUtils.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/TestUtils.java new file mode 100644 index 000000000000..28ca120a48a8 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/TestUtils.java @@ -0,0 +1,178 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.utils; + +import io.clientcore.core.implementation.AccessibleByteArrayOutputStream; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.security.SecureRandom; +import java.util.Arrays; +import java.util.Objects; + +import static io.clientcore.core.utils.CoreUtils.isNullOrEmpty; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; + +/** + * Utility methods for testing {@code core}. + */ +public final class TestUtils { + private static final byte[] BYTES; + private static final int BYTES_LENGTH; + + static { + BYTES = new byte[1024 * 1024]; + + new SecureRandom().nextBytes(BYTES); + + BYTES_LENGTH = BYTES.length; + } + + /** + * Asserts that two arrays are equal in an optimized way when they are equal (common case). + * + * @param expected Expected array. + * @param actual Actual array. + */ + public static void assertArraysEqual(byte[] expected, byte[] actual) { + assertArraysEqual(expected, 0, expected.length, actual, actual.length); + } + + /** + * Asserts that two arrays are equal in an optimized way when they are equal (common case). + * + * @param expected Expected array. + * @param expectedOffset Offset to begin comparing in the expected array. + * @param expectedLength Amount of bytes to compare in the expected array. + * @param actual Actual array. + */ + public static void assertArraysEqual(byte[] expected, int expectedOffset, int expectedLength, byte[] actual) { + assertArraysEqual(expected, expectedOffset, expectedLength, actual, actual.length); + } + + /** + * Asserts that two arrays are equal in an optimized way when they are equal (common case). + * + * @param expected Expected array. + * @param expectedOffset Offset to begin comparing in the expected array. + * @param expectedLength Amount of bytes to compare in the expected array. + * @param actual Actual array. + * @param actualLength Amount of bytes to compare in the actual array. + */ + public static void assertArraysEqual(byte[] expected, int expectedOffset, int expectedLength, byte[] actual, + int actualLength) { + + if (!Objects.equals(ByteBuffer.wrap(expected, expectedOffset, expectedLength), + ByteBuffer.wrap(actual, 0, actualLength))) { + + assertArrayEquals(Arrays.copyOfRange(expected, expectedOffset, expectedOffset + expectedLength), + Arrays.copyOfRange(actual, 0, actualLength)); + } + } + + /** + * Fills the passed byte array with random bytes. + * + * @param array The array to fill. + */ + public static void fillArray(byte[] array) { + int size = array.length; + int count = size / BYTES_LENGTH; + int remainder = size % BYTES_LENGTH; + + for (int i = 0; i < count; i++) { + System.arraycopy(BYTES, 0, array, i * BYTES_LENGTH, BYTES_LENGTH); + } + + if (remainder > 0) { + System.arraycopy(BYTES, 0, array, count * BYTES_LENGTH, remainder); + } + } + + /** + * Reads an {@link InputStream} to completion returning its contents, using a read buffer. + * + * @param stream The stream to read. + * @return The byte array representing its contents. + * @throws IOException If an error happens during reading. + */ + public static byte[] readStream(InputStream stream) throws IOException { + return readStream(stream, 8 * 1024); + } + + /** + * Reads an {@link InputStream} to completion returning its contents, using a read buffer. + * + * @param stream The stream to read. + * @param bufferSize The size of the read buffer. + * @return The byte array representing its contents. + * @throws IOException If an error happens during reading. + */ + public static byte[] readStream(InputStream stream, int bufferSize) throws IOException { + AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(); + byte[] buffer = new byte[bufferSize]; + int length; + + while ((length = stream.read(buffer)) != -1) { + outputStream.write(buffer, 0, length); + } + + return outputStream.toByteArray(); + } + + /** + * Reads an {@link InputStream} to completion returning its contents, reading byte by byte. + * + * @param stream The stream to read. + * @return The byte array representing its contents. + * @throws IOException If an error happens during reading. + */ + public static byte[] readStreamByteByByte(InputStream stream) throws IOException { + AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(); + byte[] buffer = new byte[8192]; + int bufferPosition = 0; + int tmp; + + while ((tmp = stream.read()) != -1) { + if (bufferPosition >= 8192) { + outputStream.write(buffer); + bufferPosition = 0; + } + + buffer[bufferPosition++] = (byte) tmp; + } + + if (bufferPosition > 0) { + outputStream.write(buffer, 0, bufferPosition); + } + + return outputStream.toByteArray(); + } + + private TestUtils() { + } + + /** + * Returns the first instance of the given class from an array of Objects. + * + * @param args Array of objects to search through to find the first instance of the given `clazz` type. + * @param clazz The type trying to be found. + * @param Generic type + * @return The first object of the desired type, otherwise null. + */ + public static T findFirstOfType(Object[] args, Class clazz) { + if (isNullOrEmpty(args)) { + return null; + } + + for (Object arg : args) { + if (clazz.isInstance(arg)) { + return clazz.cast(arg); + } + } + + return null; + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/UnionTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/UnionTests.java new file mode 100644 index 000000000000..a113085d832d --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/UnionTests.java @@ -0,0 +1,474 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.utils; + +import io.clientcore.core.implementation.GenericParameterizedType; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.lang.reflect.Type; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Supplier; +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.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * Test class for {@link Union}. + */ +public class UnionTests { + private static final String STRING_VALUE = "Hello, world!"; + private static final int INT_VALUE = 42; + private static final long LONG_VALUE = 42L; + private static final double DOUBLE_VALUE = 3.11d; + private static final float FLOAT_VALUE = 3.11f; + + private static final String[] STRING_ARRAY_VALUE = { "Hello", "world", "!" }; + private static final int[] INT_ARRAY_VALUE = { 1, 2, 3 }; + private static final long[] LONG_ARRAY_VALUE = { 1L, 2L, 3L }; + private static final float[] FLOAT_ARRAY_VALUE = { 1.1f, 2.2f, 3.3f }; + private static final double[] DOUBLE_ARRAY_VALUE = { 1.1d, 2.2d, 3.3d }; + + private static final GenericParameterizedType LIST_OF_STRING_TYPE + = new GenericParameterizedType(List.class, String.class); + private static final GenericParameterizedType LIST_OF_INTEGER_TYPE + = new GenericParameterizedType(List.class, Integer.class); + private static final GenericParameterizedType LIST_OF_LONG_TYPE + = new GenericParameterizedType(List.class, Long.class); + private static final GenericParameterizedType LIST_OF_FLOAT_TYPE + = new GenericParameterizedType(List.class, Float.class); + private static final GenericParameterizedType LIST_OF_DOUBLE_TYPE + = new GenericParameterizedType(List.class, Double.class); + private static final GenericParameterizedType SET_OF_STRING_TYPE + = new GenericParameterizedType(Set.class, String.class); + + private static final List LIST_OF_STRING_VALUE = Arrays.asList("Hello", "world", "!"); + private static final List LIST_OF_INTEGER_VALUE = Arrays.asList(1, 2, 3); + private static final List LIST_OF_LONG_VALUE = Arrays.asList(1L, 2L, 3L); + private static final List LIST_OF_FLOAT_VALUE = Arrays.asList(1.1f, 2.2f, 3.3f); + private static final List LIST_OF_DOUBLE_VALUE = Arrays.asList(1.1d, 2.2d, 3.3d); + + private static final Set SET_OF_STRING_VALUE + = Collections.unmodifiableSet(new HashSet<>(Arrays.asList("Hello", "world", "!"))); + + @Test + void createUnionWithMultipleTypes() { + Union union = Union.ofTypes(String.class, Integer.class, Double.class); + assertNotNull(union); + assertEquals(3, union.getSupportedTypes().size()); + } + + @Test + void setAndGetValue() { + Union union = Union.ofTypes(String.class, Integer.class, Double.class); + + union.setValue(STRING_VALUE); + assertEquals(String.class, union.getCurrentType()); + assertEquals(STRING_VALUE, union.getValue()); + + union.setValue(INT_VALUE); + assertEquals(Integer.class, union.getCurrentType()); + assertEquals(INT_VALUE, union.getValue(Integer.class)); + + union.setValue(DOUBLE_VALUE); + assertEquals(Double.class, union.getCurrentType()); + assertEquals(DOUBLE_VALUE, union.getValue(Double.class)); + } + + @Test + void setValueWithInvalidType() { + Union union = Union.ofTypes(String.class, Integer.class, Double.class); + assertThrows(IllegalArgumentException.class, () -> union.setValue(LONG_VALUE)); + assertThrows(IllegalArgumentException.class, () -> union.setValue(FLOAT_VALUE)); + } + + @Test + void tryConsumeWithValidType() { + Union union = Union.ofTypes(String.class, Integer.class, Double.class); + union.setValue(STRING_VALUE); + assertTrue(union.tryConsume(value -> assertEquals(STRING_VALUE, value), String.class)); + union.setValue(INT_VALUE); + assertTrue(union.tryConsume(value -> assertEquals(INT_VALUE, value), Integer.class)); + union.setValue(DOUBLE_VALUE); + assertTrue(union.tryConsume(value -> assertEquals(DOUBLE_VALUE, value), Double.class)); + } + + @Test + void tryConsumeWithInvalidType() { + Union union = Union.ofTypes(String.class, Integer.class, Double.class); + + union.setValue(INT_VALUE); + assertTrue(union.tryConsume(value -> assertEquals(INT_VALUE, value), Integer.class)); + assertFalse(union.tryConsume(value -> fail("Should not consume String"), String.class)); + assertFalse(union.tryConsume(value -> fail("Should not consume Double"), Double.class)); + assertFalse(union.tryConsume(value -> fail("Should not consume Long"), Long.class)); + assertFalse(union.tryConsume(value -> fail("Should not consume Float"), Float.class)); + } + + // Autoboxing tests + + @Test + void createUnionWithMultipleTypesAutoboxing() { + Union union = Union.ofTypes(String.class, int.class, double.class); + union.setValue(STRING_VALUE); + assertEquals(String.class, union.getCurrentType()); + assertEquals(STRING_VALUE, union.getValue()); + + union.setValue(42); + assertEquals(int.class, union.getCurrentType()); + assertEquals(42, union.getValue(int.class)); + + union.setValue(DOUBLE_VALUE); + assertEquals(double.class, union.getCurrentType()); + assertEquals(DOUBLE_VALUE, union.getValue(double.class)); + } + + @Test + void setAndGetValueAutoboxing() { + Union union = Union.ofTypes(String.class, double.class, int.class); + union.setValue(STRING_VALUE); + assertEquals(String.class, union.getCurrentType()); + assertEquals(STRING_VALUE, union.getValue(String.class)); + + union.setValue(INT_VALUE); + assertEquals(int.class, union.getCurrentType()); + assertEquals(INT_VALUE, union.getValue(int.class)); + + union.setValue(DOUBLE_VALUE); + assertEquals(double.class, union.getCurrentType()); + assertEquals(DOUBLE_VALUE, union.getValue(double.class)); + } + + @Test + void setValueWithInvalidTypeAutoboxing() { + Union union = Union.ofTypes(String.class, int.class, double.class); + assertThrows(IllegalArgumentException.class, () -> union.setValue(FLOAT_VALUE)); + } + + @Test + void tryConsumeWithValidTypeAutoboxing() { + Union union = Union.ofTypes(String.class, int.class, double.class); + + union.setValue(STRING_VALUE); + assertEquals(String.class, union.getCurrentType()); + assertTrue(union.tryConsume(value -> assertEquals(STRING_VALUE, value), String.class)); + + union.setValue(INT_VALUE); + assertEquals(int.class, union.getCurrentType()); + assertTrue(union.tryConsume(value -> assertEquals(INT_VALUE, value), int.class)); + + union.setValue(DOUBLE_VALUE); + assertEquals(double.class, union.getCurrentType()); + assertTrue(union.tryConsume(value -> assertEquals(DOUBLE_VALUE, value), double.class)); + } + + @Test + void tryConsumeWithInvalidTypeAutoboxing() { + Union union = Union.ofTypes(String.class, int.class, double.class); + union.setValue(INT_VALUE); + assertTrue(union.tryConsume(value -> assertEquals(INT_VALUE, value), int.class)); + assertFalse(union.tryConsume(value -> fail("Should not consume String"), String.class)); + assertFalse(union.tryConsume(value -> fail("Should not consume Double"), Double.class)); + assertFalse(union.tryConsume(value -> fail("Should not consume Long"), Long.class)); + assertFalse(union.tryConsume(value -> fail("Should not consume Float"), Float.class)); + } + + // Array types tests + + @Test + void createUnionWithArrayTypes() { + Union union = Union.ofTypes(String[].class, int[].class, float[].class); + assertNotNull(union); + assertEquals(3, union.getSupportedTypes().size()); + } + + @Test + void setAndGetValueWithArrayTypes() { + Union union = Union.ofTypes(String[].class, int[].class, float[].class); + + union.setValue(STRING_ARRAY_VALUE); + assertEquals(String[].class, union.getCurrentType()); + assertArrayEquals(STRING_ARRAY_VALUE, union.getValue(String[].class)); + + union.setValue(INT_ARRAY_VALUE); + assertEquals(int[].class, union.getCurrentType()); + assertArrayEquals(INT_ARRAY_VALUE, union.getValue(int[].class)); + + union.setValue(FLOAT_ARRAY_VALUE); + assertEquals(float[].class, union.getCurrentType()); + assertArrayEquals(FLOAT_ARRAY_VALUE, union.getValue(float[].class)); + } + + @Test + void setValueWithInvalidArrayType() { + Union union = Union.ofTypes(String[].class, int[].class, float[].class); + assertThrows(IllegalArgumentException.class, () -> union.setValue(LONG_ARRAY_VALUE)); + assertThrows(IllegalArgumentException.class, () -> union.setValue(DOUBLE_ARRAY_VALUE)); + } + + @Test + void tryConsumeWithValidArrayType() { + Union union = Union.ofTypes(String[].class, int[].class, float[].class); + + union.setValue(STRING_ARRAY_VALUE); + assertTrue(union.tryConsume(value -> assertArrayEquals(STRING_ARRAY_VALUE, value), String[].class)); + + union.setValue(INT_ARRAY_VALUE); + assertTrue(union.tryConsume(value -> assertArrayEquals(INT_ARRAY_VALUE, value), int[].class)); + + union.setValue(FLOAT_ARRAY_VALUE); + assertTrue(union.tryConsume(value -> assertArrayEquals(FLOAT_ARRAY_VALUE, value), float[].class)); + } + + @Test + void tryConsumeWithInvalidArrayType() { + Union union = Union.ofTypes(String[].class, int[].class, float[].class); + union.setValue(INT_ARRAY_VALUE); + + assertTrue(union.tryConsume(value -> assertArrayEquals(INT_ARRAY_VALUE, value), int[].class)); + assertFalse(union.tryConsume(value -> fail("Should not consume Double"), double[].class)); + assertFalse(union.tryConsume(value -> fail("Should not consume Long"), long[].class)); + } + + // Parameterized types tests + + @Test + void createUnionWithParameterizedTypes() { + Union union = Union.ofTypes(LIST_OF_STRING_TYPE, LIST_OF_INTEGER_TYPE, LIST_OF_DOUBLE_TYPE); + assertNotNull(union); + assertEquals(3, union.getSupportedTypes().size()); + } + + @Test + void setAndGetValueWithParameterizedTypes() { + Union union = Union.ofTypes(LIST_OF_STRING_TYPE, LIST_OF_INTEGER_TYPE, LIST_OF_DOUBLE_TYPE); + + union.setValue(LIST_OF_STRING_VALUE); + assertEquals(LIST_OF_STRING_TYPE, union.getCurrentType()); + assertEquals(LIST_OF_STRING_VALUE, union.getValue(LIST_OF_STRING_TYPE)); + + union.setValue(LIST_OF_INTEGER_VALUE); + assertEquals(LIST_OF_INTEGER_TYPE, union.getCurrentType()); + assertEquals(LIST_OF_INTEGER_VALUE, union.getValue(LIST_OF_INTEGER_TYPE)); + + union.setValue(LIST_OF_DOUBLE_VALUE); + assertEquals(LIST_OF_DOUBLE_TYPE, union.getCurrentType()); + assertEquals(LIST_OF_DOUBLE_VALUE, union.getValue(LIST_OF_DOUBLE_TYPE)); + } + + @Test + void setValueWithInvalidParameterizedType() { + Union union = Union.ofTypes(LIST_OF_STRING_TYPE, LIST_OF_INTEGER_TYPE, LIST_OF_DOUBLE_TYPE); + + assertThrows(IllegalArgumentException.class, () -> union.setValue(LIST_OF_LONG_VALUE)); + assertThrows(IllegalArgumentException.class, () -> union.setValue(LIST_OF_FLOAT_VALUE)); + assertThrows(IllegalArgumentException.class, () -> union.setValue(SET_OF_STRING_VALUE)); + } + + @Test + void tryConsumeWithValidParameterizedType() { + Union union = Union.ofTypes(LIST_OF_STRING_TYPE, LIST_OF_INTEGER_TYPE, LIST_OF_DOUBLE_TYPE); + + union.setValue(LIST_OF_STRING_VALUE); + assertTrue(union.tryConsume(value -> assertEquals(LIST_OF_STRING_VALUE, value), LIST_OF_STRING_TYPE)); + + union.setValue(LIST_OF_INTEGER_VALUE); + assertTrue(union.tryConsume(value -> assertEquals(LIST_OF_INTEGER_VALUE, value), LIST_OF_INTEGER_TYPE)); + + union.setValue(LIST_OF_DOUBLE_VALUE); + assertTrue(union.tryConsume(value -> assertEquals(LIST_OF_DOUBLE_VALUE, value), LIST_OF_DOUBLE_TYPE)); + } + + @Test + void tryConsumeWithInvalidParameterizedType() { + Union union = Union.ofTypes(LIST_OF_STRING_TYPE, LIST_OF_INTEGER_TYPE, LIST_OF_DOUBLE_TYPE, LIST_OF_FLOAT_TYPE); + + union.setValue(LIST_OF_INTEGER_VALUE); + assertTrue(union.tryConsume(value -> assertEquals(LIST_OF_INTEGER_VALUE, value), LIST_OF_INTEGER_TYPE)); + assertFalse(union.tryConsume(value -> fail("Should not consume List"), LIST_OF_STRING_TYPE)); + assertFalse(union.tryConsume(value -> fail("Should not consume List"), LIST_OF_LONG_TYPE)); + assertFalse(union.tryConsume(value -> fail("Should not consume List"), LIST_OF_FLOAT_TYPE)); + assertFalse(union.tryConsume(value -> fail("Should not consume List"), LIST_OF_DOUBLE_TYPE)); + assertFalse(union.tryConsume(value -> fail("Should not consume Set"), SET_OF_STRING_TYPE)); + } + + // Additional tests + @ParameterizedTest + @MethodSource("invalidUnionOfTypesSupplier") + public void invalidUnionOfTypes(Supplier unionSupplier) { + assertThrows(IllegalArgumentException.class, unionSupplier::get); + } + + private static Stream> invalidUnionOfTypesSupplier() { + return Stream.of( + // null array + () -> Union.ofTypes((Type[]) null), + + // empty array + () -> Union.ofTypes(), + + // null type in array + () -> Union.ofTypes(String.class, null, int.class), + + // unknown type + () -> Union.ofTypes(new Type() { + })); + } + + @Test + void setAndGetValueWithNull() { + Union union = Union.ofTypes(String.class, Integer.class, Double.class); + union.setValue(null); + assertNull(union.getValue()); + } + + @Test + void setAndGetValueWithEmptyCollection() { + Union union = Union.ofTypes(LIST_OF_STRING_TYPE); + List emptyList = Arrays.asList(); + union.setValue(emptyList); + assertEquals(LIST_OF_STRING_TYPE, union.getCurrentType()); + assertEquals(emptyList, union.getValue(LIST_OF_STRING_TYPE)); + } + + @Test + void setValueWithMixedTypeCollection() { + Union union = Union.ofTypes(LIST_OF_STRING_TYPE); + + List mixedList = Arrays.asList("Hello", 1); + assertThrows(IllegalArgumentException.class, () -> union.setValue(mixedList)); + } + + @Test + void setAndGetValueWithNestedParameterizedType() { + GenericParameterizedType listOfListOfString + = new GenericParameterizedType(List.class, new GenericParameterizedType(List.class, String.class)); + Union union = Union.ofTypes(listOfListOfString); + + List> nestedList = Arrays.asList(LIST_OF_STRING_VALUE); + union.setValue(nestedList); + assertEquals(listOfListOfString, union.getCurrentType()); + assertEquals(nestedList, union.getValue(listOfListOfString)); + } + + @Test + void setAndGetValueWithPrimitiveArray() { + Union union = Union.ofTypes(int[].class, double[].class); + + union.setValue(INT_ARRAY_VALUE); + assertEquals(int[].class, union.getCurrentType()); + assertArrayEquals(INT_ARRAY_VALUE, union.getValue(int[].class)); + + union.setValue(DOUBLE_ARRAY_VALUE); + assertEquals(double[].class, union.getCurrentType()); + assertArrayEquals(DOUBLE_ARRAY_VALUE, union.getValue(double[].class)); + } + + @Test + void setAndGetValueWithDeeplyNestedParameterizedType() { + GenericParameterizedType listOfListOfListOfString + = new GenericParameterizedType(List.class, new GenericParameterizedType(List.class, LIST_OF_STRING_TYPE)); + Union union = Union.ofTypes(listOfListOfListOfString); + + List>> deeplyNestedList = Arrays.asList(Arrays.asList(LIST_OF_STRING_VALUE)); + union.setValue(deeplyNestedList); + assertEquals(listOfListOfListOfString, union.getCurrentType()); + assertEquals(deeplyNestedList, union.getValue(listOfListOfListOfString)); + } + + @Test + void setAndGetValueWithMixedParameterizedTypesAndClass() { + Union union = Union.ofTypes(LIST_OF_STRING_TYPE, SET_OF_STRING_TYPE, String.class); + + union.setValue(LIST_OF_STRING_VALUE); + assertEquals(LIST_OF_STRING_TYPE, union.getCurrentType()); + assertEquals(LIST_OF_STRING_VALUE, union.getValue(LIST_OF_STRING_TYPE)); + + union.setValue(SET_OF_STRING_VALUE); + assertEquals(SET_OF_STRING_TYPE, union.getCurrentType()); + assertEquals(SET_OF_STRING_VALUE, union.getValue(SET_OF_STRING_TYPE)); + + union.setValue(STRING_VALUE); + assertEquals(String.class, union.getCurrentType()); + assertEquals(STRING_VALUE, union.getValue(String.class)); + } + + @Test + void unionWithMap() { + Union union = Union.ofTypes(String.class, Integer.class, Map.class); + String key = "key"; + String value = "value"; + Map map = Collections.singletonMap(key, value); + union.setValue(map); + + assertEquals(Map.class, union.getCurrentType()); + assertEquals(map, union.getValue(Map.class)); + + union.tryConsume(map1 -> assertEquals(value, map1.get(key)), Map.class); + + assertFalse(union.tryConsume(ignore -> fail("Should not consume List"), LIST_OF_FLOAT_TYPE)); + } + + @Test + void unionWithBooleanShortBytes() { + Union union = Union.ofTypes(Boolean.class, Short.class, Byte.class); + union.setValue(true); + assertEquals(Boolean.class, union.getCurrentType()); + assertEquals(true, union.getValue(boolean.class)); + + union.setValue((short) 1); + assertEquals(Short.class, union.getCurrentType()); + assertEquals((short) 1, union.getValue(Short.class)); + union.setValue((byte) 1); + assertEquals(Byte.class, union.getCurrentType()); + assertEquals((byte) 1, union.getValue(Byte.class)); + + assertFalse(union.tryConsume(ignore -> fail("Should not consume List"), LIST_OF_FLOAT_TYPE)); + } + + @Test + void unionWithNestedUnion() { + Union union = Union.ofTypes(String.class, Union.class); + Union nestedUnion = Union.ofTypes(String.class, Integer.class, Double.class); + nestedUnion = nestedUnion.setValue(STRING_VALUE); + union.setValue(nestedUnion); + + assertEquals(Union.class, union.getCurrentType()); + Union unionValue = union.getValue(Union.class); + assertNotNull(unionValue); + assertEquals(nestedUnion, unionValue); + assertEquals(STRING_VALUE, unionValue.getValue()); + } + + @Test + public void getValueWithSuperType() { + Union union = Union.ofTypes(Long.class, Integer.class); + union.setValue(1L); + + Number number = union.getValue(Number.class); + assertEquals(1L, number.longValue()); + } + + @Test + public void getValueWithSubType() { + Union union = Union.ofTypes(Number.class); + union.setValue(1L); + + Long number = union.getValue(Long.class); + assertEquals(1L, number.longValue()); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/UriBuilderTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/UriBuilderTests.java new file mode 100644 index 000000000000..e60b0f979c49 --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/UriBuilderTests.java @@ -0,0 +1,739 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.utils; + +import org.junit.jupiter.api.Test; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class UriBuilderTests { + @Test + public void scheme() { + final UriBuilder builder = new UriBuilder().setScheme("http"); + assertEquals("http://", builder.toString()); + } + + @Test + public void schemeWhenSchemeIsNull() { + final UriBuilder builder = new UriBuilder().setScheme("http"); + builder.setScheme(null); + assertNull(builder.getScheme()); + } + + @Test + public void schemeWhenSchemeIsEmpty() { + final UriBuilder builder = new UriBuilder().setScheme("http"); + builder.setScheme(""); + assertNull(builder.getScheme()); + } + + @Test + public void schemeWhenSchemeIsNotEmpty() { + final UriBuilder builder = new UriBuilder().setScheme("http"); + builder.setScheme("https"); + assertEquals("https", builder.getScheme()); + } + + @Test + public void schemeWhenSchemeContainsTerminator() { + final UriBuilder builder = new UriBuilder().setScheme("http://"); + assertEquals("http", builder.getScheme()); + assertNull(builder.getHost()); + assertEquals("http://", builder.toString()); + } + + @Test + public void schemeWhenSchemeContainsHost() { + final UriBuilder builder = new UriBuilder().setScheme("http://www.example.com"); + assertEquals("http", builder.getScheme()); + assertEquals("www.example.com", builder.getHost()); + assertEquals("http://www.example.com", builder.toString()); + } + + @Test + public void schemeAndHost() { + final UriBuilder builder = new UriBuilder().setScheme("http").setHost("www.example.com"); + assertEquals("http://www.example.com", builder.toString()); + } + + @Test + public void schemeAndHostWhenHostHasWhitespace() { + final UriBuilder builder = new UriBuilder().setScheme("http").setHost("www.exa mple.com"); + assertEquals("http://www.exa mple.com", builder.toString()); + } + + @Test + public void host() { + final UriBuilder builder = new UriBuilder().setHost("www.example.com"); + assertEquals("www.example.com", builder.toString()); + } + + @Test + public void hostWhenHostIsNull() { + final UriBuilder builder = new UriBuilder().setHost("www.example.com"); + builder.setHost(null); + assertNull(builder.getHost()); + } + + @Test + public void hostWhenHostIsEmpty() { + final UriBuilder builder = new UriBuilder().setHost("www.example.com"); + builder.setHost(""); + assertNull(builder.getHost()); + } + + @Test + public void hostWhenHostIsNotEmpty() { + final UriBuilder builder = new UriBuilder().setHost("www.example.com"); + builder.setHost("www.bing.com"); + assertEquals("www.bing.com", builder.getHost()); + } + + @Test + public void hostWhenHostContainsSchemeTerminator() { + final UriBuilder builder = new UriBuilder().setHost("://www.example.com"); + assertNull(builder.getScheme()); + assertEquals("www.example.com", builder.getHost()); + assertEquals("www.example.com", builder.toString()); + } + + @Test + public void hostWhenHostContainsScheme() { + final UriBuilder builder = new UriBuilder().setHost("https://www.example.com"); + assertEquals("https", builder.getScheme()); + assertEquals("www.example.com", builder.getHost()); + assertEquals("https://www.example.com", builder.toString()); + } + + @Test + public void hostWhenHostContainsColonButNoPort() { + final UriBuilder builder = new UriBuilder().setHost("www.example.com:"); + assertEquals("www.example.com", builder.getHost()); + assertNull(builder.getPort()); + assertEquals("www.example.com", builder.toString()); + } + + @Test + public void hostWhenHostContainsPort() { + final UriBuilder builder = new UriBuilder().setHost("www.example.com:1234"); + assertEquals("www.example.com", builder.getHost()); + assertEquals(1234, builder.getPort()); + assertEquals("www.example.com:1234", builder.toString()); + } + + @Test + public void hostWhenHostContainsForwardSlashButNoPath() { + final UriBuilder builder = new UriBuilder().setHost("www.example.com/"); + assertEquals("www.example.com", builder.getHost()); + assertEquals("/", builder.getPath()); + assertEquals("www.example.com/", builder.toString()); + } + + @Test + public void hostWhenHostContainsPath() { + final UriBuilder builder = new UriBuilder().setHost("www.example.com/index.html"); + assertEquals("www.example.com", builder.getHost()); + assertEquals("/index.html", builder.getPath()); + assertEquals("www.example.com/index.html", builder.toString()); + } + + @Test + public void hostWhenHostContainsQuestionMarkButNoQuery() { + final UriBuilder builder = new UriBuilder().setHost("www.example.com?"); + assertEquals("www.example.com", builder.getHost()); + assertEquals(0, builder.getQuery().size()); + assertEquals("www.example.com", builder.toString()); + } + + @Test + public void hostWhenHostContainsQuery() { + final UriBuilder builder = new UriBuilder().setHost("www.example.com?a=b"); + assertEquals("www.example.com", builder.getHost()); + assertTrue(builder.toString().contains("a=b"), "Expected 'a=b' in " + builder); + assertEquals("www.example.com?a=b", builder.toString()); + } + + @Test + public void hostWhenHostHasWhitespace() { + final UriBuilder builder = new UriBuilder().setHost("www.exampl e.com"); + assertEquals("www.exampl e.com", builder.toString()); + } + + @Test + public void hostAndPath() { + final UriBuilder builder = new UriBuilder().setHost("www.example.com").setPath("my/path"); + assertEquals("www.example.com/my/path", builder.toString()); + } + + @Test + public void hostAndPathWithSlashAfterHost() { + final UriBuilder builder = new UriBuilder().setHost("www.example.com/").setPath("my/path"); + assertEquals("www.example.com/my/path", builder.toString()); + } + + @Test + public void hostAndPathWithSlashBeforePath() { + final UriBuilder builder = new UriBuilder().setHost("www.example.com").setPath("/my/path"); + assertEquals("www.example.com/my/path", builder.toString()); + } + + @Test + public void hostAndPathWithSlashAfterHostAndBeforePath() { + final UriBuilder builder = new UriBuilder().setHost("www.example.com/").setPath("/my/path"); + assertEquals("www.example.com/my/path", builder.toString()); + } + + @Test + public void hostAndPathWithWhitespaceInPath() { + final UriBuilder builder = new UriBuilder().setHost("www.example.com").setPath("my path"); + assertEquals("www.example.com/my path", builder.toString()); + } + + @Test + public void hostAndPathWithPlusInPath() { + final UriBuilder builder = new UriBuilder().setHost("www.example.com").setPath("my+path"); + assertEquals("www.example.com/my+path", builder.toString()); + } + + @Test + public void hostAndPathWithPercent20InPath() { + final UriBuilder builder = new UriBuilder().setHost("www.example.com").setPath("my%20path"); + assertEquals("www.example.com/my%20path", builder.toString()); + } + + @Test + public void portInt() { + final UriBuilder builder = new UriBuilder().setPort(50); + assertEquals(50, builder.getPort()); + assertEquals(":50", builder.toString()); + } + + @Test + public void portStringWithNull() { + final UriBuilder builder = new UriBuilder().setPort(null); + assertNull(builder.getPort()); + assertEquals("", builder.toString()); + } + + @Test + public void portStringWithEmpty() { + final UriBuilder builder = new UriBuilder().setPort(""); + assertNull(builder.getPort()); + assertEquals("", builder.toString()); + } + + @Test + public void portString() { + final UriBuilder builder = new UriBuilder().setPort("50"); + assertEquals(50, builder.getPort()); + assertEquals(":50", builder.toString()); + } + + @Test + public void portStringWithForwardSlashButNoPath() { + final UriBuilder builder = new UriBuilder().setPort("50/"); + assertEquals(50, builder.getPort()); + assertEquals("/", builder.getPath()); + assertEquals(":50/", builder.toString()); + } + + @Test + public void portStringPath() { + final UriBuilder builder = new UriBuilder().setPort("50/index.html"); + assertEquals(50, builder.getPort()); + assertEquals("/index.html", builder.getPath()); + assertEquals(":50/index.html", builder.toString()); + } + + @Test + public void portStringWithQuestionMarkButNoQuery() { + final UriBuilder builder = new UriBuilder().setPort("50?"); + assertEquals(50, builder.getPort()); + assertEquals(0, builder.getQuery().size()); + assertEquals(":50", builder.toString()); + } + + @Test + public void portStringQuery() { + final UriBuilder builder = new UriBuilder().setPort("50?a=b&c=d"); + assertEquals(50, builder.getPort()); + assertTrue(builder.toString().contains("?a=b&c=d"), "Expected '?a=b&c=d' in " + builder); + assertEquals(":50?a=b&c=d", builder.toString()); + } + + @Test + public void portStringWhenPortIsNull() { + final UriBuilder builder = new UriBuilder().setPort(8080); + builder.setPort(null); + assertNull(builder.getPort()); + } + + @Test + public void portStringWhenPortIsEmpty() { + final UriBuilder builder = new UriBuilder().setPort(8080); + builder.setPort(""); + assertNull(builder.getPort()); + } + + @Test + public void portStringWhenPortIsNotEmpty() { + final UriBuilder builder = new UriBuilder().setPort(8080); + builder.setPort("132"); + assertEquals(132, builder.getPort()); + } + + @Test + public void schemeAndHostAndOneQueryParameter() { + final UriBuilder builder + = new UriBuilder().setScheme("http").setHost("www.example.com").setQueryParameter("A", "B"); + assertEquals("http://www.example.com?A=B", builder.toString()); + } + + @Test + public void schemeAndHostAndPathAndOneQueryParameterGetQuery() { + final UriBuilder builder + = new UriBuilder().setScheme("http").setHost("www.example.com").setQueryParameter("A", "B"); + assertEquals(builder.getQuery().get("A"), "B"); + } + + @Test + public void schemeAndHostAndOneQueryParameterWhenQueryParameterNameHasWhitespace() { + final UriBuilder builder + = new UriBuilder().setScheme("http").setHost("www.example.com").setQueryParameter("App les", "B"); + assertEquals("http://www.example.com?App les=B", builder.toString()); + } + + @Test + public void schemeAndHostAndOneQueryParameterWhenQueryParameterNameHasPercent20() { + final UriBuilder builder + = new UriBuilder().setScheme("http").setHost("www.example.com").setQueryParameter("App%20les", "B"); + assertEquals("http://www.example.com?App%20les=B", builder.toString()); + } + + @Test + public void schemeAndHostAndOneQueryParameterWhenQueryParameterValueHasWhitespace() { + final UriBuilder builder + = new UriBuilder().setScheme("http").setHost("www.example.com").setQueryParameter("Apples", "Go od"); + assertEquals("http://www.example.com?Apples=Go od", builder.toString()); + } + + @Test + public void schemeAndHostAndOneQueryParameterWhenQueryParameterValueHasPercent20() { + final UriBuilder builder + = new UriBuilder().setScheme("http").setHost("www.example.com").setQueryParameter("Apples", "Go%20od"); + assertEquals("http://www.example.com?Apples=Go%20od", builder.toString()); + } + + @Test + public void schemeAndHostAndTwoQueryParameters() { + final UriBuilder builder = new UriBuilder().setScheme("http") + .setHost("www.example.com") + .setQueryParameter("A", "B") + .setQueryParameter("C", "D"); + assertEquals("http://www.example.com?A=B&C=D", builder.toString()); + } + + @Test + public void schemeAndHostAndPathAndTwoQueryParameters() { + final UriBuilder builder = new UriBuilder().setScheme("http") + .setHost("www.example.com") + .setQueryParameter("A", "B") + .setQueryParameter("C", "D") + .setPath("index.html"); + assertEquals("http://www.example.com/index.html?A=B&C=D", builder.toString()); + } + + @Test + public void schemeAndHostAndPathAndTwoIdenticalQueryParameters() { + final UriBuilder builder = new UriBuilder().setScheme("http") + .setHost("www.example.com") + .addQueryParameter("A", "B") + .addQueryParameter("A", "D") + .setPath("index.html"); + assertEquals("http://www.example.com/index.html?A=B&A=D", builder.toString()); + } + + @Test + public void schemeAndHostAndPathAndTwoIdenticalQueryParametersGetQuery() { + final UriBuilder builder = new UriBuilder().setScheme("http") + .setHost("www.example.com") + .addQueryParameter("A", "B") + .addQueryParameter("A", "D") + .setPath("index.html"); + assertEquals(builder.getQuery().get("A"), "B,D"); + } + + @Test + public void pathWhenBuilderPathIsNullAndPathIsNull() { + final UriBuilder builder = new UriBuilder(); + builder.setPath(null); + assertNull(builder.getPath()); + } + + @Test + public void pathWhenBuilderPathIsNullAndPathIsEmptyString() { + final UriBuilder builder = new UriBuilder(); + builder.setPath(""); + assertNull(builder.getPath()); + } + + @Test + public void pathWhenBuilderPathIsNullAndPathIsForwardSlash() { + final UriBuilder builder = new UriBuilder(); + builder.setPath("/"); + assertEquals("/", builder.getPath()); + } + + @Test + public void pathWhenBuilderPathIsNullAndPath() { + final UriBuilder builder = new UriBuilder(); + builder.setPath("test/path.html"); + assertEquals("test/path.html", builder.getPath()); + } + + @Test + public void pathWhenBuilderPathIsForwardSlashAndPathIsNull() { + final UriBuilder builder = new UriBuilder().setPath("/"); + builder.setPath(null); + assertNull(builder.getPath()); + } + + @Test + public void pathWhenBuilderPathIsForwardSlashAndPathIsEmptyString() { + final UriBuilder builder = new UriBuilder().setPath("/"); + builder.setPath(""); + assertNull(builder.getPath()); + } + + @Test + public void pathWhenBuilderPathIsForwardSlashAndPathIsForwardSlash() { + final UriBuilder builder = new UriBuilder().setPath("/"); + builder.setPath("/"); + assertEquals("/", builder.getPath()); + } + + @Test + public void pathWhenBuilderPathIsForwardSlashAndPath() { + final UriBuilder builder = new UriBuilder().setPath("/"); + builder.setPath("test/path.html"); + assertEquals("test/path.html", builder.getPath()); + } + + @Test + public void pathWhenHostContainsPath() { + final UriBuilder builder = new UriBuilder().setHost("www.example.com/site").setPath("index.html"); + assertEquals("www.example.com", builder.getHost()); + assertEquals("index.html", builder.getPath()); + assertEquals("www.example.com/index.html", builder.toString()); + } + + @Test + public void pathFirstWhenHostContainsPath() { + final UriBuilder builder = new UriBuilder().setPath("index.html").setHost("www.example.com/site"); + assertEquals("www.example.com", builder.getHost()); + assertEquals("/site", builder.getPath()); + assertEquals("www.example.com/site", builder.toString()); + } + + @Test + public void emptyPathWhenHostContainsPath() { + final UriBuilder builder = new UriBuilder().setPath("").setHost("www.example.com/site"); + assertEquals("www.example.com", builder.getHost()); + assertEquals("/site", builder.getPath()); + assertEquals("www.example.com/site", builder.toString()); + } + + @Test + public void slashPathWhenHostContainsPath() { + final UriBuilder builder = new UriBuilder().setPath("//").setHost("www.example.com/site"); + assertEquals("www.example.com", builder.getHost()); + assertEquals("/site", builder.getPath()); + assertEquals("www.example.com/site", builder.toString()); + } + + @Test + public void withAbsolutePath() { + final UriBuilder builder + = new UriBuilder().setScheme("http").setHost("www.example.com").setPath("http://www.othersite.com"); + assertEquals("http://www.othersite.com", builder.toString()); + } + + @Test + public void queryInPath() { + final UriBuilder builder = new UriBuilder().setScheme("http") + .setHost("www.example.com") + .setPath("mypath?thing=stuff") + .setQueryParameter("otherthing", "otherstuff"); + assertEquals("http://www.example.com/mypath?thing=stuff&otherthing=otherstuff", builder.toString()); + } + + @Test + public void withAbsolutePathAndQuery() { + final UriBuilder builder = new UriBuilder().setScheme("http") + .setHost("www.example.com") + .setPath("http://www.othersite.com/mypath?thing=stuff") + .setQueryParameter("otherthing", "otherstuff"); + assertEquals("http://www.othersite.com/mypath?thing=stuff&otherthing=otherstuff", builder.toString()); + } + + @Test + public void queryWithNull() { + final UriBuilder builder = new UriBuilder().setQuery(null); + assertEquals(0, builder.getQuery().size()); + assertEquals("", builder.toString()); + } + + @Test + public void queryWithEmpty() { + final UriBuilder builder = new UriBuilder().setQuery(""); + assertEquals(0, builder.getQuery().size()); + assertEquals("", builder.toString()); + } + + @Test + public void queryWithQuestionMark() { + final UriBuilder builder = new UriBuilder().setQuery("?"); + assertEquals(0, builder.getQuery().size()); + assertEquals("", builder.toString()); + } + + @Test + public void parseWithNullString() { + final UriBuilder builder = UriBuilder.parse((String) null); + assertEquals("", builder.toString()); + } + + @Test + public void parseWithEmpty() { + final UriBuilder builder = UriBuilder.parse(""); + assertEquals("", builder.toString()); + } + + @Test + public void parseHost() { + final UriBuilder builder = UriBuilder.parse("www.bing.com"); + assertEquals("www.bing.com", builder.toString()); + } + + @Test + public void parseWithProtocolAndHost() { + final UriBuilder builder = UriBuilder.parse("https://www.bing.com"); + assertEquals("https://www.bing.com", builder.toString()); + } + + @Test + public void parseHostAndPort() { + final UriBuilder builder = UriBuilder.parse("www.bing.com:8080"); + assertEquals("www.bing.com:8080", builder.toString()); + } + + @Test + public void parseWithProtocolAndHostAndPort() { + final UriBuilder builder = UriBuilder.parse("ftp://www.bing.com:8080"); + assertEquals("ftp://www.bing.com:8080", builder.toString()); + } + + @Test + public void parseHostAndPath() { + final UriBuilder builder = UriBuilder.parse("www.bing.com/my/path"); + assertEquals("www.bing.com/my/path", builder.toString()); + } + + @Test + public void parseWithProtocolAndHostAndPath() { + final UriBuilder builder = UriBuilder.parse("ftp://www.bing.com/my/path"); + assertEquals("ftp://www.bing.com/my/path", builder.toString()); + } + + @Test + public void parseHostAndPortAndPath() { + final UriBuilder builder = UriBuilder.parse("www.bing.com:1234/my/path"); + assertEquals("www.bing.com:1234/my/path", builder.toString()); + } + + @Test + public void parseWithProtocolAndHostAndPortAndPath() { + final UriBuilder builder = UriBuilder.parse("ftp://www.bing.com:2345/my/path"); + assertEquals("ftp://www.bing.com:2345/my/path", builder.toString()); + } + + @Test + public void parseHostAndOneQueryParameter() { + final UriBuilder builder = UriBuilder.parse("www.bing.com?a=1"); + assertEquals("www.bing.com?a=1", builder.toString()); + } + + @Test + public void parseWithProtocolAndHostAndOneQueryParameter() { + final UriBuilder builder = UriBuilder.parse("https://www.bing.com?a=1"); + assertEquals("https://www.bing.com?a=1", builder.toString()); + } + + @Test + public void parseHostAndPortAndOneQueryParameter() { + final UriBuilder builder = UriBuilder.parse("www.bing.com:123?a=1"); + assertEquals("www.bing.com:123?a=1", builder.toString()); + } + + @Test + public void parseWithProtocolAndHostAndPortAndOneQueryParameter() { + final UriBuilder builder = UriBuilder.parse("https://www.bing.com:987?a=1"); + assertEquals("https://www.bing.com:987?a=1", builder.toString()); + } + + @Test + public void parseHostAndPathAndOneQueryParameter() { + final UriBuilder builder = UriBuilder.parse("www.bing.com/folder/index.html?a=1"); + assertEquals("www.bing.com/folder/index.html?a=1", builder.toString()); + } + + @Test + public void parseWithProtocolAndHostAndPathAndOneQueryParameter() { + final UriBuilder builder = UriBuilder.parse("https://www.bing.com/image.gif?a=1"); + assertEquals("https://www.bing.com/image.gif?a=1", builder.toString()); + } + + @Test + public void parseHostAndPortAndPathAndOneQueryParameter() { + final UriBuilder builder = UriBuilder.parse("www.bing.com:123/index.html?a=1"); + assertEquals("www.bing.com:123/index.html?a=1", builder.toString()); + } + + @Test + public void parseWithProtocolAndHostAndPortAndPathAndOneQueryParameter() { + final UriBuilder builder = UriBuilder.parse("https://www.bing.com:987/my/path/again?a=1"); + assertEquals("https://www.bing.com:987/my/path/again?a=1", builder.toString()); + } + + @Test + public void parseHostAndTwoQueryParameters() { + final UriBuilder builder = UriBuilder.parse("www.bing.com?a=1&b=2"); + assertEquals("www.bing.com?a=1&b=2", builder.toString()); + } + + @Test + public void parseWithProtocolAndHostAndTwoQueryParameters() { + final UriBuilder builder = UriBuilder.parse("https://www.bing.com?a=1&b=2"); + assertEquals("https://www.bing.com?a=1&b=2", builder.toString()); + } + + @Test + public void parseHostAndPortAndTwoQueryParameters() { + final UriBuilder builder = UriBuilder.parse("www.bing.com:123?a=1&b=2"); + assertEquals("www.bing.com:123?a=1&b=2", builder.toString()); + } + + @Test + public void parseWithProtocolAndHostAndPortAndTwoQueryParameters() { + final UriBuilder builder = UriBuilder.parse("https://www.bing.com:987?a=1&b=2"); + assertEquals("https://www.bing.com:987?a=1&b=2", builder.toString()); + } + + @Test + public void parseHostAndPathAndTwoQueryParameters() { + final UriBuilder builder = UriBuilder.parse("www.bing.com/folder/index.html?a=1&b=2"); + assertEquals("www.bing.com/folder/index.html?a=1&b=2", builder.toString()); + } + + @Test + public void parseHostAndPathAndTwoIdenticalQueryParameters() { + final UriBuilder builder = UriBuilder.parse("www.bing.com/folder/index.html?a=1&a=2"); + assertEquals("www.bing.com/folder/index.html?a=1&a=2", builder.toString()); + } + + @Test + public void parseWithProtocolAndHostAndPathAndTwoQueryParameters() { + final UriBuilder builder = UriBuilder.parse("https://www.bing.com/image.gif?a=1&b=2"); + assertEquals("https://www.bing.com/image.gif?a=1&b=2", builder.toString()); + } + + @Test + public void parseHostAndPortAndPathAndTwoQueryParameters() { + final UriBuilder builder = UriBuilder.parse("www.bing.com:123/index.html?a=1&b=2"); + assertEquals("www.bing.com:123/index.html?a=1&b=2", builder.toString()); + } + + @Test + public void parseWithProtocolAndHostAndPortAndPathAndTwoQueryParameters() { + final UriBuilder builder = UriBuilder.parse("https://www.bing.com:987/my/path/again?a=1&b=2"); + assertEquals("https://www.bing.com:987/my/path/again?a=1&b=2", builder.toString()); + } + + @Test + public void parseWithColonInPath() { + final UriBuilder builder = UriBuilder.parse("https://www.bing.com/my:/path"); + assertEquals("https://www.bing.com/my:/path", builder.toString()); + } + + @Test + public void parseURIWithNull() { + final UriBuilder builder = UriBuilder.parse((URI) null); + assertEquals("", builder.toString()); + } + + @Test + public void parseURISchemeAndHost() { + final UriBuilder builder = UriBuilder.parse(URI.create("http://www.bing.com")); + assertEquals("http://www.bing.com", builder.toString()); + } + + @Test + public void parseUriEverything() { + final UriBuilder builder = UriBuilder.parse(URI.create("https://www.bing.com:123/index.html?a=1&b=2")); + assertEquals("https://www.bing.com:123/index.html?a=1&b=2", builder.toString()); + } + + @Test + public void parallelParsing() throws InterruptedException { + AtomicInteger callCount = new AtomicInteger(); + List> tasks = IntStream.range(0, 20000).mapToObj(i -> (Callable) () -> { + callCount.incrementAndGet(); + return UriBuilder.parse("https://example" + i + ".com"); + }).collect(Collectors.toCollection(() -> new ArrayList<>(20000))); + + List> futures = SharedExecutorService.getInstance().invokeAll(tasks, 10, TimeUnit.SECONDS); + for (Future future : futures) { + assertTrue(future.isDone()); + assertDoesNotThrow(() -> future.get()); + } + assertEquals(20000, callCount.get()); + } + + @Test + public void parseUniqueURIs() { + IntStream.range(0, 20000).parallel().forEach(i -> { + UriBuilder uriBuilder = io.clientcore.core.utils.UriBuilder.parse("www.bing.com:123/index.html?a=" + i); + assertNotNull(uriBuilder); + assertEquals("www.bing.com:123/index.html?a=" + i, uriBuilder.toString()); + }); + + // validate the size of the cache is not greater than 10000 + assertTrue(UriBuilder.getParsedUris().size() <= 10000); + } + + @Test + public void clearQuery() { + final UriBuilder builder = new UriBuilder().setScheme("http") + .setHost("www.example.com") + .setQueryParameter("A", "B") + .setQueryParameter("C", "D"); + assertEquals("http://www.example.com?A=B&C=D", builder.toString()); + builder.clearQuery(); + assertEquals("http://www.example.com", builder.toString()); + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/serializers/JsonSerializerTests.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/serializers/JsonSerializerTests.java new file mode 100644 index 000000000000..c3e911bd159b --- /dev/null +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/serializers/JsonSerializerTests.java @@ -0,0 +1,362 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.utils.serializers; + +import io.clientcore.core.http.models.HttpMethod; +import io.clientcore.core.implementation.AccessibleByteArrayOutputStream; +import io.clientcore.core.implementation.TypeUtil; +import io.clientcore.core.models.SimpleClass; +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonSerializable; +import io.clientcore.core.serialization.json.JsonSerializer; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.serialization.json.JsonWriter; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.ParameterizedType; +import java.net.URI; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import static io.clientcore.core.utils.TestUtils.assertArraysEqual; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class JsonSerializerTests { + private static final JsonSerializer SERIALIZER = new JsonSerializer(); + + @Test + public void mapWithEmptyKeyAndNullValue() throws IOException { + final MapHolder mapHolder = new MapHolder(); + + mapHolder.map(new HashMap<>()); + mapHolder.map().put("", null); + + assertEquals("{\"map\":{\"\":null}}", new String(SERIALIZER.serializeToBytes(mapHolder))); + } + + @Test + public void mapWithEmptyKeyAndEmptyValue() throws IOException { + final MapHolder mapHolder = new MapHolder(); + + mapHolder.map = new HashMap<>(); + mapHolder.map.put("", ""); + + assertEquals("{\"map\":{\"\":\"\"}}", new String(SERIALIZER.serializeToBytes(mapHolder))); + } + + private static class MapHolder implements JsonSerializable { + private Map map = new HashMap<>(); + + public Map map() { + return map; + } + + public void map(Map map) { + this.map = map; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject() + .writeMapField("map", this.map, JsonWriter::writeString) + .writeEndObject(); + } + + public static MapHolder fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + MapHolder mapHolder = new MapHolder(); + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("map".equals(fieldName)) { + mapHolder.map = reader.readMap(JsonReader::getString); + } else { + reader.skipChildren(); + } + } + + return mapHolder; + }); + } + } + + @ParameterizedTest + @MethodSource("deserializeJsonSupplier") + public void deserializeJson(String json, DateTimeWrapper expected) throws IOException { + DateTimeWrapper actual = new JsonSerializer().deserializeFromBytes(json.getBytes(), DateTimeWrapper.class); + + assertEquals(expected.getOffsetDateTime(), actual.getOffsetDateTime()); + } + + private static Stream deserializeJsonSupplier() { + final String jsonFormatDate = "{\"OffsetDateTime\":\"%s\"}"; + DateTimeWrapper minValue + = new DateTimeWrapper().setOffsetDateTime(OffsetDateTime.of(1, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC)); + DateTimeWrapper unixEpoch + = new DateTimeWrapper().setOffsetDateTime(OffsetDateTime.of(1970, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC)); + + return Stream.of(Arguments.of(String.format(jsonFormatDate, "0001-01-01T00:00:00Z"), minValue), + Arguments.of(String.format(jsonFormatDate, "1970-01-01T00:00:00Z"), unixEpoch)); + } + + public static class DateTimeWrapper implements JsonSerializable { + private OffsetDateTime offsetDateTime; + + public DateTimeWrapper setOffsetDateTime(OffsetDateTime offsetDateTime) { + this.offsetDateTime = offsetDateTime; + + return this; + } + + public OffsetDateTime getOffsetDateTime() { + return offsetDateTime; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject() + .writeStringField("OffsetDateTime", offsetDateTime.toString()) + .writeEndObject(); + } + + public static DateTimeWrapper fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + DateTimeWrapper dateTimeWrapper = new DateTimeWrapper(); + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("OffsetDateTime".equals(fieldName)) { + dateTimeWrapper.offsetDateTime = OffsetDateTime.parse(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return dateTimeWrapper; + }); + } + } + + @ParameterizedTest + @MethodSource("textSerializationSupplier") + public void textToStringSerialization(Object value, String expected) throws IOException { + if (expected == null) { + assertNull(value); + } else { + assertEquals(expected, new String(SERIALIZER.serializeToBytes(value))); + } + } + + @ParameterizedTest + @MethodSource("textSerializationSupplier") + public void textToBytesSerialization(Object value, String expected) throws IOException { + byte[] actual = SERIALIZER.serializeToBytes(value); + + if (expected == null) { + assertNull(actual); + } else { + assertEquals(expected, new String(actual, StandardCharsets.UTF_8)); + } + } + + @ParameterizedTest + @MethodSource("textSerializationSupplier") + public void textToOutputStreamSerialization(Object value, String expected) throws IOException { + AccessibleByteArrayOutputStream outputStream = new AccessibleByteArrayOutputStream(); + SERIALIZER.serializeToStream(outputStream, value); + + if (expected == null) { + assertEquals(0, outputStream.count()); + } else { + assertEquals(expected, outputStream.toString(StandardCharsets.UTF_8)); + } + } + + private static Stream textSerializationSupplier() { + Map map = Collections.singletonMap("key", "value"); + + return Stream.of(Arguments.of(1, "1"), Arguments.of(1L, "1"), Arguments.of(1.0F, "1.0"), + Arguments.of(1.0D, "1.0"), Arguments.of("1", "\"1\""), Arguments.of(HttpMethod.GET, "\"GET\""), + Arguments.of(map, "{\"key\":\"value\"}"), Arguments.of(null, null)); + } + + @ParameterizedTest + @MethodSource("bytesDeserializationSupplier") + public void stringToTextDeserialization(byte[] stringBytes, Class type, Object expected) throws IOException { + Object actual = SERIALIZER.deserializeFromBytes(stringBytes, type); + + if (type == byte[].class) { + assertArraysEqual((byte[]) expected, (byte[]) actual); + } else { + assertEquals(expected, actual); + } + } + + @ParameterizedTest + @MethodSource("bytesDeserializationSupplier") + public void bytesToTextDeserialization(byte[] bytes, Class type, Object expected) throws IOException { + Object actual = SERIALIZER.deserializeFromBytes(bytes, type); + + if (type == byte[].class) { + assertArraysEqual((byte[]) expected, (byte[]) actual); + } else { + assertEquals(expected, actual); + } + } + + @ParameterizedTest + @MethodSource("bytesDeserializationSupplier") + public void inputStreamToTextDeserialization(byte[] inputStreamBytes, Class type, Object expected) + throws IOException { + Object actual = SERIALIZER.deserializeFromStream(new ByteArrayInputStream(inputStreamBytes), type); + + if (type == byte[].class) { + assertArraysEqual((byte[]) expected, (byte[]) actual); + } else { + assertEquals(expected, actual); + } + } + + private static Stream bytesDeserializationSupplier() { + return Stream.of(Arguments.of("\"hello\"".getBytes(StandardCharsets.UTF_8), String.class, "hello"), + Arguments.of("1".getBytes(StandardCharsets.UTF_8), Integer.class, 1), + Arguments.of("1000000000000".getBytes(StandardCharsets.UTF_8), Long.class, 1000000000000L), + Arguments.of("1.0".getBytes(StandardCharsets.UTF_8), Double.class, 1.0D), + Arguments.of("true".getBytes(StandardCharsets.UTF_8), Boolean.class, true)); + } + + @ParameterizedTest + @MethodSource("unsupportedDeserializationSupplier") + public void unsupportedTextTypesDeserialization(Class unsupportedType, + Class exceptionType) { + assertThrows(exceptionType, () -> { + try { + SERIALIZER.deserializeFromBytes(":////".getBytes(), unsupportedType); + } catch (RuntimeException e) { + throw e.getCause(); + } + }); + } + + private static Stream unsupportedDeserializationSupplier() { + return Stream.of(Arguments.of(InputStream.class, IOException.class), + // Thrown when the String cannot be parsed by core + Arguments.of(SimpleClass.class, InvocationTargetException.class), + // Thrown when the class doesn't have a fromJson method + Arguments.of(URL.class, IOException.class), + // Thrown when the String cannot be parsed by core + Arguments.of(URI.class, IOException.class) // Thrown when the String cannot be parsed by core + ); + } + + @Test + public void deserializeListOfJsonSerializableTypes() throws IOException { + byte[] bytes = "[{\"property\":\"value1\"},{\"property\":\"value2\"}]".getBytes(StandardCharsets.UTF_8); + + ParameterizedType type = TypeUtil.createParameterizedType(List.class, FooModel.class); + + List models = SERIALIZER.deserializeFromBytes(bytes, type); + assertNotNull(models); + assertEquals(2, models.size()); + assertEquals("value1", models.get(0).getProperty()); + assertEquals("value2", models.get(1).getProperty()); + } + + @SuppressWarnings("unchecked") + @Test + public void deserializeListOfNonJsonSerializableTypes() throws IOException { + byte[] bytes = "[{\"property\":\"value1\"},{\"property\":\"value2\"}]".getBytes(StandardCharsets.UTF_8); + + ParameterizedType type = TypeUtil.createParameterizedType(List.class, BarModel.class); + + List models = SERIALIZER.deserializeFromBytes(bytes, type); + assertNotNull(models); + assertEquals(2, models.size()); + assertTrue(models.get(0) instanceof LinkedHashMap); + + if (models.get(0) instanceof LinkedHashMap) { + LinkedHashMap model = (LinkedHashMap) models.get(0); + assertEquals("value1", model.get("property")); + } + } + + /** + * A model that implements {@link JsonSerializable}. + */ + public static final class FooModel implements JsonSerializable { + private final String property; + + public FooModel(String property) { + this.property = property; + } + + public String getProperty() { + return this.property; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("property", this.property); + return jsonWriter.writeEndObject(); + } + + public static FooModel fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String property = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("property".equals(fieldName)) { + property = reader.getString(); + } else { + reader.skipChildren(); + } + } + FooModel deserializedModel = new FooModel(property); + + return deserializedModel; + }); + } + } + + /** + * A model that does not implement {@link JsonSerializable}. + */ + public static final class BarModel { + private final String property; + + public BarModel(String property) { + this.property = property; + } + + public String getProperty() { + return this.property; + } + } +} diff --git a/sdk/clientcore/core/src/test/java/io/clientcore/core/util/serializer/MockSerializer.java b/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/serializers/MockSerializer.java similarity index 85% rename from sdk/clientcore/core/src/test/java/io/clientcore/core/util/serializer/MockSerializer.java rename to sdk/clientcore/core/src/test/java/io/clientcore/core/utils/serializers/MockSerializer.java index 1712a6953bb0..a23cd7c91f25 100644 --- a/sdk/clientcore/core/src/test/java/io/clientcore/core/util/serializer/MockSerializer.java +++ b/sdk/clientcore/core/src/test/java/io/clientcore/core/utils/serializers/MockSerializer.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package io.clientcore.core.util.serializer; +package io.clientcore.core.utils.serializers; -import io.clientcore.core.implementation.util.JsonSerializer; +import io.clientcore.core.serialization.json.JsonSerializer; import java.io.InputStream; import java.io.OutputStream; diff --git a/sdk/clientcore/core/src/test/resources/CloudEvent/CloudEventBinaryData.json b/sdk/clientcore/core/src/test/resources/CloudEvent/CloudEventBinaryData.json new file mode 100644 index 000000000000..ad5db038dfd2 --- /dev/null +++ b/sdk/clientcore/core/src/test/resources/CloudEvent/CloudEventBinaryData.json @@ -0,0 +1,12 @@ +[ + { + "id": "2d1781af-3a4c-4d7c-bd0c-e34b19da4e66", + "source": "contoso/items", + "type": "Contoso.Items.ItemReceived", + "subject": "", + "data_base64": "c2FtcGxlYmluYXJ5ZGF0YQ==", + "time": "2018-01-25T22:12:19.4556811Z", + "specversion": "1.0", + "foo": "bar" + } +] diff --git a/sdk/clientcore/core/src/test/resources/CloudEvent/CloudEventDifferentDataTypes.json b/sdk/clientcore/core/src/test/resources/CloudEvent/CloudEventDifferentDataTypes.json new file mode 100644 index 000000000000..9125098aa4b1 --- /dev/null +++ b/sdk/clientcore/core/src/test/resources/CloudEvent/CloudEventDifferentDataTypes.json @@ -0,0 +1,19 @@ +{ + "id": "9ddf9b10-fe3d-4a16-94bc-c0298924ded1", + "source": "/testresource", + "datacontenttype": "application/json", + "dataschema": "/testschema", + "subject": "testsubject", + "data": { + "str": "str value", + "number": 1.3, + "integer": 1, + "bool": true, + "array": [1,2,3], + "null": null, + "object": {"okey": "ovalue"} + }, + "type": "Microsoft.MockPublisher.TestEvent", + "time": "2020-07-21T18:41:31.166Z", + "specversion": "1.0" +} diff --git a/sdk/clientcore/core/src/test/resources/CloudEvent/CloudEventJsonData.json b/sdk/clientcore/core/src/test/resources/CloudEvent/CloudEventJsonData.json new file mode 100644 index 000000000000..3b356c497e87 --- /dev/null +++ b/sdk/clientcore/core/src/test/resources/CloudEvent/CloudEventJsonData.json @@ -0,0 +1,15 @@ +[ + { + "id": "2d1781af-3a4c-4d7c-bd0c-e34b19da4e66", + "source": "contoso/items", + "type": "Contoso.Items.ItemReceived", + "subject": "", + "data": { + "itemSku": "512d38b6-c7b8-40c8-89fe-f46f9e9622b6", + "itemUri": "https://rp-eastus2.eventgrid.azure.net:553/eventsubscriptions/estest/validate?id=B2E34264-7D71-453A-B5FB-B62D0FDC85EE&t=2018-04-26T20:30:54.4538837Z&apiVersion=2018-05-01-preview&token=1BNqCxBBSSE9OnNSfZM4%2b5H9zDegKMY6uJ%2fO2DFRkwQ%3d" + }, + "time": "2018-01-25T22:12:19.4556811Z", + "specversion": "1.0", + "foo": "bar" + } +] diff --git a/sdk/clientcore/core/src/test/resources/CloudEvent/CloudEventNoArray.json b/sdk/clientcore/core/src/test/resources/CloudEvent/CloudEventNoArray.json new file mode 100644 index 000000000000..24e33f09e0d2 --- /dev/null +++ b/sdk/clientcore/core/src/test/resources/CloudEvent/CloudEventNoArray.json @@ -0,0 +1,13 @@ +{ + "id": "2d1781af-3a4c-4d7c-bd0c-e34b19da4e66", + "source": "contoso/items", + "type": "Contoso.Items.ItemReceived", + "subject": "", + "data": { + "itemSku": "512d38b6-c7b8-40c8-89fe-f46f9e9622b6", + "itemUri": "https://rp-eastus2.eventgrid.azure.net:553/eventsubscriptions/estest/validate?id=B2E34264-7D71-453A-B5FB-B62D0FDC85EE&t=2018-04-26T20:30:54.4538837Z&apiVersion=2018-05-01-preview&token=1BNqCxBBSSE9OnNSfZM4%2b5H9zDegKMY6uJ%2fO2DFRkwQ%3d" + }, + "time": "2018-01-25T22:12:19.4556811Z", + "specversion": "1.0", + "foo": "bar" +} diff --git a/sdk/clientcore/core/src/test/resources/CloudEvent/CloudEventNoType.json b/sdk/clientcore/core/src/test/resources/CloudEvent/CloudEventNoType.json new file mode 100644 index 000000000000..513fb8db9d35 --- /dev/null +++ b/sdk/clientcore/core/src/test/resources/CloudEvent/CloudEventNoType.json @@ -0,0 +1,18 @@ +{ + "id": "9ddf9b10-fe3d-4a16-94bc-c0298924ded1", + "source": "/testresource", + "datacontenttype": "application/json", + "dataschema": "/testschema", + "subject": "testsubject", + "data": { + "str": "str value", + "number": 1.3, + "integer": 1, + "bool": true, + "array": [1,2,3], + "null": null, + "object": {"okey": "ovalue"} + }, + "time": "2020-07-21T18:41:31.166Z", + "specversion": "1.0" +} diff --git a/sdk/clientcore/core/src/test/resources/CloudEvent/CloudEventNullData.json b/sdk/clientcore/core/src/test/resources/CloudEvent/CloudEventNullData.json new file mode 100644 index 000000000000..5bb3627a8f83 --- /dev/null +++ b/sdk/clientcore/core/src/test/resources/CloudEvent/CloudEventNullData.json @@ -0,0 +1,11 @@ +[ + { + "id": "2d1781af-3a4c-4d7c-bd0c-e34b19da4e66", + "source": "contoso/items", + "type": "Contoso.Items.ItemReceived", + "subject": "", + "time": "2018-01-25T22:12:19.4556811Z", + "specversion": "1.0", + "foo": "bar" + } +] diff --git a/sdk/clientcore/core/src/test/resources/CloudEvent/CloudEventXmlData.json b/sdk/clientcore/core/src/test/resources/CloudEvent/CloudEventXmlData.json new file mode 100644 index 000000000000..02524005f486 --- /dev/null +++ b/sdk/clientcore/core/src/test/resources/CloudEvent/CloudEventXmlData.json @@ -0,0 +1,11 @@ +{ + "specversion": "1.0", + "type": "com.example.someevent", + "source": "/mycontext", + "id": "A234-1234-1234", + "time": "2018-04-05T17:31:00Z", + "comexampleextension1": "value", + "comexampleothervalue": 5, + "datacontenttype": "text/xml", + "data": "" +} diff --git a/sdk/clientcore/http-okhttp3/CHANGELOG.md b/sdk/clientcore/http-okhttp3/CHANGELOG.md index 4144f75694a0..50f8c861c38d 100644 --- a/sdk/clientcore/http-okhttp3/CHANGELOG.md +++ b/sdk/clientcore/http-okhttp3/CHANGELOG.md @@ -1,3 +1,19 @@ # Release History -## 1.0.0-beta.1 (Unreleased) +## 1.0.0-beta.2 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + +## 1.0.0-beta.1 ((2025-03-10) + +### Features Added + +- Initial release. Please see the README and wiki for more information. + This package contains core types for building Java client libraries for accessing web services. + diff --git a/sdk/clientcore/http-okhttp3/checkstyle-suppressions.xml b/sdk/clientcore/http-okhttp3/checkstyle-suppressions.xml index 303fdde4cde4..9560f3675fbf 100644 --- a/sdk/clientcore/http-okhttp3/checkstyle-suppressions.xml +++ b/sdk/clientcore/http-okhttp3/checkstyle-suppressions.xml @@ -6,7 +6,6 @@ - diff --git a/sdk/clientcore/http-okhttp3/pom.xml b/sdk/clientcore/http-okhttp3/pom.xml index 978489f8db65..6d264d6e5daf 100644 --- a/sdk/clientcore/http-okhttp3/pom.xml +++ b/sdk/clientcore/http-okhttp3/pom.xml @@ -8,14 +8,14 @@ io.clientcore clientcore-parent - 1.0.0-beta.1 + 1.0.0-beta.3 ../../parents/clientcore-parent io.clientcore http-okhttp3 jar - 1.0.0-beta.1 + 1.0.0-beta.2 Java OkHttp3 HTTP Client Library This package contains the OkHttp HTTP client plugin for io.clientcore. @@ -43,7 +43,7 @@ --add-exports io.clientcore.core/io.clientcore.core.implementation.http=ALL-UNNAMED --add-exports io.clientcore.core/io.clientcore.core.implementation.http.serializer=ALL-UNNAMED - --add-exports io.clientcore.core/io.clientcore.core.implementation.util=ALL-UNNAMED + --add-exports io.clientcore.core/io.clientcore.core.implementation.utils=ALL-UNNAMED --add-opens io.clientcore.http.okhttp3/io.clientcore.http.okhttp3=ALL-UNNAMED --add-opens io.clientcore.http.okhttp3/io.clientcore.http.okhttp3.implementation=ALL-UNNAMED @@ -55,7 +55,7 @@ io.clientcore.core.annotation,io.clientcore.core.credential,io.clientcore.core.http,io.clientcore.core.http.annotation,io.clientcore.core.http.client, io.clientcore.core.http.exception,io.clientcore.core.http.models,io.clientcore.core.http.pipeline,io.clientcore.core.implementation, - io.clientcore.core.implementation*,io.clientcore.core.models,io.clientcore.core.util,io.clientcore.core.util* + io.clientcore.core.implementation*,io.clientcore.core.models,io.clientcore.core.utils,io.clientcore.core.util* @@ -63,7 +63,7 @@ io.clientcore core - 1.0.0-beta.2 + 1.0.0-beta.7 com.squareup.okio @@ -86,7 +86,7 @@ io.clientcore core - 1.0.0-beta.2 + 1.0.0-beta.7 test-jar test diff --git a/sdk/clientcore/http-okhttp3/spotbugs-exclude.xml b/sdk/clientcore/http-okhttp3/spotbugs-exclude.xml index 6b03df0b01cc..423ce0df234a 100644 --- a/sdk/clientcore/http-okhttp3/spotbugs-exclude.xml +++ b/sdk/clientcore/http-okhttp3/spotbugs-exclude.xml @@ -11,7 +11,11 @@ - + + + + + diff --git a/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/OkHttpHttpClient.java b/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/OkHttpHttpClient.java index ce3fb8f92283..4bfa36e95f8e 100644 --- a/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/OkHttpHttpClient.java +++ b/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/OkHttpHttpClient.java @@ -4,7 +4,6 @@ package io.clientcore.http.okhttp3; import io.clientcore.core.http.client.HttpClient; -import io.clientcore.core.http.models.HttpHeader; import io.clientcore.core.http.models.HttpHeaderName; import io.clientcore.core.http.models.HttpHeaders; import io.clientcore.core.http.models.HttpMethod; @@ -14,15 +13,13 @@ import io.clientcore.core.http.models.ResponseBodyMode; import io.clientcore.core.http.models.ServerSentEventListener; import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.util.ServerSentEventUtils; -import io.clientcore.core.util.ServerSentResult; -import io.clientcore.core.util.binarydata.BinaryData; -import io.clientcore.core.util.binarydata.FileBinaryData; -import io.clientcore.core.util.binarydata.InputStreamBinaryData; +import io.clientcore.core.models.ServerSentResult; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.models.binarydata.FileBinaryData; +import io.clientcore.core.models.binarydata.InputStreamBinaryData; +import io.clientcore.core.utils.ServerSentEventUtils; import io.clientcore.http.okhttp3.implementation.OkHttpFileRequestBody; import io.clientcore.http.okhttp3.implementation.OkHttpInputStreamRequestBody; -import io.clientcore.http.okhttp3.implementation.OkHttpResponse; -import okhttp3.Headers; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; @@ -31,14 +28,13 @@ import java.io.IOException; -import static io.clientcore.core.http.models.ContentType.APPLICATION_OCTET_STREAM; -import static io.clientcore.core.http.models.HttpHeaderName.CONTENT_TYPE; import static io.clientcore.core.http.models.HttpMethod.HEAD; import static io.clientcore.core.http.models.ResponseBodyMode.BUFFER; import static io.clientcore.core.http.models.ResponseBodyMode.IGNORE; import static io.clientcore.core.http.models.ResponseBodyMode.STREAM; -import static io.clientcore.core.util.ServerSentEventUtils.processTextEventStream; -import static io.clientcore.core.util.ServerSentEventUtils.attemptRetry; +import static io.clientcore.core.utils.ServerSentEventUtils.attemptRetry; +import static io.clientcore.core.utils.ServerSentEventUtils.processTextEventStream; +import static io.clientcore.http.okhttp3.implementation.OkHttpToCoreHttpHeadersWrapper.fromOkHttpHeaders; /** * HttpClient implementation for OkHttp. @@ -47,6 +43,13 @@ class OkHttpHttpClient implements HttpClient { private static final ClientLogger LOGGER = new ClientLogger(OkHttpHttpClient.class); private static final byte[] EMPTY_BODY = new byte[0]; private static final RequestBody EMPTY_REQUEST_BODY = RequestBody.create(EMPTY_BODY); + + /** + * Error message for when no {@link ServerSentEventListener} is attached to the {@link HttpRequest}. + */ + private static final String NO_LISTENER_ERROR_MESSAGE + = "No ServerSentEventListener attached to HttpRequest to handle the text/event-stream response"; + final OkHttpClient httpClient; OkHttpHttpClient(OkHttpClient httpClient) { @@ -54,7 +57,7 @@ class OkHttpHttpClient implements HttpClient { } @Override - public Response send(HttpRequest request) throws IOException { + public Response send(HttpRequest request) throws IOException { Request okHttpRequest = toOkHttpRequest(request); okhttp3.Response okHttpResponse = httpClient.newCall(okHttpRequest).execute(); @@ -72,11 +75,11 @@ private okhttp3.Request toOkHttpRequest(HttpRequest request) { Request.Builder requestBuilder = new Request.Builder().url(request.getUri().toString()); if (request.getHeaders() != null) { - for (HttpHeader hdr : request.getHeaders()) { + request.getHeaders().stream().forEach(hdr -> { // OkHttp allows for headers with multiple values, but it treats them as separate headers, // therefore, we must call rb.addHeader for each value, using the same key for all of them hdr.getValues().forEach(value -> requestBuilder.addHeader(hdr.getName().toString(), value)); - } + }); } if (request.getHttpMethod() == HttpMethod.GET) { @@ -139,10 +142,11 @@ private static long getRequestContentLength(BinaryData content, HttpHeaders head return contentLength; } - private Response toResponse(HttpRequest request, okhttp3.Response response) throws IOException { - okhttp3.Headers responseHeaders = response.headers(); + private Response toResponse(HttpRequest request, okhttp3.Response response) throws IOException { ServerSentResult serverSentResult = null; - if (isTextEventStream(responseHeaders) && response.body() != null) { + HttpHeaders headers = fromOkHttpHeaders(response.headers()); + + if (isTextEventStream(headers) && response.body() != null) { ServerSentEventListener listener = request.getServerSentEventListener(); if (listener != null) { @@ -158,25 +162,19 @@ private Response toResponse(HttpRequest request, okhttp3.Response response) t return this.send(request); } } else { - throw LOGGER.logThrowableAsError(new RuntimeException(ServerSentEventUtils.NO_LISTENER_ERROR_MESSAGE)); + throw LOGGER.logThrowableAsError(new RuntimeException(NO_LISTENER_ERROR_MESSAGE)); } } - return processResponse(request, response, serverSentResult); - } - - private Response processResponse(HttpRequest request, okhttp3.Response response, - ServerSentResult serverSentResult) throws IOException { RequestOptions options = request.getRequestOptions(); ResponseBodyMode responseBodyMode = null; - Headers responseHeaders = response.headers(); if (options != null) { responseBodyMode = options.getResponseBodyMode(); } if (responseBodyMode == null) { - responseBodyMode = determineResponseBodyMode(request, responseHeaders); + responseBodyMode = determineResponseBodyMode(request, headers); } BinaryData body = null; @@ -186,11 +184,10 @@ private Response processResponse(HttpRequest request, okhttp3.Response respon if (response.body() != null) { response.body().close(); } - break; case STREAM: - if (isTextEventStream(responseHeaders)) { + if (isTextEventStream(headers)) { body = createBodyFromServerSentResult(serverSentResult); } else if (response.body() != null && response.body().contentLength() != 0) { body = BinaryData.fromStream(response.body().byteStream()); @@ -200,7 +197,7 @@ private Response processResponse(HttpRequest request, okhttp3.Response respon case BUFFER: case DESERIALIZE: // Deserialization will occur at a later point in HttpResponseBodyDecoder. - if (isTextEventStream(responseHeaders)) { + if (isTextEventStream(headers)) { body = createBodyFromServerSentResult(serverSentResult); } else { body = createBodyFromResponseBody(response.body()); @@ -212,7 +209,7 @@ private Response processResponse(HttpRequest request, okhttp3.Response respon break; } - return new OkHttpResponse(response, request, body == null ? BinaryData.empty() : body); + return new Response<>(request, response.code(), headers, body); } private BinaryData createBodyFromServerSentResult(ServerSentResult serverSentResult) { @@ -229,24 +226,22 @@ private BinaryData createBodyFromResponseBody(ResponseBody responseBody) throws return null; } - private ResponseBodyMode determineResponseBodyMode(HttpRequest request, Headers responseHeaders) { - String contentType = responseHeaders.get(CONTENT_TYPE.getCaseInsensitiveName()); + private ResponseBodyMode determineResponseBodyMode(HttpRequest request, HttpHeaders responseHeaders) { + String contentType = responseHeaders.getValue(HttpHeaderName.CONTENT_TYPE); if (request.getHttpMethod() == HEAD) { return IGNORE; - } else if (contentType != null - && (APPLICATION_OCTET_STREAM.regionMatches(true, 0, contentType, 0, APPLICATION_OCTET_STREAM.length()))) { - + } else if ("application/octet-stream".equalsIgnoreCase(contentType)) { return STREAM; } else { return BUFFER; } } - private static boolean isTextEventStream(okhttp3.Headers responseHeaders) { + private static boolean isTextEventStream(HttpHeaders responseHeaders) { if (responseHeaders != null) { return ServerSentEventUtils - .isTextEventStreamContentType(responseHeaders.get(HttpHeaderName.CONTENT_TYPE.toString())); + .isTextEventStreamContentType(responseHeaders.getValue(HttpHeaderName.CONTENT_TYPE)); } return false; diff --git a/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/OkHttpHttpClientBuilder.java b/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/OkHttpHttpClientBuilder.java index 0735f8eadf90..2dde61c50353 100644 --- a/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/OkHttpHttpClientBuilder.java +++ b/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/OkHttpHttpClientBuilder.java @@ -6,9 +6,9 @@ import io.clientcore.core.http.client.HttpClient; import io.clientcore.core.http.models.ProxyOptions; import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.util.SharedExecutorService; -import io.clientcore.core.util.auth.ChallengeHandler; -import io.clientcore.core.util.configuration.Configuration; +import io.clientcore.core.utils.SharedExecutorService; +import io.clientcore.core.utils.ChallengeHandler; +import io.clientcore.core.utils.configuration.Configuration; import io.clientcore.http.okhttp3.implementation.OkHttpProxySelector; import io.clientcore.http.okhttp3.implementation.ProxyAuthenticator; import okhttp3.ConnectionPool; @@ -137,7 +137,7 @@ public OkHttpHttpClientBuilder dispatcher(Dispatcher dispatcher) { * The connection timeout begins once the request attempts to connect to the remote host and finishes once the * connection is resolved. *

        - * If {@code connectTimeout} is null either {@link Configuration#PROPERTY_REQUEST_CONNECT_TIMEOUT} or a + * If {@code connectTimeout} is null either {@link Configuration#REQUEST_CONNECT_TIMEOUT_IN_MS} or a * 10-second timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code connectTimeout} will * be used. @@ -188,7 +188,7 @@ public OkHttpHttpClientBuilder callTimeout(Duration callTimeout) { * timeout triggers periodically but won't fire its operation if another read operation has completed between when * the timeout is triggered and completes. *

        - * If {@code readTimeout} is null or {@link Configuration#PROPERTY_REQUEST_READ_TIMEOUT} or a 60-second + * If {@code readTimeout} is null or {@link Configuration#REQUEST_READ_TIMEOUT_IN_MS} or a 60-second * timeout will be used, if it is a {@link Duration} less than or equal to zero then no timeout period will be * applied to response read. When applying the timeout the greatest of one millisecond and the value of {@code * readTimeout} will be used. @@ -212,7 +212,7 @@ public OkHttpHttpClientBuilder readTimeout(Duration readTimeout) { * write tracker will update when each operation completes and the outbound buffer will be periodically checked to * determine if it is still draining. *

        - * If {@code writeTimeout} is null either {@link Configuration#PROPERTY_REQUEST_WRITE_TIMEOUT} or a 60-second + * If {@code writeTimeout} is null either {@link Configuration#REQUEST_WRITE_TIMEOUT_IN_MS} or a 60-second * timeout will be used, if it is a {@link Duration} less than or equal to zero then no write timeout will be * applied. When applying the timeout the greatest of one millisecond and the value of {@code writeTimeout} will be * used. diff --git a/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/implementation/OkHttpFileRequestBody.java b/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/implementation/OkHttpFileRequestBody.java index b604eeb56290..e5f1be744b0a 100644 --- a/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/implementation/OkHttpFileRequestBody.java +++ b/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/implementation/OkHttpFileRequestBody.java @@ -3,7 +3,7 @@ package io.clientcore.http.okhttp3.implementation; -import io.clientcore.core.util.binarydata.FileBinaryData; +import io.clientcore.core.models.binarydata.FileBinaryData; import okhttp3.MediaType; import okio.BufferedSink; diff --git a/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/implementation/OkHttpInputStreamRequestBody.java b/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/implementation/OkHttpInputStreamRequestBody.java index 5e657ba966dc..7d1c6613a8ef 100644 --- a/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/implementation/OkHttpInputStreamRequestBody.java +++ b/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/implementation/OkHttpInputStreamRequestBody.java @@ -4,7 +4,7 @@ package io.clientcore.http.okhttp3.implementation; import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.util.binarydata.InputStreamBinaryData; +import io.clientcore.core.models.binarydata.InputStreamBinaryData; import okhttp3.MediaType; import okio.BufferedSink; import okio.Okio; diff --git a/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/implementation/OkHttpResponse.java b/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/implementation/OkHttpResponse.java deleted file mode 100644 index 448671434022..000000000000 --- a/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/implementation/OkHttpResponse.java +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.http.okhttp3.implementation; - -import io.clientcore.core.http.models.HttpHeaderName; -import io.clientcore.core.http.models.HttpHeaders; -import io.clientcore.core.http.models.HttpRequest; -import io.clientcore.core.http.models.HttpResponse; -import io.clientcore.core.util.binarydata.BinaryData; -import okhttp3.Headers; -import okhttp3.ResponseBody; - -/** - * Base response class for OkHttp with implementations for response metadata. - */ -public class OkHttpResponse extends HttpResponse { - private final ResponseBody responseBody; - private BinaryData body; - - public OkHttpResponse(okhttp3.Response response, HttpRequest request, BinaryData body) { - super(request, response.code(), new OkHttpToCoreHttpHeadersWrapper(response.headers()), null); - - // innerResponse.body() getter will not return null for server returned responses. - // It can be null: - // [a]. if response is built manually with null body (e.g. for mocking) - // [b]. for the cases described here - // [ref](https://square.github.io/okhttp/4.x/okhttp/okhttp3/-response/body/). - this.responseBody = response.body(); - this.body = body; - } - - /** - * Creates {@link HttpHeaders Generic Core's headers} from {@link Headers OkHttp headers}. - * - * @param okHttpHeaders {@link Headers OkHttp headers}. - * - * @return {@link HttpHeaders Generic Core's headers}. - */ - static HttpHeaders fromOkHttpHeaders(Headers okHttpHeaders) { - /* - * While OkHttp's Headers class offers a method which converts the headers into a Map>, - * which matches one of the setters in our HttpHeaders, the method implicitly lower cases header names while - * doing the conversion. This is fine when working purely with HTTPs request-response structure as headers are - * case-insensitive per their definition RFC but this could cause issues when/if the headers are used in - * serialization or deserialization as casing may matter. - */ - HttpHeaders httpHeaders = new HttpHeaders((int) (okHttpHeaders.size() / 0.75F)); - - /* - * Use OkHttp's Headers.forEach() instead of the names and values approach. forEach() allows for a single - * iteration over the internal array of header values whereas names and values will iterate over the internal - * array of header values for each name. With the new approach we also use Generic Core's Headers.add() method. - * Overall, this is much better performing as almost all headers will have a single value. - */ - okHttpHeaders.forEach(nameValuePair -> httpHeaders.add(HttpHeaderName.fromString(nameValuePair.getFirst()), - nameValuePair.getSecond())); - - return httpHeaders; - } - - /** - * Gets the {@link BinaryData} that represents the body of the response. - * - * @return The {@link BinaryData} containing the response body. - */ - @Override - public BinaryData getBody() { - if (body == null) { - if (super.getValue() == null) { - body = BinaryData.empty(); - } else { - body = super.getValue(); - } - } - - return body; - } - - @Override - public void close() { - if (this.responseBody != null) { - // It's safe to invoke close() multiple times, additional calls will be ignored. - this.responseBody.close(); - } - } -} diff --git a/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/implementation/OkHttpStreamableRequestBody.java b/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/implementation/OkHttpStreamableRequestBody.java index 2ce64dbd557f..e000ca5d991a 100644 --- a/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/implementation/OkHttpStreamableRequestBody.java +++ b/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/implementation/OkHttpStreamableRequestBody.java @@ -3,7 +3,7 @@ package io.clientcore.http.okhttp3.implementation; -import io.clientcore.core.util.binarydata.BinaryData; +import io.clientcore.core.models.binarydata.BinaryData; import okhttp3.MediaType; import okhttp3.RequestBody; diff --git a/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/implementation/OkHttpToCoreHttpHeadersWrapper.java b/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/implementation/OkHttpToCoreHttpHeadersWrapper.java index efac19f07d44..2794fa5baa41 100644 --- a/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/implementation/OkHttpToCoreHttpHeadersWrapper.java +++ b/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/implementation/OkHttpToCoreHttpHeadersWrapper.java @@ -9,9 +9,7 @@ import io.clientcore.core.http.models.Response; import okhttp3.Headers; -import java.util.Iterator; import java.util.List; -import java.util.Map; import java.util.stream.Stream; /** @@ -113,20 +111,6 @@ public List getValues(HttpHeaderName name) { return coreHeaders.getValues(name); } - @Override - public Map toMap() { - convertIfNeeded(); - - return coreHeaders.toMap(); - } - - @Override - public Iterator iterator() { - convertIfNeeded(); - - return coreHeaders.iterator(); - } - @Override public Stream stream() { convertIfNeeded(); @@ -146,7 +130,36 @@ private void convertIfNeeded() { return; } - coreHeaders = OkHttpResponse.fromOkHttpHeaders(okhttpHeaders); + coreHeaders = fromOkHttpHeaders(okhttpHeaders); converted = true; } + + /** + * Creates {@link HttpHeaders Generic Core's headers} from {@link Headers OkHttp headers}. + * + * @param okHttpHeaders {@link Headers OkHttp headers}. + * + * @return {@link HttpHeaders Generic Core's headers}. + */ + public static HttpHeaders fromOkHttpHeaders(Headers okHttpHeaders) { + /* + * While OkHttp's Headers class offers a method which converts the headers into a Map>, + * which matches one of the setters in our HttpHeaders, the method implicitly lower cases header names while + * doing the conversion. This is fine when working purely with HTTPs request-response structure as headers are + * case-insensitive per their definition RFC but this could cause issues when/if the headers are used in + * serialization or deserialization as casing may matter. + */ + HttpHeaders httpHeaders = new HttpHeaders((int) (okHttpHeaders.size() / 0.75F)); + + /* + * Use OkHttp's Headers.forEach() instead of the names and values approach. forEach() allows for a single + * iteration over the internal array of header values whereas names and values will iterate over the internal + * array of header values for each name. With the new approach we also use Generic Core's Headers.add() method. + * Overall, this is much better performing as almost all headers will have a single value. + */ + okHttpHeaders.forEach(nameValuePair -> httpHeaders.add(HttpHeaderName.fromString(nameValuePair.getFirst()), + nameValuePair.getSecond())); + + return httpHeaders; + } } diff --git a/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/implementation/ProxyAuthenticator.java b/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/implementation/ProxyAuthenticator.java index 0fbc68e8b4d4..3cacfea0f45a 100644 --- a/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/implementation/ProxyAuthenticator.java +++ b/sdk/clientcore/http-okhttp3/src/main/java/io/clientcore/http/okhttp3/implementation/ProxyAuthenticator.java @@ -6,11 +6,10 @@ import io.clientcore.core.http.models.HttpHeaderName; import io.clientcore.core.http.models.HttpMethod; import io.clientcore.core.http.models.HttpRequest; -import io.clientcore.core.http.models.HttpResponse; import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.util.auth.AuthUtils; -import io.clientcore.core.util.auth.ChallengeHandler; -import io.clientcore.core.util.binarydata.BinaryData; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.utils.AuthUtils; +import io.clientcore.core.utils.ChallengeHandler; import okhttp3.Authenticator; import okhttp3.Interceptor; import okhttp3.Request; @@ -20,7 +19,6 @@ import java.io.IOException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import java.util.function.Supplier; import static io.clientcore.core.http.models.HttpHeaderName.PROXY_AUTHORIZATION; @@ -41,7 +39,7 @@ public final class ProxyAuthenticator implements Authenticator { /* * Proxies use 'CONNECT' as the HTTP method. */ - private static final String PROXY_METHOD = HttpMethod.CONNECT.name(); + private static final HttpMethod PROXY_METHOD = HttpMethod.CONNECT; /* * Proxies are always the root path. @@ -51,7 +49,6 @@ public final class ProxyAuthenticator implements Authenticator { /* * Digest authentication to a proxy uses the 'CONNECT' method, these can't have a request body. */ - private static final Supplier NO_BODY = BinaryData::empty; private static final String CNONCE = "cnonce"; private static final String NC = "nc"; @@ -106,9 +103,10 @@ public Request authenticate(Route route, Response response) { } Request.Builder requestBuilder = response.request().newBuilder(); - HttpRequest httpRequest = new HttpRequest(HttpMethod.valueOf(PROXY_METHOD), PROXY_URI_PATH); - HttpResponse httpResponse = new HttpResponse<>(httpRequest, response.code(), - OkHttpResponse.fromOkHttpHeaders(response.headers()), NO_BODY); + HttpRequest httpRequest = new HttpRequest().setMethod(PROXY_METHOD).setUri(PROXY_URI_PATH); + io.clientcore.core.http.models.Response httpResponse + = new io.clientcore.core.http.models.Response<>(httpRequest, response.code(), + OkHttpToCoreHttpHeadersWrapper.fromOkHttpHeaders(response.headers()), BinaryData.empty()); String authorizationHeader; // Replace nonce value in the PROXY_AUTHENTICATE header with the updated nonce ConcurrentHashMap lastChallengeMap = proxyInterceptor.getLastChallenge(); @@ -194,7 +192,7 @@ public Response intercept(Chain chain) throws IOException { String proxyAuthenticationInfoHeader = response.header(PROXY_AUTHENTICATION_INFO); - if (!AuthUtils.isNullOrEmpty(proxyAuthenticationInfoHeader)) { + if (proxyAuthenticationInfoHeader != null && !proxyAuthenticationInfoHeader.isEmpty()) { Map authenticationInfoPieces = AuthUtils.parseAuthenticationOrAuthorizationHeader(proxyAuthenticationInfoHeader); Map authorizationPieces = AuthUtils.parseAuthenticationOrAuthorizationHeader( diff --git a/sdk/clientcore/http-okhttp3/src/test/java/io/clientcore/http/okhttp3/OkHttpHttpClientBuilderTests.java b/sdk/clientcore/http-okhttp3/src/test/java/io/clientcore/http/okhttp3/OkHttpHttpClientBuilderTests.java index fa3e42805d86..507737dd1f22 100644 --- a/sdk/clientcore/http-okhttp3/src/test/java/io/clientcore/http/okhttp3/OkHttpHttpClientBuilderTests.java +++ b/sdk/clientcore/http-okhttp3/src/test/java/io/clientcore/http/okhttp3/OkHttpHttpClientBuilderTests.java @@ -8,12 +8,12 @@ import io.clientcore.core.http.models.HttpRequest; import io.clientcore.core.http.models.ProxyOptions; import io.clientcore.core.http.models.Response; +import io.clientcore.core.models.binarydata.BinaryData; import io.clientcore.core.shared.LocalTestServer; import io.clientcore.core.shared.TestConfigurationSource; -import io.clientcore.core.util.SharedExecutorService; -import io.clientcore.core.util.configuration.Configuration; -import io.clientcore.core.util.configuration.ConfigurationBuilder; -import io.clientcore.core.util.configuration.ConfigurationSource; +import io.clientcore.core.utils.SharedExecutorService; +import io.clientcore.core.utils.configuration.Configuration; +import io.clientcore.core.utils.configuration.ConfigurationSource; import okhttp3.Call; import okhttp3.ConnectionPool; import okhttp3.Dispatcher; @@ -129,7 +129,8 @@ public void buildClientWithExistingClient() throws IOException { .build(); HttpClient client = new OkHttpHttpClientBuilder(existingClient).build(); - try (Response response = client.send(new HttpRequest(HttpMethod.GET, cookieValidatorUri))) { + try (Response response + = client.send(new HttpRequest().setMethod(HttpMethod.GET).setUri(cookieValidatorUri))) { assertEquals(200, response.getStatusCode()); } } @@ -152,7 +153,8 @@ public void addNetworkInterceptor() throws IOException { = chain -> chain.proceed(chain.request().newBuilder().addHeader("Cookie", "test=success").build()); HttpClient client = new OkHttpHttpClientBuilder().addNetworkInterceptor(testInterceptor).build(); - try (Response response = client.send(new HttpRequest(HttpMethod.GET, cookieValidatorUri))) { + try (Response response + = client.send(new HttpRequest().setMethod(HttpMethod.GET).setUri(cookieValidatorUri))) { assertEquals(200, response.getStatusCode()); } } @@ -179,7 +181,8 @@ public void setNetworkInterceptors() throws IOException { .networkInterceptors(Collections.singletonList(goodCookieSetter)) .build(); - try (Response response = client.send(new HttpRequest(HttpMethod.GET, cookieValidatorUri))) { + try (Response response + = client.send(new HttpRequest().setMethod(HttpMethod.GET).setUri(cookieValidatorUri))) { assertEquals(200, response.getStatusCode()); } } @@ -208,7 +211,8 @@ public void buildWithConnectionTimeout() throws IOException { .connectionTimeout(Duration.ofSeconds(3600)) .build(); - try (Response response = client.send(new HttpRequest(HttpMethod.GET, defaultUri))) { + try (Response response + = client.send(new HttpRequest().setMethod(HttpMethod.GET).setUri(defaultUri))) { assertEquals(200, response.getStatusCode()); } } @@ -217,7 +221,8 @@ public void buildWithConnectionTimeout() throws IOException { public void buildWithFollowRedirectSetToTrue() throws IOException { HttpClient client = new OkHttpHttpClientBuilder().followRedirects(true).build(); - try (Response response = client.send(new HttpRequest(HttpMethod.GET, redirectUri))) { + try (Response response + = client.send(new HttpRequest().setMethod(HttpMethod.GET).setUri(redirectUri))) { assertEquals(200, response.getStatusCode()); } } @@ -226,7 +231,8 @@ public void buildWithFollowRedirectSetToTrue() throws IOException { public void buildWithFollowRedirectSetToFalse() throws IOException { HttpClient client = new OkHttpHttpClientBuilder().followRedirects(false).build(); - try (Response response = client.send(new HttpRequest(HttpMethod.GET, redirectUri))) { + try (Response response + = client.send(new HttpRequest().setMethod(HttpMethod.GET).setUri(redirectUri))) { assertEquals(307, response.getStatusCode()); } } @@ -235,7 +241,8 @@ public void buildWithFollowRedirectSetToFalse() throws IOException { public void buildWithFollowRedirectDefault() throws IOException { HttpClient client = new OkHttpHttpClientBuilder().build(); - try (Response response = client.send(new HttpRequest(HttpMethod.GET, redirectUri))) { + try (Response response + = client.send(new HttpRequest().setMethod(HttpMethod.GET).setUri(redirectUri))) { assertEquals(307, response.getStatusCode()); } } @@ -255,7 +262,8 @@ public void buildWithReadTimeout() throws IOException { .readTimeout(Duration.ofSeconds(3600)) .build(); - try (Response response = client.send(new HttpRequest(HttpMethod.GET, defaultUri))) { + try (Response response + = client.send(new HttpRequest().setMethod(HttpMethod.GET).setUri(defaultUri))) { assertEquals(200, response.getStatusCode()); } } @@ -274,7 +282,8 @@ public void buildWithCallTimeout() throws IOException { .callTimeout(Duration.ofSeconds(3600)) .build(); - try (Response response = client.send(new HttpRequest(HttpMethod.GET, defaultUri))) { + try (Response response + = client.send(new HttpRequest().setMethod(HttpMethod.GET).setUri(defaultUri))) { assertEquals(200, response.getStatusCode()); } } @@ -302,7 +311,8 @@ public void buildWithDefaultTimeouts() throws IOException { }; HttpClient client = new OkHttpHttpClientBuilder().addNetworkInterceptor(validatorInterceptor).build(); - try (Response response = client.send(new HttpRequest(HttpMethod.GET, defaultUri))) { + try (Response response + = client.send(new HttpRequest().setMethod(HttpMethod.GET).setUri(defaultUri))) { assertEquals(200, response.getStatusCode()); } } @@ -315,7 +325,8 @@ public void buildWithConnectionPool() throws IOException { ConnectionPool connectionPool = new ConnectionPool(); HttpClient client = new OkHttpHttpClientBuilder().connectionPool(connectionPool).build(); - try (Response response = client.send(new HttpRequest(HttpMethod.GET, defaultUri))) { + try (Response response + = client.send(new HttpRequest().setMethod(HttpMethod.GET).setUri(defaultUri))) { assertEquals(200, response.getStatusCode()); assertEquals(1, connectionPool.connectionCount()); } @@ -350,7 +361,8 @@ public void buildWithDispatcher() { dispatcher.cancelAll(); }, 1000, TimeUnit.MILLISECONDS); - assertThrows(IOException.class, () -> client.send(new HttpRequest(HttpMethod.GET, dispatcherUri)).close()); + assertThrows(IOException.class, + () -> client.send(new HttpRequest().setMethod(HttpMethod.GET).setUri(dispatcherUri)).close()); } /** @@ -371,7 +383,8 @@ public void buildWithProxy(boolean shouldHaveProxy, Proxy.Type proxyType, ProxyO OkHttpClient validatorClient = okHttpClientWithProxyValidation(shouldHaveProxy, proxyType); HttpClient client = new OkHttpHttpClientBuilder(validatorClient).proxy(proxyOptions).build(); - assertThrows(RuntimeException.class, () -> client.send(new HttpRequest(HttpMethod.GET, requestUri)).close(), + assertThrows(RuntimeException.class, + () -> client.send(new HttpRequest().setMethod(HttpMethod.GET).setUri(requestUri)).close(), TestEventListenerValidator.EXPECTED_EXCEPTION_MESSAGE); } @@ -451,7 +464,8 @@ public void buildWithEnvConfigurationProxy(boolean shouldHaveProxy, Configuratio OkHttpClient validatorClient = okHttpClientWithProxyValidation(shouldHaveProxy, Proxy.Type.HTTP); HttpClient client = new OkHttpHttpClientBuilder(validatorClient).configuration(configuration).build(); - assertThrows(Throwable.class, () -> client.send(new HttpRequest(HttpMethod.GET, requestUri)).close(), + assertThrows(Throwable.class, + () -> client.send(new HttpRequest().setMethod(HttpMethod.GET).setUri(requestUri)).close(), TestEventListenerValidator.EXPECTED_EXCEPTION_MESSAGE); } @@ -463,7 +477,8 @@ public void buildWithExplicitConfigurationProxySupplier(boolean shouldHaveProxy, HttpClient client = new OkHttpHttpClientBuilder(validatorClient).configuration(configuration).build(); - assertThrows(Throwable.class, () -> client.send(new HttpRequest(HttpMethod.GET, requestUri)).close(), + assertThrows(Throwable.class, + () -> client.send(new HttpRequest().setMethod(HttpMethod.GET).setUri(requestUri)).close(), TestEventListenerValidator.EXPECTED_EXCEPTION_MESSAGE); } @@ -476,28 +491,26 @@ private static Stream buildWithEnvConfigurationProxySupplier() { /* * Simple non-authenticated HTTP proxies. */ - arguments.add(Arguments.of(true, - new ConfigurationBuilder(EMPTY_SOURCE, baseJavaProxyConfigurationSupplier.get(), EMPTY_SOURCE).build(), - defaultUri)); + arguments.add(Arguments.of(true, new Configuration(baseJavaProxyConfigurationSupplier.get()), defaultUri)); - Configuration simpleEnvProxy = new ConfigurationBuilder(EMPTY_SOURCE, EMPTY_SOURCE, - new TestConfigurationSource().put(Configuration.PROPERTY_HTTP_PROXY, "http://localhost:12345") - .put(JAVA_SYSTEM_PROXY_PREREQUISITE, "true")).build(); + Configuration simpleEnvProxy + = new Configuration(new TestConfigurationSource().put(Configuration.HTTP_PROXY, "http://localhost:12345") + .put(JAVA_SYSTEM_PROXY_PREREQUISITE, "true")); arguments.add(Arguments.of(true, simpleEnvProxy, defaultUri)); /* * HTTP proxy with authentication configured. */ - Configuration javaProxyWithAuthentication = new ConfigurationBuilder(EMPTY_SOURCE, + Configuration javaProxyWithAuthentication = new Configuration(EMPTY_SOURCE, baseJavaProxyConfigurationSupplier.get().put(JAVA_HTTP_PROXY_USER, "1").put(JAVA_HTTP_PROXY_PASSWORD, "1"), - EMPTY_SOURCE).build(); + EMPTY_SOURCE); arguments.add(Arguments.of(true, javaProxyWithAuthentication, defaultUri)); - Configuration envProxyWithAuthentication = new ConfigurationBuilder(EMPTY_SOURCE, EMPTY_SOURCE, - new TestConfigurationSource().put(Configuration.PROPERTY_HTTP_PROXY, "http://1:1@localhost:12345") - .put(JAVA_SYSTEM_PROXY_PREREQUISITE, "true")).build(); + Configuration envProxyWithAuthentication = new Configuration(EMPTY_SOURCE, EMPTY_SOURCE, + new TestConfigurationSource().put(Configuration.HTTP_PROXY, "http://1:1@localhost:12345") + .put(JAVA_SYSTEM_PROXY_PREREQUISITE, "true")); arguments.add(Arguments.of(true, envProxyWithAuthentication, defaultUri)); @@ -520,8 +533,8 @@ private static Stream buildWithEnvConfigurationProxySupplier() { Supplier javaNonProxyHostsSupplier = () -> baseJavaProxyConfigurationSupplier.get().put(JAVA_NON_PROXY_HOSTS, rawJavaNonProxyHosts); Supplier envNonProxyHostsSupplier - = () -> new TestConfigurationSource().put(Configuration.PROPERTY_HTTP_PROXY, "http://localhost:12345") - .put(Configuration.PROPERTY_NO_PROXY, rawEnvNonProxyHosts) + = () -> new TestConfigurationSource().put(Configuration.HTTP_PROXY, "http://localhost:12345") + .put(Configuration.NO_PROXY, rawEnvNonProxyHosts) .put(JAVA_SYSTEM_PROXY_PREREQUISITE, "true"); List> nonProxyHostsSuppliers = Arrays.asList(javaNonProxyHostsSupplier, envNonProxyHostsSupplier); @@ -529,14 +542,12 @@ private static Stream buildWithEnvConfigurationProxySupplier() { for (Supplier configurationSupplier : nonProxyHostsSuppliers) { for (String requestUri : requestUrisWithoutProxying) { arguments.add(Arguments.of(false, - new ConfigurationBuilder(EMPTY_SOURCE, configurationSupplier.get(), EMPTY_SOURCE).build(), - requestUri)); + new Configuration(EMPTY_SOURCE, configurationSupplier.get(), EMPTY_SOURCE), requestUri)); } for (String requestUri : requestUrisWithProxying) { arguments.add(Arguments.of(true, - new ConfigurationBuilder(EMPTY_SOURCE, configurationSupplier.get(), EMPTY_SOURCE).build(), - requestUri)); + new Configuration(EMPTY_SOURCE, configurationSupplier.get(), EMPTY_SOURCE), requestUri)); } } @@ -546,8 +557,8 @@ private static Stream buildWithEnvConfigurationProxySupplier() { Supplier authenticatedJavaNonProxyHostsSupplier = () -> javaNonProxyHostsSupplier.get().put(JAVA_HTTP_PROXY_USER, "1").put(JAVA_HTTP_PROXY_PASSWORD, "1"); Supplier authenticatedEnvNonProxyHostsSupplier - = () -> new TestConfigurationSource().put(Configuration.PROPERTY_HTTP_PROXY, "http://1:1@localhost:12345") - .put(Configuration.PROPERTY_NO_PROXY, rawEnvNonProxyHosts) + = () -> new TestConfigurationSource().put(Configuration.HTTP_PROXY, "http://1:1@localhost:12345") + .put(Configuration.NO_PROXY, rawEnvNonProxyHosts) .put(JAVA_SYSTEM_PROXY_PREREQUISITE, "true"); List> authenticatedNonProxyHostsSuppliers = Arrays.asList(authenticatedJavaNonProxyHostsSupplier, authenticatedEnvNonProxyHostsSupplier); @@ -555,14 +566,12 @@ private static Stream buildWithEnvConfigurationProxySupplier() { for (Supplier configurationSupplier : authenticatedNonProxyHostsSuppliers) { for (String requestUri : requestUrisWithoutProxying) { arguments.add(Arguments.of(false, - new ConfigurationBuilder(EMPTY_SOURCE, configurationSupplier.get(), EMPTY_SOURCE).build(), - requestUri)); + new Configuration(EMPTY_SOURCE, configurationSupplier.get(), EMPTY_SOURCE), requestUri)); } for (String requestUri : requestUrisWithProxying) { arguments.add(Arguments.of(true, - new ConfigurationBuilder(EMPTY_SOURCE, configurationSupplier.get(), EMPTY_SOURCE).build(), - requestUri)); + new Configuration(EMPTY_SOURCE, configurationSupplier.get(), EMPTY_SOURCE), requestUri)); } } @@ -570,24 +579,22 @@ private static Stream buildWithEnvConfigurationProxySupplier() { } private static Stream buildWithExplicitConfigurationProxySupplier() { - Supplier baseHttpProxy - = () -> new ConfigurationBuilder().putProperty("http.proxy.hostname", "localhost") - .putProperty("http.proxy.port", "12345"); + Supplier baseHttpProxy + = () -> new TestConfigurationSource().put("http.proxy.hostname", "localhost") + .put("http.proxy.port", "12345"); List arguments = new ArrayList<>(); /* * Simple non-authenticated HTTP proxies. */ - arguments.add(Arguments.of(true, baseHttpProxy.get().build(), defaultUri)); + arguments.add(Arguments.of(true, new Configuration(baseHttpProxy.get()), defaultUri)); /* * HTTP proxy with authentication configured. */ - Configuration httpProxyWithAuthentication = baseHttpProxy.get() - .putProperty("http.proxy.username", "1") - .putProperty("http.proxy.password", "1") - .build(); + Configuration httpProxyWithAuthentication + = new Configuration(baseHttpProxy.get().put("http.proxy.username", "1").put("http.proxy.password", "1")); arguments.add(Arguments.of(true, httpProxyWithAuthentication, defaultUri)); @@ -607,29 +614,30 @@ private static Stream buildWithExplicitConfigurationProxySupplier() { /* * HTTP proxies with non-proxy hosts configured. */ - Supplier javaNonProxyHostsSupplier - = () -> baseHttpProxy.get().putProperty("http.proxy.non-proxy-hosts", rawJavaNonProxyHosts); + Supplier javaNonProxyHostsSupplier + = () -> baseHttpProxy.get().put("http.proxy.non-proxy-hosts", rawJavaNonProxyHosts); for (String requestUri : requestUrisWithoutProxying) { - arguments.add(Arguments.of(false, javaNonProxyHostsSupplier.get().build(), requestUri)); + arguments.add(Arguments.of(false, new Configuration(javaNonProxyHostsSupplier.get()), requestUri)); } for (String requestUri : requestUrisWithProxying) { - arguments.add(Arguments.of(true, javaNonProxyHostsSupplier.get().build(), requestUri)); + arguments.add(Arguments.of(true, new Configuration(javaNonProxyHostsSupplier.get()), requestUri)); } /* * HTTP proxies with authentication and non-proxy hosts configured. */ - Supplier authenticatedJavaNonProxyHostsSupplier = () -> javaNonProxyHostsSupplier.get() - .putProperty("http.proxy.username", "1") - .putProperty("http.proxy.password", "1"); + Supplier authenticatedJavaNonProxyHostsSupplier + = () -> javaNonProxyHostsSupplier.get().put("http.proxy.username", "1").put("http.proxy.password", "1"); for (String requestUri : requestUrisWithoutProxying) { - arguments.add(Arguments.of(false, authenticatedJavaNonProxyHostsSupplier.get().build(), requestUri)); + arguments + .add(Arguments.of(false, new Configuration(authenticatedJavaNonProxyHostsSupplier.get()), requestUri)); } for (String requestUri : requestUrisWithProxying) { - arguments.add(Arguments.of(true, authenticatedJavaNonProxyHostsSupplier.get().build(), requestUri)); + arguments + .add(Arguments.of(true, new Configuration(authenticatedJavaNonProxyHostsSupplier.get()), requestUri)); } return arguments.stream(); diff --git a/sdk/clientcore/http-okhttp3/src/test/java/io/clientcore/http/okhttp3/OkHttpHttpClientProviderTests.java b/sdk/clientcore/http-okhttp3/src/test/java/io/clientcore/http/okhttp3/OkHttpHttpClientProviderTests.java index 97a6c5a45b65..945553ddbe4b 100644 --- a/sdk/clientcore/http-okhttp3/src/test/java/io/clientcore/http/okhttp3/OkHttpHttpClientProviderTests.java +++ b/sdk/clientcore/http-okhttp3/src/test/java/io/clientcore/http/okhttp3/OkHttpHttpClientProviderTests.java @@ -4,7 +4,7 @@ package io.clientcore.http.okhttp3; import io.clientcore.core.http.models.ProxyOptions; -import io.clientcore.core.util.configuration.Configuration; +import io.clientcore.core.utils.configuration.Configuration; import org.junit.jupiter.api.Test; import java.net.ProxySelector; diff --git a/sdk/clientcore/http-okhttp3/src/test/java/io/clientcore/http/okhttp3/OkHttpHttpClientTests.java b/sdk/clientcore/http-okhttp3/src/test/java/io/clientcore/http/okhttp3/OkHttpHttpClientTests.java index e6b3bf86845a..7ee2c380e60c 100644 --- a/sdk/clientcore/http-okhttp3/src/test/java/io/clientcore/http/okhttp3/OkHttpHttpClientTests.java +++ b/sdk/clientcore/http-okhttp3/src/test/java/io/clientcore/http/okhttp3/OkHttpHttpClientTests.java @@ -10,6 +10,7 @@ import io.clientcore.core.http.models.HttpMethod; import io.clientcore.core.http.models.HttpRequest; import io.clientcore.core.http.models.Response; +import io.clientcore.core.models.binarydata.BinaryData; import io.clientcore.core.shared.InsecureTrustManager; import io.clientcore.core.shared.LocalTestServer; import org.conscrypt.Conscrypt; @@ -110,9 +111,9 @@ public void testFlowableResponseLongBodyAsByteArrayAsync() throws IOException { @Test public void testServerShutsDownSocketShouldPushErrorToContentFlowable() { HttpClient client = new OkHttpHttpClientProvider().getSharedInstance(); - HttpRequest request = new HttpRequest(HttpMethod.GET, uri(server, "/connectionClose")); + HttpRequest request = new HttpRequest().setMethod(HttpMethod.GET).setUri(uri(server, "/connectionClose")); - assertThrows(IOException.class, () -> client.send(request).getBody().toBytes()); + assertThrows(IOException.class, () -> client.send(request).getValue().toBytes()); } @Test @@ -125,8 +126,8 @@ public void testConcurrentRequests() throws InterruptedException { for (int i = 0; i < numRequests; i++) { requests.add(() -> { - try (Response response = doRequest(client, "/long")) { - byte[] body = response.getBody().toBytes(); + try (Response response = doRequest(client, "/long")) { + byte[] body = response.getValue().toBytes(); assertArraysEqual(LONG_BODY, body); return null; @@ -151,8 +152,9 @@ public void validateHeadersReturnAsIs() throws IOException { HttpHeaders headers = new HttpHeaders().set(singleValueHeaderName, singleValueHeaderValue) .set(multiValueHeaderName, multiValueHeaderValue); - try (Response response = client - .send(new HttpRequest(HttpMethod.GET, uri(server, RETURN_HEADERS_AS_IS_PATH)).setHeaders(headers))) { + try (Response response = client.send(new HttpRequest().setMethod(HttpMethod.GET) + .setUri(uri(server, RETURN_HEADERS_AS_IS_PATH)) + .setHeaders(headers))) { assertEquals(200, response.getStatusCode()); @@ -182,8 +184,9 @@ public void testCustomSslSocketFactory() throws IOException, GeneralSecurityExce .hostnameVerifier((hostname, session) -> true) .build(); - try (Response response = httpClient.send(new HttpRequest(HttpMethod.GET, httpsUri(server, "/short")))) { - TestUtils.assertArraysEqual(SHORT_BODY, response.getBody().toBytes()); + try (Response response + = httpClient.send(new HttpRequest().setMethod(HttpMethod.GET).setUri(httpsUri(server, "/short")))) { + TestUtils.assertArraysEqual(SHORT_BODY, response.getValue().toBytes()); } } @@ -216,15 +219,15 @@ private static byte[] createLongBody() { private static void checkBodyReceived(byte[] expectedBody, String path) throws IOException { HttpClient client = new OkHttpHttpClientBuilder().build(); - try (Response response = doRequest(client, path)) { - byte[] bytes = response.getBody().toBytes(); + try (Response response = doRequest(client, path)) { + byte[] bytes = response.getValue().toBytes(); assertArraysEqual(expectedBody, bytes); } } - private static Response doRequest(HttpClient client, String path) throws IOException { - HttpRequest request = new HttpRequest(HttpMethod.GET, uri(server, path)); + private static Response doRequest(HttpClient client, String path) throws IOException { + HttpRequest request = new HttpRequest().setMethod(HttpMethod.GET).setUri(uri(server, path)); return client.send(request); } diff --git a/sdk/clientcore/http-okhttp3/src/test/java/io/clientcore/http/okhttp3/TestUtils.java b/sdk/clientcore/http-okhttp3/src/test/java/io/clientcore/http/okhttp3/TestUtils.java index 621b79eecc0d..14b391ed01ed 100644 --- a/sdk/clientcore/http-okhttp3/src/test/java/io/clientcore/http/okhttp3/TestUtils.java +++ b/sdk/clientcore/http-okhttp3/src/test/java/io/clientcore/http/okhttp3/TestUtils.java @@ -28,7 +28,7 @@ public static Dispatcher createQuietDispatcher(Class expect // Most tests will only run a single network call, so it's fine to use a single thread executor that won't // allow for concurrent requests. return new Dispatcher(Executors.newSingleThreadExecutor(r -> { - Thread thread = new Thread(r, "AzureQuietDispatch-" + QUIET_DISPATCHER_THREAD.getAndIncrement()); + Thread thread = new Thread(r, "ClientCoreQuietDispatch-" + QUIET_DISPATCHER_THREAD.getAndIncrement()); thread.setUncaughtExceptionHandler((t, e) -> { if (e.getClass() == expectedErrorType && e.getMessage() != null diff --git a/sdk/clientcore/http-okhttp3/src/test/java/io/clientcore/http/okhttp3/implementation/OkHttpFileRequestBodyTest.java b/sdk/clientcore/http-okhttp3/src/test/java/io/clientcore/http/okhttp3/implementation/OkHttpFileRequestBodyTest.java index b915773ebabf..e29399e422fa 100644 --- a/sdk/clientcore/http-okhttp3/src/test/java/io/clientcore/http/okhttp3/implementation/OkHttpFileRequestBodyTest.java +++ b/sdk/clientcore/http-okhttp3/src/test/java/io/clientcore/http/okhttp3/implementation/OkHttpFileRequestBodyTest.java @@ -3,7 +3,7 @@ package io.clientcore.http.okhttp3.implementation; -import io.clientcore.core.util.binarydata.FileBinaryData; +import io.clientcore.core.models.binarydata.FileBinaryData; import okio.Buffer; import okio.BufferedSink; import okio.ByteString; diff --git a/sdk/clientcore/http-okhttp3/src/test/java/io/clientcore/http/okhttp3/implementation/ProxyAuthenticatorTests.java b/sdk/clientcore/http-okhttp3/src/test/java/io/clientcore/http/okhttp3/implementation/ProxyAuthenticatorTests.java index 001d7ecb3e7c..ca08a5e8b6c3 100644 --- a/sdk/clientcore/http-okhttp3/src/test/java/io/clientcore/http/okhttp3/implementation/ProxyAuthenticatorTests.java +++ b/sdk/clientcore/http-okhttp3/src/test/java/io/clientcore/http/okhttp3/implementation/ProxyAuthenticatorTests.java @@ -3,10 +3,10 @@ package io.clientcore.http.okhttp3.implementation; -import io.clientcore.core.util.auth.BasicChallengeHandler; -import io.clientcore.core.util.auth.AuthUtils; -import io.clientcore.core.util.auth.ChallengeHandler; -import io.clientcore.core.util.auth.DigestChallengeHandler; +import io.clientcore.core.utils.BasicChallengeHandler; +import io.clientcore.core.utils.AuthUtils; +import io.clientcore.core.utils.ChallengeHandler; +import io.clientcore.core.utils.DigestChallengeHandler; import okhttp3.Address; import okhttp3.Authenticator; import okhttp3.ConnectionSpec; diff --git a/sdk/clientcore/http-stress/pom.xml b/sdk/clientcore/http-stress/pom.xml index 714b68e60e36..332b2532cfca 100644 --- a/sdk/clientcore/http-stress/pom.xml +++ b/sdk/clientcore/http-stress/pom.xml @@ -1,5 +1,5 @@ - - + @@ -8,7 +8,7 @@ io.clientcore clientcore-parent - 1.0.0-beta.1 + 1.0.0-beta.3 ../../parents/clientcore-parent @@ -32,18 +32,18 @@ io.clientcore core - 1.0.0-beta.1 + 1.0.0-beta.7 io.clientcore http-okhttp3 - 1.0.0-beta.1 + 1.0.0-beta.2 io.opentelemetry opentelemetry-api - 1.43.0 + 1.46.0 @@ -54,18 +54,18 @@ com.azure - azure-monitor-opentelemetry-exporter - 1.0.0-beta.31 + azure-monitor-opentelemetry-autoconfigure + 1.0.0 io.opentelemetry.instrumentation opentelemetry-runtime-telemetry-java8 - 2.9.0-alpha + 2.12.0-alpha io.opentelemetry.instrumentation opentelemetry-logback-appender-1.0 - 2.9.0-alpha + 2.12.0-alpha @@ -80,11 +80,11 @@ com.azure:perf-test-core:[1.0.0-beta.1] - com.azure:azure-monitor-opentelemetry-exporter:[1.0.0-beta.31] - io.opentelemetry.instrumentation:opentelemetry-runtime-telemetry-java8:[2.9.0-alpha] - io.opentelemetry.instrumentation:opentelemetry-logback-appender-1.0:[2.9.0-alpha] + com.azure:azure-monitor-opentelemetry-autoconfigure:[1.0.0] + io.opentelemetry.instrumentation:opentelemetry-runtime-telemetry-java8:[2.12.0-alpha] + io.opentelemetry.instrumentation:opentelemetry-logback-appender-1.0:[2.12.0-alpha] ch.qos.logback:logback-classic:[1.3.14] - io.opentelemetry:opentelemetry-api:[1.43.0] + io.opentelemetry:opentelemetry-api:[1.46.0] diff --git a/sdk/clientcore/http-stress/spotbugs-exclude.xml b/sdk/clientcore/http-stress/spotbugs-exclude.xml index 6396a43b9b13..b5d5b3aa70f3 100644 --- a/sdk/clientcore/http-stress/spotbugs-exclude.xml +++ b/sdk/clientcore/http-stress/spotbugs-exclude.xml @@ -21,4 +21,8 @@ + + + + diff --git a/sdk/clientcore/http-stress/src/main/java/io/clientcore/http/stress/HttpGet.java b/sdk/clientcore/http-stress/src/main/java/io/clientcore/http/stress/HttpGet.java index 9ed784836eb7..3de828ea6f41 100644 --- a/sdk/clientcore/http-stress/src/main/java/io/clientcore/http/stress/HttpGet.java +++ b/sdk/clientcore/http-stress/src/main/java/io/clientcore/http/stress/HttpGet.java @@ -4,9 +4,9 @@ package io.clientcore.http.stress; import com.azure.perf.test.core.PerfStressOptions; -import io.clientcore.core.http.client.DefaultHttpClientBuilder; +import io.clientcore.core.http.client.JdkHttpClientBuilder; import io.clientcore.core.http.models.HttpHeaderName; -import io.clientcore.core.http.models.HttpLogOptions; +import io.clientcore.core.http.pipeline.HttpInstrumentationOptions; import io.clientcore.core.http.models.HttpMethod; import io.clientcore.core.http.models.HttpRequest; import io.clientcore.core.http.models.Response; @@ -15,6 +15,7 @@ import io.clientcore.core.http.pipeline.HttpPipelineBuilder; import io.clientcore.core.http.pipeline.HttpRetryPolicy; import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.models.binarydata.BinaryData; import io.clientcore.http.okhttp3.OkHttpHttpClientProvider; import io.clientcore.http.stress.util.TelemetryHelper; import reactor.core.publisher.Mono; @@ -66,8 +67,8 @@ public void run() { private void runInternal() { // no need to handle exceptions here, they will be handled (and recorded) by the telemetry helper HttpRequest request = createRequest(); - try (Response response = pipeline.send(request)) { - response.getBody().toBytes(); + try (Response response = pipeline.send(request)) { + response.getValue().toBytes(); } catch (IOException e) { LOGGER.logThrowableAsError(new UncheckedIOException(e)); } @@ -95,7 +96,7 @@ public Runnable runAsyncWithVirtualThread() { private Mono runInternalAsync() { return Mono.usingWhen(Mono.fromCallable(() -> pipeline.send(createRequest())), response -> { - response.getBody().toBytes(); + response.getValue().toBytes(); return Mono.empty(); }, response -> Mono.fromRunnable(() -> { try { @@ -109,8 +110,8 @@ private Mono runInternalAsync() { // Method to run using CompletableFuture private CompletableFuture runAsyncWithCompletableFutureInternal() { return CompletableFuture.supplyAsync(() -> { - try (Response response = pipeline.send(createRequest())) { - response.getBody().toBytes(); + try (Response response = pipeline.send(createRequest())) { + response.getValue().toBytes(); } catch (Exception e) { LOGGER.logThrowableAsError(e); } @@ -121,8 +122,8 @@ private CompletableFuture runAsyncWithCompletableFutureInternal() { // Method to run using ExecutorService private Runnable runAsyncWithExecutorServiceInternal() { return () -> { - try (Response response = pipeline.send(createRequest())) { - response.getBody().toBytes(); + try (Response response = pipeline.send(createRequest())) { + response.getValue().toBytes(); } catch (Exception e) { LOGGER.logThrowableAsError(e); } @@ -132,8 +133,8 @@ private Runnable runAsyncWithExecutorServiceInternal() { // Method to run using Virtual Threads private Runnable runAsyncWithVirtualThreadInternal() { return () -> { - try (Response response = pipeline.send(createRequest())) { - response.getBody().toBytes(); + try (Response response = pipeline.send(createRequest())) { + response.getValue().toBytes(); } catch (Exception e) { LOGGER.logThrowableAsError(e); } @@ -141,23 +142,22 @@ private Runnable runAsyncWithVirtualThreadInternal() { } private HttpRequest createRequest() { - HttpRequest request = new HttpRequest(HttpMethod.GET, uri); - request.getHeaders().set(HttpHeaderName.USER_AGENT, "azsdk-java-clientcore-stress"); + HttpRequest request = new HttpRequest().setMethod(HttpMethod.GET).setUri(uri); + request.getHeaders().set(HttpHeaderName.USER_AGENT, "clientcore-stress"); request.getHeaders() .set(HttpHeaderName.fromString("x-client-id"), String.valueOf(clientRequestId.incrementAndGet())); return request; } private HttpPipelineBuilder getPipelineBuilder() { - HttpLogOptions logOptions = new HttpLogOptions().setLogLevel(HttpLogOptions.HttpLogDetailLevel.HEADERS); - - HttpPipelineBuilder builder = new HttpPipelineBuilder().policies(new HttpRetryPolicy(), - new HttpInstrumentationPolicy(null, logOptions)); + HttpPipelineBuilder builder = new HttpPipelineBuilder().addPolicy(new HttpRetryPolicy()) + .addPolicy(new HttpInstrumentationPolicy( + new HttpInstrumentationOptions().setHttpLogLevel(HttpInstrumentationOptions.HttpLogLevel.HEADERS))); if (options.getHttpClient() == PerfStressOptions.HttpClientType.OKHTTP) { builder.httpClient(new OkHttpHttpClientProvider().getSharedInstance()); } else { - builder.httpClient(new DefaultHttpClientBuilder().build()); + builder.httpClient(new JdkHttpClientBuilder().build()); } return builder; } diff --git a/sdk/clientcore/http-stress/src/main/java/io/clientcore/http/stress/HttpPatch.java b/sdk/clientcore/http-stress/src/main/java/io/clientcore/http/stress/HttpPatch.java index 192003ae4499..87bd33701fa0 100644 --- a/sdk/clientcore/http-stress/src/main/java/io/clientcore/http/stress/HttpPatch.java +++ b/sdk/clientcore/http-stress/src/main/java/io/clientcore/http/stress/HttpPatch.java @@ -4,9 +4,9 @@ package io.clientcore.http.stress; import com.azure.perf.test.core.PerfStressOptions; -import io.clientcore.core.http.client.DefaultHttpClientBuilder; +import io.clientcore.core.http.client.JdkHttpClientBuilder; import io.clientcore.core.http.models.HttpHeaderName; -import io.clientcore.core.http.models.HttpLogOptions; +import io.clientcore.core.http.pipeline.HttpInstrumentationOptions; import io.clientcore.core.http.models.HttpMethod; import io.clientcore.core.http.models.HttpRequest; import io.clientcore.core.http.models.Response; @@ -15,7 +15,7 @@ import io.clientcore.core.http.pipeline.HttpPipelineBuilder; import io.clientcore.core.http.pipeline.HttpRetryPolicy; import io.clientcore.core.instrumentation.logging.ClientLogger; -import io.clientcore.core.util.binarydata.BinaryData; +import io.clientcore.core.models.binarydata.BinaryData; import io.clientcore.http.okhttp3.OkHttpHttpClientProvider; import io.clientcore.http.stress.util.TelemetryHelper; import reactor.core.publisher.Mono; @@ -60,10 +60,10 @@ public void run() { private void runInternal() { // no need to handle exceptions here, they will be handled (and recorded) by the telemetry helper - try (Response response = pipeline.send(createRequest())) { + try (Response response = pipeline.send(createRequest())) { int responseCode = response.getStatusCode(); assert responseCode == 200 : "Unexpected response code: " + responseCode; - response.getBody().close(); + response.getValue().close(); } catch (IOException e) { throw LOGGER.logThrowableAsError(new RuntimeException(e)); } @@ -76,9 +76,10 @@ public Mono runAsync() { private HttpRequest createRequest() { String body = "{\"id\": \"1\", \"name\": \"test\"}"; - HttpRequest request = new HttpRequest(HttpMethod.PATCH, uri).setBody(BinaryData.fromString(body)); + HttpRequest request + = new HttpRequest().setMethod(HttpMethod.PATCH).setUri(uri).setBody(BinaryData.fromString(body)); request.getHeaders().set(HttpHeaderName.CONTENT_LENGTH, String.valueOf(body.length())); - request.getHeaders().set(HttpHeaderName.USER_AGENT, "azsdk-java-stress"); + request.getHeaders().set(HttpHeaderName.USER_AGENT, "clientcore-stress"); request.getHeaders() .set(HttpHeaderName.fromString("x-client-id"), String.valueOf(clientRequestId.incrementAndGet())); request.getHeaders().set(HttpHeaderName.CONTENT_TYPE, "application/json"); @@ -87,15 +88,14 @@ private HttpRequest createRequest() { } private HttpPipelineBuilder getPipelineBuilder() { - HttpLogOptions logOptions = new HttpLogOptions().setLogLevel(HttpLogOptions.HttpLogDetailLevel.HEADERS); - - HttpPipelineBuilder builder = new HttpPipelineBuilder().policies(new HttpRetryPolicy(), - new HttpInstrumentationPolicy(null, logOptions)); + HttpPipelineBuilder builder = new HttpPipelineBuilder().addPolicy(new HttpRetryPolicy()) + .addPolicy(new HttpInstrumentationPolicy( + new HttpInstrumentationOptions().setHttpLogLevel(HttpInstrumentationOptions.HttpLogLevel.HEADERS))); if (options.getHttpClient() == PerfStressOptions.HttpClientType.OKHTTP) { builder.httpClient(new OkHttpHttpClientProvider().getSharedInstance()); } else { - builder.httpClient(new DefaultHttpClientBuilder().build()); + builder.httpClient(new JdkHttpClientBuilder().build()); } return builder; } diff --git a/sdk/clientcore/http-stress/src/main/java/io/clientcore/http/stress/util/TelemetryHelper.java b/sdk/clientcore/http-stress/src/main/java/io/clientcore/http/stress/util/TelemetryHelper.java index 871fecf765aa..e4f945637e31 100644 --- a/sdk/clientcore/http-stress/src/main/java/io/clientcore/http/stress/util/TelemetryHelper.java +++ b/sdk/clientcore/http-stress/src/main/java/io/clientcore/http/stress/util/TelemetryHelper.java @@ -3,8 +3,7 @@ package io.clientcore.http.stress.util; -import com.azure.monitor.opentelemetry.exporter.AzureMonitorExporter; -import com.azure.monitor.opentelemetry.exporter.AzureMonitorExporterOptions; +import com.azure.monitor.opentelemetry.autoconfigure.AzureMonitorAutoConfigure; import io.clientcore.core.instrumentation.logging.ClientLogger; import io.clientcore.http.stress.StressOptions; import io.opentelemetry.api.GlobalOpenTelemetry; @@ -101,8 +100,7 @@ public static void init() { AutoConfiguredOpenTelemetrySdkBuilder sdkBuilder = AutoConfiguredOpenTelemetrySdk.builder(); String applicationInsightsConnectionString = System.getenv("APPLICATIONINSIGHTS_CONNECTION_STRING"); if (applicationInsightsConnectionString != null) { - AzureMonitorExporter.customize(sdkBuilder, - new AzureMonitorExporterOptions().connectionString(applicationInsightsConnectionString)); + AzureMonitorAutoConfigure.customize(sdkBuilder, applicationInsightsConnectionString); } else { System.setProperty("otel.traces.exporter", "none"); System.setProperty("otel.logs.exporter", "none"); diff --git a/sdk/clientcore/http-stress/src/main/java/module-info.java b/sdk/clientcore/http-stress/src/main/java/module-info.java index c7ad143213ce..0c6289081e8a 100644 --- a/sdk/clientcore/http-stress/src/main/java/module-info.java +++ b/sdk/clientcore/http-stress/src/main/java/module-info.java @@ -9,7 +9,7 @@ requires transitive io.clientcore.core; requires transitive io.clientcore.http.okhttp3; - requires azure.monitor.opentelemetry.exporter; + requires com.azure.monitor.opentelemetry.autoconfigure; requires com.azure.core; requires jcommander; requires io.opentelemetry.api; diff --git a/sdk/clientcore/optional-dependency-tests/README.md b/sdk/clientcore/optional-dependency-tests/README.md index f8d099bea9ea..a1f3290535ce 100644 --- a/sdk/clientcore/optional-dependency-tests/README.md +++ b/sdk/clientcore/optional-dependency-tests/README.md @@ -16,4 +16,4 @@ Tests that validate optional dependencies and features of the Core library. -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%clientcore%2Foptional-dependency-tests%2FREADME.png) + diff --git a/sdk/clientcore/optional-dependency-tests/pom.xml b/sdk/clientcore/optional-dependency-tests/pom.xml index 2dc7d8116531..a7c9a32d3779 100644 --- a/sdk/clientcore/optional-dependency-tests/pom.xml +++ b/sdk/clientcore/optional-dependency-tests/pom.xml @@ -8,7 +8,7 @@ io.clientcore clientcore-parent - 1.0.0-beta.1 + 1.0.0-beta.3 ../../parents/clientcore-parent @@ -56,14 +56,14 @@ io.clientcore core - 1.0.0-beta.2 + 1.0.0-beta.7 io.clientcore core - 1.0.0-beta.2 + 1.0.0-beta.7 test-jar test @@ -76,19 +76,19 @@ io.opentelemetry opentelemetry-sdk - 1.43.0 + 1.46.0 test io.opentelemetry opentelemetry-sdk-testing - 1.43.0 + 1.46.0 test io.opentelemetry opentelemetry-sdk-extension-autoconfigure - 1.43.0 + 1.46.0 test @@ -109,6 +109,12 @@ 1.37 test + + org.assertj + assertj-core + 3.22.0 + test + diff --git a/sdk/clientcore/optional-dependency-tests/src/samples/java/io/clientcore/core/instrumentation/TelemetryJavaDocCodeSnippets.java b/sdk/clientcore/optional-dependency-tests/src/samples/java/io/clientcore/core/instrumentation/TelemetryJavaDocCodeSnippets.java index 157d476671c2..9eef0ce01a75 100644 --- a/sdk/clientcore/optional-dependency-tests/src/samples/java/io/clientcore/core/instrumentation/TelemetryJavaDocCodeSnippets.java +++ b/sdk/clientcore/optional-dependency-tests/src/samples/java/io/clientcore/core/instrumentation/TelemetryJavaDocCodeSnippets.java @@ -3,6 +3,7 @@ package io.clientcore.core.instrumentation; +import io.clientcore.core.http.pipeline.HttpInstrumentationOptions; import io.clientcore.core.http.models.HttpMethod; import io.clientcore.core.http.models.HttpRequest; import io.clientcore.core.http.models.RequestOptions; @@ -10,8 +11,6 @@ import io.clientcore.core.http.pipeline.HttpInstrumentationPolicy; import io.clientcore.core.http.pipeline.HttpPipeline; import io.clientcore.core.http.pipeline.HttpPipelineBuilder; -import io.clientcore.core.instrumentation.tracing.SpanKind; -import io.clientcore.core.instrumentation.tracing.TracingScope; import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.api.OpenTelemetry; import io.opentelemetry.api.trace.Span; @@ -19,9 +18,6 @@ import io.opentelemetry.context.Scope; import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk; -import java.io.IOException; -import java.io.UncheckedIOException; - /** * Application developers are expected to configure OpenTelemetry * to leverage instrumentation code in client libraries. @@ -58,6 +54,8 @@ public void useGlobalOpenTelemetry() { AutoConfiguredOpenTelemetrySdk.initialize(); SampleClient client = new SampleClientBuilder().build(); + + // this call will be traced using OpenTelemetry SDK initialized globally client.clientCall(); // END: io.clientcore.core.telemetry.useglobalopentelemetry @@ -70,11 +68,13 @@ public void useGlobalOpenTelemetry() { public void useExplicitOpenTelemetry() { // BEGIN: io.clientcore.core.telemetry.useexplicitopentelemetry - OpenTelemetry openTelemetry = AutoConfiguredOpenTelemetrySdk.initialize().getOpenTelemetrySdk(); - InstrumentationOptions instrumentationOptions = new InstrumentationOptions() - .setProvider(openTelemetry); + OpenTelemetry openTelemetry = AutoConfiguredOpenTelemetrySdk.initialize().getOpenTelemetrySdk(); + HttpInstrumentationOptions instrumentationOptions = new HttpInstrumentationOptions() + .setTelemetryProvider(openTelemetry); SampleClient client = new SampleClientBuilder().instrumentationOptions(instrumentationOptions).build(); + + // this call will be traced using OpenTelemetry SDK provided explicitly client.clientCall(); // END: io.clientcore.core.telemetry.useexplicitopentelemetry @@ -87,7 +87,7 @@ public void useExplicitOpenTelemetry() { public void disableDistributedTracing() { // BEGIN: io.clientcore.core.telemetry.disabledistributedtracing - InstrumentationOptions instrumentationOptions = new InstrumentationOptions<>() + HttpInstrumentationOptions instrumentationOptions = new HttpInstrumentationOptions() .setTracingEnabled(false); SampleClient client = new SampleClientBuilder().instrumentationOptions(instrumentationOptions).build(); @@ -96,6 +96,22 @@ public void disableDistributedTracing() { // END: io.clientcore.core.telemetry.disabledistributedtracing } + /** + * This code snippet shows how to disable distributed tracing + * for a specific instance of client. + */ + public void disableMetrics() { + // BEGIN: io.clientcore.core.telemetry.disablemetrics + + HttpInstrumentationOptions instrumentationOptions = new HttpInstrumentationOptions() + .setMetricsEnabled(false); + + SampleClient client = new SampleClientBuilder().instrumentationOptions(instrumentationOptions).build(); + client.clientCall(); + + // END: io.clientcore.core.telemetry.disablemetrics + } + /** * This code snippet shows how to correlate spans from * client library with spans from application code @@ -132,6 +148,7 @@ public void correlationWithExplicitContext() { Tracer tracer = GlobalOpenTelemetry.getTracer("sample"); Span span = tracer.spanBuilder("my-operation") .startSpan(); + SampleClient client = new SampleClientBuilder().build(); // Propagating context implicitly is preferred way in synchronous code. @@ -148,60 +165,53 @@ public void correlationWithExplicitContext() { } static class SampleClientBuilder { - private InstrumentationOptions instrumentationOptions; - // TODO (limolkova): do we need InstrumentationTrait? - public SampleClientBuilder instrumentationOptions(InstrumentationOptions instrumentationOptions) { + private HttpInstrumentationOptions instrumentationOptions; + public SampleClientBuilder instrumentationOptions(HttpInstrumentationOptions instrumentationOptions) { this.instrumentationOptions = instrumentationOptions; return this; } public SampleClient build() { return new SampleClient(instrumentationOptions, new HttpPipelineBuilder() - .policies(new HttpInstrumentationPolicy(instrumentationOptions, null)) + .addPolicy(new HttpInstrumentationPolicy(instrumentationOptions)) .build()); } } static class SampleClient { - private final static LibraryInstrumentationOptions LIBRARY_OPTIONS = new LibraryInstrumentationOptions("sample"); + private static final String LIBRARY_NAME = "contoso.sample"; + private final Instrumentation instrumentation; private final HttpPipeline httpPipeline; - private final io.clientcore.core.instrumentation.tracing.Tracer tracer; + private final String serviceEndpoint; - SampleClient(InstrumentationOptions instrumentationOptions, HttpPipeline httpPipeline) { + SampleClient(InstrumentationOptions instrumentationOptions, HttpPipeline httpPipeline) { + serviceEndpoint = "https://contoso.com"; + LibraryInstrumentationOptions libraryOptions = new LibraryInstrumentationOptions(LIBRARY_NAME) + .setEndpoint(serviceEndpoint); this.httpPipeline = httpPipeline; - this.tracer = Instrumentation.create(instrumentationOptions, LIBRARY_OPTIONS).getTracer(); + this.instrumentation = Instrumentation.create(instrumentationOptions, libraryOptions); } - public void clientCall() { - this.clientCall(null); + public Response clientCall() { + return this.clientCallWithResponse(null); + } + + @SuppressWarnings("try") + public Response clientCallWithResponse(RequestOptions options) { + return instrumentation.instrumentWithResponse("Sample.call", options, this::clientCallWithResponseImpl); } @SuppressWarnings("try") public void clientCall(RequestOptions options) { - io.clientcore.core.instrumentation.tracing.Span span = tracer.spanBuilder("clientCall", SpanKind.CLIENT, null) - .startSpan(); - - if (options == null) { - options = new RequestOptions(); - } - - options.setInstrumentationContext(span.getInstrumentationContext()); - - try (TracingScope scope = span.makeCurrent()) { - Response response = httpPipeline.send(new HttpRequest(HttpMethod.GET, "https://example.com")); - response.close(); - span.end(); - } catch (Throwable t) { - span.end(t); - - if (t instanceof IOException) { - throw new UncheckedIOException((IOException) t); - } else if (t instanceof RuntimeException) { - throw (RuntimeException) t; - } else { - throw new RuntimeException(t); - } - } + instrumentation.instrument("Sample.call", options, this::clientCallImpl); + } + + private Response clientCallWithResponseImpl(RequestOptions options) { + return httpPipeline.send(new HttpRequest().setMethod(HttpMethod.GET).setUri(serviceEndpoint).setRequestOptions(options)); + } + + private void clientCallImpl(RequestOptions options) { + httpPipeline.send(new HttpRequest().setMethod(HttpMethod.GET).setUri(serviceEndpoint).setRequestOptions(options)); } } } diff --git a/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/http/pipeline/HttpInstrumentationPolicyTests.java b/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/http/pipeline/HttpInstrumentationPolicyTests.java index f6b4c6d12236..8b0bafb8966d 100644 --- a/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/http/pipeline/HttpInstrumentationPolicyTests.java +++ b/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/http/pipeline/HttpInstrumentationPolicyTests.java @@ -3,18 +3,20 @@ package io.clientcore.core.http.pipeline; -import io.clientcore.core.http.MockHttpResponse; import io.clientcore.core.http.models.HttpHeaderName; -import io.clientcore.core.http.models.HttpLogOptions; +import io.clientcore.core.http.models.HttpHeaders; import io.clientcore.core.http.models.HttpMethod; import io.clientcore.core.http.models.HttpRequest; import io.clientcore.core.http.models.RequestOptions; +import io.clientcore.core.http.models.Response; import io.clientcore.core.instrumentation.Instrumentation; import io.clientcore.core.instrumentation.InstrumentationContext; import io.clientcore.core.instrumentation.LibraryInstrumentationOptions; -import io.clientcore.core.instrumentation.InstrumentationOptions; +import io.clientcore.core.models.binarydata.BinaryData; import io.opentelemetry.api.OpenTelemetry; import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.AttributesBuilder; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.StatusCode; @@ -27,6 +29,13 @@ import io.opentelemetry.context.propagation.TextMapPropagator; import io.opentelemetry.context.propagation.TextMapSetter; import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.data.HistogramData; +import io.opentelemetry.sdk.metrics.data.HistogramPointData; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter; import io.opentelemetry.sdk.trace.IdGenerator; import io.opentelemetry.sdk.trace.ReadableSpan; @@ -45,13 +54,17 @@ import java.net.SocketException; import java.net.URI; import java.net.UnknownHostException; +import java.util.ArrayList; import java.util.Collection; import java.util.Collections; +import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Collectors; import static io.clientcore.core.http.models.HttpHeaderName.TRACEPARENT; import static io.clientcore.core.instrumentation.tracing.SpanKind.INTERNAL; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -75,22 +88,27 @@ public class HttpInstrumentationPolicyTests { private InMemorySpanExporter exporter; private SdkTracerProvider tracerProvider; + private SdkMeterProvider meterProvider; + private InMemoryMetricReader meterReader; private OpenTelemetry openTelemetry; - private InstrumentationOptions otelOptions; + private HttpInstrumentationOptions otelOptions; @BeforeEach public void setUp() { exporter = InMemorySpanExporter.create(); tracerProvider = SdkTracerProvider.builder().addSpanProcessor(SimpleSpanProcessor.create(exporter)).build(); - - openTelemetry = OpenTelemetrySdk.builder().setTracerProvider(tracerProvider).build(); - otelOptions = new InstrumentationOptions().setProvider(openTelemetry); + meterReader = InMemoryMetricReader.create(); + meterProvider = SdkMeterProvider.builder().registerMetricReader(meterReader).build(); + openTelemetry + = OpenTelemetrySdk.builder().setTracerProvider(tracerProvider).setMeterProvider(meterProvider).build(); + otelOptions = new HttpInstrumentationOptions().setTelemetryProvider(openTelemetry); } @AfterEach public void tearDown() { exporter.reset(); tracerProvider.close(); + meterProvider.close(); } @ParameterizedTest @@ -98,17 +116,20 @@ public void tearDown() { public void simpleRequestIsRecorded(int statusCode) throws IOException { AtomicReference current = new AtomicReference<>(); - HttpPipeline pipeline = new HttpPipelineBuilder().policies(new HttpInstrumentationPolicy(otelOptions, null)) - .httpClient(request -> { + HttpPipeline pipeline + = new HttpPipelineBuilder().addPolicy(new HttpInstrumentationPolicy(otelOptions)).httpClient(request -> { assertStartAttributes((ReadableSpan) Span.current(), request.getHttpMethod(), request.getUri()); assertNull(request.getHeaders().get(TRACESTATE)); - assertEquals(traceparent(Span.current()), request.getHeaders().get(TRACEPARENT).getValue()); + assertEquals(traceparent(Span.current().getSpanContext()), + request.getHeaders().get(TRACEPARENT).getValue()); current.set(Span.current()); - return new MockHttpResponse(request, statusCode); - }) - .build(); + return new Response<>(request, statusCode, new HttpHeaders(), BinaryData.empty()); + }).build(); + + long start = System.nanoTime(); + pipeline.send(new HttpRequest().setMethod(HttpMethod.GET).setUri("https://localhost/")).close(); + long duration = System.nanoTime() - start; - pipeline.send(new HttpRequest(HttpMethod.GET, "https://localhost/")).close(); assertNotNull(exporter.getFinishedSpanItems()); assertEquals(1, exporter.getFinishedSpanItems().size()); @@ -122,16 +143,25 @@ public void simpleRequestIsRecorded(int statusCode) throws IOException { assertNull(exportedSpan.getAttributes().get(ERROR_TYPE)); assertNull(exportedSpan.getAttributes().get(USER_AGENT_ORIGINAL)); assertEquals(StatusCode.UNSET, exportedSpan.getStatus().getStatusCode()); + + HistogramData durationHistogram + = assertDurationMetric(HttpMethod.GET, "localhost", 443, statusCode, null, exportedSpan.getSpanContext()); + List points = new ArrayList<>(durationHistogram.getPoints()); + assertEquals(1, points.size()); + assertDuration(duration, points.get(0)); } @ParameterizedTest @ValueSource(ints = { 400, 404, 500, 503 }) public void errorResponseIsRecorded(int statusCode) throws IOException { - HttpPipeline pipeline = new HttpPipelineBuilder().policies(new HttpInstrumentationPolicy(otelOptions, null)) - .httpClient(request -> new MockHttpResponse(request, statusCode)) + HttpPipeline pipeline = new HttpPipelineBuilder().addPolicy(new HttpInstrumentationPolicy(otelOptions)) + .httpClient(request -> new Response<>(request, statusCode, new HttpHeaders(), BinaryData.empty())) .build(); - pipeline.send(new HttpRequest(HttpMethod.GET, "https://localhost:8080/path/to/resource?query=param")).close(); + pipeline + .send(new HttpRequest().setMethod(HttpMethod.GET) + .setUri("https://localhost:8080/path/to/resource?query=param")) + .close(); assertNotNull(exporter.getFinishedSpanItems()); assertEquals(1, exporter.getFinishedSpanItems().size()); @@ -142,6 +172,9 @@ public void errorResponseIsRecorded(int statusCode) throws IOException { assertEquals(String.valueOf(statusCode), exportedSpan.getAttributes().get(ERROR_TYPE)); assertEquals(StatusCode.ERROR, exportedSpan.getStatus().getStatusCode()); assertEquals("", exportedSpan.getStatus().getDescription()); + + assertDurationMetric(HttpMethod.GET, "localhost", 8080, statusCode, String.valueOf(statusCode), + exportedSpan.getSpanContext()); } @SuppressWarnings("try") @@ -152,20 +185,23 @@ public void tracingWithRetries() throws IOException { try (Scope scope = testSpan.makeCurrent()) { AtomicInteger count = new AtomicInteger(0); - HttpPipeline pipeline = new HttpPipelineBuilder() - .policies(new HttpRetryPolicy(), new HttpInstrumentationPolicy(otelOptions, null)) + HttpPipeline pipeline = new HttpPipelineBuilder().addPolicy(new HttpRetryPolicy()) + .addPolicy(new HttpInstrumentationPolicy(otelOptions)) .httpClient(request -> { - assertEquals(traceparent(Span.current()), request.getHeaders().get(TRACEPARENT).getValue()); + assertEquals(traceparent(Span.current().getSpanContext()), + request.getHeaders().get(TRACEPARENT).getValue()); if (count.getAndIncrement() == 0) { throw new UnknownHostException("test exception"); } else { - return new MockHttpResponse(request, 200); + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); } }) .build(); - pipeline.send(new HttpRequest(HttpMethod.GET, "https://localhost:8080/path/to/resource?query=param")) - .close(); + long start = System.nanoTime(); + pipeline.send(new HttpRequest().setMethod(HttpMethod.GET) + .setUri("https://localhost:8080/path/to/resource?query=param")).close(); + long duration = System.nanoTime() - start; assertEquals(2, count.get()); assertNotNull(exporter.getFinishedSpanItems()); @@ -183,6 +219,32 @@ public void tracingWithRetries() throws IOException { 200); assertEquals(1L, successfulTry.getAttributes().get(HTTP_REQUEST_RESEND_COUNT)); assertNull(successfulTry.getAttributes().get(ERROR_TYPE)); + + List metrics = new ArrayList<>(meterReader.collectAllMetrics()); + assertEquals(1, metrics.size()); + assertEquals("http.client.request.duration", metrics.get(0).getName()); + + HistogramData histogram = (HistogramData) metrics.get(0).getData(); + List points = new ArrayList<>(histogram.getPoints()); + assertEquals(2, points.size()); + assertDuration(duration, points.get(0)); + assertDuration(duration, points.get(1)); + + HistogramPointData errorPoint = points.stream() + .filter(p -> p.getAttributes().get(ERROR_TYPE) != null) + .collect(Collectors.toList()) + .get(0); + + HistogramPointData successPoint = points.stream() + .filter(p -> p.getAttributes().get(ERROR_TYPE) == null) + .collect(Collectors.toList()) + .get(0); + + assertNull(errorPoint.getAttributes().get(HTTP_RESPONSE_STATUS_CODE)); + assertEquals(200, successPoint.getAttributes().get(HTTP_RESPONSE_STATUS_CODE)); + + assertNull(successPoint.getAttributes().get(ERROR_TYPE)); + assertEquals(UnknownHostException.class.getCanonicalName(), errorPoint.getAttributes().get(ERROR_TYPE)); } finally { testSpan.end(); } @@ -194,21 +256,27 @@ public void unsampledSpan() throws IOException { .setSampler(Sampler.alwaysOff()) .addSpanProcessor(SimpleSpanProcessor.create(exporter)) .build(); - OpenTelemetry openTelemetry = OpenTelemetrySdk.builder().setTracerProvider(sampleNone).build(); - InstrumentationOptions otelOptions - = new InstrumentationOptions().setProvider(openTelemetry); + OpenTelemetry openTelemetry + = OpenTelemetrySdk.builder().setTracerProvider(sampleNone).setMeterProvider(meterProvider).build(); + HttpInstrumentationOptions otelOptions = new HttpInstrumentationOptions().setTelemetryProvider(openTelemetry); - HttpPipeline pipeline = new HttpPipelineBuilder().policies(new HttpInstrumentationPolicy(otelOptions, null)) - .httpClient(request -> { - assertTrue(Span.current().getSpanContext().isValid()); - assertEquals(traceparent(Span.current()), request.getHeaders().get(TRACEPARENT).getValue()); - return new MockHttpResponse(request, 200); - }) - .build(); + AtomicReference spanContext = new AtomicReference<>(); + HttpPipeline pipeline + = new HttpPipelineBuilder().addPolicy(new HttpInstrumentationPolicy(otelOptions)).httpClient(request -> { + spanContext.set(Span.current().getSpanContext()); + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); + }).build(); + + HttpRequest request = new HttpRequest().setMethod(HttpMethod.GET).setUri("http://localhost/"); + pipeline.send(request).close(); + + assertTrue(spanContext.get().isValid()); + assertEquals(traceparent(spanContext.get()), request.getHeaders().get(TRACEPARENT).getValue()); - pipeline.send(new HttpRequest(HttpMethod.GET, "http://localhost/")).close(); assertNotNull(exporter.getFinishedSpanItems()); assertEquals(0, exporter.getFinishedSpanItems().size()); + + assertDurationMetric(HttpMethod.GET, "localhost", 80, 200, null, spanContext.get()); } @Test @@ -218,20 +286,22 @@ public void tracestateIsPropagated() throws IOException { = SpanContext.create(IdGenerator.random().generateTraceId(), IdGenerator.random().generateSpanId(), TraceFlags.getSampled(), TraceState.builder().put("key", "value").build()); - HttpPipeline pipeline = new HttpPipelineBuilder().policies(new HttpInstrumentationPolicy(otelOptions, null)) - .httpClient(request -> { + HttpPipeline pipeline + = new HttpPipelineBuilder().addPolicy(new HttpInstrumentationPolicy(otelOptions)).httpClient(request -> { assertEquals("key=value", request.getHeaders().get(TRACESTATE).getValue()); - assertEquals(traceparent(Span.current()), request.getHeaders().get(TRACEPARENT).getValue()); - return new MockHttpResponse(request, 200); - }) - .build(); + assertEquals(traceparent(Span.current().getSpanContext()), + request.getHeaders().get(TRACEPARENT).getValue()); + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); + }).build(); try (Scope scope = Span.wrap(parentContext).makeCurrent()) { - pipeline.send(new HttpRequest(HttpMethod.GET, "http://localhost/")).close(); + pipeline.send(new HttpRequest().setMethod(HttpMethod.POST).setUri("http://localhost/")).close(); } assertNotNull(exporter.getFinishedSpanItems()); assertEquals(1, exporter.getFinishedSpanItems().size()); + assertDurationMetric(HttpMethod.POST, "localhost", 80, 200, null, + exporter.getFinishedSpanItems().get(0).getSpanContext()); } @Test @@ -259,30 +329,28 @@ public io.opentelemetry.context.Context extract(io.opentelemetry.context.Con .setPropagators(ContextPropagators.create(testPropagator)) .build(); - InstrumentationOptions otelOptions - = new InstrumentationOptions().setProvider(openTelemetry); + HttpInstrumentationOptions otelOptions = new HttpInstrumentationOptions().setTelemetryProvider(openTelemetry); - HttpPipeline pipeline = new HttpPipelineBuilder().policies(new HttpInstrumentationPolicy(otelOptions, null)) - .httpClient(request -> { - assertEquals(traceparent(Span.current()), request.getHeaders().get(TRACEPARENT).getValue()); - return new MockHttpResponse(request, 200); - }) - .build(); + HttpPipeline pipeline + = new HttpPipelineBuilder().addPolicy(new HttpInstrumentationPolicy(otelOptions)).httpClient(request -> { + assertEquals(traceparent(Span.current().getSpanContext()), + request.getHeaders().get(TRACEPARENT).getValue()); + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); + }).build(); - pipeline.send(new HttpRequest(HttpMethod.GET, "http://localhost/")).close(); + pipeline.send(new HttpRequest().setMethod(HttpMethod.GET).setUri("http://localhost/")).close(); } @Test public void exceptionIsRecorded() { SocketException exception = new SocketException("test exception"); - HttpPipeline pipeline = new HttpPipelineBuilder().policies(new HttpInstrumentationPolicy(otelOptions, null)) - .httpClient(request -> { + HttpPipeline pipeline + = new HttpPipelineBuilder().addPolicy(new HttpInstrumentationPolicy(otelOptions)).httpClient(request -> { throw exception; - }) - .build(); + }).build(); assertThrows(UncheckedIOException.class, - () -> pipeline.send(new HttpRequest(HttpMethod.GET, "https://localhost/")).close()); + () -> pipeline.send(new HttpRequest().setMethod(HttpMethod.GET).setUri("https://localhost/")).close()); assertNotNull(exporter.getFinishedSpanItems()); assertEquals(1, exporter.getFinishedSpanItems().size()); @@ -291,33 +359,56 @@ public void exceptionIsRecorded() { assertEquals(exception.getClass().getCanonicalName(), exportedSpan.getAttributes().get(ERROR_TYPE)); assertEquals(StatusCode.ERROR, exportedSpan.getStatus().getStatusCode()); assertEquals(exception.getMessage(), exportedSpan.getStatus().getDescription()); + assertDurationMetric(HttpMethod.GET, "localhost", 443, -1, exception.getClass().getCanonicalName(), + exportedSpan.getSpanContext()); } @Test public void tracingIsDisabledOnInstance() throws IOException { - InstrumentationOptions options - = new InstrumentationOptions().setTracingEnabled(false).setProvider(openTelemetry); + HttpInstrumentationOptions options + = new HttpInstrumentationOptions().setTracingEnabled(false).setTelemetryProvider(openTelemetry); HttpPipeline pipeline - = new HttpPipelineBuilder().policies(new HttpInstrumentationPolicy(options, null)).httpClient(request -> { + = new HttpPipelineBuilder().addPolicy(new HttpInstrumentationPolicy(options)).httpClient(request -> { assertFalse(Span.current().getSpanContext().isValid()); assertFalse(Span.current().isRecording()); assertNull(request.getHeaders().get(TRACEPARENT)); - return new MockHttpResponse(request, 200); + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); }).build(); URI url = URI.create("http://localhost/"); - pipeline.send(new HttpRequest(HttpMethod.GET, url)).close(); + pipeline.send(new HttpRequest().setMethod(HttpMethod.GET).setUri(url)).close(); assertNotNull(exporter.getFinishedSpanItems()); assertEquals(0, exporter.getFinishedSpanItems().size()); + + assertDurationMetric(HttpMethod.GET, "localhost", 80, 200, null, SpanContext.getInvalid()); + } + + @Test + public void metricsDisabledOnInstance() throws IOException { + HttpInstrumentationOptions options + = new HttpInstrumentationOptions().setMetricsEnabled(false).setTelemetryProvider(openTelemetry); + HttpPipeline pipeline + = new HttpPipelineBuilder().addPolicy(new HttpInstrumentationPolicy(options)).httpClient(request -> { + assertTrue(Span.current().getSpanContext().isValid()); + assertTrue(Span.current().isRecording()); + assertNotNull(request.getHeaders().get(TRACEPARENT)); + return new Response<>(request, 200, new HttpHeaders(), BinaryData.empty()); + }).build(); + + URI url = URI.create("http://localhost/"); + pipeline.send(new HttpRequest().setMethod(HttpMethod.GET).setUri(url)).close(); + assertNotNull(exporter.getFinishedSpanItems()); + assertEquals(1, exporter.getFinishedSpanItems().size()); + assertEquals(0, meterReader.collectAllMetrics().size()); } @Test public void userAgentIsRecorded() throws IOException { - HttpPipeline pipeline = new HttpPipelineBuilder().policies(new HttpInstrumentationPolicy(otelOptions, null)) - .httpClient(request -> new MockHttpResponse(request, 200)) + HttpPipeline pipeline = new HttpPipelineBuilder().addPolicy(new HttpInstrumentationPolicy(otelOptions)) + .httpClient(request -> new Response<>(request, 200, new HttpHeaders(), BinaryData.empty())) .build(); - HttpRequest request = new HttpRequest(HttpMethod.GET, "https://localhost/"); + HttpRequest request = new HttpRequest().setMethod(HttpMethod.GET).setUri("https://localhost/"); request.getHeaders().set(HttpHeaderName.USER_AGENT, "test-user-agent"); pipeline.send(request).close(); @@ -332,25 +423,33 @@ public void userAgentIsRecorded() throws IOException { @Test public void enrichSpans() throws IOException { - HttpLogOptions logOptions = new HttpLogOptions().setLogLevel(HttpLogOptions.HttpLogDetailLevel.HEADERS); + HttpInstrumentationPolicy httpInstrumentationPolicy = new HttpInstrumentationPolicy( + otelOptions.setHttpLogLevel(HttpInstrumentationOptions.HttpLogLevel.HEADERS)); - HttpInstrumentationPolicy httpInstrumentationPolicy = new HttpInstrumentationPolicy(otelOptions, logOptions); - - HttpPipelinePolicy enrichingPolicy = (request, next) -> { - io.clientcore.core.instrumentation.tracing.Span span - = request.getRequestOptions().getInstrumentationContext().getSpan(); - if (span.isRecording()) { - span.setAttribute("custom.request.id", request.getHeaders().getValue(CUSTOM_REQUEST_ID)); + HttpPipelinePolicy enrichingPolicy = new HttpPipelinePolicy() { + @Override + public Response process(HttpRequest request, HttpPipelineNextPolicy next) { + io.clientcore.core.instrumentation.tracing.Span span + = request.getRequestOptions().getInstrumentationContext().getSpan(); + if (span.isRecording()) { + span.setAttribute("custom.request.id", request.getHeaders().getValue(CUSTOM_REQUEST_ID)); + } + + return next.process(); } - return next.process(); + @Override + public HttpPipelinePosition getPipelinePosition() { + return HttpPipelinePosition.AFTER_INSTRUMENTATION; + } }; - HttpPipeline pipeline = new HttpPipelineBuilder().policies(httpInstrumentationPolicy, enrichingPolicy) - .httpClient(request -> new MockHttpResponse(request, 200)) + HttpPipeline pipeline = new HttpPipelineBuilder().addPolicy(httpInstrumentationPolicy) + .addPolicy(enrichingPolicy) + .httpClient(request -> new Response<>(request, 200, new HttpHeaders(), BinaryData.empty())) .build(); - HttpRequest request = new HttpRequest(HttpMethod.GET, "https://localhost/"); + HttpRequest request = new HttpRequest().setMethod(HttpMethod.GET).setUri("https://localhost/"); request.getHeaders().set(CUSTOM_REQUEST_ID, "42"); pipeline.send(request).close(); @@ -371,12 +470,12 @@ public void implicitParent() throws IOException { Span testSpan = testTracer.spanBuilder("test").startSpan(); try (Scope scope = testSpan.makeCurrent()) { - HttpPipeline pipeline = new HttpPipelineBuilder().policies(new HttpInstrumentationPolicy(otelOptions, null)) - .httpClient(request -> new MockHttpResponse(request, 200)) + HttpPipeline pipeline = new HttpPipelineBuilder().addPolicy(new HttpInstrumentationPolicy(otelOptions)) + .httpClient(request -> new Response<>(request, 200, new HttpHeaders(), BinaryData.empty())) .build(); - pipeline.send(new HttpRequest(HttpMethod.GET, "https://localhost:8080/path/to/resource?query=param")) - .close(); + pipeline.send(new HttpRequest().setMethod(HttpMethod.GET) + .setUri("https://localhost:8080/path/to/resource?query=param")).close(); } finally { testSpan.end(); } @@ -395,14 +494,15 @@ public void explicitParent() throws IOException { Tracer testTracer = tracerProvider.get("test"); Span testSpan = testTracer.spanBuilder("test").startSpan(); - HttpPipeline pipeline = new HttpPipelineBuilder().policies(new HttpInstrumentationPolicy(otelOptions, null)) - .httpClient(request -> new MockHttpResponse(request, 200)) + HttpPipeline pipeline = new HttpPipelineBuilder().addPolicy(new HttpInstrumentationPolicy(otelOptions)) + .httpClient(request -> new Response<>(request, 200, new HttpHeaders(), BinaryData.empty())) .build(); RequestOptions requestOptions = new RequestOptions(); requestOptions.setInstrumentationContext(Instrumentation.createInstrumentationContext(testSpan)); - pipeline.send(new HttpRequest(HttpMethod.GET, "https://localhost:8080/path/to/resource?query=param") + pipeline.send(new HttpRequest().setMethod(HttpMethod.GET) + .setUri("https://localhost:8080/path/to/resource?query=param") .setRequestOptions(requestOptions)).close(); testSpan.end(); @@ -417,15 +517,13 @@ public void explicitParent() throws IOException { @Test public void customUrlRedaction() throws IOException { - HttpLogOptions logOptions = new HttpLogOptions().setAllowedQueryParamNames(Collections.singleton("key1")); - HttpPipeline pipeline - = new HttpPipelineBuilder().policies(new HttpInstrumentationPolicy(otelOptions, logOptions)) - .httpClient(request -> new MockHttpResponse(request, 200)) - .build(); + otelOptions.setAllowedQueryParamNames(Collections.singleton("key1")); + HttpPipeline pipeline = new HttpPipelineBuilder().addPolicy(new HttpInstrumentationPolicy(otelOptions)) + .httpClient(request -> new Response<>(request, 200, new HttpHeaders(), BinaryData.empty())) + .build(); - pipeline - .send(new HttpRequest(HttpMethod.GET, "https://localhost:8080/path/to/resource?query=param&key1=value1")) - .close(); + pipeline.send(new HttpRequest().setMethod(HttpMethod.GET) + .setUri("https://localhost:8080/path/to/resource?query=param&key1=value1")).close(); assertNotNull(exporter.getFinishedSpanItems()); assertEquals(1, exporter.getFinishedSpanItems().size()); @@ -446,11 +544,12 @@ public void explicitLibraryCallParent() throws IOException { requestOptions.setInstrumentationContext(parent.getInstrumentationContext()); - HttpPipeline pipeline = new HttpPipelineBuilder().policies(new HttpInstrumentationPolicy(otelOptions, null)) - .httpClient(request -> new MockHttpResponse(request, 200)) + HttpPipeline pipeline = new HttpPipelineBuilder().addPolicy(new HttpInstrumentationPolicy(otelOptions)) + .httpClient(request -> new Response<>(request, 200, new HttpHeaders(), BinaryData.empty())) .build(); - pipeline.send(new HttpRequest(HttpMethod.GET, "https://localhost:8080/path/to/resource?query=param") + pipeline.send(new HttpRequest().setMethod(HttpMethod.GET) + .setUri("https://localhost:8080/path/to/resource?query=param") .setRequestOptions(requestOptions)).close(); parent.end(); @@ -486,13 +585,58 @@ private void assertHttpSpan(SpanData span, HttpMethod method, String urlStr, Int assertNull(span.getAttributes().get(HTTP_RESPONSE_STATUS_CODE)); } - assertEquals("core", span.getInstrumentationScopeInfo().getName()); - assertNotNull(span.getInstrumentationScopeInfo().getVersion()); - assertEquals("https://opentelemetry.io/schemas/1.29.0", span.getInstrumentationScopeInfo().getSchemaUrl()); + assertInstrumentationScope(span.getInstrumentationScopeInfo()); + } + + private String traceparent(SpanContext context) { + return String.format("00-%s-%s-%s", context.getTraceId(), context.getSpanId(), context.getTraceFlags()); + } + + private HistogramData assertDurationMetric(HttpMethod method, String host, int port, int statusCode, + String errorType, SpanContext spanContext) { + AttributesBuilder attributesBuilder = Attributes.builder() + .put(AttributeKey.stringKey("server.address"), host) + .put(AttributeKey.longKey("server.port"), (long) port) + .put(AttributeKey.stringKey("http.request.method"), method.toString()); + if (statusCode > 0) { + attributesBuilder.put(AttributeKey.longKey("http.response.status_code"), (long) statusCode); + } + + if (errorType != null) { + attributesBuilder.put(AttributeKey.stringKey("error.type"), errorType); + } + + Collection metrics = meterReader.collectAllMetrics(); + assertThat(metrics).satisfiesExactly(metric -> OpenTelemetryAssertions.assertThat(metric) + .hasName("http.client.request.duration") + .hasDescription("Duration of HTTP client requests") + .hasUnit("s") + .hasHistogramSatisfying(h -> h.isCumulative().hasPointsSatisfying(point -> { + point.hasAttributes(attributesBuilder.build()) + .hasCount(1) + .hasBucketBoundaries(0.005d, 0.01d, 0.025d, 0.05d, 0.075d, 0.1d, 0.25d, 0.5d, 0.75d, 1d, 2.5d, 5d, + 7.5d, 10d); + + if (spanContext.isSampled()) { + point.hasExemplarsSatisfying( + exemplar -> exemplar.hasTraceId(spanContext.getTraceId()).hasSpanId(spanContext.getSpanId())); + } + }))); + + assertThat(metrics).satisfiesExactly(m -> assertInstrumentationScope(m.getInstrumentationScopeInfo())); + + return (HistogramData) metrics.iterator().next().getData(); + } + + private void assertInstrumentationScope(InstrumentationScopeInfo scope) { + assertThat(scope).satisfies(info -> { + assertThat(info.getName()).isEqualTo("core"); + assertThat(info.getVersion()).isNotNull(); + assertThat(info.getSchemaUrl()).isEqualTo("https://opentelemetry.io/schemas/1.29.0"); + }); } - private String traceparent(Span span) { - return String.format("00-%s-%s-%s", span.getSpanContext().getTraceId(), span.getSpanContext().getSpanId(), - span.getSpanContext().getTraceFlags()); + private void assertDuration(long approxDurationNs, HistogramPointData data) { + assertThat((long) (data.getSum() * 1_000_000_000L)).isStrictlyBetween(0L, approxDurationNs + 1); } } diff --git a/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/implementation/instrumentation/Slf4jLoggerShimIT.java b/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/implementation/instrumentation/Slf4jLoggerShimIT.java index 5a53c0d982cd..2fd28af7eed5 100644 --- a/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/implementation/instrumentation/Slf4jLoggerShimIT.java +++ b/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/implementation/instrumentation/Slf4jLoggerShimIT.java @@ -2,7 +2,7 @@ // Licensed under the MIT License. package io.clientcore.core.implementation.instrumentation; -import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.instrumentation.logging.LogLevel; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -67,17 +67,17 @@ public void slf4jLoggingLevelsAreInspectedCorrectly() { Slf4jLoggerShim shim = new Slf4jLoggerShim(Slf4jLoggerShimIT.class.getName()); // All logging levels should be enabled for Slf4jLoggerShimIT based on the simplelogger.properties in resources. - assertTrue(shim.canLogAtLevel(ClientLogger.LogLevel.VERBOSE)); - assertTrue(shim.canLogAtLevel(ClientLogger.LogLevel.INFORMATIONAL)); - assertTrue(shim.canLogAtLevel(ClientLogger.LogLevel.WARNING)); - assertTrue(shim.canLogAtLevel(ClientLogger.LogLevel.ERROR)); + assertTrue(shim.canLogAtLevel(LogLevel.VERBOSE)); + assertTrue(shim.canLogAtLevel(LogLevel.INFORMATIONAL)); + assertTrue(shim.canLogAtLevel(LogLevel.WARNING)); + assertTrue(shim.canLogAtLevel(LogLevel.ERROR)); shim = new Slf4jLoggerShim(Slf4jLoggerShim.class); // But the default log level should be INFO for everything else. - assertFalse(shim.canLogAtLevel(ClientLogger.LogLevel.VERBOSE)); - assertTrue(shim.canLogAtLevel(ClientLogger.LogLevel.INFORMATIONAL)); - assertTrue(shim.canLogAtLevel(ClientLogger.LogLevel.WARNING)); - assertTrue(shim.canLogAtLevel(ClientLogger.LogLevel.ERROR)); + assertFalse(shim.canLogAtLevel(LogLevel.VERBOSE)); + assertTrue(shim.canLogAtLevel(LogLevel.INFORMATIONAL)); + assertTrue(shim.canLogAtLevel(LogLevel.WARNING)); + assertTrue(shim.canLogAtLevel(LogLevel.ERROR)); } } diff --git a/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/instrumentation/ContextPropagationTests.java b/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/instrumentation/ContextPropagationTests.java index d603fdf3c0ea..d37277f70b6b 100644 --- a/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/instrumentation/ContextPropagationTests.java +++ b/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/instrumentation/ContextPropagationTests.java @@ -49,7 +49,7 @@ public String get(Map carrier, String key) { private InMemorySpanExporter exporter; private SdkTracerProvider tracerProvider; - private InstrumentationOptions otelOptions; + private InstrumentationOptions otelOptions; private Tracer tracer; private TraceContextPropagator contextPropagator; private Instrumentation instrumentation; @@ -60,7 +60,7 @@ public void setUp() { tracerProvider = SdkTracerProvider.builder().addSpanProcessor(SimpleSpanProcessor.create(exporter)).build(); OpenTelemetry openTelemetry = OpenTelemetrySdk.builder().setTracerProvider(tracerProvider).build(); - otelOptions = new InstrumentationOptions().setProvider(openTelemetry); + otelOptions = new InstrumentationOptions().setTelemetryProvider(openTelemetry); instrumentation = Instrumentation.create(otelOptions, DEFAULT_LIB_OPTIONS); tracer = instrumentation.getTracer(); contextPropagator = instrumentation.getW3CTraceContextPropagator(); diff --git a/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/instrumentation/InstrumentationTests.java b/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/instrumentation/InstrumentationTests.java index aa766c1a51e5..9cfdb93cf69a 100644 --- a/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/instrumentation/InstrumentationTests.java +++ b/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/instrumentation/InstrumentationTests.java @@ -3,15 +3,20 @@ package io.clientcore.core.instrumentation; +import io.clientcore.core.implementation.instrumentation.otel.OTelAttributes; +import io.clientcore.core.instrumentation.metrics.DoubleHistogram; +import io.clientcore.core.instrumentation.metrics.LongCounter; +import io.clientcore.core.instrumentation.metrics.Meter; import io.clientcore.core.instrumentation.tracing.Span; import io.clientcore.core.instrumentation.tracing.Tracer; import io.clientcore.core.instrumentation.tracing.TracingScope; import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.api.OpenTelemetry; +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.TraceFlags; import io.opentelemetry.api.trace.TraceState; -import io.opentelemetry.api.trace.TracerProvider; import io.opentelemetry.context.Context; import io.opentelemetry.sdk.OpenTelemetrySdk; import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter; @@ -26,12 +31,18 @@ import org.junit.jupiter.api.parallel.ExecutionMode; import org.junit.jupiter.api.parallel.Isolated; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + import static io.clientcore.core.instrumentation.logging.InstrumentationTestUtils.createInvalidInstrumentationContext; import static io.clientcore.core.instrumentation.logging.InstrumentationTestUtils.createRandomInstrumentationContext; import static io.clientcore.core.instrumentation.tracing.SpanKind.INTERNAL; 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.assertNotSame; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -66,8 +77,8 @@ public void createTracerOTelNotConfigured() { public void createTracerTracingDisabled() { OpenTelemetry otel = OpenTelemetrySdk.builder().setTracerProvider(tracerProvider).buildAndRegisterGlobal(); - InstrumentationOptions options - = new InstrumentationOptions().setTracingEnabled(false).setProvider(otel); + InstrumentationOptions options + = new InstrumentationOptions().setTracingEnabled(false).setTelemetryProvider(otel); Tracer tracer = Instrumentation.create(options, DEFAULT_LIB_OPTIONS).getTracer(); assertFalse(tracer.isEnabled()); @@ -82,7 +93,8 @@ public void createTracerGlobalOTel() throws Exception { try (AutoCloseable otel = OpenTelemetrySdk.builder().setTracerProvider(tracerProvider).buildAndRegisterGlobal()) { - Tracer tracer = Instrumentation.create(null, DEFAULT_LIB_OPTIONS).getTracer(); + Instrumentation instrumentation = Instrumentation.create(null, DEFAULT_LIB_OPTIONS); + Tracer tracer = instrumentation.getTracer(); assertTrue(tracer.isEnabled()); tracer.spanBuilder("test", INTERNAL, null).startSpan().end(); @@ -109,7 +121,7 @@ public void createTracerExplicitOTel() throws Exception { OpenTelemetry localOTel = OpenTelemetrySdk.builder().setTracerProvider(localTracerProvider).build(); Tracer tracer = Instrumentation - .create(new InstrumentationOptions().setProvider(localOTel), DEFAULT_LIB_OPTIONS) + .create(new InstrumentationOptions().setTelemetryProvider(localOTel), DEFAULT_LIB_OPTIONS) .getTracer(); assertTrue(tracer.isEnabled()); @@ -123,8 +135,7 @@ public void createTracerExplicitOTel() throws Exception { @Test public void createTracerBadArguments() { - InstrumentationOptions options - = new InstrumentationOptions().setProvider(tracerProvider); + InstrumentationOptions options = new InstrumentationOptions().setTelemetryProvider(tracerProvider); assertThrows(IllegalArgumentException.class, () -> Instrumentation.create(options, DEFAULT_LIB_OPTIONS).getTracer()); @@ -175,7 +186,7 @@ public void createInstrumentationContextFromOTelSpan() { assertEquals(otelSpan.getSpanContext().getTraceFlags().asHex(), context.getTraceFlags()); Tracer tracer - = Instrumentation.create(new InstrumentationOptions().setProvider(otel), DEFAULT_LIB_OPTIONS) + = Instrumentation.create(new InstrumentationOptions().setTelemetryProvider(otel), DEFAULT_LIB_OPTIONS) .getTracer(); Span span = tracer.spanBuilder("test", INTERNAL, context).startSpan(); assertEquals(otelSpan.getSpanContext().getTraceId(), span.getInstrumentationContext().getTraceId()); @@ -219,7 +230,7 @@ public void createInstrumentationContextFromOTelSpanContext() { assertEquals(otelSpanContext.getTraceFlags().asHex(), context.getTraceFlags()); Tracer tracer - = Instrumentation.create(new InstrumentationOptions().setProvider(otel), DEFAULT_LIB_OPTIONS) + = Instrumentation.create(new InstrumentationOptions().setTelemetryProvider(otel), DEFAULT_LIB_OPTIONS) .getTracer(); Span span = tracer.spanBuilder("test", INTERNAL, context).startSpan(); assertEquals(otelSpanContext.getTraceId(), span.getInstrumentationContext().getTraceId()); @@ -256,4 +267,163 @@ public void createInstrumentationContextFromInvalidContext() { assertFalse(context.isValid()); assertNotNull(context.getSpan()); } + + @Test + public void testCreateMeterAndInstruments() { + Instrumentation instrumentation = Instrumentation.create(null, DEFAULT_LIB_OPTIONS); + Meter meter = instrumentation.getMeter(); + assertTrue(meter.isEnabled()); + + InstrumentationAttributes attributes = instrumentation.createAttributes(Collections.emptyMap()); + DoubleHistogram histogram = meter.createDoubleHistogram("test", "description", "By", null); + histogram.record(42.0, attributes, null); + assertTrue(histogram.isEnabled()); + + LongCounter counter = meter.createLongCounter("test", "description", "1"); + counter.add(42, attributes, null); + assertTrue(counter.isEnabled()); + + LongCounter upDownCounter = meter.createLongUpDownCounter("test", "description", "1"); + upDownCounter.add(42, attributes, null); + assertTrue(upDownCounter.isEnabled()); + } + + @Test + public void testInvalidParams() { + Instrumentation instrumentation = Instrumentation.create(null, DEFAULT_LIB_OPTIONS); + Meter meter = instrumentation.getMeter(); + + assertThrows(NullPointerException.class, () -> meter.createDoubleHistogram("test", null, "1", null)); + assertThrows(NullPointerException.class, () -> meter.createLongCounter("test", null, "1")); + assertThrows(NullPointerException.class, () -> meter.createLongUpDownCounter("test", null, "1")); + assertThrows(NullPointerException.class, () -> meter.createDoubleHistogram(null, "description", "1", null)); + assertThrows(NullPointerException.class, () -> meter.createLongCounter(null, "description", "1")); + assertThrows(NullPointerException.class, () -> meter.createLongUpDownCounter(null, "description", "1")); + assertThrows(NullPointerException.class, () -> meter.createDoubleHistogram("test", "description", null, null)); + assertThrows(NullPointerException.class, () -> meter.createLongCounter("test", "description", null)); + assertThrows(NullPointerException.class, () -> meter.createLongUpDownCounter("test", "description", null)); + + DoubleHistogram histogram = meter.createDoubleHistogram("test", "description", "1", null); + assertThrows(NullPointerException.class, () -> histogram.record(42.0, null, null)); + + LongCounter counter = meter.createLongCounter("test", "description", "1"); + assertThrows(NullPointerException.class, () -> counter.add(42, null, null)); + + LongCounter upDownCounter = meter.createLongUpDownCounter("test", "description", "1"); + assertThrows(NullPointerException.class, () -> upDownCounter.add(42, null, null)); + } + + @Test + public void testCreateAttributes() { + Instrumentation instrumentation = Instrumentation.create(null, DEFAULT_LIB_OPTIONS); + InstrumentationAttributes attributes = instrumentation.createAttributes(Collections.emptyMap()); + assertInstanceOf(OTelAttributes.class, attributes); + + // does not throw + attributes.put("key", "value1"); + attributes.put("key", "value2"); + instrumentation.createAttributes(null); + } + + @Test + public void testAttributesInvalidParams() { + Instrumentation instrumentation = Instrumentation.create(null, DEFAULT_LIB_OPTIONS); + assertThrows(NullPointerException.class, + () -> instrumentation.createAttributes(Collections.singletonMap(null, "value"))); + assertThrows(NullPointerException.class, + () -> instrumentation.createAttributes(Collections.singletonMap("key", null))); + InstrumentationAttributes attributes = instrumentation.createAttributes(null); + assertThrows(NullPointerException.class, () -> attributes.put(null, "value")); + assertThrows(NullPointerException.class, () -> attributes.put("key", null)); + } + + @Test + public void testAttributes() { + Instrumentation instrumentation = Instrumentation.create(null, DEFAULT_LIB_OPTIONS); + Map start = new HashMap<>(); + start.put("string", "value"); + start.put("int", 42); + start.put("double", 0.42); + start.put("float", 4.2f); + start.put("boolean", true); + start.put("long", 420L); + + InstrumentationAttributes attributes = instrumentation.createAttributes(start); + OTelAttributes otelAttributes = (OTelAttributes) attributes; + Object otelAttrs = otelAttributes.getOTelAttributes(); + assertInstanceOf(Attributes.class, otelAttrs); + + Attributes attrs = (Attributes) otelAttrs; + assertEquals(6, attrs.size()); + assertEquals("value", attrs.get(AttributeKey.stringKey("string"))); + assertEquals(42L, attrs.get(AttributeKey.longKey("int"))); + assertEquals(420L, attrs.get(AttributeKey.longKey("long"))); + assertEquals(0.42, attrs.get(AttributeKey.doubleKey("double"))); + assertEquals(4.2f, attrs.get(AttributeKey.doubleKey("float")), 0.1); + assertEquals(true, attrs.get(AttributeKey.booleanKey("boolean"))); + + InstrumentationAttributes attributes2 = attributes.put("string2", "value2"); + + assertNotSame(attributes, attributes2); + assertNull(attrs.get(AttributeKey.stringKey("string2"))); + assertEquals(6, attrs.size()); + + attributes2 = attributes2.put("int2", 24) + .put("double2", 0.24) + .put("float2", 2.4f) + .put("boolean2", false) + .put("long2", 240L); + + attrs = (Attributes) ((OTelAttributes) attributes2).getOTelAttributes(); + assertEquals(12, attrs.size()); + assertEquals("value2", attrs.get(AttributeKey.stringKey("string2"))); + assertEquals(24L, attrs.get(AttributeKey.longKey("int2"))); + assertEquals(240L, attrs.get(AttributeKey.longKey("long2"))); + assertEquals(0.24, attrs.get(AttributeKey.doubleKey("double2"))); + assertEquals(2.4f, attrs.get(AttributeKey.doubleKey("float2")), 0.1); + assertEquals(false, attrs.get(AttributeKey.booleanKey("boolean2"))); + } + + @Test + public void testDuplicates() { + Instrumentation instrumentation = Instrumentation.create(null, DEFAULT_LIB_OPTIONS); + Map start = new HashMap<>(); + start.put("string", "value1"); + start.put("string", "value2"); + + InstrumentationAttributes attributes + = instrumentation.createAttributes(start).put("string", "value3").put("string", "value4"); + Object otelAttrs = ((OTelAttributes) attributes).getOTelAttributes(); + + Attributes attrs = (Attributes) otelAttrs; + assertEquals(1, attrs.size()); + assertEquals("value4", attrs.get(AttributeKey.stringKey("string"))); + } + + /*@Test + public void testSuppression() { + OpenTelemetry otel = OpenTelemetrySdk.builder().setTracerProvider(tracerProvider).buildAndRegisterGlobal(); + InstrumentationOptions options = new InstrumentationOptions().setTelemetryProvider(otel); + Instrumentation instrumentation = Instrumentation.create(options, DEFAULT_LIB_OPTIONS, null); + assertTrue(instrumentation.shouldInstrument(CLIENT, null)); + + Tracer tracer = instrumentation.getTracer(); + Span span = tracer.spanBuilder("test", CLIENT, null).startSpan(); + + assertFalse(instrumentation.shouldInstrument(CLIENT, span.getInstrumentationContext())); + assertTrue(instrumentation.shouldInstrument(INTERNAL, span.getInstrumentationContext())); + assertTrue(instrumentation.shouldInstrument(CONSUMER, span.getInstrumentationContext())); + assertTrue(instrumentation.shouldInstrument(PRODUCER, span.getInstrumentationContext())); + assertTrue(instrumentation.shouldInstrument(SERVER, span.getInstrumentationContext())); + } + + @Test + public void testSuppressionTracingAndMetricsDisabled() { + OpenTelemetry otel = OpenTelemetrySdk.builder().setTracerProvider(tracerProvider).buildAndRegisterGlobal(); + + InstrumentationOptions options + = new InstrumentationOptions().setTracingEnabled(false).setMetricsEnabled(false).setTelemetryProvider(otel); + + assertFalse(Instrumentation.create(options, DEFAULT_LIB_OPTIONS, null).shouldInstrument(CLIENT, null)); + }*/ } diff --git a/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/instrumentation/MeterTests.java b/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/instrumentation/MeterTests.java new file mode 100644 index 000000000000..63548a721eb5 --- /dev/null +++ b/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/instrumentation/MeterTests.java @@ -0,0 +1,253 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.instrumentation; + +import io.clientcore.core.instrumentation.metrics.DoubleHistogram; +import io.clientcore.core.instrumentation.metrics.LongCounter; +import io.clientcore.core.instrumentation.metrics.Meter; +import io.clientcore.core.instrumentation.tracing.Span; +import io.clientcore.core.instrumentation.tracing.SpanKind; +import io.clientcore.core.instrumentation.tracing.Tracer; +import io.opentelemetry.api.OpenTelemetry; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import io.opentelemetry.sdk.testing.time.TestClock; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; + +public class MeterTests { + private static final LibraryInstrumentationOptions DEFAULT_LIB_OPTIONS + = new LibraryInstrumentationOptions("test-library"); + private static final Resource RESOURCE + = Resource.create(Attributes.of(stringKey("resource_key"), "resource_value")); + private static final InstrumentationScopeInfo INSTRUMENTATION_SCOPE + = InstrumentationScopeInfo.builder(DEFAULT_LIB_OPTIONS.getLibraryName()) + .setVersion(DEFAULT_LIB_OPTIONS.getLibraryVersion()) + .setSchemaUrl(DEFAULT_LIB_OPTIONS.getSchemaUrl()) + .build(); + private static final long SECOND_NANOS = 1_000_000_000; + + private SdkMeterProvider meterProvider; + private Meter meter; + private InMemoryMetricReader sdkMeterReader; + private TestClock testClock; + private Instrumentation instrumentation; + private InstrumentationAttributes emptyAttributes; + + @BeforeEach + public void setUp() { + testClock = TestClock.create(); + sdkMeterReader = InMemoryMetricReader.create(); + + meterProvider = SdkMeterProvider.builder() + .setResource(RESOURCE) + .setClock(testClock) + .registerMetricReader(sdkMeterReader) + .build(); + + OpenTelemetry openTelemetry = OpenTelemetrySdk.builder().setMeterProvider(meterProvider).build(); + InstrumentationOptions otelOptions = new InstrumentationOptions().setTelemetryProvider(openTelemetry); + instrumentation = Instrumentation.create(otelOptions, DEFAULT_LIB_OPTIONS); + emptyAttributes = instrumentation.createAttributes(null); + meter = instrumentation.getMeter(); + } + + @AfterEach + public void tearDown() { + meterProvider.close(); + } + + @Test + public void basicHistogram() { + assertTrue(meter.isEnabled()); + DoubleHistogram histogram = meter.createDoubleHistogram("core.test-histogram", "important metric", "s", null); + assertTrue(histogram.isEnabled()); + histogram.record(1, emptyAttributes, null); + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + assertThat(sdkMeterReader.collectAllMetrics()).satisfiesExactly(metric -> assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE) + .hasName("core.test-histogram") + .hasDescription("important metric") + .hasHistogramSatisfying(h -> h.isCumulative() + .hasPointsSatisfying(point -> point.hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasCount(1) + .hasSum(1) + .hasBucketBoundaries(0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1_000, 2_500, 5_000, 7_500, 10_000) + .hasBucketCounts(0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)))); + } + + @Test + public void histogramWithAttributesAndBoundaries() { + Map attributesMap = new HashMap<>(); + attributesMap.put("key1", "value"); + attributesMap.put("key2", 42); + InstrumentationAttributes attributes = instrumentation.createAttributes(attributesMap); + + Attributes otelAttributes = Attributes.builder().put("key1", "value").put("key2", 42).build(); + + DoubleHistogram histogram = meter.createDoubleHistogram("core.test-histogram", "important metric", "unit", + Arrays.asList(0d, 1d, 2d, 42d)); + histogram.record(1, attributes, null); + histogram.record(10, attributes, null); + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + assertThat(sdkMeterReader.collectAllMetrics()) + .satisfiesExactly(metric -> assertThat(metric).hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE) + .hasName("core.test-histogram") + .hasDescription("important metric") + .hasUnit("unit") + .hasHistogramSatisfying(h -> h.isCumulative() + .hasPointsSatisfying(point -> point.hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(otelAttributes) + .hasCount(2) + .hasSum(11) + .hasBucketBoundaries(0, 1, 2, 42) + .hasBucketCounts(0, 1, 0, 1, 0)))); + } + + @Test + public void histogramWithContext() { + DoubleHistogram histogram + = meter.createDoubleHistogram("core.test-histogram", "important metric", "unit", null); + InstrumentationAttributes attributes + = instrumentation.createAttributes(Collections.singletonMap("key1", "value")); + Attributes otelAttributes = Attributes.builder().put("key1", "value").build(); + + Tracer tracer = instrumentation.getTracer(); + Span span = tracer.spanBuilder("test-span", SpanKind.CLIENT, null).startSpan(); + InstrumentationContext context = Instrumentation.createInstrumentationContext(span); + + histogram.record(42, attributes, context); + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + assertThat(sdkMeterReader.collectAllMetrics()).satisfiesExactly(metric -> assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE) + .hasName("core.test-histogram") + .hasDescription("important metric") + .hasUnit("unit") + .hasHistogramSatisfying(h -> h.isCumulative() + .hasPointsSatisfying(point -> point.hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(otelAttributes) + .hasCount(1) + .hasSum(42) + .hasBucketBoundaries(0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1_000, 2_500, 5_000, 7_500, 10_000) + .hasBucketCounts(0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) + .hasExemplarsSatisfying(exemplar -> exemplar.hasValue(42) + .hasTraceId(span.getInstrumentationContext().getTraceId()) + .hasSpanId(span.getInstrumentationContext().getSpanId()))))); + } + + @Test + public void basicCounter() { + LongCounter longCounter = meter.createLongCounter("core.test-counter", "important metric", "1"); + assertTrue(longCounter.isEnabled()); + longCounter.add(1, emptyAttributes, null); + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + assertThat(sdkMeterReader.collectAllMetrics()) + .satisfiesExactly(metric -> assertThat(metric).hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE) + .hasName("core.test-counter") + .hasDescription("important metric") + .hasLongSumSatisfying(s -> s.isCumulative() + .hasPointsSatisfying(point -> point.hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(1)))); + } + + @Test + public void counterWithAttributes() { + Map attributesMap = new HashMap<>(); + attributesMap.put("key1", "value"); + attributesMap.put("key2", 42); + InstrumentationAttributes attributes = instrumentation.createAttributes(attributesMap); + + Attributes otelAttributes = Attributes.builder().put("key1", "value").put("key2", 42).build(); + + LongCounter longCounter = meter.createLongCounter("core.test-counter", "important metric", "unit"); + assertTrue(longCounter.isEnabled()); + longCounter.add(42, attributes, null); + longCounter.add(1, attributes, null); + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + assertThat(sdkMeterReader.collectAllMetrics()) + .satisfiesExactly(metric -> assertThat(metric).hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE) + .hasName("core.test-counter") + .hasDescription("important metric") + .hasUnit("unit") + .hasLongSumSatisfying(s -> s.isCumulative() + .hasPointsSatisfying(point -> point.hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(otelAttributes) + .hasValue(43)))); + } + + @Test + public void basicUpDownCounter() { + LongCounter longCounter = meter.createLongUpDownCounter("core.test-updowncounter", "important metric", "1"); + assertTrue(longCounter.isEnabled()); + longCounter.add(1, emptyAttributes, null); + longCounter.add(1, emptyAttributes, null); + longCounter.add(-1, emptyAttributes, null); + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + assertThat(sdkMeterReader.collectAllMetrics()) + .satisfiesExactly(metric -> assertThat(metric).hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE) + .hasName("core.test-updowncounter") + .hasDescription("important metric") + .hasLongSumSatisfying(s -> s.isCumulative() + .hasPointsSatisfying(point -> point.hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(1)))); + } + + @Test + public void upDownCounterWithAttributes() { + Map attributesMap = new HashMap<>(); + attributesMap.put("key1", "value"); + attributesMap.put("key2", 42); + InstrumentationAttributes attributes = instrumentation.createAttributes(attributesMap); + + Attributes otelAttributes = Attributes.builder().put("key1", "value").put("key2", 42).build(); + + LongCounter longCounter = meter.createLongUpDownCounter("core.test-updowncounter", "important metric", "unit"); + assertTrue(longCounter.isEnabled()); + longCounter.add(42, attributes, null); + longCounter.add(-1, attributes, null); + longCounter.add(-42, attributes, null); + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + assertThat(sdkMeterReader.collectAllMetrics()) + .satisfiesExactly(metric -> assertThat(metric).hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE) + .hasName("core.test-updowncounter") + .hasDescription("important metric") + .hasUnit("unit") + .hasLongSumSatisfying(s -> s.isCumulative() + .hasPointsSatisfying(point -> point.hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(otelAttributes) + .hasValue(-1)))); + } +} diff --git a/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/instrumentation/OperationInstrumentationTests.java b/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/instrumentation/OperationInstrumentationTests.java new file mode 100644 index 000000000000..808245a50b8c --- /dev/null +++ b/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/instrumentation/OperationInstrumentationTests.java @@ -0,0 +1,362 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package io.clientcore.core.instrumentation; + +import io.clientcore.core.http.models.RequestOptions; +import io.clientcore.core.instrumentation.tracing.SpanKind; +import io.opentelemetry.api.OpenTelemetry; +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.AttributesBuilder; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter; +import io.opentelemetry.sdk.testing.time.TestClock; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.data.SpanData; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.net.URI; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class OperationInstrumentationTests { + private static final String DEFAULT_ENDPOINT = "https://localhost"; + + private InMemorySpanExporter exporter; + private SdkTracerProvider tracerProvider; + private SdkMeterProvider meterProvider; + private InMemoryMetricReader meterReader; + private TestClock testClock; + + private InstrumentationOptions otelOptions; + private LibraryInstrumentationOptions libraryInstrumentationOptions + = new LibraryInstrumentationOptions("test-lib").setLibraryVersion("1.0.0") + .setSchemaUrl("https://opentelemetry.io/schemas/1.29.0"); + + @BeforeEach + public void setUp() { + exporter = InMemorySpanExporter.create(); + tracerProvider = SdkTracerProvider.builder().addSpanProcessor(SimpleSpanProcessor.create(exporter)).build(); + testClock = TestClock.create(); + meterReader = InMemoryMetricReader.create(); + + meterProvider = SdkMeterProvider.builder().setClock(testClock).registerMetricReader(meterReader).build(); + + OpenTelemetry openTelemetry + = OpenTelemetrySdk.builder().setTracerProvider(tracerProvider).setMeterProvider(meterProvider).build(); + otelOptions = new InstrumentationOptions().setTelemetryProvider(openTelemetry); + } + + @AfterEach + public void tearDown() { + exporter.reset(); + tracerProvider.close(); + } + + @Test + public void invalidArguments() { + Instrumentation instrumentation = Instrumentation.create(otelOptions, libraryInstrumentationOptions); + assertThrows(NullPointerException.class, + () -> instrumentation.instrumentWithResponse(null, new RequestOptions(), o -> "done")); + assertThrows(NullPointerException.class, () -> instrumentation.instrument("call", new RequestOptions(), null)); + } + + @Test + public void basicCall() { + Instrumentation instrumentation + = Instrumentation.create(otelOptions, libraryInstrumentationOptions.setEndpoint(DEFAULT_ENDPOINT)); + + AtomicReference current = new AtomicReference<>(); + instrumentation.instrument("call", null, options -> { + current.set(Span.current()); + assertTrue(current.get().getSpanContext().isValid()); + assertEquals(current.get().getSpanContext().getTraceId(), options.getInstrumentationContext().getTraceId()); + assertEquals(current.get().getSpanContext().getSpanId(), options.getInstrumentationContext().getSpanId()); + }); + + assertFalse(Span.current().getSpanContext().isValid()); + assertEquals(1, exporter.getFinishedSpanItems().size()); + assertCallSpan(exporter.getFinishedSpanItems().get(0), "call", SpanKind.CLIENT, "localhost", 443L, null); + + Collection metrics = meterReader.collectAllMetrics(); + assertDurationMetric(metrics, "test.lib.client.operation.duration", "call", "localhost", 443L, null, + current.get().getSpanContext()); + } + + @Test + public void callWithError() { + Instrumentation instrumentation + = Instrumentation.create(otelOptions, libraryInstrumentationOptions.setEndpoint(DEFAULT_ENDPOINT)); + RuntimeException error = new RuntimeException("Test error"); + assertThrows(RuntimeException.class, + () -> instrumentation.instrument("call", new RequestOptions(), (Consumer) o -> { + throw error; + })); + + assertEquals(1, exporter.getFinishedSpanItems().size()); + SpanData spanData = exporter.getFinishedSpanItems().get(0); + assertCallSpan(spanData, "call", SpanKind.CLIENT, "localhost", 443L, error.getClass().getCanonicalName()); + Collection metrics = meterReader.collectAllMetrics(); + assertDurationMetric(metrics, "test.lib.client.operation.duration", "call", "localhost", 443L, + error.getClass().getCanonicalName(), spanData.getSpanContext()); + } + + @Test + public void noEndpoint() { + Instrumentation instrumentation = Instrumentation.create(otelOptions, libraryInstrumentationOptions); + instrumentation.instrument("call", RequestOptions.none(), __ -> { + }); + + assertEquals(1, exporter.getFinishedSpanItems().size()); + SpanData spanData = exporter.getFinishedSpanItems().get(0); + assertCallSpan(spanData, "call", SpanKind.CLIENT, null, null, null); + Collection metrics = meterReader.collectAllMetrics(); + assertDurationMetric(metrics, "test.lib.client.operation.duration", "call", null, null, null, + spanData.getSpanContext()); + } + + @ParameterizedTest + @ValueSource(strings = { "http://example.com", "https://example.com:8080", "http://example.com:9090" }) + public void testEndpoints(String endpoint) { + Instrumentation instrumentation + = Instrumentation.create(otelOptions, libraryInstrumentationOptions.setEndpoint(endpoint)); + instrumentation.instrument("Call", new RequestOptions(), __ -> { + }); + + assertEquals(1, exporter.getFinishedSpanItems().size()); + SpanData spanData = exporter.getFinishedSpanItems().get(0); + + URI uri = URI.create(endpoint); + Long expectedPort = uri.getPort() == -1 ? 80 : (long) uri.getPort(); + assertCallSpan(spanData, "Call", SpanKind.CLIENT, uri.getHost(), expectedPort, null); + Collection metrics = meterReader.collectAllMetrics(); + assertDurationMetric(metrics, "test.lib.client.operation.duration", "Call", uri.getHost(), expectedPort, null, + spanData.getSpanContext()); + } + + @Test + public void tracingDisabled() { + otelOptions.setTracingEnabled(false); + Instrumentation instrumentation + = Instrumentation.create(otelOptions, libraryInstrumentationOptions.setEndpoint(DEFAULT_ENDPOINT)); + instrumentation.instrument("call", new RequestOptions(), __ -> { + assertFalse(Span.current().getSpanContext().isValid()); + }); + + assertEquals(0, exporter.getFinishedSpanItems().size()); + Collection metrics = meterReader.collectAllMetrics(); + assertDurationMetric(metrics, "test.lib.client.operation.duration", "call", "localhost", 443L, null, + SpanContext.getInvalid()); + } + + @Test + public void metricsDisabled() { + otelOptions.setMetricsEnabled(false); + Instrumentation instrumentation + = Instrumentation.create(otelOptions, libraryInstrumentationOptions.setEndpoint(DEFAULT_ENDPOINT)); + instrumentation.instrument("call", new RequestOptions(), __ -> { + }); + + assertEquals(1, exporter.getFinishedSpanItems().size()); + assertCallSpan(exporter.getFinishedSpanItems().get(0), "call", SpanKind.CLIENT, "localhost", 443L, null); + assertEquals(0, meterReader.collectAllMetrics().size()); + } + + @Test + public void tracingAndMetricsDisabled() { + otelOptions.setTracingEnabled(false); + otelOptions.setMetricsEnabled(false); + Instrumentation instrumentation + = Instrumentation.create(otelOptions, libraryInstrumentationOptions.setEndpoint(DEFAULT_ENDPOINT)); + instrumentation.instrument("call", new RequestOptions(), __ -> { + }); + assertEquals(0, exporter.getFinishedSpanItems().size()); + assertEquals(0, meterReader.collectAllMetrics().size()); + } + + @Test + public void testNestedOperations() { + LibraryInstrumentationOptions libOptions1 + = new LibraryInstrumentationOptions("test-lib1").setLibraryVersion("1.0.0") + .setSchemaUrl("https://opentelemetry.io/schemas/1.29.0"); + LibraryInstrumentationOptions libOptions2 + = new LibraryInstrumentationOptions("test-lib2").setLibraryVersion("2.0.0") + .setSchemaUrl("https://opentelemetry.io/schemas/1.29.0"); + Instrumentation instrumentation1 = Instrumentation.create(otelOptions, libOptions1); + Instrumentation instrumentation2 = Instrumentation.create(otelOptions, libOptions2); + + RequestOptions options = new RequestOptions(); + + io.clientcore.core.instrumentation.tracing.Span span = instrumentation1.getTracer() + .spanBuilder("call1", SpanKind.CONSUMER, options.getInstrumentationContext()) + .setAttribute("operation.name", "call1") + .startSpan(); + + options.setInstrumentationContext(span.getInstrumentationContext()); + + instrumentation2.instrument("call2", options, o2 -> { + assertTrue(o2.getInstrumentationContext().isValid()); + assertSame(o2.getInstrumentationContext(), options.getInstrumentationContext()); + //assertNotSame(o2.getInstrumentationContext(), o1.getInstrumentationContext()); + instrumentation2.instrument("call3", o2, o3 -> { + // this call is suppressed + assertSame(o2.getInstrumentationContext(), options.getInstrumentationContext()); + //assertNotSame(o3.getInstrumentationContext(), options.getInstrumentationContext()); + }); + }); + span.end(); + + assertEquals(2, exporter.getFinishedSpanItems().size()); + SpanData spanData2 = exporter.getFinishedSpanItems().get(0); + SpanData spanData1 = exporter.getFinishedSpanItems().get(1); + assertCallSpan(spanData2, "call2", SpanKind.CLIENT, null, null, null); + assertCallSpan(spanData1, "call1", SpanKind.CONSUMER, null, null, null); + assertEquals(spanData1.getSpanContext().getTraceId(), spanData2.getSpanContext().getTraceId()); + assertEquals(spanData1.getSpanContext().getSpanId(), spanData2.getParentSpanContext().getSpanId()); + + Collection metrics = meterReader.collectAllMetrics(); + assertEquals(1, metrics.size()); + assertDurationMetric(metrics, "test.lib2.client.operation.duration", "call2", null, null, null, + spanData2.getSpanContext()); + } + + @Test + public void testSiblingOperations() { + Instrumentation instrumentation + = Instrumentation.create(otelOptions, libraryInstrumentationOptions.setEndpoint("https://localhost")); + RequestOptions options = new RequestOptions(); + + AtomicReference parent = new AtomicReference<>(); + + io.clientcore.core.instrumentation.tracing.Span span = instrumentation.getTracer() + .spanBuilder("call1", SpanKind.CONSUMER, options.getInstrumentationContext()) + .setAttribute("operation.name", "call1") + .startSpan(); + + parent.set(span.getInstrumentationContext()); + options.setInstrumentationContext(span.getInstrumentationContext()); + + instrumentation.instrument("call2", options, o2 -> { + assertTrue(o2.getInstrumentationContext().isValid()); + assertSame(o2.getInstrumentationContext(), options.getInstrumentationContext()); + //assertNotSame(o2.getInstrumentationContext(), parent.get()); + }); + + // reset context to parent - it's modified by call2 + // it's not perfect, but also not a big problem since we rarely have nested sibling sub-operations sharing + // the same request options instance + options.setInstrumentationContext(parent.get()); + instrumentation.instrument("call3", options, o3 -> { + assertTrue(o3.getInstrumentationContext().isValid()); + assertSame(o3.getInstrumentationContext(), options.getInstrumentationContext()); + //assertNotSame(o3.getInstrumentationContext(), parent.get()); + }); + + span.end(); + + assertEquals(3, exporter.getFinishedSpanItems().size()); + SpanData spanData2 = exporter.getFinishedSpanItems().get(0); + SpanData spanData3 = exporter.getFinishedSpanItems().get(1); + SpanData spanData1 = exporter.getFinishedSpanItems().get(2); + assertCallSpan(spanData2, "call2", SpanKind.CLIENT, "localhost", 443L, null); + assertCallSpan(spanData3, "call3", SpanKind.CLIENT, "localhost", 443L, null); + assertCallSpan(spanData1, "call1", SpanKind.CONSUMER, null, null, null); + assertEquals(parent.get().getTraceId(), spanData2.getSpanContext().getTraceId()); + assertEquals(parent.get().getSpanId(), spanData2.getParentSpanContext().getSpanId()); + assertEquals(parent.get().getTraceId(), spanData3.getSpanContext().getTraceId()); + + List metrics = meterReader.collectAllMetrics().stream().collect(Collectors.toList()); + assertEquals(1, metrics.size()); + assertEquals(2, metrics.get(0).getHistogramData().getPoints().size()); + } + + private void assertCallSpan(SpanData spanData, String name, SpanKind kind, String host, Long port, + String errorType) { + assertEquals(name, spanData.getName()); + assertEquals(kind.name(), spanData.getKind().name()); + assertEquals(host, spanData.getAttributes().get(AttributeKey.stringKey("server.address"))); + assertEquals(name, spanData.getAttributes().get(AttributeKey.stringKey("operation.name"))); + if (port != null) { + assertEquals(port, spanData.getAttributes().get(AttributeKey.longKey("server.port"))); + } else { + assertNull(spanData.getAttributes().get(AttributeKey.longKey("server.port"))); + } + + if (errorType != null) { + assertEquals(errorType, spanData.getAttributes().get(AttributeKey.stringKey("error.type"))); + } else { + assertNull(spanData.getAttributes().get(AttributeKey.stringKey("error.type"))); + } + } + + private void assertDurationMetric(Collection metrics, String metricName, String operationName, + String host, Long port, String errorType, SpanContext spanContext) { + AttributesBuilder attributesBuilder + = Attributes.builder().put(AttributeKey.stringKey("operation.name"), operationName); + + if (host != null) { + attributesBuilder.put(AttributeKey.stringKey("server.address"), host); + } + + if (port != null) { + attributesBuilder.put(AttributeKey.longKey("server.port"), port); + } + + if (errorType != null) { + attributesBuilder.put(AttributeKey.stringKey("error.type"), errorType); + } + + assertThat(metrics).anySatisfy(metric -> OpenTelemetryAssertions.assertThat(metric) + .hasName(metricName) + .hasUnit("s") + .hasHistogramSatisfying(h -> h.isCumulative().hasPointsSatisfying(point -> { + point.hasAttributes(attributesBuilder.build()) + .hasBucketBoundaries(0.005d, 0.01d, 0.025d, 0.05d, 0.075d, 0.1d, 0.25d, 0.5d, 0.75d, 1d, 2.5d, 5d, + 7.5d, 10d); + + if (spanContext.isSampled()) { + point.hasExemplarsSatisfying( + exemplar -> exemplar.hasTraceId(spanContext.getTraceId()).hasSpanId(spanContext.getSpanId())); + } + }))); + + assertThat(metrics).anySatisfy(m -> assertInstrumentationScope(m.getInstrumentationScopeInfo())); + } + + private void assertInstrumentationScope(InstrumentationScopeInfo scope) { + assertThat(scope).satisfies(info -> { + assertThat(info.getName()).startsWith("test-lib"); + assertThat(info.getVersion()).isNotNull(); + assertThat(info.getSchemaUrl()).isEqualTo("https://opentelemetry.io/schemas/1.29.0"); + }); + } + + public static Stream spanKindSource() { + return Stream.of(SpanKind.CLIENT, SpanKind.SERVER, SpanKind.PRODUCER, SpanKind.CONSUMER, SpanKind.INTERNAL); + } +} diff --git a/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/instrumentation/SuppressionTests.java b/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/instrumentation/SuppressionTests.java index 0787d9bc7435..cbcb07eb15b6 100644 --- a/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/instrumentation/SuppressionTests.java +++ b/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/instrumentation/SuppressionTests.java @@ -3,7 +3,7 @@ package io.clientcore.core.instrumentation; -import io.clientcore.core.http.MockHttpResponse; +import io.clientcore.core.http.models.HttpHeaders; import io.clientcore.core.http.models.HttpMethod; import io.clientcore.core.http.models.HttpRequest; import io.clientcore.core.http.models.RequestOptions; @@ -14,10 +14,15 @@ import io.clientcore.core.instrumentation.tracing.SpanKind; import io.clientcore.core.instrumentation.tracing.Tracer; import io.clientcore.core.instrumentation.tracing.TracingScope; +import io.clientcore.core.models.binarydata.BinaryData; import io.opentelemetry.api.OpenTelemetry; import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter; +import io.opentelemetry.sdk.testing.time.TestClock; import io.opentelemetry.sdk.trace.SdkTracerProvider; import io.opentelemetry.sdk.trace.data.SpanData; import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; @@ -29,11 +34,13 @@ import org.junit.jupiter.params.provider.MethodSource; import java.io.IOException; +import java.time.Duration; import java.util.stream.Stream; import static io.clientcore.core.instrumentation.tracing.SpanKind.CLIENT; import static io.clientcore.core.instrumentation.tracing.SpanKind.INTERNAL; import static io.clientcore.core.instrumentation.tracing.SpanKind.PRODUCER; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -43,22 +50,31 @@ import static org.junit.jupiter.api.Assertions.fail; public class SuppressionTests { - - private static final LibraryInstrumentationOptions DEFAULT_LIB_OPTIONS - = new LibraryInstrumentationOptions("test-library"); + private static final long SECOND_NANOS = 1_000_000_000; private InMemorySpanExporter exporter; private SdkTracerProvider tracerProvider; - private InstrumentationOptions otelOptions; + private SdkMeterProvider meterProvider; + private InMemoryMetricReader sdkMeterReader; + private TestClock testClock; + + private InstrumentationOptions otelOptions; private Tracer tracer; + private final LibraryInstrumentationOptions libOptions = new LibraryInstrumentationOptions("test-library"); @BeforeEach public void setUp() { exporter = InMemorySpanExporter.create(); tracerProvider = SdkTracerProvider.builder().addSpanProcessor(SimpleSpanProcessor.create(exporter)).build(); - OpenTelemetry openTelemetry = OpenTelemetrySdk.builder().setTracerProvider(tracerProvider).build(); - otelOptions = new InstrumentationOptions().setProvider(openTelemetry); - tracer = Instrumentation.create(otelOptions, DEFAULT_LIB_OPTIONS).getTracer(); + testClock = TestClock.create(); + sdkMeterReader = InMemoryMetricReader.create(); + + meterProvider = SdkMeterProvider.builder().setClock(testClock).registerMetricReader(sdkMeterReader).build(); + + OpenTelemetry openTelemetry + = OpenTelemetrySdk.builder().setTracerProvider(tracerProvider).setMeterProvider(meterProvider).build(); + otelOptions = new InstrumentationOptions().setTelemetryProvider(openTelemetry); + tracer = Instrumentation.create(otelOptions, libOptions).getTracer(); } @AfterEach @@ -69,9 +85,10 @@ public void tearDown() { @Test public void testNoSuppressionForSimpleMethod() { - HttpPipeline pipeline - = new HttpPipelineBuilder().httpClient(request -> new MockHttpResponse(request, 200)).build(); - SampleClient client = new SampleClient(pipeline, otelOptions); + HttpPipeline pipeline = new HttpPipelineBuilder() + .httpClient(request -> new Response<>(request, 200, new HttpHeaders(), BinaryData.empty())) + .build(); + SampleClientTracing client = new SampleClientTracing(pipeline, otelOptions); client.protocolMethod(new RequestOptions()); @@ -83,9 +100,10 @@ public void testNoSuppressionForSimpleMethod() { @Test public void testNestedInternalSpanSuppression() { - HttpPipeline pipeline - = new HttpPipelineBuilder().httpClient(request -> new MockHttpResponse(request, 200)).build(); - SampleClient client = new SampleClient(pipeline, otelOptions); + HttpPipeline pipeline = new HttpPipelineBuilder() + .httpClient(request -> new Response<>(request, 200, new HttpHeaders(), BinaryData.empty())) + .build(); + SampleClientTracing client = new SampleClientTracing(pipeline, otelOptions); client.convenienceMethod(new RequestOptions()); assertEquals(1, exporter.getFinishedSpanItems().size()); @@ -93,12 +111,56 @@ public void testNestedInternalSpanSuppression() { assertEquals("convenienceMethod", span.getName()); } + @Test + public void testNestedInternalScopeSuppression() throws IOException { + HttpPipeline pipeline = new HttpPipelineBuilder() + .httpClient(request -> new Response<>(request, 200, new HttpHeaders(), BinaryData.empty())) + .build(); + + LibraryInstrumentationOptions libraryInstrumentationOptions + = new LibraryInstrumentationOptions("test-library").setEndpoint("https://localhost"); + + SampleClientCallInstrumentation client + = new SampleClientCallInstrumentation(pipeline, otelOptions, libraryInstrumentationOptions); + + client.convenienceMethod(new RequestOptions()); + assertEquals(1, exporter.getFinishedSpanItems().size()); + SpanData span = exporter.getFinishedSpanItems().get(0); + assertEquals("convenience", span.getName()); + + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + assertThat(sdkMeterReader.collectAllMetrics()) + .satisfiesExactly(metric -> OpenTelemetryAssertions.assertThat(metric) + .hasName("test.library.client.operation.duration") + .hasHistogramSatisfying(h -> h.isCumulative().hasPointsSatisfying(point -> point.hasCount(1)))); + } + + @Test + public void testNestedInternalScopeDisabledSuppression() throws IOException { + HttpPipeline pipeline = new HttpPipelineBuilder() + .httpClient(request -> new Response<>(request, 200, new HttpHeaders(), BinaryData.empty())) + .build(); + LibraryInstrumentationOptions libOptions + = new LibraryInstrumentationOptions("test-library").disableSpanSuppression(true); + SampleClientCallInstrumentation client = new SampleClientCallInstrumentation(pipeline, otelOptions, libOptions); + + client.convenienceMethod(new RequestOptions()); + assertEquals(2, exporter.getFinishedSpanItems().size()); + assertEquals("protocol", exporter.getFinishedSpanItems().get(0).getName()); + assertEquals("convenience", exporter.getFinishedSpanItems().get(1).getName()); + + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + assertThat(sdkMeterReader.collectAllMetrics()) + .satisfiesExactly(metric -> OpenTelemetryAssertions.assertThat(metric) + .hasName("test.library.client.operation.duration") + .hasHistogramSatisfying( + h -> h.isCumulative().hasPointsSatisfying(point -> point.hasCount(1), point -> point.hasCount(1)))); + } + @Test public void testDisabledSuppression() { Tracer outerTracer = tracer; - Tracer innerTracer = Instrumentation - .create(otelOptions, new LibraryInstrumentationOptions("test-library").disableSpanSuppression(true)) - .getTracer(); + Tracer innerTracer = Instrumentation.create(otelOptions, libOptions.disableSpanSuppression(true)).getTracer(); RequestOptions options = new RequestOptions(); Span outerSpan = outerTracer.spanBuilder("outerSpan", CLIENT, options.getInstrumentationContext()).startSpan(); @@ -155,7 +217,7 @@ public void noSuppressionForSiblings() { @Test public void multipleLayers() { - Tracer tracer = Instrumentation.create(otelOptions, DEFAULT_LIB_OPTIONS).getTracer(); + Tracer tracer = Instrumentation.create(otelOptions, libOptions).getTracer(); RequestOptions options = new RequestOptions(); @@ -296,20 +358,24 @@ private static void assertSpanContextEquals(io.opentelemetry.api.trace.Span firs } public static Stream suppressionTestCases() { - return Stream.of(Arguments.of(CLIENT, CLIENT, 1), Arguments.of(CLIENT, INTERNAL, 1), - Arguments.of(INTERNAL, CLIENT, 1), Arguments.of(INTERNAL, INTERNAL, 1), + return Stream.of(Arguments.of(CLIENT, CLIENT, 1), Arguments.of(CLIENT, INTERNAL, 2), + Arguments.of(INTERNAL, CLIENT, 2), Arguments.of(INTERNAL, INTERNAL, 1), Arguments.of(SpanKind.SERVER, CLIENT, 2), Arguments.of(SpanKind.SERVER, INTERNAL, 2), Arguments.of(PRODUCER, CLIENT, 2), Arguments.of(INTERNAL, PRODUCER, 2), Arguments.of(SpanKind.CONSUMER, CLIENT, 2), Arguments.of(SpanKind.CONSUMER, INTERNAL, 2)); } - static class SampleClient { + static class SampleClientTracing { + private static final String LIBRARY_NAME = "test-library"; private final HttpPipeline pipeline; private final Tracer tracer; - SampleClient(HttpPipeline pipeline, InstrumentationOptions options) { + SampleClientTracing(HttpPipeline pipeline, InstrumentationOptions options) { this.pipeline = pipeline; - this.tracer = Instrumentation.create(options, DEFAULT_LIB_OPTIONS).getTracer(); + + LibraryInstrumentationOptions libraryInstrumentationOptions + = new LibraryInstrumentationOptions(LIBRARY_NAME).setEndpoint("https://localhost"); + this.tracer = Instrumentation.create(options, libraryInstrumentationOptions).getTracer(); } @SuppressWarnings("try") @@ -319,7 +385,8 @@ public void protocolMethod(RequestOptions options) { options.setInstrumentationContext(span.getInstrumentationContext()); try (TracingScope scope = span.makeCurrent()) { - Response response = pipeline.send(new HttpRequest(HttpMethod.GET, "https://localhost")); + Response response + = pipeline.send(new HttpRequest().setMethod(HttpMethod.GET).setUri("https://localhost")); try { response.close(); } catch (IOException e) { @@ -344,4 +411,28 @@ public void convenienceMethod(RequestOptions options) { } } } + + static class SampleClientCallInstrumentation { + private final HttpPipeline pipeline; + private final Instrumentation instrumentation; + + SampleClientCallInstrumentation(HttpPipeline pipeline, InstrumentationOptions options, + LibraryInstrumentationOptions libraryInstrumentationOptions) { + this.pipeline = pipeline; + this.instrumentation = Instrumentation.create(options, libraryInstrumentationOptions); + } + + @SuppressWarnings("try") + public Response protocolMethod(RequestOptions options) { + return instrumentation.instrumentWithResponse("protocol", options, + updatedOptions -> pipeline.send(new HttpRequest().setMethod(HttpMethod.GET) + .setUri("https://localhost") + .setRequestOptions(updatedOptions))); + } + + @SuppressWarnings("try") + public Response convenienceMethod(RequestOptions options) throws IOException { + return instrumentation.instrumentWithResponse("convenience", options, this::protocolMethod); + } + } } diff --git a/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/instrumentation/TracerTests.java b/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/instrumentation/TracerTests.java index 6b9cd3c528e0..e749ec0c77a8 100644 --- a/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/instrumentation/TracerTests.java +++ b/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/instrumentation/TracerTests.java @@ -10,6 +10,7 @@ import io.clientcore.core.instrumentation.tracing.TracingScope; import io.opentelemetry.api.OpenTelemetry; import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; import io.opentelemetry.context.Context; import io.opentelemetry.sdk.OpenTelemetrySdk; import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter; @@ -24,6 +25,8 @@ import org.junit.jupiter.params.provider.MethodSource; import java.io.IOException; +import java.util.HashMap; +import java.util.Map; import java.util.stream.Stream; import static io.clientcore.core.instrumentation.tracing.SpanKind.INTERNAL; @@ -36,7 +39,9 @@ public class TracerTests { private InMemorySpanExporter exporter; private SdkTracerProvider tracerProvider; - private InstrumentationOptions otelOptions; + private InstrumentationOptions otelOptions; + private OpenTelemetry openTelemetry; + private Instrumentation instrumentation; private Tracer tracer; @BeforeEach @@ -44,9 +49,10 @@ public void setUp() { exporter = InMemorySpanExporter.create(); tracerProvider = SdkTracerProvider.builder().addSpanProcessor(SimpleSpanProcessor.create(exporter)).build(); - OpenTelemetry openTelemetry = OpenTelemetrySdk.builder().setTracerProvider(tracerProvider).build(); - otelOptions = new InstrumentationOptions().setProvider(openTelemetry); - tracer = Instrumentation.create(otelOptions, DEFAULT_LIB_OPTIONS).getTracer(); + openTelemetry = OpenTelemetrySdk.builder().setTracerProvider(tracerProvider).build(); + otelOptions = new InstrumentationOptions().setTelemetryProvider(openTelemetry); + instrumentation = Instrumentation.create(otelOptions, DEFAULT_LIB_OPTIONS); + tracer = instrumentation.getTracer(); } @AfterEach @@ -103,6 +109,32 @@ public void testSpan() { assertEquals(io.opentelemetry.api.trace.StatusCode.UNSET, spanData.getStatus().getStatusCode()); } + @Test + public void testSetAllAttributes() { + Map start = new HashMap<>(); + start.put("string", "value"); + start.put("int", 42); + start.put("double", 0.42); + start.put("float", 4.2f); + start.put("boolean", true); + start.put("long", 420L); + InstrumentationAttributes startAttributes = instrumentation.createAttributes(start); + + Span span = tracer.spanBuilder("test-span", INTERNAL, null).setAllAttributes(startAttributes).startSpan(); + span.end(); + + assertEquals(1, exporter.getFinishedSpanItems().size()); + SpanData spanData = exporter.getFinishedSpanItems().get(0); + Attributes attrs = spanData.getAttributes(); + assertEquals(6, attrs.size()); + assertEquals("value", attrs.get(AttributeKey.stringKey("string"))); + assertEquals(42L, attrs.get(AttributeKey.longKey("int"))); + assertEquals(420L, attrs.get(AttributeKey.longKey("long"))); + assertEquals(0.42, attrs.get(AttributeKey.doubleKey("double"))); + assertEquals(4.2f, attrs.get(AttributeKey.doubleKey("float")), 0.1); + assertEquals(true, attrs.get(AttributeKey.booleanKey("boolean"))); + } + @Test public void testEndWithErrorString() { Span span = tracer.spanBuilder("test-span", INTERNAL, null).startSpan(); @@ -152,7 +184,7 @@ public void testKinds(SpanKind kind, io.opentelemetry.api.trace.SpanKind expecte @SuppressWarnings("try") @Test public void implicitParent() throws Exception { - io.opentelemetry.api.trace.Tracer otelTracer = otelOptions.getProvider().getTracer("test"); + io.opentelemetry.api.trace.Tracer otelTracer = openTelemetry.getTracer("test"); io.opentelemetry.api.trace.Span parent = otelTracer.spanBuilder("parent").startSpan(); try (AutoCloseable scope = parent.makeCurrent()) { Span child = tracer.spanBuilder("child", INTERNAL, null).startSpan(); @@ -171,8 +203,8 @@ public void implicitParent() throws Exception { } @Test - public void explicitParent() throws Exception { - io.opentelemetry.api.trace.Tracer otelTracer = otelOptions.getProvider().getTracer("test"); + public void explicitParent() { + io.opentelemetry.api.trace.Tracer otelTracer = openTelemetry.getTracer("test"); io.opentelemetry.api.trace.Span parent = otelTracer.spanBuilder("parent").startSpan(); Span child = tracer.spanBuilder("child", INTERNAL, OTelSpanContext.fromOTelContext(Context.root().with(parent))) diff --git a/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/instrumentation/TracingShimBenchmarks.java b/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/instrumentation/TracingShimBenchmarks.java index 8f029d16e5db..24f72e6a7aff 100644 --- a/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/instrumentation/TracingShimBenchmarks.java +++ b/sdk/clientcore/optional-dependency-tests/src/test/java/io/clientcore/core/instrumentation/TracingShimBenchmarks.java @@ -43,6 +43,7 @@ public class TracingShimBenchmarks { private io.opentelemetry.api.trace.Tracer otelTracer; private io.opentelemetry.api.trace.Tracer otelTracerDisabled; private OpenTelemetry openTelemetry; + private LibraryInstrumentationOptions libraryInstrumentationOptions; private static final AttributeKey STRING_ATTRIBUTE_KEY_1 = AttributeKey.stringKey("string1"); private static final AttributeKey STRING_ATTRIBUTE_KEY_2 = AttributeKey.stringKey("string2"); @@ -58,17 +59,19 @@ public void setupOtel() { .setTracerProvider(SdkTracerProvider.builder().addSpanProcessor(new NoopProcessor()).build()) .build(); + libraryInstrumentationOptions + = new LibraryInstrumentationOptions("test").setLibraryVersion("https://localhost:8080"); + otelTracer = openTelemetry.getTracer("test"); otelTracerDisabled = TracerProvider.noop().get("test"); - shimTracer - = Instrumentation - .create(new InstrumentationOptions().setProvider(openTelemetry), - new LibraryInstrumentationOptions("test")) - .getTracer(); + + shimTracer = Instrumentation + .create(new InstrumentationOptions().setTelemetryProvider(openTelemetry), libraryInstrumentationOptions) + .getTracer(); shimTracerDisabled = Instrumentation - .create(new InstrumentationOptions().setProvider(OpenTelemetry.noop()), - new LibraryInstrumentationOptions("test")) + .create(new InstrumentationOptions().setTelemetryProvider(OpenTelemetry.noop()), + libraryInstrumentationOptions) .getTracer(); } diff --git a/sdk/clientcore/platform-matrix.json b/sdk/clientcore/platform-matrix.json index b5b4edaa73e4..78cb5a2293f9 100644 --- a/sdk/clientcore/platform-matrix.json +++ b/sdk/clientcore/platform-matrix.json @@ -15,8 +15,8 @@ "NotFromSource_TestsOnly": { "TestFromSource": false, "RunAggregateReports": false, - "TestOptions": "", - "TestGoals": "surefire:test failsafe:integration-test failsafe:verify" + "TestOptions": "-DskipCompile=true -DskipTestCompile=true -DcreateSourcesJar=false -Djacoco.skip", + "TestGoals": "verify" } } }, @@ -27,6 +27,36 @@ } ], "include": [ + { + "Agent": { + "ubuntu-20.04": { "OSVmImage": "env:LINUXVMIMAGE", "Pool": "env:LINUXPOOL" } + }, + "JavaTestVersion": "1.8", + "TEST_HTTP_CLIENT_IMPLEMENTATION": "io.clientcore.http.okhttp3.OkHttpHttpClientProvider", + "Options": { + "NotFromSource_TestsOnly": { + "TestFromSource": false, + "RunAggregateReports": false, + "TestOptions": "-DskipCompile=true -DskipTestCompile=true -DcreateSourcesJar=false -Djacoco.skip", + "TestGoals": "verify" + } + } + }, + { + "Agent": { + "ubuntu-20.04": { "OSVmImage": "env:LINUXVMIMAGE", "Pool": "env:LINUXPOOL" } + }, + "JavaTestVersion": "1.11", + "TEST_HTTP_CLIENT_IMPLEMENTATION": "io.clientcore.http.okhttp3.OkHttpHttpClientProvider", + "Options": { + "NotFromSource_TestsOnly": { + "TestFromSource": false, + "RunAggregateReports": false, + "TestOptions": "-DskipCompile=true -DskipTestCompile=true -DcreateSourcesJar=false -Djacoco.skip", + "TestGoals": "verify" + } + } + }, { "Agent": { "ubuntu-20.04": { "OSVmImage": "env:LINUXVMIMAGE", "Pool": "env:LINUXPOOL" } diff --git a/sdk/clientcore/pom.xml b/sdk/clientcore/pom.xml index 252a22840d50..fd0ab8dc800c 100644 --- a/sdk/clientcore/pom.xml +++ b/sdk/clientcore/pom.xml @@ -14,6 +14,7 @@ http-okhttp3 optional-dependency-tests http-stress - tools + annotation-processor + annotation-processor-test diff --git a/sdk/clientcore/tools/annotation-processor/README.md b/sdk/clientcore/tools/annotation-processor/README.md deleted file mode 100644 index e677bb0e2b3d..000000000000 --- a/sdk/clientcore/tools/annotation-processor/README.md +++ /dev/null @@ -1,136 +0,0 @@ -# Client Core Compile-Time Annotation Processor - -The client-core annotation processor for introducing compile-time code generation for libraries based on client core ->Note: This project is for experimentation and exploring new ideas that may or may not make it into a supported GA release. - -## Usage - -1. Add the plugin dependency: - ```xml - - - io.clientcore.tools - annotation-processor - 1.0.0.beta.1 - provided - - - ``` - 1.1. Add the plugin configuration to your `pom.xml`: - ```xml - - - org.apache.maven.plugins - maven-compiler-plugin - 3.11.0 - - ${project.build.directory}/generated-sources/ - - io.generation.tools.codegen.AnnotationProcessor - - - - - ``` -2. Annotate your interfaces with `@ServiceInterface`, `@HttpRequestInformation` and - `@UnexpectedResponseExceptionDetail` such annotations: - ```java - @ServiceInterface(name = "ExampleClient", host = "{endpoint}/example") - public interface ExampleService { - @HttpRequestInformation(method = HttpMethod.GET, path = "/user/{userId}", expectedStatusCodes = { 200 }) - @UnexpectedResponseExceptionDetail(exceptionTypeName = "CLIENT_AUTHENTICATION", statusCode = { 401 }) - @UnexpectedResponseExceptionDetail(exceptionTypeName = "RESOURCE_NOT_FOUND", statusCode = { 404 }) - @UnexpectedResponseExceptionDetail(exceptionTypeName = "RESOURCE_MODIFIED", statusCode = { 409 }) - User getUser(@PathParam("userId") String userId); - } - ``` - -3. Build your project and the plugin will generate an implementation of the annotated interface. - The processor would generate an implementation: - ```java - public class ExampleServiceImpl implements ExampleService { - private static final ClientLogger LOGGER = new ClientLogger(OpenAIClientServiceImpl.class); - - private final HttpPipeline defaultPipeline; - - private final ObjectSerializer serializer; - - private final String endpoint; - - private final ExampleServiceVersion serviceVersion; - - private String apiVersion; - - public ExampleServiceImpl (HttpPipeline defaultPipeline, ObjectSerializer serializer, - String endpoint, ExampleServiceVersion serviceVersion) { - this.defaultPipeline = defaultPipeline; - this.serializer = serializer; - this.endpoint = endpoint; - this.apiVersion = serviceVersion.getVersion(); - this.serviceVersion = serviceVersion; - } - - public String getEndpoint() { - return endpoint; - } - - public HttpPipeline getPipeline() { - return defaultPipeline; - } - - public ExampleServiceVersion getServiceVersion() { - return serviceVersion; - } - - private final HttpPipeline pipeline; - - public ExampleServiceImpl(HttpPipeline pipeline) { - this.pipeline = pipeline; - } - - public Response getUser(String userId, Context context) { - return getUser(endpoint, apiVersion, userId, context); - } - - @Override - private Response getUser(String endpoint, String apiVersion, String userId, Context context) { - HttpPipeline pipeline = this.getPipeline(); - String host = endpoint + "/example/users/" + userId + "?api-version=" + apiVersion; - - // create the request - HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, host); - - // set the headers - HttpHeaders headers = new HttpHeaders(); - httpRequest.setHeaders(headers); - - // add RequestOptions to the request - httpRequest.setRequestOptions(requestOptions); - - // set the body content if present - - // send the request through the pipeline - Response response = pipeline.send(httpRequest); - - final int responseCode = response.getStatusCode(); - boolean expectedResponse = responseCode == 200; - if (!expectedResponse) { - throw new RuntimeException("Unexpected response code: " + responseCode); - } - ResponseBodyMode responseBodyMode = ResponseBodyMode.IGNORE; - if (requestOptions != null) { - responseBodyMode = requestOptions.getResponseBodyMode(); - } - if (responseBodyMode == ResponseBodyMode.DESERIALIZE) { - BinaryData responseBody = response.getBody(); - HttpResponseAccessHelper.setValue((HttpResponse) response, responseBody); - } else { - BinaryData responseBody = response.getBody(); - HttpResponseAccessHelper.setBodyDeserializer((HttpResponse) response, (body) -> responseBody); - } - return (Response) response; - } - } - ``` -This implementation eliminates reflection and integrates directly with your HTTP client infrastructure. - diff --git a/sdk/clientcore/tools/annotation-processor/pom.xml b/sdk/clientcore/tools/annotation-processor/pom.xml deleted file mode 100644 index f835b2267347..000000000000 --- a/sdk/clientcore/tools/annotation-processor/pom.xml +++ /dev/null @@ -1,112 +0,0 @@ - - - - 4.0.0 - - io.clientcore.tools - annotation-processor - 1.0.0-beta.1 - - Client Core Compile-Time Annotation Processor - The client-core annotation processor for introducing compile-time code generation for libraries based on client core - - - - ossrh - https://oss.sonatype.org/content/repositories/snapshots - - - ossrh - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - - https://github.com/azure/azure-sdk-for-java - - Microsoft Corporation - http://microsoft.com - - - - The MIT License (MIT) - http://opensource.org/licenses/MIT - repo - - - - - - microsoft - Microsoft Corporation - - - - - GitHub - https://github.com/Azure/azure-sdk-for-java/issues - - - - https://github.com/Azure/azure-sdk-for-java - scm:git:https://github.com/Azure/azure-sdk-for-java.git - - HEAD - - - - 8 - 8 - ${project.build.directory} - - - - - com.squareup - javapoet - 1.13.0 - - - io.clientcore - core - 1.0.0-beta.1 - compile - - - - - org.junit.jupiter - junit-jupiter-api - 5.11.2 - test - - - org.junit.jupiter - junit-jupiter-engine - 5.11.2 - test - - - org.junit.jupiter - junit-jupiter-params - 5.11.2 - test - - - org.mockito - mockito-core - 4.11.0 - test - - - - - - - src/main/resources - true - - - - diff --git a/sdk/clientcore/tools/annotation-processor/src/main/java/io/clientcore/tools/codegen/AnnotationProcessor.java b/sdk/clientcore/tools/annotation-processor/src/main/java/io/clientcore/tools/codegen/AnnotationProcessor.java deleted file mode 100644 index b4b28fba71cf..000000000000 --- a/sdk/clientcore/tools/annotation-processor/src/main/java/io/clientcore/tools/codegen/AnnotationProcessor.java +++ /dev/null @@ -1,205 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.tools.codegen; - -import io.clientcore.core.annotation.ServiceInterface; -import io.clientcore.core.http.annotation.BodyParam; -import io.clientcore.core.http.annotation.HeaderParam; -import io.clientcore.core.http.annotation.HostParam; -import io.clientcore.core.http.annotation.HttpRequestInformation; -import io.clientcore.core.http.annotation.PathParam; -import io.clientcore.core.http.annotation.QueryParam; -import io.clientcore.core.http.annotation.UnexpectedResponseExceptionDetail; -import io.clientcore.core.http.models.HttpHeaderName; -import io.clientcore.core.http.models.HttpHeaders; -import io.clientcore.core.http.models.HttpMethod; -import io.clientcore.core.http.models.HttpRequest; -import io.clientcore.core.http.models.HttpResponse; -import io.clientcore.core.http.models.Response; -import io.clientcore.core.http.pipeline.HttpPipeline; -import io.clientcore.core.util.Context; -import io.clientcore.core.util.binarydata.BinaryData; -import io.clientcore.tools.codegen.models.HttpRequestContext; -import io.clientcore.tools.codegen.models.Substitution; -import io.clientcore.tools.codegen.models.TemplateInput; -import io.clientcore.tools.codegen.templating.TemplateProcessor; -import io.clientcore.tools.codegen.utils.PathBuilder; - -import javax.annotation.processing.AbstractProcessor; -import javax.annotation.processing.RoundEnvironment; -import javax.annotation.processing.SupportedAnnotationTypes; -import javax.annotation.processing.SupportedSourceVersion; -import javax.lang.model.SourceVersion; -import javax.lang.model.element.Element; -import javax.lang.model.element.ElementKind; -import javax.lang.model.element.ExecutableElement; -import javax.lang.model.element.TypeElement; -import javax.lang.model.element.VariableElement; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; - -@SupportedAnnotationTypes("io.clientcore.core.annotation.*") -@SupportedSourceVersion(SourceVersion.RELEASE_8) -public class AnnotationProcessor extends AbstractProcessor { - - @Override - public boolean process(Set annotations, RoundEnvironment roundEnv) { - // We iterate through each interface annotated with @ServiceInterface separately. - // This outer for-loop is not strictly necessary, as we only have one annotation that we care about - // (@ServiceInterface), but we'll leave it here for now - annotations.stream() - .map(roundEnv::getElementsAnnotatedWith) - .flatMap(Set::stream) - .filter(element -> element.getKind().isInterface()) - .forEach(element -> { - if (element.getAnnotation(ServiceInterface.class) != null) { - this.processServiceInterface(element); - } - }); - - return true; - } - - - private void processServiceInterface(Element serviceInterface) { - if (serviceInterface == null || serviceInterface.getKind() != ElementKind.INTERFACE) { - throw new IllegalArgumentException("Invalid service interface provided."); - } - - TemplateInput templateInput = new TemplateInput(); - - // Determine the fully qualified name (FQN) and package name - final String serviceInterfaceFQN = serviceInterface.asType().toString(); - int lastDot = serviceInterfaceFQN.lastIndexOf('.'); - String packageName = (lastDot > 0) ? serviceInterfaceFQN.substring(0, lastDot) : "default.generated"; - - final String serviceInterfaceShortName = serviceInterfaceFQN.substring(lastDot + 1); - final String serviceInterfaceImplFQN = serviceInterfaceFQN + "Impl"; - final String serviceInterfaceImplShortName = serviceInterfaceImplFQN.substring(lastDot + 1); - - templateInput.setPackageName(packageName); - templateInput.setServiceInterfaceFQN(serviceInterfaceFQN); - templateInput.setServiceInterfaceShortName(serviceInterfaceShortName); - templateInput.setServiceInterfaceImplShortName(serviceInterfaceImplShortName); - - // Read the ServiceInterface.host() value from annotations - ServiceInterface annotation = serviceInterface.getAnnotation(ServiceInterface.class); - if (annotation != null && annotation.host() != null) { - templateInput.setHost(annotation.host()); - } - - // Add all required imports - addImports(templateInput); - - // Collect methods annotated with @HttpRequestInformation - List httpRequestMethods = serviceInterface.getEnclosedElements().stream() - .filter(element -> element.getKind() == ElementKind.METHOD) - .filter(element -> element.getAnnotation(HttpRequestInformation.class) != null) - .map(ExecutableElement.class::cast) - .collect(Collectors.toList()); - - // Generate HTTP request contexts - templateInput.setHttpRequestContexts(httpRequestMethods.stream() - .map(e -> createHttpRequestContext(e, templateInput)) - .filter(Objects::nonNull) // Exclude null contexts - .collect(Collectors.toList())); - - // Set UnexpectedResponseExceptionDetails - templateInput.setUnexpectedResponseExceptionDetails(httpRequestMethods.stream() - .map(e -> e.getAnnotation(UnexpectedResponseExceptionDetail.class)) - .filter(Objects::nonNull) // Exclude null annotations - .collect(Collectors.toList())); - - // Process the template - TemplateProcessor.getInstance().process(templateInput, processingEnv); - - // Additional formatting or logging if necessary - } - - private void addImports(TemplateInput templateInput) { - templateInput.addImport(Context.class.getName()); - templateInput.addImport(BinaryData.class.getName()); - templateInput.addImport(HttpHeaders.class.getName()); - templateInput.addImport(HttpPipeline.class.getName()); - templateInput.addImport(HttpHeaderName.class.getName()); - templateInput.addImport(HttpMethod.class.getName()); - templateInput.addImport(HttpResponse.class.getName()); - templateInput.addImport(HttpRequest.class.getName()); - templateInput.addImport(Response.class.getName()); - templateInput.addImport(Map.class.getName()); - templateInput.addImport(HashMap.class.getName()); - templateInput.addImport(Arrays.class.getName()); - templateInput.addImport(Void.class.getName()); - templateInput.addImport(List.class.getName()); - } - - private HttpRequestContext createHttpRequestContext(ExecutableElement requestMethod, TemplateInput templateInput) { - HttpRequestContext method = new HttpRequestContext(); - method.setHost(templateInput.getHost()); - method.setMethodName(requestMethod.getSimpleName().toString()); - - // Extract @HttpRequestInformation annotation details - final HttpRequestInformation httpRequestInfo = requestMethod.getAnnotation(HttpRequestInformation.class); - method.setPath(httpRequestInfo.path()); - method.setHttpMethod(httpRequestInfo.method()); - method.setExpectedStatusCodes(httpRequestInfo.expectedStatusCodes()); - - // Add return type as an import - String returnTypeShortName = templateInput.addImport(requestMethod.getReturnType()); - method.setMethodReturnType(returnTypeShortName); - - // Process parameters - for (VariableElement param : requestMethod.getParameters()) { - // Cache annotations for each parameter - HostParam hostParam = param.getAnnotation(HostParam.class); - PathParam pathParam = param.getAnnotation(PathParam.class); - HeaderParam headerParam = param.getAnnotation(HeaderParam.class); - QueryParam queryParam = param.getAnnotation(QueryParam.class); - BodyParam bodyParam = param.getAnnotation(BodyParam.class); - - // Switch based on annotations - if (hostParam != null) { - method.addSubstitution(new Substitution( - hostParam.value(), - param.getSimpleName().toString(), - hostParam.encoded())); - } else if (pathParam != null) { - method.addSubstitution(new Substitution( - pathParam.value(), - param.getSimpleName().toString(), - pathParam.encoded())); - } else if (headerParam != null) { - method.addHeader(headerParam.value(), param.getSimpleName().toString()); - } else if (queryParam != null) { - method.addQueryParam(queryParam.value(), param.getSimpleName().toString()); - // TODO: Add support for multipleQueryParams and encoded handling - } else if (bodyParam != null) { - method.setBody(new HttpRequestContext.Body( - bodyParam.value(), - param.asType().toString(), - param.getSimpleName().toString())); - } - - // Add parameter details to method context - String shortParamName = templateInput.addImport(param.asType()); - method.addParameter(new HttpRequestContext.MethodParameter(param.asType(), shortParamName, param.getSimpleName().toString())); - } - - // Pre-compute host substitutions - method.setHost(getHost(templateInput, method)); - - return method; - } - - private static String getHost(TemplateInput templateInput, HttpRequestContext method) { - String rawHost = templateInput.getHost() + method.getPath(); - - return PathBuilder.buildPath(rawHost, method); - } -} diff --git a/sdk/clientcore/tools/annotation-processor/src/main/java/io/clientcore/tools/codegen/templating/JavaPoetTemplateProcessor.java b/sdk/clientcore/tools/annotation-processor/src/main/java/io/clientcore/tools/codegen/templating/JavaPoetTemplateProcessor.java deleted file mode 100644 index 129fc54adf15..000000000000 --- a/sdk/clientcore/tools/annotation-processor/src/main/java/io/clientcore/tools/codegen/templating/JavaPoetTemplateProcessor.java +++ /dev/null @@ -1,511 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.tools.codegen.templating; - -import io.clientcore.tools.codegen.models.HttpRequestContext; -import io.clientcore.tools.codegen.models.TemplateInput; -import io.clientcore.tools.codegen.utils.ResponseBodyModeGeneration; -import com.squareup.javapoet.ClassName; -import com.squareup.javapoet.FieldSpec; -import com.squareup.javapoet.JavaFile; -import com.squareup.javapoet.MethodSpec; -import com.squareup.javapoet.ParameterizedTypeName; -import com.squareup.javapoet.TypeName; -import com.squareup.javapoet.TypeSpec; -import io.clientcore.core.http.models.ContentType; -import io.clientcore.core.http.models.HttpHeaderName; -import io.clientcore.core.http.models.HttpMethod; -import io.clientcore.core.util.binarydata.BinaryData; -import io.clientcore.core.util.serializer.ObjectSerializer; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.util.Map; -import java.util.stream.Collectors; -import javax.annotation.processing.ProcessingEnvironment; -import javax.lang.model.element.Modifier; - -public class JavaPoetTemplateProcessor implements TemplateProcessor { - private static final ClassName HTTP_HEADER_NAME = ClassName.get("io.clientcore.core.http.models", "HttpHeaderName"); - private static final ClassName CONTENT_TYPE = ClassName.get("io.clientcore.core.http.models", "ContentType"); - - private final ClassName HTTP_REQUEST = ClassName.get("io.clientcore.core.http.models", "HttpRequest"); - private final ClassName RESPONSE = ClassName.get("io.clientcore.core.http" + - ".models", "Response"); - private final ClassName HTTP_METHOD = ClassName.get("io.clientcore.core.http.models", "HttpMethod"); - - private TypeSpec.Builder classBuilder; - final ClassName HTTP_PIPELINE = ClassName.get("io.clientcore.core.http.pipeline", "HttpPipeline"); - static ClassName SERVICE_VERSION_TYPE; - final ClassName CLIENTLOGGER_NAME = ClassName.get("io.clientcore.core.util", "ClientLogger"); - - @Override - public void process(TemplateInput templateInput, ProcessingEnvironment processingEnv) { - String packageName = templateInput.getPackageName(); - String serviceInterfaceImplShortName = templateInput.getServiceInterfaceImplShortName(); - String serviceInterfaceShortName = templateInput.getServiceInterfaceShortName(); - - ClassName interfaceType = ClassName.get(packageName, serviceInterfaceShortName); - - // add LoggerField - FieldSpec loggerField = getLoggerField(packageName, serviceInterfaceShortName); - - // Create the defaultPipeline field - FieldSpec defaultPipeline = - FieldSpec.builder(HTTP_PIPELINE, "defaultPipeline", Modifier.PRIVATE, Modifier.FINAL) - .build(); - - // Create the serializer field - FieldSpec serializer = FieldSpec.builder(ObjectSerializer.class, "serializer", Modifier.PRIVATE, Modifier.FINAL) - .build(); - - // Create the endpoint field - FieldSpec endpoint = FieldSpec.builder(String.class, "endpoint", Modifier.PRIVATE, Modifier.FINAL) - .build(); - - // Create the serviceVersion field - ClassName serviceVersionType = getServiceVersionType(packageName, serviceInterfaceShortName); - FieldSpec serviceVersion = - FieldSpec.builder(serviceVersionType, "serviceVersion", Modifier.PRIVATE, Modifier.FINAL) - .build(); - - // Create the constructor - MethodSpec constructor = getServiceImplConstructor(packageName, serviceInterfaceShortName); - - FieldSpec apiVersion = FieldSpec.builder(String.class, "apiVersion") - .addModifiers(Modifier.PRIVATE) - .build(); - - classBuilder = TypeSpec.classBuilder(serviceInterfaceImplShortName) - .addModifiers(Modifier.PUBLIC) - .addSuperinterface(interfaceType) - .addField(loggerField) - .addField(defaultPipeline) - .addField(serializer) - .addField(endpoint) - .addField(serviceVersion) - .addField(apiVersion) - .addMethod(getEndpointMethod()) - .addMethod(getPipelineMethod()) - .addMethod(getServiceVersionMethod()) - .addMethod(constructor); - - getGeneratedServiceMethods(templateInput); - - TypeSpec typeSpec = classBuilder.build(); - - // Sets the indentation for the generated source file to four spaces. - JavaFile javaFile = JavaFile.builder(packageName, typeSpec) - .indent(" ") // four spaces - .build(); - - try { - javaFile.writeTo(processingEnv.getFiler()); - } catch (IOException e) { - e.printStackTrace(); - } - } - - void getGeneratedServiceMethods(TemplateInput templateInput) { - for (HttpRequestContext method : templateInput.getHttpRequestContexts()) { - classBuilder.addMethod(generatePublicMethod(method)); - generateInternalMethod(method); - } - } - - FieldSpec getLoggerField(String packageName, String serviceInterfaceShortName) { - return FieldSpec.builder(CLIENTLOGGER_NAME, "LOGGER", Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) - .initializer("new $T($T.class)", CLIENTLOGGER_NAME, ClassName.get(packageName, serviceInterfaceShortName)) - .build(); - } - - MethodSpec getServiceImplConstructor(String packageName, String serviceInterfaceShortName) { - return MethodSpec.constructorBuilder() - .addModifiers(Modifier.PUBLIC) - .addParameter(HTTP_PIPELINE, "defaultPipeline") - .addStatement("this.defaultPipeline = defaultPipeline") - .addParameter(ClassName.get("io.clientcore.core.util.serializer", "ObjectSerializer"), "serializer") - .addStatement("this.serializer = serializer") - .addParameter(String.class, "endpoint") - .addStatement("this.endpoint = endpoint") - .addParameter(getServiceVersionType(packageName, serviceInterfaceShortName), - "serviceVersion") - .addStatement("this.apiVersion = serviceVersion.getVersion()") - .addStatement("this.serviceVersion = serviceVersion") - .build(); - } - - static ClassName getServiceVersionType(String packageName, String serviceInterfaceShortName) { - SERVICE_VERSION_TYPE = ClassName.get(packageName, serviceInterfaceShortName.substring(0, - serviceInterfaceShortName.indexOf("ClientService")) + "ServiceVersion"); - return SERVICE_VERSION_TYPE; - } - - MethodSpec getEndpointMethod() { - return MethodSpec.methodBuilder("getEndpoint") - .addModifiers(Modifier.PUBLIC) - .returns(String.class) - .addStatement("return endpoint") - .build(); - } - - MethodSpec getPipelineMethod() { - return MethodSpec.methodBuilder("getPipeline") - .addModifiers(Modifier.PUBLIC) - .returns(HTTP_PIPELINE) - .addStatement("return defaultPipeline") - .build(); - } - - MethodSpec getServiceVersionMethod() { - return MethodSpec.methodBuilder("getServiceVersion") - .addModifiers(Modifier.PUBLIC) - .returns(SERVICE_VERSION_TYPE) - .addStatement("return serviceVersion") - .build(); - } - - MethodSpec generatePublicMethod(HttpRequestContext method) { - - MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(method.getMethodName()) - .addModifiers(Modifier.PUBLIC) - .returns(inferTypeNameFromReturnType(method.getMethodReturnType())); - - // add method parameters, with Context at the end - for (HttpRequestContext.MethodParameter parameter : method.getParameters()) { - if (parameter.getName().equals("endpoint") || parameter.getName().equals("apiVersion")) { - continue; - } - methodBuilder.addParameter(TypeName.get(parameter.getTypeMirror()), parameter.getName()); - } - - // add call to the overloaded version of this method - String params = method.getParameters().stream() - .map(HttpRequestContext.MethodParameter::getName) - .reduce((a, b) -> a + ", " + b) - .orElse(""); - - if (!"void".equals(method.getMethodReturnType())) { - methodBuilder.addStatement("return $L($L)", - method.getMethodName(), params); - } else { - methodBuilder.addStatement("$L($L)", - method.getMethodName(), params); - } - - return methodBuilder.build(); - } - - private void generateInternalMethod(HttpRequestContext method) { - TypeName returnTypeName = inferTypeNameFromReturnType(method.getMethodReturnType()); - MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(method.getMethodName()) - .addModifiers(Modifier.PRIVATE) - .addAnnotation(Override.class) - .returns(returnTypeName); - - // add method parameters, as well as the HttpPipeline at the front - for (HttpRequestContext.MethodParameter parameter : method.getParameters()) { - methodBuilder.addParameter(TypeName.get(parameter.getTypeMirror()), parameter.getName()); - } - - // add field pipeline - methodBuilder.addStatement("HttpPipeline pipeline = this.getPipeline()"); - - methodBuilder - .addStatement("String host = $L", method.getHost()) - .addCode("\n") - .addComment("create the request") - .addStatement("$T httpRequest = new $T($T.$L, host)", HTTP_REQUEST, HTTP_REQUEST, HTTP_METHOD, - method.getHttpMethod()); - - // add headers - if (!method.getHeaders().isEmpty()) { - methodBuilder - .addCode("\n") - .addComment("set the headers") - .addStatement("$T headers = new $T()", ClassName.get("io.clientcore.core.http.models", "HttpHeaders"), - ClassName.get("io.clientcore.core.http.models", "HttpHeaders")); - for (Map.Entry header : method.getHeaders().entrySet()) { - String enumHeaderKey = header.getKey().toUpperCase().replace("-", "_"); - boolean isEnumExists = false; - for (HttpHeaderName httpHeaderName : HttpHeaderName.values()) { - if (httpHeaderName.getCaseInsensitiveName().equals(header.getKey().toLowerCase())) { - isEnumExists = true; - break; - } - } - if (isEnumExists) { - methodBuilder.addStatement("headers.add($T.$L, $L)", - HTTP_HEADER_NAME, enumHeaderKey, header.getValue()); - } else { - methodBuilder.addStatement("headers.add($T.fromString($S), $L)", - HTTP_HEADER_NAME, header.getKey(), header.getValue()); - } - } - - methodBuilder.addStatement("httpRequest.setHeaders(headers)"); - } - - methodBuilder - .addCode("\n") - .addComment("add RequestOptions to the request") - .addStatement("httpRequest.setRequestOptions(requestOptions)"); - - // [TODO] set SSE listener if available - - // set the body - methodBuilder - .addCode("\n") - .addComment("set the body content if present"); - if (method.getBody() != null) { - HttpRequestContext.Body body = method.getBody(); - String contentType = body.getContentType(); - String parameterType = body.getParameterType(); - String parameterName = body.getParameterName(); - - configureRequestWithBodyAndContentType(methodBuilder, parameterType, contentType, parameterName); - } else { - methodBuilder - .addStatement("httpRequest.getHeaders().set($T.CONTENT_LENGTH, $S)", HttpHeaderName.class, "0"); - methodBuilder.addComment("no body content to set"); - } - - // send request through pipeline - methodBuilder - .addCode("\n") - .addComment("send the request through the pipeline") - .addStatement("$T response = pipeline.send(httpRequest)", RESPONSE); - - // check for expected status codes - if (!method.getExpectedStatusCodes().isEmpty()) { - methodBuilder - .addCode("\n") - .addStatement("final int responseCode = response.getStatusCode()"); - if (method.getExpectedStatusCodes().size() == 1) { - methodBuilder.addStatement("boolean expectedResponse = responseCode == $L", - method.getExpectedStatusCodes().get(0)); - } else { - String statusCodes = method.getExpectedStatusCodes().stream() - .map(code -> "responseCode == " + code) - .collect(Collectors.joining(" || ")); - methodBuilder.addStatement("boolean expectedResponse = " + statusCodes); - } - methodBuilder.beginControlFlow("if (!expectedResponse)") - .addStatement("throw new $T(\"Unexpected response code: \" + responseCode)", RuntimeException.class) - .endControlFlow(); - } - - // add return statement if method return type is not "void" - if (returnTypeName.toString().contains("void") && returnTypeName.toString().contains("Void")) { - methodBuilder.addStatement("return"); - } else if (returnTypeName.toString().contains("Response")) { - if (returnTypeName.toString().contains("Void")) { - methodBuilder.beginControlFlow("try") - .addStatement("response.close()") - .nextControlFlow("catch ($T e)", IOException.class) - .addStatement("throw LOGGER.logThrowableAsError(new $T(e))", UncheckedIOException.class) - .endControlFlow(); - createResponseIfNecessary(returnTypeName, methodBuilder); - } else { - // Step 1: Generate ResponseBodyMode assignment - ResponseBodyModeGeneration.generateResponseBodyModeAssignment(methodBuilder); - - // Step 2: Generate DESERIALIZE handling - ResponseBodyModeGeneration.generateDeserializeResponseHandling(methodBuilder); - - // Step 3: Generate non-DESERIALIZE handling - ResponseBodyModeGeneration.generateNonDeserializeResponseHandling(methodBuilder); - - // Step 4: Create the response if necessary - createResponseIfNecessary(returnTypeName, methodBuilder); - } - } else { - handleResponseModeToCreateResponse(method, returnTypeName, methodBuilder); - } - - classBuilder.addMethod(methodBuilder.build()); - } - - private static void createResponseIfNecessary(TypeName returnTypeName, MethodSpec.Builder methodBuilder) { - // TODO: Fix me - methodBuilder.addStatement("return ($T) response", returnTypeName); - } - - private static void handleResponseModeToCreateResponse(HttpRequestContext method, TypeName returnTypeName, - MethodSpec.Builder methodBuilder) { - HttpMethod httpMethod = method.getHttpMethod(); - if (httpMethod == HttpMethod.HEAD && - (returnTypeName.toString().contains("Boolean") || returnTypeName.toString().contains("boolean"))) { - methodBuilder.addStatement("return (responseCode / 100) == 2"); - } else if (returnTypeName.toString().contains("byte[]")) { - methodBuilder - .addStatement("$T responseBody = response.getBody()", BinaryData.class) - .addStatement("byte[] responseBodyBytes = responseBody != null ? responseBody.toBytes() : null") - .addStatement( - "return responseBodyBytes != null ? (responseBodyBytes.length == 0 ? null : responseBodyBytes) : null"); - } else if (returnTypeName.toString().contains("InputStream")) { - methodBuilder - .addStatement("$T responseBody = response.getBody()", BinaryData.class) - .addStatement("return responseBody.toStream()"); - } else if (returnTypeName.toString().contains("BinaryData")) { - methodBuilder - .addStatement("$T responseBody = response.getBody()", BinaryData.class); - } else { - methodBuilder - .addStatement("$T responseBody = response.getBody()", BinaryData.class) - .addStatement("return decodeByteArray(responseBody.toBytes(), response, serializer, methodParser)"); - } - } - - public void configureRequestWithBodyAndContentType(MethodSpec.Builder methodBuilder, String parameterType, - String contentType, String parameterName) { - if (parameterType == null) { - // No body content to set - methodBuilder - .addStatement("httpRequest.getHeaders().set($T.CONTENT_LENGTH, $S))", HttpHeaderName.class, 0); - } else { - - if (contentType == null || contentType.isEmpty()) { - if (parameterType.equals("byte[]") || parameterType.equals("String")) { - - contentType = ContentType.APPLICATION_OCTET_STREAM; - } else { - - contentType = ContentType.APPLICATION_JSON; - } - } - setContentTypeHeader(methodBuilder, contentType); - if (parameterType.equals("io.clientcore.core.util.binarydata.BinaryData")) { - methodBuilder - .addStatement("$T binaryData = ($T) $L", BinaryData.class, BinaryData.class, parameterName) - .beginControlFlow("if (binaryData.getLength() != null)") - .addStatement( - "httpRequest.getHeaders().set($T.CONTENT_LENGTH, String.valueOf(binaryData.getLength()))", - HttpHeaderName.class) - .addStatement("httpRequest.setBody(binaryData)") - .endControlFlow(); - return; - } - - boolean isJson = false; - final String[] contentTypeParts = contentType.split(";"); - - for (final String contentTypePart : contentTypeParts) { - if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { - isJson = true; - - break; - } - } - updateRequestWithBodyContent(methodBuilder, isJson, parameterType, parameterName); - } - } - - private static void setContentTypeHeader(MethodSpec.Builder methodBuilder, String contentType) { - switch (contentType) { - case ContentType.APPLICATION_JSON: - methodBuilder.addStatement("httpRequest.getHeaders().set($T.$L, $T.$L)", - ClassName.get("io.clientcore.core.http.models", "HttpHeaderName"), - "CONTENT_TYPE", - CONTENT_TYPE, - "APPLICATION_JSON"); - break; - case ContentType.APPLICATION_OCTET_STREAM: - methodBuilder.addStatement("httpRequest.getHeaders().set($T.$L, $T.$L)", - ClassName.get("io.clientcore.core.http.models", "HttpHeaderName"), - "CONTENT_TYPE", - CONTENT_TYPE, - "APPLICATION_OCTET_STREAM"); - break; - case ContentType.APPLICATION_X_WWW_FORM_URLENCODED: - methodBuilder.addStatement("httpRequest.getHeaders().set($T.$L, $T.$L)", - ClassName.get("io.clientcore.core.http.models", "HttpHeaderName"), - "CONTENT_TYPE", - CONTENT_TYPE, - "APPLICATION_X_WWW_FORM_URLENCODED"); - break; - case ContentType.TEXT_EVENT_STREAM: - methodBuilder.addStatement("httpRequest.getHeaders().set($T.$L, $T.$L)", - ClassName.get("io.clientcore.core.http.models", "HttpHeaderName"), - "CONTENT_TYPE", - CONTENT_TYPE, - "TEXT_EVENT_STREAM"); - break; - } - } - - private void updateRequestWithBodyContent(MethodSpec.Builder methodBuilder, boolean isJson, String parameterType, - String parameterName) { - if (parameterType == null) { - return; - } - if (isJson) { - methodBuilder - .addStatement("httpRequest.setBody($T.fromObject($L, serializer))", BinaryData.class, parameterName); - } else if (parameterType.equals("byte[]")) { - methodBuilder - .addStatement("httpRequest.setBody($T.fromBytes((byte[]) $L))", BinaryData.class, parameterName); - } else if (parameterType.equals("String")) { - methodBuilder - .addStatement("httpRequest.setBody($T.fromString((String) $L))", BinaryData.class, parameterName); - } else if (parameterType.equals("ByteBuffer")) { - // TODO: confirm behavior - //if (((ByteBuffer) bodyContentObject).hasArray()) { - // methodBuilder - // .addStatement("httpRequest.setBody($T.fromBytes(((ByteBuffer) $L).array()))", BinaryData.class, parameterName); - //} else { - // byte[] array = new byte[((ByteBuffer) bodyContentObject).remaining()]; - // - // ((ByteBuffer) bodyContentObject).get(array); - // methodBuilder - // .addStatement("httpRequest.setBody($T.fromBytes($L))", BinaryData.class, array); - //} - methodBuilder - .addStatement("httpRequest.setBody($T.fromBytes(((ByteBuffer) $L).array()))", BinaryData.class, - parameterName); - - } else { - methodBuilder - .addStatement("httpRequest.setBody($T.fromObject($L, serializer))", BinaryData.class, parameterName); - } - } - - /* - * Get a TypeName for a parameterized type, given the raw type and type arguments as Class objects. - */ - private static TypeName inferTypeNameFromReturnType(String typeString) { - // Split the string into raw type and type arguments - int angleBracketIndex = typeString.indexOf('<'); - if (angleBracketIndex == -1) { - // No type arguments - return ClassName.get("", typeString); - } - String rawTypeString = typeString.substring(0, angleBracketIndex); - String typeArgumentsString = typeString.substring(angleBracketIndex + 1, typeString.length() - 1); - - // Get the Class objects for the raw type and type arguments - Class rawType; - Class typeArgument; - try { - rawType = Class.forName(rawTypeString); - typeArgument = Class.forName(typeArgumentsString); - } catch (ClassNotFoundException e) { - throw new RuntimeException(e); - } - // Use the inferTypeNameFromReturnType method to create a ParameterizedTypeName - return getParameterizedTypeNameFromRawArguments(rawType, typeArgument); - } - - /* - * Get a TypeName for a parameterized type, given the raw type and type arguments as Class objects. - */ - private static ParameterizedTypeName getParameterizedTypeNameFromRawArguments(Class rawType, - Class... typeArguments) { - ClassName rawTypeName = ClassName.get(rawType); - TypeName[] typeArgumentNames = new TypeName[typeArguments.length]; - for (int i = 0; i < typeArguments.length; i++) { - typeArgumentNames[i] = ClassName.get(typeArguments[i]); - } - return ParameterizedTypeName.get(rawTypeName, typeArgumentNames); - } -} diff --git a/sdk/clientcore/tools/annotation-processor/src/main/java/io/clientcore/tools/codegen/templating/TemplateProcessor.java b/sdk/clientcore/tools/annotation-processor/src/main/java/io/clientcore/tools/codegen/templating/TemplateProcessor.java deleted file mode 100644 index cb15935bffeb..000000000000 --- a/sdk/clientcore/tools/annotation-processor/src/main/java/io/clientcore/tools/codegen/templating/TemplateProcessor.java +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.tools.codegen.templating; - -import io.clientcore.tools.codegen.models.TemplateInput; - -import javax.annotation.processing.ProcessingEnvironment; - -public interface TemplateProcessor { - static TemplateProcessor getInstance() { - return new JavaPoetTemplateProcessor(); - } - - void process(TemplateInput templateInput, ProcessingEnvironment processingEnv); -} diff --git a/sdk/clientcore/tools/annotation-processor/src/main/java/io/clientcore/tools/codegen/utils/PathBuilder.java b/sdk/clientcore/tools/annotation-processor/src/main/java/io/clientcore/tools/codegen/utils/PathBuilder.java deleted file mode 100644 index 5877213caf67..000000000000 --- a/sdk/clientcore/tools/annotation-processor/src/main/java/io/clientcore/tools/codegen/utils/PathBuilder.java +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.tools.codegen.utils; - -import io.clientcore.tools.codegen.exceptions.MissingSubstitutionException; -import io.clientcore.tools.codegen.models.HttpRequestContext; -import io.clientcore.tools.codegen.models.Substitution; - -import java.util.Objects; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class PathBuilder { - // this class takes a 'raw host' string that contains {} delimited parameters, and needs to convert it into a - // Java string concatenation that can be used in the generated code. For example, the raw host string: - // https://{endpoint}/keys/{path1} - // would be converted into: - // "https://" + endpointParam + "/keys/" + pathValue - // Note that query parameters may also exist, and should be appended to the end of the URL string using - // a Map containing key-value pairs. - // Note that the 'endpoint' parameter is special - it is always the first parameter, and is always a host parameter. - public static String buildPath(String rawHost, HttpRequestContext method) { - if (method == null) { - throw new NullPointerException("method cannot be null"); - } - - boolean hasQueryParams = !method.getQueryParams().isEmpty(); - - // Pattern for substitution placeholders - Pattern pattern = Pattern.compile("\\{(.+?)\\}"); - Matcher matcher = pattern.matcher(rawHost); - StringBuffer buffer = new StringBuffer(); - - while (matcher.find()) { - String paramName = matcher.group(1); - Substitution substitution = method.getSubstitution(paramName); - - if (substitution != null) { - String substitutionValue = substitution.getParameterVariableName(); - String replacementValue = substitutionValue != null - ? Objects.toString(substitutionValue, "null") - : ""; - - matcher.appendReplacement(buffer, ""); - if (buffer.length() != 0) { - buffer.append("\" + "); - } - buffer.append(replacementValue).append(" + \""); - } else { - throw new MissingSubstitutionException("Could not find substitution for '" + paramName + "' in method '" + method.getMethodName() + "'"); - } - } - - matcher.appendTail(buffer); - - if (hasQueryParams) { - buffer.append("?"); - - method.getQueryParams().forEach((key, value) -> { - if (key.isEmpty() || value.isEmpty()) { - throw new IllegalArgumentException("Query parameter key and value must not be empty"); - } - buffer.append(key).append("=\" + ").append(Objects.toString(value, "null")).append(" + \"&"); - }); - - // Remove the trailing '&' - buffer.setLength(buffer.length() - 1); - } - - // Ensure the output is properly quoted - if (buffer.charAt(0) != '"' && !rawHost.startsWith("{")) { - buffer.insert(0, '"'); - } - if (!hasQueryParams && buffer.charAt(buffer.length() - 1) != '"' && !rawHost.endsWith("}")) { - buffer.append('"'); - } - - // Clean unnecessary `+ ""` in the buffer - String result = buffer.toString().replaceAll(" \\+ \"\"", ""); - - // Remove trailing ' + ' if it exists - if (result.endsWith(" + ")) { - result = result.substring(0, result.length() - 3); - } - - // Remove trailing ' + "' if it exists - if (result.endsWith(" + \"")) { - result = result.substring(0, result.length() - 4); - } - - // Check for missing or incorrect braces - long openingBracesCount = rawHost.chars().filter(ch -> ch == '{').count(); - long closingBracesCount = rawHost.chars().filter(ch -> ch == '}').count(); - - if (openingBracesCount != closingBracesCount) { - throw new MissingSubstitutionException("Mismatched braces in raw host: " + rawHost); - } - - return result; - } -} diff --git a/sdk/clientcore/tools/annotation-processor/src/main/java/io/clientcore/tools/codegen/utils/ResponseBodyModeGeneration.java b/sdk/clientcore/tools/annotation-processor/src/main/java/io/clientcore/tools/codegen/utils/ResponseBodyModeGeneration.java deleted file mode 100644 index 187f4d57ce91..000000000000 --- a/sdk/clientcore/tools/annotation-processor/src/main/java/io/clientcore/tools/codegen/utils/ResponseBodyModeGeneration.java +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.tools.codegen.utils; - -import com.squareup.javapoet.MethodSpec; -import io.clientcore.core.http.models.HttpResponse; -import io.clientcore.core.http.models.ResponseBodyMode; -import io.clientcore.core.implementation.http.HttpResponseAccessHelper; -import io.clientcore.core.util.binarydata.BinaryData; - -/* - * Utility class to generate response body mode assignment and response handling based on the response body mode. - */ -public class ResponseBodyModeGeneration { - public static void generateResponseBodyModeAssignment(MethodSpec.Builder methodBuilder) { - methodBuilder.addStatement("$T responseBodyMode = null", ResponseBodyMode.class) - .beginControlFlow("if (requestOptions != null)") - .addStatement("responseBodyMode = requestOptions.getResponseBodyMode()") - .endControlFlow(); - } - - public static void generateDeserializeResponseHandling(MethodSpec.Builder methodBuilder) { - methodBuilder.beginControlFlow("if (responseBodyMode == $T.DESERIALIZE)", ResponseBodyMode.class) - .addStatement("$T responseBody = response.getBody()", BinaryData.class) - .addStatement("$T.setValue(($T) response, responseBody)", - HttpResponseAccessHelper.class, HttpResponse.class) - .endControlFlow(); - } - - public static void generateNonDeserializeResponseHandling(MethodSpec.Builder methodBuilder) { - methodBuilder.nextControlFlow("else") - .addStatement("$T responseBody = response.getBody()", BinaryData.class) - .addStatement("$T.setBodyDeserializer(($T) response, (body) -> responseBody)", - HttpResponseAccessHelper.class, HttpResponse.class) - .endControlFlow(); - } -} - diff --git a/sdk/clientcore/tools/annotation-processor/src/main/resources/META-INF/maven/services/javax.annotation.processing.Processor b/sdk/clientcore/tools/annotation-processor/src/main/resources/META-INF/maven/services/javax.annotation.processing.Processor deleted file mode 100644 index 7966f81cda3f..000000000000 --- a/sdk/clientcore/tools/annotation-processor/src/main/resources/META-INF/maven/services/javax.annotation.processing.Processor +++ /dev/null @@ -1 +0,0 @@ -io.clientcore.tools.codegen.AnnotationProcessor diff --git a/sdk/clientcore/tools/annotation-processor/src/test/java/io/clientcore/tools/codegen/models/TemplateInputTest.java b/sdk/clientcore/tools/annotation-processor/src/test/java/io/clientcore/tools/codegen/models/TemplateInputTest.java deleted file mode 100644 index 5deedb7b0ba6..000000000000 --- a/sdk/clientcore/tools/annotation-processor/src/test/java/io/clientcore/tools/codegen/models/TemplateInputTest.java +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.tools.codegen.models; - -import io.clientcore.core.http.annotation.UnexpectedResponseExceptionDetail; -import java.util.Collections; -import java.util.List; -import javax.lang.model.type.DeclaredType; -import javax.lang.model.type.TypeKind; -import javax.lang.model.type.TypeMirror; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * Tests for the {@link TemplateInput} class. - */ -public class TemplateInputTest { - - @Test - void getHostReturnsCorrectHost() { - TemplateInput templateInput = new TemplateInput(); - templateInput.setHost("localhost"); - assertEquals("localhost", templateInput.getHost()); - } - - @Test - void setHostUpdatesHost() { - TemplateInput templateInput = new TemplateInput(); - templateInput.setHost("127.0.0.1"); - assertEquals("127.0.0.1", templateInput.getHost()); - } - - @Test - void addImportAddsValidImport() { - TemplateInput templateInput = new TemplateInput(); - String shortName = templateInput.addImport("java.util.List"); - assertEquals("List", shortName); - assertTrue(templateInput.getImports().containsKey("java.util.List")); - } - - @Test - void addImportIgnoresNullImport() { - TemplateInput templateInput = new TemplateInput(); - String shortName = templateInput.addImport((String) null); - assertNull(shortName); - assertTrue(templateInput.getImports().isEmpty()); - } - - @Test - void addImportIgnoresEmptyImport() { - TemplateInput templateInput = new TemplateInput(); - String shortName = templateInput.addImport(""); - assertNull(shortName); - assertTrue(templateInput.getImports().isEmpty()); - } - - @Test - void addImportTypeMirrorAddsValidImport() { - TemplateInput templateInput = new TemplateInput(); - DeclaredType declaredType = mock(DeclaredType.class); - when(declaredType.toString()).thenReturn("java.util.Map"); - when(declaredType.getKind()).thenReturn(TypeKind.DECLARED); - String shortName = templateInput.addImport(declaredType); - assertEquals("Map", shortName); - assertTrue(templateInput.getImports().containsKey("java.util.Map")); - } - - @Test - void addImportTypeMirrorHandlesPrimitiveType() { - TemplateInput templateInput = new TemplateInput(); - TypeMirror typeMirror = mock(TypeMirror.class); - when(typeMirror.toString()).thenReturn("int"); - when(typeMirror.getKind()).thenReturn(TypeKind.INT); - String shortName = templateInput.addImport(typeMirror); - assertEquals("int", shortName); - assertTrue(templateInput.getImports().containsKey("int")); - } - - @Test - void setAndGetServiceInterfaceFQN() { - TemplateInput templateInput = new TemplateInput(); - templateInput.setServiceInterfaceFQN("com.example.Service"); - assertEquals("com.example.Service", templateInput.getServiceInterfaceFQN()); - } - - @Test - void setAndGetUnexpectedResponseExceptionDetails() { - TemplateInput templateInput = new TemplateInput(); - List details = - Collections.singletonList(mock(UnexpectedResponseExceptionDetail.class)); - templateInput.setUnexpectedResponseExceptionDetails(details); - assertEquals(details, templateInput.getUnexpectedResponseExceptionDetails()); - } -} diff --git a/sdk/clientcore/tools/annotation-processor/src/test/java/io/clientcore/tools/codegen/templating/APIGenerationTest.java b/sdk/clientcore/tools/annotation-processor/src/test/java/io/clientcore/tools/codegen/templating/APIGenerationTest.java deleted file mode 100644 index ebd90fbc74d7..000000000000 --- a/sdk/clientcore/tools/annotation-processor/src/test/java/io/clientcore/tools/codegen/templating/APIGenerationTest.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.tools.codegen.templating; - -import io.clientcore.tools.codegen.models.HttpRequestContext; -import io.clientcore.tools.codegen.models.Substitution; -import io.clientcore.tools.codegen.models.TemplateInput; -import com.squareup.javapoet.MethodSpec; -import io.clientcore.core.http.models.HttpMethod; -import java.util.Collections; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.mock; - -/* - * This class tests the methods generated from the provided ServiceInterface Template. - */ -public class APIGenerationTest { - - private JavaPoetTemplateProcessor processor; - private TemplateInput templateInput; - - @BeforeEach - public void setUp() { - processor = new JavaPoetTemplateProcessor(); - templateInput = mock(TemplateInput.class); - } - - @Test - public void testPublicAPIUserMethodGeneration() { - //@HttpRequestInformation( - // method = HttpMethod.GET, - // path = "/users/{userId}", - // expectedStatusCodes = {200} - // ) - // User getUser(@PathParam("userId") String userId); - HttpRequestContext getUserMethodContext = new HttpRequestContext(); - - getUserMethodContext.setHttpMethod(HttpMethod.GET); - getUserMethodContext.setPath("/users/{userId}"); - getUserMethodContext.setExpectedStatusCodes(new int[]{200}); - getUserMethodContext.setMethodName("getUser"); - getUserMethodContext.setMethodReturnType("User"); - getUserMethodContext.addSubstitution(new Substitution( - "String", - "userId", - false)); - getUserMethodContext.setBody(new HttpRequestContext.Body("multipart/form-data", "BinaryData", "audioTranscriptionOptions")); - templateInput.setHttpRequestContexts(Collections.singletonList(getUserMethodContext)); - - MethodSpec getUserMethodGenerationSpec = processor.generatePublicMethod(getUserMethodContext); - assertEquals("getUser", getUserMethodGenerationSpec.name); - assertEquals("User", getUserMethodGenerationSpec.returnType.toString()); - // assert code block contains the expected method body - assertEquals("return getUser();\n", getUserMethodGenerationSpec.code.toString()); - } -} diff --git a/sdk/clientcore/tools/annotation-processor/src/test/java/io/clientcore/tools/codegen/templating/BodyContentTypeProcessorTest.java b/sdk/clientcore/tools/annotation-processor/src/test/java/io/clientcore/tools/codegen/templating/BodyContentTypeProcessorTest.java deleted file mode 100644 index d2efb5dcb83d..000000000000 --- a/sdk/clientcore/tools/annotation-processor/src/test/java/io/clientcore/tools/codegen/templating/BodyContentTypeProcessorTest.java +++ /dev/null @@ -1,145 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.tools.codegen.templating; - -import io.clientcore.tools.codegen.models.HttpRequestContext; -import com.squareup.javapoet.MethodSpec; -import java.util.stream.Stream; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class BodyContentTypeProcessorTest { - private JavaPoetTemplateProcessor processor; - - @BeforeEach - public void setup() { - processor = new JavaPoetTemplateProcessor(); - } - - /** - * Test for the method configureRequestWithBodyAndContentType - */ - @Test - public void bodyParamAnnotationPriorityOverContentTypeHeaderTest() { - // Create a new HttpRequestContext - HttpRequestContext context = new HttpRequestContext(); - byte[] bytes = "hello".getBytes(); - - // Set the body - // BodyParam annotation is set to "application/octet-stream" - context.setBody(new HttpRequestContext.Body("application/octet-stream", "ByteBuffer", "request")); - - // Add headers - // Content-Type header is set to "application/json" - context.addHeader("Content-Type", "application/json"); - context.addHeader("Content-Length", String.valueOf((long) bytes.length)); - HttpRequestContext.Body body = context.getBody(); - - MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("testMethod"); - processor.configureRequestWithBodyAndContentType(methodBuilder, body.getParameterType(), body.getContentType(), - body.getParameterName()); - MethodSpec methodSpec = methodBuilder.build(); - - // Expected output - String expectedOutput = - "httpRequest.setBody(io.clientcore.core.util.binarydata.BinaryData.fromBytes(((ByteBuffer) request).array()));"; - - // Actual output - String actualOutput = methodSpec.toString(); - - assertTrue(actualOutput.contains(expectedOutput)); - // Verify headers in a separate test request content type header is set to application/octet-stream - - } - - @ParameterizedTest - @MethodSource("knownParameterTypesProvider") - public void testConfigureRequestWithBodyAndParameterType(HttpRequestContext.Body body, String expectedOutput) { - MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("testMethod"); - processor.configureRequestWithBodyAndContentType(methodBuilder, body.getParameterType(), body.getContentType(), - body.getParameterName()); - MethodSpec methodSpec = methodBuilder.build(); - - // Actual output - String actualOutput = methodSpec.toString(); - assertTrue(actualOutput.contains(expectedOutput)); - } - - @ParameterizedTest - @MethodSource("knownContentTypesProvider") - public void testConfigureRequestWithBodyAndContentType(String parameterType, String expectedContentType) { - // Create a new HttpRequestContext - HttpRequestContext context = new HttpRequestContext(); - - // Set the body without specifying ContentType - context.setBody(new HttpRequestContext.Body(null, parameterType, "request")); - - MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("testMethod"); - processor.configureRequestWithBodyAndContentType(methodBuilder, context.getBody().getParameterType(), - context.getBody().getContentType(), context.getBody().getParameterName()); - MethodSpec methodSpec = methodBuilder.build(); - - // Expected output - String expectedOutput = - "httpRequest.getHeaders().set(io.clientcore.core.http.models.HttpHeaderName.CONTENT_TYPE, " + - expectedContentType; - - // Actual output - String actualOutput = methodSpec.toString(); - - assertTrue(actualOutput.contains(expectedOutput)); - } - - private static Stream knownContentTypesProvider() { - return Stream.of( - Arguments.of("byte[]", "io.clientcore.core.http.models.ContentType.APPLICATION_OCTET_STREAM"), - Arguments.of("String", "io.clientcore.core.http.models.ContentType.APPLICATION_OCTET_STREAM"), - Arguments.of("BinaryData", "io.clientcore.core.http.models.ContentType.APPLICATION_JSON"), - Arguments.of("Object", "io.clientcore.core.http.models.ContentType.APPLICATION_JSON"), - Arguments.of("ByteBuffer", "io.clientcore.core.http.models.ContentType.APPLICATION_JSON") - ); - } - - private static Stream knownParameterTypesProvider() { - return Stream.of( - // scenario for isJson = true and parameterType == "ByteBuffer" - Arguments.of(new HttpRequestContext.Body(null, "ByteBuffer", "request"), - "httpRequest.setBody(io.clientcore.core.util.binarydata.BinaryData.fromObject(request, serializer));"), - Arguments.of(new HttpRequestContext.Body("application/octet-stream", "BinaryData", "request"), - "httpRequest.setBody(io.clientcore.core.util.binarydata.BinaryData.fromObject(request, serializer));"), - Arguments.of(new HttpRequestContext.Body("application/json", "BinaryData", "request"), - "httpRequest.setBody(io.clientcore.core.util.binarydata.BinaryData.fromObject(request, serializer));"), - Arguments.of(new HttpRequestContext.Body("application/json", "serializable", "request"), - "httpRequest.setBody(io.clientcore.core.util.binarydata.BinaryData.fromObject(request, serializer))"), - Arguments.of(new HttpRequestContext.Body("application/octet-stream", "byte[]", "request"), - "httpRequest.setBody(io.clientcore.core.util.binarydata.BinaryData.fromBytes((byte[]) request))"), - Arguments.of(new HttpRequestContext.Body("application/octet-stream", "String", "request"), - "httpRequest.setBody(io.clientcore.core.util.binarydata.BinaryData.fromString((String) request))"), - Arguments.of(new HttpRequestContext.Body("application/octet-stream", "ByteBuffer", "request"), - "httpRequest.setBody(io.clientcore.core.util.binarydata.BinaryData.fromBytes(((ByteBuffer) request).array()))"), - Arguments.of(new HttpRequestContext.Body("application/octet-stream", "Object", "request"), - "httpRequest.setBody(io.clientcore.core.util.binarydata.BinaryData.fromObject(request, serializer))"), - // scenario for isJson = false and parameterType == "String" - Arguments.of(new HttpRequestContext.Body("text/html", "String", "request"), - "httpRequest.setBody(io.clientcore.core.util.binarydata.BinaryData.fromString((String) request));"), - // scenario for isJson = false and parameterType == "ByteBuffer" - Arguments.of(new HttpRequestContext.Body("text/html", "ByteBuffer", "request"), - "httpRequest.setBody(io.clientcore.core.util.binarydata.BinaryData.fromBytes(((ByteBuffer) request).array()));"), - // scenario for parameterType = null - Arguments.of(new HttpRequestContext.Body("application/json", null, "request"), - "httpRequest.getHeaders().set(io.clientcore.core.http.models.HttpHeaderName.CONTENT_LENGTH, \"0\"));"), - // scenario for parameterType == "byte[]" - Arguments.of(new HttpRequestContext.Body("application/octet-stream", "byte[]", "request"), - "httpRequest.setBody(io.clientcore.core.util.binarydata.BinaryData.fromBytes((byte[]) request));"), - // Add scenario for parameterType == "String" - Arguments.of(new HttpRequestContext.Body("application/octet-stream", "String", "request"), - "httpRequest.setBody(io.clientcore.core.util.binarydata.BinaryData.fromString((String) request));") - ); - } -} diff --git a/sdk/clientcore/tools/annotation-processor/src/test/java/io/clientcore/tools/codegen/templating/HttpPipelineBuilderMethodTest.java b/sdk/clientcore/tools/annotation-processor/src/test/java/io/clientcore/tools/codegen/templating/HttpPipelineBuilderMethodTest.java deleted file mode 100644 index 857b221106e8..000000000000 --- a/sdk/clientcore/tools/annotation-processor/src/test/java/io/clientcore/tools/codegen/templating/HttpPipelineBuilderMethodTest.java +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.tools.codegen.templating; - -import io.clientcore.tools.codegen.models.TemplateInput; -import com.squareup.javapoet.ClassName; -import com.squareup.javapoet.FieldSpec; -import com.squareup.javapoet.MethodSpec; -import java.io.IOException; -import java.io.Writer; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import javax.annotation.processing.Filer; -import javax.annotation.processing.ProcessingEnvironment; -import javax.lang.model.element.Modifier; -import javax.tools.JavaFileObject; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/* - * Tests for builder/helper methods generated in ServiceClientImpl class. - */ -public class HttpPipelineBuilderMethodTest { - - private static final String PACKAGE_NAME = "com.example"; - private static final String SERVICE_INTERFACE_SHORT_NAME = getExampleClientServiceImpl(); - private JavaPoetTemplateProcessor processor; - private ProcessingEnvironment processingEnv; - private TemplateInput templateInput; - - @BeforeEach - public void setUp() { - processor = new JavaPoetTemplateProcessor(); - processingEnv = mock(ProcessingEnvironment.class); - templateInput = mock(TemplateInput.class); - - when(templateInput.getPackageName()).thenReturn(PACKAGE_NAME); - when(templateInput.getServiceInterfaceImplShortName()).thenReturn(SERVICE_INTERFACE_SHORT_NAME); - when(templateInput.getServiceInterfaceShortName()).thenReturn("ExampleClientService"); - when(templateInput.getHttpRequestContexts()).thenReturn(Collections.emptyList()); - } - - private static String getExampleClientServiceImpl() { - return "ExampleClientServiceImpl"; - } - - @Test - public void testProcess() throws IOException { - Filer filer = mock(Filer.class); - JavaFileObject filerSourceFile = mock(JavaFileObject.class); - when(processingEnv.getFiler()).thenReturn(filer); - when(filer.createSourceFile(anyString())).thenReturn(filerSourceFile); - when(filerSourceFile.openWriter()).thenReturn(mock(Writer.class)); - - processor.process(templateInput, processingEnv); - - // Verify that the JavaFile.writeTo was called - verify(processingEnv, times(1)).getFiler(); - } - - @Test - public void testGetEndpointMethod() { - MethodSpec method = processor.getEndpointMethod(); - assertEquals("getEndpoint", method.name); - assertEquals(Modifier.PUBLIC, method.modifiers.iterator().next()); - assertEquals(ClassName.get("java.lang", "String"), method.returnType); - } - - @Test - public void testGetPipelineMethod() { - MethodSpec method = processor.getPipelineMethod(); - assertEquals("getPipeline", method.name); - assertEquals(Modifier.PUBLIC, method.modifiers.iterator().next()); - assertEquals(processor.HTTP_PIPELINE, method.returnType); - } - - @Test - public void testGetServiceVersionMethod() { - MethodSpec method = processor.getServiceVersionMethod(); - assertEquals("getServiceVersion", method.name); - assertEquals(Modifier.PUBLIC, method.modifiers.iterator().next()); - when(templateInput.getServiceInterfaceShortName()).thenReturn("ExampleClientService"); - assertTrue(method.code.toString().contains("return serviceVersion")); - } - - @Test - public void testGetServiceVersionType() { - assertEquals("com.example.ExampleServiceVersion", processor.getServiceVersionType(PACKAGE_NAME, - SERVICE_INTERFACE_SHORT_NAME).toString()); - } - - @Test - public void testServiceImplConstructorGeneration() { - MethodSpec constructor = processor.getServiceImplConstructor(PACKAGE_NAME, - SERVICE_INTERFACE_SHORT_NAME); - assertEquals(Modifier.PUBLIC, constructor.modifiers.iterator().next()); - assertEquals(4, constructor.parameters.size()); - assertTrue(constructor.code.toString().contains("this.defaultPipeline = defaultPipeline")); - assertTrue(constructor.code.toString().contains("this.serializer = serializer")); - assertTrue(constructor.code.toString().contains("this.endpoint = endpoint")); - assertTrue(constructor.code.toString().contains("this.apiVersion = serviceVersion.getVersion()")); - assertTrue(constructor.code.toString().contains("this.serviceVersion = serviceVersion")); - } - - @Test - public void testLoggerFieldGeneration() { - FieldSpec loggerField = processor.getLoggerField(PACKAGE_NAME, SERVICE_INTERFACE_SHORT_NAME); - assertEquals(new HashSet<>(Arrays.asList(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)), - loggerField.modifiers); - assertEquals(processor.CLIENTLOGGER_NAME, loggerField.type); - assertEquals("LOGGER", loggerField.name); - assertTrue(loggerField.initializer.toString().contains("new io.clientcore.core.util.ClientLogger(com.example.ExampleClientServiceImpl.class)")); - } -} diff --git a/sdk/clientcore/tools/annotation-processor/src/test/java/io/clientcore/tools/codegen/utils/ResponseBodyModeGenerationTest.java b/sdk/clientcore/tools/annotation-processor/src/test/java/io/clientcore/tools/codegen/utils/ResponseBodyModeGenerationTest.java deleted file mode 100644 index 418cfc6edcbc..000000000000 --- a/sdk/clientcore/tools/annotation-processor/src/test/java/io/clientcore/tools/codegen/utils/ResponseBodyModeGenerationTest.java +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package io.clientcore.tools.codegen.utils; - -import com.squareup.javapoet.MethodSpec; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -class ResponseBodyModeGenerationTest { - - private MethodSpec.Builder methodBuilder; - - @BeforeEach - void setUp() { - methodBuilder = MethodSpec.methodBuilder("testMethod"); - } - - @Test - void generateResponseBodyModeAssignment_withRequestOptions() { - ResponseBodyModeGeneration.generateResponseBodyModeAssignment(methodBuilder); - MethodSpec methodSpec = methodBuilder.build(); - assertTrue(methodSpec.toString().contains("responseBodyMode = requestOptions.getResponseBodyMode()")); - } - - @Test - void generateResponseHandling_withDeserializeMode() { - ResponseBodyModeGeneration.generateDeserializeResponseHandling(methodBuilder); - MethodSpec methodSpec = methodBuilder.build(); - // verify generation calls HttpResponseAccessHelper.setValue() with the correct parameters; - assertTrue(methodSpec.toString().contains("HttpResponseAccessHelper.setValue((io.clientcore.core.http.models.HttpResponse) response, responseBody);")); - } - - //@Test - //void generateResponseHandling_withNonDeserializeMode() { - // ResponseBodyModeGeneration.generateNonDeserializeResponseHandling(methodBuilder); - // MethodSpec methodSpec = methodBuilder.build(); - // // verify generation calls HttpResponseAccessHelper.setValue() with the correct parameters; - // assertTrue(methodSpec.toString().contains("HttpResponseAccessHelper.setValue((io.clientcore.core.http.models.HttpResponse) response, responseBody);")); - //} -} diff --git a/sdk/clientcore/tools/pom.xml b/sdk/clientcore/tools/pom.xml deleted file mode 100644 index c4a6300b1008..000000000000 --- a/sdk/clientcore/tools/pom.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - 4.0.0 - io.clientcore - clientcore-tools-parent - pom - 1.0.0 - - annotation-processor - - diff --git a/sdk/cognitiveservices/azure-resourcemanager-cognitiveservices/README.md b/sdk/cognitiveservices/azure-resourcemanager-cognitiveservices/README.md index e3b317072af1..979346d1e8a5 100644 --- a/sdk/cognitiveservices/azure-resourcemanager-cognitiveservices/README.md +++ b/sdk/cognitiveservices/azure-resourcemanager-cognitiveservices/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-cognitiveservices - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -110,4 +110,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcognitiveservices%2Fazure-resourcemanager-cognitiveservices%2FREADME.png) + diff --git a/sdk/cognitiveservices/azure-resourcemanager-cognitiveservices/pom.xml b/sdk/cognitiveservices/azure-resourcemanager-cognitiveservices/pom.xml index 236a2e186869..c6c00df86b65 100644 --- a/sdk/cognitiveservices/azure-resourcemanager-cognitiveservices/pom.xml +++ b/sdk/cognitiveservices/azure-resourcemanager-cognitiveservices/pom.xml @@ -52,23 +52,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test @@ -92,7 +92,7 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/commerce/azure-resourcemanager-commerce/README.md b/sdk/commerce/azure-resourcemanager-commerce/README.md index 49356cb031e0..328b771f3f7d 100644 --- a/sdk/commerce/azure-resourcemanager-commerce/README.md +++ b/sdk/commerce/azure-resourcemanager-commerce/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-commerce - 1.0.0-beta.2 + 1.0.0-beta.3 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/commerce/azure-resourcemanager-commerce/pom.xml b/sdk/commerce/azure-resourcemanager-commerce/pom.xml index abe3c18449c2..d46bbd539b80 100644 --- a/sdk/commerce/azure-resourcemanager-commerce/pom.xml +++ b/sdk/commerce/azure-resourcemanager-commerce/pom.xml @@ -45,23 +45,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/communication/azure-communication-callautomation/CHANGELOG.md b/sdk/communication/azure-communication-callautomation/CHANGELOG.md index c077f78246bb..452d29102d95 100644 --- a/sdk/communication/azure-communication-callautomation/CHANGELOG.md +++ b/sdk/communication/azure-communication-callautomation/CHANGELOG.md @@ -10,6 +10,16 @@ ### Other Changes +## 1.3.2 (2025-03-03) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-communication-common` from `1.3.8` to version `1.3.9`. +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`. +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. + ## 1.4.0-beta.1 (2024-11-22) ### Features Added diff --git a/sdk/communication/azure-communication-callautomation/README.md b/sdk/communication/azure-communication-callautomation/README.md index ff8eed86e4e9..033189d8d86d 100644 --- a/sdk/communication/azure-communication-callautomation/README.md +++ b/sdk/communication/azure-communication-callautomation/README.md @@ -22,7 +22,7 @@ This package contains a Java SDK for Azure Communication Call Automation Service com.azure azure-communication-callautomation - 1.1.0 + 1.4.0-beta.2 ``` diff --git a/sdk/communication/azure-communication-callautomation/assets.json b/sdk/communication/azure-communication-callautomation/assets.json index e011f2ddd486..b143a3d7add2 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_cf67d9f149" + "Tag": "java/communication/azure-communication-callautomation_9339e7fc0c" } \ 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 2512db5c3185..8a86db86c48b 100644 --- a/sdk/communication/azure-communication-callautomation/pom.xml +++ b/sdk/communication/azure-communication-callautomation/pom.xml @@ -59,34 +59,34 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-communication-common - 1.3.9 + 1.3.10 com.azure azure-communication-identity - 1.6.2 + 1.6.3 test com.azure azure-messaging-servicebus - 7.17.8 + 7.17.9 test com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test @@ -104,13 +104,13 @@ com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-communication-phonenumbers - 1.1.19 + 1.2.1 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 f2764d4f3da2..2cf26d6aaae6 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 @@ -230,6 +230,11 @@ private CreateCallRequestInternal getCreateCallRequestInternal(CreateCallOptions callIntelligenceOptionsInternal = new CallIntelligenceOptionsInternal(); callIntelligenceOptionsInternal.setCognitiveServicesEndpoint( createCallOptions.getCallIntelligenceOptions().getCognitiveServicesEndpoint()); + + if (createCallOptions.getCallIntelligenceOptions().getBackupCognitiveServicesEndpoint() != null) { + callIntelligenceOptionsInternal.setBackupCognitiveServicesEndpoint( + createCallOptions.getCallIntelligenceOptions().getBackupCognitiveServicesEndpoint()); + } } CreateCallRequestInternal request = new CreateCallRequestInternal() @@ -278,6 +283,11 @@ private CreateCallRequestInternal getCreateCallRequestInternal(CreateGroupCallOp callIntelligenceOptionsInternal = new CallIntelligenceOptionsInternal(); callIntelligenceOptionsInternal.setCognitiveServicesEndpoint( createCallGroupOptions.getCallIntelligenceOptions().getCognitiveServicesEndpoint()); + + if (createCallGroupOptions.getCallIntelligenceOptions().getBackupCognitiveServicesEndpoint() != null) { + callIntelligenceOptionsInternal.setBackupCognitiveServicesEndpoint( + createCallGroupOptions.getCallIntelligenceOptions().getBackupCognitiveServicesEndpoint()); + } } CreateCallRequestInternal request = new CreateCallRequestInternal() @@ -383,6 +393,12 @@ Mono> answerCallWithResponseInternal(AnswerCallOption CallIntelligenceOptionsInternal callIntelligenceOptionsInternal = new CallIntelligenceOptionsInternal(); callIntelligenceOptionsInternal.setCognitiveServicesEndpoint( answerCallOptions.getCallIntelligenceOptions().getCognitiveServicesEndpoint()); + + if (answerCallOptions.getCallIntelligenceOptions().getBackupCognitiveServicesEndpoint() != null) { + callIntelligenceOptionsInternal.setBackupCognitiveServicesEndpoint( + answerCallOptions.getCallIntelligenceOptions().getBackupCognitiveServicesEndpoint()); + } + request.setCallIntelligenceOptions(callIntelligenceOptionsInternal); } @@ -581,6 +597,12 @@ Mono> connectCallWithResponseInternal(ConnectCallOpt CallIntelligenceOptionsInternal callIntelligenceOptionsInternal = new CallIntelligenceOptionsInternal(); callIntelligenceOptionsInternal.setCognitiveServicesEndpoint( connectCallOptions.getCallIntelligenceOptions().getCognitiveServicesEndpoint()); + + if (connectCallOptions.getCallIntelligenceOptions().getBackupCognitiveServicesEndpoint() != null) { + callIntelligenceOptionsInternal.setBackupCognitiveServicesEndpoint( + connectCallOptions.getCallIntelligenceOptions().getBackupCognitiveServicesEndpoint()); + } + request.setCallIntelligenceOptions(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 cad0d1636555..044726acd362 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 @@ -3,6 +3,11 @@ package com.azure.communication.callautomation; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + import com.azure.communication.callautomation.models.events.AddParticipantFailed; import com.azure.communication.callautomation.models.events.AddParticipantSucceeded; import com.azure.communication.callautomation.models.events.AnswerFailed; @@ -31,6 +36,9 @@ import com.azure.communication.callautomation.models.events.HoldAudioResumed; import com.azure.communication.callautomation.models.events.HoldAudioStarted; import com.azure.communication.callautomation.models.events.HoldFailed; +import com.azure.communication.callautomation.models.events.MediaStreamingFailed; +import com.azure.communication.callautomation.models.events.MediaStreamingStarted; +import com.azure.communication.callautomation.models.events.MediaStreamingStopped; import com.azure.communication.callautomation.models.events.ParticipantsUpdated; import com.azure.communication.callautomation.models.events.PlayCanceled; import com.azure.communication.callautomation.models.events.PlayCompleted; @@ -44,26 +52,19 @@ import com.azure.communication.callautomation.models.events.RecordingStateChanged; import com.azure.communication.callautomation.models.events.RemoveParticipantFailed; import com.azure.communication.callautomation.models.events.RemoveParticipantSucceeded; +import com.azure.communication.callautomation.models.events.SendDtmfTonesCompleted; +import com.azure.communication.callautomation.models.events.SendDtmfTonesFailed; +import com.azure.communication.callautomation.models.events.StartRecordingFailed; import com.azure.communication.callautomation.models.events.TranscriptionFailed; import com.azure.communication.callautomation.models.events.TranscriptionResumed; import com.azure.communication.callautomation.models.events.TranscriptionStarted; import com.azure.communication.callautomation.models.events.TranscriptionStopped; -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.azure.json.JsonProviders; import com.azure.json.JsonReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - /** * Event handler for taking care of event related tasks. */ @@ -133,6 +134,8 @@ private static CallAutomationEventBase parseSingleCloudEvent(String data, String ret = ParticipantsUpdated.fromJson(jsonReader); } else if (Objects.equals(eventType, "Microsoft.Communication.RecordingStateChanged")) { ret = RecordingStateChanged.fromJson(jsonReader); + } else if (Objects.equals(eventType, "Microsoft.Communication.StartRecordingFailed")) { + ret = StartRecordingFailed.fromJson(jsonReader); } else if (Objects.equals(eventType, "Microsoft.Communication.PlayCompleted")) { ret = PlayCompleted.fromJson(jsonReader); } else if (Objects.equals(eventType, "Microsoft.Communication.PlayFailed")) { diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/CallMediaAsync.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/CallMediaAsync.java index f502161d5ee4..2c8cb646d7c2 100644 --- a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/CallMediaAsync.java +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/CallMediaAsync.java @@ -3,6 +3,11 @@ package com.azure.communication.callautomation; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + import com.azure.communication.callautomation.implementation.CallMediasImpl; import com.azure.communication.callautomation.implementation.accesshelpers.SendDtmfTonesResponseConstructorProxy; import com.azure.communication.callautomation.implementation.converters.CommunicationIdentifierConverter; @@ -62,16 +67,11 @@ import com.azure.core.http.rest.SimpleResponse; import com.azure.core.util.Context; import com.azure.core.util.FluxUtil; -import com.azure.core.util.logging.ClientLogger; -import reactor.core.publisher.Mono; - -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - import static com.azure.core.util.FluxUtil.monoError; import static com.azure.core.util.FluxUtil.withContext; +import com.azure.core.util.logging.ClientLogger; + +import reactor.core.publisher.Mono; /** * CallContent. @@ -303,6 +303,7 @@ PlayRequest getPlayRequest(PlayOptions options) { request.setPlayOptions(new PlayOptionsInternal().setLoop(options.isLoop())); request.setOperationContext(options.getOperationContext()); request.setOperationCallbackUri(options.getOperationCallbackUrl()); + request.setPlayOptions(new PlayOptionsInternal().setInterruptHoldAudio(options.isInterruptHoldAudio())); return request; } diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/CallRecordingAsync.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/CallRecordingAsync.java index f31440fae4ec..c5290114fd79 100644 --- a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/CallRecordingAsync.java +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/CallRecordingAsync.java @@ -3,6 +3,22 @@ package com.azure.communication.callautomation; +import java.io.IOException; +import java.io.OutputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.ByteBuffer; +import java.nio.channels.AsynchronousFileChannel; +import java.nio.file.OpenOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.security.InvalidParameterException; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + import com.azure.communication.callautomation.implementation.CallRecordingsImpl; import com.azure.communication.callautomation.implementation.accesshelpers.RecordingStateResponseConstructorProxy; import com.azure.communication.callautomation.implementation.converters.CommunicationIdentifierConverter; @@ -24,8 +40,8 @@ import com.azure.communication.callautomation.models.GroupCallLocator; import com.azure.communication.callautomation.models.ParallelDownloadOptions; import com.azure.communication.callautomation.models.RecordingStateResult; -import com.azure.communication.callautomation.models.ServerCallLocator; import com.azure.communication.callautomation.models.RoomCallLocator; +import com.azure.communication.callautomation.models.ServerCallLocator; import com.azure.communication.callautomation.models.StartRecordingOptions; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; @@ -38,29 +54,13 @@ import com.azure.core.http.rest.SimpleResponse; import com.azure.core.util.BinaryData; import com.azure.core.util.Context; +import static com.azure.core.util.FluxUtil.monoError; +import static com.azure.core.util.FluxUtil.withContext; import com.azure.core.util.logging.ClientLogger; + import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; -import java.io.IOException; -import java.io.OutputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.nio.ByteBuffer; -import java.nio.channels.AsynchronousFileChannel; -import java.nio.file.OpenOption; -import java.nio.file.Path; -import java.nio.file.StandardOpenOption; -import java.security.InvalidParameterException; -import java.util.HashSet; -import java.util.List; -import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; - -import static com.azure.core.util.FluxUtil.monoError; -import static com.azure.core.util.FluxUtil.withContext; - /** * CallRecordingAsync. */ @@ -126,23 +126,24 @@ Mono> startWithResponseInternal(StartRecordingOpt } private StartCallRecordingRequestInternal getStartCallRecordingRequest(StartRecordingOptions options) { - CallLocator callLocator = options.getCallLocator(); - CallLocatorInternal callLocatorInternal - = new CallLocatorInternal().setKind(CallLocatorKindInternal.fromString(callLocator.getKind().toString())); - - if (callLocator.getKind() == CallLocatorKind.GROUP_CALL_LOCATOR) { - callLocatorInternal.setGroupCallId(((GroupCallLocator) callLocator).getGroupCallId()); - } else if (callLocator.getKind() == CallLocatorKind.SERVER_CALL_LOCATOR) { - callLocatorInternal.setServerCallId(((ServerCallLocator) callLocator).getServerCallId()); - } else if (callLocator.getKind() == CallLocatorKind.ROOM_CALL_LOCATOR) { - callLocatorInternal.setRoomId(((RoomCallLocator) callLocator).getRoomId()); - } else { - throw logger.logExceptionAsError(new InvalidParameterException("callLocator has invalid kind.")); + StartCallRecordingRequestInternal request = new StartCallRecordingRequestInternal(); + if (options.getCallLocator() != null) { + CallLocator callLocator = options.getCallLocator(); + CallLocatorInternal callLocatorInternal = new CallLocatorInternal() + .setKind(CallLocatorKindInternal.fromString(callLocator.getKind().toString())); + + if (callLocator.getKind() == CallLocatorKind.GROUP_CALL_LOCATOR) { + callLocatorInternal.setGroupCallId(((GroupCallLocator) callLocator).getGroupCallId()); + } else if (callLocator.getKind() == CallLocatorKind.SERVER_CALL_LOCATOR) { + callLocatorInternal.setServerCallId(((ServerCallLocator) callLocator).getServerCallId()); + } else if (callLocator.getKind() == CallLocatorKind.ROOM_CALL_LOCATOR) { + callLocatorInternal.setRoomId(((RoomCallLocator) callLocator).getRoomId()); + } else { + throw logger.logExceptionAsError(new InvalidParameterException("callLocator has invalid kind.")); + } + request.setCallLocator(callLocatorInternal); } - StartCallRecordingRequestInternal request - = new StartCallRecordingRequestInternal().setCallLocator(callLocatorInternal); - if (options.getRecordingContent() != null) { request .setRecordingContentType(RecordingContentInternal.fromString(options.getRecordingContent().toString())); @@ -185,7 +186,9 @@ private StartCallRecordingRequestInternal getStartCallRecordingRequest(StartReco if (options.isPauseOnStart() != null) { request.setPauseOnStart(options.isPauseOnStart()); } - + if (options.getCallConnectionId() != null) { + request.setCallConnectionId(options.getCallConnectionId()); + } return request; } diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/CallRecordingsImpl.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/CallRecordingsImpl.java index ef6a1ac8638e..574d7c291acd 100644 --- a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/CallRecordingsImpl.java +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/CallRecordingsImpl.java @@ -5,6 +5,7 @@ package com.azure.communication.callautomation.implementation; import com.azure.communication.callautomation.implementation.models.CommunicationErrorResponseException; +import com.azure.communication.callautomation.implementation.models.RecordingResultResponse; import com.azure.communication.callautomation.implementation.models.RecordingStateResponseInternal; import com.azure.communication.callautomation.implementation.models.StartCallRecordingRequestInternal; import com.azure.core.annotation.BodyParam; @@ -63,7 +64,7 @@ public final class CallRecordingsImpl { @ServiceInterface(name = "AzureCommunicationCa") public interface CallRecordingsService { @Post("/calling/recordings") - @ExpectedResponses({ 200, 202 }) + @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(CommunicationErrorResponseException.class) Mono> startRecording(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @@ -99,6 +100,13 @@ Mono> pauseRecording(@HostParam("endpoint") String endpoint, Mono> resumeRecording(@HostParam("endpoint") String endpoint, @PathParam("recordingId") String recordingId, @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + + @Get("/calling/recordings/{recordingId}/result") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(CommunicationErrorResponseException.class) + Mono> getRecordingResult(@HostParam("endpoint") String endpoint, + @PathParam("recordingId") String recordingId, @QueryParam("api-version") String apiVersion, + @HeaderParam("Accept") String accept, Context context); } /** @@ -566,4 +574,97 @@ public Response resumeRecordingWithResponse(String recordingId, Context co public void resumeRecording(String recordingId) { resumeRecordingWithResponse(recordingId, Context.NONE); } + + /** + * Get recording result. This includes the download URLs for the recording chunks. + * + * @param recordingId The recording id. + * @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 recording result along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getRecordingResultWithResponseAsync(String recordingId) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.getRecordingResult(this.client.getEndpoint(), recordingId, + this.client.getApiVersion(), accept, context)); + } + + /** + * Get recording result. This includes the download URLs for the recording chunks. + * + * @param recordingId The recording id. + * @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 recording result along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getRecordingResultWithResponseAsync(String recordingId, + Context context) { + final String accept = "application/json"; + return service.getRecordingResult(this.client.getEndpoint(), recordingId, this.client.getApiVersion(), accept, + context); + } + + /** + * Get recording result. This includes the download URLs for the recording chunks. + * + * @param recordingId The recording id. + * @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 recording result on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getRecordingResultAsync(String recordingId) { + return getRecordingResultWithResponseAsync(recordingId).flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get recording result. This includes the download URLs for the recording chunks. + * + * @param recordingId The recording id. + * @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 recording result on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getRecordingResultAsync(String recordingId, Context context) { + return getRecordingResultWithResponseAsync(recordingId, context) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get recording result. This includes the download URLs for the recording chunks. + * + * @param recordingId The recording id. + * @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 recording result along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getRecordingResultWithResponse(String recordingId, Context context) { + return getRecordingResultWithResponseAsync(recordingId, context).block(); + } + + /** + * Get recording result. This includes the download URLs for the recording chunks. + * + * @param recordingId The recording id. + * @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 recording result. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public RecordingResultResponse getRecordingResult(String recordingId) { + return getRecordingResultWithResponse(recordingId, Context.NONE).getValue(); + } } diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/CallIntelligenceOptionsInternal.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/CallIntelligenceOptionsInternal.java index 3ee92c645bb8..a5f84949726e 100644 --- a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/CallIntelligenceOptionsInternal.java +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/CallIntelligenceOptionsInternal.java @@ -21,6 +21,11 @@ public final class CallIntelligenceOptionsInternal implements JsonSerializable { - /** - * Static value unknown for CallLocatorKindInternal. - */ - public static final CallLocatorKindInternal UNKNOWN = fromString("unknown"); - /** * Static value groupCallLocator for CallLocatorKindInternal. */ diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/CallSessionEndReason.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/CallSessionEndReason.java new file mode 100644 index 000000000000..f2f426200c5a --- /dev/null +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/CallSessionEndReason.java @@ -0,0 +1,181 @@ +// 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 java.util.Collection; + +/** + * Defines values for CallSessionEndReason. + */ +public final class CallSessionEndReason extends ExpandableStringEnum { + /** + * Static value sessionStillOngoing for CallSessionEndReason. + */ + public static final CallSessionEndReason SESSION_STILL_ONGOING = fromString("sessionStillOngoing"); + + /** + * Static value callEnded for CallSessionEndReason. + */ + public static final CallSessionEndReason CALL_ENDED = fromString("callEnded"); + + /** + * Static value initiatorLeft for CallSessionEndReason. + */ + public static final CallSessionEndReason INITIATOR_LEFT = fromString("initiatorLeft"); + + /** + * Static value handedOverOrTransfered for CallSessionEndReason. + */ + public static final CallSessionEndReason HANDED_OVER_OR_TRANSFERED = fromString("handedOverOrTransfered"); + + /** + * Static value maximumSessionTimeReached for CallSessionEndReason. + */ + public static final CallSessionEndReason MAXIMUM_SESSION_TIME_REACHED = fromString("maximumSessionTimeReached"); + + /** + * Static value callStartTimeout for CallSessionEndReason. + */ + public static final CallSessionEndReason CALL_START_TIMEOUT = fromString("callStartTimeout"); + + /** + * Static value mediaTimeout for CallSessionEndReason. + */ + public static final CallSessionEndReason MEDIA_TIMEOUT = fromString("mediaTimeout"); + + /** + * Static value audioStreamFailure for CallSessionEndReason. + */ + public static final CallSessionEndReason AUDIO_STREAM_FAILURE = fromString("audioStreamFailure"); + + /** + * Static value allInstancesBusy for CallSessionEndReason. + */ + public static final CallSessionEndReason ALL_INSTANCES_BUSY = fromString("allInstancesBusy"); + + /** + * Static value teamsTokenConversionFailed for CallSessionEndReason. + */ + public static final CallSessionEndReason TEAMS_TOKEN_CONVERSION_FAILED = fromString("teamsTokenConversionFailed"); + + /** + * Static value reportCallStateFailed for CallSessionEndReason. + */ + public static final CallSessionEndReason REPORT_CALL_STATE_FAILED = fromString("reportCallStateFailed"); + + /** + * Static value reportCallStateFailedAndSessionMustBeDiscarded for CallSessionEndReason. + */ + public static final CallSessionEndReason REPORT_CALL_STATE_FAILED_AND_SESSION_MUST_BE_DISCARDED + = fromString("reportCallStateFailedAndSessionMustBeDiscarded"); + + /** + * Static value couldNotRejoinCall for CallSessionEndReason. + */ + public static final CallSessionEndReason COULD_NOT_REJOIN_CALL = fromString("couldNotRejoinCall"); + + /** + * Static value invalidBotData for CallSessionEndReason. + */ + public static final CallSessionEndReason INVALID_BOT_DATA = fromString("invalidBotData"); + + /** + * Static value couldNotStart for CallSessionEndReason. + */ + public static final CallSessionEndReason COULD_NOT_START = fromString("couldNotStart"); + + /** + * Static value appHostedMediaFailureOutcomeWithError for CallSessionEndReason. + */ + public static final CallSessionEndReason APP_HOSTED_MEDIA_FAILURE_OUTCOME_WITH_ERROR + = fromString("appHostedMediaFailureOutcomeWithError"); + + /** + * Static value appHostedMediaFailureOutcomeGracefully for CallSessionEndReason. + */ + public static final CallSessionEndReason APP_HOSTED_MEDIA_FAILURE_OUTCOME_GRACEFULLY + = fromString("appHostedMediaFailureOutcomeGracefully"); + + /** + * Static value handedOverDueToMediaTimeout for CallSessionEndReason. + */ + public static final CallSessionEndReason HANDED_OVER_DUE_TO_MEDIA_TIMEOUT + = fromString("handedOverDueToMediaTimeout"); + + /** + * Static value handedOverDueToAudioStreamFailure for CallSessionEndReason. + */ + public static final CallSessionEndReason HANDED_OVER_DUE_TO_AUDIO_STREAM_FAILURE + = fromString("handedOverDueToAudioStreamFailure"); + + /** + * Static value speechRecognitionSessionNonRetriableError for CallSessionEndReason. + */ + public static final CallSessionEndReason SPEECH_RECOGNITION_SESSION_NON_RETRIABLE_ERROR + = fromString("speechRecognitionSessionNonRetriableError"); + + /** + * Static value speechRecognitionSessionRetriableErrorMaxRetryCountReached for CallSessionEndReason. + */ + public static final CallSessionEndReason SPEECH_RECOGNITION_SESSION_RETRIABLE_ERROR_MAX_RETRY_COUNT_REACHED + = fromString("speechRecognitionSessionRetriableErrorMaxRetryCountReached"); + + /** + * Static value handedOverDueToChunkCreationFailure for CallSessionEndReason. + */ + public static final CallSessionEndReason HANDED_OVER_DUE_TO_CHUNK_CREATION_FAILURE + = fromString("handedOverDueToChunkCreationFailure"); + + /** + * Static value chunkCreationFailed for CallSessionEndReason. + */ + public static final CallSessionEndReason CHUNK_CREATION_FAILED = fromString("chunkCreationFailed"); + + /** + * Static value handedOverDueToProcessingTimeout for CallSessionEndReason. + */ + public static final CallSessionEndReason HANDED_OVER_DUE_TO_PROCESSING_TIMEOUT + = fromString("handedOverDueToProcessingTimeout"); + + /** + * Static value processingTimeout for CallSessionEndReason. + */ + public static final CallSessionEndReason PROCESSING_TIMEOUT = fromString("processingTimeout"); + + /** + * Static value transcriptObjectCreationFailed for CallSessionEndReason. + */ + public static final CallSessionEndReason TRANSCRIPT_OBJECT_CREATION_FAILED + = fromString("transcriptObjectCreationFailed"); + + /** + * Creates a new instance of CallSessionEndReason value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public CallSessionEndReason() { + } + + /** + * Creates or finds a CallSessionEndReason from its string representation. + * + * @param name a name to look for. + * @return the corresponding CallSessionEndReason. + */ + public static CallSessionEndReason fromString(String name) { + return fromString(name, CallSessionEndReason.class); + } + + /** + * Gets known CallSessionEndReason values. + * + * @return known CallSessionEndReason values. + */ + public static Collection values() { + return values(CallSessionEndReason.class); + } +} diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/ChunkEndReason.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/ChunkEndReason.java new file mode 100644 index 000000000000..de4b5cfc84d7 --- /dev/null +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/ChunkEndReason.java @@ -0,0 +1,66 @@ +// 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 java.util.Collection; + +/** + * Reason this chunk ended. + */ +public final class ChunkEndReason extends ExpandableStringEnum { + /** + * Static value chunkIsBeingRecorded for ChunkEndReason. + */ + public static final ChunkEndReason CHUNK_IS_BEING_RECORDED = fromString("chunkIsBeingRecorded"); + + /** + * Static value sessionEnded for ChunkEndReason. + */ + public static final ChunkEndReason SESSION_ENDED = fromString("sessionEnded"); + + /** + * Static value chunkMaximumSizeExceeded for ChunkEndReason. + */ + public static final ChunkEndReason CHUNK_MAXIMUM_SIZE_EXCEEDED = fromString("chunkMaximumSizeExceeded"); + + /** + * Static value chunkMaximumTimeExceeded for ChunkEndReason. + */ + public static final ChunkEndReason CHUNK_MAXIMUM_TIME_EXCEEDED = fromString("chunkMaximumTimeExceeded"); + + /** + * Static value chunkUploadFailure for ChunkEndReason. + */ + public static final ChunkEndReason CHUNK_UPLOAD_FAILURE = fromString("chunkUploadFailure"); + + /** + * Creates a new instance of ChunkEndReason value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public ChunkEndReason() { + } + + /** + * Creates or finds a ChunkEndReason from its string representation. + * + * @param name a name to look for. + * @return the corresponding ChunkEndReason. + */ + public static ChunkEndReason fromString(String name) { + return fromString(name, ChunkEndReason.class); + } + + /** + * Gets known ChunkEndReason values. + * + * @return known ChunkEndReason values. + */ + public static Collection values() { + return values(ChunkEndReason.class); + } +} diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/Error.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/Error.java new file mode 100644 index 000000000000..7fd4d787da01 --- /dev/null +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/Error.java @@ -0,0 +1,141 @@ +// 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.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Error details. + */ +@Fluent +public final class Error implements JsonSerializable { + /* + * Error code + */ + private String code; + + /* + * Error message + */ + private String message; + + /* + * Inner error details + */ + private Error innerError; + + /** + * Creates an instance of Error class. + */ + public Error() { + } + + /** + * Get the code property: Error code. + * + * @return the code value. + */ + public String getCode() { + return this.code; + } + + /** + * Set the code property: Error code. + * + * @param code the code value to set. + * @return the Error object itself. + */ + public Error setCode(String code) { + this.code = code; + return this; + } + + /** + * Get the message property: Error message. + * + * @return the message value. + */ + public String getMessage() { + return this.message; + } + + /** + * Set the message property: Error message. + * + * @param message the message value to set. + * @return the Error object itself. + */ + public Error setMessage(String message) { + this.message = message; + return this; + } + + /** + * Get the innerError property: Inner error details. + * + * @return the innerError value. + */ + public Error getInnerError() { + return this.innerError; + } + + /** + * Set the innerError property: Inner error details. + * + * @param innerError the innerError value to set. + * @return the Error object itself. + */ + public Error setInnerError(Error innerError) { + this.innerError = innerError; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("code", this.code); + jsonWriter.writeStringField("message", this.message); + jsonWriter.writeJsonField("innerError", this.innerError); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of Error from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of Error 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 Error. + */ + public static Error fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Error deserializedError = new Error(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("code".equals(fieldName)) { + deserializedError.code = reader.getString(); + } else if ("message".equals(fieldName)) { + deserializedError.message = reader.getString(); + } else if ("innerError".equals(fieldName)) { + deserializedError.innerError = Error.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedError; + }); + } +} diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/HoldAudioCompleted.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/HoldAudioCompleted.java index ad5dd13f01a1..d4a3a740d3ae 100644 --- a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/HoldAudioCompleted.java +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/HoldAudioCompleted.java @@ -12,7 +12,7 @@ import java.io.IOException; /** - * The HoldAudioCompleted model. + * Hold Audio Completed event. */ @Fluent public final class HoldAudioCompleted implements JsonSerializable { diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/PlayOptionsInternal.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/PlayOptionsInternal.java index f5060c8ee2b4..3270d9e10960 100644 --- a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/PlayOptionsInternal.java +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/PlayOptionsInternal.java @@ -26,6 +26,11 @@ public final class PlayOptionsInternal implements JsonSerializable { + /* + * Chunk document id + */ + private String documentId; + + /* + * Chunks order in a multi chunk recording + */ + private Integer index; + + /* + * Reason this chunk ended + */ + private ChunkEndReason endReason; + + /* + * Location of the chunk + */ + private String contentLocation; + + /* + * Location of chunk metadata + */ + private String metadataLocation; + + /* + * Callback for deleting chunk + */ + private String deleteLocation; + + /** + * Creates an instance of RecordingChunkStorageInfo class. + */ + public RecordingChunkStorageInfo() { + } + + /** + * Get the documentId property: Chunk document id. + * + * @return the documentId value. + */ + public String getDocumentId() { + return this.documentId; + } + + /** + * Set the documentId property: Chunk document id. + * + * @param documentId the documentId value to set. + * @return the RecordingChunkStorageInfo object itself. + */ + public RecordingChunkStorageInfo setDocumentId(String documentId) { + this.documentId = documentId; + return this; + } + + /** + * Get the index property: Chunks order in a multi chunk recording. + * + * @return the index value. + */ + public Integer getIndex() { + return this.index; + } + + /** + * Set the index property: Chunks order in a multi chunk recording. + * + * @param index the index value to set. + * @return the RecordingChunkStorageInfo object itself. + */ + public RecordingChunkStorageInfo setIndex(Integer index) { + this.index = index; + return this; + } + + /** + * Get the endReason property: Reason this chunk ended. + * + * @return the endReason value. + */ + public ChunkEndReason getEndReason() { + return this.endReason; + } + + /** + * Set the endReason property: Reason this chunk ended. + * + * @param endReason the endReason value to set. + * @return the RecordingChunkStorageInfo object itself. + */ + public RecordingChunkStorageInfo setEndReason(ChunkEndReason endReason) { + this.endReason = endReason; + return this; + } + + /** + * Get the contentLocation property: Location of the chunk. + * + * @return the contentLocation value. + */ + public String getContentLocation() { + return this.contentLocation; + } + + /** + * Set the contentLocation property: Location of the chunk. + * + * @param contentLocation the contentLocation value to set. + * @return the RecordingChunkStorageInfo object itself. + */ + public RecordingChunkStorageInfo setContentLocation(String contentLocation) { + this.contentLocation = contentLocation; + return this; + } + + /** + * Get the metadataLocation property: Location of chunk metadata. + * + * @return the metadataLocation value. + */ + public String getMetadataLocation() { + return this.metadataLocation; + } + + /** + * Set the metadataLocation property: Location of chunk metadata. + * + * @param metadataLocation the metadataLocation value to set. + * @return the RecordingChunkStorageInfo object itself. + */ + public RecordingChunkStorageInfo setMetadataLocation(String metadataLocation) { + this.metadataLocation = metadataLocation; + return this; + } + + /** + * Get the deleteLocation property: Callback for deleting chunk. + * + * @return the deleteLocation value. + */ + public String getDeleteLocation() { + return this.deleteLocation; + } + + /** + * Set the deleteLocation property: Callback for deleting chunk. + * + * @param deleteLocation the deleteLocation value to set. + * @return the RecordingChunkStorageInfo object itself. + */ + public RecordingChunkStorageInfo setDeleteLocation(String deleteLocation) { + this.deleteLocation = deleteLocation; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("documentId", this.documentId); + jsonWriter.writeNumberField("index", this.index); + jsonWriter.writeStringField("endReason", this.endReason == null ? null : this.endReason.toString()); + jsonWriter.writeStringField("contentLocation", this.contentLocation); + jsonWriter.writeStringField("metadataLocation", this.metadataLocation); + jsonWriter.writeStringField("deleteLocation", this.deleteLocation); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of RecordingChunkStorageInfo from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of RecordingChunkStorageInfo 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 RecordingChunkStorageInfo. + */ + public static RecordingChunkStorageInfo fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + RecordingChunkStorageInfo deserializedRecordingChunkStorageInfo = new RecordingChunkStorageInfo(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("documentId".equals(fieldName)) { + deserializedRecordingChunkStorageInfo.documentId = reader.getString(); + } else if ("index".equals(fieldName)) { + deserializedRecordingChunkStorageInfo.index = reader.getNullable(JsonReader::getInt); + } else if ("endReason".equals(fieldName)) { + deserializedRecordingChunkStorageInfo.endReason = ChunkEndReason.fromString(reader.getString()); + } else if ("contentLocation".equals(fieldName)) { + deserializedRecordingChunkStorageInfo.contentLocation = reader.getString(); + } else if ("metadataLocation".equals(fieldName)) { + deserializedRecordingChunkStorageInfo.metadataLocation = reader.getString(); + } else if ("deleteLocation".equals(fieldName)) { + deserializedRecordingChunkStorageInfo.deleteLocation = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedRecordingChunkStorageInfo; + }); + } +} diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/RecordingResultResponse.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/RecordingResultResponse.java new file mode 100644 index 000000000000..a76635d792f3 --- /dev/null +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/RecordingResultResponse.java @@ -0,0 +1,175 @@ +// 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.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.OffsetDateTime; +import java.util.List; + +/** + * Recording result data. + */ +@Immutable +public final class RecordingResultResponse implements JsonSerializable { + /* + * The recordingId property. + */ + private String recordingId; + + /* + * Container for chunks + */ + private RecordingStorageInfo recordingStorageInfo; + + /* + * The errors property. + */ + private List errors; + + /* + * The recordingStartTime property. + */ + private OffsetDateTime recordingStartTime; + + /* + * The recordingDurationMs property. + */ + private Long recordingDurationMs; + + /* + * The sessionEndReason property. + */ + private CallSessionEndReason sessionEndReason; + + /* + * The recordingExpirationTime property. + */ + private OffsetDateTime recordingExpirationTime; + + /** + * Creates an instance of RecordingResultResponse class. + */ + public RecordingResultResponse() { + } + + /** + * Get the recordingId property: The recordingId property. + * + * @return the recordingId value. + */ + public String getRecordingId() { + return this.recordingId; + } + + /** + * Get the recordingStorageInfo property: Container for chunks. + * + * @return the recordingStorageInfo value. + */ + public RecordingStorageInfo getRecordingStorageInfo() { + return this.recordingStorageInfo; + } + + /** + * Get the errors property: The errors property. + * + * @return the errors value. + */ + public List getErrors() { + return this.errors; + } + + /** + * Get the recordingStartTime property: The recordingStartTime property. + * + * @return the recordingStartTime value. + */ + public OffsetDateTime getRecordingStartTime() { + return this.recordingStartTime; + } + + /** + * Get the recordingDurationMs property: The recordingDurationMs property. + * + * @return the recordingDurationMs value. + */ + public Long getRecordingDurationMs() { + return this.recordingDurationMs; + } + + /** + * Get the sessionEndReason property: The sessionEndReason property. + * + * @return the sessionEndReason value. + */ + public CallSessionEndReason getSessionEndReason() { + return this.sessionEndReason; + } + + /** + * Get the recordingExpirationTime property: The recordingExpirationTime property. + * + * @return the recordingExpirationTime value. + */ + public OffsetDateTime getRecordingExpirationTime() { + return this.recordingExpirationTime; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of RecordingResultResponse from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of RecordingResultResponse 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 RecordingResultResponse. + */ + public static RecordingResultResponse fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + RecordingResultResponse deserializedRecordingResultResponse = new RecordingResultResponse(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("recordingId".equals(fieldName)) { + deserializedRecordingResultResponse.recordingId = reader.getString(); + } else if ("recordingStorageInfo".equals(fieldName)) { + deserializedRecordingResultResponse.recordingStorageInfo = RecordingStorageInfo.fromJson(reader); + } else if ("errors".equals(fieldName)) { + List errors = reader.readArray(reader1 -> Error.fromJson(reader1)); + deserializedRecordingResultResponse.errors = errors; + } else if ("recordingStartTime".equals(fieldName)) { + deserializedRecordingResultResponse.recordingStartTime + = reader.getNullable(nonNullReader -> OffsetDateTime.parse(nonNullReader.getString())); + } else if ("recordingDurationMs".equals(fieldName)) { + deserializedRecordingResultResponse.recordingDurationMs = reader.getNullable(JsonReader::getLong); + } else if ("sessionEndReason".equals(fieldName)) { + deserializedRecordingResultResponse.sessionEndReason + = CallSessionEndReason.fromString(reader.getString()); + } else if ("recordingExpirationTime".equals(fieldName)) { + deserializedRecordingResultResponse.recordingExpirationTime + = reader.getNullable(nonNullReader -> OffsetDateTime.parse(nonNullReader.getString())); + } else { + reader.skipChildren(); + } + } + + return deserializedRecordingResultResponse; + }); + } +} diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/RecordingStorageInfo.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/RecordingStorageInfo.java new file mode 100644 index 000000000000..581e9e8bfdd4 --- /dev/null +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/implementation/models/RecordingStorageInfo.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.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; + +/** + * Container for chunks. + */ +@Fluent +public final class RecordingStorageInfo implements JsonSerializable { + /* + * Collection of {Microsoft.Skype.Platform.ExecutionAgent.Azure.Communication.Service.ServerCalling.Content.Contracts.ALPHA4_2024_09_01_preview.Models.RecordingChunkStorageInfo} + */ + private List recordingChunks; + + /** + * Creates an instance of RecordingStorageInfo class. + */ + public RecordingStorageInfo() { + } + + /** + * Get the recordingChunks property: Collection of + * {Microsoft.Skype.Platform.ExecutionAgent.Azure.Communication.Service.ServerCalling.Content.Contracts.ALPHA4_2024_09_01_preview.Models.RecordingChunkStorageInfo}. + * + * @return the recordingChunks value. + */ + public List getRecordingChunks() { + return this.recordingChunks; + } + + /** + * Set the recordingChunks property: Collection of + * {Microsoft.Skype.Platform.ExecutionAgent.Azure.Communication.Service.ServerCalling.Content.Contracts.ALPHA4_2024_09_01_preview.Models.RecordingChunkStorageInfo}. + * + * @param recordingChunks the recordingChunks value to set. + * @return the RecordingStorageInfo object itself. + */ + public RecordingStorageInfo setRecordingChunks(List recordingChunks) { + this.recordingChunks = recordingChunks; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("recordingChunks", this.recordingChunks, + (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of RecordingStorageInfo from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of RecordingStorageInfo 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 RecordingStorageInfo. + */ + public static RecordingStorageInfo fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + RecordingStorageInfo deserializedRecordingStorageInfo = new RecordingStorageInfo(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("recordingChunks".equals(fieldName)) { + List recordingChunks + = reader.readArray(reader1 -> RecordingChunkStorageInfo.fromJson(reader1)); + deserializedRecordingStorageInfo.recordingChunks = recordingChunks; + } else { + reader.skipChildren(); + } + } + + return deserializedRecordingStorageInfo; + }); + } +} diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/CallIntelligenceOptions.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/CallIntelligenceOptions.java index 8a17215b4930..49b91b15fd26 100644 --- a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/CallIntelligenceOptions.java +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/CallIntelligenceOptions.java @@ -16,6 +16,11 @@ public final class CallIntelligenceOptions { */ private String cognitiveServicesEndpoint; + /** + * A backup endpoint URL of the Azure Cognitive Services resource attached + */ + private String backupCognitiveServicesEndpoint; + /** * Creates an instance of {@link CallIntelligenceOptions}. */ @@ -37,11 +42,32 @@ public String getCognitiveServicesEndpoint() { * attached. * * @param cognitiveServicesEndpoint the cognitiveServicesEndpoint value to set. - * @return the CreateGroupCallOptions object itself. + * @return the CallIntelligenceOptions object itself. */ public CallIntelligenceOptions setCognitiveServicesEndpoint(String cognitiveServicesEndpoint) { this.cognitiveServicesEndpoint = cognitiveServicesEndpoint; return this; } + /** + * Get the backupCognitiveServicesEndpoint property: A backup endpoint URL of the Azure Cognitive Services resource + * attached. + * + * @return the backupCognitiveServicesEndpoint value. + */ + public String getBackupCognitiveServicesEndpoint() { + return this.backupCognitiveServicesEndpoint; + } + + /** + * Set the backupCognitiveServicesEndpoint property: A backup endpoint URL of the Azure Cognitive Services resource + * attached. + * + * @param backupCognitiveServicesEndpoint the backupCognitiveServicesEndpoint value to set. + * @return the CallIntelligenceOptions object itself. + */ + public CallIntelligenceOptions setBackupCognitiveServicesEndpoint(String backupCognitiveServicesEndpoint) { + this.backupCognitiveServicesEndpoint = backupCognitiveServicesEndpoint; + return this; + } } diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/PlayOptions.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/PlayOptions.java index 0f89fb69e981..f53db7ff5f63 100644 --- a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/PlayOptions.java +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/PlayOptions.java @@ -3,12 +3,12 @@ package com.azure.communication.callautomation.models; -import com.azure.communication.common.CommunicationIdentifier; -import com.azure.core.annotation.Fluent; - import java.util.ArrayList; import java.util.List; +import com.azure.communication.common.CommunicationIdentifier; +import com.azure.core.annotation.Fluent; + /** The PlayOptions model. */ @Fluent public final class PlayOptions { @@ -39,6 +39,11 @@ public final class PlayOptions { */ private String operationCallbackUrl; + /* + * If set, hold audio will be interrupted, then this request will be played, and then the hold audio will be resumed. + */ + private Boolean interruptHoldAudio; + /** * Constructor * @param playSources A List of {@link PlaySource} representing the sources to play. @@ -138,4 +143,24 @@ public PlayOptions setOperationCallbackUrl(String operationCallbackUrl) { this.operationCallbackUrl = operationCallbackUrl; return this; } + + /** + * Get the interruptHoldAudio property. + * + * @return the interruptHoldAudio value. + */ + public Boolean isInterruptHoldAudio() { + return this.interruptHoldAudio; + } + + /** + * Set the interruptHoldAudio property + * + * @param interruptHoldAudio the interruptHoldAudio value to set. + * @return the PlayOptions object itself. + */ + public PlayOptions setInterruptHoldAudio(Boolean interruptHoldAudio) { + this.interruptHoldAudio = interruptHoldAudio; + return this; + } } diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/StartRecordingOptions.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/StartRecordingOptions.java index e0b92ff69356..ee0159146a71 100644 --- a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/StartRecordingOptions.java +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/StartRecordingOptions.java @@ -3,12 +3,11 @@ package com.azure.communication.callautomation.models; +import java.util.List; + import com.azure.communication.common.CommunicationIdentifier; import com.azure.core.annotation.Fluent; -import java.util.List; -import java.util.Objects; - /** * The options for creating a call. */ @@ -19,6 +18,8 @@ public final class StartRecordingOptions { */ private final CallLocator callLocator; + private final String callConnectionId; + private String recordingStateCallbackUrl; private RecordingChannel recordingChannel; @@ -41,8 +42,18 @@ public final class StartRecordingOptions { * @param callLocator Either a {@link GroupCallLocator} or {@link ServerCallLocator} for locating the call. */ public StartRecordingOptions(CallLocator callLocator) { - Objects.requireNonNull(callLocator, "'callLocator' cannot be null."); this.callLocator = callLocator; + this.callConnectionId = null; + } + + /** + * Constructor + * + * @param callConnectionId the ID of the call connection. + */ + public StartRecordingOptions(String callConnectionId) { + this.callConnectionId = callConnectionId; + this.callLocator = null; } /** @@ -54,6 +65,15 @@ public CallLocator getCallLocator() { return this.callLocator; } + /** + * Get callConnectionId for the call + * + * @return callConnectionId for the call + */ + public String getCallConnectionId() { + return callConnectionId; + } + /** * Uri to send state change callbacks. * diff --git a/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/events/StartRecordingFailed.java b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/events/StartRecordingFailed.java new file mode 100644 index 000000000000..39616d313e21 --- /dev/null +++ b/sdk/communication/azure-communication-callautomation/src/main/java/com/azure/communication/callautomation/models/events/StartRecordingFailed.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 java.io.IOException; + +import com.azure.core.annotation.Immutable; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; + +/** + * The StartRecordingFailed model. + */ +@Immutable +public final class StartRecordingFailed extends CallAutomationEventBase { + + private StartRecordingFailed() { + + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + super.writeFields(jsonWriter); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of StartRecordingFailed from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of StartRecordingFailed 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 StartRecordingFailed. + */ + public static StartRecordingFailed fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + final StartRecordingFailed event = new StartRecordingFailed(); + while (jsonReader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if (!event.readField(fieldName, reader)) { + reader.skipChildren(); + } + } + return event; + }); + } +} 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 e8ad1c76de3d..013bc0aa6260 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 @@ -14,6 +14,7 @@ import com.azure.communication.callautomation.models.events.CallConnected; import com.azure.communication.callautomation.models.events.ContinuousDtmfRecognitionStopped; import com.azure.communication.callautomation.models.events.PlayCompleted; +import com.azure.communication.callautomation.models.events.PlayStarted; import com.azure.communication.callautomation.models.events.SendDtmfTonesCompleted; import com.azure.communication.common.CommunicationIdentifier; import com.azure.communication.common.CommunicationUserIdentifier; @@ -27,6 +28,7 @@ import com.azure.communication.callautomation.models.MediaStreamingContent; import com.azure.communication.callautomation.models.MediaStreamingOptions; import com.azure.communication.callautomation.models.MediaStreamingTransport; +import com.azure.communication.callautomation.models.PlayOptions; import com.azure.communication.callautomation.models.TranscriptionOptions; import com.azure.communication.callautomation.models.StartMediaStreamingOptions; import com.azure.communication.callautomation.models.StopMediaStreamingOptions; @@ -61,6 +63,11 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; +import com.azure.communication.callautomation.models.events.HoldAudioResumed; +import com.azure.communication.callautomation.models.events.HoldAudioCompleted; +import com.azure.communication.callautomation.models.events.HoldAudioPaused; +import com.azure.communication.callautomation.models.events.HoldAudioStarted; + public class CallMediaAsyncAutomatedLiveTests extends CallAutomationAutomatedLiveTestBase { @ParameterizedTest @@ -1316,4 +1323,137 @@ public void interruptAudioAndAnnounceToholdParticipantInACallTest(HttpClient htt } } } + + @ParameterizedTest + @MethodSource("com.azure.core.test.TestBase#getHttpClients") + @DisabledIfEnvironmentVariable( + named = "SKIP_LIVE_TEST", + matches = "(?i)(true)", + disabledReason = "Requires environment to be set up") + public void playMultipleFileSourcesWhenParticipantOnHoldTest(HttpClient httpClient) { + /* Test case: ACS to ACS call + * 1. create a CallAutomationClient. + * 2. create a call from source to one ACS target. + * 3. get updated call properties and check for the connected state. + * 4. hold the participant + * 5. play a media to target participant with mutiple file prompts + * 6. unhold the participant + * 7. hang up the call. + */ + + CommunicationIdentityAsyncClient identityAsyncClient + = getCommunicationIdentityClientUsingConnectionString(httpClient) + .addPolicy((context, next) -> logHeaders("playMultipleFileSourcesWhenParticipantOnHoldTest", next)) + .buildAsyncClient(); + + List callDestructors = new ArrayList<>(); + + try { + // create caller and receiver + CommunicationUserIdentifier caller = identityAsyncClient.createUser().block(); + CommunicationIdentifier receiver = identityAsyncClient.createUser().block(); + + CallAutomationAsyncClient callerAsyncClient = getCallAutomationClientUsingConnectionString(httpClient) + .addPolicy((context, next) -> logHeaders("playMultipleFileSourcesWhenParticipantOnHoldTest", next)) + .sourceIdentity(caller) + .buildAsyncClient(); + + // Create call automation client for receivers. + CallAutomationAsyncClient receiverAsyncClient = getCallAutomationClientUsingConnectionString(httpClient) + .addPolicy((context, next) -> logHeaders("playMultipleFileSourcesWhenParticipantOnHoldTest", next)) + .buildAsyncClient(); + + String uniqueId = serviceBusWithNewCall(caller, receiver); + + // create a call + List targets = Collections.singletonList(receiver); + CreateGroupCallOptions createCallOptions + = new CreateGroupCallOptions(targets, DISPATCHER_CALLBACK + String.format("?q=%s", uniqueId)); + Response createCallResultResponse + = callerAsyncClient.createGroupCallWithResponse(createCallOptions).block(); + assertNotNull(createCallResultResponse); + CreateCallResult createCallResult = createCallResultResponse.getValue(); + assertNotNull(createCallResult); + assertNotNull(createCallResult.getCallConnectionProperties()); + String callerConnectionId = createCallResult.getCallConnectionProperties().getCallConnectionId(); + assertNotNull(callerConnectionId); + + // wait for the incomingCallContext + String incomingCallContext = waitForIncomingCallContext(uniqueId, Duration.ofSeconds(10)); + assertNotNull(incomingCallContext); + + // answer the call + AnswerCallOptions answerCallOptions + = new AnswerCallOptions(incomingCallContext, DISPATCHER_CALLBACK + String.format("?q=%s", uniqueId)); + AnswerCallResult answerCallResult + = Objects.requireNonNull(receiverAsyncClient.answerCallWithResponse(answerCallOptions).block()) + .getValue(); + assertNotNull(answerCallResult); + assertNotNull(answerCallResult.getCallConnectionAsync()); + assertNotNull(answerCallResult.getCallConnectionProperties()); + callDestructors.add(answerCallResult.getCallConnectionAsync()); + + // wait for callConnected + CallConnected callConnected = waitForEvent(CallConnected.class, callerConnectionId, Duration.ofSeconds(10)); + assertNotNull(callConnected); + + // hold the participant + CallMediaAsync callMediaAsync = createCallResult.getCallConnectionAsync().getCallMediaAsync(); + PlaySource holdPlaySource = new FileSource().setUrl(MEDIA_SOURCE); + callMediaAsync.hold(receiver, holdPlaySource).block(); + sleepIfRunningAgainstService(3000); + HoldAudioStarted holdAudioStarted + = waitForEvent(HoldAudioStarted.class, callerConnectionId, Duration.ofSeconds(20)); + assertNotNull(holdAudioStarted); + + CallConnectionAsync callConnectionAsync = callerAsyncClient.getCallConnectionAsync(callerConnectionId); + CallParticipant participantResult = callConnectionAsync.getParticipant(receiver).block(); + assertNotNull(participantResult); + assertTrue(participantResult.isOnHold()); + + // Assert multiple File Sources + List playFileSources = new ArrayList(); + playFileSources.add(new FileSource().setUrl(MEDIA_SOURCE)); + playFileSources.add(new FileSource().setUrl(MEDIA_SOURCE)); + PlayOptions playOptions = new PlayOptions(playFileSources, targets); + playOptions.setInterruptHoldAudio(true); + // Play multiple files sources + callMediaAsync.playWithResponse(playOptions).block(); + HoldAudioPaused holdAudioPaused + = waitForEvent(HoldAudioPaused.class, callerConnectionId, Duration.ofSeconds(20)); + assertNotNull(holdAudioPaused); + + PlayStarted playStarted = waitForEvent(PlayStarted.class, callerConnectionId, Duration.ofSeconds(20)); + assertNotNull(playStarted); + + PlayCompleted playCompleted = waitForEvent(PlayCompleted.class, callerConnectionId, Duration.ofSeconds(20)); + assertNotNull(playCompleted); + + HoldAudioResumed holdAudioResumed + = waitForEvent(HoldAudioResumed.class, callerConnectionId, Duration.ofSeconds(20)); + assertNotNull(holdAudioResumed); + + // unhold the participant + callMediaAsync.unhold(receiver).block(); + HoldAudioCompleted holdAudioCompleted + = waitForEvent(HoldAudioCompleted.class, callerConnectionId, Duration.ofSeconds(20)); + assertNotNull(holdAudioCompleted); + + sleepIfRunningAgainstService(3000); + participantResult = callConnectionAsync.getParticipant(receiver).block(); + assertNotNull(participantResult); + assertFalse(participantResult.isOnHold()); + } catch (Exception ex) { + fail("Unexpected exception received", ex); + } finally { + if (!callDestructors.isEmpty()) { + try { + callDestructors.forEach(callConnection -> callConnection.hangUpWithResponse(true).block()); + } catch (Exception ignored) { + // Some call might have been terminated during the test, and it will cause exceptions here. + // Do nothing and iterate to next call connection. + } + } + } + } } diff --git a/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallRecordingAsyncUnitTests.java b/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallRecordingAsyncUnitTests.java index 90daf237cc3c..363bcea85597 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallRecordingAsyncUnitTests.java +++ b/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallRecordingAsyncUnitTests.java @@ -45,6 +45,25 @@ public void recordingOperationsTest() { assertThrows(HttpResponseException.class, () -> callRecording.getState(RECORDING_ID).block()); } + @Test + public void recordingOperationsWithCallConnectionIdTest() { + CallAutomationAsyncClient callingServerClient + = CallAutomationUnitTestBase.getCallAutomationAsyncClient(recordingOperationsResponses); + callRecording = callingServerClient.getCallRecordingAsync(); + + validateRecordingState( + callRecording.start( + new StartRecordingOptions(CALL_CONNECTION_ID).setRecordingStateCallbackUrl("https://localhost/")), + RecordingState.ACTIVE); + + validateOperationWithRecordingState(callRecording.pause(RECORDING_ID), RecordingState.INACTIVE); + + validateOperationWithRecordingState(callRecording.resume(RECORDING_ID), RecordingState.ACTIVE); + + validateOperation(callRecording.stop(RECORDING_ID)); + assertThrows(HttpResponseException.class, () -> callRecording.getState(RECORDING_ID).block()); + } + private void validateRecordingState(Publisher publisher, RecordingState status) { StepVerifier.create(publisher) .consumeNextWith(recordingStateResponse -> validateRecording(recordingStateResponse, status)) 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 7dd21d7fb41b..2bdb35ea314f 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 org.junit.jupiter.api.Disabled; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -214,4 +215,92 @@ public void createACSCallUnmixedAudioAffinityTest(HttpClient httpClient) { fail("Unexpected exception received", ex); } } + + @Disabled("This test is failing in the pipeline, needs to be fixed.") + @ParameterizedTest + @MethodSource("com.azure.core.test.TestBase#getHttpClients") + public void createACSCallAndStartRecordingWithCallConnectionIdTest(HttpClient httpClient) { + /* Test case: ACS to ACS call + * 1. create a CallAutomationClient. + * 2. create a call from source to one ACS target. + * 3. get updated call properties and check for the connected state. + * 4. start recording with callConnectionId and the call without channel affinity + * 5. stop recording the call + * 6. hang up the call. + * 7. once call is hung up, verify disconnected event + */ + CommunicationIdentityClient communicationIdentityClient + = getCommunicationIdentityClientUsingConnectionString(httpClient).buildClient(); + + String callConnectionId = ""; + try { + // Create caller and receiver + CommunicationUserIdentifier source = communicationIdentityClient.createUser(); + CommunicationUserIdentifier target = communicationIdentityClient.createUser(); + + // Create call automation client and use source as the caller. + CallAutomationClient callerClient = getCallAutomationClientUsingConnectionString(httpClient) + .addPolicy((context, next) -> logHeaders("recordingOperations", next)) + .sourceIdentity(source) + .buildClient(); + + // Create call automation client for receivers. + CallAutomationClient receiverClient = getCallAutomationClientUsingConnectionString(httpClient) + .addPolicy((context, next) -> logHeaders("recordingOperations", next)) + .buildClient(); + + // setup service bus + String uniqueId = serviceBusWithNewCall(source, target); + + // create call and assert response + CreateGroupCallOptions createCallOptions = new CreateGroupCallOptions(Arrays.asList(target), + String.format("%s?q=%s", DISPATCHER_CALLBACK, uniqueId)); + CreateCallResult createCallResult + = callerClient.createGroupCallWithResponse(createCallOptions, null).getValue(); + callConnectionId = createCallResult.getCallConnectionProperties().getCallConnectionId(); + assertNotNull(callConnectionId); + + // wait for incoming call context + String incomingCallContext = waitForIncomingCallContext(uniqueId, Duration.ofSeconds(10)); + assertNotNull(incomingCallContext); + + // answer the call + AnswerCallOptions answerCallOptions = new AnswerCallOptions(incomingCallContext, DISPATCHER_CALLBACK); + AnswerCallResult answerCallResult + = receiverClient.answerCallWithResponse(answerCallOptions, null).getValue(); + assertNotNull(answerCallResult); + + // wait for callConnected + CallConnected callConnected = waitForEvent(CallConnected.class, callConnectionId, Duration.ofSeconds(10)); + assertNotNull(callConnected); + + // get properties + CallConnectionProperties callConnectionProperties + = createCallResult.getCallConnection().getCallProperties(); + assertEquals(CallConnectionState.CONNECTED, callConnectionProperties.getCallConnectionState()); + + // start recording + RecordingStateResult recordingStateResult = callerClient.getCallRecording() + .start(new StartRecordingOptions(callConnectionId).setRecordingChannel(RecordingChannel.UNMIXED) + .setRecordingContent(RecordingContent.AUDIO) + .setRecordingFormat(RecordingFormat.WAV) + .setRecordingStateCallbackUrl(DISPATCHER_CALLBACK)); + + assertNotNull(recordingStateResult.getRecordingId()); + + // stop recording + callerClient.getCallRecording().stop(recordingStateResult.getRecordingId()); + + // hangup + if (!callConnectionId.isEmpty()) { + CallConnection callConnection = callerClient.getCallConnection(callConnectionId); + callConnection.hangUp(true); + CallDisconnected callDisconnected + = waitForEvent(CallDisconnected.class, callConnectionId, Duration.ofSeconds(10)); + assertNotNull(callDisconnected); + } + } catch (Exception ex) { + fail("Unexpected exception received", ex); + } + } } diff --git a/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallRecordingUnitTestBase.java b/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallRecordingUnitTestBase.java index f567e8a82ac8..ecaae567aa68 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallRecordingUnitTestBase.java +++ b/sdk/communication/azure-communication-callautomation/src/test/java/com/azure/communication/callautomation/CallRecordingUnitTestBase.java @@ -20,6 +20,7 @@ public class CallRecordingUnitTestBase { = "aHR0cHM6Ly9jb252LXVzd2UtMDguY29udi5za3lwZS5jb20vY29udi8tby1FWjVpMHJrS3RFTDBNd0FST1J3P2k9ODgmZT02Mzc1Nzc0MTY4MDc4MjQyOTM"; static final String RECORDING_ID = "recordingId"; + static final String CALL_CONNECTION_ID = "callConnectionId"; private final RecordingStateResponseInternal recordingState = new RecordingStateResponseInternal().setRecordingId(RECORDING_ID); diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/createACSCallAndStartRecordingWithCallConnectionIdTest.json b/sdk/communication/azure-communication-callautomation/src/test/resources/createACSCallAndStartRecordingWithCallConnectionIdTest.json new file mode 100644 index 000000000000..04e7b7d7da7f --- /dev/null +++ b/sdk/communication/azure-communication-callautomation/src/test/resources/createACSCallAndStartRecordingWithCallConnectionIdTest.json @@ -0,0 +1 @@ +["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"11787422-8388-43a2-a1a1-22fa16a870dd\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/08002680-03e9-47de-ba71-201fae0827b3\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"08002680-03e9-47de-ba71-201fae0827b3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"11787422-8388-43a2-a1a1-22fa16a870dd\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-01-30T06:50:22.2551138\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/08002680-03e9-47de-ba71-201fae0827b3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/08002680-03e9-47de-ba71-201fae0827b3\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"08002680-03e9-47de-ba71-201fae0827b3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"11787422-8388-43a2-a1a1-22fa16a870dd\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-01-30T06:50:22.3573445\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/08002680-03e9-47de-ba71-201fae0827b3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/08002680-03e9-47de-ba71-201fae0827b3\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"08002680-03e9-47de-ba71-201fae0827b3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"11787422-8388-43a2-a1a1-22fa16a870dd\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-01-30T06:50:37.8143942\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/08002680-03e9-47de-ba71-201fae0827b3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/08002680-03e9-47de-ba71-201fae0827b3\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":4,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"08002680-03e9-47de-ba71-201fae0827b3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"11787422-8388-43a2-a1a1-22fa16a870dd\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-01-30T06:50:39.9364459\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/08002680-03e9-47de-ba71-201fae0827b3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/08002680-03e9-47de-ba71-201fae0827b3\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":5,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"08002680-03e9-47de-ba71-201fae0827b3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"11787422-8388-43a2-a1a1-22fa16a870dd\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-01-30T06:50:40.3031284\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/08002680-03e9-47de-ba71-201fae0827b3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/08002680-03e9-47de-ba71-201fae0827b3\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":7,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"08002680-03e9-47de-ba71-201fae0827b3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"11787422-8388-43a2-a1a1-22fa16a870dd\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-01-30T06:50:40.6767871\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/08002680-03e9-47de-ba71-201fae0827b3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/08002680-03e9-47de-ba71-201fae0827b3\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":7,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"08002680-03e9-47de-ba71-201fae0827b3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"11787422-8388-43a2-a1a1-22fa16a870dd\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-01-30T06:50:41.0444358\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/08002680-03e9-47de-ba71-201fae0827b3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/08002680-03e9-47de-ba71-201fae0827b3\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":8,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"08002680-03e9-47de-ba71-201fae0827b3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"11787422-8388-43a2-a1a1-22fa16a870dd\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-01-30T06:50:41.4251917\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/08002680-03e9-47de-ba71-201fae0827b3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/08002680-03e9-47de-ba71-201fae0827b3\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":9,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"08002680-03e9-47de-ba71-201fae0827b3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"11787422-8388-43a2-a1a1-22fa16a870dd\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-01-30T06:50:41.8045889\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/08002680-03e9-47de-ba71-201fae0827b3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/08002680-03e9-47de-ba71-201fae0827b3\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":10,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"08002680-03e9-47de-ba71-201fae0827b3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"11787422-8388-43a2-a1a1-22fa16a870dd\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-01-30T06:50:47.0956863\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/08002680-03e9-47de-ba71-201fae0827b3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/08002680-03e9-47de-ba71-201fae0827b3\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":7000,\"message\":\"The conversation has ended. DiagCode: 0#7000.@\"},\"callConnectionId\":\"08002680-03e9-47de-ba71-201fae0827b3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"11787422-8388-43a2-a1a1-22fa16a870dd\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2025-01-30T06:50:51.2057936\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/08002680-03e9-47de-ba71-201fae0827b3\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/createACSCallAndUnmixedAudioTest.json b/sdk/communication/azure-communication-callautomation/src/test/resources/createACSCallAndUnmixedAudioTest.json index c4868990d04e..c619abbdc48e 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/createACSCallAndUnmixedAudioTest.json +++ b/sdk/communication/azure-communication-callautomation/src/test/resources/createACSCallAndUnmixedAudioTest.json @@ -1 +1 @@ -["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"4c3c45d9-0c20-4c81-9bfe-8bb90a11237a\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-d2d8-494a-814b-1b9440b44e3b\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-d2d8-494a-814b-1b9440b44e3b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"4c3c45d9-0c20-4c81-9bfe-8bb90a11237a\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:13:33.7700044\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-d2d8-494a-814b-1b9440b44e3b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-d2d8-494a-814b-1b9440b44e3b\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-d2d8-494a-814b-1b9440b44e3b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"4c3c45d9-0c20-4c81-9bfe-8bb90a11237a\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:13:33.8912226\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-d2d8-494a-814b-1b9440b44e3b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-d2d8-494a-814b-1b9440b44e3b\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-d2d8-494a-814b-1b9440b44e3b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"4c3c45d9-0c20-4c81-9bfe-8bb90a11237a\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:13:39.844094\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-d2d8-494a-814b-1b9440b44e3b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-d2d8-494a-814b-1b9440b44e3b\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":4,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-d2d8-494a-814b-1b9440b44e3b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"4c3c45d9-0c20-4c81-9bfe-8bb90a11237a\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:13:40.0951359\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-d2d8-494a-814b-1b9440b44e3b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-d2d8-494a-814b-1b9440b44e3b\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":7000,\"message\":\"The conversation has ended. DiagCode: 0#7000.@\"},\"callConnectionId\":\"16001e80-d2d8-494a-814b-1b9440b44e3b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"4c3c45d9-0c20-4c81-9bfe-8bb90a11237a\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2024-12-16T17:13:40.194165\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-d2d8-494a-814b-1b9440b44e3b\"}]"] \ No newline at end of file +["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"73078c8e-47d1-4614-9a2e-a0fb0314a2aa\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-f7c7-45e9-b142-a3a205f4a8dd\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-f7c7-45e9-b142-a3a205f4a8dd\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"73078c8e-47d1-4614-9a2e-a0fb0314a2aa\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:11:41.6073482\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-f7c7-45e9-b142-a3a205f4a8dd\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-f7c7-45e9-b142-a3a205f4a8dd\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"00002680-f7c7-45e9-b142-a3a205f4a8dd\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"73078c8e-47d1-4614-9a2e-a0fb0314a2aa\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:11:41.6546675\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-f7c7-45e9-b142-a3a205f4a8dd\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-f7c7-45e9-b142-a3a205f4a8dd\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-f7c7-45e9-b142-a3a205f4a8dd\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"73078c8e-47d1-4614-9a2e-a0fb0314a2aa\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:11:48.0723857\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-f7c7-45e9-b142-a3a205f4a8dd\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-f7c7-45e9-b142-a3a205f4a8dd\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":4,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-f7c7-45e9-b142-a3a205f4a8dd\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"73078c8e-47d1-4614-9a2e-a0fb0314a2aa\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:11:48.4456209\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-f7c7-45e9-b142-a3a205f4a8dd\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-f7c7-45e9-b142-a3a205f4a8dd\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":7000,\"message\":\"The conversation has ended. DiagCode: 0#7000.@\"},\"callConnectionId\":\"00002680-f7c7-45e9-b142-a3a205f4a8dd\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"73078c8e-47d1-4614-9a2e-a0fb0314a2aa\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2025-03-05T05:11:48.496922\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-f7c7-45e9-b142-a3a205f4a8dd\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/createACSCallUnmixedAudioAffinityTest.json b/sdk/communication/azure-communication-callautomation/src/test/resources/createACSCallUnmixedAudioAffinityTest.json index fdf905d2150d..7ed0bb528f8a 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/createACSCallUnmixedAudioAffinityTest.json +++ b/sdk/communication/azure-communication-callautomation/src/test/resources/createACSCallUnmixedAudioAffinityTest.json @@ -1 +1 @@ -["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"38bd6b0b-4185-4ce5-8709-88719fc68508\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-2ebf-427e-af33-0768fb7b4e49\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-2ebf-427e-af33-0768fb7b4e49\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"38bd6b0b-4185-4ce5-8709-88719fc68508\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:13:45.8320455\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-2ebf-427e-af33-0768fb7b4e49\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-2ebf-427e-af33-0768fb7b4e49\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-2ebf-427e-af33-0768fb7b4e49\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"38bd6b0b-4185-4ce5-8709-88719fc68508\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:13:45.9617402\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-2ebf-427e-af33-0768fb7b4e49\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-2ebf-427e-af33-0768fb7b4e49\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-2ebf-427e-af33-0768fb7b4e49\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"38bd6b0b-4185-4ce5-8709-88719fc68508\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:13:49.5011436\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-2ebf-427e-af33-0768fb7b4e49\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-2ebf-427e-af33-0768fb7b4e49\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":7000,\"message\":\"The conversation has ended. DiagCode: 0#7000.@\"},\"callConnectionId\":\"16001e80-2ebf-427e-af33-0768fb7b4e49\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"38bd6b0b-4185-4ce5-8709-88719fc68508\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2024-12-16T17:13:49.7627452\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-2ebf-427e-af33-0768fb7b4e49\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-2ebf-427e-af33-0768fb7b4e49\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":4,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-2ebf-427e-af33-0768fb7b4e49\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"38bd6b0b-4185-4ce5-8709-88719fc68508\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:13:49.7576743\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-2ebf-427e-af33-0768fb7b4e49\"}]"] \ No newline at end of file +["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"7d5756d0-129e-4f56-83ef-52bb83957f86\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-367e-4e96-a974-0f74dc9b9665\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-367e-4e96-a974-0f74dc9b9665\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7d5756d0-129e-4f56-83ef-52bb83957f86\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:11:57.8684639\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-367e-4e96-a974-0f74dc9b9665\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-367e-4e96-a974-0f74dc9b9665\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"00002680-367e-4e96-a974-0f74dc9b9665\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7d5756d0-129e-4f56-83ef-52bb83957f86\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:11:57.8684639\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-367e-4e96-a974-0f74dc9b9665\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-367e-4e96-a974-0f74dc9b9665\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-367e-4e96-a974-0f74dc9b9665\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7d5756d0-129e-4f56-83ef-52bb83957f86\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:12:01.858633\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-367e-4e96-a974-0f74dc9b9665\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-367e-4e96-a974-0f74dc9b9665\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":6,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-367e-4e96-a974-0f74dc9b9665\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7d5756d0-129e-4f56-83ef-52bb83957f86\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:12:02.3131944\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-367e-4e96-a974-0f74dc9b9665\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-367e-4e96-a974-0f74dc9b9665\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":7000,\"message\":\"The conversation has ended. DiagCode: 0#7000.@\"},\"callConnectionId\":\"00002680-367e-4e96-a974-0f74dc9b9665\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7d5756d0-129e-4f56-83ef-52bb83957f86\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2025-03-05T05:12:02.5478732\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-367e-4e96-a974-0f74dc9b9665\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndAnswerThenAddParticipantFinallyCancelAddParticipant.json b/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndAnswerThenAddParticipantFinallyCancelAddParticipant.json index 227b7f05238b..c9d2aeac3417 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndAnswerThenAddParticipantFinallyCancelAddParticipant.json +++ b/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndAnswerThenAddParticipantFinallyCancelAddParticipant.json @@ -1 +1 @@ -["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"c238ccb7-9d7c-4ede-b47a-7f3f9b3e30cd\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-07c0-4ac4-8bf9-11fe990fe113\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-07c0-4ac4-8bf9-11fe990fe113\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"c238ccb7-9d7c-4ede-b47a-7f3f9b3e30cd\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:11:01.6259979\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-07c0-4ac4-8bf9-11fe990fe113\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-0c7f-42f5-903c-5256cee158dd\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-0c7f-42f5-903c-5256cee158dd\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"c238ccb7-9d7c-4ede-b47a-7f3f9b3e30cd\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:11:01.6188443\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-0c7f-42f5-903c-5256cee158dd\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-0c7f-42f5-903c-5256cee158dd\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-0c7f-42f5-903c-5256cee158dd\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"c238ccb7-9d7c-4ede-b47a-7f3f9b3e30cd\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:11:01.7614434\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-0c7f-42f5-903c-5256cee158dd\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-07c0-4ac4-8bf9-11fe990fe113\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-07c0-4ac4-8bf9-11fe990fe113\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"c238ccb7-9d7c-4ede-b47a-7f3f9b3e30cd\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:11:01.7852478\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-07c0-4ac4-8bf9-11fe990fe113\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-07c0-4ac4-8bf9-11fe990fe113\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-07c0-4ac4-8bf9-11fe990fe113\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"c238ccb7-9d7c-4ede-b47a-7f3f9b3e30cd\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:11:03.6882129\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-07c0-4ac4-8bf9-11fe990fe113\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-0c7f-42f5-903c-5256cee158dd\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-0c7f-42f5-903c-5256cee158dd\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"c238ccb7-9d7c-4ede-b47a-7f3f9b3e30cd\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:11:03.6962845\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-0c7f-42f5-903c-5256cee158dd\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-07c0-4ac4-8bf9-11fe990fe113\",\"type\":\"Microsoft.Communication.CancelAddParticipantSucceeded\",\"data\":{\"invitationId\":\"a9d7dcef-bc23-4ec6-8af8-ed2c416d9827\",\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":5300,\"message\":\"addParticipants failed for participant 8:acs:6d889502-3d7a-41a8-befa-d21fd80e8767_00000024-7055-3dda-f40f-343a0d000ed0. Underlying reason: The conversation has ended. DiagCode: 0#5300.@\"},\"callConnectionId\":\"16001e80-07c0-4ac4-8bf9-11fe990fe113\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"c238ccb7-9d7c-4ede-b47a-7f3f9b3e30cd\",\"publicEventType\":\"Microsoft.Communication.CancelAddParticipantSucceeded\"},\"time\":\"2024-12-16T17:11:05.6812519\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-07c0-4ac4-8bf9-11fe990fe113\"}]"] \ No newline at end of file +["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"7ebb1af4-7128-484c-a195-84b7dddcf6a5\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-9fe2-4103-a268-f2808d080e57\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-9fe2-4103-a268-f2808d080e57\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7ebb1af4-7128-484c-a195-84b7dddcf6a5\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:07:06.6992364\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-9fe2-4103-a268-f2808d080e57\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-8f91-42e5-bcbf-8ce44bb54de9\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-8f91-42e5-bcbf-8ce44bb54de9\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7ebb1af4-7128-484c-a195-84b7dddcf6a5\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:07:06.7016009\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-8f91-42e5-bcbf-8ce44bb54de9\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-9fe2-4103-a268-f2808d080e57\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"09002680-9fe2-4103-a268-f2808d080e57\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7ebb1af4-7128-484c-a195-84b7dddcf6a5\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:07:06.7022265\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-9fe2-4103-a268-f2808d080e57\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-8f91-42e5-bcbf-8ce44bb54de9\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"09002680-8f91-42e5-bcbf-8ce44bb54de9\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7ebb1af4-7128-484c-a195-84b7dddcf6a5\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:07:06.7716479\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-8f91-42e5-bcbf-8ce44bb54de9\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-9fe2-4103-a268-f2808d080e57\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-9fe2-4103-a268-f2808d080e57\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7ebb1af4-7128-484c-a195-84b7dddcf6a5\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:07:09.2896178\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-9fe2-4103-a268-f2808d080e57\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-8f91-42e5-bcbf-8ce44bb54de9\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-8f91-42e5-bcbf-8ce44bb54de9\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7ebb1af4-7128-484c-a195-84b7dddcf6a5\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:07:09.2896178\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-8f91-42e5-bcbf-8ce44bb54de9\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-8f91-42e5-bcbf-8ce44bb54de9\",\"type\":\"Microsoft.Communication.CancelAddParticipantSucceeded\",\"data\":{\"invitationId\":\"8067ff1e-2472-4db1-bff8-67a63e6c7ab2\",\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":5300,\"message\":\"addParticipants failed for participant 8:acs:6d889502-3d7a-41a8-befa-d21fd80e8767_00000026-0494-d3bb-85f4-343a0d0061cb. Underlying reason: The conversation has ended. DiagCode: 0#5300.@\"},\"callConnectionId\":\"09002680-8f91-42e5-bcbf-8ce44bb54de9\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7ebb1af4-7128-484c-a195-84b7dddcf6a5\",\"publicEventType\":\"Microsoft.Communication.CancelAddParticipantSucceeded\"},\"time\":\"2025-03-05T05:07:11.4374908\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-8f91-42e5-bcbf-8ce44bb54de9\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndAnswerThenAddParticipantFinallyRemoveParticipantAutomatedTest.json b/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndAnswerThenAddParticipantFinallyRemoveParticipantAutomatedTest.json index 11d77b77c920..ba726c547c31 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndAnswerThenAddParticipantFinallyRemoveParticipantAutomatedTest.json +++ b/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndAnswerThenAddParticipantFinallyRemoveParticipantAutomatedTest.json @@ -1 +1 @@ -["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"6bafa18b-7cec-49a0-84c7-a74c390d616e\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-4bc5-419f-85ee-fc9fca5bb457\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-4bc5-419f-85ee-fc9fca5bb457\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6bafa18b-7cec-49a0-84c7-a74c390d616e\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:10:50.5400461\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-4bc5-419f-85ee-fc9fca5bb457\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-badb-4b14-91e7-a68b533f1cf5\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-badb-4b14-91e7-a68b533f1cf5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6bafa18b-7cec-49a0-84c7-a74c390d616e\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:10:50.5411923\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-badb-4b14-91e7-a68b533f1cf5\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-badb-4b14-91e7-a68b533f1cf5\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-badb-4b14-91e7-a68b533f1cf5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6bafa18b-7cec-49a0-84c7-a74c390d616e\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:10:50.578893\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-badb-4b14-91e7-a68b533f1cf5\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-4bc5-419f-85ee-fc9fca5bb457\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-4bc5-419f-85ee-fc9fca5bb457\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6bafa18b-7cec-49a0-84c7-a74c390d616e\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:10:50.5974949\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-4bc5-419f-85ee-fc9fca5bb457\"}]","{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"6bafa18b-7cec-49a0-84c7-a74c390d616e\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-f3df-47ed-a14b-173c4ba2f341\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-f3df-47ed-a14b-173c4ba2f341\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6bafa18b-7cec-49a0-84c7-a74c390d616e\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:10:55.003664\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-f3df-47ed-a14b-173c4ba2f341\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-badb-4b14-91e7-a68b533f1cf5\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":4,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-badb-4b14-91e7-a68b533f1cf5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6bafa18b-7cec-49a0-84c7-a74c390d616e\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:10:55.2027457\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-badb-4b14-91e7-a68b533f1cf5\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-f3df-47ed-a14b-173c4ba2f341\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":5,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-f3df-47ed-a14b-173c4ba2f341\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6bafa18b-7cec-49a0-84c7-a74c390d616e\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:10:55.2289615\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-f3df-47ed-a14b-173c4ba2f341\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-4bc5-419f-85ee-fc9fca5bb457\",\"type\":\"Microsoft.Communication.AddParticipantSucceeded\",\"data\":{\"participant\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-4bc5-419f-85ee-fc9fca5bb457\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6bafa18b-7cec-49a0-84c7-a74c390d616e\",\"publicEventType\":\"Microsoft.Communication.AddParticipantSucceeded\"},\"time\":\"2024-12-16T17:10:55.2084574\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-4bc5-419f-85ee-fc9fca5bb457\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-4bc5-419f-85ee-fc9fca5bb457\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":4,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-4bc5-419f-85ee-fc9fca5bb457\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6bafa18b-7cec-49a0-84c7-a74c390d616e\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:10:55.2084574\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-4bc5-419f-85ee-fc9fca5bb457\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-f3df-47ed-a14b-173c4ba2f341\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":6,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-f3df-47ed-a14b-173c4ba2f341\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6bafa18b-7cec-49a0-84c7-a74c390d616e\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:10:55.4859245\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-f3df-47ed-a14b-173c4ba2f341\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-4bc5-419f-85ee-fc9fca5bb457\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":6,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-4bc5-419f-85ee-fc9fca5bb457\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6bafa18b-7cec-49a0-84c7-a74c390d616e\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:10:55.4717699\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-4bc5-419f-85ee-fc9fca5bb457\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-badb-4b14-91e7-a68b533f1cf5\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":6,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-badb-4b14-91e7-a68b533f1cf5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6bafa18b-7cec-49a0-84c7-a74c390d616e\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:10:55.458873\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-badb-4b14-91e7-a68b533f1cf5\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-f3df-47ed-a14b-173c4ba2f341\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":7,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-f3df-47ed-a14b-173c4ba2f341\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6bafa18b-7cec-49a0-84c7-a74c390d616e\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:10:55.7334465\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-f3df-47ed-a14b-173c4ba2f341\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-badb-4b14-91e7-a68b533f1cf5\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":7,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-badb-4b14-91e7-a68b533f1cf5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6bafa18b-7cec-49a0-84c7-a74c390d616e\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:10:55.7233435\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-badb-4b14-91e7-a68b533f1cf5\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-4bc5-419f-85ee-fc9fca5bb457\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":6,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-4bc5-419f-85ee-fc9fca5bb457\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6bafa18b-7cec-49a0-84c7-a74c390d616e\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:10:55.70753\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-4bc5-419f-85ee-fc9fca5bb457\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-f3df-47ed-a14b-173c4ba2f341\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":8,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-f3df-47ed-a14b-173c4ba2f341\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6bafa18b-7cec-49a0-84c7-a74c390d616e\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:10:55.9848427\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-f3df-47ed-a14b-173c4ba2f341\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-4bc5-419f-85ee-fc9fca5bb457\",\"type\":\"Microsoft.Communication.RemoveParticipantSucceeded\",\"data\":{\"participant\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-4bc5-419f-85ee-fc9fca5bb457\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6bafa18b-7cec-49a0-84c7-a74c390d616e\",\"publicEventType\":\"Microsoft.Communication.RemoveParticipantSucceeded\"},\"time\":\"2024-12-16T17:10:55.8380696\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-4bc5-419f-85ee-fc9fca5bb457\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-f3df-47ed-a14b-173c4ba2f341\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":9,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-f3df-47ed-a14b-173c4ba2f341\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6bafa18b-7cec-49a0-84c7-a74c390d616e\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:10:56.2191276\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-f3df-47ed-a14b-173c4ba2f341\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-badb-4b14-91e7-a68b533f1cf5\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":5300,\"message\":\"The conversation has ended. DiagCode: 0#5300.@\"},\"callConnectionId\":\"16001e80-badb-4b14-91e7-a68b533f1cf5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6bafa18b-7cec-49a0-84c7-a74c390d616e\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2024-12-16T17:10:55.848328\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-badb-4b14-91e7-a68b533f1cf5\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-4bc5-419f-85ee-fc9fca5bb457\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":7,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-4bc5-419f-85ee-fc9fca5bb457\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6bafa18b-7cec-49a0-84c7-a74c390d616e\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:10:55.9687711\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-4bc5-419f-85ee-fc9fca5bb457\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-4bc5-419f-85ee-fc9fca5bb457\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":9,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-4bc5-419f-85ee-fc9fca5bb457\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6bafa18b-7cec-49a0-84c7-a74c390d616e\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:10:56.2090286\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-4bc5-419f-85ee-fc9fca5bb457\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-f3df-47ed-a14b-173c4ba2f341\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":10,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-f3df-47ed-a14b-173c4ba2f341\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6bafa18b-7cec-49a0-84c7-a74c390d616e\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:10:56.4702525\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-f3df-47ed-a14b-173c4ba2f341\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-4bc5-419f-85ee-fc9fca5bb457\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":11,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-4bc5-419f-85ee-fc9fca5bb457\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6bafa18b-7cec-49a0-84c7-a74c390d616e\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:10:56.4651793\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-4bc5-419f-85ee-fc9fca5bb457\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-f3df-47ed-a14b-173c4ba2f341\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":11,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-f3df-47ed-a14b-173c4ba2f341\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6bafa18b-7cec-49a0-84c7-a74c390d616e\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:10:56.7062782\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-f3df-47ed-a14b-173c4ba2f341\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-4bc5-419f-85ee-fc9fca5bb457\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":11,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-4bc5-419f-85ee-fc9fca5bb457\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6bafa18b-7cec-49a0-84c7-a74c390d616e\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:10:56.7318557\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-4bc5-419f-85ee-fc9fca5bb457\"}]"] \ No newline at end of file +["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-cb8a-40e5-b225-f5026d191283\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-cb8a-40e5-b225-f5026d191283\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:46.3538501\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-cb8a-40e5-b225-f5026d191283\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-9e6d-44c4-ad76-e627a9bdf093\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-9e6d-44c4-ad76-e627a9bdf093\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:46.3538501\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-9e6d-44c4-ad76-e627a9bdf093\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-cb8a-40e5-b225-f5026d191283\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"09002680-cb8a-40e5-b225-f5026d191283\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:06:46.3850956\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-cb8a-40e5-b225-f5026d191283\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-9e6d-44c4-ad76-e627a9bdf093\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"09002680-9e6d-44c4-ad76-e627a9bdf093\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:06:46.4937384\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-9e6d-44c4-ad76-e627a9bdf093\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-cb8a-40e5-b225-f5026d191283\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-cb8a-40e5-b225-f5026d191283\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:49.3731169\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-cb8a-40e5-b225-f5026d191283\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-9e6d-44c4-ad76-e627a9bdf093\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-9e6d-44c4-ad76-e627a9bdf093\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:49.3731169\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-9e6d-44c4-ad76-e627a9bdf093\"}]","{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-fa2b-429a-bf56-85418121eea5\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"09002680-fa2b-429a-bf56-85418121eea5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:06:51.6893582\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-fa2b-429a-bf56-85418121eea5\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-9e6d-44c4-ad76-e627a9bdf093\",\"type\":\"Microsoft.Communication.AddParticipantSucceeded\",\"data\":{\"participant\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"09002680-9e6d-44c4-ad76-e627a9bdf093\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.AddParticipantSucceeded\"},\"time\":\"2025-03-05T05:06:51.990545\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-9e6d-44c4-ad76-e627a9bdf093\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-fa2b-429a-bf56-85418121eea5\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":5,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-fa2b-429a-bf56-85418121eea5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:52.0374514\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-fa2b-429a-bf56-85418121eea5\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-9e6d-44c4-ad76-e627a9bdf093\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":4,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-9e6d-44c4-ad76-e627a9bdf093\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:51.990545\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-9e6d-44c4-ad76-e627a9bdf093\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-fa2b-429a-bf56-85418121eea5\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":6,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-fa2b-429a-bf56-85418121eea5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:52.425134\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-fa2b-429a-bf56-85418121eea5\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-cb8a-40e5-b225-f5026d191283\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":4,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-cb8a-40e5-b225-f5026d191283\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:51.990545\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-cb8a-40e5-b225-f5026d191283\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-fa2b-429a-bf56-85418121eea5\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":7,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-fa2b-429a-bf56-85418121eea5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:52.8042529\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-fa2b-429a-bf56-85418121eea5\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-cb8a-40e5-b225-f5026d191283\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":8,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-cb8a-40e5-b225-f5026d191283\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:52.3675687\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-cb8a-40e5-b225-f5026d191283\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-fa2b-429a-bf56-85418121eea5\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":8,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-fa2b-429a-bf56-85418121eea5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:53.166662\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-fa2b-429a-bf56-85418121eea5\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-fa2b-429a-bf56-85418121eea5\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":9,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-fa2b-429a-bf56-85418121eea5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:53.5439266\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-fa2b-429a-bf56-85418121eea5\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-9e6d-44c4-ad76-e627a9bdf093\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":8,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-9e6d-44c4-ad76-e627a9bdf093\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:52.3517692\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-9e6d-44c4-ad76-e627a9bdf093\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-fa2b-429a-bf56-85418121eea5\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":10,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-fa2b-429a-bf56-85418121eea5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:53.9278232\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-fa2b-429a-bf56-85418121eea5\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-cb8a-40e5-b225-f5026d191283\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":8,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-cb8a-40e5-b225-f5026d191283\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:52.7371451\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-cb8a-40e5-b225-f5026d191283\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-9e6d-44c4-ad76-e627a9bdf093\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":8,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-9e6d-44c4-ad76-e627a9bdf093\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:52.7409013\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-9e6d-44c4-ad76-e627a9bdf093\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-fa2b-429a-bf56-85418121eea5\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":11,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-fa2b-429a-bf56-85418121eea5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:54.2806653\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-fa2b-429a-bf56-85418121eea5\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-cb8a-40e5-b225-f5026d191283\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":8,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-cb8a-40e5-b225-f5026d191283\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:53.1194526\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-cb8a-40e5-b225-f5026d191283\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-fa2b-429a-bf56-85418121eea5\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":12,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-fa2b-429a-bf56-85418121eea5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:54.6576011\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-fa2b-429a-bf56-85418121eea5\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-9e6d-44c4-ad76-e627a9bdf093\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":8,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-9e6d-44c4-ad76-e627a9bdf093\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:53.1345043\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-9e6d-44c4-ad76-e627a9bdf093\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-fa2b-429a-bf56-85418121eea5\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":13,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-fa2b-429a-bf56-85418121eea5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:55.0292462\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-fa2b-429a-bf56-85418121eea5\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-cb8a-40e5-b225-f5026d191283\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":8,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-cb8a-40e5-b225-f5026d191283\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:53.5124042\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-cb8a-40e5-b225-f5026d191283\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-fa2b-429a-bf56-85418121eea5\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":14,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-fa2b-429a-bf56-85418121eea5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:55.3806345\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-fa2b-429a-bf56-85418121eea5\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-9e6d-44c4-ad76-e627a9bdf093\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":8,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-9e6d-44c4-ad76-e627a9bdf093\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:53.5124042\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-9e6d-44c4-ad76-e627a9bdf093\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-fa2b-429a-bf56-85418121eea5\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":15,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-fa2b-429a-bf56-85418121eea5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:55.7417547\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-fa2b-429a-bf56-85418121eea5\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-9e6d-44c4-ad76-e627a9bdf093\",\"type\":\"Microsoft.Communication.RemoveParticipantSucceeded\",\"data\":{\"participant\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"09002680-9e6d-44c4-ad76-e627a9bdf093\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.RemoveParticipantSucceeded\"},\"time\":\"2025-03-05T05:06:53.5751461\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-9e6d-44c4-ad76-e627a9bdf093\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-fa2b-429a-bf56-85418121eea5\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":16,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-fa2b-429a-bf56-85418121eea5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:56.1731107\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-fa2b-429a-bf56-85418121eea5\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-cb8a-40e5-b225-f5026d191283\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":5300,\"message\":\"The conversation has ended. DiagCode: 0#5300.@\"},\"callConnectionId\":\"09002680-cb8a-40e5-b225-f5026d191283\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2025-03-05T05:06:53.7327175\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-cb8a-40e5-b225-f5026d191283\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-fa2b-429a-bf56-85418121eea5\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":17,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-fa2b-429a-bf56-85418121eea5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:56.6215817\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-fa2b-429a-bf56-85418121eea5\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-9e6d-44c4-ad76-e627a9bdf093\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":12,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-9e6d-44c4-ad76-e627a9bdf093\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"54749c24-977a-48ce-baf9-c862bcf657e3\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:53.8942696\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-9e6d-44c4-ad76-e627a9bdf093\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndAnswerThenHangupAutomatedTest.json b/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndAnswerThenHangupAutomatedTest.json index c577fe994f1c..fd8cb079883c 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndAnswerThenHangupAutomatedTest.json +++ b/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndAnswerThenHangupAutomatedTest.json @@ -1 +1 @@ -["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"0546b33e-00ac-44b0-b051-93200e1e39f7\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-7e94-494f-a648-fda3b99c72b1\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-7e94-494f-a648-fda3b99c72b1\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"0546b33e-00ac-44b0-b051-93200e1e39f7\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:10:33.9270693\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-7e94-494f-a648-fda3b99c72b1\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-81d9-4094-9398-4f05d6a621c3\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-81d9-4094-9398-4f05d6a621c3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"0546b33e-00ac-44b0-b051-93200e1e39f7\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:10:33.9270693\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-81d9-4094-9398-4f05d6a621c3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-81d9-4094-9398-4f05d6a621c3\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-81d9-4094-9398-4f05d6a621c3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"0546b33e-00ac-44b0-b051-93200e1e39f7\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:10:34.023208\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-81d9-4094-9398-4f05d6a621c3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-7e94-494f-a648-fda3b99c72b1\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-7e94-494f-a648-fda3b99c72b1\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"0546b33e-00ac-44b0-b051-93200e1e39f7\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:10:34.0434902\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-7e94-494f-a648-fda3b99c72b1\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-7e94-494f-a648-fda3b99c72b1\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":7000,\"message\":\"The conversation has ended. DiagCode: 0#7000.@\"},\"callConnectionId\":\"16001e80-7e94-494f-a648-fda3b99c72b1\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"0546b33e-00ac-44b0-b051-93200e1e39f7\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2024-12-16T17:10:35.6255635\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-7e94-494f-a648-fda3b99c72b1\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-81d9-4094-9398-4f05d6a621c3\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":7000,\"message\":\"The conversation has ended. DiagCode: 0#7000.@\"},\"callConnectionId\":\"16001e80-81d9-4094-9398-4f05d6a621c3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"0546b33e-00ac-44b0-b051-93200e1e39f7\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2024-12-16T17:10:35.6366744\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-81d9-4094-9398-4f05d6a621c3\"}]"] \ No newline at end of file +["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"7358f836-7518-4122-8e1c-a10dae27157d\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-8943-45ff-9f77-0c54434c66fd\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-8943-45ff-9f77-0c54434c66fd\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7358f836-7518-4122-8e1c-a10dae27157d\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:34.6640995\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-8943-45ff-9f77-0c54434c66fd\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-7911-4f79-b1a4-44d873153897\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"09002680-7911-4f79-b1a4-44d873153897\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7358f836-7518-4122-8e1c-a10dae27157d\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:06:34.6640995\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-7911-4f79-b1a4-44d873153897\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-7911-4f79-b1a4-44d873153897\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-7911-4f79-b1a4-44d873153897\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7358f836-7518-4122-8e1c-a10dae27157d\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:34.6640995\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-7911-4f79-b1a4-44d873153897\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-8943-45ff-9f77-0c54434c66fd\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"09002680-8943-45ff-9f77-0c54434c66fd\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7358f836-7518-4122-8e1c-a10dae27157d\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:06:34.7115432\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-8943-45ff-9f77-0c54434c66fd\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-7911-4f79-b1a4-44d873153897\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":7000,\"message\":\"The conversation has ended. DiagCode: 0#7000.@\"},\"callConnectionId\":\"09002680-7911-4f79-b1a4-44d873153897\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7358f836-7518-4122-8e1c-a10dae27157d\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2025-03-05T05:06:36.7602543\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-7911-4f79-b1a4-44d873153897\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-8943-45ff-9f77-0c54434c66fd\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":7000,\"message\":\"The conversation has ended. DiagCode: 0#7000.@\"},\"callConnectionId\":\"09002680-8943-45ff-9f77-0c54434c66fd\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7358f836-7518-4122-8e1c-a10dae27157d\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2025-03-05T05:06:36.9906406\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-8943-45ff-9f77-0c54434c66fd\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndAnswerWithCustomContextThenHangupAutomatedTest.json b/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndAnswerWithCustomContextThenHangupAutomatedTest.json index b8311df376ee..6d17f61fb962 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndAnswerWithCustomContextThenHangupAutomatedTest.json +++ b/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndAnswerWithCustomContextThenHangupAutomatedTest.json @@ -1 +1 @@ -["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"dd7b828d-5f8b-43d4-be3f-d95c675f19ca\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/24002180-b059-4741-a392-a1aed1126925\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"24002180-b059-4741-a392-a1aed1126925\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"dd7b828d-5f8b-43d4-be3f-d95c675f19ca\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-27T21:04:58.0090118\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/24002180-b059-4741-a392-a1aed1126925\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/24002180-2951-4e61-aace-194bbd10bbb1\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"24002180-2951-4e61-aace-194bbd10bbb1\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"dd7b828d-5f8b-43d4-be3f-d95c675f19ca\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-27T21:04:58.0121227\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/24002180-2951-4e61-aace-194bbd10bbb1\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/24002180-2951-4e61-aace-194bbd10bbb1\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"24002180-2951-4e61-aace-194bbd10bbb1\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"dd7b828d-5f8b-43d4-be3f-d95c675f19ca\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-27T21:04:58.0090118\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/24002180-2951-4e61-aace-194bbd10bbb1\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/24002180-b059-4741-a392-a1aed1126925\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"24002180-b059-4741-a392-a1aed1126925\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"dd7b828d-5f8b-43d4-be3f-d95c675f19ca\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-27T21:04:58.0121227\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/24002180-b059-4741-a392-a1aed1126925\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/24002180-2951-4e61-aace-194bbd10bbb1\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":7000,\"message\":\"The conversation has ended. DiagCode: 0#7000.@\"},\"callConnectionId\":\"24002180-2951-4e61-aace-194bbd10bbb1\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"dd7b828d-5f8b-43d4-be3f-d95c675f19ca\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2024-12-27T21:04:59.0901871\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/24002180-2951-4e61-aace-194bbd10bbb1\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/24002180-b059-4741-a392-a1aed1126925\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":5001,\"message\":\"This conversation has ended.. DiagCode: 0#5001.@\"},\"callConnectionId\":\"24002180-b059-4741-a392-a1aed1126925\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"dd7b828d-5f8b-43d4-be3f-d95c675f19ca\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2024-12-27T21:04:59.3246749\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/24002180-b059-4741-a392-a1aed1126925\"}]"] \ No newline at end of file +["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"3af097bb-6e5a-46e4-b0d8-5f4aef0f0fa6\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-f8dc-4d66-906c-89d2f86b3e2d\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-f8dc-4d66-906c-89d2f86b3e2d\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"3af097bb-6e5a-46e4-b0d8-5f4aef0f0fa6\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:21.5519281\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-f8dc-4d66-906c-89d2f86b3e2d\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-f8dc-4d66-906c-89d2f86b3e2d\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"09002680-f8dc-4d66-906c-89d2f86b3e2d\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"3af097bb-6e5a-46e4-b0d8-5f4aef0f0fa6\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:06:21.5438438\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-f8dc-4d66-906c-89d2f86b3e2d\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-0758-4c57-938b-ff47d6ed04ef\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"09002680-0758-4c57-938b-ff47d6ed04ef\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"3af097bb-6e5a-46e4-b0d8-5f4aef0f0fa6\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:06:21.6290238\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-0758-4c57-938b-ff47d6ed04ef\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-0758-4c57-938b-ff47d6ed04ef\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-0758-4c57-938b-ff47d6ed04ef\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"3af097bb-6e5a-46e4-b0d8-5f4aef0f0fa6\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:21.5610094\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-0758-4c57-938b-ff47d6ed04ef\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-f8dc-4d66-906c-89d2f86b3e2d\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":7000,\"message\":\"The conversation has ended. DiagCode: 0#7000.@\"},\"callConnectionId\":\"09002680-f8dc-4d66-906c-89d2f86b3e2d\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"3af097bb-6e5a-46e4-b0d8-5f4aef0f0fa6\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2025-03-05T05:06:24.3763374\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-f8dc-4d66-906c-89d2f86b3e2d\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-0758-4c57-938b-ff47d6ed04ef\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":5001,\"message\":\"This conversation has ended.. DiagCode: 0#5001.@\"},\"callConnectionId\":\"09002680-0758-4c57-938b-ff47d6ed04ef\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"3af097bb-6e5a-46e4-b0d8-5f4aef0f0fa6\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2025-03-05T05:06:24.522503\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-0758-4c57-938b-ff47d6ed04ef\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndConnectCallTest.json b/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndConnectCallTest.json index 03d1d06ce3b8..697fd82f3d78 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndConnectCallTest.json +++ b/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndConnectCallTest.json @@ -1 +1 @@ -["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"cdaace40-1586-4e78-8137-96d2ae56ea7b\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-c64f-462e-a1ed-791c803dc801\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-c64f-462e-a1ed-791c803dc801\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"cdaace40-1586-4e78-8137-96d2ae56ea7b\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:10:23.1864055\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-c64f-462e-a1ed-791c803dc801\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-c64f-462e-a1ed-791c803dc801\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-c64f-462e-a1ed-791c803dc801\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"cdaace40-1586-4e78-8137-96d2ae56ea7b\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:10:23.1905065\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-c64f-462e-a1ed-791c803dc801\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-dbad-41be-a9bd-0e2db1c8bca1\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-dbad-41be-a9bd-0e2db1c8bca1\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"cdaace40-1586-4e78-8137-96d2ae56ea7b\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:10:23.1864055\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-dbad-41be-a9bd-0e2db1c8bca1\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-dbad-41be-a9bd-0e2db1c8bca1\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-dbad-41be-a9bd-0e2db1c8bca1\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"cdaace40-1586-4e78-8137-96d2ae56ea7b\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:10:23.3006525\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-dbad-41be-a9bd-0e2db1c8bca1\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-298e-4ca4-a8a1-db2f97fb26f9\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":2,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-298e-4ca4-a8a1-db2f97fb26f9\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"cdaace40-1586-4e78-8137-96d2ae56ea7b\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:10:27.0917726\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-298e-4ca4-a8a1-db2f97fb26f9\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-298e-4ca4-a8a1-db2f97fb26f9\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-298e-4ca4-a8a1-db2f97fb26f9\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"cdaace40-1586-4e78-8137-96d2ae56ea7b\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:10:27.0948147\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-298e-4ca4-a8a1-db2f97fb26f9\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-298e-4ca4-a8a1-db2f97fb26f9\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-298e-4ca4-a8a1-db2f97fb26f9\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"cdaace40-1586-4e78-8137-96d2ae56ea7b\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:10:27.3693603\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-298e-4ca4-a8a1-db2f97fb26f9\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-298e-4ca4-a8a1-db2f97fb26f9\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":7000,\"message\":\"The conversation has ended. DiagCode: 0#7000.@\"},\"callConnectionId\":\"16001e80-298e-4ca4-a8a1-db2f97fb26f9\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"cdaace40-1586-4e78-8137-96d2ae56ea7b\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2024-12-16T17:10:28.0560329\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-298e-4ca4-a8a1-db2f97fb26f9\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-dbad-41be-a9bd-0e2db1c8bca1\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":5001,\"message\":\"This conversation has ended.. DiagCode: 0#5001.@\"},\"callConnectionId\":\"16001e80-dbad-41be-a9bd-0e2db1c8bca1\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"cdaace40-1586-4e78-8137-96d2ae56ea7b\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2024-12-16T17:10:28.0803745\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-dbad-41be-a9bd-0e2db1c8bca1\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-c64f-462e-a1ed-791c803dc801\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":7000,\"message\":\"The conversation has ended. DiagCode: 0#7000.@\"},\"callConnectionId\":\"16001e80-c64f-462e-a1ed-791c803dc801\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"cdaace40-1586-4e78-8137-96d2ae56ea7b\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2024-12-16T17:10:28.1011318\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-c64f-462e-a1ed-791c803dc801\"}]"] \ No newline at end of file +["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"7c6c686b-ba40-421a-8b92-e4e278730789\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-a836-475c-8c1f-58bceffba0a1\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-a836-475c-8c1f-58bceffba0a1\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7c6c686b-ba40-421a-8b92-e4e278730789\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:03.2180262\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-a836-475c-8c1f-58bceffba0a1\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-a836-475c-8c1f-58bceffba0a1\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"09002680-a836-475c-8c1f-58bceffba0a1\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7c6c686b-ba40-421a-8b92-e4e278730789\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:06:03.2493338\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-a836-475c-8c1f-58bceffba0a1\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-4aad-4475-aef6-174e6efb4ee9\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"09002680-4aad-4475-aef6-174e6efb4ee9\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7c6c686b-ba40-421a-8b92-e4e278730789\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:06:03.2805992\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-4aad-4475-aef6-174e6efb4ee9\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-4aad-4475-aef6-174e6efb4ee9\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-4aad-4475-aef6-174e6efb4ee9\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7c6c686b-ba40-421a-8b92-e4e278730789\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:03.2805992\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-4aad-4475-aef6-174e6efb4ee9\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-777a-432f-bd28-534333d1b7bd\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":2,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-777a-432f-bd28-534333d1b7bd\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7c6c686b-ba40-421a-8b92-e4e278730789\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:07.3307313\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-777a-432f-bd28-534333d1b7bd\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-777a-432f-bd28-534333d1b7bd\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"09002680-777a-432f-bd28-534333d1b7bd\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7c6c686b-ba40-421a-8b92-e4e278730789\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:06:07.346421\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-777a-432f-bd28-534333d1b7bd\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-777a-432f-bd28-534333d1b7bd\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-777a-432f-bd28-534333d1b7bd\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7c6c686b-ba40-421a-8b92-e4e278730789\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:06:07.7076641\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-777a-432f-bd28-534333d1b7bd\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-777a-432f-bd28-534333d1b7bd\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":7000,\"message\":\"The conversation has ended. DiagCode: 0#7000.@\"},\"callConnectionId\":\"09002680-777a-432f-bd28-534333d1b7bd\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7c6c686b-ba40-421a-8b92-e4e278730789\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2025-03-05T05:06:09.2617903\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-777a-432f-bd28-534333d1b7bd\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-a836-475c-8c1f-58bceffba0a1\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":5001,\"message\":\"This conversation has ended.. DiagCode: 0#5001.@\"},\"callConnectionId\":\"09002680-a836-475c-8c1f-58bceffba0a1\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7c6c686b-ba40-421a-8b92-e4e278730789\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2025-03-05T05:06:09.2740451\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-a836-475c-8c1f-58bceffba0a1\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-4aad-4475-aef6-174e6efb4ee9\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":5001,\"message\":\"This conversation has ended.. DiagCode: 0#5001.@\"},\"callConnectionId\":\"09002680-4aad-4475-aef6-174e6efb4ee9\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"7c6c686b-ba40-421a-8b92-e4e278730789\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2025-03-05T05:06:09.4158514\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-4aad-4475-aef6-174e6efb4ee9\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndMediaStreamingTest.json b/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndMediaStreamingTest.json index 938f134e5850..64ad343aa610 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndMediaStreamingTest.json +++ b/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndMediaStreamingTest.json @@ -1 +1 @@ -["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"ad92d39b-d678-4454-8048-41a677b91ff2\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-cb8a-4dc2-8c45-5e7cda760017\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-cb8a-4dc2-8c45-5e7cda760017\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"ad92d39b-d678-4454-8048-41a677b91ff2\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:13:01.1393022\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-cb8a-4dc2-8c45-5e7cda760017\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-e556-4b2b-9454-516c1672c229\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-e556-4b2b-9454-516c1672c229\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"ad92d39b-d678-4454-8048-41a677b91ff2\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:13:01.1393022\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-e556-4b2b-9454-516c1672c229\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-cb8a-4dc2-8c45-5e7cda760017\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-cb8a-4dc2-8c45-5e7cda760017\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"ad92d39b-d678-4454-8048-41a677b91ff2\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:13:01.2278287\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-cb8a-4dc2-8c45-5e7cda760017\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-e556-4b2b-9454-516c1672c229\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-e556-4b2b-9454-516c1672c229\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"ad92d39b-d678-4454-8048-41a677b91ff2\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:13:01.2691477\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-e556-4b2b-9454-516c1672c229\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-e556-4b2b-9454-516c1672c229\",\"type\":\"Microsoft.Communication.MediaStreamingStarted\",\"data\":{\"mediaStreamingUpdate\":{\"contentType\":\"Audio\",\"mediaStreamingStatus\":\"mediaStreamingStarted\",\"mediaStreamingStatusDetails\":\"subscriptionStarted\"},\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"16001e80-e556-4b2b-9454-516c1672c229\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"ad92d39b-d678-4454-8048-41a677b91ff2\",\"publicEventType\":\"Microsoft.Communication.MediaStreamingStarted\"},\"time\":\"2024-12-16T17:13:02.3681964\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-e556-4b2b-9454-516c1672c229\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-e556-4b2b-9454-516c1672c229\",\"type\":\"Microsoft.Communication.MediaStreamingStopped\",\"data\":{\"mediaStreamingUpdate\":{\"contentType\":\"Audio\",\"mediaStreamingStatus\":\"mediaStreamingStopped\",\"mediaStreamingStatusDetails\":\"subscriptionStopped\"},\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"16001e80-e556-4b2b-9454-516c1672c229\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"ad92d39b-d678-4454-8048-41a677b91ff2\",\"publicEventType\":\"Microsoft.Communication.MediaStreamingStopped\"},\"time\":\"2024-12-16T17:13:03.5052801\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-e556-4b2b-9454-516c1672c229\"}]"] \ No newline at end of file +["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"a0a4ce36-d74b-4155-8659-3b0e5d2c09b4\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-9f1f-437d-b004-4ea4924fddb5\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-9f1f-437d-b004-4ea4924fddb5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a0a4ce36-d74b-4155-8659-3b0e5d2c09b4\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:10:53.6079705\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-9f1f-437d-b004-4ea4924fddb5\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-fbf3-4b55-ab4c-3caaf7f2a583\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"00002680-fbf3-4b55-ab4c-3caaf7f2a583\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a0a4ce36-d74b-4155-8659-3b0e5d2c09b4\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:10:53.6079705\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-fbf3-4b55-ab4c-3caaf7f2a583\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-fbf3-4b55-ab4c-3caaf7f2a583\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-fbf3-4b55-ab4c-3caaf7f2a583\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a0a4ce36-d74b-4155-8659-3b0e5d2c09b4\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:10:53.6079705\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-fbf3-4b55-ab4c-3caaf7f2a583\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-9f1f-437d-b004-4ea4924fddb5\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"00002680-9f1f-437d-b004-4ea4924fddb5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a0a4ce36-d74b-4155-8659-3b0e5d2c09b4\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:10:53.6870147\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-9f1f-437d-b004-4ea4924fddb5\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-9f1f-437d-b004-4ea4924fddb5\",\"type\":\"Microsoft.Communication.MediaStreamingStarted\",\"data\":{\"mediaStreamingUpdate\":{\"contentType\":\"Audio\",\"mediaStreamingStatus\":\"mediaStreamingStarted\",\"mediaStreamingStatusDetails\":\"subscriptionStarted\"},\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"00002680-9f1f-437d-b004-4ea4924fddb5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a0a4ce36-d74b-4155-8659-3b0e5d2c09b4\",\"publicEventType\":\"Microsoft.Communication.MediaStreamingStarted\"},\"time\":\"2025-03-05T05:10:56.9546699\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-9f1f-437d-b004-4ea4924fddb5\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-9f1f-437d-b004-4ea4924fddb5\",\"type\":\"Microsoft.Communication.MediaStreamingStopped\",\"data\":{\"mediaStreamingUpdate\":{\"contentType\":\"Audio\",\"mediaStreamingStatus\":\"mediaStreamingStopped\",\"mediaStreamingStatusDetails\":\"subscriptionStopped\"},\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"00002680-9f1f-437d-b004-4ea4924fddb5\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a0a4ce36-d74b-4155-8659-3b0e5d2c09b4\",\"publicEventType\":\"Microsoft.Communication.MediaStreamingStopped\"},\"time\":\"2025-03-05T05:10:58.1240543\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-9f1f-437d-b004-4ea4924fddb5\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndRejectAutomatedTest.json b/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndRejectAutomatedTest.json index 9d2a30448c1f..beb48d375ded 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndRejectAutomatedTest.json +++ b/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndRejectAutomatedTest.json @@ -1 +1 @@ -["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"ce42ff5a-3571-4b5e-86fe-765523eea33b\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/2d002280-747b-40c9-b042-46b9f04f8edd\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":603,\"subCode\":0,\"message\":\"Decline. DiagCode: 603#0.@\"},\"callConnectionId\":\"2d002280-747b-40c9-b042-46b9f04f8edd\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"ce42ff5a-3571-4b5e-86fe-765523eea33b\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2024-12-16T17:10:17.1334347\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/2d002280-747b-40c9-b042-46b9f04f8edd\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/2d002280-747b-40c9-b042-46b9f04f8edd\",\"type\":\"Microsoft.Communication.CreateCallFailed\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":603,\"subCode\":0,\"message\":\"Decline. DiagCode: 603#0.@\"},\"callConnectionId\":\"2d002280-747b-40c9-b042-46b9f04f8edd\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"ce42ff5a-3571-4b5e-86fe-765523eea33b\",\"publicEventType\":\"Microsoft.Communication.CreateCallFailed\"},\"time\":\"2024-12-16T17:10:17.1334347\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/2d002280-747b-40c9-b042-46b9f04f8edd\"}]"] \ No newline at end of file +["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"bf80131a-2147-4577-b660-b6908d4f31d7\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-4a25-4c10-b9a4-5341af3c6021\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":603,\"subCode\":0,\"message\":\"Decline. DiagCode: 603#0.@\"},\"callConnectionId\":\"09002680-4a25-4c10-b9a4-5341af3c6021\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"bf80131a-2147-4577-b660-b6908d4f31d7\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2025-03-05T05:05:47.9701737\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-4a25-4c10-b9a4-5341af3c6021\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-4a25-4c10-b9a4-5341af3c6021\",\"type\":\"Microsoft.Communication.CreateCallFailed\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":603,\"subCode\":0,\"message\":\"Decline. DiagCode: 603#0.@\"},\"callConnectionId\":\"09002680-4a25-4c10-b9a4-5341af3c6021\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"bf80131a-2147-4577-b660-b6908d4f31d7\",\"publicEventType\":\"Microsoft.Communication.CreateCallFailed\"},\"time\":\"2025-03-05T05:05:47.9701737\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-4a25-4c10-b9a4-5341af3c6021\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndTranscriptionTest.json b/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndTranscriptionTest.json index 52dc791601f3..8203e86f7498 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndTranscriptionTest.json +++ b/sdk/communication/azure-communication-callautomation/src/test/resources/createVOIPCallAndTranscriptionTest.json @@ -1 +1 @@ -["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"b0eb2a09-97ca-4f9d-b99f-8588a78b44f0\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-cb91-4078-a33d-37f047d74f1b\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-cb91-4078-a33d-37f047d74f1b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"b0eb2a09-97ca-4f9d-b99f-8588a78b44f0\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:13:22.9408836\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-cb91-4078-a33d-37f047d74f1b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-3d72-4a31-ae28-c7b15c25f1a1\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-3d72-4a31-ae28-c7b15c25f1a1\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"b0eb2a09-97ca-4f9d-b99f-8588a78b44f0\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:13:22.9408836\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-3d72-4a31-ae28-c7b15c25f1a1\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-3d72-4a31-ae28-c7b15c25f1a1\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-3d72-4a31-ae28-c7b15c25f1a1\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"b0eb2a09-97ca-4f9d-b99f-8588a78b44f0\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:13:23.0487831\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-3d72-4a31-ae28-c7b15c25f1a1\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-cb91-4078-a33d-37f047d74f1b\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-cb91-4078-a33d-37f047d74f1b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"b0eb2a09-97ca-4f9d-b99f-8588a78b44f0\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:13:23.0939701\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-cb91-4078-a33d-37f047d74f1b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-cb91-4078-a33d-37f047d74f1b\",\"type\":\"Microsoft.Communication.TranscriptionStarted\",\"data\":{\"transcriptionUpdate\":{\"transcriptionStatus\":\"transcriptionStarted\",\"transcriptionStatusDetails\":\"subscriptionStarted\"},\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"16001e80-cb91-4078-a33d-37f047d74f1b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"b0eb2a09-97ca-4f9d-b99f-8588a78b44f0\",\"publicEventType\":\"Microsoft.Communication.TranscriptionStarted\"},\"time\":\"2024-12-16T17:13:24.6841041\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-cb91-4078-a33d-37f047d74f1b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-cb91-4078-a33d-37f047d74f1b\",\"type\":\"Microsoft.Communication.TranscriptionStopped\",\"data\":{\"transcriptionUpdate\":{\"transcriptionStatus\":\"transcriptionStopped\",\"transcriptionStatusDetails\":\"subscriptionStopped\"},\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"16001e80-cb91-4078-a33d-37f047d74f1b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"b0eb2a09-97ca-4f9d-b99f-8588a78b44f0\",\"publicEventType\":\"Microsoft.Communication.TranscriptionStopped\"},\"time\":\"2024-12-16T17:13:28.0543802\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-cb91-4078-a33d-37f047d74f1b\"}]"] \ No newline at end of file +["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"52a62de0-cc1f-4434-ba2a-ad43bcbfb947\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-2a53-4922-85f3-70195db1d669\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"00002680-2a53-4922-85f3-70195db1d669\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"52a62de0-cc1f-4434-ba2a-ad43bcbfb947\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:11:25.7298232\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-2a53-4922-85f3-70195db1d669\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-2a53-4922-85f3-70195db1d669\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-2a53-4922-85f3-70195db1d669\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"52a62de0-cc1f-4434-ba2a-ad43bcbfb947\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:11:25.7773603\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-2a53-4922-85f3-70195db1d669\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-5475-4f84-8842-2222ead9a207\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"00002680-5475-4f84-8842-2222ead9a207\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"52a62de0-cc1f-4434-ba2a-ad43bcbfb947\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:11:25.8874441\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-5475-4f84-8842-2222ead9a207\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-5475-4f84-8842-2222ead9a207\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-5475-4f84-8842-2222ead9a207\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"52a62de0-cc1f-4434-ba2a-ad43bcbfb947\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:11:26.2723107\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-5475-4f84-8842-2222ead9a207\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-5475-4f84-8842-2222ead9a207\",\"type\":\"Microsoft.Communication.TranscriptionStarted\",\"data\":{\"transcriptionUpdate\":{\"transcriptionStatus\":\"transcriptionStarted\",\"transcriptionStatusDetails\":\"subscriptionStarted\"},\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"00002680-5475-4f84-8842-2222ead9a207\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"52a62de0-cc1f-4434-ba2a-ad43bcbfb947\",\"publicEventType\":\"Microsoft.Communication.TranscriptionStarted\"},\"time\":\"2025-03-05T05:11:29.4717109\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-5475-4f84-8842-2222ead9a207\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-5475-4f84-8842-2222ead9a207\",\"type\":\"Microsoft.Communication.TranscriptionStopped\",\"data\":{\"transcriptionUpdate\":{\"transcriptionStatus\":\"transcriptionStopped\",\"transcriptionStatusDetails\":\"subscriptionStopped\"},\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"00002680-5475-4f84-8842-2222ead9a207\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"52a62de0-cc1f-4434-ba2a-ad43bcbfb947\",\"publicEventType\":\"Microsoft.Communication.TranscriptionStopped\"},\"time\":\"2025-03-05T05:11:32.6029876\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-5475-4f84-8842-2222ead9a207\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-5475-4f84-8842-2222ead9a207\",\"type\":\"Microsoft.Communication.TranscriptionStopped\",\"data\":{\"transcriptionUpdate\":{\"transcriptionStatus\":\"transcriptionStopped\",\"transcriptionStatusDetails\":\"streamConnectionInterrupted\"},\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":500,\"subCode\":8579,\"message\":\"Action failed, transcription was canceled.\"},\"callConnectionId\":\"00002680-5475-4f84-8842-2222ead9a207\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"52a62de0-cc1f-4434-ba2a-ad43bcbfb947\",\"publicEventType\":\"Microsoft.Communication.TranscriptionStopped\"},\"time\":\"2025-03-05T05:11:32.6029876\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-5475-4f84-8842-2222ead9a207\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/dtmfActionsInACallAutomatedTest.json b/sdk/communication/azure-communication-callautomation/src/test/resources/dtmfActionsInACallAutomatedTest.json index ef9c8ffd0815..6932a6b5e7bf 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/dtmfActionsInACallAutomatedTest.json +++ b/sdk/communication/azure-communication-callautomation/src/test/resources/dtmfActionsInACallAutomatedTest.json @@ -1 +1 @@ -["{\"to\":{\"kind\":\"phoneNumber\",\"rawId\":\"REDACTED\",\"phoneNumber\":{\"value\":\"REDACTED\"}},\"from\":{\"kind\":\"phoneNumber\",\"rawId\":\"REDACTED\",\"phoneNumber\":{\"value\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"0f2c1907-0dda-4ee9-b877-9e893864d342\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-0cd5-42f2-b732-9cbbafbd5d3b\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-0cd5-42f2-b732-9cbbafbd5d3b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"0f2c1907-0dda-4ee9-b877-9e893864d342\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:11:59.3010989\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-0cd5-42f2-b732-9cbbafbd5d3b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-0cd5-42f2-b732-9cbbafbd5d3b\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"phoneNumber\",\"phoneNumber\":{\"value\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-0cd5-42f2-b732-9cbbafbd5d3b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"0f2c1907-0dda-4ee9-b877-9e893864d342\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:11:59.4059277\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-0cd5-42f2-b732-9cbbafbd5d3b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-bb41-433b-82b5-3c50b7b4ba03\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"phoneNumber\",\"phoneNumber\":{\"value\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-bb41-433b-82b5-3c50b7b4ba03\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"706f3324-002b-4d2b-b760-2c7b32df69d0\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:11:59.389228\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-bb41-433b-82b5-3c50b7b4ba03\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-bb41-433b-82b5-3c50b7b4ba03\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-bb41-433b-82b5-3c50b7b4ba03\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"706f3324-002b-4d2b-b760-2c7b32df69d0\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:11:59.4431575\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-bb41-433b-82b5-3c50b7b4ba03\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-bb41-433b-82b5-3c50b7b4ba03\",\"type\":\"Microsoft.Communication.SendDtmfTonesCompleted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-bb41-433b-82b5-3c50b7b4ba03\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"706f3324-002b-4d2b-b760-2c7b32df69d0\",\"publicEventType\":\"Microsoft.Communication.SendDtmfTonesCompleted\"},\"time\":\"2024-12-16T17:12:03.3393912\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-bb41-433b-82b5-3c50b7b4ba03\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-bb41-433b-82b5-3c50b7b4ba03\",\"type\":\"Microsoft.Communication.ContinuousDtmfRecognitionStopped\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":7000,\"message\":\"The conversation has ended. DiagCode: 0#7000.@\"},\"callConnectionId\":\"16001e80-bb41-433b-82b5-3c50b7b4ba03\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"706f3324-002b-4d2b-b760-2c7b32df69d0\",\"publicEventType\":\"Microsoft.Communication.ContinuousDtmfRecognitionStopped\"},\"time\":\"2024-12-16T17:12:03.9179959\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-bb41-433b-82b5-3c50b7b4ba03\"}]"] \ No newline at end of file +["[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/08002680-d9b2-43e0-9e4e-4a44ad7dad4f\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":7000,\"message\":\"The conversation has ended. DiagCode: 0#7000.@\"},\"callConnectionId\":\"08002680-d9b2-43e0-9e4e-4a44ad7dad4f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"4500fed7-e1cd-4c1f-9c7f-1ec545843a38\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2025-03-05T05:06:09.2240574\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/08002680-d9b2-43e0-9e4e-4a44ad7dad4f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/08002680-a72d-45ec-aa54-d156ae433b95\",\"type\":\"Microsoft.Communication.CallDisconnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":540000,\"message\":\"The conversation has ended\"},\"callConnectionId\":\"08002680-a72d-45ec-aa54-d156ae433b95\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"d2b98a7f-e0ce-4405-98ae-1b5b85bb9e10\",\"publicEventType\":\"Microsoft.Communication.CallDisconnected\"},\"time\":\"2025-03-05T05:06:09.7269266\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/08002680-a72d-45ec-aa54-d156ae433b95\"}]","{\"to\":{\"kind\":\"phoneNumber\",\"rawId\":\"REDACTED\",\"phoneNumber\":{\"value\":\"REDACTED\"}},\"from\":{\"kind\":\"phoneNumber\",\"rawId\":\"REDACTED\",\"phoneNumber\":{\"value\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"716fb88e-7a5a-4ae1-b953-a1d519595a52\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-b0ee-44ac-be45-b6015074d407\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"phoneNumber\",\"phoneNumber\":{\"value\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-b0ee-44ac-be45-b6015074d407\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"4ba75dae-5a1d-4c72-911e-a5d805dedb69\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:08:58.0584334\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-b0ee-44ac-be45-b6015074d407\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-3717-497b-a894-f68c64158883\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"00002680-3717-497b-a894-f68c64158883\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"716fb88e-7a5a-4ae1-b953-a1d519595a52\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:08:58.0747348\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-3717-497b-a894-f68c64158883\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-b0ee-44ac-be45-b6015074d407\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"00002680-b0ee-44ac-be45-b6015074d407\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"4ba75dae-5a1d-4c72-911e-a5d805dedb69\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:08:58.3583025\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-b0ee-44ac-be45-b6015074d407\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-3717-497b-a894-f68c64158883\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"phoneNumber\",\"phoneNumber\":{\"value\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-3717-497b-a894-f68c64158883\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"716fb88e-7a5a-4ae1-b953-a1d519595a52\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:08:58.609263\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-3717-497b-a894-f68c64158883\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-b0ee-44ac-be45-b6015074d407\",\"type\":\"Microsoft.Communication.SendDtmfTonesCompleted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"00002680-b0ee-44ac-be45-b6015074d407\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"4ba75dae-5a1d-4c72-911e-a5d805dedb69\",\"publicEventType\":\"Microsoft.Communication.SendDtmfTonesCompleted\"},\"time\":\"2025-03-05T05:09:05.0583303\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-b0ee-44ac-be45-b6015074d407\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-b0ee-44ac-be45-b6015074d407\",\"type\":\"Microsoft.Communication.ContinuousDtmfRecognitionStopped\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":7000,\"message\":\"The conversation has ended. DiagCode: 0#7000.@\"},\"callConnectionId\":\"00002680-b0ee-44ac-be45-b6015074d407\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"4ba75dae-5a1d-4c72-911e-a5d805dedb69\",\"publicEventType\":\"Microsoft.Communication.ContinuousDtmfRecognitionStopped\"},\"time\":\"2025-03-05T05:09:05.6716338\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-b0ee-44ac-be45-b6015074d407\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/holdUnholdParticipantInACallTest.json b/sdk/communication/azure-communication-callautomation/src/test/resources/holdUnholdParticipantInACallTest.json index 7e2607ef0627..bee4038d7049 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/holdUnholdParticipantInACallTest.json +++ b/sdk/communication/azure-communication-callautomation/src/test/resources/holdUnholdParticipantInACallTest.json @@ -1 +1 @@ -["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"64ed90b1-6f9c-43b8-b6b5-78d626670c69\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-240b-4931-b1b7-72e75f663045\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-240b-4931-b1b7-72e75f663045\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"64ed90b1-6f9c-43b8-b6b5-78d626670c69\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:13:09.0467996\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-240b-4931-b1b7-72e75f663045\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-63ce-4e7b-a52d-e6b5b2cb9261\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-63ce-4e7b-a52d-e6b5b2cb9261\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"64ed90b1-6f9c-43b8-b6b5-78d626670c69\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:13:09.0533368\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-63ce-4e7b-a52d-e6b5b2cb9261\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-63ce-4e7b-a52d-e6b5b2cb9261\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-63ce-4e7b-a52d-e6b5b2cb9261\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"64ed90b1-6f9c-43b8-b6b5-78d626670c69\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:13:09.1638479\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-63ce-4e7b-a52d-e6b5b2cb9261\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-240b-4931-b1b7-72e75f663045\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-240b-4931-b1b7-72e75f663045\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"64ed90b1-6f9c-43b8-b6b5-78d626670c69\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:13:09.227973\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-240b-4931-b1b7-72e75f663045\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-240b-4931-b1b7-72e75f663045\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":true}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-240b-4931-b1b7-72e75f663045\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"64ed90b1-6f9c-43b8-b6b5-78d626670c69\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:13:12.3561446\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-240b-4931-b1b7-72e75f663045\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-63ce-4e7b-a52d-e6b5b2cb9261\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":true}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-63ce-4e7b-a52d-e6b5b2cb9261\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"64ed90b1-6f9c-43b8-b6b5-78d626670c69\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:13:12.3561446\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-63ce-4e7b-a52d-e6b5b2cb9261\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-240b-4931-b1b7-72e75f663045\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":5,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-240b-4931-b1b7-72e75f663045\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"64ed90b1-6f9c-43b8-b6b5-78d626670c69\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:13:15.869228\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-240b-4931-b1b7-72e75f663045\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-63ce-4e7b-a52d-e6b5b2cb9261\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":5,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-63ce-4e7b-a52d-e6b5b2cb9261\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"64ed90b1-6f9c-43b8-b6b5-78d626670c69\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:13:15.869876\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-63ce-4e7b-a52d-e6b5b2cb9261\"}]"] \ No newline at end of file +["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"a9735b79-beed-4882-8449-5eade4c353cf\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-357e-4638-bcc7-f67c84ff6931\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-357e-4638-bcc7-f67c84ff6931\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a9735b79-beed-4882-8449-5eade4c353cf\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:11:07.050362\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-357e-4638-bcc7-f67c84ff6931\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-0bee-4251-a78d-385e6f2930f3\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-0bee-4251-a78d-385e6f2930f3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a9735b79-beed-4882-8449-5eade4c353cf\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:11:07.0564601\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-0bee-4251-a78d-385e6f2930f3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-357e-4638-bcc7-f67c84ff6931\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"00002680-357e-4638-bcc7-f67c84ff6931\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a9735b79-beed-4882-8449-5eade4c353cf\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:11:07.0551994\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-357e-4638-bcc7-f67c84ff6931\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-0bee-4251-a78d-385e6f2930f3\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"00002680-0bee-4251-a78d-385e6f2930f3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a9735b79-beed-4882-8449-5eade4c353cf\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:11:07.1401195\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-0bee-4251-a78d-385e6f2930f3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-357e-4638-bcc7-f67c84ff6931\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":true}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-357e-4638-bcc7-f67c84ff6931\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a9735b79-beed-4882-8449-5eade4c353cf\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:11:11.1252698\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-357e-4638-bcc7-f67c84ff6931\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-0bee-4251-a78d-385e6f2930f3\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":true}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-0bee-4251-a78d-385e6f2930f3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a9735b79-beed-4882-8449-5eade4c353cf\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:11:11.1252698\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-0bee-4251-a78d-385e6f2930f3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-0bee-4251-a78d-385e6f2930f3\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":5,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-0bee-4251-a78d-385e6f2930f3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a9735b79-beed-4882-8449-5eade4c353cf\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:11:14.519588\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-0bee-4251-a78d-385e6f2930f3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-357e-4638-bcc7-f67c84ff6931\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":5,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-357e-4638-bcc7-f67c84ff6931\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a9735b79-beed-4882-8449-5eade4c353cf\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:11:14.519588\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-357e-4638-bcc7-f67c84ff6931\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/interruptAudioAndAnnounceToholdParticipantInACallTest.json b/sdk/communication/azure-communication-callautomation/src/test/resources/interruptAudioAndAnnounceToholdParticipantInACallTest.json index 7e306b4fa374..92debf9c7a4b 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/interruptAudioAndAnnounceToholdParticipantInACallTest.json +++ b/sdk/communication/azure-communication-callautomation/src/test/resources/interruptAudioAndAnnounceToholdParticipantInACallTest.json @@ -1 +1 @@ -["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"bef88182-f4f9-4cb8-9a94-7c58ede238b1\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/2a002280-735b-49f6-9b04-f3e34728ad19\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"2a002280-735b-49f6-9b04-f3e34728ad19\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"bef88182-f4f9-4cb8-9a94-7c58ede238b1\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-20T18:25:09.7605863\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/2a002280-735b-49f6-9b04-f3e34728ad19\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/2a002280-735b-49f6-9b04-f3e34728ad19\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"2a002280-735b-49f6-9b04-f3e34728ad19\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"bef88182-f4f9-4cb8-9a94-7c58ede238b1\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-20T18:25:09.7195532\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/2a002280-735b-49f6-9b04-f3e34728ad19\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/2a002280-ba93-4255-9f16-c3f0d32cbebb\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"2a002280-ba93-4255-9f16-c3f0d32cbebb\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"bef88182-f4f9-4cb8-9a94-7c58ede238b1\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-20T18:25:09.7195532\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/2a002280-ba93-4255-9f16-c3f0d32cbebb\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/2a002280-ba93-4255-9f16-c3f0d32cbebb\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"2a002280-ba93-4255-9f16-c3f0d32cbebb\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"bef88182-f4f9-4cb8-9a94-7c58ede238b1\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-20T18:25:09.836015\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/2a002280-ba93-4255-9f16-c3f0d32cbebb\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/2a002280-ba93-4255-9f16-c3f0d32cbebb\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":true}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"2a002280-ba93-4255-9f16-c3f0d32cbebb\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"bef88182-f4f9-4cb8-9a94-7c58ede238b1\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-20T18:25:15.741316\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/2a002280-ba93-4255-9f16-c3f0d32cbebb\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/2a002280-735b-49f6-9b04-f3e34728ad19\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":true}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"2a002280-735b-49f6-9b04-f3e34728ad19\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"bef88182-f4f9-4cb8-9a94-7c58ede238b1\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-20T18:25:15.741316\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/2a002280-735b-49f6-9b04-f3e34728ad19\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/2a002280-ba93-4255-9f16-c3f0d32cbebb\",\"type\":\"Microsoft.Communication.PlayStarted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"2a002280-ba93-4255-9f16-c3f0d32cbebb\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"bef88182-f4f9-4cb8-9a94-7c58ede238b1\",\"publicEventType\":\"Microsoft.Communication.PlayStarted\"},\"time\":\"2024-12-20T18:25:21.4972602\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/2a002280-ba93-4255-9f16-c3f0d32cbebb\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/2a002280-ba93-4255-9f16-c3f0d32cbebb\",\"type\":\"Microsoft.Communication.PlayCanceled\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":400,\"subCode\":8508,\"message\":\"Action falied, the operation was cancelled.\"},\"callConnectionId\":\"2a002280-ba93-4255-9f16-c3f0d32cbebb\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"bef88182-f4f9-4cb8-9a94-7c58ede238b1\",\"publicEventType\":\"Microsoft.Communication.PlayCanceled\"},\"time\":\"2024-12-20T18:25:24.4389091\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/2a002280-ba93-4255-9f16-c3f0d32cbebb\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/2a002280-735b-49f6-9b04-f3e34728ad19\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":5,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"2a002280-735b-49f6-9b04-f3e34728ad19\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"bef88182-f4f9-4cb8-9a94-7c58ede238b1\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-20T18:25:24.5361406\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/2a002280-735b-49f6-9b04-f3e34728ad19\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/2a002280-ba93-4255-9f16-c3f0d32cbebb\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":5,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"2a002280-ba93-4255-9f16-c3f0d32cbebb\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"bef88182-f4f9-4cb8-9a94-7c58ede238b1\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-20T18:25:24.5361406\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/2a002280-ba93-4255-9f16-c3f0d32cbebb\"}]"] \ No newline at end of file +["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"045c6a37-998c-432b-a217-494d76ae28a7\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-4820-4dab-9dc9-24d5e1e5ff2f\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-4820-4dab-9dc9-24d5e1e5ff2f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"045c6a37-998c-432b-a217-494d76ae28a7\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:10:16.2670063\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-4820-4dab-9dc9-24d5e1e5ff2f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-9f69-43d2-aa6d-aae32c92d187\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-9f69-43d2-aa6d-aae32c92d187\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"045c6a37-998c-432b-a217-494d76ae28a7\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:10:16.297698\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-9f69-43d2-aa6d-aae32c92d187\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-4820-4dab-9dc9-24d5e1e5ff2f\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"00002680-4820-4dab-9dc9-24d5e1e5ff2f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"045c6a37-998c-432b-a217-494d76ae28a7\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:10:16.3290051\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-4820-4dab-9dc9-24d5e1e5ff2f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-9f69-43d2-aa6d-aae32c92d187\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"00002680-9f69-43d2-aa6d-aae32c92d187\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"045c6a37-998c-432b-a217-494d76ae28a7\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:10:16.5025027\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-9f69-43d2-aa6d-aae32c92d187\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-9f69-43d2-aa6d-aae32c92d187\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":true},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-9f69-43d2-aa6d-aae32c92d187\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"045c6a37-998c-432b-a217-494d76ae28a7\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:10:20.5691432\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-9f69-43d2-aa6d-aae32c92d187\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-4820-4dab-9dc9-24d5e1e5ff2f\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":true},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-4820-4dab-9dc9-24d5e1e5ff2f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"045c6a37-998c-432b-a217-494d76ae28a7\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:10:20.5967382\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-4820-4dab-9dc9-24d5e1e5ff2f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-9f69-43d2-aa6d-aae32c92d187\",\"type\":\"Microsoft.Communication.PlayStarted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"00002680-9f69-43d2-aa6d-aae32c92d187\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"045c6a37-998c-432b-a217-494d76ae28a7\",\"publicEventType\":\"Microsoft.Communication.PlayStarted\"},\"time\":\"2025-03-05T05:10:24.7604956\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-9f69-43d2-aa6d-aae32c92d187\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-9f69-43d2-aa6d-aae32c92d187\",\"type\":\"Microsoft.Communication.PlayCanceled\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":400,\"subCode\":8508,\"message\":\"Action falied, the operation was cancelled.\"},\"callConnectionId\":\"00002680-9f69-43d2-aa6d-aae32c92d187\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"045c6a37-998c-432b-a217-494d76ae28a7\",\"publicEventType\":\"Microsoft.Communication.PlayCanceled\"},\"time\":\"2025-03-05T05:10:27.1661006\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-9f69-43d2-aa6d-aae32c92d187\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-4820-4dab-9dc9-24d5e1e5ff2f\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":5,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-4820-4dab-9dc9-24d5e1e5ff2f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"045c6a37-998c-432b-a217-494d76ae28a7\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:10:27.2286743\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-4820-4dab-9dc9-24d5e1e5ff2f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-9f69-43d2-aa6d-aae32c92d187\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":5,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-9f69-43d2-aa6d-aae32c92d187\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"045c6a37-998c-432b-a217-494d76ae28a7\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:10:27.2443009\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-9f69-43d2-aa6d-aae32c92d187\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/playMediaInACallAutomatedTest.json b/sdk/communication/azure-communication-callautomation/src/test/resources/playMediaInACallAutomatedTest.json index bc6920f2d4ba..b3d29b52ab95 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/playMediaInACallAutomatedTest.json +++ b/sdk/communication/azure-communication-callautomation/src/test/resources/playMediaInACallAutomatedTest.json @@ -1 +1 @@ -["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"ef48b285-681b-414b-879c-e977cc0f2fcd\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-a301-4c9f-9caf-b4a414e9c2e7\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-a301-4c9f-9caf-b4a414e9c2e7\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"ef48b285-681b-414b-879c-e977cc0f2fcd\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:12:50.6192198\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-a301-4c9f-9caf-b4a414e9c2e7\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-18a3-47fb-a721-856cc3732785\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-18a3-47fb-a721-856cc3732785\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"ef48b285-681b-414b-879c-e977cc0f2fcd\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:12:50.6237782\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-18a3-47fb-a721-856cc3732785\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-18a3-47fb-a721-856cc3732785\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-18a3-47fb-a721-856cc3732785\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"ef48b285-681b-414b-879c-e977cc0f2fcd\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:12:50.7021964\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-18a3-47fb-a721-856cc3732785\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-a301-4c9f-9caf-b4a414e9c2e7\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-a301-4c9f-9caf-b4a414e9c2e7\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"ef48b285-681b-414b-879c-e977cc0f2fcd\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:12:50.733158\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-a301-4c9f-9caf-b4a414e9c2e7\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-a301-4c9f-9caf-b4a414e9c2e7\",\"type\":\"Microsoft.Communication.PlayStarted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"16001e80-a301-4c9f-9caf-b4a414e9c2e7\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"ef48b285-681b-414b-879c-e977cc0f2fcd\",\"publicEventType\":\"Microsoft.Communication.PlayStarted\"},\"time\":\"2024-12-16T17:12:51.7403421\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-a301-4c9f-9caf-b4a414e9c2e7\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-a301-4c9f-9caf-b4a414e9c2e7\",\"type\":\"Microsoft.Communication.PlayCompleted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"16001e80-a301-4c9f-9caf-b4a414e9c2e7\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"ef48b285-681b-414b-879c-e977cc0f2fcd\",\"publicEventType\":\"Microsoft.Communication.PlayCompleted\"},\"time\":\"2024-12-16T17:12:55.9586329\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-a301-4c9f-9caf-b4a414e9c2e7\"}]"] \ No newline at end of file +["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"dd4edbb8-36a7-40db-8f4f-3b481d60d5d8\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-062f-4308-ab87-5427daa80363\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-062f-4308-ab87-5427daa80363\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"dd4edbb8-36a7-40db-8f4f-3b481d60d5d8\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:10:38.2941461\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-062f-4308-ab87-5427daa80363\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-6f85-4b4c-938e-9e58586f1fb9\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-6f85-4b4c-938e-9e58586f1fb9\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"dd4edbb8-36a7-40db-8f4f-3b481d60d5d8\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:10:38.2941461\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-6f85-4b4c-938e-9e58586f1fb9\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-6f85-4b4c-938e-9e58586f1fb9\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"00002680-6f85-4b4c-938e-9e58586f1fb9\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"dd4edbb8-36a7-40db-8f4f-3b481d60d5d8\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:10:38.3268155\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-6f85-4b4c-938e-9e58586f1fb9\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-062f-4308-ab87-5427daa80363\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"00002680-062f-4308-ab87-5427daa80363\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"dd4edbb8-36a7-40db-8f4f-3b481d60d5d8\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:10:38.3573005\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-062f-4308-ab87-5427daa80363\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-062f-4308-ab87-5427daa80363\",\"type\":\"Microsoft.Communication.PlayStarted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"00002680-062f-4308-ab87-5427daa80363\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"dd4edbb8-36a7-40db-8f4f-3b481d60d5d8\",\"publicEventType\":\"Microsoft.Communication.PlayStarted\"},\"time\":\"2025-03-05T05:10:40.9324277\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-062f-4308-ab87-5427daa80363\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-062f-4308-ab87-5427daa80363\",\"type\":\"Microsoft.Communication.PlayCompleted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"00002680-062f-4308-ab87-5427daa80363\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"dd4edbb8-36a7-40db-8f4f-3b481d60d5d8\",\"publicEventType\":\"Microsoft.Communication.PlayCompleted\"},\"time\":\"2025-03-05T05:10:45.1536721\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-062f-4308-ab87-5427daa80363\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/playMultipleCombinedSourcesWithPlayMediaAllTest.json b/sdk/communication/azure-communication-callautomation/src/test/resources/playMultipleCombinedSourcesWithPlayMediaAllTest.json index 59280e72eae4..4edf9039a5ce 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/playMultipleCombinedSourcesWithPlayMediaAllTest.json +++ b/sdk/communication/azure-communication-callautomation/src/test/resources/playMultipleCombinedSourcesWithPlayMediaAllTest.json @@ -1 +1 @@ -["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"74d9363f-588b-4824-959d-e2382a8ae7fd\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-316b-4b5f-bc9a-93076b94a58d\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-316b-4b5f-bc9a-93076b94a58d\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"74d9363f-588b-4824-959d-e2382a8ae7fd\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:12:08.74575\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-316b-4b5f-bc9a-93076b94a58d\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-0ee5-471a-876e-1bd2b92c6411\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-0ee5-471a-876e-1bd2b92c6411\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"74d9363f-588b-4824-959d-e2382a8ae7fd\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:12:08.74575\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-0ee5-471a-876e-1bd2b92c6411\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-0ee5-471a-876e-1bd2b92c6411\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-0ee5-471a-876e-1bd2b92c6411\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"74d9363f-588b-4824-959d-e2382a8ae7fd\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:12:08.9306926\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-0ee5-471a-876e-1bd2b92c6411\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-316b-4b5f-bc9a-93076b94a58d\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-316b-4b5f-bc9a-93076b94a58d\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"74d9363f-588b-4824-959d-e2382a8ae7fd\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:12:08.998423\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-316b-4b5f-bc9a-93076b94a58d\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-316b-4b5f-bc9a-93076b94a58d\",\"type\":\"Microsoft.Communication.PlayStarted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"16001e80-316b-4b5f-bc9a-93076b94a58d\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"74d9363f-588b-4824-959d-e2382a8ae7fd\",\"publicEventType\":\"Microsoft.Communication.PlayStarted\"},\"time\":\"2024-12-16T17:12:11.0255222\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-316b-4b5f-bc9a-93076b94a58d\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-316b-4b5f-bc9a-93076b94a58d\",\"type\":\"Microsoft.Communication.PlayCompleted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"16001e80-316b-4b5f-bc9a-93076b94a58d\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"74d9363f-588b-4824-959d-e2382a8ae7fd\",\"publicEventType\":\"Microsoft.Communication.PlayCompleted\"},\"time\":\"2024-12-16T17:12:17.4098016\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-316b-4b5f-bc9a-93076b94a58d\"}]"] \ No newline at end of file +["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"c10105df-684c-4992-8954-6677ec8f04c1\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-9356-4a4b-888f-eb46bfbfc06f\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"00002680-9356-4a4b-888f-eb46bfbfc06f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"c10105df-684c-4992-8954-6677ec8f04c1\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:09:15.3831389\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-9356-4a4b-888f-eb46bfbfc06f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-b751-4c98-af4e-e6e6231f7c8d\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-b751-4c98-af4e-e6e6231f7c8d\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"c10105df-684c-4992-8954-6677ec8f04c1\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:09:15.3763301\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-b751-4c98-af4e-e6e6231f7c8d\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-9356-4a4b-888f-eb46bfbfc06f\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-9356-4a4b-888f-eb46bfbfc06f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"c10105df-684c-4992-8954-6677ec8f04c1\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:09:15.3861631\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-9356-4a4b-888f-eb46bfbfc06f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-b751-4c98-af4e-e6e6231f7c8d\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"00002680-b751-4c98-af4e-e6e6231f7c8d\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"c10105df-684c-4992-8954-6677ec8f04c1\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:09:15.4835351\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-b751-4c98-af4e-e6e6231f7c8d\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-b751-4c98-af4e-e6e6231f7c8d\",\"type\":\"Microsoft.Communication.PlayStarted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"00002680-b751-4c98-af4e-e6e6231f7c8d\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"c10105df-684c-4992-8954-6677ec8f04c1\",\"publicEventType\":\"Microsoft.Communication.PlayStarted\"},\"time\":\"2025-03-05T05:09:20.0184554\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-b751-4c98-af4e-e6e6231f7c8d\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-b751-4c98-af4e-e6e6231f7c8d\",\"type\":\"Microsoft.Communication.PlayCompleted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"00002680-b751-4c98-af4e-e6e6231f7c8d\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"c10105df-684c-4992-8954-6677ec8f04c1\",\"publicEventType\":\"Microsoft.Communication.PlayCompleted\"},\"time\":\"2025-03-05T05:09:26.42697\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-b751-4c98-af4e-e6e6231f7c8d\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/playMultipleCombinedSourcesWithPlayMediaTest.json b/sdk/communication/azure-communication-callautomation/src/test/resources/playMultipleCombinedSourcesWithPlayMediaTest.json index 66f5014f6136..66c0e2e88a74 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/playMultipleCombinedSourcesWithPlayMediaTest.json +++ b/sdk/communication/azure-communication-callautomation/src/test/resources/playMultipleCombinedSourcesWithPlayMediaTest.json @@ -1 +1 @@ -["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"90928f9e-37f6-4f57-a834-1b0cd5b46d15\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-4391-4195-8135-da79fcc1b75b\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-4391-4195-8135-da79fcc1b75b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"90928f9e-37f6-4f57-a834-1b0cd5b46d15\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:12:21.83157\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-4391-4195-8135-da79fcc1b75b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-4391-4195-8135-da79fcc1b75b\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-4391-4195-8135-da79fcc1b75b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"90928f9e-37f6-4f57-a834-1b0cd5b46d15\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:12:21.8499899\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-4391-4195-8135-da79fcc1b75b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-cd22-484f-b549-14b9bae36edd\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-cd22-484f-b549-14b9bae36edd\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"90928f9e-37f6-4f57-a834-1b0cd5b46d15\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:12:21.8499899\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-cd22-484f-b549-14b9bae36edd\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-cd22-484f-b549-14b9bae36edd\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-cd22-484f-b549-14b9bae36edd\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"90928f9e-37f6-4f57-a834-1b0cd5b46d15\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:12:21.9217836\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-cd22-484f-b549-14b9bae36edd\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-cd22-484f-b549-14b9bae36edd\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":true},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-cd22-484f-b549-14b9bae36edd\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"90928f9e-37f6-4f57-a834-1b0cd5b46d15\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:12:24.4742945\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-cd22-484f-b549-14b9bae36edd\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-4391-4195-8135-da79fcc1b75b\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":true},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-4391-4195-8135-da79fcc1b75b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"90928f9e-37f6-4f57-a834-1b0cd5b46d15\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:12:24.4730985\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-4391-4195-8135-da79fcc1b75b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-cd22-484f-b549-14b9bae36edd\",\"type\":\"Microsoft.Communication.PlayStarted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"16001e80-cd22-484f-b549-14b9bae36edd\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"90928f9e-37f6-4f57-a834-1b0cd5b46d15\",\"publicEventType\":\"Microsoft.Communication.PlayStarted\"},\"time\":\"2024-12-16T17:12:25.3918491\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-cd22-484f-b549-14b9bae36edd\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-cd22-484f-b549-14b9bae36edd\",\"type\":\"Microsoft.Communication.PlayCompleted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"16001e80-cd22-484f-b549-14b9bae36edd\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"90928f9e-37f6-4f57-a834-1b0cd5b46d15\",\"publicEventType\":\"Microsoft.Communication.PlayCompleted\"},\"time\":\"2024-12-16T17:12:31.8222835\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-cd22-484f-b549-14b9bae36edd\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-4391-4195-8135-da79fcc1b75b\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":5,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-4391-4195-8135-da79fcc1b75b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"90928f9e-37f6-4f57-a834-1b0cd5b46d15\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:12:31.8447519\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-4391-4195-8135-da79fcc1b75b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-cd22-484f-b549-14b9bae36edd\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":5,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-cd22-484f-b549-14b9bae36edd\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"90928f9e-37f6-4f57-a834-1b0cd5b46d15\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:12:31.8447519\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-cd22-484f-b549-14b9bae36edd\"}]"] \ No newline at end of file +["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"6a3bdb74-6cca-4964-b544-74c1a9301b8a\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-9832-4e1c-bc5b-5b9acd3b2f7b\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"00002680-9832-4e1c-bc5b-5b9acd3b2f7b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6a3bdb74-6cca-4964-b544-74c1a9301b8a\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:09:35.6617539\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-9832-4e1c-bc5b-5b9acd3b2f7b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-a41a-4aac-9c52-7149a7b0344f\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-a41a-4aac-9c52-7149a7b0344f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6a3bdb74-6cca-4964-b544-74c1a9301b8a\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:09:35.6548122\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-a41a-4aac-9c52-7149a7b0344f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-9832-4e1c-bc5b-5b9acd3b2f7b\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-9832-4e1c-bc5b-5b9acd3b2f7b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6a3bdb74-6cca-4964-b544-74c1a9301b8a\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:09:35.6562069\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-9832-4e1c-bc5b-5b9acd3b2f7b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-a41a-4aac-9c52-7149a7b0344f\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"00002680-a41a-4aac-9c52-7149a7b0344f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6a3bdb74-6cca-4964-b544-74c1a9301b8a\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:09:35.7724452\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-a41a-4aac-9c52-7149a7b0344f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-9832-4e1c-bc5b-5b9acd3b2f7b\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":true},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-9832-4e1c-bc5b-5b9acd3b2f7b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6a3bdb74-6cca-4964-b544-74c1a9301b8a\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:09:39.8231573\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-9832-4e1c-bc5b-5b9acd3b2f7b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-a41a-4aac-9c52-7149a7b0344f\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":true},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-a41a-4aac-9c52-7149a7b0344f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6a3bdb74-6cca-4964-b544-74c1a9301b8a\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:09:39.8231573\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-a41a-4aac-9c52-7149a7b0344f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-a41a-4aac-9c52-7149a7b0344f\",\"type\":\"Microsoft.Communication.PlayStarted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"00002680-a41a-4aac-9c52-7149a7b0344f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6a3bdb74-6cca-4964-b544-74c1a9301b8a\",\"publicEventType\":\"Microsoft.Communication.PlayStarted\"},\"time\":\"2025-03-05T05:09:41.3865239\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-a41a-4aac-9c52-7149a7b0344f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-a41a-4aac-9c52-7149a7b0344f\",\"type\":\"Microsoft.Communication.PlayCompleted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"00002680-a41a-4aac-9c52-7149a7b0344f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6a3bdb74-6cca-4964-b544-74c1a9301b8a\",\"publicEventType\":\"Microsoft.Communication.PlayCompleted\"},\"time\":\"2025-03-05T05:09:47.8448204\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-a41a-4aac-9c52-7149a7b0344f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-a41a-4aac-9c52-7149a7b0344f\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":5,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-a41a-4aac-9c52-7149a7b0344f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6a3bdb74-6cca-4964-b544-74c1a9301b8a\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:09:47.8675283\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-a41a-4aac-9c52-7149a7b0344f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-9832-4e1c-bc5b-5b9acd3b2f7b\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":5,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-9832-4e1c-bc5b-5b9acd3b2f7b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"6a3bdb74-6cca-4964-b544-74c1a9301b8a\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:09:47.8637087\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-9832-4e1c-bc5b-5b9acd3b2f7b\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/playMultipleFileSourcesWhenParticipantOnHoldTest.json b/sdk/communication/azure-communication-callautomation/src/test/resources/playMultipleFileSourcesWhenParticipantOnHoldTest.json new file mode 100644 index 000000000000..5475c9ff09ff --- /dev/null +++ b/sdk/communication/azure-communication-callautomation/src/test/resources/playMultipleFileSourcesWhenParticipantOnHoldTest.json @@ -0,0 +1 @@ +["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"987aa996-a9f3-40bf-94a2-f7737fdd8963\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-0b30-4194-900c-399f079be4e9\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-0b30-4194-900c-399f079be4e9\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"987aa996-a9f3-40bf-94a2-f7737fdd8963\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:07:20.4810656\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-0b30-4194-900c-399f079be4e9\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-0b30-4194-900c-399f079be4e9\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"09002680-0b30-4194-900c-399f079be4e9\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"987aa996-a9f3-40bf-94a2-f7737fdd8963\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:07:20.4810656\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-0b30-4194-900c-399f079be4e9\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-3f46-4565-b27d-719cedd670e3\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-3f46-4565-b27d-719cedd670e3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"987aa996-a9f3-40bf-94a2-f7737fdd8963\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:07:20.4810656\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-3f46-4565-b27d-719cedd670e3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-3f46-4565-b27d-719cedd670e3\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"09002680-3f46-4565-b27d-719cedd670e3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"987aa996-a9f3-40bf-94a2-f7737fdd8963\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:07:20.512609\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-3f46-4565-b27d-719cedd670e3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-0b30-4194-900c-399f079be4e9\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":true}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-0b30-4194-900c-399f079be4e9\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"987aa996-a9f3-40bf-94a2-f7737fdd8963\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:07:24.8722385\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-0b30-4194-900c-399f079be4e9\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-3f46-4565-b27d-719cedd670e3\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":true}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-3f46-4565-b27d-719cedd670e3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"987aa996-a9f3-40bf-94a2-f7737fdd8963\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:07:24.8708139\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-3f46-4565-b27d-719cedd670e3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-3f46-4565-b27d-719cedd670e3\",\"type\":\"Microsoft.Communication.HoldAudioStarted\",\"data\":{\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-3f46-4565-b27d-719cedd670e3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"987aa996-a9f3-40bf-94a2-f7737fdd8963\",\"publicEventType\":\"Microsoft.Communication.HoldAudioStarted\"},\"time\":\"2025-03-05T05:07:25.55961\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-3f46-4565-b27d-719cedd670e3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-3f46-4565-b27d-719cedd670e3\",\"type\":\"Microsoft.Communication.HoldAudioPaused\",\"data\":{\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-3f46-4565-b27d-719cedd670e3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"987aa996-a9f3-40bf-94a2-f7737fdd8963\",\"publicEventType\":\"Microsoft.Communication.HoldAudioPaused\"},\"time\":\"2025-03-05T05:07:28.4959994\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-3f46-4565-b27d-719cedd670e3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-3f46-4565-b27d-719cedd670e3\",\"type\":\"Microsoft.Communication.PlayStarted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"09002680-3f46-4565-b27d-719cedd670e3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"987aa996-a9f3-40bf-94a2-f7737fdd8963\",\"publicEventType\":\"Microsoft.Communication.PlayStarted\"},\"time\":\"2025-03-05T05:07:28.5904312\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-3f46-4565-b27d-719cedd670e3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-3f46-4565-b27d-719cedd670e3\",\"type\":\"Microsoft.Communication.PlayCompleted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"09002680-3f46-4565-b27d-719cedd670e3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"987aa996-a9f3-40bf-94a2-f7737fdd8963\",\"publicEventType\":\"Microsoft.Communication.PlayCompleted\"},\"time\":\"2025-03-05T05:07:37.0723771\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-3f46-4565-b27d-719cedd670e3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-3f46-4565-b27d-719cedd670e3\",\"type\":\"Microsoft.Communication.HoldAudioResumed\",\"data\":{\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-3f46-4565-b27d-719cedd670e3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"987aa996-a9f3-40bf-94a2-f7737fdd8963\",\"publicEventType\":\"Microsoft.Communication.HoldAudioResumed\"},\"time\":\"2025-03-05T05:07:37.0757195\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-3f46-4565-b27d-719cedd670e3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-3f46-4565-b27d-719cedd670e3\",\"type\":\"Microsoft.Communication.HoldAudioCompleted\",\"data\":{\"resultInformation\":{\"code\":400,\"subCode\":8508,\"message\":\"Action falied, the operation was cancelled.\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-3f46-4565-b27d-719cedd670e3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"987aa996-a9f3-40bf-94a2-f7737fdd8963\",\"publicEventType\":\"Microsoft.Communication.HoldAudioCompleted\"},\"time\":\"2025-03-05T05:07:38.8190494\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-3f46-4565-b27d-719cedd670e3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-0b30-4194-900c-399f079be4e9\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":5,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-0b30-4194-900c-399f079be4e9\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"987aa996-a9f3-40bf-94a2-f7737fdd8963\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:07:38.900625\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-0b30-4194-900c-399f079be4e9\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-3f46-4565-b27d-719cedd670e3\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":5,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-3f46-4565-b27d-719cedd670e3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"987aa996-a9f3-40bf-94a2-f7737fdd8963\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:07:38.9001028\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-3f46-4565-b27d-719cedd670e3\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/playMultipleFileSourcesWithPlayMediaAllTest.json b/sdk/communication/azure-communication-callautomation/src/test/resources/playMultipleFileSourcesWithPlayMediaAllTest.json index fa4f93b1eed1..e1db7df9cbd4 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/playMultipleFileSourcesWithPlayMediaAllTest.json +++ b/sdk/communication/azure-communication-callautomation/src/test/resources/playMultipleFileSourcesWithPlayMediaAllTest.json @@ -1 +1 @@ -["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"499df6ee-c671-4d65-aab1-459ec40ad17f\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-2587-41fc-934d-213cdc480a03\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-2587-41fc-934d-213cdc480a03\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"499df6ee-c671-4d65-aab1-459ec40ad17f\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:11:40.93221\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-2587-41fc-934d-213cdc480a03\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-28e8-4174-a487-45e73851b31f\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-28e8-4174-a487-45e73851b31f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"499df6ee-c671-4d65-aab1-459ec40ad17f\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:11:40.93221\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-28e8-4174-a487-45e73851b31f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-2587-41fc-934d-213cdc480a03\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-2587-41fc-934d-213cdc480a03\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"499df6ee-c671-4d65-aab1-459ec40ad17f\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:11:41.0414032\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-2587-41fc-934d-213cdc480a03\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-28e8-4174-a487-45e73851b31f\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-28e8-4174-a487-45e73851b31f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"499df6ee-c671-4d65-aab1-459ec40ad17f\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:11:41.068059\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-28e8-4174-a487-45e73851b31f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-28e8-4174-a487-45e73851b31f\",\"type\":\"Microsoft.Communication.PlayStarted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"16001e80-28e8-4174-a487-45e73851b31f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"499df6ee-c671-4d65-aab1-459ec40ad17f\",\"publicEventType\":\"Microsoft.Communication.PlayStarted\"},\"time\":\"2024-12-16T17:11:41.9450023\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-28e8-4174-a487-45e73851b31f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-28e8-4174-a487-45e73851b31f\",\"type\":\"Microsoft.Communication.PlayCompleted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"16001e80-28e8-4174-a487-45e73851b31f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"499df6ee-c671-4d65-aab1-459ec40ad17f\",\"publicEventType\":\"Microsoft.Communication.PlayCompleted\"},\"time\":\"2024-12-16T17:11:50.4579183\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-28e8-4174-a487-45e73851b31f\"}]"] \ No newline at end of file +["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"0ae4ce89-1565-4c3c-9480-fc4579d920fe\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-bd9a-4964-abdd-a01fa862c675\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-bd9a-4964-abdd-a01fa862c675\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"0ae4ce89-1565-4c3c-9480-fc4579d920fe\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:08:33.3082004\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-bd9a-4964-abdd-a01fa862c675\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-027c-42c0-958f-ae8be373146f\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-027c-42c0-958f-ae8be373146f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"0ae4ce89-1565-4c3c-9480-fc4579d920fe\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:08:33.3144374\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-027c-42c0-958f-ae8be373146f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-027c-42c0-958f-ae8be373146f\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"00002680-027c-42c0-958f-ae8be373146f\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"0ae4ce89-1565-4c3c-9480-fc4579d920fe\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:08:33.3545829\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-027c-42c0-958f-ae8be373146f\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-bd9a-4964-abdd-a01fa862c675\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"00002680-bd9a-4964-abdd-a01fa862c675\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"0ae4ce89-1565-4c3c-9480-fc4579d920fe\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:08:33.4025175\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-bd9a-4964-abdd-a01fa862c675\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-bd9a-4964-abdd-a01fa862c675\",\"type\":\"Microsoft.Communication.PlayStarted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"00002680-bd9a-4964-abdd-a01fa862c675\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"0ae4ce89-1565-4c3c-9480-fc4579d920fe\",\"publicEventType\":\"Microsoft.Communication.PlayStarted\"},\"time\":\"2025-03-05T05:08:36.2223199\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-bd9a-4964-abdd-a01fa862c675\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-bd9a-4964-abdd-a01fa862c675\",\"type\":\"Microsoft.Communication.PlayCompleted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"00002680-bd9a-4964-abdd-a01fa862c675\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"0ae4ce89-1565-4c3c-9480-fc4579d920fe\",\"publicEventType\":\"Microsoft.Communication.PlayCompleted\"},\"time\":\"2025-03-05T05:08:44.6860623\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-bd9a-4964-abdd-a01fa862c675\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/playMultipleFileSourcesWithPlayMediaTest.json b/sdk/communication/azure-communication-callautomation/src/test/resources/playMultipleFileSourcesWithPlayMediaTest.json index ab025a70c6d0..1bec9e689fb4 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/playMultipleFileSourcesWithPlayMediaTest.json +++ b/sdk/communication/azure-communication-callautomation/src/test/resources/playMultipleFileSourcesWithPlayMediaTest.json @@ -1 +1 @@ -["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"21ada2ef-99b8-45f1-aaa3-0262ad38a4e2\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-b2d7-4dbe-ad0f-ec1e3aa10bd9\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-b2d7-4dbe-ad0f-ec1e3aa10bd9\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"21ada2ef-99b8-45f1-aaa3-0262ad38a4e2\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:11:11.3423005\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-b2d7-4dbe-ad0f-ec1e3aa10bd9\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-ddf2-4481-8026-591590c36305\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-ddf2-4481-8026-591590c36305\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"21ada2ef-99b8-45f1-aaa3-0262ad38a4e2\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:11:11.3376526\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-ddf2-4481-8026-591590c36305\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-ddf2-4481-8026-591590c36305\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-ddf2-4481-8026-591590c36305\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"21ada2ef-99b8-45f1-aaa3-0262ad38a4e2\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:11:11.4995484\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-ddf2-4481-8026-591590c36305\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-b2d7-4dbe-ad0f-ec1e3aa10bd9\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-b2d7-4dbe-ad0f-ec1e3aa10bd9\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"21ada2ef-99b8-45f1-aaa3-0262ad38a4e2\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:11:11.4790955\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-b2d7-4dbe-ad0f-ec1e3aa10bd9\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-b2d7-4dbe-ad0f-ec1e3aa10bd9\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":true}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-b2d7-4dbe-ad0f-ec1e3aa10bd9\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"21ada2ef-99b8-45f1-aaa3-0262ad38a4e2\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:11:14.0960697\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-b2d7-4dbe-ad0f-ec1e3aa10bd9\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-ddf2-4481-8026-591590c36305\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":true}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-ddf2-4481-8026-591590c36305\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"21ada2ef-99b8-45f1-aaa3-0262ad38a4e2\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:11:14.0960697\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-ddf2-4481-8026-591590c36305\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-ddf2-4481-8026-591590c36305\",\"type\":\"Microsoft.Communication.PlayStarted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"16001e80-ddf2-4481-8026-591590c36305\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"21ada2ef-99b8-45f1-aaa3-0262ad38a4e2\",\"publicEventType\":\"Microsoft.Communication.PlayStarted\"},\"time\":\"2024-12-16T17:11:14.5715183\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-ddf2-4481-8026-591590c36305\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-ddf2-4481-8026-591590c36305\",\"type\":\"Microsoft.Communication.PlayCompleted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"16001e80-ddf2-4481-8026-591590c36305\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"21ada2ef-99b8-45f1-aaa3-0262ad38a4e2\",\"publicEventType\":\"Microsoft.Communication.PlayCompleted\"},\"time\":\"2024-12-16T17:11:23.2179029\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-ddf2-4481-8026-591590c36305\"}]"] \ No newline at end of file +["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"a13c2afd-1cb4-438c-9184-c6232e38b86a\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-9d88-4312-84d1-4e54ff22de3b\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-9d88-4312-84d1-4e54ff22de3b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a13c2afd-1cb4-438c-9184-c6232e38b86a\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:07:51.3167081\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-9d88-4312-84d1-4e54ff22de3b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-3574-4a62-9ff0-b4a75afbb8b7\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-3574-4a62-9ff0-b4a75afbb8b7\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a13c2afd-1cb4-438c-9184-c6232e38b86a\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:07:51.3130214\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-3574-4a62-9ff0-b4a75afbb8b7\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-3574-4a62-9ff0-b4a75afbb8b7\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"00002680-3574-4a62-9ff0-b4a75afbb8b7\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a13c2afd-1cb4-438c-9184-c6232e38b86a\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:07:51.3280513\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-3574-4a62-9ff0-b4a75afbb8b7\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-9d88-4312-84d1-4e54ff22de3b\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"09002680-9d88-4312-84d1-4e54ff22de3b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a13c2afd-1cb4-438c-9184-c6232e38b86a\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:07:51.4151285\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-9d88-4312-84d1-4e54ff22de3b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-3574-4a62-9ff0-b4a75afbb8b7\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":true},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-3574-4a62-9ff0-b4a75afbb8b7\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a13c2afd-1cb4-438c-9184-c6232e38b86a\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:07:55.4615213\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-3574-4a62-9ff0-b4a75afbb8b7\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-9d88-4312-84d1-4e54ff22de3b\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":true},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-9d88-4312-84d1-4e54ff22de3b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a13c2afd-1cb4-438c-9184-c6232e38b86a\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:07:55.4678785\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-9d88-4312-84d1-4e54ff22de3b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-9d88-4312-84d1-4e54ff22de3b\",\"type\":\"Microsoft.Communication.PlayStarted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"09002680-9d88-4312-84d1-4e54ff22de3b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a13c2afd-1cb4-438c-9184-c6232e38b86a\",\"publicEventType\":\"Microsoft.Communication.PlayStarted\"},\"time\":\"2025-03-05T05:07:56.1592327\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-9d88-4312-84d1-4e54ff22de3b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-9d88-4312-84d1-4e54ff22de3b\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":5,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"09002680-9d88-4312-84d1-4e54ff22de3b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a13c2afd-1cb4-438c-9184-c6232e38b86a\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:08:04.7077106\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-9d88-4312-84d1-4e54ff22de3b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/09002680-9d88-4312-84d1-4e54ff22de3b\",\"type\":\"Microsoft.Communication.PlayCompleted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"09002680-9d88-4312-84d1-4e54ff22de3b\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a13c2afd-1cb4-438c-9184-c6232e38b86a\",\"publicEventType\":\"Microsoft.Communication.PlayCompleted\"},\"time\":\"2025-03-05T05:08:04.6864093\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/09002680-9d88-4312-84d1-4e54ff22de3b\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-3574-4a62-9ff0-b4a75afbb8b7\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":5,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-3574-4a62-9ff0-b4a75afbb8b7\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a13c2afd-1cb4-438c-9184-c6232e38b86a\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:08:04.7068903\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-3574-4a62-9ff0-b4a75afbb8b7\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/playMultipleTextSourcesWithPlayMediaAllTest.json b/sdk/communication/azure-communication-callautomation/src/test/resources/playMultipleTextSourcesWithPlayMediaAllTest.json index 670f55e81d95..f6527fe59285 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/playMultipleTextSourcesWithPlayMediaAllTest.json +++ b/sdk/communication/azure-communication-callautomation/src/test/resources/playMultipleTextSourcesWithPlayMediaAllTest.json @@ -1 +1 @@ -["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"a0d5f0af-92f9-46df-bc15-6f01c2466767\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-e93a-47c6-81e2-4286094d78c3\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-e93a-47c6-81e2-4286094d78c3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a0d5f0af-92f9-46df-bc15-6f01c2466767\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:12:36.4943602\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-e93a-47c6-81e2-4286094d78c3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-ff9e-4cba-ad70-cbb3ae70a3cf\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-ff9e-4cba-ad70-cbb3ae70a3cf\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a0d5f0af-92f9-46df-bc15-6f01c2466767\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:12:36.4954146\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-ff9e-4cba-ad70-cbb3ae70a3cf\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-e93a-47c6-81e2-4286094d78c3\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-e93a-47c6-81e2-4286094d78c3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a0d5f0af-92f9-46df-bc15-6f01c2466767\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:12:36.6733845\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-e93a-47c6-81e2-4286094d78c3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-ff9e-4cba-ad70-cbb3ae70a3cf\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-ff9e-4cba-ad70-cbb3ae70a3cf\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a0d5f0af-92f9-46df-bc15-6f01c2466767\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:12:36.6995989\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-ff9e-4cba-ad70-cbb3ae70a3cf\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-ff9e-4cba-ad70-cbb3ae70a3cf\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":true}],\"sequenceNumber\":4,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-ff9e-4cba-ad70-cbb3ae70a3cf\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a0d5f0af-92f9-46df-bc15-6f01c2466767\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:12:39.7724345\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-ff9e-4cba-ad70-cbb3ae70a3cf\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-e93a-47c6-81e2-4286094d78c3\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":true}],\"sequenceNumber\":4,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-e93a-47c6-81e2-4286094d78c3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a0d5f0af-92f9-46df-bc15-6f01c2466767\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:12:39.7707576\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-e93a-47c6-81e2-4286094d78c3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-ff9e-4cba-ad70-cbb3ae70a3cf\",\"type\":\"Microsoft.Communication.PlayStarted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"16001e80-ff9e-4cba-ad70-cbb3ae70a3cf\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a0d5f0af-92f9-46df-bc15-6f01c2466767\",\"publicEventType\":\"Microsoft.Communication.PlayStarted\"},\"time\":\"2024-12-16T17:12:40.7819407\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-ff9e-4cba-ad70-cbb3ae70a3cf\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-e93a-47c6-81e2-4286094d78c3\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":5,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-e93a-47c6-81e2-4286094d78c3\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a0d5f0af-92f9-46df-bc15-6f01c2466767\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:12:45.3338658\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-e93a-47c6-81e2-4286094d78c3\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-ff9e-4cba-ad70-cbb3ae70a3cf\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":5,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-ff9e-4cba-ad70-cbb3ae70a3cf\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a0d5f0af-92f9-46df-bc15-6f01c2466767\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:12:45.3338658\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-ff9e-4cba-ad70-cbb3ae70a3cf\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-ff9e-4cba-ad70-cbb3ae70a3cf\",\"type\":\"Microsoft.Communication.PlayCompleted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"16001e80-ff9e-4cba-ad70-cbb3ae70a3cf\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"a0d5f0af-92f9-46df-bc15-6f01c2466767\",\"publicEventType\":\"Microsoft.Communication.PlayCompleted\"},\"time\":\"2024-12-16T17:12:45.3067262\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-ff9e-4cba-ad70-cbb3ae70a3cf\"}]"] \ No newline at end of file +["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"51770722-c7d9-4ea4-bb33-003ac9f5943c\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-38fe-451a-ad0f-591871adeded\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-38fe-451a-ad0f-591871adeded\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"51770722-c7d9-4ea4-bb33-003ac9f5943c\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:09:56.9758725\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-38fe-451a-ad0f-591871adeded\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-54e4-4719-85f5-e0a52ec5ff07\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-54e4-4719-85f5-e0a52ec5ff07\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"51770722-c7d9-4ea4-bb33-003ac9f5943c\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:09:56.9608317\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-54e4-4719-85f5-e0a52ec5ff07\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-38fe-451a-ad0f-591871adeded\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"00002680-38fe-451a-ad0f-591871adeded\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"51770722-c7d9-4ea4-bb33-003ac9f5943c\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:09:56.9915383\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-38fe-451a-ad0f-591871adeded\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-54e4-4719-85f5-e0a52ec5ff07\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"00002680-54e4-4719-85f5-e0a52ec5ff07\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"51770722-c7d9-4ea4-bb33-003ac9f5943c\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:09:57.1219019\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-54e4-4719-85f5-e0a52ec5ff07\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-38fe-451a-ad0f-591871adeded\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":true},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-38fe-451a-ad0f-591871adeded\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"51770722-c7d9-4ea4-bb33-003ac9f5943c\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:10:01.3020749\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-38fe-451a-ad0f-591871adeded\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-54e4-4719-85f5-e0a52ec5ff07\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":true},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-54e4-4719-85f5-e0a52ec5ff07\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"51770722-c7d9-4ea4-bb33-003ac9f5943c\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:10:01.3020749\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-54e4-4719-85f5-e0a52ec5ff07\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-54e4-4719-85f5-e0a52ec5ff07\",\"type\":\"Microsoft.Communication.PlayStarted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"00002680-54e4-4719-85f5-e0a52ec5ff07\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"51770722-c7d9-4ea4-bb33-003ac9f5943c\",\"publicEventType\":\"Microsoft.Communication.PlayStarted\"},\"time\":\"2025-03-05T05:10:02.8798758\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-54e4-4719-85f5-e0a52ec5ff07\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-54e4-4719-85f5-e0a52ec5ff07\",\"type\":\"Microsoft.Communication.PlayCompleted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"00002680-54e4-4719-85f5-e0a52ec5ff07\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"51770722-c7d9-4ea4-bb33-003ac9f5943c\",\"publicEventType\":\"Microsoft.Communication.PlayCompleted\"},\"time\":\"2025-03-05T05:10:07.3180004\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-54e4-4719-85f5-e0a52ec5ff07\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-54e4-4719-85f5-e0a52ec5ff07\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":5,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-54e4-4719-85f5-e0a52ec5ff07\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"51770722-c7d9-4ea4-bb33-003ac9f5943c\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:10:07.3337147\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-54e4-4719-85f5-e0a52ec5ff07\"}]"] \ No newline at end of file diff --git a/sdk/communication/azure-communication-callautomation/src/test/resources/playMultipleTextSourcesWithPlayMediaTest.json b/sdk/communication/azure-communication-callautomation/src/test/resources/playMultipleTextSourcesWithPlayMediaTest.json index cc4729565adb..a76333f087e4 100644 --- a/sdk/communication/azure-communication-callautomation/src/test/resources/playMultipleTextSourcesWithPlayMediaTest.json +++ b/sdk/communication/azure-communication-callautomation/src/test/resources/playMultipleTextSourcesWithPlayMediaTest.json @@ -1 +1 @@ -["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"5323676f-7035-410b-afab-0605212d9b3b\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-76ba-493d-add9-6690cb548339\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-76ba-493d-add9-6690cb548339\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"5323676f-7035-410b-afab-0605212d9b3b\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:11:27.403765\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-76ba-493d-add9-6690cb548339\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-9cf1-48bc-a4ce-372e38bee581\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-9cf1-48bc-a4ce-372e38bee581\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"5323676f-7035-410b-afab-0605212d9b3b\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:11:27.403765\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-9cf1-48bc-a4ce-372e38bee581\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-76ba-493d-add9-6690cb548339\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-76ba-493d-add9-6690cb548339\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"5323676f-7035-410b-afab-0605212d9b3b\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:11:27.5418711\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-76ba-493d-add9-6690cb548339\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-9cf1-48bc-a4ce-372e38bee581\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"16001e80-9cf1-48bc-a4ce-372e38bee581\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"5323676f-7035-410b-afab-0605212d9b3b\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2024-12-16T17:11:27.5737102\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-9cf1-48bc-a4ce-372e38bee581\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-76ba-493d-add9-6690cb548339\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":true},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-76ba-493d-add9-6690cb548339\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"5323676f-7035-410b-afab-0605212d9b3b\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:11:30.0467528\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-76ba-493d-add9-6690cb548339\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-9cf1-48bc-a4ce-372e38bee581\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":true},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-9cf1-48bc-a4ce-372e38bee581\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"5323676f-7035-410b-afab-0605212d9b3b\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:11:30.0467528\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-9cf1-48bc-a4ce-372e38bee581\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-9cf1-48bc-a4ce-372e38bee581\",\"type\":\"Microsoft.Communication.PlayStarted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"16001e80-9cf1-48bc-a4ce-372e38bee581\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"5323676f-7035-410b-afab-0605212d9b3b\",\"publicEventType\":\"Microsoft.Communication.PlayStarted\"},\"time\":\"2024-12-16T17:11:31.0316545\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-9cf1-48bc-a4ce-372e38bee581\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-9cf1-48bc-a4ce-372e38bee581\",\"type\":\"Microsoft.Communication.PlayCompleted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"16001e80-9cf1-48bc-a4ce-372e38bee581\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"5323676f-7035-410b-afab-0605212d9b3b\",\"publicEventType\":\"Microsoft.Communication.PlayCompleted\"},\"time\":\"2024-12-16T17:11:35.4876991\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-9cf1-48bc-a4ce-372e38bee581\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-9cf1-48bc-a4ce-372e38bee581\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":5,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-9cf1-48bc-a4ce-372e38bee581\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"5323676f-7035-410b-afab-0605212d9b3b\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:11:35.5100724\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-9cf1-48bc-a4ce-372e38bee581\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/16001e80-76ba-493d-add9-6690cb548339\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":5,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"16001e80-76ba-493d-add9-6690cb548339\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"5323676f-7035-410b-afab-0605212d9b3b\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2024-12-16T17:11:35.5101237\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/16001e80-76ba-493d-add9-6690cb548339\"}]"] \ No newline at end of file +["{\"to\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"from\":{\"kind\":\"communicationUser\",\"rawId\":\"REDACTED\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"serverCallId\":\"REDACTED\",\"callerDisplayName\":\"\",\"incomingCallContext\":\"REDACTED\",\"correlationId\":\"e1d3849d-2d55-497a-8829-9def9e225787\"}","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-0aa8-4f75-891a-5aec1a28d4ef\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-0aa8-4f75-891a-5aec1a28d4ef\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"e1d3849d-2d55-497a-8829-9def9e225787\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:08:13.9102397\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-0aa8-4f75-891a-5aec1a28d4ef\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-5942-4ba1-9078-66ccb0671665\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":1,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-5942-4ba1-9078-66ccb0671665\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"e1d3849d-2d55-497a-8829-9def9e225787\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:08:13.9102397\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-5942-4ba1-9078-66ccb0671665\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-0aa8-4f75-891a-5aec1a28d4ef\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"00002680-0aa8-4f75-891a-5aec1a28d4ef\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"e1d3849d-2d55-497a-8829-9def9e225787\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:08:13.925914\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-0aa8-4f75-891a-5aec1a28d4ef\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-5942-4ba1-9078-66ccb0671665\",\"type\":\"Microsoft.Communication.CallConnected\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"callConnectionId\":\"00002680-5942-4ba1-9078-66ccb0671665\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"e1d3849d-2d55-497a-8829-9def9e225787\",\"publicEventType\":\"Microsoft.Communication.CallConnected\"},\"time\":\"2025-03-05T05:08:13.9739143\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-5942-4ba1-9078-66ccb0671665\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-5942-4ba1-9078-66ccb0671665\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":true},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-5942-4ba1-9078-66ccb0671665\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"e1d3849d-2d55-497a-8829-9def9e225787\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:08:18.1852333\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-5942-4ba1-9078-66ccb0671665\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-0aa8-4f75-891a-5aec1a28d4ef\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":true},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":3,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-0aa8-4f75-891a-5aec1a28d4ef\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"e1d3849d-2d55-497a-8829-9def9e225787\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:08:18.1852333\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-0aa8-4f75-891a-5aec1a28d4ef\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-5942-4ba1-9078-66ccb0671665\",\"type\":\"Microsoft.Communication.PlayStarted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"00002680-5942-4ba1-9078-66ccb0671665\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"e1d3849d-2d55-497a-8829-9def9e225787\",\"publicEventType\":\"Microsoft.Communication.PlayStarted\"},\"time\":\"2025-03-05T05:08:19.9953987\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-5942-4ba1-9078-66ccb0671665\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-5942-4ba1-9078-66ccb0671665\",\"type\":\"Microsoft.Communication.PlayCompleted\",\"data\":{\"version\":\"2024-09-01-preview\",\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"Action completed successfully.\"},\"callConnectionId\":\"00002680-5942-4ba1-9078-66ccb0671665\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"e1d3849d-2d55-497a-8829-9def9e225787\",\"publicEventType\":\"Microsoft.Communication.PlayCompleted\"},\"time\":\"2025-03-05T05:08:24.4084005\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-5942-4ba1-9078-66ccb0671665\"}]","[{\"id\":\"REDACTED\",\"source\":\"calling/callConnections/00002680-5942-4ba1-9078-66ccb0671665\",\"type\":\"Microsoft.Communication.ParticipantsUpdated\",\"data\":{\"participants\":[{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false},{\"identifier\":{\"rawId\":\"REDACTED\",\"kind\":\"communicationUser\",\"communicationUser\":{\"id\":\"REDACTED\"}},\"isMuted\":false,\"isOnHold\":false}],\"sequenceNumber\":5,\"resultInformation\":{\"code\":200,\"subCode\":0,\"message\":\"\"},\"version\":\"2024-09-01-preview\",\"callConnectionId\":\"00002680-5942-4ba1-9078-66ccb0671665\",\"serverCallId\":\"REDACTED\",\"correlationId\":\"e1d3849d-2d55-497a-8829-9def9e225787\",\"publicEventType\":\"Microsoft.Communication.ParticipantsUpdated\"},\"time\":\"2025-03-05T05:08:24.4558662\\u002B00:00\",\"specversion\":\"1.0\",\"datacontenttype\":\"application/json\",\"subject\":\"calling/callConnections/00002680-5942-4ba1-9078-66ccb0671665\"}]"] \ 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 671f69250d3a..2f586f56dbc7 100644 --- a/sdk/communication/azure-communication-callautomation/swagger/README.md +++ b/sdk/communication/azure-communication-callautomation/swagger/README.md @@ -32,7 +32,7 @@ autorest README.md --java --v4 tag: package-2024-09-01-preview use: '@autorest/java@4.1.29' require: - - https://github.com/Azure/azure-rest-api-specs/blob/691fea3efb9ff22b20904e92d5116223f452a3b1/specification/communication/data-plane/CallAutomation/readme.md + - https://github.com/Azure/azure-rest-api-specs/blob/d1bedfa9c084a2e3f9cbeb075c532d691c3c0095/specification/communication/data-plane/CallAutomation/readme.md java: true output-folder: ../ license-header: MICROSOFT_MIT_SMALL diff --git a/sdk/communication/azure-communication-callingserver/pom.xml b/sdk/communication/azure-communication-callingserver/pom.xml index 17c1ca914a01..d92aeb12e503 100644 --- a/sdk/communication/azure-communication-callingserver/pom.xml +++ b/sdk/communication/azure-communication-callingserver/pom.xml @@ -58,28 +58,28 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-communication-common - 1.3.9 + 1.3.10 com.azure azure-communication-identity - 1.6.2 + 1.6.3 test com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test @@ -117,7 +117,7 @@ com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/communication/azure-communication-chat/CHANGELOG.md b/sdk/communication/azure-communication-chat/CHANGELOG.md index 1b6334c9f10a..e544e7a63a43 100644 --- a/sdk/communication/azure-communication-chat/CHANGELOG.md +++ b/sdk/communication/azure-communication-chat/CHANGELOG.md @@ -10,6 +10,16 @@ ### Other Changes +## 1.5.8 (2025-03-03) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-communication-common` from `1.3.8` to version `1.3.9`. +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`. +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. + ## 1.5.7 (2024-12-04) ### Other Changes diff --git a/sdk/communication/azure-communication-chat/README.md b/sdk/communication/azure-communication-chat/README.md index 7d3bcdd30af5..e60bf2d0d7dd 100644 --- a/sdk/communication/azure-communication-chat/README.md +++ b/sdk/communication/azure-communication-chat/README.md @@ -52,7 +52,7 @@ add the direct dependency to your project as follows. com.azure azure-communication-chat - 1.4.0 + 1.6.0-beta.1 ``` diff --git a/sdk/communication/azure-communication-chat/pom.xml b/sdk/communication/azure-communication-chat/pom.xml index c8e1b2d0e319..05c15ea6289e 100644 --- a/sdk/communication/azure-communication-chat/pom.xml +++ b/sdk/communication/azure-communication-chat/pom.xml @@ -54,28 +54,28 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-communication-common - 1.3.9 + 1.3.10 com.azure azure-communication-identity - 1.6.2 + 1.6.3 test com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test diff --git a/sdk/communication/azure-communication-common-perf/README.md b/sdk/communication/azure-communication-common-perf/README.md index 5f2e06e97767..535803a2d397 100644 --- a/sdk/communication/azure-communication-common-perf/README.md +++ b/sdk/communication/azure-communication-common-perf/README.md @@ -46,4 +46,4 @@ For details on contributing to this repository, see the [contributing guide](htt 1. Push to the branch (`git push origin my-new-feature`) 1. Create new Pull Request -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcommunication%2Fazure-communication-common-perf%2FREADME.png) + diff --git a/sdk/communication/azure-communication-common-perf/pom.xml b/sdk/communication/azure-communication-common-perf/pom.xml index 8d6b325d2b5c..9a98f64ff315 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.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 diff --git a/sdk/communication/azure-communication-common/CHANGELOG.md b/sdk/communication/azure-communication-common/CHANGELOG.md index 9a7beadad0fd..f5fdb3c9a2b2 100644 --- a/sdk/communication/azure-communication-common/CHANGELOG.md +++ b/sdk/communication/azure-communication-common/CHANGELOG.md @@ -10,6 +10,15 @@ ### Other Changes +## 1.3.10 (2025-03-03) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`. +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. + ## 1.3.9 (2024-12-04) ### Other Changes diff --git a/sdk/communication/azure-communication-common/README.md b/sdk/communication/azure-communication-common/README.md index 8223e0e607b8..5166f5d878fb 100644 --- a/sdk/communication/azure-communication-common/README.md +++ b/sdk/communication/azure-communication-common/README.md @@ -51,7 +51,7 @@ add the direct dependency to your project as follows. com.azure azure-communication-common - 1.3.0 + 1.4.0-beta.1 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/communication/azure-communication-common/pom.xml b/sdk/communication/azure-communication-common/pom.xml index e34a1b033c97..2b3397e3d02b 100644 --- a/sdk/communication/azure-communication-common/pom.xml +++ b/sdk/communication/azure-communication-common/pom.xml @@ -50,12 +50,12 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 compile diff --git a/sdk/communication/azure-communication-email/CHANGELOG.md b/sdk/communication/azure-communication-email/CHANGELOG.md index e2c4be6abbd2..76c2e15d6991 100644 --- a/sdk/communication/azure-communication-email/CHANGELOG.md +++ b/sdk/communication/azure-communication-email/CHANGELOG.md @@ -10,6 +10,15 @@ ### Other Changes +## 1.0.20 (2025-03-03) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-communication-common` from `1.3.8` to version `1.3.9`. +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`. +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. ## 1.0.19 (2024-12-04) diff --git a/sdk/communication/azure-communication-email/README.md b/sdk/communication/azure-communication-email/README.md index 95414424b677..f15e0f3ebbdc 100644 --- a/sdk/communication/azure-communication-email/README.md +++ b/sdk/communication/azure-communication-email/README.md @@ -57,7 +57,7 @@ add the direct dependency to your project as follows. com.azure azure-communication-email - 1.0.4 + 1.1.0-beta.2 ``` diff --git a/sdk/communication/azure-communication-email/pom.xml b/sdk/communication/azure-communication-email/pom.xml index 1ac419a6fbac..d978a9da9033 100644 --- a/sdk/communication/azure-communication-email/pom.xml +++ b/sdk/communication/azure-communication-email/pom.xml @@ -59,30 +59,30 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-communication-common - 1.3.9 + 1.3.10 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/communication/azure-communication-identity/CHANGELOG.md b/sdk/communication/azure-communication-identity/CHANGELOG.md index 609e6acc4177..86051b8f7ba6 100644 --- a/sdk/communication/azure-communication-identity/CHANGELOG.md +++ b/sdk/communication/azure-communication-identity/CHANGELOG.md @@ -10,6 +10,15 @@ ### Other Changes +## 1.6.3 (2025-03-03) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-communication-common` from `1.3.8` to version `1.3.9`. +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`. +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. ## 1.6.2 (2024-12-04) diff --git a/sdk/communication/azure-communication-identity/README.md b/sdk/communication/azure-communication-identity/README.md index c81570dddb62..9fc198e11525 100644 --- a/sdk/communication/azure-communication-identity/README.md +++ b/sdk/communication/azure-communication-identity/README.md @@ -55,7 +55,7 @@ add the direct dependency to your project as follows. com.azure azure-communication-identity - 1.6.0 + 1.7.0-beta.1 ``` @@ -239,4 +239,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [samples]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/communication/azure-communication-identity/src/samples/java/com/azure/communication/identity/ReadmeSamples.java [source]: https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/communication/azure-communication-identity/src -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcommunication%2Fazure-communication-identity%2FREADME.png) + diff --git a/sdk/communication/azure-communication-identity/pom.xml b/sdk/communication/azure-communication-identity/pom.xml index 38dea50d2a16..8b8bdacb8c8f 100644 --- a/sdk/communication/azure-communication-identity/pom.xml +++ b/sdk/communication/azure-communication-identity/pom.xml @@ -67,17 +67,17 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-communication-common - 1.3.9 + 1.3.10 com.nimbusds @@ -88,13 +88,13 @@ com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/communication/azure-communication-jobrouter/CHANGELOG.md b/sdk/communication/azure-communication-jobrouter/CHANGELOG.md index 578f3b504067..069449067f79 100644 --- a/sdk/communication/azure-communication-jobrouter/CHANGELOG.md +++ b/sdk/communication/azure-communication-jobrouter/CHANGELOG.md @@ -20,6 +20,16 @@ ### Other Changes +## 1.1.11 (2025-03-03) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-communication-common` from `1.3.8` to version `1.3.9`. +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`. +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. + ## 1.1.10 (2024-12-04) ### Other Changes diff --git a/sdk/communication/azure-communication-jobrouter/README.md b/sdk/communication/azure-communication-jobrouter/README.md index f15ef887cd79..7097cabcc17b 100644 --- a/sdk/communication/azure-communication-jobrouter/README.md +++ b/sdk/communication/azure-communication-jobrouter/README.md @@ -51,7 +51,7 @@ add the direct dependency to your project as follows. com.azure azure-communication-jobrouter - 2.0.0 + 2.0.0-beta.1 ``` @@ -255,4 +255,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ [coc_contact]: mailto:opencode@microsoft.com -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcommunication%2Fazure-communication-jobrouter%2FREADME.png) + diff --git a/sdk/communication/azure-communication-jobrouter/pom.xml b/sdk/communication/azure-communication-jobrouter/pom.xml index 71ac75bb9e8d..c76b27d25445 100644 --- a/sdk/communication/azure-communication-jobrouter/pom.xml +++ b/sdk/communication/azure-communication-jobrouter/pom.xml @@ -55,22 +55,22 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-communication-common - 1.3.9 + 1.3.10 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test diff --git a/sdk/communication/azure-communication-messages/CHANGELOG.md b/sdk/communication/azure-communication-messages/CHANGELOG.md index 31543dd4c2b3..98702f7203e3 100644 --- a/sdk/communication/azure-communication-messages/CHANGELOG.md +++ b/sdk/communication/azure-communication-messages/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.2.0-beta.1 (Unreleased) +## 1.2.0-beta.2 (Unreleased) ### Features Added @@ -10,6 +10,24 @@ ### Other Changes +## 1.1.2 (2025-03-03) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-communication-common` from `1.3.8` to version `1.3.9`. +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`. +- Upgraded `azure-json` from `1.3.0` to version `1.4.0`. +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. + +## 1.2.0-beta.1 (2025-02-11) + +### Features Added +- Added Interactive Message. +- Added Reaction Message. +- Added Sticker Message. + ## 1.1.1 (2024-12-04) @@ -24,7 +42,7 @@ ## 1.1.0 (2024-10-23) ### Features Added -- Added ImageNotificationContent to send image messgae. +- Added ImageNotificationContent to send image message. - Added DocumentNotificationContent to send document message. - Added VideoNotificationContent to send video message. - Added AudioNotificationContent to send audio message. diff --git a/sdk/communication/azure-communication-messages/README.md b/sdk/communication/azure-communication-messages/README.md index 1371d7ee2c6d..9833d5f5e92d 100644 --- a/sdk/communication/azure-communication-messages/README.md +++ b/sdk/communication/azure-communication-messages/README.md @@ -58,7 +58,7 @@ add the direct dependency to your project as follows. com.azure azure-communication-messages - 1.1.0 + 1.2.0-beta.2 ``` [//]: # ({x-version-update-end}) @@ -274,6 +274,127 @@ public void sendDocumentMessage() { result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId())); } ``` +```java readme-sample-sendStickerMessage +/* + * This sample shows how to send sticker message with below details + * Supported sticker type - (.webp) + * Note: Business cannot initiate conversation with media message. + * */ +public static void sendStickerMessage() { + //Update the Media URL + String mediaUrl = "https://www.gstatic.com/webp/gallery/1.sm.webp"; + List recipients = new ArrayList<>(); + recipients.add(""); + NotificationMessagesClient client = new NotificationMessagesClientBuilder() + .connectionString("") + .buildClient(); + SendMessageResult result = client.send( + new StickerNotificationContent("", recipients, mediaUrl)); + + result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId())); +} +``` +```java readme-sample-sendReactionMessage +/* + * This sample shows how to send reaction message with below details + * Emoji - unicode for emoji character. + * Reply Message ID - ID of the message to be replied with emoji + * Note: Business cannot initiate conversation with media message. + * */ +public static void sendReactionMessage() { + List recipients = new ArrayList<>(); + recipients.add(""); + NotificationMessagesClient client = new NotificationMessagesClientBuilder() + .connectionString("") + .buildClient(); + SendMessageResult result = client.send( + new ReactionNotificationContent("", recipients, "\uD83D\uDE00", "")); + + result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId())); +} +``` +```java readme-sample-sendInteractiveMessageWithButtonAction +/* + * This sample shows how to send interactive message with Button Action + * Note: Business cannot initiate conversation with interactive message. + * */ +public void sendInteractiveMessageWithButtonAction() { + List recipients = new ArrayList<>(); + recipients.add(""); + NotificationMessagesClient client = new NotificationMessagesClientBuilder() + .connectionString("") + .buildClient(); + List buttonActions = new ArrayList<>(); + buttonActions.add(new ButtonContent("no", "No")); + buttonActions.add(new ButtonContent("yes", "Yes")); + ButtonSetContent buttonSet = new ButtonSetContent(buttonActions); + InteractiveMessage interactiveMessage = new InteractiveMessage( + new TextMessageContent("Do you want to proceed?"), new WhatsAppButtonActionBindings(buttonSet)); + SendMessageResult result = client.send( + new InteractiveNotificationContent("", recipients, interactiveMessage)); + + result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId())); +} +``` +```java readme-sample-sendInteractiveMessageWithListAction +/* + * This sample shows how to send list action interactive message + * Note: Business cannot initiate conversation with interactive message. + * */ +public static void sendInteractiveMessageWithListAction() { + List group1 = new ArrayList<>(); + group1.add(new ActionGroupItem("priority_express", "Priority Mail Express", "Delivered on same day!")); + group1.add(new ActionGroupItem("priority_mail", "Priority Mail", "Delivered in 1-2 days")); + + List group2 = new ArrayList<>(); + group2.add(new ActionGroupItem("usps_ground_advantage", "USPS Ground Advantage", "Delivered in 2-5 days")); + group2.add(new ActionGroupItem("media_mail", "Media Mail", "Delivered in 5-8 days")); + + List options = new ArrayList<>(); + options.add(new ActionGroup("Express Delivery", group1)); + options.add(new ActionGroup("Normal Delivery", group2)); + + ActionGroupContent actionGroupContent = new ActionGroupContent("Shipping Options", options); + InteractiveMessage interactiveMessage = new InteractiveMessage( + new TextMessageContent("Which shipping option do you want?"), new WhatsAppListActionBindings(actionGroupContent)); + interactiveMessage.setFooter(new TextMessageContent("Eagle Logistic")); + interactiveMessage.setHeader(new TextMessageContent("Shipping Options")); + + List recipients = new ArrayList<>(); + recipients.add(""); + NotificationMessagesClient client = new NotificationMessagesClientBuilder() + .connectionString("") + .buildClient(); + SendMessageResult result = client.send( + new InteractiveNotificationContent("", recipients, interactiveMessage)); + + result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId())); + +} +``` +```java readme-sample-sendInteractiveMessageWithUrlAction +/* + * This sample shows how to send url action interactive message + * Note: Business cannot initiate conversation with interactive message. + * */ +public static void sendInteractiveMessageWithUrlAction() { + LinkContent urlAction = new LinkContent("Rocket is the best!", "https://wallpapercave.com/wp/wp2163723.jpg"); + InteractiveMessage interactiveMessage = new InteractiveMessage( + new TextMessageContent("The best Guardian of Galaxy"), new WhatsAppUrlActionBindings(urlAction)); + interactiveMessage.setFooter(new TextMessageContent("Intergalactic New Ltd")); + + List recipients = new ArrayList<>(); + recipients.add(""); + NotificationMessagesClient client = new NotificationMessagesClientBuilder() + .connectionString("") + .buildClient(); + SendMessageResult result = client.send( + new InteractiveNotificationContent("", recipients, interactiveMessage)); + + result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId())); +} +``` + ### Get Template List for given channel example: ```java readme-sample-ListTemplates MessageTemplateClient templateClient = @@ -331,4 +452,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [azure_portal]: https://portal.azure.com [azure_powershell]: https://learn.microsoft.com/powershell/module/az.communication/new-azcommunicationservice -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcommunication%2Fazure-communication-messages%2FREADME.png) + diff --git a/sdk/communication/azure-communication-messages/assets.json b/sdk/communication/azure-communication-messages/assets.json index 99d7da0bd362..f44dcf14cecd 100644 --- a/sdk/communication/azure-communication-messages/assets.json +++ b/sdk/communication/azure-communication-messages/assets.json @@ -2,5 +2,5 @@ "AssetsRepo" : "Azure/azure-sdk-assets", "AssetsRepoPrefixPath" : "java", "TagPrefix" : "java/communication/azure-communication-messages", - "Tag" : "java/communication/azure-communication-messages_d7c7441f3b" + "Tag" : "java/communication/azure-communication-messages_d7e86da684" } diff --git a/sdk/communication/azure-communication-messages/customization/src/main/java/MessagesSdkCustomization.java b/sdk/communication/azure-communication-messages/customization/src/main/java/MessagesSdkCustomization.java index cb534b0d5ec9..af713de649ae 100644 --- a/sdk/communication/azure-communication-messages/customization/src/main/java/MessagesSdkCustomization.java +++ b/sdk/communication/azure-communication-messages/customization/src/main/java/MessagesSdkCustomization.java @@ -8,6 +8,8 @@ import com.github.javaparser.ast.Modifier; import com.github.javaparser.ast.Node; import com.github.javaparser.ast.NodeList; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.Parameter; import com.github.javaparser.ast.stmt.BlockStmt; import com.github.javaparser.ast.type.ClassOrInterfaceType; import com.github.javaparser.javadoc.Javadoc; @@ -15,6 +17,10 @@ import com.github.javaparser.javadoc.description.JavadocSnippet; import org.slf4j.Logger; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + public class MessagesSdkCustomization extends Customization { @Override @@ -32,13 +38,24 @@ public void customize(LibraryCustomization libraryCustomization, Logger logger) customizeMessageTemplateLocation(modelsPackage); customizeMessageTemplateItemModel(modelsPackage); + //Handle Interactive message content models + updateModelClassModifierToAbstract(modelsPackage, "MessageContent"); + updateModelClassModifierToAbstract(modelsPackage, "ActionBindings"); + updateJavaDocForMethodFromJson(modelsPackage, "ActionBindings"); + updateJavaDocForMethodFromJson(modelsPackage, "MessageContent"); + customizeInteractiveMessage(modelsPackage); + PackageCustomization channelsModelsPackage = libraryCustomization.getPackage( "com.azure.communication.messages.models.channels"); updateWhatsAppMessageTemplateItemWithBinaryDataContent(channelsModelsPackage); - AddDeprecateAnnotationToMediaNotificationContent(modelsPackage); + addDeprecateAnnotationToMediaNotificationContent(modelsPackage); + + addDeprecateAnnotationForImageV0CommunicationKind(modelsPackage); - AddDeprecateAnnotationForImageV0CommunicationKind(modelsPackage); + customizeActionGroup(modelsPackage); + customizeActionGroupContent(modelsPackage); + customizeButtonSetContent(modelsPackage); } private void updateModelClassModifierToAbstract(PackageCustomization modelsPackage, String className) { @@ -174,6 +191,45 @@ private void customizeMessageTemplateLocation(PackageCustomization modelsPackage }); } + private void customizeInteractiveMessage(PackageCustomization modelsPackage) { + modelsPackage.getClass("InteractiveMessage").customizeAst(ast -> { + ast.getClassByName("InteractiveMessage").ifPresent(clazz -> { + clazz.addMethod("getHeader", Modifier.Keyword.PUBLIC) + .setType(clazz.getMethodsByName("getHeaderProperty").get(0).getType()) + .setBody(clazz.getMethodsByName("getHeaderProperty").get(0).getBody().get()) + .setJavadocComment(clazz.getMethodsByName("getHeaderProperty").get(0).getJavadocComment().get()); + + clazz.getMethodsByName("getHeaderProperty").forEach(Node::remove); + + MethodDeclaration setHeaderMethodDeclaration = clazz.getMethodsByName("setHeaderProperty").get(0); + List parameters = setHeaderMethodDeclaration + .getParameters() + .stream() + .map(p -> p.setName("header")) + .collect(Collectors.toList()); + String methodBodyContent = setHeaderMethodDeclaration + .getBody() + .get() + .toString() + .replace("headerProperty;", "header;"); + + String docComment = setHeaderMethodDeclaration + .getJavadocComment() + .get() + .getContent() + .replace("headerProperty", "header"); + + clazz.addMethod("setHeader", Modifier.Keyword.PUBLIC) + .setParameters(new NodeList(parameters)) + .setType(setHeaderMethodDeclaration.getType()) + .setBody(StaticJavaParser.parseBlock(methodBodyContent)) + .setJavadocComment(new Javadoc(JavadocDescription.parseText(docComment))); + + clazz.getMethodsByName("setHeaderProperty").forEach(Node::remove); + }); + }); + } + private void updateWhatsAppMessageTemplateItemWithBinaryDataContent(PackageCustomization channelsModelsPackage) { channelsModelsPackage.getClass("WhatsAppMessageTemplateItem").customizeAst(ast -> { // ast.addImport("com.azure.core.util.BinaryData"); @@ -206,7 +262,7 @@ private void removeJsonKnownDiscriminatorMethod(PackageCustomization modelPackag }); } - private void AddDeprecateAnnotationToMediaNotificationContent(PackageCustomization modelsPackage) { + private void addDeprecateAnnotationToMediaNotificationContent(PackageCustomization modelsPackage) { modelsPackage.getClass("MediaNotificationContent").customizeAst(ast -> { ast.getClassByName("MediaNotificationContent").ifPresent(clazz -> { clazz.addAnnotation(Deprecated.class); @@ -222,7 +278,7 @@ private void AddDeprecateAnnotationToMediaNotificationContent(PackageCustomizati }); } - private void AddDeprecateAnnotationForImageV0CommunicationKind(PackageCustomization modelsPackage) { + private void addDeprecateAnnotationForImageV0CommunicationKind(PackageCustomization modelsPackage) { modelsPackage.getClass("CommunicationMessageKind").customizeAst(ast -> { ast.getClassByName("CommunicationMessageKind") .flatMap(clazz -> clazz.getFieldByName("IMAGE_V0")) @@ -240,4 +296,72 @@ private void AddDeprecateAnnotationForImageV0CommunicationKind(PackageCustomiza }); }); } + + private void updateJavaDocForMethodFromJson(PackageCustomization modelPackage, String className) { + String originalDocText = String.format("@throws IOException If an error occurs while reading the %s.", className); + modelPackage.getClass(className).customizeAst(ast -> { + ast.getClassByName(className).ifPresent( clazz -> { + String fromJsonDoc = clazz.getMethodsByName("fromJson") + .get(0).getJavadoc().get().toText() + .replace(originalDocText, + "@throws IllegalStateException If the deserialized JSON object was missing any required properties.\n" + + originalDocText); + clazz.getMethodsByName("fromJson").get(0).setJavadocComment(fromJsonDoc); + }); + }); + } + + private void customizeActionGroup(PackageCustomization modelsPackage) { + modelsPackage.getClass("ActionGroup").customizeAst(ast -> { + ast.getClassByName("ActionGroup") + .flatMap(clazz -> clazz.getConstructorByParameterTypes(String.class, List.class)) + .ifPresent(c -> { + String body = c.getBody().toString().replace("this.items = items;", + "this.items = new ArrayList<>(items);"); + c.setBody(StaticJavaParser.parseBlock(body)); + }); + + ast.getClassByName("ActionGroup").ifPresent(clazz -> { + String getItemsBody = clazz.getMethodsByName("getItems").get(0).getBody().get().toString() + .replace("return this.items;", "return new ArrayList<>(this.items);"); + clazz.getMethodsByName("getItems").get(0).setBody(StaticJavaParser.parseBlock(getItemsBody)); + }); + }); + } + + private void customizeActionGroupContent(PackageCustomization modelsPackage) { + modelsPackage.getClass("ActionGroupContent").customizeAst(ast -> { + ast.getClassByName("ActionGroupContent") + .flatMap(clazz -> clazz.getConstructorByParameterTypes(String.class, List.class)) + .ifPresent(c -> { + String body = c.getBody().toString().replace("this.groups = groups;", + "this.groups = new ArrayList<>(groups);"); + c.setBody(StaticJavaParser.parseBlock(body)); + }); + + ast.getClassByName("ActionGroupContent").ifPresent(clazz -> { + String getItemsBody = clazz.getMethodsByName("getGroups").get(0).getBody().get().toString() + .replace("return this.groups;", "return new ArrayList<>(this.groups);"); + clazz.getMethodsByName("getGroups").get(0).setBody(StaticJavaParser.parseBlock(getItemsBody)); + }); + }); + } + + private void customizeButtonSetContent(PackageCustomization modelsPackage) { + modelsPackage.getClass("ButtonSetContent").customizeAst(ast -> { + ast.getClassByName("ButtonSetContent") + .flatMap(clazz -> clazz.getConstructorByParameterTypes(List.class)) + .ifPresent(c -> { + String body = c.getBody().toString().replace("this.buttons = buttons;", + "this.buttons = new ArrayList<>(buttons);"); + c.setBody(StaticJavaParser.parseBlock(body)); + }); + + ast.getClassByName("ButtonSetContent").ifPresent(clazz -> { + String getItemsBody = clazz.getMethodsByName("getButtons").get(0).getBody().get().toString() + .replace("return this.buttons;", "return new ArrayList<>(this.buttons);"); + clazz.getMethodsByName("getButtons").get(0).setBody(StaticJavaParser.parseBlock(getItemsBody)); + }); + }); + } } diff --git a/sdk/communication/azure-communication-messages/pom.xml b/sdk/communication/azure-communication-messages/pom.xml index 6b96d22fbc33..4de8182e023b 100644 --- a/sdk/communication/azure-communication-messages/pom.xml +++ b/sdk/communication/azure-communication-messages/pom.xml @@ -14,7 +14,7 @@ com.azure azure-communication-messages - 1.2.0-beta.1 + 1.2.0-beta.2 jar Microsoft Azure client library for Azure Communication Services - Messaging application @@ -55,33 +55,33 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-communication-common - 1.3.9 + 1.3.10 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/MessagesServiceVersion.java b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/MessagesServiceVersion.java index 8673e4222036..462bb0b33834 100644 --- a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/MessagesServiceVersion.java +++ b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/MessagesServiceVersion.java @@ -18,7 +18,12 @@ public enum MessagesServiceVersion implements ServiceVersion { /** * Enum value 2024-08-30. */ - V2024_08_30("2024-08-30"); + V2024_08_30("2024-08-30"), + + /** + * Enum value 2025-01-15-preview. + */ + V2025_01_15_PREVIEW("2025-01-15-preview"); private final String version; @@ -40,6 +45,6 @@ public String getVersion() { * @return The latest {@link MessagesServiceVersion}. */ public static MessagesServiceVersion getLatest() { - return V2024_08_30; + return V2025_01_15_PREVIEW; } } diff --git a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/NotificationMessagesAsyncClient.java b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/NotificationMessagesAsyncClient.java index 435f82449d3b..655037080cda 100644 --- a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/NotificationMessagesAsyncClient.java +++ b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/NotificationMessagesAsyncClient.java @@ -55,7 +55,7 @@ public final class NotificationMessagesAsyncClient { *

              * {@code
              * {
        -     *     kind: String(text/image/image_v0/document/video/audio/template) (Required)
        +     *     kind: String(text/image/image_v0/document/video/audio/template/sticker/reaction/interactive) (Required)
              *     channelRegistrationId: String (Required)
              *     to (Required): [
              *         String (Required)
        diff --git a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/NotificationMessagesClient.java b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/NotificationMessagesClient.java
        index 59266523b678..1d4c46e92ef1 100644
        --- a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/NotificationMessagesClient.java
        +++ b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/NotificationMessagesClient.java
        @@ -53,7 +53,7 @@ public final class NotificationMessagesClient {
              * 
              * {@code
              * {
        -     *     kind: String(text/image/image_v0/document/video/audio/template) (Required)
        +     *     kind: String(text/image/image_v0/document/video/audio/template/sticker/reaction/interactive) (Required)
              *     channelRegistrationId: String (Required)
              *     to (Required): [
              *         String (Required)
        diff --git a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/implementation/NotificationMessagesClientImpl.java b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/implementation/NotificationMessagesClientImpl.java
        index a9176df99148..3d7f4d8bdabb 100644
        --- a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/implementation/NotificationMessagesClientImpl.java
        +++ b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/implementation/NotificationMessagesClientImpl.java
        @@ -212,7 +212,7 @@ Response downloadMediaSync(@HostParam("endpoint") String endpoint,
              * 
              * {@code
              * {
        -     *     kind: String(text/image/image_v0/document/video/audio/template) (Required)
        +     *     kind: String(text/image/image_v0/document/video/audio/template/sticker/reaction/interactive) (Required)
              *     channelRegistrationId: String (Required)
              *     to (Required): [
              *         String (Required)
        @@ -284,7 +284,7 @@ public Mono> sendWithResponseAsync(BinaryData notificationC
              * 
              * {@code
              * {
        -     *     kind: String(text/image/image_v0/document/video/audio/template) (Required)
        +     *     kind: String(text/image/image_v0/document/video/audio/template/sticker/reaction/interactive) (Required)
              *     channelRegistrationId: String (Required)
              *     to (Required): [
              *         String (Required)
        diff --git a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/ActionBindings.java b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/ActionBindings.java
        new file mode 100644
        index 000000000000..e11152962e27
        --- /dev/null
        +++ b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/ActionBindings.java
        @@ -0,0 +1,96 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) TypeSpec Code Generator.
        +package com.azure.communication.messages.models;
        +
        +import com.azure.communication.messages.models.channels.WhatsAppButtonActionBindings;
        +import com.azure.communication.messages.models.channels.WhatsAppListActionBindings;
        +import com.azure.communication.messages.models.channels.WhatsAppUrlActionBindings;
        +import com.azure.core.annotation.Generated;
        +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;
        +
        +/**
        + * Binding actions to the interactive message.
        + */
        +@Immutable
        +public abstract class ActionBindings implements JsonSerializable {
        +
        +    /*
        +     * Kind of the MessageActionBinding.
        +     */
        +    @Generated
        +    private MessageActionBindingKind kind = MessageActionBindingKind.fromString("ActionBindings");
        +
        +    /**
        +     * Creates an instance of ActionBindings class.
        +     */
        +    @Generated
        +    protected ActionBindings() {
        +    }
        +
        +    /**
        +     * Get the kind property: Kind of the MessageActionBinding.
        +     *
        +     * @return the kind value.
        +     */
        +    @Generated
        +    public MessageActionBindingKind getKind() {
        +        return this.kind;
        +    }
        +
        +    /**
        +     * {@inheritDoc}
        +     */
        +    @Generated
        +    @Override
        +    public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
        +        jsonWriter.writeStartObject();
        +        jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString());
        +        return jsonWriter.writeEndObject();
        +    }
        +
        +    /**
        +     * Reads an instance of ActionBindings from the JsonReader.
        +     *
        +     * @param jsonReader The JsonReader being read.
        +     * @return An instance of ActionBindings 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 ActionBindings.
        +     */
        +    @Generated
        +    public static ActionBindings 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 ("kind".equals(fieldName)) {
        +                        discriminatorValue = readerToUse.getString();
        +                        break;
        +                    } else {
        +                        readerToUse.skipChildren();
        +                    }
        +                }
        +                // Use the discriminator value to determine which subtype should be deserialized.
        +                if ("whatsAppListAction".equals(discriminatorValue)) {
        +                    return WhatsAppListActionBindings.fromJson(readerToUse.reset());
        +                } else if ("whatsAppButtonAction".equals(discriminatorValue)) {
        +                    return WhatsAppButtonActionBindings.fromJson(readerToUse.reset());
        +                } else if ("whatsAppUrlAction".equals(discriminatorValue)) {
        +                    return WhatsAppUrlActionBindings.fromJson(readerToUse.reset());
        +                } else {
        +                    throw new IllegalStateException("Invalid Kind value - " + discriminatorValue);
        +                }
        +            }
        +        });
        +    }
        +}
        diff --git a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/ActionGroup.java b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/ActionGroup.java
        new file mode 100644
        index 000000000000..74f4f2309fd5
        --- /dev/null
        +++ b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/ActionGroup.java
        @@ -0,0 +1,106 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) TypeSpec Code Generator.
        +package com.azure.communication.messages.models;
        +
        +import com.azure.core.annotation.Generated;
        +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;
        +import java.util.ArrayList;
        +import java.util.List;
        +
        +/**
        + * The Action Group content.
        + */
        +@Immutable
        +public final class ActionGroup implements JsonSerializable {
        +
        +    /*
        +     * Title of the ActionGroup.
        +     */
        +    @Generated
        +    private final String title;
        +
        +    /*
        +     * Array of items in ActionGroup.
        +     */
        +    @Generated
        +    private final List items;
        +
        +    /**
        +     * Creates an instance of ActionGroup class.
        +     *
        +     * @param title the title value to set.
        +     * @param items the items value to set.
        +     */
        +    @Generated
        +    public ActionGroup(String title, List items) {
        +        this.title = title;
        +        this.items = new ArrayList<>(items);
        +    }
        +
        +    /**
        +     * Get the title property: Title of the ActionGroup.
        +     *
        +     * @return the title value.
        +     */
        +    @Generated
        +    public String getTitle() {
        +        return this.title;
        +    }
        +
        +    /**
        +     * Get the items property: Array of items in ActionGroup.
        +     *
        +     * @return the items value.
        +     */
        +    @Generated
        +    public List getItems() {
        +        return new ArrayList<>(this.items);
        +    }
        +
        +    /**
        +     * {@inheritDoc}
        +     */
        +    @Generated
        +    @Override
        +    public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
        +        jsonWriter.writeStartObject();
        +        jsonWriter.writeStringField("title", this.title);
        +        jsonWriter.writeArrayField("items", this.items, (writer, element) -> writer.writeJson(element));
        +        return jsonWriter.writeEndObject();
        +    }
        +
        +    /**
        +     * Reads an instance of ActionGroup from the JsonReader.
        +     *
        +     * @param jsonReader The JsonReader being read.
        +     * @return An instance of ActionGroup 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 ActionGroup.
        +     */
        +    @Generated
        +    public static ActionGroup fromJson(JsonReader jsonReader) throws IOException {
        +        return jsonReader.readObject(reader -> {
        +            String title = null;
        +            List items = null;
        +            while (reader.nextToken() != JsonToken.END_OBJECT) {
        +                String fieldName = reader.getFieldName();
        +                reader.nextToken();
        +                if ("title".equals(fieldName)) {
        +                    title = reader.getString();
        +                } else if ("items".equals(fieldName)) {
        +                    items = reader.readArray(reader1 -> ActionGroupItem.fromJson(reader1));
        +                } else {
        +                    reader.skipChildren();
        +                }
        +            }
        +            return new ActionGroup(title, items);
        +        });
        +    }
        +}
        diff --git a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/ActionGroupContent.java b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/ActionGroupContent.java
        new file mode 100644
        index 000000000000..ec8825ce37ee
        --- /dev/null
        +++ b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/ActionGroupContent.java
        @@ -0,0 +1,128 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) TypeSpec Code Generator.
        +package com.azure.communication.messages.models;
        +
        +import com.azure.core.annotation.Generated;
        +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;
        +import java.util.ArrayList;
        +import java.util.List;
        +
        +/**
        + * The action content of type ActionGroup.
        + */
        +@Immutable
        +public final class ActionGroupContent extends MessageContent {
        +
        +    /*
        +     * Kind of MessageContent.
        +     */
        +    @Generated
        +    private MessageContentKind kind = MessageContentKind.GROUP;
        +
        +    /*
        +     * Title of the actionGroup content.
        +     */
        +    @Generated
        +    private final String title;
        +
        +    /*
        +     * Set or group of actions.
        +     */
        +    @Generated
        +    private final List groups;
        +
        +    /**
        +     * Creates an instance of ActionGroupContent class.
        +     *
        +     * @param title the title value to set.
        +     * @param groups the groups value to set.
        +     */
        +    @Generated
        +    public ActionGroupContent(String title, List groups) {
        +        this.title = title;
        +        this.groups = new ArrayList<>(groups);
        +    }
        +
        +    /**
        +     * Get the kind property: Kind of MessageContent.
        +     *
        +     * @return the kind value.
        +     */
        +    @Generated
        +    @Override
        +    public MessageContentKind getKind() {
        +        return this.kind;
        +    }
        +
        +    /**
        +     * Get the title property: Title of the actionGroup content.
        +     *
        +     * @return the title value.
        +     */
        +    @Generated
        +    public String getTitle() {
        +        return this.title;
        +    }
        +
        +    /**
        +     * Get the groups property: Set or group of actions.
        +     *
        +     * @return the groups value.
        +     */
        +    @Generated
        +    public List getGroups() {
        +        return new ArrayList<>(this.groups);
        +    }
        +
        +    /**
        +     * {@inheritDoc}
        +     */
        +    @Generated
        +    @Override
        +    public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
        +        jsonWriter.writeStartObject();
        +        jsonWriter.writeStringField("title", this.title);
        +        jsonWriter.writeArrayField("groups", this.groups, (writer, element) -> writer.writeJson(element));
        +        jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString());
        +        return jsonWriter.writeEndObject();
        +    }
        +
        +    /**
        +     * Reads an instance of ActionGroupContent from the JsonReader.
        +     *
        +     * @param jsonReader The JsonReader being read.
        +     * @return An instance of ActionGroupContent 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 ActionGroupContent.
        +     */
        +    @Generated
        +    public static ActionGroupContent fromJson(JsonReader jsonReader) throws IOException {
        +        return jsonReader.readObject(reader -> {
        +            String title = null;
        +            List groups = null;
        +            MessageContentKind kind = MessageContentKind.GROUP;
        +            while (reader.nextToken() != JsonToken.END_OBJECT) {
        +                String fieldName = reader.getFieldName();
        +                reader.nextToken();
        +                if ("title".equals(fieldName)) {
        +                    title = reader.getString();
        +                } else if ("groups".equals(fieldName)) {
        +                    groups = reader.readArray(reader1 -> ActionGroup.fromJson(reader1));
        +                } else if ("kind".equals(fieldName)) {
        +                    kind = MessageContentKind.fromString(reader.getString());
        +                } else {
        +                    reader.skipChildren();
        +                }
        +            }
        +            ActionGroupContent deserializedActionGroupContent = new ActionGroupContent(title, groups);
        +            deserializedActionGroupContent.kind = kind;
        +            return deserializedActionGroupContent;
        +        });
        +    }
        +}
        diff --git a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/ActionGroupItem.java b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/ActionGroupItem.java
        new file mode 100644
        index 000000000000..9fa292486f2d
        --- /dev/null
        +++ b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/ActionGroupItem.java
        @@ -0,0 +1,126 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) TypeSpec Code Generator.
        +package com.azure.communication.messages.models;
        +
        +import com.azure.core.annotation.Generated;
        +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 Action group item in the content.
        + */
        +@Immutable
        +public final class ActionGroupItem implements JsonSerializable {
        +
        +    /*
        +     * Id of the Item.
        +     */
        +    @Generated
        +    private final String id;
        +
        +    /*
        +     * Title of the Item.
        +     */
        +    @Generated
        +    private final String title;
        +
        +    /*
        +     * Description of the Item.
        +     */
        +    @Generated
        +    private final String description;
        +
        +    /**
        +     * Creates an instance of ActionGroupItem class.
        +     *
        +     * @param id the id value to set.
        +     * @param title the title value to set.
        +     * @param description the description value to set.
        +     */
        +    @Generated
        +    public ActionGroupItem(String id, String title, String description) {
        +        this.id = id;
        +        this.title = title;
        +        this.description = description;
        +    }
        +
        +    /**
        +     * Get the id property: Id of the Item.
        +     *
        +     * @return the id value.
        +     */
        +    @Generated
        +    public String getId() {
        +        return this.id;
        +    }
        +
        +    /**
        +     * Get the title property: Title of the Item.
        +     *
        +     * @return the title value.
        +     */
        +    @Generated
        +    public String getTitle() {
        +        return this.title;
        +    }
        +
        +    /**
        +     * Get the description property: Description of the Item.
        +     *
        +     * @return the description value.
        +     */
        +    @Generated
        +    public String getDescription() {
        +        return this.description;
        +    }
        +
        +    /**
        +     * {@inheritDoc}
        +     */
        +    @Generated
        +    @Override
        +    public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
        +        jsonWriter.writeStartObject();
        +        jsonWriter.writeStringField("id", this.id);
        +        jsonWriter.writeStringField("title", this.title);
        +        jsonWriter.writeStringField("description", this.description);
        +        return jsonWriter.writeEndObject();
        +    }
        +
        +    /**
        +     * Reads an instance of ActionGroupItem from the JsonReader.
        +     *
        +     * @param jsonReader The JsonReader being read.
        +     * @return An instance of ActionGroupItem 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 ActionGroupItem.
        +     */
        +    @Generated
        +    public static ActionGroupItem fromJson(JsonReader jsonReader) throws IOException {
        +        return jsonReader.readObject(reader -> {
        +            String id = null;
        +            String title = null;
        +            String description = null;
        +            while (reader.nextToken() != JsonToken.END_OBJECT) {
        +                String fieldName = reader.getFieldName();
        +                reader.nextToken();
        +                if ("id".equals(fieldName)) {
        +                    id = reader.getString();
        +                } else if ("title".equals(fieldName)) {
        +                    title = reader.getString();
        +                } else if ("description".equals(fieldName)) {
        +                    description = reader.getString();
        +                } else {
        +                    reader.skipChildren();
        +                }
        +            }
        +            return new ActionGroupItem(id, title, description);
        +        });
        +    }
        +}
        diff --git a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/ButtonContent.java b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/ButtonContent.java
        new file mode 100644
        index 000000000000..a548f12070f8
        --- /dev/null
        +++ b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/ButtonContent.java
        @@ -0,0 +1,104 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) TypeSpec Code Generator.
        +package com.azure.communication.messages.models;
        +
        +import com.azure.core.annotation.Generated;
        +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 message content of type Button information.
        + */
        +@Immutable
        +public final class ButtonContent implements JsonSerializable {
        +
        +    /*
        +     * Unique Id of the button content.
        +     */
        +    @Generated
        +    private final String id;
        +
        +    /*
        +     * Title of the button content.
        +     */
        +    @Generated
        +    private final String title;
        +
        +    /**
        +     * Creates an instance of ButtonContent class.
        +     *
        +     * @param id the id value to set.
        +     * @param title the title value to set.
        +     */
        +    @Generated
        +    public ButtonContent(String id, String title) {
        +        this.id = id;
        +        this.title = title;
        +    }
        +
        +    /**
        +     * Get the id property: Unique Id of the button content.
        +     *
        +     * @return the id value.
        +     */
        +    @Generated
        +    public String getId() {
        +        return this.id;
        +    }
        +
        +    /**
        +     * Get the title property: Title of the button content.
        +     *
        +     * @return the title value.
        +     */
        +    @Generated
        +    public String getTitle() {
        +        return this.title;
        +    }
        +
        +    /**
        +     * {@inheritDoc}
        +     */
        +    @Generated
        +    @Override
        +    public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
        +        jsonWriter.writeStartObject();
        +        jsonWriter.writeStringField("id", this.id);
        +        jsonWriter.writeStringField("title", this.title);
        +        return jsonWriter.writeEndObject();
        +    }
        +
        +    /**
        +     * Reads an instance of ButtonContent from the JsonReader.
        +     *
        +     * @param jsonReader The JsonReader being read.
        +     * @return An instance of ButtonContent 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 ButtonContent.
        +     */
        +    @Generated
        +    public static ButtonContent fromJson(JsonReader jsonReader) throws IOException {
        +        return jsonReader.readObject(reader -> {
        +            String id = null;
        +            String title = null;
        +            while (reader.nextToken() != JsonToken.END_OBJECT) {
        +                String fieldName = reader.getFieldName();
        +                reader.nextToken();
        +                if ("id".equals(fieldName)) {
        +                    id = reader.getString();
        +                } else if ("title".equals(fieldName)) {
        +                    title = reader.getString();
        +                } else {
        +                    reader.skipChildren();
        +                }
        +            }
        +            return new ButtonContent(id, title);
        +        });
        +    }
        +}
        diff --git a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/ButtonSetContent.java b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/ButtonSetContent.java
        new file mode 100644
        index 000000000000..9e5dfc65ed4c
        --- /dev/null
        +++ b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/ButtonSetContent.java
        @@ -0,0 +1,106 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) TypeSpec Code Generator.
        +package com.azure.communication.messages.models;
        +
        +import com.azure.core.annotation.Generated;
        +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;
        +import java.util.ArrayList;
        +import java.util.List;
        +
        +/**
        + * The message content of type ButtonSet/ List of buttons information.
        + */
        +@Immutable
        +public final class ButtonSetContent extends MessageContent {
        +
        +    /*
        +     * Kind of MessageContent.
        +     */
        +    @Generated
        +    private MessageContentKind kind = MessageContentKind.BUTTON_SET;
        +
        +    /*
        +     * Unique Id of the button content.
        +     */
        +    @Generated
        +    private final List buttons;
        +
        +    /**
        +     * Creates an instance of ButtonSetContent class.
        +     *
        +     * @param buttons the buttons value to set.
        +     */
        +    @Generated
        +    public ButtonSetContent(List buttons) {
        +        this.buttons = new ArrayList<>(buttons);
        +    }
        +
        +    /**
        +     * Get the kind property: Kind of MessageContent.
        +     *
        +     * @return the kind value.
        +     */
        +    @Generated
        +    @Override
        +    public MessageContentKind getKind() {
        +        return this.kind;
        +    }
        +
        +    /**
        +     * Get the buttons property: Unique Id of the button content.
        +     *
        +     * @return the buttons value.
        +     */
        +    @Generated
        +    public List getButtons() {
        +        return new ArrayList<>(this.buttons);
        +    }
        +
        +    /**
        +     * {@inheritDoc}
        +     */
        +    @Generated
        +    @Override
        +    public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
        +        jsonWriter.writeStartObject();
        +        jsonWriter.writeArrayField("buttons", this.buttons, (writer, element) -> writer.writeJson(element));
        +        jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString());
        +        return jsonWriter.writeEndObject();
        +    }
        +
        +    /**
        +     * Reads an instance of ButtonSetContent from the JsonReader.
        +     *
        +     * @param jsonReader The JsonReader being read.
        +     * @return An instance of ButtonSetContent 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 ButtonSetContent.
        +     */
        +    @Generated
        +    public static ButtonSetContent fromJson(JsonReader jsonReader) throws IOException {
        +        return jsonReader.readObject(reader -> {
        +            List buttons = null;
        +            MessageContentKind kind = MessageContentKind.BUTTON_SET;
        +            while (reader.nextToken() != JsonToken.END_OBJECT) {
        +                String fieldName = reader.getFieldName();
        +                reader.nextToken();
        +                if ("buttons".equals(fieldName)) {
        +                    buttons = reader.readArray(reader1 -> ButtonContent.fromJson(reader1));
        +                } else if ("kind".equals(fieldName)) {
        +                    kind = MessageContentKind.fromString(reader.getString());
        +                } else {
        +                    reader.skipChildren();
        +                }
        +            }
        +            ButtonSetContent deserializedButtonSetContent = new ButtonSetContent(buttons);
        +            deserializedButtonSetContent.kind = kind;
        +            return deserializedButtonSetContent;
        +        });
        +    }
        +}
        diff --git a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/CommunicationMessageKind.java b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/CommunicationMessageKind.java
        index b07ef3e8bcbf..6decf5ae4113 100644
        --- a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/CommunicationMessageKind.java
        +++ b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/CommunicationMessageKind.java
        @@ -85,4 +85,22 @@ public static Collection values() {
             @Generated
             @Deprecated()
             public static final CommunicationMessageKind IMAGE_V0 = fromString("image_v0");
        +
        +    /**
        +     * Sticker message type.
        +     */
        +    @Generated
        +    public static final CommunicationMessageKind STICKER = fromString("sticker");
        +
        +    /**
        +     * Reaction message type.
        +     */
        +    @Generated
        +    public static final CommunicationMessageKind REACTION = fromString("reaction");
        +
        +    /**
        +     * Interactive Actionable message type.
        +     */
        +    @Generated
        +    public static final CommunicationMessageKind INTERACTIVE = fromString("interactive");
         }
        diff --git a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/DocumentMessageContent.java b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/DocumentMessageContent.java
        new file mode 100644
        index 000000000000..e0bcd4e1ba48
        --- /dev/null
        +++ b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/DocumentMessageContent.java
        @@ -0,0 +1,104 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) TypeSpec Code Generator.
        +package com.azure.communication.messages.models;
        +
        +import com.azure.core.annotation.Generated;
        +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 message content of type document information.
        + */
        +@Immutable
        +public final class DocumentMessageContent extends MessageContent {
        +
        +    /*
        +     * Kind of MessageContent.
        +     */
        +    @Generated
        +    private MessageContentKind kind = MessageContentKind.DOCUMENT;
        +
        +    /*
        +     * MediaUri of the media content.
        +     */
        +    @Generated
        +    private final String mediaUrl;
        +
        +    /**
        +     * Creates an instance of DocumentMessageContent class.
        +     *
        +     * @param mediaUrl the mediaUrl value to set.
        +     */
        +    @Generated
        +    public DocumentMessageContent(String mediaUrl) {
        +        this.mediaUrl = mediaUrl;
        +    }
        +
        +    /**
        +     * Get the kind property: Kind of MessageContent.
        +     *
        +     * @return the kind value.
        +     */
        +    @Generated
        +    @Override
        +    public MessageContentKind getKind() {
        +        return this.kind;
        +    }
        +
        +    /**
        +     * Get the mediaUrl property: MediaUri of the media content.
        +     *
        +     * @return the mediaUrl value.
        +     */
        +    @Generated
        +    public String getMediaUrl() {
        +        return this.mediaUrl;
        +    }
        +
        +    /**
        +     * {@inheritDoc}
        +     */
        +    @Generated
        +    @Override
        +    public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
        +        jsonWriter.writeStartObject();
        +        jsonWriter.writeStringField("mediaUri", this.mediaUrl);
        +        jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString());
        +        return jsonWriter.writeEndObject();
        +    }
        +
        +    /**
        +     * Reads an instance of DocumentMessageContent from the JsonReader.
        +     *
        +     * @param jsonReader The JsonReader being read.
        +     * @return An instance of DocumentMessageContent 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 DocumentMessageContent.
        +     */
        +    @Generated
        +    public static DocumentMessageContent fromJson(JsonReader jsonReader) throws IOException {
        +        return jsonReader.readObject(reader -> {
        +            String mediaUrl = null;
        +            MessageContentKind kind = MessageContentKind.DOCUMENT;
        +            while (reader.nextToken() != JsonToken.END_OBJECT) {
        +                String fieldName = reader.getFieldName();
        +                reader.nextToken();
        +                if ("mediaUri".equals(fieldName)) {
        +                    mediaUrl = reader.getString();
        +                } else if ("kind".equals(fieldName)) {
        +                    kind = MessageContentKind.fromString(reader.getString());
        +                } else {
        +                    reader.skipChildren();
        +                }
        +            }
        +            DocumentMessageContent deserializedDocumentMessageContent = new DocumentMessageContent(mediaUrl);
        +            deserializedDocumentMessageContent.kind = kind;
        +            return deserializedDocumentMessageContent;
        +        });
        +    }
        +}
        diff --git a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/ImageMessageContent.java b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/ImageMessageContent.java
        new file mode 100644
        index 000000000000..11a8a5088753
        --- /dev/null
        +++ b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/ImageMessageContent.java
        @@ -0,0 +1,104 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) TypeSpec Code Generator.
        +package com.azure.communication.messages.models;
        +
        +import com.azure.core.annotation.Generated;
        +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 message content of type image information.
        + */
        +@Immutable
        +public final class ImageMessageContent extends MessageContent {
        +
        +    /*
        +     * Kind of MessageContent.
        +     */
        +    @Generated
        +    private MessageContentKind kind = MessageContentKind.IMAGE;
        +
        +    /*
        +     * MediaUri of the media content.
        +     */
        +    @Generated
        +    private final String mediaUrl;
        +
        +    /**
        +     * Creates an instance of ImageMessageContent class.
        +     *
        +     * @param mediaUrl the mediaUrl value to set.
        +     */
        +    @Generated
        +    public ImageMessageContent(String mediaUrl) {
        +        this.mediaUrl = mediaUrl;
        +    }
        +
        +    /**
        +     * Get the kind property: Kind of MessageContent.
        +     *
        +     * @return the kind value.
        +     */
        +    @Generated
        +    @Override
        +    public MessageContentKind getKind() {
        +        return this.kind;
        +    }
        +
        +    /**
        +     * Get the mediaUrl property: MediaUri of the media content.
        +     *
        +     * @return the mediaUrl value.
        +     */
        +    @Generated
        +    public String getMediaUrl() {
        +        return this.mediaUrl;
        +    }
        +
        +    /**
        +     * {@inheritDoc}
        +     */
        +    @Generated
        +    @Override
        +    public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
        +        jsonWriter.writeStartObject();
        +        jsonWriter.writeStringField("mediaUri", this.mediaUrl);
        +        jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString());
        +        return jsonWriter.writeEndObject();
        +    }
        +
        +    /**
        +     * Reads an instance of ImageMessageContent from the JsonReader.
        +     *
        +     * @param jsonReader The JsonReader being read.
        +     * @return An instance of ImageMessageContent 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 ImageMessageContent.
        +     */
        +    @Generated
        +    public static ImageMessageContent fromJson(JsonReader jsonReader) throws IOException {
        +        return jsonReader.readObject(reader -> {
        +            String mediaUrl = null;
        +            MessageContentKind kind = MessageContentKind.IMAGE;
        +            while (reader.nextToken() != JsonToken.END_OBJECT) {
        +                String fieldName = reader.getFieldName();
        +                reader.nextToken();
        +                if ("mediaUri".equals(fieldName)) {
        +                    mediaUrl = reader.getString();
        +                } else if ("kind".equals(fieldName)) {
        +                    kind = MessageContentKind.fromString(reader.getString());
        +                } else {
        +                    reader.skipChildren();
        +                }
        +            }
        +            ImageMessageContent deserializedImageMessageContent = new ImageMessageContent(mediaUrl);
        +            deserializedImageMessageContent.kind = kind;
        +            return deserializedImageMessageContent;
        +        });
        +    }
        +}
        diff --git a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/InteractiveMessage.java b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/InteractiveMessage.java
        new file mode 100644
        index 000000000000..1a66a31647f1
        --- /dev/null
        +++ b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/InteractiveMessage.java
        @@ -0,0 +1,170 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) TypeSpec Code Generator.
        +package com.azure.communication.messages.models;
        +
        +import com.azure.core.annotation.Fluent;
        +import com.azure.core.annotation.Generated;
        +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 Interactive message content to which user can read and respond.
        + */
        +@Fluent
        +public final class InteractiveMessage implements JsonSerializable {
        +
        +    /*
        +     * Gets or Sets Header content. Supports the following types:text, images etc.
        +     */
        +    @Generated
        +    private MessageContent headerProperty;
        +
        +    /*
        +     * Gets or Sets Message body content. Emojis, markdown, and links are supported.
        +     */
        +    @Generated
        +    private final TextMessageContent body;
        +
        +    /*
        +     * Gets or Sets Message footer content. Emojis, markdown, and links are supported.
        +     */
        +    @Generated
        +    private TextMessageContent footer;
        +
        +    /*
        +     * The binding object to get or set Action which describes options user have to respond to message.
        +     */
        +    @Generated
        +    private final ActionBindings action;
        +
        +    /**
        +     * Creates an instance of InteractiveMessage class.
        +     *
        +     * @param body the body value to set.
        +     * @param action the action value to set.
        +     */
        +    @Generated
        +    public InteractiveMessage(TextMessageContent body, ActionBindings action) {
        +        this.body = body;
        +        this.action = action;
        +    }
        +
        +    /**
        +     * Get the body property: Gets or Sets Message body content. Emojis, markdown, and links are supported.
        +     *
        +     * @return the body value.
        +     */
        +    @Generated
        +    public TextMessageContent getBody() {
        +        return this.body;
        +    }
        +
        +    /**
        +     * Get the footer property: Gets or Sets Message footer content. Emojis, markdown, and links are supported.
        +     *
        +     * @return the footer value.
        +     */
        +    @Generated
        +    public TextMessageContent getFooter() {
        +        return this.footer;
        +    }
        +
        +    /**
        +     * Set the footer property: Gets or Sets Message footer content. Emojis, markdown, and links are supported.
        +     *
        +     * @param footer the footer value to set.
        +     * @return the InteractiveMessage object itself.
        +     */
        +    @Generated
        +    public InteractiveMessage setFooter(TextMessageContent footer) {
        +        this.footer = footer;
        +        return this;
        +    }
        +
        +    /**
        +     * Get the action property: The binding object to get or set Action which describes options user have to respond to
        +     * message.
        +     *
        +     * @return the action value.
        +     */
        +    @Generated
        +    public ActionBindings getAction() {
        +        return this.action;
        +    }
        +
        +    /**
        +     * {@inheritDoc}
        +     */
        +    @Generated
        +    @Override
        +    public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
        +        jsonWriter.writeStartObject();
        +        jsonWriter.writeJsonField("body", this.body);
        +        jsonWriter.writeJsonField("action", this.action);
        +        jsonWriter.writeJsonField("header", this.headerProperty);
        +        jsonWriter.writeJsonField("footer", this.footer);
        +        return jsonWriter.writeEndObject();
        +    }
        +
        +    /**
        +     * Reads an instance of InteractiveMessage from the JsonReader.
        +     *
        +     * @param jsonReader The JsonReader being read.
        +     * @return An instance of InteractiveMessage 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 InteractiveMessage.
        +     */
        +    @Generated
        +    public static InteractiveMessage fromJson(JsonReader jsonReader) throws IOException {
        +        return jsonReader.readObject(reader -> {
        +            TextMessageContent body = null;
        +            ActionBindings action = null;
        +            MessageContent headerProperty = null;
        +            TextMessageContent footer = null;
        +            while (reader.nextToken() != JsonToken.END_OBJECT) {
        +                String fieldName = reader.getFieldName();
        +                reader.nextToken();
        +                if ("body".equals(fieldName)) {
        +                    body = TextMessageContent.fromJson(reader);
        +                } else if ("action".equals(fieldName)) {
        +                    action = ActionBindings.fromJson(reader);
        +                } else if ("header".equals(fieldName)) {
        +                    headerProperty = MessageContent.fromJson(reader);
        +                } else if ("footer".equals(fieldName)) {
        +                    footer = TextMessageContent.fromJson(reader);
        +                } else {
        +                    reader.skipChildren();
        +                }
        +            }
        +            InteractiveMessage deserializedInteractiveMessage = new InteractiveMessage(body, action);
        +            deserializedInteractiveMessage.headerProperty = headerProperty;
        +            deserializedInteractiveMessage.footer = footer;
        +            return deserializedInteractiveMessage;
        +        });
        +    }
        +
        +    /**
        +     * Get the headerProperty property: Gets or Sets Header content. Supports the following types:text, images etc.
        +     *
        +     * @return the headerProperty value.
        +     */
        +    public MessageContent getHeader() {
        +        return this.headerProperty;
        +    }
        +
        +    /**
        +     * Set the header property: Gets or Sets Header content. Supports the following types:text, images etc.
        +     *
        +     * @param header the header value to set.
        +     * @return the InteractiveMessage object itself.
        +     */
        +    public InteractiveMessage setHeader(MessageContent header) {
        +        this.headerProperty = header;
        +        return this;
        +    }
        +}
        diff --git a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/InteractiveNotificationContent.java b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/InteractiveNotificationContent.java
        new file mode 100644
        index 000000000000..728bc397b88b
        --- /dev/null
        +++ b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/InteractiveNotificationContent.java
        @@ -0,0 +1,118 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) TypeSpec Code Generator.
        +package com.azure.communication.messages.models;
        +
        +import com.azure.core.annotation.Generated;
        +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;
        +import java.util.List;
        +
        +/**
        + * A request to send an Interactive message notification.
        + */
        +@Immutable
        +public final class InteractiveNotificationContent extends NotificationContent {
        +
        +    /*
        +     * The type discriminator describing a notification type.
        +     */
        +    @Generated
        +    private CommunicationMessageKind kind = CommunicationMessageKind.INTERACTIVE;
        +
        +    /*
        +     * The interactive message content.
        +     */
        +    @Generated
        +    private final InteractiveMessage interactiveMessage;
        +
        +    /**
        +     * Creates an instance of InteractiveNotificationContent class.
        +     *
        +     * @param channelRegistrationId the channelRegistrationId value to set.
        +     * @param to the to value to set.
        +     * @param interactiveMessage the interactiveMessage value to set.
        +     */
        +    @Generated
        +    public InteractiveNotificationContent(String channelRegistrationId, List to,
        +        InteractiveMessage interactiveMessage) {
        +        super(channelRegistrationId, to);
        +        this.interactiveMessage = interactiveMessage;
        +    }
        +
        +    /**
        +     * Get the kind property: The type discriminator describing a notification type.
        +     *
        +     * @return the kind value.
        +     */
        +    @Generated
        +    @Override
        +    public CommunicationMessageKind getKind() {
        +        return this.kind;
        +    }
        +
        +    /**
        +     * Get the interactiveMessage property: The interactive message content.
        +     *
        +     * @return the interactiveMessage value.
        +     */
        +    @Generated
        +    public InteractiveMessage getInteractiveMessage() {
        +        return this.interactiveMessage;
        +    }
        +
        +    /**
        +     * {@inheritDoc}
        +     */
        +    @Generated
        +    @Override
        +    public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
        +        jsonWriter.writeStartObject();
        +        jsonWriter.writeStringField("channelRegistrationId", getChannelRegistrationId());
        +        jsonWriter.writeArrayField("to", getTo(), (writer, element) -> writer.writeString(element));
        +        jsonWriter.writeJsonField("interactiveMessage", this.interactiveMessage);
        +        jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString());
        +        return jsonWriter.writeEndObject();
        +    }
        +
        +    /**
        +     * Reads an instance of InteractiveNotificationContent from the JsonReader.
        +     *
        +     * @param jsonReader The JsonReader being read.
        +     * @return An instance of InteractiveNotificationContent 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 InteractiveNotificationContent.
        +     */
        +    @Generated
        +    public static InteractiveNotificationContent fromJson(JsonReader jsonReader) throws IOException {
        +        return jsonReader.readObject(reader -> {
        +            String channelRegistrationId = null;
        +            List to = null;
        +            InteractiveMessage interactiveMessage = null;
        +            CommunicationMessageKind kind = CommunicationMessageKind.INTERACTIVE;
        +            while (reader.nextToken() != JsonToken.END_OBJECT) {
        +                String fieldName = reader.getFieldName();
        +                reader.nextToken();
        +                if ("channelRegistrationId".equals(fieldName)) {
        +                    channelRegistrationId = reader.getString();
        +                } else if ("to".equals(fieldName)) {
        +                    to = reader.readArray(reader1 -> reader1.getString());
        +                } else if ("interactiveMessage".equals(fieldName)) {
        +                    interactiveMessage = InteractiveMessage.fromJson(reader);
        +                } else if ("kind".equals(fieldName)) {
        +                    kind = CommunicationMessageKind.fromString(reader.getString());
        +                } else {
        +                    reader.skipChildren();
        +                }
        +            }
        +            InteractiveNotificationContent deserializedInteractiveNotificationContent
        +                = new InteractiveNotificationContent(channelRegistrationId, to, interactiveMessage);
        +            deserializedInteractiveNotificationContent.kind = kind;
        +            return deserializedInteractiveNotificationContent;
        +        });
        +    }
        +}
        diff --git a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/LinkContent.java b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/LinkContent.java
        new file mode 100644
        index 000000000000..9d7e2cbff8e6
        --- /dev/null
        +++ b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/LinkContent.java
        @@ -0,0 +1,126 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) TypeSpec Code Generator.
        +package com.azure.communication.messages.models;
        +
        +import com.azure.core.annotation.Generated;
        +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 message content of type Url information.
        + */
        +@Immutable
        +public final class LinkContent extends MessageContent {
        +
        +    /*
        +     * Kind of MessageContent.
        +     */
        +    @Generated
        +    private MessageContentKind kind = MessageContentKind.URL;
        +
        +    /*
        +     * Title of the url content.
        +     */
        +    @Generated
        +    private final String title;
        +
        +    /*
        +     * The url in the content.
        +     */
        +    @Generated
        +    private final String url;
        +
        +    /**
        +     * Creates an instance of LinkContent class.
        +     *
        +     * @param title the title value to set.
        +     * @param url the url value to set.
        +     */
        +    @Generated
        +    public LinkContent(String title, String url) {
        +        this.title = title;
        +        this.url = url;
        +    }
        +
        +    /**
        +     * Get the kind property: Kind of MessageContent.
        +     *
        +     * @return the kind value.
        +     */
        +    @Generated
        +    @Override
        +    public MessageContentKind getKind() {
        +        return this.kind;
        +    }
        +
        +    /**
        +     * Get the title property: Title of the url content.
        +     *
        +     * @return the title value.
        +     */
        +    @Generated
        +    public String getTitle() {
        +        return this.title;
        +    }
        +
        +    /**
        +     * Get the url property: The url in the content.
        +     *
        +     * @return the url value.
        +     */
        +    @Generated
        +    public String getUrl() {
        +        return this.url;
        +    }
        +
        +    /**
        +     * {@inheritDoc}
        +     */
        +    @Generated
        +    @Override
        +    public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
        +        jsonWriter.writeStartObject();
        +        jsonWriter.writeStringField("title", this.title);
        +        jsonWriter.writeStringField("url", this.url);
        +        jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString());
        +        return jsonWriter.writeEndObject();
        +    }
        +
        +    /**
        +     * Reads an instance of LinkContent from the JsonReader.
        +     *
        +     * @param jsonReader The JsonReader being read.
        +     * @return An instance of LinkContent 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 LinkContent.
        +     */
        +    @Generated
        +    public static LinkContent fromJson(JsonReader jsonReader) throws IOException {
        +        return jsonReader.readObject(reader -> {
        +            String title = null;
        +            String url = null;
        +            MessageContentKind kind = MessageContentKind.URL;
        +            while (reader.nextToken() != JsonToken.END_OBJECT) {
        +                String fieldName = reader.getFieldName();
        +                reader.nextToken();
        +                if ("title".equals(fieldName)) {
        +                    title = reader.getString();
        +                } else if ("url".equals(fieldName)) {
        +                    url = reader.getString();
        +                } else if ("kind".equals(fieldName)) {
        +                    kind = MessageContentKind.fromString(reader.getString());
        +                } else {
        +                    reader.skipChildren();
        +                }
        +            }
        +            LinkContent deserializedLinkContent = new LinkContent(title, url);
        +            deserializedLinkContent.kind = kind;
        +            return deserializedLinkContent;
        +        });
        +    }
        +}
        diff --git a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/MessageActionBindingKind.java b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/MessageActionBindingKind.java
        new file mode 100644
        index 000000000000..343f058f887a
        --- /dev/null
        +++ b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/MessageActionBindingKind.java
        @@ -0,0 +1,63 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) TypeSpec Code Generator.
        +package com.azure.communication.messages.models;
        +
        +import com.azure.core.annotation.Generated;
        +import com.azure.core.util.ExpandableStringEnum;
        +import java.util.Collection;
        +
        +/**
        + * The Kind of interactive message channel action binding like WhatsAppListAction.
        + */
        +public final class MessageActionBindingKind extends ExpandableStringEnum {
        +
        +    /**
        +     * The WhatsApp List action binding kind.
        +     */
        +    @Generated
        +    public static final MessageActionBindingKind WHATS_APP_LIST_ACTION = fromString("whatsAppListAction");
        +
        +    /**
        +     * The WhatsApp Button action binding kind.
        +     */
        +    @Generated
        +    public static final MessageActionBindingKind WHATS_APP_BUTTON_ACTION = fromString("whatsAppButtonAction");
        +
        +    /**
        +     * The WhatsApp Url action binding kind.
        +     */
        +    @Generated
        +    public static final MessageActionBindingKind WHATS_APP_URL_ACTION = fromString("whatsAppUrlAction");
        +
        +    /**
        +     * Creates a new instance of MessageActionBindingKind value.
        +     *
        +     * @deprecated Use the {@link #fromString(String)} factory method.
        +     */
        +    @Generated
        +    @Deprecated
        +    public MessageActionBindingKind() {
        +    }
        +
        +    /**
        +     * Creates or finds a MessageActionBindingKind from its string representation.
        +     *
        +     * @param name a name to look for.
        +     * @return the corresponding MessageActionBindingKind.
        +     */
        +    @Generated
        +    public static MessageActionBindingKind fromString(String name) {
        +        return fromString(name, MessageActionBindingKind.class);
        +    }
        +
        +    /**
        +     * Gets known MessageActionBindingKind values.
        +     *
        +     * @return known MessageActionBindingKind values.
        +     */
        +    @Generated
        +    public static Collection values() {
        +        return values(MessageActionBindingKind.class);
        +    }
        +}
        diff --git a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/MessageContent.java b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/MessageContent.java
        new file mode 100644
        index 000000000000..55eab96b6f6d
        --- /dev/null
        +++ b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/MessageContent.java
        @@ -0,0 +1,101 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) TypeSpec Code Generator.
        +package com.azure.communication.messages.models;
        +
        +import com.azure.core.annotation.Generated;
        +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 message content object used to create interactive messages components.
        + */
        +@Immutable
        +public abstract class MessageContent implements JsonSerializable {
        +
        +    /*
        +     * Kind of MessageContent.
        +     */
        +    @Generated
        +    private MessageContentKind kind = MessageContentKind.fromString("MessageContent");
        +
        +    /**
        +     * Creates an instance of MessageContent class.
        +     */
        +    @Generated
        +    protected MessageContent() {
        +    }
        +
        +    /**
        +     * Get the kind property: Kind of MessageContent.
        +     *
        +     * @return the kind value.
        +     */
        +    @Generated
        +    public MessageContentKind getKind() {
        +        return this.kind;
        +    }
        +
        +    /**
        +     * {@inheritDoc}
        +     */
        +    @Generated
        +    @Override
        +    public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
        +        jsonWriter.writeStartObject();
        +        jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString());
        +        return jsonWriter.writeEndObject();
        +    }
        +
        +    /**
        +     * Reads an instance of MessageContent from the JsonReader.
        +     *
        +     * @param jsonReader The JsonReader being read.
        +     * @return An instance of MessageContent 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 MessageContent.
        +     */
        +    @Generated
        +    public static MessageContent 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 ("kind".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 TextMessageContent.fromJson(readerToUse.reset());
        +                } else if ("document".equals(discriminatorValue)) {
        +                    return DocumentMessageContent.fromJson(readerToUse.reset());
        +                } else if ("image".equals(discriminatorValue)) {
        +                    return ImageMessageContent.fromJson(readerToUse.reset());
        +                } else if ("video".equals(discriminatorValue)) {
        +                    return VideoMessageContent.fromJson(readerToUse.reset());
        +                } else if ("buttonSet".equals(discriminatorValue)) {
        +                    return ButtonSetContent.fromJson(readerToUse.reset());
        +                } else if ("url".equals(discriminatorValue)) {
        +                    return LinkContent.fromJson(readerToUse.reset());
        +                } else if ("group".equals(discriminatorValue)) {
        +                    return ActionGroupContent.fromJson(readerToUse.reset());
        +                } else {
        +                    throw new IllegalStateException("Invalid Kind value - " + discriminatorValue);
        +                }
        +            }
        +        });
        +    }
        +}
        diff --git a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/MessageContentKind.java b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/MessageContentKind.java
        new file mode 100644
        index 000000000000..763a4efb1cff
        --- /dev/null
        +++ b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/MessageContentKind.java
        @@ -0,0 +1,87 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) TypeSpec Code Generator.
        +package com.azure.communication.messages.models;
        +
        +import com.azure.core.annotation.Generated;
        +import com.azure.core.util.ExpandableStringEnum;
        +import java.util.Collection;
        +
        +/**
        + * The kind of Interactive message content.
        + */
        +public final class MessageContentKind extends ExpandableStringEnum {
        +
        +    /**
        +     * The text content type.
        +     */
        +    @Generated
        +    public static final MessageContentKind TEXT = fromString("text");
        +
        +    /**
        +     * The image content type.
        +     */
        +    @Generated
        +    public static final MessageContentKind IMAGE = fromString("image");
        +
        +    /**
        +     * The video content type.
        +     */
        +    @Generated
        +    public static final MessageContentKind VIDEO = fromString("video");
        +
        +    /**
        +     * The document content type.
        +     */
        +    @Generated
        +    public static final MessageContentKind DOCUMENT = fromString("document");
        +
        +    /**
        +     * The ActionSet content type.
        +     */
        +    @Generated
        +    public static final MessageContentKind GROUP = fromString("group");
        +
        +    /**
        +     * The ButtonSet content type.
        +     */
        +    @Generated
        +    public static final MessageContentKind BUTTON_SET = fromString("buttonSet");
        +
        +    /**
        +     * The Url content type.
        +     */
        +    @Generated
        +    public static final MessageContentKind URL = fromString("url");
        +
        +    /**
        +     * Creates a new instance of MessageContentKind value.
        +     *
        +     * @deprecated Use the {@link #fromString(String)} factory method.
        +     */
        +    @Generated
        +    @Deprecated
        +    public MessageContentKind() {
        +    }
        +
        +    /**
        +     * Creates or finds a MessageContentKind from its string representation.
        +     *
        +     * @param name a name to look for.
        +     * @return the corresponding MessageContentKind.
        +     */
        +    @Generated
        +    public static MessageContentKind fromString(String name) {
        +        return fromString(name, MessageContentKind.class);
        +    }
        +
        +    /**
        +     * Gets known MessageContentKind values.
        +     *
        +     * @return known MessageContentKind values.
        +     */
        +    @Generated
        +    public static Collection values() {
        +        return values(MessageContentKind.class);
        +    }
        +}
        diff --git a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/NotificationContent.java b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/NotificationContent.java
        index cd28761960e1..7f082a0b7938 100644
        --- a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/NotificationContent.java
        +++ b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/NotificationContent.java
        @@ -130,6 +130,12 @@ public static NotificationContent fromJson(JsonReader jsonReader) throws IOExcep
                             return VideoNotificationContent.fromJson(readerToUse.reset());
                         } else if ("audio".equals(discriminatorValue)) {
                             return AudioNotificationContent.fromJson(readerToUse.reset());
        +                } else if ("reaction".equals(discriminatorValue)) {
        +                    return ReactionNotificationContent.fromJson(readerToUse.reset());
        +                } else if ("sticker".equals(discriminatorValue)) {
        +                    return StickerNotificationContent.fromJson(readerToUse.reset());
        +                } else if ("interactive".equals(discriminatorValue)) {
        +                    return InteractiveNotificationContent.fromJson(readerToUse.reset());
                         } else if ("template".equals(discriminatorValue)) {
                             return TemplateNotificationContent.fromJson(readerToUse.reset());
                         } else {
        diff --git a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/ReactionNotificationContent.java b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/ReactionNotificationContent.java
        new file mode 100644
        index 000000000000..99f5ec1bae19
        --- /dev/null
        +++ b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/ReactionNotificationContent.java
        @@ -0,0 +1,139 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) TypeSpec Code Generator.
        +package com.azure.communication.messages.models;
        +
        +import com.azure.core.annotation.Generated;
        +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;
        +import java.util.List;
        +
        +/**
        + * A request to send a Reaction notification.
        + */
        +@Immutable
        +public final class ReactionNotificationContent extends NotificationContent {
        +
        +    /*
        +     * The type discriminator describing a notification type.
        +     */
        +    @Generated
        +    private CommunicationMessageKind kind = CommunicationMessageKind.REACTION;
        +
        +    /*
        +     * emoji content like \uD83D\uDE00.
        +     */
        +    @Generated
        +    private final String emoji;
        +
        +    /*
        +     * ID of the previous message you want to reply to.
        +     */
        +    @Generated
        +    private final String messageId;
        +
        +    /**
        +     * Creates an instance of ReactionNotificationContent class.
        +     *
        +     * @param channelRegistrationId the channelRegistrationId value to set.
        +     * @param to the to value to set.
        +     * @param emoji the emoji value to set.
        +     * @param messageId the messageId value to set.
        +     */
        +    @Generated
        +    public ReactionNotificationContent(String channelRegistrationId, List to, String emoji, String messageId) {
        +        super(channelRegistrationId, to);
        +        this.emoji = emoji;
        +        this.messageId = messageId;
        +    }
        +
        +    /**
        +     * Get the kind property: The type discriminator describing a notification type.
        +     *
        +     * @return the kind value.
        +     */
        +    @Generated
        +    @Override
        +    public CommunicationMessageKind getKind() {
        +        return this.kind;
        +    }
        +
        +    /**
        +     * Get the emoji property: emoji content like \uD83D\uDE00.
        +     *
        +     * @return the emoji value.
        +     */
        +    @Generated
        +    public String getEmoji() {
        +        return this.emoji;
        +    }
        +
        +    /**
        +     * Get the messageId property: ID of the previous message you want to reply to.
        +     *
        +     * @return the messageId value.
        +     */
        +    @Generated
        +    public String getMessageId() {
        +        return this.messageId;
        +    }
        +
        +    /**
        +     * {@inheritDoc}
        +     */
        +    @Generated
        +    @Override
        +    public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
        +        jsonWriter.writeStartObject();
        +        jsonWriter.writeStringField("channelRegistrationId", getChannelRegistrationId());
        +        jsonWriter.writeArrayField("to", getTo(), (writer, element) -> writer.writeString(element));
        +        jsonWriter.writeStringField("emoji", this.emoji);
        +        jsonWriter.writeStringField("messageId", this.messageId);
        +        jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString());
        +        return jsonWriter.writeEndObject();
        +    }
        +
        +    /**
        +     * Reads an instance of ReactionNotificationContent from the JsonReader.
        +     *
        +     * @param jsonReader The JsonReader being read.
        +     * @return An instance of ReactionNotificationContent 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 ReactionNotificationContent.
        +     */
        +    @Generated
        +    public static ReactionNotificationContent fromJson(JsonReader jsonReader) throws IOException {
        +        return jsonReader.readObject(reader -> {
        +            String channelRegistrationId = null;
        +            List to = null;
        +            String emoji = null;
        +            String messageId = null;
        +            CommunicationMessageKind kind = CommunicationMessageKind.REACTION;
        +            while (reader.nextToken() != JsonToken.END_OBJECT) {
        +                String fieldName = reader.getFieldName();
        +                reader.nextToken();
        +                if ("channelRegistrationId".equals(fieldName)) {
        +                    channelRegistrationId = reader.getString();
        +                } else if ("to".equals(fieldName)) {
        +                    to = reader.readArray(reader1 -> reader1.getString());
        +                } else if ("emoji".equals(fieldName)) {
        +                    emoji = reader.getString();
        +                } else if ("messageId".equals(fieldName)) {
        +                    messageId = reader.getString();
        +                } else if ("kind".equals(fieldName)) {
        +                    kind = CommunicationMessageKind.fromString(reader.getString());
        +                } else {
        +                    reader.skipChildren();
        +                }
        +            }
        +            ReactionNotificationContent deserializedReactionNotificationContent
        +                = new ReactionNotificationContent(channelRegistrationId, to, emoji, messageId);
        +            deserializedReactionNotificationContent.kind = kind;
        +            return deserializedReactionNotificationContent;
        +        });
        +    }
        +}
        diff --git a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/StickerNotificationContent.java b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/StickerNotificationContent.java
        new file mode 100644
        index 000000000000..d404b4eb3fb7
        --- /dev/null
        +++ b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/StickerNotificationContent.java
        @@ -0,0 +1,118 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) TypeSpec Code Generator.
        +package com.azure.communication.messages.models;
        +
        +import com.azure.core.annotation.Generated;
        +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;
        +import java.util.List;
        +
        +/**
        + * A request to send a Sticker notification.
        + */
        +@Immutable
        +public final class StickerNotificationContent extends NotificationContent {
        +
        +    /*
        +     * The type discriminator describing a notification type.
        +     */
        +    @Generated
        +    private CommunicationMessageKind kind = CommunicationMessageKind.STICKER;
        +
        +    /*
        +     * A media url for the file. Required if the type is one of the supported media types, e.g. image
        +     */
        +    @Generated
        +    private final String mediaUrl;
        +
        +    /**
        +     * Creates an instance of StickerNotificationContent class.
        +     *
        +     * @param channelRegistrationId the channelRegistrationId value to set.
        +     * @param to the to value to set.
        +     * @param mediaUrl the mediaUrl value to set.
        +     */
        +    @Generated
        +    public StickerNotificationContent(String channelRegistrationId, List to, String mediaUrl) {
        +        super(channelRegistrationId, to);
        +        this.mediaUrl = mediaUrl;
        +    }
        +
        +    /**
        +     * Get the kind property: The type discriminator describing a notification type.
        +     *
        +     * @return the kind value.
        +     */
        +    @Generated
        +    @Override
        +    public CommunicationMessageKind getKind() {
        +        return this.kind;
        +    }
        +
        +    /**
        +     * Get the mediaUrl property: A media url for the file. Required if the type is one of the supported media types,
        +     * e.g. image.
        +     *
        +     * @return the mediaUrl value.
        +     */
        +    @Generated
        +    public String getMediaUrl() {
        +        return this.mediaUrl;
        +    }
        +
        +    /**
        +     * {@inheritDoc}
        +     */
        +    @Generated
        +    @Override
        +    public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
        +        jsonWriter.writeStartObject();
        +        jsonWriter.writeStringField("channelRegistrationId", getChannelRegistrationId());
        +        jsonWriter.writeArrayField("to", getTo(), (writer, element) -> writer.writeString(element));
        +        jsonWriter.writeStringField("mediaUri", this.mediaUrl);
        +        jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString());
        +        return jsonWriter.writeEndObject();
        +    }
        +
        +    /**
        +     * Reads an instance of StickerNotificationContent from the JsonReader.
        +     *
        +     * @param jsonReader The JsonReader being read.
        +     * @return An instance of StickerNotificationContent 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 StickerNotificationContent.
        +     */
        +    @Generated
        +    public static StickerNotificationContent fromJson(JsonReader jsonReader) throws IOException {
        +        return jsonReader.readObject(reader -> {
        +            String channelRegistrationId = null;
        +            List to = null;
        +            String mediaUrl = null;
        +            CommunicationMessageKind kind = CommunicationMessageKind.STICKER;
        +            while (reader.nextToken() != JsonToken.END_OBJECT) {
        +                String fieldName = reader.getFieldName();
        +                reader.nextToken();
        +                if ("channelRegistrationId".equals(fieldName)) {
        +                    channelRegistrationId = reader.getString();
        +                } else if ("to".equals(fieldName)) {
        +                    to = reader.readArray(reader1 -> reader1.getString());
        +                } else if ("mediaUri".equals(fieldName)) {
        +                    mediaUrl = reader.getString();
        +                } else if ("kind".equals(fieldName)) {
        +                    kind = CommunicationMessageKind.fromString(reader.getString());
        +                } else {
        +                    reader.skipChildren();
        +                }
        +            }
        +            StickerNotificationContent deserializedStickerNotificationContent
        +                = new StickerNotificationContent(channelRegistrationId, to, mediaUrl);
        +            deserializedStickerNotificationContent.kind = kind;
        +            return deserializedStickerNotificationContent;
        +        });
        +    }
        +}
        diff --git a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/TextMessageContent.java b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/TextMessageContent.java
        new file mode 100644
        index 000000000000..31dbc6fc15a7
        --- /dev/null
        +++ b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/TextMessageContent.java
        @@ -0,0 +1,104 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) TypeSpec Code Generator.
        +package com.azure.communication.messages.models;
        +
        +import com.azure.core.annotation.Generated;
        +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 message content of type text information.
        + */
        +@Immutable
        +public final class TextMessageContent extends MessageContent {
        +
        +    /*
        +     * Kind of MessageContent.
        +     */
        +    @Generated
        +    private MessageContentKind kind = MessageContentKind.TEXT;
        +
        +    /*
        +     * The text value.
        +     */
        +    @Generated
        +    private final String text;
        +
        +    /**
        +     * Creates an instance of TextMessageContent class.
        +     *
        +     * @param text the text value to set.
        +     */
        +    @Generated
        +    public TextMessageContent(String text) {
        +        this.text = text;
        +    }
        +
        +    /**
        +     * Get the kind property: Kind of MessageContent.
        +     *
        +     * @return the kind value.
        +     */
        +    @Generated
        +    @Override
        +    public MessageContentKind getKind() {
        +        return this.kind;
        +    }
        +
        +    /**
        +     * Get the text property: The text value.
        +     *
        +     * @return the text value.
        +     */
        +    @Generated
        +    public String getText() {
        +        return this.text;
        +    }
        +
        +    /**
        +     * {@inheritDoc}
        +     */
        +    @Generated
        +    @Override
        +    public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
        +        jsonWriter.writeStartObject();
        +        jsonWriter.writeStringField("text", this.text);
        +        jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString());
        +        return jsonWriter.writeEndObject();
        +    }
        +
        +    /**
        +     * Reads an instance of TextMessageContent from the JsonReader.
        +     *
        +     * @param jsonReader The JsonReader being read.
        +     * @return An instance of TextMessageContent 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 TextMessageContent.
        +     */
        +    @Generated
        +    public static TextMessageContent fromJson(JsonReader jsonReader) throws IOException {
        +        return jsonReader.readObject(reader -> {
        +            String text = null;
        +            MessageContentKind kind = MessageContentKind.TEXT;
        +            while (reader.nextToken() != JsonToken.END_OBJECT) {
        +                String fieldName = reader.getFieldName();
        +                reader.nextToken();
        +                if ("text".equals(fieldName)) {
        +                    text = reader.getString();
        +                } else if ("kind".equals(fieldName)) {
        +                    kind = MessageContentKind.fromString(reader.getString());
        +                } else {
        +                    reader.skipChildren();
        +                }
        +            }
        +            TextMessageContent deserializedTextMessageContent = new TextMessageContent(text);
        +            deserializedTextMessageContent.kind = kind;
        +            return deserializedTextMessageContent;
        +        });
        +    }
        +}
        diff --git a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/VideoMessageContent.java b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/VideoMessageContent.java
        new file mode 100644
        index 000000000000..736d48581889
        --- /dev/null
        +++ b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/VideoMessageContent.java
        @@ -0,0 +1,104 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) TypeSpec Code Generator.
        +package com.azure.communication.messages.models;
        +
        +import com.azure.core.annotation.Generated;
        +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 message content of type video information.
        + */
        +@Immutable
        +public final class VideoMessageContent extends MessageContent {
        +
        +    /*
        +     * Kind of MessageContent.
        +     */
        +    @Generated
        +    private MessageContentKind kind = MessageContentKind.VIDEO;
        +
        +    /*
        +     * MediaUri of the media content.
        +     */
        +    @Generated
        +    private final String mediaUrl;
        +
        +    /**
        +     * Creates an instance of VideoMessageContent class.
        +     *
        +     * @param mediaUrl the mediaUrl value to set.
        +     */
        +    @Generated
        +    public VideoMessageContent(String mediaUrl) {
        +        this.mediaUrl = mediaUrl;
        +    }
        +
        +    /**
        +     * Get the kind property: Kind of MessageContent.
        +     *
        +     * @return the kind value.
        +     */
        +    @Generated
        +    @Override
        +    public MessageContentKind getKind() {
        +        return this.kind;
        +    }
        +
        +    /**
        +     * Get the mediaUrl property: MediaUri of the media content.
        +     *
        +     * @return the mediaUrl value.
        +     */
        +    @Generated
        +    public String getMediaUrl() {
        +        return this.mediaUrl;
        +    }
        +
        +    /**
        +     * {@inheritDoc}
        +     */
        +    @Generated
        +    @Override
        +    public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
        +        jsonWriter.writeStartObject();
        +        jsonWriter.writeStringField("mediaUri", this.mediaUrl);
        +        jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString());
        +        return jsonWriter.writeEndObject();
        +    }
        +
        +    /**
        +     * Reads an instance of VideoMessageContent from the JsonReader.
        +     *
        +     * @param jsonReader The JsonReader being read.
        +     * @return An instance of VideoMessageContent 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 VideoMessageContent.
        +     */
        +    @Generated
        +    public static VideoMessageContent fromJson(JsonReader jsonReader) throws IOException {
        +        return jsonReader.readObject(reader -> {
        +            String mediaUrl = null;
        +            MessageContentKind kind = MessageContentKind.VIDEO;
        +            while (reader.nextToken() != JsonToken.END_OBJECT) {
        +                String fieldName = reader.getFieldName();
        +                reader.nextToken();
        +                if ("mediaUri".equals(fieldName)) {
        +                    mediaUrl = reader.getString();
        +                } else if ("kind".equals(fieldName)) {
        +                    kind = MessageContentKind.fromString(reader.getString());
        +                } else {
        +                    reader.skipChildren();
        +                }
        +            }
        +            VideoMessageContent deserializedVideoMessageContent = new VideoMessageContent(mediaUrl);
        +            deserializedVideoMessageContent.kind = kind;
        +            return deserializedVideoMessageContent;
        +        });
        +    }
        +}
        diff --git a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/channels/WhatsAppButtonActionBindings.java b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/channels/WhatsAppButtonActionBindings.java
        new file mode 100644
        index 000000000000..ede678fd1e87
        --- /dev/null
        +++ b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/channels/WhatsAppButtonActionBindings.java
        @@ -0,0 +1,108 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) TypeSpec Code Generator.
        +package com.azure.communication.messages.models.channels;
        +
        +import com.azure.communication.messages.models.ActionBindings;
        +import com.azure.communication.messages.models.ButtonSetContent;
        +import com.azure.communication.messages.models.MessageActionBindingKind;
        +import com.azure.core.annotation.Generated;
        +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;
        +
        +/**
        + * WhatsApp Binding actions to the interactive message.
        + */
        +@Immutable
        +public final class WhatsAppButtonActionBindings extends ActionBindings {
        +
        +    /*
        +     * Kind of the MessageActionBinding.
        +     */
        +    @Generated
        +    private MessageActionBindingKind kind = MessageActionBindingKind.WHATS_APP_BUTTON_ACTION;
        +
        +    /*
        +     * Action content of Interactive message.
        +     */
        +    @Generated
        +    private final ButtonSetContent content;
        +
        +    /**
        +     * Creates an instance of WhatsAppButtonActionBindings class.
        +     *
        +     * @param content the content value to set.
        +     */
        +    @Generated
        +    public WhatsAppButtonActionBindings(ButtonSetContent content) {
        +        this.content = content;
        +    }
        +
        +    /**
        +     * Get the kind property: Kind of the MessageActionBinding.
        +     *
        +     * @return the kind value.
        +     */
        +    @Generated
        +    @Override
        +    public MessageActionBindingKind getKind() {
        +        return this.kind;
        +    }
        +
        +    /**
        +     * Get the content property: Action content of Interactive message.
        +     *
        +     * @return the content value.
        +     */
        +    @Generated
        +    public ButtonSetContent getContent() {
        +        return this.content;
        +    }
        +
        +    /**
        +     * {@inheritDoc}
        +     */
        +    @Generated
        +    @Override
        +    public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
        +        jsonWriter.writeStartObject();
        +        jsonWriter.writeJsonField("content", this.content);
        +        jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString());
        +        return jsonWriter.writeEndObject();
        +    }
        +
        +    /**
        +     * Reads an instance of WhatsAppButtonActionBindings from the JsonReader.
        +     *
        +     * @param jsonReader The JsonReader being read.
        +     * @return An instance of WhatsAppButtonActionBindings 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 WhatsAppButtonActionBindings.
        +     */
        +    @Generated
        +    public static WhatsAppButtonActionBindings fromJson(JsonReader jsonReader) throws IOException {
        +        return jsonReader.readObject(reader -> {
        +            ButtonSetContent content = null;
        +            MessageActionBindingKind kind = MessageActionBindingKind.WHATS_APP_BUTTON_ACTION;
        +            while (reader.nextToken() != JsonToken.END_OBJECT) {
        +                String fieldName = reader.getFieldName();
        +                reader.nextToken();
        +                if ("content".equals(fieldName)) {
        +                    content = ButtonSetContent.fromJson(reader);
        +                } else if ("kind".equals(fieldName)) {
        +                    kind = MessageActionBindingKind.fromString(reader.getString());
        +                } else {
        +                    reader.skipChildren();
        +                }
        +            }
        +            WhatsAppButtonActionBindings deserializedWhatsAppButtonActionBindings
        +                = new WhatsAppButtonActionBindings(content);
        +            deserializedWhatsAppButtonActionBindings.kind = kind;
        +            return deserializedWhatsAppButtonActionBindings;
        +        });
        +    }
        +}
        diff --git a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/channels/WhatsAppListActionBindings.java b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/channels/WhatsAppListActionBindings.java
        new file mode 100644
        index 000000000000..37c144bdb88a
        --- /dev/null
        +++ b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/channels/WhatsAppListActionBindings.java
        @@ -0,0 +1,107 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) TypeSpec Code Generator.
        +package com.azure.communication.messages.models.channels;
        +
        +import com.azure.communication.messages.models.ActionBindings;
        +import com.azure.communication.messages.models.ActionGroupContent;
        +import com.azure.communication.messages.models.MessageActionBindingKind;
        +import com.azure.core.annotation.Generated;
        +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;
        +
        +/**
        + * WhatsApp List Binding actions to the interactive message.
        + */
        +@Immutable
        +public final class WhatsAppListActionBindings extends ActionBindings {
        +
        +    /*
        +     * Kind of the MessageActionBinding.
        +     */
        +    @Generated
        +    private MessageActionBindingKind kind = MessageActionBindingKind.WHATS_APP_LIST_ACTION;
        +
        +    /*
        +     * Action content of Interactive message.
        +     */
        +    @Generated
        +    private final ActionGroupContent content;
        +
        +    /**
        +     * Creates an instance of WhatsAppListActionBindings class.
        +     *
        +     * @param content the content value to set.
        +     */
        +    @Generated
        +    public WhatsAppListActionBindings(ActionGroupContent content) {
        +        this.content = content;
        +    }
        +
        +    /**
        +     * Get the kind property: Kind of the MessageActionBinding.
        +     *
        +     * @return the kind value.
        +     */
        +    @Generated
        +    @Override
        +    public MessageActionBindingKind getKind() {
        +        return this.kind;
        +    }
        +
        +    /**
        +     * Get the content property: Action content of Interactive message.
        +     *
        +     * @return the content value.
        +     */
        +    @Generated
        +    public ActionGroupContent getContent() {
        +        return this.content;
        +    }
        +
        +    /**
        +     * {@inheritDoc}
        +     */
        +    @Generated
        +    @Override
        +    public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
        +        jsonWriter.writeStartObject();
        +        jsonWriter.writeJsonField("content", this.content);
        +        jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString());
        +        return jsonWriter.writeEndObject();
        +    }
        +
        +    /**
        +     * Reads an instance of WhatsAppListActionBindings from the JsonReader.
        +     *
        +     * @param jsonReader The JsonReader being read.
        +     * @return An instance of WhatsAppListActionBindings 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 WhatsAppListActionBindings.
        +     */
        +    @Generated
        +    public static WhatsAppListActionBindings fromJson(JsonReader jsonReader) throws IOException {
        +        return jsonReader.readObject(reader -> {
        +            ActionGroupContent content = null;
        +            MessageActionBindingKind kind = MessageActionBindingKind.WHATS_APP_LIST_ACTION;
        +            while (reader.nextToken() != JsonToken.END_OBJECT) {
        +                String fieldName = reader.getFieldName();
        +                reader.nextToken();
        +                if ("content".equals(fieldName)) {
        +                    content = ActionGroupContent.fromJson(reader);
        +                } else if ("kind".equals(fieldName)) {
        +                    kind = MessageActionBindingKind.fromString(reader.getString());
        +                } else {
        +                    reader.skipChildren();
        +                }
        +            }
        +            WhatsAppListActionBindings deserializedWhatsAppListActionBindings = new WhatsAppListActionBindings(content);
        +            deserializedWhatsAppListActionBindings.kind = kind;
        +            return deserializedWhatsAppListActionBindings;
        +        });
        +    }
        +}
        diff --git a/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/channels/WhatsAppUrlActionBindings.java b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/channels/WhatsAppUrlActionBindings.java
        new file mode 100644
        index 000000000000..254153941599
        --- /dev/null
        +++ b/sdk/communication/azure-communication-messages/src/main/java/com/azure/communication/messages/models/channels/WhatsAppUrlActionBindings.java
        @@ -0,0 +1,107 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) TypeSpec Code Generator.
        +package com.azure.communication.messages.models.channels;
        +
        +import com.azure.communication.messages.models.ActionBindings;
        +import com.azure.communication.messages.models.LinkContent;
        +import com.azure.communication.messages.models.MessageActionBindingKind;
        +import com.azure.core.annotation.Generated;
        +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;
        +
        +/**
        + * WhatsApp Binding actions to the interactive message.
        + */
        +@Immutable
        +public final class WhatsAppUrlActionBindings extends ActionBindings {
        +
        +    /*
        +     * Kind of the MessageActionBinding.
        +     */
        +    @Generated
        +    private MessageActionBindingKind kind = MessageActionBindingKind.WHATS_APP_URL_ACTION;
        +
        +    /*
        +     * Action content of Interactive message.
        +     */
        +    @Generated
        +    private final LinkContent content;
        +
        +    /**
        +     * Creates an instance of WhatsAppUrlActionBindings class.
        +     *
        +     * @param content the content value to set.
        +     */
        +    @Generated
        +    public WhatsAppUrlActionBindings(LinkContent content) {
        +        this.content = content;
        +    }
        +
        +    /**
        +     * Get the kind property: Kind of the MessageActionBinding.
        +     *
        +     * @return the kind value.
        +     */
        +    @Generated
        +    @Override
        +    public MessageActionBindingKind getKind() {
        +        return this.kind;
        +    }
        +
        +    /**
        +     * Get the content property: Action content of Interactive message.
        +     *
        +     * @return the content value.
        +     */
        +    @Generated
        +    public LinkContent getContent() {
        +        return this.content;
        +    }
        +
        +    /**
        +     * {@inheritDoc}
        +     */
        +    @Generated
        +    @Override
        +    public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
        +        jsonWriter.writeStartObject();
        +        jsonWriter.writeJsonField("content", this.content);
        +        jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString());
        +        return jsonWriter.writeEndObject();
        +    }
        +
        +    /**
        +     * Reads an instance of WhatsAppUrlActionBindings from the JsonReader.
        +     *
        +     * @param jsonReader The JsonReader being read.
        +     * @return An instance of WhatsAppUrlActionBindings 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 WhatsAppUrlActionBindings.
        +     */
        +    @Generated
        +    public static WhatsAppUrlActionBindings fromJson(JsonReader jsonReader) throws IOException {
        +        return jsonReader.readObject(reader -> {
        +            LinkContent content = null;
        +            MessageActionBindingKind kind = MessageActionBindingKind.WHATS_APP_URL_ACTION;
        +            while (reader.nextToken() != JsonToken.END_OBJECT) {
        +                String fieldName = reader.getFieldName();
        +                reader.nextToken();
        +                if ("content".equals(fieldName)) {
        +                    content = LinkContent.fromJson(reader);
        +                } else if ("kind".equals(fieldName)) {
        +                    kind = MessageActionBindingKind.fromString(reader.getString());
        +                } else {
        +                    reader.skipChildren();
        +                }
        +            }
        +            WhatsAppUrlActionBindings deserializedWhatsAppUrlActionBindings = new WhatsAppUrlActionBindings(content);
        +            deserializedWhatsAppUrlActionBindings.kind = kind;
        +            return deserializedWhatsAppUrlActionBindings;
        +        });
        +    }
        +}
        diff --git a/sdk/communication/azure-communication-messages/src/main/resources/META-INF/azure-communication-messages_apiview_properties.json b/sdk/communication/azure-communication-messages/src/main/resources/META-INF/azure-communication-messages_apiview_properties.json
        index 47302ac76e22..2e3d0e8156de 100644
        --- a/sdk/communication/azure-communication-messages/src/main/resources/META-INF/azure-communication-messages_apiview_properties.json
        +++ b/sdk/communication/azure-communication-messages/src/main/resources/META-INF/azure-communication-messages_apiview_properties.json
        @@ -17,12 +17,26 @@
             "com.azure.communication.messages.NotificationMessagesClient.send": "Azure.Communication.MessagesService.NotificationMessagesClient.send",
             "com.azure.communication.messages.NotificationMessagesClient.sendWithResponse": "Azure.Communication.MessagesService.NotificationMessagesClient.send",
             "com.azure.communication.messages.NotificationMessagesClientBuilder": "ClientForAcsMessages.NotificationMessagesClient",
        +    "com.azure.communication.messages.models.ActionBindings": "Azure.Communication.MessagesService.ActionBindings",
        +    "com.azure.communication.messages.models.ActionGroup": "Azure.Communication.MessagesService.ActionGroup",
        +    "com.azure.communication.messages.models.ActionGroupContent": "Azure.Communication.MessagesService.ActionGroupContent",
        +    "com.azure.communication.messages.models.ActionGroupItem": "Azure.Communication.MessagesService.ActionGroupItem",
             "com.azure.communication.messages.models.AudioNotificationContent": "Azure.Communication.MessagesService.AudioNotificationContent",
        +    "com.azure.communication.messages.models.ButtonContent": "Azure.Communication.MessagesService.ButtonContent",
        +    "com.azure.communication.messages.models.ButtonSetContent": "Azure.Communication.MessagesService.ButtonSetContent",
             "com.azure.communication.messages.models.CommunicationMessageKind": "Azure.Communication.MessagesService.CommunicationMessageKind",
             "com.azure.communication.messages.models.CommunicationMessagesChannel": "Azure.Communication.MessagesService.CommunicationMessagesChannel",
        +    "com.azure.communication.messages.models.DocumentMessageContent": "Azure.Communication.MessagesService.DocumentMessageContent",
             "com.azure.communication.messages.models.DocumentNotificationContent": "Azure.Communication.MessagesService.DocumentNotificationContent",
        +    "com.azure.communication.messages.models.ImageMessageContent": "Azure.Communication.MessagesService.ImageMessageContent",
             "com.azure.communication.messages.models.ImageNotificationContent": "Azure.Communication.MessagesService.ImageNotificationContent",
        +    "com.azure.communication.messages.models.InteractiveMessage": "Azure.Communication.MessagesService.InteractiveMessage",
        +    "com.azure.communication.messages.models.InteractiveNotificationContent": "Azure.Communication.MessagesService.InteractiveNotificationContent",
        +    "com.azure.communication.messages.models.LinkContent": "Azure.Communication.MessagesService.LinkContent",
             "com.azure.communication.messages.models.MediaNotificationContent": "Azure.Communication.MessagesService.MediaNotificationContent",
        +    "com.azure.communication.messages.models.MessageActionBindingKind": "Azure.Communication.MessagesService.MessageActionBindingKind",
        +    "com.azure.communication.messages.models.MessageContent": "Azure.Communication.MessagesService.MessageContent",
        +    "com.azure.communication.messages.models.MessageContentKind": "Azure.Communication.MessagesService.MessageContentKind",
             "com.azure.communication.messages.models.MessageReceipt": "Azure.Communication.MessagesService.MessageReceipt",
             "com.azure.communication.messages.models.MessageTemplate": "Azure.Communication.MessagesService.MessageTemplate",
             "com.azure.communication.messages.models.MessageTemplateBindings": "Azure.Communication.MessagesService.MessageTemplateBindings",
        @@ -38,14 +52,21 @@
             "com.azure.communication.messages.models.MessageTemplateValueKind": "Azure.Communication.MessagesService.MessageTemplateValueKind",
             "com.azure.communication.messages.models.MessageTemplateVideo": "Azure.Communication.MessagesService.MessageTemplateVideo",
             "com.azure.communication.messages.models.NotificationContent": "Azure.Communication.MessagesService.NotificationContent",
        +    "com.azure.communication.messages.models.ReactionNotificationContent": "Azure.Communication.MessagesService.ReactionNotificationContent",
             "com.azure.communication.messages.models.SendMessageResult": "Azure.Communication.MessagesService.SendMessageResult",
        +    "com.azure.communication.messages.models.StickerNotificationContent": "Azure.Communication.MessagesService.StickerNotificationContent",
             "com.azure.communication.messages.models.TemplateNotificationContent": "Azure.Communication.MessagesService.TemplateNotificationContent",
        +    "com.azure.communication.messages.models.TextMessageContent": "Azure.Communication.MessagesService.TextMessageContent",
             "com.azure.communication.messages.models.TextNotificationContent": "Azure.Communication.MessagesService.TextNotificationContent",
        +    "com.azure.communication.messages.models.VideoMessageContent": "Azure.Communication.MessagesService.VideoMessageContent",
             "com.azure.communication.messages.models.VideoNotificationContent": "Azure.Communication.MessagesService.VideoNotificationContent",
        +    "com.azure.communication.messages.models.channels.WhatsAppButtonActionBindings": "Azure.Communication.MessagesService.WhatsAppButtonActionBindings",
        +    "com.azure.communication.messages.models.channels.WhatsAppListActionBindings": "Azure.Communication.MessagesService.WhatsAppListActionBindings",
             "com.azure.communication.messages.models.channels.WhatsAppMessageButtonSubType": "Azure.Communication.MessagesService.WhatsAppMessageButtonSubType",
             "com.azure.communication.messages.models.channels.WhatsAppMessageTemplateBindings": "Azure.Communication.MessagesService.WhatsAppMessageTemplateBindings",
             "com.azure.communication.messages.models.channels.WhatsAppMessageTemplateBindingsButton": "Azure.Communication.MessagesService.WhatsAppMessageTemplateBindingsButton",
             "com.azure.communication.messages.models.channels.WhatsAppMessageTemplateBindingsComponent": "Azure.Communication.MessagesService.WhatsAppMessageTemplateBindingsComponent",
        -    "com.azure.communication.messages.models.channels.WhatsAppMessageTemplateItem": "Azure.Communication.MessagesService.WhatsAppMessageTemplateItem"
        +    "com.azure.communication.messages.models.channels.WhatsAppMessageTemplateItem": "Azure.Communication.MessagesService.WhatsAppMessageTemplateItem",
        +    "com.azure.communication.messages.models.channels.WhatsAppUrlActionBindings": "Azure.Communication.MessagesService.WhatsAppUrlActionBindings"
           }
         }
        diff --git a/sdk/communication/azure-communication-messages/src/samples/java/com/azure/communication/messages/NotificationMessageSample.java b/sdk/communication/azure-communication-messages/src/samples/java/com/azure/communication/messages/NotificationMessageSample.java
        index 748149927ce8..4df793bb66c6 100644
        --- a/sdk/communication/azure-communication-messages/src/samples/java/com/azure/communication/messages/NotificationMessageSample.java
        +++ b/sdk/communication/azure-communication-messages/src/samples/java/com/azure/communication/messages/NotificationMessageSample.java
        @@ -3,9 +3,18 @@
         
         package com.azure.communication.messages;
         
        +import com.azure.communication.messages.models.ActionGroup;
        +import com.azure.communication.messages.models.ActionGroupContent;
        +import com.azure.communication.messages.models.ActionGroupItem;
         import com.azure.communication.messages.models.AudioNotificationContent;
        +import com.azure.communication.messages.models.ButtonContent;
        +import com.azure.communication.messages.models.ButtonSetContent;
        +import com.azure.communication.messages.models.DocumentMessageContent;
         import com.azure.communication.messages.models.DocumentNotificationContent;
        +import com.azure.communication.messages.models.ImageMessageContent;
         import com.azure.communication.messages.models.ImageNotificationContent;
        +import com.azure.communication.messages.models.InteractiveMessage;
        +import com.azure.communication.messages.models.InteractiveNotificationContent;
         import com.azure.communication.messages.models.MessageTemplate;
         import com.azure.communication.messages.models.MessageTemplateBindings;
         import com.azure.communication.messages.models.MessageTemplateDocument;
        @@ -14,18 +23,27 @@
         import com.azure.communication.messages.models.MessageTemplateText;
         import com.azure.communication.messages.models.MessageTemplateValue;
         import com.azure.communication.messages.models.MessageTemplateVideo;
        +import com.azure.communication.messages.models.LinkContent;
        +import com.azure.communication.messages.models.ReactionNotificationContent;
        +import com.azure.communication.messages.models.StickerNotificationContent;
        +import com.azure.communication.messages.models.TextMessageContent;
         import com.azure.communication.messages.models.TextNotificationContent;
         import com.azure.communication.messages.models.TemplateNotificationContent;
        +import com.azure.communication.messages.models.VideoMessageContent;
         import com.azure.communication.messages.models.VideoNotificationContent;
         import com.azure.communication.messages.models.SendMessageResult;
        +import com.azure.communication.messages.models.channels.WhatsAppButtonActionBindings;
         import com.azure.communication.messages.models.channels.WhatsAppMessageButtonSubType;
         import com.azure.communication.messages.models.channels.WhatsAppMessageTemplateBindings;
         import com.azure.communication.messages.models.channels.WhatsAppMessageTemplateBindingsButton;
         import com.azure.communication.messages.models.channels.WhatsAppMessageTemplateBindingsComponent;
        +import com.azure.communication.messages.models.channels.WhatsAppListActionBindings;
        +import com.azure.communication.messages.models.channels.WhatsAppUrlActionBindings;
         import com.azure.core.credential.AzureKeyCredential;
         import com.azure.core.credential.TokenCredential;
         import com.azure.identity.DefaultAzureCredentialBuilder;
         
        +import java.io.IOException;
         import java.util.ArrayList;
         import java.util.List;
         
        @@ -38,7 +56,12 @@ public class NotificationMessageSample {
         
             public static void main(String[] args) {
                 TO_LIST.add(RECIPIENT_IDENTIFIER);
        -        sendTemplateMessageWithDocument();
        +        sendInteractiveMessageWithListAction();
        +        //sendOtpTemplateMessage();
        +        //sendTemplateMessageWithDocument();
        +        //sendStickerMessage();
        +        //sendReactionMessage();
        +        //sendImageMessage();
             }
         
             /*
        @@ -79,6 +102,80 @@ private static void sendTemplateMessage() {
                 result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId()));
             }
         
        +    /*
        +    * This sample shows how to send template message with below details
        +    * Name: otp, Language: en_US
        +    *  [
        +          {
        +            "type": "BODY",
        +            "text": "*{{1}}* is your verification code. For your security, do not share this code.",
        +            "example": {
        +              "body_text": [
        +                [
        +                  "123456"
        +                ]
        +              ]
        +            }
        +          },
        +          {
        +            "type": "FOOTER",
        +            "text": "This code expires in 10 minutes."
        +          },
        +          {
        +            "type": "BUTTONS",
        +            "buttons": [
        +              {
        +                "type": "URL",
        +                "text": "Copy code",
        +                "url": "https://www.whatsapp.com/otp/code/?otp_type=COPY_CODE&code_expiration_minutes=10&code=otp{{1}}",
        +                "example": [
        +                  "https://www.whatsapp.com/otp/code/?otp_type=COPY_CODE&code_expiration_minutes=10&code=otp123456"
        +                ]
        +              }
        +            ]
        +          }
        +        ]
        +    * */
        +    private static void sendOtpTemplateMessage() {
        +
        +        //Update Template Name and language according your template associate to your channel.
        +        MessageTemplate template = new MessageTemplate("otp", "en_US");
        +
        +        //Update template parameter type and value
        +        List messageTemplateValues = new ArrayList<>();
        +        messageTemplateValues.add(new MessageTemplateText("code", "123456"));
        +        MessageTemplateQuickAction btnRf = new MessageTemplateQuickAction("btnRf");
        +        btnRf.setText("123456");
        +        messageTemplateValues.add(btnRf);
        +        template.setValues(messageTemplateValues);
        +
        +        //Update template parameter binding
        +        List bodyComponents = new ArrayList<>();
        +        bodyComponents.add(new WhatsAppMessageTemplateBindingsComponent("code"));
        +
        +        List buttonComponents = new ArrayList<>();
        +        buttonComponents.add(new WhatsAppMessageTemplateBindingsButton(WhatsAppMessageButtonSubType.URL, "btnRf"));
        +
        +        MessageTemplateBindings bindings = new WhatsAppMessageTemplateBindings()
        +            .setBody(bodyComponents)
        +            .setButtons(buttonComponents);
        +        template.setBindings(bindings);
        +
        +        try {
        +            System.out.println(template.toJsonString());
        +        } catch (IOException e) {
        +            throw new RuntimeException(e);
        +        }
        +
        +        NotificationMessagesClient client = createClientWithConnectionString();
        +        SendMessageResult result = client.send(
        +            new TemplateNotificationContent(CHANNEL_ID, TO_LIST, template));
        +
        +
        +
        +        result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId()));
        +    }
        +
             /*
             * This sample shows how to send template message with below details
             * Name: sample_issue_resolution, Language: en_US
        @@ -391,6 +488,158 @@ public void sendDocumentMessage() {
                 result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId()));
             }
         
        +    /*
        +     * This sample shows how to send sticker message with below details
        +     * Supported sticker type - (.webp)
        +     * Note: Business cannot initiate conversation with media message.
        +     * */
        +    public static void sendStickerMessage() {
        +        //Update the Media URL
        +        String mediaUrl = "https://www.gstatic.com/webp/gallery/1.sm.webp";
        +        NotificationMessagesClient client = createClientWithConnectionString();
        +        SendMessageResult result = client.send(
        +            new StickerNotificationContent(CHANNEL_ID, TO_LIST, mediaUrl));
        +
        +        result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId()));
        +    }
        +
        +    /*
        +     * This sample shows how to send reaction message with below details
        +     * Emoji - unicode for emoji character.
        +     * Reply Message ID - ID of the message to be replied with emoji
        +     * Note: Business cannot initiate conversation with media message.
        +     * */
        +    public static void sendReactionMessage() {
        +        NotificationMessagesClient client = createClientWithConnectionString();
        +        SendMessageResult result = client.send(
        +            new ReactionNotificationContent(CHANNEL_ID, TO_LIST, "\uD83D\uDE00", "3b5c2a30-936b-4f26-bd5c-491b22e74853"));
        +
        +        result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId()));
        +    }
        +
        +    /*
        +     * This sample shows how to send interactive message with Button Action
        +     * Note: Business cannot initiate conversation with interactive message.
        +     * */
        +    public static void sendInteractiveMessageWithButtonAction() {
        +        NotificationMessagesClient client = createClientWithConnectionString();
        +        List buttonActions =  new ArrayList<>();
        +        buttonActions.add(new ButtonContent("no",  "No"));
        +        buttonActions.add(new ButtonContent("yes",  "Yes"));
        +        ButtonSetContent buttonSet = new ButtonSetContent(buttonActions);
        +        InteractiveMessage interactiveMessage = new InteractiveMessage(
        +            new TextMessageContent("Do you want to proceed?"), new WhatsAppButtonActionBindings(buttonSet));
        +        SendMessageResult result = client.send(
        +            new InteractiveNotificationContent(CHANNEL_ID,  TO_LIST, interactiveMessage));
        +
        +        result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId()));
        +    }
        +
        +    /*
        +     * This sample shows how to send button action interactive message with image header
        +     * Note: Business cannot initiate conversation with interactive message.
        +     * */
        +    public static void sendInteractiveMessageWithButtonActionWithImageHeader() {
        +        NotificationMessagesClient client = createClientWithConnectionString();
        +        List buttonActions =  new ArrayList<>();
        +        buttonActions.add(new ButtonContent("no",  "No"));
        +        buttonActions.add(new ButtonContent("yes",  "Yes"));
        +        ButtonSetContent buttonSet = new ButtonSetContent(buttonActions);
        +        InteractiveMessage interactiveMessage = new InteractiveMessage(
        +            new TextMessageContent("Do you want to proceed?"), new WhatsAppButtonActionBindings(buttonSet));
        +        interactiveMessage.setHeader(new ImageMessageContent("https://wallpapercave.com/wp/wp2163723.jpg"));
        +        SendMessageResult result = client.send(
        +            new InteractiveNotificationContent(CHANNEL_ID,  TO_LIST, interactiveMessage));
        +
        +        result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId()));
        +    }
        +
        +    /*
        +     * This sample shows how to send button action interactive message with document header
        +     * Note: Business cannot initiate conversation with interactive message.
        +     * */
        +    public static void sendInteractiveMessageWithButtonActionWithDocumentHeader() {
        +        NotificationMessagesClient client = createClientWithConnectionString();
        +        List buttonActions =  new ArrayList<>();
        +        buttonActions.add(new ButtonContent("no",  "No"));
        +        buttonActions.add(new ButtonContent("yes",  "Yes"));
        +        ButtonSetContent buttonSet = new ButtonSetContent(buttonActions);
        +        InteractiveMessage interactiveMessage = new InteractiveMessage(
        +            new TextMessageContent("Do you want to proceed?"), new WhatsAppButtonActionBindings(buttonSet));
        +        interactiveMessage.setHeader(new DocumentMessageContent("https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"));
        +        SendMessageResult result = client.send(
        +            new InteractiveNotificationContent(CHANNEL_ID,  TO_LIST, interactiveMessage));
        +
        +        result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId()));
        +    }
        +
        +    /*
        +     * This sample shows how to send button action interactive message with video header
        +     * Note: Business cannot initiate conversation with interactive message.
        +     * */
        +    public static void sendInteractiveMessageWithButtonActionWithVideoHeader() {
        +        NotificationMessagesClient client = createClientWithConnectionString();
        +        List buttonActions =  new ArrayList<>();
        +        buttonActions.add(new ButtonContent("no",  "No"));
        +        buttonActions.add(new ButtonContent("yes",  "Yes"));
        +        ButtonSetContent buttonSet = new ButtonSetContent(buttonActions);
        +        InteractiveMessage interactiveMessage = new InteractiveMessage(
        +            new TextMessageContent("Do you like it?"), new WhatsAppButtonActionBindings(buttonSet));
        +        interactiveMessage.setHeader(new VideoMessageContent("https://sample-videos.com/audio/mp3/wave.mp3"));
        +        SendMessageResult result = client.send(
        +            new InteractiveNotificationContent(CHANNEL_ID,  TO_LIST, interactiveMessage));
        +
        +        result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId()));
        +    }
        +
        +    /*
        +     * This sample shows how to send list action interactive message
        +     * Note: Business cannot initiate conversation with interactive message.
        +     * */
        +    public static void sendInteractiveMessageWithListAction() {
        +        List group1 = new ArrayList<>();
        +        group1.add(new ActionGroupItem("priority_express", "Priority Mail Express", "Delivered on same day!"));
        +        group1.add(new ActionGroupItem("priority_mail", "Priority Mail", "Delivered in 1-2 days"));
        +
        +        List group2 = new ArrayList<>();
        +        group2.add(new ActionGroupItem("usps_ground_advantage", "USPS Ground Advantage", "Delivered in 2-5 days"));
        +        group2.add(new ActionGroupItem("media_mail", "Media Mail", "Delivered in 5-8 days"));
        +
        +        List options = new ArrayList<>();
        +        options.add(new ActionGroup("Express Delivery", group1));
        +        options.add(new ActionGroup("Normal Delivery", group2));
        +
        +        ActionGroupContent actionGroupContent = new ActionGroupContent("Shipping Options", options);
        +        InteractiveMessage interactiveMessage = new InteractiveMessage(
        +            new TextMessageContent("Which shipping option do you want?"), new WhatsAppListActionBindings(actionGroupContent));
        +        interactiveMessage.setFooter(new TextMessageContent("Eagle Logistic"));
        +        interactiveMessage.setHeader(new TextMessageContent("Shipping Options"));
        +
        +        NotificationMessagesClient client = createClientWithConnectionString();
        +        SendMessageResult result = client.send(
        +            new InteractiveNotificationContent(CHANNEL_ID,  TO_LIST, interactiveMessage));
        +
        +        result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId()));
        +
        +    }
        +
        +    /*
        +     * This sample shows how to send url action interactive message
        +     * Note: Business cannot initiate conversation with interactive message.
        +     * */
        +    public static void sendInteractiveMessageWithUrlAction() {
        +        LinkContent urlAction = new LinkContent("Rocket is the best!", "https://wallpapercave.com/wp/wp2163723.jpg");
        +        InteractiveMessage interactiveMessage = new InteractiveMessage(
        +            new TextMessageContent("The best Guardian of Galaxy"), new WhatsAppUrlActionBindings(urlAction));
        +        interactiveMessage.setFooter(new TextMessageContent("Intergalactic New Ltd"));
        +
        +        NotificationMessagesClient client = createClientWithConnectionString();
        +        SendMessageResult result = client.send(
        +            new InteractiveNotificationContent(CHANNEL_ID,  TO_LIST, interactiveMessage));
        +
        +        result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId()));
        +    }
        +
             private static NotificationMessagesClient createClientWithConnectionString() {
                 return new NotificationMessagesClientBuilder()
                     .connectionString(CONNECTION_STRING)
        diff --git a/sdk/communication/azure-communication-messages/src/samples/java/com/azure/communication/messages/ReadmeSamples.java b/sdk/communication/azure-communication-messages/src/samples/java/com/azure/communication/messages/ReadmeSamples.java
        index 29d9a33c754c..bb6007519930 100644
        --- a/sdk/communication/azure-communication-messages/src/samples/java/com/azure/communication/messages/ReadmeSamples.java
        +++ b/sdk/communication/azure-communication-messages/src/samples/java/com/azure/communication/messages/ReadmeSamples.java
        @@ -4,21 +4,38 @@
         
         package com.azure.communication.messages;
         
        +import com.azure.communication.messages.models.ActionGroup;
        +import com.azure.communication.messages.models.ActionGroupContent;
        +import com.azure.communication.messages.models.ActionGroupItem;
         import com.azure.communication.messages.models.AudioNotificationContent;
        +import com.azure.communication.messages.models.ButtonContent;
        +import com.azure.communication.messages.models.ButtonSetContent;
        +import com.azure.communication.messages.models.DocumentMessageContent;
         import com.azure.communication.messages.models.DocumentNotificationContent;
        +import com.azure.communication.messages.models.ImageMessageContent;
         import com.azure.communication.messages.models.ImageNotificationContent;
        +import com.azure.communication.messages.models.InteractiveMessage;
        +import com.azure.communication.messages.models.InteractiveNotificationContent;
         import com.azure.communication.messages.models.MessageTemplate;
         import com.azure.communication.messages.models.MessageTemplateBindings;
         import com.azure.communication.messages.models.MessageTemplateItem;
         import com.azure.communication.messages.models.MessageTemplateText;
         import com.azure.communication.messages.models.MessageTemplateValue;
        -import com.azure.communication.messages.models.SendMessageResult;
        -import com.azure.communication.messages.models.TemplateNotificationContent;
        +import com.azure.communication.messages.models.LinkContent;
        +import com.azure.communication.messages.models.ReactionNotificationContent;
        +import com.azure.communication.messages.models.StickerNotificationContent;
        +import com.azure.communication.messages.models.TextMessageContent;
         import com.azure.communication.messages.models.TextNotificationContent;
        +import com.azure.communication.messages.models.TemplateNotificationContent;
        +import com.azure.communication.messages.models.VideoMessageContent;
         import com.azure.communication.messages.models.VideoNotificationContent;
        +import com.azure.communication.messages.models.SendMessageResult;
        +import com.azure.communication.messages.models.channels.WhatsAppButtonActionBindings;
         import com.azure.communication.messages.models.channels.WhatsAppMessageTemplateBindings;
         import com.azure.communication.messages.models.channels.WhatsAppMessageTemplateBindingsComponent;
         import com.azure.communication.messages.models.channels.WhatsAppMessageTemplateItem;
        +import com.azure.communication.messages.models.channels.WhatsAppListActionBindings;
        +import com.azure.communication.messages.models.channels.WhatsAppUrlActionBindings;
         import com.azure.core.credential.AzureKeyCredential;
         import com.azure.core.credential.TokenCredential;
         import com.azure.core.http.rest.PagedIterable;
        @@ -239,6 +256,207 @@ public void sendDocumentMessage() {
             }
             // END: readme-sample-sendDocumentMessage
         
        +    // BEGIN: readme-sample-sendStickerMessage
        +    /*
        +     * This sample shows how to send sticker message with below details
        +     * Supported sticker type - (.webp)
        +     * Note: Business cannot initiate conversation with media message.
        +     * */
        +    public static void sendStickerMessage() {
        +        //Update the Media URL
        +        String mediaUrl = "https://www.gstatic.com/webp/gallery/1.sm.webp";
        +        List recipients = new ArrayList<>();
        +        recipients.add("");
        +        NotificationMessagesClient client = new NotificationMessagesClientBuilder()
        +            .connectionString("")
        +            .buildClient();
        +        SendMessageResult result = client.send(
        +            new StickerNotificationContent("", recipients, mediaUrl));
        +
        +        result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId()));
        +    }
        +    // END: readme-sample-sendStickerMessage
        +
        +    // BEGIN: readme-sample-sendReactionMessage
        +    /*
        +     * This sample shows how to send reaction message with below details
        +     * Emoji - unicode for emoji character.
        +     * Reply Message ID - ID of the message to be replied with emoji
        +     * Note: Business cannot initiate conversation with media message.
        +     * */
        +    public static void sendReactionMessage() {
        +        List recipients = new ArrayList<>();
        +        recipients.add("");
        +        NotificationMessagesClient client = new NotificationMessagesClientBuilder()
        +            .connectionString("")
        +            .buildClient();
        +        SendMessageResult result = client.send(
        +            new ReactionNotificationContent("", recipients, "\uD83D\uDE00", ""));
        +
        +        result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId()));
        +    }
        +    // END: readme-sample-sendReactionMessage
        +
        +    // BEGIN: readme-sample-sendInteractiveMessageWithButtonAction
        +    /*
        +     * This sample shows how to send interactive message with Button Action
        +     * Note: Business cannot initiate conversation with interactive message.
        +     * */
        +    public void sendInteractiveMessageWithButtonAction() {
        +        List recipients = new ArrayList<>();
        +        recipients.add("");
        +        NotificationMessagesClient client = new NotificationMessagesClientBuilder()
        +            .connectionString("")
        +            .buildClient();
        +        List buttonActions =  new ArrayList<>();
        +        buttonActions.add(new ButtonContent("no",  "No"));
        +        buttonActions.add(new ButtonContent("yes",  "Yes"));
        +        ButtonSetContent buttonSet = new ButtonSetContent(buttonActions);
        +        InteractiveMessage interactiveMessage = new InteractiveMessage(
        +            new TextMessageContent("Do you want to proceed?"), new WhatsAppButtonActionBindings(buttonSet));
        +        SendMessageResult result = client.send(
        +            new InteractiveNotificationContent("",  recipients, interactiveMessage));
        +
        +        result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId()));
        +    }
        +    // END: readme-sample-sendInteractiveMessageWithButtonAction
        +
        +    // BEGIN: readme-sample-sendInteractiveMessageWithButtonActionWithImageHeader
        +    /*
        +     * This sample shows how to send button action interactive message with image header
        +     * Note: Business cannot initiate conversation with interactive message.
        +     * */
        +    public void sendInteractiveMessageWithButtonActionWithImageHeader() {
        +        List recipients = new ArrayList<>();
        +        recipients.add("");
        +        NotificationMessagesClient client = new NotificationMessagesClientBuilder()
        +            .connectionString("")
        +            .buildClient();
        +        List buttonActions =  new ArrayList<>();
        +        buttonActions.add(new ButtonContent("no",  "No"));
        +        buttonActions.add(new ButtonContent("yes",  "Yes"));
        +        ButtonSetContent buttonSet = new ButtonSetContent(buttonActions);
        +        InteractiveMessage interactiveMessage = new InteractiveMessage(
        +            new TextMessageContent("Do you want to proceed?"), new WhatsAppButtonActionBindings(buttonSet));
        +        interactiveMessage.setHeader(new ImageMessageContent("https://wallpapercave.com/wp/wp2163723.jpg"));
        +        SendMessageResult result = client.send(
        +            new InteractiveNotificationContent("",  recipients, interactiveMessage));
        +
        +        result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId()));
        +    }
        +    // END: readme-sample-sendInteractiveMessageWithButtonActionWithImageHeader
        +
        +    // BEGIN: readme-sample-sendInteractiveMessageWithButtonActionWithDocumentHeader
        +    /*
        +     * This sample shows how to send button action interactive message with document header
        +     * Note: Business cannot initiate conversation with interactive message.
        +     * */
        +    public static void sendInteractiveMessageWithButtonActionWithDocumentHeader() {
        +        List recipients = new ArrayList<>();
        +        recipients.add("");
        +        NotificationMessagesClient client = new NotificationMessagesClientBuilder()
        +            .connectionString("")
        +            .buildClient();
        +        List buttonActions =  new ArrayList<>();
        +        buttonActions.add(new ButtonContent("no",  "No"));
        +        buttonActions.add(new ButtonContent("yes",  "Yes"));
        +        ButtonSetContent buttonSet = new ButtonSetContent(buttonActions);
        +        InteractiveMessage interactiveMessage = new InteractiveMessage(
        +            new TextMessageContent("Do you want to proceed?"), new WhatsAppButtonActionBindings(buttonSet));
        +        interactiveMessage.setHeader(new DocumentMessageContent("https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"));
        +        SendMessageResult result = client.send(
        +            new InteractiveNotificationContent("",  recipients, interactiveMessage));
        +
        +        result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId()));
        +    }
        +    // END: readme-sample-sendInteractiveMessageWithButtonActionWithDocumentHeader
        +
        +
        +    // BEGIN: readme-sample-sendInteractiveMessageWithButtonActionWithVideoHeader
        +    /*
        +     * This sample shows how to send button action interactive message with video header
        +     * Note: Business cannot initiate conversation with interactive message.
        +     * */
        +    public static void sendInteractiveMessageWithButtonActionWithVideoHeader() {
        +        List recipients = new ArrayList<>();
        +        recipients.add("");
        +        NotificationMessagesClient client = new NotificationMessagesClientBuilder()
        +            .connectionString("")
        +            .buildClient();
        +        List buttonActions =  new ArrayList<>();
        +        buttonActions.add(new ButtonContent("no",  "No"));
        +        buttonActions.add(new ButtonContent("yes",  "Yes"));
        +        ButtonSetContent buttonSet = new ButtonSetContent(buttonActions);
        +        InteractiveMessage interactiveMessage = new InteractiveMessage(
        +            new TextMessageContent("Do you like it?"), new WhatsAppButtonActionBindings(buttonSet));
        +        interactiveMessage.setHeader(new VideoMessageContent("https://sample-videos.com/audio/mp3/wave.mp3"));
        +        SendMessageResult result = client.send(
        +            new InteractiveNotificationContent("",  recipients, interactiveMessage));
        +
        +        result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId()));
        +    }
        +    // END: readme-sample-sendInteractiveMessageWithButtonActionWithVideoHeader
        +
        +    // BEGIN: readme-sample-sendInteractiveMessageWithListAction
        +    /*
        +     * This sample shows how to send list action interactive message
        +     * Note: Business cannot initiate conversation with interactive message.
        +     * */
        +    public static void sendInteractiveMessageWithListAction() {
        +        List group1 = new ArrayList<>();
        +        group1.add(new ActionGroupItem("priority_express", "Priority Mail Express", "Delivered on same day!"));
        +        group1.add(new ActionGroupItem("priority_mail", "Priority Mail", "Delivered in 1-2 days"));
        +
        +        List group2 = new ArrayList<>();
        +        group2.add(new ActionGroupItem("usps_ground_advantage", "USPS Ground Advantage", "Delivered in 2-5 days"));
        +        group2.add(new ActionGroupItem("media_mail", "Media Mail", "Delivered in 5-8 days"));
        +
        +        List options = new ArrayList<>();
        +        options.add(new ActionGroup("Express Delivery", group1));
        +        options.add(new ActionGroup("Normal Delivery", group2));
        +
        +        ActionGroupContent actionGroupContent = new ActionGroupContent("Shipping Options", options);
        +        InteractiveMessage interactiveMessage = new InteractiveMessage(
        +            new TextMessageContent("Which shipping option do you want?"), new WhatsAppListActionBindings(actionGroupContent));
        +        interactiveMessage.setFooter(new TextMessageContent("Eagle Logistic"));
        +        interactiveMessage.setHeader(new TextMessageContent("Shipping Options"));
        +
        +        List recipients = new ArrayList<>();
        +        recipients.add("");
        +        NotificationMessagesClient client = new NotificationMessagesClientBuilder()
        +            .connectionString("")
        +            .buildClient();
        +        SendMessageResult result = client.send(
        +            new InteractiveNotificationContent("",  recipients, interactiveMessage));
        +
        +        result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId()));
        +
        +    }
        +    // END: readme-sample-sendInteractiveMessageWithListAction
        +
        +    // BEGIN: readme-sample-sendInteractiveMessageWithUrlAction
        +    /*
        +     * This sample shows how to send url action interactive message
        +     * Note: Business cannot initiate conversation with interactive message.
        +     * */
        +    public static void sendInteractiveMessageWithUrlAction() {
        +        LinkContent urlAction = new LinkContent("Rocket is the best!", "https://wallpapercave.com/wp/wp2163723.jpg");
        +        InteractiveMessage interactiveMessage = new InteractiveMessage(
        +            new TextMessageContent("The best Guardian of Galaxy"), new WhatsAppUrlActionBindings(urlAction));
        +        interactiveMessage.setFooter(new TextMessageContent("Intergalactic New Ltd"));
        +
        +        List recipients = new ArrayList<>();
        +        recipients.add("");
        +        NotificationMessagesClient client = new NotificationMessagesClientBuilder()
        +            .connectionString("")
        +            .buildClient();
        +        SendMessageResult result = client.send(
        +            new InteractiveNotificationContent("",  recipients, interactiveMessage));
        +
        +        result.getReceipts().forEach(r -> System.out.println("Message sent to:" + r.getTo() + " and message id:" + r.getMessageId()));
        +    }
        +    // END: readme-sample-sendInteractiveMessageWithUrlAction
        +
             public static void getMessageTemplateWithConnectionString() {
                 // BEGIN: readme-sample-ListTemplates
                 MessageTemplateClient templateClient =
        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 69595e96905d..da4384e7f389 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
        @@ -28,7 +28,7 @@ public class CommunicationMessagesTestBase extends TestProxyTestBase {
                     "endpoint=https://REDACTED.int.communication.azure.net;accessKey=secret");
         
             protected static final String CHANNEL_REGISTRATION_ID = Configuration.getGlobalConfiguration()
        -        .get("SENDER_CHANNEL_REGISTRATION_ID", "bc73327d-d246-4983-9e13-284468af7240");
        +        .get("SENDER_CHANNEL_REGISTRATION_ID", "77ffd898-ec44-42cd-b560-57a8903d05c7");
         
             protected static final String RECIPIENT_IDENTIFIER
                 = Configuration.getGlobalConfiguration().get("RECIPIENT_IDENTIFIER", "+11234567788");
        diff --git a/sdk/communication/azure-communication-messages/src/test/java/com/azure/communication/messages/NotificationMessageAsyncClientTest.java b/sdk/communication/azure-communication-messages/src/test/java/com/azure/communication/messages/NotificationMessageAsyncClientTest.java
        index 352353058cee..76f57826e7b8 100644
        --- a/sdk/communication/azure-communication-messages/src/test/java/com/azure/communication/messages/NotificationMessageAsyncClientTest.java
        +++ b/sdk/communication/azure-communication-messages/src/test/java/com/azure/communication/messages/NotificationMessageAsyncClientTest.java
        @@ -4,10 +4,7 @@
         package com.azure.communication.messages;
         
         import com.azure.communication.messages.models.*;
        -import com.azure.communication.messages.models.channels.WhatsAppMessageButtonSubType;
        -import com.azure.communication.messages.models.channels.WhatsAppMessageTemplateBindings;
        -import com.azure.communication.messages.models.channels.WhatsAppMessageTemplateBindingsButton;
        -import com.azure.communication.messages.models.channels.WhatsAppMessageTemplateBindingsComponent;
        +import com.azure.communication.messages.models.channels.*;
         import com.azure.core.credential.TokenCredential;
         import com.azure.core.http.HttpClient;
         import com.azure.core.test.utils.MockTokenCredential;
        @@ -100,6 +97,186 @@ public void shouldSendDocumentMessage(HttpClient httpClient) {
                     }).verifyComplete();
             }
         
        +    @ParameterizedTest
        +    @MethodSource("com.azure.core.test.TestBase#getHttpClients")
        +    public void sendStickerMessage(HttpClient httpClient) {
        +        String mediaUrl = "https://www.gstatic.com/webp/gallery/1.sm.webp";
        +        messagesClient = buildNotificationMessagesAsyncClient(httpClient);
        +        List recipients = new ArrayList<>();
        +        recipients.add(RECIPIENT_IDENTIFIER);
        +        StepVerifier
        +            .create(messagesClient.send(new StickerNotificationContent(CHANNEL_REGISTRATION_ID, recipients, mediaUrl)))
        +            .assertNext(resp -> {
        +                assertEquals(1, resp.getReceipts().size());
        +                assertNotNull(resp.getReceipts().get(0).getMessageId());
        +            })
        +            .verifyComplete();
        +    }
        +
        +    @ParameterizedTest
        +    @MethodSource("com.azure.core.test.TestBase#getHttpClients")
        +    public void sendReactionMessage(HttpClient httpClient) {
        +        messagesClient = buildNotificationMessagesAsyncClient(httpClient);
        +        List recipients = new ArrayList<>();
        +        recipients.add(RECIPIENT_IDENTIFIER);
        +        StepVerifier
        +            .create(messagesClient.send(new ReactionNotificationContent(CHANNEL_REGISTRATION_ID, recipients,
        +                "\uD83D\uDE00", "3b5c2a30-936b-4f26-bd5c-491b22e74853")))
        +            .assertNext(resp -> {
        +                assertEquals(1, resp.getReceipts().size());
        +                assertNotNull(resp.getReceipts().get(0).getMessageId());
        +            })
        +            .verifyComplete();
        +    }
        +
        +    @ParameterizedTest
        +    @MethodSource("com.azure.core.test.TestBase#getHttpClients")
        +    public void sendInteractiveMessageWithButtonAction(HttpClient httpClient) {
        +        messagesClient = buildNotificationMessagesAsyncClient(httpClient);
        +        List recipients = new ArrayList<>();
        +        recipients.add(RECIPIENT_IDENTIFIER);
        +        List buttonActions = new ArrayList<>();
        +        buttonActions.add(new ButtonContent("no", "No"));
        +        buttonActions.add(new ButtonContent("yes", "Yes"));
        +        ButtonSetContent buttonSet = new ButtonSetContent(buttonActions);
        +        InteractiveMessage interactiveMessage = new InteractiveMessage(
        +            new TextMessageContent("Do you want to proceed?"), new WhatsAppButtonActionBindings(buttonSet));
        +        StepVerifier
        +            .create(messagesClient
        +                .send(new InteractiveNotificationContent(CHANNEL_REGISTRATION_ID, recipients, interactiveMessage)))
        +            .assertNext(resp -> {
        +                assertEquals(1, resp.getReceipts().size());
        +                assertNotNull(resp.getReceipts().get(0).getMessageId());
        +            })
        +            .verifyComplete();
        +    }
        +
        +    @ParameterizedTest
        +    @MethodSource("com.azure.core.test.TestBase#getHttpClients")
        +    public void sendInteractiveMessageWithButtonActionWithImageHeader(HttpClient httpClient) {
        +        messagesClient = buildNotificationMessagesAsyncClient(httpClient);
        +        List recipients = new ArrayList<>();
        +        recipients.add(RECIPIENT_IDENTIFIER);
        +        List buttonActions = new ArrayList<>();
        +        buttonActions.add(new ButtonContent("no", "No"));
        +        buttonActions.add(new ButtonContent("yes", "Yes"));
        +        ButtonSetContent buttonSet = new ButtonSetContent(buttonActions);
        +        InteractiveMessage interactiveMessage = new InteractiveMessage(
        +            new TextMessageContent("Do you want to proceed?"), new WhatsAppButtonActionBindings(buttonSet));
        +        interactiveMessage.setHeader(new ImageMessageContent("https://wallpapercave.com/wp/wp2163723.jpg"));
        +        StepVerifier
        +            .create(messagesClient
        +                .send(new InteractiveNotificationContent(CHANNEL_REGISTRATION_ID, recipients, interactiveMessage)))
        +            .assertNext(resp -> {
        +                assertEquals(1, resp.getReceipts().size());
        +                assertNotNull(resp.getReceipts().get(0).getMessageId());
        +            })
        +            .verifyComplete();
        +    }
        +
        +    @ParameterizedTest
        +    @MethodSource("com.azure.core.test.TestBase#getHttpClients")
        +    public void sendInteractiveMessageWithButtonActionWithDocumentHeader(HttpClient httpClient) {
        +        messagesClient = buildNotificationMessagesAsyncClient(httpClient);
        +        List recipients = new ArrayList<>();
        +        recipients.add(RECIPIENT_IDENTIFIER);
        +        List buttonActions = new ArrayList<>();
        +        buttonActions.add(new ButtonContent("no", "No"));
        +        buttonActions.add(new ButtonContent("yes", "Yes"));
        +        ButtonSetContent buttonSet = new ButtonSetContent(buttonActions);
        +        InteractiveMessage interactiveMessage = new InteractiveMessage(
        +            new TextMessageContent("Do you want to proceed?"), new WhatsAppButtonActionBindings(buttonSet));
        +        interactiveMessage.setHeader(
        +            new DocumentMessageContent("https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"));
        +        StepVerifier
        +            .create(messagesClient
        +                .send(new InteractiveNotificationContent(CHANNEL_REGISTRATION_ID, recipients, interactiveMessage)))
        +            .assertNext(resp -> {
        +                assertEquals(1, resp.getReceipts().size());
        +                assertNotNull(resp.getReceipts().get(0).getMessageId());
        +            })
        +            .verifyComplete();
        +    }
        +
        +    @ParameterizedTest
        +    @MethodSource("com.azure.core.test.TestBase#getHttpClients")
        +    public void sendInteractiveMessageWithButtonActionWithVideoHeader(HttpClient httpClient) {
        +        messagesClient = buildNotificationMessagesAsyncClient(httpClient);
        +        List recipients = new ArrayList<>();
        +        recipients.add(RECIPIENT_IDENTIFIER);
        +        List buttonActions = new ArrayList<>();
        +        buttonActions.add(new ButtonContent("no", "No"));
        +        buttonActions.add(new ButtonContent("yes", "Yes"));
        +        ButtonSetContent buttonSet = new ButtonSetContent(buttonActions);
        +        InteractiveMessage interactiveMessage = new InteractiveMessage(new TextMessageContent("Do you like it?"),
        +            new WhatsAppButtonActionBindings(buttonSet));
        +        interactiveMessage.setHeader(new VideoMessageContent("https://sample-videos.com/audio/mp3/wave.mp3"));
        +        StepVerifier
        +            .create(messagesClient
        +                .send(new InteractiveNotificationContent(CHANNEL_REGISTRATION_ID, recipients, interactiveMessage)))
        +            .assertNext(resp -> {
        +                assertEquals(1, resp.getReceipts().size());
        +                assertNotNull(resp.getReceipts().get(0).getMessageId());
        +            })
        +            .verifyComplete();
        +    }
        +
        +    @ParameterizedTest
        +    @MethodSource("com.azure.core.test.TestBase#getHttpClients")
        +    public void sendInteractiveMessageWithListAction(HttpClient httpClient) {
        +        List group1 = new ArrayList<>();
        +        group1.add(new ActionGroupItem("priority_express", "Priority Mail Express", "Delivered on same day!"));
        +        group1.add(new ActionGroupItem("priority_mail", "Priority Mail", "Delivered in 1-2 days"));
        +
        +        List group2 = new ArrayList<>();
        +        group2.add(new ActionGroupItem("usps_ground_advantage", "USPS Ground Advantage", "Delivered in 2-5 days"));
        +        group2.add(new ActionGroupItem("media_mail", "Media Mail", "Delivered in 5-8 days"));
        +
        +        List options = new ArrayList<>();
        +        options.add(new ActionGroup("Express Delivery", group1));
        +        options.add(new ActionGroup("Normal Delivery", group2));
        +
        +        ActionGroupContent actionGroupContent = new ActionGroupContent("Shipping Options", options);
        +        InteractiveMessage interactiveMessage
        +            = new InteractiveMessage(new TextMessageContent("Which shipping option do you want?"),
        +                new WhatsAppListActionBindings(actionGroupContent));
        +        interactiveMessage.setFooter(new TextMessageContent("Eagle Logistic"));
        +        interactiveMessage.setHeader(new TextMessageContent("Shipping Options"));
        +
        +        messagesClient = buildNotificationMessagesAsyncClient(httpClient);
        +        List recipients = new ArrayList<>();
        +        recipients.add(RECIPIENT_IDENTIFIER);
        +        StepVerifier
        +            .create(messagesClient
        +                .send(new InteractiveNotificationContent(CHANNEL_REGISTRATION_ID, recipients, interactiveMessage)))
        +            .assertNext(resp -> {
        +                assertEquals(1, resp.getReceipts().size());
        +                assertNotNull(resp.getReceipts().get(0).getMessageId());
        +            })
        +            .verifyComplete();
        +    }
        +
        +    @ParameterizedTest
        +    @MethodSource("com.azure.core.test.TestBase#getHttpClients")
        +    public void sendInteractiveMessageWithUrlAction(HttpClient httpClient) {
        +        LinkContent urlAction = new LinkContent("Rocket is the best!", "https://wallpapercave.com/wp/wp2163723.jpg");
        +        InteractiveMessage interactiveMessage = new InteractiveMessage(
        +            new TextMessageContent("The best Guardian of Galaxy"), new WhatsAppUrlActionBindings(urlAction));
        +        interactiveMessage.setFooter(new TextMessageContent("Intergalactic New Ltd"));
        +
        +        messagesClient = buildNotificationMessagesAsyncClient(httpClient);
        +        List recipients = new ArrayList<>();
        +        recipients.add(RECIPIENT_IDENTIFIER);
        +        StepVerifier
        +            .create(messagesClient
        +                .send(new InteractiveNotificationContent(CHANNEL_REGISTRATION_ID, recipients, interactiveMessage)))
        +            .assertNext(resp -> {
        +                assertEquals(1, resp.getReceipts().size());
        +                assertNotNull(resp.getReceipts().get(0).getMessageId());
        +            })
        +            .verifyComplete();
        +    }
        +
             @ParameterizedTest
             @MethodSource("com.azure.core.test.TestBase#getHttpClients")
             public void shouldSendMessageTemplateWithImage(HttpClient httpClient) {
        diff --git a/sdk/communication/azure-communication-messages/src/test/java/com/azure/communication/messages/NotificationMessagesClientTest.java b/sdk/communication/azure-communication-messages/src/test/java/com/azure/communication/messages/NotificationMessagesClientTest.java
        index e82a4e24ee10..6e524244293f 100644
        --- a/sdk/communication/azure-communication-messages/src/test/java/com/azure/communication/messages/NotificationMessagesClientTest.java
        +++ b/sdk/communication/azure-communication-messages/src/test/java/com/azure/communication/messages/NotificationMessagesClientTest.java
        @@ -4,10 +4,7 @@
         package com.azure.communication.messages;
         
         import com.azure.communication.messages.models.*;
        -import com.azure.communication.messages.models.channels.WhatsAppMessageButtonSubType;
        -import com.azure.communication.messages.models.channels.WhatsAppMessageTemplateBindings;
        -import com.azure.communication.messages.models.channels.WhatsAppMessageTemplateBindingsButton;
        -import com.azure.communication.messages.models.channels.WhatsAppMessageTemplateBindingsComponent;
        +import com.azure.communication.messages.models.channels.*;
         import com.azure.core.credential.TokenCredential;
         import com.azure.core.http.HttpClient;
         import com.azure.core.test.utils.MockTokenCredential;
        @@ -117,6 +114,163 @@ public void shouldSendDocumentMessage(HttpClient httpClient) {
                 assertNotNull(result.getReceipts().get(0).getMessageId());
             }
         
        +    @ParameterizedTest
        +    @MethodSource("com.azure.core.test.TestBase#getHttpClients")
        +    public void sendStickerMessage(HttpClient httpClient) {
        +        String mediaUrl = "https://www.gstatic.com/webp/gallery/1.sm.webp";
        +        messagesClient = buildNotificationMessagesClient(httpClient);
        +        List recipients = new ArrayList<>();
        +        recipients.add(RECIPIENT_IDENTIFIER);
        +        SendMessageResult result
        +            = messagesClient.send(new StickerNotificationContent(CHANNEL_REGISTRATION_ID, recipients, mediaUrl));
        +
        +        assertEquals(1, result.getReceipts().size());
        +        assertNotNull(result.getReceipts().get(0).getMessageId());
        +    }
        +
        +    @ParameterizedTest
        +    @MethodSource("com.azure.core.test.TestBase#getHttpClients")
        +    public void sendReactionMessage(HttpClient httpClient) {
        +        messagesClient = buildNotificationMessagesClient(httpClient);
        +        List recipients = new ArrayList<>();
        +        recipients.add(RECIPIENT_IDENTIFIER);
        +        SendMessageResult result = messagesClient.send(new ReactionNotificationContent(CHANNEL_REGISTRATION_ID,
        +            recipients, "\uD83D\uDE00", "3b5c2a30-936b-4f26-bd5c-491b22e74853"));
        +
        +        assertEquals(1, result.getReceipts().size());
        +        assertNotNull(result.getReceipts().get(0).getMessageId());
        +    }
        +
        +    @ParameterizedTest
        +    @MethodSource("com.azure.core.test.TestBase#getHttpClients")
        +    public void sendInteractiveMessageWithButtonAction(HttpClient httpClient) {
        +        messagesClient = buildNotificationMessagesClient(httpClient);
        +        List recipients = new ArrayList<>();
        +        recipients.add(RECIPIENT_IDENTIFIER);
        +        List buttonActions = new ArrayList<>();
        +        buttonActions.add(new ButtonContent("no", "No"));
        +        buttonActions.add(new ButtonContent("yes", "Yes"));
        +        ButtonSetContent buttonSet = new ButtonSetContent(buttonActions);
        +        InteractiveMessage interactiveMessage = new InteractiveMessage(
        +            new TextMessageContent("Do you want to proceed?"), new WhatsAppButtonActionBindings(buttonSet));
        +        SendMessageResult result = messagesClient
        +            .send(new InteractiveNotificationContent(CHANNEL_REGISTRATION_ID, recipients, interactiveMessage));
        +
        +        assertEquals(1, result.getReceipts().size());
        +        assertNotNull(result.getReceipts().get(0).getMessageId());
        +    }
        +
        +    @ParameterizedTest
        +    @MethodSource("com.azure.core.test.TestBase#getHttpClients")
        +    public void sendInteractiveMessageWithButtonActionWithImageHeader(HttpClient httpClient) {
        +        messagesClient = buildNotificationMessagesClient(httpClient);
        +        List recipients = new ArrayList<>();
        +        recipients.add(RECIPIENT_IDENTIFIER);
        +        List buttonActions = new ArrayList<>();
        +        buttonActions.add(new ButtonContent("no", "No"));
        +        buttonActions.add(new ButtonContent("yes", "Yes"));
        +        ButtonSetContent buttonSet = new ButtonSetContent(buttonActions);
        +        InteractiveMessage interactiveMessage = new InteractiveMessage(
        +            new TextMessageContent("Do you want to proceed?"), new WhatsAppButtonActionBindings(buttonSet));
        +        interactiveMessage.setHeader(new ImageMessageContent("https://wallpapercave.com/wp/wp2163723.jpg"));
        +        SendMessageResult result = messagesClient
        +            .send(new InteractiveNotificationContent(CHANNEL_REGISTRATION_ID, recipients, interactiveMessage));
        +
        +        assertEquals(1, result.getReceipts().size());
        +        assertNotNull(result.getReceipts().get(0).getMessageId());
        +    }
        +
        +    @ParameterizedTest
        +    @MethodSource("com.azure.core.test.TestBase#getHttpClients")
        +    public void sendInteractiveMessageWithButtonActionWithDocumentHeader(HttpClient httpClient) {
        +        messagesClient = buildNotificationMessagesClient(httpClient);
        +        List recipients = new ArrayList<>();
        +        recipients.add(RECIPIENT_IDENTIFIER);
        +        List buttonActions = new ArrayList<>();
        +        buttonActions.add(new ButtonContent("no", "No"));
        +        buttonActions.add(new ButtonContent("yes", "Yes"));
        +        ButtonSetContent buttonSet = new ButtonSetContent(buttonActions);
        +        InteractiveMessage interactiveMessage = new InteractiveMessage(
        +            new TextMessageContent("Do you want to proceed?"), new WhatsAppButtonActionBindings(buttonSet));
        +        interactiveMessage.setHeader(
        +            new DocumentMessageContent("https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"));
        +        SendMessageResult result = messagesClient
        +            .send(new InteractiveNotificationContent(CHANNEL_REGISTRATION_ID, recipients, interactiveMessage));
        +
        +        assertEquals(1, result.getReceipts().size());
        +        assertNotNull(result.getReceipts().get(0).getMessageId());
        +    }
        +
        +    @ParameterizedTest
        +    @MethodSource("com.azure.core.test.TestBase#getHttpClients")
        +    public void sendInteractiveMessageWithButtonActionWithVideoHeader(HttpClient httpClient) {
        +        messagesClient = buildNotificationMessagesClient(httpClient);
        +        List recipients = new ArrayList<>();
        +        recipients.add(RECIPIENT_IDENTIFIER);
        +        List buttonActions = new ArrayList<>();
        +        buttonActions.add(new ButtonContent("no", "No"));
        +        buttonActions.add(new ButtonContent("yes", "Yes"));
        +        ButtonSetContent buttonSet = new ButtonSetContent(buttonActions);
        +        InteractiveMessage interactiveMessage = new InteractiveMessage(new TextMessageContent("Do you like it?"),
        +            new WhatsAppButtonActionBindings(buttonSet));
        +        interactiveMessage.setHeader(new VideoMessageContent("https://sample-videos.com/audio/mp3/wave.mp3"));
        +        SendMessageResult result = messagesClient
        +            .send(new InteractiveNotificationContent(CHANNEL_REGISTRATION_ID, recipients, interactiveMessage));
        +
        +        assertEquals(1, result.getReceipts().size());
        +        assertNotNull(result.getReceipts().get(0).getMessageId());
        +    }
        +
        +    @ParameterizedTest
        +    @MethodSource("com.azure.core.test.TestBase#getHttpClients")
        +    public void sendInteractiveMessageWithListAction(HttpClient httpClient) {
        +        List group1 = new ArrayList<>();
        +        group1.add(new ActionGroupItem("priority_express", "Priority Mail Express", "Delivered on same day!"));
        +        group1.add(new ActionGroupItem("priority_mail", "Priority Mail", "Delivered in 1-2 days"));
        +
        +        List group2 = new ArrayList<>();
        +        group2.add(new ActionGroupItem("usps_ground_advantage", "USPS Ground Advantage", "Delivered in 2-5 days"));
        +        group2.add(new ActionGroupItem("usps_mail", "USPS Mail", "Delivered in 5-8 days"));
        +
        +        List options = new ArrayList<>();
        +        options.add(new ActionGroup("Express Delivery", group1));
        +        options.add(new ActionGroup("Normal Delivery", group2));
        +
        +        ActionGroupContent actionGroupContent = new ActionGroupContent("Shipping Options", options);
        +        InteractiveMessage interactiveMessage
        +            = new InteractiveMessage(new TextMessageContent("Which shipping option do you want?"),
        +                new WhatsAppListActionBindings(actionGroupContent));
        +        interactiveMessage.setFooter(new TextMessageContent("Eagle Logistic"));
        +        interactiveMessage.setHeader(new TextMessageContent("Shipping Options"));
        +
        +        messagesClient = buildNotificationMessagesClient(httpClient);
        +        List recipients = new ArrayList<>();
        +        recipients.add(RECIPIENT_IDENTIFIER);
        +        SendMessageResult result = messagesClient
        +            .send(new InteractiveNotificationContent(CHANNEL_REGISTRATION_ID, recipients, interactiveMessage));
        +
        +        assertEquals(1, result.getReceipts().size());
        +        assertNotNull(result.getReceipts().get(0).getMessageId());
        +    }
        +
        +    @ParameterizedTest
        +    @MethodSource("com.azure.core.test.TestBase#getHttpClients")
        +    public void sendInteractiveMessageWithUrlAction(HttpClient httpClient) {
        +        LinkContent urlAction = new LinkContent("Rocket is the best!", "https://wallpapercave.com/wp/wp2163723.jpg");
        +        InteractiveMessage interactiveMessage = new InteractiveMessage(
        +            new TextMessageContent("The best Guardian of Galaxy"), new WhatsAppUrlActionBindings(urlAction));
        +        interactiveMessage.setFooter(new TextMessageContent("Intergalactic News Ltd"));
        +
        +        messagesClient = buildNotificationMessagesClient(httpClient);
        +        List recipients = new ArrayList<>();
        +        recipients.add(RECIPIENT_IDENTIFIER);
        +        SendMessageResult result = messagesClient
        +            .send(new InteractiveNotificationContent(CHANNEL_REGISTRATION_ID, recipients, interactiveMessage));
        +
        +        assertEquals(1, result.getReceipts().size());
        +        assertNotNull(result.getReceipts().get(0).getMessageId());
        +    }
        +
             @ParameterizedTest
             @MethodSource("com.azure.core.test.TestBase#getHttpClients")
             public void shouldSendMessageImageTemplate(HttpClient httpClient) {
        diff --git a/sdk/communication/azure-communication-messages/tsp-location.yaml b/sdk/communication/azure-communication-messages/tsp-location.yaml
        index 277f8c2c5f5a..68ed2cb02364 100644
        --- a/sdk/communication/azure-communication-messages/tsp-location.yaml
        +++ b/sdk/communication/azure-communication-messages/tsp-location.yaml
        @@ -1,4 +1,4 @@
         directory: specification/communication/Communication.Messages
        -commit: abe3209e7c6924a58ab560ebab2349bc8fde6aa7
        +commit: 7797d20dce4f18ee2b3709b894f22634d6fb8b1e
         repo: Azure/azure-rest-api-specs
         additionalDirectories: null
        diff --git a/sdk/communication/azure-communication-phonenumbers/CHANGELOG.md b/sdk/communication/azure-communication-phonenumbers/CHANGELOG.md
        index c51f7565aa00..aac50a75b60a 100644
        --- a/sdk/communication/azure-communication-phonenumbers/CHANGELOG.md
        +++ b/sdk/communication/azure-communication-phonenumbers/CHANGELOG.md
        @@ -1,6 +1,6 @@
         # Release History
         
        -## 1.2.0-beta.4 (Unreleased)
        +## 1.3.0-beta.1 (Unreleased)
         
         ### Features Added
         
        @@ -10,6 +10,22 @@
         
         ### Other Changes
         
        +## 1.2.1 (2025-03-03)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core-http-netty` from `1.15.8` to version `1.15.10`.
        +- Upgraded `azure-core` from `1.55.0` to version `1.55.2`.
        +
        +## 1.2.0 (2025-02-11)
        +
        +### Other Changes
        +
        +- Release of Number Insight GA.
        +- API version `2025-02-11` is the default.
        +
         ## 1.1.19 (2024-12-04)
         
         ### Other Changes
        diff --git a/sdk/communication/azure-communication-phonenumbers/README.md b/sdk/communication/azure-communication-phonenumbers/README.md
        index 3ec10ee449f6..2d872d086e30 100644
        --- a/sdk/communication/azure-communication-phonenumbers/README.md
        +++ b/sdk/communication/azure-communication-phonenumbers/README.md
        @@ -55,7 +55,7 @@ add the direct dependency to your project as follows.
         
           com.azure
           azure-communication-phonenumbers
        -  1.1.4
        +  1.3.0-beta.1
         
         ```
         
        @@ -332,4 +332,4 @@ Check out other client libraries for Azure communication service
         
         
         
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcommunication%2Fazure-communication-phonenumbers%2FREADME.png)
        +
        diff --git a/sdk/communication/azure-communication-phonenumbers/assets.json b/sdk/communication/azure-communication-phonenumbers/assets.json
        index 407d713a0173..783ea88e5031 100644
        --- a/sdk/communication/azure-communication-phonenumbers/assets.json
        +++ b/sdk/communication/azure-communication-phonenumbers/assets.json
        @@ -2,5 +2,5 @@
           "AssetsRepo": "Azure/azure-sdk-assets",
           "AssetsRepoPrefixPath": "java",
           "TagPrefix": "java/communication/azure-communication-phonenumbers",
        -  "Tag": "java/communication/azure-communication-phonenumbers_737e64b52b"
        +  "Tag": "java/communication/azure-communication-phonenumbers_2dd73df054"
         }
        diff --git a/sdk/communication/azure-communication-phonenumbers/pom.xml b/sdk/communication/azure-communication-phonenumbers/pom.xml
        index 85d7003ae7db..5aab531a9cec 100644
        --- a/sdk/communication/azure-communication-phonenumbers/pom.xml
        +++ b/sdk/communication/azure-communication-phonenumbers/pom.xml
        @@ -16,7 +16,7 @@
           com.azure
           azure-communication-phonenumbers
           jar
        -  1.2.0-beta.4 
        +  1.3.0-beta.1 
         
           Microsoft Azure client phone numbers library for communication
           
        @@ -67,17 +67,17 @@
             
               com.azure
               azure-core
        -      1.54.1 
        +      1.55.3 
             
             
               com.azure
               azure-core-http-netty
        -      1.15.7 
        +      1.15.11 
             
             
               com.azure
               azure-communication-common
        -      1.3.9 
        +      1.3.10 
             
             
               com.nimbusds
        @@ -88,7 +88,7 @@
             
               com.azure
               azure-core-test
        -      1.27.0-beta.4 
        +      1.27.0-beta.8 
               test
             
             
        @@ -114,7 +114,7 @@
             
               com.azure
               azure-identity
        -      1.15.0 
        +      1.15.4 
               test
             
           
        diff --git a/sdk/communication/azure-communication-phonenumbers/src/main/java/com/azure/communication/phonenumbers/CodeCoverageAnnotation.java b/sdk/communication/azure-communication-phonenumbers/src/main/java/com/azure/communication/phonenumbers/CodeCoverageAnnotation.java
        deleted file mode 100644
        index d9fbead0e9f4..000000000000
        --- a/sdk/communication/azure-communication-phonenumbers/src/main/java/com/azure/communication/phonenumbers/CodeCoverageAnnotation.java
        +++ /dev/null
        @@ -1,26 +0,0 @@
        -// Copyright (c) Microsoft Corporation. All rights reserved.
        -// Licensed under the MIT License.
        -
        -package com.azure.communication.phonenumbers;
        -
        -import java.lang.annotation.Documented;
        -import java.lang.annotation.ElementType;
        -import java.lang.annotation.Retention;
        -import java.lang.annotation.RetentionPolicy;
        -import java.lang.annotation.Target;
        -
        -/** Class used for code coverage. */
        -public class CodeCoverageAnnotation {
        -    /** Annotation used to exclude from code coverage */
        -    @Documented
        -    @Retention(RetentionPolicy.RUNTIME)
        -    @Target({ ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR })
        -    public @interface Generated {
        -    }
        -
        -    /**
        -     * Creates a new instance of {@link CodeCoverageAnnotation}.
        -     */
        -    public CodeCoverageAnnotation() {
        -    }
        -}
        diff --git a/sdk/communication/azure-communication-phonenumbers/src/main/java/com/azure/communication/phonenumbers/PhoneNumbersServiceVersion.java b/sdk/communication/azure-communication-phonenumbers/src/main/java/com/azure/communication/phonenumbers/PhoneNumbersServiceVersion.java
        index ac4b94ed4bc3..cf2c8c7b6e31 100644
        --- a/sdk/communication/azure-communication-phonenumbers/src/main/java/com/azure/communication/phonenumbers/PhoneNumbersServiceVersion.java
        +++ b/sdk/communication/azure-communication-phonenumbers/src/main/java/com/azure/communication/phonenumbers/PhoneNumbersServiceVersion.java
        @@ -15,9 +15,9 @@ public enum PhoneNumbersServiceVersion implements ServiceVersion {
             V2021_03_07("2021-03-07"),
         
             /**
        -     * Number Lookup update to public preview {@code 2024-03-01-preview}
        +     * Number Lookup GA {@code 2025-02-11}
              */
        -    V2024_03_01_PREVIEW("2024-03-01-preview");
        +    V2025_02_11("2025-02-11");
         
             private final String version;
         
        @@ -42,6 +42,6 @@ public String getVersion() {
              */
             public static PhoneNumbersServiceVersion getLatest() {
         
        -        return V2024_03_01_PREVIEW;
        +        return V2025_02_11;
             }
         }
        diff --git a/sdk/communication/azure-communication-phonenumbers/src/main/java/com/azure/communication/phonenumbers/implementation/PhoneNumberAdminClientImplBuilder.java b/sdk/communication/azure-communication-phonenumbers/src/main/java/com/azure/communication/phonenumbers/implementation/PhoneNumberAdminClientImplBuilder.java
        index 922462a46ffd..848b878b8dbe 100644
        --- a/sdk/communication/azure-communication-phonenumbers/src/main/java/com/azure/communication/phonenumbers/implementation/PhoneNumberAdminClientImplBuilder.java
        +++ b/sdk/communication/azure-communication-phonenumbers/src/main/java/com/azure/communication/phonenumbers/implementation/PhoneNumberAdminClientImplBuilder.java
        @@ -249,7 +249,7 @@ public PhoneNumberAdminClientImplBuilder retryPolicy(RetryPolicy retryPolicy) {
             @Generated
             public PhoneNumberAdminClientImpl buildClient() {
                 HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline();
        -        String localApiVersion = (apiVersion != null) ? apiVersion : "2024-03-01-preview";
        +        String localApiVersion = (apiVersion != null) ? apiVersion : "2025-02-11";
                 SerializerAdapter localSerializerAdapter
                     = (serializerAdapter != null) ? serializerAdapter : JacksonAdapter.createDefaultSerializerAdapter();
                 PhoneNumberAdminClientImpl client
        diff --git a/sdk/communication/azure-communication-phonenumbers/src/main/java/com/azure/communication/phonenumbers/implementation/models/PhoneNumberSearchResultError.java b/sdk/communication/azure-communication-phonenumbers/src/main/java/com/azure/communication/phonenumbers/implementation/models/PhoneNumberSearchResultError.java
        deleted file mode 100644
        index f2d7d760ffe0..000000000000
        --- a/sdk/communication/azure-communication-phonenumbers/src/main/java/com/azure/communication/phonenumbers/implementation/models/PhoneNumberSearchResultError.java
        +++ /dev/null
        @@ -1,93 +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.phonenumbers.implementation.models;
        -
        -import com.azure.core.util.ExpandableStringEnum;
        -
        -import java.util.Collection;
        -
        -/** Defines values for PhoneNumberSearchResultError. */
        -public final class PhoneNumberSearchResultError extends ExpandableStringEnum {
        -    /** Static value NoError for PhoneNumberSearchResultError. */
        -    public static final PhoneNumberSearchResultError NO_ERROR = fromString("NoError");
        -
        -    /** Static value UnknownErrorCode for PhoneNumberSearchResultError. */
        -    public static final PhoneNumberSearchResultError UNKNOWN_ERROR_CODE = fromString("UnknownErrorCode");
        -
        -    /** Static value OutOfStock for PhoneNumberSearchResultError. */
        -    public static final PhoneNumberSearchResultError OUT_OF_STOCK = fromString("OutOfStock");
        -
        -    /** Static value AuthorizationDenied for PhoneNumberSearchResultError. */
        -    public static final PhoneNumberSearchResultError AUTHORIZATION_DENIED = fromString("AuthorizationDenied");
        -
        -    /** Static value MissingAddress for PhoneNumberSearchResultError. */
        -    public static final PhoneNumberSearchResultError MISSING_ADDRESS = fromString("MissingAddress");
        -
        -    /** Static value InvalidAddress for PhoneNumberSearchResultError. */
        -    public static final PhoneNumberSearchResultError INVALID_ADDRESS = fromString("InvalidAddress");
        -
        -    /** Static value InvalidOfferModel for PhoneNumberSearchResultError. */
        -    public static final PhoneNumberSearchResultError INVALID_OFFER_MODEL = fromString("InvalidOfferModel");
        -
        -    /** Static value NotEnoughLicenses for PhoneNumberSearchResultError. */
        -    public static final PhoneNumberSearchResultError NOT_ENOUGH_LICENSES = fromString("NotEnoughLicenses");
        -
        -    /** Static value NoWallet for PhoneNumberSearchResultError. */
        -    public static final PhoneNumberSearchResultError NO_WALLET = fromString("NoWallet");
        -
        -    /** Static value NotEnoughCredit for PhoneNumberSearchResultError. */
        -    public static final PhoneNumberSearchResultError NOT_ENOUGH_CREDIT = fromString("NotEnoughCredit");
        -
        -    /** Static value NumbersPartiallyAcquired for PhoneNumberSearchResultError. */
        -    public static final PhoneNumberSearchResultError NUMBERS_PARTIALLY_ACQUIRED
        -        = fromString("NumbersPartiallyAcquired");
        -
        -    /** Static value AllNumbersNotAcquired for PhoneNumberSearchResultError. */
        -    public static final PhoneNumberSearchResultError ALL_NUMBERS_NOT_ACQUIRED = fromString("AllNumbersNotAcquired");
        -
        -    /** Static value ReservationExpired for PhoneNumberSearchResultError. */
        -    public static final PhoneNumberSearchResultError RESERVATION_EXPIRED = fromString("ReservationExpired");
        -
        -    /** Static value PurchaseFailed for PhoneNumberSearchResultError. */
        -    public static final PhoneNumberSearchResultError PURCHASE_FAILED = fromString("PurchaseFailed");
        -
        -    /** Static value BillingUnavailable for PhoneNumberSearchResultError. */
        -    public static final PhoneNumberSearchResultError BILLING_UNAVAILABLE = fromString("BillingUnavailable");
        -
        -    /** Static value ProvisioningFailed for PhoneNumberSearchResultError. */
        -    public static final PhoneNumberSearchResultError PROVISIONING_FAILED = fromString("ProvisioningFailed");
        -
        -    /** Static value UnknownSearchError for PhoneNumberSearchResultError. */
        -    public static final PhoneNumberSearchResultError UNKNOWN_SEARCH_ERROR = fromString("UnknownSearchError");
        -
        -    /**
        -     * Creates an instance of {@link PhoneNumberSearchResultError} with no string value.
        -     *
        -     * @deprecated Use {@link #fromString(String)} to create or get an instance of {@link PhoneNumberSearchResultError}
        -     * instead.
        -     */
        -    @Deprecated
        -    public PhoneNumberSearchResultError() {
        -    }
        -
        -    /**
        -     * Creates or finds a PhoneNumberSearchResultError from its string representation.
        -     *
        -     * @param name a name to look for.
        -     * @return the corresponding PhoneNumberSearchResultError.
        -     */
        -    public static PhoneNumberSearchResultError fromString(String name) {
        -        return fromString(name, PhoneNumberSearchResultError.class);
        -    }
        -
        -    /**
        -     * Gets known PhoneNumberSearchResultError values.
        -     *
        -     * @return known PhoneNumberSearchResultError values.
        -     */
        -    public static Collection values() {
        -        return values(PhoneNumberSearchResultError.class);
        -    }
        -}
        diff --git a/sdk/communication/azure-communication-phonenumbers/src/main/java/com/azure/communication/phonenumbers/models/OperatorDetails.java b/sdk/communication/azure-communication-phonenumbers/src/main/java/com/azure/communication/phonenumbers/models/OperatorDetails.java
        index c79549f59d42..6cc2bdd74e81 100644
        --- a/sdk/communication/azure-communication-phonenumbers/src/main/java/com/azure/communication/phonenumbers/models/OperatorDetails.java
        +++ b/sdk/communication/azure-communication-phonenumbers/src/main/java/com/azure/communication/phonenumbers/models/OperatorDetails.java
        @@ -22,12 +22,12 @@ public final class OperatorDetails implements JsonSerializable
             private String name;
         
             /*
        -     * Mobile Network Code
        +     * Mobile Network Code, 2 or 3 decimal digits that identify mobile networks within a country/region
              */
             private String mobileNetworkCode;
         
             /*
        -     * Mobile Country Code
        +     * Mobile Country Code, 3 decimal digits that identify a country/region
              */
             private String mobileCountryCode;
         
        diff --git a/sdk/communication/azure-communication-phonenumbers/src/main/java/com/azure/communication/phonenumbers/models/PhoneNumberSearchResult.java b/sdk/communication/azure-communication-phonenumbers/src/main/java/com/azure/communication/phonenumbers/models/PhoneNumberSearchResult.java
        index e82533c6d7bb..c3916596d469 100644
        --- a/sdk/communication/azure-communication-phonenumbers/src/main/java/com/azure/communication/phonenumbers/models/PhoneNumberSearchResult.java
        +++ b/sdk/communication/azure-communication-phonenumbers/src/main/java/com/azure/communication/phonenumbers/models/PhoneNumberSearchResult.java
        @@ -53,16 +53,6 @@ public final class PhoneNumberSearchResult implements JsonSerializable OffsetDateTime.parse(nonNullReader.getString()));
        -                } else if ("errorCode".equals(fieldName)) {
        -                    deserializedPhoneNumberSearchResult.errorCode = reader.getNullable(JsonReader::getInt);
        -                } else if ("error".equals(fieldName)) {
        -                    deserializedPhoneNumberSearchResult.error
        -                        = PhoneNumberSearchResultError.fromString(reader.getString());
                         } else {
                             reader.skipChildren();
                         }
        diff --git a/sdk/communication/azure-communication-phonenumbers/src/main/java/com/azure/communication/phonenumbers/models/PhoneNumberSearchResultError.java b/sdk/communication/azure-communication-phonenumbers/src/main/java/com/azure/communication/phonenumbers/models/PhoneNumberSearchResultError.java
        deleted file mode 100644
        index a1d858c6505d..000000000000
        --- a/sdk/communication/azure-communication-phonenumbers/src/main/java/com/azure/communication/phonenumbers/models/PhoneNumberSearchResultError.java
        +++ /dev/null
        @@ -1,127 +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.phonenumbers.models;
        -
        -import com.azure.core.util.ExpandableStringEnum;
        -import java.util.Collection;
        -
        -/**
        - * Mapping Error Messages to Codes.
        - */
        -public final class PhoneNumberSearchResultError extends ExpandableStringEnum {
        -    /**
        -     * Static value NoError for PhoneNumberSearchResultError.
        -     */
        -    public static final PhoneNumberSearchResultError NO_ERROR = fromString("NoError");
        -
        -    /**
        -     * Static value UnknownErrorCode for PhoneNumberSearchResultError.
        -     */
        -    public static final PhoneNumberSearchResultError UNKNOWN_ERROR_CODE = fromString("UnknownErrorCode");
        -
        -    /**
        -     * Static value OutOfStock for PhoneNumberSearchResultError.
        -     */
        -    public static final PhoneNumberSearchResultError OUT_OF_STOCK = fromString("OutOfStock");
        -
        -    /**
        -     * Static value AuthorizationDenied for PhoneNumberSearchResultError.
        -     */
        -    public static final PhoneNumberSearchResultError AUTHORIZATION_DENIED = fromString("AuthorizationDenied");
        -
        -    /**
        -     * Static value MissingAddress for PhoneNumberSearchResultError.
        -     */
        -    public static final PhoneNumberSearchResultError MISSING_ADDRESS = fromString("MissingAddress");
        -
        -    /**
        -     * Static value InvalidAddress for PhoneNumberSearchResultError.
        -     */
        -    public static final PhoneNumberSearchResultError INVALID_ADDRESS = fromString("InvalidAddress");
        -
        -    /**
        -     * Static value InvalidOfferModel for PhoneNumberSearchResultError.
        -     */
        -    public static final PhoneNumberSearchResultError INVALID_OFFER_MODEL = fromString("InvalidOfferModel");
        -
        -    /**
        -     * Static value NotEnoughLicenses for PhoneNumberSearchResultError.
        -     */
        -    public static final PhoneNumberSearchResultError NOT_ENOUGH_LICENSES = fromString("NotEnoughLicenses");
        -
        -    /**
        -     * Static value NoWallet for PhoneNumberSearchResultError.
        -     */
        -    public static final PhoneNumberSearchResultError NO_WALLET = fromString("NoWallet");
        -
        -    /**
        -     * Static value NotEnoughCredit for PhoneNumberSearchResultError.
        -     */
        -    public static final PhoneNumberSearchResultError NOT_ENOUGH_CREDIT = fromString("NotEnoughCredit");
        -
        -    /**
        -     * Static value NumbersPartiallyAcquired for PhoneNumberSearchResultError.
        -     */
        -    public static final PhoneNumberSearchResultError NUMBERS_PARTIALLY_ACQUIRED
        -        = fromString("NumbersPartiallyAcquired");
        -
        -    /**
        -     * Static value AllNumbersNotAcquired for PhoneNumberSearchResultError.
        -     */
        -    public static final PhoneNumberSearchResultError ALL_NUMBERS_NOT_ACQUIRED = fromString("AllNumbersNotAcquired");
        -
        -    /**
        -     * Static value ReservationExpired for PhoneNumberSearchResultError.
        -     */
        -    public static final PhoneNumberSearchResultError RESERVATION_EXPIRED = fromString("ReservationExpired");
        -
        -    /**
        -     * Static value PurchaseFailed for PhoneNumberSearchResultError.
        -     */
        -    public static final PhoneNumberSearchResultError PURCHASE_FAILED = fromString("PurchaseFailed");
        -
        -    /**
        -     * Static value BillingUnavailable for PhoneNumberSearchResultError.
        -     */
        -    public static final PhoneNumberSearchResultError BILLING_UNAVAILABLE = fromString("BillingUnavailable");
        -
        -    /**
        -     * Static value ProvisioningFailed for PhoneNumberSearchResultError.
        -     */
        -    public static final PhoneNumberSearchResultError PROVISIONING_FAILED = fromString("ProvisioningFailed");
        -
        -    /**
        -     * Static value UnknownSearchError for PhoneNumberSearchResultError.
        -     */
        -    public static final PhoneNumberSearchResultError UNKNOWN_SEARCH_ERROR = fromString("UnknownSearchError");
        -
        -    /**
        -     * Creates a new instance of PhoneNumberSearchResultError value.
        -     * 
        -     * @deprecated Use the {@link #fromString(String)} factory method.
        -     */
        -    @Deprecated
        -    public PhoneNumberSearchResultError() {
        -    }
        -
        -    /**
        -     * Creates or finds a PhoneNumberSearchResultError from its string representation.
        -     * 
        -     * @param name a name to look for.
        -     * @return the corresponding PhoneNumberSearchResultError.
        -     */
        -    public static PhoneNumberSearchResultError fromString(String name) {
        -        return fromString(name, PhoneNumberSearchResultError.class);
        -    }
        -
        -    /**
        -     * Gets known PhoneNumberSearchResultError values.
        -     * 
        -     * @return known PhoneNumberSearchResultError values.
        -     */
        -    public static Collection values() {
        -        return values(PhoneNumberSearchResultError.class);
        -    }
        -}
        diff --git a/sdk/communication/azure-communication-phonenumbers/src/test/java/com/azure/communication/phonenumbers/PhoneNumbersClientBuilderTest.java b/sdk/communication/azure-communication-phonenumbers/src/test/java/com/azure/communication/phonenumbers/PhoneNumbersClientBuilderTest.java
        index b175f44f38b9..01c93cff4081 100644
        --- a/sdk/communication/azure-communication-phonenumbers/src/test/java/com/azure/communication/phonenumbers/PhoneNumbersClientBuilderTest.java
        +++ b/sdk/communication/azure-communication-phonenumbers/src/test/java/com/azure/communication/phonenumbers/PhoneNumbersClientBuilderTest.java
        @@ -25,6 +25,7 @@
         import java.util.concurrent.atomic.AtomicReference;
         
         import static org.junit.jupiter.api.Assertions.*;
        +import static org.mockito.ArgumentMatchers.any;
         import static org.mockito.Mockito.*;
         
         @Execution(value = ExecutionMode.SAME_THREAD)
        @@ -110,7 +111,7 @@ public void buildClientWithConfiguration() {
             public void buildClientWithServiceVersion() {
                 // Build client with required settings and mock configuration
                 PhoneNumbersClient phoneNumberClient = this.setupBuilderWithHttpClientWithCredential(this.clientBuilder)
        -            .serviceVersion(PhoneNumbersServiceVersion.V2024_03_01_PREVIEW)
        +            .serviceVersion(PhoneNumbersServiceVersion.V2025_02_11)
                     .buildClient();
         
                 // Validate client created with expected settings
        @@ -227,7 +228,7 @@ public void buildAsyncClientWithServiceVersion() {
                 // Build client with required settings and mock configuration
                 PhoneNumbersAsyncClient phoneNumberAsyncClient
                     = this.setupBuilderWithHttpClientWithCredential(this.clientBuilder)
        -                .serviceVersion(PhoneNumbersServiceVersion.V2024_03_01_PREVIEW)
        +                .serviceVersion(PhoneNumbersServiceVersion.V2025_02_11)
                         .buildAsyncClient();
         
                 // Validate client created with expected settings
        diff --git a/sdk/communication/azure-communication-phonenumbers/swagger/README.md b/sdk/communication/azure-communication-phonenumbers/swagger/README.md
        index 995c8adf41d3..c3938eda50ba 100644
        --- a/sdk/communication/azure-communication-phonenumbers/swagger/README.md
        +++ b/sdk/communication/azure-communication-phonenumbers/swagger/README.md
        @@ -23,9 +23,9 @@ autorest README.md --java --v4 --use=@autorest/java@4.0.2
         
         ### Code generation settings
         ``` yaml
        -tag: package-phonenumber-2024-03-01-preview
        +tag: package-phonenumber-2025-02-11
         use: '@autorest/java@4.1.29'
        -require: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/b56afb26c5450157006a3a1d9be57bae429051a2/specification/communication/data-plane/PhoneNumbers/readme.md
        +require: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/a3d9c16f14fbfa814d6315a4972517cec77c6bfb/specification/communication/data-plane/PhoneNumbers/readme.md
         override-client-name: PhoneNumberAdminClient
         custom-types: PurchasedPhoneNumber,BillingFrequency,PhoneNumberOperationStatus,PhoneNumberOperationStatusCodes,PhoneNumberOperationType,PhoneNumberAssignmentType,PhoneNumberCapabilities,PhoneNumberCapabilityType,PhoneNumberCost,PhoneNumberSearchResult,PhoneNumberType,PhoneNumberCapability,PhoneNumberAdministrativeDivision,PhoneNumberCountry,PhoneNumberLocality,PhoneNumberOffering,AreaCodeResult,AreaCodes,PhoneNumberAreaCode,PhoneNumberSearchResultError,OperatorDetails,OperatorInformation,OperatorInformationResult,OperatorInformationOptions,OperatorNumberType
         custom-types-subpackage: models
        diff --git a/sdk/communication/azure-communication-rooms/CHANGELOG.md b/sdk/communication/azure-communication-rooms/CHANGELOG.md
        index 5455d1184441..6233a49902be 100644
        --- a/sdk/communication/azure-communication-rooms/CHANGELOG.md
        +++ b/sdk/communication/azure-communication-rooms/CHANGELOG.md
        @@ -1,15 +1,27 @@
         # Release History
         
        -## 1.2.0-beta.1 (Unreleased)
        +## 1.2.0 (2025-03-13)
         
         ### Features Added
        +- General Availability version of Collaborator role.
         
        -### Breaking Changes
        +### Other Changes
        +#### Dependency Updates
        +- Upgraded `azure-identity` from `1.14.2` to version `1.15.2`
        +- Upgraded `azure-core` from `1.54.1` to version `1.55.1`.
        +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.9`.
        +- Upgraded `azure-core-test` from `1.27.0-beta.4` to version `1.27.0-beta.6`.
         
        -### Bugs Fixed
        +## 1.1.9 (2025-03-03)
         
         ### Other Changes
         
        +#### Dependency Updates
        +
        +- Upgraded `azure-communication-common` from `1.3.8` to version `1.3.9`.
        +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`.
        +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`.
        +
         ## 1.1.8 (2024-12-04)
         
         ### Other Changes
        diff --git a/sdk/communication/azure-communication-rooms/README.md b/sdk/communication/azure-communication-rooms/README.md
        index 9884725da82d..32dafa27d6f1 100644
        --- a/sdk/communication/azure-communication-rooms/README.md
        +++ b/sdk/communication/azure-communication-rooms/README.md
        @@ -25,7 +25,7 @@ add the direct dependency to your project as follows.
         
           com.azure
           azure-communication-rooms
        -  1.1.0
        +  1.2.0
         
         ```
         [//]: # ({x-version-update-end})
        @@ -225,5 +225,5 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m
         [product_docs]: https://learn.microsoft.com/azure/communication-services/
         [api_documentation]: https://aka.ms/java-docs
         [next_steps]: https://learn.microsoft.com/azure/communication-services/concepts/rooms/room-concept
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fappconfiguration%2Fazure-data-appconfiguration%2FREADME.png)
        +
         
        diff --git a/sdk/communication/azure-communication-rooms/assets.json b/sdk/communication/azure-communication-rooms/assets.json
        index 5145793110ef..03c2c419c9d5 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_5116842cd0"
        +  "Tag": "java/communication/azure-communication-rooms_0569c759b4"
         }
        diff --git a/sdk/communication/azure-communication-rooms/pom.xml b/sdk/communication/azure-communication-rooms/pom.xml
        index 7d68452fb641..6185d42e23f1 100644
        --- a/sdk/communication/azure-communication-rooms/pom.xml
        +++ b/sdk/communication/azure-communication-rooms/pom.xml
        @@ -15,7 +15,7 @@
           com.azure
           azure-communication-rooms
           jar
        -  1.2.0-beta.1 
        +  1.2.0 
           Microsoft Azure library for ACS Room Service
           
             This package contains clients and data structures used to create, update, get, delete the Azure Communication Room Service.
        @@ -61,34 +61,34 @@
             
               com.azure
               azure-core
        -      1.54.1 
        +      1.55.3 
             
             
               com.azure
               azure-core-http-netty
        -      1.15.7 
        +      1.15.11 
             
             
               com.azure
               azure-communication-common
        -      1.3.9 
        +      1.3.10 
             
             
               com.azure
               azure-communication-identity
        -      1.6.2 
        +      1.6.3 
               test
             
             
               com.azure
               azure-core-test
        -      1.27.0-beta.4 
        +      1.27.0-beta.8 
               test
             
             
               com.azure
               azure-identity
        -      1.15.0 
        +      1.15.4 
               test
             
           
        diff --git a/sdk/communication/azure-communication-rooms/src/main/java/com/azure/communication/rooms/RoomsServiceVersion.java b/sdk/communication/azure-communication-rooms/src/main/java/com/azure/communication/rooms/RoomsServiceVersion.java
        index 1f6b40303c45..4f02e492e2bc 100644
        --- a/sdk/communication/azure-communication-rooms/src/main/java/com/azure/communication/rooms/RoomsServiceVersion.java
        +++ b/sdk/communication/azure-communication-rooms/src/main/java/com/azure/communication/rooms/RoomsServiceVersion.java
        @@ -17,7 +17,12 @@ public enum RoomsServiceVersion implements ServiceVersion {
             /**
              * Service version {@code 2024-04-15}
              */
        -    V2024_04_15("2024-04-15");
        +    V2024_04_15("2024-04-15"),
        +
        +    /**
        +     * Service version {@code 2025-03-13}
        +     */
        +    V2025_03_13("2025-03-13");
         
             private final String version;
         
        @@ -39,6 +44,6 @@ public String getVersion() {
              * @return the latest {@link RoomsServiceVersion}
              */
             public static RoomsServiceVersion getLatest() {
        -        return V2024_04_15;
        +        return V2025_03_13;
             }
         }
        diff --git a/sdk/communication/azure-communication-rooms/src/main/java/com/azure/communication/rooms/implementation/AzureCommunicationRoomServiceImplBuilder.java b/sdk/communication/azure-communication-rooms/src/main/java/com/azure/communication/rooms/implementation/AzureCommunicationRoomServiceImplBuilder.java
        index d0c28f479a16..826092c6cc81 100644
        --- a/sdk/communication/azure-communication-rooms/src/main/java/com/azure/communication/rooms/implementation/AzureCommunicationRoomServiceImplBuilder.java
        +++ b/sdk/communication/azure-communication-rooms/src/main/java/com/azure/communication/rooms/implementation/AzureCommunicationRoomServiceImplBuilder.java
        @@ -270,7 +270,7 @@ public AzureCommunicationRoomServiceImplBuilder retryPolicy(RetryPolicy retryPol
             @Generated
             public AzureCommunicationRoomServiceImpl buildClient() {
                 HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline();
        -        String localApiVersion = (apiVersion != null) ? apiVersion : "2024-04-15";
        +        String localApiVersion = (apiVersion != null) ? apiVersion : "2025-03-13";
                 SerializerAdapter localSerializerAdapter
                     = (serializerAdapter != null) ? serializerAdapter : JacksonAdapter.createDefaultSerializerAdapter();
                 AzureCommunicationRoomServiceImpl client = new AzureCommunicationRoomServiceImpl(localPipeline,
        diff --git a/sdk/communication/azure-communication-rooms/src/main/java/com/azure/communication/rooms/implementation/converters/ParticipantRoleConverter.java b/sdk/communication/azure-communication-rooms/src/main/java/com/azure/communication/rooms/implementation/converters/ParticipantRoleConverter.java
        index 2daaa480510f..44c0441aab6d 100644
        --- a/sdk/communication/azure-communication-rooms/src/main/java/com/azure/communication/rooms/implementation/converters/ParticipantRoleConverter.java
        +++ b/sdk/communication/azure-communication-rooms/src/main/java/com/azure/communication/rooms/implementation/converters/ParticipantRoleConverter.java
        @@ -34,6 +34,10 @@ public final class ParticipantRoleConverter {
                         role = ParticipantRole.PRESENTER;
                         break;
         
        +            case "Collaborator":
        +                role = ParticipantRole.COLLABORATOR;
        +                break;
        +
                     default:
                         role = ParticipantRole.ATTENDEE;
                         break;
        @@ -66,6 +70,10 @@ public final class ParticipantRoleConverter {
                         role = com.azure.communication.rooms.implementation.models.ParticipantRole.PRESENTER;
                         break;
         
        +            case "Collaborator":
        +                role = com.azure.communication.rooms.implementation.models.ParticipantRole.COLLABORATOR;
        +                break;
        +
                     default:
                         role = com.azure.communication.rooms.implementation.models.ParticipantRole.ATTENDEE;
                         break;
        diff --git a/sdk/communication/azure-communication-rooms/src/main/java/com/azure/communication/rooms/implementation/models/ParticipantRole.java b/sdk/communication/azure-communication-rooms/src/main/java/com/azure/communication/rooms/implementation/models/ParticipantRole.java
        index b983a0a3f687..623560d453da 100644
        --- a/sdk/communication/azure-communication-rooms/src/main/java/com/azure/communication/rooms/implementation/models/ParticipantRole.java
        +++ b/sdk/communication/azure-communication-rooms/src/main/java/com/azure/communication/rooms/implementation/models/ParticipantRole.java
        @@ -26,6 +26,11 @@ public final class ParticipantRole extends ExpandableStringEnum
              */
             public static final ParticipantRole CONSUMER = fromString("Consumer");
         
        +    /**
        +     * Static value Collaborator for ParticipantRole.
        +     */
        +    public static final ParticipantRole COLLABORATOR = fromString("Collaborator");
        +
             /**
              * Creates a new instance of ParticipantRole value.
              * 
        diff --git a/sdk/communication/azure-communication-rooms/src/main/java/com/azure/communication/rooms/implementation/models/RoomsCollection.java b/sdk/communication/azure-communication-rooms/src/main/java/com/azure/communication/rooms/implementation/models/RoomsCollection.java
        index cd6027c3aa8e..c0f62180e7d3 100644
        --- a/sdk/communication/azure-communication-rooms/src/main/java/com/azure/communication/rooms/implementation/models/RoomsCollection.java
        +++ b/sdk/communication/azure-communication-rooms/src/main/java/com/azure/communication/rooms/implementation/models/RoomsCollection.java
        @@ -18,7 +18,7 @@
         @Fluent
         public final class RoomsCollection implements JsonSerializable {
             /*
        -     * A collection of rooms
        +     * A collection of rooms.
              */
             private List value;
         
        diff --git a/sdk/communication/azure-communication-rooms/src/main/java/com/azure/communication/rooms/implementation/models/UpdateRoomRequest.java b/sdk/communication/azure-communication-rooms/src/main/java/com/azure/communication/rooms/implementation/models/UpdateRoomRequest.java
        index e61e59a2af75..e262d887946c 100644
        --- a/sdk/communication/azure-communication-rooms/src/main/java/com/azure/communication/rooms/implementation/models/UpdateRoomRequest.java
        +++ b/sdk/communication/azure-communication-rooms/src/main/java/com/azure/communication/rooms/implementation/models/UpdateRoomRequest.java
        @@ -31,8 +31,8 @@ public final class UpdateRoomRequest implements JsonSerializable
             /** Static value Consumer for ParticipantRole. */
             public static final ParticipantRole CONSUMER = fromString("Consumer");
         
        +    /** Static value Collaborator for ParticipantRole. */
        +    public static final ParticipantRole COLLABORATOR = fromString("Collaborator");
        +
             /**
              * Creates a new instance of {@link ParticipantRole} with no string value.
              *
        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 1ab5ada10ff4..52fedd6a7245 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
        @@ -865,7 +865,7 @@ private HttpClient buildAsyncAssertingClient(HttpClient httpClient) {
             private RoomsAsyncClient setupAsyncClient(HttpClient httpClient, String testName) {
                 RoomsClientBuilder builder = getRoomsClientWithConnectionString(
                     buildAsyncAssertingClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient),
        -            RoomsServiceVersion.V2024_04_15);
        +            RoomsServiceVersion.V2025_03_13);
                 communicationClient = getCommunicationIdentityClientBuilder(httpClient).buildClient();
                 return addLoggingPolicy(builder, testName).buildAsyncClient();
             }
        diff --git a/sdk/communication/azure-communication-rooms/src/test/java/com/azure/communication/rooms/RoomsClientTest.java b/sdk/communication/azure-communication-rooms/src/test/java/com/azure/communication/rooms/RoomsClientTest.java
        index e20baf16c2ca..5cd480640770 100644
        --- a/sdk/communication/azure-communication-rooms/src/test/java/com/azure/communication/rooms/RoomsClientTest.java
        +++ b/sdk/communication/azure-communication-rooms/src/test/java/com/azure/communication/rooms/RoomsClientTest.java
        @@ -123,6 +123,38 @@ public void createRoomSyncWithFullOperationWithResponse(HttpClient httpClient) {
                 assertEquals(deleteResponse.getStatusCode(), 204);
             }
         
        +    @ParameterizedTest
        +    @MethodSource("com.azure.core.test.TestBase#getHttpClients")
        +    public void createRoomSyncWithParticipants(HttpClient httpClient) {
        +        roomsClient = setupSyncClient(httpClient, "createRoomSyncWithParticipants");
        +        assertNotNull(roomsClient);
        +
        +        // Create 4 participants
        +        RoomParticipant firstParticipant
        +            = new RoomParticipant(communicationClient.createUser()).setRole(ParticipantRole.PRESENTER);
        +        RoomParticipant secondParticipant
        +            = new RoomParticipant(communicationClient.createUser()).setRole(ParticipantRole.COLLABORATOR);
        +        RoomParticipant thirdParticipant
        +            = new RoomParticipant(communicationClient.createUser()).setRole(ParticipantRole.CONSUMER);
        +        RoomParticipant fourthParticipant
        +            = new RoomParticipant(communicationClient.createUser()).setRole(ParticipantRole.ATTENDEE);
        +
        +        List participants
        +            = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant, fourthParticipant);
        +
        +        CreateRoomOptions createRoomOptions = new CreateRoomOptions().setParticipants(participants);
        +
        +        Response createdRoomResponse = roomsClient.createRoomWithResponse(createRoomOptions, null);
        +        String roomId = createdRoomResponse.getValue().getRoomId();
        +
        +        // Check participant count, expected 3
        +        PagedIterable listParticipantsResponse = roomsClient.listParticipants(roomId);
        +        assertEquals(4, listParticipantsResponse.stream().count());
        +
        +        Response deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE);
        +        assertEquals(deleteResponse.getStatusCode(), 204);
        +    }
        +
             @ParameterizedTest
             @MethodSource("com.azure.core.test.TestBase#getHttpClients")
             public void listRoomTestFirstRoomIsNotNullThenDeleteRoomWithOutResponse(HttpClient httpClient) {
        @@ -170,7 +202,8 @@ public void addUpdateAndRemoveParticipantsOperationsSyncWithFullFlow(HttpClient
         
                 // Create 3 participants
                 RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser());
        -        RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser());
        +        RoomParticipant secondParticipant
        +            = new RoomParticipant(communicationClient.createUser()).setRole(ParticipantRole.COLLABORATOR);
                 RoomParticipant thirdParticipant
                     = new RoomParticipant(communicationClient.createUser()).setRole(ParticipantRole.CONSUMER);
         
        @@ -192,7 +225,7 @@ public void addUpdateAndRemoveParticipantsOperationsSyncWithFullFlow(HttpClient
         
                 List participantsToUpdate = Arrays.asList(firstParticipantUpdated, secondParticipantUpdated);
         
        -        // Update 2 participants roles, ATTENDEE -> CONSUMER
        +        // Update 2 participants roles, ATTENDEE or COLLABORATOR -> CONSUMER
                 AddOrUpdateParticipantsResult updateParticipantResponse
                     = roomsClient.addOrUpdateParticipants(roomId, participantsToUpdate);
                 assertEquals(true, updateParticipantResponse instanceof AddOrUpdateParticipantsResult);
        @@ -297,23 +330,42 @@ public void updateParticipantsSyncWithFullOperation(HttpClient httpClient) {
         
                 String roomId = createCommunicationRoom.getRoomId();
         
        -        RoomParticipant firstParticipantToUpdate
        +        RoomParticipant firstParticipantToUpdateToPresenter
                     = new RoomParticipant(firstParticipant.getCommunicationIdentifier()).setRole(ParticipantRole.PRESENTER);
        -        RoomParticipant secondParticipantToUpdate
        +        RoomParticipant secondParticipantToUpdateToPresenter
                     = new RoomParticipant(secondParticipant.getCommunicationIdentifier()).setRole(ParticipantRole.PRESENTER);
         
        -        List participantsToUpdate = Arrays.asList(firstParticipantToUpdate, secondParticipantToUpdate);
        +        List participantsToUpdateToPresenter
        +            = Arrays.asList(firstParticipantToUpdateToPresenter, secondParticipantToUpdateToPresenter);
         
        -        // Update 2 participants.
        -        AddOrUpdateParticipantsResult addPartcipantResponse
        -            = roomsClient.addOrUpdateParticipants(roomId, participantsToUpdate);
        +        // Update 2 participants, both to presenter
        +        AddOrUpdateParticipantsResult addParticipantsAsPresenterResponse
        +            = roomsClient.addOrUpdateParticipants(roomId, participantsToUpdateToPresenter);
         
        -        PagedIterable listResponse = roomsClient.listParticipants(roomId);
        +        PagedIterable listPresentersResponse = roomsClient.listParticipants(roomId);
         
        -        for (RoomParticipant participant : listResponse) {
        +        for (RoomParticipant participant : listPresentersResponse) {
                     assertEquals(ParticipantRole.PRESENTER, participant.getRole());
                 }
         
        +        RoomParticipant firstParticipantToUpdateToCollaborator
        +            = new RoomParticipant(firstParticipant.getCommunicationIdentifier()).setRole(ParticipantRole.COLLABORATOR);
        +        RoomParticipant secondParticipantToUpdateToCollaborator
        +            = new RoomParticipant(secondParticipant.getCommunicationIdentifier()).setRole(ParticipantRole.COLLABORATOR);
        +
        +        List participantsToUpdateToCollaborator
        +            = Arrays.asList(firstParticipantToUpdateToCollaborator, secondParticipantToUpdateToCollaborator);
        +
        +        // Update 2 participants, to collaborator
        +        AddOrUpdateParticipantsResult addParticipantsAsNonPresentersResponse
        +            = roomsClient.addOrUpdateParticipants(roomId, participantsToUpdateToCollaborator);
        +
        +        PagedIterable listNonPresentersResponse = roomsClient.listParticipants(roomId);
        +
        +        for (RoomParticipant participant : listNonPresentersResponse) {
        +            assertEquals(ParticipantRole.COLLABORATOR, participant.getRole());
        +        }
        +
                 Response deleteResponse = roomsClient.deleteRoomWithResponse(roomId, Context.NONE);
                 assertEquals(deleteResponse.getStatusCode(), 204);
             }
        @@ -919,7 +971,7 @@ private HttpClient buildSyncAssertingClient(HttpClient httpClient) {
             private RoomsClient setupSyncClient(HttpClient httpClient, String testName) {
                 RoomsClientBuilder builder = getRoomsClientWithConnectionString(
                     buildSyncAssertingClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient),
        -            RoomsServiceVersion.V2024_04_15);
        +            RoomsServiceVersion.V2025_03_13);
         
                 communicationClient = getCommunicationIdentityClientBuilder(httpClient).buildClient();
         
        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 753ca786b80b..ab3e0defee2a 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
        @@ -24,6 +24,7 @@
         import reactor.core.publisher.Mono;
         
         import java.time.OffsetDateTime;
        +import java.time.ZoneId;
         import java.util.Arrays;
         
         import static org.junit.jupiter.api.Assertions.assertEquals;
        @@ -36,7 +37,7 @@ public class RoomsTestBase extends TestProxyTestBase {
                 .get("COMMUNICATION_CONNECTION_STRING_ROOMS",
                     "endpoint=https://REDACTED.communication.azure.com/;accesskey=P2tP5RwZVFcJa3sfJvHEmGaKbemSAw2e");
         
        -    protected static final OffsetDateTime VALID_FROM = OffsetDateTime.now();
        +    protected static final OffsetDateTime VALID_FROM = OffsetDateTime.now(ZoneId.of("Z")); // UTC
             protected static final OffsetDateTime VALID_UNTIL = VALID_FROM.plusDays(30);
         
             protected RoomsClientBuilder getRoomsClient(HttpClient httpClient) {
        diff --git a/sdk/communication/azure-communication-rooms/swagger/README.md b/sdk/communication/azure-communication-rooms/swagger/README.md
        index d3dcb50ab750..f8b9a4bc050b 100644
        --- a/sdk/communication/azure-communication-rooms/swagger/README.md
        +++ b/sdk/communication/azure-communication-rooms/swagger/README.md
        @@ -21,7 +21,7 @@ To update generated files for rooms service, run the following command
         ### Code generation settings
         ``` yaml
         require:
        -    - https://raw.githubusercontent.com/Azure/azure-rest-api-specs/91813ca7a287fe944262e992413ce4d51d987276/specification/communication/data-plane/Rooms/readme.md
        +    - https://raw.githubusercontent.com/Azure/azure-rest-api-specs/538040a7bbb466baf361e98d6d36faec417cff7a/specification/communication/data-plane/Rooms/readme.md
         use: '@autorest/java@4.1.27'
         java: true
         title: AzureCommunicationRoomService
        diff --git a/sdk/communication/azure-communication-sms/CHANGELOG.md b/sdk/communication/azure-communication-sms/CHANGELOG.md
        index 3d463be97d9e..3d33f8607a49 100644
        --- a/sdk/communication/azure-communication-sms/CHANGELOG.md
        +++ b/sdk/communication/azure-communication-sms/CHANGELOG.md
        @@ -10,6 +10,15 @@
         
         ### Other Changes
         
        +## 1.1.31 (2025-03-03)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-communication-common` from `1.3.8` to version `1.3.9`.
        +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`.
        +
         ## 1.1.30 (2024-12-04)
         
         ### Other Changes
        diff --git a/sdk/communication/azure-communication-sms/README.md b/sdk/communication/azure-communication-sms/README.md
        index 915e63bcc9b8..902d6e5260de 100644
        --- a/sdk/communication/azure-communication-sms/README.md
        +++ b/sdk/communication/azure-communication-sms/README.md
        @@ -53,7 +53,7 @@ add the direct dependency to your project as follows.
         
           com.azure
           azure-communication-sms
        -  1.1.15
        +  1.2.0-beta.1
         
         ```
         
        @@ -192,7 +192,7 @@ try {
         [handle_sms_events]: https://learn.microsoft.com/azure/communication-services/quickstarts/telephony-sms/handle-sms-events
         [next_steps]:https://learn.microsoft.com/azure/communication-services/quickstarts/telephony-sms/send?pivots=programming-language-java
         
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Feng%2Fazure-communications-sms%2FREADME.png)
        +
         
         ## Contributing
         
        diff --git a/sdk/communication/azure-communication-sms/pom.xml b/sdk/communication/azure-communication-sms/pom.xml
        index 0028ee0f3e04..4dbaea2a154a 100644
        --- a/sdk/communication/azure-communication-sms/pom.xml
        +++ b/sdk/communication/azure-communication-sms/pom.xml
        @@ -58,17 +58,17 @@
             
               com.azure
               azure-core
        -      1.54.1 
        +      1.55.3 
             
             
               com.azure
               azure-communication-common
        -      1.3.9 
        +      1.3.10 
             
             
               com.azure
               azure-core-test
        -      1.27.0-beta.4 
        +      1.27.0-beta.8 
               test
             
             
        @@ -80,7 +80,7 @@
             
               com.azure
               azure-identity
        -      1.15.0 
        +      1.15.4 
               test
             
           
        diff --git a/sdk/communication/azure-resourcemanager-communication/README.md b/sdk/communication/azure-resourcemanager-communication/README.md
        index a5397cfbbe10..858ec6b5709b 100644
        --- a/sdk/communication/azure-resourcemanager-communication/README.md
        +++ b/sdk/communication/azure-resourcemanager-communication/README.md
        @@ -32,7 +32,7 @@ Various documentation is available to help you get started
         
             com.azure.resourcemanager
             azure-resourcemanager-communication
        -    2.2.0
        +    2.3.0-beta.1
         
         ```
         [//]: # ({x-version-update-end})
        @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m
         [coc]: https://opensource.microsoft.com/codeofconduct/
         [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/
         
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcommunication%2Fazure-resourcemanager-communication%2FREADME.png)
        +
        diff --git a/sdk/communication/azure-resourcemanager-communication/pom.xml b/sdk/communication/azure-resourcemanager-communication/pom.xml
        index fa85c1470a57..a6da4af5a732 100644
        --- a/sdk/communication/azure-resourcemanager-communication/pom.xml
        +++ b/sdk/communication/azure-resourcemanager-communication/pom.xml
        @@ -51,23 +51,23 @@
             
               com.azure
               azure-core
        -      1.54.1 
        +      1.55.3 
             
             
               com.azure
               azure-core-management
        -      1.15.6 
        +      1.17.0 
             
             
               com.azure
               azure-core-test
        -      1.27.0-beta.4 
        +      1.27.0-beta.8 
               test
             
             
               com.azure
               azure-identity
        -      1.15.0 
        +      1.15.4 
               test
             
             
        diff --git a/sdk/computefleet/azure-resourcemanager-computefleet/README.md b/sdk/computefleet/azure-resourcemanager-computefleet/README.md
        index f707d4cda708..0dee5ed27391 100644
        --- a/sdk/computefleet/azure-resourcemanager-computefleet/README.md
        +++ b/sdk/computefleet/azure-resourcemanager-computefleet/README.md
        @@ -32,7 +32,7 @@ Various documentation is available to help you get started
         
             com.azure.resourcemanager
             azure-resourcemanager-computefleet
        -    1.0.0
        +    1.1.0-beta.1
         
         ```
         [//]: # ({x-version-update-end})
        @@ -227,4 +227,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m
         [coc]: https://opensource.microsoft.com/codeofconduct/
         [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/
         
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcomputefleet%2Fazure-resourcemanager-computefleet%2FREADME.png)
        +
        diff --git a/sdk/computefleet/azure-resourcemanager-computefleet/pom.xml b/sdk/computefleet/azure-resourcemanager-computefleet/pom.xml
        index 1be04c3de201..0706124f5d4a 100644
        --- a/sdk/computefleet/azure-resourcemanager-computefleet/pom.xml
        +++ b/sdk/computefleet/azure-resourcemanager-computefleet/pom.xml
        @@ -51,40 +51,40 @@
             
               com.azure
               azure-core
        -      1.54.1 
        +      1.55.3 
             
             
               com.azure
               azure-core-management
        -      1.15.6 
        +      1.17.0 
             
             
               com.azure
               azure-core-test
        -      1.27.0-beta.4 
        +      1.27.0-beta.8 
               test
             
             
               com.azure
               azure-identity
        -      1.15.0 
        +      1.15.4 
               test
             
             
               com.azure
               azure-json
        -      1.3.0 
        +      1.5.0 
             
             
               com.azure.resourcemanager
               azure-resourcemanager-resources
        -      2.46.0 
        +      2.48.0 
               test
             
             
               com.azure.resourcemanager
               azure-resourcemanager-network
        -      2.46.0 
        +      2.48.0 
               test
             
           
        diff --git a/sdk/computefleet/azure-resourcemanager-computefleet/src/main/java/com/azure/resourcemanager/computefleet/ComputeFleetManager.java b/sdk/computefleet/azure-resourcemanager-computefleet/src/main/java/com/azure/resourcemanager/computefleet/ComputeFleetManager.java
        index da94fd7f3e5e..286faf873ad0 100644
        --- a/sdk/computefleet/azure-resourcemanager-computefleet/src/main/java/com/azure/resourcemanager/computefleet/ComputeFleetManager.java
        +++ b/sdk/computefleet/azure-resourcemanager-computefleet/src/main/java/com/azure/resourcemanager/computefleet/ComputeFleetManager.java
        @@ -22,6 +22,7 @@
         import com.azure.core.http.policy.UserAgentPolicy;
         import com.azure.core.management.profile.AzureProfile;
         import com.azure.core.util.Configuration;
        +import com.azure.core.util.CoreUtils;
         import com.azure.core.util.logging.ClientLogger;
         import com.azure.resourcemanager.computefleet.fluent.ComputeFleetManagementClient;
         import com.azure.resourcemanager.computefleet.implementation.ComputeFleetManagementClientBuilder;
        @@ -33,6 +34,7 @@
         import java.time.temporal.ChronoUnit;
         import java.util.ArrayList;
         import java.util.List;
        +import java.util.Map;
         import java.util.Objects;
         import java.util.stream.Collectors;
         
        @@ -96,6 +98,9 @@ public static Configurable configure() {
              */
             public static final class Configurable {
                 private static final ClientLogger LOGGER = new ClientLogger(Configurable.class);
        +        private static final String SDK_VERSION = "version";
        +        private static final Map PROPERTIES
        +            = CoreUtils.getProperties("azure-resourcemanager-computefleet.properties");
         
                 private HttpClient httpClient;
                 private HttpLogOptions httpLogOptions;
        @@ -203,12 +208,14 @@ public ComputeFleetManager authenticate(TokenCredential credential, AzureProfile
                     Objects.requireNonNull(credential, "'credential' cannot be null.");
                     Objects.requireNonNull(profile, "'profile' cannot be null.");
         
        +            String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion");
        +
                     StringBuilder userAgentBuilder = new StringBuilder();
                     userAgentBuilder.append("azsdk-java")
                         .append("-")
                         .append("com.azure.resourcemanager.computefleet")
                         .append("/")
        -                .append("1.0.0-beta.1");
        +                .append(clientVersion);
                     if (!Configuration.getGlobalConfiguration().get("AZURE_TELEMETRY_DISABLED", false)) {
                         userAgentBuilder.append(" (")
                             .append(Configuration.getGlobalConfiguration().get("java.version"))
        diff --git a/sdk/computefleet/azure-resourcemanager-computefleet/src/main/java/com/azure/resourcemanager/computefleet/models/UserAssignedIdentity.java b/sdk/computefleet/azure-resourcemanager-computefleet/src/main/java/com/azure/resourcemanager/computefleet/models/UserAssignedIdentity.java
        index 8c85e55b6aaa..3ba8466204c2 100644
        --- a/sdk/computefleet/azure-resourcemanager-computefleet/src/main/java/com/azure/resourcemanager/computefleet/models/UserAssignedIdentity.java
        +++ b/sdk/computefleet/azure-resourcemanager-computefleet/src/main/java/com/azure/resourcemanager/computefleet/models/UserAssignedIdentity.java
        @@ -17,14 +17,14 @@
         @Immutable
         public final class UserAssignedIdentity implements JsonSerializable {
             /*
        -     * The principal ID of the assigned identity.
        +     * The client ID of the assigned identity.
              */
        -    private String principalId;
        +    private String clientId;
         
             /*
        -     * The client ID of the assigned identity.
        +     * The principal ID of the assigned identity.
              */
        -    private String clientId;
        +    private String principalId;
         
             /**
              * Creates an instance of UserAssignedIdentity class.
        @@ -33,21 +33,21 @@ public UserAssignedIdentity() {
             }
         
             /**
        -     * Get the principalId property: The principal ID of the assigned identity.
        +     * Get the clientId property: The client ID of the assigned identity.
              * 
        -     * @return the principalId value.
        +     * @return the clientId value.
              */
        -    public String principalId() {
        -        return this.principalId;
        +    public String clientId() {
        +        return this.clientId;
             }
         
             /**
        -     * Get the clientId property: The client ID of the assigned identity.
        +     * Get the principalId property: The principal ID of the assigned identity.
              * 
        -     * @return the clientId value.
        +     * @return the principalId value.
              */
        -    public String clientId() {
        -        return this.clientId;
        +    public String principalId() {
        +        return this.principalId;
             }
         
             /**
        @@ -82,10 +82,10 @@ public static UserAssignedIdentity fromJson(JsonReader jsonReader) throws IOExce
                         String fieldName = reader.getFieldName();
                         reader.nextToken();
         
        -                if ("principalId".equals(fieldName)) {
        -                    deserializedUserAssignedIdentity.principalId = reader.getString();
        -                } else if ("clientId".equals(fieldName)) {
        +                if ("clientId".equals(fieldName)) {
                             deserializedUserAssignedIdentity.clientId = reader.getString();
        +                } else if ("principalId".equals(fieldName)) {
        +                    deserializedUserAssignedIdentity.principalId = reader.getString();
                         } else {
                             reader.skipChildren();
                         }
        diff --git a/sdk/computefleet/azure-resourcemanager-computefleet/src/main/resources/azure-resourcemanager-computefleet.properties b/sdk/computefleet/azure-resourcemanager-computefleet/src/main/resources/azure-resourcemanager-computefleet.properties
        new file mode 100644
        index 000000000000..defbd48204e4
        --- /dev/null
        +++ b/sdk/computefleet/azure-resourcemanager-computefleet/src/main/resources/azure-resourcemanager-computefleet.properties
        @@ -0,0 +1 @@
        +version=${project.version}
        diff --git a/sdk/computeschedule/azure-resourcemanager-computeschedule/CHANGELOG.md b/sdk/computeschedule/azure-resourcemanager-computeschedule/CHANGELOG.md
        index 1a9502d5ccb9..0507d886e864 100644
        --- a/sdk/computeschedule/azure-resourcemanager-computeschedule/CHANGELOG.md
        +++ b/sdk/computeschedule/azure-resourcemanager-computeschedule/CHANGELOG.md
        @@ -1,6 +1,6 @@
         # Release History
         
        -## 1.0.0-beta.2 (Unreleased)
        +## 1.1.0-beta.1 (Unreleased)
         
         ### Features Added
         
        @@ -10,6 +10,38 @@
         
         ### Other Changes
         
        +## 1.0.0 (2025-01-22)
        +
        +- Azure Resource Manager Compute Schedule client library for Java. This package contains Microsoft Azure SDK for Compute Schedule Management SDK. Microsoft.ComputeSchedule Resource Provider management API. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt).
        +
        +### Breaking Changes
        +
        +#### `models.OperationErrorDetails` was modified
        +
        +* `java.time.OffsetDateTime errorDetails()` -> `java.lang.String errorDetails()`
        +
        +#### `ComputeScheduleManager` was modified
        +
        +* `fluent.ComputeScheduleClient serviceClient()` -> `fluent.ComputeScheduleMgmtClient serviceClient()`
        +
        +### Features Added
        +
        +#### `models.OperationErrorDetails` was modified
        +
        +* `azureOperationName()` was added
        +* `timestamp()` was added
        +
        +#### `models.ResourceOperationDetails` was modified
        +
        +* `timezone()` was added
        +
        +#### `models.Schedule` was modified
        +
        +* `timezone()` was added
        +* `withTimezone(java.lang.String)` was added
        +* `withDeadline(java.time.OffsetDateTime)` was added
        +* `deadline()` was added
        +
         ## 1.0.0-beta.1 (2024-09-25)
         
         - Azure Resource Manager Compute Schedule client library for Java. This package contains Microsoft Azure SDK for Compute Schedule Management SDK. Microsoft.ComputeSchedule Resource Provider management API. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt).
        diff --git a/sdk/computeschedule/azure-resourcemanager-computeschedule/README.md b/sdk/computeschedule/azure-resourcemanager-computeschedule/README.md
        index 040bb09afcb5..5d21d3f2de92 100644
        --- a/sdk/computeschedule/azure-resourcemanager-computeschedule/README.md
        +++ b/sdk/computeschedule/azure-resourcemanager-computeschedule/README.md
        @@ -32,7 +32,7 @@ Various documentation is available to help you get started
         
             com.azure.resourcemanager
             azure-resourcemanager-computeschedule
        -    1.0.0-beta.1
        +    1.1.0-beta.1
         
         ```
         [//]: # ({x-version-update-end})
        @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m
         [coc]: https://opensource.microsoft.com/codeofconduct/
         [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/
         
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcomputeschedule%2Fazure-resourcemanager-computeschedule%2FREADME.png)
        +
        diff --git a/sdk/computeschedule/azure-resourcemanager-computeschedule/SAMPLE.md b/sdk/computeschedule/azure-resourcemanager-computeschedule/SAMPLE.md
        index f8d13e6eeeb3..c2a9848216b9 100644
        --- a/sdk/computeschedule/azure-resourcemanager-computeschedule/SAMPLE.md
        +++ b/sdk/computeschedule/azure-resourcemanager-computeschedule/SAMPLE.md
        @@ -24,28 +24,14 @@
          */
         public final class OperationsListSamples {
             /*
        -     * x-ms-original-file: 2024-08-15-preview/Operations_List_MaximumSet_Gen.json
        +     * x-ms-original-file: 2024-10-01/Operations_List.json
              */
             /**
        -     * Sample code: Operations_ListMax - generated by [MaximumSet] rule - generated by [MaximumSet] rule.
        +     * Sample code: Operations_List.
              * 
              * @param manager Entry point to ComputeScheduleManager.
              */
        -    public static void operationsListMaxGeneratedByMaximumSetRuleGeneratedByMaximumSetRule(
        -        com.azure.resourcemanager.computeschedule.ComputeScheduleManager manager) {
        -        manager.operations().list(com.azure.core.util.Context.NONE);
        -    }
        -
        -    /*
        -     * x-ms-original-file: 2024-08-15-preview/Operations_List_MinimumSet_Gen.json
        -     */
        -    /**
        -     * Sample code: Operations_ListMax - generated by [MaximumSet] rule - generated by [MinimumSet] rule.
        -     * 
        -     * @param manager Entry point to ComputeScheduleManager.
        -     */
        -    public static void operationsListMaxGeneratedByMaximumSetRuleGeneratedByMinimumSetRule(
        -        com.azure.resourcemanager.computeschedule.ComputeScheduleManager manager) {
        +    public static void operationsList(com.azure.resourcemanager.computeschedule.ComputeScheduleManager manager) {
                 manager.operations().list(com.azure.core.util.Context.NONE);
             }
         }
        @@ -62,40 +48,19 @@ import java.util.Arrays;
          */
         public final class ScheduledActionsVirtualMachinesCancelOperationsSamples {
             /*
        -     * x-ms-original-file: 2024-08-15-preview/ScheduledActions_VirtualMachinesCancelOperations_MinimumSet_Gen.json
        +     * x-ms-original-file: 2024-10-01/ScheduledActions_VirtualMachinesCancelOperations.json
              */
             /**
        -     * Sample code: ScheduledActions_VirtualMachinesCancelOperations - generated by [MaximumSet] rule - generated by
        -     * [MinimumSet] rule.
        +     * Sample code: ScheduledActions_VirtualMachinesCancelOperations.
              * 
              * @param manager Entry point to ComputeScheduleManager.
              */
        -    public static void
        -        scheduledActionsVirtualMachinesCancelOperationsGeneratedByMaximumSetRuleGeneratedByMinimumSetRule(
        -            com.azure.resourcemanager.computeschedule.ComputeScheduleManager manager) {
        -        manager.scheduledActions()
        -            .virtualMachinesCancelOperationsWithResponse("lwapkjsbltcqp",
        -                new CancelOperationsRequest().withOperationIds(Arrays.asList("23480d2f-1dca-4610-afb4-dd25eec1f34r"))
        -                    .withCorrelationid("01080d2f-1dca-4610-afb4-dd25eec1f3c1"),
        -                com.azure.core.util.Context.NONE);
        -    }
        -
        -    /*
        -     * x-ms-original-file: 2024-08-15-preview/ScheduledActions_VirtualMachinesCancelOperations_MaximumSet_Gen.json
        -     */
        -    /**
        -     * Sample code: ScheduledActions_VirtualMachinesCancelOperations - generated by [MaximumSet] rule - generated by
        -     * [MaximumSet] rule.
        -     * 
        -     * @param manager Entry point to ComputeScheduleManager.
        -     */
        -    public static void
        -        scheduledActionsVirtualMachinesCancelOperationsGeneratedByMaximumSetRuleGeneratedByMaximumSetRule(
        -            com.azure.resourcemanager.computeschedule.ComputeScheduleManager manager) {
        +    public static void scheduledActionsVirtualMachinesCancelOperations(
        +        com.azure.resourcemanager.computeschedule.ComputeScheduleManager manager) {
                 manager.scheduledActions()
        -            .virtualMachinesCancelOperationsWithResponse("tdxypnse",
        +            .virtualMachinesCancelOperationsWithResponse("eastus2euap",
                         new CancelOperationsRequest().withOperationIds(Arrays.asList("23480d2f-1dca-4610-afb4-dd25eec1f34r"))
        -                    .withCorrelationid("01080d2f-1dca-4610-afb4-dd25eec1f3c1"),
        +                    .withCorrelationid("23480d2f-1dca-4610-afb4-gg25eec1f34r"),
                         com.azure.core.util.Context.NONE);
             }
         }
        @@ -106,7 +71,6 @@ public final class ScheduledActionsVirtualMachinesCancelOperationsSamples {
         ```java
         import com.azure.resourcemanager.computeschedule.models.ExecuteDeallocateRequest;
         import com.azure.resourcemanager.computeschedule.models.ExecutionParameters;
        -import com.azure.resourcemanager.computeschedule.models.OptimizationPreference;
         import com.azure.resourcemanager.computeschedule.models.Resources;
         import com.azure.resourcemanager.computeschedule.models.RetryPolicy;
         import java.util.Arrays;
        @@ -116,45 +80,22 @@ import java.util.Arrays;
          */
         public final class ScheduledActionsVirtualMachinesExecuteDeallocateSamples {
             /*
        -     * x-ms-original-file: 2024-08-15-preview/ScheduledActions_VirtualMachinesExecuteDeallocate_MaximumSet_Gen.json
        -     */
        -    /**
        -     * Sample code: ScheduledActions_VirtualMachinesExecuteDeallocate - generated by [MaximumSet] rule - generated by
        -     * [MaximumSet] rule.
        -     * 
        -     * @param manager Entry point to ComputeScheduleManager.
        -     */
        -    public static void
        -        scheduledActionsVirtualMachinesExecuteDeallocateGeneratedByMaximumSetRuleGeneratedByMaximumSetRule(
        -            com.azure.resourcemanager.computeschedule.ComputeScheduleManager manager) {
        -        manager.scheduledActions()
        -            .virtualMachinesExecuteDeallocateWithResponse("mklyzgztbivwzo", new ExecuteDeallocateRequest()
        -                .withExecutionParameters(
        -                    new ExecutionParameters().withOptimizationPreference(OptimizationPreference.COST)
        -                        .withRetryPolicy(new RetryPolicy().withRetryCount(30).withRetryWindowInMinutes(27)))
        -                .withResources(new Resources().withIds(Arrays.asList(
        -                    "/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource2")))
        -                .withCorrelationid("01080d2f-1dca-4610-afb4-dd25eddf1f3c1"), com.azure.core.util.Context.NONE);
        -    }
        -
        -    /*
        -     * x-ms-original-file: 2024-08-15-preview/ScheduledActions_VirtualMachinesExecuteDeallocate_MinimumSet_Gen.json
        +     * x-ms-original-file: 2024-10-01/ScheduledActions_VirtualMachinesExecuteDeallocate.json
              */
             /**
        -     * Sample code: ScheduledActions_VirtualMachinesExecuteDeallocate - generated by [MaximumSet] rule - generated by
        -     * [MinimumSet] rule.
        +     * Sample code: ScheduledActions_VirtualMachinesExecuteDeallocate.
              * 
              * @param manager Entry point to ComputeScheduleManager.
              */
        -    public static void
        -        scheduledActionsVirtualMachinesExecuteDeallocateGeneratedByMaximumSetRuleGeneratedByMinimumSetRule(
        -            com.azure.resourcemanager.computeschedule.ComputeScheduleManager manager) {
        +    public static void scheduledActionsVirtualMachinesExecuteDeallocate(
        +        com.azure.resourcemanager.computeschedule.ComputeScheduleManager manager) {
                 manager.scheduledActions()
        -            .virtualMachinesExecuteDeallocateWithResponse("irbtacrhjgfpyvhvjo", new ExecuteDeallocateRequest()
        -                .withExecutionParameters(new ExecutionParameters())
        +            .virtualMachinesExecuteDeallocateWithResponse("eastus2euap", new ExecuteDeallocateRequest()
        +                .withExecutionParameters(new ExecutionParameters()
        +                    .withRetryPolicy(new RetryPolicy().withRetryCount(4).withRetryWindowInMinutes(27)))
                         .withResources(new Resources().withIds(Arrays.asList(
        -                    "/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource2")))
        -                .withCorrelationid("01080d2f-1dca-4610-afb4-dd25eddf1f3c1"), com.azure.core.util.Context.NONE);
        +                    "/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3")))
        +                .withCorrelationid("23480d2f-1dca-4610-afb4-dd25eec1f34r"), com.azure.core.util.Context.NONE);
             }
         }
         ```
        @@ -164,7 +105,6 @@ public final class ScheduledActionsVirtualMachinesExecuteDeallocateSamples {
         ```java
         import com.azure.resourcemanager.computeschedule.models.ExecuteHibernateRequest;
         import com.azure.resourcemanager.computeschedule.models.ExecutionParameters;
        -import com.azure.resourcemanager.computeschedule.models.OptimizationPreference;
         import com.azure.resourcemanager.computeschedule.models.Resources;
         import com.azure.resourcemanager.computeschedule.models.RetryPolicy;
         import java.util.Arrays;
        @@ -174,45 +114,22 @@ import java.util.Arrays;
          */
         public final class ScheduledActionsVirtualMachinesExecuteHibernateSamples {
             /*
        -     * x-ms-original-file: 2024-08-15-preview/ScheduledActions_VirtualMachinesExecuteHibernate_MinimumSet_Gen.json
        +     * x-ms-original-file: 2024-10-01/ScheduledActions_VirtualMachinesExecuteHibernate.json
              */
             /**
        -     * Sample code: ScheduledActions_VirtualMachinesExecuteHibernate - generated by [MaximumSet] rule - generated by
        -     * [MinimumSet] rule.
        +     * Sample code: ScheduledActions_VirtualMachinesExecuteHibernate.
              * 
              * @param manager Entry point to ComputeScheduleManager.
              */
        -    public static void
        -        scheduledActionsVirtualMachinesExecuteHibernateGeneratedByMaximumSetRuleGeneratedByMinimumSetRule(
        -            com.azure.resourcemanager.computeschedule.ComputeScheduleManager manager) {
        -        manager.scheduledActions()
        -            .virtualMachinesExecuteHibernateWithResponse("kga", new ExecuteHibernateRequest()
        -                .withExecutionParameters(new ExecutionParameters())
        -                .withResources(new Resources().withIds(Arrays.asList(
        -                    "/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3")))
        -                .withCorrelationid("01080d2f-1dca-4610-afb4-dd25eec1f3c1"), com.azure.core.util.Context.NONE);
        -    }
        -
        -    /*
        -     * x-ms-original-file: 2024-08-15-preview/ScheduledActions_VirtualMachinesExecuteHibernate_MaximumSet_Gen.json
        -     */
        -    /**
        -     * Sample code: ScheduledActions_VirtualMachinesExecuteHibernate - generated by [MaximumSet] rule - generated by
        -     * [MaximumSet] rule.
        -     * 
        -     * @param manager Entry point to ComputeScheduleManager.
        -     */
        -    public static void
        -        scheduledActionsVirtualMachinesExecuteHibernateGeneratedByMaximumSetRuleGeneratedByMaximumSetRule(
        -            com.azure.resourcemanager.computeschedule.ComputeScheduleManager manager) {
        +    public static void scheduledActionsVirtualMachinesExecuteHibernate(
        +        com.azure.resourcemanager.computeschedule.ComputeScheduleManager manager) {
                 manager.scheduledActions()
        -            .virtualMachinesExecuteHibernateWithResponse("sejdmamuhhvfpljomwumsplc", new ExecuteHibernateRequest()
        -                .withExecutionParameters(
        -                    new ExecutionParameters().withOptimizationPreference(OptimizationPreference.COST)
        -                        .withRetryPolicy(new RetryPolicy().withRetryCount(30).withRetryWindowInMinutes(27)))
        +            .virtualMachinesExecuteHibernateWithResponse("eastus2euap", new ExecuteHibernateRequest()
        +                .withExecutionParameters(new ExecutionParameters()
        +                    .withRetryPolicy(new RetryPolicy().withRetryCount(5).withRetryWindowInMinutes(27)))
                         .withResources(new Resources().withIds(Arrays.asList(
                             "/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3")))
        -                .withCorrelationid("01080d2f-1dca-4610-afb4-dd25eec1f3c1"), com.azure.core.util.Context.NONE);
        +                .withCorrelationid("23480d2f-1dca-4610-afb4-dd25eec1f34r"), com.azure.core.util.Context.NONE);
             }
         }
         ```
        @@ -222,7 +139,6 @@ public final class ScheduledActionsVirtualMachinesExecuteHibernateSamples {
         ```java
         import com.azure.resourcemanager.computeschedule.models.ExecuteStartRequest;
         import com.azure.resourcemanager.computeschedule.models.ExecutionParameters;
        -import com.azure.resourcemanager.computeschedule.models.OptimizationPreference;
         import com.azure.resourcemanager.computeschedule.models.Resources;
         import com.azure.resourcemanager.computeschedule.models.RetryPolicy;
         import java.util.Arrays;
        @@ -232,43 +148,22 @@ import java.util.Arrays;
          */
         public final class ScheduledActionsVirtualMachinesExecuteStartSamples {
             /*
        -     * x-ms-original-file: 2024-08-15-preview/ScheduledActions_VirtualMachinesExecuteStart_MaximumSet_Gen.json
        -     */
        -    /**
        -     * Sample code: ScheduledActions_VirtualMachinesExecuteStart - generated by [MaximumSet] rule - generated by
        -     * [MaximumSet] rule.
        -     * 
        -     * @param manager Entry point to ComputeScheduleManager.
        -     */
        -    public static void scheduledActionsVirtualMachinesExecuteStartGeneratedByMaximumSetRuleGeneratedByMaximumSetRule(
        -        com.azure.resourcemanager.computeschedule.ComputeScheduleManager manager) {
        -        manager.scheduledActions()
        -            .virtualMachinesExecuteStartWithResponse("ysfrwcfmfsh", new ExecuteStartRequest()
        -                .withExecutionParameters(
        -                    new ExecutionParameters().withOptimizationPreference(OptimizationPreference.COST)
        -                        .withRetryPolicy(new RetryPolicy().withRetryCount(30).withRetryWindowInMinutes(27)))
        -                .withResources(new Resources().withIds(Arrays.asList(
        -                    "/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource4")))
        -                .withCorrelationid("23230d2f-1dca-4610-afb4-dd25eec1f34"), com.azure.core.util.Context.NONE);
        -    }
        -
        -    /*
        -     * x-ms-original-file: 2024-08-15-preview/ScheduledActions_VirtualMachinesExecuteStart_MinimumSet_Gen.json
        +     * x-ms-original-file: 2024-10-01/ScheduledActions_VirtualMachinesExecuteStart.json
              */
             /**
        -     * Sample code: ScheduledActions_VirtualMachinesExecuteStart - generated by [MaximumSet] rule - generated by
        -     * [MinimumSet] rule.
        +     * Sample code: ScheduledActions_VirtualMachinesExecuteStart.
              * 
              * @param manager Entry point to ComputeScheduleManager.
              */
        -    public static void scheduledActionsVirtualMachinesExecuteStartGeneratedByMaximumSetRuleGeneratedByMinimumSetRule(
        +    public static void scheduledActionsVirtualMachinesExecuteStart(
                 com.azure.resourcemanager.computeschedule.ComputeScheduleManager manager) {
                 manager.scheduledActions()
        -            .virtualMachinesExecuteStartWithResponse("qegbgjculewswqvnmaclcgpqqidl", new ExecuteStartRequest()
        -                .withExecutionParameters(new ExecutionParameters())
        +            .virtualMachinesExecuteStartWithResponse("eastus2euap", new ExecuteStartRequest()
        +                .withExecutionParameters(new ExecutionParameters()
        +                    .withRetryPolicy(new RetryPolicy().withRetryCount(2).withRetryWindowInMinutes(27)))
                         .withResources(new Resources().withIds(Arrays.asList(
        -                    "/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource4")))
        -                .withCorrelationid("23230d2f-1dca-4610-afb4-dd25eec1f34"), com.azure.core.util.Context.NONE);
        +                    "/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3")))
        +                .withCorrelationid("23480d2f-1dca-4610-afb4-dd25eec1f34r"), com.azure.core.util.Context.NONE);
             }
         }
         ```
        @@ -284,34 +179,18 @@ import java.util.Arrays;
          */
         public final class ScheduledActionsVirtualMachinesGetOperationErrorsSamples {
             /*
        -     * x-ms-original-file: 2024-08-15-preview/ScheduledActions_VirtualMachinesGetOperationErrors_MinimumSet_Gen.json
        +     * x-ms-original-file: 2024-10-01/ScheduledActions_VirtualMachinesGetOperationErrors.json
              */
             /**
        -     * Sample code: CS_ScheduledActions_VirtualMachinesGetOperationErrors_Min.
        +     * Sample code: ScheduledActions_VirtualMachinesGetOperationErrors.
              * 
              * @param manager Entry point to ComputeScheduleManager.
              */
        -    public static void csScheduledActionsVirtualMachinesGetOperationErrorsMin(
        +    public static void scheduledActionsVirtualMachinesGetOperationErrors(
                 com.azure.resourcemanager.computeschedule.ComputeScheduleManager manager) {
                 manager.scheduledActions()
        -            .virtualMachinesGetOperationErrorsWithResponse("ggxoaxzxtdbi",
        -                new GetOperationErrorsRequest().withOperationIds(Arrays.asList("qeicik")),
        -                com.azure.core.util.Context.NONE);
        -    }
        -
        -    /*
        -     * x-ms-original-file: 2024-08-15-preview/ScheduledActions_VirtualMachinesGetOperationErrors_MaximumSet_Gen.json
        -     */
        -    /**
        -     * Sample code: CS_ScheduledActions_VirtualMachinesGetOperationErrors_Max.
        -     * 
        -     * @param manager Entry point to ComputeScheduleManager.
        -     */
        -    public static void csScheduledActionsVirtualMachinesGetOperationErrorsMax(
        -        com.azure.resourcemanager.computeschedule.ComputeScheduleManager manager) {
        -        manager.scheduledActions()
        -            .virtualMachinesGetOperationErrorsWithResponse("hfsa",
        -                new GetOperationErrorsRequest().withOperationIds(Arrays.asList("DE84A209-5715-43E7-BC76-3E208A9A323")),
        +            .virtualMachinesGetOperationErrorsWithResponse("eastus2euap",
        +                new GetOperationErrorsRequest().withOperationIds(Arrays.asList("23480d2f-1dca-4610-afb4-dd25eec1f34r")),
                         com.azure.core.util.Context.NONE);
             }
         }
        @@ -328,38 +207,19 @@ import java.util.Arrays;
          */
         public final class ScheduledActionsVirtualMachinesGetOperationStatusSamples {
             /*
        -     * x-ms-original-file: 2024-08-15-preview/ScheduledActions_VirtualMachinesGetOperationStatus_MinimumSet_Gen.json
        +     * x-ms-original-file: 2024-10-01/ScheduledActions_VirtualMachinesGetOperationStatus.json
              */
             /**
        -     * Sample code: ScheduledActions_VirtualMachinesGetOperationStatus - generated by [MinimumSet] rule.
        +     * Sample code: ScheduledActions_VirtualMachinesGetOperationStatus.
              * 
              * @param manager Entry point to ComputeScheduleManager.
              */
        -    public static void scheduledActionsVirtualMachinesGetOperationStatusGeneratedByMinimumSetRule(
        +    public static void scheduledActionsVirtualMachinesGetOperationStatus(
                 com.azure.resourcemanager.computeschedule.ComputeScheduleManager manager) {
                 manager.scheduledActions()
        -            .virtualMachinesGetOperationStatusWithResponse("csay",
        -                new GetOperationStatusRequest().withOperationIds(Arrays.asList("01080d2f-1dca-4610-afb4-dd25eec1f3df"))
        -                    .withCorrelationid("01080d2f-1dca-4610-afb4-dd25eec1f3c1"),
        -                com.azure.core.util.Context.NONE);
        -    }
        -
        -    /*
        -     * x-ms-original-file: 2024-08-15-preview/ScheduledActions_VirtualMachinesGetOperationStatus_MaximumSet_Gen.json
        -     */
        -    /**
        -     * Sample code: ScheduledActions_VirtualMachinesGetOperationStatus - generated by [MinimumSet] rule - generated by
        -     * [MaximumSet] rule.
        -     * 
        -     * @param manager Entry point to ComputeScheduleManager.
        -     */
        -    public static void
        -        scheduledActionsVirtualMachinesGetOperationStatusGeneratedByMinimumSetRuleGeneratedByMaximumSetRule(
        -            com.azure.resourcemanager.computeschedule.ComputeScheduleManager manager) {
        -        manager.scheduledActions()
        -            .virtualMachinesGetOperationStatusWithResponse("htxxasfxaesuecem",
        -                new GetOperationStatusRequest().withOperationIds(Arrays.asList("01080d2f-1dca-4610-afb4-dd25eec1f3df"))
        -                    .withCorrelationid("01080d2f-1dca-4610-afb4-dd25eec1f3c1"),
        +            .virtualMachinesGetOperationStatusWithResponse("eastus2euap",
        +                new GetOperationStatusRequest().withOperationIds(Arrays.asList("23480d2f-1dca-4610-afb4-dd25eec1f34r"))
        +                    .withCorrelationid("35780d2f-1dca-4610-afb4-dd25eec1f34r"),
                         com.azure.core.util.Context.NONE);
             }
         }
        @@ -370,7 +230,6 @@ public final class ScheduledActionsVirtualMachinesGetOperationStatusSamples {
         ```java
         import com.azure.resourcemanager.computeschedule.models.DeadlineType;
         import com.azure.resourcemanager.computeschedule.models.ExecutionParameters;
        -import com.azure.resourcemanager.computeschedule.models.OptimizationPreference;
         import com.azure.resourcemanager.computeschedule.models.Resources;
         import com.azure.resourcemanager.computeschedule.models.RetryPolicy;
         import com.azure.resourcemanager.computeschedule.models.Schedule;
        @@ -383,51 +242,25 @@ import java.util.Arrays;
          */
         public final class ScheduledActionsVirtualMachinesSubmitDeallocateSamples {
             /*
        -     * x-ms-original-file: 2024-08-15-preview/ScheduledActions_VirtualMachinesSubmitDeallocate_MaximumSet_Gen.json
        -     */
        -    /**
        -     * Sample code: ScheduledActions_VirtualMachinesSubmitDeallocate - generated by [MaximumSet] rule - generated by
        -     * [MaximumSet] rule.
        -     * 
        -     * @param manager Entry point to ComputeScheduleManager.
        -     */
        -    public static void
        -        scheduledActionsVirtualMachinesSubmitDeallocateGeneratedByMaximumSetRuleGeneratedByMaximumSetRule(
        -            com.azure.resourcemanager.computeschedule.ComputeScheduleManager manager) {
        -        manager.scheduledActions()
        -            .virtualMachinesSubmitDeallocateWithResponse("ibfxsvilwrgqttuslbduzdtxcckdet", new SubmitDeallocateRequest()
        -                .withSchedule(new Schedule().withDeadLine(OffsetDateTime.parse("2024-07-12T18:06:53.361Z"))
        -                    .withTimeZone("zlcujrtgxtgyik")
        -                    .withDeadlineType(DeadlineType.UNKNOWN))
        -                .withExecutionParameters(
        -                    new ExecutionParameters().withOptimizationPreference(OptimizationPreference.COST)
        -                        .withRetryPolicy(new RetryPolicy().withRetryCount(30).withRetryWindowInMinutes(27)))
        -                .withResources(new Resources().withIds(Arrays.asList(
        -                    "/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource2")))
        -                .withCorrelationid("23519o2f-1dca-4610-afb4-dd25eec1f34"), com.azure.core.util.Context.NONE);
        -    }
        -
        -    /*
        -     * x-ms-original-file: 2024-08-15-preview/ScheduledActions_VirtualMachinesSubmitDeallocate_MinimumSet_Gen.json
        +     * x-ms-original-file: 2024-10-01/ScheduledActions_VirtualMachinesSubmitDeallocate.json
              */
             /**
        -     * Sample code: ScheduledActions_VirtualMachinesSubmitDeallocate - generated by [MaximumSet] rule - generated by
        -     * [MinimumSet] rule.
        +     * Sample code: ScheduledActions_VirtualMachinesSubmitDeallocate.
              * 
              * @param manager Entry point to ComputeScheduleManager.
              */
        -    public static void
        -        scheduledActionsVirtualMachinesSubmitDeallocateGeneratedByMaximumSetRuleGeneratedByMinimumSetRule(
        -            com.azure.resourcemanager.computeschedule.ComputeScheduleManager manager) {
        +    public static void scheduledActionsVirtualMachinesSubmitDeallocate(
        +        com.azure.resourcemanager.computeschedule.ComputeScheduleManager manager) {
                 manager.scheduledActions()
        -            .virtualMachinesSubmitDeallocateWithResponse("qwfcdtmshnlownbkyh", new SubmitDeallocateRequest()
        -                .withSchedule(new Schedule().withDeadLine(OffsetDateTime.parse("2024-07-12T18:06:53.361Z"))
        -                    .withTimeZone("zlcujrtgxtgyik")
        -                    .withDeadlineType(DeadlineType.UNKNOWN))
        -                .withExecutionParameters(new ExecutionParameters())
        +            .virtualMachinesSubmitDeallocateWithResponse("eastus2euap", new SubmitDeallocateRequest()
        +                .withSchedule(new Schedule().withDeadline(OffsetDateTime.parse("2024-11-01T17:52:54.215Z"))
        +                    .withTimezone("UTC")
        +                    .withDeadlineType(DeadlineType.INITIATE_AT))
        +                .withExecutionParameters(new ExecutionParameters()
        +                    .withRetryPolicy(new RetryPolicy().withRetryCount(4).withRetryWindowInMinutes(27)))
                         .withResources(new Resources().withIds(Arrays.asList(
        -                    "/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource2")))
        -                .withCorrelationid("23519o2f-1dca-4610-afb4-dd25eec1f34"), com.azure.core.util.Context.NONE);
        +                    "/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3")))
        +                .withCorrelationid("23480d2f-1dca-4610-afb4-dd25eec1f34r"), com.azure.core.util.Context.NONE);
             }
         }
         ```
        @@ -437,7 +270,6 @@ public final class ScheduledActionsVirtualMachinesSubmitDeallocateSamples {
         ```java
         import com.azure.resourcemanager.computeschedule.models.DeadlineType;
         import com.azure.resourcemanager.computeschedule.models.ExecutionParameters;
        -import com.azure.resourcemanager.computeschedule.models.OptimizationPreference;
         import com.azure.resourcemanager.computeschedule.models.Resources;
         import com.azure.resourcemanager.computeschedule.models.RetryPolicy;
         import com.azure.resourcemanager.computeschedule.models.Schedule;
        @@ -450,49 +282,25 @@ import java.util.Arrays;
          */
         public final class ScheduledActionsVirtualMachinesSubmitHibernateSamples {
             /*
        -     * x-ms-original-file: 2024-08-15-preview/ScheduledActions_VirtualMachinesSubmitHibernate_MinimumSet_Gen.json
        +     * x-ms-original-file: 2024-10-01/ScheduledActions_VirtualMachinesSubmitHibernate.json
              */
             /**
        -     * Sample code: ScheduledActions_VirtualMachinesSubmitHibernate - generated by [MaximumSet] rule - generated by
        -     * [MinimumSet] rule.
        +     * Sample code: ScheduledActions_VirtualMachinesSubmitHibernate.
              * 
              * @param manager Entry point to ComputeScheduleManager.
              */
        -    public static void scheduledActionsVirtualMachinesSubmitHibernateGeneratedByMaximumSetRuleGeneratedByMinimumSetRule(
        +    public static void scheduledActionsVirtualMachinesSubmitHibernate(
                 com.azure.resourcemanager.computeschedule.ComputeScheduleManager manager) {
                 manager.scheduledActions()
        -            .virtualMachinesSubmitHibernateWithResponse("fvjciwudfbndlqumcgqs", new SubmitHibernateRequest()
        -                .withSchedule(new Schedule().withDeadLine(OffsetDateTime.parse("2024-07-12T18:06:53.361Z"))
        -                    .withTimeZone("zlcujrtgxtgyik")
        -                    .withDeadlineType(DeadlineType.UNKNOWN))
        -                .withExecutionParameters(new ExecutionParameters())
        +            .virtualMachinesSubmitHibernateWithResponse("eastus2euap", new SubmitHibernateRequest()
        +                .withSchedule(new Schedule().withDeadline(OffsetDateTime.parse("2024-11-01T17:52:54.215Z"))
        +                    .withTimezone("UTC")
        +                    .withDeadlineType(DeadlineType.INITIATE_AT))
        +                .withExecutionParameters(new ExecutionParameters()
        +                    .withRetryPolicy(new RetryPolicy().withRetryCount(2).withRetryWindowInMinutes(27)))
                         .withResources(new Resources().withIds(Arrays.asList(
                             "/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3")))
        -                .withCorrelationid("23519o2f-1dca-4610-afb4-dd25eec1f34"), com.azure.core.util.Context.NONE);
        -    }
        -
        -    /*
        -     * x-ms-original-file: 2024-08-15-preview/ScheduledActions_VirtualMachinesSubmitHibernate_MaximumSet_Gen.json
        -     */
        -    /**
        -     * Sample code: ScheduledActions_VirtualMachinesSubmitHibernate - generated by [MaximumSet] rule - generated by
        -     * [MaximumSet] rule.
        -     * 
        -     * @param manager Entry point to ComputeScheduleManager.
        -     */
        -    public static void scheduledActionsVirtualMachinesSubmitHibernateGeneratedByMaximumSetRuleGeneratedByMaximumSetRule(
        -        com.azure.resourcemanager.computeschedule.ComputeScheduleManager manager) {
        -        manager.scheduledActions()
        -            .virtualMachinesSubmitHibernateWithResponse("bgxeayimbxqzev", new SubmitHibernateRequest()
        -                .withSchedule(new Schedule().withDeadLine(OffsetDateTime.parse("2024-07-12T18:06:53.361Z"))
        -                    .withTimeZone("zlcujrtgxtgyik")
        -                    .withDeadlineType(DeadlineType.UNKNOWN))
        -                .withExecutionParameters(
        -                    new ExecutionParameters().withOptimizationPreference(OptimizationPreference.COST)
        -                        .withRetryPolicy(new RetryPolicy().withRetryCount(30).withRetryWindowInMinutes(27)))
        -                .withResources(new Resources().withIds(Arrays.asList(
        -                    "/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3")))
        -                .withCorrelationid("23519o2f-1dca-4610-afb4-dd25eec1f34"), com.azure.core.util.Context.NONE);
        +                .withCorrelationid("23480d2f-1dca-4610-afb4-dd25eec1f34r"), com.azure.core.util.Context.NONE);
             }
         }
         ```
        @@ -502,7 +310,6 @@ public final class ScheduledActionsVirtualMachinesSubmitHibernateSamples {
         ```java
         import com.azure.resourcemanager.computeschedule.models.DeadlineType;
         import com.azure.resourcemanager.computeschedule.models.ExecutionParameters;
        -import com.azure.resourcemanager.computeschedule.models.OptimizationPreference;
         import com.azure.resourcemanager.computeschedule.models.Resources;
         import com.azure.resourcemanager.computeschedule.models.RetryPolicy;
         import com.azure.resourcemanager.computeschedule.models.Schedule;
        @@ -515,49 +322,25 @@ import java.util.Arrays;
          */
         public final class ScheduledActionsVirtualMachinesSubmitStartSamples {
             /*
        -     * x-ms-original-file: 2024-08-15-preview/ScheduledActions_VirtualMachinesSubmitStart_MaximumSet_Gen.json
        -     */
        -    /**
        -     * Sample code: ScheduledActions_VirtualMachinesSubmitStart - generated by [MaximumSet] rule - generated by
        -     * [MaximumSet] rule.
        -     * 
        -     * @param manager Entry point to ComputeScheduleManager.
        -     */
        -    public static void scheduledActionsVirtualMachinesSubmitStartGeneratedByMaximumSetRuleGeneratedByMaximumSetRule(
        -        com.azure.resourcemanager.computeschedule.ComputeScheduleManager manager) {
        -        manager.scheduledActions()
        -            .virtualMachinesSubmitStartWithResponse("fxiidszhrokwjmewlahfqjiocnes", new SubmitStartRequest()
        -                .withSchedule(new Schedule().withDeadLine(OffsetDateTime.parse("2024-07-12T18:06:53.361Z"))
        -                    .withTimeZone("zlcujrtgxtgyik")
        -                    .withDeadlineType(DeadlineType.UNKNOWN))
        -                .withExecutionParameters(
        -                    new ExecutionParameters().withOptimizationPreference(OptimizationPreference.COST)
        -                        .withRetryPolicy(new RetryPolicy().withRetryCount(30).withRetryWindowInMinutes(27)))
        -                .withResources(new Resources().withIds(Arrays.asList(
        -                    "/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource4")))
        -                .withCorrelationid("23480d2f-1dca-4610-afb4-dd25eec1f34"), com.azure.core.util.Context.NONE);
        -    }
        -
        -    /*
        -     * x-ms-original-file: 2024-08-15-preview/ScheduledActions_VirtualMachinesSubmitStart_MinimumSet_Gen.json
        +     * x-ms-original-file: 2024-10-01/ScheduledActions_VirtualMachinesSubmitStart.json
              */
             /**
        -     * Sample code: ScheduledActions_VirtualMachinesSubmitStart - generated by [MaximumSet] rule - generated by
        -     * [MinimumSet] rule.
        +     * Sample code: ScheduledActions_VirtualMachinesSubmitStart.
              * 
              * @param manager Entry point to ComputeScheduleManager.
              */
        -    public static void scheduledActionsVirtualMachinesSubmitStartGeneratedByMaximumSetRuleGeneratedByMinimumSetRule(
        +    public static void scheduledActionsVirtualMachinesSubmitStart(
                 com.azure.resourcemanager.computeschedule.ComputeScheduleManager manager) {
                 manager.scheduledActions()
        -            .virtualMachinesSubmitStartWithResponse("httzei", new SubmitStartRequest()
        -                .withSchedule(new Schedule().withDeadLine(OffsetDateTime.parse("2024-07-12T18:06:53.361Z"))
        -                    .withTimeZone("zlcujrtgxtgyik")
        -                    .withDeadlineType(DeadlineType.UNKNOWN))
        -                .withExecutionParameters(new ExecutionParameters())
        +            .virtualMachinesSubmitStartWithResponse("eastus2euap", new SubmitStartRequest()
        +                .withSchedule(new Schedule().withDeadline(OffsetDateTime.parse("2024-11-01T17:52:54.215Z"))
        +                    .withTimezone("UTC")
        +                    .withDeadlineType(DeadlineType.INITIATE_AT))
        +                .withExecutionParameters(new ExecutionParameters()
        +                    .withRetryPolicy(new RetryPolicy().withRetryCount(5).withRetryWindowInMinutes(27)))
                         .withResources(new Resources().withIds(Arrays.asList(
        -                    "/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource4")))
        -                .withCorrelationid("23480d2f-1dca-4610-afb4-dd25eec1f34"), com.azure.core.util.Context.NONE);
        +                    "/subscriptions/YourSubscriptionId/resourceGroups/YourResourceGroupName/providers/Microsoft.Compute/virtualMachines/testResource3")))
        +                .withCorrelationid("23480d2f-1dca-4610-afb4-dd25eec1f34r"), com.azure.core.util.Context.NONE);
             }
         }
         ```
        diff --git a/sdk/computeschedule/azure-resourcemanager-computeschedule/pom.xml b/sdk/computeschedule/azure-resourcemanager-computeschedule/pom.xml
        index 7e43f5c30723..7073611b611e 100644
        --- a/sdk/computeschedule/azure-resourcemanager-computeschedule/pom.xml
        +++ b/sdk/computeschedule/azure-resourcemanager-computeschedule/pom.xml
        @@ -14,7 +14,7 @@
         
           com.azure.resourcemanager
           azure-resourcemanager-computeschedule
        -  1.0.0-beta.2 
        +  1.1.0-beta.1 
           jar
         
           Microsoft Azure SDK for Compute Schedule Management
        @@ -46,34 +46,35 @@
             0
             0
             true
        +    false
           
           
        -    
        -      com.azure
        -      azure-json
        -      1.3.0 
        -    
             
               com.azure
               azure-core
        -      1.54.1 
        +      1.55.3 
             
             
               com.azure
               azure-core-management
        -      1.15.6 
        +      1.17.0 
             
             
               com.azure
               azure-core-test
        -      1.27.0-beta.4 
        +      1.27.0-beta.8 
               test
             
             
               com.azure
               azure-identity
        -      1.15.0 
        +      1.15.4 
               test
             
        +    
        +      com.azure
        +      azure-json
        +      1.5.0 
        +    
           
         
        diff --git a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/ComputeScheduleManager.java b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/ComputeScheduleManager.java
        index 564a62115316..83c53e649d59 100644
        --- a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/ComputeScheduleManager.java
        +++ b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/ComputeScheduleManager.java
        @@ -22,9 +22,10 @@
         import com.azure.core.http.policy.UserAgentPolicy;
         import com.azure.core.management.profile.AzureProfile;
         import com.azure.core.util.Configuration;
        +import com.azure.core.util.CoreUtils;
         import com.azure.core.util.logging.ClientLogger;
        -import com.azure.resourcemanager.computeschedule.fluent.ComputeScheduleClient;
        -import com.azure.resourcemanager.computeschedule.implementation.ComputeScheduleClientBuilder;
        +import com.azure.resourcemanager.computeschedule.fluent.ComputeScheduleMgmtClient;
        +import com.azure.resourcemanager.computeschedule.implementation.ComputeScheduleMgmtClientBuilder;
         import com.azure.resourcemanager.computeschedule.implementation.OperationsImpl;
         import com.azure.resourcemanager.computeschedule.implementation.ScheduledActionsImpl;
         import com.azure.resourcemanager.computeschedule.models.Operations;
        @@ -33,6 +34,7 @@
         import java.time.temporal.ChronoUnit;
         import java.util.ArrayList;
         import java.util.List;
        +import java.util.Map;
         import java.util.Objects;
         import java.util.stream.Collectors;
         
        @@ -45,12 +47,12 @@ public final class ComputeScheduleManager {
         
             private ScheduledActions scheduledActions;
         
        -    private final ComputeScheduleClient clientObject;
        +    private final ComputeScheduleMgmtClient clientObject;
         
             private ComputeScheduleManager(HttpPipeline httpPipeline, AzureProfile profile, Duration defaultPollInterval) {
                 Objects.requireNonNull(httpPipeline, "'httpPipeline' cannot be null.");
                 Objects.requireNonNull(profile, "'profile' cannot be null.");
        -        this.clientObject = new ComputeScheduleClientBuilder().pipeline(httpPipeline)
        +        this.clientObject = new ComputeScheduleMgmtClientBuilder().pipeline(httpPipeline)
                     .endpoint(profile.getEnvironment().getResourceManagerEndpoint())
                     .subscriptionId(profile.getSubscriptionId())
                     .defaultPollInterval(defaultPollInterval)
        @@ -97,6 +99,9 @@ public static Configurable configure() {
              */
             public static final class Configurable {
                 private static final ClientLogger LOGGER = new ClientLogger(Configurable.class);
        +        private static final String SDK_VERSION = "version";
        +        private static final Map PROPERTIES
        +            = CoreUtils.getProperties("azure-resourcemanager-computeschedule.properties");
         
                 private HttpClient httpClient;
                 private HttpLogOptions httpLogOptions;
        @@ -204,12 +209,14 @@ public ComputeScheduleManager authenticate(TokenCredential credential, AzureProf
                     Objects.requireNonNull(credential, "'credential' cannot be null.");
                     Objects.requireNonNull(profile, "'profile' cannot be null.");
         
        +            String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion");
        +
                     StringBuilder userAgentBuilder = new StringBuilder();
                     userAgentBuilder.append("azsdk-java")
                         .append("-")
                         .append("com.azure.resourcemanager.computeschedule")
                         .append("/")
        -                .append("1.0.0-beta.1");
        +                .append(clientVersion);
                     if (!Configuration.getGlobalConfiguration().get("AZURE_TELEMETRY_DISABLED", false)) {
                         userAgentBuilder.append(" (")
                             .append(Configuration.getGlobalConfiguration().get("java.version"))
        @@ -280,12 +287,12 @@ public ScheduledActions scheduledActions() {
             }
         
             /**
        -     * Gets wrapped service client ComputeScheduleClient providing direct access to the underlying auto-generated API
        -     * implementation, based on Azure REST API.
        +     * Gets wrapped service client ComputeScheduleMgmtClient providing direct access to the underlying auto-generated
        +     * API implementation, based on Azure REST API.
              * 
        -     * @return Wrapped service client ComputeScheduleClient.
        +     * @return Wrapped service client ComputeScheduleMgmtClient.
              */
        -    public ComputeScheduleClient serviceClient() {
        +    public ComputeScheduleMgmtClient serviceClient() {
                 return this.clientObject;
             }
         }
        diff --git a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/fluent/ComputeScheduleClient.java b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/fluent/ComputeScheduleClient.java
        deleted file mode 100644
        index 849747a27a1c..000000000000
        --- a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/fluent/ComputeScheduleClient.java
        +++ /dev/null
        @@ -1,62 +0,0 @@
        -// Copyright (c) Microsoft Corporation. All rights reserved.
        -// Licensed under the MIT License.
        -// Code generated by Microsoft (R) TypeSpec Code Generator.
        -
        -package com.azure.resourcemanager.computeschedule.fluent;
        -
        -import com.azure.core.http.HttpPipeline;
        -import java.time.Duration;
        -
        -/**
        - * The interface for ComputeScheduleClient class.
        - */
        -public interface ComputeScheduleClient {
        -    /**
        -     * Gets Service host.
        -     * 
        -     * @return the endpoint value.
        -     */
        -    String getEndpoint();
        -
        -    /**
        -     * Gets Version parameter.
        -     * 
        -     * @return the apiVersion value.
        -     */
        -    String getApiVersion();
        -
        -    /**
        -     * Gets The ID of the target subscription. The value must be an UUID.
        -     * 
        -     * @return the subscriptionId value.
        -     */
        -    String getSubscriptionId();
        -
        -    /**
        -     * Gets The HTTP pipeline to send requests through.
        -     * 
        -     * @return the httpPipeline value.
        -     */
        -    HttpPipeline getHttpPipeline();
        -
        -    /**
        -     * Gets The default poll interval for long-running operation.
        -     * 
        -     * @return the defaultPollInterval value.
        -     */
        -    Duration getDefaultPollInterval();
        -
        -    /**
        -     * Gets the OperationsClient object to access its operations.
        -     * 
        -     * @return the OperationsClient object.
        -     */
        -    OperationsClient getOperations();
        -
        -    /**
        -     * Gets the ScheduledActionsClient object to access its operations.
        -     * 
        -     * @return the ScheduledActionsClient object.
        -     */
        -    ScheduledActionsClient getScheduledActions();
        -}
        diff --git a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/fluent/ComputeScheduleMgmtClient.java b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/fluent/ComputeScheduleMgmtClient.java
        new file mode 100644
        index 000000000000..d42ac61bf644
        --- /dev/null
        +++ b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/fluent/ComputeScheduleMgmtClient.java
        @@ -0,0 +1,62 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) TypeSpec Code Generator.
        +
        +package com.azure.resourcemanager.computeschedule.fluent;
        +
        +import com.azure.core.http.HttpPipeline;
        +import java.time.Duration;
        +
        +/**
        + * The interface for ComputeScheduleMgmtClient class.
        + */
        +public interface ComputeScheduleMgmtClient {
        +    /**
        +     * Gets Service host.
        +     * 
        +     * @return the endpoint value.
        +     */
        +    String getEndpoint();
        +
        +    /**
        +     * Gets Version parameter.
        +     * 
        +     * @return the apiVersion value.
        +     */
        +    String getApiVersion();
        +
        +    /**
        +     * Gets The ID of the target subscription. The value must be an UUID.
        +     * 
        +     * @return the subscriptionId value.
        +     */
        +    String getSubscriptionId();
        +
        +    /**
        +     * Gets The HTTP pipeline to send requests through.
        +     * 
        +     * @return the httpPipeline value.
        +     */
        +    HttpPipeline getHttpPipeline();
        +
        +    /**
        +     * Gets The default poll interval for long-running operation.
        +     * 
        +     * @return the defaultPollInterval value.
        +     */
        +    Duration getDefaultPollInterval();
        +
        +    /**
        +     * Gets the OperationsClient object to access its operations.
        +     * 
        +     * @return the OperationsClient object.
        +     */
        +    OperationsClient getOperations();
        +
        +    /**
        +     * Gets the ScheduledActionsClient object to access its operations.
        +     * 
        +     * @return the ScheduledActionsClient object.
        +     */
        +    ScheduledActionsClient getScheduledActions();
        +}
        diff --git a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/fluent/ScheduledActionsClient.java b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/fluent/ScheduledActionsClient.java
        index 4e35bfcd1e53..197f2dbc9c7a 100644
        --- a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/fluent/ScheduledActionsClient.java
        +++ b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/fluent/ScheduledActionsClient.java
        @@ -29,7 +29,8 @@
          */
         public interface ScheduledActionsClient {
             /**
        -     * virtualMachinesSubmitDeallocate: submitDeallocate for a virtual machine.
        +     * VirtualMachinesSubmitDeallocate: Schedule deallocate operation for a batch of virtual machines at datetime in
        +     * future.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -44,7 +45,8 @@ Response virtualMachinesSubmitDealloca
                 String locationparameter, SubmitDeallocateRequest requestBody, Context context);
         
             /**
        -     * virtualMachinesSubmitDeallocate: submitDeallocate for a virtual machine.
        +     * VirtualMachinesSubmitDeallocate: Schedule deallocate operation for a batch of virtual machines at datetime in
        +     * future.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -58,7 +60,8 @@ DeallocateResourceOperationResponseInner virtualMachinesSubmitDeallocate(String
                 SubmitDeallocateRequest requestBody);
         
             /**
        -     * virtualMachinesSubmitHibernate: submitHibernate for a virtual machine.
        +     * VirtualMachinesSubmitHibernate: Schedule hibernate operation for a batch of virtual machines at datetime in
        +     * future.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -73,7 +76,8 @@ Response virtualMachinesSubmitHibernate
                 String locationparameter, SubmitHibernateRequest requestBody, Context context);
         
             /**
        -     * virtualMachinesSubmitHibernate: submitHibernate for a virtual machine.
        +     * VirtualMachinesSubmitHibernate: Schedule hibernate operation for a batch of virtual machines at datetime in
        +     * future.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -87,7 +91,7 @@ HibernateResourceOperationResponseInner virtualMachinesSubmitHibernate(String lo
                 SubmitHibernateRequest requestBody);
         
             /**
        -     * virtualMachinesSubmitStart: submitStart for a virtual machine.
        +     * VirtualMachinesSubmitStart: Schedule start operation for a batch of virtual machines at datetime in future.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -102,7 +106,7 @@ Response virtualMachinesSubmitStartWithResp
                 SubmitStartRequest requestBody, Context context);
         
             /**
        -     * virtualMachinesSubmitStart: submitStart for a virtual machine.
        +     * VirtualMachinesSubmitStart: Schedule start operation for a batch of virtual machines at datetime in future.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -116,7 +120,8 @@ StartResourceOperationResponseInner virtualMachinesSubmitStart(String locationpa
                 SubmitStartRequest requestBody);
         
             /**
        -     * virtualMachinesExecuteDeallocate: executeDeallocate for a virtual machine.
        +     * VirtualMachinesExecuteDeallocate: Execute deallocate operation for a batch of virtual machines, this operation is
        +     * triggered as soon as Computeschedule receives it.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -131,7 +136,8 @@ Response virtualMachinesExecuteDealloc
                 String locationparameter, ExecuteDeallocateRequest requestBody, Context context);
         
             /**
        -     * virtualMachinesExecuteDeallocate: executeDeallocate for a virtual machine.
        +     * VirtualMachinesExecuteDeallocate: Execute deallocate operation for a batch of virtual machines, this operation is
        +     * triggered as soon as Computeschedule receives it.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -145,7 +151,8 @@ DeallocateResourceOperationResponseInner virtualMachinesExecuteDeallocate(String
                 ExecuteDeallocateRequest requestBody);
         
             /**
        -     * virtualMachinesExecuteHibernate: executeHibernate for a virtual machine.
        +     * VirtualMachinesExecuteHibernate: Execute hibernate operation for a batch of virtual machines, this operation is
        +     * triggered as soon as Computeschedule receives it.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -160,7 +167,8 @@ Response virtualMachinesExecuteHibernat
                 String locationparameter, ExecuteHibernateRequest requestBody, Context context);
         
             /**
        -     * virtualMachinesExecuteHibernate: executeHibernate for a virtual machine.
        +     * VirtualMachinesExecuteHibernate: Execute hibernate operation for a batch of virtual machines, this operation is
        +     * triggered as soon as Computeschedule receives it.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -174,7 +182,8 @@ HibernateResourceOperationResponseInner virtualMachinesExecuteHibernate(String l
                 ExecuteHibernateRequest requestBody);
         
             /**
        -     * virtualMachinesExecuteStart: executeStart for a virtual machine.
        +     * VirtualMachinesExecuteStart: Execute start operation for a batch of virtual machines, this operation is triggered
        +     * as soon as Computeschedule receives it.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -189,7 +198,8 @@ Response virtualMachinesExecuteStartWithRes
                 ExecuteStartRequest requestBody, Context context);
         
             /**
        -     * virtualMachinesExecuteStart: executeStart for a virtual machine.
        +     * VirtualMachinesExecuteStart: Execute start operation for a batch of virtual machines, this operation is triggered
        +     * as soon as Computeschedule receives it.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -203,7 +213,7 @@ StartResourceOperationResponseInner virtualMachinesExecuteStart(String locationp
                 ExecuteStartRequest requestBody);
         
             /**
        -     * virtualMachinesGetOperationStatus: getOperationStatus for a virtual machine.
        +     * VirtualMachinesGetOperationStatus: Polling endpoint to read status of operations performed on virtual machines.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -218,7 +228,7 @@ Response virtualMachinesGetOperationStatusWithR
                 GetOperationStatusRequest requestBody, Context context);
         
             /**
        -     * virtualMachinesGetOperationStatus: getOperationStatus for a virtual machine.
        +     * VirtualMachinesGetOperationStatus: Polling endpoint to read status of operations performed on virtual machines.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -232,7 +242,7 @@ GetOperationStatusResponseInner virtualMachinesGetOperationStatus(String locatio
                 GetOperationStatusRequest requestBody);
         
             /**
        -     * virtualMachinesCancelOperations: cancelOperations for a virtual machine.
        +     * VirtualMachinesCancelOperations: Cancel a previously submitted (start/deallocate/hibernate) request.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -247,7 +257,7 @@ Response virtualMachinesCancelOperationsWithRespo
                 CancelOperationsRequest requestBody, Context context);
         
             /**
        -     * virtualMachinesCancelOperations: cancelOperations for a virtual machine.
        +     * VirtualMachinesCancelOperations: Cancel a previously submitted (start/deallocate/hibernate) request.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -261,7 +271,8 @@ CancelOperationsResponseInner virtualMachinesCancelOperations(String locationpar
                 CancelOperationsRequest requestBody);
         
             /**
        -     * virtualMachinesGetOperationErrors: getOperationErrors associated with an operation on a virtual machine.
        +     * VirtualMachinesGetOperationErrors: Get error details on operation errors (like transient errors encountered,
        +     * additional logs) if they exist.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -276,7 +287,8 @@ Response virtualMachinesGetOperationErrorsWithR
                 GetOperationErrorsRequest requestBody, Context context);
         
             /**
        -     * virtualMachinesGetOperationErrors: getOperationErrors associated with an operation on a virtual machine.
        +     * VirtualMachinesGetOperationErrors: Get error details on operation errors (like transient errors encountered,
        +     * additional logs) if they exist.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        diff --git a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/implementation/ComputeScheduleClientBuilder.java b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/implementation/ComputeScheduleClientBuilder.java
        deleted file mode 100644
        index 863157199db2..000000000000
        --- a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/implementation/ComputeScheduleClientBuilder.java
        +++ /dev/null
        @@ -1,138 +0,0 @@
        -// Copyright (c) Microsoft Corporation. All rights reserved.
        -// Licensed under the MIT License.
        -// Code generated by Microsoft (R) TypeSpec Code Generator.
        -
        -package com.azure.resourcemanager.computeschedule.implementation;
        -
        -import com.azure.core.annotation.ServiceClientBuilder;
        -import com.azure.core.http.HttpPipeline;
        -import com.azure.core.http.HttpPipelineBuilder;
        -import com.azure.core.http.policy.RetryPolicy;
        -import com.azure.core.http.policy.UserAgentPolicy;
        -import com.azure.core.management.AzureEnvironment;
        -import com.azure.core.management.serializer.SerializerFactory;
        -import com.azure.core.util.serializer.SerializerAdapter;
        -import java.time.Duration;
        -
        -/**
        - * A builder for creating a new instance of the ComputeScheduleClientImpl type.
        - */
        -@ServiceClientBuilder(serviceClients = { ComputeScheduleClientImpl.class })
        -public final class ComputeScheduleClientBuilder {
        -    /*
        -     * Service host
        -     */
        -    private String endpoint;
        -
        -    /**
        -     * Sets Service host.
        -     * 
        -     * @param endpoint the endpoint value.
        -     * @return the ComputeScheduleClientBuilder.
        -     */
        -    public ComputeScheduleClientBuilder endpoint(String endpoint) {
        -        this.endpoint = endpoint;
        -        return this;
        -    }
        -
        -    /*
        -     * The ID of the target subscription. The value must be an UUID.
        -     */
        -    private String subscriptionId;
        -
        -    /**
        -     * Sets The ID of the target subscription. The value must be an UUID.
        -     * 
        -     * @param subscriptionId the subscriptionId value.
        -     * @return the ComputeScheduleClientBuilder.
        -     */
        -    public ComputeScheduleClientBuilder subscriptionId(String subscriptionId) {
        -        this.subscriptionId = subscriptionId;
        -        return this;
        -    }
        -
        -    /*
        -     * The environment to connect to
        -     */
        -    private AzureEnvironment environment;
        -
        -    /**
        -     * Sets The environment to connect to.
        -     * 
        -     * @param environment the environment value.
        -     * @return the ComputeScheduleClientBuilder.
        -     */
        -    public ComputeScheduleClientBuilder environment(AzureEnvironment environment) {
        -        this.environment = environment;
        -        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 ComputeScheduleClientBuilder.
        -     */
        -    public ComputeScheduleClientBuilder pipeline(HttpPipeline pipeline) {
        -        this.pipeline = pipeline;
        -        return this;
        -    }
        -
        -    /*
        -     * The default poll interval for long-running operation
        -     */
        -    private Duration defaultPollInterval;
        -
        -    /**
        -     * Sets The default poll interval for long-running operation.
        -     * 
        -     * @param defaultPollInterval the defaultPollInterval value.
        -     * @return the ComputeScheduleClientBuilder.
        -     */
        -    public ComputeScheduleClientBuilder defaultPollInterval(Duration defaultPollInterval) {
        -        this.defaultPollInterval = defaultPollInterval;
        -        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 ComputeScheduleClientBuilder.
        -     */
        -    public ComputeScheduleClientBuilder serializerAdapter(SerializerAdapter serializerAdapter) {
        -        this.serializerAdapter = serializerAdapter;
        -        return this;
        -    }
        -
        -    /**
        -     * Builds an instance of ComputeScheduleClientImpl with the provided parameters.
        -     * 
        -     * @return an instance of ComputeScheduleClientImpl.
        -     */
        -    public ComputeScheduleClientImpl buildClient() {
        -        String localEndpoint = (endpoint != null) ? endpoint : "https://management.azure.com";
        -        AzureEnvironment localEnvironment = (environment != null) ? environment : AzureEnvironment.AZURE;
        -        HttpPipeline localPipeline = (pipeline != null)
        -            ? pipeline
        -            : new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build();
        -        Duration localDefaultPollInterval
        -            = (defaultPollInterval != null) ? defaultPollInterval : Duration.ofSeconds(30);
        -        SerializerAdapter localSerializerAdapter = (serializerAdapter != null)
        -            ? serializerAdapter
        -            : SerializerFactory.createDefaultManagementSerializerAdapter();
        -        ComputeScheduleClientImpl client = new ComputeScheduleClientImpl(localPipeline, localSerializerAdapter,
        -            localDefaultPollInterval, localEnvironment, localEndpoint, this.subscriptionId);
        -        return client;
        -    }
        -}
        diff --git a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/implementation/ComputeScheduleClientImpl.java b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/implementation/ComputeScheduleClientImpl.java
        deleted file mode 100644
        index 531f90f13b5c..000000000000
        --- a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/implementation/ComputeScheduleClientImpl.java
        +++ /dev/null
        @@ -1,304 +0,0 @@
        -// Copyright (c) Microsoft Corporation. All rights reserved.
        -// Licensed under the MIT License.
        -// Code generated by Microsoft (R) TypeSpec Code Generator.
        -
        -package com.azure.resourcemanager.computeschedule.implementation;
        -
        -import com.azure.core.annotation.ServiceClient;
        -import com.azure.core.http.HttpHeaderName;
        -import com.azure.core.http.HttpHeaders;
        -import com.azure.core.http.HttpPipeline;
        -import com.azure.core.http.HttpResponse;
        -import com.azure.core.http.rest.Response;
        -import com.azure.core.management.AzureEnvironment;
        -import com.azure.core.management.exception.ManagementError;
        -import com.azure.core.management.exception.ManagementException;
        -import com.azure.core.management.polling.PollResult;
        -import com.azure.core.management.polling.PollerFactory;
        -import com.azure.core.util.Context;
        -import com.azure.core.util.CoreUtils;
        -import com.azure.core.util.logging.ClientLogger;
        -import com.azure.core.util.polling.AsyncPollResponse;
        -import com.azure.core.util.polling.LongRunningOperationStatus;
        -import com.azure.core.util.polling.PollerFlux;
        -import com.azure.core.util.serializer.SerializerAdapter;
        -import com.azure.core.util.serializer.SerializerEncoding;
        -import com.azure.resourcemanager.computeschedule.fluent.ComputeScheduleClient;
        -import com.azure.resourcemanager.computeschedule.fluent.OperationsClient;
        -import com.azure.resourcemanager.computeschedule.fluent.ScheduledActionsClient;
        -import java.io.IOException;
        -import java.lang.reflect.Type;
        -import java.nio.ByteBuffer;
        -import java.nio.charset.Charset;
        -import java.nio.charset.StandardCharsets;
        -import java.time.Duration;
        -import reactor.core.publisher.Flux;
        -import reactor.core.publisher.Mono;
        -
        -/**
        - * Initializes a new instance of the ComputeScheduleClientImpl type.
        - */
        -@ServiceClient(builder = ComputeScheduleClientBuilder.class)
        -public final class ComputeScheduleClientImpl implements ComputeScheduleClient {
        -    /**
        -     * Service host.
        -     */
        -    private final String endpoint;
        -
        -    /**
        -     * Gets Service host.
        -     * 
        -     * @return the endpoint value.
        -     */
        -    public String getEndpoint() {
        -        return this.endpoint;
        -    }
        -
        -    /**
        -     * Version parameter.
        -     */
        -    private final String apiVersion;
        -
        -    /**
        -     * Gets Version parameter.
        -     * 
        -     * @return the apiVersion value.
        -     */
        -    public String getApiVersion() {
        -        return this.apiVersion;
        -    }
        -
        -    /**
        -     * The ID of the target subscription. The value must be an UUID.
        -     */
        -    private final String subscriptionId;
        -
        -    /**
        -     * Gets The ID of the target subscription. The value must be an UUID.
        -     * 
        -     * @return the subscriptionId value.
        -     */
        -    public String getSubscriptionId() {
        -        return this.subscriptionId;
        -    }
        -
        -    /**
        -     * 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.
        -     */
        -    SerializerAdapter getSerializerAdapter() {
        -        return this.serializerAdapter;
        -    }
        -
        -    /**
        -     * The default poll interval for long-running operation.
        -     */
        -    private final Duration defaultPollInterval;
        -
        -    /**
        -     * Gets The default poll interval for long-running operation.
        -     * 
        -     * @return the defaultPollInterval value.
        -     */
        -    public Duration getDefaultPollInterval() {
        -        return this.defaultPollInterval;
        -    }
        -
        -    /**
        -     * The OperationsClient object to access its operations.
        -     */
        -    private final OperationsClient operations;
        -
        -    /**
        -     * Gets the OperationsClient object to access its operations.
        -     * 
        -     * @return the OperationsClient object.
        -     */
        -    public OperationsClient getOperations() {
        -        return this.operations;
        -    }
        -
        -    /**
        -     * The ScheduledActionsClient object to access its operations.
        -     */
        -    private final ScheduledActionsClient scheduledActions;
        -
        -    /**
        -     * Gets the ScheduledActionsClient object to access its operations.
        -     * 
        -     * @return the ScheduledActionsClient object.
        -     */
        -    public ScheduledActionsClient getScheduledActions() {
        -        return this.scheduledActions;
        -    }
        -
        -    /**
        -     * Initializes an instance of ComputeScheduleClient client.
        -     * 
        -     * @param httpPipeline The HTTP pipeline to send requests through.
        -     * @param serializerAdapter The serializer to serialize an object into a string.
        -     * @param defaultPollInterval The default poll interval for long-running operation.
        -     * @param environment The Azure environment.
        -     * @param endpoint Service host.
        -     * @param subscriptionId The ID of the target subscription. The value must be an UUID.
        -     */
        -    ComputeScheduleClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter,
        -        Duration defaultPollInterval, AzureEnvironment environment, String endpoint, String subscriptionId) {
        -        this.httpPipeline = httpPipeline;
        -        this.serializerAdapter = serializerAdapter;
        -        this.defaultPollInterval = defaultPollInterval;
        -        this.endpoint = endpoint;
        -        this.subscriptionId = subscriptionId;
        -        this.apiVersion = "2024-08-15-preview";
        -        this.operations = new OperationsClientImpl(this);
        -        this.scheduledActions = new ScheduledActionsClientImpl(this);
        -    }
        -
        -    /**
        -     * Gets default client context.
        -     * 
        -     * @return the default client context.
        -     */
        -    public Context getContext() {
        -        return Context.NONE;
        -    }
        -
        -    /**
        -     * Merges default client context with provided context.
        -     * 
        -     * @param context the context to be merged with default client context.
        -     * @return the merged context.
        -     */
        -    public Context mergeContext(Context context) {
        -        return CoreUtils.mergeContexts(this.getContext(), context);
        -    }
        -
        -    /**
        -     * Gets long running operation result.
        -     * 
        -     * @param activationResponse the response of activation operation.
        -     * @param httpPipeline the http pipeline.
        -     * @param pollResultType type of poll result.
        -     * @param finalResultType type of final result.
        -     * @param context the context shared by all requests.
        -     * @param  type of poll result.
        -     * @param  type of final result.
        -     * @return poller flux for poll result and final result.
        -     */
        -    public  PollerFlux, U> getLroResult(Mono>> activationResponse,
        -        HttpPipeline httpPipeline, Type pollResultType, Type finalResultType, Context context) {
        -        return PollerFactory.create(serializerAdapter, httpPipeline, pollResultType, finalResultType,
        -            defaultPollInterval, activationResponse, context);
        -    }
        -
        -    /**
        -     * Gets the final result, or an error, based on last async poll response.
        -     * 
        -     * @param response the last async poll response.
        -     * @param  type of poll result.
        -     * @param  type of final result.
        -     * @return the final result, or an error.
        -     */
        -    public  Mono getLroFinalResultOrError(AsyncPollResponse, U> response) {
        -        if (response.getStatus() != LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) {
        -            String errorMessage;
        -            ManagementError managementError = null;
        -            HttpResponse errorResponse = null;
        -            PollResult.Error lroError = response.getValue().getError();
        -            if (lroError != null) {
        -                errorResponse = new HttpResponseImpl(lroError.getResponseStatusCode(), lroError.getResponseHeaders(),
        -                    lroError.getResponseBody());
        -
        -                errorMessage = response.getValue().getError().getMessage();
        -                String errorBody = response.getValue().getError().getResponseBody();
        -                if (errorBody != null) {
        -                    // try to deserialize error body to ManagementError
        -                    try {
        -                        managementError = this.getSerializerAdapter()
        -                            .deserialize(errorBody, ManagementError.class, SerializerEncoding.JSON);
        -                        if (managementError.getCode() == null || managementError.getMessage() == null) {
        -                            managementError = null;
        -                        }
        -                    } catch (IOException | RuntimeException ioe) {
        -                        LOGGER.logThrowableAsWarning(ioe);
        -                    }
        -                }
        -            } else {
        -                // fallback to default error message
        -                errorMessage = "Long running operation failed.";
        -            }
        -            if (managementError == null) {
        -                // fallback to default ManagementError
        -                managementError = new ManagementError(response.getStatus().toString(), errorMessage);
        -            }
        -            return Mono.error(new ManagementException(errorMessage, errorResponse, managementError));
        -        } else {
        -            return response.getFinalResult();
        -        }
        -    }
        -
        -    private static final class HttpResponseImpl extends HttpResponse {
        -        private final int statusCode;
        -
        -        private final byte[] responseBody;
        -
        -        private final HttpHeaders httpHeaders;
        -
        -        HttpResponseImpl(int statusCode, HttpHeaders httpHeaders, String responseBody) {
        -            super(null);
        -            this.statusCode = statusCode;
        -            this.httpHeaders = httpHeaders;
        -            this.responseBody = responseBody == null ? null : responseBody.getBytes(StandardCharsets.UTF_8);
        -        }
        -
        -        public int getStatusCode() {
        -            return statusCode;
        -        }
        -
        -        public String getHeaderValue(String s) {
        -            return httpHeaders.getValue(HttpHeaderName.fromString(s));
        -        }
        -
        -        public HttpHeaders getHeaders() {
        -            return httpHeaders;
        -        }
        -
        -        public Flux getBody() {
        -            return Flux.just(ByteBuffer.wrap(responseBody));
        -        }
        -
        -        public Mono getBodyAsByteArray() {
        -            return Mono.just(responseBody);
        -        }
        -
        -        public Mono getBodyAsString() {
        -            return Mono.just(new String(responseBody, StandardCharsets.UTF_8));
        -        }
        -
        -        public Mono getBodyAsString(Charset charset) {
        -            return Mono.just(new String(responseBody, charset));
        -        }
        -    }
        -
        -    private static final ClientLogger LOGGER = new ClientLogger(ComputeScheduleClientImpl.class);
        -}
        diff --git a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/implementation/ComputeScheduleMgmtClientBuilder.java b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/implementation/ComputeScheduleMgmtClientBuilder.java
        new file mode 100644
        index 000000000000..b57c5a1812d5
        --- /dev/null
        +++ b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/implementation/ComputeScheduleMgmtClientBuilder.java
        @@ -0,0 +1,138 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) TypeSpec Code Generator.
        +
        +package com.azure.resourcemanager.computeschedule.implementation;
        +
        +import com.azure.core.annotation.ServiceClientBuilder;
        +import com.azure.core.http.HttpPipeline;
        +import com.azure.core.http.HttpPipelineBuilder;
        +import com.azure.core.http.policy.RetryPolicy;
        +import com.azure.core.http.policy.UserAgentPolicy;
        +import com.azure.core.management.AzureEnvironment;
        +import com.azure.core.management.serializer.SerializerFactory;
        +import com.azure.core.util.serializer.SerializerAdapter;
        +import java.time.Duration;
        +
        +/**
        + * A builder for creating a new instance of the ComputeScheduleMgmtClientImpl type.
        + */
        +@ServiceClientBuilder(serviceClients = { ComputeScheduleMgmtClientImpl.class })
        +public final class ComputeScheduleMgmtClientBuilder {
        +    /*
        +     * Service host
        +     */
        +    private String endpoint;
        +
        +    /**
        +     * Sets Service host.
        +     * 
        +     * @param endpoint the endpoint value.
        +     * @return the ComputeScheduleMgmtClientBuilder.
        +     */
        +    public ComputeScheduleMgmtClientBuilder endpoint(String endpoint) {
        +        this.endpoint = endpoint;
        +        return this;
        +    }
        +
        +    /*
        +     * The ID of the target subscription. The value must be an UUID.
        +     */
        +    private String subscriptionId;
        +
        +    /**
        +     * Sets The ID of the target subscription. The value must be an UUID.
        +     * 
        +     * @param subscriptionId the subscriptionId value.
        +     * @return the ComputeScheduleMgmtClientBuilder.
        +     */
        +    public ComputeScheduleMgmtClientBuilder subscriptionId(String subscriptionId) {
        +        this.subscriptionId = subscriptionId;
        +        return this;
        +    }
        +
        +    /*
        +     * The environment to connect to
        +     */
        +    private AzureEnvironment environment;
        +
        +    /**
        +     * Sets The environment to connect to.
        +     * 
        +     * @param environment the environment value.
        +     * @return the ComputeScheduleMgmtClientBuilder.
        +     */
        +    public ComputeScheduleMgmtClientBuilder environment(AzureEnvironment environment) {
        +        this.environment = environment;
        +        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 ComputeScheduleMgmtClientBuilder.
        +     */
        +    public ComputeScheduleMgmtClientBuilder pipeline(HttpPipeline pipeline) {
        +        this.pipeline = pipeline;
        +        return this;
        +    }
        +
        +    /*
        +     * The default poll interval for long-running operation
        +     */
        +    private Duration defaultPollInterval;
        +
        +    /**
        +     * Sets The default poll interval for long-running operation.
        +     * 
        +     * @param defaultPollInterval the defaultPollInterval value.
        +     * @return the ComputeScheduleMgmtClientBuilder.
        +     */
        +    public ComputeScheduleMgmtClientBuilder defaultPollInterval(Duration defaultPollInterval) {
        +        this.defaultPollInterval = defaultPollInterval;
        +        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 ComputeScheduleMgmtClientBuilder.
        +     */
        +    public ComputeScheduleMgmtClientBuilder serializerAdapter(SerializerAdapter serializerAdapter) {
        +        this.serializerAdapter = serializerAdapter;
        +        return this;
        +    }
        +
        +    /**
        +     * Builds an instance of ComputeScheduleMgmtClientImpl with the provided parameters.
        +     * 
        +     * @return an instance of ComputeScheduleMgmtClientImpl.
        +     */
        +    public ComputeScheduleMgmtClientImpl buildClient() {
        +        String localEndpoint = (endpoint != null) ? endpoint : "https://management.azure.com";
        +        AzureEnvironment localEnvironment = (environment != null) ? environment : AzureEnvironment.AZURE;
        +        HttpPipeline localPipeline = (pipeline != null)
        +            ? pipeline
        +            : new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build();
        +        Duration localDefaultPollInterval
        +            = (defaultPollInterval != null) ? defaultPollInterval : Duration.ofSeconds(30);
        +        SerializerAdapter localSerializerAdapter = (serializerAdapter != null)
        +            ? serializerAdapter
        +            : SerializerFactory.createDefaultManagementSerializerAdapter();
        +        ComputeScheduleMgmtClientImpl client = new ComputeScheduleMgmtClientImpl(localPipeline, localSerializerAdapter,
        +            localDefaultPollInterval, localEnvironment, localEndpoint, this.subscriptionId);
        +        return client;
        +    }
        +}
        diff --git a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/implementation/ComputeScheduleMgmtClientImpl.java b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/implementation/ComputeScheduleMgmtClientImpl.java
        new file mode 100644
        index 000000000000..ad546852c1fc
        --- /dev/null
        +++ b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/implementation/ComputeScheduleMgmtClientImpl.java
        @@ -0,0 +1,304 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) TypeSpec Code Generator.
        +
        +package com.azure.resourcemanager.computeschedule.implementation;
        +
        +import com.azure.core.annotation.ServiceClient;
        +import com.azure.core.http.HttpHeaderName;
        +import com.azure.core.http.HttpHeaders;
        +import com.azure.core.http.HttpPipeline;
        +import com.azure.core.http.HttpResponse;
        +import com.azure.core.http.rest.Response;
        +import com.azure.core.management.AzureEnvironment;
        +import com.azure.core.management.exception.ManagementError;
        +import com.azure.core.management.exception.ManagementException;
        +import com.azure.core.management.polling.PollResult;
        +import com.azure.core.management.polling.PollerFactory;
        +import com.azure.core.util.Context;
        +import com.azure.core.util.CoreUtils;
        +import com.azure.core.util.logging.ClientLogger;
        +import com.azure.core.util.polling.AsyncPollResponse;
        +import com.azure.core.util.polling.LongRunningOperationStatus;
        +import com.azure.core.util.polling.PollerFlux;
        +import com.azure.core.util.serializer.SerializerAdapter;
        +import com.azure.core.util.serializer.SerializerEncoding;
        +import com.azure.resourcemanager.computeschedule.fluent.ComputeScheduleMgmtClient;
        +import com.azure.resourcemanager.computeschedule.fluent.OperationsClient;
        +import com.azure.resourcemanager.computeschedule.fluent.ScheduledActionsClient;
        +import java.io.IOException;
        +import java.lang.reflect.Type;
        +import java.nio.ByteBuffer;
        +import java.nio.charset.Charset;
        +import java.nio.charset.StandardCharsets;
        +import java.time.Duration;
        +import reactor.core.publisher.Flux;
        +import reactor.core.publisher.Mono;
        +
        +/**
        + * Initializes a new instance of the ComputeScheduleMgmtClientImpl type.
        + */
        +@ServiceClient(builder = ComputeScheduleMgmtClientBuilder.class)
        +public final class ComputeScheduleMgmtClientImpl implements ComputeScheduleMgmtClient {
        +    /**
        +     * Service host.
        +     */
        +    private final String endpoint;
        +
        +    /**
        +     * Gets Service host.
        +     * 
        +     * @return the endpoint value.
        +     */
        +    public String getEndpoint() {
        +        return this.endpoint;
        +    }
        +
        +    /**
        +     * Version parameter.
        +     */
        +    private final String apiVersion;
        +
        +    /**
        +     * Gets Version parameter.
        +     * 
        +     * @return the apiVersion value.
        +     */
        +    public String getApiVersion() {
        +        return this.apiVersion;
        +    }
        +
        +    /**
        +     * The ID of the target subscription. The value must be an UUID.
        +     */
        +    private final String subscriptionId;
        +
        +    /**
        +     * Gets The ID of the target subscription. The value must be an UUID.
        +     * 
        +     * @return the subscriptionId value.
        +     */
        +    public String getSubscriptionId() {
        +        return this.subscriptionId;
        +    }
        +
        +    /**
        +     * 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.
        +     */
        +    SerializerAdapter getSerializerAdapter() {
        +        return this.serializerAdapter;
        +    }
        +
        +    /**
        +     * The default poll interval for long-running operation.
        +     */
        +    private final Duration defaultPollInterval;
        +
        +    /**
        +     * Gets The default poll interval for long-running operation.
        +     * 
        +     * @return the defaultPollInterval value.
        +     */
        +    public Duration getDefaultPollInterval() {
        +        return this.defaultPollInterval;
        +    }
        +
        +    /**
        +     * The OperationsClient object to access its operations.
        +     */
        +    private final OperationsClient operations;
        +
        +    /**
        +     * Gets the OperationsClient object to access its operations.
        +     * 
        +     * @return the OperationsClient object.
        +     */
        +    public OperationsClient getOperations() {
        +        return this.operations;
        +    }
        +
        +    /**
        +     * The ScheduledActionsClient object to access its operations.
        +     */
        +    private final ScheduledActionsClient scheduledActions;
        +
        +    /**
        +     * Gets the ScheduledActionsClient object to access its operations.
        +     * 
        +     * @return the ScheduledActionsClient object.
        +     */
        +    public ScheduledActionsClient getScheduledActions() {
        +        return this.scheduledActions;
        +    }
        +
        +    /**
        +     * Initializes an instance of ComputeScheduleMgmtClient client.
        +     * 
        +     * @param httpPipeline The HTTP pipeline to send requests through.
        +     * @param serializerAdapter The serializer to serialize an object into a string.
        +     * @param defaultPollInterval The default poll interval for long-running operation.
        +     * @param environment The Azure environment.
        +     * @param endpoint Service host.
        +     * @param subscriptionId The ID of the target subscription. The value must be an UUID.
        +     */
        +    ComputeScheduleMgmtClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter,
        +        Duration defaultPollInterval, AzureEnvironment environment, String endpoint, String subscriptionId) {
        +        this.httpPipeline = httpPipeline;
        +        this.serializerAdapter = serializerAdapter;
        +        this.defaultPollInterval = defaultPollInterval;
        +        this.endpoint = endpoint;
        +        this.subscriptionId = subscriptionId;
        +        this.apiVersion = "2024-10-01";
        +        this.operations = new OperationsClientImpl(this);
        +        this.scheduledActions = new ScheduledActionsClientImpl(this);
        +    }
        +
        +    /**
        +     * Gets default client context.
        +     * 
        +     * @return the default client context.
        +     */
        +    public Context getContext() {
        +        return Context.NONE;
        +    }
        +
        +    /**
        +     * Merges default client context with provided context.
        +     * 
        +     * @param context the context to be merged with default client context.
        +     * @return the merged context.
        +     */
        +    public Context mergeContext(Context context) {
        +        return CoreUtils.mergeContexts(this.getContext(), context);
        +    }
        +
        +    /**
        +     * Gets long running operation result.
        +     * 
        +     * @param activationResponse the response of activation operation.
        +     * @param httpPipeline the http pipeline.
        +     * @param pollResultType type of poll result.
        +     * @param finalResultType type of final result.
        +     * @param context the context shared by all requests.
        +     * @param  type of poll result.
        +     * @param  type of final result.
        +     * @return poller flux for poll result and final result.
        +     */
        +    public  PollerFlux, U> getLroResult(Mono>> activationResponse,
        +        HttpPipeline httpPipeline, Type pollResultType, Type finalResultType, Context context) {
        +        return PollerFactory.create(serializerAdapter, httpPipeline, pollResultType, finalResultType,
        +            defaultPollInterval, activationResponse, context);
        +    }
        +
        +    /**
        +     * Gets the final result, or an error, based on last async poll response.
        +     * 
        +     * @param response the last async poll response.
        +     * @param  type of poll result.
        +     * @param  type of final result.
        +     * @return the final result, or an error.
        +     */
        +    public  Mono getLroFinalResultOrError(AsyncPollResponse, U> response) {
        +        if (response.getStatus() != LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) {
        +            String errorMessage;
        +            ManagementError managementError = null;
        +            HttpResponse errorResponse = null;
        +            PollResult.Error lroError = response.getValue().getError();
        +            if (lroError != null) {
        +                errorResponse = new HttpResponseImpl(lroError.getResponseStatusCode(), lroError.getResponseHeaders(),
        +                    lroError.getResponseBody());
        +
        +                errorMessage = response.getValue().getError().getMessage();
        +                String errorBody = response.getValue().getError().getResponseBody();
        +                if (errorBody != null) {
        +                    // try to deserialize error body to ManagementError
        +                    try {
        +                        managementError = this.getSerializerAdapter()
        +                            .deserialize(errorBody, ManagementError.class, SerializerEncoding.JSON);
        +                        if (managementError.getCode() == null || managementError.getMessage() == null) {
        +                            managementError = null;
        +                        }
        +                    } catch (IOException | RuntimeException ioe) {
        +                        LOGGER.logThrowableAsWarning(ioe);
        +                    }
        +                }
        +            } else {
        +                // fallback to default error message
        +                errorMessage = "Long running operation failed.";
        +            }
        +            if (managementError == null) {
        +                // fallback to default ManagementError
        +                managementError = new ManagementError(response.getStatus().toString(), errorMessage);
        +            }
        +            return Mono.error(new ManagementException(errorMessage, errorResponse, managementError));
        +        } else {
        +            return response.getFinalResult();
        +        }
        +    }
        +
        +    private static final class HttpResponseImpl extends HttpResponse {
        +        private final int statusCode;
        +
        +        private final byte[] responseBody;
        +
        +        private final HttpHeaders httpHeaders;
        +
        +        HttpResponseImpl(int statusCode, HttpHeaders httpHeaders, String responseBody) {
        +            super(null);
        +            this.statusCode = statusCode;
        +            this.httpHeaders = httpHeaders;
        +            this.responseBody = responseBody == null ? null : responseBody.getBytes(StandardCharsets.UTF_8);
        +        }
        +
        +        public int getStatusCode() {
        +            return statusCode;
        +        }
        +
        +        public String getHeaderValue(String s) {
        +            return httpHeaders.getValue(HttpHeaderName.fromString(s));
        +        }
        +
        +        public HttpHeaders getHeaders() {
        +            return httpHeaders;
        +        }
        +
        +        public Flux getBody() {
        +            return Flux.just(ByteBuffer.wrap(responseBody));
        +        }
        +
        +        public Mono getBodyAsByteArray() {
        +            return Mono.just(responseBody);
        +        }
        +
        +        public Mono getBodyAsString() {
        +            return Mono.just(new String(responseBody, StandardCharsets.UTF_8));
        +        }
        +
        +        public Mono getBodyAsString(Charset charset) {
        +            return Mono.just(new String(responseBody, charset));
        +        }
        +    }
        +
        +    private static final ClientLogger LOGGER = new ClientLogger(ComputeScheduleMgmtClientImpl.class);
        +}
        diff --git a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/implementation/OperationsClientImpl.java b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/implementation/OperationsClientImpl.java
        index 66a9c4c4f30e..682079658101 100644
        --- a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/implementation/OperationsClientImpl.java
        +++ b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/implementation/OperationsClientImpl.java
        @@ -42,25 +42,25 @@ public final class OperationsClientImpl implements OperationsClient {
             /**
              * The service client containing this operation class.
              */
        -    private final ComputeScheduleClientImpl client;
        +    private final ComputeScheduleMgmtClientImpl client;
         
             /**
              * Initializes an instance of OperationsClientImpl.
              * 
              * @param client the instance of the service client containing this operation class.
              */
        -    OperationsClientImpl(ComputeScheduleClientImpl client) {
        +    OperationsClientImpl(ComputeScheduleMgmtClientImpl client) {
                 this.service
                     = RestProxy.create(OperationsService.class, client.getHttpPipeline(), client.getSerializerAdapter());
                 this.client = client;
             }
         
             /**
        -     * The interface defining all the services for ComputeScheduleClientOperations to be used by the proxy service to
        -     * perform REST calls.
        +     * The interface defining all the services for ComputeScheduleMgmtClientOperations to be used by the proxy service
        +     * to perform REST calls.
              */
             @Host("{endpoint}")
        -    @ServiceInterface(name = "ComputeScheduleClien")
        +    @ServiceInterface(name = "ComputeScheduleMgmtC")
             public interface OperationsService {
                 @Headers({ "Content-Type: application/json" })
                 @Get("/providers/Microsoft.ComputeSchedule/operations")
        diff --git a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/implementation/ScheduledActionsClientImpl.java b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/implementation/ScheduledActionsClientImpl.java
        index 37c4ee2f7678..8f0038fa7f2e 100644
        --- a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/implementation/ScheduledActionsClientImpl.java
        +++ b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/implementation/ScheduledActionsClientImpl.java
        @@ -51,25 +51,25 @@ public final class ScheduledActionsClientImpl implements ScheduledActionsClient
             /**
              * The service client containing this operation class.
              */
        -    private final ComputeScheduleClientImpl client;
        +    private final ComputeScheduleMgmtClientImpl client;
         
             /**
              * Initializes an instance of ScheduledActionsClientImpl.
              * 
              * @param client the instance of the service client containing this operation class.
              */
        -    ScheduledActionsClientImpl(ComputeScheduleClientImpl client) {
        +    ScheduledActionsClientImpl(ComputeScheduleMgmtClientImpl client) {
                 this.service
                     = RestProxy.create(ScheduledActionsService.class, client.getHttpPipeline(), client.getSerializerAdapter());
                 this.client = client;
             }
         
             /**
        -     * The interface defining all the services for ComputeScheduleClientScheduledActions to be used by the proxy service
        -     * to perform REST calls.
        +     * The interface defining all the services for ComputeScheduleMgmtClientScheduledActions to be used by the proxy
        +     * service to perform REST calls.
              */
             @Host("{endpoint}")
        -    @ServiceInterface(name = "ComputeScheduleClien")
        +    @ServiceInterface(name = "ComputeScheduleMgmtC")
             public interface ScheduledActionsService {
                 @Post("/subscriptions/{subscriptionId}/providers/Microsoft.ComputeSchedule/locations/{locationparameter}/virtualMachinesSubmitDeallocate")
                 @ExpectedResponses({ 200 })
        @@ -163,7 +163,8 @@ Mono> virtualMachinesGetOperationError
             }
         
             /**
        -     * virtualMachinesSubmitDeallocate: submitDeallocate for a virtual machine.
        +     * VirtualMachinesSubmitDeallocate: Schedule deallocate operation for a batch of virtual machines at datetime in
        +     * future.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -203,7 +204,8 @@ private Mono> virtualMachines
             }
         
             /**
        -     * virtualMachinesSubmitDeallocate: submitDeallocate for a virtual machine.
        +     * VirtualMachinesSubmitDeallocate: Schedule deallocate operation for a batch of virtual machines at datetime in
        +     * future.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -242,7 +244,8 @@ private Mono> virtualMachines
             }
         
             /**
        -     * virtualMachinesSubmitDeallocate: submitDeallocate for a virtual machine.
        +     * VirtualMachinesSubmitDeallocate: Schedule deallocate operation for a batch of virtual machines at datetime in
        +     * future.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -259,7 +262,8 @@ private Mono> virtualMachines
             }
         
             /**
        -     * virtualMachinesSubmitDeallocate: submitDeallocate for a virtual machine.
        +     * VirtualMachinesSubmitDeallocate: Schedule deallocate operation for a batch of virtual machines at datetime in
        +     * future.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -276,7 +280,8 @@ public Response virtualMachinesSubmitD
             }
         
             /**
        -     * virtualMachinesSubmitDeallocate: submitDeallocate for a virtual machine.
        +     * VirtualMachinesSubmitDeallocate: Schedule deallocate operation for a batch of virtual machines at datetime in
        +     * future.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -292,7 +297,8 @@ public DeallocateResourceOperationResponseInner virtualMachinesSubmitDeallocate(
             }
         
             /**
        -     * virtualMachinesSubmitHibernate: submitHibernate for a virtual machine.
        +     * VirtualMachinesSubmitHibernate: Schedule hibernate operation for a batch of virtual machines at datetime in
        +     * future.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -332,7 +338,8 @@ public DeallocateResourceOperationResponseInner virtualMachinesSubmitDeallocate(
             }
         
             /**
        -     * virtualMachinesSubmitHibernate: submitHibernate for a virtual machine.
        +     * VirtualMachinesSubmitHibernate: Schedule hibernate operation for a batch of virtual machines at datetime in
        +     * future.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -371,7 +378,8 @@ private Mono> virtualMachinesS
             }
         
             /**
        -     * virtualMachinesSubmitHibernate: submitHibernate for a virtual machine.
        +     * VirtualMachinesSubmitHibernate: Schedule hibernate operation for a batch of virtual machines at datetime in
        +     * future.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -388,7 +396,8 @@ private Mono virtualMachinesSubmitHiber
             }
         
             /**
        -     * virtualMachinesSubmitHibernate: submitHibernate for a virtual machine.
        +     * VirtualMachinesSubmitHibernate: Schedule hibernate operation for a batch of virtual machines at datetime in
        +     * future.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -405,7 +414,8 @@ public Response virtualMachinesSubmitHi
             }
         
             /**
        -     * virtualMachinesSubmitHibernate: submitHibernate for a virtual machine.
        +     * VirtualMachinesSubmitHibernate: Schedule hibernate operation for a batch of virtual machines at datetime in
        +     * future.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -421,7 +431,7 @@ public HibernateResourceOperationResponseInner virtualMachinesSubmitHibernate(St
             }
         
             /**
        -     * virtualMachinesSubmitStart: submitStart for a virtual machine.
        +     * VirtualMachinesSubmitStart: Schedule start operation for a batch of virtual machines at datetime in future.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -460,7 +470,7 @@ public HibernateResourceOperationResponseInner virtualMachinesSubmitHibernate(St
             }
         
             /**
        -     * virtualMachinesSubmitStart: submitStart for a virtual machine.
        +     * VirtualMachinesSubmitStart: Schedule start operation for a batch of virtual machines at datetime in future.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -498,7 +508,7 @@ private Mono> virtualMachinesSubmi
             }
         
             /**
        -     * virtualMachinesSubmitStart: submitStart for a virtual machine.
        +     * VirtualMachinesSubmitStart: Schedule start operation for a batch of virtual machines at datetime in future.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -515,7 +525,7 @@ private Mono virtualMachinesSubmitStartAsyn
             }
         
             /**
        -     * virtualMachinesSubmitStart: submitStart for a virtual machine.
        +     * VirtualMachinesSubmitStart: Schedule start operation for a batch of virtual machines at datetime in future.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -532,7 +542,7 @@ public Response virtualMachinesSubmitStartW
             }
         
             /**
        -     * virtualMachinesSubmitStart: submitStart for a virtual machine.
        +     * VirtualMachinesSubmitStart: Schedule start operation for a batch of virtual machines at datetime in future.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -548,7 +558,8 @@ public StartResourceOperationResponseInner virtualMachinesSubmitStart(String loc
             }
         
             /**
        -     * virtualMachinesExecuteDeallocate: executeDeallocate for a virtual machine.
        +     * VirtualMachinesExecuteDeallocate: Execute deallocate operation for a batch of virtual machines, this operation is
        +     * triggered as soon as Computeschedule receives it.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -588,7 +599,8 @@ private Mono> virtualMachines
             }
         
             /**
        -     * virtualMachinesExecuteDeallocate: executeDeallocate for a virtual machine.
        +     * VirtualMachinesExecuteDeallocate: Execute deallocate operation for a batch of virtual machines, this operation is
        +     * triggered as soon as Computeschedule receives it.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -627,7 +639,8 @@ private Mono> virtualMachines
             }
         
             /**
        -     * virtualMachinesExecuteDeallocate: executeDeallocate for a virtual machine.
        +     * VirtualMachinesExecuteDeallocate: Execute deallocate operation for a batch of virtual machines, this operation is
        +     * triggered as soon as Computeschedule receives it.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -644,7 +657,8 @@ private Mono> virtualMachines
             }
         
             /**
        -     * virtualMachinesExecuteDeallocate: executeDeallocate for a virtual machine.
        +     * VirtualMachinesExecuteDeallocate: Execute deallocate operation for a batch of virtual machines, this operation is
        +     * triggered as soon as Computeschedule receives it.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -661,7 +675,8 @@ public Response virtualMachinesExecute
             }
         
             /**
        -     * virtualMachinesExecuteDeallocate: executeDeallocate for a virtual machine.
        +     * VirtualMachinesExecuteDeallocate: Execute deallocate operation for a batch of virtual machines, this operation is
        +     * triggered as soon as Computeschedule receives it.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -677,7 +692,8 @@ public DeallocateResourceOperationResponseInner virtualMachinesExecuteDeallocate
             }
         
             /**
        -     * virtualMachinesExecuteHibernate: executeHibernate for a virtual machine.
        +     * VirtualMachinesExecuteHibernate: Execute hibernate operation for a batch of virtual machines, this operation is
        +     * triggered as soon as Computeschedule receives it.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -717,7 +733,8 @@ private Mono> virtualMachinesE
             }
         
             /**
        -     * virtualMachinesExecuteHibernate: executeHibernate for a virtual machine.
        +     * VirtualMachinesExecuteHibernate: Execute hibernate operation for a batch of virtual machines, this operation is
        +     * triggered as soon as Computeschedule receives it.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -756,7 +773,8 @@ private Mono> virtualMachinesE
             }
         
             /**
        -     * virtualMachinesExecuteHibernate: executeHibernate for a virtual machine.
        +     * VirtualMachinesExecuteHibernate: Execute hibernate operation for a batch of virtual machines, this operation is
        +     * triggered as soon as Computeschedule receives it.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -773,7 +791,8 @@ private Mono virtualMachinesExecuteHibe
             }
         
             /**
        -     * virtualMachinesExecuteHibernate: executeHibernate for a virtual machine.
        +     * VirtualMachinesExecuteHibernate: Execute hibernate operation for a batch of virtual machines, this operation is
        +     * triggered as soon as Computeschedule receives it.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -790,7 +809,8 @@ public Response virtualMachinesExecuteH
             }
         
             /**
        -     * virtualMachinesExecuteHibernate: executeHibernate for a virtual machine.
        +     * VirtualMachinesExecuteHibernate: Execute hibernate operation for a batch of virtual machines, this operation is
        +     * triggered as soon as Computeschedule receives it.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -806,7 +826,8 @@ public HibernateResourceOperationResponseInner virtualMachinesExecuteHibernate(S
             }
         
             /**
        -     * virtualMachinesExecuteStart: executeStart for a virtual machine.
        +     * VirtualMachinesExecuteStart: Execute start operation for a batch of virtual machines, this operation is triggered
        +     * as soon as Computeschedule receives it.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -845,7 +866,8 @@ public HibernateResourceOperationResponseInner virtualMachinesExecuteHibernate(S
             }
         
             /**
        -     * virtualMachinesExecuteStart: executeStart for a virtual machine.
        +     * VirtualMachinesExecuteStart: Execute start operation for a batch of virtual machines, this operation is triggered
        +     * as soon as Computeschedule receives it.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -883,7 +905,8 @@ private Mono> virtualMachinesExecu
             }
         
             /**
        -     * virtualMachinesExecuteStart: executeStart for a virtual machine.
        +     * VirtualMachinesExecuteStart: Execute start operation for a batch of virtual machines, this operation is triggered
        +     * as soon as Computeschedule receives it.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -900,7 +923,8 @@ private Mono virtualMachinesExecuteStartAsy
             }
         
             /**
        -     * virtualMachinesExecuteStart: executeStart for a virtual machine.
        +     * VirtualMachinesExecuteStart: Execute start operation for a batch of virtual machines, this operation is triggered
        +     * as soon as Computeschedule receives it.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -917,7 +941,8 @@ public Response virtualMachinesExecuteStart
             }
         
             /**
        -     * virtualMachinesExecuteStart: executeStart for a virtual machine.
        +     * VirtualMachinesExecuteStart: Execute start operation for a batch of virtual machines, this operation is triggered
        +     * as soon as Computeschedule receives it.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -933,7 +958,7 @@ public StartResourceOperationResponseInner virtualMachinesExecuteStart(String lo
             }
         
             /**
        -     * virtualMachinesGetOperationStatus: getOperationStatus for a virtual machine.
        +     * VirtualMachinesGetOperationStatus: Polling endpoint to read status of operations performed on virtual machines.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -973,7 +998,7 @@ private Mono> virtualMachinesGetOperat
             }
         
             /**
        -     * virtualMachinesGetOperationStatus: getOperationStatus for a virtual machine.
        +     * VirtualMachinesGetOperationStatus: Polling endpoint to read status of operations performed on virtual machines.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -1012,7 +1037,7 @@ private Mono> virtualMachinesGetOperat
             }
         
             /**
        -     * virtualMachinesGetOperationStatus: getOperationStatus for a virtual machine.
        +     * VirtualMachinesGetOperationStatus: Polling endpoint to read status of operations performed on virtual machines.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -1029,7 +1054,7 @@ private Mono virtualMachinesGetOperationStatusA
             }
         
             /**
        -     * virtualMachinesGetOperationStatus: getOperationStatus for a virtual machine.
        +     * VirtualMachinesGetOperationStatus: Polling endpoint to read status of operations performed on virtual machines.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -1046,7 +1071,7 @@ public Response virtualMachinesGetOperationStat
             }
         
             /**
        -     * virtualMachinesGetOperationStatus: getOperationStatus for a virtual machine.
        +     * VirtualMachinesGetOperationStatus: Polling endpoint to read status of operations performed on virtual machines.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -1062,7 +1087,7 @@ public GetOperationStatusResponseInner virtualMachinesGetOperationStatus(String
             }
         
             /**
        -     * virtualMachinesCancelOperations: cancelOperations for a virtual machine.
        +     * VirtualMachinesCancelOperations: Cancel a previously submitted (start/deallocate/hibernate) request.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -1102,7 +1127,7 @@ private Mono> virtualMachinesCancelOpera
             }
         
             /**
        -     * virtualMachinesCancelOperations: cancelOperations for a virtual machine.
        +     * VirtualMachinesCancelOperations: Cancel a previously submitted (start/deallocate/hibernate) request.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -1141,7 +1166,7 @@ private Mono> virtualMachinesCancelOpera
             }
         
             /**
        -     * virtualMachinesCancelOperations: cancelOperations for a virtual machine.
        +     * VirtualMachinesCancelOperations: Cancel a previously submitted (start/deallocate/hibernate) request.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -1158,7 +1183,7 @@ private Mono virtualMachinesCancelOperationsAsync
             }
         
             /**
        -     * virtualMachinesCancelOperations: cancelOperations for a virtual machine.
        +     * VirtualMachinesCancelOperations: Cancel a previously submitted (start/deallocate/hibernate) request.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -1175,7 +1200,7 @@ public Response virtualMachinesCancelOperationsWi
             }
         
             /**
        -     * virtualMachinesCancelOperations: cancelOperations for a virtual machine.
        +     * VirtualMachinesCancelOperations: Cancel a previously submitted (start/deallocate/hibernate) request.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -1191,7 +1216,8 @@ public CancelOperationsResponseInner virtualMachinesCancelOperations(String loca
             }
         
             /**
        -     * virtualMachinesGetOperationErrors: getOperationErrors associated with an operation on a virtual machine.
        +     * VirtualMachinesGetOperationErrors: Get error details on operation errors (like transient errors encountered,
        +     * additional logs) if they exist.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -1231,7 +1257,8 @@ private Mono> virtualMachinesGetOperat
             }
         
             /**
        -     * virtualMachinesGetOperationErrors: getOperationErrors associated with an operation on a virtual machine.
        +     * VirtualMachinesGetOperationErrors: Get error details on operation errors (like transient errors encountered,
        +     * additional logs) if they exist.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -1270,7 +1297,8 @@ private Mono> virtualMachinesGetOperat
             }
         
             /**
        -     * virtualMachinesGetOperationErrors: getOperationErrors associated with an operation on a virtual machine.
        +     * VirtualMachinesGetOperationErrors: Get error details on operation errors (like transient errors encountered,
        +     * additional logs) if they exist.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -1287,7 +1315,8 @@ private Mono virtualMachinesGetOperationErrorsA
             }
         
             /**
        -     * virtualMachinesGetOperationErrors: getOperationErrors associated with an operation on a virtual machine.
        +     * VirtualMachinesGetOperationErrors: Get error details on operation errors (like transient errors encountered,
        +     * additional logs) if they exist.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -1304,7 +1333,8 @@ public Response virtualMachinesGetOperationErro
             }
         
             /**
        -     * virtualMachinesGetOperationErrors: getOperationErrors associated with an operation on a virtual machine.
        +     * VirtualMachinesGetOperationErrors: Get error details on operation errors (like transient errors encountered,
        +     * additional logs) if they exist.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        diff --git a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/models/CancelOperationsRequest.java b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/models/CancelOperationsRequest.java
        index 1c900af06a0d..c06204cf8375 100644
        --- a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/models/CancelOperationsRequest.java
        +++ b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/models/CancelOperationsRequest.java
        @@ -24,7 +24,7 @@ public final class CancelOperationsRequest implements JsonSerializable operationIds;
         
             /*
        -     * Correlationid item
        +     * CorrelationId item
              */
             private String correlationid;
         
        @@ -55,7 +55,7 @@ public CancelOperationsRequest withOperationIds(List operationIds) {
             }
         
             /**
        -     * Get the correlationid property: Correlationid item.
        +     * Get the correlationid property: CorrelationId item.
              * 
              * @return the correlationid value.
              */
        @@ -64,7 +64,7 @@ public String correlationid() {
             }
         
             /**
        -     * Set the correlationid property: Correlationid item.
        +     * Set the correlationid property: CorrelationId item.
              * 
              * @param correlationid the correlationid value to set.
              * @return the CancelOperationsRequest object itself.
        diff --git a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/models/ExecuteDeallocateRequest.java b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/models/ExecuteDeallocateRequest.java
        index 8f90faf2f07f..43941ca73e6f 100644
        --- a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/models/ExecuteDeallocateRequest.java
        +++ b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/models/ExecuteDeallocateRequest.java
        @@ -28,7 +28,7 @@ public final class ExecuteDeallocateRequest implements JsonSerializable operationIds;
         
             /*
        -     * Correlationid item
        +     * CorrelationId item
              */
             private String correlationid;
         
        @@ -55,7 +55,7 @@ public GetOperationStatusRequest withOperationIds(List operationIds) {
             }
         
             /**
        -     * Get the correlationid property: Correlationid item.
        +     * Get the correlationid property: CorrelationId item.
              * 
              * @return the correlationid value.
              */
        @@ -64,7 +64,7 @@ public String correlationid() {
             }
         
             /**
        -     * Set the correlationid property: Correlationid item.
        +     * Set the correlationid property: CorrelationId item.
              * 
              * @param correlationid the correlationid value to set.
              * @return the GetOperationStatusRequest object itself.
        diff --git a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/models/OperationErrorDetails.java b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/models/OperationErrorDetails.java
        index 32260c6692bb..de568ea3f9b2 100644
        --- a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/models/OperationErrorDetails.java
        +++ b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/models/OperationErrorDetails.java
        @@ -28,7 +28,12 @@ public final class OperationErrorDetails implements JsonSerializable CoreUtils.parseBestOffsetDateTime(nonNullReader.getString()));
                         } else if ("timeStamp".equals(fieldName)) {
                             deserializedOperationErrorDetails.timeStamp = reader
                                 .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString()));
        +                } else if ("azureOperationName".equals(fieldName)) {
        +                    deserializedOperationErrorDetails.azureOperationName = reader.getString();
                         } else if ("crpOperationId".equals(fieldName)) {
                             deserializedOperationErrorDetails.crpOperationId = reader.getString();
                         } else {
        diff --git a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/models/OperationState.java b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/models/OperationState.java
        index 80cd9c0d6d63..9b3edd43ed46 100644
        --- a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/models/OperationState.java
        +++ b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/models/OperationState.java
        @@ -47,7 +47,7 @@ public final class OperationState extends ExpandableStringEnum {
             public static final OperationState FAILED = fromString("Failed");
         
             /**
        -     * Operations that have been cancelled by the user.
        +     * Operations that have been Cancelled by the user.
              */
             public static final OperationState CANCELLED = fromString("Cancelled");
         
        diff --git a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/models/ResourceOperationDetails.java b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/models/ResourceOperationDetails.java
        index 2ba6652f4015..2a036ccfdbad 100644
        --- a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/models/ResourceOperationDetails.java
        +++ b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/models/ResourceOperationDetails.java
        @@ -55,6 +55,11 @@ public final class ResourceOperationDetails implements JsonSerializable {
        +    /*
        +     * The deadline for the operation
        +     */
        +    private OffsetDateTime deadline;
        +
             /*
              * The deadline for the operation
              */
             private OffsetDateTime deadLine;
         
        +    /*
        +     * The timezone for the operation
        +     */
        +    private String timezone;
        +
             /*
              * The timezone for the operation
              */
        @@ -41,6 +51,26 @@ public final class Schedule implements JsonSerializable {
             public Schedule() {
             }
         
        +    /**
        +     * Get the deadline property: The deadline for the operation.
        +     * 
        +     * @return the deadline value.
        +     */
        +    public OffsetDateTime deadline() {
        +        return this.deadline;
        +    }
        +
        +    /**
        +     * Set the deadline property: The deadline for the operation.
        +     * 
        +     * @param deadline the deadline value to set.
        +     * @return the Schedule object itself.
        +     */
        +    public Schedule withDeadline(OffsetDateTime deadline) {
        +        this.deadline = deadline;
        +        return this;
        +    }
        +
             /**
              * Get the deadLine property: The deadline for the operation.
              * 
        @@ -61,6 +91,26 @@ public Schedule withDeadLine(OffsetDateTime deadLine) {
                 return this;
             }
         
        +    /**
        +     * Get the timezone property: The timezone for the operation.
        +     * 
        +     * @return the timezone value.
        +     */
        +    public String timezone() {
        +        return this.timezone;
        +    }
        +
        +    /**
        +     * Set the timezone property: The timezone for the operation.
        +     * 
        +     * @param timezone the timezone value to set.
        +     * @return the Schedule object itself.
        +     */
        +    public Schedule withTimezone(String timezone) {
        +        this.timezone = timezone;
        +        return this;
        +    }
        +
             /**
              * Get the timeZone property: The timezone for the operation.
              * 
        @@ -107,14 +157,6 @@ public Schedule withDeadlineType(DeadlineType deadlineType) {
              * @throws IllegalArgumentException thrown if the instance is not valid.
              */
             public void validate() {
        -        if (deadLine() == null) {
        -            throw LOGGER.atError()
        -                .log(new IllegalArgumentException("Missing required property deadLine in model Schedule"));
        -        }
        -        if (timeZone() == null) {
        -            throw LOGGER.atError()
        -                .log(new IllegalArgumentException("Missing required property timeZone in model Schedule"));
        -        }
                 if (deadlineType() == null) {
                     throw LOGGER.atError()
                         .log(new IllegalArgumentException("Missing required property deadlineType in model Schedule"));
        @@ -129,10 +171,13 @@ public void validate() {
             @Override
             public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
                 jsonWriter.writeStartObject();
        +        jsonWriter.writeStringField("deadlineType", this.deadlineType == null ? null : this.deadlineType.toString());
        +        jsonWriter.writeStringField("deadline",
        +            this.deadline == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.deadline));
                 jsonWriter.writeStringField("deadLine",
                     this.deadLine == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.deadLine));
        +        jsonWriter.writeStringField("timezone", this.timezone);
                 jsonWriter.writeStringField("timeZone", this.timeZone);
        -        jsonWriter.writeStringField("deadlineType", this.deadlineType == null ? null : this.deadlineType.toString());
                 return jsonWriter.writeEndObject();
             }
         
        @@ -152,13 +197,18 @@ public static Schedule fromJson(JsonReader jsonReader) throws IOException {
                         String fieldName = reader.getFieldName();
                         reader.nextToken();
         
        -                if ("deadLine".equals(fieldName)) {
        +                if ("deadlineType".equals(fieldName)) {
        +                    deserializedSchedule.deadlineType = DeadlineType.fromString(reader.getString());
        +                } else if ("deadline".equals(fieldName)) {
        +                    deserializedSchedule.deadline = reader
        +                        .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString()));
        +                } else if ("deadLine".equals(fieldName)) {
                             deserializedSchedule.deadLine = reader
                                 .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString()));
        +                } else if ("timezone".equals(fieldName)) {
        +                    deserializedSchedule.timezone = reader.getString();
                         } else if ("timeZone".equals(fieldName)) {
                             deserializedSchedule.timeZone = reader.getString();
        -                } else if ("deadlineType".equals(fieldName)) {
        -                    deserializedSchedule.deadlineType = DeadlineType.fromString(reader.getString());
                         } else {
                             reader.skipChildren();
                         }
        diff --git a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/models/ScheduledActions.java b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/models/ScheduledActions.java
        index ac835771e990..f768a804cc5b 100644
        --- a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/models/ScheduledActions.java
        +++ b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/models/ScheduledActions.java
        @@ -12,7 +12,8 @@
          */
         public interface ScheduledActions {
             /**
        -     * virtualMachinesSubmitDeallocate: submitDeallocate for a virtual machine.
        +     * VirtualMachinesSubmitDeallocate: Schedule deallocate operation for a batch of virtual machines at datetime in
        +     * future.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -26,7 +27,8 @@ Response virtualMachinesSubmitDeallocateWit
                 SubmitDeallocateRequest requestBody, Context context);
         
             /**
        -     * virtualMachinesSubmitDeallocate: submitDeallocate for a virtual machine.
        +     * VirtualMachinesSubmitDeallocate: Schedule deallocate operation for a batch of virtual machines at datetime in
        +     * future.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -39,7 +41,8 @@ DeallocateResourceOperationResponse virtualMachinesSubmitDeallocate(String locat
                 SubmitDeallocateRequest requestBody);
         
             /**
        -     * virtualMachinesSubmitHibernate: submitHibernate for a virtual machine.
        +     * VirtualMachinesSubmitHibernate: Schedule hibernate operation for a batch of virtual machines at datetime in
        +     * future.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -53,7 +56,8 @@ Response virtualMachinesSubmitHibernateWithR
                 SubmitHibernateRequest requestBody, Context context);
         
             /**
        -     * virtualMachinesSubmitHibernate: submitHibernate for a virtual machine.
        +     * VirtualMachinesSubmitHibernate: Schedule hibernate operation for a batch of virtual machines at datetime in
        +     * future.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -66,7 +70,7 @@ HibernateResourceOperationResponse virtualMachinesSubmitHibernate(String locatio
                 SubmitHibernateRequest requestBody);
         
             /**
        -     * virtualMachinesSubmitStart: submitStart for a virtual machine.
        +     * VirtualMachinesSubmitStart: Schedule start operation for a batch of virtual machines at datetime in future.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -80,7 +84,7 @@ Response virtualMachinesSubmitStartWithResponse(
                 SubmitStartRequest requestBody, Context context);
         
             /**
        -     * virtualMachinesSubmitStart: submitStart for a virtual machine.
        +     * VirtualMachinesSubmitStart: Schedule start operation for a batch of virtual machines at datetime in future.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -92,7 +96,8 @@ Response virtualMachinesSubmitStartWithResponse(
             StartResourceOperationResponse virtualMachinesSubmitStart(String locationparameter, SubmitStartRequest requestBody);
         
             /**
        -     * virtualMachinesExecuteDeallocate: executeDeallocate for a virtual machine.
        +     * VirtualMachinesExecuteDeallocate: Execute deallocate operation for a batch of virtual machines, this operation is
        +     * triggered as soon as Computeschedule receives it.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -106,7 +111,8 @@ Response virtualMachinesExecuteDeallocateWi
                 ExecuteDeallocateRequest requestBody, Context context);
         
             /**
        -     * virtualMachinesExecuteDeallocate: executeDeallocate for a virtual machine.
        +     * VirtualMachinesExecuteDeallocate: Execute deallocate operation for a batch of virtual machines, this operation is
        +     * triggered as soon as Computeschedule receives it.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -119,7 +125,8 @@ DeallocateResourceOperationResponse virtualMachinesExecuteDeallocate(String loca
                 ExecuteDeallocateRequest requestBody);
         
             /**
        -     * virtualMachinesExecuteHibernate: executeHibernate for a virtual machine.
        +     * VirtualMachinesExecuteHibernate: Execute hibernate operation for a batch of virtual machines, this operation is
        +     * triggered as soon as Computeschedule receives it.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -133,7 +140,8 @@ Response virtualMachinesExecuteHibernateWith
                 ExecuteHibernateRequest requestBody, Context context);
         
             /**
        -     * virtualMachinesExecuteHibernate: executeHibernate for a virtual machine.
        +     * VirtualMachinesExecuteHibernate: Execute hibernate operation for a batch of virtual machines, this operation is
        +     * triggered as soon as Computeschedule receives it.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -146,7 +154,8 @@ HibernateResourceOperationResponse virtualMachinesExecuteHibernate(String locati
                 ExecuteHibernateRequest requestBody);
         
             /**
        -     * virtualMachinesExecuteStart: executeStart for a virtual machine.
        +     * VirtualMachinesExecuteStart: Execute start operation for a batch of virtual machines, this operation is triggered
        +     * as soon as Computeschedule receives it.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -160,7 +169,8 @@ Response virtualMachinesExecuteStartWithResponse
                 ExecuteStartRequest requestBody, Context context);
         
             /**
        -     * virtualMachinesExecuteStart: executeStart for a virtual machine.
        +     * VirtualMachinesExecuteStart: Execute start operation for a batch of virtual machines, this operation is triggered
        +     * as soon as Computeschedule receives it.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -173,7 +183,7 @@ StartResourceOperationResponse virtualMachinesExecuteStart(String locationparame
                 ExecuteStartRequest requestBody);
         
             /**
        -     * virtualMachinesGetOperationStatus: getOperationStatus for a virtual machine.
        +     * VirtualMachinesGetOperationStatus: Polling endpoint to read status of operations performed on virtual machines.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -187,7 +197,7 @@ Response virtualMachinesGetOperationStatusWithRespon
                 GetOperationStatusRequest requestBody, Context context);
         
             /**
        -     * virtualMachinesGetOperationStatus: getOperationStatus for a virtual machine.
        +     * VirtualMachinesGetOperationStatus: Polling endpoint to read status of operations performed on virtual machines.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -200,7 +210,7 @@ GetOperationStatusResponse virtualMachinesGetOperationStatus(String locationpara
                 GetOperationStatusRequest requestBody);
         
             /**
        -     * virtualMachinesCancelOperations: cancelOperations for a virtual machine.
        +     * VirtualMachinesCancelOperations: Cancel a previously submitted (start/deallocate/hibernate) request.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -214,7 +224,7 @@ Response virtualMachinesCancelOperationsWithResponse(S
                 CancelOperationsRequest requestBody, Context context);
         
             /**
        -     * virtualMachinesCancelOperations: cancelOperations for a virtual machine.
        +     * VirtualMachinesCancelOperations: Cancel a previously submitted (start/deallocate/hibernate) request.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -227,7 +237,8 @@ CancelOperationsResponse virtualMachinesCancelOperations(String locationparamete
                 CancelOperationsRequest requestBody);
         
             /**
        -     * virtualMachinesGetOperationErrors: getOperationErrors associated with an operation on a virtual machine.
        +     * VirtualMachinesGetOperationErrors: Get error details on operation errors (like transient errors encountered,
        +     * additional logs) if they exist.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        @@ -241,7 +252,8 @@ Response virtualMachinesGetOperationErrorsWithRespon
                 GetOperationErrorsRequest requestBody, Context context);
         
             /**
        -     * virtualMachinesGetOperationErrors: getOperationErrors associated with an operation on a virtual machine.
        +     * VirtualMachinesGetOperationErrors: Get error details on operation errors (like transient errors encountered,
        +     * additional logs) if they exist.
              * 
              * @param locationparameter The location name.
              * @param requestBody The request body.
        diff --git a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/models/SubmitDeallocateRequest.java b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/models/SubmitDeallocateRequest.java
        index 09f9b03ed729..2e2326dd3073 100644
        --- a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/models/SubmitDeallocateRequest.java
        +++ b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/main/java/com/azure/resourcemanager/computeschedule/models/SubmitDeallocateRequest.java
        @@ -33,7 +33,7 @@ public final class SubmitDeallocateRequest implements JsonSerializable Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8)));
        @@ -34,6 +32,5 @@ public void testList() throws Exception {
         
                 PagedIterable response = manager.operations().list(com.azure.core.util.Context.NONE);
         
        -        Assertions.assertEquals(ActionType.INTERNAL, response.iterator().next().actionType());
             }
         }
        diff --git a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/test/java/com/azure/resourcemanager/computeschedule/generated/ResourcesTests.java b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/test/java/com/azure/resourcemanager/computeschedule/generated/ResourcesTests.java
        index 30ca995d588c..ae5a055fa2e0 100644
        --- a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/test/java/com/azure/resourcemanager/computeschedule/generated/ResourcesTests.java
        +++ b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/test/java/com/azure/resourcemanager/computeschedule/generated/ResourcesTests.java
        @@ -12,14 +12,14 @@
         public final class ResourcesTests {
             @org.junit.jupiter.api.Test
             public void testDeserialize() throws Exception {
        -        Resources model = BinaryData.fromString("{\"ids\":[\"jcny\"]}").toObject(Resources.class);
        -        Assertions.assertEquals("jcny", model.ids().get(0));
        +        Resources model = BinaryData.fromString("{\"ids\":[\"k\",\"vd\"]}").toObject(Resources.class);
        +        Assertions.assertEquals("k", model.ids().get(0));
             }
         
             @org.junit.jupiter.api.Test
             public void testSerialize() throws Exception {
        -        Resources model = new Resources().withIds(Arrays.asList("jcny"));
        +        Resources model = new Resources().withIds(Arrays.asList("k", "vd"));
                 model = BinaryData.fromObject(model).toObject(Resources.class);
        -        Assertions.assertEquals("jcny", model.ids().get(0));
        +        Assertions.assertEquals("k", model.ids().get(0));
             }
         }
        diff --git a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/test/java/com/azure/resourcemanager/computeschedule/generated/RetryPolicyTests.java b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/test/java/com/azure/resourcemanager/computeschedule/generated/RetryPolicyTests.java
        index aa1eeceff2cc..d2f0ab029712 100644
        --- a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/test/java/com/azure/resourcemanager/computeschedule/generated/RetryPolicyTests.java
        +++ b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/test/java/com/azure/resourcemanager/computeschedule/generated/RetryPolicyTests.java
        @@ -11,17 +11,17 @@
         public final class RetryPolicyTests {
             @org.junit.jupiter.api.Test
             public void testDeserialize() throws Exception {
        -        RetryPolicy model = BinaryData.fromString("{\"retryCount\":1674535960,\"retryWindowInMinutes\":70776342}")
        +        RetryPolicy model = BinaryData.fromString("{\"retryCount\":257838249,\"retryWindowInMinutes\":355535904}")
                     .toObject(RetryPolicy.class);
        -        Assertions.assertEquals(1674535960, model.retryCount());
        -        Assertions.assertEquals(70776342, model.retryWindowInMinutes());
        +        Assertions.assertEquals(257838249, model.retryCount());
        +        Assertions.assertEquals(355535904, model.retryWindowInMinutes());
             }
         
             @org.junit.jupiter.api.Test
             public void testSerialize() throws Exception {
        -        RetryPolicy model = new RetryPolicy().withRetryCount(1674535960).withRetryWindowInMinutes(70776342);
        +        RetryPolicy model = new RetryPolicy().withRetryCount(257838249).withRetryWindowInMinutes(355535904);
                 model = BinaryData.fromObject(model).toObject(RetryPolicy.class);
        -        Assertions.assertEquals(1674535960, model.retryCount());
        -        Assertions.assertEquals(70776342, model.retryWindowInMinutes());
        +        Assertions.assertEquals(257838249, model.retryCount());
        +        Assertions.assertEquals(355535904, model.retryWindowInMinutes());
             }
         }
        diff --git a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/test/java/com/azure/resourcemanager/computeschedule/generated/ScheduleTests.java b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/test/java/com/azure/resourcemanager/computeschedule/generated/ScheduleTests.java
        index ec48ee539398..5f59d8e6e37a 100644
        --- a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/test/java/com/azure/resourcemanager/computeschedule/generated/ScheduleTests.java
        +++ b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/test/java/com/azure/resourcemanager/computeschedule/generated/ScheduleTests.java
        @@ -13,22 +13,28 @@
         public final class ScheduleTests {
             @org.junit.jupiter.api.Test
             public void testDeserialize() throws Exception {
        -        Schedule model = BinaryData
        -            .fromString("{\"deadLine\":\"2021-06-10T17:14:25Z\",\"timeZone\":\"rtfw\",\"deadlineType\":\"Unknown\"}")
        +        Schedule model = BinaryData.fromString(
        +            "{\"deadline\":\"2021-11-30T01:16:03Z\",\"deadLine\":\"2021-08-06T18:49:52Z\",\"timezone\":\"czbysc\",\"timeZone\":\"q\",\"deadlineType\":\"Unknown\"}")
                     .toObject(Schedule.class);
        -        Assertions.assertEquals(OffsetDateTime.parse("2021-06-10T17:14:25Z"), model.deadLine());
        -        Assertions.assertEquals("rtfw", model.timeZone());
        +        Assertions.assertEquals(OffsetDateTime.parse("2021-11-30T01:16:03Z"), model.deadline());
        +        Assertions.assertEquals(OffsetDateTime.parse("2021-08-06T18:49:52Z"), model.deadLine());
        +        Assertions.assertEquals("czbysc", model.timezone());
        +        Assertions.assertEquals("q", model.timeZone());
                 Assertions.assertEquals(DeadlineType.UNKNOWN, model.deadlineType());
             }
         
             @org.junit.jupiter.api.Test
             public void testSerialize() throws Exception {
        -        Schedule model = new Schedule().withDeadLine(OffsetDateTime.parse("2021-06-10T17:14:25Z"))
        -            .withTimeZone("rtfw")
        +        Schedule model = new Schedule().withDeadline(OffsetDateTime.parse("2021-11-30T01:16:03Z"))
        +            .withDeadLine(OffsetDateTime.parse("2021-08-06T18:49:52Z"))
        +            .withTimezone("czbysc")
        +            .withTimeZone("q")
                     .withDeadlineType(DeadlineType.UNKNOWN);
                 model = BinaryData.fromObject(model).toObject(Schedule.class);
        -        Assertions.assertEquals(OffsetDateTime.parse("2021-06-10T17:14:25Z"), model.deadLine());
        -        Assertions.assertEquals("rtfw", model.timeZone());
        +        Assertions.assertEquals(OffsetDateTime.parse("2021-11-30T01:16:03Z"), model.deadline());
        +        Assertions.assertEquals(OffsetDateTime.parse("2021-08-06T18:49:52Z"), model.deadLine());
        +        Assertions.assertEquals("czbysc", model.timezone());
        +        Assertions.assertEquals("q", model.timeZone());
                 Assertions.assertEquals(DeadlineType.UNKNOWN, model.deadlineType());
             }
         }
        diff --git a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/test/java/com/azure/resourcemanager/computeschedule/generated/SubmitDeallocateRequestTests.java b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/test/java/com/azure/resourcemanager/computeschedule/generated/SubmitDeallocateRequestTests.java
        index fc681a74892c..925e6fdc48b4 100644
        --- a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/test/java/com/azure/resourcemanager/computeschedule/generated/SubmitDeallocateRequestTests.java
        +++ b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/test/java/com/azure/resourcemanager/computeschedule/generated/SubmitDeallocateRequestTests.java
        @@ -20,37 +20,45 @@ public final class SubmitDeallocateRequestTests {
             @org.junit.jupiter.api.Test
             public void testDeserialize() throws Exception {
                 SubmitDeallocateRequest model = BinaryData.fromString(
        -            "{\"schedule\":{\"deadLine\":\"2021-10-11T02:15:13Z\",\"timeZone\":\"ijbpzvgnwzsymgl\",\"deadlineType\":\"InitiateAt\"},\"executionParameters\":{\"optimizationPreference\":\"Cost\",\"retryPolicy\":{\"retryCount\":2049014083,\"retryWindowInMinutes\":1760407196}},\"resources\":{\"ids\":[\"bihanuf\",\"fcbjysagithxqha\",\"ifpikxwczby\",\"cnpqxuhivyqniwby\"]},\"correlationid\":\"rkxvdum\"}")
        +            "{\"schedule\":{\"deadline\":\"2021-09-06T02:12:49Z\",\"deadLine\":\"2021-12-03T06:58:55Z\",\"timezone\":\"zvgnwzs\",\"timeZone\":\"glzufc\",\"deadlineType\":\"CompleteBy\"},\"executionParameters\":{\"optimizationPreference\":\"CostAvailabilityBalanced\",\"retryPolicy\":{\"retryCount\":1757371466,\"retryWindowInMinutes\":1730607260}},\"resources\":{\"ids\":[\"nufhf\",\"bj\",\"s\",\"git\"]},\"correlationid\":\"xqhabi\"}")
                     .toObject(SubmitDeallocateRequest.class);
        -        Assertions.assertEquals(OffsetDateTime.parse("2021-10-11T02:15:13Z"), model.schedule().deadLine());
        -        Assertions.assertEquals("ijbpzvgnwzsymgl", model.schedule().timeZone());
        -        Assertions.assertEquals(DeadlineType.INITIATE_AT, model.schedule().deadlineType());
        -        Assertions.assertEquals(OptimizationPreference.COST, model.executionParameters().optimizationPreference());
        -        Assertions.assertEquals(2049014083, model.executionParameters().retryPolicy().retryCount());
        -        Assertions.assertEquals(1760407196, model.executionParameters().retryPolicy().retryWindowInMinutes());
        -        Assertions.assertEquals("bihanuf", model.resources().ids().get(0));
        -        Assertions.assertEquals("rkxvdum", model.correlationid());
        +        Assertions.assertEquals(OffsetDateTime.parse("2021-09-06T02:12:49Z"), model.schedule().deadline());
        +        Assertions.assertEquals(OffsetDateTime.parse("2021-12-03T06:58:55Z"), model.schedule().deadLine());
        +        Assertions.assertEquals("zvgnwzs", model.schedule().timezone());
        +        Assertions.assertEquals("glzufc", model.schedule().timeZone());
        +        Assertions.assertEquals(DeadlineType.COMPLETE_BY, model.schedule().deadlineType());
        +        Assertions.assertEquals(OptimizationPreference.COST_AVAILABILITY_BALANCED,
        +            model.executionParameters().optimizationPreference());
        +        Assertions.assertEquals(1757371466, model.executionParameters().retryPolicy().retryCount());
        +        Assertions.assertEquals(1730607260, model.executionParameters().retryPolicy().retryWindowInMinutes());
        +        Assertions.assertEquals("nufhf", model.resources().ids().get(0));
        +        Assertions.assertEquals("xqhabi", model.correlationid());
             }
         
             @org.junit.jupiter.api.Test
             public void testSerialize() throws Exception {
                 SubmitDeallocateRequest model = new SubmitDeallocateRequest()
        -            .withSchedule(new Schedule().withDeadLine(OffsetDateTime.parse("2021-10-11T02:15:13Z"))
        -                .withTimeZone("ijbpzvgnwzsymgl")
        -                .withDeadlineType(DeadlineType.INITIATE_AT))
        -            .withExecutionParameters(new ExecutionParameters().withOptimizationPreference(OptimizationPreference.COST)
        -                .withRetryPolicy(new RetryPolicy().withRetryCount(2049014083).withRetryWindowInMinutes(1760407196)))
        -            .withResources(
        -                new Resources().withIds(Arrays.asList("bihanuf", "fcbjysagithxqha", "ifpikxwczby", "cnpqxuhivyqniwby")))
        -            .withCorrelationid("rkxvdum");
        +            .withSchedule(new Schedule().withDeadline(OffsetDateTime.parse("2021-09-06T02:12:49Z"))
        +                .withDeadLine(OffsetDateTime.parse("2021-12-03T06:58:55Z"))
        +                .withTimezone("zvgnwzs")
        +                .withTimeZone("glzufc")
        +                .withDeadlineType(DeadlineType.COMPLETE_BY))
        +            .withExecutionParameters(
        +                new ExecutionParameters().withOptimizationPreference(OptimizationPreference.COST_AVAILABILITY_BALANCED)
        +                    .withRetryPolicy(new RetryPolicy().withRetryCount(1757371466).withRetryWindowInMinutes(1730607260)))
        +            .withResources(new Resources().withIds(Arrays.asList("nufhf", "bj", "s", "git")))
        +            .withCorrelationid("xqhabi");
                 model = BinaryData.fromObject(model).toObject(SubmitDeallocateRequest.class);
        -        Assertions.assertEquals(OffsetDateTime.parse("2021-10-11T02:15:13Z"), model.schedule().deadLine());
        -        Assertions.assertEquals("ijbpzvgnwzsymgl", model.schedule().timeZone());
        -        Assertions.assertEquals(DeadlineType.INITIATE_AT, model.schedule().deadlineType());
        -        Assertions.assertEquals(OptimizationPreference.COST, model.executionParameters().optimizationPreference());
        -        Assertions.assertEquals(2049014083, model.executionParameters().retryPolicy().retryCount());
        -        Assertions.assertEquals(1760407196, model.executionParameters().retryPolicy().retryWindowInMinutes());
        -        Assertions.assertEquals("bihanuf", model.resources().ids().get(0));
        -        Assertions.assertEquals("rkxvdum", model.correlationid());
        +        Assertions.assertEquals(OffsetDateTime.parse("2021-09-06T02:12:49Z"), model.schedule().deadline());
        +        Assertions.assertEquals(OffsetDateTime.parse("2021-12-03T06:58:55Z"), model.schedule().deadLine());
        +        Assertions.assertEquals("zvgnwzs", model.schedule().timezone());
        +        Assertions.assertEquals("glzufc", model.schedule().timeZone());
        +        Assertions.assertEquals(DeadlineType.COMPLETE_BY, model.schedule().deadlineType());
        +        Assertions.assertEquals(OptimizationPreference.COST_AVAILABILITY_BALANCED,
        +            model.executionParameters().optimizationPreference());
        +        Assertions.assertEquals(1757371466, model.executionParameters().retryPolicy().retryCount());
        +        Assertions.assertEquals(1730607260, model.executionParameters().retryPolicy().retryWindowInMinutes());
        +        Assertions.assertEquals("nufhf", model.resources().ids().get(0));
        +        Assertions.assertEquals("xqhabi", model.correlationid());
             }
         }
        diff --git a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/test/java/com/azure/resourcemanager/computeschedule/generated/SubmitHibernateRequestTests.java b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/test/java/com/azure/resourcemanager/computeschedule/generated/SubmitHibernateRequestTests.java
        index c9f27469eebd..1a8513f1280c 100644
        --- a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/test/java/com/azure/resourcemanager/computeschedule/generated/SubmitHibernateRequestTests.java
        +++ b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/test/java/com/azure/resourcemanager/computeschedule/generated/SubmitHibernateRequestTests.java
        @@ -20,40 +20,45 @@ public final class SubmitHibernateRequestTests {
             @org.junit.jupiter.api.Test
             public void testDeserialize() throws Exception {
                 SubmitHibernateRequest model = BinaryData.fromString(
        -            "{\"schedule\":{\"deadLine\":\"2021-11-13T06:20:15Z\",\"timeZone\":\"ahbc\",\"deadlineType\":\"InitiateAt\"},\"executionParameters\":{\"optimizationPreference\":\"CostAvailabilityBalanced\",\"retryPolicy\":{\"retryCount\":1276886479,\"retryWindowInMinutes\":491201544}},\"resources\":{\"ids\":[\"gexpaojakhmsbz\",\"hcrzevd\",\"hlxaolthqtr\",\"qjbpfzfsin\"]},\"correlationid\":\"gvfcj\"}")
        +            "{\"schedule\":{\"deadline\":\"2021-01-15T00:39:28Z\",\"deadLine\":\"2021-04-04T07:45:50Z\",\"timezone\":\"dio\",\"timeZone\":\"pslwejdpvw\",\"deadlineType\":\"CompleteBy\"},\"executionParameters\":{\"optimizationPreference\":\"CostAvailabilityBalanced\",\"retryPolicy\":{\"retryCount\":1977100929,\"retryWindowInMinutes\":1527303417}},\"resources\":{\"ids\":[\"tazak\",\"j\",\"ahbc\",\"yffdfdos\"]},\"correlationid\":\"gexpaojakhmsbz\"}")
                     .toObject(SubmitHibernateRequest.class);
        -        Assertions.assertEquals(OffsetDateTime.parse("2021-11-13T06:20:15Z"), model.schedule().deadLine());
        -        Assertions.assertEquals("ahbc", model.schedule().timeZone());
        -        Assertions.assertEquals(DeadlineType.INITIATE_AT, model.schedule().deadlineType());
        +        Assertions.assertEquals(OffsetDateTime.parse("2021-01-15T00:39:28Z"), model.schedule().deadline());
        +        Assertions.assertEquals(OffsetDateTime.parse("2021-04-04T07:45:50Z"), model.schedule().deadLine());
        +        Assertions.assertEquals("dio", model.schedule().timezone());
        +        Assertions.assertEquals("pslwejdpvw", model.schedule().timeZone());
        +        Assertions.assertEquals(DeadlineType.COMPLETE_BY, model.schedule().deadlineType());
                 Assertions.assertEquals(OptimizationPreference.COST_AVAILABILITY_BALANCED,
                     model.executionParameters().optimizationPreference());
        -        Assertions.assertEquals(1276886479, model.executionParameters().retryPolicy().retryCount());
        -        Assertions.assertEquals(491201544, model.executionParameters().retryPolicy().retryWindowInMinutes());
        -        Assertions.assertEquals("gexpaojakhmsbz", model.resources().ids().get(0));
        -        Assertions.assertEquals("gvfcj", model.correlationid());
        +        Assertions.assertEquals(1977100929, model.executionParameters().retryPolicy().retryCount());
        +        Assertions.assertEquals(1527303417, model.executionParameters().retryPolicy().retryWindowInMinutes());
        +        Assertions.assertEquals("tazak", model.resources().ids().get(0));
        +        Assertions.assertEquals("gexpaojakhmsbz", model.correlationid());
             }
         
             @org.junit.jupiter.api.Test
             public void testSerialize() throws Exception {
                 SubmitHibernateRequest model = new SubmitHibernateRequest()
        -            .withSchedule(new Schedule().withDeadLine(OffsetDateTime.parse("2021-11-13T06:20:15Z"))
        -                .withTimeZone("ahbc")
        -                .withDeadlineType(DeadlineType.INITIATE_AT))
        +            .withSchedule(new Schedule().withDeadline(OffsetDateTime.parse("2021-01-15T00:39:28Z"))
        +                .withDeadLine(OffsetDateTime.parse("2021-04-04T07:45:50Z"))
        +                .withTimezone("dio")
        +                .withTimeZone("pslwejdpvw")
        +                .withDeadlineType(DeadlineType.COMPLETE_BY))
                     .withExecutionParameters(
                         new ExecutionParameters().withOptimizationPreference(OptimizationPreference.COST_AVAILABILITY_BALANCED)
        -                    .withRetryPolicy(new RetryPolicy().withRetryCount(1276886479).withRetryWindowInMinutes(491201544)))
        -            .withResources(
        -                new Resources().withIds(Arrays.asList("gexpaojakhmsbz", "hcrzevd", "hlxaolthqtr", "qjbpfzfsin")))
        -            .withCorrelationid("gvfcj");
        +                    .withRetryPolicy(new RetryPolicy().withRetryCount(1977100929).withRetryWindowInMinutes(1527303417)))
        +            .withResources(new Resources().withIds(Arrays.asList("tazak", "j", "ahbc", "yffdfdos")))
        +            .withCorrelationid("gexpaojakhmsbz");
                 model = BinaryData.fromObject(model).toObject(SubmitHibernateRequest.class);
        -        Assertions.assertEquals(OffsetDateTime.parse("2021-11-13T06:20:15Z"), model.schedule().deadLine());
        -        Assertions.assertEquals("ahbc", model.schedule().timeZone());
        -        Assertions.assertEquals(DeadlineType.INITIATE_AT, model.schedule().deadlineType());
        +        Assertions.assertEquals(OffsetDateTime.parse("2021-01-15T00:39:28Z"), model.schedule().deadline());
        +        Assertions.assertEquals(OffsetDateTime.parse("2021-04-04T07:45:50Z"), model.schedule().deadLine());
        +        Assertions.assertEquals("dio", model.schedule().timezone());
        +        Assertions.assertEquals("pslwejdpvw", model.schedule().timeZone());
        +        Assertions.assertEquals(DeadlineType.COMPLETE_BY, model.schedule().deadlineType());
                 Assertions.assertEquals(OptimizationPreference.COST_AVAILABILITY_BALANCED,
                     model.executionParameters().optimizationPreference());
        -        Assertions.assertEquals(1276886479, model.executionParameters().retryPolicy().retryCount());
        -        Assertions.assertEquals(491201544, model.executionParameters().retryPolicy().retryWindowInMinutes());
        -        Assertions.assertEquals("gexpaojakhmsbz", model.resources().ids().get(0));
        -        Assertions.assertEquals("gvfcj", model.correlationid());
        +        Assertions.assertEquals(1977100929, model.executionParameters().retryPolicy().retryCount());
        +        Assertions.assertEquals(1527303417, model.executionParameters().retryPolicy().retryWindowInMinutes());
        +        Assertions.assertEquals("tazak", model.resources().ids().get(0));
        +        Assertions.assertEquals("gexpaojakhmsbz", model.correlationid());
             }
         }
        diff --git a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/test/java/com/azure/resourcemanager/computeschedule/generated/SubmitStartRequestTests.java b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/test/java/com/azure/resourcemanager/computeschedule/generated/SubmitStartRequestTests.java
        index 4688dc9e1fd1..0657427af193 100644
        --- a/sdk/computeschedule/azure-resourcemanager-computeschedule/src/test/java/com/azure/resourcemanager/computeschedule/generated/SubmitStartRequestTests.java
        +++ b/sdk/computeschedule/azure-resourcemanager-computeschedule/src/test/java/com/azure/resourcemanager/computeschedule/generated/SubmitStartRequestTests.java
        @@ -20,39 +20,45 @@ public final class SubmitStartRequestTests {
             @org.junit.jupiter.api.Test
             public void testDeserialize() throws Exception {
                 SubmitStartRequest model = BinaryData.fromString(
        -            "{\"schedule\":{\"deadLine\":\"2021-05-28T01:58:06Z\",\"timeZone\":\"yhuybbkpod\",\"deadlineType\":\"InitiateAt\"},\"executionParameters\":{\"optimizationPreference\":\"Availability\",\"retryPolicy\":{\"retryCount\":895630833,\"retryWindowInMinutes\":1290742637}},\"resources\":{\"ids\":[\"mihe\",\"gnarxzxtheo\",\"usivye\"]},\"correlationid\":\"cciqihnhungbwjz\"}")
        +            "{\"schedule\":{\"deadline\":\"2021-11-24T18:52:18Z\",\"deadLine\":\"2021-10-29T01:56:29Z\",\"timezone\":\"hpf\",\"timeZone\":\"ypininm\",\"deadlineType\":\"InitiateAt\"},\"executionParameters\":{\"optimizationPreference\":\"CostAvailabilityBalanced\",\"retryPolicy\":{\"retryCount\":1439394091,\"retryWindowInMinutes\":1813280112}},\"resources\":{\"ids\":[\"depoog\",\"nuvamiheogna\",\"xzxtheo\"]},\"correlationid\":\"usivye\"}")
                     .toObject(SubmitStartRequest.class);
        -        Assertions.assertEquals(OffsetDateTime.parse("2021-05-28T01:58:06Z"), model.schedule().deadLine());
        -        Assertions.assertEquals("yhuybbkpod", model.schedule().timeZone());
        +        Assertions.assertEquals(OffsetDateTime.parse("2021-11-24T18:52:18Z"), model.schedule().deadline());
        +        Assertions.assertEquals(OffsetDateTime.parse("2021-10-29T01:56:29Z"), model.schedule().deadLine());
        +        Assertions.assertEquals("hpf", model.schedule().timezone());
        +        Assertions.assertEquals("ypininm", model.schedule().timeZone());
                 Assertions.assertEquals(DeadlineType.INITIATE_AT, model.schedule().deadlineType());
        -        Assertions.assertEquals(OptimizationPreference.AVAILABILITY,
        +        Assertions.assertEquals(OptimizationPreference.COST_AVAILABILITY_BALANCED,
                     model.executionParameters().optimizationPreference());
        -        Assertions.assertEquals(895630833, model.executionParameters().retryPolicy().retryCount());
        -        Assertions.assertEquals(1290742637, model.executionParameters().retryPolicy().retryWindowInMinutes());
        -        Assertions.assertEquals("mihe", model.resources().ids().get(0));
        -        Assertions.assertEquals("cciqihnhungbwjz", model.correlationid());
        +        Assertions.assertEquals(1439394091, model.executionParameters().retryPolicy().retryCount());
        +        Assertions.assertEquals(1813280112, model.executionParameters().retryPolicy().retryWindowInMinutes());
        +        Assertions.assertEquals("depoog", model.resources().ids().get(0));
        +        Assertions.assertEquals("usivye", model.correlationid());
             }
         
             @org.junit.jupiter.api.Test
             public void testSerialize() throws Exception {
                 SubmitStartRequest model = new SubmitStartRequest()
        -            .withSchedule(new Schedule().withDeadLine(OffsetDateTime.parse("2021-05-28T01:58:06Z"))
        -                .withTimeZone("yhuybbkpod")
        +            .withSchedule(new Schedule().withDeadline(OffsetDateTime.parse("2021-11-24T18:52:18Z"))
        +                .withDeadLine(OffsetDateTime.parse("2021-10-29T01:56:29Z"))
        +                .withTimezone("hpf")
        +                .withTimeZone("ypininm")
                         .withDeadlineType(DeadlineType.INITIATE_AT))
                     .withExecutionParameters(
        -                new ExecutionParameters().withOptimizationPreference(OptimizationPreference.AVAILABILITY)
        -                    .withRetryPolicy(new RetryPolicy().withRetryCount(895630833).withRetryWindowInMinutes(1290742637)))
        -            .withResources(new Resources().withIds(Arrays.asList("mihe", "gnarxzxtheo", "usivye")))
        -            .withCorrelationid("cciqihnhungbwjz");
        +                new ExecutionParameters().withOptimizationPreference(OptimizationPreference.COST_AVAILABILITY_BALANCED)
        +                    .withRetryPolicy(new RetryPolicy().withRetryCount(1439394091).withRetryWindowInMinutes(1813280112)))
        +            .withResources(new Resources().withIds(Arrays.asList("depoog", "nuvamiheogna", "xzxtheo")))
        +            .withCorrelationid("usivye");
                 model = BinaryData.fromObject(model).toObject(SubmitStartRequest.class);
        -        Assertions.assertEquals(OffsetDateTime.parse("2021-05-28T01:58:06Z"), model.schedule().deadLine());
        -        Assertions.assertEquals("yhuybbkpod", model.schedule().timeZone());
        +        Assertions.assertEquals(OffsetDateTime.parse("2021-11-24T18:52:18Z"), model.schedule().deadline());
        +        Assertions.assertEquals(OffsetDateTime.parse("2021-10-29T01:56:29Z"), model.schedule().deadLine());
        +        Assertions.assertEquals("hpf", model.schedule().timezone());
        +        Assertions.assertEquals("ypininm", model.schedule().timeZone());
                 Assertions.assertEquals(DeadlineType.INITIATE_AT, model.schedule().deadlineType());
        -        Assertions.assertEquals(OptimizationPreference.AVAILABILITY,
        +        Assertions.assertEquals(OptimizationPreference.COST_AVAILABILITY_BALANCED,
                     model.executionParameters().optimizationPreference());
        -        Assertions.assertEquals(895630833, model.executionParameters().retryPolicy().retryCount());
        -        Assertions.assertEquals(1290742637, model.executionParameters().retryPolicy().retryWindowInMinutes());
        -        Assertions.assertEquals("mihe", model.resources().ids().get(0));
        -        Assertions.assertEquals("cciqihnhungbwjz", model.correlationid());
        +        Assertions.assertEquals(1439394091, model.executionParameters().retryPolicy().retryCount());
        +        Assertions.assertEquals(1813280112, model.executionParameters().retryPolicy().retryWindowInMinutes());
        +        Assertions.assertEquals("depoog", model.resources().ids().get(0));
        +        Assertions.assertEquals("usivye", model.correlationid());
             }
         }
        diff --git a/sdk/computeschedule/azure-resourcemanager-computeschedule/tsp-location.yaml b/sdk/computeschedule/azure-resourcemanager-computeschedule/tsp-location.yaml
        index be9e75debb24..15e780964f87 100644
        --- a/sdk/computeschedule/azure-resourcemanager-computeschedule/tsp-location.yaml
        +++ b/sdk/computeschedule/azure-resourcemanager-computeschedule/tsp-location.yaml
        @@ -1,4 +1,4 @@
         directory: specification/computeschedule/ComputeSchedule.Management
        -commit: d79d73bea550b643c312dde6a7e817840c1ac914
        +commit: 63685369d3d7bdee95c51fb111c410c2cb5be8ec
         repo: Azure/azure-rest-api-specs
         additionalDirectories: 
        diff --git a/sdk/confidentialledger/azure-resourcemanager-confidentialledger/README.md b/sdk/confidentialledger/azure-resourcemanager-confidentialledger/README.md
        index bd4804ef6782..1afc59f6ae12 100644
        --- a/sdk/confidentialledger/azure-resourcemanager-confidentialledger/README.md
        +++ b/sdk/confidentialledger/azure-resourcemanager-confidentialledger/README.md
        @@ -32,7 +32,7 @@ Various documentation is available to help you get started
         
             com.azure.resourcemanager
             azure-resourcemanager-confidentialledger
        -    1.0.0
        +    1.1.0-beta.1
         
         ```
         [//]: # ({x-version-update-end})
        @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m
         [coc]: https://opensource.microsoft.com/codeofconduct/
         [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/
         
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fconfidentialledger%2Fazure-resourcemanager-confidentialledger%2FREADME.png)
        +
        diff --git a/sdk/confidentialledger/azure-resourcemanager-confidentialledger/pom.xml b/sdk/confidentialledger/azure-resourcemanager-confidentialledger/pom.xml
        index 6f2c07767aa4..fde1a9b51b3f 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.54.1 
        +      1.55.3 
             
             
               com.azure
               azure-core-management
        -      1.15.6 
        +      1.17.0 
             
             
               com.azure
               azure-core-test
        -      1.27.0-beta.4 
        +      1.27.0-beta.8 
               test
             
             
               com.azure
               azure-identity
        -      1.15.0 
        +      1.15.4 
               test
             
             
        @@ -91,7 +91,7 @@
             
               com.azure.resourcemanager
               azure-resourcemanager-resources
        -      2.46.0 
        +      2.48.0 
               test
             
           
        diff --git a/sdk/confidentialledger/azure-security-confidentialledger/CHANGELOG.md b/sdk/confidentialledger/azure-security-confidentialledger/CHANGELOG.md
        index b05475633032..54dbf8e32d6a 100644
        --- a/sdk/confidentialledger/azure-security-confidentialledger/CHANGELOG.md
        +++ b/sdk/confidentialledger/azure-security-confidentialledger/CHANGELOG.md
        @@ -10,6 +10,16 @@
         
         ### Other Changes
         
        +## 1.0.27 (2025-02-25)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`.
        +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`.
        +
        +
         ## 1.0.26 (2024-12-04)
         
         ### Other Changes
        @@ -66,8 +76,8 @@
         
         #### Dependency Updates
         
        -- Upgraded `azure-core` from `1.49.0` to version `1.49.1`.
         - Upgraded `azure-core-http-netty` from `1.15.0` to version `1.15.1`.
        +- Upgraded `azure-core` from `1.49.0` to version `1.49.1`.
         
         
         ## 1.0.20 (2024-05-28)
        diff --git a/sdk/confidentialledger/azure-security-confidentialledger/README.md b/sdk/confidentialledger/azure-security-confidentialledger/README.md
        index 953a0b2776a6..a3247170d5cc 100644
        --- a/sdk/confidentialledger/azure-security-confidentialledger/README.md
        +++ b/sdk/confidentialledger/azure-security-confidentialledger/README.md
        @@ -21,7 +21,7 @@ portfolio, Azure Confidential Ledger runs in SGX enclaves. It is built on Micros
         
           com.azure
           azure-security-confidentialledger
        -  1.0.11
        +  1.1.0-beta.1
         
         ```
         [//]: # ({x-version-update-end})
        @@ -49,7 +49,7 @@ To use the [DefaultAzureCredential][DefaultAzureCredential] provider shown below
         
             com.azure
             azure-identity
        -    1.14.2
        +    1.15.3
         
         ```
         
        @@ -128,4 +128,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m
         [coc_contact]: mailto:opencode@microsoft.com
         
         
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fconfidentialledger%2Fazure-security-confidentialledger%2FREADME.png)
        +
        diff --git a/sdk/confidentialledger/azure-security-confidentialledger/pom.xml b/sdk/confidentialledger/azure-security-confidentialledger/pom.xml
        index 74f0f67fdbb6..bdeadd803d10 100644
        --- a/sdk/confidentialledger/azure-security-confidentialledger/pom.xml
        +++ b/sdk/confidentialledger/azure-security-confidentialledger/pom.xml
        @@ -52,31 +52,31 @@
             
               com.azure
               azure-core
        -      1.54.1 
        +      1.55.3 
             
             
               com.azure
               azure-core-http-netty
        -      1.15.7 
        +      1.15.11 
             
         
             
             
               com.azure
               azure-core-test
        -      1.27.0-beta.4 
        +      1.27.0-beta.8 
               test
             
             
               com.azure
               azure-identity
        -      1.15.0 
        +      1.15.4 
               test
             
             
               com.azure
               azure-core-serializer-json-jackson
        -      1.5.4 
        +      1.5.8 
               test
             
           
        diff --git a/sdk/confluent/azure-resourcemanager-confluent/README.md b/sdk/confluent/azure-resourcemanager-confluent/README.md
        index 12b4da188610..0e0edfdc1ad2 100644
        --- a/sdk/confluent/azure-resourcemanager-confluent/README.md
        +++ b/sdk/confluent/azure-resourcemanager-confluent/README.md
        @@ -32,7 +32,7 @@ Various documentation is available to help you get started
         
             com.azure.resourcemanager
             azure-resourcemanager-confluent
        -    1.2.0
        +    1.3.0-beta.1
         
         ```
         [//]: # ({x-version-update-end})
        @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m
         [coc]: https://opensource.microsoft.com/codeofconduct/
         [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/
         
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fconfluent%2Fazure-resourcemanager-confluent%2FREADME.png)
        +
        diff --git a/sdk/confluent/azure-resourcemanager-confluent/pom.xml b/sdk/confluent/azure-resourcemanager-confluent/pom.xml
        index 0c735539bf60..b0b225f5e201 100644
        --- a/sdk/confluent/azure-resourcemanager-confluent/pom.xml
        +++ b/sdk/confluent/azure-resourcemanager-confluent/pom.xml
        @@ -51,23 +51,23 @@
             
               com.azure
               azure-core
        -      1.54.1 
        +      1.55.3 
             
             
               com.azure
               azure-core-management
        -      1.15.6 
        +      1.17.0 
             
             
               com.azure
               azure-core-test
        -      1.27.0-beta.4 
        +      1.27.0-beta.8 
               test
             
             
               com.azure
               azure-identity
        -      1.15.0 
        +      1.15.4 
               test
             
             
        @@ -91,7 +91,7 @@
             
               com.azure.resourcemanager
               azure-resourcemanager-resources
        -      2.46.0 
        +      2.48.0 
               test
             
           
        diff --git a/sdk/connectedcache/azure-resourcemanager-connectedcache/README.md b/sdk/connectedcache/azure-resourcemanager-connectedcache/README.md
        index 59a5e2e3c07d..65ca414b6872 100644
        --- a/sdk/connectedcache/azure-resourcemanager-connectedcache/README.md
        +++ b/sdk/connectedcache/azure-resourcemanager-connectedcache/README.md
        @@ -32,7 +32,7 @@ Various documentation is available to help you get started
         
             com.azure.resourcemanager
             azure-resourcemanager-connectedcache
        -    1.0.0-beta.1
        +    1.0.0-beta.2
         
         ```
         [//]: # ({x-version-update-end})
        @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m
         [coc]: https://opensource.microsoft.com/codeofconduct/
         [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/
         
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fconnectedcache%2Fazure-resourcemanager-connectedcache%2FREADME.png)
        +
        diff --git a/sdk/connectedcache/azure-resourcemanager-connectedcache/pom.xml b/sdk/connectedcache/azure-resourcemanager-connectedcache/pom.xml
        index f4b437d90dc6..dac72cef94e6 100644
        --- a/sdk/connectedcache/azure-resourcemanager-connectedcache/pom.xml
        +++ b/sdk/connectedcache/azure-resourcemanager-connectedcache/pom.xml
        @@ -52,23 +52,23 @@
             
               com.azure
               azure-core
        -      1.54.1 
        +      1.55.3 
             
             
               com.azure
               azure-core-management
        -      1.15.6 
        +      1.17.0 
             
             
               com.azure
               azure-core-test
        -      1.27.0-beta.4 
        +      1.27.0-beta.8 
               test
             
             
               com.azure
               azure-identity
        -      1.15.0 
        +      1.15.4 
               test
             
           
        diff --git a/sdk/connectedcache/azure-resourcemanager-connectedcache/src/main/java/com/azure/resourcemanager/connectedcache/ConnectedCacheManager.java b/sdk/connectedcache/azure-resourcemanager-connectedcache/src/main/java/com/azure/resourcemanager/connectedcache/ConnectedCacheManager.java
        index 859eaf0ee41d..d8a335d28ef7 100644
        --- a/sdk/connectedcache/azure-resourcemanager-connectedcache/src/main/java/com/azure/resourcemanager/connectedcache/ConnectedCacheManager.java
        +++ b/sdk/connectedcache/azure-resourcemanager-connectedcache/src/main/java/com/azure/resourcemanager/connectedcache/ConnectedCacheManager.java
        @@ -22,6 +22,7 @@
         import com.azure.core.http.policy.UserAgentPolicy;
         import com.azure.core.management.profile.AzureProfile;
         import com.azure.core.util.Configuration;
        +import com.azure.core.util.CoreUtils;
         import com.azure.core.util.logging.ClientLogger;
         import com.azure.resourcemanager.connectedcache.fluent.ConnectedCacheManagementClient;
         import com.azure.resourcemanager.connectedcache.implementation.CacheNodesOperationsImpl;
        @@ -43,6 +44,7 @@
         import java.time.temporal.ChronoUnit;
         import java.util.ArrayList;
         import java.util.List;
        +import java.util.Map;
         import java.util.Objects;
         import java.util.stream.Collectors;
         
        @@ -117,6 +119,9 @@ public static Configurable configure() {
              */
             public static final class Configurable {
                 private static final ClientLogger LOGGER = new ClientLogger(Configurable.class);
        +        private static final String SDK_VERSION = "version";
        +        private static final Map PROPERTIES
        +            = CoreUtils.getProperties("azure-resourcemanager-connectedcache.properties");
         
                 private HttpClient httpClient;
                 private HttpLogOptions httpLogOptions;
        @@ -224,12 +229,14 @@ public ConnectedCacheManager authenticate(TokenCredential credential, AzureProfi
                     Objects.requireNonNull(credential, "'credential' cannot be null.");
                     Objects.requireNonNull(profile, "'profile' cannot be null.");
         
        +            String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion");
        +
                     StringBuilder userAgentBuilder = new StringBuilder();
                     userAgentBuilder.append("azsdk-java")
                         .append("-")
                         .append("com.azure.resourcemanager.connectedcache")
                         .append("/")
        -                .append("1.0.0-beta.1");
        +                .append(clientVersion);
                     if (!Configuration.getGlobalConfiguration().get("AZURE_TELEMETRY_DISABLED", false)) {
                         userAgentBuilder.append(" (")
                             .append(Configuration.getGlobalConfiguration().get("java.version"))
        diff --git a/sdk/connectedcache/azure-resourcemanager-connectedcache/src/main/resources/azure-resourcemanager-connectedcache.properties b/sdk/connectedcache/azure-resourcemanager-connectedcache/src/main/resources/azure-resourcemanager-connectedcache.properties
        new file mode 100644
        index 000000000000..defbd48204e4
        --- /dev/null
        +++ b/sdk/connectedcache/azure-resourcemanager-connectedcache/src/main/resources/azure-resourcemanager-connectedcache.properties
        @@ -0,0 +1 @@
        +version=${project.version}
        diff --git a/sdk/connectedvmware/azure-resourcemanager-connectedvmware/README.md b/sdk/connectedvmware/azure-resourcemanager-connectedvmware/README.md
        index 89a772f1f703..9380c6c7e74c 100644
        --- a/sdk/connectedvmware/azure-resourcemanager-connectedvmware/README.md
        +++ b/sdk/connectedvmware/azure-resourcemanager-connectedvmware/README.md
        @@ -32,7 +32,7 @@ Various documentation is available to help you get started
         
             com.azure.resourcemanager
             azure-resourcemanager-connectedvmware
        -    1.1.0
        +    1.2.0-beta.1
         
         ```
         [//]: # ({x-version-update-end})
        @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m
         [coc]: https://opensource.microsoft.com/codeofconduct/
         [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/
         
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fconnectedvmware%2Fazure-resourcemanager-connectedvmware%2FREADME.png)
        +
        diff --git a/sdk/connectedvmware/azure-resourcemanager-connectedvmware/pom.xml b/sdk/connectedvmware/azure-resourcemanager-connectedvmware/pom.xml
        index 90bda67c7396..97d41c85b149 100644
        --- a/sdk/connectedvmware/azure-resourcemanager-connectedvmware/pom.xml
        +++ b/sdk/connectedvmware/azure-resourcemanager-connectedvmware/pom.xml
        @@ -51,23 +51,23 @@
             
               com.azure
               azure-core
        -      1.54.1 
        +      1.55.3 
             
             
               com.azure
               azure-core-management
        -      1.15.6 
        +      1.17.0 
             
             
               com.azure
               azure-core-test
        -      1.27.0-beta.4 
        +      1.27.0-beta.8 
               test
             
             
               com.azure
               azure-identity
        -      1.15.0 
        +      1.15.4 
               test
             
             
        diff --git a/sdk/consumption/azure-resourcemanager-consumption/README.md b/sdk/consumption/azure-resourcemanager-consumption/README.md
        index f519e85e75fe..339faa32331a 100644
        --- a/sdk/consumption/azure-resourcemanager-consumption/README.md
        +++ b/sdk/consumption/azure-resourcemanager-consumption/README.md
        @@ -32,7 +32,7 @@ Various documentation is available to help you get started
         
             com.azure.resourcemanager
             azure-resourcemanager-consumption
        -    1.0.0
        +    1.1.0-beta.1
         
         ```
         [//]: # ({x-version-update-end})
        @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m
         [coc]: https://opensource.microsoft.com/codeofconduct/
         [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/
         
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fconsumption%2Fazure-resourcemanager-consumption%2FREADME.png)
        +
        diff --git a/sdk/consumption/azure-resourcemanager-consumption/pom.xml b/sdk/consumption/azure-resourcemanager-consumption/pom.xml
        index b4e4254f6816..4d880202f034 100644
        --- a/sdk/consumption/azure-resourcemanager-consumption/pom.xml
        +++ b/sdk/consumption/azure-resourcemanager-consumption/pom.xml
        @@ -51,23 +51,23 @@
             
               com.azure
               azure-core
        -      1.54.1 
        +      1.55.3 
             
             
               com.azure
               azure-core-management
        -      1.15.6 
        +      1.17.0 
             
             
               com.azure
               azure-core-test
        -      1.27.0-beta.4 
        +      1.27.0-beta.8 
               test
             
             
               com.azure
               azure-identity
        -      1.15.0 
        +      1.15.4 
               test
             
           
        diff --git a/sdk/containerorchestratorruntime/azure-resourcemanager-containerorchestratorruntime/README.md b/sdk/containerorchestratorruntime/azure-resourcemanager-containerorchestratorruntime/README.md
        index edd84fea27a0..3847256324a6 100644
        --- a/sdk/containerorchestratorruntime/azure-resourcemanager-containerorchestratorruntime/README.md
        +++ b/sdk/containerorchestratorruntime/azure-resourcemanager-containerorchestratorruntime/README.md
        @@ -32,7 +32,7 @@ Various documentation is available to help you get started
         
             com.azure.resourcemanager
             azure-resourcemanager-containerorchestratorruntime
        -    1.0.0-beta.1
        +    1.0.0-beta.2
         
         ```
         [//]: # ({x-version-update-end})
        @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m
         [coc]: https://opensource.microsoft.com/codeofconduct/
         [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/
         
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcontainerorchestratorruntime%2Fazure-resourcemanager-containerorchestratorruntime%2FREADME.png)
        +
        diff --git a/sdk/containerorchestratorruntime/azure-resourcemanager-containerorchestratorruntime/pom.xml b/sdk/containerorchestratorruntime/azure-resourcemanager-containerorchestratorruntime/pom.xml
        index 538680fe75f0..87dadf208c77 100644
        --- a/sdk/containerorchestratorruntime/azure-resourcemanager-containerorchestratorruntime/pom.xml
        +++ b/sdk/containerorchestratorruntime/azure-resourcemanager-containerorchestratorruntime/pom.xml
        @@ -51,23 +51,23 @@
             
               com.azure
               azure-core
        -      1.54.1 
        +      1.55.3 
             
             
               com.azure
               azure-core-management
        -      1.15.6 
        +      1.17.0 
             
             
               com.azure
               azure-core-test
        -      1.27.0-beta.4 
        +      1.27.0-beta.8 
               test
             
             
               com.azure
               azure-identity
        -      1.15.0 
        +      1.15.4 
               test
             
           
        diff --git a/sdk/containerorchestratorruntime/azure-resourcemanager-containerorchestratorruntime/src/main/java/com/azure/resourcemanager/containerorchestratorruntime/ContainerOrchestratorRuntimeManager.java b/sdk/containerorchestratorruntime/azure-resourcemanager-containerorchestratorruntime/src/main/java/com/azure/resourcemanager/containerorchestratorruntime/ContainerOrchestratorRuntimeManager.java
        index dec29ed5f86e..08b1eea1f337 100644
        --- a/sdk/containerorchestratorruntime/azure-resourcemanager-containerorchestratorruntime/src/main/java/com/azure/resourcemanager/containerorchestratorruntime/ContainerOrchestratorRuntimeManager.java
        +++ b/sdk/containerorchestratorruntime/azure-resourcemanager-containerorchestratorruntime/src/main/java/com/azure/resourcemanager/containerorchestratorruntime/ContainerOrchestratorRuntimeManager.java
        @@ -22,6 +22,7 @@
         import com.azure.core.http.policy.UserAgentPolicy;
         import com.azure.core.management.profile.AzureProfile;
         import com.azure.core.util.Configuration;
        +import com.azure.core.util.CoreUtils;
         import com.azure.core.util.logging.ClientLogger;
         import com.azure.resourcemanager.containerorchestratorruntime.fluent.ContainerOrchestratorRuntimeMgmtClient;
         import com.azure.resourcemanager.containerorchestratorruntime.implementation.BgpPeersImpl;
        @@ -39,6 +40,7 @@
         import java.time.temporal.ChronoUnit;
         import java.util.ArrayList;
         import java.util.List;
        +import java.util.Map;
         import java.util.Objects;
         import java.util.stream.Collectors;
         
        @@ -109,6 +111,9 @@ public static Configurable configure() {
              */
             public static final class Configurable {
                 private static final ClientLogger LOGGER = new ClientLogger(Configurable.class);
        +        private static final String SDK_VERSION = "version";
        +        private static final Map PROPERTIES
        +            = CoreUtils.getProperties("azure-resourcemanager-containerorchestratorruntime.properties");
         
                 private HttpClient httpClient;
                 private HttpLogOptions httpLogOptions;
        @@ -216,12 +221,14 @@ public ContainerOrchestratorRuntimeManager authenticate(TokenCredential credenti
                     Objects.requireNonNull(credential, "'credential' cannot be null.");
                     Objects.requireNonNull(profile, "'profile' cannot be null.");
         
        +            String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion");
        +
                     StringBuilder userAgentBuilder = new StringBuilder();
                     userAgentBuilder.append("azsdk-java")
                         .append("-")
                         .append("com.azure.resourcemanager.containerorchestratorruntime")
                         .append("/")
        -                .append("1.0.0-beta.1");
        +                .append(clientVersion);
                     if (!Configuration.getGlobalConfiguration().get("AZURE_TELEMETRY_DISABLED", false)) {
                         userAgentBuilder.append(" (")
                             .append(Configuration.getGlobalConfiguration().get("java.version"))
        diff --git a/sdk/containerorchestratorruntime/azure-resourcemanager-containerorchestratorruntime/src/main/resources/azure-resourcemanager-containerorchestratorruntime.properties b/sdk/containerorchestratorruntime/azure-resourcemanager-containerorchestratorruntime/src/main/resources/azure-resourcemanager-containerorchestratorruntime.properties
        new file mode 100644
        index 000000000000..defbd48204e4
        --- /dev/null
        +++ b/sdk/containerorchestratorruntime/azure-resourcemanager-containerorchestratorruntime/src/main/resources/azure-resourcemanager-containerorchestratorruntime.properties
        @@ -0,0 +1 @@
        +version=${project.version}
        diff --git a/sdk/containerregistry/azure-containers-containerregistry-perf/README.md b/sdk/containerregistry/azure-containers-containerregistry-perf/README.md
        index 73ec380fc539..76a38c055480 100644
        --- a/sdk/containerregistry/azure-containers-containerregistry-perf/README.md
        +++ b/sdk/containerregistry/azure-containers-containerregistry-perf/README.md
        @@ -66,4 +66,4 @@ For details on contributing to this repository, see the [contributing guide](htt
         1. Push to the branch (`git push origin my-new-feature`)
         1. Create new Pull Request
         
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%template%2Fperf-test-core%2FREADME.png)
        +
        diff --git a/sdk/containerregistry/azure-containers-containerregistry-perf/pom.xml b/sdk/containerregistry/azure-containers-containerregistry-perf/pom.xml
        index 805bbc6fac4f..293904f309b9 100644
        --- a/sdk/containerregistry/azure-containers-containerregistry-perf/pom.xml
        +++ b/sdk/containerregistry/azure-containers-containerregistry-perf/pom.xml
        @@ -36,29 +36,29 @@
             
               com.azure
               azure-core
        -      1.54.1 
        +      1.55.3 
             
             
               com.azure
               azure-core-http-netty
        -      1.15.7 
        +      1.15.11 
             
         
             
               com.azure
               azure-core-http-okhttp
        -      1.12.6 
        +      1.12.10 
             
         
             
               com.azure.resourcemanager
               azure-resourcemanager-containerregistry
        -      2.46.0 
        +      2.48.0 
             
             
               com.azure
               azure-identity
        -      1.15.0 
        +      1.15.4 
             
           
         
        diff --git a/sdk/containerregistry/azure-containers-containerregistry/CHANGELOG.md b/sdk/containerregistry/azure-containers-containerregistry/CHANGELOG.md
        index 0af80f151980..0519a59f9961 100644
        --- a/sdk/containerregistry/azure-containers-containerregistry/CHANGELOG.md
        +++ b/sdk/containerregistry/azure-containers-containerregistry/CHANGELOG.md
        @@ -10,6 +10,16 @@
         
         ### Other Changes
         
        +## 1.2.15 (2025-02-25)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`.
        +- Upgraded `azure-json` from `1.3.0` to version `1.4.0`.
        +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`.
        +
         
         ## 1.2.14 (2024-12-04)
         
        diff --git a/sdk/containerregistry/azure-containers-containerregistry/README.md b/sdk/containerregistry/azure-containers-containerregistry/README.md
        index e964298cb3f2..c921a0a747c1 100644
        --- a/sdk/containerregistry/azure-containers-containerregistry/README.md
        +++ b/sdk/containerregistry/azure-containers-containerregistry/README.md
        @@ -56,7 +56,7 @@ and then include the direct dependency in the dependencies section without the v
         
           com.azure
           azure-containers-containerregistry
        -  1.2.0
        +  1.3.0-beta.1
         
         ```
         [//]: # ({x-version-update-end})
        @@ -382,4 +382,4 @@ additional questions or comments.
         [coc]: https://opensource.microsoft.com/codeofconduct/
         [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/
         [coc_contact]: mailto:opencode@microsoft.com
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcontainerregistry%2Fazure-contianers-containerregistry%2FREADME.png)
        +
        diff --git a/sdk/containerregistry/azure-containers-containerregistry/pom.xml b/sdk/containerregistry/azure-containers-containerregistry/pom.xml
        index ccebf75579bd..43b0b6a9ae7e 100644
        --- a/sdk/containerregistry/azure-containers-containerregistry/pom.xml
        +++ b/sdk/containerregistry/azure-containers-containerregistry/pom.xml
        @@ -50,34 +50,34 @@
             
               com.azure
               azure-core
        -      1.54.1 
        +      1.55.3 
             
             
               com.azure
               azure-json
        -      1.3.0 
        +      1.5.0 
             
              
               com.azure
               azure-core-http-netty
        -      1.15.7 
        +      1.15.11 
             
             
               com.azure
               azure-core-test
        -      1.27.0-beta.4 
        +      1.27.0-beta.8 
               test
             
             
               com.azure.resourcemanager
               azure-resourcemanager-containerregistry
        -      2.46.0 
        +      2.48.0 
               test
             
             
               com.azure
               azure-identity
        -      1.15.0 
        +      1.15.4 
               test
             
           
        diff --git a/sdk/containerservicefleet/azure-resourcemanager-containerservicefleet/README.md b/sdk/containerservicefleet/azure-resourcemanager-containerservicefleet/README.md
        index 8beab83c8b60..47abe32d8e37 100644
        --- a/sdk/containerservicefleet/azure-resourcemanager-containerservicefleet/README.md
        +++ b/sdk/containerservicefleet/azure-resourcemanager-containerservicefleet/README.md
        @@ -32,7 +32,7 @@ Various documentation is available to help you get started
         
             com.azure.resourcemanager
             azure-resourcemanager-containerservicefleet
        -    1.2.0-beta.1
        +    1.2.0-beta.2
         
         ```
         [//]: # ({x-version-update-end})
        @@ -108,4 +108,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m
         [coc]: https://opensource.microsoft.com/codeofconduct/
         [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/
         
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcontainerservicefleet%2Fazure-resourcemanager-containerservicefleet%2FREADME.png)
        +
        diff --git a/sdk/containerservicefleet/azure-resourcemanager-containerservicefleet/pom.xml b/sdk/containerservicefleet/azure-resourcemanager-containerservicefleet/pom.xml
        index 91409a6e65fd..8821f5450f1b 100644
        --- a/sdk/containerservicefleet/azure-resourcemanager-containerservicefleet/pom.xml
        +++ b/sdk/containerservicefleet/azure-resourcemanager-containerservicefleet/pom.xml
        @@ -51,29 +51,29 @@
             
               com.azure
               azure-core
        -      1.54.1 
        +      1.55.3 
             
             
               com.azure
               azure-core-management
        -      1.15.6 
        +      1.17.0 
             
             
               com.azure
               azure-core-test
        -      1.27.0-beta.4 
        +      1.27.0-beta.8 
               test
             
             
               com.azure
               azure-identity
        -      1.15.0 
        +      1.15.4 
               test
             
             
               com.azure.resourcemanager
               azure-resourcemanager-resources
        -      2.46.0 
        +      2.48.0 
               test
             
           
        diff --git a/sdk/contentsafety/azure-ai-contentsafety/CHANGELOG.md b/sdk/contentsafety/azure-ai-contentsafety/CHANGELOG.md
        index d48bd1e6076d..23c802ed4b5c 100644
        --- a/sdk/contentsafety/azure-ai-contentsafety/CHANGELOG.md
        +++ b/sdk/contentsafety/azure-ai-contentsafety/CHANGELOG.md
        @@ -10,6 +10,17 @@
         
         ### Other Changes
         
        +
        +## 1.0.10 (2025-02-27)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`.
        +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`.
        +
        +
         ## 1.0.9 (2024-12-04)
         
         ### Other Changes
        diff --git a/sdk/contentsafety/azure-ai-contentsafety/README.md b/sdk/contentsafety/azure-ai-contentsafety/README.md
        index 779e797986ad..bafa14263085 100644
        --- a/sdk/contentsafety/azure-ai-contentsafety/README.md
        +++ b/sdk/contentsafety/azure-ai-contentsafety/README.md
        @@ -28,7 +28,7 @@ Various documentation is available to help you get started
         
             com.azure
             azure-ai-contentsafety
        -    1.0.0
        +    1.1.0-beta.1
         
         ```
         [//]: # ({x-version-update-end})
        @@ -325,4 +325,4 @@ For details on contributing to this repository, see the [contributing guide](htt
         [authenticate_with_microsoft_entra_id]: https://learn.microsoft.com/azure/ai-services/authentication?tabs=powershell#authenticate-with-microsoft-entra-id
         [text_severity_levels]: https://learn.microsoft.com/azure/ai-services/content-safety/concepts/harm-categories?tabs=definitions#text-content
         [image_severity_levels]: https://learn.microsoft.com/azure/ai-services/content-safety/concepts/harm-categories?tabs=definitions#image-content
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcontentsafety%2Fazure-ai-contentsafety%2FREADME.png)
        +
        diff --git a/sdk/contentsafety/azure-ai-contentsafety/pom.xml b/sdk/contentsafety/azure-ai-contentsafety/pom.xml
        index 1b6fd8f73b75..bfbc9bffd40f 100644
        --- a/sdk/contentsafety/azure-ai-contentsafety/pom.xml
        +++ b/sdk/contentsafety/azure-ai-contentsafety/pom.xml
        @@ -54,23 +54,23 @@
             
               com.azure
               azure-core
        -      1.54.1 
        +      1.55.3 
             
             
               com.azure
               azure-core-http-netty
        -      1.15.7 
        +      1.15.11 
             
             
               com.azure
               azure-core-test
        -      1.27.0-beta.4 
        +      1.27.0-beta.8 
               test
             
             
               com.azure
               azure-identity
        -      1.15.0 
        +      1.15.4 
               test
             
           
        diff --git a/sdk/core/README.md b/sdk/core/README.md
        index 460c5cbeb10e..42354b2793a3 100644
        --- a/sdk/core/README.md
        +++ b/sdk/core/README.md
        @@ -29,4 +29,4 @@ Azure Core is split into a number of sub-components:
         
         For documentation on using Azure Core, refer to the [https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/core/azure-core readme](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/core/azure-core).
         
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcore%2FREADME.png)
        +
        diff --git a/sdk/core/azure-core-amqp-experimental/README.md b/sdk/core/azure-core-amqp-experimental/README.md
        index bee99e980230..6235aba04798 100644
        --- a/sdk/core/azure-core-amqp-experimental/README.md
        +++ b/sdk/core/azure-core-amqp-experimental/README.md
        @@ -54,4 +54,4 @@ For details on contributing to this repository, see the [contributing guide](htt
         [jdk_link]: https://learn.microsoft.com/java/azure/jdk/?view=azure-java-stable
         [java8_client_compatibility]: https://learn.microsoft.com/azure/security/fundamentals/azure-ca-details?tabs=root-and-subordinate-cas-list#client-compatibility-for-public-pkis
         
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcore%2Fazure-core-amqp-experimental%2FREADME.png)
        +
        diff --git a/sdk/core/azure-core-amqp/CHANGELOG.md b/sdk/core/azure-core-amqp/CHANGELOG.md
        index dfa3c4c7d866..a5c412cba633 100644
        --- a/sdk/core/azure-core-amqp/CHANGELOG.md
        +++ b/sdk/core/azure-core-amqp/CHANGELOG.md
        @@ -10,6 +10,38 @@
         
         ### Other Changes
         
        +## 2.9.16 (2025-03-10)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.55.2` to `1.55.3`.
        +
        +## 2.9.15 (2025-02-20)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.55.1` to `1.55.2`.
        +
        +## 2.9.14 (2025-02-12)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.55.0` to `1.55.1`.
        +
        +## 2.9.13 (2025-02-06)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.54.1` to `1.55.0`.
        +
         ## 2.9.12 (2024-11-14)
         
         ### Other Changes
        diff --git a/sdk/core/azure-core-amqp/README.md b/sdk/core/azure-core-amqp/README.md
        index e74d47900d3c..775063989ce6 100644
        --- a/sdk/core/azure-core-amqp/README.md
        +++ b/sdk/core/azure-core-amqp/README.md
        @@ -49,7 +49,7 @@ add the direct dependency to your project as follows.
         
             com.azure
             azure-core-amqp
        -    2.9.12
        +    2.9.16
         
         ```
         [//]: # ({x-version-update-end})
        @@ -86,4 +86,4 @@ For details on contributing to this repository, see the [contributing guide](htt
         [jdk_link]: https://learn.microsoft.com/java/azure/jdk/?view=azure-java-stable
         [java8_client_compatibility]: https://learn.microsoft.com/azure/security/fundamentals/azure-ca-details?tabs=root-and-subordinate-cas-list#client-compatibility-for-public-pkis
         
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcore%2Fazure-core-amqp%2FREADME.png)
        +
        diff --git a/sdk/core/azure-core-amqp/pom.xml b/sdk/core/azure-core-amqp/pom.xml
        index 2c64ae5df115..ec83fd0fc059 100644
        --- a/sdk/core/azure-core-amqp/pom.xml
        +++ b/sdk/core/azure-core-amqp/pom.xml
        @@ -77,7 +77,7 @@
             
               com.azure
               azure-core
        -      1.55.0-beta.1 
        +      1.56.0-beta.1 
             
             
               com.microsoft.azure
        @@ -113,7 +113,7 @@
             
               com.azure
               azure-core-test
        -      1.27.0-beta.5  
        +      1.27.0-beta.9  
               test
             
           
        diff --git a/sdk/core/azure-core-experimental/CHANGELOG.md b/sdk/core/azure-core-experimental/CHANGELOG.md
        index e52c2d313d41..53c22bf7f524 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.57 (Unreleased)
        +## 1.0.0-beta.61 (Unreleased)
         
         ### Features Added
         
        @@ -10,6 +10,38 @@
         
         ### Other Changes
         
        +## 1.0.0-beta.60 (2025-03-10)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.55.2` to `1.55.3`.
        +
        +## 1.0.0-beta.59 (2025-02-20)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.55.1` to `1.55.2`.
        +
        +## 1.0.0-beta.58 (2025-02-12)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.55.0` to `1.55.1`.
        +
        +## 1.0.0-beta.57 (2025-02-06)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.54.1` to `1.55.0`.
        +
         ## 1.0.0-beta.56 (2024-11-14)
         
         ### Other Changes
        diff --git a/sdk/core/azure-core-experimental/README.md b/sdk/core/azure-core-experimental/README.md
        index 119694955a38..85d7813057cd 100644
        --- a/sdk/core/azure-core-experimental/README.md
        +++ b/sdk/core/azure-core-experimental/README.md
        @@ -18,7 +18,7 @@ Azure Core Experimental contains types that are being evaluated and might eventu
         
             com.azure
             azure-core-experimental
        -    1.0.0-beta.56
        +    1.0.0-beta.60
         
         ```
         [//]: # ({x-version-update-end})
        @@ -55,4 +55,4 @@ For details on contributing to this repository, see the [contributing guide](htt
         [jdk_link]: https://learn.microsoft.com/java/azure/jdk/?view=azure-java-stable
         [java8_client_compatibility]: https://learn.microsoft.com/azure/security/fundamentals/azure-ca-details?tabs=root-and-subordinate-cas-list#client-compatibility-for-public-pkis
         
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcore%2Fazure-core-experimental%2FREADME.png)
        +
        diff --git a/sdk/core/azure-core-experimental/pom.xml b/sdk/core/azure-core-experimental/pom.xml
        index 396b52856523..173a258936c7 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.57 
        +  1.0.0-beta.61 
         
           Microsoft Azure Java Core Experimental Library
           This package contains experimental core types for Azure Java clients.
        @@ -79,7 +79,7 @@
             
               com.azure
               azure-core
        -      1.55.0-beta.1 
        +      1.56.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 ea423354840e..73bf28d94b7e 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.20 (Unreleased)
        +## 1.1.0-beta.1 (Unreleased)
         
         ### Features Added
         
        @@ -10,6 +10,40 @@
         
         ### Other Changes
         
        +## 1.0.3 (2025-03-10)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.55.2` to `1.55.3`.
        +
        +## 1.0.2 (2025-02-20)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.55.1` to `1.55.2`.
        +
        +## 1.0.1 (2025-02-12)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.55.0` to `1.55.1`.
        +
        +## 1.0.0 (2025-02-06)
        +
        +Initial GA of `azure-core-http-jdk-httpclient`.
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.54.1` to `1.55.0`.
        +
         ## 1.0.0-beta.19 (2024-11-14)
         
         ### Other Changes
        diff --git a/sdk/core/azure-core-http-jdk-httpclient/README.md b/sdk/core/azure-core-http-jdk-httpclient/README.md
        index 9a643da7086c..1a11d355457a 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.19
        +    1.0.3
         
         ```
         [//]: # ({x-version-update-end})
        @@ -83,4 +83,4 @@ For details on contributing to this repository, see the [contributing guide](htt
         [logging]: https://github.com/Azure/azure-sdk-for-java/wiki/Logging-in-Azure-SDK
         [jdk_link]: https://learn.microsoft.com/java/azure/jdk/?view=azure-java-stable
         
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcore%2Fazure-core-http-jdk-httpclient%2FREADME.png)
        +
        diff --git a/sdk/core/azure-core-http-jdk-httpclient/pom.xml b/sdk/core/azure-core-http-jdk-httpclient/pom.xml
        index 750a6d16368d..e8cac4a0492f 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.20 
        +  1.1.0-beta.1 
         
           Microsoft Azure JDK HTTP Client Library
           This package contains the Azure HTTP client library using the JDK HttpClient API.
        @@ -77,14 +77,14 @@
             
               com.azure
               azure-core
        -      1.55.0-beta.1 
        +      1.56.0-beta.1 
             
         
             
             
               com.azure
               azure-core
        -      1.55.0-beta.1 
        +      1.56.0-beta.1 
               tests
               test-jar
               test
        @@ -160,7 +160,7 @@
                   
                     org.apache.maven.plugins
                     maven-surefire-plugin
        -            3.5.1 
        +            3.5.2 
                     
                       true
                     
        @@ -187,7 +187,7 @@
                   
                     org.apache.maven.plugins
                     maven-checkstyle-plugin
        -            3.5.0 
        +            3.6.0 
                     
                       true
                     
        diff --git a/sdk/core/azure-core-http-netty/CHANGELOG.md b/sdk/core/azure-core-http-netty/CHANGELOG.md
        index bfeea4867dfd..7238aa3aa970 100644
        --- a/sdk/core/azure-core-http-netty/CHANGELOG.md
        +++ b/sdk/core/azure-core-http-netty/CHANGELOG.md
        @@ -10,6 +10,37 @@
         
         ### Other Changes
         
        +## 1.15.11 (2025-03-10)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.55.2` to `1.55.3`.
        +
        +## 1.15.10 (2025-02-20)
        +
        +### Other Changes
        +
        +- Fix for the `1.15.9` release as Netty dependencies weren't updated.
        +
        +## 1.15.9 (2025-02-12)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded Netty dependencies from `4.1.115.Final` to `4.1.118.Final` to resolve a CVE.
        +- Upgraded Netty TcNative dependencies from `2.0.69.Final` to `2.0.70.Final` to resolve a CVE.
        +
        +## 1.15.8 (2025-02-06)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.54.1` to `1.55.0`.
        +
         ## 1.15.7 (2024-11-14)
         
         ### Other Changes
        diff --git a/sdk/core/azure-core-http-netty/README.md b/sdk/core/azure-core-http-netty/README.md
        index 3b03ce67c099..c350ccba1036 100644
        --- a/sdk/core/azure-core-http-netty/README.md
        +++ b/sdk/core/azure-core-http-netty/README.md
        @@ -48,7 +48,7 @@ add the direct dependency to your project as follows.
         
             com.azure
             azure-core-http-netty
        -    1.15.7
        +    1.15.11
         
         ```
         [//]: # ({x-version-update-end})
        @@ -148,4 +148,4 @@ For details on contributing to this repository, see the [contributing guide](htt
         [jdk_link]: https://learn.microsoft.com/java/azure/jdk/?view=azure-java-stable
         [java8_client_compatibility]: https://learn.microsoft.com/azure/security/fundamentals/azure-ca-details?tabs=root-and-subordinate-cas-list#client-compatibility-for-public-pkis
         
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcore%2Fazure-core-http-netty%2FREADME.png)
        +
        diff --git a/sdk/core/azure-core-http-netty/pom.xml b/sdk/core/azure-core-http-netty/pom.xml
        index d58697d765c5..261e22aebe05 100644
        --- a/sdk/core/azure-core-http-netty/pom.xml
        +++ b/sdk/core/azure-core-http-netty/pom.xml
        @@ -67,8 +67,8 @@
             spotbugs-exclude.xml
             false
         
        -    4.1.115.Final 
        -    2.0.69.Final 
        +    4.1.118.Final 
        +    2.0.70.Final 
           
         
           
        @@ -82,62 +82,62 @@
             
               com.azure
               azure-core
        -      1.55.0-beta.1 
        +      1.56.0-beta.1 
             
         
             
               io.netty
               netty-handler
        -      4.1.115.Final 
        +      4.1.118.Final 
             
             
               io.netty
               netty-handler-proxy
        -      4.1.115.Final 
        +      4.1.118.Final 
             
             
               io.netty
               netty-buffer
        -      4.1.115.Final 
        +      4.1.118.Final 
             
             
               io.netty
               netty-codec
        -      4.1.115.Final 
        +      4.1.118.Final 
             
             
               io.netty
               netty-codec-http
        -      4.1.115.Final 
        +      4.1.118.Final 
             
         
             
               io.netty
               netty-codec-http2
        -      4.1.115.Final 
        +      4.1.118.Final 
             
             
               io.netty
               netty-transport-native-unix-common
        -      4.1.115.Final 
        +      4.1.118.Final 
             
             
               io.netty
               netty-transport-native-epoll
        -      4.1.115.Final 
        +      4.1.118.Final 
               linux-x86_64
             
             
               io.netty
               netty-transport-native-kqueue
        -      4.1.115.Final 
        +      4.1.118.Final 
               osx-x86_64
             
         
             
               io.netty
               netty-tcnative-boringssl-static
        -      2.0.69.Final 
        +      2.0.70.Final 
               ${boring-ssl-classifier}
             
         
        @@ -150,13 +150,13 @@
             
               io.netty
               netty-common
        -      4.1.115.Final  
        +      4.1.118.Final  
             
             
             
               com.azure
               azure-core
        -      1.55.0-beta.1 
        +      1.56.0-beta.1 
               tests
               test-jar
               test
        @@ -211,18 +211,18 @@
                   
                     
                       
        -                io.netty:netty-tcnative-boringssl-static:[2.0.69.Final] 
        +                io.netty:netty-tcnative-boringssl-static:[2.0.70.Final] 
                         io.projectreactor.netty:reactor-netty-http:[1.0.48] 
        -                io.netty:netty-buffer:[4.1.115.Final] 
        -                io.netty:netty-common:[4.1.115.Final] 
        -                io.netty:netty-codec:[4.1.115.Final] 
        -                io.netty:netty-codec-http:[4.1.115.Final] 
        -                io.netty:netty-codec-http2:[4.1.115.Final] 
        -                io.netty:netty-handler:[4.1.115.Final] 
        -                io.netty:netty-handler-proxy:[4.1.115.Final] 
        -                io.netty:netty-transport-native-unix-common:[4.1.115.Final] 
        -                io.netty:netty-transport-native-epoll:[4.1.115.Final] 
        -                io.netty:netty-transport-native-kqueue:[4.1.115.Final] 
        +                io.netty:netty-buffer:[4.1.118.Final] 
        +                io.netty:netty-common:[4.1.118.Final] 
        +                io.netty:netty-codec:[4.1.118.Final] 
        +                io.netty:netty-codec-http:[4.1.118.Final] 
        +                io.netty:netty-codec-http2:[4.1.118.Final] 
        +                io.netty:netty-handler:[4.1.118.Final] 
        +                io.netty:netty-handler-proxy:[4.1.118.Final] 
        +                io.netty:netty-transport-native-unix-common:[4.1.118.Final] 
        +                io.netty:netty-transport-native-epoll:[4.1.118.Final] 
        +                io.netty:netty-transport-native-kqueue:[4.1.118.Final] 
                       
                     
                   
        diff --git a/sdk/core/azure-core-http-okhttp/CHANGELOG.md b/sdk/core/azure-core-http-okhttp/CHANGELOG.md
        index 6c43143566b8..9960729de133 100644
        --- a/sdk/core/azure-core-http-okhttp/CHANGELOG.md
        +++ b/sdk/core/azure-core-http-okhttp/CHANGELOG.md
        @@ -10,6 +10,38 @@
         
         ### Other Changes
         
        +## 1.12.10 (2025-03-10)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.55.2` to `1.55.3`.
        +
        +## 1.12.9 (2025-02-20)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.55.1` to `1.55.2`.
        +
        +## 1.12.8 (2025-02-12)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.55.0` to `1.55.1`.
        +
        +## 1.12.7 (2025-02-06)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.54.1` to `1.55.0`.
        +
         ## 1.12.6 (2024-11-14)
         
         ### Bugs Fixed
        diff --git a/sdk/core/azure-core-http-okhttp/README.md b/sdk/core/azure-core-http-okhttp/README.md
        index ea4b04fa83d2..afea1c4b5942 100644
        --- a/sdk/core/azure-core-http-okhttp/README.md
        +++ b/sdk/core/azure-core-http-okhttp/README.md
        @@ -48,7 +48,7 @@ add the direct dependency to your project as follows.
         
             com.azure
             azure-core-http-okhttp
        -    1.12.6
        +    1.12.10
         
         ```
         [//]: # ({x-version-update-end})
        @@ -133,4 +133,4 @@ For details on contributing to this repository, see the [contributing guide](htt
         [jdk_link]: https://learn.microsoft.com/java/azure/jdk/?view=azure-java-stable
         [java8_client_compatibility]: https://learn.microsoft.com/azure/security/fundamentals/azure-ca-details?tabs=root-and-subordinate-cas-list#client-compatibility-for-public-pkis
         
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcore%2Fazure-core-http-okhttp%2FREADME.png)
        +
        diff --git a/sdk/core/azure-core-http-okhttp/pom.xml b/sdk/core/azure-core-http-okhttp/pom.xml
        index f7cf0c0684f5..f5a4c1402866 100644
        --- a/sdk/core/azure-core-http-okhttp/pom.xml
        +++ b/sdk/core/azure-core-http-okhttp/pom.xml
        @@ -78,7 +78,7 @@
             
               com.azure
               azure-core
        -      1.55.0-beta.1 
        +      1.56.0-beta.1 
             
         
             
        @@ -103,7 +103,7 @@
             
               com.azure
               azure-core
        -      1.55.0-beta.1 
        +      1.56.0-beta.1 
               tests
               test-jar
               test
        diff --git a/sdk/core/azure-core-http-vertx/CHANGELOG.md b/sdk/core/azure-core-http-vertx/CHANGELOG.md
        index 9cf277e0412a..c0c320adeb59 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.25 (Unreleased)
        +## 1.1.0-beta.1 (Unreleased)
         
         ### Features Added
         
        @@ -10,6 +10,47 @@
         
         ### Other Changes
         
        +## 1.0.3 (2025-03-10)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.55.2` to `1.55.3`.
        +- Upgraded `vertx-codegen` from `4.5.10` to `4.5.13`.
        +
        +## 1.0.2 (2025-02-20)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.55.1` to `1.55.2`.
        +
        +## 1.0.1 (2025-02-12)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.55.0` to `1.55.1`.
        +
        +## 1.0.0 (2025-02-06)
        +
        +Initial GA of `azure-core-http-vertx`.
        +
        +### Bugs Fixed
        +
        +- Fixed a bug where a request would fail with `IllegalStateException("Result is already complete")` when multiple
        +  exceptions happened during the request. When multiple exceptions happen, the first exception is now thrown and 
        +  subsequent exceptions are added to the suppressed exceptions of the first exception. ([#43402](https://github.com/Azure/azure-sdk-for-java/pull/43402))
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.54.1` to `1.55.0`.
        +
         ## 1.0.0-beta.24 (2024-11-14)
         
         ### Other Changes
        diff --git a/sdk/core/azure-core-http-vertx/README.md b/sdk/core/azure-core-http-vertx/README.md
        index 94182d9fb0d3..afc3c535a7bc 100644
        --- a/sdk/core/azure-core-http-vertx/README.md
        +++ b/sdk/core/azure-core-http-vertx/README.md
        @@ -17,7 +17,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.24
        +    1.0.3
           
         
         ```
        @@ -86,4 +86,4 @@ For details on contributing to this repository, see the [contributing guide](htt
         [jdk_link]: https://learn.microsoft.com/java/azure/jdk/?view=azure-java-stable
         [java8_client_compatibility]: https://learn.microsoft.com/azure/security/fundamentals/azure-ca-details?tabs=root-and-subordinate-cas-list#client-compatibility-for-public-pkis
         
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcore%2Fazure-core-http-vertx%2FREADME.png)
        +
        diff --git a/sdk/core/azure-core-http-vertx/pom.xml b/sdk/core/azure-core-http-vertx/pom.xml
        index f79ffbf3e98e..0fa8817a44c5 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.25 
        +  1.1.0-beta.1 
         
           Microsoft Azure Vert.x HTTP Client Library
           This package contains the Vert.x HTTP client plugin for azure-core.
        @@ -78,28 +78,28 @@
             
               com.azure
               azure-core
        -      1.55.0-beta.1 
        +      1.56.0-beta.1 
             
         
             
             
               io.vertx
               vertx-codegen
        -      4.5.10 
        +      4.5.13 
               provided
             
         
             
               io.vertx
               vertx-core
        -      4.5.10 
        +      4.5.13 
             
         
             
             
               com.azure
               azure-core
        -      1.55.0-beta.1 
        +      1.56.0-beta.1 
               tests
               test-jar
               test
        @@ -175,8 +175,8 @@
                   
                     
                       
        -                io.vertx:vertx-codegen:[4.5.10] 
        -                io.vertx:vertx-core:[4.5.10] 
        +                io.vertx:vertx-codegen:[4.5.13] 
        +                io.vertx:vertx-core:[4.5.13] 
                       
                     
                   
        diff --git a/sdk/core/azure-core-management/CHANGELOG.md b/sdk/core/azure-core-management/CHANGELOG.md
        index 1a2a233cb7fd..097f7865fe40 100644
        --- a/sdk/core/azure-core-management/CHANGELOG.md
        +++ b/sdk/core/azure-core-management/CHANGELOG.md
        @@ -1,17 +1,55 @@
         # Release History
         
        -## 1.16.0-beta.1 (Unreleased)
        +## 1.18.0-beta.1 (Unreleased)
         
         ### Features Added
         
        -- Added `AzureProfile(AzureCloud azureCloud)` constructor overload.
        -
         ### Breaking Changes
         
         ### Bugs Fixed
         
         ### Other Changes
         
        +## 1.17.0 (2025-03-10)
        +
        +### Features Added
        +
        +- Added sync-stack support `SyncPollerFactory`, for Azure Resource Manager(ARM) long-running-operation(LRO).
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.55.2` to `1.55.3`.
        +
        +## 1.16.2 (2025-02-20)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.55.1` to `1.55.2`.
        +
        +## 1.16.1 (2025-02-12)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.55.0` to `1.55.1`.
        +
        +## 1.16.0 (2025-02-06)
        +
        +### Features Added
        +
        +- Added `AzureProfile(AzureCloud azureCloud)` constructor overload.
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.54.1` to `1.55.0`.
        +
         ## 1.15.6 (2024-11-14)
         
         ### Other Changes
        diff --git a/sdk/core/azure-core-management/README.md b/sdk/core/azure-core-management/README.md
        index c01e0eabd85b..ae6e10505fdd 100644
        --- a/sdk/core/azure-core-management/README.md
        +++ b/sdk/core/azure-core-management/README.md
        @@ -16,7 +16,7 @@ Azure Core Management library is a collection of classes common to the [Azure Re
         
             com.azure
             azure-core-management
        -    1.15.6
        +    1.17.0
         
         ```
         [//]: # ({x-version-update-end})
        @@ -61,4 +61,4 @@ For details on contributing to this repository, see the [contributing guide](htt
         [jdk_link]: https://learn.microsoft.com/java/azure/jdk/?view=azure-java-stable
         [java8_client_compatibility]: https://learn.microsoft.com/azure/security/fundamentals/azure-ca-details?tabs=root-and-subordinate-cas-list#client-compatibility-for-public-pkis
         
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcore%2Fazure-core-management%2FREADME.png)
        +
        diff --git a/sdk/core/azure-core-management/pom.xml b/sdk/core/azure-core-management/pom.xml
        index a78dbde0e120..fe5c5fb3d919 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.16.0-beta.1 
        +  1.18.0-beta.1 
           jar
         
           Microsoft Azure Management Java Core Library
        @@ -76,13 +76,13 @@
             
               com.azure
               azure-core
        -      1.55.0-beta.1 
        +      1.56.0-beta.1 
             
         
             
               com.azure
               azure-json
        -      1.3.0 
        +      1.5.0 
             
         
             
        @@ -97,6 +97,12 @@
               5.11.2 
               test
             
        +    
        +      org.junit.jupiter
        +      junit-jupiter-params
        +      5.11.2 
        +      test
        +    
             
               io.projectreactor
               reactor-test
        diff --git a/sdk/core/azure-core-management/src/main/java/com/azure/core/management/implementation/polling/PollOperation.java b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/implementation/polling/PollOperation.java
        index 9e15e450f1a5..95f27338c78b 100644
        --- a/sdk/core/azure-core-management/src/main/java/com/azure/core/management/implementation/polling/PollOperation.java
        +++ b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/implementation/polling/PollOperation.java
        @@ -50,12 +50,14 @@ public final class PollOperation {
                 return pollingContext -> {
                     PollingState pollingState = PollingState.from(serializerAdapter, pollingContext);
                     if (pollingState.getOperationStatus().isComplete()) {
        -                return pollResponseMonoFromPollingState(serializerAdapter, pollResultType, pollingState);
        +                return Mono.defer(
        +                    () -> Mono.just(pollResponseFromPollingState(serializerAdapter, pollResultType, pollingState)));
                     } else {
                         // InProgress|NonTerminal-Status
                         return doSinglePoll(pipeline, pollingState, context).flatMap(updatedState -> {
                             updatedState.store(pollingContext);
        -                    return pollResponseMonoFromPollingState(serializerAdapter, pollResultType, updatedState);
        +                    return Mono.defer(
        +                        () -> Mono.just(pollResponseFromPollingState(serializerAdapter, pollResultType, updatedState)));
                         });
                     }
                 };
        @@ -116,37 +118,6 @@ public static  Function>, Mono> fetchResul
                 };
             }
         
        -    /**
        -     * Create a PollResponse indicating service error.
        -     *
        -     * @param opStatus the long-running-operation errored status
        -     * @param error the error description
        -     * @param  the poll result type
        -     * @return PollResponse
        -     */
        -    private static  Mono>> errorPollResponseMono(LongRunningOperationStatus opStatus,
        -        Error error) {
        -        PollResult pollResult = new PollResult<>(new PollResult.Error(error.getMessage(),
        -            error.getResponseStatusCode(), new HttpHeaders(error.getResponseHeaders()), error.getResponseBody()));
        -        return Mono.just(new PollResponse<>(opStatus, pollResult));
        -    }
        -
        -    /**
        -     * Create a PollResponse indicating succeeded or in-progress LRO.
        -     *
        -     * @param serializerAdapter the serializer for any encoding and decoding
        -     * @param opStatus the long-running-operation succeeded or in-progress status
        -     * @param pollResponseBody the poll response body
        -     * @param pollResultType the poll result type
        -     * @param  the poll result type
        -     * @return PollResponse
        -     */
        -    private static  Mono>> pollResponseMono(SerializerAdapter serializerAdapter,
        -        LongRunningOperationStatus opStatus, String pollResponseBody, Type pollResultType, Duration pollDelay) {
        -        T result = deserialize(serializerAdapter, pollResponseBody, pollResultType);
        -        return Mono.just(new PollResponse<>(opStatus, new PollResult(result), pollDelay));
        -    }
        -
             /**
              * Do a poll to retrieve the LRO status.
              *
        @@ -170,34 +141,72 @@ private static Mono doSinglePoll(HttpPipeline pipeline, PollingSta
                             .fromSupplier(() -> pollingState.update(response.getStatusCode(), response.getHeaders(), null))));
             }
         
        -    private static  Mono>> pollResponseMonoFromPollingState(
        -        SerializerAdapter serializerAdapter, Type pollResultType, PollingState pollingState) {
        +    /**
        +     * Gets the latest poll response from PollingState.
        +     *
        +     * @param serializerAdapter the serializer for any encoding and decoding
        +     * @param pollResultType the poll result type
        +     * @param pollingState the polling state
        +     * @param  the poll result type
        +     * @return the latest poll response
        +     */
        +    static  PollResponse> pollResponseFromPollingState(SerializerAdapter serializerAdapter,
        +        Type pollResultType, PollingState pollingState) {
                 if (pollingState.getOperationStatus().isComplete()) {
                     if (pollingState.getOperationStatus() == LongRunningOperationStatus.FAILED
                         || pollingState.getOperationStatus() == LRO_CANCELLED) {
                         // Failed|Cancelled
                         Error lroInitError = pollingState.getSynchronouslyFailedLroError();
                         if (lroInitError != null) {
        -                    return errorPollResponseMono(pollingState.getOperationStatus(), lroInitError);
        +                    return errorPollResponse(pollingState.getOperationStatus(), lroInitError);
                         }
                         Error pollError = pollingState.getPollError();
                         if (pollError != null) {
        -                    return errorPollResponseMono(pollingState.getOperationStatus(), pollError);
        +                    return errorPollResponse(pollingState.getOperationStatus(), pollError);
                         }
                         throw new IllegalStateException(
                             "Either LroError or PollError must" + "be set when OperationStatus is in Failed|Cancelled State.");
                     } else {
                         // Succeeded
        -                return pollResponseMono(serializerAdapter, pollingState.getOperationStatus(),
        +                return pollResponse(serializerAdapter, pollingState.getOperationStatus(),
                             pollingState.getLastResponseBody(), pollResultType, pollingState.getPollDelay());
                     }
                 } else {
                     // InProgress|NonTerminal-Status
        -            return pollResponseMono(serializerAdapter, pollingState.getOperationStatus(),
        +            return pollResponse(serializerAdapter, pollingState.getOperationStatus(),
                         pollingState.getLastResponseBody(), pollResultType, pollingState.getPollDelay());
                 }
             }
         
        +    /**
        +     * Create a PollResponse indicating succeeded or in-progress LRO.
        +     *
        +     * @param serializerAdapter the serializer for any encoding and decoding
        +     * @param operationStatus the long-running-operation succeeded or in-progress status
        +     * @param pollResponseBody the poll response body
        +     * @param pollResultType the poll result type
        +     * @param  the poll result type
        +     * @return PollResponse
        +     */
        +    static  PollResponse> pollResponse(SerializerAdapter serializerAdapter,
        +        LongRunningOperationStatus operationStatus, String pollResponseBody, Type pollResultType, Duration pollDelay) {
        +        T result = deserialize(serializerAdapter, pollResponseBody, pollResultType);
        +        return new PollResponse<>(operationStatus, new PollResult<>(result), pollDelay);
        +    }
        +
        +    /**
        +     * Create a PollResponse indicating service error.
        +     *
        +     * @param operationStatus the long-running-operation errored status
        +     * @param error the error description
        +     * @param  the poll result type
        +     * @return PollResponse
        +     */
        +    static  PollResponse> errorPollResponse(LongRunningOperationStatus operationStatus, Error error) {
        +        return new PollResponse<>(operationStatus, new PollResult<>(new PollResult.Error(error.getMessage(),
        +            error.getResponseStatusCode(), new HttpHeaders(error.getResponseHeaders()), error.getResponseBody())));
        +    }
        +
             /**
              * Decorate the request.
              *
        diff --git a/sdk/core/azure-core-management/src/main/java/com/azure/core/management/implementation/polling/SyncPollOperation.java b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/implementation/polling/SyncPollOperation.java
        new file mode 100644
        index 000000000000..54b9c4ae6d4c
        --- /dev/null
        +++ b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/implementation/polling/SyncPollOperation.java
        @@ -0,0 +1,123 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +
        +package com.azure.core.management.implementation.polling;
        +
        +import com.azure.core.http.HttpMethod;
        +import com.azure.core.http.HttpPipeline;
        +import com.azure.core.http.HttpRequest;
        +import com.azure.core.http.HttpResponse;
        +import com.azure.core.http.rest.Response;
        +import com.azure.core.management.polling.PollResult;
        +import com.azure.core.util.BinaryData;
        +import com.azure.core.util.Context;
        +import com.azure.core.util.polling.PollResponse;
        +import com.azure.core.util.polling.PollingContext;
        +import com.azure.core.util.serializer.SerializerAdapter;
        +
        +import java.lang.reflect.Type;
        +import java.util.function.BiFunction;
        +import java.util.function.Function;
        +import java.util.function.Supplier;
        +
        +/**
        + * Synchronous poll operation for Azure resource manager (ARM) long-running-operation (LRO).
        + */
        +public final class SyncPollOperation {
        +    /**
        +     * Gets a Function that starts the Azure resource manager(ARM) long-running-operation(LRO).
        +     *
        +     * @param serializerAdapter the serializer for any encoding and decoding
        +     * @param pollResultType the type of the poll result, if no result is expecting then this should be Void.class
        +     * @param lroInitialResponseSupplier Supplier of the activation operation to activate (start) the long-running operation
        +     * @param  the type of poll result
        +     * @return the ARM LRO activation Function
        +     */
        +    public static  Function>, PollResponse>> activationFunction(
        +        SerializerAdapter serializerAdapter, Type pollResultType,
        +        Supplier> lroInitialResponseSupplier) {
        +        return pollingContext -> {
        +            Response response = lroInitialResponseSupplier.get();
        +            PollingState state = PollingState.create(serializerAdapter, response.getRequest(), response.getStatusCode(),
        +                response.getHeaders(), response.getValue().toString());
        +            state.store(pollingContext);
        +            T result = PollOperation.deserialize(serializerAdapter, response.getValue().toString(), pollResultType);
        +            return new PollResponse<>(state.getOperationStatus(), new PollResult<>(result), state.getPollDelay());
        +        };
        +    }
        +
        +    /**
        +     * Gets a Function that polls provisioning state of ARM resource.
        +     *
        +     * @param serializerAdapter the serializer for any encoding and decoding
        +     * @param httpPipeline the HttpPipeline for making poll request
        +     * @param pollResultType the type of the poll result
        +     * @param context the context
        +     * @param  the type of poll result type
        +     * @return the ARM poll function
        +     */
        +    public static  Function>, PollResponse>> pollFunction(
        +        SerializerAdapter serializerAdapter, HttpPipeline httpPipeline, Type pollResultType, Context context) {
        +        return pollingContext -> {
        +            PollingState state = PollingState.from(serializerAdapter, pollingContext);
        +            if (state.getOperationStatus().isComplete()) {
        +                return PollOperation.pollResponseFromPollingState(serializerAdapter, pollResultType, state);
        +            } else {
        +                try (HttpResponse response
        +                    = httpPipeline.sendSync(new HttpRequest(HttpMethod.GET, state.getPollUrl()), context)) {
        +                    String body = response.getBodyAsBinaryData().toString();
        +                    state.update(response.getStatusCode(), response.getHeaders(), body);
        +                    state.store(pollingContext);
        +                    return PollOperation.pollResponseFromPollingState(serializerAdapter, pollResultType, state);
        +                }
        +            }
        +        };
        +    }
        +
        +    /**
        +     * Currently there is no option to cancel an ARM LRO in generic way, this is NOP.
        +     *
        +     * @param context the context
        +     * @param  the type of poll result type
        +     * @return cancel Function
        +     */
        +    public static  BiFunction>, PollResponse>, PollResult>
        +        cancelFunction(Context context) {
        +        return (pollingContext, pollResultPollResponse) -> null;
        +    }
        +
        +    /**
        +     * Gets a Function that retrieves final result of a LRO.
        +     *
        +     * @param serializerAdapter the serializer for any encoding and decoding
        +     * @param httpPipeline the HttpPipeline for fetching final result
        +     * @param finalResultType the final result type
        +     * @param context the context
        +     * @param  the final result type
        +     * @param  the poll result type
        +     * @return retrieve final LRO result Function
        +     */
        +    public static  Function, U> fetchResultFunction(SerializerAdapter serializerAdapter,
        +        HttpPipeline httpPipeline, Type finalResultType, Context context) {
        +        return pollingContext -> {
        +            PollingState state = PollingState.from(serializerAdapter, pollingContext);
        +            FinalResult finalResult = state.getFinalResult();
        +            if (finalResult == null) {
        +                return null;
        +            } else {
        +                String value = finalResult.getResult();
        +                U result;
        +                if (value != null) {
        +                    result = PollOperation.deserialize(serializerAdapter, value, finalResultType);
        +                } else {
        +                    try (HttpResponse response
        +                        = httpPipeline.sendSync(new HttpRequest(HttpMethod.GET, finalResult.getResultUri()), context)) {
        +                        result = PollOperation.deserialize(serializerAdapter, response.getBodyAsBinaryData().toString(),
        +                            finalResultType);
        +                    }
        +                }
        +                return result;
        +            }
        +        };
        +    }
        +}
        diff --git a/sdk/core/azure-core-management/src/main/java/com/azure/core/management/polling/SyncPollerFactory.java b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/polling/SyncPollerFactory.java
        new file mode 100644
        index 000000000000..f325f3825179
        --- /dev/null
        +++ b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/polling/SyncPollerFactory.java
        @@ -0,0 +1,71 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +
        +package com.azure.core.management.polling;
        +
        +import com.azure.core.http.HttpPipeline;
        +import com.azure.core.http.rest.Response;
        +import com.azure.core.management.implementation.polling.SyncPollOperation;
        +import com.azure.core.util.BinaryData;
        +import com.azure.core.util.Context;
        +import com.azure.core.util.polling.SyncPoller;
        +import com.azure.core.util.serializer.SerializerAdapter;
        +
        +import java.lang.reflect.Type;
        +import java.time.Duration;
        +import java.util.function.Supplier;
        +
        +/**
        + * Factory to create SyncPoller for Azure Resource Manager (ARM) long-running-operation (LRO).
        + */
        +public final class SyncPollerFactory {
        +
        +    private SyncPollerFactory() {
        +    }
        +
        +    /**
        +     * Creates a SyncPoller with ARM LRO init operation.
        +     *
        +     * @param serializerAdapter the serializer for any encoding and decoding
        +     * @param httpPipeline the HttpPipeline for making any Http request (e.g. poll)
        +     * @param pollResultType the type of the poll result, if no result is expecting then this should be Void.class
        +     * @param finalResultType the type of the final result, if no result is expecting then this should be Void.class
        +     * @param defaultPollDuration the default poll interval to use if service does not return retry-after
        +     * @param lroInitialResponseSupplier Supplier of the activation operation to activate (start) the long-running operation. This operation
        +     *        will be invoked at most once.
        +     * @param  the type of poll result
        +     * @param  the type of final result
        +     * @return SyncPoller
        +     */
        +    public static  SyncPoller, U> create(SerializerAdapter serializerAdapter,
        +        HttpPipeline httpPipeline, Type pollResultType, Type finalResultType, Duration defaultPollDuration,
        +        Supplier> lroInitialResponseSupplier) {
        +        return create(serializerAdapter, httpPipeline, pollResultType, finalResultType, defaultPollDuration,
        +            lroInitialResponseSupplier, Context.NONE);
        +    }
        +
        +    /**
        +     * Creates a SyncPoller with ARM LRO init operation.
        +     *
        +     * @param serializerAdapter the serializer for any encoding and decoding
        +     * @param httpPipeline the HttpPipeline for making any Http request (e.g. poll)
        +     * @param pollResultType the type of the poll result, if no result is expecting then this should be Void.class
        +     * @param finalResultType the type of the final result, if no result is expecting then this should be Void.class
        +     * @param defaultPollDuration the default poll interval to use if service does not return retry-after
        +     * @param lroInitialResponseSupplier Supplier of the activation operation to activate (start) the long-running operation. This operation
        +     *        will be invoked at most once.
        +     * @param context the context shared by all requests
        +     * @param  the type of poll result
        +     * @param  the type of final result
        +     * @return SyncPoller
        +     */
        +    public static  SyncPoller, U> create(SerializerAdapter serializerAdapter,
        +        HttpPipeline httpPipeline, Type pollResultType, Type finalResultType, Duration defaultPollDuration,
        +        Supplier> lroInitialResponseSupplier, Context context) {
        +        return SyncPoller.createPoller(defaultPollDuration,
        +            SyncPollOperation.activationFunction(serializerAdapter, pollResultType, lroInitialResponseSupplier),
        +            SyncPollOperation.pollFunction(serializerAdapter, httpPipeline, pollResultType, context),
        +            SyncPollOperation.cancelFunction(context),
        +            SyncPollOperation.fetchResultFunction(serializerAdapter, httpPipeline, finalResultType, context));
        +    }
        +}
        diff --git a/sdk/core/azure-core-management/src/main/java/com/azure/core/management/profile/AzureProfile.java b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/profile/AzureProfile.java
        index a6c66978a10d..38236e7af16c 100644
        --- a/sdk/core/azure-core-management/src/main/java/com/azure/core/management/profile/AzureProfile.java
        +++ b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/profile/AzureProfile.java
        @@ -25,7 +25,7 @@ public final class AzureProfile {
             static {
                 ENDPOINT_MAP.put(AzureCloud.AZURE_PUBLIC_CLOUD, AzureEnvironment.AZURE);
                 ENDPOINT_MAP.put(AzureCloud.AZURE_CHINA_CLOUD, AzureEnvironment.AZURE_CHINA);
        -        ENDPOINT_MAP.put(AzureCloud.AZURE_US_GOVERNMENT, AzureEnvironment.AZURE_US_GOVERNMENT);
        +        ENDPOINT_MAP.put(AzureCloud.AZURE_US_GOVERNMENT_CLOUD, AzureEnvironment.AZURE_US_GOVERNMENT);
             }
         
             /**
        diff --git a/sdk/core/azure-core-management/src/test/java/com/azure/core/management/AzureProfileTests.java b/sdk/core/azure-core-management/src/test/java/com/azure/core/management/AzureProfileTests.java
        index e019160dee41..71b3774fa110 100644
        --- a/sdk/core/azure-core-management/src/test/java/com/azure/core/management/AzureProfileTests.java
        +++ b/sdk/core/azure-core-management/src/test/java/com/azure/core/management/AzureProfileTests.java
        @@ -20,7 +20,7 @@ public void testFromAzureCloud() {
                 AzureProfile azureChinaCloud = new AzureProfile(AzureCloud.AZURE_CHINA_CLOUD);
                 Assertions.assertEquals(AzureEnvironment.AZURE_CHINA, azureChinaCloud.getEnvironment());
         
        -        AzureProfile azureUSGovernment = new AzureProfile(AzureCloud.AZURE_US_GOVERNMENT);
        +        AzureProfile azureUSGovernment = new AzureProfile(AzureCloud.AZURE_US_GOVERNMENT_CLOUD);
                 Assertions.assertEquals(AzureEnvironment.AZURE_US_GOVERNMENT, azureUSGovernment.getEnvironment());
         
                 // exception case
        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 031ed96e6cd0..8bb9a236b5aa 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
        @@ -18,6 +18,7 @@
         import com.azure.core.management.Resource;
         import com.azure.core.management.polling.PollResult;
         import com.azure.core.management.polling.PollerFactory;
        +import com.azure.core.management.polling.SyncPollerFactory;
         import com.azure.core.management.serializer.SerializerFactory;
         import com.azure.core.util.BinaryData;
         import com.azure.core.util.Context;
        @@ -26,7 +27,9 @@
         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.PollResponse;
         import com.azure.core.util.polling.PollerFlux;
        +import com.azure.core.util.polling.SyncPoller;
         import com.azure.core.util.serializer.SerializerAdapter;
         import com.azure.core.util.serializer.SerializerEncoding;
         import com.github.tomakehurst.wiremock.WireMockServer;
        @@ -41,9 +44,13 @@
         import com.github.tomakehurst.wiremock.http.RequestMethod;
         import org.junit.jupiter.api.Assertions;
         import org.junit.jupiter.api.Test;
        +import org.junit.jupiter.params.ParameterizedTest;
        +import org.junit.jupiter.params.provider.ValueSource;
         import reactor.core.publisher.Flux;
         import reactor.core.publisher.Mono;
         import reactor.test.StepVerifier;
        +import wiremock.com.google.common.util.concurrent.SimpleTimeLimiter;
        +import wiremock.com.google.common.util.concurrent.TimeLimiter;
         
         import java.io.IOException;
         import java.net.MalformedURLException;
        @@ -58,6 +65,7 @@
         import java.util.List;
         import java.util.Optional;
         import java.util.UUID;
        +import java.util.concurrent.Executors;
         import java.util.concurrent.TimeoutException;
         import java.util.concurrent.atomic.AtomicInteger;
         
        @@ -74,36 +82,62 @@ public class LROPollerTests {
             interface ProvisioningStateLroServiceClient {
                 @Put("/resource/1")
                 Mono>> startLro(Context context);
        +
        +        @Put("/resource/1")
        +        Response startLroSync(Context context);
             }
         
        -    @Test
        -    public void lroBasedOnProvisioningState() {
        +    @ParameterizedTest
        +    @ValueSource(booleans = { true, false })
        +    public void lroBasedOnProvisioningState(boolean syncStack) {
                 WireMockServer lroServer = startServer();
         
                 try {
                     final ProvisioningStateLroServiceClient client = RestProxy.create(ProvisioningStateLroServiceClient.class,
                         createHttpPipeline(lroServer.port()), SERIALIZER);
        -
        -            PollerFlux, FooWithProvisioningState> lroFlux
        -                = PollerFactory.create(SERIALIZER, new HttpPipelineBuilder().build(), FooWithProvisioningState.class,
        -                    FooWithProvisioningState.class, POLLING_DURATION, newLroInitFunction(client));
        -
        -            int[] onNextCallCount = new int[1];
        -            lroFlux.doOnNext(response -> {
        -                PollResult pollResult = response.getValue();
        -                Assertions.assertNotNull(pollResult);
        -                Assertions.assertNotNull(pollResult.getValue());
        -                onNextCallCount[0]++;
        -                if (onNextCallCount[0] == 1) {
        -                    Assertions.assertEquals(LongRunningOperationStatus.IN_PROGRESS, response.getStatus());
        -                    Assertions.assertNull(pollResult.getValue().getResourceId());
        -                } else if (onNextCallCount[0] == 2) {
        -                    Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, response.getStatus());
        -                    Assertions.assertNotNull(pollResult.getValue().getResourceId());
        -                } else {
        -                    throw new IllegalStateException("Poller emitted more than expected value.");
        +            if (syncStack) {
        +                SyncPoller, FooWithProvisioningState> syncPoller
        +                    = SyncPollerFactory.create(SERIALIZER, new HttpPipelineBuilder().build(),
        +                        FooWithProvisioningState.class, FooWithProvisioningState.class, POLLING_DURATION,
        +                        () -> newLroInitResponse(client));
        +
        +                for (int i = 0; i < 2; i++) {
        +                    PollResponse> pollResponse = syncPoller.poll();
        +                    PollResult pollResult = pollResponse.getValue();
        +                    Assertions.assertNotNull(pollResult);
        +                    Assertions.assertNotNull(pollResult.getValue());
        +                    if (i == 0) {
        +                        Assertions.assertEquals(LongRunningOperationStatus.IN_PROGRESS, pollResponse.getStatus());
        +                        Assertions.assertNull(pollResult.getValue().getResourceId());
        +                    } else {
        +                        Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED,
        +                            pollResponse.getStatus());
        +                        Assertions.assertNotNull(pollResult.getValue().getResourceId());
        +                    }
                         }
        -            }).blockLast();
        +            } else {
        +                PollerFlux, FooWithProvisioningState> lroFlux = PollerFactory
        +                    .create(SERIALIZER, new HttpPipelineBuilder().build(), FooWithProvisioningState.class,
        +                        FooWithProvisioningState.class, POLLING_DURATION, newLroInitFunction(client));
        +
        +                int[] onNextCallCount = new int[1];
        +                lroFlux.doOnNext(response -> {
        +                    PollResult pollResult = response.getValue();
        +                    Assertions.assertNotNull(pollResult);
        +                    Assertions.assertNotNull(pollResult.getValue());
        +                    onNextCallCount[0]++;
        +                    if (onNextCallCount[0] == 1) {
        +                        Assertions.assertEquals(LongRunningOperationStatus.IN_PROGRESS, response.getStatus());
        +                        Assertions.assertNull(pollResult.getValue().getResourceId());
        +                    } else if (onNextCallCount[0] == 2) {
        +                        Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED,
        +                            response.getStatus());
        +                        Assertions.assertNotNull(pollResult.getValue().getResourceId());
        +                    } else {
        +                        throw new IllegalStateException("Poller emitted more than expected value.");
        +                    }
        +                }).blockLast();
        +            }
                 } finally {
                     if (lroServer.isRunning()) {
                         lroServer.shutdown();
        @@ -111,8 +145,9 @@ public void lroBasedOnProvisioningState() {
                 }
             }
         
        -    @Test
        -    public void lroBasedOnAsyncOperation() {
        +    @ParameterizedTest
        +    @ValueSource(booleans = { true, false })
        +    public void lroBasedOnAsyncOperation(boolean syncStack) {
                 ServerConfigure serverConfigure = new ServerConfigure();
         
                 final String resourceEndpoint = "/resource/1";
        @@ -177,31 +212,53 @@ public String getName() {
                 try {
                     final ProvisioningStateLroServiceClient client = RestProxy.create(ProvisioningStateLroServiceClient.class,
                         createHttpPipeline(lroServer.port()), SERIALIZER);
        -
        -            PollerFlux, FooWithProvisioningState> lroFlux
        -                = PollerFactory.create(SERIALIZER, new HttpPipelineBuilder().build(), FooWithProvisioningState.class,
        -                    FooWithProvisioningState.class, POLLING_DURATION, newLroInitFunction(client));
        -
        -            int[] onNextCallCount = new int[1];
        -            AsyncPollResponse, FooWithProvisioningState> pollResponse
        -                = lroFlux.doOnNext(response -> {
        -                    PollResult pollResult = response.getValue();
        +            if (syncStack) {
        +                SyncPoller, FooWithProvisioningState> lroPoller = SyncPollerFactory
        +                    .create(SERIALIZER, new HttpPipelineBuilder().build(), FooWithProvisioningState.class,
        +                        FooWithProvisioningState.class, POLLING_DURATION, () -> newLroInitResponse(client));
        +
        +                for (int i = 0; i < 2; i++) {
        +                    PollResponse> pollResponse = lroPoller.poll();
        +                    PollResult pollResult = pollResponse.getValue();
                             Assertions.assertNotNull(pollResult);
                             Assertions.assertNotNull(pollResult.getValue());
        -                    onNextCallCount[0]++;
        -                    if (onNextCallCount[0] == 1) {
        -                        Assertions.assertEquals(LongRunningOperationStatus.IN_PROGRESS, response.getStatus());
        -                    } else if (onNextCallCount[0] == 2) {
        -                        Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED,
        -                            response.getStatus());
        +                    if (i == 0) {
        +                        Assertions.assertEquals(LongRunningOperationStatus.IN_PROGRESS, pollResponse.getStatus());
                             } else {
        -                        throw new IllegalStateException("Poller emitted more than expected value.");
        +                        Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED,
        +                            pollResponse.getStatus());
                             }
        -                }).blockLast();
        +                }
        +
        +                FooWithProvisioningState foo = lroPoller.getFinalResult();
        +                Assertions.assertNotNull(foo.getResourceId());
        +                Assertions.assertEquals("Succeeded", foo.getProvisioningState());
        +            } else {
        +                PollerFlux, FooWithProvisioningState> lroFlux = PollerFactory
        +                    .create(SERIALIZER, new HttpPipelineBuilder().build(), FooWithProvisioningState.class,
        +                        FooWithProvisioningState.class, POLLING_DURATION, newLroInitFunction(client));
        +
        +                int[] onNextCallCount = new int[1];
        +                AsyncPollResponse, FooWithProvisioningState> pollResponse
        +                    = lroFlux.doOnNext(response -> {
        +                        PollResult pollResult = response.getValue();
        +                        Assertions.assertNotNull(pollResult);
        +                        Assertions.assertNotNull(pollResult.getValue());
        +                        onNextCallCount[0]++;
        +                        if (onNextCallCount[0] == 1) {
        +                            Assertions.assertEquals(LongRunningOperationStatus.IN_PROGRESS, response.getStatus());
        +                        } else if (onNextCallCount[0] == 2) {
        +                            Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED,
        +                                response.getStatus());
        +                        } else {
        +                            throw new IllegalStateException("Poller emitted more than expected value.");
        +                        }
        +                    }).blockLast();
         
        -            FooWithProvisioningState foo = pollResponse.getFinalResult().block();
        -            Assertions.assertNotNull(foo.getResourceId());
        -            Assertions.assertEquals("Succeeded", foo.getProvisioningState());
        +                FooWithProvisioningState foo = pollResponse.getFinalResult().block();
        +                Assertions.assertNotNull(foo.getResourceId());
        +                Assertions.assertEquals("Succeeded", foo.getProvisioningState());
        +            }
                 } finally {
                     if (lroServer.isRunning()) {
                         lroServer.shutdown();
        @@ -209,8 +266,9 @@ public String getName() {
                 }
             }
         
        -    @Test
        -    public void lroBasedOnAsyncOperationFailed() {
        +    @ParameterizedTest
        +    @ValueSource(booleans = { true, false })
        +    public void lroBasedOnAsyncOperationFailed(boolean syncStack) {
                 ServerConfigure serverConfigure = new ServerConfigure();
         
                 final String resourceEndpoint = "/resource/1";
        @@ -272,29 +330,48 @@ public String getName() {
                     final ProvisioningStateLroServiceClient client = RestProxy.create(ProvisioningStateLroServiceClient.class,
                         createHttpPipeline(lroServer.port()), SERIALIZER);
         
        -            PollerFlux, FooWithProvisioningState> lroFlux
        -                = PollerFactory.create(SERIALIZER, new HttpPipelineBuilder().build(), FooWithProvisioningState.class,
        -                    FooWithProvisioningState.class, POLLING_DURATION, newLroInitFunction(client));
        +            if (syncStack) {
        +                SyncPoller, FooWithProvisioningState> lroPoller = SyncPollerFactory
        +                    .create(SERIALIZER, new HttpPipelineBuilder().build(), FooWithProvisioningState.class,
        +                        FooWithProvisioningState.class, POLLING_DURATION, () -> newLroInitResponse(client));
         
        -            int[] onNextCallCount = new int[1];
        -            AsyncPollResponse, FooWithProvisioningState> pollResponse
        -                = lroFlux.doOnNext(response -> {
        -                    PollResult pollResult = response.getValue();
        +                for (int i = 0; i < 2; i++) {
        +                    PollResponse> pollResponse = lroPoller.poll();
        +                    PollResult pollResult = pollResponse.getValue();
                             Assertions.assertNotNull(pollResult);
        -                    onNextCallCount[0]++;
        -                    if (onNextCallCount[0] == 1) {
        +                    if (i == 0) {
        +                        Assertions.assertEquals(LongRunningOperationStatus.IN_PROGRESS, pollResponse.getStatus());
                                 Assertions.assertNotNull(pollResult.getValue());
        -                        Assertions.assertEquals(LongRunningOperationStatus.IN_PROGRESS, response.getStatus());
        -                    } else if (onNextCallCount[0] == 2) {
        -                        Assertions.assertEquals(LongRunningOperationStatus.FAILED, response.getStatus());
        -                        Assertions.assertEquals(200, response.getValue().getError().getResponseStatusCode());
        -                        Assertions.assertNotNull(response.getValue().getError());
                             } else {
        -                        throw new IllegalStateException("Poller emitted more than expected value.");
        +                        Assertions.assertEquals(LongRunningOperationStatus.FAILED, pollResponse.getStatus());
        +                        Assertions.assertNotNull(pollResult.getError());
                             }
        -                }).blockLast();
        +                }
        +            } else {
        +                PollerFlux, FooWithProvisioningState> lroFlux = PollerFactory
        +                    .create(SERIALIZER, new HttpPipelineBuilder().build(), FooWithProvisioningState.class,
        +                        FooWithProvisioningState.class, POLLING_DURATION, newLroInitFunction(client));
        +
        +                int[] onNextCallCount = new int[1];
        +                AsyncPollResponse, FooWithProvisioningState> pollResponse
        +                    = lroFlux.doOnNext(response -> {
        +                        PollResult pollResult = response.getValue();
        +                        Assertions.assertNotNull(pollResult);
        +                        onNextCallCount[0]++;
        +                        if (onNextCallCount[0] == 1) {
        +                            Assertions.assertNotNull(pollResult.getValue());
        +                            Assertions.assertEquals(LongRunningOperationStatus.IN_PROGRESS, response.getStatus());
        +                        } else if (onNextCallCount[0] == 2) {
        +                            Assertions.assertEquals(LongRunningOperationStatus.FAILED, response.getStatus());
        +                            Assertions.assertEquals(200, response.getValue().getError().getResponseStatusCode());
        +                            Assertions.assertNotNull(response.getValue().getError());
        +                        } else {
        +                            throw new IllegalStateException("Poller emitted more than expected value.");
        +                        }
        +                    }).blockLast();
         
        -            Assertions.assertEquals(LongRunningOperationStatus.FAILED, pollResponse.getStatus());
        +                Assertions.assertEquals(LongRunningOperationStatus.FAILED, pollResponse.getStatus());
        +            }
                 } finally {
                     if (lroServer.isRunning()) {
                         lroServer.shutdown();
        @@ -302,12 +379,16 @@ public String getName() {
                 }
             }
         
        -    @Test
        -    public void lro200SucceededNoPoll() {
        +    @ParameterizedTest
        +    @ValueSource(booleans = { true, false })
        +    public void lro200SucceededNoPoll(boolean syncStack) {
                 final String resourceEndpoint = "/resource/1";
                 final String sampleVaultUpdateSucceededResponse
                     = "{\"id\":\"/subscriptions/000/resourceGroups/rg-weidxu/providers/Microsoft.KeyVault/vaults/v1weidxu\",\"name\":\"v1weidxu\",\"type\":\"Microsoft.KeyVault/vaults\",\"location\":\"centralus\",\"tags\":{},\"properties\":{\"sku\":{\"family\":\"A\",\"name\":\"standard\"},\"tenantId\":\"000\",\"accessPolicies\":[],\"enabledForDeployment\":false,\"vaultUri\":\"https://v1weidxu.vault.azure.net/\",\"provisioningState\":\"Succeeded\"}}";
        +        Duration pollInterval = Duration.ofSeconds(30);
                 ResponseTransformer provisioningStateLroService = new ResponseTransformer() {
        +            private final int[] getCallCount = new int[1];
        +
                     @Override
                     public com.github.tomakehurst.wiremock.http.Response transform(Request request,
                         com.github.tomakehurst.wiremock.http.Response response, FileSource fileSource, Parameters parameters) {
        @@ -318,8 +399,16 @@ public com.github.tomakehurst.wiremock.http.Response transform(Request request,
                                 .build();
                         }
                         if (request.getMethod().isOneOf(RequestMethod.PUT)) {
        +                    getCallCount[0]++;
        +                    if (getCallCount[0] > 1) {
        +                        return new com.github.tomakehurst.wiremock.http.Response.Builder().status(500)
        +                            .body("Unexpected additional polling detected.")
        +                            .build();
        +                    }
                             // 200 response with provisioningState=Succeeded.
                             return new com.github.tomakehurst.wiremock.http.Response.Builder().status(200)
        +                        .headers(new HttpHeaders(
        +                            HttpHeader.httpHeader("Retry-After", String.valueOf(pollInterval.getSeconds()))))
                                 .body(sampleVaultUpdateSucceededResponse)
                                 .build();
                         }
        @@ -338,27 +427,43 @@ public String getName() {
                 try {
                     final ProvisioningStateLroServiceClient client = RestProxy.create(ProvisioningStateLroServiceClient.class,
                         createHttpPipeline(lroServer.port()), SERIALIZER);
        +            if (syncStack) {
        +                SyncPoller, Resource> lroPoller
        +                    = SyncPollerFactory.create(SERIALIZER, new HttpPipelineBuilder().build(), Resource.class,
        +                        Resource.class, POLLING_DURATION, () -> newLroInitResponse(client));
         
        -            PollerFlux, Resource> lroFlux
        -                = PollerFactory.create(SERIALIZER, new HttpPipelineBuilder().build(), Resource.class, Resource.class,
        -                    POLLING_DURATION, newLroInitFunction(client));
        +                lroPoller.setPollInterval(pollInterval);
        +                long timeBeforePoll = System.currentTimeMillis();
         
        -            StepVerifier.create(lroFlux).expectSubscription().expectNextMatches(response -> {
        -                PollResult pollResult = response.getValue();
        -                return response.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED
        -                    && pollResult != null
        -                    && pollResult.getValue() != null
        -                    && pollResult.getValue().id() != null;
        -            }).verifyComplete();
        +                Resource result = lroPoller.getFinalResult();
        +                Assertions.assertNotNull(result);
        +                Assertions.assertNotNull(result.id());
        +                Assertions.assertEquals("v1weidxu", result.name());
        +                Assertions.assertEquals("Microsoft.KeyVault/vaults", result.type());
         
        -            AsyncPollResponse, Resource> asyncPollResponse = lroFlux.blockLast();
        -            Assertions.assertNotNull(asyncPollResponse);
        -
        -            Resource result = asyncPollResponse.getFinalResult().block();
        -            Assertions.assertNotNull(result);
        -            Assertions.assertNotNull(result.id());
        -            Assertions.assertEquals("v1weidxu", result.name());
        -            Assertions.assertEquals("Microsoft.KeyVault/vaults", result.type());
        +                Assertions.assertTrue(System.currentTimeMillis() - timeBeforePoll < pollInterval.toMillis());
        +            } else {
        +                PollerFlux, Resource> lroFlux
        +                    = PollerFactory.create(SERIALIZER, new HttpPipelineBuilder().build(), Resource.class,
        +                        Resource.class, POLLING_DURATION, newLroInitFunction(client));
        +
        +                StepVerifier.create(lroFlux).expectSubscription().expectNextMatches(response -> {
        +                    PollResult pollResult = response.getValue();
        +                    return response.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED
        +                        && pollResult != null
        +                        && pollResult.getValue() != null
        +                        && pollResult.getValue().id() != null;
        +                }).verifyComplete();
        +
        +                AsyncPollResponse, Resource> asyncPollResponse = lroFlux.blockLast();
        +                Assertions.assertNotNull(asyncPollResponse);
        +
        +                Resource result = asyncPollResponse.getFinalResult().block();
        +                Assertions.assertNotNull(result);
        +                Assertions.assertNotNull(result.id());
        +                Assertions.assertEquals("v1weidxu", result.name());
        +                Assertions.assertEquals("Microsoft.KeyVault/vaults", result.type());
        +            }
                 } finally {
                     if (lroServer.isRunning()) {
                         lroServer.shutdown();
        @@ -366,8 +471,9 @@ public String getName() {
                 }
             }
         
        -    @Test
        -    public void lro201AsyncOperationSucceededNoPoll() {
        +    @ParameterizedTest
        +    @ValueSource(booleans = { true, false })
        +    public void lro201AsyncOperationSucceededNoPoll(boolean syncStack) {
                 final String resourceEndpoint = "/resource/1";
                 final String sampleNicCreateSucceededResponse
                     = "{\"name\":\"nic4159682782\",\"id\":\"/subscriptions/000/resourceGroups/javanwmrg59122/providers/Microsoft.Network/networkInterfaces/nic4159682782\",\"etag\":\"W/\\\"92581fdf-b55d-4ca1-a1fa-9de0cf117b4f\\\"\",\"location\":\"eastus\",\"tags\":{},\"properties\":{\"provisioningState\":\"Succeeded\",\"resourceGuid\":\"e0a8ecd1-faa0-468c-8e30-411ca27417a1\",\"ipConfigurations\":[{\"name\":\"primary\",\"id\":\"/subscriptions/ec0aa5f7-9e78-40c9-85cd-535c6305b380/resourceGroups/javanwmrg59122/providers/Microsoft.Network/networkInterfaces/nic4159682782/ipConfigurations/primary\",\"etag\":\"W/\\\"92581fdf-b55d-4ca1-a1fa-9de0cf117b4f\\\"\",\"type\":\"Microsoft.Network/networkInterfaces/ipConfigurations\",\"properties\":{\"provisioningState\":\"Succeeded\",\"privateIPAddress\":\"10.0.0.6\",\"privateIPAllocationMethod\":\"Dynamic\",\"subnet\":{\"id\":\"/subscriptions/ec0aa5f7-9e78-40c9-85cd-535c6305b380/resourceGroups/javanwmrg59122/providers/Microsoft.Network/virtualNetworks/neta3e8953331/subnets/subnet1\"},\"primary\":true,\"privateIPAddressVersion\":\"IPv4\"}}],\"dnsSettings\":{\"dnsServers\":[],\"appliedDnsServers\":[],\"internalDomainNameSuffix\":\"a4vv4vgg2cluvfhfgw43jtn2aa.bx.internal.cloudapp.net\"},\"enableAcceleratedNetworking\":false,\"enableIPForwarding\":false,\"hostedWorkloads\":[],\"tapConfigurations\":[]},\"type\":\"Microsoft.Network/networkInterfaces\"}";
        @@ -405,27 +511,44 @@ public String getName() {
                 try {
                     final ProvisioningStateLroServiceClient client = RestProxy.create(ProvisioningStateLroServiceClient.class,
                         createHttpPipeline(lroServer.port()), SERIALIZER);
        +            if (syncStack) {
        +                SyncPoller, Resource> lroPoller
        +                    = SyncPollerFactory.create(SERIALIZER, new HttpPipelineBuilder().build(), Resource.class,
        +                        Resource.class, POLLING_DURATION, () -> newLroInitResponse(client));
         
        -            PollerFlux, Resource> lroFlux
        -                = PollerFactory.create(SERIALIZER, new HttpPipelineBuilder().build(), Resource.class, Resource.class,
        -                    POLLING_DURATION, newLroInitFunction(client));
        -
        -            StepVerifier.create(lroFlux).expectSubscription().expectNextMatches(response -> {
        +                PollResponse> response = lroPoller.poll();
        +                Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, response.getStatus());
                         PollResult pollResult = response.getValue();
        -                return response.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED
        -                    && pollResult != null
        -                    && pollResult.getValue() != null
        -                    && pollResult.getValue().id() != null;
        -            }).verifyComplete();
        -
        -            AsyncPollResponse, Resource> asyncPollResponse = lroFlux.blockLast();
        -            Assertions.assertNotNull(asyncPollResponse);
        +                Assertions.assertNotNull(pollResult);
        +                Assertions.assertNotNull(pollResult.getValue().id());
         
        -            Resource result = asyncPollResponse.getFinalResult().block();
        -            Assertions.assertNotNull(result);
        -            Assertions.assertNotNull(result.id());
        -            Assertions.assertEquals("nic4159682782", result.name());
        -            Assertions.assertEquals("Microsoft.Network/networkInterfaces", result.type());
        +                Resource result = lroPoller.getFinalResult();
        +                Assertions.assertNotNull(result);
        +                Assertions.assertNotNull(result.id());
        +                Assertions.assertEquals("nic4159682782", result.name());
        +                Assertions.assertEquals("Microsoft.Network/networkInterfaces", result.type());
        +            } else {
        +                PollerFlux, Resource> lroFlux
        +                    = PollerFactory.create(SERIALIZER, new HttpPipelineBuilder().build(), Resource.class,
        +                        Resource.class, POLLING_DURATION, newLroInitFunction(client));
        +
        +                StepVerifier.create(lroFlux).expectSubscription().expectNextMatches(response -> {
        +                    PollResult pollResult = response.getValue();
        +                    return response.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED
        +                        && pollResult != null
        +                        && pollResult.getValue() != null
        +                        && pollResult.getValue().id() != null;
        +                }).verifyComplete();
        +
        +                AsyncPollResponse, Resource> asyncPollResponse = lroFlux.blockLast();
        +                Assertions.assertNotNull(asyncPollResponse);
        +
        +                Resource result = asyncPollResponse.getFinalResult().block();
        +                Assertions.assertNotNull(result);
        +                Assertions.assertNotNull(result.id());
        +                Assertions.assertEquals("nic4159682782", result.name());
        +                Assertions.assertEquals("Microsoft.Network/networkInterfaces", result.type());
        +            }
                 } finally {
                     if (lroServer.isRunning()) {
                         lroServer.shutdown();
        @@ -433,8 +556,9 @@ public String getName() {
                 }
             }
         
        -    @Test
        -    public void lro201SucceededNoPoll() {
        +    @ParameterizedTest
        +    @ValueSource(booleans = { true, false })
        +    public void lro201SucceededNoPoll(boolean syncStack) {
                 final String resourceEndpoint = "/resource/1";
                 final String sampleSearchServiceCreateSucceededResponse
                     = "{\"id\":\"/subscriptions/000/resourceGroups/rg86829b7a87d74/providers/Microsoft.Search/searchServices/ss3edfb54d\",\"name\":\"ss3edfb54d\",\"type\":\"Microsoft.Search/searchServices\",\"location\":\"West US\",\"properties\":{\"replicaCount\":1,\"partitionCount\":1,\"status\":\"running\",\"statusDetails\":\"\",\"provisioningState\":\"succeeded\",\"hostingMode\":\"Default\",\"publicNetworkAccess\":\"Enabled\",\"networkRuleSet\":{\"ipRules\":[],\"bypass\":\"None\"},\"privateEndpointConnections\":[],\"sharedPrivateLinkResources\":[]},\"sku\":{\"name\":\"free\"}}";
        @@ -472,27 +596,41 @@ public String getName() {
                 try {
                     final ProvisioningStateLroServiceClient client = RestProxy.create(ProvisioningStateLroServiceClient.class,
                         createHttpPipeline(lroServer.port()), SERIALIZER);
        -
        -            PollerFlux, Resource> lroFlux
        -                = PollerFactory.create(SERIALIZER, new HttpPipelineBuilder().build(), Resource.class, Resource.class,
        -                    POLLING_DURATION, newLroInitFunction(client));
        -
        -            StepVerifier.create(lroFlux).expectSubscription().expectNextMatches(response -> {
        -                PollResult pollResult = response.getValue();
        -                return response.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED
        -                    && pollResult != null
        -                    && pollResult.getValue() != null
        -                    && pollResult.getValue().id() != null;
        -            }).verifyComplete();
        -
        -            AsyncPollResponse, Resource> asyncPollResponse = lroFlux.blockLast();
        -            Assertions.assertNotNull(asyncPollResponse);
        -
        -            Resource result = asyncPollResponse.getFinalResult().block();
        -            Assertions.assertNotNull(result);
        -            Assertions.assertNotNull(result.id());
        -            Assertions.assertEquals("ss3edfb54d", result.name());
        -            Assertions.assertEquals("Microsoft.Search/searchServices", result.type());
        +            if (syncStack) {
        +                SyncPoller, Resource> lroPoller
        +                    = SyncPollerFactory.create(SERIALIZER, new HttpPipelineBuilder().build(), Resource.class,
        +                        Resource.class, POLLING_DURATION, () -> newLroInitResponse(client));
        +
        +                PollResponse> pollResponse = lroPoller.poll();
        +                Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollResponse.getStatus());
        +
        +                Resource result = lroPoller.getFinalResult();
        +                Assertions.assertNotNull(result);
        +                Assertions.assertNotNull(result.id());
        +                Assertions.assertEquals("ss3edfb54d", result.name());
        +                Assertions.assertEquals("Microsoft.Search/searchServices", result.type());
        +            } else {
        +                PollerFlux, Resource> lroFlux
        +                    = PollerFactory.create(SERIALIZER, new HttpPipelineBuilder().build(), Resource.class,
        +                        Resource.class, POLLING_DURATION, newLroInitFunction(client));
        +
        +                StepVerifier.create(lroFlux).expectSubscription().expectNextMatches(response -> {
        +                    PollResult pollResult = response.getValue();
        +                    return response.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED
        +                        && pollResult != null
        +                        && pollResult.getValue() != null
        +                        && pollResult.getValue().id() != null;
        +                }).verifyComplete();
        +
        +                AsyncPollResponse, Resource> asyncPollResponse = lroFlux.blockLast();
        +                Assertions.assertNotNull(asyncPollResponse);
        +
        +                Resource result = asyncPollResponse.getFinalResult().block();
        +                Assertions.assertNotNull(result);
        +                Assertions.assertNotNull(result.id());
        +                Assertions.assertEquals("ss3edfb54d", result.name());
        +                Assertions.assertEquals("Microsoft.Search/searchServices", result.type());
        +            }
                 } finally {
                     if (lroServer.isRunning()) {
                         lroServer.shutdown();
        @@ -500,8 +638,9 @@ public String getName() {
                 }
             }
         
        -    @Test
        -    public void lroMalformedAaoUrl() {
        +    @ParameterizedTest
        +    @ValueSource(booleans = { true, false })
        +    public void lroMalformedAaoUrl(boolean syncStack) {
                 ServerConfigure serverConfigure = new ServerConfigure();
                 serverConfigure.pollingCountTillSuccess = 3;
         
        @@ -574,22 +713,33 @@ public String getName() {
                 try {
                     final ProvisioningStateLroServiceClient client = RestProxy.create(ProvisioningStateLroServiceClient.class,
                         createHttpPipeline(lroServer.port()), SERIALIZER);
        +            if (syncStack) {
        +                SyncPoller, FooWithProvisioningState> lroPoller = SyncPollerFactory
        +                    .create(SERIALIZER, new HttpPipelineBuilder().build(), FooWithProvisioningState.class,
        +                        FooWithProvisioningState.class, POLLING_DURATION, () -> newLroInitResponse(client));
         
        -            PollerFlux, FooWithProvisioningState> lroFlux
        -                = PollerFactory.create(SERIALIZER, new HttpPipelineBuilder().build(), FooWithProvisioningState.class,
        -                    FooWithProvisioningState.class, POLLING_DURATION, newLroInitFunction(client));
        +                PollResponse> pollResult = lroPoller.poll();
        +                Assertions.assertEquals(LongRunningOperationStatus.IN_PROGRESS, pollResult.getStatus());
        +
        +                pollResult = lroPoller.poll();
        +                Assertions.assertEquals(LongRunningOperationStatus.FAILED, pollResult.getStatus());
        +            } else {
        +                PollerFlux, FooWithProvisioningState> lroFlux = PollerFactory
        +                    .create(SERIALIZER, new HttpPipelineBuilder().build(), FooWithProvisioningState.class,
        +                        FooWithProvisioningState.class, POLLING_DURATION, newLroInitFunction(client));
         
        -            StepVerifier.create(lroFlux).expectSubscription().expectNextMatches(response -> {
        -                PollResult pollResult = response.getValue();
        -                return response.getStatus() == LongRunningOperationStatus.IN_PROGRESS
        -                    && pollResult != null
        -                    && pollResult.getValue() != null;
        -            }).expectNextMatches(response -> {
        -                PollResult pollResult = response.getValue();
        -                return response.getStatus() == LongRunningOperationStatus.FAILED
        -                    && pollResult != null
        -                    && pollResult.getError() != null;
        -            }).verifyComplete();
        +                StepVerifier.create(lroFlux).expectSubscription().expectNextMatches(response -> {
        +                    PollResult pollResult = response.getValue();
        +                    return response.getStatus() == LongRunningOperationStatus.IN_PROGRESS
        +                        && pollResult != null
        +                        && pollResult.getValue() != null;
        +                }).expectNextMatches(response -> {
        +                    PollResult pollResult = response.getValue();
        +                    return response.getStatus() == LongRunningOperationStatus.FAILED
        +                        && pollResult != null
        +                        && pollResult.getError() != null;
        +                }).verifyComplete();
        +            }
                 } finally {
                     if (lroServer.isRunning()) {
                         lroServer.shutdown();
        @@ -597,8 +747,9 @@ public String getName() {
                 }
             }
         
        -    @Test
        -    public void lroTimeout() {
        +    @ParameterizedTest
        +    @ValueSource(booleans = { true, false })
        +    public void lroTimeout(boolean syncStack) {
                 final Duration timeoutDuration = Duration.ofMillis(1000);   // use a large timeout for manual verification
         
                 final String resourceEndpoint = "/resource/1";
        @@ -636,26 +787,42 @@ public String getName() {
                 try {
                     final ProvisioningStateLroServiceClient client = RestProxy.create(ProvisioningStateLroServiceClient.class,
                         createHttpPipeline(lroServer.port()), SERIALIZER);
        +            if (syncStack) {
        +                SyncPoller, FooWithProvisioningState> lroPoller = SyncPollerFactory
        +                    .create(SERIALIZER, new HttpPipelineBuilder().build(), FooWithProvisioningState.class,
        +                        FooWithProvisioningState.class, POLLING_DURATION, () -> newLroInitResponse(client));
         
        -            PollerFlux, FooWithProvisioningState> lroFlux
        -                = PollerFactory.create(SERIALIZER, new HttpPipelineBuilder().build(), FooWithProvisioningState.class,
        -                    FooWithProvisioningState.class, POLLING_DURATION, newLroInitFunction(client));
        +                boolean timedOut = false;
        +                TimeLimiter timeLimiter = SimpleTimeLimiter.create(Executors.newSingleThreadExecutor());
        +                try {
        +                    timeLimiter.callWithTimeout(lroPoller::getFinalResult, timeoutDuration);
        +                } catch (TimeoutException e) {
        +                    timedOut = true;
        +                } catch (Exception e) {
        +                    throw new RuntimeException(e);
        +                }
        +                Assertions.assertTrue(timedOut);
        +            } else {
        +                PollerFlux, FooWithProvisioningState> lroFlux = PollerFactory
        +                    .create(SERIALIZER, new HttpPipelineBuilder().build(), FooWithProvisioningState.class,
        +                        FooWithProvisioningState.class, POLLING_DURATION, newLroInitFunction(client));
         
        -            Mono resultMonoWithTimeout
        -                = lroFlux.last().flatMap(AsyncPollResponse::getFinalResult).timeout(timeoutDuration);
        +                Mono resultMonoWithTimeout
        +                    = lroFlux.last().flatMap(AsyncPollResponse::getFinalResult).timeout(timeoutDuration);
         
        -            // VirtualTimeScheduler seems not working correctly in StepVerifier. Could be a problem.
        -            // verify timeout.
        -            StepVerifier.create(resultMonoWithTimeout).thenAwait().verifyError(TimeoutException.class);
        +                // VirtualTimeScheduler seems not working correctly in StepVerifier. Could be a problem.
        +                // verify timeout.
        +                StepVerifier.create(resultMonoWithTimeout).thenAwait().verifyError(TimeoutException.class);
         
        -            // verify no more polling after timeout.
        -            int count = getCallCount.get();
        -            try {
        -                Thread.sleep(timeoutDuration.toMillis());
        -            } catch (InterruptedException e) {
        -                //
        +                // verify no more polling after timeout.
        +                int count = getCallCount.get();
        +                try {
        +                    Thread.sleep(timeoutDuration.toMillis());
        +                } catch (InterruptedException e) {
        +                    //
        +                }
        +                // Assertions.assertEquals(count, getCallCount.get());
                     }
        -            // Assertions.assertEquals(count, getCallCount.get());
                 } finally {
                     if (lroServer.isRunning()) {
                         lroServer.shutdown();
        @@ -663,10 +830,11 @@ public String getName() {
                 }
             }
         
        -    @Test
        -    public void lroRetryAfter() {
        +    @ParameterizedTest
        +    @ValueSource(booleans = { true, false })
        +    public void lroRetryAfter(boolean syncStack) {
                 ServerConfigure configure = new ServerConfigure();
        -        Duration expectedPollingDuration = Duration.ofSeconds(3);
        +        Duration expectedPollingDuration = Duration.ofSeconds(1);
                 configure.pollingCountTillSuccess = 3;
                 configure.additionalHeaders = new HttpHeaders(new HttpHeader("Retry-After", "1"));  // 1 second
                 WireMockServer lroServer = startServer(configure);
        @@ -674,23 +842,36 @@ public void lroRetryAfter() {
                 try {
                     final ProvisioningStateLroServiceClient client = RestProxy.create(ProvisioningStateLroServiceClient.class,
                         createHttpPipeline(lroServer.port()), SERIALIZER);
        -
        -            PollerFlux, FooWithProvisioningState> lroFlux
        -                = PollerFactory.create(SERIALIZER, new HttpPipelineBuilder().build(), FooWithProvisioningState.class,
        -                    FooWithProvisioningState.class, POLLING_DURATION, newLroInitFunction(client));
        -
        -            long nanoTime = System.nanoTime();
        -
        -            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);
        -            Assertions.assertTrue(pollingDuration.compareTo(expectedPollingDuration) > 0);
        +            if (syncStack) {
        +                SyncPoller, FooWithProvisioningState> syncPoller
        +                    = SyncPollerFactory.create(SERIALIZER, new HttpPipelineBuilder().build(),
        +                        FooWithProvisioningState.class, FooWithProvisioningState.class, POLLING_DURATION,
        +                        () -> newLroInitResponse(client));
        +
        +                long nanoTime = System.nanoTime();
        +                FooWithProvisioningState result = syncPoller.getFinalResult();
        +                Assertions.assertNotNull(result);
        +
        +                Duration pollingDuration = Duration.ofNanos(System.nanoTime() - nanoTime);
        +                Assertions.assertTrue(pollingDuration.compareTo(expectedPollingDuration) > 0);
        +            } else {
        +                PollerFlux, FooWithProvisioningState> lroFlux = PollerFactory
        +                    .create(SERIALIZER, new HttpPipelineBuilder().build(), FooWithProvisioningState.class,
        +                        FooWithProvisioningState.class, POLLING_DURATION, newLroInitFunction(client));
        +
        +                long nanoTime = System.nanoTime();
        +
        +                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);
        +                Assertions.assertTrue(pollingDuration.compareTo(expectedPollingDuration) > 0);
        +            }
                 } finally {
                     if (lroServer.isRunning()) {
                         lroServer.shutdown();
        @@ -731,8 +912,9 @@ public void lroContextSubscriberContext() {
                 }
             }
         
        -    @Test
        -    public void lroContext() {
        +    @ParameterizedTest
        +    @ValueSource(booleans = { true, false })
        +    public void lroContext(boolean syncStack) {
                 WireMockServer lroServer = startServer();
         
                 HttpPipelinePolicy contextVerifyPolicy = (context, next) -> {
        @@ -750,14 +932,24 @@ public void lroContext() {
                     final ProvisioningStateLroServiceClient client
                         = RestProxy.create(ProvisioningStateLroServiceClient.class, httpPipeline, SERIALIZER);
         
        -            Flux, FooWithProvisioningState>> lroFlux
        -                = PollerFactory.create(SERIALIZER, httpPipeline, FooWithProvisioningState.class,
        -                    FooWithProvisioningState.class, POLLING_DURATION,
        -                    newLroInitFunction(client).contextWrite(context -> context.put("key1", "value1")),
        -                    new Context("key1", "value1"));
        +            if (syncStack) {
        +                SyncPoller, FooWithProvisioningState> lroPoller
        +                    = SyncPollerFactory.create(SERIALIZER, httpPipeline, FooWithProvisioningState.class,
        +                        FooWithProvisioningState.class, POLLING_DURATION,
        +                        () -> newLroInitResponse(client, new Context("key1", "value1")), new Context("key1", "value1"));
         
        -            FooWithProvisioningState result = lroFlux.blockLast().getFinalResult().block();
        -            Assertions.assertNotNull(result);
        +                FooWithProvisioningState result = lroPoller.getFinalResult();
        +                Assertions.assertNotNull(result);
        +            } else {
        +                Flux, FooWithProvisioningState>> lroFlux
        +                    = PollerFactory.create(SERIALIZER, httpPipeline, FooWithProvisioningState.class,
        +                        FooWithProvisioningState.class, POLLING_DURATION,
        +                        newLroInitFunction(client).contextWrite(context -> context.put("key1", "value1")),
        +                        new Context("key1", "value1"));
        +
        +                FooWithProvisioningState result = lroFlux.blockLast().getFinalResult().block();
        +                Assertions.assertNotNull(result);
        +            }
                 } finally {
                     if (lroServer.isRunning()) {
                         lroServer.shutdown();
        @@ -765,8 +957,9 @@ public void lroContext() {
                 }
             }
         
        -    @Test
        -    public void lroBasedOnAsyncOperationInBinaryData() {
        +    @ParameterizedTest
        +    @ValueSource(booleans = { true, false })
        +    public void lroBasedOnAsyncOperationInBinaryData(boolean syncStack) {
                 ServerConfigure serverConfigure = new ServerConfigure();
         
                 final String resourceEndpoint = "/resource/1";
        @@ -832,29 +1025,54 @@ public String getName() {
                     final ProvisioningStateLroServiceClient client = RestProxy.create(ProvisioningStateLroServiceClient.class,
                         createHttpPipeline(lroServer.port()), SERIALIZER);
         
        -            PollerFlux, BinaryData> lroFlux
        -                = PollerFactory.create(SERIALIZER, new HttpPipelineBuilder().build(), BinaryData.class,
        -                    BinaryData.class, POLLING_DURATION, newLroInitFunction(client));
        +            if (syncStack) {
        +                SyncPoller, BinaryData> lroPoller
        +                    = SyncPollerFactory.create(SERIALIZER, new HttpPipelineBuilder().build(), BinaryData.class,
        +                        BinaryData.class, POLLING_DURATION, () -> newLroInitResponse(client));
         
        -            int[] onNextCallCount = new int[1];
        -            AsyncPollResponse, BinaryData> pollResponse = lroFlux.doOnNext(response -> {
        -                PollResult pollResult = response.getValue();
        -                Assertions.assertNotNull(pollResult);
        -                Assertions.assertNotNull(pollResult.getValue());
        -                onNextCallCount[0]++;
        -                if (onNextCallCount[0] == 1) {
        -                    Assertions.assertEquals(LongRunningOperationStatus.IN_PROGRESS, response.getStatus());
        -                } else if (onNextCallCount[0] == 2) {
        -                    Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, response.getStatus());
        -                } else {
        -                    throw new IllegalStateException("Poller emitted more than expected value.");
        +                for (int i = 0; i < 2; i++) {
        +                    PollResponse> response = lroPoller.poll();
        +                    PollResult pollResult = response.getValue();
        +                    Assertions.assertNotNull(pollResult);
        +                    Assertions.assertNotNull(pollResult.getValue());
        +                    if (i == 0) {
        +                        Assertions.assertEquals(LongRunningOperationStatus.IN_PROGRESS, response.getStatus());
        +                    } else {
        +                        Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED,
        +                            response.getStatus());
        +                    }
                         }
        -            }).blockLast();
         
        -            BinaryData foo = pollResponse.getFinalResult().block();
        -            FooWithProvisioningState fooAsObject = foo.toObject(FooWithProvisioningState.class);
        -            Assertions.assertNotNull(fooAsObject.getResourceId());
        -            Assertions.assertEquals("Succeeded", fooAsObject.getProvisioningState());
        +                BinaryData foo = lroPoller.getFinalResult();
        +                FooWithProvisioningState fooAsObject = foo.toObject(FooWithProvisioningState.class);
        +                Assertions.assertNotNull(fooAsObject.getResourceId());
        +                Assertions.assertEquals("Succeeded", fooAsObject.getProvisioningState());
        +            } else {
        +                PollerFlux, BinaryData> lroFlux
        +                    = PollerFactory.create(SERIALIZER, new HttpPipelineBuilder().build(), BinaryData.class,
        +                        BinaryData.class, POLLING_DURATION, newLroInitFunction(client));
        +
        +                int[] onNextCallCount = new int[1];
        +                AsyncPollResponse, BinaryData> pollResponse = lroFlux.doOnNext(response -> {
        +                    PollResult pollResult = response.getValue();
        +                    Assertions.assertNotNull(pollResult);
        +                    Assertions.assertNotNull(pollResult.getValue());
        +                    onNextCallCount[0]++;
        +                    if (onNextCallCount[0] == 1) {
        +                        Assertions.assertEquals(LongRunningOperationStatus.IN_PROGRESS, response.getStatus());
        +                    } else if (onNextCallCount[0] == 2) {
        +                        Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED,
        +                            response.getStatus());
        +                    } else {
        +                        throw new IllegalStateException("Poller emitted more than expected value.");
        +                    }
        +                }).blockLast();
        +
        +                BinaryData foo = pollResponse.getFinalResult().block();
        +                FooWithProvisioningState fooAsObject = foo.toObject(FooWithProvisioningState.class);
        +                Assertions.assertNotNull(fooAsObject.getResourceId());
        +                Assertions.assertEquals("Succeeded", fooAsObject.getProvisioningState());
        +            }
                 } finally {
                     if (lroServer.isRunning()) {
                         lroServer.shutdown();
        @@ -864,6 +1082,7 @@ public String getName() {
         
             private static class ServerConfigure {
                 private int pollingCountTillSuccess = 2;
        +
                 private HttpHeaders additionalHeaders = HttpHeaders.noHeaders();
             }
         
        @@ -965,6 +1184,14 @@ private Mono>> newLroInitFunction(ProvisioningStateLro
                 return FluxUtil.fluxContext(context -> client.startLro(context).flux()).next();
             }
         
        +    private Response newLroInitResponse(ProvisioningStateLroServiceClient client) {
        +        return newLroInitResponse(client, Context.NONE);
        +    }
        +
        +    private Response newLroInitResponse(ProvisioningStateLroServiceClient client, Context context) {
        +        return client.startLroSync(context);
        +    }
        +
             private static String toJson(Object object) {
                 try {
                     return SERIALIZER.serialize(object, SerializerEncoding.JSON);
        diff --git a/sdk/core/azure-core-metrics-opentelemetry/CHANGELOG.md b/sdk/core/azure-core-metrics-opentelemetry/CHANGELOG.md
        index 94a051104f5c..acfc6c376c9c 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.26 (Unreleased)
        +## 1.0.0-beta.30 (Unreleased)
         
         ### Features Added
         
        @@ -10,6 +10,39 @@
         
         ### Other Changes
         
        +## 1.0.0-beta.29 (2025-03-10)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.55.2` to `1.55.3`.
        +
        +## 1.0.0-beta.28 (2025-02-20)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.55.1` to `1.55.2`.
        +
        +## 1.0.0-beta.27 (2025-02-12)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.55.0` to `1.55.1`.
        +
        +## 1.0.0-beta.26 (2025-02-06)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.54.1` to `1.55.0`.
        +- Upgraded `opentelemetry-api` from `1.43.0` to `1.46.0`.
        +
         ## 1.0.0-beta.25 (2024-11-14)
         
         ### Other Changes
        diff --git a/sdk/core/azure-core-metrics-opentelemetry/README.md b/sdk/core/azure-core-metrics-opentelemetry/README.md
        index bfc65d084399..75246a79b97b 100644
        --- a/sdk/core/azure-core-metrics-opentelemetry/README.md
        +++ b/sdk/core/azure-core-metrics-opentelemetry/README.md
        @@ -20,7 +20,7 @@ services.
         
           com.azure
           azure-core-metrics-opentelemetry
        -  1.0.0-beta.25
        +  1.0.0-beta.29
         
         ```
         [//]: # ({x-version-update-end})
        @@ -130,4 +130,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct](https://ope
         [OpenTelemetry]: https://github.com/open-telemetry/opentelemetry-java#opentelemetry-for-java
         [samples]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/core/azure-core-metrics-opentelemetry/src/samples/
         
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcore%2Fazure-core-metrics-opentelemetry%2FREADME.png)
        +
        diff --git a/sdk/core/azure-core-metrics-opentelemetry/pom.xml b/sdk/core/azure-core-metrics-opentelemetry/pom.xml
        index e73cba2fae14..c0a35bd1a613 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.26 
        +  1.0.0-beta.30 
         
           Microsoft Azure OpenTelemetry metrics plugin
           This package contains the OpenTelemetry metrics plugin for Azure client libraries.
        @@ -48,12 +48,12 @@
             
               io.opentelemetry
               opentelemetry-api
        -      1.43.0 
        +      1.46.0 
             
             
               com.azure
               azure-core
        -      1.55.0-beta.1 
        +      1.56.0-beta.1 
             
             
               com.google.code.findbugs
        @@ -66,21 +66,21 @@
             
               io.opentelemetry
               opentelemetry-sdk
        -      1.43.0 
        +      1.46.0 
               test
             
         
             
               io.opentelemetry
               opentelemetry-sdk-testing
        -      1.43.0 
        +      1.46.0 
               test
             
         
             
               com.azure
               azure-core-test
        -      1.27.0-beta.5  
        +      1.27.0-beta.9  
               test
             
             
        @@ -104,7 +104,7 @@
             
               io.opentelemetry
               opentelemetry-exporter-otlp
        -      1.43.0  
        +      1.46.0  
               test
             
           
        @@ -119,11 +119,11 @@
                   
                     
                       
        -                io.opentelemetry:opentelemetry-api:[1.43.0] 
        -                io.opentelemetry:opentelemetry-sdk:[1.43.0] 
        -                io.opentelemetry:opentelemetry-sdk-testing:[1.43.0] 
        -                io.opentelemetry:opentelemetry-exporter-logging:[1.43.0] 
        -                io.opentelemetry:opentelemetry-exporter-otlp:[1.43.0] 
        +                io.opentelemetry:opentelemetry-api:[1.46.0] 
        +                io.opentelemetry:opentelemetry-sdk:[1.46.0] 
        +                io.opentelemetry:opentelemetry-sdk-testing:[1.46.0] 
        +                io.opentelemetry:opentelemetry-exporter-logging:[1.46.0] 
        +                io.opentelemetry:opentelemetry-exporter-otlp:[1.46.0] 
                       
                     
                   
        diff --git a/sdk/core/azure-core-perf/README.md b/sdk/core/azure-core-perf/README.md
        index f337706b3449..c690c5608101 100644
        --- a/sdk/core/azure-core-perf/README.md
        +++ b/sdk/core/azure-core-perf/README.md
        @@ -58,4 +58,4 @@ For details on contributing to this repository, see the [contributing guide](htt
         1. Push to the branch (`git push origin my-new-feature`)
         1. Create new Pull Request
         
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcore%2Fperf-test-core%2FREADME.png)
        +
        diff --git a/sdk/core/azure-core-perf/pom.xml b/sdk/core/azure-core-perf/pom.xml
        index b27a19a75c61..bdbbf299a8bc 100644
        --- a/sdk/core/azure-core-perf/pom.xml
        +++ b/sdk/core/azure-core-perf/pom.xml
        @@ -21,7 +21,7 @@
             
               com.azure
               azure-core
        -      1.55.0-beta.1 
        +      1.56.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 92819abdb5ca..b54477edcb84 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.53 (Unreleased)
        +## 1.0.0-beta.57 (Unreleased)
         
         ### Features Added
         
        @@ -10,6 +10,38 @@
         
         ### Other Changes
         
        +## 1.0.0-beta.56 (2025-03-10)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.55.2` to `1.55.3`.
        +
        +## 1.0.0-beta.55 (2025-02-20)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.55.1` to `1.55.2`.
        +
        +## 1.0.0-beta.54 (2025-02-12)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.55.0` to `1.55.1`.
        +
        +## 1.0.0-beta.53 (2025-02-06)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.54.1` to `1.55.0`.
        +
         ## 1.0.0-beta.52 (2024-11-14)
         
         ### 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 a29a9cf984ca..79e29a9107fa 100644
        --- a/sdk/core/azure-core-serializer-avro-apache/README.md
        +++ b/sdk/core/azure-core-serializer-avro-apache/README.md
        @@ -16,7 +16,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.52
        +    1.0.0-beta.56
         
         ```
         [//]: # ({x-version-update-end})
        @@ -55,4 +55,4 @@ For details on contributing to this repository, see the [contributing guide](htt
         [jdk_link]: https://learn.microsoft.com/java/azure/jdk/?view=azure-java-stable
         [java8_client_compatibility]: https://learn.microsoft.com/azure/security/fundamentals/azure-ca-details?tabs=root-and-subordinate-cas-list#client-compatibility-for-public-pkis
         
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcore%2Fazure-core-serializer-avro-apache%2FREADME.png)
        +
        diff --git a/sdk/core/azure-core-serializer-avro-apache/pom.xml b/sdk/core/azure-core-serializer-avro-apache/pom.xml
        index cdce1a96881a..f04508ee01e9 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.53 
        +  1.0.0-beta.57 
         
           Microsoft Azure Apache Avro Serializer Library
           This package contains the Apache Avro serializer client plugin for azure-core.
        @@ -77,12 +77,12 @@
             
               com.azure
               azure-core
        -      1.55.0-beta.1 
        +      1.56.0-beta.1 
             
             
               com.azure
               azure-core-experimental
        -      1.0.0-beta.57 
        +      1.0.0-beta.61 
             
         
             
        diff --git a/sdk/core/azure-core-serializer-avro-jackson/README.md b/sdk/core/azure-core-serializer-avro-jackson/README.md
        index 10c75c7b852b..11ad87897cec 100644
        --- a/sdk/core/azure-core-serializer-avro-jackson/README.md
        +++ b/sdk/core/azure-core-serializer-avro-jackson/README.md
        @@ -16,7 +16,7 @@ Azure Core Jackson Avro Serializer is a plugin for the `azure-core` `AvroSeriali
         
             com.azure
             azure-core-serializer-avro-jackson
        -    1.0.0-beta.1
        +    1.0.0-beta.2
         
         ```
         [//]: # ({x-version-update-end})
        @@ -55,4 +55,4 @@ For details on contributing to this repository, see the [contributing guide](htt
         [jdk_link]: https://learn.microsoft.com/java/azure/jdk/?view=azure-java-stable
         [java8_client_compatibility]: https://learn.microsoft.com/azure/security/fundamentals/azure-ca-details?tabs=root-and-subordinate-cas-list#client-compatibility-for-public-pkis
         
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcore%2Fazure-core-serializer-avro-jackson%2FREADME.png)
        +
        diff --git a/sdk/core/azure-core-serializer-avro-jackson/pom.xml b/sdk/core/azure-core-serializer-avro-jackson/pom.xml
        index f976952e1e53..2258dead2a55 100644
        --- a/sdk/core/azure-core-serializer-avro-jackson/pom.xml
        +++ b/sdk/core/azure-core-serializer-avro-jackson/pom.xml
        @@ -69,12 +69,12 @@
             
               com.azure
               azure-core
        -      1.55.0-beta.1 
        +      1.56.0-beta.1 
             
             
               com.azure
               azure-core-experimental
        -      1.0.0-beta.57 
        +      1.0.0-beta.61 
             
         
             
        diff --git a/sdk/core/azure-core-serializer-json-gson/CHANGELOG.md b/sdk/core/azure-core-serializer-json-gson/CHANGELOG.md
        index fbb5190a6094..f83b08c0a9ef 100644
        --- a/sdk/core/azure-core-serializer-json-gson/CHANGELOG.md
        +++ b/sdk/core/azure-core-serializer-json-gson/CHANGELOG.md
        @@ -10,6 +10,38 @@
         
         ### Other Changes
         
        +## 1.3.8 (2025-03-10)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.55.2` to `1.55.3`.
        +
        +## 1.3.7 (2025-02-20)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.55.1` to `1.55.2`.
        +
        +## 1.3.6 (2025-02-12)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.55.0` to `1.55.1`.
        +
        +## 1.3.5 (2025-02-06)
        +
        +### Other Changes
        +
        +#### Dependency Updates
        +
        +- Upgraded `azure-core` from `1.54.1` to `1.55.0`.
        +
         ## 1.3.4 (2024-11-14)
         
         ### 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 af45e5d6fc4f..666c3ef1df51 100644
        --- a/sdk/core/azure-core-serializer-json-gson/README.md
        +++ b/sdk/core/azure-core-serializer-json-gson/README.md
        @@ -48,7 +48,7 @@ add the direct dependency to your project as follows.
         
             com.azure
             azure-core-serializer-json-gson
        -    1.3.4
        +    1.3.8
         
         ```
         [//]: # ({x-version-update-end})
        @@ -87,4 +87,4 @@ For details on contributing to this repository, see the [contributing guide](htt
         [jdk_link]: https://learn.microsoft.com/java/azure/jdk/?view=azure-java-stable
         [java8_client_compatibility]: https://learn.microsoft.com/azure/security/fundamentals/azure-ca-details?tabs=root-and-subordinate-cas-list#client-compatibility-for-public-pkis
         
        -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcore%2Fazure-core-serializer-json-gson%2FREADME.png)
        +
        diff --git a/sdk/core/azure-core-serializer-json-gson/checkstyle-suppressions.xml b/sdk/core/azure-core-serializer-json-gson/checkstyle-suppressions.xml
        index ff3fe44bbcc8..84b5f0dd5c37 100644
        --- a/sdk/core/azure-core-serializer-json-gson/checkstyle-suppressions.xml
        +++ b/sdk/core/azure-core-serializer-json-gson/checkstyle-suppressions.xml
        @@ -1,16 +1,17 @@
         
        -
        +
        +
         
         
        -  
        -  
        -  
        -  
        -  
        -
        -  
        -
        -  
        +  
        +  
        +  
        +  
        +  
        +  
        +  
        +  
        +  
        +  
        +  
         
        diff --git a/sdk/core/azure-core-serializer-json-gson/pom.xml b/sdk/core/azure-core-serializer-json-gson/pom.xml
        index e1c3b58069c0..004bf556658e 100644
        --- a/sdk/core/azure-core-serializer-json-gson/pom.xml
        +++ b/sdk/core/azure-core-serializer-json-gson/pom.xml
        @@ -78,12 +78,12 @@
             
               com.azure
               azure-core
        -      1.55.0-beta.1 
        +      1.56.0-beta.1 
             
             
               com.azure
               azure-json
        -      1.3.0 
        +      1.5.0 
             
         
             
        @@ -95,7 +95,7 @@
             
               com.azure
               azure-json
        -      1.3.0 
        +      1.5.0 
               test-jar
               test
             
        diff --git a/sdk/core/azure-core-serializer-json-gson/spotbugs-exclude.xml b/sdk/core/azure-core-serializer-json-gson/spotbugs-exclude.xml
        index 092cda28f607..9962576079f2 100644
        --- a/sdk/core/azure-core-serializer-json-gson/spotbugs-exclude.xml
        +++ b/sdk/core/azure-core-serializer-json-gson/spotbugs-exclude.xml
        @@ -1,15 +1,17 @@
         
         
         
        -  
        -    
        -    
        -    
        -  
        -
        +                xsi:schemaLocation="https://github.com/spotbugs/filter/3.0.0 https://raw.githubusercontent.com/spotbugs/spotbugs/3.1.0/spotbugs/etc/findbugsfilter.xsd">
           
             
             
           
        +  
        +    
        +    
        +  
        +  
        +    
        +    
        +  
         
        diff --git a/sdk/core/azure-core-serializer-json-gson/src/main/java/com/azure/core/serializer/json/gson/implementation/CustomGsonReader.java b/sdk/core/azure-core-serializer-json-gson/src/main/java/com/azure/core/serializer/json/gson/implementation/CustomGsonReader.java
        new file mode 100644
        index 000000000000..047c8158bc2a
        --- /dev/null
        +++ b/sdk/core/azure-core-serializer-json-gson/src/main/java/com/azure/core/serializer/json/gson/implementation/CustomGsonReader.java
        @@ -0,0 +1,1384 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +package com.azure.core.serializer.json.gson.implementation;
        +
        +import com.azure.json.JsonOptions;
        +import com.google.gson.Strictness;
        +import com.google.gson.stream.JsonReader;
        +import com.google.gson.stream.JsonToken;
        +import com.google.gson.stream.MalformedJsonException;
        +
        +import java.io.EOFException;
        +import java.io.IOException;
        +import java.io.Reader;
        +import java.util.Arrays;
        +import java.util.Objects;
        +
        +/**
        + * This class is a copy of {@link JsonReader} with fine-grain control over lenient parsing.
        + * 

        + * By default, GSON has a single flag/enum for lenient parsing, where the behavior is all or nothing. The Azure SDK for + * Java offers finer grain control for whether non-numeric numbers or JSON with comments is supported. This class + * mutates the default GSON behaviors to control that. + */ +public final class CustomGsonReader extends JsonReader { + private static final long MIN_INCOMPLETE_INTEGER = Long.MIN_VALUE / 10; + + // Unsupported peek states have been commented out. + private static final int PEEKED_NONE = 0; + private static final int PEEKED_BEGIN_OBJECT = 1; + private static final int PEEKED_END_OBJECT = 2; + private static final int PEEKED_BEGIN_ARRAY = 3; + private static final int PEEKED_END_ARRAY = 4; + private static final int PEEKED_TRUE = 5; + private static final int PEEKED_FALSE = 6; + private static final int PEEKED_NULL = 7; + // private static final int PEEKED_SINGLE_QUOTED = 8; + private static final int PEEKED_DOUBLE_QUOTED = 9; + // private static final int PEEKED_UNQUOTED = 10; + + /** When this is returned, the string value is stored in peekedString. */ + private static final int PEEKED_BUFFERED = 11; + + // private static final int PEEKED_SINGLE_QUOTED_NAME = 12; + private static final int PEEKED_DOUBLE_QUOTED_NAME = 13; + // private static final int PEEKED_UNQUOTED_NAME = 14; + + /** When this is returned, the integer value is stored in peekedLong. */ + private static final int PEEKED_LONG = 15; + + private static final int PEEKED_NUMBER = 16; + private static final int PEEKED_EOF = 17; + + /* State machine when parsing numbers */ + private static final int NUMBER_CHAR_NONE = 0; + private static final int NUMBER_CHAR_SIGN = 1; + private static final int NUMBER_CHAR_DIGIT = 2; + private static final int NUMBER_CHAR_DECIMAL = 3; + private static final int NUMBER_CHAR_FRACTION_DIGIT = 4; + private static final int NUMBER_CHAR_EXP_E = 5; + private static final int NUMBER_CHAR_EXP_SIGN = 6; + private static final int NUMBER_CHAR_EXP_DIGIT = 7; + + /** The input JSON. */ + private final Reader in; + + private final boolean nonNumericNumbersSupported; + private final boolean jsonCSupported; + + static final int BUFFER_SIZE = 1024; + + /** + * Use a manual buffer to easily read and unread upcoming characters, and also so we can create + * strings without an intermediate StringBuilder. We decode literals directly out of this buffer, + * so it must be at least as long as the longest token that can be reported as a number. + */ + private final char[] buffer = new char[BUFFER_SIZE]; + + private int pos = 0; + private int limit = 0; + + private int lineNumber = 0; + private int lineStart = 0; + + int peeked = PEEKED_NONE; + + /** + * A peeked value that was composed entirely of digits with an optional leading dash. Positive + * values may not have a leading 0. + */ + private long peekedLong; + + /** + * The number of characters in a peeked number literal. Increment 'pos' by this after reading a + * number. + */ + private int peekedNumberLength; + + /** + * A peeked string that should be parsed on the next double, long or string. This is populated + * before a numeric value is parsed and used if that parsing fails. + */ + private String peekedString; + + /* + * The nesting stack. Using a manual array rather than an ArrayList saves 20%. + */ + private int[] stack = new int[32]; + private int stackSize = 0; + + { + stack[stackSize++] = JsonScope.EMPTY_DOCUMENT; + } + + /* + * The path members. It corresponds directly to stack: At indices where the + * stack contains an object (EMPTY_OBJECT, DANGLING_NAME or NONEMPTY_OBJECT), + * pathNames contains the name at this scope. Where it contains an array + * (EMPTY_ARRAY, NONEMPTY_ARRAY) pathIndices contains the current index in + * that array. Otherwise the value is undefined, and we take advantage of that + * by incrementing pathIndices when doing so isn't useful. + */ + private String[] pathNames = new String[32]; + private int[] pathIndices = new int[32]; + + /** Creates a new instance that reads a JSON-encoded stream from {@code in}. */ + public CustomGsonReader(Reader in, JsonOptions options) { + super(in); + this.in = Objects.requireNonNull(in, "in == null"); + if (options == null) { + this.nonNumericNumbersSupported = true; + this.jsonCSupported = false; + } else { + this.nonNumericNumbersSupported = options.isNonNumericNumbersSupported(); + this.jsonCSupported = options.isJsoncSupported(); + } + } + + /** + * Consumes the next token from the JSON stream and asserts that it is the beginning of a new + * array. + * + * @throws IllegalStateException if the next token is not the beginning of an array. + */ + public void beginArray() throws IOException { + int p = peeked; + if (p == PEEKED_NONE) { + p = doPeek(); + } + if (p == PEEKED_BEGIN_ARRAY) { + push(JsonScope.EMPTY_ARRAY); + pathIndices[stackSize - 1] = 0; + peeked = PEEKED_NONE; + } else { + throw unexpectedTokenError("BEGIN_ARRAY"); + } + } + + /** + * Consumes the next token from the JSON stream and asserts that it is the end of the current + * array. + * + * @throws IllegalStateException if the next token is not the end of an array. + */ + public void endArray() throws IOException { + int p = peeked; + if (p == PEEKED_NONE) { + p = doPeek(); + } + if (p == PEEKED_END_ARRAY) { + stackSize--; + pathIndices[stackSize - 1]++; + peeked = PEEKED_NONE; + } else { + throw unexpectedTokenError("END_ARRAY"); + } + } + + /** + * Consumes the next token from the JSON stream and asserts that it is the beginning of a new + * object. + * + * @throws IllegalStateException if the next token is not the beginning of an object. + */ + public void beginObject() throws IOException { + int p = peeked; + if (p == PEEKED_NONE) { + p = doPeek(); + } + if (p == PEEKED_BEGIN_OBJECT) { + push(JsonScope.EMPTY_OBJECT); + peeked = PEEKED_NONE; + } else { + throw unexpectedTokenError("BEGIN_OBJECT"); + } + } + + /** + * Consumes the next token from the JSON stream and asserts that it is the end of the current + * object. + * + * @throws IllegalStateException if the next token is not the end of an object. + */ + public void endObject() throws IOException { + int p = peeked; + if (p == PEEKED_NONE) { + p = doPeek(); + } + if (p == PEEKED_END_OBJECT) { + stackSize--; + pathNames[stackSize] = null; // Free the last path name so that it can be garbage collected! + pathIndices[stackSize - 1]++; + peeked = PEEKED_NONE; + } else { + throw unexpectedTokenError("END_OBJECT"); + } + } + + /** Returns true if the current array or object has another element. */ + public boolean hasNext() throws IOException { + int p = peeked; + if (p == PEEKED_NONE) { + p = doPeek(); + } + return p != PEEKED_END_OBJECT && p != PEEKED_END_ARRAY && p != PEEKED_EOF; + } + + /** Returns the type of the next token without consuming it. */ + public JsonToken peek() throws IOException { + int p = peeked; + if (p == PEEKED_NONE) { + p = doPeek(); + } + + switch (p) { + case PEEKED_BEGIN_OBJECT: + return JsonToken.BEGIN_OBJECT; + + case PEEKED_END_OBJECT: + return JsonToken.END_OBJECT; + + case PEEKED_BEGIN_ARRAY: + return JsonToken.BEGIN_ARRAY; + + case PEEKED_END_ARRAY: + return JsonToken.END_ARRAY; + + case PEEKED_DOUBLE_QUOTED_NAME: + return JsonToken.NAME; + + case PEEKED_TRUE: + case PEEKED_FALSE: + return JsonToken.BOOLEAN; + + case PEEKED_NULL: + return JsonToken.NULL; + + case PEEKED_DOUBLE_QUOTED: + case PEEKED_BUFFERED: + return JsonToken.STRING; + + case PEEKED_LONG: + case PEEKED_NUMBER: + return JsonToken.NUMBER; + + case PEEKED_EOF: + return JsonToken.END_DOCUMENT; + + default: + throw new AssertionError(); + } + } + + @SuppressWarnings("fallthrough") + int doPeek() throws IOException { + int peekStack = stack[stackSize - 1]; + if (peekStack == JsonScope.EMPTY_ARRAY) { + stack[stackSize - 1] = JsonScope.NONEMPTY_ARRAY; + } else if (peekStack == JsonScope.NONEMPTY_ARRAY) { + // Look for a comma before the next element. + int c = nextNonWhitespace(true); + switch (c) { + case ']': + return peeked = PEEKED_END_ARRAY; + + case ';': + throw syntaxError("Unsupported array element separator ';'"); + + case ',': + break; + + default: + throw syntaxError("Unterminated array"); + } + } else if (peekStack == JsonScope.EMPTY_OBJECT || peekStack == JsonScope.NONEMPTY_OBJECT) { + stack[stackSize - 1] = JsonScope.DANGLING_NAME; + // Look for a comma before the next element. + if (peekStack == JsonScope.NONEMPTY_OBJECT) { + int c = nextNonWhitespace(true); + switch (c) { + case '}': + return peeked = PEEKED_END_OBJECT; + + case ';': + throw syntaxError("Unsupported object member separator ';'"); + + case ',': + break; + + default: + throw syntaxError("Unterminated object"); + } + } + int c = nextNonWhitespace(true); + switch (c) { + case '"': + return peeked = PEEKED_DOUBLE_QUOTED_NAME; + + case '\'': + throw syntaxError("Unsupported name quoting character: '"); + + case '}': + if (peekStack != JsonScope.NONEMPTY_OBJECT) { + return peeked = PEEKED_END_OBJECT; + } else { + throw syntaxError("Expected name"); + } + default: + throw syntaxError("Expected name"); + } + } else if (peekStack == JsonScope.DANGLING_NAME) { + stack[stackSize - 1] = JsonScope.NONEMPTY_OBJECT; + // Look for a colon before the value. + int c = nextNonWhitespace(true); + switch (c) { + case ':': + break; + + case '=': + default: + throw syntaxError("Expected ':'"); + } + } else if (peekStack == JsonScope.EMPTY_DOCUMENT) { + stack[stackSize - 1] = JsonScope.NONEMPTY_DOCUMENT; + } else if (peekStack == JsonScope.NONEMPTY_DOCUMENT) { + int c = nextNonWhitespace(false); + if (c == -1) { + return peeked = PEEKED_EOF; + } else { + throw syntaxError("Unexpected additional value at root of document."); + } + } else if (peekStack == JsonScope.CLOSED) { + throw new IllegalStateException("JsonReader is closed"); + } + + int c = nextNonWhitespace(true); + switch (c) { + case ']': + if (peekStack == JsonScope.EMPTY_ARRAY) { + return peeked = PEEKED_END_ARRAY; + } + // fall-through to handle ",]" + case ';': + case ',': + // In lenient mode, a 0-length literal in an array means 'null'. + if (peekStack == JsonScope.EMPTY_ARRAY || peekStack == JsonScope.NONEMPTY_ARRAY) { + throw syntaxError("Expected array value"); + } else { + throw syntaxError("Unexpected value"); + } + case '\'': + // + throw syntaxError("Unsupported quoting character: '"); + + case '"': + return peeked = PEEKED_DOUBLE_QUOTED; + + case '[': + return peeked = PEEKED_BEGIN_ARRAY; + + case '{': + return peeked = PEEKED_BEGIN_OBJECT; + + default: + pos--; // Don't consume the first character in a literal value. + } + + int result = peekKeyword(); + if (result != PEEKED_NONE) { + return result; + } + + result = peekNumber(); + if (result != PEEKED_NONE) { + return result; + } + + if (!isLiteral(buffer[pos])) { + throw syntaxError("Expected value"); + } + + throw syntaxError("Unsupported unquoted string value."); + } + + private int peekKeyword() throws IOException { + // Figure out which keyword we're matching against by its first character. + char c = buffer[pos]; + String keyword; + String keywordUpper; + int peeking; + + // Look at the first letter to determine what keyword we are trying to match. + if (c == 't' || c == 'T') { + keyword = "true"; + keywordUpper = "TRUE"; + peeking = PEEKED_TRUE; + } else if (c == 'f' || c == 'F') { + keyword = "false"; + keywordUpper = "FALSE"; + peeking = PEEKED_FALSE; + } else if (c == 'n' || c == 'N') { + keyword = "null"; + keywordUpper = "NULL"; + peeking = PEEKED_NULL; + } else { + return PEEKED_NONE; + } + + // Confirm that chars [0..length) match the keyword. + int length = keyword.length(); + for (int i = 0; i < length; i++) { + if (pos + i >= limit && !fillBuffer(i + 1)) { + return PEEKED_NONE; + } + c = buffer[pos + i]; + boolean matched = c == keyword.charAt(i) || (c == keywordUpper.charAt(i)); + if (!matched) { + return PEEKED_NONE; + } + } + + if ((pos + length < limit || fillBuffer(length + 1)) && isLiteral(buffer[pos + length])) { + return PEEKED_NONE; // Don't match trues, falsey or nullsoft! + } + + // We've found the keyword followed either by EOF or by a non-literal character. + pos += length; + return peeked = peeking; + } + + private int peekNumber() throws IOException { + // Like nextNonWhitespace, this uses locals 'p' and 'l' to save inner-loop field access. + char[] buffer = this.buffer; + int p = pos; + int l = limit; + + long value = 0; // Negative to accommodate Long.MIN_VALUE more easily. + boolean negative = false; + boolean fitsInLong = true; + int last = NUMBER_CHAR_NONE; + + int i = 0; + + charactersOfNumber: for (; true; i++) { + if (p + i == l) { + if (i == buffer.length) { + // Though this looks like a well-formed number, it's too long to continue reading. Give up + // and let the application handle this as an unquoted literal. + return PEEKED_NONE; + } + if (!fillBuffer(i + 1)) { + break; + } + p = pos; + l = limit; + } + + char c = buffer[p + i]; + switch (c) { + case '-': + if (last == NUMBER_CHAR_NONE) { + negative = true; + last = NUMBER_CHAR_SIGN; + continue; + } else if (last == NUMBER_CHAR_EXP_E) { + last = NUMBER_CHAR_EXP_SIGN; + continue; + } + return PEEKED_NONE; + + case '+': + if (last == NUMBER_CHAR_NONE) { + last = NUMBER_CHAR_SIGN; + continue; + } else if (last == NUMBER_CHAR_EXP_E) { + last = NUMBER_CHAR_EXP_SIGN; + continue; + } + return PEEKED_NONE; + + case 'e': + case 'E': + if (last == NUMBER_CHAR_DIGIT || last == NUMBER_CHAR_FRACTION_DIGIT) { + last = NUMBER_CHAR_EXP_E; + continue; + } + return PEEKED_NONE; + + case '.': + if (last == NUMBER_CHAR_DIGIT) { + last = NUMBER_CHAR_DECIMAL; + continue; + } + return PEEKED_NONE; + + default: + if (nonNumericNumbersSupported) { + if (c == 'N' && l - (p + i) == 3) { + if (buffer[p + i + 1] == 'a' && buffer[p + i + 2] == 'N') { + peekedNumberLength = i + 3; + return peeked = PEEKED_NUMBER; + } + } else if (c == 'I' && l - (p + i) == 8) { + if (buffer[p + i + 1] == 'n' + && buffer[p + i + 2] == 'f' + && buffer[p + i + 3] == 'i' + && buffer[p + i + 4] == 'n' + && buffer[p + i + 5] == 'i' + && buffer[p + i + 6] == 't' + && buffer[p + i + 7] == 'y') { + peekedNumberLength = i + 8; + return peeked = PEEKED_NUMBER; + } + } + } + + if (c < '0' || c > '9') { + if (!isLiteral(c)) { + break charactersOfNumber; + } + return PEEKED_NONE; + } + if (last == NUMBER_CHAR_SIGN || last == NUMBER_CHAR_NONE) { + value = -(c - '0'); + last = NUMBER_CHAR_DIGIT; + } else if (last == NUMBER_CHAR_DIGIT) { + if (value == 0) { + return PEEKED_NONE; // Leading '0' prefix is not allowed (since it could be octal). + } + long newValue = value * 10 - (c - '0'); + fitsInLong + &= value > MIN_INCOMPLETE_INTEGER || (value == MIN_INCOMPLETE_INTEGER && newValue < value); + value = newValue; + } else if (last == NUMBER_CHAR_DECIMAL) { + last = NUMBER_CHAR_FRACTION_DIGIT; + } else if (last == NUMBER_CHAR_EXP_E || last == NUMBER_CHAR_EXP_SIGN) { + last = NUMBER_CHAR_EXP_DIGIT; + } + } + } + + // We've read a complete number. Decide if it's a PEEKED_LONG or a PEEKED_NUMBER. + // Don't store -0 as long; user might want to read it as double -0.0 + // Don't try to convert Long.MIN_VALUE to positive long; it would overflow MAX_VALUE + if (last == NUMBER_CHAR_DIGIT + && fitsInLong + && (value != Long.MIN_VALUE || negative) + && (value != 0 || !negative)) { + peekedLong = negative ? value : -value; + pos += i; + return peeked = PEEKED_LONG; + } else if (last == NUMBER_CHAR_DIGIT || last == NUMBER_CHAR_FRACTION_DIGIT || last == NUMBER_CHAR_EXP_DIGIT) { + peekedNumberLength = i; + return peeked = PEEKED_NUMBER; + } else { + return PEEKED_NONE; + } + } + + private boolean isLiteral(char c) throws IOException { + switch (c) { + case '/': + case '\\': + case ';': + case '#': + case '=': + throw syntaxError("Unsupported character: " + c); + + case '{': + case '}': + case '[': + case ']': + case ':': + case ',': + case ' ': + case '\t': + case '\f': + case '\r': + case '\n': + return false; + + default: + return true; + } + } + + /** + * Returns the next token, a {@link JsonToken#NAME property name}, and consumes it. + * + * @throws IllegalStateException if the next token is not a property name. + */ + public String nextName() throws IOException { + int p = peeked; + if (p == PEEKED_NONE) { + p = doPeek(); + } + String result; + if (p == PEEKED_DOUBLE_QUOTED_NAME) { + result = nextQuotedValue(); + } else { + throw unexpectedTokenError("a name"); + } + peeked = PEEKED_NONE; + pathNames[stackSize - 1] = result; + return result; + } + + /** + * Returns the {@link JsonToken#STRING string} value of the next token, consuming it. If the next + * token is a number, this method will return its string form. + * + * @throws IllegalStateException if the next token is not a string. + */ + public String nextString() throws IOException { + int p = peeked; + if (p == PEEKED_NONE) { + p = doPeek(); + } + String result; + if (p == PEEKED_DOUBLE_QUOTED) { + result = nextQuotedValue(); + } else if (p == PEEKED_BUFFERED) { + result = peekedString; + peekedString = null; + } else if (p == PEEKED_LONG) { + result = Long.toString(peekedLong); + } else if (p == PEEKED_NUMBER) { + result = new String(buffer, pos, peekedNumberLength); + pos += peekedNumberLength; + } else { + throw unexpectedTokenError("a string"); + } + peeked = PEEKED_NONE; + pathIndices[stackSize - 1]++; + return result; + } + + /** + * Returns the {@link JsonToken#BOOLEAN boolean} value of the next token, consuming it. + * + * @throws IllegalStateException if the next token is not a boolean. + */ + public boolean nextBoolean() throws IOException { + int p = peeked; + if (p == PEEKED_NONE) { + p = doPeek(); + } + if (p == PEEKED_TRUE) { + peeked = PEEKED_NONE; + pathIndices[stackSize - 1]++; + return true; + } else if (p == PEEKED_FALSE) { + peeked = PEEKED_NONE; + pathIndices[stackSize - 1]++; + return false; + } + throw unexpectedTokenError("a boolean"); + } + + /** + * Consumes the next token from the JSON stream and asserts that it is a literal null. + * + * @throws IllegalStateException if the next token is not a JSON null. + */ + public void nextNull() throws IOException { + int p = peeked; + if (p == PEEKED_NONE) { + p = doPeek(); + } + if (p == PEEKED_NULL) { + peeked = PEEKED_NONE; + pathIndices[stackSize - 1]++; + } else { + throw unexpectedTokenError("null"); + } + } + + /** + * Returns the {@link JsonToken#NUMBER double} value of the next token, consuming it. If the next + * token is a string, this method will attempt to parse it as a double using {@link + * Double#parseDouble(String)}. + * + * @throws IllegalStateException if the next token is neither a number nor a string. + * @throws NumberFormatException if the next literal value cannot be parsed as a double. + * @throws MalformedJsonException if the next literal value is NaN or Infinity and this reader is + * not {@link #setStrictness(Strictness) lenient}. + */ + public double nextDouble() throws IOException { + int p = peeked; + if (p == PEEKED_NONE) { + p = doPeek(); + } + + if (p == PEEKED_LONG) { + peeked = PEEKED_NONE; + pathIndices[stackSize - 1]++; + return (double) peekedLong; + } + + if (p == PEEKED_NUMBER) { + peekedString = new String(buffer, pos, peekedNumberLength); + pos += peekedNumberLength; + } else if (p != PEEKED_BUFFERED) { + throw unexpectedTokenError("a double"); + } + + peeked = PEEKED_BUFFERED; + double result = Double.parseDouble(peekedString); // don't catch this NumberFormatException. + if (!nonNumericNumbersSupported && (Double.isNaN(result) || Double.isInfinite(result))) { + throw syntaxError("JSON forbids NaN and infinities: " + result); + } + peekedString = null; + peeked = PEEKED_NONE; + pathIndices[stackSize - 1]++; + return result; + } + + /** + * Returns the {@link JsonToken#NUMBER long} value of the next token, consuming it. If the next + * token is a string, this method will attempt to parse it as a long. If the next token's numeric + * value cannot be exactly represented by a Java {@code long}, this method throws. + * + * @throws IllegalStateException if the next token is neither a number nor a string. + * @throws NumberFormatException if the next literal value cannot be parsed as a number, or + * exactly represented as a long. + */ + public long nextLong() throws IOException { + int p = peeked; + if (p == PEEKED_NONE) { + p = doPeek(); + } + + if (p == PEEKED_LONG) { + peeked = PEEKED_NONE; + pathIndices[stackSize - 1]++; + return peekedLong; + } + + if (p == PEEKED_NUMBER) { + peekedString = new String(buffer, pos, peekedNumberLength); + pos += peekedNumberLength; + } else if (p == PEEKED_DOUBLE_QUOTED) { + peekedString = nextQuotedValue(); + try { + long result = Long.parseLong(peekedString); + peeked = PEEKED_NONE; + pathIndices[stackSize - 1]++; + return result; + } catch (NumberFormatException ignored) { + // Fall back to parse as a double below. + } + } else { + throw unexpectedTokenError("a long"); + } + + peeked = PEEKED_BUFFERED; + double asDouble = Double.parseDouble(peekedString); // don't catch this NumberFormatException. + long result = (long) asDouble; + if (result != asDouble) { // Make sure no precision was lost casting to 'long'. + throw new NumberFormatException("Expected a long but was " + peekedString + locationString()); + } + peekedString = null; + peeked = PEEKED_NONE; + pathIndices[stackSize - 1]++; + return result; + } + + /** + * Returns the string up to but not including {@code quote}, unescaping any character escape + * sequences encountered along the way. The opening quote should have already been read. This + * consumes the closing quote, but does not include it in the returned string. + */ + private String nextQuotedValue() throws IOException { + // Like nextNonWhitespace, this uses locals 'p' and 'l' to save inner-loop field access. + char[] buffer = this.buffer; + StringBuilder builder = null; + while (true) { + int p = pos; + int l = limit; + /* the index of the first character not yet appended to the builder. */ + int start = p; + while (p < l) { + int c = buffer[p++]; + + // In strict mode, throw an exception when meeting unescaped control characters (U+0000 + // through U+001F) + if (c < 0x20) { + throw syntaxError("Unescaped control characters (\\u0000-\\u001F) are not allowed in strict mode"); + } else if (c == '"') { + pos = p; + int len = p - start - 1; + if (builder == null) { + return new String(buffer, start, len); + } else { + builder.append(buffer, start, len); + return builder.toString(); + } + } else if (c == '\\') { + pos = p; + int len = p - start - 1; + if (builder == null) { + int estimatedLength = (len + 1) * 2; + builder = new StringBuilder(Math.max(estimatedLength, 16)); + } + builder.append(buffer, start, len); + builder.append(readEscapeCharacter()); + p = pos; + l = limit; + start = p; + } + } + + if (builder == null) { + int estimatedLength = (p - start) * 2; + builder = new StringBuilder(Math.max(estimatedLength, 16)); + } + builder.append(buffer, start, p - start); + pos = p; + if (!fillBuffer(1)) { + throw syntaxError("Unterminated string"); + } + } + } + + private void skipQuotedValue() throws IOException { + // Like nextNonWhitespace, this uses locals 'p' and 'l' to save inner-loop field access. + char[] buffer = this.buffer; + do { + int p = pos; + int l = limit; + /* the index of the first character not yet appended to the builder. */ + while (p < l) { + int c = buffer[p++]; + if (c == '"') { + pos = p; + return; + } else if (c == '\\') { + pos = p; + char unused = readEscapeCharacter(); + p = pos; + l = limit; + } else if (c == '\n') { + lineNumber++; + lineStart = p; + } + } + pos = p; + } while (fillBuffer(1)); + throw syntaxError("Unterminated string"); + } + + /** + * Returns the {@link JsonToken#NUMBER int} value of the next token, consuming it. If the next + * token is a string, this method will attempt to parse it as an int. If the next token's numeric + * value cannot be exactly represented by a Java {@code int}, this method throws. + * + * @throws IllegalStateException if the next token is neither a number nor a string. + * @throws NumberFormatException if the next literal value cannot be parsed as a number, or + * exactly represented as an int. + */ + public int nextInt() throws IOException { + int p = peeked; + if (p == PEEKED_NONE) { + p = doPeek(); + } + + int result; + if (p == PEEKED_LONG) { + result = (int) peekedLong; + if (peekedLong != result) { // Make sure no precision was lost casting to 'int'. + throw new NumberFormatException("Expected an int but was " + peekedLong + locationString()); + } + peeked = PEEKED_NONE; + pathIndices[stackSize - 1]++; + return result; + } + + if (p == PEEKED_NUMBER) { + peekedString = new String(buffer, pos, peekedNumberLength); + pos += peekedNumberLength; + } else if (p == PEEKED_DOUBLE_QUOTED) { + peekedString = nextQuotedValue(); + try { + result = Integer.parseInt(peekedString); + peeked = PEEKED_NONE; + pathIndices[stackSize - 1]++; + return result; + } catch (NumberFormatException ignored) { + // Fall back to parse as a double below. + } + } else { + throw unexpectedTokenError("an int"); + } + + peeked = PEEKED_BUFFERED; + double asDouble = Double.parseDouble(peekedString); // don't catch this NumberFormatException. + result = (int) asDouble; + if (result != asDouble) { // Make sure no precision was lost casting to 'int'. + throw new NumberFormatException("Expected an int but was " + peekedString + locationString()); + } + peekedString = null; + peeked = PEEKED_NONE; + pathIndices[stackSize - 1]++; + return result; + } + + /** + * Closes this JSON reader and the underlying {@link Reader}. + * + *

        Using the JSON reader after it has been closed will throw an {@link IllegalStateException} + * in most cases. + */ + @Override + public void close() throws IOException { + peeked = PEEKED_NONE; + stack[0] = JsonScope.CLOSED; + stackSize = 1; + in.close(); + } + + /** + * Skips the next value recursively. This method is intended for use when the JSON token stream + * contains unrecognized or unhandled values. + * + *

        The behavior depends on the type of the next JSON token: + * + *

          + *
        • Start of a JSON array or object: It and all of its nested values are skipped. + *
        • Primitive value (for example a JSON number): The primitive value is skipped. + *
        • Property name: Only the name but not the value of the property is skipped. {@code + * skipValue()} has to be called again to skip the property value as well. + *
        • End of a JSON array or object: Only this end token is skipped. + *
        • End of JSON document: Skipping has no effect, the next token continues to be the end of + * the document. + *
        + */ + public void skipValue() throws IOException { + int count = 0; + do { + int p = peeked; + if (p == PEEKED_NONE) { + p = doPeek(); + } + + switch (p) { + case PEEKED_BEGIN_ARRAY: + push(JsonScope.EMPTY_ARRAY); + count++; + break; + + case PEEKED_BEGIN_OBJECT: + push(JsonScope.EMPTY_OBJECT); + count++; + break; + + case PEEKED_END_ARRAY: + stackSize--; + count--; + break; + + case PEEKED_END_OBJECT: + // Only update when object end is explicitly skipped, otherwise stack is not updated + // anyways + if (count == 0) { + // Free the last path name so that it can be garbage collected + pathNames[stackSize - 1] = null; + } + stackSize--; + count--; + break; + + case PEEKED_DOUBLE_QUOTED: + skipQuotedValue(); + break; + + case PEEKED_DOUBLE_QUOTED_NAME: + skipQuotedValue(); + // Only update when name is explicitly skipped, otherwise stack is not updated anyways + if (count == 0) { + pathNames[stackSize - 1] = ""; + } + break; + + case PEEKED_NUMBER: + pos += peekedNumberLength; + break; + + case PEEKED_EOF: + // Do nothing + return; + + default: + // For all other tokens there is nothing to do; token has already been consumed from + // underlying reader + } + peeked = PEEKED_NONE; + } while (count > 0); + + pathIndices[stackSize - 1]++; + } + + private void push(int newTop) { + if (stackSize == stack.length) { + int newLength = stackSize * 2; + stack = Arrays.copyOf(stack, newLength); + pathIndices = Arrays.copyOf(pathIndices, newLength); + pathNames = Arrays.copyOf(pathNames, newLength); + } + stack[stackSize++] = newTop; + } + + /** + * Returns true once {@code limit - pos >= minimum}. If the data is exhausted before that many + * characters are available, this returns false. + */ + private boolean fillBuffer(int minimum) throws IOException { + char[] buffer = this.buffer; + lineStart -= pos; + if (limit != pos) { + limit -= pos; + System.arraycopy(buffer, pos, buffer, 0, limit); + } else { + limit = 0; + } + + pos = 0; + int total; + while ((total = in.read(buffer, limit, buffer.length - limit)) != -1) { + limit += total; + + // if this is the first read, consume an optional byte order mark (BOM) if it exists + if (lineNumber == 0 && lineStart == 0 && limit > 0 && buffer[0] == '\ufeff') { + pos++; + lineStart++; + minimum++; + } + + if (limit >= minimum) { + return true; + } + } + return false; + } + + /** + * Returns the next character in the stream that is neither whitespace nor a part of a comment. + * When this returns, the returned character is always at {@code buffer[pos-1]}; this means the + * caller can always push back the returned character by decrementing {@code pos}. + */ + private int nextNonWhitespace(boolean throwOnEof) throws IOException { + /* + * This code uses ugly local variables 'p' and 'l' representing the 'pos' + * and 'limit' fields respectively. Using locals rather than fields saves + * a few field reads for each whitespace character in a pretty-printed + * document, resulting in a 5% speedup. We need to flush 'p' to its field + * before any (potentially indirect) call to fillBuffer() and reread both + * 'p' and 'l' after any (potentially indirect) call to the same method. + */ + char[] buffer = this.buffer; + int p = pos; + int l = limit; + while (true) { + if (p == l) { + pos = p; + if (!fillBuffer(1)) { + break; + } + p = pos; + l = limit; + } + + int c = buffer[p++]; + if (c == '\n') { + lineNumber++; + lineStart = p; + continue; + } else if (c == ' ' || c == '\r' || c == '\t') { + continue; + } + + if (c == '/') { + pos = p; + if (p == l) { + pos--; // push back '/' so it's still in the buffer when this method returns + boolean charsLoaded = fillBuffer(2); + pos++; // consume the '/' again + if (!charsLoaded) { + return c; + } + } + + if (!jsonCSupported) { + throw syntaxError("Unsupported JSON C-style comment."); + } + char peek = buffer[pos]; + switch (peek) { + case '*': + // skip a /* c-style comment */ + pos++; + if (!skipTo()) { + throw syntaxError("Unterminated comment"); + } + p = pos + 2; + l = limit; + continue; + + case '/': + // skip a // end-of-line comment + pos++; + skipToEndOfLine(); + p = pos; + l = limit; + continue; + + default: + return c; + } + } else if (c == '#') { + pos = p; + // Throw on '#' comment. + throw syntaxError("Unsupported '#' comment."); + } else { + pos = p; + return c; + } + } + if (throwOnEof) { + throw new EOFException("End of input" + locationString()); + } else { + return -1; + } + } + + /** + * Advances the position until after the next newline character. If the line is terminated by + * "\r\n", the '\n' must be consumed as whitespace by the caller. + */ + private void skipToEndOfLine() throws IOException { + while (pos < limit || fillBuffer(1)) { + char c = buffer[pos++]; + if (c == '\n') { + lineNumber++; + lineStart = pos; + break; + } else if (c == '\r') { + break; + } + } + } + + /** + * + */ + private boolean skipTo() throws IOException { + int length = "*/".length(); + outer: for (; pos + length <= limit || fillBuffer(length); pos++) { + if (buffer[pos] == '\n') { + lineNumber++; + lineStart = pos + 1; + continue; + } + for (int c = 0; c < length; c++) { + if (buffer[pos + c] != "*/".charAt(c)) { + continue outer; + } + } + return true; + } + return false; + } + + @Override + public String toString() { + return getClass().getSimpleName() + locationString(); + } + + String locationString() { + int line = lineNumber + 1; + int column = pos - lineStart + 1; + return " at line " + line + " column " + column + " path " + getPath(); + } + + private String getPath(boolean usePreviousPath) { + StringBuilder result = new StringBuilder().append('$'); + for (int i = 0; i < stackSize; i++) { + int scope = stack[i]; + switch (scope) { + case JsonScope.EMPTY_ARRAY: + case JsonScope.NONEMPTY_ARRAY: + int pathIndex = pathIndices[i]; + // If index is last path element it points to next array element; have to decrement + if (usePreviousPath && pathIndex > 0 && i == stackSize - 1) { + pathIndex--; + } + result.append('[').append(pathIndex).append(']'); + break; + + case JsonScope.EMPTY_OBJECT: + case JsonScope.DANGLING_NAME: + case JsonScope.NONEMPTY_OBJECT: + result.append('.'); + if (pathNames[i] != null) { + result.append(pathNames[i]); + } + break; + + case JsonScope.NONEMPTY_DOCUMENT: + case JsonScope.EMPTY_DOCUMENT: + case JsonScope.CLOSED: + break; + + default: + throw new AssertionError("Unknown scope value: " + scope); + } + } + return result.toString(); + } + + /** + * Returns a JSONPath in dot-notation + * to the next (or current) location in the JSON document. That means: + * + *
          + *
        • For JSON arrays the path points to the index of the next element (even if there are no + * further elements). + *
        • For JSON objects the path points to the last property, or to the current property if its + * name has already been consumed. + *
        + * + *

        This method can be useful to add additional context to exception messages before a + * value is consumed, for example when the {@linkplain #peek() peeked} token is unexpected. + */ + public String getPath() { + return getPath(false); + } + + /** + * Returns a JSONPath in dot-notation + * to the previous (or current) location in the JSON document. That means: + * + *

          + *
        • For JSON arrays the path points to the index of the previous element.
          + * If no element has been consumed yet it uses the index 0 (even if there are no elements). + *
        • For JSON objects the path points to the last property, or to the current property if its + * name has already been consumed. + *
        + * + *

        This method can be useful to add additional context to exception messages after a + * value has been consumed. + */ + public String getPreviousPath() { + return getPath(true); + } + + /** + * Unescapes the character identified by the character or characters that immediately follow a + * backslash. The backslash '\' should have already been read. This supports both Unicode escapes + * "u000A" and two-character escapes "\n". + * + * @throws MalformedJsonException if the escape sequence is malformed + */ + @SuppressWarnings("fallthrough") + private char readEscapeCharacter() throws IOException { + if (pos == limit && !fillBuffer(1)) { + throw syntaxError("Unterminated escape sequence"); + } + + char escaped = buffer[pos++]; + switch (escaped) { + case 'u': + if (pos + 4 > limit && !fillBuffer(4)) { + throw syntaxError("Unterminated escape sequence"); + } + // Equivalent to Integer.parseInt(stringPool.get(buffer, pos, 4), 16); + int result = 0; + for (int i = pos, end = i + 4; i < end; i++) { + char c = buffer[i]; + result <<= 4; + if (c >= '0' && c <= '9') { + result += (c - '0'); + } else if (c >= 'a' && c <= 'f') { + result += (c - 'a' + 10); + } else if (c >= 'A' && c <= 'F') { + result += (c - 'A' + 10); + } else { + throw syntaxError("Malformed Unicode escape \\u" + new String(buffer, pos, 4)); + } + } + pos += 4; + return (char) result; + + case 't': + return '\t'; + + case 'b': + return '\b'; + + case 'n': + return '\n'; + + case 'r': + return '\r'; + + case 'f': + return '\f'; + + case '\n': + lineNumber++; + lineStart = pos; + // fall-through + + case '\'': + case '"': + case '\\': + case '/': + return escaped; + + default: + // throw error when none of the above cases are matched + throw syntaxError("Invalid escape sequence"); + } + } + + /** + * Throws a new {@link MalformedJsonException} with the given message and information about the + * current location. + */ + private MalformedJsonException syntaxError(String message) throws MalformedJsonException { + throw new MalformedJsonException(message + locationString()); + } + + private IllegalStateException unexpectedTokenError(String expected) throws IOException { + JsonToken peeked = peek(); + return new IllegalStateException("Expected " + expected + " but was " + peeked + locationString()); + } + + static final class JsonScope { + private JsonScope() { + } + + /** An array with no elements requires no separator before the next element. */ + static final int EMPTY_ARRAY = 1; + + /** An array with at least one value requires a separator before the next element. */ + static final int NONEMPTY_ARRAY = 2; + + /** An object with no name/value pairs requires no separator before the next element. */ + static final int EMPTY_OBJECT = 3; + + /** An object whose most recent element is a key. The next element must be a value. */ + static final int DANGLING_NAME = 4; + + /** An object with at least one name/value pair requires a separator before the next element. */ + static final int NONEMPTY_OBJECT = 5; + + /** No top-level value has been started yet. */ + static final int EMPTY_DOCUMENT = 6; + + /** A top-level value has already been started. */ + static final int NONEMPTY_DOCUMENT = 7; + + /** A document that's been closed and cannot be accessed. */ + static final int CLOSED = 8; + } +} diff --git a/sdk/core/azure-core-serializer-json-gson/src/main/java/com/azure/core/serializer/json/gson/implementation/GsonJsonReader.java b/sdk/core/azure-core-serializer-json-gson/src/main/java/com/azure/core/serializer/json/gson/implementation/GsonJsonReader.java index fc30a438e390..39e3291db3cd 100644 --- a/sdk/core/azure-core-serializer-json-gson/src/main/java/com/azure/core/serializer/json/gson/implementation/GsonJsonReader.java +++ b/sdk/core/azure-core-serializer-json-gson/src/main/java/com/azure/core/serializer/json/gson/implementation/GsonJsonReader.java @@ -30,6 +30,7 @@ public final class GsonJsonReader extends JsonReader { private JsonToken currentToken; private boolean consumed = false; + private Object value = null; private boolean complete = false; private int objectDepth = 0; @@ -52,7 +53,7 @@ public GsonJsonReader(Reader reader, byte[] jsonBytes, String jsonString, boolea @SuppressWarnings("deprecation") private static com.google.gson.stream.JsonReader createGsonReader(Reader reader, JsonOptions options) { - com.google.gson.stream.JsonReader gsonReader = new com.google.gson.stream.JsonReader(reader); + com.google.gson.stream.JsonReader gsonReader = new CustomGsonReader(reader, options); gsonReader.setLenient(options == null || options.isNonNumericNumbersSupported() || options.isJsoncSupported()); return gsonReader; @@ -133,13 +134,11 @@ public JsonToken nextToken() throws IOException { } } - com.google.gson.stream.JsonToken gsonToken = reader.peek(); - if (gsonToken == com.google.gson.stream.JsonToken.END_DOCUMENT) { + currentToken = mapToken(reader.peek()); + if (currentToken == JsonToken.END_DOCUMENT) { complete = true; } - currentToken = mapToken(reader.peek()); - // When within a type adapter context special handling needs to be performed. // GSON validates that the JSON sub-object stream is complete read when the value is returned from the // TypeAdapter, the design by default doesn't call 'endObject' when the end of the sub-object stream is seen. @@ -151,72 +150,102 @@ public JsonToken nextToken() throws IOException { } consumed = false; + value = null; return currentToken; } @Override public byte[] getBinary() throws IOException { - consumed = true; + if (consumed) { + return (byte[]) value; + } + consumed = true; if (currentToken == JsonToken.NULL) { reader.nextNull(); - return null; + value = null; } else { - return Base64.getDecoder().decode(reader.nextString()); + value = Base64.getDecoder().decode(reader.nextString()); } + + return (byte[]) value; } @Override public boolean getBoolean() throws IOException { - consumed = true; + if (consumed) { + return (boolean) value; + } - return reader.nextBoolean(); + consumed = true; + value = reader.nextBoolean(); + return (boolean) value; } @Override public double getDouble() throws IOException { - consumed = true; + if (consumed) { + return (double) value; + } - return reader.nextDouble(); + consumed = true; + value = reader.nextDouble(); + return (double) value; } @Override public float getFloat() throws IOException { - consumed = true; - - return (float) reader.nextDouble(); + return (float) getDouble(); } @Override public int getInt() throws IOException { - consumed = true; + if (consumed) { + return (int) value; + } - return reader.nextInt(); + consumed = true; + value = reader.nextInt(); + return (int) value; } @Override public long getLong() throws IOException { - consumed = true; + if (consumed) { + return (long) value; + } - return reader.nextLong(); + consumed = true; + value = reader.nextLong(); + return (long) value; } @Override public String getString() throws IOException { - consumed = true; + if (consumed) { + return (String) value; + } + consumed = true; if (currentToken == JsonToken.NULL) { - return null; + reader.nextNull(); + value = null; } else { - return reader.nextString(); + value = reader.nextString(); } + + return (String) value; } @Override public String getFieldName() throws IOException { - consumed = true; + if (consumed) { + return (String) value; + } - return reader.nextName(); + consumed = true; + value = reader.nextName(); + return (String) value; } @Override diff --git a/sdk/core/azure-core-serializer-json-gson/src/test/java/com/azure/core/serializer/json/gson/implementation/GsonJsonReaderContractTests.java b/sdk/core/azure-core-serializer-json-gson/src/test/java/com/azure/core/serializer/json/gson/implementation/GsonJsonReaderContractTests.java index 7be4d65d5604..38b3bcf5eb73 100644 --- a/sdk/core/azure-core-serializer-json-gson/src/test/java/com/azure/core/serializer/json/gson/implementation/GsonJsonReaderContractTests.java +++ b/sdk/core/azure-core-serializer-json-gson/src/test/java/com/azure/core/serializer/json/gson/implementation/GsonJsonReaderContractTests.java @@ -6,26 +6,19 @@ import com.azure.json.JsonOptions; import com.azure.json.JsonReader; import com.azure.json.contract.JsonReaderContractTests; -import com.google.gson.stream.MalformedJsonException; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; - /** * Tests {@link GsonJsonReader} against the contract required by {@link JsonReader}. */ public class GsonJsonReaderContractTests extends JsonReaderContractTests { private JsonReader reader; - String jsonWithComments = "{ // single line comment\n" + " \"single-line\": \"comment\",\n" + " /*\n" - + " multi-line comment\n" + " */\n" + " \"multi-line\": \"comment\"}"; @Override - public JsonReader getJsonReader(String json) throws IOException { - this.reader = AzureJsonUtils.createReader(json, new JsonOptions()); + public JsonReader getJsonReader(String json, JsonOptions options) throws IOException { + this.reader = AzureJsonUtils.createReader(json, options); return reader; } @@ -35,28 +28,4 @@ public void afterEach() throws IOException { reader.close(); } } - - @Test - public void readJsonc() throws IOException { - try (JsonReader jsonReader - = AzureJsonUtils.createReader(jsonWithComments, new JsonOptions().setJsoncSupported(true))) { - jsonReader.nextToken(); - String outputJson = jsonReader.readChildren(); - assertNotNull(outputJson); - } - } - - @Test - public void readJsoncFails() throws IOException { - assertThrows(MalformedJsonException.class, () -> { - // need to disable non-numeric number support as Gson only has a single "lenient" concept that both - // of these control. - try (JsonReader jsonReader = AzureJsonUtils.createReader(jsonWithComments, - new JsonOptions().setNonNumericNumbersSupported(false))) { - jsonReader.nextToken(); - String outputJson = jsonReader.readChildren(); - assertNotNull(outputJson); - } - }); - } } diff --git a/sdk/core/azure-core-serializer-json-jackson/CHANGELOG.md b/sdk/core/azure-core-serializer-json-jackson/CHANGELOG.md index 65ba5bd8613d..87c727ab93ab 100644 --- a/sdk/core/azure-core-serializer-json-jackson/CHANGELOG.md +++ b/sdk/core/azure-core-serializer-json-jackson/CHANGELOG.md @@ -10,6 +10,38 @@ ### Other Changes +## 1.5.8 (2025-03-10) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.55.2` to `1.55.3`. + +## 1.5.7 (2025-02-20) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.55.1` to `1.55.2`. + +## 1.5.6 (2025-02-12) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.55.0` to `1.55.1`. + +## 1.5.5 (2025-02-06) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.54.1` to `1.55.0`. + ## 1.5.4 (2024-11-14) ### 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 4a809c28d73b..b3781762df4b 100644 --- a/sdk/core/azure-core-serializer-json-jackson/README.md +++ b/sdk/core/azure-core-serializer-json-jackson/README.md @@ -48,7 +48,7 @@ add the direct dependency to your project as follows. com.azure azure-core-serializer-json-jackson - 1.5.4 + 1.5.8 ``` [//]: # ({x-version-update-end}) @@ -87,4 +87,4 @@ For details on contributing to this repository, see the [contributing guide](htt [jdk_link]: https://learn.microsoft.com/java/azure/jdk/?view=azure-java-stable [java8_client_compatibility]: https://learn.microsoft.com/azure/security/fundamentals/azure-ca-details?tabs=root-and-subordinate-cas-list#client-compatibility-for-public-pkis -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcore%2Fazure-core-serializer-json-jackson%2FREADME.png) + diff --git a/sdk/core/azure-core-serializer-json-jackson/pom.xml b/sdk/core/azure-core-serializer-json-jackson/pom.xml index 90931e30da84..0e8217dc3a7b 100644 --- a/sdk/core/azure-core-serializer-json-jackson/pom.xml +++ b/sdk/core/azure-core-serializer-json-jackson/pom.xml @@ -81,17 +81,17 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-xml - 1.1.0 + 1.2.0 com.azure azure-core - 1.55.0-beta.1 + 1.56.0-beta.1 @@ -125,7 +125,7 @@ com.azure azure-json - 1.3.0 + 1.5.0 test-jar test diff --git a/sdk/core/azure-core-serializer-json-jackson/src/test/java/com/azure/core/serializer/json/jackson/implementation/JacksonJsonReaderContractTests.java b/sdk/core/azure-core-serializer-json-jackson/src/test/java/com/azure/core/serializer/json/jackson/implementation/JacksonJsonReaderContractTests.java index 1a203e159b81..8164b20ce928 100644 --- a/sdk/core/azure-core-serializer-json-jackson/src/test/java/com/azure/core/serializer/json/jackson/implementation/JacksonJsonReaderContractTests.java +++ b/sdk/core/azure-core-serializer-json-jackson/src/test/java/com/azure/core/serializer/json/jackson/implementation/JacksonJsonReaderContractTests.java @@ -6,26 +6,19 @@ import com.azure.json.JsonOptions; import com.azure.json.JsonReader; import com.azure.json.contract.JsonReaderContractTests; -import com.fasterxml.jackson.core.JsonParseException; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; - /** * Tests {@link JacksonJsonReader} against the contract required by {@link JsonReader}. */ public class JacksonJsonReaderContractTests extends JsonReaderContractTests { private JsonReader reader; - String jsonWithComments = "{ // single line comment\n" + " \"single-line\": \"comment\",\n" + " /*\n" - + " multi-line comment\n" + " */\n" + " \"multi-line\": \"comment\"}"; @Override - public JsonReader getJsonReader(String json) throws IOException { - this.reader = AzureJsonUtils.createReader(json, null); + public JsonReader getJsonReader(String json, JsonOptions options) throws IOException { + this.reader = AzureJsonUtils.createReader(json, options); return reader; } @@ -35,26 +28,4 @@ public void afterEach() throws IOException { reader.close(); } } - - @Test - public void readJsonc() throws IOException { - - try (JsonReader jsonReader - = AzureJsonUtils.createReader(jsonWithComments, new JsonOptions().setJsoncSupported(true))) { - jsonReader.nextToken(); - String outputJson = jsonReader.readChildren(); - assertNotNull(outputJson); - } - } - - @Test - public void readJsoncFails() throws IOException { - assertThrows(JsonParseException.class, () -> { - try (JsonReader jsonReader = getJsonReader(jsonWithComments)) { - jsonReader.nextToken(); - String outputJson = jsonReader.readChildren(); - assertNotNull(outputJson); - } - }); - } } diff --git a/sdk/core/azure-core-test/CHANGELOG.md b/sdk/core/azure-core-test/CHANGELOG.md index e7ee60e7a6dd..e9d0580beef7 100644 --- a/sdk/core/azure-core-test/CHANGELOG.md +++ b/sdk/core/azure-core-test/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.27.0-beta.5 (Unreleased) +## 1.27.0-beta.9 (Unreleased) ### Features Added @@ -10,6 +10,38 @@ ### Other Changes +## 1.27.0-beta.8 (2025-03-10) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.55.2` to `1.55.3`. + +## 1.27.0-beta.7 (2025-02-20) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.55.1` to `1.55.2`. + +## 1.27.0-beta.6 (2025-02-12) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.55.0` to `1.55.1`. + +## 1.27.0-beta.5 (2025-02-06) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.54.1` to `1.55.0`. + ## 1.27.0-beta.4 (2024-11-14) ### Other Changes diff --git a/sdk/core/azure-core-test/README.md b/sdk/core/azure-core-test/README.md index 91b24343a767..7b88320e08cd 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.27.0-beta.4 + 1.27.0-beta.8 ``` @@ -353,4 +353,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcore%2Fazure-core-test%2FREADME.png) + diff --git a/sdk/core/azure-core-test/pom.xml b/sdk/core/azure-core-test/pom.xml index f05fd91be556..3a26f23e58c0 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.27.0-beta.5 + 1.27.0-beta.9 Microsoft Azure Java Core Test Library This package contains core test types for Azure Java clients. @@ -71,7 +71,7 @@ com.azure azure-core - 1.55.0-beta.1 + 1.56.0-beta.1 @@ -79,7 +79,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.20 + 1.1.0-beta.1 com.azure @@ -94,7 +94,7 @@ com.azure azure-core-http-vertx - 1.0.0-beta.25 + 1.1.0-beta.1 diff --git a/sdk/core/azure-core-tracing-opentelemetry-samples/README.md b/sdk/core/azure-core-tracing-opentelemetry-samples/README.md index bc08827055f2..7e04dc8d5413 100644 --- a/sdk/core/azure-core-tracing-opentelemetry-samples/README.md +++ b/sdk/core/azure-core-tracing-opentelemetry-samples/README.md @@ -14,4 +14,4 @@ This package contains samples for the `azure-core-tracing-opentelemetry` library ## Contributing -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcore%2Fazure-core-tracing-opentelemetry-samples%2FREADME.png) + diff --git a/sdk/core/azure-core-tracing-opentelemetry-samples/pom.xml b/sdk/core/azure-core-tracing-opentelemetry-samples/pom.xml index 18c9a7714445..9c3d54ead0db 100644 --- a/sdk/core/azure-core-tracing-opentelemetry-samples/pom.xml +++ b/sdk/core/azure-core-tracing-opentelemetry-samples/pom.xml @@ -39,7 +39,7 @@ com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.53 + 1.0.0-beta.57 @@ -52,31 +52,31 @@ com.azure azure-data-appconfiguration - 1.7.3 + 1.7.4 test io.opentelemetry opentelemetry-exporter-logging - 1.43.0 + 1.46.0 test io.opentelemetry opentelemetry-sdk-extension-autoconfigure - 1.43.0 + 1.46.0 test com.azure azure-security-keyvault-secrets - 4.9.1 + 4.9.3 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/core/azure-core-tracing-opentelemetry/CHANGELOG.md b/sdk/core/azure-core-tracing-opentelemetry/CHANGELOG.md index 161300bf4d27..4ec90f91127a 100644 --- a/sdk/core/azure-core-tracing-opentelemetry/CHANGELOG.md +++ b/sdk/core/azure-core-tracing-opentelemetry/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.0.0-beta.53 (Unreleased) +## 1.0.0-beta.57 (Unreleased) ### Features Added @@ -10,6 +10,39 @@ ### Other Changes +## 1.0.0-beta.56 (2025-03-10) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.55.2` to `1.55.3`. + +## 1.0.0-beta.55 (2025-02-20) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.55.1` to `1.55.2`. + +## 1.0.0-beta.54 (2025-02-12) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.55.0` to `1.55.1`. + +## 1.0.0-beta.53 (2025-02-06) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.54.1` to `1.55.0`. +- Upgraded OpenTelemetry from `1.43.0` to `1.46.0`. + ## 1.0.0-beta.52 (2024-11-14) ### Other Changes diff --git a/sdk/core/azure-core-tracing-opentelemetry/README.md b/sdk/core/azure-core-tracing-opentelemetry/README.md index ea56a2083d02..731141be5e27 100644 --- a/sdk/core/azure-core-tracing-opentelemetry/README.md +++ b/sdk/core/azure-core-tracing-opentelemetry/README.md @@ -52,7 +52,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.52 + 1.0.0-beta.56 ``` [//]: # ({x-version-update-end}) @@ -280,4 +280,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct](https://ope [source_code]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/core/azure-core-tracing-opentelemetry/src [event_hubs_samples]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/eventhubs/azure-messaging-eventhubs/src/samples/java/com/azure/messaging/eventhubs/PublishEventsTracingWithCustomContextSample.java -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcore%2Fazure-core-tracing-opentelemetry%2FREADME.png) + diff --git a/sdk/core/azure-core-tracing-opentelemetry/pom.xml b/sdk/core/azure-core-tracing-opentelemetry/pom.xml index 96eb9de4e476..c44710eb346c 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.53 + 1.0.0-beta.57 Microsoft Azure OpenTelemetry tracing plugin This package contains the OpenTelemetry tracing plugin for Azure client libraries. @@ -61,12 +61,12 @@ io.opentelemetry opentelemetry-api - 1.43.0 + 1.46.0 com.azure azure-core - 1.55.0-beta.1 + 1.56.0-beta.1 com.google.code.findbugs @@ -79,26 +79,26 @@ io.opentelemetry opentelemetry-sdk - 1.43.0 + 1.46.0 test com.azure azure-core-experimental - 1.0.0-beta.57 + 1.0.0-beta.61 test com.azure azure-core-test - 1.27.0-beta.5 + 1.27.0-beta.9 test io.opentelemetry opentelemetry-sdk-testing test - 1.43.0 + 1.46.0 io.projectreactor @@ -130,9 +130,9 @@ - io.opentelemetry:opentelemetry-api:[1.43.0] - io.opentelemetry:opentelemetry-sdk:[1.43.0] - io.opentelemetry:opentelemetry-sdk-testing:[1.43.0] + io.opentelemetry:opentelemetry-api:[1.46.0] + io.opentelemetry:opentelemetry-sdk:[1.46.0] + io.opentelemetry:opentelemetry-sdk-testing:[1.46.0] diff --git a/sdk/core/azure-core-version-tests/README.md b/sdk/core/azure-core-version-tests/README.md index 7c83c05a60ab..3e2353bed171 100644 --- a/sdk/core/azure-core-version-tests/README.md +++ b/sdk/core/azure-core-version-tests/README.md @@ -16,4 +16,4 @@ Provides end-to-end tests using the Core libraries as dependencies. -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcore%2Fazure-core-version-tests%2FREADME.png) + diff --git a/sdk/core/azure-core-version-tests/pom.xml b/sdk/core/azure-core-version-tests/pom.xml index 58be3b764147..bc13bcd492a6 100644 --- a/sdk/core/azure-core-version-tests/pom.xml +++ b/sdk/core/azure-core-version-tests/pom.xml @@ -60,7 +60,7 @@ com.azure azure-core - 1.55.0-beta.1 + 1.56.0-beta.1 com.azure @@ -111,7 +111,7 @@ com.azure azure-core-test - 1.27.0-beta.5 + 1.27.0-beta.9 diff --git a/sdk/core/azure-core/CHANGELOG.md b/sdk/core/azure-core/CHANGELOG.md index a6fd0251a33b..75cffa799d99 100644 --- a/sdk/core/azure-core/CHANGELOG.md +++ b/sdk/core/azure-core/CHANGELOG.md @@ -1,15 +1,55 @@ # Release History -## 1.55.0-beta.1 (Unreleased) +## 1.56.0-beta.1 (Unreleased) ### Features Added -- Added `azure.core.models.AzureCloud` expandable enum to represent different Azure clouds. +### Breaking Changes + +### Bugs Fixed + +### Other Changes + +## 1.55.3 (2025-03-10) + +### Other Changes + +#### Dependency Updates + +- Updated `azure-json` from `1.4.0` to `1.5.0`. + +## 1.55.2 (2025-02-20) + +### Other Changes + +- Fix for the `1.55.1` release as Netty dependencies weren't updated. + +## 1.55.1 (2025-02-12) + +### Other Changes + +#### Dependency Updates + +- Upgraded Netty dependencies from `4.1.115.Final` to `4.1.118.Final` to resolve a CVE. +- Upgraded Netty TcNative dependencies from `2.0.69.Final` to `2.0.70.Final` to resolve a CVE. + +## 1.55.0 (2025-02-06) + +### Features Added + +- Added `azure.core.models.AzureCloud` expandable enum to represent different Azure clouds. ([#43099](https://github.com/Azure/azure-sdk-for-java/pull/43099)) +- Added `CoreUtils.parseAuthenticateHeader` and `AuthenticateChallenge` class for parsing and consuming + `WWW-Authenticate` and `Proxy-Authenticate` headers. ([#43714](https://github.com/Azure/azure-sdk-for-java/pull/43714)) ### Other Changes - Removed length restriction on application id in `ClientOptions`. ([#42937](https://github.com/Azure/azure-sdk-for-java/pull/42937)) +#### Dependency Updates + +- Updated `azure-json` from `1.3.0` to `1.4.0`. +- Updated `azure-xml` from `1.1.0` to `1.2.0`. + ## 1.54.1 (2024-11-14) ### Bugs Fixed diff --git a/sdk/core/azure-core/README.md b/sdk/core/azure-core/README.md index 62709d75b043..9c50ed772ac0 100644 --- a/sdk/core/azure-core/README.md +++ b/sdk/core/azure-core/README.md @@ -66,7 +66,7 @@ add the direct dependency to your project as follows. com.azure azure-core - 1.54.1 + 1.55.3 ``` [//]: # ({x-version-update-end}) @@ -264,4 +264,4 @@ the [contributing guide](https://github.com/Azure/azure-sdk-for-java/blob/main/C [jdk_link]: https://learn.microsoft.com/java/azure/jdk/?view=azure-java-stable [java8_client_compatibility]: https://learn.microsoft.com/azure/security/fundamentals/azure-ca-details?tabs=root-and-subordinate-cas-list#client-compatibility-for-public-pkis -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcore%2Fazure-core%2FREADME.png) + diff --git a/sdk/core/azure-core/pom.xml b/sdk/core/azure-core/pom.xml index 036e86b9a22b..10427a171929 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.55.0-beta.1 + 1.56.0-beta.1 Microsoft Azure Java Core Library This package contains core types for Azure Java clients. @@ -103,12 +103,12 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-xml - 1.1.0 + 1.2.0 com.fasterxml.jackson.core @@ -155,7 +155,7 @@ com.azure azure-json - 1.3.0 + 1.5.0 test-jar test diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/models/AzureCloud.java b/sdk/core/azure-core/src/main/java/com/azure/core/models/AzureCloud.java index e6877f5838cb..0bca1dfda0d4 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/models/AzureCloud.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/models/AzureCloud.java @@ -20,7 +20,7 @@ public final class AzureCloud extends ExpandableStringEnum { /** * Azure US government cloud. */ - public static final AzureCloud AZURE_US_GOVERNMENT = fromString("AZURE_US_GOVERNMENT"); + public static final AzureCloud AZURE_US_GOVERNMENT_CLOUD = fromString("AZURE_US_GOVERNMENT"); /** * Creates or finds an AzureCloud from its string representation. diff --git a/sdk/core/azure-core/src/test/java/com/azure/core/implementation/jackson/JacksonJsonReaderContractTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/jackson/JacksonJsonReaderContractTests.java index 985d016dc5a9..184284fd2f92 100644 --- a/sdk/core/azure-core/src/test/java/com/azure/core/implementation/jackson/JacksonJsonReaderContractTests.java +++ b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/jackson/JacksonJsonReaderContractTests.java @@ -6,26 +6,19 @@ import com.azure.json.JsonOptions; import com.azure.json.JsonReader; import com.azure.json.contract.JsonReaderContractTests; -import com.fasterxml.jackson.core.JsonParseException; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; - /** * Tests {@link JacksonJsonReader} against the contract required by {@link JsonReader}. */ public class JacksonJsonReaderContractTests extends JsonReaderContractTests { private JsonReader reader; - String jsonWithComments = "{ // single line comment\n" + " \"single-line\": \"comment\",\n" + " /*\n" - + " multi-line comment\n" + " */\n" + " \"multi-line\": \"comment\"}"; @Override - public JsonReader getJsonReader(String json) throws IOException { - this.reader = AzureJsonUtils.createReader(json, null); + public JsonReader getJsonReader(String json, JsonOptions options) throws IOException { + this.reader = AzureJsonUtils.createReader(json, options); return reader; } @@ -35,26 +28,4 @@ public void afterEach() throws IOException { reader.close(); } } - - @Test - public void readJsonc() throws IOException { - try (JsonReader jsonReader - = AzureJsonUtils.createReader(jsonWithComments, new JsonOptions().setJsoncSupported(true))) { - jsonReader.nextToken(); - String outputJson = jsonReader.readChildren(); - assertNotNull(outputJson); - } - } - - @Test - public void readJsoncFails() throws IOException { - assertThrows(JsonParseException.class, () -> { - try (JsonReader jsonReader = getJsonReader(jsonWithComments)) { - jsonReader.nextToken(); - String outputJson = jsonReader.readChildren(); - assertNotNull(outputJson); - } - }); - } - } diff --git a/sdk/core/ci.yml b/sdk/core/ci.yml index ed7fdb306ada..7a03b3b14fcc 100644 --- a/sdk/core/ci.yml +++ b/sdk/core/ci.yml @@ -106,6 +106,10 @@ extends: groupId: com.azure safeName: azurecore releaseInBatch: ${{ parameters.release_azurecore }} + triggeringPaths: + - /eng + - /sdk/parents/azure-sdk-parent + - /sdk/parents/azure-client-sdk-parent - name: azure-core-amqp groupId: com.azure safeName: azurecoreamqp @@ -170,36 +174,25 @@ extends: # required by the above perf library - name: perf-test-core groupId: com.azure - AdditionalStagesAfterBuild: - - stage: DependencyVersionOverridesTests - displayName: 'Dependency Version Overrides' - dependsOn: [] - jobs: - - template: /eng/pipelines/templates/jobs/ci.versions.tests.yml - parameters: - Artifacts: - - name: azure-core-version-tests - groupId: com.azure - safeName: azurecoreversiontests - VersionOverrides: - - jackson_2.10 - - jackson_2.11 - - jackson_2.12 - - jackson_2.13 - - jackson_2.14 - - jackson_2.15 - - jackson_2.16 - - jackson_2.17 - - jackson_2.18 - - reactor_2020 - - reactor_2022 - - reactor_2023 - - reactor_2024 - TestGoals: surefire:test + + # This needs to be temporarily here for the PR pipeline. + MatrixConfigs: + - Name: Java_ci_test_base + Path: eng/pipelines/templates/stages/platform-matrix.json + Selection: sparse + NonSparseParameters: Agent + GenerateVMJobs: true + # Run separate version override tests using a different artifacts list + # This matrix config overrides the ArtifactsJson variable + AdditionalMatrixConfigs: + - Name: version_overrides_tests + Path: sdk/core/version-overrides-matrix.json + Selection: all + PRBatching: false + GenerateVMJobs: true LiveTestStages: - template: /sdk/storage/tests-template.yml parameters: AdditionalMatrixReplace: - TestFromSource=(.*)/true - diff --git a/sdk/core/version-overrides-matrix.json b/sdk/core/version-overrides-matrix.json new file mode 100644 index 000000000000..dee9c50836e1 --- /dev/null +++ b/sdk/core/version-overrides-matrix.json @@ -0,0 +1,37 @@ +{ + "matrix": { + "Agent": { + "ubuntu-20.04": { "OSVmImage": "env:LINUXVMIMAGE", "Pool": "env:LINUXPOOL" } + }, + "TestConfig": { + "version_override": { + "TestVersionSupport": true, + "VERSION_OVERRIDE_TESTS": true, + "TestGoals": "surefire:test", + // This has to be stringified json + "ArtifactsJson": "{ + \"name\": \"azure-core-version-tests\", + \"groupId\": \"com.azure\", + \"safeName\": \"azurecoreversiontests\" + }", + // blank this out so we don't pick up the defaults from ci.yml + "AdditionalModulesJson": "" + } + }, + "VersionOverride": [ + "jackson_2.10", + "jackson_2.11", + "jackson_2.12", + "jackson_2.13", + "jackson_2.14", + "jackson_2.15", + "jackson_2.16", + "jackson_2.17", + "jackson_2.18", + "reactor_2020", + "reactor_2022", + "reactor_2023", + "reactor_2024" + ] + } +} diff --git a/sdk/corev2/azure-core-test/CHANGELOG.md b/sdk/corev2/azure-core-test/CHANGELOG.md new file mode 100644 index 000000000000..567d6975765a --- /dev/null +++ b/sdk/corev2/azure-core-test/CHANGELOG.md @@ -0,0 +1,11 @@ +# Release History + +## 2.0.0-beta.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes diff --git a/sdk/corev2/azure-core-test/README.md b/sdk/corev2/azure-core-test/README.md new file mode 100644 index 000000000000..a72397ede65d --- /dev/null +++ b/sdk/corev2/azure-core-test/README.md @@ -0,0 +1,85 @@ +# Azure Core Test V2 shared library for Java + +This library contains core classes used to test Azure SDK client libraries. + +Newer SDK tests utilize the [Azure SDK Tools Test Proxy][test-proxy-readme] to record and playback HTTP interactions. +To migrate from existing [TestBase][TestBase.java] to use the test proxy, or to learn more about using the test proxy, +refer to the [test proxy migration guide][test-proxy-migration-guide]. + +## Table of contents + +- [Getting started](#getting-started) +- [Key concepts](#key-concepts) +- [Troubleshooting](#troubleshooting) +- [Next steps](#next-steps) +- [Contributing](#contributing) + +## Getting started + +To use this package, add the following to your _pom.xml_. + +[//]: # ({x-version-update-start;com.azure.v2:azure-core-test;current}) + +```xml + + + com.azure.v2 + azure-core-test + 2.0.0-beta.1 + +``` + +[//]: # ({x-version-update-end}) + +## Key concepts + +## Examples + +## Troubleshooting + +If you encounter any bugs with these SDKs, please file issues via +[Issues](https://github.com/Azure/azure-sdk-for-java/issues) or checkout +[StackOverflow for Azure Java SDK](https://stackoverflow.com/questions/tagged/azure-java-sdk). + +## Next steps + +Other useful packages are: + +* [azure-core](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/core/azure-core): Contains core classes and + functionality used by all client libraries. + +## Contributing + +For details on contributing to this repository, see the [contributing guide](https://github.com/Azure/azure-sdk-for-java/blob/main/CONTRIBUTING.md). + +This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit . + +When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repositories using our CLA. + +This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For more information see the [Code of Conduct FAQ][coc_faq] or contact with any additional questions or comments. + +[azure_portal]: https://portal.azure.com/ +[azure_cli_service_principal]: https://learn.microsoft.com/cli/azure/ad/sp?view=azure-cli-latest#az-ad-sp-create-for-rbac +[default_sanitizers]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/core/azure-core-test/src/main/java/com/azure/core/test/utils/TestProxyUtils.java#L259 +[git_setup]: https://git-scm.com/book/en/v2/Getting-Started-First-Time-Git-Setup +[git_token]: https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token +[powershell]: https://learn.microsoft.com/powershell/scripting/install/installing-powershell?view=powershell-latest +[recording-migration]: https://github.com/Azure/azure-sdk-for-java/blob/64de460d8080127a1e0c58fbfc7ab9e95f70a2c7/sdk/core/azure-core-test/RecordingMigrationGuide.md +[sanitize-secrets]: https://github.com/Azure/azure-sdk-tools/blob/main/tools/test-proxy/Azure.Sdk.Tools.TestProxy/README.md#session-and-test-level-transforms-sanitizers-and-matchers +[test-proxy-readme]: https://github.com/Azure/azure-sdk-tools/blob/main/tools/test-proxy/Azure.Sdk.Tools.TestProxy/README.md +[test-proxy-migration-guide]: https://github.com/Azure/azure-sdk-for-java/blob/64de460d8080127a1e0c58fbfc7ab9e95f70a2c7/sdk/core/azure-core-test/TestProxyMigrationGuide.md +[InterceptorManager.java]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/core/azure-core-test/src/main/java/com/azure/core/test/InterceptorManager.java +[TestProxyPlaybackClient.java]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/core/azure-core-test/src/main/java/com/azure/core/test/http/TestProxyPlaybackClient.java +[TestProxyRecordPolicy.java]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/core/azure-core-test/src/main/java/com/azure/core/test/policy/TestProxyRecordPolicy.java +[TestBase.java]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/core/azure-core-test/src/main/java/com/azure/core/test/TestProxyTestBase.java +[TestProxyTestBase.java]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/core/azure-core-test/src/main/java/com/azure/core/test/TestProxyTestBase.java +[TableClientTestBase]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/tables/azure-data-tables/src/test/java/com/azure/data/tables/TableClientTestBase.java#L61 +[tables-test-resources]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/tables/test-resources.json +[tables-test-resources-resources]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/tables/test-resources.json#L42 +[tables-test-resources-outputs]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/tables/test-resources.json#L115 +[test-resources]: https://github.com/Azure/azure-sdk-for-java/tree/main/eng/common/TestResources#readme +[test_proxy_sanitizer]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/core/azure-core-test/src/main/java/com/azure/core/test/models/TestProxySanitizer.java +[coc]: https://opensource.microsoft.com/codeofconduct/ +[coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ + + diff --git a/sdk/corev2/azure-core-test/RecordingMigrationGuide.md b/sdk/corev2/azure-core-test/RecordingMigrationGuide.md new file mode 100644 index 000000000000..19f642c6bf6d --- /dev/null +++ b/sdk/corev2/azure-core-test/RecordingMigrationGuide.md @@ -0,0 +1,125 @@ +# Guide for migrating test recordings out of the `azure-sdk-for-java` repository + +The Azure SDK test proxy enables tests to run recorded tests, even when these test recordings are outside the +`azure-sdk-for-java` repository. Migrating to this out-of-repo recording setup requires an initial recording move, +and after this the flow to update recordings will be slightly different. This guide describes the first stage of this +process and links to updated recording instructions. + +More technical documentation of the test proxy's out-of-repo recording support can be found [here][detailed_docs] in +the `azure-sdk-tools` repository. + +## Table of contents + +- [Guide for migrating test recordings out of the `azure-sdk-for-java` repository](#guide-for-migrating-test-recordings-out-of-the-azure-sdk-for-java-repository) + - [Table of contents](#table-of-contents) + - [Current recording setup](#current-recording-setup) + - [New recording setup](#new-recording-setup) + - [Initial recording migration](#initial-recording-migration) + - [Migration script prerequisites](#migration-script-prerequisites) + - [Execute the migration script](#execute-the-migration-script) + - [Run tests with out-of-repo recordings](#run-tests-with-out-of-repo-recordings) + +## Current recording setup + +Currently, test recordings live in the `azure-sdk-for-java` repository (or "language repo"), under a given package's +`src/test/resources/session-records/` directory. The test proxy loads recordings from this local directory and can be +done entirely offline. + +Storing recordings in the language repository significantly contributes to the repository's large size, which is its +main drawback. Recording file updates are also included in pull requests, which can make them more tedious to review +and difficult to load. + +## New recording setup + +With the test proxy, we can instead store recordings in a completely different git repository (called +[`azure-sdk-assets`][azure_sdk_assets], or the "assets repo"). The test proxy creates a sparse clone of only the +recordings for the package being tested, stores them locally in a git-excluded language repo directory, and runs +playback tests in the same way as before. + +The out-of-repo recording system requires a connection to fetch recordings but frees up considerable space in the +language repo. Additionally, pull requests that update recordings now update a single pointer to new recordings instead +of full recording files. + +The pointer to test recordings is stored in a new `assets.json` file that will be created for each package during the +initial migration. + +## Initial recording migration + +A [PowerShell script][transition_script] in the `azure-sdk-tools` repository will assist in pushing recordings to the +assets repo, removing recordings from the language repo, and creating an `assets.json` file for the package you're +migrating. + +This script -- [`generate-assets-json.ps1`][generate_assets_json] -- should be run once per package, and can be used +either directly from an `azure-sdk-tools` repo clone or with a local download of the script. To download the script to +your current working directory, use the following PowerShell command: + +```PowerShell +Invoke-WebRequest -OutFile "generate-assets-json.ps1" https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/eng/common/testproxy/onboarding/generate-assets-json.ps1 +``` + +### Migration script prerequisites + +- The targeted library is already migrated to use the test proxy. +- Git version > 2.25.0 is to on the machine and in the path. Git is used by the script and test proxy. +- [PowerShell Core][powershell] >= 7.0 is installed. +- Global [git config settings][git_setup] are configured for `user.name` and `user.email`. + - These settings can be overridden with environment variables `GIT_COMMIT_OWNER` and `GIT_COMMIT_EMAIL`, respectively. +- Membership in the `azure-sdk-write` GitHub group. + +### Execute the migration script + +In a PowerShell window: + +1. Set your working directory to the root of the package you're migrating (`sdk/{service}/{package}`) -- for example: + +```PowerShell +cd C:\azure-sdk-for-java\sdk\textanalytics\azure-ai-textanalytics +``` + +2. Run the following command: + +```PowerShell +/generate-assets-json.ps1 -InitialPush +``` + +If you run `git status` from within the language repo, you should see: + +- Deleted files for each test recording in the package +- A new `assets.json` file under the root of your package + +The `assets.json` file will have the form: + +```json +{ + "AssetsRepo": "Azure/azure-sdk-assets", + "AssetsRepoPrefixPath": "java", + "TagPrefix": "java/{service}/{package}", + "Tag": "java/{service}/{package}_<10-character-commit-SHA>" +} +``` + +The `Tag` field matches the name of a tag that's been created in the assets repo and contains the uploaded recordings. +Before creating a PR to cement the recording move, it's a good idea to check out that tag in the assets repo and make +sure the recordings that you expect to see are there. + +## Run tests with out-of-repo recordings + +After moving recordings to the asset repo, live and playback testing will be the same as it was in the past. The test +proxy automatically pulls down the correct set of recordings based on the `Tag` in your package's `assets.json` file. + +The process for updating test recordings is slightly different from it was with in-repo recordings, and differs in two +primary ways: + +1. When tests are run in recording mode, recording changes won't be visible in the language repo and will instead be + tracked in a separate git ignored `.assets` directory. +2. When updated recordings are pushed to the assets repo, the `Tag` field in your package's `assets.json` file will be + updated to point to these new recordings. This `assets.json` change is what you'll include in a pull request to update + recordings in the language repo. + +[azure_sdk_assets]: https://github.com/Azure/azure-sdk-assets +[detailed_docs]: https://github.com/Azure/azure-sdk-tools/blob/main/tools/test-proxy/documentation/asset-sync/README.md +[generate_assets_json]: https://github.com/Azure/azure-sdk-tools/blob/main/eng/common/testproxy/onboarding/generate-assets-json.ps1 +[git_setup]: https://git-scm.com/book/en/v2/Getting-Started-First-Time-Git-Setup +[git_token]: https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token +[powershell]: https://learn.microsoft.com/powershell/scripting/install/installing-powershell?view=powershell-latest +[transition_script]: https://github.com/Azure/azure-sdk-for-java/blob/main/eng/common/testproxy/onboarding/README.md diff --git a/sdk/corev2/azure-core-test/assets.json b/sdk/corev2/azure-core-test/assets.json new file mode 100644 index 000000000000..5a091f334ac7 --- /dev/null +++ b/sdk/corev2/azure-core-test/assets.json @@ -0,0 +1,6 @@ +{ + "AssetsRepo": "Azure/azure-sdk-assets", + "AssetsRepoPrefixPath": "java", + "TagPrefix": "java/corev2/azure-core-test", + "Tag": "java/corev2/azure-core-test_161d2b17df" +} diff --git a/sdk/corev2/azure-core-test/checkstyle-suppressions.xml b/sdk/corev2/azure-core-test/checkstyle-suppressions.xml new file mode 100644 index 000000000000..f5ccb97aff06 --- /dev/null +++ b/sdk/corev2/azure-core-test/checkstyle-suppressions.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sdk/corev2/azure-core-test/pom.xml b/sdk/corev2/azure-core-test/pom.xml new file mode 100644 index 000000000000..02604cdf22a1 --- /dev/null +++ b/sdk/corev2/azure-core-test/pom.xml @@ -0,0 +1,143 @@ + + + 4.0.0 + + com.azure.v2 + azure-client-sdk-parent + 2.0.0-beta.1 + ../../parents/azure-client-sdk-parent-v2/pom.xml + + + com.azure.v2 + azure-core-test + jar + 2.0.0-beta.1 + + Microsoft Azure Java Core Test V2 Library + This package contains core test types for Azure Java V2 clients. + 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:https://github.com/Azure/azure-sdk-for-java.git + scm:git:https://github.com/Azure/azure-sdk-for-java.git + + + + + --add-exports org.junit.platform.commons/org.junit.platform.commons.util=ALL-UNNAMED + --add-exports org.junit.platform.commons/org.junit.platform.commons.logging=ALL-UNNAMED + + --add-reads com.azure.v2.core.test=ALL-UNNAMED + --add-opens com.azure.v2.core.test/com.azure.v2.core.test.http=org.junit.platform.commons + --add-opens com.azure.v2.core.test/com.azure.v2.core.test.models=ALL-UNNAMED + --add-opens com.azure.v2.core.test/com.azure.v2.core.test.policy=org.junit.platform.commons + --add-opens com.azure.v2.core.test/com.azure.v2.core.test.implementation=org.junit.platform.commons + + + + true + + + + + com.azure.v2.core.implementation*,com.azure.core.util,com.azure.core.util*, + com.azure.core.models,com.azure.core.http,com.azure.core.http.policy,com.azure.core.http.rest,com.azure.core.exception,com.azure.core.cryptography, + com.azure.core.credential,com.azure.core.client.traits,com.azure.core.annotation + + 4g + + + true + + checkstyle-suppressions.xml + + false + spotbugs-exclude.xml + false + java.lang.management.ThreadMXBean,java.lang.management.ThreadInfo,java.lang.management.ManagementFactory + + + + + io.clientcore + core + 1.0.0-beta.7 + + + com.azure.v2 + azure-core + 2.0.0-beta.1 + + + + org.junit.jupiter + junit-jupiter-api + 5.11.2 + + + org.junit.jupiter + junit-jupiter-engine + 5.11.2 + + + org.junit.jupiter + junit-jupiter-params + 5.11.2 + + + + + + + org.apache.ant + ant + 1.10.14 + + + + org.eclipse.jetty + jetty-server + 9.4.56.v20240826 + test + + + org.eclipse.jetty + jetty-servlet + 9.4.56.v20240826 + test + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.5.0 + + + + + + org.junit.jupiter:junit-jupiter-api:[5.11.2] + org.junit.jupiter:junit-jupiter-engine:[5.11.2] + org.junit.jupiter:junit-jupiter-params:[5.11.2] + org.apache.ant:ant:[1.10.14] + + + + + + + + diff --git a/sdk/corev2/azure-core-test/spotbugs-exclude.xml b/sdk/corev2/azure-core-test/spotbugs-exclude.xml new file mode 100644 index 000000000000..4ce1eb88f0cf --- /dev/null +++ b/sdk/corev2/azure-core-test/spotbugs-exclude.xml @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/AzureTestWatcher.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/AzureTestWatcher.java new file mode 100644 index 000000000000..e8fc98a9e7a9 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/AzureTestWatcher.java @@ -0,0 +1,67 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test; + +import org.junit.jupiter.api.extension.AfterTestExecutionCallback; +import org.junit.jupiter.api.extension.BeforeTestExecutionCallback; +import org.junit.jupiter.api.extension.ExtensionContext; + +import static com.azure.v2.core.test.TestBase.shouldLogExecutionStatus; +import static com.azure.v2.core.test.implementation.TestingHelpers.getTestName; + +/** + * JUnit 5 extension class which reports on testing running and simple metrics about the test such as run time. + */ +public class AzureTestWatcher implements BeforeTestExecutionCallback, AfterTestExecutionCallback { + /** + * Creates an instance of {@link AzureTestWatcher}. + */ + public AzureTestWatcher() { + } + + @Override + public void beforeTestExecution(ExtensionContext context) { + // If the test class is an instance of TestBase or is a subtype of TestBase, then we don't need to track + // anything here as TestBase handles this logic in it's Before and After test methods. + Class clazz = context.getTestClass().orElse(null); + if (clazz != null && TestBase.class.isAssignableFrom(clazz)) { + return; + } + + // Check if test debugging is enabled to determine whether logging should happen. + if (!shouldLogExecutionStatus()) { + return; + } + + String testName = getTestName(context.getTestMethod(), context.getDisplayName(), context.getTestClass()); + System.out.println("Starting test " + testName + "."); + + getStore(context).put(context.getRequiredTestMethod(), System.currentTimeMillis()); + } + + @Override + public void afterTestExecution(ExtensionContext context) { + // If the test class is an instance of TestBase or is a subtype of TestBase, then we don't need to track + // anything here as TestBase handles this logic in it's Before and After test methods. + Class clazz = context.getTestClass().orElse(null); + if (clazz != null && TestBase.class.isAssignableFrom(clazz)) { + return; + } + + // Check if test debugging is enabled to determine whether logging should happen. + if (!shouldLogExecutionStatus()) { + return; + } + + long startMillis = getStore(context).remove(context.getRequiredTestMethod(), long.class); + long duration = System.currentTimeMillis() - startMillis; + + String testName = getTestName(context.getTestMethod(), context.getDisplayName(), context.getTestClass()); + System.out.println("Finished test " + testName + " in " + duration + " ms."); + } + + private static ExtensionContext.Store getStore(ExtensionContext context) { + return context.getStore(ExtensionContext.Namespace.create(AzureTestWatcher.class, context)); + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/InterceptorManager.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/InterceptorManager.java new file mode 100644 index 000000000000..f16ef6c531df --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/InterceptorManager.java @@ -0,0 +1,352 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.v2.core.test; + +import com.azure.v2.core.test.http.TestProxyPlaybackClient; +import com.azure.v2.core.test.models.TestProxyRecordingOptions; +import com.azure.v2.core.test.models.TestProxyRequestMatcher; +import com.azure.v2.core.test.models.TestProxySanitizer; +import com.azure.v2.core.test.policy.TestProxyRecordPolicy; +import com.azure.v2.core.test.utils.TestUtils; +import io.clientcore.core.http.client.HttpClient; +import io.clientcore.core.http.pipeline.HttpPipelinePolicy; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.utils.CoreUtils; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.Objects; +import java.util.Queue; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * A class that keeps track of network calls by either reading the data from an existing test session record or + * recording the network calls in memory. Test session records are saved or read from: + * "session-records/{@code testName}.json" + * + *

          + *
        • If the {@code testMode} is {@link TestMode#PLAYBACK}, the manager tries to find an existing test session + * record to read network calls from.
        • + *
        • If the {@code testMode} is {@link TestMode#RECORD}, the manager creates a new test session record and saves + * all the network calls to it.
        • + *
        • If the {@code testMode} is {@link TestMode#LIVE}, the manager won't attempt to read or create a test session + * record.
        • + *
        + * + * When the {@link InterceptorManager} is disposed, if the {@code testMode} is {@link TestMode#RECORD}, the network + * calls that were recorded are persisted to: "session-records/{@code testName}.json" + */ +public class InterceptorManager implements AutoCloseable { + private static final ClientLogger LOGGER = new ClientLogger(InterceptorManager.class); + private final String testName; + private final String playbackRecordName; + private final TestMode testMode; + private final boolean allowedToReadRecordedValues; + private final boolean allowedToRecordValues; + + private final boolean skipRecordingRequestBody; + private TestProxyRecordPolicy testProxyRecordPolicy; + private TestProxyPlaybackClient testProxyPlaybackClient; + private final Queue proxyVariableQueue = new LinkedList<>(); + private HttpClient httpClient; + private final Path testClassPath; + private String xRecordingFileLocation; + + /** + * Creates a new InterceptorManager that either replays test-session records or saves them. + * + *
          + *
        • If {@code testMode} is {@link TestMode#PLAYBACK}, the manager tries to find an existing test session + * record to read network calls from.
        • + *
        • If {@code testMode} is {@link TestMode#RECORD}, the manager creates a new test session record and saves + * all the network calls to it.
        • + *
        • If {@code testMode} is {@link TestMode#LIVE}, the manager won't attempt to read or create a test session + * record.
        • + *
        + * + * The test session records are persisted in the path: "session-records/{@code testName}.json" + * + * @param testContextManager Contextual information about the test being ran, such as test name, {@link TestMode}, + * and others. + * @throws NullPointerException If {@code testName} is {@code null}. + */ + public InterceptorManager(TestContextManager testContextManager) { + this(testContextManager.getTestName(), testContextManager.getTestPlaybackRecordingName(), + testContextManager.getTestMode(), testContextManager.doNotRecordTest(), + testContextManager.skipRecordingRequestBody(), testContextManager.getTestClassPath()); + } + + private InterceptorManager(String testName, String playbackRecordName, TestMode testMode, boolean doNotRecord, + boolean skipRecordingRequestBody, Path testClassPath) { + Objects.requireNonNull(testName, "'testName' cannot be null."); + + this.testName = testName; + this.playbackRecordName = CoreUtils.isNullOrEmpty(playbackRecordName) ? testName : playbackRecordName; + this.testMode = testMode; + this.skipRecordingRequestBody = skipRecordingRequestBody; + this.testClassPath = testClassPath; + + this.allowedToReadRecordedValues = (testMode == TestMode.PLAYBACK && !doNotRecord); + this.allowedToRecordValues = (testMode == TestMode.RECORD && !doNotRecord); + } + + /** + * Gets whether this InterceptorManager is in playback mode. + * + * @return true if the InterceptorManager is in playback mode and false otherwise. + */ + public boolean isPlaybackMode() { + return testMode == TestMode.PLAYBACK; + } + + /** + * Gets whether this InterceptorManager is in live mode. + * + * @return true if the InterceptorManager is in live mode and false otherwise. + */ + public boolean isLiveMode() { + return testMode == TestMode.LIVE; + } + + /** + * Gets whether this InterceptorManager is in record mode. + * + * @return true if the InterceptorManager is in record mode and false otherwise. + */ + public boolean isRecordMode() { + return testMode == TestMode.RECORD; + } + + /** + * A {@link Supplier} for retrieving a variable from a test proxy recording. + * + * @return The supplier for retrieving a variable. + */ + public Supplier getProxyVariableSupplier() { + return () -> { + Objects.requireNonNull(this.testProxyPlaybackClient, "Playback must be started to retrieve values"); + if (!CoreUtils.isNullOrEmpty(proxyVariableQueue)) { + return proxyVariableQueue.remove(); + } else { + throw LOGGER.logThrowableAsError(new RuntimeException("'proxyVariableQueue' cannot be null or empty.")); + } + }; + } + + /** + * Get a {@link Consumer} for adding variables used in test proxy tests. + * + * @return The consumer for adding a variable. + */ + public Consumer getProxyVariableConsumer() { + return proxyVariableQueue::add; + } + + /** + * Gets a new HTTP pipeline policy that records network calls and its data is managed by + * {@link InterceptorManager}. + * + * @return HttpPipelinePolicy to record network calls. + * @throws IllegalStateException A recording policy was requested when the test proxy is enabled and test mode is not RECORD. + */ + public HttpPipelinePolicy getRecordPolicy() { + return getProxyRecordingPolicy(); + } + + /** + * Gets the HTTP client that is used for this test. + * + * @return The {@link HttpClient} implementation used for this test. + */ + public HttpClient getHttpClient() { + return httpClient; + } + + /** + * Gets a new HTTP client that plays back test session records managed by {@link InterceptorManager}. + * + * @return An HTTP client that plays back network calls from its recorded data. + * @throws IllegalStateException A playback client was requested when the test proxy is enabled and test mode is LIVE. + */ + public HttpClient getPlaybackClient() { + if (!isPlaybackMode()) { + throw new IllegalStateException("A playback client can only be requested in PLAYBACK mode."); + } + if (testProxyPlaybackClient == null) { + testProxyPlaybackClient = new TestProxyPlaybackClient(httpClient, skipRecordingRequestBody); + proxyVariableQueue.addAll(testProxyPlaybackClient.startPlayback(getTestProxyRecordFile(), testClassPath)); + xRecordingFileLocation = testProxyPlaybackClient.getRecordingFileLocation(); + } + return testProxyPlaybackClient; + } + + /** + * Disposes of resources used by this InterceptorManager. + *

        + * If {@code testMode} is {@link TestMode#RECORD}, all the network calls are persisted to: + * "session-records/{@code testName}.json" + * + * @throws IOException If an I/O error occurs. + */ + @Override + public void close() throws IOException { + if (allowedToRecordValues) { + testProxyRecordPolicy.stopRecording(proxyVariableQueue); + } else if (isPlaybackMode() && allowedToReadRecordedValues) { + testProxyPlaybackClient.stopPlayback(); + } + } + + private HttpPipelinePolicy getProxyRecordingPolicy() { + if (testProxyRecordPolicy == null) { + if (!isRecordMode()) { + throw new IllegalStateException("A recording policy can only be requested in RECORD mode."); + } + testProxyRecordPolicy = new TestProxyRecordPolicy(httpClient, skipRecordingRequestBody); + testProxyRecordPolicy.startRecording(getTestProxyRecordFile(), testClassPath); + } + return testProxyRecordPolicy; + } + + /** + * Computes the relative path of the record file to the repo root. + * + * @return A {@link File} with the partial path to where the record file lives. + */ + private File getTestProxyRecordFile() { + Path repoRoot = TestUtils.getRepoRootResolveUntil(testClassPath, "eng"); + Path targetFolderRoot = TestUtils.getRepoRootResolveUntil(testClassPath, "target"); + Path filePath = Paths.get(targetFolderRoot.toString(), "src/test/resources/session-records", + playbackRecordName + ".json"); + return repoRoot.relativize(filePath).toFile(); + } + + /** + * Add sanitizer rule for sanitization during record or playback. + * + * @param testProxySanitizers the list of replacement regex and rules. + * @throws RuntimeException Neither playback nor record has started. + * @throws IOException If an error occurs while sending the request. + */ + public void addSanitizers(List testProxySanitizers) throws IOException { + if (CoreUtils.isNullOrEmpty(testProxySanitizers)) { + return; + } + if (testProxyPlaybackClient != null) { + testProxyPlaybackClient.addProxySanitization(testProxySanitizers); + } else if (testProxyRecordPolicy != null) { + testProxyRecordPolicy.addProxySanitization(testProxySanitizers); + } else { + throw new RuntimeException("Playback or record must have been started before adding sanitizers."); + } + } + + /** + * Disable common sanitizer rule for sanitization during record or playback. + * + * @param testProxySanitizersId the list of sanitizer rule ID to disable. + * @throws RuntimeException Neither playback nor record has started. + * @throws IOException If an error occurs while sending the request. + */ + public void removeSanitizers(String... testProxySanitizersId) throws IOException { + if (CoreUtils.isNullOrEmpty(testProxySanitizersId)) { + return; + } + if (testProxyPlaybackClient != null) { + testProxyPlaybackClient.removeProxySanitization(Arrays.asList(testProxySanitizersId)); + } else if (testProxyRecordPolicy != null) { + testProxyRecordPolicy.removeProxySanitization(Arrays.asList(testProxySanitizersId)); + } else { + throw new RuntimeException("Playback or record must have been started before removing sanitizers."); + } + } + + /** + * Add sanitizer rule for sanitization during record or playback. + * + * @param testProxySanitizers the list of replacement regex and rules. + * @throws IOException If an error occurs while sending the request. + */ + public void addSanitizers(TestProxySanitizer... testProxySanitizers) throws IOException { + if (testProxySanitizers != null) { + addSanitizers(Arrays.asList(testProxySanitizers)); + } + } + + /** + * Add matcher rules to match recorded data in playback. + * Matchers are only applied for playback session and so this will be a noop when invoked in RECORD/LIVE mode. + * + * @param testProxyMatchers the list of matcher rules when playing back recorded data. + * @throws RuntimeException Playback has not started. + * @throws IOException If an error occurs while sending the request. + */ + public void addMatchers(List testProxyMatchers) throws IOException { + if (CoreUtils.isNullOrEmpty(testProxyMatchers)) { + return; + } + + if (testMode != TestMode.PLAYBACK) { + return; + } + if (testProxyPlaybackClient != null) { + testProxyPlaybackClient.addMatcherRequests(testProxyMatchers); + } else { + throw new RuntimeException("Playback must have been started before adding matchers."); + } + } + + /** + * Add matcher rules to match recorded data in playback. + * Matchers are only applied for playback session and so this will be a noop when invoked in RECORD/LIVE mode. + * + * @param testProxyRequestMatchers the list of matcher rules when playing back recorded data. + * @throws IOException If an error occurs while sending the request. + */ + public void addMatchers(TestProxyRequestMatcher... testProxyRequestMatchers) throws IOException { + if (testProxyRequestMatchers != null) { + addMatchers(Arrays.asList(testProxyRequestMatchers)); + } + } + + /** + * Get the recording file location in assets repo. + * + * @return the assets repo location of the recording file. + */ + public String getRecordingFileLocation() { + return xRecordingFileLocation; + } + + /** + * Sets the httpClient to be used for this test. + * + * @param httpClient The {@link HttpClient} implementation to use. + */ + void setHttpClient(HttpClient httpClient) { + this.httpClient = httpClient; + } + + /** + * Sets the recording options for the proxy. + * + * @param testProxyRecordingOptions The {@link TestProxyRecordingOptions} to use. + * @throws RuntimeException if test mode is not record. + */ + public void setProxyRecordingOptions(TestProxyRecordingOptions testProxyRecordingOptions) { + if (testMode != TestMode.RECORD) { + return; + } + if (testProxyRecordPolicy != null) { + testProxyRecordPolicy.setRecordingOptions(testProxyRecordingOptions); + } else { + throw new RuntimeException("Recording must have been started before setting recording options."); + } + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/TestBase.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/TestBase.java new file mode 100644 index 000000000000..9cd61fcd0577 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/TestBase.java @@ -0,0 +1,376 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.v2.core.test; + +import com.azure.v2.core.test.implementation.TestingHelpers; +import com.azure.v2.core.test.junitextensions.TestContextManagerParameterResolver; +import com.azure.v2.core.test.utils.HttpUrlConnectionHttpClient; +import com.azure.v2.core.test.utils.TestProxyManager; +import com.azure.v2.core.test.utils.TestResourceNamer; +import io.clientcore.core.http.client.HttpClient; +import io.clientcore.core.http.client.HttpClientProvider; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.utils.CoreUtils; +import io.clientcore.core.utils.configuration.Configuration; +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.extension.ExtendWith; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Path; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.ServiceConfigurationError; +import java.util.ServiceLoader; +import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +/** + * Base class for running live and playback tests using {@link InterceptorManager}. + */ +@ExtendWith(TestContextManagerParameterResolver.class) +public abstract class TestBase { + /** + * 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} + */ + @BeforeAll + public static void setupTestProxy() { + testMode = initializeTestMode(); + if (testMode == TestMode.PLAYBACK || testMode == TestMode.RECORD) { + TestProxyManager.startProxy(); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(TestBase.class); + + private static final String AZURE_TEST_DEBUG = "AZURE_TEST_DEBUG"; + + // Environment variable name used to determine the TestMode. + private static final String AZURE_TEST_HTTP_CLIENTS = "AZURE_TEST_HTTP_CLIENTS"; + + /** + * Specifies to use all HttpClient implementations in testing. + */ + public static final String AZURE_TEST_HTTP_CLIENTS_VALUE_ALL = "ALL"; + + private static final Duration PLAYBACK_POLL_INTERVAL = Duration.ofMillis(1); + private static final String CONFIGURED_HTTP_CLIENTS_TO_TEST + = Configuration.getGlobalConfiguration().get(AZURE_TEST_HTTP_CLIENTS); + private static final boolean DEFAULT_TO_NETTY = CoreUtils.isNullOrEmpty(CONFIGURED_HTTP_CLIENTS_TO_TEST); + private static final List CONFIGURED_HTTP_CLIENTS; + + private static final AtomicReference TEST_PROXY_HTTP_CLIENT = new AtomicReference<>(); + + static { + CONFIGURED_HTTP_CLIENTS = new ArrayList<>(); + + if (DEFAULT_TO_NETTY) { + CONFIGURED_HTTP_CLIENTS.add("netty"); + } else { + for (String configuredHttpClient : CONFIGURED_HTTP_CLIENTS_TO_TEST.split(",")) { + if (CoreUtils.isNullOrEmpty(configuredHttpClient)) { + continue; + } + + CONFIGURED_HTTP_CLIENTS.add(configuredHttpClient.trim().toLowerCase(Locale.ROOT)); + } + } + } + + /** + * The {@link TestMode} used for this execution. + */ + static TestMode testMode; + + private final ClientLogger logger = new ClientLogger(TestBase.class); + + /** + * {@link InterceptorManager} used for this test run. + */ + protected InterceptorManager interceptorManager; + + /** + * {@link TestResourceNamer} used for this test run. + */ + protected TestResourceNamer testResourceNamer; + + /** + * {@link TestContextManager} used for this test run. + */ + protected TestContextManager testContextManager; + + private long testStartTimeMillis; + + /** + * Creates a new instance of {@link TestBase}. + */ + public TestBase() { + } + + /** + * 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} + */ + @BeforeAll + public static void setupClass() { + testMode = initializeTestMode(); + } + + /** + * 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 testContextManager The {@link TestContextManager} managing information about this test. + */ + @BeforeEach + 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'"); + + ThreadDumper.addRunningTest(testContextManager.getTrackerTestName()); + logger.atInfo() + .addKeyValue("testMode", testContextManager.getTestMode()) + .addKeyValue("testName", testContextManager.getTrackerTestName()) + .log(); + + if (shouldLogExecutionStatus()) { + System.out.println("Starting test " + testContextManager.getTrackerTestName() + "."); + testStartTimeMillis = System.currentTimeMillis(); + } + + try { + interceptorManager = new InterceptorManager(testContextManager); + } catch (UncheckedIOException e) { + fail(logger.atError() + .addKeyValue("testName", testContextManager.getTestName()) + .log("Could not create interceptor.", e)); + } + + interceptorManager.setHttpClient(getTestProxyHttpClient()); + // The supplier/consumer are used to retrieve/store variables over the wire. + testResourceNamer = new TestResourceNamer(testContextManager, interceptorManager.getProxyVariableConsumer(), + interceptorManager.getProxyVariableSupplier()); + 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 (testContextManager.getTestMode() == TestMode.RECORD && !testContextManager.doNotRecordTest()) { + // Similarly we create the record policy early so matchers/sanitizers can be added. + interceptorManager.getRecordPolicy(); + } + beforeTest(); + } + + /** + * Disposes of {@link InterceptorManager} and its inheriting class' resources. + * + * @throws IOException If an error occurs while shutting down test resources. + */ + @AfterEach + public void teardownTest() throws IOException { + if (shouldLogExecutionStatus()) { + if (testStartTimeMillis > 0) { + long duration = System.currentTimeMillis() - testStartTimeMillis; + System.out + .println("Finished test " + testContextManager.getTrackerTestName() + " in " + duration + " ms."); + } else { + System.out.println("Finished test " + testContextManager.getTrackerTestName() + ", duration unknown."); + } + } + + if (testContextManager != null) { + ThreadDumper.removeRunningTest(testContextManager.getTrackerTestName()); + + if (testContextManager.didTestRun()) { + afterTest(); + interceptorManager.close(); + } + } + } + + /** + * Gets the TestMode that has been initialized. + * + * @return The TestMode that has been initialized. + */ + public TestMode getTestMode() { + return testMode; + } + + /** + * Gets the name of the current test being run. + * + * @return The name of the current test. + * @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(TestContextManager)}. + */ + @Deprecated + protected String getTestName() { + if (testContextManager != null) { + return testContextManager.getTestName(); + } + return null; + } + + /** + * Performs any set-up before each test case. Any initialization that occurs in TestBase occurs first before this. + * Can be overridden in an inheriting class to add additional functionality during test set-up. + */ + protected void beforeTest() { + } + + /** + * Dispose of any resources and clean-up after a test case runs. Can be overridden in an inheriting class to add + * additional functionality during test teardown. + */ + protected void afterTest() { + } + + /** + * Returns a list of {@link HttpClient HttpClients} that should be tested. + * + * @return A list of {@link HttpClient HttpClients} to be tested. + */ + public static Stream getHttpClients() { + List httpClientsToTest = new ArrayList<>(); + Iterator iterator = ServiceLoader.load(HttpClientProvider.class).iterator(); + while (iterator.hasNext()) { + try { + HttpClientProvider httpClientProvider = iterator.next(); + if (includeHttpClientOrHttpClientProvider( + httpClientProvider.getClass().getSimpleName().toLowerCase(Locale.ROOT))) { + httpClientsToTest.add(httpClientProvider.getSharedInstance()); + } + } catch (ServiceConfigurationError | LinkageError error) { + LOGGER.atWarning().log("Skipping HttpClientProvider due to LinkageError.", error); + } + } + + return httpClientsToTest.stream(); + } + + /** + * Returns whether the given http clients match the rules of test framework. + * + *

          + *
        • Using Netty http client as default if no environment variable is set.
        • + *
        • If it's set to ALL, all HttpClients in the classpath will be tested.
        • + *
        • Otherwise, the name of the HttpClient class should match env variable.
        • + *
        + * + * Environment values currently supported are: "ALL", "netty", "okhttp" which is case insensitive. + * Use comma to separate http clients want to test. + * e.g. {@code set AZURE_TEST_HTTP_CLIENTS = NettyAsyncHttpClient, OkHttpAsyncHttpClient} + * + * @param client Http client needs to check + * @return Boolean indicates whether filters out the client or not. + */ + public static boolean shouldClientBeTested(HttpClient client) { + return includeHttpClientOrHttpClientProvider(client.getClass().getSimpleName().toLowerCase(Locale.ROOT)); + } + + private static boolean includeHttpClientOrHttpClientProvider(String name) { + if (AZURE_TEST_HTTP_CLIENTS_VALUE_ALL.equalsIgnoreCase(CONFIGURED_HTTP_CLIENTS_TO_TEST)) { + return true; + } + + return CONFIGURED_HTTP_CLIENTS.stream().anyMatch(name::contains); + } + + /** + * Initializes the {@link TestMode} from the environment configuration {@code AZURE_TEST_MODE}. + *

        + * If {@code AZURE_TEST_MODE} isn't configured or is invalid then {@link TestMode#PLAYBACK} is returned. + * + * @return The {@link TestMode} being used for testing. + */ + static TestMode initializeTestMode() { + return TestingHelpers.getTestMode(); + } + + /** + * Returns the path of the class to which the test belongs. + * + * @return The file path of the test class. + */ + protected Path getTestClassPath() { + return testContextManager.getTestClassPath(); + } + + /** + * Sleeps the test for the given amount of milliseconds if {@link TestMode} isn't {@link TestMode#PLAYBACK}. + * + * @param millis Number of milliseconds to sleep the test. + * @throws IllegalStateException If the sleep is interrupted. + */ + protected void sleepIfRunningAgainstService(long millis) { + if (testMode == TestMode.PLAYBACK) { + return; + } + + try { + Thread.sleep(millis); + } catch (InterruptedException ex) { + throw logger.logThrowableAsWarning(new IllegalStateException(ex)); + } + } + + // /** + // * Sets the polling interval for the passed {@link SyncPoller}. + // *

        + // * This configures the {@link SyncPoller} to use a poll interval of one millisecond if the test mode is playback. In + // * live or record test mode the polling interval is left as-is. + // * + // * @param syncPoller The {@link SyncPoller}. + // * @param The type of poll response value. + // * @param The type of the final result of long-running operation. + // * @return The updated {@link SyncPoller}. + // */ + // protected SyncPoller setPlaybackSyncPollerPollInterval(SyncPoller syncPoller) { + // return (testMode == TestMode.PLAYBACK) ? syncPoller.setPollInterval(PLAYBACK_POLL_INTERVAL) : syncPoller; + // } + + /** + * Convenience method which either returned the passed {@link HttpClient} or returns a {@link InterceptorManager#getPlaybackClient()} + * depending on whether the test mode is playback. + *

        + * When the test mode is playback the {@link InterceptorManager#getPlaybackClient()} corresponding to the test will be returned, otherwise + * the passed {@link HttpClient} will be returned. + * + * @param httpClient The initial {@link HttpClient} that will be used. + * @return Either the passed {@link HttpClient} or {@link InterceptorManager#getPlaybackClient()} based on the test mode. + */ + protected HttpClient getHttpClientOrUsePlayback(HttpClient httpClient) { + return (testMode == TestMode.PLAYBACK) ? interceptorManager.getPlaybackClient() : httpClient; + } + + private static HttpClient getTestProxyHttpClient() { + return TEST_PROXY_HTTP_CLIENT.updateAndGet(httpClient -> httpClient == null + ? getHttpClients().findFirst().orElse(new HttpUrlConnectionHttpClient()) + : httpClient); + } + + static boolean shouldLogExecutionStatus() { + String testMode = Configuration.getGlobalConfiguration().get(AZURE_TEST_DEBUG); + if (testMode == null) { + return false; + } + + return Boolean.parseBoolean(testMode); + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/TestContextManager.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/TestContextManager.java new file mode 100644 index 000000000000..fd15b69edeee --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/TestContextManager.java @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.v2.core.test; + +import com.azure.v2.core.test.annotation.DoNotRecord; +import com.azure.v2.core.test.annotation.RecordWithoutRequestBody; + +import java.lang.reflect.Method; +import java.nio.file.Path; + +/** + * This class handles managing context about a test, such as custom testing annotations and verifying whether the test + * is capable of running. + */ +public class TestContextManager { + private final String testName; + private final String className; + private final TestMode testMode; + private final boolean doNotRecord; + private final boolean testRan; + + private Integer testIteration; + private final boolean skipRecordingRequestBody; + private final Path testClassPath; + private final String trackerTestName; + + /** + * 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 recordWithoutRequestBodyClassAnnotation flag indicating if {@code RecordWithoutRequestBody} annotation + * present on test class. + * @param testClassPath the test class path + */ + public TestContextManager(Method testMethod, TestMode testMode, boolean recordWithoutRequestBodyClassAnnotation, + Path testClassPath) { + this(testMethod, testMode, 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 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 recordWithoutRequestBodyClassAnnotation, + Path testClassPath, String trackerTestName) { + this.testName = testMethod.getName(); + this.className = testMethod.getDeclaringClass().getSimpleName(); + this.testMode = testMode; + + RecordWithoutRequestBody recordWithoutRequestBody = testMethod.getAnnotation(RecordWithoutRequestBody.class); + this.skipRecordingRequestBody = recordWithoutRequestBody != null || recordWithoutRequestBodyClassAnnotation; + + DoNotRecord doNotRecordAnnotation = testMethod.getAnnotation(DoNotRecord.class); + this.doNotRecord = doNotRecordAnnotation != null; + + this.testClassPath = testClassPath; + this.testRan = true; + this.trackerTestName = trackerTestName; + } + + /** + * Returns the name of the test being ran. + * + * @return The test name. + */ + public String getTestName() { + return testName; + } + + /** + * Returns the path of the class to which the test belongs. + * + * @return The file path of the test class. + */ + Path getTestClassPath() { + return testClassPath; + } + + /** + * Returns the name of the playback record for the test being ran. + * + * @return The playback record name. + */ + public String getTestPlaybackRecordingName() { + StringBuilder builder = new StringBuilder(className).append(".").append(testName); + + if (testIteration != null) { + builder.append("[").append(testIteration).append("]"); + } + + return builder.toString(); + } + + /** + * Returns the mode being used to run tests. + * + * @return The {@link TestMode} being used to run tests. + */ + public TestMode getTestMode() { + return testMode; + } + + /** + * Returns whether the test should have its network calls recorded during a {@link TestMode#RECORD record} test + * run. + * + * @return Flag indicating whether to record test network calls. + */ + public boolean doNotRecordTest() { + return doNotRecord; + } + + /** + * Returns whether the test is recording request body when run {@link TestMode#RECORD record} mode. + * + * @return Flag indicating whether test should record request bodies. + */ + public boolean skipRecordingRequestBody() { + return skipRecordingRequestBody; + } + + /** + * Returns whether the current test was ran. + * + * @return Flag indicating whether the current test was ran. + */ + public boolean didTestRun() { + return testRan; + } + + /** + * Sets the test iteration for parameterized tests. + * + * @param testIteration Test iteration. + */ + 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/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/TestMode.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/TestMode.java new file mode 100644 index 000000000000..2f9f3e62482f --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/TestMode.java @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.v2.core.test; + +/** + * The possible testing modes. + */ +public enum TestMode { + /** + * Record data from a live test. + */ + RECORD, + /** + * Run a live test without recording. + */ + LIVE, + /** + * Playback data from an existing test session. + */ + PLAYBACK, +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/ThreadDumper.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/ThreadDumper.java new file mode 100644 index 000000000000..ec3a9b9e5066 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/ThreadDumper.java @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.v2.core.test; + +import com.azure.v2.core.test.implementation.TestingHelpers; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import org.junit.jupiter.api.extension.AfterEachCallback; +import org.junit.jupiter.api.extension.BeforeAllCallback; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtensionContext; + +import java.lang.management.ManagementFactory; +import java.lang.management.ThreadInfo; +import java.lang.management.ThreadMXBean; +import java.time.Duration; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +/** + * A utility and extension to dump threads after 30 minutes from starting tests. It can be used as standalone utility + * via {@link #initialize()} as well as hooked up with JUnit by implementing + * {@link BeforeAllCallback#beforeAll(ExtensionContext)}. + *

        + * ThreadDumper also tracks which tests are running and when they began running. These tests and how long they've been + * running will be included in the thread dumps if they've been running longer than 5 minutes. + */ +public class ThreadDumper implements BeforeAllCallback, BeforeEachCallback, AfterEachCallback { + + private static final ClientLogger LOGGER = new ClientLogger(ThreadDumper.class); + private static volatile ExecutorService executorService; + + // Assume that after 30 minutes test job hangs. + private static final int INITIAL_DELAY_IN_MINUTES = 30; + // Log every minute after initial interval passes. + private static final int RATE_IN_MINUTES = 2; + private static final long FIVE_MINUTES_MILLIS = Duration.ofMinutes(5).toMillis(); + + private static final Map RUNNING_TEST_TIMES = new ConcurrentHashMap<>(); + + /** + * Creates a new instance of {@link ThreadDumper}. + */ + public ThreadDumper() { + } + + /** + * Initializes the singleton dumper. Can be called multiple times safely. + */ + public static void initialize() { + if (executorService == null) { + synchronized (ThreadDumper.class) { + if (executorService == null) { + executorService = createExecutorService(); + } + } + } + } + + private static ExecutorService createExecutorService() { + ScheduledExecutorService service = Executors.newScheduledThreadPool(1, r -> { + Thread t = new Thread(r); + t.setDaemon(true); + return t; + }); + Runtime.getRuntime().addShutdownHook(new Thread(service::shutdown)); + + service.scheduleAtFixedRate(ThreadDumper::printThreadStacks, INITIAL_DELAY_IN_MINUTES, RATE_IN_MINUTES, + TimeUnit.MINUTES); + + return service; + } + + private static void printThreadStacks() { + final StringBuilder dump = new StringBuilder("============= THREAD DUMP START ========="); + final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); + final ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), 100); + for (ThreadInfo threadInfo : threadInfos) { + dump.append('"'); + dump.append(threadInfo.getThreadName()); + dump.append("\" "); + final Thread.State state = threadInfo.getThreadState(); + dump.append("\n java.lang.Thread.State: "); + dump.append(state); + final StackTraceElement[] stackTraceElements = threadInfo.getStackTrace(); + for (final StackTraceElement stackTraceElement : stackTraceElements) { + dump.append("\n at "); + dump.append(stackTraceElement); + } + dump.append("\n\n"); + } + + dump.append("============= THREAD DUMP END =========") + .append(System.lineSeparator()) + .append("========= RUNNING TESTS START ========="); + + long nowMillis = System.currentTimeMillis(); + for (Map.Entry runningTest : RUNNING_TEST_TIMES.entrySet()) { + if (nowMillis - runningTest.getValue() > FIVE_MINUTES_MILLIS) { + dump.append(System.lineSeparator()) + .append(runningTest.getKey()) + .append(": ") + .append(nowMillis - runningTest.getValue()) + .append(" millis"); + } + } + dump.append("========== RUNNING TESTS END ==========\n"); + + String output = dump.toString(); + + // Log to both console and logs + System.err.println(output); + LOGGER.atInfo().log(output); + } + + @Override + public void beforeAll(ExtensionContext context) { + initialize(); + } + + @Override + public void beforeEach(ExtensionContext context) { + // If the test class is an instance of TestBase or is a subtype of TestBase, then we don't need to track + // anything here as TestBase handles this logic in it's Before and After test methods. + Class clazz = context.getTestClass().orElse(null); + if (clazz != null && TestBase.class.isAssignableFrom(clazz)) { + return; + } + + RUNNING_TEST_TIMES.put(getFullTestName(context), System.currentTimeMillis()); + } + + static void addRunningTest(String testName) { + RUNNING_TEST_TIMES.put(testName, System.currentTimeMillis()); + } + + @Override + public void afterEach(ExtensionContext context) { + // If the test class is an instance of TestBase or is a subtype of TestBase, then we don't need to track + // anything here as TestBase handles this logic in it's Before and After test methods. + Class clazz = context.getTestClass().orElse(null); + if (clazz != null && TestBase.class.isAssignableFrom(clazz)) { + return; + } + + RUNNING_TEST_TIMES.remove(getFullTestName(context)); + } + + static void removeRunningTest(String testName) { + RUNNING_TEST_TIMES.remove(testName); + } + + private static String getFullTestName(ExtensionContext context) { + return TestingHelpers.getTestName(context.getTestMethod(), context.getDisplayName(), context.getTestClass()); + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/annotation/DoNotRecord.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/annotation/DoNotRecord.java new file mode 100644 index 000000000000..31d749aec916 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/annotation/DoNotRecord.java @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.annotation; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.METHOD; +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 or there + * won't be any network calls made during the test to prevent creating an empty recording. + */ +@Retention(RUNTIME) +@Target({ METHOD }) +public @interface DoNotRecord { +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/annotation/LiveOnly.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/annotation/LiveOnly.java new file mode 100644 index 000000000000..7c6cf0c2f7ec --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/annotation/LiveOnly.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.annotation; + +import com.azure.v2.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/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/annotation/PlaybackOnly.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/annotation/PlaybackOnly.java new file mode 100644 index 000000000000..1ababe062811 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/annotation/PlaybackOnly.java @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.annotation; + +import com.azure.v2.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/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/annotation/RecordWithoutRequestBody.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/annotation/RecordWithoutRequestBody.java new file mode 100644 index 000000000000..c97a6420cae4 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/annotation/RecordWithoutRequestBody.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + * Annotation given to some tests to skip recording request bodies when test run in Record mode and using Test Proxy. + *

        + * A common case for setting this is when the test has either + * sensitive content that cannot be redacted or large request body content that does not need to be recorded. + *

        + */ +@Retention(RUNTIME) +@Target({ ElementType.TYPE, ElementType.METHOD }) +public @interface RecordWithoutRequestBody { +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/annotation/package-info.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/annotation/package-info.java new file mode 100644 index 000000000000..b17838af01b0 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/annotation/package-info.java @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * Package containing annotations test classes for Azure client libraries. + */ +package com.azure.v2.core.test.annotation; diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/http/MockHttpClient.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/http/MockHttpClient.java new file mode 100644 index 000000000000..6e5a0343ff21 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/http/MockHttpClient.java @@ -0,0 +1,266 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.http; + +import com.azure.v2.core.test.implementation.models.HttpBinFormDataJson; +import com.azure.v2.core.test.implementation.models.HttpBinJson; +import com.azure.v2.core.test.implementation.models.PizzaSize; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpHeaders; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.utils.Base64Uri; +import io.clientcore.core.utils.DateTimeRfc1123; + +import java.io.IOException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.ThreadLocalRandom; + +/** + * This HttpClient attempts to mimic the behavior of http://httpbin.org without ever making a network call. + */ +public class MockHttpClient extends NoOpHttpClient { + private static final HttpHeaders RESPONSE_HEADERS + = new HttpHeaders().set(HttpHeaderName.DATE, "Fri, 13 Oct 2017 20:33:09 GMT") + .set(HttpHeaderName.VIA, "1.1 via") + .set(HttpHeaderName.CONNECTION, "keep-alive") + .set(HttpHeaderName.fromString("X-Processed-Time"), "1.0") + .set(HttpHeaderName.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true") + .set(HttpHeaderName.CONTENT_TYPE, "application/json"); + + /** + * Creates a new instance of MockHttpClient. + */ + public MockHttpClient() { + } + + @Override + public Response send(HttpRequest request) throws IOException { + Response response = null; + final URI requestUri = request.getUri(); + final String requestHost = requestUri.getHost(); + final String contentType = request.getHeaders().getValue(HttpHeaderName.CONTENT_TYPE); + if ("localhost".equalsIgnoreCase(requestHost)) { + final String requestPath = requestUri.getPath(); + final String requestPathLower = requestPath.toLowerCase(Locale.ROOT); + if (requestPathLower.startsWith("/anything")) { + if ("HEAD".equals(request.getHttpMethod().name())) { + response = new MockHttpResponse(request, 200, new byte[0]); + } else { + final HttpBinJson json = new HttpBinJson(); + json.uri(cleanseUri(requestUri)); + json.headers(toMap(request.getHeaders())); + response = new MockHttpResponse(request, 200, json.toJsonBytes()); + } + } else if (requestPathLower.startsWith("/bytes/")) { + final String byteCountString = requestPath.substring("/bytes/".length()); + final int byteCount = Integer.parseInt(byteCountString); + HttpHeaders newHeaders + = new HttpHeaders(RESPONSE_HEADERS).set(HttpHeaderName.CONTENT_TYPE, "application/octet-stream") + .set(HttpHeaderName.CONTENT_LENGTH, Integer.toString(byteCount)); + byte[] content; + if (byteCount > 0) { + content = new byte[byteCount]; + ThreadLocalRandom.current().nextBytes(content); + newHeaders = newHeaders.set(HttpHeaderName.ETAG, md5(content)); + } else { + content = null; + } + response = new MockHttpResponse(request, 200, newHeaders, content); + } else if (requestPathLower.startsWith("/base64urlbytes/")) { + final String byteCountString = requestPath.substring("/base64urlbytes/".length()); + final int byteCount = Integer.parseInt(byteCountString); + final byte[] bytes = new byte[byteCount]; + for (int i = 0; i < byteCount; ++i) { + bytes[i] = (byte) i; + } + final Base64Uri base64EncodedBytes = bytes.length == 0 ? null : Base64Uri.encode(bytes); + response = new MockHttpResponse(request, 200, RESPONSE_HEADERS, base64EncodedBytes); + } else if ("/base64urllistofbytes".equals(requestPathLower)) { + final List base64EncodedBytesList = new ArrayList<>(); + for (int i = 0; i < 3; ++i) { + final int byteCount = (i + 1) * 10; + final byte[] bytes = new byte[byteCount]; + for (int j = 0; j < byteCount; ++j) { + bytes[j] = (byte) j; + } + final Base64Uri base64UriEncodedBytes = Base64Uri.encode(bytes); + base64EncodedBytesList.add(base64UriEncodedBytes.toString()); + } + response = new MockHttpResponse(request, 200, RESPONSE_HEADERS, base64EncodedBytesList); + } else if ("/base64urllistoflistofbytes".equals(requestPathLower)) { + final List> result = new ArrayList<>(); + for (int i = 0; i < 2; ++i) { + final List innerList = new ArrayList<>(); + for (int j = 0; j < (i + 1) * 2; ++j) { + final int byteCount = (j + 1) * 5; + final byte[] bytes = new byte[byteCount]; + for (int k = 0; k < byteCount; ++k) { + bytes[k] = (byte) k; + } + + final Base64Uri base64UriEncodedBytes = Base64Uri.encode(bytes); + innerList.add(base64UriEncodedBytes.toString()); + } + result.add(innerList); + } + response = new MockHttpResponse(request, 200, RESPONSE_HEADERS, result); + } else if ("/base64urlmapofbytes".equals(requestPathLower)) { + final Map result = new HashMap<>(); + for (int i = 0; i < 2; ++i) { + final String key = Integer.toString(i); + + final int byteCount = (i + 1) * 10; + final byte[] bytes = new byte[byteCount]; + for (int j = 0; j < byteCount; ++j) { + bytes[j] = (byte) j; + } + + final Base64Uri base64UriEncodedBytes = Base64Uri.encode(bytes); + result.put(key, base64UriEncodedBytes.toString()); + } + response = new MockHttpResponse(request, 200, RESPONSE_HEADERS, result); + } else if ("/datetimerfc1123".equals(requestPathLower)) { + final DateTimeRfc1123 now + = new DateTimeRfc1123(OffsetDateTime.ofInstant(Instant.ofEpochSecond(0), ZoneOffset.UTC)); + final String result = now.toString(); + response = new MockHttpResponse(request, 200, RESPONSE_HEADERS, result); + } else if ("/unixtime".equals(requestPathLower)) { + response = new MockHttpResponse(request, 200, RESPONSE_HEADERS, 0); + } else if ("/delete".equals(requestPathLower)) { + final HttpBinJson json = new HttpBinJson(); + json.uri(cleanseUri(requestUri)); + json.data(createHttpBinResponseDataForRequest(request)); + response = new MockHttpResponse(request, 200, json.toJsonBytes()); + } else if ("/get".equals(requestPathLower)) { + final HttpBinJson json = new HttpBinJson(); + json.uri(cleanseUri(requestUri)); + json.headers(toMap(request.getHeaders())); + response = new MockHttpResponse(request, 200, json.toJsonBytes()); + } else if ("/patch".equals(requestPathLower)) { + final HttpBinJson json = new HttpBinJson(); + json.uri(cleanseUri(requestUri)); + json.data(createHttpBinResponseDataForRequest(request)); + response = new MockHttpResponse(request, 200, json.toJsonBytes()); + } else if ("/post".equals(requestPathLower)) { + if (contentType != null && contentType.contains("x-www-form-urlencoded")) { + Map parsed = bodyToMap(request); + final HttpBinFormDataJson json = new HttpBinFormDataJson(); + HttpBinFormDataJson.Form form = new HttpBinFormDataJson.Form(); + form.customerName(parsed.get("custname")); + form.customerEmail(parsed.get("custemail")); + form.customerTelephone(parsed.get("custtel")); + form.pizzaSize(PizzaSize.valueOf(parsed.get("size"))); + form.toppings(Arrays.asList(parsed.get("toppings").split(","))); + json.form(form); + response = new MockHttpResponse(request, 200, RESPONSE_HEADERS, json.toJsonBytes()); + } else { + final HttpBinJson json = new HttpBinJson(); + json.uri(cleanseUri(requestUri)); + json.data(createHttpBinResponseDataForRequest(request)); + json.headers(toMap(request.getHeaders())); + response = new MockHttpResponse(request, 200, json.toJsonBytes()); + } + } else if ("/put".equals(requestPathLower)) { + final HttpBinJson json = new HttpBinJson(); + json.uri(cleanseUri(requestUri)); + json.data(createHttpBinResponseDataForRequest(request)); + json.headers(toMap(request.getHeaders())); + response = new MockHttpResponse(request, 200, RESPONSE_HEADERS, json.toJsonBytes()); + } else if (requestPathLower.startsWith("/status/")) { + final String statusCodeString = requestPathLower.substring("/status/".length()); + final int statusCode = Integer.parseInt(statusCodeString); + response = new MockHttpResponse(request, statusCode); + } else if (requestPathLower.startsWith("/voideagerreadoom")) { + response = new MockHttpResponse(request, 200); + } else if (requestPathLower.startsWith("/voiderrorreturned")) { + response + = new MockHttpResponse(request, 400, "void exception body thrown".getBytes(StandardCharsets.UTF_8)); + } + } else if ("echo.org".equalsIgnoreCase(requestHost)) { + return new MockHttpResponse(request, 200, new HttpHeaders(request.getHeaders()), request.getBody()); + } + + if (response == null) { + response = new MockHttpResponse(request, 500); + } + + return response; + } + + private static String createHttpBinResponseDataForRequest(HttpRequest request) { + return bodyToString(request); + } + + private static String bodyToString(HttpRequest request) { + String body = ""; + if (request.getBody() != null) { + return request.getBody().toString(); + } + return body; + } + + private static Map> toMap(HttpHeaders headers) { + final Map> result = new HashMap<>(); + headers.stream().forEach(header -> result.put(header.getName().getCaseSensitiveName(), header.getValues())); + return result; + } + + private static Map bodyToMap(HttpRequest request) { + final Map result = new HashMap<>(); + String body = bodyToString(request); + for (String keyValPair : body.split("&")) { + String[] parts = keyValPair.split("="); + assert parts.length == 2; + if (result.containsKey(parts[0])) { + result.put(parts[0], result.get(parts[0]) + "," + parts[1]); + } else { + result.put(parts[0], parts[1]); + } + } + return result; + } + + private static String cleanseUri(URI uri) { + StringBuilder builder = new StringBuilder(); + builder.append(uri.getScheme()).append("://").append(uri.getHost()).append(uri.getPath().replace("%20", " ")); + + if (uri.getQuery() != null) { + builder.append("?").append(uri.getQuery().replace("%20", " ")); + } + + return builder.toString(); + } + + /** + * Returns base64 encoded MD5 of bytes. + * + * @param bytes bytes. + * @return base64 encoded MD5 of bytes. + * @throws RuntimeException if md5 is not found. + */ + public static String md5(byte[] bytes) { + try { + MessageDigest digest = MessageDigest.getInstance("MD5"); + digest.update(bytes); + return Base64.getEncoder().encodeToString(digest.digest()); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/http/MockHttpResponse.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/http/MockHttpResponse.java new file mode 100644 index 000000000000..30bf4265e330 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/http/MockHttpResponse.java @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.http; + +import io.clientcore.core.http.models.HttpHeaders; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.models.binarydata.ByteArrayBinaryData; + +import java.io.IOException; + +/** + * An HTTP response that is created to simulate an HTTP request. + */ +public class MockHttpResponse extends Response { + /** + * Creates an HTTP response associated with a {@code request}, returns the {@code statusCode}, and has an empty + * response body. + * + * @param request HttpRequest associated with the response. + * @param statusCode Status code of the response. + */ + public MockHttpResponse(HttpRequest request, int statusCode) { + this(request, statusCode, new byte[0]); + } + + /** + * Creates an HTTP response associated with a {@code request}, returns the {@code statusCode}, and response body of + * {@code bodyBytes}. + * + * @param request HttpRequest associated with the response. + * @param statusCode Status code of the response. + * @param bodyBytes Contents of the response. + */ + public MockHttpResponse(HttpRequest request, int statusCode, byte[] bodyBytes) { + this(request, statusCode, new HttpHeaders(), bodyBytes); + } + + /** + * Creates an HTTP response associated with a {@code request}, returns the {@code statusCode}, contains the + * {@code headers}, and response body of {@code bodyBytes}. + * + * @param request HttpRequest associated with the response. + * @param statusCode Status code of the response. + * @param headers HttpHeaders of the response. + * @param bodyBytes Contents of the response. + */ + public MockHttpResponse(HttpRequest request, int statusCode, HttpHeaders headers, byte[] bodyBytes) { + this(request, statusCode, headers, new ByteArrayBinaryData(bodyBytes)); + } + + /** + * Creates an HTTP response associated with a {@code request}, returns the {@code statusCode}, contains the + * {@code headers}, and response body of {@code body}. + * + * @param request HttpRequest associated with the response. + * @param statusCode Status code of the response. + * @param headers HttpHeaders of the response. + * @param body Contents of the response. + */ + public MockHttpResponse(HttpRequest request, int statusCode, HttpHeaders headers, BinaryData body) { + super(request, statusCode, headers, body); + } + + /** + * Creates an HTTP response associated with a {@code request}, returns the {@code statusCode}, contains the given + * {@code headers}, and response body that is JSON serialized from {@code serializable}. + * + * @param request HttpRequest associated with the response. + * @param headers HttpHeaders of the response. + * @param statusCode Status code of the response. + * @param serializable Contents to be serialized into JSON for the response. + */ + public MockHttpResponse(HttpRequest request, int statusCode, HttpHeaders headers, Object serializable) { + this(request, statusCode, headers, serialize(serializable)); + } + + private static BinaryData serialize(Object serializable) { + return BinaryData.fromObject(serializable); + } + + @Override + public void close() throws IOException { + super.close(); + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/http/NoOpHttpClient.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/http/NoOpHttpClient.java new file mode 100644 index 000000000000..226db912d470 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/http/NoOpHttpClient.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.http; + +import io.clientcore.core.http.client.HttpClient; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.models.binarydata.BinaryData; + +import java.io.IOException; + +/** + * An HttpClient instance that does not do anything. + */ +public class NoOpHttpClient implements HttpClient { + /** + * Creates a new NoOpHttpClient. + */ + public NoOpHttpClient() { + } + + @Override + public Response send(HttpRequest request) throws IOException { + return null; + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/http/TestProxyPlaybackClient.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/http/TestProxyPlaybackClient.java new file mode 100644 index 000000000000..4c97412a9d1f --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/http/TestProxyPlaybackClient.java @@ -0,0 +1,281 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.http; + +import com.azure.v2.core.test.models.RecordFilePayload; +import com.azure.v2.core.test.models.TestProxyRequestMatcher; +import com.azure.v2.core.test.models.TestProxySanitizer; +import com.azure.v2.core.test.utils.HttpUrlConnectionHttpClient; +import com.azure.v2.core.test.utils.TestProxyUtils; +import io.clientcore.core.http.client.HttpClient; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpMethod; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonWriter; +import io.clientcore.core.models.binarydata.BinaryData; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Queue; +import java.util.concurrent.TimeUnit; + +import static com.azure.v2.core.test.implementation.TestingHelpers.X_RECORDING_FILE_LOCATION; +import static com.azure.v2.core.test.implementation.TestingHelpers.X_RECORDING_ID; +import static com.azure.v2.core.test.utils.TestProxyUtils.checkForTestProxyErrors; +import static com.azure.v2.core.test.utils.TestProxyUtils.createAddSanitizersRequest; +import static com.azure.v2.core.test.utils.TestProxyUtils.getAssetJsonFile; +import static com.azure.v2.core.test.utils.TestProxyUtils.getMatcherRequests; +import static com.azure.v2.core.test.utils.TestProxyUtils.getRemoveSanitizerRequest; +import static com.azure.v2.core.test.utils.TestProxyUtils.loadSanitizers; + +/** + * A {@link HttpClient} that plays back test recordings from the external test proxy. + */ +public class TestProxyPlaybackClient implements HttpClient { + + private static final ClientLogger LOGGER = new ClientLogger(TestProxyPlaybackClient.class); + private final HttpClient client; + private final URI proxyUri; + private String xRecordingId; + private String xRecordingFileLocation; + + private static final List DEFAULT_SANITIZERS = loadSanitizers(); + private final List sanitizers = new ArrayList<>(); + + private final List matchers = new ArrayList<>(); + private final boolean skipRecordingRequestBody; + + /** + * Create an instance of {@link TestProxyPlaybackClient} with a list of custom sanitizers. + * + * @param httpClient The {@link HttpClient} to use. If none is passed {@link HttpUrlConnectionHttpClient} is the + * default. + * @param skipRecordingRequestBody Flag indicating to skip recording request bodies, so to set a custom matcher to + * skip comparing bodies when run in playback. + */ + public TestProxyPlaybackClient(HttpClient httpClient, boolean skipRecordingRequestBody) { + this.client = (httpClient == null ? new HttpUrlConnectionHttpClient() : httpClient); + this.proxyUri = TestProxyUtils.getProxyUri(); + this.sanitizers.addAll(DEFAULT_SANITIZERS); + this.skipRecordingRequestBody = skipRecordingRequestBody; + } + + /** + * Starts playback of a test recording. + * + * @param recordFile The name of the file to read. + * @return A {@link Queue} representing the variables in the recording. + * @param testClassPath the test class path + * @throws UncheckedIOException if an {@link IOException} is thrown. + * @throws RuntimeException Failed to serialize body payload. + */ + public Queue startPlayback(File recordFile, Path testClassPath) { + HttpRequest request; + String assetJsonPath = getAssetJsonFile(recordFile, testClassPath); + try { + request = new HttpRequest().setMethod(HttpMethod.POST) + .setUri(proxyUri + "/playback/start") + .setBody(BinaryData.fromObject(new RecordFilePayload(recordFile.toString(), assetJsonPath))); + request.getHeaders() + .set(HttpHeaderName.ACCEPT, "application/json") + .set(HttpHeaderName.CONTENT_TYPE, "application/json"); + Response response = sendRequestWithRetries(request); + checkForTestProxyErrors(response); + xRecordingId = response.getHeaders().getValue(X_RECORDING_ID); + xRecordingFileLocation + = new String(Base64.getUrlDecoder().decode(response.getHeaders().getValue(X_RECORDING_FILE_LOCATION)), + StandardCharsets.UTF_8); + addProxySanitization(this.sanitizers); + addMatcherRequests(this.matchers); + // The test proxy stores variables in a map with no guaranteed order. + // The Java implementation of recording did not use a map, but relied on the order + // of the variables as they were stored. Our scheme instead sets an increasing integer + // the key. See TestProxyRecordPolicy.serializeVariables. + // This deserializes the map returned from the test proxy and creates an ordered list + // based on the key. + try (JsonReader jsonReader = JsonReader.fromBytes(response.getValue().toBytes())) { + Map variables = jsonReader.readMap(JsonReader::getString); + List> toSort; + if (variables == null) { + toSort = new ArrayList<>(); + } else { + toSort = new ArrayList<>(variables.entrySet()); + toSort.sort(Comparator.comparingInt(e -> Integer.parseInt(e.getKey()))); + } + + LinkedList strings = new LinkedList<>(); + for (Map.Entry stringStringEntry : toSort) { + String value = stringStringEntry.getValue(); + strings.add(value); + } + return strings; + } + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private Response sendRequestWithRetries(HttpRequest request) throws IOException { + int retries = 0; + while (true) { + try { + Response response = client.send(request); + if (response.getStatusCode() / 100 != 2) { + throw new RuntimeException("Test proxy returned a non-successful status code. " + + response.getStatusCode() + "; response: " + response.getValue()); + } + return response; + } catch (Exception e) { + retries++; + if (retries >= 3) { + throw e; + } + sleep(1); + LOGGER.atWarning().addKeyValue("retryAttempt", retries).log("Retrying request to test proxy."); + } + } + } + + private void sleep(int durationInSeconds) { + try { + TimeUnit.SECONDS.sleep(durationInSeconds); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + + /** + * Stops playback of a test recording. + * + * @throws IOException If an error occurs while sending the request. + */ + public void stopPlayback() throws IOException { + HttpRequest request = new HttpRequest().setMethod(HttpMethod.POST).setUri(proxyUri + "/playback/stop"); + request.getHeaders().set(X_RECORDING_ID, xRecordingId); + sendRequestWithRetries(request).close(); + } + + /** + * Method is invoked before the request is sent. + * + * @param request The request context. + * @throws RuntimeException if playback was started before request is sent. + */ + private void beforeSendingRequest(HttpRequest request) { + if (xRecordingId == null) { + throw new RuntimeException("Playback was not started before a request was sent."); + } + TestProxyUtils.changeHeaders(request, proxyUri, xRecordingId, "playback", false); + } + + /** + * Method is invoked after the response is received. + * + * @param response The response received. + * @return The transformed response. + */ + private Response afterReceivedResponse(Response response) { + TestProxyUtils.checkForTestProxyErrors(response); + return TestProxyUtils.resetTestProxyData(response); + } + + /** + * Redirects the request to the test-proxy to retrieve the playback response synchronously. + * @param request The HTTP request to send. + * @return The HTTP response. + * @throws IOException If an error occurs while sending the request. + */ + @Override + public Response send(HttpRequest request) throws IOException { + beforeSendingRequest(request); + Response response = client.send(request); + return afterReceivedResponse(response); + } + + /** + * Add a list of {@link TestProxySanitizer} to the current playback session. + * @param sanitizers The sanitizers to add. + * @throws IOException If an error occurs while sending the request. + */ + public void addProxySanitization(List sanitizers) throws IOException { + if (isPlayingBack()) { + HttpRequest request = createAddSanitizersRequest(sanitizers, proxyUri); + request.getHeaders().set(X_RECORDING_ID, xRecordingId); + + sendRequestWithRetries(request).close(); + } else { + this.sanitizers.addAll(sanitizers); + } + } + + /** + * Removes the list of sanitizers from the current playback session. + * @param sanitizers The sanitizers to remove. + * @throws IOException If an error occurs while sending the request. + */ + public void removeProxySanitization(List sanitizers) throws IOException { + if (isPlayingBack()) { + Map> data = new HashMap<>(); + data.put("Sanitizers", sanitizers); + + HttpRequest request; + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + JsonWriter jsonWriter = JsonWriter.toStream(outputStream)) { + jsonWriter.writeMap(data, (writer, value) -> writer.writeArray(value, JsonWriter::writeString)).flush(); + request = getRemoveSanitizerRequest().setBody(BinaryData.fromBytes(outputStream.toByteArray())); + request.getHeaders().set(X_RECORDING_ID, xRecordingId); + } + + sendRequestWithRetries(request).close(); + } + } + + /** + * Add a list of {@link TestProxyRequestMatcher} to the current playback session. + * @param matchers The matchers to add. + * @throws IOException If an error occurs while sending the request. + */ + public void addMatcherRequests(List matchers) throws IOException { + if (isPlayingBack()) { + List matcherRequests = getMatcherRequests(matchers, proxyUri); + if (skipRecordingRequestBody) { + matcherRequests.add(TestProxyUtils.setCompareBodiesMatcher()); + } + + for (HttpRequest request : matcherRequests) { + request.getHeaders().set(X_RECORDING_ID, xRecordingId); + sendRequestWithRetries(request).close(); + } + } else { + this.matchers.addAll(matchers); + } + } + + private boolean isPlayingBack() { + return xRecordingId != null; + } + + /** + * Get the recording file location in assets repo. + * @return the assets repo location of the recording file. + */ + public String getRecordingFileLocation() { + return xRecordingFileLocation; + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/http/package-info.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/http/package-info.java new file mode 100644 index 000000000000..8e5bba4f2c43 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/http/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing classes to test HTTP communications in Azure client libraries. + */ +package com.azure.v2.core.test.http; diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/implementation/TestingHelpers.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/implementation/TestingHelpers.java new file mode 100644 index 000000000000..9ebf5c54d0d5 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/implementation/TestingHelpers.java @@ -0,0 +1,162 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.implementation; + +import com.azure.v2.core.test.TestMode; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.utils.IOExceptionCheckedBiConsumer; +import io.clientcore.core.utils.configuration.Configuration; + +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; +import java.util.function.Supplier; + +/** + * Implementation utility class. + */ +public final class TestingHelpers { + private static final ClientLogger LOGGER = new ClientLogger(TestingHelpers.class); + + public static final String AZURE_TEST_MODE = "AZURE_TEST_MODE"; + public static final HttpHeaderName X_RECORDING_ID = HttpHeaderName.fromString("x-recording-id"); + public static final HttpHeaderName X_RECORDING_FILE_LOCATION + = HttpHeaderName.fromString("x-base64-recording-file-location"); + + private static final TestMode TEST_MODE = initializeTestMode(); + + private static TestMode initializeTestMode() { + final String azureTestMode = Configuration.getGlobalConfiguration().get(AZURE_TEST_MODE); + + if (azureTestMode != null) { + try { + return TestMode.valueOf(azureTestMode.toUpperCase(Locale.US)); + } catch (IllegalArgumentException e) { + LOGGER.atWarning() + .addKeyValue("testMode", azureTestMode) + .log("Could not parse into TestEnum. Using 'Playback' mode."); + return TestMode.PLAYBACK; + } + } + + LOGGER.atInfo() + .addKeyValue("envVar", AZURE_TEST_MODE) + .log("Environment variable has not been set yet. Using 'Playback' mode."); + 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. + * + * @param source The input stream to copy from. + * @param destination The output stream to copy to. + * @throws IOException If an I/O error occurs. + */ + public static void copy(InputStream source, OutputStream destination) throws IOException { + byte[] buffer = new byte[8192]; + int read; + + while ((read = source.read(buffer, 0, buffer.length)) != -1) { + 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 + ")"; + } + + /** + * Reads a JSON object from the passed {@code jsonReader} and creates an object of type {@code T} using the passed + * {@code objectCreator}. The {@code callback} is then called for each field in the JSON object to read the field + * value and set it on the object. + * + * @param jsonReader The JSON reader to read the object from. + * @param objectCreator The supplier that creates a new instance of the object. + * @param callback The callback that reads the field value and sets it on the object. + * @return The object created from the JSON object. + * @param The type of object to create. + * @throws IOException If an error occurs while reading the JSON object. + */ + public static T readObject(JsonReader jsonReader, Supplier objectCreator, ReadObjectCallback callback) + throws IOException { + return jsonReader.readObject(reader -> { + T object = objectCreator.get(); + fieldReaderLoop(reader, (fieldName, r) -> callback.read(object, fieldName, r)); + return object; + }); + } + + /** + * Callback for reading a JSON object. + * + * @param The type of the object being read. + */ + public interface ReadObjectCallback { + /** + * Reads a field from the JSON object and sets it on the object. + * + * @param object The object to set the field on. + * @param fieldName The name of the field being read. + * @param jsonReader The JSON reader to read the field value from. + * @throws IOException If an error occurs while reading the field value. + */ + void read(T object, String fieldName, JsonReader jsonReader) throws IOException; + } + + /** + * Helper method to iterate over the field of a JSON object. + *

        + * This method will reader the passed {@code jsonReader} until the end of the object is reached. For each field it + * will get the field name and iterate the reader to the next token. This method will then pass the field name and + * reader to the {@code fieldConsumer} for it to consume the JSON field as needed for the object being read. + * + * @param jsonReader The JSON reader to read the object from. + * @param fieldConsumer The consumer that will consume the field name and reader for each field in the object. + * @throws IOException If an error occurs while reading the JSON object. + */ + public static void fieldReaderLoop(JsonReader jsonReader, + IOExceptionCheckedBiConsumer fieldConsumer) throws IOException { + while (jsonReader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = jsonReader.getFieldName(); + jsonReader.nextToken(); + + fieldConsumer.accept(fieldName, jsonReader); + } + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/implementation/models/HttpBinFormDataJson.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/implementation/models/HttpBinFormDataJson.java new file mode 100644 index 000000000000..66c9bf611bb0 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/implementation/models/HttpBinFormDataJson.java @@ -0,0 +1,271 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.v2.core.test.implementation.models; + +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonSerializable; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.serialization.json.JsonWriter; + +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + * Maps to the JSON return values from http://httpbin.org. + */ +public final class HttpBinFormDataJson implements JsonSerializable { + private String uri; + private Map headers; + private Form form; + + /** + * Creates an instance of HttpBinFormDataJson. + */ + public HttpBinFormDataJson() { + } + + /** + * Gets the URI associated with this request. + * + * @return he URI associated with the request. + */ + public String uri() { + return uri; + } + + /** + * Sets the URI associated with this request. + * + * @param uri The URI associated with the request. + */ + public void uri(String uri) { + this.uri = uri; + } + + /** + * Gets the headers. + * + * @return The headers. + */ + public Map headers() { + return headers; + } + + /** + * Sets the headers. + * + * @param headers The headers. + */ + public void headers(Map headers) { + this.headers = headers; + } + + /** + * Gets the form. + * + * @return The form. + */ + public Form form() { + return form; + } + + /** + * Sets the form. + * + * @param form The form. + */ + public void form(Form form) { + this.form = form; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject() + .writeStringField("uri", uri) + .writeMapField("headers", headers, JsonWriter::writeString) + .writeJsonField("form", form) + .writeEndObject(); + } + + /** + * Deserializes an instance of HttpBinFormDataJson from the input JSON. + * + * @param jsonReader The JSON reader to read from. + * @return An instance of HttpBinFormDataJson deserialized from the input JSON. + * @throws IOException If an error occurs while reading from the JSON. + */ + public static HttpBinFormDataJson fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + HttpBinFormDataJson form = new HttpBinFormDataJson(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("uri".equals(fieldName)) { + form.uri = reader.getString(); + } else if ("headers".equals(fieldName)) { + form.headers = reader.readMap(JsonReader::getString); + } else if ("form".equals(fieldName)) { + form.form = Form.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return form; + }); + } + + /** + * Form. + */ + public static class Form implements JsonSerializable

        { + private String customerName; + private String customerTelephone; + private String customerEmail; + private PizzaSize pizzaSize; + private List toppings; + + /** + * Creates an instance of Form. + */ + public Form() { + } + + /** + * Gets the customer name. + * + * @return The customer name. + */ + public String customerName() { + return this.customerName; + } + + /** + * Sets the customer name. + * + * @param customerName The customer name. + */ + public void customerName(String customerName) { + this.customerName = customerName; + } + + /** + * Gets the customer telephone. + * + * @return The customer telephone. + */ + public String customerTelephone() { + return this.customerTelephone; + } + + /** + * Sets the customer telephone. + * + * @param customerTelephone The customer telephone. + */ + public void customerTelephone(String customerTelephone) { + this.customerTelephone = customerTelephone; + } + + /** + * Gets the customer email. + * + * @return The customer email. + */ + public String customerEmail() { + return this.customerEmail; + } + + /** + * Sets the customer email. + * + * @param customerEmail The customer email. + */ + public void customerEmail(String customerEmail) { + this.customerEmail = customerEmail; + } + + /** + * Gets the pizza size. + * + * @return The pizza size. + */ + public PizzaSize pizzaSize() { + return this.pizzaSize; + } + + /** + * Sets the pizza size. + * + * @param pizzaSize The pizza size. + */ + public void pizzaSize(PizzaSize pizzaSize) { + this.pizzaSize = pizzaSize; + } + + /** + * Gets the toppings. + * + * @return The toppings. + */ + public List toppings() { + return this.toppings; + } + + /** + * Sets the toppings. + * + * @param toppings The toppings. + */ + public void toppings(List toppings) { + this.toppings = toppings; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject() + .writeStringField("custname", customerName) + .writeStringField("custtel", customerTelephone) + .writeStringField("custemail", customerEmail) + .writeStringField("size", Objects.toString(pizzaSize, null)) + .writeArrayField("toppings", toppings, JsonWriter::writeString) + .writeEndObject(); + } + + /** + * Deserializes an instance of Form from the input JSON. + * + * @param jsonReader The JSON reader to read from. + * @return An instance of Form deserialized from the input JSON. + * @throws IOException If an error occurs while reading from the JSON. + */ + public static Form fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Form form = new Form(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("custname".equals(fieldName)) { + form.customerName = reader.getString(); + } else if ("custtel".equals(fieldName)) { + form.customerTelephone = reader.getString(); + } else if ("custemail".equals(fieldName)) { + form.customerEmail = reader.getString(); + } else if ("size".equals(fieldName)) { + form.pizzaSize = PizzaSize.fromString(reader.getString()); + } else if ("toppings".equals(fieldName)) { + form.toppings = reader.readArray(JsonReader::getString); + } else { + reader.skipChildren(); + } + } + + return form; + }); + } + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/implementation/models/HttpBinHeaders.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/implementation/models/HttpBinHeaders.java new file mode 100644 index 000000000000..a5eaeff76e66 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/implementation/models/HttpBinHeaders.java @@ -0,0 +1,181 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.v2.core.test.implementation.models; + +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpHeaders; +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonSerializable; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.serialization.json.JsonWriter; +import io.clientcore.core.utils.DateTimeRfc1123; + +import java.io.IOException; +import java.util.Objects; + +/** + * Defines headers for httpbin.org operations. + */ +public final class HttpBinHeaders implements JsonSerializable { + private static final HttpHeaderName X_PROCESSED_TIME = HttpHeaderName.fromString("X-Processed-Time"); + private static final HttpHeaderName ACCESS_CONTROL_ALLOW_CREDENTIALS + = HttpHeaderName.fromString("Access-Control-Allow-Credentials"); + + private DateTimeRfc1123 date; + private String via; + private String connection; + private double xProcessedTime; + private boolean accessControlAllowCredentials; + + /** + * Creates an instance of HttpBinHeaders. + */ + public HttpBinHeaders() { + } + + /** + * Creates an instance of HttpBinHeaders. + * + * @param headers The headers to use for initialization. + */ + public HttpBinHeaders(HttpHeaders headers) { + String dateHeader = headers.getValue(HttpHeaderName.DATE); + if (dateHeader != null) { + this.date = new DateTimeRfc1123(dateHeader); + } + this.via = headers.getValue(HttpHeaderName.VIA); + this.connection = headers.getValue(HttpHeaderName.CONNECTION); + + String xProcessedTimeHeader = headers.getValue(X_PROCESSED_TIME); + if (xProcessedTimeHeader != null) { + this.xProcessedTime = Double.parseDouble(xProcessedTimeHeader); + } + + String accessControlAllowCredentialsHeader = headers.getValue(ACCESS_CONTROL_ALLOW_CREDENTIALS); + if (accessControlAllowCredentialsHeader != null) { + this.accessControlAllowCredentials = Boolean.parseBoolean(accessControlAllowCredentialsHeader); + } + } + + /** + * Gets the date of the response. + * + * @return The date of the response. + */ + public DateTimeRfc1123 date() { + return date; + } + + /** + * Sets the date of the response. + * + * @param date The date of the response. + */ + public void date(DateTimeRfc1123 date) { + this.date = date; + } + + /** + * Gets any proxy information. + * + * @return Gets any proxy information. + * @see Via + */ + public String via() { + return via; + } + + /** + * Sets any proxy information. + * + * @param via Proxy information associated with this response. + * @see Via + */ + public void via(String via) { + this.via = via; + } + + /** + * Gets information about the connection status after this message is received. + * + * @return Information whether to keep network connection open or not. + * @see Connection + */ + public String connection() { + return connection; + } + + /** + * Sets information about the connection status after this message is received. + * + * @param connection Information whether to keep network connection open or not. + * @see Connection + */ + public void connection(String connection) { + this.connection = connection; + } + + /** + * Gets the time it took to process this request. + * + * @return Time to process this request in seconds. + * @see X-Processed-Time + */ + public double xProcessedTime() { + return xProcessedTime; + } + + /** + * Indicates whether to expose response to frontend JS code. + * + * @return True to expose response to frontend JS code and false otherwise. + * @see Access-Control-Allow-Credentials + */ + public boolean accessControlAllowCredentials() { + return accessControlAllowCredentials; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject() + .writeStringField("Date", Objects.toString(date, null)) + .writeStringField("Via", via) + .writeStringField("Connection", connection) + .writeDoubleField("X-Processed-Time", xProcessedTime) + .writeBooleanField("Access-Control-Allow-Credentials", accessControlAllowCredentials) + .writeEndObject(); + } + + /** + * Deserializes an instance of HttpBinHeaders from the input JSON. + * + * @param jsonReader The JSON reader to read from. + * @return An instance of HttpBinHeaders deserialized from the input JSON. + * @throws IOException If an error occurs while reading from the JSON. + */ + public static HttpBinHeaders fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + HttpBinHeaders headers = new HttpBinHeaders(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("Date".equals(fieldName)) { + headers.date = reader.getNullable(nonNullReader -> new DateTimeRfc1123(nonNullReader.getString())); + } else if ("Via".equals(fieldName)) { + headers.via = reader.getString(); + } else if ("Connection".equals(fieldName)) { + headers.connection = reader.getString(); + } else if ("X-Processed-Time".equals(fieldName)) { + headers.xProcessedTime = reader.getDouble(); + } else if ("Access-Control-Allow-Credentials".equals(fieldName)) { + headers.accessControlAllowCredentials = reader.getBoolean(); + } else { + reader.skipChildren(); + } + } + + return headers; + }); + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/implementation/models/HttpBinJson.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/implementation/models/HttpBinJson.java new file mode 100644 index 000000000000..95eea79fdb23 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/implementation/models/HttpBinJson.java @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.v2.core.test.implementation.models; + +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonSerializable; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.serialization.json.JsonWriter; + +import java.io.IOException; +import java.util.List; +import java.util.Map; + +/** + * Maps to the JSON return values from http://httpbin.org. + */ +public final class HttpBinJson implements JsonSerializable { + private String uri; + private Map> headers; + private String data; + + /** + * Creates an instance of HttpBinJson. + */ + public HttpBinJson() { + } + + /** + * Gets the URI associated with this request. + * + * @return he URI associated with the request. + */ + public String uri() { + return uri; + } + + /** + * Sets the URI associated with this request. + * + * @param uri The URI associated with the request. + */ + public void uri(String uri) { + this.uri = uri; + } + + /** + * Gets the response headers. + * + * @return The response headers. + */ + public Map> headers() { + return headers; + } + + /** + * Gets the value of the header with the provided name. + * + * @param name The name of the header. + * @return The value of the header with the provided name. + */ + public String getHeaderValue(String name) { + return headers == null ? null : headers.containsKey(name) ? headers.get(name).get(0) : null; + } + + /** + * Sets the response headers. + * + * @param headers The response headers. + */ + public void headers(Map> headers) { + this.headers = headers; + } + + /** + * Gets the response body. + * + * @return The response body. + */ + public String data() { + return data; + } + + /** + * Sets the response body. + * + * @param data The response body. + */ + public void data(String data) { + this.data = data; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject() + .writeStringField("uri", uri) + .writeMapField("headers", headers, (writer, list) -> writer.writeArray(list, JsonWriter::writeString)) + .writeStringField("data", data) + .writeEndObject(); + } + + /** + * Deserializes an instance of HttpBinJson from the input JSON. + * + * @param jsonReader The JSON reader to read from. + * @return An instance of HttpBinJson deserialized from the input JSON. + * @throws IOException If an error occurs while reading from the JSON. + */ + public static HttpBinJson fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + HttpBinJson headers = new HttpBinJson(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("uri".equals(fieldName)) { + headers.uri = reader.getString(); + } else if ("headers".equals(fieldName)) { + headers.headers = reader.readMap(listReader -> listReader.readArray(JsonReader::getString)); + } else if ("data".equals(fieldName)) { + headers.data = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return headers; + }); + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/implementation/models/PizzaSize.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/implementation/models/PizzaSize.java new file mode 100644 index 000000000000..81e543d0454e --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/implementation/models/PizzaSize.java @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.v2.core.test.implementation.models; + +/** + * Pizza size. + */ +public enum PizzaSize { + /** + * Small pizza. + */ + SMALL("small"), + + /** + * Medium pizza. + */ + MEDIUM("medium"), + + /** + * Large pizza. + */ + LARGE("large"); + + private final String value; + + PizzaSize(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } + + /** + * Parses a string value to a {@link PizzaSize}. + * + * @param value The string value to parse. + * @return The parsed {@link PizzaSize} object, or null if the string value is invalid. + */ + public static PizzaSize fromString(String value) { + for (PizzaSize size : PizzaSize.values()) { + if (size.value.equals(value)) { + return size; + } + } + return null; + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/implementation/models/package-info.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/implementation/models/package-info.java new file mode 100644 index 000000000000..7511b72dff59 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/implementation/models/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Internal testing models. + */ +package com.azure.v2.core.test.implementation.models; diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/implementation/package-info.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/implementation/package-info.java new file mode 100644 index 000000000000..b31d2d237d29 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/implementation/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing implementation classes for Azure Core Test. + */ +package com.azure.v2.core.test.implementation; diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/junitextensions/LiveOnlyExtension.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/junitextensions/LiveOnlyExtension.java new file mode 100644 index 000000000000..bd2284d29b71 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/junitextensions/LiveOnlyExtension.java @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.junitextensions; + +import com.azure.v2.core.test.TestMode; +import com.azure.v2.core.test.annotation.LiveOnly; +import com.azure.v2.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 { + /** + * Creates a new instance of LiveOnlyExtension. + */ + public LiveOnlyExtension() { + } + + @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/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/junitextensions/PlaybackOnlyExtension.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/junitextensions/PlaybackOnlyExtension.java new file mode 100644 index 000000000000..45232a7bec6f --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/junitextensions/PlaybackOnlyExtension.java @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.junitextensions; + +import com.azure.v2.core.test.TestMode; +import com.azure.v2.core.test.annotation.PlaybackOnly; +import com.azure.v2.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 { + /** + * Creates a new instance of PlaybackOnlyExtension. + */ + public PlaybackOnlyExtension() { + } + + @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/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/junitextensions/TestContextManagerParameterResolver.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/junitextensions/TestContextManagerParameterResolver.java new file mode 100644 index 000000000000..21d416c1ea6e --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/junitextensions/TestContextManagerParameterResolver.java @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.v2.core.test.junitextensions; + +import com.azure.v2.core.test.TestBase; +import com.azure.v2.core.test.TestContextManager; +import com.azure.v2.core.test.TestMode; +import com.azure.v2.core.test.annotation.RecordWithoutRequestBody; +import com.azure.v2.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.v2.core.test.implementation.TestingHelpers.getTestName; +import static com.azure.v2.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, + 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/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/junitextensions/package-info.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/junitextensions/package-info.java new file mode 100644 index 000000000000..356a10995c40 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/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.v2.core.test.junitextensions; diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/models/BodilessMatcher.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/models/BodilessMatcher.java new file mode 100644 index 000000000000..173fb5e53aaa --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/models/BodilessMatcher.java @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.models; + +/** + * Adjusts the "match" operation to EXCLUDE the body when matching a request to a recording's entries + */ +public class BodilessMatcher extends TestProxyRequestMatcher { + + /** + * Creates an instance of BodilessMatcher + */ + public BodilessMatcher() { + super(TestProxyRequestMatcherType.BODILESS); + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/models/CustomMatcher.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/models/CustomMatcher.java new file mode 100644 index 000000000000..333b4b9ef156 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/models/CustomMatcher.java @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.models; + +import java.util.List; + +/** + * This matcher exposes the default matcher in a customizable way. + * Currently, this includes ignoring/excluding headers, comparing request bodies and ignoring query params or query + * params ordering. + */ +public class CustomMatcher extends TestProxyRequestMatcher { + private List excludedHeaders; + + private List headersKeyOnlyMatch; + private boolean queryOrderingIgnored; + private List ignoredQueryParameters; + + private boolean comparingBodies; + + /** + * Creates an instance of CustomMatcher + */ + public CustomMatcher() { + super(TestProxyRequestMatcherType.CUSTOM); + } + + /** + * Gets the list of headers that should be excluded during matching. + * The presence of these headers will not be taken into account while matching. + * + * @return the excluded headers list + */ + public List getExcludedHeaders() { + return excludedHeaders; + } + + /** + * Sets the list of headers that should be excluded during matching. + * The presence of these headers will not be taken into account while matching. + * + * @param excludedHeaders the list of excluded headers + * @return The updated {@link CustomMatcher} object. + */ + public CustomMatcher setExcludedHeaders(List excludedHeaders) { + this.excludedHeaders = excludedHeaders; + return this; + } + + /** + * Gets the list of headers that should be ignored during matching. + * The header values won't be matched, but the presence of these headers will be taken into account while matching. + * + * @return the ignored headers list + */ + public List getHeadersKeyOnlyMatch() { + return headersKeyOnlyMatch; + } + + /** + * Sets the list of headers that should be ignored during matching. + * The header values won't be matched, but the presence of these headers will be taken into account while matching. + * + * @param headersKeyOnlyMatch the ignored headers list + * @return The updated {@link CustomMatcher} object. + */ + public CustomMatcher setHeadersKeyOnlyMatch(List headersKeyOnlyMatch) { + this.headersKeyOnlyMatch = headersKeyOnlyMatch; + return this; + } + + /** + * Get the boolean value to sort query params alphabetically before comparing URIs when matching + * @return the boolean + */ + public boolean isQueryOrderingIgnored() { + return queryOrderingIgnored; + } + + /** + * Sets query ordering to a boolean value to sort query params alphabetically before comparing URIs when matching. + * + * @param queryOrderingIgnored to ignore query ordering boolean value + * @return The updated {@link CustomMatcher} object. + */ + public CustomMatcher setQueryOrderingIgnored(boolean queryOrderingIgnored) { + this.queryOrderingIgnored = queryOrderingIgnored; + return this; + } + + /** + * Gets the list of query parameters that should be ignored during matching. + * The parameter values won't be matched, but the presence of these parameters will be taken into account. + * + * @return the ignored query parameters + */ + public List getIgnoredQueryParameters() { + return ignoredQueryParameters; + } + + /** + * Sets the list of query parameters that should be ignored during matching. + * The parameter values won't be matched, but the presence of these parameters will be taken into account. + * + * @param ignoredQueryParameters the ignored query parameters + * @return The updated {@link CustomMatcher} object. + */ + public CustomMatcher setIgnoredQueryParameters(List ignoredQueryParameters) { + this.ignoredQueryParameters = ignoredQueryParameters; + return this; + } + + /** + * Get the comparing bodies boolean. + * True to enable body matching (default behavior), or false to disable body matching. + * + * @return the boolean + */ + public boolean isComparingBodies() { + return comparingBodies; + } + + /** + * Sets true to enable body matching (default behavior), or false to disable body matching. + * + * @param comparingBodies the compare bodies + * @return The updated {@link CustomMatcher} object. + */ + public CustomMatcher setComparingBodies(boolean comparingBodies) { + this.comparingBodies = comparingBodies; + return this; + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/models/HeaderlessMatcher.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/models/HeaderlessMatcher.java new file mode 100644 index 000000000000..bcbcccd1839b --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/models/HeaderlessMatcher.java @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.models; + +/** + * Adjusts the "match" operation to ignore header differences when matching a request + */ +public class HeaderlessMatcher extends TestProxyRequestMatcher { + /** + * Creates an instance of HeaderlessMatcher + */ + public HeaderlessMatcher() { + super(TestProxyRequestMatcherType.HEADERLESS); + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/models/RecordFilePayload.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/models/RecordFilePayload.java new file mode 100644 index 000000000000..fac89df6b3cc --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/models/RecordFilePayload.java @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.models; + +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonSerializable; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.serialization.json.JsonWriter; + +import java.io.IOException; + +/** + * Model type for serializing the record file path passed to the test proxy. + */ +public class RecordFilePayload implements JsonSerializable { + + /** + * The record file path + */ + private final String recordingFile; + + /** + * The asset file path + */ + private final String assetFile; + + /** + * Creates an instance of {@link RecordFilePayload}. + * + * @param recordingFile The partial path to the recording file. + * @param assetFile The path to asset file. + */ + public RecordFilePayload(String recordingFile, String assetFile) { + this.recordingFile = recordingFile; + this.assetFile = assetFile; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject() + .writeStringField("x-recording-file", recordingFile) + .writeStringField("x-recording-assets-file", assetFile) + .writeEndObject(); + } + + /** + * Deserializes an instance of RecordFilePayload from the input JSON. + * + * @param jsonReader The JSON reader to deserialize the data from. + * @return An instance of RecordFilePayload deserialized from the JSON. + * @throws IOException If the JSON reader encounters an error while reading the JSON. + */ + public static RecordFilePayload fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String recordingFile = null; + String assetFile = null; + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("x-recording-file".equals(fieldName)) { + recordingFile = reader.getString(); + } else if ("x-recording-assets-file".equals(fieldName)) { + assetFile = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return new RecordFilePayload(recordingFile, assetFile); + }); + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/models/TestProxyRecordingOptions.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/models/TestProxyRecordingOptions.java new file mode 100644 index 000000000000..29734ebcd559 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/models/TestProxyRecordingOptions.java @@ -0,0 +1,244 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.models; + +import com.azure.v2.core.test.implementation.TestingHelpers; +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonSerializable; +import io.clientcore.core.serialization.json.JsonWriter; + +import java.io.IOException; +import java.util.List; + +/** + * Keeps track of transport layer recording options to send to proxy. + */ +public class TestProxyRecordingOptions implements JsonSerializable { + private boolean autoRedirect = false; + private ProxyTransport proxyTransportOptions; + + /** + * Creates a new instance of TestProxyRecordingOptions. + */ + public TestProxyRecordingOptions() { + } + + /** + * Model for proxy transport options + */ + public static class ProxyTransport implements JsonSerializable { + private List certificates; + private String tLSValidationCert; + + /** + * Creates a new instance of ProxyTransport. + */ + public ProxyTransport() { + } + + /** + * Get allowed certificates for the recording. + * @return the list of allowed certificates for the recording. + */ + public List getCertificates() { + return certificates; + } + + /** + * Set allowed certificates for the recording. + * @param certificates the list of allowed certificates for the recording. + * @return the updated {@link ProxyTransport} object. + */ + public ProxyTransport setCertificates(List certificates) { + this.certificates = certificates; + return this; + } + + /** + * Get the TLS/SSL Certificate + * @return the TLS/SSL Certificate + */ + public String gettLSValidationCert() { + return tLSValidationCert; + } + + /** + * Set the TLS/SSL Certificate + * @param tLSValidationCert the TLS/SSL Certificate to set + * @return the updated {@link ProxyTransport} object. + */ + public ProxyTransport settLSValidationCert(String tLSValidationCert) { + this.tLSValidationCert = tLSValidationCert; + return this; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject() + .writeArrayField("Certificates", certificates, JsonWriter::writeJson) + .writeStringField("TLSValidationCert", tLSValidationCert) + .writeEndObject(); + } + + /** + * Deserializes an instance of ProxyTransport from the input JSON. + * + * @param jsonReader The JSON reader to deserialize the data from. + * @return An instance of ProxyTransport deserialized from the JSON. + * @throws IOException If the JSON reader encounters an error while reading the JSON. + */ + public static ProxyTransport fromJson(JsonReader jsonReader) throws IOException { + return TestingHelpers.readObject(jsonReader, ProxyTransport::new, (proxyTransport, fieldName, reader) -> { + if ("Certificates".equals(fieldName)) { + proxyTransport.certificates = reader.readArray(Certificate::fromJson); + } else if ("TLSValidationCert".equals(fieldName)) { + proxyTransport.tLSValidationCert = reader.getString(); + } else { + reader.skipChildren(); + } + }); + } + } + + /** + * Model representing the certificate item object + */ + public static class Certificate implements JsonSerializable { + private String pemValue; + private String pemKey; + + /** + * Creates a new instance of Certificate. + */ + public Certificate() { + } + + /** + * Get the cert pem value + * @return the cert pem value + */ + public String getPemValue() { + return pemValue; + } + + /** + * Set the cert pem value + * @param pemValue the cert pem value + * @return the {@link Certificate} object + */ + public Certificate setPemValue(String pemValue) { + this.pemValue = pemValue; + return this; + } + + /** + * Get the cert pem key + * @return the cert pem key + */ + public String getPemKey() { + return pemKey; + } + + /** + * Get the cert pem key + * @param pemKey the cert pem key + * @return the {@link Certificate} object + */ + public Certificate setPemKey(String pemKey) { + this.pemKey = pemKey; + return this; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject() + .writeStringField("PemValue", pemValue) + .writeStringField("PemKey", pemKey) + .writeEndObject(); + } + + /** + * Deserializes an instance of Certificate from the input JSON. + * + * @param jsonReader The JSON reader to deserialize the data from. + * @return An instance of Certificate deserialized from the JSON. + * @throws IOException If the JSON reader encounters an error while reading the JSON. + */ + public static Certificate fromJson(JsonReader jsonReader) throws IOException { + return TestingHelpers.readObject(jsonReader, Certificate::new, (certificate, fieldName, reader) -> { + if ("PemValue".equals(fieldName)) { + certificate.pemValue = reader.getString(); + } else if ("PemKey".equals(fieldName)) { + certificate.pemKey = reader.getString(); + } else { + reader.skipChildren(); + } + }); + } + } + + /** + * Get if auto redirecting is allowed. Default value is set to true. + * @return the boolean value indicating if auto redirect is allowed. + */ + public boolean isAutoRedirect() { + return autoRedirect; + } + + /** + * Set the boolean value indicating if auto redirect is allowed. + * @param autoRedirect the boolean value indicating if auto redirect is allowed. + * @return the {@link TestProxyRecordingOptions} object. + */ + public TestProxyRecordingOptions setAutoRedirect(boolean autoRedirect) { + this.autoRedirect = autoRedirect; + return this; + } + + /** + * Get test proxy transport options for recording. + * @return the {@link ProxyTransport} options. + */ + public ProxyTransport getTransportOptions() { + return proxyTransportOptions; + } + + /** + * Set test proxy transport options for recording. + * @param proxyTransportOptions the test proxy transport options for recording + * @return the {@link ProxyTransport} options. + */ + public TestProxyRecordingOptions setTransportOptions(ProxyTransport proxyTransportOptions) { + this.proxyTransportOptions = proxyTransportOptions; + return this; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject() + .writeBooleanField("HandleRedirects", autoRedirect) + .writeJsonField("Transport", proxyTransportOptions) + .writeEndObject(); + } + + /** + * Deserializes an instance of TestProxyRecordingOptions from the input JSON. + * + * @param jsonReader The JSON reader to deserialize the data from. + * @return An instance of TestProxyRecordingOptions deserialized from the JSON. + * @throws IOException If the JSON reader encounters an error while reading the JSON. + */ + public static TestProxyRecordingOptions fromJson(JsonReader jsonReader) throws IOException { + return TestingHelpers.readObject(jsonReader, TestProxyRecordingOptions::new, + (testProxyRecordingOptions, fieldName, reader) -> { + if ("HandleRedirects".equals(fieldName)) { + testProxyRecordingOptions.autoRedirect = reader.getBoolean(); + } else if ("Transport".equals(fieldName)) { + testProxyRecordingOptions.proxyTransportOptions = ProxyTransport.fromJson(reader); + } else { + reader.skipChildren(); + } + }); + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/models/TestProxyRequestMatcher.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/models/TestProxyRequestMatcher.java new file mode 100644 index 000000000000..d94b353dc77b --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/models/TestProxyRequestMatcher.java @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.models; + +/** + * A matcher is applied during a playback session. The default matcher matches a request on headers, URI, and the body + * on playback recorded data. + */ +public class TestProxyRequestMatcher { + private final TestProxyRequestMatcherType testProxyMatcherType; + + /** + * Creates an instance of TestProxyMatcher + * @param testProxyMatcherType the type of matcher + */ + public TestProxyRequestMatcher(TestProxyRequestMatcherType testProxyMatcherType) { + this.testProxyMatcherType = testProxyMatcherType; + } + + /** + * Get the type of proxy matcher + * @return the type of proxy matcher + */ + public TestProxyRequestMatcherType getType() { + return testProxyMatcherType; + } + + /** + * The possible types for Matcher. + */ + public enum TestProxyRequestMatcherType { + + /** + * Adjusts the "match" operation to EXCLUDE the body when matching a request to a recording's entries + */ + BODILESS("BodilessMatcher"), + + /** + * Exposes the default matcher to be customized, using setting properties of compareBodies, excludedHeaders, ignoredHeaders, ignoreQueryOrdering, ignoredQueryParameters + */ + CUSTOM("CustomDefaultMatcher"), + + /** + * Adjusts the "match" operation to ignore header differences when matching a request + */ + HEADERLESS("HeaderlessMatcher"); + + private final String name; + + TestProxyRequestMatcherType(String name) { + this.name = name; + } + + /** + * Gets the name value of the enum. + * @return the name value of the enum. + */ + public String getName() { + return name; + } + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/models/TestProxySanitizer.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/models/TestProxySanitizer.java new file mode 100644 index 000000000000..1702f4ea8025 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/models/TestProxySanitizer.java @@ -0,0 +1,95 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.models; + +/** + * Keeps track of different sanitizers that redact the sensitive information when recording + */ +public class TestProxySanitizer { + private final TestProxySanitizerType testProxySanitizerType; + private final String regex; + private final String redactedValue; + private final String key; + private String groupForReplace; + + /** + * Creates an instance of TestProxySanitizer with regex + * @param regex the regex to apply for redaction + * @param redactedValue the replacement text for the regex matched content + * @param testProxySanitizerType the type of sanitizer + */ + public TestProxySanitizer(String regex, String redactedValue, TestProxySanitizerType testProxySanitizerType) { + this.testProxySanitizerType = testProxySanitizerType; + this.regex = regex; + this.redactedValue = redactedValue; + this.key = null; + } + + /** + * Creates an instance of TestProxySanitizer for a key with specified regex pattern + * + * @param key the body json key ("$..apiKey", "$..resourceId") or header key("Location") to apply regex to + * @param regex the regex to apply for redaction + * @param redactedValue the replacement text for the regex matched content + * @param testProxySanitizerType the type of sanitizer + */ + public TestProxySanitizer(String key, String regex, String redactedValue, + TestProxySanitizerType testProxySanitizerType) { + this.testProxySanitizerType = testProxySanitizerType; + this.key = key; + this.regex = regex; + this.redactedValue = redactedValue; + } + + /** + * Get the type of proxy sanitizer + * @return the type of proxy sanitizer + */ + public TestProxySanitizerType getType() { + return testProxySanitizerType; + } + + /** + * Get the regex to apply for redaction + * @return the regex to apply for redaction + */ + public String getRegex() { + return regex; + } + + /** + * Get the replacement for regex matched content + * @return the replacement for regex matched content + */ + public String getRedactedValue() { + return redactedValue; + } + + /** + * Get the group for replace + * @return the group for replace. + */ + public String getGroupForReplace() { + return groupForReplace; + } + + /** + * Set the group for replace. + * + * @param groupForReplace The name of the group to replace. + * @return the {@link TestProxySanitizer} itself. + */ + public TestProxySanitizer setGroupForReplace(String groupForReplace) { + this.groupForReplace = groupForReplace; + return this; + } + + /** + * Get the header or body json key that is being redacted. + * @return the header or body json key being redacted. + */ + public String getKey() { + return key; + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/models/TestProxySanitizerType.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/models/TestProxySanitizerType.java new file mode 100644 index 000000000000..d37876126388 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/models/TestProxySanitizerType.java @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.v2.core.test.models; + +/** + * The possible record sanitizer types. + * Each sanitizer is optionally prefaced with the specific part of the request/response pair that it applies to. + */ +public enum TestProxySanitizerType { + /** + * Sanitize the request URI. + */ + URI("UriRegexSanitizer"), + /** + * Sanitize the response body. + */ + BODY_KEY("BodyKeySanitizer"), + /** + * Sanitize the response body. + */ + BODY_REGEX("BodyRegexSanitizer"), + /** + * Sanitize the request/response headers. + */ + HEADER("HeaderRegexSanitizer"); + + private final String name; + + TestProxySanitizerType(String name) { + this.name = name; + } + + /** + * Gets the name value of the enum. + * @return the name value of the enum. + */ + public String getName() { + return name; + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/models/package-info.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/models/package-info.java new file mode 100644 index 000000000000..29d0571aba98 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/models/package-info.java @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * Package containing models used to test Azure client libraries. + */ +package com.azure.v2.core.test.models; diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/package-info.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/package-info.java new file mode 100644 index 000000000000..68d38a516726 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/package-info.java @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * Package containing common test classes for Azure client libraries. + */ +package com.azure.v2.core.test; diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/policy/TestProxyRecordPolicy.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/policy/TestProxyRecordPolicy.java new file mode 100644 index 000000000000..d56c95811585 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/policy/TestProxyRecordPolicy.java @@ -0,0 +1,248 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.policy; + +import com.azure.v2.core.test.models.RecordFilePayload; +import com.azure.v2.core.test.models.TestProxyRecordingOptions; +import com.azure.v2.core.test.models.TestProxySanitizer; +import com.azure.v2.core.test.utils.HttpUrlConnectionHttpClient; +import com.azure.v2.core.test.utils.TestProxyUtils; +import io.clientcore.core.http.client.HttpClient; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpMethod; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.http.pipeline.HttpPipelineNextPolicy; +import io.clientcore.core.http.pipeline.HttpPipelinePolicy; +import io.clientcore.core.http.pipeline.HttpPipelinePosition; +import io.clientcore.core.serialization.json.JsonWriter; +import io.clientcore.core.models.binarydata.BinaryData; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Queue; + +import static com.azure.v2.core.test.utils.TestProxyUtils.checkForTestProxyErrors; +import static com.azure.v2.core.test.utils.TestProxyUtils.createAddSanitizersRequest; +import static com.azure.v2.core.test.utils.TestProxyUtils.getAssetJsonFile; +import static com.azure.v2.core.test.utils.TestProxyUtils.getRemoveSanitizerRequest; +import static com.azure.v2.core.test.utils.TestProxyUtils.loadSanitizers; + +/** + * A {@link HttpPipelinePolicy} for redirecting traffic through the test proxy for recording. + */ +public class TestProxyRecordPolicy implements HttpPipelinePolicy { + private static final HttpHeaderName X_RECORDING_ID = HttpHeaderName.fromString("x-recording-id"); + private final HttpClient client; + private final URI proxyUri; + private final boolean skipRecordingRequestBody; + private String xRecordingId; + private final List sanitizers = new ArrayList<>(); + private static final List DEFAULT_SANITIZERS = loadSanitizers(); + + /** + * The mode to use when recording. + */ + public static final String RECORD_MODE = "record"; + + /** + * Create an instance of {@link TestProxyRecordPolicy} with a list of custom sanitizers. + * + * @param httpClient The {@link HttpClient} to use. If none is passed {@link HttpUrlConnectionHttpClient} is the default. + * @param skipRecordingRequestBody Flag indicating to skip recording request bodies when tests run in Record mode. + */ + public TestProxyRecordPolicy(HttpClient httpClient, boolean skipRecordingRequestBody) { + this.client = (httpClient == null ? new HttpUrlConnectionHttpClient() : httpClient); + this.skipRecordingRequestBody = skipRecordingRequestBody; + this.proxyUri = TestProxyUtils.getProxyUri(); + this.sanitizers.addAll(DEFAULT_SANITIZERS); + } + + /** + * Starts a recording of test traffic. + * + * @param recordFile The name of the file to save the recording to. + * @param testClassPath the test class path + * @throws RuntimeException Failed to serialize body payload. + */ + public void startRecording(File recordFile, Path testClassPath) { + try { + String assetJsonPath = getAssetJsonFile(recordFile, testClassPath); + HttpRequest request = new HttpRequest().setMethod(HttpMethod.POST) + .setUri(proxyUri + "/record/start") + .setBody(BinaryData.fromObject(new RecordFilePayload(recordFile.toString(), assetJsonPath))); + request.getHeaders().set(HttpHeaderName.CONTENT_TYPE, "application/json"); + + try (Response response = client.send(request)) { + checkForTestProxyErrors(response); + if (response.getStatusCode() != 200) { + throw new RuntimeException(response.getValue().toString()); + } + + this.xRecordingId = response.getHeaders().getValue(X_RECORDING_ID); + } + + addProxySanitization(this.sanitizers); + setDefaultRecordingOptions(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private void setDefaultRecordingOptions() throws IOException { + HttpRequest request = new HttpRequest().setMethod(HttpMethod.POST) + .setUri(proxyUri + "/Admin/SetRecordingOptions") + .setBody(BinaryData.fromString("{\"HandleRedirects\": false}")); + request.getHeaders().set(HttpHeaderName.CONTENT_TYPE, "application/json"); + client.send(request).close(); + } + + /** + * Stops recording of test traffic. + * @param variables A list of random variables generated during the test which is saved in the recording. + * @throws RuntimeException If the test proxy returns an error while stopping recording. + * @throws IOException If an error occurs while sending the request. + */ + public void stopRecording(Queue variables) throws IOException { + HttpRequest request = new HttpRequest().setMethod(HttpMethod.POST) + .setUri(proxyUri + "/record/stop") + .setBody(serializeVariables(variables)); + request.getHeaders().set(HttpHeaderName.CONTENT_TYPE, "application/json").set(X_RECORDING_ID, xRecordingId); + + try (Response response = client.send(request)) { + checkForTestProxyErrors(response); + if (response.getStatusCode() != 200) { + throw new RuntimeException(response.getValue().toString()); + } + } + } + + /** + * Transform the {@link Queue} containing variables into a JSON map for sending to the test proxy. + * @param variables The variables to send. + * @return A BinaryData containing the JSON map (or an empty map.) + */ + private BinaryData serializeVariables(Queue variables) { + if (variables.isEmpty()) { + return BinaryData.fromString("{}"); + } + + StringBuilder builder = new StringBuilder().append('{'); + + int count = 0; + for (String variable : variables) { + if (count > 0) { + builder.append(','); + } + + builder.append('"').append(count).append("\":\""); + count++; + + if (variable == null) { + builder.append("null"); + } else { + builder.append(variable).append('"'); + } + } + + return BinaryData.fromString(builder.append('}').toString()); + } + + /** + * Method is invoked before the request is sent. + * + * @param request The request. + */ + private void beforeSendingRequest(HttpRequest request) { + TestProxyUtils.changeHeaders(request, proxyUri, xRecordingId, RECORD_MODE, skipRecordingRequestBody); + } + + /** + * Method is invoked after the response is received. + * + * @param response The response received. + * @return The transformed response. + */ + private Response afterReceivedResponse(Response response) { + TestProxyUtils.checkForTestProxyErrors(response); + return TestProxyUtils.resetTestProxyData(response); + } + + @Override + public Response process(HttpRequest request, HttpPipelineNextPolicy next) { + beforeSendingRequest(request); + return afterReceivedResponse(next.process()); + } + + /** + * Add a list of {@link TestProxySanitizer} to the current recording session. + * @param sanitizers The sanitizers to add. + * @throws IOException If an error occurs while sending the request. + */ + public void addProxySanitization(List sanitizers) throws IOException { + if (isRecording()) { + HttpRequest request = createAddSanitizersRequest(sanitizers, proxyUri); + request.getHeaders().set(X_RECORDING_ID, xRecordingId); + + client.send(request).close(); + } else { + this.sanitizers.addAll(sanitizers); + } + } + + private boolean isRecording() { + return xRecordingId != null; + } + + /** + * Removes the list of sanitizers from the current playback session. + * @param sanitizers The sanitizers to remove. + * @throws IOException If an error occurs while sending the request. + */ + public void removeProxySanitization(List sanitizers) throws IOException { + if (isRecording()) { + Map> data = new HashMap<>(); + data.put("Sanitizers", sanitizers); + + HttpRequest request; + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + JsonWriter jsonWriter = JsonWriter.toStream(outputStream)) { + jsonWriter.writeMap(data, (writer, value) -> writer.writeArray(value, JsonWriter::writeString)).flush(); + request = getRemoveSanitizerRequest().setBody(BinaryData.fromBytes(outputStream.toByteArray())); + request.getHeaders().set(X_RECORDING_ID, xRecordingId); + } + + client.send(request).close(); + } + } + + /** + * Set transport layer test proxy recording options + * @param testProxyRecordingOptions the transport layer test proxy recording options to set + * @throws IllegalArgumentException if testProxyRecordingOptions cannot be serialized + */ + public void setRecordingOptions(TestProxyRecordingOptions testProxyRecordingOptions) { + try { + HttpRequest request = new HttpRequest().setMethod(HttpMethod.POST) + .setUri(proxyUri + "/admin/setrecordingoptions") + .setBody(BinaryData.fromObject(testProxyRecordingOptions)); + request.getHeaders().set(HttpHeaderName.CONTENT_TYPE, "application/json"); + client.send(request).close(); + } catch (IOException ex) { + throw new IllegalArgumentException("Failed to process JSON input", ex); + } + } + + @Override + public HttpPipelinePosition getPipelinePosition() { + return HttpPipelinePosition.AFTER_INSTRUMENTATION; + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/policy/package-info.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/policy/package-info.java new file mode 100644 index 000000000000..084cf733a116 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/policy/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * Package containing {@link io.clientcore.core.http.pipeline.HttpPipelinePolicy HttpPipelinePolicies} used to test + * Azure client libraries. + */ +package com.azure.v2.core.test.policy; diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/HttpUrlConnectionHttpClient.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/HttpUrlConnectionHttpClient.java new file mode 100644 index 000000000000..3aec6abb001e --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/HttpUrlConnectionHttpClient.java @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.utils; + +import io.clientcore.core.http.client.HttpClient; +import io.clientcore.core.http.models.HttpHeader; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpHeaders; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.models.binarydata.ByteArrayBinaryData; +import io.clientcore.core.utils.ProgressReporter; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.net.HttpURLConnection; + +/** + * A {@link HttpClient} that uses the JDK {@link HttpURLConnection}. + */ +public class HttpUrlConnectionHttpClient implements HttpClient { + /** + * Creates an instance of {@link HttpUrlConnectionHttpClient}. + */ + public HttpUrlConnectionHttpClient() { + } + + @Override + public Response send(HttpRequest request) throws IOException { + HttpURLConnection connection = null; + try { + connection = (HttpURLConnection) request.getUri().toURL().openConnection(); + createConnection(connection, request); + + return createHttpResponse(connection, request); + } catch (IOException e) { + throw new UncheckedIOException(e); + } finally { + if (connection != null) { + connection.disconnect(); + } + } + } + + private void createConnection(HttpURLConnection connection, HttpRequest request) throws IOException { + connection.setRequestMethod(request.getHttpMethod().name()); + setHeadersOnRequest(request, connection); + setBodyOnRequest(request, connection, null); + connection.setInstanceFollowRedirects(false); + connection.connect(); + } + + private Response createHttpResponse(HttpURLConnection connection, HttpRequest request) { + + if (connection == null) { + return null; + } + + return new HttpURLResponse(connection, request); + } + + private static void setBodyOnRequest(HttpRequest request, HttpURLConnection connection, + ProgressReporter progressReporter) { + try { + BinaryData body = request.getBody(); + if (body != null) { + connection.setDoOutput(true); + try (BufferedOutputStream stream = new BufferedOutputStream(connection.getOutputStream())) { + byte[] bodyBytes = body.toBytes(); + if (progressReporter != null) { + progressReporter.reportProgress(bodyBytes.length); + } + stream.write(bodyBytes); + stream.flush(); + } + } + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private static void setHeadersOnRequest(HttpRequest request, HttpURLConnection connection) { + HttpHeaders headers = request.getHeaders(); + if (headers != null) { + headers.stream().forEach(header -> { + String name = header.getName().getCaseSensitiveName(); + + header.getValues().forEach(value -> connection.addRequestProperty(name, value)); + }); + } + } + + private static class HttpURLResponse extends Response { + private final HttpURLConnection connection; + + /** + * Constructor for HttpURLResponse + * + * @param connection The {@link HttpURLConnection} to create a {@link Response} from. + * @param request The {@link HttpRequest} that resulted in this {@link Response}. + */ + HttpURLResponse(HttpURLConnection connection, HttpRequest request) { + super(request, getResponseCode(connection), createHttpHeaders(connection), getResponseBody(connection)); + this.connection = connection; + } + + private static int getResponseCode(HttpURLConnection connection) { + try { + return connection.getResponseCode(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private static HttpHeaders createHttpHeaders(HttpURLConnection connection) { + HttpHeaders headers = new HttpHeaders(); + connection.getHeaderFields().forEach((key, value) -> { + if (key == null) { + return; + } + headers.add(new HttpHeader(HttpHeaderName.fromString(key), value)); + }); + return headers; + } + + private static BinaryData getResponseBody(HttpURLConnection connection) { + try { + if (connection.getResponseCode() >= 100 && connection.getResponseCode() < 400) { + InputStream inputStream = connection.getInputStream(); + return new ByteArrayBinaryData(readResponseBytes(inputStream)); + } else { + InputStream inputStream = connection.getErrorStream(); + return new ByteArrayBinaryData(readResponseBytes(inputStream)); + } + } catch (IOException e) { + // Handle connection exception and retrieve error information + int responseCode = -1; + String responseMessage = "Unknown error"; + try { + responseCode = connection.getResponseCode(); + responseMessage = connection.getResponseMessage(); + } catch (IOException ignored) { + + } + + throw new UncheckedIOException( + String.format("Connection failed: %s, %s", responseCode, responseMessage), e); + } + } + + private static byte[] readResponseBytes(InputStream inputStream) throws IOException { + BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + byte[] buffer = new byte[8192]; + int bytesRead; + while ((bytesRead = bufferedInputStream.read(buffer)) != -1) { + byteArrayOutputStream.write(buffer, 0, bytesRead); + } + bufferedInputStream.close(); + byteArrayOutputStream.close(); + return byteArrayOutputStream.toByteArray(); + } + + @Override + public void close() { + connection.disconnect(); + } + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/MockTokenCredential.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/MockTokenCredential.java new file mode 100644 index 000000000000..ff271324d538 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/MockTokenCredential.java @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.utils; + +import io.clientcore.core.credentials.oauth.AccessToken; +import io.clientcore.core.credentials.oauth.OAuthTokenCredential; +import io.clientcore.core.credentials.oauth.OAuthTokenRequestContext; + +import java.time.OffsetDateTime; + +/** + * This class mocks the behavior of {@code TokenCredential} without making a network call + * with dummy credentials. + */ +public class MockTokenCredential implements OAuthTokenCredential { + + /** + * Creates an instance of {@link MockTokenCredential}. + */ + public MockTokenCredential() { + } + + @Override + public AccessToken getToken(OAuthTokenRequestContext request) { + return new AccessToken("mockToken", OffsetDateTime.now().plusHours(2)); + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/ResourceNamer.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/ResourceNamer.java new file mode 100644 index 000000000000..0ac516b7c45e --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/ResourceNamer.java @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.utils; + +import io.clientcore.core.utils.CoreUtils; + +import java.util.Locale; +import java.util.concurrent.ThreadLocalRandom; + +/** + * A random string generator used in tests. + */ +public class ResourceNamer { + private static final Locale LOCALE = Locale.US; + + private final String randName; + + /** + * Creates a ResourceNameGenerator that prefixes its strings with the name. + * + * @param name The prefix for generated strings. + */ + public ResourceNamer(String name) { + this.randName = name.toLowerCase(LOCALE) + + CoreUtils.randomUuid().toString().replace("-", "").substring(0, 3).toLowerCase(LOCALE); + } + + /** + * Gets a random name. + * + * @param prefix the prefix to be used if possible + * @param maxLen the max length for the random generated name + * @return the random name + */ + public String randomName(String prefix, int maxLen) { + prefix = prefix.toLowerCase(LOCALE); + int minRandomnessLength = 5; + if (maxLen <= minRandomnessLength) { + return randomString(maxLen); + } + + if (maxLen < prefix.length() + minRandomnessLength) { + return randomString(maxLen); + } + + String minRandomString + = String.format(LOCALE, "%05d", Math.abs(ThreadLocalRandom.current().nextInt() % 100000)); + + if (maxLen <= prefix.length() + randName.length() + minRandomnessLength) { + String str = prefix + minRandomString; + return str + randomString((maxLen - str.length()) / 2); + } + + String str = prefix + randName + minRandomString; + return str + randomString((maxLen - str.length()) / 2); + } + + /** + * Creates a random UUID. + * @return the UUID string. + */ + public String randomUuid() { + return CoreUtils.randomUuid().toString(); + } + + private String randomString(int length) { + StringBuilder str = new StringBuilder(); + while (str.length() < length) { + str.append(CoreUtils.randomUuid() + .toString() + .replace("-", "") + .substring(0, Math.min(32, length)) + .toLowerCase(LOCALE)); + } + return str.toString(); + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/TestConfigurationSource.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/TestConfigurationSource.java new file mode 100644 index 000000000000..a57653ce3c53 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/TestConfigurationSource.java @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.utils; + +import io.clientcore.core.utils.configuration.ConfigurationSource; + +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +/** + * Test configuration source implementation. + */ +public class TestConfigurationSource implements ConfigurationSource { + private final Map testData; + + /** + * Creates an instance of {@link TestConfigurationSource}. + */ + public TestConfigurationSource() { + this.testData = new HashMap<>(); + } + + /** + * Adds a key-value pair to the test configuration source. + * + * @param key The key to add. + * @param value The value to add. + * @return The current instance of {@link TestConfigurationSource}. + */ + public TestConfigurationSource put(String key, String value) { + this.testData.put(key, value); + return this; + } + + @Override + public String getProperty(String name) { + Objects.requireNonNull(name, "'name' cannot be null."); + return testData.get(name); + } + + @Override + public boolean isMutable() { + return true; + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/TestProxyDownloader.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/TestProxyDownloader.java new file mode 100644 index 000000000000..0988b14d7d6a --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/TestProxyDownloader.java @@ -0,0 +1,214 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.utils; + +import com.azure.v2.core.test.implementation.TestingHelpers; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.utils.UriBuilder; +import org.apache.tools.tar.TarEntry; +import org.apache.tools.tar.TarInputStream; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.util.Collections; +import java.util.Comparator; +import java.util.Locale; +import java.util.concurrent.Callable; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.zip.GZIPInputStream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +/** + * Class for managing downloads of the test proxy + */ +public final class TestProxyDownloader { + private static final ClientLogger LOGGER = new ClientLogger(TestProxyDownloader.class); + private static final Path PROXY_PATH = Paths.get(System.getProperty("java.io.tmpdir"), "test-proxy"); + + private static String testProxyTag; + + private TestProxyDownloader() { + } + + /** + * Reports the directory the test proxy was installed to. + * @return A {@link Path} with the test proxy location. + */ + public static Path getProxyDirectory() { + return PROXY_PATH; + } + + /** + * Requests that the test proxy be downloaded and unpacked. If it is already present this is a no-op. + * @param testClassPath the test class path + */ + public static void installTestProxy(Path testClassPath) { + testProxyTag = TestProxyUtils.getTestProxyVersion(testClassPath); + if (!checkDownloadedVersion()) { + PlatformInfo platformInfo = new PlatformInfo(); + downloadProxy(platformInfo); + extractTestProxy(platformInfo); + } + } + + private static void extractTestProxy(PlatformInfo platformInfo) { + Path zipFile = getZipFileLocation(platformInfo.getExtension()); + try { + if (Files.exists(PROXY_PATH)) { + Files.walk(PROXY_PATH).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete); + } + + if (platformInfo.extension.equals("tar.gz")) { + try (TarInputStream tar = new TarInputStream(new GZIPInputStream(Files.newInputStream(zipFile)))) { + decompress(tar::getNextEntry, TestProxyDownloader::getTarOutputFile, TarEntry::isDirectory, tar); + } + } else { + try (ZipInputStream zip = new ZipInputStream(new BufferedInputStream(Files.newInputStream(zipFile)))) { + decompress(zip::getNextEntry, TestProxyDownloader::getZipOutputFile, ZipEntry::isDirectory, zip); + } + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private static void decompress(Callable entryGetter, Function outputFileFunc, + Predicate isDirectory, InputStream archive) throws Exception { + T entry = entryGetter.call(); + + while (entry != null) { + File outputFile = outputFileFunc.apply(entry); + if (isDirectory.test(entry)) { + if (!outputFile.isDirectory() && !outputFile.mkdirs()) { + throw new RuntimeException("Could not create all required directories"); + } + } else { + File parent = outputFile.getParentFile(); + if (!parent.isDirectory() && !parent.mkdirs()) { + throw new RuntimeException("Could not create all required directories"); + } + try (OutputStream outputStream = Files.newOutputStream(outputFile.toPath())) { + TestingHelpers.copy(archive, outputStream); + if (outputFile.getName().equals(TestProxyUtils.getProxyProcessName())) { + outputFile.setExecutable(true, false); + } + } + } + entry = entryGetter.call(); + } + } + + private static File getZipOutputFile(ZipEntry entry) { + return new File(PROXY_PATH.toFile(), entry.getName()); + } + + private static File getTarOutputFile(TarEntry entry) { + return new File(PROXY_PATH.toFile(), entry.getName()); + } + + private static void downloadProxy(PlatformInfo platformInfo) { + LOGGER.atInfo().log("Downloading test proxy. This may take a few moments."); + + try { + URL url = UriBuilder.parse(getProxyDownloadUrl(platformInfo)).toUri().toURL(); + Files.copy(url.openStream(), getZipFileLocation(platformInfo.getExtension()), + StandardCopyOption.REPLACE_EXISTING); + } catch (IOException | URISyntaxException e) { + throw new RuntimeException("Could not save test proxy download", e); + } + + updateDownloadedFileVersion(); + } + + private static Path getZipFileLocation(String extension) { + return Paths.get(System.getProperty("java.io.tmpdir"), String.format("testproxy.%s", extension)); + } + + private static void updateDownloadedFileVersion() { + Path filePath = getFileVersionPath(); + try { + Files.write(filePath, Collections.singletonList(testProxyTag)); + } catch (IOException e) { + throw new RuntimeException("Failed to write version data to file", e); + } + } + + private static boolean checkDownloadedVersion() { + Path filePath = getFileVersionPath(); + if (!Files.exists(filePath)) { + return false; + } + String fileVersion; + try { + fileVersion = Files.readAllLines(filePath).get(0); + } catch (IOException e) { + throw new RuntimeException("Failed to read version data from file", e); + } + return fileVersion.equals(testProxyTag); + } + + private static Path getFileVersionPath() { + return Paths.get(System.getProperty("java.io.tmpdir"), "test-proxy-version.txt"); + } + + private static String getProxyDownloadUrl(PlatformInfo platformInfo) { + return String.format( + "https://github.com/Azure/azure-sdk-tools/releases/download/Azure.Sdk.Tools.TestProxy_%s/test-proxy-standalone-%s-%s.%s", + testProxyTag, platformInfo.getPlatform(), platformInfo.getArchitecture(), platformInfo.getExtension()); + } + + private static class PlatformInfo { + private final String platform; + private final String extension; + private final String architecture; + + PlatformInfo() { + String osName = System.getProperty("os.name").toLowerCase(Locale.ROOT); + if (osName.contains("windows")) { + platform = "win"; + extension = "zip"; + } else if (osName.contains("linux")) { + platform = "linux"; + extension = "tar.gz"; + } else if (osName.contains("mac os x")) { + platform = "osx"; + extension = "zip"; + } else { + throw new RuntimeException("unexpected osName " + osName); + } + String arch = System.getProperty("os.arch").toLowerCase(Locale.ROOT); + // intel Macs are x86_64. + if (arch.contains("amd64") || arch.contains("x86_64")) { + architecture = "x64"; + } else if (arch.contains("arm64") || arch.contains("aarch64")) { + architecture = "arm64"; + } else { + throw new RuntimeException("Unsupported platform " + arch); + } + } + + public String getPlatform() { + return platform; + } + + public String getArchitecture() { + return architecture; + } + + public String getExtension() { + return extension; + } + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/TestProxyManager.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/TestProxyManager.java new file mode 100644 index 000000000000..f14992c7c84e --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/TestProxyManager.java @@ -0,0 +1,146 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.utils; + +import io.clientcore.core.http.models.HttpMethod; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.utils.CoreUtils; +import io.clientcore.core.utils.configuration.Configuration; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.time.Duration; +import java.util.Map; + +/** + * Manages running the test recording proxy server + */ +public final class TestProxyManager { + private static final ClientLogger LOGGER = new ClientLogger(TestProxyManager.class); + private static Process proxy; + private static final Path WORKING_DIRECTORY = Paths.get(System.getProperty("user.dir")); + + static { + Runtime.getRuntime().addShutdownHook(new Thread(TestProxyManager::stopProxy)); + if (runningLocally()) { + TestProxyDownloader.installTestProxy(WORKING_DIRECTORY); + } + } + + @Deprecated + private TestProxyManager() { + } + + /** + * Start an instance of the test proxy. + * @throws UncheckedIOException There was an issue communicating with the proxy. + * @throws RuntimeException There was an issue starting the proxy process. + */ + public static synchronized void startProxy() { + try { + // if we're not running in CI we will check to see if someone has started the proxy, and start one if not. + if (runningLocally() && !checkAlive(1, Duration.ofSeconds(1), null)) { + String commandLine = Paths + .get(TestProxyDownloader.getProxyDirectory().toString(), TestProxyUtils.getProxyProcessName()) + .toString(); + + Path repoRoot = TestUtils.getRepoRootResolveUntil(WORKING_DIRECTORY, "eng"); + + // Resolve the path to the repo root 'target' folder and create the folder if it doesn't exist. + // This folder will be used to store the 'test-proxy.log' file to enable simpler debugging of Test Proxy + // locally. This is similar to what CI does, but CI uses a PowerShell process to run the Test Proxy + // where running locally uses a Java ProcessBuilder. + Path repoRootTarget = repoRoot.resolve("target"); + if (!Files.exists(repoRootTarget)) { + Files.createDirectory(repoRootTarget); + } + + ProcessBuilder builder = new ProcessBuilder(commandLine, "--storage-location", repoRoot.toString()) + .redirectOutput(repoRootTarget.resolve("test-proxy.log").toFile()) + .redirectError(repoRootTarget.resolve("test-proxy-error.log").toFile()); + Map environment = builder.environment(); + environment.put("LOGGING__LOGLEVEL", "Debug"); + environment.put("LOGGING__LOGLEVEL__MICROSOFT", "Debug"); + environment.put("LOGGING__LOGLEVEL__DEFAULT", "Debug"); + proxy = builder.start(); + } + // in either case the proxy should now be started, so let's wait to make sure. + if (checkAlive(10, Duration.ofSeconds(6), proxy)) { + return; + } + + // If the Test Proxy process doesn't start within the timeout period read the error stream of the Process + // for any additional details that could help determine why the Test Proxy process didn't start. + // Include this additional information in the exception message. + ByteArrayOutputStream errorLog = new ByteArrayOutputStream(); + byte[] buffer = new byte[4096]; + int read; + while ((read = proxy.getErrorStream().read(buffer)) != -1) { + errorLog.write(buffer, 0, read); + } + + String errorLogString = new String(errorLog.toByteArray(), StandardCharsets.UTF_8); + if (CoreUtils.isNullOrEmpty(errorLogString)) { + throw new RuntimeException("Test proxy did not initialize."); + } else { + throw new RuntimeException("Test proxy did not initialize. Error log: " + errorLogString); + } + } catch (IOException e) { + throw LOGGER.logThrowableAsError(new UncheckedIOException(e)); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + + private static boolean checkAlive(int loops, Duration waitTime, Process proxy) throws InterruptedException { + HttpUrlConnectionHttpClient client = new HttpUrlConnectionHttpClient(); + HttpRequest request = new HttpRequest().setMethod(HttpMethod.GET) + .setUri(String.format("%s/admin/isalive", TestProxyUtils.getProxyUri())); + for (int i = 0; i < loops; i++) { + // If the proxy isn't alive and the exit value isn't 0, then the proxy process has exited with an error + // and stop waiting. + if (proxy != null && !proxy.isAlive() && proxy.exitValue() != 0) { + return false; + } + + try { + Response response = client.send(request); + if (response != null && response.getStatusCode() == 200) { + return true; + } + TestProxyUtils.checkForTestProxyErrors(response); + } catch (Exception ignored) { + } + + Thread.sleep(waitTime.toMillis()); + } + return false; + } + + /** + * Stop the running instance of the test proxy. + */ + private static void stopProxy() { + if (proxy != null && proxy.isAlive()) { + proxy.destroy(); + } + } + + /** + * Checks the environment variables commonly set in CI to determine if the run is local. + * @return True if the run is local. + */ + private static boolean runningLocally() { + return Configuration.getGlobalConfiguration().get("TF_BUILD") == null + && Configuration.getGlobalConfiguration().get("CI") == null; + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/TestProxyUtils.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/TestProxyUtils.java new file mode 100644 index 000000000000..a02a7b57c65d --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/TestProxyUtils.java @@ -0,0 +1,555 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.utils; + +import com.azure.v2.core.test.models.CustomMatcher; +import com.azure.v2.core.test.models.TestProxyRequestMatcher; +import com.azure.v2.core.test.models.TestProxySanitizer; +import com.azure.v2.core.test.models.TestProxySanitizerType; +import io.clientcore.core.http.models.HttpHeader; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpHeaders; +import io.clientcore.core.http.models.HttpMethod; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.models.binarydata.StringBinaryData; +import io.clientcore.core.utils.CoreUtils; +import io.clientcore.core.utils.UriBuilder; + +import java.io.File; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Locale; +import java.util.stream.Collectors; + +import static com.azure.v2.core.test.implementation.TestingHelpers.X_RECORDING_ID; +import static com.azure.v2.core.test.models.TestProxySanitizerType.HEADER; +import static com.azure.v2.core.test.policy.TestProxyRecordPolicy.RECORD_MODE; + +/** + * Utility functions for interaction with the test proxy. + */ +public final class TestProxyUtils { + private static final ClientLogger LOGGER = new ClientLogger(TestProxyUtils.class); + private static final HttpHeaderName X_RECORDING_SKIP = HttpHeaderName.fromString("x-recording-skip"); + private static final String REDACTED_VALUE = "REDACTED"; + private static final String URI_REGEX = "(?<=http://|https://)([^/?]+)"; + + // These are prepended with "$.." creating a Jsonpath expression. + private static final List JSON_BODY_KEYS_TO_REDACT = Arrays.asList("authHeader", "accountKey", + "accessToken", "accountName", "applicationId", "apiKey", "client_secret", "connectionString", "url", "host", + "password", "userName", "applicationSecret", "aliasSecondaryConnectionString", "aliasPrimaryConnectionString", + "primaryKey", "secondaryKey", "adminPassword.value", "administratorLoginPassword", "runAsPassword", + "adminPassword", "accessSAS", "WEBSITE_AUTH_ENCRYPTION_KEY", "decryptionKey", "primaryMasterKey", + "primaryReadonlyMasterKey", "secondaryMasterKey", "secondaryReadonlyMasterKey", "certificatePassword", + "clientSecret", "keyVaultClientSecret", "authHeader", "httpHeader", "encryptedCredential", "functionKey", + "atlasKafkaPrimaryEndpoint", "atlasKafkaSecondaryEndpoint", "certificatePassword", "storageAccountPrimaryKey", + "privateKey", "fencingClientPassword", "acrToken", "scriptUrlSasToken", "azureBlobSource.containerUrl", + "properties.DOCKER_REGISTRY_SEVER_PASSWORD"); + + private static final String HOST_NAME_REGEX = "(?<=http://|https://)(?[^/?\\\\.]+)"; + private static final List HEADER_KEY_REGEX_TO_REDACT = Arrays.asList( + new TestProxySanitizer("ServiceBusDlqSupplementaryAuthorization", + "(?:(sv|sig|se|srt|ss|sp)=)(?[^&\\\"]+)", REDACTED_VALUE, TestProxySanitizerType.HEADER) + .setGroupForReplace("secret"), + new TestProxySanitizer("ServiceBusSupplementaryAuthorization", "(?:(sv|sig|se|srt|ss|sp)=)(?[^&\\\"]+)", + REDACTED_VALUE, TestProxySanitizerType.HEADER).setGroupForReplace("secret"), + new TestProxySanitizer("operation-location", HOST_NAME_REGEX, REDACTED_VALUE, TestProxySanitizerType.HEADER) + .setGroupForReplace("host"), + new TestProxySanitizer("Location", HOST_NAME_REGEX, REDACTED_VALUE, TestProxySanitizerType.HEADER) + .setGroupForReplace("host")); + + // Values in this list must have a capture group named "secret" for the redaction to work. + private static final List BODY_REGEXES_TO_REDACT + = Arrays.asList("(?:(Password|User ID)=)(?.*)(?:;)", "client_secret=(?[^&]+)", + "(?.*?)", "(?.*?)", + ".*?(?.*?).*?", + ".*?(?.*?).*?", + ".*?(?.*?).*?", + "SharedAccessKey=(?[^;\\\"]+)", "AccountKey=(?[^;\\\"]+)", "accesskey=(?[^;\\\"]+)", + "AccessKey=(?[^;\\\"]+)", "Secret=(?[^;\\\"]+)", "access_token=(?.*?)(?=&|$)", + "refresh_token=(?.*?)(?=&|$)"); + + private static final List HEADER_KEYS_TO_REDACT = Arrays.asList("Ocp-Apim-Subscription-Key", "api-key", + "x-api-key", "subscription-key", "x-ms-encryption-key", "sshPassword"); + + private static final HttpHeaderName X_RECORDING_UPSTREAM_BASE_URI + = HttpHeaderName.fromString("x-recording-upstream-base-uri"); + private static final HttpHeaderName X_RECORDING_MODE = HttpHeaderName.fromString("x-recording-mode"); + private static final HttpHeaderName X_REQUEST_MISMATCH_ERROR + = HttpHeaderName.fromString("x-request-mismatch-error"); + private static final HttpHeaderName X_REQUEST_KNOWN_EXCEPTION_ERROR + = HttpHeaderName.fromString("x-request-known-exception-error"); + private static final HttpHeaderName X_REQUEST_EXCEPTION_EXCEPTION_ERROR + = HttpHeaderName.fromString("x-request-exception-exception-error"); + private static final HttpHeaderName X_ABSTRACTION_IDENTIFIER + = HttpHeaderName.fromString("x-abstraction-identifier"); + + private static volatile URI proxyUri; + + /** + * Adds headers required for communication with the test proxy. + * + * @param request The request to add headers to. + * @param proxyUri The {@link URI} the proxy lives at. + * @param xRecordingId The x-recording-id value for the current session. + * @param mode The current test proxy mode. + * @param skipRecordingRequestBody Flag indicating to skip recording request bodies when tests run in Record mode. + * @throws RuntimeException Construction of one of the URIs failed. + */ + public static void changeHeaders(HttpRequest request, URI proxyUri, String xRecordingId, String mode, + boolean skipRecordingRequestBody) { + HttpHeader upstreamUri = request.getHeaders().get(X_RECORDING_UPSTREAM_BASE_URI); + + UriBuilder proxyUriBuilder = UriBuilder.parse(request.getUri()); + proxyUriBuilder.setScheme(proxyUri.getScheme()); + proxyUriBuilder.setHost(proxyUri.getHost()); + if (proxyUri.getPort() != -1) { + proxyUriBuilder.setPort(proxyUri.getPort()); + } + + UriBuilder originalUriBuilder = UriBuilder.parse(request.getUri()); + originalUriBuilder.setPath(""); + originalUriBuilder.setQuery(""); + + try { + URI originalUri = originalUriBuilder.toUri(); + + HttpHeaders headers = request.getHeaders(); + if (upstreamUri == null) { + headers.set(X_RECORDING_UPSTREAM_BASE_URI, originalUri.toString()); + headers.set(X_RECORDING_MODE, mode); + headers.set(X_RECORDING_ID, xRecordingId); + if (mode.equals(RECORD_MODE) && skipRecordingRequestBody) { + headers.set(X_RECORDING_SKIP, "request-body"); + } + } + + request.setUri(proxyUriBuilder.toUri()); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + } + + /** + * Get the assets json file path if it exists. + * @param recordFile the record/playback file + * @param testClassPath the test class path + * @return the assets json file path if it exists. + */ + public static String getAssetJsonFile(File recordFile, Path testClassPath) { + if (assetJsonFileExists(testClassPath)) { + // subpath removes nodes "src/test/resources/session-records" + return Paths.get(recordFile.toPath().subpath(0, 3).toString(), "assets.json").toString(); + } else { + return null; + } + } + + private static boolean assetJsonFileExists(Path testClassPath) { + return Files.exists( + Paths.get(String.valueOf(TestUtils.getRepoRootResolveUntil(testClassPath, "target")), "assets.json")); + } + + /** + * Sets the response URI back to the original URI before returning it through the pipeline. + * @param response The {@link Response} to modify. + * @return The modified response. + * @throws RuntimeException Construction of one of the URIs failed. + */ + public static Response resetTestProxyData(Response response) { + HttpRequest responseRequest = response.getRequest(); + HttpHeaders requestHeaders = responseRequest.getHeaders(); + try { + URI originalUri = UriBuilder.parse(requestHeaders.getValue(X_RECORDING_UPSTREAM_BASE_URI)).toUri(); + UriBuilder currentUri = UriBuilder.parse(responseRequest.getUri()); + currentUri.setScheme(originalUri.getScheme()); + currentUri.setHost(originalUri.getHost()); + int port = originalUri.getPort(); + if (port == -1) { + currentUri.setPort(""); // empty string is no port. + } else { + currentUri.setPort(port); + } + responseRequest.setUri(currentUri.toUri()); + + requestHeaders.remove(X_RECORDING_UPSTREAM_BASE_URI); + requestHeaders.remove(X_RECORDING_MODE); + requestHeaders.remove(X_RECORDING_SKIP); + requestHeaders.remove(X_RECORDING_ID); + return response; + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + } + + /** + * Gets the process name of the test proxy binary. + * @return The platform specific process name. + * @throws UnsupportedOperationException The current OS is not recognized. + */ + public static String getProxyProcessName() { + String osName = System.getProperty("os.name").toLowerCase(Locale.ROOT); + if (osName.contains("windows")) { + return "Azure.Sdk.Tools.TestProxy.exe"; + } else if (osName.contains("linux")) { + return "Azure.Sdk.Tools.TestProxy"; + } else if (osName.contains("mac os x")) { + return "Azure.Sdk.Tools.TestProxy"; + } else { + throw new UnsupportedOperationException(); + } + } + + /** + * Checks the return from a request through the test proxy for special error headers. + * @param response The {@link Response} from the test proxy. + */ + public static void checkForTestProxyErrors(Response response) { + String error = response.getHeaders().getValue(X_REQUEST_MISMATCH_ERROR); + if (error == null) { + error = response.getHeaders().getValue(X_REQUEST_KNOWN_EXCEPTION_ERROR); + } + if (error == null) { + error = response.getHeaders().getValue(X_REQUEST_EXCEPTION_EXCEPTION_ERROR); + } + if (error != null) { + throw LOGGER.logThrowableAsError(new RuntimeException( + "Test proxy exception: " + new String(Base64.getDecoder().decode(error), StandardCharsets.UTF_8))); + } + } + + /** + * Finds the test proxy version in the source tree. + * @param testClassPath the test class path + * @return The version string to use. + * @throws RuntimeException The eng folder could not be located in the repo. + * @throws UncheckedIOException The version file could not be read properly. + */ + public static String getTestProxyVersion(Path testClassPath) { + Path rootPath = TestUtils.getRepoRootResolveUntil(testClassPath, "eng"); + Path overrideVersionFile = Paths.get("eng", "target_proxy_version.txt"); + Path versionFile = Paths.get("eng", "common", "testproxy", "target_version.txt"); + + // if a long-lived override exists, use it. + if (Files.exists(rootPath.resolve(overrideVersionFile))) { + versionFile = overrideVersionFile; + } + + Path versionFilePath = rootPath.resolve(versionFile); + try { + return Files.readAllLines(versionFilePath).get(0).replace(System.lineSeparator(), ""); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + /** + * Gets the current URI for the test proxy. + * @return The {@link URI} location of the test proxy. + * @throws RuntimeException The URI could not be constructed. + */ + public static URI getProxyUri() { + if (proxyUri != null) { + return proxyUri; + } + UriBuilder builder = new UriBuilder(); + builder.setHost("localhost"); + builder.setScheme("http"); + builder.setPort(5000); + try { + proxyUri = builder.toUri(); + return proxyUri; + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + } + + /** + * Registers the default set of sanitizers for sanitizing request and responses + * @return the list of default sanitizers to be added. + */ + public static List loadSanitizers() { + List sanitizers = addDefaultRegexSanitizers(); + sanitizers.add(addDefaultUriSanitizer()); + sanitizers.addAll(addDefaultBodySanitizers()); + sanitizers.addAll(addDefaultHeaderKeySanitizers()); + return sanitizers; + } + + private static String createCustomMatcherRequestBody(CustomMatcher customMatcher) { + return String.format( + "{\"ignoredHeaders\":\"%s\",\"excludedHeaders\":\"%s\",\"compareBodies\":%s,\"ignoredQueryParameters\":\"%s\",\"ignoreQueryOrdering\":%s}", + getCommaSeperatedString(customMatcher.getHeadersKeyOnlyMatch()), + getCommaSeperatedString(customMatcher.getExcludedHeaders()), customMatcher.isComparingBodies(), + getCommaSeperatedString(customMatcher.getIgnoredQueryParameters()), customMatcher.isQueryOrderingIgnored()); + } + + private static String getCommaSeperatedString(List stringList) { + if (stringList == null) { + return null; + } + return stringList.stream().filter(s -> !CoreUtils.isNullOrEmpty(s)).collect(Collectors.joining(",")); + } + + private static String createBodyJsonKeyRequestBody(String jsonKey, String regex, String redactedValue) { + if (regex == null) { + return String.format("{\"value\":\"%s\",\"jsonPath\":\"%s\"}", redactedValue, jsonKey); + } else { + return String.format("{\"value\":\"%s\",\"jsonPath\":\"%s\",\"regex\":\"%s\"}", redactedValue, jsonKey, + regex); + } + } + + private static String createRegexRequestBody(String key, String regex, String value, String groupForReplace) { + if (key == null) { + if (groupForReplace == null) { + // regex pattern and redaction value + return String.format("{\"value\":\"%s\",\"regex\":\"%s\"}", value, regex); + } else { + // regex pattern and redaction value with group replace + return String.format("{\"value\":\"%s\",\"regex\":\"%s\",\"groupForReplace\":\"%s\"}", value, regex, + groupForReplace); + } + } else if (regex == null) { + // header key value + return String.format("{\"key\":\"%s\",\"value\":\"%s\"}", key, value); + } + if (groupForReplace == null) { + // header key with regex + return String.format("{\"key\":\"%s\",\"value\":\"%s\",\"regex\":\"%s\"}", key, value, regex); + } else { + return String.format("{\"key\":\"%s\",\"value\":\"%s\",\"regex\":\"%s\",\"groupForReplace\":\"%s\"}", key, + value, regex, groupForReplace); + } + } + + /** + * Creates a list of sanitizer requests to be sent to the test proxy server. + * + * @param sanitizers the list of sanitizers to be added. + * @param proxyUri The proxyUri to use when constructing requests. + * @return the list of sanitizer {@link HttpRequest requests} to be sent. + * @throws RuntimeException if {@link TestProxySanitizerType} is not supported. + * @deprecated Use {@link #createAddSanitizersRequest(List, URI)} instead as this will create a bulk HttpRequest + * for setting the sanitizers for a test proxy session instead of a request per sanitizer. + */ + @Deprecated + public static List getSanitizerRequests(List sanitizers, URI proxyUri) { + return sanitizers.stream().map(testProxySanitizer -> { + String requestBody; + String sanitizerType; + switch (testProxySanitizer.getType()) { + case URI: + sanitizerType = TestProxySanitizerType.URI.getName(); + requestBody = createRegexRequestBody(null, testProxySanitizer.getRegex(), + testProxySanitizer.getRedactedValue(), testProxySanitizer.getGroupForReplace()); + return createHttpRequest(requestBody, sanitizerType, proxyUri); + + case BODY_REGEX: + sanitizerType = TestProxySanitizerType.BODY_REGEX.getName(); + requestBody = createRegexRequestBody(null, testProxySanitizer.getRegex(), + testProxySanitizer.getRedactedValue(), testProxySanitizer.getGroupForReplace()); + return createHttpRequest(requestBody, sanitizerType, proxyUri); + + case BODY_KEY: + sanitizerType = TestProxySanitizerType.BODY_KEY.getName(); + requestBody = createBodyJsonKeyRequestBody(testProxySanitizer.getKey(), + testProxySanitizer.getRegex(), testProxySanitizer.getRedactedValue()); + return createHttpRequest(requestBody, sanitizerType, proxyUri); + + case HEADER: + sanitizerType = HEADER.getName(); + if (testProxySanitizer.getKey() == null && testProxySanitizer.getRegex() == null) { + throw new RuntimeException( + "Missing regexKey and/or headerKey for sanitizer type {" + sanitizerType + "}"); + } + requestBody = createRegexRequestBody(testProxySanitizer.getKey(), testProxySanitizer.getRegex(), + testProxySanitizer.getRedactedValue(), testProxySanitizer.getGroupForReplace()); + return createHttpRequest(requestBody, sanitizerType, proxyUri); + + default: + throw new RuntimeException("Sanitizer type {" + testProxySanitizer.getType() + "} not supported"); + } + }).collect(Collectors.toList()); + } + + /** + * Creates a request to bulk add sanitizers to the test proxy server. + *

        + * For more information about adding bulk sanitizers see the + * Passing Sanitizers in Bulk + * wiki. + * + * @param sanitizers The list of sanitizers to be added. + * @param proxyUri The proxyUri to use when constructing requests. + * @return The {@link HttpRequest request} to be sent. + * @throws RuntimeException if {@link TestProxySanitizerType} is not supported. + */ + public static HttpRequest createAddSanitizersRequest(List sanitizers, URI proxyUri) { + List sanitizersJsonPayloads = new ArrayList<>(sanitizers.size()); + + for (TestProxySanitizer sanitizer : sanitizers) { + String requestBody; + String sanitizerType; + switch (sanitizer.getType()) { + case URI: + sanitizerType = TestProxySanitizerType.URI.getName(); + requestBody = createRegexRequestBody(null, sanitizer.getRegex(), sanitizer.getRedactedValue(), + sanitizer.getGroupForReplace()); + break; + + case BODY_REGEX: + sanitizerType = TestProxySanitizerType.BODY_REGEX.getName(); + requestBody = createRegexRequestBody(null, sanitizer.getRegex(), sanitizer.getRedactedValue(), + sanitizer.getGroupForReplace()); + break; + + case BODY_KEY: + sanitizerType = TestProxySanitizerType.BODY_KEY.getName(); + requestBody = createBodyJsonKeyRequestBody(sanitizer.getKey(), sanitizer.getRegex(), + sanitizer.getRedactedValue()); + break; + + case HEADER: + sanitizerType = HEADER.getName(); + if (sanitizer.getKey() == null && sanitizer.getRegex() == null) { + throw new RuntimeException( + "Missing regexKey and/or headerKey for sanitizer type {" + sanitizerType + "}"); + } + requestBody = createRegexRequestBody(sanitizer.getKey(), sanitizer.getRegex(), + sanitizer.getRedactedValue(), sanitizer.getGroupForReplace()); + break; + + default: + throw new RuntimeException("Sanitizer type {" + sanitizer.getType() + "} not supported"); + } + + sanitizersJsonPayloads.add("{\"Name\":\"" + sanitizerType + "\",\"Body\":" + requestBody + "}"); + } + + String requestBody = "[" + CoreUtils.stringJoin(",", sanitizersJsonPayloads) + "]"; + return new HttpRequest().setMethod(HttpMethod.POST) + .setUri(proxyUri + "/Admin/AddSanitizers") + .setBody(new StringBinaryData(requestBody)); + } + + /** + * Creates a request to remove sanitizers from the request. + * @return The {@link HttpRequest request} to be sent. + */ + public static HttpRequest getRemoveSanitizerRequest() { + HttpRequest request = new HttpRequest().setMethod(HttpMethod.POST).setUri(proxyUri + "/Admin/RemoveSanitizers"); + request.getHeaders().set(HttpHeaderName.CONTENT_TYPE, "application/json"); + return request; + } + + private static HttpRequest createHttpRequest(String requestBody, String sanitizerType, URI proxyUri) { + HttpRequest request = new HttpRequest().setMethod(HttpMethod.POST) + .setUri(proxyUri + "/Admin/RemoveSanitizers") + .setBody(new StringBinaryData(requestBody)); + request.getHeaders().set(X_ABSTRACTION_IDENTIFIER, sanitizerType); + return request; + } + + /** + * Creates a {@link List} of {@link HttpRequest} to be sent to the test proxy to register matchers. + * @param matchers The {@link TestProxyRequestMatcher}s to encode into requests. + * @param proxyUri The proxyUri to use when constructing requests. + * @return The {@link HttpRequest}s to send to the proxy. + * @throws RuntimeException The {@link TestProxyRequestMatcher.TestProxyRequestMatcherType} is unsupported. + */ + public static List getMatcherRequests(List matchers, URI proxyUri) { + return matchers.stream().map(testProxyMatcher -> { + HttpRequest request; + String matcherType; + switch (testProxyMatcher.getType()) { + case HEADERLESS: + matcherType = TestProxyRequestMatcher.TestProxyRequestMatcherType.HEADERLESS.getName(); + request = new HttpRequest().setMethod(HttpMethod.POST).setUri(proxyUri + "/Admin/setmatcher"); + break; + + case BODILESS: + matcherType = TestProxyRequestMatcher.TestProxyRequestMatcherType.BODILESS.getName(); + request = new HttpRequest().setMethod(HttpMethod.POST).setUri(proxyUri + "/Admin/setmatcher"); + break; + + case CUSTOM: + CustomMatcher customMatcher = (CustomMatcher) testProxyMatcher; + String requestBody = createCustomMatcherRequestBody(customMatcher); + matcherType = TestProxyRequestMatcher.TestProxyRequestMatcherType.CUSTOM.getName(); + request = new HttpRequest().setMethod(HttpMethod.POST) + .setUri(proxyUri + "/Admin/setmatcher") + .setBody(new StringBinaryData(requestBody)); + break; + + default: + throw new RuntimeException("Matcher type {" + testProxyMatcher.getType() + "} not supported"); + } + + request.getHeaders().set(X_ABSTRACTION_IDENTIFIER, matcherType); + return request; + }).collect(Collectors.toList()); + } + + /** + * Set comparing bodies to false when running in playback and RecordWithoutRequestBody is set for the test. + * @return the HttpRequest for setting compare bodies matcher to false. + */ + public static HttpRequest setCompareBodiesMatcher() { + String requestBody = createCustomMatcherRequestBody(new CustomMatcher().setComparingBodies(false)); + HttpRequest request = new HttpRequest().setMethod(HttpMethod.POST) + .setUri(proxyUri + "/Admin/setmatcher") + .setBody(new StringBinaryData(requestBody)); + + request.getHeaders() + .set(X_ABSTRACTION_IDENTIFIER, TestProxyRequestMatcher.TestProxyRequestMatcherType.CUSTOM.getName()); + return request; + } + + private static TestProxySanitizer addDefaultUriSanitizer() { + return new TestProxySanitizer(URI_REGEX, REDACTED_VALUE, TestProxySanitizerType.URI); + } + + private static List addDefaultBodySanitizers() { + return JSON_BODY_KEYS_TO_REDACT.stream() + .map(jsonProperty -> new TestProxySanitizer("$.." + jsonProperty, null, REDACTED_VALUE, + TestProxySanitizerType.BODY_KEY)) + .collect(Collectors.toList()); + } + + private static List addDefaultRegexSanitizers() { + List regexSanitizers = new ArrayList<>(); + + regexSanitizers.addAll(BODY_REGEXES_TO_REDACT.stream() + .map(regex -> new TestProxySanitizer(regex, REDACTED_VALUE, TestProxySanitizerType.BODY_REGEX) + .setGroupForReplace("secret")) + .collect(Collectors.toList())); + + regexSanitizers.addAll(HEADER_KEY_REGEX_TO_REDACT); + + return regexSanitizers; + } + + private static List addDefaultHeaderKeySanitizers() { + return HEADER_KEYS_TO_REDACT.stream() + .map(headerKey -> new TestProxySanitizer(headerKey, null, REDACTED_VALUE, HEADER)) + .collect(Collectors.toList()); + } + + private TestProxyUtils() { + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/TestResourceNamer.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/TestResourceNamer.java new file mode 100644 index 000000000000..939a4cfcc1c1 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/TestResourceNamer.java @@ -0,0 +1,110 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.utils; + +import com.azure.v2.core.test.TestContextManager; +import com.azure.v2.core.test.TestMode; + +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; + +/** + * Provides random string names. If the test mode is {@link TestMode#PLAYBACK}, then names are fetched from + * the recording. If the test mode is {@link TestMode#RECORD}, then the names are randomly generated and + * persisted to the recording. + */ +public class TestResourceNamer extends ResourceNamer { + private final boolean allowedToReadRecordedValues; + private final boolean allowedToRecordValues; + private final Consumer storeVariable; + private final Supplier getVariable; + + /** + * Constructor of TestResourceNamer + * + * @param testContextManager Contextual information about the test being run, such as test name, {@link TestMode}, + * and others. + * @param storeVariable A {@link Consumer} for storing random variables into a recording. + * @param getVariable a {@link Supplier} for retrieving random variables from a recording. + */ + public TestResourceNamer(TestContextManager testContextManager, Consumer storeVariable, + Supplier getVariable) { + this(testContextManager.getTestName(), testContextManager.getTestMode(), testContextManager.doNotRecordTest(), + storeVariable, getVariable); + } + + private TestResourceNamer(String name, TestMode testMode, boolean doNotRecord, Consumer storeVariable, + Supplier getVariable) { + super(name); + + this.allowedToReadRecordedValues = (testMode == TestMode.PLAYBACK && !doNotRecord); + this.allowedToRecordValues = (testMode == TestMode.RECORD && !doNotRecord); + + if (this.allowedToReadRecordedValues || this.allowedToRecordValues) { + this.storeVariable = storeVariable; + this.getVariable = getVariable; + } else { + this.storeVariable = null; + this.getVariable = null; + } + } + + /** + * Gets a random name. + * + * @param prefix the prefix to be used if possible + * @param maxLen the max length for the random generated name + * @return the random name + */ + @Override + public String randomName(String prefix, int maxLen) { + return getValue(readValue -> readValue, () -> super.randomName(prefix, maxLen)); + } + + /** + * Gets a random UUID. + * + * @return A random UUID. + */ + @Override + public String randomUuid() { + return getValue(readValue -> readValue, super::randomUuid); + } + + /** + * Gets an OffsetDateTime of UTC now. + * + * @return OffsetDateTime of UTC now. + */ + public OffsetDateTime now() { + return getValue(OffsetDateTime::parse, () -> OffsetDateTime.now(ZoneOffset.UTC)); + } + + /** + * Record the value into storage, and pop it up when playback. + * + * @param value the value needs to record. + * @return the recorded value. + */ + public String recordValueFromConfig(String value) { + return getValue(readValue -> readValue, () -> value); + } + + private T getValue(Function readHandler, Supplier valueSupplier) { + if (allowedToReadRecordedValues) { + return readHandler.apply(getVariable.get()); + } else { + T value = valueSupplier.get(); + + if (allowedToRecordValues) { + storeVariable.accept(value.toString()); + } + + return value; + } + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/TestUtils.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/TestUtils.java new file mode 100644 index 000000000000..7096c86d4564 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/TestUtils.java @@ -0,0 +1,304 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.utils; + +import io.clientcore.core.http.client.HttpClient; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.utils.UriBuilder; +import org.junit.jupiter.api.Assertions; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.ByteBuffer; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.Objects; +import java.util.concurrent.ThreadLocalRandom; + +/** + * Contains utility methods used for testing. + */ +public final class TestUtils { + + private static final ClientLogger LOGGER = new ClientLogger(TestUtils.class); + + private static final HttpHeaderName UPSTREAM_URI_HEADER = HttpHeaderName.fromString("X-Upstream-Base-Uri"); + private static final HttpHeaderName HTTP_FAULT_INJECTOR_RESPONSE_HEADER + = HttpHeaderName.fromString("x-ms-faultinjector-response-option"); + + /** + * Asserts that two arrays are equal. + *

        + * This method is similar to JUnit's {@link Assertions#assertArrayEquals(byte[], byte[])} except that it takes + * advantage of hardware intrinsics offered by the JDK to optimize comparing the byte arrays. + *

        + * If the arrays aren't equal this will call {@link Assertions#assertArrayEquals(byte[], byte[])} to take advantage + * of the better error message, but this is the exceptional case and worth the double comparison performance hit. + * + * @param expected The expected byte array. + * @param actual The actual byte array. + */ + public static void assertArraysEqual(byte[] expected, byte[] actual) { + if (!Arrays.equals(expected, actual)) { + Assertions.assertArrayEquals(expected, actual); + } + } + + /** + * Asserts that two arrays are equal. + *

        + * This method is similar to JUnit's {@link Assertions#assertArrayEquals(byte[], byte[])} except that it takes + * advantage of hardware intrinsics offered by the JDK to optimize comparing the byte arrays and allows for + * comparing subsections of the arrays. + *

        + * If the arrays aren't equal this will copy the array ranges and call + * {@link Assertions#assertArrayEquals(byte[], byte[])} to take advantage of the better error message, but this is + * the exceptional case and worth the double comparison performance hit. + * + * @param expected The expected byte array. + * @param expectedOffset Starting offset to begin comparing in the expected array. + * @param actual The actual byte array. + * @param actualOffset Starting offset to begin comparing in the actual array. + * @param length Amount of bytes to compare. + */ + public static void assertArraysEqual(byte[] expected, int expectedOffset, byte[] actual, int actualOffset, + int length) { + // Use ByteBuffer comparison as it provides an optimized byte array comparison. + // In Java 9+ there is Arrays.mismatch that provides this functionality directly, but Java 8 needs support. + assertByteBuffersEqual(ByteBuffer.wrap(expected, expectedOffset, length), + ByteBuffer.wrap(actual, actualOffset, length)); + } + + /** + * Asserts that two {@link ByteBuffer ByteBuffers} are equal. + *

        + * This method is similar to JUnit's {@link Assertions#assertArrayEquals(byte[], byte[])} except that it takes + * advantage of hardware intrinsics offered by the JDK to optimize comparing the ByteBuffers. + *

        + * If the ByteBuffers aren't equal this will copy the ByteBuffer contents into byte arrays and call + * {@link Assertions#assertArrayEquals(byte[], byte[])} to take advantage of the better error message, but this is + * the exceptional case and worth the double comparison performance hit. + * + * @param expected The expected {@link ByteBuffer}. + * @param actual The actual {@link ByteBuffer}. + */ + public static void assertByteBuffersEqual(ByteBuffer expected, ByteBuffer actual) { + int expectedPosition = 0; + int actualPosition = 0; + if (expected != null) { + expectedPosition = expected.position(); + } + + if (actual != null) { + actualPosition = actual.position(); + } + + if (!Objects.equals(expected, actual)) { + // Reset the ByteBuffers in case their position was changed. + byte[] expectedArray = null; + if (expected != null) { + expected.position(expectedPosition); + expectedArray = new byte[expected.remaining()]; + expected.get(expectedArray); + } + + byte[] actualArray = null; + if (actual != null) { + actual.position(actualPosition); + actualArray = new byte[actual.remaining()]; + actual.get(actualArray); + } + + Assertions.assertArrayEquals(expectedArray, actualArray); + } + } + + /** + * Returns a {@link java.net.URI} equivalent to this URL. + * @param url the url to be converted to URI + * @return the URI + */ + public static URI toURI(URL url) { + try { + return url.toURI(); + } catch (URISyntaxException ex) { + throw LOGGER.logThrowableAsError(new IllegalStateException(ex)); + } + } + + private TestUtils() { + } + + /** + * Locates the root of the current repo until the provided folder's parent. + * + * @param testClassPath the test class path + * @param resolveFolder the folder parent to resolve the path until + * @return The {@link Path} to the root of the repo. + * @throws RuntimeException The specified folder could not be located. + */ + public static Path getRepoRootResolveUntil(Path testClassPath, String resolveFolder) { + String repoName = "\\azure-sdk-for-java"; + Path path = testClassPath; + Path candidate; + while (path != null && !path.endsWith(repoName)) { + candidate = path.resolve(resolveFolder); + if (Files.exists(candidate)) { + break; + } + path = path.getParent(); + } + if (path == null) { + throw new RuntimeException( + String.format("Could not locate %s folder within repository %s", resolveFolder, repoName)); + } + return path; + } + + /** + * Wraps an {@link HttpClient} to make calls to + * HTTP fault injector + * to test random network failures. + *

        + * Using the {@link HttpClient} returned by this method requires all setup required by HTTP fault injector to be + * configured. {@code useHttps} determines whether requests are forwarded to HTTP fault injector using HTTPS or + * HTTP, using HTTP doesn't require the self-signed certificate used by HTTP fault injector to be trusted by the JVM + * making it easier to prototype tests using HTTP fault injector. Merge ready tests should always use HTTPS. + *

        + * The {@link HttpClient} returned will use the default successful and failure response percentages. 75% of request + * will succeed, 24% of requests will fail with a partial body returned, and 1% of requests will never return a + * response. + * + * @param clientToWrap The {@link HttpClient} being wrapped that will send the actual request. + * @param useHttps Whether HTTPS should be used to communicate with HTTP fault injector. + * @return An {@link HttpClient} that forwards requests to HTTP fault injector with automatic fault injection + * handling to run tests with flaky network. + */ + public static HttpClient getFaultInjectingHttpClient(HttpClient clientToWrap, boolean useHttps) { + return getFaultInjectingHttpClient(clientToWrap, useHttps, 75, 24, 1); + } + + /** + * Wraps an {@link HttpClient} to make calls to + * HTTP fault injector + * to test random network failures. + *

        + * Using the {@link HttpClient} returned by this method requires all setup required by HTTP fault injector to be + * configured. {@code useHttps} determines whether requests are forwarded to HTTP fault injector using HTTPS or + * HTTP, using HTTP doesn't require the self-signed certificate used by HTTP fault injector to be trusted by the JVM + * making it easier to prototype tests using HTTP fault injector. Merge ready tests should always use HTTPS. + *

        + * The {@link HttpClient} returned will use the specified successful and failure response percentages. The + * combination of {@code successRate}, {@code partialRate}, and {@code failureRate} must equal 100, if not an + * {@link IllegalArgumentException} will be thrown. An {@link IllegalArgumentException} will also be thrown if any + * of the values are negative. + * + * @param clientToWrap The {@link HttpClient} being wrapped that will send the actual request. + * @param useHttps Whether HTTPS should be used to communicate with HTTP fault injector. + * @param successRate Percent of requests that will succeed. + * @param partialRate Percent of requests that will partially succeed. + * @param failureRate Percent of requests that will fail. + * @return An {@link HttpClient} that forwards requests to HTTP fault injector with automatic fault injection + * handling to run tests with flaky network. + * @throws IllegalArgumentException If {@code successRate}, {@code partialRate}, and {@code failureRate} don't add + * up to 100 or if any of the values are negative. + */ + public static HttpClient getFaultInjectingHttpClient(HttpClient clientToWrap, boolean useHttps, int successRate, + int partialRate, int failureRate) { + if (successRate + partialRate + failureRate != 100 || successRate < 0 || partialRate < 0 || failureRate < 0) { + throw LOGGER.atError() + .addKeyValue("successRate", successRate) + .addKeyValue("partialRage", partialRate) + .addKeyValue("failureRate", failureRate) + .log("", new IllegalStateException( + "'successRate', 'partialRate', and 'failureRate' must add to 100 and no values can be negative.")); + } + + return new HttpFaultInjectingHttpClient(clientToWrap, useHttps, successRate, partialRate); + } + + private static final class HttpFaultInjectingHttpClient implements HttpClient { + private final HttpClient wrappedHttpClient; + private final boolean useHttps; + private final int successRate; + private final int partialRate; + + HttpFaultInjectingHttpClient(HttpClient wrappedHttpClient, boolean useHttps, int successRate, int partialRate) { + this.wrappedHttpClient = wrappedHttpClient; + this.useHttps = useHttps; + this.successRate = successRate; + this.partialRate = partialRate; + } + + @Override + public Response send(HttpRequest request) throws IOException { + URI originalUri = request.getUri(); + request.getHeaders().set(UPSTREAM_URI_HEADER, originalUri.toString()); + request.setUri(rewriteUri(originalUri)); + String faultType = faultInjectorHandling(); + request.getHeaders().set(HTTP_FAULT_INJECTOR_RESPONSE_HEADER, faultType); + + Response response = wrappedHttpClient.send(request); + response.getRequest().setUri(originalUri); + response.getRequest().getHeaders().remove(UPSTREAM_URI_HEADER); + + return response; + } + + private URI rewriteUri(URI originalUri) { + try { + return UriBuilder.parse(originalUri) + .setScheme(useHttps ? "https" : "http") + .setHost("localhost") + .setPort(useHttps ? 7778 : 7777) + .toUri(); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + } + + private String faultInjectorHandling() { + // f: Full response + // p: Partial Response (full headers, 50% of body), then wait indefinitely + // pc: Partial Response (full headers, 50% of body), then close (TCP FIN) + // pa: Partial Response (full headers, 50% of body), then abort (TCP RST) + // pn: Partial Response (full headers, 50% of body), then finish normally + // n: No response, then wait indefinitely + // nc: No response, then close (TCP FIN) + // na: No response, then abort (TCP RST) + double random = ThreadLocalRandom.current().nextDouble(); + int choice = (int) (random * 100); + + if (choice >= (100 - successRate)) { + // 75% of requests complete without error. + return "f"; + } else if (choice >= (100 - successRate - partialRate)) { + if (random <= 0.34D) { + return "n"; + } else if (random <= 0.67D) { + return "nc"; + } else { + return "na"; + } + } else { + if (random <= 0.25D) { + return "p"; + } else if (random <= 0.50D) { + return "pc"; + } else if (random <= 0.75D) { + return "pa"; + } else { + return "pn"; + } + } + } + } +} diff --git a/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/package-info.java b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/package-info.java new file mode 100644 index 000000000000..35368761098b --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/com/azure/v2/core/test/utils/package-info.java @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * Package containing utility classes used for testing Azure client libraries. + */ +package com.azure.v2.core.test.utils; diff --git a/sdk/corev2/azure-core-test/src/main/java/module-info.java b/sdk/corev2/azure-core-test/src/main/java/module-info.java new file mode 100644 index 000000000000..85014178a131 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/java/module-info.java @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +module com.azure.core.test { + requires transitive io.clientcore.core; + requires transitive com.azure.v2.core; + + requires org.junit.jupiter.api; + requires org.junit.jupiter.engine; + requires org.junit.jupiter.params; + requires org.junit.platform.commons; + requires java.management; + requires java.net.http; + requires ant; + + exports com.azure.v2.core.test; + exports com.azure.v2.core.test.annotation; + exports com.azure.v2.core.test.http; + exports com.azure.v2.core.test.junitextensions; + exports com.azure.v2.core.test.models; + exports com.azure.v2.core.test.policy; + exports com.azure.v2.core.test.utils; + + opens com.azure.v2.core.test.implementation to com.azure.v2.core, org.junit.platform.commons; + opens com.azure.v2.core.test to com.azure.v2.core, org.junit.platform.commons; + opens com.azure.v2.core.test.junitextensions to com.azure.v2.core, org.junit.platform.commons; + opens com.azure.v2.core.test.annotation to com.azure.v2.core, org.junit.platform.commons; + + uses io.clientcore.core.http.client.HttpClientProvider; +} diff --git a/sdk/corev2/azure-core-test/src/main/resources/META-INF/native-image/com.azure/azure-core-test/resource-config.json b/sdk/corev2/azure-core-test/src/main/resources/META-INF/native-image/com.azure/azure-core-test/resource-config.json new file mode 100644 index 000000000000..bf98168e5d73 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/resources/META-INF/native-image/com.azure/azure-core-test/resource-config.json @@ -0,0 +1,9 @@ +{ + "resources": { + "includes": [ + { + "pattern": "\\Qsession-records/\\E" + } + ] + } +} diff --git a/sdk/corev2/azure-core-test/src/main/resources/META-INF/services/org.junit.jupiter.api.extension.Extension b/sdk/corev2/azure-core-test/src/main/resources/META-INF/services/org.junit.jupiter.api.extension.Extension new file mode 100644 index 000000000000..e080f7834c1a --- /dev/null +++ b/sdk/corev2/azure-core-test/src/main/resources/META-INF/services/org.junit.jupiter.api.extension.Extension @@ -0,0 +1,5 @@ +com.azure.v2.core.test.AzureTestWatcher +com.azure.v2.core.test.ThreadDumper +com.azure.v2.core.test.junitextensions.LiveOnlyExtension +com.azure.v2.core.test.junitextensions.PlaybackOnlyExtension +com.azure.v2.core.test.junitextensions.TestContextManagerParameterResolver diff --git a/sdk/corev2/azure-core-test/src/samples/java/com/azure/core/test/ReadmeSamples.java b/sdk/corev2/azure-core-test/src/samples/java/com/azure/core/test/ReadmeSamples.java new file mode 100644 index 000000000000..b1bab73c1d64 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/samples/java/com/azure/core/test/ReadmeSamples.java @@ -0,0 +1,98 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.core.test; + +import com.azure.v2.core.test.TestBase; +import com.azure.v2.core.test.models.CustomMatcher; +import com.azure.v2.core.test.models.TestProxySanitizer; +import com.azure.v2.core.test.models.TestProxySanitizerType; +import io.clientcore.core.http.models.HttpMethod; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.http.pipeline.HttpPipelineBuilder; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Class containing code snippets that will be injected to README.md. + */ +public class ReadmeSamples { + // BEGIN: readme-sample-createATestClass + + /** + * Set the AZURE_TEST_MODE environment variable to either PLAYBACK or RECORD to determine if tests are playback or + * record. By default, tests are run in playback mode. + */ + public static class ClientTests extends TestBase { + + /** + * Use JUnit annotation here for your testcase + */ + public void testMethodName() { + HttpPipelineBuilder pipelineBuilder = new HttpPipelineBuilder(); + if (interceptorManager.isRecordMode()) { + // Add a policy to record network calls. + pipelineBuilder.addPolicy(interceptorManager.getRecordPolicy()); + } + if (interceptorManager.isPlaybackMode()) { + // Use a playback client when running in playback mode + pipelineBuilder.httpClient(interceptorManager.getPlaybackClient()); + } + + try (Response response = pipelineBuilder.build().send(new HttpRequest().setMethod(HttpMethod.GET) + .setUri("http://bing.com"))) { + // Validate test results. + assertEquals(200, response.getStatusCode()); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + } + // END: readme-sample-createATestClass + + + /** + * Sample code for adding sanitizer and matcher to the interceptor manager. + */ + public void testAddSanitizersAndMatchers() throws IOException { + HttpPipelineBuilder pipelineBuilder = new HttpPipelineBuilder(); + // BEGIN: readme-sample-add-sanitizer-matcher + + List customSanitizer = new ArrayList<>(); + // sanitize value for key: "modelId" in response json body + customSanitizer.add( + new TestProxySanitizer("$..modelId", "REPLACEMENT_TEXT", TestProxySanitizerType.BODY_KEY)); + + if (interceptorManager.isRecordMode()) { + // Add a policy to record network calls. + pipelineBuilder.addPolicy(interceptorManager.getRecordPolicy()); + } + if (interceptorManager.isPlaybackMode()) { + // Use a playback client when running in playback mode + pipelineBuilder.httpClient(interceptorManager.getPlaybackClient()); + // Add matchers only in playback mode + interceptorManager.addMatchers(Arrays.asList(new CustomMatcher() + .setHeadersKeyOnlyMatch(Arrays.asList("x-ms-client-request-id")))); + } + if (!interceptorManager.isLiveMode()) { + // Add sanitizers when running in playback or record mode + interceptorManager.addSanitizers(customSanitizer); + } + // END: readme-sample-add-sanitizer-matcher + + try (Response response = pipelineBuilder.build().send(new HttpRequest().setMethod(HttpMethod.GET) + .setUri("http://bing.com"))) { + // Validate test results. + assertEquals(200, response.getStatusCode()); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + } + } +} diff --git a/sdk/corev2/azure-core-test/src/test/java/com/azure/v2/core/test/FakeTestClass.java b/sdk/corev2/azure-core-test/src/test/java/com/azure/v2/core/test/FakeTestClass.java new file mode 100644 index 000000000000..49b35de19bd1 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/test/java/com/azure/v2/core/test/FakeTestClass.java @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.v2.core.test; + +import io.clientcore.core.instrumentation.logging.ClientLogger; + +import java.lang.reflect.Method; + +/** + * This is a dummy class used to mock scenarios for {@link TestContextManager}. + */ +public final class FakeTestClass { + public static final Method METHOD_WITHOUT_DONOTRECORD = getTestMethod("testWithoutDoNotRecord"); + public static final Method DONOTRECORD_FALSE_SKIPINPLAYBACK = getTestMethod("testWithDoNotRecordRunInPlayback"); + public static final Method DONOTRECORD_SKIPINPLAYBACK = getTestMethod("testWithDoNotRecordSkipInPlayback"); + + public void testWithoutDoNotRecord() { + } + + public void testWithDoNotRecordRunInPlayback() { + + } + + @SuppressWarnings("deprecation") + public void testWithDoNotRecordSkipInPlayback() { + } + + private static Method getTestMethod(String methodName) { + try { + return FakeTestClass.class.getMethod(methodName); + } catch (NoSuchMethodException e) { + throw new ClientLogger(FakeTestClass.class).logThrowableAsWarning(new RuntimeException(e)); + } + } +} diff --git a/sdk/corev2/azure-core-test/src/test/java/com/azure/v2/core/test/TestProxyTests.java b/sdk/corev2/azure-core-test/src/test/java/com/azure/v2/core/test/TestProxyTests.java new file mode 100644 index 000000000000..a59c5b4334c3 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/test/java/com/azure/v2/core/test/TestProxyTests.java @@ -0,0 +1,496 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test; + +import com.azure.v2.core.test.annotation.DoNotRecord; +import com.azure.v2.core.test.annotation.RecordWithoutRequestBody; +import com.azure.v2.core.test.implementation.TestingHelpers; +import com.azure.v2.core.test.models.CustomMatcher; +import com.azure.v2.core.test.models.TestProxySanitizer; +import com.azure.v2.core.test.models.TestProxySanitizerType; +import com.azure.v2.core.test.utils.HttpUrlConnectionHttpClient; +import com.azure.v2.core.test.utils.TestProxyTestServer; +import com.azure.v2.core.test.utils.TestProxyUtils; +import io.clientcore.core.http.client.HttpClient; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpHeaders; +import io.clientcore.core.http.models.HttpMethod; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.http.pipeline.HttpPipeline; +import io.clientcore.core.http.pipeline.HttpPipelineBuilder; +import io.clientcore.core.http.pipeline.HttpRedirectPolicy; +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonSerializable; +import io.clientcore.core.serialization.json.JsonWriter; +import io.clientcore.core.models.binarydata.BinaryData; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledIfEnvironmentVariable; +import org.junit.jupiter.api.condition.DisabledIfSystemProperty; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Test class for testing Test proxy functionality of record, playback and redaction. + */ + +// These tests override the environment variable so they can test playback and record in the same test run. +// This strategy fails if we are in a LIVE test mode, so we'll just skip these entirely if that's the case. +@DisabledIfEnvironmentVariable(named = "AZURE_TEST_MODE", matches = "(LIVE|live|Live)") +@DisabledIfSystemProperty(named = "AZURE_TEST_MODE", matches = "(LIVE|live|Live)") +public class TestProxyTests extends TestBase { + public static final String TEST_DATA = "{\"test\":\"proxy\"}"; + static TestProxyTestServer server; + + private static final List CUSTOM_SANITIZER = new ArrayList<>(); + + public static final String REDACTED = "REDACTED"; + private static final HttpHeaderName OCP_APIM_SUBSCRIPTION_KEY + = HttpHeaderName.fromString("Ocp-Apim-Subscription-Key"); + + static { + CUSTOM_SANITIZER.add(new TestProxySanitizer("$..modelId", null, REDACTED, TestProxySanitizerType.BODY_KEY)); + CUSTOM_SANITIZER.add(new TestProxySanitizer("TableName\\\"*:*\\\"(?.*)\\\"", REDACTED, + TestProxySanitizerType.BODY_REGEX).setGroupForReplace("tablename")); + } + + @BeforeAll + public static void setupClass() { + server = new TestProxyTestServer(); + } + + @AfterAll + public static void teardownClass() throws IOException { + server.close(); + } + + @Test + @Tag("Record") + public void testBasicRecord() throws IOException { + HttpUrlConnectionHttpClient client = new HttpUrlConnectionHttpClient(); + HttpPipeline pipeline + = new HttpPipelineBuilder().httpClient(client).addPolicy(interceptorManager.getRecordPolicy()).build(); + + testResourceNamer.randomName("test", 10); + testResourceNamer.now(); + HttpRequest request = new HttpRequest().setMethod(HttpMethod.GET).setUri("http://localhost:" + server.port()); + + try (Response response = pipeline.send(request)) { + assertEquals(200, response.getStatusCode()); + } + } + + @Test + @Tag("Playback") + public void testOrdering() { + // this proves that regardless of where in your test method you might try and get a variable it works. + String name = testResourceNamer.randomName("test", 10); + assertEquals("test32950", name); + } + + @Test + @Tag("Record") + @DoNotRecord + public void testDoNotRecord() { + testResourceNamer.now(); + } + + @Test + @Tag("Playback") + @DoNotRecord + public void testDoNotPlayback() { + testResourceNamer.now(); + } + + @Test + @Tag("Playback") + public void testMismatch() { + HttpClient client = interceptorManager.getPlaybackClient(); + + HttpRequest request + = new HttpRequest().setMethod(HttpMethod.GET).setUri("http://localhost:" + server.port() + "/first/path"); + RuntimeException thrown = assertThrows(RuntimeException.class, () -> client.send(request).close()); + assertTrue(thrown.getMessage().contains("Uri doesn't match")); + } + + @Test + @Tag("Record") + @RecordWithoutRequestBody + public void testRecordWithPath() throws IOException { + HttpUrlConnectionHttpClient client = new HttpUrlConnectionHttpClient(); + HttpPipeline pipeline + = new HttpPipelineBuilder().httpClient(client).addPolicy(interceptorManager.getRecordPolicy()).build(); + + testResourceNamer.randomName("test", 10); + testResourceNamer.now(); + HttpRequest request = new HttpRequest().setMethod(HttpMethod.POST) + .setUri("http://localhost:" + server.port() + "/first/path") + .setBody(BinaryData.fromString(TEST_DATA)); + request.getHeaders() + .set(HttpHeaderName.CONTENT_TYPE, "application/json") + .set(HttpHeaderName.CONTENT_LENGTH, String.valueOf(TEST_DATA.length())); + + try (Response response = pipeline.send(request)) { + assertEquals(200, response.getStatusCode()); + } + } + + @Test + @Tag("Record") + public void testRecordWithHeaders() throws IOException { + HttpUrlConnectionHttpClient client = new HttpUrlConnectionHttpClient(); + HttpPipeline pipeline + = new HttpPipelineBuilder().httpClient(client).addPolicy(interceptorManager.getRecordPolicy()).build(); + + testResourceNamer.randomName("test", 10); + testResourceNamer.now(); + HttpRequest request + = new HttpRequest().setMethod(HttpMethod.GET).setUri("http://localhost:" + server.port() + "/echoheaders"); + request.getHeaders() + .set(HttpHeaderName.fromString("header1"), "value1") + .set(HttpHeaderName.fromString("header2"), "value2"); + + try (Response response = pipeline.send(request)) { + assertEquals(200, response.getStatusCode()); + } + } + + @Test + @Tag("Playback") + public void testPlayback() throws IOException { + HttpClient client = interceptorManager.getPlaybackClient(); + interceptorManager.addMatchers(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Connection"))); + + HttpRequest request + = new HttpRequest().setMethod(HttpMethod.GET).setUri("http://localhost:" + server.port() + "/first/path"); + // For this test set an Accept header as most HttpClients will use a default which could result in this + // test being flaky + request.getHeaders().set(HttpHeaderName.ACCEPT, "*/*"); + + try (Response response = client.send(request)) { + assertEquals("first path", response.getValue().toString()); + assertEquals(200, response.getStatusCode()); + } + } + + @Test + @Tag("Live") + public void testCannotGetPlaybackClient() { + RuntimeException thrown + = assertThrows(IllegalStateException.class, () -> interceptorManager.getPlaybackClient()); + assertEquals("A playback client can only be requested in PLAYBACK mode.", thrown.getMessage()); + } + + @Test + @Tag("Live") + public void testCannotGetRecordPolicy() { + RuntimeException thrown = assertThrows(IllegalStateException.class, () -> interceptorManager.getRecordPolicy()); + assertEquals("A recording policy can only be requested in RECORD mode.", thrown.getMessage()); + } + + @Test + @Tag("Playback") + public void testRecordWithRedaction() throws IOException { + interceptorManager.addSanitizers(CUSTOM_SANITIZER); + interceptorManager.addMatchers(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Connection"))); + HttpClient client = interceptorManager.getPlaybackClient(); + + HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(client).build(); + + HttpRequest request + = new HttpRequest().setMethod(HttpMethod.GET).setUri("http://localhost:" + server.port() + "/fr/path/1"); + request.getHeaders() + .set(OCP_APIM_SUBSCRIPTION_KEY, "SECRET_API_KEY") + .set(HttpHeaderName.CONTENT_TYPE, "application/json") + // For this test set an Accept header as most HttpClients will use a default which could result in this + // test being flaky + .set(HttpHeaderName.ACCEPT, "*/*"); + + try (Response response = pipeline.send(request)) { + assertEquals(200, response.getStatusCode()); + RecordedTestProxyData recordedTestProxyData = readDataFromFile(); + RecordedTestProxyData.TestProxyDataRecord record = recordedTestProxyData.getTestProxyDataRecords().get(0); + // default sanitizers + assertEquals("http://REDACTED/fr/path/1", record.getUri()); + assertEquals(REDACTED, record.getHeaders().get("Ocp-Apim-Subscription-Key")); + assertTrue(record.getResponseHeaders() + .get("Operation-Location") + .startsWith("https://REDACTED/fr/models//905a58f9-131e-42b8-8410-493ab1517d62")); + // custom sanitizers + assertEquals(REDACTED, record.getResponse().get("modelId")); + assertEquals(REDACTED, record.getResponse().get("client_secret")); + } + } + + @Test + @Tag("Playback") + public void testPlaybackWithRedaction() throws IOException { + interceptorManager.addSanitizers(CUSTOM_SANITIZER); + interceptorManager.addMatchers(Collections.singletonList( + new CustomMatcher().setExcludedHeaders(Arrays.asList("Ocp-Apim-Subscription-Key", "Connection")))); + HttpClient client = interceptorManager.getPlaybackClient(); + + HttpRequest request + = new HttpRequest().setMethod(HttpMethod.GET).setUri("http://localhost:" + server.port() + "/fr/models"); + request.getHeaders() + .set(OCP_APIM_SUBSCRIPTION_KEY, "SECRET_API_KEY") + .set(HttpHeaderName.CONTENT_TYPE, "application/json") + // For this test set an Accept header as most HttpClients will use a default which could result in this + // test being flaky + .set(HttpHeaderName.ACCEPT, "*/*"); + + try (Response response = client.send(request)) { + assertEquals(200, response.getStatusCode()); + } + } + + @Test + @Tag("Playback") + public void testBodyRegexRedactRecord() throws IOException { + HttpClient client = interceptorManager.getPlaybackClient(); + + interceptorManager.addSanitizers(CUSTOM_SANITIZER); + interceptorManager.addMatchers(new CustomMatcher().setHeadersKeyOnlyMatch(Collections.singletonList("Accept")) + .setExcludedHeaders(Collections.singletonList("Connection"))); + + HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(client).build(); + + HttpRequest request + = new HttpRequest().setMethod(HttpMethod.GET).setUri("http://localhost:" + server.port() + "/fr/path/2"); + request.getHeaders().set(HttpHeaderName.CONTENT_TYPE, "application/json"); + + try (Response response = pipeline.send(request)) { + assertEquals(200, response.getStatusCode()); + } + + RecordedTestProxyData recordedTestProxyData = readDataFromFile(); + RecordedTestProxyData.TestProxyDataRecord record = recordedTestProxyData.getTestProxyDataRecords().get(0); + // default regex sanitizers + assertEquals("http://REDACTED/fr/path/2", record.getUri()); + + // user delegation sanitizers + assertTrue(record.getResponse() + .get("Body") + .contains("REDACTED")); + assertTrue(record.getResponse().get("primaryKey").contains("REDACTED")); + + // custom body regex + assertEquals(REDACTED, record.getResponse().get("TableName")); + } + + @Test + @Tag("Playback") + public void testRedactRequestBodyRegex() throws IOException { + + HttpClient client = interceptorManager.getPlaybackClient(); + HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(client).build(); + interceptorManager.addMatchers(new CustomMatcher().setHeadersKeyOnlyMatch(Collections.singletonList("Accept")) + .setExcludedHeaders(Collections.singletonList("Connection"))); + + // HttpClient client = new HttpURLConnectionHttpClient(); + // HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(client).policies(interceptorManager.getRecordPolicy()).build(); + + HttpRequest request + = new HttpRequest().setMethod(HttpMethod.POST).setUri("http://localhost:" + server.port() + "/post"); + request.getHeaders().set(HttpHeaderName.CONTENT_TYPE, "application/x-www-form-urlencoded"); + request.setBody(BinaryData.fromString("first_value=value&client_secret=aVerySecretSecret&other=value&is=cool")); + + try (Response response = pipeline.send(request)) { + assertEquals(200, response.getStatusCode()); + } + + RecordedTestProxyData recordedTestProxyData = readDataFromFile(); + RecordedTestProxyData.TestProxyDataRecord record = recordedTestProxyData.getTestProxyDataRecords().get(0); + + assertEquals("first_value=value&client_secret=REDACTED&other=value&is=cool", record.getRequestBody()); + + } + + @Test + @Tag("Live") + public void canGetTestProxyVersion() { + String version = TestProxyUtils.getTestProxyVersion(this.getTestClassPath()); + assertNotNull(version); + } + + @Test + @Tag("Record") + public void testResetTestProxyData() throws IOException { + HttpUrlConnectionHttpClient client = new HttpUrlConnectionHttpClient(); + + final HttpPipeline pipeline + = new HttpPipelineBuilder().httpClient(client).addPolicy(interceptorManager.getRecordPolicy()).build(); + + try (Response response + = pipeline.send(new HttpRequest().setMethod(HttpMethod.GET).setUri("http://localhost:" + server.port()))) { + assertEquals(200, response.getStatusCode()); + HttpHeaders headers = response.getRequest().getHeaders(); + assertNull(headers.get(HttpHeaderName.fromString("x-recording-upstream-base-uri"))); + assertNull(headers.get(HttpHeaderName.fromString("x-recording-mode"))); + assertNull(headers.get(HttpHeaderName.fromString("x-recording-id"))); + assertNull(headers.get(HttpHeaderName.fromString("x-recording-skip"))); + } + } + + @Test + @Tag("Record") + public void testRecordWithRedirect() throws IOException { + HttpUrlConnectionHttpClient client = new HttpUrlConnectionHttpClient(); + + HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(client) + .addPolicy(new HttpRedirectPolicy()) + .addPolicy(interceptorManager.getRecordPolicy()) + .build(); + + HttpRequest request + = new HttpRequest().setMethod(HttpMethod.GET).setUri("http://localhost:" + server.port() + "/getRedirect"); + + try (Response response = pipeline.send(request)) { + assertEquals(200, response.getStatusCode()); + + assertEquals("http://localhost:" + server.port() + "/echoheaders", + response.getRequest().getUri().toString()); + assertNull( + response.getRequest().getHeaders().get(HttpHeaderName.fromString("x-recording-upstream-base-uri"))); + } + } + + private RecordedTestProxyData readDataFromFile() { + try (BufferedReader reader = Files.newBufferedReader(Paths.get(interceptorManager.getRecordingFileLocation())); + JsonReader jsonReader = JsonReader.fromReader(reader)) { + return RecordedTestProxyData.fromJson(jsonReader); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + } + + static class RecordedTestProxyData implements JsonSerializable { + private final LinkedList testProxyDataRecords; + + RecordedTestProxyData() { + testProxyDataRecords = new LinkedList<>(); + } + + public LinkedList getTestProxyDataRecords() { + return testProxyDataRecords; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject() + .writeArrayField("Entries", testProxyDataRecords, JsonWriter::writeJson) + .writeEndObject(); + } + + /** + * Deserializes an instance of RecordedTestProxyData from the input JSON. + * + * @param jsonReader The JSON reader to deserialize the data from. + * @return An instance of RecordedTestProxyData deserialized from the JSON. + * @throws IOException If the JSON reader encounters an error while reading the JSON. + */ + public static RecordedTestProxyData fromJson(JsonReader jsonReader) throws IOException { + return TestingHelpers.readObject(jsonReader, RecordedTestProxyData::new, + (recordedData, fieldName, reader) -> { + if ("Entries".equals(fieldName)) { + recordedData.testProxyDataRecords.addAll(reader.readArray(TestProxyDataRecord::fromJson)); + } else { + reader.skipChildren(); + } + }); + } + + static class TestProxyDataRecord implements JsonSerializable { + private String method; + private String uri; + private Map headers; + private Map response; + private Map responseHeaders; + private String requestBody; + + public String getMethod() { + return method; + } + + public String getUri() { + return uri; + } + + public Map getHeaders() { + return headers; + } + + public Map getResponse() { + return response; + } + + public Map getResponseHeaders() { + return responseHeaders; + } + + public String getRequestBody() { + return requestBody; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject() + .writeStringField("RequestMethod", method) + .writeStringField("RequestUri", uri) + .writeMapField("RequestHeaders", headers, JsonWriter::writeString) + .writeMapField("ResponseBody", response, JsonWriter::writeString) + .writeMapField("ResponseHeaders", responseHeaders, JsonWriter::writeString) + .writeStringField("RequestBody", requestBody) + .writeEndObject(); + } + + /** + * Deserializes an instance of TestProxyDataRecord from the input JSON. + * + * @param jsonReader The JSON reader to deserialize the data from. + * @return An instance of TestProxyDataRecord deserialized from the JSON. + * @throws IOException If the JSON reader encounters an error while reading the JSON. + */ + public static TestProxyDataRecord fromJson(JsonReader jsonReader) throws IOException { + return TestingHelpers.readObject(jsonReader, TestProxyDataRecord::new, + (dataRecord, fieldName, reader) -> { + if ("RequestMethod".equals(fieldName)) { + dataRecord.method = reader.getString(); + } else if ("RequestUri".equals(fieldName)) { + dataRecord.uri = reader.getString(); + } else if ("RequestHeaders".equals(fieldName)) { + dataRecord.headers = reader.readMap(JsonReader::getString); + } else if ("ResponseBody".equals(fieldName)) { + dataRecord.response = reader.readMap(JsonReader::getString); + } else if ("ResponseHeaders".equals(fieldName)) { + dataRecord.responseHeaders = reader.readMap(JsonReader::getString); + } else if ("RequestBody".equals(fieldName)) { + dataRecord.requestBody = reader.getString(); + } else { + reader.skipChildren(); + } + }); + } + } + } +} diff --git a/sdk/corev2/azure-core-test/src/test/java/com/azure/v2/core/test/TestUtilsTests.java b/sdk/corev2/azure-core-test/src/test/java/com/azure/v2/core/test/TestUtilsTests.java new file mode 100644 index 000000000000..1096b8207047 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/test/java/com/azure/v2/core/test/TestUtilsTests.java @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test; + +import com.azure.v2.core.test.utils.TestUtils; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.opentest4j.AssertionFailedError; + +import java.nio.ByteBuffer; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * Tests {@link TestUtils}. + */ +public class TestUtilsTests { + @ParameterizedTest + @MethodSource("arraysAreEqualSupplier") + public void arraysAreEqual(byte[] array1, byte[] array2) { + assertDoesNotThrow(() -> TestUtils.assertArraysEqual(array1, array2)); + } + + private static Stream arraysAreEqualSupplier() { + byte[] sameInstance = new byte[] { 1, 2, 3 }; + return Stream.of(Arguments.of(null, null), Arguments.of(new byte[0], new byte[0]), + Arguments.of(sameInstance, sameInstance), Arguments.of(new byte[] { 1, 2, 3 }, new byte[] { 1, 2, 3 })); + } + + @Test + public void arraysAreNotEqual() { + assertThrows(AssertionFailedError.class, () -> TestUtils.assertArraysEqual(new byte[0], new byte[] { 1, 2 })); + } + + @ParameterizedTest + @MethodSource("byteBuffersAreEqualSupplier") + public void byteBuffersAreEqual(ByteBuffer byteBuffer1, ByteBuffer byteBuffer2) { + assertDoesNotThrow(() -> TestUtils.assertByteBuffersEqual(byteBuffer1, byteBuffer2)); + } + + private static Stream byteBuffersAreEqualSupplier() { + ByteBuffer sameInstance = ByteBuffer.wrap(new byte[] { 1, 2, 3 }); + return Stream.of(Arguments.of(null, null), Arguments.of(ByteBuffer.allocate(0), ByteBuffer.allocate(0)), + Arguments.of(sameInstance, sameInstance), + Arguments.of(ByteBuffer.wrap(new byte[] { 1, 2, 3 }), ByteBuffer.wrap(new byte[] { 1, 2, 3 }))); + } + + @Test + public void byteBuffersAreNotEqual() { + assertThrows(AssertionFailedError.class, () -> TestUtils + .assertByteBuffersEqual(ByteBuffer.wrap(new byte[] { 1 }), ByteBuffer.wrap(new byte[] { 1, 2 }))); + } +} diff --git a/sdk/corev2/azure-core-test/src/test/java/com/azure/v2/core/test/utils/MockTokenCredentialTests.java b/sdk/corev2/azure-core-test/src/test/java/com/azure/v2/core/test/utils/MockTokenCredentialTests.java new file mode 100644 index 000000000000..fb5207924765 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/test/java/com/azure/v2/core/test/utils/MockTokenCredentialTests.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.utils; + +import io.clientcore.core.credentials.oauth.AccessToken; +import io.clientcore.core.credentials.oauth.OAuthTokenRequestContext; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Tests for {@link MockTokenCredential}. + */ +public class MockTokenCredentialTests { + + @Test + public void basicRetrieveToken() { + MockTokenCredential credential = new MockTokenCredential(); + AccessToken credentialToken = credential.getToken(new OAuthTokenRequestContext()); + assertEquals("mockToken", credentialToken.getToken()); + } +} diff --git a/sdk/corev2/azure-core-test/src/test/java/com/azure/v2/core/test/utils/TestProxyTestServer.java b/sdk/corev2/azure-core-test/src/test/java/com/azure/v2/core/test/utils/TestProxyTestServer.java new file mode 100644 index 000000000000..ae0ff8b94310 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/test/java/com/azure/v2/core/test/utils/TestProxyTestServer.java @@ -0,0 +1,205 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.test.utils; + +import org.eclipse.jetty.server.HttpConnectionFactory; +import org.eclipse.jetty.server.Request; +import org.eclipse.jetty.server.Response; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.ServerConnector; +import org.eclipse.jetty.servlet.ServletContextHandler; +import org.eclipse.jetty.servlet.ServletHolder; +import org.eclipse.jetty.util.component.AbstractLifeCycle; +import org.eclipse.jetty.util.thread.ExecutorThreadPool; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.ByteArrayOutputStream; +import java.io.Closeable; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Collections; + +/** + * A simple HTTP server for unit testing the test proxy infrastructure. + */ +public class TestProxyTestServer implements Closeable { + private final Server server; + private final ServerConnector httpConnector; + + private static final String TEST_JSON_RESPONSE_BODY = "{\"modelId\":\"0cd2728b-210e-4c05-b706-f70554276bcc\"," + + "\"createdDateTime\":\"2022-08-31T00:00:00Z\",\"apiVersion\":\"2022-08-31\"," + + " \"accountKey\" : \"secret_account_key\"," + " \"client_secret\" : \"secret_client_secret\"}"; + private static final String TEST_XML_RESPONSE_BODY = "{\"Body\":\"" + + "sensitiveInformation=\",\"primaryKey\":" + + "\"fakePrimaryKey\", \"TableName\":\"listtable09bf2a3d\"}"; + + /** + * Constructor for TestProxyTestServer + */ + public TestProxyTestServer() { + this.server = new Server(new ExecutorThreadPool(10)); + + HttpConnectionFactory httpConnectionFactory = new HttpConnectionFactory(); + httpConnector = new ServerConnector(server, httpConnectionFactory); + httpConnector.setHost("localhost"); + + server.addConnector(httpConnector); + + ServletContextHandler servletContextHandler = new ServletContextHandler(); + servletContextHandler.setContextPath("/"); + server.setHandler(servletContextHandler); + + ServletHolder servletHolder = new ServletHolder(new AzureTestHttpServlet((req, resp, requestBody) -> { + String method = req.getMethod(); + if ("GET".equalsIgnoreCase(method)) { + if ("/".equals(req.getRequestURI())) { + resp.setStatus(HttpServletResponse.SC_OK); + resp.setContentLengthLong("hello world".length()); + resp.getHttpOutput().write("hello world".getBytes(StandardCharsets.UTF_8)); + resp.getHttpOutput().flush(); + } else if ("/echoheaders".equals(req.getRequestURI())) { + resp.setStatus(HttpServletResponse.SC_OK); + Collections.list(req.getHeaderNames()) + .forEach(headerName -> resp.addHeader(headerName, req.getHeader(headerName))); + resp.setContentLengthLong("echoheaders".length()); + resp.getHttpOutput().write("echoheaders".getBytes(StandardCharsets.UTF_8)); + resp.getHttpOutput().flush(); + } else if ("/fr/path/1".equals(req.getRequestURI())) { + resp.setStatus(HttpServletResponse.SC_OK); + Collections.list(req.getHeaderNames()) + .forEach(headerName -> resp.addHeader(headerName, req.getHeader(headerName))); + resp.setContentType("application/json"); + resp.setHeader("Operation-Location", + "https://resourceInfo.cognitiveservices.azure.com/fr/models//905a58f9-131e-42b8-8410-493ab1517d62"); + resp.setContentLengthLong(TEST_JSON_RESPONSE_BODY.length()); + resp.getHttpOutput().write(TEST_JSON_RESPONSE_BODY.getBytes(StandardCharsets.UTF_8)); + resp.getHttpOutput().flush(); + } else if ("/fr/path/2".equals(req.getRequestURI())) { + resp.setStatus(HttpServletResponse.SC_OK); + resp.setContentType("application/json"); + resp.setContentLengthLong(TEST_XML_RESPONSE_BODY.length()); + resp.getHttpOutput().write(TEST_XML_RESPONSE_BODY.getBytes(StandardCharsets.UTF_8)); + resp.getHttpOutput().flush(); + } else if ("/getRedirect".equals(req.getRequestURI())) { + resp.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT); + resp.setContentType("application/json"); + resp.setHeader("Location", "http://localhost:" + port() + "/echoheaders"); + resp.getHttpOutput().flush(); + } else { + throw new RuntimeException( + "Uri doesn't match any routes. Uri: " + req.getRequestURI() + ", Method: GET"); + } + } else if ("POST".equalsIgnoreCase(method)) { + if ("/first/path".equals(req.getRequestURI())) { + resp.setStatus(HttpServletResponse.SC_OK); + resp.setContentLengthLong("first path".length()); + resp.getHttpOutput().write("first path".getBytes(StandardCharsets.UTF_8)); + resp.getHttpOutput().flush(); + } else if ("/post".equals(req.getRequestURI())) { + resp.setStatus(HttpServletResponse.SC_OK); + resp.getHttpOutput().flush(); + } else { + throw new RuntimeException( + "Uri doesn't match any routes. Uri: " + req.getRequestURI() + ", Method: POST"); + } + } else { + throw new RuntimeException( + "Uri doesn't match any routes. Uri: " + req.getRequestURI() + ", Method: " + method); + } + })); + + servletContextHandler.addServlet(servletHolder, "/"); + + try { + server.start(); + while (!hasServerStarted(server)) { + Thread.sleep(1000); // Wait until the server has actually started. + } + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private static final class AzureTestHttpServlet extends HttpServlet { + private final RequestHandler requestHandler; + + private AzureTestHttpServlet(RequestHandler requestHandler) { + this.requestHandler = requestHandler; + } + + @Override + protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + byte[] requestBody = fullyReadRequest(req.getInputStream()); + requestHandler.handle((Request) req, (Response) resp, requestBody); + } + } + + /** + * Handler that will be used to process requests. + */ + public interface RequestHandler { + /** + * Handles the request. + * + * @param req The request. + * @param resp The response. + * @param requestBody The request body. + * @throws IOException If an IO error occurs. + * @throws ServletException If a servlet error occurs. + */ + void handle(Request req, Response resp, byte[] requestBody) throws IOException, ServletException; + } + + private static byte[] fullyReadRequest(InputStream requestBody) throws IOException { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + + byte[] buffer = new byte[8192]; + int read; + + while ((read = requestBody.read(buffer, 0, buffer.length)) != -1) { + outputStream.write(buffer, 0, read); + } + + return outputStream.toByteArray(); + } + + private static boolean hasServerStarted(Server server) { + String serverState = server.getState(); + + if (serverState.equals(AbstractLifeCycle.FAILED) + || serverState.equals(AbstractLifeCycle.STOPPING) + || serverState.equals(AbstractLifeCycle.STOPPED)) { + throw new RuntimeException( + "Server state has reached an unexpected state while waiting for it to start: " + serverState); + } + + return serverState.equals(AbstractLifeCycle.STARTED) || serverState.equals(AbstractLifeCycle.RUNNING); + } + + /** + * Get the port of the server. + * + * @return The port of the server. + */ + public int port() { + return httpConnector.getLocalPort(); + } + + @Override + public void close() { + try { + if (server.isRunning()) { + server.stop(); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/sdk/corev2/azure-core-test/src/test/resources/GetContainerACLs.xml b/sdk/corev2/azure-core-test/src/test/resources/GetContainerACLs.xml new file mode 100644 index 000000000000..c7a98eae476f --- /dev/null +++ b/sdk/corev2/azure-core-test/src/test/resources/GetContainerACLs.xml @@ -0,0 +1,16 @@ + + + + + + MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI= + + 2009-09-28T08:49:37.0000000Z + 2009-09-29T08:49:37.0000000Z + rwd + + + diff --git a/sdk/corev2/azure-core-test/src/test/resources/GetXMLWithAttributes.xml b/sdk/corev2/azure-core-test/src/test/resources/GetXMLWithAttributes.xml new file mode 100644 index 000000000000..5b6233c14ac9 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/test/resources/GetXMLWithAttributes.xml @@ -0,0 +1,21 @@ + + + + + + Wake up to WonderWidgets! + + + + Overview + Why WonderWidgets are great + + Who buys WonderWidgets + + diff --git a/sdk/corev2/azure-core-test/src/test/resources/upload.txt b/sdk/corev2/azure-core-test/src/test/resources/upload.txt new file mode 100644 index 000000000000..ff3bb63948b4 --- /dev/null +++ b/sdk/corev2/azure-core-test/src/test/resources/upload.txt @@ -0,0 +1 @@ +The quick brown fox jumps over the lazy dog \ No newline at end of file diff --git a/sdk/corev2/azure-core/CHANGELOG.md b/sdk/corev2/azure-core/CHANGELOG.md new file mode 100644 index 000000000000..b8756050e2b6 --- /dev/null +++ b/sdk/corev2/azure-core/CHANGELOG.md @@ -0,0 +1,12 @@ +# Release History + +## 2.0.0-beta.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + diff --git a/sdk/corev2/azure-core/README.md b/sdk/corev2/azure-core/README.md new file mode 100644 index 000000000000..bc0434cd1f2c --- /dev/null +++ b/sdk/corev2/azure-core/README.md @@ -0,0 +1,57 @@ +# Azure Core V2 shared library for Java + +[![Build Documentation](https://img.shields.io/badge/documentation-published-blue.svg)](https://azure.github.io/azure-sdk-for-java) + +Azure Core V2 provides shared primitives, abstractions, and helpers for modern Java Azure SDK client libraries. + +## Getting started + +### Prerequisites + +- A [Java Development Kit (JDK)][jdk_link], version 8 or later. + +### Include the package + +#### Include direct dependency + +If you want to take dependency on a particular version of the library that is not present in the BOM, +add the direct dependency to your project as follows. + +[//]: # ({x-version-update-start;com.azure.v2:azure-core;current}) +```xml + + com.azure.v2 + azure-core + 2.0.0-beta.1 + +``` +[//]: # ({x-version-update-end}) + +## Key concepts + +## Examples + +## Next steps + +## Troubleshooting + +If you encounter any bugs, please file issues +via [GitHub Issues](https://github.com/Azure/azure-sdk-for-java/issues/new/choose) +or checkout [StackOverflow for Azure Java SDK](https://stackoverflow.com/questions/tagged/azure-java-sdk). + +## Contributing + +For details on contributing to this repository, see +the [contributing guide](https://github.com/Azure/azure-sdk-for-java/blob/main/CONTRIBUTING.md). + +1. Fork it +2. Create your feature branch (`git checkout -b my-new-feature`) +3. Commit your changes (`git commit -am 'Add some feature'`) +4. Push to the branch (`git push origin my-new-feature`) +5. Create new Pull Request + + + +[jdk_link]: https://learn.microsoft.com/java/azure/jdk/?view=azure-java-stable + + diff --git a/sdk/corev2/azure-core/checkstyle-suppressions.xml b/sdk/corev2/azure-core/checkstyle-suppressions.xml new file mode 100644 index 000000000000..eba855f52f2e --- /dev/null +++ b/sdk/corev2/azure-core/checkstyle-suppressions.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/sdk/corev2/azure-core/pom.xml b/sdk/corev2/azure-core/pom.xml new file mode 100644 index 000000000000..82a0c98c8d68 --- /dev/null +++ b/sdk/corev2/azure-core/pom.xml @@ -0,0 +1,174 @@ + + + 4.0.0 + + com.azure.v2 + azure-client-sdk-parent + 2.0.0-beta.1 + ../../parents/azure-client-sdk-parent-v2/pom.xml + + + com.azure.v2 + azure-core + jar + 2.0.0-beta.1 + + Microsoft Azure Java Core V2 Library + This package contains core types for Azure Java V2 clients. + https://github.com/Azure/azure-sdk-for-java + + + + The MIT License (MIT) + http://opensource.org/licenses/MIT + repo + + + + + + azure-java-build-docs + ${site.url}/site/${project.artifactId} + + + + + https://github.com/Azure/azure-sdk-for-java + scm:git:https://github.com/Azure/azure-sdk-for-java.git + scm:git:https://github.com/Azure/azure-sdk-for-java.git + + + + UTF-8 + + 0.60 + 0.60 + + + + + **/generated/**/*.java + + + + io.clientcore.core + + + true + + + true + + + + + microsoft + Microsoft + + + + + + io.clientcore + core + 1.0.0-beta.7 + + + + org.junit.jupiter + junit-jupiter-api + 5.11.2 + test + + + org.junit.jupiter + junit-jupiter-engine + 5.11.2 + test + + + org.junit.jupiter + junit-jupiter-params + 5.11.2 + test + + + org.hamcrest + hamcrest-library + 2.2 + test + + + org.openjdk.jmh + jmh-core + 1.37 + test + + + org.openjdk.jmh + jmh-generator-annprocess + 1.37 + test + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.4.2 + + + test-jar + test-compile + + test-jar + + + + + + + + + + jmh-benchmark + + + jmh-benchmark + + + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.13.0 + + + + + org.openjdk.jmh + jmh-generator-annprocess + 1.37 + + + + + + + + + diff --git a/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/credentials/AzureSasCredential.java b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/credentials/AzureSasCredential.java new file mode 100644 index 000000000000..851360fa909e --- /dev/null +++ b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/credentials/AzureSasCredential.java @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.credentials; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.instrumentation.logging.ClientLogger; + +import java.util.Objects; +import java.util.function.Function; + +/** + *

        + * Represents a credential that uses a shared access signature to authenticate to an Azure Service. + * It is used for authenticating and authorizing access to Azure services using a shared access signature. + *

        + * + *

        + * A shared access signature is a string-based token that grants limited permissions and access to specific + * resources within an Azure service for a specified period. It allows you to provide time-limited access to your + * resources without sharing your account key or other sensitive credentials. + *

        + * + *

        + * The {@link AzureSasCredential} enables you to authenticate and access Azure services that + * support shared access signatures. By creating an instance of the {@link AzureSasCredential} class and providing the + * SAS token as a parameter, you can use this credential to authenticate requests to Azure services. + *

        + * + *

        + * To use the Credential, you typically pass it to the appropriate Azure client or service client + * builder during instantiation. The library internally handles the authentication process and includes the + * SAS token in the HTTP requests made to the Azure service, allowing you to access the resources specified in + * the SAS token. + *

        + * + *

        + * The {@link AzureSasCredential} is particularly useful when you need to grant temporary and limited access to + * specific resources, such as Azure Storage containers, blobs, queues, or files, without exposing + * your account key. + *

        + * + *

        + * It's important to note that the availability and usage of the {@link AzureSasCredential} may depend on the + * specific Azure service and its support for shared access signatures. Additionally, the format and content of the + * SAS token may vary depending on the service and resource you are targeting. + *

        + * + *

        + * Sample: Azure SAS Authentication + *

        + * + *

        + * The following code sample demonstrates the creation of a {@link AzureSasCredential}, + * using the sas token to configure it. + *

        + * + * + * + * + * @see com.azure.v2.core.credentials + */ +@Metadata(properties = MetadataProperties.FLUENT) +public final class AzureSasCredential { + // AzureSasCredential is a commonly used credential type, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(AzureSasCredential.class); + private final Function signatureEncoder; + + private volatile String signature; + + /** + * Creates a credential that authorizes request with the given shared access signature. + *

        + * The {@code signature} passed is assumed to be encoded. This constructor is effectively the same as calling {@link + * #AzureSasCredential(String, Function) new AzureSasCredential(signature, null))}. + * + * @param signature The shared access signature used to authorize requests. + * @throws NullPointerException If {@code signature} is {@code null}. + * @throws IllegalArgumentException If {@code signature} is an empty string. + */ + public AzureSasCredential(String signature) { + this(signature, null); + } + + /** + * Creates a credential that authorizes request within the given shared access signature. + *

        + * If {@code signatureEncoder} is non-null the {@code signature}, and all {@link #update(String) updated + * signatures}, will be encoded using the function. {@code signatureEncoder} should be as idempotent as possible to + * reduce the chance of double encoding errors. + * + * @param signature The shared access signature used to authorize requests. + * @param signatureEncoder An optional function which encodes the {@code signature}. + * @throws NullPointerException If {@code signature} is {@code null}. + * @throws IllegalArgumentException If {@code signature} is an empty string. + */ + public AzureSasCredential(String signature, Function signatureEncoder) { + Objects.requireNonNull(signature, "'signature' cannot be null."); + if (signature.isEmpty()) { + throw LOGGER.logThrowableAsError(new IllegalArgumentException("'signature' cannot be empty.")); + } + + this.signatureEncoder = signatureEncoder; + this.signature = (signatureEncoder == null) ? signature : signatureEncoder.apply(signature); + } + + /** + * Retrieves the shared access signature associated to this credential. + * + * @return The shared access signature being used to authorize requests. + */ + public String getSignature() { + return signature; + } + + /** + * Rotates the shared access signature associated to this credential. + * + * @param signature The new shared access signature to be associated with this credential. + * @return The updated {@code AzureSasCredential} object. + * @throws NullPointerException If {@code signature} is {@code null}. + * @throws IllegalArgumentException If {@code signature} is an empty string. + */ + public AzureSasCredential update(String signature) { + Objects.requireNonNull(signature, "'signature' cannot be null."); + if (signature.isEmpty()) { + throw LOGGER.logThrowableAsError(new IllegalArgumentException("'signature' cannot be empty.")); + } + + this.signature = (signatureEncoder == null) ? signature : signatureEncoder.apply(signature); + return this; + } +} diff --git a/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/credentials/TokenCredential.java b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/credentials/TokenCredential.java new file mode 100644 index 000000000000..3265be16c381 --- /dev/null +++ b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/credentials/TokenCredential.java @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.credentials; + +import io.clientcore.core.credentials.oauth.AccessToken; + +/** + *

        + * The Token Credential interface serves as a fundamental component for managing and providing access tokens. + *

        + * + *

        + * The {@link TokenCredential#getToken(TokenRequestContext)} method is responsible for retrieving an access token that + * can be used for bearer token authentication. The scopes parameter specified as part of {@link TokenRequestContext} + * represents the resources or permissions required for the token. + *

        + * + *

        + * By utilizing the Token Credential interface, you can abstract the authentication logic away from your + * application code. This allows for flexibility in choosing authentication mechanisms and simplifies the management + * of access tokens, including token caching and refreshing. + *

        + * + * @see io.clientcore.core.credentials + */ +@FunctionalInterface +public interface TokenCredential { + + /** + * Get a token for a given resource/audience. + * You may call this method directly, but you must also handle token caching and token refreshing. + * + * @param request the details of the token request + * @return The Access Token + */ + AccessToken getToken(TokenRequestContext request); +} diff --git a/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/credentials/TokenRequestContext.java b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/credentials/TokenRequestContext.java new file mode 100644 index 000000000000..57fcff7bd019 --- /dev/null +++ b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/credentials/TokenRequestContext.java @@ -0,0 +1,181 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.credentials; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.utils.CoreUtils; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; + +/** + *

        + * The {@link TokenRequestContext} is a class used to provide additional information and context when requesting an + * access token from an authentication source. It allows you to customize the token request and specify additional + * parameters, such as scopes, claims, or authentication options. + *

        + * + *

        + * The {@link TokenRequestContext} is typically used with authentication mechanisms that require more advanced + * configurations or options, such as + * Microsoft Entra ID authentication. + *

        + * + *

        + * Here's a high-level overview of how you can use the {@link TokenRequestContext}: + *

        + * + *
          + *
        1. Create an instance of the {@link TokenRequestContext} class and configure the required properties. + * The {@link TokenRequestContext} class allows you to specify the scopes or resources for which you want to request + * an access token, as well as any additional claims or options.
        2. + * + *
        3. Pass the TokenRequestContext instance to the appropriate authentication client or mechanism when + * requesting an access token. The specific method or API to do this will depend on the authentication mechanism + * you are using. For example, if you are using Azure Identity for Microsoft Entra authentication, you would pass the + * TokenRequestContext instance to the getToken method of the {@link TokenCredential} implementation.
        4. + * + *
        5. The authentication client or mechanism will handle the token request and return an access token that can + * be used to authenticate and authorize requests to Azure services.
        6. + *
        + * + * @see com.azure.v2.core.credentials + * @see TokenCredential + */ +@Metadata(properties = MetadataProperties.FLUENT) +public class TokenRequestContext { + private static final ClientLogger LOGGER = new ClientLogger(TokenRequestContext.class); + private final List scopes; + private String claims; + private String tenantId; + private boolean enableCae; + + /** + * Creates a token request instance. + */ + public TokenRequestContext() { + this.scopes = new ArrayList<>(); + } + + /** + * Gets the scopes required for the token. + * @return the scopes required for the token + */ + public List getScopes() { + return scopes; + } + + /** + * Sets the scopes required for the token. + * @param scopes the scopes required for the token + * @return the TokenRequestContext itself + */ + public TokenRequestContext setScopes(List scopes) { + Objects.requireNonNull(scopes, "'scopes' cannot be null."); + this.scopes.clear(); + this.scopes.addAll(scopes); + return this; + } + + /** + * Adds one or more scopes to the request scopes. + * @param scopes one or more scopes to add + * @return the TokenRequestContext itself + * @throws IllegalArgumentException if scopes list is empty or any of the provided is null or empty. + * @throws NullPointerException if scopes is null. + */ + public TokenRequestContext addScopes(String... scopes) { + Objects.requireNonNull(scopes, "The scopes parameter cannot be null."); + + if (scopes.length == 0) { + throw LOGGER.logThrowableAsError(new IllegalArgumentException("At least one scope must be provided.")); + } + + for (String scope : scopes) { + if (CoreUtils.isNullOrEmpty(scope)) { + throw LOGGER + .logThrowableAsError(new IllegalArgumentException("Scopes cannot contain null or empty values.")); + } + } + this.scopes.addAll(Arrays.asList(scopes)); + return this; + } + + /** + * Set the additional claims to be included in the token. + * + * @see + * https://openid.net/specs/openid-connect-core-1_0-final.html#ClaimsParameter + * + * @param claims the additional claims to be included in the token. + * @return the updated TokenRequestContext itself + */ + public TokenRequestContext setClaims(String claims) { + this.claims = claims; + return this; + } + + /** + * Get the additional claims to be included in the token. + * + * @see + * https://openid.net/specs/openid-connect-core-1_0-final.html#ClaimsParameter + * + * @return the additional claims to be included in the token. + */ + public String getClaims() { + return this.claims; + } + + /** + * Set the tenant id to be used for the authentication request. + * + * @param tenantId the tenant to be used when requesting the token. + * @return the updated TokenRequestContext itself + */ + public TokenRequestContext setTenantId(String tenantId) { + this.tenantId = tenantId; + return this; + } + + /** + * Get the tenant id to be used for the authentication request. + * + * @return the configured tenant id. + */ + public String getTenantId() { + return this.tenantId; + } + + /** + * Indicates whether to enable Continuous Access Evaluation (CAE) for the requested token. + * + *

        If a resource API implements CAE and your application declares it can handle CAE, your app receives + * CAE tokens for that resource. For this reason, if you declare your app CAE ready, your application must handle + * the CAE claim challenge for all resource APIs that accept Microsoft Identity access tokens. If you don't handle + * CAE responses in these API calls, your app could end up in a loop retrying an API call with a token that is + * still in the returned lifespan of the token but has been revoked due to CAE.

        + * + * @param enableCae the flag indicating whether to enable Continuous Access Evaluation (CAE) for + * the requested token. + * @return the updated TokenRequestContext. + */ + public TokenRequestContext setCaeEnabled(boolean enableCae) { + this.enableCae = enableCae; + return this; + } + + /** + * Get the status indicating whether Continuous Access Evaluation (CAE) is enabled for the requested token. + * + * @return the flag indicating whether CAE authentication should be used or not. + */ + public boolean isCaeEnabled() { + return this.enableCae; + } +} diff --git a/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/credentials/package-info.java b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/credentials/package-info.java new file mode 100644 index 000000000000..e88a6decb81a --- /dev/null +++ b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/credentials/package-info.java @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + *

        + * Azure Core Credential library is designed to simplify the process of authenticating and authorizing access + * to Azure services from Java applications. The SDK provides a set of classes and methods that handle authentication + * and credential management, allowing developers to securely connect to Azure services without dealing with the + * low-level details of authentication protocols. + *

        + * + *

        + * The library provides a unified way to obtain credentials for various Azure authentication + * mechanisms, such as Azure Active Directory (AAD), shared access signatures, and API keys. It abstracts the + * complexities of authentication and provides a consistent programming model for accessing Azure services. + *

        + * + *

        + * By using the library, users can easily integrate Azure authentication into their applications, retrieve the + * required credentials based on the desired authentication method, and use those credentials to authenticate + * requests to Azure services like Azure Storage, Azure Key Vault, Azure Service Bus, and more. + *

        + * + *

        + * The library offers several authentication types for authenticating with Azure services. Here are some of the + * authentication mechanisms supported by the library: + *

        + *
          + *
        • Azure Active Directory (AAD) Authentication
        • + *
        • Shared Access Signature (SAS) Authentication
        • + *
        • Key Based Authentication
        • + *
        + * + *

        Azure Active Directory (AAD) Authentication

        + * + *

        + * This type of authentication allows you to authenticate using Azure Active Directory and obtain a token to access + * Azure resources. You can authenticate with AAD using client secrets, client certificates, or user credentials. + * The library offers {@link com.azure.v2.core.credentials.TokenCredential} interface which is accepted as an argument + * on the client builders in Azure SDKs where AAD authentication is supported. + * You can refer to and include our + * Azure + * Identity + * library in your application as it offers pluggable implementation of + * {@link com.azure.v2.core.credentials.TokenCredential} for various AAD based authentication mechanism including + * service principal, managed identity, and more. + *

        + * + *
        + * + *
        + * + *

        Shared Access Signature (SAS) Authentication

        + * + *

        + * Shared Access Signatures enable you to grant time-limited access to Azure resources. The library offers + * {@link com.azure.v2.core.credentials.AzureSasCredential} which allows you to authenticate using a shared access + * signature, which is a string-based token that grants access to specific resources for a specific period. + *

        + * + *

        + * Sample: Azure SAS Authentication + *

        + * + *

        + * The following code sample demonstrates the creation of a {@link com.azure.v2.core.credentials.AzureSasCredential}, + * using the sas token to configure it. + *

        + * + * + * + * + * + * @see com.azure.v2.core.credentials.AzureSasCredential + * @see com.azure.v2.core.credentials.TokenCredential + */ +package com.azure.v2.core.credentials; diff --git a/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/http/pipeline/AzureSasCredentialPolicy.java b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/http/pipeline/AzureSasCredentialPolicy.java new file mode 100644 index 000000000000..f963029e51f5 --- /dev/null +++ b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/http/pipeline/AzureSasCredentialPolicy.java @@ -0,0 +1,102 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.http.pipeline; + +import com.azure.v2.core.credentials.AzureSasCredential; +import io.clientcore.core.http.pipeline.HttpCredentialPolicy; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.http.pipeline.HttpPipeline; +import io.clientcore.core.http.pipeline.HttpPipelineNextPolicy; +import io.clientcore.core.http.pipeline.HttpPipelinePolicy; +import io.clientcore.core.models.binarydata.BinaryData; + +import java.util.Objects; + +/** + * The {@code AzureSasCredentialPolicy} class is an implementation of the {@link HttpPipelinePolicy} interface. This + * policy uses an {@link AzureSasCredential} to append a shared access signature (SAS) to the query string of a + * request. + * + *

        This class is useful when you need to authorize requests with a SAS from Azure. It ensures that the requests are + * sent over HTTPS to prevent the SAS from being leaked.

        + * + *

        Code sample:

        + * + *

        In this example, an {@code AzureSasCredentialPolicy} is created with a SAS. The policy can then added to the + * pipeline. The request sent by the pipeline will then include the SAS appended to its query string.

        + * + * + * + * @see com.azure.v2.core.http.pipeline + * @see HttpPipelinePolicy + * @see AzureSasCredential + * @see HttpPipeline + * @see HttpRequest + * @see Response + */ +public final class AzureSasCredentialPolicy extends HttpCredentialPolicy { + private static final ClientLogger LOGGER = new ClientLogger(AzureSasCredentialPolicy.class); + private final AzureSasCredential credential; + private final boolean requireHttps; + + /** + * Creates a policy that uses the passed {@link AzureSasCredential} to append sas to query string. + *

        + * Requests sent with this pipeline policy are required to use {@code HTTPS}. If the request isn't using + * {@code HTTPS} an exception will be thrown to prevent leaking the shared access signature. + * + * @param credential The {@link AzureSasCredential} containing the shared access signature to use. + * + * @throws NullPointerException If {@code credential} is {@code null}. + */ + public AzureSasCredentialPolicy(AzureSasCredential credential) { + this(credential, true); + } + + /** + * Creates a policy that uses the passed {@link AzureSasCredential} to append sas to query string. + * + * @param credential The {@link AzureSasCredential} containing the shared access signature to use. + * @param requireHttps A flag indicating whether {@code HTTPS} is required. + * + * @throws NullPointerException If {@code credential} is {@code null}. + */ + public AzureSasCredentialPolicy(AzureSasCredential credential, boolean requireHttps) { + Objects.requireNonNull(credential, "'credential' cannot be null."); + this.credential = credential; + this.requireHttps = requireHttps; + } + + @Override + public Response process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { + + if (requireHttps && !"https".equals(httpRequest.getUri().getScheme())) { + throw LOGGER.logThrowableAsError( + new IllegalStateException("Shared access signature credentials require HTTPS to prevent leaking" + + " the shared access signature.")); + } + + String signature = credential.getSignature(); + if (signature.startsWith("?")) { + signature = signature.substring(1); + } + + String query = httpRequest.getUri().getQuery(); + String url = httpRequest.getUri().toString(); + if (query == null || query.isEmpty()) { + if (url.endsWith("?")) { + url = url + signature; + } else { + url = url + "?" + signature; + } + } else { + url = url + "&" + signature; + } + httpRequest.setUri(url); + + return next.process(); + } +} diff --git a/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/http/pipeline/BearerTokenAuthenticationPolicy.java b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/http/pipeline/BearerTokenAuthenticationPolicy.java new file mode 100644 index 000000000000..f07e1e9ce497 --- /dev/null +++ b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/http/pipeline/BearerTokenAuthenticationPolicy.java @@ -0,0 +1,214 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.http.pipeline; + +import com.azure.v2.core.credentials.TokenCredential; +import com.azure.v2.core.credentials.TokenRequestContext; +import com.azure.v2.core.implementation.AccessTokenCache; +import io.clientcore.core.credentials.oauth.AccessToken; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.http.pipeline.HttpCredentialPolicy; +import io.clientcore.core.http.pipeline.HttpPipeline; +import io.clientcore.core.http.pipeline.HttpPipelineNextPolicy; +import io.clientcore.core.http.pipeline.HttpPipelinePolicy; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.instrumentation.logging.LogLevel; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.utils.AuthUtils; +import io.clientcore.core.utils.AuthenticateChallenge; +import io.clientcore.core.utils.CoreUtils; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.List; +import java.util.Objects; + +/** + *

        The {@code BearerTokenAuthenticationPolicy} class is an implementation of the + * {@link HttpCredentialPolicy}. This policy uses a {@link TokenCredential} to authenticate the request with + * a bearer token.

        + * + *

        This class is useful when you need to authorize requests with a bearer token from Azure. It ensures that the + * requests are sent over HTTPS to prevent the token from being leaked.

        + * + *

        Code sample:

        + * + *

        In this example, a {@code BearerTokenAuthenticationPolicy} is created with a {@link TokenCredential} and a scope. + * The policy can then added to the pipeline. The request sent via the pipeline will then include the + * Authorization header with the bearer token.

        + * + *
        + * TokenCredential credential = new BasicAuthenticationCredential("username", "password");
        + * BearerTokenAuthenticationPolicy policy = new BearerTokenAuthenticationPolicy(credential,
        + *     "https://management.azure.com/.default");
        + * 
        + * + * @see HttpPipelinePolicy + * @see TokenCredential + * @see HttpPipeline + * @see HttpRequest + * @see Response + */ +public class BearerTokenAuthenticationPolicy extends HttpCredentialPolicy { + private static final ClientLogger LOGGER = new ClientLogger(BearerTokenAuthenticationPolicy.class); + private static final String BEARER = "Bearer"; + + private final String[] scopes; + private final AccessTokenCache cache; + + /** + * Creates BearerTokenAuthenticationPolicy. + * + * @param credential the token credential to authenticate the request + * @param scopes the scopes of authentication the credential should get token for + */ + public BearerTokenAuthenticationPolicy(TokenCredential credential, String... scopes) { + Objects.requireNonNull(credential); + this.scopes = scopes; + this.cache = new AccessTokenCache(credential); + } + + /** + * Executed before sending the initial request and authenticates the request. + * + * @param httpRequest The request context. + */ + public void authorizeRequest(HttpRequest httpRequest) { + setAuthorizationHeaderHelper(httpRequest, new TokenRequestContext().addScopes(scopes).setCaeEnabled(true), + false); + } + + /** + * Handles the authentication challenge in the event a 401 response with a WWW-Authenticate authentication challenge + * header is received after the initial request and returns appropriate {@link TokenRequestContext} to be used for + * re-authentication. + *

        + * The default implementation will attempt to handle Continuous Access Evaluation (CAE) challenges. + *

        + * + * @param httpRequest The http request. + * @param response The Http Response containing the authentication challenge header. + * @return A boolean indicating if the request was authorized again via re-authentication + */ + public boolean authorizeRequestOnChallenge(HttpRequest httpRequest, Response response) { + if (isCaeClaimsChallenge(response)) { + TokenRequestContext tokenRequestContext = getTokenRequestContextForCaeChallenge(response); + if (tokenRequestContext != null) { + setAuthorizationHeader(httpRequest, tokenRequestContext); + return true; + } + } + + return false; + } + + /** + * Authorizes the request with the bearer token acquired using the specified {@code tokenRequestContext} + * + * @param request the HTTP request. + * @param tokenRequestContext the token request context to be used for token acquisition. + */ + protected void setAuthorizationHeader(HttpRequest request, TokenRequestContext tokenRequestContext) { + setAuthorizationHeaderHelper(request, tokenRequestContext, true); + } + + private void setAuthorizationHeaderHelper(HttpRequest httpRequest, TokenRequestContext tokenRequestContext, + boolean checkToForceFetchToken) { + AccessToken token = cache.getToken(tokenRequestContext, checkToForceFetchToken); + httpRequest.getHeaders().set(HttpHeaderName.AUTHORIZATION, BEARER + " " + token); + } + + @Override + public Response process(HttpRequest httpRequest, HttpPipelineNextPolicy next) { + if (!"https".equals(httpRequest.getUri().getScheme())) { + throw LOGGER.logThrowableAsError( + new RuntimeException("token credentials require a URL using the HTTPS protocol scheme")); + } + + HttpPipelineNextPolicy nextPolicy = next.copy(); + + authorizeRequest(httpRequest); + Response httpResponse = next.process(); + String authHeader = httpResponse.getHeaders().getValue(HttpHeaderName.WWW_AUTHENTICATE); + if (httpResponse.getStatusCode() == 401 && authHeader != null) { + if (authorizeRequestOnChallenge(httpRequest, httpResponse)) { + // body needs to be closed or read to the end to release the connection + try { + httpResponse.close(); + } catch (IOException e) { + throw LOGGER.logThrowableAsError(new RuntimeException(e)); + } + return nextPolicy.process(); + } else { + return httpResponse; + } + } + return httpResponse; + } + + private TokenRequestContext getTokenRequestContextForCaeChallenge(Response response) { + String decodedClaims = null; + String encodedClaims = getChallengeParameterFromResponse(response, "Bearer", "claims"); + + if (!CoreUtils.isNullOrEmpty(encodedClaims)) { + try { + decodedClaims = new String(Base64.getDecoder().decode(encodedClaims), StandardCharsets.UTF_8); + } catch (IllegalArgumentException e) { + // We don't want to throw here, but we want to log this for future incident investigation. + LOGGER.atLevel(LogLevel.WARNING) + .log("Failed to decode the claims from the CAE challenge. Encoded claims: " + encodedClaims); + } + } + + if (decodedClaims == null) { + return null; + } + + return new TokenRequestContext().setClaims(decodedClaims).addScopes(scopes).setCaeEnabled(true); + } + + /** + * Examines a {@link Response} to see if it is a CAE challenge. + * @param response The {@link Response} to examine. + * @return True if the response is a CAE challenge, false otherwise. + */ + static boolean isCaeClaimsChallenge(Response response) { + List authenticateChallengeList + = AuthUtils.parseAuthenticateHeader(response.getHeaders().getValue(HttpHeaderName.WWW_AUTHENTICATE)); + + for (AuthenticateChallenge authChallenge : authenticateChallengeList) { + if (authChallenge.getScheme().equals("Bearer")) { + + String error = authChallenge.getParameters().get("error"); + String claims = authChallenge.getParameters().get("claims"); + return !CoreUtils.isNullOrEmpty(claims) && "insufficient_claims".equals(error); + } + } + return false; + } + + /** + * Gets the specified challenge parameter from the challenge response. + * + * @param response the Http response with auth challenge + * @param challengeScheme the challenge scheme to be checked + * @param parameter the challenge parameter value to get + * + * @return the extracted value of the challenge parameter + */ + static String getChallengeParameterFromResponse(Response response, String challengeScheme, String parameter) { + String challenge = response.getHeaders().getValue(HttpHeaderName.WWW_AUTHENTICATE); + List authenticateChallengeList = AuthUtils.parseAuthenticateHeader(challenge); + + for (AuthenticateChallenge authChallenge : authenticateChallengeList) { + if (authChallenge.getScheme().equals(challengeScheme)) { + return authChallenge.getParameters().get(parameter); + } + } + return null; + } +} diff --git a/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/http/pipeline/package-info.java b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/http/pipeline/package-info.java new file mode 100644 index 000000000000..2d43b44a72fe --- /dev/null +++ b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/http/pipeline/package-info.java @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * This package contains the HttpPipelinePolicy interface and its implementations. These policies are used to form an + * HTTP pipeline, which is a series of policies that are invoked to handle an HTTP request. + * + *

        The HttpPipelinePolicy interface defines process and processSync methods. These + * methods transform an HTTP request into an HttpResponse asynchronously and synchronously respectively. + * Implementations of this interface can modify the request, pass it to the next policy, and then modify the response.

        + * + *

        Code Sample:

        + * + *

        In this example, the UserAgentPolicy, RetryPolicy, and CustomPolicy are added to the pipeline. The pipeline is + * then used to send an HTTP request, and the response is retrieved.

        + * + *
        + * {@code
        + * HttpPipeline pipeline = new HttpPipelineBuilder()
        + *     .policies(new UserAgentPolicy(), new RetryPolicy(), new CustomPolicy())
        + *     .build();
        + *
        + * HttpRequest request = new HttpRequest(HttpMethod.GET, new URL("http://example.com"));
        + * Response response = pipeline.send(request).block();
        + * }
        + * 
        + * + *

        This package is crucial for the communication between Azure SDK client libraries and Azure services. It provides + * a layer of abstraction over the HTTP protocol, allowing client libraries to focus on service-specific logic.

        + * + * @see io.clientcore.core.http.pipeline.HttpPipelinePolicy + * @see io.clientcore.core.http.pipeline.HttpInstrumentationOptions.HttpLogLevel + * @see io.clientcore.core.http.pipeline.HttpInstrumentationOptions + * @see io.clientcore.core.http.pipeline.HttpInstrumentationPolicy + * @see io.clientcore.core.http.pipeline.HttpPipelinePolicy + * @see io.clientcore.core.http.pipeline.HttpRetryPolicy + * @see io.clientcore.core.http.pipeline.UserAgentPolicy + */ +package com.azure.v2.core.http.pipeline; diff --git a/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/implementation/AccessTokenCache.java b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/implementation/AccessTokenCache.java new file mode 100644 index 000000000000..f58b8ee95e62 --- /dev/null +++ b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/implementation/AccessTokenCache.java @@ -0,0 +1,176 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.implementation; + +import com.azure.v2.core.credentials.TokenCredential; +import com.azure.v2.core.credentials.TokenRequestContext; +import io.clientcore.core.credentials.oauth.AccessToken; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.instrumentation.logging.LogLevel; + +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Objects; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +/** + * A token cache that supports caching a token and refreshing it. + */ +public final class AccessTokenCache { + // The delay after a refresh to attempt another token refresh + private static final Duration REFRESH_DELAY = Duration.ofSeconds(30); + private static final String REFRESH_DELAY_STRING = String.valueOf(REFRESH_DELAY.getSeconds()); + + // the offset before token expiry to attempt proactive token refresh + private static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); + // AccessTokenCache is a commonly used class, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(AccessTokenCache.class); + private volatile AccessTokenCacheInfo cacheInfo; + private final TokenCredential tokenCredential; + // Stores the last authenticated token request context. The cached token is valid under this context. + private TokenRequestContext tokenRequestContext; + + // Used for sync flow. + private final Lock lock; + + /** + * Creates an instance of AccessTokenCache. + * + * @param tokenCredential the token credential to be used to acquire the token. + */ + public AccessTokenCache(TokenCredential tokenCredential) { + Objects.requireNonNull(tokenCredential, "The token credential cannot be null"); + this.tokenCredential = tokenCredential; + this.cacheInfo = new AccessTokenCacheInfo(null, OffsetDateTime.now()); + this.lock = new ReentrantLock(); + } + + private boolean checkIfRefreshIsNeeded(AccessToken accessToken) { + return OffsetDateTime.now() + .isAfter(accessToken.getRefreshAt() == null + ? accessToken.getExpiresAt().minus(REFRESH_OFFSET) + : accessToken.getRefreshAt()); + } + + /** + * Get a token from either the cache or replenish the cache with a new token. + * + * @param tokenRequestContext The request context for token acquisition. + * @param checkToForceFetchToken The flag indicating whether to force fetch a new token or not. + * @return The Publisher that emits an AccessToken + */ + public AccessToken getToken(TokenRequestContext tokenRequestContext, boolean checkToForceFetchToken) { + lock.lock(); + try { + return retrieveToken(tokenRequestContext, checkToForceFetchToken); + } finally { + lock.unlock(); + } + } + + private AccessToken retrieveToken(TokenRequestContext tokenRequestContext, boolean forceFetchToken) { + if (tokenRequestContext == null) { + throw LOGGER + .logThrowableAsError(new IllegalArgumentException("The token request context input cannot be null.")); + } + + AccessTokenCacheInfo cache = this.cacheInfo; + AccessToken cachedToken = cache.getCachedAccessToken(); + + boolean needsRefresh = determineRefreshRequirement(tokenRequestContext, forceFetchToken, cachedToken); + + if (!needsRefresh) { + return cachedToken; + } + + return attemptTokenRefresh(cachedToken, tokenRequestContext); + } + + private boolean determineRefreshRequirement(TokenRequestContext tokenRequestContext, boolean forceFetchToken, + AccessToken cachedToken) { + + if (cachedToken == null || cachedToken.isExpired()) { + return true; + } + + if (forceFetchToken && checkIfTokenRequestsAreDifferent(tokenRequestContext)) { + this.tokenRequestContext = tokenRequestContext; + return true; + } + + if (!checkIfRefreshIsNeeded(cachedToken)) { + return false; + } + + return OffsetDateTime.now().isAfter(this.cacheInfo.getNextTokenRefreshAt()); + } + + private AccessToken attemptTokenRefresh(AccessToken cachedToken, TokenRequestContext tokenRequestContext) { + try { + AccessToken newToken = getToken(tokenRequestContext); + logTokenRefresh(LogLevel.VERBOSE, cachedToken, "Acquired a new access token."); + + this.cacheInfo = new AccessTokenCacheInfo(newToken, OffsetDateTime.now().plus(REFRESH_DELAY)); + return newToken; + + } catch (Throwable error) { + logTokenRefresh(LogLevel.ERROR, cachedToken, "Failed to acquire a new access token."); + this.cacheInfo = new AccessTokenCacheInfo(cachedToken, OffsetDateTime.now()); + + if (cachedToken != null) { + return cachedToken; + } + throw error; + } + } + + private boolean checkIfTokenRequestsAreDifferent(TokenRequestContext tokenRequestContext) { + return !(this.tokenRequestContext != null + && (this.tokenRequestContext.getClaims() == null + ? tokenRequestContext.getClaims() == null + : (tokenRequestContext.getClaims() != null + && tokenRequestContext.getClaims().equals(this.tokenRequestContext.getClaims()))) + && this.tokenRequestContext.getScopes().equals(tokenRequestContext.getScopes())); + } + + private static void logTokenRefresh(LogLevel level, AccessToken cache, String prefix) { + if (cache == null || !LOGGER.canLogAtLevel(level)) { + return; + } + + Duration tte = getDurationUntilExpiration(cache); + + LOGGER.atLevel(level) + .log(String.format("%s. expiresAt: %s, tteSeconds: %s, retryAfterSeconds: %s, expired: %s", prefix, + cache.getExpiresAt(), tte.abs().getSeconds(), REFRESH_DELAY_STRING, tte.isNegative())); + } + + private AccessToken getToken(TokenRequestContext tokenRequestContext) { + return this.tokenCredential.getToken(tokenRequestContext); + } + + /** + * Gets the {@link Duration} until the {@link AccessToken} expires. + *

        + * The {@link Duration} is based on the {@link OffsetDateTime#now() current time} and may return a negative + * {@link Duration}, indicating that the {@link AccessToken} has expired. + * + * @return The {@link Duration} until the {@link AccessToken} expires. + */ + private static Duration getDurationUntilExpiration(AccessToken accessToken) { + // Call Duration.between with the 'cache.getExpiresAt' as the start Temporal and 'now' as the end Temporal as + // some TokenCredential implementations may use 'OffsetDateTime.MAX' as the expiration time. When comparing the + // time between now and 'OffsetDateTime.MAX', depending on the Java version, it may attempt to change the end + // Temporal's time zone to match the start Temporal's time zone. Since 'OffsetDateTime.MAX' uses the most + // minimal time zone offset, if the now time is using anything before that it will result in + // 'OffsetDateTime.MAX' needing to roll over its time to the next day which results in the 'year' value being + // incremented to a value outside the 'year' bounds allowed by OffsetDateTime. + // + // Changing to having the 'cache.getExpiresAt' means it is impossible for this rollover to occur as the start + // Temporal doesn't have its time zone modified. But it now means the time between value is inverted, so the + // result is 'negated()' to maintain current behaviors. + return Duration.between(accessToken.getExpiresAt(), OffsetDateTime.now()).negated(); + } +} diff --git a/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/implementation/AccessTokenCacheInfo.java b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/implementation/AccessTokenCacheInfo.java new file mode 100644 index 000000000000..04840b40688b --- /dev/null +++ b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/implementation/AccessTokenCacheInfo.java @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.implementation; + +import io.clientcore.core.credentials.oauth.AccessToken; + +import java.time.OffsetDateTime; + +/** + * The Access Token Cache Info holds the metadata used by {@link AccessTokenCache} to proactively refresh the token. + */ +public class AccessTokenCacheInfo { + private final AccessToken cache; + private final OffsetDateTime nextTokenRefreshAt; + + /** + * Create an Instance of Access Token Cache Info. + * + * @param cache the cached token + * @param nextTokenRefresh the next token refresh time + */ + public AccessTokenCacheInfo(AccessToken cache, OffsetDateTime nextTokenRefresh) { + this.cache = cache; + this.nextTokenRefreshAt = nextTokenRefresh; + } + + /** + * Get the cached token. + * + * @return the cached token. + */ + public AccessToken getCachedAccessToken() { + return cache; + } + + /** + * Get the next refresh time for the token. + * + * @return the token refresh time. + */ + public OffsetDateTime getNextTokenRefreshAt() { + return nextTokenRefreshAt; + } +} diff --git a/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/implementation/package-info.java b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/implementation/package-info.java new file mode 100644 index 000000000000..29f6773735b5 --- /dev/null +++ b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/implementation/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing implementation-specific APIs that should not be used by end-users. + */ +package com.azure.v2.core.implementation; diff --git a/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/models/AzureCloud.java b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/models/AzureCloud.java new file mode 100644 index 000000000000..a7a86be6b5e8 --- /dev/null +++ b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/models/AzureCloud.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.models; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.utils.ExpandableEnum; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * An expandable enum that describes Azure cloud environment. + */ +@Metadata(properties = MetadataProperties.IMMUTABLE) +public final class AzureCloud implements ExpandableEnum { + private static final Map VALUES = new ConcurrentHashMap<>(); + + /** + * Azure public cloud. + */ + public static final AzureCloud AZURE_PUBLIC_CLOUD = fromString("AZURE_PUBLIC_CLOUD"); + /** + * Azure China cloud. + */ + public static final AzureCloud AZURE_CHINA_CLOUD = fromString("AZURE_CHINA_CLOUD"); + /** + * Azure US government cloud. + */ + public static final AzureCloud AZURE_US_GOVERNMENT_CLOUD = fromString("AZURE_US_GOVERNMENT"); + + private final String cloudName; + + private AzureCloud(String cloudName) { + this.cloudName = cloudName; + } + + /** + * Creates or finds an AzureCloud from its string representation. + * + * @param cloudName cloud name to look for + * @return the corresponding AzureCloud + */ + public static AzureCloud fromString(String cloudName) { + if (cloudName == null) { + return null; + } + return VALUES.computeIfAbsent(cloudName, AzureCloud::new); + } + + @Override + public String getValue() { + return this.cloudName; + } + + @Override + public String toString() { + return this.cloudName; + } +} diff --git a/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/models/AzureResponseError.java b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/models/AzureResponseError.java new file mode 100644 index 000000000000..3f25bb5699dd --- /dev/null +++ b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/models/AzureResponseError.java @@ -0,0 +1,214 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.models; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonSerializable; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.serialization.json.JsonWriter; + +import java.io.IOException; +import java.util.List; + +/** + *

        Represents the error details of an HTTP response.

        + * + *

        This class encapsulates the details of an HTTP error response, including the error code, message, target, + * inner error, and additional error details. It provides methods to access these properties.

        + * + *

        This class also provides a {@link #toJson(JsonWriter)} method to serialize the error details to JSON, and + * a {@link #fromJson(JsonReader)} method to deserialize the error details from JSON.

        + * + * @see JsonSerializable + * @see JsonReader + * @see JsonWriter + */ +@Metadata(properties = MetadataProperties.FLUENT) +public final class AzureResponseError implements JsonSerializable { + private final String code; + private final String message; + private String target; + private AzureResponseInnerError innerError; + private List errorDetails; + + /** + * Creates an instance of {@link AzureResponseError}. + * + * @param code the error code of this error. + * @param message the error message of this error. + */ + public AzureResponseError(String code, String message) { + this.code = code; + this.message = message; + } + + /** + * Returns the error code of this error. + * + * @return the error code of this error. + */ + public String getCode() { + return code; + } + + /** + * Returns the error message of this error. + * + * @return the error message of this error. + */ + public String getMessage() { + return message; + } + + /** + * Returns the target of this error. + * + * @return the target of this error. + */ + String getTarget() { + return target; + } + + /** + * Sets the target of this error. + * + * @param target the target of this error. + * @return the updated {@link AzureResponseError} instance. + */ + AzureResponseError setTarget(String target) { + this.target = target; + return this; + } + + /** + * Returns the inner error information for this error. + * + * @return the inner error for this error. + */ + AzureResponseInnerError getInnerError() { + return innerError; + } + + /** + * Sets the inner error information for this error. + * + * @param innerError the inner error for this error. + * @return the updated {@link AzureResponseError} instance. + */ + AzureResponseError setInnerError(AzureResponseInnerError innerError) { + this.innerError = innerError; + return this; + } + + /** + * Returns a list of details about specific errors that led to this reported error. + * + * @return the error details. + */ + List getErrorDetails() { + return errorDetails; + } + + /** + * Sets a list of details about specific errors that led to this reported error. + * + * @param errorDetails the error details. + * @return the updated {@link AzureResponseError} instance. + */ + AzureResponseError setErrorDetails(List errorDetails) { + this.errorDetails = errorDetails; + return this; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject() + .writeStringField("code", code) + .writeStringField("message", message) + .writeStringField("target", target) + .writeJsonField("innererror", innerError) + .writeArrayField("details", errorDetails, JsonWriter::writeJson) + .writeEndObject(); + } + + /** + * Reads a JSON stream into a {@link AzureResponseError}. + * + * @param jsonReader The {@link JsonReader} being read. + * @return The {@link AzureResponseError} that the JSON stream represented, or null if it pointed to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If a {@link AzureResponseError} fails to be read from the {@code jsonReader}. + */ + public static AzureResponseError fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + // Buffer the next JSON object as ResponseError can take two forms: + // + // - A ResponseError object + // - A ResponseError object wrapped in an "error" node. + JsonReader bufferedReader = reader.bufferObject(); + bufferedReader.nextToken(); // Get to the START_OBJECT token. + while (bufferedReader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = bufferedReader.getFieldName(); + bufferedReader.nextToken(); + + if ("error".equals(fieldName)) { + // If the ResponseError was wrapped in the "error" node begin reading it now. + return readResponseError(bufferedReader); + } else { + bufferedReader.skipChildren(); + } + } + + // Otherwise reset the JsonReader and read the whole JSON object. + return readResponseError(bufferedReader.reset()); + }); + } + + private static AzureResponseError readResponseError(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String code = null; + boolean codeFound = false; + String message = null; + boolean messageFound = false; + String target = null; + AzureResponseInnerError innerError = null; + List errorDetails = null; + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("code".equalsIgnoreCase(fieldName)) { + code = reader.getString(); + codeFound = true; + } else if ("message".equalsIgnoreCase(fieldName)) { + message = reader.getString(); + messageFound = true; + } else if ("target".equalsIgnoreCase(fieldName)) { + target = reader.getString(); + } else if ("innererror".equalsIgnoreCase(fieldName)) { + innerError = AzureResponseInnerError.fromJson(reader); + } else if ("details".equalsIgnoreCase(fieldName)) { + errorDetails = reader.readArray(AzureResponseError::fromJson); + } else { + reader.skipChildren(); + } + } + + if (!codeFound && !messageFound) { + throw new IllegalStateException("Missing required properties: code, message"); + } else if (!codeFound) { + throw new IllegalStateException("Missing required property: code"); + } else if (!messageFound) { + throw new IllegalStateException("Missing required property: message"); + } + + return new AzureResponseError(code, message).setTarget(target) + .setInnerError(innerError) + .setErrorDetails(errorDetails); + }); + } +} diff --git a/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/models/AzureResponseInnerError.java b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/models/AzureResponseInnerError.java new file mode 100644 index 000000000000..0b2457bafe25 --- /dev/null +++ b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/models/AzureResponseInnerError.java @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.models; + +import io.clientcore.core.annotations.Metadata; +import io.clientcore.core.annotations.MetadataProperties; +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonSerializable; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.serialization.json.JsonWriter; + +import java.io.IOException; + +/** + *

        Represents the inner error details of a {@link AzureResponseError}.

        + * + *

        This class encapsulates the details of an inner error in a {@link AzureResponseError}, including the error code + * and a nested inner error. It provides methods to access and modify these properties.

        + * + *

        This class also provides a {@link #toJson(JsonWriter)} method to serialize the inner error details to JSON, + * and a {@link #fromJson(JsonReader)} method to deserialize the inner error details from JSON.

        + * + * @see AzureResponseError + * @see JsonSerializable + * @see JsonReader + * @see JsonWriter + */ +@Metadata(properties = MetadataProperties.FLUENT) +final class AzureResponseInnerError implements JsonSerializable { + private String code; + private AzureResponseInnerError innerError; + + /** + * Returns the error code of the inner error. + * + * @return the error code of this inner error. + */ + public String getCode() { + return code; + } + + /** + * Sets the error code of the inner error. + * + * @param code the error code of this inner error. + * @return the updated {@link AzureResponseInnerError} instance. + */ + public AzureResponseInnerError setCode(String code) { + this.code = code; + return this; + } + + /** + * Returns the nested inner error for this error. + * + * @return the nested inner error for this error. + */ + public AzureResponseInnerError getInnerError() { + return innerError; + } + + /** + * Sets the nested inner error for this error. + * + * @param innerError the nested inner error for this error. + * @return the updated {@link AzureResponseInnerError} instance. + */ + public AzureResponseInnerError setInnerError(AzureResponseInnerError innerError) { + this.innerError = innerError; + return this; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject() + .writeStringField("code", code) + .writeJsonField("innererror", innerError) + .writeEndObject(); + } + + /** + * Reads a JSON stream into a {@link AzureResponseInnerError}. + * + * @param jsonReader The {@link JsonReader} being read. + * @return The {@link AzureResponseInnerError} that the JSON stream represented, or null if it pointed to JSON null. + * @throws IOException If a {@link AzureResponseInnerError} fails to be read from the {@code jsonReader}. + */ + public static AzureResponseInnerError fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AzureResponseInnerError innerError = new AzureResponseInnerError(); + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("code".equals(fieldName)) { + innerError.code = reader.getString(); + } else if ("innererror".equals(fieldName)) { + innerError.innerError = AzureResponseInnerError.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return innerError; + }); + } +} diff --git a/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/models/package-info.java b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/models/package-info.java new file mode 100644 index 000000000000..ed35a66257da --- /dev/null +++ b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/models/package-info.java @@ -0,0 +1,13 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * This package contains the core model classes used across the Azure SDK. + * + *

        These classes provide common structures and functionality for working with Azure services. They include + * representations for various types of data.

        + * + *

        Classes in this package are typically used as base classes or utility classes, and are extended or used by other + * classes in the Azure SDK to provide service-specific functionality.

        + */ +package com.azure.v2.core.models; diff --git a/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/traits/AzureSasCredentialTrait.java b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/traits/AzureSasCredentialTrait.java new file mode 100644 index 000000000000..64d36ea756ef --- /dev/null +++ b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/traits/AzureSasCredentialTrait.java @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.traits; + +import com.azure.v2.core.credentials.AzureSasCredential; + +/** + * An {@link com.azure.v2.core.traits Azure SDK for Java trait} providing a consistent interface for setting + * {@link AzureSasCredential}. Refer to the Azure SDK for Java + * identity and authentication + * documentation for more details on proper usage of the {@link AzureSasCredential} type. + * + * @param The concrete type that implements the trait. This is required so that fluent operations can continue + * to return the concrete type, rather than the trait type. + * @see com.azure.v2.core.traits + * @see AzureSasCredential + */ +public interface AzureSasCredentialTrait> { + /** + * Sets the {@link AzureSasCredential} used for authentication. Refer to the Azure SDK for Java + * identity and authentication + * documentation for more details on proper usage of the {@link AzureSasCredential} type. + * + * @param credential the {@link AzureSasCredential} to be used for authentication. + * @return Returns the same concrete type with the appropriate properties updated, to allow for fluent chaining of + * operations. + */ + T credential(AzureSasCredential credential); +} diff --git a/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/traits/ConnectionStringTrait.java b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/traits/ConnectionStringTrait.java new file mode 100644 index 000000000000..e4197d62d11e --- /dev/null +++ b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/traits/ConnectionStringTrait.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.traits; + +/** + * An {@link com.azure.v2.core.traits Azure SDK for Java trait} providing a consistent interface for + * setting connection strings. + * + * @param The concrete type that implements the trait. This is required so that fluent operations can continue + * to return the concrete type, rather than the trait type. + * @see com.azure.v2.core.traits + */ +public interface ConnectionStringTrait> { + /** + * Sets the connection string to connect to the service. + * + * @param connectionString Connection string of the service. + * @return Returns the same concrete type with the appropriate properties updated, to allow for fluent chaining of + * operations. + */ + T connectionString(String connectionString); +} diff --git a/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/traits/TokenCredentialTrait.java b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/traits/TokenCredentialTrait.java new file mode 100644 index 000000000000..324f2f03c024 --- /dev/null +++ b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/traits/TokenCredentialTrait.java @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.traits; + +import com.azure.v2.core.credentials.TokenCredential; + +/** + * A {@link com.azure.v2.core.traits Core V2 Trait} providing a consistent interface for setting + * {@link TokenCredential}. + + * @param The concrete type that implements the trait. This is required so that fluent operations can continue + * to return the concrete type, rather than the trait type. + * + * @see com.azure.v2.core.traits + * @see TokenCredential + */ +public interface TokenCredentialTrait> { + + /** + * Sets the {@link TokenCredential} used to authorize requests sent to the service. + * + * @param credential {@link TokenCredential} used to authorize requests sent to the service. + * @return Returns the same concrete type with the appropriate properties updated, to allow for fluent chaining of + * operations. + */ + T credential(TokenCredential credential); +} diff --git a/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/traits/package-info.java b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/traits/package-info.java new file mode 100644 index 000000000000..9670240c8a24 --- /dev/null +++ b/sdk/corev2/azure-core/src/main/java/com/azure/v2/core/traits/package-info.java @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * This package contains interfaces that represent common cross-cutting aspects of functionality offered by libraries + * in the Azure SDK for Java. Each interface is referred to as a 'trait', and classes that implement the interface are + * said to have that trait. There are additional traits related to AMQP use cases in the + * {@code com.azure.core.amqp.client.traits} package. + * + *

        + * The particular focus of traits in the Azure SDK for Java is to enable higher-level + * libraries the ability to more abstractly configure client libraries as part of their builders, prior to the client + * itself being instantiated. By doing this, these high-level libraries are able to reason about functionality more + * simply. It is important to appreciate that despite the availability of these cross-cutting traits, there is no + * promise that configuration of each builder can simply be a matter of providing the same arguments for all builders! + * Each builder must be configured appropriately for its requirements, or else runtime failures may occur when the + * builder is asked to create the associated client. + *

        + */ +package com.azure.v2.core.traits; diff --git a/sdk/corev2/azure-core/src/main/java/module-info.java b/sdk/corev2/azure-core/src/main/java/module-info.java new file mode 100644 index 000000000000..5f9fde0f457a --- /dev/null +++ b/sdk/corev2/azure-core/src/main/java/module-info.java @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * This module contains the core classes for Azure SDK. + */ +module com.azure.v2.core { + requires transitive io.clientcore.core; + + // public API surface area + exports com.azure.v2.core.credentials; + exports com.azure.v2.core.http.pipeline; + exports com.azure.v2.core.models; + exports com.azure.v2.core.traits; +} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/resources/azure-key-vault-administration.properties b/sdk/corev2/azure-core/src/main/resources/azure-core.v2.properties similarity index 100% rename from sdk/keyvault/azure-security-keyvault-administration/src/main/resources/azure-key-vault-administration.properties rename to sdk/corev2/azure-core/src/main/resources/azure-core.v2.properties diff --git a/sdk/corev2/azure-core/src/test/java/com/azure/v2/core/credentials/TokenCacheTests.java b/sdk/corev2/azure-core/src/test/java/com/azure/v2/core/credentials/TokenCacheTests.java new file mode 100644 index 000000000000..84dc25128f63 --- /dev/null +++ b/sdk/corev2/azure-core/src/test/java/com/azure/v2/core/credentials/TokenCacheTests.java @@ -0,0 +1,112 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.credentials; + +import com.azure.v2.core.implementation.AccessTokenCache; +import io.clientcore.core.credentials.oauth.AccessToken; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.stream.IntStream; + +import static java.lang.Thread.sleep; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TokenCacheTests { + + @Test + public void testEachSyncThreadRefreshesToken() { + AtomicLong refreshes = new AtomicLong(0); + + TokenCredential dummyCred = request -> { + refreshes.incrementAndGet(); + // Token acquisition time grows in 1 sec, 2 sec... To make sure only one token acquisition is run + return incrementalRemoteGetTokenAsync(new AtomicInteger(1)); + }; + + AccessTokenCache cache = new AccessTokenCache(dummyCred); + + IntStream.range(0, 5).parallel().flatMap(integer -> { + cache.getToken(new TokenRequestContext().addScopes("test" + integer + "/.default"), true); + return IntStream.of(integer); + }).forEach(ignored -> { + }); + + // Ensure that refresh attempts are made. + assertEquals(5, refreshes.get()); + } + + @Test + public void testOnlyOneSyncThreadRefreshesToken() { + AtomicLong refreshes = new AtomicLong(0); + + TokenCredential dummyCred = request -> { + refreshes.incrementAndGet(); + return incrementalRemoteGetTokenAsync(new AtomicInteger(1)); + }; + + // Token acquisition time grows in 1 sec, 2 sec... To make sure only one token acquisition is run + AccessTokenCache cache = new AccessTokenCache(dummyCred); + + IntStream.range(1, 10).parallel().flatMap(integer -> { + cache.getToken(new TokenRequestContext(), false); + return IntStream.of(integer); + }).forEach(ignored -> { + }); + + // Ensure that only one refresh attempt is made. + assertEquals(1, refreshes.get()); + } + + @Test + public void testRefreshOnFlow() throws InterruptedException { + AtomicLong refreshes = new AtomicLong(0); + + TokenCredential dummyCred = request -> { + refreshes.incrementAndGet(); + return new Token("testToken", 200000, 33000); + }; + + AccessTokenCache cache = new AccessTokenCache(dummyCred); + + cache.getToken(new TokenRequestContext(), false); + + sleep(40000); + + cache.getToken(new TokenRequestContext(), false); + + // Ensure refresh is made after refreshOn duration. + assertEquals(2, refreshes.get()); + } + + // First token takes latency seconds, and adds 1 sec every subsequent call + private AccessToken incrementalRemoteGetTokenAsync(AtomicInteger latency) { + try { + Thread.sleep(latency.getAndIncrement()); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + return new Token(Integer.toString(ThreadLocalRandom.current().nextInt(100))); + } + + public static class Token extends AccessToken { + Token(String token) { + this(token, 5000); + } + + Token(String token, long validityInMillis) { + super(token, OffsetDateTime.now().plus(Duration.ofMillis(validityInMillis)), + OffsetDateTime.now().plusSeconds(5)); + } + + Token(String token, long validityInMillis, long refreshInMillis) { + super(token, OffsetDateTime.now().plus(Duration.ofMillis(validityInMillis)), + OffsetDateTime.now().plus(Duration.ofMillis(refreshInMillis))); + } + } +} diff --git a/sdk/corev2/azure-core/src/test/java/com/azure/v2/core/http/pipeline/BearerTokenAuthenticationPolicyTests.java b/sdk/corev2/azure-core/src/test/java/com/azure/v2/core/http/pipeline/BearerTokenAuthenticationPolicyTests.java new file mode 100644 index 000000000000..57a15f9a383e --- /dev/null +++ b/sdk/corev2/azure-core/src/test/java/com/azure/v2/core/http/pipeline/BearerTokenAuthenticationPolicyTests.java @@ -0,0 +1,108 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.core.http.pipeline; + +import com.azure.v2.core.credentials.TokenCredential; +import io.clientcore.core.credentials.oauth.AccessToken; +import io.clientcore.core.http.client.HttpClient; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpHeaders; +import io.clientcore.core.http.models.HttpMethod; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.http.pipeline.HttpPipeline; +import io.clientcore.core.http.pipeline.HttpPipelineBuilder; +import io.clientcore.core.models.binarydata.BinaryData; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.time.OffsetDateTime; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class BearerTokenAuthenticationPolicyTests { + + @ParameterizedTest + @MethodSource("caeTestArguments") + public void testDefaultCae(String challenge, int expectedStatusCode, String expectedClaims, String encodedClaims) { + AtomicReference claims = new AtomicReference<>(); + AtomicInteger callCount = new AtomicInteger(); + + TokenCredential credential = getCaeTokenCredential(claims, callCount); + BearerTokenAuthenticationPolicy policy = new BearerTokenAuthenticationPolicy(credential, "scope"); + HttpClient client = getCaeHttpClient(challenge, callCount); + HttpPipeline pipeline = new HttpPipelineBuilder().addPolicy(policy).httpClient(client).build(); + + try (Response response + = pipeline.send(new HttpRequest().setMethod(HttpMethod.GET).setUri("https://localhost"))) { + assertEquals(expectedStatusCode, response.getStatusCode()); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + assertEquals(expectedClaims, claims.get()); + + if (expectedClaims != null) { + String actualEncodedClaims = BearerTokenAuthenticationPolicy.getChallengeParameterFromResponse( + new Response<>(null, 401, new HttpHeaders().add(HttpHeaderName.WWW_AUTHENTICATE, challenge), null), + "Bearer", "claims"); + assertEquals(encodedClaims, actualEncodedClaims); + } + } + + // A fake token credential that lets us keep track of what got parsed out of a CAE claim for assertion. + private static TokenCredential getCaeTokenCredential(AtomicReference claims, AtomicInteger callCount) { + return request -> { + claims.set(request.getClaims()); + assertTrue(request.isCaeEnabled()); + callCount.incrementAndGet(); + return new AccessToken("token", OffsetDateTime.now().plusHours(2)); + }; + } + + // This http client is effectively a state sentinel for how we progressed through the challenge. + // If we had a challenge, and it is invalid, the policy stops and returns 401 all the way out. + // If the CAE challenge parses properly we will end complete the policy normally and get 200. + private static HttpClient getCaeHttpClient(String challenge, AtomicInteger callCount) { + return request -> { + if (callCount.get() <= 1) { + if (challenge == null) { + return new Response<>(request, 200, new HttpHeaders(), null); + } + return new Response<>(request, 401, new HttpHeaders().add(HttpHeaderName.WWW_AUTHENTICATE, challenge), + null); + } + return new Response<>(request, 200, new HttpHeaders(), null); + }; + } + + private static Stream caeTestArguments() { + return Stream.of(Arguments.of(null, 200, null, null), // no challenge + Arguments.of( + "Bearer authorization_uri=\"https://login.windows.net/\", error=\"invalid_token\", claims=\"ey==\"", + 401, null, "ey=="), // unexpected error value + Arguments.of("Bearer claims=\"not base64\", error=\"insufficient_claims\"", 401, null, "not base64"), // parsing error + Arguments.of( + "Bearer realm=\"\", authorization_uri=\"http://localhost\", client_id=\"00000003-0000-0000-c000-000000000000\", error=\"insufficient_claims\", claims=\"ey==\"", + 200, "{", "ey=="), // more parameters in a different order + Arguments.of( + "Bearer realm=\"\", authorization_uri=\"https://login.microsoftonline.com/common/oauth2/authorize\", error=\"insufficient_claims\", claims=\"eyJhY2Nlc3NfdG9rZW4iOnsibmJmIjp7ImVzc2VudGlhbCI6dHJ1ZSwidmFsdWUiOiIxNzI2MDc3NTk1In0sInhtc19jYWVlcnJvciI6eyJ2YWx1ZSI6IjEwMDEyIn19fQ==\"", + 200, + "{\"access_token\":{\"nbf\":{\"essential\":true,\"value\":\"1726077595\"},\"xms_caeerror\":{\"value\":\"10012\"}}}", + "eyJhY2Nlc3NfdG9rZW4iOnsibmJmIjp7ImVzc2VudGlhbCI6dHJ1ZSwidmFsdWUiOiIxNzI2MDc3NTk1In0sInhtc19jYWVlcnJvciI6eyJ2YWx1ZSI6IjEwMDEyIn19fQ=="), // standard request + Arguments.of( + "PoP realm=\"\", authorization_uri=\"https://login.microsoftonline.com/common/oauth2/authorize\", client_id=\"00000003-0000-0000-c000-000000000000\", nonce=\"ey==\", Bearer realm=\"\", authorization_uri=\"https://login.microsoftonline.com/common/oauth2/authorize\", client_id=\"00000003-0000-0000-c000-000000000000\", error_description=\"Continuous access evaluation resulted in challenge with result: InteractionRequired and code: TokenIssuedBeforeRevocationTimestamp\", error=\"insufficient_claims\", claims=\"eyJhY2Nlc3NfdG9rZW4iOnsibmJmIjp7ImVzc2VudGlhbCI6dHJ1ZSwgInZhbHVlIjoiMTcyNjI1ODEyMiJ9fX0=\"", + 200, "{\"access_token\":{\"nbf\":{\"essential\":true, \"value\":\"1726258122\"}}}", + "eyJhY2Nlc3NfdG9rZW4iOnsibmJmIjp7ImVzc2VudGlhbCI6dHJ1ZSwgInZhbHVlIjoiMTcyNjI1ODEyMiJ9fX0="), // multiple challenges + Arguments.of("Bearer claims=\"\", error=\"insufficient_claims\"", 401, null, ""), // empty claims + Arguments.of("Bearer error=\"insufficient_claims\"", 401, null, "") // missing claims + ); + } +} diff --git a/sdk/corev2/ci.yml b/sdk/corev2/ci.yml new file mode 100644 index 000000000000..c0ca590b618c --- /dev/null +++ b/sdk/corev2/ci.yml @@ -0,0 +1,56 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. + +trigger: + branches: + include: + - main + - hotfix/* + - release/* + paths: + include: + - sdk/corev2/ + - sdk/parents/azure-client-sdk-parent-v2/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/corev2/ + - sdk/parents/azure-client-sdk-parent-v2/ + +parameters: + - name: release_dependsonlivetests + displayName: 'Release depends on live tests' + type: boolean + default: true + - name: release_azurecore + displayName: 'azure-core' + type: boolean + default: true + - name: release_azurecoretest + displayName: 'azure-core-test' + type: boolean + default: true + +extends: + template: /eng/pipelines/templates/stages/archetype-sdk-client.yml + parameters: + ServiceDirectory: corev2 + TimeoutInMinutes: 90 + ReleaseDependsOnLiveTests: ${{ parameters.release_dependsonlivetests }} + Artifacts: + - name: azure-core + groupId: com.azure.v2 + safeName: azurecore + releaseInBatch: ${{ parameters.release_azurecore }} + triggeringPaths: + - /sdk/parents/azure-client-sdk-parent-v2 + - name: azure-core-test + groupId: com.azure.v2 + safeName: azurecoretest + releaseInBatch: ${{ parameters.release_azurecoretest }} diff --git a/sdk/corev2/pom.xml b/sdk/corev2/pom.xml new file mode 100644 index 000000000000..6068d2f634ab --- /dev/null +++ b/sdk/corev2/pom.xml @@ -0,0 +1,16 @@ + + + 4.0.0 + com.azure.v2 + azure-core-service + pom + 2.0.0 + + + azure-core + azure-core-test + + diff --git a/sdk/cosmos/README.md b/sdk/cosmos/README.md index c5ebdfccb4b9..ac4f5f132526 100644 --- a/sdk/cosmos/README.md +++ b/sdk/cosmos/README.md @@ -19,4 +19,4 @@ To get started with a specific library, see the **README.md** file located in th [sql_api_query]: https://learn.microsoft.com/azure/cosmos-db/sql-api-sql-query [cosmos_introduction]: https://learn.microsoft.com/azure/cosmos-db/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcosmos%2Fazure-cosmos%2FREADME.png) + diff --git a/sdk/cosmos/azure-cosmos-benchmark/README.md b/sdk/cosmos/azure-cosmos-benchmark/README.md index a8b446e25b7d..67505e2aa189 100644 --- a/sdk/cosmos/azure-cosmos-benchmark/README.md +++ b/sdk/cosmos/azure-cosmos-benchmark/README.md @@ -75,4 +75,4 @@ You can provide ``--help`` to the tool to see the list of other work loads (read -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcosmos%2Fazure-cosmos-benchmark%2FREADME.png) + diff --git a/sdk/cosmos/azure-cosmos-benchmark/pom.xml b/sdk/cosmos/azure-cosmos-benchmark/pom.xml index 921114c1736c..2d0a896a8ac2 100644 --- a/sdk/cosmos/azure-cosmos-benchmark/pom.xml +++ b/sdk/cosmos/azure-cosmos-benchmark/pom.xml @@ -52,19 +52,19 @@ Licensed under the MIT License. com.azure azure-cosmos - 4.67.0-beta.1 + 4.68.0-beta.1 com.azure azure-cosmos-encryption - 2.18.0-beta.1 + 2.19.0-beta.1 com.azure azure-identity - 1.15.0 + 1.15.4 com.azure @@ -183,7 +183,7 @@ Licensed under the MIT License. com.azure azure-security-keyvault-keys - 4.9.1 + 4.9.3 compile @@ -194,7 +194,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 unit @@ -213,7 +213,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-checkstyle-plugin - 3.5.0 + 3.6.0 false false @@ -233,7 +233,7 @@ Licensed under the MIT License. org.codehaus.mojo exec-maven-plugin - 3.4.1 + 3.5.0 com.azure.cosmos.benchmark.Main @@ -298,7 +298,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 @@ -316,7 +316,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/fast-testng.xml @@ -337,7 +337,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/split-testng.xml @@ -358,7 +358,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/cfp-split-testng.xml @@ -379,7 +379,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/query-testng.xml @@ -400,7 +400,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/long-testng.xml @@ -421,7 +421,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/direct-testng.xml @@ -442,7 +442,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/multi-master-testng.xml @@ -463,7 +463,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/flaky-multi-master-testng.xml @@ -485,7 +485,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/examples-testng.xml @@ -514,7 +514,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/emulator-testng.xml @@ -535,7 +535,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/e2e-testng.xml diff --git a/sdk/cosmos/azure-cosmos-benchmark/src/main/java/com/azure/cosmos/benchmark/ReadMyWriteWorkflow.java b/sdk/cosmos/azure-cosmos-benchmark/src/main/java/com/azure/cosmos/benchmark/ReadMyWriteWorkflow.java index 9e6416bbe398..6ebba7d1a93a 100644 --- a/sdk/cosmos/azure-cosmos-benchmark/src/main/java/com/azure/cosmos/benchmark/ReadMyWriteWorkflow.java +++ b/sdk/cosmos/azure-cosmos-benchmark/src/main/java/com/azure/cosmos/benchmark/ReadMyWriteWorkflow.java @@ -5,7 +5,6 @@ import com.azure.cosmos.CosmosBridgeInternal; import com.azure.cosmos.CosmosException; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.AsyncDocumentClient; import com.azure.cosmos.implementation.CosmosPagedFluxOptions; import com.azure.cosmos.implementation.Database; @@ -194,12 +193,12 @@ private Flux writeDocument(Integer i) { String randomVal = UUID.randomUUID().toString(); Document document = new Document(); document.setId(idString); - document.set(partitionKey, idString, CosmosItemSerializer.DEFAULT_SERIALIZER); - document.set(QUERY_FIELD_NAME, randomVal, CosmosItemSerializer.DEFAULT_SERIALIZER); - document.set("dataField1", randomVal, CosmosItemSerializer.DEFAULT_SERIALIZER); - document.set("dataField2", randomVal, CosmosItemSerializer.DEFAULT_SERIALIZER); - document.set("dataField3", randomVal, CosmosItemSerializer.DEFAULT_SERIALIZER); - document.set("dataField4", randomVal, CosmosItemSerializer.DEFAULT_SERIALIZER); + document.set(partitionKey, idString); + document.set(QUERY_FIELD_NAME, randomVal); + document.set("dataField1", randomVal); + document.set("dataField2", randomVal); + document.set("dataField3", randomVal); + document.set("dataField4", randomVal); Integer key = i == null ? cacheKey() : i; return client.createDocument(getCollectionLink(), document, null, false) diff --git a/sdk/cosmos/azure-cosmos-dotnet-benchmark/README.md b/sdk/cosmos/azure-cosmos-dotnet-benchmark/README.md index 199293105aa3..f3c6c2a44b36 100644 --- a/sdk/cosmos/azure-cosmos-dotnet-benchmark/README.md +++ b/sdk/cosmos/azure-cosmos-dotnet-benchmark/README.md @@ -99,7 +99,7 @@ or contact [opencode@microsoft.com][coc_contact] with any additional questions o [source_code]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/cosmos/azure-cosmos/src [cosmos_introduction]: https://learn.microsoft.com/azure/cosmos-db/ -[api_documentation]: https://azuresdkdocs.blob.core.windows.net/$web/java/azure-cosmos/latest/index.html +[api_documentation]: https://azuresdkdocs.z19.web.core.windows.net/java/azure-cosmos/latest/index.html [cosmos_docs]: https://learn.microsoft.com/azure/cosmos-db/introduction [jdk]: https://learn.microsoft.com/java/azure/java-supported-jdk-runtime?view=azure-java-stable [maven]: https://maven.apache.org/ @@ -119,4 +119,5 @@ or contact [opencode@microsoft.com][coc_contact] with any additional questions o [quickstart]: https://learn.microsoft.com/azure/cosmos-db/create-sql-api-java?tabs=sync [project_reactor_schedulers]: https://projectreactor.io/docs/core/release/api/reactor/core/scheduler/Schedulers.html -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcosmos%2Fazure-cosmos%2FREADME.png) + + diff --git a/sdk/cosmos/azure-cosmos-dotnet-benchmark/pom.xml b/sdk/cosmos/azure-cosmos-dotnet-benchmark/pom.xml index 667f314d43d8..61bb01a115a8 100644 --- a/sdk/cosmos/azure-cosmos-dotnet-benchmark/pom.xml +++ b/sdk/cosmos/azure-cosmos-dotnet-benchmark/pom.xml @@ -51,7 +51,7 @@ Licensed under the MIT License. com.azure azure-cosmos - 4.67.0-beta.1 + 4.68.0-beta.1 @@ -120,7 +120,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 unit @@ -139,7 +139,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-checkstyle-plugin - 3.5.0 + 3.6.0 true true @@ -159,7 +159,7 @@ Licensed under the MIT License. org.codehaus.mojo exec-maven-plugin - 3.4.1 + 3.5.0 com.azure.cosmos.dotnet.benchmark.Main @@ -221,7 +221,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 @@ -239,7 +239,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/fast-testng.xml @@ -260,7 +260,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/long-testng.xml @@ -281,7 +281,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/direct-testng.xml @@ -302,7 +302,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/multi-master-testng.xml @@ -324,7 +324,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/examples-testng.xml @@ -353,7 +353,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/emulator-testng.xml @@ -374,7 +374,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/e2e-testng.xml diff --git a/sdk/cosmos/azure-cosmos-dotnet-benchmark/src/main/java/com/azure/cosmos/dotnet/benchmark/ThinClientReproMain.java b/sdk/cosmos/azure-cosmos-dotnet-benchmark/src/main/java/com/azure/cosmos/dotnet/benchmark/ThinClientReproMain.java index 02cb3dab01c5..6cf8a4a26dcd 100644 --- a/sdk/cosmos/azure-cosmos-dotnet-benchmark/src/main/java/com/azure/cosmos/dotnet/benchmark/ThinClientReproMain.java +++ b/sdk/cosmos/azure-cosmos-dotnet-benchmark/src/main/java/com/azure/cosmos/dotnet/benchmark/ThinClientReproMain.java @@ -5,6 +5,7 @@ import com.azure.cosmos.CosmosAsyncContainer; import com.azure.cosmos.CosmosClientBuilder; import com.azure.cosmos.CosmosException; +import com.azure.cosmos.implementation.TestConfigurations; import com.azure.cosmos.models.CosmosContainerResponse; import com.azure.cosmos.models.CosmosItemResponse; import com.azure.cosmos.models.PartitionKey; @@ -14,49 +15,47 @@ import java.util.UUID; public class ThinClientReproMain { + + public static void main(String[] args) { try { System.setProperty("COSMOS.THINCLIENT_ENABLED", "true"); System.setProperty("COSMOS.HTTP2_ENABLED", "true"); CosmosAsyncClient client = new CosmosClientBuilder() - .key(System.getProperty("COSMOS.KEY")) - .endpoint(System.getProperty("COSMOS.ENDPOINT")) + .key(TestConfigurations.MASTER_KEY) + .endpoint(TestConfigurations.HOST) .gatewayMode() .consistencyLevel(ConsistencyLevel.SESSION) - .userAgentSuffix("fabianmThinClientProxyTest") + .userAgentSuffix("fabianmThinClientProxyTest02") .buildAsyncClient(); - CosmosAsyncContainer container = client.getDatabase("HashV2Small1").getContainer("HashV2Small1"); + CosmosAsyncContainer container = client.getDatabase("updatedd-thin-client-test-db").getContainer("thin-client-test-container-1"); CosmosContainerResponse containerResponse = container.read().block(); System.out.println("Container RID: " + containerResponse.getProperties().getResourceId()); ObjectMapper mapper = new ObjectMapper(); ObjectNode doc = mapper.createObjectNode(); String idValue = UUID.randomUUID().toString(); doc.put("id", idValue); + doc.put("pk", idValue); System.out.println("Document to be ingested - " + doc.toPrettyString()); - while (true) { - try { - // container.readItem( - // "HelloWorld", - // new PartitionKey("HelloWorld"), - // ObjectNode.class) - CosmosItemResponse createResponse = container.createItem(doc).block(); - System.out.println("CREATE DIAGNOSTICS: " + createResponse.getDiagnostics()); - break; - } catch (CosmosException cosmosError) { - System.out.println("COSMOS ERROR: " + cosmosError.getStatusCode() + "/" + cosmosError.getShortMessage()); - Thread.sleep(10_000); - } + try { + // container.readItem( + // "HelloWorld", + // new PartitionKey("HelloWorld"), + // ObjectNode.class) + CosmosItemResponse createResponse = container.createItem(doc).block(); + System.out.println("CREATE DIAGNOSTICS: " + createResponse.getDiagnostics()); + } catch (CosmosException cosmosError) { + System.out.println("COSMOS ERROR: " + cosmosError.getStatusCode() + "/" + cosmosError.getShortMessage()); } CosmosItemResponse response = container.readItem(idValue, new PartitionKey(idValue), ObjectNode.class).block(); System.out.println("READ DIAGNOSTICS: " + response.getDiagnostics()); ObjectNode readDoc = response.getItem(); - System.out.println("Document read - " + readDoc.toPrettyString()); - } catch (CosmosException | InterruptedException cosmosException) { + } catch (CosmosException cosmosException) { System.out.println("COSMOS ERROR: " + cosmosException); } } diff --git a/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md b/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md index f875090043de..a12f72756ec5 100644 --- a/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md +++ b/sdk/cosmos/azure-cosmos-encryption/CHANGELOG.md @@ -1,6 +1,6 @@ ## Release History -### 2.18.0-beta.1 (Unreleased) +### 2.19.0-beta.1 (Unreleased) #### Features Added @@ -10,6 +10,16 @@ #### Other Changes +### 2.18.0 (2025-02-20) + +#### Other Changes +* Updated `azure-cosmos` to version `4.67.0`. + +### 2.17.1 (2025-02-08) + +#### Other Changes +* Updated `azure-cosmos` to version `4.66.1`. + ### 2.17.0 (2025-01-14) #### Other Changes diff --git a/sdk/cosmos/azure-cosmos-encryption/README.md b/sdk/cosmos/azure-cosmos-encryption/README.md index f727af0285d6..084262d3672a 100644 --- a/sdk/cosmos/azure-cosmos-encryption/README.md +++ b/sdk/cosmos/azure-cosmos-encryption/README.md @@ -12,7 +12,7 @@ The Azure Cosmos Encryption Plugin is used for encrypting data with a user-provi com.azure azure-cosmos-encryption - 2.17.0 + 2.19.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -209,8 +209,8 @@ or contact [opencode@microsoft.com][coc_contact] with any additional questions o [encryption_source_code]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/cosmos/azure-cosmos-encryption/src [cosmos_introduction]: https://learn.microsoft.com/azure/cosmos-db/ -[api_documentation]: https://azuresdkdocs.blob.core.windows.net/$web/java/azure-cosmos/latest/index.html -[encryption_api_documentation]: https://azuresdkdocs.blob.core.windows.net/$web/java/azure-cosmos-encryption/latest/index.html +[api_documentation]: https://azuresdkdocs.z19.web.core.windows.net/java/azure-cosmos/latest/index.html +[encryption_api_documentation]: https://azuresdkdocs.z19.web.core.windows.net/java/azure-cosmos-encryption/latest/index.html [cosmos_docs]: https://learn.microsoft.com/azure/cosmos-db/introduction [jdk]: https://learn.microsoft.com/java/azure/jdk/ [maven]: https://maven.apache.org/ @@ -226,4 +226,5 @@ or contact [opencode@microsoft.com][coc_contact] with any additional questions o [getting_started_encryption]: https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/cosmos/azure-cosmos-encryption/src/samples/java/com/azure/cosmos/encryption/ [quickstart]: https://learn.microsoft.com/azure/cosmos-db/create-sql-api-java?tabs=sync -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcosmos%2Fazure-cosmos-encryption%2FREADME.png) + + diff --git a/sdk/cosmos/azure-cosmos-encryption/pom.xml b/sdk/cosmos/azure-cosmos-encryption/pom.xml index 32904d1f67af..ba05dcc0717a 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.18.0-beta.1 + 2.19.0-beta.1 Encryption Plugin for Azure Cosmos DB SDK This Package contains Encryption Plugin for Microsoft Azure Cosmos SDK jar @@ -59,13 +59,13 @@ Licensed under the MIT License. com.azure azure-cosmos - 4.67.0-beta.1 + 4.68.0-beta.1 com.azure azure-security-keyvault-keys - 4.9.1 + 4.9.3 test @@ -82,7 +82,7 @@ Licensed under the MIT License. com.azure azure-identity - 1.15.0 + 1.15.4 test @@ -214,7 +214,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 unit @@ -260,7 +260,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 @@ -278,7 +278,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/encryption-testng.xml diff --git a/sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/models/SqlQuerySpecWithEncryption.java b/sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/models/SqlQuerySpecWithEncryption.java index 21007204d622..7c2dbb1cc791 100644 --- a/sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/models/SqlQuerySpecWithEncryption.java +++ b/sdk/cosmos/azure-cosmos-encryption/src/main/java/com/azure/cosmos/encryption/models/SqlQuerySpecWithEncryption.java @@ -11,6 +11,7 @@ import com.azure.cosmos.encryption.implementation.EncryptionUtils; import com.azure.cosmos.encryption.implementation.mdesrc.cryptography.EncryptionType; import com.azure.cosmos.encryption.implementation.mdesrc.cryptography.MicrosoftDataEncryptionException; +import com.azure.cosmos.implementation.DefaultCosmosItemSerializer; import com.azure.cosmos.implementation.Utils; import com.azure.cosmos.implementation.apachecommons.lang.StringUtils; import com.azure.cosmos.implementation.apachecommons.lang.tuple.Pair; @@ -84,9 +85,11 @@ Mono addEncryptionParameterAsync(String path, SqlParameter sqlParameter, } } byte[] valueByte = - EncryptionUtils.serializeJsonToByteArray(CosmosItemSerializer.DEFAULT_SERIALIZER, + EncryptionUtils.serializeJsonToByteArray( + DefaultCosmosItemSerializer.INTERNAL_DEFAULT_SERIALIZER, sqlParameter.getValue(Object.class)); - JsonNode itemJObj = Utils.parse(valueByte, JsonNode.class, CosmosItemSerializer.DEFAULT_SERIALIZER); + JsonNode itemJObj = Utils.parse( + valueByte, JsonNode.class, DefaultCosmosItemSerializer.INTERNAL_DEFAULT_SERIALIZER); Pair typeMarkerPair = EncryptionProcessor.toByteArray(itemJObj); byte[] cipherText = diff --git a/sdk/cosmos/azure-cosmos-examples/README.md b/sdk/cosmos/azure-cosmos-examples/README.md index f9a3d87e1c08..7f04ce0ae1d9 100644 --- a/sdk/cosmos/azure-cosmos-examples/README.md +++ b/sdk/cosmos/azure-cosmos-examples/README.md @@ -4,4 +4,4 @@ Examples for Azure Cosmos DB Java SDK for SQL API have been moved to a separate [github repository](https://github.com/Azure-Samples/azure-cosmos-java-sql-api-samples) -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcosmos%2Fazure-cosmos-examples%2FREADME.png) + diff --git a/sdk/cosmos/azure-cosmos-kafka-connect/CHANGELOG.md b/sdk/cosmos/azure-cosmos-kafka-connect/CHANGELOG.md index e17567081d93..71e24fd06e46 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 -### 2.2.0-beta.1 (Unreleased) +### 2.3.0-beta.1 (Unreleased) #### Features Added @@ -10,6 +10,16 @@ #### Other Changes +### 2.2.0 (2025-02-20) + +#### Other Changes +* Updated `azure-cosmos` to version `4.67.0`. + +### 2.1.1 (2025-02-08) + +#### Other Changes +* Updated `azure-cosmos` to version `4.66.1`. + ### 2.1.0 (2025-01-14) #### Bugs Fixed diff --git a/sdk/cosmos/azure-cosmos-kafka-connect/README.md b/sdk/cosmos/azure-cosmos-kafka-connect/README.md index 2edc250f54d0..56b854cf82b8 100644 --- a/sdk/cosmos/azure-cosmos-kafka-connect/README.md +++ b/sdk/cosmos/azure-cosmos-kafka-connect/README.md @@ -85,4 +85,4 @@ or contact [opencode@microsoft.com][coc_contact] with any additional questions o [sql_api_query]: https://learn.microsoft.com/azure/cosmos-db/sql-api-sql-query [quickstart]: https://learn.microsoft.com/azure/cosmos-db/create-sql-api-java?tabs=sync -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcosmos%2Fazure-cosmos-kafka-connect%2FREADME.png) + diff --git a/sdk/cosmos/azure-cosmos-kafka-connect/pom.xml b/sdk/cosmos/azure-cosmos-kafka-connect/pom.xml index 2b6a55854fbf..ce938934df83 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 - 2.2.0-beta.1 + 2.3.0-beta.1 Apache Kafka Connect connector for Azure Cosmos DB This Package contains an Apache Kafka Connect source and sink connector for Azure Cosmos DB jar @@ -86,7 +86,7 @@ Licensed under the MIT License. com.azure azure-cosmos - 4.67.0-beta.1 + 4.68.0-beta.1 + 1.0.0-beta.12 test @@ -130,7 +130,7 @@ Licensed under the MIT License. com.azure azure-identity - 1.15.0 + 1.15.4 com.azure @@ -268,7 +268,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 unit @@ -519,7 +519,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 @@ -537,7 +537,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/kafka-emulator-testng.xml @@ -558,7 +558,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/kafka-testng.xml @@ -579,7 +579,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/kafka-integration-testng.xml diff --git a/sdk/cosmos/azure-cosmos-spark-account-data-resolver-sample/pom.xml b/sdk/cosmos/azure-cosmos-spark-account-data-resolver-sample/pom.xml index 81f4afa0c660..6efeb6d4697c 100644 --- a/sdk/cosmos/azure-cosmos-spark-account-data-resolver-sample/pom.xml +++ b/sdk/cosmos/azure-cosmos-spark-account-data-resolver-sample/pom.xml @@ -97,7 +97,7 @@ com.azure.cosmos.spark azure-cosmos-spark_3-5_2-12 - 4.37.0-beta.1 + 4.38.0-beta.1 provided @@ -119,12 +119,12 @@ com.azure.resourcemanager azure-resourcemanager-cosmos - 2.46.0 + 2.48.0 com.azure azure-identity - 1.15.0 + 1.15.4 com.azure @@ -135,7 +135,7 @@ com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure @@ -292,7 +292,7 @@ com.fasterxml.jackson.core:jackson-databind:[2.15.2] com.fasterxml.jackson.module:jackson-module-scala_2.12:[2.15.2] com.globalmentor:hadoop-bare-naked-local-fs:[0.1.0] - com.azure.cosmos.spark:azure-cosmos-spark_3-5_2-12:[4.37.0-beta.1] + com.azure.cosmos.spark:azure-cosmos-spark_3-5_2-12:[4.38.0-beta.1] @@ -694,7 +694,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 **/*.* diff --git a/sdk/cosmos/azure-cosmos-spark_3-1_2-12/CHANGELOG.md b/sdk/cosmos/azure-cosmos-spark_3-1_2-12/CHANGELOG.md index 88b89ec33a1b..c5f32d045a6e 100644 --- a/sdk/cosmos/azure-cosmos-spark_3-1_2-12/CHANGELOG.md +++ b/sdk/cosmos/azure-cosmos-spark_3-1_2-12/CHANGELOG.md @@ -1,6 +1,6 @@ ## Release History -### 4.37.0-beta.1 (Unreleased) +### 4.38.0-beta.1 (Unreleased) #### Features Added @@ -10,6 +10,21 @@ #### Other Changes +### 4.37.1 (2025-03-04) + +#### Features Added +* Added config option `spark.cosmos.read.responseContinuationTokenLimitInKb` to reduce query continuation token size. - See [PR 44480](https://github.com/Azure/azure-sdk-for-java/pull/44480) + +### 4.37.0 (2025-02-20) + +#### Other Changes +* Updated netty dependency + +### 4.36.1 (2025-02-08) + +#### Bugs Fixed +* Fixed an issue in change feed where under certain rare race conditions records could be skipped and excessive requests are prefetched. - See [PR 43788](https://github.com/Azure/azure-sdk-for-java/pull/43788) + ### 4.36.0 (2025-01-14) #### Features Added diff --git a/sdk/cosmos/azure-cosmos-spark_3-1_2-12/README.md b/sdk/cosmos/azure-cosmos-spark_3-1_2-12/README.md index d40c03e4a8c0..2577211de1ea 100644 --- a/sdk/cosmos/azure-cosmos-spark_3-1_2-12/README.md +++ b/sdk/cosmos/azure-cosmos-spark_3-1_2-12/README.md @@ -29,6 +29,9 @@ https://github.com/Azure/azure-sdk-for-java/issues/new #### azure-cosmos-spark_3-1_2-12 | Connector | Supported Spark Versions | Supported JVM Versions | Supported Scala Versions | Supported Databricks Runtimes | |--------------|--------------------------|------------------------|--------------------------|-------------------------------| +| 4.37.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 9.\* | +| 4.37.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 9.\* | +| 4.36.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 9.\* | | 4.36.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | | 4.35.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | | 4.34.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | @@ -102,6 +105,9 @@ https://github.com/Azure/azure-sdk-for-java/issues/new #### azure-cosmos-spark_3-2_2-12 | Connector | Supported Spark Versions | Supported JVM Versions | Supported Scala Versions | Supported Databricks Runtimes | |-----------|--------------------------|------------------------|--------------------------|-------------------------------| +| 4.37.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | +| 4.37.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | +| 4.36.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | | 4.36.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | | 4.35.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | | 4.34.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | @@ -160,6 +166,9 @@ https://github.com/Azure/azure-sdk-for-java/issues/new #### azure-cosmos-spark_3-3_2-12 | Connector | Supported Spark Versions | Supported JVM Versions | Supported Scala Versions | Supported Databricks Runtimes | |-----------|--------------------------|------------------------|--------------------------|-------------------------------| +| 4.37.1 | 3.3.0 - 3.3.2 | [8, 11] | 2.12 | 11.\*, 12.\* | +| 4.37.0 | 3.3.0 - 3.3.2 | [8, 11] | 2.12 | 11.\*, 12.\* | +| 4.36.1 | 3.3.0 - 3.3.2 | [8, 11] | 2.12 | 11.\*, 12.\* | | 4.36.0 | 3.3.0 | [8, 11] | 2.12 | 11.\*, 12.\* | | 4.35.0 | 3.3.0 | [8, 11] | 2.12 | 11.\*, 12.\* | | 4.34.0 | 3.3.0 | [8, 11] | 2.12 | 11.\*, 12.\* | @@ -200,6 +209,9 @@ https://github.com/Azure/azure-sdk-for-java/issues/new #### azure-cosmos-spark_3-4_2-12 | Connector | Supported Spark Versions | Supported JVM Versions | Supported Scala Versions | Supported Databricks Runtimes | |-----------|--------------------------|------------------------|--------------------------|-------------------------------| +| 4.37.1 | 3.4.0 - 3.4.1 | [8, 11] | 2.12 | 13.\* | +| 4.37.0 | 3.4.0 - 3.4.1 | [8, 11] | 2.12 | 13.\* | +| 4.36.1 | 3.4.0 - 3.4.1 | [8, 11] | 2.12 | 13.\* | | 4.36.0 | 3.4.0 | [8, 11] | 2.12 | 13.\* | | 4.35.0 | 3.4.0 | [8, 11] | 2.12 | 13.\* | | 4.34.0 | 3.4.0 | [8, 11] | 2.12 | 13.\* | @@ -232,6 +244,9 @@ https://github.com/Azure/azure-sdk-for-java/issues/new #### azure-cosmos-spark_3-5_2-12 | Connector | Supported Spark Versions | Minimum Java Version | Supported Scala Versions | Supported Databricks Runtimes | |-----------|--------------------------|------------------------|--------------------------|-------------------------------| +| 4.37.1 | 3.5.0 | [8, 11] | 2.12 | 14.*, 15.\* | +| 4.37.0 | 3.5.0 | [8, 11] | 2.12 | 14.*, 15.\* | +| 4.36.1 | 3.5.0 | [8, 11] | 2.12 | 14.*, 15.\* | | 4.36.0 | 3.5.0 | [8, 11] | 2.12 | 14.*, 15.\* | | 4.35.0 | 3.5.0 | [8, 11] | 2.12 | 14.*, 15.\* | | 4.34.0 | 3.5.0 | [8, 11] | 2.12 | 14.*, 15.\* | @@ -249,11 +264,11 @@ to use the same version of Scala that Spark was compiled for. ### Download You can use the maven coordinate of the jar to auto install the Spark Connector to your Databricks Runtime 8 from Maven: -`com.azure.cosmos.spark:azure-cosmos-spark_3-1_2-12:4.36.0` +`com.azure.cosmos.spark:azure-cosmos-spark_3-1_2-12:4.37.1` You can also integrate against Cosmos DB Spark Connector in your SBT project: ```scala -libraryDependencies += "com.azure.cosmos.spark" % "azure-cosmos-spark_3-1_2-12" % "4.36.0" +libraryDependencies += "com.azure.cosmos.spark" % "azure-cosmos-spark_3-1_2-12" % "4.37.1" ``` Cosmos DB Spark Connector is available on [Maven Central Repo](https://central.sonatype.com/search?namespace=com.azure.cosmos.spark). diff --git a/sdk/cosmos/azure-cosmos-spark_3-1_2-12/pom.xml b/sdk/cosmos/azure-cosmos-spark_3-1_2-12/pom.xml index a1b1780063a5..a1af4f1a2cb6 100644 --- a/sdk/cosmos/azure-cosmos-spark_3-1_2-12/pom.xml +++ b/sdk/cosmos/azure-cosmos-spark_3-1_2-12/pom.xml @@ -11,7 +11,7 @@ com.azure.cosmos.spark azure-cosmos-spark_3-1_2-12 - 4.37.0-beta.1 + 4.38.0-beta.1 jar https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/cosmos/azure-cosmos-spark_3-1_2-12 OLTP Spark 3.1 Connector for Azure Cosmos DB SQL API @@ -109,7 +109,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 **/*.* diff --git a/sdk/cosmos/azure-cosmos-spark_3-2_2-12/CHANGELOG.md b/sdk/cosmos/azure-cosmos-spark_3-2_2-12/CHANGELOG.md index 8f007258e5f5..427851c66a18 100644 --- a/sdk/cosmos/azure-cosmos-spark_3-2_2-12/CHANGELOG.md +++ b/sdk/cosmos/azure-cosmos-spark_3-2_2-12/CHANGELOG.md @@ -1,6 +1,6 @@ ## Release History -### 4.37.0-beta.1 (Unreleased) +### 4.38.0-beta.1 (Unreleased) #### Features Added @@ -10,6 +10,21 @@ #### Other Changes +### 4.37.1 (2025-03-04) + +#### Features Added +* Added config option `spark.cosmos.read.responseContinuationTokenLimitInKb` to reduce query continuation token size. - See [PR 44480](https://github.com/Azure/azure-sdk-for-java/pull/44480) + +### 4.37.0 (2025-02-20) + +#### Other Changes +* Updated netty dependency + +### 4.36.1 (2025-02-08) + +#### Bugs Fixed +* Fixed an issue in change feed where under certain rare race conditions records could be skipped and excessive requests are prefetched. - See [PR 43788](https://github.com/Azure/azure-sdk-for-java/pull/43788) + ### 4.36.0 (2025-01-14) #### Features Added diff --git a/sdk/cosmos/azure-cosmos-spark_3-2_2-12/README.md b/sdk/cosmos/azure-cosmos-spark_3-2_2-12/README.md index 9bb6d1a7e237..488e17266ed7 100644 --- a/sdk/cosmos/azure-cosmos-spark_3-2_2-12/README.md +++ b/sdk/cosmos/azure-cosmos-spark_3-2_2-12/README.md @@ -28,6 +28,9 @@ https://github.com/Azure/azure-sdk-for-java/issues/new #### azure-cosmos-spark_3-2_2-12 | Connector | Supported Spark Versions | Supported JVM Versions | Supported Scala Versions | Supported Databricks Runtimes | |-----------|--------------------------|------------------------|--------------------------|-------------------------------| +| 4.37.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | +| 4.37.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | +| 4.36.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | | 4.36.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | | 4.35.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | | 4.34.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | @@ -86,6 +89,9 @@ https://github.com/Azure/azure-sdk-for-java/issues/new #### azure-cosmos-spark_3-3_2-12 | Connector | Supported Spark Versions | Supported JVM Versions | Supported Scala Versions | Supported Databricks Runtimes | |-----------|--------------------------|------------------------|--------------------------|-------------------------------| +| 4.37.1 | 3.3.0 - 3.3.2 | [8, 11] | 2.12 | 11.\*, 12.\* | +| 4.37.0 | 3.3.0 - 3.3.2 | [8, 11] | 2.12 | 11.\*, 12.\* | +| 4.36.1 | 3.3.0 - 3.3.2 | [8, 11] | 2.12 | 11.\*, 12.\* | | 4.36.0 | 3.3.0 | [8, 11] | 2.12 | 11.\*, 12.\* | | 4.35.0 | 3.3.0 | [8, 11] | 2.12 | 11.\*, 12.\* | | 4.34.0 | 3.3.0 | [8, 11] | 2.12 | 11.\*, 12.\* | @@ -126,46 +132,49 @@ https://github.com/Azure/azure-sdk-for-java/issues/new #### azure-cosmos-spark_3-1_2-12 | Connector | Supported Spark Versions | Supported JVM Versions | Supported Scala Versions | Supported Databricks Runtimes | |--------------|--------------------------|------------------------|--------------------------|-------------------------------| -| 4.36.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.35.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.34.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.33.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.33.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.32.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.32.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.31.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.30.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.29.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.28.4 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.28.3 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.28.2 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.28.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.28.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.27.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.27.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.26.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.26.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.25.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.25.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.24.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.24.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.23.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.22.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.21.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.21.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.20.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.19.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.18.2 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.18.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.18.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.17.2 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.17.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.16.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.15.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.14.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.14.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.13.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.13.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.37.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 9.\* | +| 4.37.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 9.\* | +| 4.36.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 9.\* | +| 4.36.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.35.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.34.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.33.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.33.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.32.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.32.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.31.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.30.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.29.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.28.4 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.28.3 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.28.2 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.28.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.28.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.27.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.27.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.26.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.26.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.25.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.25.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.24.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.24.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.23.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.22.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.21.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.21.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.20.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.19.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.18.2 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.18.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.18.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.17.2 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.17.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.16.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.15.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.14.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.14.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.13.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.13.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | | 4.12.2 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | | 4.12.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | | 4.12.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | @@ -196,9 +205,13 @@ https://github.com/Azure/azure-sdk-for-java/issues/new | 4.0.0-beta.2 | 3.1.1 | [8, 11] | 2.12 | 8.\* | | 4.0.0-beta.1 | 3.1.1 | [8, 11] | 2.12 | 8.\* | + #### azure-cosmos-spark_3-4_2-12 | Connector | Supported Spark Versions | Supported JVM Versions | Supported Scala Versions | Supported Databricks Runtimes | |-----------|--------------------------|------------------------|--------------------------|-------------------------------| +| 4.37.1 | 3.4.0 - 3.4.1 | [8, 11] | 2.12 | 13.\* | +| 4.37.0 | 3.4.0 - 3.4.1 | [8, 11] | 2.12 | 13.\* | +| 4.36.1 | 3.4.0 - 3.4.1 | [8, 11] | 2.12 | 13.\* | | 4.36.0 | 3.4.0 | [8, 11] | 2.12 | 13.* | | 4.35.0 | 3.4.0 | [8, 11] | 2.12 | 13.* | | 4.34.0 | 3.4.0 | [8, 11] | 2.12 | 13.* | @@ -230,6 +243,9 @@ https://github.com/Azure/azure-sdk-for-java/issues/new #### azure-cosmos-spark_3-5_2-12 | Connector | Supported Spark Versions | Minimum Java Version | Supported Scala Versions | Supported Databricks Runtimes | |-----------|--------------------------|------------------------|--------------------------|-------------------------------| +| 4.37.1 | 3.5.0 | [8, 11] | 2.12 | 14.*, 15.\* | +| 4.37.0 | 3.5.0 | [8, 11] | 2.12 | 14.*, 15.\* | +| 4.36.1 | 3.5.0 | [8, 11] | 2.12 | 14.*, 15.\* | | 4.36.0 | 3.5.0 | [8, 11] | 2.12 | 14.*, 15.\* | | 4.35.0 | 3.5.0 | [8, 11] | 2.12 | 14.*, 15.\* | | 4.34.0 | 3.5.0 | [8, 11] | 2.12 | 14.*, 15.\* | @@ -246,11 +262,11 @@ to use the same version of Scala that Spark was compiled for. ### Download You can use the maven coordinate of the jar to auto install the Spark Connector to your Databricks Runtime 10 from Maven: -`com.azure.cosmos.spark:azure-cosmos-spark_3-2_2-12:4.36.0` +`com.azure.cosmos.spark:azure-cosmos-spark_3-2_2-12:4.37.1` You can also integrate against Cosmos DB Spark Connector in your SBT project: ```scala -libraryDependencies += "com.azure.cosmos.spark" % "azure-cosmos-spark_3-2_2-12" % "4.36.0" +libraryDependencies += "com.azure.cosmos.spark" % "azure-cosmos-spark_3-2_2-12" % "4.37.1" ``` Cosmos DB Spark Connector is available on [Maven Central Repo](https://central.sonatype.com/search?namespace=com.azure.cosmos.spark). diff --git a/sdk/cosmos/azure-cosmos-spark_3-2_2-12/pom.xml b/sdk/cosmos/azure-cosmos-spark_3-2_2-12/pom.xml index 90d2f3bf0db8..2a8090d50b10 100644 --- a/sdk/cosmos/azure-cosmos-spark_3-2_2-12/pom.xml +++ b/sdk/cosmos/azure-cosmos-spark_3-2_2-12/pom.xml @@ -11,7 +11,7 @@ com.azure.cosmos.spark azure-cosmos-spark_3-2_2-12 - 4.37.0-beta.1 + 4.38.0-beta.1 jar https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/cosmos/azure-cosmos-spark_3-2_2-12 OLTP Spark 3.2 Connector for Azure Cosmos DB SQL API @@ -111,7 +111,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 **/*.* diff --git a/sdk/cosmos/azure-cosmos-spark_3-3_2-12/CHANGELOG.md b/sdk/cosmos/azure-cosmos-spark_3-3_2-12/CHANGELOG.md index 28c1f0382497..929d137253da 100644 --- a/sdk/cosmos/azure-cosmos-spark_3-3_2-12/CHANGELOG.md +++ b/sdk/cosmos/azure-cosmos-spark_3-3_2-12/CHANGELOG.md @@ -1,6 +1,6 @@ ## Release History -### 4.37.0-beta.1 (Unreleased) +### 4.38.0-beta.1 (Unreleased) #### Features Added @@ -10,6 +10,21 @@ #### Other Changes +### 4.37.1 (2025-03-04) + +#### Features Added +* Added config option `spark.cosmos.read.responseContinuationTokenLimitInKb` to reduce query continuation token size. - See [PR 44480](https://github.com/Azure/azure-sdk-for-java/pull/44480) + +### 4.37.0 (2025-02-20) + +#### Other Changes +* Updated netty dependency + +### 4.36.1 (2025-02-08) + +#### Bugs Fixed +* Fixed an issue in change feed where under certain rare race conditions records could be skipped and excessive requests are prefetched. - See [PR 43788](https://github.com/Azure/azure-sdk-for-java/pull/43788) + ### 4.36.0 (2025-01-14) #### Features Added diff --git a/sdk/cosmos/azure-cosmos-spark_3-3_2-12/README.md b/sdk/cosmos/azure-cosmos-spark_3-3_2-12/README.md index 16c3823f64a4..3fa3eb824303 100644 --- a/sdk/cosmos/azure-cosmos-spark_3-3_2-12/README.md +++ b/sdk/cosmos/azure-cosmos-spark_3-3_2-12/README.md @@ -28,6 +28,9 @@ https://github.com/Azure/azure-sdk-for-java/issues/new #### azure-cosmos-spark_3-3_2-12 | Connector | Supported Spark Versions | Supported JVM Versions | Supported Scala Versions | Supported Databricks Runtimes | |-----------|--------------------------|------------------------|--------------------------|-------------------------------| +| 4.37.1 | 3.3.0 - 3.3.2 | [8, 11] | 2.12 | 11.\*, 12.\* | +| 4.37.0 | 3.3.0 - 3.3.2 | [8, 11] | 2.12 | 11.\*, 12.\* | +| 4.36.1 | 3.3.0 - 3.3.2 | [8, 11] | 2.12 | 11.\*, 12.\* | | 4.36.0 | 3.3.0 | [8, 11] | 2.12 | 11.\*, 12.\* | | 4.35.0 | 3.3.0 | [8, 11] | 2.12 | 11.\*, 12.\* | | 4.34.0 | 3.3.0 | [8, 11] | 2.12 | 11.\*, 12.\* | @@ -68,6 +71,9 @@ https://github.com/Azure/azure-sdk-for-java/issues/new #### azure-cosmos-spark_3-2_2-12 | Connector | Supported Spark Versions | Supported JVM Versions | Supported Scala Versions | Supported Databricks Runtimes | |-----------|--------------------------|------------------------|--------------------------|-------------------------------| +| 4.37.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | +| 4.37.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | +| 4.36.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | | 4.36.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | | 4.35.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | | 4.34.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | @@ -126,46 +132,49 @@ https://github.com/Azure/azure-sdk-for-java/issues/new #### azure-cosmos-spark_3-1_2-12 | Connector | Supported Spark Versions | Supported JVM Versions | Supported Scala Versions | Supported Databricks Runtimes | |--------------|--------------------------|------------------------|--------------------------|-------------------------------| -| 4.36.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.35.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.34.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.33.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.33.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.32.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.32.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.31.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.30.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.29.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.28.4 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.28.3 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.28.2 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.28.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.28.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.27.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.27.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.26.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.26.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.25.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.25.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.24.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.24.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.23.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.22.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.21.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.21.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.20.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.19.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.18.2 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.18.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.18.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.17.2 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.17.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.16.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.15.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.14.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.14.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.13.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.13.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.37.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 9.\* | +| 4.37.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 9.\* | +| 4.36.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 9.\* | +| 4.36.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.35.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.34.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.33.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.33.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.32.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.32.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.31.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.30.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.29.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.28.4 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.28.3 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.28.2 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.28.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.28.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.27.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.27.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.26.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.26.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.25.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.25.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.24.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.24.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.23.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.22.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.21.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.21.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.20.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.19.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.18.2 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.18.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.18.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.17.2 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.17.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.16.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.15.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.14.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.14.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.13.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.13.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | | 4.12.2 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | | 4.12.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | | 4.12.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | @@ -196,9 +205,13 @@ https://github.com/Azure/azure-sdk-for-java/issues/new | 4.0.0-beta.2 | 3.1.1 | [8, 11] | 2.12 | 8.\* | | 4.0.0-beta.1 | 3.1.1 | [8, 11] | 2.12 | 8.\* | + #### azure-cosmos-spark_3-4_2-12 | Connector | Supported Spark Versions | Supported JVM Versions | Supported Scala Versions | Supported Databricks Runtimes | |-----------|--------------------------|------------------------|--------------------------|-------------------------------| +| 4.37.1 | 3.4.0 - 3.4.1 | [8, 11] | 2.12 | 13.\* | +| 4.37.0 | 3.4.0 - 3.4.1 | [8, 11] | 2.12 | 13.\* | +| 4.36.1 | 3.4.0 | [8, 11] | 2.12 | 13.* | | 4.36.0 | 3.4.0 | [8, 11] | 2.12 | 13.* | | 4.35.0 | 3.4.0 | [8, 11] | 2.12 | 13.* | | 4.34.0 | 3.4.0 | [8, 11] | 2.12 | 13.* | @@ -230,6 +243,9 @@ https://github.com/Azure/azure-sdk-for-java/issues/new #### azure-cosmos-spark_3-5_2-12 | Connector | Supported Spark Versions | Minimum Java Version | Supported Scala Versions | Supported Databricks Runtimes | |-----------|--------------------------|----------------------|----------------------------|-------------------------------| +| 4.37.1 | 3.5.0 | [8, 11] | 2.12 | 14.*, 15.\* | +| 4.37.0 | 3.5.0 | [8, 11] | 2.12 | 14.*, 15.\* | +| 4.36.1 | 3.5.0 | [8, 11] | 2.12 | 14.*, 15.\* | | 4.36.0 | 3.5.0 | [8, 11] | 2.12 | 14.*, 15.\* | | 4.35.0 | 3.5.0 | [8, 11] | 2.12 | 14.*, 15.\* | | 4.34.0 | 3.5.0 | [8, 11] | 2.12 | 14.*, 15.\* | @@ -247,11 +263,11 @@ to use the same version of Scala that Spark was compiled for. ### Download You can use the maven coordinate of the jar to auto install the Spark Connector to your Databricks Runtime 11 from Maven: -`com.azure.cosmos.spark:azure-cosmos-spark_3-3_2-12:4.36.0` +`com.azure.cosmos.spark:azure-cosmos-spark_3-3_2-12:4.37.1` You can also integrate against Cosmos DB Spark Connector in your SBT project: ```scala -libraryDependencies += "com.azure.cosmos.spark" % "azure-cosmos-spark_3-3_2-12" % "4.36.0" +libraryDependencies += "com.azure.cosmos.spark" % "azure-cosmos-spark_3-3_2-12" % "4.37.1" ``` Cosmos DB Spark Connector is available on [Maven Central Repo](https://central.sonatype.com/search?namespace=com.azure.cosmos.spark). diff --git a/sdk/cosmos/azure-cosmos-spark_3-3_2-12/pom.xml b/sdk/cosmos/azure-cosmos-spark_3-3_2-12/pom.xml index 09293e3b7315..ec2c0486d9c6 100644 --- a/sdk/cosmos/azure-cosmos-spark_3-3_2-12/pom.xml +++ b/sdk/cosmos/azure-cosmos-spark_3-3_2-12/pom.xml @@ -11,7 +11,7 @@ com.azure.cosmos.spark azure-cosmos-spark_3-3_2-12 - 4.37.0-beta.1 + 4.38.0-beta.1 jar https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/cosmos/azure-cosmos-spark_3-3_2-12 OLTP Spark 3.3 Connector for Azure Cosmos DB SQL API @@ -116,7 +116,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 **/*.* diff --git a/sdk/cosmos/azure-cosmos-spark_3-4_2-12/CHANGELOG.md b/sdk/cosmos/azure-cosmos-spark_3-4_2-12/CHANGELOG.md index d6e8ce2d8d2a..36ec7c9908cd 100644 --- a/sdk/cosmos/azure-cosmos-spark_3-4_2-12/CHANGELOG.md +++ b/sdk/cosmos/azure-cosmos-spark_3-4_2-12/CHANGELOG.md @@ -1,6 +1,6 @@ ## Release History -### 4.37.0-beta.1 (Unreleased) +### 4.38.0-beta.1 (Unreleased) #### Features Added @@ -10,6 +10,21 @@ #### Other Changes +### 4.37.1 (2025-03-04) + +#### Features Added +* Added config option `spark.cosmos.read.responseContinuationTokenLimitInKb` to reduce query continuation token size. - See [PR 44480](https://github.com/Azure/azure-sdk-for-java/pull/44480) + +### 4.37.0 (2025-02-20) + +#### Other Changes +* Updated netty dependency + +### 4.36.1 (2025-02-08) + +#### Bugs Fixed +* Fixed an issue in change feed where under certain rare race conditions records could be skipped and excessive requests are prefetched. - See [PR 43788](https://github.com/Azure/azure-sdk-for-java/pull/43788) + ### 4.36.0 (2025-01-14) #### Features Added diff --git a/sdk/cosmos/azure-cosmos-spark_3-4_2-12/README.md b/sdk/cosmos/azure-cosmos-spark_3-4_2-12/README.md index 040d3898bb3e..a242c3cf0a3c 100644 --- a/sdk/cosmos/azure-cosmos-spark_3-4_2-12/README.md +++ b/sdk/cosmos/azure-cosmos-spark_3-4_2-12/README.md @@ -28,6 +28,9 @@ https://github.com/Azure/azure-sdk-for-java/issues/new #### azure-cosmos-spark_3-4_2-12 | Connector | Supported Spark Versions | Supported JVM Versions | Supported Scala Versions | Supported Databricks Runtimes | |-----------|--------------------------|------------------------|--------------------------|-------------------------------| +| 4.37.1 | 3.4.0 - 3.4.1 | [8, 11] | 2.12 | 13.\* | +| 4.37.0 | 3.4.0 - 3.4.1 | [8, 11] | 2.12 | 13.\* | +| 4.36.1 | 3.4.0 - 3.4.1 | [8, 11] | 2.12 | 13.\* | | 4.36.0 | 3.4.0 | [8, 11] | 2.12 | 13.* | | 4.35.0 | 3.4.0 | [8, 11] | 2.12 | 13.* | | 4.34.0 | 3.4.0 | [8, 11] | 2.12 | 13.* | @@ -59,6 +62,9 @@ https://github.com/Azure/azure-sdk-for-java/issues/new #### azure-cosmos-spark_3-3_2-12 | Connector | Supported Spark Versions | Supported JVM Versions | Supported Scala Versions | Supported Databricks Runtimes | |-----------|--------------------------|------------------------|--------------------------|-------------------------------| +| 4.37.1 | 3.3.0 - 3.3.2 | [8, 11] | 2.12 | 11.\*, 12.\* | +| 4.37.0 | 3.3.0 - 3.3.2 | [8, 11] | 2.12 | 11.\*, 12.\* | +| 4.36.1 | 3.3.0 - 3.3.2 | [8, 11] | 2.12 | 11.\*, 12.\* | | 4.36.0 | 3.3.0 | [8, 11] | 2.12 | 11.\*, 12.\* | | 4.35.0 | 3.3.0 | [8, 11] | 2.12 | 11.\*, 12.\* | | 4.34.0 | 3.3.0 | [8, 11] | 2.12 | 11.\*, 12.\* | @@ -99,6 +105,9 @@ https://github.com/Azure/azure-sdk-for-java/issues/new #### azure-cosmos-spark_3-2_2-12 | Connector | Supported Spark Versions | Supported JVM Versions | Supported Scala Versions | Supported Databricks Runtimes | |-----------|--------------------------|------------------------|--------------------------|-------------------------------| +| 4.37.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | +| 4.37.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | +| 4.36.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | | 4.36.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | | 4.35.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | | 4.34.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | @@ -157,46 +166,49 @@ https://github.com/Azure/azure-sdk-for-java/issues/new #### azure-cosmos-spark_3-1_2-12 | Connector | Supported Spark Versions | Supported JVM Versions | Supported Scala Versions | Supported Databricks Runtimes | |--------------|--------------------------|------------------------|--------------------------|-------------------------------| -| 4.36.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.35.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.34.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.33.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.33.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.32.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.32.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.31.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.30.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.29.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.28.4 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.28.3 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.28.2 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.28.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.28.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.27.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.27.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.26.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.26.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.25.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.25.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.24.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.24.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.23.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.22.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.21.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.21.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.20.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.19.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.18.2 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.18.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.18.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.17.2 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.17.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.16.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.15.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.14.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.14.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.13.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.13.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.37.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 9.\* | +| 4.37.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 9.\* | +| 4.36.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 9.\* | +| 4.36.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.35.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.34.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.33.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.33.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.32.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.32.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.31.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.30.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.29.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.28.4 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.28.3 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.28.2 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.28.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.28.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.27.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.27.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.26.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.26.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.25.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.25.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.24.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.24.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.23.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.22.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.21.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.21.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.20.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.19.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.18.2 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.18.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.18.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.17.2 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.17.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.16.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.15.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.14.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.14.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.13.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.13.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | | 4.12.2 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | | 4.12.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | | 4.12.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | @@ -230,6 +242,9 @@ https://github.com/Azure/azure-sdk-for-java/issues/new #### azure-cosmos-spark_3-5_2-12 | Connector | Supported Spark Versions | Minimum Java Version | Supported Scala Versions | Supported Databricks Runtimes | |-----------|--------------------------|------------------------|--------------------------|-------------------------------| +| 4.37.1 | 3.5.0 | [8, 11] | 2.12 | 14.*, 15.\* | +| 4.37.0 | 3.5.0 | [8, 11] | 2.12 | 14.*, 15.\* | +| 4.36.1 | 3.5.0 | [8, 11] | 2.12 | 14.*, 15.\* | | 4.36.0 | 3.5.0 | [8, 11] | 2.12 | 14.*, 15.\* | | 4.35.0 | 3.5.0 | [8, 11] | 2.12 | 14.*, 15.\* | | 4.34.0 | 3.5.0 | [8, 11] | 2.12 | 14.*, 15.\* | @@ -247,11 +262,11 @@ to use the same version of Scala that Spark was compiled for. ### Download You can use the maven coordinate of the jar to auto install the Spark Connector to your Databricks Runtime 11 from Maven: -`com.azure.cosmos.spark:azure-cosmos-spark_3-4_2-12:4.36.0` +`com.azure.cosmos.spark:azure-cosmos-spark_3-4_2-12:4.37.1` You can also integrate against Cosmos DB Spark Connector in your SBT project: ```scala -libraryDependencies += "com.azure.cosmos.spark" % "azure-cosmos-spark_3-4_2-12" % "4.36.0" +libraryDependencies += "com.azure.cosmos.spark" % "azure-cosmos-spark_3-4_2-12" % "4.37.1" ``` Cosmos DB Spark Connector is available on [Maven Central Repo](https://central.sonatype.com/search?namespace=com.azure.cosmos.spark). diff --git a/sdk/cosmos/azure-cosmos-spark_3-4_2-12/pom.xml b/sdk/cosmos/azure-cosmos-spark_3-4_2-12/pom.xml index fb3e7f93b567..b15678e817d8 100644 --- a/sdk/cosmos/azure-cosmos-spark_3-4_2-12/pom.xml +++ b/sdk/cosmos/azure-cosmos-spark_3-4_2-12/pom.xml @@ -11,7 +11,7 @@ com.azure.cosmos.spark azure-cosmos-spark_3-4_2-12 - 4.37.0-beta.1 + 4.38.0-beta.1 jar https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/cosmos/azure-cosmos-spark_3-4_2-12 OLTP Spark 3.4 Connector for Azure Cosmos DB SQL API @@ -116,7 +116,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 **/*.* diff --git a/sdk/cosmos/azure-cosmos-spark_3-5_2-12/CHANGELOG.md b/sdk/cosmos/azure-cosmos-spark_3-5_2-12/CHANGELOG.md index 6a10f047de7c..353e89351514 100644 --- a/sdk/cosmos/azure-cosmos-spark_3-5_2-12/CHANGELOG.md +++ b/sdk/cosmos/azure-cosmos-spark_3-5_2-12/CHANGELOG.md @@ -1,6 +1,6 @@ ## Release History -### 4.37.0-beta.1 (Unreleased) +### 4.38.0-beta.1 (Unreleased) #### Features Added @@ -10,6 +10,21 @@ #### Other Changes +### 4.37.1 (2025-03-04) + +#### Features Added +* Added config option `spark.cosmos.read.responseContinuationTokenLimitInKb` to reduce query continuation token size. - See [PR 44480](https://github.com/Azure/azure-sdk-for-java/pull/44480) + +### 4.37.0 (2025-02-20) + +#### Other Changes +* Updated netty dependency + +### 4.36.1 (2025-02-08) + +#### Bugs Fixed +* Fixed an issue in change feed where under certain rare race conditions records could be skipped and excessive requests are prefetched. - See [PR 43788](https://github.com/Azure/azure-sdk-for-java/pull/43788) + ### 4.36.0 (2025-01-14) #### Features Added diff --git a/sdk/cosmos/azure-cosmos-spark_3-5_2-12/README.md b/sdk/cosmos/azure-cosmos-spark_3-5_2-12/README.md index b1d7f82b0667..d6ca21f9bbd7 100644 --- a/sdk/cosmos/azure-cosmos-spark_3-5_2-12/README.md +++ b/sdk/cosmos/azure-cosmos-spark_3-5_2-12/README.md @@ -28,6 +28,9 @@ https://github.com/Azure/azure-sdk-for-java/issues/new #### azure-cosmos-spark_3-5_2-12 | Connector | Supported Spark Versions | Minimum Java Version | Supported Scala Versions | Supported Databricks Runtimes | |-----------|--------------------------|-----------------------|---------------------------|-------------------------------| +| 4.37.1 | 3.5.0 | [8, 11] | 2.12 | 14.\*, 15.\* | +| 4.37.0 | 3.5.0 | [8, 11] | 2.12 | 14.\*, 15.\* | +| 4.36.1 | 3.5.0 | [8, 11] | 2.12 | 14.\*, 15.\* | | 4.36.0 | 3.5.0 | [8, 11] | 2.12 | 14.\*, 15.\* | | 4.35.0 | 3.5.0 | [8, 11] | 2.12 | 14.\*, 15.\* | | 4.34.0 | 3.5.0 | [8, 11] | 2.12 | 14.\*, 15.\* | @@ -45,6 +48,9 @@ to use the same version of Scala that Spark was compiled for. #### azure-cosmos-spark_3-4_2-12 | Connector | Supported Spark Versions | Supported JVM Versions | Supported Scala Versions | Supported Databricks Runtimes | |-----------|--------------------------|------------------------|--------------------------|-------------------------------| +| 4.37.1 | 3.4.0 - 3.4.1 | [8, 11] | 2.12 | 13.\* | +| 4.37.0 | 3.4.0 - 3.4.1 | [8, 11] | 2.12 | 13.\* | +| 4.36.1 | 3.4.0 - 3.4.1 | [8, 11] | 2.12 | 13.\* | | 4.36.0 | 3.4.0 | [8, 11] | 2.12 | 13.* | | 4.35.0 | 3.4.0 | [8, 11] | 2.12 | 13.* | | 4.34.0 | 3.4.0 | [8, 11] | 2.12 | 13.* | @@ -76,6 +82,9 @@ to use the same version of Scala that Spark was compiled for. #### azure-cosmos-spark_3-3_2-12 | Connector | Supported Spark Versions | Supported JVM Versions | Supported Scala Versions | Supported Databricks Runtimes | |-----------|--------------------------|------------------------|--------------------------|-------------------------------| +| 4.37.1 | 3.3.0 - 3.3.2 | [8, 11] | 2.12 | 11.\*, 12.\* | +| 4.37.0 | 3.3.0 - 3.3.2 | [8, 11] | 2.12 | 11.\*, 12.\* | +| 4.36.1 | 3.3.0 - 3.3.2 | [8, 11] | 2.12 | 11.\*, 12.\* | | 4.36.0 | 3.3.0 | [8, 11] | 2.12 | 11.\*, 12.\* | | 4.35.0 | 3.3.0 | [8, 11] | 2.12 | 11.\*, 12.\* | | 4.34.0 | 3.3.0 | [8, 11] | 2.12 | 11.\*, 12.\* | @@ -116,6 +125,9 @@ to use the same version of Scala that Spark was compiled for. #### azure-cosmos-spark_3-2_2-12 | Connector | Supported Spark Versions | Supported JVM Versions | Supported Scala Versions | Supported Databricks Runtimes | |-----------|--------------------------|------------------------|--------------------------|-------------------------------| +| 4.37.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | +| 4.37.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | +| 4.36.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | | 4.36.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | | 4.35.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | | 4.34.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | @@ -174,46 +186,49 @@ to use the same version of Scala that Spark was compiled for. #### azure-cosmos-spark_3-1_2-12 | Connector | Supported Spark Versions | Supported JVM Versions | Supported Scala Versions | Supported Databricks Runtimes | |--------------|--------------------------|------------------------|--------------------------|-------------------------------| -| 4.36.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.35.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.34.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.33.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.33.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.32.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.32.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.31.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.30.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.29.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.28.4 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.28.3 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.28.2 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.28.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.28.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.27.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.27.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.26.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.26.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.25.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.25.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.24.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.24.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.23.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.22.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.21.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.21.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.20.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.19.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.18.2 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.18.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.18.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.17.2 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.17.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.16.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.15.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 10.\* | -| 4.14.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.14.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.13.1 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | -| 4.13.0 | 3.2.0 - 3.2.1 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.37.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 9.\* | +| 4.37.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 9.\* | +| 4.36.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 9.\* | +| 4.36.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.35.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.34.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.33.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.33.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.32.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.32.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.31.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.30.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.29.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.28.4 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.28.3 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.28.2 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.28.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.28.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.27.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.27.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.26.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.26.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.25.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.25.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.24.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.24.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.23.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.22.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.21.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.21.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.20.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.19.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.18.2 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.18.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.18.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.17.2 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.17.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.16.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.15.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.14.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.14.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.13.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | +| 4.13.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | | 4.12.2 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | | 4.12.1 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | | 4.12.0 | 3.1.1 - 3.1.2 | [8, 11] | 2.12 | 8.\*, 9.\* | @@ -247,11 +262,11 @@ to use the same version of Scala that Spark was compiled for. ### Download You can use the maven coordinate of the jar to auto install the Spark Connector to your Databricks Runtime 14 from Maven: -`com.azure.cosmos.spark:azure-cosmos-spark_3-5_2-12:4.36.0` +`com.azure.cosmos.spark:azure-cosmos-spark_3-5_2-12:4.37.1` You can also integrate against Cosmos DB Spark Connector in your SBT project: ```scala -libraryDependencies += "com.azure.cosmos.spark" % "azure-cosmos-spark_3-5_2-12" % "4.36.0" +libraryDependencies += "com.azure.cosmos.spark" % "azure-cosmos-spark_3-5_2-12" % "4.37.1" ``` Cosmos DB Spark Connector is available on [Maven Central Repo](https://central.sonatype.com/search?namespace=com.azure.cosmos.spark). diff --git a/sdk/cosmos/azure-cosmos-spark_3-5_2-12/pom.xml b/sdk/cosmos/azure-cosmos-spark_3-5_2-12/pom.xml index 2adeffc29fa3..a55c937e1c65 100644 --- a/sdk/cosmos/azure-cosmos-spark_3-5_2-12/pom.xml +++ b/sdk/cosmos/azure-cosmos-spark_3-5_2-12/pom.xml @@ -11,7 +11,7 @@ com.azure.cosmos.spark azure-cosmos-spark_3-5_2-12 - 4.37.0-beta.1 + 4.38.0-beta.1 jar https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/cosmos/azure-cosmos-spark_3-5_2-12 OLTP Spark 3.5 Connector for Azure Cosmos DB SQL API @@ -116,7 +116,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 **/*.* diff --git a/sdk/cosmos/azure-cosmos-spark_3_2-12/Samples/DatabricksLiveContainerMigration/README.md b/sdk/cosmos/azure-cosmos-spark_3_2-12/Samples/DatabricksLiveContainerMigration/README.md index 149ca9d0fab5..26800027abd4 100644 --- a/sdk/cosmos/azure-cosmos-spark_3_2-12/Samples/DatabricksLiveContainerMigration/README.md +++ b/sdk/cosmos/azure-cosmos-spark_3_2-12/Samples/DatabricksLiveContainerMigration/README.md @@ -13,13 +13,13 @@ This sample shows how to live migrate between Azure Cosmos DB SQL API containers ## Provision a Spark cluster -Select the latest Azure Databricks runtime version which supports Spark 3.0 or higher. +Select the latest Azure Databricks runtime version which supports Spark 3.5 or higher. ![image](./media/spark-cluster.jpg) ## Install Azure Cosmos DB Spark Connector jar -* Install the Azure Cosmos DB Spark Connector jar on the cluster by providing maven co-ordinates `com.azure.cosmos.spark:azure-cosmos-spark_3-2_2-12:4.17.2`: +* Install the Azure Cosmos DB Spark Connector jar on the cluster by providing maven co-ordinates `com.azure.cosmos.spark:azure-cosmos-spark_3-5_2-12:4.37.1`: ![image](./media/jar.jpg) @@ -40,11 +40,11 @@ Select the latest Azure Databricks runtime version which supports Spark 3.0 or h ![image](./media/attach-cluster-o.jpg) -* Locate the below, and enter/replace the highlighted fields for Cosmos DB account URI, key, region, source database/container, target database/container, and target container partition key values as approprate. Then you are ready to click "Run all": +* Locate the below, and enter/replace the highlighted fields for Cosmos DB account URI, key, region, source database/container, target database/container, and target container partition key values as appropriate. Then you are ready to click "Run all": ![image](./media/run-notebook-o.jpg) -* As long as everything has been configured correctly, all cells should run in sequence. The final cell, which is writing data received from the source container's [change feed](https://learn.microsoft.com/azure/cosmos-db/change-feed) to the target container, will run continually. It will process all historic data from the beginning of the source container's change feed record, as well as any new changes that occur. It will not stop unless there is an error, or the notebook is explictly stopped. +* As long as everything has been configured correctly, all cells should run in sequence. The final cell, which is writing data received from the source container's [change feed](https://learn.microsoft.com/azure/cosmos-db/change-feed) to the target container, will run continually. It will process all historic data from the beginning of the source container's change feed record, as well as any new changes that occur. It will not stop unless there is an error, or the notebook is explicitly stopped. ![image](./media/streaming-o.jpg) diff --git a/sdk/cosmos/azure-cosmos-spark_3_2-12/docs/configuration-reference.md b/sdk/cosmos/azure-cosmos-spark_3_2-12/docs/configuration-reference.md index 97cdcbe205e3..23e936a94ac8 100644 --- a/sdk/cosmos/azure-cosmos-spark_3_2-12/docs/configuration-reference.md +++ b/sdk/cosmos/azure-cosmos-spark_3_2-12/docs/configuration-reference.md @@ -56,13 +56,14 @@ | `spark.cosmos.write.patch.filter` | None | Used for [Conditional patch](https://docs.microsoft.com/azure/cosmos-db/partial-document-update-getting-started#java) | ### Query Config -| Config Property Name | Default | Description | -|:-------------------------------------------------------------|:--------|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `spark.cosmos.read.customQuery` | None | When provided the custom query will be processed against the Cosmos endpoint instead of dynamically generating the query via predicate push down. Usually it is recommended to rely on Spark's predicate push down because that will allow to generate the most efficient set of filters based on the query plan. But there are a couple of predicates like aggregates (count, group by, avg, sum etc.) that cannot be pushed down yet (at least in Spark 3.1) - so the custom query is a fallback to allow them to be pushed into the query sent to Cosmos. If specified, with schema inference enabled, the custom query will also be used to infer the schema. | -| `spark.cosmos.read.maxItemCount` | `1000` | Overrides the maximum number of documents that can be returned for a single query- or change feed request. The default value is `1000` - consider increasing this only for average document sizes significantly smaller than 1KB or when projection reduces the number of properties selected in queries significantly (like when only selecting "id" of documents etc.). | -| `spark.cosmos.read.maxIntegratedCacheStalenessInMS` | None | Sets the max staleness window in milliseconds for the point read or query request results in the integrated cache when using the dedicated gateway. Learn more about `MaxIntegratedCacheStaleness` [here](https://learn.microsoft.com/azure/cosmos-db/integrated-cache#maxintegratedcachestaleness) | -| `spark.cosmos.read.runtimeFiltering.enabled` | true | Indicates whether dynamic partition pruning filters will be pushed down when applicable. | -| `spark.cosmos.read.readManyFiltering.enabled` | false | Indicates whether use readMany instead of query when applicable. When enabled, if there is a filter based on the readMany filtering property, readMany will be used internally. For containers with `id` being the partitionKey, the readManyFiltering property will be `id`, else it will be `_itemIdentity`. And can use udf `GetCosmosItemIdentityValue` to compute the `_itemIdentity` column. GetCosmosItemIdentityValue(id, pk) or GetCosmosItemIdentityValue(id, array(pk1, pk2, pk3)) for containers with subpartitions. | +| Config Property Name | Default | Description | +|:-------------------------------------------------------------|:--------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `spark.cosmos.read.customQuery` | None | When provided the custom query will be processed against the Cosmos endpoint instead of dynamically generating the query via predicate push down. Usually it is recommended to rely on Spark's predicate push down because that will allow to generate the most efficient set of filters based on the query plan. But there are a couple of predicates like aggregates (count, group by, avg, sum etc.) that cannot be pushed down yet (at least in Spark 3.1) - so the custom query is a fallback to allow them to be pushed into the query sent to Cosmos. If specified, with schema inference enabled, the custom query will also be used to infer the schema. | +| `spark.cosmos.read.maxItemCount` | `1000` | Overrides the maximum number of documents that can be returned for a single query- or change feed request. The default value is `1000` - consider increasing this only for average document sizes significantly smaller than 1KB or when projection reduces the number of properties selected in queries significantly (like when only selecting "id" of documents etc.). | +| `spark.cosmos.read.maxIntegratedCacheStalenessInMS` | None | Sets the max staleness window in milliseconds for the point read or query request results in the integrated cache when using the dedicated gateway. Learn more about `MaxIntegratedCacheStaleness` [here](https://learn.microsoft.com/azure/cosmos-db/integrated-cache#maxintegratedcachestaleness) | +| `spark.cosmos.read.runtimeFiltering.enabled` | true | Indicates whether dynamic partition pruning filters will be pushed down when applicable. | +| `spark.cosmos.read.readManyFiltering.enabled` | false | Indicates whether use readMany instead of query when applicable. When enabled, if there is a filter based on the readMany filtering property, readMany will be used internally. For containers with `id` being the partitionKey, the readManyFiltering property will be `id`, else it will be `_itemIdentity`. And can use udf `GetCosmosItemIdentityValue` to compute the `_itemIdentity` column. GetCosmosItemIdentityValue(id, pk) or GetCosmosItemIdentityValue(id, array(pk1, pk2, pk3)) for containers with subpartitions. | +| `spark.cosmos.read.responseContinuationTokenLimitInKb` | None | Can be used to limit the max. continuation token size the service should return for query responses. This can be used when a customer faces errors because headers are too large. The min. possible value is `1` (for 1 KB). | #### Schema Inference Config When doing read operations, users can specify a custom schema or allow the connector to infer it. Schema inference is enabled by default. diff --git a/sdk/cosmos/azure-cosmos-spark_3_2-12/docs/quick-start.md b/sdk/cosmos/azure-cosmos-spark_3_2-12/docs/quick-start.md index fc9f7a77acec..b53c7f0df2c1 100644 --- a/sdk/cosmos/azure-cosmos-spark_3_2-12/docs/quick-start.md +++ b/sdk/cosmos/azure-cosmos-spark_3_2-12/docs/quick-start.md @@ -15,10 +15,13 @@ You can use any other Spark 3.1.1 spark offering as well, also you should be abl - For Spark 3.1: - [Azure Databricks Runtime 9.1 LTS with Spark 3.1.2](https://docs.microsoft.com/azure/databricks/release-notes/runtime/9.1) - For Spark 3.2: - - [Azure Databricks Runtime 10.2 with Spark 3.2.0](https://docs.microsoft.com/azure/databricks/release-notes/runtime/10.2) + - [Azure Databricks Runtime 10.2 with Spark 3.2.1](https://docs.microsoft.com/azure/databricks/release-notes/runtime/10.4) - For Spark 3.3 - - [Azure Databricks Runtime 11.3 LTS with Spark 3.3.0](https://learn.microsoft.com/azure/databricks/release-notes/runtime/11.3) - + - [Azure Databricks Runtime 11.3 LTS with Spark 3.3.2](https://learn.microsoft.com/azure/databricks/release-notes/runtime/12.2) +- For Spark 3.4 + - [Azure Databricks Runtime 13.3 LTS with Spark 3.4.1](https://learn.microsoft.com/azure/databricks/release-notes/runtime/13.3lts) +- For Spark 3.5 + - [Azure Databricks Runtime 15.4 LTS with Spark 3.5.0](https://learn.microsoft.com/azure/databricks/release-notes/runtime/15.4lts) - (Optional) [SLF4J binding](https://www.slf4j.org/manual.html) is used to associate a specific logging framework with SLF4J. @@ -26,19 +29,19 @@ You can use any other Spark 3.1.1 spark offering as well, also you should be abl SLF4J is only needed if you plan to use logging, please also download an SLF4J binding which will link the SLF4J API with the logging implementation of your choice. See the [SLF4J user manual](https://www.slf4j.org/manual.html) for more information. For Spark 3.1: -- Install Cosmos DB Spark Connector, in your spark Cluster [com.azure.cosmos.spark:azure-cosmos-spark_3-1_2-12:4.36.0](https://search.maven.org/artifact/com.azure.cosmos.spark/azure-cosmos-spark_3-1_2-12/4.36.0/jar) +- Install Cosmos DB Spark Connector, in your spark Cluster [com.azure.cosmos.spark:azure-cosmos-spark_3-1_2-12:4.37.1](https://search.maven.org/artifact/com.azure.cosmos.spark/azure-cosmos-spark_3-1_2-12/4.37.1/jar) For Spark 3.2: -- Install Cosmos DB Spark Connector, in your spark Cluster [com.azure.cosmos.spark:azure-cosmos-spark_3-2_2-12:4.36.0](https://search.maven.org/artifact/com.azure.cosmos.spark/azure-cosmos-spark_3-2_2-12/4.36.0/jar) +- Install Cosmos DB Spark Connector, in your spark Cluster [com.azure.cosmos.spark:azure-cosmos-spark_3-2_2-12:4.37.1](https://search.maven.org/artifact/com.azure.cosmos.spark/azure-cosmos-spark_3-2_2-12/4.37.1/jar) For Spark 3.3: -- Install Cosmos DB Spark Connector, in your spark Cluster [com.azure.cosmos.spark:azure-cosmos-spark_3-3_2-12:4.36.0](https://search.maven.org/artifact/com.azure.cosmos.spark/azure-cosmos-spark_3-3_2-12/4.36.0/jar) +- Install Cosmos DB Spark Connector, in your spark Cluster [com.azure.cosmos.spark:azure-cosmos-spark_3-3_2-12:4.37.1](https://search.maven.org/artifact/com.azure.cosmos.spark/azure-cosmos-spark_3-3_2-12/4.37.1/jar) For Spark 3.4: -- Install Cosmos DB Spark Connector, in your spark Cluster [com.azure.cosmos.spark:azure-cosmos-spark_3-4_2-12:4.36.0](https://search.maven.org/artifact/com.azure.cosmos.spark/azure-cosmos-spark_3-4_2-12/4.36.0/jar) +- Install Cosmos DB Spark Connector, in your spark Cluster [com.azure.cosmos.spark:azure-cosmos-spark_3-4_2-12:4.37.1](https://search.maven.org/artifact/com.azure.cosmos.spark/azure-cosmos-spark_3-4_2-12/4.37.1/jar) For Spark 3.5: -- Install Cosmos DB Spark Connector, in your spark Cluster [com.azure.cosmos.spark:azure-cosmos-spark_3-5_2-12:4.36.0](https://search.maven.org/artifact/com.azure.cosmos.spark/azure-cosmos-spark_3-5_2-12/4.36.0/jar) +- Install Cosmos DB Spark Connector, in your spark Cluster [com.azure.cosmos.spark:azure-cosmos-spark_3-5_2-12:4.37.1](https://search.maven.org/artifact/com.azure.cosmos.spark/azure-cosmos-spark_3-5_2-12/4.37.1/jar) The getting started guide is based on PySpark however you can use the equivalent scala version as well, and you can run the following code snippet in an Azure Databricks PySpark notebook. 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 3a5e6794762b..b05f6dacfdf1 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.67.0-beta.1 + 4.68.0-beta.1 org.scala-lang.modules @@ -85,17 +85,17 @@ com.azure azure-core-serializer-json-jackson - 1.5.4 + 1.5.8 com.azure.resourcemanager azure-resourcemanager-cosmos - 2.46.0 + 2.48.0 com.azure azure-identity - 1.15.0 + 1.15.4 com.azure @@ -106,7 +106,7 @@ com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure @@ -172,7 +172,7 @@ com.azure azure-cosmos-test - 1.0.0-beta.10 + 1.0.0-beta.12 test @@ -687,7 +687,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 **/*.* diff --git a/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/CosmosItemSerializerNoExceptionWrapping.scala b/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/CosmosItemSerializerNoExceptionWrapping.scala index 64c2ce2b81ac..5a64e065eac4 100644 --- a/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/CosmosItemSerializerNoExceptionWrapping.scala +++ b/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/CosmosItemSerializerNoExceptionWrapping.scala @@ -2,5 +2,11 @@ // Licensed under the MIT License. package com.azure.cosmos -private[cosmos] abstract class CosmosItemSerializerNoExceptionWrapping extends CosmosItemSerializer(false) { +import com.azure.cosmos.implementation.ImplementationBridgeHelpers + +private[cosmos] abstract class CosmosItemSerializerNoExceptionWrapping extends CosmosItemSerializer() { + ImplementationBridgeHelpers + .CosmosItemSerializerHelper + .getCosmosItemSerializerAccessor + .setShouldWrapSerializationExceptions(this, false) } diff --git a/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/SparkBridgeInternal.scala b/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/SparkBridgeInternal.scala index 95d8107f3fb6..8c1e48212b43 100644 --- a/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/SparkBridgeInternal.scala +++ b/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/SparkBridgeInternal.scala @@ -6,7 +6,7 @@ package com.azure.cosmos import com.azure.cosmos.implementation.{DocumentCollection, ImplementationBridgeHelpers, PartitionKeyRange, SparkBridgeImplementationInternal} import com.azure.cosmos.implementation.feedranges.FeedRangeEpkImpl import com.azure.cosmos.implementation.routing.Range -import com.azure.cosmos.models.{CosmosContainerProperties, CosmosQueryRequestOptions, FeedRange, ModelBridgeInternal} +import com.azure.cosmos.models.{CosmosContainerProperties, CosmosQueryRequestOptions} import com.azure.cosmos.spark.NormalizedRange import java.time.Duration diff --git a/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/spark/ChangeFeedTable.scala b/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/spark/ChangeFeedTable.scala index 2f66f1f1cb73..474386806151 100644 --- a/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/spark/ChangeFeedTable.scala +++ b/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/spark/ChangeFeedTable.scala @@ -38,7 +38,7 @@ private[spark] object ChangeFeedTable { StructField(RawJsonBodyAttributeName, StringType, nullable=true), StructField(IdAttributeName, StringType, nullable=false), StructField(TimestampAttributeName, LongType, nullable=false), - StructField(ETagAttributeName, StringType, nullable=false), + StructField(ETagAttributeName, StringType, nullable=true), StructField(LsnAttributeName, LongType, nullable=false), StructField(MetadataJsonBodyAttributeName, StringType, nullable=false), StructField(PreviousRawJsonBodyAttributeName, StringType, nullable=true), diff --git a/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/spark/CosmosConfig.scala b/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/spark/CosmosConfig.scala index 4d0938c1b3b7..6e37f526138b 100644 --- a/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/spark/CosmosConfig.scala +++ b/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/spark/CosmosConfig.scala @@ -68,6 +68,7 @@ private[spark] object CosmosConfigNames { val AllowInvalidJsonWithDuplicateJsonProperties = "spark.cosmos.read.allowInvalidJsonWithDuplicateJsonProperties" val ReadCustomQuery = "spark.cosmos.read.customQuery" val ReadMaxItemCount = "spark.cosmos.read.maxItemCount" + val ReadResponseContinuationTokenLimitInKb = "spark.cosmos.read.responseContinuationTokenLimitInKb" val ReadPrefetchBufferSize = "spark.cosmos.read.prefetchBufferSize" val ReadForceEventualConsistency = "spark.cosmos.read.forceEventualConsistency" val ReadSchemaConversionMode = "spark.cosmos.read.schemaConversionMode" @@ -174,6 +175,7 @@ private[spark] object CosmosConfigNames { ReadForceEventualConsistency, ReadSchemaConversionMode, ReadMaxItemCount, + ReadResponseContinuationTokenLimitInKb, ReadPrefetchBufferSize, ReadInferSchemaSamplingSize, ReadInferSchemaEnabled, @@ -915,7 +917,8 @@ private case class CosmosReadConfig(forceEventualConsistency: Boolean, customQuery: Option[CosmosParameterizedQuery], throughputControlConfig: Option[CosmosThroughputControlConfig] = None, runtimeFilteringEnabled: Boolean, - readManyFilteringConfig: CosmosReadManyFilteringConfig) + readManyFilteringConfig: CosmosReadManyFilteringConfig, + responseContinuationTokenLimitInKb: Option[Int] = None) private object SchemaConversionModes extends Enumeration { type SchemaConversionMode = Value @@ -962,6 +965,13 @@ private object CosmosReadConfig { parseFromStringFunction = queryText => queryText.toInt, helpMessage = "The maximum number of documents returned in a single request. The default is 1000.") + private val ResponseContinuationTokenLimitInKb = CosmosConfigEntry[Int]( + key = CosmosConfigNames.ReadResponseContinuationTokenLimitInKb, + mandatory = false, + defaultValue = None, + parseFromStringFunction = queryText => Math.max(1, queryText.toInt), + helpMessage = "The maximum continuation token size allowed in kilo-bytes. It has to be at least 1 KB.") + private val PrefetchBufferSize = CosmosConfigEntry[Int]( key = CosmosConfigNames.ReadPrefetchBufferSize, mandatory = false, @@ -1000,6 +1010,7 @@ private object CosmosReadConfig { val customQuery = CosmosConfigEntry.parse(cfg, CustomQuery) val maxItemCount = CosmosConfigEntry.parse(cfg, MaxItemCount) val prefetchBufferSize = CosmosConfigEntry.parse(cfg, PrefetchBufferSize) + val responseContinuationTokenLimitInKb = CosmosConfigEntry.parse(cfg, ResponseContinuationTokenLimitInKb) val maxIntegratedCacheStalenessInMilliseconds = CosmosConfigEntry.parse(cfg, MaxIntegratedCacheStalenessInMilliseconds) val dedicatedGatewayRequestOptions = { val result = new DedicatedGatewayRequestOptions @@ -1034,7 +1045,8 @@ private object CosmosReadConfig { customQuery, throughputControlConfigOpt, runtimeFilteringEnabled.get, - readManyFilteringConfig) + readManyFilteringConfig, + responseContinuationTokenLimitInKb) } } diff --git a/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/spark/CosmosRowConverterBase.scala b/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/spark/CosmosRowConverterBase.scala index 3bf04f0a51fb..c8fb0ca9af58 100644 --- a/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/spark/CosmosRowConverterBase.scala +++ b/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/spark/CosmosRowConverterBase.scala @@ -712,7 +712,15 @@ private[cosmos] class CosmosRowConverterBase( case _ => null } } else { - null + objectNode.get(MetadataJsonBodyAttributeName) match { + case metadataNode: JsonNode => + metadataNode.get(IdAttributeName) match { + case valueNode: JsonNode => + Option(valueNode).fold(null: String)(v => v.asText(null)) + case _ => null + } + case _ => null + } } } diff --git a/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/spark/CosmosTableSchemaInferrer.scala b/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/spark/CosmosTableSchemaInferrer.scala index d978fc6594a3..41af8d70cef9 100644 --- a/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/spark/CosmosTableSchemaInferrer.scala +++ b/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/spark/CosmosTableSchemaInferrer.scala @@ -121,6 +121,10 @@ private object CosmosTableSchemaInferrer val queryOptions = new CosmosQueryRequestOptions() queryOptions.setMaxBufferedItemCount(cosmosInferenceConfig.inferSchemaSamplingSize) queryOptions.setDedicatedGatewayRequestOptions(cosmosReadConfig.dedicatedGatewayRequestOptions) + if (cosmosReadConfig.responseContinuationTokenLimitInKb.isDefined) { + queryOptions.setResponseContinuationTokenLimitInKb( + cosmosReadConfig.responseContinuationTokenLimitInKb.get) + } ThroughputControlHelper.populateThroughputControlGroupName( ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper diff --git a/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/spark/ItemsPartitionReader.scala b/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/spark/ItemsPartitionReader.scala index db30e92e93ea..7b789509cfcc 100644 --- a/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/spark/ItemsPartitionReader.scala +++ b/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/spark/ItemsPartitionReader.scala @@ -239,6 +239,11 @@ private case class ItemsPartitionReader queryOptions.setDedicatedGatewayRequestOptions(readConfig.dedicatedGatewayRequestOptions) queryOptions.setCosmosEndToEndOperationLatencyPolicyConfig(endToEndTimeoutPolicy) + if (readConfig.responseContinuationTokenLimitInKb.isDefined) { + queryOptions.setResponseContinuationTokenLimitInKb( + readConfig.responseContinuationTokenLimitInKb.get) + } + ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor diff --git a/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/spark/SparkUtils.scala b/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/spark/SparkUtils.scala index 39d5124fbfc7..2a154de0b7f0 100644 --- a/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/spark/SparkUtils.scala +++ b/sdk/cosmos/azure-cosmos-spark_3_2-12/src/main/scala/com/azure/cosmos/spark/SparkUtils.scala @@ -3,13 +3,9 @@ package com.azure.cosmos.spark -import com.azure.cosmos.CosmosAsyncContainer -import com.azure.cosmos.models.{CosmosQueryRequestOptions, SqlParameter, SqlQuerySpec} -import com.azure.cosmos.spark.diagnostics.ILogger import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.node.ObjectNode -import java.util.UUID import java.util.concurrent.ThreadFactory import java.util.concurrent.atomic.AtomicInteger diff --git a/sdk/cosmos/azure-cosmos-spark_3_2-12/src/test/scala/com/azure/cosmos/spark/CosmosConfigSpec.scala b/sdk/cosmos/azure-cosmos-spark_3_2-12/src/test/scala/com/azure/cosmos/spark/CosmosConfigSpec.scala index 73fc9a2563c6..f3eee25bb253 100644 --- a/sdk/cosmos/azure-cosmos-spark_3_2-12/src/test/scala/com/azure/cosmos/spark/CosmosConfigSpec.scala +++ b/sdk/cosmos/azure-cosmos-spark_3_2-12/src/test/scala/com/azure/cosmos/spark/CosmosConfigSpec.scala @@ -392,6 +392,7 @@ class CosmosConfigSpec extends UnitSpec with BasicLoggingTrait { var config = CosmosReadConfig.parseCosmosReadConfig(userConfig) config.forceEventualConsistency shouldBe false + config.responseContinuationTokenLimitInKb shouldBe None config.schemaConversionMode shouldBe SchemaConversionModes.Strict config.customQuery shouldBe empty config.maxItemCount shouldBe 1000 @@ -407,7 +408,8 @@ class CosmosConfigSpec extends UnitSpec with BasicLoggingTrait { "spark.cosmos.read.maxItemCount" -> "1000", "spark.cosmos.read.maxIntegratedCacheStalenessInMS" -> "1000", "spark.cosmos.read.runtimeFiltering.enabled" -> "false", - "spark.cosmos.read.readManyFiltering.enabled" -> "true" + "spark.cosmos.read.readManyFiltering.enabled" -> "true", + "spark.cosmos.read.responseContinuationTokenLimitInKb" -> "8" ) config = CosmosReadConfig.parseCosmosReadConfig(userConfig) @@ -417,6 +419,7 @@ class CosmosConfigSpec extends UnitSpec with BasicLoggingTrait { config.customQuery shouldBe empty config.maxItemCount shouldBe 1000 config.prefetchBufferSize shouldBe 8 + config.responseContinuationTokenLimitInKb shouldBe Some(8) config.dedicatedGatewayRequestOptions.getMaxIntegratedCacheStaleness shouldBe Duration.ofMillis(1000) config.runtimeFilteringEnabled shouldBe false config.readManyFilteringConfig.readManyFilteringEnabled shouldBe true @@ -470,7 +473,8 @@ class CosmosConfigSpec extends UnitSpec with BasicLoggingTrait { userConfig = Map( "spark.cosmos.read.forceEventualConsistency" -> "false", "spark.cosmos.read.schemaConversionMode" -> "Strict", - "spark.cosmos.read.maxItemCount" -> "1001" + "spark.cosmos.read.maxItemCount" -> "1001", + "spark.cosmos.read.responseContinuationTokenLimitInKb" -> "0" ) config = CosmosReadConfig.parseCosmosReadConfig(userConfig) @@ -480,6 +484,8 @@ class CosmosConfigSpec extends UnitSpec with BasicLoggingTrait { config.customQuery shouldBe empty config.maxItemCount shouldBe 1001 config.prefetchBufferSize shouldBe 1 + // forcing min value to be 1 + config.responseContinuationTokenLimitInKb shouldBe Some(1) } it should "parse custom query option of read configuration" in { diff --git a/sdk/cosmos/azure-cosmos-spark_3_2-12/src/test/scala/com/azure/cosmos/spark/SparkE2EChangeFeedITest.scala b/sdk/cosmos/azure-cosmos-spark_3_2-12/src/test/scala/com/azure/cosmos/spark/SparkE2EChangeFeedITest.scala index f6144f78f0aa..214db1c2f8af 100644 --- a/sdk/cosmos/azure-cosmos-spark_3_2-12/src/test/scala/com/azure/cosmos/spark/SparkE2EChangeFeedITest.scala +++ b/sdk/cosmos/azure-cosmos-spark_3_2-12/src/test/scala/com/azure/cosmos/spark/SparkE2EChangeFeedITest.scala @@ -5,18 +5,22 @@ package com.azure.cosmos.spark import com.azure.cosmos.SparkBridgeInternal import com.azure.cosmos.implementation.changefeed.common.ChangeFeedState import com.azure.cosmos.implementation.{TestConfigurations, Utils} -import com.azure.cosmos.models.PartitionKey +import com.azure.cosmos.models.{ChangeFeedPolicy, CosmosContainerProperties, PartitionKey} import com.azure.cosmos.spark.diagnostics.BasicLoggingTrait import com.azure.cosmos.spark.udf.{CreateChangeFeedOffsetFromSpark2, CreateSpark2ContinuationsFromChangeFeedOffset, GetFeedRangeForPartitionKeyValue} +import com.fasterxml.jackson.databind.node.ObjectNode import org.apache.hadoop.fs.{FileSystem, Path} import org.apache.spark.sql.functions +import org.apache.spark.sql.functions.{col, concat, lit} import org.apache.spark.sql.types._ import java.io.{BufferedReader, InputStreamReader} import java.nio.file.Paths +import java.time.Duration import java.util.UUID import scala.collection.mutable import scala.collection.mutable.ArrayBuffer +import scala.jdk.CollectionConverters.asScalaBufferConverter class SparkE2EChangeFeedITest extends IntegrationSpec @@ -522,7 +526,7 @@ class SparkE2EChangeFeedITest } // wait for the log store to get these changes - Thread.sleep(2000) + Thread.sleep(1000) val df2 = spark.read.format("cosmos.oltp.changeFeed").options(cfg).load() val groupedFrame = df2.groupBy(CosmosTableSchemaInferrer.OperationTypeAttributeName) @@ -543,6 +547,119 @@ class SparkE2EChangeFeedITest }) } + "spark change feed query streaming (full fidelity)" can "use default schema" in { + + val cosmosEndpoint = TestConfigurations.HOST + val cosmosMasterKey = TestConfigurations.MASTER_KEY + val cosmosContainerName = s"${UUID.randomUUID().toString}" + val properties: CosmosContainerProperties = + new CosmosContainerProperties(cosmosContainerName, "/pk") + properties.setChangeFeedPolicy( + ChangeFeedPolicy.createAllVersionsAndDeletesPolicy(Duration.ofMinutes(10))) + cosmosClient + .getDatabase(cosmosDatabase) + .createContainer(properties) + .block + val sinkContainerName = cosmosClient + .getDatabase(cosmosDatabase) + .createContainer(s"sink-${UUID.randomUUID().toString}", "/pk") + .block + .getProperties + .getId + + val readCfg = Map( + "spark.cosmos.accountEndpoint" -> cosmosEndpoint, + "spark.cosmos.accountKey" -> cosmosMasterKey, + "spark.cosmos.database" -> cosmosDatabase, + "spark.cosmos.container" -> cosmosContainerName, + "spark.cosmos.read.inferSchema.enabled" -> "false", + "spark.cosmos.changeFeed.mode" -> "FullFidelity", + "spark.cosmos.changeFeed.startFrom" -> "NOW", + ) + + val writeCfg = Map( + "spark.cosmos.accountEndpoint" -> cosmosEndpoint, + "spark.cosmos.accountKey" -> cosmosMasterKey, + "spark.cosmos.database" -> cosmosDatabase, + "spark.cosmos.container" -> sinkContainerName, + "spark.cosmos.write.strategy" -> "ItemOverwrite", + "spark.cosmos.write.bulk.enabled" -> "true" + ) + + val changeFeedDF = spark + .readStream + .format("cosmos.oltp.changeFeed") + .options(readCfg) + .load() + + val modifiedChangeFeedDF = changeFeedDF.withColumn("_rawBody", concat(lit("{\"id\":\""), col("id"), lit("\"}"))) + + val microBatchQuery = modifiedChangeFeedDF + .writeStream + .format("cosmos.oltp") + .options(writeCfg) + .option("checkpointLocation", "/tmp/" + UUID.randomUUID().toString) + .outputMode("append") + .start() + + val container = cosmosClient.getDatabase(cosmosDatabase).getContainer(cosmosContainerName) + + val createdObjectIds = new mutable.HashMap[String, String]() + val replacedObjectIds = new mutable.HashMap[String, String]() + val deletedObjectIds = new mutable.HashMap[String, String]() + // Perform operations for change feed to capture + for (sequenceNumber <- 1 to 20) { + val objectNode = Utils.getSimpleObjectMapper.createObjectNode() + objectNode.put("name", "Shrodigner's cat") + objectNode.put("type", "cat") + val pk = UUID.randomUUID().toString + objectNode.put("pk", pk) + objectNode.put("age", 20) + objectNode.put("sequenceNumber", sequenceNumber) + val id = UUID.randomUUID().toString + objectNode.put("id", id) + createdObjectIds.put(id, pk) + if (sequenceNumber % 2 == 0) { + replacedObjectIds.put(id, pk) + } + if (sequenceNumber % 3 == 0) { + deletedObjectIds.put(id, pk) + } + container.createItem(objectNode).block() + } + + for (id <- replacedObjectIds.keys) { + val objectNode = Utils.getSimpleObjectMapper.createObjectNode() + objectNode.put("name", "Shrodigner's cat") + objectNode.put("type", "dog") + objectNode.put("age", 25) + objectNode.put("id", id) + objectNode.put("pk", replacedObjectIds(id)) + container.replaceItem(objectNode, id, new PartitionKey(replacedObjectIds(id))).block() + } + + for (id <- deletedObjectIds.keys) { + container.deleteItem(id, new PartitionKey(deletedObjectIds(id))).block() + } + // wait for the log store to get these changes + Thread.sleep(1000) + changeFeedDF.schema.equals( + ChangeFeedTable.defaultFullFidelityChangeFeedSchemaForInferenceDisabled) shouldEqual true + microBatchQuery.processAllAvailable() + microBatchQuery.stop() + + val sinkContainer = cosmosClient.getDatabase(cosmosDatabase).getContainer(sinkContainerName) + val feedResponses = sinkContainer.queryItems("SELECT * FROM c", classOf[ObjectNode]).byPage().collectList().block() + + var numResults = 0 + for (feedResponse <- feedResponses.asScala) { + numResults += feedResponse.getResults.size() + } + + // Basic validation that something was written from bulk + numResults should be > 0 + } + "spark change feed query (incremental)" can "proceed with simulated Spark2 Checkpoint" in { val cosmosEndpoint = TestConfigurations.HOST val cosmosMasterKey = TestConfigurations.MASTER_KEY diff --git a/sdk/cosmos/azure-cosmos-spark_3_2-12/src/test/scala/com/azure/cosmos/spark/SparkE2EGatewayChangeFeedITest.scala b/sdk/cosmos/azure-cosmos-spark_3_2-12/src/test/scala/com/azure/cosmos/spark/SparkE2EGatewayChangeFeedITest.scala index 5bced2b5598b..517aff9f0d35 100644 --- a/sdk/cosmos/azure-cosmos-spark_3_2-12/src/test/scala/com/azure/cosmos/spark/SparkE2EGatewayChangeFeedITest.scala +++ b/sdk/cosmos/azure-cosmos-spark_3_2-12/src/test/scala/com/azure/cosmos/spark/SparkE2EGatewayChangeFeedITest.scala @@ -116,7 +116,6 @@ class SparkE2EGatewayChangeFeedITest assertMetrics(meterRegistry, "cosmos.client.op.latency", expectedToFind = true) assertMetrics(meterRegistry, "cosmos.client.system.avgCpuLoad", expectedToFind = true) assertMetrics(meterRegistry, "cosmos.client.req.gw", expectedToFind = true) - assertMetrics(meterRegistry, "cosmos.client.req.rntbd", expectedToFind = false) } //scalastyle:on magic.number //scalastyle:on multiple.string.literals diff --git a/sdk/cosmos/azure-cosmos-spark_3_2-12/src/test/scala/com/azure/cosmos/spark/SparkE2EQueryITestBase.scala b/sdk/cosmos/azure-cosmos-spark_3_2-12/src/test/scala/com/azure/cosmos/spark/SparkE2EQueryITestBase.scala index 81d3169c2915..c7a143493898 100644 --- a/sdk/cosmos/azure-cosmos-spark_3_2-12/src/test/scala/com/azure/cosmos/spark/SparkE2EQueryITestBase.scala +++ b/sdk/cosmos/azure-cosmos-spark_3_2-12/src/test/scala/com/azure/cosmos/spark/SparkE2EQueryITestBase.scala @@ -203,7 +203,8 @@ abstract class SparkE2EQueryITestBase "spark.cosmos.database" -> cosmosDatabase, "spark.cosmos.container" -> cosmosContainer, "spark.cosmos.read.maxItemCount" -> "1", - "spark.cosmos.read.partitioning.strategy" -> "Restrictive" + "spark.cosmos.read.partitioning.strategy" -> "Restrictive", + "spark.cosmos.read.responseContinuationTokenLimitInKb" -> "1" ) val df = spark.read.format("cosmos.oltp").options(cfg).load() diff --git a/sdk/cosmos/azure-cosmos-test/CHANGELOG.md b/sdk/cosmos/azure-cosmos-test/CHANGELOG.md index cc3aa49e84a9..106424637f57 100644 --- a/sdk/cosmos/azure-cosmos-test/CHANGELOG.md +++ b/sdk/cosmos/azure-cosmos-test/CHANGELOG.md @@ -1,6 +1,6 @@ ## Release History -### 1.0.0-beta.10 (Unreleased) +### 1.0.0-beta.12 (Unreleased) #### Features Added @@ -10,6 +10,16 @@ #### Other Changes +### 1.0.0-beta.11 (2025-02-20) + +#### Other Changes +* Updated `azure-cosmos` to version `4.67.0`. + +### 1.0.0-beta.10 (2025-02-08) + +#### Other Changes +* Updated `azure-cosmos` to version `4.66.1`. + ### 1.0.0-beta.9 (2024-09-10) #### Other Changes diff --git a/sdk/cosmos/azure-cosmos-test/README.md b/sdk/cosmos/azure-cosmos-test/README.md index d23c99c4571f..ef647d5a6d34 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.9 + 1.0.0-beta.12 ``` [//]: # ({x-version-update-end}) @@ -158,7 +158,7 @@ or contact [opencode@microsoft.com][coc_contact] with any additional questions o [cosmos_introduction]: https://learn.microsoft.com/azure/cosmos-db/ -[api_documentation]: https://azuresdkdocs.blob.core.windows.net/$web/java/azure-cosmos/latest/index.html +[api_documentation]: https://azuresdkdocs.z19.web.core.windows.net/java/azure-cosmos/latest/index.html [cosmos_docs]: https://learn.microsoft.com/azure/cosmos-db/introduction [jdk]: https://learn.microsoft.com/java/azure/jdk/ [maven]: https://maven.apache.org/ @@ -170,3 +170,4 @@ or contact [opencode@microsoft.com][coc_contact] with any additional questions o [troubleshooting]: https://learn.microsoft.com/azure/cosmos-db/troubleshoot-java-sdk-v4-sql [perf_guide]: https://learn.microsoft.com/azure/cosmos-db/performance-tips-java-sdk-v4-sql?tabs=api-async [quickstart]: https://learn.microsoft.com/azure/cosmos-db/create-sql-api-java?tabs=sync + diff --git a/sdk/cosmos/azure-cosmos-test/pom.xml b/sdk/cosmos/azure-cosmos-test/pom.xml index 3c9414c0f12c..222aa7938eab 100644 --- a/sdk/cosmos/azure-cosmos-test/pom.xml +++ b/sdk/cosmos/azure-cosmos-test/pom.xml @@ -13,7 +13,7 @@ Licensed under the MIT License. com.azure azure-cosmos-test - 1.0.0-beta.10 + 1.0.0-beta.12 Microsoft Azure Java Cosmos Test Library This package contains core fault injection types for Azure Java Cosmos client. jar @@ -59,7 +59,7 @@ Licensed under the MIT License. com.azure azure-cosmos - 4.67.0-beta.1 + 4.68.0-beta.1 @@ -149,7 +149,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 unit @@ -195,7 +195,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 @@ -213,7 +213,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/multi-region-testng.xml @@ -234,7 +234,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/fast-testng.xml diff --git a/sdk/cosmos/azure-cosmos-test/src/main/java/com/azure/cosmos/test/implementation/faultinjection/FaultInjectionRuleProcessor.java b/sdk/cosmos/azure-cosmos-test/src/main/java/com/azure/cosmos/test/implementation/faultinjection/FaultInjectionRuleProcessor.java index 7682743b3a96..85a5843a304f 100644 --- a/sdk/cosmos/azure-cosmos-test/src/main/java/com/azure/cosmos/test/implementation/faultinjection/FaultInjectionRuleProcessor.java +++ b/sdk/cosmos/azure-cosmos-test/src/main/java/com/azure/cosmos/test/implementation/faultinjection/FaultInjectionRuleProcessor.java @@ -23,8 +23,8 @@ import com.azure.cosmos.implementation.directconnectivity.AddressSelector; import com.azure.cosmos.implementation.directconnectivity.rntbd.RntbdUtils; import com.azure.cosmos.implementation.feedranges.FeedRangeInternal; -import com.azure.cosmos.implementation.routing.LocationCache; import com.azure.cosmos.implementation.routing.PartitionKeyRangeIdentity; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; import com.azure.cosmos.test.faultinjection.FaultInjectionCondition; import com.azure.cosmos.test.faultinjection.FaultInjectionConnectionErrorResult; import com.azure.cosmos.test.faultinjection.FaultInjectionConnectionType; @@ -447,8 +447,7 @@ private Mono> resolvePhysicalAddresses( ResourceType.Document, null); - faultInjectionAddressRequest.requestContext.locationEndpointToRoute = regionEndpoint; - faultInjectionAddressRequest.requestContext.consolidatedRegionalEndpointToRoute = new LocationCache.ConsolidatedRegionalEndpoint(regionEndpoint, null); + faultInjectionAddressRequest.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(regionEndpoint); faultInjectionAddressRequest.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity(pkRangeId)); if (isWriteOnly) { diff --git a/sdk/cosmos/azure-cosmos-tests/README.md b/sdk/cosmos/azure-cosmos-tests/README.md index a4182933b2e0..10f0b6af19a8 100644 --- a/sdk/cosmos/azure-cosmos-tests/README.md +++ b/sdk/cosmos/azure-cosmos-tests/README.md @@ -31,7 +31,7 @@ or contact [opencode@microsoft.com][coc_contact] with any additional questions o [cosmos_introduction]: https://learn.microsoft.com/azure/cosmos-db/ -[api_documentation]: https://azuresdkdocs.blob.core.windows.net/$web/java/azure-cosmos/latest/index.html +[api_documentation]: https://azuresdkdocs.z19.web.core.windows.net/java/azure-cosmos/latest/index.html [cosmos_docs]: https://learn.microsoft.com/azure/cosmos-db/introduction [jdk]: https://learn.microsoft.com/java/azure/jdk/ [maven]: https://maven.apache.org/ @@ -43,3 +43,4 @@ or contact [opencode@microsoft.com][coc_contact] with any additional questions o [troubleshooting]: https://learn.microsoft.com/azure/cosmos-db/troubleshoot-java-sdk-v4-sql [perf_guide]: https://learn.microsoft.com/azure/cosmos-db/performance-tips-java-sdk-v4-sql?tabs=api-async [quickstart]: https://learn.microsoft.com/azure/cosmos-db/create-sql-api-java?tabs=sync + diff --git a/sdk/cosmos/azure-cosmos-tests/pom.xml b/sdk/cosmos/azure-cosmos-tests/pom.xml index 14c9ecf3c88e..d3a31a4b015c 100644 --- a/sdk/cosmos/azure-cosmos-tests/pom.xml +++ b/sdk/cosmos/azure-cosmos-tests/pom.xml @@ -100,12 +100,12 @@ Licensed under the MIT License. com.azure azure-cosmos - 4.67.0-beta.1 + 4.68.0-beta.1 com.azure azure-cosmos-test - 1.0.0-beta.10 + 1.0.0-beta.12 commons-io @@ -151,7 +151,7 @@ Licensed under the MIT License. com.azure azure-identity - 1.15.0 + 1.15.4 test @@ -230,7 +230,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 unit @@ -249,7 +249,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-checkstyle-plugin - 3.5.0 + 3.6.0 false false @@ -311,7 +311,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 @@ -329,7 +329,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/fast-testng.xml @@ -350,7 +350,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/split-testng.xml @@ -371,7 +371,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/cfp-split-testng.xml @@ -392,7 +392,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/query-testng.xml @@ -413,7 +413,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/long-testng.xml @@ -434,7 +434,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/direct-testng.xml @@ -455,7 +455,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/multi-master-testng.xml @@ -476,7 +476,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/circuit-breaker-read-all-read-many-testng.xml @@ -497,7 +497,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/circuit-breaker-misc-direct-testng.xml @@ -518,7 +518,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/circuit-breaker-misc-gateway-testng.xml @@ -539,7 +539,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/flaky-multi-master-testng.xml @@ -560,7 +560,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/multi-region-testng.xml @@ -582,7 +582,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/examples-testng.xml @@ -611,7 +611,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/emulator-testng.xml @@ -632,7 +632,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/emulator-vnext-testng.xml @@ -653,7 +653,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 src/test/resources/e2e-testng.xml diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/ClientMetricsTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/ClientMetricsTest.java index 4268aed8704b..0fbb063cdc6d 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/ClientMetricsTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/ClientMetricsTest.java @@ -9,6 +9,7 @@ import com.azure.cosmos.implementation.AsyncDocumentClient; import com.azure.cosmos.implementation.Configs; import com.azure.cosmos.implementation.ConsoleLoggingRegistryFactory; +import com.azure.cosmos.implementation.DiagnosticsProvider; import com.azure.cosmos.implementation.GlobalEndpointManager; import com.azure.cosmos.implementation.ImplementationBridgeHelpers; import com.azure.cosmos.implementation.InternalObjectNode; @@ -88,6 +89,8 @@ public class ClientMetricsTest extends BatchTestBase { private CosmosClientTelemetryConfig inputClientTelemetryConfig; private CosmosMicrometerMetricsOptions inputMetricsOptions; private Tag clientCorrelationTag; + private long diagnosticHandlerFailuresBaseline; + private DiagnosticsProvider diagnosticsProvider; @Factory(dataProvider = "clientBuildersWithDirectTcpSession") public ClientMetricsTest(CosmosClientBuilder clientBuilder) { @@ -113,7 +116,6 @@ public void beforeTest( assertThat(this.meterRegistry).isNull(); this.meterRegistry = ConsoleLoggingRegistryFactory.create(1); - this.inputMetricsOptions = new CosmosMicrometerMetricsOptions() .meterRegistry(this.meterRegistry) .setMetricCategories(metricCategories) @@ -137,6 +139,9 @@ public void beforeTest( .clientTelemetryConfig(inputClientTelemetryConfig) .buildClient(); + this.diagnosticsProvider = ReflectionUtils.getDiagnosticsProvider(client.asyncClient()); + this.diagnosticHandlerFailuresBaseline = diagnosticsProvider.getDiagnosticHandlerFailuresSnapshot(); + assertThat( ImplementationBridgeHelpers .CosmosAsyncClientHelper @@ -162,6 +167,10 @@ public void beforeTest( } public void afterTest() { + if (this.diagnosticsProvider != null) { + assertThat(this.diagnosticsProvider.getDiagnosticHandlerFailuresSnapshot()) + .isEqualTo(this.diagnosticHandlerFailuresBaseline); + } this.container = null; CosmosClient clientSnapshot = this.client; if (clientSnapshot != null) { @@ -414,6 +423,38 @@ public void readItem() throws Exception { } } + @Test(groups = { "fast" }, timeOut = TIMEOUT) + public void readNonExistingItem() throws Exception { + this.beforeTest(CosmosMetricCategory.DEFAULT); + try { + + try { + container.readItem( + UUID.randomUUID().toString(), + new PartitionKey(UUID.randomUUID().toString()), + new CosmosItemRequestOptions(), + InternalObjectNode.class); + } catch (CosmosException expectedError) { + assertThat(expectedError.getStatusCode()).isEqualTo(404); + assertThat(expectedError.getSubStatusCode()).isEqualTo(0); + } + + this.validateMetrics( + Tag.of( + TagName.Operation.toString(), "Document/Read"), + Tag.of(TagName.RequestOperationType.toString(), "Document/Read"), + 0, + 500 + ); + + Tag queryPlanTag = Tag.of(TagName.RequestOperationType.toString(), "DocumentCollection_QueryPlan"); + this.assertMetrics("cosmos.client.req.gw", false, queryPlanTag); + this.assertMetrics("cosmos.client.req.rntbd", false, queryPlanTag); + } finally { + this.afterTest(); + } + } + @Test(groups = { "fast" }, timeOut = TIMEOUT) public void readManySingleItem() throws Exception { this.beforeTest(CosmosMetricCategory.DEFAULT); @@ -563,7 +604,7 @@ public void replaceItem() throws Exception { validateItemResponse(properties, itemResponse); String newPropValue = UUID.randomUUID().toString(); - properties.set("newProp", newPropValue, CosmosItemSerializer.DEFAULT_SERIALIZER); + properties.set("newProp", newPropValue); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); ModelBridgeInternal.setPartitionKey(options, new PartitionKey(properties.get("mypk"))); // replace document diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/ClientTelemetryTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/ClientTelemetryTest.java index 3fa7894e3689..5b2809d6705d 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/ClientTelemetryTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/ClientTelemetryTest.java @@ -430,7 +430,7 @@ private InternalObjectNode getInternalObjectNode() { InternalObjectNode internalObjectNode = new InternalObjectNode(); String uuid = UUID.randomUUID().toString(); internalObjectNode.setId(uuid); - internalObjectNode.set("mypk", uuid, CosmosItemSerializer.DEFAULT_SERIALIZER); + internalObjectNode.set("mypk", uuid); return internalObjectNode; } diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/CosmosContainerChangeFeedTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/CosmosContainerChangeFeedTest.java index 134a6a7e09d0..827bf2c8ca76 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/CosmosContainerChangeFeedTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/CosmosContainerChangeFeedTest.java @@ -10,6 +10,7 @@ import com.azure.cosmos.implementation.ImplementationBridgeHelpers; import com.azure.cosmos.implementation.RetryAnalyzer; import com.azure.cosmos.implementation.Utils; +import com.azure.cosmos.implementation.changefeed.common.ChangeFeedMode; import com.azure.cosmos.implementation.changefeed.common.ChangeFeedState; import com.azure.cosmos.implementation.changefeed.common.ChangeFeedStateV1; import com.azure.cosmos.implementation.feedranges.FeedRangeEpkImpl; @@ -48,6 +49,7 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; +import org.testng.annotations.Ignore; import org.testng.annotations.Test; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -119,6 +121,14 @@ public static Object[][] changeFeedQueryEndLSNDataProvider() { }; } + @DataProvider(name = "changeFeedQueryPrefetchingDataProvider") + public static Object[][] changeFeedQueryPrefetchingDataProvider() { + return new Object[][]{ + {ChangeFeedMode.FULL_FIDELITY}, + { ChangeFeedMode.INCREMENTAL}, + }; + } + @DataProvider(name = "changeFeedQueryEndLSNHangDataProvider") public static Object[][] changeFeedQueryEndLSNHangDataProvider() { return new Object[][]{ @@ -323,6 +333,63 @@ public void asyncChangeFeed_fromBeginning_incremental_forLogicalPartition() thro } } + @Test(groups = { "emulator" }, dataProvider = "changeFeedQueryPrefetchingDataProvider", timeOut = TIMEOUT) + public void asyncChangeFeedPrefetching(ChangeFeedMode changeFeedMode) throws Exception { + this.createContainer( + (cp) -> { + if (changeFeedMode.equals(ChangeFeedMode.INCREMENTAL)) { + return cp.setChangeFeedPolicy(ChangeFeedPolicy.createLatestVersionPolicy()); + } + return cp.setChangeFeedPolicy(ChangeFeedPolicy.createAllVersionsAndDeletesPolicy(Duration.ofMinutes(10))); + } + ); + CosmosChangeFeedRequestOptions options; + if (changeFeedMode.equals(ChangeFeedMode.FULL_FIDELITY)) { + options = CosmosChangeFeedRequestOptions + .createForProcessingFromNow(FeedRange.forFullRange()) + .setMaxItemCount(10).allVersionsAndDeletes(); + } else { + options = CosmosChangeFeedRequestOptions + .createForProcessingFromBeginning(FeedRange.forFullRange()).setMaxItemCount(10); + } + AtomicInteger count = new AtomicInteger(0); + insertDocuments(5, 20); + AtomicReference continuation = new AtomicReference<>(""); + createdContainer.asyncContainer.queryChangeFeed(options, ObjectNode.class).handle((r) -> { + count.incrementAndGet(); + continuation.set(r.getContinuationToken()); + } + ).byPage().subscribe(); + + CosmosChangeFeedRequestOptions optionsFF = null; + if (changeFeedMode.equals(ChangeFeedMode.FULL_FIDELITY)) { + insertDocuments(5, 20); + count.set(0); + optionsFF = CosmosChangeFeedRequestOptions + .createForProcessingFromContinuation(continuation.get()) + .setMaxItemCount(10).allVersionsAndDeletes(); + createdContainer.asyncContainer.queryChangeFeed(optionsFF, ObjectNode.class).handle((r) -> { + count.incrementAndGet(); + continuation.set(r.getContinuationToken()); + } + ).byPage().subscribe(); + } + Thread.sleep(3000); + assertThat(count.get()).isGreaterThan(2); + + if (changeFeedMode.equals(ChangeFeedMode.FULL_FIDELITY)) { + // full fidelity is only from now so need to insert more documents + insertDocuments(5, 20); + } + count.set(0); + // should only get two pages + createdContainer.asyncContainer.queryChangeFeed(changeFeedMode.equals(ChangeFeedMode.FULL_FIDELITY)? optionsFF + : options, ObjectNode.class).handle((r) -> count.incrementAndGet()) + .byPage().take(2, true).subscribe(); + Thread.sleep(3000); + assertThat(count.get()).isEqualTo(2); + } + @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void asyncChangeFeed_fromBeginning_incremental_forEPK() throws Exception { this.createContainer( @@ -880,6 +947,7 @@ public void split_only_notModified() throws Exception { assertThat(stateAfterLastDrainAttempt.getContinuation().getCompositeContinuationTokens()).hasSize(3); } + @Ignore @Test(groups = { "fast" }, dataProvider = "changeFeedQueryEndLSNDataProvider", timeOut = 100 * TIMEOUT) public void changeFeedQueryCompleteAfterEndLSN( int throughput, diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/CosmosDiagnosticsTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/CosmosDiagnosticsTest.java index 249a402127c9..c5b7129ea727 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/CosmosDiagnosticsTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/CosmosDiagnosticsTest.java @@ -1119,12 +1119,6 @@ public void directDiagnosticsOnException() throws Exception { assertThat(responseStatisticsList.size()).isGreaterThan(0); JsonNode storeResult = responseStatisticsList.get(0).get("storeResult"); assertThat(storeResult).isNotNull(); - int currentReplicaSetSize = storeResult.get("currentReplicaSetSize").asInt(-1); - assertThat(currentReplicaSetSize).isEqualTo(-1); - JsonNode replicaStatusList = storeResult.get("replicaStatusList"); - assertThat(replicaStatusList.isObject()).isTrue(); - int quorumAcked = storeResult.get("quorumAckedLSN").asInt(-1); - assertThat(quorumAcked).isEqualTo(-1); } } @@ -1833,7 +1827,7 @@ private InternalObjectNode getInternalObjectNode() { InternalObjectNode internalObjectNode = new InternalObjectNode(); String uuid = UUID.randomUUID().toString(); internalObjectNode.setId(uuid); - internalObjectNode.set("mypk", uuid, CosmosItemSerializer.DEFAULT_SERIALIZER); + internalObjectNode.set("mypk", uuid); return internalObjectNode; } @@ -1841,7 +1835,7 @@ private InternalObjectNode getInternalObjectNode(String pkValue) { InternalObjectNode internalObjectNode = new InternalObjectNode(); String uuid = UUID.randomUUID().toString(); internalObjectNode.setId(uuid); - internalObjectNode.set( "mypk", pkValue, CosmosItemSerializer.DEFAULT_SERIALIZER); + internalObjectNode.set( "mypk", pkValue); return internalObjectNode; } diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/CosmosItemContentResponseOnWriteTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/CosmosItemContentResponseOnWriteTest.java index 7222de246a3b..421a9a415750 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/CosmosItemContentResponseOnWriteTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/CosmosItemContentResponseOnWriteTest.java @@ -126,7 +126,7 @@ public void replaceItem_withContentResponseOnWriteDisabled() { validateMinimalItemResponse(properties, itemResponse, true); String newPropValue = UUID.randomUUID().toString(); - properties.set("newProp", newPropValue, CosmosItemSerializer.DEFAULT_SERIALIZER); + properties.set("newProp", newPropValue); ModelBridgeInternal.setPartitionKey(cosmosItemRequestOptions, new PartitionKey(properties.get("mypk"))); // replace document @@ -148,7 +148,7 @@ public void replaceItem_withContentResponseOnWriteEnabledThroughRequestOptions() validateItemResponse(properties, itemResponse); String newPropValue = UUID.randomUUID().toString(); - properties.set("newProp", newPropValue, CosmosItemSerializer.DEFAULT_SERIALIZER); + properties.set("newProp", newPropValue); ModelBridgeInternal.setPartitionKey(cosmosItemRequestOptions, new PartitionKey(properties.get("mypk"))); // replace document diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/CosmosItemSerializerNoExceptionWrapping.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/CosmosItemSerializerNoExceptionWrapping.java index 91c1de2184ad..a2c15a5af177 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/CosmosItemSerializerNoExceptionWrapping.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/CosmosItemSerializerNoExceptionWrapping.java @@ -6,8 +6,13 @@ package com.azure.cosmos; +import com.azure.cosmos.implementation.ImplementationBridgeHelpers; + public abstract class CosmosItemSerializerNoExceptionWrapping extends CosmosItemSerializer { public CosmosItemSerializerNoExceptionWrapping() { - super(false); + ImplementationBridgeHelpers + .CosmosItemSerializerHelper + .getCosmosItemSerializerAccessor() + .setShouldWrapSerializationExceptions(this, false); } } diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/CosmosItemSerializerUnitTests.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/CosmosItemSerializerUnitTests.java new file mode 100644 index 000000000000..82cc7bf9f213 --- /dev/null +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/CosmosItemSerializerUnitTests.java @@ -0,0 +1,200 @@ +package com.azure.cosmos; + +import com.azure.cosmos.implementation.Configs; +import com.azure.cosmos.implementation.DefaultCosmosItemSerializer; +import com.azure.cosmos.implementation.Utils; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +public class CosmosItemSerializerUnitTests { + protected static Logger logger = LoggerFactory.getLogger(CosmosItemSerializerUnitTests.class.getSimpleName()); + @DataProvider + public static Object[][] serializationInclusionModeDataProvider() { + List providers = new ArrayList<>(); + + providers.add( + new Object[] { + "", + "{\"id\":\"SomeId\",\"defaultValueProperty\":0,\"nullValueProperty\":null,\"emptyValueProperty\":\"\"}" + }); + providers.add( + new Object[] { + null, + "{\"id\":\"SomeId\",\"defaultValueProperty\":0,\"nullValueProperty\":null,\"emptyValueProperty\":\"\"}" + } + ); + providers.add( + new Object[] { + "Always", + "{\"id\":\"SomeId\",\"defaultValueProperty\":0,\"nullValueProperty\":null,\"emptyValueProperty\":\"\"}" + } + ); + providers.add( + new Object[] { + "NonNull", + "{\"id\":\"SomeId\",\"defaultValueProperty\":0,\"emptyValueProperty\":\"\"}" + } + ); + providers.add( + new Object[] { + "NOnNULl", + "{\"id\":\"SomeId\",\"defaultValueProperty\":0,\"emptyValueProperty\":\"\"}" + } + ); + providers.add( + new Object[] { + "NonDefault", + "{\"id\":\"SomeId\",\"defaultValueProperty\":0,\"emptyValueProperty\":\"\"}" + } + ); + providers.add( + new Object[] { + "NonEmpty", + "{\"id\":\"SomeId\",\"defaultValueProperty\":0}" + } + ); + + Object[][] array = new Object[providers.size()][]; + + return providers.toArray(array); + } + + @DataProvider + public static Object[][] serializationInclusionModePojoDataProvider() { + List providers = new ArrayList<>(); + + providers.add( + new Object[] { + "", + "{\"id\":\"SomeId\",\"defaultValueProperty\":0,\"nullValueProperty\":null,\"emptyValueProperty\":\"\"}" + }); + providers.add( + new Object[] { + null, + "{\"id\":\"SomeId\",\"defaultValueProperty\":0,\"nullValueProperty\":null,\"emptyValueProperty\":\"\"}" + } + ); + providers.add( + new Object[] { + "Always", + "{\"id\":\"SomeId\",\"defaultValueProperty\":0,\"nullValueProperty\":null,\"emptyValueProperty\":\"\"}" + } + ); + providers.add( + new Object[] { + "NonNull", + "{\"id\":\"SomeId\",\"defaultValueProperty\":0,\"emptyValueProperty\":\"\"}" + } + ); + providers.add( + new Object[] { + "NOnNULl", + "{\"id\":\"SomeId\",\"defaultValueProperty\":0,\"emptyValueProperty\":\"\"}" + } + ); + providers.add( + new Object[] { + "NonDefault", + "{\"id\":\"SomeId\"}" + } + ); + providers.add( + new Object[] { + "NonEmpty", + "{\"id\":\"SomeId\",\"defaultValueProperty\":0}" + } + ); + + Object[][] array = new Object[providers.size()][]; + + return providers.toArray(array); + } + + @Test(groups = { "unit" }, dataProvider = "serializationInclusionModeDataProvider") + public void serializationInclusionModesTests( + String systemPropertyValue, + String expectedOutcome + ) { + try { + if (systemPropertyValue != null) { + System.setProperty(Configs.ITEM_SERIALIZATION_INCLUSION_MODE, systemPropertyValue); + } + runSerializationInclusionModeTest(expectedOutcome); + } finally { + System.clearProperty(Configs.ITEM_SERIALIZATION_INCLUSION_MODE); + } + } + + @Test(groups = { "unit" }, dataProvider = "serializationInclusionModePojoDataProvider") + public void serializationInclusionModesPojoTests( + String systemPropertyValue, + String expectedOutcome + ) { + try { + if (systemPropertyValue != null) { + System.setProperty(Configs.ITEM_SERIALIZATION_INCLUSION_MODE, systemPropertyValue); + } + runSerializationInclusionModePojoTest(expectedOutcome); + } finally { + System.clearProperty(Configs.ITEM_SERIALIZATION_INCLUSION_MODE); + } + } + + private void runSerializationInclusionModeTest(String expectedOutcome) { + + ObjectMapper mapper = Utils.getDocumentObjectMapper(Configs.getItemSerializationInclusionMode()); + CosmosItemSerializer serializer = new DefaultCosmosItemSerializer(mapper); + + ObjectNode node = Utils.getSimpleObjectMapper().createObjectNode(); + node.put("id", "SomeId"); + node.put("defaultValueProperty", 0); + node.put("nullValueProperty", (String)null); + node.put("emptyValueProperty", ""); + Map jsonMap = serializer.serialize(node); + ByteBuffer buffer = Utils.serializeJsonToByteBuffer( + serializer, + jsonMap, + null, + false); + String json = new String(buffer.array(), 0, buffer.limit(), StandardCharsets.UTF_8); + logger.info("Actual: {}, Expected: {}", json, expectedOutcome); + assertThat(json).isEqualTo(expectedOutcome); + } + + private void runSerializationInclusionModePojoTest(String expectedOutcome) { + + ObjectMapper mapper = Utils.getDocumentObjectMapper(Configs.getItemSerializationInclusionMode()); + CosmosItemSerializer serializer = new DefaultCosmosItemSerializer(mapper); + + PojoItem node = new PojoItem(); + Map jsonMap = serializer.serialize(node); + ByteBuffer buffer = Utils.serializeJsonToByteBuffer( + serializer, + jsonMap, + null, + false); + String json = new String(buffer.array(), 0, buffer.limit(), StandardCharsets.UTF_8); + logger.info("Actual: {}, Expected: {}", json, expectedOutcome); + assertThat(json).isEqualTo(expectedOutcome); + } + + private static class PojoItem + { + public String id = "SomeId"; + public int defaultValueProperty = 0; + public String nullValueProperty = null; + public String emptyValueProperty = ""; + } +} diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/CosmosItemTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/CosmosItemTest.java index bbc7e26a3104..ba56c121e577 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/CosmosItemTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/CosmosItemTest.java @@ -59,7 +59,6 @@ import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; @@ -140,7 +139,7 @@ public void createLargeItem() throws Exception { //Keep size as ~ 1.5MB to account for size of other props int size = (int) (ONE_MB * 1.5); - docDefinition.set("largeString", StringUtils.repeat("x", size), CosmosItemSerializer.DEFAULT_SERIALIZER); + docDefinition.set("largeString", StringUtils.repeat("x", size)); CosmosItemResponse itemResponse = container.createItem(docDefinition, new CosmosItemRequestOptions()); @@ -154,7 +153,7 @@ public void createItemWithVeryLargePartitionKey() throws Exception { for(int i = 0; i < 100; i++) { sb.append(i).append("x"); } - docDefinition.set("mypk", sb.toString(), CosmosItemSerializer.DEFAULT_SERIALIZER); + docDefinition.set("mypk", sb.toString()); CosmosItemResponse itemResponse = container.createItem(docDefinition, new CosmosItemRequestOptions()); @@ -168,7 +167,7 @@ public void readItemWithVeryLargePartitionKey() throws Exception { for(int i = 0; i < 100; i++) { sb.append(i).append("x"); } - docDefinition.set("mypk", sb.toString(), CosmosItemSerializer.DEFAULT_SERIALIZER); + docDefinition.set("mypk", sb.toString()); CosmosItemResponse itemResponse = container.createItem(docDefinition); @@ -1100,7 +1099,7 @@ public void replaceItem() throws Exception{ validateItemResponse(properties, itemResponse); String newPropValue = UUID.randomUUID().toString(); - properties.set("newProp", newPropValue, CosmosItemSerializer.DEFAULT_SERIALIZER); + properties.set("newProp", newPropValue); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); ModelBridgeInternal.setPartitionKey(options, new PartitionKey(properties.get("mypk"))); // replace document diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/CosmosTracerTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/CosmosTracerTest.java index f08a5ef4fb7a..795e883b6681 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/CosmosTracerTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/CosmosTracerTest.java @@ -911,6 +911,36 @@ public void cosmosAsyncContainer( mockTracer.reset(); } + @Test(groups = { "fast", "simple" }, timeOut = 10 * TIMEOUT) + public void readItemWith404() { + ITEM_ID = "tracerDoc_" + testCaseCount.incrementAndGet(); + TracerUnderTest mockTracer = Mockito.spy(new TracerUnderTest()); + + DiagnosticsProvider provider = createAndInitializeDiagnosticsProvider( + mockTracer, + false, + true, + ShowQueryMode.NONE, + false, + 1); + + long diagnosticHandlerFailuresBaseline = provider.getDiagnosticHandlerFailuresSnapshot(); + try { + cosmosAsyncContainer + .readItem(ITEM_ID, new PartitionKey(ITEM_ID), null, ObjectNode.class) + .block(); + + fail("404 Expected"); + } catch (CosmosException cosmosException) { + assertThat(cosmosException.getStatusCode()).isEqualTo(404); + } + + assertThat(provider.getDiagnosticHandlerFailuresSnapshot()) + .isEqualTo(diagnosticHandlerFailuresBaseline); + + mockTracer.reset(); + } + @Test(groups = { "fast", "simple" }, dataProvider = "traceTestCaseProvider", timeOut = TIMEOUT) public void cosmosAsyncScripts( boolean useLegacyTracing, diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/GlobalPartitionEndpointManagerForCircuitBreakerTests.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/GlobalPartitionEndpointManagerForCircuitBreakerTests.java index 51f7b9fb1915..d3b4d9b8134d 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/GlobalPartitionEndpointManagerForCircuitBreakerTests.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/GlobalPartitionEndpointManagerForCircuitBreakerTests.java @@ -16,7 +16,7 @@ import com.azure.cosmos.implementation.circuitBreaker.LocationSpecificHealthContext; import com.azure.cosmos.implementation.circuitBreaker.PartitionKeyRangeWrapper; import com.azure.cosmos.implementation.guava25.collect.ImmutableList; -import com.azure.cosmos.implementation.routing.LocationCache; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; import org.apache.commons.lang3.tuple.Pair; import org.mockito.Mockito; import org.slf4j.Logger; @@ -142,11 +142,11 @@ public void recordHealthyStatus(String partitionLevelCircuitBreakerConfigAsJsonS Object partitionAndLocationSpecificUnavailabilityInfo = partitionKeyRangeToLocationSpecificUnavailabilityInfo.get(new PartitionKeyRangeWrapper(request.requestContext.resolvedPartitionKeyRange, collectionResourceId)); - ConcurrentHashMap locationEndpointToLocationSpecificContextForPartition - = (ConcurrentHashMap) locationEndpointToLocationSpecificContextForPartitionField.get(partitionAndLocationSpecificUnavailabilityInfo); + ConcurrentHashMap locationEndpointToLocationSpecificContextForPartition + = (ConcurrentHashMap) locationEndpointToLocationSpecificContextForPartitionField.get(partitionAndLocationSpecificUnavailabilityInfo); LocationSpecificHealthContext locationSpecificHealthContext - = locationEndpointToLocationSpecificContextForPartition.get(new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getKey(), null)); + = locationEndpointToLocationSpecificContextForPartition.get(new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getKey())); assertThat(locationSpecificHealthContext.isRegionAvailableToProcessRequests()).isTrue(); assertThat(locationSpecificHealthContext.isExceptionThresholdBreached()).isFalse(); @@ -167,12 +167,12 @@ public void recordHealthyToHealthyWithFailuresStatusTransition(String partitionL String maxExclusive = "BB"; String collectionResourceId = "dbs/db1/colls/coll1"; - List applicableReadWriteEndpoints = ImmutableList.of( + List applicableReadWriteEndpoints = ImmutableList.of( LocationEastUs2EndpointToLocationPair, LocationEastUsEndpointToLocationPair, LocationCentralUsEndpointToLocationPair) .stream() - .map(uriStringPair -> new LocationCache.ConsolidatedRegionalEndpoint(uriStringPair.getLeft(), null)) + .map(uriStringPair -> new RegionalRoutingContext(uriStringPair.getLeft())) .collect(Collectors.toList()); RxDocumentServiceRequest request = constructRxDocumentServiceRequestInstance( @@ -185,11 +185,11 @@ public void recordHealthyToHealthyWithFailuresStatusTransition(String partitionL maxExclusive, LocationEastUs2EndpointToLocationPair.getKey()); - Mockito.when(this.globalEndpointManagerMock.getReadEndpoints()).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); - Mockito.when(this.globalEndpointManagerMock.getWriteEndpoints()).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); + Mockito.when(this.globalEndpointManagerMock.getReadEndpoints()).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); + Mockito.when(this.globalEndpointManagerMock.getWriteEndpoints()).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); globalPartitionEndpointManagerForCircuitBreaker - .handleLocationExceptionForPartitionKeyRange(request, new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getKey(), null)); + .handleLocationExceptionForPartitionKeyRange(request, new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getKey())); Class[] enclosedClasses = GlobalPartitionEndpointManagerForCircuitBreaker.class.getDeclaredClasses(); Class partitionLevelUnavailabilityInfoClass @@ -210,11 +210,11 @@ public void recordHealthyToHealthyWithFailuresStatusTransition(String partitionL Object partitionAndLocationSpecificUnavailabilityInfo = partitionKeyRangeToLocationSpecificUnavailabilityInfo.get(new PartitionKeyRangeWrapper(request.requestContext.resolvedPartitionKeyRange, collectionResourceId)); - ConcurrentHashMap locationEndpointToLocationSpecificContextForPartition - = (ConcurrentHashMap) locationEndpointToLocationSpecificContextForPartitionField.get(partitionAndLocationSpecificUnavailabilityInfo); + ConcurrentHashMap locationEndpointToLocationSpecificContextForPartition + = (ConcurrentHashMap) locationEndpointToLocationSpecificContextForPartitionField.get(partitionAndLocationSpecificUnavailabilityInfo); LocationSpecificHealthContext locationSpecificHealthContext - = locationEndpointToLocationSpecificContextForPartition.get(new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getKey(), null)); + = locationEndpointToLocationSpecificContextForPartition.get(new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getKey())); assertThat(locationSpecificHealthContext.isRegionAvailableToProcessRequests()).isTrue(); assertThat(locationSpecificHealthContext.isExceptionThresholdBreached()).isFalse(); @@ -235,12 +235,12 @@ public void recordHealthyWithFailuresToUnavailableStatusTransition(String partit String maxExclusive = "BB"; String collectionResourceId = "dbs/db1/colls/coll1"; - List applicableReadWriteEndpoints = ImmutableList.of( + List applicableReadWriteEndpoints = ImmutableList.of( LocationEastUs2EndpointToLocationPair, LocationEastUsEndpointToLocationPair, LocationCentralUsEndpointToLocationPair) .stream() - .map(uriStringPair -> new LocationCache.ConsolidatedRegionalEndpoint(uriStringPair.getLeft(), null)) + .map(uriStringPair -> new RegionalRoutingContext(uriStringPair.getLeft())) .collect(Collectors.toList()); RxDocumentServiceRequest request = constructRxDocumentServiceRequestInstance( @@ -253,15 +253,15 @@ public void recordHealthyWithFailuresToUnavailableStatusTransition(String partit maxExclusive, LocationEastUs2EndpointToLocationPair.getKey()); - Mockito.when(this.globalEndpointManagerMock.getApplicableWriteEndpoints(Mockito.anyList())).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); - Mockito.when(this.globalEndpointManagerMock.getApplicableReadEndpoints(Mockito.anyList())).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); + Mockito.when(this.globalEndpointManagerMock.getApplicableWriteEndpoints(Mockito.anyList())).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); + Mockito.when(this.globalEndpointManagerMock.getApplicableReadEndpoints(Mockito.anyList())).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); int exceptionCountToHandle = globalPartitionEndpointManagerForCircuitBreaker.getConsecutiveExceptionBasedCircuitBreaker().getAllowedExceptionCountToMaintainStatus(LocationHealthStatus.HealthyWithFailures, readOperationTrue); for (int i = 1; i <= exceptionCountToHandle; i++) { globalPartitionEndpointManagerForCircuitBreaker - .handleLocationExceptionForPartitionKeyRange(request, new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getKey(), null)); + .handleLocationExceptionForPartitionKeyRange(request, new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getKey())); } Class[] enclosedClasses = GlobalPartitionEndpointManagerForCircuitBreaker.class.getDeclaredClasses(); @@ -283,11 +283,11 @@ public void recordHealthyWithFailuresToUnavailableStatusTransition(String partit Object partitionAndLocationSpecificUnavailabilityInfo = partitionKeyRangeToLocationSpecificUnavailabilityInfo.get(new PartitionKeyRangeWrapper(request.requestContext.resolvedPartitionKeyRange, collectionResourceId)); - ConcurrentHashMap locationEndpointToLocationSpecificContextForPartition - = (ConcurrentHashMap) locationEndpointToLocationSpecificContextForPartitionField.get(partitionAndLocationSpecificUnavailabilityInfo); + ConcurrentHashMap locationEndpointToLocationSpecificContextForPartition + = (ConcurrentHashMap) locationEndpointToLocationSpecificContextForPartitionField.get(partitionAndLocationSpecificUnavailabilityInfo); LocationSpecificHealthContext locationSpecificHealthContext - = locationEndpointToLocationSpecificContextForPartition.get(new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getKey(), null)); + = locationEndpointToLocationSpecificContextForPartition.get(new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getKey())); assertThat(locationSpecificHealthContext.isRegionAvailableToProcessRequests()).isFalse(); assertThat(locationSpecificHealthContext.isExceptionThresholdBreached()).isTrue(); @@ -310,12 +310,12 @@ public void recordUnavailableToHealthyTentativeStatusTransition(String partition String maxExclusive = "BB"; String collectionResourceId = "dbs/db1/colls/coll1"; - List applicableReadWriteEndpoints = ImmutableList.of( + List applicableReadWriteEndpoints = ImmutableList.of( LocationEastUs2EndpointToLocationPair, LocationEastUsEndpointToLocationPair, LocationCentralUsEndpointToLocationPair) .stream() - .map(uriStringPair -> new LocationCache.ConsolidatedRegionalEndpoint(uriStringPair.getLeft(), null)) + .map(uriStringPair -> new RegionalRoutingContext(uriStringPair.getLeft())) .collect(Collectors.toList()); RxDocumentServiceRequest request = constructRxDocumentServiceRequestInstance( @@ -328,15 +328,15 @@ public void recordUnavailableToHealthyTentativeStatusTransition(String partition maxExclusive, LocationEastUs2EndpointToLocationPair.getKey()); - Mockito.when(this.globalEndpointManagerMock.getApplicableWriteEndpoints(Mockito.anyList())).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); - Mockito.when(this.globalEndpointManagerMock.getApplicableReadEndpoints(Mockito.anyList())).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); + Mockito.when(this.globalEndpointManagerMock.getApplicableWriteEndpoints(Mockito.anyList())).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); + Mockito.when(this.globalEndpointManagerMock.getApplicableReadEndpoints(Mockito.anyList())).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); int exceptionCountToHandle = globalPartitionEndpointManagerForCircuitBreaker.getConsecutiveExceptionBasedCircuitBreaker().getAllowedExceptionCountToMaintainStatus(LocationHealthStatus.HealthyWithFailures, readOperationTrue); for (int i = 1; i <= exceptionCountToHandle; i++) { globalPartitionEndpointManagerForCircuitBreaker - .handleLocationExceptionForPartitionKeyRange(request, new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getKey(), null)); + .handleLocationExceptionForPartitionKeyRange(request, new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getKey())); } Class[] enclosedClasses = GlobalPartitionEndpointManagerForCircuitBreaker.class.getDeclaredClasses(); @@ -358,11 +358,11 @@ public void recordUnavailableToHealthyTentativeStatusTransition(String partition Object partitionAndLocationSpecificUnavailabilityInfo = partitionKeyRangeToLocationSpecificUnavailabilityInfo.get(new PartitionKeyRangeWrapper(request.requestContext.resolvedPartitionKeyRange, collectionResourceId)); - ConcurrentHashMap locationEndpointToLocationSpecificContextForPartition - = (ConcurrentHashMap) locationEndpointToLocationSpecificContextForPartitionField.get(partitionAndLocationSpecificUnavailabilityInfo); + ConcurrentHashMap locationEndpointToLocationSpecificContextForPartition + = (ConcurrentHashMap) locationEndpointToLocationSpecificContextForPartitionField.get(partitionAndLocationSpecificUnavailabilityInfo); LocationSpecificHealthContext locationSpecificHealthContext - = locationEndpointToLocationSpecificContextForPartition.get(new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getKey(), null)); + = locationEndpointToLocationSpecificContextForPartition.get(new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getKey())); assertThat(locationSpecificHealthContext.isRegionAvailableToProcessRequests()).isFalse(); assertThat(locationSpecificHealthContext.isExceptionThresholdBreached()).isTrue(); @@ -373,7 +373,7 @@ public void recordUnavailableToHealthyTentativeStatusTransition(String partition throw new RuntimeException(ex); } - locationSpecificHealthContext = locationEndpointToLocationSpecificContextForPartition.get(new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getKey(), null)); + locationSpecificHealthContext = locationEndpointToLocationSpecificContextForPartition.get(new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getKey())); assertThat(locationSpecificHealthContext.isRegionAvailableToProcessRequests()).isTrue(); assertThat(locationSpecificHealthContext.isExceptionThresholdBreached()).isFalse(); @@ -396,12 +396,12 @@ public void recordHealthyTentativeToHealthyStatusTransition(String partitionLeve String maxExclusive = "BB"; String collectionResourceId = "dbs/db1/colls/coll1"; - List applicableReadWriteEndpoints = ImmutableList.of( + List applicableReadWriteEndpoints = ImmutableList.of( LocationEastUs2EndpointToLocationPair, LocationEastUsEndpointToLocationPair, LocationCentralUsEndpointToLocationPair) .stream() - .map(uriStringPair -> new LocationCache.ConsolidatedRegionalEndpoint(uriStringPair.getLeft(), null)) + .map(uriStringPair -> new RegionalRoutingContext(uriStringPair.getLeft())) .collect(Collectors.toList()); RxDocumentServiceRequest request = constructRxDocumentServiceRequestInstance( @@ -414,15 +414,15 @@ public void recordHealthyTentativeToHealthyStatusTransition(String partitionLeve maxExclusive, LocationEastUs2EndpointToLocationPair.getKey()); - Mockito.when(this.globalEndpointManagerMock.getApplicableWriteEndpoints(Mockito.anyList())).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); - Mockito.when(this.globalEndpointManagerMock.getApplicableReadEndpoints(Mockito.anyList())).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); + Mockito.when(this.globalEndpointManagerMock.getApplicableWriteEndpoints(Mockito.anyList())).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); + Mockito.when(this.globalEndpointManagerMock.getApplicableReadEndpoints(Mockito.anyList())).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); int exceptionCountToHandle = globalPartitionEndpointManagerForCircuitBreaker.getConsecutiveExceptionBasedCircuitBreaker().getAllowedExceptionCountToMaintainStatus(LocationHealthStatus.HealthyWithFailures, readOperationTrue); for (int i = 1; i <= exceptionCountToHandle; i++) { globalPartitionEndpointManagerForCircuitBreaker - .handleLocationExceptionForPartitionKeyRange(request, new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getKey(), null)); + .handleLocationExceptionForPartitionKeyRange(request, new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getKey())); } Class[] enclosedClasses = GlobalPartitionEndpointManagerForCircuitBreaker.class.getDeclaredClasses(); @@ -444,11 +444,11 @@ public void recordHealthyTentativeToHealthyStatusTransition(String partitionLeve Object partitionAndLocationSpecificUnavailabilityInfo = partitionKeyRangeToLocationSpecificUnavailabilityInfo.get(new PartitionKeyRangeWrapper(request.requestContext.resolvedPartitionKeyRange, collectionResourceId)); - ConcurrentHashMap locationEndpointToLocationSpecificContextForPartition - = (ConcurrentHashMap) locationEndpointToLocationSpecificContextForPartitionField.get(partitionAndLocationSpecificUnavailabilityInfo); + ConcurrentHashMap locationEndpointToLocationSpecificContextForPartition + = (ConcurrentHashMap) locationEndpointToLocationSpecificContextForPartitionField.get(partitionAndLocationSpecificUnavailabilityInfo); LocationSpecificHealthContext locationSpecificHealthContext - = locationEndpointToLocationSpecificContextForPartition.get(new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getKey(), null)); + = locationEndpointToLocationSpecificContextForPartition.get(new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getKey())); assertThat(locationSpecificHealthContext.isRegionAvailableToProcessRequests()).isFalse(); assertThat(locationSpecificHealthContext.isExceptionThresholdBreached()).isTrue(); @@ -459,7 +459,7 @@ public void recordHealthyTentativeToHealthyStatusTransition(String partitionLeve throw new RuntimeException(ex); } - locationSpecificHealthContext = locationEndpointToLocationSpecificContextForPartition.get(new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getKey(), null)); + locationSpecificHealthContext = locationEndpointToLocationSpecificContextForPartition.get(new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getKey())); int successCountToUpgradeStatus = globalPartitionEndpointManagerForCircuitBreaker.getConsecutiveExceptionBasedCircuitBreaker().getMinimumSuccessCountForStatusUpgrade(LocationHealthStatus.HealthyTentative, readOperationTrue); @@ -489,12 +489,12 @@ public void recordHealthyTentativeToUnavailableTransition(String partitionLevelC String maxExclusive = "BB"; String collectionResourceId = "dbs/db1/colls/coll1"; - List applicableReadWriteEndpoints = ImmutableList.of( + List applicableReadWriteEndpoints = ImmutableList.of( LocationEastUs2EndpointToLocationPair, LocationEastUsEndpointToLocationPair, LocationCentralUsEndpointToLocationPair) .stream() - .map(uriStringPair -> new LocationCache.ConsolidatedRegionalEndpoint(uriStringPair.getLeft(), null)) + .map(uriStringPair -> new RegionalRoutingContext(uriStringPair.getLeft())) .collect(Collectors.toList()); RxDocumentServiceRequest request = constructRxDocumentServiceRequestInstance( @@ -507,15 +507,15 @@ public void recordHealthyTentativeToUnavailableTransition(String partitionLevelC maxExclusive, LocationEastUs2EndpointToLocationPair.getKey()); - Mockito.when(this.globalEndpointManagerMock.getApplicableWriteEndpoints(Mockito.anyList())).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); - Mockito.when(this.globalEndpointManagerMock.getApplicableReadEndpoints(Mockito.anyList())).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); + Mockito.when(this.globalEndpointManagerMock.getApplicableWriteEndpoints(Mockito.anyList())).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); + Mockito.when(this.globalEndpointManagerMock.getApplicableReadEndpoints(Mockito.anyList())).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); int exceptionCountToHandle = globalPartitionEndpointManagerForCircuitBreaker.getConsecutiveExceptionBasedCircuitBreaker().getAllowedExceptionCountToMaintainStatus(LocationHealthStatus.HealthyWithFailures, readOperationTrue); for (int i = 1; i <= exceptionCountToHandle; i++) { globalPartitionEndpointManagerForCircuitBreaker - .handleLocationExceptionForPartitionKeyRange(request, new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getKey(), null)); + .handleLocationExceptionForPartitionKeyRange(request, new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getKey())); } Class[] enclosedClasses = GlobalPartitionEndpointManagerForCircuitBreaker.class.getDeclaredClasses(); @@ -537,11 +537,11 @@ public void recordHealthyTentativeToUnavailableTransition(String partitionLevelC Object partitionAndLocationSpecificUnavailabilityInfo = partitionKeyRangeToLocationSpecificUnavailabilityInfo.get(new PartitionKeyRangeWrapper(request.requestContext.resolvedPartitionKeyRange, collectionResourceId)); - ConcurrentHashMap locationEndpointToLocationSpecificContextForPartition - = (ConcurrentHashMap) locationEndpointToLocationSpecificContextForPartitionField.get(partitionAndLocationSpecificUnavailabilityInfo); + ConcurrentHashMap locationEndpointToLocationSpecificContextForPartition + = (ConcurrentHashMap) locationEndpointToLocationSpecificContextForPartitionField.get(partitionAndLocationSpecificUnavailabilityInfo); LocationSpecificHealthContext locationSpecificHealthContext - = locationEndpointToLocationSpecificContextForPartition.get(new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getKey(), null)); + = locationEndpointToLocationSpecificContextForPartition.get(new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getKey())); assertThat(locationSpecificHealthContext.isRegionAvailableToProcessRequests()).isFalse(); assertThat(locationSpecificHealthContext.isExceptionThresholdBreached()).isTrue(); @@ -556,10 +556,10 @@ public void recordHealthyTentativeToUnavailableTransition(String partitionLevelC for (int i = 1; i <= exceptionCountToHandle; i++) { globalPartitionEndpointManagerForCircuitBreaker - .handleLocationExceptionForPartitionKeyRange(request, new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getKey(), null)); + .handleLocationExceptionForPartitionKeyRange(request, new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getKey())); } - locationSpecificHealthContext = locationEndpointToLocationSpecificContextForPartition.get(new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getKey(), null)); + locationSpecificHealthContext = locationEndpointToLocationSpecificContextForPartition.get(new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getKey())); assertThat(locationSpecificHealthContext.isRegionAvailableToProcessRequests()).isFalse(); assertThat(locationSpecificHealthContext.isExceptionThresholdBreached()).isTrue(); @@ -581,12 +581,12 @@ public void allRegionsUnavailableHandling(String partitionLevelCircuitBreakerCon String maxExclusive = "BB"; String collectionResourceId = "dbs/db1/colls/coll1"; - List applicableReadWriteEndpoints = ImmutableList.of( + List applicableReadWriteEndpoints = ImmutableList.of( LocationEastUs2EndpointToLocationPair, LocationEastUsEndpointToLocationPair, LocationCentralUsEndpointToLocationPair) .stream() - .map(uriStringPair -> new LocationCache.ConsolidatedRegionalEndpoint(uriStringPair.getLeft(), null)) + .map(uriStringPair -> new RegionalRoutingContext(uriStringPair.getLeft())) .collect(Collectors.toList()); RxDocumentServiceRequest request = constructRxDocumentServiceRequestInstance( @@ -599,8 +599,8 @@ public void allRegionsUnavailableHandling(String partitionLevelCircuitBreakerCon maxExclusive, LocationEastUs2EndpointToLocationPair.getKey()); - Mockito.when(this.globalEndpointManagerMock.getApplicableWriteEndpoints(Mockito.anyList())).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); - Mockito.when(this.globalEndpointManagerMock.getApplicableReadEndpoints(Mockito.anyList())).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); + Mockito.when(this.globalEndpointManagerMock.getApplicableWriteEndpoints(Mockito.anyList())).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); + Mockito.when(this.globalEndpointManagerMock.getApplicableReadEndpoints(Mockito.anyList())).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); int exceptionCountToHandle = globalPartitionEndpointManagerForCircuitBreaker @@ -609,11 +609,11 @@ public void allRegionsUnavailableHandling(String partitionLevelCircuitBreakerCon for (int i = 1; i <= exceptionCountToHandle; i++) { globalPartitionEndpointManagerForCircuitBreaker - .handleLocationExceptionForPartitionKeyRange(request, new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getKey(), null)); + .handleLocationExceptionForPartitionKeyRange(request, new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getKey())); globalPartitionEndpointManagerForCircuitBreaker - .handleLocationExceptionForPartitionKeyRange(request, new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUsEndpointToLocationPair.getKey(), null)); + .handleLocationExceptionForPartitionKeyRange(request, new RegionalRoutingContext(LocationEastUsEndpointToLocationPair.getKey())); globalPartitionEndpointManagerForCircuitBreaker - .handleLocationExceptionForPartitionKeyRange(request, new LocationCache.ConsolidatedRegionalEndpoint(LocationCentralUsEndpointToLocationPair.getKey(), null)); + .handleLocationExceptionForPartitionKeyRange(request, new RegionalRoutingContext(LocationCentralUsEndpointToLocationPair.getKey())); } Class[] enclosedClasses = GlobalPartitionEndpointManagerForCircuitBreaker.class.getDeclaredClasses(); @@ -653,12 +653,12 @@ public void multiContainerBothWithSinglePartitionHealthyToUnavailableHandling(St String collectionResourceId1 = "dbs/db1/colls/coll1"; String collectionResourceId2 = "dbs/db1/colls/coll2"; - List applicableReadWriteEndpoints = ImmutableList.of( + List applicableReadWriteEndpoints = ImmutableList.of( LocationEastUs2EndpointToLocationPair, LocationEastUsEndpointToLocationPair, LocationCentralUsEndpointToLocationPair) .stream() - .map(uriStringPair -> new LocationCache.ConsolidatedRegionalEndpoint(uriStringPair.getLeft(), null)) + .map(uriStringPair -> new RegionalRoutingContext(uriStringPair.getLeft())) .collect(Collectors.toList()); RxDocumentServiceRequest request1 = constructRxDocumentServiceRequestInstance( @@ -681,15 +681,15 @@ public void multiContainerBothWithSinglePartitionHealthyToUnavailableHandling(St maxExclusive, LocationEastUs2EndpointToLocationPair.getKey()); - Mockito.when(this.globalEndpointManagerMock.getApplicableWriteEndpoints(Mockito.anyList())).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); - Mockito.when(this.globalEndpointManagerMock.getApplicableReadEndpoints(Mockito.anyList())).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); + Mockito.when(this.globalEndpointManagerMock.getApplicableWriteEndpoints(Mockito.anyList())).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); + Mockito.when(this.globalEndpointManagerMock.getApplicableReadEndpoints(Mockito.anyList())).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); int exceptionCountToHandle = globalPartitionEndpointManagerForCircuitBreaker.getConsecutiveExceptionBasedCircuitBreaker().getAllowedExceptionCountToMaintainStatus(LocationHealthStatus.HealthyWithFailures, readOperationTrue); for (int i = 1; i <= exceptionCountToHandle; i++) { globalPartitionEndpointManagerForCircuitBreaker - .handleLocationExceptionForPartitionKeyRange(request1, new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getKey(), null)); + .handleLocationExceptionForPartitionKeyRange(request1, new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getKey())); } globalPartitionEndpointManagerForCircuitBreaker.handleLocationSuccessForPartitionKeyRange(request2); @@ -714,21 +714,21 @@ public void multiContainerBothWithSinglePartitionHealthyToUnavailableHandling(St = partitionKeyRangeToLocationSpecificUnavailabilityInfo.get(new PartitionKeyRangeWrapper( new PartitionKeyRange(pkRangeId, minInclusive, maxExclusive), collectionResourceId1)); - ConcurrentHashMap locationEndpointToLocationSpecificContextForPartitionForColl1 - = (ConcurrentHashMap) locationEndpointToLocationSpecificContextForPartitionField.get(partitionLevelLocationUnavailabilityInfoSnapshotForColl1); + ConcurrentHashMap locationEndpointToLocationSpecificContextForPartitionForColl1 + = (ConcurrentHashMap) locationEndpointToLocationSpecificContextForPartitionField.get(partitionLevelLocationUnavailabilityInfoSnapshotForColl1); Object partitionLevelLocationUnavailabilityInfoSnapshotForColl2 = partitionKeyRangeToLocationSpecificUnavailabilityInfo.get(new PartitionKeyRangeWrapper( new PartitionKeyRange(pkRangeId, minInclusive, maxExclusive), collectionResourceId2)); - ConcurrentHashMap locationEndpointToLocationSpecificContextForPartitionForColl2 - = (ConcurrentHashMap) locationEndpointToLocationSpecificContextForPartitionField.get(partitionLevelLocationUnavailabilityInfoSnapshotForColl2); + ConcurrentHashMap locationEndpointToLocationSpecificContextForPartitionForColl2 + = (ConcurrentHashMap) locationEndpointToLocationSpecificContextForPartitionField.get(partitionLevelLocationUnavailabilityInfoSnapshotForColl2); LocationSpecificHealthContext locationSpecificHealthContext1 - = locationEndpointToLocationSpecificContextForPartitionForColl1.get(new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getKey(), null)); + = locationEndpointToLocationSpecificContextForPartitionForColl1.get(new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getKey())); LocationSpecificHealthContext locationSpecificHealthContext2 - = locationEndpointToLocationSpecificContextForPartitionForColl2.get(new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getKey(), null)); + = locationEndpointToLocationSpecificContextForPartitionForColl2.get(new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getKey())); assertThat(locationSpecificHealthContext1.isRegionAvailableToProcessRequests()).isFalse(); assertThat(locationSpecificHealthContext1.isExceptionThresholdBreached()).isTrue(); @@ -766,16 +766,16 @@ public void allRegionsUnavailableHandlingWithMultiThreading(String partitionLeve String collectionResourceId = "dbs/db1/colls/coll1"; PartitionKeyRange partitionKeyRange = new PartitionKeyRange(pkRangeId, minInclusive, maxExclusive); - List applicableReadWriteEndpoints = ImmutableList.of( + List applicableReadWriteEndpoints = ImmutableList.of( LocationEastUs2EndpointToLocationPair, LocationEastUsEndpointToLocationPair, LocationCentralUsEndpointToLocationPair) .stream() - .map(uriStringPair -> new LocationCache.ConsolidatedRegionalEndpoint(uriStringPair.getLeft(), null)) + .map(uriStringPair -> new RegionalRoutingContext(uriStringPair.getLeft())) .collect(Collectors.toList()); - Mockito.when(this.globalEndpointManagerMock.getApplicableWriteEndpoints(Mockito.anyList())).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); - Mockito.when(this.globalEndpointManagerMock.getApplicableReadEndpoints(Mockito.anyList())).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); + Mockito.when(this.globalEndpointManagerMock.getApplicableWriteEndpoints(Mockito.anyList())).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); + Mockito.when(this.globalEndpointManagerMock.getApplicableReadEndpoints(Mockito.anyList())).thenReturn((UnmodifiableList) UnmodifiableList.unmodifiableList(applicableReadWriteEndpoints)); RxDocumentServiceRequest requestCentralUs = constructRxDocumentServiceRequestInstance( readOperationTrue ? OperationType.Read : OperationType.Create, @@ -883,10 +883,10 @@ private static void validateAllRegionsAreNotUnavailableAfterExceptionInLocation( URI locationWithFailure, String collectionResourceId, PartitionKeyRange partitionKeyRange, - List applicableReadWriteLocations) { + List applicableReadWriteLocations) { logger.warn("Handling exception for {}", locationWithFailure.getPath()); - globalPartitionEndpointManagerForCircuitBreaker.handleLocationExceptionForPartitionKeyRange(request, new LocationCache.ConsolidatedRegionalEndpoint(locationWithFailure, null)); + globalPartitionEndpointManagerForCircuitBreaker.handleLocationExceptionForPartitionKeyRange(request, new RegionalRoutingContext(locationWithFailure)); List unavailableRegions = globalPartitionEndpointManagerForCircuitBreaker.getUnavailableRegionsForPartitionKeyRange(collectionResourceId, partitionKeyRange, request.getOperationType()); @@ -914,8 +914,8 @@ private RxDocumentServiceRequest constructRxDocumentServiceRequestInstance( request.requestContext.resolvedPartitionKeyRange = new PartitionKeyRange(partitionKeyRangeId, minInclusive, maxExclusive); request.requestContext.resolvedPartitionKeyRangeForCircuitBreaker = request.requestContext.resolvedPartitionKeyRange; - request.requestContext.locationEndpointToRoute = locationEndpointToRoute; - request.requestContext.consolidatedRegionalEndpointToRoute = new LocationCache.ConsolidatedRegionalEndpoint(locationEndpointToRoute, null); + + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointToRoute); request.requestContext.setExcludeRegions(Collections.emptyList()); request.requestContext.setPointOperationContext( diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/MultipleCosmosClientsWithTransportClientSharingTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/MultipleCosmosClientsWithTransportClientSharingTest.java index b55538a0ff47..34592482b40b 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/MultipleCosmosClientsWithTransportClientSharingTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/MultipleCosmosClientsWithTransportClientSharingTest.java @@ -126,7 +126,7 @@ public void replaceItem() throws Exception{ validateItemResponse(properties, itemResponse); String newPropValue = UUID.randomUUID().toString(); - properties.set("newProp", newPropValue, CosmosItemSerializer.DEFAULT_SERIALIZER); + properties.set("newProp", newPropValue); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); ModelBridgeInternal.setPartitionKey(options, new PartitionKey(properties.get("mypk"))); // replace document diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/OperationPoliciesTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/OperationPoliciesTest.java index 01a8b5ae8e1e..10787e470b86 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/OperationPoliciesTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/OperationPoliciesTest.java @@ -321,7 +321,7 @@ public void upsertItem(String[] changedOptions) throws Throwable { String newPropLabel = "newProp"; String newPropValue = UUID.randomUUID().toString(); - item.set(newPropLabel, newPropValue, CosmosItemSerializer.DEFAULT_SERIALIZER); + item.set(newPropLabel, newPropValue); upsertResponse = container.upsertItem(item, new CosmosItemRequestOptions()).block(); assertThat(upsertResponse.getRequestCharge()).isGreaterThan(0); @@ -376,7 +376,7 @@ public void replaceItem(String[] changedOptions) throws Exception { validateItemResponse(item, itemResponse); String newPropLabel = "newProp"; String newPropValue = UUID.randomUUID().toString(); - item.set(newPropLabel, newPropValue, CosmosItemSerializer.DEFAULT_SERIALIZER); + item.set(newPropLabel, newPropValue); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); PartitionKey pk = new PartitionKey(item.get("mypk")); ModelBridgeInternal.setPartitionKey(options, pk); @@ -390,7 +390,7 @@ public void replaceItem(String[] changedOptions) throws Exception { changeProperties(changedOptions); newPropValue = UUID.randomUUID().toString(); - item.set(newPropLabel, newPropValue, CosmosItemSerializer.DEFAULT_SERIALIZER); + item.set(newPropLabel, newPropValue); // replace document replace = container.replaceItem(item, item.getId(), @@ -477,7 +477,7 @@ public void bulk(String[] changedOptions) { public void batch(String[] changedOptions) { InternalObjectNode item = getDocumentDefinition(UUID.randomUUID().toString()); InternalObjectNode item2 = getDocumentDefinition(UUID.randomUUID().toString()); - item2.set("mypk", item.get("mypk"), CosmosItemSerializer.DEFAULT_SERIALIZER); + item2.set("mypk", item.get("mypk")); CosmosBatch batch = CosmosBatch.createCosmosBatch(new PartitionKey(item.get("mypk"))); batch.createItemOperation(item); batch.createItemOperation(item2); @@ -497,7 +497,7 @@ public void batch(String[] changedOptions) { item = getDocumentDefinition(UUID.randomUUID().toString()); item2 = getDocumentDefinition(UUID.randomUUID().toString()); - item2.set("mypk", item.get("mypk"), CosmosItemSerializer.DEFAULT_SERIALIZER); + item2.set("mypk", item.get("mypk")); batch = CosmosBatch.createCosmosBatch(new PartitionKey(item.get("mypk"))); batch.createItemOperation(item); batch.createItemOperation(item2); diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/PartitionLevelCircuitBreakerTests.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/PartitionLevelCircuitBreakerTests.java index c1c5e50d832c..3d6963ad3cf0 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/PartitionLevelCircuitBreakerTests.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/PartitionLevelCircuitBreakerTests.java @@ -26,7 +26,7 @@ import com.azure.cosmos.implementation.feedranges.FeedRangeEpkImpl; import com.azure.cosmos.implementation.feedranges.FeedRangePartitionKeyImpl; import com.azure.cosmos.implementation.guava25.base.Function; -import com.azure.cosmos.implementation.routing.LocationCache; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; import com.azure.cosmos.models.CosmosBatch; import com.azure.cosmos.models.CosmosBatchResponse; import com.azure.cosmos.models.CosmosChangeFeedRequestOptions; @@ -5144,8 +5144,8 @@ private static double getEstimatedFailureCountSeenPerRegionPerPartitionKeyRange( return 0d; } - ConcurrentHashMap locationEndpointToLocationSpecificContextForPartition - = (ConcurrentHashMap) locationEndpointToLocationSpecificContextForPartitionField.get(partitionAndLocationSpecificUnavailabilityInfo); + ConcurrentHashMap locationEndpointToLocationSpecificContextForPartition + = (ConcurrentHashMap) locationEndpointToLocationSpecificContextForPartitionField.get(partitionAndLocationSpecificUnavailabilityInfo); int count = 0; boolean failuresExist = false; diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/ProactiveConnectionManagementTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/ProactiveConnectionManagementTest.java index 75ec2b6d4013..fbfeff9897eb 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/ProactiveConnectionManagementTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/ProactiveConnectionManagementTest.java @@ -27,9 +27,9 @@ import com.azure.cosmos.implementation.directconnectivity.RntbdTransportClient; import com.azure.cosmos.implementation.directconnectivity.rntbd.RntbdEndpoint; import com.azure.cosmos.implementation.routing.CollectionRoutingMap; -import com.azure.cosmos.implementation.routing.LocationCache; import com.azure.cosmos.implementation.routing.PartitionKeyInternalHelper; import com.azure.cosmos.implementation.routing.PartitionKeyRangeIdentity; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; import com.azure.cosmos.models.CosmosContainerIdentity; import com.azure.cosmos.rx.TestSuiteBase; import org.testng.annotations.BeforeClass; @@ -181,13 +181,13 @@ public void openConnectionsAndInitCachesWithContainer(ProactiveConnectionManagem cosmosAsyncContainer.openConnectionsAndInitCaches(proactiveConnectionRegionCount).block(); - UnmodifiableList readEndpoints = + UnmodifiableList readEndpoints = globalEndpointManager.getReadEndpoints(); List proactiveConnectionEndpoints = readEndpoints.subList( 0, Math.min(readEndpoints.size(),proactiveContainerInitConfig.getProactiveConnectionRegionsCount())) - .stream().map(LocationCache.ConsolidatedRegionalEndpoint::getGatewayLocationEndpoint).collect(Collectors.toList()); + .stream().map(RegionalRoutingContext::getGatewayRegionalEndpoint).collect(Collectors.toList()); Mono asyncContainerMono = Mono.just(cosmosAsyncContainer); @@ -345,13 +345,13 @@ public void openConnectionsAndInitCachesWithCosmosClient_And_PerContainerConnect ConcurrentHashMap routingMap = getRoutingMap(rxDocumentClient); ConcurrentHashMap collectionInfoByNameMap = getCollectionInfoByNameMap(rxDocumentClient); Set endpoints = ConcurrentHashMap.newKeySet(); - UnmodifiableList readEndpoints = globalEndpointManager.getReadEndpoints(); + UnmodifiableList readEndpoints = globalEndpointManager.getReadEndpoints(); List proactiveConnectionEndpoints = readEndpoints.subList( 0, Math.min(readEndpoints.size(), proactiveContainerInitConfig.getProactiveConnectionRegionsCount())) .stream() - .map(LocationCache.ConsolidatedRegionalEndpoint::getGatewayLocationEndpoint) + .map(RegionalRoutingContext::getGatewayRegionalEndpoint) .collect(Collectors.toList()); Flux asyncContainerFlux = Flux.fromIterable(asyncContainers); @@ -495,12 +495,12 @@ public void openConnectionsAndInitCachesWithCosmosClient_And_PerContainerConnect ConcurrentHashMap routingMap = getRoutingMap(rxDocumentClient); ConcurrentHashMap collectionInfoByNameMap = getCollectionInfoByNameMap(rxDocumentClient); Set endpoints = ConcurrentHashMap.newKeySet(); - UnmodifiableList readEndpoints = globalEndpointManager.getReadEndpoints(); + UnmodifiableList readEndpoints = globalEndpointManager.getReadEndpoints(); List proactiveConnectionEndpoints = readEndpoints.subList( 0, Math.min(readEndpoints.size(), proactiveContainerInitConfig.getProactiveConnectionRegionsCount())) .stream() - .map(LocationCache.ConsolidatedRegionalEndpoint::getGatewayLocationEndpoint) + .map(RegionalRoutingContext::getGatewayRegionalEndpoint) .collect(Collectors.toList());; Flux asyncContainerFlux = Flux.fromIterable(asyncContainers); @@ -666,12 +666,12 @@ public void openConnectionsAndInitCachesWithCosmosClient_And_PerContainerConnect ConcurrentHashMap routingMap = getRoutingMap(rxDocumentClient); ConcurrentHashMap collectionInfoByNameMap = getCollectionInfoByNameMap(rxDocumentClient); Set endpoints = ConcurrentHashMap.newKeySet(); - UnmodifiableList readEndpoints = globalEndpointManager.getReadEndpoints(); + UnmodifiableList readEndpoints = globalEndpointManager.getReadEndpoints(); List proactiveConnectionEndpoints = readEndpoints.subList( 0, Math.min(readEndpoints.size(), proactiveContainerInitConfig.getProactiveConnectionRegionsCount())) .stream() - .map(LocationCache.ConsolidatedRegionalEndpoint::getGatewayLocationEndpoint) + .map(RegionalRoutingContext::getGatewayRegionalEndpoint) .collect(Collectors.toList());; Flux asyncContainerFlux = Flux.fromIterable(asyncContainers); diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/faultinjection/FaultInjectionMetadataRequestRuleTests.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/faultinjection/FaultInjectionMetadataRequestRuleTests.java index 6b362339429f..38ed45b785bd 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/faultinjection/FaultInjectionMetadataRequestRuleTests.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/faultinjection/FaultInjectionMetadataRequestRuleTests.java @@ -19,6 +19,7 @@ import com.azure.cosmos.implementation.OperationType; import com.azure.cosmos.implementation.Utils; import com.azure.cosmos.implementation.throughputControl.TestItem; +import com.azure.cosmos.models.CosmosItemResponse; import com.azure.cosmos.models.CosmosQueryRequestOptions; import com.azure.cosmos.models.FeedRange; import com.azure.cosmos.models.PartitionKey; @@ -208,9 +209,9 @@ public void faultInjectionServerErrorRuleTests_AddressRefresh_ConnectionDelay(bo // when preferred regions is 2 // Due to issue https://github.com/Azure/azure-sdk-for-java/issues/35779, the request mark the region unavailable will retry // in the unavailable region again, hence the addressRefresh fault injection will be happened 4 times - validateFaultInjectionRuleAppliedForAddressResolution(cosmosDiagnostics, addressRefreshConnectionDelay, 4); + validateFaultInjectionRuleAppliedForAddressResolution(cosmosDiagnostics, addressRefreshConnectionDelay, 4, false); } else { - validateFaultInjectionRuleAppliedForAddressResolution(cosmosDiagnostics, addressRefreshConnectionDelay, 3); + validateFaultInjectionRuleAppliedForAddressResolution(cosmosDiagnostics, addressRefreshConnectionDelay, 3, false); } } catch (CosmosException e) { fail("Request should be able to succeed by retrying in another region. " + e.getDiagnostics()); @@ -305,18 +306,34 @@ public void faultInjectionServerErrorRuleTests_AddressRefresh_ResponseDelay( CosmosDiagnostics cosmosDiagnostics = this.performDocumentOperation(container, operationType, createdItem); - assertThat(cosmosDiagnostics.getContactedRegionNames().size()).isEqualTo(1); - assertThat( - cosmosDiagnostics - .getContactedRegionNames() - .containsAll(Arrays.asList(this.readPreferredLocations.get(0).toLowerCase()))) - .isTrue(); - assertThat(cosmosDiagnostics.getDiagnosticsContext().getStatusCode()) - .isEqualTo(HttpConstants.StatusCodes.REQUEST_TIMEOUT); - assertThat(cosmosDiagnostics.getDiagnosticsContext().getSubStatusCode()) - .isEqualTo(HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); - validateFaultInjectionRuleAppliedForAddressResolution(cosmosDiagnostics, addressRefreshResponseDelay, 3); + if (isNonWriteDocumentOperation(operationType)) { + assertThat(cosmosDiagnostics.getContactedRegionNames().size()).isEqualTo(2); + assertThat( + cosmosDiagnostics + .getContactedRegionNames() + .containsAll(Arrays.asList(this.readPreferredLocations.get(0).toLowerCase(), this.readPreferredLocations.get(0).toLowerCase()))) + .isTrue(); + + assertThat(cosmosDiagnostics.getDiagnosticsContext().getStatusCode()) + .isNotEqualTo(HttpConstants.StatusCodes.REQUEST_TIMEOUT); + assertThat(cosmosDiagnostics.getDiagnosticsContext().getSubStatusCode()) + .isNotEqualTo(HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); + } else { + assertThat(cosmosDiagnostics.getContactedRegionNames().size()).isEqualTo(1); + assertThat( + cosmosDiagnostics + .getContactedRegionNames() + .containsAll(Arrays.asList(this.readPreferredLocations.get(0).toLowerCase()))) + .isTrue(); + + assertThat(cosmosDiagnostics.getDiagnosticsContext().getStatusCode()) + .isEqualTo(HttpConstants.StatusCodes.REQUEST_TIMEOUT); + assertThat(cosmosDiagnostics.getDiagnosticsContext().getSubStatusCode()) + .isEqualTo(HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); + } + + validateFaultInjectionRuleAppliedForAddressResolution(cosmosDiagnostics, addressRefreshResponseDelay, 3, operationType == OperationType.Query); } finally { addressRefreshResponseDelayRule.disable(); dataOperationGoneRule.disable(); @@ -404,17 +421,25 @@ public void faultInjectionServerErrorRuleTests_AddressRefresh_byPartition(boolea Arrays.asList(addressRefreshResponseDelayRule, dataOperationGoneRule)) .block(); - // validate for request on feed range 0, it will fail + // validate for request on feed range 0, address refresh request failures will happen but request will succeed in second region as request is Document read try { - CosmosDiagnostics cosmosDiagnostics = + CosmosItemResponse itemResponse = container .readItem(itemOnFeedRange1.getId(), new PartitionKey(itemOnFeedRange1.getId()), JsonNode.class) - .block() - .getDiagnostics(); + .block(); - fail("Item on feed range 1 should have failed. " + cosmosDiagnostics); + assertThat(itemResponse).isNotNull(); + + CosmosDiagnostics cosmosDiagnostics = itemResponse.getDiagnostics(); + + assertThat(addressRefreshResponseDelayRule.getHitCount()).isGreaterThan(0); + + assertThat(cosmosDiagnostics).isNotNull(); + assertThat(cosmosDiagnostics.getDiagnosticsContext()).isNotNull(); + assertThat(cosmosDiagnostics.getDiagnosticsContext().getContactedRegionNames()).isNotNull(); + assertThat(cosmosDiagnostics.getDiagnosticsContext().getContactedRegionNames().size()).isEqualTo(2); } catch (CosmosException e) { - // no-op + fail("Item on feed range 1 should have succeeded. " + e.getDiagnostics()); } try { @@ -497,7 +522,7 @@ public void faultInjectionServerErrorRuleTests_AddressRefresh_TooManyRequest(boo assertThat(cosmosDiagnostics.getContactedRegionNames().size()).isEqualTo(1); assertThat(cosmosDiagnostics.getContactedRegionNames().containsAll(Arrays.asList(this.readPreferredLocations.get(0).toLowerCase()))).isTrue(); - validateFaultInjectionRuleAppliedForAddressResolution(cosmosDiagnostics, addressRefreshTooManyRequest, 1); + validateFaultInjectionRuleAppliedForAddressResolution(cosmosDiagnostics, addressRefreshTooManyRequest, 1, false); } finally { addressRefreshTooManyRequestRule.disable(); dataOperationGoneRule.disable(); @@ -719,10 +744,24 @@ public void afterClass() { private void validateFaultInjectionRuleAppliedForAddressResolution( CosmosDiagnostics cosmosDiagnostics, String ruleId, - int failureInjectedExpectedCount) throws JsonProcessingException { + int failureInjectedExpectedCount, + boolean isQueryOperation) throws JsonProcessingException { ObjectNode diagnosticsNode = (ObjectNode) Utils.getSimpleObjectMapper().readTree(cosmosDiagnostics.toString()); - JsonNode addressResolutionStatistics = diagnosticsNode.get("addressResolutionStatistics"); + JsonNode addressResolutionStatistics; + + if (isQueryOperation) { + + ArrayNode arrayNode = (ArrayNode) diagnosticsNode.get("clientSideRequestStatistics"); + + assertThat(arrayNode).isNotNull(); + assertThat(arrayNode.get(0)).isNotNull(); + + addressResolutionStatistics = arrayNode.get(0).get("addressResolutionStatistics"); + } else { + addressResolutionStatistics = diagnosticsNode.get("addressResolutionStatistics"); + } + Iterator> addressResolutionIterator = addressResolutionStatistics.fields(); int failureInjectedCount = 0; while (addressResolutionIterator.hasNext()) { @@ -736,6 +775,12 @@ private void validateFaultInjectionRuleAppliedForAddressResolution( assertThat(failureInjectedCount).isEqualTo(failureInjectedExpectedCount); } + private static boolean isNonWriteDocumentOperation(OperationType operationType) { + return operationType == OperationType.Read || + operationType == OperationType.Query || + operationType == OperationType.ReadFeed; + } + private static AccountLevelLocationContext getAccountLevelLocationContext(DatabaseAccount databaseAccount, boolean writeOnly) { Iterator locationIterator = writeOnly ? databaseAccount.getWritableLocations().iterator() : databaseAccount.getReadableLocations().iterator(); diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/ClientRetryPolicyTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/ClientRetryPolicyTest.java index f8ed32b0a9ee..13f6ca4cd0ca 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/ClientRetryPolicyTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/ClientRetryPolicyTest.java @@ -8,7 +8,7 @@ import com.azure.cosmos.ThrottlingRetryOptions; import com.azure.cosmos.implementation.circuitBreaker.GlobalPartitionEndpointManagerForCircuitBreaker; import com.azure.cosmos.implementation.directconnectivity.ChannelAcquisitionException; -import com.azure.cosmos.implementation.routing.LocationCache; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; import io.netty.handler.timeout.ReadTimeoutException; import io.reactivex.subscribers.TestSubscriber; import org.mockito.Mockito; @@ -35,8 +35,9 @@ public static Object[][] operationProvider() { return new Object[][]{ // OperationType, ResourceType, isAddressRequest, RequestFullPath, ShouldRetryCrossRegion { OperationType.Read, ResourceType.Document, Boolean.FALSE, TEST_DOCUMENT_PATH, Boolean.TRUE }, - { OperationType.Read, ResourceType.Document, Boolean.TRUE, TEST_DOCUMENT_PATH, Boolean.FALSE }, + { OperationType.Read, ResourceType.Document, Boolean.TRUE, TEST_DOCUMENT_PATH, Boolean.TRUE }, { OperationType.Create, ResourceType.Document, Boolean.FALSE, TEST_DOCUMENT_PATH, Boolean.FALSE }, + { OperationType.Create, ResourceType.Document, Boolean.TRUE, TEST_DOCUMENT_PATH, Boolean.FALSE }, { OperationType.Read, ResourceType.Database, Boolean.FALSE, TEST_DATABASE_PATH, Boolean.TRUE }, { OperationType.Create, ResourceType.Database, Boolean.FALSE, TEST_DATABASE_PATH, Boolean.FALSE }, { OperationType.QueryPlan, ResourceType.Document, Boolean.FALSE, TEST_DOCUMENT_PATH, Boolean.TRUE } @@ -66,7 +67,7 @@ public void networkFailureOnRead() throws Exception { ThrottlingRetryOptions throttlingRetryOptions = new ThrottlingRetryOptions(); GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); GlobalPartitionEndpointManagerForCircuitBreaker globalPartitionEndpointManager = Mockito.mock(GlobalPartitionEndpointManagerForCircuitBreaker.class); - Mockito.doReturn(new LocationCache.ConsolidatedRegionalEndpoint(new URI("http://localhost"), null)).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); + Mockito.doReturn(new RegionalRoutingContext(new URI("http://localhost"))).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(false)); ClientRetryPolicy clientRetryPolicy = new ClientRetryPolicy(mockDiagnosticsClientContext(), endpointManager, true, throttlingRetryOptions, null, globalPartitionEndpointManager); @@ -107,7 +108,7 @@ public void shouldRetryOnGatewayTimeout( GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); GlobalPartitionEndpointManagerForCircuitBreaker globalPartitionEndpointManager = Mockito.mock(GlobalPartitionEndpointManagerForCircuitBreaker.class); - Mockito.doReturn(new LocationCache.ConsolidatedRegionalEndpoint(new URI("http://localhost"), null)).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); + Mockito.doReturn(new RegionalRoutingContext(new URI("http://localhost"))).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(true)); ClientRetryPolicy clientRetryPolicy = new ClientRetryPolicy( @@ -150,7 +151,7 @@ public void tcpNetworkFailureOnRead() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); GlobalPartitionEndpointManagerForCircuitBreaker globalPartitionEndpointManager = Mockito.mock(GlobalPartitionEndpointManagerForCircuitBreaker.class); - Mockito.doReturn(new LocationCache.ConsolidatedRegionalEndpoint(new URI("http://localhost"), null)).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); + Mockito.doReturn(new RegionalRoutingContext(new URI("http://localhost"))).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(false)); Mockito.doReturn(2).when(endpointManager).getPreferredLocationCount(); ClientRetryPolicy clientRetryPolicy = new ClientRetryPolicy(mockDiagnosticsClientContext(), endpointManager, true, retryOptions, null, globalPartitionEndpointManager); @@ -198,7 +199,7 @@ public void networkFailureOnWrite() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); GlobalPartitionEndpointManagerForCircuitBreaker globalPartitionEndpointManager = Mockito.mock(GlobalPartitionEndpointManagerForCircuitBreaker.class); - Mockito.doReturn(new LocationCache.ConsolidatedRegionalEndpoint(new URI("http://localhost"), null)).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); + Mockito.doReturn(new RegionalRoutingContext(new URI("http://localhost"))).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(false)); ClientRetryPolicy clientRetryPolicy = new ClientRetryPolicy(mockDiagnosticsClientContext(), endpointManager, true, throttlingRetryOptions, null, globalPartitionEndpointManager); @@ -233,7 +234,7 @@ public void tcpNetworkFailureOnWrite( GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); GlobalPartitionEndpointManagerForCircuitBreaker globalPartitionEndpointManager = Mockito.mock(GlobalPartitionEndpointManagerForCircuitBreaker.class); - Mockito.doReturn(new LocationCache.ConsolidatedRegionalEndpoint(new URI("http://localhost"), null)).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); + Mockito.doReturn(new RegionalRoutingContext(new URI("http://localhost"))).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(false)); Mockito.doReturn(2).when(endpointManager).getPreferredLocationCount(); ClientRetryPolicy clientRetryPolicy = new ClientRetryPolicy(mockDiagnosticsClientContext(), endpointManager, true, retryOptions, null, globalPartitionEndpointManager); @@ -293,7 +294,7 @@ public void networkFailureOnUpsert() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); GlobalPartitionEndpointManagerForCircuitBreaker globalPartitionEndpointManager = Mockito.mock(GlobalPartitionEndpointManagerForCircuitBreaker.class); - Mockito.doReturn(new LocationCache.ConsolidatedRegionalEndpoint(new URI("http://localhost"), null)).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); + Mockito.doReturn(new RegionalRoutingContext(new URI("http://localhost"))).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(false)); ClientRetryPolicy clientRetryPolicy = new ClientRetryPolicy(mockDiagnosticsClientContext(), endpointManager, true, throttlingRetryOptions, null, globalPartitionEndpointManager); @@ -326,7 +327,7 @@ public void tcpNetworkFailureOnUpsert() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); GlobalPartitionEndpointManagerForCircuitBreaker globalPartitionEndpointManager = Mockito.mock(GlobalPartitionEndpointManagerForCircuitBreaker.class); - Mockito.doReturn(new LocationCache.ConsolidatedRegionalEndpoint(new URI("http://localhost"), null)).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); + Mockito.doReturn(new RegionalRoutingContext(new URI("http://localhost"))).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(false)); Mockito.doReturn(2).when(endpointManager).getPreferredLocationCount(); ClientRetryPolicy clientRetryPolicy = new ClientRetryPolicy(mockDiagnosticsClientContext(), endpointManager, true, retryOptions, null, globalPartitionEndpointManager); @@ -362,7 +363,7 @@ public void networkFailureOnDelete() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); GlobalPartitionEndpointManagerForCircuitBreaker globalPartitionEndpointManager = Mockito.mock(GlobalPartitionEndpointManagerForCircuitBreaker.class); - Mockito.doReturn(new LocationCache.ConsolidatedRegionalEndpoint(new URI("http://localhost"), null)).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); + Mockito.doReturn(new RegionalRoutingContext(new URI("http://localhost"))).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(false)); ClientRetryPolicy clientRetryPolicy = new ClientRetryPolicy(mockDiagnosticsClientContext(), endpointManager, true, throttlingRetryOptions, null, globalPartitionEndpointManager); @@ -396,7 +397,7 @@ public void tcpNetworkFailureOnDelete() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); GlobalPartitionEndpointManagerForCircuitBreaker globalPartitionEndpointManager = Mockito.mock(GlobalPartitionEndpointManagerForCircuitBreaker.class); - Mockito.doReturn(new LocationCache.ConsolidatedRegionalEndpoint(new URI("http://localhost"), null)).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); + Mockito.doReturn(new RegionalRoutingContext(new URI("http://localhost"))).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(false)); Mockito.doReturn(2).when(endpointManager).getPreferredLocationCount(); ClientRetryPolicy clientRetryPolicy = new ClientRetryPolicy(mockDiagnosticsClientContext(), endpointManager, true, retryOptions, null, globalPartitionEndpointManager); diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/ConsistencyTests2.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/ConsistencyTests2.java index 7eef45923f19..e13377e64999 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/ConsistencyTests2.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/ConsistencyTests2.java @@ -7,7 +7,6 @@ import com.azure.cosmos.CosmosAsyncClient; import com.azure.cosmos.CosmosClientBuilder; import com.azure.cosmos.CosmosException; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.DirectConnectionConfig; import com.azure.cosmos.GatewayConnectionConfig; import com.azure.cosmos.implementation.clienttelemetry.ClientTelemetry; @@ -288,8 +287,8 @@ public void validateSessionTokenAsync(boolean isRegionScopedSessionCapturingEnab Document documentDefinition = getDocumentDefinition(); documentDefinition.set( UUID.randomUUID().toString(), - UUID.randomUUID().toString(), - CosmosItemSerializer.DEFAULT_SERIALIZER); + UUID.randomUUID().toString() + ); documents.add(documentDefinition); } diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/ConsistencyTestsBase.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/ConsistencyTestsBase.java index 7dc4619fee59..3b5244997d2e 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/ConsistencyTestsBase.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/ConsistencyTestsBase.java @@ -6,7 +6,6 @@ import com.azure.cosmos.BridgeInternal; import com.azure.cosmos.ConsistencyLevel; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.DirectConnectionConfig; import com.azure.cosmos.GatewayConnectionConfig; import com.azure.cosmos.implementation.apachecommons.collections.map.UnmodifiableMap; @@ -222,7 +221,7 @@ void validateSessionContainerAfterCollectionCreateReplace(boolean useGateway) { { Document document2 = new Document(); document2.setId("test" + UUID.randomUUID().toString()); - document2.set("customerid", 2, CosmosItemSerializer.DEFAULT_SERIALIZER); + document2.set("customerid", 2); // name link ResourceResponse document = writeClient.createDocument(BridgeInternal.getAltLink(coll), document2, null, false) @@ -236,7 +235,7 @@ void validateSessionContainerAfterCollectionCreateReplace(boolean useGateway) { { Document document2 = new Document(); document2.setId("test" + UUID.randomUUID().toString()); - document2.set("customerid", 3, CosmosItemSerializer.DEFAULT_SERIALIZER); + document2.set("customerid", 3); // name link ResourceResponse document = writeClient.createDocument(BridgeInternal.getAltLink(coll), document2, null, false) @@ -747,7 +746,7 @@ void validateSessionTokenMultiPartitionCollectionBase(boolean useGateway, boolea // Document to lock pause/resume clients Document document1 = new Document(); document1.setId("test" + UUID.randomUUID().toString()); - document1.set("mypk", 1, CosmosItemSerializer.DEFAULT_SERIALIZER); + document1.set("mypk", 1); ResourceResponse childResource1 = writeClient.createDocument(createdCollection.getSelfLink(), document1, null, true).block(); logger.info("Created {} child resource", childResource1.getResource().getResourceId()); assertThat(childResource1.getSessionToken()).isNotNull(); @@ -758,7 +757,7 @@ void validateSessionTokenMultiPartitionCollectionBase(boolean useGateway, boolea // Document to lock pause/resume clients Document document2 = new Document(); document2.setId("test" + UUID.randomUUID().toString()); - document2.set("mypk", 2, CosmosItemSerializer.DEFAULT_SERIALIZER); + document2.set("mypk", 2); ResourceResponse childResource2 = writeClient.createDocument(createdCollection.getSelfLink(), document2, null, true).block(); assertThat(childResource2).isNotNull(); assertThat(childResource2.getSessionToken()).isNotNull(); diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/GoneAndRetryPolicyWithSpyClientTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/GoneAndRetryPolicyWithSpyClientTest.java index 79bcaa41a886..ee458e55d169 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/GoneAndRetryPolicyWithSpyClientTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/GoneAndRetryPolicyWithSpyClientTest.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation; import com.azure.cosmos.BridgeInternal; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.DirectConnectionConfig; import com.azure.cosmos.ConsistencyLevel; import com.azure.cosmos.implementation.apachecommons.lang.StringUtils; @@ -444,8 +443,8 @@ private String getCollectionLink() { private Document getDocumentDefinition() { Document doc = new Document(); doc.setId(UUID.randomUUID().toString()); - doc.set(PARTITION_KEY_FIELD_NAME, UUID.randomUUID().toString(), CosmosItemSerializer.DEFAULT_SERIALIZER); - doc.set("name", "Hafez", CosmosItemSerializer.DEFAULT_SERIALIZER); + doc.set(PARTITION_KEY_FIELD_NAME, UUID.randomUUID().toString()); + doc.set("name", "Hafez"); return doc; } } diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/InternalObjectNodeTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/InternalObjectNodeTest.java index ccb632717482..171c01e712a1 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/InternalObjectNodeTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/InternalObjectNodeTest.java @@ -45,7 +45,7 @@ public void ByteArrayWithTrackingId() throws IOException { public void internalObjectNodeWithTrackingId() throws IOException { String expectedTrackingId = UUID.randomUUID().toString(); InternalObjectNode intenalObjectNode = new InternalObjectNode(); - intenalObjectNode.set("id", "myId", CosmosItemSerializer.DEFAULT_SERIALIZER); + intenalObjectNode.set("id", "myId"); ByteBuffer buffer = InternalObjectNode.serializeJsonToByteBuffer( intenalObjectNode, CosmosItemSerializer.DEFAULT_SERIALIZER, expectedTrackingId, false); byte[] blob = new byte[buffer.remaining()]; diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/RegionScopedSessionContainerTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/RegionScopedSessionContainerTest.java index 02a735a8f451..359a3a701ec8 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/RegionScopedSessionContainerTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/RegionScopedSessionContainerTest.java @@ -8,7 +8,7 @@ import com.azure.cosmos.implementation.apachecommons.collections.list.UnmodifiableList; import com.azure.cosmos.implementation.guava25.collect.ImmutableList; import com.azure.cosmos.implementation.guava25.collect.ImmutableMap; -import com.azure.cosmos.implementation.routing.LocationCache; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; import com.azure.cosmos.models.ModelBridgeInternal; import com.azure.cosmos.models.ModelBridgeUtils; import com.azure.cosmos.models.PartitionKey; @@ -375,11 +375,11 @@ public void sessionContainer() throws Exception { int numPartitionKeyRangeIds = 5; String regionContacted = LocationEastUsEndpointToLocationPair.getRight(); - UnmodifiableList endpoints = new UnmodifiableList<>( + UnmodifiableList endpoints = new UnmodifiableList<>( ImmutableList.of( - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUsEndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationCentralUsEndpointToLocationPair.getLeft(), null))); + new RegionalRoutingContext(LocationEastUsEndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationCentralUsEndpointToLocationPair.getLeft()))); Mockito.when(globalEndpointManagerMock.getReadEndpoints()).thenReturn(endpoints); Mockito.when(globalEndpointManagerMock.getRegionName(Mockito.eq(LocationEastUsEndpointToLocationPair.getLeft()), Mockito.any())).thenReturn(regionContacted); @@ -396,7 +396,7 @@ public void sessionContainer() throws Exception { String resultantSessionToken = partitionKeyRangeId + ":" + lsn; RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Read, ResourceType.Document); - request.requestContext.locationEndpointToRoute = LocationEastUsEndpointToLocationPair.getKey(); + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(LocationEastUsEndpointToLocationPair.getKey()); sessionContainer.setSessionToken( request, @@ -409,7 +409,7 @@ public void sessionContainer() throws Exception { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.ReadFeed, ResourceType.DocumentCollection, "dbs/db1/colls/collName_1", Utils.getUTF8Bytes("content1"), new HashMap<>()); - request.requestContext.locationEndpointToRoute = LocationEastUsEndpointToLocationPair.getLeft(); + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(LocationEastUsEndpointToLocationPair.getLeft()); ISessionToken sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, "range_1"); assertThat(sessionToken.getLSN()).isEqualTo(1); @@ -420,7 +420,7 @@ public void sessionContainer() throws Exception { GatewayTestUtils.setParent(resolvedPKRange, ImmutableList.of("range_2", "range_x")); dsrContext.resolvedPartitionKeyRange = resolvedPKRange; request.requestContext = dsrContext; - request.requestContext.locationEndpointToRoute = LocationEastUsEndpointToLocationPair.getLeft(); + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(LocationEastUsEndpointToLocationPair.getLeft()); sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, resolvedPKRange.getId()); assertThat(sessionToken.getLSN()).isEqualTo(2); @@ -439,18 +439,18 @@ public void setSessionToken_NoSessionTokenForPartitionKeyRangeId() throws Except GlobalEndpointManager globalEndpointManagerMock = Mockito.mock(GlobalEndpointManager.class); ISessionContainer sessionContainer = new RegionScopedSessionContainer("127.0.0.1", false, globalEndpointManagerMock); - UnmodifiableList endpoints = new UnmodifiableList<>( + UnmodifiableList endpoints = new UnmodifiableList<>( ImmutableList.of( - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUsEndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationCentralUsEndpointToLocationPair.getLeft(), null))); + new RegionalRoutingContext(LocationEastUsEndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationCentralUsEndpointToLocationPair.getLeft()))); Mockito.when(globalEndpointManagerMock.getReadEndpoints()).thenReturn(endpoints); Mockito.when(globalEndpointManagerMock.getRegionName(Mockito.eq(endpointContacted), Mockito.any())).thenReturn(regionContacted); RxDocumentServiceRequest request1 = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Create, ResourceType.Document, collectionName + "/docs", Utils.getUTF8Bytes("content1"), new HashMap<>()); - request1.requestContext.locationEndpointToRoute = endpointContacted; + request1.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(endpointContacted); String sessionTokenWithPkRangeIdForRequest1 = partitionKeyRangeId + ":" + sessionToken; @@ -483,7 +483,7 @@ public void setSessionToken_NoSessionTokenForPartitionKeyRangeId() throws Except RxDocumentServiceRequest request2 = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Read, ResourceType.Document, collectionName + "/docs", Utils.getUTF8Bytes(""), new HashMap<>()); - request2.requestContext.locationEndpointToRoute = endpointContacted; + request2.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(endpointContacted); ISessionToken resolvedSessionToken = sessionContainer.resolvePartitionLocalSessionToken(request2, partitionKeyRangeId); assertThat(resolvedSessionToken).isNotNull(); @@ -506,18 +506,18 @@ public void setSessionToken_MergeOldWithNew() throws Exception { GlobalEndpointManager globalEndpointManagerMock = Mockito.mock(GlobalEndpointManager.class); RegionScopedSessionContainer sessionContainer = new RegionScopedSessionContainer("127.0.0.1", false, globalEndpointManagerMock); - UnmodifiableList endpoints = new UnmodifiableList<>( + UnmodifiableList endpoints = new UnmodifiableList<>( ImmutableList.of( - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUsEndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationCentralUsEndpointToLocationPair.getLeft(), null))); + new RegionalRoutingContext(LocationEastUsEndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationCentralUsEndpointToLocationPair.getLeft()))); Mockito.when(globalEndpointManagerMock.getReadEndpoints()).thenReturn(endpoints); Mockito.when(globalEndpointManagerMock.getRegionName(Mockito.eq(locationEndpointContacted), Mockito.any())).thenReturn(regionContacted); RxDocumentServiceRequest request1 = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Create, ResourceType.Document, collectionName + "/docs", Utils.getUTF8Bytes("content1"), new HashMap<>()); - request1.requestContext.locationEndpointToRoute = locationEndpointContacted; + request1.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); String initialSessionTokenWithPkRangeId = partitionKeyRangeId + ":" + initialSessionToken; @@ -539,7 +539,7 @@ public void setSessionToken_MergeOldWithNew() throws Exception { RxDocumentServiceRequest request2 = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Read, ResourceType.Document, collectionName + "/docs", Utils.getUTF8Bytes(""), new HashMap<>()); - request2.requestContext.locationEndpointToRoute = locationEndpointContacted; + request2.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); ISessionToken resolvedSessionToken = sessionContainer.resolvePartitionLocalSessionToken(request2, partitionKeyRangeId); assertThat(resolvedSessionToken).isNotNull(); @@ -567,24 +567,24 @@ public void resolveGlobalSessionTokenReturnsEmptyStringOnCacheMiss() { GlobalEndpointManager globalEndpointManagerMock = Mockito.mock(GlobalEndpointManager.class); RegionScopedSessionContainer sessionContainer = new RegionScopedSessionContainer("127.0.0.1", false, globalEndpointManagerMock); - UnmodifiableList endpoints = new UnmodifiableList<>( + UnmodifiableList endpoints = new UnmodifiableList<>( ImmutableList.of( - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUsEndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationCentralUsEndpointToLocationPair.getLeft(), null))); + new RegionalRoutingContext(LocationEastUsEndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationCentralUsEndpointToLocationPair.getLeft()))); Mockito.when(globalEndpointManagerMock.getReadEndpoints()).thenReturn(endpoints); Mockito.when(globalEndpointManagerMock.getRegionName(Mockito.eq(locationEndpointContacted), Mockito.any())).thenReturn(regionContacted); RxDocumentServiceRequest collectionCreateRequest = RxDocumentServiceRequest.create( mockDiagnosticsClientContext(), OperationType.Create, ResourceType.DocumentCollection); - collectionCreateRequest.requestContext.locationEndpointToRoute = locationEndpointContacted; + collectionCreateRequest.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); sessionContainer.setSessionToken(collectionCreateRequest, documentCollectionId, "dbs/db1/colls1/collName", ImmutableMap.of(HttpConstants.HttpHeaders.SESSION_TOKEN, partitionKeyRangeId + ":" + initialSessionToken)); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Read, ResourceType.Document, "dbs/db1/colls1/collName2/docs/doc1", new HashMap<>()); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); assertThat(StringUtils.EMPTY).isEqualTo(sessionContainer.resolveGlobalSessionToken(request)); } @@ -599,17 +599,17 @@ public void resolveGlobalSessionTokenReturnsTokenMapUsingName() { String regionContacted = LocationEastUsEndpointToLocationPair.getRight(); URI locationEndpointContacted = LocationEastUsEndpointToLocationPair.getLeft(); - UnmodifiableList endpoints = new UnmodifiableList<>( + UnmodifiableList endpoints = new UnmodifiableList<>( ImmutableList.of( - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUsEndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationCentralUsEndpointToLocationPair.getLeft(), null))); + new RegionalRoutingContext(LocationEastUsEndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationCentralUsEndpointToLocationPair.getLeft()))); Mockito.when(globalEndpointManagerMock.getReadEndpoints()).thenReturn(endpoints); Mockito.when(globalEndpointManagerMock.getRegionName(Mockito.eq(locationEndpointContacted), Mockito.any())).thenReturn(regionContacted); RxDocumentServiceRequest request1 = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Read, ResourceType.Document); - request1.requestContext.locationEndpointToRoute = locationEndpointContacted; + request1.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); String sessionTokenForRequest1 = "range_0:1#100#1=20#2=5#3=30"; @@ -617,7 +617,7 @@ public void resolveGlobalSessionTokenReturnsTokenMapUsingName() { ImmutableMap.of(HttpConstants.HttpHeaders.SESSION_TOKEN, sessionTokenForRequest1)); RxDocumentServiceRequest request2 = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Read, ResourceType.Document); - request2.requestContext.locationEndpointToRoute = locationEndpointContacted; + request2.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); String sessionTokenForRequest2 = "range_1:1#101#1=20#2=5#3=30"; @@ -645,17 +645,17 @@ public void resolveGlobalSessionTokenReturnsTokenMapUsingResourceId() { String regionContacted = LocationEastUsEndpointToLocationPair.getRight(); URI locationEndpointContacted = LocationEastUsEndpointToLocationPair.getLeft(); - UnmodifiableList endpoints = new UnmodifiableList<>( + UnmodifiableList endpoints = new UnmodifiableList<>( ImmutableList.of( - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUsEndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationCentralUsEndpointToLocationPair.getLeft(), null))); + new RegionalRoutingContext(LocationEastUsEndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationCentralUsEndpointToLocationPair.getLeft()))); Mockito.when(globalEndpointManagerMock.getReadEndpoints()).thenReturn(endpoints); Mockito.when(globalEndpointManagerMock.getRegionName(Mockito.eq(locationEndpointContacted), Mockito.any())).thenReturn(regionContacted); RxDocumentServiceRequest request1 = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Read, ResourceType.Document); - request1.requestContext.locationEndpointToRoute = locationEndpointContacted; + request1.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); String sessionTokenForRequest1 = "range_0:1#100#1=20#2=5#3=30"; @@ -663,7 +663,7 @@ public void resolveGlobalSessionTokenReturnsTokenMapUsingResourceId() { ImmutableMap.of(HttpConstants.HttpHeaders.SESSION_TOKEN, sessionTokenForRequest1)); RxDocumentServiceRequest request2 = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Read, ResourceType.Document); - request2.requestContext.locationEndpointToRoute = locationEndpointContacted; + request2.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); String sessionTokenForRequest2 = "range_1:1#101#1=20#2=5#3=30"; @@ -672,7 +672,7 @@ public void resolveGlobalSessionTokenReturnsTokenMapUsingResourceId() { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Read, documentCollectionId, ResourceType.Document, new HashMap<>()); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); String sessionToken = sessionContainer.resolveGlobalSessionToken(request); @@ -693,17 +693,17 @@ public void resolveLocalSessionTokenReturnsTokenMapUsingName() { String regionContacted = LocationEastUsEndpointToLocationPair.getRight(); URI locationEndpointContacted = LocationEastUsEndpointToLocationPair.getLeft(); - UnmodifiableList endpoints = new UnmodifiableList<>( + UnmodifiableList endpoints = new UnmodifiableList<>( ImmutableList.of( - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUsEndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationCentralUsEndpointToLocationPair.getLeft(), null))); + new RegionalRoutingContext(LocationEastUsEndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationCentralUsEndpointToLocationPair.getLeft()))); Mockito.when(globalEndpointManagerMock.getReadEndpoints()).thenReturn(endpoints); Mockito.when(globalEndpointManagerMock.getRegionName(Mockito.eq(locationEndpointContacted), Mockito.any())).thenReturn(regionContacted); RxDocumentServiceRequest request1 = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Read, ResourceType.Document); - request1.requestContext.locationEndpointToRoute = locationEndpointContacted; + request1.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); String sessionTokenForRequest1 = "range_0:1#100#1=20#2=5#3=30"; @@ -711,7 +711,7 @@ public void resolveLocalSessionTokenReturnsTokenMapUsingName() { ImmutableMap.of(HttpConstants.HttpHeaders.SESSION_TOKEN, sessionTokenForRequest1)); RxDocumentServiceRequest request2 = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Read, ResourceType.Document); - request2.requestContext.locationEndpointToRoute = locationEndpointContacted; + request2.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); String sessionTokenForRequest2 = "range_1:1#101#1=20#2=5#3=30"; @@ -737,17 +737,17 @@ public void resolveLocalSessionTokenReturnsTokenMapUsingResourceId() { String regionContacted = LocationEastUsEndpointToLocationPair.getRight(); URI locationEndpointContacted = LocationEastUsEndpointToLocationPair.getLeft(); - UnmodifiableList endpoints = new UnmodifiableList<>( + UnmodifiableList endpoints = new UnmodifiableList<>( ImmutableList.of( - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUsEndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationCentralUsEndpointToLocationPair.getLeft(), null))); + new RegionalRoutingContext(LocationEastUsEndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationCentralUsEndpointToLocationPair.getLeft()))); Mockito.when(globalEndpointManagerMock.getReadEndpoints()).thenReturn(endpoints); Mockito.when(globalEndpointManagerMock.getRegionName(Mockito.eq(locationEndpointContacted), Mockito.any())).thenReturn(regionContacted); RxDocumentServiceRequest request1 = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Read, ResourceType.Document); - request1.requestContext.locationEndpointToRoute = locationEndpointContacted; + request1.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); String sessionTokenWithPkRangeIdForRequest1 = "range_0:1#100#1=20#2=5#3=30"; @@ -755,7 +755,7 @@ public void resolveLocalSessionTokenReturnsTokenMapUsingResourceId() { ImmutableMap.of(HttpConstants.HttpHeaders.SESSION_TOKEN, sessionTokenWithPkRangeIdForRequest1)); RxDocumentServiceRequest request2 = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Read, ResourceType.Document); - request2.requestContext.locationEndpointToRoute = locationEndpointContacted; + request2.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); String sessionTokenWithPkRangeIdForRequest2 = "range_1:1#101#1=20#2=5#3=30"; @@ -764,7 +764,7 @@ public void resolveLocalSessionTokenReturnsTokenMapUsingResourceId() { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Read, documentCollectionId, ResourceType.Document, new HashMap<>()); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); ISessionToken sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, "range_0"); assertThat(sessionToken).isNotNull(); @@ -786,17 +786,17 @@ public void resolveLocalSessionTokenReturnsNullOnPartitionMiss() { String regionContacted = LocationEastUsEndpointToLocationPair.getRight(); URI locationEndpointContacted = LocationEastUsEndpointToLocationPair.getLeft(); - UnmodifiableList endpoints = new UnmodifiableList<>( + UnmodifiableList endpoints = new UnmodifiableList<>( ImmutableList.of( - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUsEndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationCentralUsEndpointToLocationPair.getLeft(), null))); + new RegionalRoutingContext(LocationEastUsEndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationCentralUsEndpointToLocationPair.getLeft()))); Mockito.when(globalEndpointManagerMock.getReadEndpoints()).thenReturn(endpoints); Mockito.when(globalEndpointManagerMock.getRegionName(Mockito.eq(locationEndpointContacted), Mockito.any())).thenReturn(regionContacted); RxDocumentServiceRequest request1 = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Read, ResourceType.Document); - request1.requestContext.locationEndpointToRoute = locationEndpointContacted; + request1.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); String sessionTokenWithPkRangeIdForRequest1 = "range_0:1#100#1=20#2=5#3=30"; @@ -804,7 +804,7 @@ public void resolveLocalSessionTokenReturnsNullOnPartitionMiss() { ImmutableMap.of(HttpConstants.HttpHeaders.SESSION_TOKEN, sessionTokenWithPkRangeIdForRequest1)); RxDocumentServiceRequest request2 = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Read, ResourceType.Document); - request2.requestContext.locationEndpointToRoute = locationEndpointContacted; + request2.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); String sessionTokenWithPkRangeIdForRequest2 = "range_1:1#101#1=20#2=5#3=30"; @@ -813,7 +813,7 @@ public void resolveLocalSessionTokenReturnsNullOnPartitionMiss() { RxDocumentServiceRequest requestToResultInPkRangeIdBasedMiss = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Read, documentCollectionId, ResourceType.Document, new HashMap<>()); - requestToResultInPkRangeIdBasedMiss.requestContext.locationEndpointToRoute = locationEndpointContacted; + requestToResultInPkRangeIdBasedMiss.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); requestToResultInPkRangeIdBasedMiss.requestContext.resolvedPartitionKeyRange = new PartitionKeyRange(); ISessionToken sessionToken = sessionContainer.resolvePartitionLocalSessionToken(requestToResultInPkRangeIdBasedMiss, "range_2"); @@ -831,17 +831,17 @@ public void resolveLocalSessionTokenReturnsNullOnCollectionMiss() { String regionContacted = LocationEastUsEndpointToLocationPair.getRight(); URI locationEndpointContacted = LocationEastUsEndpointToLocationPair.getLeft(); - UnmodifiableList endpoints = new UnmodifiableList<>( + UnmodifiableList endpoints = new UnmodifiableList<>( ImmutableList.of( - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUsEndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationCentralUsEndpointToLocationPair.getLeft(), null))); + new RegionalRoutingContext(LocationEastUsEndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationCentralUsEndpointToLocationPair.getLeft()))); Mockito.when(globalEndpointManagerMock.getReadEndpoints()).thenReturn(endpoints); Mockito.when(globalEndpointManagerMock.getRegionName(Mockito.eq(locationEndpointContacted), Mockito.any())).thenReturn(regionContacted); RxDocumentServiceRequest request1 = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Read, ResourceType.Document); - request1.requestContext.locationEndpointToRoute = locationEndpointContacted; + request1.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); String sessionTokenWithPkRangeIdForRequest1 = "range_0:1#100#1=20#2=5#3=30"; @@ -849,7 +849,7 @@ public void resolveLocalSessionTokenReturnsNullOnCollectionMiss() { ImmutableMap.of(HttpConstants.HttpHeaders.SESSION_TOKEN, sessionTokenWithPkRangeIdForRequest1)); RxDocumentServiceRequest request2 = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Read, ResourceType.Document); - request2.requestContext.locationEndpointToRoute = locationEndpointContacted; + request2.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); String sessionTokenWithPkRangeIdForRequest2 = "range_1:1#101#1=20#2=5#3=30"; @@ -874,17 +874,17 @@ public void resolvePartitionLocalSessionTokenReturnsTokenOnParentMatch() { String regionContacted = LocationEastUsEndpointToLocationPair.getRight(); URI locationEndpointContacted = LocationEastUsEndpointToLocationPair.getLeft(); - UnmodifiableList endpoints = new UnmodifiableList<>( + UnmodifiableList endpoints = new UnmodifiableList<>( ImmutableList.of( - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUsEndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationCentralUsEndpointToLocationPair.getLeft(), null))); + new RegionalRoutingContext(LocationEastUsEndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationCentralUsEndpointToLocationPair.getLeft()))); Mockito.when(globalEndpointManagerMock.getReadEndpoints()).thenReturn(endpoints); Mockito.when(globalEndpointManagerMock.getRegionName(Mockito.eq(locationEndpointContacted), Mockito.any())).thenReturn(regionContacted); RxDocumentServiceRequest request1 = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Read, ResourceType.Document); - request1.requestContext.locationEndpointToRoute = locationEndpointContacted; + request1.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); String sessionTokenWithPkRangeIdForRequest1 = "range_0:1#100#1=20#2=5#3=30"; @@ -892,7 +892,7 @@ public void resolvePartitionLocalSessionTokenReturnsTokenOnParentMatch() { ImmutableMap.of(HttpConstants.HttpHeaders.SESSION_TOKEN, sessionTokenWithPkRangeIdForRequest1)); RxDocumentServiceRequest request2 = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Read, ResourceType.Document); - request2.requestContext.locationEndpointToRoute = locationEndpointContacted; + request2.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); String sessionTokenWithPkRangeIdForRequest2 = "range_1:1#101#1=20#2=5#3=30"; @@ -920,17 +920,17 @@ public void clearTokenByCollectionFullNameRemovesToken() { URI locationEndpointContacted = LocationEastUsEndpointToLocationPair.getLeft(); String unparsedSessionToken = "range_0:1#100#1=20#2=5#3=30"; - UnmodifiableList endpoints = new UnmodifiableList<>( + UnmodifiableList endpoints = new UnmodifiableList<>( ImmutableList.of( - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUsEndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationCentralUsEndpointToLocationPair.getLeft(), null))); + new RegionalRoutingContext(LocationEastUsEndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationCentralUsEndpointToLocationPair.getLeft()))); Mockito.when(globalEndpointManagerMock.getReadEndpoints()).thenReturn(endpoints); Mockito.when(globalEndpointManagerMock.getRegionName(Mockito.eq(locationEndpointContacted), Mockito.any())).thenReturn(regionContacted); RxDocumentServiceRequest documentCollectionCreateRequest = createRequestEntity(OperationType.Create, ResourceType.DocumentCollection, LocationEastUsEndpointToLocationPair.getLeft()); - documentCollectionCreateRequest.requestContext.locationEndpointToRoute = locationEndpointContacted; + documentCollectionCreateRequest.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); sessionContainer.setSessionToken(documentCollectionCreateRequest, documentCollectionId, collectionFullName, ImmutableMap.of(HttpConstants.HttpHeaders.SESSION_TOKEN, unparsedSessionToken)); @@ -938,7 +938,7 @@ public void clearTokenByCollectionFullNameRemovesToken() { // Test getResourceId based RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Read, documentCollectionId, ResourceType.Document, new HashMap<>()); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); ISessionToken sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, "range_0"); assertThat(sessionToken.getLSN()).isEqualTo(100); @@ -946,7 +946,7 @@ public void clearTokenByCollectionFullNameRemovesToken() { // Test names based request = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(),OperationType.Read, collectionFullName + "/docs/doc1", ResourceType.Document); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, "range_0"); assertThat(sessionToken.getLSN()).isEqualTo(100); @@ -956,7 +956,7 @@ public void clearTokenByCollectionFullNameRemovesToken() { // Test resourceId based request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Read, documentCollectionId, ResourceType.Document, new HashMap<>()); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, "range_0"); assertThat(sessionToken).isNull(); @@ -964,7 +964,7 @@ public void clearTokenByCollectionFullNameRemovesToken() { // Test names based request = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(),OperationType.Read, collectionFullName + "/docs/doc1", ResourceType.Document); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, "range_0"); assertThat(sessionToken).isNull(); @@ -983,17 +983,17 @@ public void clearTokenByResourceIdRemovesToken() { String unparsedSessionToken = "range_0:1#100#1=20#2=5#3=30"; - UnmodifiableList endpoints = new UnmodifiableList<>( + UnmodifiableList endpoints = new UnmodifiableList<>( ImmutableList.of( - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUsEndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationCentralUsEndpointToLocationPair.getLeft(), null))); + new RegionalRoutingContext(LocationEastUsEndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationCentralUsEndpointToLocationPair.getLeft()))); Mockito.when(globalEndpointManagerMock.getReadEndpoints()).thenReturn(endpoints); Mockito.when(globalEndpointManagerMock.getRegionName(Mockito.eq(locationEndpointContacted), Mockito.any())).thenReturn(regionContacted); RxDocumentServiceRequest documentCollectionCreateRequest = createRequestEntity(OperationType.Create, ResourceType.DocumentCollection, LocationEastUsEndpointToLocationPair.getLeft()); - documentCollectionCreateRequest.requestContext.locationEndpointToRoute = locationEndpointContacted; + documentCollectionCreateRequest.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); sessionContainer.setSessionToken(documentCollectionCreateRequest, documentCollectionId, collectionFullName, ImmutableMap.of(HttpConstants.HttpHeaders.SESSION_TOKEN, unparsedSessionToken)); @@ -1001,7 +1001,7 @@ public void clearTokenByResourceIdRemovesToken() { // Test resourceId based RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Read, documentCollectionId, ResourceType.Document, new HashMap<>()); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); ISessionToken sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, "range_0"); assertThat(sessionToken).isNotNull(); @@ -1010,7 +1010,7 @@ public void clearTokenByResourceIdRemovesToken() { // Test names based request = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(),OperationType.Read, collectionFullName + "/docs/doc1", ResourceType.Document); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, "range_0"); assertThat(sessionToken).isNotNull(); @@ -1021,7 +1021,7 @@ public void clearTokenByResourceIdRemovesToken() { // Test resourceId based request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Read, documentCollectionId, ResourceType.Document, new HashMap<>()); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, "range_0"); assertThat(sessionToken).isNull(); @@ -1029,7 +1029,7 @@ public void clearTokenByResourceIdRemovesToken() { // Test names based request = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(),OperationType.Read, collectionFullName + "/docs/doc1", ResourceType.Document); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, "range_0"); assertThat(sessionToken).isNull(); @@ -1047,17 +1047,17 @@ public void clearTokenKeepsUnmatchedCollection() { URI locationEndpointContacted = LocationEastUsEndpointToLocationPair.getLeft(); String unparsedSessionToken = "range_0:1#100#1=20#2=5#3=30"; - UnmodifiableList endpoints = new UnmodifiableList<>( + UnmodifiableList endpoints = new UnmodifiableList<>( ImmutableList.of( - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUsEndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationCentralUsEndpointToLocationPair.getLeft(), null))); + new RegionalRoutingContext(LocationEastUsEndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationCentralUsEndpointToLocationPair.getLeft()))); Mockito.when(globalEndpointManagerMock.getReadEndpoints()).thenReturn(endpoints); Mockito.when(globalEndpointManagerMock.getRegionName(Mockito.eq(locationEndpointContacted), Mockito.any())).thenReturn(regionContacted); RxDocumentServiceRequest documentCollectionCreateRequest = createRequestEntity(OperationType.Create, ResourceType.DocumentCollection, LocationEastUsEndpointToLocationPair.getLeft()); - documentCollectionCreateRequest.requestContext.locationEndpointToRoute = locationEndpointContacted; + documentCollectionCreateRequest.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); sessionContainer.setSessionToken(documentCollectionCreateRequest, documentCollectionId1, collectionFullName1, ImmutableMap.of(HttpConstants.HttpHeaders.SESSION_TOKEN, unparsedSessionToken)); @@ -1065,7 +1065,7 @@ public void clearTokenKeepsUnmatchedCollection() { // Test resourceId based RxDocumentServiceRequest request1 = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Read, documentCollectionId1, ResourceType.Document, new HashMap<>()); - request1.requestContext.locationEndpointToRoute = locationEndpointContacted; + request1.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); String documentCollectionId2 = ResourceId.newDocumentCollectionId(getRandomDbId(), randomCollectionId - 1).getDocumentCollectionId().toString(); String collectionFullName2 = "dbs/db1/colls1/collName2"; @@ -1073,7 +1073,7 @@ public void clearTokenKeepsUnmatchedCollection() { // Test resourceId based RxDocumentServiceRequest request2 = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Read, documentCollectionId2, ResourceType.Document, new HashMap<>()); - request2.requestContext.locationEndpointToRoute = locationEndpointContacted; + request2.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); sessionContainer.setSessionToken(request2, documentCollectionId2, collectionFullName2, ImmutableMap.of(HttpConstants.HttpHeaders.SESSION_TOKEN, unparsedSessionToken)); @@ -1106,18 +1106,18 @@ public void setSessionTokenSetsTokenWhenRequestIsntNameBased() { String regionContacted = LocationEastUsEndpointToLocationPair.getRight(); URI locationEndpointContacted = LocationEastUsEndpointToLocationPair.getLeft(); - UnmodifiableList endpoints = new UnmodifiableList<>( + UnmodifiableList endpoints = new UnmodifiableList<>( ImmutableList.of( - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUsEndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationCentralUsEndpointToLocationPair.getLeft(), null))); + new RegionalRoutingContext(LocationEastUsEndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationCentralUsEndpointToLocationPair.getLeft()))); Mockito.when(globalEndpointManagerMock.getReadEndpoints()).thenReturn(endpoints); Mockito.when(globalEndpointManagerMock.getRegionName(Mockito.eq(locationEndpointContacted), Mockito.any())).thenReturn(regionContacted); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Read, collectionFullName + "/docs/doc1", ResourceType.Document, new HashMap<>()); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); String sessionTokenWithPkRangeIdForRequest = "range_0:1#100#4=90#5=1"; request.setResourceId(documentCollectionId); @@ -1125,7 +1125,7 @@ public void setSessionTokenSetsTokenWhenRequestIsntNameBased() { assertThat(request.getIsNameBased()).isFalse(); sessionContainer.setSessionToken(request, ImmutableMap.of(HttpConstants.HttpHeaders.SESSION_TOKEN, sessionTokenWithPkRangeIdForRequest)); request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Read, documentCollectionId, ResourceType.Document, new HashMap<>()); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); ISessionToken sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, "range_0"); assertThat(sessionToken).isNotNull(); @@ -1148,18 +1148,18 @@ public void setSessionTokenGivesPriorityToOwnerFullNameOverResourceAddress() { String regionContacted = LocationEastUsEndpointToLocationPair.getRight(); URI locationEndpointContacted = LocationEastUsEndpointToLocationPair.getLeft(); - UnmodifiableList endpoints = new UnmodifiableList<>( + UnmodifiableList endpoints = new UnmodifiableList<>( ImmutableList.of( - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUsEndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationCentralUsEndpointToLocationPair.getLeft(), null))); + new RegionalRoutingContext(LocationEastUsEndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationCentralUsEndpointToLocationPair.getLeft()))); Mockito.when(globalEndpointManagerMock.getReadEndpoints()).thenReturn(endpoints); Mockito.when(globalEndpointManagerMock.getRegionName(Mockito.eq(locationEndpointContacted), Mockito.any())).thenReturn(regionContacted); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Read, collectionFullName1 + "/docs/doc1", ResourceType.Document, new HashMap<>()); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); String sessionTokenWithPkRangeIdForRequest = "range_0:1#100#4=90#5=1"; request.setResourceId(documentCollectionId); @@ -1169,13 +1169,13 @@ public void setSessionTokenGivesPriorityToOwnerFullNameOverResourceAddress() { HttpConstants.HttpHeaders.OWNER_FULL_NAME, collectionFullName2)); request = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(),OperationType.Read, collectionFullName1 + "/docs/doc1", ResourceType.Document); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); ISessionToken sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, "range_0"); assertThat(sessionToken).isNull(); request = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(),OperationType.Read, collectionFullName2 + "/docs/doc1", ResourceType.Document); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, "range_0"); assertThat(sessionToken).isNotNull(); @@ -1195,18 +1195,18 @@ public void setSessionTokenIgnoresOwnerIdWhenRequestIsntNameBased() { String regionContacted = LocationEastUsEndpointToLocationPair.getRight(); URI locationEndpointContacted = LocationEastUsEndpointToLocationPair.getLeft(); - UnmodifiableList endpoints = new UnmodifiableList<>( + UnmodifiableList endpoints = new UnmodifiableList<>( ImmutableList.of( - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUsEndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationCentralUsEndpointToLocationPair.getLeft(), null))); + new RegionalRoutingContext(LocationEastUsEndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationCentralUsEndpointToLocationPair.getLeft()))); Mockito.when(globalEndpointManagerMock.getReadEndpoints()).thenReturn(endpoints); Mockito.when(globalEndpointManagerMock.getRegionName(Mockito.eq(locationEndpointContacted), Mockito.any())).thenReturn(regionContacted); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Read, collectionFullName + "/docs/doc1", ResourceType.Document, new HashMap<>()); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); request.setResourceId(documentCollectionId1); @@ -1220,7 +1220,7 @@ public void setSessionTokenIgnoresOwnerIdWhenRequestIsntNameBased() { request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Read, documentCollectionId1, ResourceType.Document, new HashMap<>()); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); ISessionToken sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, "range_0"); assertThat(sessionToken).isNotNull(); @@ -1229,7 +1229,7 @@ public void setSessionTokenIgnoresOwnerIdWhenRequestIsntNameBased() { request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Read, documentCollectionId2, ResourceType.Document, new HashMap<>()); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, "range_0"); assertThat(sessionToken).isNull(); @@ -1249,18 +1249,18 @@ public void setSessionTokenGivesPriorityToOwnerIdOverResourceIdWhenRequestIsName String regionContacted = LocationEastUsEndpointToLocationPair.getRight(); URI locationEndpointContacted = LocationEastUsEndpointToLocationPair.getLeft(); - UnmodifiableList endpoints = new UnmodifiableList<>( + UnmodifiableList endpoints = new UnmodifiableList<>( ImmutableList.of( - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUsEndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationCentralUsEndpointToLocationPair.getLeft(), null))); + new RegionalRoutingContext(LocationEastUsEndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationCentralUsEndpointToLocationPair.getLeft()))); Mockito.when(globalEndpointManagerMock.getReadEndpoints()).thenReturn(endpoints); Mockito.when(globalEndpointManagerMock.getRegionName(Mockito.eq(LocationEastUsEndpointToLocationPair.getLeft()), Mockito.any())).thenReturn(regionContacted); RxDocumentServiceRequest request = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(),OperationType.Read, collectionFullName + "/docs/doc1", ResourceType.Document); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); request.setResourceId(documentCollectionId1); @@ -1273,14 +1273,14 @@ public void setSessionTokenGivesPriorityToOwnerIdOverResourceIdWhenRequestIsName request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Read, documentCollectionId1, ResourceType.Document, new HashMap<>()); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); ISessionToken sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, "range_0"); assertThat(sessionToken).isNull(); request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Read, documentCollectionId2, ResourceType.Document, new HashMap<>()); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, "range_0"); assertThat(sessionToken.getLSN()).isEqualTo(100); @@ -1317,18 +1317,18 @@ public void setSessionTokenDoesntOverwriteHigherLSN() { String regionContacted = LocationEastUsEndpointToLocationPair.getRight(); URI locationEndpointContacted = LocationEastUsEndpointToLocationPair.getLeft(); - UnmodifiableList endpoints = new UnmodifiableList<>( + UnmodifiableList endpoints = new UnmodifiableList<>( ImmutableList.of( - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUsEndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationCentralUsEndpointToLocationPair.getLeft(), null))); + new RegionalRoutingContext(LocationEastUsEndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationCentralUsEndpointToLocationPair.getLeft()))); Mockito.when(globalEndpointManagerMock.getReadEndpoints()).thenReturn(endpoints); Mockito.when(globalEndpointManagerMock.getRegionName(Mockito.eq(locationEndpointContacted), Mockito.any())).thenReturn(regionContacted); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Read, collectionFullName + "/docs/doc1", ResourceType.Document, new HashMap<>()); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); String sessionTokenWithPkRangeIdForRequest = "range_0:1#100#4=90#5=1"; @@ -1338,7 +1338,7 @@ public void setSessionTokenDoesntOverwriteHigherLSN() { request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Read, collectionFullName + "/docs/doc1", ResourceType.Document, new HashMap<>()); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); String sessionTokenWithPkRangeIdToBeOverwritten = "range_0:1#105#4=90#5=1"; @@ -1347,7 +1347,7 @@ public void setSessionTokenDoesntOverwriteHigherLSN() { request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Read, documentCollectionId, ResourceType.Document, new HashMap<>()); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); request.setResourceId(documentCollectionId); ISessionToken sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, "range_0"); @@ -1365,18 +1365,18 @@ public void setSessionTokenOverwriteLowerLSN() { String regionContacted = LocationEastUsEndpointToLocationPair.getRight(); URI locationEndpointContacted = LocationEastUsEndpointToLocationPair.getLeft(); - UnmodifiableList endpoints = new UnmodifiableList<>( + UnmodifiableList endpoints = new UnmodifiableList<>( ImmutableList.of( - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUsEndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationCentralUsEndpointToLocationPair.getLeft(), null))); + new RegionalRoutingContext(LocationEastUsEndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationCentralUsEndpointToLocationPair.getLeft()))); Mockito.when(globalEndpointManagerMock.getReadEndpoints()).thenReturn(endpoints); Mockito.when(globalEndpointManagerMock.getRegionName(Mockito.eq(locationEndpointContacted), Mockito.any())).thenReturn(regionContacted); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Read, collectionFullName + "/docs/doc1", ResourceType.Document, new HashMap<>()); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); String sessionTokenWithPkRangeIdForRequest = "range_0:1#105#4=90#5=1"; request.setResourceId(documentCollectionId); @@ -1385,7 +1385,7 @@ public void setSessionTokenOverwriteLowerLSN() { request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Read, collectionFullName + "/docs/doc1", ResourceType.Document, new HashMap<>()); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); String sessionTokenWithPkRangeIdToBeOverwritten = "range_0:1#100#4=90#5=1"; @@ -1395,7 +1395,7 @@ public void setSessionTokenOverwriteLowerLSN() { request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Read, documentCollectionId, ResourceType.Document, new HashMap<>()); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); request.setResourceId(documentCollectionId); ISessionToken sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, "range_0"); @@ -1412,17 +1412,17 @@ public void setSessionTokenDoesNothingOnEmptySessionTokenHeader() { String regionContacted = LocationEastUsEndpointToLocationPair.getRight(); URI locationEndpointContacted = LocationEastUsEndpointToLocationPair.getLeft(); - UnmodifiableList endpoints = new UnmodifiableList<>( + UnmodifiableList endpoints = new UnmodifiableList<>( ImmutableList.of( - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUsEndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationCentralUsEndpointToLocationPair.getLeft(), null))); + new RegionalRoutingContext(LocationEastUsEndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationCentralUsEndpointToLocationPair.getLeft()))); Mockito.when(globalEndpointManagerMock.getReadEndpoints()).thenReturn(endpoints); Mockito.when(globalEndpointManagerMock.getRegionName(Mockito.eq(locationEndpointContacted), Mockito.any())).thenReturn(regionContacted); RxDocumentServiceRequest docReadRequest1 = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Read, ResourceType.Document); - docReadRequest1.requestContext.locationEndpointToRoute = locationEndpointContacted; + docReadRequest1.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); String sessionTokenWithPkRangeIdForDocReadRequest1 = "range_0:1#100#4=90#5=1"; @@ -1430,7 +1430,7 @@ public void setSessionTokenDoesNothingOnEmptySessionTokenHeader() { ImmutableMap.of(HttpConstants.HttpHeaders.SESSION_TOKEN, sessionTokenWithPkRangeIdForDocReadRequest1)); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Read, documentCollectionId, ResourceType.Document, new HashMap<>()); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); String sessionToken = sessionContainer.resolveGlobalSessionToken(request); Set tokens = Sets.newSet(sessionToken.split(",")); @@ -1438,12 +1438,12 @@ public void setSessionTokenDoesNothingOnEmptySessionTokenHeader() { assertThat(tokens.contains(sessionTokenWithPkRangeIdForDocReadRequest1)).isTrue(); RxDocumentServiceRequest docReadRequest2 = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Read, ResourceType.Document); - docReadRequest2.requestContext.locationEndpointToRoute = locationEndpointContacted; + docReadRequest2.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); sessionContainer.setSessionToken(docReadRequest2, documentCollectionId, collectionFullName, new HashMap<>()); request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Read, documentCollectionId, ResourceType.Document, new HashMap<>()); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); sessionToken = sessionContainer.resolveGlobalSessionToken(request); tokens = Sets.newSet(sessionToken.split(",")); @@ -1508,11 +1508,11 @@ public void useParentSessionTokenAfterSplit() { String regionContacted = LocationEastUsEndpointToLocationPair.getRight(); URI locationEndpointContacted = LocationEastUsEndpointToLocationPair.getLeft(); - UnmodifiableList endpoints = new UnmodifiableList<>( + UnmodifiableList endpoints = new UnmodifiableList<>( ImmutableList.of( - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUsEndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationCentralUsEndpointToLocationPair.getLeft(), null))); + new RegionalRoutingContext(LocationEastUsEndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationCentralUsEndpointToLocationPair.getLeft()))); Mockito.when(globalEndpointManagerMock.getReadEndpoints()).thenReturn(endpoints); Mockito.when(globalEndpointManagerMock.getRegionName(Mockito.eq(locationEndpointContacted), Mockito.any())).thenReturn(regionContacted); @@ -1523,7 +1523,7 @@ public void useParentSessionTokenAfterSplit() { String resultantParentSessionToken = parentPKRangeId + ":" + parentSession; RxDocumentServiceRequest request1 = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Read, ResourceType.Document); - request1.requestContext.locationEndpointToRoute = locationEndpointContacted; + request1.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); sessionContainer.setSessionToken( request1, @@ -1535,7 +1535,7 @@ public void useParentSessionTokenAfterSplit() { String childPKRangeId = "1"; RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Read, documentCollectionId1, ResourceType.Document, new HashMap<>()); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); request.requestContext.resolvedPartitionKeyRange = new PartitionKeyRange( @@ -1560,11 +1560,11 @@ public void useParentSessionTokenAfterMerge() { String regionContacted = LocationEastUsEndpointToLocationPair.getRight(); URI locationEndpointContacted = LocationEastUsEndpointToLocationPair.getLeft(); - UnmodifiableList endpoints = new UnmodifiableList<>( + UnmodifiableList endpoints = new UnmodifiableList<>( ImmutableList.of( - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUsEndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationEastUs2EndpointToLocationPair.getLeft(), null), - new LocationCache.ConsolidatedRegionalEndpoint(LocationCentralUsEndpointToLocationPair.getLeft(), null))); + new RegionalRoutingContext(LocationEastUsEndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationEastUs2EndpointToLocationPair.getLeft()), + new RegionalRoutingContext(LocationCentralUsEndpointToLocationPair.getLeft()))); Mockito.when(globalEndpointManagerMock.getReadEndpoints()).thenReturn(endpoints); Mockito.when(globalEndpointManagerMock.getRegionName(Mockito.eq(locationEndpointContacted), Mockito.any())).thenReturn(regionContacted); @@ -1589,7 +1589,7 @@ public void useParentSessionTokenAfterMerge() { String parent1SessionToken = parent1PKRangeId + ":" + parent1Session; RxDocumentServiceRequest request1 = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Read, ResourceType.Document); - request1.requestContext.locationEndpointToRoute = locationEndpointContacted; + request1.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); sessionContainer.setSessionToken( request1, @@ -1607,7 +1607,7 @@ public void useParentSessionTokenAfterMerge() { String parent2SessionToken = parent2PKRangeId + ":" + parent2Session; RxDocumentServiceRequest request2 = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Read, ResourceType.Document); - request2.requestContext.locationEndpointToRoute = locationEndpointContacted; + request2.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); sessionContainer.setSessionToken( request2, @@ -1619,7 +1619,7 @@ public void useParentSessionTokenAfterMerge() { String childPKRangeId = "2"; RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(),OperationType.Read, documentCollectionId1, ResourceType.Document, new HashMap<>()); - request.requestContext.locationEndpointToRoute = locationEndpointContacted; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointContacted); request.requestContext.resolvedPartitionKeyRange = new PartitionKeyRange( @@ -1659,14 +1659,14 @@ public void resolvePartitionLocalSessionToken( GlobalEndpointManager globalEndpointManagerMock = null; RegionScopedSessionContainer sessionContainer = null; - List consolidatedWriteRegionalEndpoints = writableURIToLocationMappings + List consolidatedWriteRegionalEndpointRoutingContexts = writableURIToLocationMappings .stream() - .map(uriToLocationMappings -> new LocationCache.ConsolidatedRegionalEndpoint(uriToLocationMappings.getLeft(), null)) + .map(uriToLocationMappings -> new RegionalRoutingContext(uriToLocationMappings.getLeft())) .collect(Collectors.toList()); - List consolidatedReadRegionalEndpoints = readEndpoints + List consolidatedReadRegionalEndpointRoutingContexts = readEndpoints .stream() - .map(readEndpoint -> new LocationCache.ConsolidatedRegionalEndpoint(readEndpoint, null)) + .map(readEndpoint -> new RegionalRoutingContext(readEndpoint)) .collect(Collectors.toList()); DatabaseAccount databaseAccount = ModelBridgeUtils.createDatabaseAccount( @@ -1681,7 +1681,7 @@ public void resolvePartitionLocalSessionToken( .when(globalEndpointManagerMock.getLatestDatabaseAccount()) .thenReturn(databaseAccount); - UnmodifiableList readEndpointsInUnmodifiableList = new UnmodifiableList<>(consolidatedReadRegionalEndpoints); + UnmodifiableList readEndpointsInUnmodifiableList = new UnmodifiableList<>(consolidatedReadRegionalEndpointRoutingContexts); Mockito .when(globalEndpointManagerMock.getReadEndpoints()) @@ -1689,7 +1689,7 @@ public void resolvePartitionLocalSessionToken( Mockito .when(globalEndpointManagerMock.getApplicableWriteEndpoints(Mockito.anyList())) - .thenReturn(new UnmodifiableList<>(consolidatedWriteRegionalEndpoints)); + .thenReturn(new UnmodifiableList<>(consolidatedWriteRegionalEndpointRoutingContexts)); Mockito .when(globalEndpointManagerMock.canUseMultipleWriteLocations(Mockito.any())) @@ -1710,7 +1710,7 @@ public void resolvePartitionLocalSessionToken( RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Read, ResourceType.Document); // doesn't matter for a request for which the session token has to be resolved - request.requestContext.locationEndpointToRoute = LocationEastUsEndpointToLocationPair.getLeft(); + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(LocationEastUsEndpointToLocationPair.getLeft()); request.setResourceId(documentCollectionId1); if (pkToBeUsedForSessionTokenResolution != null) { @@ -1761,7 +1761,7 @@ private static RequestMetadata constructRequestInstance( request.setResourceId(collectionResourceId); request.setPartitionKeyInternal(BridgeInternal.getPartitionKeyInternal(partitionKey)); request.setPartitionKeyDefinition(partitionKeyDefinition); - request.requestContext.locationEndpointToRoute = locationEndpointToRoute; + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointToRoute); return new RequestMetadata(request, responseHeaders); } @@ -1773,8 +1773,7 @@ private static RxDocumentServiceRequest createRequestEntity(OperationType operat operationType, resourceType); - request.requestContext.locationEndpointToRoute = locationEndpointToRoute; - request.requestContext.consolidatedRegionalEndpointToRoute = new LocationCache.ConsolidatedRegionalEndpoint(locationEndpointToRoute, null); + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointToRoute); return request; } diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/RenameCollectionAwareClientRetryPolicyTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/RenameCollectionAwareClientRetryPolicyTest.java index 44f5896961d1..b2a9feeb879f 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/RenameCollectionAwareClientRetryPolicyTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/RenameCollectionAwareClientRetryPolicyTest.java @@ -6,7 +6,7 @@ import com.azure.cosmos.implementation.caches.RxClientCollectionCache; import com.azure.cosmos.implementation.circuitBreaker.GlobalPartitionEndpointManagerForCircuitBreaker; import com.azure.cosmos.implementation.directconnectivity.WFConstants; -import com.azure.cosmos.implementation.routing.LocationCache; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; import io.netty.handler.timeout.ReadTimeoutException; import org.mockito.Mockito; import org.testng.annotations.Test; @@ -61,7 +61,7 @@ public void shouldRetryWithNotFoundStatusCode() throws URISyntaxException { Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(eq(null), eq(false)); URI locationEndToRoute = new URI("https://location1.documents.com"); - LocationCache.ConsolidatedRegionalEndpoint consolidatedLocationEndpointToRoute = new LocationCache.ConsolidatedRegionalEndpoint(locationEndToRoute, null); + RegionalRoutingContext consolidatedLocationEndpointToRoute = new RegionalRoutingContext(locationEndToRoute); Mockito.when(endpointManager.resolveServiceEndpoint(Mockito.any())).thenReturn(consolidatedLocationEndpointToRoute); @@ -95,7 +95,7 @@ public void shouldRetryWithNotFoundStatusCodeAndReadSessionNotAvailableSubStatus Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(eq(null), eq(false)); URI locationEndToRoute = new URI("https://location1.documents.com"); - LocationCache.ConsolidatedRegionalEndpoint consolidatedLocationEndpointToRoute = new LocationCache.ConsolidatedRegionalEndpoint(locationEndToRoute, null); + RegionalRoutingContext consolidatedLocationEndpointToRoute = new RegionalRoutingContext(locationEndToRoute); Mockito.when(endpointManager.resolveServiceEndpoint(Mockito.any())).thenReturn(consolidatedLocationEndpointToRoute); @@ -138,7 +138,7 @@ public void shouldRetryWithGenericException() throws URISyntaxException { GlobalPartitionEndpointManagerForCircuitBreaker globalPartitionEndpointManager = Mockito.mock(GlobalPartitionEndpointManagerForCircuitBreaker.class); URI locationEndToRoute = new URI("https://location1.documents.com"); - LocationCache.ConsolidatedRegionalEndpoint consolidatedLocationEndpointToRoute = new LocationCache.ConsolidatedRegionalEndpoint(locationEndToRoute, null); + RegionalRoutingContext consolidatedLocationEndpointToRoute = new RegionalRoutingContext(locationEndToRoute); Mockito.when(endpointManager.resolveServiceEndpoint(Mockito.any())).thenReturn(consolidatedLocationEndpointToRoute); diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/RxGatewayStoreModelTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/RxGatewayStoreModelTest.java index ed505f63fa53..889f09b14314 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/RxGatewayStoreModelTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/RxGatewayStoreModelTest.java @@ -11,9 +11,8 @@ import com.azure.cosmos.implementation.http.HttpClient; import com.azure.cosmos.implementation.http.HttpHeaders; import com.azure.cosmos.implementation.http.HttpRequest; -import com.azure.cosmos.implementation.routing.LocationCache; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; import io.netty.channel.ConnectTimeoutException; -import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.timeout.ReadTimeoutException; import io.reactivex.subscribers.TestSubscriber; import org.mockito.ArgumentCaptor; @@ -81,9 +80,10 @@ public void readTimeout() throws Exception { QueryCompatibilityMode queryCompatibilityMode = QueryCompatibilityMode.Default; UserAgentContainer userAgentContainer = new UserAgentContainer(); GlobalEndpointManager globalEndpointManager = Mockito.mock(GlobalEndpointManager.class); - GlobalPartitionEndpointManagerForCircuitBreaker globalPartitionEndpointManager = Mockito.mock(GlobalPartitionEndpointManagerForCircuitBreaker.class); - Mockito.doReturn(new LocationCache.ConsolidatedRegionalEndpoint(new URI("https://localhost"), null)) + RegionalRoutingContext regionalRoutingContext = new RegionalRoutingContext(new URI("https://localhost")); + + Mockito.doReturn(regionalRoutingContext) .when(globalEndpointManager).resolveServiceEndpoint(any()); HttpClient httpClient = Mockito.mock(HttpClient.class); Mockito.doReturn(Mono.error(ReadTimeoutException.INSTANCE)) @@ -106,7 +106,7 @@ public void readTimeout() throws Exception { OperationType.Read, "/dbs/db/colls/col/docs/docId", ResourceType.Document); dsr.getHeaders().put("key", "value"); dsr.requestContext = new DocumentServiceRequestContext(); - + dsr.requestContext.regionalRoutingContextToRoute = regionalRoutingContext; Mono resp = storeModel.processMessage(dsr); validateFailure(resp, FailureValidator.builder() @@ -126,7 +126,9 @@ public void serviceUnavailable() throws Exception { UserAgentContainer userAgentContainer = new UserAgentContainer(); GlobalEndpointManager globalEndpointManager = Mockito.mock(GlobalEndpointManager.class); GlobalPartitionEndpointManagerForCircuitBreaker globalPartitionEndpointManager = Mockito.mock(GlobalPartitionEndpointManagerForCircuitBreaker.class); - Mockito.doReturn(new LocationCache.ConsolidatedRegionalEndpoint(new URI("https://localhost"), null)) + + RegionalRoutingContext regionalRoutingContext = new RegionalRoutingContext(new URI("https://localhost")); + Mockito.doReturn(regionalRoutingContext) .when(globalEndpointManager).resolveServiceEndpoint(any()); HttpClient httpClient = Mockito.mock(HttpClient.class); Mockito.doReturn(Mono.error(new SocketException("Dummy SocketException"))) @@ -149,7 +151,7 @@ public void serviceUnavailable() throws Exception { OperationType.Read, "/dbs/db/colls/col/docs/docId", ResourceType.Document); dsr.getHeaders().put("key", "value"); dsr.requestContext = new DocumentServiceRequestContext(); - + dsr.requestContext.regionalRoutingContextToRoute = regionalRoutingContext; Mono resp = storeModel.processMessage(dsr); validateFailure(resp, FailureValidator.builder() @@ -178,9 +180,10 @@ public void applySessionToken( Mockito.doReturn(sdkGlobalSessionToken).when(sessionContainer).resolveGlobalSessionToken(any()); GlobalEndpointManager globalEndpointManager = Mockito.mock(GlobalEndpointManager.class); - GlobalPartitionEndpointManagerForCircuitBreaker globalPartitionEndpointManager = Mockito.mock(GlobalPartitionEndpointManagerForCircuitBreaker.class); + URI locationEndpointToRoute = new URI("https://localhost"); + RegionalRoutingContext regionalRoutingContext = new RegionalRoutingContext(locationEndpointToRoute); - Mockito.doReturn(new LocationCache.ConsolidatedRegionalEndpoint(new URI("https://localhost"), null)) + Mockito.doReturn(new RegionalRoutingContext(new URI("https://localhost"))) .when(globalEndpointManager).resolveServiceEndpoint(any()); HttpClient httpClient = Mockito.mock(HttpClient.class); @@ -208,6 +211,13 @@ public void applySessionToken( operationType, "/fakeResourceFullName", resourceType); + + if (resourceType != ResourceType.DatabaseAccount) { + dsr.requestContext.regionalRoutingContextToRoute = regionalRoutingContext; + } else { + dsr.setEndpointOverride(locationEndpointToRoute); + } + if (sessionTokenFromUser) { dsr.getHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, userControlledSessionToken); } @@ -249,9 +259,8 @@ public void validateApiType() throws Exception { Mockito.doReturn(sdkGlobalSessionToken).when(sessionContainer).resolveGlobalSessionToken(any()); GlobalEndpointManager globalEndpointManager = Mockito.mock(GlobalEndpointManager.class); - GlobalPartitionEndpointManagerForCircuitBreaker globalPartitionEndpointManager = Mockito.mock(GlobalPartitionEndpointManagerForCircuitBreaker.class); - Mockito.doReturn(new LocationCache.ConsolidatedRegionalEndpoint(new URI("https://localhost"), null)) + Mockito.doReturn(new RegionalRoutingContext(new URI("https://localhost"))) .when(globalEndpointManager).resolveServiceEndpoint(any()); HttpClient httpClient = Mockito.mock(HttpClient.class); diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/SessionTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/SessionTest.java index b95958874add..e6006c14f265 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/SessionTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/SessionTest.java @@ -4,7 +4,6 @@ import com.azure.cosmos.ConnectionMode; import com.azure.cosmos.ConsistencyLevel; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.batch.ItemBatchOperation; import com.azure.cosmos.implementation.batch.SinglePartitionKeyServerBatchRequest; import com.azure.cosmos.implementation.directconnectivity.ReflectionUtils; @@ -154,7 +153,7 @@ public void partitionedSessionToken(boolean isNameBased) throws NoSuchMethodExce RequestOptions requestOptions = new RequestOptions(); for (int i = 0; i < 10; i++) { Document document = newDocument(); - document.set("mypk", document.getId(), CosmosItemSerializer.DEFAULT_SERIALIZER); + document.set("mypk", document.getId()); requestOptions.setPartitionKey(new PartitionKey(document.getId())); documentCreated = spyClient.createDocument(getCollectionLink(isNameBased), document, requestOptions, false) .block().getResource(); @@ -285,7 +284,7 @@ public void partitionedSessionToken(boolean isNameBased) throws NoSuchMethodExce if(isNameBased) { // Batch only work with name based url spyClient.clearCapturedRequests(); Document document = newDocument(); - document.set("mypk", document.getId(), CosmosItemSerializer.DEFAULT_SERIALIZER); + document.set("mypk", document.getId()); ItemBatchOperation itemBatchOperation = new ItemBatchOperation(CosmosItemOperationType.CREATE, documentCreated.getId(), new PartitionKey(documentCreated.getId()), new RequestOptions(), document); List> itemBatchOperations = new ArrayList<>(); @@ -318,7 +317,7 @@ public void sessionTokenNotRequired(boolean isNameBased) { RequestOptions requestOptions = new RequestOptions(); for (int i = 0; i < 10; i++) { Document document = newDocument(); - document.set("mypk", document.getId(), CosmosItemSerializer.DEFAULT_SERIALIZER); + document.set("mypk", document.getId()); requestOptions.setPartitionKey(new PartitionKey(document.getId())); documentCreated = spyClient.createDocument(getCollectionLink(isNameBased), document, requestOptions, false) .block().getResource(); @@ -373,7 +372,7 @@ public void sessionTokenForCreateOnMultiMaster(boolean isNameBased) { RequestOptions requestOptions = new RequestOptions(); for (int i = 0; i < 10; i++) { Document document = newDocument(); - document.set("mypk", document.getId(), CosmosItemSerializer.DEFAULT_SERIALIZER); + document.set("mypk", document.getId()); requestOptions.setPartitionKey(new PartitionKey(document.getId())); spyClient.createDocument(getCollectionLink(isNameBased), document, requestOptions, false) .block().getResource(); @@ -388,7 +387,7 @@ public void sessionTokenForCreateOnMultiMaster(boolean isNameBased) { public void sessionTokenInDocumentRead(boolean isNameBased) throws UnsupportedEncodingException { Document document = new Document(); document.setId(UUID.randomUUID().toString()); - document.set("pk", "pk", CosmosItemSerializer.DEFAULT_SERIALIZER); + document.set("pk", "pk"); document = spyClient.createDocument(getCollectionLink(isNameBased), document, null, false) .block() .getResource(); diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/ThinClientStoreModelTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/ThinClientStoreModelTest.java index f53393b6ef90..64cd7fe37115 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/ThinClientStoreModelTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/ThinClientStoreModelTest.java @@ -2,7 +2,7 @@ import com.azure.cosmos.ConsistencyLevel; import com.azure.cosmos.implementation.http.HttpClient; -import com.azure.cosmos.implementation.routing.LocationCache; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; import io.netty.channel.ConnectTimeoutException; import org.mockito.Mockito; import org.testng.annotations.Test; @@ -30,7 +30,7 @@ public void testThinClientStoreModel() throws Exception { GlobalEndpointManager globalEndpointManager = Mockito.mock(GlobalEndpointManager.class); - Mockito.doReturn(new LocationCache.ConsolidatedRegionalEndpoint(new URI("https://localhost"), null)) + Mockito.doReturn(new RegionalRoutingContext(new URI("https://localhost:8080"))) .when(globalEndpointManager).resolveServiceEndpoint(any()); // mocking with HTTP/1.1 client, just using this test as basic store model validation. e2e request flow diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/ThinClientTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/ThinClientTest.java index d2e7d6aeac8e..0dedcce9fb32 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/ThinClientTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/ThinClientTest.java @@ -16,9 +16,9 @@ public void testThinclientHttp2() { try { //String thinclientEndpoint = "https://cdb-ms-stage-eastus2-fe2.eastus2.cloudapp.azure.com:10650"; //String thinclientEndpoint = "https://chukangzhongstagesignoff.documents-staging.windows-ppe.net:443/"; - System.setProperty(Configs.THINCLIENT_ENABLED, "true"); + System.setProperty("COSMOS.THINCLIENT_ENABLED", "true"); //System.setProperty(Configs.THINCLIENT_ENDPOINT, thinclientEndpoint); - System.setProperty(Configs.HTTP2_ENABLED, "true"); + System.setProperty("COSMOS.HTTP2_ENABLED", "true"); CosmosAsyncClient client = new CosmosClientBuilder() .key(TestConfigurations.MASTER_KEY) @@ -40,7 +40,6 @@ public void testThinclientHttp2() { container.readItem(testItem.getId(), new PartitionKey(testItem.getId()), JsonNode.class).block();*/ } finally { System.clearProperty(Configs.THINCLIENT_ENABLED); - System.clearProperty(Configs.THINCLIENT_ENDPOINT); System.clearProperty(Configs.HTTP2_ENABLED); } diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/UtilsTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/UtilsTest.java index 8ba83bcd8497..0ed8473cd80a 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/UtilsTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/UtilsTest.java @@ -5,8 +5,10 @@ import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.apachecommons.lang.RandomStringUtils; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationConfig; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.module.afterburner.AfterburnerModule; import com.fasterxml.jackson.module.blackbird.BlackbirdModule; @@ -116,4 +118,51 @@ public void allowUnquotedControlChars() { assertThat(Utils.shouldAllowUnquotedControlChars()).isFalse(); System.clearProperty("COSMOS.ALLOW_UNQUOTED_CONTROL_CHARS"); } + + @Test(groups = { "unit" }) + public void serializationInclusionMode() { + assertThat( + Utils + .getDocumentObjectMapper(null) + .getSerializationConfig() + .getDefaultPropertyInclusion()) + .isEqualTo( + JsonInclude.Value.construct(JsonInclude.Include.USE_DEFAULTS, JsonInclude.Include.USE_DEFAULTS)); + + assertThat( + Utils + .getDocumentObjectMapper("") + .getSerializationConfig() + .getDefaultPropertyInclusion()) + .isEqualTo( + JsonInclude.Value.construct(JsonInclude.Include.USE_DEFAULTS, JsonInclude.Include.USE_DEFAULTS)); + assertThat( + Utils + .getDocumentObjectMapper("aLWayS") + .getSerializationConfig() + .getDefaultPropertyInclusion()) + .isEqualTo( + JsonInclude.Value.construct(JsonInclude.Include.ALWAYS, JsonInclude.Include.ALWAYS)); + assertThat( + Utils + .getDocumentObjectMapper("nONnull") + .getSerializationConfig() + .getDefaultPropertyInclusion()) + .isEqualTo( + JsonInclude.Value.construct(JsonInclude.Include.NON_NULL, JsonInclude.Include.NON_NULL)); + assertThat( + Utils + .getDocumentObjectMapper("nONEMPTY") + .getSerializationConfig() + .getDefaultPropertyInclusion()) + .isEqualTo( + JsonInclude.Value.construct(JsonInclude.Include.NON_EMPTY, JsonInclude.Include.NON_EMPTY)); + assertThat( + Utils + .getDocumentObjectMapper("NonDefault") + .getSerializationConfig() + .getDefaultPropertyInclusion()) + .isEqualTo( + JsonInclude.Value.construct(JsonInclude.Include.NON_DEFAULT, JsonInclude.Include.NON_DEFAULT)); + } } diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/WebExceptionRetryPolicyTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/WebExceptionRetryPolicyTest.java index f576126daca6..41db724bf295 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/WebExceptionRetryPolicyTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/WebExceptionRetryPolicyTest.java @@ -5,7 +5,7 @@ import com.azure.cosmos.BridgeInternal; import com.azure.cosmos.CosmosException; -import com.azure.cosmos.implementation.routing.LocationCache; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; import io.netty.handler.timeout.ReadTimeoutException; import io.reactivex.subscribers.TestSubscriber; import org.mockito.Mockito; @@ -38,7 +38,10 @@ public static Object[][] operationTypeProvider() { @Test(groups = {"unit"}) public void shouldRetryOnTimeoutForReadOperations() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); - Mockito.doReturn(new LocationCache.ConsolidatedRegionalEndpoint(new URI("http://localhost:"), null)).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); + + RegionalRoutingContext regionalRoutingContext = new RegionalRoutingContext(new URI("http://localhost:")); + + Mockito.doReturn(regionalRoutingContext).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(true)); RetryContext retryContext = new RetryContext(); @@ -53,6 +56,7 @@ public void shouldRetryOnTimeoutForReadOperations() throws Exception { //Default HttpTimeout Policy dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Read, "/dbs/db/colls/col/docs/doc", ResourceType.Document); + dsr.requestContext.regionalRoutingContextToRoute = regionalRoutingContext; // 1st Attempt webExceptionRetryPolicy.onBeforeSendRequest(dsr); @@ -90,7 +94,10 @@ public void shouldRetryOnTimeoutForReadOperations() throws Exception { @Test(groups = {"unit"}) public void shouldRetryOnTimeoutForMetaDataReadOperations() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); - Mockito.doReturn(new LocationCache.ConsolidatedRegionalEndpoint(new URI("http://localhost:"), null)).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); + + RegionalRoutingContext regionalRoutingContext = new RegionalRoutingContext(new URI("http://localhost:")); + + Mockito.doReturn(regionalRoutingContext).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(true)); RetryContext retryContext = new RetryContext(); @@ -105,6 +112,7 @@ public void shouldRetryOnTimeoutForMetaDataReadOperations() throws Exception { //Default HttpTimeout Policy dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Read, "/dbs/db", ResourceType.DatabaseAccount); + dsr.requestContext.regionalRoutingContextToRoute = regionalRoutingContext; // 1st Attempt webExceptionRetryPolicy.onBeforeSendRequest(dsr); @@ -144,7 +152,10 @@ public void shouldRetryOnTimeoutForMetaDataReadOperations() throws Exception { @Test(groups = {"unit"}) public void shouldRetryOnTimeoutForQueryPlanOperations() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); - Mockito.doReturn(new LocationCache.ConsolidatedRegionalEndpoint(new URI("http://localhost:"), null)).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); + + RegionalRoutingContext regionalRoutingContext = new RegionalRoutingContext(new URI("http://localhost:")); + + Mockito.doReturn(regionalRoutingContext).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(true)); RetryContext retryContext = new RetryContext(); @@ -159,6 +170,7 @@ public void shouldRetryOnTimeoutForQueryPlanOperations() throws Exception { //Default HttpTimeout Policy dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.QueryPlan, "/dbs/db/colls/col/docs/doc", ResourceType.Document); + dsr.requestContext.regionalRoutingContextToRoute = regionalRoutingContext; // 1st Attempt webExceptionRetryPolicy.onBeforeSendRequest(dsr); @@ -196,7 +208,10 @@ public void shouldRetryOnTimeoutForQueryPlanOperations() throws Exception { @Test(groups = "unit") public void shouldNotRetryOnTimeoutForWriteOperations() throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); - Mockito.doReturn(new LocationCache.ConsolidatedRegionalEndpoint(new URI("http://localhost:"), null)).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); + + RegionalRoutingContext regionalRoutingContext = new RegionalRoutingContext(new URI("http://localhost:")); + + Mockito.doReturn(regionalRoutingContext).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(true)); @@ -210,6 +225,7 @@ public void shouldNotRetryOnTimeoutForWriteOperations() throws Exception { //Data Plane Write - Should not retry dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Create, "/dbs/db/colls/col/docs/doc", ResourceType.Document); + dsr.requestContext.regionalRoutingContextToRoute = regionalRoutingContext; WebExceptionRetryPolicy webExceptionRetryPolicy = new WebExceptionRetryPolicy(new RetryContext()); webExceptionRetryPolicy.onBeforeSendRequest(dsr); @@ -223,6 +239,7 @@ public void shouldNotRetryOnTimeoutForWriteOperations() throws Exception { //Metadata Write - Should not Retry dsr = RxDocumentServiceRequest.createFromName(mockDiagnosticsClientContext(), OperationType.Create, "/dbs/db", ResourceType.DatabaseAccount); + dsr.requestContext.regionalRoutingContextToRoute = regionalRoutingContext; webExceptionRetryPolicy = new WebExceptionRetryPolicy(new RetryContext()); webExceptionRetryPolicy.onBeforeSendRequest(dsr); @@ -237,7 +254,10 @@ public void shouldNotRetryOnTimeoutForWriteOperations() throws Exception { @Test(groups = "unit", dataProvider = "operationTypeProvider") public void httpNetworkFailureOnAddressRefresh(OperationType operationType) throws Exception { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); - Mockito.doReturn(new LocationCache.ConsolidatedRegionalEndpoint(new URI("http://localhost:"), null)).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); + + RegionalRoutingContext regionalRoutingContext = new RegionalRoutingContext(new URI("http://localhost:")); + + Mockito.doReturn(regionalRoutingContext).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null), Mockito.eq(false)); Mockito.doReturn(2).when(endpointManager).getPreferredLocationCount(); @@ -251,6 +271,7 @@ public void httpNetworkFailureOnAddressRefresh(OperationType operationType) thro operationType, "/dbs/db/colls/col/docs/", ResourceType.Document); dsr.setAddressRefresh(true, false); dsr.requestContext = new DocumentServiceRequestContext(); + dsr.requestContext.regionalRoutingContextToRoute = regionalRoutingContext; // 1st Attempt webExceptionRetryPolicy.onBeforeSendRequest(dsr); diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/batch/BatchResponsePayloadWriter.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/batch/BatchResponsePayloadWriter.java index 03d5342edb59..a3d0c91bd633 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/batch/BatchResponsePayloadWriter.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/batch/BatchResponsePayloadWriter.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation.batch; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.JsonSerializable; import com.azure.cosmos.implementation.Utils; import com.azure.cosmos.models.CosmosBatchOperationResult; @@ -37,13 +36,13 @@ private ArrayNode writeOperationResult() { private JsonSerializable writeResult(CosmosBatchOperationResult result) { JsonSerializable jsonSerializable = new JsonSerializable(); - jsonSerializable.set(BatchRequestResponseConstants.FIELD_STATUS_CODE, result.getStatusCode(), CosmosItemSerializer.DEFAULT_SERIALIZER); - jsonSerializable.set(BatchRequestResponseConstants.FIELD_SUBSTATUS_CODE, result.getSubStatusCode(), CosmosItemSerializer.DEFAULT_SERIALIZER); - jsonSerializable.set(BatchRequestResponseConstants.FIELD_ETAG, result.getETag(), CosmosItemSerializer.DEFAULT_SERIALIZER); - jsonSerializable.set(BatchRequestResponseConstants.FIELD_REQUEST_CHARGE, result.getRequestCharge(), CosmosItemSerializer.DEFAULT_SERIALIZER); + jsonSerializable.set(BatchRequestResponseConstants.FIELD_STATUS_CODE, result.getStatusCode()); + jsonSerializable.set(BatchRequestResponseConstants.FIELD_SUBSTATUS_CODE, result.getSubStatusCode()); + jsonSerializable.set(BatchRequestResponseConstants.FIELD_ETAG, result.getETag()); + jsonSerializable.set(BatchRequestResponseConstants.FIELD_REQUEST_CHARGE, result.getRequestCharge()); if(result.getRetryAfterDuration() != null) { - jsonSerializable.set(BatchRequestResponseConstants.FIELD_RETRY_AFTER_MILLISECONDS, result.getRetryAfterDuration().toMillis(), CosmosItemSerializer.DEFAULT_SERIALIZER); + jsonSerializable.set(BatchRequestResponseConstants.FIELD_RETRY_AFTER_MILLISECONDS, result.getRetryAfterDuration().toMillis()); } return jsonSerializable; diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/batch/PartitionKeyRangeServerBatchRequestTests.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/batch/PartitionKeyRangeServerBatchRequestTests.java index 4faf0f6b9fd5..19e67f4fbee6 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/batch/PartitionKeyRangeServerBatchRequestTests.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/batch/PartitionKeyRangeServerBatchRequestTests.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation.batch; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.JsonSerializable; import com.azure.cosmos.implementation.apachecommons.lang.StringUtils; import com.azure.cosmos.models.CosmosItemOperation; @@ -155,7 +154,7 @@ private static ServerOperationBatchRequest getBatchWithCreateOperationsAsync( for (int i = 0; i < operationCount; i++) { JsonSerializable jsonSerializable = new JsonSerializable(); - jsonSerializable.set("abc", StringUtils.repeat("x", docSizeInBytes - 10), CosmosItemSerializer.DEFAULT_SERIALIZER);// {"abc":" + "} = 10 + jsonSerializable.set("abc", StringUtils.repeat("x", docSizeInBytes - 10));// {"abc":" + "} = 10 ItemBulkOperation operation = new ItemBulkOperation<>( CosmosItemOperationType.CREATE, diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/changefeed/epkversion/BootstrapperImplTests.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/changefeed/epkversion/BootstrapperImplTests.java index 7edebd7db426..2ba3744896bd 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/changefeed/epkversion/BootstrapperImplTests.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/changefeed/epkversion/BootstrapperImplTests.java @@ -10,8 +10,10 @@ import com.azure.cosmos.implementation.changefeed.common.ChangeFeedStartFromInternal; import com.azure.cosmos.implementation.changefeed.common.ChangeFeedState; import com.azure.cosmos.implementation.changefeed.common.ChangeFeedStateV1; +import com.azure.cosmos.implementation.changefeed.pkversion.ServiceItemLease; import com.azure.cosmos.implementation.feedranges.FeedRangeContinuation; import com.azure.cosmos.implementation.feedranges.FeedRangePartitionKeyRangeImpl; +import com.azure.cosmos.models.ChangeFeedProcessorOptions; import org.mockito.Mockito; import org.testng.Assert; import org.testng.annotations.DataProvider; @@ -21,11 +23,12 @@ import java.time.Duration; +import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.times; public class BootstrapperImplTests { - private static final String baseContinuationStringForFullRange = "{\"V\":1," + + private static final String BASE_CONTINUATION_STRING_FOR_EPK_FULL_RANGE = "{\"V\":1," + "\"Rid\":\"%s\"," + "\"Continuation\":[" + "{\"token\":\"%s\",\"range\":{\"min\":\"\",\"max\":\"FF\"}}" + @@ -34,9 +37,12 @@ public class BootstrapperImplTests { @DataProvider(name = "leaseProvider") public Object[][] leaseProvider() { + + String BASE_CONTINUATION_STRING_FOR_PK_FULL_RANGE = "\"100\""; + return new Object[][] { { - createLeaseWithContinuation( + createEpkRangeBasedLeaseWithContinuation( true, ChangeFeedMode.FULL_FIDELITY, ChangeFeedStartFromInternal.createFromNow(), @@ -45,10 +51,11 @@ public Object[][] leaseProvider() { "0", "-FF", "0"), + null, false }, { - createLeaseWithContinuation( + createEpkRangeBasedLeaseWithContinuation( true, ChangeFeedMode.INCREMENTAL, ChangeFeedStartFromInternal.createFromNow(), @@ -57,10 +64,11 @@ public Object[][] leaseProvider() { "0", "-FF", "0"), + null, true }, { - createLeaseWithContinuation( + createEpkRangeBasedLeaseWithContinuation( false, ChangeFeedMode.INCREMENTAL, ChangeFeedStartFromInternal.createFromNow(), @@ -69,10 +77,11 @@ public Object[][] leaseProvider() { "0", "-FF", "0"), + null, false }, { - createLeaseWithContinuation( + createEpkRangeBasedLeaseWithContinuation( false, ChangeFeedMode.FULL_FIDELITY, ChangeFeedStartFromInternal.createFromNow(), @@ -81,13 +90,51 @@ public Object[][] leaseProvider() { "0", "-FF", "0"), + null, + false + }, + { + createEpkRangeBasedLeaseWithContinuation( + true, + ChangeFeedMode.FULL_FIDELITY, + ChangeFeedStartFromInternal.createFromNow(), + "XyJKUI7=", + "NO67Hq=", + "0", + "-FF", + "0"), + createPkRangeBasedLeaseWithContinuation( + true, + "XyJKUI7=", + "NO67Hq=", + "-FF", + BASE_CONTINUATION_STRING_FOR_PK_FULL_RANGE), + true + }, + { + null, + createPkRangeBasedLeaseWithContinuation( + true, + "XyJKUI7=", + "NO67Hq=", + "-FF", + BASE_CONTINUATION_STRING_FOR_PK_FULL_RANGE), + true + }, + { + null, + null, false } }; } @Test(groups = {"unit"}, dataProvider = "leaseProvider") - public void tryInitializeStoreFromEpkVersionLeaseStoreWithExistingLeases(ServiceItemLeaseV1 lease, boolean expectIllegalStateException) { + public void tryInitializeStoreFromEpkVersionLeaseStoreWithExistingLeases( + ServiceItemLeaseV1 epkRangeBasedLease, + ServiceItemLease pkRangeBasedLease, + boolean expectIllegalStateException) { + Duration lockTime = Duration.ofSeconds(5); Duration expireTIme = Duration.ofSeconds(5); @@ -104,13 +151,30 @@ public void tryInitializeStoreFromEpkVersionLeaseStoreWithExistingLeases(Service Mockito.when(leaseStoreMock.releaseInitializationLock()).thenReturn(Mono.empty()); LeaseStoreManager epkRangeVersionLeaseStoreManagerMock = Mockito.mock(LeaseStoreManager.class); - Mockito.when(epkRangeVersionLeaseStoreManagerMock.getTopLeases(Mockito.eq(1))).thenReturn(Flux.just(lease)); + LeaseStoreManager pkRangeVersionLeaseStoreManagerMock = Mockito.mock(LeaseStoreManager.class); + + ChangeFeedProcessorOptions changeFeedProcessorOptionsMock = Mockito.mock(ChangeFeedProcessorOptions.class); + + if (epkRangeBasedLease == null) { + Mockito.when(epkRangeVersionLeaseStoreManagerMock.getTopLeases(Mockito.eq(1))).thenReturn(Flux.empty()); + } else { + Mockito.when(epkRangeVersionLeaseStoreManagerMock.getTopLeases(Mockito.eq(1))).thenReturn(Flux.just(epkRangeBasedLease)); + } + + if (pkRangeBasedLease == null) { + Mockito.when(pkRangeVersionLeaseStoreManagerMock.getTopLeases(Mockito.eq(1))).thenReturn(Flux.empty()); + } else { + Mockito.when(pkRangeVersionLeaseStoreManagerMock.getTopLeases(Mockito.eq(1))).thenReturn(Flux.just(pkRangeBasedLease)); + } + Bootstrapper bootstrapper = new BootstrapperImpl( partitionSynchronizerMock, leaseStoreMock, lockTime, expireTIme, epkRangeVersionLeaseStoreManagerMock, + pkRangeVersionLeaseStoreManagerMock, + changeFeedProcessorOptionsMock, ChangeFeedMode.FULL_FIDELITY); if (expectIllegalStateException) { @@ -119,12 +183,17 @@ public void tryInitializeStoreFromEpkVersionLeaseStoreWithExistingLeases(Service bootstrapper.initialize().block(); } - Mockito.verify(epkRangeVersionLeaseStoreManagerMock, times(1)).getTopLeases(Mockito.eq(1)); + Mockito.verify(pkRangeVersionLeaseStoreManagerMock, times(1)).getTopLeases(Mockito.eq(1)); + + if (pkRangeBasedLease == null) { + Mockito.verify(epkRangeVersionLeaseStoreManagerMock, times(1)).getTopLeases(Mockito.eq(1)); + } + Mockito.verify(partitionSynchronizerMock, times(1)).createMissingLeases(); Mockito.verify(leaseStoreMock, times(2)).isInitialized(); } - private static ServiceItemLeaseV1 createLeaseWithContinuation( + private static ServiceItemLeaseV1 createEpkRangeBasedLeaseWithContinuation( boolean withContinuation, ChangeFeedMode changeFeedMode, ChangeFeedStartFromInternal startFromSettings, @@ -141,8 +210,9 @@ private static ServiceItemLeaseV1 createLeaseWithContinuation( if (withContinuation) { FeedRangePartitionKeyRangeImpl feedRangePartitionKeyRangeImpl = new FeedRangePartitionKeyRangeImpl(pkRangeId); + String continuationAsJsonString = String.format( - baseContinuationStringForFullRange, + BASE_CONTINUATION_STRING_FOR_EPK_FULL_RANGE, collectionRid, continuationToken, pkRangeId); @@ -161,4 +231,24 @@ private static ServiceItemLeaseV1 createLeaseWithContinuation( return lease; } + + private static ServiceItemLease createPkRangeBasedLeaseWithContinuation( + boolean withContinuation, + String databaseRid, + String collectionRid, + String leaseToken, + String continuationToken) { + + ServiceItemLease lease = new ServiceItemLease(); + + lease.setId(String.format("%s_%s..%s", databaseRid, collectionRid, leaseToken)); + + lease = lease.withLeaseToken(leaseToken); + + if (withContinuation) { + lease = lease.withContinuationToken(continuationToken); + } + + return lease; + } } diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/changefeed/epkversion/PkRangeIdVersionLeasesBootstrapperImplTests.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/changefeed/epkversion/PkRangeIdVersionLeasesBootstrapperImplTests.java index a4cbcdeaa9da..f93a40560e29 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/changefeed/epkversion/PkRangeIdVersionLeasesBootstrapperImplTests.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/changefeed/epkversion/PkRangeIdVersionLeasesBootstrapperImplTests.java @@ -12,6 +12,7 @@ import com.azure.cosmos.implementation.changefeed.common.ChangeFeedStateV1; import com.azure.cosmos.implementation.feedranges.FeedRangeContinuation; import com.azure.cosmos.implementation.feedranges.FeedRangePartitionKeyRangeImpl; +import com.azure.cosmos.models.ChangeFeedProcessorOptions; import org.mockito.Mockito; import org.testng.Assert; import org.testng.annotations.DataProvider; @@ -72,6 +73,11 @@ public void initializeStoreFromPkRangeIdVersionLeaseStore() { Mockito.when(partitionSynchronizerMock.createMissingLeases(Mockito.any())).thenReturn(Mono.empty()); LeaseStore leaseStoreMock = Mockito.mock(LeaseStore.class); + + ChangeFeedProcessorOptions changeFeedProcessorOptions = new ChangeFeedProcessorOptions(); + + changeFeedProcessorOptions.setLeasePrefix("testLease"); + Mockito .when(leaseStoreMock.isInitialized()) .thenReturn(Mono.just(false)) @@ -94,6 +100,7 @@ public void initializeStoreFromPkRangeIdVersionLeaseStore() { expireTIme, pkRangeIdVersionLeaseStoreManagerMock, epkRangeVersionLeaseStoreManagerMock, + changeFeedProcessorOptions, ChangeFeedMode.INCREMENTAL); bootstrapper.initialize().block(); @@ -114,6 +121,8 @@ public void initializeStoreFromScratch() { Duration expireTIme = Duration.ofSeconds(5); PartitionSynchronizer partitionSynchronizerMock = Mockito.mock(PartitionSynchronizer.class); + ChangeFeedProcessorOptions changeFeedProcessorOptionsMock = Mockito.mock(ChangeFeedProcessorOptions.class); + Mockito.when(partitionSynchronizerMock.createMissingLeases()).thenReturn(Mono.empty()); LeaseStore leaseStoreMock = Mockito.mock(LeaseStore.class); @@ -139,6 +148,7 @@ public void initializeStoreFromScratch() { expireTIme, pkRangeIdVersionLeaseStoreManagerMock, epkRangeVersionLeaseStoreManagerMock, + changeFeedProcessorOptionsMock, ChangeFeedMode.INCREMENTAL); bootstrapper.initialize().block(); @@ -156,6 +166,8 @@ public void tryInitializeStoreFromEpkVersionLeaseStoreWithExistingLeases(Service Duration expireTIme = Duration.ofSeconds(5); PartitionSynchronizer partitionSynchronizerMock = Mockito.mock(PartitionSynchronizer.class); + ChangeFeedProcessorOptions changeFeedProcessorOptions = new ChangeFeedProcessorOptions(); + Mockito.when(partitionSynchronizerMock.createMissingLeases(Mockito.any())).thenReturn(Mono.empty()); LeaseStore leaseStoreMock = Mockito.mock(LeaseStore.class); @@ -181,6 +193,7 @@ public void tryInitializeStoreFromEpkVersionLeaseStoreWithExistingLeases(Service expireTIme, pkRangeIdVersionLeaseStoreManagerMock, epkRangeVersionLeaseStoreManagerMock, + changeFeedProcessorOptions, ChangeFeedMode.INCREMENTAL); if (expectIllegalStateException) { diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/changefeed/pkversion/BootstrapperImplTests.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/changefeed/pkversion/BootstrapperImplTests.java new file mode 100644 index 000000000000..475498a264cd --- /dev/null +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/changefeed/pkversion/BootstrapperImplTests.java @@ -0,0 +1,179 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.cosmos.implementation.changefeed.pkversion; + +import com.azure.cosmos.implementation.changefeed.Bootstrapper; +import com.azure.cosmos.implementation.changefeed.Lease; +import com.azure.cosmos.implementation.changefeed.LeaseStore; +import com.azure.cosmos.implementation.changefeed.LeaseStoreManager; +import com.azure.cosmos.implementation.changefeed.common.ChangeFeedMode; +import com.azure.cosmos.implementation.changefeed.common.ChangeFeedStartFromInternal; +import com.azure.cosmos.implementation.changefeed.common.ChangeFeedState; +import com.azure.cosmos.implementation.changefeed.common.ChangeFeedStateV1; +import com.azure.cosmos.implementation.changefeed.epkversion.ServiceItemLeaseV1; +import com.azure.cosmos.implementation.feedranges.FeedRangeContinuation; +import com.azure.cosmos.implementation.feedranges.FeedRangePartitionKeyRangeImpl; +import com.azure.cosmos.models.ChangeFeedProcessorOptions; +import org.mockito.Mockito; +import org.testng.Assert; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.time.Duration; + +import static org.mockito.Mockito.times; + +public class BootstrapperImplTests { + + private static final String BASE_CONTINUATION_STRING_FOR_EPK_FULL_RANGE = "{\"V\":1," + + "\"Rid\":\"%s\"," + + "\"Continuation\":[" + + "{\"token\":\"%s\",\"range\":{\"min\":\"\",\"max\":\"FF\"}}" + + "]," + + "\"PKRangeId\":\"%s\"}"; + + @DataProvider(name = "leaseProvider") + public Object[][] leaseProvider() { + return new Object[][] { + { + createEpkRangeBasedLeaseWithContinuation( + true, + ChangeFeedMode.FULL_FIDELITY, + ChangeFeedStartFromInternal.createFromNow(), + "XyJKUI7=", + "NO67Hq=", + "0", + "-FF", + "0"), + true + }, + { + createEpkRangeBasedLeaseWithContinuation( + false, + ChangeFeedMode.FULL_FIDELITY, + ChangeFeedStartFromInternal.createFromNow(), + "XyJKUI7=", + "NO67Hq=", + "0", + "-FF", + "0"), + true + }, + { + createEpkRangeBasedLeaseWithContinuation( + true, + ChangeFeedMode.INCREMENTAL, + ChangeFeedStartFromInternal.createFromNow(), + "XyJKUI7=", + "NO67Hq=", + "0", + "-FF", + "0"), + true + }, + { + createEpkRangeBasedLeaseWithContinuation( + false, + ChangeFeedMode.INCREMENTAL, + ChangeFeedStartFromInternal.createFromNow(), + "XyJKUI7=", + "NO67Hq=", + "0", + "-FF", + "0"), + true, + }, + { + null, + false + } + }; + } + + @Test(groups = {"unit"}, dataProvider = "leaseProvider") + public void tryInitializeStoreFromPkVersionLeaseStoreWithExistingLeases(Lease lease, boolean expectIllegalStateException) { + Duration lockTime = Duration.ofSeconds(5); + Duration sleepTime = Duration.ofSeconds(5); + + PartitionSynchronizer partitionSynchronizerMock = Mockito.mock(PartitionSynchronizer.class); + Mockito.when(partitionSynchronizerMock.createMissingLeases()).thenReturn(Mono.empty()); + + ChangeFeedProcessorOptions changeFeedProcessorOptions = new ChangeFeedProcessorOptions(); + + LeaseStore leaseStoreMock = Mockito.mock(LeaseStore.class); + Mockito + .when(leaseStoreMock.isInitialized()) + .thenReturn(Mono.just(false)) + .thenReturn(Mono.just(true)); + Mockito.when(leaseStoreMock.acquireInitializationLock(lockTime)).thenReturn(Mono.just(true)); + Mockito.when(leaseStoreMock.markInitialized()).thenReturn(Mono.just(Boolean.TRUE)); + Mockito.when(leaseStoreMock.releaseInitializationLock()).thenReturn(Mono.empty()); + + LeaseStoreManager epkRangeVersionLeaseStoreManagerMock = Mockito.mock(LeaseStoreManager.class); + + if (lease != null) { + Mockito.when(epkRangeVersionLeaseStoreManagerMock.getTopLeases(Mockito.eq(1))).thenReturn(Flux.just(lease)); + } else { + Mockito.when(epkRangeVersionLeaseStoreManagerMock.getTopLeases(Mockito.eq(1))).thenReturn(Flux.empty()); + } + + Bootstrapper bootstrapper = new BootstrapperImpl( + partitionSynchronizerMock, + leaseStoreMock, + epkRangeVersionLeaseStoreManagerMock, + changeFeedProcessorOptions, + lockTime, + sleepTime); + + if (expectIllegalStateException) { + Assert.assertThrows(IllegalStateException.class, () -> bootstrapper.initialize().block()); + } else { + bootstrapper.initialize().block(); + } + + Mockito.verify(epkRangeVersionLeaseStoreManagerMock, times(1)).getTopLeases(Mockito.eq(1)); + Mockito.verify(partitionSynchronizerMock, times(1)).createMissingLeases(); + Mockito.verify(leaseStoreMock, times(2)).isInitialized(); + } + + private static ServiceItemLeaseV1 createEpkRangeBasedLeaseWithContinuation( + boolean withContinuation, + ChangeFeedMode changeFeedMode, + ChangeFeedStartFromInternal startFromSettings, + String databaseRid, + String collectionRid, + String pkRangeId, + String leaseToken, + String continuationToken) { + + ServiceItemLeaseV1 lease = new ServiceItemLeaseV1(); + + lease.setId(String.format("%s_%s..%s", databaseRid, collectionRid, leaseToken)); + lease = lease.withLeaseToken(leaseToken); + + if (withContinuation) { + FeedRangePartitionKeyRangeImpl feedRangePartitionKeyRangeImpl = new FeedRangePartitionKeyRangeImpl(pkRangeId); + String continuationAsJsonString = String.format( + BASE_CONTINUATION_STRING_FOR_EPK_FULL_RANGE, + collectionRid, + continuationToken, + pkRangeId); + + FeedRangeContinuation feedRangeContinuation = FeedRangeContinuation.convert(continuationAsJsonString); + + ChangeFeedState changeFeedState = new ChangeFeedStateV1( + collectionRid, + feedRangePartitionKeyRangeImpl, + changeFeedMode, + startFromSettings, + feedRangeContinuation); + + lease.setContinuationToken(changeFeedState.toString()); + } + + return lease; + } +} diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/ConnectionStateListenerTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/ConnectionStateListenerTest.java index d41b688ded2e..97f86bb795d3 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/ConnectionStateListenerTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/ConnectionStateListenerTest.java @@ -26,6 +26,7 @@ import com.azure.cosmos.implementation.directconnectivity.rntbd.RntbdEndpoint; import com.azure.cosmos.implementation.directconnectivity.rntbd.RntbdRequestManager; import com.azure.cosmos.implementation.routing.PartitionKeyRangeIdentity; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; import io.netty.handler.ssl.SslContext; import org.mockito.Mockito; import org.slf4j.Logger; @@ -34,6 +35,8 @@ import org.testng.annotations.Test; import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; import java.nio.channels.ClosedChannelException; import java.util.ArrayList; import java.util.Arrays; @@ -85,7 +88,7 @@ public void connectionStateListener_OnConnectionEvent( boolean isTcpConnectionEndpointRediscoveryEnabled, RequestResponseType responseType, boolean markUnhealthy, - boolean markUnhealthyWhenServerShutdown) throws ExecutionException, InterruptedException { + boolean markUnhealthyWhenServerShutdown) throws ExecutionException, InterruptedException, URISyntaxException { ConnectionPolicy connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig()); connectionPolicy.setTcpConnectionEndpointRediscoveryEnabled(isTcpConnectionEndpointRediscoveryEnabled); @@ -124,6 +127,8 @@ public void connectionStateListener_OnConnectionEvent( RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Create, ResourceType.Document, "dbs/fakedb/colls/fakeColls", getDocumentDefinition(), new HashMap<>()); + req.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(new URI("https://localhost:8080")); + req.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity("fakeCollectionId","fakePartitionKeyRangeId")); // Validate connectionStateListener will always track the latest Uri diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/DCDocumentCrudTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/DCDocumentCrudTest.java index d3383227620e..77d68acb18bd 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/DCDocumentCrudTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/DCDocumentCrudTest.java @@ -2,12 +2,9 @@ // Licensed under the MIT License. package com.azure.cosmos.implementation.directconnectivity; -import com.azure.cosmos.BridgeInternal; import com.azure.cosmos.ConsistencyLevel; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.DirectConnectionConfig; import com.azure.cosmos.implementation.AsyncDocumentClient.Builder; -import com.azure.cosmos.implementation.ImplementationBridgeHelpers; import com.azure.cosmos.implementation.TestUtils; import com.azure.cosmos.implementation.clienttelemetry.ClientTelemetry; import com.azure.cosmos.models.CosmosClientTelemetryConfig; @@ -198,7 +195,7 @@ public void upsert() throws Exception { String propName = "newProp"; String propValue = "hello"; - document.set(propName, propValue, CosmosItemSerializer.DEFAULT_SERIALIZER); + document.set(propName, propValue); ResourceResponseValidator validator = ResourceResponseValidator.builder() .withProperty(propName, propValue) @@ -329,8 +326,8 @@ private String getCollectionLink() { private Document getDocumentDefinition() { Document doc = new Document(); doc.setId(UUID.randomUUID().toString()); - doc.set(PARTITION_KEY_FIELD_NAME, UUID.randomUUID().toString(), CosmosItemSerializer.DEFAULT_SERIALIZER); - doc.set("name", "Hafez", CosmosItemSerializer.DEFAULT_SERIALIZER); + doc.set(PARTITION_KEY_FIELD_NAME, UUID.randomUUID().toString()); + doc.set("name", "Hafez"); return doc; } diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/GlobalAddressResolverTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/GlobalAddressResolverTest.java index 483adfe5e328..331be53cc7af 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/GlobalAddressResolverTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/GlobalAddressResolverTest.java @@ -11,7 +11,6 @@ import com.azure.cosmos.implementation.ConnectionPolicy; import com.azure.cosmos.implementation.DocumentCollection; import com.azure.cosmos.implementation.GlobalEndpointManager; -import com.azure.cosmos.implementation.circuitBreaker.GlobalPartitionEndpointManagerForCircuitBreaker; import com.azure.cosmos.implementation.IAuthorizationTokenProvider; import com.azure.cosmos.implementation.OpenConnectionResponse; import com.azure.cosmos.implementation.OperationType; @@ -25,9 +24,9 @@ import com.azure.cosmos.implementation.caches.RxCollectionCache; import com.azure.cosmos.implementation.caches.RxPartitionKeyRangeCache; import com.azure.cosmos.implementation.http.HttpClient; -import com.azure.cosmos.implementation.routing.LocationCache; import com.azure.cosmos.implementation.routing.PartitionKeyInternalHelper; import com.azure.cosmos.implementation.routing.PartitionKeyRangeIdentity; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; import com.azure.cosmos.models.CosmosContainerIdentity; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; @@ -79,17 +78,17 @@ public void before_GlobalAddressResolverTest() throws Exception { httpClient = Mockito.mock(HttpClient.class); endpointManager = Mockito.mock(GlobalEndpointManager.class); - List readEndPointList = new ArrayList<>(); - readEndPointList.add(new LocationCache.ConsolidatedRegionalEndpoint(urlforRead1, null)); - readEndPointList.add(new LocationCache.ConsolidatedRegionalEndpoint(urlforRead2, null)); - readEndPointList.add(new LocationCache.ConsolidatedRegionalEndpoint(urlforRead3, null)); - UnmodifiableList readList = new UnmodifiableList<>(readEndPointList); + List readEndPointList = new ArrayList<>(); + readEndPointList.add(new RegionalRoutingContext(urlforRead1)); + readEndPointList.add(new RegionalRoutingContext(urlforRead2)); + readEndPointList.add(new RegionalRoutingContext(urlforRead3)); + UnmodifiableList readList = new UnmodifiableList<>(readEndPointList); - List writeEndPointList = new ArrayList<>(); - writeEndPointList.add(new LocationCache.ConsolidatedRegionalEndpoint(urlforWrite1, null)); - writeEndPointList.add(new LocationCache.ConsolidatedRegionalEndpoint(urlforWrite2, null)); - writeEndPointList.add(new LocationCache.ConsolidatedRegionalEndpoint(urlforWrite3, null)); - UnmodifiableList writeList = new UnmodifiableList<>(writeEndPointList); + List writeEndPointList = new ArrayList<>(); + writeEndPointList.add(new RegionalRoutingContext(urlforWrite1)); + writeEndPointList.add(new RegionalRoutingContext(urlforWrite2)); + writeEndPointList.add(new RegionalRoutingContext(urlforWrite3)); + UnmodifiableList writeList = new UnmodifiableList<>(writeEndPointList); Mockito.when(endpointManager.getReadEndpoints()).thenReturn(readList); Mockito.when(endpointManager.getWriteEndpoints()).thenReturn(writeList); @@ -123,13 +122,13 @@ public void resolveAsync() throws Exception { assertThat(urlsBeforeResolve.contains(urlforRead3)).isFalse();//Last read will be removed from addressCacheByEndpoint after 5 endpoints assertThat(urlsBeforeResolve.contains(urlforRead2)).isTrue(); - LocationCache.ConsolidatedRegionalEndpoint testUrl = new LocationCache.ConsolidatedRegionalEndpoint(new URI("http://Test.com/"), null); + RegionalRoutingContext testUrl = new RegionalRoutingContext(new URI("http://Test.com/")); Mockito.when(endpointManager.resolveServiceEndpoint(ArgumentMatchers.any())).thenReturn(testUrl); globalAddressResolver.resolveAsync(request, true); Set urlsAfterResolve = globalAddressResolver.addressCacheByEndpoint.keySet(); assertThat(urlsAfterResolve.size()).isEqualTo(5); assertThat(urlsAfterResolve.contains(urlforRead2)).isFalse();//Last read will be removed from addressCacheByEndpoint after 5 endpoints - assertThat(urlsBeforeResolve.contains(testUrl.getGatewayLocationEndpoint())).isTrue();//New endpoint will be added in addressCacheByEndpoint + assertThat(urlsBeforeResolve.contains(testUrl.getGatewayRegionalEndpoint())).isTrue();//New endpoint will be added in addressCacheByEndpoint } @Test(groups = "unit") @@ -159,7 +158,7 @@ public void submitOpenConnectionTasksAndInitCaches() { Mockito .when(endpointManager.getReadEndpoints()) .thenReturn(new UnmodifiableList<>( - Arrays.asList(new LocationCache.ConsolidatedRegionalEndpoint(urlforRead1, null), new LocationCache.ConsolidatedRegionalEndpoint(urlforRead2, null)))); + Arrays.asList(new RegionalRoutingContext(urlforRead1), new RegionalRoutingContext(urlforRead2)))); DocumentCollection documentCollection = new DocumentCollection(); documentCollection.setId("TestColl"); diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/GlobalEndPointManagerTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/GlobalEndPointManagerTest.java index 85433c8cbb82..734a3695a2c9 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/GlobalEndPointManagerTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/GlobalEndPointManagerTest.java @@ -11,6 +11,7 @@ import com.azure.cosmos.implementation.GlobalEndpointManager; import com.azure.cosmos.implementation.LifeCycleUtils; import com.azure.cosmos.implementation.routing.LocationCache; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import org.testng.Assert; @@ -99,7 +100,7 @@ public void refreshLocationAsyncForConnectivityIssue() throws Exception { LocationCache locationCache = this.getLocationCache(globalEndPointManager); Assert.assertEquals(locationCache.getReadEndpoints().size(), 2, "Read endpoints should have 2 values"); - Map availableReadEndpointByLocation = this.getAvailableReadEndpointByLocation(locationCache); + Map availableReadEndpointByLocation = this.getAvailableReadEndpointByLocation(locationCache); Assert.assertEquals(availableReadEndpointByLocation.size(), 2); Assert.assertTrue(availableReadEndpointByLocation.keySet().contains("East Asia")); @@ -155,7 +156,7 @@ public void refreshLocationAsyncForConnectivityIssueWithPreferredRegions() throw locationCache = this.getLocationCache(globalEndPointManager); Assert.assertEquals(locationCache.getReadEndpoints().size(), 2); //Cache will not refresh immediately, other preferred region East Asia is still active - Map availableReadEndpointByLocation = this.getAvailableReadEndpointByLocation(locationCache); + Map availableReadEndpointByLocation = this.getAvailableReadEndpointByLocation(locationCache); Assert.assertEquals(availableReadEndpointByLocation.size(), 2); Assert.assertTrue(availableReadEndpointByLocation.keySet().iterator().next().equalsIgnoreCase("East Asia")); @@ -195,7 +196,7 @@ public void refreshLocationAsyncForWriteForbidden() throws Exception { LocationCache locationCache = this.getLocationCache(globalEndPointManager); Assert.assertEquals(locationCache.getReadEndpoints().size(), 1); - Map availableWriteEndpointByLocation = this.getAvailableWriteEndpointByLocation(locationCache); + Map availableWriteEndpointByLocation = this.getAvailableWriteEndpointByLocation(locationCache); Assert.assertTrue(availableWriteEndpointByLocation.keySet().contains("East Asia")); AtomicBoolean isRefreshing = getIsRefreshing(globalEndPointManager); @@ -261,7 +262,7 @@ public void startRefreshLocationTimerAsync() throws Exception { LocationCache locationCache = this.getLocationCache(globalEndPointManager); Assert.assertEquals(locationCache.getReadEndpoints().size(), 1); - Map availableReadEndpointByLocation = this.getAvailableReadEndpointByLocation(locationCache); + Map availableReadEndpointByLocation = this.getAvailableReadEndpointByLocation(locationCache); Assert.assertEquals(availableReadEndpointByLocation.size(), 1); Assert.assertTrue(availableReadEndpointByLocation.keySet().iterator().next().equalsIgnoreCase("East Asia")); @@ -290,7 +291,7 @@ private LocationCache getLocationCache(GlobalEndpointManager globalEndPointManag return locationCache; } - private Map getAvailableWriteEndpointByLocation(LocationCache locationCache) throws Exception { + private Map getAvailableWriteEndpointByLocation(LocationCache locationCache) throws Exception { Field locationInfoField = LocationCache.class.getDeclaredField("locationInfo"); locationInfoField.setAccessible(true); Object locationInfo = locationInfoField.get(locationCache); @@ -302,11 +303,11 @@ private Map getAvailableWrit availableReadEndpointByLocationField.setAccessible(true); @SuppressWarnings("unchecked") - Map map = (Map) availableWriteEndpointByLocationField.get(locationInfo); + Map map = (Map) availableWriteEndpointByLocationField.get(locationInfo); return map; } - private Map getAvailableReadEndpointByLocation(LocationCache locationCache) throws Exception { + private Map getAvailableReadEndpointByLocation(LocationCache locationCache) throws Exception { Field locationInfoField = LocationCache.class.getDeclaredField("locationInfo"); locationInfoField.setAccessible(true); Object locationInfo = locationInfoField.get(locationCache); @@ -316,7 +317,7 @@ private Map getAvailableRead availableReadEndpointByLocationField.setAccessible(true); @SuppressWarnings("unchecked") - Map map = (Map) availableReadEndpointByLocationField.get(locationInfo); + Map map = (Map) availableReadEndpointByLocationField.get(locationInfo); return map; } @@ -353,8 +354,8 @@ private GlobalEndpointManager getGlobalEndPointManager() throws Exception { LocationCache locationCache = getLocationCache(globalEndPointManager); Assert.assertEquals(locationCache.getReadEndpoints().size(), 2, "Read endpoints should have 2 values"); - Map availableWriteEndpointByLocation = this.getAvailableWriteEndpointByLocation(locationCache); - Map availableReadEndpointByLocation = this.getAvailableReadEndpointByLocation(locationCache); + Map availableWriteEndpointByLocation = this.getAvailableWriteEndpointByLocation(locationCache); + Map availableReadEndpointByLocation = this.getAvailableReadEndpointByLocation(locationCache); Assert.assertEquals(availableWriteEndpointByLocation.size(), 1); Assert.assertEquals(availableReadEndpointByLocation.size(), 2); Assert.assertTrue(availableWriteEndpointByLocation.keySet().contains("East US")); diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/MetadataRequestRetryPolicyTests.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/MetadataRequestRetryPolicyTests.java index f2e08bb3c306..13b8cb738289 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/MetadataRequestRetryPolicyTests.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/MetadataRequestRetryPolicyTests.java @@ -32,7 +32,7 @@ import com.azure.cosmos.implementation.http.HttpClient; import com.azure.cosmos.implementation.http.HttpClientConfig; import com.azure.cosmos.implementation.http.HttpTimeoutPolicyControlPlaneHotPath; -import com.azure.cosmos.implementation.routing.LocationCache; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; import com.azure.cosmos.implementation.throughputControl.TestItem; import com.azure.cosmos.models.CosmosItemRequestOptions; import com.azure.cosmos.models.CosmosPatchOperations; @@ -235,14 +235,14 @@ public void forceBackgroundAddressRefresh_onConnectionTimeoutAndRequestCancellat GlobalAddressResolver globalAddressResolver = ReflectionUtils.getGlobalAddressResolver(asyncDocumentClient); GlobalEndpointManager globalEndpointManager = ReflectionUtils.getGlobalEndpointManager(asyncDocumentClient); - List readEndpoints = globalEndpointManager.getReadEndpoints(); + List readEndpoints = globalEndpointManager.getReadEndpoints(); Map endpointCacheByURIMap = globalAddressResolver.addressCacheByEndpoint; Map httpClientWrapperByRegionMap = new ConcurrentHashMap<>(); for (int i = 0; i < preferredRegions.size(); i++) { - URI readEndpoint = readEndpoints.get(i).getGatewayLocationEndpoint(); + URI readEndpoint = readEndpoints.get(i).getGatewayRegionalEndpoint(); GlobalAddressResolver.EndpointCache endpointCache = endpointCacheByURIMap.get(readEndpoint); GatewayAddressCache gatewayAddressCache = endpointCache.addressCache; HttpClientUnderTestWrapper httpClientUnderTestWrapper = getHttpClientUnderTestWrapper(configs); @@ -348,7 +348,7 @@ public void metadataRetryPolicyTest( .withException(cosmosException) .build()); - int desiredInvocationCount = request.requestContext.locationEndpointToRoute == null ? 0 : 1; + int desiredInvocationCount = request.requestContext.regionalRoutingContextToRoute == null ? 0 : 1; if (request.isReadOnlyRequest()) { Mockito @@ -554,10 +554,13 @@ private static RxDocumentServiceRequest createRequest( assert request.requestContext != null; + URI locationEndpointToRoute + = URI.create("https://account-name-some-region.documents.azure.com:443"); + if (hasLocationEndpointToRoute) { - request.requestContext.locationEndpointToRoute - = URI.create("https://account-name-some-region.documents.azure.com:443"); - request.requestContext.consolidatedRegionalEndpointToRoute = new LocationCache.ConsolidatedRegionalEndpoint(request.requestContext.locationEndpointToRoute, null); + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointToRoute); + } else { + request.setEndpointOverride(locationEndpointToRoute); } if (isAddressRefresh) { diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/PartitionKeyInternalTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/PartitionKeyInternalTest.java index a2ba04c389a2..427d8c763a7d 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/PartitionKeyInternalTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/PartitionKeyInternalTest.java @@ -4,6 +4,7 @@ package com.azure.cosmos.implementation.directconnectivity; import com.azure.cosmos.implementation.Utils; +import com.azure.cosmos.implementation.routing.HexConvert; import com.azure.cosmos.models.PartitionKey; import com.azure.cosmos.models.PartitionKeyDefinition; import com.azure.cosmos.models.PartitionKeyDefinitionVersion; @@ -288,18 +289,33 @@ public void hashEffectivePartitionKey() { assertThat(PartitionKeyInternalHelper.getEffectivePartitionKeyString(PartitionKeyInternal.InclusiveMinimum, new PartitionKeyDefinition())) .isEqualTo(PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey); + assertThat(PartitionKeyInternalHelper.getEffectivePartitionKeyBytes(PartitionKeyInternal.InclusiveMinimum, new PartitionKeyDefinition())) + .isEqualTo(PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKeyBytes); + assertThat( PartitionKeyInternalHelper.getEffectivePartitionKeyString(PartitionKeyInternal.ExclusiveMaximum, new PartitionKeyDefinition())) .isEqualTo(PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey); + assertThat( + PartitionKeyInternalHelper.getEffectivePartitionKeyBytes(PartitionKeyInternal.ExclusiveMaximum, new PartitionKeyDefinition())) + .isEqualTo(PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKeyBytes); + + PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); partitionKeyDefinition.setPaths(Lists.newArrayList("/A", "/B", "/C", "/E", "/F", "/G")); PartitionKeyInternal partitionKey = PartitionKeyInternal.fromObjectArray( new Object[]{2, true, false, null, Undefined.value(), "Привет!"}, true); - String effectivePartitionKey = PartitionKeyInternalHelper.getEffectivePartitionKeyString(partitionKey, partitionKeyDefinition); + String effectivePartitionKey = PartitionKeyInternalHelper + .getEffectivePartitionKeyString(partitionKey, partitionKeyDefinition); + + assertThat(effectivePartitionKey) + .isEqualTo("05C1D19581B37C05C0000302010008D1A0D281D1B9D1B3D1B6D2832200"); - assertThat(effectivePartitionKey).isEqualTo("05C1D19581B37C05C0000302010008D1A0D281D1B9D1B3D1B6D2832200"); + byte[] effectivePartitionKeyBytes = PartitionKeyInternalHelper + .getEffectivePartitionKeyBytes(partitionKey, partitionKeyDefinition); + assertThat(HexConvert.bytesToHex(effectivePartitionKeyBytes)) + .isEqualTo("05C1D19581B37C05C0000302010008D1A0D281D1B9D1B3D1B6D2832200"); } @DataProvider(name = "v2ParamProvider") diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/ReflectionUtils.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/ReflectionUtils.java index fd04c961143b..1f4ce8b2e6fb 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/ReflectionUtils.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/ReflectionUtils.java @@ -187,6 +187,13 @@ public static void setDiagnosticsProvider(CosmosAsyncClient cosmosAsyncClient, D set(cosmosAsyncClient, tracerProvider, "diagnosticsProvider"); } + public static DiagnosticsProvider getDiagnosticsProvider(CosmosAsyncClient cosmosAsyncClient){ + return get( + DiagnosticsProvider.class, + cosmosAsyncClient, + "diagnosticsProvider"); + } + public static void setClientTelemetryConfig(CosmosAsyncClient cosmosAsyncClient, CosmosClientTelemetryConfig cfg){ set(cosmosAsyncClient, cfg, "clientTelemetryConfig"); AsyncDocumentClient asyncClient = get( diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/RntbdTransportClientTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/RntbdTransportClientTest.java index 7d25deb33662..97c36e75cece 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/RntbdTransportClientTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/RntbdTransportClientTest.java @@ -61,6 +61,7 @@ import com.azure.cosmos.implementation.directconnectivity.rntbd.RntbdUUID; import com.azure.cosmos.implementation.guava25.base.Strings; import com.azure.cosmos.implementation.guava25.collect.ImmutableMap; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; import io.micrometer.core.instrument.Tag; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; @@ -839,7 +840,9 @@ public void cancelRequestMono() throws InterruptedException, URISyntaxException, ConnectionPolicy connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig()); RntbdTransportClient.Options options = new RntbdTransportClient.Options.Builder(connectionPolicy).build(); final SslContext sslContext = SslContextBuilder.forClient().build(); - request.requestContext.locationEndpointToRoute = locationToRoute; + + request.requestContext.regionalRoutingContextToRoute = new RegionalRoutingContext(locationToRoute); + RntbdRequestArgs requestArgs = new RntbdRequestArgs(request, addressUri); RntbdRequestTimer requestTimer = new RntbdRequestTimer(5000, 5000); RntbdRequestRecord rntbdRequestRecord = new AsyncRntbdRequestRecord(requestArgs, requestTimer); diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdTokenStreamTests.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdTokenStreamTests.java index 0ae8c3040ea1..397764e209e0 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdTokenStreamTests.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdTokenStreamTests.java @@ -1,84 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. package com.azure.cosmos.implementation.directconnectivity.rntbd; import com.azure.cosmos.implementation.HttpConstants; +import com.azure.cosmos.implementation.OperationType; +import com.azure.cosmos.implementation.ResourceType; import com.azure.cosmos.implementation.RxDocumentServiceRequest; -import com.azure.cosmos.implementation.ThinClientStoreModel; -import com.azure.cosmos.implementation.http.HttpHeaders; +import com.azure.cosmos.implementation.directconnectivity.Uri; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; -import org.apache.commons.io.FileUtils; -import org.mockito.Mockito; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.testng.annotations.Test; -import java.io.File; -import java.io.IOException; -import java.time.Instant; -import java.util.HashMap; -import java.util.Map; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.UUID; -import static com.azure.cosmos.implementation.directconnectivity.WFConstants.BackendHeaders.EFFECTIVE_PARTITION_KEY; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; public class RntbdTokenStreamTests { - // Created this test for thin client testing, to make sure thin client headers are always special cased - private static final Logger logger = LoggerFactory.getLogger(RntbdTokenStreamTests.class); - @Test - public void parseDotNet() { - //dumpFile("E:\\Temp\\dotnetRead.bin"); - //dumpFile("E:\\Temp\\javad6bd7634-35ed-44d3-849f-364456be3001.bin"); - - dumpFile("E:\\Temp\\dotnet_proxyInputRequest_Read_18.bin"); - dumpFile("E:\\Temp\\java_proxyInputRequest_Read_29.bin"); + private static final Random rnd = new Random(); + @Test(groups = { "unit" }) + public void noReorderingInDirectMode() { + List headerIds = createAndEncodeRequestHeaders(false); + assertThat(headerIds).isNotNull(); + assertThat(headerIds.size()).isEqualTo(6); + assertThat(headerIds.get(0)).isEqualTo(RntbdConstants.RntbdRequestHeader.PayloadPresent.id()); + assertThat(headerIds.get(1)).isEqualTo(RntbdConstants.RntbdRequestHeader.ReplicaPath.id()); + assertThat(headerIds.get(2)).isEqualTo(RntbdConstants.RntbdRequestHeader.TransportRequestID.id()); + assertThat(headerIds.get(3)).isEqualTo(RntbdConstants.RntbdRequestHeader.EffectivePartitionKey.id()); + assertThat(headerIds.get(4)).isEqualTo(RntbdConstants.RntbdRequestHeader.CorrelatedActivityId.id()); + assertThat(headerIds.get(5)).isEqualTo(RntbdConstants.RntbdRequestHeader.GlobalDatabaseAccountName.id()); } - private void dumpFile(String fileName) { - logger.error("FILENAME: {}", fileName); - File file = new File(fileName); - byte[] byteArray = null; - try { - byteArray = FileUtils.readFileToByteArray(file); - } catch (IOException e) { - e.printStackTrace(); - } + @Test(groups = { "unit" }) + public void withReorderingForThinClient() { + List headerIds = createAndEncodeRequestHeaders(true); + assertThat(headerIds).isNotNull(); + assertThat(headerIds.size()).isEqualTo(4); + assertThat(headerIds.get(0)).isEqualTo(RntbdConstants.RntbdRequestHeader.EffectivePartitionKey.id()); + assertThat(headerIds.get(1)).isEqualTo(RntbdConstants.RntbdRequestHeader.GlobalDatabaseAccountName.id()); + assertThat(headerIds.get(2)).isEqualTo(RntbdConstants.RntbdRequestHeader.PayloadPresent.id()); + assertThat(headerIds.get(3)).isEqualTo(RntbdConstants.RntbdRequestHeader.CorrelatedActivityId.id()); + } - ByteBuf content = Unpooled.wrappedBuffer(byteArray); + private static List createAndEncodeRequestHeaders(boolean forThinClient) { + UUID activityId = UUID.randomUUID(); + RxDocumentServiceRequest request = RxDocumentServiceRequest.create( + null, + OperationType.Create, + ResourceType.Document); - if (RntbdFramer.canDecodeHead(content)) { + String correlatedActivityId = UUID.randomUUID().toString(); + request.getHeaders().put( + HttpConstants.HttpHeaders.CORRELATED_ACTIVITY_ID, + correlatedActivityId + ); - final RntbdRequest request = RntbdRequest.decode(content); + request.getHeaders().put( + HttpConstants.HttpHeaders.GLOBAL_DATABASE_ACCOUNT_NAME, + "SomeAccount" + ); - if (request != null) { - logger.error("HEADERS: {}", request.getHeaders().dumpTokens()); - } + RntbdRequestFrame frame = new RntbdRequestFrame( + activityId, + RntbdConstants.RntbdOperationType.Create, + RntbdConstants.RntbdResourceType.Document); - logger.error("RNTBD REQUEST empty"); - } - } + RntbdRequestArgs args = new RntbdRequestArgs(request, new Uri("prefix://someUri")); - @Test(groups = { "unit" }) - public void testThinClientSpecialCasing() { - RxDocumentServiceRequest mockRequest = Mockito.mock(RxDocumentServiceRequest.class); - Map headers = new HashMap<>(); - headers.put(EFFECTIVE_PARTITION_KEY, "13A141365AE34002732EE6DD02677CFC"); - headers.put(HttpConstants.HttpHeaders.GLOBAL_DATABASE_ACCOUNT_NAME, "globalDatabaseAccountName"); - Mockito.doReturn(headers).when(mockRequest).getHeaders(); - RntbdRequestArgs mockRntbdRequestArgs = Mockito.mock(RntbdRequestArgs.class); - Mockito.doReturn(mockRequest).when(mockRntbdRequestArgs).serviceRequest(); - Mockito.doReturn("").when(mockRntbdRequestArgs).replicaPath(); - Mockito.doReturn(0L).when(mockRntbdRequestArgs).transportRequestId(); - - RntbdRequestFrame mockRntbdRequestFrame = Mockito.mock(RntbdRequestFrame.class); - Mockito.doReturn(RntbdConstants.RntbdOperationType.Connection).when(mockRntbdRequestFrame).getOperationType(); - RntbdRequestHeaders rntbdRequestHeaders = new RntbdRequestHeaders(mockRntbdRequestArgs, mockRntbdRequestFrame); - - final ByteBuf out = Unpooled.buffer(); - rntbdRequestHeaders.encode(out, false); + byte[] hashValue = new byte[16]; + rnd.nextBytes(hashValue); + RntbdTokenStream input = new RntbdRequestHeaders(args, frame); + input + .get(RntbdConstants.RntbdRequestHeader.EffectivePartitionKey) + .setValue(hashValue); + + ByteBuf out = Unpooled.buffer(1024); + input.encode(out, forThinClient); + + out.readerIndex(0); + + return getHeaderIdsInOrder(out); } - /*final class TestRntbdTokenStream extends RntbdTokenStream { - TestRntbdTokenStream(EnumSet headers, Map ids, ByteBuf in, Class classType) { - super(headers, ids, in, classType); + private static List getHeaderIdsInOrder(ByteBuf in) { + List headerIds = new ArrayList<>(); + while (in.readableBytes() > 0) { + + final short id = in.readShortLE(); + headerIds.add(id); + final RntbdTokenType type = RntbdTokenType.fromId(in.readByte()); + + RntbdToken token = RntbdToken.create(RntbdConstants.RntbdRequestHeader.map.get(id)); + token.decode(in); } - }*/ + + return headerIds; + } } diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdTokenTests.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdTokenTests.java new file mode 100644 index 000000000000..6de130598613 --- /dev/null +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdTokenTests.java @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.cosmos.implementation.directconnectivity.rntbd; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import org.testng.annotations.Test; + +import java.util.Base64; +import java.util.Random; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + +public class RntbdTokenTests { + private static final Random rnd = new Random(); + @Test(groups = { "unit" }) + public void getValueIsIdempotent() { + RntbdToken token = RntbdToken.create(RntbdConstants.RntbdRequestHeader.EffectivePartitionKey); + byte[] blob = new byte[10]; + rnd.nextBytes(blob); + token.setValue(blob); + + String expectedJson = "{\"id\":90,\"name\":\"EffectivePartitionKey\",\"present\":true," + + "\"required\":false,\"value\":\"" + + Base64.getEncoder().encodeToString(blob) + + "\",\"tokenType\":\"Bytes\"}"; + assertThat(RntbdObjectMapper.toJson(token)).isEqualTo(expectedJson); + + Object value1 = token.getValue(); + Object value2 = token.getValue(); + assertThat(value1).isSameAs(value2); + assertThat(value1).isSameAs(blob); + + assertThat(RntbdObjectMapper.toJson(token)).isEqualTo(expectedJson); + + ByteBuf buffer = Unpooled.buffer(1024); + token.encode(buffer); + + RntbdToken decodedToken = RntbdToken.create(RntbdConstants.RntbdRequestHeader.EffectivePartitionKey); + // skipping 3 bytes (2 bytes for header id + 1 byte for token type) + buffer.readerIndex(3); + // when decoding the RntbdToken.value is a ByteBuffer - not a byte[] - testing this path for idempotency as well + decodedToken.decode(buffer); + assertThat(RntbdObjectMapper.toJson(decodedToken)).isEqualTo(expectedJson); + + value1 = decodedToken.getValue(); + assertThat(value1).isInstanceOf(ByteBuf.class); + ByteBuf byteBufValue1 = (ByteBuf)value1; + assertThat(byteBufValue1.readableBytes()).isEqualTo(10); + byte[] byteArray1 = new byte[10]; + byteBufValue1.getBytes(byteBufValue1.readerIndex(), byteArray1); + assertThat(byteArray1).isEqualTo(blob); + + value2 = decodedToken.getValue(); + assertThat(value1).isSameAs(value2); + ByteBuf byteBufValue2 = (ByteBuf)value2; + assertThat(byteBufValue2.readableBytes()).isEqualTo(10); + byte[] byteArray2 = new byte[10]; + byteBufValue2.getBytes(byteBufValue2.readerIndex(), byteArray2); + assertThat(byteArray2).isEqualTo(blob); + + assertThat(RntbdObjectMapper.toJson(decodedToken)).isEqualTo(expectedJson); + } +} diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/query/DocumentProducerTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/query/DocumentProducerTest.java index 33ca6c7b089a..2bc5679eb6e4 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/query/DocumentProducerTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/query/DocumentProducerTest.java @@ -4,7 +4,6 @@ import com.azure.cosmos.BridgeInternal; import com.azure.cosmos.CosmosException; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.ConnectionPolicy; import com.azure.cosmos.implementation.CosmosError; import com.azure.cosmos.implementation.DiagnosticsClientContext; @@ -28,9 +27,9 @@ import com.azure.cosmos.implementation.guava25.collect.LinkedListMultimap; import com.azure.cosmos.implementation.query.orderbyquery.OrderByRowResult; import com.azure.cosmos.implementation.query.orderbyquery.OrderbyRowComparer; -import com.azure.cosmos.implementation.routing.LocationCache; import com.azure.cosmos.implementation.routing.PartitionKeyRangeIdentity; import com.azure.cosmos.implementation.routing.Range; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; import com.azure.cosmos.models.FeedResponse; import com.fasterxml.jackson.databind.node.ObjectNode; import io.reactivex.subscribers.TestSubscriber; @@ -113,9 +112,9 @@ public Object[][] mergeParamProvider() { } private IRetryPolicyFactory mockDocumentClientIRetryPolicyFactory() { - LocationCache.ConsolidatedRegionalEndpoint consolidatedRegionalEndpoint; + RegionalRoutingContext regionalRoutingContext; try { - consolidatedRegionalEndpoint = new LocationCache.ConsolidatedRegionalEndpoint(new URI("http://localhost"), null); + regionalRoutingContext = new RegionalRoutingContext(new URI("http://localhost")); } catch (Exception e) { throw new IllegalStateException(e); } @@ -123,7 +122,7 @@ private IRetryPolicyFactory mockDocumentClientIRetryPolicyFactory() { GlobalEndpointManager globalEndpointManager = Mockito.mock(GlobalEndpointManager.class); GlobalPartitionEndpointManagerForCircuitBreaker globalPartitionEndpointManager = Mockito.mock(GlobalPartitionEndpointManagerForCircuitBreaker.class); - Mockito.doReturn(consolidatedRegionalEndpoint).when(globalEndpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); + Mockito.doReturn(regionalRoutingContext).when(globalEndpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); doReturn(false).when(globalEndpointManager).isClosed(); return new RetryPolicy(mockDiagnosticsClientContext(), globalEndpointManager, ConnectionPolicy.getDefaultPolicy(), globalPartitionEndpointManager); } @@ -841,12 +840,12 @@ private List> mockFeedResponsesPartiallySorted(FeedRangeE Document d = getDocumentDefinition(); if (isOrderby) { - d.set(OrderByIntFieldName, orderByFieldInitialVal + RandomUtils.nextInt(0, 3), CosmosItemSerializer.DEFAULT_SERIALIZER); - d.set(DocumentPartitionKeyRangeIdFieldName, feedRangeEpk.getRange().toString(), CosmosItemSerializer.DEFAULT_SERIALIZER); + d.set(OrderByIntFieldName, orderByFieldInitialVal + RandomUtils.nextInt(0, 3)); + d.set(DocumentPartitionKeyRangeIdFieldName, feedRangeEpk.getRange().toString()); PartitionKeyRange pkr = mockPartitionKeyRange(feedRangeEpk.getRange().toString(), feedRangeEpk.getRange()); - d.set(DocumentPartitionKeyRangeMinInclusiveFieldName, pkr.getMinInclusive(), CosmosItemSerializer.DEFAULT_SERIALIZER); - d.set(DocumentPartitionKeyRangeMaxExclusiveFieldName, pkr.getMaxExclusive(), CosmosItemSerializer.DEFAULT_SERIALIZER); + d.set(DocumentPartitionKeyRangeMinInclusiveFieldName, pkr.getMinInclusive()); + d.set(DocumentPartitionKeyRangeMaxExclusiveFieldName, pkr.getMaxExclusive()); QueryItem qi = new QueryItem("{ \"item\": " + d.getInt(OrderByIntFieldName) + " }"); diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/routing/LocationCacheTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/routing/LocationCacheTest.java index 4b162208e885..eec53a04e1f0 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/routing/LocationCacheTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/implementation/routing/LocationCacheTest.java @@ -21,8 +21,6 @@ import com.azure.cosmos.models.ModelBridgeUtils; import com.azure.cosmos.implementation.guava25.collect.ImmutableList; import com.azure.cosmos.implementation.guava25.collect.Iterables; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -37,7 +35,6 @@ import java.util.HashSet; import java.util.Iterator; import java.util.List; -import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; @@ -65,8 +62,6 @@ public class LocationCacheTest { private static HashMap EndpointByLocation = new HashMap<>(); - private final static Logger logger = LoggerFactory.getLogger(LocationCache.class); - static { EndpointByLocation.put("location1", LocationCacheTest.Location1Endpoint); EndpointByLocation.put("location2", LocationCacheTest.Location2Endpoint); @@ -484,9 +479,9 @@ public void validateAsync(boolean useMultipleWriteEndpoints, @Test(groups = "long") public void validateWriteEndpointOrderWithClientSideDisableMultipleWriteLocation() throws Exception { this.initialize(false, true, false); - assertThat(this.cache.getWriteEndpoints().get(0)).isEqualTo(new LocationCache.ConsolidatedRegionalEndpoint(LocationCacheTest.Location1Endpoint, null)); - assertThat(this.cache.getWriteEndpoints().get(1)).isEqualTo(new LocationCache.ConsolidatedRegionalEndpoint(LocationCacheTest.Location2Endpoint, null)); - assertThat(this.cache.getWriteEndpoints().get(2)).isEqualTo(new LocationCache.ConsolidatedRegionalEndpoint(LocationCacheTest.Location3Endpoint, null)); + assertThat(this.cache.getWriteEndpoints().get(0)).isEqualTo(new RegionalRoutingContext(LocationCacheTest.Location1Endpoint)); + assertThat(this.cache.getWriteEndpoints().get(1)).isEqualTo(new RegionalRoutingContext(LocationCacheTest.Location2Endpoint)); + assertThat(this.cache.getWriteEndpoints().get(2)).isEqualTo(new RegionalRoutingContext(LocationCacheTest.Location3Endpoint)); } @Test(groups = "unit", dataProvider = "excludedRegionsTestConfigs") @@ -516,11 +511,11 @@ public void validateExcludedRegions( request.requestContext.setExcludeRegions(excludedRegionsOnRequest); if (request.isReadOnlyRequest()) { - List applicableReadEndpoints = cache.getApplicableReadEndpoints(request); + List applicableReadEndpoints = cache.getApplicableReadEndpoints(request); assertThat(applicableReadEndpoints.size()).isEqualTo(expectedApplicableEndpoints.size()); expectedApplicableEndpoints.forEach(endpoint -> assertThat(expectedApplicableEndpoints.contains(endpoint)).isTrue()); } else { - List applicableWriteEndpoints = cache.getApplicableWriteEndpoints(request); + List applicableWriteEndpoints = cache.getApplicableWriteEndpoints(request); assertThat(applicableWriteEndpoints.size()).isEqualTo(expectedApplicableEndpoints.size()); expectedApplicableEndpoints.forEach(endpoint -> assertThat(expectedApplicableEndpoints.contains(endpoint)).isTrue()); } @@ -536,8 +531,8 @@ public void validateEffectivePreferredRegions( boolean isDefaultEndpointAlsoRegionalEndpoint) { this.initialize(true, true, isPreferredLocationsListEmpty, isDefaultEndpointAlsoRegionalEndpoint); - List applicableReadEndpoints = cache.getApplicableReadEndpoints(request); - List applicableWriteEndpoints = cache.getApplicableWriteEndpoints(request); + List applicableReadEndpoints = cache.getApplicableReadEndpoints(request); + List applicableWriteEndpoints = cache.getApplicableWriteEndpoints(request); if (request.isReadOnlyRequest()) { assertThat(applicableReadEndpoints.size()).isEqualTo(expectedApplicableReadEndpoints.size()); @@ -671,8 +666,8 @@ private void validateLocationCacheAsync( endpointDiscoveryEnabled, isPreferredListEmpty); - UnmodifiableList currentWriteEndpoints = this.cache.getWriteEndpoints(); - UnmodifiableList currentReadEndpoints = this.cache.getReadEndpoints(); + UnmodifiableList currentWriteEndpoints = this.cache.getWriteEndpoints(); + UnmodifiableList currentReadEndpoints = this.cache.getReadEndpoints(); for (int i = 0; i < readLocationIndex; i++) { this.cache.markEndpointUnavailableForRead(createUrl(Iterables.get(this.databaseAccount.getReadableLocations(), i).getEndpoint())); this.endpointManager.markEndpointUnavailableForRead(createUrl(Iterables.get(this.databaseAccount.getReadableLocations(), i).getEndpoint()));; @@ -902,28 +897,28 @@ private void validateRequestEndpointResolution( // If current write endpoint is unavailable, write endpoints order doesn't change // ALL write requests flip-flop between current write and alternate write endpoint - UnmodifiableList writeEndpoints = this.cache.getWriteEndpoints(); + UnmodifiableList writeEndpoints = this.cache.getWriteEndpoints(); - assertThat(new LocationCache.ConsolidatedRegionalEndpoint(firstAvailableWriteEndpoint, null)).isEqualTo(writeEndpoints.get(0)); - assertThat(new LocationCache.ConsolidatedRegionalEndpoint(secondAvailableWriteEndpoint, null)).isEqualTo(this.resolveEndpointForWriteRequest(ResourceType.Document, true)); - assertThat(new LocationCache.ConsolidatedRegionalEndpoint(firstAvailableWriteEndpoint, null)).isEqualTo(this.resolveEndpointForWriteRequest(ResourceType.Document, false)); + assertThat(new RegionalRoutingContext(firstAvailableWriteEndpoint)).isEqualTo(writeEndpoints.get(0)); + assertThat(new RegionalRoutingContext(secondAvailableWriteEndpoint)).isEqualTo(this.resolveEndpointForWriteRequest(ResourceType.Document, true)); + assertThat(new RegionalRoutingContext(firstAvailableWriteEndpoint)).isEqualTo(this.resolveEndpointForWriteRequest(ResourceType.Document, false)); // Writes to other resource types should be directed to first/second write getEndpoint - assertThat(new LocationCache.ConsolidatedRegionalEndpoint(firstWriteEnpoint, null)).isEqualTo(this.resolveEndpointForWriteRequest(ResourceType.Database, false)); - assertThat(new LocationCache.ConsolidatedRegionalEndpoint(secondWriteEnpoint, null)).isEqualTo(this.resolveEndpointForWriteRequest(ResourceType.Database, true)); + assertThat(new RegionalRoutingContext(firstWriteEnpoint)).isEqualTo(this.resolveEndpointForWriteRequest(ResourceType.Database, false)); + assertThat(new RegionalRoutingContext(secondWriteEnpoint)).isEqualTo(this.resolveEndpointForWriteRequest(ResourceType.Database, true)); // Reads should be directed to available read endpoints regardless of resource type - assertThat(new LocationCache.ConsolidatedRegionalEndpoint(firstAvailableReadEndpoint, null)).isEqualTo(this.resolveEndpointForReadRequest(true)); - assertThat(new LocationCache.ConsolidatedRegionalEndpoint(firstAvailableReadEndpoint, null)).isEqualTo(this.resolveEndpointForReadRequest(false)); + assertThat(new RegionalRoutingContext(firstAvailableReadEndpoint)).isEqualTo(this.resolveEndpointForReadRequest(true)); + assertThat(new RegionalRoutingContext(firstAvailableReadEndpoint)).isEqualTo(this.resolveEndpointForReadRequest(false)); } - private LocationCache.ConsolidatedRegionalEndpoint resolveEndpointForReadRequest(boolean masterResourceType) { + private RegionalRoutingContext resolveEndpointForReadRequest(boolean masterResourceType) { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Read, masterResourceType ? ResourceType.Database : ResourceType.Document); return this.cache.resolveServiceEndpoint(request); } - private LocationCache.ConsolidatedRegionalEndpoint resolveEndpointForWriteRequest(ResourceType resourceType, boolean useAlternateWriteEndpoint) { + private RegionalRoutingContext resolveEndpointForWriteRequest(ResourceType resourceType, boolean useAlternateWriteEndpoint) { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(mockDiagnosticsClientContext(), OperationType.Create, resourceType); request.requestContext.routeToLocation(useAlternateWriteEndpoint ? 1 : 0, resourceType.isCollectionChild()); return this.cache.resolveServiceEndpoint(request); diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/models/JsonSerializableTests.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/models/JsonSerializableTests.java index 26a30cf1001b..de6cf516c73b 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/models/JsonSerializableTests.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/models/JsonSerializableTests.java @@ -3,7 +3,6 @@ package com.azure.cosmos.models; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.Document; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; @@ -58,29 +57,29 @@ public enum enums { public void getObjectAndCastToClass() { Document document = new Document(); // numeric values - document.set("intValue", Integer.MAX_VALUE, CosmosItemSerializer.DEFAULT_SERIALIZER); - document.set("doubleValue", Double.MAX_VALUE, CosmosItemSerializer.DEFAULT_SERIALIZER); - document.set("longValue", Long.MAX_VALUE, CosmosItemSerializer.DEFAULT_SERIALIZER); + document.set("intValue", Integer.MAX_VALUE); + document.set("doubleValue", Double.MAX_VALUE); + document.set("longValue", Long.MAX_VALUE); assertThat(document.getObject("intValue", Integer.class).intValue()).isEqualTo(Integer.MAX_VALUE); assertThat(document.getObject("doubleValue", Double.class).doubleValue()).isEqualTo(Double.MAX_VALUE); assertThat(document.getObject("longValue", Long.class).longValue()).isEqualTo(Long.MAX_VALUE); // string - document.set("stringValue", "stringField", CosmosItemSerializer.DEFAULT_SERIALIZER); + document.set("stringValue", "stringField"); assertThat(document.getObject("stringValue", String.class)).isEqualTo("stringField"); // boolean - document.set("boolValue", true, CosmosItemSerializer.DEFAULT_SERIALIZER); + document.set("boolValue", true); assertThat(document.getObject("boolValue", Boolean.class)).isEqualTo(true); // enum - document.set("enumValue", "third", CosmosItemSerializer.DEFAULT_SERIALIZER); + document.set("enumValue", "third"); assertThat(document.getObject("enumValue", enums.class)).isEqualTo(enums.third); // Pojo Pojo pojo = new Pojo(1, 2); - document.set( "pojoValue", pojo, CosmosItemSerializer.DEFAULT_SERIALIZER); + document.set( "pojoValue", pojo); Pojo readPojo = document.getObject("pojoValue", Pojo.class); assertThat(readPojo.getA()).isEqualTo(pojo.getA()); assertThat(readPojo.getB()).isEqualTo(pojo.getB()); @@ -88,7 +87,7 @@ public void getObjectAndCastToClass() { // JsonSerializable Document innerDocument = new Document(); innerDocument.setId("innerDocument"); - document.set("innerDocument", innerDocument, CosmosItemSerializer.DEFAULT_SERIALIZER); + document.set("innerDocument", innerDocument); Document readInnerDocument = document.getObject("innerDocument", Document.class); assertThat(readInnerDocument.getId()).isEqualTo(innerDocument.getId()); } diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/AggregateQueryTests.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/AggregateQueryTests.java index 37b2a138a432..a171bf00a4bc 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/AggregateQueryTests.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/AggregateQueryTests.java @@ -6,7 +6,6 @@ import com.azure.cosmos.CosmosAsyncContainer; import com.azure.cosmos.CosmosClientBuilder; import com.azure.cosmos.CosmosException; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.Document; import com.azure.cosmos.implementation.FeedResponseListValidator; import com.azure.cosmos.implementation.InternalObjectNode; @@ -125,15 +124,15 @@ public void generateTestData() { for (int i = 0; i < values.length; i++) { InternalObjectNode d = new InternalObjectNode(); d.setId(UUID.randomUUID().toString()); - d.set(partitionKey, values[i], CosmosItemSerializer.DEFAULT_SERIALIZER); + d.set(partitionKey, values[i]); docs.add(d); } for (int i = 0; i < numberOfDocsWithSamePartitionKey; i++) { InternalObjectNode d = new InternalObjectNode(); - d.set(partitionKey, uniquePartitionKey, CosmosItemSerializer.DEFAULT_SERIALIZER); - d.set("getResourceId", Integer.toString(i), CosmosItemSerializer.DEFAULT_SERIALIZER); - d.set(field, i + 1, CosmosItemSerializer.DEFAULT_SERIALIZER); + d.set(partitionKey, uniquePartitionKey); + d.set("getResourceId", Integer.toString(i)); + d.set(field, i + 1); d.setId(UUID.randomUUID().toString()); docs.add(d); } @@ -141,7 +140,7 @@ public void generateTestData() { numberOfDocumentsWithNumericId = numberOfDocuments - values.length - numberOfDocsWithSamePartitionKey; for (int i = 0; i < numberOfDocumentsWithNumericId; i++) { InternalObjectNode d = new InternalObjectNode(); - d.set(partitionKey, i + 1, CosmosItemSerializer.DEFAULT_SERIALIZER); + d.set(partitionKey, i + 1); d.setId(UUID.randomUUID().toString()); docs.add(d); } diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/ChangeFeedTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/ChangeFeedTest.java index f699d5edc284..8e76604cbf5c 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/ChangeFeedTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/ChangeFeedTest.java @@ -5,7 +5,6 @@ import com.azure.cosmos.BridgeInternal; import com.azure.cosmos.ConnectionMode; import com.azure.cosmos.CosmosDiagnostics; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.AsyncDocumentClient; import com.azure.cosmos.implementation.ClientSideRequestStatistics; import com.azure.cosmos.implementation.Database; @@ -493,7 +492,7 @@ public void createDocument(AsyncDocumentClient client, String partitionKey) { public Document updateDocument(AsyncDocumentClient client, Document originalDocument) { String uuid = UUID.randomUUID().toString(); - originalDocument.set("prop", uuid, CosmosItemSerializer.DEFAULT_SERIALIZER); + originalDocument.set("prop", uuid); return client .replaceDocument(originalDocument.getSelfLink(), originalDocument, null) @@ -581,8 +580,8 @@ private static Document getDocumentDefinition(String partitionKey) { String uuid = UUID.randomUUID().toString(); Document doc = new Document(); doc.setId(uuid); - doc.set("mypk", partitionKey, CosmosItemSerializer.DEFAULT_SERIALIZER); - doc.set("prop", uuid, CosmosItemSerializer.DEFAULT_SERIALIZER); + doc.set("mypk", partitionKey); + doc.set("prop", uuid); return doc; } diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/ClientRetryPolicyE2ETests.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/ClientRetryPolicyE2ETests.java index e11ea40bbc3f..a4e88d3cf8e2 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/ClientRetryPolicyE2ETests.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/ClientRetryPolicyE2ETests.java @@ -21,6 +21,7 @@ import com.azure.cosmos.implementation.Utils; import com.azure.cosmos.implementation.throughputControl.TestItem; import com.azure.cosmos.models.CosmosChangeFeedRequestOptions; +import com.azure.cosmos.models.CosmosItemResponse; import com.azure.cosmos.models.CosmosPatchOperations; import com.azure.cosmos.models.CosmosQueryRequestOptions; import com.azure.cosmos.models.FeedRange; @@ -207,7 +208,7 @@ public void queryPlanHttpTimeoutWillNotMarkRegionUnavailable(boolean shouldUsePr } @Test(groups = { "multi-master" }, dataProvider = "preferredRegionsConfigProvider", timeOut = TIMEOUT) - public void addressRefreshHttpTimeoutWillNotDoCrossRegionRetry(boolean shouldUsePreferredRegionsOnClient) { + public void addressRefreshHttpTimeoutWillDoCrossRegionRetryForReads(boolean shouldUsePreferredRegionsOnClient) { CosmosAsyncContainer resultantCosmosAsyncContainer; CosmosAsyncClient resultantCosmosAsyncClient; @@ -262,10 +263,78 @@ public void addressRefreshHttpTimeoutWillNotDoCrossRegionRetry(boolean shouldUse resultantCosmosAsyncContainer, Arrays.asList(addressRefreshDelayRule, serverGoneRule)).block(); try { - resultantCosmosAsyncContainer + CosmosItemResponse itemResponse = resultantCosmosAsyncContainer .readItem(newItem.getId(), new PartitionKey(newItem.getId()), TestItem.class) .block(); - fail("addressRefreshHttpTimeoutWillNotDoCrossRegionRetry() should fail due to addressRefresh timeout"); + + assertThat(itemResponse).isNotNull(); + + CosmosDiagnostics diagnostics = itemResponse.getDiagnostics(); + + assertThat(diagnostics.getContactedRegionNames().size()).isEqualTo(2); + assertThat(diagnostics.getContactedRegionNames()).contains(this.preferredRegions.get(0)); + assertThat(diagnostics.getContactedRegionNames()).contains(this.preferredRegions.get(1)); + } finally { + addressRefreshDelayRule.disable(); + serverGoneRule.disable(); + } + } + + @Test(groups = { "multi-master" }, dataProvider = "preferredRegionsConfigProvider", timeOut = TIMEOUT) + public void addressRefreshHttpTimeoutWillNotDoCrossRegionRetryForWrites(boolean shouldUsePreferredRegionsOnClient) { + + CosmosAsyncContainer resultantCosmosAsyncContainer; + CosmosAsyncClient resultantCosmosAsyncClient; + + if (shouldUsePreferredRegionsOnClient) { + resultantCosmosAsyncClient = this.clientWithPreferredRegions; + resultantCosmosAsyncContainer = this.cosmosAsyncContainerFromClientWithPreferredRegions; + } else { + resultantCosmosAsyncClient = this.clientWithoutPreferredRegions; + resultantCosmosAsyncContainer = this.cosmosAsyncContainerFromClientWithoutPreferredRegions; + } + + if (BridgeInternal + .getContextClient(resultantCosmosAsyncClient) + .getConnectionPolicy() + .getConnectionMode() != ConnectionMode.DIRECT) { + throw new SkipException("queryPlanHttpTimeoutWillNotMarkRegionUnavailable() is only meant for DIRECT mode"); + } + + // create fault injection rules for address refresh + FaultInjectionRule addressRefreshDelayRule = new FaultInjectionRuleBuilder("addressRefreshDelayRule") + .condition( + new FaultInjectionConditionBuilder() + .operationType(FaultInjectionOperationType.METADATA_REQUEST_ADDRESS_REFRESH) + .build()) + .result( + FaultInjectionResultBuilders.getResultBuilder(FaultInjectionServerErrorType.RESPONSE_DELAY) + .delay(Duration.ofSeconds(11)) + .times(4) // make sure it will exhaust the local region retry + .build() + ) + .build(); + + // Create gone rules to force address refresh will bound to happen + FaultInjectionRule serverGoneRule = new FaultInjectionRuleBuilder("serverGoneRule") + .condition( + new FaultInjectionConditionBuilder() + .operationType(FaultInjectionOperationType.CREATE_ITEM) + .build()) + .result( + FaultInjectionResultBuilders.getResultBuilder(FaultInjectionServerErrorType.GONE) + .times(4) // client is on session consistency, make sure exception will be bubbled up to goneAndRetry policy + .build() + ) + .build(); + + CosmosFaultInjectionHelper + .configureFaultInjectionRules( + resultantCosmosAsyncContainer, + Arrays.asList(addressRefreshDelayRule, serverGoneRule)).block(); + try { + TestItem newItem = TestItem.createNewItem(); + resultantCosmosAsyncContainer.createItem(newItem).block(); } catch (CosmosException e) { assertThat(e.getDiagnostics().getContactedRegionNames().size()).isEqualTo(1); assertThat(e.getDiagnostics().getContactedRegionNames()).contains(this.preferredRegions.get(0)); diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/CollectionCrudTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/CollectionCrudTest.java index 6efee2ef96fa..3ed837e7a83c 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/CollectionCrudTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/CollectionCrudTest.java @@ -3,7 +3,6 @@ package com.azure.cosmos.rx; import com.azure.cosmos.BridgeInternal; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.HttpConstants; import com.azure.cosmos.models.CompositePath; import com.azure.cosmos.models.CompositePathSortOrder; @@ -21,7 +20,6 @@ import com.azure.cosmos.CosmosResponseValidator; import com.azure.cosmos.models.IndexingMode; import com.azure.cosmos.models.IndexingPolicy; -import com.azure.cosmos.models.ModelBridgeInternal; import com.azure.cosmos.models.PartitionKey; import com.azure.cosmos.models.PartitionKeyDefinition; import com.azure.cosmos.models.SpatialSpec; @@ -314,8 +312,8 @@ public void sessionTokenConsistencyCollectionDeleteCreateSameName() { InternalObjectNode document = new InternalObjectNode(); document.setId("doc"); - document.set("name", "New Document", CosmosItemSerializer.DEFAULT_SERIALIZER); - document.set("mypk", "mypkValue", CosmosItemSerializer.DEFAULT_SERIALIZER); + document.set("name", "New Document"); + document.set("mypk", "mypkValue"); createDocument(collection, document); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); CosmosItemResponse readDocumentResponse = @@ -323,7 +321,7 @@ public void sessionTokenConsistencyCollectionDeleteCreateSameName() { logger.info("Client 1 READ Document Client Side Request Statistics {}", readDocumentResponse.getDiagnostics()); logger.info("Client 1 READ Document Latency {}", readDocumentResponse.getDuration()); - document.set("name", "New Updated Document", CosmosItemSerializer.DEFAULT_SERIALIZER); + document.set("name", "New Updated Document"); CosmosItemResponse upsertDocumentResponse = collection.upsertItem(document).block(); logger.info("Client 1 Upsert Document Client Side Request Statistics {}", upsertDocumentResponse.getDiagnostics()); logger.info("Client 1 Upsert Document Latency {}", upsertDocumentResponse.getDuration()); @@ -335,8 +333,8 @@ public void sessionTokenConsistencyCollectionDeleteCreateSameName() { InternalObjectNode newDocument = new InternalObjectNode(); newDocument.setId("doc"); - newDocument.set("name", "New Created Document", CosmosItemSerializer.DEFAULT_SERIALIZER); - newDocument.set("mypk", "mypk", CosmosItemSerializer.DEFAULT_SERIALIZER); + newDocument.set("name", "New Created Document"); + newDocument.set("mypk", "mypk"); createDocument(collection2, newDocument); readDocumentResponse = client1.getDatabase(dbId) diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/DocumentCrudTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/DocumentCrudTest.java index 706f09c0d1b0..016baa70b2c4 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/DocumentCrudTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/DocumentCrudTest.java @@ -8,7 +8,6 @@ import com.azure.cosmos.CosmosAsyncDatabase; import com.azure.cosmos.CosmosClientBuilder; import com.azure.cosmos.CosmosException; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.TestObject; import com.azure.cosmos.implementation.DatabaseForTest; import com.azure.cosmos.implementation.FailureValidator; @@ -18,7 +17,6 @@ import com.azure.cosmos.models.CosmosItemRequestOptions; import com.azure.cosmos.models.CosmosItemResponse; import com.azure.cosmos.models.CosmosQueryRequestOptions; -import com.azure.cosmos.models.ModelBridgeInternal; import com.azure.cosmos.models.PartitionKey; import com.azure.cosmos.util.CosmosPagedFlux; import org.testng.annotations.AfterClass; @@ -275,7 +273,7 @@ public void replaceDocument(String documentId) throws InterruptedException { container.createItem(docDefinition, new CosmosItemRequestOptions()).block(); String newPropValue = UUID.randomUUID().toString(); - docDefinition.set("newProp", newPropValue, CosmosItemSerializer.DEFAULT_SERIALIZER); + docDefinition.set("newProp", newPropValue); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); // replace document @@ -320,7 +318,7 @@ public void upsertDocument_ReplaceDocument(String documentId) throws Throwable { BridgeInternal.getProperties(container.createItem(properties, new CosmosItemRequestOptions()).block()); String newPropValue = UUID.randomUUID().toString(); - properties.set("newProp", newPropValue, CosmosItemSerializer.DEFAULT_SERIALIZER); + properties.set("newProp", newPropValue); // Replace document diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/GroupByQueryTests.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/GroupByQueryTests.java index b9c72b3542fd..1d3f0adc9b08 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/GroupByQueryTests.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/GroupByQueryTests.java @@ -5,7 +5,6 @@ import com.azure.cosmos.CosmosAsyncClient; import com.azure.cosmos.CosmosAsyncContainer; import com.azure.cosmos.CosmosClientBuilder; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.Document; import com.azure.cosmos.implementation.InternalObjectNode; import com.azure.cosmos.models.CosmosQueryRequestOptions; @@ -121,8 +120,8 @@ public void queryDocuments(Triple, Integer> gro resultMap.forEach((groupByObj, sum) -> { Document d = new Document(); - d.set("sum_age", sum, CosmosItemSerializer.DEFAULT_SERIALIZER); - d.set(groupByConfig.getLeft(), groupByObj, CosmosItemSerializer.DEFAULT_SERIALIZER); + d.set("sum_age", sum); + d.set(groupByConfig.getLeft(), groupByObj); expectedDocumentsList.add(d); }); diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/MultiOrderByQueryTests.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/MultiOrderByQueryTests.java index d37866658eba..c6e232ec7b84 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/MultiOrderByQueryTests.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/MultiOrderByQueryTests.java @@ -6,7 +6,6 @@ import com.azure.cosmos.CosmosAsyncClient; import com.azure.cosmos.CosmosAsyncContainer; import com.azure.cosmos.CosmosClientBuilder; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.FeedResponseListValidator; import com.azure.cosmos.implementation.InternalObjectNode; import com.azure.cosmos.models.CompositePath; @@ -138,23 +137,23 @@ public void before_MultiOrderByQueryTests() throws Exception { // Permute all the fields so that there are duplicates with tie breaks InternalObjectNode numberClone = new InternalObjectNode(multiOrderByDocumentString); - numberClone.set(NUMBER_FIELD, random.nextInt(5), CosmosItemSerializer.DEFAULT_SERIALIZER); + numberClone.set(NUMBER_FIELD, random.nextInt(5)); numberClone.setId(UUID.randomUUID().toString()); this.documents.add(numberClone); InternalObjectNode stringClone = new InternalObjectNode(multiOrderByDocumentString); - stringClone.set(STRING_FIELD, Integer.toString(random.nextInt(5)), CosmosItemSerializer.DEFAULT_SERIALIZER); + stringClone.set(STRING_FIELD, Integer.toString(random.nextInt(5))); stringClone.setId(UUID.randomUUID().toString()); this.documents.add(stringClone); InternalObjectNode boolClone = new InternalObjectNode(multiOrderByDocumentString); - boolClone.set(BOOL_FIELD, random.nextInt(2) % 2 == 0, CosmosItemSerializer.DEFAULT_SERIALIZER); + boolClone.set(BOOL_FIELD, random.nextInt(2) % 2 == 0); boolClone.setId(UUID.randomUUID().toString()); this.documents.add(boolClone); // Also fuzz what partition it goes to InternalObjectNode partitionClone = new InternalObjectNode(multiOrderByDocumentString); - partitionClone.set(PARTITION_KEY, random.nextInt(5), CosmosItemSerializer.DEFAULT_SERIALIZER); + partitionClone.set(PARTITION_KEY, random.nextInt(5)); partitionClone.setId(UUID.randomUUID().toString()); this.documents.add(partitionClone); } @@ -169,18 +168,18 @@ private InternalObjectNode generateMultiOrderByDocument() { Random random = new Random(); InternalObjectNode document = new InternalObjectNode(); document.setId(UUID.randomUUID().toString()); - document.set(NUMBER_FIELD, random.nextInt(5), CosmosItemSerializer.DEFAULT_SERIALIZER); - document.set(NUMBER_FIELD_2, random.nextInt(5), CosmosItemSerializer.DEFAULT_SERIALIZER); - document.set(BOOL_FIELD, (random.nextInt() % 2) == 0, CosmosItemSerializer.DEFAULT_SERIALIZER); - document.set(STRING_FIELD, Integer.toString(random.nextInt(5)), CosmosItemSerializer.DEFAULT_SERIALIZER); - document.set(STRING_FIELD_2, Integer.toString(random.nextInt(5)), CosmosItemSerializer.DEFAULT_SERIALIZER); - document.set(NULL_FIELD, null, CosmosItemSerializer.DEFAULT_SERIALIZER); - document.set(OBJECT_FIELD, "", CosmosItemSerializer.DEFAULT_SERIALIZER); - document.set(ARRAY_FIELD, (new ObjectMapper()).createArrayNode(), CosmosItemSerializer.DEFAULT_SERIALIZER); - document.set(SHORT_STRING_FIELD, "a" + random.nextInt(100), CosmosItemSerializer.DEFAULT_SERIALIZER); - document.set(MEDIUM_STRING_FIELD, "a" + random.nextInt(128) + 100, CosmosItemSerializer.DEFAULT_SERIALIZER); - document.set(LONG_STRING_FIELD, "a" + random.nextInt(255) + 128, CosmosItemSerializer.DEFAULT_SERIALIZER); - document.set(PARTITION_KEY, random.nextInt(5), CosmosItemSerializer.DEFAULT_SERIALIZER); + document.set(NUMBER_FIELD, random.nextInt(5)); + document.set(NUMBER_FIELD_2, random.nextInt(5)); + document.set(BOOL_FIELD, (random.nextInt() % 2) == 0); + document.set(STRING_FIELD, Integer.toString(random.nextInt(5))); + document.set(STRING_FIELD_2, Integer.toString(random.nextInt(5))); + document.set(NULL_FIELD, null); + document.set(OBJECT_FIELD, ""); + document.set(ARRAY_FIELD, (new ObjectMapper()).createArrayNode()); + document.set(SHORT_STRING_FIELD, "a" + random.nextInt(100)); + document.set(MEDIUM_STRING_FIELD, "a" + random.nextInt(128) + 100); + document.set(LONG_STRING_FIELD, "a" + random.nextInt(255) + 128); + document.set(PARTITION_KEY, random.nextInt(5)); return document; } diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/OffsetLimitQueryTests.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/OffsetLimitQueryTests.java index 43721b70b5bf..9a1da0599bca 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/OffsetLimitQueryTests.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/OffsetLimitQueryTests.java @@ -7,7 +7,6 @@ import com.azure.cosmos.CosmosAsyncContainer; import com.azure.cosmos.CosmosAsyncDatabase; import com.azure.cosmos.CosmosClientBuilder; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.FeedResponseListValidator; import com.azure.cosmos.implementation.FeedResponseValidator; import com.azure.cosmos.implementation.InternalObjectNode; @@ -312,24 +311,24 @@ public void generateTestData() { for (int i = 0; i < 10; i++) { InternalObjectNode d = new InternalObjectNode(); d.setId(Integer.toString(i)); - d.set(field, i, CosmosItemSerializer.DEFAULT_SERIALIZER); - d.set(partitionKey, firstPk, CosmosItemSerializer.DEFAULT_SERIALIZER); + d.set(field, i); + d.set(partitionKey, firstPk); docs.add(d); } for (int i = 10; i < 20; i++) { InternalObjectNode d = new InternalObjectNode(); d.setId(Integer.toString(i)); - d.set(field, i, CosmosItemSerializer.DEFAULT_SERIALIZER); - d.set(partitionKey, secondPk, CosmosItemSerializer.DEFAULT_SERIALIZER); + d.set(field, i); + d.set(partitionKey, secondPk); docs.add(d); } for (int i = 20; i < 100; i++) { InternalObjectNode d = new InternalObjectNode(); d.setId(Integer.toString(i)); - d.set(field, i, CosmosItemSerializer.DEFAULT_SERIALIZER); - d.set(partitionKey, thirdPk, CosmosItemSerializer.DEFAULT_SERIALIZER); + d.set(field, i); + d.set(partitionKey, thirdPk); docs.add(d); } } diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/TopQueryTests.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/TopQueryTests.java index 90233a668ce1..151e7ae519ce 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/TopQueryTests.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/TopQueryTests.java @@ -5,7 +5,6 @@ import com.azure.cosmos.CosmosAsyncClient; import com.azure.cosmos.CosmosAsyncContainer; import com.azure.cosmos.CosmosClientBuilder; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.query.LimitContinuationToken; import com.azure.cosmos.util.CosmosPagedFlux; import com.azure.cosmos.implementation.InternalObjectNode; @@ -224,16 +223,16 @@ public void generateTestData() { for (int i = 0; i < 10; i++) { InternalObjectNode d = new InternalObjectNode(); d.setId(Integer.toString(i)); - d.set(field, i, CosmosItemSerializer.DEFAULT_SERIALIZER); - d.set(partitionKey, firstPk, CosmosItemSerializer.DEFAULT_SERIALIZER); + d.set(field, i); + d.set(partitionKey, firstPk); docs.add(d); } for (int i = 10; i < 20; i++) { InternalObjectNode d = new InternalObjectNode(); d.setId(Integer.toString(i)); - d.set(field, i, CosmosItemSerializer.DEFAULT_SERIALIZER); - d.set(partitionKey, secondPk, CosmosItemSerializer.DEFAULT_SERIALIZER); + d.set(field, i); + d.set(partitionKey, secondPk); docs.add(d); } } diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/VeryLargeDocumentQueryTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/VeryLargeDocumentQueryTest.java index a404d8a76064..68e68c50731d 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/VeryLargeDocumentQueryTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/VeryLargeDocumentQueryTest.java @@ -5,7 +5,6 @@ import com.azure.cosmos.BridgeInternal; import com.azure.cosmos.CosmosAsyncClient; import com.azure.cosmos.CosmosAsyncContainer; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.models.CosmosItemResponse; import com.azure.cosmos.CosmosClientBuilder; import com.azure.cosmos.util.CosmosPagedFlux; @@ -70,7 +69,7 @@ private void createLargeDocument() { //Keep size as ~ 1.999MB to account for size of other props int size = (int) (ONE_MB * 1.999); - docDefinition.set("largeString", StringUtils.repeat("x", size), CosmosItemSerializer.DEFAULT_SERIALIZER); + docDefinition.set("largeString", StringUtils.repeat("x", size)); Mono> createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/WebExceptionRetryPolicyE2ETests.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/WebExceptionRetryPolicyE2ETests.java index c48edbb20e74..bc544fbc855d 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/WebExceptionRetryPolicyE2ETests.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/WebExceptionRetryPolicyE2ETests.java @@ -125,7 +125,7 @@ public void addressRefreshHttpTimeout() { FaultInjectionRule serverGoneRule = new FaultInjectionRuleBuilder("serverGoneRule") .condition( new FaultInjectionConditionBuilder() - .operationType(FaultInjectionOperationType.READ_ITEM) + .operationType(FaultInjectionOperationType.CREATE_ITEM) .build()) .result( FaultInjectionResultBuilders.getResultBuilder(FaultInjectionServerErrorType.GONE) @@ -140,7 +140,7 @@ public void addressRefreshHttpTimeout() { Arrays.asList(addressRefreshDelayRule, serverGoneRule)).block(); try { cosmosAsyncContainer - .readItem(newItem.getId(), new PartitionKey(newItem.getId()), TestItem.class) + .createItem(newItem) .block(); fail("addressRefreshHttpTimeout() should fail due to addressRefresh timeout"); } catch (CosmosException e) { diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/changefeed/epkversion/FullFidelityChangeFeedProcessorTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/changefeed/epkversion/FullFidelityChangeFeedProcessorTest.java index 7b4a2cd811f9..c530a168d5fc 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/changefeed/epkversion/FullFidelityChangeFeedProcessorTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/changefeed/epkversion/FullFidelityChangeFeedProcessorTest.java @@ -141,7 +141,7 @@ public void fullFidelityChangeFeedProcessorStartFromNow(boolean isContextRequire logger.info("Finished starting ChangeFeed processor"); - setupReadFeedDocuments(createdDocuments, receivedDocuments, createdFeedCollection, FEED_COUNT); + setupReadFeedDocuments(createdDocuments, createdFeedCollection, FEED_COUNT); logger.info("Set up read feed documents"); // Wait for the feed processor to receive and process the documents. @@ -198,7 +198,7 @@ public void fullFidelityChangeFeedProcessorStartFromNow(boolean isContextRequire // b) If not, then LatestVersion / INCREMENTAL ChangeFeedProcessor should be able to reuse the lease // left behind and use its own continuation. @Test(groups = { "emulator" }, dataProvider = "incrementalChangeFeedModeStartFromSetting") - public void fullFidelityChangeFeedModeToIncrementalChangeFeedMode(boolean isStartFromBeginning) throws InterruptedException, JsonProcessingException { + public void fullFidelityChangeFeedModeToIncrementalWithEpkRangeChangeFeedMode(boolean isStartFromBeginning) throws InterruptedException, JsonProcessingException { CosmosAsyncContainer createdFeedCollection = createFeedCollection(FEED_COLLECTION_THROUGHPUT); CosmosAsyncContainer createdLeaseCollection = createLeaseCollection(LEASE_COLLECTION_THROUGHPUT); @@ -208,7 +208,7 @@ public void fullFidelityChangeFeedModeToIncrementalChangeFeedMode(boolean isStar Map receivedDocumentsByFullFidelityCfp = new ConcurrentHashMap<>(); Map receivedDocumentsByIncrementalCfp = new ConcurrentHashMap<>(); - ChangeFeedProcessorOptions changeFeedProcessorOptions = new ChangeFeedProcessorOptions(); + ChangeFeedProcessorOptions changeFeedProcessorOptions = new ChangeFeedProcessorOptions().setLeasePrefix("TEST"); ChangeFeedProcessorBuilder changeFeedProcessorBuilder = new ChangeFeedProcessorBuilder() .options(changeFeedProcessorOptions) @@ -230,7 +230,7 @@ public void fullFidelityChangeFeedModeToIncrementalChangeFeedMode(boolean isStar // Wait for the feed processor to receive and process the documents. Thread.sleep(2 * CHANGE_FEED_PROCESSOR_TIMEOUT); - setupReadFeedDocuments(createdDocuments, receivedDocumentsByFullFidelityCfp, createdFeedCollection, FEED_COUNT); + setupReadFeedDocuments(createdDocuments, createdFeedCollection, FEED_COUNT); logger.info("Set up read feed documents"); // Wait for the feed processor to receive and process the documents. @@ -268,7 +268,10 @@ public void fullFidelityChangeFeedModeToIncrementalChangeFeedMode(boolean isStar } ChangeFeedProcessorBuilder incrementalChangeFeedProcessorBuilder = new ChangeFeedProcessorBuilder() - .options(new ChangeFeedProcessorOptions().setStartFromBeginning(isStartFromBeginning).setMaxItemCount(1)) + .options(new ChangeFeedProcessorOptions() + .setStartFromBeginning(isStartFromBeginning) + .setMaxItemCount(1) + .setLeasePrefix("TEST")) .hostName(hostName) .feedContainer(createdFeedCollection) .leaseContainer(createdLeaseCollection) @@ -312,6 +315,127 @@ public void fullFidelityChangeFeedModeToIncrementalChangeFeedMode(boolean isStar } } + @Test(groups = { "emulator" }, dataProvider = "incrementalChangeFeedModeStartFromSetting") + public void fullFidelityChangeFeedModeToIncrementalWithPkRangeChangeFeedMode(boolean isStartFromBeginning) throws InterruptedException, JsonProcessingException { + CosmosAsyncContainer createdFeedCollection = createFeedCollection(FEED_COLLECTION_THROUGHPUT); + CosmosAsyncContainer createdLeaseCollection = createLeaseCollection(LEASE_COLLECTION_THROUGHPUT); + + try { + List createdDocuments = new ArrayList<>(); + + Map receivedDocumentsByFullFidelityCfp = new ConcurrentHashMap<>(); + Map receivedDocumentsByIncrementalCfp = new ConcurrentHashMap<>(); + + ChangeFeedProcessorOptions changeFeedProcessorOptions = new ChangeFeedProcessorOptions().setLeasePrefix("TEST"); + + ChangeFeedProcessorBuilder changeFeedProcessorBuilder = new ChangeFeedProcessorBuilder() + .options(changeFeedProcessorOptions) + .hostName(hostName) + .feedContainer(createdFeedCollection) + .leaseContainer(createdLeaseCollection); + + changeFeedProcessorBuilder = changeFeedProcessorBuilder + .handleAllVersionsAndDeletesChanges(changeFeedProcessorHandler(receivedDocumentsByFullFidelityCfp)); + + ChangeFeedProcessor fullFidelityChangeFeedProcessor = changeFeedProcessorBuilder.buildChangeFeedProcessor(); + + try { + fullFidelityChangeFeedProcessor.start().subscribeOn(Schedulers.boundedElastic()) + .timeout(Duration.ofMillis(2 * CHANGE_FEED_PROCESSOR_TIMEOUT)) + .doOnSuccess(ignore -> logger.info("Starting FULL_FIDELITY ChangeFeedProcessor")) + .block(); + + // Wait for the feed processor to receive and process the documents. + Thread.sleep(2 * CHANGE_FEED_PROCESSOR_TIMEOUT); + + setupReadFeedDocuments(createdDocuments, createdFeedCollection, FEED_COUNT); + logger.info("Set up read feed documents"); + + // Wait for the feed processor to receive and process the documents. + Thread.sleep(2 * CHANGE_FEED_PROCESSOR_TIMEOUT); + logger.info("Validating changes now"); + + validateChangeFeedProcessing(fullFidelityChangeFeedProcessor, createdDocuments, receivedDocumentsByFullFidelityCfp, FEED_COUNT, 10 * CHANGE_FEED_PROCESSOR_TIMEOUT); + + fullFidelityChangeFeedProcessor + .stop() + .subscribeOn(Schedulers.boundedElastic()) + .timeout(Duration.ofMillis(CHANGE_FEED_PROCESSOR_TIMEOUT)) + .block(); + + // query for documents in the lease container from the createdLeaseCollection + String leaseQuery = "select * from c"; + List leaseDocuments = + createdLeaseCollection + .queryItems(leaseQuery, JsonNode.class) + .byPage() + .blockFirst() + .getResults(); + + logger.info("Lease container documents created by FULL_FIDELITY ChangeFeedProcessor fetched..."); + for (JsonNode lease : leaseDocuments) { + + JsonNode continuationToken = lease.get("ContinuationToken"); + + if (continuationToken != null && !(continuationToken instanceof NullNode)) { + logger.info("Lease document : {}", OBJECT_MAPPER.writeValueAsString(lease)); + logger.info("ContinuationToken : {}", new String(Base64.getUrlDecoder().decode(lease.get("ContinuationToken").asText()))); + } else { + logger.info("Lease container document : {}", OBJECT_MAPPER.writeValueAsString(lease)); + } + } + + ChangeFeedProcessorBuilder incrementalChangeFeedProcessorBuilder = new ChangeFeedProcessorBuilder() + .options(new ChangeFeedProcessorOptions() + .setStartFromBeginning(isStartFromBeginning) + .setMaxItemCount(1) + .setLeasePrefix("TEST")) + .hostName(hostName) + .feedContainer(createdFeedCollection) + .leaseContainer(createdLeaseCollection) + .handleChanges(changeFeedProcessorHandlerForLatestVersionWithPkRangeLease(receivedDocumentsByIncrementalCfp)); + + ChangeFeedProcessor incrementalChangeFeedProcessor = incrementalChangeFeedProcessorBuilder + .buildChangeFeedProcessor(); + + assertThrows(IllegalStateException.class, () -> incrementalChangeFeedProcessor.start().subscribeOn(Schedulers.boundedElastic()) + .timeout(Duration.ofMillis(2 * CHANGE_FEED_PROCESSOR_TIMEOUT)) + .doOnSuccess(ignore -> logger.info("Starting INCREMENTAL ChangeFeedProcessor")) + .block()); + + leaseDocuments = + createdLeaseCollection + .queryItems(leaseQuery, JsonNode.class) + .byPage() + .blockFirst() + .getResults(); + + logger.info("Lease container documents created by INCREMENTAL ChangeFeedProcessor fetched..."); + for (JsonNode lease : leaseDocuments) { + + if (lease.get("ContinuationToken") != null) { + + String continuationToken = lease.get("ContinuationToken").asText(); + + logger.info("Lease document : {}", OBJECT_MAPPER.writeValueAsString(lease)); + logger.info("ContinuationToken : {}", continuationToken); + } else { + logger.info("Lease container document : {}", OBJECT_MAPPER.writeValueAsString(lease)); + } + } + } catch (Exception ex) { + log.error("Change feed processor did not start and stopped in the expected time", ex); + throw ex; + } + + } finally { + safeDeleteCollection(createdFeedCollection); + safeDeleteCollection(createdLeaseCollection); + // Allow some time for the collections to be deleted before exiting. + Thread.sleep(5000); + } + } + // Steps followed in this test // 1. Ingest 10 documents into the feed container. // 2. Start the LatestVersion / INCREMENTAL ChangeFeedProcessor with either startFromBeginning set to 'true' or 'false'. @@ -324,7 +448,7 @@ public void fullFidelityChangeFeedModeToIncrementalChangeFeedMode(boolean isStar // b) If not, then AllVersionsAndDeletes / FULL_FIDELITY ChangeFeedProcessor should be able to reuse the lease // left behind and use its own continuation. @Test(groups = { "emulator" }, dataProvider = "incrementalChangeFeedModeStartFromSetting") - public void incrementalChangeFeedModeToFullFidelityChangeFeedModeWithProcessingStoppage(boolean isStartFromBeginning) throws InterruptedException, JsonProcessingException { + public void incrementalWithEpkRangeChangeFeedModeToFullFidelityChangeFeedModeWithProcessingStoppage(boolean isStartFromBeginning) throws InterruptedException, JsonProcessingException { CosmosAsyncContainer createdFeedCollection = createFeedCollection(FEED_COLLECTION_THROUGHPUT); CosmosAsyncContainer createdLeaseCollection = createLeaseCollection(LEASE_COLLECTION_THROUGHPUT); @@ -337,7 +461,10 @@ public void incrementalChangeFeedModeToFullFidelityChangeFeedModeWithProcessingS int docLimit = FEED_COUNT / 2; ChangeFeedProcessorBuilder changeFeedProcessorBuilder = new ChangeFeedProcessorBuilder() - .options(new ChangeFeedProcessorOptions().setStartFromBeginning(isStartFromBeginning).setMaxItemCount(1)) + .options(new ChangeFeedProcessorOptions() + .setStartFromBeginning(isStartFromBeginning) + .setMaxItemCount(1) + .setLeasePrefix("TEST")) .hostName(hostName) .feedContainer(createdFeedCollection) .leaseContainer(createdLeaseCollection); @@ -350,7 +477,7 @@ public void incrementalChangeFeedModeToFullFidelityChangeFeedModeWithProcessingS changeFeedProcessorInAtomicRefHolder.set(incrementalChangeFeedProcessor); logger.info("Set up read feed documents"); - setupReadFeedDocuments(createdDocuments, receivedDocumentsByIncrementalCfp, createdFeedCollection, FEED_COUNT); + setupReadFeedDocuments(createdDocuments, createdFeedCollection, FEED_COUNT); try { incrementalChangeFeedProcessor.start().subscribeOn(Schedulers.boundedElastic()) @@ -396,7 +523,9 @@ public void incrementalChangeFeedModeToFullFidelityChangeFeedModeWithProcessingS } ChangeFeedProcessorBuilder fullFidelityChangeFeedProcessorBuilder = new ChangeFeedProcessorBuilder() - .options(new ChangeFeedProcessorOptions().setMaxItemCount(1)) + .options(new ChangeFeedProcessorOptions() + .setMaxItemCount(1) + .setLeasePrefix("TEST")) .hostName(hostName) .feedContainer(createdFeedCollection) .leaseContainer(createdLeaseCollection) @@ -421,7 +550,7 @@ public void incrementalChangeFeedModeToFullFidelityChangeFeedModeWithProcessingS Thread.sleep(2 * CHANGE_FEED_PROCESSOR_TIMEOUT); logger.info("Set up read feed documents"); - setupReadFeedDocuments(createdDocuments, receivedDocumentsByFullFidelityCfp, createdFeedCollection, FEED_COUNT); + setupReadFeedDocuments(createdDocuments, createdFeedCollection, FEED_COUNT); Thread.sleep(2 * CHANGE_FEED_PROCESSOR_TIMEOUT); validateChangeFeedProcessing(createdDocuments, receivedDocumentsByFullFidelityCfp, FEED_COUNT); @@ -462,6 +591,163 @@ public void incrementalChangeFeedModeToFullFidelityChangeFeedModeWithProcessingS } } + // Steps followed in this test + // 1. Ingest 10 documents into the feed container. + // 2. Start the LatestVersion / INCREMENTAL ChangeFeedProcessor with either startFromBeginning set to 'true' or 'false'. + // 3. Stop the LatestVersion / INCREMENTAL ChangeFeedProcessor once 5 documents are processed (startFromBeginning set to 'true') + // or 0 otherwise (stop after some delay). + // 4. Start the AllVersionsAndDeletes / FULL_FIDELITY ChangeFeedProcessor. + // 5. Validate IllegalStateException + // a) If the LatestVersion / INCREMENTAL ChangeFeedProcessor left behind a lease with a valid continuation, + // then AllVersionsAndDeletes / FULL_FIDELITY ChangeFeedProcessor should throw the exception. + // b) If not, then AllVersionsAndDeletes / FULL_FIDELITY ChangeFeedProcessor should be able to reuse the lease + // left behind and use its own continuation. + @Test(groups = { "emulator" }, dataProvider = "incrementalChangeFeedModeStartFromSetting") + public void incrementalWithPkRangeChangeFeedModeToFullFidelityChangeFeedModeWithProcessingStoppage(boolean isStartFromBeginning) throws InterruptedException, JsonProcessingException { + CosmosAsyncContainer createdFeedCollection = createFeedCollection(FEED_COLLECTION_THROUGHPUT); + CosmosAsyncContainer createdLeaseCollection = createLeaseCollection(LEASE_COLLECTION_THROUGHPUT); + + try { + List createdDocuments = new ArrayList<>(); + Map receivedDocumentsByIncrementalCfp = new ConcurrentHashMap<>(); + Map receivedDocumentsByFullFidelityCfp = new ConcurrentHashMap<>(); + + AtomicReference changeFeedProcessorInAtomicRefHolder = new AtomicReference<>(); + int docLimit = FEED_COUNT / 2; + + ChangeFeedProcessorBuilder changeFeedProcessorBuilder = new ChangeFeedProcessorBuilder() + .options(new ChangeFeedProcessorOptions() + .setStartFromBeginning(isStartFromBeginning) + .setMaxItemCount(1) + .setLeasePrefix("TEST")) + .hostName(hostName) + .feedContainer(createdFeedCollection) + .leaseContainer(createdLeaseCollection); + + changeFeedProcessorBuilder = changeFeedProcessorBuilder + .handleChanges(changeFeedProcessorHandlerForLatestVersionWithPkRange(receivedDocumentsByIncrementalCfp, docLimit, changeFeedProcessorInAtomicRefHolder)); + + ChangeFeedProcessor incrementalChangeFeedProcessor = changeFeedProcessorBuilder.buildChangeFeedProcessor(); + + changeFeedProcessorInAtomicRefHolder.set(incrementalChangeFeedProcessor); + + logger.info("Set up read feed documents"); + setupReadFeedDocuments(createdDocuments, createdFeedCollection, FEED_COUNT); + + try { + incrementalChangeFeedProcessor.start().subscribeOn(Schedulers.boundedElastic()) + .timeout(Duration.ofMillis(2 * CHANGE_FEED_PROCESSOR_TIMEOUT)) + .doOnSuccess(ignore -> logger.info("Starting INCREMENTAL ChangeFeedProcessor")) + .block(); + + // Wait for the feed processor to receive and process the documents. + Thread.sleep(2 * CHANGE_FEED_PROCESSOR_TIMEOUT); + logger.info("Validating changes now"); + + if (isStartFromBeginning) { + validateChangeFeedProcessingForLatestVersionWithPkRangeBasedLease(createdDocuments, receivedDocumentsByIncrementalCfp, docLimit); + } else { + validateChangeFeedProcessingForLatestVersionWithPkRangeBasedLease(createdDocuments, receivedDocumentsByIncrementalCfp, 0); + } + + // query for leases from the createdLeaseCollection + // String leaseQuery = "select * from c where not contains(c.id, \"info\")"; + + String leaseQuery = "select * from c"; + List leaseDocuments = + createdLeaseCollection + .queryItems(leaseQuery, JsonNode.class) + .byPage() + .blockFirst() + .getResults(); + + int leaseDocumentsWithNonNullContinuationToken = 0; + + logger.info("Lease container documents created by INCREMENTAL ChangeFeedProcessor fetched..."); + for (JsonNode lease : leaseDocuments) { + + JsonNode continuationTokenJsonNode = lease.get("ContinuationToken"); + + if (continuationTokenJsonNode != null) { + leaseDocumentsWithNonNullContinuationToken++; + + String continuationToken = continuationTokenJsonNode.asText(); + + logger.info("Lease document : {}", OBJECT_MAPPER.writeValueAsString(lease)); + logger.info("ContinuationToken : {}", continuationToken); + } else { + logger.info("Lease container document : {}", OBJECT_MAPPER.writeValueAsString(lease)); + } + } + + ChangeFeedProcessorBuilder fullFidelityChangeFeedProcessorBuilder = new ChangeFeedProcessorBuilder() + .options(new ChangeFeedProcessorOptions() + .setMaxItemCount(1) + .setLeasePrefix("TEST")) + .hostName(hostName) + .feedContainer(createdFeedCollection) + .leaseContainer(createdLeaseCollection) + .handleAllVersionsAndDeletesChanges(changeFeedProcessorHandler(receivedDocumentsByFullFidelityCfp)); + + ChangeFeedProcessor fullFidelityChangeFeedProcessor = fullFidelityChangeFeedProcessorBuilder + .buildChangeFeedProcessor(); + + if (leaseDocumentsWithNonNullContinuationToken > 0) { + assertThrows(IllegalStateException.class, () -> fullFidelityChangeFeedProcessor.start().subscribeOn(Schedulers.boundedElastic()) + .timeout(Duration.ofMillis(2 * CHANGE_FEED_PROCESSOR_TIMEOUT)) + .doOnSuccess(ignore -> logger.info("Started FULL_FIDELITY ChangeFeedProcessor")) + .block()); + + Thread.sleep(2 * CHANGE_FEED_PROCESSOR_TIMEOUT); + validateChangeFeedProcessing(createdDocuments, receivedDocumentsByFullFidelityCfp, 0); + } else { + fullFidelityChangeFeedProcessor.start().subscribeOn(Schedulers.boundedElastic()) + .timeout(Duration.ofMillis(2 * CHANGE_FEED_PROCESSOR_TIMEOUT)) + .doOnSuccess(ignore -> logger.info("Started FULL_FIDELITY ChangeFeedProcessor")) + .block(); + Thread.sleep(2 * CHANGE_FEED_PROCESSOR_TIMEOUT); + + logger.info("Set up read feed documents"); + setupReadFeedDocuments(createdDocuments, createdFeedCollection, FEED_COUNT); + + Thread.sleep(2 * CHANGE_FEED_PROCESSOR_TIMEOUT); + validateChangeFeedProcessing(createdDocuments, receivedDocumentsByFullFidelityCfp, FEED_COUNT); + + leaseDocuments = createdLeaseCollection + .queryItems(leaseQuery, JsonNode.class) + .byPage() + .blockFirst() + .getResults(); + + logger.info("Lease container documents created by FULL_FIDELITY ChangeFeedProcessor fetched..."); + for (JsonNode lease : leaseDocuments) { + + if (lease.get("ContinuationToken") != null) { + logger.info("Lease document : {}", OBJECT_MAPPER.writeValueAsString(lease)); + logger.info("ContinuationToken : {}", new String(Base64.getUrlDecoder().decode(lease.get("ContinuationToken").asText()))); + } else { + logger.info("Lease container document : {}", OBJECT_MAPPER.writeValueAsString(lease)); + } + } + } + + fullFidelityChangeFeedProcessor.stop().subscribeOn(Schedulers.boundedElastic()) + .timeout(Duration.ofMillis(2 * CHANGE_FEED_PROCESSOR_TIMEOUT)) + .block(); + + } catch (Exception ex) { + log.error("Change feed processor did not start and stopped in the expected time", ex); + throw ex; + } + + } finally { + safeDeleteCollection(createdFeedCollection); + safeDeleteCollection(createdLeaseCollection); + // Allow some time for the collections to be deleted before exiting. + Thread.sleep(500); + } + } + // Using this test to verify basic functionality @Test(groups = { "emulator" }, dataProvider = "contextTestConfigs", timeOut = 50 * CHANGE_FEED_PROCESSOR_TIMEOUT) public void fullFidelityChangeFeedProcessorStartFromContinuationToken(boolean isContextRequired) throws InterruptedException { @@ -501,7 +787,7 @@ public void fullFidelityChangeFeedProcessorStartFromContinuationToken(boolean is logger.info("Finished starting ChangeFeed processor"); - setupReadFeedDocuments(createdDocuments, receivedDocuments, createdFeedCollection, FEED_COUNT); + setupReadFeedDocuments(createdDocuments, createdFeedCollection, FEED_COUNT); logger.info("Set up read feed documents"); // Wait for the feed processor to receive and process the documents. @@ -637,7 +923,7 @@ public void getCurrentState() throws InterruptedException { // Test for "FEED_COUNT total lag - setupReadFeedDocuments(createdDocuments, receivedDocuments, createdFeedCollection, FEED_COUNT); + setupReadFeedDocuments(createdDocuments, createdFeedCollection, FEED_COUNT); cfpCurrentState = changeFeedProcessorMain.getCurrentState() .map(state -> { @@ -769,7 +1055,7 @@ public void getCurrentStateWithInsertedDocuments() throws InterruptedException { // Test for "FEED_COUNT total lag - setupReadFeedDocuments(createdDocuments, receivedDocuments, createdFeedCollection, FEED_COUNT); + setupReadFeedDocuments(createdDocuments, createdFeedCollection, FEED_COUNT); // Waiting for change feed processor to process documents Thread.sleep(2 * CHANGE_FEED_PROCESSOR_TIMEOUT); @@ -819,7 +1105,7 @@ public void getCurrentStateWithInsertedDocuments() throws InterruptedException { Thread.sleep(2 * CHANGE_FEED_PROCESSOR_TIMEOUT); // Test for "FEED_COUNT total lag - setupReadFeedDocuments(createdDocuments, receivedDocuments, createdFeedCollection, FEED_COUNT); + setupReadFeedDocuments(createdDocuments, createdFeedCollection, FEED_COUNT); cfpCurrentState = changeFeedProcessorMain.getCurrentState() .map(state -> { @@ -1179,7 +1465,7 @@ public void inactiveOwnersRecovery() throws InterruptedException { throw ex; } - setupReadFeedDocuments(createdDocuments, receivedDocuments, createdFeedCollection, FEED_COUNT); + setupReadFeedDocuments(createdDocuments, createdFeedCollection, FEED_COUNT); // Wait for the feed processor to receive and process the documents. Thread.sleep(2 * CHANGE_FEED_PROCESSOR_TIMEOUT); @@ -1218,7 +1504,7 @@ public void inactiveOwnersRecovery() throws InterruptedException { createdDocuments.clear(); receivedDocuments.clear(); - setupReadFeedDocuments(createdDocuments, receivedDocuments, createdFeedCollection, FEED_COUNT); + setupReadFeedDocuments(createdDocuments, createdFeedCollection, FEED_COUNT); // Wait for the feed processor to receive and process the documents. Thread.sleep(2 * CHANGE_FEED_PROCESSOR_TIMEOUT); @@ -1279,7 +1565,7 @@ public void endToEndTimeoutConfigShouldBeSuppressed() throws InterruptedExceptio logger.info("Finished starting ChangeFeed processor"); - setupReadFeedDocuments(createdDocuments, receivedDocuments, createdFeedCollection, FEED_COUNT); + setupReadFeedDocuments(createdDocuments, createdFeedCollection, FEED_COUNT); logger.info("Set up read feed documents"); // Wait for the feed processor to receive and process the documents. @@ -1402,7 +1688,7 @@ public void readFeedDocumentsAfterSplit(boolean isContextRequired) throws Interr Thread.sleep(2 * CHANGE_FEED_PROCESSOR_TIMEOUT); // generate a first batch of documents on the feed collection to be split - setupReadFeedDocuments(createdDocuments, receivedDocuments, createdFeedCollectionForSplit, FEED_COUNT); + setupReadFeedDocuments(createdDocuments, createdFeedCollectionForSplit, FEED_COUNT); // this call populates the pkRangeCache being the first data-plane request // this will force using a stale pkRangeCache @@ -1623,7 +1909,7 @@ public void fullFidelityChangeFeedProcessorWithThroughputControl(boolean isConte logger.info("Finished starting ChangeFeed processor"); - setupReadFeedDocuments(createdDocuments, receivedDocuments, createdFeedCollection, feedCount); + setupReadFeedDocuments(createdDocuments, createdFeedCollection, feedCount); logger.info("Set up read feed documents"); // Wait for the feed processor to receive and process the documents. @@ -1680,6 +1966,15 @@ private Consumer> changeFeedProcessorHandler(Map> changeFeedProcessorHandlerForLatestVersionWithPkRangeLease(Map receivedDocuments) { + return docs -> { + logger.info("START processing from thread in test {}", Thread.currentThread().getId()); + for (JsonNode item : docs) { + processItem(item, receivedDocuments); + } + logger.info("END processing from thread {}", Thread.currentThread().getId()); + }; + } private Consumer> changeFeedProcessorHandler( Map receivedDocuments, int documentLimit, @@ -1700,6 +1995,27 @@ private Consumer> changeFeedProcessorHandler( }; } + private Consumer> changeFeedProcessorHandlerForLatestVersionWithPkRange( + Map receivedDocuments, + int documentLimit, + AtomicReference changeFeedProcessorAtomicReference) { + return docs -> { + logger.info("START processing from thread in test {}", Thread.currentThread().getId()); + + if (receivedDocuments.size() >= documentLimit) { + logger.info("Processed {} documents which is the document limit, stopping the change feed processor", receivedDocuments.size()); + stopChangeFeedProcessor(changeFeedProcessorAtomicReference.get()); + return; + } + + for (JsonNode item : docs) { + processItem(item, receivedDocuments); + } + logger.info("END processing from thread {}", Thread.currentThread().getId()); + }; + } + + private BiConsumer, ChangeFeedProcessorContext> changeFeedProcessorHandlerWithContext( Map receivedDocuments, Set receivedLeaseTokensFromContext) { return (docs, context) -> { @@ -1727,6 +2043,20 @@ void validateChangeFeedProcessing(List createdDocuments, } } + void validateChangeFeedProcessingForLatestVersionWithPkRangeBasedLease(List createdDocuments, + Map receivedDocuments, + int expectedFeedCount) { + + // Added this validation for now to verify received list has something - easy way to see size not being 10 + assertThat(receivedDocuments.size()).isEqualTo(expectedFeedCount); + + Set createdDocIds = createdDocuments.stream().map(createdDocument -> createdDocument.get("id").toString()).collect(Collectors.toSet()); + + for (JsonNode item : receivedDocuments.values()) { + assertThat(createdDocIds.contains(item.get("id").asText())).as("Document with getId: " + item.get("id").asText()).isTrue(); + } + } + void validateChangeFeedProcessing( ChangeFeedProcessor changeFeedProcessor, @@ -1811,7 +2141,7 @@ public void afterClass() { safeClose(client); } - private void setupReadFeedDocuments(List createdDocuments, Map receivedDocuments, CosmosAsyncContainer feedCollection, long count) { + private void setupReadFeedDocuments(List createdDocuments, CosmosAsyncContainer feedCollection, long count) { List docDefList = new ArrayList<>(); for(int i = 0; i < count; i++) { @@ -1922,6 +2252,11 @@ private static synchronized void processItem(ChangeFeedProcessorItem item, Map receivedDocuments) { + log.info("RECEIVED {}", item); + receivedDocuments.put(item.get("id").asText(), item); + } + private static synchronized void processChangeFeedProcessorContext( ChangeFeedProcessorContext context, Set receivedLeaseTokens) { diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/changefeed/epkversion/IncrementalChangeFeedProcessorTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/changefeed/epkversion/IncrementalChangeFeedProcessorTest.java index c9693cc61931..653cdba46b08 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/changefeed/epkversion/IncrementalChangeFeedProcessorTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/changefeed/epkversion/IncrementalChangeFeedProcessorTest.java @@ -64,6 +64,7 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; +import org.testng.annotations.Ignore; import org.testng.annotations.Test; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -1093,7 +1094,8 @@ public void ownerNullAcquiring() throws InterruptedException { } } - @Test(groups = { "cfp-split" }, dataProvider = "throughputControlArgProvider", timeOut = 160 * CHANGE_FEED_PROCESSOR_TIMEOUT) + // TODO reenable when investigating/fixing https://github.com/Azure/azure-sdk-for-java/issues/44115 + @Test(groups = { "cfp-split" }, dataProvider = "throughputControlArgProvider", timeOut = 160 * CHANGE_FEED_PROCESSOR_TIMEOUT, enabled = false) public void readFeedDocumentsAfterSplit(boolean throughputControlEnabled) throws InterruptedException { CosmosAsyncContainer createdFeedCollectionForSplit = createFeedCollection(FEED_COLLECTION_THROUGHPUT); CosmosAsyncContainer createdLeaseCollection = createLeaseCollection(2 * LEASE_COLLECTION_THROUGHPUT); @@ -1894,7 +1896,10 @@ public void incrementalChangeFeedModeToFullFidelityChangeFeedMode(boolean isStar Map receivedDocumentsByFullFidelityCfp = new ConcurrentHashMap<>(); ChangeFeedProcessorBuilder changeFeedProcessorBuilder = new ChangeFeedProcessorBuilder() - .options(new ChangeFeedProcessorOptions().setStartFromBeginning(isStartFromBeginning).setMaxItemCount(10)) + .options(new ChangeFeedProcessorOptions() + .setStartFromBeginning(isStartFromBeginning) + .setMaxItemCount(10) + .setLeasePrefix("TEST")) .hostName(hostName) .feedContainer(createdFeedCollection) .leaseContainer(createdLeaseCollection); @@ -1947,7 +1952,9 @@ public void incrementalChangeFeedModeToFullFidelityChangeFeedMode(boolean isStar } ChangeFeedProcessorBuilder fullFidelityChangeFeedProcessorBuilder = new ChangeFeedProcessorBuilder() - .options(new ChangeFeedProcessorOptions().setMaxItemCount(1)) + .options(new ChangeFeedProcessorOptions() + .setMaxItemCount(1) + .setLeasePrefix("TEST")) .hostName(hostName) .feedContainer(createdFeedCollection) .leaseContainer(createdLeaseCollection) diff --git a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/changefeed/pkversion/IncrementalChangeFeedProcessorTest.java b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/changefeed/pkversion/IncrementalChangeFeedProcessorTest.java index 0f0ab04840e1..10544acdde0b 100644 --- a/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/changefeed/pkversion/IncrementalChangeFeedProcessorTest.java +++ b/sdk/cosmos/azure-cosmos-tests/src/test/java/com/azure/cosmos/rx/changefeed/pkversion/IncrementalChangeFeedProcessorTest.java @@ -21,6 +21,7 @@ import com.azure.cosmos.implementation.Utils; import com.azure.cosmos.implementation.changefeed.pkversion.ServiceItemLease; import com.azure.cosmos.implementation.directconnectivity.ReflectionUtils; +import com.azure.cosmos.models.ChangeFeedProcessorItem; import com.azure.cosmos.models.ChangeFeedProcessorOptions; import com.azure.cosmos.models.ChangeFeedProcessorState; import com.azure.cosmos.models.CosmosContainerProperties; @@ -37,6 +38,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.NullNode; import org.apache.commons.lang3.RandomStringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -46,6 +48,7 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; +import org.testng.annotations.Ignore; import org.testng.annotations.Test; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -58,19 +61,23 @@ import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Arrays; +import java.util.Base64; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; +import java.util.stream.Collectors; import static com.azure.cosmos.BridgeInternal.extractContainerSelfLink; import static com.azure.cosmos.CosmosBridgeInternal.getContextClient; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; +import static org.testng.Assert.assertThrows; public class IncrementalChangeFeedProcessorTest extends TestSuiteBase { private final static Logger log = LoggerFactory.getLogger(IncrementalChangeFeedProcessorTest.class); @@ -103,6 +110,11 @@ public static Object[][] throughputControlConfigArgProvider() { }; } + @DataProvider + public Object[] incrementalChangeFeedModeStartFromSetting() { + return new Object[] { true, false }; + } + @Factory(dataProvider = "clientBuilders") public IncrementalChangeFeedProcessorTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); @@ -1217,7 +1229,8 @@ public void ownerNullAcquiring() throws InterruptedException { } } - @Test(groups = { "cfp-split" }, dataProvider = "throughputControlConfigArgProvider", timeOut = 160 * CHANGE_FEED_PROCESSOR_TIMEOUT) + // TODO reenable when investigating/fixing https://github.com/Azure/azure-sdk-for-java/issues/44115 + @Test(groups = { "cfp-split" }, dataProvider = "throughputControlConfigArgProvider", timeOut = 160 * CHANGE_FEED_PROCESSOR_TIMEOUT, enabled = false) public void readFeedDocumentsAfterSplit(boolean throughputControlConfigEnabled) throws InterruptedException { CosmosAsyncContainer createdFeedCollectionForSplit = createFeedCollection(FEED_COLLECTION_THROUGHPUT); CosmosAsyncContainer createdLeaseCollection = createLeaseCollection(2 * LEASE_COLLECTION_THROUGHPUT); @@ -1898,6 +1911,156 @@ public void readFeedDocumentsWithThroughputControl() throws InterruptedException } } + // Steps followed in this test + // 1. Ingest 10 documents into the feed container. + // 2. Start the LatestVersion / INCREMENTAL ChangeFeedProcessor with either startFromBeginning set to 'true' or 'false'. + // 3. Stop the LatestVersion / INCREMENTAL ChangeFeedProcessor once the 10 documents are processed or 0 documents are processed (stop after some delay). + // 4. Start the AllVersionsAndDeletes / FULL_FIDELITY ChangeFeedProcessor. + // 5. Validate IllegalStateException + // a) If the LatestVersion / INCREMENTAL ChangeFeedProcessor left behind a lease with a valid continuation, + // then AllVersionsAndDeletes / FULL_FIDELITY ChangeFeedProcessor should throw the exception. + // b) If not, then AllVersionsAndDeletes / FULL_FIDELITY ChangeFeedProcessor should be able to reuse the lease + // left behind and use its own continuation. + @Test(groups = { "query" }, dataProvider = "incrementalChangeFeedModeStartFromSetting") + public void incrementalChangeFeedModeToFullFidelityChangeFeedMode(boolean isStartFromBeginning) throws InterruptedException, JsonProcessingException { + CosmosAsyncContainer createdFeedCollection = createFeedCollection(FEED_COLLECTION_THROUGHPUT); + CosmosAsyncContainer createdLeaseCollection = createLeaseCollection(LEASE_COLLECTION_THROUGHPUT); + + try { + List createdDocuments = new ArrayList<>(); + Map receivedDocumentsByIncrementalCfp = new ConcurrentHashMap<>(); + Map receivedDocumentsByFullFidelityCfp = new ConcurrentHashMap<>(); + + ChangeFeedProcessorBuilder changeFeedProcessorBuilder = new ChangeFeedProcessorBuilder() + .options(new ChangeFeedProcessorOptions() + .setStartFromBeginning(isStartFromBeginning) + .setMaxItemCount(10) + .setLeasePrefix("TEST")) + .hostName(hostName) + .feedContainer(createdFeedCollection) + .leaseContainer(createdLeaseCollection); + + changeFeedProcessorBuilder = changeFeedProcessorBuilder + .handleChanges(changeFeedProcessorHandler(receivedDocumentsByIncrementalCfp)); + + ChangeFeedProcessor incrementalChangeFeedProcessor = changeFeedProcessorBuilder.buildChangeFeedProcessor(); + + logger.info("Set up read feed documents"); + setupReadFeedDocuments(createdDocuments, receivedDocumentsByIncrementalCfp, createdFeedCollection, FEED_COUNT); + + try { + if (isStartFromBeginning) { + validateChangeFeedProcessing( + incrementalChangeFeedProcessor, + createdDocuments, + receivedDocumentsByIncrementalCfp, + 2 * CHANGE_FEED_PROCESSOR_TIMEOUT); + } else { + validateChangeFeedProcessing( + incrementalChangeFeedProcessor, + new ArrayList<>(), + receivedDocumentsByIncrementalCfp, + 2 * CHANGE_FEED_PROCESSOR_TIMEOUT); + } + + String leaseQuery = "select * from c"; + List leaseDocuments = + createdLeaseCollection + .queryItems(leaseQuery, JsonNode.class) + .byPage() + .blockFirst() + .getResults(); + + int leaseDocumentsWithNonNullContinuationToken = 0; + + logger.info("Leases container documents created by INCREMENTAL ChangeFeedProcessor fetched..."); + for (JsonNode lease : leaseDocuments) { + + JsonNode continuationTokenJsonNode = lease.get("ContinuationToken"); + + if (continuationTokenJsonNode != null) { + leaseDocumentsWithNonNullContinuationToken++; + + String continuationToken = continuationTokenJsonNode.asText(); + + logger.info("Lease document : {}", OBJECT_MAPPER.writeValueAsString(lease)); + logger.info("ContinuationToken : {}", continuationToken); + } else { + logger.info("Lease container document : {}", OBJECT_MAPPER.writeValueAsString(lease)); + } + } + + ChangeFeedProcessorBuilder fullFidelityChangeFeedProcessorBuilder = new ChangeFeedProcessorBuilder() + .options(new ChangeFeedProcessorOptions() + .setMaxItemCount(1) + .setLeasePrefix("TEST")) + .hostName(hostName) + .feedContainer(createdFeedCollection) + .leaseContainer(createdLeaseCollection) + .handleAllVersionsAndDeletesChanges(changeFeedProcessorHandlerForAllVersionsAndDeletes(receivedDocumentsByFullFidelityCfp)); + + ChangeFeedProcessor fullFidelityChangeFeedProcessor = fullFidelityChangeFeedProcessorBuilder + .buildChangeFeedProcessor(); + + if (leaseDocumentsWithNonNullContinuationToken > 0) { + assertThrows(IllegalStateException.class, () -> fullFidelityChangeFeedProcessor.start().subscribeOn(Schedulers.boundedElastic()) + .timeout(Duration.ofMillis(2 * CHANGE_FEED_PROCESSOR_TIMEOUT)) + .block()); + } else { + + fullFidelityChangeFeedProcessor.start().subscribeOn(Schedulers.boundedElastic()) + .timeout(Duration.ofMillis(2 * CHANGE_FEED_PROCESSOR_TIMEOUT)) + .doOnSuccess(ignore -> logger.info("Started FULL_FIDELITY ChangeFeedProcessor successfully!")) + .block(); + + createdDocuments = new ArrayList<>(); + + // wait for FULL_FIDELITY ChangeFeedProcessor to start and acquire left behind lease + Thread.sleep(2 * CHANGE_FEED_PROCESSOR_TIMEOUT); + + setupReadFeedDocumentsForAllVersionsAndDeletes(createdDocuments, receivedDocumentsByFullFidelityCfp, createdFeedCollection, 10); + + // wait for FULL_FIDELITY ChangeFeedProcessor to process all ingested documents + Thread.sleep(2 * CHANGE_FEED_PROCESSOR_TIMEOUT); + + fullFidelityChangeFeedProcessor.stop().subscribeOn(Schedulers.boundedElastic()) + .timeout(Duration.ofMillis(2 * CHANGE_FEED_PROCESSOR_TIMEOUT)) + .block(); + + validateChangeFeedProcessing(createdDocuments, receivedDocumentsByFullFidelityCfp, FEED_COUNT); + + leaseDocuments = + createdLeaseCollection + .queryItems(leaseQuery, JsonNode.class) + .byPage() + .blockLast() + .getResults(); + + logger.info("Leases container documents fetched after starting FULL_FIDELITY ChangeFeedProcessor..."); + for (JsonNode lease : leaseDocuments) { + + if (lease.get("ContinuationToken") != null) { + logger.info("Lease document : {}", OBJECT_MAPPER.writeValueAsString(lease)); + logger.info("ContinuationToken : {}", new String(Base64.getUrlDecoder().decode(lease.get("ContinuationToken").asText()))); + } else { + logger.info("Lease container document : {}", OBJECT_MAPPER.writeValueAsString(lease)); + } + } + } + + } catch (Exception ex) { + logger.error("Change feed processor did not start and stopped in the expected time", ex); + throw ex; + } + + } finally { + safeDeleteCollection(createdFeedCollection); + safeDeleteCollection(createdLeaseCollection); + // Allow some time for the collections to be deleted before exiting. + Thread.sleep(500); + } + } + void validateChangeFeedProcessing(ChangeFeedProcessor changeFeedProcessor, List createdDocuments, Map receivedDocuments, int sleepTime) throws InterruptedException { try { changeFeedProcessor.start().subscribeOn(Schedulers.boundedElastic()) @@ -1938,6 +2101,22 @@ void validateChangeFeedProcessing(ChangeFeedProcessor changeFeedProcessor, List< } } + void validateChangeFeedProcessing(List createdDocuments, + Map receivedDocuments, + int expectedFeedCount) { + + // Added this validation for now to verify received list has something - easy way to see size not being 10 + assertThat(receivedDocuments.size()).isEqualTo(expectedFeedCount); + + Set createdDocIds = + createdDocuments.stream() + .map(createdDocument -> createdDocument.get("id").toString()).collect(Collectors.toSet()); + + for (ChangeFeedProcessorItem item : receivedDocuments.values()) { + assertThat(createdDocIds.contains(item.toJsonNode().get("id").asText())).as("Document with getId: " + item.toJsonNode().get("id").asText()).isTrue(); + } + } + private Consumer> changeFeedProcessorHandler(Map receivedDocuments) { return changeFeedProcessorHandlerWithCallback(receivedDocuments, null); } @@ -1964,6 +2143,16 @@ private Consumer> changeFeedProcessorHandlerWithCallback( }; } + private Consumer> changeFeedProcessorHandlerForAllVersionsAndDeletes(Map receivedDocuments) { + return docs -> { + + log.info("START processing from thread in test {}", Thread.currentThread().getId()); + for (ChangeFeedProcessorItem item : docs) { + processItem(item, receivedDocuments); + } + log.info("END processing from thread {}", Thread.currentThread().getId()); + }; } + private void waitToReceiveDocuments(Map receivedDocuments, long timeoutInMillisecond, long count) throws InterruptedException { long remainingWork = timeoutInMillisecond; while (remainingWork > 0 && receivedDocuments.size() < count) { @@ -2076,6 +2265,18 @@ private void setupReadFeedDocuments(List createdDocuments, M waitIfNeededForReplicasToCatchUp(getClientBuilder()); } + private void setupReadFeedDocumentsForAllVersionsAndDeletes(List createdDocuments, Map receivedDocuments, CosmosAsyncContainer feedCollection, long count) { + List docDefList = new ArrayList<>(); + + for(int i = 0; i < count; i++) { + docDefList.add(getDocumentDefinition()); + } + + createdDocuments.addAll(bulkInsertBlocking(feedCollection, docDefList)); + waitIfNeededForReplicasToCatchUp(getClientBuilder()); + } + + private void createReadFeedDocuments(List createdDocuments, CosmosAsyncContainer feedCollection, long count) { List docDefList = new ArrayList<>(); @@ -2137,6 +2338,16 @@ private static synchronized void processItem(JsonNode item, Map receivedDocuments) { + try { + IncrementalChangeFeedProcessorTest.log + .info("RECEIVED {}", OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(item)); + } catch (JsonProcessingException e) { + log.error("Failure in processing json [{}]", e.getMessage(), e); + } + receivedDocuments.put(item.toJsonNode().get("id").asText(), item); + } + class LeaseStateMonitor { public Map receivedLeases = new ConcurrentHashMap<>(); public volatile boolean isAfterLeaseInitialization = false; diff --git a/sdk/cosmos/azure-cosmos/CHANGELOG.md b/sdk/cosmos/azure-cosmos/CHANGELOG.md index 530f017b2133..0ca7600740e1 100644 --- a/sdk/cosmos/azure-cosmos/CHANGELOG.md +++ b/sdk/cosmos/azure-cosmos/CHANGELOG.md @@ -1,15 +1,31 @@ ## Release History -### 4.67.0-beta.1 (Unreleased) +### 4.68.0-beta.1 (Unreleased) #### Features Added #### Breaking Changes #### Bugs Fixed +* Fixed applications possibly not closing gracefully due to thread `partition-availability-staleness-check` not being a daemon thread. - [PR 44441](https://github.com/Azure/azure-sdk-for-java/pull/44441). + +#### Other Changes + +### 4.67.0 (2025-02-20) + +#### Other Changes +* Block `ChangeFeedProcessor` from starting by throwing an `IllegalStateException` when the lease container contains leases with the same lease prefix but different `ChangeFeedMode` - [PR 43798](https://github.com/Azure/azure-sdk-for-java/pull/43798). + +### 4.66.1 (2025-02-08) + +#### Bugs Fixed +* Fixed an issue in change feed processor where records are skipped and excessive requests are prefetched. - See [PR 43788](https://github.com/Azure/azure-sdk-for-java/pull/43788) +* Fixed small perf overhead due to NPE for readItem returning 404. - See [PR 44008](https://github.com/Azure/azure-sdk-for-java/pull/44008) +* Perform cross-region retry for `Document` reads when enclosing address requests hit request timeouts (408:10002). - See [PR 43937](https://github.com/Azure/azure-sdk-for-java/pull/43937) #### Other Changes * Added temporary internal-only option to enable thin client mode with system property COSMOS.THINCLIENT_ENABLED, setting the thin client endpoint with system property COSMOS.THINCLIENT_ENDPOINT, and default thin client endpoint with system property COSMOS.DEFAULT_THINCLIENT_ENDPOINT while the thin-client transport is still under development. This transport mode is not yet supported or ready to be used by external customers. Please don't use these configs in any production scenario yet. - [PR 43188](https://github.com/Azure/azure-sdk-for-java/pull/43188) +* Added a system property `COSMOS.ITEM_SERIALIZATION_INCLUSION_MODE` (environment variable `COSMOS_ITEM_SERIALIZATION_INCLUSION_MODE`) that allows customizing (`Always`, `NonNull`, `NonEmpty`, `NonDefault`) the JSON serialization inclusion mode when serializing items/documents. - See [PR 44035](https://github.com/Azure/azure-sdk-for-java/pull/44035) and [PR 44114](https://github.com/Azure/azure-sdk-for-java/pull/44114) ### 4.66.0 (2025-01-14) diff --git a/sdk/cosmos/azure-cosmos/README.md b/sdk/cosmos/azure-cosmos/README.md index bad4ebf4a76f..7b7b1322395c 100644 --- a/sdk/cosmos/azure-cosmos/README.md +++ b/sdk/cosmos/azure-cosmos/README.md @@ -286,7 +286,7 @@ or contact [opencode@microsoft.com][coc_contact] with any additional questions o [source_code]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/cosmos/azure-cosmos/src [cosmos_introduction]: https://learn.microsoft.com/azure/cosmos-db/ -[api_documentation]: https://azuresdkdocs.blob.core.windows.net/$web/java/azure-cosmos/latest/index.html +[api_documentation]: https://azuresdkdocs.z19.web.core.windows.net/java/azure-cosmos/latest/index.html [cosmos_docs]: https://learn.microsoft.com/azure/cosmos-db/introduction [jdk]: https://learn.microsoft.com/java/azure/jdk/ [slf4j]: http://www.slf4j.org/ @@ -307,4 +307,5 @@ or contact [opencode@microsoft.com][coc_contact] with any additional questions o [quickstart]: https://learn.microsoft.com/azure/cosmos-db/create-sql-api-java?tabs=sync [project_reactor_schedulers]: https://projectreactor.io/docs/core/release/api/reactor/core/scheduler/Schedulers.html -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcosmos%2Fazure-cosmos%2FREADME.png) + + diff --git a/sdk/cosmos/azure-cosmos/pom.xml b/sdk/cosmos/azure-cosmos/pom.xml index 5d87c3560440..88a6e0a791b4 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.67.0-beta.1 + 4.68.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 @@ -67,12 +67,12 @@ Licensed under the MIT License. com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure @@ -143,7 +143,7 @@ Licensed under the MIT License. org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 unit diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/BridgeInternal.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/BridgeInternal.java index 8a78789f1c53..5b9ae199b94e 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/BridgeInternal.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/BridgeInternal.java @@ -406,8 +406,8 @@ public static CosmosException createCosmosException(int statusCode, String error cosmosException.setError(new CosmosError()); cosmosException.getError().set( Constants.Properties.MESSAGE, - errorMessage, - CosmosItemSerializer.DEFAULT_SERIALIZER); + errorMessage + ); return cosmosException; } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosDiagnostics.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosDiagnostics.java index 0c565330ecf5..4642652800f3 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosDiagnostics.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosDiagnostics.java @@ -10,7 +10,7 @@ import com.azure.cosmos.implementation.RxDocumentServiceRequest; import com.azure.cosmos.implementation.SerializationDiagnosticsContext; import com.azure.cosmos.implementation.guava25.collect.ImmutableList; -import com.azure.cosmos.implementation.routing.LocationCache; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; import com.azure.cosmos.util.Beta; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.core.JsonProcessingException; @@ -331,7 +331,7 @@ String getFirstContactedRegion() { return this.clientSideRequestStatistics.getFirstContactedRegion(); } - LocationCache.ConsolidatedRegionalEndpoint getFirstContactedLocationEndpoint() { + RegionalRoutingContext getFirstContactedLocationEndpoint() { return this.clientSideRequestStatistics.getFirstContactedLocationEndpoint(); } @@ -479,7 +479,7 @@ public void setDiagnosticsContext(CosmosDiagnostics cosmosDiagnostics, CosmosDia } @Override - public LocationCache.ConsolidatedRegionalEndpoint getFirstContactedLocationEndpoint(CosmosDiagnostics cosmosDiagnostics) { + public RegionalRoutingContext getFirstContactedLocationEndpoint(CosmosDiagnostics cosmosDiagnostics) { if (cosmosDiagnostics == null) { return null; diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosException.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosException.java index 0cf4870cf485..5d4731cef122 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosException.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosException.java @@ -21,7 +21,6 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import java.time.Duration; -import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -185,7 +184,7 @@ protected CosmosException(int statusCode, String message, Map re protected CosmosException(int statusCode, String errorMessage) { this(statusCode, errorMessage, null, null); this.cosmosError = new CosmosError(); - cosmosError.set(Constants.Properties.MESSAGE, errorMessage, CosmosItemSerializer.DEFAULT_SERIALIZER); + cosmosError.set(Constants.Properties.MESSAGE, errorMessage); } /** diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosItemSerializer.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosItemSerializer.java index c9592a16ace8..f66dff9a21c1 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosItemSerializer.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosItemSerializer.java @@ -8,6 +8,7 @@ import com.azure.cosmos.implementation.Configs; import com.azure.cosmos.implementation.ConnectionPolicy; import com.azure.cosmos.implementation.CosmosClientMetadataCachesSnapshot; +import com.azure.cosmos.implementation.DefaultCosmosItemSerializer; import com.azure.cosmos.implementation.HttpConstants; import com.azure.cosmos.implementation.ImplementationBridgeHelpers; import com.azure.cosmos.implementation.JsonSerializable; @@ -21,30 +22,30 @@ import java.io.IOException; import java.util.Map; +import static com.azure.cosmos.implementation.guava25.base.Preconditions.checkNotNull; + /** * The {@link CosmosItemSerializer} allows customizing the serialization of Cosmos Items - either to transform payload (for * example wrap/unwrap in custom envelopes) or use custom serialization settings or json serializer stacks. */ public abstract class CosmosItemSerializer { - private final static ObjectMapper objectMapper = Utils.getSimpleObjectMapper(); + /** * Gets the default Cosmos item serializer. This serializer is used by default when no custom serializer is * specified on request options or the {@link CosmosClientBuilder} */ - public final static CosmosItemSerializer DEFAULT_SERIALIZER = new DefaultCosmosItemSerializer(); + public final static CosmosItemSerializer DEFAULT_SERIALIZER = DefaultCosmosItemSerializer.DEFAULT_SERIALIZER; private boolean shouldWrapSerializationExceptions; + private ObjectMapper mapper = Utils.getSimpleObjectMapper(); + /** * Used to instantiate subclasses */ protected CosmosItemSerializer() { - this(true); - } - - CosmosItemSerializer(boolean shouldWrapSerializationExceptions) { - this.shouldWrapSerializationExceptions = shouldWrapSerializationExceptions; + this.shouldWrapSerializationExceptions = true; } /** @@ -81,6 +82,14 @@ Map serializeSafe(T item) { } } + ObjectMapper getItemObjectMapper() { + return this.mapper; + } + + void setItemObjectMapper(ObjectMapper newMapper) { + this.mapper = newMapper; + } + /** * Used to deserialize the json tree stored in the Cosmos DB item as a POJO * @param jsonNodeMap the json tree from the Cosmos DB item @@ -121,80 +130,6 @@ void setShouldWrapSerializationExceptions(boolean enabled) { this.shouldWrapSerializationExceptions = enabled; } - private static class DefaultCosmosItemSerializer extends CosmosItemSerializer { - DefaultCosmosItemSerializer() { - super(false); - } - - /** - * Used to serialize a POJO into a json tree - * @param item the POJO to be serialized - * @return the json tree that will be used as payload in Cosmos DB items - * @param The type of the POJO - */ - @Override - @SuppressWarnings("unchecked") - public Map serialize(T item) { - if (item == null) { - return null; - } - - if (item instanceof ObjectNode) { - return new ObjectNodeMap((ObjectNode)item); - } - - if (item instanceof JsonSerializable) { - return ((JsonSerializable)item).getMap(); - } - - JsonNode jsonNode = objectMapper.convertValue(item, JsonNode.class); - if (jsonNode == null) { - return null; - } - - if (jsonNode.isObject()) { - return new ObjectNodeMap((ObjectNode)jsonNode); - } - - return new PrimitiveJsonNodeMap(jsonNode); - } - - /** - * Used to deserialize the json tree stored in the Cosmos DB item as a POJO - * @param jsonNodeMap the json tree from the Cosmos DB item - * @param classType The type of the POJO - * @return The deserialized POJO - * @param The type of the POJO - */ - @Override - @SuppressWarnings("unchecked") - public T deserialize(Map jsonNodeMap, Class classType) { - if (jsonNodeMap == null) { - return null; - } - - ObjectNode jsonNode = null; - try { - if (jsonNodeMap instanceof ObjectNodeMap) { - jsonNode = ((ObjectNodeMap)jsonNodeMap).getObjectNode(); - } else if (jsonNodeMap instanceof PrimitiveJsonNodeMap) { - return objectMapper.convertValue( - ((PrimitiveJsonNodeMap)jsonNodeMap).getPrimitiveJsonNode(), - classType); - } else { - jsonNode = objectMapper.convertValue(jsonNodeMap, ObjectNode.class); - } - - if (JsonSerializable.class.isAssignableFrom(classType)) { - return (T)JsonSerializable.instantiateFromObjectNodeAndType(jsonNode, classType); - } - - return objectMapper.treeToValue(jsonNode, classType); - } catch (IOException e) { - throw new IllegalStateException(String.format("Unable to parse JSON %s as %s", jsonNode, classType.getName()), e); - } - } - } /////////////////////////////////////////////////////////////////////////////////////////// // the following helper/accessor only helps to access this class outside of this package.// @@ -216,6 +151,16 @@ public T deserializeSafe(CosmosItemSerializer serializer, Map shouldRetry(Exception e) { isReadRequest, canUseMultipleWriteLocations, e); - if (this.locationEndpoint == null || this.consolidatedRegionalEndpoint == null) { + if (this.regionalRoutingContext == null) { // on before request is not invoked because Document Service Request creation failed. - logger.error("locationEndpoint is null because ClientRetryPolicy::onBeforeRequest(.) is not invoked, " + + logger.error("regionalRoutingContext is null because ClientRetryPolicy::onBeforeRequest(.) is not invoked, " + "probably request creation failed due to invalid options, serialization setting, etc."); return Mono.just(ShouldRetryResult.error(e)); } @@ -199,29 +198,29 @@ public Mono shouldRetry(Exception e) { return this.throttlingRetry.shouldRetry(e); } - private boolean canGatewayRequestFailoverOnTimeout(RxDocumentServiceRequest request) { - //Query Plan requests + private boolean canRequestToGatewayBeSafelyRetriedOnReadTimeout(RxDocumentServiceRequest request) { + + // QueryPlan requests can be safely retried on GW read timeouts if(request.getOperationType() == OperationType.QueryPlan) { return true; } - //Meta data request check boolean isMetaDataRequest = request.isMetadataRequest(); - //Meta Data Read - if(isMetaDataRequest && request.isReadOnly()) { + // Metadata read requests can be safely retried on GW read timeouts + if (isMetaDataRequest && request.isReadOnly()) { return true; } - //Data Plane Read - if(!isMetaDataRequest - && !request.isAddressRefresh() - && request.isReadOnly()) { - return true; - } - - return false; - } + // Document requests encapsulate address resolution to the Gateway + // Address resolution flows are present in GatewayAddressCache and use MetadataRequestRetryPolicy & OpenConnectionAndInitCachesRetryPolicy + // Address resolution flows are retried in a purely region-scoped manner by the above retry policies as addresses are unique to a partition-region combo + // If flow of control has reached here - we are at the level of the 'Document' request which ideally can be retried on + // a different region for Document reads + // For Document writes being retried on a different region there is no guarantee of idempotency as isAddressRefresh property + // on RxDocumentServiceRequest instance is not set back to false after address resolution completes so hard to stay what stage timed out - address resolution or the Document write + return request.isReadOnly(); + } private ShouldRetryResult shouldRetryOnSessionNotAvailable(RxDocumentServiceRequest request) { this.sessionTokenRetryCount++; @@ -231,7 +230,7 @@ private ShouldRetryResult shouldRetryOnSessionNotAvailable(RxDocumentServiceRequ return ShouldRetryResult.noRetry(); } else { if (this.canUseMultipleWriteLocations) { - UnmodifiableList endpoints = + UnmodifiableList endpoints = this.isReadRequest ? this.globalEndpointManager.getApplicableReadEndpoints(request) : this.globalEndpointManager.getApplicableWriteEndpoints(request); @@ -304,14 +303,14 @@ private Mono shouldRetryOnEndpointFailureAsync(boolean isRead private Mono shouldRetryOnGatewayTimeout() { - boolean canFailoverOnTimeout = canGatewayRequestFailoverOnTimeout(this.request); + boolean canPerformCrossRegionRetryOnGatewayReadTimeout = canRequestToGatewayBeSafelyRetriedOnReadTimeout(this.request); if (this.globalPartitionEndpointManagerForCircuitBreaker.isPartitionLevelCircuitBreakingApplicable(this.request)) { - this.globalPartitionEndpointManagerForCircuitBreaker.handleLocationExceptionForPartitionKeyRange(this.request, this.request.requestContext.consolidatedRegionalEndpointToRoute); + this.globalPartitionEndpointManagerForCircuitBreaker.handleLocationExceptionForPartitionKeyRange(this.request, this.request.requestContext.regionalRoutingContextToRoute); } //if operation is data plane read, metadata read, or query plan it can be retried on a different endpoint. - if (canFailoverOnTimeout) { + if (canPerformCrossRegionRetryOnGatewayReadTimeout) { if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) { logger.warn("shouldRetryOnHttpTimeout() Not retrying. Retry count = {}", this.failoverRetryCount); return Mono.just(ShouldRetryResult.noRetry()); @@ -339,12 +338,15 @@ private Mono refreshLocation(boolean isReadRequest, boolean forceRefresh, this.failoverRetryCount++; // Mark the current read endpoint as unavailable + + URI gatewayRegionalEndpoint = this.regionalRoutingContext.getGatewayRegionalEndpoint(); + if (isReadRequest) { - logger.warn("marking the endpoint {} as unavailable for read",this.locationEndpoint); - this.globalEndpointManager.markEndpointUnavailableForRead(this.consolidatedRegionalEndpoint.getGatewayLocationEndpoint()); + logger.warn("marking the endpoint {} as unavailable for read", gatewayRegionalEndpoint); + this.globalEndpointManager.markEndpointUnavailableForRead(gatewayRegionalEndpoint); } else { - logger.warn("marking the endpoint {} as unavailable for write",this.locationEndpoint); - this.globalEndpointManager.markEndpointUnavailableForWrite(this.consolidatedRegionalEndpoint.getGatewayLocationEndpoint()); + logger.warn("marking the endpoint {} as unavailable for write", gatewayRegionalEndpoint); + this.globalEndpointManager.markEndpointUnavailableForWrite(gatewayRegionalEndpoint); } this.retryContext = new RetryContext(this.failoverRetryCount, usePreferredLocations); @@ -359,7 +361,7 @@ private Mono shouldRetryOnBackendServiceUnavailableAsync( if (this.globalPartitionEndpointManagerForCircuitBreaker.isPartitionLevelCircuitBreakingApplicable(this.request)) { this.globalPartitionEndpointManagerForCircuitBreaker - .handleLocationExceptionForPartitionKeyRange(this.request, this.request.requestContext.consolidatedRegionalEndpointToRoute); + .handleLocationExceptionForPartitionKeyRange(this.request, this.request.requestContext.regionalRoutingContextToRoute); } // The request has failed with 503, SDK need to decide whether it is safe to retry for write operations @@ -404,7 +406,9 @@ private Mono shouldRetryOnBackendServiceUnavailableAsync( return Mono.just(ShouldRetryResult.noRetry()); } - logger.info("shouldRetryOnServiceUnavailable() Retrying. Received on endpoint {}, IsReadRequest = {}", this.locationEndpoint, isReadRequest); + URI gatewayLocationEndpoint = this.regionalRoutingContext.getGatewayRegionalEndpoint(); + + logger.info("shouldRetryOnServiceUnavailable() Retrying. Received on endpoint {}, IsReadRequest = {}", gatewayLocationEndpoint, isReadRequest); // Retrying on second PreferredLocations // RetryCount is used as zero-based index @@ -421,7 +425,7 @@ private Mono shouldRetryOnRequestTimeout( this.globalPartitionEndpointManagerForCircuitBreaker.handleLocationExceptionForPartitionKeyRange( this.request, - this.request.requestContext.consolidatedRegionalEndpointToRoute); + this.request.requestContext.regionalRoutingContextToRoute); } } @@ -434,7 +438,7 @@ private Mono shouldRetryOnInternalServerError() { this.globalPartitionEndpointManagerForCircuitBreaker.handleLocationExceptionForPartitionKeyRange( this.request, - this.request.requestContext.consolidatedRegionalEndpointToRoute); + this.request.requestContext.regionalRoutingContextToRoute); } return Mono.just(ShouldRetryResult.NO_RETRY); @@ -455,6 +459,7 @@ public void onBeforeSendRequest(RxDocumentServiceRequest request) { } if (this.retryContext != null) { // set location-based routing directive based on request retry context + checkNotNull(request.requestContext, "Argument 'request.requestContext' cannot be null!"); request.requestContext.routeToLocation(this.retryContext.retryCount, this.retryContext.retryRequestOnPreferredLocations); } @@ -463,17 +468,10 @@ public void onBeforeSendRequest(RxDocumentServiceRequest request) { // Resolve the endpoint for the request and pin the resolution to the resolved endpoint // This enables marking the endpoint unavailability on endpoint failover/unreachability - this.consolidatedRegionalEndpoint = this.globalEndpointManager.resolveServiceEndpoint(request); - this.locationEndpoint = request.useThinProxy && this.consolidatedRegionalEndpoint.getThinClientLocationEndpoint() != null ? - this.consolidatedRegionalEndpoint.getThinClientLocationEndpoint() : - this.consolidatedRegionalEndpoint.getGatewayLocationEndpoint(); - - if (this.consolidatedRegionalEndpoint.getThinClientLocationEndpoint() == null) { - request.useThinProxy = false; - } + this.regionalRoutingContext = this.globalEndpointManager.resolveServiceEndpoint(request); if (request.requestContext != null) { - request.requestContext.routeToLocation(this.locationEndpoint, this.consolidatedRegionalEndpoint); + request.requestContext.routeToLocation(this.regionalRoutingContext); } } @@ -519,13 +517,4 @@ public RetryContext(int retryCount, this.retryRequestOnPreferredLocations = retryRequestOnPreferredLocations; } } - - private URI getGatewayLocationEndpoint(RxDocumentServiceRequest request) { - - Objects.requireNonNull(request, "Argument 'request' must not be null'"); - Objects.requireNonNull(request.requestContext, "Argument 'request.requestContext' must not be null'"); - Objects.requireNonNull(request.requestContext.consolidatedRegionalEndpointToRoute, "Argument 'request.requestContext.consolidatedRegionalEndpointToRoute' must not be null'"); - - return request.requestContext.consolidatedRegionalEndpointToRoute.getGatewayLocationEndpoint(); - } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ClientSideRequestStatistics.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ClientSideRequestStatistics.java index 72c05373f21a..d287ec73483e 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ClientSideRequestStatistics.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ClientSideRequestStatistics.java @@ -8,7 +8,7 @@ import com.azure.cosmos.implementation.directconnectivity.StoreResponseDiagnostics; import com.azure.cosmos.implementation.directconnectivity.StoreResultDiagnostics; import com.azure.cosmos.implementation.faultinjection.FaultInjectionRequestContext; -import com.azure.cosmos.implementation.routing.LocationCache; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonGenerator; @@ -36,6 +36,9 @@ import java.util.concurrent.ConcurrentLinkedDeque; import java.util.stream.Collectors; +import static com.azure.cosmos.implementation.guava25.base.Preconditions.checkArgument; +import static com.azure.cosmos.implementation.guava25.base.Preconditions.checkNotNull; + @JsonSerialize(using = ClientSideRequestStatistics.ClientSideRequestStatisticsSerializer.class) public class ClientSideRequestStatistics { private static final int MAX_SUPPLEMENTAL_REQUESTS_FOR_TO_STRING = 10; @@ -164,7 +167,7 @@ public void recordResponse(RxDocumentServiceRequest request, StoreResultDiagnost this.requestPayloadSizeInBytes = 0; } - LocationCache.ConsolidatedRegionalEndpoint consolidatedRegionalEndpoint = null; + RegionalRoutingContext regionalRoutingContext = null; URI locationEndPoint = null; if (request.requestContext != null) { @@ -178,8 +181,7 @@ public void recordResponse(RxDocumentServiceRequest request, StoreResultDiagnost request.requestContext.getEndToEndOperationLatencyPolicyConfig().toString(); } - locationEndPoint = request.requestContext.locationEndpointToRoute; - consolidatedRegionalEndpoint = request.requestContext.consolidatedRegionalEndpointToRoute; + regionalRoutingContext = request.requestContext.regionalRoutingContextToRoute; List excludedRegions = request.requestContext.getExcludeRegions(); if (excludedRegions != null && !excludedRegions.isEmpty()) { @@ -193,12 +195,12 @@ public void recordResponse(RxDocumentServiceRequest request, StoreResultDiagnost this.requestEndTimeUTC = responseTime; } - if (consolidatedRegionalEndpoint != null) { + if (regionalRoutingContext != null) { storeResponseStatistics.regionName = - globalEndpointManager.getRegionName(consolidatedRegionalEndpoint.getGatewayLocationEndpoint(), request.getOperationType()); + globalEndpointManager.getRegionName(regionalRoutingContext.getGatewayRegionalEndpoint(), request.getOperationType()); this.regionsContacted.add(storeResponseStatistics.regionName); this.locationEndpointsContacted.add(locationEndPoint); - this.regionsContactedWithContext.add(new RegionWithContext(storeResponseStatistics.regionName, consolidatedRegionalEndpoint)); + this.regionsContactedWithContext.add(new RegionWithContext(storeResponseStatistics.regionName, regionalRoutingContext)); } if (storeResponseStatistics.requestOperationType == OperationType.Head @@ -222,26 +224,29 @@ public void recordGatewayResponse( this.requestEndTimeUTC = responseTime; } - LocationCache.ConsolidatedRegionalEndpoint consolidatedRegionalEndpoint = null; - URI locationEndPoint = null; + RegionalRoutingContext regionalRoutingContext = null; + if (rxDocumentServiceRequest != null && rxDocumentServiceRequest.requestContext != null) { - consolidatedRegionalEndpoint = rxDocumentServiceRequest.requestContext.consolidatedRegionalEndpointToRoute; - locationEndPoint = rxDocumentServiceRequest.requestContext.locationEndpointToRoute; + if (rxDocumentServiceRequest.requestContext.regionalRoutingContextToRoute != null) { + regionalRoutingContext = rxDocumentServiceRequest.requestContext.regionalRoutingContextToRoute; + } this.approximateInsertionCountInBloomFilter = rxDocumentServiceRequest.requestContext.getApproximateBloomFilterInsertionCount(); this.keywordIdentifiers = rxDocumentServiceRequest.requestContext.getKeywordIdentifiers(); } + this.recordRetryContextEndTime(); - if (locationEndPoint != null) { + if (regionalRoutingContext != null) { - String regionName = globalEndpointManager.getRegionName(locationEndPoint, rxDocumentServiceRequest.getOperationType()); + URI locationEndpoint = regionalRoutingContext.getGatewayRegionalEndpoint(); + String regionName = globalEndpointManager.getRegionName(locationEndpoint, rxDocumentServiceRequest.getOperationType()); this.regionsContacted.add(regionName); - this.locationEndpointsContacted.add(locationEndPoint); + this.locationEndpointsContacted.add(locationEndpoint); - this.regionsContactedWithContext.add(new RegionWithContext(regionName, consolidatedRegionalEndpoint)); + this.regionsContactedWithContext.add(new RegionWithContext(regionName, regionalRoutingContext)); } GatewayStatistics gatewayStatistics = new GatewayStatistics(); @@ -659,7 +664,7 @@ public String getFirstContactedRegion() { return this.regionsContactedWithContext.first().regionContacted; } - public LocationCache.ConsolidatedRegionalEndpoint getFirstContactedLocationEndpoint() { + public RegionalRoutingContext getFirstContactedLocationEndpoint() { if (this.regionsContactedWithContext == null || this.regionsContactedWithContext.isEmpty()) { return null; } @@ -1056,10 +1061,10 @@ public static CosmosDiagnosticsSystemUsageSnapshot fetchSystemInformation() { static class RegionWithContext implements Comparable { private final String regionContacted; - private final LocationCache.ConsolidatedRegionalEndpoint locationEndpointsContacted; + private final RegionalRoutingContext locationEndpointsContacted; private final long recordedTimestamp; - RegionWithContext(String regionContacted, LocationCache.ConsolidatedRegionalEndpoint locationEndpointsContacted) { + RegionWithContext(String regionContacted, RegionalRoutingContext locationEndpointsContacted) { this.regionContacted = regionContacted; this.locationEndpointsContacted = locationEndpointsContacted; this.recordedTimestamp = System.currentTimeMillis(); diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Configs.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Configs.java index 77b639f7b78d..a933b63155f6 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Configs.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Configs.java @@ -46,10 +46,10 @@ public class Configs { private static final String UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS = "COSMOS.UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS"; private static final String GLOBAL_ENDPOINT_MANAGER_INITIALIZATION_TIME_IN_SECONDS = "COSMOS.GLOBAL_ENDPOINT_MANAGER_MAX_INIT_TIME_IN_SECONDS"; private static final String DEFAULT_THINCLIENT_ENDPOINT = ""; - public static final String THINCLIENT_ENDPOINT = "COSMOS.THINCLIENT_ENDPOINT"; + private static final String THINCLIENT_ENDPOINT = "COSMOS.THINCLIENT_ENDPOINT"; private static final String THINCLIENT_ENDPOINT_VARIABLE = "COSMOS_THINCLIENT_ENDPOINT"; private static final boolean DEFAULT_THINCLIENT_ENABLED = false; - public static final String THINCLIENT_ENABLED = "COSMOS.THINCLIENT_ENABLED"; + private static final String THINCLIENT_ENABLED = "COSMOS.THINCLIENT_ENABLED"; private static final String THINCLIENT_ENABLED_VARIABLE = "COSMOS_THINCLIENT_ENABLED"; private static final String MAX_HTTP_BODY_LENGTH_IN_BYTES = "COSMOS.MAX_HTTP_BODY_LENGTH_IN_BYTES"; @@ -63,6 +63,14 @@ public class Configs { public static final String HTTP_DEFAULT_CONNECTION_POOL_SIZE = "COSMOS.DEFAULT_HTTP_CONNECTION_POOL_SIZE"; public static final String HTTP_DEFAULT_CONNECTION_POOL_SIZE_VARIABLE = "COSMOS_DEFAULT_HTTP_CONNECTION_POOL_SIZE"; + public static final String HTTP_PENDING_ACQUIRE_MAX_COUNT = "COSMOS.HTTP_PENDING_ACQUIRE_MAX_COUNT"; + public static final String HTTP_PENDING_ACQUIRE_MAX_COUNT_VARIABLE = "COSMOS_HTTP_PENDING_ACQUIRE_MAX_COUNT"; + + public static final String ITEM_SERIALIZATION_INCLUSION_MODE = "COSMOS.ITEM_SERIALIZATION_INCLUSION_MODE"; + public static final String ITEM_SERIALIZATION_INCLUSION_MODE_VARIABLE = "COSMOS_ITEM_SERIALIZATION_INCLUSION_MODE"; + + public static final String DEFAULT_ITEM_SERIALIZATION_INCLUSION_MODE = "Always"; + public static final boolean DEFAULT_E2E_FOR_NON_POINT_DISABLED_DEFAULT = false; public static final String DEFAULT_E2E_FOR_NON_POINT_DISABLED = "COSMOS.E2E_FOR_NON_POINT_DISABLED"; public static final String DEFAULT_E2E_FOR_NON_POINT_DISABLED_VARIABLE = "COSMOS_E2E_FOR_NON_POINT_DISABLED"; @@ -304,7 +312,7 @@ public class Configs { // Flag to indicate whether enabled http2 for gateway private static final boolean DEFAULT_HTTP2_ENABLED = false; - public static final String HTTP2_ENABLED = "COSMOS.HTTP2_ENABLED"; + private static final String HTTP2_ENABLED = "COSMOS.HTTP2_ENABLED"; private static final String HTTP2_ENABLED_VARIABLE = "COSMOS_HTTP2_ENABLED"; // Config to indicate the maximum number of live connections to keep in the pool for http2 @@ -333,7 +341,9 @@ private SslContext sslContextInit(boolean serverCertVerificationDisabled, boolea .forClient() .sslProvider(SslContext.defaultClientProvider()); - sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE); // disable cert verification + if (serverCertVerificationDisabled) { + sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE); // disable cert verification + } if (http2Enabled) { sslContextBuilder @@ -513,6 +523,51 @@ public static int getDefaultHttpPoolSize() { return DEFAULT_HTTP_DEFAULT_CONNECTION_POOL_SIZE; } + public static Integer getPendingAcquireMaxCount() { + String valueFromSystemProperty = System.getProperty(HTTP_PENDING_ACQUIRE_MAX_COUNT); + if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { + return Integer.parseInt(valueFromSystemProperty); + } + + String valueFromEnvVariable = System.getenv(HTTP_PENDING_ACQUIRE_MAX_COUNT_VARIABLE); + if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { + return Integer.parseInt(valueFromEnvVariable); + } + + return null; + } + + private static String validateSerializationInclusionMode(String serializationInclusionMode) { + if (!Strings.isNullOrEmpty(serializationInclusionMode)) { + if ("Always".equalsIgnoreCase(serializationInclusionMode) + || "NonNull".equalsIgnoreCase(serializationInclusionMode) + || "NonEmpty".equalsIgnoreCase(serializationInclusionMode) + || "NonDefault".equalsIgnoreCase(serializationInclusionMode)) { + + return serializationInclusionMode; + } + } + + throw new IllegalArgumentException( + "Invalid serialization inclusion mode '" + + serializationInclusionMode != null ? serializationInclusionMode : "null" + + "'."); + } + + public static String getItemSerializationInclusionMode() { + String valueFromSystemProperty = System.getProperty(ITEM_SERIALIZATION_INCLUSION_MODE); + if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { + return validateSerializationInclusionMode(valueFromSystemProperty); + } + + String valueFromEnvVariable = System.getenv(ITEM_SERIALIZATION_INCLUSION_MODE_VARIABLE); + if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) { + return validateSerializationInclusionMode(valueFromEnvVariable); + } + + return DEFAULT_ITEM_SERIALIZATION_INCLUSION_MODE; + } + public static boolean isDefaultE2ETimeoutDisabledForNonPointOperations() { String valueFromSystemProperty = System.getProperty(DEFAULT_E2E_FOR_NON_POINT_DISABLED); if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) { diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ConnectionPolicy.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ConnectionPolicy.java index 7cad767ece97..45dd54bdcb08 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ConnectionPolicy.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ConnectionPolicy.java @@ -55,6 +55,8 @@ public final class ConnectionPolicy { private int aggressiveWarmupConcurrency; private boolean serverCertValidationDisabled = false; + private Integer pendingAcquireMaxCount; + /** * Constructor. */ @@ -108,6 +110,8 @@ private ConnectionPolicy( .DirectConnectionConfigHelper .getDirectConnectionConfigAccessor() .getMinConnectionPoolSizePerEndpoint(directConnectionConfig), Configs.getMinConnectionPoolSizePerEndpoint()); + + this.pendingAcquireMaxCount = Configs.getPendingAcquireMaxCount(); } private ConnectionPolicy() { @@ -122,6 +126,7 @@ private ConnectionPolicy() { this.minConnectionPoolSizePerEndpoint = Configs.getMinConnectionPoolSizePerEndpoint(); this.openConnectionsConcurrency = Configs.getOpenConnectionsConcurrency(); this.aggressiveWarmupConcurrency = Configs.getAggressiveWarmupConcurrency(); + this.pendingAcquireMaxCount = Configs.getPendingAcquireMaxCount(); } /** @@ -637,6 +642,7 @@ public boolean isServerCertValidationDisabled() { @Override public String toString() { + return "ConnectionPolicy{" + "httpNetworkRequestTimeout=" + httpNetworkRequestTimeout + ", tcpNetworkRequestTimeout=" + tcpNetworkRequestTimeout + @@ -663,6 +669,7 @@ public String toString() { ", minConnectionPoolSizePerEndpoint=" + minConnectionPoolSizePerEndpoint + ", openConnectionsConcurrency=" + openConnectionsConcurrency + ", aggressiveWarmupConcurrency=" + aggressiveWarmupConcurrency + + ", pendingAcquireMaxCount=" + this.pendingAcquireMaxCount != null ? String.valueOf(this.pendingAcquireMaxCount) : "DEFAULT" + '}'; } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ConsistencyPolicy.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ConsistencyPolicy.java index 8f8b8a23c3da..ea24f3189501 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ConsistencyPolicy.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ConsistencyPolicy.java @@ -6,7 +6,6 @@ import com.azure.cosmos.BridgeInternal; import com.azure.cosmos.ConsistencyLevel; -import com.azure.cosmos.CosmosItemSerializer; import com.fasterxml.jackson.databind.node.ObjectNode; import java.time.Duration; @@ -79,8 +78,8 @@ public ConsistencyPolicy setDefaultConsistencyLevel(ConsistencyLevel level) { this.consistencyLevel = level; super.set( Constants.Properties.DEFAULT_CONSISTENCY_LEVEL, - level.toString(), - CosmosItemSerializer.DEFAULT_SERIALIZER); + level.toString() + ); return this; } @@ -108,8 +107,8 @@ public int getMaxStalenessPrefix() { public ConsistencyPolicy setMaxStalenessPrefix(int maxStalenessPrefix) { super.set( Constants.Properties.MAX_STALENESS_PREFIX, - maxStalenessPrefix, - CosmosItemSerializer.DEFAULT_SERIALIZER); + maxStalenessPrefix + ); return this; } @@ -140,8 +139,8 @@ public ConsistencyPolicy setMaxStalenessInterval(Duration maxStalenessInterval) } super.set( Constants.Properties.MAX_STALENESS_INTERVAL_IN_SECONDS, - maxStalenessInterval.getSeconds(), - CosmosItemSerializer.DEFAULT_SERIALIZER); + maxStalenessInterval.getSeconds() + ); return this; } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/CosmosChangeFeedRequestOptionsImpl.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/CosmosChangeFeedRequestOptionsImpl.java index 4bbdf764cce3..8ed54d006e4f 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/CosmosChangeFeedRequestOptionsImpl.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/CosmosChangeFeedRequestOptionsImpl.java @@ -11,6 +11,7 @@ import com.azure.cosmos.implementation.changefeed.common.ChangeFeedMode; import com.azure.cosmos.implementation.changefeed.common.ChangeFeedStartFromInternal; import com.azure.cosmos.implementation.changefeed.common.ChangeFeedState; +import com.azure.cosmos.implementation.changefeed.common.ChangeFeedStateV1; import com.azure.cosmos.implementation.feedranges.FeedRangeInternal; import com.azure.cosmos.implementation.spark.OperationContextAndListenerTuple; import com.azure.cosmos.models.CosmosRequestOptions; @@ -52,7 +53,11 @@ public final class CosmosChangeFeedRequestOptionsImpl implements OverridableRequ private Long endLSN; public CosmosChangeFeedRequestOptionsImpl(CosmosChangeFeedRequestOptionsImpl toBeCloned) { - this.continuationState = toBeCloned.continuationState; + if (toBeCloned.continuationState != null) { + this.continuationState = new ChangeFeedStateV1((ChangeFeedStateV1) toBeCloned.continuationState); + } else { + this.continuationState = null; + } this.feedRangeInternal = toBeCloned.feedRangeInternal; this.properties = toBeCloned.properties; this.maxItemCount = toBeCloned.maxItemCount; @@ -93,7 +98,12 @@ public CosmosChangeFeedRequestOptionsImpl( this.maxPrefetchPageCount = DEFAULT_MAX_PREFETCH_PAGE_COUNT; this.feedRangeInternal = feedRange; this.startFromInternal = startFromInternal; - this.continuationState = continuationState; + if (continuationState != null) { + this.continuationState = new ChangeFeedStateV1((ChangeFeedStateV1) continuationState); + } else { + this.continuationState = null; + } + if (mode != ChangeFeedMode.INCREMENTAL && mode != ChangeFeedMode.FULL_FIDELITY) { throw new IllegalArgumentException( diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/CosmosError.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/CosmosError.java index 87d41d077984..251885a70155 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/CosmosError.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/CosmosError.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation; -import com.azure.cosmos.CosmosItemSerializer; import com.fasterxml.jackson.databind.node.ObjectNode; /** @@ -75,7 +74,7 @@ public String getCode() { * @param code the error code. */ private void setCode(String code) { - super.set(Constants.Properties.CODE, code, CosmosItemSerializer.DEFAULT_SERIALIZER); + super.set(Constants.Properties.CODE, code); } /** @@ -93,7 +92,7 @@ public String getMessage() { * @param message the error message. */ private void setMessage(String message) { - super.set(Constants.Properties.MESSAGE, message, CosmosItemSerializer.DEFAULT_SERIALIZER); + super.set(Constants.Properties.MESSAGE, message); } /** @@ -113,8 +112,8 @@ public String getErrorDetails() { private void setAdditionalErrorInfo(String additionalErrorInfo) { super.set( Constants.Properties.ADDITIONAL_ERROR_INFO, - additionalErrorInfo, - CosmosItemSerializer.DEFAULT_SERIALIZER); + additionalErrorInfo + ); } /** diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/CosmosSchedulers.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/CosmosSchedulers.java index 00b6202f608e..91a70da06307 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/CosmosSchedulers.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/CosmosSchedulers.java @@ -56,7 +56,8 @@ public class CosmosSchedulers { Schedulers.DEFAULT_BOUNDED_ELASTIC_SIZE, Schedulers.DEFAULT_BOUNDED_ELASTIC_QUEUESIZE, CLIENT_TELEMETRY_BOUNDED_ELASTIC_THREAD_NAME, - TTL_FOR_SCHEDULER_WORKER_IN_SECONDS + TTL_FOR_SCHEDULER_WORKER_IN_SECONDS, + true ); // Custom bounded elastic scheduler for open connections diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/DatabaseAccount.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/DatabaseAccount.java index de812cd24254..f98cd1240eec 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/DatabaseAccount.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/DatabaseAccount.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation; -import com.azure.cosmos.CosmosItemSerializer; import com.fasterxml.jackson.databind.node.ObjectNode; import com.azure.cosmos.implementation.apachecommons.lang.ObjectUtils; import com.azure.cosmos.implementation.apachecommons.lang.StringUtils; @@ -65,7 +64,7 @@ String getDatabasesLink() { * @param databasesLink the databases link. */ void setDatabasesLink(String databasesLink) { - this.set(Constants.Properties.DATABASES_LINK, databasesLink, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.DATABASES_LINK, databasesLink); } /** @@ -83,7 +82,7 @@ String getMediaLink() { * @param medialink the media link. */ void setMediaLink(String medialink) { - this.set(Constants.Properties.MEDIA_LINK, medialink, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.MEDIA_LINK, medialink); } /** @@ -101,7 +100,7 @@ String getAddressesLink() { * @param addresseslink the addresses link. */ void setAddressesLink(String addresseslink) { - this.set(Constants.Properties.ADDRESS_LINK, addresseslink, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.ADDRESS_LINK, addresseslink); } /** @@ -229,7 +228,7 @@ public Iterable getWritableLocations() { * @param locations the list of writable locations. */ public void setWritableLocations(Iterable locations) { - this.set(Constants.Properties.WRITABLE_LOCATIONS, locations, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.WRITABLE_LOCATIONS, locations); } /** @@ -249,7 +248,7 @@ public Iterable getReadableLocations() { * @param locations the list of readable locations. */ public void setReadableLocations(Iterable locations) { - this.set(Constants.Properties.READABLE_LOCATIONS, locations, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.READABLE_LOCATIONS, locations); } /** @@ -269,7 +268,7 @@ public Iterable getThinClientReadableLocations() { * @param locations the list of thin client readable locations. */ public void setThinClientReadableLocations(Iterable locations) { - this.set(Constants.Properties.THINCLIENT_READABLE_LOCATIONS, locations, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.THINCLIENT_READABLE_LOCATIONS, locations); } /** @@ -289,7 +288,7 @@ public Iterable getThinClientWritableLocations() { * @param locations the list of thin clientwritable locations. */ public void setThinClientWritableLocations(Iterable locations) { - this.set(Constants.Properties.THINCLIENT_WRITABLE_LOCATIONS, locations, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.THINCLIENT_WRITABLE_LOCATIONS, locations); } /** @@ -302,7 +301,7 @@ public boolean getEnableMultipleWriteLocations() { } public void setEnableMultipleWriteLocations(boolean value) { - this.set(Constants.Properties.ENABLE_MULTIPLE_WRITE_LOCATIONS, value, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.ENABLE_MULTIPLE_WRITE_LOCATIONS, value); } public void populatePropertyBag() { @@ -311,8 +310,8 @@ public void populatePropertyBag() { this.consistencyPolicy.populatePropertyBag(); this.set( Constants.Properties.USER_CONSISTENCY_POLICY, - this.consistencyPolicy, - CosmosItemSerializer.DEFAULT_SERIALIZER); + this.consistencyPolicy + ); } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/DatabaseAccountLocation.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/DatabaseAccountLocation.java index f9da5b1bda94..6e5e93a2cb50 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/DatabaseAccountLocation.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/DatabaseAccountLocation.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation; -import com.azure.cosmos.CosmosItemSerializer; import com.fasterxml.jackson.databind.node.ObjectNode; /** @@ -53,7 +52,7 @@ public String getName() { * @param name the name of the database account location. */ public void setName(String name) { - super.set( Constants.Properties.Name, name, CosmosItemSerializer.DEFAULT_SERIALIZER); + super.set( Constants.Properties.Name, name); } /** @@ -71,6 +70,6 @@ public String getEndpoint() { * @param endpoint the endpoint of the database account location. */ public void setEndpoint(String endpoint) { - super.set(Constants.Properties.DATABASE_ACCOUNT_ENDPOINT, endpoint, CosmosItemSerializer.DEFAULT_SERIALIZER); + super.set(Constants.Properties.DATABASE_ACCOUNT_ENDPOINT, endpoint); } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/DefaultCosmosItemSerializer.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/DefaultCosmosItemSerializer.java new file mode 100644 index 000000000000..3c974ba7fdd2 --- /dev/null +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/DefaultCosmosItemSerializer.java @@ -0,0 +1,115 @@ +package com.azure.cosmos.implementation; + +import com.azure.cosmos.CosmosClientBuilder; +import com.azure.cosmos.CosmosItemSerializer; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; + +import java.io.IOException; +import java.util.Map; + +import static com.azure.cosmos.implementation.guava25.base.Preconditions.checkNotNull; + +public class DefaultCosmosItemSerializer extends CosmosItemSerializer { + ImplementationBridgeHelpers.CosmosItemSerializerHelper.CosmosItemSerializerAccessor itemSerializerAccessor = + ImplementationBridgeHelpers + .CosmosItemSerializerHelper + .getCosmosItemSerializerAccessor(); + private final static ObjectMapper serializationInclusionModeAwareObjectMapper = Utils.getDocumentObjectMapper( + Configs.getItemSerializationInclusionMode() + ); + private final static ObjectMapper defaultSerializationInclusionModeObjectMapper = Utils.getSimpleObjectMapper(); + + /** + * Gets the default Cosmos item serializer. This serializer is used by default when no custom serializer is + * specified on request options or the {@link CosmosClientBuilder} + */ + public final static CosmosItemSerializer DEFAULT_SERIALIZER = + new DefaultCosmosItemSerializer(serializationInclusionModeAwareObjectMapper); + + // guaranteed to sue serialization inclusion mode "Always" + public final static CosmosItemSerializer INTERNAL_DEFAULT_SERIALIZER = + new DefaultCosmosItemSerializer(defaultSerializationInclusionModeObjectMapper); + + private final ObjectMapper mapper; + + public DefaultCosmosItemSerializer(ObjectMapper mapper) { + checkNotNull("mapper", "Argument 'mapper' must not be null."); + + this.mapper = mapper; + itemSerializerAccessor.setItemObjectMapper(this, mapper); + itemSerializerAccessor.setShouldWrapSerializationExceptions(this, false); + } + + /** + * Used to serialize a POJO into a json tree + * + * @param item the POJO to be serialized + * @param The type of the POJO + * @return the json tree that will be used as payload in Cosmos DB items + */ + @Override + @SuppressWarnings("unchecked") + public Map serialize(T item) { + if (item == null) { + return null; + } + + if (item instanceof ObjectNode) { + return new ObjectNodeMap((ObjectNode) item); + } + + if (item instanceof JsonSerializable) { + return ((JsonSerializable) item).getMap(); + } + + JsonNode jsonNode = this.mapper.convertValue(item, JsonNode.class); + if (jsonNode == null) { + return null; + } + + if (jsonNode.isObject()) { + return new ObjectNodeMap((ObjectNode) jsonNode); + } + + return new PrimitiveJsonNodeMap(jsonNode); + } + + /** + * Used to deserialize the json tree stored in the Cosmos DB item as a POJO + * + * @param jsonNodeMap the json tree from the Cosmos DB item + * @param classType The type of the POJO + * @param The type of the POJO + * @return The deserialized POJO + */ + @Override + @SuppressWarnings("unchecked") + public T deserialize(Map jsonNodeMap, Class classType) { + if (jsonNodeMap == null) { + return null; + } + + ObjectNode jsonNode = null; + try { + if (jsonNodeMap instanceof ObjectNodeMap) { + jsonNode = ((ObjectNodeMap) jsonNodeMap).getObjectNode(); + } else if (jsonNodeMap instanceof PrimitiveJsonNodeMap) { + return this.mapper.convertValue( + ((PrimitiveJsonNodeMap) jsonNodeMap).getPrimitiveJsonNode(), + classType); + } else { + jsonNode = this.mapper.convertValue(jsonNodeMap, ObjectNode.class); + } + + if (JsonSerializable.class.isAssignableFrom(classType)) { + return (T) JsonSerializable.instantiateFromObjectNodeAndType(jsonNode, classType); + } + + return this.mapper.treeToValue(jsonNode, classType); + } catch (IOException e) { + throw new IllegalStateException(String.format("Unable to parse JSON %s as %s", jsonNode, classType.getName()), e); + } + } +} diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/DiagnosticsProvider.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/DiagnosticsProvider.java index 16d3fcd40905..d6c099ba42b2 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/DiagnosticsProvider.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/DiagnosticsProvider.java @@ -107,6 +107,8 @@ public final class DiagnosticsProvider { private final CosmosClientTelemetryConfig telemetryConfig; private final boolean shouldSystemExitOnError; + private final AtomicLong diagnosticsHandlerFailures = new AtomicLong(0); + final Supplier samplingRateSnapshotSupplier; @@ -210,6 +212,10 @@ public static Context getContextFromReactorOrNull(ContextView reactorContext) { return null; } + public long getDiagnosticHandlerFailuresSnapshot() { + return this.diagnosticsHandlerFailures.get(); + } + /** * Stores {@link Context} in Reactor {@link reactor.util.context.Context}. * @@ -538,6 +544,7 @@ private void handleDiagnostics(Context context, CosmosDiagnosticsContext cosmosC try { handler.handleDiagnostics(cosmosCtx, context); } catch (Exception e) { + this.diagnosticsHandlerFailures.incrementAndGet(); LOGGER.error("HandledDiagnostics failed. ", e); } } @@ -1698,6 +1705,7 @@ private void handleErrors(Throwable throwable, int systemExitCode) { if (throwable instanceof Error) { handleFatalError((Error) throwable, systemExitCode); } else { + this.diagnosticsHandlerFailures.incrementAndGet(); LOGGER.error("Unexpected exception in DiagnosticsProvider.endSpan. ", throwable); throw new RuntimeException(throwable); } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Document.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Document.java index d44d2919c956..cad610facb7a 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Document.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Document.java @@ -117,7 +117,7 @@ public void setTimeToLive(Integer timeToLive) { // a "null" value is represented as a missing element on the wire. // setting timeToLive to null should remove the property from the property bag. if (timeToLive != null) { - this.set(Constants.Properties.TTL, timeToLive, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.TTL, timeToLive); } else if (super.has(Constants.Properties.TTL)) { this.remove(Constants.Properties.TTL); } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/DocumentCollection.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/DocumentCollection.java index da6a08c5c276..50d903ebfa7a 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/DocumentCollection.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/DocumentCollection.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.apachecommons.lang.StringUtils; import com.azure.cosmos.implementation.caches.SerializableWrapper; import com.azure.cosmos.models.ChangeFeedPolicy; @@ -16,7 +15,6 @@ import com.azure.cosmos.models.ModelBridgeInternal; import com.azure.cosmos.models.PartitionKeyDefinition; import com.azure.cosmos.models.UniqueKeyPolicy; -import com.azure.cosmos.util.Beta; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.TextNode; @@ -179,7 +177,7 @@ public void setDefaultTimeToLive(Integer timeToLive) { // a "null" value is represented as a missing element on the wire. // setting timeToLive to null should remove the property from the property bag. if (timeToLive != null) { - this.set(Constants.Properties.DEFAULT_TTL, timeToLive, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.DEFAULT_TTL, timeToLive); } else if (super.has(Constants.Properties.DEFAULT_TTL)) { remove(Constants.Properties.DEFAULT_TTL); } @@ -199,7 +197,7 @@ public void setAnalyticalStoreTimeToLiveInSeconds(Integer timeToLive) { // a "null" value is represented as a missing element on the wire. // setting timeToLive to null should remove the property from the property bag. if (timeToLive != null) { - super.set(Constants.Properties.ANALYTICAL_STORAGE_TTL, timeToLive, CosmosItemSerializer.DEFAULT_SERIALIZER); + super.set(Constants.Properties.ANALYTICAL_STORAGE_TTL, timeToLive); } else if (super.has(Constants.Properties.ANALYTICAL_STORAGE_TTL)) { super.remove(Constants.Properties.ANALYTICAL_STORAGE_TTL); } @@ -247,7 +245,7 @@ public void setUniqueKeyPolicy(UniqueKeyPolicy uniqueKeyPolicy) { } this.uniqueKeyPolicy = uniqueKeyPolicy; - this.set(Constants.Properties.UNIQUE_KEY_POLICY, uniqueKeyPolicy, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.UNIQUE_KEY_POLICY, uniqueKeyPolicy); } /** @@ -271,7 +269,7 @@ public void setConflictResolutionPolicy(ConflictResolutionPolicy value) { throw new IllegalArgumentException("CONFLICT_RESOLUTION_POLICY cannot be null."); } - this.set(Constants.Properties.CONFLICT_RESOLUTION_POLICY, value, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.CONFLICT_RESOLUTION_POLICY, value); } /** @@ -299,7 +297,7 @@ public void setChangeFeedPolicy(ChangeFeedPolicy value) { throw new IllegalArgumentException("CHANGE_FEED_POLICY cannot be null."); } - this.set(Constants.Properties.CHANGE_FEED_POLICY, value, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.CHANGE_FEED_POLICY, value); } /** @@ -332,7 +330,7 @@ public void setComputedProperties(Collection computedPropertie } }); - this.set(Constants.Properties.COMPUTED_PROPERTIES, computedProperties, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.COMPUTED_PROPERTIES, computedProperties); } /** @@ -414,7 +412,7 @@ public void setClientEncryptionPolicy(ClientEncryptionPolicy value) { throw new IllegalArgumentException("ClientEncryptionPolicy cannot be null."); } - this.set(Constants.Properties.CLIENT_ENCRYPTION_POLICY, value, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.CLIENT_ENCRYPTION_POLICY, value); } /** @@ -441,7 +439,7 @@ public CosmosVectorEmbeddingPolicy getVectorEmbeddingPolicy() { */ public void setVectorEmbeddingPolicy(CosmosVectorEmbeddingPolicy value) { checkNotNull(value, "cosmosVectorEmbeddingPolicy cannot be null"); - this.set(Constants.Properties.VECTOR_EMBEDDING_POLICY, value, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.VECTOR_EMBEDDING_POLICY, value); } /** @@ -468,7 +466,7 @@ public CosmosFullTextPolicy getFullTextPolicy() { */ public void setFullTextPolicy(CosmosFullTextPolicy value) { checkNotNull(value, "cosmosFullTextPolicy cannot be null"); - this.set(Constants.Properties.FULL_TEXT_POLICY, value, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.FULL_TEXT_POLICY, value); } public void populatePropertyBag() { @@ -484,14 +482,14 @@ public void populatePropertyBag() { ModelBridgeInternal.populatePropertyBag(this.partitionKeyDefinition); this.set( Constants.Properties.PARTITION_KEY, - this.partitionKeyDefinition, - CosmosItemSerializer.DEFAULT_SERIALIZER); + this.partitionKeyDefinition + ); } ModelBridgeInternal.populatePropertyBag(this.indexingPolicy); ModelBridgeInternal.populatePropertyBag(this.uniqueKeyPolicy); - this.set(Constants.Properties.INDEXING_POLICY, this.indexingPolicy, CosmosItemSerializer.DEFAULT_SERIALIZER); - this.set(Constants.Properties.UNIQUE_KEY_POLICY, this.uniqueKeyPolicy, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.INDEXING_POLICY, this.indexingPolicy); + this.set(Constants.Properties.UNIQUE_KEY_POLICY, this.uniqueKeyPolicy); } @Override diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/DocumentServiceRequestContext.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/DocumentServiceRequestContext.java index 5f34f5653225..911309489584 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/DocumentServiceRequestContext.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/DocumentServiceRequestContext.java @@ -12,10 +12,9 @@ import com.azure.cosmos.implementation.directconnectivity.StoreResult; import com.azure.cosmos.implementation.directconnectivity.TimeoutHelper; import com.azure.cosmos.implementation.directconnectivity.Uri; -import com.azure.cosmos.implementation.routing.LocationCache; import com.azure.cosmos.implementation.routing.PartitionKeyInternal; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; -import java.net.URI; import java.util.List; import java.util.Map; import java.util.Set; @@ -39,8 +38,7 @@ public class DocumentServiceRequestContext implements Cloneable { public volatile Integer regionIndex; public volatile Boolean usePreferredLocations; public volatile Integer locationIndexToRoute; - public volatile URI locationEndpointToRoute; - public volatile LocationCache.ConsolidatedRegionalEndpoint consolidatedRegionalEndpointToRoute; + public volatile RegionalRoutingContext regionalRoutingContextToRoute; public volatile boolean performedBackgroundAddressRefresh; public volatile boolean performLocalRefreshOnGoneException; public volatile List storeResponses; @@ -81,19 +79,16 @@ public DocumentServiceRequestContext() {} public void routeToLocation(int locationIndex, boolean usePreferredLocations) { this.locationIndexToRoute = locationIndex; this.usePreferredLocations = usePreferredLocations; - this.locationEndpointToRoute = null; - this.consolidatedRegionalEndpointToRoute = null; + this.regionalRoutingContextToRoute = null; } /** * Sets location-based routing directive for GlobalEndpointManager to resolve * the request to given locationEndpoint. * - * @param locationEndpoint Location endpoint to which the request should be routed. */ - public void routeToLocation(URI locationEndpoint, LocationCache.ConsolidatedRegionalEndpoint consolidatedRegionalEndpointToRoute) { - this.locationEndpointToRoute = locationEndpoint; - this.consolidatedRegionalEndpointToRoute = consolidatedRegionalEndpointToRoute; + public void routeToLocation(RegionalRoutingContext regionalRoutingContextToRoute) { + this.regionalRoutingContextToRoute = regionalRoutingContextToRoute; this.locationIndexToRoute = null; this.usePreferredLocations = null; } @@ -103,8 +98,7 @@ public void routeToLocation(URI locationEndpoint, LocationCache.ConsolidatedRegi */ public void clearRouteToLocation() { this.locationIndexToRoute = null; - this.locationEndpointToRoute = null; - this.consolidatedRegionalEndpointToRoute = null; + this.regionalRoutingContextToRoute = null; this.usePreferredLocations = null; } @@ -145,8 +139,7 @@ public DocumentServiceRequestContext clone() { context.regionIndex = this.regionIndex; context.usePreferredLocations = this.usePreferredLocations; context.locationIndexToRoute = this.locationIndexToRoute; - context.locationEndpointToRoute = this.locationEndpointToRoute; - context.consolidatedRegionalEndpointToRoute = this.consolidatedRegionalEndpointToRoute; + context.regionalRoutingContextToRoute = this.regionalRoutingContextToRoute; context.performLocalRefreshOnGoneException = this.performLocalRefreshOnGoneException; context.effectivePartitionKey = this.effectivePartitionKey; context.performedBackgroundAddressRefresh = this.performedBackgroundAddressRefresh; 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 b0cd09f37c86..44269fb088a2 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 @@ -6,6 +6,7 @@ import com.azure.cosmos.implementation.apachecommons.collections.list.UnmodifiableList; import com.azure.cosmos.implementation.routing.LocationCache; import com.azure.cosmos.implementation.routing.LocationHelper; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; @@ -88,32 +89,32 @@ public void init() { startRefreshLocationTimerAsync(true).block(maxInitializationTime); } - public UnmodifiableList getReadEndpoints() { + public UnmodifiableList getReadEndpoints() { // readonly return this.locationCache.getReadEndpoints(); } - public UnmodifiableList getWriteEndpoints() { + public UnmodifiableList getWriteEndpoints() { //readonly return this.locationCache.getWriteEndpoints(); } - public UnmodifiableList getApplicableReadEndpoints(RxDocumentServiceRequest request) { + public UnmodifiableList getApplicableReadEndpoints(RxDocumentServiceRequest request) { // readonly return this.locationCache.getApplicableReadEndpoints(request); } - public UnmodifiableList getApplicableWriteEndpoints(RxDocumentServiceRequest request) { + public UnmodifiableList getApplicableWriteEndpoints(RxDocumentServiceRequest request) { //readonly return this.locationCache.getApplicableWriteEndpoints(request); } - public UnmodifiableList getApplicableReadEndpoints(List excludedRegions) { + public UnmodifiableList getApplicableReadEndpoints(List excludedRegions) { // readonly return this.locationCache.getApplicableReadEndpoints(excludedRegions, Collections.emptyList()); } - public UnmodifiableList getApplicableWriteEndpoints(List excludedRegions) { + public UnmodifiableList getApplicableWriteEndpoints(List excludedRegions) { //readonly return this.locationCache.getApplicableWriteEndpoints(excludedRegions, Collections.emptyList()); } @@ -146,11 +147,11 @@ public static Mono getDatabaseAccountFromAnyLocationsAsync( }); } - public LocationCache.ConsolidatedRegionalEndpoint resolveServiceEndpoint(RxDocumentServiceRequest request) { - LocationCache.ConsolidatedRegionalEndpoint serviceEndpoints = this.locationCache.resolveServiceEndpoint(request); + public RegionalRoutingContext resolveServiceEndpoint(RxDocumentServiceRequest request) { + RegionalRoutingContext serviceEndpoints = this.locationCache.resolveServiceEndpoint(request); if (request.faultInjectionRequestContext != null) { // TODO: integrate thin client into fault injection - request.faultInjectionRequestContext.setLocationEndpointToRoute(serviceEndpoints.getGatewayLocationEndpoint()); + request.faultInjectionRequestContext.setLocationEndpointToRoute(serviceEndpoints.getGatewayRegionalEndpoint()); } return serviceEndpoints; diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/HashIndex.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/HashIndex.java index 73c47991f86a..b5994edf61c3 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/HashIndex.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/HashIndex.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.apachecommons.lang.StringUtils; import com.fasterxml.jackson.databind.node.ObjectNode; @@ -88,7 +87,7 @@ public DataType getDataType() { * @return the Hash Index. */ public HashIndex setDataType(DataType dataType) { - super.set(Constants.Properties.DATA_TYPE, dataType.toString(), CosmosItemSerializer.DEFAULT_SERIALIZER); + super.set(Constants.Properties.DATA_TYPE, dataType.toString()); return this; } @@ -108,7 +107,7 @@ public int getPrecision() { * @return the Hash Index. */ public HashIndex setPrecision(int precision) { - super.set(Constants.Properties.PRECISION, precision, CosmosItemSerializer.DEFAULT_SERIALIZER); + super.set(Constants.Properties.PRECISION, precision); return this; } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/HttpConstants.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/HttpConstants.java index c02904e7279e..b1eb0cacca5b 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/HttpConstants.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/HttpConstants.java @@ -415,8 +415,8 @@ public static class SubStatusCodes { public static final int INCORRECT_CONTAINER_RID_SUB_STATUS = 1024; - // SDK Codes - Java specific clinet-side substatus codes - // IMPORTANT - whenever possible rather use consistency substaus codes that .Net SDK also uses + // SDK Codes - Java specific client-side substatus codes + // IMPORTANT - whenever possible rather use consistency substatus codes that .Net SDK also uses // 20000-20999 - consistent client side sdk status codes // 21000-21999 - consistent service sdk status codes diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ImplementationBridgeHelpers.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ImplementationBridgeHelpers.java index 1afa8c2a5bbc..7def5159a963 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ImplementationBridgeHelpers.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ImplementationBridgeHelpers.java @@ -40,8 +40,8 @@ import com.azure.cosmos.implementation.directconnectivity.rntbd.RntbdChannelStatistics; import com.azure.cosmos.implementation.faultinjection.IFaultInjectorProvider; import com.azure.cosmos.implementation.patch.PatchOperation; -import com.azure.cosmos.implementation.routing.LocationCache; import com.azure.cosmos.implementation.routing.PartitionKeyInternal; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; import com.azure.cosmos.implementation.spark.OperationContextAndListenerTuple; import com.azure.cosmos.models.CosmosBatch; import com.azure.cosmos.models.CosmosBatchOperationResult; @@ -75,6 +75,7 @@ import com.azure.cosmos.util.CosmosPagedFlux; import com.azure.cosmos.util.UtilBridgeInternal; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.Tag; @@ -837,7 +838,7 @@ void recordAddressResolutionEnd( void setDiagnosticsContext(CosmosDiagnostics cosmosDiagnostics, CosmosDiagnosticsContext ctx); - LocationCache.ConsolidatedRegionalEndpoint getFirstContactedLocationEndpoint(CosmosDiagnostics cosmosDiagnostics); + RegionalRoutingContext getFirstContactedLocationEndpoint(CosmosDiagnostics cosmosDiagnostics); void mergeMetadataDiagnosticContext(CosmosDiagnostics cosmosDiagnostics, MetadataDiagnosticsContext otherMetadataDiagnosticsContext); @@ -1806,6 +1807,9 @@ public interface CosmosItemSerializerAccessor { void setShouldWrapSerializationExceptions( CosmosItemSerializer serializer, boolean shouldWrapSerializationExceptions); + + void setItemObjectMapper(CosmosItemSerializer serializer, ObjectMapper mapper); + ObjectMapper getItemObjectMapper(CosmosItemSerializer serializer); } } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Index.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Index.java index b0255ac5df7f..967e83b26c36 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Index.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Index.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.apachecommons.lang.StringUtils; import com.fasterxml.jackson.databind.node.ObjectNode; @@ -136,7 +135,7 @@ IndexKind getKind() { * @param indexKind the index kind. */ private Index setKind(IndexKind indexKind) { - super.set(Constants.Properties.INDEX_KIND, indexKind.toString(), CosmosItemSerializer.DEFAULT_SERIALIZER); + super.set(Constants.Properties.INDEX_KIND, indexKind.toString()); return this; } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/JsonSerializable.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/JsonSerializable.java index a390fa490a33..c06d8a6bc1ed 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/JsonSerializable.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/JsonSerializable.java @@ -246,12 +246,8 @@ public void remove(String propertyName) { * @param value the value of the property. */ @SuppressWarnings({"unchecked", "rawtypes"}) - public void set(String propertyName, T value, CosmosItemSerializer itemSerializer) { - checkNotNull(itemSerializer, "Argument 'itemSerializer' must not be null."); - checkArgument( - itemSerializer == CosmosItemSerializer.DEFAULT_SERIALIZER, - "Argument 'itemSerializer' must be the DEFAULT_SERIALIZER when using this method."); - set(propertyName, value, itemSerializer, false); + public void set(String propertyName, T value) { + set(propertyName, value, DefaultCosmosItemSerializer.INTERNAL_DEFAULT_SERIALIZER, false); } /** diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/MetadataRequestRetryPolicy.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/MetadataRequestRetryPolicy.java index 06b549096daa..d17aed4326b6 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/MetadataRequestRetryPolicy.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/MetadataRequestRetryPolicy.java @@ -6,7 +6,7 @@ import com.azure.cosmos.BridgeInternal; import com.azure.cosmos.CosmosException; import com.azure.cosmos.implementation.directconnectivity.WebExceptionUtility; -import com.azure.cosmos.implementation.routing.LocationCache; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; @@ -70,10 +70,10 @@ public Mono shouldRetry(Exception e) { if (shouldMarkRegionAsUnavailable(cosmosException)) { - if (request.requestContext != null && request.requestContext.locationEndpointToRoute != null) { + if (request.requestContext != null && request.requestContext.regionalRoutingContextToRoute != null) { - LocationCache.ConsolidatedRegionalEndpoint consolidatedRegionalEndpoint = request.requestContext.consolidatedRegionalEndpointToRoute; - URI locationEndpointToRoute = consolidatedRegionalEndpoint.getGatewayLocationEndpoint(); + RegionalRoutingContext regionalRoutingContext = request.requestContext.regionalRoutingContextToRoute; + URI locationEndpointToRoute = regionalRoutingContext.getGatewayRegionalEndpoint(); if (request.isReadOnlyRequest()) { logger.warn("Marking the endpoint : {} as unavailable for read.", locationEndpointToRoute); diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Offer.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Offer.java index c83624d32176..8c8c4c2d144d 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Offer.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Offer.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation; -import com.azure.cosmos.CosmosItemSerializer; import com.fasterxml.jackson.databind.node.ObjectNode; /** @@ -133,7 +132,7 @@ public String getResourceLink() { * @param resourceLink the resource link. */ void setResourceLink(String resourceLink) { - this.set(Constants.Properties.RESOURCE_LINK, resourceLink, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.RESOURCE_LINK, resourceLink); } /** @@ -151,7 +150,7 @@ public String getOfferResourceId() { * @param resourceId the resource id. */ void setOfferResourceId(String resourceId) { - this.set(Constants.Properties.OFFER_RESOURCE_ID, resourceId, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.OFFER_RESOURCE_ID, resourceId); } /** @@ -169,7 +168,7 @@ public String getOfferType() { * @param offerType the offer type. */ public void setOfferType(String offerType) { - this.set(Constants.Properties.OFFER_TYPE, offerType, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.OFFER_TYPE, offerType); } /** @@ -187,7 +186,7 @@ public String getOfferVersion() { * @param offerVersion the version of the offer. */ public void setOfferVersion(String offerVersion) { - this.set(Constants.Properties.OFFER_VERSION, offerVersion, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.OFFER_VERSION, offerVersion); } /** @@ -222,7 +221,7 @@ private ObjectNode getContent() { } private void setContent(ObjectNode offerContent) { - this.set(Constants.Properties.OFFER_CONTENT, offerContent, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.OFFER_CONTENT, offerContent); } @Override diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/OfferAutoscaleAutoUpgradeProperties.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/OfferAutoscaleAutoUpgradeProperties.java index 007d080996a1..0d569367cd28 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/OfferAutoscaleAutoUpgradeProperties.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/OfferAutoscaleAutoUpgradeProperties.java @@ -2,7 +2,6 @@ // Licensed under the MIT License. package com.azure.cosmos.implementation; -import com.azure.cosmos.CosmosItemSerializer; import com.fasterxml.jackson.databind.node.ObjectNode; public class OfferAutoscaleAutoUpgradeProperties extends JsonSerializable { @@ -13,8 +12,8 @@ public class OfferAutoscaleAutoUpgradeProperties extends JsonSerializable { this.autoscaleThroughputProperties = new AutoscaleThroughputProperties(maxThroughputIncrementPercentage); super.set( Constants.Properties.AUTOPILOT_AUTO_THROUGHPUT_POLICY, - autoscaleThroughputProperties, - CosmosItemSerializer.DEFAULT_SERIALIZER); + autoscaleThroughputProperties + ); } OfferAutoscaleAutoUpgradeProperties(ObjectNode objectNode) { @@ -30,8 +29,8 @@ public static class AutoscaleThroughputProperties extends JsonSerializable { AutoscaleThroughputProperties(int maxThroughputIncrementPercentage) { super.set( Constants.Properties.AUTOPILOT_THROUGHPUT_POLICY_INCREMENT_PERCENT, - maxThroughputIncrementPercentage, - CosmosItemSerializer.DEFAULT_SERIALIZER); + maxThroughputIncrementPercentage + ); } /** diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/OfferAutoscaleSettings.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/OfferAutoscaleSettings.java index f443a0325be4..d3d99eb4b501 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/OfferAutoscaleSettings.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/OfferAutoscaleSettings.java @@ -2,7 +2,6 @@ // Licensed under the MIT License. package com.azure.cosmos.implementation; -import com.azure.cosmos.CosmosItemSerializer; import com.fasterxml.jackson.databind.node.ObjectNode; public class OfferAutoscaleSettings extends JsonSerializable { @@ -13,12 +12,12 @@ public class OfferAutoscaleSettings extends JsonSerializable { offerAutoscaleAutoUpgradeProperties = new OfferAutoscaleAutoUpgradeProperties(maxThroughputIncrementPercentage); super.set( Constants.Properties.AUTOPILOT_MAX_THROUGHPUT, - maxThroughput, - CosmosItemSerializer.DEFAULT_SERIALIZER); + maxThroughput + ); super.set( Constants.Properties.AUTOPILOT_AUTO_UPGRADE_POLICY, - offerAutoscaleAutoUpgradeProperties, - CosmosItemSerializer.DEFAULT_SERIALIZER); + offerAutoscaleAutoUpgradeProperties + ); } OfferAutoscaleSettings(String json) { @@ -41,8 +40,8 @@ int getMaxThroughput() { void setMaxThroughput(int maxAutoscaleThroughput) { super.set( Constants.Properties.AUTOPILOT_MAX_THROUGHPUT, - maxAutoscaleThroughput, - CosmosItemSerializer.DEFAULT_SERIALIZER); + maxAutoscaleThroughput + ); } /** diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/PartitionKeyRange.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/PartitionKeyRange.java index 4c13385a09bf..4488426683d0 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/PartitionKeyRange.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/PartitionKeyRange.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.routing.Range; import com.fasterxml.jackson.databind.node.ObjectNode; @@ -75,7 +74,7 @@ public String getMinInclusive() { } public PartitionKeyRange setMinInclusive(String minInclusive) { - this.set("minInclusive", minInclusive, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set("minInclusive", minInclusive); return this; } @@ -84,7 +83,7 @@ public String getMaxExclusive() { } public PartitionKeyRange setMaxExclusive(String maxExclusive) { - this.set("maxExclusive", maxExclusive, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set("maxExclusive", maxExclusive); return this; } @@ -115,7 +114,7 @@ public int hashCode() { } public void setParents(List parents) { - this.set(Constants.Properties.PARENTS, parents, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.PARENTS, parents); } /** diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Permission.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Permission.java index d3d5fa53988c..5699a1288ae6 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Permission.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Permission.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.models.ModelBridgeInternal; import com.azure.cosmos.models.PartitionKey; import com.azure.cosmos.models.PermissionMode; @@ -62,7 +61,7 @@ public String getResourceLink() { * @param resourceLink the resource link. */ public void setResourceLink(String resourceLink) { - this.set(Constants.Properties.RESOURCE_LINK, resourceLink, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.RESOURCE_LINK, resourceLink); } /** @@ -83,8 +82,8 @@ public PermissionMode getPermissionMode() { public void setPermissionMode(PermissionMode permissionMode) { this.set( Constants.Properties.PERMISSION_MODE, - permissionMode.toString().toLowerCase(Locale.ROOT), - CosmosItemSerializer.DEFAULT_SERIALIZER); + permissionMode.toString().toLowerCase(Locale.ROOT) + ); } /** @@ -122,7 +121,7 @@ public void setResourcePartitionKey(PartitionKey partitionkey) { this.set( Constants.Properties.RESOURCE_PARTITION_KEY, - ModelBridgeInternal.getPartitionKeyInternal(partitionkey).toObjectArray(), - CosmosItemSerializer.DEFAULT_SERIALIZER); + ModelBridgeInternal.getPartitionKeyInternal(partitionkey).toObjectArray() + ); } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RangeIndex.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RangeIndex.java index 9dbb5edcd004..7abc9d353299 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RangeIndex.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RangeIndex.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.apachecommons.lang.StringUtils; import com.fasterxml.jackson.databind.node.ObjectNode; @@ -84,7 +83,7 @@ public DataType getDataType() { * @return the RangeIndex. */ public RangeIndex setDataType(DataType dataType) { - super.set(Constants.Properties.DATA_TYPE, dataType.toString(), CosmosItemSerializer.DEFAULT_SERIALIZER); + super.set(Constants.Properties.DATA_TYPE, dataType.toString()); return this; } @@ -104,7 +103,7 @@ public int getPrecision() { * @return the RangeIndex. */ public RangeIndex setPrecision(int precision) { - super.set(Constants.Properties.PRECISION, precision, CosmosItemSerializer.DEFAULT_SERIALIZER); + super.set(Constants.Properties.PRECISION, precision); return this; } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RegionScopedSessionContainer.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RegionScopedSessionContainer.java index 18d9237674cd..b93761935dc5 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RegionScopedSessionContainer.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RegionScopedSessionContainer.java @@ -8,6 +8,7 @@ import com.azure.cosmos.implementation.apachecommons.math.util.Pair; import com.azure.cosmos.implementation.routing.PartitionKeyInternal; import com.azure.cosmos.implementation.routing.PartitionKeyInternalHelper; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; import com.azure.cosmos.models.PartitionKeyDefinition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -387,7 +388,9 @@ private void addSessionTokenAndTryRecordEpkInBloomFilter(RxDocumentServiceReques String regionRoutedTo = null; if (request.requestContext != null) { - URI regionEndpointRoutedTo = request.requestContext.locationEndpointToRoute; + RegionalRoutingContext regionalRoutingContext = request.requestContext.regionalRoutingContextToRoute; + URI regionEndpointRoutedTo = regionalRoutingContext.getGatewayRegionalEndpoint(); + regionRoutedTo = this.globalEndpointManager.getRegionName(regionEndpointRoutedTo, request.getOperationType()); } @@ -525,7 +528,7 @@ private String extractFirstEffectivePreferredReadableRegion() { List regionNamesForRead = globalEndpointManager .getReadEndpoints() .stream() - .map(consolidatedReadLocationEndpoints -> globalEndpointManager.getRegionName(consolidatedReadLocationEndpoints.getGatewayLocationEndpoint(), OperationType.Read)) + .map(consolidatedReadLocationEndpoints -> globalEndpointManager.getRegionName(consolidatedReadLocationEndpoints.getGatewayRegionalEndpoint(), OperationType.Read)) .collect(Collectors.toList()); checkNotNull(regionNamesForRead, "regionNamesForRead cannot be null!"); diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ReplicationPolicy.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ReplicationPolicy.java index 7196b5e8aef1..5cf9f8273371 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ReplicationPolicy.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ReplicationPolicy.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation; -import com.azure.cosmos.CosmosItemSerializer; import com.fasterxml.jackson.databind.node.ObjectNode; /** @@ -57,7 +56,7 @@ public int getMaxReplicaSetSize() { } public void setMaxReplicaSetSize(int value) { - this.set(Constants.Properties.MAX_REPLICA_SET_SIZE, value, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.MAX_REPLICA_SET_SIZE, value); this.maxReplicaSetSize = value; } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Resource.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Resource.java index d8398d238b78..d18202d069b7 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Resource.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Resource.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation; -import com.azure.cosmos.CosmosItemSerializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.azure.cosmos.implementation.apachecommons.lang.StringUtils; @@ -118,7 +117,7 @@ public String getId() { * @return the resource. */ public Resource setId(String id) { - super.set(Constants.Properties.ID, id, CosmosItemSerializer.DEFAULT_SERIALIZER); + super.set(Constants.Properties.ID, id); return this; } @@ -138,7 +137,7 @@ public String getResourceId() { * @return the resource. */ public Resource setResourceId(String resourceId) { - super.set(Constants.Properties.R_ID, resourceId, CosmosItemSerializer.DEFAULT_SERIALIZER); + super.set(Constants.Properties.R_ID, resourceId); return this; } @@ -157,7 +156,7 @@ public String getSelfLink() { * @param selfLink the self link. */ public Resource setSelfLink(String selfLink) { - super.set(Constants.Properties.SELF_LINK, selfLink, CosmosItemSerializer.DEFAULT_SERIALIZER); + super.set(Constants.Properties.SELF_LINK, selfLink); return this; } @@ -181,7 +180,7 @@ public Instant getTimestamp() { */ public Resource setTimestamp(Instant timestamp) { long seconds = timestamp.getEpochSecond(); - super.set(Constants.Properties.LAST_MODIFIED, seconds, CosmosItemSerializer.DEFAULT_SERIALIZER); + super.set(Constants.Properties.LAST_MODIFIED, seconds); return this; } @@ -200,7 +199,7 @@ public String getETag() { * @param eTag the e tag. */ Resource setETag(String eTag) { - super.set(Constants.Properties.E_TAG, eTag, CosmosItemSerializer.DEFAULT_SERIALIZER); + super.set(Constants.Properties.E_TAG, eTag); return this; } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ResourceThrottleRetryPolicy.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ResourceThrottleRetryPolicy.java index 22c68665ce2c..bea73e015285 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ResourceThrottleRetryPolicy.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ResourceThrottleRetryPolicy.java @@ -74,7 +74,7 @@ public Mono shouldRetry(Exception exception) { "Operation will NOT be retried - not a throttled request. Current attempt {}", this.currentAttemptCount, exception); - return Mono.just(ShouldRetryResult.noRetryOnNonRelatedException(exception)); + return Mono.just(ShouldRetryResult.errorOnNonRelatedException(exception)); } if (!retryOnClientSideThrottledBatchRequests && diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxDocumentClientImpl.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxDocumentClientImpl.java index 522f7cbd4c99..0fba5bf8bc75 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxDocumentClientImpl.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxDocumentClientImpl.java @@ -63,6 +63,7 @@ import com.azure.cosmos.implementation.routing.PartitionKeyRangeIdentity; import com.azure.cosmos.implementation.routing.Range; import com.azure.cosmos.implementation.routing.RegionNameToRegionIdMap; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; import com.azure.cosmos.implementation.spark.OperationContext; import com.azure.cosmos.implementation.spark.OperationContextAndListenerTuple; import com.azure.cosmos.implementation.spark.OperationListener; @@ -147,7 +148,7 @@ public class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorization private final static List EMPTY_REGION_LIST = Collections.emptyList(); - private final static List EMPTY_ENDPOINT_LIST = Collections.emptyList(); + private final static List EMPTY_ENDPOINT_LIST = Collections.emptyList(); private final static ImplementationBridgeHelpers.CosmosDiagnosticsHelper.CosmosDiagnosticsAccessor diagnosticsAccessor = @@ -960,7 +961,10 @@ private Mono> createDatabaseInternal(Database databas Map requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Create); Instant serializationStartTimeUTC = Instant.now(); - ByteBuffer byteBuffer = database.serializeJsonToByteBuffer(CosmosItemSerializer.DEFAULT_SERIALIZER, null, false); + ByteBuffer byteBuffer = database.serializeJsonToByteBuffer( + DefaultCosmosItemSerializer.INTERNAL_DEFAULT_SERIALIZER, + null, + false); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, @@ -1367,7 +1371,10 @@ private Mono> createCollectionInternal(Stri Map requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Create); Instant serializationStartTimeUTC = Instant.now(); - ByteBuffer byteBuffer = collection.serializeJsonToByteBuffer(CosmosItemSerializer.DEFAULT_SERIALIZER, null, false); + ByteBuffer byteBuffer = collection.serializeJsonToByteBuffer( + DefaultCosmosItemSerializer.INTERNAL_DEFAULT_SERIALIZER, + null, + false); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, @@ -1420,7 +1427,10 @@ private Mono> replaceCollectionInternal(Doc String path = Utils.joinPath(collection.getSelfLink(), null); Map requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Replace); Instant serializationStartTimeUTC = Instant.now(); - ByteBuffer byteBuffer = collection.serializeJsonToByteBuffer(CosmosItemSerializer.DEFAULT_SERIALIZER, null, false); + ByteBuffer byteBuffer = collection.serializeJsonToByteBuffer( + DefaultCosmosItemSerializer.INTERNAL_DEFAULT_SERIALIZER, + null, + false); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, @@ -1893,9 +1903,7 @@ private Mono false for some reason, fix it - request.useThinProxy = Configs.isThinClientEnabled() && request.useGatewayMode ? true : false; - request.useThinProxy = true; + request.useThinProxy = Configs.isThinClientEnabled() && this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY ? true : false; if (operationType.isWriteOperation() && options != null && options.getNonIdempotentWriteRetriesEnabled() != null && options.getNonIdempotentWriteRetriesEnabled()) { request.setNonIdempotentWriteRetriesEnabled(true); @@ -2061,7 +2069,7 @@ private RxDocumentServiceRequest addBatchHeaders(RxDocumentServiceRequest reques */ public Mono populateHeadersAsync(RxDocumentServiceRequest request, RequestVerb httpMethod) { // if thin client enabled, populate thin client header so we can get thin client read and writeable locations - if (this.isThinClientEnabled) { + if (request.useThinProxy) { request.getHeaders().put(HttpConstants.HttpHeaders.THINCLIENT_OPT_IN, "true"); } request.getHeaders().put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); @@ -3436,8 +3444,7 @@ private Mono> readDocumentInternal( getEffectiveClientContext(clientContextOverride), OperationType.Read, ResourceType.Document, path, requestHeaders, options); - request.useThinProxy = Configs.isThinClientEnabled() && request.useGatewayMode ? true : false; - request.useThinProxy = true; + request.useThinProxy = Configs.isThinClientEnabled() && this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY ? true : false; DocumentServiceRequestContext requestContext = request.requestContext; options.getMarkE2ETimeoutInRequestContextCallbackHook().set( @@ -5642,7 +5649,7 @@ private Flux> nonDocumentReadFeedInternal( request -> readFeed(request) .map(response -> feedResponseAccessor.createFeedResponse( response, - CosmosItemSerializer.DEFAULT_SERIALIZER, + DefaultCosmosItemSerializer.INTERNAL_DEFAULT_SERIALIZER, klass)); return Paginator @@ -5729,6 +5736,7 @@ public Flux getDatabaseAccountFromEndpoint(URI endpoint) { return Flux.defer(() -> { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null); + request.useThinProxy = this.isThinClientEnabled && this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY ? true : false; return this.populateHeadersAsync(request, RequestVerb.GET) .flatMap(requestPopulated -> { @@ -5754,8 +5762,6 @@ public Flux getDatabaseAccountFromEndpoint(URI endpoint) { * @return RxStoreModel */ private RxStoreModel getStoreProxy(RxDocumentServiceRequest request) { - // TODO: request.useThinProxy is false here, fix it - // TODO: remove, for testing if (request.isMetadataRequest()) { return this.gatewayProxy; @@ -6505,7 +6511,7 @@ private DiagnosticsClientContext getEffectiveClientContext(DiagnosticsClientCont * @param operationType - the operationT * @return the applicable endpoints ordered by preference list if any */ - private List getApplicableEndPoints(OperationType operationType, List excludedRegions) { + private List getApplicableEndPoints(OperationType operationType, List excludedRegions) { if (operationType.isReadOnlyOperation()) { return withoutNulls(this.globalEndpointManager.getApplicableReadEndpoints(excludedRegions)); } else if (operationType.isWriteOperation()) { @@ -6515,7 +6521,7 @@ private List getApplicableEndPoints( return EMPTY_ENDPOINT_LIST; } - private static List withoutNulls(List orderedEffectiveEndpointsList) { + private static List withoutNulls(List orderedEffectiveEndpointsList) { if (orderedEffectiveEndpointsList == null) { return EMPTY_ENDPOINT_LIST; } @@ -6574,7 +6580,7 @@ private List getApplicableRegionsForSpeculation( return EMPTY_REGION_LIST; } - List consolidatedRegionalEndpointList = getApplicableEndPoints(operationType, excludedRegions); + List regionalRoutingContextList = getApplicableEndPoints(operationType, excludedRegions); HashSet normalizedExcludedRegions = new HashSet<>(); if (excludedRegions != null) { @@ -6582,8 +6588,8 @@ private List getApplicableRegionsForSpeculation( } List orderedRegionsForSpeculation = new ArrayList<>(); - consolidatedRegionalEndpointList.forEach(consolidatedLocationEndpoints -> { - String regionName = this.globalEndpointManager.getRegionName(consolidatedLocationEndpoints.getGatewayLocationEndpoint(), operationType); + regionalRoutingContextList.forEach(consolidatedLocationEndpoints -> { + String regionName = this.globalEndpointManager.getRegionName(consolidatedLocationEndpoints.getGatewayRegionalEndpoint(), operationType); if (!normalizedExcludedRegions.contains(regionName.toLowerCase(Locale.ROOT))) { orderedRegionsForSpeculation.add(regionName); } @@ -6787,7 +6793,7 @@ private Mono executeFeedOperationWithAvailabilityStrategy( private void handleLocationCancellationExceptionForPartitionKeyRange(RxDocumentServiceRequest failedRequest) { - LocationCache.ConsolidatedRegionalEndpoint firstContactedLocationEndpoint = diagnosticsAccessor + RegionalRoutingContext firstContactedLocationEndpoint = diagnosticsAccessor .getFirstContactedLocationEndpoint(failedRequest.requestContext.cosmosDiagnostics); if (firstContactedLocationEndpoint != null) { diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxDocumentServiceRequest.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxDocumentServiceRequest.java index 1cc6f316388a..ea22a95ab03a 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxDocumentServiceRequest.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxDocumentServiceRequest.java @@ -19,8 +19,6 @@ import com.azure.cosmos.models.PartitionKeyDefinition; import com.azure.cosmos.models.SqlQuerySpec; import com.azure.cosmos.models.PriorityLevel; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; import reactor.core.publisher.Flux; import java.net.URI; @@ -405,9 +403,10 @@ public static RxDocumentServiceRequest create(DiagnosticsClientContext clientCon Map headers, Object options) { + // only ever used for non Document operations RxDocumentServiceRequest request = new RxDocumentServiceRequest(clientContext, operation, resourceType, relativePath, resource.serializeJsonToByteBuffer( - CosmosItemSerializer.DEFAULT_SERIALIZER, + DefaultCosmosItemSerializer.INTERNAL_DEFAULT_SERIALIZER, null, resourceType == ResourceType.Document && (operation == OperationType.Create || operation == OperationType.Upsert)), headers, @@ -581,28 +580,6 @@ public static RxDocumentServiceRequest create(DiagnosticsClientContext clientCon return new RxDocumentServiceRequest(clientContext, operation, resourceType, relativePath, headers, authorizationTokenType); } - /** - * Creates a DocumentServiceRequest without body. - * - * @param operation the operation type. - * @param resourceType the resource type. - * @param relativePath the relative URI path. - * @param headers the request headers. - * @return the created document service request. - */ - public static RxDocumentServiceRequest create(DiagnosticsClientContext clientContext, - OperationType operation, - Resource resource, - ResourceType resourceType, - String relativePath, - Map headers) { - ByteBuffer resourceContent = resource.serializeJsonToByteBuffer( - CosmosItemSerializer.DEFAULT_SERIALIZER, - null, - resourceType == ResourceType.Document && (operation == OperationType.Create || operation == OperationType.Upsert)); - return new RxDocumentServiceRequest(clientContext, operation, resourceType, relativePath, resourceContent, headers, AuthorizationTokenType.PrimaryMasterKey); - } - /** * Creates a DocumentServiceRequest without body. * @@ -621,7 +598,7 @@ public static RxDocumentServiceRequest create(DiagnosticsClientContext clientCon Map headers, AuthorizationTokenType authorizationTokenType) { ByteBuffer resourceContent = resource.serializeJsonToByteBuffer( - CosmosItemSerializer.DEFAULT_SERIALIZER, + DefaultCosmosItemSerializer.INTERNAL_DEFAULT_SERIALIZER, // only used from test code null, resourceType == ResourceType.Document && (operation == OperationType.Create || operation == OperationType.Upsert)); return new RxDocumentServiceRequest(clientContext, operation, resourceType, relativePath, resourceContent, headers, authorizationTokenType); @@ -760,7 +737,7 @@ public static RxDocumentServiceRequest createFromName( String resourceFullName, ResourceType resourceType) { ByteBuffer resourceContent = resource.serializeJsonToByteBuffer( - CosmosItemSerializer.DEFAULT_SERIALIZER, + DefaultCosmosItemSerializer.INTERNAL_DEFAULT_SERIALIZER, // only used from test code null, resourceType == ResourceType.Document && (operationType == OperationType.Create || operationType == OperationType.Upsert)); return new RxDocumentServiceRequest(clientContext, @@ -1036,38 +1013,6 @@ public boolean isValidAddress(ResourceType resourceType) { } } - public static RxDocumentServiceRequest createFromResource(RxDocumentServiceRequest request, Resource modifiedResource) { - RxDocumentServiceRequest modifiedRequest; - if (!request.getIsNameBased()) { - modifiedRequest = RxDocumentServiceRequest.create(request.clientContext, - request.getOperationType(), - request.getResourceId(), - request.getResourceType(), - modifiedResource, - request.headers); - } else { - modifiedRequest = RxDocumentServiceRequest.createFromName(request.clientContext, - request.getOperationType(), - modifiedResource, - request.getResourceAddress(), - request.getResourceType()); - } - return modifiedRequest; - } - - public void clearRoutingHints() { - this.partitionKeyRangeIdentity = null; - this.requestContext.resolvedPartitionKeyRange = null; - } - - public synchronized Flux getContentAsByteBufFlux() { - if (contentAsByteArray == null) { - return Flux.empty(); - } - - return Flux.just(Unpooled.wrappedBuffer(contentAsByteArray)); - } - public synchronized Flux getContentAsByteArrayFlux() { if (contentAsByteArray == null) { return Flux.empty(); 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 f5820ad69c9d..03d0313d677a 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 @@ -66,7 +66,7 @@ public class RxGatewayStoreModel implements RxStoreModel, HttpTransportSerialize private final QueryCompatibilityMode queryCompatibilityMode; protected final GlobalEndpointManager globalEndpointManager; private ConsistencyLevel defaultConsistencyLevel; - private ISessionContainer sessionContainer; + protected ISessionContainer sessionContainer; private ThroughputControlStore throughputControlStore; private boolean useMultipleWriteLocations; private RxPartitionKeyRangeCache partitionKeyRangeCache; @@ -316,7 +316,7 @@ private HttpHeaders getHttpRequestHeaders(Map headers) { } public URI getRootUri(RxDocumentServiceRequest request) { - return this.globalEndpointManager.resolveServiceEndpoint(request).getGatewayLocationEndpoint(); + return this.globalEndpointManager.resolveServiceEndpoint(request).getGatewayRegionalEndpoint(); } private URI getUri(RxDocumentServiceRequest request) throws URISyntaxException { @@ -324,7 +324,7 @@ private URI getUri(RxDocumentServiceRequest request) throws URISyntaxException { if (rootUri == null) { if (request.getIsMedia()) { // For media read request, always use the write endpoint. - rootUri = this.globalEndpointManager.getWriteEndpoints().get(0).getGatewayLocationEndpoint(); + rootUri = this.globalEndpointManager.getWriteEndpoints().get(0).getGatewayRegionalEndpoint(); } else { rootUri = getRootUri(request); } @@ -519,6 +519,7 @@ private void validateOrThrow(RxDocumentServiceRequest request, String.format("%s, StatusCode: %s", cosmosError.getMessage(), statusCodeString), cosmosError.getPartitionedQueryExecutionInfo()); + logger.error("Error body: {} - {}", statusCode, body); CosmosException dce = BridgeInternal.createCosmosException(request.requestContext.resourcePhysicalAddress, statusCode, cosmosError, headers.toMap()); BridgeInternal.setRequestHeaders(dce, request.getHeaders()); throw dce; diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ShouldRetryResult.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ShouldRetryResult.java index 56a0ed924c44..80eff8fcc626 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ShouldRetryResult.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ShouldRetryResult.java @@ -41,7 +41,7 @@ public static ShouldRetryResult noRetryOnNonRelatedException() { return new ShouldRetryResult(null, null, false, null, true); } - public static ShouldRetryResult noRetryOnNonRelatedException(Exception e) { + public static ShouldRetryResult errorOnNonRelatedException(Exception e) { return new ShouldRetryResult(null, e, false, null, true); } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/SpatialIndex.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/SpatialIndex.java index ddea3b50aaeb..9243238be30d 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/SpatialIndex.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/SpatialIndex.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.apachecommons.lang.StringUtils; import com.fasterxml.jackson.databind.node.ObjectNode; @@ -71,7 +70,7 @@ public DataType getDataType() { * @return the SpatialIndex. */ public SpatialIndex setDataType(DataType dataType) { - super.set(Constants.Properties.DATA_TYPE, dataType.toString(), CosmosItemSerializer.DEFAULT_SERIALIZER); + super.set(Constants.Properties.DATA_TYPE, dataType.toString()); return this; } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/StoredProcedure.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/StoredProcedure.java index a8c69f0358a2..cacb5933ce56 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/StoredProcedure.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/StoredProcedure.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation; -import com.azure.cosmos.CosmosItemSerializer; import com.fasterxml.jackson.databind.node.ObjectNode; /** @@ -56,7 +55,7 @@ public String getBody() { * @param body the body of the stored procedure. */ public void setBody(String body) { - this.set(Constants.Properties.BODY, body, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.BODY, body); } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ThinClientStoreModel.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ThinClientStoreModel.java index da153ccd5ff1..4b8e96ae9529 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ThinClientStoreModel.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ThinClientStoreModel.java @@ -3,6 +3,7 @@ package com.azure.cosmos.implementation; import com.azure.cosmos.ConsistencyLevel; +import com.azure.cosmos.implementation.apachecommons.lang.StringUtils; import com.azure.cosmos.implementation.directconnectivity.StoreResponse; import com.azure.cosmos.implementation.directconnectivity.WFConstants; import com.azure.cosmos.implementation.directconnectivity.rntbd.RntbdConstants; @@ -22,15 +23,12 @@ import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; -import java.io.IOException; import java.net.URI; -import java.nio.file.Files; import java.time.Instant; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.UUID; import static com.azure.cosmos.implementation.guava25.base.Preconditions.checkNotNull; @@ -44,20 +42,6 @@ public class ThinClientStoreModel extends RxGatewayStoreModel { private static final Logger logger = LoggerFactory.getLogger(ThinClientStoreModel.class); - private static final List thinClientHeadersInOrder = Arrays.asList( - RntbdConstants.RntbdRequestHeader.EffectivePartitionKey, - RntbdConstants.RntbdRequestHeader.GlobalDatabaseAccountName, - RntbdConstants.RntbdRequestHeader.DatabaseName, - RntbdConstants.RntbdRequestHeader.CollectionName, - RntbdConstants.RntbdRequestHeader.CollectionRid, - //RntbdConstants.RntbdRequestHeader.ResourceId, - RntbdConstants.RntbdRequestHeader.PayloadPresent, - RntbdConstants.RntbdRequestHeader.DocumentName, - RntbdConstants.RntbdRequestHeader.AuthorizationToken, - RntbdConstants.RntbdRequestHeader.Date); - - - public ThinClientStoreModel( DiagnosticsClientContext clientContext, ISessionContainer sessionContainer, @@ -101,14 +85,15 @@ protected Map getDefaultHeaders( // Since the Thin client proxy also needs to set the user-agent header to a different value // it is not added to the rntbd headers - just http-headers in the SDK defaultHeaders.put(HttpConstants.HttpHeaders.USER_AGENT, userAgentContainer.getUserAgent()); + defaultHeaders.put(HttpConstants.HttpHeaders.ACTIVITY_ID, "000000-0000-0000-00000-000000000001"); return defaultHeaders; } @Override public URI getRootUri(RxDocumentServiceRequest request) { - //var uri = this.globalEndpointManager.resolveServiceEndpoint(request).getThinClientLocationEndpoint(); - return URI.create("https://57.155.105.105:10650/"); // https://chukangzhongstagesignoff-eastus2.documents-staging.windows-ppe.net:10650/ + // need to have thin client endpoint here + return this.globalEndpointManager.resolveServiceEndpoint(request).getThinclientRegionalEndpoint(); } @Override @@ -127,12 +112,21 @@ public StoreResponse unwrapToStoreResponse(RxDocumentServiceRequest request, int response.setDecodeEndTime(Instant.now()); response.setDecodeStartTime(decodeStartTime); - return super.unwrapToStoreResponse( - request, - response.getStatus().code(), - new HttpHeaders(response.getHeaders().asMap(request.getActivityId())), - response.getContent() - ); + StoreResponse storeResponse = null; + try { + storeResponse = super.unwrapToStoreResponse( + request, + response.getStatus().code(), + new HttpHeaders(response.getHeaders().asMap(request.getActivityId())), + response.getContent() + ); + } catch (Exception error) { + logger.error("Decoding error happened", error); + + throw error; + } + + return storeResponse; } return super.unwrapToStoreResponse(request, statusCode, headers, null); @@ -141,6 +135,13 @@ public StoreResponse unwrapToStoreResponse(RxDocumentServiceRequest request, int throw new IllegalStateException("Invalid rntbd response"); } + private static String toHexString(byte[] ba) { + StringBuilder str = new StringBuilder(); + for(int i = 0; i < ba.length; i++) + str.append(String.format("%x", ba[i])); + return str.toString(); + } + @Override public HttpRequest wrapInHttpRequest(RxDocumentServiceRequest request, URI requestUri) throws Exception { @@ -148,18 +149,19 @@ public HttpRequest wrapInHttpRequest(RxDocumentServiceRequest request, URI reque request.setThinclientHeaders(request.getOperationType().name(), request.getResourceType().name()); byte[] epk = request.getPartitionKeyInternal().getEffectivePartitionKeyBytes(request.getPartitionKeyInternal(), request.getPartitionKeyDefinition()); + logger.error("EPK Base64: {}", java.util.Base64.getEncoder().encodeToString(epk)); + logger.error("EPK HEX: {}", toHexString(epk)); if (request.properties == null) { request.properties = new HashMap<>(); } + //request.properties.put(EFFECTIVE_PARTITION_KEY, epk); //request.properties.put(HttpConstants.HttpHeaders.GLOBAL_DATABASE_ACCOUNT_NAME, "chukangzhongstagesignoff"); - request.getHeaders().put(HttpConstants.HttpHeaders.GLOBAL_DATABASE_ACCOUNT_NAME, "tiagonapoli-cdb-test"); // "chukangzhongstagesignoff" - request.getHeaders().put(WFConstants.BackendHeaders.COLLECTION_RID, "cLklAJU8SN0="); + request.getHeaders().put(HttpConstants.HttpHeaders.GLOBAL_DATABASE_ACCOUNT_NAME, "thinclienttest"); // "chukangzhongstagesignoff" + request.getHeaders().put(WFConstants.BackendHeaders.COLLECTION_RID, "zd0DAK23P8I="); // todo - neharao1: no concept of a replica / service endpoint that can be passed RntbdRequestArgs rntbdRequestArgs = new RntbdRequestArgs(request); - // todo - neharao1: validate what HTTP headers are needed - for now have put default ThinClient HTTP headers - // todo - based on fabianm comment - thinClient also takes op type and resource type headers as HTTP headers HttpHeaders headers = this.getHttpHeaders(); RntbdRequest rntbdRequest = RntbdRequest.from(rntbdRequestArgs); @@ -171,6 +173,20 @@ public HttpRequest wrapInHttpRequest(RxDocumentServiceRequest request, URI reque } else { logger.error("Updated EPK to value {}", HexConvert.bytesToHex(epk)); } + + // Add SessionToken header + String sessionToken = this.sessionContainer.resolveGlobalSessionToken(request); + if (StringUtils.isNotEmpty(sessionToken)) { + boolean setSessionToken = rntbdRequest.setHeaderValue( + RntbdConstants.RntbdRequestHeader.SessionToken, + sessionToken); + if (!setSessionToken) { + logger.error("Failed to update SessionToken to value {}", sessionToken); + } else { + logger.debug("Updated SessionToken to value {}", sessionToken); + } + } + // todo: neharao1 - validate whether Java heap buffer is okay v/s Direct buffer // todo: eventually need to use pooled buffer ByteBuf byteBuf = Unpooled.buffer(); @@ -185,21 +201,9 @@ public HttpRequest wrapInHttpRequest(RxDocumentServiceRequest request, URI reque byte[] contentAsByteArray = new byte[byteBuf.writerIndex()]; byteBuf.getBytes(0, contentAsByteArray, 0, byteBuf.writerIndex()); - try { - Files.write(java.nio.file.Paths.get("E:\\Temp\\java" + UUID.randomUUID() + ".bin"), contentAsByteArray); - } catch (IOException e) { - e.printStackTrace(); - } - return new HttpRequest( HttpMethod.POST, - //requestUri, - //https://thinclient-performancetests-eastus2.documents-staging.windows-ppe.net:10650 - //https://cdb-ms-stage-eastus2-fe2-sql.eastus2.cloudapp.azure.com:10650 - //https://57.155.105.105:10650/ - // https://tiagonapoli-cdb-test-westus3.documents.azure.com:10650 - URI.create("https://57.155.105.105:10650/"), // https://127.0.0.1:10650/ //https://chukangzhongstagesignoff-eastus2.documents-staging.windows-ppe.net:10650/ // thinclient-performancetests-eastus2.documents-staging.windows-ppe.net cdb-ms-stage-eastus2-fe2-sql.eastus2.cloudapp.azure.com - //requestUri.getPort(), + requestUri, 10650, headers, Flux.just(contentAsByteArray)); @@ -211,6 +215,7 @@ private HttpHeaders getHttpHeaders() { Map defaultHeaders = this.getDefaultHeaders(); for (Map.Entry header : defaultHeaders.entrySet()) { + logger.error("HTTP Header {}: {}", header.getKey(), header.getValue()); httpHeaders.set(header.getKey(), header.getValue()); } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Trigger.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Trigger.java index a4edad87308d..afbb1204d6eb 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Trigger.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Trigger.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.apachecommons.lang.StringUtils; import com.azure.cosmos.models.TriggerOperation; import com.azure.cosmos.models.TriggerType; @@ -48,7 +47,7 @@ public String getBody() { * @param body the body of the trigger. */ public void setBody(String body) { - this.set(Constants.Properties.BODY, body, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.BODY, body); } /** @@ -74,7 +73,7 @@ public TriggerType getTriggerType() { * @param triggerType the trigger type. */ public void setTriggerType(TriggerType triggerType) { - this.set(Constants.Properties.TRIGGER_TYPE, triggerType.toString(), CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.TRIGGER_TYPE, triggerType.toString()); } /** @@ -100,6 +99,6 @@ public TriggerOperation getTriggerOperation() { * @param triggerOperation the trigger operation. */ public void setTriggerOperation(TriggerOperation triggerOperation) { - this.set(Constants.Properties.TRIGGER_OPERATION, triggerOperation.toString(), CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.TRIGGER_OPERATION, triggerOperation.toString()); } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/UserDefinedFunction.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/UserDefinedFunction.java index 2055423073d4..4f5bb2ab7ca0 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/UserDefinedFunction.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/UserDefinedFunction.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation; -import com.azure.cosmos.CosmosItemSerializer; import com.fasterxml.jackson.databind.node.ObjectNode; /** @@ -45,7 +44,7 @@ public String getBody() { * @param body the body. */ public void setBody(String body) { - this.set(Constants.Properties.BODY, body, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.BODY, body); } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Utils.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Utils.java index 9e8679bb7f37..a8779abb18e6 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Utils.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Utils.java @@ -12,6 +12,7 @@ import com.azure.cosmos.models.CosmosChangeFeedRequestOptions; import com.azure.cosmos.models.DedicatedGatewayRequestOptions; import com.azure.cosmos.models.ModelBridgeInternal; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -91,6 +92,26 @@ public class Utils { private static AtomicReference itemSerializerAccessor = new AtomicReference<>(null); + public static ObjectMapper getDocumentObjectMapper(String serializationInclusionMode) { + if (Strings.isNullOrEmpty(serializationInclusionMode)) { + return simpleObjectMapper; + } else if ("Always".equalsIgnoreCase(serializationInclusionMode)) { + return createAndInitializeObjectMapper(false) + .setSerializationInclusion(JsonInclude.Include.ALWAYS); + } else if ("NonNull".equalsIgnoreCase(serializationInclusionMode)) { + return createAndInitializeObjectMapper(false) + .setSerializationInclusion(JsonInclude.Include.NON_NULL); + } else if ("NonEmpty".equalsIgnoreCase(serializationInclusionMode)) { + return createAndInitializeObjectMapper(false) + .setSerializationInclusion(JsonInclude.Include.NON_EMPTY); + } else if ("NonDefault".equalsIgnoreCase(serializationInclusionMode)) { + return createAndInitializeObjectMapper(false) + .setSerializationInclusion(JsonInclude.Include.NON_DEFAULT); + } + + return simpleObjectMapper; + } + // NOTE DateTimeFormatter.RFC_1123_DATE_TIME cannot be used. // because cosmos db rfc1123 validation requires two digits for day. // so Thu, 04 Jan 2018 00:30:37 GMT is accepted by the cosmos db service, @@ -674,6 +695,7 @@ public static ByteBuffer serializeJsonToByteBuffer( boolean isIdValidationEnabled) { checkArgument(serializer != null || object instanceof Map, "Argument 'serializer' must not be null."); + try { ByteBufferOutputStream byteBufferOutputStream = new ByteBufferOutputStream(ONE_KB); Map jsonTreeMap = (object instanceof Map && serializer == null) @@ -688,6 +710,7 @@ public static ByteBuffer serializeJsonToByteBuffer( onAfterSerialization.accept(jsonTreeMap); } + ObjectMapper mapper = ensureItemSerializerAccessor().getItemObjectMapper(serializer); JsonNode jsonNode; if (jsonTreeMap instanceof PrimitiveJsonNodeMap) { @@ -695,10 +718,10 @@ public static ByteBuffer serializeJsonToByteBuffer( } else if (jsonTreeMap instanceof ObjectNodeMap && onAfterSerialization == null) { jsonNode = ((ObjectNodeMap) jsonTreeMap).getObjectNode(); } else { - jsonNode = simpleObjectMapper.convertValue(jsonTreeMap, JsonNode.class); + jsonNode = mapper.convertValue(jsonTreeMap, JsonNode.class); } - simpleObjectMapper.writeValue(byteBufferOutputStream, jsonNode); + mapper.writeValue(byteBufferOutputStream, jsonNode); return byteBufferOutputStream.asByteBuffer(); } catch (IOException e) { // TODO moderakh: on serialization/deserialization failure we should throw CosmosException here and elsewhere diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/WebExceptionRetryPolicy.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/WebExceptionRetryPolicy.java index c60eca10f47f..ab1452cd2537 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/WebExceptionRetryPolicy.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/WebExceptionRetryPolicy.java @@ -7,6 +7,7 @@ import com.azure.cosmos.implementation.directconnectivity.WebExceptionUtility; import com.azure.cosmos.implementation.http.HttpTimeoutPolicy; import com.azure.cosmos.implementation.http.HttpTimeoutPolicyDefault; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; @@ -14,6 +15,8 @@ import java.net.URI; import java.time.Duration; +import static com.azure.cosmos.implementation.guava25.base.Preconditions.checkArgument; + public class WebExceptionRetryPolicy implements IRetryPolicy { private final static Logger logger = LoggerFactory.getLogger(WebExceptionRetryPolicy.class); @@ -23,7 +26,8 @@ public class WebExceptionRetryPolicy implements IRetryPolicy { private HttpTimeoutPolicy timeoutPolicy; private boolean isReadRequest; private int retryCount = 0; - private URI locationEndpoint; + private RegionalRoutingContext regionalRoutingContext; + private URI overriddenEndpoint; public WebExceptionRetryPolicy() { durationTimer.start(); @@ -37,12 +41,17 @@ public WebExceptionRetryPolicy(RetryContext retryContext) { @Override public Mono shouldRetry(Exception e) { + + checkArgument(this.overriddenEndpoint != null || + this.regionalRoutingContext != null, + "Both overriddenEndpoint and regionalRoutingContext cannot null!"); + if (this.isOutOfRetries()) { logger .warn( "WebExceptionRetryPolicy() No more retrying on endpoint {}, operationType = {}, count = {}, " + "isAddressRefresh = {}", - this.locationEndpoint, + this.regionalRoutingContext != null ? this.regionalRoutingContext.getGatewayRegionalEndpoint() : this.overriddenEndpoint, this.request.getOperationType(), this.retryCount, this.request.isAddressRefresh()); @@ -63,7 +72,8 @@ public Mono shouldRetry(Exception e) { .debug("WebExceptionRetryPolicy() Retrying on endpoint {}, operationType = {}, resourceType = {}, count = {}, " + "isAddressRefresh = {}, shouldForcedAddressRefresh = {}, " + "shouldForceCollectionRoutingMapRefresh = {}", - this.locationEndpoint, this.request.getOperationType(), this.request.getResourceType(), this.retryCount, + this.regionalRoutingContext != null ? this.regionalRoutingContext.getGatewayRegionalEndpoint() : this.overriddenEndpoint, + this.request.getOperationType(), this.request.getResourceType(), this.retryCount, this.request.isAddressRefresh(), this.request.shouldForceAddressRefresh(), this.request.forceCollectionRoutingMapRefresh); @@ -77,7 +87,7 @@ public Mono shouldRetry(Exception e) { .debug( "WebExceptionRetryPolicy() No retrying on un-retryable exceptions on endpoint {}, operationType = {}, resourceType = {}, count = {}, " + "isAddressRefresh = {}", - this.locationEndpoint, + this.regionalRoutingContext != null ? this.regionalRoutingContext.getGatewayRegionalEndpoint() : this.overriddenEndpoint, this.request.getOperationType(), this.request.getResourceType(), this.retryCount, @@ -101,7 +111,8 @@ public void onBeforeSendRequest(RxDocumentServiceRequest request) { // set the initial response timeout this.request.setResponseTimeout(timeoutPolicy.getTimeoutAndDelaysList().get(0).getResponseTimeout()); - this.locationEndpoint = request.requestContext.locationEndpointToRoute; + this.regionalRoutingContext = request.requestContext.regionalRoutingContextToRoute; + this.overriddenEndpoint = request.getEndpointOverride(); } private boolean isOutOfRetries() { diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/batch/ItemBatchOperation.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/batch/ItemBatchOperation.java index 7eef76cef0ac..63ef403f4be4 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/batch/ItemBatchOperation.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/batch/ItemBatchOperation.java @@ -66,22 +66,22 @@ JsonSerializable getSerializedOperationInternal(CosmosItemSerializer effectiveIt jsonSerializable.set( BatchRequestResponseConstants.FIELD_OPERATION_TYPE, - ModelBridgeInternal.getOperationValueForCosmosItemOperationType(this.getOperationType()), - CosmosItemSerializer.DEFAULT_SERIALIZER); + ModelBridgeInternal.getOperationValueForCosmosItemOperationType(this.getOperationType()) + ); if (StringUtils.isNotEmpty(this.getId())) { jsonSerializable.set( BatchRequestResponseConstants.FIELD_ID, - this.getId(), - CosmosItemSerializer.DEFAULT_SERIALIZER); + this.getId() + ); } if (this.getItemInternal() != null) { if (this.getOperationType() == CosmosItemOperationType.PATCH) { jsonSerializable.set( BatchRequestResponseConstants.FIELD_RESOURCE_BODY, - PatchUtil.serializableBatchPatchOperation((CosmosPatchOperations) this.getItemInternal(), this.getRequestOptions()), - CosmosItemSerializer.DEFAULT_SERIALIZER); + PatchUtil.serializableBatchPatchOperation((CosmosPatchOperations) this.getItemInternal(), this.getRequestOptions()) + ); } else { jsonSerializable.set( BatchRequestResponseConstants.FIELD_RESOURCE_BODY, @@ -97,15 +97,15 @@ JsonSerializable getSerializedOperationInternal(CosmosItemSerializer effectiveIt if (StringUtils.isNotEmpty(requestOptions.getIfMatchETag())) { jsonSerializable.set( BatchRequestResponseConstants.FIELD_IF_MATCH, - requestOptions.getIfMatchETag(), - CosmosItemSerializer.DEFAULT_SERIALIZER); + requestOptions.getIfMatchETag() + ); } if (StringUtils.isNotEmpty(requestOptions.getIfNoneMatchETag())) { jsonSerializable.set( BatchRequestResponseConstants.FIELD_IF_NONE_MATCH, - requestOptions.getIfNoneMatchETag(), - CosmosItemSerializer.DEFAULT_SERIALIZER); + requestOptions.getIfNoneMatchETag() + ); } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/batch/ItemBulkOperation.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/batch/ItemBulkOperation.java index ccab373be9cb..bd08bd189748 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/batch/ItemBulkOperation.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/batch/ItemBulkOperation.java @@ -4,6 +4,7 @@ package com.azure.cosmos.implementation.batch; import com.azure.cosmos.CosmosItemSerializer; +import com.azure.cosmos.implementation.DefaultCosmosItemSerializer; import com.azure.cosmos.implementation.JsonSerializable; import com.azure.cosmos.implementation.RequestOptions; import com.azure.cosmos.implementation.apachecommons.lang.StringUtils; @@ -73,14 +74,14 @@ JsonSerializable getSerializedOperationInternal(CosmosItemSerializer effectiveIt jsonSerializable.set( BatchRequestResponseConstants.FIELD_OPERATION_TYPE, ModelBridgeInternal.getOperationValueForCosmosItemOperationType(this.getOperationType()), - CosmosItemSerializer.DEFAULT_SERIALIZER, + DefaultCosmosItemSerializer.INTERNAL_DEFAULT_SERIALIZER, false); if (StringUtils.isNotEmpty(this.getPartitionKeyJson())) { jsonSerializable.set( BatchRequestResponseConstants.FIELD_PARTITION_KEY, this.getPartitionKeyJson(), - CosmosItemSerializer.DEFAULT_SERIALIZER, + DefaultCosmosItemSerializer.INTERNAL_DEFAULT_SERIALIZER, false); } @@ -88,7 +89,7 @@ JsonSerializable getSerializedOperationInternal(CosmosItemSerializer effectiveIt jsonSerializable.set( BatchRequestResponseConstants.FIELD_ID, this.getId(), - CosmosItemSerializer.DEFAULT_SERIALIZER, + DefaultCosmosItemSerializer.INTERNAL_DEFAULT_SERIALIZER, false); } @@ -99,7 +100,7 @@ JsonSerializable getSerializedOperationInternal(CosmosItemSerializer effectiveIt PatchUtil.serializableBatchPatchOperation( (CosmosPatchOperations) this.getItemInternal(), this.getRequestOptions()), - CosmosItemSerializer.DEFAULT_SERIALIZER, + DefaultCosmosItemSerializer.INTERNAL_DEFAULT_SERIALIZER, false); } else { jsonSerializable.set( @@ -117,7 +118,7 @@ JsonSerializable getSerializedOperationInternal(CosmosItemSerializer effectiveIt jsonSerializable.set( BatchRequestResponseConstants.FIELD_IF_MATCH, requestOptions.getIfMatchETag(), - CosmosItemSerializer.DEFAULT_SERIALIZER, + DefaultCosmosItemSerializer.INTERNAL_DEFAULT_SERIALIZER, false); } @@ -125,7 +126,7 @@ JsonSerializable getSerializedOperationInternal(CosmosItemSerializer effectiveIt jsonSerializable.set( BatchRequestResponseConstants.FIELD_IF_NONE_MATCH, requestOptions.getIfNoneMatchETag(), - CosmosItemSerializer.DEFAULT_SERIALIZER, + DefaultCosmosItemSerializer.INTERNAL_DEFAULT_SERIALIZER, false); } @@ -136,7 +137,7 @@ JsonSerializable getSerializedOperationInternal(CosmosItemSerializer effectiveIt jsonSerializable.set( BatchRequestResponseConstants.FIELD_MINIMAL_RETURN_PREFERENCE, true, - CosmosItemSerializer.DEFAULT_SERIALIZER, + DefaultCosmosItemSerializer.INTERNAL_DEFAULT_SERIALIZER, false); } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/common/ChangeFeedContextClientImpl.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/common/ChangeFeedContextClientImpl.java index 9b3c58966495..b231547f3f85 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/common/ChangeFeedContextClientImpl.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/common/ChangeFeedContextClientImpl.java @@ -7,12 +7,8 @@ import com.azure.cosmos.CosmosAsyncDatabase; import com.azure.cosmos.CosmosBridgeInternal; import com.azure.cosmos.implementation.AsyncDocumentClient; -import com.azure.cosmos.implementation.ChangeFeedOperationState; -import com.azure.cosmos.implementation.Document; import com.azure.cosmos.implementation.ImplementationBridgeHelpers; -import com.azure.cosmos.implementation.OperationType; import com.azure.cosmos.implementation.PartitionKeyRange; -import com.azure.cosmos.implementation.ResourceType; import com.azure.cosmos.implementation.changefeed.ChangeFeedContextClient; import com.azure.cosmos.implementation.routing.Range; import com.azure.cosmos.models.CosmosBulkOperationResponse; @@ -42,7 +38,6 @@ import java.net.URI; import java.util.ArrayList; import java.util.List; -import java.util.stream.Collectors; import static com.azure.cosmos.CosmosBridgeInternal.getContextClient; import static com.azure.cosmos.implementation.guava25.base.Preconditions.checkNotNull; @@ -151,7 +146,7 @@ public Flux> createDocumentChangeFeedQuery(CosmosAsyncConta } return collectionLink .queryChangeFeed(changeFeedRequestOptions, klass) - .byPage() + .byPage().take(1, true) .publishOn(this.scheduler); } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/common/ChangeFeedStartFromBeginningImpl.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/common/ChangeFeedStartFromBeginningImpl.java index 73fd5a87a8ca..5cbba6d66901 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/common/ChangeFeedStartFromBeginningImpl.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/common/ChangeFeedStartFromBeginningImpl.java @@ -2,7 +2,6 @@ // Licensed under the MIT License. package com.azure.cosmos.implementation.changefeed.common; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.RxDocumentServiceRequest; @@ -18,8 +17,8 @@ public void populatePropertyBag() { synchronized(this) { this.set( Constants.Properties.CHANGE_FEED_START_FROM_TYPE, - ChangeFeedStartFromTypes.BEGINNING, - CosmosItemSerializer.DEFAULT_SERIALIZER); + ChangeFeedStartFromTypes.BEGINNING + ); } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/common/ChangeFeedStartFromETagAndFeedRangeImpl.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/common/ChangeFeedStartFromETagAndFeedRangeImpl.java index 9fef58737ba0..cf46f578b20f 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/common/ChangeFeedStartFromETagAndFeedRangeImpl.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/common/ChangeFeedStartFromETagAndFeedRangeImpl.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation.changefeed.common; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.HttpConstants; import com.azure.cosmos.implementation.RxDocumentServiceRequest; @@ -88,13 +87,13 @@ public void populatePropertyBag() { synchronized(this) { this.set( Constants.Properties.CHANGE_FEED_START_FROM_TYPE, - ChangeFeedStartFromTypes.LEASE, - CosmosItemSerializer.DEFAULT_SERIALIZER); + ChangeFeedStartFromTypes.LEASE + ); this.set( Constants.Properties.CHANGE_FEED_START_FROM_ETAG, - this.eTag, - CosmosItemSerializer.DEFAULT_SERIALIZER); + this.eTag + ); this.feedRange.setProperties( this, diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/common/ChangeFeedStartFromLegacyContinuationImpl.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/common/ChangeFeedStartFromLegacyContinuationImpl.java index 6ffc441932d0..108e7adff139 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/common/ChangeFeedStartFromLegacyContinuationImpl.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/common/ChangeFeedStartFromLegacyContinuationImpl.java @@ -2,7 +2,6 @@ // Licensed under the MIT License. package com.azure.cosmos.implementation.changefeed.common; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.RxDocumentServiceRequest; @@ -18,8 +17,8 @@ public void populatePropertyBag() { synchronized (this) { this.set( Constants.Properties.CHANGE_FEED_START_FROM_TYPE, - ChangeFeedStartFromTypes.LEGACY_CHECKPOINT, - CosmosItemSerializer.DEFAULT_SERIALIZER); + ChangeFeedStartFromTypes.LEGACY_CHECKPOINT + ); } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/common/ChangeFeedStartFromNowImpl.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/common/ChangeFeedStartFromNowImpl.java index 4612f601f63b..d3ff050f1a82 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/common/ChangeFeedStartFromNowImpl.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/common/ChangeFeedStartFromNowImpl.java @@ -2,7 +2,6 @@ // Licensed under the MIT License. package com.azure.cosmos.implementation.changefeed.common; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.HttpConstants; import com.azure.cosmos.implementation.RxDocumentServiceRequest; @@ -22,8 +21,8 @@ public void populatePropertyBag() { synchronized(this) { this.set( Constants.Properties.CHANGE_FEED_START_FROM_TYPE, - ChangeFeedStartFromTypes.NOW, - CosmosItemSerializer.DEFAULT_SERIALIZER); + ChangeFeedStartFromTypes.NOW + ); } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/common/ChangeFeedStartFromPointInTimeImpl.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/common/ChangeFeedStartFromPointInTimeImpl.java index 0a38fd42ca76..927566eeea26 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/common/ChangeFeedStartFromPointInTimeImpl.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/common/ChangeFeedStartFromPointInTimeImpl.java @@ -2,7 +2,6 @@ // Licensed under the MIT License. package com.azure.cosmos.implementation.changefeed.common; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.HttpConstants; import com.azure.cosmos.implementation.RxDocumentServiceRequest; @@ -52,13 +51,13 @@ public void populatePropertyBag() { synchronized(this) { this.set( com.azure.cosmos.implementation.Constants.Properties.CHANGE_FEED_START_FROM_TYPE, - ChangeFeedStartFromTypes.POINT_IN_TIME, - CosmosItemSerializer.DEFAULT_SERIALIZER); + ChangeFeedStartFromTypes.POINT_IN_TIME + ); this.set( Constants.Properties.CHANGE_FEED_START_FROM_POINT_IN_TIME_MS, - this.pointInTime.toEpochMilli(), - CosmosItemSerializer.DEFAULT_SERIALIZER); + this.pointInTime.toEpochMilli() + ); } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/common/ChangeFeedStateV1.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/common/ChangeFeedStateV1.java index 4311f1631462..a6298a00b783 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/common/ChangeFeedStateV1.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/common/ChangeFeedStateV1.java @@ -2,7 +2,6 @@ // Licensed under the MIT License. package com.azure.cosmos.implementation.changefeed.common; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.HttpConstants; import com.azure.cosmos.implementation.RxDocumentServiceRequest; @@ -11,6 +10,8 @@ import com.azure.cosmos.implementation.feedranges.FeedRangeInternal; import com.azure.cosmos.implementation.query.CompositeContinuationToken; +import java.util.ArrayList; +import java.util.List; import java.util.Objects; import static com.azure.cosmos.implementation.guava25.base.Preconditions.checkNotNull; @@ -38,6 +39,20 @@ public ChangeFeedStateV1( this.mode = mode; } + public ChangeFeedStateV1(ChangeFeedStateV1 toBeCloned) { + this.containerRid = toBeCloned.containerRid; + this.feedRange = toBeCloned.feedRange; + this.startFromSettings = toBeCloned.startFromSettings; + if (toBeCloned.continuation != null) { + List compositeContinuationTokens = new ArrayList<>(); + compositeContinuationTokens.addAll(toBeCloned.continuation.getCompositeContinuationTokens()); + this.continuation = FeedRangeContinuation.create(toBeCloned.continuation.getContainerRid(), toBeCloned.continuation.getFeedRange(), compositeContinuationTokens); + } else { + this.continuation = null; + } + this.mode = toBeCloned.mode; + } + @Override public FeedRangeContinuation getContinuation() { return this.continuation; @@ -141,30 +156,30 @@ public void populatePropertyBag() { this.set( Constants.Properties.CHANGE_FEED_STATE_VERSION, - ChangeFeedStateVersions.V1, - CosmosItemSerializer.DEFAULT_SERIALIZER); + ChangeFeedStateVersions.V1 + ); this.set( Constants.Properties.CHANGE_FEED_STATE_RESOURCE_ID, - this.containerRid, - CosmosItemSerializer.DEFAULT_SERIALIZER); + this.containerRid + ); this.set( Constants.Properties.CHANGE_FEED_STATE_MODE, - this.mode, - CosmosItemSerializer.DEFAULT_SERIALIZER); + this.mode + ); this.set( Constants.Properties.CHANGE_FEED_STATE_START_FROM, - this.startFromSettings, - CosmosItemSerializer.DEFAULT_SERIALIZER); + this.startFromSettings + ); if (this.continuation != null) { this.continuation.populatePropertyBag(); this.set( Constants.Properties.CHANGE_FEED_STATE_CONTINUATION, - this.continuation, - CosmosItemSerializer.DEFAULT_SERIALIZER); + this.continuation + ); this.feedRange.removeProperties(this); } else { this.feedRange.setProperties(this, true); diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/epkversion/BootstrapperImpl.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/epkversion/BootstrapperImpl.java index 8cfd5cbd5eb4..0fea7770c53e 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/epkversion/BootstrapperImpl.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/epkversion/BootstrapperImpl.java @@ -5,11 +5,13 @@ import com.azure.cosmos.implementation.CosmosSchedulers; import com.azure.cosmos.implementation.Strings; import com.azure.cosmos.implementation.changefeed.Bootstrapper; +import com.azure.cosmos.implementation.changefeed.Lease; import com.azure.cosmos.implementation.changefeed.LeaseStore; import com.azure.cosmos.implementation.changefeed.LeaseStoreManager; import com.azure.cosmos.implementation.changefeed.common.ChangeFeedMode; import com.azure.cosmos.implementation.changefeed.common.ChangeFeedState; import com.azure.cosmos.implementation.changefeed.common.LeaseVersion; +import com.azure.cosmos.models.ChangeFeedProcessorOptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; @@ -27,6 +29,8 @@ class BootstrapperImpl implements Bootstrapper { private final PartitionSynchronizer synchronizer; private final LeaseStore leaseStore; private final LeaseStoreManager epkRangeVersionLeaseStoreManager; + private final LeaseStoreManager pkRangeVersionLeaseStoreManager; + private final ChangeFeedProcessorOptions changeFeedProcessorOptions; private final ChangeFeedMode changeFeedModeToStart; private final Duration lockTime; private final Duration sleepTime; @@ -34,15 +38,31 @@ class BootstrapperImpl implements Bootstrapper { private volatile boolean isInitialized; private volatile boolean isLockAcquired; - public BootstrapperImpl(PartitionSynchronizer synchronizer, LeaseStore leaseStore, Duration lockTime, Duration sleepTime, LeaseStoreManager epkRangeVersionLeaseStoreManager, ChangeFeedMode changeFeedModeToStart) { + public BootstrapperImpl( + PartitionSynchronizer synchronizer, + LeaseStore leaseStore, + Duration lockTime, + Duration sleepTime, + LeaseStoreManager epkRangeVersionLeaseStoreManager, + LeaseStoreManager pkRangeVersionLeaseStoreManager, + ChangeFeedProcessorOptions changeFeedProcessorOptions, + ChangeFeedMode changeFeedModeToStart) { + checkNotNull(synchronizer, "Argument 'synchronizer' can not be null"); checkNotNull(leaseStore, "Argument 'leaseStore' can not be null"); + checkNotNull(epkRangeVersionLeaseStoreManager, "Argument 'epkRangeVersionLeaseStoreManager' can not be null"); + checkNotNull(pkRangeVersionLeaseStoreManager, "Argument 'pkRangeVersionLeaseStoreManager' can not be null"); + checkNotNull(changeFeedProcessorOptions, "Argument 'changeFeedProcessorOptions' can not be null"); + checkNotNull(changeFeedModeToStart, "Argument 'changeFeedModeToStart' can not be null"); + checkArgument(lockTime != null && this.isPositive(lockTime), "lockTime should be non-null and positive"); checkArgument(sleepTime != null && this.isPositive(sleepTime), "sleepTime should be non-null and positive"); this.synchronizer = synchronizer; this.leaseStore = leaseStore; this.epkRangeVersionLeaseStoreManager = epkRangeVersionLeaseStoreManager; + this.pkRangeVersionLeaseStoreManager = pkRangeVersionLeaseStoreManager; + this.changeFeedProcessorOptions = changeFeedProcessorOptions; this.changeFeedModeToStart = changeFeedModeToStart; this.lockTime = lockTime; this.sleepTime = sleepTime; @@ -97,11 +117,26 @@ public Mono initialize() { private Mono validateLeaseCFModeInteroperabilityForEpkRangeBasedLease() { - // fetches only 1 epk-based lease for a given lease prefix - return this.epkRangeVersionLeaseStoreManager - .getTopLeases(1) - // pick one lease corresponding to a lease prefix (lease prefix denotes a unique feed) - .next() + // fetch pk-range based lease first (all versions and deletes is bootstrapping) + return this.pkRangeVersionLeaseStoreManager.getTopLeases(1).next() + .flatMap(lease -> { + + if (lease.getVersion() == LeaseVersion.PARTITION_KEY_BASED_LEASE) { + + String errorMessage = String.format("ChangeFeedProcessor#handleAllVersionsAndDeletes cannot be invoked when" + + "ChangeFeedProcessor#handleChanges was also started for" + + "lease prefix : %s", this.changeFeedProcessorOptions.getLeasePrefix()); + + return Mono.error(new IllegalStateException(errorMessage)); + } + + return Mono.empty(); + } + ) + // if no pk-range based lease exists, try fetching epk-range based lease + .switchIfEmpty(this.epkRangeVersionLeaseStoreManager.getTopLeases(1).next()) + // type is known from upstream so doing an explicit cast + .flatMap(epkRangeVersionLease -> Mono.just((Lease) epkRangeVersionLease)) .flatMap(lease -> { if (lease.getVersion() == LeaseVersion.EPK_RANGE_BASED_LEASE) { @@ -111,7 +146,12 @@ private Mono validateLeaseCFModeInteroperabilityForEpkRangeBasedLease() { ChangeFeedState changeFeedState = ChangeFeedState.fromString(lease.getContinuationToken()); if (changeFeedState.getMode() != this.changeFeedModeToStart) { - return Mono.error(new IllegalStateException("Change feed mode in the pre-existing lease is : " + changeFeedState.getMode() + " while the expected change feed mode is : " + this.changeFeedModeToStart)); + + String errorMessage = String.format("ChangeFeedProcessor#handleAllVersionsAndDeletes cannot be invoked when " + + "ChangeFeedProcessor#handleLatestVersionChanges were also started for " + + "lease prefix : %s", this.changeFeedProcessorOptions.getLeasePrefix()); + + return Mono.error(new IllegalStateException(errorMessage)); } } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/epkversion/ChangeFeedProcessorImplBase.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/epkversion/ChangeFeedProcessorImplBase.java index bef9beccd058..0b0748b3d0ac 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/epkversion/ChangeFeedProcessorImplBase.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/epkversion/ChangeFeedProcessorImplBase.java @@ -232,7 +232,6 @@ public Mono> getCurrentState() { return this.feedContextClient .createDocumentChangeFeedQuery(this.feedContextClient.getContainerClient(), options, ChangeFeedProcessorItem.class, false) - .take(1) .map(feedResponse -> { ChangeFeedProcessorState changeFeedProcessorState = new ChangeFeedProcessorState() .setHostName(lease.getOwner()) @@ -386,18 +385,19 @@ private Mono buildPartitionManager(LeaseStoreManager leaseStor this.changeFeedMode); Bootstrapper bootstrapper; - if (this.canBootstrapFromPkRangeIdVersionLeaseStore()) { - String pkRangeIdVersionLeasePrefix = this.getPkRangeIdVersionLeasePrefix(); - RequestOptionsFactory requestOptionsFactory = new PartitionedByIdCollectionRequestOptionsFactory(); - LeaseStoreManager pkRangeIdVersionLeaseStoreManager = - com.azure.cosmos.implementation.changefeed.pkversion.LeaseStoreManagerImpl.builder() - .leasePrefix(pkRangeIdVersionLeasePrefix) - .leaseCollectionLink(this.leaseContextClient.getContainerClient()) - .leaseContextClient(this.leaseContextClient) - .requestOptionsFactory(requestOptionsFactory) - .hostName(this.hostName) - .build(); + String pkRangeIdVersionLeasePrefix = this.getPkRangeIdVersionLeasePrefix(); + RequestOptionsFactory requestOptionsFactory = new PartitionedByIdCollectionRequestOptionsFactory(); + LeaseStoreManager pkRangeIdVersionLeaseStoreManager = + com.azure.cosmos.implementation.changefeed.pkversion.LeaseStoreManagerImpl.builder() + .leasePrefix(pkRangeIdVersionLeasePrefix) + .leaseCollectionLink(this.leaseContextClient.getContainerClient()) + .leaseContextClient(this.leaseContextClient) + .requestOptionsFactory(requestOptionsFactory) + .hostName(this.hostName) + .build(); + + if (this.canBootstrapFromPkRangeIdVersionLeaseStore()) { bootstrapper = new PkRangeIdVersionLeaseStoreBootstrapperImpl( synchronizer, @@ -406,6 +406,7 @@ private Mono buildPartitionManager(LeaseStoreManager leaseStor this.sleepTime, pkRangeIdVersionLeaseStoreManager, leaseStoreManager, + this.changeFeedProcessorOptions, this.changeFeedMode); } else { bootstrapper = new BootstrapperImpl( @@ -414,6 +415,8 @@ private Mono buildPartitionManager(LeaseStoreManager leaseStor this.lockTime, this.sleepTime, leaseStoreManager, + pkRangeIdVersionLeaseStoreManager, + this.changeFeedProcessorOptions, this.changeFeedMode); } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/epkversion/LeaseStoreImpl.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/epkversion/LeaseStoreImpl.java index 581636dce72a..05041099f6c9 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/epkversion/LeaseStoreImpl.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/epkversion/LeaseStoreImpl.java @@ -5,7 +5,6 @@ import com.azure.cosmos.BridgeInternal; import com.azure.cosmos.CosmosAsyncContainer; import com.azure.cosmos.CosmosException; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.Exceptions; import com.azure.cosmos.implementation.InternalObjectNode; @@ -103,8 +102,8 @@ public Mono acquireInitializationLock(Duration lockExpirationTime) { containerDocument.setId(lockId); containerDocument.set( Constants.Properties.TTL, - Long.valueOf(lockExpirationTime.getSeconds()).intValue(), - CosmosItemSerializer.DEFAULT_SERIALIZER); + Long.valueOf(lockExpirationTime.getSeconds()).intValue() + ); return this.client.createItem( this.leaseCollectionLink, diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/epkversion/LeaseStoreManagerImpl.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/epkversion/LeaseStoreManagerImpl.java index 0d7e2133c3df..c243630d332e 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/epkversion/LeaseStoreManagerImpl.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/epkversion/LeaseStoreManagerImpl.java @@ -48,7 +48,7 @@ * Provides flexible way to buildAsyncClient lease manager constructor parameters. * For the actual creation of lease manager instance, delegates to lease manager factory. */ -class LeaseStoreManagerImpl implements LeaseStoreManager, LeaseStoreManager.LeaseStoreManagerBuilderDefinition { +public class LeaseStoreManagerImpl implements LeaseStoreManager, LeaseStoreManager.LeaseStoreManagerBuilderDefinition { private final String LEASE_STORE_MANAGER_LEASE_SUFFIX = ".."; private final Logger logger = LoggerFactory.getLogger(LeaseStoreManagerImpl.class); diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/epkversion/PartitionProcessorImpl.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/epkversion/PartitionProcessorImpl.java index 91c8dcb2d146..855e36c8d9f1 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/epkversion/PartitionProcessorImpl.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/epkversion/PartitionProcessorImpl.java @@ -119,8 +119,7 @@ public Mono run(CancellationToken cancellationToken) { return this.documentClient.createDocumentChangeFeedQuery( this.settings.getCollectionSelfLink(), this.options, - itemType) - .limitRequest(1); + itemType); }) .flatMap(documentFeedResponse -> { if (cancellationToken.isCancellationRequested()) return Flux.error(new TaskCancelledException()); diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/epkversion/PkRangeIdVersionLeaseStoreBootstrapperImpl.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/epkversion/PkRangeIdVersionLeaseStoreBootstrapperImpl.java index 648ada21e87f..bdd4096e93d1 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/epkversion/PkRangeIdVersionLeaseStoreBootstrapperImpl.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/epkversion/PkRangeIdVersionLeaseStoreBootstrapperImpl.java @@ -11,6 +11,7 @@ import com.azure.cosmos.implementation.changefeed.common.ChangeFeedMode; import com.azure.cosmos.implementation.changefeed.common.ChangeFeedState; import com.azure.cosmos.implementation.changefeed.common.LeaseVersion; +import com.azure.cosmos.models.ChangeFeedProcessorOptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; @@ -38,6 +39,7 @@ public class PkRangeIdVersionLeaseStoreBootstrapperImpl implements Bootstrapper private final Duration lockTime; private final Duration sleepTime; private final ChangeFeedMode changeFeedModeToStart; + private final ChangeFeedProcessorOptions changeFeedProcessorOptions; private volatile boolean isInitialized; private volatile boolean isLockAcquired; @@ -50,7 +52,9 @@ public PkRangeIdVersionLeaseStoreBootstrapperImpl( Duration sleepTime, LeaseStoreManager pkRangeIdVersionLeaseStoreManager, LeaseStoreManager epkRangeVersionLeaseStoreManager, + ChangeFeedProcessorOptions changeFeedProcessorOptions, ChangeFeedMode changeFeedModeToStart) { + checkNotNull(synchronizer, "Argument 'synchronizer' can not be null"); checkNotNull(leaseStore, "Argument 'leaseStore' can not be null"); checkArgument(lockTime != null && this.isPositive(lockTime), "lockTime should be non-null and positive"); @@ -63,6 +67,7 @@ public PkRangeIdVersionLeaseStoreBootstrapperImpl( this.leaseStore = leaseStore; this.pkRangeIdVersionLeaseStoreManager = pkRangeIdVersionLeaseStoreManager; this.epkRangeVersionLeaseStoreManager = epkRangeVersionLeaseStoreManager; + this.changeFeedProcessorOptions = changeFeedProcessorOptions; this.changeFeedModeToStart = changeFeedModeToStart; this.lockTime = lockTime; this.sleepTime = sleepTime; @@ -166,7 +171,11 @@ private Mono validateLeaseCFModeInteroperabilityForEpkRangeBasedLease() { ChangeFeedState changeFeedState = ChangeFeedState.fromString(lease.getContinuationToken()); if (changeFeedState.getMode() != this.changeFeedModeToStart) { - return Mono.error(new IllegalStateException("Change feed mode in the pre-existing lease is : " + changeFeedState.getMode() + " while the expected change feed mode is : " + this.changeFeedModeToStart)); + String errorMessage = String.format("ChangeFeedProcessor#handleLatestVersionChanges cannot be invoked when " + + "ChangeFeedProcessor#handleAllVersionsAndDeletes was also started for " + + "lease prefix : %s", this.changeFeedProcessorOptions.getLeasePrefix()); + + return Mono.error(new IllegalStateException(errorMessage)); } } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/pkversion/BootstrapperImpl.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/pkversion/BootstrapperImpl.java index 38afe6253554..b5f04ea5f594 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/pkversion/BootstrapperImpl.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/pkversion/BootstrapperImpl.java @@ -3,8 +3,14 @@ package com.azure.cosmos.implementation.changefeed.pkversion; import com.azure.cosmos.implementation.CosmosSchedulers; +import com.azure.cosmos.implementation.Strings; import com.azure.cosmos.implementation.changefeed.Bootstrapper; import com.azure.cosmos.implementation.changefeed.LeaseStore; +import com.azure.cosmos.implementation.changefeed.LeaseStoreManager; +import com.azure.cosmos.implementation.changefeed.common.ChangeFeedMode; +import com.azure.cosmos.implementation.changefeed.common.ChangeFeedState; +import com.azure.cosmos.implementation.changefeed.common.LeaseVersion; +import com.azure.cosmos.models.ChangeFeedProcessorOptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; @@ -20,11 +26,20 @@ class BootstrapperImpl implements Bootstrapper { private final LeaseStore leaseStore; private final Duration lockTime; private final Duration sleepTime; + private final LeaseStoreManager epkRangeVersionLeaseStoreManager; + private final ChangeFeedProcessorOptions changeFeedProcessorOptions; private volatile boolean isInitialized; private volatile boolean isLockAcquired; - public BootstrapperImpl(PartitionSynchronizer synchronizer, LeaseStore leaseStore, Duration lockTime, Duration sleepTime) { + public BootstrapperImpl( + PartitionSynchronizer synchronizer, + LeaseStore leaseStore, + LeaseStoreManager epkRangeVersionLeaseStoreManager, + ChangeFeedProcessorOptions changeFeedProcessorOptions, + Duration lockTime, + Duration sleepTime) { + if (synchronizer == null) { throw new IllegalArgumentException("synchronizer cannot be null!"); } @@ -41,10 +56,20 @@ public BootstrapperImpl(PartitionSynchronizer synchronizer, LeaseStore leaseStor throw new IllegalArgumentException("sleepTime should be non-null and positive"); } + if (epkRangeVersionLeaseStoreManager == null) { + throw new IllegalArgumentException("epkRangeBasedLeaseStoreManager cannot be null!"); + } + + if (changeFeedProcessorOptions == null) { + throw new IllegalArgumentException("changeFeedProcessorOptions cannot be null!"); + } + this.synchronizer = synchronizer; this.leaseStore = leaseStore; this.lockTime = lockTime; this.sleepTime = sleepTime; + this.epkRangeVersionLeaseStoreManager = epkRangeVersionLeaseStoreManager; + this.changeFeedProcessorOptions = changeFeedProcessorOptions; this.isInitialized = false; } @@ -54,15 +79,29 @@ public Mono initialize() { this.isInitialized = false; return Mono.just(this) - .flatMap( value -> this.leaseStore.isInitialized()) + .flatMap(value -> this.leaseStore.isInitialized()) .flatMap(initialized -> { this.isInitialized = initialized; if (initialized) { - // Compared to epk version based lease, there is no need to verify the changeFeedProcessor has been initialized - // with the same change feed mode as the one being tracked in the lease - // because only incremental change feed mode is supported in the pkRange based lease - return Mono.empty(); + + return this.epkRangeVersionLeaseStoreManager + .getTopLeases(1) + .next() + .flatMap(lease -> { + + if (lease.getVersion() == LeaseVersion.EPK_RANGE_BASED_LEASE) { + + String errorMessage = String.format("ChangeFeedProcessor#handleChanges cannot be invoked when one of " + + "ChangeFeedProcessor#handleLatestVersionChanges or " + + "ChangeFeedProcessor#handleAllVersionsAndDeletes were also started for " + + "lease prefix : %s", this.changeFeedProcessorOptions.getLeasePrefix()); + + return Mono.error(new IllegalStateException(errorMessage)); + } + + return Mono.empty(); + }); } else { logger.info("Acquire initialization lock"); return this.leaseStore.acquireInitializationLock(this.lockTime) diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/pkversion/IncrementalChangeFeedProcessorImpl.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/pkversion/IncrementalChangeFeedProcessorImpl.java index e2745f3af1d8..94ae7633c456 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/pkversion/IncrementalChangeFeedProcessorImpl.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/pkversion/IncrementalChangeFeedProcessorImpl.java @@ -89,6 +89,8 @@ public class IncrementalChangeFeedProcessorImpl implements ChangeFeedProcessor, private final ChangeFeedObserverFactory observerFactory; private volatile String databaseId; private volatile String collectionId; + private volatile String databaseResourceId; + private volatile String collectionResourceId; private final ChangeFeedContextClient leaseContextClient; private PartitionLoadBalancingStrategy loadBalancingStrategy; private LeaseStoreManager leaseStoreManager; @@ -354,12 +356,14 @@ private Mono initializeCollectionPropertiesForBuild() { .readDatabase(this.feedContextClient.getDatabaseClient(), null) .map( databaseResourceResponse -> { this.databaseId = databaseResourceResponse.getProperties().getId(); + this.databaseResourceId = databaseResourceResponse.getProperties().getResourceId(); return this.databaseId; }) .flatMap( id -> this.feedContextClient .readContainer(this.feedContextClient.getContainerClient(), null) .map(documentCollectionResourceResponse -> { this.collectionId = documentCollectionResourceResponse.getProperties().getId(); + this.collectionResourceId = documentCollectionResourceResponse.getProperties().getResourceId(); return this; })); } @@ -427,7 +431,25 @@ private Mono buildPartitionManager(LeaseStoreManager leaseStor this.collectionId ); - Bootstrapper bootstrapper = new BootstrapperImpl(synchronizer, leaseStoreManager, this.lockTime, this.sleepTime); + RequestOptionsFactory requestOptionsFactory = new PartitionedByIdCollectionRequestOptionsFactory(); + String epkRangeVersionLeasePrefix = this.getEpkRangeVersionLeasePrefix(); + + LeaseStoreManager epkVersionLeaseStoreManager = + com.azure.cosmos.implementation.changefeed.epkversion.LeaseStoreManagerImpl.builder() + .leasePrefix(epkRangeVersionLeasePrefix) + .leaseCollectionLink(this.leaseContextClient.getContainerClient()) + .leaseContextClient(this.leaseContextClient) + .requestOptionsFactory(requestOptionsFactory) + .hostName(this.hostName) + .build(); + + Bootstrapper bootstrapper = new BootstrapperImpl( + synchronizer, + leaseStoreManager, + epkVersionLeaseStoreManager, + this.changeFeedProcessorOptions, + this.lockTime, + this.sleepTime); FeedRangeThroughputControlConfigManager feedRangeThroughputControlConfigManager = this.getFeedRangeThroughputControlConfigManager(); @@ -491,6 +513,23 @@ private FeedRangeThroughputControlConfigManager getFeedRangeThroughputControlCon return null; } + private String getEpkRangeVersionLeasePrefix() { + String optionsPrefix = this.changeFeedProcessorOptions.getLeasePrefix(); + + if (optionsPrefix == null) { + optionsPrefix = ""; + } + + URI uri = this.feedContextClient.getServiceEndpoint(); + + return String.format( + "%s%s_%s_%s", + optionsPrefix, + uri.getHost(), + this.databaseResourceId, + this.collectionResourceId); + } + @Override public void close() { this.stop().subscribeOn(Schedulers.boundedElastic()).subscribe(); diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/pkversion/LeaseStoreImpl.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/pkversion/LeaseStoreImpl.java index fa9291a37da1..084302074e62 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/pkversion/LeaseStoreImpl.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/pkversion/LeaseStoreImpl.java @@ -4,7 +4,6 @@ import com.azure.cosmos.BridgeInternal; import com.azure.cosmos.CosmosException; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.InternalObjectNode; import com.azure.cosmos.implementation.changefeed.common.ChangeFeedHelper; import com.azure.cosmos.implementation.changefeed.epkversion.ServiceItemLeaseV1; @@ -101,8 +100,8 @@ public Mono acquireInitializationLock(Duration lockExpirationTime) { containerDocument.setId(lockId); containerDocument.set( Constants.Properties.TTL, - Long.valueOf(lockExpirationTime.getSeconds()).intValue(), - CosmosItemSerializer.DEFAULT_SERIALIZER); + Long.valueOf(lockExpirationTime.getSeconds()).intValue() + ); return this.client.createItem( this.leaseCollectionLink, diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/pkversion/PartitionProcessorImpl.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/pkversion/PartitionProcessorImpl.java index 6cd323479ba3..56d405fb3e42 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/pkversion/PartitionProcessorImpl.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/pkversion/PartitionProcessorImpl.java @@ -121,7 +121,7 @@ public Mono run(CancellationToken cancellationToken) { return this.documentClient.createDocumentChangeFeedQuery( this.settings.getCollectionSelfLink(), this.options, - JsonNode.class).limitRequest(1); + JsonNode.class); }) .flatMap(documentFeedResponse -> { if (cancellationToken.isCancellationRequested()) return Flux.error(new TaskCancelledException()); diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/circuitBreaker/GlobalPartitionEndpointManagerForCircuitBreaker.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/circuitBreaker/GlobalPartitionEndpointManagerForCircuitBreaker.java index e4a74005508b..7857d372b2ae 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/circuitBreaker/GlobalPartitionEndpointManagerForCircuitBreaker.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/circuitBreaker/GlobalPartitionEndpointManagerForCircuitBreaker.java @@ -17,7 +17,7 @@ import com.azure.cosmos.implementation.apachecommons.lang.tuple.Pair; import com.azure.cosmos.implementation.directconnectivity.GatewayAddressCache; import com.azure.cosmos.implementation.directconnectivity.GlobalAddressResolver; -import com.azure.cosmos.implementation.routing.LocationCache; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; @@ -50,9 +50,11 @@ public class GlobalPartitionEndpointManagerForCircuitBreaker implements AutoClos private final LocationSpecificHealthContextTransitionHandler locationSpecificHealthContextTransitionHandler; private final ConsecutiveExceptionBasedCircuitBreaker consecutiveExceptionBasedCircuitBreaker; private final AtomicReference globalAddressResolverSnapshot; - private final ConcurrentHashMap locationToRegion; + private final ConcurrentHashMap locationToRegion; private final AtomicBoolean isClosed = new AtomicBoolean(false); - private final Scheduler partitionRecoveryScheduler = Schedulers.newSingle("partition-availability-staleness-check"); + private final Scheduler partitionRecoveryScheduler = Schedulers.newSingle( + "partition-availability-staleness-check", + true); public GlobalPartitionEndpointManagerForCircuitBreaker(GlobalEndpointManager globalEndpointManager) { this.partitionKeyRangeToLocationSpecificUnavailabilityInfo = new ConcurrentHashMap<>(); @@ -73,7 +75,7 @@ public void init() { } } - public void handleLocationExceptionForPartitionKeyRange(RxDocumentServiceRequest request, LocationCache.ConsolidatedRegionalEndpoint failedLocation) { + public void handleLocationExceptionForPartitionKeyRange(RxDocumentServiceRequest request, RegionalRoutingContext failedLocation) { checkNotNull(request, "Argument 'request' cannot be null!"); checkNotNull(request.requestContext, "Argument 'request.requestContext' cannot be null!"); @@ -110,7 +112,7 @@ public void handleLocationExceptionForPartitionKeyRange(RxDocumentServiceRequest if (isFailureThresholdBreached.get()) { - UnmodifiableList applicableEndpoints = request.isReadOnlyRequest() ? + UnmodifiableList applicableEndpoints = request.isReadOnlyRequest() ? this.globalEndpointManager.getApplicableReadEndpoints(request.requestContext.getExcludeRegions()) : this.globalEndpointManager.getApplicableWriteEndpoints(request.requestContext.getExcludeRegions()); @@ -133,7 +135,7 @@ public void handleLocationExceptionForPartitionKeyRange(RxDocumentServiceRequest logger.warn("It is not possible to mark region {} as Unavailable for partition key range {}-{} and collection rid {} " + "as all regions will be Unavailable in that case, will remove health status tracking for this partition!", this.globalEndpointManager.getRegionName( - failedLocation.getGatewayLocationEndpoint(), request.isReadOnlyRequest() ? OperationType.Read : OperationType.Create), + failedLocation.getGatewayRegionalEndpoint(), request.isReadOnlyRequest() ? OperationType.Read : OperationType.Create), resolvedPartitionKeyRangeForCircuitBreaker.getMinInclusive(), resolvedPartitionKeyRangeForCircuitBreaker.getMaxExclusive(), collectionResourceId); @@ -162,7 +164,7 @@ public void handleLocationSuccessForPartitionKeyRange(RxDocumentServiceRequest r String resourceId = request.getResourceId(); PartitionKeyRangeWrapper partitionKeyRangeWrapper = new PartitionKeyRangeWrapper(resolvedPartitionKeyRangeForCircuitBreaker, resourceId); - LocationCache.ConsolidatedRegionalEndpoint succeededLocation = request.requestContext.consolidatedRegionalEndpointToRoute; + RegionalRoutingContext succeededLocation = request.requestContext.regionalRoutingContextToRoute; String collectionLink = getCollectionLink(request); @@ -195,13 +197,13 @@ public List getUnavailableRegionsForPartitionKeyRange(String collectionR List unavailableRegions = new ArrayList<>(); if (partitionLevelLocationUnavailabilityInfoSnapshot != null) { - Map locationEndpointToFailureMetricsForPartition = + Map locationEndpointToFailureMetricsForPartition = partitionLevelLocationUnavailabilityInfoSnapshot.locationEndpointToLocationSpecificContextForPartition; - for (Map.Entry pair : locationEndpointToFailureMetricsForPartition.entrySet()) { - LocationCache.ConsolidatedRegionalEndpoint consolidatedRegionalEndpoint = pair.getKey(); + for (Map.Entry pair : locationEndpointToFailureMetricsForPartition.entrySet()) { + RegionalRoutingContext regionalRoutingContext = pair.getKey(); - URI gatewayLocationEndpoint = consolidatedRegionalEndpoint.getGatewayLocationEndpoint(); + URI gatewayLocationEndpoint = regionalRoutingContext.getGatewayRegionalEndpoint(); LocationSpecificHealthContext locationSpecificHealthContext = pair.getValue(); @@ -229,11 +231,11 @@ private Flux updateStaleLocationInfo() { if (partitionLevelLocationUnavailabilityInfo != null) { - List>> locationToLocationSpecificHealthContextList = new ArrayList<>(); + List>> locationToLocationSpecificHealthContextList = new ArrayList<>(); - for (Map.Entry locationToLocationLevelMetrics : partitionLevelLocationUnavailabilityInfo.locationEndpointToLocationSpecificContextForPartition.entrySet()) { + for (Map.Entry locationToLocationLevelMetrics : partitionLevelLocationUnavailabilityInfo.locationEndpointToLocationSpecificContextForPartition.entrySet()) { - LocationCache.ConsolidatedRegionalEndpoint locationWithStaleUnavailabilityInfo = locationToLocationLevelMetrics.getKey(); + RegionalRoutingContext locationWithStaleUnavailabilityInfo = locationToLocationLevelMetrics.getKey(); LocationSpecificHealthContext locationSpecificHealthContext = locationToLocationLevelMetrics.getValue(); if (!locationSpecificHealthContext.isRegionAvailableToProcessRequests()) { @@ -260,7 +262,7 @@ private Flux updateStaleLocationInfo() { .flatMap(locationToLocationSpecificHealthContextPair -> { PartitionKeyRangeWrapper partitionKeyRangeWrapper = locationToLocationSpecificHealthContextPair.getLeft(); - LocationCache.ConsolidatedRegionalEndpoint locationWithStaleUnavailabilityInfo = locationToLocationSpecificHealthContextPair.getRight().getLeft(); + RegionalRoutingContext locationWithStaleUnavailabilityInfo = locationToLocationSpecificHealthContextPair.getRight().getLeft(); PartitionLevelLocationUnavailabilityInfo partitionLevelLocationUnavailabilityInfo = this.partitionKeyRangeToLocationSpecificUnavailabilityInfo.get(partitionKeyRangeWrapper); @@ -270,7 +272,7 @@ private Flux updateStaleLocationInfo() { if (globalAddressResolver != null) { - GatewayAddressCache gatewayAddressCache = globalAddressResolver.getGatewayAddressCache(locationWithStaleUnavailabilityInfo.getGatewayLocationEndpoint()); + GatewayAddressCache gatewayAddressCache = globalAddressResolver.getGatewayAddressCache(locationWithStaleUnavailabilityInfo.getGatewayRegionalEndpoint()); if (gatewayAddressCache != null) { @@ -357,7 +359,7 @@ public boolean isPartitionLevelCircuitBreakingApplicable(RxDocumentServiceReques return false; } - UnmodifiableList applicableWriteEndpoints = globalEndpointManager.getApplicableWriteEndpoints(Collections.emptyList()); + UnmodifiableList applicableWriteEndpoints = globalEndpointManager.getApplicableWriteEndpoints(Collections.emptyList()); return applicableWriteEndpoints != null && applicableWriteEndpoints.size() > 1; } @@ -374,7 +376,7 @@ public void close() { private class PartitionLevelLocationUnavailabilityInfo { - private final ConcurrentHashMap locationEndpointToLocationSpecificContextForPartition; + private final ConcurrentHashMap locationEndpointToLocationSpecificContextForPartition; private final ConcurrentHashMap regionToLocationSpecificHealthContext; private final LocationSpecificHealthContextTransitionHandler locationSpecificHealthContextTransitionHandler; @@ -386,7 +388,7 @@ private PartitionLevelLocationUnavailabilityInfo() { private boolean handleException( PartitionKeyRangeWrapper partitionKeyRangeWrapper, - LocationCache.ConsolidatedRegionalEndpoint locationWithException, + RegionalRoutingContext locationWithException, boolean isReadOnlyRequest) { AtomicBoolean isExceptionThresholdBreached = new AtomicBoolean(false); @@ -420,7 +422,7 @@ private boolean handleException( locationAsKey, GlobalPartitionEndpointManagerForCircuitBreaker .this.globalEndpointManager - .getRegionName(locationAsKey.getGatewayLocationEndpoint(), isReadOnlyRequest ? OperationType.Read : OperationType.Create)); + .getRegionName(locationAsKey.getGatewayRegionalEndpoint(), isReadOnlyRequest ? OperationType.Read : OperationType.Create)); } String region = GlobalPartitionEndpointManagerForCircuitBreaker.this.locationToRegion.get(locationAsKey); @@ -435,7 +437,7 @@ private boolean handleException( private void handleSuccess( PartitionKeyRangeWrapper partitionKeyRangeWrapper, - LocationCache.ConsolidatedRegionalEndpoint succeededLocation, + RegionalRoutingContext succeededLocation, boolean isReadOnlyRequest) { this.locationEndpointToLocationSpecificContextForPartition.compute(succeededLocation, (locationAsKey, locationSpecificContextAsVal) -> { @@ -469,7 +471,7 @@ private void handleSuccess( locationAsKey, GlobalPartitionEndpointManagerForCircuitBreaker .this.globalEndpointManager - .getRegionName(locationAsKey.getGatewayLocationEndpoint(), isReadOnlyRequest ? OperationType.Read : OperationType.Create)); + .getRegionName(locationAsKey.getGatewayRegionalEndpoint(), isReadOnlyRequest ? OperationType.Read : OperationType.Create)); } String region = GlobalPartitionEndpointManagerForCircuitBreaker.this.locationToRegion.get(locationAsKey); @@ -479,9 +481,9 @@ private void handleSuccess( }); } - public boolean areLocationsAvailableForPartitionKeyRange(List availableLocationsAtAccountLevel) { + public boolean areLocationsAvailableForPartitionKeyRange(List availableLocationsAtAccountLevel) { - for (LocationCache.ConsolidatedRegionalEndpoint availableLocation : availableLocationsAtAccountLevel) { + for (RegionalRoutingContext availableLocation : availableLocationsAtAccountLevel) { if (!this.locationEndpointToLocationSpecificContextForPartition.containsKey(availableLocation)) { return true; } else { diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/clienttelemetry/ClientTelemetry.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/clienttelemetry/ClientTelemetry.java index 8065f6307be7..636da7caf356 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/clienttelemetry/ClientTelemetry.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/clienttelemetry/ClientTelemetry.java @@ -8,6 +8,7 @@ import com.azure.cosmos.implementation.Configs; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.CosmosSchedulers; +import com.azure.cosmos.implementation.DefaultCosmosItemSerializer; import com.azure.cosmos.implementation.DiagnosticsClientContext; import com.azure.cosmos.implementation.HttpConstants; import com.azure.cosmos.implementation.IAuthorizationTokenProvider; @@ -280,7 +281,7 @@ private Mono sendClientTelemetry() { URI targetEndpoint = new URI(endpoint); ByteBuffer byteBuffer = InternalObjectNode.serializeJsonToByteBuffer(this.clientTelemetryInfo, - CosmosItemSerializer.DEFAULT_SERIALIZER, + DefaultCosmosItemSerializer.INTERNAL_DEFAULT_SERIALIZER, null, false); byte[] tempBuffer = RxDocumentServiceRequest.toByteArray(byteBuffer); diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/clienttelemetry/ClientTelemetryMetrics.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/clienttelemetry/ClientTelemetryMetrics.java index 981dac0043ec..be4b0e499b51 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/clienttelemetry/ClientTelemetryMetrics.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/clienttelemetry/ClientTelemetryMetrics.java @@ -269,10 +269,10 @@ private static void recordOperation( latency, maxItemCount == null ? -1 : maxItemCount, actualItemCount == null ? -1: actualItemCount, - opCountPerEvaluation, - opRetriedCountPerEvaluation, - globalOpCount, - targetMaxMicroBatchSize, + opCountPerEvaluation == null ? 0 : opCountPerEvaluation, + opRetriedCountPerEvaluation == null ? 0 : opRetriedCountPerEvaluation, + globalOpCount == null ? 0 : globalOpCount, + targetMaxMicroBatchSize == null ? 0 : targetMaxMicroBatchSize, diagnosticsContext, contactedRegions ); diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/Address.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/Address.java index d17c49564a97..11ecc099deeb 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/Address.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/Address.java @@ -3,8 +3,6 @@ package com.azure.cosmos.implementation.directconnectivity; -import com.azure.cosmos.BridgeInternal; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.JsonSerializable; import com.azure.cosmos.implementation.Resource; import com.azure.cosmos.implementation.Constants; @@ -46,7 +44,7 @@ public boolean isPrimary() { } void setIsPrimary(boolean isPrimary) { - this.set(Constants.Properties.IS_PRIMARY, isPrimary, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.IS_PRIMARY, isPrimary); } public String getProtocolScheme() { @@ -55,7 +53,7 @@ public String getProtocolScheme() { void setProtocol(String protocol) { - this.set(Constants.Properties.PROTOCOL, protocol, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.PROTOCOL, protocol); } public String getLogicalUri() { @@ -63,7 +61,7 @@ public String getLogicalUri() { } void setLogicalUri(String logicalUri) { - this.set(Constants.Properties.LOGICAL_URI, logicalUri, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.LOGICAL_URI, logicalUri); } public String getPhyicalUri() { @@ -71,7 +69,7 @@ public String getPhyicalUri() { } void setPhysicalUri(String phyicalUri) { - this.set(Constants.Properties.PHYISCAL_URI, phyicalUri, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.PHYISCAL_URI, phyicalUri); } public String getPartitionIndex() { @@ -79,7 +77,7 @@ public String getPartitionIndex() { } void setPartitionIndex(String partitionIndex) { - this.set(Constants.Properties.PARTITION_INDEX, partitionIndex, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.PARTITION_INDEX, partitionIndex); } public String getParitionKeyRangeId() { @@ -87,7 +85,7 @@ public String getParitionKeyRangeId() { } public void setPartitionKeyRangeId(String partitionKeyRangeId) { - this.set(Constants.Properties.PARTITION_KEY_RANGE_ID, partitionKeyRangeId, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Constants.Properties.PARTITION_KEY_RANGE_ID, partitionKeyRangeId); } @Override diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/GlobalAddressResolver.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/GlobalAddressResolver.java index 25094e6882d8..00905682b4d1 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/GlobalAddressResolver.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/GlobalAddressResolver.java @@ -23,9 +23,9 @@ import com.azure.cosmos.implementation.faultinjection.GatewayServerErrorInjector; import com.azure.cosmos.implementation.faultinjection.IFaultInjectorProvider; import com.azure.cosmos.implementation.http.HttpClient; -import com.azure.cosmos.implementation.routing.LocationCache; import com.azure.cosmos.implementation.routing.PartitionKeyInternalHelper; import com.azure.cosmos.implementation.routing.PartitionKeyRangeIdentity; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; import com.azure.cosmos.models.CosmosContainerIdentity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -92,11 +92,11 @@ public GlobalAddressResolver( this.addressCacheByEndpoint = new ConcurrentHashMap<>(); this.apiType = apiType; - for (LocationCache.ConsolidatedRegionalEndpoint endpoint : endpointManager.getWriteEndpoints()) { - this.getOrAddEndpoint(endpoint.getGatewayLocationEndpoint()); + for (RegionalRoutingContext endpoint : endpointManager.getWriteEndpoints()) { + this.getOrAddEndpoint(endpoint.getGatewayRegionalEndpoint()); } - for (LocationCache.ConsolidatedRegionalEndpoint endpoint : endpointManager.getReadEndpoints()) { - this.getOrAddEndpoint(endpoint.getGatewayLocationEndpoint()); + for (RegionalRoutingContext endpoint : endpointManager.getReadEndpoints()) { + this.getOrAddEndpoint(endpoint.getGatewayRegionalEndpoint()); } } @@ -155,8 +155,8 @@ public Flux submitOpenConnectionTasksAndInitCaches(CosmosContainerProactiv if (proactiveContainerInitConfig.getProactiveConnectionRegionsCount() > 0) { return Flux.fromIterable(this.endpointManager.getReadEndpoints().subList(0, proactiveContainerInitConfig.getProactiveConnectionRegionsCount())) .flatMap(readEndpoint -> { - if (this.addressCacheByEndpoint.containsKey(readEndpoint.getGatewayLocationEndpoint())) { - EndpointCache endpointCache = this.addressCacheByEndpoint.get(readEndpoint.getGatewayLocationEndpoint()); + if (this.addressCacheByEndpoint.containsKey(readEndpoint.getGatewayRegionalEndpoint())) { + EndpointCache endpointCache = this.addressCacheByEndpoint.get(readEndpoint.getGatewayRegionalEndpoint()); return this.resolveAddressesPerCollection( endpointCache, containerLinkToPkrs.left, @@ -273,8 +273,8 @@ public void configureFaultInjectorProvider(IFaultInjectorProvider faultInjectorP } private IAddressResolver getAddressResolver(RxDocumentServiceRequest rxDocumentServiceRequest) { - LocationCache.ConsolidatedRegionalEndpoint endpoint = this.endpointManager.resolveServiceEndpoint(rxDocumentServiceRequest); - return this.getOrAddEndpoint(endpoint.getGatewayLocationEndpoint()).addressResolver; + RegionalRoutingContext endpoint = this.endpointManager.resolveServiceEndpoint(rxDocumentServiceRequest); + return this.getOrAddEndpoint(endpoint.getGatewayRegionalEndpoint()).addressResolver; } private EndpointCache getOrAddEndpoint(URI endpoint) { @@ -300,15 +300,15 @@ private EndpointCache getOrAddEndpoint(URI endpoint) { }); if (this.addressCacheByEndpoint.size() > this.maxEndpoints) { - List allConsolidatedEndpoints = new ArrayList<>(this.endpointManager.getWriteEndpoints()); + List allConsolidatedEndpoints = new ArrayList<>(this.endpointManager.getWriteEndpoints()); allConsolidatedEndpoints.addAll(this.endpointManager.getReadEndpoints()); Collections.reverse(allConsolidatedEndpoints); - LinkedList endpoints = new LinkedList<>(allConsolidatedEndpoints); + LinkedList endpoints = new LinkedList<>(allConsolidatedEndpoints); while (this.addressCacheByEndpoint.size() > this.maxEndpoints) { if (!endpoints.isEmpty()) { - LocationCache.ConsolidatedRegionalEndpoint dequeueEndpoint = endpoints.pop(); - if (this.addressCacheByEndpoint.get(dequeueEndpoint.getGatewayLocationEndpoint()) != null) { - this.addressCacheByEndpoint.remove(dequeueEndpoint.getGatewayLocationEndpoint()); + RegionalRoutingContext dequeueEndpoint = endpoints.pop(); + if (this.addressCacheByEndpoint.get(dequeueEndpoint.getGatewayRegionalEndpoint()) != null) { + this.addressCacheByEndpoint.remove(dequeueEndpoint.getGatewayRegionalEndpoint()); } } else { break; diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/RntbdTransportClient.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/RntbdTransportClient.java index 614115a6d63e..bb56c878620a 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/RntbdTransportClient.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/RntbdTransportClient.java @@ -283,7 +283,7 @@ public Mono invokeStoreAsync(final Uri addressUri, final RxDocume config.minConnectionPoolSizePerEndpoint() : 1; final RntbdEndpoint endpoint = this.endpointProvider.createIfAbsent( - request.requestContext.locationEndpointToRoute, + request.requestContext.regionalRoutingContextToRoute.getGatewayRegionalEndpoint(), addressUri, this.proactiveOpenConnectionsProcessor, minConnectionPoolSizePerEndpoint, diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdConstants.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdConstants.java index 7e3c340aaf25..521ce2ceb4c6 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdConstants.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdConstants.java @@ -499,7 +499,7 @@ public enum RntbdRequestHeader implements RntbdHeader { ConsistencyLevel((short) 0x0010, RntbdTokenType.Byte, false), EntityId((short) 0x0011, RntbdTokenType.String, false), ResourceSchemaName((short) 0x0012, RntbdTokenType.SmallString, false), - ReplicaPath((short) 0x0013, RntbdTokenType.String, false), + ReplicaPath((short) 0x0013, RntbdTokenType.String, false), // true in direct, but not for thin client ResourceTokenExpiry((short) 0x0014, RntbdTokenType.ULong, false), DatabaseName((short) 0x0015, RntbdTokenType.String, false), CollectionName((short) 0x0016, RntbdTokenType.String, false), @@ -598,7 +598,7 @@ public enum RntbdRequestHeader implements RntbdHeader { PriorityLevel((short) 0x00BF, RntbdTokenType.Byte, false), GlobalDatabaseAccountName((short) 0x00CE, RntbdTokenType.String, false); - public static final List thinClientHeadersInOrderList = Arrays.asList( + public static final List thinClientHeadersInOrderList = Arrays.asList( EffectivePartitionKey, GlobalDatabaseAccountName, DatabaseName, @@ -618,6 +618,7 @@ public enum RntbdRequestHeader implements RntbdHeader { public static final Set thinClientProxyExcludedSet; public static final Set thinClientProxyOrderedOrExcludedSet; + public static final Map map; public static final EnumSet set = EnumSet.allOf(RntbdRequestHeader.class); @@ -625,15 +626,15 @@ public enum RntbdRequestHeader implements RntbdHeader { final Collector> collector = Collectors.toMap(RntbdRequestHeader::id, h -> h); thinClientProxyOrderedOrExcludedSet = Stream.concat( - thinClientExclusionList.stream(), - thinClientHeadersInOrderList.stream() - ) - .map(RntbdRequestHeader::id) - .collect(Collectors.toSet()); + thinClientExclusionList.stream(), + thinClientHeadersInOrderList.stream() + ) + .map(RntbdRequestHeader::id) + .collect(Collectors.toSet()); thinClientProxyExcludedSet = - thinClientExclusionList.stream() - .map(RntbdRequestHeader::id) - .collect(Collectors.toSet()); + thinClientExclusionList.stream() + .map(RntbdRequestHeader::id) + .collect(Collectors.toSet()); map = set.stream().collect(collector); } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdObjectMapper.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdObjectMapper.java index c44973c9c342..fcf1858cf266 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdObjectMapper.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdObjectMapper.java @@ -25,6 +25,7 @@ import java.io.InputStream; import java.time.Duration; import java.time.Instant; +import java.util.Base64; import java.util.concurrent.ConcurrentHashMap; import static com.azure.cosmos.implementation.guava25.base.Preconditions.checkNotNull; @@ -75,14 +76,13 @@ public static String toJson(final Object value) { Object tokenValue = token.getValue(); if (tokenValue instanceof ByteBuf) { ByteBuf buf = (ByteBuf) tokenValue; - StringBuilder hexString = new StringBuilder(); - for (int i = buf.readerIndex(); i < buf.readerIndex() + buf.readableBytes(); i++) { - hexString.append(java.lang.String.format("%02X", buf.getByte(i))); - } + byte[] blob = new byte[buf.readableBytes()]; + buf.getBytes(buf.readerIndex(), blob); + String base64String = Base64.getEncoder().encodeToString(blob); String json = objectWriter.writeValueAsString(value); ObjectNode parsed = (ObjectNode)objectMapper.readTree(json); - parsed.put("value", hexString.toString()); + parsed.put("value", base64String); return parsed.toString(); } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdOpenConnectionsHandler.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdOpenConnectionsHandler.java index 228841e30d93..baab52b212a1 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdOpenConnectionsHandler.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdOpenConnectionsHandler.java @@ -10,7 +10,7 @@ import com.azure.cosmos.implementation.RxDocumentServiceRequest; import com.azure.cosmos.implementation.apachecommons.lang.StringUtils; import com.azure.cosmos.implementation.directconnectivity.Uri; -import com.azure.cosmos.implementation.routing.LocationCache; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; @@ -77,8 +77,8 @@ public Flux openConnections(String collectionRid, List T getHeader(final RntbdRequestHeader header) { @JsonIgnore @SuppressWarnings("unchecked") + // Returns true if set successfully - false if the header does not exist public boolean setHeaderValue(final RntbdRequestHeader header, Object value) { RntbdToken token = this.headers.get(header); if (token == null) { @@ -92,34 +91,36 @@ public static RntbdRequest decode(final ByteBuf in) { public RntbdRequestHeaders getHeaders() { return this.headers; } + public void encode(final ByteBuf out, boolean forThinClient) { + // If payload exists it is encoded as prefix length (32-bit) + the raw payload final int effectivePayloadSize = this.payload != null && this.payload.length > 0 ? this.payload.length + 4 : 0; final int expectedLength = RntbdRequestFrame.LENGTH + this.headers.computeLength(forThinClient); - final int start = out.writerIndex(); - logger.error("RntbdRequest.encode Start {}, ExpectedLength {} + payload length {}", start, expectedLength, effectivePayloadSize); + final int start = out.writerIndex(); out.writeIntLE(expectedLength); this.frame.encode(out); - logger.error("After frame WriteIndex {}", out.writerIndex()); this.headers.encode(out, forThinClient); - logger.error("After headers WriteIndex {}", out.writerIndex()); - final int observedLength = out.writerIndex() - start; - /*checkState(observedLength == expectedLength, + int observedLength = out.writerIndex() - start; + + checkState(observedLength == expectedLength, "encoding error: {\"expectedLength\": %s, \"observedLength\": %s}", expectedLength, - observedLength);*/ + observedLength); if (this.payload.length > 0) { out.writeIntLE(this.payload.length); out.writeBytes(this.payload); - logger.error("After payload of length {} WriteIndex {}", this.payload.length, out.writerIndex()); - } else { - logger.error("NO PAYLOAD"); - } + observedLength = out.writerIndex() - start; + checkState(observedLength == expectedLength + effectivePayloadSize, + "payload encoding error: {\"expectedLength\": %s, \"observedLength\": %s}", + expectedLength + effectivePayloadSize, + observedLength); + } } public static RntbdRequest from(final RntbdRequestArgs args) { diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdRequestHeaders.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdRequestHeaders.java index bf09d017b50c..e3bfc0d0f12e 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdRequestHeaders.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdRequestHeaders.java @@ -68,6 +68,7 @@ public final class RntbdRequestHeaders extends RntbdTokenStream 0); + RntbdToken replicaPathToken = this.getReplicaPath(); if (replicaPathToken != null) { replicaPathToken.setValue(args.replicaPath()); @@ -290,7 +291,9 @@ private RntbdToken getCorrelatedActivityId() { private RntbdToken getPriorityLevel() { return this.get(RntbdRequestHeader.PriorityLevel); } - private RntbdToken getGlobalDatabaseAccountName() { return this.get(RntbdRequestHeader.GlobalDatabaseAccountName); } + private RntbdToken getGlobalDatabaseAccountName() { + return this.get(RntbdRequestHeader.GlobalDatabaseAccountName); + } private RntbdToken getDatabaseName() { return this.get(RntbdRequestHeader.DatabaseName); @@ -1352,11 +1355,8 @@ private void fillTokenFromHeader(final Map headers, final Suppli token.setValue(Boolean.parseBoolean(value)); break; } - case Bytes: { - token.setValue(value.getBytes()); - break; - } case Double: { + token.setValue(parseDouble(name, value)); break; } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdRequestManager.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdRequestManager.java index 6d270bc21ff4..d0517142e22a 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdRequestManager.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdRequestManager.java @@ -997,7 +997,11 @@ private void messageReceived(final ChannelHandlerContext context, final RntbdRes if ((HttpResponseStatus.OK.code() <= statusCode && statusCode < HttpResponseStatus.MULTIPLE_CHOICES.code()) || statusCode == HttpResponseStatus.NOT_MODIFIED.code()) { - final StoreResponse storeResponse = response.toStoreResponse(this.contextFuture.getNow(null)); + RntbdContext rntbdCtx = this.contextFuture.getNow(null); + if (rntbdCtx == null) { + throw new IllegalStateException("Expecting non-null rntbd context."); + } + final StoreResponse storeResponse = response.toStoreResponse(rntbdCtx.serverVersion()); if (this.serverErrorInjector != null) { Consumer completeWithInjectedDelayConsumer = @@ -1031,7 +1035,7 @@ private void messageReceived(final ChannelHandlerContext context, final RntbdRes // ..Map RNTBD response headers to HTTP response headers final Map responseHeaders = response.getHeaders().asMap( - this.rntbdContext().orElseThrow(IllegalStateException::new), activityId + this.rntbdContext().orElseThrow(IllegalStateException::new).serverVersion(), activityId ); // ..Create CosmosException based on status and sub-status codes diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdResponse.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdResponse.java index 2dac6dbd2485..362a126c0f2f 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdResponse.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdResponse.java @@ -347,46 +347,26 @@ public static RntbdResponse decode(final ByteBuf in) { return new RntbdResponse(in.readSlice(end - start), frame, headers, content); } - public StoreResponse toStoreResponse(final RntbdContext context) { + StoreResponse toStoreResponse(final String serverVersion) { - checkNotNull(context, "expected non-null context"); + checkNotNull(serverVersion, "Argument 'serverVersion' must not be null."); final int length = this.content.writerIndex(); if (length == 0) { return new StoreResponse( this.getStatus().code(), - this.headers.asMap(context, this.getActivityId()), + this.headers.asMap(serverVersion, this.getActivityId()), null, 0); } return new StoreResponse( this.getStatus().code(), - this.headers.asMap(context, this.getActivityId()), + this.headers.asMap(serverVersion, this.getActivityId()), new ByteBufInputStream(this.content.retain(), true), length); } - - public StoreResponse toStoreResponse() { - - final int length = this.content.writerIndex(); - - if (length == 0) { - return new StoreResponse( - this.getStatus().code(), - this.headers.asMap(this.getActivityId()), - null, - 0); - } - - return new StoreResponse( - this.getStatus().code(), - this.headers.asMap(this.getActivityId()), - new ByteBufInputStream(this.content.retain(), true), - length); - } - // endregion // region Types diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdResponseHeaders.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdResponseHeaders.java index 82b93fd2cad9..eb3658026ab9 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdResponseHeaders.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdResponseHeaders.java @@ -26,6 +26,7 @@ import static com.azure.cosmos.implementation.directconnectivity.WFConstants.BackendHeaders; import static com.azure.cosmos.implementation.directconnectivity.rntbd.RntbdConstants.RntbdIndexingDirective; import static com.azure.cosmos.implementation.directconnectivity.rntbd.RntbdConstants.RntbdResponseHeader; +import static com.azure.cosmos.implementation.guava25.base.Preconditions.checkNotNull; @SuppressWarnings("UnstableApiUsage") @JsonFilter("RntbdToken") @@ -205,25 +206,14 @@ boolean isPayloadPresent() { return this.payloadPresent.isPresent() && this.payloadPresent.getValue(Byte.class) != 0x00; } - List> asList(final RntbdContext context, final UUID activityId) { + public Map asMap(final String serverVersion, final UUID activityId) { - final ImmutableList.Builder> builder = ImmutableList.builderWithExpectedSize(this.computeCount(false) + 2); - builder.add(new Entry(HttpHeaders.SERVER_VERSION, context.serverVersion())); - builder.add(new Entry(HttpHeaders.ACTIVITY_ID, activityId.toString())); + checkNotNull(serverVersion, "Argument 'serverVersion' must not be null."); + checkNotNull(activityId, "Argument 'activityId' must not be null."); - this.collectEntries((token, toEntry) -> { - if (token.isPresent()) { - builder.add(toEntry.apply(token)); - } - }); - - return builder.build(); - } - - public Map asMap(final RntbdContext context, final UUID activityId) { - - final ImmutableMap.Builder builder = ImmutableMap.builderWithExpectedSize(this.computeCount(false) + 2); - builder.put(new Entry(HttpHeaders.SERVER_VERSION, context.serverVersion())); + final ImmutableMap.Builder builder = ImmutableMap.builderWithExpectedSize( + this.computeCount(false) + 2); + builder.put(new Entry(HttpHeaders.SERVER_VERSION, serverVersion)); builder.put(new Entry(HttpHeaders.ACTIVITY_ID, activityId.toString())); this.collectEntries((token, toEntry) -> { diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdToken.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdToken.java index bc44cc700d4a..1c064c30fe90 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdToken.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdToken.java @@ -12,8 +12,6 @@ import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.CorruptedFrameException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import static com.azure.cosmos.implementation.directconnectivity.rntbd.RntbdConstants.RntbdHeader; import static com.azure.cosmos.implementation.guava25.base.Preconditions.checkArgument; @@ -24,8 +22,6 @@ @JsonPropertyOrder({ "id", "name", "type", "present", "required", "value" }) final class RntbdToken { - private static final Logger logger = LoggerFactory.getLogger(RntbdToken.class); - // region Fields private static final int HEADER_LENGTH = Short.BYTES + Byte.BYTES; @@ -37,6 +33,7 @@ final class RntbdToken { private final RntbdHeader header; private int length; private Object value; + private boolean hasConvertedValue; // endregion @@ -77,22 +74,25 @@ public Object getValue() { return codec.defaultValue(); } + if (this.hasConvertedValue) { + return this.value; + } + if (this.value instanceof ByteBuf) { final ByteBuf buffer = (ByteBuf) this.value; - buffer.markReaderIndex(); try { - return codec.read(buffer); - + this.value = codec.read(buffer); + this.hasConvertedValue = true; } catch (final CorruptedFrameException error) { String message = lenientFormat("failed to read %s value: %s", this.getName(), error.getMessage()); throw new CorruptedFrameException(message); } - finally { - buffer.resetReaderIndex(); - } } else { - return codec.convert(this.value); + this.value = codec.convert(this.value); + this.hasConvertedValue = true; } + + return this.value; } public T getValue(final Class cls) { @@ -107,7 +107,7 @@ public void setValue(final Object value) { } @JsonIgnore - public final Class getValueType() { + public Class getValueType() { return this.header.type().codec().valueType(); } @@ -155,6 +155,7 @@ public void decode(final ByteBuf in) { } public void encode(final ByteBuf out) { + checkNotNull(out, "out"); if (!this.isPresent()) { @@ -165,7 +166,6 @@ public void encode(final ByteBuf out) { return; } - logger.error("RNTBD TOKEN {}", this); out.writeShortLE(this.getId()); out.writeByte(this.getTokenType().id()); diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdTokenStream.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdTokenStream.java index b3b63ce20523..8a9aecb9401c 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdTokenStream.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdTokenStream.java @@ -9,9 +9,7 @@ import java.util.EnumMap; import java.util.EnumSet; -import java.util.List; import java.util.Map; -import java.util.Set; import static com.azure.cosmos.implementation.directconnectivity.rntbd.RntbdConstants.RntbdHeader; import static com.azure.cosmos.implementation.guava25.base.Preconditions.checkNotNull; @@ -30,7 +28,7 @@ public abstract class RntbdTokenStream & RntbdHeader> implemen checkNotNull(ids, "expected non-null ids"); checkNotNull(in, "expected non-null in"); - this.tokens = new EnumMap<>(classType); + this.tokens = new EnumMap(classType); headers.stream().forEach(h -> tokens.put(h, RntbdToken.create(h))); this.headers = ids; this.in = in; @@ -59,12 +57,11 @@ final int computeCount(boolean isThinClientRequest) { int count = 0; for (final RntbdToken token : this.tokens.values()) { - if (isThinClientRequest - && RntbdConstants.RntbdRequestHeader.thinClientProxyExcludedSet.contains(token.getId())) { - continue; - } - if (token.isPresent()) { + if (isThinClientRequest + && RntbdConstants.RntbdRequestHeader.thinClientProxyExcludedSet.contains(token.getId())) { + continue; + } ++count; } } @@ -81,7 +78,6 @@ final int computeLength(boolean isThinClientRequest) { && RntbdConstants.RntbdRequestHeader.thinClientProxyExcludedSet.contains(token.getId())) { continue; } - total += token.computeLength(); } @@ -120,18 +116,18 @@ final void encode(final ByteBuf out, boolean isThinClientRequest) { if (isThinClientRequest) { for (RntbdConstants.RntbdRequestHeader header : RntbdConstants.RntbdRequestHeader.thinClientHeadersInOrderList) { RntbdToken token = this.tokens.get(header); - if (token != null) { + if (token != null && token.isPresent()) { token.encode(out); } } } for (final RntbdToken token : this.tokens.values()) { - if (isThinClientRequest - && RntbdConstants.RntbdRequestHeader.thinClientProxyOrderedOrExcludedSet.contains(token.getId())) { + if (!token.isPresent() + || (isThinClientRequest && RntbdConstants.RntbdRequestHeader.thinClientProxyOrderedOrExcludedSet.contains(token.getId()))) { + continue; } - token.encode(out); } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdTokenType.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdTokenType.java index 11b0de1f8438..052267869590 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdTokenType.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdTokenType.java @@ -7,8 +7,6 @@ import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufUtil; import io.netty.handler.codec.CorruptedFrameException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.nio.charset.StandardCharsets; import java.util.UUID; @@ -181,7 +179,7 @@ public final void write(final Object value, final ByteBuf out) { } private static class RntbdBytes implements Codec { - private static final Logger logger = LoggerFactory.getLogger(RntbdBytes.class); + public static final Codec codec = new RntbdBytes(); private static final byte[] defaultValue = {}; @@ -214,12 +212,7 @@ public boolean isValid(final Object value) { public Object read(final ByteBuf in) { final int length = in.readUnsignedShortLE(); Codec.checkReadableBytes(in, length, 0xFFFF); - StringBuilder hexString = new StringBuilder(); - for (int i = in.readerIndex(); i < in.readerIndex() + in.readableBytes(); i++) { - hexString.append(java.lang.String.format("%02X", in.getByte(i))); - } - ByteBuf returnValue = in.readBytes(length); - return returnValue; + return in.readBytes(length); } @Override diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/faultinjection/FaultInjectionRequestContext.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/faultinjection/FaultInjectionRequestContext.java index b3d421dcfae5..79b6847c3fa0 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/faultinjection/FaultInjectionRequestContext.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/faultinjection/FaultInjectionRequestContext.java @@ -3,7 +3,7 @@ package com.azure.cosmos.implementation.faultinjection; -import com.azure.cosmos.implementation.routing.LocationCache; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; import java.net.URI; import java.util.ArrayList; @@ -25,7 +25,7 @@ public class FaultInjectionRequestContext { private final AtomicBoolean addressForceRefreshed; private volatile URI locationEndpointToRoute; - private volatile LocationCache.ConsolidatedRegionalEndpoint consolidatedRegionalEndpointToRoute; + private volatile RegionalRoutingContext regionalRoutingContextToRoute; /*** * This usually is called during retries. @@ -99,7 +99,7 @@ public String getFaultInjectionRuleId(long transportRequestId) { public void setLocationEndpointToRoute(URI locationEndpointToRoute) { this.locationEndpointToRoute = locationEndpointToRoute; - this.consolidatedRegionalEndpointToRoute = new LocationCache.ConsolidatedRegionalEndpoint(locationEndpointToRoute, null); + this.regionalRoutingContextToRoute = new RegionalRoutingContext(locationEndpointToRoute); } public URI getLocationEndpointToRoute() { diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/feedranges/FeedRangeCompositeContinuationImpl.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/feedranges/FeedRangeCompositeContinuationImpl.java index ab266ff6bd34..056f617a0341 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/feedranges/FeedRangeCompositeContinuationImpl.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/feedranges/FeedRangeCompositeContinuationImpl.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation.feedranges; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.GoneException; import com.azure.cosmos.implementation.HttpConstants; @@ -111,13 +110,13 @@ public void populatePropertyBag() { this.set( Constants.Properties.FEED_RANGE_COMPOSITE_CONTINUATION_VERSION, - FeedRangeContinuationVersions.V1, - CosmosItemSerializer.DEFAULT_SERIALIZER); + FeedRangeContinuationVersions.V1 + ); this.set( Constants.Properties.FEED_RANGE_COMPOSITE_CONTINUATION_RESOURCE_ID, - this.getContainerRid(), - CosmosItemSerializer.DEFAULT_SERIALIZER); + this.getContainerRid() + ); if (this.compositeContinuationTokens.size() > 0) { for (CompositeContinuationToken token : this.compositeContinuationTokens) { @@ -126,8 +125,8 @@ public void populatePropertyBag() { this.set( Constants.Properties.FEED_RANGE_COMPOSITE_CONTINUATION_CONTINUATION, - this.compositeContinuationTokens, - CosmosItemSerializer.DEFAULT_SERIALIZER); + this.compositeContinuationTokens + ); } if (this.feedRange != null) { diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/feedranges/FeedRangeEpkImpl.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/feedranges/FeedRangeEpkImpl.java index f5fdc9b47d4a..59054fe2c14b 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/feedranges/FeedRangeEpkImpl.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/feedranges/FeedRangeEpkImpl.java @@ -4,7 +4,6 @@ package com.azure.cosmos.implementation.feedranges; import com.azure.cosmos.BridgeInternal; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.DocumentCollection; import com.azure.cosmos.implementation.GoneException; @@ -259,7 +258,7 @@ public void setProperties(JsonSerializable serializable, boolean populatePropert if (this.range != null) { ModelBridgeInternal.populatePropertyBag(this.range); - serializable.set(Constants.Properties.RANGE, this.range, CosmosItemSerializer.DEFAULT_SERIALIZER); + serializable.set(Constants.Properties.RANGE, this.range); } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/feedranges/FeedRangePartitionKeyImpl.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/feedranges/FeedRangePartitionKeyImpl.java index 38453bdca944..dd7731eaa3f6 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/feedranges/FeedRangePartitionKeyImpl.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/feedranges/FeedRangePartitionKeyImpl.java @@ -4,7 +4,6 @@ package com.azure.cosmos.implementation.feedranges; import com.azure.cosmos.BridgeInternal; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.DocumentCollection; import com.azure.cosmos.implementation.HttpConstants; @@ -194,8 +193,8 @@ public void setProperties(JsonSerializable serializable, boolean populatePropert if (this.partitionKey != null) { serializable.set( Constants.Properties.FEED_RANGE_PARTITION_KEY, - this.partitionKey, - CosmosItemSerializer.DEFAULT_SERIALIZER); + this.partitionKey + ); } } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/feedranges/FeedRangePartitionKeyRangeImpl.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/feedranges/FeedRangePartitionKeyRangeImpl.java index df92f69d23bb..fdd76fddf617 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/feedranges/FeedRangePartitionKeyRangeImpl.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/feedranges/FeedRangePartitionKeyRangeImpl.java @@ -4,7 +4,6 @@ package com.azure.cosmos.implementation.feedranges; import com.azure.cosmos.BridgeInternal; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.DocumentCollection; import com.azure.cosmos.implementation.IRoutingMapProvider; @@ -176,8 +175,8 @@ public void setProperties(JsonSerializable serializable, boolean populatePropert if (this.partitionKeyRangeId != null) { serializable.set( Constants.Properties.FEED_RANGE_PARTITION_KEY_RANGE_ID, - this.partitionKeyRangeId, - CosmosItemSerializer.DEFAULT_SERIALIZER); + this.partitionKeyRangeId + ); } } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/http/HttpClient.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/http/HttpClient.java index 22eb30e7174d..76d45a3cdd27 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/http/HttpClient.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/http/HttpClient.java @@ -42,7 +42,12 @@ static HttpClient createFixed(HttpClientConfig httpClientConfig) { ConnectionProvider.Builder fixedConnectionProviderBuilder = ConnectionProvider .builder(httpClientConfig.getConnectionPoolName()); + fixedConnectionProviderBuilder.maxConnections(httpClientConfig.getMaxPoolSize()); + Integer customPendingAcquireMaxCount = httpClientConfig.getPendingAcquireMaxCount(); + if (customPendingAcquireMaxCount != null) { + fixedConnectionProviderBuilder.pendingAcquireMaxCount(customPendingAcquireMaxCount); + } fixedConnectionProviderBuilder.pendingAcquireTimeout(httpClientConfig.getConnectionAcquireTimeout()); fixedConnectionProviderBuilder.maxIdleTime(httpClientConfig.getMaxIdleConnectionTimeout()); diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/http/HttpClientConfig.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/http/HttpClientConfig.java index d13b8d7317ae..7fb4c763e0d9 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/http/HttpClientConfig.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/http/HttpClientConfig.java @@ -16,6 +16,8 @@ public class HttpClientConfig { private final Configs configs; private Duration connectionAcquireTimeout = Configs.getConnectionAcquireTimeout(); private int maxPoolSize = Configs.getDefaultHttpPoolSize(); + + private Integer pendingAcquireMaxCount = Configs.getPendingAcquireMaxCount(); private Duration maxIdleConnectionTimeout = Configs.getMaxIdleConnectionTimeout(); private Duration networkRequestTimeout = Duration.ofSeconds(Configs.getHttpResponseTimeoutInSeconds()); private String connectionPoolName = Configs.getReactorNettyConnectionPoolName(); @@ -112,6 +114,10 @@ public int getMaxPoolSize() { return maxPoolSize; } + public Integer getPendingAcquireMaxCount() { + return pendingAcquireMaxCount; + } + public Duration getMaxIdleConnectionTimeout() { return maxIdleConnectionTimeout; } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/patch/PatchUtil.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/patch/PatchUtil.java index 566cdc702def..fef98d681a0a 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/patch/PatchUtil.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/patch/PatchUtil.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation.patch; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.JsonSerializable; import com.azure.cosmos.implementation.RequestOptions; import com.azure.cosmos.implementation.Utils; @@ -43,29 +42,29 @@ private static JsonSerializable cosmosPatchToJsonSerializable(CosmosPatchOperati JsonSerializable operationJsonSerializable = new JsonSerializable(); operationJsonSerializable.set( PatchConstants.PropertyNames_OperationType, - patchOperation.getOperationType().getOperationValue(), - CosmosItemSerializer.DEFAULT_SERIALIZER); + patchOperation.getOperationType().getOperationValue() + ); if (patchOperation instanceof PatchOperationCore) { if (patchOperation.getOperationType() == PatchOperationType.MOVE) { operationJsonSerializable.set( PatchConstants.PropertyNames_Path, - ((PatchOperationCore)patchOperation).getPath(), - CosmosItemSerializer.DEFAULT_SERIALIZER); + ((PatchOperationCore)patchOperation).getPath() + ); operationJsonSerializable.set( PatchConstants.PropertyNames_From, - ((PatchOperationCore)patchOperation).getFrom(), - CosmosItemSerializer.DEFAULT_SERIALIZER); + ((PatchOperationCore)patchOperation).getFrom() + ); } else { operationJsonSerializable.set( PatchConstants.PropertyNames_Path, - ((PatchOperationCore)patchOperation).getPath(), - CosmosItemSerializer.DEFAULT_SERIALIZER); + ((PatchOperationCore)patchOperation).getPath() + ); operationJsonSerializable.set( PatchConstants.PropertyNames_Value, - ((PatchOperationCore)patchOperation).getResource(), - CosmosItemSerializer.DEFAULT_SERIALIZER); + ((PatchOperationCore)patchOperation).getResource() + ); } } else { throw new IllegalArgumentException("Invalid patch operation type"); @@ -76,8 +75,8 @@ private static JsonSerializable cosmosPatchToJsonSerializable(CosmosPatchOperati jsonSerializable.set( PatchConstants.OPERATIONS, - operations, - CosmosItemSerializer.DEFAULT_SERIALIZER); + operations + ); if(requestOptions != null) { String filterPredicate = requestOptions.getFilterPredicate(); @@ -85,8 +84,8 @@ private static JsonSerializable cosmosPatchToJsonSerializable(CosmosPatchOperati if (!filterPredicate.isEmpty()) { jsonSerializable.set( PatchConstants.CONDITION, - filterPredicate, - CosmosItemSerializer.DEFAULT_SERIALIZER); + filterPredicate + ); } } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/CompositeContinuationToken.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/CompositeContinuationToken.java index c9bb528f715c..7eb134336794 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/CompositeContinuationToken.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/CompositeContinuationToken.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation.query; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.routing.Range; import com.azure.cosmos.implementation.JsonSerializable; import com.azure.cosmos.implementation.Utils.ValueHolder; @@ -93,7 +92,7 @@ public Range getRange() { // but converting it to the cleaner format if (rangeNode.isTextual()) { Range parsedRange = new Range<>(rangeNode.textValue()); - this.set(RangePropertyName, parsedRange, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(RangePropertyName, parsedRange); return parsedRange; } @@ -108,7 +107,7 @@ public Range getRange() { * the token to set */ public void setToken(String token) { - this.set(TokenPropertyName, token, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(TokenPropertyName, token); } /** @@ -116,7 +115,7 @@ public void setToken(String token) { * the range to set */ public void setRange(Range range) { - this.set(RangePropertyName, range, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(RangePropertyName, range); } @Override diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/DCountDocumentQueryExecutionContext.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/DCountDocumentQueryExecutionContext.java index 97d0193f4f35..cce4826b3ec2 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/DCountDocumentQueryExecutionContext.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/DCountDocumentQueryExecutionContext.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation.query; import com.azure.cosmos.BridgeInternal; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.ClientSideRequestStatistics; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.DistinctClientSideRequestStatisticsCollection; @@ -86,13 +85,13 @@ public Flux> drainAsync(int maxPageSize) { Document result = new Document(); if (Strings.isNullOrEmpty(info.getDCountAlias())) { if (info.hasSelectValue()) { - result.set(Constants.Properties.VALUE, count, CosmosItemSerializer.DEFAULT_SERIALIZER); + result.set(Constants.Properties.VALUE, count); } else { // Setting $1 as the key to be consistent with service results - result.set("$1", count, CosmosItemSerializer.DEFAULT_SERIALIZER); + result.set("$1", count); } } else { - result.set(info.getDCountAlias(), count, CosmosItemSerializer.DEFAULT_SERIALIZER); + result.set(info.getDCountAlias(), count); } headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double.toString(requestCharge)); FeedResponse frp = diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/DistinctContinuationToken.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/DistinctContinuationToken.java index b0bf4487441a..22b5b5e0191d 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/DistinctContinuationToken.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/DistinctContinuationToken.java @@ -2,7 +2,6 @@ // Licensed under the MIT License. package com.azure.cosmos.implementation.query; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.Utils; import com.azure.cosmos.implementation.routing.UInt128; import com.azure.cosmos.implementation.JsonSerializable; @@ -61,7 +60,7 @@ String getSourceToken() { * @param sourceToken Value to set for property 'sourceToken'. */ public void setSourceToken(String sourceToken) { - this.set(SOURCE_TOKEN_PROPERTY_NAME, sourceToken, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(SOURCE_TOKEN_PROPERTY_NAME, sourceToken); } UInt128 getLastHash() { @@ -79,9 +78,9 @@ UInt128 getLastHash() { */ public void setLastHash(UInt128 lastHash) { if (lastHash != null) { - this.set(LAST_HASH_PROPERTY_NAME, lastHash.toByteBuffer().array(), CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(LAST_HASH_PROPERTY_NAME, lastHash.toByteBuffer().array()); } else { - this.set(LAST_HASH_PROPERTY_NAME, null, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(LAST_HASH_PROPERTY_NAME, null); } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/Fetcher.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/Fetcher.java index d3a422bad013..1cbeada1e3d7 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/Fetcher.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/Fetcher.java @@ -10,7 +10,7 @@ import com.azure.cosmos.implementation.circuitBreaker.GlobalPartitionEndpointManagerForCircuitBreaker; import com.azure.cosmos.implementation.ImplementationBridgeHelpers; import com.azure.cosmos.implementation.RxDocumentServiceRequest; -import com.azure.cosmos.implementation.routing.LocationCache; +import com.azure.cosmos.implementation.routing.RegionalRoutingContext; import com.azure.cosmos.implementation.spark.OperationContextAndListenerTuple; import com.azure.cosmos.models.FeedResponse; import com.azure.cosmos.models.ModelBridgeInternal; @@ -228,7 +228,7 @@ private Mono> nextPage(RxDocumentServiceRequest request) { } private void handleCancellationExceptionForPartitionKeyRange(RxDocumentServiceRequest failedRequest) { - LocationCache.ConsolidatedRegionalEndpoint firstContactedLocationEndpoint = diagnosticsAccessor.getFirstContactedLocationEndpoint(failedRequest.requestContext.cosmosDiagnostics); + RegionalRoutingContext firstContactedLocationEndpoint = diagnosticsAccessor.getFirstContactedLocationEndpoint(failedRequest.requestContext.cosmosDiagnostics); if (firstContactedLocationEndpoint != null) { this.globalPartitionEndpointManagerForCircuitBreaker.handleLocationExceptionForPartitionKeyRange(failedRequest, firstContactedLocationEndpoint); diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/LimitContinuationToken.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/LimitContinuationToken.java index ea0076e1c80c..dec7ae3a14e1 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/LimitContinuationToken.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/LimitContinuationToken.java @@ -3,8 +3,6 @@ package com.azure.cosmos.implementation.query; -import com.azure.cosmos.BridgeInternal; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.JsonSerializable; import com.azure.cosmos.implementation.Utils.ValueHolder; import org.slf4j.Logger; @@ -62,11 +60,11 @@ public String getSourceToken() { } private void setLimitCount(int limitCount) { - this.set(LIMIT_PROPERTY_NAME, limitCount, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(LIMIT_PROPERTY_NAME, limitCount); } private void setSourceToken(String sourceToken) { - this.set(SOURCE_TOKEN_PROPERTY_NAME, sourceToken, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(SOURCE_TOKEN_PROPERTY_NAME, sourceToken); } @Override diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/OffsetContinuationToken.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/OffsetContinuationToken.java index 184fcb02d614..8aeefa5d6158 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/OffsetContinuationToken.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/OffsetContinuationToken.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation.query; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.JsonSerializable; import com.azure.cosmos.implementation.Utils; import com.azure.cosmos.implementation.apachecommons.lang.StringUtils; @@ -57,7 +56,7 @@ public String getSourceToken() { } private void setSourceToken(String sourceToken) { - this.set(TOKEN_PROPERTY_NAME, sourceToken, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(TOKEN_PROPERTY_NAME, sourceToken); } public int getOffset() { @@ -65,7 +64,7 @@ public int getOffset() { } private void setOffset(int offset) { - this.set(OFFSET_PROPERTY_NAME, offset, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(OFFSET_PROPERTY_NAME, offset); } @Override diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/OrderByContinuationToken.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/OrderByContinuationToken.java index a920ef40faad..4b97175da5c3 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/OrderByContinuationToken.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/OrderByContinuationToken.java @@ -3,8 +3,6 @@ package com.azure.cosmos.implementation.query; -import com.azure.cosmos.BridgeInternal; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.JsonSerializable; import com.azure.cosmos.implementation.Utils.ValueHolder; import com.azure.cosmos.implementation.routing.Range; @@ -122,19 +120,19 @@ public boolean getInclusive() { } private void setCompositeContinuationToken(CompositeContinuationToken compositeContinuationToken) { - this.set(CompositeContinuationTokenPropertyName, compositeContinuationToken.toJson(), CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(CompositeContinuationTokenPropertyName, compositeContinuationToken.toJson()); } private void setOrderByItems(QueryItem[] orderByItems) { - this.set(OrderByItemsPropetryName, Arrays.asList(orderByItems), CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(OrderByItemsPropetryName, Arrays.asList(orderByItems)); } private void setRid(String rid) { - this.set(RidPropertyName, rid, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(RidPropertyName, rid); } private void setInclusive(boolean inclusive) { - this.set(InclusivePropertyName, inclusive, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(InclusivePropertyName, inclusive); } @Override diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/PartitionedQueryExecutionInfo.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/PartitionedQueryExecutionInfo.java index 70f861f21638..4967d2b1e6be 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/PartitionedQueryExecutionInfo.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/PartitionedQueryExecutionInfo.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation.query; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.RequestTimeline; import com.azure.cosmos.implementation.query.hybridsearch.HybridSearchQueryInfo; import com.azure.cosmos.implementation.routing.Range; @@ -32,8 +31,8 @@ public final class PartitionedQueryExecutionInfo extends JsonSerializable { this.set( PartitionedQueryExecutionInfoInternal.PARTITIONED_QUERY_EXECUTION_INFO_VERSION_PROPERTY, - Constants.PartitionedQueryExecutionInfo.VERSION_1, - CosmosItemSerializer.DEFAULT_SERIALIZER); + Constants.PartitionedQueryExecutionInfo.VERSION_1 + ); } public PartitionedQueryExecutionInfo(ObjectNode content, RequestTimeline queryPlanRequestTimeline) { diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/PartitionedQueryExecutionInfoInternal.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/PartitionedQueryExecutionInfoInternal.java index aaa3554328bc..248745a1da2f 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/PartitionedQueryExecutionInfoInternal.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/PartitionedQueryExecutionInfoInternal.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation.query; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.query.hybridsearch.HybridSearchQueryInfo; import com.azure.cosmos.implementation.routing.PartitionKeyInternal; import com.azure.cosmos.implementation.routing.Range; @@ -32,8 +31,8 @@ public final class PartitionedQueryExecutionInfoInternal extends JsonSerializabl public PartitionedQueryExecutionInfoInternal() { this.set( PARTITIONED_QUERY_EXECUTION_INFO_VERSION_PROPERTY, - Constants.PartitionedQueryExecutionInfo.VERSION_1, - CosmosItemSerializer.DEFAULT_SERIALIZER); + Constants.PartitionedQueryExecutionInfo.VERSION_1 + ); } public PartitionedQueryExecutionInfoInternal(ObjectNode objectNode) { diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/QueryInfo.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/QueryInfo.java index c00cc804336c..b8ea415ebf2f 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/QueryInfo.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/QueryInfo.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation.query; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.RequestTimeline; import com.azure.cosmos.implementation.DiagnosticsInstantSerializer; import com.azure.cosmos.implementation.query.aggregation.AggregateOperator; @@ -245,17 +244,17 @@ public RequestTimeline getRequestTimeline() { public void setOrderByExpressions(List orderByExpressions) { this.orderByExpressions = orderByExpressions; - super.set("orderByExpressions", orderByExpressions, CosmosItemSerializer.DEFAULT_SERIALIZER); + super.set("orderByExpressions", orderByExpressions); } public void setRewrittenQuery(String rewrittenQuery) { this.rewrittenQuery = rewrittenQuery; - super.set("rewrittenQuery", rewrittenQuery, CosmosItemSerializer.DEFAULT_SERIALIZER); + super.set("rewrittenQuery", rewrittenQuery); } public void setOrderBy(List orderBy) { this.orderBy = orderBy; - super.set("orderBy", orderBy, CosmosItemSerializer.DEFAULT_SERIALIZER); + super.set("orderBy", orderBy); } @Override diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/SingleGroupAggregator.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/SingleGroupAggregator.java index 3a851ca12ea2..670939bc3d37 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/SingleGroupAggregator.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/SingleGroupAggregator.java @@ -2,7 +2,6 @@ // Licensed under the MIT License. package com.azure.cosmos.implementation.query; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.Document; import com.azure.cosmos.implementation.Resource; @@ -110,7 +109,7 @@ public Document getResult() { } // This is for value queries.Need to append value property for scalar values (non key value pairs) // to make them a key value pair document as our impl is based on Document. - document.set(Constants.Properties.VALUE, result, CosmosItemSerializer.DEFAULT_SERIALIZER); + document.set(Constants.Properties.VALUE, result); } return document; } @@ -178,7 +177,7 @@ public Document getResult() { for (String alias : this.orderedAliases) { AggregateValue aggregateValue = this.aliasToValue.get(alias); if (aggregateValue.getResult() != null) { - aggregateDocument.set(alias, aggregateValue.getResult(), CosmosItemSerializer.DEFAULT_SERIALIZER); + aggregateDocument.set(alias, aggregateValue.getResult()); } } return aggregateDocument; diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/TopContinuationToken.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/TopContinuationToken.java index cdd8022d3a33..32affe9c53b6 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/TopContinuationToken.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/TopContinuationToken.java @@ -3,8 +3,6 @@ package com.azure.cosmos.implementation.query; -import com.azure.cosmos.BridgeInternal; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.JsonSerializable; import com.azure.cosmos.implementation.Utils.ValueHolder; import org.slf4j.Logger; @@ -62,11 +60,11 @@ public String getSourceToken() { } private void setTopCount(int topCount) { - this.set(TOP_PROPERTY_NAME, topCount, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(TOP_PROPERTY_NAME, topCount); } private void setSourceToken(String sourceToken) { - this.set(SOURCE_TOKEN_PROPERTY_NAME, sourceToken, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(SOURCE_TOKEN_PROPERTY_NAME, sourceToken); } @Override diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/orderbyquery/OrderByRowResult.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/orderbyquery/OrderByRowResult.java index 1c0d8c0e2a6b..7d300d700bd2 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/orderbyquery/OrderByRowResult.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/orderbyquery/OrderByRowResult.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation.query.orderbyquery; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.Document; import com.azure.cosmos.implementation.feedranges.FeedRangeEpkImpl; @@ -43,7 +42,7 @@ public Document getPayload() { final Object object = super.get("payload"); if (!ObjectNode.class.isAssignableFrom(object.getClass())) { Document document = new Document(); - document.set(Constants.Properties.VALUE, object, CosmosItemSerializer.DEFAULT_SERIALIZER); + document.set(Constants.Properties.VALUE, object); payload = document; } else { this.payload = super.getObject("payload", Document.class); diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/LocationCache.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/LocationCache.java index 875d062655b1..4620c4d3d22f 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/LocationCache.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/LocationCache.java @@ -44,11 +44,11 @@ public class LocationCache { private final static Logger logger = LoggerFactory.getLogger(LocationCache.class); private final boolean enableEndpointDiscovery; - private final URI defaultEndpoint; + private final RegionalRoutingContext defaultRegionalRoutingContext; private final boolean useMultipleWriteLocations; private final Object lockObject; private final Duration unavailableLocationsExpirationTime; - private final ConcurrentHashMap locationUnavailabilityInfoByEndpoint; + private final ConcurrentHashMap locationUnavailabilityInfoByEndpoint; private final ConnectionPolicy connectionPolicy; private DatabaseAccountLocationsInfo locationInfo; @@ -67,7 +67,7 @@ public LocationCache( ); this.locationInfo = new DatabaseAccountLocationsInfo(preferredLocations, defaultEndpoint); - this.defaultEndpoint = defaultEndpoint; + this.defaultRegionalRoutingContext = new RegionalRoutingContext(defaultEndpoint); this.enableEndpointDiscovery = connectionPolicy.isEndpointDiscoveryEnabled(); this.useMultipleWriteLocations = connectionPolicy.isMultipleWriteRegionsEnabled(); @@ -88,7 +88,7 @@ public LocationCache( * 2. Endpoint availability * @return */ - public UnmodifiableList getReadEndpoints() { + public UnmodifiableList getReadEndpoints() { if (this.locationUnavailabilityInfoByEndpoint.size() > 0 && unavailableLocationsExpirationTimePassed()) { this.updateLocationCache(); @@ -103,7 +103,7 @@ && unavailableLocationsExpirationTimePassed()) { * 2. Endpoint availability * @return */ - public UnmodifiableList getWriteEndpoints() { + public UnmodifiableList getWriteEndpoints() { if (this.locationUnavailabilityInfoByEndpoint.size() > 0 && unavailableLocationsExpirationTimePassed()) { this.updateLocationCache(); @@ -121,8 +121,9 @@ && unavailableLocationsExpirationTimePassed()) { */ public List getAvailableReadEndpoints() { return this.locationInfo.availableReadEndpointsByLocation.values().stream().map(consolidatedLocationEndpoints -> { - // TODO: Integrate thinclient endpoints into fault injection - return consolidatedLocationEndpoints.gatewayLocationEndpoint; + // TODO (nehrao1): Integrate thinclient endpoints into fault injection + // TODO (nehrao1): https://github.com/Azure/azure-sdk-for-java/issues/44429 + return consolidatedLocationEndpoints.getGatewayRegionalEndpoint(); }).collect(Collectors.toList()); } @@ -135,8 +136,9 @@ public List getAvailableReadEndpoints() { */ public List getAvailableWriteEndpoints() { return this.locationInfo.availableWriteEndpointsByLocation.values().stream().map(consolidatedLocationEndpoints -> { - // TODO: Integrate thinclient endpoints into fault injection - return consolidatedLocationEndpoints.gatewayLocationEndpoint; + // TODO(nehrao1): Integrate thinclient endpoints into fault injection + // TODO(nehrao1): https://github.com/Azure/azure-sdk-for-java/issues/44429 + return consolidatedLocationEndpoints.getGatewayRegionalEndpoint(); }).collect(Collectors.toList()); } @@ -195,15 +197,12 @@ void onLocationPreferenceChanged(UnmodifiableList preferredLocations) { * @param request Request for which getEndpoint is to be resolved * @return Resolved getEndpoint */ - public ConsolidatedRegionalEndpoint resolveServiceEndpoint(RxDocumentServiceRequest request) { + public RegionalRoutingContext resolveServiceEndpoint(RxDocumentServiceRequest request) { Objects.requireNonNull(request.requestContext, "RxDocumentServiceRequest.requestContext is required and cannot be null."); - if (request.requestContext.locationEndpointToRoute != null) { - - Objects.requireNonNull(request.requestContext.consolidatedRegionalEndpointToRoute); - - return request.requestContext.consolidatedRegionalEndpointToRoute; + if (request.requestContext.regionalRoutingContextToRoute != null) { + return request.requestContext.regionalRoutingContextToRoute; } int locationIndex = Utils.getValueOrDefault(request.requestContext.locationIndexToRoute, 0); @@ -220,22 +219,22 @@ public ConsolidatedRegionalEndpoint resolveServiceEndpoint(RxDocumentServiceRequ String writeLocation = currentLocationInfo.availableWriteLocations.get(locationIndex); return currentLocationInfo.availableWriteEndpointsByLocation.get(writeLocation); } else { - return new ConsolidatedRegionalEndpoint(this.defaultEndpoint, null); + return this.defaultRegionalRoutingContext; } } else { - UnmodifiableList endpoints = + UnmodifiableList endpoints = request.getOperationType().isWriteOperation()? this.getApplicableWriteEndpoints(request) : this.getApplicableReadEndpoints(request); return endpoints.get(locationIndex % endpoints.size()); } } - public UnmodifiableList getApplicableWriteEndpoints(RxDocumentServiceRequest request) { + public UnmodifiableList getApplicableWriteEndpoints(RxDocumentServiceRequest request) { return this.getApplicableWriteEndpoints(request.requestContext.getExcludeRegions(), request.requestContext.getUnavailableRegionsForPartition()); } - public UnmodifiableList getApplicableWriteEndpoints(List excludedRegionsOnRequest, List unavailableRegionsForPartition) { + public UnmodifiableList getApplicableWriteEndpoints(List excludedRegionsOnRequest, List unavailableRegionsForPartition) { - UnmodifiableList writeEndpoints = this.getWriteEndpoints(); + UnmodifiableList writeEndpoints = this.getWriteEndpoints(); Supplier excludedRegionsSupplier = this.connectionPolicy.getExcludedRegionsSupplier(); List effectiveExcludedRegions = isExcludedRegionsSupplierConfigured(excludedRegionsSupplier) ? @@ -259,16 +258,16 @@ public UnmodifiableList getApplicableWriteEndpoint return this.getApplicableEndpoints( writeEndpoints, this.locationInfo.regionNameByWriteEndpoint, - this.defaultEndpoint, + this.defaultRegionalRoutingContext, effectiveExcludedRegionsWithPartitionUnavailableRegions); } - public UnmodifiableList getApplicableReadEndpoints(RxDocumentServiceRequest request) { + public UnmodifiableList getApplicableReadEndpoints(RxDocumentServiceRequest request) { return this.getApplicableReadEndpoints(request.requestContext.getExcludeRegions(), request.requestContext.getUnavailableRegionsForPartition()); } - public UnmodifiableList getApplicableReadEndpoints(List excludedRegionsOnRequest, List unavailableRegionsForPartition) { - UnmodifiableList readEndpoints = this.getReadEndpoints(); + public UnmodifiableList getApplicableReadEndpoints(List excludedRegionsOnRequest, List unavailableRegionsForPartition) { + UnmodifiableList readEndpoints = this.getReadEndpoints(); Supplier excludedRegionsSupplier = this.connectionPolicy.getExcludedRegionsSupplier(); List effectiveExcludedRegions = isExcludedRegionsSupplierConfigured(excludedRegionsSupplier) ? @@ -292,18 +291,18 @@ public UnmodifiableList getApplicableReadEndpoints return this.getApplicableEndpoints( readEndpoints, this.locationInfo.regionNameByReadEndpoint, - this.locationInfo.writeEndpoints.get(0).getGatewayLocationEndpoint(), // match the fallback region used in getPreferredAvailableEndpoints + this.locationInfo.writeEndpoints.get(0), // match the fallback region used in getPreferredAvailableEndpoints effectiveExcludedRegionsWithPartitionUnavailableRegions); } - private UnmodifiableList getApplicableEndpoints( - UnmodifiableList endpoints, - UnmodifiableMap regionNameByEndpoint, - URI fallbackEndpoint, + private UnmodifiableList getApplicableEndpoints( + UnmodifiableList endpoints, + UnmodifiableMap regionNameByEndpoint, + RegionalRoutingContext fallbackRegionalRoutingContext, List excludeRegionList) { - List applicableEndpoints = new ArrayList<>(); - for (ConsolidatedRegionalEndpoint endpoint : endpoints) { + List applicableEndpoints = new ArrayList<>(); + for (RegionalRoutingContext endpoint : endpoints) { Utils.ValueHolder regionName = new Utils.ValueHolder<>(); if (Utils.tryGetValue(regionNameByEndpoint, endpoint, regionName)) { if (!excludeRegionList.stream().anyMatch(regionName.v::equalsIgnoreCase)) { @@ -313,7 +312,7 @@ private UnmodifiableList getApplicableEndpoints( } if (applicableEndpoints.isEmpty()) { - applicableEndpoints.add(new ConsolidatedRegionalEndpoint(fallbackEndpoint, null)); + applicableEndpoints.add(fallbackRegionalRoutingContext); } return new UnmodifiableList<>(applicableEndpoints); @@ -327,7 +326,7 @@ private boolean isExcludeRegionsConfigured(List excludedRegionsOnRequest } public URI resolveFaultInjectionEndpoint(String region, boolean writeOnly) { - Utils.ValueHolder endpointValueHolder = new Utils.ValueHolder<>(); + Utils.ValueHolder endpointValueHolder = new Utils.ValueHolder<>(); if (writeOnly) { Utils.tryGetValue(this.locationInfo.availableWriteEndpointsByLocation, region, endpointValueHolder); } else { @@ -336,14 +335,14 @@ public URI resolveFaultInjectionEndpoint(String region, boolean writeOnly) { if (endpointValueHolder.v != null) { // TODO: Figure out how to integrate thinclient into fault injection - return endpointValueHolder.v.gatewayLocationEndpoint; + return endpointValueHolder.v.getGatewayRegionalEndpoint(); } throw new IllegalArgumentException("Can not find service endpoint for region " + region); } public URI getDefaultEndpoint() { - return this.defaultEndpoint; + return this.defaultRegionalRoutingContext.getGatewayRegionalEndpoint(); } public boolean shouldRefreshEndpoints(Utils.ValueHolder canRefreshInBackground) { @@ -359,7 +358,7 @@ public boolean shouldRefreshEndpoints(Utils.ValueHolder canRefreshInBac if (this.enableEndpointDiscovery) { boolean shouldRefresh = this.useMultipleWriteLocations && !this.enableMultipleWriteLocations; - List readLocationEndpoints = currentLocationInfo.readEndpoints; + List readLocationEndpoints = currentLocationInfo.readEndpoints; if (this.isEndpointUnavailable(readLocationEndpoints.get(0), OperationType.Read)) { // Since most preferred read endpoint is unavailable, we can only refresh in background if // we have an alternate read endpoint @@ -372,7 +371,7 @@ public boolean shouldRefreshEndpoints(Utils.ValueHolder canRefreshInBac } if (!Strings.isNullOrEmpty(mostPreferredLocation)) { - Utils.ValueHolder mostPreferredReadEndpointHolder = new Utils.ValueHolder<>(); + Utils.ValueHolder mostPreferredReadEndpointHolder = new Utils.ValueHolder<>(); logger.debug("getReadEndpoints [{}]", readLocationEndpoints); if (Utils.tryGetValue(currentLocationInfo.availableReadEndpointsByLocation, mostPreferredLocation, mostPreferredReadEndpointHolder)) { @@ -396,8 +395,8 @@ public boolean shouldRefreshEndpoints(Utils.ValueHolder canRefreshInBac } } - Utils.ValueHolder mostPreferredWriteEndpointHolder = new Utils.ValueHolder<>(); - List writeLocationEndpoints = currentLocationInfo.writeEndpoints; + Utils.ValueHolder mostPreferredWriteEndpointHolder = new Utils.ValueHolder<>(); + List writeLocationEndpoints = currentLocationInfo.writeEndpoints; logger.debug("getWriteEndpoints [{}]", writeLocationEndpoints); if (!this.canUseMultipleWriteLocations()) { @@ -447,11 +446,11 @@ public boolean shouldRefreshEndpoints(Utils.ValueHolder canRefreshInBac public String getRegionName(URI locationEndpoint, com.azure.cosmos.implementation.OperationType operationType) { Utils.ValueHolder regionName = new Utils.ValueHolder<>(); if (operationType.isWriteOperation()) { - if (Utils.tryGetValue(this.locationInfo.regionNameByWriteEndpoint, new ConsolidatedRegionalEndpoint(locationEndpoint, locationEndpoint), regionName)) { + if (Utils.tryGetValue(this.locationInfo.regionNameByWriteEndpoint, new RegionalRoutingContext(locationEndpoint), regionName)) { return regionName.v; } } else { - if (Utils.tryGetValue(this.locationInfo.regionNameByReadEndpoint, new ConsolidatedRegionalEndpoint(locationEndpoint, locationEndpoint), regionName)) { + if (Utils.tryGetValue(this.locationInfo.regionNameByReadEndpoint, new RegionalRoutingContext(locationEndpoint), regionName)) { return regionName.v; } } @@ -460,15 +459,15 @@ public String getRegionName(URI locationEndpoint, com.azure.cosmos.implementatio return this.locationInfo.availableWriteLocations.get(0).toLowerCase(Locale.ROOT); } - private boolean areEqual(ConsolidatedRegionalEndpoint url1, ConsolidatedRegionalEndpoint url2) { + private boolean areEqual(RegionalRoutingContext url1, RegionalRoutingContext url2) { return url1.equals(url2); } private void clearStaleEndpointUnavailabilityInfo() { if (!this.locationUnavailabilityInfoByEndpoint.isEmpty()) { - List unavailableEndpoints = new ArrayList<>(this.locationUnavailabilityInfoByEndpoint.keySet()); + List unavailableEndpoints = new ArrayList<>(this.locationUnavailabilityInfoByEndpoint.keySet()); - for (ConsolidatedRegionalEndpoint unavailableEndpoint: unavailableEndpoints) { + for (RegionalRoutingContext unavailableEndpoint: unavailableEndpoints) { Utils.ValueHolder unavailabilityInfoHolder = new Utils.ValueHolder<>(); Utils.ValueHolder removedHolder = new Utils.ValueHolder<>(); @@ -487,7 +486,7 @@ private void clearStaleEndpointUnavailabilityInfo() { } } - private boolean isEndpointUnavailable(ConsolidatedRegionalEndpoint endpoint, OperationType expectedAvailableOperations) { + private boolean isEndpointUnavailable(RegionalRoutingContext endpoint, OperationType expectedAvailableOperations) { Utils.ValueHolder unavailabilityInfoHolder = new Utils.ValueHolder<>(); if (expectedAvailableOperations == OperationType.None @@ -508,10 +507,10 @@ private boolean isEndpointUnavailable(ConsolidatedRegionalEndpoint endpoint, Ope } } - private boolean anyEndpointsAvailable(List endpoints, OperationType expectedAvailableOperations) { + private boolean anyEndpointsAvailable(List endpoints, OperationType expectedAvailableOperations) { Utils.ValueHolder unavailabilityInfoHolder = new Utils.ValueHolder<>(); boolean anyEndpointsAvailable = false; - for (ConsolidatedRegionalEndpoint endpoint : endpoints) { + for (RegionalRoutingContext endpoint : endpoints) { if (!isEndpointUnavailable(endpoint, expectedAvailableOperations)) { anyEndpointsAvailable = true; break; @@ -525,10 +524,10 @@ private void markEndpointUnavailable( OperationType unavailableOperationType) { Instant currentTime = Instant.now(); LocationUnavailabilityInfo updatedInfo = this.locationUnavailabilityInfoByEndpoint.compute( - new ConsolidatedRegionalEndpoint(unavailableEndpoint, null), - new BiFunction() { + new RegionalRoutingContext(unavailableEndpoint), + new BiFunction() { @Override - public LocationUnavailabilityInfo apply(ConsolidatedRegionalEndpoint url, LocationUnavailabilityInfo info) { + public LocationUnavailabilityInfo apply(RegionalRoutingContext url, LocationUnavailabilityInfo info) { if (info == null) { // not already present, add return new LocationUnavailabilityInfo(currentTime, unavailableOperationType); @@ -557,8 +556,8 @@ private void updateLocationCache(){ private void updateLocationCache( Iterable gatewayWriteLocations, Iterable gatewayReadLocations, - Iterable thinClientWriteLocations, - Iterable thinClientReadLocations, + Iterable thinclientWriteLocations, + Iterable thinclientReadLocations, UnmodifiableList preferenceList, Boolean enableMultipleWriteLocations) { synchronized (this.lockObject) { @@ -566,56 +565,6 @@ private void updateLocationCache( logger.debug("updating location cache ..., current readLocations [{}], current writeLocations [{}]", nextLocationInfo.readEndpoints, nextLocationInfo.writeEndpoints); - List effectiveThinClientWriteLocations = new ArrayList<>(); - if (thinClientWriteLocations != null) { - thinClientWriteLocations.forEach(l -> effectiveThinClientWriteLocations.add(l)); - } - - List effectiveThinClientReadLocations = new ArrayList<>(); - if (thinClientReadLocations != null) { - thinClientReadLocations.forEach(l -> effectiveThinClientReadLocations.add(l)); - } - - if (effectiveThinClientWriteLocations.size() == 0) { - logger.error("GetAccount does not contain ThinClient write locations - injecting them."); - - if (gatewayWriteLocations != null) { - gatewayWriteLocations.forEach(l -> { - DatabaseAccountLocation cloned = new DatabaseAccountLocation(l.getPropertyBag().deepCopy()); - URI uri = URI.create(cloned.getEndpoint()); - String transformed = "https://" + uri.getHost() + ":10650"; - logger.error("Transforming Uri {} -> {}", cloned.getEndpoint(), transformed); - cloned.setEndpoint(transformed); - effectiveThinClientWriteLocations.add(cloned); - }); - } - } else { - logger.error("GetAccount contains ThinClient write locations."); - effectiveThinClientReadLocations.forEach(l -> logger.error("Existing Uri {}", l.getEndpoint())); - } - - if (effectiveThinClientReadLocations.size() == 0) { - logger.error("GetAccount does not contain ThinClient read locations - injecting them."); - - if (gatewayReadLocations != null) { - gatewayReadLocations.forEach(l -> { - DatabaseAccountLocation cloned = new DatabaseAccountLocation(l.getPropertyBag().deepCopy()); - URI uri = URI.create(cloned.getEndpoint()); - String transformed = "https://" + uri.getHost() + ":10650"; - logger.error("Transforming Uri {} -> {}", cloned.getEndpoint(), transformed); - cloned.setEndpoint(transformed); - effectiveThinClientReadLocations.add(cloned); - }); - } - - } else { - logger.error("GetAccount contains ThinClient read locations."); - effectiveThinClientReadLocations.forEach(l -> logger.error("Existing Uri {}", l.getEndpoint())); - } - - thinClientWriteLocations = effectiveThinClientWriteLocations; - thinClientReadLocations = effectiveThinClientReadLocations; - if (preferenceList != null) { nextLocationInfo.preferredLocations = preferenceList; } @@ -628,29 +577,29 @@ private void updateLocationCache( if (gatewayReadLocations != null) { Utils.ValueHolder> readValueHolder = Utils.ValueHolder.initialize(nextLocationInfo.availableReadLocations); - Utils.ValueHolder> readRegionMapValueHolder = Utils.ValueHolder.initialize(nextLocationInfo.regionNameByReadEndpoint); - nextLocationInfo.availableReadEndpointsByLocation = this.getEndpointsByLocation(gatewayReadLocations, thinClientReadLocations, readValueHolder, readRegionMapValueHolder); + Utils.ValueHolder> readRegionMapValueHolder = Utils.ValueHolder.initialize(nextLocationInfo.regionNameByReadEndpoint); + nextLocationInfo.availableReadEndpointsByLocation = this.getEndpointsByLocation(gatewayReadLocations, thinclientReadLocations, readValueHolder, readRegionMapValueHolder); nextLocationInfo.availableReadLocations = readValueHolder.v; nextLocationInfo.regionNameByReadEndpoint = readRegionMapValueHolder.v; } if (gatewayWriteLocations != null) { Utils.ValueHolder> writeValueHolder = Utils.ValueHolder.initialize(nextLocationInfo.availableWriteLocations); - Utils.ValueHolder> outWriteRegionMap = Utils.ValueHolder.initialize(nextLocationInfo.regionNameByWriteEndpoint); - nextLocationInfo.availableWriteEndpointsByLocation = this.getEndpointsByLocation(gatewayWriteLocations, thinClientWriteLocations, writeValueHolder, outWriteRegionMap); + Utils.ValueHolder> outWriteRegionMap = Utils.ValueHolder.initialize(nextLocationInfo.regionNameByWriteEndpoint); + nextLocationInfo.availableWriteEndpointsByLocation = this.getEndpointsByLocation(gatewayWriteLocations, thinclientWriteLocations, writeValueHolder, outWriteRegionMap); nextLocationInfo.availableWriteLocations = writeValueHolder.v; nextLocationInfo.regionNameByWriteEndpoint = outWriteRegionMap.v; } - nextLocationInfo.writeEndpoints = this.getPreferredAvailableEndpoints(nextLocationInfo.availableWriteEndpointsByLocation, nextLocationInfo.availableWriteLocations, OperationType.Write, this.defaultEndpoint); - nextLocationInfo.readEndpoints = this.getPreferredAvailableEndpoints(nextLocationInfo.availableReadEndpointsByLocation, nextLocationInfo.availableReadLocations, OperationType.Read, nextLocationInfo.writeEndpoints.get(0).getGatewayLocationEndpoint()); + nextLocationInfo.writeEndpoints = this.getPreferredAvailableEndpoints(nextLocationInfo.availableWriteEndpointsByLocation, nextLocationInfo.availableWriteLocations, OperationType.Write, this.defaultRegionalRoutingContext); + nextLocationInfo.readEndpoints = this.getPreferredAvailableEndpoints(nextLocationInfo.availableReadEndpointsByLocation, nextLocationInfo.availableReadLocations, OperationType.Read, nextLocationInfo.writeEndpoints.get(0)); if (nextLocationInfo.preferredLocations == null || nextLocationInfo.preferredLocations.isEmpty()) { Utils.ValueHolder regionForDefaultEndpoint = new Utils.ValueHolder<>(); // only set effective preferred locations when default endpoint doesn't map to a regional endpoint - if (!Utils.tryGetValue(nextLocationInfo.regionNameByReadEndpoint, new ConsolidatedRegionalEndpoint(this.defaultEndpoint, null), regionForDefaultEndpoint)) { + if (!Utils.tryGetValue(nextLocationInfo.regionNameByReadEndpoint, this.defaultRegionalRoutingContext, regionForDefaultEndpoint)) { nextLocationInfo.effectivePreferredLocations = nextLocationInfo.availableReadLocations; } } @@ -663,16 +612,16 @@ private void updateLocationCache( } } - private UnmodifiableList getPreferredAvailableEndpoints(UnmodifiableMap endpointsByLocation, - UnmodifiableList orderedLocations, - OperationType expectedAvailableOperation, - URI fallbackEndpoint) { - List endpoints = new ArrayList<>(); + private UnmodifiableList getPreferredAvailableEndpoints(UnmodifiableMap endpointsByLocation, + UnmodifiableList orderedLocations, + OperationType expectedAvailableOperation, + RegionalRoutingContext fallbackRegionalRoutingContext) { + List endpoints = new ArrayList<>(); DatabaseAccountLocationsInfo currentLocationInfo = this.locationInfo; // if enableEndpointDiscovery is false, we always use the defaultEndpoint that user passed in during documentClient init if (this.enableEndpointDiscovery) { if (this.canUseMultipleWriteLocations() || expectedAvailableOperation.supports(OperationType.Read)) { - List unavailableEndpoints = new ArrayList<>(); + List unavailableEndpoints = new ArrayList<>(); // When client can not use multiple write locations, preferred locations list should only be used // determining read endpoints order. @@ -681,7 +630,7 @@ private UnmodifiableList getPreferredAvailableEndp if (currentLocationInfo.preferredLocations != null && !currentLocationInfo.preferredLocations.isEmpty()) { for (String location: currentLocationInfo.preferredLocations) { - Utils.ValueHolder endpoint = new Utils.ValueHolder<>(); + Utils.ValueHolder endpoint = new Utils.ValueHolder<>(); if (Utils.tryGetValue(endpointsByLocation, location, endpoint)) { if (this.isEndpointUnavailable(endpoint.v, expectedAvailableOperation)) { unavailableEndpoints.add(endpoint.v); @@ -692,12 +641,12 @@ private UnmodifiableList getPreferredAvailableEndp } } else { for (String location : orderedLocations) { - Utils.ValueHolder endpoint = Utils.ValueHolder.initialize(null); + Utils.ValueHolder endpoint = Utils.ValueHolder.initialize(null); if (Utils.tryGetValue(endpointsByLocation, location, endpoint)) { // if defaultEndpoint equals a regional endpoint then use // whatever the fallback endpoint is - if (this.defaultEndpoint.equals(endpoint.v.getGatewayLocationEndpoint())) { + if (this.defaultRegionalRoutingContext.getGatewayRegionalEndpoint().equals(endpoint.v.getGatewayRegionalEndpoint())) { endpoints = new ArrayList<>(); break; } @@ -712,14 +661,13 @@ private UnmodifiableList getPreferredAvailableEndp } if (endpoints.isEmpty()) { - endpoints.add(new ConsolidatedRegionalEndpoint(fallbackEndpoint, null)); + endpoints.add(fallbackRegionalRoutingContext); } endpoints.addAll(unavailableEndpoints); } else { for (String location : orderedLocations) { - - Utils.ValueHolder endpoint = Utils.ValueHolder.initialize(null); + Utils.ValueHolder endpoint = Utils.ValueHolder.initialize(null); if (!Strings.isNullOrEmpty(location) && // location is empty during manual failover Utils.tryGetValue(endpointsByLocation, location, endpoint)) { endpoints.add(endpoint.v); @@ -729,17 +677,16 @@ private UnmodifiableList getPreferredAvailableEndp } if (endpoints.isEmpty()) { - endpoints.add(new ConsolidatedRegionalEndpoint(fallbackEndpoint, null)); + endpoints.add(fallbackRegionalRoutingContext); } - return new UnmodifiableList<>(endpoints); } private void addEndpoints( Iterable gatewayDbAccountLocations, - Iterable thinClientDbAccountLocations, - Map endpointsByLocation, - Map regionByEndpoint, + Iterable thinclientDbAccountLocations, + Map endpointsByLocation, + Map regionByEndpoint, List parsedLocations) { if (gatewayDbAccountLocations != null) { @@ -750,65 +697,61 @@ private void addEndpoints( String location = gatewayDbAccountLocation.getName().toLowerCase(Locale.ROOT); URI endpoint = new URI(gatewayDbAccountLocation.getEndpoint().toLowerCase(Locale.ROOT)); - ConsolidatedRegionalEndpoint consolidatedRegionalEndpoint = new ConsolidatedRegionalEndpoint(endpoint, null); + RegionalRoutingContext regionalRoutingContext = new RegionalRoutingContext(endpoint); if (!endpointsByLocation.containsKey(location)) { - endpointsByLocation.put(location, consolidatedRegionalEndpoint); + endpointsByLocation.put(location, regionalRoutingContext); } - if (!regionByEndpoint.containsKey(consolidatedRegionalEndpoint)) { - regionByEndpoint.put(consolidatedRegionalEndpoint, location); + if (!regionByEndpoint.containsKey(regionalRoutingContext)) { + regionByEndpoint.put(regionalRoutingContext, location); } parsedLocations.add(gatewayDbAccountLocation.getName()); } catch (Exception e) { - logger.warn("GetAvailableEndpointsByLocation() - skipping add for location = [{}] as its location name is either empty or endpoint is malformed [{}]", + logger.warn("Skipping add for location = [{}] and endpoint = [{}] due to exception [{}]", gatewayDbAccountLocation.getName(), - gatewayDbAccountLocation.getEndpoint()); + gatewayDbAccountLocation.getEndpoint(), + e.getMessage()); } } } } - if (thinClientDbAccountLocations != null) { - for (DatabaseAccountLocation thinClientDbAccountLocation: thinClientDbAccountLocations) { - if (!Strings.isNullOrEmpty(thinClientDbAccountLocation.getName())) { + if (thinclientDbAccountLocations != null) { + for (DatabaseAccountLocation thinclientDbAccountLocation : thinclientDbAccountLocations) { + if (!Strings.isNullOrEmpty(thinclientDbAccountLocation.getName())) { try { - String location = thinClientDbAccountLocation.getName().toLowerCase(Locale.ROOT); - URI endpoint = new URI(thinClientDbAccountLocation.getEndpoint().toLowerCase(Locale.ROOT)); - - ConsolidatedRegionalEndpoint consolidatedRegionalEndpoint = endpointsByLocation.get(location); - - if (consolidatedRegionalEndpoint == null) { - throw new IllegalStateException(String.format("Gateway location endpoint doesn't exist while thin client location endpoint exists for location %s", location)); - } - - consolidatedRegionalEndpoint.thinClientLocationEndpoint = endpoint; + String location = thinclientDbAccountLocation.getName().toLowerCase(Locale.ROOT); + URI endpoint = new URI(thinclientDbAccountLocation.getEndpoint().toLowerCase(Locale.ROOT)); + RegionalRoutingContext regionalRoutingContext = endpointsByLocation.get(location); + regionalRoutingContext.setThinclientRegionalEndpoint(endpoint); } catch (Exception e) { - logger.warn("GetAvailableEndpointsByLocation() - skipping add for location = [{}] as its location name is either empty or endpoint is malformed [{}]", - thinClientDbAccountLocation.getName(), - thinClientDbAccountLocation.getEndpoint()); + logger.warn("Skipping add for location = [{}] and endpoint = [{}] due to exception [{}]", + thinclientDbAccountLocation.getName(), + thinclientDbAccountLocation.getEndpoint(), + e.getMessage()); } } } } } - private UnmodifiableMap getEndpointsByLocation(Iterable gatewayLocations, - Iterable thinClientLocations, - Utils.ValueHolder> orderedLocations, - Utils.ValueHolder> regionMap) { - Map endpointsByLocation = new CaseInsensitiveMap<>(); - Map regionByEndpoint = new CaseInsensitiveMap<>(); + private UnmodifiableMap getEndpointsByLocation(Iterable gatewayLocations, + Iterable thinclientLocations, + Utils.ValueHolder> orderedLocations, + Utils.ValueHolder> regionMap) { + Map endpointsByLocation = new CaseInsensitiveMap<>(); + Map regionByEndpoint = new CaseInsensitiveMap<>(); List parsedLocations = new ArrayList<>(); - addEndpoints(gatewayLocations, thinClientLocations, endpointsByLocation, regionByEndpoint, parsedLocations); + addEndpoints(gatewayLocations, thinclientLocations, endpointsByLocation, regionByEndpoint, parsedLocations); orderedLocations.v = new UnmodifiableList<>(parsedLocations); - regionMap.v = (UnmodifiableMap) UnmodifiableMap.unmodifiableMap(regionByEndpoint); + regionMap.v = (UnmodifiableMap) UnmodifiableMap.unmodifiableMap(regionByEndpoint); - return (UnmodifiableMap) UnmodifiableMap.unmodifiableMap(endpointsByLocation); + return (UnmodifiableMap) UnmodifiableMap.unmodifiableMap(endpointsByLocation); } public boolean canUseMultipleWriteLocations() { @@ -883,67 +826,36 @@ private static boolean isExcludedRegionsSupplierConfigured(Supplier writeEndpoints; - private UnmodifiableList readEndpoints; + private UnmodifiableList writeEndpoints; + private UnmodifiableList readEndpoints; private UnmodifiableList preferredLocations; private UnmodifiableList effectivePreferredLocations; // lower-case region private UnmodifiableList availableWriteLocations; // lower-case region private UnmodifiableList availableReadLocations; - private UnmodifiableMap availableWriteEndpointsByLocation; - private UnmodifiableMap availableReadEndpointsByLocation; - private UnmodifiableMap regionNameByWriteEndpoint; - private UnmodifiableMap regionNameByReadEndpoint; + private UnmodifiableMap availableWriteEndpointsByLocation; + private UnmodifiableMap availableReadEndpointsByLocation; + private UnmodifiableMap regionNameByWriteEndpoint; + private UnmodifiableMap regionNameByReadEndpoint; public DatabaseAccountLocationsInfo(List preferredLocations, URI defaultEndpoint) { this.preferredLocations = new UnmodifiableList<>(preferredLocations.stream().map(loc -> loc.toLowerCase(Locale.ROOT)).collect(Collectors.toList())); this.effectivePreferredLocations = new UnmodifiableList<>(Collections.emptyList()); this.availableWriteEndpointsByLocation - = (UnmodifiableMap) UnmodifiableMap.unmodifiableMap(new CaseInsensitiveMap<>()); + = (UnmodifiableMap) UnmodifiableMap.unmodifiableMap(new CaseInsensitiveMap<>()); this.availableReadEndpointsByLocation - = (UnmodifiableMap) UnmodifiableMap.unmodifiableMap(new CaseInsensitiveMap<>()); + = (UnmodifiableMap) UnmodifiableMap.unmodifiableMap(new CaseInsensitiveMap<>()); this.regionNameByWriteEndpoint - = (UnmodifiableMap) UnmodifiableMap.unmodifiableMap(new CaseInsensitiveMap<>()); + = (UnmodifiableMap) UnmodifiableMap.unmodifiableMap(new CaseInsensitiveMap<>()); this.regionNameByReadEndpoint - = (UnmodifiableMap) UnmodifiableMap.unmodifiableMap(new CaseInsensitiveMap<>()); + = (UnmodifiableMap) UnmodifiableMap.unmodifiableMap(new CaseInsensitiveMap<>()); this.availableReadLocations = new UnmodifiableList<>(Collections.emptyList()); this.availableWriteLocations = new UnmodifiableList<>(Collections.emptyList()); - this.readEndpoints = new UnmodifiableList<>(Collections.singletonList(new ConsolidatedRegionalEndpoint(defaultEndpoint, null))); - this.writeEndpoints = new UnmodifiableList<>(Collections.singletonList(new ConsolidatedRegionalEndpoint(defaultEndpoint, null))); + this.readEndpoints = new UnmodifiableList<>(Collections.singletonList(new RegionalRoutingContext(defaultEndpoint))); + this.writeEndpoints = new UnmodifiableList<>(Collections.singletonList(new RegionalRoutingContext(defaultEndpoint))); } public DatabaseAccountLocationsInfo(DatabaseAccountLocationsInfo other) { diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/PartitionKeyInternal.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/PartitionKeyInternal.java index eed0530f7242..e4dd9db725c0 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/PartitionKeyInternal.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/PartitionKeyInternal.java @@ -30,7 +30,6 @@ import java.util.Arrays; import java.util.Iterator; import java.util.List; -import java.util.stream.Collectors; import static com.azure.cosmos.implementation.Utils.as; @@ -182,16 +181,6 @@ public boolean equals(Object obj) { @Override public int hashCode() { -// TODO: @kushagraThapar, @moderakh, mbhaskar to identify proper implementation. -// Issue: https://github.com/Azure/azure-sdk-for-java/issues/9046 -// if (this.components == null || this.components.size() == 0) { -// return 0; -// } -// int [] ordinals = new int[this.components.size()]; -// for (int i = 0; i < this.components.size(); i++) { -// ordinals[i] = this.components.get(i).GetTypeOrdinal(); -// } -// return Arrays.hashCode(ordinals); return super.hashCode(); } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/PartitionKeyInternalHelper.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/PartitionKeyInternalHelper.java index 2725d4370525..2803536084be 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/PartitionKeyInternalHelper.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/PartitionKeyInternalHelper.java @@ -12,7 +12,6 @@ import java.io.IOException; import java.nio.ByteBuffer; -import java.util.Collection; import java.util.List; public class PartitionKeyInternalHelper { @@ -22,7 +21,7 @@ public class PartitionKeyInternalHelper { public static final String MaximumExclusiveEffectivePartitionKey = toHexEncodedBinaryString(PartitionKeyInternal.InfinityPartitionKey.components); public static final byte[] MaximumExclusiveEffectivePartitionKeyBytes = toBinary(PartitionKeyInternal.InfinityPartitionKey.components); - public static final Range FullRange = new Range( + public static final Range FullRange = new Range<>( PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey, PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, true, diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/Range.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/Range.java index edeb116f8ed6..ca8339cba99d 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/Range.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/Range.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation.routing; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.JsonSerializable; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @@ -84,7 +83,7 @@ public T getMin() { public void setMin(T min) { this.minValue = min; - this.set(Range.MIN_PROPERTY, min, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Range.MIN_PROPERTY, min); } @SuppressWarnings("unchecked") @@ -98,7 +97,7 @@ public T getMax() { public void setMax(T max) { this.maxValue = max; - this.set(Range.MAX_PROPERTY, max, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Range.MAX_PROPERTY, max); } @JsonProperty("isMinInclusive") @@ -111,7 +110,7 @@ public void setMinInclusive(boolean isMinInclusive) { if (isMinInclusive) { this.remove(Range.IS_MIN_INCLUSIVE_PROPERTY); } else { - this.set(Range.IS_MIN_INCLUSIVE_PROPERTY, false, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Range.IS_MIN_INCLUSIVE_PROPERTY, false); } } @@ -122,7 +121,7 @@ public boolean isMaxInclusive() { public void setMaxInclusive(boolean isMaxInclusive) { if (isMaxInclusive) { - this.set(Range.IS_MAX_INCLUSIVE_PROPERTY, true, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.set(Range.IS_MAX_INCLUSIVE_PROPERTY, true); } else { this.remove(Range.IS_MAX_INCLUSIVE_PROPERTY); } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/RegionalRoutingContext.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/RegionalRoutingContext.java new file mode 100644 index 000000000000..bdcf784744b0 --- /dev/null +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/RegionalRoutingContext.java @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.cosmos.implementation.routing; + +import java.net.URI; +import java.util.Objects; + +public class RegionalRoutingContext { + + // IMPORTANT: + // Please reevaluate overridden equals() implementation + // when adding additional properties to this class + private final URI gatewayRegionalEndpoint; + private final String gatewayRegionalEndpointAsString; + private URI thinclientRegionalEndpoint; + private String thinclientRegionalEndpointAsString; + + public RegionalRoutingContext(URI gatewayRegionalEndpoint) { + this.gatewayRegionalEndpoint = gatewayRegionalEndpoint; + this.gatewayRegionalEndpointAsString = gatewayRegionalEndpoint.toString(); + this.thinclientRegionalEndpoint = null; + thinclientRegionalEndpointAsString = null; + } + + public URI getGatewayRegionalEndpoint() { + return this.gatewayRegionalEndpoint; + } + + public void setThinclientRegionalEndpoint(URI thinclientRegionalEndpoint) { + this.thinclientRegionalEndpoint = thinclientRegionalEndpoint; + this.thinclientRegionalEndpointAsString = thinclientRegionalEndpoint.toString(); + } + + public URI getThinclientRegionalEndpoint() { + return this.thinclientRegionalEndpoint; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + RegionalRoutingContext that = (RegionalRoutingContext) o; + return this.gatewayRegionalEndpoint.equals(that.gatewayRegionalEndpoint) && + this.thinclientRegionalEndpoint.equals(that.thinclientRegionalEndpoint); + } + + @Override + public int hashCode() { + return Objects.hash(this.gatewayRegionalEndpointAsString, this.thinclientRegionalEndpointAsString); + } +} diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/ChangeFeedPolicy.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/ChangeFeedPolicy.java index 9ff875a4609c..0848c9ab6cfe 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/ChangeFeedPolicy.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/ChangeFeedPolicy.java @@ -3,7 +3,6 @@ package com.azure.cosmos.models; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.JsonSerializable; import com.azure.cosmos.util.Beta; @@ -239,14 +238,14 @@ ChangeFeedPolicy setRetentionDurationForAllVersionsAndDeletesPolicyInMinutes(Int if (retentionDurationInMinutes == null || retentionDurationInMinutes <= 0) { this.jsonSerializable.set( Constants.Properties.LOG_RETENTION_DURATION, - 0, - CosmosItemSerializer.DEFAULT_SERIALIZER); + 0 + ); } else { this.jsonSerializable.set( Constants.Properties.LOG_RETENTION_DURATION, - retentionDurationInMinutes, - CosmosItemSerializer.DEFAULT_SERIALIZER); + retentionDurationInMinutes + ); } return this; diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CompositePath.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CompositePath.java index 8cfd99b46e37..8a20ac937038 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CompositePath.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CompositePath.java @@ -3,7 +3,6 @@ package com.azure.cosmos.models; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.JsonSerializable; import com.azure.cosmos.implementation.apachecommons.lang.StringUtils; @@ -64,7 +63,7 @@ public String getPath() { */ public CompositePath setPath(String path) { this.jsonSerializable = new JsonSerializable(); - this.jsonSerializable.set(Constants.Properties.PATH, path, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.jsonSerializable.set(Constants.Properties.PATH, path); return this; } @@ -102,7 +101,7 @@ public CompositePathSortOrder getOrder() { * @return the CompositePath. */ public CompositePath setOrder(CompositePathSortOrder order) { - this.jsonSerializable.set(Constants.Properties.ORDER, order.toString(), CosmosItemSerializer.DEFAULT_SERIALIZER); + this.jsonSerializable.set(Constants.Properties.ORDER, order.toString()); return this; } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/ConflictResolutionPolicy.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/ConflictResolutionPolicy.java index a514bea4f36d..0dbcd090421b 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/ConflictResolutionPolicy.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/ConflictResolutionPolicy.java @@ -4,7 +4,6 @@ package com.azure.cosmos.models; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.JsonSerializable; import com.azure.cosmos.implementation.Paths; @@ -224,7 +223,7 @@ public ConflictResolutionMode getMode() { * @param mode One of the values of the {@link ConflictResolutionMode} enum. */ ConflictResolutionPolicy setMode(ConflictResolutionMode mode) { - this.jsonSerializable.set(Constants.Properties.MODE, mode.toString(), CosmosItemSerializer.DEFAULT_SERIALIZER); + this.jsonSerializable.set(Constants.Properties.MODE, mode.toString()); return this; } @@ -261,8 +260,8 @@ public String getConflictResolutionPath() { ConflictResolutionPolicy setConflictResolutionPath(String value) { this.jsonSerializable.set( Constants.Properties.CONFLICT_RESOLUTION_PATH, - value, - CosmosItemSerializer.DEFAULT_SERIALIZER); + value + ); return this; } @@ -288,8 +287,8 @@ public String getConflictResolutionProcedure() { ConflictResolutionPolicy setConflictResolutionProcedure(String value) { this.jsonSerializable.set( Constants.Properties.CONFLICT_RESOLUTION_PROCEDURE, - value, - CosmosItemSerializer.DEFAULT_SERIALIZER); + value + ); return this; } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosBatchOperationResult.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosBatchOperationResult.java index 267006c604fd..aa9baff39fde 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosBatchOperationResult.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosBatchOperationResult.java @@ -4,6 +4,7 @@ package com.azure.cosmos.models; import com.azure.cosmos.CosmosItemSerializer; +import com.azure.cosmos.implementation.DefaultCosmosItemSerializer; import com.azure.cosmos.implementation.ImplementationBridgeHelpers; import com.azure.cosmos.implementation.JsonSerializable; import com.azure.cosmos.implementation.Utils; @@ -89,7 +90,8 @@ public T getItem(final Class type) { T item = null; if (this.getResourceObject() != null) { - if (effectiveItemSerializer == CosmosItemSerializer.DEFAULT_SERIALIZER) { + if (effectiveItemSerializer == CosmosItemSerializer.DEFAULT_SERIALIZER + || effectiveItemSerializer == DefaultCosmosItemSerializer.INTERNAL_DEFAULT_SERIALIZER) { item = new JsonSerializable(this.getResourceObject()).toObject(type); } else { item = Utils.parse(this.getResourceObject(), type, effectiveItemSerializer); diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosBulkItemResponse.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosBulkItemResponse.java index 73c6a5271bae..3e99ea32e644 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosBulkItemResponse.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosBulkItemResponse.java @@ -6,6 +6,7 @@ import com.azure.cosmos.CosmosAsyncContainer; import com.azure.cosmos.CosmosDiagnostics; import com.azure.cosmos.CosmosItemSerializer; +import com.azure.cosmos.implementation.DefaultCosmosItemSerializer; import com.azure.cosmos.implementation.ImplementationBridgeHelpers; import com.azure.cosmos.implementation.JsonSerializable; import com.azure.cosmos.implementation.Utils; @@ -105,7 +106,8 @@ public T getItem(final Class type) { T item = null; if (this.getResourceObject() != null) { - if (effectiveItemSerializer == CosmosItemSerializer.DEFAULT_SERIALIZER) { + if (effectiveItemSerializer == CosmosItemSerializer.DEFAULT_SERIALIZER + || effectiveItemSerializer == DefaultCosmosItemSerializer.INTERNAL_DEFAULT_SERIALIZER) { item = new JsonSerializable(this.getResourceObject()).toObject(type); } else { item = Utils.parse(this.getResourceObject(), type, effectiveItemSerializer); diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosFullTextIndex.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosFullTextIndex.java index 51ec2cec823c..5d9851462665 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosFullTextIndex.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosFullTextIndex.java @@ -3,7 +3,6 @@ package com.azure.cosmos.models; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.JsonSerializable; import com.azure.cosmos.util.Beta; @@ -39,8 +38,8 @@ public CosmosFullTextIndex() { public CosmosFullTextIndex setPath(String path) { this.jsonSerializable.set( Constants.Properties.PATH, - path, - CosmosItemSerializer.DEFAULT_SERIALIZER); + path + ); return this; } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosVectorIndexSpec.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosVectorIndexSpec.java index bfc4da5af348..36ce493aab74 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosVectorIndexSpec.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosVectorIndexSpec.java @@ -3,7 +3,6 @@ package com.azure.cosmos.models; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.JsonSerializable; import com.azure.cosmos.implementation.query.IndexProperty; @@ -48,7 +47,7 @@ public String getPath() { * @return the SpatialSpec. */ public CosmosVectorIndexSpec setPath(String path) { - this.jsonSerializable.set(Constants.Properties.PATH, path, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.jsonSerializable.set(Constants.Properties.PATH, path); return this; } @@ -76,7 +75,7 @@ public CosmosVectorIndexSpec setType(String type) { throw new IllegalArgumentException(String.format("%s is an invalid index type. Valid index types are 'flat', 'quantizedFlat' or 'diskANN'.", type)); } this.type = type; - this.jsonSerializable.set(Constants.Properties.VECTOR_INDEX_TYPE, this.type, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.jsonSerializable.set(Constants.Properties.VECTOR_INDEX_TYPE, this.type); return this; } @@ -108,7 +107,7 @@ public Integer getQuantizationSizeInBytes() { public CosmosVectorIndexSpec setQuantizationSizeInBytes(Integer quantizationByteSize) { if (validateIndexType(IndexProperty.QUANTIZATION_SIZE_IN_BYTES) && quantizationByteSize != null) { this.quantizationSizeInBytes = quantizationByteSize; - this.jsonSerializable.set(Constants.Properties.VECTOR_QUANTIZATION_SIZE_IN_BYTES, this.quantizationSizeInBytes, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.jsonSerializable.set(Constants.Properties.VECTOR_QUANTIZATION_SIZE_IN_BYTES, this.quantizationSizeInBytes); } else { this.quantizationSizeInBytes = null; } @@ -141,7 +140,7 @@ public Integer getIndexingSearchListSize() { public CosmosVectorIndexSpec setIndexingSearchListSize(Integer indexingSearchListSize) { if (validateIndexType(IndexProperty.INDEXING_SEARCH_LIST_SIZE) && indexingSearchListSize != null) { this.indexingSearchListSize = indexingSearchListSize; - this.jsonSerializable.set(Constants.Properties.VECTOR_INDEXING_SEARCH_LIST_SIZE, this.indexingSearchListSize, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.jsonSerializable.set(Constants.Properties.VECTOR_INDEXING_SEARCH_LIST_SIZE, this.indexingSearchListSize); } else { this.indexingSearchListSize = null; } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/ExcludedPath.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/ExcludedPath.java index 35eecef3603f..f386c0ee62bc 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/ExcludedPath.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/ExcludedPath.java @@ -3,7 +3,6 @@ package com.azure.cosmos.models; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.JsonSerializable; import com.fasterxml.jackson.databind.node.ObjectNode; @@ -53,8 +52,8 @@ public String getPath() { public ExcludedPath setPath(String path) { this.jsonSerializable.set( Constants.Properties.PATH, - path, - CosmosItemSerializer.DEFAULT_SERIALIZER); + path + ); return this; } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/IncludedPath.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/IncludedPath.java index b32db49c5b7c..9f6c155ab2bf 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/IncludedPath.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/IncludedPath.java @@ -3,7 +3,6 @@ package com.azure.cosmos.models; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.HashIndex; import com.azure.cosmos.implementation.Index; @@ -64,8 +63,8 @@ public String getPath() { public IncludedPath setPath(String path) { this.jsonSerializable.set( Constants.Properties.PATH, - path, - CosmosItemSerializer.DEFAULT_SERIALIZER); + path + ); return this; } @@ -137,8 +136,8 @@ void populatePropertyBag() { this.jsonSerializable.set( Constants.Properties.INDEXES, - this.indexes, - CosmosItemSerializer.DEFAULT_SERIALIZER); + this.indexes + ); } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/IndexingPolicy.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/IndexingPolicy.java index 16be0368736f..bd8b853053f0 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/IndexingPolicy.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/IndexingPolicy.java @@ -3,7 +3,6 @@ package com.azure.cosmos.models; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.Index; import com.azure.cosmos.implementation.JsonSerializable; @@ -112,7 +111,7 @@ public Boolean isAutomatic() { * @return the Indexing Policy. */ public IndexingPolicy setAutomatic(boolean automatic) { - this.jsonSerializable.set(Constants.Properties.AUTOMATIC, automatic, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.jsonSerializable.set(Constants.Properties.AUTOMATIC, automatic); return this; } @@ -139,7 +138,7 @@ public IndexingMode getIndexingMode() { * @return the Indexing Policy. */ public IndexingPolicy setIndexingMode(IndexingMode indexingMode) { - this.jsonSerializable.set(Constants.Properties.INDEXING_MODE, indexingMode.toString(), CosmosItemSerializer.DEFAULT_SERIALIZER); + this.jsonSerializable.set(Constants.Properties.INDEXING_MODE, indexingMode.toString()); return this; } @@ -233,7 +232,7 @@ public List> getCompositeIndexes() { */ public IndexingPolicy setCompositeIndexes(List> compositeIndexes) { this.compositeIndexes = compositeIndexes; - this.jsonSerializable.set(Constants.Properties.COMPOSITE_INDEXES, this.compositeIndexes, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.jsonSerializable.set(Constants.Properties.COMPOSITE_INDEXES, this.compositeIndexes); return this; } @@ -264,8 +263,8 @@ public IndexingPolicy setSpatialIndexes(List spatialIndexes) { this.spatialIndexes = spatialIndexes; this.jsonSerializable.set( Constants.Properties.SPATIAL_INDEXES, - this.spatialIndexes, - CosmosItemSerializer.DEFAULT_SERIALIZER); + this.spatialIndexes + ); return this; } @@ -309,7 +308,7 @@ public List getVectorIndexes() { */ public IndexingPolicy setVectorIndexes(List vectorIndexes) { this.vectorIndexes = vectorIndexes; - this.jsonSerializable.set(Constants.Properties.VECTOR_INDEXES,this.vectorIndexes, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.jsonSerializable.set(Constants.Properties.VECTOR_INDEXES,this.vectorIndexes); return this; } @@ -340,7 +339,7 @@ public List getCosmosFullTextIndexes() { @Beta(value = Beta.SinceVersion.V4_65_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public IndexingPolicy setCosmosFullTextIndexes(List cosmosFullTextIndexes) { this.cosmosFullTextIndexes = cosmosFullTextIndexes; - this.jsonSerializable.set(Constants.Properties.FULL_TEXT_INDEXES, cosmosFullTextIndexes, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.jsonSerializable.set(Constants.Properties.FULL_TEXT_INDEXES, cosmosFullTextIndexes); return this; } @@ -359,8 +358,8 @@ void populatePropertyBag() { } this.jsonSerializable.set( Constants.Properties.INCLUDED_PATHS, - this.includedPaths, - CosmosItemSerializer.DEFAULT_SERIALIZER); + this.includedPaths + ); } if (this.excludedPaths != null) { @@ -369,8 +368,8 @@ void populatePropertyBag() { } this.jsonSerializable.set( Constants.Properties.EXCLUDED_PATHS, - this.excludedPaths, - CosmosItemSerializer.DEFAULT_SERIALIZER); + this.excludedPaths + ); } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/ModelBridgeInternal.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/ModelBridgeInternal.java index 4c8f4aaf7cd5..03e3c15c45bf 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/ModelBridgeInternal.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/ModelBridgeInternal.java @@ -12,6 +12,7 @@ import com.azure.cosmos.implementation.CosmosResourceType; import com.azure.cosmos.implementation.Database; import com.azure.cosmos.implementation.DatabaseAccount; +import com.azure.cosmos.implementation.DefaultCosmosItemSerializer; import com.azure.cosmos.implementation.DocumentCollection; import com.azure.cosmos.implementation.HttpConstants; import com.azure.cosmos.implementation.Index; @@ -402,7 +403,12 @@ public static CosmosChangeFeedRequestOptions getEffectiveChangeFeedRequestOption @Warning(value = INTERNAL_USE_ONLY_WARNING) public static ByteBuffer serializeJsonToByteBuffer(SqlQuerySpec sqlQuerySpec) { sqlQuerySpec.populatePropertyBag(); - return sqlQuerySpec.getJsonSerializable().serializeJsonToByteBuffer(CosmosItemSerializer.DEFAULT_SERIALIZER, null, false); + return sqlQuerySpec + .getJsonSerializable() + .serializeJsonToByteBuffer( + DefaultCosmosItemSerializer.INTERNAL_DEFAULT_SERIALIZER, + null, + false); } @Warning(value = INTERNAL_USE_ONLY_WARNING) diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/PartitionKeyDefinition.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/PartitionKeyDefinition.java index 29107f46e3a9..50457b214b98 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/PartitionKeyDefinition.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/PartitionKeyDefinition.java @@ -3,7 +3,6 @@ package com.azure.cosmos.models; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.JsonSerializable; import com.azure.cosmos.implementation.Strings; @@ -182,21 +181,21 @@ void populatePropertyBag() { if (this.kind != null) { this.jsonSerializable.set( Constants.Properties.PARTITION_KIND, - kind.toString(), - CosmosItemSerializer.DEFAULT_SERIALIZER); + kind.toString() + ); } if (this.paths != null) { this.jsonSerializable.set( Constants.Properties.PARTITION_KEY_PATHS, - paths, - CosmosItemSerializer.DEFAULT_SERIALIZER); + paths + ); } if (this.versionOptional != null && versionOptional.isPresent()) { this.jsonSerializable.set( Constants.Properties.PARTITION_KEY_DEFINITION_VERSION, - versionOptional.get().toString(), - CosmosItemSerializer.DEFAULT_SERIALIZER); + versionOptional.get().toString() + ); } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/SpatialSpec.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/SpatialSpec.java index ffeebb9c908c..ec71188331f5 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/SpatialSpec.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/SpatialSpec.java @@ -3,7 +3,6 @@ package com.azure.cosmos.models; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.JsonSerializable; import com.fasterxml.jackson.databind.node.ObjectNode; @@ -64,8 +63,8 @@ public String getPath() { public SpatialSpec setPath(String path) { this.jsonSerializable.set( Constants.Properties.PATH, - path, - CosmosItemSerializer.DEFAULT_SERIALIZER); + path + ); return this; } @@ -100,8 +99,8 @@ public SpatialSpec setSpatialTypes(List spatialTypes) { } this.jsonSerializable.set( Constants.Properties.TYPES, - spatialTypeNames, - CosmosItemSerializer.DEFAULT_SERIALIZER); + spatialTypeNames + ); return this; } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/SqlParameter.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/SqlParameter.java index be8d8977054d..8ba3aa6e1c74 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/SqlParameter.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/SqlParameter.java @@ -3,7 +3,6 @@ package com.azure.cosmos.models; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.JsonSerializable; import com.fasterxml.jackson.databind.node.ObjectNode; @@ -62,8 +61,8 @@ public String getName() { public SqlParameter setName(String name) { this.jsonSerializable.set( "name", - name, - CosmosItemSerializer.DEFAULT_SERIALIZER); + name + ); return this; } @@ -87,8 +86,8 @@ public T getValue(Class classType) { public SqlParameter setValue(Object value) { this.jsonSerializable.set( "value", - value, - CosmosItemSerializer.DEFAULT_SERIALIZER); + value + ); return this; } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/SqlQuerySpec.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/SqlQuerySpec.java index 18460dbe35f3..9cec02f3237b 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/SqlQuerySpec.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/SqlQuerySpec.java @@ -3,7 +3,6 @@ package com.azure.cosmos.models; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.JsonSerializable; import com.fasterxml.jackson.databind.node.ObjectNode; @@ -91,7 +90,7 @@ public String getQueryText() { * @return the SqlQuerySpec. */ public SqlQuerySpec setQueryText(String queryText) { - this.jsonSerializable.set("query", queryText, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.jsonSerializable.set("query", queryText); return this; } @@ -129,7 +128,7 @@ void populatePropertyBag() { boolean defaultParameters = (this.parameters != null && this.parameters.size() != 0); if (defaultParameters) { - this.jsonSerializable.set("parameters", this.parameters, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.jsonSerializable.set("parameters", this.parameters); } else { this.jsonSerializable.remove("parameters"); } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/UniqueKey.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/UniqueKey.java index 8bde1a57ab9d..1b4b1cd68428 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/UniqueKey.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/UniqueKey.java @@ -2,7 +2,6 @@ // Licensed under the MIT License. package com.azure.cosmos.models; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.JsonSerializable; import com.fasterxml.jackson.databind.node.ObjectNode; @@ -93,7 +92,7 @@ public UniqueKey setPaths(List paths) { void populatePropertyBag() { this.jsonSerializable.populatePropertyBag(); if (paths != null) { - this.jsonSerializable.set(Constants.Properties.PATHS, paths, CosmosItemSerializer.DEFAULT_SERIALIZER); + this.jsonSerializable.set(Constants.Properties.PATHS, paths); } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/UniqueKeyPolicy.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/UniqueKeyPolicy.java index c8d266c4e8e6..b51dbea8dd4a 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/UniqueKeyPolicy.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/UniqueKeyPolicy.java @@ -2,7 +2,6 @@ // Licensed under the MIT License. package com.azure.cosmos.models; -import com.azure.cosmos.CosmosItemSerializer; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.JsonSerializable; import com.fasterxml.jackson.databind.node.ObjectNode; @@ -83,8 +82,8 @@ void populatePropertyBag() { } this.jsonSerializable.set( Constants.Properties.UNIQUE_KEYS, - uniqueKeys, - CosmosItemSerializer.DEFAULT_SERIALIZER); + uniqueKeys + ); } } diff --git a/sdk/cosmos/azure-cosmos/src/samples/java/com/azure/cosmos/ReadmeSamples.java b/sdk/cosmos/azure-cosmos/src/samples/java/com/azure/cosmos/ReadmeSamples.java index b23defd9dbcc..7767d1e28d6f 100644 --- a/sdk/cosmos/azure-cosmos/src/samples/java/com/azure/cosmos/ReadmeSamples.java +++ b/sdk/cosmos/azure-cosmos/src/samples/java/com/azure/cosmos/ReadmeSamples.java @@ -410,6 +410,7 @@ public void databaseCreateContainerPartitionKeySample() { public void databaseCreateContainerIfNotExistsSample() { String containerId = "passengers"; PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); + partitionKeyDefinition.setPaths(Collections.singletonList("/id")); // BEGIN: com.azure.cosmos.CosmosDatabase.createContainerIfNotExists CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerId, partitionKeyDefinition); @@ -421,6 +422,7 @@ public void databaseCreateContainerIfNotExistsSample() { public void databaseCreateContainerIfNotExistsPropsSample() { String containerId = "passengers"; PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); + partitionKeyDefinition.setPaths(Collections.singletonList("/id")); int autoScaleMaxThroughput = 1000; // BEGIN: com.azure.cosmos.CosmosDatabase.createContainerIfNotExistsProps diff --git a/sdk/cosmos/faq/README.md b/sdk/cosmos/faq/README.md index 093f091594e9..e32cd5d4ac96 100644 --- a/sdk/cosmos/faq/README.md +++ b/sdk/cosmos/faq/README.md @@ -9,4 +9,4 @@ - ``CollectionPoolExhausted`` this is a SDK side error indicating that the SDK's connection pool is saturated. Consider to retry later, increase the connection pool size or use a semaphore to throttle your workload. -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcosmos%2Ffaq%2FREADME.png) + diff --git a/sdk/cosmosdbforpostgresql/azure-resourcemanager-cosmosdbforpostgresql/README.md b/sdk/cosmosdbforpostgresql/azure-resourcemanager-cosmosdbforpostgresql/README.md index 61a8e4b99f62..903e01f48651 100644 --- a/sdk/cosmosdbforpostgresql/azure-resourcemanager-cosmosdbforpostgresql/README.md +++ b/sdk/cosmosdbforpostgresql/azure-resourcemanager-cosmosdbforpostgresql/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-cosmosdbforpostgresql - 1.1.0-beta.2 + 1.1.0-beta.3 ``` [//]: # ({x-version-update-end}) @@ -126,4 +126,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcosmosdbforpostgresql%2Fazure-resourcemanager-cosmosdbforpostgresql%2FREADME.png) + diff --git a/sdk/cosmosdbforpostgresql/azure-resourcemanager-cosmosdbforpostgresql/pom.xml b/sdk/cosmosdbforpostgresql/azure-resourcemanager-cosmosdbforpostgresql/pom.xml index 109cc95226e9..eab64e005563 100644 --- a/sdk/cosmosdbforpostgresql/azure-resourcemanager-cosmosdbforpostgresql/pom.xml +++ b/sdk/cosmosdbforpostgresql/azure-resourcemanager-cosmosdbforpostgresql/pom.xml @@ -52,23 +52,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test @@ -92,7 +92,7 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/costmanagement/azure-resourcemanager-costmanagement/README.md b/sdk/costmanagement/azure-resourcemanager-costmanagement/README.md index bc11909dedb1..1f893603120d 100644 --- a/sdk/costmanagement/azure-resourcemanager-costmanagement/README.md +++ b/sdk/costmanagement/azure-resourcemanager-costmanagement/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-costmanagement - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcostmanagement%2Fazure-resourcemanager-costmanagement%2FREADME.png) + diff --git a/sdk/costmanagement/azure-resourcemanager-costmanagement/pom.xml b/sdk/costmanagement/azure-resourcemanager-costmanagement/pom.xml index 92db4a038d17..da48ed63167d 100644 --- a/sdk/costmanagement/azure-resourcemanager-costmanagement/pom.xml +++ b/sdk/costmanagement/azure-resourcemanager-costmanagement/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/customerinsights/azure-resourcemanager-customerinsights/README.md b/sdk/customerinsights/azure-resourcemanager-customerinsights/README.md index 03cbd03859be..5773e62efb88 100644 --- a/sdk/customerinsights/azure-resourcemanager-customerinsights/README.md +++ b/sdk/customerinsights/azure-resourcemanager-customerinsights/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-customerinsights - 1.0.0-beta.3 + 1.0.0-beta.4 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcustomerinsights%2Fazure-resourcemanager-customerinsights%2FREADME.png) + diff --git a/sdk/customerinsights/azure-resourcemanager-customerinsights/pom.xml b/sdk/customerinsights/azure-resourcemanager-customerinsights/pom.xml index eef4e47141d9..0b1ffade16a9 100644 --- a/sdk/customerinsights/azure-resourcemanager-customerinsights/pom.xml +++ b/sdk/customerinsights/azure-resourcemanager-customerinsights/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/dashboard/azure-resourcemanager-dashboard/README.md b/sdk/dashboard/azure-resourcemanager-dashboard/README.md index 1d8466acfce0..a9622ffc0bb4 100644 --- a/sdk/dashboard/azure-resourcemanager-dashboard/README.md +++ b/sdk/dashboard/azure-resourcemanager-dashboard/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-dashboard - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -109,4 +109,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fdashboard%2Fazure-resourcemanager-dashboard%2FREADME.png) + diff --git a/sdk/dashboard/azure-resourcemanager-dashboard/pom.xml b/sdk/dashboard/azure-resourcemanager-dashboard/pom.xml index 0c7483b3b1cd..7d25909884d3 100644 --- a/sdk/dashboard/azure-resourcemanager-dashboard/pom.xml +++ b/sdk/dashboard/azure-resourcemanager-dashboard/pom.xml @@ -51,29 +51,29 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/CHANGELOG.md b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/CHANGELOG.md new file mode 100644 index 000000000000..fab6be8f2d2b --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/CHANGELOG.md @@ -0,0 +1,18 @@ +# Release History + +## 1.0.0-beta.2 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + +## 1.0.0-beta.1 (2025-02-28) + +- Azure Resource Manager Database Watcher client library for Java. This package contains Microsoft Azure SDK for Database Watcher Management SDK. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). +### Features Added + +- Initial release for the azure-resourcemanager-databasewatcher Java SDK. diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/README.md b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/README.md new file mode 100644 index 000000000000..426d7e5275ac --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/README.md @@ -0,0 +1,102 @@ +# Azure Resource Manager Database Watcher client library for Java + +Azure Resource Manager Database Watcher client library for Java. + +This package contains Microsoft Azure SDK for Database Watcher Management SDK. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). + +## We'd love to hear your feedback + +We're always working on improving our products and the way we communicate with our users. So we'd love to learn what's working and how we can do better. + +If you haven't already, please take a few minutes to [complete this short survey][survey] we have put together. + +Thank you in advance for your collaboration. We really appreciate your time! + +## Documentation + +Various documentation is available to help you get started + +- [API reference documentation][docs] + +## Getting started + +### Prerequisites + +- [Java Development Kit (JDK)][jdk] with version 8 or above +- [Azure Subscription][azure_subscription] + +### Adding the package to your product + +[//]: # ({x-version-update-start;com.azure.resourcemanager:azure-resourcemanager-databasewatcher;current}) +```xml + + com.azure.resourcemanager + azure-resourcemanager-databasewatcher + 1.0.0-beta.2 + +``` +[//]: # ({x-version-update-end}) + +### Include the recommended packages + +Azure Management Libraries require a `TokenCredential` implementation for authentication and an `HttpClient` implementation for HTTP client. + +[Azure Identity][azure_identity] and [Azure Core Netty HTTP][azure_core_http_netty] packages provide the default implementation. + +### Authentication + +Microsoft Entra ID token authentication relies on the [credential class][azure_identity_credentials] from [Azure Identity][azure_identity] package. + +Azure subscription ID can be configured via `AZURE_SUBSCRIPTION_ID` environment variable. + +Assuming the use of the `DefaultAzureCredential` credential class, the client can be authenticated using the following code: + +```java +AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); +TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); +DatabaseWatcherManager manager = DatabaseWatcherManager + .authenticate(credential, profile); +``` + +The sample code assumes global Azure. Please change the `AzureCloud.AZURE_PUBLIC_CLOUD` variable if otherwise. + +See [Authentication][authenticate] for more options. + +## Key concepts + +See [API design][design] for general introduction on design and key concepts on Azure Management Libraries. + +## Examples + +[Code snippets and samples](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/databasewatcher/azure-resourcemanager-databasewatcher/SAMPLE.md) + + +## Troubleshooting + +## Next steps + +## Contributing + +For details on contributing to this repository, see the [contributing guide][cg]. + +This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit . + +When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repositories using our CLA. + +This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For more information see the [Code of Conduct FAQ][coc_faq] or contact with any additional questions or comments. + + +[survey]: https://microsoft.qualtrics.com/jfe/form/SV_ehN0lIk2FKEBkwd?Q_CHL=DOCS +[docs]: https://azure.github.io/azure-sdk-for-java/ +[jdk]: https://learn.microsoft.com/azure/developer/java/fundamentals/ +[azure_subscription]: https://azure.microsoft.com/free/ +[azure_identity]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/identity/azure-identity +[azure_identity_credentials]: https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/identity/azure-identity#credentials +[azure_core_http_netty]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/core/azure-core-http-netty +[authenticate]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/resourcemanager/docs/AUTH.md +[design]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/resourcemanager/docs/DESIGN.md +[cg]: https://github.com/Azure/azure-sdk-for-java/blob/main/CONTRIBUTING.md +[coc]: https://opensource.microsoft.com/codeofconduct/ +[coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/SAMPLE.md b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/SAMPLE.md new file mode 100644 index 000000000000..a950be32e816 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/SAMPLE.md @@ -0,0 +1,702 @@ +# Code snippets and samples + + +## AlertRuleResources + +- [CreateOrUpdate](#alertruleresources_createorupdate) +- [Delete](#alertruleresources_delete) +- [Get](#alertruleresources_get) +- [ListByParent](#alertruleresources_listbyparent) + +## HealthValidations + +- [Get](#healthvalidations_get) +- [ListByParent](#healthvalidations_listbyparent) +- [StartValidation](#healthvalidations_startvalidation) + +## Operations + +- [List](#operations_list) + +## SharedPrivateLinkResources + +- [Create](#sharedprivatelinkresources_create) +- [Delete](#sharedprivatelinkresources_delete) +- [Get](#sharedprivatelinkresources_get) +- [ListByWatcher](#sharedprivatelinkresources_listbywatcher) + +## Targets + +- [CreateOrUpdate](#targets_createorupdate) +- [Delete](#targets_delete) +- [Get](#targets_get) +- [ListByWatcher](#targets_listbywatcher) + +## Watchers + +- [CreateOrUpdate](#watchers_createorupdate) +- [Delete](#watchers_delete) +- [GetByResourceGroup](#watchers_getbyresourcegroup) +- [List](#watchers_list) +- [ListByResourceGroup](#watchers_listbyresourcegroup) +- [Start](#watchers_start) +- [Stop](#watchers_stop) +- [Update](#watchers_update) +### AlertRuleResources_CreateOrUpdate + +```java +import com.azure.resourcemanager.databasewatcher.models.AlertRuleCreationProperties; +import com.azure.resourcemanager.databasewatcher.models.AlertRuleResourceProperties; +import java.time.OffsetDateTime; + +/** + * Samples for AlertRuleResources CreateOrUpdate. + */ +public final class AlertRuleResourcesCreateOrUpdateSamples { + /* + * x-ms-original-file: 2025-01-02/AlertRuleResources_CreateOrUpdate_MaximumSet_Gen.json + */ + /** + * Sample code: AlertRuleResources_CreateOrUpdate_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void alertRuleResourcesCreateOrUpdateMaximumSet( + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.alertRuleResources() + .define("testAlert") + .withExistingWatcher("rgWatcher", "testWatcher") + .withProperties(new AlertRuleResourceProperties().withAlertRuleResourceId( + "/subscriptions/469DD77C-C8DB-47B7-B9E1-72D29F8C878Be/resourceGroups/rgWatcher/providers/microsoft.insights/scheduledqueryrules/alerts-demo") + .withCreatedWithProperties(AlertRuleCreationProperties.CREATED_WITH_ACTION_GROUP) + .withCreationTime(OffsetDateTime.parse("2024-07-25T15:38:47.798Z")) + .withAlertRuleTemplateId("someTemplateId") + .withAlertRuleTemplateVersion("1.0")) + .create(); + } +} +``` + +### AlertRuleResources_Delete + +```java +/** + * Samples for AlertRuleResources Delete. + */ +public final class AlertRuleResourcesDeleteSamples { + /* + * x-ms-original-file: 2025-01-02/AlertRuleResources_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: AlertRuleResources_Delete_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void + alertRuleResourcesDeleteMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.alertRuleResources() + .deleteWithResponse("rgWatcher", "testWatcher", "testAlert", com.azure.core.util.Context.NONE); + } +} +``` + +### AlertRuleResources_Get + +```java +/** + * Samples for AlertRuleResources Get. + */ +public final class AlertRuleResourcesGetSamples { + /* + * x-ms-original-file: 2025-01-02/AlertRuleResources_Get_MaximumSet_Gen.json + */ + /** + * Sample code: AlertRuleResources_Get_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void + alertRuleResourcesGetMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.alertRuleResources() + .getWithResponse("rgWatcher", "testWatcher", "testAlert", com.azure.core.util.Context.NONE); + } +} +``` + +### AlertRuleResources_ListByParent + +```java +/** + * Samples for AlertRuleResources ListByParent. + */ +public final class AlertRuleResourcesListByParentSamples { + /* + * x-ms-original-file: 2025-01-02/AlertRuleResources_ListByParent_MaximumSet_Gen.json + */ + /** + * Sample code: AlertRuleResources_ListByParent_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void alertRuleResourcesListByParentMaximumSet( + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.alertRuleResources().listByParent("rgWatcher", "testWatcher", com.azure.core.util.Context.NONE); + } +} +``` + +### HealthValidations_Get + +```java +/** + * Samples for HealthValidations Get. + */ +public final class HealthValidationsGetSamples { + /* + * x-ms-original-file: 2025-01-02/HealthValidations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: HealthValidations_Get_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void + healthValidationsGetMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.healthValidations() + .getWithResponse("rgWatcher", "testWatcher", "testHealthValidation", com.azure.core.util.Context.NONE); + } +} +``` + +### HealthValidations_ListByParent + +```java +/** + * Samples for HealthValidations ListByParent. + */ +public final class HealthValidationsListByParentSamples { + /* + * x-ms-original-file: 2025-01-02/HealthValidations_ListByParent_MaximumSet_Gen.json + */ + /** + * Sample code: HealthValidations_ListByParent_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void healthValidationsListByParentMaximumSet( + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.healthValidations().listByParent("rgWatcher", "testWatcher", com.azure.core.util.Context.NONE); + } +} +``` + +### HealthValidations_StartValidation + +```java +/** + * Samples for HealthValidations StartValidation. + */ +public final class HealthValidationsStartValidationSamples { + /* + * x-ms-original-file: 2025-01-02/HealthValidations_StartValidation_MaximumSet_Gen.json + */ + /** + * Sample code: HealthValidations_StartValidation_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void healthValidationsStartValidationMaximumSet( + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.healthValidations() + .startValidation("rgWatcher", "testWatcher", "testHealthValidation", com.azure.core.util.Context.NONE); + } +} +``` + +### Operations_List + +```java +/** + * Samples for Operations List. + */ +public final class OperationsListSamples { + /* + * x-ms-original-file: 2025-01-02/Operations_List_MinimumSet_Gen.json + */ + /** + * Sample code: Operations_List_MinimumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void + operationsListMinimumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.operations().list(com.azure.core.util.Context.NONE); + } + + /* + * x-ms-original-file: 2025-01-02/Operations_List_MaximumSet_Gen.json + */ + /** + * Sample code: Operations_List_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void + operationsListMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.operations().list(com.azure.core.util.Context.NONE); + } +} +``` + +### SharedPrivateLinkResources_Create + +```java +import com.azure.resourcemanager.databasewatcher.models.SharedPrivateLinkResourceProperties; + +/** + * Samples for SharedPrivateLinkResources Create. + */ +public final class SharedPrivateLinkResourcesCreateSamples { + /* + * x-ms-original-file: 2025-01-02/SharedPrivateLinkResources_Create_MaximumSet_Gen.json + */ + /** + * Sample code: SharedPrivateLinkResources_Create_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void sharedPrivateLinkResourcesCreateMaximumSet( + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.sharedPrivateLinkResources() + .define("monitoringh22eed") + .withExistingWatcher("apiTest-ddat4p", "databasemo3ej9ih") + .withProperties(new SharedPrivateLinkResourceProperties().withPrivateLinkResourceId( + "/subscriptions/49e0fbd3-75e8-44e7-96fd-5b64d9ad818d/resourceGroups/apiTest-ddat4p/providers/Microsoft.KeyVault/vaults/kvmo3ej9ih") + .withGroupId("vault") + .withRequestMessage("request message") + .withDnsZone("ec3ae9d410ba")) + .create(); + } +} +``` + +### SharedPrivateLinkResources_Delete + +```java +/** + * Samples for SharedPrivateLinkResources Delete. + */ +public final class SharedPrivateLinkResourcesDeleteSamples { + /* + * x-ms-original-file: 2025-01-02/SharedPrivateLinkResources_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: SharedPrivateLinkResources_Delete_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void sharedPrivateLinkResourcesDeleteMaximumSet( + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.sharedPrivateLinkResources() + .delete("apiTest-ddat4p", "databasemo3ej9ih", "monitoringh22eed", com.azure.core.util.Context.NONE); + } +} +``` + +### SharedPrivateLinkResources_Get + +```java +/** + * Samples for SharedPrivateLinkResources Get. + */ +public final class SharedPrivateLinkResourcesGetSamples { + /* + * x-ms-original-file: 2025-01-02/SharedPrivateLinkResources_Get_MaximumSet_Gen.json + */ + /** + * Sample code: SharedPrivateLinkResources_Get_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void sharedPrivateLinkResourcesGetMaximumSet( + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.sharedPrivateLinkResources() + .getWithResponse("apiTest-ddat4p", "databasemo3ej9ih", "monitoringh22eed", + com.azure.core.util.Context.NONE); + } +} +``` + +### SharedPrivateLinkResources_ListByWatcher + +```java +/** + * Samples for SharedPrivateLinkResources ListByWatcher. + */ +public final class SharedPrivateLinkResourcesListByWatcherSamples { + /* + * x-ms-original-file: 2025-01-02/SharedPrivateLinkResources_ListByWatcher_MaximumSet_Gen.json + */ + /** + * Sample code: SharedPrivateLinkResources_ListByWatcher_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void sharedPrivateLinkResourcesListByWatcherMaximumSet( + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.sharedPrivateLinkResources() + .listByWatcher("apiTest-ddat4p", "databasemo3ej9ih", com.azure.core.util.Context.NONE); + } +} +``` + +### Targets_CreateOrUpdate + +```java +import com.azure.resourcemanager.databasewatcher.models.SqlDbSingleDatabaseTargetProperties; +import com.azure.resourcemanager.databasewatcher.models.TargetAuthenticationType; + +/** + * Samples for Targets CreateOrUpdate. + */ +public final class TargetsCreateOrUpdateSamples { + /* + * x-ms-original-file: 2025-01-02/Targets_CreateOrUpdate_MaximumSet_Gen.json + */ + /** + * Sample code: Targets_CreateOrUpdate_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void + targetsCreateOrUpdateMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.targets() + .define("monitoringh22eed") + .withExistingWatcher("apiTest-ddat4p", "databasemo3ej9ih") + .withProperties(new SqlDbSingleDatabaseTargetProperties() + .withTargetAuthenticationType(TargetAuthenticationType.AAD) + .withConnectionServerName("sqlServero1ihe2") + .withSqlDbResourceId( + "/subscriptions/49e0fbd3-75e8-44e7-96fd-5b64d9ad818d/resourceGroups/apiTest-ddat4p/providers/Microsoft.Sql/servers/m1/databases/m2")) + .create(); + } +} +``` + +### Targets_Delete + +```java +/** + * Samples for Targets Delete. + */ +public final class TargetsDeleteSamples { + /* + * x-ms-original-file: 2025-01-02/Targets_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: Targets_Delete_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void + targetsDeleteMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.targets() + .deleteWithResponse("apiTest-ddat4p", "databasemo3ej9ih", "monitoringh22eed", + com.azure.core.util.Context.NONE); + } +} +``` + +### Targets_Get + +```java +/** + * Samples for Targets Get. + */ +public final class TargetsGetSamples { + /* + * x-ms-original-file: 2025-01-02/Targets_Get_MaximumSet_Gen.json + */ + /** + * Sample code: Targets_Get_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void targetsGetMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.targets() + .getWithResponse("apiTest-ddat4p", "databasemo3ej9ih", "monitoringh22eed", + com.azure.core.util.Context.NONE); + } +} +``` + +### Targets_ListByWatcher + +```java +/** + * Samples for Targets ListByWatcher. + */ +public final class TargetsListByWatcherSamples { + /* + * x-ms-original-file: 2025-01-02/Targets_ListByWatcher_MaximumSet_Gen.json + */ + /** + * Sample code: Targets_ListByWatcher_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void + targetsListByWatcherMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.targets().listByWatcher("apiTest-ddat4p", "databasemo3ej9ih", com.azure.core.util.Context.NONE); + } +} +``` + +### Watchers_CreateOrUpdate + +```java +import com.azure.resourcemanager.databasewatcher.models.Datastore; +import com.azure.resourcemanager.databasewatcher.models.KustoOfferingType; +import com.azure.resourcemanager.databasewatcher.models.ManagedServiceIdentityType; +import com.azure.resourcemanager.databasewatcher.models.ManagedServiceIdentityV4; +import com.azure.resourcemanager.databasewatcher.models.WatcherProperties; +import java.util.HashMap; +import java.util.Map; + +/** + * Samples for Watchers CreateOrUpdate. + */ +public final class WatchersCreateOrUpdateSamples { + /* + * x-ms-original-file: 2025-01-02/Watchers_CreateOrUpdate_MaximumSet_Gen.json + */ + /** + * Sample code: Watchers_CreateOrUpdate_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void + watchersCreateOrUpdateMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.watchers() + .define("testWatcher") + .withRegion("eastus2") + .withExistingResourceGroup("rgWatcher") + .withTags(mapOf()) + .withProperties(new WatcherProperties().withDatastore(new Datastore().withAdxClusterResourceId( + "/subscriptions/49e0fbd3-75e8-44e7-96fd-5b64d9ad818d/resourceGroups/apiTest/providers/Microsoft.Kusto/clusters/apiTestKusto") + .withKustoClusterDisplayName("kustoUri-adx") + .withKustoClusterUri("https://kustouri-adx.eastus.kusto.windows.net") + .withKustoDataIngestionUri("https://ingest-kustouri-adx.eastus.kusto.windows.net") + .withKustoDatabaseName("kustoDatabaseName1") + .withKustoManagementUrl("https://portal.azure.com/") + .withKustoOfferingType(KustoOfferingType.ADX)) + .withDefaultAlertRuleIdentityResourceId( + "/subscriptions/469DD77C-C8DB-47B7-B9E1-72D29F8C878B/resourceGroups/rgWatcher/providers/Microsoft.ManagedIdentity/userAssignedIdentities/3pmtest")) + .withIdentity(new ManagedServiceIdentityV4().withType(ManagedServiceIdentityType.SYSTEM_ASSIGNED)) + .create(); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} +``` + +### Watchers_Delete + +```java +/** + * Samples for Watchers Delete. + */ +public final class WatchersDeleteSamples { + /* + * x-ms-original-file: 2025-01-02/Watchers_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: Watchers_Delete_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void + watchersDeleteMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.watchers().delete("rgWatcher", "testWatcher", com.azure.core.util.Context.NONE); + } +} +``` + +### Watchers_GetByResourceGroup + +```java +/** + * Samples for Watchers GetByResourceGroup. + */ +public final class WatchersGetByResourceGroupSamples { + /* + * x-ms-original-file: 2025-01-02/Watchers_Get_MaximumSet_Gen.json + */ + /** + * Sample code: Watchers_Get_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void watchersGetMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.watchers().getByResourceGroupWithResponse("rgWatcher", "myWatcher", com.azure.core.util.Context.NONE); + } +} +``` + +### Watchers_List + +```java +/** + * Samples for Watchers List. + */ +public final class WatchersListSamples { + /* + * x-ms-original-file: 2025-01-02/Watchers_ListBySubscription_MaximumSet_Gen.json + */ + /** + * Sample code: Watchers_ListBySubscription_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void + watchersListBySubscriptionMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.watchers().list(com.azure.core.util.Context.NONE); + } +} +``` + +### Watchers_ListByResourceGroup + +```java +/** + * Samples for Watchers ListByResourceGroup. + */ +public final class WatchersListByResourceGroupSamples { + /* + * x-ms-original-file: 2025-01-02/Watchers_ListByResourceGroup_MaximumSet_Gen.json + */ + /** + * Sample code: Watchers_ListByResourceGroup_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void watchersListByResourceGroupMaximumSet( + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.watchers().listByResourceGroup("rgWatcher", com.azure.core.util.Context.NONE); + } +} +``` + +### Watchers_Start + +```java +/** + * Samples for Watchers Start. + */ +public final class WatchersStartSamples { + /* + * x-ms-original-file: 2025-01-02/Watchers_Start_MaximumSet_Gen.json + */ + /** + * Sample code: Watchers_Start_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void + watchersStartMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.watchers().start("rgWatcher", "testWatcher", com.azure.core.util.Context.NONE); + } +} +``` + +### Watchers_Stop + +```java +/** + * Samples for Watchers Stop. + */ +public final class WatchersStopSamples { + /* + * x-ms-original-file: 2025-01-02/Watchers_Stop_MaximumSet_Gen.json + */ + /** + * Sample code: Watchers_Stop_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void + watchersStopMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.watchers().stop("rgWatcher", "myWatcher", com.azure.core.util.Context.NONE); + } +} +``` + +### Watchers_Update + +```java +import com.azure.resourcemanager.databasewatcher.models.Datastore; +import com.azure.resourcemanager.databasewatcher.models.KustoOfferingType; +import com.azure.resourcemanager.databasewatcher.models.ManagedServiceIdentityType; +import com.azure.resourcemanager.databasewatcher.models.ManagedServiceIdentityV4; +import com.azure.resourcemanager.databasewatcher.models.Watcher; +import com.azure.resourcemanager.databasewatcher.models.WatcherUpdateProperties; +import java.util.HashMap; +import java.util.Map; + +/** + * Samples for Watchers Update. + */ +public final class WatchersUpdateSamples { + /* + * x-ms-original-file: 2025-01-02/Watchers_Update_MaximumSet_Gen.json + */ + /** + * Sample code: Watchers_Update_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void + watchersUpdateMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + Watcher resource = manager.watchers() + .getByResourceGroupWithResponse("rgWatcher", "testWatcher", com.azure.core.util.Context.NONE) + .getValue(); + resource.update() + .withTags(mapOf()) + .withIdentity(new ManagedServiceIdentityV4().withType(ManagedServiceIdentityType.SYSTEM_ASSIGNED)) + .withProperties(new WatcherUpdateProperties().withDatastore(new Datastore().withAdxClusterResourceId( + "/subscriptions/49e0fbd3-75e8-44e7-96fd-5b64d9ad818d/resourceGroups/apiTest/providers/Microsoft.Kusto/clusters/apiTestKusto") + .withKustoClusterDisplayName("kustoUri-adx") + .withKustoClusterUri("https://kustouri-adx.eastus.kusto.windows.net") + .withKustoDataIngestionUri("https://ingest-kustouri-adx.eastus.kusto.windows.net") + .withKustoDatabaseName("kustoDatabaseName1") + .withKustoManagementUrl("https://portal.azure.com/") + .withKustoOfferingType(KustoOfferingType.ADX)) + .withDefaultAlertRuleIdentityResourceId( + "/subscriptions/469DD77C-C8DB-47B7-B9E1-72D29F8C878B/resourceGroups/rgWatcher/providers/Microsoft.ManagedIdentity/userAssignedIdentities/newtest")) + .apply(); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} +``` + diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/pom.xml b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/pom.xml new file mode 100644 index 000000000000..96c502ef2e3a --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/pom.xml @@ -0,0 +1,74 @@ + + + 4.0.0 + + com.azure + azure-client-sdk-parent + 1.7.0 + ../../parents/azure-client-sdk-parent + + + com.azure.resourcemanager + azure-resourcemanager-databasewatcher + 1.0.0-beta.2 + jar + + Microsoft Azure SDK for Database Watcher Management + This package contains Microsoft Azure SDK for Database Watcher Management SDK. For documentation on how to use this package, please see https://aka.ms/azsdk/java/mgmt. + https://github.com/Azure/azure-sdk-for-java + + + + The MIT License (MIT) + http://opensource.org/licenses/MIT + repo + + + + + https://github.com/Azure/azure-sdk-for-java + scm:git:git@github.com:Azure/azure-sdk-for-java.git + scm:git:git@github.com:Azure/azure-sdk-for-java.git + HEAD + + + + microsoft + Microsoft + + + + UTF-8 + 0 + 0 + true + + + + com.azure + azure-core + 1.55.3 + + + com.azure + azure-core-management + 1.17.0 + + + com.azure + azure-core-test + 1.27.0-beta.8 + test + + + com.azure + azure-identity + 1.15.4 + test + + + diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/DatabaseWatcherManager.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/DatabaseWatcherManager.java new file mode 100644 index 000000000000..743a787c9f1d --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/DatabaseWatcherManager.java @@ -0,0 +1,362 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.HttpPipelinePosition; +import com.azure.core.http.policy.AddDatePolicy; +import com.azure.core.http.policy.AddHeadersFromContextPolicy; +import com.azure.core.http.policy.BearerTokenAuthenticationPolicy; +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.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.management.profile.AzureProfile; +import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.databasewatcher.fluent.DatabaseWatcherManagementClient; +import com.azure.resourcemanager.databasewatcher.implementation.AlertRuleResourcesImpl; +import com.azure.resourcemanager.databasewatcher.implementation.DatabaseWatcherManagementClientBuilder; +import com.azure.resourcemanager.databasewatcher.implementation.HealthValidationsImpl; +import com.azure.resourcemanager.databasewatcher.implementation.OperationsImpl; +import com.azure.resourcemanager.databasewatcher.implementation.SharedPrivateLinkResourcesImpl; +import com.azure.resourcemanager.databasewatcher.implementation.TargetsImpl; +import com.azure.resourcemanager.databasewatcher.implementation.WatchersImpl; +import com.azure.resourcemanager.databasewatcher.models.AlertRuleResources; +import com.azure.resourcemanager.databasewatcher.models.HealthValidations; +import com.azure.resourcemanager.databasewatcher.models.Operations; +import com.azure.resourcemanager.databasewatcher.models.SharedPrivateLinkResources; +import com.azure.resourcemanager.databasewatcher.models.Targets; +import com.azure.resourcemanager.databasewatcher.models.Watchers; +import java.time.Duration; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +/** + * Entry point to DatabaseWatcherManager. + */ +public final class DatabaseWatcherManager { + private Operations operations; + + private Watchers watchers; + + private AlertRuleResources alertRuleResources; + + private HealthValidations healthValidations; + + private Targets targets; + + private SharedPrivateLinkResources sharedPrivateLinkResources; + + private final DatabaseWatcherManagementClient clientObject; + + private DatabaseWatcherManager(HttpPipeline httpPipeline, AzureProfile profile, Duration defaultPollInterval) { + Objects.requireNonNull(httpPipeline, "'httpPipeline' cannot be null."); + Objects.requireNonNull(profile, "'profile' cannot be null."); + this.clientObject = new DatabaseWatcherManagementClientBuilder().pipeline(httpPipeline) + .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) + .subscriptionId(profile.getSubscriptionId()) + .defaultPollInterval(defaultPollInterval) + .buildClient(); + } + + /** + * Creates an instance of Database Watcher service API entry point. + * + * @param credential the credential to use. + * @param profile the Azure profile for client. + * @return the Database Watcher service API instance. + */ + public static DatabaseWatcherManager authenticate(TokenCredential credential, AzureProfile profile) { + Objects.requireNonNull(credential, "'credential' cannot be null."); + Objects.requireNonNull(profile, "'profile' cannot be null."); + return configure().authenticate(credential, profile); + } + + /** + * Creates an instance of Database Watcher service API entry point. + * + * @param httpPipeline the {@link HttpPipeline} configured with Azure authentication credential. + * @param profile the Azure profile for client. + * @return the Database Watcher service API instance. + */ + public static DatabaseWatcherManager authenticate(HttpPipeline httpPipeline, AzureProfile profile) { + Objects.requireNonNull(httpPipeline, "'httpPipeline' cannot be null."); + Objects.requireNonNull(profile, "'profile' cannot be null."); + return new DatabaseWatcherManager(httpPipeline, profile, null); + } + + /** + * Gets a Configurable instance that can be used to create DatabaseWatcherManager with optional configuration. + * + * @return the Configurable instance allowing configurations. + */ + public static Configurable configure() { + return new DatabaseWatcherManager.Configurable(); + } + + /** + * The Configurable allowing configurations to be set. + */ + public static final class Configurable { + private static final ClientLogger LOGGER = new ClientLogger(Configurable.class); + private static final String SDK_VERSION = "version"; + private static final Map PROPERTIES + = CoreUtils.getProperties("azure-resourcemanager-databasewatcher.properties"); + + private HttpClient httpClient; + private HttpLogOptions httpLogOptions; + private final List policies = new ArrayList<>(); + private final List scopes = new ArrayList<>(); + private RetryPolicy retryPolicy; + private RetryOptions retryOptions; + private Duration defaultPollInterval; + + private Configurable() { + } + + /** + * Sets the http client. + * + * @param httpClient the HTTP client. + * @return the configurable object itself. + */ + public Configurable withHttpClient(HttpClient httpClient) { + this.httpClient = Objects.requireNonNull(httpClient, "'httpClient' cannot be null."); + return this; + } + + /** + * Sets the logging options to the HTTP pipeline. + * + * @param httpLogOptions the HTTP log options. + * @return the configurable object itself. + */ + public Configurable withLogOptions(HttpLogOptions httpLogOptions) { + this.httpLogOptions = Objects.requireNonNull(httpLogOptions, "'httpLogOptions' cannot be null."); + return this; + } + + /** + * Adds the pipeline policy to the HTTP pipeline. + * + * @param policy the HTTP pipeline policy. + * @return the configurable object itself. + */ + public Configurable withPolicy(HttpPipelinePolicy policy) { + this.policies.add(Objects.requireNonNull(policy, "'policy' cannot be null.")); + return this; + } + + /** + * Adds the scope to permission sets. + * + * @param scope the scope. + * @return the configurable object itself. + */ + public Configurable withScope(String scope) { + this.scopes.add(Objects.requireNonNull(scope, "'scope' cannot be null.")); + return this; + } + + /** + * Sets the retry policy to the HTTP pipeline. + * + * @param retryPolicy the HTTP pipeline retry policy. + * @return the configurable object itself. + */ + public Configurable withRetryPolicy(RetryPolicy retryPolicy) { + this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null."); + return this; + } + + /** + * Sets the retry options for the HTTP pipeline retry policy. + *

        + * This setting has no effect, if retry policy is set via {@link #withRetryPolicy(RetryPolicy)}. + * + * @param retryOptions the retry options for the HTTP pipeline retry policy. + * @return the configurable object itself. + */ + public Configurable withRetryOptions(RetryOptions retryOptions) { + this.retryOptions = Objects.requireNonNull(retryOptions, "'retryOptions' cannot be null."); + return this; + } + + /** + * Sets the default poll interval, used when service does not provide "Retry-After" header. + * + * @param defaultPollInterval the default poll interval. + * @return the configurable object itself. + */ + public Configurable withDefaultPollInterval(Duration defaultPollInterval) { + this.defaultPollInterval + = Objects.requireNonNull(defaultPollInterval, "'defaultPollInterval' cannot be null."); + if (this.defaultPollInterval.isNegative()) { + throw LOGGER + .logExceptionAsError(new IllegalArgumentException("'defaultPollInterval' cannot be negative")); + } + return this; + } + + /** + * Creates an instance of Database Watcher service API entry point. + * + * @param credential the credential to use. + * @param profile the Azure profile for client. + * @return the Database Watcher service API instance. + */ + public DatabaseWatcherManager authenticate(TokenCredential credential, AzureProfile profile) { + Objects.requireNonNull(credential, "'credential' cannot be null."); + Objects.requireNonNull(profile, "'profile' cannot be null."); + + String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); + + StringBuilder userAgentBuilder = new StringBuilder(); + userAgentBuilder.append("azsdk-java") + .append("-") + .append("com.azure.resourcemanager.databasewatcher") + .append("/") + .append(clientVersion); + if (!Configuration.getGlobalConfiguration().get("AZURE_TELEMETRY_DISABLED", false)) { + userAgentBuilder.append(" (") + .append(Configuration.getGlobalConfiguration().get("java.version")) + .append("; ") + .append(Configuration.getGlobalConfiguration().get("os.name")) + .append("; ") + .append(Configuration.getGlobalConfiguration().get("os.version")) + .append("; auto-generated)"); + } else { + userAgentBuilder.append(" (auto-generated)"); + } + + if (scopes.isEmpty()) { + scopes.add(profile.getEnvironment().getManagementEndpoint() + "/.default"); + } + if (retryPolicy == null) { + if (retryOptions != null) { + retryPolicy = new RetryPolicy(retryOptions); + } else { + retryPolicy = new RetryPolicy("Retry-After", ChronoUnit.SECONDS); + } + } + List policies = new ArrayList<>(); + policies.add(new UserAgentPolicy(userAgentBuilder.toString())); + policies.add(new AddHeadersFromContextPolicy()); + policies.add(new RequestIdPolicy()); + policies.addAll(this.policies.stream() + .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) + .collect(Collectors.toList())); + HttpPolicyProviders.addBeforeRetryPolicies(policies); + policies.add(retryPolicy); + policies.add(new AddDatePolicy()); + policies.add(new BearerTokenAuthenticationPolicy(credential, scopes.toArray(new String[0]))); + policies.addAll(this.policies.stream() + .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) + .collect(Collectors.toList())); + HttpPolicyProviders.addAfterRetryPolicies(policies); + policies.add(new HttpLoggingPolicy(httpLogOptions)); + HttpPipeline httpPipeline = new HttpPipelineBuilder().httpClient(httpClient) + .policies(policies.toArray(new HttpPipelinePolicy[0])) + .build(); + return new DatabaseWatcherManager(httpPipeline, profile, defaultPollInterval); + } + } + + /** + * Gets the resource collection API of Operations. + * + * @return Resource collection API of Operations. + */ + public Operations operations() { + if (this.operations == null) { + this.operations = new OperationsImpl(clientObject.getOperations(), this); + } + return operations; + } + + /** + * Gets the resource collection API of Watchers. It manages Watcher. + * + * @return Resource collection API of Watchers. + */ + public Watchers watchers() { + if (this.watchers == null) { + this.watchers = new WatchersImpl(clientObject.getWatchers(), this); + } + return watchers; + } + + /** + * Gets the resource collection API of AlertRuleResources. It manages AlertRuleResource. + * + * @return Resource collection API of AlertRuleResources. + */ + public AlertRuleResources alertRuleResources() { + if (this.alertRuleResources == null) { + this.alertRuleResources = new AlertRuleResourcesImpl(clientObject.getAlertRuleResources(), this); + } + return alertRuleResources; + } + + /** + * Gets the resource collection API of HealthValidations. + * + * @return Resource collection API of HealthValidations. + */ + public HealthValidations healthValidations() { + if (this.healthValidations == null) { + this.healthValidations = new HealthValidationsImpl(clientObject.getHealthValidations(), this); + } + return healthValidations; + } + + /** + * Gets the resource collection API of Targets. It manages Target. + * + * @return Resource collection API of Targets. + */ + public Targets targets() { + if (this.targets == null) { + this.targets = new TargetsImpl(clientObject.getTargets(), this); + } + return targets; + } + + /** + * Gets the resource collection API of SharedPrivateLinkResources. It manages SharedPrivateLinkResource. + * + * @return Resource collection API of SharedPrivateLinkResources. + */ + public SharedPrivateLinkResources sharedPrivateLinkResources() { + if (this.sharedPrivateLinkResources == null) { + this.sharedPrivateLinkResources + = new SharedPrivateLinkResourcesImpl(clientObject.getSharedPrivateLinkResources(), this); + } + return sharedPrivateLinkResources; + } + + /** + * Gets wrapped service client DatabaseWatcherManagementClient providing direct access to the underlying + * auto-generated API implementation, based on Azure REST API. + * + * @return Wrapped service client DatabaseWatcherManagementClient. + */ + public DatabaseWatcherManagementClient serviceClient() { + return this.clientObject; + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/AlertRuleResourcesClient.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/AlertRuleResourcesClient.java new file mode 100644 index 000000000000..fb1d74b965c5 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/AlertRuleResourcesClient.java @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.resourcemanager.databasewatcher.fluent.models.AlertRuleResourceInner; + +/** + * An instance of this class provides access to all the operations defined in AlertRuleResourcesClient. + */ +public interface AlertRuleResourcesClient { + /** + * Get a AlertRuleResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param alertRuleResourceName The alert rule proxy resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AlertRuleResource along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceGroupName, String watcherName, + String alertRuleResourceName, Context context); + + /** + * Get a AlertRuleResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param alertRuleResourceName The alert rule proxy resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AlertRuleResource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + AlertRuleResourceInner get(String resourceGroupName, String watcherName, String alertRuleResourceName); + + /** + * Create a AlertRuleResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param alertRuleResourceName The alert rule proxy resource name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete proxy resource types can be created by aliasing this type using a specific property type along + * with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response createOrUpdateWithResponse(String resourceGroupName, String watcherName, + String alertRuleResourceName, AlertRuleResourceInner resource, Context context); + + /** + * Create a AlertRuleResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param alertRuleResourceName The alert rule proxy resource name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete proxy resource types can be created by aliasing this type using a specific property type. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + AlertRuleResourceInner createOrUpdate(String resourceGroupName, String watcherName, String alertRuleResourceName, + AlertRuleResourceInner resource); + + /** + * Delete a AlertRuleResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param alertRuleResourceName The alert rule proxy resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response deleteWithResponse(String resourceGroupName, String watcherName, String alertRuleResourceName, + Context context); + + /** + * Delete a AlertRuleResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param alertRuleResourceName The alert rule proxy resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void delete(String resourceGroupName, String watcherName, String alertRuleResourceName); + + /** + * List AlertRuleResource resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AlertRuleResource list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByParent(String resourceGroupName, String watcherName); + + /** + * List AlertRuleResource resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AlertRuleResource list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByParent(String resourceGroupName, String watcherName, Context context); +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/DatabaseWatcherManagementClient.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/DatabaseWatcherManagementClient.java new file mode 100644 index 000000000000..1464ae4e2970 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/DatabaseWatcherManagementClient.java @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.fluent; + +import com.azure.core.http.HttpPipeline; +import java.time.Duration; + +/** + * The interface for DatabaseWatcherManagementClient class. + */ +public interface DatabaseWatcherManagementClient { + /** + * Gets Service host. + * + * @return the endpoint value. + */ + String getEndpoint(); + + /** + * Gets Version parameter. + * + * @return the apiVersion value. + */ + String getApiVersion(); + + /** + * Gets The ID of the target subscription. The value must be an UUID. + * + * @return the subscriptionId value. + */ + String getSubscriptionId(); + + /** + * Gets The HTTP pipeline to send requests through. + * + * @return the httpPipeline value. + */ + HttpPipeline getHttpPipeline(); + + /** + * Gets The default poll interval for long-running operation. + * + * @return the defaultPollInterval value. + */ + Duration getDefaultPollInterval(); + + /** + * Gets the OperationsClient object to access its operations. + * + * @return the OperationsClient object. + */ + OperationsClient getOperations(); + + /** + * Gets the WatchersClient object to access its operations. + * + * @return the WatchersClient object. + */ + WatchersClient getWatchers(); + + /** + * Gets the AlertRuleResourcesClient object to access its operations. + * + * @return the AlertRuleResourcesClient object. + */ + AlertRuleResourcesClient getAlertRuleResources(); + + /** + * Gets the HealthValidationsClient object to access its operations. + * + * @return the HealthValidationsClient object. + */ + HealthValidationsClient getHealthValidations(); + + /** + * Gets the TargetsClient object to access its operations. + * + * @return the TargetsClient object. + */ + TargetsClient getTargets(); + + /** + * Gets the SharedPrivateLinkResourcesClient object to access its operations. + * + * @return the SharedPrivateLinkResourcesClient object. + */ + SharedPrivateLinkResourcesClient getSharedPrivateLinkResources(); +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/HealthValidationsClient.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/HealthValidationsClient.java new file mode 100644 index 000000000000..f5bcd9437c49 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/HealthValidationsClient.java @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.databasewatcher.fluent.models.HealthValidationInner; + +/** + * An instance of this class provides access to all the operations defined in HealthValidationsClient. + */ +public interface HealthValidationsClient { + /** + * Get a HealthValidation. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param healthValidationName The health validation resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a HealthValidation along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceGroupName, String watcherName, + String healthValidationName, Context context); + + /** + * Get a HealthValidation. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param healthValidationName The health validation resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a HealthValidation. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + HealthValidationInner get(String resourceGroupName, String watcherName, String healthValidationName); + + /** + * List HealthValidation resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a HealthValidation list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByParent(String resourceGroupName, String watcherName); + + /** + * List HealthValidation resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a HealthValidation list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByParent(String resourceGroupName, String watcherName, Context context); + + /** + * Starts health validation for a watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param healthValidationName The health validation resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, HealthValidationInner> beginStartValidation(String resourceGroupName, + String watcherName, String healthValidationName); + + /** + * Starts health validation for a watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param healthValidationName The health validation resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, HealthValidationInner> beginStartValidation(String resourceGroupName, + String watcherName, String healthValidationName, Context context); + + /** + * Starts health validation for a watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param healthValidationName The health validation resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + HealthValidationInner startValidation(String resourceGroupName, String watcherName, String healthValidationName); + + /** + * Starts health validation for a watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param healthValidationName The health validation resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + HealthValidationInner startValidation(String resourceGroupName, String watcherName, String healthValidationName, + Context context); +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/OperationsClient.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/OperationsClient.java new file mode 100644 index 000000000000..adc1a205e696 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/OperationsClient.java @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.Context; +import com.azure.resourcemanager.databasewatcher.fluent.models.OperationInner; + +/** + * An instance of this class provides access to all the operations defined in OperationsClient. + */ +public interface OperationsClient { + /** + * List the operations for the provider. + * + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(); + + /** + * List the operations for the provider. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(Context context); +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/SharedPrivateLinkResourcesClient.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/SharedPrivateLinkResourcesClient.java new file mode 100644 index 000000000000..80d8065610a3 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/SharedPrivateLinkResourcesClient.java @@ -0,0 +1,208 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.databasewatcher.fluent.models.SharedPrivateLinkResourceInner; + +/** + * An instance of this class provides access to all the operations defined in SharedPrivateLinkResourcesClient. + */ +public interface SharedPrivateLinkResourcesClient { + /** + * Get a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SharedPrivateLinkResource along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceGroupName, String watcherName, + String sharedPrivateLinkResourceName, Context context); + + /** + * Get a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SharedPrivateLinkResource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + SharedPrivateLinkResourceInner get(String resourceGroupName, String watcherName, + String sharedPrivateLinkResourceName); + + /** + * Create a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of concrete proxy resource types can be created by aliasing this type + * using a specific property type. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, SharedPrivateLinkResourceInner> beginCreate( + String resourceGroupName, String watcherName, String sharedPrivateLinkResourceName, + SharedPrivateLinkResourceInner resource); + + /** + * Create a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of concrete proxy resource types can be created by aliasing this type + * using a specific property type. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, SharedPrivateLinkResourceInner> beginCreate( + String resourceGroupName, String watcherName, String sharedPrivateLinkResourceName, + SharedPrivateLinkResourceInner resource, Context context); + + /** + * Create a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete proxy resource types can be created by aliasing this type using a specific property type. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + SharedPrivateLinkResourceInner create(String resourceGroupName, String watcherName, + String sharedPrivateLinkResourceName, SharedPrivateLinkResourceInner resource); + + /** + * Create a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete proxy resource types can be created by aliasing this type using a specific property type. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + SharedPrivateLinkResourceInner create(String resourceGroupName, String watcherName, + String sharedPrivateLinkResourceName, SharedPrivateLinkResourceInner resource, Context context); + + /** + * Delete a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, Void> beginDelete(String resourceGroupName, String watcherName, + String sharedPrivateLinkResourceName); + + /** + * Delete a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, Void> beginDelete(String resourceGroupName, String watcherName, + String sharedPrivateLinkResourceName, Context context); + + /** + * Delete a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void delete(String resourceGroupName, String watcherName, String sharedPrivateLinkResourceName); + + /** + * Delete a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void delete(String resourceGroupName, String watcherName, String sharedPrivateLinkResourceName, Context context); + + /** + * List SharedPrivateLinkResource resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SharedPrivateLinkResource list operation as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByWatcher(String resourceGroupName, String watcherName); + + /** + * List SharedPrivateLinkResource resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SharedPrivateLinkResource list operation as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByWatcher(String resourceGroupName, String watcherName, + Context context); +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/TargetsClient.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/TargetsClient.java new file mode 100644 index 000000000000..cc1c4eb5de59 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/TargetsClient.java @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.resourcemanager.databasewatcher.fluent.models.TargetInner; + +/** + * An instance of this class provides access to all the operations defined in TargetsClient. + */ +public interface TargetsClient { + /** + * Get a Target. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param targetName The target resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Target along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceGroupName, String watcherName, String targetName, + Context context); + + /** + * Get a Target. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param targetName The target resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Target. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + TargetInner get(String resourceGroupName, String watcherName, String targetName); + + /** + * Create a Target. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param targetName The target resource name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete proxy resource types can be created by aliasing this type using a specific property type along + * with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response createOrUpdateWithResponse(String resourceGroupName, String watcherName, String targetName, + TargetInner resource, Context context); + + /** + * Create a Target. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param targetName The target resource name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete proxy resource types can be created by aliasing this type using a specific property type. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + TargetInner createOrUpdate(String resourceGroupName, String watcherName, String targetName, TargetInner resource); + + /** + * Delete a Target. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param targetName The target resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response deleteWithResponse(String resourceGroupName, String watcherName, String targetName, Context context); + + /** + * Delete a Target. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param targetName The target resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void delete(String resourceGroupName, String watcherName, String targetName); + + /** + * List Target resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Target list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByWatcher(String resourceGroupName, String watcherName); + + /** + * List Target resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Target list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByWatcher(String resourceGroupName, String watcherName, Context context); +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/WatchersClient.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/WatchersClient.java new file mode 100644 index 000000000000..9010d3fb3dc0 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/WatchersClient.java @@ -0,0 +1,377 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.databasewatcher.fluent.models.WatcherInner; +import com.azure.resourcemanager.databasewatcher.models.WatcherUpdate; + +/** + * An instance of this class provides access to all the operations defined in WatchersClient. + */ +public interface WatchersClient { + /** + * Get a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Watcher along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getByResourceGroupWithResponse(String resourceGroupName, String watcherName, + Context context); + + /** + * Get a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Watcher. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + WatcherInner getByResourceGroup(String resourceGroupName, String watcherName); + + /** + * Create a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of the DatabaseWatcherProviderHub resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, WatcherInner> beginCreateOrUpdate(String resourceGroupName, String watcherName, + WatcherInner resource); + + /** + * Create a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of the DatabaseWatcherProviderHub resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, WatcherInner> beginCreateOrUpdate(String resourceGroupName, String watcherName, + WatcherInner resource, Context context); + + /** + * Create a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the DatabaseWatcherProviderHub resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + WatcherInner createOrUpdate(String resourceGroupName, String watcherName, WatcherInner resource); + + /** + * Create a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the DatabaseWatcherProviderHub resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + WatcherInner createOrUpdate(String resourceGroupName, String watcherName, WatcherInner resource, Context context); + + /** + * Update a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of the DatabaseWatcherProviderHub resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, WatcherInner> beginUpdate(String resourceGroupName, String watcherName, + WatcherUpdate properties); + + /** + * Update a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param properties The resource properties to be updated. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of the DatabaseWatcherProviderHub resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, WatcherInner> beginUpdate(String resourceGroupName, String watcherName, + WatcherUpdate properties, Context context); + + /** + * Update a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the DatabaseWatcherProviderHub resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + WatcherInner update(String resourceGroupName, String watcherName, WatcherUpdate properties); + + /** + * Update a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param properties The resource properties to be updated. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the DatabaseWatcherProviderHub resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + WatcherInner update(String resourceGroupName, String watcherName, WatcherUpdate properties, Context context); + + /** + * Delete a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, Void> beginDelete(String resourceGroupName, String watcherName); + + /** + * Delete a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, Void> beginDelete(String resourceGroupName, String watcherName, Context context); + + /** + * Delete a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void delete(String resourceGroupName, String watcherName); + + /** + * Delete a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void delete(String resourceGroupName, String watcherName, Context context); + + /** + * List Watcher resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Watcher list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByResourceGroup(String resourceGroupName); + + /** + * List Watcher resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Watcher list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByResourceGroup(String resourceGroupName, Context context); + + /** + * List Watcher resources by subscription ID. + * + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Watcher list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(); + + /** + * List Watcher resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Watcher list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(Context context); + + /** + * The action to start monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, WatcherInner> beginStart(String resourceGroupName, String watcherName); + + /** + * The action to start monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, WatcherInner> beginStart(String resourceGroupName, String watcherName, + Context context); + + /** + * The action to start monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + WatcherInner start(String resourceGroupName, String watcherName); + + /** + * The action to start monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + WatcherInner start(String resourceGroupName, String watcherName, Context context); + + /** + * The action to stop monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, WatcherInner> beginStop(String resourceGroupName, String watcherName); + + /** + * The action to stop monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, WatcherInner> beginStop(String resourceGroupName, String watcherName, + Context context); + + /** + * The action to stop monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + WatcherInner stop(String resourceGroupName, String watcherName); + + /** + * The action to stop monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + WatcherInner stop(String resourceGroupName, String watcherName, Context context); +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/models/AlertRuleResourceInner.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/models/AlertRuleResourceInner.java new file mode 100644 index 000000000000..e069162cc085 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/models/AlertRuleResourceInner.java @@ -0,0 +1,166 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.databasewatcher.models.AlertRuleResourceProperties; +import java.io.IOException; + +/** + * Concrete proxy resource types can be created by aliasing this type using a specific property type. + */ +@Fluent +public final class AlertRuleResourceInner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private AlertRuleResourceProperties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of AlertRuleResourceInner class. + */ + public AlertRuleResourceInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public AlertRuleResourceProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the AlertRuleResourceInner object itself. + */ + public AlertRuleResourceInner withProperties(AlertRuleResourceProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AlertRuleResourceInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AlertRuleResourceInner 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 AlertRuleResourceInner. + */ + public static AlertRuleResourceInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AlertRuleResourceInner deserializedAlertRuleResourceInner = new AlertRuleResourceInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedAlertRuleResourceInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedAlertRuleResourceInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedAlertRuleResourceInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedAlertRuleResourceInner.properties = AlertRuleResourceProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedAlertRuleResourceInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedAlertRuleResourceInner; + }); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/models/HealthValidationInner.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/models/HealthValidationInner.java new file mode 100644 index 000000000000..fddd4260c7b6 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/models/HealthValidationInner.java @@ -0,0 +1,155 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.fluent.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.databasewatcher.models.HealthValidationProperties; +import java.io.IOException; + +/** + * Concrete proxy resource types can be created by aliasing this type using a specific property type. + */ +@Immutable +public final class HealthValidationInner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private HealthValidationProperties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of HealthValidationInner class. + */ + private HealthValidationInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public HealthValidationProperties properties() { + return this.properties; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of HealthValidationInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of HealthValidationInner 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 HealthValidationInner. + */ + public static HealthValidationInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + HealthValidationInner deserializedHealthValidationInner = new HealthValidationInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedHealthValidationInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedHealthValidationInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedHealthValidationInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedHealthValidationInner.properties = HealthValidationProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedHealthValidationInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedHealthValidationInner; + }); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/models/OperationInner.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/models/OperationInner.java new file mode 100644 index 000000000000..6ad54c20707f --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/models/OperationInner.java @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.fluent.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 com.azure.resourcemanager.databasewatcher.models.ActionType; +import com.azure.resourcemanager.databasewatcher.models.OperationDisplay; +import com.azure.resourcemanager.databasewatcher.models.Origin; +import java.io.IOException; + +/** + * Details of a REST API operation, returned from the Resource Provider Operations API. + */ +@Immutable +public final class OperationInner implements JsonSerializable { + /* + * The name of the operation, as per Resource-Based Access Control (RBAC). Examples: + * "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action" + */ + private String name; + + /* + * Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure + * Resource Manager/control-plane operations. + */ + private Boolean isDataAction; + + /* + * Localized display information for this particular operation. + */ + private OperationDisplay display; + + /* + * The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default + * value is "user,system" + */ + private Origin origin; + + /* + * Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + */ + private ActionType actionType; + + /** + * Creates an instance of OperationInner class. + */ + private OperationInner() { + } + + /** + * Get the name property: The name of the operation, as per Resource-Based Access Control (RBAC). Examples: + * "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action". + * + * @return the name value. + */ + public String name() { + return this.name; + } + + /** + * Get the isDataAction property: Whether the operation applies to data-plane. This is "true" for data-plane + * operations and "false" for Azure Resource Manager/control-plane operations. + * + * @return the isDataAction value. + */ + public Boolean isDataAction() { + return this.isDataAction; + } + + /** + * Get the display property: Localized display information for this particular operation. + * + * @return the display value. + */ + public OperationDisplay display() { + return this.display; + } + + /** + * Get the origin property: The intended executor of the operation; as in Resource Based Access Control (RBAC) and + * audit logs UX. Default value is "user,system". + * + * @return the origin value. + */ + public Origin origin() { + return this.origin; + } + + /** + * Get the actionType property: Extensible enum. Indicates the action type. "Internal" refers to actions that are + * for internal only APIs. + * + * @return the actionType value. + */ + public ActionType actionType() { + return this.actionType; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (display() != null) { + display().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("display", this.display); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OperationInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OperationInner 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 OperationInner. + */ + public static OperationInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OperationInner deserializedOperationInner = new OperationInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("name".equals(fieldName)) { + deserializedOperationInner.name = reader.getString(); + } else if ("isDataAction".equals(fieldName)) { + deserializedOperationInner.isDataAction = reader.getNullable(JsonReader::getBoolean); + } else if ("display".equals(fieldName)) { + deserializedOperationInner.display = OperationDisplay.fromJson(reader); + } else if ("origin".equals(fieldName)) { + deserializedOperationInner.origin = Origin.fromString(reader.getString()); + } else if ("actionType".equals(fieldName)) { + deserializedOperationInner.actionType = ActionType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedOperationInner; + }); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/models/SharedPrivateLinkResourceInner.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/models/SharedPrivateLinkResourceInner.java new file mode 100644 index 000000000000..993837a5af2e --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/models/SharedPrivateLinkResourceInner.java @@ -0,0 +1,168 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.databasewatcher.models.SharedPrivateLinkResourceProperties; +import java.io.IOException; + +/** + * Concrete proxy resource types can be created by aliasing this type using a specific property type. + */ +@Fluent +public final class SharedPrivateLinkResourceInner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private SharedPrivateLinkResourceProperties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of SharedPrivateLinkResourceInner class. + */ + public SharedPrivateLinkResourceInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public SharedPrivateLinkResourceProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the SharedPrivateLinkResourceInner object itself. + */ + public SharedPrivateLinkResourceInner withProperties(SharedPrivateLinkResourceProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SharedPrivateLinkResourceInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SharedPrivateLinkResourceInner 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 SharedPrivateLinkResourceInner. + */ + public static SharedPrivateLinkResourceInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SharedPrivateLinkResourceInner deserializedSharedPrivateLinkResourceInner + = new SharedPrivateLinkResourceInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedSharedPrivateLinkResourceInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedSharedPrivateLinkResourceInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedSharedPrivateLinkResourceInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedSharedPrivateLinkResourceInner.properties + = SharedPrivateLinkResourceProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedSharedPrivateLinkResourceInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedSharedPrivateLinkResourceInner; + }); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/models/TargetInner.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/models/TargetInner.java new file mode 100644 index 000000000000..5b0cd07fc326 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/models/TargetInner.java @@ -0,0 +1,166 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.databasewatcher.models.TargetProperties; +import java.io.IOException; + +/** + * Concrete proxy resource types can be created by aliasing this type using a specific property type. + */ +@Fluent +public final class TargetInner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private TargetProperties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of TargetInner class. + */ + public TargetInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public TargetProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the TargetInner object itself. + */ + public TargetInner withProperties(TargetProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of TargetInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of TargetInner 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 TargetInner. + */ + public static TargetInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + TargetInner deserializedTargetInner = new TargetInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedTargetInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedTargetInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedTargetInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedTargetInner.properties = TargetProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedTargetInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedTargetInner; + }); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/models/WatcherInner.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/models/WatcherInner.java new file mode 100644 index 000000000000..5f8fd6f63829 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/models/WatcherInner.java @@ -0,0 +1,224 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.Resource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.databasewatcher.models.ManagedServiceIdentityV4; +import com.azure.resourcemanager.databasewatcher.models.WatcherProperties; +import java.io.IOException; +import java.util.Map; + +/** + * The DatabaseWatcherProviderHub resource. + */ +@Fluent +public final class WatcherInner extends Resource { + /* + * The resource-specific properties for this resource. + */ + private WatcherProperties properties; + + /* + * The managed service identities assigned to this resource. + */ + private ManagedServiceIdentityV4 identity; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of WatcherInner class. + */ + public WatcherInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public WatcherProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the WatcherInner object itself. + */ + public WatcherInner withProperties(WatcherProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the identity property: The managed service identities assigned to this resource. + * + * @return the identity value. + */ + public ManagedServiceIdentityV4 identity() { + return this.identity; + } + + /** + * Set the identity property: The managed service identities assigned to this resource. + * + * @param identity the identity value to set. + * @return the WatcherInner object itself. + */ + public WatcherInner withIdentity(ManagedServiceIdentityV4 identity) { + this.identity = identity; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * {@inheritDoc} + */ + @Override + public WatcherInner withLocation(String location) { + super.withLocation(location); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public WatcherInner withTags(Map tags) { + super.withTags(tags); + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + if (identity() != null) { + identity().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("location", location()); + jsonWriter.writeMapField("tags", tags(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeJsonField("properties", this.properties); + jsonWriter.writeJsonField("identity", this.identity); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of WatcherInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of WatcherInner 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 WatcherInner. + */ + public static WatcherInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + WatcherInner deserializedWatcherInner = new WatcherInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedWatcherInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedWatcherInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedWatcherInner.type = reader.getString(); + } else if ("location".equals(fieldName)) { + deserializedWatcherInner.withLocation(reader.getString()); + } else if ("tags".equals(fieldName)) { + Map tags = reader.readMap(reader1 -> reader1.getString()); + deserializedWatcherInner.withTags(tags); + } else if ("properties".equals(fieldName)) { + deserializedWatcherInner.properties = WatcherProperties.fromJson(reader); + } else if ("identity".equals(fieldName)) { + deserializedWatcherInner.identity = ManagedServiceIdentityV4.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedWatcherInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedWatcherInner; + }); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/models/package-info.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/models/package-info.java new file mode 100644 index 000000000000..5709c88d20aa --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/models/package-info.java @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +/** + * Package containing the inner data models for DatabaseWatcher. + */ +package com.azure.resourcemanager.databasewatcher.fluent.models; diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/package-info.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/package-info.java new file mode 100644 index 000000000000..b78ebf27b780 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/fluent/package-info.java @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +/** + * Package containing the service clients for DatabaseWatcher. + */ +package com.azure.resourcemanager.databasewatcher.fluent; diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/AlertRuleResourceImpl.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/AlertRuleResourceImpl.java new file mode 100644 index 000000000000..6db39ed3d0bc --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/AlertRuleResourceImpl.java @@ -0,0 +1,139 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.implementation; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.databasewatcher.fluent.models.AlertRuleResourceInner; +import com.azure.resourcemanager.databasewatcher.models.AlertRuleResource; +import com.azure.resourcemanager.databasewatcher.models.AlertRuleResourceProperties; + +public final class AlertRuleResourceImpl + implements AlertRuleResource, AlertRuleResource.Definition, AlertRuleResource.Update { + private AlertRuleResourceInner innerObject; + + private final com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager serviceManager; + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public AlertRuleResourceProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public String resourceGroupName() { + return resourceGroupName; + } + + public AlertRuleResourceInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager() { + return this.serviceManager; + } + + private String resourceGroupName; + + private String watcherName; + + private String alertRuleResourceName; + + public AlertRuleResourceImpl withExistingWatcher(String resourceGroupName, String watcherName) { + this.resourceGroupName = resourceGroupName; + this.watcherName = watcherName; + return this; + } + + public AlertRuleResource create() { + this.innerObject = serviceManager.serviceClient() + .getAlertRuleResources() + .createOrUpdateWithResponse(resourceGroupName, watcherName, alertRuleResourceName, this.innerModel(), + Context.NONE) + .getValue(); + return this; + } + + public AlertRuleResource create(Context context) { + this.innerObject = serviceManager.serviceClient() + .getAlertRuleResources() + .createOrUpdateWithResponse(resourceGroupName, watcherName, alertRuleResourceName, this.innerModel(), + context) + .getValue(); + return this; + } + + AlertRuleResourceImpl(String name, + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager serviceManager) { + this.innerObject = new AlertRuleResourceInner(); + this.serviceManager = serviceManager; + this.alertRuleResourceName = name; + } + + public AlertRuleResourceImpl update() { + return this; + } + + public AlertRuleResource apply() { + this.innerObject = serviceManager.serviceClient() + .getAlertRuleResources() + .createOrUpdateWithResponse(resourceGroupName, watcherName, alertRuleResourceName, this.innerModel(), + Context.NONE) + .getValue(); + return this; + } + + public AlertRuleResource apply(Context context) { + this.innerObject = serviceManager.serviceClient() + .getAlertRuleResources() + .createOrUpdateWithResponse(resourceGroupName, watcherName, alertRuleResourceName, this.innerModel(), + context) + .getValue(); + return this; + } + + AlertRuleResourceImpl(AlertRuleResourceInner innerObject, + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + this.resourceGroupName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "resourceGroups"); + this.watcherName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "watchers"); + this.alertRuleResourceName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "alertRuleResources"); + } + + public AlertRuleResource refresh() { + this.innerObject = serviceManager.serviceClient() + .getAlertRuleResources() + .getWithResponse(resourceGroupName, watcherName, alertRuleResourceName, Context.NONE) + .getValue(); + return this; + } + + public AlertRuleResource refresh(Context context) { + this.innerObject = serviceManager.serviceClient() + .getAlertRuleResources() + .getWithResponse(resourceGroupName, watcherName, alertRuleResourceName, context) + .getValue(); + return this; + } + + public AlertRuleResourceImpl withProperties(AlertRuleResourceProperties properties) { + this.innerModel().withProperties(properties); + return this; + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/AlertRuleResourcesClientImpl.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/AlertRuleResourcesClientImpl.java new file mode 100644 index 000000000000..ee2b68495c00 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/AlertRuleResourcesClientImpl.java @@ -0,0 +1,731 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Put; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.resourcemanager.databasewatcher.fluent.AlertRuleResourcesClient; +import com.azure.resourcemanager.databasewatcher.fluent.models.AlertRuleResourceInner; +import com.azure.resourcemanager.databasewatcher.implementation.models.AlertRuleResourceListResult; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in AlertRuleResourcesClient. + */ +public final class AlertRuleResourcesClientImpl implements AlertRuleResourcesClient { + /** + * The proxy service used to perform REST calls. + */ + private final AlertRuleResourcesService service; + + /** + * The service client containing this operation class. + */ + private final DatabaseWatcherManagementClientImpl client; + + /** + * Initializes an instance of AlertRuleResourcesClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + AlertRuleResourcesClientImpl(DatabaseWatcherManagementClientImpl client) { + this.service = RestProxy.create(AlertRuleResourcesService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for DatabaseWatcherManagementClientAlertRuleResources to be used by the + * proxy service to perform REST calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "DatabaseWatcherManag") + public interface AlertRuleResourcesService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/alertRuleResources/{alertRuleResourceName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("watcherName") String watcherName, + @PathParam("alertRuleResourceName") String alertRuleResourceName, @HeaderParam("Accept") String accept, + Context context); + + @Put("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/alertRuleResources/{alertRuleResourceName}") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> createOrUpdate(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("watcherName") String watcherName, + @PathParam("alertRuleResourceName") String alertRuleResourceName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") AlertRuleResourceInner resource, Context context); + + @Headers({ "Content-Type: application/json" }) + @Delete("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/alertRuleResources/{alertRuleResourceName}") + @ExpectedResponses({ 200, 204 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> delete(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("watcherName") String watcherName, + @PathParam("alertRuleResourceName") String alertRuleResourceName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/alertRuleResources") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByParent(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("watcherName") String watcherName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByParentNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * Get a AlertRuleResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param alertRuleResourceName The alert rule proxy resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AlertRuleResource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String watcherName, + String alertRuleResourceName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + if (alertRuleResourceName == null) { + return Mono + .error(new IllegalArgumentException("Parameter alertRuleResourceName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, watcherName, alertRuleResourceName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a AlertRuleResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param alertRuleResourceName The alert rule proxy resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AlertRuleResource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String watcherName, + String alertRuleResourceName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + if (alertRuleResourceName == null) { + return Mono + .error(new IllegalArgumentException("Parameter alertRuleResourceName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, watcherName, alertRuleResourceName, accept, context); + } + + /** + * Get a AlertRuleResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param alertRuleResourceName The alert rule proxy resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AlertRuleResource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceGroupName, String watcherName, + String alertRuleResourceName) { + return getWithResponseAsync(resourceGroupName, watcherName, alertRuleResourceName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a AlertRuleResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param alertRuleResourceName The alert rule proxy resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AlertRuleResource along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceGroupName, String watcherName, + String alertRuleResourceName, Context context) { + return getWithResponseAsync(resourceGroupName, watcherName, alertRuleResourceName, context).block(); + } + + /** + * Get a AlertRuleResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param alertRuleResourceName The alert rule proxy resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AlertRuleResource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public AlertRuleResourceInner get(String resourceGroupName, String watcherName, String alertRuleResourceName) { + return getWithResponse(resourceGroupName, watcherName, alertRuleResourceName, Context.NONE).getValue(); + } + + /** + * Create a AlertRuleResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param alertRuleResourceName The alert rule proxy resource name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete proxy resource types can be created by aliasing this type using a specific property type along + * with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> createOrUpdateWithResponseAsync(String resourceGroupName, + String watcherName, String alertRuleResourceName, AlertRuleResourceInner resource) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + if (alertRuleResourceName == null) { + return Mono + .error(new IllegalArgumentException("Parameter alertRuleResourceName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.createOrUpdate(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, watcherName, alertRuleResourceName, contentType, + accept, resource, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Create a AlertRuleResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param alertRuleResourceName The alert rule proxy resource name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete proxy resource types can be created by aliasing this type using a specific property type along + * with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> createOrUpdateWithResponseAsync(String resourceGroupName, + String watcherName, String alertRuleResourceName, AlertRuleResourceInner resource, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + if (alertRuleResourceName == null) { + return Mono + .error(new IllegalArgumentException("Parameter alertRuleResourceName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.createOrUpdate(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, watcherName, alertRuleResourceName, contentType, accept, + resource, context); + } + + /** + * Create a AlertRuleResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param alertRuleResourceName The alert rule proxy resource name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete proxy resource types can be created by aliasing this type using a specific property type on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createOrUpdateAsync(String resourceGroupName, String watcherName, + String alertRuleResourceName, AlertRuleResourceInner resource) { + return createOrUpdateWithResponseAsync(resourceGroupName, watcherName, alertRuleResourceName, resource) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Create a AlertRuleResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param alertRuleResourceName The alert rule proxy resource name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete proxy resource types can be created by aliasing this type using a specific property type along + * with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createOrUpdateWithResponse(String resourceGroupName, String watcherName, + String alertRuleResourceName, AlertRuleResourceInner resource, Context context) { + return createOrUpdateWithResponseAsync(resourceGroupName, watcherName, alertRuleResourceName, resource, context) + .block(); + } + + /** + * Create a AlertRuleResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param alertRuleResourceName The alert rule proxy resource name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete proxy resource types can be created by aliasing this type using a specific property type. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public AlertRuleResourceInner createOrUpdate(String resourceGroupName, String watcherName, + String alertRuleResourceName, AlertRuleResourceInner resource) { + return createOrUpdateWithResponse(resourceGroupName, watcherName, alertRuleResourceName, resource, Context.NONE) + .getValue(); + } + + /** + * Delete a AlertRuleResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param alertRuleResourceName The alert rule proxy resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String watcherName, + String alertRuleResourceName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + if (alertRuleResourceName == null) { + return Mono + .error(new IllegalArgumentException("Parameter alertRuleResourceName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.delete(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, watcherName, alertRuleResourceName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Delete a AlertRuleResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param alertRuleResourceName The alert rule proxy resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String watcherName, + String alertRuleResourceName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + if (alertRuleResourceName == null) { + return Mono + .error(new IllegalArgumentException("Parameter alertRuleResourceName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.delete(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, watcherName, alertRuleResourceName, accept, context); + } + + /** + * Delete a AlertRuleResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param alertRuleResourceName The alert rule proxy resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono deleteAsync(String resourceGroupName, String watcherName, String alertRuleResourceName) { + return deleteWithResponseAsync(resourceGroupName, watcherName, alertRuleResourceName) + .flatMap(ignored -> Mono.empty()); + } + + /** + * Delete a AlertRuleResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param alertRuleResourceName The alert rule proxy resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String resourceGroupName, String watcherName, String alertRuleResourceName, + Context context) { + return deleteWithResponseAsync(resourceGroupName, watcherName, alertRuleResourceName, context).block(); + } + + /** + * Delete a AlertRuleResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param alertRuleResourceName The alert rule proxy resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String resourceGroupName, String watcherName, String alertRuleResourceName) { + deleteWithResponse(resourceGroupName, watcherName, alertRuleResourceName, Context.NONE); + } + + /** + * List AlertRuleResource resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AlertRuleResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByParentSinglePageAsync(String resourceGroupName, + String watcherName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listByParent(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, watcherName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List AlertRuleResource resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AlertRuleResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByParentSinglePageAsync(String resourceGroupName, + String watcherName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByParent(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, watcherName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List AlertRuleResource resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AlertRuleResource list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByParentAsync(String resourceGroupName, String watcherName) { + return new PagedFlux<>(() -> listByParentSinglePageAsync(resourceGroupName, watcherName), + nextLink -> listByParentNextSinglePageAsync(nextLink)); + } + + /** + * List AlertRuleResource resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AlertRuleResource list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByParentAsync(String resourceGroupName, String watcherName, + Context context) { + return new PagedFlux<>(() -> listByParentSinglePageAsync(resourceGroupName, watcherName, context), + nextLink -> listByParentNextSinglePageAsync(nextLink, context)); + } + + /** + * List AlertRuleResource resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AlertRuleResource list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByParent(String resourceGroupName, String watcherName) { + return new PagedIterable<>(listByParentAsync(resourceGroupName, watcherName)); + } + + /** + * List AlertRuleResource resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AlertRuleResource list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByParent(String resourceGroupName, String watcherName, + Context context) { + return new PagedIterable<>(listByParentAsync(resourceGroupName, watcherName, context)); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AlertRuleResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByParentNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listByParentNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AlertRuleResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByParentNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listByParentNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/AlertRuleResourcesImpl.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/AlertRuleResourcesImpl.java new file mode 100644 index 000000000000..63e2ac34b81a --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/AlertRuleResourcesImpl.java @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.databasewatcher.fluent.AlertRuleResourcesClient; +import com.azure.resourcemanager.databasewatcher.fluent.models.AlertRuleResourceInner; +import com.azure.resourcemanager.databasewatcher.models.AlertRuleResource; +import com.azure.resourcemanager.databasewatcher.models.AlertRuleResources; + +public final class AlertRuleResourcesImpl implements AlertRuleResources { + private static final ClientLogger LOGGER = new ClientLogger(AlertRuleResourcesImpl.class); + + private final AlertRuleResourcesClient innerClient; + + private final com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager serviceManager; + + public AlertRuleResourcesImpl(AlertRuleResourcesClient innerClient, + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public Response getWithResponse(String resourceGroupName, String watcherName, + String alertRuleResourceName, Context context) { + Response inner + = this.serviceClient().getWithResponse(resourceGroupName, watcherName, alertRuleResourceName, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new AlertRuleResourceImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public AlertRuleResource get(String resourceGroupName, String watcherName, String alertRuleResourceName) { + AlertRuleResourceInner inner = this.serviceClient().get(resourceGroupName, watcherName, alertRuleResourceName); + if (inner != null) { + return new AlertRuleResourceImpl(inner, this.manager()); + } else { + return null; + } + } + + public Response deleteWithResponse(String resourceGroupName, String watcherName, String alertRuleResourceName, + Context context) { + return this.serviceClient().deleteWithResponse(resourceGroupName, watcherName, alertRuleResourceName, context); + } + + public void delete(String resourceGroupName, String watcherName, String alertRuleResourceName) { + this.serviceClient().delete(resourceGroupName, watcherName, alertRuleResourceName); + } + + public PagedIterable listByParent(String resourceGroupName, String watcherName) { + PagedIterable inner = this.serviceClient().listByParent(resourceGroupName, watcherName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new AlertRuleResourceImpl(inner1, this.manager())); + } + + public PagedIterable listByParent(String resourceGroupName, String watcherName, + Context context) { + PagedIterable inner + = this.serviceClient().listByParent(resourceGroupName, watcherName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new AlertRuleResourceImpl(inner1, this.manager())); + } + + public AlertRuleResource getById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String watcherName = ResourceManagerUtils.getValueFromIdByName(id, "watchers"); + if (watcherName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'watchers'.", id))); + } + String alertRuleResourceName = ResourceManagerUtils.getValueFromIdByName(id, "alertRuleResources"); + if (alertRuleResourceName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'alertRuleResources'.", id))); + } + return this.getWithResponse(resourceGroupName, watcherName, alertRuleResourceName, Context.NONE).getValue(); + } + + public Response getByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String watcherName = ResourceManagerUtils.getValueFromIdByName(id, "watchers"); + if (watcherName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'watchers'.", id))); + } + String alertRuleResourceName = ResourceManagerUtils.getValueFromIdByName(id, "alertRuleResources"); + if (alertRuleResourceName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'alertRuleResources'.", id))); + } + return this.getWithResponse(resourceGroupName, watcherName, alertRuleResourceName, context); + } + + public void deleteById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String watcherName = ResourceManagerUtils.getValueFromIdByName(id, "watchers"); + if (watcherName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'watchers'.", id))); + } + String alertRuleResourceName = ResourceManagerUtils.getValueFromIdByName(id, "alertRuleResources"); + if (alertRuleResourceName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'alertRuleResources'.", id))); + } + this.deleteWithResponse(resourceGroupName, watcherName, alertRuleResourceName, Context.NONE); + } + + public Response deleteByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String watcherName = ResourceManagerUtils.getValueFromIdByName(id, "watchers"); + if (watcherName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'watchers'.", id))); + } + String alertRuleResourceName = ResourceManagerUtils.getValueFromIdByName(id, "alertRuleResources"); + if (alertRuleResourceName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'alertRuleResources'.", id))); + } + return this.deleteWithResponse(resourceGroupName, watcherName, alertRuleResourceName, context); + } + + private AlertRuleResourcesClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager() { + return this.serviceManager; + } + + public AlertRuleResourceImpl define(String name) { + return new AlertRuleResourceImpl(name, this.manager()); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/DatabaseWatcherManagementClientBuilder.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/DatabaseWatcherManagementClientBuilder.java new file mode 100644 index 000000000000..35fe93549660 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/DatabaseWatcherManagementClientBuilder.java @@ -0,0 +1,138 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.implementation; + +import com.azure.core.annotation.ServiceClientBuilder; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.policy.RetryPolicy; +import com.azure.core.http.policy.UserAgentPolicy; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.serializer.SerializerFactory; +import com.azure.core.util.serializer.SerializerAdapter; +import java.time.Duration; + +/** + * A builder for creating a new instance of the DatabaseWatcherManagementClientImpl type. + */ +@ServiceClientBuilder(serviceClients = { DatabaseWatcherManagementClientImpl.class }) +public final class DatabaseWatcherManagementClientBuilder { + /* + * Service host + */ + private String endpoint; + + /** + * Sets Service host. + * + * @param endpoint the endpoint value. + * @return the DatabaseWatcherManagementClientBuilder. + */ + public DatabaseWatcherManagementClientBuilder endpoint(String endpoint) { + this.endpoint = endpoint; + return this; + } + + /* + * The ID of the target subscription. The value must be an UUID. + */ + private String subscriptionId; + + /** + * Sets The ID of the target subscription. The value must be an UUID. + * + * @param subscriptionId the subscriptionId value. + * @return the DatabaseWatcherManagementClientBuilder. + */ + public DatabaseWatcherManagementClientBuilder subscriptionId(String subscriptionId) { + this.subscriptionId = subscriptionId; + return this; + } + + /* + * The environment to connect to + */ + private AzureEnvironment environment; + + /** + * Sets The environment to connect to. + * + * @param environment the environment value. + * @return the DatabaseWatcherManagementClientBuilder. + */ + public DatabaseWatcherManagementClientBuilder environment(AzureEnvironment environment) { + this.environment = environment; + 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 DatabaseWatcherManagementClientBuilder. + */ + public DatabaseWatcherManagementClientBuilder pipeline(HttpPipeline pipeline) { + this.pipeline = pipeline; + return this; + } + + /* + * The default poll interval for long-running operation + */ + private Duration defaultPollInterval; + + /** + * Sets The default poll interval for long-running operation. + * + * @param defaultPollInterval the defaultPollInterval value. + * @return the DatabaseWatcherManagementClientBuilder. + */ + public DatabaseWatcherManagementClientBuilder defaultPollInterval(Duration defaultPollInterval) { + this.defaultPollInterval = defaultPollInterval; + 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 DatabaseWatcherManagementClientBuilder. + */ + public DatabaseWatcherManagementClientBuilder serializerAdapter(SerializerAdapter serializerAdapter) { + this.serializerAdapter = serializerAdapter; + return this; + } + + /** + * Builds an instance of DatabaseWatcherManagementClientImpl with the provided parameters. + * + * @return an instance of DatabaseWatcherManagementClientImpl. + */ + public DatabaseWatcherManagementClientImpl buildClient() { + String localEndpoint = (endpoint != null) ? endpoint : "https://management.azure.com"; + AzureEnvironment localEnvironment = (environment != null) ? environment : AzureEnvironment.AZURE; + HttpPipeline localPipeline = (pipeline != null) + ? pipeline + : new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build(); + Duration localDefaultPollInterval + = (defaultPollInterval != null) ? defaultPollInterval : Duration.ofSeconds(30); + SerializerAdapter localSerializerAdapter = (serializerAdapter != null) + ? serializerAdapter + : SerializerFactory.createDefaultManagementSerializerAdapter(); + DatabaseWatcherManagementClientImpl client = new DatabaseWatcherManagementClientImpl(localPipeline, + localSerializerAdapter, localDefaultPollInterval, localEnvironment, localEndpoint, this.subscriptionId); + return client; + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/DatabaseWatcherManagementClientImpl.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/DatabaseWatcherManagementClientImpl.java new file mode 100644 index 000000000000..6688f0684a96 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/DatabaseWatcherManagementClientImpl.java @@ -0,0 +1,368 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.implementation; + +import com.azure.core.annotation.ServiceClient; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.HttpHeaders; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpResponse; +import com.azure.core.http.rest.Response; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.exception.ManagementError; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.management.polling.PollResult; +import com.azure.core.management.polling.PollerFactory; +import com.azure.core.util.Context; +import com.azure.core.util.CoreUtils; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.polling.AsyncPollResponse; +import com.azure.core.util.polling.LongRunningOperationStatus; +import com.azure.core.util.polling.PollerFlux; +import com.azure.core.util.serializer.SerializerAdapter; +import com.azure.core.util.serializer.SerializerEncoding; +import com.azure.resourcemanager.databasewatcher.fluent.AlertRuleResourcesClient; +import com.azure.resourcemanager.databasewatcher.fluent.DatabaseWatcherManagementClient; +import com.azure.resourcemanager.databasewatcher.fluent.HealthValidationsClient; +import com.azure.resourcemanager.databasewatcher.fluent.OperationsClient; +import com.azure.resourcemanager.databasewatcher.fluent.SharedPrivateLinkResourcesClient; +import com.azure.resourcemanager.databasewatcher.fluent.TargetsClient; +import com.azure.resourcemanager.databasewatcher.fluent.WatchersClient; +import java.io.IOException; +import java.lang.reflect.Type; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * Initializes a new instance of the DatabaseWatcherManagementClientImpl type. + */ +@ServiceClient(builder = DatabaseWatcherManagementClientBuilder.class) +public final class DatabaseWatcherManagementClientImpl implements DatabaseWatcherManagementClient { + /** + * Service host. + */ + private final String endpoint; + + /** + * Gets Service host. + * + * @return the endpoint value. + */ + public String getEndpoint() { + return this.endpoint; + } + + /** + * Version parameter. + */ + private final String apiVersion; + + /** + * Gets Version parameter. + * + * @return the apiVersion value. + */ + public String getApiVersion() { + return this.apiVersion; + } + + /** + * The ID of the target subscription. The value must be an UUID. + */ + private final String subscriptionId; + + /** + * Gets The ID of the target subscription. The value must be an UUID. + * + * @return the subscriptionId value. + */ + public String getSubscriptionId() { + return this.subscriptionId; + } + + /** + * 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. + */ + SerializerAdapter getSerializerAdapter() { + return this.serializerAdapter; + } + + /** + * The default poll interval for long-running operation. + */ + private final Duration defaultPollInterval; + + /** + * Gets The default poll interval for long-running operation. + * + * @return the defaultPollInterval value. + */ + public Duration getDefaultPollInterval() { + return this.defaultPollInterval; + } + + /** + * The OperationsClient object to access its operations. + */ + private final OperationsClient operations; + + /** + * Gets the OperationsClient object to access its operations. + * + * @return the OperationsClient object. + */ + public OperationsClient getOperations() { + return this.operations; + } + + /** + * The WatchersClient object to access its operations. + */ + private final WatchersClient watchers; + + /** + * Gets the WatchersClient object to access its operations. + * + * @return the WatchersClient object. + */ + public WatchersClient getWatchers() { + return this.watchers; + } + + /** + * The AlertRuleResourcesClient object to access its operations. + */ + private final AlertRuleResourcesClient alertRuleResources; + + /** + * Gets the AlertRuleResourcesClient object to access its operations. + * + * @return the AlertRuleResourcesClient object. + */ + public AlertRuleResourcesClient getAlertRuleResources() { + return this.alertRuleResources; + } + + /** + * The HealthValidationsClient object to access its operations. + */ + private final HealthValidationsClient healthValidations; + + /** + * Gets the HealthValidationsClient object to access its operations. + * + * @return the HealthValidationsClient object. + */ + public HealthValidationsClient getHealthValidations() { + return this.healthValidations; + } + + /** + * The TargetsClient object to access its operations. + */ + private final TargetsClient targets; + + /** + * Gets the TargetsClient object to access its operations. + * + * @return the TargetsClient object. + */ + public TargetsClient getTargets() { + return this.targets; + } + + /** + * The SharedPrivateLinkResourcesClient object to access its operations. + */ + private final SharedPrivateLinkResourcesClient sharedPrivateLinkResources; + + /** + * Gets the SharedPrivateLinkResourcesClient object to access its operations. + * + * @return the SharedPrivateLinkResourcesClient object. + */ + public SharedPrivateLinkResourcesClient getSharedPrivateLinkResources() { + return this.sharedPrivateLinkResources; + } + + /** + * Initializes an instance of DatabaseWatcherManagementClient client. + * + * @param httpPipeline The HTTP pipeline to send requests through. + * @param serializerAdapter The serializer to serialize an object into a string. + * @param defaultPollInterval The default poll interval for long-running operation. + * @param environment The Azure environment. + * @param endpoint Service host. + * @param subscriptionId The ID of the target subscription. The value must be an UUID. + */ + DatabaseWatcherManagementClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, + Duration defaultPollInterval, AzureEnvironment environment, String endpoint, String subscriptionId) { + this.httpPipeline = httpPipeline; + this.serializerAdapter = serializerAdapter; + this.defaultPollInterval = defaultPollInterval; + this.endpoint = endpoint; + this.subscriptionId = subscriptionId; + this.apiVersion = "2025-01-02"; + this.operations = new OperationsClientImpl(this); + this.watchers = new WatchersClientImpl(this); + this.alertRuleResources = new AlertRuleResourcesClientImpl(this); + this.healthValidations = new HealthValidationsClientImpl(this); + this.targets = new TargetsClientImpl(this); + this.sharedPrivateLinkResources = new SharedPrivateLinkResourcesClientImpl(this); + } + + /** + * Gets default client context. + * + * @return the default client context. + */ + public Context getContext() { + return Context.NONE; + } + + /** + * Merges default client context with provided context. + * + * @param context the context to be merged with default client context. + * @return the merged context. + */ + public Context mergeContext(Context context) { + return CoreUtils.mergeContexts(this.getContext(), context); + } + + /** + * Gets long running operation result. + * + * @param activationResponse the response of activation operation. + * @param httpPipeline the http pipeline. + * @param pollResultType type of poll result. + * @param finalResultType type of final result. + * @param context the context shared by all requests. + * @param type of poll result. + * @param type of final result. + * @return poller flux for poll result and final result. + */ + public PollerFlux, U> getLroResult(Mono>> activationResponse, + HttpPipeline httpPipeline, Type pollResultType, Type finalResultType, Context context) { + return PollerFactory.create(serializerAdapter, httpPipeline, pollResultType, finalResultType, + defaultPollInterval, activationResponse, context); + } + + /** + * Gets the final result, or an error, based on last async poll response. + * + * @param response the last async poll response. + * @param type of poll result. + * @param type of final result. + * @return the final result, or an error. + */ + public Mono getLroFinalResultOrError(AsyncPollResponse, U> response) { + if (response.getStatus() != LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { + String errorMessage; + ManagementError managementError = null; + HttpResponse errorResponse = null; + PollResult.Error lroError = response.getValue().getError(); + if (lroError != null) { + errorResponse = new HttpResponseImpl(lroError.getResponseStatusCode(), lroError.getResponseHeaders(), + lroError.getResponseBody()); + + errorMessage = response.getValue().getError().getMessage(); + String errorBody = response.getValue().getError().getResponseBody(); + if (errorBody != null) { + // try to deserialize error body to ManagementError + try { + managementError = this.getSerializerAdapter() + .deserialize(errorBody, ManagementError.class, SerializerEncoding.JSON); + if (managementError.getCode() == null || managementError.getMessage() == null) { + managementError = null; + } + } catch (IOException | RuntimeException ioe) { + LOGGER.logThrowableAsWarning(ioe); + } + } + } else { + // fallback to default error message + errorMessage = "Long running operation failed."; + } + if (managementError == null) { + // fallback to default ManagementError + managementError = new ManagementError(response.getStatus().toString(), errorMessage); + } + return Mono.error(new ManagementException(errorMessage, errorResponse, managementError)); + } else { + return response.getFinalResult(); + } + } + + private static final class HttpResponseImpl extends HttpResponse { + private final int statusCode; + + private final byte[] responseBody; + + private final HttpHeaders httpHeaders; + + HttpResponseImpl(int statusCode, HttpHeaders httpHeaders, String responseBody) { + super(null); + this.statusCode = statusCode; + this.httpHeaders = httpHeaders; + this.responseBody = responseBody == null ? null : responseBody.getBytes(StandardCharsets.UTF_8); + } + + public int getStatusCode() { + return statusCode; + } + + public String getHeaderValue(String s) { + return httpHeaders.getValue(HttpHeaderName.fromString(s)); + } + + public HttpHeaders getHeaders() { + return httpHeaders; + } + + public Flux getBody() { + return Flux.just(ByteBuffer.wrap(responseBody)); + } + + public Mono getBodyAsByteArray() { + return Mono.just(responseBody); + } + + public Mono getBodyAsString() { + return Mono.just(new String(responseBody, StandardCharsets.UTF_8)); + } + + public Mono getBodyAsString(Charset charset) { + return Mono.just(new String(responseBody, charset)); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(DatabaseWatcherManagementClientImpl.class); +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/HealthValidationImpl.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/HealthValidationImpl.java new file mode 100644 index 000000000000..f7d45c4b4371 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/HealthValidationImpl.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.implementation; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.databasewatcher.fluent.models.HealthValidationInner; +import com.azure.resourcemanager.databasewatcher.models.HealthValidation; +import com.azure.resourcemanager.databasewatcher.models.HealthValidationProperties; + +public final class HealthValidationImpl implements HealthValidation { + private HealthValidationInner innerObject; + + private final com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager serviceManager; + + HealthValidationImpl(HealthValidationInner innerObject, + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public HealthValidationProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public HealthValidationInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/HealthValidationsClientImpl.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/HealthValidationsClientImpl.java new file mode 100644 index 000000000000..1fca2bdc2847 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/HealthValidationsClientImpl.java @@ -0,0 +1,669 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.implementation; + +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.core.util.polling.PollerFlux; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.databasewatcher.fluent.HealthValidationsClient; +import com.azure.resourcemanager.databasewatcher.fluent.models.HealthValidationInner; +import com.azure.resourcemanager.databasewatcher.implementation.models.HealthValidationListResult; +import java.nio.ByteBuffer; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in HealthValidationsClient. + */ +public final class HealthValidationsClientImpl implements HealthValidationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final HealthValidationsService service; + + /** + * The service client containing this operation class. + */ + private final DatabaseWatcherManagementClientImpl client; + + /** + * Initializes an instance of HealthValidationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + HealthValidationsClientImpl(DatabaseWatcherManagementClientImpl client) { + this.service + = RestProxy.create(HealthValidationsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for DatabaseWatcherManagementClientHealthValidations to be used by the + * proxy service to perform REST calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "DatabaseWatcherManag") + public interface HealthValidationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/healthValidations/{healthValidationName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("watcherName") String watcherName, + @PathParam("healthValidationName") String healthValidationName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/healthValidations") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByParent(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("watcherName") String watcherName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Post("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/healthValidations/{healthValidationName}/startValidation") + @ExpectedResponses({ 200, 202 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> startValidation(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("watcherName") String watcherName, + @PathParam("healthValidationName") String healthValidationName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByParentNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * Get a HealthValidation. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param healthValidationName The health validation resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a HealthValidation along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String watcherName, + String healthValidationName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + if (healthValidationName == null) { + return Mono + .error(new IllegalArgumentException("Parameter healthValidationName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, watcherName, healthValidationName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a HealthValidation. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param healthValidationName The health validation resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a HealthValidation along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String watcherName, + String healthValidationName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + if (healthValidationName == null) { + return Mono + .error(new IllegalArgumentException("Parameter healthValidationName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, watcherName, healthValidationName, accept, context); + } + + /** + * Get a HealthValidation. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param healthValidationName The health validation resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a HealthValidation on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceGroupName, String watcherName, + String healthValidationName) { + return getWithResponseAsync(resourceGroupName, watcherName, healthValidationName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a HealthValidation. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param healthValidationName The health validation resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a HealthValidation along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceGroupName, String watcherName, + String healthValidationName, Context context) { + return getWithResponseAsync(resourceGroupName, watcherName, healthValidationName, context).block(); + } + + /** + * Get a HealthValidation. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param healthValidationName The health validation resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a HealthValidation. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public HealthValidationInner get(String resourceGroupName, String watcherName, String healthValidationName) { + return getWithResponse(resourceGroupName, watcherName, healthValidationName, Context.NONE).getValue(); + } + + /** + * List HealthValidation resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a HealthValidation list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByParentSinglePageAsync(String resourceGroupName, + String watcherName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listByParent(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, watcherName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List HealthValidation resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a HealthValidation list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByParentSinglePageAsync(String resourceGroupName, + String watcherName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByParent(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, watcherName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List HealthValidation resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a HealthValidation list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByParentAsync(String resourceGroupName, String watcherName) { + return new PagedFlux<>(() -> listByParentSinglePageAsync(resourceGroupName, watcherName), + nextLink -> listByParentNextSinglePageAsync(nextLink)); + } + + /** + * List HealthValidation resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a HealthValidation list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByParentAsync(String resourceGroupName, String watcherName, + Context context) { + return new PagedFlux<>(() -> listByParentSinglePageAsync(resourceGroupName, watcherName, context), + nextLink -> listByParentNextSinglePageAsync(nextLink, context)); + } + + /** + * List HealthValidation resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a HealthValidation list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByParent(String resourceGroupName, String watcherName) { + return new PagedIterable<>(listByParentAsync(resourceGroupName, watcherName)); + } + + /** + * List HealthValidation resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a HealthValidation list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByParent(String resourceGroupName, String watcherName, + Context context) { + return new PagedIterable<>(listByParentAsync(resourceGroupName, watcherName, context)); + } + + /** + * Starts health validation for a watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param healthValidationName The health validation resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> startValidationWithResponseAsync(String resourceGroupName, + String watcherName, String healthValidationName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + if (healthValidationName == null) { + return Mono + .error(new IllegalArgumentException("Parameter healthValidationName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.startValidation(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, watcherName, healthValidationName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Starts health validation for a watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param healthValidationName The health validation resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> startValidationWithResponseAsync(String resourceGroupName, + String watcherName, String healthValidationName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + if (healthValidationName == null) { + return Mono + .error(new IllegalArgumentException("Parameter healthValidationName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.startValidation(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, watcherName, healthValidationName, accept, context); + } + + /** + * Starts health validation for a watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param healthValidationName The health validation resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, HealthValidationInner> + beginStartValidationAsync(String resourceGroupName, String watcherName, String healthValidationName) { + Mono>> mono + = startValidationWithResponseAsync(resourceGroupName, watcherName, healthValidationName); + return this.client.getLroResult(mono, + this.client.getHttpPipeline(), HealthValidationInner.class, HealthValidationInner.class, + this.client.getContext()); + } + + /** + * Starts health validation for a watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param healthValidationName The health validation resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, HealthValidationInner> beginStartValidationAsync( + String resourceGroupName, String watcherName, String healthValidationName, Context context) { + context = this.client.mergeContext(context); + Mono>> mono + = startValidationWithResponseAsync(resourceGroupName, watcherName, healthValidationName, context); + return this.client.getLroResult(mono, + this.client.getHttpPipeline(), HealthValidationInner.class, HealthValidationInner.class, context); + } + + /** + * Starts health validation for a watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param healthValidationName The health validation resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, HealthValidationInner> + beginStartValidation(String resourceGroupName, String watcherName, String healthValidationName) { + return this.beginStartValidationAsync(resourceGroupName, watcherName, healthValidationName).getSyncPoller(); + } + + /** + * Starts health validation for a watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param healthValidationName The health validation resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, HealthValidationInner> beginStartValidation( + String resourceGroupName, String watcherName, String healthValidationName, Context context) { + return this.beginStartValidationAsync(resourceGroupName, watcherName, healthValidationName, context) + .getSyncPoller(); + } + + /** + * Starts health validation for a watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param healthValidationName The health validation resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono startValidationAsync(String resourceGroupName, String watcherName, + String healthValidationName) { + return beginStartValidationAsync(resourceGroupName, watcherName, healthValidationName).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Starts health validation for a watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param healthValidationName The health validation resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono startValidationAsync(String resourceGroupName, String watcherName, + String healthValidationName, Context context) { + return beginStartValidationAsync(resourceGroupName, watcherName, healthValidationName, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Starts health validation for a watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param healthValidationName The health validation resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public HealthValidationInner startValidation(String resourceGroupName, String watcherName, + String healthValidationName) { + return startValidationAsync(resourceGroupName, watcherName, healthValidationName).block(); + } + + /** + * Starts health validation for a watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param healthValidationName The health validation resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public HealthValidationInner startValidation(String resourceGroupName, String watcherName, + String healthValidationName, Context context) { + return startValidationAsync(resourceGroupName, watcherName, healthValidationName, context).block(); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a HealthValidation list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByParentNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listByParentNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a HealthValidation list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByParentNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listByParentNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/HealthValidationsImpl.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/HealthValidationsImpl.java new file mode 100644 index 000000000000..f030939b7c27 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/HealthValidationsImpl.java @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.databasewatcher.fluent.HealthValidationsClient; +import com.azure.resourcemanager.databasewatcher.fluent.models.HealthValidationInner; +import com.azure.resourcemanager.databasewatcher.models.HealthValidation; +import com.azure.resourcemanager.databasewatcher.models.HealthValidations; + +public final class HealthValidationsImpl implements HealthValidations { + private static final ClientLogger LOGGER = new ClientLogger(HealthValidationsImpl.class); + + private final HealthValidationsClient innerClient; + + private final com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager serviceManager; + + public HealthValidationsImpl(HealthValidationsClient innerClient, + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public Response getWithResponse(String resourceGroupName, String watcherName, + String healthValidationName, Context context) { + Response inner + = this.serviceClient().getWithResponse(resourceGroupName, watcherName, healthValidationName, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new HealthValidationImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public HealthValidation get(String resourceGroupName, String watcherName, String healthValidationName) { + HealthValidationInner inner = this.serviceClient().get(resourceGroupName, watcherName, healthValidationName); + if (inner != null) { + return new HealthValidationImpl(inner, this.manager()); + } else { + return null; + } + } + + public PagedIterable listByParent(String resourceGroupName, String watcherName) { + PagedIterable inner = this.serviceClient().listByParent(resourceGroupName, watcherName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new HealthValidationImpl(inner1, this.manager())); + } + + public PagedIterable listByParent(String resourceGroupName, String watcherName, Context context) { + PagedIterable inner + = this.serviceClient().listByParent(resourceGroupName, watcherName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new HealthValidationImpl(inner1, this.manager())); + } + + public HealthValidation startValidation(String resourceGroupName, String watcherName, String healthValidationName) { + HealthValidationInner inner + = this.serviceClient().startValidation(resourceGroupName, watcherName, healthValidationName); + if (inner != null) { + return new HealthValidationImpl(inner, this.manager()); + } else { + return null; + } + } + + public HealthValidation startValidation(String resourceGroupName, String watcherName, String healthValidationName, + Context context) { + HealthValidationInner inner + = this.serviceClient().startValidation(resourceGroupName, watcherName, healthValidationName, context); + if (inner != null) { + return new HealthValidationImpl(inner, this.manager()); + } else { + return null; + } + } + + private HealthValidationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/OperationImpl.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/OperationImpl.java new file mode 100644 index 000000000000..34fd447555f9 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/OperationImpl.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.implementation; + +import com.azure.resourcemanager.databasewatcher.fluent.models.OperationInner; +import com.azure.resourcemanager.databasewatcher.models.ActionType; +import com.azure.resourcemanager.databasewatcher.models.Operation; +import com.azure.resourcemanager.databasewatcher.models.OperationDisplay; +import com.azure.resourcemanager.databasewatcher.models.Origin; + +public final class OperationImpl implements Operation { + private OperationInner innerObject; + + private final com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager serviceManager; + + OperationImpl(OperationInner innerObject, + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String name() { + return this.innerModel().name(); + } + + public Boolean isDataAction() { + return this.innerModel().isDataAction(); + } + + public OperationDisplay display() { + return this.innerModel().display(); + } + + public Origin origin() { + return this.innerModel().origin(); + } + + public ActionType actionType() { + return this.innerModel().actionType(); + } + + public OperationInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/OperationsClientImpl.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/OperationsClientImpl.java new file mode 100644 index 000000000000..aa0b7fa53718 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/OperationsClientImpl.java @@ -0,0 +1,235 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.implementation; + +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.resourcemanager.databasewatcher.fluent.OperationsClient; +import com.azure.resourcemanager.databasewatcher.fluent.models.OperationInner; +import com.azure.resourcemanager.databasewatcher.implementation.models.OperationListResult; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in OperationsClient. + */ +public final class OperationsClientImpl implements OperationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final OperationsService service; + + /** + * The service client containing this operation class. + */ + private final DatabaseWatcherManagementClientImpl client; + + /** + * Initializes an instance of OperationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + OperationsClientImpl(DatabaseWatcherManagementClientImpl client) { + this.service + = RestProxy.create(OperationsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for DatabaseWatcherManagementClientOperations to be used by the proxy + * service to perform REST calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "DatabaseWatcherManag") + public interface OperationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/providers/Microsoft.DatabaseWatcher/operations") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> list(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listNext(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("endpoint") String endpoint, @HeaderParam("Accept") String accept, Context context); + } + + /** + * List the operations for the provider. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider along with {@link PagedResponse} on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync() { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.list(this.client.getEndpoint(), this.client.getApiVersion(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), + res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List the operations for the provider. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider along with {@link PagedResponse} on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync(Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.list(this.client.getEndpoint(), this.client.getApiVersion(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List the operations for the provider. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync() { + return new PagedFlux<>(() -> listSinglePageAsync(), nextLink -> listNextSinglePageAsync(nextLink)); + } + + /** + * List the operations for the provider. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync(Context context) { + return new PagedFlux<>(() -> listSinglePageAsync(context), + nextLink -> listNextSinglePageAsync(nextLink, context)); + } + + /** + * List the operations for the provider. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list() { + return new PagedIterable<>(listAsync()); + } + + /** + * List the operations for the provider. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(Context context) { + return new PagedIterable<>(listAsync(context)); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider along with {@link PagedResponse} on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.listNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), + res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider along with {@link PagedResponse} on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listNextSinglePageAsync(String nextLink, Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/OperationsImpl.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/OperationsImpl.java new file mode 100644 index 000000000000..f7ebfb5141c8 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/OperationsImpl.java @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.databasewatcher.fluent.OperationsClient; +import com.azure.resourcemanager.databasewatcher.fluent.models.OperationInner; +import com.azure.resourcemanager.databasewatcher.models.Operation; +import com.azure.resourcemanager.databasewatcher.models.Operations; + +public final class OperationsImpl implements Operations { + private static final ClientLogger LOGGER = new ClientLogger(OperationsImpl.class); + + private final OperationsClient innerClient; + + private final com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager serviceManager; + + public OperationsImpl(OperationsClient innerClient, + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public PagedIterable list() { + PagedIterable inner = this.serviceClient().list(); + return ResourceManagerUtils.mapPage(inner, inner1 -> new OperationImpl(inner1, this.manager())); + } + + public PagedIterable list(Context context) { + PagedIterable inner = this.serviceClient().list(context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new OperationImpl(inner1, this.manager())); + } + + private OperationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/ResourceManagerUtils.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/ResourceManagerUtils.java new file mode 100644 index 000000000000..801f3cc7f864 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/ResourceManagerUtils.java @@ -0,0 +1,195 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.implementation; + +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.util.CoreUtils; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import reactor.core.publisher.Flux; + +final class ResourceManagerUtils { + private ResourceManagerUtils() { + } + + static String getValueFromIdByName(String id, String name) { + if (id == null) { + return null; + } + Iterator itr = Arrays.stream(id.split("/")).iterator(); + while (itr.hasNext()) { + String part = itr.next(); + if (part != null && !part.trim().isEmpty()) { + if (part.equalsIgnoreCase(name)) { + if (itr.hasNext()) { + return itr.next(); + } else { + return null; + } + } + } + } + return null; + } + + static String getValueFromIdByParameterName(String id, String pathTemplate, String parameterName) { + if (id == null || pathTemplate == null) { + return null; + } + String parameterNameParentheses = "{" + parameterName + "}"; + List idSegmentsReverted = Arrays.asList(id.split("/")); + List pathSegments = Arrays.asList(pathTemplate.split("/")); + Collections.reverse(idSegmentsReverted); + Iterator idItrReverted = idSegmentsReverted.iterator(); + int pathIndex = pathSegments.size(); + while (idItrReverted.hasNext() && pathIndex > 0) { + String idSegment = idItrReverted.next(); + String pathSegment = pathSegments.get(--pathIndex); + if (!CoreUtils.isNullOrEmpty(idSegment) && !CoreUtils.isNullOrEmpty(pathSegment)) { + if (pathSegment.equalsIgnoreCase(parameterNameParentheses)) { + if (pathIndex == 0 || (pathIndex == 1 && pathSegments.get(0).isEmpty())) { + List segments = new ArrayList<>(); + segments.add(idSegment); + idItrReverted.forEachRemaining(segments::add); + Collections.reverse(segments); + if (!segments.isEmpty() && segments.get(0).isEmpty()) { + segments.remove(0); + } + return String.join("/", segments); + } else { + return idSegment; + } + } + } + } + return null; + } + + static PagedIterable mapPage(PagedIterable pageIterable, Function mapper) { + return new PagedIterableImpl<>(pageIterable, mapper); + } + + private static final class PagedIterableImpl extends PagedIterable { + + private final PagedIterable pagedIterable; + private final Function mapper; + private final Function, PagedResponse> pageMapper; + + private PagedIterableImpl(PagedIterable pagedIterable, Function mapper) { + super(PagedFlux.create(() -> (continuationToken, pageSize) -> Flux + .fromStream(pagedIterable.streamByPage().map(getPageMapper(mapper))))); + this.pagedIterable = pagedIterable; + this.mapper = mapper; + this.pageMapper = getPageMapper(mapper); + } + + private static Function, PagedResponse> getPageMapper(Function mapper) { + return page -> new PagedResponseBase(page.getRequest(), page.getStatusCode(), page.getHeaders(), + page.getElements().stream().map(mapper).collect(Collectors.toList()), page.getContinuationToken(), + null); + } + + @Override + public Stream stream() { + return pagedIterable.stream().map(mapper); + } + + @Override + public Stream> streamByPage() { + return pagedIterable.streamByPage().map(pageMapper); + } + + @Override + public Stream> streamByPage(String continuationToken) { + return pagedIterable.streamByPage(continuationToken).map(pageMapper); + } + + @Override + public Stream> streamByPage(int preferredPageSize) { + return pagedIterable.streamByPage(preferredPageSize).map(pageMapper); + } + + @Override + public Stream> streamByPage(String continuationToken, int preferredPageSize) { + return pagedIterable.streamByPage(continuationToken, preferredPageSize).map(pageMapper); + } + + @Override + public Iterator iterator() { + return new IteratorImpl<>(pagedIterable.iterator(), mapper); + } + + @Override + public Iterable> iterableByPage() { + return new IterableImpl<>(pagedIterable.iterableByPage(), pageMapper); + } + + @Override + public Iterable> iterableByPage(String continuationToken) { + return new IterableImpl<>(pagedIterable.iterableByPage(continuationToken), pageMapper); + } + + @Override + public Iterable> iterableByPage(int preferredPageSize) { + return new IterableImpl<>(pagedIterable.iterableByPage(preferredPageSize), pageMapper); + } + + @Override + public Iterable> iterableByPage(String continuationToken, int preferredPageSize) { + return new IterableImpl<>(pagedIterable.iterableByPage(continuationToken, preferredPageSize), pageMapper); + } + } + + private static final class IteratorImpl implements Iterator { + + private final Iterator iterator; + private final Function mapper; + + private IteratorImpl(Iterator iterator, Function mapper) { + this.iterator = iterator; + this.mapper = mapper; + } + + @Override + public boolean hasNext() { + return iterator.hasNext(); + } + + @Override + public S next() { + return mapper.apply(iterator.next()); + } + + @Override + public void remove() { + iterator.remove(); + } + } + + private static final class IterableImpl implements Iterable { + + private final Iterable iterable; + private final Function mapper; + + private IterableImpl(Iterable iterable, Function mapper) { + this.iterable = iterable; + this.mapper = mapper; + } + + @Override + public Iterator iterator() { + return new IteratorImpl<>(iterable.iterator(), mapper); + } + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/SharedPrivateLinkResourceImpl.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/SharedPrivateLinkResourceImpl.java new file mode 100644 index 000000000000..dede4872b725 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/SharedPrivateLinkResourceImpl.java @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.implementation; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.databasewatcher.fluent.models.SharedPrivateLinkResourceInner; +import com.azure.resourcemanager.databasewatcher.models.SharedPrivateLinkResource; +import com.azure.resourcemanager.databasewatcher.models.SharedPrivateLinkResourceProperties; + +public final class SharedPrivateLinkResourceImpl + implements SharedPrivateLinkResource, SharedPrivateLinkResource.Definition { + private SharedPrivateLinkResourceInner innerObject; + + private final com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager serviceManager; + + SharedPrivateLinkResourceImpl(SharedPrivateLinkResourceInner innerObject, + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public SharedPrivateLinkResourceProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public SharedPrivateLinkResourceInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager() { + return this.serviceManager; + } + + private String resourceGroupName; + + private String watcherName; + + private String sharedPrivateLinkResourceName; + + public SharedPrivateLinkResourceImpl withExistingWatcher(String resourceGroupName, String watcherName) { + this.resourceGroupName = resourceGroupName; + this.watcherName = watcherName; + return this; + } + + public SharedPrivateLinkResource create() { + this.innerObject = serviceManager.serviceClient() + .getSharedPrivateLinkResources() + .create(resourceGroupName, watcherName, sharedPrivateLinkResourceName, this.innerModel(), Context.NONE); + return this; + } + + public SharedPrivateLinkResource create(Context context) { + this.innerObject = serviceManager.serviceClient() + .getSharedPrivateLinkResources() + .create(resourceGroupName, watcherName, sharedPrivateLinkResourceName, this.innerModel(), context); + return this; + } + + SharedPrivateLinkResourceImpl(String name, + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager serviceManager) { + this.innerObject = new SharedPrivateLinkResourceInner(); + this.serviceManager = serviceManager; + this.sharedPrivateLinkResourceName = name; + } + + public SharedPrivateLinkResource refresh() { + this.innerObject = serviceManager.serviceClient() + .getSharedPrivateLinkResources() + .getWithResponse(resourceGroupName, watcherName, sharedPrivateLinkResourceName, Context.NONE) + .getValue(); + return this; + } + + public SharedPrivateLinkResource refresh(Context context) { + this.innerObject = serviceManager.serviceClient() + .getSharedPrivateLinkResources() + .getWithResponse(resourceGroupName, watcherName, sharedPrivateLinkResourceName, context) + .getValue(); + return this; + } + + public SharedPrivateLinkResourceImpl withProperties(SharedPrivateLinkResourceProperties properties) { + this.innerModel().withProperties(properties); + return this; + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/SharedPrivateLinkResourcesClientImpl.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/SharedPrivateLinkResourcesClientImpl.java new file mode 100644 index 000000000000..408c57edb304 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/SharedPrivateLinkResourcesClientImpl.java @@ -0,0 +1,949 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Put; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.core.util.polling.PollerFlux; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.databasewatcher.fluent.SharedPrivateLinkResourcesClient; +import com.azure.resourcemanager.databasewatcher.fluent.models.SharedPrivateLinkResourceInner; +import com.azure.resourcemanager.databasewatcher.implementation.models.SharedPrivateLinkResourceListResult; +import java.nio.ByteBuffer; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in SharedPrivateLinkResourcesClient. + */ +public final class SharedPrivateLinkResourcesClientImpl implements SharedPrivateLinkResourcesClient { + /** + * The proxy service used to perform REST calls. + */ + private final SharedPrivateLinkResourcesService service; + + /** + * The service client containing this operation class. + */ + private final DatabaseWatcherManagementClientImpl client; + + /** + * Initializes an instance of SharedPrivateLinkResourcesClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + SharedPrivateLinkResourcesClientImpl(DatabaseWatcherManagementClientImpl client) { + this.service = RestProxy.create(SharedPrivateLinkResourcesService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for DatabaseWatcherManagementClientSharedPrivateLinkResources to be used + * by the proxy service to perform REST calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "DatabaseWatcherManag") + public interface SharedPrivateLinkResourcesService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("watcherName") String watcherName, + @PathParam("sharedPrivateLinkResourceName") String sharedPrivateLinkResourceName, + @HeaderParam("Accept") String accept, Context context); + + @Put("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> create(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("watcherName") String watcherName, + @PathParam("sharedPrivateLinkResourceName") String sharedPrivateLinkResourceName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") SharedPrivateLinkResourceInner resource, Context context); + + @Headers({ "Content-Type: application/json" }) + @Delete("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}") + @ExpectedResponses({ 202, 204 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> delete(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("watcherName") String watcherName, + @PathParam("sharedPrivateLinkResourceName") String sharedPrivateLinkResourceName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/sharedPrivateLinkResources") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByWatcher(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("watcherName") String watcherName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByWatcherNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * Get a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SharedPrivateLinkResource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, + String watcherName, String sharedPrivateLinkResourceName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + if (sharedPrivateLinkResourceName == null) { + return Mono.error(new IllegalArgumentException( + "Parameter sharedPrivateLinkResourceName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, watcherName, sharedPrivateLinkResourceName, accept, + context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SharedPrivateLinkResource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, + String watcherName, String sharedPrivateLinkResourceName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + if (sharedPrivateLinkResourceName == null) { + return Mono.error(new IllegalArgumentException( + "Parameter sharedPrivateLinkResourceName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, watcherName, sharedPrivateLinkResourceName, accept, context); + } + + /** + * Get a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SharedPrivateLinkResource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceGroupName, String watcherName, + String sharedPrivateLinkResourceName) { + return getWithResponseAsync(resourceGroupName, watcherName, sharedPrivateLinkResourceName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SharedPrivateLinkResource along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceGroupName, String watcherName, + String sharedPrivateLinkResourceName, Context context) { + return getWithResponseAsync(resourceGroupName, watcherName, sharedPrivateLinkResourceName, context).block(); + } + + /** + * Get a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SharedPrivateLinkResource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public SharedPrivateLinkResourceInner get(String resourceGroupName, String watcherName, + String sharedPrivateLinkResourceName) { + return getWithResponse(resourceGroupName, watcherName, sharedPrivateLinkResourceName, Context.NONE).getValue(); + } + + /** + * Create a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete proxy resource types can be created by aliasing this type using a specific property type along + * with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createWithResponseAsync(String resourceGroupName, String watcherName, + String sharedPrivateLinkResourceName, SharedPrivateLinkResourceInner resource) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + if (sharedPrivateLinkResourceName == null) { + return Mono.error(new IllegalArgumentException( + "Parameter sharedPrivateLinkResourceName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.create(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, watcherName, sharedPrivateLinkResourceName, + contentType, accept, resource, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Create a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete proxy resource types can be created by aliasing this type using a specific property type along + * with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createWithResponseAsync(String resourceGroupName, String watcherName, + String sharedPrivateLinkResourceName, SharedPrivateLinkResourceInner resource, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + if (sharedPrivateLinkResourceName == null) { + return Mono.error(new IllegalArgumentException( + "Parameter sharedPrivateLinkResourceName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.create(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, watcherName, sharedPrivateLinkResourceName, contentType, accept, resource, context); + } + + /** + * Create a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of concrete proxy resource types can be created by aliasing this type + * using a specific property type. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, SharedPrivateLinkResourceInner> beginCreateAsync( + String resourceGroupName, String watcherName, String sharedPrivateLinkResourceName, + SharedPrivateLinkResourceInner resource) { + Mono>> mono + = createWithResponseAsync(resourceGroupName, watcherName, sharedPrivateLinkResourceName, resource); + return this.client.getLroResult(mono, + this.client.getHttpPipeline(), SharedPrivateLinkResourceInner.class, SharedPrivateLinkResourceInner.class, + this.client.getContext()); + } + + /** + * Create a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of concrete proxy resource types can be created by aliasing this type + * using a specific property type. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, SharedPrivateLinkResourceInner> beginCreateAsync( + String resourceGroupName, String watcherName, String sharedPrivateLinkResourceName, + SharedPrivateLinkResourceInner resource, Context context) { + context = this.client.mergeContext(context); + Mono>> mono + = createWithResponseAsync(resourceGroupName, watcherName, sharedPrivateLinkResourceName, resource, context); + return this.client.getLroResult(mono, + this.client.getHttpPipeline(), SharedPrivateLinkResourceInner.class, SharedPrivateLinkResourceInner.class, + context); + } + + /** + * Create a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of concrete proxy resource types can be created by aliasing this type + * using a specific property type. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, SharedPrivateLinkResourceInner> beginCreate( + String resourceGroupName, String watcherName, String sharedPrivateLinkResourceName, + SharedPrivateLinkResourceInner resource) { + return this.beginCreateAsync(resourceGroupName, watcherName, sharedPrivateLinkResourceName, resource) + .getSyncPoller(); + } + + /** + * Create a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of concrete proxy resource types can be created by aliasing this type + * using a specific property type. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, SharedPrivateLinkResourceInner> beginCreate( + String resourceGroupName, String watcherName, String sharedPrivateLinkResourceName, + SharedPrivateLinkResourceInner resource, Context context) { + return this.beginCreateAsync(resourceGroupName, watcherName, sharedPrivateLinkResourceName, resource, context) + .getSyncPoller(); + } + + /** + * Create a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete proxy resource types can be created by aliasing this type using a specific property type on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createAsync(String resourceGroupName, String watcherName, + String sharedPrivateLinkResourceName, SharedPrivateLinkResourceInner resource) { + return beginCreateAsync(resourceGroupName, watcherName, sharedPrivateLinkResourceName, resource).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete proxy resource types can be created by aliasing this type using a specific property type on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createAsync(String resourceGroupName, String watcherName, + String sharedPrivateLinkResourceName, SharedPrivateLinkResourceInner resource, Context context) { + return beginCreateAsync(resourceGroupName, watcherName, sharedPrivateLinkResourceName, resource, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete proxy resource types can be created by aliasing this type using a specific property type. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public SharedPrivateLinkResourceInner create(String resourceGroupName, String watcherName, + String sharedPrivateLinkResourceName, SharedPrivateLinkResourceInner resource) { + return createAsync(resourceGroupName, watcherName, sharedPrivateLinkResourceName, resource).block(); + } + + /** + * Create a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete proxy resource types can be created by aliasing this type using a specific property type. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public SharedPrivateLinkResourceInner create(String resourceGroupName, String watcherName, + String sharedPrivateLinkResourceName, SharedPrivateLinkResourceInner resource, Context context) { + return createAsync(resourceGroupName, watcherName, sharedPrivateLinkResourceName, resource, context).block(); + } + + /** + * Delete a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> deleteWithResponseAsync(String resourceGroupName, String watcherName, + String sharedPrivateLinkResourceName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + if (sharedPrivateLinkResourceName == null) { + return Mono.error(new IllegalArgumentException( + "Parameter sharedPrivateLinkResourceName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.delete(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, watcherName, sharedPrivateLinkResourceName, accept, + context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Delete a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> deleteWithResponseAsync(String resourceGroupName, String watcherName, + String sharedPrivateLinkResourceName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + if (sharedPrivateLinkResourceName == null) { + return Mono.error(new IllegalArgumentException( + "Parameter sharedPrivateLinkResourceName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.delete(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, watcherName, sharedPrivateLinkResourceName, accept, context); + } + + /** + * Delete a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, Void> beginDeleteAsync(String resourceGroupName, String watcherName, + String sharedPrivateLinkResourceName) { + Mono>> mono + = deleteWithResponseAsync(resourceGroupName, watcherName, sharedPrivateLinkResourceName); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), Void.class, Void.class, + this.client.getContext()); + } + + /** + * Delete a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, Void> beginDeleteAsync(String resourceGroupName, String watcherName, + String sharedPrivateLinkResourceName, Context context) { + context = this.client.mergeContext(context); + Mono>> mono + = deleteWithResponseAsync(resourceGroupName, watcherName, sharedPrivateLinkResourceName, context); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), Void.class, Void.class, + context); + } + + /** + * Delete a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, Void> beginDelete(String resourceGroupName, String watcherName, + String sharedPrivateLinkResourceName) { + return this.beginDeleteAsync(resourceGroupName, watcherName, sharedPrivateLinkResourceName).getSyncPoller(); + } + + /** + * Delete a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, Void> beginDelete(String resourceGroupName, String watcherName, + String sharedPrivateLinkResourceName, Context context) { + return this.beginDeleteAsync(resourceGroupName, watcherName, sharedPrivateLinkResourceName, context) + .getSyncPoller(); + } + + /** + * Delete a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono deleteAsync(String resourceGroupName, String watcherName, String sharedPrivateLinkResourceName) { + return beginDeleteAsync(resourceGroupName, watcherName, sharedPrivateLinkResourceName).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Delete a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono deleteAsync(String resourceGroupName, String watcherName, String sharedPrivateLinkResourceName, + Context context) { + return beginDeleteAsync(resourceGroupName, watcherName, sharedPrivateLinkResourceName, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Delete a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String resourceGroupName, String watcherName, String sharedPrivateLinkResourceName) { + deleteAsync(resourceGroupName, watcherName, sharedPrivateLinkResourceName).block(); + } + + /** + * Delete a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String resourceGroupName, String watcherName, String sharedPrivateLinkResourceName, + Context context) { + deleteAsync(resourceGroupName, watcherName, sharedPrivateLinkResourceName, context).block(); + } + + /** + * List SharedPrivateLinkResource resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SharedPrivateLinkResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByWatcherSinglePageAsync(String resourceGroupName, + String watcherName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listByWatcher(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, watcherName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List SharedPrivateLinkResource resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SharedPrivateLinkResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByWatcherSinglePageAsync(String resourceGroupName, + String watcherName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByWatcher(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, watcherName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List SharedPrivateLinkResource resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SharedPrivateLinkResource list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByWatcherAsync(String resourceGroupName, String watcherName) { + return new PagedFlux<>(() -> listByWatcherSinglePageAsync(resourceGroupName, watcherName), + nextLink -> listByWatcherNextSinglePageAsync(nextLink)); + } + + /** + * List SharedPrivateLinkResource resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SharedPrivateLinkResource list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByWatcherAsync(String resourceGroupName, String watcherName, + Context context) { + return new PagedFlux<>(() -> listByWatcherSinglePageAsync(resourceGroupName, watcherName, context), + nextLink -> listByWatcherNextSinglePageAsync(nextLink, context)); + } + + /** + * List SharedPrivateLinkResource resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SharedPrivateLinkResource list operation as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByWatcher(String resourceGroupName, String watcherName) { + return new PagedIterable<>(listByWatcherAsync(resourceGroupName, watcherName)); + } + + /** + * List SharedPrivateLinkResource resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SharedPrivateLinkResource list operation as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByWatcher(String resourceGroupName, String watcherName, + Context context) { + return new PagedIterable<>(listByWatcherAsync(resourceGroupName, watcherName, context)); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SharedPrivateLinkResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByWatcherNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listByWatcherNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SharedPrivateLinkResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByWatcherNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listByWatcherNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/SharedPrivateLinkResourcesImpl.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/SharedPrivateLinkResourcesImpl.java new file mode 100644 index 000000000000..7df270f850b5 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/SharedPrivateLinkResourcesImpl.java @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.databasewatcher.fluent.SharedPrivateLinkResourcesClient; +import com.azure.resourcemanager.databasewatcher.fluent.models.SharedPrivateLinkResourceInner; +import com.azure.resourcemanager.databasewatcher.models.SharedPrivateLinkResource; +import com.azure.resourcemanager.databasewatcher.models.SharedPrivateLinkResources; + +public final class SharedPrivateLinkResourcesImpl implements SharedPrivateLinkResources { + private static final ClientLogger LOGGER = new ClientLogger(SharedPrivateLinkResourcesImpl.class); + + private final SharedPrivateLinkResourcesClient innerClient; + + private final com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager serviceManager; + + public SharedPrivateLinkResourcesImpl(SharedPrivateLinkResourcesClient innerClient, + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public Response getWithResponse(String resourceGroupName, String watcherName, + String sharedPrivateLinkResourceName, Context context) { + Response inner = this.serviceClient() + .getWithResponse(resourceGroupName, watcherName, sharedPrivateLinkResourceName, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new SharedPrivateLinkResourceImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public SharedPrivateLinkResource get(String resourceGroupName, String watcherName, + String sharedPrivateLinkResourceName) { + SharedPrivateLinkResourceInner inner + = this.serviceClient().get(resourceGroupName, watcherName, sharedPrivateLinkResourceName); + if (inner != null) { + return new SharedPrivateLinkResourceImpl(inner, this.manager()); + } else { + return null; + } + } + + public void delete(String resourceGroupName, String watcherName, String sharedPrivateLinkResourceName) { + this.serviceClient().delete(resourceGroupName, watcherName, sharedPrivateLinkResourceName); + } + + public void delete(String resourceGroupName, String watcherName, String sharedPrivateLinkResourceName, + Context context) { + this.serviceClient().delete(resourceGroupName, watcherName, sharedPrivateLinkResourceName, context); + } + + public PagedIterable listByWatcher(String resourceGroupName, String watcherName) { + PagedIterable inner + = this.serviceClient().listByWatcher(resourceGroupName, watcherName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new SharedPrivateLinkResourceImpl(inner1, this.manager())); + } + + public PagedIterable listByWatcher(String resourceGroupName, String watcherName, + Context context) { + PagedIterable inner + = this.serviceClient().listByWatcher(resourceGroupName, watcherName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new SharedPrivateLinkResourceImpl(inner1, this.manager())); + } + + public SharedPrivateLinkResource getById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String watcherName = ResourceManagerUtils.getValueFromIdByName(id, "watchers"); + if (watcherName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'watchers'.", id))); + } + String sharedPrivateLinkResourceName + = ResourceManagerUtils.getValueFromIdByName(id, "sharedPrivateLinkResources"); + if (sharedPrivateLinkResourceName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException(String + .format("The resource ID '%s' is not valid. Missing path segment 'sharedPrivateLinkResources'.", id))); + } + return this.getWithResponse(resourceGroupName, watcherName, sharedPrivateLinkResourceName, Context.NONE) + .getValue(); + } + + public Response getByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String watcherName = ResourceManagerUtils.getValueFromIdByName(id, "watchers"); + if (watcherName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'watchers'.", id))); + } + String sharedPrivateLinkResourceName + = ResourceManagerUtils.getValueFromIdByName(id, "sharedPrivateLinkResources"); + if (sharedPrivateLinkResourceName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException(String + .format("The resource ID '%s' is not valid. Missing path segment 'sharedPrivateLinkResources'.", id))); + } + return this.getWithResponse(resourceGroupName, watcherName, sharedPrivateLinkResourceName, context); + } + + public void deleteById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String watcherName = ResourceManagerUtils.getValueFromIdByName(id, "watchers"); + if (watcherName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'watchers'.", id))); + } + String sharedPrivateLinkResourceName + = ResourceManagerUtils.getValueFromIdByName(id, "sharedPrivateLinkResources"); + if (sharedPrivateLinkResourceName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException(String + .format("The resource ID '%s' is not valid. Missing path segment 'sharedPrivateLinkResources'.", id))); + } + this.delete(resourceGroupName, watcherName, sharedPrivateLinkResourceName, Context.NONE); + } + + public void deleteByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String watcherName = ResourceManagerUtils.getValueFromIdByName(id, "watchers"); + if (watcherName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'watchers'.", id))); + } + String sharedPrivateLinkResourceName + = ResourceManagerUtils.getValueFromIdByName(id, "sharedPrivateLinkResources"); + if (sharedPrivateLinkResourceName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException(String + .format("The resource ID '%s' is not valid. Missing path segment 'sharedPrivateLinkResources'.", id))); + } + this.delete(resourceGroupName, watcherName, sharedPrivateLinkResourceName, context); + } + + private SharedPrivateLinkResourcesClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager() { + return this.serviceManager; + } + + public SharedPrivateLinkResourceImpl define(String name) { + return new SharedPrivateLinkResourceImpl(name, this.manager()); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/TargetImpl.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/TargetImpl.java new file mode 100644 index 000000000000..87cb4dadf2e1 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/TargetImpl.java @@ -0,0 +1,133 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.implementation; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.databasewatcher.fluent.models.TargetInner; +import com.azure.resourcemanager.databasewatcher.models.Target; +import com.azure.resourcemanager.databasewatcher.models.TargetProperties; + +public final class TargetImpl implements Target, Target.Definition, Target.Update { + private TargetInner innerObject; + + private final com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager serviceManager; + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public TargetProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public String resourceGroupName() { + return resourceGroupName; + } + + public TargetInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager() { + return this.serviceManager; + } + + private String resourceGroupName; + + private String watcherName; + + private String targetName; + + public TargetImpl withExistingWatcher(String resourceGroupName, String watcherName) { + this.resourceGroupName = resourceGroupName; + this.watcherName = watcherName; + return this; + } + + public Target create() { + this.innerObject = serviceManager.serviceClient() + .getTargets() + .createOrUpdateWithResponse(resourceGroupName, watcherName, targetName, this.innerModel(), Context.NONE) + .getValue(); + return this; + } + + public Target create(Context context) { + this.innerObject = serviceManager.serviceClient() + .getTargets() + .createOrUpdateWithResponse(resourceGroupName, watcherName, targetName, this.innerModel(), context) + .getValue(); + return this; + } + + TargetImpl(String name, com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager serviceManager) { + this.innerObject = new TargetInner(); + this.serviceManager = serviceManager; + this.targetName = name; + } + + public TargetImpl update() { + return this; + } + + public Target apply() { + this.innerObject = serviceManager.serviceClient() + .getTargets() + .createOrUpdateWithResponse(resourceGroupName, watcherName, targetName, this.innerModel(), Context.NONE) + .getValue(); + return this; + } + + public Target apply(Context context) { + this.innerObject = serviceManager.serviceClient() + .getTargets() + .createOrUpdateWithResponse(resourceGroupName, watcherName, targetName, this.innerModel(), context) + .getValue(); + return this; + } + + TargetImpl(TargetInner innerObject, + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + this.resourceGroupName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "resourceGroups"); + this.watcherName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "watchers"); + this.targetName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "targets"); + } + + public Target refresh() { + this.innerObject = serviceManager.serviceClient() + .getTargets() + .getWithResponse(resourceGroupName, watcherName, targetName, Context.NONE) + .getValue(); + return this; + } + + public Target refresh(Context context) { + this.innerObject = serviceManager.serviceClient() + .getTargets() + .getWithResponse(resourceGroupName, watcherName, targetName, context) + .getValue(); + return this; + } + + public TargetImpl withProperties(TargetProperties properties) { + this.innerModel().withProperties(properties); + return this; + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/TargetsClientImpl.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/TargetsClientImpl.java new file mode 100644 index 000000000000..2e4f2eedf6d3 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/TargetsClientImpl.java @@ -0,0 +1,717 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Put; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.resourcemanager.databasewatcher.fluent.TargetsClient; +import com.azure.resourcemanager.databasewatcher.fluent.models.TargetInner; +import com.azure.resourcemanager.databasewatcher.implementation.models.TargetListResult; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in TargetsClient. + */ +public final class TargetsClientImpl implements TargetsClient { + /** + * The proxy service used to perform REST calls. + */ + private final TargetsService service; + + /** + * The service client containing this operation class. + */ + private final DatabaseWatcherManagementClientImpl client; + + /** + * Initializes an instance of TargetsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + TargetsClientImpl(DatabaseWatcherManagementClientImpl client) { + this.service = RestProxy.create(TargetsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for DatabaseWatcherManagementClientTargets to be used by the proxy + * service to perform REST calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "DatabaseWatcherManag") + public interface TargetsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/targets/{targetName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("watcherName") String watcherName, + @PathParam("targetName") String targetName, @HeaderParam("Accept") String accept, Context context); + + @Put("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/targets/{targetName}") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> createOrUpdate(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("watcherName") String watcherName, + @PathParam("targetName") String targetName, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") TargetInner resource, Context context); + + @Headers({ "Content-Type: application/json" }) + @Delete("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/targets/{targetName}") + @ExpectedResponses({ 200, 204 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> delete(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("watcherName") String watcherName, + @PathParam("targetName") String targetName, @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/targets") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByWatcher(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("watcherName") String watcherName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByWatcherNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * Get a Target. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param targetName The target resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Target along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String watcherName, + String targetName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + if (targetName == null) { + return Mono.error(new IllegalArgumentException("Parameter targetName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, watcherName, targetName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a Target. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param targetName The target resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Target along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String watcherName, + String targetName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + if (targetName == null) { + return Mono.error(new IllegalArgumentException("Parameter targetName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, watcherName, targetName, accept, context); + } + + /** + * Get a Target. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param targetName The target resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Target on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceGroupName, String watcherName, String targetName) { + return getWithResponseAsync(resourceGroupName, watcherName, targetName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a Target. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param targetName The target resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Target along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceGroupName, String watcherName, String targetName, + Context context) { + return getWithResponseAsync(resourceGroupName, watcherName, targetName, context).block(); + } + + /** + * Get a Target. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param targetName The target resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Target. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public TargetInner get(String resourceGroupName, String watcherName, String targetName) { + return getWithResponse(resourceGroupName, watcherName, targetName, Context.NONE).getValue(); + } + + /** + * Create a Target. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param targetName The target resource name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete proxy resource types can be created by aliasing this type using a specific property type along + * with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> createOrUpdateWithResponseAsync(String resourceGroupName, String watcherName, + String targetName, TargetInner resource) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + if (targetName == null) { + return Mono.error(new IllegalArgumentException("Parameter targetName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.createOrUpdate(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, watcherName, targetName, contentType, accept, + resource, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Create a Target. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param targetName The target resource name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete proxy resource types can be created by aliasing this type using a specific property type along + * with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> createOrUpdateWithResponseAsync(String resourceGroupName, String watcherName, + String targetName, TargetInner resource, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + if (targetName == null) { + return Mono.error(new IllegalArgumentException("Parameter targetName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.createOrUpdate(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, watcherName, targetName, contentType, accept, resource, + context); + } + + /** + * Create a Target. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param targetName The target resource name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete proxy resource types can be created by aliasing this type using a specific property type on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createOrUpdateAsync(String resourceGroupName, String watcherName, String targetName, + TargetInner resource) { + return createOrUpdateWithResponseAsync(resourceGroupName, watcherName, targetName, resource) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Create a Target. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param targetName The target resource name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete proxy resource types can be created by aliasing this type using a specific property type along + * with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createOrUpdateWithResponse(String resourceGroupName, String watcherName, + String targetName, TargetInner resource, Context context) { + return createOrUpdateWithResponseAsync(resourceGroupName, watcherName, targetName, resource, context).block(); + } + + /** + * Create a Target. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param targetName The target resource name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete proxy resource types can be created by aliasing this type using a specific property type. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public TargetInner createOrUpdate(String resourceGroupName, String watcherName, String targetName, + TargetInner resource) { + return createOrUpdateWithResponse(resourceGroupName, watcherName, targetName, resource, Context.NONE) + .getValue(); + } + + /** + * Delete a Target. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param targetName The target resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String watcherName, + String targetName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + if (targetName == null) { + return Mono.error(new IllegalArgumentException("Parameter targetName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.delete(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, watcherName, targetName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Delete a Target. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param targetName The target resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String watcherName, + String targetName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + if (targetName == null) { + return Mono.error(new IllegalArgumentException("Parameter targetName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.delete(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, watcherName, targetName, accept, context); + } + + /** + * Delete a Target. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param targetName The target resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono deleteAsync(String resourceGroupName, String watcherName, String targetName) { + return deleteWithResponseAsync(resourceGroupName, watcherName, targetName).flatMap(ignored -> Mono.empty()); + } + + /** + * Delete a Target. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param targetName The target resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String resourceGroupName, String watcherName, String targetName, + Context context) { + return deleteWithResponseAsync(resourceGroupName, watcherName, targetName, context).block(); + } + + /** + * Delete a Target. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param targetName The target resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String resourceGroupName, String watcherName, String targetName) { + deleteWithResponse(resourceGroupName, watcherName, targetName, Context.NONE); + } + + /** + * List Target resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Target list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByWatcherSinglePageAsync(String resourceGroupName, + String watcherName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listByWatcher(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, watcherName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), + res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List Target resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Target list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByWatcherSinglePageAsync(String resourceGroupName, String watcherName, + Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByWatcher(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, watcherName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List Target resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Target list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByWatcherAsync(String resourceGroupName, String watcherName) { + return new PagedFlux<>(() -> listByWatcherSinglePageAsync(resourceGroupName, watcherName), + nextLink -> listByWatcherNextSinglePageAsync(nextLink)); + } + + /** + * List Target resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Target list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByWatcherAsync(String resourceGroupName, String watcherName, Context context) { + return new PagedFlux<>(() -> listByWatcherSinglePageAsync(resourceGroupName, watcherName, context), + nextLink -> listByWatcherNextSinglePageAsync(nextLink, context)); + } + + /** + * List Target resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Target list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByWatcher(String resourceGroupName, String watcherName) { + return new PagedIterable<>(listByWatcherAsync(resourceGroupName, watcherName)); + } + + /** + * List Target resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Target list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByWatcher(String resourceGroupName, String watcherName, Context context) { + return new PagedIterable<>(listByWatcherAsync(resourceGroupName, watcherName, context)); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Target list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByWatcherNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listByWatcherNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), + res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Target list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByWatcherNextSinglePageAsync(String nextLink, Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listByWatcherNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/TargetsImpl.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/TargetsImpl.java new file mode 100644 index 000000000000..fbae2592fee7 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/TargetsImpl.java @@ -0,0 +1,157 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.databasewatcher.fluent.TargetsClient; +import com.azure.resourcemanager.databasewatcher.fluent.models.TargetInner; +import com.azure.resourcemanager.databasewatcher.models.Target; +import com.azure.resourcemanager.databasewatcher.models.Targets; + +public final class TargetsImpl implements Targets { + private static final ClientLogger LOGGER = new ClientLogger(TargetsImpl.class); + + private final TargetsClient innerClient; + + private final com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager serviceManager; + + public TargetsImpl(TargetsClient innerClient, + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public Response getWithResponse(String resourceGroupName, String watcherName, String targetName, + Context context) { + Response inner + = this.serviceClient().getWithResponse(resourceGroupName, watcherName, targetName, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new TargetImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public Target get(String resourceGroupName, String watcherName, String targetName) { + TargetInner inner = this.serviceClient().get(resourceGroupName, watcherName, targetName); + if (inner != null) { + return new TargetImpl(inner, this.manager()); + } else { + return null; + } + } + + public Response deleteWithResponse(String resourceGroupName, String watcherName, String targetName, + Context context) { + return this.serviceClient().deleteWithResponse(resourceGroupName, watcherName, targetName, context); + } + + public void delete(String resourceGroupName, String watcherName, String targetName) { + this.serviceClient().delete(resourceGroupName, watcherName, targetName); + } + + public PagedIterable listByWatcher(String resourceGroupName, String watcherName) { + PagedIterable inner = this.serviceClient().listByWatcher(resourceGroupName, watcherName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new TargetImpl(inner1, this.manager())); + } + + public PagedIterable listByWatcher(String resourceGroupName, String watcherName, Context context) { + PagedIterable inner = this.serviceClient().listByWatcher(resourceGroupName, watcherName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new TargetImpl(inner1, this.manager())); + } + + public Target getById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String watcherName = ResourceManagerUtils.getValueFromIdByName(id, "watchers"); + if (watcherName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'watchers'.", id))); + } + String targetName = ResourceManagerUtils.getValueFromIdByName(id, "targets"); + if (targetName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'targets'.", id))); + } + return this.getWithResponse(resourceGroupName, watcherName, targetName, Context.NONE).getValue(); + } + + public Response getByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String watcherName = ResourceManagerUtils.getValueFromIdByName(id, "watchers"); + if (watcherName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'watchers'.", id))); + } + String targetName = ResourceManagerUtils.getValueFromIdByName(id, "targets"); + if (targetName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'targets'.", id))); + } + return this.getWithResponse(resourceGroupName, watcherName, targetName, context); + } + + public void deleteById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String watcherName = ResourceManagerUtils.getValueFromIdByName(id, "watchers"); + if (watcherName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'watchers'.", id))); + } + String targetName = ResourceManagerUtils.getValueFromIdByName(id, "targets"); + if (targetName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'targets'.", id))); + } + this.deleteWithResponse(resourceGroupName, watcherName, targetName, Context.NONE); + } + + public Response deleteByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String watcherName = ResourceManagerUtils.getValueFromIdByName(id, "watchers"); + if (watcherName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'watchers'.", id))); + } + String targetName = ResourceManagerUtils.getValueFromIdByName(id, "targets"); + if (targetName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'targets'.", id))); + } + return this.deleteWithResponse(resourceGroupName, watcherName, targetName, context); + } + + private TargetsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager() { + return this.serviceManager; + } + + public TargetImpl define(String name) { + return new TargetImpl(name, this.manager()); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/WatcherImpl.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/WatcherImpl.java new file mode 100644 index 000000000000..f06eaa7ed787 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/WatcherImpl.java @@ -0,0 +1,214 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.implementation; + +import com.azure.core.management.Region; +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.databasewatcher.fluent.models.WatcherInner; +import com.azure.resourcemanager.databasewatcher.models.ManagedServiceIdentityV4; +import com.azure.resourcemanager.databasewatcher.models.Watcher; +import com.azure.resourcemanager.databasewatcher.models.WatcherProperties; +import com.azure.resourcemanager.databasewatcher.models.WatcherUpdate; +import com.azure.resourcemanager.databasewatcher.models.WatcherUpdateProperties; +import java.util.Collections; +import java.util.Map; + +public final class WatcherImpl implements Watcher, Watcher.Definition, Watcher.Update { + private WatcherInner innerObject; + + private final com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager serviceManager; + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public String location() { + return this.innerModel().location(); + } + + public Map tags() { + Map inner = this.innerModel().tags(); + if (inner != null) { + return Collections.unmodifiableMap(inner); + } else { + return Collections.emptyMap(); + } + } + + public WatcherProperties properties() { + return this.innerModel().properties(); + } + + public ManagedServiceIdentityV4 identity() { + return this.innerModel().identity(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public Region region() { + return Region.fromName(this.regionName()); + } + + public String regionName() { + return this.location(); + } + + public String resourceGroupName() { + return resourceGroupName; + } + + public WatcherInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager() { + return this.serviceManager; + } + + private String resourceGroupName; + + private String watcherName; + + private WatcherUpdate updateProperties; + + public WatcherImpl withExistingResourceGroup(String resourceGroupName) { + this.resourceGroupName = resourceGroupName; + return this; + } + + public Watcher create() { + this.innerObject = serviceManager.serviceClient() + .getWatchers() + .createOrUpdate(resourceGroupName, watcherName, this.innerModel(), Context.NONE); + return this; + } + + public Watcher create(Context context) { + this.innerObject = serviceManager.serviceClient() + .getWatchers() + .createOrUpdate(resourceGroupName, watcherName, this.innerModel(), context); + return this; + } + + WatcherImpl(String name, com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager serviceManager) { + this.innerObject = new WatcherInner(); + this.serviceManager = serviceManager; + this.watcherName = name; + } + + public WatcherImpl update() { + this.updateProperties = new WatcherUpdate(); + return this; + } + + public Watcher apply() { + this.innerObject = serviceManager.serviceClient() + .getWatchers() + .update(resourceGroupName, watcherName, updateProperties, Context.NONE); + return this; + } + + public Watcher apply(Context context) { + this.innerObject = serviceManager.serviceClient() + .getWatchers() + .update(resourceGroupName, watcherName, updateProperties, context); + return this; + } + + WatcherImpl(WatcherInner innerObject, + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + this.resourceGroupName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "resourceGroups"); + this.watcherName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "watchers"); + } + + public Watcher refresh() { + this.innerObject = serviceManager.serviceClient() + .getWatchers() + .getByResourceGroupWithResponse(resourceGroupName, watcherName, Context.NONE) + .getValue(); + return this; + } + + public Watcher refresh(Context context) { + this.innerObject = serviceManager.serviceClient() + .getWatchers() + .getByResourceGroupWithResponse(resourceGroupName, watcherName, context) + .getValue(); + return this; + } + + public Watcher start() { + return serviceManager.watchers().start(resourceGroupName, watcherName); + } + + public Watcher start(Context context) { + return serviceManager.watchers().start(resourceGroupName, watcherName, context); + } + + public Watcher stop() { + return serviceManager.watchers().stop(resourceGroupName, watcherName); + } + + public Watcher stop(Context context) { + return serviceManager.watchers().stop(resourceGroupName, watcherName, context); + } + + public WatcherImpl withRegion(Region location) { + this.innerModel().withLocation(location.toString()); + return this; + } + + public WatcherImpl withRegion(String location) { + this.innerModel().withLocation(location); + return this; + } + + public WatcherImpl withTags(Map tags) { + if (isInCreateMode()) { + this.innerModel().withTags(tags); + return this; + } else { + this.updateProperties.withTags(tags); + return this; + } + } + + public WatcherImpl withProperties(WatcherProperties properties) { + this.innerModel().withProperties(properties); + return this; + } + + public WatcherImpl withIdentity(ManagedServiceIdentityV4 identity) { + if (isInCreateMode()) { + this.innerModel().withIdentity(identity); + return this; + } else { + this.updateProperties.withIdentity(identity); + return this; + } + } + + public WatcherImpl withProperties(WatcherUpdateProperties properties) { + this.updateProperties.withProperties(properties); + return this; + } + + private boolean isInCreateMode() { + return this.innerModel().id() == null; + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/WatchersClientImpl.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/WatchersClientImpl.java new file mode 100644 index 000000000000..e07c9ce7b40e --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/WatchersClientImpl.java @@ -0,0 +1,1697 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.Patch; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Post; +import com.azure.core.annotation.Put; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.core.util.polling.PollerFlux; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.databasewatcher.fluent.WatchersClient; +import com.azure.resourcemanager.databasewatcher.fluent.models.WatcherInner; +import com.azure.resourcemanager.databasewatcher.implementation.models.WatcherListResult; +import com.azure.resourcemanager.databasewatcher.models.WatcherUpdate; +import java.nio.ByteBuffer; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in WatchersClient. + */ +public final class WatchersClientImpl implements WatchersClient { + /** + * The proxy service used to perform REST calls. + */ + private final WatchersService service; + + /** + * The service client containing this operation class. + */ + private final DatabaseWatcherManagementClientImpl client; + + /** + * Initializes an instance of WatchersClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + WatchersClientImpl(DatabaseWatcherManagementClientImpl client) { + this.service = RestProxy.create(WatchersService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for DatabaseWatcherManagementClientWatchers to be used by the proxy + * service to perform REST calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "DatabaseWatcherManag") + public interface WatchersService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> getByResourceGroup(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("watcherName") String watcherName, + @HeaderParam("Accept") String accept, Context context); + + @Put("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> createOrUpdate(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("watcherName") String watcherName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") WatcherInner resource, Context context); + + @Patch("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}") + @ExpectedResponses({ 200, 202 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> update(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("watcherName") String watcherName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") WatcherUpdate properties, Context context); + + @Headers({ "Content-Type: application/json" }) + @Delete("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}") + @ExpectedResponses({ 202, 204 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> delete(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("watcherName") String watcherName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByResourceGroup(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/providers/Microsoft.DatabaseWatcher/watchers") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> list(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Post("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/start") + @ExpectedResponses({ 200, 202 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> start(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("watcherName") String watcherName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Post("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/stop") + @ExpectedResponses({ 200, 202 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> stop(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("watcherName") String watcherName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByResourceGroupNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listBySubscriptionNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * Get a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Watcher along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getByResourceGroupWithResponseAsync(String resourceGroupName, + String watcherName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.getByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, watcherName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Watcher along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getByResourceGroupWithResponseAsync(String resourceGroupName, + String watcherName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.getByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, watcherName, accept, context); + } + + /** + * Get a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Watcher on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getByResourceGroupAsync(String resourceGroupName, String watcherName) { + return getByResourceGroupWithResponseAsync(resourceGroupName, watcherName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Watcher along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getByResourceGroupWithResponse(String resourceGroupName, String watcherName, + Context context) { + return getByResourceGroupWithResponseAsync(resourceGroupName, watcherName, context).block(); + } + + /** + * Get a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Watcher. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public WatcherInner getByResourceGroup(String resourceGroupName, String watcherName) { + return getByResourceGroupWithResponse(resourceGroupName, watcherName, Context.NONE).getValue(); + } + + /** + * Create a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the DatabaseWatcherProviderHub resource along with {@link Response} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createOrUpdateWithResponseAsync(String resourceGroupName, + String watcherName, WatcherInner resource) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.createOrUpdate(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, watcherName, contentType, accept, resource, + context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Create a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the DatabaseWatcherProviderHub resource along with {@link Response} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createOrUpdateWithResponseAsync(String resourceGroupName, + String watcherName, WatcherInner resource, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.createOrUpdate(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, watcherName, contentType, accept, resource, context); + } + + /** + * Create a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of the DatabaseWatcherProviderHub resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, WatcherInner> beginCreateOrUpdateAsync(String resourceGroupName, + String watcherName, WatcherInner resource) { + Mono>> mono + = createOrUpdateWithResponseAsync(resourceGroupName, watcherName, resource); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + WatcherInner.class, WatcherInner.class, this.client.getContext()); + } + + /** + * Create a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of the DatabaseWatcherProviderHub resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, WatcherInner> beginCreateOrUpdateAsync(String resourceGroupName, + String watcherName, WatcherInner resource, Context context) { + context = this.client.mergeContext(context); + Mono>> mono + = createOrUpdateWithResponseAsync(resourceGroupName, watcherName, resource, context); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + WatcherInner.class, WatcherInner.class, context); + } + + /** + * Create a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of the DatabaseWatcherProviderHub resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, WatcherInner> beginCreateOrUpdate(String resourceGroupName, + String watcherName, WatcherInner resource) { + return this.beginCreateOrUpdateAsync(resourceGroupName, watcherName, resource).getSyncPoller(); + } + + /** + * Create a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of the DatabaseWatcherProviderHub resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, WatcherInner> beginCreateOrUpdate(String resourceGroupName, + String watcherName, WatcherInner resource, Context context) { + return this.beginCreateOrUpdateAsync(resourceGroupName, watcherName, resource, context).getSyncPoller(); + } + + /** + * Create a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the DatabaseWatcherProviderHub resource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createOrUpdateAsync(String resourceGroupName, String watcherName, + WatcherInner resource) { + return beginCreateOrUpdateAsync(resourceGroupName, watcherName, resource).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the DatabaseWatcherProviderHub resource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createOrUpdateAsync(String resourceGroupName, String watcherName, WatcherInner resource, + Context context) { + return beginCreateOrUpdateAsync(resourceGroupName, watcherName, resource, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the DatabaseWatcherProviderHub resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public WatcherInner createOrUpdate(String resourceGroupName, String watcherName, WatcherInner resource) { + return createOrUpdateAsync(resourceGroupName, watcherName, resource).block(); + } + + /** + * Create a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the DatabaseWatcherProviderHub resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public WatcherInner createOrUpdate(String resourceGroupName, String watcherName, WatcherInner resource, + Context context) { + return createOrUpdateAsync(resourceGroupName, watcherName, resource, context).block(); + } + + /** + * Update a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the DatabaseWatcherProviderHub resource along with {@link Response} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> updateWithResponseAsync(String resourceGroupName, String watcherName, + WatcherUpdate properties) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + if (properties == null) { + return Mono.error(new IllegalArgumentException("Parameter properties is required and cannot be null.")); + } else { + properties.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.update(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, watcherName, contentType, accept, properties, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Update a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param properties The resource properties to be updated. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the DatabaseWatcherProviderHub resource along with {@link Response} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> updateWithResponseAsync(String resourceGroupName, String watcherName, + WatcherUpdate properties, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + if (properties == null) { + return Mono.error(new IllegalArgumentException("Parameter properties is required and cannot be null.")); + } else { + properties.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.update(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, watcherName, contentType, accept, properties, context); + } + + /** + * Update a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of the DatabaseWatcherProviderHub resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, WatcherInner> beginUpdateAsync(String resourceGroupName, + String watcherName, WatcherUpdate properties) { + Mono>> mono = updateWithResponseAsync(resourceGroupName, watcherName, properties); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + WatcherInner.class, WatcherInner.class, this.client.getContext()); + } + + /** + * Update a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param properties The resource properties to be updated. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of the DatabaseWatcherProviderHub resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, WatcherInner> beginUpdateAsync(String resourceGroupName, + String watcherName, WatcherUpdate properties, Context context) { + context = this.client.mergeContext(context); + Mono>> mono + = updateWithResponseAsync(resourceGroupName, watcherName, properties, context); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + WatcherInner.class, WatcherInner.class, context); + } + + /** + * Update a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of the DatabaseWatcherProviderHub resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, WatcherInner> beginUpdate(String resourceGroupName, String watcherName, + WatcherUpdate properties) { + return this.beginUpdateAsync(resourceGroupName, watcherName, properties).getSyncPoller(); + } + + /** + * Update a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param properties The resource properties to be updated. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of the DatabaseWatcherProviderHub resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, WatcherInner> beginUpdate(String resourceGroupName, String watcherName, + WatcherUpdate properties, Context context) { + return this.beginUpdateAsync(resourceGroupName, watcherName, properties, context).getSyncPoller(); + } + + /** + * Update a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the DatabaseWatcherProviderHub resource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono updateAsync(String resourceGroupName, String watcherName, WatcherUpdate properties) { + return beginUpdateAsync(resourceGroupName, watcherName, properties).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Update a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param properties The resource properties to be updated. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the DatabaseWatcherProviderHub resource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono updateAsync(String resourceGroupName, String watcherName, WatcherUpdate properties, + Context context) { + return beginUpdateAsync(resourceGroupName, watcherName, properties, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Update a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the DatabaseWatcherProviderHub resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public WatcherInner update(String resourceGroupName, String watcherName, WatcherUpdate properties) { + return updateAsync(resourceGroupName, watcherName, properties).block(); + } + + /** + * Update a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param properties The resource properties to be updated. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the DatabaseWatcherProviderHub resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public WatcherInner update(String resourceGroupName, String watcherName, WatcherUpdate properties, + Context context) { + return updateAsync(resourceGroupName, watcherName, properties, context).block(); + } + + /** + * Delete a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> deleteWithResponseAsync(String resourceGroupName, String watcherName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.delete(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, watcherName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Delete a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> deleteWithResponseAsync(String resourceGroupName, String watcherName, + Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.delete(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, watcherName, accept, context); + } + + /** + * Delete a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, Void> beginDeleteAsync(String resourceGroupName, String watcherName) { + Mono>> mono = deleteWithResponseAsync(resourceGroupName, watcherName); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), Void.class, Void.class, + this.client.getContext()); + } + + /** + * Delete a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, Void> beginDeleteAsync(String resourceGroupName, String watcherName, + Context context) { + context = this.client.mergeContext(context); + Mono>> mono = deleteWithResponseAsync(resourceGroupName, watcherName, context); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), Void.class, Void.class, + context); + } + + /** + * Delete a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, Void> beginDelete(String resourceGroupName, String watcherName) { + return this.beginDeleteAsync(resourceGroupName, watcherName).getSyncPoller(); + } + + /** + * Delete a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, Void> beginDelete(String resourceGroupName, String watcherName, + Context context) { + return this.beginDeleteAsync(resourceGroupName, watcherName, context).getSyncPoller(); + } + + /** + * Delete a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono deleteAsync(String resourceGroupName, String watcherName) { + return beginDeleteAsync(resourceGroupName, watcherName).last().flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Delete a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono deleteAsync(String resourceGroupName, String watcherName, Context context) { + return beginDeleteAsync(resourceGroupName, watcherName, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Delete a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String resourceGroupName, String watcherName) { + deleteAsync(resourceGroupName, watcherName).block(); + } + + /** + * Delete a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String resourceGroupName, String watcherName, Context context) { + deleteAsync(resourceGroupName, watcherName, context).block(); + } + + /** + * List Watcher resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Watcher list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByResourceGroupSinglePageAsync(String resourceGroupName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), + res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List Watcher resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Watcher list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByResourceGroupSinglePageAsync(String resourceGroupName, + Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List Watcher resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Watcher list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByResourceGroupAsync(String resourceGroupName) { + return new PagedFlux<>(() -> listByResourceGroupSinglePageAsync(resourceGroupName), + nextLink -> listByResourceGroupNextSinglePageAsync(nextLink)); + } + + /** + * List Watcher resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Watcher list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByResourceGroupAsync(String resourceGroupName, Context context) { + return new PagedFlux<>(() -> listByResourceGroupSinglePageAsync(resourceGroupName, context), + nextLink -> listByResourceGroupNextSinglePageAsync(nextLink, context)); + } + + /** + * List Watcher resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Watcher list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByResourceGroup(String resourceGroupName) { + return new PagedIterable<>(listByResourceGroupAsync(resourceGroupName)); + } + + /** + * List Watcher resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Watcher list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByResourceGroup(String resourceGroupName, Context context) { + return new PagedIterable<>(listByResourceGroupAsync(resourceGroupName, context)); + } + + /** + * List Watcher resources by subscription ID. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Watcher list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync() { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.list(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), + res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List Watcher resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Watcher list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync(Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .list(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), accept, + context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List Watcher resources by subscription ID. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Watcher list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync() { + return new PagedFlux<>(() -> listSinglePageAsync(), + nextLink -> listBySubscriptionNextSinglePageAsync(nextLink)); + } + + /** + * List Watcher resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Watcher list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync(Context context) { + return new PagedFlux<>(() -> listSinglePageAsync(context), + nextLink -> listBySubscriptionNextSinglePageAsync(nextLink, context)); + } + + /** + * List Watcher resources by subscription ID. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Watcher list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list() { + return new PagedIterable<>(listAsync()); + } + + /** + * List Watcher resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Watcher list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(Context context) { + return new PagedIterable<>(listAsync(context)); + } + + /** + * The action to start monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> startWithResponseAsync(String resourceGroupName, String watcherName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.start(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, watcherName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * The action to start monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> startWithResponseAsync(String resourceGroupName, String watcherName, + Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.start(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, watcherName, accept, context); + } + + /** + * The action to start monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, WatcherInner> beginStartAsync(String resourceGroupName, + String watcherName) { + Mono>> mono = startWithResponseAsync(resourceGroupName, watcherName); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + WatcherInner.class, WatcherInner.class, this.client.getContext()); + } + + /** + * The action to start monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, WatcherInner> beginStartAsync(String resourceGroupName, + String watcherName, Context context) { + context = this.client.mergeContext(context); + Mono>> mono = startWithResponseAsync(resourceGroupName, watcherName, context); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + WatcherInner.class, WatcherInner.class, context); + } + + /** + * The action to start monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, WatcherInner> beginStart(String resourceGroupName, String watcherName) { + return this.beginStartAsync(resourceGroupName, watcherName).getSyncPoller(); + } + + /** + * The action to start monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, WatcherInner> beginStart(String resourceGroupName, String watcherName, + Context context) { + return this.beginStartAsync(resourceGroupName, watcherName, context).getSyncPoller(); + } + + /** + * The action to start monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono startAsync(String resourceGroupName, String watcherName) { + return beginStartAsync(resourceGroupName, watcherName).last().flatMap(this.client::getLroFinalResultOrError); + } + + /** + * The action to start monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono startAsync(String resourceGroupName, String watcherName, Context context) { + return beginStartAsync(resourceGroupName, watcherName, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * The action to start monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public WatcherInner start(String resourceGroupName, String watcherName) { + return startAsync(resourceGroupName, watcherName).block(); + } + + /** + * The action to start monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public WatcherInner start(String resourceGroupName, String watcherName, Context context) { + return startAsync(resourceGroupName, watcherName, context).block(); + } + + /** + * The action to stop monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> stopWithResponseAsync(String resourceGroupName, String watcherName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.stop(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, watcherName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * The action to stop monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> stopWithResponseAsync(String resourceGroupName, String watcherName, + Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (watcherName == null) { + return Mono.error(new IllegalArgumentException("Parameter watcherName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.stop(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, watcherName, accept, context); + } + + /** + * The action to stop monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, WatcherInner> beginStopAsync(String resourceGroupName, + String watcherName) { + Mono>> mono = stopWithResponseAsync(resourceGroupName, watcherName); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + WatcherInner.class, WatcherInner.class, this.client.getContext()); + } + + /** + * The action to stop monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, WatcherInner> beginStopAsync(String resourceGroupName, + String watcherName, Context context) { + context = this.client.mergeContext(context); + Mono>> mono = stopWithResponseAsync(resourceGroupName, watcherName, context); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + WatcherInner.class, WatcherInner.class, context); + } + + /** + * The action to stop monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, WatcherInner> beginStop(String resourceGroupName, String watcherName) { + return this.beginStopAsync(resourceGroupName, watcherName).getSyncPoller(); + } + + /** + * The action to stop monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, WatcherInner> beginStop(String resourceGroupName, String watcherName, + Context context) { + return this.beginStopAsync(resourceGroupName, watcherName, context).getSyncPoller(); + } + + /** + * The action to stop monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono stopAsync(String resourceGroupName, String watcherName) { + return beginStopAsync(resourceGroupName, watcherName).last().flatMap(this.client::getLroFinalResultOrError); + } + + /** + * The action to stop monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono stopAsync(String resourceGroupName, String watcherName, Context context) { + return beginStopAsync(resourceGroupName, watcherName, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * The action to stop monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public WatcherInner stop(String resourceGroupName, String watcherName) { + return stopAsync(resourceGroupName, watcherName).block(); + } + + /** + * The action to stop monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public WatcherInner stop(String resourceGroupName, String watcherName, Context context) { + return stopAsync(resourceGroupName, watcherName, context).block(); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Watcher list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByResourceGroupNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByResourceGroupNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), + res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Watcher list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByResourceGroupNextSinglePageAsync(String nextLink, Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listByResourceGroupNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Watcher list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySubscriptionNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), + res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Watcher list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySubscriptionNextSinglePageAsync(String nextLink, Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/WatchersImpl.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/WatchersImpl.java new file mode 100644 index 000000000000..5c76217efd40 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/WatchersImpl.java @@ -0,0 +1,182 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.databasewatcher.fluent.WatchersClient; +import com.azure.resourcemanager.databasewatcher.fluent.models.WatcherInner; +import com.azure.resourcemanager.databasewatcher.models.Watcher; +import com.azure.resourcemanager.databasewatcher.models.Watchers; + +public final class WatchersImpl implements Watchers { + private static final ClientLogger LOGGER = new ClientLogger(WatchersImpl.class); + + private final WatchersClient innerClient; + + private final com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager serviceManager; + + public WatchersImpl(WatchersClient innerClient, + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public Response getByResourceGroupWithResponse(String resourceGroupName, String watcherName, + Context context) { + Response inner + = this.serviceClient().getByResourceGroupWithResponse(resourceGroupName, watcherName, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new WatcherImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public Watcher getByResourceGroup(String resourceGroupName, String watcherName) { + WatcherInner inner = this.serviceClient().getByResourceGroup(resourceGroupName, watcherName); + if (inner != null) { + return new WatcherImpl(inner, this.manager()); + } else { + return null; + } + } + + public void deleteByResourceGroup(String resourceGroupName, String watcherName) { + this.serviceClient().delete(resourceGroupName, watcherName); + } + + public void delete(String resourceGroupName, String watcherName, Context context) { + this.serviceClient().delete(resourceGroupName, watcherName, context); + } + + public PagedIterable listByResourceGroup(String resourceGroupName) { + PagedIterable inner = this.serviceClient().listByResourceGroup(resourceGroupName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new WatcherImpl(inner1, this.manager())); + } + + public PagedIterable listByResourceGroup(String resourceGroupName, Context context) { + PagedIterable inner = this.serviceClient().listByResourceGroup(resourceGroupName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new WatcherImpl(inner1, this.manager())); + } + + public PagedIterable list() { + PagedIterable inner = this.serviceClient().list(); + return ResourceManagerUtils.mapPage(inner, inner1 -> new WatcherImpl(inner1, this.manager())); + } + + public PagedIterable list(Context context) { + PagedIterable inner = this.serviceClient().list(context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new WatcherImpl(inner1, this.manager())); + } + + public Watcher start(String resourceGroupName, String watcherName) { + WatcherInner inner = this.serviceClient().start(resourceGroupName, watcherName); + if (inner != null) { + return new WatcherImpl(inner, this.manager()); + } else { + return null; + } + } + + public Watcher start(String resourceGroupName, String watcherName, Context context) { + WatcherInner inner = this.serviceClient().start(resourceGroupName, watcherName, context); + if (inner != null) { + return new WatcherImpl(inner, this.manager()); + } else { + return null; + } + } + + public Watcher stop(String resourceGroupName, String watcherName) { + WatcherInner inner = this.serviceClient().stop(resourceGroupName, watcherName); + if (inner != null) { + return new WatcherImpl(inner, this.manager()); + } else { + return null; + } + } + + public Watcher stop(String resourceGroupName, String watcherName, Context context) { + WatcherInner inner = this.serviceClient().stop(resourceGroupName, watcherName, context); + if (inner != null) { + return new WatcherImpl(inner, this.manager()); + } else { + return null; + } + } + + public Watcher getById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String watcherName = ResourceManagerUtils.getValueFromIdByName(id, "watchers"); + if (watcherName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'watchers'.", id))); + } + return this.getByResourceGroupWithResponse(resourceGroupName, watcherName, Context.NONE).getValue(); + } + + public Response getByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String watcherName = ResourceManagerUtils.getValueFromIdByName(id, "watchers"); + if (watcherName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'watchers'.", id))); + } + return this.getByResourceGroupWithResponse(resourceGroupName, watcherName, context); + } + + public void deleteById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String watcherName = ResourceManagerUtils.getValueFromIdByName(id, "watchers"); + if (watcherName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'watchers'.", id))); + } + this.delete(resourceGroupName, watcherName, Context.NONE); + } + + public void deleteByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String watcherName = ResourceManagerUtils.getValueFromIdByName(id, "watchers"); + if (watcherName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'watchers'.", id))); + } + this.delete(resourceGroupName, watcherName, context); + } + + private WatchersClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager() { + return this.serviceManager; + } + + public WatcherImpl define(String name) { + return new WatcherImpl(name, this.manager()); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/models/AlertRuleResourceListResult.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/models/AlertRuleResourceListResult.java new file mode 100644 index 000000000000..e5fc1d7c8b65 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/models/AlertRuleResourceListResult.java @@ -0,0 +1,114 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.implementation.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.databasewatcher.fluent.models.AlertRuleResourceInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a AlertRuleResource list operation. + */ +@Immutable +public final class AlertRuleResourceListResult implements JsonSerializable { + /* + * The AlertRuleResource items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of AlertRuleResourceListResult class. + */ + private AlertRuleResourceListResult() { + } + + /** + * Get the value property: The AlertRuleResource items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property value in model AlertRuleResourceListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(AlertRuleResourceListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AlertRuleResourceListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AlertRuleResourceListResult 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 AlertRuleResourceListResult. + */ + public static AlertRuleResourceListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AlertRuleResourceListResult deserializedAlertRuleResourceListResult = new AlertRuleResourceListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> AlertRuleResourceInner.fromJson(reader1)); + deserializedAlertRuleResourceListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedAlertRuleResourceListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAlertRuleResourceListResult; + }); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/models/HealthValidationListResult.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/models/HealthValidationListResult.java new file mode 100644 index 000000000000..8ca54cc9055b --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/models/HealthValidationListResult.java @@ -0,0 +1,114 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.implementation.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.databasewatcher.fluent.models.HealthValidationInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a HealthValidation list operation. + */ +@Immutable +public final class HealthValidationListResult implements JsonSerializable { + /* + * The HealthValidation items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of HealthValidationListResult class. + */ + private HealthValidationListResult() { + } + + /** + * Get the value property: The HealthValidation items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property value in model HealthValidationListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(HealthValidationListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of HealthValidationListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of HealthValidationListResult 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 HealthValidationListResult. + */ + public static HealthValidationListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + HealthValidationListResult deserializedHealthValidationListResult = new HealthValidationListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> HealthValidationInner.fromJson(reader1)); + deserializedHealthValidationListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedHealthValidationListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedHealthValidationListResult; + }); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/models/OperationListResult.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/models/OperationListResult.java new file mode 100644 index 000000000000..3c63946bc5ca --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/models/OperationListResult.java @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.implementation.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.databasewatcher.fluent.models.OperationInner; +import java.io.IOException; +import java.util.List; + +/** + * A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + * results. + */ +@Immutable +public final class OperationListResult implements JsonSerializable { + /* + * The Operation items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of OperationListResult class. + */ + private OperationListResult() { + } + + /** + * Get the value property: The Operation items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property value in model OperationListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(OperationListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OperationListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OperationListResult 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 OperationListResult. + */ + public static OperationListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OperationListResult deserializedOperationListResult = new OperationListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value = reader.readArray(reader1 -> OperationInner.fromJson(reader1)); + deserializedOperationListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedOperationListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedOperationListResult; + }); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/models/SharedPrivateLinkResourceListResult.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/models/SharedPrivateLinkResourceListResult.java new file mode 100644 index 000000000000..d142c0e617a0 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/models/SharedPrivateLinkResourceListResult.java @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.implementation.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.databasewatcher.fluent.models.SharedPrivateLinkResourceInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a SharedPrivateLinkResource list operation. + */ +@Immutable +public final class SharedPrivateLinkResourceListResult + implements JsonSerializable { + /* + * The SharedPrivateLinkResource items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of SharedPrivateLinkResourceListResult class. + */ + private SharedPrivateLinkResourceListResult() { + } + + /** + * Get the value property: The SharedPrivateLinkResource items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property value in model SharedPrivateLinkResourceListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(SharedPrivateLinkResourceListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SharedPrivateLinkResourceListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SharedPrivateLinkResourceListResult 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 SharedPrivateLinkResourceListResult. + */ + public static SharedPrivateLinkResourceListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SharedPrivateLinkResourceListResult deserializedSharedPrivateLinkResourceListResult + = new SharedPrivateLinkResourceListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> SharedPrivateLinkResourceInner.fromJson(reader1)); + deserializedSharedPrivateLinkResourceListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedSharedPrivateLinkResourceListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedSharedPrivateLinkResourceListResult; + }); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/models/TargetListResult.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/models/TargetListResult.java new file mode 100644 index 000000000000..97f78cc145d7 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/models/TargetListResult.java @@ -0,0 +1,112 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.implementation.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.databasewatcher.fluent.models.TargetInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a Target list operation. + */ +@Immutable +public final class TargetListResult implements JsonSerializable { + /* + * The Target items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of TargetListResult class. + */ + private TargetListResult() { + } + + /** + * Get the value property: The Target items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property value in model TargetListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(TargetListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of TargetListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of TargetListResult 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 TargetListResult. + */ + public static TargetListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + TargetListResult deserializedTargetListResult = new TargetListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value = reader.readArray(reader1 -> TargetInner.fromJson(reader1)); + deserializedTargetListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedTargetListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedTargetListResult; + }); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/models/WatcherListResult.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/models/WatcherListResult.java new file mode 100644 index 000000000000..98562d037b8f --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/models/WatcherListResult.java @@ -0,0 +1,112 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.implementation.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.databasewatcher.fluent.models.WatcherInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a Watcher list operation. + */ +@Immutable +public final class WatcherListResult implements JsonSerializable { + /* + * The Watcher items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of WatcherListResult class. + */ + private WatcherListResult() { + } + + /** + * Get the value property: The Watcher items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property value in model WatcherListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(WatcherListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of WatcherListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of WatcherListResult 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 WatcherListResult. + */ + public static WatcherListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + WatcherListResult deserializedWatcherListResult = new WatcherListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value = reader.readArray(reader1 -> WatcherInner.fromJson(reader1)); + deserializedWatcherListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedWatcherListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedWatcherListResult; + }); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/package-info.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/package-info.java new file mode 100644 index 000000000000..12932219effc --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/implementation/package-info.java @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +/** + * Package containing the implementations for DatabaseWatcher. + */ +package com.azure.resourcemanager.databasewatcher.implementation; diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/ActionType.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/ActionType.java new file mode 100644 index 000000000000..d902b16574ff --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/ActionType.java @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + */ +public final class ActionType extends ExpandableStringEnum { + /** + * Actions are for internal-only APIs. + */ + public static final ActionType INTERNAL = fromString("Internal"); + + /** + * Creates a new instance of ActionType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public ActionType() { + } + + /** + * Creates or finds a ActionType from its string representation. + * + * @param name a name to look for. + * @return the corresponding ActionType. + */ + public static ActionType fromString(String name) { + return fromString(name, ActionType.class); + } + + /** + * Gets known ActionType values. + * + * @return known ActionType values. + */ + public static Collection values() { + return values(ActionType.class); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/AlertRuleCreationProperties.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/AlertRuleCreationProperties.java new file mode 100644 index 000000000000..9a72859b8bc0 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/AlertRuleCreationProperties.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The properties with which the alert rule resource was created. + */ +public final class AlertRuleCreationProperties extends ExpandableStringEnum { + /** + * The alert rule was created with an action group. + */ + public static final AlertRuleCreationProperties CREATED_WITH_ACTION_GROUP = fromString("CreatedWithActionGroup"); + + /** + * The alert rule was created with no properties. + */ + public static final AlertRuleCreationProperties NONE = fromString("None"); + + /** + * Creates a new instance of AlertRuleCreationProperties value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AlertRuleCreationProperties() { + } + + /** + * Creates or finds a AlertRuleCreationProperties from its string representation. + * + * @param name a name to look for. + * @return the corresponding AlertRuleCreationProperties. + */ + public static AlertRuleCreationProperties fromString(String name) { + return fromString(name, AlertRuleCreationProperties.class); + } + + /** + * Gets known AlertRuleCreationProperties values. + * + * @return known AlertRuleCreationProperties values. + */ + public static Collection values() { + return values(AlertRuleCreationProperties.class); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/AlertRuleResource.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/AlertRuleResource.java new file mode 100644 index 000000000000..9b4ff6ca467d --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/AlertRuleResource.java @@ -0,0 +1,189 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.databasewatcher.fluent.models.AlertRuleResourceInner; + +/** + * An immutable client-side representation of AlertRuleResource. + */ +public interface AlertRuleResource { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + AlertRuleResourceProperties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the name of the resource group. + * + * @return the name of the resource group. + */ + String resourceGroupName(); + + /** + * Gets the inner com.azure.resourcemanager.databasewatcher.fluent.models.AlertRuleResourceInner object. + * + * @return the inner object. + */ + AlertRuleResourceInner innerModel(); + + /** + * The entirety of the AlertRuleResource definition. + */ + interface Definition + extends DefinitionStages.Blank, DefinitionStages.WithParentResource, DefinitionStages.WithCreate { + } + + /** + * The AlertRuleResource definition stages. + */ + interface DefinitionStages { + /** + * The first stage of the AlertRuleResource definition. + */ + interface Blank extends WithParentResource { + } + + /** + * The stage of the AlertRuleResource definition allowing to specify parent resource. + */ + interface WithParentResource { + /** + * Specifies resourceGroupName, watcherName. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @return the next definition stage. + */ + WithCreate withExistingWatcher(String resourceGroupName, String watcherName); + } + + /** + * The stage of the AlertRuleResource definition which contains all the minimum required properties for the + * resource to be created, but also allows for any other optional properties to be specified. + */ + interface WithCreate extends DefinitionStages.WithProperties { + /** + * Executes the create request. + * + * @return the created resource. + */ + AlertRuleResource create(); + + /** + * Executes the create request. + * + * @param context The context to associate with this operation. + * @return the created resource. + */ + AlertRuleResource create(Context context); + } + + /** + * The stage of the AlertRuleResource definition allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The resource-specific properties for this resource.. + * + * @param properties The resource-specific properties for this resource. + * @return the next definition stage. + */ + WithCreate withProperties(AlertRuleResourceProperties properties); + } + } + + /** + * Begins update for the AlertRuleResource resource. + * + * @return the stage of resource update. + */ + AlertRuleResource.Update update(); + + /** + * The template for AlertRuleResource update. + */ + interface Update extends UpdateStages.WithProperties { + /** + * Executes the update request. + * + * @return the updated resource. + */ + AlertRuleResource apply(); + + /** + * Executes the update request. + * + * @param context The context to associate with this operation. + * @return the updated resource. + */ + AlertRuleResource apply(Context context); + } + + /** + * The AlertRuleResource update stages. + */ + interface UpdateStages { + /** + * The stage of the AlertRuleResource update allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The resource-specific properties for this resource.. + * + * @param properties The resource-specific properties for this resource. + * @return the next definition stage. + */ + Update withProperties(AlertRuleResourceProperties properties); + } + } + + /** + * Refreshes the resource to sync with Azure. + * + * @return the refreshed resource. + */ + AlertRuleResource refresh(); + + /** + * Refreshes the resource to sync with Azure. + * + * @param context The context to associate with this operation. + * @return the refreshed resource. + */ + AlertRuleResource refresh(Context context); +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/AlertRuleResourceProperties.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/AlertRuleResourceProperties.java new file mode 100644 index 000000000000..9d1128dcf18b --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/AlertRuleResourceProperties.java @@ -0,0 +1,258 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; +import com.azure.core.util.logging.ClientLogger; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * The generic properties of the alert rule proxy resource. + */ +@Fluent +public final class AlertRuleResourceProperties implements JsonSerializable { + /* + * The resource ID of the alert rule resource. + */ + private String alertRuleResourceId; + + /* + * The properties with which the alert rule resource was created. + */ + private AlertRuleCreationProperties createdWithProperties; + + /* + * The creation time of the alert rule resource. + */ + private OffsetDateTime creationTime; + + /* + * The provisioning state of the alert rule resource. + */ + private ResourceProvisioningState provisioningState; + + /* + * The template ID associated with alert rule resource. + */ + private String alertRuleTemplateId; + + /* + * The alert rule template version. + */ + private String alertRuleTemplateVersion; + + /** + * Creates an instance of AlertRuleResourceProperties class. + */ + public AlertRuleResourceProperties() { + } + + /** + * Get the alertRuleResourceId property: The resource ID of the alert rule resource. + * + * @return the alertRuleResourceId value. + */ + public String alertRuleResourceId() { + return this.alertRuleResourceId; + } + + /** + * Set the alertRuleResourceId property: The resource ID of the alert rule resource. + * + * @param alertRuleResourceId the alertRuleResourceId value to set. + * @return the AlertRuleResourceProperties object itself. + */ + public AlertRuleResourceProperties withAlertRuleResourceId(String alertRuleResourceId) { + this.alertRuleResourceId = alertRuleResourceId; + return this; + } + + /** + * Get the createdWithProperties property: The properties with which the alert rule resource was created. + * + * @return the createdWithProperties value. + */ + public AlertRuleCreationProperties createdWithProperties() { + return this.createdWithProperties; + } + + /** + * Set the createdWithProperties property: The properties with which the alert rule resource was created. + * + * @param createdWithProperties the createdWithProperties value to set. + * @return the AlertRuleResourceProperties object itself. + */ + public AlertRuleResourceProperties withCreatedWithProperties(AlertRuleCreationProperties createdWithProperties) { + this.createdWithProperties = createdWithProperties; + return this; + } + + /** + * Get the creationTime property: The creation time of the alert rule resource. + * + * @return the creationTime value. + */ + public OffsetDateTime creationTime() { + return this.creationTime; + } + + /** + * Set the creationTime property: The creation time of the alert rule resource. + * + * @param creationTime the creationTime value to set. + * @return the AlertRuleResourceProperties object itself. + */ + public AlertRuleResourceProperties withCreationTime(OffsetDateTime creationTime) { + this.creationTime = creationTime; + return this; + } + + /** + * Get the provisioningState property: The provisioning state of the alert rule resource. + * + * @return the provisioningState value. + */ + public ResourceProvisioningState provisioningState() { + return this.provisioningState; + } + + /** + * Get the alertRuleTemplateId property: The template ID associated with alert rule resource. + * + * @return the alertRuleTemplateId value. + */ + public String alertRuleTemplateId() { + return this.alertRuleTemplateId; + } + + /** + * Set the alertRuleTemplateId property: The template ID associated with alert rule resource. + * + * @param alertRuleTemplateId the alertRuleTemplateId value to set. + * @return the AlertRuleResourceProperties object itself. + */ + public AlertRuleResourceProperties withAlertRuleTemplateId(String alertRuleTemplateId) { + this.alertRuleTemplateId = alertRuleTemplateId; + return this; + } + + /** + * Get the alertRuleTemplateVersion property: The alert rule template version. + * + * @return the alertRuleTemplateVersion value. + */ + public String alertRuleTemplateVersion() { + return this.alertRuleTemplateVersion; + } + + /** + * Set the alertRuleTemplateVersion property: The alert rule template version. + * + * @param alertRuleTemplateVersion the alertRuleTemplateVersion value to set. + * @return the AlertRuleResourceProperties object itself. + */ + public AlertRuleResourceProperties withAlertRuleTemplateVersion(String alertRuleTemplateVersion) { + this.alertRuleTemplateVersion = alertRuleTemplateVersion; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (alertRuleResourceId() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property alertRuleResourceId in model AlertRuleResourceProperties")); + } + if (createdWithProperties() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property createdWithProperties in model AlertRuleResourceProperties")); + } + if (creationTime() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property creationTime in model AlertRuleResourceProperties")); + } + if (alertRuleTemplateId() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property alertRuleTemplateId in model AlertRuleResourceProperties")); + } + if (alertRuleTemplateVersion() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property alertRuleTemplateVersion in model AlertRuleResourceProperties")); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(AlertRuleResourceProperties.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("alertRuleResourceId", this.alertRuleResourceId); + jsonWriter.writeStringField("createdWithProperties", + this.createdWithProperties == null ? null : this.createdWithProperties.toString()); + jsonWriter.writeStringField("creationTime", + this.creationTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.creationTime)); + jsonWriter.writeStringField("alertRuleTemplateId", this.alertRuleTemplateId); + jsonWriter.writeStringField("alertRuleTemplateVersion", this.alertRuleTemplateVersion); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AlertRuleResourceProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AlertRuleResourceProperties 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 AlertRuleResourceProperties. + */ + public static AlertRuleResourceProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AlertRuleResourceProperties deserializedAlertRuleResourceProperties = new AlertRuleResourceProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("alertRuleResourceId".equals(fieldName)) { + deserializedAlertRuleResourceProperties.alertRuleResourceId = reader.getString(); + } else if ("createdWithProperties".equals(fieldName)) { + deserializedAlertRuleResourceProperties.createdWithProperties + = AlertRuleCreationProperties.fromString(reader.getString()); + } else if ("creationTime".equals(fieldName)) { + deserializedAlertRuleResourceProperties.creationTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("alertRuleTemplateId".equals(fieldName)) { + deserializedAlertRuleResourceProperties.alertRuleTemplateId = reader.getString(); + } else if ("alertRuleTemplateVersion".equals(fieldName)) { + deserializedAlertRuleResourceProperties.alertRuleTemplateVersion = reader.getString(); + } else if ("provisioningState".equals(fieldName)) { + deserializedAlertRuleResourceProperties.provisioningState + = ResourceProvisioningState.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedAlertRuleResourceProperties; + }); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/AlertRuleResources.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/AlertRuleResources.java new file mode 100644 index 000000000000..48bdc522e00c --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/AlertRuleResources.java @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of AlertRuleResources. + */ +public interface AlertRuleResources { + /** + * Get a AlertRuleResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param alertRuleResourceName The alert rule proxy resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AlertRuleResource along with {@link Response}. + */ + Response getWithResponse(String resourceGroupName, String watcherName, + String alertRuleResourceName, Context context); + + /** + * Get a AlertRuleResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param alertRuleResourceName The alert rule proxy resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AlertRuleResource. + */ + AlertRuleResource get(String resourceGroupName, String watcherName, String alertRuleResourceName); + + /** + * Delete a AlertRuleResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param alertRuleResourceName The alert rule proxy resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteWithResponse(String resourceGroupName, String watcherName, String alertRuleResourceName, + Context context); + + /** + * Delete a AlertRuleResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param alertRuleResourceName The alert rule proxy resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void delete(String resourceGroupName, String watcherName, String alertRuleResourceName); + + /** + * List AlertRuleResource resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AlertRuleResource list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByParent(String resourceGroupName, String watcherName); + + /** + * List AlertRuleResource resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AlertRuleResource list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByParent(String resourceGroupName, String watcherName, Context context); + + /** + * Get a AlertRuleResource. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AlertRuleResource along with {@link Response}. + */ + AlertRuleResource getById(String id); + + /** + * Get a AlertRuleResource. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AlertRuleResource along with {@link Response}. + */ + Response getByIdWithResponse(String id, Context context); + + /** + * Delete a AlertRuleResource. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteById(String id); + + /** + * Delete a AlertRuleResource. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteByIdWithResponse(String id, Context context); + + /** + * Begins definition for a new AlertRuleResource resource. + * + * @param name resource name. + * @return the first stage of the new AlertRuleResource definition. + */ + AlertRuleResource.DefinitionStages.Blank define(String name); +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/DatabaseWatcherProvisioningState.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/DatabaseWatcherProvisioningState.java new file mode 100644 index 000000000000..07d3b2d771e8 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/DatabaseWatcherProvisioningState.java @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The status of the last provisioning operation performed on the resource. + */ +public final class DatabaseWatcherProvisioningState extends ExpandableStringEnum { + /** + * Resource has been created. + */ + public static final DatabaseWatcherProvisioningState SUCCEEDED = fromString("Succeeded"); + + /** + * Resource creation failed. + */ + public static final DatabaseWatcherProvisioningState FAILED = fromString("Failed"); + + /** + * Resource creation was canceled. + */ + public static final DatabaseWatcherProvisioningState CANCELED = fromString("Canceled"); + + /** + * Creates a new instance of DatabaseWatcherProvisioningState value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public DatabaseWatcherProvisioningState() { + } + + /** + * Creates or finds a DatabaseWatcherProvisioningState from its string representation. + * + * @param name a name to look for. + * @return the corresponding DatabaseWatcherProvisioningState. + */ + public static DatabaseWatcherProvisioningState fromString(String name) { + return fromString(name, DatabaseWatcherProvisioningState.class); + } + + /** + * Gets known DatabaseWatcherProvisioningState values. + * + * @return known DatabaseWatcherProvisioningState values. + */ + public static Collection values() { + return values(DatabaseWatcherProvisioningState.class); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/Datastore.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/Datastore.java new file mode 100644 index 000000000000..d445ad8b05e2 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/Datastore.java @@ -0,0 +1,287 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +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 properties of a data store. + */ +@Fluent +public final class Datastore implements JsonSerializable { + /* + * The Azure resource ID of an Azure Data Explorer cluster. + */ + private String adxClusterResourceId; + + /* + * The Kusto cluster display name. + */ + private String kustoClusterDisplayName; + + /* + * The Kusto cluster URI. + */ + private String kustoClusterUri; + + /* + * The Kusto data ingestion URI. + */ + private String kustoDataIngestionUri; + + /* + * The name of a Kusto database. + */ + private String kustoDatabaseName; + + /* + * The Kusto management URL. + */ + private String kustoManagementUrl; + + /* + * The type of a Kusto offering. + */ + private KustoOfferingType kustoOfferingType; + + /** + * Creates an instance of Datastore class. + */ + public Datastore() { + } + + /** + * Get the adxClusterResourceId property: The Azure resource ID of an Azure Data Explorer cluster. + * + * @return the adxClusterResourceId value. + */ + public String adxClusterResourceId() { + return this.adxClusterResourceId; + } + + /** + * Set the adxClusterResourceId property: The Azure resource ID of an Azure Data Explorer cluster. + * + * @param adxClusterResourceId the adxClusterResourceId value to set. + * @return the Datastore object itself. + */ + public Datastore withAdxClusterResourceId(String adxClusterResourceId) { + this.adxClusterResourceId = adxClusterResourceId; + return this; + } + + /** + * Get the kustoClusterDisplayName property: The Kusto cluster display name. + * + * @return the kustoClusterDisplayName value. + */ + public String kustoClusterDisplayName() { + return this.kustoClusterDisplayName; + } + + /** + * Set the kustoClusterDisplayName property: The Kusto cluster display name. + * + * @param kustoClusterDisplayName the kustoClusterDisplayName value to set. + * @return the Datastore object itself. + */ + public Datastore withKustoClusterDisplayName(String kustoClusterDisplayName) { + this.kustoClusterDisplayName = kustoClusterDisplayName; + return this; + } + + /** + * Get the kustoClusterUri property: The Kusto cluster URI. + * + * @return the kustoClusterUri value. + */ + public String kustoClusterUri() { + return this.kustoClusterUri; + } + + /** + * Set the kustoClusterUri property: The Kusto cluster URI. + * + * @param kustoClusterUri the kustoClusterUri value to set. + * @return the Datastore object itself. + */ + public Datastore withKustoClusterUri(String kustoClusterUri) { + this.kustoClusterUri = kustoClusterUri; + return this; + } + + /** + * Get the kustoDataIngestionUri property: The Kusto data ingestion URI. + * + * @return the kustoDataIngestionUri value. + */ + public String kustoDataIngestionUri() { + return this.kustoDataIngestionUri; + } + + /** + * Set the kustoDataIngestionUri property: The Kusto data ingestion URI. + * + * @param kustoDataIngestionUri the kustoDataIngestionUri value to set. + * @return the Datastore object itself. + */ + public Datastore withKustoDataIngestionUri(String kustoDataIngestionUri) { + this.kustoDataIngestionUri = kustoDataIngestionUri; + return this; + } + + /** + * Get the kustoDatabaseName property: The name of a Kusto database. + * + * @return the kustoDatabaseName value. + */ + public String kustoDatabaseName() { + return this.kustoDatabaseName; + } + + /** + * Set the kustoDatabaseName property: The name of a Kusto database. + * + * @param kustoDatabaseName the kustoDatabaseName value to set. + * @return the Datastore object itself. + */ + public Datastore withKustoDatabaseName(String kustoDatabaseName) { + this.kustoDatabaseName = kustoDatabaseName; + return this; + } + + /** + * Get the kustoManagementUrl property: The Kusto management URL. + * + * @return the kustoManagementUrl value. + */ + public String kustoManagementUrl() { + return this.kustoManagementUrl; + } + + /** + * Set the kustoManagementUrl property: The Kusto management URL. + * + * @param kustoManagementUrl the kustoManagementUrl value to set. + * @return the Datastore object itself. + */ + public Datastore withKustoManagementUrl(String kustoManagementUrl) { + this.kustoManagementUrl = kustoManagementUrl; + return this; + } + + /** + * Get the kustoOfferingType property: The type of a Kusto offering. + * + * @return the kustoOfferingType value. + */ + public KustoOfferingType kustoOfferingType() { + return this.kustoOfferingType; + } + + /** + * Set the kustoOfferingType property: The type of a Kusto offering. + * + * @param kustoOfferingType the kustoOfferingType value to set. + * @return the Datastore object itself. + */ + public Datastore withKustoOfferingType(KustoOfferingType kustoOfferingType) { + this.kustoOfferingType = kustoOfferingType; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (kustoClusterUri() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property kustoClusterUri in model Datastore")); + } + if (kustoDataIngestionUri() == null) { + throw LOGGER.atError() + .log( + new IllegalArgumentException("Missing required property kustoDataIngestionUri in model Datastore")); + } + if (kustoDatabaseName() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property kustoDatabaseName in model Datastore")); + } + if (kustoManagementUrl() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property kustoManagementUrl in model Datastore")); + } + if (kustoOfferingType() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property kustoOfferingType in model Datastore")); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(Datastore.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("kustoClusterUri", this.kustoClusterUri); + jsonWriter.writeStringField("kustoDataIngestionUri", this.kustoDataIngestionUri); + jsonWriter.writeStringField("kustoDatabaseName", this.kustoDatabaseName); + jsonWriter.writeStringField("kustoManagementUrl", this.kustoManagementUrl); + jsonWriter.writeStringField("kustoOfferingType", + this.kustoOfferingType == null ? null : this.kustoOfferingType.toString()); + jsonWriter.writeStringField("adxClusterResourceId", this.adxClusterResourceId); + jsonWriter.writeStringField("kustoClusterDisplayName", this.kustoClusterDisplayName); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of Datastore from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of Datastore 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 Datastore. + */ + public static Datastore fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Datastore deserializedDatastore = new Datastore(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("kustoClusterUri".equals(fieldName)) { + deserializedDatastore.kustoClusterUri = reader.getString(); + } else if ("kustoDataIngestionUri".equals(fieldName)) { + deserializedDatastore.kustoDataIngestionUri = reader.getString(); + } else if ("kustoDatabaseName".equals(fieldName)) { + deserializedDatastore.kustoDatabaseName = reader.getString(); + } else if ("kustoManagementUrl".equals(fieldName)) { + deserializedDatastore.kustoManagementUrl = reader.getString(); + } else if ("kustoOfferingType".equals(fieldName)) { + deserializedDatastore.kustoOfferingType = KustoOfferingType.fromString(reader.getString()); + } else if ("adxClusterResourceId".equals(fieldName)) { + deserializedDatastore.adxClusterResourceId = reader.getString(); + } else if ("kustoClusterDisplayName".equals(fieldName)) { + deserializedDatastore.kustoClusterDisplayName = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedDatastore; + }); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/HealthValidation.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/HealthValidation.java new file mode 100644 index 000000000000..c048a99516e5 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/HealthValidation.java @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.databasewatcher.fluent.models.HealthValidationInner; + +/** + * An immutable client-side representation of HealthValidation. + */ +public interface HealthValidation { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + HealthValidationProperties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.databasewatcher.fluent.models.HealthValidationInner object. + * + * @return the inner object. + */ + HealthValidationInner innerModel(); +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/HealthValidationProperties.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/HealthValidationProperties.java new file mode 100644 index 000000000000..688e6a980afa --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/HealthValidationProperties.java @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.util.List; + +/** + * The generic properties of the health validation resource. + */ +@Immutable +public final class HealthValidationProperties implements JsonSerializable { + /* + * The start time of health validation, in UTC. + */ + private OffsetDateTime startTime; + + /* + * The end time of health validation, in UTC. + */ + private OffsetDateTime endTime; + + /* + * The current health validation status. + */ + private ValidationStatus status; + + /* + * The list of issues found by health validation. + */ + private List issues; + + /* + * The provisioning state of the health validation resource. + */ + private ResourceProvisioningState provisioningState; + + /** + * Creates an instance of HealthValidationProperties class. + */ + private HealthValidationProperties() { + } + + /** + * Get the startTime property: The start time of health validation, in UTC. + * + * @return the startTime value. + */ + public OffsetDateTime startTime() { + return this.startTime; + } + + /** + * Get the endTime property: The end time of health validation, in UTC. + * + * @return the endTime value. + */ + public OffsetDateTime endTime() { + return this.endTime; + } + + /** + * Get the status property: The current health validation status. + * + * @return the status value. + */ + public ValidationStatus status() { + return this.status; + } + + /** + * Get the issues property: The list of issues found by health validation. + * + * @return the issues value. + */ + public List issues() { + return this.issues; + } + + /** + * Get the provisioningState property: The provisioning state of the health validation resource. + * + * @return the provisioningState value. + */ + public ResourceProvisioningState provisioningState() { + return this.provisioningState; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (issues() != null) { + issues().forEach(e -> e.validate()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of HealthValidationProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of HealthValidationProperties 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 HealthValidationProperties. + */ + public static HealthValidationProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + HealthValidationProperties deserializedHealthValidationProperties = new HealthValidationProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("startTime".equals(fieldName)) { + deserializedHealthValidationProperties.startTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("endTime".equals(fieldName)) { + deserializedHealthValidationProperties.endTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("status".equals(fieldName)) { + deserializedHealthValidationProperties.status = ValidationStatus.fromString(reader.getString()); + } else if ("issues".equals(fieldName)) { + List issues = reader.readArray(reader1 -> ValidationIssue.fromJson(reader1)); + deserializedHealthValidationProperties.issues = issues; + } else if ("provisioningState".equals(fieldName)) { + deserializedHealthValidationProperties.provisioningState + = ResourceProvisioningState.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedHealthValidationProperties; + }); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/HealthValidations.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/HealthValidations.java new file mode 100644 index 000000000000..a53a7ce01c92 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/HealthValidations.java @@ -0,0 +1,95 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of HealthValidations. + */ +public interface HealthValidations { + /** + * Get a HealthValidation. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param healthValidationName The health validation resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a HealthValidation along with {@link Response}. + */ + Response getWithResponse(String resourceGroupName, String watcherName, + String healthValidationName, Context context); + + /** + * Get a HealthValidation. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param healthValidationName The health validation resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a HealthValidation. + */ + HealthValidation get(String resourceGroupName, String watcherName, String healthValidationName); + + /** + * List HealthValidation resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a HealthValidation list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByParent(String resourceGroupName, String watcherName); + + /** + * List HealthValidation resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a HealthValidation list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByParent(String resourceGroupName, String watcherName, Context context); + + /** + * Starts health validation for a watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param healthValidationName The health validation resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + HealthValidation startValidation(String resourceGroupName, String watcherName, String healthValidationName); + + /** + * Starts health validation for a watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param healthValidationName The health validation resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + HealthValidation startValidation(String resourceGroupName, String watcherName, String healthValidationName, + Context context); +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/KustoOfferingType.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/KustoOfferingType.java new file mode 100644 index 000000000000..2d85bf99d3fd --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/KustoOfferingType.java @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The type of Kusto offering. + */ +public final class KustoOfferingType extends ExpandableStringEnum { + /** + * The Azure Data Explorer cluster Kusto offering. + */ + public static final KustoOfferingType ADX = fromString("adx"); + + /** + * The free Azure Data Explorer cluster Kusto offering. + */ + public static final KustoOfferingType FREE = fromString("free"); + + /** + * The Fabric Real-Time Analytics Kusto offering. + */ + public static final KustoOfferingType FABRIC = fromString("fabric"); + + /** + * Creates a new instance of KustoOfferingType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public KustoOfferingType() { + } + + /** + * Creates or finds a KustoOfferingType from its string representation. + * + * @param name a name to look for. + * @return the corresponding KustoOfferingType. + */ + public static KustoOfferingType fromString(String name) { + return fromString(name, KustoOfferingType.class); + } + + /** + * Gets known KustoOfferingType values. + * + * @return known KustoOfferingType values. + */ + public static Collection values() { + return values(KustoOfferingType.class); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/ManagedServiceIdentityType.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/ManagedServiceIdentityType.java new file mode 100644 index 000000000000..c7aea0404ae6 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/ManagedServiceIdentityType.java @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). + */ +public final class ManagedServiceIdentityType extends ExpandableStringEnum { + /** + * No managed identity. + */ + public static final ManagedServiceIdentityType NONE = fromString("None"); + + /** + * System assigned managed identity. + */ + public static final ManagedServiceIdentityType SYSTEM_ASSIGNED = fromString("SystemAssigned"); + + /** + * User assigned managed identity. + */ + public static final ManagedServiceIdentityType USER_ASSIGNED = fromString("UserAssigned"); + + /** + * System and user assigned managed identity. + */ + public static final ManagedServiceIdentityType SYSTEM_AND_USER_ASSIGNED + = fromString("SystemAssigned, UserAssigned"); + + /** + * Creates a new instance of ManagedServiceIdentityType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public ManagedServiceIdentityType() { + } + + /** + * Creates or finds a ManagedServiceIdentityType from its string representation. + * + * @param name a name to look for. + * @return the corresponding ManagedServiceIdentityType. + */ + public static ManagedServiceIdentityType fromString(String name) { + return fromString(name, ManagedServiceIdentityType.class); + } + + /** + * Gets known ManagedServiceIdentityType values. + * + * @return known ManagedServiceIdentityType values. + */ + public static Collection values() { + return values(ManagedServiceIdentityType.class); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/ManagedServiceIdentityV4.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/ManagedServiceIdentityV4.java new file mode 100644 index 000000000000..652f834744fb --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/ManagedServiceIdentityV4.java @@ -0,0 +1,178 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +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.Map; + +/** + * Managed service identity (system assigned and/or user assigned identities). + */ +@Fluent +public final class ManagedServiceIdentityV4 implements JsonSerializable { + /* + * The service principal ID of the system assigned identity. This property will only be provided for a system + * assigned identity. + */ + private String principalId; + + /* + * The tenant ID of the system assigned identity. This property will only be provided for a system assigned + * identity. + */ + private String tenantId; + + /* + * The type of managed identity assigned to this resource. + */ + private ManagedServiceIdentityType type; + + /* + * The identities assigned to this resource by the user. + */ + private Map userAssignedIdentities; + + /** + * Creates an instance of ManagedServiceIdentityV4 class. + */ + public ManagedServiceIdentityV4() { + } + + /** + * Get the principalId property: The service principal ID of the system assigned identity. This property will only + * be provided for a system assigned identity. + * + * @return the principalId value. + */ + public String principalId() { + return this.principalId; + } + + /** + * Get the tenantId property: The tenant ID of the system assigned identity. This property will only be provided for + * a system assigned identity. + * + * @return the tenantId value. + */ + public String tenantId() { + return this.tenantId; + } + + /** + * Get the type property: The type of managed identity assigned to this resource. + * + * @return the type value. + */ + public ManagedServiceIdentityType type() { + return this.type; + } + + /** + * Set the type property: The type of managed identity assigned to this resource. + * + * @param type the type value to set. + * @return the ManagedServiceIdentityV4 object itself. + */ + public ManagedServiceIdentityV4 withType(ManagedServiceIdentityType type) { + this.type = type; + return this; + } + + /** + * Get the userAssignedIdentities property: The identities assigned to this resource by the user. + * + * @return the userAssignedIdentities value. + */ + public Map userAssignedIdentities() { + return this.userAssignedIdentities; + } + + /** + * Set the userAssignedIdentities property: The identities assigned to this resource by the user. + * + * @param userAssignedIdentities the userAssignedIdentities value to set. + * @return the ManagedServiceIdentityV4 object itself. + */ + public ManagedServiceIdentityV4 + withUserAssignedIdentities(Map userAssignedIdentities) { + this.userAssignedIdentities = userAssignedIdentities; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (type() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property type in model ManagedServiceIdentityV4")); + } + if (userAssignedIdentities() != null) { + userAssignedIdentities().values().forEach(e -> { + if (e != null) { + e.validate(); + } + }); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(ManagedServiceIdentityV4.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + jsonWriter.writeMapField("userAssignedIdentities", this.userAssignedIdentities, + (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ManagedServiceIdentityV4 from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ManagedServiceIdentityV4 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 ManagedServiceIdentityV4. + */ + public static ManagedServiceIdentityV4 fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ManagedServiceIdentityV4 deserializedManagedServiceIdentityV4 = new ManagedServiceIdentityV4(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("type".equals(fieldName)) { + deserializedManagedServiceIdentityV4.type + = ManagedServiceIdentityType.fromString(reader.getString()); + } else if ("principalId".equals(fieldName)) { + deserializedManagedServiceIdentityV4.principalId = reader.getString(); + } else if ("tenantId".equals(fieldName)) { + deserializedManagedServiceIdentityV4.tenantId = reader.getString(); + } else if ("userAssignedIdentities".equals(fieldName)) { + Map userAssignedIdentities + = reader.readMap(reader1 -> UserAssignedIdentity.fromJson(reader1)); + deserializedManagedServiceIdentityV4.userAssignedIdentities = userAssignedIdentities; + } else { + reader.skipChildren(); + } + } + + return deserializedManagedServiceIdentityV4; + }); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/Operation.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/Operation.java new file mode 100644 index 000000000000..48748feea687 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/Operation.java @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.resourcemanager.databasewatcher.fluent.models.OperationInner; + +/** + * An immutable client-side representation of Operation. + */ +public interface Operation { + /** + * Gets the name property: The name of the operation, as per Resource-Based Access Control (RBAC). Examples: + * "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action". + * + * @return the name value. + */ + String name(); + + /** + * Gets the isDataAction property: Whether the operation applies to data-plane. This is "true" for data-plane + * operations and "false" for Azure Resource Manager/control-plane operations. + * + * @return the isDataAction value. + */ + Boolean isDataAction(); + + /** + * Gets the display property: Localized display information for this particular operation. + * + * @return the display value. + */ + OperationDisplay display(); + + /** + * Gets the origin property: The intended executor of the operation; as in Resource Based Access Control (RBAC) and + * audit logs UX. Default value is "user,system". + * + * @return the origin value. + */ + Origin origin(); + + /** + * Gets the actionType property: Extensible enum. Indicates the action type. "Internal" refers to actions that are + * for internal only APIs. + * + * @return the actionType value. + */ + ActionType actionType(); + + /** + * Gets the inner com.azure.resourcemanager.databasewatcher.fluent.models.OperationInner object. + * + * @return the inner object. + */ + OperationInner innerModel(); +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/OperationDisplay.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/OperationDisplay.java new file mode 100644 index 000000000000..e922507d7d08 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/OperationDisplay.java @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.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; + +/** + * Localized display information for and operation. + */ +@Immutable +public final class OperationDisplay implements JsonSerializable { + /* + * The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or + * "Microsoft Compute". + */ + private String provider; + + /* + * The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or + * "Job Schedule Collections". + */ + private String resource; + + /* + * The concise, localized friendly name for the operation; suitable for dropdowns. E.g. + * "Create or Update Virtual Machine", "Restart Virtual Machine". + */ + private String operation; + + /* + * The short, localized friendly description of the operation; suitable for tool tips and detailed views. + */ + private String description; + + /** + * Creates an instance of OperationDisplay class. + */ + private OperationDisplay() { + } + + /** + * Get the provider property: The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring + * Insights" or "Microsoft Compute". + * + * @return the provider value. + */ + public String provider() { + return this.provider; + } + + /** + * Get the resource property: The localized friendly name of the resource type related to this operation. E.g. + * "Virtual Machines" or "Job Schedule Collections". + * + * @return the resource value. + */ + public String resource() { + return this.resource; + } + + /** + * Get the operation property: The concise, localized friendly name for the operation; suitable for dropdowns. E.g. + * "Create or Update Virtual Machine", "Restart Virtual Machine". + * + * @return the operation value. + */ + public String operation() { + return this.operation; + } + + /** + * Get the description property: The short, localized friendly description of the operation; suitable for tool tips + * and detailed views. + * + * @return the description value. + */ + public String description() { + return this.description; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OperationDisplay from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OperationDisplay 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 OperationDisplay. + */ + public static OperationDisplay fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OperationDisplay deserializedOperationDisplay = new OperationDisplay(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("provider".equals(fieldName)) { + deserializedOperationDisplay.provider = reader.getString(); + } else if ("resource".equals(fieldName)) { + deserializedOperationDisplay.resource = reader.getString(); + } else if ("operation".equals(fieldName)) { + deserializedOperationDisplay.operation = reader.getString(); + } else if ("description".equals(fieldName)) { + deserializedOperationDisplay.description = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedOperationDisplay; + }); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/Operations.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/Operations.java new file mode 100644 index 000000000000..3ed2fa120569 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/Operations.java @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.Context; + +/** + * Resource collection API of Operations. + */ +public interface Operations { + /** + * List the operations for the provider. + * + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedIterable}. + */ + PagedIterable list(); + + /** + * List the operations for the provider. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedIterable}. + */ + PagedIterable list(Context context); +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/Origin.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/Origin.java new file mode 100644 index 000000000000..f403567a9448 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/Origin.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value + * is "user,system". + */ +public final class Origin extends ExpandableStringEnum { + /** + * Indicates the operation is initiated by a user. + */ + public static final Origin USER = fromString("user"); + + /** + * Indicates the operation is initiated by a system. + */ + public static final Origin SYSTEM = fromString("system"); + + /** + * Indicates the operation is initiated by a user or system. + */ + public static final Origin USER_SYSTEM = fromString("user,system"); + + /** + * Creates a new instance of Origin value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public Origin() { + } + + /** + * Creates or finds a Origin from its string representation. + * + * @param name a name to look for. + * @return the corresponding Origin. + */ + public static Origin fromString(String name) { + return fromString(name, Origin.class); + } + + /** + * Gets known Origin values. + * + * @return known Origin values. + */ + public static Collection values() { + return values(Origin.class); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/ResourceProvisioningState.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/ResourceProvisioningState.java new file mode 100644 index 000000000000..fb76a8624d24 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/ResourceProvisioningState.java @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The provisioning state of a resource type. + */ +public final class ResourceProvisioningState extends ExpandableStringEnum { + /** + * Resource has been created. + */ + public static final ResourceProvisioningState SUCCEEDED = fromString("Succeeded"); + + /** + * Resource creation failed. + */ + public static final ResourceProvisioningState FAILED = fromString("Failed"); + + /** + * Resource creation was canceled. + */ + public static final ResourceProvisioningState CANCELED = fromString("Canceled"); + + /** + * Creates a new instance of ResourceProvisioningState value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public ResourceProvisioningState() { + } + + /** + * Creates or finds a ResourceProvisioningState from its string representation. + * + * @param name a name to look for. + * @return the corresponding ResourceProvisioningState. + */ + public static ResourceProvisioningState fromString(String name) { + return fromString(name, ResourceProvisioningState.class); + } + + /** + * Gets known ResourceProvisioningState values. + * + * @return known ResourceProvisioningState values. + */ + public static Collection values() { + return values(ResourceProvisioningState.class); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/SharedPrivateLinkResource.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/SharedPrivateLinkResource.java new file mode 100644 index 000000000000..a06b3487df82 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/SharedPrivateLinkResource.java @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.databasewatcher.fluent.models.SharedPrivateLinkResourceInner; + +/** + * An immutable client-side representation of SharedPrivateLinkResource. + */ +public interface SharedPrivateLinkResource { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + SharedPrivateLinkResourceProperties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.databasewatcher.fluent.models.SharedPrivateLinkResourceInner object. + * + * @return the inner object. + */ + SharedPrivateLinkResourceInner innerModel(); + + /** + * The entirety of the SharedPrivateLinkResource definition. + */ + interface Definition + extends DefinitionStages.Blank, DefinitionStages.WithParentResource, DefinitionStages.WithCreate { + } + + /** + * The SharedPrivateLinkResource definition stages. + */ + interface DefinitionStages { + /** + * The first stage of the SharedPrivateLinkResource definition. + */ + interface Blank extends WithParentResource { + } + + /** + * The stage of the SharedPrivateLinkResource definition allowing to specify parent resource. + */ + interface WithParentResource { + /** + * Specifies resourceGroupName, watcherName. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @return the next definition stage. + */ + WithCreate withExistingWatcher(String resourceGroupName, String watcherName); + } + + /** + * The stage of the SharedPrivateLinkResource definition which contains all the minimum required properties for + * the resource to be created, but also allows for any other optional properties to be specified. + */ + interface WithCreate extends DefinitionStages.WithProperties { + /** + * Executes the create request. + * + * @return the created resource. + */ + SharedPrivateLinkResource create(); + + /** + * Executes the create request. + * + * @param context The context to associate with this operation. + * @return the created resource. + */ + SharedPrivateLinkResource create(Context context); + } + + /** + * The stage of the SharedPrivateLinkResource definition allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The resource-specific properties for this resource.. + * + * @param properties The resource-specific properties for this resource. + * @return the next definition stage. + */ + WithCreate withProperties(SharedPrivateLinkResourceProperties properties); + } + } + + /** + * Refreshes the resource to sync with Azure. + * + * @return the refreshed resource. + */ + SharedPrivateLinkResource refresh(); + + /** + * Refreshes the resource to sync with Azure. + * + * @param context The context to associate with this operation. + * @return the refreshed resource. + */ + SharedPrivateLinkResource refresh(Context context); +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/SharedPrivateLinkResourceProperties.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/SharedPrivateLinkResourceProperties.java new file mode 100644 index 000000000000..2a76234420f9 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/SharedPrivateLinkResourceProperties.java @@ -0,0 +1,247 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +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 generic properties of a Shared Private Link resource. + */ +@Fluent +public final class SharedPrivateLinkResourceProperties + implements JsonSerializable { + /* + * The resource ID of the resource the shared private link resource is for. + */ + private String privateLinkResourceId; + + /* + * The group id from the provider of resource the shared private link resource is for. + */ + private String groupId; + + /* + * The request message for requesting approval of the shared private link resource. + */ + private String requestMessage; + + /* + * The DNS zone segment to be included in the DNS name of the shared private link. Value is required for Azure Data + * Explorer clusters and SQL managed instances, and must be omitted for SQL logical servers and key vaults. The + * value is the second segment of the host FQDN name of the resource that the shared private link resource is for. + * For example: if the host name is 'adx-cluster-21187695.eastus.kusto.windows.net', then the value is 'eastus'; if + * the host name is 'sql-mi-23961134.767d5869f605.database.windows.net', then the value is '767d5869f605'. + */ + private String dnsZone; + + /* + * Status of the shared private link resource. Can be Pending, Approved, Rejected or Disconnected. + */ + private SharedPrivateLinkResourceStatus status; + + /* + * The provisioning state of the resource. + */ + private ResourceProvisioningState provisioningState; + + /** + * Creates an instance of SharedPrivateLinkResourceProperties class. + */ + public SharedPrivateLinkResourceProperties() { + } + + /** + * Get the privateLinkResourceId property: The resource ID of the resource the shared private link resource is for. + * + * @return the privateLinkResourceId value. + */ + public String privateLinkResourceId() { + return this.privateLinkResourceId; + } + + /** + * Set the privateLinkResourceId property: The resource ID of the resource the shared private link resource is for. + * + * @param privateLinkResourceId the privateLinkResourceId value to set. + * @return the SharedPrivateLinkResourceProperties object itself. + */ + public SharedPrivateLinkResourceProperties withPrivateLinkResourceId(String privateLinkResourceId) { + this.privateLinkResourceId = privateLinkResourceId; + return this; + } + + /** + * Get the groupId property: The group id from the provider of resource the shared private link resource is for. + * + * @return the groupId value. + */ + public String groupId() { + return this.groupId; + } + + /** + * Set the groupId property: The group id from the provider of resource the shared private link resource is for. + * + * @param groupId the groupId value to set. + * @return the SharedPrivateLinkResourceProperties object itself. + */ + public SharedPrivateLinkResourceProperties withGroupId(String groupId) { + this.groupId = groupId; + return this; + } + + /** + * Get the requestMessage property: The request message for requesting approval of the shared private link resource. + * + * @return the requestMessage value. + */ + public String requestMessage() { + return this.requestMessage; + } + + /** + * Set the requestMessage property: The request message for requesting approval of the shared private link resource. + * + * @param requestMessage the requestMessage value to set. + * @return the SharedPrivateLinkResourceProperties object itself. + */ + public SharedPrivateLinkResourceProperties withRequestMessage(String requestMessage) { + this.requestMessage = requestMessage; + return this; + } + + /** + * Get the dnsZone property: The DNS zone segment to be included in the DNS name of the shared private link. Value + * is required for Azure Data Explorer clusters and SQL managed instances, and must be omitted for SQL logical + * servers and key vaults. The value is the second segment of the host FQDN name of the resource that the shared + * private link resource is for. For example: if the host name is 'adx-cluster-21187695.eastus.kusto.windows.net', + * then the value is 'eastus'; if the host name is 'sql-mi-23961134.767d5869f605.database.windows.net', then the + * value is '767d5869f605'. + * + * @return the dnsZone value. + */ + public String dnsZone() { + return this.dnsZone; + } + + /** + * Set the dnsZone property: The DNS zone segment to be included in the DNS name of the shared private link. Value + * is required for Azure Data Explorer clusters and SQL managed instances, and must be omitted for SQL logical + * servers and key vaults. The value is the second segment of the host FQDN name of the resource that the shared + * private link resource is for. For example: if the host name is 'adx-cluster-21187695.eastus.kusto.windows.net', + * then the value is 'eastus'; if the host name is 'sql-mi-23961134.767d5869f605.database.windows.net', then the + * value is '767d5869f605'. + * + * @param dnsZone the dnsZone value to set. + * @return the SharedPrivateLinkResourceProperties object itself. + */ + public SharedPrivateLinkResourceProperties withDnsZone(String dnsZone) { + this.dnsZone = dnsZone; + return this; + } + + /** + * Get the status property: Status of the shared private link resource. Can be Pending, Approved, Rejected or + * Disconnected. + * + * @return the status value. + */ + public SharedPrivateLinkResourceStatus status() { + return this.status; + } + + /** + * Get the provisioningState property: The provisioning state of the resource. + * + * @return the provisioningState value. + */ + public ResourceProvisioningState provisioningState() { + return this.provisioningState; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (privateLinkResourceId() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property privateLinkResourceId in model SharedPrivateLinkResourceProperties")); + } + if (groupId() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property groupId in model SharedPrivateLinkResourceProperties")); + } + if (requestMessage() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property requestMessage in model SharedPrivateLinkResourceProperties")); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(SharedPrivateLinkResourceProperties.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("privateLinkResourceId", this.privateLinkResourceId); + jsonWriter.writeStringField("groupId", this.groupId); + jsonWriter.writeStringField("requestMessage", this.requestMessage); + jsonWriter.writeStringField("dnsZone", this.dnsZone); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SharedPrivateLinkResourceProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SharedPrivateLinkResourceProperties 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 SharedPrivateLinkResourceProperties. + */ + public static SharedPrivateLinkResourceProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SharedPrivateLinkResourceProperties deserializedSharedPrivateLinkResourceProperties + = new SharedPrivateLinkResourceProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("privateLinkResourceId".equals(fieldName)) { + deserializedSharedPrivateLinkResourceProperties.privateLinkResourceId = reader.getString(); + } else if ("groupId".equals(fieldName)) { + deserializedSharedPrivateLinkResourceProperties.groupId = reader.getString(); + } else if ("requestMessage".equals(fieldName)) { + deserializedSharedPrivateLinkResourceProperties.requestMessage = reader.getString(); + } else if ("dnsZone".equals(fieldName)) { + deserializedSharedPrivateLinkResourceProperties.dnsZone = reader.getString(); + } else if ("status".equals(fieldName)) { + deserializedSharedPrivateLinkResourceProperties.status + = SharedPrivateLinkResourceStatus.fromString(reader.getString()); + } else if ("provisioningState".equals(fieldName)) { + deserializedSharedPrivateLinkResourceProperties.provisioningState + = ResourceProvisioningState.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedSharedPrivateLinkResourceProperties; + }); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/SharedPrivateLinkResourceStatus.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/SharedPrivateLinkResourceStatus.java new file mode 100644 index 000000000000..54e4cce6b6d6 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/SharedPrivateLinkResourceStatus.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Status of the shared private link resource. Can be Pending, Approved, Rejected or Disconnected. + */ +public final class SharedPrivateLinkResourceStatus extends ExpandableStringEnum { + /** + * The shared private link connection request was not yet authorized by the resource owner. + */ + public static final SharedPrivateLinkResourceStatus PENDING = fromString("Pending"); + + /** + * The shared private link connection request was approved by the resource owner. + */ + public static final SharedPrivateLinkResourceStatus APPROVED = fromString("Approved"); + + /** + * The shared private link connection request was rejected by the resource owner. + */ + public static final SharedPrivateLinkResourceStatus REJECTED = fromString("Rejected"); + + /** + * The shared private link connection request was disconnected by the resource owner. + */ + public static final SharedPrivateLinkResourceStatus DISCONNECTED = fromString("Disconnected"); + + /** + * Creates a new instance of SharedPrivateLinkResourceStatus value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public SharedPrivateLinkResourceStatus() { + } + + /** + * Creates or finds a SharedPrivateLinkResourceStatus from its string representation. + * + * @param name a name to look for. + * @return the corresponding SharedPrivateLinkResourceStatus. + */ + public static SharedPrivateLinkResourceStatus fromString(String name) { + return fromString(name, SharedPrivateLinkResourceStatus.class); + } + + /** + * Gets known SharedPrivateLinkResourceStatus values. + * + * @return known SharedPrivateLinkResourceStatus values. + */ + public static Collection values() { + return values(SharedPrivateLinkResourceStatus.class); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/SharedPrivateLinkResources.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/SharedPrivateLinkResources.java new file mode 100644 index 000000000000..f6a2f28bc5d9 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/SharedPrivateLinkResources.java @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of SharedPrivateLinkResources. + */ +public interface SharedPrivateLinkResources { + /** + * Get a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SharedPrivateLinkResource along with {@link Response}. + */ + Response getWithResponse(String resourceGroupName, String watcherName, + String sharedPrivateLinkResourceName, Context context); + + /** + * Get a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SharedPrivateLinkResource. + */ + SharedPrivateLinkResource get(String resourceGroupName, String watcherName, String sharedPrivateLinkResourceName); + + /** + * Delete a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void delete(String resourceGroupName, String watcherName, String sharedPrivateLinkResourceName); + + /** + * Delete a SharedPrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param sharedPrivateLinkResourceName The Shared Private Link resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void delete(String resourceGroupName, String watcherName, String sharedPrivateLinkResourceName, Context context); + + /** + * List SharedPrivateLinkResource resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SharedPrivateLinkResource list operation as paginated response with + * {@link PagedIterable}. + */ + PagedIterable listByWatcher(String resourceGroupName, String watcherName); + + /** + * List SharedPrivateLinkResource resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SharedPrivateLinkResource list operation as paginated response with + * {@link PagedIterable}. + */ + PagedIterable listByWatcher(String resourceGroupName, String watcherName, + Context context); + + /** + * Get a SharedPrivateLinkResource. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SharedPrivateLinkResource along with {@link Response}. + */ + SharedPrivateLinkResource getById(String id); + + /** + * Get a SharedPrivateLinkResource. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SharedPrivateLinkResource along with {@link Response}. + */ + Response getByIdWithResponse(String id, Context context); + + /** + * Delete a SharedPrivateLinkResource. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteById(String id); + + /** + * Delete a SharedPrivateLinkResource. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteByIdWithResponse(String id, Context context); + + /** + * Begins definition for a new SharedPrivateLinkResource resource. + * + * @param name resource name. + * @return the first stage of the new SharedPrivateLinkResource definition. + */ + SharedPrivateLinkResource.DefinitionStages.Blank define(String name); +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/SqlDbElasticPoolTargetProperties.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/SqlDbElasticPoolTargetProperties.java new file mode 100644 index 000000000000..ce1df313d351 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/SqlDbElasticPoolTargetProperties.java @@ -0,0 +1,240 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * The properties specific to an elastic pool in Azure SQL Database. + */ +@Fluent +public final class SqlDbElasticPoolTargetProperties extends TargetProperties { + /* + * Discriminator property for TargetProperties. + */ + private String targetType = "SqlEp"; + + /* + * The Azure resource ID of an Azure SQL DB elastic pool target. + */ + private String sqlEpResourceId; + + /* + * The Azure resource ID of the anchor database used to connect to an elastic pool. + */ + private String anchorDatabaseResourceId; + + /* + * Set to true to monitor a high availability replica of specified target, if any. + */ + private Boolean readIntent; + + /** + * Creates an instance of SqlDbElasticPoolTargetProperties class. + */ + public SqlDbElasticPoolTargetProperties() { + } + + /** + * Get the targetType property: Discriminator property for TargetProperties. + * + * @return the targetType value. + */ + @Override + public String targetType() { + return this.targetType; + } + + /** + * Get the sqlEpResourceId property: The Azure resource ID of an Azure SQL DB elastic pool target. + * + * @return the sqlEpResourceId value. + */ + public String sqlEpResourceId() { + return this.sqlEpResourceId; + } + + /** + * Set the sqlEpResourceId property: The Azure resource ID of an Azure SQL DB elastic pool target. + * + * @param sqlEpResourceId the sqlEpResourceId value to set. + * @return the SqlDbElasticPoolTargetProperties object itself. + */ + public SqlDbElasticPoolTargetProperties withSqlEpResourceId(String sqlEpResourceId) { + this.sqlEpResourceId = sqlEpResourceId; + return this; + } + + /** + * Get the anchorDatabaseResourceId property: The Azure resource ID of the anchor database used to connect to an + * elastic pool. + * + * @return the anchorDatabaseResourceId value. + */ + public String anchorDatabaseResourceId() { + return this.anchorDatabaseResourceId; + } + + /** + * Set the anchorDatabaseResourceId property: The Azure resource ID of the anchor database used to connect to an + * elastic pool. + * + * @param anchorDatabaseResourceId the anchorDatabaseResourceId value to set. + * @return the SqlDbElasticPoolTargetProperties object itself. + */ + public SqlDbElasticPoolTargetProperties withAnchorDatabaseResourceId(String anchorDatabaseResourceId) { + this.anchorDatabaseResourceId = anchorDatabaseResourceId; + return this; + } + + /** + * Get the readIntent property: Set to true to monitor a high availability replica of specified target, if any. + * + * @return the readIntent value. + */ + public Boolean readIntent() { + return this.readIntent; + } + + /** + * Set the readIntent property: Set to true to monitor a high availability replica of specified target, if any. + * + * @param readIntent the readIntent value to set. + * @return the SqlDbElasticPoolTargetProperties object itself. + */ + public SqlDbElasticPoolTargetProperties withReadIntent(Boolean readIntent) { + this.readIntent = readIntent; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlDbElasticPoolTargetProperties + withTargetAuthenticationType(TargetAuthenticationType targetAuthenticationType) { + super.withTargetAuthenticationType(targetAuthenticationType); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlDbElasticPoolTargetProperties withTargetVault(VaultSecret targetVault) { + super.withTargetVault(targetVault); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlDbElasticPoolTargetProperties withConnectionServerName(String connectionServerName) { + super.withConnectionServerName(connectionServerName); + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + @Override + public void validate() { + if (sqlEpResourceId() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property sqlEpResourceId in model SqlDbElasticPoolTargetProperties")); + } + if (anchorDatabaseResourceId() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property anchorDatabaseResourceId in model SqlDbElasticPoolTargetProperties")); + } + if (targetAuthenticationType() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property targetAuthenticationType in model SqlDbElasticPoolTargetProperties")); + } + if (targetVault() != null) { + targetVault().validate(); + } + if (connectionServerName() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property connectionServerName in model SqlDbElasticPoolTargetProperties")); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(SqlDbElasticPoolTargetProperties.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("targetAuthenticationType", + targetAuthenticationType() == null ? null : targetAuthenticationType().toString()); + jsonWriter.writeStringField("connectionServerName", connectionServerName()); + jsonWriter.writeJsonField("targetVault", targetVault()); + jsonWriter.writeStringField("sqlEpResourceId", this.sqlEpResourceId); + jsonWriter.writeStringField("anchorDatabaseResourceId", this.anchorDatabaseResourceId); + jsonWriter.writeStringField("targetType", this.targetType); + jsonWriter.writeBooleanField("readIntent", this.readIntent); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlDbElasticPoolTargetProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlDbElasticPoolTargetProperties 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 SqlDbElasticPoolTargetProperties. + */ + public static SqlDbElasticPoolTargetProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlDbElasticPoolTargetProperties deserializedSqlDbElasticPoolTargetProperties + = new SqlDbElasticPoolTargetProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("targetAuthenticationType".equals(fieldName)) { + deserializedSqlDbElasticPoolTargetProperties + .withTargetAuthenticationType(TargetAuthenticationType.fromString(reader.getString())); + } else if ("connectionServerName".equals(fieldName)) { + deserializedSqlDbElasticPoolTargetProperties.withConnectionServerName(reader.getString()); + } else if ("targetVault".equals(fieldName)) { + deserializedSqlDbElasticPoolTargetProperties.withTargetVault(VaultSecret.fromJson(reader)); + } else if ("provisioningState".equals(fieldName)) { + deserializedSqlDbElasticPoolTargetProperties + .withProvisioningState(ResourceProvisioningState.fromString(reader.getString())); + } else if ("sqlEpResourceId".equals(fieldName)) { + deserializedSqlDbElasticPoolTargetProperties.sqlEpResourceId = reader.getString(); + } else if ("anchorDatabaseResourceId".equals(fieldName)) { + deserializedSqlDbElasticPoolTargetProperties.anchorDatabaseResourceId = reader.getString(); + } else if ("targetType".equals(fieldName)) { + deserializedSqlDbElasticPoolTargetProperties.targetType = reader.getString(); + } else if ("readIntent".equals(fieldName)) { + deserializedSqlDbElasticPoolTargetProperties.readIntent + = reader.getNullable(JsonReader::getBoolean); + } else { + reader.skipChildren(); + } + } + + return deserializedSqlDbElasticPoolTargetProperties; + }); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/SqlDbSingleDatabaseTargetProperties.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/SqlDbSingleDatabaseTargetProperties.java new file mode 100644 index 000000000000..6998d5174786 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/SqlDbSingleDatabaseTargetProperties.java @@ -0,0 +1,205 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * The properties specific to a database in Azure SQL Database. + */ +@Fluent +public final class SqlDbSingleDatabaseTargetProperties extends TargetProperties { + /* + * Discriminator property for TargetProperties. + */ + private String targetType = "SqlDb"; + + /* + * The Azure resource ID of an Azure SQL DB database target. + */ + private String sqlDbResourceId; + + /* + * Set to true to monitor a high availability replica of specified target, if any. + */ + private Boolean readIntent; + + /** + * Creates an instance of SqlDbSingleDatabaseTargetProperties class. + */ + public SqlDbSingleDatabaseTargetProperties() { + } + + /** + * Get the targetType property: Discriminator property for TargetProperties. + * + * @return the targetType value. + */ + @Override + public String targetType() { + return this.targetType; + } + + /** + * Get the sqlDbResourceId property: The Azure resource ID of an Azure SQL DB database target. + * + * @return the sqlDbResourceId value. + */ + public String sqlDbResourceId() { + return this.sqlDbResourceId; + } + + /** + * Set the sqlDbResourceId property: The Azure resource ID of an Azure SQL DB database target. + * + * @param sqlDbResourceId the sqlDbResourceId value to set. + * @return the SqlDbSingleDatabaseTargetProperties object itself. + */ + public SqlDbSingleDatabaseTargetProperties withSqlDbResourceId(String sqlDbResourceId) { + this.sqlDbResourceId = sqlDbResourceId; + return this; + } + + /** + * Get the readIntent property: Set to true to monitor a high availability replica of specified target, if any. + * + * @return the readIntent value. + */ + public Boolean readIntent() { + return this.readIntent; + } + + /** + * Set the readIntent property: Set to true to monitor a high availability replica of specified target, if any. + * + * @param readIntent the readIntent value to set. + * @return the SqlDbSingleDatabaseTargetProperties object itself. + */ + public SqlDbSingleDatabaseTargetProperties withReadIntent(Boolean readIntent) { + this.readIntent = readIntent; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlDbSingleDatabaseTargetProperties + withTargetAuthenticationType(TargetAuthenticationType targetAuthenticationType) { + super.withTargetAuthenticationType(targetAuthenticationType); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlDbSingleDatabaseTargetProperties withTargetVault(VaultSecret targetVault) { + super.withTargetVault(targetVault); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlDbSingleDatabaseTargetProperties withConnectionServerName(String connectionServerName) { + super.withConnectionServerName(connectionServerName); + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + @Override + public void validate() { + if (sqlDbResourceId() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property sqlDbResourceId in model SqlDbSingleDatabaseTargetProperties")); + } + if (targetAuthenticationType() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property targetAuthenticationType in model SqlDbSingleDatabaseTargetProperties")); + } + if (targetVault() != null) { + targetVault().validate(); + } + if (connectionServerName() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property connectionServerName in model SqlDbSingleDatabaseTargetProperties")); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(SqlDbSingleDatabaseTargetProperties.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("targetAuthenticationType", + targetAuthenticationType() == null ? null : targetAuthenticationType().toString()); + jsonWriter.writeStringField("connectionServerName", connectionServerName()); + jsonWriter.writeJsonField("targetVault", targetVault()); + jsonWriter.writeStringField("sqlDbResourceId", this.sqlDbResourceId); + jsonWriter.writeStringField("targetType", this.targetType); + jsonWriter.writeBooleanField("readIntent", this.readIntent); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlDbSingleDatabaseTargetProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlDbSingleDatabaseTargetProperties 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 SqlDbSingleDatabaseTargetProperties. + */ + public static SqlDbSingleDatabaseTargetProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlDbSingleDatabaseTargetProperties deserializedSqlDbSingleDatabaseTargetProperties + = new SqlDbSingleDatabaseTargetProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("targetAuthenticationType".equals(fieldName)) { + deserializedSqlDbSingleDatabaseTargetProperties + .withTargetAuthenticationType(TargetAuthenticationType.fromString(reader.getString())); + } else if ("connectionServerName".equals(fieldName)) { + deserializedSqlDbSingleDatabaseTargetProperties.withConnectionServerName(reader.getString()); + } else if ("targetVault".equals(fieldName)) { + deserializedSqlDbSingleDatabaseTargetProperties.withTargetVault(VaultSecret.fromJson(reader)); + } else if ("provisioningState".equals(fieldName)) { + deserializedSqlDbSingleDatabaseTargetProperties + .withProvisioningState(ResourceProvisioningState.fromString(reader.getString())); + } else if ("sqlDbResourceId".equals(fieldName)) { + deserializedSqlDbSingleDatabaseTargetProperties.sqlDbResourceId = reader.getString(); + } else if ("targetType".equals(fieldName)) { + deserializedSqlDbSingleDatabaseTargetProperties.targetType = reader.getString(); + } else if ("readIntent".equals(fieldName)) { + deserializedSqlDbSingleDatabaseTargetProperties.readIntent + = reader.getNullable(JsonReader::getBoolean); + } else { + reader.skipChildren(); + } + } + + return deserializedSqlDbSingleDatabaseTargetProperties; + }); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/SqlMiTargetProperties.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/SqlMiTargetProperties.java new file mode 100644 index 000000000000..1551023c14bb --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/SqlMiTargetProperties.java @@ -0,0 +1,233 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * The properties specific to Azure SQL Managed Instance targets. + */ +@Fluent +public final class SqlMiTargetProperties extends TargetProperties { + /* + * Discriminator property for TargetProperties. + */ + private String targetType = "SqlMi"; + + /* + * The Azure resource ID of an Azure SQL Managed Instance target. + */ + private String sqlMiResourceId; + + /* + * The TCP port number to optionally use in the connection string when connecting to an Azure SQL Managed Instance + * target. + */ + private Integer connectionTcpPort; + + /* + * Set to true to monitor a high availability replica of specified target, if any. + */ + private Boolean readIntent; + + /** + * Creates an instance of SqlMiTargetProperties class. + */ + public SqlMiTargetProperties() { + } + + /** + * Get the targetType property: Discriminator property for TargetProperties. + * + * @return the targetType value. + */ + @Override + public String targetType() { + return this.targetType; + } + + /** + * Get the sqlMiResourceId property: The Azure resource ID of an Azure SQL Managed Instance target. + * + * @return the sqlMiResourceId value. + */ + public String sqlMiResourceId() { + return this.sqlMiResourceId; + } + + /** + * Set the sqlMiResourceId property: The Azure resource ID of an Azure SQL Managed Instance target. + * + * @param sqlMiResourceId the sqlMiResourceId value to set. + * @return the SqlMiTargetProperties object itself. + */ + public SqlMiTargetProperties withSqlMiResourceId(String sqlMiResourceId) { + this.sqlMiResourceId = sqlMiResourceId; + return this; + } + + /** + * Get the connectionTcpPort property: The TCP port number to optionally use in the connection string when + * connecting to an Azure SQL Managed Instance target. + * + * @return the connectionTcpPort value. + */ + public Integer connectionTcpPort() { + return this.connectionTcpPort; + } + + /** + * Set the connectionTcpPort property: The TCP port number to optionally use in the connection string when + * connecting to an Azure SQL Managed Instance target. + * + * @param connectionTcpPort the connectionTcpPort value to set. + * @return the SqlMiTargetProperties object itself. + */ + public SqlMiTargetProperties withConnectionTcpPort(Integer connectionTcpPort) { + this.connectionTcpPort = connectionTcpPort; + return this; + } + + /** + * Get the readIntent property: Set to true to monitor a high availability replica of specified target, if any. + * + * @return the readIntent value. + */ + public Boolean readIntent() { + return this.readIntent; + } + + /** + * Set the readIntent property: Set to true to monitor a high availability replica of specified target, if any. + * + * @param readIntent the readIntent value to set. + * @return the SqlMiTargetProperties object itself. + */ + public SqlMiTargetProperties withReadIntent(Boolean readIntent) { + this.readIntent = readIntent; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlMiTargetProperties withTargetAuthenticationType(TargetAuthenticationType targetAuthenticationType) { + super.withTargetAuthenticationType(targetAuthenticationType); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlMiTargetProperties withTargetVault(VaultSecret targetVault) { + super.withTargetVault(targetVault); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlMiTargetProperties withConnectionServerName(String connectionServerName) { + super.withConnectionServerName(connectionServerName); + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + @Override + public void validate() { + if (sqlMiResourceId() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property sqlMiResourceId in model SqlMiTargetProperties")); + } + if (targetAuthenticationType() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property targetAuthenticationType in model SqlMiTargetProperties")); + } + if (targetVault() != null) { + targetVault().validate(); + } + if (connectionServerName() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property connectionServerName in model SqlMiTargetProperties")); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(SqlMiTargetProperties.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("targetAuthenticationType", + targetAuthenticationType() == null ? null : targetAuthenticationType().toString()); + jsonWriter.writeStringField("connectionServerName", connectionServerName()); + jsonWriter.writeJsonField("targetVault", targetVault()); + jsonWriter.writeStringField("sqlMiResourceId", this.sqlMiResourceId); + jsonWriter.writeStringField("targetType", this.targetType); + jsonWriter.writeNumberField("connectionTcpPort", this.connectionTcpPort); + jsonWriter.writeBooleanField("readIntent", this.readIntent); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlMiTargetProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlMiTargetProperties 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 SqlMiTargetProperties. + */ + public static SqlMiTargetProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlMiTargetProperties deserializedSqlMiTargetProperties = new SqlMiTargetProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("targetAuthenticationType".equals(fieldName)) { + deserializedSqlMiTargetProperties + .withTargetAuthenticationType(TargetAuthenticationType.fromString(reader.getString())); + } else if ("connectionServerName".equals(fieldName)) { + deserializedSqlMiTargetProperties.withConnectionServerName(reader.getString()); + } else if ("targetVault".equals(fieldName)) { + deserializedSqlMiTargetProperties.withTargetVault(VaultSecret.fromJson(reader)); + } else if ("provisioningState".equals(fieldName)) { + deserializedSqlMiTargetProperties + .withProvisioningState(ResourceProvisioningState.fromString(reader.getString())); + } else if ("sqlMiResourceId".equals(fieldName)) { + deserializedSqlMiTargetProperties.sqlMiResourceId = reader.getString(); + } else if ("targetType".equals(fieldName)) { + deserializedSqlMiTargetProperties.targetType = reader.getString(); + } else if ("connectionTcpPort".equals(fieldName)) { + deserializedSqlMiTargetProperties.connectionTcpPort = reader.getNullable(JsonReader::getInt); + } else if ("readIntent".equals(fieldName)) { + deserializedSqlMiTargetProperties.readIntent = reader.getNullable(JsonReader::getBoolean); + } else { + reader.skipChildren(); + } + } + + return deserializedSqlMiTargetProperties; + }); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/Target.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/Target.java new file mode 100644 index 000000000000..285d5c0d444f --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/Target.java @@ -0,0 +1,189 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.databasewatcher.fluent.models.TargetInner; + +/** + * An immutable client-side representation of Target. + */ +public interface Target { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + TargetProperties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the name of the resource group. + * + * @return the name of the resource group. + */ + String resourceGroupName(); + + /** + * Gets the inner com.azure.resourcemanager.databasewatcher.fluent.models.TargetInner object. + * + * @return the inner object. + */ + TargetInner innerModel(); + + /** + * The entirety of the Target definition. + */ + interface Definition + extends DefinitionStages.Blank, DefinitionStages.WithParentResource, DefinitionStages.WithCreate { + } + + /** + * The Target definition stages. + */ + interface DefinitionStages { + /** + * The first stage of the Target definition. + */ + interface Blank extends WithParentResource { + } + + /** + * The stage of the Target definition allowing to specify parent resource. + */ + interface WithParentResource { + /** + * Specifies resourceGroupName, watcherName. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @return the next definition stage. + */ + WithCreate withExistingWatcher(String resourceGroupName, String watcherName); + } + + /** + * The stage of the Target definition which contains all the minimum required properties for the resource to be + * created, but also allows for any other optional properties to be specified. + */ + interface WithCreate extends DefinitionStages.WithProperties { + /** + * Executes the create request. + * + * @return the created resource. + */ + Target create(); + + /** + * Executes the create request. + * + * @param context The context to associate with this operation. + * @return the created resource. + */ + Target create(Context context); + } + + /** + * The stage of the Target definition allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The resource-specific properties for this resource.. + * + * @param properties The resource-specific properties for this resource. + * @return the next definition stage. + */ + WithCreate withProperties(TargetProperties properties); + } + } + + /** + * Begins update for the Target resource. + * + * @return the stage of resource update. + */ + Target.Update update(); + + /** + * The template for Target update. + */ + interface Update extends UpdateStages.WithProperties { + /** + * Executes the update request. + * + * @return the updated resource. + */ + Target apply(); + + /** + * Executes the update request. + * + * @param context The context to associate with this operation. + * @return the updated resource. + */ + Target apply(Context context); + } + + /** + * The Target update stages. + */ + interface UpdateStages { + /** + * The stage of the Target update allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The resource-specific properties for this resource.. + * + * @param properties The resource-specific properties for this resource. + * @return the next definition stage. + */ + Update withProperties(TargetProperties properties); + } + } + + /** + * Refreshes the resource to sync with Azure. + * + * @return the refreshed resource. + */ + Target refresh(); + + /** + * Refreshes the resource to sync with Azure. + * + * @param context The context to associate with this operation. + * @return the refreshed resource. + */ + Target refresh(Context context); +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/TargetAuthenticationType.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/TargetAuthenticationType.java new file mode 100644 index 000000000000..60f7154502ae --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/TargetAuthenticationType.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The type of authentication to use when connecting to a target. + */ +public final class TargetAuthenticationType extends ExpandableStringEnum { + /** + * The Azure Active Directory authentication. + */ + public static final TargetAuthenticationType AAD = fromString("Aad"); + + /** + * The SQL password authentication. + */ + public static final TargetAuthenticationType SQL = fromString("Sql"); + + /** + * Creates a new instance of TargetAuthenticationType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public TargetAuthenticationType() { + } + + /** + * Creates or finds a TargetAuthenticationType from its string representation. + * + * @param name a name to look for. + * @return the corresponding TargetAuthenticationType. + */ + public static TargetAuthenticationType fromString(String name) { + return fromString(name, TargetAuthenticationType.class); + } + + /** + * Gets known TargetAuthenticationType values. + * + * @return known TargetAuthenticationType values. + */ + public static Collection values() { + return values(TargetAuthenticationType.class); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/TargetProperties.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/TargetProperties.java new file mode 100644 index 000000000000..7e1962f52d2b --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/TargetProperties.java @@ -0,0 +1,257 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +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 generic properties of a target. + */ +@Fluent +public class TargetProperties implements JsonSerializable { + /* + * Discriminator property for TargetProperties. + */ + private String targetType = "TargetProperties"; + + /* + * The type of authentication to use when connecting to a target. + */ + private TargetAuthenticationType targetAuthenticationType; + + /* + * To use SQL authentication when connecting to targets, specify the vault where the login name and password secrets + * are stored. + */ + private VaultSecret targetVault; + + /* + * The FQDN host name of the server to use in the connection string when connecting to a target. For example, for an + * Azure SQL logical server in the Azure commercial cloud, the value might be + * 'sql-logical-server-22092780.database.windows.net'; for an Azure SQL managed instance in the Azure commercial + * cloud, the value might be 'sql-mi-39441134.767d5869f605.database.windows.net'. Port number and instance name must + * be specified separately. + */ + private String connectionServerName; + + /* + * The provisioning state of the resource. + */ + private ResourceProvisioningState provisioningState; + + /** + * Creates an instance of TargetProperties class. + */ + public TargetProperties() { + } + + /** + * Get the targetType property: Discriminator property for TargetProperties. + * + * @return the targetType value. + */ + public String targetType() { + return this.targetType; + } + + /** + * Get the targetAuthenticationType property: The type of authentication to use when connecting to a target. + * + * @return the targetAuthenticationType value. + */ + public TargetAuthenticationType targetAuthenticationType() { + return this.targetAuthenticationType; + } + + /** + * Set the targetAuthenticationType property: The type of authentication to use when connecting to a target. + * + * @param targetAuthenticationType the targetAuthenticationType value to set. + * @return the TargetProperties object itself. + */ + public TargetProperties withTargetAuthenticationType(TargetAuthenticationType targetAuthenticationType) { + this.targetAuthenticationType = targetAuthenticationType; + return this; + } + + /** + * Get the targetVault property: To use SQL authentication when connecting to targets, specify the vault where the + * login name and password secrets are stored. + * + * @return the targetVault value. + */ + public VaultSecret targetVault() { + return this.targetVault; + } + + /** + * Set the targetVault property: To use SQL authentication when connecting to targets, specify the vault where the + * login name and password secrets are stored. + * + * @param targetVault the targetVault value to set. + * @return the TargetProperties object itself. + */ + public TargetProperties withTargetVault(VaultSecret targetVault) { + this.targetVault = targetVault; + return this; + } + + /** + * Get the connectionServerName property: The FQDN host name of the server to use in the connection string when + * connecting to a target. For example, for an Azure SQL logical server in the Azure commercial cloud, the value + * might be 'sql-logical-server-22092780.database.windows.net'; for an Azure SQL managed instance in the Azure + * commercial cloud, the value might be 'sql-mi-39441134.767d5869f605.database.windows.net'. Port number and + * instance name must be specified separately. + * + * @return the connectionServerName value. + */ + public String connectionServerName() { + return this.connectionServerName; + } + + /** + * Set the connectionServerName property: The FQDN host name of the server to use in the connection string when + * connecting to a target. For example, for an Azure SQL logical server in the Azure commercial cloud, the value + * might be 'sql-logical-server-22092780.database.windows.net'; for an Azure SQL managed instance in the Azure + * commercial cloud, the value might be 'sql-mi-39441134.767d5869f605.database.windows.net'. Port number and + * instance name must be specified separately. + * + * @param connectionServerName the connectionServerName value to set. + * @return the TargetProperties object itself. + */ + public TargetProperties withConnectionServerName(String connectionServerName) { + this.connectionServerName = connectionServerName; + return this; + } + + /** + * Get the provisioningState property: The provisioning state of the resource. + * + * @return the provisioningState value. + */ + public ResourceProvisioningState provisioningState() { + return this.provisioningState; + } + + /** + * Set the provisioningState property: The provisioning state of the resource. + * + * @param provisioningState the provisioningState value to set. + * @return the TargetProperties object itself. + */ + TargetProperties withProvisioningState(ResourceProvisioningState provisioningState) { + this.provisioningState = provisioningState; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (targetAuthenticationType() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property targetAuthenticationType in model TargetProperties")); + } + if (targetVault() != null) { + targetVault().validate(); + } + if (connectionServerName() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property connectionServerName in model TargetProperties")); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(TargetProperties.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("targetAuthenticationType", + this.targetAuthenticationType == null ? null : this.targetAuthenticationType.toString()); + jsonWriter.writeStringField("connectionServerName", this.connectionServerName); + jsonWriter.writeStringField("targetType", this.targetType); + jsonWriter.writeJsonField("targetVault", this.targetVault); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of TargetProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of TargetProperties 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 TargetProperties. + */ + public static TargetProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String discriminatorValue = null; + try (JsonReader readerToUse = reader.bufferObject()) { + readerToUse.nextToken(); // Prepare for reading + while (readerToUse.nextToken() != JsonToken.END_OBJECT) { + String fieldName = readerToUse.getFieldName(); + readerToUse.nextToken(); + if ("targetType".equals(fieldName)) { + discriminatorValue = readerToUse.getString(); + break; + } else { + readerToUse.skipChildren(); + } + } + // Use the discriminator value to determine which subtype should be deserialized. + if ("SqlDb".equals(discriminatorValue)) { + return SqlDbSingleDatabaseTargetProperties.fromJson(readerToUse.reset()); + } else if ("SqlEp".equals(discriminatorValue)) { + return SqlDbElasticPoolTargetProperties.fromJson(readerToUse.reset()); + } else if ("SqlMi".equals(discriminatorValue)) { + return SqlMiTargetProperties.fromJson(readerToUse.reset()); + } else { + return fromJsonKnownDiscriminator(readerToUse.reset()); + } + } + }); + } + + static TargetProperties fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + TargetProperties deserializedTargetProperties = new TargetProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("targetAuthenticationType".equals(fieldName)) { + deserializedTargetProperties.targetAuthenticationType + = TargetAuthenticationType.fromString(reader.getString()); + } else if ("connectionServerName".equals(fieldName)) { + deserializedTargetProperties.connectionServerName = reader.getString(); + } else if ("targetType".equals(fieldName)) { + deserializedTargetProperties.targetType = reader.getString(); + } else if ("targetVault".equals(fieldName)) { + deserializedTargetProperties.targetVault = VaultSecret.fromJson(reader); + } else if ("provisioningState".equals(fieldName)) { + deserializedTargetProperties.provisioningState + = ResourceProvisioningState.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedTargetProperties; + }); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/Targets.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/Targets.java new file mode 100644 index 000000000000..8ffb57ad1d21 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/Targets.java @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of Targets. + */ +public interface Targets { + /** + * Get a Target. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param targetName The target resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Target along with {@link Response}. + */ + Response getWithResponse(String resourceGroupName, String watcherName, String targetName, Context context); + + /** + * Get a Target. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param targetName The target resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Target. + */ + Target get(String resourceGroupName, String watcherName, String targetName); + + /** + * Delete a Target. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param targetName The target resource name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteWithResponse(String resourceGroupName, String watcherName, String targetName, Context context); + + /** + * Delete a Target. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param targetName The target resource name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void delete(String resourceGroupName, String watcherName, String targetName); + + /** + * List Target resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Target list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByWatcher(String resourceGroupName, String watcherName); + + /** + * List Target resources by Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Target list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByWatcher(String resourceGroupName, String watcherName, Context context); + + /** + * Get a Target. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Target along with {@link Response}. + */ + Target getById(String id); + + /** + * Get a Target. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Target along with {@link Response}. + */ + Response getByIdWithResponse(String id, Context context); + + /** + * Delete a Target. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteById(String id); + + /** + * Delete a Target. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteByIdWithResponse(String id, Context context); + + /** + * Begins definition for a new Target resource. + * + * @param name resource name. + * @return the first stage of the new Target definition. + */ + Target.DefinitionStages.Blank define(String name); +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/UserAssignedIdentity.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/UserAssignedIdentity.java new file mode 100644 index 000000000000..0f2738a4a553 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/UserAssignedIdentity.java @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.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; + +/** + * User assigned identity properties. + */ +@Immutable +public final class UserAssignedIdentity implements JsonSerializable { + /* + * The client ID of the assigned identity. + */ + private String clientId; + + /* + * The principal ID of the assigned identity. + */ + private String principalId; + + /** + * Creates an instance of UserAssignedIdentity class. + */ + public UserAssignedIdentity() { + } + + /** + * Get the clientId property: The client ID of the assigned identity. + * + * @return the clientId value. + */ + public String clientId() { + return this.clientId; + } + + /** + * Get the principalId property: The principal ID of the assigned identity. + * + * @return the principalId value. + */ + public String principalId() { + return this.principalId; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of UserAssignedIdentity from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of UserAssignedIdentity 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 UserAssignedIdentity. + */ + public static UserAssignedIdentity fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + UserAssignedIdentity deserializedUserAssignedIdentity = new UserAssignedIdentity(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("clientId".equals(fieldName)) { + deserializedUserAssignedIdentity.clientId = reader.getString(); + } else if ("principalId".equals(fieldName)) { + deserializedUserAssignedIdentity.principalId = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedUserAssignedIdentity; + }); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/ValidationIssue.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/ValidationIssue.java new file mode 100644 index 000000000000..b82237e97f03 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/ValidationIssue.java @@ -0,0 +1,178 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.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 model of a health validation issue. + */ +@Immutable +public final class ValidationIssue implements JsonSerializable { + /* + * The error code of the issue. + */ + private String errorCode; + + /* + * The error message of the issue. + */ + private String errorMessage; + + /* + * The additional details for the issue. + */ + private String additionalDetails; + + /* + * The recommendation for resolving the issue. + */ + private String recommendationMessage; + + /* + * The URL related to resolving the issue. + */ + private String recommendationUrl; + + /* + * The resource ID of the Azure resource related to the issue. + */ + private String relatedResourceId; + + /* + * The type of the Azure resource related to the issue. + */ + private String relatedResourceType; + + /** + * Creates an instance of ValidationIssue class. + */ + private ValidationIssue() { + } + + /** + * Get the errorCode property: The error code of the issue. + * + * @return the errorCode value. + */ + public String errorCode() { + return this.errorCode; + } + + /** + * Get the errorMessage property: The error message of the issue. + * + * @return the errorMessage value. + */ + public String errorMessage() { + return this.errorMessage; + } + + /** + * Get the additionalDetails property: The additional details for the issue. + * + * @return the additionalDetails value. + */ + public String additionalDetails() { + return this.additionalDetails; + } + + /** + * Get the recommendationMessage property: The recommendation for resolving the issue. + * + * @return the recommendationMessage value. + */ + public String recommendationMessage() { + return this.recommendationMessage; + } + + /** + * Get the recommendationUrl property: The URL related to resolving the issue. + * + * @return the recommendationUrl value. + */ + public String recommendationUrl() { + return this.recommendationUrl; + } + + /** + * Get the relatedResourceId property: The resource ID of the Azure resource related to the issue. + * + * @return the relatedResourceId value. + */ + public String relatedResourceId() { + return this.relatedResourceId; + } + + /** + * Get the relatedResourceType property: The type of the Azure resource related to the issue. + * + * @return the relatedResourceType value. + */ + public String relatedResourceType() { + return this.relatedResourceType; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ValidationIssue from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ValidationIssue 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 ValidationIssue. + */ + public static ValidationIssue fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ValidationIssue deserializedValidationIssue = new ValidationIssue(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("errorCode".equals(fieldName)) { + deserializedValidationIssue.errorCode = reader.getString(); + } else if ("errorMessage".equals(fieldName)) { + deserializedValidationIssue.errorMessage = reader.getString(); + } else if ("recommendationMessage".equals(fieldName)) { + deserializedValidationIssue.recommendationMessage = reader.getString(); + } else if ("additionalDetails".equals(fieldName)) { + deserializedValidationIssue.additionalDetails = reader.getString(); + } else if ("recommendationUrl".equals(fieldName)) { + deserializedValidationIssue.recommendationUrl = reader.getString(); + } else if ("relatedResourceId".equals(fieldName)) { + deserializedValidationIssue.relatedResourceId = reader.getString(); + } else if ("relatedResourceType".equals(fieldName)) { + deserializedValidationIssue.relatedResourceType = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedValidationIssue; + }); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/ValidationStatus.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/ValidationStatus.java new file mode 100644 index 000000000000..a80c2a91c57b --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/ValidationStatus.java @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Health validation status. + */ +public final class ValidationStatus extends ExpandableStringEnum { + /** + * Health validation has not started. + */ + public static final ValidationStatus NOT_STARTED = fromString("NotStarted"); + + /** + * Health validation is running. + */ + public static final ValidationStatus RUNNING = fromString("Running"); + + /** + * Health validation completed successfully. + */ + public static final ValidationStatus SUCCEEDED = fromString("Succeeded"); + + /** + * Health validation failed. + */ + public static final ValidationStatus FAILED = fromString("Failed"); + + /** + * Health validation was canceled. + */ + public static final ValidationStatus CANCELED = fromString("Canceled"); + + /** + * Health validation timed out. + */ + public static final ValidationStatus TIMED_OUT = fromString("TimedOut"); + + /** + * Creates a new instance of ValidationStatus value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public ValidationStatus() { + } + + /** + * Creates or finds a ValidationStatus from its string representation. + * + * @param name a name to look for. + * @return the corresponding ValidationStatus. + */ + public static ValidationStatus fromString(String name) { + return fromString(name, ValidationStatus.class); + } + + /** + * Gets known ValidationStatus values. + * + * @return known ValidationStatus values. + */ + public static Collection values() { + return values(ValidationStatus.class); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/VaultSecret.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/VaultSecret.java new file mode 100644 index 000000000000..078b2a8442e7 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/VaultSecret.java @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.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; + +/** + * The vault specific details required if using SQL authentication to connect to a target. + */ +@Fluent +public final class VaultSecret implements JsonSerializable { + /* + * The Azure resource ID of the Key Vault instance storing database authentication secrets. + */ + private String akvResourceId; + + /* + * The path to the Key Vault secret storing the login name (aka user name, aka account name) for authentication to a + * target. + */ + private String akvTargetUser; + + /* + * The path to the Key Vault secret storing the password for authentication to a target. + */ + private String akvTargetPassword; + + /** + * Creates an instance of VaultSecret class. + */ + public VaultSecret() { + } + + /** + * Get the akvResourceId property: The Azure resource ID of the Key Vault instance storing database authentication + * secrets. + * + * @return the akvResourceId value. + */ + public String akvResourceId() { + return this.akvResourceId; + } + + /** + * Set the akvResourceId property: The Azure resource ID of the Key Vault instance storing database authentication + * secrets. + * + * @param akvResourceId the akvResourceId value to set. + * @return the VaultSecret object itself. + */ + public VaultSecret withAkvResourceId(String akvResourceId) { + this.akvResourceId = akvResourceId; + return this; + } + + /** + * Get the akvTargetUser property: The path to the Key Vault secret storing the login name (aka user name, aka + * account name) for authentication to a target. + * + * @return the akvTargetUser value. + */ + public String akvTargetUser() { + return this.akvTargetUser; + } + + /** + * Set the akvTargetUser property: The path to the Key Vault secret storing the login name (aka user name, aka + * account name) for authentication to a target. + * + * @param akvTargetUser the akvTargetUser value to set. + * @return the VaultSecret object itself. + */ + public VaultSecret withAkvTargetUser(String akvTargetUser) { + this.akvTargetUser = akvTargetUser; + return this; + } + + /** + * Get the akvTargetPassword property: The path to the Key Vault secret storing the password for authentication to a + * target. + * + * @return the akvTargetPassword value. + */ + public String akvTargetPassword() { + return this.akvTargetPassword; + } + + /** + * Set the akvTargetPassword property: The path to the Key Vault secret storing the password for authentication to a + * target. + * + * @param akvTargetPassword the akvTargetPassword value to set. + * @return the VaultSecret object itself. + */ + public VaultSecret withAkvTargetPassword(String akvTargetPassword) { + this.akvTargetPassword = akvTargetPassword; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("akvResourceId", this.akvResourceId); + jsonWriter.writeStringField("akvTargetUser", this.akvTargetUser); + jsonWriter.writeStringField("akvTargetPassword", this.akvTargetPassword); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of VaultSecret from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of VaultSecret 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 VaultSecret. + */ + public static VaultSecret fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + VaultSecret deserializedVaultSecret = new VaultSecret(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("akvResourceId".equals(fieldName)) { + deserializedVaultSecret.akvResourceId = reader.getString(); + } else if ("akvTargetUser".equals(fieldName)) { + deserializedVaultSecret.akvTargetUser = reader.getString(); + } else if ("akvTargetPassword".equals(fieldName)) { + deserializedVaultSecret.akvTargetPassword = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedVaultSecret; + }); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/Watcher.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/Watcher.java new file mode 100644 index 000000000000..49b3695c306a --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/Watcher.java @@ -0,0 +1,339 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.management.Region; +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.databasewatcher.fluent.models.WatcherInner; +import java.util.Map; + +/** + * An immutable client-side representation of Watcher. + */ +public interface Watcher { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the location property: The geo-location where the resource lives. + * + * @return the location value. + */ + String location(); + + /** + * Gets the tags property: Resource tags. + * + * @return the tags value. + */ + Map tags(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + WatcherProperties properties(); + + /** + * Gets the identity property: The managed service identities assigned to this resource. + * + * @return the identity value. + */ + ManagedServiceIdentityV4 identity(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the region of the resource. + * + * @return the region of the resource. + */ + Region region(); + + /** + * Gets the name of the resource region. + * + * @return the name of the resource region. + */ + String regionName(); + + /** + * Gets the name of the resource group. + * + * @return the name of the resource group. + */ + String resourceGroupName(); + + /** + * Gets the inner com.azure.resourcemanager.databasewatcher.fluent.models.WatcherInner object. + * + * @return the inner object. + */ + WatcherInner innerModel(); + + /** + * The entirety of the Watcher definition. + */ + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithLocation, + DefinitionStages.WithResourceGroup, DefinitionStages.WithCreate { + } + + /** + * The Watcher definition stages. + */ + interface DefinitionStages { + /** + * The first stage of the Watcher definition. + */ + interface Blank extends WithLocation { + } + + /** + * The stage of the Watcher definition allowing to specify location. + */ + interface WithLocation { + /** + * Specifies the region for the resource. + * + * @param location The geo-location where the resource lives. + * @return the next definition stage. + */ + WithResourceGroup withRegion(Region location); + + /** + * Specifies the region for the resource. + * + * @param location The geo-location where the resource lives. + * @return the next definition stage. + */ + WithResourceGroup withRegion(String location); + } + + /** + * The stage of the Watcher definition allowing to specify parent resource. + */ + interface WithResourceGroup { + /** + * Specifies resourceGroupName. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @return the next definition stage. + */ + WithCreate withExistingResourceGroup(String resourceGroupName); + } + + /** + * The stage of the Watcher definition which contains all the minimum required properties for the resource to be + * created, but also allows for any other optional properties to be specified. + */ + interface WithCreate + extends DefinitionStages.WithTags, DefinitionStages.WithProperties, DefinitionStages.WithIdentity { + /** + * Executes the create request. + * + * @return the created resource. + */ + Watcher create(); + + /** + * Executes the create request. + * + * @param context The context to associate with this operation. + * @return the created resource. + */ + Watcher create(Context context); + } + + /** + * The stage of the Watcher definition allowing to specify tags. + */ + interface WithTags { + /** + * Specifies the tags property: Resource tags.. + * + * @param tags Resource tags. + * @return the next definition stage. + */ + WithCreate withTags(Map tags); + } + + /** + * The stage of the Watcher definition allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The resource-specific properties for this resource.. + * + * @param properties The resource-specific properties for this resource. + * @return the next definition stage. + */ + WithCreate withProperties(WatcherProperties properties); + } + + /** + * The stage of the Watcher definition allowing to specify identity. + */ + interface WithIdentity { + /** + * Specifies the identity property: The managed service identities assigned to this resource.. + * + * @param identity The managed service identities assigned to this resource. + * @return the next definition stage. + */ + WithCreate withIdentity(ManagedServiceIdentityV4 identity); + } + } + + /** + * Begins update for the Watcher resource. + * + * @return the stage of resource update. + */ + Watcher.Update update(); + + /** + * The template for Watcher update. + */ + interface Update extends UpdateStages.WithTags, UpdateStages.WithIdentity, UpdateStages.WithProperties { + /** + * Executes the update request. + * + * @return the updated resource. + */ + Watcher apply(); + + /** + * Executes the update request. + * + * @param context The context to associate with this operation. + * @return the updated resource. + */ + Watcher apply(Context context); + } + + /** + * The Watcher update stages. + */ + interface UpdateStages { + /** + * The stage of the Watcher update allowing to specify tags. + */ + interface WithTags { + /** + * Specifies the tags property: Resource tags.. + * + * @param tags Resource tags. + * @return the next definition stage. + */ + Update withTags(Map tags); + } + + /** + * The stage of the Watcher update allowing to specify identity. + */ + interface WithIdentity { + /** + * Specifies the identity property: The managed service identities assigned to this resource.. + * + * @param identity The managed service identities assigned to this resource. + * @return the next definition stage. + */ + Update withIdentity(ManagedServiceIdentityV4 identity); + } + + /** + * The stage of the Watcher update allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The resource-specific properties for this resource.. + * + * @param properties The resource-specific properties for this resource. + * @return the next definition stage. + */ + Update withProperties(WatcherUpdateProperties properties); + } + } + + /** + * Refreshes the resource to sync with Azure. + * + * @return the refreshed resource. + */ + Watcher refresh(); + + /** + * Refreshes the resource to sync with Azure. + * + * @param context The context to associate with this operation. + * @return the refreshed resource. + */ + Watcher refresh(Context context); + + /** + * The action to start monitoring all targets configured for a database watcher. + * + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + Watcher start(); + + /** + * The action to start monitoring all targets configured for a database watcher. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + Watcher start(Context context); + + /** + * The action to stop monitoring all targets configured for a database watcher. + * + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + Watcher stop(); + + /** + * The action to stop monitoring all targets configured for a database watcher. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + Watcher stop(Context context); +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/WatcherProperties.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/WatcherProperties.java new file mode 100644 index 000000000000..624c7d923aea --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/WatcherProperties.java @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.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; + +/** + * The RP specific properties of the resource. + */ +@Fluent +public final class WatcherProperties implements JsonSerializable { + /* + * The data store for collected monitoring data. + */ + private Datastore datastore; + + /* + * The monitoring collection status of the watcher. + */ + private WatcherStatus status; + + /* + * The provisioning state of the resource watcher. + */ + private DatabaseWatcherProvisioningState provisioningState; + + /* + * The resource ID of a user-assigned managed identity that will be assigned to a new alert rule. + */ + private String defaultAlertRuleIdentityResourceId; + + /** + * Creates an instance of WatcherProperties class. + */ + public WatcherProperties() { + } + + /** + * Get the datastore property: The data store for collected monitoring data. + * + * @return the datastore value. + */ + public Datastore datastore() { + return this.datastore; + } + + /** + * Set the datastore property: The data store for collected monitoring data. + * + * @param datastore the datastore value to set. + * @return the WatcherProperties object itself. + */ + public WatcherProperties withDatastore(Datastore datastore) { + this.datastore = datastore; + return this; + } + + /** + * Get the status property: The monitoring collection status of the watcher. + * + * @return the status value. + */ + public WatcherStatus status() { + return this.status; + } + + /** + * Get the provisioningState property: The provisioning state of the resource watcher. + * + * @return the provisioningState value. + */ + public DatabaseWatcherProvisioningState provisioningState() { + return this.provisioningState; + } + + /** + * Get the defaultAlertRuleIdentityResourceId property: The resource ID of a user-assigned managed identity that + * will be assigned to a new alert rule. + * + * @return the defaultAlertRuleIdentityResourceId value. + */ + public String defaultAlertRuleIdentityResourceId() { + return this.defaultAlertRuleIdentityResourceId; + } + + /** + * Set the defaultAlertRuleIdentityResourceId property: The resource ID of a user-assigned managed identity that + * will be assigned to a new alert rule. + * + * @param defaultAlertRuleIdentityResourceId the defaultAlertRuleIdentityResourceId value to set. + * @return the WatcherProperties object itself. + */ + public WatcherProperties withDefaultAlertRuleIdentityResourceId(String defaultAlertRuleIdentityResourceId) { + this.defaultAlertRuleIdentityResourceId = defaultAlertRuleIdentityResourceId; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (datastore() != null) { + datastore().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("datastore", this.datastore); + jsonWriter.writeStringField("defaultAlertRuleIdentityResourceId", this.defaultAlertRuleIdentityResourceId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of WatcherProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of WatcherProperties 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 WatcherProperties. + */ + public static WatcherProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + WatcherProperties deserializedWatcherProperties = new WatcherProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("datastore".equals(fieldName)) { + deserializedWatcherProperties.datastore = Datastore.fromJson(reader); + } else if ("status".equals(fieldName)) { + deserializedWatcherProperties.status = WatcherStatus.fromString(reader.getString()); + } else if ("provisioningState".equals(fieldName)) { + deserializedWatcherProperties.provisioningState + = DatabaseWatcherProvisioningState.fromString(reader.getString()); + } else if ("defaultAlertRuleIdentityResourceId".equals(fieldName)) { + deserializedWatcherProperties.defaultAlertRuleIdentityResourceId = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedWatcherProperties; + }); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/WatcherStatus.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/WatcherStatus.java new file mode 100644 index 000000000000..138a8f55bdbb --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/WatcherStatus.java @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The monitoring collection status of a watcher. + */ +public final class WatcherStatus extends ExpandableStringEnum { + /** + * Denotes the watcher is in a starting state. + */ + public static final WatcherStatus STARTING = fromString("Starting"); + + /** + * Denotes the watcher is in a running state. + */ + public static final WatcherStatus RUNNING = fromString("Running"); + + /** + * Denotes the watcher is in a stopping state. + */ + public static final WatcherStatus STOPPING = fromString("Stopping"); + + /** + * Denotes the watcher is in a stopped state. + */ + public static final WatcherStatus STOPPED = fromString("Stopped"); + + /** + * Denotes the watcher is in a deleting state. + */ + public static final WatcherStatus DELETING = fromString("Deleting"); + + /** + * Creates a new instance of WatcherStatus value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public WatcherStatus() { + } + + /** + * Creates or finds a WatcherStatus from its string representation. + * + * @param name a name to look for. + * @return the corresponding WatcherStatus. + */ + public static WatcherStatus fromString(String name) { + return fromString(name, WatcherStatus.class); + } + + /** + * Gets known WatcherStatus values. + * + * @return known WatcherStatus values. + */ + public static Collection values() { + return values(WatcherStatus.class); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/WatcherUpdate.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/WatcherUpdate.java new file mode 100644 index 000000000000..4ed36b55eb62 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/WatcherUpdate.java @@ -0,0 +1,157 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.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.Map; + +/** + * The type used for update operations of the Watcher. + */ +@Fluent +public final class WatcherUpdate implements JsonSerializable { + /* + * The managed service identities assigned to this resource. + */ + private ManagedServiceIdentityV4 identity; + + /* + * Resource tags. + */ + private Map tags; + + /* + * The resource-specific properties for this resource. + */ + private WatcherUpdateProperties properties; + + /** + * Creates an instance of WatcherUpdate class. + */ + public WatcherUpdate() { + } + + /** + * Get the identity property: The managed service identities assigned to this resource. + * + * @return the identity value. + */ + public ManagedServiceIdentityV4 identity() { + return this.identity; + } + + /** + * Set the identity property: The managed service identities assigned to this resource. + * + * @param identity the identity value to set. + * @return the WatcherUpdate object itself. + */ + public WatcherUpdate withIdentity(ManagedServiceIdentityV4 identity) { + this.identity = identity; + return this; + } + + /** + * Get the tags property: Resource tags. + * + * @return the tags value. + */ + public Map tags() { + return this.tags; + } + + /** + * Set the tags property: Resource tags. + * + * @param tags the tags value to set. + * @return the WatcherUpdate object itself. + */ + public WatcherUpdate withTags(Map tags) { + this.tags = tags; + return this; + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public WatcherUpdateProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the WatcherUpdate object itself. + */ + public WatcherUpdate withProperties(WatcherUpdateProperties properties) { + this.properties = properties; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (identity() != null) { + identity().validate(); + } + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("identity", this.identity); + jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of WatcherUpdate from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of WatcherUpdate 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 WatcherUpdate. + */ + public static WatcherUpdate fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + WatcherUpdate deserializedWatcherUpdate = new WatcherUpdate(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("identity".equals(fieldName)) { + deserializedWatcherUpdate.identity = ManagedServiceIdentityV4.fromJson(reader); + } else if ("tags".equals(fieldName)) { + Map tags = reader.readMap(reader1 -> reader1.getString()); + deserializedWatcherUpdate.tags = tags; + } else if ("properties".equals(fieldName)) { + deserializedWatcherUpdate.properties = WatcherUpdateProperties.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedWatcherUpdate; + }); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/WatcherUpdateProperties.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/WatcherUpdateProperties.java new file mode 100644 index 000000000000..8bc9361ef762 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/WatcherUpdateProperties.java @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.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; + +/** + * The updatable properties of the Watcher. + */ +@Fluent +public final class WatcherUpdateProperties implements JsonSerializable { + /* + * The data store for collected monitoring data. + */ + private Datastore datastore; + + /* + * The resource ID of a user-assigned managed identity that will be assigned to a new alert rule. + */ + private String defaultAlertRuleIdentityResourceId; + + /** + * Creates an instance of WatcherUpdateProperties class. + */ + public WatcherUpdateProperties() { + } + + /** + * Get the datastore property: The data store for collected monitoring data. + * + * @return the datastore value. + */ + public Datastore datastore() { + return this.datastore; + } + + /** + * Set the datastore property: The data store for collected monitoring data. + * + * @param datastore the datastore value to set. + * @return the WatcherUpdateProperties object itself. + */ + public WatcherUpdateProperties withDatastore(Datastore datastore) { + this.datastore = datastore; + return this; + } + + /** + * Get the defaultAlertRuleIdentityResourceId property: The resource ID of a user-assigned managed identity that + * will be assigned to a new alert rule. + * + * @return the defaultAlertRuleIdentityResourceId value. + */ + public String defaultAlertRuleIdentityResourceId() { + return this.defaultAlertRuleIdentityResourceId; + } + + /** + * Set the defaultAlertRuleIdentityResourceId property: The resource ID of a user-assigned managed identity that + * will be assigned to a new alert rule. + * + * @param defaultAlertRuleIdentityResourceId the defaultAlertRuleIdentityResourceId value to set. + * @return the WatcherUpdateProperties object itself. + */ + public WatcherUpdateProperties withDefaultAlertRuleIdentityResourceId(String defaultAlertRuleIdentityResourceId) { + this.defaultAlertRuleIdentityResourceId = defaultAlertRuleIdentityResourceId; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (datastore() != null) { + datastore().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("datastore", this.datastore); + jsonWriter.writeStringField("defaultAlertRuleIdentityResourceId", this.defaultAlertRuleIdentityResourceId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of WatcherUpdateProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of WatcherUpdateProperties 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 WatcherUpdateProperties. + */ + public static WatcherUpdateProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + WatcherUpdateProperties deserializedWatcherUpdateProperties = new WatcherUpdateProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("datastore".equals(fieldName)) { + deserializedWatcherUpdateProperties.datastore = Datastore.fromJson(reader); + } else if ("defaultAlertRuleIdentityResourceId".equals(fieldName)) { + deserializedWatcherUpdateProperties.defaultAlertRuleIdentityResourceId = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedWatcherUpdateProperties; + }); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/Watchers.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/Watchers.java new file mode 100644 index 000000000000..12c62e6d1903 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/Watchers.java @@ -0,0 +1,207 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of Watchers. + */ +public interface Watchers { + /** + * Get a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Watcher along with {@link Response}. + */ + Response getByResourceGroupWithResponse(String resourceGroupName, String watcherName, Context context); + + /** + * Get a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Watcher. + */ + Watcher getByResourceGroup(String resourceGroupName, String watcherName); + + /** + * Delete a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteByResourceGroup(String resourceGroupName, String watcherName); + + /** + * Delete a Watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void delete(String resourceGroupName, String watcherName, Context context); + + /** + * List Watcher resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Watcher list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByResourceGroup(String resourceGroupName); + + /** + * List Watcher resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Watcher list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByResourceGroup(String resourceGroupName, Context context); + + /** + * List Watcher resources by subscription ID. + * + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Watcher list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable list(); + + /** + * List Watcher resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Watcher list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable list(Context context); + + /** + * The action to start monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + Watcher start(String resourceGroupName, String watcherName); + + /** + * The action to start monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + Watcher start(String resourceGroupName, String watcherName, Context context); + + /** + * The action to stop monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + Watcher stop(String resourceGroupName, String watcherName); + + /** + * The action to stop monitoring all targets configured for a database watcher. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param watcherName The database watcher name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + Watcher stop(String resourceGroupName, String watcherName, Context context); + + /** + * Get a Watcher. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Watcher along with {@link Response}. + */ + Watcher getById(String id); + + /** + * Get a Watcher. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Watcher along with {@link Response}. + */ + Response getByIdWithResponse(String id, Context context); + + /** + * Delete a Watcher. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteById(String id); + + /** + * Delete a Watcher. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteByIdWithResponse(String id, Context context); + + /** + * Begins definition for a new Watcher resource. + * + * @param name resource name. + * @return the first stage of the new Watcher definition. + */ + Watcher.DefinitionStages.Blank define(String name); +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/package-info.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/package-info.java new file mode 100644 index 000000000000..fac2d221bc41 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/models/package-info.java @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +/** + * Package containing the data models for DatabaseWatcher. + */ +package com.azure.resourcemanager.databasewatcher.models; diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/package-info.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/package-info.java new file mode 100644 index 000000000000..9f1798c0d8d1 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/com/azure/resourcemanager/databasewatcher/package-info.java @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +/** + * Package containing the classes for DatabaseWatcher. + */ +package com.azure.resourcemanager.databasewatcher; diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/module-info.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/module-info.java new file mode 100644 index 000000000000..060775fabe2c --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/java/module-info.java @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +module com.azure.resourcemanager.databasewatcher { + requires transitive com.azure.core.management; + + exports com.azure.resourcemanager.databasewatcher; + exports com.azure.resourcemanager.databasewatcher.fluent; + exports com.azure.resourcemanager.databasewatcher.fluent.models; + exports com.azure.resourcemanager.databasewatcher.models; + + opens com.azure.resourcemanager.databasewatcher.fluent.models to com.azure.core; + opens com.azure.resourcemanager.databasewatcher.models to com.azure.core; + opens com.azure.resourcemanager.databasewatcher.implementation.models to com.azure.core; +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-databasewatcher/proxy-config.json b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-databasewatcher/proxy-config.json new file mode 100644 index 000000000000..a527bba8ee7c --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-databasewatcher/proxy-config.json @@ -0,0 +1 @@ +[["com.azure.resourcemanager.databasewatcher.implementation.AlertRuleResourcesClientImpl$AlertRuleResourcesService"],["com.azure.resourcemanager.databasewatcher.implementation.HealthValidationsClientImpl$HealthValidationsService"],["com.azure.resourcemanager.databasewatcher.implementation.OperationsClientImpl$OperationsService"],["com.azure.resourcemanager.databasewatcher.implementation.SharedPrivateLinkResourcesClientImpl$SharedPrivateLinkResourcesService"],["com.azure.resourcemanager.databasewatcher.implementation.TargetsClientImpl$TargetsService"],["com.azure.resourcemanager.databasewatcher.implementation.WatchersClientImpl$WatchersService"]] \ No newline at end of file diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-databasewatcher/reflect-config.json b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-databasewatcher/reflect-config.json new file mode 100644 index 000000000000..0637a088a01e --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-databasewatcher/reflect-config.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/resources/azure-resourcemanager-databasewatcher.properties b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/resources/azure-resourcemanager-databasewatcher.properties new file mode 100644 index 000000000000..defbd48204e4 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/main/resources/azure-resourcemanager-databasewatcher.properties @@ -0,0 +1 @@ +version=${project.version} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourcesCreateOrUpdateSamples.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourcesCreateOrUpdateSamples.java new file mode 100644 index 000000000000..241035c3915c --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourcesCreateOrUpdateSamples.java @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.resourcemanager.databasewatcher.models.AlertRuleCreationProperties; +import com.azure.resourcemanager.databasewatcher.models.AlertRuleResourceProperties; +import java.time.OffsetDateTime; + +/** + * Samples for AlertRuleResources CreateOrUpdate. + */ +public final class AlertRuleResourcesCreateOrUpdateSamples { + /* + * x-ms-original-file: 2025-01-02/AlertRuleResources_CreateOrUpdate_MaximumSet_Gen.json + */ + /** + * Sample code: AlertRuleResources_CreateOrUpdate_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void alertRuleResourcesCreateOrUpdateMaximumSet( + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.alertRuleResources() + .define("testAlert") + .withExistingWatcher("rgWatcher", "testWatcher") + .withProperties(new AlertRuleResourceProperties().withAlertRuleResourceId( + "/subscriptions/469DD77C-C8DB-47B7-B9E1-72D29F8C878Be/resourceGroups/rgWatcher/providers/microsoft.insights/scheduledqueryrules/alerts-demo") + .withCreatedWithProperties(AlertRuleCreationProperties.CREATED_WITH_ACTION_GROUP) + .withCreationTime(OffsetDateTime.parse("2024-07-25T15:38:47.798Z")) + .withAlertRuleTemplateId("someTemplateId") + .withAlertRuleTemplateVersion("1.0")) + .create(); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourcesDeleteSamples.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourcesDeleteSamples.java new file mode 100644 index 000000000000..9f23c4521245 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourcesDeleteSamples.java @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +/** + * Samples for AlertRuleResources Delete. + */ +public final class AlertRuleResourcesDeleteSamples { + /* + * x-ms-original-file: 2025-01-02/AlertRuleResources_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: AlertRuleResources_Delete_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void + alertRuleResourcesDeleteMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.alertRuleResources() + .deleteWithResponse("rgWatcher", "testWatcher", "testAlert", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourcesGetSamples.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourcesGetSamples.java new file mode 100644 index 000000000000..870ea2c038ca --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourcesGetSamples.java @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +/** + * Samples for AlertRuleResources Get. + */ +public final class AlertRuleResourcesGetSamples { + /* + * x-ms-original-file: 2025-01-02/AlertRuleResources_Get_MaximumSet_Gen.json + */ + /** + * Sample code: AlertRuleResources_Get_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void + alertRuleResourcesGetMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.alertRuleResources() + .getWithResponse("rgWatcher", "testWatcher", "testAlert", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourcesListByParentSamples.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourcesListByParentSamples.java new file mode 100644 index 000000000000..003c527cf474 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourcesListByParentSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +/** + * Samples for AlertRuleResources ListByParent. + */ +public final class AlertRuleResourcesListByParentSamples { + /* + * x-ms-original-file: 2025-01-02/AlertRuleResources_ListByParent_MaximumSet_Gen.json + */ + /** + * Sample code: AlertRuleResources_ListByParent_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void alertRuleResourcesListByParentMaximumSet( + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.alertRuleResources().listByParent("rgWatcher", "testWatcher", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/HealthValidationsGetSamples.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/HealthValidationsGetSamples.java new file mode 100644 index 000000000000..762621affd93 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/HealthValidationsGetSamples.java @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +/** + * Samples for HealthValidations Get. + */ +public final class HealthValidationsGetSamples { + /* + * x-ms-original-file: 2025-01-02/HealthValidations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: HealthValidations_Get_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void + healthValidationsGetMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.healthValidations() + .getWithResponse("rgWatcher", "testWatcher", "testHealthValidation", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/HealthValidationsListByParentSamples.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/HealthValidationsListByParentSamples.java new file mode 100644 index 000000000000..a43aa6983080 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/HealthValidationsListByParentSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +/** + * Samples for HealthValidations ListByParent. + */ +public final class HealthValidationsListByParentSamples { + /* + * x-ms-original-file: 2025-01-02/HealthValidations_ListByParent_MaximumSet_Gen.json + */ + /** + * Sample code: HealthValidations_ListByParent_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void healthValidationsListByParentMaximumSet( + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.healthValidations().listByParent("rgWatcher", "testWatcher", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/HealthValidationsStartValidationSamples.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/HealthValidationsStartValidationSamples.java new file mode 100644 index 000000000000..7782c549c899 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/HealthValidationsStartValidationSamples.java @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +/** + * Samples for HealthValidations StartValidation. + */ +public final class HealthValidationsStartValidationSamples { + /* + * x-ms-original-file: 2025-01-02/HealthValidations_StartValidation_MaximumSet_Gen.json + */ + /** + * Sample code: HealthValidations_StartValidation_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void healthValidationsStartValidationMaximumSet( + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.healthValidations() + .startValidation("rgWatcher", "testWatcher", "testHealthValidation", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/OperationsListSamples.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/OperationsListSamples.java new file mode 100644 index 000000000000..64dd1bae9505 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/OperationsListSamples.java @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +/** + * Samples for Operations List. + */ +public final class OperationsListSamples { + /* + * x-ms-original-file: 2025-01-02/Operations_List_MinimumSet_Gen.json + */ + /** + * Sample code: Operations_List_MinimumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void + operationsListMinimumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.operations().list(com.azure.core.util.Context.NONE); + } + + /* + * x-ms-original-file: 2025-01-02/Operations_List_MaximumSet_Gen.json + */ + /** + * Sample code: Operations_List_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void + operationsListMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.operations().list(com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourcesCreateSamples.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourcesCreateSamples.java new file mode 100644 index 000000000000..ca9957a442ab --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourcesCreateSamples.java @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.resourcemanager.databasewatcher.models.SharedPrivateLinkResourceProperties; + +/** + * Samples for SharedPrivateLinkResources Create. + */ +public final class SharedPrivateLinkResourcesCreateSamples { + /* + * x-ms-original-file: 2025-01-02/SharedPrivateLinkResources_Create_MaximumSet_Gen.json + */ + /** + * Sample code: SharedPrivateLinkResources_Create_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void sharedPrivateLinkResourcesCreateMaximumSet( + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.sharedPrivateLinkResources() + .define("monitoringh22eed") + .withExistingWatcher("apiTest-ddat4p", "databasemo3ej9ih") + .withProperties(new SharedPrivateLinkResourceProperties().withPrivateLinkResourceId( + "/subscriptions/49e0fbd3-75e8-44e7-96fd-5b64d9ad818d/resourceGroups/apiTest-ddat4p/providers/Microsoft.KeyVault/vaults/kvmo3ej9ih") + .withGroupId("vault") + .withRequestMessage("request message") + .withDnsZone("ec3ae9d410ba")) + .create(); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourcesDeleteSamples.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourcesDeleteSamples.java new file mode 100644 index 000000000000..5c93ef54e03a --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourcesDeleteSamples.java @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +/** + * Samples for SharedPrivateLinkResources Delete. + */ +public final class SharedPrivateLinkResourcesDeleteSamples { + /* + * x-ms-original-file: 2025-01-02/SharedPrivateLinkResources_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: SharedPrivateLinkResources_Delete_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void sharedPrivateLinkResourcesDeleteMaximumSet( + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.sharedPrivateLinkResources() + .delete("apiTest-ddat4p", "databasemo3ej9ih", "monitoringh22eed", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourcesGetSamples.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourcesGetSamples.java new file mode 100644 index 000000000000..044867e59994 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourcesGetSamples.java @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +/** + * Samples for SharedPrivateLinkResources Get. + */ +public final class SharedPrivateLinkResourcesGetSamples { + /* + * x-ms-original-file: 2025-01-02/SharedPrivateLinkResources_Get_MaximumSet_Gen.json + */ + /** + * Sample code: SharedPrivateLinkResources_Get_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void sharedPrivateLinkResourcesGetMaximumSet( + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.sharedPrivateLinkResources() + .getWithResponse("apiTest-ddat4p", "databasemo3ej9ih", "monitoringh22eed", + com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourcesListByWatcherSamples.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourcesListByWatcherSamples.java new file mode 100644 index 000000000000..a45a16b1931a --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourcesListByWatcherSamples.java @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +/** + * Samples for SharedPrivateLinkResources ListByWatcher. + */ +public final class SharedPrivateLinkResourcesListByWatcherSamples { + /* + * x-ms-original-file: 2025-01-02/SharedPrivateLinkResources_ListByWatcher_MaximumSet_Gen.json + */ + /** + * Sample code: SharedPrivateLinkResources_ListByWatcher_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void sharedPrivateLinkResourcesListByWatcherMaximumSet( + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.sharedPrivateLinkResources() + .listByWatcher("apiTest-ddat4p", "databasemo3ej9ih", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/TargetsCreateOrUpdateSamples.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/TargetsCreateOrUpdateSamples.java new file mode 100644 index 000000000000..de7c1e3c12d1 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/TargetsCreateOrUpdateSamples.java @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.resourcemanager.databasewatcher.models.SqlDbSingleDatabaseTargetProperties; +import com.azure.resourcemanager.databasewatcher.models.TargetAuthenticationType; + +/** + * Samples for Targets CreateOrUpdate. + */ +public final class TargetsCreateOrUpdateSamples { + /* + * x-ms-original-file: 2025-01-02/Targets_CreateOrUpdate_MaximumSet_Gen.json + */ + /** + * Sample code: Targets_CreateOrUpdate_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void + targetsCreateOrUpdateMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.targets() + .define("monitoringh22eed") + .withExistingWatcher("apiTest-ddat4p", "databasemo3ej9ih") + .withProperties(new SqlDbSingleDatabaseTargetProperties() + .withTargetAuthenticationType(TargetAuthenticationType.AAD) + .withConnectionServerName("sqlServero1ihe2") + .withSqlDbResourceId( + "/subscriptions/49e0fbd3-75e8-44e7-96fd-5b64d9ad818d/resourceGroups/apiTest-ddat4p/providers/Microsoft.Sql/servers/m1/databases/m2")) + .create(); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/TargetsDeleteSamples.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/TargetsDeleteSamples.java new file mode 100644 index 000000000000..8914a46b2779 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/TargetsDeleteSamples.java @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +/** + * Samples for Targets Delete. + */ +public final class TargetsDeleteSamples { + /* + * x-ms-original-file: 2025-01-02/Targets_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: Targets_Delete_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void + targetsDeleteMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.targets() + .deleteWithResponse("apiTest-ddat4p", "databasemo3ej9ih", "monitoringh22eed", + com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/TargetsGetSamples.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/TargetsGetSamples.java new file mode 100644 index 000000000000..ac5dc2916544 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/TargetsGetSamples.java @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +/** + * Samples for Targets Get. + */ +public final class TargetsGetSamples { + /* + * x-ms-original-file: 2025-01-02/Targets_Get_MaximumSet_Gen.json + */ + /** + * Sample code: Targets_Get_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void targetsGetMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.targets() + .getWithResponse("apiTest-ddat4p", "databasemo3ej9ih", "monitoringh22eed", + com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/TargetsListByWatcherSamples.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/TargetsListByWatcherSamples.java new file mode 100644 index 000000000000..3005dbeb1587 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/TargetsListByWatcherSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +/** + * Samples for Targets ListByWatcher. + */ +public final class TargetsListByWatcherSamples { + /* + * x-ms-original-file: 2025-01-02/Targets_ListByWatcher_MaximumSet_Gen.json + */ + /** + * Sample code: Targets_ListByWatcher_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void + targetsListByWatcherMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.targets().listByWatcher("apiTest-ddat4p", "databasemo3ej9ih", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/WatchersCreateOrUpdateSamples.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/WatchersCreateOrUpdateSamples.java new file mode 100644 index 000000000000..8824da4f8f44 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/WatchersCreateOrUpdateSamples.java @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.resourcemanager.databasewatcher.models.Datastore; +import com.azure.resourcemanager.databasewatcher.models.KustoOfferingType; +import com.azure.resourcemanager.databasewatcher.models.ManagedServiceIdentityType; +import com.azure.resourcemanager.databasewatcher.models.ManagedServiceIdentityV4; +import com.azure.resourcemanager.databasewatcher.models.WatcherProperties; +import java.util.HashMap; +import java.util.Map; + +/** + * Samples for Watchers CreateOrUpdate. + */ +public final class WatchersCreateOrUpdateSamples { + /* + * x-ms-original-file: 2025-01-02/Watchers_CreateOrUpdate_MaximumSet_Gen.json + */ + /** + * Sample code: Watchers_CreateOrUpdate_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void + watchersCreateOrUpdateMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.watchers() + .define("testWatcher") + .withRegion("eastus2") + .withExistingResourceGroup("rgWatcher") + .withTags(mapOf()) + .withProperties(new WatcherProperties().withDatastore(new Datastore().withAdxClusterResourceId( + "/subscriptions/49e0fbd3-75e8-44e7-96fd-5b64d9ad818d/resourceGroups/apiTest/providers/Microsoft.Kusto/clusters/apiTestKusto") + .withKustoClusterDisplayName("kustoUri-adx") + .withKustoClusterUri("https://kustouri-adx.eastus.kusto.windows.net") + .withKustoDataIngestionUri("https://ingest-kustouri-adx.eastus.kusto.windows.net") + .withKustoDatabaseName("kustoDatabaseName1") + .withKustoManagementUrl("https://portal.azure.com/") + .withKustoOfferingType(KustoOfferingType.ADX)) + .withDefaultAlertRuleIdentityResourceId( + "/subscriptions/469DD77C-C8DB-47B7-B9E1-72D29F8C878B/resourceGroups/rgWatcher/providers/Microsoft.ManagedIdentity/userAssignedIdentities/3pmtest")) + .withIdentity(new ManagedServiceIdentityV4().withType(ManagedServiceIdentityType.SYSTEM_ASSIGNED)) + .create(); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/WatchersDeleteSamples.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/WatchersDeleteSamples.java new file mode 100644 index 000000000000..431d1bf70884 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/WatchersDeleteSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +/** + * Samples for Watchers Delete. + */ +public final class WatchersDeleteSamples { + /* + * x-ms-original-file: 2025-01-02/Watchers_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: Watchers_Delete_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void + watchersDeleteMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.watchers().delete("rgWatcher", "testWatcher", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/WatchersGetByResourceGroupSamples.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/WatchersGetByResourceGroupSamples.java new file mode 100644 index 000000000000..1828f2ba08e2 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/WatchersGetByResourceGroupSamples.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +/** + * Samples for Watchers GetByResourceGroup. + */ +public final class WatchersGetByResourceGroupSamples { + /* + * x-ms-original-file: 2025-01-02/Watchers_Get_MaximumSet_Gen.json + */ + /** + * Sample code: Watchers_Get_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void watchersGetMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.watchers().getByResourceGroupWithResponse("rgWatcher", "myWatcher", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/WatchersListByResourceGroupSamples.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/WatchersListByResourceGroupSamples.java new file mode 100644 index 000000000000..94b0f25e2c17 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/WatchersListByResourceGroupSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +/** + * Samples for Watchers ListByResourceGroup. + */ +public final class WatchersListByResourceGroupSamples { + /* + * x-ms-original-file: 2025-01-02/Watchers_ListByResourceGroup_MaximumSet_Gen.json + */ + /** + * Sample code: Watchers_ListByResourceGroup_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void watchersListByResourceGroupMaximumSet( + com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.watchers().listByResourceGroup("rgWatcher", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/WatchersListSamples.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/WatchersListSamples.java new file mode 100644 index 000000000000..b280ce1b6c7d --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/WatchersListSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +/** + * Samples for Watchers List. + */ +public final class WatchersListSamples { + /* + * x-ms-original-file: 2025-01-02/Watchers_ListBySubscription_MaximumSet_Gen.json + */ + /** + * Sample code: Watchers_ListBySubscription_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void + watchersListBySubscriptionMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.watchers().list(com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/WatchersStartSamples.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/WatchersStartSamples.java new file mode 100644 index 000000000000..d6cfeb06c61a --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/WatchersStartSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +/** + * Samples for Watchers Start. + */ +public final class WatchersStartSamples { + /* + * x-ms-original-file: 2025-01-02/Watchers_Start_MaximumSet_Gen.json + */ + /** + * Sample code: Watchers_Start_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void + watchersStartMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.watchers().start("rgWatcher", "testWatcher", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/WatchersStopSamples.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/WatchersStopSamples.java new file mode 100644 index 000000000000..aa6d8e2fd1f3 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/WatchersStopSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +/** + * Samples for Watchers Stop. + */ +public final class WatchersStopSamples { + /* + * x-ms-original-file: 2025-01-02/Watchers_Stop_MaximumSet_Gen.json + */ + /** + * Sample code: Watchers_Stop_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void + watchersStopMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + manager.watchers().stop("rgWatcher", "myWatcher", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/WatchersUpdateSamples.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/WatchersUpdateSamples.java new file mode 100644 index 000000000000..cfd1c1274529 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/samples/java/com/azure/resourcemanager/databasewatcher/generated/WatchersUpdateSamples.java @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.resourcemanager.databasewatcher.models.Datastore; +import com.azure.resourcemanager.databasewatcher.models.KustoOfferingType; +import com.azure.resourcemanager.databasewatcher.models.ManagedServiceIdentityType; +import com.azure.resourcemanager.databasewatcher.models.ManagedServiceIdentityV4; +import com.azure.resourcemanager.databasewatcher.models.Watcher; +import com.azure.resourcemanager.databasewatcher.models.WatcherUpdateProperties; +import java.util.HashMap; +import java.util.Map; + +/** + * Samples for Watchers Update. + */ +public final class WatchersUpdateSamples { + /* + * x-ms-original-file: 2025-01-02/Watchers_Update_MaximumSet_Gen.json + */ + /** + * Sample code: Watchers_Update_MaximumSet. + * + * @param manager Entry point to DatabaseWatcherManager. + */ + public static void + watchersUpdateMaximumSet(com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager manager) { + Watcher resource = manager.watchers() + .getByResourceGroupWithResponse("rgWatcher", "testWatcher", com.azure.core.util.Context.NONE) + .getValue(); + resource.update() + .withTags(mapOf()) + .withIdentity(new ManagedServiceIdentityV4().withType(ManagedServiceIdentityType.SYSTEM_ASSIGNED)) + .withProperties(new WatcherUpdateProperties().withDatastore(new Datastore().withAdxClusterResourceId( + "/subscriptions/49e0fbd3-75e8-44e7-96fd-5b64d9ad818d/resourceGroups/apiTest/providers/Microsoft.Kusto/clusters/apiTestKusto") + .withKustoClusterDisplayName("kustoUri-adx") + .withKustoClusterUri("https://kustouri-adx.eastus.kusto.windows.net") + .withKustoDataIngestionUri("https://ingest-kustouri-adx.eastus.kusto.windows.net") + .withKustoDatabaseName("kustoDatabaseName1") + .withKustoManagementUrl("https://portal.azure.com/") + .withKustoOfferingType(KustoOfferingType.ADX)) + .withDefaultAlertRuleIdentityResourceId( + "/subscriptions/469DD77C-C8DB-47B7-B9E1-72D29F8C878B/resourceGroups/rgWatcher/providers/Microsoft.ManagedIdentity/userAssignedIdentities/newtest")) + .apply(); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourceInnerTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourceInnerTests.java new file mode 100644 index 000000000000..ba81b9bddf4c --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourceInnerTests.java @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.databasewatcher.fluent.models.AlertRuleResourceInner; +import com.azure.resourcemanager.databasewatcher.models.AlertRuleCreationProperties; +import com.azure.resourcemanager.databasewatcher.models.AlertRuleResourceProperties; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; + +public final class AlertRuleResourceInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AlertRuleResourceInner model = BinaryData.fromString( + "{\"properties\":{\"alertRuleResourceId\":\"qkwpyeicxmqc\",\"createdWithProperties\":\"None\",\"creationTime\":\"2021-08-11T13:08:26Z\",\"provisioningState\":\"Canceled\",\"alertRuleTemplateId\":\"khixuigdtopbo\",\"alertRuleTemplateVersion\":\"joghmewuama\"},\"id\":\"rzayv\",\"name\":\"t\",\"type\":\"gvdfgiotkftutq\"}") + .toObject(AlertRuleResourceInner.class); + Assertions.assertEquals("qkwpyeicxmqc", model.properties().alertRuleResourceId()); + Assertions.assertEquals(AlertRuleCreationProperties.NONE, model.properties().createdWithProperties()); + Assertions.assertEquals(OffsetDateTime.parse("2021-08-11T13:08:26Z"), model.properties().creationTime()); + Assertions.assertEquals("khixuigdtopbo", model.properties().alertRuleTemplateId()); + Assertions.assertEquals("joghmewuama", model.properties().alertRuleTemplateVersion()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AlertRuleResourceInner model = new AlertRuleResourceInner() + .withProperties(new AlertRuleResourceProperties().withAlertRuleResourceId("qkwpyeicxmqc") + .withCreatedWithProperties(AlertRuleCreationProperties.NONE) + .withCreationTime(OffsetDateTime.parse("2021-08-11T13:08:26Z")) + .withAlertRuleTemplateId("khixuigdtopbo") + .withAlertRuleTemplateVersion("joghmewuama")); + model = BinaryData.fromObject(model).toObject(AlertRuleResourceInner.class); + Assertions.assertEquals("qkwpyeicxmqc", model.properties().alertRuleResourceId()); + Assertions.assertEquals(AlertRuleCreationProperties.NONE, model.properties().createdWithProperties()); + Assertions.assertEquals(OffsetDateTime.parse("2021-08-11T13:08:26Z"), model.properties().creationTime()); + Assertions.assertEquals("khixuigdtopbo", model.properties().alertRuleTemplateId()); + Assertions.assertEquals("joghmewuama", model.properties().alertRuleTemplateVersion()); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourceListResultTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourceListResultTests.java new file mode 100644 index 000000000000..ddecec7dd249 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourceListResultTests.java @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.databasewatcher.implementation.models.AlertRuleResourceListResult; +import com.azure.resourcemanager.databasewatcher.models.AlertRuleCreationProperties; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; + +public final class AlertRuleResourceListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AlertRuleResourceListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"alertRuleResourceId\":\"hzrvqd\",\"createdWithProperties\":\"CreatedWithActionGroup\",\"creationTime\":\"2021-12-03T05:38:56Z\",\"provisioningState\":\"Failed\",\"alertRuleTemplateId\":\"yb\",\"alertRuleTemplateVersion\":\"gehoqfbowskany\"},\"id\":\"zlcuiywgqywgndrv\",\"name\":\"nhzgpphrcgyn\",\"type\":\"ocpecfvmmco\"},{\"properties\":{\"alertRuleResourceId\":\"sxlzevgbmqj\",\"createdWithProperties\":\"None\",\"creationTime\":\"2021-11-06T14:35:38Z\",\"provisioningState\":\"Succeeded\",\"alertRuleTemplateId\":\"pmivkwlzu\",\"alertRuleTemplateVersion\":\"ccfwnfnbacfion\"},\"id\":\"bxetqgtzxdpn\",\"name\":\"bqqwxrj\",\"type\":\"eallnwsubisnj\"}],\"nextLink\":\"pmng\"}") + .toObject(AlertRuleResourceListResult.class); + Assertions.assertEquals("hzrvqd", model.value().get(0).properties().alertRuleResourceId()); + Assertions.assertEquals(AlertRuleCreationProperties.CREATED_WITH_ACTION_GROUP, + model.value().get(0).properties().createdWithProperties()); + Assertions.assertEquals(OffsetDateTime.parse("2021-12-03T05:38:56Z"), + model.value().get(0).properties().creationTime()); + Assertions.assertEquals("yb", model.value().get(0).properties().alertRuleTemplateId()); + Assertions.assertEquals("gehoqfbowskany", model.value().get(0).properties().alertRuleTemplateVersion()); + Assertions.assertEquals("pmng", model.nextLink()); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourcePropertiesTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourcePropertiesTests.java new file mode 100644 index 000000000000..5995ac0c1e4b --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourcePropertiesTests.java @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.databasewatcher.models.AlertRuleCreationProperties; +import com.azure.resourcemanager.databasewatcher.models.AlertRuleResourceProperties; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; + +public final class AlertRuleResourcePropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AlertRuleResourceProperties model = BinaryData.fromString( + "{\"alertRuleResourceId\":\"ln\",\"createdWithProperties\":\"None\",\"creationTime\":\"2021-02-04T14:09:29Z\",\"provisioningState\":\"Failed\",\"alertRuleTemplateId\":\"gug\",\"alertRuleTemplateVersion\":\"xkrxdqmi\"}") + .toObject(AlertRuleResourceProperties.class); + Assertions.assertEquals("ln", model.alertRuleResourceId()); + Assertions.assertEquals(AlertRuleCreationProperties.NONE, model.createdWithProperties()); + Assertions.assertEquals(OffsetDateTime.parse("2021-02-04T14:09:29Z"), model.creationTime()); + Assertions.assertEquals("gug", model.alertRuleTemplateId()); + Assertions.assertEquals("xkrxdqmi", model.alertRuleTemplateVersion()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AlertRuleResourceProperties model = new AlertRuleResourceProperties().withAlertRuleResourceId("ln") + .withCreatedWithProperties(AlertRuleCreationProperties.NONE) + .withCreationTime(OffsetDateTime.parse("2021-02-04T14:09:29Z")) + .withAlertRuleTemplateId("gug") + .withAlertRuleTemplateVersion("xkrxdqmi"); + model = BinaryData.fromObject(model).toObject(AlertRuleResourceProperties.class); + Assertions.assertEquals("ln", model.alertRuleResourceId()); + Assertions.assertEquals(AlertRuleCreationProperties.NONE, model.createdWithProperties()); + Assertions.assertEquals(OffsetDateTime.parse("2021-02-04T14:09:29Z"), model.creationTime()); + Assertions.assertEquals("gug", model.alertRuleTemplateId()); + Assertions.assertEquals("xkrxdqmi", model.alertRuleTemplateVersion()); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourcesCreateOrUpdateWithResponseMockTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourcesCreateOrUpdateWithResponseMockTests.java new file mode 100644 index 000000000000..4751b7b1bf01 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourcesCreateOrUpdateWithResponseMockTests.java @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager; +import com.azure.resourcemanager.databasewatcher.models.AlertRuleCreationProperties; +import com.azure.resourcemanager.databasewatcher.models.AlertRuleResource; +import com.azure.resourcemanager.databasewatcher.models.AlertRuleResourceProperties; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class AlertRuleResourcesCreateOrUpdateWithResponseMockTests { + @Test + public void testCreateOrUpdateWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"alertRuleResourceId\":\"wyhzdx\",\"createdWithProperties\":\"CreatedWithActionGroup\",\"creationTime\":\"2021-03-28T04:38:02Z\",\"provisioningState\":\"Succeeded\",\"alertRuleTemplateId\":\"zmnvdfznudaod\",\"alertRuleTemplateVersion\":\"xzb\"},\"id\":\"blylpstdbh\",\"name\":\"xsrz\",\"type\":\"zucerscdntnev\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + DatabaseWatcherManager manager = DatabaseWatcherManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + AlertRuleResource response = manager.alertRuleResources() + .define("l") + .withExistingWatcher("doy", "mifthnzdnd") + .withProperties(new AlertRuleResourceProperties().withAlertRuleResourceId("ayqigynduhav") + .withCreatedWithProperties(AlertRuleCreationProperties.CREATED_WITH_ACTION_GROUP) + .withCreationTime(OffsetDateTime.parse("2021-02-05T08:21:04Z")) + .withAlertRuleTemplateId("humaqolbgyc") + .withAlertRuleTemplateVersion("uie")) + .create(); + + Assertions.assertEquals("wyhzdx", response.properties().alertRuleResourceId()); + Assertions.assertEquals(AlertRuleCreationProperties.CREATED_WITH_ACTION_GROUP, + response.properties().createdWithProperties()); + Assertions.assertEquals(OffsetDateTime.parse("2021-03-28T04:38:02Z"), response.properties().creationTime()); + Assertions.assertEquals("zmnvdfznudaod", response.properties().alertRuleTemplateId()); + Assertions.assertEquals("xzb", response.properties().alertRuleTemplateVersion()); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourcesDeleteWithResponseMockTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourcesDeleteWithResponseMockTests.java new file mode 100644 index 000000000000..fd56334dcf36 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourcesDeleteWithResponseMockTests.java @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class AlertRuleResourcesDeleteWithResponseMockTests { + @Test + public void testDeleteWithResponse() throws Exception { + String responseStr = "{}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + DatabaseWatcherManager manager = DatabaseWatcherManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + manager.alertRuleResources() + .deleteWithResponse("ytkblmpew", "wfbkrvrns", "shqjohxcrsbf", com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourcesGetWithResponseMockTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourcesGetWithResponseMockTests.java new file mode 100644 index 000000000000..10ec4141d38e --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourcesGetWithResponseMockTests.java @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager; +import com.azure.resourcemanager.databasewatcher.models.AlertRuleCreationProperties; +import com.azure.resourcemanager.databasewatcher.models.AlertRuleResource; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class AlertRuleResourcesGetWithResponseMockTests { + @Test + public void testGetWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"alertRuleResourceId\":\"qzvszjf\",\"createdWithProperties\":\"None\",\"creationTime\":\"2021-03-12T20:34:44Z\",\"provisioningState\":\"Failed\",\"alertRuleTemplateId\":\"dxxiv\",\"alertRuleTemplateVersion\":\"tvtc\"},\"id\":\"qtdo\",\"name\":\"mcbxvwvxysl\",\"type\":\"bhsfxob\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + DatabaseWatcherManager manager = DatabaseWatcherManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + AlertRuleResource response = manager.alertRuleResources() + .getWithResponse("n", "u", "ivkrtsw", com.azure.core.util.Context.NONE) + .getValue(); + + Assertions.assertEquals("qzvszjf", response.properties().alertRuleResourceId()); + Assertions.assertEquals(AlertRuleCreationProperties.NONE, response.properties().createdWithProperties()); + Assertions.assertEquals(OffsetDateTime.parse("2021-03-12T20:34:44Z"), response.properties().creationTime()); + Assertions.assertEquals("dxxiv", response.properties().alertRuleTemplateId()); + Assertions.assertEquals("tvtc", response.properties().alertRuleTemplateVersion()); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourcesListByParentMockTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourcesListByParentMockTests.java new file mode 100644 index 000000000000..13d6e6c90e2e --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/AlertRuleResourcesListByParentMockTests.java @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager; +import com.azure.resourcemanager.databasewatcher.models.AlertRuleCreationProperties; +import com.azure.resourcemanager.databasewatcher.models.AlertRuleResource; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class AlertRuleResourcesListByParentMockTests { + @Test + public void testListByParent() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"alertRuleResourceId\":\"bsrfbj\",\"createdWithProperties\":\"CreatedWithActionGroup\",\"creationTime\":\"2021-07-26T21:20:39Z\",\"provisioningState\":\"Canceled\",\"alertRuleTemplateId\":\"sotftpvj\",\"alertRuleTemplateVersion\":\"bexilzznfqqnv\"},\"id\":\"mqtaruoujmkcjh\",\"name\":\"qytjrybnwjewgd\",\"type\":\"jervnaenqpehi\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + DatabaseWatcherManager manager = DatabaseWatcherManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response = manager.alertRuleResources() + .listByParent("vasrruvwb", "sqfsubcgjbirxb", com.azure.core.util.Context.NONE); + + Assertions.assertEquals("bsrfbj", response.iterator().next().properties().alertRuleResourceId()); + Assertions.assertEquals(AlertRuleCreationProperties.CREATED_WITH_ACTION_GROUP, + response.iterator().next().properties().createdWithProperties()); + Assertions.assertEquals(OffsetDateTime.parse("2021-07-26T21:20:39Z"), + response.iterator().next().properties().creationTime()); + Assertions.assertEquals("sotftpvj", response.iterator().next().properties().alertRuleTemplateId()); + Assertions.assertEquals("bexilzznfqqnv", response.iterator().next().properties().alertRuleTemplateVersion()); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/DatastoreTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/DatastoreTests.java new file mode 100644 index 000000000000..021c6a82fe9d --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/DatastoreTests.java @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.databasewatcher.models.Datastore; +import com.azure.resourcemanager.databasewatcher.models.KustoOfferingType; +import org.junit.jupiter.api.Assertions; + +public final class DatastoreTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + Datastore model = BinaryData.fromString( + "{\"adxClusterResourceId\":\"pini\",\"kustoClusterDisplayName\":\"ayhuy\",\"kustoClusterUri\":\"bkpodepooginuv\",\"kustoDataIngestionUri\":\"mihe\",\"kustoDatabaseName\":\"gnarxzxtheo\",\"kustoManagementUrl\":\"usivye\",\"kustoOfferingType\":\"fabric\"}") + .toObject(Datastore.class); + Assertions.assertEquals("pini", model.adxClusterResourceId()); + Assertions.assertEquals("ayhuy", model.kustoClusterDisplayName()); + Assertions.assertEquals("bkpodepooginuv", model.kustoClusterUri()); + Assertions.assertEquals("mihe", model.kustoDataIngestionUri()); + Assertions.assertEquals("gnarxzxtheo", model.kustoDatabaseName()); + Assertions.assertEquals("usivye", model.kustoManagementUrl()); + Assertions.assertEquals(KustoOfferingType.FABRIC, model.kustoOfferingType()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + Datastore model = new Datastore().withAdxClusterResourceId("pini") + .withKustoClusterDisplayName("ayhuy") + .withKustoClusterUri("bkpodepooginuv") + .withKustoDataIngestionUri("mihe") + .withKustoDatabaseName("gnarxzxtheo") + .withKustoManagementUrl("usivye") + .withKustoOfferingType(KustoOfferingType.FABRIC); + model = BinaryData.fromObject(model).toObject(Datastore.class); + Assertions.assertEquals("pini", model.adxClusterResourceId()); + Assertions.assertEquals("ayhuy", model.kustoClusterDisplayName()); + Assertions.assertEquals("bkpodepooginuv", model.kustoClusterUri()); + Assertions.assertEquals("mihe", model.kustoDataIngestionUri()); + Assertions.assertEquals("gnarxzxtheo", model.kustoDatabaseName()); + Assertions.assertEquals("usivye", model.kustoManagementUrl()); + Assertions.assertEquals(KustoOfferingType.FABRIC, model.kustoOfferingType()); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/ManagedServiceIdentityV4Tests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/ManagedServiceIdentityV4Tests.java new file mode 100644 index 000000000000..38031f50b1de --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/ManagedServiceIdentityV4Tests.java @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.databasewatcher.models.ManagedServiceIdentityType; +import com.azure.resourcemanager.databasewatcher.models.ManagedServiceIdentityV4; +import com.azure.resourcemanager.databasewatcher.models.UserAssignedIdentity; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Assertions; + +public final class ManagedServiceIdentityV4Tests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + ManagedServiceIdentityV4 model = BinaryData.fromString( + "{\"principalId\":\"iqihn\",\"tenantId\":\"ngbwjz\",\"type\":\"SystemAssigned, UserAssigned\",\"userAssignedIdentities\":{\"fjaeq\":{\"clientId\":\"xgispemvtzfkufu\",\"principalId\":\"jofxqe\"},\"rwclxxwrljdo\":{\"clientId\":\"qjbasvms\",\"principalId\":\"qulngsntnbybkzgc\"},\"hxbnjbiksqrg\":{\"clientId\":\"kcqvkocrc\",\"principalId\":\"kwt\"}}}") + .toObject(ManagedServiceIdentityV4.class); + Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_AND_USER_ASSIGNED, model.type()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + ManagedServiceIdentityV4 model + = new ManagedServiceIdentityV4().withType(ManagedServiceIdentityType.SYSTEM_AND_USER_ASSIGNED) + .withUserAssignedIdentities(mapOf("fjaeq", new UserAssignedIdentity(), "rwclxxwrljdo", + new UserAssignedIdentity(), "hxbnjbiksqrg", new UserAssignedIdentity())); + model = BinaryData.fromObject(model).toObject(ManagedServiceIdentityV4.class); + Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_AND_USER_ASSIGNED, model.type()); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/OperationDisplayTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/OperationDisplayTests.java new file mode 100644 index 000000000000..98b64b7b8926 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/OperationDisplayTests.java @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.databasewatcher.models.OperationDisplay; + +public final class OperationDisplayTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + OperationDisplay model = BinaryData.fromString( + "{\"provider\":\"cdm\",\"resource\":\"rcryuanzwuxzdxta\",\"operation\":\"lhmwhfpmrqobm\",\"description\":\"kknryrtihf\"}") + .toObject(OperationDisplay.class); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/OperationInnerTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/OperationInnerTests.java new file mode 100644 index 000000000000..0d8487f39a07 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/OperationInnerTests.java @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.databasewatcher.fluent.models.OperationInner; + +public final class OperationInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + OperationInner model = BinaryData.fromString( + "{\"name\":\"nygj\",\"isDataAction\":true,\"display\":{\"provider\":\"eqsrdeupewnwreit\",\"resource\":\"yflusarhmofc\",\"operation\":\"smy\",\"description\":\"kdtmlxhekuk\"},\"origin\":\"user,system\",\"actionType\":\"Internal\"}") + .toObject(OperationInner.class); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/OperationListResultTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/OperationListResultTests.java new file mode 100644 index 000000000000..1d2b7ae9f2e6 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/OperationListResultTests.java @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.databasewatcher.implementation.models.OperationListResult; +import org.junit.jupiter.api.Assertions; + +public final class OperationListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + OperationListResult model = BinaryData.fromString( + "{\"value\":[{\"name\":\"hq\",\"isDataAction\":true,\"display\":{\"provider\":\"pybczmehmtzopb\",\"resource\":\"h\",\"operation\":\"pidgsybbejhphoyc\",\"description\":\"xaobhdxbmtqioqjz\"},\"origin\":\"system\",\"actionType\":\"Internal\"},{\"name\":\"fpownoizhwlr\",\"isDataAction\":false,\"display\":{\"provider\":\"oqijgkdmbpaz\",\"resource\":\"bc\",\"operation\":\"pdznrbtcqqjnqgl\",\"description\":\"gnufoooj\"},\"origin\":\"system\",\"actionType\":\"Internal\"},{\"name\":\"esaagdfm\",\"isDataAction\":true,\"display\":{\"provider\":\"j\",\"resource\":\"ifkwmrvktsizntoc\",\"operation\":\"a\",\"description\":\"ajpsquc\"},\"origin\":\"system\",\"actionType\":\"Internal\"}],\"nextLink\":\"kfo\"}") + .toObject(OperationListResult.class); + Assertions.assertEquals("kfo", model.nextLink()); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/OperationsListMockTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/OperationsListMockTests.java new file mode 100644 index 000000000000..b232ece5b8d0 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/OperationsListMockTests.java @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager; +import com.azure.resourcemanager.databasewatcher.models.Operation; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class OperationsListMockTests { + @Test + public void testList() throws Exception { + String responseStr + = "{\"value\":[{\"name\":\"y\",\"isDataAction\":true,\"display\":{\"provider\":\"xc\",\"resource\":\"npc\",\"operation\":\"ocohslkevleg\",\"description\":\"fbuhfmvfaxkffe\"},\"origin\":\"user,system\",\"actionType\":\"Internal\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + DatabaseWatcherManager manager = DatabaseWatcherManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response = manager.operations().list(com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourceInnerTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourceInnerTests.java new file mode 100644 index 000000000000..9a71b5897d5b --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourceInnerTests.java @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.databasewatcher.fluent.models.SharedPrivateLinkResourceInner; +import com.azure.resourcemanager.databasewatcher.models.SharedPrivateLinkResourceProperties; +import org.junit.jupiter.api.Assertions; + +public final class SharedPrivateLinkResourceInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SharedPrivateLinkResourceInner model = BinaryData.fromString( + "{\"properties\":{\"privateLinkResourceId\":\"dpuozmyz\",\"groupId\":\"dagfuaxbezyiuok\",\"requestMessage\":\"twhrdxwzywqsm\",\"dnsZone\":\"ureximoryocfs\",\"status\":\"Pending\",\"provisioningState\":\"Failed\"},\"id\":\"dystkiiuxhqyud\",\"name\":\"o\",\"type\":\"rq\"}") + .toObject(SharedPrivateLinkResourceInner.class); + Assertions.assertEquals("dpuozmyz", model.properties().privateLinkResourceId()); + Assertions.assertEquals("dagfuaxbezyiuok", model.properties().groupId()); + Assertions.assertEquals("twhrdxwzywqsm", model.properties().requestMessage()); + Assertions.assertEquals("ureximoryocfs", model.properties().dnsZone()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SharedPrivateLinkResourceInner model = new SharedPrivateLinkResourceInner() + .withProperties(new SharedPrivateLinkResourceProperties().withPrivateLinkResourceId("dpuozmyz") + .withGroupId("dagfuaxbezyiuok") + .withRequestMessage("twhrdxwzywqsm") + .withDnsZone("ureximoryocfs")); + model = BinaryData.fromObject(model).toObject(SharedPrivateLinkResourceInner.class); + Assertions.assertEquals("dpuozmyz", model.properties().privateLinkResourceId()); + Assertions.assertEquals("dagfuaxbezyiuok", model.properties().groupId()); + Assertions.assertEquals("twhrdxwzywqsm", model.properties().requestMessage()); + Assertions.assertEquals("ureximoryocfs", model.properties().dnsZone()); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourceListResultTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourceListResultTests.java new file mode 100644 index 000000000000..b30380fe86b3 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourceListResultTests.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.databasewatcher.implementation.models.SharedPrivateLinkResourceListResult; +import org.junit.jupiter.api.Assertions; + +public final class SharedPrivateLinkResourceListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SharedPrivateLinkResourceListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"privateLinkResourceId\":\"zwtruwiqzbqjvsov\",\"groupId\":\"yokacspkw\",\"requestMessage\":\"hzdobpxjmflbvvnc\",\"dnsZone\":\"kcciwwzjuqkhr\",\"status\":\"Disconnected\",\"provisioningState\":\"Canceled\"},\"id\":\"uo\",\"name\":\"oskg\",\"type\":\"sauuimj\"}],\"nextLink\":\"xieduugidyjrr\"}") + .toObject(SharedPrivateLinkResourceListResult.class); + Assertions.assertEquals("zwtruwiqzbqjvsov", model.value().get(0).properties().privateLinkResourceId()); + Assertions.assertEquals("yokacspkw", model.value().get(0).properties().groupId()); + Assertions.assertEquals("hzdobpxjmflbvvnc", model.value().get(0).properties().requestMessage()); + Assertions.assertEquals("kcciwwzjuqkhr", model.value().get(0).properties().dnsZone()); + Assertions.assertEquals("xieduugidyjrr", model.nextLink()); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourcePropertiesTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourcePropertiesTests.java new file mode 100644 index 000000000000..59d7ef236359 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourcePropertiesTests.java @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.databasewatcher.models.SharedPrivateLinkResourceProperties; +import org.junit.jupiter.api.Assertions; + +public final class SharedPrivateLinkResourcePropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SharedPrivateLinkResourceProperties model = BinaryData.fromString( + "{\"privateLinkResourceId\":\"b\",\"groupId\":\"oczvy\",\"requestMessage\":\"fqrvkdvjsllrmvvd\",\"dnsZone\":\"atkpnp\",\"status\":\"Rejected\",\"provisioningState\":\"Failed\"}") + .toObject(SharedPrivateLinkResourceProperties.class); + Assertions.assertEquals("b", model.privateLinkResourceId()); + Assertions.assertEquals("oczvy", model.groupId()); + Assertions.assertEquals("fqrvkdvjsllrmvvd", model.requestMessage()); + Assertions.assertEquals("atkpnp", model.dnsZone()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SharedPrivateLinkResourceProperties model + = new SharedPrivateLinkResourceProperties().withPrivateLinkResourceId("b") + .withGroupId("oczvy") + .withRequestMessage("fqrvkdvjsllrmvvd") + .withDnsZone("atkpnp"); + model = BinaryData.fromObject(model).toObject(SharedPrivateLinkResourceProperties.class); + Assertions.assertEquals("b", model.privateLinkResourceId()); + Assertions.assertEquals("oczvy", model.groupId()); + Assertions.assertEquals("fqrvkdvjsllrmvvd", model.requestMessage()); + Assertions.assertEquals("atkpnp", model.dnsZone()); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourcesCreateMockTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourcesCreateMockTests.java new file mode 100644 index 000000000000..46acda55f63b --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourcesCreateMockTests.java @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager; +import com.azure.resourcemanager.databasewatcher.models.SharedPrivateLinkResource; +import com.azure.resourcemanager.databasewatcher.models.SharedPrivateLinkResourceProperties; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class SharedPrivateLinkResourcesCreateMockTests { + @Test + public void testCreate() throws Exception { + String responseStr + = "{\"properties\":{\"privateLinkResourceId\":\"washr\",\"groupId\":\"dtkcnqxwbpokulp\",\"requestMessage\":\"ujw\",\"dnsZone\":\"sipqii\",\"status\":\"Pending\",\"provisioningState\":\"Succeeded\"},\"id\":\"rpqlp\",\"name\":\"wcciuqgbdbu\",\"type\":\"auvfbtkuwhhmhyk\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + DatabaseWatcherManager manager = DatabaseWatcherManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + SharedPrivateLinkResource response = manager.sharedPrivateLinkResources() + .define("kcbcue") + .withExistingWatcher("helxprglya", "dd") + .withProperties(new SharedPrivateLinkResourceProperties().withPrivateLinkResourceId("jxgciqibrh") + .withGroupId("sxsdqrhzoymibm") + .withRequestMessage("qyib") + .withDnsZone("wfluszdt")) + .create(); + + Assertions.assertEquals("washr", response.properties().privateLinkResourceId()); + Assertions.assertEquals("dtkcnqxwbpokulp", response.properties().groupId()); + Assertions.assertEquals("ujw", response.properties().requestMessage()); + Assertions.assertEquals("sipqii", response.properties().dnsZone()); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourcesGetWithResponseMockTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourcesGetWithResponseMockTests.java new file mode 100644 index 000000000000..237bfddd4c63 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourcesGetWithResponseMockTests.java @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager; +import com.azure.resourcemanager.databasewatcher.models.SharedPrivateLinkResource; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class SharedPrivateLinkResourcesGetWithResponseMockTests { + @Test + public void testGetWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"privateLinkResourceId\":\"bobzdopcjwvnhd\",\"groupId\":\"d\",\"requestMessage\":\"mgxcxrslpm\",\"dnsZone\":\"wuoegrpk\",\"status\":\"Rejected\",\"provisioningState\":\"Failed\"},\"id\":\"qsluicp\",\"name\":\"ggkzzlvmbmpa\",\"type\":\"modfvuefywsbpfvm\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + DatabaseWatcherManager manager = DatabaseWatcherManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + SharedPrivateLinkResource response = manager.sharedPrivateLinkResources() + .getWithResponse("pnedgf", "cvkcvqvpkeqdcv", "rhvoods", com.azure.core.util.Context.NONE) + .getValue(); + + Assertions.assertEquals("bobzdopcjwvnhd", response.properties().privateLinkResourceId()); + Assertions.assertEquals("d", response.properties().groupId()); + Assertions.assertEquals("mgxcxrslpm", response.properties().requestMessage()); + Assertions.assertEquals("wuoegrpk", response.properties().dnsZone()); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourcesListByWatcherMockTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourcesListByWatcherMockTests.java new file mode 100644 index 000000000000..2bf2cceea74d --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/SharedPrivateLinkResourcesListByWatcherMockTests.java @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager; +import com.azure.resourcemanager.databasewatcher.models.SharedPrivateLinkResource; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class SharedPrivateLinkResourcesListByWatcherMockTests { + @Test + public void testListByWatcher() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"privateLinkResourceId\":\"ubex\",\"groupId\":\"pzk\",\"requestMessage\":\"mond\",\"dnsZone\":\"quxvypomgkop\",\"status\":\"Disconnected\",\"provisioningState\":\"Canceled\"},\"id\":\"pajqgxysm\",\"name\":\"cmbqfqvmk\",\"type\":\"xozap\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + DatabaseWatcherManager manager = DatabaseWatcherManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response = manager.sharedPrivateLinkResources() + .listByWatcher("yhrfouyftaakcpw", "yzvqt", com.azure.core.util.Context.NONE); + + Assertions.assertEquals("ubex", response.iterator().next().properties().privateLinkResourceId()); + Assertions.assertEquals("pzk", response.iterator().next().properties().groupId()); + Assertions.assertEquals("mond", response.iterator().next().properties().requestMessage()); + Assertions.assertEquals("quxvypomgkop", response.iterator().next().properties().dnsZone()); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/TargetsDeleteWithResponseMockTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/TargetsDeleteWithResponseMockTests.java new file mode 100644 index 000000000000..e5a2c50d63c4 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/TargetsDeleteWithResponseMockTests.java @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class TargetsDeleteWithResponseMockTests { + @Test + public void testDeleteWithResponse() throws Exception { + String responseStr = "{}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + DatabaseWatcherManager manager = DatabaseWatcherManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + manager.targets() + .deleteWithResponse("ttdumorppxebmnzb", "bhjpglkfgohdne", "el", com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/UserAssignedIdentityTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/UserAssignedIdentityTests.java new file mode 100644 index 000000000000..6d68be080f41 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/UserAssignedIdentityTests.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.databasewatcher.models.UserAssignedIdentity; + +public final class UserAssignedIdentityTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + UserAssignedIdentity model = BinaryData.fromString("{\"clientId\":\"sainqpjwnzl\",\"principalId\":\"fmppe\"}") + .toObject(UserAssignedIdentity.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + UserAssignedIdentity model = new UserAssignedIdentity(); + model = BinaryData.fromObject(model).toObject(UserAssignedIdentity.class); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatcherInnerTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatcherInnerTests.java new file mode 100644 index 000000000000..9f5842670784 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatcherInnerTests.java @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.databasewatcher.fluent.models.WatcherInner; +import com.azure.resourcemanager.databasewatcher.models.Datastore; +import com.azure.resourcemanager.databasewatcher.models.KustoOfferingType; +import com.azure.resourcemanager.databasewatcher.models.ManagedServiceIdentityType; +import com.azure.resourcemanager.databasewatcher.models.ManagedServiceIdentityV4; +import com.azure.resourcemanager.databasewatcher.models.UserAssignedIdentity; +import com.azure.resourcemanager.databasewatcher.models.WatcherProperties; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Assertions; + +public final class WatcherInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + WatcherInner model = BinaryData.fromString( + "{\"properties\":{\"datastore\":{\"adxClusterResourceId\":\"bpzvgn\",\"kustoClusterDisplayName\":\"symglzufcyz\",\"kustoClusterUri\":\"ohdbihanufh\",\"kustoDataIngestionUri\":\"cbjy\",\"kustoDatabaseName\":\"a\",\"kustoManagementUrl\":\"ithxqhabifpi\",\"kustoOfferingType\":\"free\"},\"status\":\"Running\",\"provisioningState\":\"Succeeded\",\"defaultAlertRuleIdentityResourceId\":\"scnpqxuhivy\"},\"identity\":{\"principalId\":\"wby\",\"tenantId\":\"k\",\"type\":\"None\",\"userAssignedIdentities\":{\"yejhk\":{\"clientId\":\"jgrtfwvukxga\",\"principalId\":\"ccsnhsjc\"},\"jnchgej\":{\"clientId\":\"htnapczwlokjyem\",\"principalId\":\"vnipjox\"},\"wyahuxinpmqnja\":{\"clientId\":\"odmailzyd\",\"principalId\":\"o\"}}},\"location\":\"ixjsprozvcputeg\",\"tags\":{\"u\":\"mfdatscmdvpj\",\"kjozkrwfnd\":\"suuv\",\"vwryoqpso\":\"odjpslwejd\",\"yffdfdos\":\"cctazakljlahbc\"},\"id\":\"gexpaojakhmsbz\",\"name\":\"hcrzevd\",\"type\":\"hlxaolthqtr\"}") + .toObject(WatcherInner.class); + Assertions.assertEquals("ixjsprozvcputeg", model.location()); + Assertions.assertEquals("mfdatscmdvpj", model.tags().get("u")); + Assertions.assertEquals("bpzvgn", model.properties().datastore().adxClusterResourceId()); + Assertions.assertEquals("symglzufcyz", model.properties().datastore().kustoClusterDisplayName()); + Assertions.assertEquals("ohdbihanufh", model.properties().datastore().kustoClusterUri()); + Assertions.assertEquals("cbjy", model.properties().datastore().kustoDataIngestionUri()); + Assertions.assertEquals("a", model.properties().datastore().kustoDatabaseName()); + Assertions.assertEquals("ithxqhabifpi", model.properties().datastore().kustoManagementUrl()); + Assertions.assertEquals(KustoOfferingType.FREE, model.properties().datastore().kustoOfferingType()); + Assertions.assertEquals("scnpqxuhivy", model.properties().defaultAlertRuleIdentityResourceId()); + Assertions.assertEquals(ManagedServiceIdentityType.NONE, model.identity().type()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + WatcherInner model = new WatcherInner().withLocation("ixjsprozvcputeg") + .withTags(mapOf("u", "mfdatscmdvpj", "kjozkrwfnd", "suuv", "vwryoqpso", "odjpslwejd", "yffdfdos", + "cctazakljlahbc")) + .withProperties(new WatcherProperties() + .withDatastore(new Datastore().withAdxClusterResourceId("bpzvgn") + .withKustoClusterDisplayName("symglzufcyz") + .withKustoClusterUri("ohdbihanufh") + .withKustoDataIngestionUri("cbjy") + .withKustoDatabaseName("a") + .withKustoManagementUrl("ithxqhabifpi") + .withKustoOfferingType(KustoOfferingType.FREE)) + .withDefaultAlertRuleIdentityResourceId("scnpqxuhivy")) + .withIdentity(new ManagedServiceIdentityV4().withType(ManagedServiceIdentityType.NONE) + .withUserAssignedIdentities(mapOf("yejhk", new UserAssignedIdentity(), "jnchgej", + new UserAssignedIdentity(), "wyahuxinpmqnja", new UserAssignedIdentity()))); + model = BinaryData.fromObject(model).toObject(WatcherInner.class); + Assertions.assertEquals("ixjsprozvcputeg", model.location()); + Assertions.assertEquals("mfdatscmdvpj", model.tags().get("u")); + Assertions.assertEquals("bpzvgn", model.properties().datastore().adxClusterResourceId()); + Assertions.assertEquals("symglzufcyz", model.properties().datastore().kustoClusterDisplayName()); + Assertions.assertEquals("ohdbihanufh", model.properties().datastore().kustoClusterUri()); + Assertions.assertEquals("cbjy", model.properties().datastore().kustoDataIngestionUri()); + Assertions.assertEquals("a", model.properties().datastore().kustoDatabaseName()); + Assertions.assertEquals("ithxqhabifpi", model.properties().datastore().kustoManagementUrl()); + Assertions.assertEquals(KustoOfferingType.FREE, model.properties().datastore().kustoOfferingType()); + Assertions.assertEquals("scnpqxuhivy", model.properties().defaultAlertRuleIdentityResourceId()); + Assertions.assertEquals(ManagedServiceIdentityType.NONE, model.identity().type()); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatcherListResultTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatcherListResultTests.java new file mode 100644 index 000000000000..19530d9fe302 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatcherListResultTests.java @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.databasewatcher.implementation.models.WatcherListResult; +import com.azure.resourcemanager.databasewatcher.models.KustoOfferingType; +import com.azure.resourcemanager.databasewatcher.models.ManagedServiceIdentityType; +import org.junit.jupiter.api.Assertions; + +public final class WatcherListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + WatcherListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"datastore\":{\"adxClusterResourceId\":\"ysvlejuvf\",\"kustoClusterDisplayName\":\"wrlyxwjkcprb\",\"kustoClusterUri\":\"wbxgjvt\",\"kustoDataIngestionUri\":\"vpys\",\"kustoDatabaseName\":\"zdn\",\"kustoManagementUrl\":\"uj\",\"kustoOfferingType\":\"free\"},\"status\":\"Running\",\"provisioningState\":\"Failed\",\"defaultAlertRuleIdentityResourceId\":\"uqfprwzw\"},\"identity\":{\"principalId\":\"uitnwuiz\",\"tenantId\":\"zxufiz\",\"type\":\"SystemAssigned\",\"userAssignedIdentities\":{\"zuhtymwisdkfthwx\":{\"clientId\":\"i\",\"principalId\":\"fidfvzw\"}}},\"location\":\"t\",\"tags\":{\"km\":\"aop\",\"mzidnsezcxtb\":\"jcmmxdcufufsrp\",\"dwzjeiach\":\"sgfyccsnew\",\"sfqpteehz\":\"oosflnr\"},\"id\":\"vypyqrimzinpv\",\"name\":\"wjdk\",\"type\":\"rsoodqxhcrmnoh\"},{\"properties\":{\"datastore\":{\"adxClusterResourceId\":\"whdsoifiyip\",\"kustoClusterDisplayName\":\"sqwpgrjb\",\"kustoClusterUri\":\"norcjxvsnbyxqab\",\"kustoDataIngestionUri\":\"mocpc\",\"kustoDatabaseName\":\"shurzafbljjgpbto\",\"kustoManagementUrl\":\"c\",\"kustoOfferingType\":\"free\"},\"status\":\"Running\",\"provisioningState\":\"Canceled\",\"defaultAlertRuleIdentityResourceId\":\"bqidtqaj\"},\"identity\":{\"principalId\":\"l\",\"tenantId\":\"u\",\"type\":\"SystemAssigned, UserAssigned\",\"userAssignedIdentities\":{\"ierhhbcsglummaj\":{\"clientId\":\"khbzhfepgzg\",\"principalId\":\"xzlocxscp\"},\"onpimexgstxg\":{\"clientId\":\"aodxo\",\"principalId\":\"bdxkqpxokaj\"},\"zaqsqsycbkbfk\":{\"clientId\":\"odgmaajrmvdjwz\",\"principalId\":\"ovmclwhijcoejct\"},\"c\":{\"clientId\":\"kdkexxp\",\"principalId\":\"fmxa\"}}},\"location\":\"pg\",\"tags\":{\"zxibqeoj\":\"ocjjxhvpmouexh\"},\"id\":\"xqbzvddntwnd\",\"name\":\"icbtwnpzao\",\"type\":\"vuhrhcffcyddgl\"}],\"nextLink\":\"t\"}") + .toObject(WatcherListResult.class); + Assertions.assertEquals("t", model.value().get(0).location()); + Assertions.assertEquals("aop", model.value().get(0).tags().get("km")); + Assertions.assertEquals("ysvlejuvf", model.value().get(0).properties().datastore().adxClusterResourceId()); + Assertions.assertEquals("wrlyxwjkcprb", + model.value().get(0).properties().datastore().kustoClusterDisplayName()); + Assertions.assertEquals("wbxgjvt", model.value().get(0).properties().datastore().kustoClusterUri()); + Assertions.assertEquals("vpys", model.value().get(0).properties().datastore().kustoDataIngestionUri()); + Assertions.assertEquals("zdn", model.value().get(0).properties().datastore().kustoDatabaseName()); + Assertions.assertEquals("uj", model.value().get(0).properties().datastore().kustoManagementUrl()); + Assertions.assertEquals(KustoOfferingType.FREE, + model.value().get(0).properties().datastore().kustoOfferingType()); + Assertions.assertEquals("uqfprwzw", model.value().get(0).properties().defaultAlertRuleIdentityResourceId()); + Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_ASSIGNED, model.value().get(0).identity().type()); + Assertions.assertEquals("t", model.nextLink()); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatcherPropertiesTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatcherPropertiesTests.java new file mode 100644 index 000000000000..c5f3bb35ae27 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatcherPropertiesTests.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.databasewatcher.models.Datastore; +import com.azure.resourcemanager.databasewatcher.models.KustoOfferingType; +import com.azure.resourcemanager.databasewatcher.models.WatcherProperties; +import org.junit.jupiter.api.Assertions; + +public final class WatcherPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + WatcherProperties model = BinaryData.fromString( + "{\"datastore\":{\"adxClusterResourceId\":\"bpf\",\"kustoClusterDisplayName\":\"s\",\"kustoClusterUri\":\"n\",\"kustoDataIngestionUri\":\"gvfcj\",\"kustoDatabaseName\":\"wzo\",\"kustoManagementUrl\":\"xjtfelluwfzit\",\"kustoOfferingType\":\"free\"},\"status\":\"Stopping\",\"provisioningState\":\"Canceled\",\"defaultAlertRuleIdentityResourceId\":\"jkjlxofpdvhpfx\"}") + .toObject(WatcherProperties.class); + Assertions.assertEquals("bpf", model.datastore().adxClusterResourceId()); + Assertions.assertEquals("s", model.datastore().kustoClusterDisplayName()); + Assertions.assertEquals("n", model.datastore().kustoClusterUri()); + Assertions.assertEquals("gvfcj", model.datastore().kustoDataIngestionUri()); + Assertions.assertEquals("wzo", model.datastore().kustoDatabaseName()); + Assertions.assertEquals("xjtfelluwfzit", model.datastore().kustoManagementUrl()); + Assertions.assertEquals(KustoOfferingType.FREE, model.datastore().kustoOfferingType()); + Assertions.assertEquals("jkjlxofpdvhpfx", model.defaultAlertRuleIdentityResourceId()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + WatcherProperties model = new WatcherProperties() + .withDatastore(new Datastore().withAdxClusterResourceId("bpf") + .withKustoClusterDisplayName("s") + .withKustoClusterUri("n") + .withKustoDataIngestionUri("gvfcj") + .withKustoDatabaseName("wzo") + .withKustoManagementUrl("xjtfelluwfzit") + .withKustoOfferingType(KustoOfferingType.FREE)) + .withDefaultAlertRuleIdentityResourceId("jkjlxofpdvhpfx"); + model = BinaryData.fromObject(model).toObject(WatcherProperties.class); + Assertions.assertEquals("bpf", model.datastore().adxClusterResourceId()); + Assertions.assertEquals("s", model.datastore().kustoClusterDisplayName()); + Assertions.assertEquals("n", model.datastore().kustoClusterUri()); + Assertions.assertEquals("gvfcj", model.datastore().kustoDataIngestionUri()); + Assertions.assertEquals("wzo", model.datastore().kustoDatabaseName()); + Assertions.assertEquals("xjtfelluwfzit", model.datastore().kustoManagementUrl()); + Assertions.assertEquals(KustoOfferingType.FREE, model.datastore().kustoOfferingType()); + Assertions.assertEquals("jkjlxofpdvhpfx", model.defaultAlertRuleIdentityResourceId()); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatcherUpdatePropertiesTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatcherUpdatePropertiesTests.java new file mode 100644 index 000000000000..a1f3599f066b --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatcherUpdatePropertiesTests.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.databasewatcher.models.Datastore; +import com.azure.resourcemanager.databasewatcher.models.KustoOfferingType; +import com.azure.resourcemanager.databasewatcher.models.WatcherUpdateProperties; +import org.junit.jupiter.api.Assertions; + +public final class WatcherUpdatePropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + WatcherUpdateProperties model = BinaryData.fromString( + "{\"datastore\":{\"adxClusterResourceId\":\"mutduqktaps\",\"kustoClusterDisplayName\":\"gcue\",\"kustoClusterUri\":\"tumkdosvqwhbm\",\"kustoDataIngestionUri\":\"gbbjfddgmbmbe\",\"kustoDatabaseName\":\"ppbhtqqrolfp\",\"kustoManagementUrl\":\"psalgbqux\",\"kustoOfferingType\":\"adx\"},\"defaultAlertRuleIdentityResourceId\":\"yjgzjaoyfhrtxiln\"}") + .toObject(WatcherUpdateProperties.class); + Assertions.assertEquals("mutduqktaps", model.datastore().adxClusterResourceId()); + Assertions.assertEquals("gcue", model.datastore().kustoClusterDisplayName()); + Assertions.assertEquals("tumkdosvqwhbm", model.datastore().kustoClusterUri()); + Assertions.assertEquals("gbbjfddgmbmbe", model.datastore().kustoDataIngestionUri()); + Assertions.assertEquals("ppbhtqqrolfp", model.datastore().kustoDatabaseName()); + Assertions.assertEquals("psalgbqux", model.datastore().kustoManagementUrl()); + Assertions.assertEquals(KustoOfferingType.ADX, model.datastore().kustoOfferingType()); + Assertions.assertEquals("yjgzjaoyfhrtxiln", model.defaultAlertRuleIdentityResourceId()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + WatcherUpdateProperties model = new WatcherUpdateProperties() + .withDatastore(new Datastore().withAdxClusterResourceId("mutduqktaps") + .withKustoClusterDisplayName("gcue") + .withKustoClusterUri("tumkdosvqwhbm") + .withKustoDataIngestionUri("gbbjfddgmbmbe") + .withKustoDatabaseName("ppbhtqqrolfp") + .withKustoManagementUrl("psalgbqux") + .withKustoOfferingType(KustoOfferingType.ADX)) + .withDefaultAlertRuleIdentityResourceId("yjgzjaoyfhrtxiln"); + model = BinaryData.fromObject(model).toObject(WatcherUpdateProperties.class); + Assertions.assertEquals("mutduqktaps", model.datastore().adxClusterResourceId()); + Assertions.assertEquals("gcue", model.datastore().kustoClusterDisplayName()); + Assertions.assertEquals("tumkdosvqwhbm", model.datastore().kustoClusterUri()); + Assertions.assertEquals("gbbjfddgmbmbe", model.datastore().kustoDataIngestionUri()); + Assertions.assertEquals("ppbhtqqrolfp", model.datastore().kustoDatabaseName()); + Assertions.assertEquals("psalgbqux", model.datastore().kustoManagementUrl()); + Assertions.assertEquals(KustoOfferingType.ADX, model.datastore().kustoOfferingType()); + Assertions.assertEquals("yjgzjaoyfhrtxiln", model.defaultAlertRuleIdentityResourceId()); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatcherUpdateTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatcherUpdateTests.java new file mode 100644 index 000000000000..56199556510b --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatcherUpdateTests.java @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.databasewatcher.models.Datastore; +import com.azure.resourcemanager.databasewatcher.models.KustoOfferingType; +import com.azure.resourcemanager.databasewatcher.models.ManagedServiceIdentityType; +import com.azure.resourcemanager.databasewatcher.models.ManagedServiceIdentityV4; +import com.azure.resourcemanager.databasewatcher.models.UserAssignedIdentity; +import com.azure.resourcemanager.databasewatcher.models.WatcherUpdate; +import com.azure.resourcemanager.databasewatcher.models.WatcherUpdateProperties; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Assertions; + +public final class WatcherUpdateTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + WatcherUpdate model = BinaryData.fromString( + "{\"identity\":{\"principalId\":\"mgxsab\",\"tenantId\":\"qduujitcjczdz\",\"type\":\"UserAssigned\",\"userAssignedIdentities\":{\"jfeusnh\":{\"clientId\":\"krwpdap\",\"principalId\":\"sbdkvwr\"},\"jzzd\":{\"clientId\":\"je\",\"principalId\":\"mrldhu\"},\"aozwyiftyhxhu\":{\"clientId\":\"qxhocdgeablgphut\",\"principalId\":\"ndv\"},\"cukjf\":{\"clientId\":\"k\",\"principalId\":\"yxolniwp\"}}},\"tags\":{\"plwckbas\":\"awxklr\",\"cph\":\"ypnddhsgcb\"},\"properties\":{\"datastore\":{\"adxClusterResourceId\":\"tynqgoul\",\"kustoClusterDisplayName\":\"dlikwyqkgfgibma\",\"kustoClusterUri\":\"gakeqsr\",\"kustoDataIngestionUri\":\"yb\",\"kustoDatabaseName\":\"qqedqytbciqfou\",\"kustoManagementUrl\":\"lmmnkzsmodmglo\",\"kustoOfferingType\":\"fabric\"},\"defaultAlertRuleIdentityResourceId\":\"b\"}}") + .toObject(WatcherUpdate.class); + Assertions.assertEquals(ManagedServiceIdentityType.USER_ASSIGNED, model.identity().type()); + Assertions.assertEquals("awxklr", model.tags().get("plwckbas")); + Assertions.assertEquals("tynqgoul", model.properties().datastore().adxClusterResourceId()); + Assertions.assertEquals("dlikwyqkgfgibma", model.properties().datastore().kustoClusterDisplayName()); + Assertions.assertEquals("gakeqsr", model.properties().datastore().kustoClusterUri()); + Assertions.assertEquals("yb", model.properties().datastore().kustoDataIngestionUri()); + Assertions.assertEquals("qqedqytbciqfou", model.properties().datastore().kustoDatabaseName()); + Assertions.assertEquals("lmmnkzsmodmglo", model.properties().datastore().kustoManagementUrl()); + Assertions.assertEquals(KustoOfferingType.FABRIC, model.properties().datastore().kustoOfferingType()); + Assertions.assertEquals("b", model.properties().defaultAlertRuleIdentityResourceId()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + WatcherUpdate model + = new WatcherUpdate() + .withIdentity(new ManagedServiceIdentityV4().withType(ManagedServiceIdentityType.USER_ASSIGNED) + .withUserAssignedIdentities( + mapOf("jfeusnh", new UserAssignedIdentity(), "jzzd", new UserAssignedIdentity(), + "aozwyiftyhxhu", new UserAssignedIdentity(), "cukjf", new UserAssignedIdentity()))) + .withTags(mapOf("plwckbas", "awxklr", "cph", "ypnddhsgcb")) + .withProperties( + new WatcherUpdateProperties() + .withDatastore(new Datastore().withAdxClusterResourceId("tynqgoul") + .withKustoClusterDisplayName("dlikwyqkgfgibma") + .withKustoClusterUri("gakeqsr") + .withKustoDataIngestionUri("yb") + .withKustoDatabaseName("qqedqytbciqfou") + .withKustoManagementUrl("lmmnkzsmodmglo") + .withKustoOfferingType(KustoOfferingType.FABRIC)) + .withDefaultAlertRuleIdentityResourceId("b")); + model = BinaryData.fromObject(model).toObject(WatcherUpdate.class); + Assertions.assertEquals(ManagedServiceIdentityType.USER_ASSIGNED, model.identity().type()); + Assertions.assertEquals("awxklr", model.tags().get("plwckbas")); + Assertions.assertEquals("tynqgoul", model.properties().datastore().adxClusterResourceId()); + Assertions.assertEquals("dlikwyqkgfgibma", model.properties().datastore().kustoClusterDisplayName()); + Assertions.assertEquals("gakeqsr", model.properties().datastore().kustoClusterUri()); + Assertions.assertEquals("yb", model.properties().datastore().kustoDataIngestionUri()); + Assertions.assertEquals("qqedqytbciqfou", model.properties().datastore().kustoDatabaseName()); + Assertions.assertEquals("lmmnkzsmodmglo", model.properties().datastore().kustoManagementUrl()); + Assertions.assertEquals(KustoOfferingType.FABRIC, model.properties().datastore().kustoOfferingType()); + Assertions.assertEquals("b", model.properties().defaultAlertRuleIdentityResourceId()); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatchersCreateOrUpdateMockTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatchersCreateOrUpdateMockTests.java new file mode 100644 index 000000000000..6941963d47f0 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatchersCreateOrUpdateMockTests.java @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager; +import com.azure.resourcemanager.databasewatcher.models.Datastore; +import com.azure.resourcemanager.databasewatcher.models.KustoOfferingType; +import com.azure.resourcemanager.databasewatcher.models.ManagedServiceIdentityType; +import com.azure.resourcemanager.databasewatcher.models.ManagedServiceIdentityV4; +import com.azure.resourcemanager.databasewatcher.models.UserAssignedIdentity; +import com.azure.resourcemanager.databasewatcher.models.Watcher; +import com.azure.resourcemanager.databasewatcher.models.WatcherProperties; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class WatchersCreateOrUpdateMockTests { + @Test + public void testCreateOrUpdate() throws Exception { + String responseStr + = "{\"properties\":{\"datastore\":{\"adxClusterResourceId\":\"uh\",\"kustoClusterDisplayName\":\"p\",\"kustoClusterUri\":\"sjyofdx\",\"kustoDataIngestionUri\":\"uusdttouwa\",\"kustoDatabaseName\":\"oekqvk\",\"kustoManagementUrl\":\"lns\",\"kustoOfferingType\":\"adx\"},\"status\":\"Running\",\"provisioningState\":\"Succeeded\",\"defaultAlertRuleIdentityResourceId\":\"sflhhca\"},\"identity\":{\"principalId\":\"jixisxyawjoyaqcs\",\"tenantId\":\"jpkiidzyexznelix\",\"type\":\"None\",\"userAssignedIdentities\":{\"ggdtpnapnyiro\":{\"clientId\":\"folhbnxknal\",\"principalId\":\"lp\"},\"n\":{\"clientId\":\"hpigv\",\"principalId\":\"ylgqgitxmedjvcsl\"},\"tfdygpfqb\":{\"clientId\":\"wncwzzhxgktrmg\",\"principalId\":\"napkteoellw\"}}},\"location\":\"ceopzfqrhhuaopp\",\"tags\":{\"lzdahzxctobgbkdm\":\"eqx\",\"grcfb\":\"izpost\"},\"id\":\"nrmfqjhhk\",\"name\":\"bpvjymjhx\",\"type\":\"j\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + DatabaseWatcherManager manager = DatabaseWatcherManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + Watcher response + = manager.watchers() + .define("zbtd") + .withRegion("iwwroyqbexrmc") + .withExistingResourceGroup("l") + .withTags(mapOf("vah", "ycnojvknmefqsg", "qzcjrvxdj", "pjyzhpv", "awjvzunluthnnp", "lmwlxkvugfhzo")) + .withProperties(new WatcherProperties() + .withDatastore(new Datastore().withAdxClusterResourceId("znbmpowuwprzq") + .withKustoClusterDisplayName("eualupjmkhf") + .withKustoClusterUri("obbc") + .withKustoDataIngestionUri("wsrtjriplrbpbe") + .withKustoDatabaseName("tghfgblcgwxzvl") + .withKustoManagementUrl("qhjk") + .withKustoOfferingType(KustoOfferingType.FREE)) + .withDefaultAlertRuleIdentityResourceId("mxiebw")) + .withIdentity(new ManagedServiceIdentityV4().withType(ManagedServiceIdentityType.SYSTEM_ASSIGNED) + .withUserAssignedIdentities(mapOf("iuhprwmdyvxqta", new UserAssignedIdentity()))) + .create(); + + Assertions.assertEquals("ceopzfqrhhuaopp", response.location()); + Assertions.assertEquals("eqx", response.tags().get("lzdahzxctobgbkdm")); + Assertions.assertEquals("uh", response.properties().datastore().adxClusterResourceId()); + Assertions.assertEquals("p", response.properties().datastore().kustoClusterDisplayName()); + Assertions.assertEquals("sjyofdx", response.properties().datastore().kustoClusterUri()); + Assertions.assertEquals("uusdttouwa", response.properties().datastore().kustoDataIngestionUri()); + Assertions.assertEquals("oekqvk", response.properties().datastore().kustoDatabaseName()); + Assertions.assertEquals("lns", response.properties().datastore().kustoManagementUrl()); + Assertions.assertEquals(KustoOfferingType.ADX, response.properties().datastore().kustoOfferingType()); + Assertions.assertEquals("sflhhca", response.properties().defaultAlertRuleIdentityResourceId()); + Assertions.assertEquals(ManagedServiceIdentityType.NONE, response.identity().type()); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatchersGetByResourceGroupWithResponseMockTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatchersGetByResourceGroupWithResponseMockTests.java new file mode 100644 index 000000000000..353ab360e3e0 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatchersGetByResourceGroupWithResponseMockTests.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager; +import com.azure.resourcemanager.databasewatcher.models.KustoOfferingType; +import com.azure.resourcemanager.databasewatcher.models.ManagedServiceIdentityType; +import com.azure.resourcemanager.databasewatcher.models.Watcher; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class WatchersGetByResourceGroupWithResponseMockTests { + @Test + public void testGetByResourceGroupWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"datastore\":{\"adxClusterResourceId\":\"vjxxjnsp\",\"kustoClusterDisplayName\":\"ptkoenkoukn\",\"kustoClusterUri\":\"udwtiukbl\",\"kustoDataIngestionUri\":\"ngkpocipazy\",\"kustoDatabaseName\":\"o\",\"kustoManagementUrl\":\"gukgjnpiucgygevq\",\"kustoOfferingType\":\"fabric\"},\"status\":\"Deleting\",\"provisioningState\":\"Failed\",\"defaultAlertRuleIdentityResourceId\":\"bpizcdrqjsdpydn\"},\"identity\":{\"principalId\":\"xdeoejzic\",\"tenantId\":\"fsj\",\"type\":\"UserAssigned\",\"userAssignedIdentities\":{\"agalpbuxwgipwhon\":{\"clientId\":\"bishcbkhajdeyea\",\"principalId\":\"p\"},\"uzoqft\":{\"clientId\":\"kgshwa\",\"principalId\":\"ixzbinjeputtmryw\"},\"yav\":{\"clientId\":\"qzrnkcqvyxlwhz\",\"principalId\":\"icohoqqnwvl\"}}},\"location\":\"heun\",\"tags\":{\"koklya\":\"hgyxzkonoc\",\"ewrmjmwvvjektc\":\"uconuqszfkbey\",\"frzpwvlqdqgb\":\"senhwlrs\",\"fcivfsnkym\":\"qylihkaetckt\"},\"id\":\"ctq\",\"name\":\"jf\",\"type\":\"ebrjcxe\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + DatabaseWatcherManager manager = DatabaseWatcherManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + Watcher response = manager.watchers() + .getByResourceGroupWithResponse("vmezy", "shxmzsbbzoggigrx", com.azure.core.util.Context.NONE) + .getValue(); + + Assertions.assertEquals("heun", response.location()); + Assertions.assertEquals("hgyxzkonoc", response.tags().get("koklya")); + Assertions.assertEquals("vjxxjnsp", response.properties().datastore().adxClusterResourceId()); + Assertions.assertEquals("ptkoenkoukn", response.properties().datastore().kustoClusterDisplayName()); + Assertions.assertEquals("udwtiukbl", response.properties().datastore().kustoClusterUri()); + Assertions.assertEquals("ngkpocipazy", response.properties().datastore().kustoDataIngestionUri()); + Assertions.assertEquals("o", response.properties().datastore().kustoDatabaseName()); + Assertions.assertEquals("gukgjnpiucgygevq", response.properties().datastore().kustoManagementUrl()); + Assertions.assertEquals(KustoOfferingType.FABRIC, response.properties().datastore().kustoOfferingType()); + Assertions.assertEquals("bpizcdrqjsdpydn", response.properties().defaultAlertRuleIdentityResourceId()); + Assertions.assertEquals(ManagedServiceIdentityType.USER_ASSIGNED, response.identity().type()); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatchersListByResourceGroupMockTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatchersListByResourceGroupMockTests.java new file mode 100644 index 000000000000..66e3d127a5da --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatchersListByResourceGroupMockTests.java @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager; +import com.azure.resourcemanager.databasewatcher.models.KustoOfferingType; +import com.azure.resourcemanager.databasewatcher.models.ManagedServiceIdentityType; +import com.azure.resourcemanager.databasewatcher.models.Watcher; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class WatchersListByResourceGroupMockTests { + @Test + public void testListByResourceGroup() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"datastore\":{\"adxClusterResourceId\":\"i\",\"kustoClusterDisplayName\":\"hxepcyvahfnlj\",\"kustoClusterUri\":\"yq\",\"kustoDataIngestionUri\":\"j\",\"kustoDatabaseName\":\"uujqgidokgjljyo\",\"kustoManagementUrl\":\"gvcl\",\"kustoOfferingType\":\"adx\"},\"status\":\"Starting\",\"provisioningState\":\"Failed\",\"defaultAlertRuleIdentityResourceId\":\"hkjeszzhbi\"},\"identity\":{\"principalId\":\"xfvgxbfsmxne\",\"tenantId\":\"pvecxgodeb\",\"type\":\"SystemAssigned\",\"userAssignedIdentities\":{\"qzahmgkbrp\":{\"clientId\":\"bmpukgriwflz\",\"principalId\":\"bxzpuzycisp\"}}},\"location\":\"dhibnuq\",\"tags\":{\"drgvtqagn\":\"ik\",\"mebf\":\"uynhijg\"},\"id\":\"iarbutrcvpna\",\"name\":\"zmhjrunmp\",\"type\":\"ttdbhrbnl\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + DatabaseWatcherManager manager = DatabaseWatcherManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response + = manager.watchers().listByResourceGroup("fuwutttxf", com.azure.core.util.Context.NONE); + + Assertions.assertEquals("dhibnuq", response.iterator().next().location()); + Assertions.assertEquals("ik", response.iterator().next().tags().get("drgvtqagn")); + Assertions.assertEquals("i", response.iterator().next().properties().datastore().adxClusterResourceId()); + Assertions.assertEquals("hxepcyvahfnlj", + response.iterator().next().properties().datastore().kustoClusterDisplayName()); + Assertions.assertEquals("yq", response.iterator().next().properties().datastore().kustoClusterUri()); + Assertions.assertEquals("j", response.iterator().next().properties().datastore().kustoDataIngestionUri()); + Assertions.assertEquals("uujqgidokgjljyo", + response.iterator().next().properties().datastore().kustoDatabaseName()); + Assertions.assertEquals("gvcl", response.iterator().next().properties().datastore().kustoManagementUrl()); + Assertions.assertEquals(KustoOfferingType.ADX, + response.iterator().next().properties().datastore().kustoOfferingType()); + Assertions.assertEquals("hkjeszzhbi", + response.iterator().next().properties().defaultAlertRuleIdentityResourceId()); + Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_ASSIGNED, + response.iterator().next().identity().type()); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatchersListMockTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatchersListMockTests.java new file mode 100644 index 000000000000..d0d6b3724473 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatchersListMockTests.java @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager; +import com.azure.resourcemanager.databasewatcher.models.KustoOfferingType; +import com.azure.resourcemanager.databasewatcher.models.ManagedServiceIdentityType; +import com.azure.resourcemanager.databasewatcher.models.Watcher; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class WatchersListMockTests { + @Test + public void testList() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"datastore\":{\"adxClusterResourceId\":\"myskpbhenbtkcxy\",\"kustoClusterDisplayName\":\"y\",\"kustoClusterUri\":\"nrs\",\"kustoDataIngestionUri\":\"nlqidybyxczf\",\"kustoDatabaseName\":\"lhaaxdbabp\",\"kustoManagementUrl\":\"lwrq\",\"kustoOfferingType\":\"adx\"},\"status\":\"Stopping\",\"provisioningState\":\"Failed\",\"defaultAlertRuleIdentityResourceId\":\"sucocmnyyazttbtw\"},\"identity\":{\"principalId\":\"puedckzywbiexzf\",\"tenantId\":\"ue\",\"type\":\"SystemAssigned, UserAssigned\",\"userAssignedIdentities\":{\"zyoxaepdkzjan\":{\"clientId\":\"ujwb\",\"principalId\":\"walm\"}}},\"location\":\"xrhdwbavxbniwdjs\",\"tags\":{\"bpg\":\"s\",\"fzab\":\"xytxhpzxbz\"},\"id\":\"lcuhxwtctyqiklb\",\"name\":\"ovplw\",\"type\":\"bhvgy\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + DatabaseWatcherManager manager = DatabaseWatcherManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response = manager.watchers().list(com.azure.core.util.Context.NONE); + + Assertions.assertEquals("xrhdwbavxbniwdjs", response.iterator().next().location()); + Assertions.assertEquals("s", response.iterator().next().tags().get("bpg")); + Assertions.assertEquals("myskpbhenbtkcxy", + response.iterator().next().properties().datastore().adxClusterResourceId()); + Assertions.assertEquals("y", response.iterator().next().properties().datastore().kustoClusterDisplayName()); + Assertions.assertEquals("nrs", response.iterator().next().properties().datastore().kustoClusterUri()); + Assertions.assertEquals("nlqidybyxczf", + response.iterator().next().properties().datastore().kustoDataIngestionUri()); + Assertions.assertEquals("lhaaxdbabp", response.iterator().next().properties().datastore().kustoDatabaseName()); + Assertions.assertEquals("lwrq", response.iterator().next().properties().datastore().kustoManagementUrl()); + Assertions.assertEquals(KustoOfferingType.ADX, + response.iterator().next().properties().datastore().kustoOfferingType()); + Assertions.assertEquals("sucocmnyyazttbtw", + response.iterator().next().properties().defaultAlertRuleIdentityResourceId()); + Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_AND_USER_ASSIGNED, + response.iterator().next().identity().type()); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatchersStartMockTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatchersStartMockTests.java new file mode 100644 index 000000000000..fb898f1ed726 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatchersStartMockTests.java @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager; +import com.azure.resourcemanager.databasewatcher.models.KustoOfferingType; +import com.azure.resourcemanager.databasewatcher.models.ManagedServiceIdentityType; +import com.azure.resourcemanager.databasewatcher.models.Watcher; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class WatchersStartMockTests { + @Test + public void testStart() throws Exception { + String responseStr + = "{\"properties\":{\"datastore\":{\"adxClusterResourceId\":\"gmgsxnkjzkde\",\"kustoClusterDisplayName\":\"pvlopwiyighxpkd\",\"kustoClusterUri\":\"zb\",\"kustoDataIngestionUri\":\"iuebbaumny\",\"kustoDatabaseName\":\"upedeojnabckhs\",\"kustoManagementUrl\":\"txp\",\"kustoOfferingType\":\"fabric\"},\"status\":\"Running\",\"provisioningState\":\"Succeeded\",\"defaultAlertRuleIdentityResourceId\":\"vpesapskrdqmhjjd\"},\"identity\":{\"principalId\":\"dwkyzxuu\",\"tenantId\":\"ncwscwsvlxoto\",\"type\":\"UserAssigned\",\"userAssignedIdentities\":{\"yfjfcnjbkcn\":{\"clientId\":\"pqsxvnmicy\",\"principalId\":\"ceoveilovno\"},\"phoxus\":{\"clientId\":\"hbttkphyw\",\"principalId\":\"vjtoqnermclfp\"},\"wfqkquj\":{\"clientId\":\"pabgyeps\",\"principalId\":\"tazqugxywpmueefj\"}}},\"location\":\"suyonobglaocq\",\"tags\":{\"ytlmoyrxvwfud\":\"cmgyud\"},\"id\":\"pz\",\"name\":\"txhdzh\",\"type\":\"rqjbhckfrl\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + DatabaseWatcherManager manager = DatabaseWatcherManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + Watcher response = manager.watchers().start("gu", "svmkfssxquk", com.azure.core.util.Context.NONE); + + Assertions.assertEquals("suyonobglaocq", response.location()); + Assertions.assertEquals("cmgyud", response.tags().get("ytlmoyrxvwfud")); + Assertions.assertEquals("gmgsxnkjzkde", response.properties().datastore().adxClusterResourceId()); + Assertions.assertEquals("pvlopwiyighxpkd", response.properties().datastore().kustoClusterDisplayName()); + Assertions.assertEquals("zb", response.properties().datastore().kustoClusterUri()); + Assertions.assertEquals("iuebbaumny", response.properties().datastore().kustoDataIngestionUri()); + Assertions.assertEquals("upedeojnabckhs", response.properties().datastore().kustoDatabaseName()); + Assertions.assertEquals("txp", response.properties().datastore().kustoManagementUrl()); + Assertions.assertEquals(KustoOfferingType.FABRIC, response.properties().datastore().kustoOfferingType()); + Assertions.assertEquals("vpesapskrdqmhjjd", response.properties().defaultAlertRuleIdentityResourceId()); + Assertions.assertEquals(ManagedServiceIdentityType.USER_ASSIGNED, response.identity().type()); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatchersStopMockTests.java b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatchersStopMockTests.java new file mode 100644 index 000000000000..14c5c4933bd0 --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/src/test/java/com/azure/resourcemanager/databasewatcher/generated/WatchersStopMockTests.java @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.databasewatcher.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.databasewatcher.DatabaseWatcherManager; +import com.azure.resourcemanager.databasewatcher.models.KustoOfferingType; +import com.azure.resourcemanager.databasewatcher.models.ManagedServiceIdentityType; +import com.azure.resourcemanager.databasewatcher.models.Watcher; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class WatchersStopMockTests { + @Test + public void testStop() throws Exception { + String responseStr + = "{\"properties\":{\"datastore\":{\"adxClusterResourceId\":\"p\",\"kustoClusterDisplayName\":\"afkuwb\",\"kustoClusterUri\":\"rnwb\",\"kustoDataIngestionUri\":\"ehhseyvjusrts\",\"kustoDatabaseName\":\"hspkdeemao\",\"kustoManagementUrl\":\"mx\",\"kustoOfferingType\":\"free\"},\"status\":\"Deleting\",\"provisioningState\":\"Succeeded\",\"defaultAlertRuleIdentityResourceId\":\"lmqkrhahvlj\"},\"identity\":{\"principalId\":\"aquhcdhm\",\"tenantId\":\"alaexqpvfadmwsrc\",\"type\":\"None\",\"userAssignedIdentities\":{\"e\":{\"clientId\":\"vgomz\",\"principalId\":\"misgwbnb\"},\"uhashsfwx\":{\"clientId\":\"awkz\",\"principalId\":\"liourqhak\"}}},\"location\":\"owzxcu\",\"tags\":{\"ucww\":\"jooxdjebw\",\"bvmeuecivy\":\"vo\",\"ueiotwmcdyt\":\"zceuojgjrw\",\"it\":\"x\"},\"id\":\"nrjawgqwg\",\"name\":\"hniskxfbkpyc\",\"type\":\"klwndnhjdauwhv\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + DatabaseWatcherManager manager = DatabaseWatcherManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + Watcher response = manager.watchers().stop("rxsbkyvp", "ca", com.azure.core.util.Context.NONE); + + Assertions.assertEquals("owzxcu", response.location()); + Assertions.assertEquals("jooxdjebw", response.tags().get("ucww")); + Assertions.assertEquals("p", response.properties().datastore().adxClusterResourceId()); + Assertions.assertEquals("afkuwb", response.properties().datastore().kustoClusterDisplayName()); + Assertions.assertEquals("rnwb", response.properties().datastore().kustoClusterUri()); + Assertions.assertEquals("ehhseyvjusrts", response.properties().datastore().kustoDataIngestionUri()); + Assertions.assertEquals("hspkdeemao", response.properties().datastore().kustoDatabaseName()); + Assertions.assertEquals("mx", response.properties().datastore().kustoManagementUrl()); + Assertions.assertEquals(KustoOfferingType.FREE, response.properties().datastore().kustoOfferingType()); + Assertions.assertEquals("lmqkrhahvlj", response.properties().defaultAlertRuleIdentityResourceId()); + Assertions.assertEquals(ManagedServiceIdentityType.NONE, response.identity().type()); + } +} diff --git a/sdk/databasewatcher/azure-resourcemanager-databasewatcher/tsp-location.yaml b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/tsp-location.yaml new file mode 100644 index 000000000000..daf4d951d9dc --- /dev/null +++ b/sdk/databasewatcher/azure-resourcemanager-databasewatcher/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/databasewatcher/DatabaseWatcher.Management +commit: 57323ac6c745ba3af373dd1f62fa924e79fb828c +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/databasewatcher/ci.yml b/sdk/databasewatcher/ci.yml new file mode 100644 index 000000000000..60553b79960e --- /dev/null +++ b/sdk/databasewatcher/ci.yml @@ -0,0 +1,46 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. + +trigger: + branches: + include: + - main + - hotfix/* + - release/* + paths: + include: + - sdk/databasewatcher/ci.yml + - sdk/databasewatcher/azure-resourcemanager-databasewatcher/ + exclude: + - sdk/databasewatcher/pom.xml + - sdk/databasewatcher/azure-resourcemanager-databasewatcher/pom.xml + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/databasewatcher/ci.yml + - sdk/databasewatcher/azure-resourcemanager-databasewatcher/ + exclude: + - sdk/databasewatcher/pom.xml + - sdk/databasewatcher/azure-resourcemanager-databasewatcher/pom.xml + +parameters: + - name: release_azureresourcemanagerdatabasewatcher + displayName: azure-resourcemanager-databasewatcher + type: boolean + default: false + +extends: + template: ../../eng/pipelines/templates/stages/archetype-sdk-client.yml + parameters: + ServiceDirectory: databasewatcher + Artifacts: + - name: azure-resourcemanager-databasewatcher + groupId: com.azure.resourcemanager + safeName: azureresourcemanagerdatabasewatcher + releaseInBatch: ${{ parameters.release_azureresourcemanagerdatabasewatcher }} diff --git a/sdk/databasewatcher/pom.xml b/sdk/databasewatcher/pom.xml new file mode 100644 index 000000000000..a3dd9f80b4a6 --- /dev/null +++ b/sdk/databasewatcher/pom.xml @@ -0,0 +1,15 @@ + + + 4.0.0 + com.azure + azure-databasewatcher-service + pom + 1.0.0 + + + azure-resourcemanager-databasewatcher + + diff --git a/sdk/databox/azure-resourcemanager-databox/README.md b/sdk/databox/azure-resourcemanager-databox/README.md index 0c69d7ba40db..525d88bd31cf 100644 --- a/sdk/databox/azure-resourcemanager-databox/README.md +++ b/sdk/databox/azure-resourcemanager-databox/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-databox - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fdatabox%2Fazure-resourcemanager-databox%2FREADME.png) + diff --git a/sdk/databox/azure-resourcemanager-databox/pom.xml b/sdk/databox/azure-resourcemanager-databox/pom.xml index bf8104aca3a2..929b1a6bc219 100644 --- a/sdk/databox/azure-resourcemanager-databox/pom.xml +++ b/sdk/databox/azure-resourcemanager-databox/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/databoxedge/azure-resourcemanager-databoxedge/README.md b/sdk/databoxedge/azure-resourcemanager-databoxedge/README.md index d5ea0f496807..f4a969457776 100644 --- a/sdk/databoxedge/azure-resourcemanager-databoxedge/README.md +++ b/sdk/databoxedge/azure-resourcemanager-databoxedge/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-databoxedge - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fdataboxedge%2Fazure-resourcemanager-databoxedge%2FREADME.png) + diff --git a/sdk/databoxedge/azure-resourcemanager-databoxedge/pom.xml b/sdk/databoxedge/azure-resourcemanager-databoxedge/pom.xml index 1a7778760a63..f534c74241ae 100644 --- a/sdk/databoxedge/azure-resourcemanager-databoxedge/pom.xml +++ b/sdk/databoxedge/azure-resourcemanager-databoxedge/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/databricks/azure-resourcemanager-databricks/README.md b/sdk/databricks/azure-resourcemanager-databricks/README.md index f896177c4b7b..ee1b343f7dee 100644 --- a/sdk/databricks/azure-resourcemanager-databricks/README.md +++ b/sdk/databricks/azure-resourcemanager-databricks/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-databricks - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -110,4 +110,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fdatabricks%2Fazure-resourcemanager-databricks%2FREADME.png) + diff --git a/sdk/databricks/azure-resourcemanager-databricks/pom.xml b/sdk/databricks/azure-resourcemanager-databricks/pom.xml index de2b06c7f37f..e351ec321b32 100644 --- a/sdk/databricks/azure-resourcemanager-databricks/pom.xml +++ b/sdk/databricks/azure-resourcemanager-databricks/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test @@ -91,7 +91,7 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/datadog/azure-resourcemanager-datadog/README.md b/sdk/datadog/azure-resourcemanager-datadog/README.md index c96a4ae18878..a370a3ab6009 100644 --- a/sdk/datadog/azure-resourcemanager-datadog/README.md +++ b/sdk/datadog/azure-resourcemanager-datadog/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-datadog - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fdatadog%2Fazure-resourcemanager-datadog%2FREADME.png) + diff --git a/sdk/datadog/azure-resourcemanager-datadog/pom.xml b/sdk/datadog/azure-resourcemanager-datadog/pom.xml index 735cb756dcf7..18a80cf9125c 100644 --- a/sdk/datadog/azure-resourcemanager-datadog/pom.xml +++ b/sdk/datadog/azure-resourcemanager-datadog/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/datafactory/azure-resourcemanager-datafactory/README.md b/sdk/datafactory/azure-resourcemanager-datafactory/README.md index 3325d497a2c8..632bda66c33b 100644 --- a/sdk/datafactory/azure-resourcemanager-datafactory/README.md +++ b/sdk/datafactory/azure-resourcemanager-datafactory/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-datafactory - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -194,4 +194,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fdatafactory%2Fazure-resourcemanager-datafactory%2FREADME.png) + diff --git a/sdk/datafactory/azure-resourcemanager-datafactory/pom.xml b/sdk/datafactory/azure-resourcemanager-datafactory/pom.xml index 5c9aec89b2ae..ce379582f49f 100644 --- a/sdk/datafactory/azure-resourcemanager-datafactory/pom.xml +++ b/sdk/datafactory/azure-resourcemanager-datafactory/pom.xml @@ -51,40 +51,40 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-json - 1.3.0 + 1.5.0 com.azure.resourcemanager azure-resourcemanager-storage - 2.46.0 + 2.48.0 test com.azure azure-storage-blob - 12.29.0 + 12.29.1 test diff --git a/sdk/datalakeanalytics/azure-resourcemanager-datalakeanalytics/README.md b/sdk/datalakeanalytics/azure-resourcemanager-datalakeanalytics/README.md index 8ade841a2f4d..419624053e3e 100644 --- a/sdk/datalakeanalytics/azure-resourcemanager-datalakeanalytics/README.md +++ b/sdk/datalakeanalytics/azure-resourcemanager-datalakeanalytics/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-datalakeanalytics - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fdatalakeanalytics%2Fazure-resourcemanager-datalakeanalytics%2FREADME.png) + diff --git a/sdk/datalakeanalytics/azure-resourcemanager-datalakeanalytics/pom.xml b/sdk/datalakeanalytics/azure-resourcemanager-datalakeanalytics/pom.xml index 5be0593f5cf8..36652bddd861 100644 --- a/sdk/datalakeanalytics/azure-resourcemanager-datalakeanalytics/pom.xml +++ b/sdk/datalakeanalytics/azure-resourcemanager-datalakeanalytics/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/datalakestore/azure-resourcemanager-datalakestore/README.md b/sdk/datalakestore/azure-resourcemanager-datalakestore/README.md index b2f5a56d1340..b7728425ad64 100644 --- a/sdk/datalakestore/azure-resourcemanager-datalakestore/README.md +++ b/sdk/datalakestore/azure-resourcemanager-datalakestore/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-datalakestore - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fdatalakestore%2Fazure-resourcemanager-datalakestore%2FREADME.png) + diff --git a/sdk/datalakestore/azure-resourcemanager-datalakestore/pom.xml b/sdk/datalakestore/azure-resourcemanager-datalakestore/pom.xml index 73a46152f97e..adbfafbe9f47 100644 --- a/sdk/datalakestore/azure-resourcemanager-datalakestore/pom.xml +++ b/sdk/datalakestore/azure-resourcemanager-datalakestore/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/datamigration/azure-resourcemanager-datamigration/README.md b/sdk/datamigration/azure-resourcemanager-datamigration/README.md index a6c388c6d428..2c302bd4b9c5 100644 --- a/sdk/datamigration/azure-resourcemanager-datamigration/README.md +++ b/sdk/datamigration/azure-resourcemanager-datamigration/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-datamigration - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fdatamigration%2Fazure-resourcemanager-datamigration%2FREADME.png) + diff --git a/sdk/datamigration/azure-resourcemanager-datamigration/pom.xml b/sdk/datamigration/azure-resourcemanager-datamigration/pom.xml index fc9ad0f5ee5c..54f6afa11759 100644 --- a/sdk/datamigration/azure-resourcemanager-datamigration/pom.xml +++ b/sdk/datamigration/azure-resourcemanager-datamigration/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/dataprotection/azure-resourcemanager-dataprotection/README.md b/sdk/dataprotection/azure-resourcemanager-dataprotection/README.md index 2bba0d00551e..274599bc9402 100644 --- a/sdk/dataprotection/azure-resourcemanager-dataprotection/README.md +++ b/sdk/dataprotection/azure-resourcemanager-dataprotection/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-dataprotection - 1.3.0 + 1.4.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -136,4 +136,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fdataprotection%2Fazure-resourcemanager-dataprotection%2FREADME.png) + diff --git a/sdk/dataprotection/azure-resourcemanager-dataprotection/pom.xml b/sdk/dataprotection/azure-resourcemanager-dataprotection/pom.xml index f40e3dad1d85..a5abf625ca53 100644 --- a/sdk/dataprotection/azure-resourcemanager-dataprotection/pom.xml +++ b/sdk/dataprotection/azure-resourcemanager-dataprotection/pom.xml @@ -51,34 +51,34 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/defendereasm/azure-resourcemanager-defendereasm/README.md b/sdk/defendereasm/azure-resourcemanager-defendereasm/README.md index 229eac73952b..7abe2426270f 100644 --- a/sdk/defendereasm/azure-resourcemanager-defendereasm/README.md +++ b/sdk/defendereasm/azure-resourcemanager-defendereasm/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-defendereasm - 1.0.0-beta.2 + 1.0.0-beta.3 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fdefendereasm%2Fazure-resourcemanager-defendereasm%2FREADME.png) + diff --git a/sdk/defendereasm/azure-resourcemanager-defendereasm/pom.xml b/sdk/defendereasm/azure-resourcemanager-defendereasm/pom.xml index 6368015a5b1f..dbbcc4a7980c 100644 --- a/sdk/defendereasm/azure-resourcemanager-defendereasm/pom.xml +++ b/sdk/defendereasm/azure-resourcemanager-defendereasm/pom.xml @@ -52,23 +52,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/delegatednetwork/azure-resourcemanager-delegatednetwork/README.md b/sdk/delegatednetwork/azure-resourcemanager-delegatednetwork/README.md index 57f08dd641aa..08b829ba8253 100644 --- a/sdk/delegatednetwork/azure-resourcemanager-delegatednetwork/README.md +++ b/sdk/delegatednetwork/azure-resourcemanager-delegatednetwork/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-delegatednetwork - 1.0.0-beta.3 + 1.0.0-beta.4 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fdelegatednetwork%2Fazure-resourcemanager-delegatednetwork%2FREADME.png) + diff --git a/sdk/delegatednetwork/azure-resourcemanager-delegatednetwork/pom.xml b/sdk/delegatednetwork/azure-resourcemanager-delegatednetwork/pom.xml index 8f36e55279de..ac35813b5c41 100644 --- a/sdk/delegatednetwork/azure-resourcemanager-delegatednetwork/pom.xml +++ b/sdk/delegatednetwork/azure-resourcemanager-delegatednetwork/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/deploymentmanager/azure-resourcemanager-deploymentmanager/README.md b/sdk/deploymentmanager/azure-resourcemanager-deploymentmanager/README.md index c17a39ca83b7..cc7a91207839 100644 --- a/sdk/deploymentmanager/azure-resourcemanager-deploymentmanager/README.md +++ b/sdk/deploymentmanager/azure-resourcemanager-deploymentmanager/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-deploymentmanager - 1.0.0-beta.2 + 1.0.0-beta.3 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/deploymentmanager/azure-resourcemanager-deploymentmanager/pom.xml b/sdk/deploymentmanager/azure-resourcemanager-deploymentmanager/pom.xml index ebd1ddc1aab0..2a617382b3af 100644 --- a/sdk/deploymentmanager/azure-resourcemanager-deploymentmanager/pom.xml +++ b/sdk/deploymentmanager/azure-resourcemanager-deploymentmanager/pom.xml @@ -45,23 +45,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/desktopvirtualization/azure-resourcemanager-desktopvirtualization/README.md b/sdk/desktopvirtualization/azure-resourcemanager-desktopvirtualization/README.md index 3117a8ce0042..e24bec575a81 100644 --- a/sdk/desktopvirtualization/azure-resourcemanager-desktopvirtualization/README.md +++ b/sdk/desktopvirtualization/azure-resourcemanager-desktopvirtualization/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-desktopvirtualization - 1.2.0 + 1.3.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fdesktopvirtualization%2Fazure-resourcemanager-desktopvirtualization%2FREADME.png) + diff --git a/sdk/desktopvirtualization/azure-resourcemanager-desktopvirtualization/pom.xml b/sdk/desktopvirtualization/azure-resourcemanager-desktopvirtualization/pom.xml index 30ba7a9212c1..7b7583686d3d 100644 --- a/sdk/desktopvirtualization/azure-resourcemanager-desktopvirtualization/pom.xml +++ b/sdk/desktopvirtualization/azure-resourcemanager-desktopvirtualization/pom.xml @@ -50,28 +50,28 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/devcenter/azure-developer-devcenter/CHANGELOG.md b/sdk/devcenter/azure-developer-devcenter/CHANGELOG.md index 4483040f09ac..e2d5071e9662 100644 --- a/sdk/devcenter/azure-developer-devcenter/CHANGELOG.md +++ b/sdk/devcenter/azure-developer-devcenter/CHANGELOG.md @@ -10,6 +10,17 @@ ### Other Changes + +## 1.0.7 (2025-02-28) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`. + + ## 1.0.6 (2024-12-04) ### Other Changes diff --git a/sdk/devcenter/azure-developer-devcenter/README.md b/sdk/devcenter/azure-developer-devcenter/README.md index e5524aa87e2c..05a410b7bb99 100644 --- a/sdk/devcenter/azure-developer-devcenter/README.md +++ b/sdk/devcenter/azure-developer-devcenter/README.md @@ -25,7 +25,7 @@ Various documentation is available to help you get started com.azure azure-developer-devcenter - 1.0.1 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/devcenter/azure-developer-devcenter/pom.xml b/sdk/devcenter/azure-developer-devcenter/pom.xml index 0f5d6003ca9f..ceba8c3668db 100644 --- a/sdk/devcenter/azure-developer-devcenter/pom.xml +++ b/sdk/devcenter/azure-developer-devcenter/pom.xml @@ -47,23 +47,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/devcenter/azure-resourcemanager-devcenter/README.md b/sdk/devcenter/azure-resourcemanager-devcenter/README.md index b0588cc8e0f3..41744c733b6f 100644 --- a/sdk/devcenter/azure-resourcemanager-devcenter/README.md +++ b/sdk/devcenter/azure-resourcemanager-devcenter/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-devcenter - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fdevcenter%2Fazure-resourcemanager-devcenter%2FREADME.png) + diff --git a/sdk/devcenter/azure-resourcemanager-devcenter/pom.xml b/sdk/devcenter/azure-resourcemanager-devcenter/pom.xml index 54291c84a875..3da7576414cd 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.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/devhub/azure-resourcemanager-devhub/README.md b/sdk/devhub/azure-resourcemanager-devhub/README.md index df4487dcd37f..655d36c253e3 100644 --- a/sdk/devhub/azure-resourcemanager-devhub/README.md +++ b/sdk/devhub/azure-resourcemanager-devhub/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-devhub - 1.0.0-beta.3 + 1.0.0-beta.4 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fdevhub%2Fazure-resourcemanager-devhub%2FREADME.png) + diff --git a/sdk/devhub/azure-resourcemanager-devhub/pom.xml b/sdk/devhub/azure-resourcemanager-devhub/pom.xml index 7ab1e2187bdd..4885117ae7bb 100644 --- a/sdk/devhub/azure-resourcemanager-devhub/pom.xml +++ b/sdk/devhub/azure-resourcemanager-devhub/pom.xml @@ -52,23 +52,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/deviceprovisioningservices/azure-resourcemanager-deviceprovisioningservices/README.md b/sdk/deviceprovisioningservices/azure-resourcemanager-deviceprovisioningservices/README.md index 04e688f4848d..a4a0f84bec24 100644 --- a/sdk/deviceprovisioningservices/azure-resourcemanager-deviceprovisioningservices/README.md +++ b/sdk/deviceprovisioningservices/azure-resourcemanager-deviceprovisioningservices/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-deviceprovisioningservices - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fdeviceprovisioningservices%2Fazure-resourcemanager-deviceprovisioningservices%2FREADME.png) + diff --git a/sdk/deviceprovisioningservices/azure-resourcemanager-deviceprovisioningservices/pom.xml b/sdk/deviceprovisioningservices/azure-resourcemanager-deviceprovisioningservices/pom.xml index 8e5a12c6e794..17bde417c605 100644 --- a/sdk/deviceprovisioningservices/azure-resourcemanager-deviceprovisioningservices/pom.xml +++ b/sdk/deviceprovisioningservices/azure-resourcemanager-deviceprovisioningservices/pom.xml @@ -52,29 +52,29 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/CHANGELOG.md b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/CHANGELOG.md index 20bc22df6448..9bcb65aa9218 100644 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/CHANGELOG.md +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.0.0-beta.3 (Unreleased) +## 1.1.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,13 @@ ### Other Changes +## 1.0.0 (2025-02-21) + +- Azure Resource Manager Device Registry client library for Java. This package contains Microsoft Azure SDK for Device Registry Management SDK. Microsoft.DeviceRegistry Resource Provider management API. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). + +### Other Changes +- Initial GA release of azure-resourcemanager-deviceregistry. + ## 1.0.0-beta.2 (2024-12-16) - Azure Resource Manager Device Registry client library for Java. This package contains Microsoft Azure SDK for Device Registry Management SDK. Microsoft.DeviceRegistry Resource Provider management API. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/README.md b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/README.md index de2739da6ed8..68869ea216a1 100644 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/README.md +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-deviceregistry - 1.0.0-beta.2 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -52,7 +52,7 @@ Azure subscription ID can be configured via `AZURE_SUBSCRIPTION_ID` environment Assuming the use of the `DefaultAzureCredential` credential class, the client can be authenticated using the following code: ```java -AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); +AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); @@ -60,7 +60,7 @@ DeviceRegistryManager manager = DeviceRegistryManager .authenticate(credential, profile); ``` -The sample code assumes global Azure. Please change `AzureEnvironment.AZURE` variable if otherwise. +The sample code assumes global Azure. Please change the `AzureCloud.AZURE_PUBLIC_CLOUD` variable if otherwise. See [Authentication][authenticate] for more options. @@ -100,5 +100,3 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [cg]: https://github.com/Azure/azure-sdk-for-java/blob/main/CONTRIBUTING.md [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ - -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fdeviceregistry%2Fazure-resourcemanager-deviceregistry%2FREADME.png) diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/SAMPLE.md b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/SAMPLE.md index 79279e2d46d7..c46a84377e44 100644 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/SAMPLE.md +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/SAMPLE.md @@ -24,24 +24,6 @@ - [Get](#billingcontainers_get) - [List](#billingcontainers_list) -## DiscoveredAssetEndpointProfiles - -- [CreateOrReplace](#discoveredassetendpointprofiles_createorreplace) -- [Delete](#discoveredassetendpointprofiles_delete) -- [GetByResourceGroup](#discoveredassetendpointprofiles_getbyresourcegroup) -- [List](#discoveredassetendpointprofiles_list) -- [ListByResourceGroup](#discoveredassetendpointprofiles_listbyresourcegroup) -- [Update](#discoveredassetendpointprofiles_update) - -## DiscoveredAssets - -- [CreateOrReplace](#discoveredassets_createorreplace) -- [Delete](#discoveredassets_delete) -- [GetByResourceGroup](#discoveredassets_getbyresourcegroup) -- [List](#discoveredassets_list) -- [ListByResourceGroup](#discoveredassets_listbyresourcegroup) -- [Update](#discoveredassets_update) - ## OperationStatus - [Get](#operationstatus_get) @@ -49,29 +31,6 @@ ## Operations - [List](#operations_list) - -## SchemaRegistries - -- [CreateOrReplace](#schemaregistries_createorreplace) -- [Delete](#schemaregistries_delete) -- [GetByResourceGroup](#schemaregistries_getbyresourcegroup) -- [List](#schemaregistries_list) -- [ListByResourceGroup](#schemaregistries_listbyresourcegroup) -- [Update](#schemaregistries_update) - -## SchemaVersions - -- [CreateOrReplace](#schemaversions_createorreplace) -- [Delete](#schemaversions_delete) -- [Get](#schemaversions_get) -- [ListBySchema](#schemaversions_listbyschema) - -## Schemas - -- [CreateOrReplace](#schemas_createorreplace) -- [Delete](#schemas_delete) -- [Get](#schemas_get) -- [ListBySchemaRegistry](#schemas_listbyschemaregistry) ### AssetEndpointProfiles_CreateOrReplace ```java @@ -87,7 +46,7 @@ import java.util.Map; */ public final class AssetEndpointProfilesCreateOrReplaceSamples { /* - * x-ms-original-file: 2024-09-01-preview/Create_AssetEndpointProfile_With_DiscoveredAepRef.json + * x-ms-original-file: 2024-11-01/Create_AssetEndpointProfile_With_DiscoveredAepRef.json */ /** * Sample code: Create_AssetEndpointProfile_With_DiscoveredAepRef. @@ -113,7 +72,7 @@ public final class AssetEndpointProfilesCreateOrReplaceSamples { } /* - * x-ms-original-file: 2024-09-01-preview/Create_AssetEndpointProfile.json + * x-ms-original-file: 2024-11-01/Create_AssetEndpointProfile.json */ /** * Sample code: Create_AssetEndpointProfile. @@ -159,7 +118,7 @@ public final class AssetEndpointProfilesCreateOrReplaceSamples { */ public final class AssetEndpointProfilesDeleteSamples { /* - * x-ms-original-file: 2024-09-01-preview/Delete_AssetEndpointProfile.json + * x-ms-original-file: 2024-11-01/Delete_AssetEndpointProfile.json */ /** * Sample code: Delete_AssetEndpointProfile. @@ -182,7 +141,7 @@ public final class AssetEndpointProfilesDeleteSamples { */ public final class AssetEndpointProfilesGetByResourceGroupSamples { /* - * x-ms-original-file: 2024-09-01-preview/Get_AssetEndpointProfile.json + * x-ms-original-file: 2024-11-01/Get_AssetEndpointProfile.json */ /** * Sample code: Get_AssetEndpointProfile. @@ -196,7 +155,7 @@ public final class AssetEndpointProfilesGetByResourceGroupSamples { } /* - * x-ms-original-file: 2024-09-01-preview/Get_AssetEndpointProfile_With_SyncStatus.json + * x-ms-original-file: 2024-11-01/Get_AssetEndpointProfile_With_SyncStatus.json */ /** * Sample code: Get_AssetEndpointProfile_With_SyncStatus. @@ -220,7 +179,7 @@ public final class AssetEndpointProfilesGetByResourceGroupSamples { */ public final class AssetEndpointProfilesListSamples { /* - * x-ms-original-file: 2024-09-01-preview/List_AssetEndpointProfiles_Subscription.json + * x-ms-original-file: 2024-11-01/List_AssetEndpointProfiles_Subscription.json */ /** * Sample code: List_AssetEndpointProfiles_Subscription. @@ -242,7 +201,7 @@ public final class AssetEndpointProfilesListSamples { */ public final class AssetEndpointProfilesListByResourceGroupSamples { /* - * x-ms-original-file: 2024-09-01-preview/List_AssetEndpointProfiles_ResourceGroup.json + * x-ms-original-file: 2024-11-01/List_AssetEndpointProfiles_ResourceGroup.json */ /** * Sample code: List_AssetEndpointProfiles_ResourceGroup. @@ -267,7 +226,7 @@ import com.azure.resourcemanager.deviceregistry.models.AssetEndpointProfileUpdat */ public final class AssetEndpointProfilesUpdateSamples { /* - * x-ms-original-file: 2024-09-01-preview/Update_AssetEndpointProfile.json + * x-ms-original-file: 2024-11-01/Update_AssetEndpointProfile.json */ /** * Sample code: Update_AssetEndpointProfile. @@ -309,7 +268,7 @@ import java.util.Map; */ public final class AssetsCreateOrReplaceSamples { /* - * x-ms-original-file: 2024-09-01-preview/Create_Asset_With_DiscoveredAssetRef.json + * x-ms-original-file: 2024-11-01/Create_Asset_With_DiscoveredAssetRef.json */ /** * Sample code: Create_Asset_With_DiscoveredAssetRefs. @@ -376,7 +335,7 @@ public final class AssetsCreateOrReplaceSamples { } /* - * x-ms-original-file: 2024-09-01-preview/Create_Asset_Without_ExternalAssetId.json + * x-ms-original-file: 2024-11-01/Create_Asset_Without_ExternalAssetId.json */ /** * Sample code: Create_Asset_Without_ExternalAssetId. @@ -441,7 +400,7 @@ public final class AssetsCreateOrReplaceSamples { } /* - * x-ms-original-file: 2024-09-01-preview/Create_Asset_With_ExternalAssetId.json + * x-ms-original-file: 2024-11-01/Create_Asset_With_ExternalAssetId.json */ /** * Sample code: Create_Asset_With_ExternalAssetId. @@ -507,7 +466,7 @@ public final class AssetsCreateOrReplaceSamples { } /* - * x-ms-original-file: 2024-09-01-preview/Create_Asset_Without_DisplayName.json + * x-ms-original-file: 2024-11-01/Create_Asset_Without_DisplayName.json */ /** * Sample code: Create_Asset_Without_DisplayName. @@ -593,7 +552,7 @@ public final class AssetsCreateOrReplaceSamples { */ public final class AssetsDeleteSamples { /* - * x-ms-original-file: 2024-09-01-preview/Delete_Asset.json + * x-ms-original-file: 2024-11-01/Delete_Asset.json */ /** * Sample code: Delete_Asset. @@ -614,7 +573,7 @@ public final class AssetsDeleteSamples { */ public final class AssetsGetByResourceGroupSamples { /* - * x-ms-original-file: 2024-09-01-preview/Get_Asset_With_SyncStatus.json + * x-ms-original-file: 2024-11-01/Get_Asset_With_SyncStatus.json */ /** * Sample code: Get_Asset_With_SyncStatus. @@ -627,7 +586,7 @@ public final class AssetsGetByResourceGroupSamples { } /* - * x-ms-original-file: 2024-09-01-preview/Get_Asset.json + * x-ms-original-file: 2024-11-01/Get_Asset.json */ /** * Sample code: Get_Asset. @@ -649,7 +608,7 @@ public final class AssetsGetByResourceGroupSamples { */ public final class AssetsListSamples { /* - * x-ms-original-file: 2024-09-01-preview/List_Assets_Subscription.json + * x-ms-original-file: 2024-11-01/List_Assets_Subscription.json */ /** * Sample code: List_Assets_Subscription. @@ -670,7 +629,7 @@ public final class AssetsListSamples { */ public final class AssetsListByResourceGroupSamples { /* - * x-ms-original-file: 2024-09-01-preview/List_Assets_ResourceGroup.json + * x-ms-original-file: 2024-11-01/List_Assets_ResourceGroup.json */ /** * Sample code: List_Assets_ResourceGroup. @@ -694,7 +653,7 @@ import com.azure.resourcemanager.deviceregistry.models.AssetUpdateProperties; */ public final class AssetsUpdateSamples { /* - * x-ms-original-file: 2024-09-01-preview/Update_Asset.json + * x-ms-original-file: 2024-11-01/Update_Asset.json */ /** * Sample code: Update_Asset. @@ -720,7 +679,7 @@ public final class AssetsUpdateSamples { */ public final class BillingContainersGetSamples { /* - * x-ms-original-file: 2024-09-01-preview/Get_BillingContainer.json + * x-ms-original-file: 2024-11-01/Get_BillingContainer.json */ /** * Sample code: Get_BillingContainer. @@ -741,7 +700,7 @@ public final class BillingContainersGetSamples { */ public final class BillingContainersListSamples { /* - * x-ms-original-file: 2024-09-01-preview/List_BillingContainers_Subscription.json + * x-ms-original-file: 2024-11-01/List_BillingContainers_Subscription.json */ /** * Sample code: List_BillingContainers_Subscription. @@ -755,436 +714,40 @@ public final class BillingContainersListSamples { } ``` -### DiscoveredAssetEndpointProfiles_CreateOrReplace - -```java -import com.azure.resourcemanager.deviceregistry.models.AuthenticationMethod; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetEndpointProfileProperties; -import com.azure.resourcemanager.deviceregistry.models.ExtendedLocation; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -/** - * Samples for DiscoveredAssetEndpointProfiles CreateOrReplace. - */ -public final class DiscoveredAssetEndpointProfilesCreateOrReplaceSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Create_DiscoveredAssetEndpointProfile.json - */ - /** - * Sample code: Create_DiscoveredAssetEndpointProfile. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void - createDiscoveredAssetEndpointProfile(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.discoveredAssetEndpointProfiles() - .define("my-discoveredassetendpointprofile") - .withRegion("West Europe") - .withExistingResourceGroup("myResourceGroup") - .withExtendedLocation(new ExtendedLocation().withType("CustomLocation") - .withName( - "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/myResourceGroup/providers/microsoft.extendedlocation/customlocations/location1")) - .withTags(mapOf("site", "building-1")) - .withProperties(new DiscoveredAssetEndpointProfileProperties() - .withTargetAddress("https://www.example.com/myTargetAddress") - .withAdditionalConfiguration("{\"foo\": \"bar\"}") - .withSupportedAuthenticationMethods(Arrays.asList(AuthenticationMethod.ANONYMOUS, - AuthenticationMethod.CERTIFICATE, AuthenticationMethod.USERNAME_PASSWORD)) - .withEndpointProfileType("myEndpointProfileType") - .withDiscoveryId("11111111-1111-1111-1111-111111111111") - .withVersion(73766L)) - .create(); - } - - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; - } -} -``` - -### DiscoveredAssetEndpointProfiles_Delete - -```java -/** - * Samples for DiscoveredAssetEndpointProfiles Delete. - */ -public final class DiscoveredAssetEndpointProfilesDeleteSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Delete_DiscoveredAssetEndpointProfile.json - */ - /** - * Sample code: Delete_DiscoveredAssetEndpointProfile. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void - deleteDiscoveredAssetEndpointProfile(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.discoveredAssetEndpointProfiles() - .delete("myResourceGroup", "my-discoveredassetendpointprofile", com.azure.core.util.Context.NONE); - } -} -``` - -### DiscoveredAssetEndpointProfiles_GetByResourceGroup - -```java -/** - * Samples for DiscoveredAssetEndpointProfiles GetByResourceGroup. - */ -public final class DiscoveredAssetEndpointProfilesGetByResourceGroupSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Get_DiscoveredAssetEndpointProfile.json - */ - /** - * Sample code: Get_DiscoveredAssetEndpointProfile. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void - getDiscoveredAssetEndpointProfile(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.discoveredAssetEndpointProfiles() - .getByResourceGroupWithResponse("myResourceGroup", "my-discoveredassetendpointprofile", - com.azure.core.util.Context.NONE); - } -} -``` - -### DiscoveredAssetEndpointProfiles_List - -```java -/** - * Samples for DiscoveredAssetEndpointProfiles List. - */ -public final class DiscoveredAssetEndpointProfilesListSamples { - /* - * x-ms-original-file: 2024-09-01-preview/List_DiscoveredAssetEndpointProfiles_Subscription.json - */ - /** - * Sample code: List_DiscoveredAssetEndpointProfiles_Subscription. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void listDiscoveredAssetEndpointProfilesSubscription( - com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.discoveredAssetEndpointProfiles().list(com.azure.core.util.Context.NONE); - } -} -``` - -### DiscoveredAssetEndpointProfiles_ListByResourceGroup - -```java -/** - * Samples for DiscoveredAssetEndpointProfiles ListByResourceGroup. - */ -public final class DiscoveredAssetEndpointProfilesListByResourceGroupSamples { - /* - * x-ms-original-file: 2024-09-01-preview/List_DiscoveredAssetEndpointProfiles_ResourceGroup.json - */ - /** - * Sample code: List_DiscoveredAssetEndpointProfiles_ResourceGroup. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void listDiscoveredAssetEndpointProfilesResourceGroup( - com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.discoveredAssetEndpointProfiles() - .listByResourceGroup("myResourceGroup", com.azure.core.util.Context.NONE); - } -} -``` - -### DiscoveredAssetEndpointProfiles_Update - -```java -import com.azure.resourcemanager.deviceregistry.models.AuthenticationMethod; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetEndpointProfile; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetEndpointProfileUpdateProperties; -import java.util.Arrays; - -/** - * Samples for DiscoveredAssetEndpointProfiles Update. - */ -public final class DiscoveredAssetEndpointProfilesUpdateSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Update_DiscoveredAssetEndpointProfile.json - */ - /** - * Sample code: Update_DiscoveredAssetEndpointProfile. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void - updateDiscoveredAssetEndpointProfile(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - DiscoveredAssetEndpointProfile resource = manager.discoveredAssetEndpointProfiles() - .getByResourceGroupWithResponse("myResourceGroup", "my-discoveredassetendpointprofile", - com.azure.core.util.Context.NONE) - .getValue(); - resource.update() - .withProperties(new DiscoveredAssetEndpointProfileUpdateProperties() - .withTargetAddress("https://www.example.com/myTargetAddress") - .withAdditionalConfiguration("{\"foo\": \"bar\"}") - .withSupportedAuthenticationMethods( - Arrays.asList(AuthenticationMethod.ANONYMOUS, AuthenticationMethod.CERTIFICATE)) - .withEndpointProfileType("myEndpointProfileType") - .withDiscoveryId("11111111-1111-1111-1111-111111111111") - .withVersion(73766L)) - .apply(); - } -} -``` - -### DiscoveredAssets_CreateOrReplace - -```java -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetProperties; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredDataPoint; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredDataset; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredEvent; -import com.azure.resourcemanager.deviceregistry.models.ExtendedLocation; -import com.azure.resourcemanager.deviceregistry.models.Topic; -import com.azure.resourcemanager.deviceregistry.models.TopicRetainType; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -/** - * Samples for DiscoveredAssets CreateOrReplace. - */ -public final class DiscoveredAssetsCreateOrReplaceSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Create_DiscoveredAsset.json - */ - /** - * Sample code: Create_DiscoveredAsset. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void createDiscoveredAsset(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.discoveredAssets() - .define("my-discoveredasset") - .withRegion("West Europe") - .withExistingResourceGroup("myResourceGroup") - .withExtendedLocation(new ExtendedLocation().withType("CustomLocation") - .withName( - "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/myResourceGroup/providers/microsoft.extendedlocation/customlocations/location1")) - .withTags(mapOf("site", "building-1")) - .withProperties(new DiscoveredAssetProperties().withAssetEndpointProfileRef("myAssetEndpointProfile") - .withDiscoveryId("11111111-1111-1111-1111-111111111111") - .withVersion(73766L) - .withManufacturer("Contoso") - .withManufacturerUri("https://www.contoso.com/manufacturerUri") - .withModel("ContosoModel") - .withProductCode("fakeTokenPlaceholder") - .withHardwareRevision("1.0") - .withSoftwareRevision("2.0") - .withDocumentationUri("https://www.example.com/manual") - .withSerialNumber("64-103816-519918-8") - .withDefaultDatasetsConfiguration( - "{\"publishingInterval\":10,\"samplingInterval\":15,\"queueSize\":20}") - .withDefaultEventsConfiguration("{\"publishingInterval\":10,\"samplingInterval\":15,\"queueSize\":20}") - .withDefaultTopic(new Topic().withPath("/path/defaultTopic").withRetain(TopicRetainType.KEEP)) - .withDatasets(Arrays.asList(new DiscoveredDataset().withName("dataset1") - .withDatasetConfiguration("{\"publishingInterval\":10,\"samplingInterval\":15,\"queueSize\":20}") - .withTopic(new Topic().withPath("/path/dataset1").withRetain(TopicRetainType.KEEP)) - .withDataPoints(Arrays.asList( - new DiscoveredDataPoint().withName("dataPoint1") - .withDataSource("nsu=http://microsoft.com/Opc/OpcPlc/;s=FastUInt1") - .withDataPointConfiguration( - "{\"publishingInterval\":8,\"samplingInterval\":8,\"queueSize\":4}"), - new DiscoveredDataPoint().withName("dataPoint2") - .withDataSource("nsu=http://microsoft.com/Opc/OpcPlc/;s=FastUInt2") - .withDataPointConfiguration( - "{\"publishingInterval\":4,\"samplingInterval\":4,\"queueSize\":7}"))))) - .withEvents(Arrays.asList( - new DiscoveredEvent().withName("event1") - .withEventNotifier("nsu=http://microsoft.com/Opc/OpcPlc/;s=FastUInt3") - .withEventConfiguration("{\"publishingInterval\":7,\"samplingInterval\":1,\"queueSize\":8}") - .withTopic(new Topic().withPath("/path/event1").withRetain(TopicRetainType.KEEP)), - new DiscoveredEvent().withName("event2") - .withEventNotifier("nsu=http://microsoft.com/Opc/OpcPlc/;s=FastUInt4") - .withEventConfiguration("{\"publishingInterval\":7,\"samplingInterval\":8,\"queueSize\":4}")))) - .create(); - } - - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; - } -} -``` - -### DiscoveredAssets_Delete - -```java -/** - * Samples for DiscoveredAssets Delete. - */ -public final class DiscoveredAssetsDeleteSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Delete_DiscoveredAsset.json - */ - /** - * Sample code: Delete_DiscoveredAsset. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void deleteDiscoveredAsset(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.discoveredAssets().delete("myResourceGroup", "my-discoveredasset", com.azure.core.util.Context.NONE); - } -} -``` - -### DiscoveredAssets_GetByResourceGroup - -```java -/** - * Samples for DiscoveredAssets GetByResourceGroup. - */ -public final class DiscoveredAssetsGetByResourceGroupSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Get_DiscoveredAsset.json - */ - /** - * Sample code: Get_DiscoveredAsset. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void getDiscoveredAsset(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.discoveredAssets() - .getByResourceGroupWithResponse("myResourceGroup", "my-discoveredasset", com.azure.core.util.Context.NONE); - } -} -``` - -### DiscoveredAssets_List - -```java -/** - * Samples for DiscoveredAssets List. - */ -public final class DiscoveredAssetsListSamples { - /* - * x-ms-original-file: 2024-09-01-preview/List_DiscoveredAssets_Subscription.json - */ - /** - * Sample code: List_DiscoveredAssets_Subscription. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void - listDiscoveredAssetsSubscription(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.discoveredAssets().list(com.azure.core.util.Context.NONE); - } -} -``` - -### DiscoveredAssets_ListByResourceGroup +### OperationStatus_Get ```java /** - * Samples for DiscoveredAssets ListByResourceGroup. + * Samples for OperationStatus Get. */ -public final class DiscoveredAssetsListByResourceGroupSamples { +public final class OperationStatusGetSamples { /* - * x-ms-original-file: 2024-09-01-preview/List_DiscoveredAssets_ResourceGroup.json + * x-ms-original-file: 2024-11-01/Get_OperationStatus.json */ /** - * Sample code: List_DiscoveredAssets_ResourceGroup. + * Sample code: Get_OperationStatus. * * @param manager Entry point to DeviceRegistryManager. */ - public static void - listDiscoveredAssetsResourceGroup(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.discoveredAssets().listByResourceGroup("myResourceGroup", com.azure.core.util.Context.NONE); + public static void getOperationStatus(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { + manager.operationStatus() + .getWithResponse("testLocation", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", com.azure.core.util.Context.NONE); } } ``` -### DiscoveredAssets_Update +### Operations_List ```java -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAsset; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetUpdateProperties; -import com.azure.resourcemanager.deviceregistry.models.Topic; -import com.azure.resourcemanager.deviceregistry.models.TopicRetainType; - /** - * Samples for DiscoveredAssets Update. + * Samples for Operations List. */ -public final class DiscoveredAssetsUpdateSamples { +public final class OperationsListSamples { /* - * x-ms-original-file: 2024-09-01-preview/Update_DiscoveredAsset.json + * x-ms-original-file: 2024-11-01/List_Operations.json */ /** - * Sample code: Update_DiscoveredAsset. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void updateDiscoveredAsset(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - DiscoveredAsset resource = manager.discoveredAssets() - .getByResourceGroupWithResponse("myResourceGroup", "my-discoveredasset", com.azure.core.util.Context.NONE) - .getValue(); - resource.update() - .withProperties( - new DiscoveredAssetUpdateProperties().withDocumentationUri("https://www.example.com/manual-2") - .withDefaultTopic(new Topic().withPath("/path/defaultTopic").withRetain(TopicRetainType.NEVER))) - .apply(); - } -} -``` - -### OperationStatus_Get - -```java -/** - * Samples for OperationStatus Get. - */ -public final class OperationStatusGetSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Get_OperationStatus.json - */ - /** - * Sample code: Get_OperationStatus. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void getOperationStatus(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.operationStatus() - .getWithResponse("testLocation", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", com.azure.core.util.Context.NONE); - } -} -``` - -### Operations_List - -```java -/** - * Samples for Operations List. - */ -public final class OperationsListSamples { - /* - * x-ms-original-file: 2024-09-01-preview/List_Operations.json - */ - /** - * Sample code: List_Operations. + * Sample code: List_Operations. * * @param manager Entry point to DeviceRegistryManager. */ @@ -1194,396 +757,3 @@ public final class OperationsListSamples { } ``` -### SchemaRegistries_CreateOrReplace - -```java -import com.azure.resourcemanager.deviceregistry.models.SchemaRegistryProperties; -import com.azure.resourcemanager.deviceregistry.models.SystemAssignedServiceIdentity; -import com.azure.resourcemanager.deviceregistry.models.SystemAssignedServiceIdentityType; -import java.util.HashMap; -import java.util.Map; - -/** - * Samples for SchemaRegistries CreateOrReplace. - */ -public final class SchemaRegistriesCreateOrReplaceSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Create_SchemaRegistry.json - */ - /** - * Sample code: Create_SchemaRegistry. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void createSchemaRegistry(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.schemaRegistries() - .define("my-schema-registry") - .withRegion("West Europe") - .withExistingResourceGroup("myResourceGroup") - .withTags(mapOf()) - .withProperties(new SchemaRegistryProperties().withNamespace("sr-namespace-001") - .withDisplayName("Schema Registry namespace 001") - .withDescription("This is a sample Schema Registry") - .withStorageAccountContainerUrl("my-blob-storage.blob.core.windows.net/my-container")) - .withIdentity(new SystemAssignedServiceIdentity().withType(SystemAssignedServiceIdentityType.NONE)) - .create(); - } - - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; - } -} -``` - -### SchemaRegistries_Delete - -```java -/** - * Samples for SchemaRegistries Delete. - */ -public final class SchemaRegistriesDeleteSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Delete_SchemaRegistry.json - */ - /** - * Sample code: Delete_SchemaRegistry. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void deleteSchemaRegistry(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.schemaRegistries().delete("myResourceGroup", "my-schema-registry", com.azure.core.util.Context.NONE); - } -} -``` - -### SchemaRegistries_GetByResourceGroup - -```java -/** - * Samples for SchemaRegistries GetByResourceGroup. - */ -public final class SchemaRegistriesGetByResourceGroupSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Get_SchemaRegistry.json - */ - /** - * Sample code: Get_SchemaRegistry. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void getSchemaRegistry(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.schemaRegistries() - .getByResourceGroupWithResponse("myResourceGroup", "my-schema-registry", com.azure.core.util.Context.NONE); - } -} -``` - -### SchemaRegistries_List - -```java -/** - * Samples for SchemaRegistries List. - */ -public final class SchemaRegistriesListSamples { - /* - * x-ms-original-file: 2024-09-01-preview/List_SchemaRegistries_Subscription.json - */ - /** - * Sample code: List_SchemaRegistries_Subscription. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void - listSchemaRegistriesSubscription(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.schemaRegistries().list(com.azure.core.util.Context.NONE); - } -} -``` - -### SchemaRegistries_ListByResourceGroup - -```java -/** - * Samples for SchemaRegistries ListByResourceGroup. - */ -public final class SchemaRegistriesListByResourceGroupSamples { - /* - * x-ms-original-file: 2024-09-01-preview/List_SchemaRegistries_ResourceGroup.json - */ - /** - * Sample code: List_SchemaRegistries_ResourceGroup. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void - listSchemaRegistriesResourceGroup(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.schemaRegistries().listByResourceGroup("myResourceGroup", com.azure.core.util.Context.NONE); - } -} -``` - -### SchemaRegistries_Update - -```java -import com.azure.resourcemanager.deviceregistry.models.SchemaRegistry; -import com.azure.resourcemanager.deviceregistry.models.SchemaRegistryUpdateProperties; -import java.util.HashMap; -import java.util.Map; - -/** - * Samples for SchemaRegistries Update. - */ -public final class SchemaRegistriesUpdateSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Update_SchemaRegistry.json - */ - /** - * Sample code: Update_SchemaRegistry. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void updateSchemaRegistry(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - SchemaRegistry resource = manager.schemaRegistries() - .getByResourceGroupWithResponse("myResourceGroup", "my-schema-registry", com.azure.core.util.Context.NONE) - .getValue(); - resource.update() - .withTags(mapOf()) - .withProperties(new SchemaRegistryUpdateProperties().withDisplayName("Schema Registry namespace 001") - .withDescription("This is a sample Schema Registry")) - .apply(); - } - - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; - } -} -``` - -### SchemaVersions_CreateOrReplace - -```java -import com.azure.resourcemanager.deviceregistry.models.SchemaVersionProperties; - -/** - * Samples for SchemaVersions CreateOrReplace. - */ -public final class SchemaVersionsCreateOrReplaceSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Create_SchemaVersion.json - */ - /** - * Sample code: Create_SchemaVersion. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void createSchemaVersion(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.schemaVersions() - .define("1") - .withExistingSchema("myResourceGroup", "my-schema-registry", "my-schema") - .withProperties(new SchemaVersionProperties().withDescription("Schema version 1") - .withSchemaContent( - "{\"$schema\": \"http://json-schema.org/draft-07/schema#\",\"type\": \"object\",\"properties\": {\"humidity\": {\"type\": \"string\"},\"temperature\": {\"type\":\"number\"}}}")) - .create(); - } -} -``` - -### SchemaVersions_Delete - -```java -/** - * Samples for SchemaVersions Delete. - */ -public final class SchemaVersionsDeleteSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Delete_SchemaVersion.json - */ - /** - * Sample code: Delete_SchemaVersion. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void deleteSchemaVersion(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.schemaVersions() - .deleteWithResponse("myResourceGroup", "my-schema-registry", "my-schema", "1", - com.azure.core.util.Context.NONE); - } -} -``` - -### SchemaVersions_Get - -```java -/** - * Samples for SchemaVersions Get. - */ -public final class SchemaVersionsGetSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Get_SchemaVersion.json - */ - /** - * Sample code: Get_SchemaVersion. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void getSchemaVersion(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.schemaVersions() - .getWithResponse("myResourceGroup", "my-schema-registry", "my-schema", "1", - com.azure.core.util.Context.NONE); - } -} -``` - -### SchemaVersions_ListBySchema - -```java -/** - * Samples for SchemaVersions ListBySchema. - */ -public final class SchemaVersionsListBySchemaSamples { - /* - * x-ms-original-file: 2024-09-01-preview/List_SchemaVersions_Schema.json - */ - /** - * Sample code: List_SchemaVersions_Schema. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void - listSchemaVersionsSchema(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.schemaVersions() - .listBySchema("myResourceGroup", "my-schema-registry", "my-schema", com.azure.core.util.Context.NONE); - } -} -``` - -### Schemas_CreateOrReplace - -```java -import com.azure.resourcemanager.deviceregistry.models.Format; -import com.azure.resourcemanager.deviceregistry.models.SchemaProperties; -import com.azure.resourcemanager.deviceregistry.models.SchemaType; -import java.util.HashMap; -import java.util.Map; - -/** - * Samples for Schemas CreateOrReplace. - */ -public final class SchemasCreateOrReplaceSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Create_Schema.json - */ - /** - * Sample code: Create_Schema. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void createSchema(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.schemas() - .define("my-schema") - .withExistingSchemaRegistry("myResourceGroup", "my-schema-registry") - .withProperties(new SchemaProperties().withDisplayName("My Schema") - .withDescription("This is a sample Schema") - .withFormat(Format.JSON_SCHEMA_DRAFT7) - .withSchemaType(SchemaType.MESSAGE_SCHEMA) - .withTags(mapOf("sampleKey", "fakeTokenPlaceholder"))) - .create(); - } - - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; - } -} -``` - -### Schemas_Delete - -```java -/** - * Samples for Schemas Delete. - */ -public final class SchemasDeleteSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Delete_Schema.json - */ - /** - * Sample code: Delete_Schema. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void deleteSchema(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.schemas() - .deleteWithResponse("myResourceGroup", "my-schema-registry", "my-schema", com.azure.core.util.Context.NONE); - } -} -``` - -### Schemas_Get - -```java -/** - * Samples for Schemas Get. - */ -public final class SchemasGetSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Get_Schema.json - */ - /** - * Sample code: Schemas_Get. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void schemasGet(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.schemas() - .getWithResponse("myResourceGroup", "my-schema-registry", "my-schema", com.azure.core.util.Context.NONE); - } -} -``` - -### Schemas_ListBySchemaRegistry - -```java -/** - * Samples for Schemas ListBySchemaRegistry. - */ -public final class SchemasListBySchemaRegistrySamples { - /* - * x-ms-original-file: 2024-09-01-preview/List_Schemas_SchemaRegistry.json - */ - /** - * Sample code: List_Schemas_SchemaRegistry. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void - listSchemasSchemaRegistry(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.schemas() - .listBySchemaRegistry("myResourceGroup", "my-schema-registry", com.azure.core.util.Context.NONE); - } -} -``` - diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/pom.xml b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/pom.xml index c3e523d00b74..13fe5f52c906 100644 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/pom.xml +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/pom.xml @@ -14,7 +14,7 @@ com.azure.resourcemanager azure-resourcemanager-deviceregistry - 1.0.0-beta.3 + 1.1.0-beta.1 jar Microsoft Azure SDK for Device Registry Management @@ -45,36 +45,41 @@ UTF-8 0 0 - true false com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-json - 1.3.0 + 1.5.0 + + + com.azure.resourcemanager + azure-resourcemanager-resources + 2.48.0 + test diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/DeviceRegistryManager.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/DeviceRegistryManager.java index 1f39c58fce5d..319b62bf03b4 100644 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/DeviceRegistryManager.java +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/DeviceRegistryManager.java @@ -22,33 +22,25 @@ import com.azure.core.http.policy.UserAgentPolicy; import com.azure.core.management.profile.AzureProfile; import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.deviceregistry.fluent.DeviceRegistryManagementClient; import com.azure.resourcemanager.deviceregistry.implementation.AssetEndpointProfilesImpl; import com.azure.resourcemanager.deviceregistry.implementation.AssetsImpl; import com.azure.resourcemanager.deviceregistry.implementation.BillingContainersImpl; import com.azure.resourcemanager.deviceregistry.implementation.DeviceRegistryManagementClientBuilder; -import com.azure.resourcemanager.deviceregistry.implementation.DiscoveredAssetEndpointProfilesImpl; -import com.azure.resourcemanager.deviceregistry.implementation.DiscoveredAssetsImpl; import com.azure.resourcemanager.deviceregistry.implementation.OperationStatusImpl; import com.azure.resourcemanager.deviceregistry.implementation.OperationsImpl; -import com.azure.resourcemanager.deviceregistry.implementation.SchemaRegistriesImpl; -import com.azure.resourcemanager.deviceregistry.implementation.SchemaVersionsImpl; -import com.azure.resourcemanager.deviceregistry.implementation.SchemasImpl; import com.azure.resourcemanager.deviceregistry.models.AssetEndpointProfiles; import com.azure.resourcemanager.deviceregistry.models.Assets; import com.azure.resourcemanager.deviceregistry.models.BillingContainers; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetEndpointProfiles; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssets; import com.azure.resourcemanager.deviceregistry.models.OperationStatus; import com.azure.resourcemanager.deviceregistry.models.Operations; -import com.azure.resourcemanager.deviceregistry.models.SchemaRegistries; -import com.azure.resourcemanager.deviceregistry.models.SchemaVersions; -import com.azure.resourcemanager.deviceregistry.models.Schemas; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; @@ -67,16 +59,6 @@ public final class DeviceRegistryManager { private BillingContainers billingContainers; - private DiscoveredAssets discoveredAssets; - - private DiscoveredAssetEndpointProfiles discoveredAssetEndpointProfiles; - - private SchemaRegistries schemaRegistries; - - private Schemas schemas; - - private SchemaVersions schemaVersions; - private final DeviceRegistryManagementClient clientObject; private DeviceRegistryManager(HttpPipeline httpPipeline, AzureProfile profile, Duration defaultPollInterval) { @@ -129,6 +111,9 @@ public static Configurable configure() { */ public static final class Configurable { private static final ClientLogger LOGGER = new ClientLogger(Configurable.class); + private static final String SDK_VERSION = "version"; + private static final Map PROPERTIES + = CoreUtils.getProperties("azure-resourcemanager-deviceregistry.properties"); private HttpClient httpClient; private HttpLogOptions httpLogOptions; @@ -236,12 +221,14 @@ public DeviceRegistryManager authenticate(TokenCredential credential, AzureProfi Objects.requireNonNull(credential, "'credential' cannot be null."); Objects.requireNonNull(profile, "'profile' cannot be null."); + String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); + StringBuilder userAgentBuilder = new StringBuilder(); userAgentBuilder.append("azsdk-java") .append("-") .append("com.azure.resourcemanager.deviceregistry") .append("/") - .append("1.0.0-beta.1"); + .append(clientVersion); if (!Configuration.getGlobalConfiguration().get("AZURE_TELEMETRY_DISABLED", false)) { userAgentBuilder.append(" (") .append(Configuration.getGlobalConfiguration().get("java.version")) @@ -347,67 +334,6 @@ public BillingContainers billingContainers() { return billingContainers; } - /** - * Gets the resource collection API of DiscoveredAssets. It manages DiscoveredAsset. - * - * @return Resource collection API of DiscoveredAssets. - */ - public DiscoveredAssets discoveredAssets() { - if (this.discoveredAssets == null) { - this.discoveredAssets = new DiscoveredAssetsImpl(clientObject.getDiscoveredAssets(), this); - } - return discoveredAssets; - } - - /** - * Gets the resource collection API of DiscoveredAssetEndpointProfiles. It manages DiscoveredAssetEndpointProfile. - * - * @return Resource collection API of DiscoveredAssetEndpointProfiles. - */ - public DiscoveredAssetEndpointProfiles discoveredAssetEndpointProfiles() { - if (this.discoveredAssetEndpointProfiles == null) { - this.discoveredAssetEndpointProfiles - = new DiscoveredAssetEndpointProfilesImpl(clientObject.getDiscoveredAssetEndpointProfiles(), this); - } - return discoveredAssetEndpointProfiles; - } - - /** - * Gets the resource collection API of SchemaRegistries. It manages SchemaRegistry. - * - * @return Resource collection API of SchemaRegistries. - */ - public SchemaRegistries schemaRegistries() { - if (this.schemaRegistries == null) { - this.schemaRegistries = new SchemaRegistriesImpl(clientObject.getSchemaRegistries(), this); - } - return schemaRegistries; - } - - /** - * Gets the resource collection API of Schemas. It manages Schema. - * - * @return Resource collection API of Schemas. - */ - public Schemas schemas() { - if (this.schemas == null) { - this.schemas = new SchemasImpl(clientObject.getSchemas(), this); - } - return schemas; - } - - /** - * Gets the resource collection API of SchemaVersions. It manages SchemaVersion. - * - * @return Resource collection API of SchemaVersions. - */ - public SchemaVersions schemaVersions() { - if (this.schemaVersions == null) { - this.schemaVersions = new SchemaVersionsImpl(clientObject.getSchemaVersions(), this); - } - return schemaVersions; - } - /** * Gets wrapped service client DeviceRegistryManagementClient providing direct access to the underlying * auto-generated API implementation, based on Azure REST API. diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/DeviceRegistryManagementClient.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/DeviceRegistryManagementClient.java index 6e64e3324c3a..95fa8f8ea5d2 100644 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/DeviceRegistryManagementClient.java +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/DeviceRegistryManagementClient.java @@ -80,39 +80,4 @@ public interface DeviceRegistryManagementClient { * @return the BillingContainersClient object. */ BillingContainersClient getBillingContainers(); - - /** - * Gets the DiscoveredAssetsClient object to access its operations. - * - * @return the DiscoveredAssetsClient object. - */ - DiscoveredAssetsClient getDiscoveredAssets(); - - /** - * Gets the DiscoveredAssetEndpointProfilesClient object to access its operations. - * - * @return the DiscoveredAssetEndpointProfilesClient object. - */ - DiscoveredAssetEndpointProfilesClient getDiscoveredAssetEndpointProfiles(); - - /** - * Gets the SchemaRegistriesClient object to access its operations. - * - * @return the SchemaRegistriesClient object. - */ - SchemaRegistriesClient getSchemaRegistries(); - - /** - * Gets the SchemasClient object to access its operations. - * - * @return the SchemasClient object. - */ - SchemasClient getSchemas(); - - /** - * Gets the SchemaVersionsClient object to access its operations. - * - * @return the SchemaVersionsClient object. - */ - SchemaVersionsClient getSchemaVersions(); } diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/DiscoveredAssetEndpointProfilesClient.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/DiscoveredAssetEndpointProfilesClient.java deleted file mode 100644 index 07d2ea342172..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/DiscoveredAssetEndpointProfilesClient.java +++ /dev/null @@ -1,281 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.fluent; - -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.Response; -import com.azure.core.management.polling.PollResult; -import com.azure.core.util.Context; -import com.azure.core.util.polling.SyncPoller; -import com.azure.resourcemanager.deviceregistry.fluent.models.DiscoveredAssetEndpointProfileInner; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetEndpointProfileUpdate; - -/** - * An instance of this class provides access to all the operations defined in DiscoveredAssetEndpointProfilesClient. - */ -public interface DiscoveredAssetEndpointProfilesClient { - /** - * Get a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DiscoveredAssetEndpointProfile along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - Response getByResourceGroupWithResponse(String resourceGroupName, - String discoveredAssetEndpointProfileName, Context context); - - /** - * Get a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DiscoveredAssetEndpointProfile. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - DiscoveredAssetEndpointProfileInner getByResourceGroup(String resourceGroupName, - String discoveredAssetEndpointProfileName); - - /** - * Create a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param resource Resource create parameters. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of discovered Asset Endpoint Profile definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, DiscoveredAssetEndpointProfileInner> - beginCreateOrReplace(String resourceGroupName, String discoveredAssetEndpointProfileName, - DiscoveredAssetEndpointProfileInner resource); - - /** - * Create a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param resource Resource create parameters. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of discovered Asset Endpoint Profile definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, DiscoveredAssetEndpointProfileInner> - beginCreateOrReplace(String resourceGroupName, String discoveredAssetEndpointProfileName, - DiscoveredAssetEndpointProfileInner resource, Context context); - - /** - * Create a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param resource Resource create parameters. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset Endpoint Profile definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - DiscoveredAssetEndpointProfileInner createOrReplace(String resourceGroupName, - String discoveredAssetEndpointProfileName, DiscoveredAssetEndpointProfileInner resource); - - /** - * Create a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param resource Resource create parameters. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset Endpoint Profile definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - DiscoveredAssetEndpointProfileInner createOrReplace(String resourceGroupName, - String discoveredAssetEndpointProfileName, DiscoveredAssetEndpointProfileInner resource, Context context); - - /** - * Update a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param properties The resource properties to be updated. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of discovered Asset Endpoint Profile definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, DiscoveredAssetEndpointProfileInner> beginUpdate( - String resourceGroupName, String discoveredAssetEndpointProfileName, - DiscoveredAssetEndpointProfileUpdate properties); - - /** - * Update a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param properties The resource properties to be updated. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of discovered Asset Endpoint Profile definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, DiscoveredAssetEndpointProfileInner> beginUpdate( - String resourceGroupName, String discoveredAssetEndpointProfileName, - DiscoveredAssetEndpointProfileUpdate properties, Context context); - - /** - * Update a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param properties The resource properties to be updated. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset Endpoint Profile definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - DiscoveredAssetEndpointProfileInner update(String resourceGroupName, String discoveredAssetEndpointProfileName, - DiscoveredAssetEndpointProfileUpdate properties); - - /** - * Update a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param properties The resource properties to be updated. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset Endpoint Profile definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - DiscoveredAssetEndpointProfileInner update(String resourceGroupName, String discoveredAssetEndpointProfileName, - DiscoveredAssetEndpointProfileUpdate properties, Context context); - - /** - * Delete a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of long-running operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, Void> beginDelete(String resourceGroupName, String discoveredAssetEndpointProfileName); - - /** - * Delete a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of long-running operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, Void> beginDelete(String resourceGroupName, String discoveredAssetEndpointProfileName, - Context context); - - /** - * Delete a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - void delete(String resourceGroupName, String discoveredAssetEndpointProfileName); - - /** - * Delete a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - void delete(String resourceGroupName, String discoveredAssetEndpointProfileName, Context context); - - /** - * List DiscoveredAssetEndpointProfile resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAssetEndpointProfile list operation as paginated response with - * {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable listByResourceGroup(String resourceGroupName); - - /** - * List DiscoveredAssetEndpointProfile resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAssetEndpointProfile list operation as paginated response with - * {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable listByResourceGroup(String resourceGroupName, Context context); - - /** - * List DiscoveredAssetEndpointProfile resources by subscription ID. - * - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAssetEndpointProfile list operation as paginated response with - * {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable list(); - - /** - * List DiscoveredAssetEndpointProfile resources by subscription ID. - * - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAssetEndpointProfile list operation as paginated response with - * {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable list(Context context); -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/DiscoveredAssetsClient.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/DiscoveredAssetsClient.java deleted file mode 100644 index 3362c3d1e02f..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/DiscoveredAssetsClient.java +++ /dev/null @@ -1,271 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.fluent; - -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.Response; -import com.azure.core.management.polling.PollResult; -import com.azure.core.util.Context; -import com.azure.core.util.polling.SyncPoller; -import com.azure.resourcemanager.deviceregistry.fluent.models.DiscoveredAssetInner; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetUpdate; - -/** - * An instance of this class provides access to all the operations defined in DiscoveredAssetsClient. - */ -public interface DiscoveredAssetsClient { - /** - * Get a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DiscoveredAsset along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - Response getByResourceGroupWithResponse(String resourceGroupName, String discoveredAssetName, - Context context); - - /** - * Get a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DiscoveredAsset. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - DiscoveredAssetInner getByResourceGroup(String resourceGroupName, String discoveredAssetName); - - /** - * Create a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param resource Resource create parameters. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of discovered Asset definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, DiscoveredAssetInner> beginCreateOrReplace(String resourceGroupName, - String discoveredAssetName, DiscoveredAssetInner resource); - - /** - * Create a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param resource Resource create parameters. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of discovered Asset definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, DiscoveredAssetInner> beginCreateOrReplace(String resourceGroupName, - String discoveredAssetName, DiscoveredAssetInner resource, Context context); - - /** - * Create a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param resource Resource create parameters. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - DiscoveredAssetInner createOrReplace(String resourceGroupName, String discoveredAssetName, - DiscoveredAssetInner resource); - - /** - * Create a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param resource Resource create parameters. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - DiscoveredAssetInner createOrReplace(String resourceGroupName, String discoveredAssetName, - DiscoveredAssetInner resource, Context context); - - /** - * Update a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param properties The resource properties to be updated. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of discovered Asset definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, DiscoveredAssetInner> beginUpdate(String resourceGroupName, - String discoveredAssetName, DiscoveredAssetUpdate properties); - - /** - * Update a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param properties The resource properties to be updated. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of discovered Asset definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, DiscoveredAssetInner> beginUpdate(String resourceGroupName, - String discoveredAssetName, DiscoveredAssetUpdate properties, Context context); - - /** - * Update a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param properties The resource properties to be updated. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - DiscoveredAssetInner update(String resourceGroupName, String discoveredAssetName, DiscoveredAssetUpdate properties); - - /** - * Update a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param properties The resource properties to be updated. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - DiscoveredAssetInner update(String resourceGroupName, String discoveredAssetName, DiscoveredAssetUpdate properties, - Context context); - - /** - * Delete a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of long-running operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, Void> beginDelete(String resourceGroupName, String discoveredAssetName); - - /** - * Delete a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of long-running operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, Void> beginDelete(String resourceGroupName, String discoveredAssetName, - Context context); - - /** - * Delete a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - void delete(String resourceGroupName, String discoveredAssetName); - - /** - * Delete a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - void delete(String resourceGroupName, String discoveredAssetName, Context context); - - /** - * List DiscoveredAsset resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAsset list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable listByResourceGroup(String resourceGroupName); - - /** - * List DiscoveredAsset resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAsset list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable listByResourceGroup(String resourceGroupName, Context context); - - /** - * List DiscoveredAsset resources by subscription ID. - * - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAsset list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable list(); - - /** - * List DiscoveredAsset resources by subscription ID. - * - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAsset list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable list(Context context); -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/SchemaRegistriesClient.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/SchemaRegistriesClient.java deleted file mode 100644 index cea69f6ae34f..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/SchemaRegistriesClient.java +++ /dev/null @@ -1,271 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.fluent; - -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.Response; -import com.azure.core.management.polling.PollResult; -import com.azure.core.util.Context; -import com.azure.core.util.polling.SyncPoller; -import com.azure.resourcemanager.deviceregistry.fluent.models.SchemaRegistryInner; -import com.azure.resourcemanager.deviceregistry.models.SchemaRegistryUpdate; - -/** - * An instance of this class provides access to all the operations defined in SchemaRegistriesClient. - */ -public interface SchemaRegistriesClient { - /** - * Get a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a SchemaRegistry along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - Response getByResourceGroupWithResponse(String resourceGroupName, String schemaRegistryName, - Context context); - - /** - * Get a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a SchemaRegistry. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - SchemaRegistryInner getByResourceGroup(String resourceGroupName, String schemaRegistryName); - - /** - * Create a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param resource Resource create parameters. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of schema registry definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, SchemaRegistryInner> beginCreateOrReplace(String resourceGroupName, - String schemaRegistryName, SchemaRegistryInner resource); - - /** - * Create a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param resource Resource create parameters. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of schema registry definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, SchemaRegistryInner> beginCreateOrReplace(String resourceGroupName, - String schemaRegistryName, SchemaRegistryInner resource, Context context); - - /** - * Create a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param resource Resource create parameters. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema registry definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - SchemaRegistryInner createOrReplace(String resourceGroupName, String schemaRegistryName, - SchemaRegistryInner resource); - - /** - * Create a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param resource Resource create parameters. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema registry definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - SchemaRegistryInner createOrReplace(String resourceGroupName, String schemaRegistryName, - SchemaRegistryInner resource, Context context); - - /** - * Update a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param properties The resource properties to be updated. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of schema registry definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, SchemaRegistryInner> beginUpdate(String resourceGroupName, - String schemaRegistryName, SchemaRegistryUpdate properties); - - /** - * Update a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param properties The resource properties to be updated. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of schema registry definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, SchemaRegistryInner> beginUpdate(String resourceGroupName, - String schemaRegistryName, SchemaRegistryUpdate properties, Context context); - - /** - * Update a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param properties The resource properties to be updated. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema registry definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - SchemaRegistryInner update(String resourceGroupName, String schemaRegistryName, SchemaRegistryUpdate properties); - - /** - * Update a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param properties The resource properties to be updated. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema registry definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - SchemaRegistryInner update(String resourceGroupName, String schemaRegistryName, SchemaRegistryUpdate properties, - Context context); - - /** - * Delete a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of long-running operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, Void> beginDelete(String resourceGroupName, String schemaRegistryName); - - /** - * Delete a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of long-running operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, Void> beginDelete(String resourceGroupName, String schemaRegistryName, - Context context); - - /** - * Delete a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - void delete(String resourceGroupName, String schemaRegistryName); - - /** - * Delete a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - void delete(String resourceGroupName, String schemaRegistryName, Context context); - - /** - * List SchemaRegistry resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaRegistry list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable listByResourceGroup(String resourceGroupName); - - /** - * List SchemaRegistry resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaRegistry list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable listByResourceGroup(String resourceGroupName, Context context); - - /** - * List SchemaRegistry resources by subscription ID. - * - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaRegistry list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable list(); - - /** - * List SchemaRegistry resources by subscription ID. - * - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaRegistry list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable list(Context context); -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/SchemaVersionsClient.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/SchemaVersionsClient.java deleted file mode 100644 index 5241f1271986..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/SchemaVersionsClient.java +++ /dev/null @@ -1,147 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.fluent; - -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.Response; -import com.azure.core.util.Context; -import com.azure.resourcemanager.deviceregistry.fluent.models.SchemaVersionInner; - -/** - * An instance of this class provides access to all the operations defined in SchemaVersionsClient. - */ -public interface SchemaVersionsClient { - /** - * Get a SchemaVersion. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param schemaVersionName Schema version name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a SchemaVersion along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - Response getWithResponse(String resourceGroupName, String schemaRegistryName, String schemaName, - String schemaVersionName, Context context); - - /** - * Get a SchemaVersion. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param schemaVersionName Schema version name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a SchemaVersion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - SchemaVersionInner get(String resourceGroupName, String schemaRegistryName, String schemaName, - String schemaVersionName); - - /** - * Create a SchemaVersion. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param schemaVersionName Schema version name parameter. - * @param resource Resource create parameters. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema version's definition along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - Response createOrReplaceWithResponse(String resourceGroupName, String schemaRegistryName, - String schemaName, String schemaVersionName, SchemaVersionInner resource, Context context); - - /** - * Create a SchemaVersion. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param schemaVersionName Schema version name parameter. - * @param resource Resource create parameters. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema version's definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - SchemaVersionInner createOrReplace(String resourceGroupName, String schemaRegistryName, String schemaName, - String schemaVersionName, SchemaVersionInner resource); - - /** - * Delete a SchemaVersion. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param schemaVersionName Schema version name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - Response deleteWithResponse(String resourceGroupName, String schemaRegistryName, String schemaName, - String schemaVersionName, Context context); - - /** - * Delete a SchemaVersion. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param schemaVersionName Schema version name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - void delete(String resourceGroupName, String schemaRegistryName, String schemaName, String schemaVersionName); - - /** - * List SchemaVersion resources by Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaVersion list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable listBySchema(String resourceGroupName, String schemaRegistryName, - String schemaName); - - /** - * List SchemaVersion resources by Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaVersion list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable listBySchema(String resourceGroupName, String schemaRegistryName, - String schemaName, Context context); -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/SchemasClient.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/SchemasClient.java deleted file mode 100644 index 4bd64cc2174e..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/SchemasClient.java +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.fluent; - -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.Response; -import com.azure.core.util.Context; -import com.azure.resourcemanager.deviceregistry.fluent.models.SchemaInner; - -/** - * An instance of this class provides access to all the operations defined in SchemasClient. - */ -public interface SchemasClient { - /** - * Get a Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Schema along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - Response getWithResponse(String resourceGroupName, String schemaRegistryName, String schemaName, - Context context); - - /** - * Get a Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Schema. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - SchemaInner get(String resourceGroupName, String schemaRegistryName, String schemaName); - - /** - * Create a Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param resource Resource create parameters. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema definition along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - Response createOrReplaceWithResponse(String resourceGroupName, String schemaRegistryName, - String schemaName, SchemaInner resource, Context context); - - /** - * Create a Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param resource Resource create parameters. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - SchemaInner createOrReplace(String resourceGroupName, String schemaRegistryName, String schemaName, - SchemaInner resource); - - /** - * Delete a Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - Response deleteWithResponse(String resourceGroupName, String schemaRegistryName, String schemaName, - Context context); - - /** - * Delete a Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - void delete(String resourceGroupName, String schemaRegistryName, String schemaName); - - /** - * List Schema resources by SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Schema list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable listBySchemaRegistry(String resourceGroupName, String schemaRegistryName); - - /** - * List Schema resources by SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Schema list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable listBySchemaRegistry(String resourceGroupName, String schemaRegistryName, - Context context); -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/models/DiscoveredAssetEndpointProfileInner.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/models/DiscoveredAssetEndpointProfileInner.java deleted file mode 100644 index 44ef009c51ad..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/models/DiscoveredAssetEndpointProfileInner.java +++ /dev/null @@ -1,234 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.fluent.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.management.Resource; -import com.azure.core.management.SystemData; -import com.azure.core.util.logging.ClientLogger; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetEndpointProfileProperties; -import com.azure.resourcemanager.deviceregistry.models.ExtendedLocation; -import java.io.IOException; -import java.util.Map; - -/** - * Discovered Asset Endpoint Profile definition. - */ -@Fluent -public final class DiscoveredAssetEndpointProfileInner extends Resource { - /* - * The resource-specific properties for this resource. - */ - private DiscoveredAssetEndpointProfileProperties properties; - - /* - * The extended location. - */ - private ExtendedLocation extendedLocation; - - /* - * Azure Resource Manager metadata containing createdBy and modifiedBy information. - */ - private SystemData systemData; - - /* - * The type of the resource. - */ - private String type; - - /* - * The name of the resource. - */ - private String name; - - /* - * Fully qualified resource Id for the resource. - */ - private String id; - - /** - * Creates an instance of DiscoveredAssetEndpointProfileInner class. - */ - public DiscoveredAssetEndpointProfileInner() { - } - - /** - * Get the properties property: The resource-specific properties for this resource. - * - * @return the properties value. - */ - public DiscoveredAssetEndpointProfileProperties properties() { - return this.properties; - } - - /** - * Set the properties property: The resource-specific properties for this resource. - * - * @param properties the properties value to set. - * @return the DiscoveredAssetEndpointProfileInner object itself. - */ - public DiscoveredAssetEndpointProfileInner withProperties(DiscoveredAssetEndpointProfileProperties properties) { - this.properties = properties; - return this; - } - - /** - * Get the extendedLocation property: The extended location. - * - * @return the extendedLocation value. - */ - public ExtendedLocation extendedLocation() { - return this.extendedLocation; - } - - /** - * Set the extendedLocation property: The extended location. - * - * @param extendedLocation the extendedLocation value to set. - * @return the DiscoveredAssetEndpointProfileInner object itself. - */ - public DiscoveredAssetEndpointProfileInner withExtendedLocation(ExtendedLocation extendedLocation) { - this.extendedLocation = extendedLocation; - return this; - } - - /** - * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. - * - * @return the systemData value. - */ - public SystemData systemData() { - return this.systemData; - } - - /** - * Get the type property: The type of the resource. - * - * @return the type value. - */ - @Override - public String type() { - return this.type; - } - - /** - * Get the name property: The name of the resource. - * - * @return the name value. - */ - @Override - public String name() { - return this.name; - } - - /** - * Get the id property: Fully qualified resource Id for the resource. - * - * @return the id value. - */ - @Override - public String id() { - return this.id; - } - - /** - * {@inheritDoc} - */ - @Override - public DiscoveredAssetEndpointProfileInner withLocation(String location) { - super.withLocation(location); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public DiscoveredAssetEndpointProfileInner withTags(Map tags) { - super.withTags(tags); - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (properties() != null) { - properties().validate(); - } - if (extendedLocation() == null) { - throw LOGGER.atError() - .log(new IllegalArgumentException( - "Missing required property extendedLocation in model DiscoveredAssetEndpointProfileInner")); - } else { - extendedLocation().validate(); - } - } - - private static final ClientLogger LOGGER = new ClientLogger(DiscoveredAssetEndpointProfileInner.class); - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("location", location()); - jsonWriter.writeMapField("tags", tags(), (writer, element) -> writer.writeString(element)); - jsonWriter.writeJsonField("extendedLocation", this.extendedLocation); - jsonWriter.writeJsonField("properties", this.properties); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of DiscoveredAssetEndpointProfileInner from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of DiscoveredAssetEndpointProfileInner 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 DiscoveredAssetEndpointProfileInner. - */ - public static DiscoveredAssetEndpointProfileInner fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - DiscoveredAssetEndpointProfileInner deserializedDiscoveredAssetEndpointProfileInner - = new DiscoveredAssetEndpointProfileInner(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("id".equals(fieldName)) { - deserializedDiscoveredAssetEndpointProfileInner.id = reader.getString(); - } else if ("name".equals(fieldName)) { - deserializedDiscoveredAssetEndpointProfileInner.name = reader.getString(); - } else if ("type".equals(fieldName)) { - deserializedDiscoveredAssetEndpointProfileInner.type = reader.getString(); - } else if ("location".equals(fieldName)) { - deserializedDiscoveredAssetEndpointProfileInner.withLocation(reader.getString()); - } else if ("tags".equals(fieldName)) { - Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedDiscoveredAssetEndpointProfileInner.withTags(tags); - } else if ("extendedLocation".equals(fieldName)) { - deserializedDiscoveredAssetEndpointProfileInner.extendedLocation - = ExtendedLocation.fromJson(reader); - } else if ("properties".equals(fieldName)) { - deserializedDiscoveredAssetEndpointProfileInner.properties - = DiscoveredAssetEndpointProfileProperties.fromJson(reader); - } else if ("systemData".equals(fieldName)) { - deserializedDiscoveredAssetEndpointProfileInner.systemData = SystemData.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedDiscoveredAssetEndpointProfileInner; - }); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/models/DiscoveredAssetInner.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/models/DiscoveredAssetInner.java deleted file mode 100644 index 366bebe17b20..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/models/DiscoveredAssetInner.java +++ /dev/null @@ -1,231 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.fluent.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.management.Resource; -import com.azure.core.management.SystemData; -import com.azure.core.util.logging.ClientLogger; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetProperties; -import com.azure.resourcemanager.deviceregistry.models.ExtendedLocation; -import java.io.IOException; -import java.util.Map; - -/** - * Discovered Asset definition. - */ -@Fluent -public final class DiscoveredAssetInner extends Resource { - /* - * The resource-specific properties for this resource. - */ - private DiscoveredAssetProperties properties; - - /* - * The extended location. - */ - private ExtendedLocation extendedLocation; - - /* - * Azure Resource Manager metadata containing createdBy and modifiedBy information. - */ - private SystemData systemData; - - /* - * The type of the resource. - */ - private String type; - - /* - * The name of the resource. - */ - private String name; - - /* - * Fully qualified resource Id for the resource. - */ - private String id; - - /** - * Creates an instance of DiscoveredAssetInner class. - */ - public DiscoveredAssetInner() { - } - - /** - * Get the properties property: The resource-specific properties for this resource. - * - * @return the properties value. - */ - public DiscoveredAssetProperties properties() { - return this.properties; - } - - /** - * Set the properties property: The resource-specific properties for this resource. - * - * @param properties the properties value to set. - * @return the DiscoveredAssetInner object itself. - */ - public DiscoveredAssetInner withProperties(DiscoveredAssetProperties properties) { - this.properties = properties; - return this; - } - - /** - * Get the extendedLocation property: The extended location. - * - * @return the extendedLocation value. - */ - public ExtendedLocation extendedLocation() { - return this.extendedLocation; - } - - /** - * Set the extendedLocation property: The extended location. - * - * @param extendedLocation the extendedLocation value to set. - * @return the DiscoveredAssetInner object itself. - */ - public DiscoveredAssetInner withExtendedLocation(ExtendedLocation extendedLocation) { - this.extendedLocation = extendedLocation; - return this; - } - - /** - * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. - * - * @return the systemData value. - */ - public SystemData systemData() { - return this.systemData; - } - - /** - * Get the type property: The type of the resource. - * - * @return the type value. - */ - @Override - public String type() { - return this.type; - } - - /** - * Get the name property: The name of the resource. - * - * @return the name value. - */ - @Override - public String name() { - return this.name; - } - - /** - * Get the id property: Fully qualified resource Id for the resource. - * - * @return the id value. - */ - @Override - public String id() { - return this.id; - } - - /** - * {@inheritDoc} - */ - @Override - public DiscoveredAssetInner withLocation(String location) { - super.withLocation(location); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public DiscoveredAssetInner withTags(Map tags) { - super.withTags(tags); - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (properties() != null) { - properties().validate(); - } - if (extendedLocation() == null) { - throw LOGGER.atError() - .log(new IllegalArgumentException( - "Missing required property extendedLocation in model DiscoveredAssetInner")); - } else { - extendedLocation().validate(); - } - } - - private static final ClientLogger LOGGER = new ClientLogger(DiscoveredAssetInner.class); - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("location", location()); - jsonWriter.writeMapField("tags", tags(), (writer, element) -> writer.writeString(element)); - jsonWriter.writeJsonField("extendedLocation", this.extendedLocation); - jsonWriter.writeJsonField("properties", this.properties); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of DiscoveredAssetInner from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of DiscoveredAssetInner 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 DiscoveredAssetInner. - */ - public static DiscoveredAssetInner fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - DiscoveredAssetInner deserializedDiscoveredAssetInner = new DiscoveredAssetInner(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("id".equals(fieldName)) { - deserializedDiscoveredAssetInner.id = reader.getString(); - } else if ("name".equals(fieldName)) { - deserializedDiscoveredAssetInner.name = reader.getString(); - } else if ("type".equals(fieldName)) { - deserializedDiscoveredAssetInner.type = reader.getString(); - } else if ("location".equals(fieldName)) { - deserializedDiscoveredAssetInner.withLocation(reader.getString()); - } else if ("tags".equals(fieldName)) { - Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedDiscoveredAssetInner.withTags(tags); - } else if ("extendedLocation".equals(fieldName)) { - deserializedDiscoveredAssetInner.extendedLocation = ExtendedLocation.fromJson(reader); - } else if ("properties".equals(fieldName)) { - deserializedDiscoveredAssetInner.properties = DiscoveredAssetProperties.fromJson(reader); - } else if ("systemData".equals(fieldName)) { - deserializedDiscoveredAssetInner.systemData = SystemData.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedDiscoveredAssetInner; - }); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/models/SchemaInner.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/models/SchemaInner.java deleted file mode 100644 index d11d9dbe8bd8..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/models/SchemaInner.java +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.fluent.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.management.ProxyResource; -import com.azure.core.management.SystemData; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.resourcemanager.deviceregistry.models.SchemaProperties; -import java.io.IOException; - -/** - * Schema definition. - */ -@Fluent -public final class SchemaInner extends ProxyResource { - /* - * The resource-specific properties for this resource. - */ - private SchemaProperties properties; - - /* - * Azure Resource Manager metadata containing createdBy and modifiedBy information. - */ - private SystemData systemData; - - /* - * The type of the resource. - */ - private String type; - - /* - * The name of the resource. - */ - private String name; - - /* - * Fully qualified resource Id for the resource. - */ - private String id; - - /** - * Creates an instance of SchemaInner class. - */ - public SchemaInner() { - } - - /** - * Get the properties property: The resource-specific properties for this resource. - * - * @return the properties value. - */ - public SchemaProperties properties() { - return this.properties; - } - - /** - * Set the properties property: The resource-specific properties for this resource. - * - * @param properties the properties value to set. - * @return the SchemaInner object itself. - */ - public SchemaInner withProperties(SchemaProperties properties) { - this.properties = properties; - return this; - } - - /** - * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. - * - * @return the systemData value. - */ - public SystemData systemData() { - return this.systemData; - } - - /** - * Get the type property: The type of the resource. - * - * @return the type value. - */ - @Override - public String type() { - return this.type; - } - - /** - * Get the name property: The name of the resource. - * - * @return the name value. - */ - @Override - public String name() { - return this.name; - } - - /** - * Get the id property: Fully qualified resource Id for the resource. - * - * @return the id value. - */ - @Override - public String id() { - return this.id; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (properties() != null) { - properties().validate(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeJsonField("properties", this.properties); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SchemaInner from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SchemaInner 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 SchemaInner. - */ - public static SchemaInner fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SchemaInner deserializedSchemaInner = new SchemaInner(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("id".equals(fieldName)) { - deserializedSchemaInner.id = reader.getString(); - } else if ("name".equals(fieldName)) { - deserializedSchemaInner.name = reader.getString(); - } else if ("type".equals(fieldName)) { - deserializedSchemaInner.type = reader.getString(); - } else if ("properties".equals(fieldName)) { - deserializedSchemaInner.properties = SchemaProperties.fromJson(reader); - } else if ("systemData".equals(fieldName)) { - deserializedSchemaInner.systemData = SystemData.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedSchemaInner; - }); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/models/SchemaRegistryInner.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/models/SchemaRegistryInner.java deleted file mode 100644 index 8abb1090dddc..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/models/SchemaRegistryInner.java +++ /dev/null @@ -1,224 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.fluent.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.management.Resource; -import com.azure.core.management.SystemData; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.resourcemanager.deviceregistry.models.SchemaRegistryProperties; -import com.azure.resourcemanager.deviceregistry.models.SystemAssignedServiceIdentity; -import java.io.IOException; -import java.util.Map; - -/** - * Schema registry definition. - */ -@Fluent -public final class SchemaRegistryInner extends Resource { - /* - * The resource-specific properties for this resource. - */ - private SchemaRegistryProperties properties; - - /* - * The managed service identities assigned to this resource. - */ - private SystemAssignedServiceIdentity identity; - - /* - * Azure Resource Manager metadata containing createdBy and modifiedBy information. - */ - private SystemData systemData; - - /* - * The type of the resource. - */ - private String type; - - /* - * The name of the resource. - */ - private String name; - - /* - * Fully qualified resource Id for the resource. - */ - private String id; - - /** - * Creates an instance of SchemaRegistryInner class. - */ - public SchemaRegistryInner() { - } - - /** - * Get the properties property: The resource-specific properties for this resource. - * - * @return the properties value. - */ - public SchemaRegistryProperties properties() { - return this.properties; - } - - /** - * Set the properties property: The resource-specific properties for this resource. - * - * @param properties the properties value to set. - * @return the SchemaRegistryInner object itself. - */ - public SchemaRegistryInner withProperties(SchemaRegistryProperties properties) { - this.properties = properties; - return this; - } - - /** - * Get the identity property: The managed service identities assigned to this resource. - * - * @return the identity value. - */ - public SystemAssignedServiceIdentity identity() { - return this.identity; - } - - /** - * Set the identity property: The managed service identities assigned to this resource. - * - * @param identity the identity value to set. - * @return the SchemaRegistryInner object itself. - */ - public SchemaRegistryInner withIdentity(SystemAssignedServiceIdentity identity) { - this.identity = identity; - return this; - } - - /** - * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. - * - * @return the systemData value. - */ - public SystemData systemData() { - return this.systemData; - } - - /** - * Get the type property: The type of the resource. - * - * @return the type value. - */ - @Override - public String type() { - return this.type; - } - - /** - * Get the name property: The name of the resource. - * - * @return the name value. - */ - @Override - public String name() { - return this.name; - } - - /** - * Get the id property: Fully qualified resource Id for the resource. - * - * @return the id value. - */ - @Override - public String id() { - return this.id; - } - - /** - * {@inheritDoc} - */ - @Override - public SchemaRegistryInner withLocation(String location) { - super.withLocation(location); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public SchemaRegistryInner withTags(Map tags) { - super.withTags(tags); - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (properties() != null) { - properties().validate(); - } - if (identity() != null) { - identity().validate(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("location", location()); - jsonWriter.writeMapField("tags", tags(), (writer, element) -> writer.writeString(element)); - jsonWriter.writeJsonField("properties", this.properties); - jsonWriter.writeJsonField("identity", this.identity); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SchemaRegistryInner from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SchemaRegistryInner 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 SchemaRegistryInner. - */ - public static SchemaRegistryInner fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SchemaRegistryInner deserializedSchemaRegistryInner = new SchemaRegistryInner(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("id".equals(fieldName)) { - deserializedSchemaRegistryInner.id = reader.getString(); - } else if ("name".equals(fieldName)) { - deserializedSchemaRegistryInner.name = reader.getString(); - } else if ("type".equals(fieldName)) { - deserializedSchemaRegistryInner.type = reader.getString(); - } else if ("location".equals(fieldName)) { - deserializedSchemaRegistryInner.withLocation(reader.getString()); - } else if ("tags".equals(fieldName)) { - Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedSchemaRegistryInner.withTags(tags); - } else if ("properties".equals(fieldName)) { - deserializedSchemaRegistryInner.properties = SchemaRegistryProperties.fromJson(reader); - } else if ("identity".equals(fieldName)) { - deserializedSchemaRegistryInner.identity = SystemAssignedServiceIdentity.fromJson(reader); - } else if ("systemData".equals(fieldName)) { - deserializedSchemaRegistryInner.systemData = SystemData.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedSchemaRegistryInner; - }); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/models/SchemaVersionInner.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/models/SchemaVersionInner.java deleted file mode 100644 index 9c234ec7f0c8..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/fluent/models/SchemaVersionInner.java +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.fluent.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.management.ProxyResource; -import com.azure.core.management.SystemData; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.resourcemanager.deviceregistry.models.SchemaVersionProperties; -import java.io.IOException; - -/** - * Schema version's definition. - */ -@Fluent -public final class SchemaVersionInner extends ProxyResource { - /* - * The resource-specific properties for this resource. - */ - private SchemaVersionProperties properties; - - /* - * Azure Resource Manager metadata containing createdBy and modifiedBy information. - */ - private SystemData systemData; - - /* - * The type of the resource. - */ - private String type; - - /* - * The name of the resource. - */ - private String name; - - /* - * Fully qualified resource Id for the resource. - */ - private String id; - - /** - * Creates an instance of SchemaVersionInner class. - */ - public SchemaVersionInner() { - } - - /** - * Get the properties property: The resource-specific properties for this resource. - * - * @return the properties value. - */ - public SchemaVersionProperties properties() { - return this.properties; - } - - /** - * Set the properties property: The resource-specific properties for this resource. - * - * @param properties the properties value to set. - * @return the SchemaVersionInner object itself. - */ - public SchemaVersionInner withProperties(SchemaVersionProperties properties) { - this.properties = properties; - return this; - } - - /** - * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. - * - * @return the systemData value. - */ - public SystemData systemData() { - return this.systemData; - } - - /** - * Get the type property: The type of the resource. - * - * @return the type value. - */ - @Override - public String type() { - return this.type; - } - - /** - * Get the name property: The name of the resource. - * - * @return the name value. - */ - @Override - public String name() { - return this.name; - } - - /** - * Get the id property: Fully qualified resource Id for the resource. - * - * @return the id value. - */ - @Override - public String id() { - return this.id; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (properties() != null) { - properties().validate(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeJsonField("properties", this.properties); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SchemaVersionInner from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SchemaVersionInner 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 SchemaVersionInner. - */ - public static SchemaVersionInner fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SchemaVersionInner deserializedSchemaVersionInner = new SchemaVersionInner(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("id".equals(fieldName)) { - deserializedSchemaVersionInner.id = reader.getString(); - } else if ("name".equals(fieldName)) { - deserializedSchemaVersionInner.name = reader.getString(); - } else if ("type".equals(fieldName)) { - deserializedSchemaVersionInner.type = reader.getString(); - } else if ("properties".equals(fieldName)) { - deserializedSchemaVersionInner.properties = SchemaVersionProperties.fromJson(reader); - } else if ("systemData".equals(fieldName)) { - deserializedSchemaVersionInner.systemData = SystemData.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedSchemaVersionInner; - }); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/DeviceRegistryManagementClientImpl.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/DeviceRegistryManagementClientImpl.java index 9aa7a4bce55a..34a6a5cf0f5d 100644 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/DeviceRegistryManagementClientImpl.java +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/DeviceRegistryManagementClientImpl.java @@ -27,13 +27,8 @@ import com.azure.resourcemanager.deviceregistry.fluent.AssetsClient; import com.azure.resourcemanager.deviceregistry.fluent.BillingContainersClient; import com.azure.resourcemanager.deviceregistry.fluent.DeviceRegistryManagementClient; -import com.azure.resourcemanager.deviceregistry.fluent.DiscoveredAssetEndpointProfilesClient; -import com.azure.resourcemanager.deviceregistry.fluent.DiscoveredAssetsClient; import com.azure.resourcemanager.deviceregistry.fluent.OperationStatusClient; import com.azure.resourcemanager.deviceregistry.fluent.OperationsClient; -import com.azure.resourcemanager.deviceregistry.fluent.SchemaRegistriesClient; -import com.azure.resourcemanager.deviceregistry.fluent.SchemaVersionsClient; -import com.azure.resourcemanager.deviceregistry.fluent.SchemasClient; import java.io.IOException; import java.lang.reflect.Type; import java.nio.ByteBuffer; @@ -202,76 +197,6 @@ public BillingContainersClient getBillingContainers() { return this.billingContainers; } - /** - * The DiscoveredAssetsClient object to access its operations. - */ - private final DiscoveredAssetsClient discoveredAssets; - - /** - * Gets the DiscoveredAssetsClient object to access its operations. - * - * @return the DiscoveredAssetsClient object. - */ - public DiscoveredAssetsClient getDiscoveredAssets() { - return this.discoveredAssets; - } - - /** - * The DiscoveredAssetEndpointProfilesClient object to access its operations. - */ - private final DiscoveredAssetEndpointProfilesClient discoveredAssetEndpointProfiles; - - /** - * Gets the DiscoveredAssetEndpointProfilesClient object to access its operations. - * - * @return the DiscoveredAssetEndpointProfilesClient object. - */ - public DiscoveredAssetEndpointProfilesClient getDiscoveredAssetEndpointProfiles() { - return this.discoveredAssetEndpointProfiles; - } - - /** - * The SchemaRegistriesClient object to access its operations. - */ - private final SchemaRegistriesClient schemaRegistries; - - /** - * Gets the SchemaRegistriesClient object to access its operations. - * - * @return the SchemaRegistriesClient object. - */ - public SchemaRegistriesClient getSchemaRegistries() { - return this.schemaRegistries; - } - - /** - * The SchemasClient object to access its operations. - */ - private final SchemasClient schemas; - - /** - * Gets the SchemasClient object to access its operations. - * - * @return the SchemasClient object. - */ - public SchemasClient getSchemas() { - return this.schemas; - } - - /** - * The SchemaVersionsClient object to access its operations. - */ - private final SchemaVersionsClient schemaVersions; - - /** - * Gets the SchemaVersionsClient object to access its operations. - * - * @return the SchemaVersionsClient object. - */ - public SchemaVersionsClient getSchemaVersions() { - return this.schemaVersions; - } - /** * Initializes an instance of DeviceRegistryManagementClient client. * @@ -289,17 +214,12 @@ public SchemaVersionsClient getSchemaVersions() { this.defaultPollInterval = defaultPollInterval; this.endpoint = endpoint; this.subscriptionId = subscriptionId; - this.apiVersion = "2024-09-01-preview"; + this.apiVersion = "2024-11-01"; this.operations = new OperationsClientImpl(this); this.operationStatus = new OperationStatusClientImpl(this); this.assets = new AssetsClientImpl(this); this.assetEndpointProfiles = new AssetEndpointProfilesClientImpl(this); this.billingContainers = new BillingContainersClientImpl(this); - this.discoveredAssets = new DiscoveredAssetsClientImpl(this); - this.discoveredAssetEndpointProfiles = new DiscoveredAssetEndpointProfilesClientImpl(this); - this.schemaRegistries = new SchemaRegistriesClientImpl(this); - this.schemas = new SchemasClientImpl(this); - this.schemaVersions = new SchemaVersionsClientImpl(this); } /** diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/DiscoveredAssetEndpointProfileImpl.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/DiscoveredAssetEndpointProfileImpl.java deleted file mode 100644 index 88b31fc2df85..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/DiscoveredAssetEndpointProfileImpl.java +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.implementation; - -import com.azure.core.management.Region; -import com.azure.core.management.SystemData; -import com.azure.core.util.Context; -import com.azure.resourcemanager.deviceregistry.fluent.models.DiscoveredAssetEndpointProfileInner; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetEndpointProfile; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetEndpointProfileProperties; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetEndpointProfileUpdate; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetEndpointProfileUpdateProperties; -import com.azure.resourcemanager.deviceregistry.models.ExtendedLocation; -import java.util.Collections; -import java.util.Map; - -public final class DiscoveredAssetEndpointProfileImpl implements DiscoveredAssetEndpointProfile, - DiscoveredAssetEndpointProfile.Definition, DiscoveredAssetEndpointProfile.Update { - private DiscoveredAssetEndpointProfileInner innerObject; - - private final com.azure.resourcemanager.deviceregistry.DeviceRegistryManager serviceManager; - - public String id() { - return this.innerModel().id(); - } - - public String name() { - return this.innerModel().name(); - } - - public String type() { - return this.innerModel().type(); - } - - public String location() { - return this.innerModel().location(); - } - - public Map tags() { - Map inner = this.innerModel().tags(); - if (inner != null) { - return Collections.unmodifiableMap(inner); - } else { - return Collections.emptyMap(); - } - } - - public DiscoveredAssetEndpointProfileProperties properties() { - return this.innerModel().properties(); - } - - public ExtendedLocation extendedLocation() { - return this.innerModel().extendedLocation(); - } - - public SystemData systemData() { - return this.innerModel().systemData(); - } - - public Region region() { - return Region.fromName(this.regionName()); - } - - public String regionName() { - return this.location(); - } - - public String resourceGroupName() { - return resourceGroupName; - } - - public DiscoveredAssetEndpointProfileInner innerModel() { - return this.innerObject; - } - - private com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager() { - return this.serviceManager; - } - - private String resourceGroupName; - - private String discoveredAssetEndpointProfileName; - - private DiscoveredAssetEndpointProfileUpdate updateProperties; - - public DiscoveredAssetEndpointProfileImpl withExistingResourceGroup(String resourceGroupName) { - this.resourceGroupName = resourceGroupName; - return this; - } - - public DiscoveredAssetEndpointProfile create() { - this.innerObject = serviceManager.serviceClient() - .getDiscoveredAssetEndpointProfiles() - .createOrReplace(resourceGroupName, discoveredAssetEndpointProfileName, this.innerModel(), Context.NONE); - return this; - } - - public DiscoveredAssetEndpointProfile create(Context context) { - this.innerObject = serviceManager.serviceClient() - .getDiscoveredAssetEndpointProfiles() - .createOrReplace(resourceGroupName, discoveredAssetEndpointProfileName, this.innerModel(), context); - return this; - } - - DiscoveredAssetEndpointProfileImpl(String name, - com.azure.resourcemanager.deviceregistry.DeviceRegistryManager serviceManager) { - this.innerObject = new DiscoveredAssetEndpointProfileInner(); - this.serviceManager = serviceManager; - this.discoveredAssetEndpointProfileName = name; - } - - public DiscoveredAssetEndpointProfileImpl update() { - this.updateProperties = new DiscoveredAssetEndpointProfileUpdate(); - return this; - } - - public DiscoveredAssetEndpointProfile apply() { - this.innerObject = serviceManager.serviceClient() - .getDiscoveredAssetEndpointProfiles() - .update(resourceGroupName, discoveredAssetEndpointProfileName, updateProperties, Context.NONE); - return this; - } - - public DiscoveredAssetEndpointProfile apply(Context context) { - this.innerObject = serviceManager.serviceClient() - .getDiscoveredAssetEndpointProfiles() - .update(resourceGroupName, discoveredAssetEndpointProfileName, updateProperties, context); - return this; - } - - DiscoveredAssetEndpointProfileImpl(DiscoveredAssetEndpointProfileInner innerObject, - com.azure.resourcemanager.deviceregistry.DeviceRegistryManager serviceManager) { - this.innerObject = innerObject; - this.serviceManager = serviceManager; - this.resourceGroupName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "resourceGroups"); - this.discoveredAssetEndpointProfileName - = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "discoveredAssetEndpointProfiles"); - } - - public DiscoveredAssetEndpointProfile refresh() { - this.innerObject = serviceManager.serviceClient() - .getDiscoveredAssetEndpointProfiles() - .getByResourceGroupWithResponse(resourceGroupName, discoveredAssetEndpointProfileName, Context.NONE) - .getValue(); - return this; - } - - public DiscoveredAssetEndpointProfile refresh(Context context) { - this.innerObject = serviceManager.serviceClient() - .getDiscoveredAssetEndpointProfiles() - .getByResourceGroupWithResponse(resourceGroupName, discoveredAssetEndpointProfileName, context) - .getValue(); - return this; - } - - public DiscoveredAssetEndpointProfileImpl withRegion(Region location) { - this.innerModel().withLocation(location.toString()); - return this; - } - - public DiscoveredAssetEndpointProfileImpl withRegion(String location) { - this.innerModel().withLocation(location); - return this; - } - - public DiscoveredAssetEndpointProfileImpl withExtendedLocation(ExtendedLocation extendedLocation) { - this.innerModel().withExtendedLocation(extendedLocation); - return this; - } - - public DiscoveredAssetEndpointProfileImpl withTags(Map tags) { - if (isInCreateMode()) { - this.innerModel().withTags(tags); - return this; - } else { - this.updateProperties.withTags(tags); - return this; - } - } - - public DiscoveredAssetEndpointProfileImpl withProperties(DiscoveredAssetEndpointProfileProperties properties) { - this.innerModel().withProperties(properties); - return this; - } - - public DiscoveredAssetEndpointProfileImpl - withProperties(DiscoveredAssetEndpointProfileUpdateProperties properties) { - this.updateProperties.withProperties(properties); - return this; - } - - private boolean isInCreateMode() { - return this.innerModel().id() == null; - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/DiscoveredAssetEndpointProfilesClientImpl.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/DiscoveredAssetEndpointProfilesClientImpl.java deleted file mode 100644 index 0075dd1ba2ab..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/DiscoveredAssetEndpointProfilesClientImpl.java +++ /dev/null @@ -1,1337 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.implementation; - -import com.azure.core.annotation.BodyParam; -import com.azure.core.annotation.Delete; -import com.azure.core.annotation.ExpectedResponses; -import com.azure.core.annotation.Get; -import com.azure.core.annotation.HeaderParam; -import com.azure.core.annotation.Headers; -import com.azure.core.annotation.Host; -import com.azure.core.annotation.HostParam; -import com.azure.core.annotation.Patch; -import com.azure.core.annotation.PathParam; -import com.azure.core.annotation.Put; -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.PagedFlux; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.PagedResponse; -import com.azure.core.http.rest.PagedResponseBase; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.RestProxy; -import com.azure.core.management.exception.ManagementException; -import com.azure.core.management.polling.PollResult; -import com.azure.core.util.Context; -import com.azure.core.util.FluxUtil; -import com.azure.core.util.polling.PollerFlux; -import com.azure.core.util.polling.SyncPoller; -import com.azure.resourcemanager.deviceregistry.fluent.DiscoveredAssetEndpointProfilesClient; -import com.azure.resourcemanager.deviceregistry.fluent.models.DiscoveredAssetEndpointProfileInner; -import com.azure.resourcemanager.deviceregistry.implementation.models.DiscoveredAssetEndpointProfileListResult; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetEndpointProfileUpdate; -import java.nio.ByteBuffer; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -/** - * An instance of this class provides access to all the operations defined in DiscoveredAssetEndpointProfilesClient. - */ -public final class DiscoveredAssetEndpointProfilesClientImpl implements DiscoveredAssetEndpointProfilesClient { - /** - * The proxy service used to perform REST calls. - */ - private final DiscoveredAssetEndpointProfilesService service; - - /** - * The service client containing this operation class. - */ - private final DeviceRegistryManagementClientImpl client; - - /** - * Initializes an instance of DiscoveredAssetEndpointProfilesClientImpl. - * - * @param client the instance of the service client containing this operation class. - */ - DiscoveredAssetEndpointProfilesClientImpl(DeviceRegistryManagementClientImpl client) { - this.service = RestProxy.create(DiscoveredAssetEndpointProfilesService.class, client.getHttpPipeline(), - client.getSerializerAdapter()); - this.client = client; - } - - /** - * The interface defining all the services for DeviceRegistryManagementClientDiscoveredAssetEndpointProfiles to be - * used by the proxy service to perform REST calls. - */ - @Host("{endpoint}") - @ServiceInterface(name = "DeviceRegistryManage") - public interface DiscoveredAssetEndpointProfilesService { - @Headers({ "Content-Type: application/json" }) - @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DeviceRegistry/discoveredAssetEndpointProfiles/{discoveredAssetEndpointProfileName}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> getByResourceGroup(@HostParam("endpoint") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, - @PathParam("discoveredAssetEndpointProfileName") String discoveredAssetEndpointProfileName, - @HeaderParam("Accept") String accept, Context context); - - @Put("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DeviceRegistry/discoveredAssetEndpointProfiles/{discoveredAssetEndpointProfileName}") - @ExpectedResponses({ 200, 201 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono>> createOrReplace(@HostParam("endpoint") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, - @PathParam("discoveredAssetEndpointProfileName") String discoveredAssetEndpointProfileName, - @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, - @BodyParam("application/json") DiscoveredAssetEndpointProfileInner resource, Context context); - - @Patch("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DeviceRegistry/discoveredAssetEndpointProfiles/{discoveredAssetEndpointProfileName}") - @ExpectedResponses({ 200, 202 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono>> update(@HostParam("endpoint") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, - @PathParam("discoveredAssetEndpointProfileName") String discoveredAssetEndpointProfileName, - @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, - @BodyParam("application/json") DiscoveredAssetEndpointProfileUpdate properties, Context context); - - @Headers({ "Content-Type: application/json" }) - @Delete("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DeviceRegistry/discoveredAssetEndpointProfiles/{discoveredAssetEndpointProfileName}") - @ExpectedResponses({ 202, 204 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono>> delete(@HostParam("endpoint") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, - @PathParam("discoveredAssetEndpointProfileName") String discoveredAssetEndpointProfileName, - @HeaderParam("Accept") String accept, Context context); - - @Headers({ "Content-Type: application/json" }) - @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DeviceRegistry/discoveredAssetEndpointProfiles") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> listByResourceGroup( - @HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, - @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, @HeaderParam("Accept") String accept, - Context context); - - @Headers({ "Content-Type: application/json" }) - @Get("/subscriptions/{subscriptionId}/providers/Microsoft.DeviceRegistry/discoveredAssetEndpointProfiles") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> list(@HostParam("endpoint") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @HeaderParam("Accept") String accept, Context context); - - @Headers({ "Content-Type: application/json" }) - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> listByResourceGroupNext( - @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, - @HeaderParam("Accept") String accept, Context context); - - @Headers({ "Content-Type: application/json" }) - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> listBySubscriptionNext( - @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, - @HeaderParam("Accept") String accept, Context context); - } - - /** - * Get a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DiscoveredAssetEndpointProfile along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> - getByResourceGroupWithResponseAsync(String resourceGroupName, String discoveredAssetEndpointProfileName) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (discoveredAssetEndpointProfileName == null) { - return Mono.error(new IllegalArgumentException( - "Parameter discoveredAssetEndpointProfileName is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.getByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, discoveredAssetEndpointProfileName, accept, - context)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Get a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DiscoveredAssetEndpointProfile along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> getByResourceGroupWithResponseAsync( - String resourceGroupName, String discoveredAssetEndpointProfileName, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (discoveredAssetEndpointProfileName == null) { - return Mono.error(new IllegalArgumentException( - "Parameter discoveredAssetEndpointProfileName is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.getByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, discoveredAssetEndpointProfileName, accept, context); - } - - /** - * Get a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DiscoveredAssetEndpointProfile on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono getByResourceGroupAsync(String resourceGroupName, - String discoveredAssetEndpointProfileName) { - return getByResourceGroupWithResponseAsync(resourceGroupName, discoveredAssetEndpointProfileName) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Get a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DiscoveredAssetEndpointProfile along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getByResourceGroupWithResponse(String resourceGroupName, - String discoveredAssetEndpointProfileName, Context context) { - return getByResourceGroupWithResponseAsync(resourceGroupName, discoveredAssetEndpointProfileName, context) - .block(); - } - - /** - * Get a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DiscoveredAssetEndpointProfile. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public DiscoveredAssetEndpointProfileInner getByResourceGroup(String resourceGroupName, - String discoveredAssetEndpointProfileName) { - return getByResourceGroupWithResponse(resourceGroupName, discoveredAssetEndpointProfileName, Context.NONE) - .getValue(); - } - - /** - * Create a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param resource Resource create parameters. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset Endpoint Profile definition along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> createOrReplaceWithResponseAsync(String resourceGroupName, - String discoveredAssetEndpointProfileName, DiscoveredAssetEndpointProfileInner resource) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (discoveredAssetEndpointProfileName == null) { - return Mono.error(new IllegalArgumentException( - "Parameter discoveredAssetEndpointProfileName is required and cannot be null.")); - } - if (resource == null) { - return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); - } else { - resource.validate(); - } - final String contentType = "application/json"; - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.createOrReplace(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, discoveredAssetEndpointProfileName, contentType, - accept, resource, context)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Create a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param resource Resource create parameters. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset Endpoint Profile definition along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> createOrReplaceWithResponseAsync(String resourceGroupName, - String discoveredAssetEndpointProfileName, DiscoveredAssetEndpointProfileInner resource, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (discoveredAssetEndpointProfileName == null) { - return Mono.error(new IllegalArgumentException( - "Parameter discoveredAssetEndpointProfileName is required and cannot be null.")); - } - if (resource == null) { - return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); - } else { - resource.validate(); - } - final String contentType = "application/json"; - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.createOrReplace(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, discoveredAssetEndpointProfileName, contentType, accept, - resource, context); - } - - /** - * Create a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param resource Resource create parameters. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of discovered Asset Endpoint Profile definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, DiscoveredAssetEndpointProfileInner> - beginCreateOrReplaceAsync(String resourceGroupName, String discoveredAssetEndpointProfileName, - DiscoveredAssetEndpointProfileInner resource) { - Mono>> mono - = createOrReplaceWithResponseAsync(resourceGroupName, discoveredAssetEndpointProfileName, resource); - return this.client.getLroResult(mono, - this.client.getHttpPipeline(), DiscoveredAssetEndpointProfileInner.class, - DiscoveredAssetEndpointProfileInner.class, this.client.getContext()); - } - - /** - * Create a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param resource Resource create parameters. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of discovered Asset Endpoint Profile definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, DiscoveredAssetEndpointProfileInner> - beginCreateOrReplaceAsync(String resourceGroupName, String discoveredAssetEndpointProfileName, - DiscoveredAssetEndpointProfileInner resource, Context context) { - context = this.client.mergeContext(context); - Mono>> mono = createOrReplaceWithResponseAsync(resourceGroupName, - discoveredAssetEndpointProfileName, resource, context); - return this.client.getLroResult(mono, - this.client.getHttpPipeline(), DiscoveredAssetEndpointProfileInner.class, - DiscoveredAssetEndpointProfileInner.class, context); - } - - /** - * Create a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param resource Resource create parameters. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of discovered Asset Endpoint Profile definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, DiscoveredAssetEndpointProfileInner> - beginCreateOrReplace(String resourceGroupName, String discoveredAssetEndpointProfileName, - DiscoveredAssetEndpointProfileInner resource) { - return this.beginCreateOrReplaceAsync(resourceGroupName, discoveredAssetEndpointProfileName, resource) - .getSyncPoller(); - } - - /** - * Create a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param resource Resource create parameters. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of discovered Asset Endpoint Profile definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, DiscoveredAssetEndpointProfileInner> - beginCreateOrReplace(String resourceGroupName, String discoveredAssetEndpointProfileName, - DiscoveredAssetEndpointProfileInner resource, Context context) { - return this.beginCreateOrReplaceAsync(resourceGroupName, discoveredAssetEndpointProfileName, resource, context) - .getSyncPoller(); - } - - /** - * Create a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param resource Resource create parameters. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset Endpoint Profile definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono createOrReplaceAsync(String resourceGroupName, - String discoveredAssetEndpointProfileName, DiscoveredAssetEndpointProfileInner resource) { - return beginCreateOrReplaceAsync(resourceGroupName, discoveredAssetEndpointProfileName, resource).last() - .flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Create a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param resource Resource create parameters. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset Endpoint Profile definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono createOrReplaceAsync(String resourceGroupName, - String discoveredAssetEndpointProfileName, DiscoveredAssetEndpointProfileInner resource, Context context) { - return beginCreateOrReplaceAsync(resourceGroupName, discoveredAssetEndpointProfileName, resource, context) - .last() - .flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Create a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param resource Resource create parameters. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset Endpoint Profile definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public DiscoveredAssetEndpointProfileInner createOrReplace(String resourceGroupName, - String discoveredAssetEndpointProfileName, DiscoveredAssetEndpointProfileInner resource) { - return createOrReplaceAsync(resourceGroupName, discoveredAssetEndpointProfileName, resource).block(); - } - - /** - * Create a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param resource Resource create parameters. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset Endpoint Profile definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public DiscoveredAssetEndpointProfileInner createOrReplace(String resourceGroupName, - String discoveredAssetEndpointProfileName, DiscoveredAssetEndpointProfileInner resource, Context context) { - return createOrReplaceAsync(resourceGroupName, discoveredAssetEndpointProfileName, resource, context).block(); - } - - /** - * Update a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param properties The resource properties to be updated. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset Endpoint Profile definition along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> updateWithResponseAsync(String resourceGroupName, - String discoveredAssetEndpointProfileName, DiscoveredAssetEndpointProfileUpdate properties) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (discoveredAssetEndpointProfileName == null) { - return Mono.error(new IllegalArgumentException( - "Parameter discoveredAssetEndpointProfileName is required and cannot be null.")); - } - if (properties == null) { - return Mono.error(new IllegalArgumentException("Parameter properties is required and cannot be null.")); - } else { - properties.validate(); - } - final String contentType = "application/json"; - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.update(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, discoveredAssetEndpointProfileName, contentType, - accept, properties, context)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Update a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param properties The resource properties to be updated. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset Endpoint Profile definition along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> updateWithResponseAsync(String resourceGroupName, - String discoveredAssetEndpointProfileName, DiscoveredAssetEndpointProfileUpdate properties, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (discoveredAssetEndpointProfileName == null) { - return Mono.error(new IllegalArgumentException( - "Parameter discoveredAssetEndpointProfileName is required and cannot be null.")); - } - if (properties == null) { - return Mono.error(new IllegalArgumentException("Parameter properties is required and cannot be null.")); - } else { - properties.validate(); - } - final String contentType = "application/json"; - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.update(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), - resourceGroupName, discoveredAssetEndpointProfileName, contentType, accept, properties, context); - } - - /** - * Update a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param properties The resource properties to be updated. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of discovered Asset Endpoint Profile definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, DiscoveredAssetEndpointProfileInner> - beginUpdateAsync(String resourceGroupName, String discoveredAssetEndpointProfileName, - DiscoveredAssetEndpointProfileUpdate properties) { - Mono>> mono - = updateWithResponseAsync(resourceGroupName, discoveredAssetEndpointProfileName, properties); - return this.client.getLroResult(mono, - this.client.getHttpPipeline(), DiscoveredAssetEndpointProfileInner.class, - DiscoveredAssetEndpointProfileInner.class, this.client.getContext()); - } - - /** - * Update a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param properties The resource properties to be updated. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of discovered Asset Endpoint Profile definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, DiscoveredAssetEndpointProfileInner> - beginUpdateAsync(String resourceGroupName, String discoveredAssetEndpointProfileName, - DiscoveredAssetEndpointProfileUpdate properties, Context context) { - context = this.client.mergeContext(context); - Mono>> mono - = updateWithResponseAsync(resourceGroupName, discoveredAssetEndpointProfileName, properties, context); - return this.client.getLroResult(mono, - this.client.getHttpPipeline(), DiscoveredAssetEndpointProfileInner.class, - DiscoveredAssetEndpointProfileInner.class, context); - } - - /** - * Update a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param properties The resource properties to be updated. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of discovered Asset Endpoint Profile definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, DiscoveredAssetEndpointProfileInner> beginUpdate( - String resourceGroupName, String discoveredAssetEndpointProfileName, - DiscoveredAssetEndpointProfileUpdate properties) { - return this.beginUpdateAsync(resourceGroupName, discoveredAssetEndpointProfileName, properties).getSyncPoller(); - } - - /** - * Update a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param properties The resource properties to be updated. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of discovered Asset Endpoint Profile definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, DiscoveredAssetEndpointProfileInner> beginUpdate( - String resourceGroupName, String discoveredAssetEndpointProfileName, - DiscoveredAssetEndpointProfileUpdate properties, Context context) { - return this.beginUpdateAsync(resourceGroupName, discoveredAssetEndpointProfileName, properties, context) - .getSyncPoller(); - } - - /** - * Update a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param properties The resource properties to be updated. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset Endpoint Profile definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono updateAsync(String resourceGroupName, - String discoveredAssetEndpointProfileName, DiscoveredAssetEndpointProfileUpdate properties) { - return beginUpdateAsync(resourceGroupName, discoveredAssetEndpointProfileName, properties).last() - .flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Update a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param properties The resource properties to be updated. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset Endpoint Profile definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono updateAsync(String resourceGroupName, - String discoveredAssetEndpointProfileName, DiscoveredAssetEndpointProfileUpdate properties, Context context) { - return beginUpdateAsync(resourceGroupName, discoveredAssetEndpointProfileName, properties, context).last() - .flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Update a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param properties The resource properties to be updated. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset Endpoint Profile definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public DiscoveredAssetEndpointProfileInner update(String resourceGroupName, - String discoveredAssetEndpointProfileName, DiscoveredAssetEndpointProfileUpdate properties) { - return updateAsync(resourceGroupName, discoveredAssetEndpointProfileName, properties).block(); - } - - /** - * Update a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param properties The resource properties to be updated. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset Endpoint Profile definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public DiscoveredAssetEndpointProfileInner update(String resourceGroupName, - String discoveredAssetEndpointProfileName, DiscoveredAssetEndpointProfileUpdate properties, Context context) { - return updateAsync(resourceGroupName, discoveredAssetEndpointProfileName, properties, context).block(); - } - - /** - * Delete a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> deleteWithResponseAsync(String resourceGroupName, - String discoveredAssetEndpointProfileName) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (discoveredAssetEndpointProfileName == null) { - return Mono.error(new IllegalArgumentException( - "Parameter discoveredAssetEndpointProfileName is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.delete(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, discoveredAssetEndpointProfileName, accept, context)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Delete a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> deleteWithResponseAsync(String resourceGroupName, - String discoveredAssetEndpointProfileName, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (discoveredAssetEndpointProfileName == null) { - return Mono.error(new IllegalArgumentException( - "Parameter discoveredAssetEndpointProfileName is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.delete(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), - resourceGroupName, discoveredAssetEndpointProfileName, accept, context); - } - - /** - * Delete a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of long-running operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, Void> beginDeleteAsync(String resourceGroupName, - String discoveredAssetEndpointProfileName) { - Mono>> mono - = deleteWithResponseAsync(resourceGroupName, discoveredAssetEndpointProfileName); - return this.client.getLroResult(mono, this.client.getHttpPipeline(), Void.class, Void.class, - this.client.getContext()); - } - - /** - * Delete a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of long-running operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, Void> beginDeleteAsync(String resourceGroupName, - String discoveredAssetEndpointProfileName, Context context) { - context = this.client.mergeContext(context); - Mono>> mono - = deleteWithResponseAsync(resourceGroupName, discoveredAssetEndpointProfileName, context); - return this.client.getLroResult(mono, this.client.getHttpPipeline(), Void.class, Void.class, - context); - } - - /** - * Delete a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of long-running operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, Void> beginDelete(String resourceGroupName, - String discoveredAssetEndpointProfileName) { - return this.beginDeleteAsync(resourceGroupName, discoveredAssetEndpointProfileName).getSyncPoller(); - } - - /** - * Delete a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of long-running operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, Void> beginDelete(String resourceGroupName, - String discoveredAssetEndpointProfileName, Context context) { - return this.beginDeleteAsync(resourceGroupName, discoveredAssetEndpointProfileName, context).getSyncPoller(); - } - - /** - * Delete a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono deleteAsync(String resourceGroupName, String discoveredAssetEndpointProfileName) { - return beginDeleteAsync(resourceGroupName, discoveredAssetEndpointProfileName).last() - .flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Delete a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono deleteAsync(String resourceGroupName, String discoveredAssetEndpointProfileName, - Context context) { - return beginDeleteAsync(resourceGroupName, discoveredAssetEndpointProfileName, context).last() - .flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Delete a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void delete(String resourceGroupName, String discoveredAssetEndpointProfileName) { - deleteAsync(resourceGroupName, discoveredAssetEndpointProfileName).block(); - } - - /** - * Delete a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void delete(String resourceGroupName, String discoveredAssetEndpointProfileName, Context context) { - deleteAsync(resourceGroupName, discoveredAssetEndpointProfileName, context).block(); - } - - /** - * List DiscoveredAssetEndpointProfile resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAssetEndpointProfile list operation along with {@link PagedResponse} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> - listByResourceGroupSinglePageAsync(String resourceGroupName) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.listByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), - res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * List DiscoveredAssetEndpointProfile resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAssetEndpointProfile list operation along with {@link PagedResponse} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> - listByResourceGroupSinglePageAsync(String resourceGroupName, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service - .listByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } - - /** - * List DiscoveredAssetEndpointProfile resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAssetEndpointProfile list operation as paginated response with - * {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listByResourceGroupAsync(String resourceGroupName) { - return new PagedFlux<>(() -> listByResourceGroupSinglePageAsync(resourceGroupName), - nextLink -> listByResourceGroupNextSinglePageAsync(nextLink)); - } - - /** - * List DiscoveredAssetEndpointProfile resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAssetEndpointProfile list operation as paginated response with - * {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listByResourceGroupAsync(String resourceGroupName, - Context context) { - return new PagedFlux<>(() -> listByResourceGroupSinglePageAsync(resourceGroupName, context), - nextLink -> listByResourceGroupNextSinglePageAsync(nextLink, context)); - } - - /** - * List DiscoveredAssetEndpointProfile resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAssetEndpointProfile list operation as paginated response with - * {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listByResourceGroup(String resourceGroupName) { - return new PagedIterable<>(listByResourceGroupAsync(resourceGroupName)); - } - - /** - * List DiscoveredAssetEndpointProfile resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAssetEndpointProfile list operation as paginated response with - * {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listByResourceGroup(String resourceGroupName, - Context context) { - return new PagedIterable<>(listByResourceGroupAsync(resourceGroupName, context)); - } - - /** - * List DiscoveredAssetEndpointProfile resources by subscription ID. - * - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAssetEndpointProfile list operation along with {@link PagedResponse} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listSinglePageAsync() { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.list(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), - res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * List DiscoveredAssetEndpointProfile resources by subscription ID. - * - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAssetEndpointProfile list operation along with {@link PagedResponse} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listSinglePageAsync(Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service - .list(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), accept, - context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } - - /** - * List DiscoveredAssetEndpointProfile resources by subscription ID. - * - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAssetEndpointProfile list operation as paginated response with - * {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listAsync() { - return new PagedFlux<>(() -> listSinglePageAsync(), - nextLink -> listBySubscriptionNextSinglePageAsync(nextLink)); - } - - /** - * List DiscoveredAssetEndpointProfile resources by subscription ID. - * - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAssetEndpointProfile list operation as paginated response with - * {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listAsync(Context context) { - return new PagedFlux<>(() -> listSinglePageAsync(context), - nextLink -> listBySubscriptionNextSinglePageAsync(nextLink, context)); - } - - /** - * List DiscoveredAssetEndpointProfile resources by subscription ID. - * - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAssetEndpointProfile list operation as paginated response with - * {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list() { - return new PagedIterable<>(listAsync()); - } - - /** - * List DiscoveredAssetEndpointProfile resources by subscription ID. - * - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAssetEndpointProfile list operation as paginated response with - * {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list(Context context) { - return new PagedIterable<>(listAsync(context)); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAssetEndpointProfile list operation along with {@link PagedResponse} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> - listByResourceGroupNextSinglePageAsync(String nextLink) { - if (nextLink == null) { - return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - } - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext( - context -> service.listByResourceGroupNext(nextLink, this.client.getEndpoint(), accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), - res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAssetEndpointProfile list operation along with {@link PagedResponse} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> - listByResourceGroupNextSinglePageAsync(String nextLink, Context context) { - if (nextLink == null) { - return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - } - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.listByResourceGroupNext(nextLink, this.client.getEndpoint(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAssetEndpointProfile list operation along with {@link PagedResponse} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> - listBySubscriptionNextSinglePageAsync(String nextLink) { - if (nextLink == null) { - return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - } - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext( - context -> service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), - res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAssetEndpointProfile list operation along with {@link PagedResponse} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> - listBySubscriptionNextSinglePageAsync(String nextLink, Context context) { - if (nextLink == null) { - return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - } - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/DiscoveredAssetEndpointProfilesImpl.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/DiscoveredAssetEndpointProfilesImpl.java deleted file mode 100644 index 34c7bc45c5df..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/DiscoveredAssetEndpointProfilesImpl.java +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.implementation; - -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.SimpleResponse; -import com.azure.core.util.Context; -import com.azure.core.util.logging.ClientLogger; -import com.azure.resourcemanager.deviceregistry.fluent.DiscoveredAssetEndpointProfilesClient; -import com.azure.resourcemanager.deviceregistry.fluent.models.DiscoveredAssetEndpointProfileInner; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetEndpointProfile; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetEndpointProfiles; - -public final class DiscoveredAssetEndpointProfilesImpl implements DiscoveredAssetEndpointProfiles { - private static final ClientLogger LOGGER = new ClientLogger(DiscoveredAssetEndpointProfilesImpl.class); - - private final DiscoveredAssetEndpointProfilesClient innerClient; - - private final com.azure.resourcemanager.deviceregistry.DeviceRegistryManager serviceManager; - - public DiscoveredAssetEndpointProfilesImpl(DiscoveredAssetEndpointProfilesClient innerClient, - com.azure.resourcemanager.deviceregistry.DeviceRegistryManager serviceManager) { - this.innerClient = innerClient; - this.serviceManager = serviceManager; - } - - public Response getByResourceGroupWithResponse(String resourceGroupName, - String discoveredAssetEndpointProfileName, Context context) { - Response inner = this.serviceClient() - .getByResourceGroupWithResponse(resourceGroupName, discoveredAssetEndpointProfileName, context); - if (inner != null) { - return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), - new DiscoveredAssetEndpointProfileImpl(inner.getValue(), this.manager())); - } else { - return null; - } - } - - public DiscoveredAssetEndpointProfile getByResourceGroup(String resourceGroupName, - String discoveredAssetEndpointProfileName) { - DiscoveredAssetEndpointProfileInner inner - = this.serviceClient().getByResourceGroup(resourceGroupName, discoveredAssetEndpointProfileName); - if (inner != null) { - return new DiscoveredAssetEndpointProfileImpl(inner, this.manager()); - } else { - return null; - } - } - - public void deleteByResourceGroup(String resourceGroupName, String discoveredAssetEndpointProfileName) { - this.serviceClient().delete(resourceGroupName, discoveredAssetEndpointProfileName); - } - - public void delete(String resourceGroupName, String discoveredAssetEndpointProfileName, Context context) { - this.serviceClient().delete(resourceGroupName, discoveredAssetEndpointProfileName, context); - } - - public PagedIterable listByResourceGroup(String resourceGroupName) { - PagedIterable inner - = this.serviceClient().listByResourceGroup(resourceGroupName); - return ResourceManagerUtils.mapPage(inner, - inner1 -> new DiscoveredAssetEndpointProfileImpl(inner1, this.manager())); - } - - public PagedIterable listByResourceGroup(String resourceGroupName, - Context context) { - PagedIterable inner - = this.serviceClient().listByResourceGroup(resourceGroupName, context); - return ResourceManagerUtils.mapPage(inner, - inner1 -> new DiscoveredAssetEndpointProfileImpl(inner1, this.manager())); - } - - public PagedIterable list() { - PagedIterable inner = this.serviceClient().list(); - return ResourceManagerUtils.mapPage(inner, - inner1 -> new DiscoveredAssetEndpointProfileImpl(inner1, this.manager())); - } - - public PagedIterable list(Context context) { - PagedIterable inner = this.serviceClient().list(context); - return ResourceManagerUtils.mapPage(inner, - inner1 -> new DiscoveredAssetEndpointProfileImpl(inner1, this.manager())); - } - - public DiscoveredAssetEndpointProfile getById(String id) { - String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); - if (resourceGroupName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); - } - String discoveredAssetEndpointProfileName - = ResourceManagerUtils.getValueFromIdByName(id, "discoveredAssetEndpointProfiles"); - if (discoveredAssetEndpointProfileName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format( - "The resource ID '%s' is not valid. Missing path segment 'discoveredAssetEndpointProfiles'.", id))); - } - return this.getByResourceGroupWithResponse(resourceGroupName, discoveredAssetEndpointProfileName, Context.NONE) - .getValue(); - } - - public Response getByIdWithResponse(String id, Context context) { - String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); - if (resourceGroupName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); - } - String discoveredAssetEndpointProfileName - = ResourceManagerUtils.getValueFromIdByName(id, "discoveredAssetEndpointProfiles"); - if (discoveredAssetEndpointProfileName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format( - "The resource ID '%s' is not valid. Missing path segment 'discoveredAssetEndpointProfiles'.", id))); - } - return this.getByResourceGroupWithResponse(resourceGroupName, discoveredAssetEndpointProfileName, context); - } - - public void deleteById(String id) { - String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); - if (resourceGroupName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); - } - String discoveredAssetEndpointProfileName - = ResourceManagerUtils.getValueFromIdByName(id, "discoveredAssetEndpointProfiles"); - if (discoveredAssetEndpointProfileName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format( - "The resource ID '%s' is not valid. Missing path segment 'discoveredAssetEndpointProfiles'.", id))); - } - this.delete(resourceGroupName, discoveredAssetEndpointProfileName, Context.NONE); - } - - public void deleteByIdWithResponse(String id, Context context) { - String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); - if (resourceGroupName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); - } - String discoveredAssetEndpointProfileName - = ResourceManagerUtils.getValueFromIdByName(id, "discoveredAssetEndpointProfiles"); - if (discoveredAssetEndpointProfileName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format( - "The resource ID '%s' is not valid. Missing path segment 'discoveredAssetEndpointProfiles'.", id))); - } - this.delete(resourceGroupName, discoveredAssetEndpointProfileName, context); - } - - private DiscoveredAssetEndpointProfilesClient serviceClient() { - return this.innerClient; - } - - private com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager() { - return this.serviceManager; - } - - public DiscoveredAssetEndpointProfileImpl define(String name) { - return new DiscoveredAssetEndpointProfileImpl(name, this.manager()); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/DiscoveredAssetImpl.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/DiscoveredAssetImpl.java deleted file mode 100644 index 06cf3ec63c15..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/DiscoveredAssetImpl.java +++ /dev/null @@ -1,193 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.implementation; - -import com.azure.core.management.Region; -import com.azure.core.management.SystemData; -import com.azure.core.util.Context; -import com.azure.resourcemanager.deviceregistry.fluent.models.DiscoveredAssetInner; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAsset; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetProperties; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetUpdate; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetUpdateProperties; -import com.azure.resourcemanager.deviceregistry.models.ExtendedLocation; -import java.util.Collections; -import java.util.Map; - -public final class DiscoveredAssetImpl implements DiscoveredAsset, DiscoveredAsset.Definition, DiscoveredAsset.Update { - private DiscoveredAssetInner innerObject; - - private final com.azure.resourcemanager.deviceregistry.DeviceRegistryManager serviceManager; - - public String id() { - return this.innerModel().id(); - } - - public String name() { - return this.innerModel().name(); - } - - public String type() { - return this.innerModel().type(); - } - - public String location() { - return this.innerModel().location(); - } - - public Map tags() { - Map inner = this.innerModel().tags(); - if (inner != null) { - return Collections.unmodifiableMap(inner); - } else { - return Collections.emptyMap(); - } - } - - public DiscoveredAssetProperties properties() { - return this.innerModel().properties(); - } - - public ExtendedLocation extendedLocation() { - return this.innerModel().extendedLocation(); - } - - public SystemData systemData() { - return this.innerModel().systemData(); - } - - public Region region() { - return Region.fromName(this.regionName()); - } - - public String regionName() { - return this.location(); - } - - public String resourceGroupName() { - return resourceGroupName; - } - - public DiscoveredAssetInner innerModel() { - return this.innerObject; - } - - private com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager() { - return this.serviceManager; - } - - private String resourceGroupName; - - private String discoveredAssetName; - - private DiscoveredAssetUpdate updateProperties; - - public DiscoveredAssetImpl withExistingResourceGroup(String resourceGroupName) { - this.resourceGroupName = resourceGroupName; - return this; - } - - public DiscoveredAsset create() { - this.innerObject = serviceManager.serviceClient() - .getDiscoveredAssets() - .createOrReplace(resourceGroupName, discoveredAssetName, this.innerModel(), Context.NONE); - return this; - } - - public DiscoveredAsset create(Context context) { - this.innerObject = serviceManager.serviceClient() - .getDiscoveredAssets() - .createOrReplace(resourceGroupName, discoveredAssetName, this.innerModel(), context); - return this; - } - - DiscoveredAssetImpl(String name, com.azure.resourcemanager.deviceregistry.DeviceRegistryManager serviceManager) { - this.innerObject = new DiscoveredAssetInner(); - this.serviceManager = serviceManager; - this.discoveredAssetName = name; - } - - public DiscoveredAssetImpl update() { - this.updateProperties = new DiscoveredAssetUpdate(); - return this; - } - - public DiscoveredAsset apply() { - this.innerObject = serviceManager.serviceClient() - .getDiscoveredAssets() - .update(resourceGroupName, discoveredAssetName, updateProperties, Context.NONE); - return this; - } - - public DiscoveredAsset apply(Context context) { - this.innerObject = serviceManager.serviceClient() - .getDiscoveredAssets() - .update(resourceGroupName, discoveredAssetName, updateProperties, context); - return this; - } - - DiscoveredAssetImpl(DiscoveredAssetInner innerObject, - com.azure.resourcemanager.deviceregistry.DeviceRegistryManager serviceManager) { - this.innerObject = innerObject; - this.serviceManager = serviceManager; - this.resourceGroupName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "resourceGroups"); - this.discoveredAssetName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "discoveredAssets"); - } - - public DiscoveredAsset refresh() { - this.innerObject = serviceManager.serviceClient() - .getDiscoveredAssets() - .getByResourceGroupWithResponse(resourceGroupName, discoveredAssetName, Context.NONE) - .getValue(); - return this; - } - - public DiscoveredAsset refresh(Context context) { - this.innerObject = serviceManager.serviceClient() - .getDiscoveredAssets() - .getByResourceGroupWithResponse(resourceGroupName, discoveredAssetName, context) - .getValue(); - return this; - } - - public DiscoveredAssetImpl withRegion(Region location) { - this.innerModel().withLocation(location.toString()); - return this; - } - - public DiscoveredAssetImpl withRegion(String location) { - this.innerModel().withLocation(location); - return this; - } - - public DiscoveredAssetImpl withExtendedLocation(ExtendedLocation extendedLocation) { - this.innerModel().withExtendedLocation(extendedLocation); - return this; - } - - public DiscoveredAssetImpl withTags(Map tags) { - if (isInCreateMode()) { - this.innerModel().withTags(tags); - return this; - } else { - this.updateProperties.withTags(tags); - return this; - } - } - - public DiscoveredAssetImpl withProperties(DiscoveredAssetProperties properties) { - this.innerModel().withProperties(properties); - return this; - } - - public DiscoveredAssetImpl withProperties(DiscoveredAssetUpdateProperties properties) { - this.updateProperties.withProperties(properties); - return this; - } - - private boolean isInCreateMode() { - return this.innerModel().id() == null; - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/DiscoveredAssetsClientImpl.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/DiscoveredAssetsClientImpl.java deleted file mode 100644 index 17a821c7e2dd..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/DiscoveredAssetsClientImpl.java +++ /dev/null @@ -1,1296 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.implementation; - -import com.azure.core.annotation.BodyParam; -import com.azure.core.annotation.Delete; -import com.azure.core.annotation.ExpectedResponses; -import com.azure.core.annotation.Get; -import com.azure.core.annotation.HeaderParam; -import com.azure.core.annotation.Headers; -import com.azure.core.annotation.Host; -import com.azure.core.annotation.HostParam; -import com.azure.core.annotation.Patch; -import com.azure.core.annotation.PathParam; -import com.azure.core.annotation.Put; -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.PagedFlux; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.PagedResponse; -import com.azure.core.http.rest.PagedResponseBase; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.RestProxy; -import com.azure.core.management.exception.ManagementException; -import com.azure.core.management.polling.PollResult; -import com.azure.core.util.Context; -import com.azure.core.util.FluxUtil; -import com.azure.core.util.polling.PollerFlux; -import com.azure.core.util.polling.SyncPoller; -import com.azure.resourcemanager.deviceregistry.fluent.DiscoveredAssetsClient; -import com.azure.resourcemanager.deviceregistry.fluent.models.DiscoveredAssetInner; -import com.azure.resourcemanager.deviceregistry.implementation.models.DiscoveredAssetListResult; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetUpdate; -import java.nio.ByteBuffer; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -/** - * An instance of this class provides access to all the operations defined in DiscoveredAssetsClient. - */ -public final class DiscoveredAssetsClientImpl implements DiscoveredAssetsClient { - /** - * The proxy service used to perform REST calls. - */ - private final DiscoveredAssetsService service; - - /** - * The service client containing this operation class. - */ - private final DeviceRegistryManagementClientImpl client; - - /** - * Initializes an instance of DiscoveredAssetsClientImpl. - * - * @param client the instance of the service client containing this operation class. - */ - DiscoveredAssetsClientImpl(DeviceRegistryManagementClientImpl client) { - this.service - = RestProxy.create(DiscoveredAssetsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); - this.client = client; - } - - /** - * The interface defining all the services for DeviceRegistryManagementClientDiscoveredAssets to be used by the - * proxy service to perform REST calls. - */ - @Host("{endpoint}") - @ServiceInterface(name = "DeviceRegistryManage") - public interface DiscoveredAssetsService { - @Headers({ "Content-Type: application/json" }) - @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DeviceRegistry/discoveredAssets/{discoveredAssetName}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> getByResourceGroup(@HostParam("endpoint") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, - @PathParam("discoveredAssetName") String discoveredAssetName, @HeaderParam("Accept") String accept, - Context context); - - @Put("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DeviceRegistry/discoveredAssets/{discoveredAssetName}") - @ExpectedResponses({ 200, 201 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono>> createOrReplace(@HostParam("endpoint") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, - @PathParam("discoveredAssetName") String discoveredAssetName, - @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, - @BodyParam("application/json") DiscoveredAssetInner resource, Context context); - - @Patch("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DeviceRegistry/discoveredAssets/{discoveredAssetName}") - @ExpectedResponses({ 200, 202 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono>> update(@HostParam("endpoint") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, - @PathParam("discoveredAssetName") String discoveredAssetName, - @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, - @BodyParam("application/json") DiscoveredAssetUpdate properties, Context context); - - @Headers({ "Content-Type: application/json" }) - @Delete("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DeviceRegistry/discoveredAssets/{discoveredAssetName}") - @ExpectedResponses({ 202, 204 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono>> delete(@HostParam("endpoint") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, - @PathParam("discoveredAssetName") String discoveredAssetName, @HeaderParam("Accept") String accept, - Context context); - - @Headers({ "Content-Type: application/json" }) - @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DeviceRegistry/discoveredAssets") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> listByResourceGroup(@HostParam("endpoint") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, @HeaderParam("Accept") String accept, - Context context); - - @Headers({ "Content-Type: application/json" }) - @Get("/subscriptions/{subscriptionId}/providers/Microsoft.DeviceRegistry/discoveredAssets") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> list(@HostParam("endpoint") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @HeaderParam("Accept") String accept, Context context); - - @Headers({ "Content-Type: application/json" }) - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> listByResourceGroupNext( - @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, - @HeaderParam("Accept") String accept, Context context); - - @Headers({ "Content-Type: application/json" }) - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> listBySubscriptionNext( - @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, - @HeaderParam("Accept") String accept, Context context); - } - - /** - * Get a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DiscoveredAsset along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> getByResourceGroupWithResponseAsync(String resourceGroupName, - String discoveredAssetName) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (discoveredAssetName == null) { - return Mono - .error(new IllegalArgumentException("Parameter discoveredAssetName is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.getByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, discoveredAssetName, accept, context)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Get a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DiscoveredAsset along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> getByResourceGroupWithResponseAsync(String resourceGroupName, - String discoveredAssetName, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (discoveredAssetName == null) { - return Mono - .error(new IllegalArgumentException("Parameter discoveredAssetName is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.getByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, discoveredAssetName, accept, context); - } - - /** - * Get a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DiscoveredAsset on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono getByResourceGroupAsync(String resourceGroupName, String discoveredAssetName) { - return getByResourceGroupWithResponseAsync(resourceGroupName, discoveredAssetName) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Get a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DiscoveredAsset along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getByResourceGroupWithResponse(String resourceGroupName, - String discoveredAssetName, Context context) { - return getByResourceGroupWithResponseAsync(resourceGroupName, discoveredAssetName, context).block(); - } - - /** - * Get a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DiscoveredAsset. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public DiscoveredAssetInner getByResourceGroup(String resourceGroupName, String discoveredAssetName) { - return getByResourceGroupWithResponse(resourceGroupName, discoveredAssetName, Context.NONE).getValue(); - } - - /** - * Create a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param resource Resource create parameters. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset definition along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> createOrReplaceWithResponseAsync(String resourceGroupName, - String discoveredAssetName, DiscoveredAssetInner resource) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (discoveredAssetName == null) { - return Mono - .error(new IllegalArgumentException("Parameter discoveredAssetName is required and cannot be null.")); - } - if (resource == null) { - return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); - } else { - resource.validate(); - } - final String contentType = "application/json"; - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.createOrReplace(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, discoveredAssetName, contentType, accept, resource, - context)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Create a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param resource Resource create parameters. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset definition along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> createOrReplaceWithResponseAsync(String resourceGroupName, - String discoveredAssetName, DiscoveredAssetInner resource, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (discoveredAssetName == null) { - return Mono - .error(new IllegalArgumentException("Parameter discoveredAssetName is required and cannot be null.")); - } - if (resource == null) { - return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); - } else { - resource.validate(); - } - final String contentType = "application/json"; - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.createOrReplace(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, discoveredAssetName, contentType, accept, resource, - context); - } - - /** - * Create a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param resource Resource create parameters. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of discovered Asset definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, DiscoveredAssetInner> - beginCreateOrReplaceAsync(String resourceGroupName, String discoveredAssetName, DiscoveredAssetInner resource) { - Mono>> mono - = createOrReplaceWithResponseAsync(resourceGroupName, discoveredAssetName, resource); - return this.client.getLroResult(mono, this.client.getHttpPipeline(), - DiscoveredAssetInner.class, DiscoveredAssetInner.class, this.client.getContext()); - } - - /** - * Create a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param resource Resource create parameters. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of discovered Asset definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, DiscoveredAssetInner> beginCreateOrReplaceAsync( - String resourceGroupName, String discoveredAssetName, DiscoveredAssetInner resource, Context context) { - context = this.client.mergeContext(context); - Mono>> mono - = createOrReplaceWithResponseAsync(resourceGroupName, discoveredAssetName, resource, context); - return this.client.getLroResult(mono, this.client.getHttpPipeline(), - DiscoveredAssetInner.class, DiscoveredAssetInner.class, context); - } - - /** - * Create a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param resource Resource create parameters. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of discovered Asset definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, DiscoveredAssetInner> - beginCreateOrReplace(String resourceGroupName, String discoveredAssetName, DiscoveredAssetInner resource) { - return this.beginCreateOrReplaceAsync(resourceGroupName, discoveredAssetName, resource).getSyncPoller(); - } - - /** - * Create a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param resource Resource create parameters. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of discovered Asset definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, DiscoveredAssetInner> beginCreateOrReplace( - String resourceGroupName, String discoveredAssetName, DiscoveredAssetInner resource, Context context) { - return this.beginCreateOrReplaceAsync(resourceGroupName, discoveredAssetName, resource, context) - .getSyncPoller(); - } - - /** - * Create a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param resource Resource create parameters. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono createOrReplaceAsync(String resourceGroupName, String discoveredAssetName, - DiscoveredAssetInner resource) { - return beginCreateOrReplaceAsync(resourceGroupName, discoveredAssetName, resource).last() - .flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Create a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param resource Resource create parameters. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono createOrReplaceAsync(String resourceGroupName, String discoveredAssetName, - DiscoveredAssetInner resource, Context context) { - return beginCreateOrReplaceAsync(resourceGroupName, discoveredAssetName, resource, context).last() - .flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Create a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param resource Resource create parameters. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public DiscoveredAssetInner createOrReplace(String resourceGroupName, String discoveredAssetName, - DiscoveredAssetInner resource) { - return createOrReplaceAsync(resourceGroupName, discoveredAssetName, resource).block(); - } - - /** - * Create a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param resource Resource create parameters. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public DiscoveredAssetInner createOrReplace(String resourceGroupName, String discoveredAssetName, - DiscoveredAssetInner resource, Context context) { - return createOrReplaceAsync(resourceGroupName, discoveredAssetName, resource, context).block(); - } - - /** - * Update a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param properties The resource properties to be updated. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset definition along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> updateWithResponseAsync(String resourceGroupName, - String discoveredAssetName, DiscoveredAssetUpdate properties) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (discoveredAssetName == null) { - return Mono - .error(new IllegalArgumentException("Parameter discoveredAssetName is required and cannot be null.")); - } - if (properties == null) { - return Mono.error(new IllegalArgumentException("Parameter properties is required and cannot be null.")); - } else { - properties.validate(); - } - final String contentType = "application/json"; - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.update(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, discoveredAssetName, contentType, accept, - properties, context)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Update a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param properties The resource properties to be updated. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset definition along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> updateWithResponseAsync(String resourceGroupName, - String discoveredAssetName, DiscoveredAssetUpdate properties, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (discoveredAssetName == null) { - return Mono - .error(new IllegalArgumentException("Parameter discoveredAssetName is required and cannot be null.")); - } - if (properties == null) { - return Mono.error(new IllegalArgumentException("Parameter properties is required and cannot be null.")); - } else { - properties.validate(); - } - final String contentType = "application/json"; - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.update(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), - resourceGroupName, discoveredAssetName, contentType, accept, properties, context); - } - - /** - * Update a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param properties The resource properties to be updated. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of discovered Asset definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, DiscoveredAssetInner> - beginUpdateAsync(String resourceGroupName, String discoveredAssetName, DiscoveredAssetUpdate properties) { - Mono>> mono - = updateWithResponseAsync(resourceGroupName, discoveredAssetName, properties); - return this.client.getLroResult(mono, this.client.getHttpPipeline(), - DiscoveredAssetInner.class, DiscoveredAssetInner.class, this.client.getContext()); - } - - /** - * Update a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param properties The resource properties to be updated. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of discovered Asset definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, DiscoveredAssetInner> beginUpdateAsync( - String resourceGroupName, String discoveredAssetName, DiscoveredAssetUpdate properties, Context context) { - context = this.client.mergeContext(context); - Mono>> mono - = updateWithResponseAsync(resourceGroupName, discoveredAssetName, properties, context); - return this.client.getLroResult(mono, this.client.getHttpPipeline(), - DiscoveredAssetInner.class, DiscoveredAssetInner.class, context); - } - - /** - * Update a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param properties The resource properties to be updated. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of discovered Asset definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, DiscoveredAssetInner> beginUpdate(String resourceGroupName, - String discoveredAssetName, DiscoveredAssetUpdate properties) { - return this.beginUpdateAsync(resourceGroupName, discoveredAssetName, properties).getSyncPoller(); - } - - /** - * Update a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param properties The resource properties to be updated. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of discovered Asset definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, DiscoveredAssetInner> beginUpdate(String resourceGroupName, - String discoveredAssetName, DiscoveredAssetUpdate properties, Context context) { - return this.beginUpdateAsync(resourceGroupName, discoveredAssetName, properties, context).getSyncPoller(); - } - - /** - * Update a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param properties The resource properties to be updated. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono updateAsync(String resourceGroupName, String discoveredAssetName, - DiscoveredAssetUpdate properties) { - return beginUpdateAsync(resourceGroupName, discoveredAssetName, properties).last() - .flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Update a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param properties The resource properties to be updated. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono updateAsync(String resourceGroupName, String discoveredAssetName, - DiscoveredAssetUpdate properties, Context context) { - return beginUpdateAsync(resourceGroupName, discoveredAssetName, properties, context).last() - .flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Update a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param properties The resource properties to be updated. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public DiscoveredAssetInner update(String resourceGroupName, String discoveredAssetName, - DiscoveredAssetUpdate properties) { - return updateAsync(resourceGroupName, discoveredAssetName, properties).block(); - } - - /** - * Update a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param properties The resource properties to be updated. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return discovered Asset definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public DiscoveredAssetInner update(String resourceGroupName, String discoveredAssetName, - DiscoveredAssetUpdate properties, Context context) { - return updateAsync(resourceGroupName, discoveredAssetName, properties, context).block(); - } - - /** - * Delete a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> deleteWithResponseAsync(String resourceGroupName, - String discoveredAssetName) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (discoveredAssetName == null) { - return Mono - .error(new IllegalArgumentException("Parameter discoveredAssetName is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.delete(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, discoveredAssetName, accept, context)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Delete a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> deleteWithResponseAsync(String resourceGroupName, - String discoveredAssetName, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (discoveredAssetName == null) { - return Mono - .error(new IllegalArgumentException("Parameter discoveredAssetName is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.delete(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), - resourceGroupName, discoveredAssetName, accept, context); - } - - /** - * Delete a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of long-running operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, Void> beginDeleteAsync(String resourceGroupName, String discoveredAssetName) { - Mono>> mono = deleteWithResponseAsync(resourceGroupName, discoveredAssetName); - return this.client.getLroResult(mono, this.client.getHttpPipeline(), Void.class, Void.class, - this.client.getContext()); - } - - /** - * Delete a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of long-running operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, Void> beginDeleteAsync(String resourceGroupName, String discoveredAssetName, - Context context) { - context = this.client.mergeContext(context); - Mono>> mono - = deleteWithResponseAsync(resourceGroupName, discoveredAssetName, context); - return this.client.getLroResult(mono, this.client.getHttpPipeline(), Void.class, Void.class, - context); - } - - /** - * Delete a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of long-running operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, Void> beginDelete(String resourceGroupName, String discoveredAssetName) { - return this.beginDeleteAsync(resourceGroupName, discoveredAssetName).getSyncPoller(); - } - - /** - * Delete a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of long-running operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, Void> beginDelete(String resourceGroupName, String discoveredAssetName, - Context context) { - return this.beginDeleteAsync(resourceGroupName, discoveredAssetName, context).getSyncPoller(); - } - - /** - * Delete a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono deleteAsync(String resourceGroupName, String discoveredAssetName) { - return beginDeleteAsync(resourceGroupName, discoveredAssetName).last() - .flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Delete a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono deleteAsync(String resourceGroupName, String discoveredAssetName, Context context) { - return beginDeleteAsync(resourceGroupName, discoveredAssetName, context).last() - .flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Delete a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void delete(String resourceGroupName, String discoveredAssetName) { - deleteAsync(resourceGroupName, discoveredAssetName).block(); - } - - /** - * Delete a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void delete(String resourceGroupName, String discoveredAssetName, Context context) { - deleteAsync(resourceGroupName, discoveredAssetName, context).block(); - } - - /** - * List DiscoveredAsset resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAsset list operation along with {@link PagedResponse} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listByResourceGroupSinglePageAsync(String resourceGroupName) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.listByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), - res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * List DiscoveredAsset resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAsset list operation along with {@link PagedResponse} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listByResourceGroupSinglePageAsync(String resourceGroupName, - Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service - .listByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } - - /** - * List DiscoveredAsset resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAsset list operation as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listByResourceGroupAsync(String resourceGroupName) { - return new PagedFlux<>(() -> listByResourceGroupSinglePageAsync(resourceGroupName), - nextLink -> listByResourceGroupNextSinglePageAsync(nextLink)); - } - - /** - * List DiscoveredAsset resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAsset list operation as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listByResourceGroupAsync(String resourceGroupName, Context context) { - return new PagedFlux<>(() -> listByResourceGroupSinglePageAsync(resourceGroupName, context), - nextLink -> listByResourceGroupNextSinglePageAsync(nextLink, context)); - } - - /** - * List DiscoveredAsset resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAsset list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listByResourceGroup(String resourceGroupName) { - return new PagedIterable<>(listByResourceGroupAsync(resourceGroupName)); - } - - /** - * List DiscoveredAsset resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAsset list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listByResourceGroup(String resourceGroupName, Context context) { - return new PagedIterable<>(listByResourceGroupAsync(resourceGroupName, context)); - } - - /** - * List DiscoveredAsset resources by subscription ID. - * - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAsset list operation along with {@link PagedResponse} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listSinglePageAsync() { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.list(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), - res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * List DiscoveredAsset resources by subscription ID. - * - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAsset list operation along with {@link PagedResponse} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listSinglePageAsync(Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service - .list(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), accept, - context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } - - /** - * List DiscoveredAsset resources by subscription ID. - * - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAsset list operation as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listAsync() { - return new PagedFlux<>(() -> listSinglePageAsync(), - nextLink -> listBySubscriptionNextSinglePageAsync(nextLink)); - } - - /** - * List DiscoveredAsset resources by subscription ID. - * - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAsset list operation as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listAsync(Context context) { - return new PagedFlux<>(() -> listSinglePageAsync(context), - nextLink -> listBySubscriptionNextSinglePageAsync(nextLink, context)); - } - - /** - * List DiscoveredAsset resources by subscription ID. - * - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAsset list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list() { - return new PagedIterable<>(listAsync()); - } - - /** - * List DiscoveredAsset resources by subscription ID. - * - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAsset list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list(Context context) { - return new PagedIterable<>(listAsync(context)); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAsset list operation along with {@link PagedResponse} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listByResourceGroupNextSinglePageAsync(String nextLink) { - if (nextLink == null) { - return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - } - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext( - context -> service.listByResourceGroupNext(nextLink, this.client.getEndpoint(), accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), - res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAsset list operation along with {@link PagedResponse} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listByResourceGroupNextSinglePageAsync(String nextLink, - Context context) { - if (nextLink == null) { - return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - } - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.listByResourceGroupNext(nextLink, this.client.getEndpoint(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAsset list operation along with {@link PagedResponse} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listBySubscriptionNextSinglePageAsync(String nextLink) { - if (nextLink == null) { - return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - } - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext( - context -> service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), - res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAsset list operation along with {@link PagedResponse} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listBySubscriptionNextSinglePageAsync(String nextLink, - Context context) { - if (nextLink == null) { - return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - } - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/DiscoveredAssetsImpl.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/DiscoveredAssetsImpl.java deleted file mode 100644 index e4c26f8f15db..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/DiscoveredAssetsImpl.java +++ /dev/null @@ -1,147 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.implementation; - -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.SimpleResponse; -import com.azure.core.util.Context; -import com.azure.core.util.logging.ClientLogger; -import com.azure.resourcemanager.deviceregistry.fluent.DiscoveredAssetsClient; -import com.azure.resourcemanager.deviceregistry.fluent.models.DiscoveredAssetInner; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAsset; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssets; - -public final class DiscoveredAssetsImpl implements DiscoveredAssets { - private static final ClientLogger LOGGER = new ClientLogger(DiscoveredAssetsImpl.class); - - private final DiscoveredAssetsClient innerClient; - - private final com.azure.resourcemanager.deviceregistry.DeviceRegistryManager serviceManager; - - public DiscoveredAssetsImpl(DiscoveredAssetsClient innerClient, - com.azure.resourcemanager.deviceregistry.DeviceRegistryManager serviceManager) { - this.innerClient = innerClient; - this.serviceManager = serviceManager; - } - - public Response getByResourceGroupWithResponse(String resourceGroupName, - String discoveredAssetName, Context context) { - Response inner - = this.serviceClient().getByResourceGroupWithResponse(resourceGroupName, discoveredAssetName, context); - if (inner != null) { - return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), - new DiscoveredAssetImpl(inner.getValue(), this.manager())); - } else { - return null; - } - } - - public DiscoveredAsset getByResourceGroup(String resourceGroupName, String discoveredAssetName) { - DiscoveredAssetInner inner = this.serviceClient().getByResourceGroup(resourceGroupName, discoveredAssetName); - if (inner != null) { - return new DiscoveredAssetImpl(inner, this.manager()); - } else { - return null; - } - } - - public void deleteByResourceGroup(String resourceGroupName, String discoveredAssetName) { - this.serviceClient().delete(resourceGroupName, discoveredAssetName); - } - - public void delete(String resourceGroupName, String discoveredAssetName, Context context) { - this.serviceClient().delete(resourceGroupName, discoveredAssetName, context); - } - - public PagedIterable listByResourceGroup(String resourceGroupName) { - PagedIterable inner = this.serviceClient().listByResourceGroup(resourceGroupName); - return ResourceManagerUtils.mapPage(inner, inner1 -> new DiscoveredAssetImpl(inner1, this.manager())); - } - - public PagedIterable listByResourceGroup(String resourceGroupName, Context context) { - PagedIterable inner - = this.serviceClient().listByResourceGroup(resourceGroupName, context); - return ResourceManagerUtils.mapPage(inner, inner1 -> new DiscoveredAssetImpl(inner1, this.manager())); - } - - public PagedIterable list() { - PagedIterable inner = this.serviceClient().list(); - return ResourceManagerUtils.mapPage(inner, inner1 -> new DiscoveredAssetImpl(inner1, this.manager())); - } - - public PagedIterable list(Context context) { - PagedIterable inner = this.serviceClient().list(context); - return ResourceManagerUtils.mapPage(inner, inner1 -> new DiscoveredAssetImpl(inner1, this.manager())); - } - - public DiscoveredAsset getById(String id) { - String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); - if (resourceGroupName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); - } - String discoveredAssetName = ResourceManagerUtils.getValueFromIdByName(id, "discoveredAssets"); - if (discoveredAssetName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'discoveredAssets'.", id))); - } - return this.getByResourceGroupWithResponse(resourceGroupName, discoveredAssetName, Context.NONE).getValue(); - } - - public Response getByIdWithResponse(String id, Context context) { - String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); - if (resourceGroupName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); - } - String discoveredAssetName = ResourceManagerUtils.getValueFromIdByName(id, "discoveredAssets"); - if (discoveredAssetName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'discoveredAssets'.", id))); - } - return this.getByResourceGroupWithResponse(resourceGroupName, discoveredAssetName, context); - } - - public void deleteById(String id) { - String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); - if (resourceGroupName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); - } - String discoveredAssetName = ResourceManagerUtils.getValueFromIdByName(id, "discoveredAssets"); - if (discoveredAssetName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'discoveredAssets'.", id))); - } - this.delete(resourceGroupName, discoveredAssetName, Context.NONE); - } - - public void deleteByIdWithResponse(String id, Context context) { - String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); - if (resourceGroupName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); - } - String discoveredAssetName = ResourceManagerUtils.getValueFromIdByName(id, "discoveredAssets"); - if (discoveredAssetName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'discoveredAssets'.", id))); - } - this.delete(resourceGroupName, discoveredAssetName, context); - } - - private DiscoveredAssetsClient serviceClient() { - return this.innerClient; - } - - private com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager() { - return this.serviceManager; - } - - public DiscoveredAssetImpl define(String name) { - return new DiscoveredAssetImpl(name, this.manager()); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/SchemaImpl.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/SchemaImpl.java deleted file mode 100644 index 19245be6f64e..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/SchemaImpl.java +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.implementation; - -import com.azure.core.management.SystemData; -import com.azure.core.util.Context; -import com.azure.resourcemanager.deviceregistry.fluent.models.SchemaInner; -import com.azure.resourcemanager.deviceregistry.models.Schema; -import com.azure.resourcemanager.deviceregistry.models.SchemaProperties; - -public final class SchemaImpl implements Schema, Schema.Definition { - private SchemaInner innerObject; - - private final com.azure.resourcemanager.deviceregistry.DeviceRegistryManager serviceManager; - - SchemaImpl(SchemaInner innerObject, com.azure.resourcemanager.deviceregistry.DeviceRegistryManager serviceManager) { - this.innerObject = innerObject; - this.serviceManager = serviceManager; - } - - public String id() { - return this.innerModel().id(); - } - - public String name() { - return this.innerModel().name(); - } - - public String type() { - return this.innerModel().type(); - } - - public SchemaProperties properties() { - return this.innerModel().properties(); - } - - public SystemData systemData() { - return this.innerModel().systemData(); - } - - public SchemaInner innerModel() { - return this.innerObject; - } - - private com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager() { - return this.serviceManager; - } - - private String resourceGroupName; - - private String schemaRegistryName; - - private String schemaName; - - public SchemaImpl withExistingSchemaRegistry(String resourceGroupName, String schemaRegistryName) { - this.resourceGroupName = resourceGroupName; - this.schemaRegistryName = schemaRegistryName; - return this; - } - - public Schema create() { - this.innerObject = serviceManager.serviceClient() - .getSchemas() - .createOrReplaceWithResponse(resourceGroupName, schemaRegistryName, schemaName, this.innerModel(), - Context.NONE) - .getValue(); - return this; - } - - public Schema create(Context context) { - this.innerObject = serviceManager.serviceClient() - .getSchemas() - .createOrReplaceWithResponse(resourceGroupName, schemaRegistryName, schemaName, this.innerModel(), context) - .getValue(); - return this; - } - - SchemaImpl(String name, com.azure.resourcemanager.deviceregistry.DeviceRegistryManager serviceManager) { - this.innerObject = new SchemaInner(); - this.serviceManager = serviceManager; - this.schemaName = name; - } - - public Schema refresh() { - this.innerObject = serviceManager.serviceClient() - .getSchemas() - .getWithResponse(resourceGroupName, schemaRegistryName, schemaName, Context.NONE) - .getValue(); - return this; - } - - public Schema refresh(Context context) { - this.innerObject = serviceManager.serviceClient() - .getSchemas() - .getWithResponse(resourceGroupName, schemaRegistryName, schemaName, context) - .getValue(); - return this; - } - - public SchemaImpl withProperties(SchemaProperties properties) { - this.innerModel().withProperties(properties); - return this; - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/SchemaRegistriesClientImpl.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/SchemaRegistriesClientImpl.java deleted file mode 100644 index 761f2767beb5..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/SchemaRegistriesClientImpl.java +++ /dev/null @@ -1,1294 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.implementation; - -import com.azure.core.annotation.BodyParam; -import com.azure.core.annotation.Delete; -import com.azure.core.annotation.ExpectedResponses; -import com.azure.core.annotation.Get; -import com.azure.core.annotation.HeaderParam; -import com.azure.core.annotation.Headers; -import com.azure.core.annotation.Host; -import com.azure.core.annotation.HostParam; -import com.azure.core.annotation.Patch; -import com.azure.core.annotation.PathParam; -import com.azure.core.annotation.Put; -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.PagedFlux; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.PagedResponse; -import com.azure.core.http.rest.PagedResponseBase; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.RestProxy; -import com.azure.core.management.exception.ManagementException; -import com.azure.core.management.polling.PollResult; -import com.azure.core.util.Context; -import com.azure.core.util.FluxUtil; -import com.azure.core.util.polling.PollerFlux; -import com.azure.core.util.polling.SyncPoller; -import com.azure.resourcemanager.deviceregistry.fluent.SchemaRegistriesClient; -import com.azure.resourcemanager.deviceregistry.fluent.models.SchemaRegistryInner; -import com.azure.resourcemanager.deviceregistry.implementation.models.SchemaRegistryListResult; -import com.azure.resourcemanager.deviceregistry.models.SchemaRegistryUpdate; -import java.nio.ByteBuffer; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -/** - * An instance of this class provides access to all the operations defined in SchemaRegistriesClient. - */ -public final class SchemaRegistriesClientImpl implements SchemaRegistriesClient { - /** - * The proxy service used to perform REST calls. - */ - private final SchemaRegistriesService service; - - /** - * The service client containing this operation class. - */ - private final DeviceRegistryManagementClientImpl client; - - /** - * Initializes an instance of SchemaRegistriesClientImpl. - * - * @param client the instance of the service client containing this operation class. - */ - SchemaRegistriesClientImpl(DeviceRegistryManagementClientImpl client) { - this.service - = RestProxy.create(SchemaRegistriesService.class, client.getHttpPipeline(), client.getSerializerAdapter()); - this.client = client; - } - - /** - * The interface defining all the services for DeviceRegistryManagementClientSchemaRegistries to be used by the - * proxy service to perform REST calls. - */ - @Host("{endpoint}") - @ServiceInterface(name = "DeviceRegistryManage") - public interface SchemaRegistriesService { - @Headers({ "Content-Type: application/json" }) - @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DeviceRegistry/schemaRegistries/{schemaRegistryName}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> getByResourceGroup(@HostParam("endpoint") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, - @PathParam("schemaRegistryName") String schemaRegistryName, @HeaderParam("Accept") String accept, - Context context); - - @Put("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DeviceRegistry/schemaRegistries/{schemaRegistryName}") - @ExpectedResponses({ 200, 201 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono>> createOrReplace(@HostParam("endpoint") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, - @PathParam("schemaRegistryName") String schemaRegistryName, @HeaderParam("Content-Type") String contentType, - @HeaderParam("Accept") String accept, @BodyParam("application/json") SchemaRegistryInner resource, - Context context); - - @Patch("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DeviceRegistry/schemaRegistries/{schemaRegistryName}") - @ExpectedResponses({ 200, 202 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono>> update(@HostParam("endpoint") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, - @PathParam("schemaRegistryName") String schemaRegistryName, @HeaderParam("Content-Type") String contentType, - @HeaderParam("Accept") String accept, @BodyParam("application/json") SchemaRegistryUpdate properties, - Context context); - - @Headers({ "Content-Type: application/json" }) - @Delete("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DeviceRegistry/schemaRegistries/{schemaRegistryName}") - @ExpectedResponses({ 202, 204 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono>> delete(@HostParam("endpoint") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, - @PathParam("schemaRegistryName") String schemaRegistryName, @HeaderParam("Accept") String accept, - Context context); - - @Headers({ "Content-Type: application/json" }) - @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DeviceRegistry/schemaRegistries") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> listByResourceGroup(@HostParam("endpoint") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, @HeaderParam("Accept") String accept, - Context context); - - @Headers({ "Content-Type: application/json" }) - @Get("/subscriptions/{subscriptionId}/providers/Microsoft.DeviceRegistry/schemaRegistries") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> list(@HostParam("endpoint") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @HeaderParam("Accept") String accept, Context context); - - @Headers({ "Content-Type: application/json" }) - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> listByResourceGroupNext( - @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, - @HeaderParam("Accept") String accept, Context context); - - @Headers({ "Content-Type: application/json" }) - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> listBySubscriptionNext( - @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, - @HeaderParam("Accept") String accept, Context context); - } - - /** - * Get a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a SchemaRegistry along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> getByResourceGroupWithResponseAsync(String resourceGroupName, - String schemaRegistryName) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (schemaRegistryName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaRegistryName is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.getByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, schemaRegistryName, accept, context)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Get a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a SchemaRegistry along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> getByResourceGroupWithResponseAsync(String resourceGroupName, - String schemaRegistryName, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (schemaRegistryName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaRegistryName is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.getByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, schemaRegistryName, accept, context); - } - - /** - * Get a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a SchemaRegistry on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono getByResourceGroupAsync(String resourceGroupName, String schemaRegistryName) { - return getByResourceGroupWithResponseAsync(resourceGroupName, schemaRegistryName) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Get a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a SchemaRegistry along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getByResourceGroupWithResponse(String resourceGroupName, - String schemaRegistryName, Context context) { - return getByResourceGroupWithResponseAsync(resourceGroupName, schemaRegistryName, context).block(); - } - - /** - * Get a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a SchemaRegistry. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SchemaRegistryInner getByResourceGroup(String resourceGroupName, String schemaRegistryName) { - return getByResourceGroupWithResponse(resourceGroupName, schemaRegistryName, Context.NONE).getValue(); - } - - /** - * Create a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param resource Resource create parameters. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema registry definition along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> createOrReplaceWithResponseAsync(String resourceGroupName, - String schemaRegistryName, SchemaRegistryInner resource) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (schemaRegistryName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaRegistryName is required and cannot be null.")); - } - if (resource == null) { - return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); - } else { - resource.validate(); - } - final String contentType = "application/json"; - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.createOrReplace(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, schemaRegistryName, contentType, accept, resource, - context)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Create a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param resource Resource create parameters. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema registry definition along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> createOrReplaceWithResponseAsync(String resourceGroupName, - String schemaRegistryName, SchemaRegistryInner resource, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (schemaRegistryName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaRegistryName is required and cannot be null.")); - } - if (resource == null) { - return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); - } else { - resource.validate(); - } - final String contentType = "application/json"; - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.createOrReplace(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, schemaRegistryName, contentType, accept, resource, - context); - } - - /** - * Create a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param resource Resource create parameters. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of schema registry definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, SchemaRegistryInner> - beginCreateOrReplaceAsync(String resourceGroupName, String schemaRegistryName, SchemaRegistryInner resource) { - Mono>> mono - = createOrReplaceWithResponseAsync(resourceGroupName, schemaRegistryName, resource); - return this.client.getLroResult(mono, this.client.getHttpPipeline(), - SchemaRegistryInner.class, SchemaRegistryInner.class, this.client.getContext()); - } - - /** - * Create a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param resource Resource create parameters. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of schema registry definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, SchemaRegistryInner> beginCreateOrReplaceAsync( - String resourceGroupName, String schemaRegistryName, SchemaRegistryInner resource, Context context) { - context = this.client.mergeContext(context); - Mono>> mono - = createOrReplaceWithResponseAsync(resourceGroupName, schemaRegistryName, resource, context); - return this.client.getLroResult(mono, this.client.getHttpPipeline(), - SchemaRegistryInner.class, SchemaRegistryInner.class, context); - } - - /** - * Create a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param resource Resource create parameters. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of schema registry definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, SchemaRegistryInner> - beginCreateOrReplace(String resourceGroupName, String schemaRegistryName, SchemaRegistryInner resource) { - return this.beginCreateOrReplaceAsync(resourceGroupName, schemaRegistryName, resource).getSyncPoller(); - } - - /** - * Create a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param resource Resource create parameters. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of schema registry definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, SchemaRegistryInner> beginCreateOrReplace( - String resourceGroupName, String schemaRegistryName, SchemaRegistryInner resource, Context context) { - return this.beginCreateOrReplaceAsync(resourceGroupName, schemaRegistryName, resource, context).getSyncPoller(); - } - - /** - * Create a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param resource Resource create parameters. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema registry definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono createOrReplaceAsync(String resourceGroupName, String schemaRegistryName, - SchemaRegistryInner resource) { - return beginCreateOrReplaceAsync(resourceGroupName, schemaRegistryName, resource).last() - .flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Create a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param resource Resource create parameters. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema registry definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono createOrReplaceAsync(String resourceGroupName, String schemaRegistryName, - SchemaRegistryInner resource, Context context) { - return beginCreateOrReplaceAsync(resourceGroupName, schemaRegistryName, resource, context).last() - .flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Create a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param resource Resource create parameters. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema registry definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SchemaRegistryInner createOrReplace(String resourceGroupName, String schemaRegistryName, - SchemaRegistryInner resource) { - return createOrReplaceAsync(resourceGroupName, schemaRegistryName, resource).block(); - } - - /** - * Create a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param resource Resource create parameters. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema registry definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SchemaRegistryInner createOrReplace(String resourceGroupName, String schemaRegistryName, - SchemaRegistryInner resource, Context context) { - return createOrReplaceAsync(resourceGroupName, schemaRegistryName, resource, context).block(); - } - - /** - * Update a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param properties The resource properties to be updated. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema registry definition along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> updateWithResponseAsync(String resourceGroupName, - String schemaRegistryName, SchemaRegistryUpdate properties) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (schemaRegistryName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaRegistryName is required and cannot be null.")); - } - if (properties == null) { - return Mono.error(new IllegalArgumentException("Parameter properties is required and cannot be null.")); - } else { - properties.validate(); - } - final String contentType = "application/json"; - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.update(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, schemaRegistryName, contentType, accept, properties, - context)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Update a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param properties The resource properties to be updated. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema registry definition along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> updateWithResponseAsync(String resourceGroupName, - String schemaRegistryName, SchemaRegistryUpdate properties, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (schemaRegistryName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaRegistryName is required and cannot be null.")); - } - if (properties == null) { - return Mono.error(new IllegalArgumentException("Parameter properties is required and cannot be null.")); - } else { - properties.validate(); - } - final String contentType = "application/json"; - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.update(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), - resourceGroupName, schemaRegistryName, contentType, accept, properties, context); - } - - /** - * Update a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param properties The resource properties to be updated. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of schema registry definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, SchemaRegistryInner> beginUpdateAsync(String resourceGroupName, - String schemaRegistryName, SchemaRegistryUpdate properties) { - Mono>> mono - = updateWithResponseAsync(resourceGroupName, schemaRegistryName, properties); - return this.client.getLroResult(mono, this.client.getHttpPipeline(), - SchemaRegistryInner.class, SchemaRegistryInner.class, this.client.getContext()); - } - - /** - * Update a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param properties The resource properties to be updated. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of schema registry definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, SchemaRegistryInner> beginUpdateAsync(String resourceGroupName, - String schemaRegistryName, SchemaRegistryUpdate properties, Context context) { - context = this.client.mergeContext(context); - Mono>> mono - = updateWithResponseAsync(resourceGroupName, schemaRegistryName, properties, context); - return this.client.getLroResult(mono, this.client.getHttpPipeline(), - SchemaRegistryInner.class, SchemaRegistryInner.class, context); - } - - /** - * Update a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param properties The resource properties to be updated. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of schema registry definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, SchemaRegistryInner> beginUpdate(String resourceGroupName, - String schemaRegistryName, SchemaRegistryUpdate properties) { - return this.beginUpdateAsync(resourceGroupName, schemaRegistryName, properties).getSyncPoller(); - } - - /** - * Update a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param properties The resource properties to be updated. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of schema registry definition. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, SchemaRegistryInner> beginUpdate(String resourceGroupName, - String schemaRegistryName, SchemaRegistryUpdate properties, Context context) { - return this.beginUpdateAsync(resourceGroupName, schemaRegistryName, properties, context).getSyncPoller(); - } - - /** - * Update a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param properties The resource properties to be updated. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema registry definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono updateAsync(String resourceGroupName, String schemaRegistryName, - SchemaRegistryUpdate properties) { - return beginUpdateAsync(resourceGroupName, schemaRegistryName, properties).last() - .flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Update a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param properties The resource properties to be updated. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema registry definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono updateAsync(String resourceGroupName, String schemaRegistryName, - SchemaRegistryUpdate properties, Context context) { - return beginUpdateAsync(resourceGroupName, schemaRegistryName, properties, context).last() - .flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Update a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param properties The resource properties to be updated. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema registry definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SchemaRegistryInner update(String resourceGroupName, String schemaRegistryName, - SchemaRegistryUpdate properties) { - return updateAsync(resourceGroupName, schemaRegistryName, properties).block(); - } - - /** - * Update a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param properties The resource properties to be updated. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema registry definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SchemaRegistryInner update(String resourceGroupName, String schemaRegistryName, - SchemaRegistryUpdate properties, Context context) { - return updateAsync(resourceGroupName, schemaRegistryName, properties, context).block(); - } - - /** - * Delete a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> deleteWithResponseAsync(String resourceGroupName, - String schemaRegistryName) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (schemaRegistryName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaRegistryName is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.delete(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, schemaRegistryName, accept, context)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Delete a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> deleteWithResponseAsync(String resourceGroupName, - String schemaRegistryName, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (schemaRegistryName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaRegistryName is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.delete(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), - resourceGroupName, schemaRegistryName, accept, context); - } - - /** - * Delete a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of long-running operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, Void> beginDeleteAsync(String resourceGroupName, String schemaRegistryName) { - Mono>> mono = deleteWithResponseAsync(resourceGroupName, schemaRegistryName); - return this.client.getLroResult(mono, this.client.getHttpPipeline(), Void.class, Void.class, - this.client.getContext()); - } - - /** - * Delete a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of long-running operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, Void> beginDeleteAsync(String resourceGroupName, String schemaRegistryName, - Context context) { - context = this.client.mergeContext(context); - Mono>> mono = deleteWithResponseAsync(resourceGroupName, schemaRegistryName, context); - return this.client.getLroResult(mono, this.client.getHttpPipeline(), Void.class, Void.class, - context); - } - - /** - * Delete a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of long-running operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, Void> beginDelete(String resourceGroupName, String schemaRegistryName) { - return this.beginDeleteAsync(resourceGroupName, schemaRegistryName).getSyncPoller(); - } - - /** - * Delete a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of long-running operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, Void> beginDelete(String resourceGroupName, String schemaRegistryName, - Context context) { - return this.beginDeleteAsync(resourceGroupName, schemaRegistryName, context).getSyncPoller(); - } - - /** - * Delete a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono deleteAsync(String resourceGroupName, String schemaRegistryName) { - return beginDeleteAsync(resourceGroupName, schemaRegistryName).last() - .flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Delete a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono deleteAsync(String resourceGroupName, String schemaRegistryName, Context context) { - return beginDeleteAsync(resourceGroupName, schemaRegistryName, context).last() - .flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Delete a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void delete(String resourceGroupName, String schemaRegistryName) { - deleteAsync(resourceGroupName, schemaRegistryName).block(); - } - - /** - * Delete a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void delete(String resourceGroupName, String schemaRegistryName, Context context) { - deleteAsync(resourceGroupName, schemaRegistryName, context).block(); - } - - /** - * List SchemaRegistry resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaRegistry list operation along with {@link PagedResponse} on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listByResourceGroupSinglePageAsync(String resourceGroupName) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.listByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), - res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * List SchemaRegistry resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaRegistry list operation along with {@link PagedResponse} on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listByResourceGroupSinglePageAsync(String resourceGroupName, - Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service - .listByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } - - /** - * List SchemaRegistry resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaRegistry list operation as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listByResourceGroupAsync(String resourceGroupName) { - return new PagedFlux<>(() -> listByResourceGroupSinglePageAsync(resourceGroupName), - nextLink -> listByResourceGroupNextSinglePageAsync(nextLink)); - } - - /** - * List SchemaRegistry resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaRegistry list operation as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listByResourceGroupAsync(String resourceGroupName, Context context) { - return new PagedFlux<>(() -> listByResourceGroupSinglePageAsync(resourceGroupName, context), - nextLink -> listByResourceGroupNextSinglePageAsync(nextLink, context)); - } - - /** - * List SchemaRegistry resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaRegistry list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listByResourceGroup(String resourceGroupName) { - return new PagedIterable<>(listByResourceGroupAsync(resourceGroupName)); - } - - /** - * List SchemaRegistry resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaRegistry list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listByResourceGroup(String resourceGroupName, Context context) { - return new PagedIterable<>(listByResourceGroupAsync(resourceGroupName, context)); - } - - /** - * List SchemaRegistry resources by subscription ID. - * - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaRegistry list operation along with {@link PagedResponse} on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listSinglePageAsync() { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.list(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), - res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * List SchemaRegistry resources by subscription ID. - * - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaRegistry list operation along with {@link PagedResponse} on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listSinglePageAsync(Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service - .list(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), accept, - context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } - - /** - * List SchemaRegistry resources by subscription ID. - * - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaRegistry list operation as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listAsync() { - return new PagedFlux<>(() -> listSinglePageAsync(), - nextLink -> listBySubscriptionNextSinglePageAsync(nextLink)); - } - - /** - * List SchemaRegistry resources by subscription ID. - * - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaRegistry list operation as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listAsync(Context context) { - return new PagedFlux<>(() -> listSinglePageAsync(context), - nextLink -> listBySubscriptionNextSinglePageAsync(nextLink, context)); - } - - /** - * List SchemaRegistry resources by subscription ID. - * - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaRegistry list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list() { - return new PagedIterable<>(listAsync()); - } - - /** - * List SchemaRegistry resources by subscription ID. - * - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaRegistry list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list(Context context) { - return new PagedIterable<>(listAsync(context)); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaRegistry list operation along with {@link PagedResponse} on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listByResourceGroupNextSinglePageAsync(String nextLink) { - if (nextLink == null) { - return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - } - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext( - context -> service.listByResourceGroupNext(nextLink, this.client.getEndpoint(), accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), - res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaRegistry list operation along with {@link PagedResponse} on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listByResourceGroupNextSinglePageAsync(String nextLink, - Context context) { - if (nextLink == null) { - return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - } - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.listByResourceGroupNext(nextLink, this.client.getEndpoint(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaRegistry list operation along with {@link PagedResponse} on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listBySubscriptionNextSinglePageAsync(String nextLink) { - if (nextLink == null) { - return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - } - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext( - context -> service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), - res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaRegistry list operation along with {@link PagedResponse} on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listBySubscriptionNextSinglePageAsync(String nextLink, - Context context) { - if (nextLink == null) { - return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - } - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/SchemaRegistriesImpl.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/SchemaRegistriesImpl.java deleted file mode 100644 index b5aa03b8e1a1..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/SchemaRegistriesImpl.java +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.implementation; - -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.SimpleResponse; -import com.azure.core.util.Context; -import com.azure.core.util.logging.ClientLogger; -import com.azure.resourcemanager.deviceregistry.fluent.SchemaRegistriesClient; -import com.azure.resourcemanager.deviceregistry.fluent.models.SchemaRegistryInner; -import com.azure.resourcemanager.deviceregistry.models.SchemaRegistries; -import com.azure.resourcemanager.deviceregistry.models.SchemaRegistry; - -public final class SchemaRegistriesImpl implements SchemaRegistries { - private static final ClientLogger LOGGER = new ClientLogger(SchemaRegistriesImpl.class); - - private final SchemaRegistriesClient innerClient; - - private final com.azure.resourcemanager.deviceregistry.DeviceRegistryManager serviceManager; - - public SchemaRegistriesImpl(SchemaRegistriesClient innerClient, - com.azure.resourcemanager.deviceregistry.DeviceRegistryManager serviceManager) { - this.innerClient = innerClient; - this.serviceManager = serviceManager; - } - - public Response getByResourceGroupWithResponse(String resourceGroupName, String schemaRegistryName, - Context context) { - Response inner - = this.serviceClient().getByResourceGroupWithResponse(resourceGroupName, schemaRegistryName, context); - if (inner != null) { - return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), - new SchemaRegistryImpl(inner.getValue(), this.manager())); - } else { - return null; - } - } - - public SchemaRegistry getByResourceGroup(String resourceGroupName, String schemaRegistryName) { - SchemaRegistryInner inner = this.serviceClient().getByResourceGroup(resourceGroupName, schemaRegistryName); - if (inner != null) { - return new SchemaRegistryImpl(inner, this.manager()); - } else { - return null; - } - } - - public void deleteByResourceGroup(String resourceGroupName, String schemaRegistryName) { - this.serviceClient().delete(resourceGroupName, schemaRegistryName); - } - - public void delete(String resourceGroupName, String schemaRegistryName, Context context) { - this.serviceClient().delete(resourceGroupName, schemaRegistryName, context); - } - - public PagedIterable listByResourceGroup(String resourceGroupName) { - PagedIterable inner = this.serviceClient().listByResourceGroup(resourceGroupName); - return ResourceManagerUtils.mapPage(inner, inner1 -> new SchemaRegistryImpl(inner1, this.manager())); - } - - public PagedIterable listByResourceGroup(String resourceGroupName, Context context) { - PagedIterable inner = this.serviceClient().listByResourceGroup(resourceGroupName, context); - return ResourceManagerUtils.mapPage(inner, inner1 -> new SchemaRegistryImpl(inner1, this.manager())); - } - - public PagedIterable list() { - PagedIterable inner = this.serviceClient().list(); - return ResourceManagerUtils.mapPage(inner, inner1 -> new SchemaRegistryImpl(inner1, this.manager())); - } - - public PagedIterable list(Context context) { - PagedIterable inner = this.serviceClient().list(context); - return ResourceManagerUtils.mapPage(inner, inner1 -> new SchemaRegistryImpl(inner1, this.manager())); - } - - public SchemaRegistry getById(String id) { - String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); - if (resourceGroupName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); - } - String schemaRegistryName = ResourceManagerUtils.getValueFromIdByName(id, "schemaRegistries"); - if (schemaRegistryName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'schemaRegistries'.", id))); - } - return this.getByResourceGroupWithResponse(resourceGroupName, schemaRegistryName, Context.NONE).getValue(); - } - - public Response getByIdWithResponse(String id, Context context) { - String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); - if (resourceGroupName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); - } - String schemaRegistryName = ResourceManagerUtils.getValueFromIdByName(id, "schemaRegistries"); - if (schemaRegistryName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'schemaRegistries'.", id))); - } - return this.getByResourceGroupWithResponse(resourceGroupName, schemaRegistryName, context); - } - - public void deleteById(String id) { - String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); - if (resourceGroupName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); - } - String schemaRegistryName = ResourceManagerUtils.getValueFromIdByName(id, "schemaRegistries"); - if (schemaRegistryName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'schemaRegistries'.", id))); - } - this.delete(resourceGroupName, schemaRegistryName, Context.NONE); - } - - public void deleteByIdWithResponse(String id, Context context) { - String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); - if (resourceGroupName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); - } - String schemaRegistryName = ResourceManagerUtils.getValueFromIdByName(id, "schemaRegistries"); - if (schemaRegistryName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'schemaRegistries'.", id))); - } - this.delete(resourceGroupName, schemaRegistryName, context); - } - - private SchemaRegistriesClient serviceClient() { - return this.innerClient; - } - - private com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager() { - return this.serviceManager; - } - - public SchemaRegistryImpl define(String name) { - return new SchemaRegistryImpl(name, this.manager()); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/SchemaRegistryImpl.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/SchemaRegistryImpl.java deleted file mode 100644 index 91428a0ac6ee..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/SchemaRegistryImpl.java +++ /dev/null @@ -1,198 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.implementation; - -import com.azure.core.management.Region; -import com.azure.core.management.SystemData; -import com.azure.core.util.Context; -import com.azure.resourcemanager.deviceregistry.fluent.models.SchemaRegistryInner; -import com.azure.resourcemanager.deviceregistry.models.SchemaRegistry; -import com.azure.resourcemanager.deviceregistry.models.SchemaRegistryProperties; -import com.azure.resourcemanager.deviceregistry.models.SchemaRegistryUpdate; -import com.azure.resourcemanager.deviceregistry.models.SchemaRegistryUpdateProperties; -import com.azure.resourcemanager.deviceregistry.models.SystemAssignedServiceIdentity; -import java.util.Collections; -import java.util.Map; - -public final class SchemaRegistryImpl implements SchemaRegistry, SchemaRegistry.Definition, SchemaRegistry.Update { - private SchemaRegistryInner innerObject; - - private final com.azure.resourcemanager.deviceregistry.DeviceRegistryManager serviceManager; - - public String id() { - return this.innerModel().id(); - } - - public String name() { - return this.innerModel().name(); - } - - public String type() { - return this.innerModel().type(); - } - - public String location() { - return this.innerModel().location(); - } - - public Map tags() { - Map inner = this.innerModel().tags(); - if (inner != null) { - return Collections.unmodifiableMap(inner); - } else { - return Collections.emptyMap(); - } - } - - public SchemaRegistryProperties properties() { - return this.innerModel().properties(); - } - - public SystemAssignedServiceIdentity identity() { - return this.innerModel().identity(); - } - - public SystemData systemData() { - return this.innerModel().systemData(); - } - - public Region region() { - return Region.fromName(this.regionName()); - } - - public String regionName() { - return this.location(); - } - - public String resourceGroupName() { - return resourceGroupName; - } - - public SchemaRegistryInner innerModel() { - return this.innerObject; - } - - private com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager() { - return this.serviceManager; - } - - private String resourceGroupName; - - private String schemaRegistryName; - - private SchemaRegistryUpdate updateProperties; - - public SchemaRegistryImpl withExistingResourceGroup(String resourceGroupName) { - this.resourceGroupName = resourceGroupName; - return this; - } - - public SchemaRegistry create() { - this.innerObject = serviceManager.serviceClient() - .getSchemaRegistries() - .createOrReplace(resourceGroupName, schemaRegistryName, this.innerModel(), Context.NONE); - return this; - } - - public SchemaRegistry create(Context context) { - this.innerObject = serviceManager.serviceClient() - .getSchemaRegistries() - .createOrReplace(resourceGroupName, schemaRegistryName, this.innerModel(), context); - return this; - } - - SchemaRegistryImpl(String name, com.azure.resourcemanager.deviceregistry.DeviceRegistryManager serviceManager) { - this.innerObject = new SchemaRegistryInner(); - this.serviceManager = serviceManager; - this.schemaRegistryName = name; - } - - public SchemaRegistryImpl update() { - this.updateProperties = new SchemaRegistryUpdate(); - return this; - } - - public SchemaRegistry apply() { - this.innerObject = serviceManager.serviceClient() - .getSchemaRegistries() - .update(resourceGroupName, schemaRegistryName, updateProperties, Context.NONE); - return this; - } - - public SchemaRegistry apply(Context context) { - this.innerObject = serviceManager.serviceClient() - .getSchemaRegistries() - .update(resourceGroupName, schemaRegistryName, updateProperties, context); - return this; - } - - SchemaRegistryImpl(SchemaRegistryInner innerObject, - com.azure.resourcemanager.deviceregistry.DeviceRegistryManager serviceManager) { - this.innerObject = innerObject; - this.serviceManager = serviceManager; - this.resourceGroupName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "resourceGroups"); - this.schemaRegistryName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "schemaRegistries"); - } - - public SchemaRegistry refresh() { - this.innerObject = serviceManager.serviceClient() - .getSchemaRegistries() - .getByResourceGroupWithResponse(resourceGroupName, schemaRegistryName, Context.NONE) - .getValue(); - return this; - } - - public SchemaRegistry refresh(Context context) { - this.innerObject = serviceManager.serviceClient() - .getSchemaRegistries() - .getByResourceGroupWithResponse(resourceGroupName, schemaRegistryName, context) - .getValue(); - return this; - } - - public SchemaRegistryImpl withRegion(Region location) { - this.innerModel().withLocation(location.toString()); - return this; - } - - public SchemaRegistryImpl withRegion(String location) { - this.innerModel().withLocation(location); - return this; - } - - public SchemaRegistryImpl withTags(Map tags) { - if (isInCreateMode()) { - this.innerModel().withTags(tags); - return this; - } else { - this.updateProperties.withTags(tags); - return this; - } - } - - public SchemaRegistryImpl withProperties(SchemaRegistryProperties properties) { - this.innerModel().withProperties(properties); - return this; - } - - public SchemaRegistryImpl withIdentity(SystemAssignedServiceIdentity identity) { - if (isInCreateMode()) { - this.innerModel().withIdentity(identity); - return this; - } else { - this.updateProperties.withIdentity(identity); - return this; - } - } - - public SchemaRegistryImpl withProperties(SchemaRegistryUpdateProperties properties) { - this.updateProperties.withProperties(properties); - return this; - } - - private boolean isInCreateMode() { - return this.innerModel().id() == null; - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/SchemaVersionImpl.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/SchemaVersionImpl.java deleted file mode 100644 index 942a8c00390b..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/SchemaVersionImpl.java +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.implementation; - -import com.azure.core.management.SystemData; -import com.azure.core.util.Context; -import com.azure.resourcemanager.deviceregistry.fluent.models.SchemaVersionInner; -import com.azure.resourcemanager.deviceregistry.models.SchemaVersion; -import com.azure.resourcemanager.deviceregistry.models.SchemaVersionProperties; - -public final class SchemaVersionImpl implements SchemaVersion, SchemaVersion.Definition { - private SchemaVersionInner innerObject; - - private final com.azure.resourcemanager.deviceregistry.DeviceRegistryManager serviceManager; - - SchemaVersionImpl(SchemaVersionInner innerObject, - com.azure.resourcemanager.deviceregistry.DeviceRegistryManager serviceManager) { - this.innerObject = innerObject; - this.serviceManager = serviceManager; - } - - public String id() { - return this.innerModel().id(); - } - - public String name() { - return this.innerModel().name(); - } - - public String type() { - return this.innerModel().type(); - } - - public SchemaVersionProperties properties() { - return this.innerModel().properties(); - } - - public SystemData systemData() { - return this.innerModel().systemData(); - } - - public SchemaVersionInner innerModel() { - return this.innerObject; - } - - private com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager() { - return this.serviceManager; - } - - private String resourceGroupName; - - private String schemaRegistryName; - - private String schemaName; - - private String schemaVersionName; - - public SchemaVersionImpl withExistingSchema(String resourceGroupName, String schemaRegistryName, - String schemaName) { - this.resourceGroupName = resourceGroupName; - this.schemaRegistryName = schemaRegistryName; - this.schemaName = schemaName; - return this; - } - - public SchemaVersion create() { - this.innerObject = serviceManager.serviceClient() - .getSchemaVersions() - .createOrReplaceWithResponse(resourceGroupName, schemaRegistryName, schemaName, schemaVersionName, - this.innerModel(), Context.NONE) - .getValue(); - return this; - } - - public SchemaVersion create(Context context) { - this.innerObject = serviceManager.serviceClient() - .getSchemaVersions() - .createOrReplaceWithResponse(resourceGroupName, schemaRegistryName, schemaName, schemaVersionName, - this.innerModel(), context) - .getValue(); - return this; - } - - SchemaVersionImpl(String name, com.azure.resourcemanager.deviceregistry.DeviceRegistryManager serviceManager) { - this.innerObject = new SchemaVersionInner(); - this.serviceManager = serviceManager; - this.schemaVersionName = name; - } - - public SchemaVersion refresh() { - this.innerObject = serviceManager.serviceClient() - .getSchemaVersions() - .getWithResponse(resourceGroupName, schemaRegistryName, schemaName, schemaVersionName, Context.NONE) - .getValue(); - return this; - } - - public SchemaVersion refresh(Context context) { - this.innerObject = serviceManager.serviceClient() - .getSchemaVersions() - .getWithResponse(resourceGroupName, schemaRegistryName, schemaName, schemaVersionName, context) - .getValue(); - return this; - } - - public SchemaVersionImpl withProperties(SchemaVersionProperties properties) { - this.innerModel().withProperties(properties); - return this; - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/SchemaVersionsClientImpl.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/SchemaVersionsClientImpl.java deleted file mode 100644 index d2adc087fef1..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/SchemaVersionsClientImpl.java +++ /dev/null @@ -1,797 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.implementation; - -import com.azure.core.annotation.BodyParam; -import com.azure.core.annotation.Delete; -import com.azure.core.annotation.ExpectedResponses; -import com.azure.core.annotation.Get; -import com.azure.core.annotation.HeaderParam; -import com.azure.core.annotation.Headers; -import com.azure.core.annotation.Host; -import com.azure.core.annotation.HostParam; -import com.azure.core.annotation.PathParam; -import com.azure.core.annotation.Put; -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.PagedFlux; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.PagedResponse; -import com.azure.core.http.rest.PagedResponseBase; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.RestProxy; -import com.azure.core.management.exception.ManagementException; -import com.azure.core.util.Context; -import com.azure.core.util.FluxUtil; -import com.azure.resourcemanager.deviceregistry.fluent.SchemaVersionsClient; -import com.azure.resourcemanager.deviceregistry.fluent.models.SchemaVersionInner; -import com.azure.resourcemanager.deviceregistry.implementation.models.SchemaVersionListResult; -import reactor.core.publisher.Mono; - -/** - * An instance of this class provides access to all the operations defined in SchemaVersionsClient. - */ -public final class SchemaVersionsClientImpl implements SchemaVersionsClient { - /** - * The proxy service used to perform REST calls. - */ - private final SchemaVersionsService service; - - /** - * The service client containing this operation class. - */ - private final DeviceRegistryManagementClientImpl client; - - /** - * Initializes an instance of SchemaVersionsClientImpl. - * - * @param client the instance of the service client containing this operation class. - */ - SchemaVersionsClientImpl(DeviceRegistryManagementClientImpl client) { - this.service - = RestProxy.create(SchemaVersionsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); - this.client = client; - } - - /** - * The interface defining all the services for DeviceRegistryManagementClientSchemaVersions to be used by the proxy - * service to perform REST calls. - */ - @Host("{endpoint}") - @ServiceInterface(name = "DeviceRegistryManage") - public interface SchemaVersionsService { - @Headers({ "Content-Type: application/json" }) - @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DeviceRegistry/schemaRegistries/{schemaRegistryName}/schemas/{schemaName}/schemaVersions/{schemaVersionName}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> get(@HostParam("endpoint") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, - @PathParam("schemaRegistryName") String schemaRegistryName, @PathParam("schemaName") String schemaName, - @PathParam("schemaVersionName") String schemaVersionName, @HeaderParam("Accept") String accept, - Context context); - - @Put("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DeviceRegistry/schemaRegistries/{schemaRegistryName}/schemas/{schemaName}/schemaVersions/{schemaVersionName}") - @ExpectedResponses({ 200, 201 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> createOrReplace(@HostParam("endpoint") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, - @PathParam("schemaRegistryName") String schemaRegistryName, @PathParam("schemaName") String schemaName, - @PathParam("schemaVersionName") String schemaVersionName, @HeaderParam("Content-Type") String contentType, - @HeaderParam("Accept") String accept, @BodyParam("application/json") SchemaVersionInner resource, - Context context); - - @Headers({ "Content-Type: application/json" }) - @Delete("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DeviceRegistry/schemaRegistries/{schemaRegistryName}/schemas/{schemaName}/schemaVersions/{schemaVersionName}") - @ExpectedResponses({ 200, 204 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> delete(@HostParam("endpoint") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, - @PathParam("schemaRegistryName") String schemaRegistryName, @PathParam("schemaName") String schemaName, - @PathParam("schemaVersionName") String schemaVersionName, @HeaderParam("Accept") String accept, - Context context); - - @Headers({ "Content-Type: application/json" }) - @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DeviceRegistry/schemaRegistries/{schemaRegistryName}/schemas/{schemaName}/schemaVersions") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> listBySchema(@HostParam("endpoint") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, - @PathParam("schemaRegistryName") String schemaRegistryName, @PathParam("schemaName") String schemaName, - @HeaderParam("Accept") String accept, Context context); - - @Headers({ "Content-Type: application/json" }) - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> listBySchemaNext( - @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, - @HeaderParam("Accept") String accept, Context context); - } - - /** - * Get a SchemaVersion. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param schemaVersionName Schema version name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a SchemaVersion along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> getWithResponseAsync(String resourceGroupName, String schemaRegistryName, - String schemaName, String schemaVersionName) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (schemaRegistryName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaRegistryName is required and cannot be null.")); - } - if (schemaName == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); - } - if (schemaVersionName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaVersionName is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, schemaRegistryName, schemaName, schemaVersionName, - accept, context)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Get a SchemaVersion. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param schemaVersionName Schema version name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a SchemaVersion along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> getWithResponseAsync(String resourceGroupName, String schemaRegistryName, - String schemaName, String schemaVersionName, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (schemaRegistryName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaRegistryName is required and cannot be null.")); - } - if (schemaName == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); - } - if (schemaVersionName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaVersionName is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), - resourceGroupName, schemaRegistryName, schemaName, schemaVersionName, accept, context); - } - - /** - * Get a SchemaVersion. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param schemaVersionName Schema version name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a SchemaVersion on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono getAsync(String resourceGroupName, String schemaRegistryName, String schemaName, - String schemaVersionName) { - return getWithResponseAsync(resourceGroupName, schemaRegistryName, schemaName, schemaVersionName) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Get a SchemaVersion. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param schemaVersionName Schema version name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a SchemaVersion along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getWithResponse(String resourceGroupName, String schemaRegistryName, - String schemaName, String schemaVersionName, Context context) { - return getWithResponseAsync(resourceGroupName, schemaRegistryName, schemaName, schemaVersionName, context) - .block(); - } - - /** - * Get a SchemaVersion. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param schemaVersionName Schema version name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a SchemaVersion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SchemaVersionInner get(String resourceGroupName, String schemaRegistryName, String schemaName, - String schemaVersionName) { - return getWithResponse(resourceGroupName, schemaRegistryName, schemaName, schemaVersionName, Context.NONE) - .getValue(); - } - - /** - * Create a SchemaVersion. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param schemaVersionName Schema version name parameter. - * @param resource Resource create parameters. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema version's definition along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> createOrReplaceWithResponseAsync(String resourceGroupName, - String schemaRegistryName, String schemaName, String schemaVersionName, SchemaVersionInner resource) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (schemaRegistryName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaRegistryName is required and cannot be null.")); - } - if (schemaName == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); - } - if (schemaVersionName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaVersionName is required and cannot be null.")); - } - if (resource == null) { - return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); - } else { - resource.validate(); - } - final String contentType = "application/json"; - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.createOrReplace(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, schemaRegistryName, schemaName, schemaVersionName, - contentType, accept, resource, context)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Create a SchemaVersion. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param schemaVersionName Schema version name parameter. - * @param resource Resource create parameters. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema version's definition along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> createOrReplaceWithResponseAsync(String resourceGroupName, - String schemaRegistryName, String schemaName, String schemaVersionName, SchemaVersionInner resource, - Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (schemaRegistryName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaRegistryName is required and cannot be null.")); - } - if (schemaName == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); - } - if (schemaVersionName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaVersionName is required and cannot be null.")); - } - if (resource == null) { - return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); - } else { - resource.validate(); - } - final String contentType = "application/json"; - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.createOrReplace(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, schemaRegistryName, schemaName, schemaVersionName, - contentType, accept, resource, context); - } - - /** - * Create a SchemaVersion. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param schemaVersionName Schema version name parameter. - * @param resource Resource create parameters. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema version's definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono createOrReplaceAsync(String resourceGroupName, String schemaRegistryName, - String schemaName, String schemaVersionName, SchemaVersionInner resource) { - return createOrReplaceWithResponseAsync(resourceGroupName, schemaRegistryName, schemaName, schemaVersionName, - resource).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Create a SchemaVersion. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param schemaVersionName Schema version name parameter. - * @param resource Resource create parameters. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema version's definition along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createOrReplaceWithResponse(String resourceGroupName, String schemaRegistryName, - String schemaName, String schemaVersionName, SchemaVersionInner resource, Context context) { - return createOrReplaceWithResponseAsync(resourceGroupName, schemaRegistryName, schemaName, schemaVersionName, - resource, context).block(); - } - - /** - * Create a SchemaVersion. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param schemaVersionName Schema version name parameter. - * @param resource Resource create parameters. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema version's definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SchemaVersionInner createOrReplace(String resourceGroupName, String schemaRegistryName, String schemaName, - String schemaVersionName, SchemaVersionInner resource) { - return createOrReplaceWithResponse(resourceGroupName, schemaRegistryName, schemaName, schemaVersionName, - resource, Context.NONE).getValue(); - } - - /** - * Delete a SchemaVersion. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param schemaVersionName Schema version name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> deleteWithResponseAsync(String resourceGroupName, String schemaRegistryName, - String schemaName, String schemaVersionName) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (schemaRegistryName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaRegistryName is required and cannot be null.")); - } - if (schemaName == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); - } - if (schemaVersionName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaVersionName is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.delete(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, schemaRegistryName, schemaName, schemaVersionName, - accept, context)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Delete a SchemaVersion. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param schemaVersionName Schema version name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> deleteWithResponseAsync(String resourceGroupName, String schemaRegistryName, - String schemaName, String schemaVersionName, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (schemaRegistryName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaRegistryName is required and cannot be null.")); - } - if (schemaName == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); - } - if (schemaVersionName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaVersionName is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.delete(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), - resourceGroupName, schemaRegistryName, schemaName, schemaVersionName, accept, context); - } - - /** - * Delete a SchemaVersion. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param schemaVersionName Schema version name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono deleteAsync(String resourceGroupName, String schemaRegistryName, String schemaName, - String schemaVersionName) { - return deleteWithResponseAsync(resourceGroupName, schemaRegistryName, schemaName, schemaVersionName) - .flatMap(ignored -> Mono.empty()); - } - - /** - * Delete a SchemaVersion. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param schemaVersionName Schema version name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteWithResponse(String resourceGroupName, String schemaRegistryName, String schemaName, - String schemaVersionName, Context context) { - return deleteWithResponseAsync(resourceGroupName, schemaRegistryName, schemaName, schemaVersionName, context) - .block(); - } - - /** - * Delete a SchemaVersion. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param schemaVersionName Schema version name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void delete(String resourceGroupName, String schemaRegistryName, String schemaName, - String schemaVersionName) { - deleteWithResponse(resourceGroupName, schemaRegistryName, schemaName, schemaVersionName, Context.NONE); - } - - /** - * List SchemaVersion resources by Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaVersion list operation along with {@link PagedResponse} on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listBySchemaSinglePageAsync(String resourceGroupName, - String schemaRegistryName, String schemaName) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (schemaRegistryName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaRegistryName is required and cannot be null.")); - } - if (schemaName == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.listBySchema(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, schemaRegistryName, schemaName, accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), - res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * List SchemaVersion resources by Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaVersion list operation along with {@link PagedResponse} on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listBySchemaSinglePageAsync(String resourceGroupName, - String schemaRegistryName, String schemaName, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (schemaRegistryName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaRegistryName is required and cannot be null.")); - } - if (schemaName == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service - .listBySchema(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), - resourceGroupName, schemaRegistryName, schemaName, accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } - - /** - * List SchemaVersion resources by Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaVersion list operation as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listBySchemaAsync(String resourceGroupName, String schemaRegistryName, - String schemaName) { - return new PagedFlux<>(() -> listBySchemaSinglePageAsync(resourceGroupName, schemaRegistryName, schemaName), - nextLink -> listBySchemaNextSinglePageAsync(nextLink)); - } - - /** - * List SchemaVersion resources by Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaVersion list operation as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listBySchemaAsync(String resourceGroupName, String schemaRegistryName, - String schemaName, Context context) { - return new PagedFlux<>( - () -> listBySchemaSinglePageAsync(resourceGroupName, schemaRegistryName, schemaName, context), - nextLink -> listBySchemaNextSinglePageAsync(nextLink, context)); - } - - /** - * List SchemaVersion resources by Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaVersion list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listBySchema(String resourceGroupName, String schemaRegistryName, - String schemaName) { - return new PagedIterable<>(listBySchemaAsync(resourceGroupName, schemaRegistryName, schemaName)); - } - - /** - * List SchemaVersion resources by Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaVersion list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listBySchema(String resourceGroupName, String schemaRegistryName, - String schemaName, Context context) { - return new PagedIterable<>(listBySchemaAsync(resourceGroupName, schemaRegistryName, schemaName, context)); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaVersion list operation along with {@link PagedResponse} on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listBySchemaNextSinglePageAsync(String nextLink) { - if (nextLink == null) { - return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - } - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.listBySchemaNext(nextLink, this.client.getEndpoint(), accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), - res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaVersion list operation along with {@link PagedResponse} on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listBySchemaNextSinglePageAsync(String nextLink, Context context) { - if (nextLink == null) { - return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - } - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.listBySchemaNext(nextLink, this.client.getEndpoint(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/SchemaVersionsImpl.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/SchemaVersionsImpl.java deleted file mode 100644 index cd010688dbf6..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/SchemaVersionsImpl.java +++ /dev/null @@ -1,186 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.implementation; - -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.SimpleResponse; -import com.azure.core.util.Context; -import com.azure.core.util.logging.ClientLogger; -import com.azure.resourcemanager.deviceregistry.fluent.SchemaVersionsClient; -import com.azure.resourcemanager.deviceregistry.fluent.models.SchemaVersionInner; -import com.azure.resourcemanager.deviceregistry.models.SchemaVersion; -import com.azure.resourcemanager.deviceregistry.models.SchemaVersions; - -public final class SchemaVersionsImpl implements SchemaVersions { - private static final ClientLogger LOGGER = new ClientLogger(SchemaVersionsImpl.class); - - private final SchemaVersionsClient innerClient; - - private final com.azure.resourcemanager.deviceregistry.DeviceRegistryManager serviceManager; - - public SchemaVersionsImpl(SchemaVersionsClient innerClient, - com.azure.resourcemanager.deviceregistry.DeviceRegistryManager serviceManager) { - this.innerClient = innerClient; - this.serviceManager = serviceManager; - } - - public Response getWithResponse(String resourceGroupName, String schemaRegistryName, - String schemaName, String schemaVersionName, Context context) { - Response inner = this.serviceClient() - .getWithResponse(resourceGroupName, schemaRegistryName, schemaName, schemaVersionName, context); - if (inner != null) { - return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), - new SchemaVersionImpl(inner.getValue(), this.manager())); - } else { - return null; - } - } - - public SchemaVersion get(String resourceGroupName, String schemaRegistryName, String schemaName, - String schemaVersionName) { - SchemaVersionInner inner - = this.serviceClient().get(resourceGroupName, schemaRegistryName, schemaName, schemaVersionName); - if (inner != null) { - return new SchemaVersionImpl(inner, this.manager()); - } else { - return null; - } - } - - public Response deleteWithResponse(String resourceGroupName, String schemaRegistryName, String schemaName, - String schemaVersionName, Context context) { - return this.serviceClient() - .deleteWithResponse(resourceGroupName, schemaRegistryName, schemaName, schemaVersionName, context); - } - - public void delete(String resourceGroupName, String schemaRegistryName, String schemaName, - String schemaVersionName) { - this.serviceClient().delete(resourceGroupName, schemaRegistryName, schemaName, schemaVersionName); - } - - public PagedIterable listBySchema(String resourceGroupName, String schemaRegistryName, - String schemaName) { - PagedIterable inner - = this.serviceClient().listBySchema(resourceGroupName, schemaRegistryName, schemaName); - return ResourceManagerUtils.mapPage(inner, inner1 -> new SchemaVersionImpl(inner1, this.manager())); - } - - public PagedIterable listBySchema(String resourceGroupName, String schemaRegistryName, - String schemaName, Context context) { - PagedIterable inner - = this.serviceClient().listBySchema(resourceGroupName, schemaRegistryName, schemaName, context); - return ResourceManagerUtils.mapPage(inner, inner1 -> new SchemaVersionImpl(inner1, this.manager())); - } - - public SchemaVersion getById(String id) { - String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); - if (resourceGroupName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); - } - String schemaRegistryName = ResourceManagerUtils.getValueFromIdByName(id, "schemaRegistries"); - if (schemaRegistryName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'schemaRegistries'.", id))); - } - String schemaName = ResourceManagerUtils.getValueFromIdByName(id, "schemas"); - if (schemaName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'schemas'.", id))); - } - String schemaVersionName = ResourceManagerUtils.getValueFromIdByName(id, "schemaVersions"); - if (schemaVersionName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'schemaVersions'.", id))); - } - return this.getWithResponse(resourceGroupName, schemaRegistryName, schemaName, schemaVersionName, Context.NONE) - .getValue(); - } - - public Response getByIdWithResponse(String id, Context context) { - String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); - if (resourceGroupName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); - } - String schemaRegistryName = ResourceManagerUtils.getValueFromIdByName(id, "schemaRegistries"); - if (schemaRegistryName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'schemaRegistries'.", id))); - } - String schemaName = ResourceManagerUtils.getValueFromIdByName(id, "schemas"); - if (schemaName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'schemas'.", id))); - } - String schemaVersionName = ResourceManagerUtils.getValueFromIdByName(id, "schemaVersions"); - if (schemaVersionName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'schemaVersions'.", id))); - } - return this.getWithResponse(resourceGroupName, schemaRegistryName, schemaName, schemaVersionName, context); - } - - public void deleteById(String id) { - String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); - if (resourceGroupName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); - } - String schemaRegistryName = ResourceManagerUtils.getValueFromIdByName(id, "schemaRegistries"); - if (schemaRegistryName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'schemaRegistries'.", id))); - } - String schemaName = ResourceManagerUtils.getValueFromIdByName(id, "schemas"); - if (schemaName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'schemas'.", id))); - } - String schemaVersionName = ResourceManagerUtils.getValueFromIdByName(id, "schemaVersions"); - if (schemaVersionName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'schemaVersions'.", id))); - } - this.deleteWithResponse(resourceGroupName, schemaRegistryName, schemaName, schemaVersionName, Context.NONE); - } - - public Response deleteByIdWithResponse(String id, Context context) { - String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); - if (resourceGroupName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); - } - String schemaRegistryName = ResourceManagerUtils.getValueFromIdByName(id, "schemaRegistries"); - if (schemaRegistryName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'schemaRegistries'.", id))); - } - String schemaName = ResourceManagerUtils.getValueFromIdByName(id, "schemas"); - if (schemaName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'schemas'.", id))); - } - String schemaVersionName = ResourceManagerUtils.getValueFromIdByName(id, "schemaVersions"); - if (schemaVersionName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'schemaVersions'.", id))); - } - return this.deleteWithResponse(resourceGroupName, schemaRegistryName, schemaName, schemaVersionName, context); - } - - private SchemaVersionsClient serviceClient() { - return this.innerClient; - } - - private com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager() { - return this.serviceManager; - } - - public SchemaVersionImpl define(String name) { - return new SchemaVersionImpl(name, this.manager()); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/SchemasClientImpl.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/SchemasClientImpl.java deleted file mode 100644 index d678c0266990..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/SchemasClientImpl.java +++ /dev/null @@ -1,731 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.implementation; - -import com.azure.core.annotation.BodyParam; -import com.azure.core.annotation.Delete; -import com.azure.core.annotation.ExpectedResponses; -import com.azure.core.annotation.Get; -import com.azure.core.annotation.HeaderParam; -import com.azure.core.annotation.Headers; -import com.azure.core.annotation.Host; -import com.azure.core.annotation.HostParam; -import com.azure.core.annotation.PathParam; -import com.azure.core.annotation.Put; -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.PagedFlux; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.PagedResponse; -import com.azure.core.http.rest.PagedResponseBase; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.RestProxy; -import com.azure.core.management.exception.ManagementException; -import com.azure.core.util.Context; -import com.azure.core.util.FluxUtil; -import com.azure.resourcemanager.deviceregistry.fluent.SchemasClient; -import com.azure.resourcemanager.deviceregistry.fluent.models.SchemaInner; -import com.azure.resourcemanager.deviceregistry.implementation.models.SchemaListResult; -import reactor.core.publisher.Mono; - -/** - * An instance of this class provides access to all the operations defined in SchemasClient. - */ -public final class SchemasClientImpl implements SchemasClient { - /** - * The proxy service used to perform REST calls. - */ - private final SchemasService service; - - /** - * The service client containing this operation class. - */ - private final DeviceRegistryManagementClientImpl client; - - /** - * Initializes an instance of SchemasClientImpl. - * - * @param client the instance of the service client containing this operation class. - */ - SchemasClientImpl(DeviceRegistryManagementClientImpl client) { - this.service = RestProxy.create(SchemasService.class, client.getHttpPipeline(), client.getSerializerAdapter()); - this.client = client; - } - - /** - * The interface defining all the services for DeviceRegistryManagementClientSchemas to be used by the proxy service - * to perform REST calls. - */ - @Host("{endpoint}") - @ServiceInterface(name = "DeviceRegistryManage") - public interface SchemasService { - @Headers({ "Content-Type: application/json" }) - @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DeviceRegistry/schemaRegistries/{schemaRegistryName}/schemas/{schemaName}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> get(@HostParam("endpoint") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, - @PathParam("schemaRegistryName") String schemaRegistryName, @PathParam("schemaName") String schemaName, - @HeaderParam("Accept") String accept, Context context); - - @Put("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DeviceRegistry/schemaRegistries/{schemaRegistryName}/schemas/{schemaName}") - @ExpectedResponses({ 200, 201 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> createOrReplace(@HostParam("endpoint") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, - @PathParam("schemaRegistryName") String schemaRegistryName, @PathParam("schemaName") String schemaName, - @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, - @BodyParam("application/json") SchemaInner resource, Context context); - - @Headers({ "Content-Type: application/json" }) - @Delete("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DeviceRegistry/schemaRegistries/{schemaRegistryName}/schemas/{schemaName}") - @ExpectedResponses({ 200, 204 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> delete(@HostParam("endpoint") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, - @PathParam("schemaRegistryName") String schemaRegistryName, @PathParam("schemaName") String schemaName, - @HeaderParam("Accept") String accept, Context context); - - @Headers({ "Content-Type: application/json" }) - @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DeviceRegistry/schemaRegistries/{schemaRegistryName}/schemas") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> listBySchemaRegistry(@HostParam("endpoint") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, - @PathParam("schemaRegistryName") String schemaRegistryName, @HeaderParam("Accept") String accept, - Context context); - - @Headers({ "Content-Type: application/json" }) - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> listBySchemaRegistryNext( - @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, - @HeaderParam("Accept") String accept, Context context); - } - - /** - * Get a Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Schema along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> getWithResponseAsync(String resourceGroupName, String schemaRegistryName, - String schemaName) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (schemaRegistryName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaRegistryName is required and cannot be null.")); - } - if (schemaName == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, schemaRegistryName, schemaName, accept, context)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Get a Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Schema along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> getWithResponseAsync(String resourceGroupName, String schemaRegistryName, - String schemaName, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (schemaRegistryName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaRegistryName is required and cannot be null.")); - } - if (schemaName == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), - resourceGroupName, schemaRegistryName, schemaName, accept, context); - } - - /** - * Get a Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Schema on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono getAsync(String resourceGroupName, String schemaRegistryName, String schemaName) { - return getWithResponseAsync(resourceGroupName, schemaRegistryName, schemaName) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Get a Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Schema along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getWithResponse(String resourceGroupName, String schemaRegistryName, String schemaName, - Context context) { - return getWithResponseAsync(resourceGroupName, schemaRegistryName, schemaName, context).block(); - } - - /** - * Get a Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Schema. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SchemaInner get(String resourceGroupName, String schemaRegistryName, String schemaName) { - return getWithResponse(resourceGroupName, schemaRegistryName, schemaName, Context.NONE).getValue(); - } - - /** - * Create a Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param resource Resource create parameters. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema definition along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> createOrReplaceWithResponseAsync(String resourceGroupName, - String schemaRegistryName, String schemaName, SchemaInner resource) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (schemaRegistryName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaRegistryName is required and cannot be null.")); - } - if (schemaName == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); - } - if (resource == null) { - return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); - } else { - resource.validate(); - } - final String contentType = "application/json"; - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.createOrReplace(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, schemaRegistryName, schemaName, contentType, accept, - resource, context)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Create a Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param resource Resource create parameters. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema definition along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> createOrReplaceWithResponseAsync(String resourceGroupName, - String schemaRegistryName, String schemaName, SchemaInner resource, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (schemaRegistryName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaRegistryName is required and cannot be null.")); - } - if (schemaName == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); - } - if (resource == null) { - return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); - } else { - resource.validate(); - } - final String contentType = "application/json"; - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.createOrReplace(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, schemaRegistryName, schemaName, contentType, accept, - resource, context); - } - - /** - * Create a Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param resource Resource create parameters. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono createOrReplaceAsync(String resourceGroupName, String schemaRegistryName, - String schemaName, SchemaInner resource) { - return createOrReplaceWithResponseAsync(resourceGroupName, schemaRegistryName, schemaName, resource) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Create a Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param resource Resource create parameters. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema definition along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createOrReplaceWithResponse(String resourceGroupName, String schemaRegistryName, - String schemaName, SchemaInner resource, Context context) { - return createOrReplaceWithResponseAsync(resourceGroupName, schemaRegistryName, schemaName, resource, context) - .block(); - } - - /** - * Create a Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param resource Resource create parameters. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SchemaInner createOrReplace(String resourceGroupName, String schemaRegistryName, String schemaName, - SchemaInner resource) { - return createOrReplaceWithResponse(resourceGroupName, schemaRegistryName, schemaName, resource, Context.NONE) - .getValue(); - } - - /** - * Delete a Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> deleteWithResponseAsync(String resourceGroupName, String schemaRegistryName, - String schemaName) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (schemaRegistryName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaRegistryName is required and cannot be null.")); - } - if (schemaName == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.delete(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, schemaRegistryName, schemaName, accept, context)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Delete a Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> deleteWithResponseAsync(String resourceGroupName, String schemaRegistryName, - String schemaName, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (schemaRegistryName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaRegistryName is required and cannot be null.")); - } - if (schemaName == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.delete(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), - resourceGroupName, schemaRegistryName, schemaName, accept, context); - } - - /** - * Delete a Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono deleteAsync(String resourceGroupName, String schemaRegistryName, String schemaName) { - return deleteWithResponseAsync(resourceGroupName, schemaRegistryName, schemaName) - .flatMap(ignored -> Mono.empty()); - } - - /** - * Delete a Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteWithResponse(String resourceGroupName, String schemaRegistryName, String schemaName, - Context context) { - return deleteWithResponseAsync(resourceGroupName, schemaRegistryName, schemaName, context).block(); - } - - /** - * Delete a Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void delete(String resourceGroupName, String schemaRegistryName, String schemaName) { - deleteWithResponse(resourceGroupName, schemaRegistryName, schemaName, Context.NONE); - } - - /** - * List Schema resources by SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Schema list operation along with {@link PagedResponse} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listBySchemaRegistrySinglePageAsync(String resourceGroupName, - String schemaRegistryName) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (schemaRegistryName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaRegistryName is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.listBySchemaRegistry(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, schemaRegistryName, accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), - res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * List Schema resources by SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Schema list operation along with {@link PagedResponse} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listBySchemaRegistrySinglePageAsync(String resourceGroupName, - String schemaRegistryName, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (schemaRegistryName == null) { - return Mono - .error(new IllegalArgumentException("Parameter schemaRegistryName is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service - .listBySchemaRegistry(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, schemaRegistryName, accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } - - /** - * List Schema resources by SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Schema list operation as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listBySchemaRegistryAsync(String resourceGroupName, String schemaRegistryName) { - return new PagedFlux<>(() -> listBySchemaRegistrySinglePageAsync(resourceGroupName, schemaRegistryName), - nextLink -> listBySchemaRegistryNextSinglePageAsync(nextLink)); - } - - /** - * List Schema resources by SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Schema list operation as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listBySchemaRegistryAsync(String resourceGroupName, String schemaRegistryName, - Context context) { - return new PagedFlux<>( - () -> listBySchemaRegistrySinglePageAsync(resourceGroupName, schemaRegistryName, context), - nextLink -> listBySchemaRegistryNextSinglePageAsync(nextLink, context)); - } - - /** - * List Schema resources by SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Schema list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listBySchemaRegistry(String resourceGroupName, String schemaRegistryName) { - return new PagedIterable<>(listBySchemaRegistryAsync(resourceGroupName, schemaRegistryName)); - } - - /** - * List Schema resources by SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Schema list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listBySchemaRegistry(String resourceGroupName, String schemaRegistryName, - Context context) { - return new PagedIterable<>(listBySchemaRegistryAsync(resourceGroupName, schemaRegistryName, context)); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Schema list operation along with {@link PagedResponse} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listBySchemaRegistryNextSinglePageAsync(String nextLink) { - if (nextLink == null) { - return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - } - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext( - context -> service.listBySchemaRegistryNext(nextLink, this.client.getEndpoint(), accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), - res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Schema list operation along with {@link PagedResponse} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listBySchemaRegistryNextSinglePageAsync(String nextLink, Context context) { - if (nextLink == null) { - return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - } - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.listBySchemaRegistryNext(nextLink, this.client.getEndpoint(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/SchemasImpl.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/SchemasImpl.java deleted file mode 100644 index 1ab0e703460f..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/SchemasImpl.java +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.implementation; - -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.SimpleResponse; -import com.azure.core.util.Context; -import com.azure.core.util.logging.ClientLogger; -import com.azure.resourcemanager.deviceregistry.fluent.SchemasClient; -import com.azure.resourcemanager.deviceregistry.fluent.models.SchemaInner; -import com.azure.resourcemanager.deviceregistry.models.Schema; -import com.azure.resourcemanager.deviceregistry.models.Schemas; - -public final class SchemasImpl implements Schemas { - private static final ClientLogger LOGGER = new ClientLogger(SchemasImpl.class); - - private final SchemasClient innerClient; - - private final com.azure.resourcemanager.deviceregistry.DeviceRegistryManager serviceManager; - - public SchemasImpl(SchemasClient innerClient, - com.azure.resourcemanager.deviceregistry.DeviceRegistryManager serviceManager) { - this.innerClient = innerClient; - this.serviceManager = serviceManager; - } - - public Response getWithResponse(String resourceGroupName, String schemaRegistryName, String schemaName, - Context context) { - Response inner - = this.serviceClient().getWithResponse(resourceGroupName, schemaRegistryName, schemaName, context); - if (inner != null) { - return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), - new SchemaImpl(inner.getValue(), this.manager())); - } else { - return null; - } - } - - public Schema get(String resourceGroupName, String schemaRegistryName, String schemaName) { - SchemaInner inner = this.serviceClient().get(resourceGroupName, schemaRegistryName, schemaName); - if (inner != null) { - return new SchemaImpl(inner, this.manager()); - } else { - return null; - } - } - - public Response deleteWithResponse(String resourceGroupName, String schemaRegistryName, String schemaName, - Context context) { - return this.serviceClient().deleteWithResponse(resourceGroupName, schemaRegistryName, schemaName, context); - } - - public void delete(String resourceGroupName, String schemaRegistryName, String schemaName) { - this.serviceClient().delete(resourceGroupName, schemaRegistryName, schemaName); - } - - public PagedIterable listBySchemaRegistry(String resourceGroupName, String schemaRegistryName) { - PagedIterable inner - = this.serviceClient().listBySchemaRegistry(resourceGroupName, schemaRegistryName); - return ResourceManagerUtils.mapPage(inner, inner1 -> new SchemaImpl(inner1, this.manager())); - } - - public PagedIterable listBySchemaRegistry(String resourceGroupName, String schemaRegistryName, - Context context) { - PagedIterable inner - = this.serviceClient().listBySchemaRegistry(resourceGroupName, schemaRegistryName, context); - return ResourceManagerUtils.mapPage(inner, inner1 -> new SchemaImpl(inner1, this.manager())); - } - - public Schema getById(String id) { - String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); - if (resourceGroupName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); - } - String schemaRegistryName = ResourceManagerUtils.getValueFromIdByName(id, "schemaRegistries"); - if (schemaRegistryName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'schemaRegistries'.", id))); - } - String schemaName = ResourceManagerUtils.getValueFromIdByName(id, "schemas"); - if (schemaName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'schemas'.", id))); - } - return this.getWithResponse(resourceGroupName, schemaRegistryName, schemaName, Context.NONE).getValue(); - } - - public Response getByIdWithResponse(String id, Context context) { - String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); - if (resourceGroupName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); - } - String schemaRegistryName = ResourceManagerUtils.getValueFromIdByName(id, "schemaRegistries"); - if (schemaRegistryName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'schemaRegistries'.", id))); - } - String schemaName = ResourceManagerUtils.getValueFromIdByName(id, "schemas"); - if (schemaName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'schemas'.", id))); - } - return this.getWithResponse(resourceGroupName, schemaRegistryName, schemaName, context); - } - - public void deleteById(String id) { - String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); - if (resourceGroupName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); - } - String schemaRegistryName = ResourceManagerUtils.getValueFromIdByName(id, "schemaRegistries"); - if (schemaRegistryName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'schemaRegistries'.", id))); - } - String schemaName = ResourceManagerUtils.getValueFromIdByName(id, "schemas"); - if (schemaName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'schemas'.", id))); - } - this.deleteWithResponse(resourceGroupName, schemaRegistryName, schemaName, Context.NONE); - } - - public Response deleteByIdWithResponse(String id, Context context) { - String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); - if (resourceGroupName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); - } - String schemaRegistryName = ResourceManagerUtils.getValueFromIdByName(id, "schemaRegistries"); - if (schemaRegistryName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'schemaRegistries'.", id))); - } - String schemaName = ResourceManagerUtils.getValueFromIdByName(id, "schemas"); - if (schemaName == null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The resource ID '%s' is not valid. Missing path segment 'schemas'.", id))); - } - return this.deleteWithResponse(resourceGroupName, schemaRegistryName, schemaName, context); - } - - private SchemasClient serviceClient() { - return this.innerClient; - } - - private com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager() { - return this.serviceManager; - } - - public SchemaImpl define(String name) { - return new SchemaImpl(name, this.manager()); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/models/DiscoveredAssetEndpointProfileListResult.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/models/DiscoveredAssetEndpointProfileListResult.java deleted file mode 100644 index ab54f80a63f3..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/models/DiscoveredAssetEndpointProfileListResult.java +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.implementation.models; - -import com.azure.core.annotation.Immutable; -import com.azure.core.util.logging.ClientLogger; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.resourcemanager.deviceregistry.fluent.models.DiscoveredAssetEndpointProfileInner; -import java.io.IOException; -import java.util.List; - -/** - * The response of a DiscoveredAssetEndpointProfile list operation. - */ -@Immutable -public final class DiscoveredAssetEndpointProfileListResult - implements JsonSerializable { - /* - * The DiscoveredAssetEndpointProfile items on this page - */ - private List value; - - /* - * The link to the next page of items - */ - private String nextLink; - - /** - * Creates an instance of DiscoveredAssetEndpointProfileListResult class. - */ - private DiscoveredAssetEndpointProfileListResult() { - } - - /** - * Get the value property: The DiscoveredAssetEndpointProfile items on this page. - * - * @return the value value. - */ - public List value() { - return this.value; - } - - /** - * Get the nextLink property: The link to the next page of items. - * - * @return the nextLink value. - */ - public String nextLink() { - return this.nextLink; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (value() == null) { - throw LOGGER.atError() - .log(new IllegalArgumentException( - "Missing required property value in model DiscoveredAssetEndpointProfileListResult")); - } else { - value().forEach(e -> e.validate()); - } - } - - private static final ClientLogger LOGGER = new ClientLogger(DiscoveredAssetEndpointProfileListResult.class); - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); - jsonWriter.writeStringField("nextLink", this.nextLink); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of DiscoveredAssetEndpointProfileListResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of DiscoveredAssetEndpointProfileListResult 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 DiscoveredAssetEndpointProfileListResult. - */ - public static DiscoveredAssetEndpointProfileListResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - DiscoveredAssetEndpointProfileListResult deserializedDiscoveredAssetEndpointProfileListResult - = new DiscoveredAssetEndpointProfileListResult(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - List value - = reader.readArray(reader1 -> DiscoveredAssetEndpointProfileInner.fromJson(reader1)); - deserializedDiscoveredAssetEndpointProfileListResult.value = value; - } else if ("nextLink".equals(fieldName)) { - deserializedDiscoveredAssetEndpointProfileListResult.nextLink = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedDiscoveredAssetEndpointProfileListResult; - }); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/models/DiscoveredAssetListResult.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/models/DiscoveredAssetListResult.java deleted file mode 100644 index bb97da2021d3..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/models/DiscoveredAssetListResult.java +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.implementation.models; - -import com.azure.core.annotation.Immutable; -import com.azure.core.util.logging.ClientLogger; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.resourcemanager.deviceregistry.fluent.models.DiscoveredAssetInner; -import java.io.IOException; -import java.util.List; - -/** - * The response of a DiscoveredAsset list operation. - */ -@Immutable -public final class DiscoveredAssetListResult implements JsonSerializable { - /* - * The DiscoveredAsset items on this page - */ - private List value; - - /* - * The link to the next page of items - */ - private String nextLink; - - /** - * Creates an instance of DiscoveredAssetListResult class. - */ - private DiscoveredAssetListResult() { - } - - /** - * Get the value property: The DiscoveredAsset items on this page. - * - * @return the value value. - */ - public List value() { - return this.value; - } - - /** - * Get the nextLink property: The link to the next page of items. - * - * @return the nextLink value. - */ - public String nextLink() { - return this.nextLink; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (value() == null) { - throw LOGGER.atError() - .log( - new IllegalArgumentException("Missing required property value in model DiscoveredAssetListResult")); - } else { - value().forEach(e -> e.validate()); - } - } - - private static final ClientLogger LOGGER = new ClientLogger(DiscoveredAssetListResult.class); - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); - jsonWriter.writeStringField("nextLink", this.nextLink); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of DiscoveredAssetListResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of DiscoveredAssetListResult 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 DiscoveredAssetListResult. - */ - public static DiscoveredAssetListResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - DiscoveredAssetListResult deserializedDiscoveredAssetListResult = new DiscoveredAssetListResult(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - List value - = reader.readArray(reader1 -> DiscoveredAssetInner.fromJson(reader1)); - deserializedDiscoveredAssetListResult.value = value; - } else if ("nextLink".equals(fieldName)) { - deserializedDiscoveredAssetListResult.nextLink = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedDiscoveredAssetListResult; - }); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/models/SchemaListResult.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/models/SchemaListResult.java deleted file mode 100644 index a32b045693cf..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/models/SchemaListResult.java +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.implementation.models; - -import com.azure.core.annotation.Immutable; -import com.azure.core.util.logging.ClientLogger; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.resourcemanager.deviceregistry.fluent.models.SchemaInner; -import java.io.IOException; -import java.util.List; - -/** - * The response of a Schema list operation. - */ -@Immutable -public final class SchemaListResult implements JsonSerializable { - /* - * The Schema items on this page - */ - private List value; - - /* - * The link to the next page of items - */ - private String nextLink; - - /** - * Creates an instance of SchemaListResult class. - */ - private SchemaListResult() { - } - - /** - * Get the value property: The Schema items on this page. - * - * @return the value value. - */ - public List value() { - return this.value; - } - - /** - * Get the nextLink property: The link to the next page of items. - * - * @return the nextLink value. - */ - public String nextLink() { - return this.nextLink; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (value() == null) { - throw LOGGER.atError() - .log(new IllegalArgumentException("Missing required property value in model SchemaListResult")); - } else { - value().forEach(e -> e.validate()); - } - } - - private static final ClientLogger LOGGER = new ClientLogger(SchemaListResult.class); - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); - jsonWriter.writeStringField("nextLink", this.nextLink); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SchemaListResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SchemaListResult 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 SchemaListResult. - */ - public static SchemaListResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SchemaListResult deserializedSchemaListResult = new SchemaListResult(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - List value = reader.readArray(reader1 -> SchemaInner.fromJson(reader1)); - deserializedSchemaListResult.value = value; - } else if ("nextLink".equals(fieldName)) { - deserializedSchemaListResult.nextLink = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedSchemaListResult; - }); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/models/SchemaRegistryListResult.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/models/SchemaRegistryListResult.java deleted file mode 100644 index 550f36d7844a..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/models/SchemaRegistryListResult.java +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.implementation.models; - -import com.azure.core.annotation.Immutable; -import com.azure.core.util.logging.ClientLogger; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.resourcemanager.deviceregistry.fluent.models.SchemaRegistryInner; -import java.io.IOException; -import java.util.List; - -/** - * The response of a SchemaRegistry list operation. - */ -@Immutable -public final class SchemaRegistryListResult implements JsonSerializable { - /* - * The SchemaRegistry items on this page - */ - private List value; - - /* - * The link to the next page of items - */ - private String nextLink; - - /** - * Creates an instance of SchemaRegistryListResult class. - */ - private SchemaRegistryListResult() { - } - - /** - * Get the value property: The SchemaRegistry items on this page. - * - * @return the value value. - */ - public List value() { - return this.value; - } - - /** - * Get the nextLink property: The link to the next page of items. - * - * @return the nextLink value. - */ - public String nextLink() { - return this.nextLink; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (value() == null) { - throw LOGGER.atError() - .log(new IllegalArgumentException("Missing required property value in model SchemaRegistryListResult")); - } else { - value().forEach(e -> e.validate()); - } - } - - private static final ClientLogger LOGGER = new ClientLogger(SchemaRegistryListResult.class); - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); - jsonWriter.writeStringField("nextLink", this.nextLink); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SchemaRegistryListResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SchemaRegistryListResult 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 SchemaRegistryListResult. - */ - public static SchemaRegistryListResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SchemaRegistryListResult deserializedSchemaRegistryListResult = new SchemaRegistryListResult(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - List value - = reader.readArray(reader1 -> SchemaRegistryInner.fromJson(reader1)); - deserializedSchemaRegistryListResult.value = value; - } else if ("nextLink".equals(fieldName)) { - deserializedSchemaRegistryListResult.nextLink = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedSchemaRegistryListResult; - }); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/models/SchemaVersionListResult.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/models/SchemaVersionListResult.java deleted file mode 100644 index f90715495873..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/implementation/models/SchemaVersionListResult.java +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.implementation.models; - -import com.azure.core.annotation.Immutable; -import com.azure.core.util.logging.ClientLogger; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.resourcemanager.deviceregistry.fluent.models.SchemaVersionInner; -import java.io.IOException; -import java.util.List; - -/** - * The response of a SchemaVersion list operation. - */ -@Immutable -public final class SchemaVersionListResult implements JsonSerializable { - /* - * The SchemaVersion items on this page - */ - private List value; - - /* - * The link to the next page of items - */ - private String nextLink; - - /** - * Creates an instance of SchemaVersionListResult class. - */ - private SchemaVersionListResult() { - } - - /** - * Get the value property: The SchemaVersion items on this page. - * - * @return the value value. - */ - public List value() { - return this.value; - } - - /** - * Get the nextLink property: The link to the next page of items. - * - * @return the nextLink value. - */ - public String nextLink() { - return this.nextLink; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (value() == null) { - throw LOGGER.atError() - .log(new IllegalArgumentException("Missing required property value in model SchemaVersionListResult")); - } else { - value().forEach(e -> e.validate()); - } - } - - private static final ClientLogger LOGGER = new ClientLogger(SchemaVersionListResult.class); - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); - jsonWriter.writeStringField("nextLink", this.nextLink); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SchemaVersionListResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SchemaVersionListResult 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 SchemaVersionListResult. - */ - public static SchemaVersionListResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SchemaVersionListResult deserializedSchemaVersionListResult = new SchemaVersionListResult(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - List value = reader.readArray(reader1 -> SchemaVersionInner.fromJson(reader1)); - deserializedSchemaVersionListResult.value = value; - } else if ("nextLink".equals(fieldName)) { - deserializedSchemaVersionListResult.nextLink = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedSchemaVersionListResult; - }); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAsset.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAsset.java deleted file mode 100644 index 8f8524780878..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAsset.java +++ /dev/null @@ -1,285 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.models; - -import com.azure.core.management.Region; -import com.azure.core.management.SystemData; -import com.azure.core.util.Context; -import com.azure.resourcemanager.deviceregistry.fluent.models.DiscoveredAssetInner; -import java.util.Map; - -/** - * An immutable client-side representation of DiscoveredAsset. - */ -public interface DiscoveredAsset { - /** - * Gets the id property: Fully qualified resource Id for the resource. - * - * @return the id value. - */ - String id(); - - /** - * Gets the name property: The name of the resource. - * - * @return the name value. - */ - String name(); - - /** - * Gets the type property: The type of the resource. - * - * @return the type value. - */ - String type(); - - /** - * Gets the location property: The geo-location where the resource lives. - * - * @return the location value. - */ - String location(); - - /** - * Gets the tags property: Resource tags. - * - * @return the tags value. - */ - Map tags(); - - /** - * Gets the properties property: The resource-specific properties for this resource. - * - * @return the properties value. - */ - DiscoveredAssetProperties properties(); - - /** - * Gets the extendedLocation property: The extended location. - * - * @return the extendedLocation value. - */ - ExtendedLocation extendedLocation(); - - /** - * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. - * - * @return the systemData value. - */ - SystemData systemData(); - - /** - * Gets the region of the resource. - * - * @return the region of the resource. - */ - Region region(); - - /** - * Gets the name of the resource region. - * - * @return the name of the resource region. - */ - String regionName(); - - /** - * Gets the name of the resource group. - * - * @return the name of the resource group. - */ - String resourceGroupName(); - - /** - * Gets the inner com.azure.resourcemanager.deviceregistry.fluent.models.DiscoveredAssetInner object. - * - * @return the inner object. - */ - DiscoveredAssetInner innerModel(); - - /** - * The entirety of the DiscoveredAsset definition. - */ - interface Definition extends DefinitionStages.Blank, DefinitionStages.WithLocation, - DefinitionStages.WithResourceGroup, DefinitionStages.WithExtendedLocation, DefinitionStages.WithCreate { - } - - /** - * The DiscoveredAsset definition stages. - */ - interface DefinitionStages { - /** - * The first stage of the DiscoveredAsset definition. - */ - interface Blank extends WithLocation { - } - - /** - * The stage of the DiscoveredAsset definition allowing to specify location. - */ - interface WithLocation { - /** - * Specifies the region for the resource. - * - * @param location The geo-location where the resource lives. - * @return the next definition stage. - */ - WithResourceGroup withRegion(Region location); - - /** - * Specifies the region for the resource. - * - * @param location The geo-location where the resource lives. - * @return the next definition stage. - */ - WithResourceGroup withRegion(String location); - } - - /** - * The stage of the DiscoveredAsset definition allowing to specify parent resource. - */ - interface WithResourceGroup { - /** - * Specifies resourceGroupName. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @return the next definition stage. - */ - WithExtendedLocation withExistingResourceGroup(String resourceGroupName); - } - - /** - * The stage of the DiscoveredAsset definition allowing to specify extendedLocation. - */ - interface WithExtendedLocation { - /** - * Specifies the extendedLocation property: The extended location.. - * - * @param extendedLocation The extended location. - * @return the next definition stage. - */ - WithCreate withExtendedLocation(ExtendedLocation extendedLocation); - } - - /** - * The stage of the DiscoveredAsset definition which contains all the minimum required properties for the - * resource to be created, but also allows for any other optional properties to be specified. - */ - interface WithCreate extends DefinitionStages.WithTags, DefinitionStages.WithProperties { - /** - * Executes the create request. - * - * @return the created resource. - */ - DiscoveredAsset create(); - - /** - * Executes the create request. - * - * @param context The context to associate with this operation. - * @return the created resource. - */ - DiscoveredAsset create(Context context); - } - - /** - * The stage of the DiscoveredAsset definition allowing to specify tags. - */ - interface WithTags { - /** - * Specifies the tags property: Resource tags.. - * - * @param tags Resource tags. - * @return the next definition stage. - */ - WithCreate withTags(Map tags); - } - - /** - * The stage of the DiscoveredAsset definition allowing to specify properties. - */ - interface WithProperties { - /** - * Specifies the properties property: The resource-specific properties for this resource.. - * - * @param properties The resource-specific properties for this resource. - * @return the next definition stage. - */ - WithCreate withProperties(DiscoveredAssetProperties properties); - } - } - - /** - * Begins update for the DiscoveredAsset resource. - * - * @return the stage of resource update. - */ - DiscoveredAsset.Update update(); - - /** - * The template for DiscoveredAsset update. - */ - interface Update extends UpdateStages.WithTags, UpdateStages.WithProperties { - /** - * Executes the update request. - * - * @return the updated resource. - */ - DiscoveredAsset apply(); - - /** - * Executes the update request. - * - * @param context The context to associate with this operation. - * @return the updated resource. - */ - DiscoveredAsset apply(Context context); - } - - /** - * The DiscoveredAsset update stages. - */ - interface UpdateStages { - /** - * The stage of the DiscoveredAsset update allowing to specify tags. - */ - interface WithTags { - /** - * Specifies the tags property: Resource tags.. - * - * @param tags Resource tags. - * @return the next definition stage. - */ - Update withTags(Map tags); - } - - /** - * The stage of the DiscoveredAsset update allowing to specify properties. - */ - interface WithProperties { - /** - * Specifies the properties property: The resource-specific properties for this resource.. - * - * @param properties The resource-specific properties for this resource. - * @return the next definition stage. - */ - Update withProperties(DiscoveredAssetUpdateProperties properties); - } - } - - /** - * Refreshes the resource to sync with Azure. - * - * @return the refreshed resource. - */ - DiscoveredAsset refresh(); - - /** - * Refreshes the resource to sync with Azure. - * - * @param context The context to associate with this operation. - * @return the refreshed resource. - */ - DiscoveredAsset refresh(Context context); -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAssetEndpointProfile.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAssetEndpointProfile.java deleted file mode 100644 index ae0646d90b83..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAssetEndpointProfile.java +++ /dev/null @@ -1,285 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.models; - -import com.azure.core.management.Region; -import com.azure.core.management.SystemData; -import com.azure.core.util.Context; -import com.azure.resourcemanager.deviceregistry.fluent.models.DiscoveredAssetEndpointProfileInner; -import java.util.Map; - -/** - * An immutable client-side representation of DiscoveredAssetEndpointProfile. - */ -public interface DiscoveredAssetEndpointProfile { - /** - * Gets the id property: Fully qualified resource Id for the resource. - * - * @return the id value. - */ - String id(); - - /** - * Gets the name property: The name of the resource. - * - * @return the name value. - */ - String name(); - - /** - * Gets the type property: The type of the resource. - * - * @return the type value. - */ - String type(); - - /** - * Gets the location property: The geo-location where the resource lives. - * - * @return the location value. - */ - String location(); - - /** - * Gets the tags property: Resource tags. - * - * @return the tags value. - */ - Map tags(); - - /** - * Gets the properties property: The resource-specific properties for this resource. - * - * @return the properties value. - */ - DiscoveredAssetEndpointProfileProperties properties(); - - /** - * Gets the extendedLocation property: The extended location. - * - * @return the extendedLocation value. - */ - ExtendedLocation extendedLocation(); - - /** - * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. - * - * @return the systemData value. - */ - SystemData systemData(); - - /** - * Gets the region of the resource. - * - * @return the region of the resource. - */ - Region region(); - - /** - * Gets the name of the resource region. - * - * @return the name of the resource region. - */ - String regionName(); - - /** - * Gets the name of the resource group. - * - * @return the name of the resource group. - */ - String resourceGroupName(); - - /** - * Gets the inner com.azure.resourcemanager.deviceregistry.fluent.models.DiscoveredAssetEndpointProfileInner object. - * - * @return the inner object. - */ - DiscoveredAssetEndpointProfileInner innerModel(); - - /** - * The entirety of the DiscoveredAssetEndpointProfile definition. - */ - interface Definition extends DefinitionStages.Blank, DefinitionStages.WithLocation, - DefinitionStages.WithResourceGroup, DefinitionStages.WithExtendedLocation, DefinitionStages.WithCreate { - } - - /** - * The DiscoveredAssetEndpointProfile definition stages. - */ - interface DefinitionStages { - /** - * The first stage of the DiscoveredAssetEndpointProfile definition. - */ - interface Blank extends WithLocation { - } - - /** - * The stage of the DiscoveredAssetEndpointProfile definition allowing to specify location. - */ - interface WithLocation { - /** - * Specifies the region for the resource. - * - * @param location The geo-location where the resource lives. - * @return the next definition stage. - */ - WithResourceGroup withRegion(Region location); - - /** - * Specifies the region for the resource. - * - * @param location The geo-location where the resource lives. - * @return the next definition stage. - */ - WithResourceGroup withRegion(String location); - } - - /** - * The stage of the DiscoveredAssetEndpointProfile definition allowing to specify parent resource. - */ - interface WithResourceGroup { - /** - * Specifies resourceGroupName. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @return the next definition stage. - */ - WithExtendedLocation withExistingResourceGroup(String resourceGroupName); - } - - /** - * The stage of the DiscoveredAssetEndpointProfile definition allowing to specify extendedLocation. - */ - interface WithExtendedLocation { - /** - * Specifies the extendedLocation property: The extended location.. - * - * @param extendedLocation The extended location. - * @return the next definition stage. - */ - WithCreate withExtendedLocation(ExtendedLocation extendedLocation); - } - - /** - * The stage of the DiscoveredAssetEndpointProfile definition which contains all the minimum required properties - * for the resource to be created, but also allows for any other optional properties to be specified. - */ - interface WithCreate extends DefinitionStages.WithTags, DefinitionStages.WithProperties { - /** - * Executes the create request. - * - * @return the created resource. - */ - DiscoveredAssetEndpointProfile create(); - - /** - * Executes the create request. - * - * @param context The context to associate with this operation. - * @return the created resource. - */ - DiscoveredAssetEndpointProfile create(Context context); - } - - /** - * The stage of the DiscoveredAssetEndpointProfile definition allowing to specify tags. - */ - interface WithTags { - /** - * Specifies the tags property: Resource tags.. - * - * @param tags Resource tags. - * @return the next definition stage. - */ - WithCreate withTags(Map tags); - } - - /** - * The stage of the DiscoveredAssetEndpointProfile definition allowing to specify properties. - */ - interface WithProperties { - /** - * Specifies the properties property: The resource-specific properties for this resource.. - * - * @param properties The resource-specific properties for this resource. - * @return the next definition stage. - */ - WithCreate withProperties(DiscoveredAssetEndpointProfileProperties properties); - } - } - - /** - * Begins update for the DiscoveredAssetEndpointProfile resource. - * - * @return the stage of resource update. - */ - DiscoveredAssetEndpointProfile.Update update(); - - /** - * The template for DiscoveredAssetEndpointProfile update. - */ - interface Update extends UpdateStages.WithTags, UpdateStages.WithProperties { - /** - * Executes the update request. - * - * @return the updated resource. - */ - DiscoveredAssetEndpointProfile apply(); - - /** - * Executes the update request. - * - * @param context The context to associate with this operation. - * @return the updated resource. - */ - DiscoveredAssetEndpointProfile apply(Context context); - } - - /** - * The DiscoveredAssetEndpointProfile update stages. - */ - interface UpdateStages { - /** - * The stage of the DiscoveredAssetEndpointProfile update allowing to specify tags. - */ - interface WithTags { - /** - * Specifies the tags property: Resource tags.. - * - * @param tags Resource tags. - * @return the next definition stage. - */ - Update withTags(Map tags); - } - - /** - * The stage of the DiscoveredAssetEndpointProfile update allowing to specify properties. - */ - interface WithProperties { - /** - * Specifies the properties property: The resource-specific properties for this resource.. - * - * @param properties The resource-specific properties for this resource. - * @return the next definition stage. - */ - Update withProperties(DiscoveredAssetEndpointProfileUpdateProperties properties); - } - } - - /** - * Refreshes the resource to sync with Azure. - * - * @return the refreshed resource. - */ - DiscoveredAssetEndpointProfile refresh(); - - /** - * Refreshes the resource to sync with Azure. - * - * @param context The context to associate with this operation. - * @return the refreshed resource. - */ - DiscoveredAssetEndpointProfile refresh(Context context); -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAssetEndpointProfileProperties.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAssetEndpointProfileProperties.java deleted file mode 100644 index d6df4e63298d..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAssetEndpointProfileProperties.java +++ /dev/null @@ -1,289 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.util.logging.ClientLogger; -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; - -/** - * Defines the Discovered Asset Endpoint Profile properties. - */ -@Fluent -public final class DiscoveredAssetEndpointProfileProperties - implements JsonSerializable { - /* - * The local valid URI specifying the network address/DNS name of a southbound device. The scheme part of the - * targetAddress URI specifies the type of the device. The additionalConfiguration field holds further connector - * type specific configuration. - */ - private String targetAddress; - - /* - * Stringified JSON that contains connectivity type specific further configuration (e.g. OPC UA, Modbus, ONVIF). - */ - private String additionalConfiguration; - - /* - * List of supported authentication methods supported by the target server. - */ - private List supportedAuthenticationMethods; - - /* - * Defines the configuration for the connector type that is being used with the endpoint profile. - */ - private String endpointProfileType; - - /* - * Identifier used to detect changes in the asset endpoint profile. - */ - private String discoveryId; - - /* - * An integer that is incremented each time the resource is modified. - */ - private long version; - - /* - * Provisioning state of the resource. - */ - private ProvisioningState provisioningState; - - /** - * Creates an instance of DiscoveredAssetEndpointProfileProperties class. - */ - public DiscoveredAssetEndpointProfileProperties() { - } - - /** - * Get the targetAddress property: The local valid URI specifying the network address/DNS name of a southbound - * device. The scheme part of the targetAddress URI specifies the type of the device. The additionalConfiguration - * field holds further connector type specific configuration. - * - * @return the targetAddress value. - */ - public String targetAddress() { - return this.targetAddress; - } - - /** - * Set the targetAddress property: The local valid URI specifying the network address/DNS name of a southbound - * device. The scheme part of the targetAddress URI specifies the type of the device. The additionalConfiguration - * field holds further connector type specific configuration. - * - * @param targetAddress the targetAddress value to set. - * @return the DiscoveredAssetEndpointProfileProperties object itself. - */ - public DiscoveredAssetEndpointProfileProperties withTargetAddress(String targetAddress) { - this.targetAddress = targetAddress; - return this; - } - - /** - * Get the additionalConfiguration property: Stringified JSON that contains connectivity type specific further - * configuration (e.g. OPC UA, Modbus, ONVIF). - * - * @return the additionalConfiguration value. - */ - public String additionalConfiguration() { - return this.additionalConfiguration; - } - - /** - * Set the additionalConfiguration property: Stringified JSON that contains connectivity type specific further - * configuration (e.g. OPC UA, Modbus, ONVIF). - * - * @param additionalConfiguration the additionalConfiguration value to set. - * @return the DiscoveredAssetEndpointProfileProperties object itself. - */ - public DiscoveredAssetEndpointProfileProperties withAdditionalConfiguration(String additionalConfiguration) { - this.additionalConfiguration = additionalConfiguration; - return this; - } - - /** - * Get the supportedAuthenticationMethods property: List of supported authentication methods supported by the target - * server. - * - * @return the supportedAuthenticationMethods value. - */ - public List supportedAuthenticationMethods() { - return this.supportedAuthenticationMethods; - } - - /** - * Set the supportedAuthenticationMethods property: List of supported authentication methods supported by the target - * server. - * - * @param supportedAuthenticationMethods the supportedAuthenticationMethods value to set. - * @return the DiscoveredAssetEndpointProfileProperties object itself. - */ - public DiscoveredAssetEndpointProfileProperties - withSupportedAuthenticationMethods(List supportedAuthenticationMethods) { - this.supportedAuthenticationMethods = supportedAuthenticationMethods; - return this; - } - - /** - * Get the endpointProfileType property: Defines the configuration for the connector type that is being used with - * the endpoint profile. - * - * @return the endpointProfileType value. - */ - public String endpointProfileType() { - return this.endpointProfileType; - } - - /** - * Set the endpointProfileType property: Defines the configuration for the connector type that is being used with - * the endpoint profile. - * - * @param endpointProfileType the endpointProfileType value to set. - * @return the DiscoveredAssetEndpointProfileProperties object itself. - */ - public DiscoveredAssetEndpointProfileProperties withEndpointProfileType(String endpointProfileType) { - this.endpointProfileType = endpointProfileType; - return this; - } - - /** - * Get the discoveryId property: Identifier used to detect changes in the asset endpoint profile. - * - * @return the discoveryId value. - */ - public String discoveryId() { - return this.discoveryId; - } - - /** - * Set the discoveryId property: Identifier used to detect changes in the asset endpoint profile. - * - * @param discoveryId the discoveryId value to set. - * @return the DiscoveredAssetEndpointProfileProperties object itself. - */ - public DiscoveredAssetEndpointProfileProperties withDiscoveryId(String discoveryId) { - this.discoveryId = discoveryId; - return this; - } - - /** - * Get the version property: An integer that is incremented each time the resource is modified. - * - * @return the version value. - */ - public long version() { - return this.version; - } - - /** - * Set the version property: An integer that is incremented each time the resource is modified. - * - * @param version the version value to set. - * @return the DiscoveredAssetEndpointProfileProperties object itself. - */ - public DiscoveredAssetEndpointProfileProperties withVersion(long version) { - this.version = version; - return this; - } - - /** - * Get the provisioningState property: Provisioning state of the resource. - * - * @return the provisioningState value. - */ - public ProvisioningState provisioningState() { - return this.provisioningState; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (targetAddress() == null) { - throw LOGGER.atError() - .log(new IllegalArgumentException( - "Missing required property targetAddress in model DiscoveredAssetEndpointProfileProperties")); - } - if (endpointProfileType() == null) { - throw LOGGER.atError() - .log(new IllegalArgumentException( - "Missing required property endpointProfileType in model DiscoveredAssetEndpointProfileProperties")); - } - if (discoveryId() == null) { - throw LOGGER.atError() - .log(new IllegalArgumentException( - "Missing required property discoveryId in model DiscoveredAssetEndpointProfileProperties")); - } - } - - private static final ClientLogger LOGGER = new ClientLogger(DiscoveredAssetEndpointProfileProperties.class); - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("targetAddress", this.targetAddress); - jsonWriter.writeStringField("endpointProfileType", this.endpointProfileType); - jsonWriter.writeStringField("discoveryId", this.discoveryId); - jsonWriter.writeLongField("version", this.version); - jsonWriter.writeStringField("additionalConfiguration", this.additionalConfiguration); - jsonWriter.writeArrayField("supportedAuthenticationMethods", this.supportedAuthenticationMethods, - (writer, element) -> writer.writeString(element == null ? null : element.toString())); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of DiscoveredAssetEndpointProfileProperties from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of DiscoveredAssetEndpointProfileProperties 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 DiscoveredAssetEndpointProfileProperties. - */ - public static DiscoveredAssetEndpointProfileProperties fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - DiscoveredAssetEndpointProfileProperties deserializedDiscoveredAssetEndpointProfileProperties - = new DiscoveredAssetEndpointProfileProperties(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("targetAddress".equals(fieldName)) { - deserializedDiscoveredAssetEndpointProfileProperties.targetAddress = reader.getString(); - } else if ("endpointProfileType".equals(fieldName)) { - deserializedDiscoveredAssetEndpointProfileProperties.endpointProfileType = reader.getString(); - } else if ("discoveryId".equals(fieldName)) { - deserializedDiscoveredAssetEndpointProfileProperties.discoveryId = reader.getString(); - } else if ("version".equals(fieldName)) { - deserializedDiscoveredAssetEndpointProfileProperties.version = reader.getLong(); - } else if ("additionalConfiguration".equals(fieldName)) { - deserializedDiscoveredAssetEndpointProfileProperties.additionalConfiguration = reader.getString(); - } else if ("supportedAuthenticationMethods".equals(fieldName)) { - List supportedAuthenticationMethods - = reader.readArray(reader1 -> AuthenticationMethod.fromString(reader1.getString())); - deserializedDiscoveredAssetEndpointProfileProperties.supportedAuthenticationMethods - = supportedAuthenticationMethods; - } else if ("provisioningState".equals(fieldName)) { - deserializedDiscoveredAssetEndpointProfileProperties.provisioningState - = ProvisioningState.fromString(reader.getString()); - } else { - reader.skipChildren(); - } - } - - return deserializedDiscoveredAssetEndpointProfileProperties; - }); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAssetEndpointProfileUpdate.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAssetEndpointProfileUpdate.java deleted file mode 100644 index 7391068cc552..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAssetEndpointProfileUpdate.java +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.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.Map; - -/** - * The type used for update operations of the DiscoveredAssetEndpointProfile. - */ -@Fluent -public final class DiscoveredAssetEndpointProfileUpdate - implements JsonSerializable { - /* - * Resource tags. - */ - private Map tags; - - /* - * The resource-specific properties for this resource. - */ - private DiscoveredAssetEndpointProfileUpdateProperties properties; - - /** - * Creates an instance of DiscoveredAssetEndpointProfileUpdate class. - */ - public DiscoveredAssetEndpointProfileUpdate() { - } - - /** - * Get the tags property: Resource tags. - * - * @return the tags value. - */ - public Map tags() { - return this.tags; - } - - /** - * Set the tags property: Resource tags. - * - * @param tags the tags value to set. - * @return the DiscoveredAssetEndpointProfileUpdate object itself. - */ - public DiscoveredAssetEndpointProfileUpdate withTags(Map tags) { - this.tags = tags; - return this; - } - - /** - * Get the properties property: The resource-specific properties for this resource. - * - * @return the properties value. - */ - public DiscoveredAssetEndpointProfileUpdateProperties properties() { - return this.properties; - } - - /** - * Set the properties property: The resource-specific properties for this resource. - * - * @param properties the properties value to set. - * @return the DiscoveredAssetEndpointProfileUpdate object itself. - */ - public DiscoveredAssetEndpointProfileUpdate - withProperties(DiscoveredAssetEndpointProfileUpdateProperties properties) { - this.properties = properties; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (properties() != null) { - properties().validate(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); - jsonWriter.writeJsonField("properties", this.properties); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of DiscoveredAssetEndpointProfileUpdate from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of DiscoveredAssetEndpointProfileUpdate 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 DiscoveredAssetEndpointProfileUpdate. - */ - public static DiscoveredAssetEndpointProfileUpdate fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - DiscoveredAssetEndpointProfileUpdate deserializedDiscoveredAssetEndpointProfileUpdate - = new DiscoveredAssetEndpointProfileUpdate(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("tags".equals(fieldName)) { - Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedDiscoveredAssetEndpointProfileUpdate.tags = tags; - } else if ("properties".equals(fieldName)) { - deserializedDiscoveredAssetEndpointProfileUpdate.properties - = DiscoveredAssetEndpointProfileUpdateProperties.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedDiscoveredAssetEndpointProfileUpdate; - }); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAssetEndpointProfileUpdateProperties.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAssetEndpointProfileUpdateProperties.java deleted file mode 100644 index 9fbf0c0410ff..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAssetEndpointProfileUpdateProperties.java +++ /dev/null @@ -1,255 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.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.List; - -/** - * The updatable properties of the DiscoveredAssetEndpointProfile. - */ -@Fluent -public final class DiscoveredAssetEndpointProfileUpdateProperties - implements JsonSerializable { - /* - * The local valid URI specifying the network address/DNS name of a southbound device. The scheme part of the - * targetAddress URI specifies the type of the device. The additionalConfiguration field holds further connector - * type specific configuration. - */ - private String targetAddress; - - /* - * Stringified JSON that contains connectivity type specific further configuration (e.g. OPC UA, Modbus, ONVIF). - */ - private String additionalConfiguration; - - /* - * List of supported authentication methods supported by the target server. - */ - private List supportedAuthenticationMethods; - - /* - * Defines the configuration for the connector type that is being used with the endpoint profile. - */ - private String endpointProfileType; - - /* - * Identifier used to detect changes in the asset endpoint profile. - */ - private String discoveryId; - - /* - * An integer that is incremented each time the resource is modified. - */ - private Long version; - - /** - * Creates an instance of DiscoveredAssetEndpointProfileUpdateProperties class. - */ - public DiscoveredAssetEndpointProfileUpdateProperties() { - } - - /** - * Get the targetAddress property: The local valid URI specifying the network address/DNS name of a southbound - * device. The scheme part of the targetAddress URI specifies the type of the device. The additionalConfiguration - * field holds further connector type specific configuration. - * - * @return the targetAddress value. - */ - public String targetAddress() { - return this.targetAddress; - } - - /** - * Set the targetAddress property: The local valid URI specifying the network address/DNS name of a southbound - * device. The scheme part of the targetAddress URI specifies the type of the device. The additionalConfiguration - * field holds further connector type specific configuration. - * - * @param targetAddress the targetAddress value to set. - * @return the DiscoveredAssetEndpointProfileUpdateProperties object itself. - */ - public DiscoveredAssetEndpointProfileUpdateProperties withTargetAddress(String targetAddress) { - this.targetAddress = targetAddress; - return this; - } - - /** - * Get the additionalConfiguration property: Stringified JSON that contains connectivity type specific further - * configuration (e.g. OPC UA, Modbus, ONVIF). - * - * @return the additionalConfiguration value. - */ - public String additionalConfiguration() { - return this.additionalConfiguration; - } - - /** - * Set the additionalConfiguration property: Stringified JSON that contains connectivity type specific further - * configuration (e.g. OPC UA, Modbus, ONVIF). - * - * @param additionalConfiguration the additionalConfiguration value to set. - * @return the DiscoveredAssetEndpointProfileUpdateProperties object itself. - */ - public DiscoveredAssetEndpointProfileUpdateProperties withAdditionalConfiguration(String additionalConfiguration) { - this.additionalConfiguration = additionalConfiguration; - return this; - } - - /** - * Get the supportedAuthenticationMethods property: List of supported authentication methods supported by the target - * server. - * - * @return the supportedAuthenticationMethods value. - */ - public List supportedAuthenticationMethods() { - return this.supportedAuthenticationMethods; - } - - /** - * Set the supportedAuthenticationMethods property: List of supported authentication methods supported by the target - * server. - * - * @param supportedAuthenticationMethods the supportedAuthenticationMethods value to set. - * @return the DiscoveredAssetEndpointProfileUpdateProperties object itself. - */ - public DiscoveredAssetEndpointProfileUpdateProperties - withSupportedAuthenticationMethods(List supportedAuthenticationMethods) { - this.supportedAuthenticationMethods = supportedAuthenticationMethods; - return this; - } - - /** - * Get the endpointProfileType property: Defines the configuration for the connector type that is being used with - * the endpoint profile. - * - * @return the endpointProfileType value. - */ - public String endpointProfileType() { - return this.endpointProfileType; - } - - /** - * Set the endpointProfileType property: Defines the configuration for the connector type that is being used with - * the endpoint profile. - * - * @param endpointProfileType the endpointProfileType value to set. - * @return the DiscoveredAssetEndpointProfileUpdateProperties object itself. - */ - public DiscoveredAssetEndpointProfileUpdateProperties withEndpointProfileType(String endpointProfileType) { - this.endpointProfileType = endpointProfileType; - return this; - } - - /** - * Get the discoveryId property: Identifier used to detect changes in the asset endpoint profile. - * - * @return the discoveryId value. - */ - public String discoveryId() { - return this.discoveryId; - } - - /** - * Set the discoveryId property: Identifier used to detect changes in the asset endpoint profile. - * - * @param discoveryId the discoveryId value to set. - * @return the DiscoveredAssetEndpointProfileUpdateProperties object itself. - */ - public DiscoveredAssetEndpointProfileUpdateProperties withDiscoveryId(String discoveryId) { - this.discoveryId = discoveryId; - return this; - } - - /** - * Get the version property: An integer that is incremented each time the resource is modified. - * - * @return the version value. - */ - public Long version() { - return this.version; - } - - /** - * Set the version property: An integer that is incremented each time the resource is modified. - * - * @param version the version value to set. - * @return the DiscoveredAssetEndpointProfileUpdateProperties object itself. - */ - public DiscoveredAssetEndpointProfileUpdateProperties withVersion(Long version) { - this.version = version; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("targetAddress", this.targetAddress); - jsonWriter.writeStringField("additionalConfiguration", this.additionalConfiguration); - jsonWriter.writeArrayField("supportedAuthenticationMethods", this.supportedAuthenticationMethods, - (writer, element) -> writer.writeString(element == null ? null : element.toString())); - jsonWriter.writeStringField("endpointProfileType", this.endpointProfileType); - jsonWriter.writeStringField("discoveryId", this.discoveryId); - jsonWriter.writeNumberField("version", this.version); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of DiscoveredAssetEndpointProfileUpdateProperties from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of DiscoveredAssetEndpointProfileUpdateProperties 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 DiscoveredAssetEndpointProfileUpdateProperties. - */ - public static DiscoveredAssetEndpointProfileUpdateProperties fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - DiscoveredAssetEndpointProfileUpdateProperties deserializedDiscoveredAssetEndpointProfileUpdateProperties - = new DiscoveredAssetEndpointProfileUpdateProperties(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("targetAddress".equals(fieldName)) { - deserializedDiscoveredAssetEndpointProfileUpdateProperties.targetAddress = reader.getString(); - } else if ("additionalConfiguration".equals(fieldName)) { - deserializedDiscoveredAssetEndpointProfileUpdateProperties.additionalConfiguration - = reader.getString(); - } else if ("supportedAuthenticationMethods".equals(fieldName)) { - List supportedAuthenticationMethods - = reader.readArray(reader1 -> AuthenticationMethod.fromString(reader1.getString())); - deserializedDiscoveredAssetEndpointProfileUpdateProperties.supportedAuthenticationMethods - = supportedAuthenticationMethods; - } else if ("endpointProfileType".equals(fieldName)) { - deserializedDiscoveredAssetEndpointProfileUpdateProperties.endpointProfileType = reader.getString(); - } else if ("discoveryId".equals(fieldName)) { - deserializedDiscoveredAssetEndpointProfileUpdateProperties.discoveryId = reader.getString(); - } else if ("version".equals(fieldName)) { - deserializedDiscoveredAssetEndpointProfileUpdateProperties.version - = reader.getNullable(JsonReader::getLong); - } else { - reader.skipChildren(); - } - } - - return deserializedDiscoveredAssetEndpointProfileUpdateProperties; - }); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAssetEndpointProfiles.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAssetEndpointProfiles.java deleted file mode 100644 index 4743ca56ef09..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAssetEndpointProfiles.java +++ /dev/null @@ -1,163 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.models; - -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.Response; -import com.azure.core.util.Context; - -/** - * Resource collection API of DiscoveredAssetEndpointProfiles. - */ -public interface DiscoveredAssetEndpointProfiles { - /** - * Get a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DiscoveredAssetEndpointProfile along with {@link Response}. - */ - Response getByResourceGroupWithResponse(String resourceGroupName, - String discoveredAssetEndpointProfileName, Context context); - - /** - * Get a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DiscoveredAssetEndpointProfile. - */ - DiscoveredAssetEndpointProfile getByResourceGroup(String resourceGroupName, - String discoveredAssetEndpointProfileName); - - /** - * Delete a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - void deleteByResourceGroup(String resourceGroupName, String discoveredAssetEndpointProfileName); - - /** - * Delete a DiscoveredAssetEndpointProfile. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetEndpointProfileName Discovered Asset Endpoint Profile name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - void delete(String resourceGroupName, String discoveredAssetEndpointProfileName, Context context); - - /** - * List DiscoveredAssetEndpointProfile resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAssetEndpointProfile list operation as paginated response with - * {@link PagedIterable}. - */ - PagedIterable listByResourceGroup(String resourceGroupName); - - /** - * List DiscoveredAssetEndpointProfile resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAssetEndpointProfile list operation as paginated response with - * {@link PagedIterable}. - */ - PagedIterable listByResourceGroup(String resourceGroupName, Context context); - - /** - * List DiscoveredAssetEndpointProfile resources by subscription ID. - * - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAssetEndpointProfile list operation as paginated response with - * {@link PagedIterable}. - */ - PagedIterable list(); - - /** - * List DiscoveredAssetEndpointProfile resources by subscription ID. - * - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAssetEndpointProfile list operation as paginated response with - * {@link PagedIterable}. - */ - PagedIterable list(Context context); - - /** - * Get a DiscoveredAssetEndpointProfile. - * - * @param id the resource ID. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DiscoveredAssetEndpointProfile along with {@link Response}. - */ - DiscoveredAssetEndpointProfile getById(String id); - - /** - * Get a DiscoveredAssetEndpointProfile. - * - * @param id the resource ID. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DiscoveredAssetEndpointProfile along with {@link Response}. - */ - Response getByIdWithResponse(String id, Context context); - - /** - * Delete a DiscoveredAssetEndpointProfile. - * - * @param id the resource ID. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - void deleteById(String id); - - /** - * Delete a DiscoveredAssetEndpointProfile. - * - * @param id the resource ID. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - void deleteByIdWithResponse(String id, Context context); - - /** - * Begins definition for a new DiscoveredAssetEndpointProfile resource. - * - * @param name resource name. - * @return the first stage of the new DiscoveredAssetEndpointProfile definition. - */ - DiscoveredAssetEndpointProfile.DefinitionStages.Blank define(String name); -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAssetProperties.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAssetProperties.java deleted file mode 100644 index 294db13d4612..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAssetProperties.java +++ /dev/null @@ -1,571 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.util.logging.ClientLogger; -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; - -/** - * Defines the discovered asset properties. - */ -@Fluent -public final class DiscoveredAssetProperties implements JsonSerializable { - /* - * A reference to the asset endpoint profile (connection information) used by brokers to connect to an endpoint that - * provides data points for this asset. Must provide asset endpoint profile name. - */ - private String assetEndpointProfileRef; - - /* - * Identifier used to detect changes in the asset. - */ - private String discoveryId; - - /* - * An integer that is incremented each time the resource is modified. - */ - private long version; - - /* - * Asset manufacturer name. - */ - private String manufacturer; - - /* - * Asset manufacturer URI. - */ - private String manufacturerUri; - - /* - * Asset model name. - */ - private String model; - - /* - * Asset product code. - */ - private String productCode; - - /* - * Revision number of the hardware. - */ - private String hardwareRevision; - - /* - * Revision number of the software. - */ - private String softwareRevision; - - /* - * Reference to the documentation. - */ - private String documentationUri; - - /* - * Asset serial number. - */ - private String serialNumber; - - /* - * Stringified JSON that contains connector-specific default configuration for all datasets. Each dataset can have - * its own configuration that overrides the default settings here. - */ - private String defaultDatasetsConfiguration; - - /* - * Stringified JSON that contains connector-specific default configuration for all events. Each event can have its - * own configuration that overrides the default settings here. - */ - private String defaultEventsConfiguration; - - /* - * Object that describes the default topic information for the asset. - */ - private Topic defaultTopic; - - /* - * Array of datasets that are part of the asset. Each dataset spec describes the data points that make up the set. - */ - private List datasets; - - /* - * Array of events that are part of the asset. Each event can have per-event configuration. - */ - private List events; - - /* - * Provisioning state of the resource. - */ - private ProvisioningState provisioningState; - - /** - * Creates an instance of DiscoveredAssetProperties class. - */ - public DiscoveredAssetProperties() { - } - - /** - * Get the assetEndpointProfileRef property: A reference to the asset endpoint profile (connection information) used - * by brokers to connect to an endpoint that provides data points for this asset. Must provide asset endpoint - * profile name. - * - * @return the assetEndpointProfileRef value. - */ - public String assetEndpointProfileRef() { - return this.assetEndpointProfileRef; - } - - /** - * Set the assetEndpointProfileRef property: A reference to the asset endpoint profile (connection information) used - * by brokers to connect to an endpoint that provides data points for this asset. Must provide asset endpoint - * profile name. - * - * @param assetEndpointProfileRef the assetEndpointProfileRef value to set. - * @return the DiscoveredAssetProperties object itself. - */ - public DiscoveredAssetProperties withAssetEndpointProfileRef(String assetEndpointProfileRef) { - this.assetEndpointProfileRef = assetEndpointProfileRef; - return this; - } - - /** - * Get the discoveryId property: Identifier used to detect changes in the asset. - * - * @return the discoveryId value. - */ - public String discoveryId() { - return this.discoveryId; - } - - /** - * Set the discoveryId property: Identifier used to detect changes in the asset. - * - * @param discoveryId the discoveryId value to set. - * @return the DiscoveredAssetProperties object itself. - */ - public DiscoveredAssetProperties withDiscoveryId(String discoveryId) { - this.discoveryId = discoveryId; - return this; - } - - /** - * Get the version property: An integer that is incremented each time the resource is modified. - * - * @return the version value. - */ - public long version() { - return this.version; - } - - /** - * Set the version property: An integer that is incremented each time the resource is modified. - * - * @param version the version value to set. - * @return the DiscoveredAssetProperties object itself. - */ - public DiscoveredAssetProperties withVersion(long version) { - this.version = version; - return this; - } - - /** - * Get the manufacturer property: Asset manufacturer name. - * - * @return the manufacturer value. - */ - public String manufacturer() { - return this.manufacturer; - } - - /** - * Set the manufacturer property: Asset manufacturer name. - * - * @param manufacturer the manufacturer value to set. - * @return the DiscoveredAssetProperties object itself. - */ - public DiscoveredAssetProperties withManufacturer(String manufacturer) { - this.manufacturer = manufacturer; - return this; - } - - /** - * Get the manufacturerUri property: Asset manufacturer URI. - * - * @return the manufacturerUri value. - */ - public String manufacturerUri() { - return this.manufacturerUri; - } - - /** - * Set the manufacturerUri property: Asset manufacturer URI. - * - * @param manufacturerUri the manufacturerUri value to set. - * @return the DiscoveredAssetProperties object itself. - */ - public DiscoveredAssetProperties withManufacturerUri(String manufacturerUri) { - this.manufacturerUri = manufacturerUri; - return this; - } - - /** - * Get the model property: Asset model name. - * - * @return the model value. - */ - public String model() { - return this.model; - } - - /** - * Set the model property: Asset model name. - * - * @param model the model value to set. - * @return the DiscoveredAssetProperties object itself. - */ - public DiscoveredAssetProperties withModel(String model) { - this.model = model; - return this; - } - - /** - * Get the productCode property: Asset product code. - * - * @return the productCode value. - */ - public String productCode() { - return this.productCode; - } - - /** - * Set the productCode property: Asset product code. - * - * @param productCode the productCode value to set. - * @return the DiscoveredAssetProperties object itself. - */ - public DiscoveredAssetProperties withProductCode(String productCode) { - this.productCode = productCode; - return this; - } - - /** - * Get the hardwareRevision property: Revision number of the hardware. - * - * @return the hardwareRevision value. - */ - public String hardwareRevision() { - return this.hardwareRevision; - } - - /** - * Set the hardwareRevision property: Revision number of the hardware. - * - * @param hardwareRevision the hardwareRevision value to set. - * @return the DiscoveredAssetProperties object itself. - */ - public DiscoveredAssetProperties withHardwareRevision(String hardwareRevision) { - this.hardwareRevision = hardwareRevision; - return this; - } - - /** - * Get the softwareRevision property: Revision number of the software. - * - * @return the softwareRevision value. - */ - public String softwareRevision() { - return this.softwareRevision; - } - - /** - * Set the softwareRevision property: Revision number of the software. - * - * @param softwareRevision the softwareRevision value to set. - * @return the DiscoveredAssetProperties object itself. - */ - public DiscoveredAssetProperties withSoftwareRevision(String softwareRevision) { - this.softwareRevision = softwareRevision; - return this; - } - - /** - * Get the documentationUri property: Reference to the documentation. - * - * @return the documentationUri value. - */ - public String documentationUri() { - return this.documentationUri; - } - - /** - * Set the documentationUri property: Reference to the documentation. - * - * @param documentationUri the documentationUri value to set. - * @return the DiscoveredAssetProperties object itself. - */ - public DiscoveredAssetProperties withDocumentationUri(String documentationUri) { - this.documentationUri = documentationUri; - return this; - } - - /** - * Get the serialNumber property: Asset serial number. - * - * @return the serialNumber value. - */ - public String serialNumber() { - return this.serialNumber; - } - - /** - * Set the serialNumber property: Asset serial number. - * - * @param serialNumber the serialNumber value to set. - * @return the DiscoveredAssetProperties object itself. - */ - public DiscoveredAssetProperties withSerialNumber(String serialNumber) { - this.serialNumber = serialNumber; - return this; - } - - /** - * Get the defaultDatasetsConfiguration property: Stringified JSON that contains connector-specific default - * configuration for all datasets. Each dataset can have its own configuration that overrides the default settings - * here. - * - * @return the defaultDatasetsConfiguration value. - */ - public String defaultDatasetsConfiguration() { - return this.defaultDatasetsConfiguration; - } - - /** - * Set the defaultDatasetsConfiguration property: Stringified JSON that contains connector-specific default - * configuration for all datasets. Each dataset can have its own configuration that overrides the default settings - * here. - * - * @param defaultDatasetsConfiguration the defaultDatasetsConfiguration value to set. - * @return the DiscoveredAssetProperties object itself. - */ - public DiscoveredAssetProperties withDefaultDatasetsConfiguration(String defaultDatasetsConfiguration) { - this.defaultDatasetsConfiguration = defaultDatasetsConfiguration; - return this; - } - - /** - * Get the defaultEventsConfiguration property: Stringified JSON that contains connector-specific default - * configuration for all events. Each event can have its own configuration that overrides the default settings here. - * - * @return the defaultEventsConfiguration value. - */ - public String defaultEventsConfiguration() { - return this.defaultEventsConfiguration; - } - - /** - * Set the defaultEventsConfiguration property: Stringified JSON that contains connector-specific default - * configuration for all events. Each event can have its own configuration that overrides the default settings here. - * - * @param defaultEventsConfiguration the defaultEventsConfiguration value to set. - * @return the DiscoveredAssetProperties object itself. - */ - public DiscoveredAssetProperties withDefaultEventsConfiguration(String defaultEventsConfiguration) { - this.defaultEventsConfiguration = defaultEventsConfiguration; - return this; - } - - /** - * Get the defaultTopic property: Object that describes the default topic information for the asset. - * - * @return the defaultTopic value. - */ - public Topic defaultTopic() { - return this.defaultTopic; - } - - /** - * Set the defaultTopic property: Object that describes the default topic information for the asset. - * - * @param defaultTopic the defaultTopic value to set. - * @return the DiscoveredAssetProperties object itself. - */ - public DiscoveredAssetProperties withDefaultTopic(Topic defaultTopic) { - this.defaultTopic = defaultTopic; - return this; - } - - /** - * Get the datasets property: Array of datasets that are part of the asset. Each dataset spec describes the data - * points that make up the set. - * - * @return the datasets value. - */ - public List datasets() { - return this.datasets; - } - - /** - * Set the datasets property: Array of datasets that are part of the asset. Each dataset spec describes the data - * points that make up the set. - * - * @param datasets the datasets value to set. - * @return the DiscoveredAssetProperties object itself. - */ - public DiscoveredAssetProperties withDatasets(List datasets) { - this.datasets = datasets; - return this; - } - - /** - * Get the events property: Array of events that are part of the asset. Each event can have per-event configuration. - * - * @return the events value. - */ - public List events() { - return this.events; - } - - /** - * Set the events property: Array of events that are part of the asset. Each event can have per-event configuration. - * - * @param events the events value to set. - * @return the DiscoveredAssetProperties object itself. - */ - public DiscoveredAssetProperties withEvents(List events) { - this.events = events; - return this; - } - - /** - * Get the provisioningState property: Provisioning state of the resource. - * - * @return the provisioningState value. - */ - public ProvisioningState provisioningState() { - return this.provisioningState; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (assetEndpointProfileRef() == null) { - throw LOGGER.atError() - .log(new IllegalArgumentException( - "Missing required property assetEndpointProfileRef in model DiscoveredAssetProperties")); - } - if (discoveryId() == null) { - throw LOGGER.atError() - .log(new IllegalArgumentException( - "Missing required property discoveryId in model DiscoveredAssetProperties")); - } - if (defaultTopic() != null) { - defaultTopic().validate(); - } - if (datasets() != null) { - datasets().forEach(e -> e.validate()); - } - if (events() != null) { - events().forEach(e -> e.validate()); - } - } - - private static final ClientLogger LOGGER = new ClientLogger(DiscoveredAssetProperties.class); - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("assetEndpointProfileRef", this.assetEndpointProfileRef); - jsonWriter.writeStringField("discoveryId", this.discoveryId); - jsonWriter.writeLongField("version", this.version); - jsonWriter.writeStringField("manufacturer", this.manufacturer); - jsonWriter.writeStringField("manufacturerUri", this.manufacturerUri); - jsonWriter.writeStringField("model", this.model); - jsonWriter.writeStringField("productCode", this.productCode); - jsonWriter.writeStringField("hardwareRevision", this.hardwareRevision); - jsonWriter.writeStringField("softwareRevision", this.softwareRevision); - jsonWriter.writeStringField("documentationUri", this.documentationUri); - jsonWriter.writeStringField("serialNumber", this.serialNumber); - jsonWriter.writeStringField("defaultDatasetsConfiguration", this.defaultDatasetsConfiguration); - jsonWriter.writeStringField("defaultEventsConfiguration", this.defaultEventsConfiguration); - jsonWriter.writeJsonField("defaultTopic", this.defaultTopic); - jsonWriter.writeArrayField("datasets", this.datasets, (writer, element) -> writer.writeJson(element)); - jsonWriter.writeArrayField("events", this.events, (writer, element) -> writer.writeJson(element)); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of DiscoveredAssetProperties from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of DiscoveredAssetProperties 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 DiscoveredAssetProperties. - */ - public static DiscoveredAssetProperties fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - DiscoveredAssetProperties deserializedDiscoveredAssetProperties = new DiscoveredAssetProperties(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("assetEndpointProfileRef".equals(fieldName)) { - deserializedDiscoveredAssetProperties.assetEndpointProfileRef = reader.getString(); - } else if ("discoveryId".equals(fieldName)) { - deserializedDiscoveredAssetProperties.discoveryId = reader.getString(); - } else if ("version".equals(fieldName)) { - deserializedDiscoveredAssetProperties.version = reader.getLong(); - } else if ("manufacturer".equals(fieldName)) { - deserializedDiscoveredAssetProperties.manufacturer = reader.getString(); - } else if ("manufacturerUri".equals(fieldName)) { - deserializedDiscoveredAssetProperties.manufacturerUri = reader.getString(); - } else if ("model".equals(fieldName)) { - deserializedDiscoveredAssetProperties.model = reader.getString(); - } else if ("productCode".equals(fieldName)) { - deserializedDiscoveredAssetProperties.productCode = reader.getString(); - } else if ("hardwareRevision".equals(fieldName)) { - deserializedDiscoveredAssetProperties.hardwareRevision = reader.getString(); - } else if ("softwareRevision".equals(fieldName)) { - deserializedDiscoveredAssetProperties.softwareRevision = reader.getString(); - } else if ("documentationUri".equals(fieldName)) { - deserializedDiscoveredAssetProperties.documentationUri = reader.getString(); - } else if ("serialNumber".equals(fieldName)) { - deserializedDiscoveredAssetProperties.serialNumber = reader.getString(); - } else if ("defaultDatasetsConfiguration".equals(fieldName)) { - deserializedDiscoveredAssetProperties.defaultDatasetsConfiguration = reader.getString(); - } else if ("defaultEventsConfiguration".equals(fieldName)) { - deserializedDiscoveredAssetProperties.defaultEventsConfiguration = reader.getString(); - } else if ("defaultTopic".equals(fieldName)) { - deserializedDiscoveredAssetProperties.defaultTopic = Topic.fromJson(reader); - } else if ("datasets".equals(fieldName)) { - List datasets = reader.readArray(reader1 -> DiscoveredDataset.fromJson(reader1)); - deserializedDiscoveredAssetProperties.datasets = datasets; - } else if ("events".equals(fieldName)) { - List events = reader.readArray(reader1 -> DiscoveredEvent.fromJson(reader1)); - deserializedDiscoveredAssetProperties.events = events; - } else if ("provisioningState".equals(fieldName)) { - deserializedDiscoveredAssetProperties.provisioningState - = ProvisioningState.fromString(reader.getString()); - } else { - reader.skipChildren(); - } - } - - return deserializedDiscoveredAssetProperties; - }); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAssetUpdate.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAssetUpdate.java deleted file mode 100644 index 916b32492f3e..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAssetUpdate.java +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.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.Map; - -/** - * The type used for update operations of the DiscoveredAsset. - */ -@Fluent -public final class DiscoveredAssetUpdate implements JsonSerializable { - /* - * Resource tags. - */ - private Map tags; - - /* - * The resource-specific properties for this resource. - */ - private DiscoveredAssetUpdateProperties properties; - - /** - * Creates an instance of DiscoveredAssetUpdate class. - */ - public DiscoveredAssetUpdate() { - } - - /** - * Get the tags property: Resource tags. - * - * @return the tags value. - */ - public Map tags() { - return this.tags; - } - - /** - * Set the tags property: Resource tags. - * - * @param tags the tags value to set. - * @return the DiscoveredAssetUpdate object itself. - */ - public DiscoveredAssetUpdate withTags(Map tags) { - this.tags = tags; - return this; - } - - /** - * Get the properties property: The resource-specific properties for this resource. - * - * @return the properties value. - */ - public DiscoveredAssetUpdateProperties properties() { - return this.properties; - } - - /** - * Set the properties property: The resource-specific properties for this resource. - * - * @param properties the properties value to set. - * @return the DiscoveredAssetUpdate object itself. - */ - public DiscoveredAssetUpdate withProperties(DiscoveredAssetUpdateProperties properties) { - this.properties = properties; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (properties() != null) { - properties().validate(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); - jsonWriter.writeJsonField("properties", this.properties); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of DiscoveredAssetUpdate from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of DiscoveredAssetUpdate 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 DiscoveredAssetUpdate. - */ - public static DiscoveredAssetUpdate fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - DiscoveredAssetUpdate deserializedDiscoveredAssetUpdate = new DiscoveredAssetUpdate(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("tags".equals(fieldName)) { - Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedDiscoveredAssetUpdate.tags = tags; - } else if ("properties".equals(fieldName)) { - deserializedDiscoveredAssetUpdate.properties = DiscoveredAssetUpdateProperties.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedDiscoveredAssetUpdate; - }); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAssetUpdateProperties.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAssetUpdateProperties.java deleted file mode 100644 index a7cffab66be8..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAssetUpdateProperties.java +++ /dev/null @@ -1,508 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.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.List; - -/** - * The updatable properties of the DiscoveredAsset. - */ -@Fluent -public final class DiscoveredAssetUpdateProperties implements JsonSerializable { - /* - * Identifier used to detect changes in the asset. - */ - private String discoveryId; - - /* - * An integer that is incremented each time the resource is modified. - */ - private Long version; - - /* - * Asset manufacturer name. - */ - private String manufacturer; - - /* - * Asset manufacturer URI. - */ - private String manufacturerUri; - - /* - * Asset model name. - */ - private String model; - - /* - * Asset product code. - */ - private String productCode; - - /* - * Revision number of the hardware. - */ - private String hardwareRevision; - - /* - * Revision number of the software. - */ - private String softwareRevision; - - /* - * Reference to the documentation. - */ - private String documentationUri; - - /* - * Asset serial number. - */ - private String serialNumber; - - /* - * Stringified JSON that contains connector-specific default configuration for all datasets. Each dataset can have - * its own configuration that overrides the default settings here. - */ - private String defaultDatasetsConfiguration; - - /* - * Stringified JSON that contains connector-specific default configuration for all events. Each event can have its - * own configuration that overrides the default settings here. - */ - private String defaultEventsConfiguration; - - /* - * Object that describes the default topic information for the asset. - */ - private Topic defaultTopic; - - /* - * Array of datasets that are part of the asset. Each dataset spec describes the data points that make up the set. - */ - private List datasets; - - /* - * Array of events that are part of the asset. Each event can have per-event configuration. - */ - private List events; - - /** - * Creates an instance of DiscoveredAssetUpdateProperties class. - */ - public DiscoveredAssetUpdateProperties() { - } - - /** - * Get the discoveryId property: Identifier used to detect changes in the asset. - * - * @return the discoveryId value. - */ - public String discoveryId() { - return this.discoveryId; - } - - /** - * Set the discoveryId property: Identifier used to detect changes in the asset. - * - * @param discoveryId the discoveryId value to set. - * @return the DiscoveredAssetUpdateProperties object itself. - */ - public DiscoveredAssetUpdateProperties withDiscoveryId(String discoveryId) { - this.discoveryId = discoveryId; - return this; - } - - /** - * Get the version property: An integer that is incremented each time the resource is modified. - * - * @return the version value. - */ - public Long version() { - return this.version; - } - - /** - * Set the version property: An integer that is incremented each time the resource is modified. - * - * @param version the version value to set. - * @return the DiscoveredAssetUpdateProperties object itself. - */ - public DiscoveredAssetUpdateProperties withVersion(Long version) { - this.version = version; - return this; - } - - /** - * Get the manufacturer property: Asset manufacturer name. - * - * @return the manufacturer value. - */ - public String manufacturer() { - return this.manufacturer; - } - - /** - * Set the manufacturer property: Asset manufacturer name. - * - * @param manufacturer the manufacturer value to set. - * @return the DiscoveredAssetUpdateProperties object itself. - */ - public DiscoveredAssetUpdateProperties withManufacturer(String manufacturer) { - this.manufacturer = manufacturer; - return this; - } - - /** - * Get the manufacturerUri property: Asset manufacturer URI. - * - * @return the manufacturerUri value. - */ - public String manufacturerUri() { - return this.manufacturerUri; - } - - /** - * Set the manufacturerUri property: Asset manufacturer URI. - * - * @param manufacturerUri the manufacturerUri value to set. - * @return the DiscoveredAssetUpdateProperties object itself. - */ - public DiscoveredAssetUpdateProperties withManufacturerUri(String manufacturerUri) { - this.manufacturerUri = manufacturerUri; - return this; - } - - /** - * Get the model property: Asset model name. - * - * @return the model value. - */ - public String model() { - return this.model; - } - - /** - * Set the model property: Asset model name. - * - * @param model the model value to set. - * @return the DiscoveredAssetUpdateProperties object itself. - */ - public DiscoveredAssetUpdateProperties withModel(String model) { - this.model = model; - return this; - } - - /** - * Get the productCode property: Asset product code. - * - * @return the productCode value. - */ - public String productCode() { - return this.productCode; - } - - /** - * Set the productCode property: Asset product code. - * - * @param productCode the productCode value to set. - * @return the DiscoveredAssetUpdateProperties object itself. - */ - public DiscoveredAssetUpdateProperties withProductCode(String productCode) { - this.productCode = productCode; - return this; - } - - /** - * Get the hardwareRevision property: Revision number of the hardware. - * - * @return the hardwareRevision value. - */ - public String hardwareRevision() { - return this.hardwareRevision; - } - - /** - * Set the hardwareRevision property: Revision number of the hardware. - * - * @param hardwareRevision the hardwareRevision value to set. - * @return the DiscoveredAssetUpdateProperties object itself. - */ - public DiscoveredAssetUpdateProperties withHardwareRevision(String hardwareRevision) { - this.hardwareRevision = hardwareRevision; - return this; - } - - /** - * Get the softwareRevision property: Revision number of the software. - * - * @return the softwareRevision value. - */ - public String softwareRevision() { - return this.softwareRevision; - } - - /** - * Set the softwareRevision property: Revision number of the software. - * - * @param softwareRevision the softwareRevision value to set. - * @return the DiscoveredAssetUpdateProperties object itself. - */ - public DiscoveredAssetUpdateProperties withSoftwareRevision(String softwareRevision) { - this.softwareRevision = softwareRevision; - return this; - } - - /** - * Get the documentationUri property: Reference to the documentation. - * - * @return the documentationUri value. - */ - public String documentationUri() { - return this.documentationUri; - } - - /** - * Set the documentationUri property: Reference to the documentation. - * - * @param documentationUri the documentationUri value to set. - * @return the DiscoveredAssetUpdateProperties object itself. - */ - public DiscoveredAssetUpdateProperties withDocumentationUri(String documentationUri) { - this.documentationUri = documentationUri; - return this; - } - - /** - * Get the serialNumber property: Asset serial number. - * - * @return the serialNumber value. - */ - public String serialNumber() { - return this.serialNumber; - } - - /** - * Set the serialNumber property: Asset serial number. - * - * @param serialNumber the serialNumber value to set. - * @return the DiscoveredAssetUpdateProperties object itself. - */ - public DiscoveredAssetUpdateProperties withSerialNumber(String serialNumber) { - this.serialNumber = serialNumber; - return this; - } - - /** - * Get the defaultDatasetsConfiguration property: Stringified JSON that contains connector-specific default - * configuration for all datasets. Each dataset can have its own configuration that overrides the default settings - * here. - * - * @return the defaultDatasetsConfiguration value. - */ - public String defaultDatasetsConfiguration() { - return this.defaultDatasetsConfiguration; - } - - /** - * Set the defaultDatasetsConfiguration property: Stringified JSON that contains connector-specific default - * configuration for all datasets. Each dataset can have its own configuration that overrides the default settings - * here. - * - * @param defaultDatasetsConfiguration the defaultDatasetsConfiguration value to set. - * @return the DiscoveredAssetUpdateProperties object itself. - */ - public DiscoveredAssetUpdateProperties withDefaultDatasetsConfiguration(String defaultDatasetsConfiguration) { - this.defaultDatasetsConfiguration = defaultDatasetsConfiguration; - return this; - } - - /** - * Get the defaultEventsConfiguration property: Stringified JSON that contains connector-specific default - * configuration for all events. Each event can have its own configuration that overrides the default settings here. - * - * @return the defaultEventsConfiguration value. - */ - public String defaultEventsConfiguration() { - return this.defaultEventsConfiguration; - } - - /** - * Set the defaultEventsConfiguration property: Stringified JSON that contains connector-specific default - * configuration for all events. Each event can have its own configuration that overrides the default settings here. - * - * @param defaultEventsConfiguration the defaultEventsConfiguration value to set. - * @return the DiscoveredAssetUpdateProperties object itself. - */ - public DiscoveredAssetUpdateProperties withDefaultEventsConfiguration(String defaultEventsConfiguration) { - this.defaultEventsConfiguration = defaultEventsConfiguration; - return this; - } - - /** - * Get the defaultTopic property: Object that describes the default topic information for the asset. - * - * @return the defaultTopic value. - */ - public Topic defaultTopic() { - return this.defaultTopic; - } - - /** - * Set the defaultTopic property: Object that describes the default topic information for the asset. - * - * @param defaultTopic the defaultTopic value to set. - * @return the DiscoveredAssetUpdateProperties object itself. - */ - public DiscoveredAssetUpdateProperties withDefaultTopic(Topic defaultTopic) { - this.defaultTopic = defaultTopic; - return this; - } - - /** - * Get the datasets property: Array of datasets that are part of the asset. Each dataset spec describes the data - * points that make up the set. - * - * @return the datasets value. - */ - public List datasets() { - return this.datasets; - } - - /** - * Set the datasets property: Array of datasets that are part of the asset. Each dataset spec describes the data - * points that make up the set. - * - * @param datasets the datasets value to set. - * @return the DiscoveredAssetUpdateProperties object itself. - */ - public DiscoveredAssetUpdateProperties withDatasets(List datasets) { - this.datasets = datasets; - return this; - } - - /** - * Get the events property: Array of events that are part of the asset. Each event can have per-event configuration. - * - * @return the events value. - */ - public List events() { - return this.events; - } - - /** - * Set the events property: Array of events that are part of the asset. Each event can have per-event configuration. - * - * @param events the events value to set. - * @return the DiscoveredAssetUpdateProperties object itself. - */ - public DiscoveredAssetUpdateProperties withEvents(List events) { - this.events = events; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (defaultTopic() != null) { - defaultTopic().validate(); - } - if (datasets() != null) { - datasets().forEach(e -> e.validate()); - } - if (events() != null) { - events().forEach(e -> e.validate()); - } - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("discoveryId", this.discoveryId); - jsonWriter.writeNumberField("version", this.version); - jsonWriter.writeStringField("manufacturer", this.manufacturer); - jsonWriter.writeStringField("manufacturerUri", this.manufacturerUri); - jsonWriter.writeStringField("model", this.model); - jsonWriter.writeStringField("productCode", this.productCode); - jsonWriter.writeStringField("hardwareRevision", this.hardwareRevision); - jsonWriter.writeStringField("softwareRevision", this.softwareRevision); - jsonWriter.writeStringField("documentationUri", this.documentationUri); - jsonWriter.writeStringField("serialNumber", this.serialNumber); - jsonWriter.writeStringField("defaultDatasetsConfiguration", this.defaultDatasetsConfiguration); - jsonWriter.writeStringField("defaultEventsConfiguration", this.defaultEventsConfiguration); - jsonWriter.writeJsonField("defaultTopic", this.defaultTopic); - jsonWriter.writeArrayField("datasets", this.datasets, (writer, element) -> writer.writeJson(element)); - jsonWriter.writeArrayField("events", this.events, (writer, element) -> writer.writeJson(element)); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of DiscoveredAssetUpdateProperties from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of DiscoveredAssetUpdateProperties 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 DiscoveredAssetUpdateProperties. - */ - public static DiscoveredAssetUpdateProperties fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - DiscoveredAssetUpdateProperties deserializedDiscoveredAssetUpdateProperties - = new DiscoveredAssetUpdateProperties(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("discoveryId".equals(fieldName)) { - deserializedDiscoveredAssetUpdateProperties.discoveryId = reader.getString(); - } else if ("version".equals(fieldName)) { - deserializedDiscoveredAssetUpdateProperties.version = reader.getNullable(JsonReader::getLong); - } else if ("manufacturer".equals(fieldName)) { - deserializedDiscoveredAssetUpdateProperties.manufacturer = reader.getString(); - } else if ("manufacturerUri".equals(fieldName)) { - deserializedDiscoveredAssetUpdateProperties.manufacturerUri = reader.getString(); - } else if ("model".equals(fieldName)) { - deserializedDiscoveredAssetUpdateProperties.model = reader.getString(); - } else if ("productCode".equals(fieldName)) { - deserializedDiscoveredAssetUpdateProperties.productCode = reader.getString(); - } else if ("hardwareRevision".equals(fieldName)) { - deserializedDiscoveredAssetUpdateProperties.hardwareRevision = reader.getString(); - } else if ("softwareRevision".equals(fieldName)) { - deserializedDiscoveredAssetUpdateProperties.softwareRevision = reader.getString(); - } else if ("documentationUri".equals(fieldName)) { - deserializedDiscoveredAssetUpdateProperties.documentationUri = reader.getString(); - } else if ("serialNumber".equals(fieldName)) { - deserializedDiscoveredAssetUpdateProperties.serialNumber = reader.getString(); - } else if ("defaultDatasetsConfiguration".equals(fieldName)) { - deserializedDiscoveredAssetUpdateProperties.defaultDatasetsConfiguration = reader.getString(); - } else if ("defaultEventsConfiguration".equals(fieldName)) { - deserializedDiscoveredAssetUpdateProperties.defaultEventsConfiguration = reader.getString(); - } else if ("defaultTopic".equals(fieldName)) { - deserializedDiscoveredAssetUpdateProperties.defaultTopic = Topic.fromJson(reader); - } else if ("datasets".equals(fieldName)) { - List datasets = reader.readArray(reader1 -> DiscoveredDataset.fromJson(reader1)); - deserializedDiscoveredAssetUpdateProperties.datasets = datasets; - } else if ("events".equals(fieldName)) { - List events = reader.readArray(reader1 -> DiscoveredEvent.fromJson(reader1)); - deserializedDiscoveredAssetUpdateProperties.events = events; - } else { - reader.skipChildren(); - } - } - - return deserializedDiscoveredAssetUpdateProperties; - }); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAssets.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAssets.java deleted file mode 100644 index b573d15f1268..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredAssets.java +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.models; - -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.Response; -import com.azure.core.util.Context; - -/** - * Resource collection API of DiscoveredAssets. - */ -public interface DiscoveredAssets { - /** - * Get a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DiscoveredAsset along with {@link Response}. - */ - Response getByResourceGroupWithResponse(String resourceGroupName, String discoveredAssetName, - Context context); - - /** - * Get a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DiscoveredAsset. - */ - DiscoveredAsset getByResourceGroup(String resourceGroupName, String discoveredAssetName); - - /** - * Delete a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - void deleteByResourceGroup(String resourceGroupName, String discoveredAssetName); - - /** - * Delete a DiscoveredAsset. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param discoveredAssetName Discovered Asset name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - void delete(String resourceGroupName, String discoveredAssetName, Context context); - - /** - * List DiscoveredAsset resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAsset list operation as paginated response with {@link PagedIterable}. - */ - PagedIterable listByResourceGroup(String resourceGroupName); - - /** - * List DiscoveredAsset resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAsset list operation as paginated response with {@link PagedIterable}. - */ - PagedIterable listByResourceGroup(String resourceGroupName, Context context); - - /** - * List DiscoveredAsset resources by subscription ID. - * - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAsset list operation as paginated response with {@link PagedIterable}. - */ - PagedIterable list(); - - /** - * List DiscoveredAsset resources by subscription ID. - * - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a DiscoveredAsset list operation as paginated response with {@link PagedIterable}. - */ - PagedIterable list(Context context); - - /** - * Get a DiscoveredAsset. - * - * @param id the resource ID. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DiscoveredAsset along with {@link Response}. - */ - DiscoveredAsset getById(String id); - - /** - * Get a DiscoveredAsset. - * - * @param id the resource ID. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DiscoveredAsset along with {@link Response}. - */ - Response getByIdWithResponse(String id, Context context); - - /** - * Delete a DiscoveredAsset. - * - * @param id the resource ID. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - void deleteById(String id); - - /** - * Delete a DiscoveredAsset. - * - * @param id the resource ID. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - void deleteByIdWithResponse(String id, Context context); - - /** - * Begins definition for a new DiscoveredAsset resource. - * - * @param name resource name. - * @return the first stage of the new DiscoveredAsset definition. - */ - DiscoveredAsset.DefinitionStages.Blank define(String name); -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredDataPoint.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredDataPoint.java deleted file mode 100644 index bf5234410ffd..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredDataPoint.java +++ /dev/null @@ -1,202 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.logging.ClientLogger; -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.OffsetDateTime; -import java.time.format.DateTimeFormatter; - -/** - * Defines the data point properties. - */ -@Fluent -public final class DiscoveredDataPoint implements JsonSerializable { - /* - * The name of the data point. - */ - private String name; - - /* - * The address of the source of the data in the asset (e.g. URL) so that a client can access the data source on the - * asset. - */ - private String dataSource; - - /* - * Stringified JSON that contains connector-specific configuration for the data point. For OPC UA, this could - * include configuration like, publishingInterval, samplingInterval, and queueSize. - */ - private String dataPointConfiguration; - - /* - * UTC timestamp indicating when the data point was added or modified. - */ - private OffsetDateTime lastUpdatedOn; - - /** - * Creates an instance of DiscoveredDataPoint class. - */ - public DiscoveredDataPoint() { - } - - /** - * Get the name property: The name of the data point. - * - * @return the name value. - */ - public String name() { - return this.name; - } - - /** - * Set the name property: The name of the data point. - * - * @param name the name value to set. - * @return the DiscoveredDataPoint object itself. - */ - public DiscoveredDataPoint withName(String name) { - this.name = name; - return this; - } - - /** - * Get the dataSource property: The address of the source of the data in the asset (e.g. URL) so that a client can - * access the data source on the asset. - * - * @return the dataSource value. - */ - public String dataSource() { - return this.dataSource; - } - - /** - * Set the dataSource property: The address of the source of the data in the asset (e.g. URL) so that a client can - * access the data source on the asset. - * - * @param dataSource the dataSource value to set. - * @return the DiscoveredDataPoint object itself. - */ - public DiscoveredDataPoint withDataSource(String dataSource) { - this.dataSource = dataSource; - return this; - } - - /** - * Get the dataPointConfiguration property: Stringified JSON that contains connector-specific configuration for the - * data point. For OPC UA, this could include configuration like, publishingInterval, samplingInterval, and - * queueSize. - * - * @return the dataPointConfiguration value. - */ - public String dataPointConfiguration() { - return this.dataPointConfiguration; - } - - /** - * Set the dataPointConfiguration property: Stringified JSON that contains connector-specific configuration for the - * data point. For OPC UA, this could include configuration like, publishingInterval, samplingInterval, and - * queueSize. - * - * @param dataPointConfiguration the dataPointConfiguration value to set. - * @return the DiscoveredDataPoint object itself. - */ - public DiscoveredDataPoint withDataPointConfiguration(String dataPointConfiguration) { - this.dataPointConfiguration = dataPointConfiguration; - return this; - } - - /** - * Get the lastUpdatedOn property: UTC timestamp indicating when the data point was added or modified. - * - * @return the lastUpdatedOn value. - */ - public OffsetDateTime lastUpdatedOn() { - return this.lastUpdatedOn; - } - - /** - * Set the lastUpdatedOn property: UTC timestamp indicating when the data point was added or modified. - * - * @param lastUpdatedOn the lastUpdatedOn value to set. - * @return the DiscoveredDataPoint object itself. - */ - public DiscoveredDataPoint withLastUpdatedOn(OffsetDateTime lastUpdatedOn) { - this.lastUpdatedOn = lastUpdatedOn; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (name() == null) { - throw LOGGER.atError() - .log(new IllegalArgumentException("Missing required property name in model DiscoveredDataPoint")); - } - if (dataSource() == null) { - throw LOGGER.atError() - .log(new IllegalArgumentException("Missing required property dataSource in model DiscoveredDataPoint")); - } - } - - private static final ClientLogger LOGGER = new ClientLogger(DiscoveredDataPoint.class); - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("name", this.name); - jsonWriter.writeStringField("dataSource", this.dataSource); - jsonWriter.writeStringField("dataPointConfiguration", this.dataPointConfiguration); - jsonWriter.writeStringField("lastUpdatedOn", - this.lastUpdatedOn == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.lastUpdatedOn)); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of DiscoveredDataPoint from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of DiscoveredDataPoint 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 DiscoveredDataPoint. - */ - public static DiscoveredDataPoint fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - DiscoveredDataPoint deserializedDiscoveredDataPoint = new DiscoveredDataPoint(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("name".equals(fieldName)) { - deserializedDiscoveredDataPoint.name = reader.getString(); - } else if ("dataSource".equals(fieldName)) { - deserializedDiscoveredDataPoint.dataSource = reader.getString(); - } else if ("dataPointConfiguration".equals(fieldName)) { - deserializedDiscoveredDataPoint.dataPointConfiguration = reader.getString(); - } else if ("lastUpdatedOn".equals(fieldName)) { - deserializedDiscoveredDataPoint.lastUpdatedOn = reader - .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); - } else { - reader.skipChildren(); - } - } - - return deserializedDiscoveredDataPoint; - }); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredDataset.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredDataset.java deleted file mode 100644 index fd0d627590b4..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredDataset.java +++ /dev/null @@ -1,199 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.util.logging.ClientLogger; -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; - -/** - * Defines the dataset properties. - */ -@Fluent -public final class DiscoveredDataset implements JsonSerializable { - /* - * Name of the dataset. - */ - private String name; - - /* - * Stringified JSON that contains connector-specific properties that describes configuration for the specific - * dataset. - */ - private String datasetConfiguration; - - /* - * Object that describes the topic information for the specific dataset. - */ - private Topic topic; - - /* - * Array of data points that are part of the dataset. Each data point can have per-data point configuration. - */ - private List dataPoints; - - /** - * Creates an instance of DiscoveredDataset class. - */ - public DiscoveredDataset() { - } - - /** - * Get the name property: Name of the dataset. - * - * @return the name value. - */ - public String name() { - return this.name; - } - - /** - * Set the name property: Name of the dataset. - * - * @param name the name value to set. - * @return the DiscoveredDataset object itself. - */ - public DiscoveredDataset withName(String name) { - this.name = name; - return this; - } - - /** - * Get the datasetConfiguration property: Stringified JSON that contains connector-specific properties that - * describes configuration for the specific dataset. - * - * @return the datasetConfiguration value. - */ - public String datasetConfiguration() { - return this.datasetConfiguration; - } - - /** - * Set the datasetConfiguration property: Stringified JSON that contains connector-specific properties that - * describes configuration for the specific dataset. - * - * @param datasetConfiguration the datasetConfiguration value to set. - * @return the DiscoveredDataset object itself. - */ - public DiscoveredDataset withDatasetConfiguration(String datasetConfiguration) { - this.datasetConfiguration = datasetConfiguration; - return this; - } - - /** - * Get the topic property: Object that describes the topic information for the specific dataset. - * - * @return the topic value. - */ - public Topic topic() { - return this.topic; - } - - /** - * Set the topic property: Object that describes the topic information for the specific dataset. - * - * @param topic the topic value to set. - * @return the DiscoveredDataset object itself. - */ - public DiscoveredDataset withTopic(Topic topic) { - this.topic = topic; - return this; - } - - /** - * Get the dataPoints property: Array of data points that are part of the dataset. Each data point can have per-data - * point configuration. - * - * @return the dataPoints value. - */ - public List dataPoints() { - return this.dataPoints; - } - - /** - * Set the dataPoints property: Array of data points that are part of the dataset. Each data point can have per-data - * point configuration. - * - * @param dataPoints the dataPoints value to set. - * @return the DiscoveredDataset object itself. - */ - public DiscoveredDataset withDataPoints(List dataPoints) { - this.dataPoints = dataPoints; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (name() == null) { - throw LOGGER.atError() - .log(new IllegalArgumentException("Missing required property name in model DiscoveredDataset")); - } - if (topic() != null) { - topic().validate(); - } - if (dataPoints() != null) { - dataPoints().forEach(e -> e.validate()); - } - } - - private static final ClientLogger LOGGER = new ClientLogger(DiscoveredDataset.class); - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("name", this.name); - jsonWriter.writeStringField("datasetConfiguration", this.datasetConfiguration); - jsonWriter.writeJsonField("topic", this.topic); - jsonWriter.writeArrayField("dataPoints", this.dataPoints, (writer, element) -> writer.writeJson(element)); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of DiscoveredDataset from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of DiscoveredDataset 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 DiscoveredDataset. - */ - public static DiscoveredDataset fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - DiscoveredDataset deserializedDiscoveredDataset = new DiscoveredDataset(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("name".equals(fieldName)) { - deserializedDiscoveredDataset.name = reader.getString(); - } else if ("datasetConfiguration".equals(fieldName)) { - deserializedDiscoveredDataset.datasetConfiguration = reader.getString(); - } else if ("topic".equals(fieldName)) { - deserializedDiscoveredDataset.topic = Topic.fromJson(reader); - } else if ("dataPoints".equals(fieldName)) { - List dataPoints - = reader.readArray(reader1 -> DiscoveredDataPoint.fromJson(reader1)); - deserializedDiscoveredDataset.dataPoints = dataPoints; - } else { - reader.skipChildren(); - } - } - - return deserializedDiscoveredDataset; - }); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredEvent.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredEvent.java deleted file mode 100644 index 1a8a4f07f1dc..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/DiscoveredEvent.java +++ /dev/null @@ -1,231 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.logging.ClientLogger; -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.OffsetDateTime; -import java.time.format.DateTimeFormatter; - -/** - * Defines the event properties. - */ -@Fluent -public final class DiscoveredEvent implements JsonSerializable { - /* - * The name of the event. - */ - private String name; - - /* - * The address of the notifier of the event in the asset (e.g. URL) so that a client can access the event on the - * asset. - */ - private String eventNotifier; - - /* - * Stringified JSON that contains connector-specific configuration for the event. For OPC UA, this could include - * configuration like, publishingInterval, samplingInterval, and queueSize. - */ - private String eventConfiguration; - - /* - * Object that describes the topic information for the specific event. - */ - private Topic topic; - - /* - * UTC timestamp indicating when the event was added or modified. - */ - private OffsetDateTime lastUpdatedOn; - - /** - * Creates an instance of DiscoveredEvent class. - */ - public DiscoveredEvent() { - } - - /** - * Get the name property: The name of the event. - * - * @return the name value. - */ - public String name() { - return this.name; - } - - /** - * Set the name property: The name of the event. - * - * @param name the name value to set. - * @return the DiscoveredEvent object itself. - */ - public DiscoveredEvent withName(String name) { - this.name = name; - return this; - } - - /** - * Get the eventNotifier property: The address of the notifier of the event in the asset (e.g. URL) so that a client - * can access the event on the asset. - * - * @return the eventNotifier value. - */ - public String eventNotifier() { - return this.eventNotifier; - } - - /** - * Set the eventNotifier property: The address of the notifier of the event in the asset (e.g. URL) so that a client - * can access the event on the asset. - * - * @param eventNotifier the eventNotifier value to set. - * @return the DiscoveredEvent object itself. - */ - public DiscoveredEvent withEventNotifier(String eventNotifier) { - this.eventNotifier = eventNotifier; - return this; - } - - /** - * Get the eventConfiguration property: Stringified JSON that contains connector-specific configuration for the - * event. For OPC UA, this could include configuration like, publishingInterval, samplingInterval, and queueSize. - * - * @return the eventConfiguration value. - */ - public String eventConfiguration() { - return this.eventConfiguration; - } - - /** - * Set the eventConfiguration property: Stringified JSON that contains connector-specific configuration for the - * event. For OPC UA, this could include configuration like, publishingInterval, samplingInterval, and queueSize. - * - * @param eventConfiguration the eventConfiguration value to set. - * @return the DiscoveredEvent object itself. - */ - public DiscoveredEvent withEventConfiguration(String eventConfiguration) { - this.eventConfiguration = eventConfiguration; - return this; - } - - /** - * Get the topic property: Object that describes the topic information for the specific event. - * - * @return the topic value. - */ - public Topic topic() { - return this.topic; - } - - /** - * Set the topic property: Object that describes the topic information for the specific event. - * - * @param topic the topic value to set. - * @return the DiscoveredEvent object itself. - */ - public DiscoveredEvent withTopic(Topic topic) { - this.topic = topic; - return this; - } - - /** - * Get the lastUpdatedOn property: UTC timestamp indicating when the event was added or modified. - * - * @return the lastUpdatedOn value. - */ - public OffsetDateTime lastUpdatedOn() { - return this.lastUpdatedOn; - } - - /** - * Set the lastUpdatedOn property: UTC timestamp indicating when the event was added or modified. - * - * @param lastUpdatedOn the lastUpdatedOn value to set. - * @return the DiscoveredEvent object itself. - */ - public DiscoveredEvent withLastUpdatedOn(OffsetDateTime lastUpdatedOn) { - this.lastUpdatedOn = lastUpdatedOn; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (name() == null) { - throw LOGGER.atError() - .log(new IllegalArgumentException("Missing required property name in model DiscoveredEvent")); - } - if (eventNotifier() == null) { - throw LOGGER.atError() - .log(new IllegalArgumentException("Missing required property eventNotifier in model DiscoveredEvent")); - } - if (topic() != null) { - topic().validate(); - } - } - - private static final ClientLogger LOGGER = new ClientLogger(DiscoveredEvent.class); - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("name", this.name); - jsonWriter.writeStringField("eventNotifier", this.eventNotifier); - jsonWriter.writeStringField("eventConfiguration", this.eventConfiguration); - jsonWriter.writeJsonField("topic", this.topic); - jsonWriter.writeStringField("lastUpdatedOn", - this.lastUpdatedOn == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.lastUpdatedOn)); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of DiscoveredEvent from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of DiscoveredEvent 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 DiscoveredEvent. - */ - public static DiscoveredEvent fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - DiscoveredEvent deserializedDiscoveredEvent = new DiscoveredEvent(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("name".equals(fieldName)) { - deserializedDiscoveredEvent.name = reader.getString(); - } else if ("eventNotifier".equals(fieldName)) { - deserializedDiscoveredEvent.eventNotifier = reader.getString(); - } else if ("eventConfiguration".equals(fieldName)) { - deserializedDiscoveredEvent.eventConfiguration = reader.getString(); - } else if ("topic".equals(fieldName)) { - deserializedDiscoveredEvent.topic = Topic.fromJson(reader); - } else if ("lastUpdatedOn".equals(fieldName)) { - deserializedDiscoveredEvent.lastUpdatedOn = reader - .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); - } else { - reader.skipChildren(); - } - } - - return deserializedDiscoveredEvent; - }); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/Format.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/Format.java deleted file mode 100644 index 775301f93450..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/Format.java +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.models; - -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * Defines the schema format. - */ -public final class Format extends ExpandableStringEnum { - /** - * JSON Schema version draft 7 format. - */ - public static final Format JSON_SCHEMA_DRAFT7 = fromString("JsonSchema/draft-07"); - - /** - * Delta format. - */ - public static final Format DELTA_1_0 = fromString("Delta/1.0"); - - /** - * Creates a new instance of Format value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Deprecated - public Format() { - } - - /** - * Creates or finds a Format from its string representation. - * - * @param name a name to look for. - * @return the corresponding Format. - */ - public static Format fromString(String name) { - return fromString(name, Format.class); - } - - /** - * Gets known Format values. - * - * @return known Format values. - */ - public static Collection values() { - return values(Format.class); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/Schema.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/Schema.java deleted file mode 100644 index bde48886f14c..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/Schema.java +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.models; - -import com.azure.core.management.SystemData; -import com.azure.core.util.Context; -import com.azure.resourcemanager.deviceregistry.fluent.models.SchemaInner; - -/** - * An immutable client-side representation of Schema. - */ -public interface Schema { - /** - * Gets the id property: Fully qualified resource Id for the resource. - * - * @return the id value. - */ - String id(); - - /** - * Gets the name property: The name of the resource. - * - * @return the name value. - */ - String name(); - - /** - * Gets the type property: The type of the resource. - * - * @return the type value. - */ - String type(); - - /** - * Gets the properties property: The resource-specific properties for this resource. - * - * @return the properties value. - */ - SchemaProperties properties(); - - /** - * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. - * - * @return the systemData value. - */ - SystemData systemData(); - - /** - * Gets the inner com.azure.resourcemanager.deviceregistry.fluent.models.SchemaInner object. - * - * @return the inner object. - */ - SchemaInner innerModel(); - - /** - * The entirety of the Schema definition. - */ - interface Definition - extends DefinitionStages.Blank, DefinitionStages.WithParentResource, DefinitionStages.WithCreate { - } - - /** - * The Schema definition stages. - */ - interface DefinitionStages { - /** - * The first stage of the Schema definition. - */ - interface Blank extends WithParentResource { - } - - /** - * The stage of the Schema definition allowing to specify parent resource. - */ - interface WithParentResource { - /** - * Specifies resourceGroupName, schemaRegistryName. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @return the next definition stage. - */ - WithCreate withExistingSchemaRegistry(String resourceGroupName, String schemaRegistryName); - } - - /** - * The stage of the Schema definition which contains all the minimum required properties for the resource to be - * created, but also allows for any other optional properties to be specified. - */ - interface WithCreate extends DefinitionStages.WithProperties { - /** - * Executes the create request. - * - * @return the created resource. - */ - Schema create(); - - /** - * Executes the create request. - * - * @param context The context to associate with this operation. - * @return the created resource. - */ - Schema create(Context context); - } - - /** - * The stage of the Schema definition allowing to specify properties. - */ - interface WithProperties { - /** - * Specifies the properties property: The resource-specific properties for this resource.. - * - * @param properties The resource-specific properties for this resource. - * @return the next definition stage. - */ - WithCreate withProperties(SchemaProperties properties); - } - } - - /** - * Refreshes the resource to sync with Azure. - * - * @return the refreshed resource. - */ - Schema refresh(); - - /** - * Refreshes the resource to sync with Azure. - * - * @param context The context to associate with this operation. - * @return the refreshed resource. - */ - Schema refresh(Context context); -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaProperties.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaProperties.java deleted file mode 100644 index 52c5195de45d..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaProperties.java +++ /dev/null @@ -1,251 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.util.logging.ClientLogger; -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.Map; - -/** - * Defines the schema properties. - */ -@Fluent -public final class SchemaProperties implements JsonSerializable { - /* - * Globally unique, immutable, non-reusable id. - */ - private String uuid; - - /* - * Human-readable display name. - */ - private String displayName; - - /* - * Human-readable description of the schema. - */ - private String description; - - /* - * Format of the schema. - */ - private Format format; - - /* - * Type of the schema. - */ - private SchemaType schemaType; - - /* - * Provisioning state of the resource. - */ - private ProvisioningState provisioningState; - - /* - * Schema tags. - */ - private Map tags; - - /** - * Creates an instance of SchemaProperties class. - */ - public SchemaProperties() { - } - - /** - * Get the uuid property: Globally unique, immutable, non-reusable id. - * - * @return the uuid value. - */ - public String uuid() { - return this.uuid; - } - - /** - * Get the displayName property: Human-readable display name. - * - * @return the displayName value. - */ - public String displayName() { - return this.displayName; - } - - /** - * Set the displayName property: Human-readable display name. - * - * @param displayName the displayName value to set. - * @return the SchemaProperties object itself. - */ - public SchemaProperties withDisplayName(String displayName) { - this.displayName = displayName; - return this; - } - - /** - * Get the description property: Human-readable description of the schema. - * - * @return the description value. - */ - public String description() { - return this.description; - } - - /** - * Set the description property: Human-readable description of the schema. - * - * @param description the description value to set. - * @return the SchemaProperties object itself. - */ - public SchemaProperties withDescription(String description) { - this.description = description; - return this; - } - - /** - * Get the format property: Format of the schema. - * - * @return the format value. - */ - public Format format() { - return this.format; - } - - /** - * Set the format property: Format of the schema. - * - * @param format the format value to set. - * @return the SchemaProperties object itself. - */ - public SchemaProperties withFormat(Format format) { - this.format = format; - return this; - } - - /** - * Get the schemaType property: Type of the schema. - * - * @return the schemaType value. - */ - public SchemaType schemaType() { - return this.schemaType; - } - - /** - * Set the schemaType property: Type of the schema. - * - * @param schemaType the schemaType value to set. - * @return the SchemaProperties object itself. - */ - public SchemaProperties withSchemaType(SchemaType schemaType) { - this.schemaType = schemaType; - return this; - } - - /** - * Get the provisioningState property: Provisioning state of the resource. - * - * @return the provisioningState value. - */ - public ProvisioningState provisioningState() { - return this.provisioningState; - } - - /** - * Get the tags property: Schema tags. - * - * @return the tags value. - */ - public Map tags() { - return this.tags; - } - - /** - * Set the tags property: Schema tags. - * - * @param tags the tags value to set. - * @return the SchemaProperties object itself. - */ - public SchemaProperties withTags(Map tags) { - this.tags = tags; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (format() == null) { - throw LOGGER.atError() - .log(new IllegalArgumentException("Missing required property format in model SchemaProperties")); - } - if (schemaType() == null) { - throw LOGGER.atError() - .log(new IllegalArgumentException("Missing required property schemaType in model SchemaProperties")); - } - } - - private static final ClientLogger LOGGER = new ClientLogger(SchemaProperties.class); - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("format", this.format == null ? null : this.format.toString()); - jsonWriter.writeStringField("schemaType", this.schemaType == null ? null : this.schemaType.toString()); - jsonWriter.writeStringField("displayName", this.displayName); - jsonWriter.writeStringField("description", this.description); - jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SchemaProperties from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SchemaProperties 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 SchemaProperties. - */ - public static SchemaProperties fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SchemaProperties deserializedSchemaProperties = new SchemaProperties(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("format".equals(fieldName)) { - deserializedSchemaProperties.format = Format.fromString(reader.getString()); - } else if ("schemaType".equals(fieldName)) { - deserializedSchemaProperties.schemaType = SchemaType.fromString(reader.getString()); - } else if ("uuid".equals(fieldName)) { - deserializedSchemaProperties.uuid = reader.getString(); - } else if ("displayName".equals(fieldName)) { - deserializedSchemaProperties.displayName = reader.getString(); - } else if ("description".equals(fieldName)) { - deserializedSchemaProperties.description = reader.getString(); - } else if ("provisioningState".equals(fieldName)) { - deserializedSchemaProperties.provisioningState = ProvisioningState.fromString(reader.getString()); - } else if ("tags".equals(fieldName)) { - Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedSchemaProperties.tags = tags; - } else { - reader.skipChildren(); - } - } - - return deserializedSchemaProperties; - }); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaRegistries.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaRegistries.java deleted file mode 100644 index c04e14791f50..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaRegistries.java +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.models; - -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.Response; -import com.azure.core.util.Context; - -/** - * Resource collection API of SchemaRegistries. - */ -public interface SchemaRegistries { - /** - * Get a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a SchemaRegistry along with {@link Response}. - */ - Response getByResourceGroupWithResponse(String resourceGroupName, String schemaRegistryName, - Context context); - - /** - * Get a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a SchemaRegistry. - */ - SchemaRegistry getByResourceGroup(String resourceGroupName, String schemaRegistryName); - - /** - * Delete a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - void deleteByResourceGroup(String resourceGroupName, String schemaRegistryName); - - /** - * Delete a SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - void delete(String resourceGroupName, String schemaRegistryName, Context context); - - /** - * List SchemaRegistry resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaRegistry list operation as paginated response with {@link PagedIterable}. - */ - PagedIterable listByResourceGroup(String resourceGroupName); - - /** - * List SchemaRegistry resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaRegistry list operation as paginated response with {@link PagedIterable}. - */ - PagedIterable listByResourceGroup(String resourceGroupName, Context context); - - /** - * List SchemaRegistry resources by subscription ID. - * - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaRegistry list operation as paginated response with {@link PagedIterable}. - */ - PagedIterable list(); - - /** - * List SchemaRegistry resources by subscription ID. - * - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaRegistry list operation as paginated response with {@link PagedIterable}. - */ - PagedIterable list(Context context); - - /** - * Get a SchemaRegistry. - * - * @param id the resource ID. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a SchemaRegistry along with {@link Response}. - */ - SchemaRegistry getById(String id); - - /** - * Get a SchemaRegistry. - * - * @param id the resource ID. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a SchemaRegistry along with {@link Response}. - */ - Response getByIdWithResponse(String id, Context context); - - /** - * Delete a SchemaRegistry. - * - * @param id the resource ID. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - void deleteById(String id); - - /** - * Delete a SchemaRegistry. - * - * @param id the resource ID. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - void deleteByIdWithResponse(String id, Context context); - - /** - * Begins definition for a new SchemaRegistry resource. - * - * @param name resource name. - * @return the first stage of the new SchemaRegistry definition. - */ - SchemaRegistry.DefinitionStages.Blank define(String name); -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaRegistry.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaRegistry.java deleted file mode 100644 index 8a0f9ab98e46..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaRegistry.java +++ /dev/null @@ -1,299 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.models; - -import com.azure.core.management.Region; -import com.azure.core.management.SystemData; -import com.azure.core.util.Context; -import com.azure.resourcemanager.deviceregistry.fluent.models.SchemaRegistryInner; -import java.util.Map; - -/** - * An immutable client-side representation of SchemaRegistry. - */ -public interface SchemaRegistry { - /** - * Gets the id property: Fully qualified resource Id for the resource. - * - * @return the id value. - */ - String id(); - - /** - * Gets the name property: The name of the resource. - * - * @return the name value. - */ - String name(); - - /** - * Gets the type property: The type of the resource. - * - * @return the type value. - */ - String type(); - - /** - * Gets the location property: The geo-location where the resource lives. - * - * @return the location value. - */ - String location(); - - /** - * Gets the tags property: Resource tags. - * - * @return the tags value. - */ - Map tags(); - - /** - * Gets the properties property: The resource-specific properties for this resource. - * - * @return the properties value. - */ - SchemaRegistryProperties properties(); - - /** - * Gets the identity property: The managed service identities assigned to this resource. - * - * @return the identity value. - */ - SystemAssignedServiceIdentity identity(); - - /** - * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. - * - * @return the systemData value. - */ - SystemData systemData(); - - /** - * Gets the region of the resource. - * - * @return the region of the resource. - */ - Region region(); - - /** - * Gets the name of the resource region. - * - * @return the name of the resource region. - */ - String regionName(); - - /** - * Gets the name of the resource group. - * - * @return the name of the resource group. - */ - String resourceGroupName(); - - /** - * Gets the inner com.azure.resourcemanager.deviceregistry.fluent.models.SchemaRegistryInner object. - * - * @return the inner object. - */ - SchemaRegistryInner innerModel(); - - /** - * The entirety of the SchemaRegistry definition. - */ - interface Definition extends DefinitionStages.Blank, DefinitionStages.WithLocation, - DefinitionStages.WithResourceGroup, DefinitionStages.WithCreate { - } - - /** - * The SchemaRegistry definition stages. - */ - interface DefinitionStages { - /** - * The first stage of the SchemaRegistry definition. - */ - interface Blank extends WithLocation { - } - - /** - * The stage of the SchemaRegistry definition allowing to specify location. - */ - interface WithLocation { - /** - * Specifies the region for the resource. - * - * @param location The geo-location where the resource lives. - * @return the next definition stage. - */ - WithResourceGroup withRegion(Region location); - - /** - * Specifies the region for the resource. - * - * @param location The geo-location where the resource lives. - * @return the next definition stage. - */ - WithResourceGroup withRegion(String location); - } - - /** - * The stage of the SchemaRegistry definition allowing to specify parent resource. - */ - interface WithResourceGroup { - /** - * Specifies resourceGroupName. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @return the next definition stage. - */ - WithCreate withExistingResourceGroup(String resourceGroupName); - } - - /** - * The stage of the SchemaRegistry definition which contains all the minimum required properties for the - * resource to be created, but also allows for any other optional properties to be specified. - */ - interface WithCreate - extends DefinitionStages.WithTags, DefinitionStages.WithProperties, DefinitionStages.WithIdentity { - /** - * Executes the create request. - * - * @return the created resource. - */ - SchemaRegistry create(); - - /** - * Executes the create request. - * - * @param context The context to associate with this operation. - * @return the created resource. - */ - SchemaRegistry create(Context context); - } - - /** - * The stage of the SchemaRegistry definition allowing to specify tags. - */ - interface WithTags { - /** - * Specifies the tags property: Resource tags.. - * - * @param tags Resource tags. - * @return the next definition stage. - */ - WithCreate withTags(Map tags); - } - - /** - * The stage of the SchemaRegistry definition allowing to specify properties. - */ - interface WithProperties { - /** - * Specifies the properties property: The resource-specific properties for this resource.. - * - * @param properties The resource-specific properties for this resource. - * @return the next definition stage. - */ - WithCreate withProperties(SchemaRegistryProperties properties); - } - - /** - * The stage of the SchemaRegistry definition allowing to specify identity. - */ - interface WithIdentity { - /** - * Specifies the identity property: The managed service identities assigned to this resource.. - * - * @param identity The managed service identities assigned to this resource. - * @return the next definition stage. - */ - WithCreate withIdentity(SystemAssignedServiceIdentity identity); - } - } - - /** - * Begins update for the SchemaRegistry resource. - * - * @return the stage of resource update. - */ - SchemaRegistry.Update update(); - - /** - * The template for SchemaRegistry update. - */ - interface Update extends UpdateStages.WithTags, UpdateStages.WithIdentity, UpdateStages.WithProperties { - /** - * Executes the update request. - * - * @return the updated resource. - */ - SchemaRegistry apply(); - - /** - * Executes the update request. - * - * @param context The context to associate with this operation. - * @return the updated resource. - */ - SchemaRegistry apply(Context context); - } - - /** - * The SchemaRegistry update stages. - */ - interface UpdateStages { - /** - * The stage of the SchemaRegistry update allowing to specify tags. - */ - interface WithTags { - /** - * Specifies the tags property: Resource tags.. - * - * @param tags Resource tags. - * @return the next definition stage. - */ - Update withTags(Map tags); - } - - /** - * The stage of the SchemaRegistry update allowing to specify identity. - */ - interface WithIdentity { - /** - * Specifies the identity property: The managed service identities assigned to this resource.. - * - * @param identity The managed service identities assigned to this resource. - * @return the next definition stage. - */ - Update withIdentity(SystemAssignedServiceIdentity identity); - } - - /** - * The stage of the SchemaRegistry update allowing to specify properties. - */ - interface WithProperties { - /** - * Specifies the properties property: The resource-specific properties for this resource.. - * - * @param properties The resource-specific properties for this resource. - * @return the next definition stage. - */ - Update withProperties(SchemaRegistryUpdateProperties properties); - } - } - - /** - * Refreshes the resource to sync with Azure. - * - * @return the refreshed resource. - */ - SchemaRegistry refresh(); - - /** - * Refreshes the resource to sync with Azure. - * - * @param context The context to associate with this operation. - * @return the refreshed resource. - */ - SchemaRegistry refresh(Context context); -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaRegistryProperties.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaRegistryProperties.java deleted file mode 100644 index 8b792b0c4f70..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaRegistryProperties.java +++ /dev/null @@ -1,224 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.util.logging.ClientLogger; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * Defines the schema registry properties. - */ -@Fluent -public final class SchemaRegistryProperties implements JsonSerializable { - /* - * Globally unique, immutable, non-reusable id. - */ - private String uuid; - - /* - * Schema registry namespace. Uniquely identifies a schema registry within a tenant. - */ - private String namespace; - - /* - * Human-readable display name. - */ - private String displayName; - - /* - * Human-readable description of the schema registry. - */ - private String description; - - /* - * The Storage Account's Container URL where schemas will be stored. - */ - private String storageAccountContainerUrl; - - /* - * Provisioning state of the resource. - */ - private ProvisioningState provisioningState; - - /** - * Creates an instance of SchemaRegistryProperties class. - */ - public SchemaRegistryProperties() { - } - - /** - * Get the uuid property: Globally unique, immutable, non-reusable id. - * - * @return the uuid value. - */ - public String uuid() { - return this.uuid; - } - - /** - * Get the namespace property: Schema registry namespace. Uniquely identifies a schema registry within a tenant. - * - * @return the namespace value. - */ - public String namespace() { - return this.namespace; - } - - /** - * Set the namespace property: Schema registry namespace. Uniquely identifies a schema registry within a tenant. - * - * @param namespace the namespace value to set. - * @return the SchemaRegistryProperties object itself. - */ - public SchemaRegistryProperties withNamespace(String namespace) { - this.namespace = namespace; - return this; - } - - /** - * Get the displayName property: Human-readable display name. - * - * @return the displayName value. - */ - public String displayName() { - return this.displayName; - } - - /** - * Set the displayName property: Human-readable display name. - * - * @param displayName the displayName value to set. - * @return the SchemaRegistryProperties object itself. - */ - public SchemaRegistryProperties withDisplayName(String displayName) { - this.displayName = displayName; - return this; - } - - /** - * Get the description property: Human-readable description of the schema registry. - * - * @return the description value. - */ - public String description() { - return this.description; - } - - /** - * Set the description property: Human-readable description of the schema registry. - * - * @param description the description value to set. - * @return the SchemaRegistryProperties object itself. - */ - public SchemaRegistryProperties withDescription(String description) { - this.description = description; - return this; - } - - /** - * Get the storageAccountContainerUrl property: The Storage Account's Container URL where schemas will be stored. - * - * @return the storageAccountContainerUrl value. - */ - public String storageAccountContainerUrl() { - return this.storageAccountContainerUrl; - } - - /** - * Set the storageAccountContainerUrl property: The Storage Account's Container URL where schemas will be stored. - * - * @param storageAccountContainerUrl the storageAccountContainerUrl value to set. - * @return the SchemaRegistryProperties object itself. - */ - public SchemaRegistryProperties withStorageAccountContainerUrl(String storageAccountContainerUrl) { - this.storageAccountContainerUrl = storageAccountContainerUrl; - return this; - } - - /** - * Get the provisioningState property: Provisioning state of the resource. - * - * @return the provisioningState value. - */ - public ProvisioningState provisioningState() { - return this.provisioningState; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (namespace() == null) { - throw LOGGER.atError() - .log(new IllegalArgumentException( - "Missing required property namespace in model SchemaRegistryProperties")); - } - if (storageAccountContainerUrl() == null) { - throw LOGGER.atError() - .log(new IllegalArgumentException( - "Missing required property storageAccountContainerUrl in model SchemaRegistryProperties")); - } - } - - private static final ClientLogger LOGGER = new ClientLogger(SchemaRegistryProperties.class); - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("namespace", this.namespace); - jsonWriter.writeStringField("storageAccountContainerUrl", this.storageAccountContainerUrl); - jsonWriter.writeStringField("displayName", this.displayName); - jsonWriter.writeStringField("description", this.description); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SchemaRegistryProperties from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SchemaRegistryProperties 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 SchemaRegistryProperties. - */ - public static SchemaRegistryProperties fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SchemaRegistryProperties deserializedSchemaRegistryProperties = new SchemaRegistryProperties(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("namespace".equals(fieldName)) { - deserializedSchemaRegistryProperties.namespace = reader.getString(); - } else if ("storageAccountContainerUrl".equals(fieldName)) { - deserializedSchemaRegistryProperties.storageAccountContainerUrl = reader.getString(); - } else if ("uuid".equals(fieldName)) { - deserializedSchemaRegistryProperties.uuid = reader.getString(); - } else if ("displayName".equals(fieldName)) { - deserializedSchemaRegistryProperties.displayName = reader.getString(); - } else if ("description".equals(fieldName)) { - deserializedSchemaRegistryProperties.description = reader.getString(); - } else if ("provisioningState".equals(fieldName)) { - deserializedSchemaRegistryProperties.provisioningState - = ProvisioningState.fromString(reader.getString()); - } else { - reader.skipChildren(); - } - } - - return deserializedSchemaRegistryProperties; - }); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaRegistryUpdate.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaRegistryUpdate.java deleted file mode 100644 index 05f3cfc4a579..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaRegistryUpdate.java +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.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.Map; - -/** - * The type used for update operations of the SchemaRegistry. - */ -@Fluent -public final class SchemaRegistryUpdate implements JsonSerializable { - /* - * The managed service identities assigned to this resource. - */ - private SystemAssignedServiceIdentity identity; - - /* - * Resource tags. - */ - private Map tags; - - /* - * The resource-specific properties for this resource. - */ - private SchemaRegistryUpdateProperties properties; - - /** - * Creates an instance of SchemaRegistryUpdate class. - */ - public SchemaRegistryUpdate() { - } - - /** - * Get the identity property: The managed service identities assigned to this resource. - * - * @return the identity value. - */ - public SystemAssignedServiceIdentity identity() { - return this.identity; - } - - /** - * Set the identity property: The managed service identities assigned to this resource. - * - * @param identity the identity value to set. - * @return the SchemaRegistryUpdate object itself. - */ - public SchemaRegistryUpdate withIdentity(SystemAssignedServiceIdentity identity) { - this.identity = identity; - return this; - } - - /** - * Get the tags property: Resource tags. - * - * @return the tags value. - */ - public Map tags() { - return this.tags; - } - - /** - * Set the tags property: Resource tags. - * - * @param tags the tags value to set. - * @return the SchemaRegistryUpdate object itself. - */ - public SchemaRegistryUpdate withTags(Map tags) { - this.tags = tags; - return this; - } - - /** - * Get the properties property: The resource-specific properties for this resource. - * - * @return the properties value. - */ - public SchemaRegistryUpdateProperties properties() { - return this.properties; - } - - /** - * Set the properties property: The resource-specific properties for this resource. - * - * @param properties the properties value to set. - * @return the SchemaRegistryUpdate object itself. - */ - public SchemaRegistryUpdate withProperties(SchemaRegistryUpdateProperties properties) { - this.properties = properties; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (identity() != null) { - identity().validate(); - } - if (properties() != null) { - properties().validate(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeJsonField("identity", this.identity); - jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); - jsonWriter.writeJsonField("properties", this.properties); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SchemaRegistryUpdate from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SchemaRegistryUpdate 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 SchemaRegistryUpdate. - */ - public static SchemaRegistryUpdate fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SchemaRegistryUpdate deserializedSchemaRegistryUpdate = new SchemaRegistryUpdate(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("identity".equals(fieldName)) { - deserializedSchemaRegistryUpdate.identity = SystemAssignedServiceIdentity.fromJson(reader); - } else if ("tags".equals(fieldName)) { - Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedSchemaRegistryUpdate.tags = tags; - } else if ("properties".equals(fieldName)) { - deserializedSchemaRegistryUpdate.properties = SchemaRegistryUpdateProperties.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedSchemaRegistryUpdate; - }); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaRegistryUpdateProperties.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaRegistryUpdateProperties.java deleted file mode 100644 index 9aed811d776f..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaRegistryUpdateProperties.java +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.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; - -/** - * The updatable properties of the SchemaRegistry. - */ -@Fluent -public final class SchemaRegistryUpdateProperties implements JsonSerializable { - /* - * Human-readable display name. - */ - private String displayName; - - /* - * Human-readable description of the schema registry. - */ - private String description; - - /** - * Creates an instance of SchemaRegistryUpdateProperties class. - */ - public SchemaRegistryUpdateProperties() { - } - - /** - * Get the displayName property: Human-readable display name. - * - * @return the displayName value. - */ - public String displayName() { - return this.displayName; - } - - /** - * Set the displayName property: Human-readable display name. - * - * @param displayName the displayName value to set. - * @return the SchemaRegistryUpdateProperties object itself. - */ - public SchemaRegistryUpdateProperties withDisplayName(String displayName) { - this.displayName = displayName; - return this; - } - - /** - * Get the description property: Human-readable description of the schema registry. - * - * @return the description value. - */ - public String description() { - return this.description; - } - - /** - * Set the description property: Human-readable description of the schema registry. - * - * @param description the description value to set. - * @return the SchemaRegistryUpdateProperties object itself. - */ - public SchemaRegistryUpdateProperties withDescription(String description) { - this.description = description; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("displayName", this.displayName); - jsonWriter.writeStringField("description", this.description); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SchemaRegistryUpdateProperties from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SchemaRegistryUpdateProperties 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 SchemaRegistryUpdateProperties. - */ - public static SchemaRegistryUpdateProperties fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SchemaRegistryUpdateProperties deserializedSchemaRegistryUpdateProperties - = new SchemaRegistryUpdateProperties(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("displayName".equals(fieldName)) { - deserializedSchemaRegistryUpdateProperties.displayName = reader.getString(); - } else if ("description".equals(fieldName)) { - deserializedSchemaRegistryUpdateProperties.description = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedSchemaRegistryUpdateProperties; - }); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaType.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaType.java deleted file mode 100644 index 8e48c5748b6c..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaType.java +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.models; - -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * Defines the schema type. - */ -public final class SchemaType extends ExpandableStringEnum { - /** - * Message Schema schema type. - */ - public static final SchemaType MESSAGE_SCHEMA = fromString("MessageSchema"); - - /** - * Creates a new instance of SchemaType value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Deprecated - public SchemaType() { - } - - /** - * Creates or finds a SchemaType from its string representation. - * - * @param name a name to look for. - * @return the corresponding SchemaType. - */ - public static SchemaType fromString(String name) { - return fromString(name, SchemaType.class); - } - - /** - * Gets known SchemaType values. - * - * @return known SchemaType values. - */ - public static Collection values() { - return values(SchemaType.class); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaVersion.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaVersion.java deleted file mode 100644 index e981d2031fb6..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaVersion.java +++ /dev/null @@ -1,138 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.models; - -import com.azure.core.management.SystemData; -import com.azure.core.util.Context; -import com.azure.resourcemanager.deviceregistry.fluent.models.SchemaVersionInner; - -/** - * An immutable client-side representation of SchemaVersion. - */ -public interface SchemaVersion { - /** - * Gets the id property: Fully qualified resource Id for the resource. - * - * @return the id value. - */ - String id(); - - /** - * Gets the name property: The name of the resource. - * - * @return the name value. - */ - String name(); - - /** - * Gets the type property: The type of the resource. - * - * @return the type value. - */ - String type(); - - /** - * Gets the properties property: The resource-specific properties for this resource. - * - * @return the properties value. - */ - SchemaVersionProperties properties(); - - /** - * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. - * - * @return the systemData value. - */ - SystemData systemData(); - - /** - * Gets the inner com.azure.resourcemanager.deviceregistry.fluent.models.SchemaVersionInner object. - * - * @return the inner object. - */ - SchemaVersionInner innerModel(); - - /** - * The entirety of the SchemaVersion definition. - */ - interface Definition - extends DefinitionStages.Blank, DefinitionStages.WithParentResource, DefinitionStages.WithCreate { - } - - /** - * The SchemaVersion definition stages. - */ - interface DefinitionStages { - /** - * The first stage of the SchemaVersion definition. - */ - interface Blank extends WithParentResource { - } - - /** - * The stage of the SchemaVersion definition allowing to specify parent resource. - */ - interface WithParentResource { - /** - * Specifies resourceGroupName, schemaRegistryName, schemaName. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @return the next definition stage. - */ - WithCreate withExistingSchema(String resourceGroupName, String schemaRegistryName, String schemaName); - } - - /** - * The stage of the SchemaVersion definition which contains all the minimum required properties for the resource - * to be created, but also allows for any other optional properties to be specified. - */ - interface WithCreate extends DefinitionStages.WithProperties { - /** - * Executes the create request. - * - * @return the created resource. - */ - SchemaVersion create(); - - /** - * Executes the create request. - * - * @param context The context to associate with this operation. - * @return the created resource. - */ - SchemaVersion create(Context context); - } - - /** - * The stage of the SchemaVersion definition allowing to specify properties. - */ - interface WithProperties { - /** - * Specifies the properties property: The resource-specific properties for this resource.. - * - * @param properties The resource-specific properties for this resource. - * @return the next definition stage. - */ - WithCreate withProperties(SchemaVersionProperties properties); - } - } - - /** - * Refreshes the resource to sync with Azure. - * - * @return the refreshed resource. - */ - SchemaVersion refresh(); - - /** - * Refreshes the resource to sync with Azure. - * - * @param context The context to associate with this operation. - * @return the refreshed resource. - */ - SchemaVersion refresh(Context context); -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaVersionProperties.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaVersionProperties.java deleted file mode 100644 index ef2cef5c9f23..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaVersionProperties.java +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.util.logging.ClientLogger; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * Defines the schema version properties. - */ -@Fluent -public final class SchemaVersionProperties implements JsonSerializable { - /* - * Globally unique, immutable, non-reusable id. - */ - private String uuid; - - /* - * Human-readable description of the schema. - */ - private String description; - - /* - * Schema content. - */ - private String schemaContent; - - /* - * Hash of the schema content. - */ - private String hash; - - /* - * Provisioning state of the resource. - */ - private ProvisioningState provisioningState; - - /** - * Creates an instance of SchemaVersionProperties class. - */ - public SchemaVersionProperties() { - } - - /** - * Get the uuid property: Globally unique, immutable, non-reusable id. - * - * @return the uuid value. - */ - public String uuid() { - return this.uuid; - } - - /** - * Get the description property: Human-readable description of the schema. - * - * @return the description value. - */ - public String description() { - return this.description; - } - - /** - * Set the description property: Human-readable description of the schema. - * - * @param description the description value to set. - * @return the SchemaVersionProperties object itself. - */ - public SchemaVersionProperties withDescription(String description) { - this.description = description; - return this; - } - - /** - * Get the schemaContent property: Schema content. - * - * @return the schemaContent value. - */ - public String schemaContent() { - return this.schemaContent; - } - - /** - * Set the schemaContent property: Schema content. - * - * @param schemaContent the schemaContent value to set. - * @return the SchemaVersionProperties object itself. - */ - public SchemaVersionProperties withSchemaContent(String schemaContent) { - this.schemaContent = schemaContent; - return this; - } - - /** - * Get the hash property: Hash of the schema content. - * - * @return the hash value. - */ - public String hash() { - return this.hash; - } - - /** - * Get the provisioningState property: Provisioning state of the resource. - * - * @return the provisioningState value. - */ - public ProvisioningState provisioningState() { - return this.provisioningState; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (schemaContent() == null) { - throw LOGGER.atError() - .log(new IllegalArgumentException( - "Missing required property schemaContent in model SchemaVersionProperties")); - } - } - - private static final ClientLogger LOGGER = new ClientLogger(SchemaVersionProperties.class); - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("schemaContent", this.schemaContent); - jsonWriter.writeStringField("description", this.description); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SchemaVersionProperties from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SchemaVersionProperties 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 SchemaVersionProperties. - */ - public static SchemaVersionProperties fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SchemaVersionProperties deserializedSchemaVersionProperties = new SchemaVersionProperties(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("schemaContent".equals(fieldName)) { - deserializedSchemaVersionProperties.schemaContent = reader.getString(); - } else if ("uuid".equals(fieldName)) { - deserializedSchemaVersionProperties.uuid = reader.getString(); - } else if ("description".equals(fieldName)) { - deserializedSchemaVersionProperties.description = reader.getString(); - } else if ("hash".equals(fieldName)) { - deserializedSchemaVersionProperties.hash = reader.getString(); - } else if ("provisioningState".equals(fieldName)) { - deserializedSchemaVersionProperties.provisioningState - = ProvisioningState.fromString(reader.getString()); - } else { - reader.skipChildren(); - } - } - - return deserializedSchemaVersionProperties; - }); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaVersions.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaVersions.java deleted file mode 100644 index 5bf06a2dabee..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SchemaVersions.java +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.models; - -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.Response; -import com.azure.core.util.Context; - -/** - * Resource collection API of SchemaVersions. - */ -public interface SchemaVersions { - /** - * Get a SchemaVersion. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param schemaVersionName Schema version name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a SchemaVersion along with {@link Response}. - */ - Response getWithResponse(String resourceGroupName, String schemaRegistryName, String schemaName, - String schemaVersionName, Context context); - - /** - * Get a SchemaVersion. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param schemaVersionName Schema version name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a SchemaVersion. - */ - SchemaVersion get(String resourceGroupName, String schemaRegistryName, String schemaName, String schemaVersionName); - - /** - * Delete a SchemaVersion. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param schemaVersionName Schema version name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response}. - */ - Response deleteWithResponse(String resourceGroupName, String schemaRegistryName, String schemaName, - String schemaVersionName, Context context); - - /** - * Delete a SchemaVersion. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param schemaVersionName Schema version name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - void delete(String resourceGroupName, String schemaRegistryName, String schemaName, String schemaVersionName); - - /** - * List SchemaVersion resources by Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaVersion list operation as paginated response with {@link PagedIterable}. - */ - PagedIterable listBySchema(String resourceGroupName, String schemaRegistryName, String schemaName); - - /** - * List SchemaVersion resources by Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SchemaVersion list operation as paginated response with {@link PagedIterable}. - */ - PagedIterable listBySchema(String resourceGroupName, String schemaRegistryName, String schemaName, - Context context); - - /** - * Get a SchemaVersion. - * - * @param id the resource ID. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a SchemaVersion along with {@link Response}. - */ - SchemaVersion getById(String id); - - /** - * Get a SchemaVersion. - * - * @param id the resource ID. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a SchemaVersion along with {@link Response}. - */ - Response getByIdWithResponse(String id, Context context); - - /** - * Delete a SchemaVersion. - * - * @param id the resource ID. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - void deleteById(String id); - - /** - * Delete a SchemaVersion. - * - * @param id the resource ID. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response}. - */ - Response deleteByIdWithResponse(String id, Context context); - - /** - * Begins definition for a new SchemaVersion resource. - * - * @param name resource name. - * @return the first stage of the new SchemaVersion definition. - */ - SchemaVersion.DefinitionStages.Blank define(String name); -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/Schemas.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/Schemas.java deleted file mode 100644 index 458c2cae223d..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/Schemas.java +++ /dev/null @@ -1,147 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.models; - -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.Response; -import com.azure.core.util.Context; - -/** - * Resource collection API of Schemas. - */ -public interface Schemas { - /** - * Get a Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Schema along with {@link Response}. - */ - Response getWithResponse(String resourceGroupName, String schemaRegistryName, String schemaName, - Context context); - - /** - * Get a Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Schema. - */ - Schema get(String resourceGroupName, String schemaRegistryName, String schemaName); - - /** - * Delete a Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response}. - */ - Response deleteWithResponse(String resourceGroupName, String schemaRegistryName, String schemaName, - Context context); - - /** - * Delete a Schema. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param schemaName Schema name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - void delete(String resourceGroupName, String schemaRegistryName, String schemaName); - - /** - * List Schema resources by SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Schema list operation as paginated response with {@link PagedIterable}. - */ - PagedIterable listBySchemaRegistry(String resourceGroupName, String schemaRegistryName); - - /** - * List Schema resources by SchemaRegistry. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param schemaRegistryName Schema registry name parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Schema list operation as paginated response with {@link PagedIterable}. - */ - PagedIterable listBySchemaRegistry(String resourceGroupName, String schemaRegistryName, Context context); - - /** - * Get a Schema. - * - * @param id the resource ID. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Schema along with {@link Response}. - */ - Schema getById(String id); - - /** - * Get a Schema. - * - * @param id the resource ID. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Schema along with {@link Response}. - */ - Response getByIdWithResponse(String id, Context context); - - /** - * Delete a Schema. - * - * @param id the resource ID. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - void deleteById(String id); - - /** - * Delete a Schema. - * - * @param id the resource ID. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response}. - */ - Response deleteByIdWithResponse(String id, Context context); - - /** - * Begins definition for a new Schema resource. - * - * @param name resource name. - * @return the first stage of the new Schema definition. - */ - Schema.DefinitionStages.Blank define(String name); -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SystemAssignedServiceIdentity.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SystemAssignedServiceIdentity.java deleted file mode 100644 index 1e29f42eddab..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SystemAssignedServiceIdentity.java +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.util.logging.ClientLogger; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * Managed service identity (either system assigned, or none). - */ -@Fluent -public final class SystemAssignedServiceIdentity implements JsonSerializable { - /* - * The service principal ID of the system assigned identity. This property will only be provided for a system - * assigned identity. - */ - private String principalId; - - /* - * The tenant ID of the system assigned identity. This property will only be provided for a system assigned - * identity. - */ - private String tenantId; - - /* - * The type of managed identity assigned to this resource. - */ - private SystemAssignedServiceIdentityType type; - - /** - * Creates an instance of SystemAssignedServiceIdentity class. - */ - public SystemAssignedServiceIdentity() { - } - - /** - * Get the principalId property: The service principal ID of the system assigned identity. This property will only - * be provided for a system assigned identity. - * - * @return the principalId value. - */ - public String principalId() { - return this.principalId; - } - - /** - * Get the tenantId property: The tenant ID of the system assigned identity. This property will only be provided for - * a system assigned identity. - * - * @return the tenantId value. - */ - public String tenantId() { - return this.tenantId; - } - - /** - * Get the type property: The type of managed identity assigned to this resource. - * - * @return the type value. - */ - public SystemAssignedServiceIdentityType type() { - return this.type; - } - - /** - * Set the type property: The type of managed identity assigned to this resource. - * - * @param type the type value to set. - * @return the SystemAssignedServiceIdentity object itself. - */ - public SystemAssignedServiceIdentity withType(SystemAssignedServiceIdentityType type) { - this.type = type; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (type() == null) { - throw LOGGER.atError() - .log(new IllegalArgumentException( - "Missing required property type in model SystemAssignedServiceIdentity")); - } - } - - private static final ClientLogger LOGGER = new ClientLogger(SystemAssignedServiceIdentity.class); - - /** - * {@inheritDoc} - */ - @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 SystemAssignedServiceIdentity from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SystemAssignedServiceIdentity 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 SystemAssignedServiceIdentity. - */ - public static SystemAssignedServiceIdentity fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SystemAssignedServiceIdentity deserializedSystemAssignedServiceIdentity - = new SystemAssignedServiceIdentity(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("type".equals(fieldName)) { - deserializedSystemAssignedServiceIdentity.type - = SystemAssignedServiceIdentityType.fromString(reader.getString()); - } else if ("principalId".equals(fieldName)) { - deserializedSystemAssignedServiceIdentity.principalId = reader.getString(); - } else if ("tenantId".equals(fieldName)) { - deserializedSystemAssignedServiceIdentity.tenantId = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedSystemAssignedServiceIdentity; - }); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SystemAssignedServiceIdentityType.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SystemAssignedServiceIdentityType.java deleted file mode 100644 index 1d08927e99f8..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/java/com/azure/resourcemanager/deviceregistry/models/SystemAssignedServiceIdentityType.java +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.models; - -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * Type of managed service identity (either system assigned, or none). - */ -public final class SystemAssignedServiceIdentityType extends ExpandableStringEnum { - /** - * No managed system identity. - */ - public static final SystemAssignedServiceIdentityType NONE = fromString("None"); - - /** - * System assigned managed system identity. - */ - public static final SystemAssignedServiceIdentityType SYSTEM_ASSIGNED = fromString("SystemAssigned"); - - /** - * Creates a new instance of SystemAssignedServiceIdentityType value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Deprecated - public SystemAssignedServiceIdentityType() { - } - - /** - * Creates or finds a SystemAssignedServiceIdentityType from its string representation. - * - * @param name a name to look for. - * @return the corresponding SystemAssignedServiceIdentityType. - */ - public static SystemAssignedServiceIdentityType fromString(String name) { - return fromString(name, SystemAssignedServiceIdentityType.class); - } - - /** - * Gets known SystemAssignedServiceIdentityType values. - * - * @return known SystemAssignedServiceIdentityType values. - */ - public static Collection values() { - return values(SystemAssignedServiceIdentityType.class); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-deviceregistry/proxy-config.json b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-deviceregistry/proxy-config.json index 3cb6e4ed9293..fa86168e34db 100644 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-deviceregistry/proxy-config.json +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-deviceregistry/proxy-config.json @@ -1 +1 @@ -[["com.azure.resourcemanager.deviceregistry.implementation.AssetEndpointProfilesClientImpl$AssetEndpointProfilesService"],["com.azure.resourcemanager.deviceregistry.implementation.AssetsClientImpl$AssetsService"],["com.azure.resourcemanager.deviceregistry.implementation.BillingContainersClientImpl$BillingContainersService"],["com.azure.resourcemanager.deviceregistry.implementation.DiscoveredAssetEndpointProfilesClientImpl$DiscoveredAssetEndpointProfilesService"],["com.azure.resourcemanager.deviceregistry.implementation.DiscoveredAssetsClientImpl$DiscoveredAssetsService"],["com.azure.resourcemanager.deviceregistry.implementation.OperationStatusClientImpl$OperationStatusService"],["com.azure.resourcemanager.deviceregistry.implementation.OperationsClientImpl$OperationsService"],["com.azure.resourcemanager.deviceregistry.implementation.SchemaRegistriesClientImpl$SchemaRegistriesService"],["com.azure.resourcemanager.deviceregistry.implementation.SchemaVersionsClientImpl$SchemaVersionsService"],["com.azure.resourcemanager.deviceregistry.implementation.SchemasClientImpl$SchemasService"]] \ No newline at end of file +[["com.azure.resourcemanager.deviceregistry.implementation.AssetEndpointProfilesClientImpl$AssetEndpointProfilesService"],["com.azure.resourcemanager.deviceregistry.implementation.AssetsClientImpl$AssetsService"],["com.azure.resourcemanager.deviceregistry.implementation.BillingContainersClientImpl$BillingContainersService"],["com.azure.resourcemanager.deviceregistry.implementation.OperationStatusClientImpl$OperationStatusService"],["com.azure.resourcemanager.deviceregistry.implementation.OperationsClientImpl$OperationsService"]] \ No newline at end of file diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/resources/azure-resourcemanager-deviceregistry.properties b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/resources/azure-resourcemanager-deviceregistry.properties new file mode 100644 index 000000000000..defbd48204e4 --- /dev/null +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/main/resources/azure-resourcemanager-deviceregistry.properties @@ -0,0 +1 @@ +version=${project.version} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetEndpointProfilesCreateOrReplaceSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetEndpointProfilesCreateOrReplaceSamples.java index dc391320bcae..655bb380e04f 100644 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetEndpointProfilesCreateOrReplaceSamples.java +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetEndpointProfilesCreateOrReplaceSamples.java @@ -16,7 +16,7 @@ */ public final class AssetEndpointProfilesCreateOrReplaceSamples { /* - * x-ms-original-file: 2024-09-01-preview/Create_AssetEndpointProfile_With_DiscoveredAepRef.json + * x-ms-original-file: 2024-11-01/Create_AssetEndpointProfile_With_DiscoveredAepRef.json */ /** * Sample code: Create_AssetEndpointProfile_With_DiscoveredAepRef. @@ -42,7 +42,7 @@ public static void createAssetEndpointProfileWithDiscoveredAepRef( } /* - * x-ms-original-file: 2024-09-01-preview/Create_AssetEndpointProfile.json + * x-ms-original-file: 2024-11-01/Create_AssetEndpointProfile.json */ /** * Sample code: Create_AssetEndpointProfile. diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetEndpointProfilesDeleteSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetEndpointProfilesDeleteSamples.java index 39666bcc05e2..bffb0fae3859 100644 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetEndpointProfilesDeleteSamples.java +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetEndpointProfilesDeleteSamples.java @@ -9,7 +9,7 @@ */ public final class AssetEndpointProfilesDeleteSamples { /* - * x-ms-original-file: 2024-09-01-preview/Delete_AssetEndpointProfile.json + * x-ms-original-file: 2024-11-01/Delete_AssetEndpointProfile.json */ /** * Sample code: Delete_AssetEndpointProfile. diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetEndpointProfilesGetByResourceGroupSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetEndpointProfilesGetByResourceGroupSamples.java index b663bea06602..49d159e6002a 100644 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetEndpointProfilesGetByResourceGroupSamples.java +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetEndpointProfilesGetByResourceGroupSamples.java @@ -9,7 +9,7 @@ */ public final class AssetEndpointProfilesGetByResourceGroupSamples { /* - * x-ms-original-file: 2024-09-01-preview/Get_AssetEndpointProfile.json + * x-ms-original-file: 2024-11-01/Get_AssetEndpointProfile.json */ /** * Sample code: Get_AssetEndpointProfile. @@ -23,7 +23,7 @@ public static void getAssetEndpointProfile(com.azure.resourcemanager.deviceregis } /* - * x-ms-original-file: 2024-09-01-preview/Get_AssetEndpointProfile_With_SyncStatus.json + * x-ms-original-file: 2024-11-01/Get_AssetEndpointProfile_With_SyncStatus.json */ /** * Sample code: Get_AssetEndpointProfile_With_SyncStatus. diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetEndpointProfilesListByResourceGroupSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetEndpointProfilesListByResourceGroupSamples.java index e787068197ae..8ad3acd56b14 100644 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetEndpointProfilesListByResourceGroupSamples.java +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetEndpointProfilesListByResourceGroupSamples.java @@ -9,7 +9,7 @@ */ public final class AssetEndpointProfilesListByResourceGroupSamples { /* - * x-ms-original-file: 2024-09-01-preview/List_AssetEndpointProfiles_ResourceGroup.json + * x-ms-original-file: 2024-11-01/List_AssetEndpointProfiles_ResourceGroup.json */ /** * Sample code: List_AssetEndpointProfiles_ResourceGroup. diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetEndpointProfilesListSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetEndpointProfilesListSamples.java index ea0d22e16586..283ab95580c0 100644 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetEndpointProfilesListSamples.java +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetEndpointProfilesListSamples.java @@ -9,7 +9,7 @@ */ public final class AssetEndpointProfilesListSamples { /* - * x-ms-original-file: 2024-09-01-preview/List_AssetEndpointProfiles_Subscription.json + * x-ms-original-file: 2024-11-01/List_AssetEndpointProfiles_Subscription.json */ /** * Sample code: List_AssetEndpointProfiles_Subscription. diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetEndpointProfilesUpdateSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetEndpointProfilesUpdateSamples.java index 0b6c02fe658e..535278cf0c28 100644 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetEndpointProfilesUpdateSamples.java +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetEndpointProfilesUpdateSamples.java @@ -12,7 +12,7 @@ */ public final class AssetEndpointProfilesUpdateSamples { /* - * x-ms-original-file: 2024-09-01-preview/Update_AssetEndpointProfile.json + * x-ms-original-file: 2024-11-01/Update_AssetEndpointProfile.json */ /** * Sample code: Update_AssetEndpointProfile. diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetsCreateOrReplaceSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetsCreateOrReplaceSamples.java index edd3db1aa956..05cd5ada0578 100644 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetsCreateOrReplaceSamples.java +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetsCreateOrReplaceSamples.java @@ -22,7 +22,7 @@ */ public final class AssetsCreateOrReplaceSamples { /* - * x-ms-original-file: 2024-09-01-preview/Create_Asset_With_DiscoveredAssetRef.json + * x-ms-original-file: 2024-11-01/Create_Asset_With_DiscoveredAssetRef.json */ /** * Sample code: Create_Asset_With_DiscoveredAssetRefs. @@ -89,7 +89,7 @@ public final class AssetsCreateOrReplaceSamples { } /* - * x-ms-original-file: 2024-09-01-preview/Create_Asset_Without_ExternalAssetId.json + * x-ms-original-file: 2024-11-01/Create_Asset_Without_ExternalAssetId.json */ /** * Sample code: Create_Asset_Without_ExternalAssetId. @@ -154,7 +154,7 @@ public final class AssetsCreateOrReplaceSamples { } /* - * x-ms-original-file: 2024-09-01-preview/Create_Asset_With_ExternalAssetId.json + * x-ms-original-file: 2024-11-01/Create_Asset_With_ExternalAssetId.json */ /** * Sample code: Create_Asset_With_ExternalAssetId. @@ -220,7 +220,7 @@ public final class AssetsCreateOrReplaceSamples { } /* - * x-ms-original-file: 2024-09-01-preview/Create_Asset_Without_DisplayName.json + * x-ms-original-file: 2024-11-01/Create_Asset_Without_DisplayName.json */ /** * Sample code: Create_Asset_Without_DisplayName. diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetsDeleteSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetsDeleteSamples.java index ab590b114b16..0d9e66e82986 100644 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetsDeleteSamples.java +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetsDeleteSamples.java @@ -9,7 +9,7 @@ */ public final class AssetsDeleteSamples { /* - * x-ms-original-file: 2024-09-01-preview/Delete_Asset.json + * x-ms-original-file: 2024-11-01/Delete_Asset.json */ /** * Sample code: Delete_Asset. diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetsGetByResourceGroupSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetsGetByResourceGroupSamples.java index 6d2718dfa05d..9608db4782f1 100644 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetsGetByResourceGroupSamples.java +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetsGetByResourceGroupSamples.java @@ -9,7 +9,7 @@ */ public final class AssetsGetByResourceGroupSamples { /* - * x-ms-original-file: 2024-09-01-preview/Get_Asset_With_SyncStatus.json + * x-ms-original-file: 2024-11-01/Get_Asset_With_SyncStatus.json */ /** * Sample code: Get_Asset_With_SyncStatus. @@ -22,7 +22,7 @@ public static void getAssetWithSyncStatus(com.azure.resourcemanager.deviceregist } /* - * x-ms-original-file: 2024-09-01-preview/Get_Asset.json + * x-ms-original-file: 2024-11-01/Get_Asset.json */ /** * Sample code: Get_Asset. diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetsListByResourceGroupSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetsListByResourceGroupSamples.java index 7181801b9f46..8eca96bc556e 100644 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetsListByResourceGroupSamples.java +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetsListByResourceGroupSamples.java @@ -9,7 +9,7 @@ */ public final class AssetsListByResourceGroupSamples { /* - * x-ms-original-file: 2024-09-01-preview/List_Assets_ResourceGroup.json + * x-ms-original-file: 2024-11-01/List_Assets_ResourceGroup.json */ /** * Sample code: List_Assets_ResourceGroup. diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetsListSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetsListSamples.java index 053425992e96..7b01c8912711 100644 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetsListSamples.java +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetsListSamples.java @@ -9,7 +9,7 @@ */ public final class AssetsListSamples { /* - * x-ms-original-file: 2024-09-01-preview/List_Assets_Subscription.json + * x-ms-original-file: 2024-11-01/List_Assets_Subscription.json */ /** * Sample code: List_Assets_Subscription. diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetsUpdateSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetsUpdateSamples.java index d9aab729ee3b..1a4422742df4 100644 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetsUpdateSamples.java +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/AssetsUpdateSamples.java @@ -12,7 +12,7 @@ */ public final class AssetsUpdateSamples { /* - * x-ms-original-file: 2024-09-01-preview/Update_Asset.json + * x-ms-original-file: 2024-11-01/Update_Asset.json */ /** * Sample code: Update_Asset. diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/BillingContainersGetSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/BillingContainersGetSamples.java index 59d3ddaea298..3e99b8c30549 100644 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/BillingContainersGetSamples.java +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/BillingContainersGetSamples.java @@ -9,7 +9,7 @@ */ public final class BillingContainersGetSamples { /* - * x-ms-original-file: 2024-09-01-preview/Get_BillingContainer.json + * x-ms-original-file: 2024-11-01/Get_BillingContainer.json */ /** * Sample code: Get_BillingContainer. diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/BillingContainersListSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/BillingContainersListSamples.java index 91c0c29f8ada..c168af42e5e6 100644 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/BillingContainersListSamples.java +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/BillingContainersListSamples.java @@ -9,7 +9,7 @@ */ public final class BillingContainersListSamples { /* - * x-ms-original-file: 2024-09-01-preview/List_BillingContainers_Subscription.json + * x-ms-original-file: 2024-11-01/List_BillingContainers_Subscription.json */ /** * Sample code: List_BillingContainers_Subscription. diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesCreateOrReplaceSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesCreateOrReplaceSamples.java deleted file mode 100644 index 980379745ac5..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesCreateOrReplaceSamples.java +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.resourcemanager.deviceregistry.models.AuthenticationMethod; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetEndpointProfileProperties; -import com.azure.resourcemanager.deviceregistry.models.ExtendedLocation; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -/** - * Samples for DiscoveredAssetEndpointProfiles CreateOrReplace. - */ -public final class DiscoveredAssetEndpointProfilesCreateOrReplaceSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Create_DiscoveredAssetEndpointProfile.json - */ - /** - * Sample code: Create_DiscoveredAssetEndpointProfile. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void - createDiscoveredAssetEndpointProfile(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.discoveredAssetEndpointProfiles() - .define("my-discoveredassetendpointprofile") - .withRegion("West Europe") - .withExistingResourceGroup("myResourceGroup") - .withExtendedLocation(new ExtendedLocation().withType("CustomLocation") - .withName( - "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/myResourceGroup/providers/microsoft.extendedlocation/customlocations/location1")) - .withTags(mapOf("site", "building-1")) - .withProperties(new DiscoveredAssetEndpointProfileProperties() - .withTargetAddress("https://www.example.com/myTargetAddress") - .withAdditionalConfiguration("{\"foo\": \"bar\"}") - .withSupportedAuthenticationMethods(Arrays.asList(AuthenticationMethod.ANONYMOUS, - AuthenticationMethod.CERTIFICATE, AuthenticationMethod.USERNAME_PASSWORD)) - .withEndpointProfileType("myEndpointProfileType") - .withDiscoveryId("11111111-1111-1111-1111-111111111111") - .withVersion(73766L)) - .create(); - } - - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesDeleteSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesDeleteSamples.java deleted file mode 100644 index 66932617ea70..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesDeleteSamples.java +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -/** - * Samples for DiscoveredAssetEndpointProfiles Delete. - */ -public final class DiscoveredAssetEndpointProfilesDeleteSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Delete_DiscoveredAssetEndpointProfile.json - */ - /** - * Sample code: Delete_DiscoveredAssetEndpointProfile. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void - deleteDiscoveredAssetEndpointProfile(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.discoveredAssetEndpointProfiles() - .delete("myResourceGroup", "my-discoveredassetendpointprofile", com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesGetByResourceGroupSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesGetByResourceGroupSamples.java deleted file mode 100644 index 902d00108312..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesGetByResourceGroupSamples.java +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -/** - * Samples for DiscoveredAssetEndpointProfiles GetByResourceGroup. - */ -public final class DiscoveredAssetEndpointProfilesGetByResourceGroupSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Get_DiscoveredAssetEndpointProfile.json - */ - /** - * Sample code: Get_DiscoveredAssetEndpointProfile. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void - getDiscoveredAssetEndpointProfile(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.discoveredAssetEndpointProfiles() - .getByResourceGroupWithResponse("myResourceGroup", "my-discoveredassetendpointprofile", - com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesListByResourceGroupSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesListByResourceGroupSamples.java deleted file mode 100644 index e5ba67836217..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesListByResourceGroupSamples.java +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -/** - * Samples for DiscoveredAssetEndpointProfiles ListByResourceGroup. - */ -public final class DiscoveredAssetEndpointProfilesListByResourceGroupSamples { - /* - * x-ms-original-file: 2024-09-01-preview/List_DiscoveredAssetEndpointProfiles_ResourceGroup.json - */ - /** - * Sample code: List_DiscoveredAssetEndpointProfiles_ResourceGroup. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void listDiscoveredAssetEndpointProfilesResourceGroup( - com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.discoveredAssetEndpointProfiles() - .listByResourceGroup("myResourceGroup", com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesListSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesListSamples.java deleted file mode 100644 index 3e70c95f7add..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesListSamples.java +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -/** - * Samples for DiscoveredAssetEndpointProfiles List. - */ -public final class DiscoveredAssetEndpointProfilesListSamples { - /* - * x-ms-original-file: 2024-09-01-preview/List_DiscoveredAssetEndpointProfiles_Subscription.json - */ - /** - * Sample code: List_DiscoveredAssetEndpointProfiles_Subscription. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void listDiscoveredAssetEndpointProfilesSubscription( - com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.discoveredAssetEndpointProfiles().list(com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesUpdateSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesUpdateSamples.java deleted file mode 100644 index 9f1f74a9c58b..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesUpdateSamples.java +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.resourcemanager.deviceregistry.models.AuthenticationMethod; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetEndpointProfile; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetEndpointProfileUpdateProperties; -import java.util.Arrays; - -/** - * Samples for DiscoveredAssetEndpointProfiles Update. - */ -public final class DiscoveredAssetEndpointProfilesUpdateSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Update_DiscoveredAssetEndpointProfile.json - */ - /** - * Sample code: Update_DiscoveredAssetEndpointProfile. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void - updateDiscoveredAssetEndpointProfile(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - DiscoveredAssetEndpointProfile resource = manager.discoveredAssetEndpointProfiles() - .getByResourceGroupWithResponse("myResourceGroup", "my-discoveredassetendpointprofile", - com.azure.core.util.Context.NONE) - .getValue(); - resource.update() - .withProperties(new DiscoveredAssetEndpointProfileUpdateProperties() - .withTargetAddress("https://www.example.com/myTargetAddress") - .withAdditionalConfiguration("{\"foo\": \"bar\"}") - .withSupportedAuthenticationMethods( - Arrays.asList(AuthenticationMethod.ANONYMOUS, AuthenticationMethod.CERTIFICATE)) - .withEndpointProfileType("myEndpointProfileType") - .withDiscoveryId("11111111-1111-1111-1111-111111111111") - .withVersion(73766L)) - .apply(); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetsCreateOrReplaceSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetsCreateOrReplaceSamples.java deleted file mode 100644 index 7b827e572ffa..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetsCreateOrReplaceSamples.java +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetProperties; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredDataPoint; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredDataset; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredEvent; -import com.azure.resourcemanager.deviceregistry.models.ExtendedLocation; -import com.azure.resourcemanager.deviceregistry.models.Topic; -import com.azure.resourcemanager.deviceregistry.models.TopicRetainType; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -/** - * Samples for DiscoveredAssets CreateOrReplace. - */ -public final class DiscoveredAssetsCreateOrReplaceSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Create_DiscoveredAsset.json - */ - /** - * Sample code: Create_DiscoveredAsset. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void createDiscoveredAsset(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.discoveredAssets() - .define("my-discoveredasset") - .withRegion("West Europe") - .withExistingResourceGroup("myResourceGroup") - .withExtendedLocation(new ExtendedLocation().withType("CustomLocation") - .withName( - "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/myResourceGroup/providers/microsoft.extendedlocation/customlocations/location1")) - .withTags(mapOf("site", "building-1")) - .withProperties(new DiscoveredAssetProperties().withAssetEndpointProfileRef("myAssetEndpointProfile") - .withDiscoveryId("11111111-1111-1111-1111-111111111111") - .withVersion(73766L) - .withManufacturer("Contoso") - .withManufacturerUri("https://www.contoso.com/manufacturerUri") - .withModel("ContosoModel") - .withProductCode("fakeTokenPlaceholder") - .withHardwareRevision("1.0") - .withSoftwareRevision("2.0") - .withDocumentationUri("https://www.example.com/manual") - .withSerialNumber("64-103816-519918-8") - .withDefaultDatasetsConfiguration( - "{\"publishingInterval\":10,\"samplingInterval\":15,\"queueSize\":20}") - .withDefaultEventsConfiguration("{\"publishingInterval\":10,\"samplingInterval\":15,\"queueSize\":20}") - .withDefaultTopic(new Topic().withPath("/path/defaultTopic").withRetain(TopicRetainType.KEEP)) - .withDatasets(Arrays.asList(new DiscoveredDataset().withName("dataset1") - .withDatasetConfiguration("{\"publishingInterval\":10,\"samplingInterval\":15,\"queueSize\":20}") - .withTopic(new Topic().withPath("/path/dataset1").withRetain(TopicRetainType.KEEP)) - .withDataPoints(Arrays.asList( - new DiscoveredDataPoint().withName("dataPoint1") - .withDataSource("nsu=http://microsoft.com/Opc/OpcPlc/;s=FastUInt1") - .withDataPointConfiguration( - "{\"publishingInterval\":8,\"samplingInterval\":8,\"queueSize\":4}"), - new DiscoveredDataPoint().withName("dataPoint2") - .withDataSource("nsu=http://microsoft.com/Opc/OpcPlc/;s=FastUInt2") - .withDataPointConfiguration( - "{\"publishingInterval\":4,\"samplingInterval\":4,\"queueSize\":7}"))))) - .withEvents(Arrays.asList( - new DiscoveredEvent().withName("event1") - .withEventNotifier("nsu=http://microsoft.com/Opc/OpcPlc/;s=FastUInt3") - .withEventConfiguration("{\"publishingInterval\":7,\"samplingInterval\":1,\"queueSize\":8}") - .withTopic(new Topic().withPath("/path/event1").withRetain(TopicRetainType.KEEP)), - new DiscoveredEvent().withName("event2") - .withEventNotifier("nsu=http://microsoft.com/Opc/OpcPlc/;s=FastUInt4") - .withEventConfiguration("{\"publishingInterval\":7,\"samplingInterval\":8,\"queueSize\":4}")))) - .create(); - } - - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetsDeleteSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetsDeleteSamples.java deleted file mode 100644 index 0d59bfe0d1a5..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetsDeleteSamples.java +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -/** - * Samples for DiscoveredAssets Delete. - */ -public final class DiscoveredAssetsDeleteSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Delete_DiscoveredAsset.json - */ - /** - * Sample code: Delete_DiscoveredAsset. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void deleteDiscoveredAsset(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.discoveredAssets().delete("myResourceGroup", "my-discoveredasset", com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetsGetByResourceGroupSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetsGetByResourceGroupSamples.java deleted file mode 100644 index 0023b0ec8197..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetsGetByResourceGroupSamples.java +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -/** - * Samples for DiscoveredAssets GetByResourceGroup. - */ -public final class DiscoveredAssetsGetByResourceGroupSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Get_DiscoveredAsset.json - */ - /** - * Sample code: Get_DiscoveredAsset. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void getDiscoveredAsset(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.discoveredAssets() - .getByResourceGroupWithResponse("myResourceGroup", "my-discoveredasset", com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetsListByResourceGroupSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetsListByResourceGroupSamples.java deleted file mode 100644 index fd6cea3872ad..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetsListByResourceGroupSamples.java +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -/** - * Samples for DiscoveredAssets ListByResourceGroup. - */ -public final class DiscoveredAssetsListByResourceGroupSamples { - /* - * x-ms-original-file: 2024-09-01-preview/List_DiscoveredAssets_ResourceGroup.json - */ - /** - * Sample code: List_DiscoveredAssets_ResourceGroup. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void - listDiscoveredAssetsResourceGroup(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.discoveredAssets().listByResourceGroup("myResourceGroup", com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetsListSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetsListSamples.java deleted file mode 100644 index e8998ccfa8bd..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetsListSamples.java +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -/** - * Samples for DiscoveredAssets List. - */ -public final class DiscoveredAssetsListSamples { - /* - * x-ms-original-file: 2024-09-01-preview/List_DiscoveredAssets_Subscription.json - */ - /** - * Sample code: List_DiscoveredAssets_Subscription. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void - listDiscoveredAssetsSubscription(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.discoveredAssets().list(com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetsUpdateSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetsUpdateSamples.java deleted file mode 100644 index 41de069e6c7e..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetsUpdateSamples.java +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAsset; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetUpdateProperties; -import com.azure.resourcemanager.deviceregistry.models.Topic; -import com.azure.resourcemanager.deviceregistry.models.TopicRetainType; - -/** - * Samples for DiscoveredAssets Update. - */ -public final class DiscoveredAssetsUpdateSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Update_DiscoveredAsset.json - */ - /** - * Sample code: Update_DiscoveredAsset. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void updateDiscoveredAsset(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - DiscoveredAsset resource = manager.discoveredAssets() - .getByResourceGroupWithResponse("myResourceGroup", "my-discoveredasset", com.azure.core.util.Context.NONE) - .getValue(); - resource.update() - .withProperties( - new DiscoveredAssetUpdateProperties().withDocumentationUri("https://www.example.com/manual-2") - .withDefaultTopic(new Topic().withPath("/path/defaultTopic").withRetain(TopicRetainType.NEVER))) - .apply(); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/OperationStatusGetSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/OperationStatusGetSamples.java index 75ca8405dbfe..6d8f739d390e 100644 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/OperationStatusGetSamples.java +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/OperationStatusGetSamples.java @@ -9,7 +9,7 @@ */ public final class OperationStatusGetSamples { /* - * x-ms-original-file: 2024-09-01-preview/Get_OperationStatus.json + * x-ms-original-file: 2024-11-01/Get_OperationStatus.json */ /** * Sample code: Get_OperationStatus. diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/OperationsListSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/OperationsListSamples.java index 675cc123c41f..da4d08aa6b60 100644 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/OperationsListSamples.java +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/OperationsListSamples.java @@ -9,7 +9,7 @@ */ public final class OperationsListSamples { /* - * x-ms-original-file: 2024-09-01-preview/List_Operations.json + * x-ms-original-file: 2024-11-01/List_Operations.json */ /** * Sample code: List_Operations. diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesCreateOrReplaceSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesCreateOrReplaceSamples.java deleted file mode 100644 index aedf0714bcd2..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesCreateOrReplaceSamples.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.resourcemanager.deviceregistry.models.SchemaRegistryProperties; -import com.azure.resourcemanager.deviceregistry.models.SystemAssignedServiceIdentity; -import com.azure.resourcemanager.deviceregistry.models.SystemAssignedServiceIdentityType; -import java.util.HashMap; -import java.util.Map; - -/** - * Samples for SchemaRegistries CreateOrReplace. - */ -public final class SchemaRegistriesCreateOrReplaceSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Create_SchemaRegistry.json - */ - /** - * Sample code: Create_SchemaRegistry. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void createSchemaRegistry(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.schemaRegistries() - .define("my-schema-registry") - .withRegion("West Europe") - .withExistingResourceGroup("myResourceGroup") - .withTags(mapOf()) - .withProperties(new SchemaRegistryProperties().withNamespace("sr-namespace-001") - .withDisplayName("Schema Registry namespace 001") - .withDescription("This is a sample Schema Registry") - .withStorageAccountContainerUrl("my-blob-storage.blob.core.windows.net/my-container")) - .withIdentity(new SystemAssignedServiceIdentity().withType(SystemAssignedServiceIdentityType.NONE)) - .create(); - } - - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesDeleteSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesDeleteSamples.java deleted file mode 100644 index 118576c57f94..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesDeleteSamples.java +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -/** - * Samples for SchemaRegistries Delete. - */ -public final class SchemaRegistriesDeleteSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Delete_SchemaRegistry.json - */ - /** - * Sample code: Delete_SchemaRegistry. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void deleteSchemaRegistry(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.schemaRegistries().delete("myResourceGroup", "my-schema-registry", com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesGetByResourceGroupSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesGetByResourceGroupSamples.java deleted file mode 100644 index 87c8c6c91764..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesGetByResourceGroupSamples.java +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -/** - * Samples for SchemaRegistries GetByResourceGroup. - */ -public final class SchemaRegistriesGetByResourceGroupSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Get_SchemaRegistry.json - */ - /** - * Sample code: Get_SchemaRegistry. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void getSchemaRegistry(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.schemaRegistries() - .getByResourceGroupWithResponse("myResourceGroup", "my-schema-registry", com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesListByResourceGroupSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesListByResourceGroupSamples.java deleted file mode 100644 index 53766e391b4c..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesListByResourceGroupSamples.java +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -/** - * Samples for SchemaRegistries ListByResourceGroup. - */ -public final class SchemaRegistriesListByResourceGroupSamples { - /* - * x-ms-original-file: 2024-09-01-preview/List_SchemaRegistries_ResourceGroup.json - */ - /** - * Sample code: List_SchemaRegistries_ResourceGroup. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void - listSchemaRegistriesResourceGroup(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.schemaRegistries().listByResourceGroup("myResourceGroup", com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesListSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesListSamples.java deleted file mode 100644 index cda2ad2af26c..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesListSamples.java +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -/** - * Samples for SchemaRegistries List. - */ -public final class SchemaRegistriesListSamples { - /* - * x-ms-original-file: 2024-09-01-preview/List_SchemaRegistries_Subscription.json - */ - /** - * Sample code: List_SchemaRegistries_Subscription. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void - listSchemaRegistriesSubscription(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.schemaRegistries().list(com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesUpdateSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesUpdateSamples.java deleted file mode 100644 index 136bb88fa550..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesUpdateSamples.java +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.resourcemanager.deviceregistry.models.SchemaRegistry; -import com.azure.resourcemanager.deviceregistry.models.SchemaRegistryUpdateProperties; -import java.util.HashMap; -import java.util.Map; - -/** - * Samples for SchemaRegistries Update. - */ -public final class SchemaRegistriesUpdateSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Update_SchemaRegistry.json - */ - /** - * Sample code: Update_SchemaRegistry. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void updateSchemaRegistry(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - SchemaRegistry resource = manager.schemaRegistries() - .getByResourceGroupWithResponse("myResourceGroup", "my-schema-registry", com.azure.core.util.Context.NONE) - .getValue(); - resource.update() - .withTags(mapOf()) - .withProperties(new SchemaRegistryUpdateProperties().withDisplayName("Schema Registry namespace 001") - .withDescription("This is a sample Schema Registry")) - .apply(); - } - - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionsCreateOrReplaceSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionsCreateOrReplaceSamples.java deleted file mode 100644 index 6a5824352539..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionsCreateOrReplaceSamples.java +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.resourcemanager.deviceregistry.models.SchemaVersionProperties; - -/** - * Samples for SchemaVersions CreateOrReplace. - */ -public final class SchemaVersionsCreateOrReplaceSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Create_SchemaVersion.json - */ - /** - * Sample code: Create_SchemaVersion. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void createSchemaVersion(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.schemaVersions() - .define("1") - .withExistingSchema("myResourceGroup", "my-schema-registry", "my-schema") - .withProperties(new SchemaVersionProperties().withDescription("Schema version 1") - .withSchemaContent( - "{\"$schema\": \"http://json-schema.org/draft-07/schema#\",\"type\": \"object\",\"properties\": {\"humidity\": {\"type\": \"string\"},\"temperature\": {\"type\":\"number\"}}}")) - .create(); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionsDeleteSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionsDeleteSamples.java deleted file mode 100644 index 6fcc426be6c3..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionsDeleteSamples.java +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -/** - * Samples for SchemaVersions Delete. - */ -public final class SchemaVersionsDeleteSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Delete_SchemaVersion.json - */ - /** - * Sample code: Delete_SchemaVersion. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void deleteSchemaVersion(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.schemaVersions() - .deleteWithResponse("myResourceGroup", "my-schema-registry", "my-schema", "1", - com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionsGetSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionsGetSamples.java deleted file mode 100644 index 138db4a3ba6e..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionsGetSamples.java +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -/** - * Samples for SchemaVersions Get. - */ -public final class SchemaVersionsGetSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Get_SchemaVersion.json - */ - /** - * Sample code: Get_SchemaVersion. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void getSchemaVersion(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.schemaVersions() - .getWithResponse("myResourceGroup", "my-schema-registry", "my-schema", "1", - com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionsListBySchemaSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionsListBySchemaSamples.java deleted file mode 100644 index da174a8b4672..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionsListBySchemaSamples.java +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -/** - * Samples for SchemaVersions ListBySchema. - */ -public final class SchemaVersionsListBySchemaSamples { - /* - * x-ms-original-file: 2024-09-01-preview/List_SchemaVersions_Schema.json - */ - /** - * Sample code: List_SchemaVersions_Schema. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void - listSchemaVersionsSchema(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.schemaVersions() - .listBySchema("myResourceGroup", "my-schema-registry", "my-schema", com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemasCreateOrReplaceSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemasCreateOrReplaceSamples.java deleted file mode 100644 index d063442e01d6..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemasCreateOrReplaceSamples.java +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.resourcemanager.deviceregistry.models.Format; -import com.azure.resourcemanager.deviceregistry.models.SchemaProperties; -import com.azure.resourcemanager.deviceregistry.models.SchemaType; -import java.util.HashMap; -import java.util.Map; - -/** - * Samples for Schemas CreateOrReplace. - */ -public final class SchemasCreateOrReplaceSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Create_Schema.json - */ - /** - * Sample code: Create_Schema. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void createSchema(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.schemas() - .define("my-schema") - .withExistingSchemaRegistry("myResourceGroup", "my-schema-registry") - .withProperties(new SchemaProperties().withDisplayName("My Schema") - .withDescription("This is a sample Schema") - .withFormat(Format.JSON_SCHEMA_DRAFT7) - .withSchemaType(SchemaType.MESSAGE_SCHEMA) - .withTags(mapOf("sampleKey", "fakeTokenPlaceholder"))) - .create(); - } - - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemasDeleteSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemasDeleteSamples.java deleted file mode 100644 index a9a7fb3b83db..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemasDeleteSamples.java +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -/** - * Samples for Schemas Delete. - */ -public final class SchemasDeleteSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Delete_Schema.json - */ - /** - * Sample code: Delete_Schema. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void deleteSchema(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.schemas() - .deleteWithResponse("myResourceGroup", "my-schema-registry", "my-schema", com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemasGetSamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemasGetSamples.java deleted file mode 100644 index 52af6cc3fdc2..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemasGetSamples.java +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -/** - * Samples for Schemas Get. - */ -public final class SchemasGetSamples { - /* - * x-ms-original-file: 2024-09-01-preview/Get_Schema.json - */ - /** - * Sample code: Schemas_Get. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void schemasGet(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.schemas() - .getWithResponse("myResourceGroup", "my-schema-registry", "my-schema", com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemasListBySchemaRegistrySamples.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemasListBySchemaRegistrySamples.java deleted file mode 100644 index 4fd405c92e5b..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/samples/java/com/azure/resourcemanager/deviceregistry/generated/SchemasListBySchemaRegistrySamples.java +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -/** - * Samples for Schemas ListBySchemaRegistry. - */ -public final class SchemasListBySchemaRegistrySamples { - /* - * x-ms-original-file: 2024-09-01-preview/List_Schemas_SchemaRegistry.json - */ - /** - * Sample code: List_Schemas_SchemaRegistry. - * - * @param manager Entry point to DeviceRegistryManager. - */ - public static void - listSchemasSchemaRegistry(com.azure.resourcemanager.deviceregistry.DeviceRegistryManager manager) { - manager.schemas() - .listBySchemaRegistry("myResourceGroup", "my-schema-registry", com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/DeviceRegistryManagerTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/DeviceRegistryManagerTests.java new file mode 100644 index 000000000000..7d558be32c2d --- /dev/null +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/DeviceRegistryManagerTests.java @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.resourcemanager.deviceregistry; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.policy.HttpLogOptions; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.test.TestProxyTestBase; +import com.azure.core.test.annotation.LiveOnly; +import com.azure.identity.AzurePowerShellCredentialBuilder; +import com.azure.resourcemanager.deviceregistry.models.Asset; +import com.azure.resourcemanager.deviceregistry.models.AssetEndpointProfile; +import com.azure.resourcemanager.deviceregistry.models.BillingContainer; +import com.azure.resourcemanager.resources.ResourceManager; +import com.azure.resourcemanager.resources.fluentcore.policy.ProviderRegistrationPolicy; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.stream.Collectors; + +public class DeviceRegistryManagerTests extends TestProxyTestBase { + private DeviceRegistryManager deviceRegistryManager = null; + private ResourceManager resourceManager = null; + + @Override + public void beforeTest() { + final TokenCredential credential = new AzurePowerShellCredentialBuilder().build(); + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + + resourceManager = ResourceManager.configure() + .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) + .authenticate(credential, profile) + .withDefaultSubscription(); + + deviceRegistryManager = DeviceRegistryManager.configure() + .withPolicy(new ProviderRegistrationPolicy(resourceManager)) + .withLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)) + .authenticate(credential, profile); + } + + @Test + @LiveOnly + public void testList() { + // The AssetEndpointProfile and Assets service must be supported by the service Kubernetes cluster with Azure Arc + // and Microsoft.ExtendedLocation, but Kubernetes cluster with Azure Arc can only be created by script. + // so only add List test + List assets = deviceRegistryManager.assets().list().stream().collect(Collectors.toList()); + Assertions.assertTrue(assets.size() >= 0); + + List assetEndpointProfiles + = deviceRegistryManager.assetEndpointProfiles().list().stream().collect(Collectors.toList()); + Assertions.assertTrue(assetEndpointProfiles.size() >= 0); + + // The BillingContainers only supported `get` and `list`. + List billingContainers + = deviceRegistryManager.billingContainers().list().stream().collect(Collectors.toList()); + Assertions.assertTrue(billingContainers.size() >= 0); + } +} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/BillingContainersGetWithResponseMockTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/BillingContainersGetWithResponseMockTests.java index 8901a275a6f6..55f151cc3821 100644 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/BillingContainersGetWithResponseMockTests.java +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/BillingContainersGetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.deviceregistry.DeviceRegistryManager; import com.azure.resourcemanager.deviceregistry.models.BillingContainer; @@ -20,17 +20,17 @@ public final class BillingContainersGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"provisioningState\":\"Deleting\"},\"etag\":\"cogjltdtbn\",\"id\":\"adoocrkvc\",\"name\":\"khnvpam\",\"type\":\"gxqquezik\"}"; + = "{\"properties\":{\"provisioningState\":\"Accepted\"},\"etag\":\"civfsnkymuctq\",\"id\":\"fbebrjcxer\",\"name\":\"uwutttxfvjrbi\",\"type\":\"phxepcyvahf\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); DeviceRegistryManager manager = DeviceRegistryManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); BillingContainer response - = manager.billingContainers().getWithResponse("xdy", com.azure.core.util.Context.NONE).getValue(); + = manager.billingContainers().getWithResponse("biqylihkaet", com.azure.core.util.Context.NONE).getValue(); } } diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/BillingContainersListMockTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/BillingContainersListMockTests.java index d6bfd0372c2c..84350843fee6 100644 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/BillingContainersListMockTests.java +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/BillingContainersListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.deviceregistry.DeviceRegistryManager; import com.azure.resourcemanager.deviceregistry.models.BillingContainer; @@ -21,14 +21,14 @@ public final class BillingContainersListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"provisioningState\":\"Deleting\"},\"etag\":\"kallatmel\",\"id\":\"ipicc\",\"name\":\"zkzivgvvcnay\",\"type\":\"hyrnxxmu\"}]}"; + = "{\"value\":[{\"properties\":{\"provisioningState\":\"Deleting\"},\"etag\":\"qxj\",\"id\":\"ujqgidok\",\"name\":\"jljyoxgv\",\"type\":\"ltbgsncghkj\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); DeviceRegistryManager manager = DeviceRegistryManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.billingContainers().list(com.azure.core.util.Context.NONE); diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfileInnerTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfileInnerTests.java deleted file mode 100644 index 8d5b39b78b32..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfileInnerTests.java +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.deviceregistry.fluent.models.DiscoveredAssetEndpointProfileInner; -import com.azure.resourcemanager.deviceregistry.models.AuthenticationMethod; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetEndpointProfileProperties; -import com.azure.resourcemanager.deviceregistry.models.ExtendedLocation; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import org.junit.jupiter.api.Assertions; - -public final class DiscoveredAssetEndpointProfileInnerTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - DiscoveredAssetEndpointProfileInner model = BinaryData.fromString( - "{\"properties\":{\"targetAddress\":\"xbczwtruwiqz\",\"additionalConfiguration\":\"j\",\"supportedAuthenticationMethods\":[\"Certificate\"],\"endpointProfileType\":\"myokacspkwlh\",\"discoveryId\":\"dobpxjmflbvvn\",\"version\":2925444529354115235,\"provisioningState\":\"Canceled\"},\"extendedLocation\":{\"type\":\"ciwwzjuqkhr\",\"name\":\"ajiwkuo\"},\"location\":\"skghsauuimj\",\"tags\":{\"ugidyjrr\":\"ied\",\"v\":\"byao\",\"onpc\":\"xc\",\"eggzfb\":\"hocohslkev\"},\"id\":\"hfmvfaxkffe\",\"name\":\"ithlvmezyvshxm\",\"type\":\"sbbzo\"}") - .toObject(DiscoveredAssetEndpointProfileInner.class); - Assertions.assertEquals("skghsauuimj", model.location()); - Assertions.assertEquals("ied", model.tags().get("ugidyjrr")); - Assertions.assertEquals("xbczwtruwiqz", model.properties().targetAddress()); - Assertions.assertEquals("j", model.properties().additionalConfiguration()); - Assertions.assertEquals(AuthenticationMethod.CERTIFICATE, - model.properties().supportedAuthenticationMethods().get(0)); - Assertions.assertEquals("myokacspkwlh", model.properties().endpointProfileType()); - Assertions.assertEquals("dobpxjmflbvvn", model.properties().discoveryId()); - Assertions.assertEquals(2925444529354115235L, model.properties().version()); - Assertions.assertEquals("ciwwzjuqkhr", model.extendedLocation().type()); - Assertions.assertEquals("ajiwkuo", model.extendedLocation().name()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - DiscoveredAssetEndpointProfileInner model - = new DiscoveredAssetEndpointProfileInner().withLocation("skghsauuimj") - .withTags(mapOf("ugidyjrr", "ied", "v", "byao", "onpc", "xc", "eggzfb", "hocohslkev")) - .withProperties(new DiscoveredAssetEndpointProfileProperties().withTargetAddress("xbczwtruwiqz") - .withAdditionalConfiguration("j") - .withSupportedAuthenticationMethods(Arrays.asList(AuthenticationMethod.CERTIFICATE)) - .withEndpointProfileType("myokacspkwlh") - .withDiscoveryId("dobpxjmflbvvn") - .withVersion(2925444529354115235L)) - .withExtendedLocation(new ExtendedLocation().withType("ciwwzjuqkhr").withName("ajiwkuo")); - model = BinaryData.fromObject(model).toObject(DiscoveredAssetEndpointProfileInner.class); - Assertions.assertEquals("skghsauuimj", model.location()); - Assertions.assertEquals("ied", model.tags().get("ugidyjrr")); - Assertions.assertEquals("xbczwtruwiqz", model.properties().targetAddress()); - Assertions.assertEquals("j", model.properties().additionalConfiguration()); - Assertions.assertEquals(AuthenticationMethod.CERTIFICATE, - model.properties().supportedAuthenticationMethods().get(0)); - Assertions.assertEquals("myokacspkwlh", model.properties().endpointProfileType()); - Assertions.assertEquals("dobpxjmflbvvn", model.properties().discoveryId()); - Assertions.assertEquals(2925444529354115235L, model.properties().version()); - Assertions.assertEquals("ciwwzjuqkhr", model.extendedLocation().type()); - Assertions.assertEquals("ajiwkuo", model.extendedLocation().name()); - } - - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfileListResultTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfileListResultTests.java deleted file mode 100644 index 2b5be14f640d..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfileListResultTests.java +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.deviceregistry.implementation.models.DiscoveredAssetEndpointProfileListResult; -import com.azure.resourcemanager.deviceregistry.models.AuthenticationMethod; -import org.junit.jupiter.api.Assertions; - -public final class DiscoveredAssetEndpointProfileListResultTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - DiscoveredAssetEndpointProfileListResult model = BinaryData.fromString( - "{\"value\":[{\"properties\":{\"targetAddress\":\"konocu\",\"additionalConfiguration\":\"klyaxuconu\",\"supportedAuthenticationMethods\":[\"Certificate\"],\"endpointProfileType\":\"kbeype\",\"discoveryId\":\"rmjmwvvjektc\",\"version\":9050422304173328061,\"provisioningState\":\"Failed\"},\"extendedLocation\":{\"type\":\"wlrsffrzpwv\",\"name\":\"qdqgbi\"},\"location\":\"lihkaetcktvfc\",\"tags\":{\"jf\":\"snkymuctq\",\"fuwutttxf\":\"ebrjcxe\",\"hfnljkyq\":\"jrbirphxepcyv\"},\"id\":\"j\",\"name\":\"uujqgidokgjljyo\",\"type\":\"gvcl\"}],\"nextLink\":\"gsncghkjeszz\"}") - .toObject(DiscoveredAssetEndpointProfileListResult.class); - Assertions.assertEquals("lihkaetcktvfc", model.value().get(0).location()); - Assertions.assertEquals("snkymuctq", model.value().get(0).tags().get("jf")); - Assertions.assertEquals("konocu", model.value().get(0).properties().targetAddress()); - Assertions.assertEquals("klyaxuconu", model.value().get(0).properties().additionalConfiguration()); - Assertions.assertEquals(AuthenticationMethod.CERTIFICATE, - model.value().get(0).properties().supportedAuthenticationMethods().get(0)); - Assertions.assertEquals("kbeype", model.value().get(0).properties().endpointProfileType()); - Assertions.assertEquals("rmjmwvvjektc", model.value().get(0).properties().discoveryId()); - Assertions.assertEquals(9050422304173328061L, model.value().get(0).properties().version()); - Assertions.assertEquals("wlrsffrzpwv", model.value().get(0).extendedLocation().type()); - Assertions.assertEquals("qdqgbi", model.value().get(0).extendedLocation().name()); - Assertions.assertEquals("gsncghkjeszz", model.nextLink()); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilePropertiesTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilePropertiesTests.java deleted file mode 100644 index 065da1e60d85..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilePropertiesTests.java +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.deviceregistry.models.AuthenticationMethod; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetEndpointProfileProperties; -import java.util.Arrays; -import org.junit.jupiter.api.Assertions; - -public final class DiscoveredAssetEndpointProfilePropertiesTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - DiscoveredAssetEndpointProfileProperties model = BinaryData.fromString( - "{\"targetAddress\":\"gigr\",\"additionalConfiguration\":\"burvjxxjnspy\",\"supportedAuthenticationMethods\":[\"Anonymous\"],\"endpointProfileType\":\"oenkouknvudwti\",\"discoveryId\":\"kbldngkpocipa\",\"version\":2857636660248584289,\"provisioningState\":\"Failed\"}") - .toObject(DiscoveredAssetEndpointProfileProperties.class); - Assertions.assertEquals("gigr", model.targetAddress()); - Assertions.assertEquals("burvjxxjnspy", model.additionalConfiguration()); - Assertions.assertEquals(AuthenticationMethod.ANONYMOUS, model.supportedAuthenticationMethods().get(0)); - Assertions.assertEquals("oenkouknvudwti", model.endpointProfileType()); - Assertions.assertEquals("kbldngkpocipa", model.discoveryId()); - Assertions.assertEquals(2857636660248584289L, model.version()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - DiscoveredAssetEndpointProfileProperties model - = new DiscoveredAssetEndpointProfileProperties().withTargetAddress("gigr") - .withAdditionalConfiguration("burvjxxjnspy") - .withSupportedAuthenticationMethods(Arrays.asList(AuthenticationMethod.ANONYMOUS)) - .withEndpointProfileType("oenkouknvudwti") - .withDiscoveryId("kbldngkpocipa") - .withVersion(2857636660248584289L); - model = BinaryData.fromObject(model).toObject(DiscoveredAssetEndpointProfileProperties.class); - Assertions.assertEquals("gigr", model.targetAddress()); - Assertions.assertEquals("burvjxxjnspy", model.additionalConfiguration()); - Assertions.assertEquals(AuthenticationMethod.ANONYMOUS, model.supportedAuthenticationMethods().get(0)); - Assertions.assertEquals("oenkouknvudwti", model.endpointProfileType()); - Assertions.assertEquals("kbldngkpocipa", model.discoveryId()); - Assertions.assertEquals(2857636660248584289L, model.version()); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfileUpdatePropertiesTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfileUpdatePropertiesTests.java deleted file mode 100644 index ad5806ce2d45..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfileUpdatePropertiesTests.java +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.deviceregistry.models.AuthenticationMethod; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetEndpointProfileUpdateProperties; -import java.util.Arrays; -import org.junit.jupiter.api.Assertions; - -public final class DiscoveredAssetEndpointProfileUpdatePropertiesTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - DiscoveredAssetEndpointProfileUpdateProperties model = BinaryData.fromString( - "{\"targetAddress\":\"nkixzbinj\",\"additionalConfiguration\":\"uttmrywnuzoqft\",\"supportedAuthenticationMethods\":[\"UsernamePassword\",\"Certificate\",\"Certificate\",\"Certificate\"],\"endpointProfileType\":\"qvyxlwhzlsicoho\",\"discoveryId\":\"nwvlryavwhheunmm\",\"version\":5242913098058290048}") - .toObject(DiscoveredAssetEndpointProfileUpdateProperties.class); - Assertions.assertEquals("nkixzbinj", model.targetAddress()); - Assertions.assertEquals("uttmrywnuzoqft", model.additionalConfiguration()); - Assertions.assertEquals(AuthenticationMethod.USERNAME_PASSWORD, model.supportedAuthenticationMethods().get(0)); - Assertions.assertEquals("qvyxlwhzlsicoho", model.endpointProfileType()); - Assertions.assertEquals("nwvlryavwhheunmm", model.discoveryId()); - Assertions.assertEquals(5242913098058290048L, model.version()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - DiscoveredAssetEndpointProfileUpdateProperties model = new DiscoveredAssetEndpointProfileUpdateProperties() - .withTargetAddress("nkixzbinj") - .withAdditionalConfiguration("uttmrywnuzoqft") - .withSupportedAuthenticationMethods(Arrays.asList(AuthenticationMethod.USERNAME_PASSWORD, - AuthenticationMethod.CERTIFICATE, AuthenticationMethod.CERTIFICATE, AuthenticationMethod.CERTIFICATE)) - .withEndpointProfileType("qvyxlwhzlsicoho") - .withDiscoveryId("nwvlryavwhheunmm") - .withVersion(5242913098058290048L); - model = BinaryData.fromObject(model).toObject(DiscoveredAssetEndpointProfileUpdateProperties.class); - Assertions.assertEquals("nkixzbinj", model.targetAddress()); - Assertions.assertEquals("uttmrywnuzoqft", model.additionalConfiguration()); - Assertions.assertEquals(AuthenticationMethod.USERNAME_PASSWORD, model.supportedAuthenticationMethods().get(0)); - Assertions.assertEquals("qvyxlwhzlsicoho", model.endpointProfileType()); - Assertions.assertEquals("nwvlryavwhheunmm", model.discoveryId()); - Assertions.assertEquals(5242913098058290048L, model.version()); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfileUpdateTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfileUpdateTests.java deleted file mode 100644 index 78735aeca2b9..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfileUpdateTests.java +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.deviceregistry.models.AuthenticationMethod; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetEndpointProfileUpdate; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetEndpointProfileUpdateProperties; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import org.junit.jupiter.api.Assertions; - -public final class DiscoveredAssetEndpointProfileUpdateTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - DiscoveredAssetEndpointProfileUpdate model = BinaryData.fromString( - "{\"tags\":{\"iucgygevqzn\":\"kgjn\",\"rbpizc\":\"yp\",\"j\":\"r\",\"yhxdeoejzicwi\":\"dpydn\"},\"properties\":{\"targetAddress\":\"ttgzfbis\",\"additionalConfiguration\":\"bkh\",\"supportedAuthenticationMethods\":[\"UsernamePassword\",\"Certificate\",\"UsernamePassword\",\"Anonymous\"],\"endpointProfileType\":\"dphagalpbuxwgip\",\"discoveryId\":\"onowk\",\"version\":7362184502931754827}}") - .toObject(DiscoveredAssetEndpointProfileUpdate.class); - Assertions.assertEquals("kgjn", model.tags().get("iucgygevqzn")); - Assertions.assertEquals("ttgzfbis", model.properties().targetAddress()); - Assertions.assertEquals("bkh", model.properties().additionalConfiguration()); - Assertions.assertEquals(AuthenticationMethod.USERNAME_PASSWORD, - model.properties().supportedAuthenticationMethods().get(0)); - Assertions.assertEquals("dphagalpbuxwgip", model.properties().endpointProfileType()); - Assertions.assertEquals("onowk", model.properties().discoveryId()); - Assertions.assertEquals(7362184502931754827L, model.properties().version()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - DiscoveredAssetEndpointProfileUpdate model = new DiscoveredAssetEndpointProfileUpdate() - .withTags(mapOf("iucgygevqzn", "kgjn", "rbpizc", "yp", "j", "r", "yhxdeoejzicwi", "dpydn")) - .withProperties(new DiscoveredAssetEndpointProfileUpdateProperties().withTargetAddress("ttgzfbis") - .withAdditionalConfiguration("bkh") - .withSupportedAuthenticationMethods( - Arrays.asList(AuthenticationMethod.USERNAME_PASSWORD, AuthenticationMethod.CERTIFICATE, - AuthenticationMethod.USERNAME_PASSWORD, AuthenticationMethod.ANONYMOUS)) - .withEndpointProfileType("dphagalpbuxwgip") - .withDiscoveryId("onowk") - .withVersion(7362184502931754827L)); - model = BinaryData.fromObject(model).toObject(DiscoveredAssetEndpointProfileUpdate.class); - Assertions.assertEquals("kgjn", model.tags().get("iucgygevqzn")); - Assertions.assertEquals("ttgzfbis", model.properties().targetAddress()); - Assertions.assertEquals("bkh", model.properties().additionalConfiguration()); - Assertions.assertEquals(AuthenticationMethod.USERNAME_PASSWORD, - model.properties().supportedAuthenticationMethods().get(0)); - Assertions.assertEquals("dphagalpbuxwgip", model.properties().endpointProfileType()); - Assertions.assertEquals("onowk", model.properties().discoveryId()); - Assertions.assertEquals(7362184502931754827L, model.properties().version()); - } - - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesCreateOrReplaceMockTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesCreateOrReplaceMockTests.java deleted file mode 100644 index c8cae6f552c2..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesCreateOrReplaceMockTests.java +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.credential.AccessToken; -import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.profile.AzureProfile; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.resourcemanager.deviceregistry.DeviceRegistryManager; -import com.azure.resourcemanager.deviceregistry.models.AuthenticationMethod; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetEndpointProfile; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetEndpointProfileProperties; -import com.azure.resourcemanager.deviceregistry.models.ExtendedLocation; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -public final class DiscoveredAssetEndpointProfilesCreateOrReplaceMockTests { - @Test - public void testCreateOrReplace() throws Exception { - String responseStr - = "{\"properties\":{\"targetAddress\":\"szufoxciqopidoa\",\"additionalConfiguration\":\"iodhkhazxkhnz\",\"supportedAuthenticationMethods\":[\"Anonymous\",\"Certificate\"],\"endpointProfileType\":\"ntoe\",\"discoveryId\":\"okdwb\",\"version\":4169571464200013299,\"provisioningState\":\"Succeeded\"},\"extendedLocation\":{\"type\":\"zcmrvexztvb\",\"name\":\"qgsfraoyzkoow\"},\"location\":\"mnguxawqaldsyu\",\"tags\":{\"kutwpf\":\"merqfobwyznkb\",\"sd\":\"pagmhrskdsnf\",\"wpusdsttwvogv\":\"akgtdlmkkzevdlh\",\"qqmoaku\":\"bejdcn\"},\"id\":\"gm\",\"name\":\"zr\",\"type\":\"rdgrtw\"}"; - - HttpClient httpClient - = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); - DeviceRegistryManager manager = DeviceRegistryManager.configure() - .withHttpClient(httpClient) - .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); - - DiscoveredAssetEndpointProfile response = manager.discoveredAssetEndpointProfiles() - .define("vkg") - .withRegion("ab") - .withExistingResourceGroup("f") - .withExtendedLocation(new ExtendedLocation().withType("ovsm").withName("l")) - .withTags(mapOf("tpuqujmq", "efkifr", "jcntuj", "gkfbtndoaong")) - .withProperties(new DiscoveredAssetEndpointProfileProperties().withTargetAddress("bgdknnqv") - .withAdditionalConfiguration("znqntoru") - .withSupportedAuthenticationMethods(Arrays.asList(AuthenticationMethod.USERNAME_PASSWORD, - AuthenticationMethod.ANONYMOUS, AuthenticationMethod.CERTIFICATE, AuthenticationMethod.ANONYMOUS)) - .withEndpointProfileType("kycgrauwj") - .withDiscoveryId("etaebu") - .withVersion(602178268406598897L)) - .create(); - - Assertions.assertEquals("mnguxawqaldsyu", response.location()); - Assertions.assertEquals("merqfobwyznkb", response.tags().get("kutwpf")); - Assertions.assertEquals("szufoxciqopidoa", response.properties().targetAddress()); - Assertions.assertEquals("iodhkhazxkhnz", response.properties().additionalConfiguration()); - Assertions.assertEquals(AuthenticationMethod.ANONYMOUS, - response.properties().supportedAuthenticationMethods().get(0)); - Assertions.assertEquals("ntoe", response.properties().endpointProfileType()); - Assertions.assertEquals("okdwb", response.properties().discoveryId()); - Assertions.assertEquals(4169571464200013299L, response.properties().version()); - Assertions.assertEquals("zcmrvexztvb", response.extendedLocation().type()); - Assertions.assertEquals("qgsfraoyzkoow", response.extendedLocation().name()); - } - - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesGetByResourceGroupWithResponseMockTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesGetByResourceGroupWithResponseMockTests.java deleted file mode 100644 index dca02d5d02c3..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesGetByResourceGroupWithResponseMockTests.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.credential.AccessToken; -import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.profile.AzureProfile; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.resourcemanager.deviceregistry.DeviceRegistryManager; -import com.azure.resourcemanager.deviceregistry.models.AuthenticationMethod; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetEndpointProfile; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -public final class DiscoveredAssetEndpointProfilesGetByResourceGroupWithResponseMockTests { - @Test - public void testGetByResourceGroupWithResponse() throws Exception { - String responseStr - = "{\"properties\":{\"targetAddress\":\"xkgymareqnajxqu\",\"additionalConfiguration\":\"hky\",\"supportedAuthenticationMethods\":[\"Anonymous\",\"UsernamePassword\",\"Anonymous\"],\"endpointProfileType\":\"gssofwq\",\"discoveryId\":\"zqalkrmnjijpx\",\"version\":6013226485484313004,\"provisioningState\":\"Succeeded\"},\"extendedLocation\":{\"type\":\"dfnbyxbaaabjyv\",\"name\":\"yffimrzrtuzqogs\"},\"location\":\"nevfdnw\",\"tags\":{\"ud\":\"ewzsyyceuzsoib\",\"brqubp\":\"frxtrthzvaytdwk\"},\"id\":\"xhexiilivpdti\",\"name\":\"r\",\"type\":\"tdqoaxoruzfgsq\"}"; - - HttpClient httpClient - = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); - DeviceRegistryManager manager = DeviceRegistryManager.configure() - .withHttpClient(httpClient) - .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); - - DiscoveredAssetEndpointProfile response = manager.discoveredAssetEndpointProfiles() - .getByResourceGroupWithResponse("ywdmjsjqbjh", "yxxrwlycoduh", com.azure.core.util.Context.NONE) - .getValue(); - - Assertions.assertEquals("nevfdnw", response.location()); - Assertions.assertEquals("ewzsyyceuzsoib", response.tags().get("ud")); - Assertions.assertEquals("xkgymareqnajxqu", response.properties().targetAddress()); - Assertions.assertEquals("hky", response.properties().additionalConfiguration()); - Assertions.assertEquals(AuthenticationMethod.ANONYMOUS, - response.properties().supportedAuthenticationMethods().get(0)); - Assertions.assertEquals("gssofwq", response.properties().endpointProfileType()); - Assertions.assertEquals("zqalkrmnjijpx", response.properties().discoveryId()); - Assertions.assertEquals(6013226485484313004L, response.properties().version()); - Assertions.assertEquals("dfnbyxbaaabjyv", response.extendedLocation().type()); - Assertions.assertEquals("yffimrzrtuzqogs", response.extendedLocation().name()); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesListByResourceGroupMockTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesListByResourceGroupMockTests.java deleted file mode 100644 index c3db890c3339..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesListByResourceGroupMockTests.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.credential.AccessToken; -import com.azure.core.http.HttpClient; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.profile.AzureProfile; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.resourcemanager.deviceregistry.DeviceRegistryManager; -import com.azure.resourcemanager.deviceregistry.models.AuthenticationMethod; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetEndpointProfile; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -public final class DiscoveredAssetEndpointProfilesListByResourceGroupMockTests { - @Test - public void testListByResourceGroup() throws Exception { - String responseStr - = "{\"value\":[{\"properties\":{\"targetAddress\":\"eptra\",\"additionalConfiguration\":\"jezwlwnw\",\"supportedAuthenticationMethods\":[\"Certificate\",\"Certificate\"],\"endpointProfileType\":\"vydypatdoo\",\"discoveryId\":\"ojknio\",\"version\":8422661722393224797,\"provisioningState\":\"Accepted\"},\"extendedLocation\":{\"type\":\"bw\",\"name\":\"ujhemmsbvdkcrodt\"},\"location\":\"nfwjlfltkacjvefk\",\"tags\":{\"owpulpq\":\"oakggkfpag\",\"xkqjnsjervt\":\"lyls\"},\"id\":\"agxsdszuemps\",\"name\":\"zkfzbeyv\",\"type\":\"nqicvinvkjjxdxrb\"}]}"; - - HttpClient httpClient - = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); - DeviceRegistryManager manager = DeviceRegistryManager.configure() - .withHttpClient(httpClient) - .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); - - PagedIterable response - = manager.discoveredAssetEndpointProfiles().listByResourceGroup("yfxrx", com.azure.core.util.Context.NONE); - - Assertions.assertEquals("nfwjlfltkacjvefk", response.iterator().next().location()); - Assertions.assertEquals("oakggkfpag", response.iterator().next().tags().get("owpulpq")); - Assertions.assertEquals("eptra", response.iterator().next().properties().targetAddress()); - Assertions.assertEquals("jezwlwnw", response.iterator().next().properties().additionalConfiguration()); - Assertions.assertEquals(AuthenticationMethod.CERTIFICATE, - response.iterator().next().properties().supportedAuthenticationMethods().get(0)); - Assertions.assertEquals("vydypatdoo", response.iterator().next().properties().endpointProfileType()); - Assertions.assertEquals("ojknio", response.iterator().next().properties().discoveryId()); - Assertions.assertEquals(8422661722393224797L, response.iterator().next().properties().version()); - Assertions.assertEquals("bw", response.iterator().next().extendedLocation().type()); - Assertions.assertEquals("ujhemmsbvdkcrodt", response.iterator().next().extendedLocation().name()); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesListMockTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesListMockTests.java deleted file mode 100644 index 165ef44f280a..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredAssetEndpointProfilesListMockTests.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.credential.AccessToken; -import com.azure.core.http.HttpClient; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.profile.AzureProfile; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.resourcemanager.deviceregistry.DeviceRegistryManager; -import com.azure.resourcemanager.deviceregistry.models.AuthenticationMethod; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredAssetEndpointProfile; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -public final class DiscoveredAssetEndpointProfilesListMockTests { - @Test - public void testList() throws Exception { - String responseStr - = "{\"value\":[{\"properties\":{\"targetAddress\":\"kzclewyh\",\"additionalConfiguration\":\"wp\",\"supportedAuthenticationMethods\":[\"Certificate\",\"Anonymous\",\"UsernamePassword\",\"Anonymous\"],\"endpointProfileType\":\"ncckw\",\"discoveryId\":\"fz\",\"version\":1751290787011310749,\"provisioningState\":\"Accepted\"},\"extendedLocation\":{\"type\":\"buy\",\"name\":\"a\"},\"location\":\"feqztppriol\",\"tags\":{\"sobqw\":\"jaltolmnc\",\"vglsbjjca\":\"sdbnwdcfhucqdpf\",\"t\":\"vxb\"},\"id\":\"udutnco\",\"name\":\"mr\",\"type\":\"xqtvcofu\"}]}"; - - HttpClient httpClient - = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); - DeviceRegistryManager manager = DeviceRegistryManager.configure() - .withHttpClient(httpClient) - .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); - - PagedIterable response - = manager.discoveredAssetEndpointProfiles().list(com.azure.core.util.Context.NONE); - - Assertions.assertEquals("feqztppriol", response.iterator().next().location()); - Assertions.assertEquals("jaltolmnc", response.iterator().next().tags().get("sobqw")); - Assertions.assertEquals("kzclewyh", response.iterator().next().properties().targetAddress()); - Assertions.assertEquals("wp", response.iterator().next().properties().additionalConfiguration()); - Assertions.assertEquals(AuthenticationMethod.CERTIFICATE, - response.iterator().next().properties().supportedAuthenticationMethods().get(0)); - Assertions.assertEquals("ncckw", response.iterator().next().properties().endpointProfileType()); - Assertions.assertEquals("fz", response.iterator().next().properties().discoveryId()); - Assertions.assertEquals(1751290787011310749L, response.iterator().next().properties().version()); - Assertions.assertEquals("buy", response.iterator().next().extendedLocation().type()); - Assertions.assertEquals("a", response.iterator().next().extendedLocation().name()); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredDataPointTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredDataPointTests.java deleted file mode 100644 index 25a3aae3a889..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredDataPointTests.java +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredDataPoint; -import java.time.OffsetDateTime; -import org.junit.jupiter.api.Assertions; - -public final class DiscoveredDataPointTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - DiscoveredDataPoint model = BinaryData.fromString( - "{\"name\":\"ggd\",\"dataSource\":\"jixhbk\",\"dataPointConfiguration\":\"fqweykhmene\",\"lastUpdatedOn\":\"2021-09-26T05:32:17Z\"}") - .toObject(DiscoveredDataPoint.class); - Assertions.assertEquals("ggd", model.name()); - Assertions.assertEquals("jixhbk", model.dataSource()); - Assertions.assertEquals("fqweykhmene", model.dataPointConfiguration()); - Assertions.assertEquals(OffsetDateTime.parse("2021-09-26T05:32:17Z"), model.lastUpdatedOn()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - DiscoveredDataPoint model = new DiscoveredDataPoint().withName("ggd") - .withDataSource("jixhbk") - .withDataPointConfiguration("fqweykhmene") - .withLastUpdatedOn(OffsetDateTime.parse("2021-09-26T05:32:17Z")); - model = BinaryData.fromObject(model).toObject(DiscoveredDataPoint.class); - Assertions.assertEquals("ggd", model.name()); - Assertions.assertEquals("jixhbk", model.dataSource()); - Assertions.assertEquals("fqweykhmene", model.dataPointConfiguration()); - Assertions.assertEquals(OffsetDateTime.parse("2021-09-26T05:32:17Z"), model.lastUpdatedOn()); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredDatasetTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredDatasetTests.java deleted file mode 100644 index 6324d0b4341b..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredDatasetTests.java +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredDataPoint; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredDataset; -import com.azure.resourcemanager.deviceregistry.models.Topic; -import com.azure.resourcemanager.deviceregistry.models.TopicRetainType; -import java.time.OffsetDateTime; -import java.util.Arrays; -import org.junit.jupiter.api.Assertions; - -public final class DiscoveredDatasetTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - DiscoveredDataset model = BinaryData.fromString( - "{\"name\":\"bonqvpkvlrxnjeas\",\"datasetConfiguration\":\"pheoflokeyy\",\"topic\":{\"path\":\"nj\",\"retain\":\"Never\"},\"dataPoints\":[{\"name\":\"grhpdjpju\",\"dataSource\":\"asxazjpqyegualhb\",\"dataPointConfiguration\":\"hejjz\",\"lastUpdatedOn\":\"2021-01-27T02:51:11Z\"},{\"name\":\"udgwdslfho\",\"dataSource\":\"wmc\",\"dataPointConfiguration\":\"pwlbjnpg\",\"lastUpdatedOn\":\"2021-06-30T18:10:14Z\"},{\"name\":\"tadehxnltyfsopp\",\"dataSource\":\"suesnzw\",\"dataPointConfiguration\":\"jbavorxzdm\",\"lastUpdatedOn\":\"2021-07-20T12:25:55Z\"},{\"name\":\"tbqvudw\",\"dataSource\":\"dndnvow\",\"dataPointConfiguration\":\"jjugwdkcglhslaz\",\"lastUpdatedOn\":\"2021-04-05T17:23:15Z\"}]}") - .toObject(DiscoveredDataset.class); - Assertions.assertEquals("bonqvpkvlrxnjeas", model.name()); - Assertions.assertEquals("pheoflokeyy", model.datasetConfiguration()); - Assertions.assertEquals("nj", model.topic().path()); - Assertions.assertEquals(TopicRetainType.NEVER, model.topic().retain()); - Assertions.assertEquals("grhpdjpju", model.dataPoints().get(0).name()); - Assertions.assertEquals("asxazjpqyegualhb", model.dataPoints().get(0).dataSource()); - Assertions.assertEquals("hejjz", model.dataPoints().get(0).dataPointConfiguration()); - Assertions.assertEquals(OffsetDateTime.parse("2021-01-27T02:51:11Z"), - model.dataPoints().get(0).lastUpdatedOn()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - DiscoveredDataset model = new DiscoveredDataset().withName("bonqvpkvlrxnjeas") - .withDatasetConfiguration("pheoflokeyy") - .withTopic(new Topic().withPath("nj").withRetain(TopicRetainType.NEVER)) - .withDataPoints(Arrays.asList( - new DiscoveredDataPoint().withName("grhpdjpju") - .withDataSource("asxazjpqyegualhb") - .withDataPointConfiguration("hejjz") - .withLastUpdatedOn(OffsetDateTime.parse("2021-01-27T02:51:11Z")), - new DiscoveredDataPoint().withName("udgwdslfho") - .withDataSource("wmc") - .withDataPointConfiguration("pwlbjnpg") - .withLastUpdatedOn(OffsetDateTime.parse("2021-06-30T18:10:14Z")), - new DiscoveredDataPoint().withName("tadehxnltyfsopp") - .withDataSource("suesnzw") - .withDataPointConfiguration("jbavorxzdm") - .withLastUpdatedOn(OffsetDateTime.parse("2021-07-20T12:25:55Z")), - new DiscoveredDataPoint().withName("tbqvudw") - .withDataSource("dndnvow") - .withDataPointConfiguration("jjugwdkcglhslaz") - .withLastUpdatedOn(OffsetDateTime.parse("2021-04-05T17:23:15Z")))); - model = BinaryData.fromObject(model).toObject(DiscoveredDataset.class); - Assertions.assertEquals("bonqvpkvlrxnjeas", model.name()); - Assertions.assertEquals("pheoflokeyy", model.datasetConfiguration()); - Assertions.assertEquals("nj", model.topic().path()); - Assertions.assertEquals(TopicRetainType.NEVER, model.topic().retain()); - Assertions.assertEquals("grhpdjpju", model.dataPoints().get(0).name()); - Assertions.assertEquals("asxazjpqyegualhb", model.dataPoints().get(0).dataSource()); - Assertions.assertEquals("hejjz", model.dataPoints().get(0).dataPointConfiguration()); - Assertions.assertEquals(OffsetDateTime.parse("2021-01-27T02:51:11Z"), - model.dataPoints().get(0).lastUpdatedOn()); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredEventTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredEventTests.java deleted file mode 100644 index dc19ac3d0a82..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/DiscoveredEventTests.java +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.deviceregistry.models.DiscoveredEvent; -import com.azure.resourcemanager.deviceregistry.models.Topic; -import com.azure.resourcemanager.deviceregistry.models.TopicRetainType; -import java.time.OffsetDateTime; -import org.junit.jupiter.api.Assertions; - -public final class DiscoveredEventTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - DiscoveredEvent model = BinaryData.fromString( - "{\"name\":\"exfwhy\",\"eventNotifier\":\"cibvyvdcsitynn\",\"eventConfiguration\":\"mdectehfiqscjey\",\"topic\":{\"path\":\"hezrkgq\",\"retain\":\"Never\"},\"lastUpdatedOn\":\"2021-06-04T03:18:37Z\"}") - .toObject(DiscoveredEvent.class); - Assertions.assertEquals("exfwhy", model.name()); - Assertions.assertEquals("cibvyvdcsitynn", model.eventNotifier()); - Assertions.assertEquals("mdectehfiqscjey", model.eventConfiguration()); - Assertions.assertEquals("hezrkgq", model.topic().path()); - Assertions.assertEquals(TopicRetainType.NEVER, model.topic().retain()); - Assertions.assertEquals(OffsetDateTime.parse("2021-06-04T03:18:37Z"), model.lastUpdatedOn()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - DiscoveredEvent model = new DiscoveredEvent().withName("exfwhy") - .withEventNotifier("cibvyvdcsitynn") - .withEventConfiguration("mdectehfiqscjey") - .withTopic(new Topic().withPath("hezrkgq").withRetain(TopicRetainType.NEVER)) - .withLastUpdatedOn(OffsetDateTime.parse("2021-06-04T03:18:37Z")); - model = BinaryData.fromObject(model).toObject(DiscoveredEvent.class); - Assertions.assertEquals("exfwhy", model.name()); - Assertions.assertEquals("cibvyvdcsitynn", model.eventNotifier()); - Assertions.assertEquals("mdectehfiqscjey", model.eventConfiguration()); - Assertions.assertEquals("hezrkgq", model.topic().path()); - Assertions.assertEquals(TopicRetainType.NEVER, model.topic().retain()); - Assertions.assertEquals(OffsetDateTime.parse("2021-06-04T03:18:37Z"), model.lastUpdatedOn()); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/OperationsListMockTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/OperationsListMockTests.java index 2ec8855d7289..bd8c570f987c 100644 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/OperationsListMockTests.java +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/OperationsListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.deviceregistry.DeviceRegistryManager; import com.azure.resourcemanager.deviceregistry.models.Operation; @@ -21,14 +21,14 @@ public final class OperationsListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"name\":\"umaq\",\"isDataAction\":true,\"display\":{\"provider\":\"cdui\",\"resource\":\"tgccymvaolpss\",\"operation\":\"lfmmdnbbglzpswi\",\"description\":\"mcwyhzdxssadb\"},\"origin\":\"system\",\"actionType\":\"Internal\"}]}"; + = "{\"value\":[{\"name\":\"gpphrcgyn\",\"isDataAction\":true,\"display\":{\"provider\":\"cfvmmco\",\"resource\":\"sxlzevgbmqj\",\"operation\":\"bcypmi\",\"description\":\"w\"},\"origin\":\"system\",\"actionType\":\"Internal\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); DeviceRegistryManager manager = DeviceRegistryManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.operations().list(com.azure.core.util.Context.NONE); diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaInnerTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaInnerTests.java deleted file mode 100644 index 2c308e7586f9..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaInnerTests.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.deviceregistry.fluent.models.SchemaInner; -import com.azure.resourcemanager.deviceregistry.models.Format; -import com.azure.resourcemanager.deviceregistry.models.SchemaProperties; -import com.azure.resourcemanager.deviceregistry.models.SchemaType; -import java.util.HashMap; -import java.util.Map; -import org.junit.jupiter.api.Assertions; - -public final class SchemaInnerTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - SchemaInner model = BinaryData.fromString( - "{\"properties\":{\"uuid\":\"ngmtsavjcb\",\"displayName\":\"xqpsrknftguv\",\"description\":\"uhprwmdyvxqt\",\"format\":\"Delta/1.0\",\"schemaType\":\"MessageSchema\",\"provisioningState\":\"Failed\",\"tags\":{\"exrmcqibycnojvk\":\"oyq\"}},\"id\":\"e\",\"name\":\"qsgzvahapj\",\"type\":\"zhpvgqzcjrvxd\"}") - .toObject(SchemaInner.class); - Assertions.assertEquals("xqpsrknftguv", model.properties().displayName()); - Assertions.assertEquals("uhprwmdyvxqt", model.properties().description()); - Assertions.assertEquals(Format.DELTA_1_0, model.properties().format()); - Assertions.assertEquals(SchemaType.MESSAGE_SCHEMA, model.properties().schemaType()); - Assertions.assertEquals("oyq", model.properties().tags().get("exrmcqibycnojvk")); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - SchemaInner model = new SchemaInner().withProperties(new SchemaProperties().withDisplayName("xqpsrknftguv") - .withDescription("uhprwmdyvxqt") - .withFormat(Format.DELTA_1_0) - .withSchemaType(SchemaType.MESSAGE_SCHEMA) - .withTags(mapOf("exrmcqibycnojvk", "oyq"))); - model = BinaryData.fromObject(model).toObject(SchemaInner.class); - Assertions.assertEquals("xqpsrknftguv", model.properties().displayName()); - Assertions.assertEquals("uhprwmdyvxqt", model.properties().description()); - Assertions.assertEquals(Format.DELTA_1_0, model.properties().format()); - Assertions.assertEquals(SchemaType.MESSAGE_SCHEMA, model.properties().schemaType()); - Assertions.assertEquals("oyq", model.properties().tags().get("exrmcqibycnojvk")); - } - - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaListResultTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaListResultTests.java deleted file mode 100644 index 8e08baab5861..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaListResultTests.java +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.deviceregistry.implementation.models.SchemaListResult; -import com.azure.resourcemanager.deviceregistry.models.Format; -import com.azure.resourcemanager.deviceregistry.models.SchemaType; -import org.junit.jupiter.api.Assertions; - -public final class SchemaListResultTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - SchemaListResult model = BinaryData.fromString( - "{\"value\":[{\"properties\":{\"uuid\":\"n\",\"displayName\":\"xisxyawjoyaqcsl\",\"description\":\"pkii\",\"format\":\"JsonSchema/draft-07\",\"schemaType\":\"MessageSchema\",\"provisioningState\":\"Accepted\",\"tags\":{\"hnrztfol\":\"eli\",\"dtpnapnyiropuhp\":\"bnxknalaulppg\",\"gqgitxmedjvcsl\":\"gvpgy\"}},\"id\":\"qwwncw\",\"name\":\"zhxgktrmgucn\",\"type\":\"pkteo\"},{\"properties\":{\"uuid\":\"wptfdy\",\"displayName\":\"fqbuaceopzf\",\"description\":\"hhuao\",\"format\":\"Delta/1.0\",\"schemaType\":\"MessageSchema\",\"provisioningState\":\"Canceled\",\"tags\":{\"t\":\"xolzdahzx\",\"grcfb\":\"bgbkdmoizpost\",\"bpvjymjhx\":\"nrmfqjhhk\"}},\"id\":\"yngudivk\",\"name\":\"tswb\",\"type\":\"qzvszjf\"}],\"nextLink\":\"vjfdx\"}") - .toObject(SchemaListResult.class); - Assertions.assertEquals("xisxyawjoyaqcsl", model.value().get(0).properties().displayName()); - Assertions.assertEquals("pkii", model.value().get(0).properties().description()); - Assertions.assertEquals(Format.JSON_SCHEMA_DRAFT7, model.value().get(0).properties().format()); - Assertions.assertEquals(SchemaType.MESSAGE_SCHEMA, model.value().get(0).properties().schemaType()); - Assertions.assertEquals("eli", model.value().get(0).properties().tags().get("hnrztfol")); - Assertions.assertEquals("vjfdx", model.nextLink()); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaPropertiesTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaPropertiesTests.java deleted file mode 100644 index 7f948e306a47..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaPropertiesTests.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.deviceregistry.models.Format; -import com.azure.resourcemanager.deviceregistry.models.SchemaProperties; -import com.azure.resourcemanager.deviceregistry.models.SchemaType; -import java.util.HashMap; -import java.util.Map; -import org.junit.jupiter.api.Assertions; - -public final class SchemaPropertiesTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - SchemaProperties model = BinaryData.fromString( - "{\"uuid\":\"lmwlxkvugfhzo\",\"displayName\":\"wjvzunluthnn\",\"description\":\"nxipeil\",\"format\":\"Delta/1.0\",\"schemaType\":\"MessageSchema\",\"provisioningState\":\"Failed\",\"tags\":{\"kzbbtd\":\"xdult\",\"bsjyofdx\":\"umveekgpwozuhkf\",\"oekqvk\":\"uusdttouwa\",\"vbxwyjsflhh\":\"lns\"}}") - .toObject(SchemaProperties.class); - Assertions.assertEquals("wjvzunluthnn", model.displayName()); - Assertions.assertEquals("nxipeil", model.description()); - Assertions.assertEquals(Format.DELTA_1_0, model.format()); - Assertions.assertEquals(SchemaType.MESSAGE_SCHEMA, model.schemaType()); - Assertions.assertEquals("xdult", model.tags().get("kzbbtd")); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - SchemaProperties model = new SchemaProperties().withDisplayName("wjvzunluthnn") - .withDescription("nxipeil") - .withFormat(Format.DELTA_1_0) - .withSchemaType(SchemaType.MESSAGE_SCHEMA) - .withTags( - mapOf("kzbbtd", "xdult", "bsjyofdx", "umveekgpwozuhkf", "oekqvk", "uusdttouwa", "vbxwyjsflhh", "lns")); - model = BinaryData.fromObject(model).toObject(SchemaProperties.class); - Assertions.assertEquals("wjvzunluthnn", model.displayName()); - Assertions.assertEquals("nxipeil", model.description()); - Assertions.assertEquals(Format.DELTA_1_0, model.format()); - Assertions.assertEquals(SchemaType.MESSAGE_SCHEMA, model.schemaType()); - Assertions.assertEquals("xdult", model.tags().get("kzbbtd")); - } - - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesCreateOrReplaceMockTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesCreateOrReplaceMockTests.java deleted file mode 100644 index 02b457021dc6..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesCreateOrReplaceMockTests.java +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.credential.AccessToken; -import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.profile.AzureProfile; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.resourcemanager.deviceregistry.DeviceRegistryManager; -import com.azure.resourcemanager.deviceregistry.models.SchemaRegistry; -import com.azure.resourcemanager.deviceregistry.models.SchemaRegistryProperties; -import com.azure.resourcemanager.deviceregistry.models.SystemAssignedServiceIdentity; -import com.azure.resourcemanager.deviceregistry.models.SystemAssignedServiceIdentityType; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import java.util.HashMap; -import java.util.Map; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -public final class SchemaRegistriesCreateOrReplaceMockTests { - @Test - public void testCreateOrReplace() throws Exception { - String responseStr - = "{\"properties\":{\"uuid\":\"qhl\",\"namespace\":\"vriiio\",\"displayName\":\"al\",\"description\":\"fk\",\"storageAccountContainerUrl\":\"tvsexsowuel\",\"provisioningState\":\"Succeeded\"},\"identity\":{\"principalId\":\"hhxvrhmzkwpj\",\"tenantId\":\"wspughftqsxhqx\",\"type\":\"None\"},\"location\":\"ukndxdigrjgu\",\"tags\":{\"z\":\"dmsyqtfihwhbo\",\"zudphqamvdkfw\":\"ngamvpphosz\",\"qiatkzwpcnp\":\"nwcvtbvkayhmtnv\"},\"id\":\"zcjaesgvvsccy\",\"name\":\"jguq\",\"type\":\"hwyg\"}"; - - HttpClient httpClient - = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); - DeviceRegistryManager manager = DeviceRegistryManager.configure() - .withHttpClient(httpClient) - .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); - - SchemaRegistry response = manager.schemaRegistries() - .define("x") - .withRegion("frl") - .withExistingResourceGroup("slthaq") - .withTags(mapOf("iin", "zrnw", "h", "fpwpjylwbt")) - .withProperties(new SchemaRegistryProperties().withNamespace("pdrhne") - .withDisplayName("owqkdwytisi") - .withDescription("rcgp") - .withStorageAccountContainerUrl("kpzi")) - .withIdentity(new SystemAssignedServiceIdentity().withType(SystemAssignedServiceIdentityType.NONE)) - .create(); - - Assertions.assertEquals("ukndxdigrjgu", response.location()); - Assertions.assertEquals("dmsyqtfihwhbo", response.tags().get("z")); - Assertions.assertEquals("vriiio", response.properties().namespace()); - Assertions.assertEquals("al", response.properties().displayName()); - Assertions.assertEquals("fk", response.properties().description()); - Assertions.assertEquals("tvsexsowuel", response.properties().storageAccountContainerUrl()); - Assertions.assertEquals(SystemAssignedServiceIdentityType.NONE, response.identity().type()); - } - - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesGetByResourceGroupWithResponseMockTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesGetByResourceGroupWithResponseMockTests.java deleted file mode 100644 index fed1b9d56e0f..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesGetByResourceGroupWithResponseMockTests.java +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.credential.AccessToken; -import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.profile.AzureProfile; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.resourcemanager.deviceregistry.DeviceRegistryManager; -import com.azure.resourcemanager.deviceregistry.models.SchemaRegistry; -import com.azure.resourcemanager.deviceregistry.models.SystemAssignedServiceIdentityType; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -public final class SchemaRegistriesGetByResourceGroupWithResponseMockTests { - @Test - public void testGetByResourceGroupWithResponse() throws Exception { - String responseStr - = "{\"properties\":{\"uuid\":\"hhziuief\",\"namespace\":\"zbhd\",\"displayName\":\"mlmz\",\"description\":\"oftrmaequia\",\"storageAccountContainerUrl\":\"xicslfao\",\"provisioningState\":\"Deleting\"},\"identity\":{\"principalId\":\"ylhalnswhcc\",\"tenantId\":\"hka\",\"type\":\"SystemAssigned\"},\"location\":\"itqscywuggwoluhc\",\"tags\":{\"i\":\"emh\"},\"id\":\"sbrgz\",\"name\":\"wmsweypqwd\",\"type\":\"ggicccnxqhue\"}"; - - HttpClient httpClient - = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); - DeviceRegistryManager manager = DeviceRegistryManager.configure() - .withHttpClient(httpClient) - .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); - - SchemaRegistry response = manager.schemaRegistries() - .getByResourceGroupWithResponse("enuuzkopbm", "nrfdw", com.azure.core.util.Context.NONE) - .getValue(); - - Assertions.assertEquals("itqscywuggwoluhc", response.location()); - Assertions.assertEquals("emh", response.tags().get("i")); - Assertions.assertEquals("zbhd", response.properties().namespace()); - Assertions.assertEquals("mlmz", response.properties().displayName()); - Assertions.assertEquals("oftrmaequia", response.properties().description()); - Assertions.assertEquals("xicslfao", response.properties().storageAccountContainerUrl()); - Assertions.assertEquals(SystemAssignedServiceIdentityType.SYSTEM_ASSIGNED, response.identity().type()); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesListByResourceGroupMockTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesListByResourceGroupMockTests.java deleted file mode 100644 index 0883b28b3ca4..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesListByResourceGroupMockTests.java +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.credential.AccessToken; -import com.azure.core.http.HttpClient; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.profile.AzureProfile; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.resourcemanager.deviceregistry.DeviceRegistryManager; -import com.azure.resourcemanager.deviceregistry.models.SchemaRegistry; -import com.azure.resourcemanager.deviceregistry.models.SystemAssignedServiceIdentityType; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -public final class SchemaRegistriesListByResourceGroupMockTests { - @Test - public void testListByResourceGroup() throws Exception { - String responseStr - = "{\"value\":[{\"properties\":{\"uuid\":\"ncsdtclusiyp\",\"namespace\":\"sfgytguslfead\",\"displayName\":\"gq\",\"description\":\"yhejhzisxgfp\",\"storageAccountContainerUrl\":\"lolp\",\"provisioningState\":\"Canceled\"},\"identity\":{\"principalId\":\"pqvujzraehtwdwrf\",\"tenantId\":\"wib\",\"type\":\"SystemAssigned\"},\"location\":\"dl\",\"tags\":{\"khevxccedc\":\"hfwpracstwit\",\"jc\":\"nmdyodnwzxl\",\"vvwxqi\":\"nhltiugcxn\",\"unyowxwl\":\"y\"},\"id\":\"djrkvfgbvfvpd\",\"name\":\"odacizs\",\"type\":\"q\"}]}"; - - HttpClient httpClient - = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); - DeviceRegistryManager manager = DeviceRegistryManager.configure() - .withHttpClient(httpClient) - .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); - - PagedIterable response - = manager.schemaRegistries().listByResourceGroup("mkttlstvlzywem", com.azure.core.util.Context.NONE); - - Assertions.assertEquals("dl", response.iterator().next().location()); - Assertions.assertEquals("hfwpracstwit", response.iterator().next().tags().get("khevxccedc")); - Assertions.assertEquals("sfgytguslfead", response.iterator().next().properties().namespace()); - Assertions.assertEquals("gq", response.iterator().next().properties().displayName()); - Assertions.assertEquals("yhejhzisxgfp", response.iterator().next().properties().description()); - Assertions.assertEquals("lolp", response.iterator().next().properties().storageAccountContainerUrl()); - Assertions.assertEquals(SystemAssignedServiceIdentityType.SYSTEM_ASSIGNED, - response.iterator().next().identity().type()); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesListMockTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesListMockTests.java deleted file mode 100644 index ce224492e587..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistriesListMockTests.java +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.credential.AccessToken; -import com.azure.core.http.HttpClient; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.profile.AzureProfile; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.resourcemanager.deviceregistry.DeviceRegistryManager; -import com.azure.resourcemanager.deviceregistry.models.SchemaRegistry; -import com.azure.resourcemanager.deviceregistry.models.SystemAssignedServiceIdentityType; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -public final class SchemaRegistriesListMockTests { - @Test - public void testList() throws Exception { - String responseStr - = "{\"value\":[{\"properties\":{\"uuid\":\"rribd\",\"namespace\":\"ibqipqkg\",\"displayName\":\"xndzwm\",\"description\":\"efajpj\",\"storageAccountContainerUrl\":\"rwkq\",\"provisioningState\":\"Failed\"},\"identity\":{\"principalId\":\"ij\",\"tenantId\":\"ivfxzsjabibsyst\",\"type\":\"SystemAssigned\"},\"location\":\"sdjpvkvp\",\"tags\":{\"ncj\":\"bkzbzkd\",\"zhjjklffhmouwq\":\"budurgkakmo\",\"eeyebi\":\"gzrf\"},\"id\":\"ikayuhqlbjbsybb\",\"name\":\"wrv\",\"type\":\"ldgmfpgvmpip\"}]}"; - - HttpClient httpClient - = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); - DeviceRegistryManager manager = DeviceRegistryManager.configure() - .withHttpClient(httpClient) - .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); - - PagedIterable response = manager.schemaRegistries().list(com.azure.core.util.Context.NONE); - - Assertions.assertEquals("sdjpvkvp", response.iterator().next().location()); - Assertions.assertEquals("bkzbzkd", response.iterator().next().tags().get("ncj")); - Assertions.assertEquals("ibqipqkg", response.iterator().next().properties().namespace()); - Assertions.assertEquals("xndzwm", response.iterator().next().properties().displayName()); - Assertions.assertEquals("efajpj", response.iterator().next().properties().description()); - Assertions.assertEquals("rwkq", response.iterator().next().properties().storageAccountContainerUrl()); - Assertions.assertEquals(SystemAssignedServiceIdentityType.SYSTEM_ASSIGNED, - response.iterator().next().identity().type()); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistryInnerTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistryInnerTests.java deleted file mode 100644 index 1a737e1e9dd5..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistryInnerTests.java +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.deviceregistry.fluent.models.SchemaRegistryInner; -import com.azure.resourcemanager.deviceregistry.models.SchemaRegistryProperties; -import com.azure.resourcemanager.deviceregistry.models.SystemAssignedServiceIdentity; -import com.azure.resourcemanager.deviceregistry.models.SystemAssignedServiceIdentityType; -import java.util.HashMap; -import java.util.Map; -import org.junit.jupiter.api.Assertions; - -public final class SchemaRegistryInnerTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - SchemaRegistryInner model = BinaryData.fromString( - "{\"properties\":{\"uuid\":\"jhtxfvgxbfsmxne\",\"namespace\":\"mpvecxgodebfqk\",\"displayName\":\"bmpukgriwflz\",\"description\":\"bxzpuzycisp\",\"storageAccountContainerUrl\":\"qzahmgkbrp\",\"provisioningState\":\"Canceled\"},\"identity\":{\"principalId\":\"bnuqqkpik\",\"tenantId\":\"rgvtqag\",\"type\":\"SystemAssigned\"},\"location\":\"ynhijggme\",\"tags\":{\"zmhjrunmp\":\"iarbutrcvpna\",\"nkxmyskpbhenbtk\":\"ttdbhrbnl\",\"yxczfclh\":\"xywnytnrsynlqidy\"},\"id\":\"axdbabph\",\"name\":\"wrqlfktsthsuco\",\"type\":\"mnyyazt\"}") - .toObject(SchemaRegistryInner.class); - Assertions.assertEquals("ynhijggme", model.location()); - Assertions.assertEquals("iarbutrcvpna", model.tags().get("zmhjrunmp")); - Assertions.assertEquals("mpvecxgodebfqk", model.properties().namespace()); - Assertions.assertEquals("bmpukgriwflz", model.properties().displayName()); - Assertions.assertEquals("bxzpuzycisp", model.properties().description()); - Assertions.assertEquals("qzahmgkbrp", model.properties().storageAccountContainerUrl()); - Assertions.assertEquals(SystemAssignedServiceIdentityType.SYSTEM_ASSIGNED, model.identity().type()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - SchemaRegistryInner model = new SchemaRegistryInner().withLocation("ynhijggme") - .withTags( - mapOf("zmhjrunmp", "iarbutrcvpna", "nkxmyskpbhenbtk", "ttdbhrbnl", "yxczfclh", "xywnytnrsynlqidy")) - .withProperties(new SchemaRegistryProperties().withNamespace("mpvecxgodebfqk") - .withDisplayName("bmpukgriwflz") - .withDescription("bxzpuzycisp") - .withStorageAccountContainerUrl("qzahmgkbrp")) - .withIdentity( - new SystemAssignedServiceIdentity().withType(SystemAssignedServiceIdentityType.SYSTEM_ASSIGNED)); - model = BinaryData.fromObject(model).toObject(SchemaRegistryInner.class); - Assertions.assertEquals("ynhijggme", model.location()); - Assertions.assertEquals("iarbutrcvpna", model.tags().get("zmhjrunmp")); - Assertions.assertEquals("mpvecxgodebfqk", model.properties().namespace()); - Assertions.assertEquals("bmpukgriwflz", model.properties().displayName()); - Assertions.assertEquals("bxzpuzycisp", model.properties().description()); - Assertions.assertEquals("qzahmgkbrp", model.properties().storageAccountContainerUrl()); - Assertions.assertEquals(SystemAssignedServiceIdentityType.SYSTEM_ASSIGNED, model.identity().type()); - } - - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistryListResultTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistryListResultTests.java deleted file mode 100644 index 3b5048ec4d28..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistryListResultTests.java +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.deviceregistry.implementation.models.SchemaRegistryListResult; -import com.azure.resourcemanager.deviceregistry.models.SystemAssignedServiceIdentityType; -import org.junit.jupiter.api.Assertions; - -public final class SchemaRegistryListResultTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - SchemaRegistryListResult model = BinaryData.fromString( - "{\"value\":[{\"properties\":{\"uuid\":\"lxotogtwrupq\",\"namespace\":\"xvnmicykvceov\",\"displayName\":\"lo\",\"description\":\"oty\",\"storageAccountContainerUrl\":\"jfcn\",\"provisioningState\":\"Accepted\"},\"identity\":{\"principalId\":\"x\",\"tenantId\":\"bttk\",\"type\":\"None\"},\"location\":\"wpn\",\"tags\":{\"hoxus\":\"oqnermclfpl\"},\"id\":\"rpabg\",\"name\":\"epsbjtazqu\",\"type\":\"xywpmueefjzwfqkq\"},{\"properties\":{\"uuid\":\"dsuyonobgla\",\"namespace\":\"cq\",\"displayName\":\"ccm\",\"description\":\"udxytlmoyrx\",\"storageAccountContainerUrl\":\"wfudwpzntxhdzhl\",\"provisioningState\":\"Deleting\"},\"identity\":{\"principalId\":\"ck\",\"tenantId\":\"lhrxsbkyvpyc\",\"type\":\"None\"},\"location\":\"z\",\"tags\":{\"hhseyv\":\"kafkuwbcrnwbm\"},\"id\":\"us\",\"name\":\"tslhspkdeem\",\"type\":\"ofmxagkvtmelmqkr\"},{\"properties\":{\"uuid\":\"vljua\",\"namespace\":\"aquhcdhm\",\"displayName\":\"alaexqpvfadmwsrc\",\"description\":\"vxpvgomz\",\"storageAccountContainerUrl\":\"fmisg\",\"provisioningState\":\"Deleting\"},\"identity\":{\"principalId\":\"e\",\"tenantId\":\"awkz\",\"type\":\"None\"},\"location\":\"io\",\"tags\":{\"xosow\":\"hakauhashsf\",\"cjooxdjebwpucwwf\":\"xcug\",\"hzceuojgjrwjue\":\"ovbvmeueciv\"},\"id\":\"otwmcdyt\",\"name\":\"x\",\"type\":\"it\"},{\"properties\":{\"uuid\":\"jawgqwg\",\"namespace\":\"hniskxfbkpyc\",\"displayName\":\"lwn\",\"description\":\"hjdauwhvylwz\",\"storageAccountContainerUrl\":\"tdhxujznbmpowuwp\",\"provisioningState\":\"Accepted\"},\"identity\":{\"principalId\":\"eualupjmkhf\",\"tenantId\":\"bbcswsrtjri\",\"type\":\"SystemAssigned\"},\"location\":\"bpbewtghfgb\",\"tags\":{\"gibtnm\":\"wxzvlvqhjkb\"},\"id\":\"iebwwaloayqcgwrt\",\"name\":\"j\",\"type\":\"zg\"}],\"nextLink\":\"zmh\"}") - .toObject(SchemaRegistryListResult.class); - Assertions.assertEquals("wpn", model.value().get(0).location()); - Assertions.assertEquals("oqnermclfpl", model.value().get(0).tags().get("hoxus")); - Assertions.assertEquals("xvnmicykvceov", model.value().get(0).properties().namespace()); - Assertions.assertEquals("lo", model.value().get(0).properties().displayName()); - Assertions.assertEquals("oty", model.value().get(0).properties().description()); - Assertions.assertEquals("jfcn", model.value().get(0).properties().storageAccountContainerUrl()); - Assertions.assertEquals(SystemAssignedServiceIdentityType.NONE, model.value().get(0).identity().type()); - Assertions.assertEquals("zmh", model.nextLink()); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistryPropertiesTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistryPropertiesTests.java deleted file mode 100644 index 735b2f64b29c..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistryPropertiesTests.java +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.deviceregistry.models.SchemaRegistryProperties; -import org.junit.jupiter.api.Assertions; - -public final class SchemaRegistryPropertiesTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - SchemaRegistryProperties model = BinaryData.fromString( - "{\"uuid\":\"twwrqp\",\"namespace\":\"edckzywbiexzfey\",\"displayName\":\"axibxujw\",\"description\":\"qwalmuzyoxaepd\",\"storageAccountContainerUrl\":\"zjancuxr\",\"provisioningState\":\"Canceled\"}") - .toObject(SchemaRegistryProperties.class); - Assertions.assertEquals("edckzywbiexzfey", model.namespace()); - Assertions.assertEquals("axibxujw", model.displayName()); - Assertions.assertEquals("qwalmuzyoxaepd", model.description()); - Assertions.assertEquals("zjancuxr", model.storageAccountContainerUrl()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - SchemaRegistryProperties model = new SchemaRegistryProperties().withNamespace("edckzywbiexzfey") - .withDisplayName("axibxujw") - .withDescription("qwalmuzyoxaepd") - .withStorageAccountContainerUrl("zjancuxr"); - model = BinaryData.fromObject(model).toObject(SchemaRegistryProperties.class); - Assertions.assertEquals("edckzywbiexzfey", model.namespace()); - Assertions.assertEquals("axibxujw", model.displayName()); - Assertions.assertEquals("qwalmuzyoxaepd", model.description()); - Assertions.assertEquals("zjancuxr", model.storageAccountContainerUrl()); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistryUpdatePropertiesTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistryUpdatePropertiesTests.java deleted file mode 100644 index a15054ded060..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistryUpdatePropertiesTests.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.deviceregistry.models.SchemaRegistryUpdateProperties; -import org.junit.jupiter.api.Assertions; - -public final class SchemaRegistryUpdatePropertiesTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - SchemaRegistryUpdateProperties model - = BinaryData.fromString("{\"displayName\":\"tldwkyzxuutk\",\"description\":\"ws\"}") - .toObject(SchemaRegistryUpdateProperties.class); - Assertions.assertEquals("tldwkyzxuutk", model.displayName()); - Assertions.assertEquals("ws", model.description()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - SchemaRegistryUpdateProperties model - = new SchemaRegistryUpdateProperties().withDisplayName("tldwkyzxuutk").withDescription("ws"); - model = BinaryData.fromObject(model).toObject(SchemaRegistryUpdateProperties.class); - Assertions.assertEquals("tldwkyzxuutk", model.displayName()); - Assertions.assertEquals("ws", model.description()); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistryUpdateTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistryUpdateTests.java deleted file mode 100644 index 958d084383da..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaRegistryUpdateTests.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.deviceregistry.models.SchemaRegistryUpdate; -import com.azure.resourcemanager.deviceregistry.models.SchemaRegistryUpdateProperties; -import com.azure.resourcemanager.deviceregistry.models.SystemAssignedServiceIdentity; -import com.azure.resourcemanager.deviceregistry.models.SystemAssignedServiceIdentityType; -import java.util.HashMap; -import java.util.Map; -import org.junit.jupiter.api.Assertions; - -public final class SchemaRegistryUpdateTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - SchemaRegistryUpdate model = BinaryData.fromString( - "{\"identity\":{\"principalId\":\"zpfzabglc\",\"tenantId\":\"xwtctyqiklbbovpl\",\"type\":\"SystemAssigned\"},\"tags\":{\"mkfssxqukkfplgm\":\"vgyuguos\",\"wiyighxpkdw\":\"sxnkjzkdeslpvlo\",\"upedeojnabckhs\":\"baiuebbaumny\"},\"properties\":{\"displayName\":\"psiebtfhvpes\",\"description\":\"skrdqmhjj\"}}") - .toObject(SchemaRegistryUpdate.class); - Assertions.assertEquals(SystemAssignedServiceIdentityType.SYSTEM_ASSIGNED, model.identity().type()); - Assertions.assertEquals("vgyuguos", model.tags().get("mkfssxqukkfplgm")); - Assertions.assertEquals("psiebtfhvpes", model.properties().displayName()); - Assertions.assertEquals("skrdqmhjj", model.properties().description()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - SchemaRegistryUpdate model = new SchemaRegistryUpdate() - .withIdentity( - new SystemAssignedServiceIdentity().withType(SystemAssignedServiceIdentityType.SYSTEM_ASSIGNED)) - .withTags(mapOf("mkfssxqukkfplgm", "vgyuguos", "wiyighxpkdw", "sxnkjzkdeslpvlo", "upedeojnabckhs", - "baiuebbaumny")) - .withProperties( - new SchemaRegistryUpdateProperties().withDisplayName("psiebtfhvpes").withDescription("skrdqmhjj")); - model = BinaryData.fromObject(model).toObject(SchemaRegistryUpdate.class); - Assertions.assertEquals(SystemAssignedServiceIdentityType.SYSTEM_ASSIGNED, model.identity().type()); - Assertions.assertEquals("vgyuguos", model.tags().get("mkfssxqukkfplgm")); - Assertions.assertEquals("psiebtfhvpes", model.properties().displayName()); - Assertions.assertEquals("skrdqmhjj", model.properties().description()); - } - - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionInnerTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionInnerTests.java deleted file mode 100644 index 12dabcc15478..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionInnerTests.java +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.deviceregistry.fluent.models.SchemaVersionInner; -import com.azure.resourcemanager.deviceregistry.models.SchemaVersionProperties; -import org.junit.jupiter.api.Assertions; - -public final class SchemaVersionInnerTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - SchemaVersionInner model = BinaryData.fromString( - "{\"properties\":{\"uuid\":\"e\",\"description\":\"t\",\"schemaContent\":\"qaqtdoqmcbxvwvxy\",\"hash\":\"qbhsfxobl\",\"provisioningState\":\"Canceled\"},\"id\":\"lmpewwwfbkr\",\"name\":\"rn\",\"type\":\"vshqjohxcr\"}") - .toObject(SchemaVersionInner.class); - Assertions.assertEquals("t", model.properties().description()); - Assertions.assertEquals("qaqtdoqmcbxvwvxy", model.properties().schemaContent()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - SchemaVersionInner model = new SchemaVersionInner() - .withProperties(new SchemaVersionProperties().withDescription("t").withSchemaContent("qaqtdoqmcbxvwvxy")); - model = BinaryData.fromObject(model).toObject(SchemaVersionInner.class); - Assertions.assertEquals("t", model.properties().description()); - Assertions.assertEquals("qaqtdoqmcbxvwvxy", model.properties().schemaContent()); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionListResultTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionListResultTests.java deleted file mode 100644 index 1ae95b9de94e..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionListResultTests.java +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.deviceregistry.implementation.models.SchemaVersionListResult; -import org.junit.jupiter.api.Assertions; - -public final class SchemaVersionListResultTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - SchemaVersionListResult model = BinaryData.fromString( - "{\"value\":[{\"properties\":{\"uuid\":\"otftpvjzbexilz\",\"description\":\"fqqnvwpmqtaruo\",\"schemaContent\":\"jmkcjhwqytj\",\"hash\":\"bnw\",\"provisioningState\":\"Deleting\"},\"id\":\"drjervnaenqpehin\",\"name\":\"oygmift\",\"type\":\"nzdndslgna\"}],\"nextLink\":\"igynduhavhqlk\"}") - .toObject(SchemaVersionListResult.class); - Assertions.assertEquals("fqqnvwpmqtaruo", model.value().get(0).properties().description()); - Assertions.assertEquals("jmkcjhwqytj", model.value().get(0).properties().schemaContent()); - Assertions.assertEquals("igynduhavhqlk", model.nextLink()); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionPropertiesTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionPropertiesTests.java deleted file mode 100644 index c7e2d60e48af..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionPropertiesTests.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.deviceregistry.models.SchemaVersionProperties; -import org.junit.jupiter.api.Assertions; - -public final class SchemaVersionPropertiesTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - SchemaVersionProperties model = BinaryData.fromString( - "{\"uuid\":\"fovasr\",\"description\":\"v\",\"schemaContent\":\"bhsqfsubcgjbirxb\",\"hash\":\"bsrfbj\",\"provisioningState\":\"Deleting\"}") - .toObject(SchemaVersionProperties.class); - Assertions.assertEquals("v", model.description()); - Assertions.assertEquals("bhsqfsubcgjbirxb", model.schemaContent()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - SchemaVersionProperties model - = new SchemaVersionProperties().withDescription("v").withSchemaContent("bhsqfsubcgjbirxb"); - model = BinaryData.fromObject(model).toObject(SchemaVersionProperties.class); - Assertions.assertEquals("v", model.description()); - Assertions.assertEquals("bhsqfsubcgjbirxb", model.schemaContent()); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionsCreateOrReplaceWithResponseMockTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionsCreateOrReplaceWithResponseMockTests.java deleted file mode 100644 index 0aa5c64f3ff6..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionsCreateOrReplaceWithResponseMockTests.java +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.credential.AccessToken; -import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.profile.AzureProfile; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.resourcemanager.deviceregistry.DeviceRegistryManager; -import com.azure.resourcemanager.deviceregistry.models.SchemaVersion; -import com.azure.resourcemanager.deviceregistry.models.SchemaVersionProperties; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -public final class SchemaVersionsCreateOrReplaceWithResponseMockTests { - @Test - public void testCreateOrReplaceWithResponse() throws Exception { - String responseStr - = "{\"properties\":{\"uuid\":\"hfssnrb\",\"description\":\"efr\",\"schemaContent\":\"msgaoj\",\"hash\":\"wncot\",\"provisioningState\":\"Accepted\"},\"id\":\"irctymoxoftpipiw\",\"name\":\"czuhxacpqjlihh\",\"type\":\"usps\"}"; - - HttpClient httpClient - = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); - DeviceRegistryManager manager = DeviceRegistryManager.configure() - .withHttpClient(httpClient) - .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); - - SchemaVersion response = manager.schemaVersions() - .define("ieoxorggufhyaomt") - .withExistingSchema("awnopqgikyzirtxd", "uxzejntpsew", "ioilqukrydxtq") - .withProperties(new SchemaVersionProperties().withDescription("ovjzhpjbibgjmfx").withSchemaContent("mv")) - .create(); - - Assertions.assertEquals("efr", response.properties().description()); - Assertions.assertEquals("msgaoj", response.properties().schemaContent()); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionsDeleteWithResponseMockTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionsDeleteWithResponseMockTests.java deleted file mode 100644 index 1bff9a8eb8b7..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionsDeleteWithResponseMockTests.java +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.credential.AccessToken; -import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.profile.AzureProfile; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.resourcemanager.deviceregistry.DeviceRegistryManager; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -public final class SchemaVersionsDeleteWithResponseMockTests { - @Test - public void testDeleteWithResponse() throws Exception { - String responseStr = "{}"; - - HttpClient httpClient - = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); - DeviceRegistryManager manager = DeviceRegistryManager.configure() - .withHttpClient(httpClient) - .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); - - manager.schemaVersions() - .deleteWithResponse("wtovvtgsein", "fiufx", "knpirgnepttwq", "sniffc", com.azure.core.util.Context.NONE); - - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionsGetWithResponseMockTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionsGetWithResponseMockTests.java deleted file mode 100644 index 1eeb0250aab2..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionsGetWithResponseMockTests.java +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.credential.AccessToken; -import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.profile.AzureProfile; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.resourcemanager.deviceregistry.DeviceRegistryManager; -import com.azure.resourcemanager.deviceregistry.models.SchemaVersion; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -public final class SchemaVersionsGetWithResponseMockTests { - @Test - public void testGetWithResponse() throws Exception { - String responseStr - = "{\"properties\":{\"uuid\":\"bfpncurdo\",\"description\":\"iithtywu\",\"schemaContent\":\"xcbihw\",\"hash\":\"nfdn\",\"provisioningState\":\"Deleting\"},\"id\":\"hrdgoihxumwcto\",\"name\":\"dzjlu\",\"type\":\"dfdlwggyts\"}"; - - HttpClient httpClient - = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); - DeviceRegistryManager manager = DeviceRegistryManager.configure() - .withHttpClient(httpClient) - .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); - - SchemaVersion response = manager.schemaVersions() - .getWithResponse("stotxh", "jujbypelmcuvhixb", "xyfwnylrcool", "ttpkiwkkbnujrywv", - com.azure.core.util.Context.NONE) - .getValue(); - - Assertions.assertEquals("iithtywu", response.properties().description()); - Assertions.assertEquals("xcbihw", response.properties().schemaContent()); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionsListBySchemaMockTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionsListBySchemaMockTests.java deleted file mode 100644 index 310798aeee94..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemaVersionsListBySchemaMockTests.java +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.credential.AccessToken; -import com.azure.core.http.HttpClient; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.profile.AzureProfile; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.resourcemanager.deviceregistry.DeviceRegistryManager; -import com.azure.resourcemanager.deviceregistry.models.SchemaVersion; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -public final class SchemaVersionsListBySchemaMockTests { - @Test - public void testListBySchema() throws Exception { - String responseStr - = "{\"value\":[{\"properties\":{\"uuid\":\"yzhftwesgogczh\",\"description\":\"nxkrlgnyhmossxkk\",\"schemaContent\":\"thrrgh\",\"hash\":\"bdhqxvcxgf\",\"provisioningState\":\"Canceled\"},\"id\":\"ofbshr\",\"name\":\"svbuswdvzyy\",\"type\":\"ycnunvjsrtk\"}]}"; - - HttpClient httpClient - = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); - DeviceRegistryManager manager = DeviceRegistryManager.configure() - .withHttpClient(httpClient) - .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); - - PagedIterable response = manager.schemaVersions() - .listBySchema("mqnrojlpijnkr", "frddhcrati", "zronasxift", com.azure.core.util.Context.NONE); - - Assertions.assertEquals("nxkrlgnyhmossxkk", response.iterator().next().properties().description()); - Assertions.assertEquals("thrrgh", response.iterator().next().properties().schemaContent()); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemasCreateOrReplaceWithResponseMockTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemasCreateOrReplaceWithResponseMockTests.java deleted file mode 100644 index 3bf3c1d7afd7..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemasCreateOrReplaceWithResponseMockTests.java +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.credential.AccessToken; -import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.profile.AzureProfile; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.resourcemanager.deviceregistry.DeviceRegistryManager; -import com.azure.resourcemanager.deviceregistry.models.Format; -import com.azure.resourcemanager.deviceregistry.models.Schema; -import com.azure.resourcemanager.deviceregistry.models.SchemaProperties; -import com.azure.resourcemanager.deviceregistry.models.SchemaType; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import java.util.HashMap; -import java.util.Map; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -public final class SchemasCreateOrReplaceWithResponseMockTests { - @Test - public void testCreateOrReplaceWithResponse() throws Exception { - String responseStr - = "{\"properties\":{\"uuid\":\"zejjoqk\",\"displayName\":\"fhsxttaugz\",\"description\":\"faazpxdtnkdmkqjj\",\"format\":\"JsonSchema/draft-07\",\"schemaType\":\"MessageSchema\",\"provisioningState\":\"Accepted\",\"tags\":{\"j\":\"kpyouaibrebqaay\",\"ttezlw\":\"ixqtn\",\"pqqmted\":\"ffiakp\",\"wau\":\"tmmjihyeozph\"}},\"id\":\"ncyg\",\"name\":\"p\",\"type\":\"vipmdscwxqupevzh\"}"; - - HttpClient httpClient - = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); - DeviceRegistryManager manager = DeviceRegistryManager.configure() - .withHttpClient(httpClient) - .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); - - Schema response = manager.schemas() - .define("on") - .withExistingSchemaRegistry("ycxzbfvoo", "vrvmtgjqppyost") - .withProperties(new SchemaProperties().withDisplayName("krrjrea") - .withDescription("tsgumhj") - .withFormat(Format.JSON_SCHEMA_DRAFT7) - .withSchemaType(SchemaType.MESSAGE_SCHEMA) - .withTags(mapOf("qpvuzlmvfelf", "slol", "crpw", "tgp"))) - .create(); - - Assertions.assertEquals("fhsxttaugz", response.properties().displayName()); - Assertions.assertEquals("faazpxdtnkdmkqjj", response.properties().description()); - Assertions.assertEquals(Format.JSON_SCHEMA_DRAFT7, response.properties().format()); - Assertions.assertEquals(SchemaType.MESSAGE_SCHEMA, response.properties().schemaType()); - Assertions.assertEquals("kpyouaibrebqaay", response.properties().tags().get("j")); - } - - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemasDeleteWithResponseMockTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemasDeleteWithResponseMockTests.java deleted file mode 100644 index 7dba3ad0dff0..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemasDeleteWithResponseMockTests.java +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.credential.AccessToken; -import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.profile.AzureProfile; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.resourcemanager.deviceregistry.DeviceRegistryManager; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -public final class SchemasDeleteWithResponseMockTests { - @Test - public void testDeleteWithResponse() throws Exception { - String responseStr = "{}"; - - HttpClient httpClient - = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); - DeviceRegistryManager manager = DeviceRegistryManager.configure() - .withHttpClient(httpClient) - .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); - - manager.schemas().deleteWithResponse("gikdgsz", "w", "birryuzhl", com.azure.core.util.Context.NONE); - - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemasGetWithResponseMockTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemasGetWithResponseMockTests.java deleted file mode 100644 index 2eead55996ce..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemasGetWithResponseMockTests.java +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.credential.AccessToken; -import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.profile.AzureProfile; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.resourcemanager.deviceregistry.DeviceRegistryManager; -import com.azure.resourcemanager.deviceregistry.models.Format; -import com.azure.resourcemanager.deviceregistry.models.Schema; -import com.azure.resourcemanager.deviceregistry.models.SchemaType; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -public final class SchemasGetWithResponseMockTests { - @Test - public void testGetWithResponse() throws Exception { - String responseStr - = "{\"properties\":{\"uuid\":\"psvuoymgc\",\"displayName\":\"lvez\",\"description\":\"pqlmfe\",\"format\":\"JsonSchema/draft-07\",\"schemaType\":\"MessageSchema\",\"provisioningState\":\"Deleting\",\"tags\":{\"opgxedkowepb\":\"yhko\",\"fkbw\":\"pc\",\"khtj\":\"csnjvcdwxlpqekft\"}},\"id\":\"i\",\"name\":\"gwfqatmt\",\"type\":\"htmdvy\"}"; - - HttpClient httpClient - = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); - DeviceRegistryManager manager = DeviceRegistryManager.configure() - .withHttpClient(httpClient) - .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); - - Schema response = manager.schemas() - .getWithResponse("lvdnkfx", "semdwzrmu", "apfcqdpsq", com.azure.core.util.Context.NONE) - .getValue(); - - Assertions.assertEquals("lvez", response.properties().displayName()); - Assertions.assertEquals("pqlmfe", response.properties().description()); - Assertions.assertEquals(Format.JSON_SCHEMA_DRAFT7, response.properties().format()); - Assertions.assertEquals(SchemaType.MESSAGE_SCHEMA, response.properties().schemaType()); - Assertions.assertEquals("yhko", response.properties().tags().get("opgxedkowepb")); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemasListBySchemaRegistryMockTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemasListBySchemaRegistryMockTests.java deleted file mode 100644 index a1a436d051f8..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SchemasListBySchemaRegistryMockTests.java +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.credential.AccessToken; -import com.azure.core.http.HttpClient; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.profile.AzureProfile; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.resourcemanager.deviceregistry.DeviceRegistryManager; -import com.azure.resourcemanager.deviceregistry.models.Format; -import com.azure.resourcemanager.deviceregistry.models.Schema; -import com.azure.resourcemanager.deviceregistry.models.SchemaType; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -public final class SchemasListBySchemaRegistryMockTests { - @Test - public void testListBySchemaRegistry() throws Exception { - String responseStr - = "{\"value\":[{\"properties\":{\"uuid\":\"jinrvgoupmfiibfg\",\"displayName\":\"ioolvrwxkvtkkgll\",\"description\":\"jygvjayvbl\",\"format\":\"JsonSchema/draft-07\",\"schemaType\":\"MessageSchema\",\"provisioningState\":\"Succeeded\",\"tags\":{\"opbyrqufegxu\":\"bxvvyhg\",\"bnhlmc\":\"wz\",\"dn\":\"l\",\"ijejvegrhbpn\":\"itvgbmhrixkwm\"}},\"id\":\"xexccbdreaxhcexd\",\"name\":\"rvqahqkghtpwi\",\"type\":\"nhyjsv\"}]}"; - - HttpClient httpClient - = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); - DeviceRegistryManager manager = DeviceRegistryManager.configure() - .withHttpClient(httpClient) - .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); - - PagedIterable response - = manager.schemas().listBySchemaRegistry("kj", "qrvqq", com.azure.core.util.Context.NONE); - - Assertions.assertEquals("ioolvrwxkvtkkgll", response.iterator().next().properties().displayName()); - Assertions.assertEquals("jygvjayvbl", response.iterator().next().properties().description()); - Assertions.assertEquals(Format.JSON_SCHEMA_DRAFT7, response.iterator().next().properties().format()); - Assertions.assertEquals(SchemaType.MESSAGE_SCHEMA, response.iterator().next().properties().schemaType()); - Assertions.assertEquals("bxvvyhg", response.iterator().next().properties().tags().get("opbyrqufegxu")); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SystemAssignedServiceIdentityTests.java b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SystemAssignedServiceIdentityTests.java deleted file mode 100644 index cb67f0006a34..000000000000 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/src/test/java/com/azure/resourcemanager/deviceregistry/generated/SystemAssignedServiceIdentityTests.java +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.azure.resourcemanager.deviceregistry.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.deviceregistry.models.SystemAssignedServiceIdentity; -import com.azure.resourcemanager.deviceregistry.models.SystemAssignedServiceIdentityType; -import org.junit.jupiter.api.Assertions; - -public final class SystemAssignedServiceIdentityTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - SystemAssignedServiceIdentity model = BinaryData - .fromString("{\"principalId\":\"avxbniwdjswztsdb\",\"tenantId\":\"nxytxh\",\"type\":\"SystemAssigned\"}") - .toObject(SystemAssignedServiceIdentity.class); - Assertions.assertEquals(SystemAssignedServiceIdentityType.SYSTEM_ASSIGNED, model.type()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - SystemAssignedServiceIdentity model - = new SystemAssignedServiceIdentity().withType(SystemAssignedServiceIdentityType.SYSTEM_ASSIGNED); - model = BinaryData.fromObject(model).toObject(SystemAssignedServiceIdentity.class); - Assertions.assertEquals(SystemAssignedServiceIdentityType.SYSTEM_ASSIGNED, model.type()); - } -} diff --git a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/tsp-location.yaml b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/tsp-location.yaml index a3c794017c7b..05a816a2ca90 100644 --- a/sdk/deviceregistry/azure-resourcemanager-deviceregistry/tsp-location.yaml +++ b/sdk/deviceregistry/azure-resourcemanager-deviceregistry/tsp-location.yaml @@ -1,4 +1,4 @@ directory: specification/deviceregistry/DeviceRegistry.Management -commit: 58740206b853320974ef5e4864f7be8120b15a27 +commit: fb07075e59f7e2403e4a9f5a13beea0b29ac9b9c repo: Azure/azure-rest-api-specs additionalDirectories: diff --git a/sdk/deviceregistry/test-resources.bicep b/sdk/deviceregistry/test-resources.bicep new file mode 100644 index 000000000000..3ff2bac58bec --- /dev/null +++ b/sdk/deviceregistry/test-resources.bicep @@ -0,0 +1,22 @@ +@description('The tenant id to which the application and resources belong.') +param tenantId string = '72f988bf-86f1-41af-91ab-2d7cd011db47' + +@description('The client id of the service principal used to run tests.') +param testApplicationId string + +@description('This is the object id of the service principal used to run tests.') +param testApplicationOid string + +var contributorRoleId = '/subscriptions/${subscription().subscriptionId}/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c' + +resource contributorRoleId_name 'Microsoft.Authorization/roleAssignments@2022-04-01' = { + name: guid('contributorRoleId${resourceGroup().name}') + properties: { + roleDefinitionId: contributorRoleId + principalId: testApplicationOid + } +} + +output AZURE_TENANT_ID string = tenantId +output AZURE_SUBSCRIPTION_ID string = subscription().subscriptionId +output AZURE_RESOURCE_GROUP_NAME string = resourceGroup().name diff --git a/sdk/deviceregistry/tests.mgmt.yml b/sdk/deviceregistry/tests.mgmt.yml new file mode 100644 index 000000000000..8238e3a8e93b --- /dev/null +++ b/sdk/deviceregistry/tests.mgmt.yml @@ -0,0 +1,15 @@ +trigger: none + +pr: none + +extends: + template: /eng/pipelines/templates/stages/archetype-sdk-tests.yml + parameters: + ServiceDirectory: deviceregistry + Artifacts: + - name: azure-resourcemanager-deviceregistry + groupId: com.azure.resourcemanager + safeName: azureresourcemanagerdeviceregistry + # Only run tests on Windows to save cost. + MatrixFilters: + - pool=.*(win).* diff --git a/sdk/deviceupdate/azure-iot-deviceupdate/CHANGELOG.md b/sdk/deviceupdate/azure-iot-deviceupdate/CHANGELOG.md index 29d64dcb6eb1..7da93a4abdee 100644 --- a/sdk/deviceupdate/azure-iot-deviceupdate/CHANGELOG.md +++ b/sdk/deviceupdate/azure-iot-deviceupdate/CHANGELOG.md @@ -10,6 +10,16 @@ ### Other Changes +## 1.0.25 (2025-02-25) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`. +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. + + ## 1.0.24 (2024-12-04) ### Other Changes @@ -19,6 +29,7 @@ - Upgraded `azure-core` from `1.53.0` to version `1.54.1`. - Upgraded `azure-core-http-netty` from `1.15.5` to version `1.15.7`. + ## 1.0.23 (2024-10-27) ### Other Changes diff --git a/sdk/deviceupdate/azure-iot-deviceupdate/README.md b/sdk/deviceupdate/azure-iot-deviceupdate/README.md index e1d77ec48235..a1649e3c8d26 100644 --- a/sdk/deviceupdate/azure-iot-deviceupdate/README.md +++ b/sdk/deviceupdate/azure-iot-deviceupdate/README.md @@ -24,7 +24,7 @@ For the best development experience, developers should use the official Microsof com.azure azure-iot-deviceupdate - 1.0.9 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -87,4 +87,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ [coc_contact]: mailto:opencode@microsoft.com -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fdeviceupdate%2Fazure-iot-deviceupdate%2FREADME.png) + diff --git a/sdk/deviceupdate/azure-iot-deviceupdate/pom.xml b/sdk/deviceupdate/azure-iot-deviceupdate/pom.xml index 939bc1df9cdf..d499f11d1078 100644 --- a/sdk/deviceupdate/azure-iot-deviceupdate/pom.xml +++ b/sdk/deviceupdate/azure-iot-deviceupdate/pom.xml @@ -43,23 +43,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test diff --git a/sdk/deviceupdate/azure-resourcemanager-deviceupdate/README.md b/sdk/deviceupdate/azure-resourcemanager-deviceupdate/README.md index e81f301d9a28..e8f9535b8cf4 100644 --- a/sdk/deviceupdate/azure-resourcemanager-deviceupdate/README.md +++ b/sdk/deviceupdate/azure-resourcemanager-deviceupdate/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-deviceupdate - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -108,4 +108,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fdeviceupdate%2Fazure-resourcemanager-deviceupdate%2FREADME.png) + diff --git a/sdk/deviceupdate/azure-resourcemanager-deviceupdate/pom.xml b/sdk/deviceupdate/azure-resourcemanager-deviceupdate/pom.xml index 86f33655a220..e70d1bd80bb3 100644 --- a/sdk/deviceupdate/azure-resourcemanager-deviceupdate/pom.xml +++ b/sdk/deviceupdate/azure-resourcemanager-deviceupdate/pom.xml @@ -51,29 +51,29 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/devopsinfrastructure/azure-resourcemanager-devopsinfrastructure/README.md b/sdk/devopsinfrastructure/azure-resourcemanager-devopsinfrastructure/README.md index a0eb82092b22..4841308a730c 100644 --- a/sdk/devopsinfrastructure/azure-resourcemanager-devopsinfrastructure/README.md +++ b/sdk/devopsinfrastructure/azure-resourcemanager-devopsinfrastructure/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-devopsinfrastructure - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fdevopsinfrastructure%2Fazure-resourcemanager-devopsinfrastructure%2FREADME.png) + diff --git a/sdk/devopsinfrastructure/azure-resourcemanager-devopsinfrastructure/pom.xml b/sdk/devopsinfrastructure/azure-resourcemanager-devopsinfrastructure/pom.xml index 1ee85ae96081..4d674e1bf373 100644 --- a/sdk/devopsinfrastructure/azure-resourcemanager-devopsinfrastructure/pom.xml +++ b/sdk/devopsinfrastructure/azure-resourcemanager-devopsinfrastructure/pom.xml @@ -52,29 +52,29 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-json - 1.3.0 + 1.5.0 diff --git a/sdk/devopsinfrastructure/azure-resourcemanager-devopsinfrastructure/src/main/java/com/azure/resourcemanager/devopsinfrastructure/DevOpsInfrastructureManager.java b/sdk/devopsinfrastructure/azure-resourcemanager-devopsinfrastructure/src/main/java/com/azure/resourcemanager/devopsinfrastructure/DevOpsInfrastructureManager.java index cbcbd91cb524..796c7433f7e7 100644 --- a/sdk/devopsinfrastructure/azure-resourcemanager-devopsinfrastructure/src/main/java/com/azure/resourcemanager/devopsinfrastructure/DevOpsInfrastructureManager.java +++ b/sdk/devopsinfrastructure/azure-resourcemanager-devopsinfrastructure/src/main/java/com/azure/resourcemanager/devopsinfrastructure/DevOpsInfrastructureManager.java @@ -22,6 +22,7 @@ import com.azure.core.http.policy.UserAgentPolicy; import com.azure.core.management.profile.AzureProfile; import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.devopsinfrastructure.fluent.DevOpsInfrastructureManagementClient; import com.azure.resourcemanager.devopsinfrastructure.implementation.DevOpsInfrastructureManagementClientBuilder; @@ -41,6 +42,7 @@ import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; @@ -112,6 +114,9 @@ public static Configurable configure() { */ public static final class Configurable { private static final ClientLogger LOGGER = new ClientLogger(Configurable.class); + private static final String SDK_VERSION = "version"; + private static final Map PROPERTIES + = CoreUtils.getProperties("azure-resourcemanager-devopsinfrastructure.properties"); private HttpClient httpClient; private HttpLogOptions httpLogOptions; @@ -219,12 +224,14 @@ public DevOpsInfrastructureManager authenticate(TokenCredential credential, Azur Objects.requireNonNull(credential, "'credential' cannot be null."); Objects.requireNonNull(profile, "'profile' cannot be null."); + String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); + StringBuilder userAgentBuilder = new StringBuilder(); userAgentBuilder.append("azsdk-java") .append("-") .append("com.azure.resourcemanager.devopsinfrastructure") .append("/") - .append("1.0.0-beta.1"); + .append(clientVersion); if (!Configuration.getGlobalConfiguration().get("AZURE_TELEMETRY_DISABLED", false)) { userAgentBuilder.append(" (") .append(Configuration.getGlobalConfiguration().get("java.version")) diff --git a/sdk/devopsinfrastructure/azure-resourcemanager-devopsinfrastructure/src/main/java/com/azure/resourcemanager/devopsinfrastructure/models/UserAssignedIdentity.java b/sdk/devopsinfrastructure/azure-resourcemanager-devopsinfrastructure/src/main/java/com/azure/resourcemanager/devopsinfrastructure/models/UserAssignedIdentity.java index b55c395c305a..04fb871be842 100644 --- a/sdk/devopsinfrastructure/azure-resourcemanager-devopsinfrastructure/src/main/java/com/azure/resourcemanager/devopsinfrastructure/models/UserAssignedIdentity.java +++ b/sdk/devopsinfrastructure/azure-resourcemanager-devopsinfrastructure/src/main/java/com/azure/resourcemanager/devopsinfrastructure/models/UserAssignedIdentity.java @@ -17,14 +17,14 @@ @Immutable public final class UserAssignedIdentity implements JsonSerializable { /* - * The principal ID of the assigned identity. + * The client ID of the assigned identity. */ - private String principalId; + private String clientId; /* - * The client ID of the assigned identity. + * The principal ID of the assigned identity. */ - private String clientId; + private String principalId; /** * Creates an instance of UserAssignedIdentity class. @@ -33,21 +33,21 @@ public UserAssignedIdentity() { } /** - * Get the principalId property: The principal ID of the assigned identity. + * Get the clientId property: The client ID of the assigned identity. * - * @return the principalId value. + * @return the clientId value. */ - public String principalId() { - return this.principalId; + public String clientId() { + return this.clientId; } /** - * Get the clientId property: The client ID of the assigned identity. + * Get the principalId property: The principal ID of the assigned identity. * - * @return the clientId value. + * @return the principalId value. */ - public String clientId() { - return this.clientId; + public String principalId() { + return this.principalId; } /** @@ -82,10 +82,10 @@ public static UserAssignedIdentity fromJson(JsonReader jsonReader) throws IOExce String fieldName = reader.getFieldName(); reader.nextToken(); - if ("principalId".equals(fieldName)) { - deserializedUserAssignedIdentity.principalId = reader.getString(); - } else if ("clientId".equals(fieldName)) { + if ("clientId".equals(fieldName)) { deserializedUserAssignedIdentity.clientId = reader.getString(); + } else if ("principalId".equals(fieldName)) { + deserializedUserAssignedIdentity.principalId = reader.getString(); } else { reader.skipChildren(); } diff --git a/sdk/devopsinfrastructure/azure-resourcemanager-devopsinfrastructure/src/main/resources/azure-resourcemanager-devopsinfrastructure.properties b/sdk/devopsinfrastructure/azure-resourcemanager-devopsinfrastructure/src/main/resources/azure-resourcemanager-devopsinfrastructure.properties new file mode 100644 index 000000000000..defbd48204e4 --- /dev/null +++ b/sdk/devopsinfrastructure/azure-resourcemanager-devopsinfrastructure/src/main/resources/azure-resourcemanager-devopsinfrastructure.properties @@ -0,0 +1 @@ +version=${project.version} diff --git a/sdk/devspaces/azure-resourcemanager-devspaces/README.md b/sdk/devspaces/azure-resourcemanager-devspaces/README.md index c5bced98adee..f7e43bbf92ee 100644 --- a/sdk/devspaces/azure-resourcemanager-devspaces/README.md +++ b/sdk/devspaces/azure-resourcemanager-devspaces/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-devspaces - 1.0.0-beta.3 + 1.0.0-beta.4 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fdevspaces%2Fazure-resourcemanager-devspaces%2FREADME.png) + diff --git a/sdk/devspaces/azure-resourcemanager-devspaces/pom.xml b/sdk/devspaces/azure-resourcemanager-devspaces/pom.xml index ba3237045f38..90f630a69b0d 100644 --- a/sdk/devspaces/azure-resourcemanager-devspaces/pom.xml +++ b/sdk/devspaces/azure-resourcemanager-devspaces/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/devtestlabs/azure-resourcemanager-devtestlabs/README.md b/sdk/devtestlabs/azure-resourcemanager-devtestlabs/README.md index f6fdb9dd76da..9916a9c49e7b 100644 --- a/sdk/devtestlabs/azure-resourcemanager-devtestlabs/README.md +++ b/sdk/devtestlabs/azure-resourcemanager-devtestlabs/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-devtestlabs - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -108,4 +108,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fdevtestlabs%2Fazure-resourcemanager-devtestlabs%2FREADME.png) + diff --git a/sdk/devtestlabs/azure-resourcemanager-devtestlabs/pom.xml b/sdk/devtestlabs/azure-resourcemanager-devtestlabs/pom.xml index cfe803cdaf54..ed07611aecd5 100644 --- a/sdk/devtestlabs/azure-resourcemanager-devtestlabs/pom.xml +++ b/sdk/devtestlabs/azure-resourcemanager-devtestlabs/pom.xml @@ -51,29 +51,29 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/digitaltwins/azure-digitaltwins-core/CHANGELOG.md b/sdk/digitaltwins/azure-digitaltwins-core/CHANGELOG.md index 3fb62f9e4b40..2693f1ae336a 100644 --- a/sdk/digitaltwins/azure-digitaltwins-core/CHANGELOG.md +++ b/sdk/digitaltwins/azure-digitaltwins-core/CHANGELOG.md @@ -10,6 +10,17 @@ ### Other Changes + +## 1.4.1 (2025-02-28) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`. +- Upgraded `azure-core-serializer-json-jackson` from `1.5.4` to version `1.5.7`. + ## 1.4.0 (2024-11-14) ### Features Added diff --git a/sdk/digitaltwins/azure-digitaltwins-core/README.md b/sdk/digitaltwins/azure-digitaltwins-core/README.md index dec4b6f35a79..fcb7ac68f30a 100644 --- a/sdk/digitaltwins/azure-digitaltwins-core/README.md +++ b/sdk/digitaltwins/azure-digitaltwins-core/README.md @@ -51,7 +51,7 @@ add the direct dependency to your project as follows. com.azure azure-digitaltwins-core - 1.4.0 + 1.5.0-beta.1 ``` diff --git a/sdk/digitaltwins/azure-digitaltwins-core/pom.xml b/sdk/digitaltwins/azure-digitaltwins-core/pom.xml index a84fac6b393a..8374f499c442 100644 --- a/sdk/digitaltwins/azure-digitaltwins-core/pom.xml +++ b/sdk/digitaltwins/azure-digitaltwins-core/pom.xml @@ -46,38 +46,33 @@ - - com.azure - azure-json - 1.3.0 - com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-serializer-json-jackson - 1.5.4 + 1.5.8 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/digitaltwins/azure-resourcemanager-digitaltwins/README.md b/sdk/digitaltwins/azure-resourcemanager-digitaltwins/README.md index adc3bb5fe0ef..30e819d1f8c1 100644 --- a/sdk/digitaltwins/azure-resourcemanager-digitaltwins/README.md +++ b/sdk/digitaltwins/azure-resourcemanager-digitaltwins/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-digitaltwins - 1.3.0 + 1.4.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fdigitaltwins%2Fazure-resourcemanager-digitaltwins%2FREADME.png) + diff --git a/sdk/digitaltwins/azure-resourcemanager-digitaltwins/pom.xml b/sdk/digitaltwins/azure-resourcemanager-digitaltwins/pom.xml index 10e62bcc389b..41642783cd62 100644 --- a/sdk/digitaltwins/azure-resourcemanager-digitaltwins/pom.xml +++ b/sdk/digitaltwins/azure-resourcemanager-digitaltwins/pom.xml @@ -52,23 +52,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test @@ -92,7 +92,7 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/dnsresolver/azure-resourcemanager-dnsresolver/README.md b/sdk/dnsresolver/azure-resourcemanager-dnsresolver/README.md index d04a7d469018..9e9b544c85f0 100644 --- a/sdk/dnsresolver/azure-resourcemanager-dnsresolver/README.md +++ b/sdk/dnsresolver/azure-resourcemanager-dnsresolver/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-dnsresolver - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fdnsresolver%2Fazure-resourcemanager-dnsresolver%2FREADME.png) + diff --git a/sdk/dnsresolver/azure-resourcemanager-dnsresolver/pom.xml b/sdk/dnsresolver/azure-resourcemanager-dnsresolver/pom.xml index 94acfae746a7..e57eca260796 100644 --- a/sdk/dnsresolver/azure-resourcemanager-dnsresolver/pom.xml +++ b/sdk/dnsresolver/azure-resourcemanager-dnsresolver/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/documentintelligence/azure-ai-documentintelligence/CHANGELOG.md b/sdk/documentintelligence/azure-ai-documentintelligence/CHANGELOG.md index 6425f4ae9be9..9c4d51a54119 100644 --- a/sdk/documentintelligence/azure-ai-documentintelligence/CHANGELOG.md +++ b/sdk/documentintelligence/azure-ai-documentintelligence/CHANGELOG.md @@ -1,5 +1,15 @@ # Release History +## 1.1.0-beta.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + ## 1.0.0 (2024-12-16) ### Features Added diff --git a/sdk/documentintelligence/azure-ai-documentintelligence/MIGRATION_GUIDE.md b/sdk/documentintelligence/azure-ai-documentintelligence/MIGRATION_GUIDE.md index b1d74b94d14f..c53f8fc9bcf8 100644 --- a/sdk/documentintelligence/azure-ai-documentintelligence/MIGRATION_GUIDE.md +++ b/sdk/documentintelligence/azure-ai-documentintelligence/MIGRATION_GUIDE.md @@ -182,4 +182,4 @@ For additional samples please take a look at the [Document Intelligence Samples] [Sample-AnalyzeAddOnFormulas]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/documentintelligence/azure-ai-documentintelligence/src/samples/java/com/azure/ai/documentintelligence/AnalyzeAddOnFormulas.java [service_supported_models]: https://aka.ms/azsdk/documentintelligence/models -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fdocumentintelligence%2Fazure-ai-documentintelligence%2Fmigration-guide.png) + diff --git a/sdk/documentintelligence/azure-ai-documentintelligence/README.md b/sdk/documentintelligence/azure-ai-documentintelligence/README.md index 90c55e7df65d..58f401ded74f 100644 --- a/sdk/documentintelligence/azure-ai-documentintelligence/README.md +++ b/sdk/documentintelligence/azure-ai-documentintelligence/README.md @@ -29,7 +29,7 @@ It includes the following main features: com.azure azure-ai-documentintelligence - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -94,7 +94,7 @@ Authentication with AAD requires some initial setup: com.azure azure-identity - 1.14.2 + 1.15.3 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/documentintelligence/azure-ai-documentintelligence/pom.xml b/sdk/documentintelligence/azure-ai-documentintelligence/pom.xml index 7eed9b2d79be..b5736b962b0f 100644 --- a/sdk/documentintelligence/azure-ai-documentintelligence/pom.xml +++ b/sdk/documentintelligence/azure-ai-documentintelligence/pom.xml @@ -13,7 +13,7 @@ com.azure azure-ai-documentintelligence - 1.0.0 + 1.1.0-beta.1 Microsoft Azure client library for Document Intelligence This package contains the Microsoft Azure AI Document Intelligence SDK. @@ -50,25 +50,25 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/documentintelligence/azure-ai-documentintelligence/src/samples/README.md b/sdk/documentintelligence/azure-ai-documentintelligence/src/samples/README.md index a3ab928a41b1..62a6634dd9d1 100644 --- a/sdk/documentintelligence/azure-ai-documentintelligence/src/samples/README.md +++ b/sdk/documentintelligence/azure-ai-documentintelligence/src/samples/README.md @@ -118,4 +118,4 @@ Guidelines][SDK_README_CONTRIBUTING] for more information. [build_classifier]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/documentintelligence/azure-ai-documentintelligence/src/samples/java/com/azure/ai/documentintelligence/generated/BuildDocumentClassifier.java [build_classifier_async]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/documentintelligence/azure-ai-documentintelligence/src/samples/java/com/azure/ai/documentintelligence/generated/BuildDocumentClassifierAsync.java -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fdocumentintelligence%2Fazure-ai-documentintelligence%2FREADME.png) + diff --git a/sdk/dynatrace/azure-resourcemanager-dynatrace/README.md b/sdk/dynatrace/azure-resourcemanager-dynatrace/README.md index 853a309ea2f7..07c1d2a9fe6b 100644 --- a/sdk/dynatrace/azure-resourcemanager-dynatrace/README.md +++ b/sdk/dynatrace/azure-resourcemanager-dynatrace/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-dynatrace - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fdynatrace%2Fazure-resourcemanager-dynatrace%2FREADME.png) + diff --git a/sdk/dynatrace/azure-resourcemanager-dynatrace/pom.xml b/sdk/dynatrace/azure-resourcemanager-dynatrace/pom.xml index 4a65f210b907..b7e0422bc83b 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.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/e2e/pom.xml b/sdk/e2e/pom.xml index 7ee86604c263..7c5096e073a8 100644 --- a/sdk/e2e/pom.xml +++ b/sdk/e2e/pom.xml @@ -29,7 +29,7 @@ com.azure azure-core - 1.55.0-beta.1 + 1.56.0-beta.1 com.azure @@ -70,7 +70,7 @@ com.azure azure-core-test - 1.27.0-beta.5 + 1.27.0-beta.9 test diff --git a/sdk/e2e/src/main/java/com/azure/endtoend/identity/MultiTenantTest.java b/sdk/e2e/src/main/java/com/azure/endtoend/identity/MultiTenantTest.java index aedf2c4b6fcf..92ae60d42cc8 100644 --- a/sdk/e2e/src/main/java/com/azure/endtoend/identity/MultiTenantTest.java +++ b/sdk/e2e/src/main/java/com/azure/endtoend/identity/MultiTenantTest.java @@ -23,6 +23,7 @@ /** * Runs Identity tests across multiple tests. */ +@SuppressWarnings("deprecation") class MultiTenantTest { private static final String AZURE_MULTI_TENANT_TEST_MODE = "AZURE_MULTI_TENANT_TEST_MODE"; private static final String AZURE_USER_NAME = "AZURE_USER_NAME"; diff --git a/sdk/easm/azure-analytics-defender-easm/README.md b/sdk/easm/azure-analytics-defender-easm/README.md index e1b3d71179d2..d481ddc68bab 100644 --- a/sdk/easm/azure-analytics-defender-easm/README.md +++ b/sdk/easm/azure-analytics-defender-easm/README.md @@ -25,7 +25,7 @@ Various documentation is available to help you get started com.azure azure-analytics-defender-easm - 1.0.0-beta.1 + 1.0.0-beta.2 ``` [//]: # ({x-version-update-end}) @@ -107,4 +107,4 @@ For details on contributing to this repository, see the [contributing guide](htt [assets_documentation]: https://learn.microsoft.com/azure/external-attack-surface-management/understanding-inventory-assets [discovery_documentation]: https://learn.microsoft.com/azure/external-attack-surface-management/what-is-discovery [discovery_groups_documentation]: https://learn.microsoft.com/azure/external-attack-surface-management/using-and-managing-discovery#discovery-groups -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Feasm%2Fazure-analytics-defender-easm%2FREADME.png) + diff --git a/sdk/easm/azure-analytics-defender-easm/pom.xml b/sdk/easm/azure-analytics-defender-easm/pom.xml index 24982d680bda..d0aac25fefd9 100644 --- a/sdk/easm/azure-analytics-defender-easm/pom.xml +++ b/sdk/easm/azure-analytics-defender-easm/pom.xml @@ -53,23 +53,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/easm/azure-analytics-defender-easm/src/main/java/com/azure/analytics/defender/easm/EasmAsyncClient.java b/sdk/easm/azure-analytics-defender-easm/src/main/java/com/azure/analytics/defender/easm/EasmAsyncClient.java index da58169a67a9..376d18a26aa4 100644 --- a/sdk/easm/azure-analytics-defender-easm/src/main/java/com/azure/analytics/defender/easm/EasmAsyncClient.java +++ b/sdk/easm/azure-analytics-defender-easm/src/main/java/com/azure/analytics/defender/easm/EasmAsyncClient.java @@ -296,7 +296,7 @@ public PagedFlux listDataConnection(RequestOptions requestOptions) { * ] * innererror (Optional): { * code: String (Optional) - * value: BinaryData (Optional) + * innererror (Optional): (recursive schema, see innererror above) * } * } * } @@ -541,7 +541,7 @@ public PagedFlux listDiscoGroup(RequestOptions requestOptions) { * ] * innererror (Optional): { * code: String (Optional) - * value: BinaryData (Optional) + * innererror (Optional): (recursive schema, see innererror above) * } * } * } diff --git a/sdk/easm/azure-analytics-defender-easm/src/main/java/com/azure/analytics/defender/easm/EasmClient.java b/sdk/easm/azure-analytics-defender-easm/src/main/java/com/azure/analytics/defender/easm/EasmClient.java index 81e859071444..b5ba2598ffc9 100644 --- a/sdk/easm/azure-analytics-defender-easm/src/main/java/com/azure/analytics/defender/easm/EasmClient.java +++ b/sdk/easm/azure-analytics-defender-easm/src/main/java/com/azure/analytics/defender/easm/EasmClient.java @@ -289,7 +289,7 @@ public PagedIterable listDataConnection(RequestOptions requestOption * ] * innererror (Optional): { * code: String (Optional) - * value: BinaryData (Optional) + * innererror (Optional): (recursive schema, see innererror above) * } * } * } @@ -530,7 +530,7 @@ public PagedIterable listDiscoGroup(RequestOptions requestOptions) { * ] * innererror (Optional): { * code: String (Optional) - * value: BinaryData (Optional) + * innererror (Optional): (recursive schema, see innererror above) * } * } * } diff --git a/sdk/easm/azure-analytics-defender-easm/src/main/java/com/azure/analytics/defender/easm/implementation/EasmClientImpl.java b/sdk/easm/azure-analytics-defender-easm/src/main/java/com/azure/analytics/defender/easm/implementation/EasmClientImpl.java index 5c9242f8d739..cd574da24ef2 100644 --- a/sdk/easm/azure-analytics-defender-easm/src/main/java/com/azure/analytics/defender/easm/implementation/EasmClientImpl.java +++ b/sdk/easm/azure-analytics-defender-easm/src/main/java/com/azure/analytics/defender/easm/implementation/EasmClientImpl.java @@ -1605,7 +1605,7 @@ public PagedIterable listDataConnection(RequestOptions requestOption * ] * innererror (Optional): { * code: String (Optional) - * value: BinaryData (Optional) + * innererror (Optional): (recursive schema, see innererror above) * } * } * } @@ -1660,7 +1660,7 @@ public Mono> validateDataConnectionWithResponseAsync(Binary * ] * innererror (Optional): { * code: String (Optional) - * value: BinaryData (Optional) + * innererror (Optional): (recursive schema, see innererror above) * } * } * } @@ -2285,7 +2285,7 @@ public PagedIterable listDiscoGroup(RequestOptions requestOptions) { * ] * innererror (Optional): { * code: String (Optional) - * value: BinaryData (Optional) + * innererror (Optional): (recursive schema, see innererror above) * } * } * } @@ -2352,7 +2352,7 @@ public Mono> validateDiscoGroupWithResponseAsync(BinaryData * ] * innererror (Optional): { * code: String (Optional) - * value: BinaryData (Optional) + * innererror (Optional): (recursive schema, see innererror above) * } * } * } diff --git a/sdk/easm/azure-analytics-defender-easm/src/main/resources/META-INF/azure-analytics-defender-easm_apiview_properties.json b/sdk/easm/azure-analytics-defender-easm/src/main/resources/META-INF/azure-analytics-defender-easm_apiview_properties.json index ab00eaa8e32f..377ff06f60bc 100644 --- a/sdk/easm/azure-analytics-defender-easm/src/main/resources/META-INF/azure-analytics-defender-easm_apiview_properties.json +++ b/sdk/easm/azure-analytics-defender-easm/src/main/resources/META-INF/azure-analytics-defender-easm_apiview_properties.json @@ -137,7 +137,6 @@ "com.azure.analytics.defender.easm.models.HostAsset": "Easm.HostAsset", "com.azure.analytics.defender.easm.models.HostAssetResource": "Easm.HostAssetResource", "com.azure.analytics.defender.easm.models.HostCore": "Easm.HostCore", - "com.azure.analytics.defender.easm.models.InnerError": "Easm.InnerError", "com.azure.analytics.defender.easm.models.InventoryAsset": "Easm.InventoryAsset", "com.azure.analytics.defender.easm.models.IpAddressAsset": "Easm.IpAddressAsset", "com.azure.analytics.defender.easm.models.IpAddressAssetResource": "Easm.IpAddressAssetResource", diff --git a/sdk/edgeorder/azure-resourcemanager-edgeorder/README.md b/sdk/edgeorder/azure-resourcemanager-edgeorder/README.md index c12305be7feb..84443c722b0d 100644 --- a/sdk/edgeorder/azure-resourcemanager-edgeorder/README.md +++ b/sdk/edgeorder/azure-resourcemanager-edgeorder/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-edgeorder - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fedgeorder%2Fazure-resourcemanager-edgeorder%2FREADME.png) + diff --git a/sdk/edgeorder/azure-resourcemanager-edgeorder/pom.xml b/sdk/edgeorder/azure-resourcemanager-edgeorder/pom.xml index 14b9bbe642a7..72c92684e141 100644 --- a/sdk/edgeorder/azure-resourcemanager-edgeorder/pom.xml +++ b/sdk/edgeorder/azure-resourcemanager-edgeorder/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/edgezones/azure-resourcemanager-edgezones/README.md b/sdk/edgezones/azure-resourcemanager-edgezones/README.md index fb70eb504ee8..2176b4376ca6 100644 --- a/sdk/edgezones/azure-resourcemanager-edgezones/README.md +++ b/sdk/edgezones/azure-resourcemanager-edgezones/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-edgezones - 1.0.0-beta.2 + 1.0.0-beta.3 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fedgezones%2Fazure-resourcemanager-edgezones%2FREADME.png) + diff --git a/sdk/edgezones/azure-resourcemanager-edgezones/pom.xml b/sdk/edgezones/azure-resourcemanager-edgezones/pom.xml index 232ff4472038..eeb1537b9011 100644 --- a/sdk/edgezones/azure-resourcemanager-edgezones/pom.xml +++ b/sdk/edgezones/azure-resourcemanager-edgezones/pom.xml @@ -52,23 +52,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/education/azure-resourcemanager-education/README.md b/sdk/education/azure-resourcemanager-education/README.md index 87dd3240ae32..1584ec7d37ac 100644 --- a/sdk/education/azure-resourcemanager-education/README.md +++ b/sdk/education/azure-resourcemanager-education/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-education - 1.0.0-beta.4 + 1.0.0-beta.5 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Feducation%2Fazure-resourcemanager-education%2FREADME.png) + diff --git a/sdk/education/azure-resourcemanager-education/pom.xml b/sdk/education/azure-resourcemanager-education/pom.xml index 88afae041f55..fe799c5af734 100644 --- a/sdk/education/azure-resourcemanager-education/pom.xml +++ b/sdk/education/azure-resourcemanager-education/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/elastic/azure-resourcemanager-elastic/README.md b/sdk/elastic/azure-resourcemanager-elastic/README.md index 56d4ef06a66c..9a83f5c06c4d 100644 --- a/sdk/elastic/azure-resourcemanager-elastic/README.md +++ b/sdk/elastic/azure-resourcemanager-elastic/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-elastic - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Felastic%2Fazure-resourcemanager-elastic%2FREADME.png) + diff --git a/sdk/elastic/azure-resourcemanager-elastic/pom.xml b/sdk/elastic/azure-resourcemanager-elastic/pom.xml index 15b343766162..a553252e2403 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.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/elasticsan/azure-resourcemanager-elasticsan/README.md b/sdk/elasticsan/azure-resourcemanager-elasticsan/README.md index c8cd9be9e72c..2a39f034affc 100644 --- a/sdk/elasticsan/azure-resourcemanager-elasticsan/README.md +++ b/sdk/elasticsan/azure-resourcemanager-elasticsan/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-elasticsan - 1.2.0-beta.1 + 1.2.0-beta.2 ``` [//]: # ({x-version-update-end}) @@ -111,4 +111,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Felasticsan%2Fazure-resourcemanager-elasticsan%2FREADME.png) + diff --git a/sdk/elasticsan/azure-resourcemanager-elasticsan/pom.xml b/sdk/elasticsan/azure-resourcemanager-elasticsan/pom.xml index 11e42cc9c0a1..1f443fdbef2b 100644 --- a/sdk/elasticsan/azure-resourcemanager-elasticsan/pom.xml +++ b/sdk/elasticsan/azure-resourcemanager-elasticsan/pom.xml @@ -51,34 +51,34 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-json - 1.3.0 + 1.5.0 com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/eventgrid/azure-messaging-eventgrid-cloudnative-cloudevents/README.md b/sdk/eventgrid/azure-messaging-eventgrid-cloudnative-cloudevents/README.md index 3c662618c1a7..deac9069c242 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid-cloudnative-cloudevents/README.md +++ b/sdk/eventgrid/azure-messaging-eventgrid-cloudnative-cloudevents/README.md @@ -121,4 +121,4 @@ Contribution Guidelines for more information. [CNCFCloudEvents]: https://cloudevents.github.io/sdk-java/ [HttpResponseException]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/core/azure-core/src/main/java/com/azure/core/exception/HttpResponseException.java -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Feventgrid%2Fazure-messaging-eventgrid-cloudnative-cloudevents%2FREADME.png) + diff --git a/sdk/eventgrid/azure-messaging-eventgrid-cloudnative-cloudevents/pom.xml b/sdk/eventgrid/azure-messaging-eventgrid-cloudnative-cloudevents/pom.xml index 1a8f16b39010..e1f09bccbf8b 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid-cloudnative-cloudevents/pom.xml +++ b/sdk/eventgrid/azure-messaging-eventgrid-cloudnative-cloudevents/pom.xml @@ -87,17 +87,17 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-messaging-eventgrid - 4.28.0 + 4.30.0-beta.1 com.azure azure-identity - 1.15.0 + 1.15.4 test @@ -110,7 +110,7 @@ com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test diff --git a/sdk/eventgrid/azure-messaging-eventgrid-cloudnative-cloudevents/src/samples/README.md b/sdk/eventgrid/azure-messaging-eventgrid-cloudnative-cloudevents/src/samples/README.md index 46d7b9c6fddf..3dd7ad43b6f0 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid-cloudnative-cloudevents/src/samples/README.md +++ b/sdk/eventgrid/azure-messaging-eventgrid-cloudnative-cloudevents/src/samples/README.md @@ -50,4 +50,4 @@ Guidelines](https://github.com/Azure/azure-sdk-for-java/blob/main/CONTRIBUTING.m [sdk_readme_troubleshooting]: https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/eventgrid/azure-messaging-eventgrid#troubleshooting [sdk_readme_next_steps]: https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/eventgrid/azure-messaging-eventgrid#next-steps -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Feventgrid%2Fazure-messaging-eventgrid-cloudnative-cloudevents%2Fsamples%2FREADME.png) + diff --git a/sdk/eventgrid/azure-messaging-eventgrid-namespaces/CHANGELOG.md b/sdk/eventgrid/azure-messaging-eventgrid-namespaces/CHANGELOG.md index 61194b79eb39..4301a326cedc 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid-namespaces/CHANGELOG.md +++ b/sdk/eventgrid/azure-messaging-eventgrid-namespaces/CHANGELOG.md @@ -10,6 +10,17 @@ ### Other Changes +## 1.1.2 (2025-02-25) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`. +- Upgraded `azure-json` from `1.3.0` to version `1.4.0`. +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. + + ## 1.1.1 (2024-11-18) ### Other Changes diff --git a/sdk/eventgrid/azure-messaging-eventgrid-namespaces/README.md b/sdk/eventgrid/azure-messaging-eventgrid-namespaces/README.md index 33f5236f3907..af15e7ac5239 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid-namespaces/README.md +++ b/sdk/eventgrid/azure-messaging-eventgrid-namespaces/README.md @@ -28,7 +28,7 @@ Various documentation is available to help you get started com.azure azure-messaging-eventgrid-namespaces - 1.1.1 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -227,4 +227,4 @@ For details on contributing to this repository, see the [contributing guide](htt [portal]: https://ms.portal.azure.com/ [service_docs]: https://learn.microsoft.com/azure/event-grid/ [HttpResponseException]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/core/azure-core/src/main/java/com/azure/core/exception/HttpResponseException.java -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Feventgrid%2Fazure-messaging-eventgrid-namespaces%2FREADME.png) + diff --git a/sdk/eventgrid/azure-messaging-eventgrid-namespaces/pom.xml b/sdk/eventgrid/azure-messaging-eventgrid-namespaces/pom.xml index 83a7b2e30c28..1d10fdcb068a 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid-namespaces/pom.xml +++ b/sdk/eventgrid/azure-messaging-eventgrid-namespaces/pom.xml @@ -52,28 +52,28 @@ Code generated by Microsoft (R) TypeSpec Code Generator. com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/CHANGELOG.md b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/CHANGELOG.md new file mode 100644 index 000000000000..cdc7dd7eafaf --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/CHANGELOG.md @@ -0,0 +1,17 @@ +# Release History + +## 1.0.0-beta.2 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + +## 1.0.0-beta.1 (2025-02-26) + +### Features Added +- Azure SystemEvents client library for Java. This package contains Microsoft Azure SystemEvents client library. +- Initial beta release of azure-messaging-eventgrid-systemevents. diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/README.md b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/README.md new file mode 100644 index 000000000000..87f1e5edfd7b --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/README.md @@ -0,0 +1,78 @@ +# Azure SystemEvents client library for Java + +Azure SystemEvents client library for Java. + +This package contains Microsoft Azure SystemEvents client library. + +## Documentation + +Various documentation is available to help you get started + +- [API reference documentation][docs] +- [Product documentation][product_documentation] + +## Getting started + +### Prerequisites + +- [Java Development Kit (JDK)][jdk] with version 8 or above +- [Azure Subscription][azure_subscription] + +### Adding the package to your product + +[//]: # ({x-version-update-start;com.azure:azure-messaging-eventgrid-systemevents;current}) +```xml + + com.azure + azure-messaging-eventgrid-systemevents + 1.0.0-beta.2 + +``` +[//]: # ({x-version-update-end}) + +### Authentication + +[Azure Identity][azure_identity] package provides the default implementation for authenticating the client. + +## Key concepts + +### Examples + +-```java com.azure.messaging.eventgrid.readme +-``` + +### Service API versions + +The client library targets the latest service API version by default. +The service client builder accepts an optional service API version parameter to specify which API version to communicate. + +#### Select a service API version + +You have the flexibility to explicitly select a supported service API version when initializing a service client via the service client builder. +This ensures that the client can communicate with services using the specified API version. + +When selecting an API version, it is important to verify that there are no breaking changes compared to the latest API version. +If there are significant differences, API calls may fail due to incompatibility. + +Always ensure that the chosen API version is fully supported and operational for your specific use case and that it aligns with the service's versioning policy. + +## Troubleshooting + +## Next steps + +## Contributing + +For details on contributing to this repository, see the [contributing guide](https://github.com/Azure/azure-sdk-for-java/blob/main/CONTRIBUTING.md). + +1. Fork it +1. Create your feature branch (`git checkout -b my-new-feature`) +1. Commit your changes (`git commit -am 'Add some feature'`) +1. Push to the branch (`git push origin my-new-feature`) +1. Create new Pull Request + + +[product_documentation]: https://azure.microsoft.com/services/ +[docs]: https://azure.github.io/azure-sdk-for-java/ +[jdk]: https://learn.microsoft.com/azure/developer/java/fundamentals/ +[azure_subscription]: https://azure.microsoft.com/free/ +[azure_identity]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/identity/azure-identity diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/customization/pom.xml b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/customization/pom.xml new file mode 100644 index 000000000000..43a1f82d6169 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/customization/pom.xml @@ -0,0 +1,17 @@ + + + 4.0.0 + + + com.azure + azure-code-customization-parent + 1.0.0-beta.1 + ../../../parents/azure-code-customization-parent + + + azure-messaging-eventgrid-systemevents-customization + 1.0.0-beta.1 + jar + diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/customization/src/main/java/EventGridSystemEventsCustomization.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/customization/src/main/java/EventGridSystemEventsCustomization.java new file mode 100644 index 000000000000..bb6ce91e6aa0 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/customization/src/main/java/EventGridSystemEventsCustomization.java @@ -0,0 +1,289 @@ +// 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.Editor; +import com.azure.autorest.customization.LibraryCustomization; +import com.azure.autorest.customization.PackageCustomization; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.comments.Comment; +import com.github.javaparser.javadoc.Javadoc; +import com.github.javaparser.javadoc.description.JavadocDescription; +import com.github.javaparser.javadoc.description.JavadocSnippet; +import org.slf4j.Logger; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.stream.Collectors; + +import static com.github.javaparser.StaticJavaParser.parseBlock; + +/** + * This class contains the customization code to customize the AutoRest generated code for Event Grid. + */ +public class EventGridSystemEventsCustomization extends Customization { + private static final String newLine = System.lineSeparator(); + + private static final String SYSTEM_EVENT_CLASS_HEADER = "// Copyright (c) Microsoft Corporation. All rights reserved." + newLine + + "// Licensed under the MIT License." + newLine + newLine + + "package com.azure.messaging.eventgrid;" + newLine + newLine; + + private static final String CLASS_DEF = "/**" + newLine + + " * This class contains a number of constants that correspond to the value of {@code eventType} of {@code EventGridEvent}s" + newLine + + " * and {@code code} of {@code CloudEvent}s, when the event originated from an Azure service. This list should be" + newLine + + " * updated with all the service event strings. It also contains a mapping from each service event string to the" + newLine + + " * model class that the event string corresponds to in the {@code data} field, which is used to automatically deserialize" + newLine + + " * system events by their known string." + newLine + + " */" + newLine + + "public final class SystemEventNames {" + newLine; + + private static final String PRIVATE_CTOR = "/**" + newLine + + " * Get a mapping of all the system event type strings to their respective class. This is used by default in" + newLine + + " * the {@code EventGridEvent} and {@code CloudEvent} classes." + newLine + + " * @return a mapping of all the system event strings to system event objects." + newLine + + " */" + newLine + + " public static Map> getSystemEventMappings() {" + newLine + + " return Collections.unmodifiableMap(SYSTEM_EVENT_MAPPINGS);" + newLine + + " }" + newLine + + newLine + + " private SystemEventNames() { " + newLine + + " }"; + + @Override + public void customize(LibraryCustomization customization, Logger logger) { + customizeModuleInfo(customization, logger); + customizeAcsRouterEvents(customization, logger); + customizeAcsRecordingFileStatusUpdatedEventDataDuration(customization, logger); + customizeStorageDirectoryDeletedEventData(customization, logger); + customizeAcsMessageEventDataAndInheritingClasses(customization, logger); + generateSystemEventNames(customization, logger); + } + + + public void generateSystemEventNames(LibraryCustomization customization, Logger logger) { + + PackageCustomization packageCustomization = customization.getPackage("com.azure.messaging.eventgrid.systemevents"); + + List classCustomizations = customization.getPackage("com.azure.messaging.eventgrid.systemevents") + .listClasses(); + + Map nameMap = new TreeMap<>(); + Map classMap = new TreeMap<>(); + Map descriptionMap = new TreeMap<>(); + Map constantNameMap = new TreeMap<>(); + List imports = new ArrayList<>(); + StringBuilder sb = new StringBuilder(); + + logger.info("Total number of classes " + classCustomizations.size()); + + List eventData = classCustomizations + .stream() + .filter(classCustomization -> classCustomization.getClassName().endsWith("EventData")) + .collect(Collectors.toList()); + + List validEventDescription = eventData.stream() + .filter(classCustomization -> { + int startIndex = + classCustomization.getJavadoc().getDescription().indexOf("Microsoft."); + int endIndex = classCustomization.getJavadoc().getDescription().lastIndexOf(" event."); + boolean hasEventName = startIndex > 0 && endIndex > 0; + if (!hasEventName) { + logger.info("Class " + classCustomization.getClassName() + " " + classCustomization.getJavadoc().getDescription()); + } + return hasEventName; + }) + .map(classCustomization -> { + int startIndex = + classCustomization.getJavadoc().getDescription().indexOf("Microsoft."); + int endIndex = classCustomization.getJavadoc().getDescription().indexOf(" ", startIndex); + String eventName = classCustomization.getJavadoc().getDescription().substring(startIndex, endIndex); + String className = classCustomization.getClassName(); + String constantName = getConstantName(className.replace("EventData", "")); + + constantNameMap.put(className, constantName); + nameMap.put(className, eventName); + classMap.put(className, className + ".class"); + descriptionMap.put(className, classCustomization.getJavadoc().getDescription()); + imports.add(className); + return eventName; + }) + .collect(Collectors.toList()); + + Collections.sort(imports); + sb.append(SYSTEM_EVENT_CLASS_HEADER); + + Consumer appender = s -> { + sb.append(s); + sb.append(newLine); + }; + + appender.accept("import java.util.Collections;"); + appender.accept("import java.util.HashMap;"); + appender.accept("import java.util.Map;"); + // these two imports are for deprecated events. + appender.accept("import com.azure.messaging.eventgrid.systemevents.AcsChatMemberAddedToThreadWithUserEventData;"); + appender.accept("import com.azure.messaging.eventgrid.systemevents.AcsChatMemberRemovedFromThreadWithUserEventData;"); + for (String className : imports) { + appender.accept("import com.azure.messaging.eventgrid.systemevents." + className + ";"); + } + appender.accept(CLASS_DEF); + + for (String className : imports) { + appender.accept("/**"); + appender.accept("* " + descriptionMap.get(className)); + appender.accept("*/"); + appender.accept("public static final String " + constantNameMap.get(className) + " = \"" + nameMap.get(className) + "\";"); + appender.accept(""); + } + + appender.accept("private static final Map> SYSTEM_EVENT_MAPPINGS = new HashMap>() {{"); + + for (String className : imports) { + appender.accept("put(" + constantNameMap.get(className) + ", " + classMap.get(className) + ");"); + } + appender.accept("}};"); + + appender.accept(PRIVATE_CTOR); + + appender.accept("}"); + logger.info("Total number of events " + eventData.size()); + logger.info("Total number of events with proper description " + validEventDescription.size()); + + customization.getRawEditor() + .addFile("src/main/java/com/azure/messaging/eventgrid/SystemEventNames.java", sb.toString()); + + Editor editor = customization.getRawEditor(); + editor.addFile("src/main/java/com/azure/messaging/eventgrid/SystemEventNames.java", SYSTEM_EVENT_CLASS_HEADER + CLASS_DEF + PRIVATE_CTOR); + } + + + /** + * Customize the module-info.java file. This is necessary due to having a models subpackage logically; we + * end up with an export for a package with no types, so we remove the export. + * + * @param customization The LibraryCustomization object. + * @param logger The logger object. + */ + public void customizeModuleInfo(LibraryCustomization customization, Logger logger) { + + Editor editor = customization.getRawEditor(); + List lines = editor.getFileLines("src/main/java/module-info.java"); + StringBuilder sb = new StringBuilder(); + lines.forEach(line -> { + if (!line.trim().equals("exports com.azure.messaging.eventgrid;")) { + sb.append(line).append(newLine); + } + }); + editor.replaceFile("src/main/java/module-info.java", sb.toString()); + } + + public void customizeAcsRouterEvents(LibraryCustomization customization, Logger logger) { + PackageCustomization packageModels = customization.getPackage("com.azure.messaging.eventgrid.systemevents"); + ClassCustomization classCustomization = packageModels.getClass("AcsRouterWorkerSelector"); + + classCustomization.customizeAst(comp -> { + ClassOrInterfaceDeclaration clazz = comp.getClassByName("AcsRouterWorkerSelector").get(); + clazz.getMethodsByName("getTimeToLive").forEach(m -> { + m.setType(Duration.class); + m.setBody(parseBlock("{ return Duration.ofSeconds((long)timeToLive); }")); + }); + }); + + classCustomization = packageModels.getClass("AcsRouterJobClassificationFailedEventData"); + classCustomization.addImports("com.azure.core.models.ResponseError"); + classCustomization.addImports("java.util.stream.Collectors"); + classCustomization.customizeAst(comp -> { + ClassOrInterfaceDeclaration clazz = comp.getClassByName("AcsRouterJobClassificationFailedEventData").get(); + clazz.getMethodsByName("getErrors").forEach(m -> { + m.setType("List"); + m.setBody(parseBlock("{ return this.errors.stream().map(e -> new ResponseError(e.getCode(), e.getMessage())).collect(Collectors.toList()); }")); + }); + }); + } + + public void customizeAcsRecordingFileStatusUpdatedEventDataDuration(LibraryCustomization customization, Logger logger) { + PackageCustomization packageModels = customization.getPackage("com.azure.messaging.eventgrid.systemevents"); + ClassCustomization classCustomization = packageModels.getClass("AcsRecordingFileStatusUpdatedEventData"); + + classCustomization.customizeAst(ast -> { + ast.addImport("java.time.Duration"); + ClassOrInterfaceDeclaration clazz = ast.getClassByName("AcsRecordingFileStatusUpdatedEventData").get(); + clazz.getMethodsByName("getRecordingDuration").forEach(method -> { + method.setType("Duration"); + method.setBody(parseBlock("{ if (this.recordingDuration != null) { return Duration.ofMillis(this.recordingDuration); } return null; }")); + method.setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Get the recordingDuration property: The recording duration.")))) + .addBlockTag("return", "the recordingDuration value.")); + }); + + }); + } + + public void customizeStorageDirectoryDeletedEventData(LibraryCustomization customization, Logger logger) { + PackageCustomization packageModels = customization.getPackage("com.azure.messaging.eventgrid.systemevents"); + ClassCustomization classCustomization = packageModels.getClass("StorageDirectoryDeletedEventData"); + classCustomization.getMethod("getRecursive").rename("isRecursive").setReturnType("Boolean", "Boolean.getBoolean(%s)"); + } + + public void customizeAcsMessageEventDataAndInheritingClasses(LibraryCustomization customization, Logger logger) { + PackageCustomization packageModels = customization.getPackage("com.azure.messaging.eventgrid.systemevents"); + List classNames = Arrays.asList( + "AcsMessageEventData", + "AcsMessageDeliveryStatusUpdatedEventData", + "AcsMessageReceivedEventData" + ); + for (String className : classNames) { + ClassCustomization classCustomization = packageModels.getClass(className); + classCustomization.addImports("com.azure.core.models.ResponseError"); + classCustomization.customizeAst(comp -> { + ClassOrInterfaceDeclaration clazz = comp.getClassByName(className).get(); + // Fix up the getError method to always return a ResponseError. + clazz.getMethodsByName("getError").forEach(m -> { + m.setType("ResponseError") + .setBody(parseBlock("{ return new ResponseError(this.error.getChannelCode(), this.error.getChannelMessage()); }")) + .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Get the error property: The channel error code and message.")))) + .addBlockTag("return", "the error value.")); + }); + }); + } + } + + public static String getConstantName(String name) { + if (name == null || name.trim().isEmpty()) { + return name; + } + + // trim leading and trailing '_' + if ((name.startsWith("_") || name.endsWith("_")) && !name.chars().allMatch(c -> c == '_')) { + StringBuilder sb = new StringBuilder(name); + while (sb.length() > 0 && sb.charAt(0) == '_') { + sb.deleteCharAt(0); + } + while (sb.length() > 0 && sb.charAt(sb.length() - 1) == '_') { + sb.setLength(sb.length() - 1); + } + name = sb.toString(); + } + + String result = name; + result = result.replaceAll("_{2,}", "_"); // merge multiple underlines + Function isUpper = c -> c >= 'A' && c <= 'Z'; + Function isLower = c -> c >= 'a' && c <= 'z'; + for (int i = 1; i < result.length() - 1; i++) { + if (isUpper.apply(result.charAt(i))) { + if (result.charAt(i - 1) != '_' && isLower.apply(result.charAt(i - 1))) { + result = result.substring(0, i) + "_" + result.substring(i); + } + } + } + return result.toUpperCase(); + } + +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/pom.xml b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/pom.xml new file mode 100644 index 000000000000..317cccef7c24 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/pom.xml @@ -0,0 +1,115 @@ + + + 4.0.0 + + com.azure + azure-client-sdk-parent + 1.7.0 + ../../parents/azure-client-sdk-parent + + + com.azure + azure-messaging-eventgrid-systemevents + 1.0.0-beta.2 + jar + + Microsoft Azure SDK for System Events + This package contains Microsoft Azure System Events client library. + https://github.com/Azure/azure-sdk-for-java + + + + The MIT License (MIT) + http://opensource.org/licenses/MIT + repo + + + + + https://github.com/Azure/azure-sdk-for-java + scm:git:git@github.com:Azure/azure-sdk-for-java.git + scm:git:git@github.com:Azure/azure-sdk-for-java.git + HEAD + + + + microsoft + Microsoft + + + + UTF-8 + false + + + + com.azure + azure-core + 1.55.3 + + + com.azure + azure-core-http-netty + 1.15.11 + + + com.azure + azure-core-test + 1.27.0-beta.8 + test + + + com.azure + azure-identity + 1.15.4 + test + + + com.azure + azure-json + 1.5.0 + + + com.azure + azure-xml + 1.2.0 + + + org.junit.jupiter + junit-jupiter-api + 5.11.2 + test + + + org.junit.jupiter + junit-jupiter-engine + 5.11.2 + test + + + org.slf4j + slf4j-simple + 1.7.36 + test + + + + + + org.jacoco + jacoco-maven-plugin + 0.8.12 + + + com/azure/messaging/eventgrid/systemevents/** + com/azure/messaging/eventgrid/implementation/** + + + + + + diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/SystemEventNames.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/SystemEventNames.java new file mode 100644 index 000000000000..135184a930b7 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/SystemEventNames.java @@ -0,0 +1,1498 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.messaging.eventgrid; + +import com.azure.messaging.eventgrid.systemevents.AcsChatMessageDeletedEventData; +import com.azure.messaging.eventgrid.systemevents.AcsChatMessageDeletedInThreadEventData; +import com.azure.messaging.eventgrid.systemevents.AcsChatMessageEditedEventData; +import com.azure.messaging.eventgrid.systemevents.AcsChatMessageEditedInThreadEventData; +import com.azure.messaging.eventgrid.systemevents.AcsChatMessageReceivedEventData; +import com.azure.messaging.eventgrid.systemevents.AcsChatMessageReceivedInThreadEventData; +import com.azure.messaging.eventgrid.systemevents.AcsChatParticipantAddedToThreadEventData; +import com.azure.messaging.eventgrid.systemevents.AcsChatParticipantAddedToThreadWithUserEventData; +import com.azure.messaging.eventgrid.systemevents.AcsChatParticipantRemovedFromThreadEventData; +import com.azure.messaging.eventgrid.systemevents.AcsChatParticipantRemovedFromThreadWithUserEventData; +import com.azure.messaging.eventgrid.systemevents.AcsChatThreadCreatedEventData; +import com.azure.messaging.eventgrid.systemevents.AcsChatThreadCreatedWithUserEventData; +import com.azure.messaging.eventgrid.systemevents.AcsChatThreadDeletedEventData; +import com.azure.messaging.eventgrid.systemevents.AcsChatThreadPropertiesUpdatedEventData; +import com.azure.messaging.eventgrid.systemevents.AcsChatThreadPropertiesUpdatedPerUserEventData; +import com.azure.messaging.eventgrid.systemevents.AcsChatThreadWithUserDeletedEventData; +import com.azure.messaging.eventgrid.systemevents.AcsEmailDeliveryReportReceivedEventData; +import com.azure.messaging.eventgrid.systemevents.AcsEmailEngagementTrackingReportReceivedEventData; +import com.azure.messaging.eventgrid.systemevents.AcsIncomingCallEventData; +import com.azure.messaging.eventgrid.systemevents.AcsMessageDeliveryStatusUpdatedEventData; +import com.azure.messaging.eventgrid.systemevents.AcsMessageReceivedEventData; +import com.azure.messaging.eventgrid.systemevents.AcsRecordingFileStatusUpdatedEventData; +import com.azure.messaging.eventgrid.systemevents.AcsRouterJobCancelledEventData; +import com.azure.messaging.eventgrid.systemevents.AcsRouterJobClassificationFailedEventData; +import com.azure.messaging.eventgrid.systemevents.AcsRouterJobClassifiedEventData; +import com.azure.messaging.eventgrid.systemevents.AcsRouterJobClosedEventData; +import com.azure.messaging.eventgrid.systemevents.AcsRouterJobCompletedEventData; +import com.azure.messaging.eventgrid.systemevents.AcsRouterJobDeletedEventData; +import com.azure.messaging.eventgrid.systemevents.AcsRouterJobExceptionTriggeredEventData; +import com.azure.messaging.eventgrid.systemevents.AcsRouterJobQueuedEventData; +import com.azure.messaging.eventgrid.systemevents.AcsRouterJobReceivedEventData; +import com.azure.messaging.eventgrid.systemevents.AcsRouterJobSchedulingFailedEventData; +import com.azure.messaging.eventgrid.systemevents.AcsRouterJobUnassignedEventData; +import com.azure.messaging.eventgrid.systemevents.AcsRouterJobWaitingForActivationEventData; +import com.azure.messaging.eventgrid.systemevents.AcsRouterJobWorkerSelectorsExpiredEventData; +import com.azure.messaging.eventgrid.systemevents.AcsRouterWorkerDeletedEventData; +import com.azure.messaging.eventgrid.systemevents.AcsRouterWorkerDeregisteredEventData; +import com.azure.messaging.eventgrid.systemevents.AcsRouterWorkerOfferAcceptedEventData; +import com.azure.messaging.eventgrid.systemevents.AcsRouterWorkerOfferDeclinedEventData; +import com.azure.messaging.eventgrid.systemevents.AcsRouterWorkerOfferExpiredEventData; +import com.azure.messaging.eventgrid.systemevents.AcsRouterWorkerOfferIssuedEventData; +import com.azure.messaging.eventgrid.systemevents.AcsRouterWorkerOfferRevokedEventData; +import com.azure.messaging.eventgrid.systemevents.AcsRouterWorkerRegisteredEventData; +import com.azure.messaging.eventgrid.systemevents.AcsRouterWorkerUpdatedEventData; +import com.azure.messaging.eventgrid.systemevents.AcsSmsDeliveryReportReceivedEventData; +import com.azure.messaging.eventgrid.systemevents.AcsSmsReceivedEventData; +import com.azure.messaging.eventgrid.systemevents.AcsUserDisconnectedEventData; +import com.azure.messaging.eventgrid.systemevents.ApiCenterApiDefinitionAddedEventData; +import com.azure.messaging.eventgrid.systemevents.ApiCenterApiDefinitionUpdatedEventData; +import com.azure.messaging.eventgrid.systemevents.ApiManagementApiCreatedEventData; +import com.azure.messaging.eventgrid.systemevents.ApiManagementApiDeletedEventData; +import com.azure.messaging.eventgrid.systemevents.ApiManagementApiReleaseCreatedEventData; +import com.azure.messaging.eventgrid.systemevents.ApiManagementApiReleaseDeletedEventData; +import com.azure.messaging.eventgrid.systemevents.ApiManagementApiReleaseUpdatedEventData; +import com.azure.messaging.eventgrid.systemevents.ApiManagementApiUpdatedEventData; +import com.azure.messaging.eventgrid.systemevents.ApiManagementGatewayApiAddedEventData; +import com.azure.messaging.eventgrid.systemevents.ApiManagementGatewayApiRemovedEventData; +import com.azure.messaging.eventgrid.systemevents.ApiManagementGatewayCertificateAuthorityCreatedEventData; +import com.azure.messaging.eventgrid.systemevents.ApiManagementGatewayCertificateAuthorityDeletedEventData; +import com.azure.messaging.eventgrid.systemevents.ApiManagementGatewayCertificateAuthorityUpdatedEventData; +import com.azure.messaging.eventgrid.systemevents.ApiManagementGatewayCreatedEventData; +import com.azure.messaging.eventgrid.systemevents.ApiManagementGatewayDeletedEventData; +import com.azure.messaging.eventgrid.systemevents.ApiManagementGatewayHostnameConfigurationCreatedEventData; +import com.azure.messaging.eventgrid.systemevents.ApiManagementGatewayHostnameConfigurationDeletedEventData; +import com.azure.messaging.eventgrid.systemevents.ApiManagementGatewayHostnameConfigurationUpdatedEventData; +import com.azure.messaging.eventgrid.systemevents.ApiManagementGatewayUpdatedEventData; +import com.azure.messaging.eventgrid.systemevents.ApiManagementProductCreatedEventData; +import com.azure.messaging.eventgrid.systemevents.ApiManagementProductDeletedEventData; +import com.azure.messaging.eventgrid.systemevents.ApiManagementProductUpdatedEventData; +import com.azure.messaging.eventgrid.systemevents.ApiManagementSubscriptionCreatedEventData; +import com.azure.messaging.eventgrid.systemevents.ApiManagementSubscriptionDeletedEventData; +import com.azure.messaging.eventgrid.systemevents.ApiManagementSubscriptionUpdatedEventData; +import com.azure.messaging.eventgrid.systemevents.ApiManagementUserCreatedEventData; +import com.azure.messaging.eventgrid.systemevents.ApiManagementUserDeletedEventData; +import com.azure.messaging.eventgrid.systemevents.ApiManagementUserUpdatedEventData; +import com.azure.messaging.eventgrid.systemevents.AppConfigurationKeyValueDeletedEventData; +import com.azure.messaging.eventgrid.systemevents.AppConfigurationKeyValueModifiedEventData; +import com.azure.messaging.eventgrid.systemevents.AppConfigurationSnapshotCreatedEventData; +import com.azure.messaging.eventgrid.systemevents.AppConfigurationSnapshotModifiedEventData; +import com.azure.messaging.eventgrid.systemevents.AvsClusterCreatedEventData; +import com.azure.messaging.eventgrid.systemevents.AvsClusterDeletedEventData; +import com.azure.messaging.eventgrid.systemevents.AvsClusterFailedEventData; +import com.azure.messaging.eventgrid.systemevents.AvsClusterUpdatedEventData; +import com.azure.messaging.eventgrid.systemevents.AvsClusterUpdatingEventData; +import com.azure.messaging.eventgrid.systemevents.AvsPrivateCloudFailedEventData; +import com.azure.messaging.eventgrid.systemevents.AvsPrivateCloudUpdatedEventData; +import com.azure.messaging.eventgrid.systemevents.AvsPrivateCloudUpdatingEventData; +import com.azure.messaging.eventgrid.systemevents.AvsScriptExecutionCancelledEventData; +import com.azure.messaging.eventgrid.systemevents.AvsScriptExecutionFailedEventData; +import com.azure.messaging.eventgrid.systemevents.AvsScriptExecutionFinishedEventData; +import com.azure.messaging.eventgrid.systemevents.AvsScriptExecutionStartedEventData; +import com.azure.messaging.eventgrid.systemevents.ContainerRegistryChartDeletedEventData; +import com.azure.messaging.eventgrid.systemevents.ContainerRegistryChartPushedEventData; +import com.azure.messaging.eventgrid.systemevents.ContainerRegistryImageDeletedEventData; +import com.azure.messaging.eventgrid.systemevents.ContainerRegistryImagePushedEventData; +import com.azure.messaging.eventgrid.systemevents.ContainerServiceClusterSupportEndedEventData; +import com.azure.messaging.eventgrid.systemevents.ContainerServiceClusterSupportEndingEventData; +import com.azure.messaging.eventgrid.systemevents.ContainerServiceNewKubernetesVersionAvailableEventData; +import com.azure.messaging.eventgrid.systemevents.ContainerServiceNodePoolRollingFailedEventData; +import com.azure.messaging.eventgrid.systemevents.ContainerServiceNodePoolRollingStartedEventData; +import com.azure.messaging.eventgrid.systemevents.ContainerServiceNodePoolRollingSucceededEventData; +import com.azure.messaging.eventgrid.systemevents.DataBoxCopyCompletedEventData; +import com.azure.messaging.eventgrid.systemevents.DataBoxCopyStartedEventData; +import com.azure.messaging.eventgrid.systemevents.DataBoxOrderCompletedEventData; +import com.azure.messaging.eventgrid.systemevents.EventGridMqttClientCreatedOrUpdatedEventData; +import com.azure.messaging.eventgrid.systemevents.EventGridMqttClientDeletedEventData; +import com.azure.messaging.eventgrid.systemevents.EventGridMqttClientSessionConnectedEventData; +import com.azure.messaging.eventgrid.systemevents.EventGridMqttClientSessionDisconnectedEventData; +import com.azure.messaging.eventgrid.systemevents.EventHubCaptureFileCreatedEventData; +import com.azure.messaging.eventgrid.systemevents.HealthcareDicomImageCreatedEventData; +import com.azure.messaging.eventgrid.systemevents.HealthcareDicomImageDeletedEventData; +import com.azure.messaging.eventgrid.systemevents.HealthcareDicomImageUpdatedEventData; +import com.azure.messaging.eventgrid.systemevents.HealthcareFhirResourceCreatedEventData; +import com.azure.messaging.eventgrid.systemevents.HealthcareFhirResourceDeletedEventData; +import com.azure.messaging.eventgrid.systemevents.HealthcareFhirResourceUpdatedEventData; +import com.azure.messaging.eventgrid.systemevents.IotHubDeviceConnectedEventData; +import com.azure.messaging.eventgrid.systemevents.IotHubDeviceCreatedEventData; +import com.azure.messaging.eventgrid.systemevents.IotHubDeviceDeletedEventData; +import com.azure.messaging.eventgrid.systemevents.IotHubDeviceDisconnectedEventData; +import com.azure.messaging.eventgrid.systemevents.IotHubDeviceTelemetryEventData; +import com.azure.messaging.eventgrid.systemevents.KeyVaultAccessPolicyChangedEventData; +import com.azure.messaging.eventgrid.systemevents.KeyVaultCertificateExpiredEventData; +import com.azure.messaging.eventgrid.systemevents.KeyVaultCertificateNearExpiryEventData; +import com.azure.messaging.eventgrid.systemevents.KeyVaultCertificateNewVersionCreatedEventData; +import com.azure.messaging.eventgrid.systemevents.KeyVaultKeyExpiredEventData; +import com.azure.messaging.eventgrid.systemevents.KeyVaultKeyNearExpiryEventData; +import com.azure.messaging.eventgrid.systemevents.KeyVaultKeyNewVersionCreatedEventData; +import com.azure.messaging.eventgrid.systemevents.KeyVaultSecretExpiredEventData; +import com.azure.messaging.eventgrid.systemevents.KeyVaultSecretNearExpiryEventData; +import com.azure.messaging.eventgrid.systemevents.KeyVaultSecretNewVersionCreatedEventData; +import com.azure.messaging.eventgrid.systemevents.MachineLearningServicesDatasetDriftDetectedEventData; +import com.azure.messaging.eventgrid.systemevents.MachineLearningServicesModelDeployedEventData; +import com.azure.messaging.eventgrid.systemevents.MachineLearningServicesModelRegisteredEventData; +import com.azure.messaging.eventgrid.systemevents.MachineLearningServicesRunCompletedEventData; +import com.azure.messaging.eventgrid.systemevents.MachineLearningServicesRunStatusChangedEventData; +import com.azure.messaging.eventgrid.systemevents.MapsGeofenceEnteredEventData; +import com.azure.messaging.eventgrid.systemevents.MapsGeofenceExitedEventData; +import com.azure.messaging.eventgrid.systemevents.MapsGeofenceResultEventData; +import com.azure.messaging.eventgrid.systemevents.PolicyInsightsPolicyStateChangedEventData; +import com.azure.messaging.eventgrid.systemevents.PolicyInsightsPolicyStateCreatedEventData; +import com.azure.messaging.eventgrid.systemevents.PolicyInsightsPolicyStateDeletedEventData; +import com.azure.messaging.eventgrid.systemevents.RedisExportRdbCompletedEventData; +import com.azure.messaging.eventgrid.systemevents.RedisImportRdbCompletedEventData; +import com.azure.messaging.eventgrid.systemevents.RedisPatchingCompletedEventData; +import com.azure.messaging.eventgrid.systemevents.RedisScalingCompletedEventData; +import com.azure.messaging.eventgrid.systemevents.ResourceActionCancelEventData; +import com.azure.messaging.eventgrid.systemevents.ResourceActionFailureEventData; +import com.azure.messaging.eventgrid.systemevents.ResourceActionSuccessEventData; +import com.azure.messaging.eventgrid.systemevents.ResourceDeleteCancelEventData; +import com.azure.messaging.eventgrid.systemevents.ResourceDeleteFailureEventData; +import com.azure.messaging.eventgrid.systemevents.ResourceDeleteSuccessEventData; +import com.azure.messaging.eventgrid.systemevents.ResourceNotificationsContainerServiceEventResourcesScheduledEventData; +import com.azure.messaging.eventgrid.systemevents.ResourceNotificationsHealthResourcesAnnotatedEventData; +import com.azure.messaging.eventgrid.systemevents.ResourceNotificationsHealthResourcesAvailabilityStatusChangedEventData; +import com.azure.messaging.eventgrid.systemevents.ResourceNotificationsResourceManagementCreatedOrUpdatedEventData; +import com.azure.messaging.eventgrid.systemevents.ResourceNotificationsResourceManagementDeletedEventData; +import com.azure.messaging.eventgrid.systemevents.ResourceWriteCancelEventData; +import com.azure.messaging.eventgrid.systemevents.ResourceWriteFailureEventData; +import com.azure.messaging.eventgrid.systemevents.ResourceWriteSuccessEventData; +import com.azure.messaging.eventgrid.systemevents.ServiceBusActiveMessagesAvailablePeriodicNotificationsEventData; +import com.azure.messaging.eventgrid.systemevents.ServiceBusActiveMessagesAvailableWithNoListenersEventData; +import com.azure.messaging.eventgrid.systemevents.ServiceBusDeadletterMessagesAvailablePeriodicNotificationsEventData; +import com.azure.messaging.eventgrid.systemevents.ServiceBusDeadletterMessagesAvailableWithNoListenersEventData; +import com.azure.messaging.eventgrid.systemevents.SignalRServiceClientConnectionConnectedEventData; +import com.azure.messaging.eventgrid.systemevents.SignalRServiceClientConnectionDisconnectedEventData; +import com.azure.messaging.eventgrid.systemevents.StorageAsyncOperationInitiatedEventData; +import com.azure.messaging.eventgrid.systemevents.StorageBlobCreatedEventData; +import com.azure.messaging.eventgrid.systemevents.StorageBlobDeletedEventData; +import com.azure.messaging.eventgrid.systemevents.StorageBlobInventoryPolicyCompletedEventData; +import com.azure.messaging.eventgrid.systemevents.StorageBlobRenamedEventData; +import com.azure.messaging.eventgrid.systemevents.StorageBlobTierChangedEventData; +import com.azure.messaging.eventgrid.systemevents.StorageDirectoryCreatedEventData; +import com.azure.messaging.eventgrid.systemevents.StorageDirectoryDeletedEventData; +import com.azure.messaging.eventgrid.systemevents.StorageDirectoryRenamedEventData; +import com.azure.messaging.eventgrid.systemevents.StorageLifecyclePolicyCompletedEventData; +import com.azure.messaging.eventgrid.systemevents.StorageTaskAssignmentCompletedEventData; +import com.azure.messaging.eventgrid.systemevents.StorageTaskAssignmentQueuedEventData; +import com.azure.messaging.eventgrid.systemevents.StorageTaskCompletedEventData; +import com.azure.messaging.eventgrid.systemevents.StorageTaskQueuedEventData; +import com.azure.messaging.eventgrid.systemevents.SubscriptionDeletedEventData; +import com.azure.messaging.eventgrid.systemevents.SubscriptionValidationEventData; +import com.azure.messaging.eventgrid.systemevents.WebAppServicePlanUpdatedEventData; +import com.azure.messaging.eventgrid.systemevents.WebAppUpdatedEventData; +import com.azure.messaging.eventgrid.systemevents.WebBackupOperationCompletedEventData; +import com.azure.messaging.eventgrid.systemevents.WebBackupOperationFailedEventData; +import com.azure.messaging.eventgrid.systemevents.WebBackupOperationStartedEventData; +import com.azure.messaging.eventgrid.systemevents.WebRestoreOperationCompletedEventData; +import com.azure.messaging.eventgrid.systemevents.WebRestoreOperationFailedEventData; +import com.azure.messaging.eventgrid.systemevents.WebRestoreOperationStartedEventData; +import com.azure.messaging.eventgrid.systemevents.WebSlotSwapCompletedEventData; +import com.azure.messaging.eventgrid.systemevents.WebSlotSwapFailedEventData; +import com.azure.messaging.eventgrid.systemevents.WebSlotSwapStartedEventData; +import com.azure.messaging.eventgrid.systemevents.WebSlotSwapWithPreviewCancelledEventData; +import com.azure.messaging.eventgrid.systemevents.WebSlotSwapWithPreviewStartedEventData; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +/** + * This class contains a number of constants that correspond to the value of {@code eventType} of + * {@code EventGridEvent}s + * and {@code code} of {@code CloudEvent}s, when the event originated from an Azure service. This list should be + * updated with all the service event strings. It also contains a mapping from each service event string to the + * model class that the event string corresponds to in the {@code data} field, which is used to automatically + * deserialize + * system events by their known string. + */ +public final class SystemEventNames { + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatMessageDeleted event. + */ + public static final String ACS_CHAT_MESSAGE_DELETED = "Microsoft.Communication.ChatMessageDeleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatMessageDeletedInThread event. + */ + public static final String ACS_CHAT_MESSAGE_DELETED_IN_THREAD + = "Microsoft.Communication.ChatMessageDeletedInThread"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatMessageEdited event. + */ + public static final String ACS_CHAT_MESSAGE_EDITED = "Microsoft.Communication.ChatMessageEdited"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatMessageEditedInThread event. + */ + public static final String ACS_CHAT_MESSAGE_EDITED_IN_THREAD = "Microsoft.Communication.ChatMessageEditedInThread"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatMessageReceived event. + */ + public static final String ACS_CHAT_MESSAGE_RECEIVED = "Microsoft.Communication.ChatMessageReceived"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatMessageReceivedInThread event. + */ + public static final String ACS_CHAT_MESSAGE_RECEIVED_IN_THREAD + = "Microsoft.Communication.ChatMessageReceivedInThread"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatThreadParticipantAdded event. + */ + public static final String ACS_CHAT_PARTICIPANT_ADDED_TO_THREAD + = "Microsoft.Communication.ChatThreadParticipantAdded"; + + /** + * Schema of the Data property of an EventGridEvent for a + * Microsoft.Communication.ChatParticipantAddedToThreadWithUser event. + */ + public static final String ACS_CHAT_PARTICIPANT_ADDED_TO_THREAD_WITH_USER + = "Microsoft.Communication.ChatParticipantAddedToThreadWithUser"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatThreadParticipantRemoved + * event. + */ + public static final String ACS_CHAT_PARTICIPANT_REMOVED_FROM_THREAD + = "Microsoft.Communication.ChatThreadParticipantRemoved"; + + /** + * Schema of the Data property of an EventGridEvent for a + * Microsoft.Communication.ChatParticipantRemovedFromThreadWithUser event. + */ + public static final String ACS_CHAT_PARTICIPANT_REMOVED_FROM_THREAD_WITH_USER + = "Microsoft.Communication.ChatParticipantRemovedFromThreadWithUser"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatThreadCreated event. + */ + public static final String ACS_CHAT_THREAD_CREATED = "Microsoft.Communication.ChatThreadCreated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatThreadCreatedWithUser event. + */ + public static final String ACS_CHAT_THREAD_CREATED_WITH_USER = "Microsoft.Communication.ChatThreadCreatedWithUser"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatThreadDeleted event. + */ + public static final String ACS_CHAT_THREAD_DELETED = "Microsoft.Communication.ChatThreadDeleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatThreadPropertiesUpdated event. + */ + public static final String ACS_CHAT_THREAD_PROPERTIES_UPDATED + = "Microsoft.Communication.ChatThreadPropertiesUpdated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatThreadPropertiesUpdatedPerUser + * event. + */ + public static final String ACS_CHAT_THREAD_PROPERTIES_UPDATED_PER_USER + = "Microsoft.Communication.ChatThreadPropertiesUpdatedPerUser"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatThreadWithUserDeleted event. + */ + public static final String ACS_CHAT_THREAD_WITH_USER_DELETED = "Microsoft.Communication.ChatThreadWithUserDeleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.EmailDeliveryReportReceived event. + */ + public static final String ACS_EMAIL_DELIVERY_REPORT_RECEIVED + = "Microsoft.Communication.EmailDeliveryReportReceived"; + + /** + * Schema of the Data property of an EventGridEvent for a + * Microsoft.Communication.EmailEngagementTrackingReportReceived event. + */ + public static final String ACS_EMAIL_ENGAGEMENT_TRACKING_REPORT_RECEIVED + = "Microsoft.Communication.EmailEngagementTrackingReportReceived"; + + /** + * Schema of the Data property of an EventGridEvent for an Microsoft.Communication.IncomingCall event. + */ + public static final String ACS_INCOMING_CALL = "Microsoft.Communication.IncomingCall"; + + /** + * Schema of the Data property of an EventGridEvent for a + * Microsoft.Communication.AdvancedMessageDeliveryStatusUpdated event. + */ + public static final String ACS_MESSAGE_DELIVERY_STATUS_UPDATED + = "Microsoft.Communication.AdvancedMessageDeliveryStatusUpdated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.AdvancedMessageReceived event. + */ + public static final String ACS_MESSAGE_RECEIVED = "Microsoft.Communication.AdvancedMessageReceived"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RecordingFileStatusUpdated event. + */ + public static final String ACS_RECORDING_FILE_STATUS_UPDATED = "Microsoft.Communication.RecordingFileStatusUpdated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobCancelled event. + */ + public static final String ACS_ROUTER_JOB_CANCELLED = "Microsoft.Communication.RouterJobCancelled"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobClassificationFailed + * event. + */ + public static final String ACS_ROUTER_JOB_CLASSIFICATION_FAILED + = "Microsoft.Communication.RouterJobClassificationFailed"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobClassified event. + */ + public static final String ACS_ROUTER_JOB_CLASSIFIED = "Microsoft.Communication.RouterJobClassified"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobClosed event. + */ + public static final String ACS_ROUTER_JOB_CLOSED = "Microsoft.Communication.RouterJobClosed"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobCompleted event. + */ + public static final String ACS_ROUTER_JOB_COMPLETED = "Microsoft.Communication.RouterJobCompleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobDeleted event. + */ + public static final String ACS_ROUTER_JOB_DELETED = "Microsoft.Communication.RouterJobDeleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobExceptionTriggered event. + */ + public static final String ACS_ROUTER_JOB_EXCEPTION_TRIGGERED + = "Microsoft.Communication.RouterJobExceptionTriggered"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobQueued event. + */ + public static final String ACS_ROUTER_JOB_QUEUED = "Microsoft.Communication.RouterJobQueued"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobReceived event. + */ + public static final String ACS_ROUTER_JOB_RECEIVED = "Microsoft.Communication.RouterJobReceived"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobSchedulingFailed event. + */ + public static final String ACS_ROUTER_JOB_SCHEDULING_FAILED = "Microsoft.Communication.RouterJobSchedulingFailed"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobUnassigned event. + */ + public static final String ACS_ROUTER_JOB_UNASSIGNED = "Microsoft.Communication.RouterJobUnassigned"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobWaitingForActivation + * event. + */ + public static final String ACS_ROUTER_JOB_WAITING_FOR_ACTIVATION + = "Microsoft.Communication.RouterJobWaitingForActivation"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobWorkerSelectorsExpired + * event. + */ + public static final String ACS_ROUTER_JOB_WORKER_SELECTORS_EXPIRED + = "Microsoft.Communication.RouterJobWorkerSelectorsExpired"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterWorkerDeleted event. + */ + public static final String ACS_ROUTER_WORKER_DELETED = "Microsoft.Communication.RouterWorkerDeleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterWorkerDeregistered event. + */ + public static final String ACS_ROUTER_WORKER_DEREGISTERED = "Microsoft.Communication.RouterWorkerDeregistered"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterWorkerOfferAccepted event. + */ + public static final String ACS_ROUTER_WORKER_OFFER_ACCEPTED = "Microsoft.Communication.RouterWorkerOfferAccepted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterWorkerOfferDeclined event. + */ + public static final String ACS_ROUTER_WORKER_OFFER_DECLINED = "Microsoft.Communication.RouterWorkerOfferDeclined"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterWorkerOfferExpired event. + */ + public static final String ACS_ROUTER_WORKER_OFFER_EXPIRED = "Microsoft.Communication.RouterWorkerOfferExpired"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterWorkerOfferIssued event. + */ + public static final String ACS_ROUTER_WORKER_OFFER_ISSUED = "Microsoft.Communication.RouterWorkerOfferIssued"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterWorkerOfferRevoked event. + */ + public static final String ACS_ROUTER_WORKER_OFFER_REVOKED = "Microsoft.Communication.RouterWorkerOfferRevoked"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterWorkerRegistered event. + */ + public static final String ACS_ROUTER_WORKER_REGISTERED = "Microsoft.Communication.RouterWorkerRegistered"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterWorkerUpdated event. + */ + public static final String ACS_ROUTER_WORKER_UPDATED = "Microsoft.Communication.RouterWorkerUpdated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.SMSDeliveryReportReceived event. + */ + public static final String ACS_SMS_DELIVERY_REPORT_RECEIVED = "Microsoft.Communication.SMSDeliveryReportReceived"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.SMSReceived event. + */ + public static final String ACS_SMS_RECEIVED = "Microsoft.Communication.SMSReceived"; + + /** + * Schema of the Data property of an EventGridEvent for an Microsoft.Communication.UserDisconnected event. + */ + public static final String ACS_USER_DISCONNECTED = "Microsoft.Communication.UserDisconnected"; + + /** + * Schema of the data property of an EventGridEvent for a Microsoft.ApiCenter.ApiDefinitionAdded event. + */ + public static final String API_CENTER_API_DEFINITION_ADDED = "Microsoft.ApiCenter.ApiDefinitionAdded"; + + /** + * Schema of the data property of an EventGridEvent for a Microsoft.ApiCenter.ApiDefinitionUpdated event. + */ + public static final String API_CENTER_API_DEFINITION_UPDATED = "Microsoft.ApiCenter.ApiDefinitionUpdated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.APICreated event. + */ + public static final String API_MANAGEMENT_API_CREATED = "Microsoft.ApiManagement.APICreated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.APIDeleted event. + */ + public static final String API_MANAGEMENT_API_DELETED = "Microsoft.ApiManagement.APIDeleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.APIReleaseCreated event. + */ + public static final String API_MANAGEMENT_API_RELEASE_CREATED = "Microsoft.ApiManagement.APIReleaseCreated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.APIReleaseDeleted event. + */ + public static final String API_MANAGEMENT_API_RELEASE_DELETED = "Microsoft.ApiManagement.APIReleaseDeleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.APIReleaseUpdated event. + */ + public static final String API_MANAGEMENT_API_RELEASE_UPDATED = "Microsoft.ApiManagement.APIReleaseUpdated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.APIUpdated event. + */ + public static final String API_MANAGEMENT_API_UPDATED = "Microsoft.ApiManagement.APIUpdated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.GatewayAPIAdded event. + */ + public static final String API_MANAGEMENT_GATEWAY_API_ADDED = "Microsoft.ApiManagement.GatewayAPIAdded"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.GatewayAPIRemoved event. + */ + public static final String API_MANAGEMENT_GATEWAY_API_REMOVED = "Microsoft.ApiManagement.GatewayAPIRemoved"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.GatewayCertificateAuthorityCreated + * event. + */ + public static final String API_MANAGEMENT_GATEWAY_CERTIFICATE_AUTHORITY_CREATED + = "Microsoft.ApiManagement.GatewayCertificateAuthorityCreated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.GatewayCertificateAuthorityDeleted + * event. + */ + public static final String API_MANAGEMENT_GATEWAY_CERTIFICATE_AUTHORITY_DELETED + = "Microsoft.ApiManagement.GatewayCertificateAuthorityDeleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.GatewayCertificateAuthorityUpdated + * event. + */ + public static final String API_MANAGEMENT_GATEWAY_CERTIFICATE_AUTHORITY_UPDATED + = "Microsoft.ApiManagement.GatewayCertificateAuthorityUpdated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.GatewayCreated event. + */ + public static final String API_MANAGEMENT_GATEWAY_CREATED = "Microsoft.ApiManagement.GatewayCreated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.GatewayDeleted event. + */ + public static final String API_MANAGEMENT_GATEWAY_DELETED = "Microsoft.ApiManagement.GatewayDeleted"; + + /** + * Schema of the Data property of an EventGridEvent for a + * Microsoft.ApiManagement.GatewayHostnameConfigurationCreated event. + */ + public static final String API_MANAGEMENT_GATEWAY_HOSTNAME_CONFIGURATION_CREATED + = "Microsoft.ApiManagement.GatewayHostnameConfigurationCreated"; + + /** + * Schema of the Data property of an EventGridEvent for a + * Microsoft.ApiManagement.GatewayHostnameConfigurationDeleted event. + */ + public static final String API_MANAGEMENT_GATEWAY_HOSTNAME_CONFIGURATION_DELETED + = "Microsoft.ApiManagement.GatewayHostnameConfigurationDeleted"; + + /** + * Schema of the Data property of an EventGridEvent for a + * Microsoft.ApiManagement.GatewayHostnameConfigurationUpdated event. + */ + public static final String API_MANAGEMENT_GATEWAY_HOSTNAME_CONFIGURATION_UPDATED + = "Microsoft.ApiManagement.GatewayHostnameConfigurationUpdated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.GatewayUpdated event. + */ + public static final String API_MANAGEMENT_GATEWAY_UPDATED = "Microsoft.ApiManagement.GatewayUpdated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.ProductCreated event. + */ + public static final String API_MANAGEMENT_PRODUCT_CREATED = "Microsoft.ApiManagement.ProductCreated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.ProductDeleted event. + */ + public static final String API_MANAGEMENT_PRODUCT_DELETED = "Microsoft.ApiManagement.ProductDeleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.ProductUpdated event. + */ + public static final String API_MANAGEMENT_PRODUCT_UPDATED = "Microsoft.ApiManagement.ProductUpdated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.SubscriptionCreated event. + */ + public static final String API_MANAGEMENT_SUBSCRIPTION_CREATED = "Microsoft.ApiManagement.SubscriptionCreated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.SubscriptionDeleted event. + */ + public static final String API_MANAGEMENT_SUBSCRIPTION_DELETED = "Microsoft.ApiManagement.SubscriptionDeleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.SubscriptionUpdated event. + */ + public static final String API_MANAGEMENT_SUBSCRIPTION_UPDATED = "Microsoft.ApiManagement.SubscriptionUpdated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.UserCreated event. + */ + public static final String API_MANAGEMENT_USER_CREATED = "Microsoft.ApiManagement.UserCreated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.UserDeleted event. + */ + public static final String API_MANAGEMENT_USER_DELETED = "Microsoft.ApiManagement.UserDeleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.UserUpdated event. + */ + public static final String API_MANAGEMENT_USER_UPDATED = "Microsoft.ApiManagement.UserUpdated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.AppConfiguration.KeyValueDeleted event. + */ + public static final String APP_CONFIGURATION_KEY_VALUE_DELETED = "Microsoft.AppConfiguration.KeyValueDeleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.AppConfiguration.KeyValueModified event. + */ + public static final String APP_CONFIGURATION_KEY_VALUE_MODIFIED = "Microsoft.AppConfiguration.KeyValueModified"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.AppConfiguration.SnapshotCreated event. + */ + public static final String APP_CONFIGURATION_SNAPSHOT_CREATED = "Microsoft.AppConfiguration.SnapshotCreated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.AppConfiguration.SnapshotModified event. + */ + public static final String APP_CONFIGURATION_SNAPSHOT_MODIFIED = "Microsoft.AppConfiguration.SnapshotModified"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.AVS.ClusterCreated event. + */ + public static final String AVS_CLUSTER_CREATED = "Microsoft.AVS.ClusterCreated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.AVS.ClusterDeleted event. + */ + public static final String AVS_CLUSTER_DELETED = "Microsoft.AVS.ClusterDeleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.AVS.ClusterFailed event. + */ + public static final String AVS_CLUSTER_FAILED = "Microsoft.AVS.ClusterFailed"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.AVS.ClusterUpdated event. + */ + public static final String AVS_CLUSTER_UPDATED = "Microsoft.AVS.ClusterUpdated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.AVS.ClusterUpdating event. + */ + public static final String AVS_CLUSTER_UPDATING = "Microsoft.AVS.ClusterUpdating"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.AVS.PrivateCloudFailed event. + */ + public static final String AVS_PRIVATE_CLOUD_FAILED = "Microsoft.AVS.PrivateCloudFailed"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.AVS.PrivateCloudUpdated event. + */ + public static final String AVS_PRIVATE_CLOUD_UPDATED = "Microsoft.AVS.PrivateCloudUpdated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.AVS.PrivateCloudUpdating event. + */ + public static final String AVS_PRIVATE_CLOUD_UPDATING = "Microsoft.AVS.PrivateCloudUpdating"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.AVS.ScriptExecutionCancelled event. + */ + public static final String AVS_SCRIPT_EXECUTION_CANCELLED = "Microsoft.AVS.ScriptExecutionCancelled"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.AVS.ScriptExecutionFailed event. + */ + public static final String AVS_SCRIPT_EXECUTION_FAILED = "Microsoft.AVS.ScriptExecutionFailed"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.AVS.ScriptExecutionFinished event. + */ + public static final String AVS_SCRIPT_EXECUTION_FINISHED = "Microsoft.AVS.ScriptExecutionFinished"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.AVS.ScriptExecutionStarted event. + */ + public static final String AVS_SCRIPT_EXECUTION_STARTED = "Microsoft.AVS.ScriptExecutionStarted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ContainerRegistry.ChartDeleted event. + */ + public static final String CONTAINER_REGISTRY_CHART_DELETED = "Microsoft.ContainerRegistry.ChartDeleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ContainerRegistry.ChartPushed event. + */ + public static final String CONTAINER_REGISTRY_CHART_PUSHED = "Microsoft.ContainerRegistry.ChartPushed"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ContainerRegistry.ImageDeleted event. + */ + public static final String CONTAINER_REGISTRY_IMAGE_DELETED = "Microsoft.ContainerRegistry.ImageDeleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ContainerRegistry.ImagePushed event. + */ + public static final String CONTAINER_REGISTRY_IMAGE_PUSHED = "Microsoft.ContainerRegistry.ImagePushed"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ContainerService.ClusterSupportEnded event. + */ + public static final String CONTAINER_SERVICE_CLUSTER_SUPPORT_ENDED + = "Microsoft.ContainerService.ClusterSupportEnded"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ContainerService.ClusterSupportEnding event. + */ + public static final String CONTAINER_SERVICE_CLUSTER_SUPPORT_ENDING + = "Microsoft.ContainerService.ClusterSupportEnding"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ContainerService.NewKubernetesVersionAvailable + * event. + */ + public static final String CONTAINER_SERVICE_NEW_KUBERNETES_VERSION_AVAILABLE + = "Microsoft.ContainerService.NewKubernetesVersionAvailable"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ContainerService.NodePoolRollingFailed event. + */ + public static final String CONTAINER_SERVICE_NODE_POOL_ROLLING_FAILED + = "Microsoft.ContainerService.NodePoolRollingFailed"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ContainerService.NodePoolRollingStarted event. + */ + public static final String CONTAINER_SERVICE_NODE_POOL_ROLLING_STARTED + = "Microsoft.ContainerService.NodePoolRollingStarted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ContainerService.NodePoolRollingSucceeded event. + */ + public static final String CONTAINER_SERVICE_NODE_POOL_ROLLING_SUCCEEDED + = "Microsoft.ContainerService.NodePoolRollingSucceeded"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.DataBox.CopyCompleted event. + */ + public static final String DATA_BOX_COPY_COMPLETED = "Microsoft.DataBox.CopyCompleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.DataBox.CopyStarted event. + */ + public static final String DATA_BOX_COPY_STARTED = "Microsoft.DataBox.CopyStarted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.DataBox.OrderCompleted event. + */ + public static final String DATA_BOX_ORDER_COMPLETED = "Microsoft.DataBox.OrderCompleted"; + + /** + * Event data for Microsoft.EventGrid.MQTTClientCreatedOrUpdated event. + */ + public static final String EVENT_GRID_MQTT_CLIENT_CREATED_OR_UPDATED + = "Microsoft.EventGrid.MQTTClientCreatedOrUpdated"; + + /** + * Event data for Microsoft.EventGrid.MQTTClientDeleted event. + */ + public static final String EVENT_GRID_MQTT_CLIENT_DELETED = "Microsoft.EventGrid.MQTTClientDeleted"; + + /** + * Event data for Microsoft.EventGrid.MQTTClientSessionConnected event. + */ + public static final String EVENT_GRID_MQTT_CLIENT_SESSION_CONNECTED + = "Microsoft.EventGrid.MQTTClientSessionConnected"; + + /** + * Event data for Microsoft.EventGrid.MQTTClientSessionDisconnected event. + */ + public static final String EVENT_GRID_MQTT_CLIENT_SESSION_DISCONNECTED + = "Microsoft.EventGrid.MQTTClientSessionDisconnected"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.EventHub.CaptureFileCreated event. + */ + public static final String EVENT_HUB_CAPTURE_FILE_CREATED = "Microsoft.EventHub.CaptureFileCreated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.HealthcareApis.DicomImageCreated event. + */ + public static final String HEALTHCARE_DICOM_IMAGE_CREATED = "Microsoft.HealthcareApis.DicomImageCreated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.HealthcareApis.DicomImageDeleted event. + */ + public static final String HEALTHCARE_DICOM_IMAGE_DELETED = "Microsoft.HealthcareApis.DicomImageDeleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.HealthcareApis.DicomImageUpdated event. + */ + public static final String HEALTHCARE_DICOM_IMAGE_UPDATED = "Microsoft.HealthcareApis.DicomImageUpdated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.HealthcareApis.FhirResourceCreated event. + */ + public static final String HEALTHCARE_FHIR_RESOURCE_CREATED = "Microsoft.HealthcareApis.FhirResourceCreated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.HealthcareApis.FhirResourceDeleted event. + */ + public static final String HEALTHCARE_FHIR_RESOURCE_DELETED = "Microsoft.HealthcareApis.FhirResourceDeleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.HealthcareApis.FhirResourceUpdated event. + */ + public static final String HEALTHCARE_FHIR_RESOURCE_UPDATED = "Microsoft.HealthcareApis.FhirResourceUpdated"; + + /** + * Event data for Microsoft.Devices.DeviceConnected event. + */ + public static final String IOT_HUB_DEVICE_CONNECTED = "Microsoft.Devices.DeviceConnected"; + + /** + * Event data for Microsoft.Devices.DeviceCreated event. + */ + public static final String IOT_HUB_DEVICE_CREATED = "Microsoft.Devices.DeviceCreated"; + + /** + * Event data for Microsoft.Devices.DeviceDeleted event. + */ + public static final String IOT_HUB_DEVICE_DELETED = "Microsoft.Devices.DeviceDeleted"; + + /** + * Event data for Microsoft.Devices.DeviceDisconnected event. + */ + public static final String IOT_HUB_DEVICE_DISCONNECTED = "Microsoft.Devices.DeviceDisconnected"; + + /** + * Event data for Microsoft.Devices.DeviceTelemetry event. + */ + public static final String IOT_HUB_DEVICE_TELEMETRY = "Microsoft.Devices.DeviceTelemetry"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.VaultAccessPolicyChanged event. + */ + public static final String KEY_VAULT_ACCESS_POLICY_CHANGED = "Microsoft.KeyVault.VaultAccessPolicyChanged"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.CertificateExpired event. + */ + public static final String KEY_VAULT_CERTIFICATE_EXPIRED = "Microsoft.KeyVault.CertificateExpired"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.CertificateNearExpiry event. + */ + public static final String KEY_VAULT_CERTIFICATE_NEAR_EXPIRY = "Microsoft.KeyVault.CertificateNearExpiry"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.CertificateNewVersionCreated event. + */ + public static final String KEY_VAULT_CERTIFICATE_NEW_VERSION_CREATED + = "Microsoft.KeyVault.CertificateNewVersionCreated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.KeyExpired event. + */ + public static final String KEY_VAULT_KEY_EXPIRED = "Microsoft.KeyVault.KeyExpired"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.KeyNearExpiry event. + */ + public static final String KEY_VAULT_KEY_NEAR_EXPIRY = "Microsoft.KeyVault.KeyNearExpiry"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.KeyNewVersionCreated event. + */ + public static final String KEY_VAULT_KEY_NEW_VERSION_CREATED = "Microsoft.KeyVault.KeyNewVersionCreated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.SecretExpired event. + */ + public static final String KEY_VAULT_SECRET_EXPIRED = "Microsoft.KeyVault.SecretExpired"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.SecretNearExpiry event. + */ + public static final String KEY_VAULT_SECRET_NEAR_EXPIRY = "Microsoft.KeyVault.SecretNearExpiry"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.SecretNewVersionCreated event. + */ + public static final String KEY_VAULT_SECRET_NEW_VERSION_CREATED = "Microsoft.KeyVault.SecretNewVersionCreated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.MachineLearningServices.DatasetDriftDetected + * event. + */ + public static final String MACHINE_LEARNING_SERVICES_DATASET_DRIFT_DETECTED + = "Microsoft.MachineLearningServices.DatasetDriftDetected"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.MachineLearningServices.ModelDeployed event. + */ + public static final String MACHINE_LEARNING_SERVICES_MODEL_DEPLOYED + = "Microsoft.MachineLearningServices.ModelDeployed"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.MachineLearningServices.ModelRegistered event. + */ + public static final String MACHINE_LEARNING_SERVICES_MODEL_REGISTERED + = "Microsoft.MachineLearningServices.ModelRegistered"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.MachineLearningServices.RunCompleted event. + */ + public static final String MACHINE_LEARNING_SERVICES_RUN_COMPLETED + = "Microsoft.MachineLearningServices.RunCompleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.MachineLearningServices.RunStatusChanged event. + */ + public static final String MACHINE_LEARNING_SERVICES_RUN_STATUS_CHANGED + = "Microsoft.MachineLearningServices.RunStatusChanged"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Maps.GeofenceEntered event. + */ + public static final String MAPS_GEOFENCE_ENTERED = "Microsoft.Maps.GeofenceEntered"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Maps.GeofenceExited event. + */ + public static final String MAPS_GEOFENCE_EXITED = "Microsoft.Maps.GeofenceExited"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Maps.GeofenceResult event. + */ + public static final String MAPS_GEOFENCE_RESULT = "Microsoft.Maps.GeofenceResult"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.PolicyInsights.PolicyStateChanged event. + */ + public static final String POLICY_INSIGHTS_POLICY_STATE_CHANGED = "Microsoft.PolicyInsights.PolicyStateChanged"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.PolicyInsights.PolicyStateCreated event. + */ + public static final String POLICY_INSIGHTS_POLICY_STATE_CREATED = "Microsoft.PolicyInsights.PolicyStateCreated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.PolicyInsights.PolicyStateDeleted event. + */ + public static final String POLICY_INSIGHTS_POLICY_STATE_DELETED = "Microsoft.PolicyInsights.PolicyStateDeleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Cache.ExportRDBCompleted event. + */ + public static final String REDIS_EXPORT_RDB_COMPLETED = "Microsoft.Cache.ExportRDBCompleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Cache.ImportRDBCompleted event. + */ + public static final String REDIS_IMPORT_RDB_COMPLETED = "Microsoft.Cache.ImportRDBCompleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Cache.PatchingCompleted event. + */ + public static final String REDIS_PATCHING_COMPLETED = "Microsoft.Cache.PatchingCompleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Cache.ScalingCompleted event. + */ + public static final String REDIS_SCALING_COMPLETED = "Microsoft.Cache.ScalingCompleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Resources.ResourceActionCancel event. This is + * raised when a resource action operation is canceled. + */ + public static final String RESOURCE_ACTION_CANCEL = "Microsoft.Resources.ResourceActionCancel"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Resources.ResourceActionFailure event. This is + * raised when a resource action operation fails. + */ + public static final String RESOURCE_ACTION_FAILURE = "Microsoft.Resources.ResourceActionFailure"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Resources.ResourceActionSuccess event. This is + * raised when a resource action operation succeeds. + */ + public static final String RESOURCE_ACTION_SUCCESS = "Microsoft.Resources.ResourceActionSuccess"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Resources.ResourceDeleteCancel event. This is + * raised when a resource delete operation is canceled. + */ + public static final String RESOURCE_DELETE_CANCEL = "Microsoft.Resources.ResourceDeleteCancel"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Resources.ResourceDeleteFailure event. This is + * raised when a resource delete operation fails. + */ + public static final String RESOURCE_DELETE_FAILURE = "Microsoft.Resources.ResourceDeleteFailure"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Resources.ResourceDeleteSuccess event. This is + * raised when a resource delete operation succeeds. + */ + public static final String RESOURCE_DELETE_SUCCESS = "Microsoft.Resources.ResourceDeleteSuccess"; + + /** + * Schema of the Data property of an event grid event for a + * Microsoft.ResourceNotifications.ContainerServiceEventResources.ScheduledEventEmitted preview event. + */ + public static final String RESOURCE_NOTIFICATIONS_CONTAINER_SERVICE_EVENT_RESOURCES_SCHEDULED + = "Microsoft.ResourceNotifications.ContainerServiceEventResources.ScheduledEventEmitted"; + + /** + * Schema of the Data property of an EventGridEvent for a + * Microsoft.ResourceNotifications.HealthResources.ResourceAnnotated event. + */ + public static final String RESOURCE_NOTIFICATIONS_HEALTH_RESOURCES_ANNOTATED + = "Microsoft.ResourceNotifications.HealthResources.ResourceAnnotated"; + + /** + * Schema of the Data property of an EventGridEvent for a + * Microsoft.ResourceNotifications.HealthResources.AvailabilityStatusChanged event. + */ + public static final String RESOURCE_NOTIFICATIONS_HEALTH_RESOURCES_AVAILABILITY_STATUS_CHANGED + = "Microsoft.ResourceNotifications.HealthResources.AvailabilityStatusChanged"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ResourceNotifications.Resources.CreatedOrUpdated + * event. + */ + public static final String RESOURCE_NOTIFICATIONS_RESOURCE_MANAGEMENT_CREATED_OR_UPDATED + = "Microsoft.ResourceNotifications.Resources.CreatedOrUpdated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.ResourceNotifications.Resources.Deleted event. + */ + public static final String RESOURCE_NOTIFICATIONS_RESOURCE_MANAGEMENT_DELETED + = "Microsoft.ResourceNotifications.Resources.Deleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Resources.ResourceWriteCancel event. This is + * raised when a resource create or update operation is canceled. + */ + public static final String RESOURCE_WRITE_CANCEL = "Microsoft.Resources.ResourceWriteCancel"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Resources.ResourceWriteFailure event. This is + * raised when a resource create or update operation fails. + */ + public static final String RESOURCE_WRITE_FAILURE = "Microsoft.Resources.ResourceWriteFailure"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Resources.ResourceWriteSuccess event. This is + * raised when a resource create or update operation succeeds. + */ + public static final String RESOURCE_WRITE_SUCCESS = "Microsoft.Resources.ResourceWriteSuccess"; + + /** + * Schema of the Data property of an EventGridEvent for a + * Microsoft.ServiceBus.ActiveMessagesAvailablePeriodicNotifications event. + */ + public static final String SERVICE_BUS_ACTIVE_MESSAGES_AVAILABLE_PERIODIC_NOTIFICATIONS + = "Microsoft.ServiceBus.ActiveMessagesAvailablePeriodicNotifications"; + + /** + * Schema of the Data property of an EventGridEvent for a + * Microsoft.ServiceBus.ActiveMessagesAvailableWithNoListeners event. + */ + public static final String SERVICE_BUS_ACTIVE_MESSAGES_AVAILABLE_WITH_NO_LISTENERS + = "Microsoft.ServiceBus.ActiveMessagesAvailableWithNoListeners"; + + /** + * Schema of the Data property of an EventGridEvent for a + * Microsoft.ServiceBus.DeadletterMessagesAvailablePeriodicNotifications event. + */ + public static final String SERVICE_BUS_DEADLETTER_MESSAGES_AVAILABLE_PERIODIC_NOTIFICATIONS + = "Microsoft.ServiceBus.DeadletterMessagesAvailablePeriodicNotifications"; + + /** + * Schema of the Data property of an EventGridEvent for a + * Microsoft.ServiceBus.DeadletterMessagesAvailableWithNoListeners event. + */ + public static final String SERVICE_BUS_DEADLETTER_MESSAGES_AVAILABLE_WITH_NO_LISTENERS + = "Microsoft.ServiceBus.DeadletterMessagesAvailableWithNoListeners"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.SignalRService.ClientConnectionConnected event. + */ + public static final String SIGNAL_RSERVICE_CLIENT_CONNECTION_CONNECTED + = "Microsoft.SignalRService.ClientConnectionConnected"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.SignalRService.ClientConnectionDisconnected + * event. + */ + public static final String SIGNAL_RSERVICE_CLIENT_CONNECTION_DISCONNECTED + = "Microsoft.SignalRService.ClientConnectionDisconnected"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Storage.AsyncOperationInitiated event. + */ + public static final String STORAGE_ASYNC_OPERATION_INITIATED = "Microsoft.Storage.AsyncOperationInitiated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Storage.BlobCreated event. + */ + public static final String STORAGE_BLOB_CREATED = "Microsoft.Storage.BlobCreated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Storage.BlobDeleted event. + */ + public static final String STORAGE_BLOB_DELETED = "Microsoft.Storage.BlobDeleted"; + + /** + * Schema of the Data property of an EventGridEvent for an Microsoft.Storage.BlobInventoryPolicyCompleted event. + */ + public static final String STORAGE_BLOB_INVENTORY_POLICY_COMPLETED + = "Microsoft.Storage.BlobInventoryPolicyCompleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Storage.BlobRenamed event. + */ + public static final String STORAGE_BLOB_RENAMED = "Microsoft.Storage.BlobRenamed"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Storage.BlobTierChanged event. + */ + public static final String STORAGE_BLOB_TIER_CHANGED = "Microsoft.Storage.BlobTierChanged"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Storage.DirectoryCreated event. + */ + public static final String STORAGE_DIRECTORY_CREATED = "Microsoft.Storage.DirectoryCreated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Storage.DirectoryDeleted event. + */ + public static final String STORAGE_DIRECTORY_DELETED = "Microsoft.Storage.DirectoryDeleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Storage.DirectoryRenamed event. + */ + public static final String STORAGE_DIRECTORY_RENAMED = "Microsoft.Storage.DirectoryRenamed"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Storage.LifecyclePolicyCompleted event. + */ + public static final String STORAGE_LIFECYCLE_POLICY_COMPLETED = "Microsoft.Storage.LifecyclePolicyCompleted"; + + /** + * Schema of the Data property of an EventGridEvent for an Microsoft.Storage.StorageTaskAssignmentCompleted event. + */ + public static final String STORAGE_TASK_ASSIGNMENT_COMPLETED = "Microsoft.Storage.StorageTaskAssignmentCompleted"; + + /** + * Schema of the Data property of an EventGridEvent for an Microsoft.Storage.StorageTaskAssignmentQueued event. + */ + public static final String STORAGE_TASK_ASSIGNMENT_QUEUED = "Microsoft.Storage.StorageTaskAssignmentQueued"; + + /** + * Schema of the Data property of an EventGridEvent for an Microsoft.Storage.StorageTaskCompleted event. + */ + public static final String STORAGE_TASK_COMPLETED = "Microsoft.Storage.StorageTaskCompleted"; + + /** + * Schema of the Data property of an EventGridEvent for an Microsoft.Storage.StorageTaskQueued event. + */ + public static final String STORAGE_TASK_QUEUED = "Microsoft.Storage.StorageTaskQueued"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.EventGrid.SubscriptionDeletedEvent event. + */ + public static final String SUBSCRIPTION_DELETED = "Microsoft.EventGrid.SubscriptionDeletedEvent"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.EventGrid.SubscriptionValidationEvent event. + */ + public static final String SUBSCRIPTION_VALIDATION = "Microsoft.EventGrid.SubscriptionValidationEvent"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Web.AppServicePlanUpdated event. + */ + public static final String WEB_APP_SERVICE_PLAN_UPDATED = "Microsoft.Web.AppServicePlanUpdated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Web.AppUpdated event. + */ + public static final String WEB_APP_UPDATED = "Microsoft.Web.AppUpdated"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Web.BackupOperationCompleted event. + */ + public static final String WEB_BACKUP_OPERATION_COMPLETED = "Microsoft.Web.BackupOperationCompleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Web.BackupOperationFailed event. + */ + public static final String WEB_BACKUP_OPERATION_FAILED = "Microsoft.Web.BackupOperationFailed"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Web.BackupOperationStarted event. + */ + public static final String WEB_BACKUP_OPERATION_STARTED = "Microsoft.Web.BackupOperationStarted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Web.RestoreOperationCompleted event. + */ + public static final String WEB_RESTORE_OPERATION_COMPLETED = "Microsoft.Web.RestoreOperationCompleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Web.RestoreOperationFailed event. + */ + public static final String WEB_RESTORE_OPERATION_FAILED = "Microsoft.Web.RestoreOperationFailed"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Web.RestoreOperationStarted event. + */ + public static final String WEB_RESTORE_OPERATION_STARTED = "Microsoft.Web.RestoreOperationStarted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Web.SlotSwapCompleted event. + */ + public static final String WEB_SLOT_SWAP_COMPLETED = "Microsoft.Web.SlotSwapCompleted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Web.SlotSwapFailed event. + */ + public static final String WEB_SLOT_SWAP_FAILED = "Microsoft.Web.SlotSwapFailed"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Web.SlotSwapStarted event. + */ + public static final String WEB_SLOT_SWAP_STARTED = "Microsoft.Web.SlotSwapStarted"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Web.SlotSwapWithPreviewCancelled event. + */ + public static final String WEB_SLOT_SWAP_WITH_PREVIEW_CANCELLED = "Microsoft.Web.SlotSwapWithPreviewCancelled"; + + /** + * Schema of the Data property of an EventGridEvent for a Microsoft.Web.SlotSwapWithPreviewStarted event. + */ + public static final String WEB_SLOT_SWAP_WITH_PREVIEW_STARTED = "Microsoft.Web.SlotSwapWithPreviewStarted"; + + private static final Map> SYSTEM_EVENT_MAPPINGS = new HashMap>() { + { + put(ACS_CHAT_MESSAGE_DELETED, AcsChatMessageDeletedEventData.class); + put(ACS_CHAT_MESSAGE_DELETED_IN_THREAD, AcsChatMessageDeletedInThreadEventData.class); + put(ACS_CHAT_MESSAGE_EDITED, AcsChatMessageEditedEventData.class); + put(ACS_CHAT_MESSAGE_EDITED_IN_THREAD, AcsChatMessageEditedInThreadEventData.class); + put(ACS_CHAT_MESSAGE_RECEIVED, AcsChatMessageReceivedEventData.class); + put(ACS_CHAT_MESSAGE_RECEIVED_IN_THREAD, AcsChatMessageReceivedInThreadEventData.class); + put(ACS_CHAT_PARTICIPANT_ADDED_TO_THREAD, AcsChatParticipantAddedToThreadEventData.class); + put(ACS_CHAT_PARTICIPANT_ADDED_TO_THREAD_WITH_USER, AcsChatParticipantAddedToThreadWithUserEventData.class); + put(ACS_CHAT_PARTICIPANT_REMOVED_FROM_THREAD, AcsChatParticipantRemovedFromThreadEventData.class); + put(ACS_CHAT_PARTICIPANT_REMOVED_FROM_THREAD_WITH_USER, + AcsChatParticipantRemovedFromThreadWithUserEventData.class); + put(ACS_CHAT_THREAD_CREATED, AcsChatThreadCreatedEventData.class); + put(ACS_CHAT_THREAD_CREATED_WITH_USER, AcsChatThreadCreatedWithUserEventData.class); + put(ACS_CHAT_THREAD_DELETED, AcsChatThreadDeletedEventData.class); + put(ACS_CHAT_THREAD_PROPERTIES_UPDATED, AcsChatThreadPropertiesUpdatedEventData.class); + put(ACS_CHAT_THREAD_PROPERTIES_UPDATED_PER_USER, AcsChatThreadPropertiesUpdatedPerUserEventData.class); + put(ACS_CHAT_THREAD_WITH_USER_DELETED, AcsChatThreadWithUserDeletedEventData.class); + put(ACS_EMAIL_DELIVERY_REPORT_RECEIVED, AcsEmailDeliveryReportReceivedEventData.class); + put(ACS_EMAIL_ENGAGEMENT_TRACKING_REPORT_RECEIVED, AcsEmailEngagementTrackingReportReceivedEventData.class); + put(ACS_INCOMING_CALL, AcsIncomingCallEventData.class); + put(ACS_MESSAGE_DELIVERY_STATUS_UPDATED, AcsMessageDeliveryStatusUpdatedEventData.class); + put(ACS_MESSAGE_RECEIVED, AcsMessageReceivedEventData.class); + put(ACS_RECORDING_FILE_STATUS_UPDATED, AcsRecordingFileStatusUpdatedEventData.class); + put(ACS_ROUTER_JOB_CANCELLED, AcsRouterJobCancelledEventData.class); + put(ACS_ROUTER_JOB_CLASSIFICATION_FAILED, AcsRouterJobClassificationFailedEventData.class); + put(ACS_ROUTER_JOB_CLASSIFIED, AcsRouterJobClassifiedEventData.class); + put(ACS_ROUTER_JOB_CLOSED, AcsRouterJobClosedEventData.class); + put(ACS_ROUTER_JOB_COMPLETED, AcsRouterJobCompletedEventData.class); + put(ACS_ROUTER_JOB_DELETED, AcsRouterJobDeletedEventData.class); + put(ACS_ROUTER_JOB_EXCEPTION_TRIGGERED, AcsRouterJobExceptionTriggeredEventData.class); + put(ACS_ROUTER_JOB_QUEUED, AcsRouterJobQueuedEventData.class); + put(ACS_ROUTER_JOB_RECEIVED, AcsRouterJobReceivedEventData.class); + put(ACS_ROUTER_JOB_SCHEDULING_FAILED, AcsRouterJobSchedulingFailedEventData.class); + put(ACS_ROUTER_JOB_UNASSIGNED, AcsRouterJobUnassignedEventData.class); + put(ACS_ROUTER_JOB_WAITING_FOR_ACTIVATION, AcsRouterJobWaitingForActivationEventData.class); + put(ACS_ROUTER_JOB_WORKER_SELECTORS_EXPIRED, AcsRouterJobWorkerSelectorsExpiredEventData.class); + put(ACS_ROUTER_WORKER_DELETED, AcsRouterWorkerDeletedEventData.class); + put(ACS_ROUTER_WORKER_DEREGISTERED, AcsRouterWorkerDeregisteredEventData.class); + put(ACS_ROUTER_WORKER_OFFER_ACCEPTED, AcsRouterWorkerOfferAcceptedEventData.class); + put(ACS_ROUTER_WORKER_OFFER_DECLINED, AcsRouterWorkerOfferDeclinedEventData.class); + put(ACS_ROUTER_WORKER_OFFER_EXPIRED, AcsRouterWorkerOfferExpiredEventData.class); + put(ACS_ROUTER_WORKER_OFFER_ISSUED, AcsRouterWorkerOfferIssuedEventData.class); + put(ACS_ROUTER_WORKER_OFFER_REVOKED, AcsRouterWorkerOfferRevokedEventData.class); + put(ACS_ROUTER_WORKER_REGISTERED, AcsRouterWorkerRegisteredEventData.class); + put(ACS_ROUTER_WORKER_UPDATED, AcsRouterWorkerUpdatedEventData.class); + put(ACS_SMS_DELIVERY_REPORT_RECEIVED, AcsSmsDeliveryReportReceivedEventData.class); + put(ACS_SMS_RECEIVED, AcsSmsReceivedEventData.class); + put(ACS_USER_DISCONNECTED, AcsUserDisconnectedEventData.class); + put(API_CENTER_API_DEFINITION_ADDED, ApiCenterApiDefinitionAddedEventData.class); + put(API_CENTER_API_DEFINITION_UPDATED, ApiCenterApiDefinitionUpdatedEventData.class); + put(API_MANAGEMENT_API_CREATED, ApiManagementApiCreatedEventData.class); + put(API_MANAGEMENT_API_DELETED, ApiManagementApiDeletedEventData.class); + put(API_MANAGEMENT_API_RELEASE_CREATED, ApiManagementApiReleaseCreatedEventData.class); + put(API_MANAGEMENT_API_RELEASE_DELETED, ApiManagementApiReleaseDeletedEventData.class); + put(API_MANAGEMENT_API_RELEASE_UPDATED, ApiManagementApiReleaseUpdatedEventData.class); + put(API_MANAGEMENT_API_UPDATED, ApiManagementApiUpdatedEventData.class); + put(API_MANAGEMENT_GATEWAY_API_ADDED, ApiManagementGatewayApiAddedEventData.class); + put(API_MANAGEMENT_GATEWAY_API_REMOVED, ApiManagementGatewayApiRemovedEventData.class); + put(API_MANAGEMENT_GATEWAY_CERTIFICATE_AUTHORITY_CREATED, + ApiManagementGatewayCertificateAuthorityCreatedEventData.class); + put(API_MANAGEMENT_GATEWAY_CERTIFICATE_AUTHORITY_DELETED, + ApiManagementGatewayCertificateAuthorityDeletedEventData.class); + put(API_MANAGEMENT_GATEWAY_CERTIFICATE_AUTHORITY_UPDATED, + ApiManagementGatewayCertificateAuthorityUpdatedEventData.class); + put(API_MANAGEMENT_GATEWAY_CREATED, ApiManagementGatewayCreatedEventData.class); + put(API_MANAGEMENT_GATEWAY_DELETED, ApiManagementGatewayDeletedEventData.class); + put(API_MANAGEMENT_GATEWAY_HOSTNAME_CONFIGURATION_CREATED, + ApiManagementGatewayHostnameConfigurationCreatedEventData.class); + put(API_MANAGEMENT_GATEWAY_HOSTNAME_CONFIGURATION_DELETED, + ApiManagementGatewayHostnameConfigurationDeletedEventData.class); + put(API_MANAGEMENT_GATEWAY_HOSTNAME_CONFIGURATION_UPDATED, + ApiManagementGatewayHostnameConfigurationUpdatedEventData.class); + put(API_MANAGEMENT_GATEWAY_UPDATED, ApiManagementGatewayUpdatedEventData.class); + put(API_MANAGEMENT_PRODUCT_CREATED, ApiManagementProductCreatedEventData.class); + put(API_MANAGEMENT_PRODUCT_DELETED, ApiManagementProductDeletedEventData.class); + put(API_MANAGEMENT_PRODUCT_UPDATED, ApiManagementProductUpdatedEventData.class); + put(API_MANAGEMENT_SUBSCRIPTION_CREATED, ApiManagementSubscriptionCreatedEventData.class); + put(API_MANAGEMENT_SUBSCRIPTION_DELETED, ApiManagementSubscriptionDeletedEventData.class); + put(API_MANAGEMENT_SUBSCRIPTION_UPDATED, ApiManagementSubscriptionUpdatedEventData.class); + put(API_MANAGEMENT_USER_CREATED, ApiManagementUserCreatedEventData.class); + put(API_MANAGEMENT_USER_DELETED, ApiManagementUserDeletedEventData.class); + put(API_MANAGEMENT_USER_UPDATED, ApiManagementUserUpdatedEventData.class); + put(APP_CONFIGURATION_KEY_VALUE_DELETED, AppConfigurationKeyValueDeletedEventData.class); + put(APP_CONFIGURATION_KEY_VALUE_MODIFIED, AppConfigurationKeyValueModifiedEventData.class); + put(APP_CONFIGURATION_SNAPSHOT_CREATED, AppConfigurationSnapshotCreatedEventData.class); + put(APP_CONFIGURATION_SNAPSHOT_MODIFIED, AppConfigurationSnapshotModifiedEventData.class); + put(AVS_CLUSTER_CREATED, AvsClusterCreatedEventData.class); + put(AVS_CLUSTER_DELETED, AvsClusterDeletedEventData.class); + put(AVS_CLUSTER_FAILED, AvsClusterFailedEventData.class); + put(AVS_CLUSTER_UPDATED, AvsClusterUpdatedEventData.class); + put(AVS_CLUSTER_UPDATING, AvsClusterUpdatingEventData.class); + put(AVS_PRIVATE_CLOUD_FAILED, AvsPrivateCloudFailedEventData.class); + put(AVS_PRIVATE_CLOUD_UPDATED, AvsPrivateCloudUpdatedEventData.class); + put(AVS_PRIVATE_CLOUD_UPDATING, AvsPrivateCloudUpdatingEventData.class); + put(AVS_SCRIPT_EXECUTION_CANCELLED, AvsScriptExecutionCancelledEventData.class); + put(AVS_SCRIPT_EXECUTION_FAILED, AvsScriptExecutionFailedEventData.class); + put(AVS_SCRIPT_EXECUTION_FINISHED, AvsScriptExecutionFinishedEventData.class); + put(AVS_SCRIPT_EXECUTION_STARTED, AvsScriptExecutionStartedEventData.class); + put(CONTAINER_REGISTRY_CHART_DELETED, ContainerRegistryChartDeletedEventData.class); + put(CONTAINER_REGISTRY_CHART_PUSHED, ContainerRegistryChartPushedEventData.class); + put(CONTAINER_REGISTRY_IMAGE_DELETED, ContainerRegistryImageDeletedEventData.class); + put(CONTAINER_REGISTRY_IMAGE_PUSHED, ContainerRegistryImagePushedEventData.class); + put(CONTAINER_SERVICE_CLUSTER_SUPPORT_ENDED, ContainerServiceClusterSupportEndedEventData.class); + put(CONTAINER_SERVICE_CLUSTER_SUPPORT_ENDING, ContainerServiceClusterSupportEndingEventData.class); + put(CONTAINER_SERVICE_NEW_KUBERNETES_VERSION_AVAILABLE, + ContainerServiceNewKubernetesVersionAvailableEventData.class); + put(CONTAINER_SERVICE_NODE_POOL_ROLLING_FAILED, ContainerServiceNodePoolRollingFailedEventData.class); + put(CONTAINER_SERVICE_NODE_POOL_ROLLING_STARTED, ContainerServiceNodePoolRollingStartedEventData.class); + put(CONTAINER_SERVICE_NODE_POOL_ROLLING_SUCCEEDED, ContainerServiceNodePoolRollingSucceededEventData.class); + put(DATA_BOX_COPY_COMPLETED, DataBoxCopyCompletedEventData.class); + put(DATA_BOX_COPY_STARTED, DataBoxCopyStartedEventData.class); + put(DATA_BOX_ORDER_COMPLETED, DataBoxOrderCompletedEventData.class); + put(EVENT_GRID_MQTT_CLIENT_CREATED_OR_UPDATED, EventGridMqttClientCreatedOrUpdatedEventData.class); + put(EVENT_GRID_MQTT_CLIENT_DELETED, EventGridMqttClientDeletedEventData.class); + put(EVENT_GRID_MQTT_CLIENT_SESSION_CONNECTED, EventGridMqttClientSessionConnectedEventData.class); + put(EVENT_GRID_MQTT_CLIENT_SESSION_DISCONNECTED, EventGridMqttClientSessionDisconnectedEventData.class); + put(EVENT_HUB_CAPTURE_FILE_CREATED, EventHubCaptureFileCreatedEventData.class); + put(HEALTHCARE_DICOM_IMAGE_CREATED, HealthcareDicomImageCreatedEventData.class); + put(HEALTHCARE_DICOM_IMAGE_DELETED, HealthcareDicomImageDeletedEventData.class); + put(HEALTHCARE_DICOM_IMAGE_UPDATED, HealthcareDicomImageUpdatedEventData.class); + put(HEALTHCARE_FHIR_RESOURCE_CREATED, HealthcareFhirResourceCreatedEventData.class); + put(HEALTHCARE_FHIR_RESOURCE_DELETED, HealthcareFhirResourceDeletedEventData.class); + put(HEALTHCARE_FHIR_RESOURCE_UPDATED, HealthcareFhirResourceUpdatedEventData.class); + put(IOT_HUB_DEVICE_CONNECTED, IotHubDeviceConnectedEventData.class); + put(IOT_HUB_DEVICE_CREATED, IotHubDeviceCreatedEventData.class); + put(IOT_HUB_DEVICE_DELETED, IotHubDeviceDeletedEventData.class); + put(IOT_HUB_DEVICE_DISCONNECTED, IotHubDeviceDisconnectedEventData.class); + put(IOT_HUB_DEVICE_TELEMETRY, IotHubDeviceTelemetryEventData.class); + put(KEY_VAULT_ACCESS_POLICY_CHANGED, KeyVaultAccessPolicyChangedEventData.class); + put(KEY_VAULT_CERTIFICATE_EXPIRED, KeyVaultCertificateExpiredEventData.class); + put(KEY_VAULT_CERTIFICATE_NEAR_EXPIRY, KeyVaultCertificateNearExpiryEventData.class); + put(KEY_VAULT_CERTIFICATE_NEW_VERSION_CREATED, KeyVaultCertificateNewVersionCreatedEventData.class); + put(KEY_VAULT_KEY_EXPIRED, KeyVaultKeyExpiredEventData.class); + put(KEY_VAULT_KEY_NEAR_EXPIRY, KeyVaultKeyNearExpiryEventData.class); + put(KEY_VAULT_KEY_NEW_VERSION_CREATED, KeyVaultKeyNewVersionCreatedEventData.class); + put(KEY_VAULT_SECRET_EXPIRED, KeyVaultSecretExpiredEventData.class); + put(KEY_VAULT_SECRET_NEAR_EXPIRY, KeyVaultSecretNearExpiryEventData.class); + put(KEY_VAULT_SECRET_NEW_VERSION_CREATED, KeyVaultSecretNewVersionCreatedEventData.class); + put(MACHINE_LEARNING_SERVICES_DATASET_DRIFT_DETECTED, + MachineLearningServicesDatasetDriftDetectedEventData.class); + put(MACHINE_LEARNING_SERVICES_MODEL_DEPLOYED, MachineLearningServicesModelDeployedEventData.class); + put(MACHINE_LEARNING_SERVICES_MODEL_REGISTERED, MachineLearningServicesModelRegisteredEventData.class); + put(MACHINE_LEARNING_SERVICES_RUN_COMPLETED, MachineLearningServicesRunCompletedEventData.class); + put(MACHINE_LEARNING_SERVICES_RUN_STATUS_CHANGED, MachineLearningServicesRunStatusChangedEventData.class); + put(MAPS_GEOFENCE_ENTERED, MapsGeofenceEnteredEventData.class); + put(MAPS_GEOFENCE_EXITED, MapsGeofenceExitedEventData.class); + put(MAPS_GEOFENCE_RESULT, MapsGeofenceResultEventData.class); + put(POLICY_INSIGHTS_POLICY_STATE_CHANGED, PolicyInsightsPolicyStateChangedEventData.class); + put(POLICY_INSIGHTS_POLICY_STATE_CREATED, PolicyInsightsPolicyStateCreatedEventData.class); + put(POLICY_INSIGHTS_POLICY_STATE_DELETED, PolicyInsightsPolicyStateDeletedEventData.class); + put(REDIS_EXPORT_RDB_COMPLETED, RedisExportRdbCompletedEventData.class); + put(REDIS_IMPORT_RDB_COMPLETED, RedisImportRdbCompletedEventData.class); + put(REDIS_PATCHING_COMPLETED, RedisPatchingCompletedEventData.class); + put(REDIS_SCALING_COMPLETED, RedisScalingCompletedEventData.class); + put(RESOURCE_ACTION_CANCEL, ResourceActionCancelEventData.class); + put(RESOURCE_ACTION_FAILURE, ResourceActionFailureEventData.class); + put(RESOURCE_ACTION_SUCCESS, ResourceActionSuccessEventData.class); + put(RESOURCE_DELETE_CANCEL, ResourceDeleteCancelEventData.class); + put(RESOURCE_DELETE_FAILURE, ResourceDeleteFailureEventData.class); + put(RESOURCE_DELETE_SUCCESS, ResourceDeleteSuccessEventData.class); + put(RESOURCE_NOTIFICATIONS_CONTAINER_SERVICE_EVENT_RESOURCES_SCHEDULED, + ResourceNotificationsContainerServiceEventResourcesScheduledEventData.class); + put(RESOURCE_NOTIFICATIONS_HEALTH_RESOURCES_ANNOTATED, + ResourceNotificationsHealthResourcesAnnotatedEventData.class); + put(RESOURCE_NOTIFICATIONS_HEALTH_RESOURCES_AVAILABILITY_STATUS_CHANGED, + ResourceNotificationsHealthResourcesAvailabilityStatusChangedEventData.class); + put(RESOURCE_NOTIFICATIONS_RESOURCE_MANAGEMENT_CREATED_OR_UPDATED, + ResourceNotificationsResourceManagementCreatedOrUpdatedEventData.class); + put(RESOURCE_NOTIFICATIONS_RESOURCE_MANAGEMENT_DELETED, + ResourceNotificationsResourceManagementDeletedEventData.class); + put(RESOURCE_WRITE_CANCEL, ResourceWriteCancelEventData.class); + put(RESOURCE_WRITE_FAILURE, ResourceWriteFailureEventData.class); + put(RESOURCE_WRITE_SUCCESS, ResourceWriteSuccessEventData.class); + put(SERVICE_BUS_ACTIVE_MESSAGES_AVAILABLE_PERIODIC_NOTIFICATIONS, + ServiceBusActiveMessagesAvailablePeriodicNotificationsEventData.class); + put(SERVICE_BUS_ACTIVE_MESSAGES_AVAILABLE_WITH_NO_LISTENERS, + ServiceBusActiveMessagesAvailableWithNoListenersEventData.class); + put(SERVICE_BUS_DEADLETTER_MESSAGES_AVAILABLE_PERIODIC_NOTIFICATIONS, + ServiceBusDeadletterMessagesAvailablePeriodicNotificationsEventData.class); + put(SERVICE_BUS_DEADLETTER_MESSAGES_AVAILABLE_WITH_NO_LISTENERS, + ServiceBusDeadletterMessagesAvailableWithNoListenersEventData.class); + put(SIGNAL_RSERVICE_CLIENT_CONNECTION_CONNECTED, SignalRServiceClientConnectionConnectedEventData.class); + put(SIGNAL_RSERVICE_CLIENT_CONNECTION_DISCONNECTED, + SignalRServiceClientConnectionDisconnectedEventData.class); + put(STORAGE_ASYNC_OPERATION_INITIATED, StorageAsyncOperationInitiatedEventData.class); + put(STORAGE_BLOB_CREATED, StorageBlobCreatedEventData.class); + put(STORAGE_BLOB_DELETED, StorageBlobDeletedEventData.class); + put(STORAGE_BLOB_INVENTORY_POLICY_COMPLETED, StorageBlobInventoryPolicyCompletedEventData.class); + put(STORAGE_BLOB_RENAMED, StorageBlobRenamedEventData.class); + put(STORAGE_BLOB_TIER_CHANGED, StorageBlobTierChangedEventData.class); + put(STORAGE_DIRECTORY_CREATED, StorageDirectoryCreatedEventData.class); + put(STORAGE_DIRECTORY_DELETED, StorageDirectoryDeletedEventData.class); + put(STORAGE_DIRECTORY_RENAMED, StorageDirectoryRenamedEventData.class); + put(STORAGE_LIFECYCLE_POLICY_COMPLETED, StorageLifecyclePolicyCompletedEventData.class); + put(STORAGE_TASK_ASSIGNMENT_COMPLETED, StorageTaskAssignmentCompletedEventData.class); + put(STORAGE_TASK_ASSIGNMENT_QUEUED, StorageTaskAssignmentQueuedEventData.class); + put(STORAGE_TASK_COMPLETED, StorageTaskCompletedEventData.class); + put(STORAGE_TASK_QUEUED, StorageTaskQueuedEventData.class); + put(SUBSCRIPTION_DELETED, SubscriptionDeletedEventData.class); + put(SUBSCRIPTION_VALIDATION, SubscriptionValidationEventData.class); + put(WEB_APP_SERVICE_PLAN_UPDATED, WebAppServicePlanUpdatedEventData.class); + put(WEB_APP_UPDATED, WebAppUpdatedEventData.class); + put(WEB_BACKUP_OPERATION_COMPLETED, WebBackupOperationCompletedEventData.class); + put(WEB_BACKUP_OPERATION_FAILED, WebBackupOperationFailedEventData.class); + put(WEB_BACKUP_OPERATION_STARTED, WebBackupOperationStartedEventData.class); + put(WEB_RESTORE_OPERATION_COMPLETED, WebRestoreOperationCompletedEventData.class); + put(WEB_RESTORE_OPERATION_FAILED, WebRestoreOperationFailedEventData.class); + put(WEB_RESTORE_OPERATION_STARTED, WebRestoreOperationStartedEventData.class); + put(WEB_SLOT_SWAP_COMPLETED, WebSlotSwapCompletedEventData.class); + put(WEB_SLOT_SWAP_FAILED, WebSlotSwapFailedEventData.class); + put(WEB_SLOT_SWAP_STARTED, WebSlotSwapStartedEventData.class); + put(WEB_SLOT_SWAP_WITH_PREVIEW_CANCELLED, WebSlotSwapWithPreviewCancelledEventData.class); + put(WEB_SLOT_SWAP_WITH_PREVIEW_STARTED, WebSlotSwapWithPreviewStartedEventData.class); + } + }; + + /** + * Get a mapping of all the system event type strings to their respective class. This is used by default in + * the {@code EventGridEvent} and {@code CloudEvent} classes. + * + * @return a mapping of all the system event strings to system event objects. + */ + public static Map> getSystemEventMappings() { + return Collections.unmodifiableMap(SYSTEM_EVENT_MAPPINGS); + } + + private SystemEventNames() { + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/implementation/models/AcsMessageChannelEventError.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/implementation/models/AcsMessageChannelEventError.java new file mode 100644 index 000000000000..faef3b34fd76 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/implementation/models/AcsMessageChannelEventError.java @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.implementation.models; + +import com.azure.core.annotation.Generated; +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; + +/** + * Message Channel Event Error. + */ +@Immutable +public final class AcsMessageChannelEventError implements JsonSerializable { + /* + * The channel error code + */ + @Generated + private String channelCode; + + /* + * The channel error message + */ + @Generated + private String channelMessage; + + /** + * Creates an instance of AcsMessageChannelEventError class. + */ + @Generated + private AcsMessageChannelEventError() { + } + + /** + * Get the channelCode property: The channel error code. + * + * @return the channelCode value. + */ + @Generated + public String getChannelCode() { + return this.channelCode; + } + + /** + * Get the channelMessage property: The channel error message. + * + * @return the channelMessage value. + */ + @Generated + public String getChannelMessage() { + return this.channelMessage; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("channelCode", this.channelCode); + jsonWriter.writeStringField("channelMessage", this.channelMessage); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsMessageChannelEventError from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsMessageChannelEventError 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 AcsMessageChannelEventError. + */ + @Generated + public static AcsMessageChannelEventError fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AcsMessageChannelEventError deserializedAcsMessageChannelEventError = new AcsMessageChannelEventError(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("channelCode".equals(fieldName)) { + deserializedAcsMessageChannelEventError.channelCode = reader.getString(); + } else if ("channelMessage".equals(fieldName)) { + deserializedAcsMessageChannelEventError.channelMessage = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAcsMessageChannelEventError; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/implementation/models/AcsRouterCommunicationError.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/implementation/models/AcsRouterCommunicationError.java new file mode 100644 index 000000000000..93125770f4ca --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/implementation/models/AcsRouterCommunicationError.java @@ -0,0 +1,173 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.implementation.models; + +import com.azure.core.annotation.Generated; +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; +import java.util.List; + +/** + * Router Communication Error. + */ +@Immutable +public final class AcsRouterCommunicationError implements JsonSerializable { + /* + * Router Communication Error Code + */ + @Generated + private String code; + + /* + * Router Communication Error Message + */ + @Generated + private String message; + + /* + * Router Communication Error Target + */ + @Generated + private String target; + + /* + * Router Communication Inner Error + */ + @Generated + private final AcsRouterCommunicationError innererror; + + /* + * List of Router Communication Errors + */ + @Generated + private final List details; + + /** + * Creates an instance of AcsRouterCommunicationError class. + * + * @param innererror the innererror value to set. + * @param details the details value to set. + */ + @Generated + private AcsRouterCommunicationError(AcsRouterCommunicationError innererror, + List details) { + this.innererror = innererror; + this.details = details; + } + + /** + * Get the code property: Router Communication Error Code. + * + * @return the code value. + */ + @Generated + public String getCode() { + return this.code; + } + + /** + * Get the message property: Router Communication Error Message. + * + * @return the message value. + */ + @Generated + public String getMessage() { + return this.message; + } + + /** + * Get the target property: Router Communication Error Target. + * + * @return the target value. + */ + @Generated + public String getTarget() { + return this.target; + } + + /** + * Get the innererror property: Router Communication Inner Error. + * + * @return the innererror value. + */ + @Generated + public AcsRouterCommunicationError getInnererror() { + return this.innererror; + } + + /** + * Get the details property: List of Router Communication Errors. + * + * @return the details value. + */ + @Generated + public List getDetails() { + return this.details; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("innererror", this.innererror); + jsonWriter.writeArrayField("details", this.details, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("code", this.code); + jsonWriter.writeStringField("message", this.message); + jsonWriter.writeStringField("target", this.target); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRouterCommunicationError from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRouterCommunicationError 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 AcsRouterCommunicationError. + */ + @Generated + public static AcsRouterCommunicationError fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AcsRouterCommunicationError innererror = null; + List details = null; + String code = null; + String message = null; + String target = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("innererror".equals(fieldName)) { + innererror = AcsRouterCommunicationError.fromJson(reader); + } else if ("details".equals(fieldName)) { + details = reader.readArray(reader1 -> AcsRouterCommunicationError.fromJson(reader1)); + } else if ("code".equals(fieldName)) { + code = reader.getString(); + } else if ("message".equals(fieldName)) { + message = reader.getString(); + } else if ("target".equals(fieldName)) { + target = reader.getString(); + } else { + reader.skipChildren(); + } + } + AcsRouterCommunicationError deserializedAcsRouterCommunicationError + = new AcsRouterCommunicationError(innererror, details); + deserializedAcsRouterCommunicationError.code = code; + deserializedAcsRouterCommunicationError.message = message; + deserializedAcsRouterCommunicationError.target = target; + + return deserializedAcsRouterCommunicationError; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/implementation/models/package-info.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/implementation/models/package-info.java new file mode 100644 index 000000000000..a7a4c54d946d --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/implementation/models/package-info.java @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +/** + * Package containing the data models for SystemEvents. + * Azure Messaging EventGrid SystemEvents. + */ +package com.azure.messaging.eventgrid.implementation.models; diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/implementation/package-info.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/implementation/package-info.java new file mode 100644 index 000000000000..e8c7db696666 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/implementation/package-info.java @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +/** + * Package containing the implementations for SystemEvents. + * Azure Messaging EventGrid SystemEvents. + */ +package com.azure.messaging.eventgrid.implementation; diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/package-info.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/package-info.java new file mode 100644 index 000000000000..490ce05cc5a5 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/package-info.java @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +/** + * Package containing the classes for SystemEvents. + * Azure Messaging EventGrid SystemEvents. + */ +package com.azure.messaging.eventgrid; diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatEventBaseProperties.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatEventBaseProperties.java new file mode 100644 index 000000000000..028e05610522 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatEventBaseProperties.java @@ -0,0 +1,152 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of common properties of all chat events. + */ +@Immutable +public class AcsChatEventBaseProperties implements JsonSerializable { + /* + * The communication identifier of the target user + */ + @Generated + private final CommunicationIdentifierModel recipientCommunicationIdentifier; + + /* + * The transaction id will be used as co-relation vector + */ + @Generated + private String transactionId; + + /* + * The chat thread id + */ + @Generated + private String threadId; + + /** + * Creates an instance of AcsChatEventBaseProperties class. + * + * @param recipientCommunicationIdentifier the recipientCommunicationIdentifier value to set. + */ + @Generated + protected AcsChatEventBaseProperties(CommunicationIdentifierModel recipientCommunicationIdentifier) { + this.recipientCommunicationIdentifier = recipientCommunicationIdentifier; + } + + /** + * Get the recipientCommunicationIdentifier property: The communication identifier of the target user. + * + * @return the recipientCommunicationIdentifier value. + */ + @Generated + public CommunicationIdentifierModel getRecipientCommunicationIdentifier() { + return this.recipientCommunicationIdentifier; + } + + /** + * Get the transactionId property: The transaction id will be used as co-relation vector. + * + * @return the transactionId value. + */ + @Generated + public String getTransactionId() { + return this.transactionId; + } + + /** + * Set the transactionId property: The transaction id will be used as co-relation vector. + * + * @param transactionId the transactionId value to set. + * @return the AcsChatEventBaseProperties object itself. + */ + @Generated + AcsChatEventBaseProperties setTransactionId(String transactionId) { + this.transactionId = transactionId; + return this; + } + + /** + * Get the threadId property: The chat thread id. + * + * @return the threadId value. + */ + @Generated + public String getThreadId() { + return this.threadId; + } + + /** + * Set the threadId property: The chat thread id. + * + * @param threadId the threadId value to set. + * @return the AcsChatEventBaseProperties object itself. + */ + @Generated + AcsChatEventBaseProperties setThreadId(String threadId) { + this.threadId = threadId; + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("recipientCommunicationIdentifier", this.recipientCommunicationIdentifier); + jsonWriter.writeStringField("transactionId", this.transactionId); + jsonWriter.writeStringField("threadId", this.threadId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsChatEventBaseProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsChatEventBaseProperties 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 AcsChatEventBaseProperties. + */ + @Generated + public static AcsChatEventBaseProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CommunicationIdentifierModel recipientCommunicationIdentifier = null; + String transactionId = null; + String threadId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("recipientCommunicationIdentifier".equals(fieldName)) { + recipientCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("transactionId".equals(fieldName)) { + transactionId = reader.getString(); + } else if ("threadId".equals(fieldName)) { + threadId = reader.getString(); + } else { + reader.skipChildren(); + } + } + AcsChatEventBaseProperties deserializedAcsChatEventBaseProperties + = new AcsChatEventBaseProperties(recipientCommunicationIdentifier); + deserializedAcsChatEventBaseProperties.transactionId = transactionId; + deserializedAcsChatEventBaseProperties.threadId = threadId; + + return deserializedAcsChatEventBaseProperties; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatEventInThreadBaseProperties.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatEventInThreadBaseProperties.java new file mode 100644 index 000000000000..188a745840b5 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatEventInThreadBaseProperties.java @@ -0,0 +1,124 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of common properties of all thread-level chat events. + */ +@Immutable +public class AcsChatEventInThreadBaseProperties implements JsonSerializable { + /* + * The transaction id will be used as co-relation vector + */ + @Generated + private String transactionId; + + /* + * The chat thread id + */ + @Generated + private String threadId; + + /** + * Creates an instance of AcsChatEventInThreadBaseProperties class. + */ + @Generated + protected AcsChatEventInThreadBaseProperties() { + } + + /** + * Get the transactionId property: The transaction id will be used as co-relation vector. + * + * @return the transactionId value. + */ + @Generated + public String getTransactionId() { + return this.transactionId; + } + + /** + * Set the transactionId property: The transaction id will be used as co-relation vector. + * + * @param transactionId the transactionId value to set. + * @return the AcsChatEventInThreadBaseProperties object itself. + */ + @Generated + AcsChatEventInThreadBaseProperties setTransactionId(String transactionId) { + this.transactionId = transactionId; + return this; + } + + /** + * Get the threadId property: The chat thread id. + * + * @return the threadId value. + */ + @Generated + public String getThreadId() { + return this.threadId; + } + + /** + * Set the threadId property: The chat thread id. + * + * @param threadId the threadId value to set. + * @return the AcsChatEventInThreadBaseProperties object itself. + */ + @Generated + AcsChatEventInThreadBaseProperties setThreadId(String threadId) { + this.threadId = threadId; + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("transactionId", this.transactionId); + jsonWriter.writeStringField("threadId", this.threadId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsChatEventInThreadBaseProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsChatEventInThreadBaseProperties 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 AcsChatEventInThreadBaseProperties. + */ + @Generated + public static AcsChatEventInThreadBaseProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AcsChatEventInThreadBaseProperties deserializedAcsChatEventInThreadBaseProperties + = new AcsChatEventInThreadBaseProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("transactionId".equals(fieldName)) { + deserializedAcsChatEventInThreadBaseProperties.transactionId = reader.getString(); + } else if ("threadId".equals(fieldName)) { + deserializedAcsChatEventInThreadBaseProperties.threadId = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAcsChatEventInThreadBaseProperties; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatMessageDeletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatMessageDeletedEventData.java new file mode 100644 index 000000000000..faebe4036f89 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatMessageDeletedEventData.java @@ -0,0 +1,243 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatMessageDeleted event. + */ +@Immutable +public final class AcsChatMessageDeletedEventData extends AcsChatMessageEventBaseProperties { + /* + * The time at which the message was deleted + */ + @Generated + private final OffsetDateTime deleteTime; + + /* + * The version of the message + */ + @Generated + private Long version; + + /* + * The type of the message + */ + @Generated + private String type; + + /* + * The display name of the sender + */ + @Generated + private String senderDisplayName; + + /* + * The chat message id + */ + @Generated + private String messageId; + + /* + * The chat thread id + */ + @Generated + private String threadId; + + /* + * The transaction id will be used as co-relation vector + */ + @Generated + private String transactionId; + + /** + * Creates an instance of AcsChatMessageDeletedEventData class. + * + * @param recipientCommunicationIdentifier the recipientCommunicationIdentifier value to set. + * @param senderCommunicationIdentifier the senderCommunicationIdentifier value to set. + * @param composeTime the composeTime value to set. + * @param deleteTime the deleteTime value to set. + */ + @Generated + private AcsChatMessageDeletedEventData(CommunicationIdentifierModel recipientCommunicationIdentifier, + CommunicationIdentifierModel senderCommunicationIdentifier, OffsetDateTime composeTime, + OffsetDateTime deleteTime) { + super(recipientCommunicationIdentifier, senderCommunicationIdentifier, composeTime); + this.deleteTime = deleteTime; + } + + /** + * Get the deleteTime property: The time at which the message was deleted. + * + * @return the deleteTime value. + */ + @Generated + public OffsetDateTime getDeleteTime() { + return this.deleteTime; + } + + /** + * Get the version property: The version of the message. + * + * @return the version value. + */ + @Generated + @Override + public Long getVersion() { + return this.version; + } + + /** + * Get the type property: The type of the message. + * + * @return the type value. + */ + @Generated + @Override + public String getType() { + return this.type; + } + + /** + * Get the senderDisplayName property: The display name of the sender. + * + * @return the senderDisplayName value. + */ + @Generated + @Override + public String getSenderDisplayName() { + return this.senderDisplayName; + } + + /** + * Get the messageId property: The chat message id. + * + * @return the messageId value. + */ + @Generated + @Override + public String getMessageId() { + return this.messageId; + } + + /** + * Get the threadId property: The chat thread id. + * + * @return the threadId value. + */ + @Generated + @Override + public String getThreadId() { + return this.threadId; + } + + /** + * Get the transactionId property: The transaction id will be used as co-relation vector. + * + * @return the transactionId value. + */ + @Generated + @Override + public String getTransactionId() { + return this.transactionId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("recipientCommunicationIdentifier", getRecipientCommunicationIdentifier()); + jsonWriter.writeJsonField("senderCommunicationIdentifier", getSenderCommunicationIdentifier()); + jsonWriter.writeStringField("composeTime", + getComposeTime() == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(getComposeTime())); + jsonWriter.writeStringField("transactionId", getTransactionId()); + jsonWriter.writeStringField("threadId", getThreadId()); + jsonWriter.writeStringField("messageId", getMessageId()); + jsonWriter.writeStringField("senderDisplayName", getSenderDisplayName()); + jsonWriter.writeStringField("type", getType()); + jsonWriter.writeNumberField("version", getVersion()); + jsonWriter.writeStringField("deleteTime", + this.deleteTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.deleteTime)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsChatMessageDeletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsChatMessageDeletedEventData 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 AcsChatMessageDeletedEventData. + */ + @Generated + public static AcsChatMessageDeletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CommunicationIdentifierModel recipientCommunicationIdentifier = null; + CommunicationIdentifierModel senderCommunicationIdentifier = null; + OffsetDateTime composeTime = null; + String transactionId = null; + String threadId = null; + String messageId = null; + String senderDisplayName = null; + String type = null; + Long version = null; + OffsetDateTime deleteTime = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("recipientCommunicationIdentifier".equals(fieldName)) { + recipientCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("senderCommunicationIdentifier".equals(fieldName)) { + senderCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("composeTime".equals(fieldName)) { + composeTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("transactionId".equals(fieldName)) { + transactionId = reader.getString(); + } else if ("threadId".equals(fieldName)) { + threadId = reader.getString(); + } else if ("messageId".equals(fieldName)) { + messageId = reader.getString(); + } else if ("senderDisplayName".equals(fieldName)) { + senderDisplayName = reader.getString(); + } else if ("type".equals(fieldName)) { + type = reader.getString(); + } else if ("version".equals(fieldName)) { + version = reader.getNullable(JsonReader::getLong); + } else if ("deleteTime".equals(fieldName)) { + deleteTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else { + reader.skipChildren(); + } + } + AcsChatMessageDeletedEventData deserializedAcsChatMessageDeletedEventData + = new AcsChatMessageDeletedEventData(recipientCommunicationIdentifier, senderCommunicationIdentifier, + composeTime, deleteTime); + deserializedAcsChatMessageDeletedEventData.transactionId = transactionId; + deserializedAcsChatMessageDeletedEventData.threadId = threadId; + deserializedAcsChatMessageDeletedEventData.messageId = messageId; + deserializedAcsChatMessageDeletedEventData.senderDisplayName = senderDisplayName; + deserializedAcsChatMessageDeletedEventData.type = type; + deserializedAcsChatMessageDeletedEventData.version = version; + + return deserializedAcsChatMessageDeletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatMessageDeletedInThreadEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatMessageDeletedInThreadEventData.java new file mode 100644 index 000000000000..68d155f5f6ae --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatMessageDeletedInThreadEventData.java @@ -0,0 +1,236 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatMessageDeletedInThread event. + */ +@Immutable +public final class AcsChatMessageDeletedInThreadEventData extends AcsChatMessageEventInThreadBaseProperties { + /* + * The time at which the message was deleted + */ + @Generated + private final OffsetDateTime deleteTime; + + /* + * The version of the message + */ + @Generated + private Long version; + + /* + * The type of the message + */ + @Generated + private String type; + + /* + * The display name of the sender + */ + @Generated + private String senderDisplayName; + + /* + * The chat message id + */ + @Generated + private String messageId; + + /* + * The chat thread id + */ + @Generated + private String threadId; + + /* + * The transaction id will be used as co-relation vector + */ + @Generated + private String transactionId; + + /** + * Creates an instance of AcsChatMessageDeletedInThreadEventData class. + * + * @param senderCommunicationIdentifier the senderCommunicationIdentifier value to set. + * @param composeTime the composeTime value to set. + * @param deleteTime the deleteTime value to set. + */ + @Generated + private AcsChatMessageDeletedInThreadEventData(CommunicationIdentifierModel senderCommunicationIdentifier, + OffsetDateTime composeTime, OffsetDateTime deleteTime) { + super(senderCommunicationIdentifier, composeTime); + this.deleteTime = deleteTime; + } + + /** + * Get the deleteTime property: The time at which the message was deleted. + * + * @return the deleteTime value. + */ + @Generated + public OffsetDateTime getDeleteTime() { + return this.deleteTime; + } + + /** + * Get the version property: The version of the message. + * + * @return the version value. + */ + @Generated + @Override + public Long getVersion() { + return this.version; + } + + /** + * Get the type property: The type of the message. + * + * @return the type value. + */ + @Generated + @Override + public String getType() { + return this.type; + } + + /** + * Get the senderDisplayName property: The display name of the sender. + * + * @return the senderDisplayName value. + */ + @Generated + @Override + public String getSenderDisplayName() { + return this.senderDisplayName; + } + + /** + * Get the messageId property: The chat message id. + * + * @return the messageId value. + */ + @Generated + @Override + public String getMessageId() { + return this.messageId; + } + + /** + * Get the threadId property: The chat thread id. + * + * @return the threadId value. + */ + @Generated + @Override + public String getThreadId() { + return this.threadId; + } + + /** + * Get the transactionId property: The transaction id will be used as co-relation vector. + * + * @return the transactionId value. + */ + @Generated + @Override + public String getTransactionId() { + return this.transactionId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("senderCommunicationIdentifier", getSenderCommunicationIdentifier()); + jsonWriter.writeStringField("composeTime", + getComposeTime() == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(getComposeTime())); + jsonWriter.writeStringField("transactionId", getTransactionId()); + jsonWriter.writeStringField("threadId", getThreadId()); + jsonWriter.writeStringField("messageId", getMessageId()); + jsonWriter.writeStringField("senderDisplayName", getSenderDisplayName()); + jsonWriter.writeStringField("type", getType()); + jsonWriter.writeNumberField("version", getVersion()); + jsonWriter.writeStringField("deleteTime", + this.deleteTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.deleteTime)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsChatMessageDeletedInThreadEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsChatMessageDeletedInThreadEventData 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 AcsChatMessageDeletedInThreadEventData. + */ + @Generated + public static AcsChatMessageDeletedInThreadEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CommunicationIdentifierModel senderCommunicationIdentifier = null; + OffsetDateTime composeTime = null; + String transactionId = null; + String threadId = null; + String messageId = null; + String senderDisplayName = null; + String type = null; + Long version = null; + OffsetDateTime deleteTime = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("senderCommunicationIdentifier".equals(fieldName)) { + senderCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("composeTime".equals(fieldName)) { + composeTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("transactionId".equals(fieldName)) { + transactionId = reader.getString(); + } else if ("threadId".equals(fieldName)) { + threadId = reader.getString(); + } else if ("messageId".equals(fieldName)) { + messageId = reader.getString(); + } else if ("senderDisplayName".equals(fieldName)) { + senderDisplayName = reader.getString(); + } else if ("type".equals(fieldName)) { + type = reader.getString(); + } else if ("version".equals(fieldName)) { + version = reader.getNullable(JsonReader::getLong); + } else if ("deleteTime".equals(fieldName)) { + deleteTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else { + reader.skipChildren(); + } + } + AcsChatMessageDeletedInThreadEventData deserializedAcsChatMessageDeletedInThreadEventData + = new AcsChatMessageDeletedInThreadEventData(senderCommunicationIdentifier, composeTime, deleteTime); + deserializedAcsChatMessageDeletedInThreadEventData.transactionId = transactionId; + deserializedAcsChatMessageDeletedInThreadEventData.threadId = threadId; + deserializedAcsChatMessageDeletedInThreadEventData.messageId = messageId; + deserializedAcsChatMessageDeletedInThreadEventData.senderDisplayName = senderDisplayName; + deserializedAcsChatMessageDeletedInThreadEventData.type = type; + deserializedAcsChatMessageDeletedInThreadEventData.version = version; + + return deserializedAcsChatMessageDeletedInThreadEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatMessageEditedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatMessageEditedEventData.java new file mode 100644 index 000000000000..b4c0dd139c93 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatMessageEditedEventData.java @@ -0,0 +1,286 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatMessageEdited event. + */ +@Immutable +public final class AcsChatMessageEditedEventData extends AcsChatMessageEventBaseProperties { + /* + * The body of the chat message + */ + @Generated + private String messageBody; + + /* + * The chat message metadata + */ + @Generated + private final Map metadata; + + /* + * The time at which the message was edited + */ + @Generated + private final OffsetDateTime editTime; + + /* + * The version of the message + */ + @Generated + private Long version; + + /* + * The type of the message + */ + @Generated + private String type; + + /* + * The display name of the sender + */ + @Generated + private String senderDisplayName; + + /* + * The chat message id + */ + @Generated + private String messageId; + + /* + * The chat thread id + */ + @Generated + private String threadId; + + /* + * The transaction id will be used as co-relation vector + */ + @Generated + private String transactionId; + + /** + * Creates an instance of AcsChatMessageEditedEventData class. + * + * @param recipientCommunicationIdentifier the recipientCommunicationIdentifier value to set. + * @param senderCommunicationIdentifier the senderCommunicationIdentifier value to set. + * @param composeTime the composeTime value to set. + * @param metadata the metadata value to set. + * @param editTime the editTime value to set. + */ + @Generated + private AcsChatMessageEditedEventData(CommunicationIdentifierModel recipientCommunicationIdentifier, + CommunicationIdentifierModel senderCommunicationIdentifier, OffsetDateTime composeTime, + Map metadata, OffsetDateTime editTime) { + super(recipientCommunicationIdentifier, senderCommunicationIdentifier, composeTime); + this.metadata = metadata; + this.editTime = editTime; + } + + /** + * Get the messageBody property: The body of the chat message. + * + * @return the messageBody value. + */ + @Generated + public String getMessageBody() { + return this.messageBody; + } + + /** + * Get the metadata property: The chat message metadata. + * + * @return the metadata value. + */ + @Generated + public Map getMetadata() { + return this.metadata; + } + + /** + * Get the editTime property: The time at which the message was edited. + * + * @return the editTime value. + */ + @Generated + public OffsetDateTime getEditTime() { + return this.editTime; + } + + /** + * Get the version property: The version of the message. + * + * @return the version value. + */ + @Generated + @Override + public Long getVersion() { + return this.version; + } + + /** + * Get the type property: The type of the message. + * + * @return the type value. + */ + @Generated + @Override + public String getType() { + return this.type; + } + + /** + * Get the senderDisplayName property: The display name of the sender. + * + * @return the senderDisplayName value. + */ + @Generated + @Override + public String getSenderDisplayName() { + return this.senderDisplayName; + } + + /** + * Get the messageId property: The chat message id. + * + * @return the messageId value. + */ + @Generated + @Override + public String getMessageId() { + return this.messageId; + } + + /** + * Get the threadId property: The chat thread id. + * + * @return the threadId value. + */ + @Generated + @Override + public String getThreadId() { + return this.threadId; + } + + /** + * Get the transactionId property: The transaction id will be used as co-relation vector. + * + * @return the transactionId value. + */ + @Generated + @Override + public String getTransactionId() { + return this.transactionId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("recipientCommunicationIdentifier", getRecipientCommunicationIdentifier()); + jsonWriter.writeJsonField("senderCommunicationIdentifier", getSenderCommunicationIdentifier()); + jsonWriter.writeStringField("composeTime", + getComposeTime() == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(getComposeTime())); + jsonWriter.writeStringField("transactionId", getTransactionId()); + jsonWriter.writeStringField("threadId", getThreadId()); + jsonWriter.writeStringField("messageId", getMessageId()); + jsonWriter.writeStringField("senderDisplayName", getSenderDisplayName()); + jsonWriter.writeStringField("type", getType()); + jsonWriter.writeNumberField("version", getVersion()); + jsonWriter.writeMapField("metadata", this.metadata, (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("editTime", + this.editTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.editTime)); + jsonWriter.writeStringField("messageBody", this.messageBody); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsChatMessageEditedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsChatMessageEditedEventData 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 AcsChatMessageEditedEventData. + */ + @Generated + public static AcsChatMessageEditedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CommunicationIdentifierModel recipientCommunicationIdentifier = null; + CommunicationIdentifierModel senderCommunicationIdentifier = null; + OffsetDateTime composeTime = null; + String transactionId = null; + String threadId = null; + String messageId = null; + String senderDisplayName = null; + String type = null; + Long version = null; + Map metadata = null; + OffsetDateTime editTime = null; + String messageBody = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("recipientCommunicationIdentifier".equals(fieldName)) { + recipientCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("senderCommunicationIdentifier".equals(fieldName)) { + senderCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("composeTime".equals(fieldName)) { + composeTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("transactionId".equals(fieldName)) { + transactionId = reader.getString(); + } else if ("threadId".equals(fieldName)) { + threadId = reader.getString(); + } else if ("messageId".equals(fieldName)) { + messageId = reader.getString(); + } else if ("senderDisplayName".equals(fieldName)) { + senderDisplayName = reader.getString(); + } else if ("type".equals(fieldName)) { + type = reader.getString(); + } else if ("version".equals(fieldName)) { + version = reader.getNullable(JsonReader::getLong); + } else if ("metadata".equals(fieldName)) { + metadata = reader.readMap(reader1 -> reader1.getString()); + } else if ("editTime".equals(fieldName)) { + editTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("messageBody".equals(fieldName)) { + messageBody = reader.getString(); + } else { + reader.skipChildren(); + } + } + AcsChatMessageEditedEventData deserializedAcsChatMessageEditedEventData = new AcsChatMessageEditedEventData( + recipientCommunicationIdentifier, senderCommunicationIdentifier, composeTime, metadata, editTime); + deserializedAcsChatMessageEditedEventData.transactionId = transactionId; + deserializedAcsChatMessageEditedEventData.threadId = threadId; + deserializedAcsChatMessageEditedEventData.messageId = messageId; + deserializedAcsChatMessageEditedEventData.senderDisplayName = senderDisplayName; + deserializedAcsChatMessageEditedEventData.type = type; + deserializedAcsChatMessageEditedEventData.version = version; + deserializedAcsChatMessageEditedEventData.messageBody = messageBody; + + return deserializedAcsChatMessageEditedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatMessageEditedInThreadEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatMessageEditedInThreadEventData.java new file mode 100644 index 000000000000..30575e375db6 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatMessageEditedInThreadEventData.java @@ -0,0 +1,281 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatMessageEditedInThread event. + */ +@Immutable +public final class AcsChatMessageEditedInThreadEventData extends AcsChatMessageEventInThreadBaseProperties { + /* + * The body of the chat message + */ + @Generated + private String messageBody; + + /* + * The chat message metadata + */ + @Generated + private final Map metadata; + + /* + * The time at which the message was edited + */ + @Generated + private final OffsetDateTime editTime; + + /* + * The version of the message + */ + @Generated + private Long version; + + /* + * The type of the message + */ + @Generated + private String type; + + /* + * The display name of the sender + */ + @Generated + private String senderDisplayName; + + /* + * The chat message id + */ + @Generated + private String messageId; + + /* + * The chat thread id + */ + @Generated + private String threadId; + + /* + * The transaction id will be used as co-relation vector + */ + @Generated + private String transactionId; + + /** + * Creates an instance of AcsChatMessageEditedInThreadEventData class. + * + * @param senderCommunicationIdentifier the senderCommunicationIdentifier value to set. + * @param composeTime the composeTime value to set. + * @param metadata the metadata value to set. + * @param editTime the editTime value to set. + */ + @Generated + private AcsChatMessageEditedInThreadEventData(CommunicationIdentifierModel senderCommunicationIdentifier, + OffsetDateTime composeTime, Map metadata, OffsetDateTime editTime) { + super(senderCommunicationIdentifier, composeTime); + this.metadata = metadata; + this.editTime = editTime; + } + + /** + * Get the messageBody property: The body of the chat message. + * + * @return the messageBody value. + */ + @Generated + public String getMessageBody() { + return this.messageBody; + } + + /** + * Get the metadata property: The chat message metadata. + * + * @return the metadata value. + */ + @Generated + public Map getMetadata() { + return this.metadata; + } + + /** + * Get the editTime property: The time at which the message was edited. + * + * @return the editTime value. + */ + @Generated + public OffsetDateTime getEditTime() { + return this.editTime; + } + + /** + * Get the version property: The version of the message. + * + * @return the version value. + */ + @Generated + @Override + public Long getVersion() { + return this.version; + } + + /** + * Get the type property: The type of the message. + * + * @return the type value. + */ + @Generated + @Override + public String getType() { + return this.type; + } + + /** + * Get the senderDisplayName property: The display name of the sender. + * + * @return the senderDisplayName value. + */ + @Generated + @Override + public String getSenderDisplayName() { + return this.senderDisplayName; + } + + /** + * Get the messageId property: The chat message id. + * + * @return the messageId value. + */ + @Generated + @Override + public String getMessageId() { + return this.messageId; + } + + /** + * Get the threadId property: The chat thread id. + * + * @return the threadId value. + */ + @Generated + @Override + public String getThreadId() { + return this.threadId; + } + + /** + * Get the transactionId property: The transaction id will be used as co-relation vector. + * + * @return the transactionId value. + */ + @Generated + @Override + public String getTransactionId() { + return this.transactionId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("senderCommunicationIdentifier", getSenderCommunicationIdentifier()); + jsonWriter.writeStringField("composeTime", + getComposeTime() == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(getComposeTime())); + jsonWriter.writeStringField("transactionId", getTransactionId()); + jsonWriter.writeStringField("threadId", getThreadId()); + jsonWriter.writeStringField("messageId", getMessageId()); + jsonWriter.writeStringField("senderDisplayName", getSenderDisplayName()); + jsonWriter.writeStringField("type", getType()); + jsonWriter.writeNumberField("version", getVersion()); + jsonWriter.writeMapField("metadata", this.metadata, (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("editTime", + this.editTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.editTime)); + jsonWriter.writeStringField("messageBody", this.messageBody); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsChatMessageEditedInThreadEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsChatMessageEditedInThreadEventData 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 AcsChatMessageEditedInThreadEventData. + */ + @Generated + public static AcsChatMessageEditedInThreadEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CommunicationIdentifierModel senderCommunicationIdentifier = null; + OffsetDateTime composeTime = null; + String transactionId = null; + String threadId = null; + String messageId = null; + String senderDisplayName = null; + String type = null; + Long version = null; + Map metadata = null; + OffsetDateTime editTime = null; + String messageBody = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("senderCommunicationIdentifier".equals(fieldName)) { + senderCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("composeTime".equals(fieldName)) { + composeTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("transactionId".equals(fieldName)) { + transactionId = reader.getString(); + } else if ("threadId".equals(fieldName)) { + threadId = reader.getString(); + } else if ("messageId".equals(fieldName)) { + messageId = reader.getString(); + } else if ("senderDisplayName".equals(fieldName)) { + senderDisplayName = reader.getString(); + } else if ("type".equals(fieldName)) { + type = reader.getString(); + } else if ("version".equals(fieldName)) { + version = reader.getNullable(JsonReader::getLong); + } else if ("metadata".equals(fieldName)) { + metadata = reader.readMap(reader1 -> reader1.getString()); + } else if ("editTime".equals(fieldName)) { + editTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("messageBody".equals(fieldName)) { + messageBody = reader.getString(); + } else { + reader.skipChildren(); + } + } + AcsChatMessageEditedInThreadEventData deserializedAcsChatMessageEditedInThreadEventData + = new AcsChatMessageEditedInThreadEventData(senderCommunicationIdentifier, composeTime, metadata, + editTime); + deserializedAcsChatMessageEditedInThreadEventData.transactionId = transactionId; + deserializedAcsChatMessageEditedInThreadEventData.threadId = threadId; + deserializedAcsChatMessageEditedInThreadEventData.messageId = messageId; + deserializedAcsChatMessageEditedInThreadEventData.senderDisplayName = senderDisplayName; + deserializedAcsChatMessageEditedInThreadEventData.type = type; + deserializedAcsChatMessageEditedInThreadEventData.version = version; + deserializedAcsChatMessageEditedInThreadEventData.messageBody = messageBody; + + return deserializedAcsChatMessageEditedInThreadEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatMessageEventBaseProperties.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatMessageEventBaseProperties.java new file mode 100644 index 000000000000..0ef110d10a5d --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatMessageEventBaseProperties.java @@ -0,0 +1,296 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of common properties of all chat message events. + */ +@Immutable +public class AcsChatMessageEventBaseProperties extends AcsChatEventBaseProperties { + /* + * The chat message id + */ + @Generated + private String messageId; + + /* + * The communication identifier of the sender + */ + @Generated + private final CommunicationIdentifierModel senderCommunicationIdentifier; + + /* + * The display name of the sender + */ + @Generated + private String senderDisplayName; + + /* + * The original compose time of the message + */ + @Generated + private final OffsetDateTime composeTime; + + /* + * The type of the message + */ + @Generated + private String type; + + /* + * The version of the message + */ + @Generated + private Long version; + + /* + * The chat thread id + */ + @Generated + private String threadId; + + /* + * The transaction id will be used as co-relation vector + */ + @Generated + private String transactionId; + + /** + * Creates an instance of AcsChatMessageEventBaseProperties class. + * + * @param recipientCommunicationIdentifier the recipientCommunicationIdentifier value to set. + * @param senderCommunicationIdentifier the senderCommunicationIdentifier value to set. + * @param composeTime the composeTime value to set. + */ + @Generated + protected AcsChatMessageEventBaseProperties(CommunicationIdentifierModel recipientCommunicationIdentifier, + CommunicationIdentifierModel senderCommunicationIdentifier, OffsetDateTime composeTime) { + super(recipientCommunicationIdentifier); + this.senderCommunicationIdentifier = senderCommunicationIdentifier; + this.composeTime = composeTime; + } + + /** + * Get the messageId property: The chat message id. + * + * @return the messageId value. + */ + @Generated + public String getMessageId() { + return this.messageId; + } + + /** + * Set the messageId property: The chat message id. + * + * @param messageId the messageId value to set. + * @return the AcsChatMessageEventBaseProperties object itself. + */ + @Generated + AcsChatMessageEventBaseProperties setMessageId(String messageId) { + this.messageId = messageId; + return this; + } + + /** + * Get the senderCommunicationIdentifier property: The communication identifier of the sender. + * + * @return the senderCommunicationIdentifier value. + */ + @Generated + public CommunicationIdentifierModel getSenderCommunicationIdentifier() { + return this.senderCommunicationIdentifier; + } + + /** + * Get the senderDisplayName property: The display name of the sender. + * + * @return the senderDisplayName value. + */ + @Generated + public String getSenderDisplayName() { + return this.senderDisplayName; + } + + /** + * Set the senderDisplayName property: The display name of the sender. + * + * @param senderDisplayName the senderDisplayName value to set. + * @return the AcsChatMessageEventBaseProperties object itself. + */ + @Generated + AcsChatMessageEventBaseProperties setSenderDisplayName(String senderDisplayName) { + this.senderDisplayName = senderDisplayName; + return this; + } + + /** + * Get the composeTime property: The original compose time of the message. + * + * @return the composeTime value. + */ + @Generated + public OffsetDateTime getComposeTime() { + return this.composeTime; + } + + /** + * Get the type property: The type of the message. + * + * @return the type value. + */ + @Generated + public String getType() { + return this.type; + } + + /** + * Set the type property: The type of the message. + * + * @param type the type value to set. + * @return the AcsChatMessageEventBaseProperties object itself. + */ + @Generated + AcsChatMessageEventBaseProperties setType(String type) { + this.type = type; + return this; + } + + /** + * Get the version property: The version of the message. + * + * @return the version value. + */ + @Generated + public Long getVersion() { + return this.version; + } + + /** + * Set the version property: The version of the message. + * + * @param version the version value to set. + * @return the AcsChatMessageEventBaseProperties object itself. + */ + @Generated + AcsChatMessageEventBaseProperties setVersion(Long version) { + this.version = version; + return this; + } + + /** + * Get the threadId property: The chat thread id. + * + * @return the threadId value. + */ + @Generated + @Override + public String getThreadId() { + return this.threadId; + } + + /** + * Get the transactionId property: The transaction id will be used as co-relation vector. + * + * @return the transactionId value. + */ + @Generated + @Override + public String getTransactionId() { + return this.transactionId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("recipientCommunicationIdentifier", getRecipientCommunicationIdentifier()); + jsonWriter.writeStringField("transactionId", getTransactionId()); + jsonWriter.writeStringField("threadId", getThreadId()); + jsonWriter.writeJsonField("senderCommunicationIdentifier", this.senderCommunicationIdentifier); + jsonWriter.writeStringField("composeTime", + this.composeTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.composeTime)); + jsonWriter.writeStringField("messageId", this.messageId); + jsonWriter.writeStringField("senderDisplayName", this.senderDisplayName); + jsonWriter.writeStringField("type", this.type); + jsonWriter.writeNumberField("version", this.version); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsChatMessageEventBaseProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsChatMessageEventBaseProperties 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 AcsChatMessageEventBaseProperties. + */ + @Generated + public static AcsChatMessageEventBaseProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CommunicationIdentifierModel recipientCommunicationIdentifier = null; + String transactionId = null; + String threadId = null; + CommunicationIdentifierModel senderCommunicationIdentifier = null; + OffsetDateTime composeTime = null; + String messageId = null; + String senderDisplayName = null; + String type = null; + Long version = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("recipientCommunicationIdentifier".equals(fieldName)) { + recipientCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("transactionId".equals(fieldName)) { + transactionId = reader.getString(); + } else if ("threadId".equals(fieldName)) { + threadId = reader.getString(); + } else if ("senderCommunicationIdentifier".equals(fieldName)) { + senderCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("composeTime".equals(fieldName)) { + composeTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("messageId".equals(fieldName)) { + messageId = reader.getString(); + } else if ("senderDisplayName".equals(fieldName)) { + senderDisplayName = reader.getString(); + } else if ("type".equals(fieldName)) { + type = reader.getString(); + } else if ("version".equals(fieldName)) { + version = reader.getNullable(JsonReader::getLong); + } else { + reader.skipChildren(); + } + } + AcsChatMessageEventBaseProperties deserializedAcsChatMessageEventBaseProperties + = new AcsChatMessageEventBaseProperties(recipientCommunicationIdentifier, senderCommunicationIdentifier, + composeTime); + deserializedAcsChatMessageEventBaseProperties.transactionId = transactionId; + deserializedAcsChatMessageEventBaseProperties.threadId = threadId; + deserializedAcsChatMessageEventBaseProperties.messageId = messageId; + deserializedAcsChatMessageEventBaseProperties.senderDisplayName = senderDisplayName; + deserializedAcsChatMessageEventBaseProperties.type = type; + deserializedAcsChatMessageEventBaseProperties.version = version; + + return deserializedAcsChatMessageEventBaseProperties; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatMessageEventInThreadBaseProperties.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatMessageEventInThreadBaseProperties.java new file mode 100644 index 000000000000..219d5c286f69 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatMessageEventInThreadBaseProperties.java @@ -0,0 +1,289 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of common properties of all thread-level chat message events. + */ +@Immutable +public class AcsChatMessageEventInThreadBaseProperties extends AcsChatEventInThreadBaseProperties { + /* + * The chat message id + */ + @Generated + private String messageId; + + /* + * The communication identifier of the sender + */ + @Generated + private final CommunicationIdentifierModel senderCommunicationIdentifier; + + /* + * The display name of the sender + */ + @Generated + private String senderDisplayName; + + /* + * The original compose time of the message + */ + @Generated + private final OffsetDateTime composeTime; + + /* + * The type of the message + */ + @Generated + private String type; + + /* + * The version of the message + */ + @Generated + private Long version; + + /* + * The chat thread id + */ + @Generated + private String threadId; + + /* + * The transaction id will be used as co-relation vector + */ + @Generated + private String transactionId; + + /** + * Creates an instance of AcsChatMessageEventInThreadBaseProperties class. + * + * @param senderCommunicationIdentifier the senderCommunicationIdentifier value to set. + * @param composeTime the composeTime value to set. + */ + @Generated + protected AcsChatMessageEventInThreadBaseProperties(CommunicationIdentifierModel senderCommunicationIdentifier, + OffsetDateTime composeTime) { + this.senderCommunicationIdentifier = senderCommunicationIdentifier; + this.composeTime = composeTime; + } + + /** + * Get the messageId property: The chat message id. + * + * @return the messageId value. + */ + @Generated + public String getMessageId() { + return this.messageId; + } + + /** + * Set the messageId property: The chat message id. + * + * @param messageId the messageId value to set. + * @return the AcsChatMessageEventInThreadBaseProperties object itself. + */ + @Generated + AcsChatMessageEventInThreadBaseProperties setMessageId(String messageId) { + this.messageId = messageId; + return this; + } + + /** + * Get the senderCommunicationIdentifier property: The communication identifier of the sender. + * + * @return the senderCommunicationIdentifier value. + */ + @Generated + public CommunicationIdentifierModel getSenderCommunicationIdentifier() { + return this.senderCommunicationIdentifier; + } + + /** + * Get the senderDisplayName property: The display name of the sender. + * + * @return the senderDisplayName value. + */ + @Generated + public String getSenderDisplayName() { + return this.senderDisplayName; + } + + /** + * Set the senderDisplayName property: The display name of the sender. + * + * @param senderDisplayName the senderDisplayName value to set. + * @return the AcsChatMessageEventInThreadBaseProperties object itself. + */ + @Generated + AcsChatMessageEventInThreadBaseProperties setSenderDisplayName(String senderDisplayName) { + this.senderDisplayName = senderDisplayName; + return this; + } + + /** + * Get the composeTime property: The original compose time of the message. + * + * @return the composeTime value. + */ + @Generated + public OffsetDateTime getComposeTime() { + return this.composeTime; + } + + /** + * Get the type property: The type of the message. + * + * @return the type value. + */ + @Generated + public String getType() { + return this.type; + } + + /** + * Set the type property: The type of the message. + * + * @param type the type value to set. + * @return the AcsChatMessageEventInThreadBaseProperties object itself. + */ + @Generated + AcsChatMessageEventInThreadBaseProperties setType(String type) { + this.type = type; + return this; + } + + /** + * Get the version property: The version of the message. + * + * @return the version value. + */ + @Generated + public Long getVersion() { + return this.version; + } + + /** + * Set the version property: The version of the message. + * + * @param version the version value to set. + * @return the AcsChatMessageEventInThreadBaseProperties object itself. + */ + @Generated + AcsChatMessageEventInThreadBaseProperties setVersion(Long version) { + this.version = version; + return this; + } + + /** + * Get the threadId property: The chat thread id. + * + * @return the threadId value. + */ + @Generated + @Override + public String getThreadId() { + return this.threadId; + } + + /** + * Get the transactionId property: The transaction id will be used as co-relation vector. + * + * @return the transactionId value. + */ + @Generated + @Override + public String getTransactionId() { + return this.transactionId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("transactionId", getTransactionId()); + jsonWriter.writeStringField("threadId", getThreadId()); + jsonWriter.writeJsonField("senderCommunicationIdentifier", this.senderCommunicationIdentifier); + jsonWriter.writeStringField("composeTime", + this.composeTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.composeTime)); + jsonWriter.writeStringField("messageId", this.messageId); + jsonWriter.writeStringField("senderDisplayName", this.senderDisplayName); + jsonWriter.writeStringField("type", this.type); + jsonWriter.writeNumberField("version", this.version); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsChatMessageEventInThreadBaseProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsChatMessageEventInThreadBaseProperties 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 AcsChatMessageEventInThreadBaseProperties. + */ + @Generated + public static AcsChatMessageEventInThreadBaseProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String transactionId = null; + String threadId = null; + CommunicationIdentifierModel senderCommunicationIdentifier = null; + OffsetDateTime composeTime = null; + String messageId = null; + String senderDisplayName = null; + String type = null; + Long version = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("transactionId".equals(fieldName)) { + transactionId = reader.getString(); + } else if ("threadId".equals(fieldName)) { + threadId = reader.getString(); + } else if ("senderCommunicationIdentifier".equals(fieldName)) { + senderCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("composeTime".equals(fieldName)) { + composeTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("messageId".equals(fieldName)) { + messageId = reader.getString(); + } else if ("senderDisplayName".equals(fieldName)) { + senderDisplayName = reader.getString(); + } else if ("type".equals(fieldName)) { + type = reader.getString(); + } else if ("version".equals(fieldName)) { + version = reader.getNullable(JsonReader::getLong); + } else { + reader.skipChildren(); + } + } + AcsChatMessageEventInThreadBaseProperties deserializedAcsChatMessageEventInThreadBaseProperties + = new AcsChatMessageEventInThreadBaseProperties(senderCommunicationIdentifier, composeTime); + deserializedAcsChatMessageEventInThreadBaseProperties.transactionId = transactionId; + deserializedAcsChatMessageEventInThreadBaseProperties.threadId = threadId; + deserializedAcsChatMessageEventInThreadBaseProperties.messageId = messageId; + deserializedAcsChatMessageEventInThreadBaseProperties.senderDisplayName = senderDisplayName; + deserializedAcsChatMessageEventInThreadBaseProperties.type = type; + deserializedAcsChatMessageEventInThreadBaseProperties.version = version; + + return deserializedAcsChatMessageEventInThreadBaseProperties; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatMessageReceivedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatMessageReceivedEventData.java new file mode 100644 index 000000000000..3b3ab0e90291 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatMessageReceivedEventData.java @@ -0,0 +1,263 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatMessageReceived event. + */ +@Immutable +public final class AcsChatMessageReceivedEventData extends AcsChatMessageEventBaseProperties { + /* + * The body of the chat message + */ + @Generated + private String messageBody; + + /* + * The chat message metadata + */ + @Generated + private final Map metadata; + + /* + * The version of the message + */ + @Generated + private Long version; + + /* + * The type of the message + */ + @Generated + private String type; + + /* + * The display name of the sender + */ + @Generated + private String senderDisplayName; + + /* + * The chat message id + */ + @Generated + private String messageId; + + /* + * The chat thread id + */ + @Generated + private String threadId; + + /* + * The transaction id will be used as co-relation vector + */ + @Generated + private String transactionId; + + /** + * Creates an instance of AcsChatMessageReceivedEventData class. + * + * @param recipientCommunicationIdentifier the recipientCommunicationIdentifier value to set. + * @param senderCommunicationIdentifier the senderCommunicationIdentifier value to set. + * @param composeTime the composeTime value to set. + * @param metadata the metadata value to set. + */ + @Generated + private AcsChatMessageReceivedEventData(CommunicationIdentifierModel recipientCommunicationIdentifier, + CommunicationIdentifierModel senderCommunicationIdentifier, OffsetDateTime composeTime, + Map metadata) { + super(recipientCommunicationIdentifier, senderCommunicationIdentifier, composeTime); + this.metadata = metadata; + } + + /** + * Get the messageBody property: The body of the chat message. + * + * @return the messageBody value. + */ + @Generated + public String getMessageBody() { + return this.messageBody; + } + + /** + * Get the metadata property: The chat message metadata. + * + * @return the metadata value. + */ + @Generated + public Map getMetadata() { + return this.metadata; + } + + /** + * Get the version property: The version of the message. + * + * @return the version value. + */ + @Generated + @Override + public Long getVersion() { + return this.version; + } + + /** + * Get the type property: The type of the message. + * + * @return the type value. + */ + @Generated + @Override + public String getType() { + return this.type; + } + + /** + * Get the senderDisplayName property: The display name of the sender. + * + * @return the senderDisplayName value. + */ + @Generated + @Override + public String getSenderDisplayName() { + return this.senderDisplayName; + } + + /** + * Get the messageId property: The chat message id. + * + * @return the messageId value. + */ + @Generated + @Override + public String getMessageId() { + return this.messageId; + } + + /** + * Get the threadId property: The chat thread id. + * + * @return the threadId value. + */ + @Generated + @Override + public String getThreadId() { + return this.threadId; + } + + /** + * Get the transactionId property: The transaction id will be used as co-relation vector. + * + * @return the transactionId value. + */ + @Generated + @Override + public String getTransactionId() { + return this.transactionId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("recipientCommunicationIdentifier", getRecipientCommunicationIdentifier()); + jsonWriter.writeJsonField("senderCommunicationIdentifier", getSenderCommunicationIdentifier()); + jsonWriter.writeStringField("composeTime", + getComposeTime() == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(getComposeTime())); + jsonWriter.writeStringField("transactionId", getTransactionId()); + jsonWriter.writeStringField("threadId", getThreadId()); + jsonWriter.writeStringField("messageId", getMessageId()); + jsonWriter.writeStringField("senderDisplayName", getSenderDisplayName()); + jsonWriter.writeStringField("type", getType()); + jsonWriter.writeNumberField("version", getVersion()); + jsonWriter.writeMapField("metadata", this.metadata, (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("messageBody", this.messageBody); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsChatMessageReceivedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsChatMessageReceivedEventData 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 AcsChatMessageReceivedEventData. + */ + @Generated + public static AcsChatMessageReceivedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CommunicationIdentifierModel recipientCommunicationIdentifier = null; + CommunicationIdentifierModel senderCommunicationIdentifier = null; + OffsetDateTime composeTime = null; + String transactionId = null; + String threadId = null; + String messageId = null; + String senderDisplayName = null; + String type = null; + Long version = null; + Map metadata = null; + String messageBody = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("recipientCommunicationIdentifier".equals(fieldName)) { + recipientCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("senderCommunicationIdentifier".equals(fieldName)) { + senderCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("composeTime".equals(fieldName)) { + composeTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("transactionId".equals(fieldName)) { + transactionId = reader.getString(); + } else if ("threadId".equals(fieldName)) { + threadId = reader.getString(); + } else if ("messageId".equals(fieldName)) { + messageId = reader.getString(); + } else if ("senderDisplayName".equals(fieldName)) { + senderDisplayName = reader.getString(); + } else if ("type".equals(fieldName)) { + type = reader.getString(); + } else if ("version".equals(fieldName)) { + version = reader.getNullable(JsonReader::getLong); + } else if ("metadata".equals(fieldName)) { + metadata = reader.readMap(reader1 -> reader1.getString()); + } else if ("messageBody".equals(fieldName)) { + messageBody = reader.getString(); + } else { + reader.skipChildren(); + } + } + AcsChatMessageReceivedEventData deserializedAcsChatMessageReceivedEventData + = new AcsChatMessageReceivedEventData(recipientCommunicationIdentifier, senderCommunicationIdentifier, + composeTime, metadata); + deserializedAcsChatMessageReceivedEventData.transactionId = transactionId; + deserializedAcsChatMessageReceivedEventData.threadId = threadId; + deserializedAcsChatMessageReceivedEventData.messageId = messageId; + deserializedAcsChatMessageReceivedEventData.senderDisplayName = senderDisplayName; + deserializedAcsChatMessageReceivedEventData.type = type; + deserializedAcsChatMessageReceivedEventData.version = version; + deserializedAcsChatMessageReceivedEventData.messageBody = messageBody; + + return deserializedAcsChatMessageReceivedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatMessageReceivedInThreadEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatMessageReceivedInThreadEventData.java new file mode 100644 index 000000000000..6f878a5f3dbd --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatMessageReceivedInThreadEventData.java @@ -0,0 +1,256 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatMessageReceivedInThread event. + */ +@Immutable +public final class AcsChatMessageReceivedInThreadEventData extends AcsChatMessageEventInThreadBaseProperties { + /* + * The body of the chat message + */ + @Generated + private String messageBody; + + /* + * The chat message metadata + */ + @Generated + private final Map metadata; + + /* + * The version of the message + */ + @Generated + private Long version; + + /* + * The type of the message + */ + @Generated + private String type; + + /* + * The display name of the sender + */ + @Generated + private String senderDisplayName; + + /* + * The chat message id + */ + @Generated + private String messageId; + + /* + * The chat thread id + */ + @Generated + private String threadId; + + /* + * The transaction id will be used as co-relation vector + */ + @Generated + private String transactionId; + + /** + * Creates an instance of AcsChatMessageReceivedInThreadEventData class. + * + * @param senderCommunicationIdentifier the senderCommunicationIdentifier value to set. + * @param composeTime the composeTime value to set. + * @param metadata the metadata value to set. + */ + @Generated + private AcsChatMessageReceivedInThreadEventData(CommunicationIdentifierModel senderCommunicationIdentifier, + OffsetDateTime composeTime, Map metadata) { + super(senderCommunicationIdentifier, composeTime); + this.metadata = metadata; + } + + /** + * Get the messageBody property: The body of the chat message. + * + * @return the messageBody value. + */ + @Generated + public String getMessageBody() { + return this.messageBody; + } + + /** + * Get the metadata property: The chat message metadata. + * + * @return the metadata value. + */ + @Generated + public Map getMetadata() { + return this.metadata; + } + + /** + * Get the version property: The version of the message. + * + * @return the version value. + */ + @Generated + @Override + public Long getVersion() { + return this.version; + } + + /** + * Get the type property: The type of the message. + * + * @return the type value. + */ + @Generated + @Override + public String getType() { + return this.type; + } + + /** + * Get the senderDisplayName property: The display name of the sender. + * + * @return the senderDisplayName value. + */ + @Generated + @Override + public String getSenderDisplayName() { + return this.senderDisplayName; + } + + /** + * Get the messageId property: The chat message id. + * + * @return the messageId value. + */ + @Generated + @Override + public String getMessageId() { + return this.messageId; + } + + /** + * Get the threadId property: The chat thread id. + * + * @return the threadId value. + */ + @Generated + @Override + public String getThreadId() { + return this.threadId; + } + + /** + * Get the transactionId property: The transaction id will be used as co-relation vector. + * + * @return the transactionId value. + */ + @Generated + @Override + public String getTransactionId() { + return this.transactionId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("senderCommunicationIdentifier", getSenderCommunicationIdentifier()); + jsonWriter.writeStringField("composeTime", + getComposeTime() == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(getComposeTime())); + jsonWriter.writeStringField("transactionId", getTransactionId()); + jsonWriter.writeStringField("threadId", getThreadId()); + jsonWriter.writeStringField("messageId", getMessageId()); + jsonWriter.writeStringField("senderDisplayName", getSenderDisplayName()); + jsonWriter.writeStringField("type", getType()); + jsonWriter.writeNumberField("version", getVersion()); + jsonWriter.writeMapField("metadata", this.metadata, (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("messageBody", this.messageBody); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsChatMessageReceivedInThreadEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsChatMessageReceivedInThreadEventData 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 AcsChatMessageReceivedInThreadEventData. + */ + @Generated + public static AcsChatMessageReceivedInThreadEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CommunicationIdentifierModel senderCommunicationIdentifier = null; + OffsetDateTime composeTime = null; + String transactionId = null; + String threadId = null; + String messageId = null; + String senderDisplayName = null; + String type = null; + Long version = null; + Map metadata = null; + String messageBody = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("senderCommunicationIdentifier".equals(fieldName)) { + senderCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("composeTime".equals(fieldName)) { + composeTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("transactionId".equals(fieldName)) { + transactionId = reader.getString(); + } else if ("threadId".equals(fieldName)) { + threadId = reader.getString(); + } else if ("messageId".equals(fieldName)) { + messageId = reader.getString(); + } else if ("senderDisplayName".equals(fieldName)) { + senderDisplayName = reader.getString(); + } else if ("type".equals(fieldName)) { + type = reader.getString(); + } else if ("version".equals(fieldName)) { + version = reader.getNullable(JsonReader::getLong); + } else if ("metadata".equals(fieldName)) { + metadata = reader.readMap(reader1 -> reader1.getString()); + } else if ("messageBody".equals(fieldName)) { + messageBody = reader.getString(); + } else { + reader.skipChildren(); + } + } + AcsChatMessageReceivedInThreadEventData deserializedAcsChatMessageReceivedInThreadEventData + = new AcsChatMessageReceivedInThreadEventData(senderCommunicationIdentifier, composeTime, metadata); + deserializedAcsChatMessageReceivedInThreadEventData.transactionId = transactionId; + deserializedAcsChatMessageReceivedInThreadEventData.threadId = threadId; + deserializedAcsChatMessageReceivedInThreadEventData.messageId = messageId; + deserializedAcsChatMessageReceivedInThreadEventData.senderDisplayName = senderDisplayName; + deserializedAcsChatMessageReceivedInThreadEventData.type = type; + deserializedAcsChatMessageReceivedInThreadEventData.version = version; + deserializedAcsChatMessageReceivedInThreadEventData.messageBody = messageBody; + + return deserializedAcsChatMessageReceivedInThreadEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatParticipantAddedToThreadEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatParticipantAddedToThreadEventData.java new file mode 100644 index 000000000000..50e9309bdb02 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatParticipantAddedToThreadEventData.java @@ -0,0 +1,201 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatThreadParticipantAdded event. + */ +@Immutable +public final class AcsChatParticipantAddedToThreadEventData extends AcsChatEventInThreadBaseProperties { + /* + * The time at which the user was added to the thread + */ + @Generated + private final OffsetDateTime time; + + /* + * The communication identifier of the user who added the user + */ + @Generated + private final CommunicationIdentifierModel addedByCommunicationIdentifier; + + /* + * The details of the user who was added + */ + @Generated + private final AcsChatThreadParticipantProperties participantAdded; + + /* + * The version of the thread + */ + @Generated + private Long version; + + /* + * The chat thread id + */ + @Generated + private String threadId; + + /* + * The transaction id will be used as co-relation vector + */ + @Generated + private String transactionId; + + /** + * Creates an instance of AcsChatParticipantAddedToThreadEventData class. + * + * @param time the time value to set. + * @param addedByCommunicationIdentifier the addedByCommunicationIdentifier value to set. + * @param participantAdded the participantAdded value to set. + */ + @Generated + private AcsChatParticipantAddedToThreadEventData(OffsetDateTime time, + CommunicationIdentifierModel addedByCommunicationIdentifier, + AcsChatThreadParticipantProperties participantAdded) { + this.time = time; + this.addedByCommunicationIdentifier = addedByCommunicationIdentifier; + this.participantAdded = participantAdded; + } + + /** + * Get the time property: The time at which the user was added to the thread. + * + * @return the time value. + */ + @Generated + public OffsetDateTime getTime() { + return this.time; + } + + /** + * Get the addedByCommunicationIdentifier property: The communication identifier of the user who added the user. + * + * @return the addedByCommunicationIdentifier value. + */ + @Generated + public CommunicationIdentifierModel getAddedByCommunicationIdentifier() { + return this.addedByCommunicationIdentifier; + } + + /** + * Get the participantAdded property: The details of the user who was added. + * + * @return the participantAdded value. + */ + @Generated + public AcsChatThreadParticipantProperties getParticipantAdded() { + return this.participantAdded; + } + + /** + * Get the version property: The version of the thread. + * + * @return the version value. + */ + @Generated + public Long getVersion() { + return this.version; + } + + /** + * Get the threadId property: The chat thread id. + * + * @return the threadId value. + */ + @Generated + @Override + public String getThreadId() { + return this.threadId; + } + + /** + * Get the transactionId property: The transaction id will be used as co-relation vector. + * + * @return the transactionId value. + */ + @Generated + @Override + public String getTransactionId() { + return this.transactionId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("transactionId", getTransactionId()); + jsonWriter.writeStringField("threadId", getThreadId()); + jsonWriter.writeStringField("time", + this.time == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.time)); + jsonWriter.writeJsonField("addedByCommunicationIdentifier", this.addedByCommunicationIdentifier); + jsonWriter.writeJsonField("participantAdded", this.participantAdded); + jsonWriter.writeNumberField("version", this.version); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsChatParticipantAddedToThreadEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsChatParticipantAddedToThreadEventData 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 AcsChatParticipantAddedToThreadEventData. + */ + @Generated + public static AcsChatParticipantAddedToThreadEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String transactionId = null; + String threadId = null; + OffsetDateTime time = null; + CommunicationIdentifierModel addedByCommunicationIdentifier = null; + AcsChatThreadParticipantProperties participantAdded = null; + Long version = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("transactionId".equals(fieldName)) { + transactionId = reader.getString(); + } else if ("threadId".equals(fieldName)) { + threadId = reader.getString(); + } else if ("time".equals(fieldName)) { + time = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("addedByCommunicationIdentifier".equals(fieldName)) { + addedByCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("participantAdded".equals(fieldName)) { + participantAdded = AcsChatThreadParticipantProperties.fromJson(reader); + } else if ("version".equals(fieldName)) { + version = reader.getNullable(JsonReader::getLong); + } else { + reader.skipChildren(); + } + } + AcsChatParticipantAddedToThreadEventData deserializedAcsChatParticipantAddedToThreadEventData + = new AcsChatParticipantAddedToThreadEventData(time, addedByCommunicationIdentifier, participantAdded); + deserializedAcsChatParticipantAddedToThreadEventData.transactionId = transactionId; + deserializedAcsChatParticipantAddedToThreadEventData.threadId = threadId; + deserializedAcsChatParticipantAddedToThreadEventData.version = version; + + return deserializedAcsChatParticipantAddedToThreadEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatParticipantAddedToThreadWithUserEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatParticipantAddedToThreadWithUserEventData.java new file mode 100644 index 000000000000..92f51735ec27 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatParticipantAddedToThreadWithUserEventData.java @@ -0,0 +1,218 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatParticipantAddedToThreadWithUser + * event. + */ +@Immutable +public final class AcsChatParticipantAddedToThreadWithUserEventData extends AcsChatThreadEventBaseProperties { + /* + * The time at which the user was added to the thread + */ + @Generated + private final OffsetDateTime time; + + /* + * The communication identifier of the user who added the user + */ + @Generated + private final CommunicationIdentifierModel addedByCommunicationIdentifier; + + /* + * The details of the user who was added + */ + @Generated + private final AcsChatThreadParticipantProperties participantAdded; + + /* + * The version of the thread + */ + @Generated + private Long version; + + /* + * The chat thread id + */ + @Generated + private String threadId; + + /* + * The transaction id will be used as co-relation vector + */ + @Generated + private String transactionId; + + /** + * Creates an instance of AcsChatParticipantAddedToThreadWithUserEventData class. + * + * @param recipientCommunicationIdentifier the recipientCommunicationIdentifier value to set. + * @param createTime the createTime value to set. + * @param time the time value to set. + * @param addedByCommunicationIdentifier the addedByCommunicationIdentifier value to set. + * @param participantAdded the participantAdded value to set. + */ + @Generated + private AcsChatParticipantAddedToThreadWithUserEventData( + CommunicationIdentifierModel recipientCommunicationIdentifier, OffsetDateTime createTime, OffsetDateTime time, + CommunicationIdentifierModel addedByCommunicationIdentifier, + AcsChatThreadParticipantProperties participantAdded) { + super(recipientCommunicationIdentifier, createTime); + this.time = time; + this.addedByCommunicationIdentifier = addedByCommunicationIdentifier; + this.participantAdded = participantAdded; + } + + /** + * Get the time property: The time at which the user was added to the thread. + * + * @return the time value. + */ + @Generated + public OffsetDateTime getTime() { + return this.time; + } + + /** + * Get the addedByCommunicationIdentifier property: The communication identifier of the user who added the user. + * + * @return the addedByCommunicationIdentifier value. + */ + @Generated + public CommunicationIdentifierModel getAddedByCommunicationIdentifier() { + return this.addedByCommunicationIdentifier; + } + + /** + * Get the participantAdded property: The details of the user who was added. + * + * @return the participantAdded value. + */ + @Generated + public AcsChatThreadParticipantProperties getParticipantAdded() { + return this.participantAdded; + } + + /** + * Get the version property: The version of the thread. + * + * @return the version value. + */ + @Generated + @Override + public Long getVersion() { + return this.version; + } + + /** + * Get the threadId property: The chat thread id. + * + * @return the threadId value. + */ + @Generated + @Override + public String getThreadId() { + return this.threadId; + } + + /** + * Get the transactionId property: The transaction id will be used as co-relation vector. + * + * @return the transactionId value. + */ + @Generated + @Override + public String getTransactionId() { + return this.transactionId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("recipientCommunicationIdentifier", getRecipientCommunicationIdentifier()); + jsonWriter.writeStringField("createTime", + getCreateTime() == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(getCreateTime())); + jsonWriter.writeStringField("transactionId", getTransactionId()); + jsonWriter.writeStringField("threadId", getThreadId()); + jsonWriter.writeNumberField("version", getVersion()); + jsonWriter.writeStringField("time", + this.time == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.time)); + jsonWriter.writeJsonField("addedByCommunicationIdentifier", this.addedByCommunicationIdentifier); + jsonWriter.writeJsonField("participantAdded", this.participantAdded); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsChatParticipantAddedToThreadWithUserEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsChatParticipantAddedToThreadWithUserEventData 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 AcsChatParticipantAddedToThreadWithUserEventData. + */ + @Generated + public static AcsChatParticipantAddedToThreadWithUserEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CommunicationIdentifierModel recipientCommunicationIdentifier = null; + OffsetDateTime createTime = null; + String transactionId = null; + String threadId = null; + Long version = null; + OffsetDateTime time = null; + CommunicationIdentifierModel addedByCommunicationIdentifier = null; + AcsChatThreadParticipantProperties participantAdded = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("recipientCommunicationIdentifier".equals(fieldName)) { + recipientCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("createTime".equals(fieldName)) { + createTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("transactionId".equals(fieldName)) { + transactionId = reader.getString(); + } else if ("threadId".equals(fieldName)) { + threadId = reader.getString(); + } else if ("version".equals(fieldName)) { + version = reader.getNullable(JsonReader::getLong); + } else if ("time".equals(fieldName)) { + time = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("addedByCommunicationIdentifier".equals(fieldName)) { + addedByCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("participantAdded".equals(fieldName)) { + participantAdded = AcsChatThreadParticipantProperties.fromJson(reader); + } else { + reader.skipChildren(); + } + } + AcsChatParticipantAddedToThreadWithUserEventData deserializedAcsChatParticipantAddedToThreadWithUserEventData + = new AcsChatParticipantAddedToThreadWithUserEventData(recipientCommunicationIdentifier, createTime, + time, addedByCommunicationIdentifier, participantAdded); + deserializedAcsChatParticipantAddedToThreadWithUserEventData.transactionId = transactionId; + deserializedAcsChatParticipantAddedToThreadWithUserEventData.threadId = threadId; + deserializedAcsChatParticipantAddedToThreadWithUserEventData.version = version; + + return deserializedAcsChatParticipantAddedToThreadWithUserEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatParticipantRemovedFromThreadEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatParticipantRemovedFromThreadEventData.java new file mode 100644 index 000000000000..d986c3d3dc16 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatParticipantRemovedFromThreadEventData.java @@ -0,0 +1,202 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatThreadParticipantRemoved event. + */ +@Immutable +public final class AcsChatParticipantRemovedFromThreadEventData extends AcsChatEventInThreadBaseProperties { + /* + * The time at which the user was removed to the thread + */ + @Generated + private final OffsetDateTime time; + + /* + * The communication identifier of the user who removed the user + */ + @Generated + private final CommunicationIdentifierModel removedByCommunicationIdentifier; + + /* + * The details of the user who was removed + */ + @Generated + private final AcsChatThreadParticipantProperties participantRemoved; + + /* + * The version of the thread + */ + @Generated + private Long version; + + /* + * The chat thread id + */ + @Generated + private String threadId; + + /* + * The transaction id will be used as co-relation vector + */ + @Generated + private String transactionId; + + /** + * Creates an instance of AcsChatParticipantRemovedFromThreadEventData class. + * + * @param time the time value to set. + * @param removedByCommunicationIdentifier the removedByCommunicationIdentifier value to set. + * @param participantRemoved the participantRemoved value to set. + */ + @Generated + private AcsChatParticipantRemovedFromThreadEventData(OffsetDateTime time, + CommunicationIdentifierModel removedByCommunicationIdentifier, + AcsChatThreadParticipantProperties participantRemoved) { + this.time = time; + this.removedByCommunicationIdentifier = removedByCommunicationIdentifier; + this.participantRemoved = participantRemoved; + } + + /** + * Get the time property: The time at which the user was removed to the thread. + * + * @return the time value. + */ + @Generated + public OffsetDateTime getTime() { + return this.time; + } + + /** + * Get the removedByCommunicationIdentifier property: The communication identifier of the user who removed the user. + * + * @return the removedByCommunicationIdentifier value. + */ + @Generated + public CommunicationIdentifierModel getRemovedByCommunicationIdentifier() { + return this.removedByCommunicationIdentifier; + } + + /** + * Get the participantRemoved property: The details of the user who was removed. + * + * @return the participantRemoved value. + */ + @Generated + public AcsChatThreadParticipantProperties getParticipantRemoved() { + return this.participantRemoved; + } + + /** + * Get the version property: The version of the thread. + * + * @return the version value. + */ + @Generated + public Long getVersion() { + return this.version; + } + + /** + * Get the threadId property: The chat thread id. + * + * @return the threadId value. + */ + @Generated + @Override + public String getThreadId() { + return this.threadId; + } + + /** + * Get the transactionId property: The transaction id will be used as co-relation vector. + * + * @return the transactionId value. + */ + @Generated + @Override + public String getTransactionId() { + return this.transactionId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("transactionId", getTransactionId()); + jsonWriter.writeStringField("threadId", getThreadId()); + jsonWriter.writeStringField("time", + this.time == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.time)); + jsonWriter.writeJsonField("removedByCommunicationIdentifier", this.removedByCommunicationIdentifier); + jsonWriter.writeJsonField("participantRemoved", this.participantRemoved); + jsonWriter.writeNumberField("version", this.version); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsChatParticipantRemovedFromThreadEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsChatParticipantRemovedFromThreadEventData 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 AcsChatParticipantRemovedFromThreadEventData. + */ + @Generated + public static AcsChatParticipantRemovedFromThreadEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String transactionId = null; + String threadId = null; + OffsetDateTime time = null; + CommunicationIdentifierModel removedByCommunicationIdentifier = null; + AcsChatThreadParticipantProperties participantRemoved = null; + Long version = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("transactionId".equals(fieldName)) { + transactionId = reader.getString(); + } else if ("threadId".equals(fieldName)) { + threadId = reader.getString(); + } else if ("time".equals(fieldName)) { + time = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("removedByCommunicationIdentifier".equals(fieldName)) { + removedByCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("participantRemoved".equals(fieldName)) { + participantRemoved = AcsChatThreadParticipantProperties.fromJson(reader); + } else if ("version".equals(fieldName)) { + version = reader.getNullable(JsonReader::getLong); + } else { + reader.skipChildren(); + } + } + AcsChatParticipantRemovedFromThreadEventData deserializedAcsChatParticipantRemovedFromThreadEventData + = new AcsChatParticipantRemovedFromThreadEventData(time, removedByCommunicationIdentifier, + participantRemoved); + deserializedAcsChatParticipantRemovedFromThreadEventData.transactionId = transactionId; + deserializedAcsChatParticipantRemovedFromThreadEventData.threadId = threadId; + deserializedAcsChatParticipantRemovedFromThreadEventData.version = version; + + return deserializedAcsChatParticipantRemovedFromThreadEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatParticipantRemovedFromThreadWithUserEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatParticipantRemovedFromThreadWithUserEventData.java new file mode 100644 index 000000000000..8195fdf15ec6 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatParticipantRemovedFromThreadWithUserEventData.java @@ -0,0 +1,219 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a + * Microsoft.Communication.ChatParticipantRemovedFromThreadWithUser event. + */ +@Immutable +public final class AcsChatParticipantRemovedFromThreadWithUserEventData extends AcsChatThreadEventBaseProperties { + /* + * The time at which the user was removed to the thread + */ + @Generated + private final OffsetDateTime time; + + /* + * The communication identifier of the user who removed the user + */ + @Generated + private final CommunicationIdentifierModel removedByCommunicationIdentifier; + + /* + * The details of the user who was removed + */ + @Generated + private final AcsChatThreadParticipantProperties participantRemoved; + + /* + * The version of the thread + */ + @Generated + private Long version; + + /* + * The chat thread id + */ + @Generated + private String threadId; + + /* + * The transaction id will be used as co-relation vector + */ + @Generated + private String transactionId; + + /** + * Creates an instance of AcsChatParticipantRemovedFromThreadWithUserEventData class. + * + * @param recipientCommunicationIdentifier the recipientCommunicationIdentifier value to set. + * @param createTime the createTime value to set. + * @param time the time value to set. + * @param removedByCommunicationIdentifier the removedByCommunicationIdentifier value to set. + * @param participantRemoved the participantRemoved value to set. + */ + @Generated + private AcsChatParticipantRemovedFromThreadWithUserEventData( + CommunicationIdentifierModel recipientCommunicationIdentifier, OffsetDateTime createTime, OffsetDateTime time, + CommunicationIdentifierModel removedByCommunicationIdentifier, + AcsChatThreadParticipantProperties participantRemoved) { + super(recipientCommunicationIdentifier, createTime); + this.time = time; + this.removedByCommunicationIdentifier = removedByCommunicationIdentifier; + this.participantRemoved = participantRemoved; + } + + /** + * Get the time property: The time at which the user was removed to the thread. + * + * @return the time value. + */ + @Generated + public OffsetDateTime getTime() { + return this.time; + } + + /** + * Get the removedByCommunicationIdentifier property: The communication identifier of the user who removed the user. + * + * @return the removedByCommunicationIdentifier value. + */ + @Generated + public CommunicationIdentifierModel getRemovedByCommunicationIdentifier() { + return this.removedByCommunicationIdentifier; + } + + /** + * Get the participantRemoved property: The details of the user who was removed. + * + * @return the participantRemoved value. + */ + @Generated + public AcsChatThreadParticipantProperties getParticipantRemoved() { + return this.participantRemoved; + } + + /** + * Get the version property: The version of the thread. + * + * @return the version value. + */ + @Generated + @Override + public Long getVersion() { + return this.version; + } + + /** + * Get the threadId property: The chat thread id. + * + * @return the threadId value. + */ + @Generated + @Override + public String getThreadId() { + return this.threadId; + } + + /** + * Get the transactionId property: The transaction id will be used as co-relation vector. + * + * @return the transactionId value. + */ + @Generated + @Override + public String getTransactionId() { + return this.transactionId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("recipientCommunicationIdentifier", getRecipientCommunicationIdentifier()); + jsonWriter.writeStringField("createTime", + getCreateTime() == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(getCreateTime())); + jsonWriter.writeStringField("transactionId", getTransactionId()); + jsonWriter.writeStringField("threadId", getThreadId()); + jsonWriter.writeNumberField("version", getVersion()); + jsonWriter.writeStringField("time", + this.time == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.time)); + jsonWriter.writeJsonField("removedByCommunicationIdentifier", this.removedByCommunicationIdentifier); + jsonWriter.writeJsonField("participantRemoved", this.participantRemoved); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsChatParticipantRemovedFromThreadWithUserEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsChatParticipantRemovedFromThreadWithUserEventData 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 AcsChatParticipantRemovedFromThreadWithUserEventData. + */ + @Generated + public static AcsChatParticipantRemovedFromThreadWithUserEventData fromJson(JsonReader jsonReader) + throws IOException { + return jsonReader.readObject(reader -> { + CommunicationIdentifierModel recipientCommunicationIdentifier = null; + OffsetDateTime createTime = null; + String transactionId = null; + String threadId = null; + Long version = null; + OffsetDateTime time = null; + CommunicationIdentifierModel removedByCommunicationIdentifier = null; + AcsChatThreadParticipantProperties participantRemoved = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("recipientCommunicationIdentifier".equals(fieldName)) { + recipientCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("createTime".equals(fieldName)) { + createTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("transactionId".equals(fieldName)) { + transactionId = reader.getString(); + } else if ("threadId".equals(fieldName)) { + threadId = reader.getString(); + } else if ("version".equals(fieldName)) { + version = reader.getNullable(JsonReader::getLong); + } else if ("time".equals(fieldName)) { + time = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("removedByCommunicationIdentifier".equals(fieldName)) { + removedByCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("participantRemoved".equals(fieldName)) { + participantRemoved = AcsChatThreadParticipantProperties.fromJson(reader); + } else { + reader.skipChildren(); + } + } + AcsChatParticipantRemovedFromThreadWithUserEventData deserializedAcsChatParticipantRemovedFromThreadWithUserEventData + = new AcsChatParticipantRemovedFromThreadWithUserEventData(recipientCommunicationIdentifier, createTime, + time, removedByCommunicationIdentifier, participantRemoved); + deserializedAcsChatParticipantRemovedFromThreadWithUserEventData.transactionId = transactionId; + deserializedAcsChatParticipantRemovedFromThreadWithUserEventData.threadId = threadId; + deserializedAcsChatParticipantRemovedFromThreadWithUserEventData.version = version; + + return deserializedAcsChatParticipantRemovedFromThreadWithUserEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatThreadCreatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatThreadCreatedEventData.java new file mode 100644 index 000000000000..98e28ca5cff5 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatThreadCreatedEventData.java @@ -0,0 +1,236 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.BinaryData; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.List; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatThreadCreated event. + */ +@Immutable +public final class AcsChatThreadCreatedEventData extends AcsChatThreadEventInThreadBaseProperties { + /* + * The communication identifier of the user who created the thread + */ + @Generated + private final CommunicationIdentifierModel createdByCommunicationIdentifier; + + /* + * The thread properties + */ + @Generated + private final Map properties; + + /* + * The thread metadata + */ + @Generated + private final Map metadata; + + /* + * The list of properties of participants who are part of the thread + */ + @Generated + private final List participants; + + /* + * The version of the thread + */ + @Generated + private Long version; + + /* + * The chat thread id + */ + @Generated + private String threadId; + + /* + * The transaction id will be used as co-relation vector + */ + @Generated + private String transactionId; + + /** + * Creates an instance of AcsChatThreadCreatedEventData class. + * + * @param createTime the createTime value to set. + * @param createdByCommunicationIdentifier the createdByCommunicationIdentifier value to set. + * @param properties the properties value to set. + * @param metadata the metadata value to set. + * @param participants the participants value to set. + */ + @Generated + private AcsChatThreadCreatedEventData(OffsetDateTime createTime, + CommunicationIdentifierModel createdByCommunicationIdentifier, Map properties, + Map metadata, List participants) { + super(createTime); + this.createdByCommunicationIdentifier = createdByCommunicationIdentifier; + this.properties = properties; + this.metadata = metadata; + this.participants = participants; + } + + /** + * Get the createdByCommunicationIdentifier property: The communication identifier of the user who created the + * thread. + * + * @return the createdByCommunicationIdentifier value. + */ + @Generated + public CommunicationIdentifierModel getCreatedByCommunicationIdentifier() { + return this.createdByCommunicationIdentifier; + } + + /** + * Get the properties property: The thread properties. + * + * @return the properties value. + */ + @Generated + public Map getProperties() { + return this.properties; + } + + /** + * Get the metadata property: The thread metadata. + * + * @return the metadata value. + */ + @Generated + public Map getMetadata() { + return this.metadata; + } + + /** + * Get the participants property: The list of properties of participants who are part of the thread. + * + * @return the participants value. + */ + @Generated + public List getParticipants() { + return this.participants; + } + + /** + * Get the version property: The version of the thread. + * + * @return the version value. + */ + @Generated + @Override + public Long getVersion() { + return this.version; + } + + /** + * Get the threadId property: The chat thread id. + * + * @return the threadId value. + */ + @Generated + @Override + public String getThreadId() { + return this.threadId; + } + + /** + * Get the transactionId property: The transaction id will be used as co-relation vector. + * + * @return the transactionId value. + */ + @Generated + @Override + public String getTransactionId() { + return this.transactionId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("createTime", + getCreateTime() == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(getCreateTime())); + jsonWriter.writeStringField("transactionId", getTransactionId()); + jsonWriter.writeStringField("threadId", getThreadId()); + jsonWriter.writeNumberField("version", getVersion()); + jsonWriter.writeJsonField("createdByCommunicationIdentifier", this.createdByCommunicationIdentifier); + jsonWriter.writeMapField("properties", this.properties, + (writer, element) -> writer.writeUntyped(element == null ? null : element.toObject(Object.class))); + jsonWriter.writeMapField("metadata", this.metadata, (writer, element) -> writer.writeString(element)); + jsonWriter.writeArrayField("participants", this.participants, (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsChatThreadCreatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsChatThreadCreatedEventData 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 AcsChatThreadCreatedEventData. + */ + @Generated + public static AcsChatThreadCreatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OffsetDateTime createTime = null; + String transactionId = null; + String threadId = null; + Long version = null; + CommunicationIdentifierModel createdByCommunicationIdentifier = null; + Map properties = null; + Map metadata = null; + List participants = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("createTime".equals(fieldName)) { + createTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("transactionId".equals(fieldName)) { + transactionId = reader.getString(); + } else if ("threadId".equals(fieldName)) { + threadId = reader.getString(); + } else if ("version".equals(fieldName)) { + version = reader.getNullable(JsonReader::getLong); + } else if ("createdByCommunicationIdentifier".equals(fieldName)) { + createdByCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("properties".equals(fieldName)) { + properties = reader.readMap(reader1 -> reader1 + .getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); + } else if ("metadata".equals(fieldName)) { + metadata = reader.readMap(reader1 -> reader1.getString()); + } else if ("participants".equals(fieldName)) { + participants = reader.readArray(reader1 -> AcsChatThreadParticipantProperties.fromJson(reader1)); + } else { + reader.skipChildren(); + } + } + AcsChatThreadCreatedEventData deserializedAcsChatThreadCreatedEventData = new AcsChatThreadCreatedEventData( + createTime, createdByCommunicationIdentifier, properties, metadata, participants); + deserializedAcsChatThreadCreatedEventData.transactionId = transactionId; + deserializedAcsChatThreadCreatedEventData.threadId = threadId; + deserializedAcsChatThreadCreatedEventData.version = version; + + return deserializedAcsChatThreadCreatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatThreadCreatedWithUserEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatThreadCreatedWithUserEventData.java new file mode 100644 index 000000000000..6c5e35e8bb06 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatThreadCreatedWithUserEventData.java @@ -0,0 +1,243 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.BinaryData; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.List; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatThreadCreatedWithUser event. + */ +@Immutable +public final class AcsChatThreadCreatedWithUserEventData extends AcsChatThreadEventBaseProperties { + /* + * The communication identifier of the user who created the thread + */ + @Generated + private final CommunicationIdentifierModel createdByCommunicationIdentifier; + + /* + * The thread properties + */ + @Generated + private final Map properties; + + /* + * The thread metadata + */ + @Generated + private final Map metadata; + + /* + * The list of properties of participants who are part of the thread + */ + @Generated + private final List participants; + + /* + * The version of the thread + */ + @Generated + private Long version; + + /* + * The chat thread id + */ + @Generated + private String threadId; + + /* + * The transaction id will be used as co-relation vector + */ + @Generated + private String transactionId; + + /** + * Creates an instance of AcsChatThreadCreatedWithUserEventData class. + * + * @param recipientCommunicationIdentifier the recipientCommunicationIdentifier value to set. + * @param createTime the createTime value to set. + * @param createdByCommunicationIdentifier the createdByCommunicationIdentifier value to set. + * @param properties the properties value to set. + * @param metadata the metadata value to set. + * @param participants the participants value to set. + */ + @Generated + private AcsChatThreadCreatedWithUserEventData(CommunicationIdentifierModel recipientCommunicationIdentifier, + OffsetDateTime createTime, CommunicationIdentifierModel createdByCommunicationIdentifier, + Map properties, Map metadata, + List participants) { + super(recipientCommunicationIdentifier, createTime); + this.createdByCommunicationIdentifier = createdByCommunicationIdentifier; + this.properties = properties; + this.metadata = metadata; + this.participants = participants; + } + + /** + * Get the createdByCommunicationIdentifier property: The communication identifier of the user who created the + * thread. + * + * @return the createdByCommunicationIdentifier value. + */ + @Generated + public CommunicationIdentifierModel getCreatedByCommunicationIdentifier() { + return this.createdByCommunicationIdentifier; + } + + /** + * Get the properties property: The thread properties. + * + * @return the properties value. + */ + @Generated + public Map getProperties() { + return this.properties; + } + + /** + * Get the metadata property: The thread metadata. + * + * @return the metadata value. + */ + @Generated + public Map getMetadata() { + return this.metadata; + } + + /** + * Get the participants property: The list of properties of participants who are part of the thread. + * + * @return the participants value. + */ + @Generated + public List getParticipants() { + return this.participants; + } + + /** + * Get the version property: The version of the thread. + * + * @return the version value. + */ + @Generated + @Override + public Long getVersion() { + return this.version; + } + + /** + * Get the threadId property: The chat thread id. + * + * @return the threadId value. + */ + @Generated + @Override + public String getThreadId() { + return this.threadId; + } + + /** + * Get the transactionId property: The transaction id will be used as co-relation vector. + * + * @return the transactionId value. + */ + @Generated + @Override + public String getTransactionId() { + return this.transactionId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("recipientCommunicationIdentifier", getRecipientCommunicationIdentifier()); + jsonWriter.writeStringField("createTime", + getCreateTime() == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(getCreateTime())); + jsonWriter.writeStringField("transactionId", getTransactionId()); + jsonWriter.writeStringField("threadId", getThreadId()); + jsonWriter.writeNumberField("version", getVersion()); + jsonWriter.writeJsonField("createdByCommunicationIdentifier", this.createdByCommunicationIdentifier); + jsonWriter.writeMapField("properties", this.properties, + (writer, element) -> writer.writeUntyped(element == null ? null : element.toObject(Object.class))); + jsonWriter.writeMapField("metadata", this.metadata, (writer, element) -> writer.writeString(element)); + jsonWriter.writeArrayField("participants", this.participants, (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsChatThreadCreatedWithUserEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsChatThreadCreatedWithUserEventData 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 AcsChatThreadCreatedWithUserEventData. + */ + @Generated + public static AcsChatThreadCreatedWithUserEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CommunicationIdentifierModel recipientCommunicationIdentifier = null; + OffsetDateTime createTime = null; + String transactionId = null; + String threadId = null; + Long version = null; + CommunicationIdentifierModel createdByCommunicationIdentifier = null; + Map properties = null; + Map metadata = null; + List participants = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("recipientCommunicationIdentifier".equals(fieldName)) { + recipientCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("createTime".equals(fieldName)) { + createTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("transactionId".equals(fieldName)) { + transactionId = reader.getString(); + } else if ("threadId".equals(fieldName)) { + threadId = reader.getString(); + } else if ("version".equals(fieldName)) { + version = reader.getNullable(JsonReader::getLong); + } else if ("createdByCommunicationIdentifier".equals(fieldName)) { + createdByCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("properties".equals(fieldName)) { + properties = reader.readMap(reader1 -> reader1 + .getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); + } else if ("metadata".equals(fieldName)) { + metadata = reader.readMap(reader1 -> reader1.getString()); + } else if ("participants".equals(fieldName)) { + participants = reader.readArray(reader1 -> AcsChatThreadParticipantProperties.fromJson(reader1)); + } else { + reader.skipChildren(); + } + } + AcsChatThreadCreatedWithUserEventData deserializedAcsChatThreadCreatedWithUserEventData + = new AcsChatThreadCreatedWithUserEventData(recipientCommunicationIdentifier, createTime, + createdByCommunicationIdentifier, properties, metadata, participants); + deserializedAcsChatThreadCreatedWithUserEventData.transactionId = transactionId; + deserializedAcsChatThreadCreatedWithUserEventData.threadId = threadId; + deserializedAcsChatThreadCreatedWithUserEventData.version = version; + + return deserializedAcsChatThreadCreatedWithUserEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatThreadDeletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatThreadDeletedEventData.java new file mode 100644 index 000000000000..51ca29a5d562 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatThreadDeletedEventData.java @@ -0,0 +1,188 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatThreadDeleted event. + */ +@Immutable +public final class AcsChatThreadDeletedEventData extends AcsChatThreadEventInThreadBaseProperties { + /* + * The communication identifier of the user who deleted the thread + */ + @Generated + private final CommunicationIdentifierModel deletedByCommunicationIdentifier; + + /* + * The deletion time of the thread + */ + @Generated + private final OffsetDateTime deleteTime; + + /* + * The version of the thread + */ + @Generated + private Long version; + + /* + * The chat thread id + */ + @Generated + private String threadId; + + /* + * The transaction id will be used as co-relation vector + */ + @Generated + private String transactionId; + + /** + * Creates an instance of AcsChatThreadDeletedEventData class. + * + * @param createTime the createTime value to set. + * @param deletedByCommunicationIdentifier the deletedByCommunicationIdentifier value to set. + * @param deleteTime the deleteTime value to set. + */ + @Generated + private AcsChatThreadDeletedEventData(OffsetDateTime createTime, + CommunicationIdentifierModel deletedByCommunicationIdentifier, OffsetDateTime deleteTime) { + super(createTime); + this.deletedByCommunicationIdentifier = deletedByCommunicationIdentifier; + this.deleteTime = deleteTime; + } + + /** + * Get the deletedByCommunicationIdentifier property: The communication identifier of the user who deleted the + * thread. + * + * @return the deletedByCommunicationIdentifier value. + */ + @Generated + public CommunicationIdentifierModel getDeletedByCommunicationIdentifier() { + return this.deletedByCommunicationIdentifier; + } + + /** + * Get the deleteTime property: The deletion time of the thread. + * + * @return the deleteTime value. + */ + @Generated + public OffsetDateTime getDeleteTime() { + return this.deleteTime; + } + + /** + * Get the version property: The version of the thread. + * + * @return the version value. + */ + @Generated + @Override + public Long getVersion() { + return this.version; + } + + /** + * Get the threadId property: The chat thread id. + * + * @return the threadId value. + */ + @Generated + @Override + public String getThreadId() { + return this.threadId; + } + + /** + * Get the transactionId property: The transaction id will be used as co-relation vector. + * + * @return the transactionId value. + */ + @Generated + @Override + public String getTransactionId() { + return this.transactionId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("createTime", + getCreateTime() == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(getCreateTime())); + jsonWriter.writeStringField("transactionId", getTransactionId()); + jsonWriter.writeStringField("threadId", getThreadId()); + jsonWriter.writeNumberField("version", getVersion()); + jsonWriter.writeJsonField("deletedByCommunicationIdentifier", this.deletedByCommunicationIdentifier); + jsonWriter.writeStringField("deleteTime", + this.deleteTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.deleteTime)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsChatThreadDeletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsChatThreadDeletedEventData 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 AcsChatThreadDeletedEventData. + */ + @Generated + public static AcsChatThreadDeletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OffsetDateTime createTime = null; + String transactionId = null; + String threadId = null; + Long version = null; + CommunicationIdentifierModel deletedByCommunicationIdentifier = null; + OffsetDateTime deleteTime = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("createTime".equals(fieldName)) { + createTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("transactionId".equals(fieldName)) { + transactionId = reader.getString(); + } else if ("threadId".equals(fieldName)) { + threadId = reader.getString(); + } else if ("version".equals(fieldName)) { + version = reader.getNullable(JsonReader::getLong); + } else if ("deletedByCommunicationIdentifier".equals(fieldName)) { + deletedByCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("deleteTime".equals(fieldName)) { + deleteTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else { + reader.skipChildren(); + } + } + AcsChatThreadDeletedEventData deserializedAcsChatThreadDeletedEventData + = new AcsChatThreadDeletedEventData(createTime, deletedByCommunicationIdentifier, deleteTime); + deserializedAcsChatThreadDeletedEventData.transactionId = transactionId; + deserializedAcsChatThreadDeletedEventData.threadId = threadId; + deserializedAcsChatThreadDeletedEventData.version = version; + + return deserializedAcsChatThreadDeletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatThreadEventBaseProperties.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatThreadEventBaseProperties.java new file mode 100644 index 000000000000..a7271a7e7340 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatThreadEventBaseProperties.java @@ -0,0 +1,174 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of common properties of all chat thread events. + */ +@Immutable +public class AcsChatThreadEventBaseProperties extends AcsChatEventBaseProperties { + /* + * The original creation time of the thread + */ + @Generated + private final OffsetDateTime createTime; + + /* + * The version of the thread + */ + @Generated + private Long version; + + /* + * The chat thread id + */ + @Generated + private String threadId; + + /* + * The transaction id will be used as co-relation vector + */ + @Generated + private String transactionId; + + /** + * Creates an instance of AcsChatThreadEventBaseProperties class. + * + * @param recipientCommunicationIdentifier the recipientCommunicationIdentifier value to set. + * @param createTime the createTime value to set. + */ + @Generated + protected AcsChatThreadEventBaseProperties(CommunicationIdentifierModel recipientCommunicationIdentifier, + OffsetDateTime createTime) { + super(recipientCommunicationIdentifier); + this.createTime = createTime; + } + + /** + * Get the createTime property: The original creation time of the thread. + * + * @return the createTime value. + */ + @Generated + public OffsetDateTime getCreateTime() { + return this.createTime; + } + + /** + * Get the version property: The version of the thread. + * + * @return the version value. + */ + @Generated + public Long getVersion() { + return this.version; + } + + /** + * Set the version property: The version of the thread. + * + * @param version the version value to set. + * @return the AcsChatThreadEventBaseProperties object itself. + */ + @Generated + AcsChatThreadEventBaseProperties setVersion(Long version) { + this.version = version; + return this; + } + + /** + * Get the threadId property: The chat thread id. + * + * @return the threadId value. + */ + @Generated + @Override + public String getThreadId() { + return this.threadId; + } + + /** + * Get the transactionId property: The transaction id will be used as co-relation vector. + * + * @return the transactionId value. + */ + @Generated + @Override + public String getTransactionId() { + return this.transactionId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("recipientCommunicationIdentifier", getRecipientCommunicationIdentifier()); + jsonWriter.writeStringField("transactionId", getTransactionId()); + jsonWriter.writeStringField("threadId", getThreadId()); + jsonWriter.writeStringField("createTime", + this.createTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.createTime)); + jsonWriter.writeNumberField("version", this.version); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsChatThreadEventBaseProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsChatThreadEventBaseProperties 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 AcsChatThreadEventBaseProperties. + */ + @Generated + public static AcsChatThreadEventBaseProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CommunicationIdentifierModel recipientCommunicationIdentifier = null; + String transactionId = null; + String threadId = null; + OffsetDateTime createTime = null; + Long version = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("recipientCommunicationIdentifier".equals(fieldName)) { + recipientCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("transactionId".equals(fieldName)) { + transactionId = reader.getString(); + } else if ("threadId".equals(fieldName)) { + threadId = reader.getString(); + } else if ("createTime".equals(fieldName)) { + createTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("version".equals(fieldName)) { + version = reader.getNullable(JsonReader::getLong); + } else { + reader.skipChildren(); + } + } + AcsChatThreadEventBaseProperties deserializedAcsChatThreadEventBaseProperties + = new AcsChatThreadEventBaseProperties(recipientCommunicationIdentifier, createTime); + deserializedAcsChatThreadEventBaseProperties.transactionId = transactionId; + deserializedAcsChatThreadEventBaseProperties.threadId = threadId; + deserializedAcsChatThreadEventBaseProperties.version = version; + + return deserializedAcsChatThreadEventBaseProperties; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatThreadEventInThreadBaseProperties.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatThreadEventInThreadBaseProperties.java new file mode 100644 index 000000000000..71d2f3e12bea --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatThreadEventInThreadBaseProperties.java @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of common properties of all chat thread events. + */ +@Immutable +public class AcsChatThreadEventInThreadBaseProperties extends AcsChatEventInThreadBaseProperties { + /* + * The original creation time of the thread + */ + @Generated + private final OffsetDateTime createTime; + + /* + * The version of the thread + */ + @Generated + private Long version; + + /* + * The chat thread id + */ + @Generated + private String threadId; + + /* + * The transaction id will be used as co-relation vector + */ + @Generated + private String transactionId; + + /** + * Creates an instance of AcsChatThreadEventInThreadBaseProperties class. + * + * @param createTime the createTime value to set. + */ + @Generated + protected AcsChatThreadEventInThreadBaseProperties(OffsetDateTime createTime) { + this.createTime = createTime; + } + + /** + * Get the createTime property: The original creation time of the thread. + * + * @return the createTime value. + */ + @Generated + public OffsetDateTime getCreateTime() { + return this.createTime; + } + + /** + * Get the version property: The version of the thread. + * + * @return the version value. + */ + @Generated + public Long getVersion() { + return this.version; + } + + /** + * Set the version property: The version of the thread. + * + * @param version the version value to set. + * @return the AcsChatThreadEventInThreadBaseProperties object itself. + */ + @Generated + AcsChatThreadEventInThreadBaseProperties setVersion(Long version) { + this.version = version; + return this; + } + + /** + * Get the threadId property: The chat thread id. + * + * @return the threadId value. + */ + @Generated + @Override + public String getThreadId() { + return this.threadId; + } + + /** + * Get the transactionId property: The transaction id will be used as co-relation vector. + * + * @return the transactionId value. + */ + @Generated + @Override + public String getTransactionId() { + return this.transactionId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("transactionId", getTransactionId()); + jsonWriter.writeStringField("threadId", getThreadId()); + jsonWriter.writeStringField("createTime", + this.createTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.createTime)); + jsonWriter.writeNumberField("version", this.version); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsChatThreadEventInThreadBaseProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsChatThreadEventInThreadBaseProperties 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 AcsChatThreadEventInThreadBaseProperties. + */ + @Generated + public static AcsChatThreadEventInThreadBaseProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String transactionId = null; + String threadId = null; + OffsetDateTime createTime = null; + Long version = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("transactionId".equals(fieldName)) { + transactionId = reader.getString(); + } else if ("threadId".equals(fieldName)) { + threadId = reader.getString(); + } else if ("createTime".equals(fieldName)) { + createTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("version".equals(fieldName)) { + version = reader.getNullable(JsonReader::getLong); + } else { + reader.skipChildren(); + } + } + AcsChatThreadEventInThreadBaseProperties deserializedAcsChatThreadEventInThreadBaseProperties + = new AcsChatThreadEventInThreadBaseProperties(createTime); + deserializedAcsChatThreadEventInThreadBaseProperties.transactionId = transactionId; + deserializedAcsChatThreadEventInThreadBaseProperties.threadId = threadId; + deserializedAcsChatThreadEventInThreadBaseProperties.version = version; + + return deserializedAcsChatThreadEventInThreadBaseProperties; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatThreadParticipantProperties.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatThreadParticipantProperties.java new file mode 100644 index 000000000000..5e30814bc44b --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatThreadParticipantProperties.java @@ -0,0 +1,131 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.Map; + +/** + * Schema of the chat thread participant. + */ +@Immutable +public final class AcsChatThreadParticipantProperties implements JsonSerializable { + /* + * The name of the user + */ + @Generated + private String displayName; + + /* + * The communication identifier of the user + */ + @Generated + private final CommunicationIdentifierModel participantCommunicationIdentifier; + + /* + * The metadata of the user + */ + @Generated + private final Map metadata; + + /** + * Creates an instance of AcsChatThreadParticipantProperties class. + * + * @param participantCommunicationIdentifier the participantCommunicationIdentifier value to set. + * @param metadata the metadata value to set. + */ + @Generated + private AcsChatThreadParticipantProperties(CommunicationIdentifierModel participantCommunicationIdentifier, + Map metadata) { + this.participantCommunicationIdentifier = participantCommunicationIdentifier; + this.metadata = metadata; + } + + /** + * Get the displayName property: The name of the user. + * + * @return the displayName value. + */ + @Generated + public String getDisplayName() { + return this.displayName; + } + + /** + * Get the participantCommunicationIdentifier property: The communication identifier of the user. + * + * @return the participantCommunicationIdentifier value. + */ + @Generated + public CommunicationIdentifierModel getParticipantCommunicationIdentifier() { + return this.participantCommunicationIdentifier; + } + + /** + * Get the metadata property: The metadata of the user. + * + * @return the metadata value. + */ + @Generated + public Map getMetadata() { + return this.metadata; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("participantCommunicationIdentifier", this.participantCommunicationIdentifier); + jsonWriter.writeMapField("metadata", this.metadata, (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("displayName", this.displayName); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsChatThreadParticipantProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsChatThreadParticipantProperties 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 AcsChatThreadParticipantProperties. + */ + @Generated + public static AcsChatThreadParticipantProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CommunicationIdentifierModel participantCommunicationIdentifier = null; + Map metadata = null; + String displayName = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("participantCommunicationIdentifier".equals(fieldName)) { + participantCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("metadata".equals(fieldName)) { + metadata = reader.readMap(reader1 -> reader1.getString()); + } else if ("displayName".equals(fieldName)) { + displayName = reader.getString(); + } else { + reader.skipChildren(); + } + } + AcsChatThreadParticipantProperties deserializedAcsChatThreadParticipantProperties + = new AcsChatThreadParticipantProperties(participantCommunicationIdentifier, metadata); + deserializedAcsChatThreadParticipantProperties.displayName = displayName; + + return deserializedAcsChatThreadParticipantProperties; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatThreadPropertiesUpdatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatThreadPropertiesUpdatedEventData.java new file mode 100644 index 000000000000..2cdee9fcf0ca --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatThreadPropertiesUpdatedEventData.java @@ -0,0 +1,238 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.BinaryData; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatThreadPropertiesUpdated event. + */ +@Immutable +public final class AcsChatThreadPropertiesUpdatedEventData extends AcsChatThreadEventInThreadBaseProperties { + /* + * The communication identifier of the user who updated the thread properties + */ + @Generated + private final CommunicationIdentifierModel editedByCommunicationIdentifier; + + /* + * The time at which the properties of the thread were updated + */ + @Generated + private final OffsetDateTime editTime; + + /* + * The updated thread properties + */ + @Generated + private final Map properties; + + /* + * The thread metadata + */ + @Generated + private final Map metadata; + + /* + * The version of the thread + */ + @Generated + private Long version; + + /* + * The chat thread id + */ + @Generated + private String threadId; + + /* + * The transaction id will be used as co-relation vector + */ + @Generated + private String transactionId; + + /** + * Creates an instance of AcsChatThreadPropertiesUpdatedEventData class. + * + * @param createTime the createTime value to set. + * @param editedByCommunicationIdentifier the editedByCommunicationIdentifier value to set. + * @param editTime the editTime value to set. + * @param properties the properties value to set. + * @param metadata the metadata value to set. + */ + @Generated + private AcsChatThreadPropertiesUpdatedEventData(OffsetDateTime createTime, + CommunicationIdentifierModel editedByCommunicationIdentifier, OffsetDateTime editTime, + Map properties, Map metadata) { + super(createTime); + this.editedByCommunicationIdentifier = editedByCommunicationIdentifier; + this.editTime = editTime; + this.properties = properties; + this.metadata = metadata; + } + + /** + * Get the editedByCommunicationIdentifier property: The communication identifier of the user who updated the thread + * properties. + * + * @return the editedByCommunicationIdentifier value. + */ + @Generated + public CommunicationIdentifierModel getEditedByCommunicationIdentifier() { + return this.editedByCommunicationIdentifier; + } + + /** + * Get the editTime property: The time at which the properties of the thread were updated. + * + * @return the editTime value. + */ + @Generated + public OffsetDateTime getEditTime() { + return this.editTime; + } + + /** + * Get the properties property: The updated thread properties. + * + * @return the properties value. + */ + @Generated + public Map getProperties() { + return this.properties; + } + + /** + * Get the metadata property: The thread metadata. + * + * @return the metadata value. + */ + @Generated + public Map getMetadata() { + return this.metadata; + } + + /** + * Get the version property: The version of the thread. + * + * @return the version value. + */ + @Generated + @Override + public Long getVersion() { + return this.version; + } + + /** + * Get the threadId property: The chat thread id. + * + * @return the threadId value. + */ + @Generated + @Override + public String getThreadId() { + return this.threadId; + } + + /** + * Get the transactionId property: The transaction id will be used as co-relation vector. + * + * @return the transactionId value. + */ + @Generated + @Override + public String getTransactionId() { + return this.transactionId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("createTime", + getCreateTime() == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(getCreateTime())); + jsonWriter.writeStringField("transactionId", getTransactionId()); + jsonWriter.writeStringField("threadId", getThreadId()); + jsonWriter.writeNumberField("version", getVersion()); + jsonWriter.writeJsonField("editedByCommunicationIdentifier", this.editedByCommunicationIdentifier); + jsonWriter.writeStringField("editTime", + this.editTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.editTime)); + jsonWriter.writeMapField("properties", this.properties, + (writer, element) -> writer.writeUntyped(element == null ? null : element.toObject(Object.class))); + jsonWriter.writeMapField("metadata", this.metadata, (writer, element) -> writer.writeString(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsChatThreadPropertiesUpdatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsChatThreadPropertiesUpdatedEventData 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 AcsChatThreadPropertiesUpdatedEventData. + */ + @Generated + public static AcsChatThreadPropertiesUpdatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OffsetDateTime createTime = null; + String transactionId = null; + String threadId = null; + Long version = null; + CommunicationIdentifierModel editedByCommunicationIdentifier = null; + OffsetDateTime editTime = null; + Map properties = null; + Map metadata = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("createTime".equals(fieldName)) { + createTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("transactionId".equals(fieldName)) { + transactionId = reader.getString(); + } else if ("threadId".equals(fieldName)) { + threadId = reader.getString(); + } else if ("version".equals(fieldName)) { + version = reader.getNullable(JsonReader::getLong); + } else if ("editedByCommunicationIdentifier".equals(fieldName)) { + editedByCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("editTime".equals(fieldName)) { + editTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("properties".equals(fieldName)) { + properties = reader.readMap(reader1 -> reader1 + .getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); + } else if ("metadata".equals(fieldName)) { + metadata = reader.readMap(reader1 -> reader1.getString()); + } else { + reader.skipChildren(); + } + } + AcsChatThreadPropertiesUpdatedEventData deserializedAcsChatThreadPropertiesUpdatedEventData + = new AcsChatThreadPropertiesUpdatedEventData(createTime, editedByCommunicationIdentifier, editTime, + properties, metadata); + deserializedAcsChatThreadPropertiesUpdatedEventData.transactionId = transactionId; + deserializedAcsChatThreadPropertiesUpdatedEventData.threadId = threadId; + deserializedAcsChatThreadPropertiesUpdatedEventData.version = version; + + return deserializedAcsChatThreadPropertiesUpdatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatThreadPropertiesUpdatedPerUserEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatThreadPropertiesUpdatedPerUserEventData.java new file mode 100644 index 000000000000..fc58f728e639 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatThreadPropertiesUpdatedPerUserEventData.java @@ -0,0 +1,245 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.BinaryData; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatThreadPropertiesUpdatedPerUser + * event. + */ +@Immutable +public final class AcsChatThreadPropertiesUpdatedPerUserEventData extends AcsChatThreadEventBaseProperties { + /* + * The communication identifier of the user who updated the thread properties + */ + @Generated + private final CommunicationIdentifierModel editedByCommunicationIdentifier; + + /* + * The time at which the properties of the thread were updated + */ + @Generated + private final OffsetDateTime editTime; + + /* + * The thread metadata + */ + @Generated + private final Map metadata; + + /* + * The updated thread properties + */ + @Generated + private final Map properties; + + /* + * The version of the thread + */ + @Generated + private Long version; + + /* + * The chat thread id + */ + @Generated + private String threadId; + + /* + * The transaction id will be used as co-relation vector + */ + @Generated + private String transactionId; + + /** + * Creates an instance of AcsChatThreadPropertiesUpdatedPerUserEventData class. + * + * @param recipientCommunicationIdentifier the recipientCommunicationIdentifier value to set. + * @param createTime the createTime value to set. + * @param editedByCommunicationIdentifier the editedByCommunicationIdentifier value to set. + * @param editTime the editTime value to set. + * @param metadata the metadata value to set. + * @param properties the properties value to set. + */ + @Generated + private AcsChatThreadPropertiesUpdatedPerUserEventData( + CommunicationIdentifierModel recipientCommunicationIdentifier, OffsetDateTime createTime, + CommunicationIdentifierModel editedByCommunicationIdentifier, OffsetDateTime editTime, + Map metadata, Map properties) { + super(recipientCommunicationIdentifier, createTime); + this.editedByCommunicationIdentifier = editedByCommunicationIdentifier; + this.editTime = editTime; + this.metadata = metadata; + this.properties = properties; + } + + /** + * Get the editedByCommunicationIdentifier property: The communication identifier of the user who updated the thread + * properties. + * + * @return the editedByCommunicationIdentifier value. + */ + @Generated + public CommunicationIdentifierModel getEditedByCommunicationIdentifier() { + return this.editedByCommunicationIdentifier; + } + + /** + * Get the editTime property: The time at which the properties of the thread were updated. + * + * @return the editTime value. + */ + @Generated + public OffsetDateTime getEditTime() { + return this.editTime; + } + + /** + * Get the metadata property: The thread metadata. + * + * @return the metadata value. + */ + @Generated + public Map getMetadata() { + return this.metadata; + } + + /** + * Get the properties property: The updated thread properties. + * + * @return the properties value. + */ + @Generated + public Map getProperties() { + return this.properties; + } + + /** + * Get the version property: The version of the thread. + * + * @return the version value. + */ + @Generated + @Override + public Long getVersion() { + return this.version; + } + + /** + * Get the threadId property: The chat thread id. + * + * @return the threadId value. + */ + @Generated + @Override + public String getThreadId() { + return this.threadId; + } + + /** + * Get the transactionId property: The transaction id will be used as co-relation vector. + * + * @return the transactionId value. + */ + @Generated + @Override + public String getTransactionId() { + return this.transactionId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("recipientCommunicationIdentifier", getRecipientCommunicationIdentifier()); + jsonWriter.writeStringField("createTime", + getCreateTime() == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(getCreateTime())); + jsonWriter.writeStringField("transactionId", getTransactionId()); + jsonWriter.writeStringField("threadId", getThreadId()); + jsonWriter.writeNumberField("version", getVersion()); + jsonWriter.writeJsonField("editedByCommunicationIdentifier", this.editedByCommunicationIdentifier); + jsonWriter.writeStringField("editTime", + this.editTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.editTime)); + jsonWriter.writeMapField("metadata", this.metadata, (writer, element) -> writer.writeString(element)); + jsonWriter.writeMapField("properties", this.properties, + (writer, element) -> writer.writeUntyped(element == null ? null : element.toObject(Object.class))); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsChatThreadPropertiesUpdatedPerUserEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsChatThreadPropertiesUpdatedPerUserEventData 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 AcsChatThreadPropertiesUpdatedPerUserEventData. + */ + @Generated + public static AcsChatThreadPropertiesUpdatedPerUserEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CommunicationIdentifierModel recipientCommunicationIdentifier = null; + OffsetDateTime createTime = null; + String transactionId = null; + String threadId = null; + Long version = null; + CommunicationIdentifierModel editedByCommunicationIdentifier = null; + OffsetDateTime editTime = null; + Map metadata = null; + Map properties = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("recipientCommunicationIdentifier".equals(fieldName)) { + recipientCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("createTime".equals(fieldName)) { + createTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("transactionId".equals(fieldName)) { + transactionId = reader.getString(); + } else if ("threadId".equals(fieldName)) { + threadId = reader.getString(); + } else if ("version".equals(fieldName)) { + version = reader.getNullable(JsonReader::getLong); + } else if ("editedByCommunicationIdentifier".equals(fieldName)) { + editedByCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("editTime".equals(fieldName)) { + editTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("metadata".equals(fieldName)) { + metadata = reader.readMap(reader1 -> reader1.getString()); + } else if ("properties".equals(fieldName)) { + properties = reader.readMap(reader1 -> reader1 + .getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); + } else { + reader.skipChildren(); + } + } + AcsChatThreadPropertiesUpdatedPerUserEventData deserializedAcsChatThreadPropertiesUpdatedPerUserEventData + = new AcsChatThreadPropertiesUpdatedPerUserEventData(recipientCommunicationIdentifier, createTime, + editedByCommunicationIdentifier, editTime, metadata, properties); + deserializedAcsChatThreadPropertiesUpdatedPerUserEventData.transactionId = transactionId; + deserializedAcsChatThreadPropertiesUpdatedPerUserEventData.threadId = threadId; + deserializedAcsChatThreadPropertiesUpdatedPerUserEventData.version = version; + + return deserializedAcsChatThreadPropertiesUpdatedPerUserEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatThreadWithUserDeletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatThreadWithUserDeletedEventData.java new file mode 100644 index 000000000000..f7fc914a5427 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsChatThreadWithUserDeletedEventData.java @@ -0,0 +1,195 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.ChatThreadWithUserDeleted event. + */ +@Immutable +public final class AcsChatThreadWithUserDeletedEventData extends AcsChatThreadEventBaseProperties { + /* + * The communication identifier of the user who deleted the thread + */ + @Generated + private final CommunicationIdentifierModel deletedByCommunicationIdentifier; + + /* + * The deletion time of the thread + */ + @Generated + private final OffsetDateTime deleteTime; + + /* + * The version of the thread + */ + @Generated + private Long version; + + /* + * The chat thread id + */ + @Generated + private String threadId; + + /* + * The transaction id will be used as co-relation vector + */ + @Generated + private String transactionId; + + /** + * Creates an instance of AcsChatThreadWithUserDeletedEventData class. + * + * @param recipientCommunicationIdentifier the recipientCommunicationIdentifier value to set. + * @param createTime the createTime value to set. + * @param deletedByCommunicationIdentifier the deletedByCommunicationIdentifier value to set. + * @param deleteTime the deleteTime value to set. + */ + @Generated + private AcsChatThreadWithUserDeletedEventData(CommunicationIdentifierModel recipientCommunicationIdentifier, + OffsetDateTime createTime, CommunicationIdentifierModel deletedByCommunicationIdentifier, + OffsetDateTime deleteTime) { + super(recipientCommunicationIdentifier, createTime); + this.deletedByCommunicationIdentifier = deletedByCommunicationIdentifier; + this.deleteTime = deleteTime; + } + + /** + * Get the deletedByCommunicationIdentifier property: The communication identifier of the user who deleted the + * thread. + * + * @return the deletedByCommunicationIdentifier value. + */ + @Generated + public CommunicationIdentifierModel getDeletedByCommunicationIdentifier() { + return this.deletedByCommunicationIdentifier; + } + + /** + * Get the deleteTime property: The deletion time of the thread. + * + * @return the deleteTime value. + */ + @Generated + public OffsetDateTime getDeleteTime() { + return this.deleteTime; + } + + /** + * Get the version property: The version of the thread. + * + * @return the version value. + */ + @Generated + @Override + public Long getVersion() { + return this.version; + } + + /** + * Get the threadId property: The chat thread id. + * + * @return the threadId value. + */ + @Generated + @Override + public String getThreadId() { + return this.threadId; + } + + /** + * Get the transactionId property: The transaction id will be used as co-relation vector. + * + * @return the transactionId value. + */ + @Generated + @Override + public String getTransactionId() { + return this.transactionId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("recipientCommunicationIdentifier", getRecipientCommunicationIdentifier()); + jsonWriter.writeStringField("createTime", + getCreateTime() == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(getCreateTime())); + jsonWriter.writeStringField("transactionId", getTransactionId()); + jsonWriter.writeStringField("threadId", getThreadId()); + jsonWriter.writeNumberField("version", getVersion()); + jsonWriter.writeJsonField("deletedByCommunicationIdentifier", this.deletedByCommunicationIdentifier); + jsonWriter.writeStringField("deleteTime", + this.deleteTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.deleteTime)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsChatThreadWithUserDeletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsChatThreadWithUserDeletedEventData 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 AcsChatThreadWithUserDeletedEventData. + */ + @Generated + public static AcsChatThreadWithUserDeletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CommunicationIdentifierModel recipientCommunicationIdentifier = null; + OffsetDateTime createTime = null; + String transactionId = null; + String threadId = null; + Long version = null; + CommunicationIdentifierModel deletedByCommunicationIdentifier = null; + OffsetDateTime deleteTime = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("recipientCommunicationIdentifier".equals(fieldName)) { + recipientCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("createTime".equals(fieldName)) { + createTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("transactionId".equals(fieldName)) { + transactionId = reader.getString(); + } else if ("threadId".equals(fieldName)) { + threadId = reader.getString(); + } else if ("version".equals(fieldName)) { + version = reader.getNullable(JsonReader::getLong); + } else if ("deletedByCommunicationIdentifier".equals(fieldName)) { + deletedByCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("deleteTime".equals(fieldName)) { + deleteTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else { + reader.skipChildren(); + } + } + AcsChatThreadWithUserDeletedEventData deserializedAcsChatThreadWithUserDeletedEventData + = new AcsChatThreadWithUserDeletedEventData(recipientCommunicationIdentifier, createTime, + deletedByCommunicationIdentifier, deleteTime); + deserializedAcsChatThreadWithUserDeletedEventData.transactionId = transactionId; + deserializedAcsChatThreadWithUserDeletedEventData.threadId = threadId; + deserializedAcsChatThreadWithUserDeletedEventData.version = version; + + return deserializedAcsChatThreadWithUserDeletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsEmailDeliveryReportReceivedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsEmailDeliveryReportReceivedEventData.java new file mode 100644 index 000000000000..3ffdd8bdef37 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsEmailDeliveryReportReceivedEventData.java @@ -0,0 +1,228 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.EmailDeliveryReportReceived event. + */ +@Immutable +public final class AcsEmailDeliveryReportReceivedEventData + implements JsonSerializable { + /* + * The Sender Email Address + */ + @Generated + private final String sender; + + /* + * The recipient Email Address + */ + @Generated + private final String recipient; + + /* + * The Internet Message Id of the email that has been sent + */ + @Generated + private final String internetMessageId; + + /* + * The Id of the email that has been sent + */ + @Generated + private String messageId; + + /* + * The status of the email. Any value other than Delivered is considered failed. + */ + @Generated + private final AcsEmailDeliveryReportStatus status; + + /* + * Detailed information about the status if any + */ + @Generated + private final AcsEmailDeliveryReportStatusDetails deliveryStatusDetails; + + /* + * The time at which the email delivery report received timestamp + */ + @Generated + private final OffsetDateTime deliveryAttemptTimestamp; + + /** + * Creates an instance of AcsEmailDeliveryReportReceivedEventData class. + * + * @param sender the sender value to set. + * @param recipient the recipient value to set. + * @param internetMessageId the internetMessageId value to set. + * @param status the status value to set. + * @param deliveryStatusDetails the deliveryStatusDetails value to set. + * @param deliveryAttemptTimestamp the deliveryAttemptTimestamp value to set. + */ + @Generated + private AcsEmailDeliveryReportReceivedEventData(String sender, String recipient, String internetMessageId, + AcsEmailDeliveryReportStatus status, AcsEmailDeliveryReportStatusDetails deliveryStatusDetails, + OffsetDateTime deliveryAttemptTimestamp) { + this.sender = sender; + this.recipient = recipient; + this.internetMessageId = internetMessageId; + this.status = status; + this.deliveryStatusDetails = deliveryStatusDetails; + this.deliveryAttemptTimestamp = deliveryAttemptTimestamp; + } + + /** + * Get the sender property: The Sender Email Address. + * + * @return the sender value. + */ + @Generated + public String getSender() { + return this.sender; + } + + /** + * Get the recipient property: The recipient Email Address. + * + * @return the recipient value. + */ + @Generated + public String getRecipient() { + return this.recipient; + } + + /** + * Get the internetMessageId property: The Internet Message Id of the email that has been sent. + * + * @return the internetMessageId value. + */ + @Generated + public String getInternetMessageId() { + return this.internetMessageId; + } + + /** + * Get the messageId property: The Id of the email that has been sent. + * + * @return the messageId value. + */ + @Generated + public String getMessageId() { + return this.messageId; + } + + /** + * Get the status property: The status of the email. Any value other than Delivered is considered failed. + * + * @return the status value. + */ + @Generated + public AcsEmailDeliveryReportStatus getStatus() { + return this.status; + } + + /** + * Get the deliveryStatusDetails property: Detailed information about the status if any. + * + * @return the deliveryStatusDetails value. + */ + @Generated + public AcsEmailDeliveryReportStatusDetails getDeliveryStatusDetails() { + return this.deliveryStatusDetails; + } + + /** + * Get the deliveryAttemptTimestamp property: The time at which the email delivery report received timestamp. + * + * @return the deliveryAttemptTimestamp value. + */ + @Generated + public OffsetDateTime getDeliveryAttemptTimestamp() { + return this.deliveryAttemptTimestamp; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("sender", this.sender); + jsonWriter.writeStringField("recipient", this.recipient); + jsonWriter.writeStringField("internetMessageId", this.internetMessageId); + jsonWriter.writeStringField("status", this.status == null ? null : this.status.toString()); + jsonWriter.writeJsonField("deliveryStatusDetails", this.deliveryStatusDetails); + jsonWriter.writeStringField("deliveryAttemptTimestamp", + this.deliveryAttemptTimestamp == null + ? null + : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.deliveryAttemptTimestamp)); + jsonWriter.writeStringField("messageId", this.messageId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsEmailDeliveryReportReceivedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsEmailDeliveryReportReceivedEventData 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 AcsEmailDeliveryReportReceivedEventData. + */ + @Generated + public static AcsEmailDeliveryReportReceivedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String sender = null; + String recipient = null; + String internetMessageId = null; + AcsEmailDeliveryReportStatus status = null; + AcsEmailDeliveryReportStatusDetails deliveryStatusDetails = null; + OffsetDateTime deliveryAttemptTimestamp = null; + String messageId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("sender".equals(fieldName)) { + sender = reader.getString(); + } else if ("recipient".equals(fieldName)) { + recipient = reader.getString(); + } else if ("internetMessageId".equals(fieldName)) { + internetMessageId = reader.getString(); + } else if ("status".equals(fieldName)) { + status = AcsEmailDeliveryReportStatus.fromString(reader.getString()); + } else if ("deliveryStatusDetails".equals(fieldName)) { + deliveryStatusDetails = AcsEmailDeliveryReportStatusDetails.fromJson(reader); + } else if ("deliveryAttemptTimestamp".equals(fieldName)) { + deliveryAttemptTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("messageId".equals(fieldName)) { + messageId = reader.getString(); + } else { + reader.skipChildren(); + } + } + AcsEmailDeliveryReportReceivedEventData deserializedAcsEmailDeliveryReportReceivedEventData + = new AcsEmailDeliveryReportReceivedEventData(sender, recipient, internetMessageId, status, + deliveryStatusDetails, deliveryAttemptTimestamp); + deserializedAcsEmailDeliveryReportReceivedEventData.messageId = messageId; + + return deserializedAcsEmailDeliveryReportReceivedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsEmailDeliveryReportStatus.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsEmailDeliveryReportStatus.java new file mode 100644 index 000000000000..9c3f7549949d --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsEmailDeliveryReportStatus.java @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The status of the email. Any value other than Delivered is considered failed. + */ +public final class AcsEmailDeliveryReportStatus extends ExpandableStringEnum { + /** + * Hard bounce detected while sending the email. + */ + @Generated + public static final AcsEmailDeliveryReportStatus BOUNCED = fromString("Bounced"); + + /** + * The email was delivered. + */ + @Generated + public static final AcsEmailDeliveryReportStatus DELIVERED = fromString("Delivered"); + + /** + * The email failed to be delivered. + */ + @Generated + public static final AcsEmailDeliveryReportStatus FAILED = fromString("Failed"); + + /** + * The message was identified as spam and was rejected or blocked (not quarantined). + */ + @Generated + public static final AcsEmailDeliveryReportStatus FILTERED_SPAM = fromString("FilteredSpam"); + + /** + * The message was quarantined (as spam, bulk mail, or phishing). For more information, see Quarantined email + * messages in EOP (EXCHANGE ONLINE PROTECTION). + */ + @Generated + public static final AcsEmailDeliveryReportStatus QUARANTINED = fromString("Quarantined"); + + /** + * The email was suppressed. + */ + @Generated + public static final AcsEmailDeliveryReportStatus SUPPRESSED = fromString("Suppressed"); + + /** + * Creates a new instance of AcsEmailDeliveryReportStatus value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public AcsEmailDeliveryReportStatus() { + } + + /** + * Creates or finds a AcsEmailDeliveryReportStatus from its string representation. + * + * @param name a name to look for. + * @return the corresponding AcsEmailDeliveryReportStatus. + */ + @Generated + public static AcsEmailDeliveryReportStatus fromString(String name) { + return fromString(name, AcsEmailDeliveryReportStatus.class); + } + + /** + * Gets known AcsEmailDeliveryReportStatus values. + * + * @return known AcsEmailDeliveryReportStatus values. + */ + @Generated + public static Collection values() { + return values(AcsEmailDeliveryReportStatus.class); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsEmailDeliveryReportStatusDetails.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsEmailDeliveryReportStatusDetails.java new file mode 100644 index 000000000000..4335005f42c5 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsEmailDeliveryReportStatusDetails.java @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Detailed information about the status if any. + */ +@Immutable +public final class AcsEmailDeliveryReportStatusDetails + implements JsonSerializable { + /* + * Detailed status message + */ + @Generated + private String statusMessage; + + /* + * Recipient mail server host name + */ + @Generated + private String recipientMailServerHostName; + + /** + * Creates an instance of AcsEmailDeliveryReportStatusDetails class. + */ + @Generated + private AcsEmailDeliveryReportStatusDetails() { + } + + /** + * Get the statusMessage property: Detailed status message. + * + * @return the statusMessage value. + */ + @Generated + public String getStatusMessage() { + return this.statusMessage; + } + + /** + * Get the recipientMailServerHostName property: Recipient mail server host name. + * + * @return the recipientMailServerHostName value. + */ + @Generated + public String getRecipientMailServerHostName() { + return this.recipientMailServerHostName; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("statusMessage", this.statusMessage); + jsonWriter.writeStringField("recipientMailServerHostName", this.recipientMailServerHostName); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsEmailDeliveryReportStatusDetails from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsEmailDeliveryReportStatusDetails 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 AcsEmailDeliveryReportStatusDetails. + */ + @Generated + public static AcsEmailDeliveryReportStatusDetails fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AcsEmailDeliveryReportStatusDetails deserializedAcsEmailDeliveryReportStatusDetails + = new AcsEmailDeliveryReportStatusDetails(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("statusMessage".equals(fieldName)) { + deserializedAcsEmailDeliveryReportStatusDetails.statusMessage = reader.getString(); + } else if ("recipientMailServerHostName".equals(fieldName)) { + deserializedAcsEmailDeliveryReportStatusDetails.recipientMailServerHostName = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAcsEmailDeliveryReportStatusDetails; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsEmailEngagementTrackingReportReceivedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsEmailEngagementTrackingReportReceivedEventData.java new file mode 100644 index 000000000000..24a7a454ec77 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsEmailEngagementTrackingReportReceivedEventData.java @@ -0,0 +1,224 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.EmailEngagementTrackingReportReceived + * event. + */ +@Immutable +public final class AcsEmailEngagementTrackingReportReceivedEventData + implements JsonSerializable { + /* + * The Sender Email Address + */ + @Generated + private String sender; + + /* + * The Recipient Email Address + */ + @Generated + private String recipient; + + /* + * The Id of the email that has been sent + */ + @Generated + private String messageId; + + /* + * The time at which the user interacted with the email + */ + @Generated + private final OffsetDateTime userActionTimestamp; + + /* + * The context of the type of engagement user had with email + */ + @Generated + private String engagementContext; + + /* + * The user agent interacting with the email + */ + @Generated + private String userAgent; + + /* + * The type of engagement user have with email + */ + @Generated + private final AcsUserEngagement engagementType; + + /** + * Creates an instance of AcsEmailEngagementTrackingReportReceivedEventData class. + * + * @param userActionTimestamp the userActionTimestamp value to set. + * @param engagementType the engagementType value to set. + */ + @Generated + private AcsEmailEngagementTrackingReportReceivedEventData(OffsetDateTime userActionTimestamp, + AcsUserEngagement engagementType) { + this.userActionTimestamp = userActionTimestamp; + this.engagementType = engagementType; + } + + /** + * Get the sender property: The Sender Email Address. + * + * @return the sender value. + */ + @Generated + public String getSender() { + return this.sender; + } + + /** + * Get the recipient property: The Recipient Email Address. + * + * @return the recipient value. + */ + @Generated + public String getRecipient() { + return this.recipient; + } + + /** + * Get the messageId property: The Id of the email that has been sent. + * + * @return the messageId value. + */ + @Generated + public String getMessageId() { + return this.messageId; + } + + /** + * Get the userActionTimestamp property: The time at which the user interacted with the email. + * + * @return the userActionTimestamp value. + */ + @Generated + public OffsetDateTime getUserActionTimestamp() { + return this.userActionTimestamp; + } + + /** + * Get the engagementContext property: The context of the type of engagement user had with email. + * + * @return the engagementContext value. + */ + @Generated + public String getEngagementContext() { + return this.engagementContext; + } + + /** + * Get the userAgent property: The user agent interacting with the email. + * + * @return the userAgent value. + */ + @Generated + public String getUserAgent() { + return this.userAgent; + } + + /** + * Get the engagementType property: The type of engagement user have with email. + * + * @return the engagementType value. + */ + @Generated + public AcsUserEngagement getEngagementType() { + return this.engagementType; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("userActionTimestamp", + this.userActionTimestamp == null + ? null + : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.userActionTimestamp)); + jsonWriter.writeStringField("engagementType", + this.engagementType == null ? null : this.engagementType.toString()); + jsonWriter.writeStringField("sender", this.sender); + jsonWriter.writeStringField("recipient", this.recipient); + jsonWriter.writeStringField("messageId", this.messageId); + jsonWriter.writeStringField("engagementContext", this.engagementContext); + jsonWriter.writeStringField("userAgent", this.userAgent); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsEmailEngagementTrackingReportReceivedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsEmailEngagementTrackingReportReceivedEventData 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 AcsEmailEngagementTrackingReportReceivedEventData. + */ + @Generated + public static AcsEmailEngagementTrackingReportReceivedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OffsetDateTime userActionTimestamp = null; + AcsUserEngagement engagementType = null; + String sender = null; + String recipient = null; + String messageId = null; + String engagementContext = null; + String userAgent = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("userActionTimestamp".equals(fieldName)) { + userActionTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("engagementType".equals(fieldName)) { + engagementType = AcsUserEngagement.fromString(reader.getString()); + } else if ("sender".equals(fieldName)) { + sender = reader.getString(); + } else if ("recipient".equals(fieldName)) { + recipient = reader.getString(); + } else if ("messageId".equals(fieldName)) { + messageId = reader.getString(); + } else if ("engagementContext".equals(fieldName)) { + engagementContext = reader.getString(); + } else if ("userAgent".equals(fieldName)) { + userAgent = reader.getString(); + } else { + reader.skipChildren(); + } + } + AcsEmailEngagementTrackingReportReceivedEventData deserializedAcsEmailEngagementTrackingReportReceivedEventData + = new AcsEmailEngagementTrackingReportReceivedEventData(userActionTimestamp, engagementType); + deserializedAcsEmailEngagementTrackingReportReceivedEventData.sender = sender; + deserializedAcsEmailEngagementTrackingReportReceivedEventData.recipient = recipient; + deserializedAcsEmailEngagementTrackingReportReceivedEventData.messageId = messageId; + deserializedAcsEmailEngagementTrackingReportReceivedEventData.engagementContext = engagementContext; + deserializedAcsEmailEngagementTrackingReportReceivedEventData.userAgent = userAgent; + + return deserializedAcsEmailEngagementTrackingReportReceivedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsIncomingCallCustomContext.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsIncomingCallCustomContext.java new file mode 100644 index 000000000000..99f7960b3a7c --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsIncomingCallCustomContext.java @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.Map; + +/** + * Custom Context of Incoming Call. + */ +@Immutable +public final class AcsIncomingCallCustomContext implements JsonSerializable { + /* + * Sip Headers for incoming call + */ + @Generated + private final Map sipHeaders; + + /* + * Voip Headers for incoming call + */ + @Generated + private final Map voipHeaders; + + /** + * Creates an instance of AcsIncomingCallCustomContext class. + * + * @param sipHeaders the sipHeaders value to set. + * @param voipHeaders the voipHeaders value to set. + */ + @Generated + private AcsIncomingCallCustomContext(Map sipHeaders, Map voipHeaders) { + this.sipHeaders = sipHeaders; + this.voipHeaders = voipHeaders; + } + + /** + * Get the sipHeaders property: Sip Headers for incoming call. + * + * @return the sipHeaders value. + */ + @Generated + public Map getSipHeaders() { + return this.sipHeaders; + } + + /** + * Get the voipHeaders property: Voip Headers for incoming call. + * + * @return the voipHeaders value. + */ + @Generated + public Map getVoipHeaders() { + return this.voipHeaders; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("sipHeaders", this.sipHeaders, (writer, element) -> writer.writeString(element)); + jsonWriter.writeMapField("voipHeaders", this.voipHeaders, (writer, element) -> writer.writeString(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsIncomingCallCustomContext from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsIncomingCallCustomContext 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 AcsIncomingCallCustomContext. + */ + @Generated + public static AcsIncomingCallCustomContext fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Map sipHeaders = null; + Map voipHeaders = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("sipHeaders".equals(fieldName)) { + sipHeaders = reader.readMap(reader1 -> reader1.getString()); + } else if ("voipHeaders".equals(fieldName)) { + voipHeaders = reader.readMap(reader1 -> reader1.getString()); + } else { + reader.skipChildren(); + } + } + return new AcsIncomingCallCustomContext(sipHeaders, voipHeaders); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsIncomingCallEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsIncomingCallEventData.java new file mode 100644 index 000000000000..7777854214f0 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsIncomingCallEventData.java @@ -0,0 +1,237 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for an Microsoft.Communication.IncomingCall event. + */ +@Immutable +public final class AcsIncomingCallEventData implements JsonSerializable { + /* + * The communication identifier of the target user. + */ + @Generated + private final CommunicationIdentifierModel toCommunicationIdentifier; + + /* + * The communication identifier of the user who initiated the call. + */ + @Generated + private final CommunicationIdentifierModel fromCommunicationIdentifier; + + /* + * The Id of the server call + */ + @Generated + private String serverCallId; + + /* + * Display name of caller. + */ + @Generated + private String callerDisplayName; + + /* + * Custom Context of Incoming Call + */ + @Generated + private final AcsIncomingCallCustomContext customContext; + + /* + * Signed incoming call context. + */ + @Generated + private String incomingCallContext; + + /* + * The communication identifier of the user on behalf of whom the call is made. + */ + @Generated + private CommunicationIdentifierModel onBehalfOfCommunicationIdentifier; + + /* + * CorrelationId (CallId). + */ + @Generated + private String correlationId; + + /** + * Creates an instance of AcsIncomingCallEventData class. + * + * @param toCommunicationIdentifier the toCommunicationIdentifier value to set. + * @param fromCommunicationIdentifier the fromCommunicationIdentifier value to set. + * @param customContext the customContext value to set. + */ + @Generated + private AcsIncomingCallEventData(CommunicationIdentifierModel toCommunicationIdentifier, + CommunicationIdentifierModel fromCommunicationIdentifier, AcsIncomingCallCustomContext customContext) { + this.toCommunicationIdentifier = toCommunicationIdentifier; + this.fromCommunicationIdentifier = fromCommunicationIdentifier; + this.customContext = customContext; + } + + /** + * Get the toCommunicationIdentifier property: The communication identifier of the target user. + * + * @return the toCommunicationIdentifier value. + */ + @Generated + public CommunicationIdentifierModel getToCommunicationIdentifier() { + return this.toCommunicationIdentifier; + } + + /** + * Get the fromCommunicationIdentifier property: The communication identifier of the user who initiated the call. + * + * @return the fromCommunicationIdentifier value. + */ + @Generated + public CommunicationIdentifierModel getFromCommunicationIdentifier() { + return this.fromCommunicationIdentifier; + } + + /** + * Get the serverCallId property: The Id of the server call. + * + * @return the serverCallId value. + */ + @Generated + public String getServerCallId() { + return this.serverCallId; + } + + /** + * Get the callerDisplayName property: Display name of caller. + * + * @return the callerDisplayName value. + */ + @Generated + public String getCallerDisplayName() { + return this.callerDisplayName; + } + + /** + * Get the customContext property: Custom Context of Incoming Call. + * + * @return the customContext value. + */ + @Generated + public AcsIncomingCallCustomContext getCustomContext() { + return this.customContext; + } + + /** + * Get the incomingCallContext property: Signed incoming call context. + * + * @return the incomingCallContext value. + */ + @Generated + public String getIncomingCallContext() { + return this.incomingCallContext; + } + + /** + * Get the onBehalfOfCommunicationIdentifier property: The communication identifier of the user on behalf of whom + * the call is made. + * + * @return the onBehalfOfCommunicationIdentifier value. + */ + @Generated + public CommunicationIdentifierModel getOnBehalfOfCommunicationIdentifier() { + return this.onBehalfOfCommunicationIdentifier; + } + + /** + * Get the correlationId property: CorrelationId (CallId). + * + * @return the correlationId value. + */ + @Generated + public String getCorrelationId() { + return this.correlationId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("to", this.toCommunicationIdentifier); + jsonWriter.writeJsonField("from", this.fromCommunicationIdentifier); + jsonWriter.writeJsonField("customContext", this.customContext); + jsonWriter.writeStringField("serverCallId", this.serverCallId); + jsonWriter.writeStringField("callerDisplayName", this.callerDisplayName); + jsonWriter.writeStringField("incomingCallContext", this.incomingCallContext); + jsonWriter.writeJsonField("onBehalfOfCallee", this.onBehalfOfCommunicationIdentifier); + jsonWriter.writeStringField("correlationId", this.correlationId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsIncomingCallEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsIncomingCallEventData 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 AcsIncomingCallEventData. + */ + @Generated + public static AcsIncomingCallEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CommunicationIdentifierModel toCommunicationIdentifier = null; + CommunicationIdentifierModel fromCommunicationIdentifier = null; + AcsIncomingCallCustomContext customContext = null; + String serverCallId = null; + String callerDisplayName = null; + String incomingCallContext = null; + CommunicationIdentifierModel onBehalfOfCommunicationIdentifier = null; + String correlationId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("to".equals(fieldName)) { + toCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("from".equals(fieldName)) { + fromCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("customContext".equals(fieldName)) { + customContext = AcsIncomingCallCustomContext.fromJson(reader); + } else if ("serverCallId".equals(fieldName)) { + serverCallId = reader.getString(); + } else if ("callerDisplayName".equals(fieldName)) { + callerDisplayName = reader.getString(); + } else if ("incomingCallContext".equals(fieldName)) { + incomingCallContext = reader.getString(); + } else if ("onBehalfOfCallee".equals(fieldName)) { + onBehalfOfCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else if ("correlationId".equals(fieldName)) { + correlationId = reader.getString(); + } else { + reader.skipChildren(); + } + } + AcsIncomingCallEventData deserializedAcsIncomingCallEventData + = new AcsIncomingCallEventData(toCommunicationIdentifier, fromCommunicationIdentifier, customContext); + deserializedAcsIncomingCallEventData.serverCallId = serverCallId; + deserializedAcsIncomingCallEventData.callerDisplayName = callerDisplayName; + deserializedAcsIncomingCallEventData.incomingCallContext = incomingCallContext; + deserializedAcsIncomingCallEventData.onBehalfOfCommunicationIdentifier = onBehalfOfCommunicationIdentifier; + deserializedAcsIncomingCallEventData.correlationId = correlationId; + + return deserializedAcsIncomingCallEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsInteractiveReplyKind.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsInteractiveReplyKind.java new file mode 100644 index 000000000000..49e29ae57ff6 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsInteractiveReplyKind.java @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Interactive reply kind. + */ +public final class AcsInteractiveReplyKind extends ExpandableStringEnum { + /** + * Messaged interactive reply type is ButtonReply. + */ + @Generated + public static final AcsInteractiveReplyKind BUTTON_REPLY = fromString("buttonReply"); + + /** + * Messaged interactive reply type is ListReply. + */ + @Generated + public static final AcsInteractiveReplyKind LIST_REPLY = fromString("listReply"); + + /** + * Messaged interactive reply type is Unknown. + */ + @Generated + public static final AcsInteractiveReplyKind UNKNOWN = fromString("unknown"); + + /** + * Creates a new instance of AcsInteractiveReplyKind value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public AcsInteractiveReplyKind() { + } + + /** + * Creates or finds a AcsInteractiveReplyKind from its string representation. + * + * @param name a name to look for. + * @return the corresponding AcsInteractiveReplyKind. + */ + @Generated + public static AcsInteractiveReplyKind fromString(String name) { + return fromString(name, AcsInteractiveReplyKind.class); + } + + /** + * Gets known AcsInteractiveReplyKind values. + * + * @return known AcsInteractiveReplyKind values. + */ + @Generated + public static Collection values() { + return values(AcsInteractiveReplyKind.class); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageButtonContent.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageButtonContent.java new file mode 100644 index 000000000000..8ad6a9e34f06 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageButtonContent.java @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Message Button Content. + */ +@Immutable +public final class AcsMessageButtonContent implements JsonSerializable { + /* + * The Text of the button + */ + @Generated + private String text; + + /* + * The Payload of the button which was clicked by the user, setup by the business + */ + @Generated + private String payload; + + /** + * Creates an instance of AcsMessageButtonContent class. + */ + @Generated + private AcsMessageButtonContent() { + } + + /** + * Get the text property: The Text of the button. + * + * @return the text value. + */ + @Generated + public String getText() { + return this.text; + } + + /** + * Get the payload property: The Payload of the button which was clicked by the user, setup by the business. + * + * @return the payload value. + */ + @Generated + public String getPayload() { + return this.payload; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("text", this.text); + jsonWriter.writeStringField("payload", this.payload); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsMessageButtonContent from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsMessageButtonContent 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 AcsMessageButtonContent. + */ + @Generated + public static AcsMessageButtonContent fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AcsMessageButtonContent deserializedAcsMessageButtonContent = new AcsMessageButtonContent(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("text".equals(fieldName)) { + deserializedAcsMessageButtonContent.text = reader.getString(); + } else if ("payload".equals(fieldName)) { + deserializedAcsMessageButtonContent.payload = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAcsMessageButtonContent; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageChannelKind.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageChannelKind.java new file mode 100644 index 000000000000..2055d8029dda --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageChannelKind.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Message channel kind. + */ +public final class AcsMessageChannelKind extends ExpandableStringEnum { + /** + * Updated message channel type is WhatsApp. + */ + @Generated + public static final AcsMessageChannelKind WHATSAPP = fromString("whatsapp"); + + /** + * Creates a new instance of AcsMessageChannelKind value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public AcsMessageChannelKind() { + } + + /** + * Creates or finds a AcsMessageChannelKind from its string representation. + * + * @param name a name to look for. + * @return the corresponding AcsMessageChannelKind. + */ + @Generated + public static AcsMessageChannelKind fromString(String name) { + return fromString(name, AcsMessageChannelKind.class); + } + + /** + * Gets known AcsMessageChannelKind values. + * + * @return known AcsMessageChannelKind values. + */ + @Generated + public static Collection values() { + return values(AcsMessageChannelKind.class); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageContext.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageContext.java new file mode 100644 index 000000000000..bda946cc19be --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageContext.java @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Message Context. + */ +@Immutable +public final class AcsMessageContext implements JsonSerializable { + /* + * The WhatsApp ID for the customer who replied to an inbound message. + */ + @Generated + private String from; + + /* + * The message ID for the sent message for an inbound reply + */ + @Generated + private String messageId; + + /** + * Creates an instance of AcsMessageContext class. + */ + @Generated + private AcsMessageContext() { + } + + /** + * Get the from property: The WhatsApp ID for the customer who replied to an inbound message. + * + * @return the from value. + */ + @Generated + public String getFrom() { + return this.from; + } + + /** + * Get the messageId property: The message ID for the sent message for an inbound reply. + * + * @return the messageId value. + */ + @Generated + public String getMessageId() { + return this.messageId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("from", this.from); + jsonWriter.writeStringField("id", this.messageId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsMessageContext from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsMessageContext 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 AcsMessageContext. + */ + @Generated + public static AcsMessageContext fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AcsMessageContext deserializedAcsMessageContext = new AcsMessageContext(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("from".equals(fieldName)) { + deserializedAcsMessageContext.from = reader.getString(); + } else if ("id".equals(fieldName)) { + deserializedAcsMessageContext.messageId = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAcsMessageContext; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageDeliveryStatus.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageDeliveryStatus.java new file mode 100644 index 000000000000..94ad43e3a94b --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageDeliveryStatus.java @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Message delivery status. + */ +public final class AcsMessageDeliveryStatus extends ExpandableStringEnum { + /** + * Read. + */ + @Generated + public static final AcsMessageDeliveryStatus READ = fromString("read"); + + /** + * Delivered. + */ + @Generated + public static final AcsMessageDeliveryStatus DELIVERED = fromString("delivered"); + + /** + * Failed. + */ + @Generated + public static final AcsMessageDeliveryStatus FAILED = fromString("failed"); + + /** + * Sent. + */ + @Generated + public static final AcsMessageDeliveryStatus SENT = fromString("sent"); + + /** + * Warning. + */ + @Generated + public static final AcsMessageDeliveryStatus WARNING = fromString("warning"); + + /** + * Unknown. + */ + @Generated + public static final AcsMessageDeliveryStatus UNKNOWN = fromString("unknown"); + + /** + * Creates a new instance of AcsMessageDeliveryStatus value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public AcsMessageDeliveryStatus() { + } + + /** + * Creates or finds a AcsMessageDeliveryStatus from its string representation. + * + * @param name a name to look for. + * @return the corresponding AcsMessageDeliveryStatus. + */ + @Generated + public static AcsMessageDeliveryStatus fromString(String name) { + return fromString(name, AcsMessageDeliveryStatus.class); + } + + /** + * Gets known AcsMessageDeliveryStatus values. + * + * @return known AcsMessageDeliveryStatus values. + */ + @Generated + public static Collection values() { + return values(AcsMessageDeliveryStatus.class); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageDeliveryStatusUpdatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageDeliveryStatusUpdatedEventData.java new file mode 100644 index 000000000000..398a7b95bbe0 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageDeliveryStatusUpdatedEventData.java @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.models.ResponseError; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.messaging.eventgrid.implementation.models.AcsMessageChannelEventError; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.AdvancedMessageDeliveryStatusUpdated + * event. + */ +@Immutable +public final class AcsMessageDeliveryStatusUpdatedEventData extends AcsMessageEventData { + + /* + * The message id + */ + @Generated + private String messageId; + + /* + * The updated message status + */ + @Generated + private final AcsMessageDeliveryStatus status; + + /* + * The updated message channel type + */ + @Generated + private final AcsMessageChannelKind channelKind; + + /* + * The channel event error + */ + @Generated + private AcsMessageChannelEventError error; + + /** + * Creates an instance of AcsMessageDeliveryStatusUpdatedEventData class. + * + * @param from the from value to set. + * @param to the to value to set. + * @param receivedTimestamp the receivedTimestamp value to set. + * @param status the status value to set. + * @param channelKind the channelKind value to set. + */ + @Generated + private AcsMessageDeliveryStatusUpdatedEventData(String from, String to, OffsetDateTime receivedTimestamp, + AcsMessageDeliveryStatus status, AcsMessageChannelKind channelKind) { + super(from, to, receivedTimestamp); + this.status = status; + this.channelKind = channelKind; + } + + /** + * Get the messageId property: The message id. + * + * @return the messageId value. + */ + @Generated + public String getMessageId() { + return this.messageId; + } + + /** + * Get the status property: The updated message status. + * + * @return the status value. + */ + @Generated + public AcsMessageDeliveryStatus getStatus() { + return this.status; + } + + /** + * Get the channelKind property: The updated message channel type. + * + * @return the channelKind value. + */ + @Generated + public AcsMessageChannelKind getChannelKind() { + return this.channelKind; + } + + /** + * Get the error property: The channel error code and message. + * + * @return the error value. + */ + @Generated + @Override + public ResponseError getError() { + return new ResponseError(this.error.getChannelCode(), this.error.getChannelMessage()); + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("from", getFrom()); + jsonWriter.writeStringField("to", getTo()); + jsonWriter.writeStringField("receivedTimeStamp", + getReceivedTimestamp() == null + ? null + : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(getReceivedTimestamp())); + jsonWriter.writeJsonField("error", getError()); + jsonWriter.writeStringField("status", this.status == null ? null : this.status.toString()); + jsonWriter.writeStringField("channelType", this.channelKind == null ? null : this.channelKind.toString()); + jsonWriter.writeStringField("messageId", this.messageId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsMessageDeliveryStatusUpdatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsMessageDeliveryStatusUpdatedEventData 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 AcsMessageDeliveryStatusUpdatedEventData. + */ + @Generated + public static AcsMessageDeliveryStatusUpdatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String from = null; + String to = null; + OffsetDateTime receivedTimestamp = null; + AcsMessageChannelEventError error = null; + AcsMessageDeliveryStatus status = null; + AcsMessageChannelKind channelKind = null; + String messageId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("from".equals(fieldName)) { + from = reader.getString(); + } else if ("to".equals(fieldName)) { + to = reader.getString(); + } else if ("receivedTimeStamp".equals(fieldName)) { + receivedTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("error".equals(fieldName)) { + error = AcsMessageChannelEventError.fromJson(reader); + } else if ("status".equals(fieldName)) { + status = AcsMessageDeliveryStatus.fromString(reader.getString()); + } else if ("channelType".equals(fieldName)) { + channelKind = AcsMessageChannelKind.fromString(reader.getString()); + } else if ("messageId".equals(fieldName)) { + messageId = reader.getString(); + } else { + reader.skipChildren(); + } + } + AcsMessageDeliveryStatusUpdatedEventData deserializedAcsMessageDeliveryStatusUpdatedEventData + = new AcsMessageDeliveryStatusUpdatedEventData(from, to, receivedTimestamp, status, channelKind); + deserializedAcsMessageDeliveryStatusUpdatedEventData.error = error; + deserializedAcsMessageDeliveryStatusUpdatedEventData.messageId = messageId; + return deserializedAcsMessageDeliveryStatusUpdatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageEventData.java new file mode 100644 index 000000000000..2999ea5a150d --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageEventData.java @@ -0,0 +1,169 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.models.ResponseError; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.messaging.eventgrid.implementation.models.AcsMessageChannelEventError; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of common properties of all chat thread events. + */ +@Immutable +public class AcsMessageEventData implements JsonSerializable { + + /* + * The message sender + */ + @Generated + private final String from; + + /* + * The message recipient + */ + @Generated + private final String to; + + /* + * The time message was received + */ + @Generated + private final OffsetDateTime receivedTimestamp; + + /* + * The channel event error + */ + @Generated + private AcsMessageChannelEventError error; + + /** + * Creates an instance of AcsMessageEventData class. + * + * @param from the from value to set. + * @param to the to value to set. + * @param receivedTimestamp the receivedTimestamp value to set. + */ + @Generated + protected AcsMessageEventData(String from, String to, OffsetDateTime receivedTimestamp) { + this.from = from; + this.to = to; + this.receivedTimestamp = receivedTimestamp; + } + + /** + * Get the from property: The message sender. + * + * @return the from value. + */ + @Generated + public String getFrom() { + return this.from; + } + + /** + * Get the to property: The message recipient. + * + * @return the to value. + */ + @Generated + public String getTo() { + return this.to; + } + + /** + * Get the receivedTimestamp property: The time message was received. + * + * @return the receivedTimestamp value. + */ + @Generated + public OffsetDateTime getReceivedTimestamp() { + return this.receivedTimestamp; + } + + /** + * Get the error property: The channel error code and message. + * + * @return the error value. + */ + @Generated + public ResponseError getError() { + return new ResponseError(this.error.getChannelCode(), this.error.getChannelMessage()); + } + + /** + * Set the error property: The channel event error. + * + * @param error the error value to set. + * @return the AcsMessageEventData object itself. + */ + @Generated + AcsMessageEventData setError(AcsMessageChannelEventError error) { + this.error = error; + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("from", this.from); + jsonWriter.writeStringField("to", this.to); + jsonWriter.writeStringField("receivedTimeStamp", + this.receivedTimestamp == null + ? null + : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.receivedTimestamp)); + jsonWriter.writeJsonField("error", this.error); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsMessageEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsMessageEventData 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 AcsMessageEventData. + */ + @Generated + public static AcsMessageEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String from = null; + String to = null; + OffsetDateTime receivedTimestamp = null; + AcsMessageChannelEventError error = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("from".equals(fieldName)) { + from = reader.getString(); + } else if ("to".equals(fieldName)) { + to = reader.getString(); + } else if ("receivedTimeStamp".equals(fieldName)) { + receivedTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("error".equals(fieldName)) { + error = AcsMessageChannelEventError.fromJson(reader); + } else { + reader.skipChildren(); + } + } + AcsMessageEventData deserializedAcsMessageEventData = new AcsMessageEventData(from, to, receivedTimestamp); + deserializedAcsMessageEventData.error = error; + return deserializedAcsMessageEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageInteractiveButtonReplyContent.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageInteractiveButtonReplyContent.java new file mode 100644 index 000000000000..86ab99ea3b6b --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageInteractiveButtonReplyContent.java @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Message Interactive button reply content for a user to business message. + */ +@Immutable +public final class AcsMessageInteractiveButtonReplyContent + implements JsonSerializable { + /* + * The ID of the button + */ + @Generated + private String buttonId; + + /* + * The title of the button + */ + @Generated + private String title; + + /** + * Creates an instance of AcsMessageInteractiveButtonReplyContent class. + */ + @Generated + private AcsMessageInteractiveButtonReplyContent() { + } + + /** + * Get the buttonId property: The ID of the button. + * + * @return the buttonId value. + */ + @Generated + public String getButtonId() { + return this.buttonId; + } + + /** + * Get the title property: The title of the button. + * + * @return the title value. + */ + @Generated + public String getTitle() { + return this.title; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("id", this.buttonId); + jsonWriter.writeStringField("title", this.title); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsMessageInteractiveButtonReplyContent from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsMessageInteractiveButtonReplyContent 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 AcsMessageInteractiveButtonReplyContent. + */ + @Generated + public static AcsMessageInteractiveButtonReplyContent fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AcsMessageInteractiveButtonReplyContent deserializedAcsMessageInteractiveButtonReplyContent + = new AcsMessageInteractiveButtonReplyContent(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedAcsMessageInteractiveButtonReplyContent.buttonId = reader.getString(); + } else if ("title".equals(fieldName)) { + deserializedAcsMessageInteractiveButtonReplyContent.title = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAcsMessageInteractiveButtonReplyContent; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageInteractiveContent.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageInteractiveContent.java new file mode 100644 index 000000000000..24f3967893b3 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageInteractiveContent.java @@ -0,0 +1,128 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Message Interactive Content. + */ +@Immutable +public final class AcsMessageInteractiveContent implements JsonSerializable { + /* + * The Message interactive reply type + */ + @Generated + private final AcsInteractiveReplyKind replyKind; + + /* + * The Message Sent when a customer clicks a button + */ + @Generated + private AcsMessageInteractiveButtonReplyContent buttonReply; + + /* + * The Message Sent when a customer selects an item from a list + */ + @Generated + private AcsMessageInteractiveListReplyContent listReply; + + /** + * Creates an instance of AcsMessageInteractiveContent class. + * + * @param replyKind the replyKind value to set. + */ + @Generated + private AcsMessageInteractiveContent(AcsInteractiveReplyKind replyKind) { + this.replyKind = replyKind; + } + + /** + * Get the replyKind property: The Message interactive reply type. + * + * @return the replyKind value. + */ + @Generated + public AcsInteractiveReplyKind getReplyKind() { + return this.replyKind; + } + + /** + * Get the buttonReply property: The Message Sent when a customer clicks a button. + * + * @return the buttonReply value. + */ + @Generated + public AcsMessageInteractiveButtonReplyContent getButtonReply() { + return this.buttonReply; + } + + /** + * Get the listReply property: The Message Sent when a customer selects an item from a list. + * + * @return the listReply value. + */ + @Generated + public AcsMessageInteractiveListReplyContent getListReply() { + return this.listReply; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.replyKind == null ? null : this.replyKind.toString()); + jsonWriter.writeJsonField("buttonReply", this.buttonReply); + jsonWriter.writeJsonField("listReply", this.listReply); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsMessageInteractiveContent from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsMessageInteractiveContent 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 AcsMessageInteractiveContent. + */ + @Generated + public static AcsMessageInteractiveContent fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AcsInteractiveReplyKind replyKind = null; + AcsMessageInteractiveButtonReplyContent buttonReply = null; + AcsMessageInteractiveListReplyContent listReply = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("type".equals(fieldName)) { + replyKind = AcsInteractiveReplyKind.fromString(reader.getString()); + } else if ("buttonReply".equals(fieldName)) { + buttonReply = AcsMessageInteractiveButtonReplyContent.fromJson(reader); + } else if ("listReply".equals(fieldName)) { + listReply = AcsMessageInteractiveListReplyContent.fromJson(reader); + } else { + reader.skipChildren(); + } + } + AcsMessageInteractiveContent deserializedAcsMessageInteractiveContent + = new AcsMessageInteractiveContent(replyKind); + deserializedAcsMessageInteractiveContent.buttonReply = buttonReply; + deserializedAcsMessageInteractiveContent.listReply = listReply; + + return deserializedAcsMessageInteractiveContent; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageInteractiveListReplyContent.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageInteractiveListReplyContent.java new file mode 100644 index 000000000000..88c5467c91d6 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageInteractiveListReplyContent.java @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Message Interactive list reply content for a user to business message. + */ +@Immutable +public final class AcsMessageInteractiveListReplyContent + implements JsonSerializable { + /* + * The ID of the selected list item + */ + @Generated + private String listItemId; + + /* + * The title of the selected list item + */ + @Generated + private String title; + + /* + * The description of the selected row + */ + @Generated + private String description; + + /** + * Creates an instance of AcsMessageInteractiveListReplyContent class. + */ + @Generated + private AcsMessageInteractiveListReplyContent() { + } + + /** + * Get the listItemId property: The ID of the selected list item. + * + * @return the listItemId value. + */ + @Generated + public String getListItemId() { + return this.listItemId; + } + + /** + * Get the title property: The title of the selected list item. + * + * @return the title value. + */ + @Generated + public String getTitle() { + return this.title; + } + + /** + * Get the description property: The description of the selected row. + * + * @return the description value. + */ + @Generated + public String getDescription() { + return this.description; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("id", this.listItemId); + jsonWriter.writeStringField("title", this.title); + jsonWriter.writeStringField("description", this.description); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsMessageInteractiveListReplyContent from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsMessageInteractiveListReplyContent 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 AcsMessageInteractiveListReplyContent. + */ + @Generated + public static AcsMessageInteractiveListReplyContent fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AcsMessageInteractiveListReplyContent deserializedAcsMessageInteractiveListReplyContent + = new AcsMessageInteractiveListReplyContent(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedAcsMessageInteractiveListReplyContent.listItemId = reader.getString(); + } else if ("title".equals(fieldName)) { + deserializedAcsMessageInteractiveListReplyContent.title = reader.getString(); + } else if ("description".equals(fieldName)) { + deserializedAcsMessageInteractiveListReplyContent.description = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAcsMessageInteractiveListReplyContent; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageMediaContent.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageMediaContent.java new file mode 100644 index 000000000000..5fe72b9b20eb --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageMediaContent.java @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Message Media Content. + */ +@Immutable +public final class AcsMessageMediaContent implements JsonSerializable { + /* + * Required. The MIME type of the file this media represents + */ + @Generated + private final String mimeType; + + /* + * Required. The media identifier + */ + @Generated + private final String mediaId; + + /* + * Optional. The filename of the underlying media file as specified when uploaded + */ + @Generated + private String fileName; + + /* + * Optional. The caption for the media object, if supported and provided + */ + @Generated + private String caption; + + /* + * Optional. Set to true if the sticker is animated; false otherwise. + */ + @Generated + private Boolean animated; + + /** + * Creates an instance of AcsMessageMediaContent class. + * + * @param mimeType the mimeType value to set. + * @param mediaId the mediaId value to set. + */ + @Generated + private AcsMessageMediaContent(String mimeType, String mediaId) { + this.mimeType = mimeType; + this.mediaId = mediaId; + } + + /** + * Get the mimeType property: Required. The MIME type of the file this media represents. + * + * @return the mimeType value. + */ + @Generated + public String getMimeType() { + return this.mimeType; + } + + /** + * Get the mediaId property: Required. The media identifier. + * + * @return the mediaId value. + */ + @Generated + public String getMediaId() { + return this.mediaId; + } + + /** + * Get the fileName property: Optional. The filename of the underlying media file as specified when uploaded. + * + * @return the fileName value. + */ + @Generated + public String getFileName() { + return this.fileName; + } + + /** + * Get the caption property: Optional. The caption for the media object, if supported and provided. + * + * @return the caption value. + */ + @Generated + public String getCaption() { + return this.caption; + } + + /** + * Get the animated property: Optional. Set to true if the sticker is animated; false otherwise. + * + * @return the animated value. + */ + @Generated + public Boolean isAnimated() { + return this.animated; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("mimeType", this.mimeType); + jsonWriter.writeStringField("id", this.mediaId); + jsonWriter.writeStringField("fileName", this.fileName); + jsonWriter.writeStringField("caption", this.caption); + jsonWriter.writeBooleanField("animated", this.animated); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsMessageMediaContent from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsMessageMediaContent 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 AcsMessageMediaContent. + */ + @Generated + public static AcsMessageMediaContent fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String mimeType = null; + String mediaId = null; + String fileName = null; + String caption = null; + Boolean animated = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("mimeType".equals(fieldName)) { + mimeType = reader.getString(); + } else if ("id".equals(fieldName)) { + mediaId = reader.getString(); + } else if ("fileName".equals(fieldName)) { + fileName = reader.getString(); + } else if ("caption".equals(fieldName)) { + caption = reader.getString(); + } else if ("animated".equals(fieldName)) { + animated = reader.getNullable(JsonReader::getBoolean); + } else { + reader.skipChildren(); + } + } + AcsMessageMediaContent deserializedAcsMessageMediaContent = new AcsMessageMediaContent(mimeType, mediaId); + deserializedAcsMessageMediaContent.fileName = fileName; + deserializedAcsMessageMediaContent.caption = caption; + deserializedAcsMessageMediaContent.animated = animated; + + return deserializedAcsMessageMediaContent; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageReactionContent.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageReactionContent.java new file mode 100644 index 000000000000..a005691fb412 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageReactionContent.java @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Message Reaction Content. + */ +@Immutable +public final class AcsMessageReactionContent implements JsonSerializable { + /* + * Required. WhatsApp message ID of the message that the emoji is applied to + */ + @Generated + private final String messageId; + + /* + * Optional. Unicode escape sequence of the emoji. + */ + @Generated + private String emoji; + + /** + * Creates an instance of AcsMessageReactionContent class. + * + * @param messageId the messageId value to set. + */ + @Generated + private AcsMessageReactionContent(String messageId) { + this.messageId = messageId; + } + + /** + * Get the messageId property: Required. WhatsApp message ID of the message that the emoji is applied to. + * + * @return the messageId value. + */ + @Generated + public String getMessageId() { + return this.messageId; + } + + /** + * Get the emoji property: Optional. Unicode escape sequence of the emoji. + * + * @return the emoji value. + */ + @Generated + public String getEmoji() { + return this.emoji; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("messageId", this.messageId); + jsonWriter.writeStringField("emoji", this.emoji); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsMessageReactionContent from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsMessageReactionContent 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 AcsMessageReactionContent. + */ + @Generated + public static AcsMessageReactionContent fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String messageId = null; + String emoji = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("messageId".equals(fieldName)) { + messageId = reader.getString(); + } else if ("emoji".equals(fieldName)) { + emoji = reader.getString(); + } else { + reader.skipChildren(); + } + } + AcsMessageReactionContent deserializedAcsMessageReactionContent = new AcsMessageReactionContent(messageId); + deserializedAcsMessageReactionContent.emoji = emoji; + + return deserializedAcsMessageReactionContent; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageReceivedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageReceivedEventData.java new file mode 100644 index 000000000000..3ae4adf569d7 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageReceivedEventData.java @@ -0,0 +1,300 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.models.ResponseError; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.messaging.eventgrid.implementation.models.AcsMessageChannelEventError; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.AdvancedMessageReceived event. + */ +@Immutable +public final class AcsMessageReceivedEventData extends AcsMessageEventData { + + /* + * Optional. The message content + */ + @Generated + private String content; + + /* + * Optional. Message ID. Format is Guid as string. + */ + @Generated + private String messageId; + + /* + * Required. The message channel type + */ + @Generated + private final AcsMessageChannelKind channelKind; + + /* + * Required. Whatsapp message type + */ + @Generated + private final String messageType; + + /* + * Optional. The received message media content + */ + @Generated + private AcsMessageMediaContent mediaContent; + + /* + * Optional. The received message reaction content + */ + @Generated + private AcsMessageReactionContent reaction; + + /* + * Optional. The received message context + */ + @Generated + private AcsMessageContext context; + + /* + * Optional. The received message button content + */ + @Generated + private AcsMessageButtonContent button; + + /* + * Optional. The received message interactive content + */ + @Generated + private AcsMessageInteractiveContent interactiveContent; + + /* + * The channel event error + */ + @Generated + private AcsMessageChannelEventError error; + + /** + * Creates an instance of AcsMessageReceivedEventData class. + * + * @param from the from value to set. + * @param to the to value to set. + * @param receivedTimestamp the receivedTimestamp value to set. + * @param channelKind the channelKind value to set. + * @param messageType the messageType value to set. + */ + @Generated + private AcsMessageReceivedEventData(String from, String to, OffsetDateTime receivedTimestamp, + AcsMessageChannelKind channelKind, String messageType) { + super(from, to, receivedTimestamp); + this.channelKind = channelKind; + this.messageType = messageType; + } + + /** + * Get the content property: Optional. The message content. + * + * @return the content value. + */ + @Generated + public String getContent() { + return this.content; + } + + /** + * Get the messageId property: Optional. Message ID. Format is Guid as string. + * + * @return the messageId value. + */ + @Generated + public String getMessageId() { + return this.messageId; + } + + /** + * Get the channelKind property: Required. The message channel type. + * + * @return the channelKind value. + */ + @Generated + public AcsMessageChannelKind getChannelKind() { + return this.channelKind; + } + + /** + * Get the messageType property: Required. Whatsapp message type. + * + * @return the messageType value. + */ + @Generated + public String getMessageType() { + return this.messageType; + } + + /** + * Get the mediaContent property: Optional. The received message media content. + * + * @return the mediaContent value. + */ + @Generated + public AcsMessageMediaContent getMediaContent() { + return this.mediaContent; + } + + /** + * Get the reaction property: Optional. The received message reaction content. + * + * @return the reaction value. + */ + @Generated + public AcsMessageReactionContent getReaction() { + return this.reaction; + } + + /** + * Get the context property: Optional. The received message context. + * + * @return the context value. + */ + @Generated + public AcsMessageContext getContext() { + return this.context; + } + + /** + * Get the button property: Optional. The received message button content. + * + * @return the button value. + */ + @Generated + public AcsMessageButtonContent getButton() { + return this.button; + } + + /** + * Get the interactiveContent property: Optional. The received message interactive content. + * + * @return the interactiveContent value. + */ + @Generated + public AcsMessageInteractiveContent getInteractiveContent() { + return this.interactiveContent; + } + + /** + * Get the error property: The channel error code and message. + * + * @return the error value. + */ + @Generated + @Override + public ResponseError getError() { + return new ResponseError(this.error.getChannelCode(), this.error.getChannelMessage()); + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("from", getFrom()); + jsonWriter.writeStringField("to", getTo()); + jsonWriter.writeStringField("receivedTimeStamp", + getReceivedTimestamp() == null + ? null + : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(getReceivedTimestamp())); + jsonWriter.writeJsonField("error", getError()); + jsonWriter.writeStringField("channelType", this.channelKind == null ? null : this.channelKind.toString()); + jsonWriter.writeStringField("messageType", this.messageType); + jsonWriter.writeStringField("content", this.content); + jsonWriter.writeStringField("messageId", this.messageId); + jsonWriter.writeJsonField("media", this.mediaContent); + jsonWriter.writeJsonField("reaction", this.reaction); + jsonWriter.writeJsonField("context", this.context); + jsonWriter.writeJsonField("button", this.button); + jsonWriter.writeJsonField("interactive", this.interactiveContent); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsMessageReceivedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsMessageReceivedEventData 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 AcsMessageReceivedEventData. + */ + @Generated + public static AcsMessageReceivedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String from = null; + String to = null; + OffsetDateTime receivedTimestamp = null; + AcsMessageChannelEventError error = null; + AcsMessageChannelKind channelKind = null; + String messageType = null; + String content = null; + String messageId = null; + AcsMessageMediaContent mediaContent = null; + AcsMessageReactionContent reaction = null; + AcsMessageContext context = null; + AcsMessageButtonContent button = null; + AcsMessageInteractiveContent interactiveContent = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("from".equals(fieldName)) { + from = reader.getString(); + } else if ("to".equals(fieldName)) { + to = reader.getString(); + } else if ("receivedTimeStamp".equals(fieldName)) { + receivedTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("error".equals(fieldName)) { + error = AcsMessageChannelEventError.fromJson(reader); + } else if ("channelType".equals(fieldName)) { + channelKind = AcsMessageChannelKind.fromString(reader.getString()); + } else if ("messageType".equals(fieldName)) { + messageType = reader.getString(); + } else if ("content".equals(fieldName)) { + content = reader.getString(); + } else if ("messageId".equals(fieldName)) { + messageId = reader.getString(); + } else if ("media".equals(fieldName)) { + mediaContent = AcsMessageMediaContent.fromJson(reader); + } else if ("reaction".equals(fieldName)) { + reaction = AcsMessageReactionContent.fromJson(reader); + } else if ("context".equals(fieldName)) { + context = AcsMessageContext.fromJson(reader); + } else if ("button".equals(fieldName)) { + button = AcsMessageButtonContent.fromJson(reader); + } else if ("interactive".equals(fieldName)) { + interactiveContent = AcsMessageInteractiveContent.fromJson(reader); + } else { + reader.skipChildren(); + } + } + AcsMessageReceivedEventData deserializedAcsMessageReceivedEventData + = new AcsMessageReceivedEventData(from, to, receivedTimestamp, channelKind, messageType); + deserializedAcsMessageReceivedEventData.error = error; + deserializedAcsMessageReceivedEventData.content = content; + deserializedAcsMessageReceivedEventData.messageId = messageId; + deserializedAcsMessageReceivedEventData.mediaContent = mediaContent; + deserializedAcsMessageReceivedEventData.reaction = reaction; + deserializedAcsMessageReceivedEventData.context = context; + deserializedAcsMessageReceivedEventData.button = button; + deserializedAcsMessageReceivedEventData.interactiveContent = interactiveContent; + return deserializedAcsMessageReceivedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRecordingChunkInfoProperties.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRecordingChunkInfoProperties.java new file mode 100644 index 000000000000..a93c3bc0b363 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRecordingChunkInfoProperties.java @@ -0,0 +1,176 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema for all properties of Recording Chunk Information. + */ +@Immutable +public final class AcsRecordingChunkInfoProperties implements JsonSerializable { + /* + * The documentId of the recording chunk + */ + @Generated + private String documentId; + + /* + * The index of the recording chunk + */ + @Generated + private Long index; + + /* + * The reason for ending the recording chunk + */ + @Generated + private String endReason; + + /* + * The location of the metadata for this chunk + */ + @Generated + private String metadataLocation; + + /* + * The location of the content for this chunk + */ + @Generated + private String contentLocation; + + /* + * The location to delete all chunk storage + */ + @Generated + private String deleteLocation; + + /** + * Creates an instance of AcsRecordingChunkInfoProperties class. + */ + @Generated + private AcsRecordingChunkInfoProperties() { + } + + /** + * Get the documentId property: The documentId of the recording chunk. + * + * @return the documentId value. + */ + @Generated + public String getDocumentId() { + return this.documentId; + } + + /** + * Get the index property: The index of the recording chunk. + * + * @return the index value. + */ + @Generated + public Long getIndex() { + return this.index; + } + + /** + * Get the endReason property: The reason for ending the recording chunk. + * + * @return the endReason value. + */ + @Generated + public String getEndReason() { + return this.endReason; + } + + /** + * Get the metadataLocation property: The location of the metadata for this chunk. + * + * @return the metadataLocation value. + */ + @Generated + public String getMetadataLocation() { + return this.metadataLocation; + } + + /** + * Get the contentLocation property: The location of the content for this chunk. + * + * @return the contentLocation value. + */ + @Generated + public String getContentLocation() { + return this.contentLocation; + } + + /** + * Get the deleteLocation property: The location to delete all chunk storage. + * + * @return the deleteLocation value. + */ + @Generated + public String getDeleteLocation() { + return this.deleteLocation; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("documentId", this.documentId); + jsonWriter.writeNumberField("index", this.index); + jsonWriter.writeStringField("endReason", this.endReason); + jsonWriter.writeStringField("metadataLocation", this.metadataLocation); + jsonWriter.writeStringField("contentLocation", this.contentLocation); + jsonWriter.writeStringField("deleteLocation", this.deleteLocation); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRecordingChunkInfoProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRecordingChunkInfoProperties 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 AcsRecordingChunkInfoProperties. + */ + @Generated + public static AcsRecordingChunkInfoProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AcsRecordingChunkInfoProperties deserializedAcsRecordingChunkInfoProperties + = new AcsRecordingChunkInfoProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("documentId".equals(fieldName)) { + deserializedAcsRecordingChunkInfoProperties.documentId = reader.getString(); + } else if ("index".equals(fieldName)) { + deserializedAcsRecordingChunkInfoProperties.index = reader.getNullable(JsonReader::getLong); + } else if ("endReason".equals(fieldName)) { + deserializedAcsRecordingChunkInfoProperties.endReason = reader.getString(); + } else if ("metadataLocation".equals(fieldName)) { + deserializedAcsRecordingChunkInfoProperties.metadataLocation = reader.getString(); + } else if ("contentLocation".equals(fieldName)) { + deserializedAcsRecordingChunkInfoProperties.contentLocation = reader.getString(); + } else if ("deleteLocation".equals(fieldName)) { + deserializedAcsRecordingChunkInfoProperties.deleteLocation = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAcsRecordingChunkInfoProperties; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRecordingFileStatusUpdatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRecordingFileStatusUpdatedEventData.java new file mode 100644 index 000000000000..47f8c159f4c2 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRecordingFileStatusUpdatedEventData.java @@ -0,0 +1,232 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RecordingFileStatusUpdated event. + */ +@Immutable +public final class AcsRecordingFileStatusUpdatedEventData + implements JsonSerializable { + + /* + * The details of recording storage information + */ + @Generated + private final AcsRecordingStorageInfoProperties recordingStorageInfo; + + /* + * The time at which the recording started + */ + @Generated + private final OffsetDateTime recordingStartTime; + + /* + * The recording duration in milliseconds + */ + @Generated + private Long recordingDuration; + + /* + * The recording content type- AudioVideo, or Audio + */ + @Generated + private final RecordingContentType recordingContentType; + + /* + * The recording channel type - Mixed, Unmixed + */ + @Generated + private final RecordingChannelType recordingChannelType; + + /* + * The recording format type - Mp4, Mp3, Wav + */ + @Generated + private final RecordingFormatType recordingFormatType; + + /* + * The reason for ending recording session + */ + @Generated + private String sessionEndReason; + + /** + * Creates an instance of AcsRecordingFileStatusUpdatedEventData class. + * + * @param recordingStorageInfo the recordingStorageInfo value to set. + * @param recordingStartTime the recordingStartTime value to set. + * @param recordingContentType the recordingContentType value to set. + * @param recordingChannelType the recordingChannelType value to set. + * @param recordingFormatType the recordingFormatType value to set. + */ + @Generated + private AcsRecordingFileStatusUpdatedEventData(AcsRecordingStorageInfoProperties recordingStorageInfo, + OffsetDateTime recordingStartTime, RecordingContentType recordingContentType, + RecordingChannelType recordingChannelType, RecordingFormatType recordingFormatType) { + this.recordingStorageInfo = recordingStorageInfo; + this.recordingStartTime = recordingStartTime; + this.recordingContentType = recordingContentType; + this.recordingChannelType = recordingChannelType; + this.recordingFormatType = recordingFormatType; + } + + /** + * Get the recordingStorageInfo property: The details of recording storage information. + * + * @return the recordingStorageInfo value. + */ + @Generated + public AcsRecordingStorageInfoProperties getRecordingStorageInfo() { + return this.recordingStorageInfo; + } + + /** + * Get the recordingStartTime property: The time at which the recording started. + * + * @return the recordingStartTime value. + */ + @Generated + public OffsetDateTime getRecordingStartTime() { + return this.recordingStartTime; + } + + /** + * Get the recordingDuration property: The recording duration. + * + * @return the recordingDuration value. + */ + @Generated + public Duration getRecordingDuration() { + if (this.recordingDuration != null) { + return Duration.ofMillis(this.recordingDuration); + } + return null; + } + + /** + * Get the recordingContentType property: The recording content type- AudioVideo, or Audio. + * + * @return the recordingContentType value. + */ + @Generated + public RecordingContentType getRecordingContentType() { + return this.recordingContentType; + } + + /** + * Get the recordingChannelType property: The recording channel type - Mixed, Unmixed. + * + * @return the recordingChannelType value. + */ + @Generated + public RecordingChannelType getRecordingChannelType() { + return this.recordingChannelType; + } + + /** + * Get the recordingFormatType property: The recording format type - Mp4, Mp3, Wav. + * + * @return the recordingFormatType value. + */ + @Generated + public RecordingFormatType getRecordingFormatType() { + return this.recordingFormatType; + } + + /** + * Get the sessionEndReason property: The reason for ending recording session. + * + * @return the sessionEndReason value. + */ + @Generated + public String getSessionEndReason() { + return this.sessionEndReason; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("recordingStorageInfo", this.recordingStorageInfo); + jsonWriter.writeStringField("recordingStartTime", + this.recordingStartTime == null + ? null + : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.recordingStartTime)); + jsonWriter.writeStringField("recordingContentType", + this.recordingContentType == null ? null : this.recordingContentType.toString()); + jsonWriter.writeStringField("recordingChannelType", + this.recordingChannelType == null ? null : this.recordingChannelType.toString()); + jsonWriter.writeStringField("recordingFormatType", + this.recordingFormatType == null ? null : this.recordingFormatType.toString()); + jsonWriter.writeNumberField("recordingDurationMs", this.recordingDuration); + jsonWriter.writeStringField("sessionEndReason", this.sessionEndReason); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRecordingFileStatusUpdatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRecordingFileStatusUpdatedEventData 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 AcsRecordingFileStatusUpdatedEventData. + */ + @Generated + public static AcsRecordingFileStatusUpdatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AcsRecordingStorageInfoProperties recordingStorageInfo = null; + OffsetDateTime recordingStartTime = null; + RecordingContentType recordingContentType = null; + RecordingChannelType recordingChannelType = null; + RecordingFormatType recordingFormatType = null; + Long recordingDuration = null; + String sessionEndReason = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("recordingStorageInfo".equals(fieldName)) { + recordingStorageInfo = AcsRecordingStorageInfoProperties.fromJson(reader); + } else if ("recordingStartTime".equals(fieldName)) { + recordingStartTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("recordingContentType".equals(fieldName)) { + recordingContentType = RecordingContentType.fromString(reader.getString()); + } else if ("recordingChannelType".equals(fieldName)) { + recordingChannelType = RecordingChannelType.fromString(reader.getString()); + } else if ("recordingFormatType".equals(fieldName)) { + recordingFormatType = RecordingFormatType.fromString(reader.getString()); + } else if ("recordingDurationMs".equals(fieldName)) { + recordingDuration = reader.getNullable(JsonReader::getLong); + } else if ("sessionEndReason".equals(fieldName)) { + sessionEndReason = reader.getString(); + } else { + reader.skipChildren(); + } + } + AcsRecordingFileStatusUpdatedEventData deserializedAcsRecordingFileStatusUpdatedEventData + = new AcsRecordingFileStatusUpdatedEventData(recordingStorageInfo, recordingStartTime, + recordingContentType, recordingChannelType, recordingFormatType); + deserializedAcsRecordingFileStatusUpdatedEventData.recordingDuration = recordingDuration; + deserializedAcsRecordingFileStatusUpdatedEventData.sessionEndReason = sessionEndReason; + return deserializedAcsRecordingFileStatusUpdatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRecordingStorageInfoProperties.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRecordingStorageInfoProperties.java new file mode 100644 index 000000000000..aa00a3fd49ae --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRecordingStorageInfoProperties.java @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.List; + +/** + * Schema for all properties of Recording Storage Information. + */ +@Immutable +public final class AcsRecordingStorageInfoProperties implements JsonSerializable { + /* + * List of details of recording chunks information + */ + @Generated + private final List recordingChunks; + + /** + * Creates an instance of AcsRecordingStorageInfoProperties class. + * + * @param recordingChunks the recordingChunks value to set. + */ + @Generated + private AcsRecordingStorageInfoProperties(List recordingChunks) { + this.recordingChunks = recordingChunks; + } + + /** + * Get the recordingChunks property: List of details of recording chunks information. + * + * @return the recordingChunks value. + */ + @Generated + public List getRecordingChunks() { + return this.recordingChunks; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("recordingChunks", this.recordingChunks, + (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRecordingStorageInfoProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRecordingStorageInfoProperties 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 AcsRecordingStorageInfoProperties. + */ + @Generated + public static AcsRecordingStorageInfoProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + List recordingChunks = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("recordingChunks".equals(fieldName)) { + recordingChunks = reader.readArray(reader1 -> AcsRecordingChunkInfoProperties.fromJson(reader1)); + } else { + reader.skipChildren(); + } + } + return new AcsRecordingStorageInfoProperties(recordingChunks); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterChannelConfiguration.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterChannelConfiguration.java new file mode 100644 index 000000000000..c844a4fbd7e1 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterChannelConfiguration.java @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Router Channel Configuration. + */ +@Immutable +public final class AcsRouterChannelConfiguration implements JsonSerializable { + /* + * Channel ID for Router Job + */ + @Generated + private String channelId; + + /* + * Capacity Cost Per Job for Router Job + */ + @Generated + private Integer capacityCostPerJob; + + /* + * Max Number of Jobs for Router Job + */ + @Generated + private Integer maxNumberOfJobs; + + /** + * Creates an instance of AcsRouterChannelConfiguration class. + */ + @Generated + private AcsRouterChannelConfiguration() { + } + + /** + * Get the channelId property: Channel ID for Router Job. + * + * @return the channelId value. + */ + @Generated + public String getChannelId() { + return this.channelId; + } + + /** + * Get the capacityCostPerJob property: Capacity Cost Per Job for Router Job. + * + * @return the capacityCostPerJob value. + */ + @Generated + public Integer getCapacityCostPerJob() { + return this.capacityCostPerJob; + } + + /** + * Get the maxNumberOfJobs property: Max Number of Jobs for Router Job. + * + * @return the maxNumberOfJobs value. + */ + @Generated + public Integer getMaxNumberOfJobs() { + return this.maxNumberOfJobs; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("channelId", this.channelId); + jsonWriter.writeNumberField("capacityCostPerJob", this.capacityCostPerJob); + jsonWriter.writeNumberField("maxNumberOfJobs", this.maxNumberOfJobs); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRouterChannelConfiguration from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRouterChannelConfiguration 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 AcsRouterChannelConfiguration. + */ + @Generated + public static AcsRouterChannelConfiguration fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AcsRouterChannelConfiguration deserializedAcsRouterChannelConfiguration + = new AcsRouterChannelConfiguration(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("channelId".equals(fieldName)) { + deserializedAcsRouterChannelConfiguration.channelId = reader.getString(); + } else if ("capacityCostPerJob".equals(fieldName)) { + deserializedAcsRouterChannelConfiguration.capacityCostPerJob + = reader.getNullable(JsonReader::getInt); + } else if ("maxNumberOfJobs".equals(fieldName)) { + deserializedAcsRouterChannelConfiguration.maxNumberOfJobs = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + + return deserializedAcsRouterChannelConfiguration; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterEventData.java new file mode 100644 index 000000000000..5f6a1420b141 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterEventData.java @@ -0,0 +1,154 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of common properties of all Router events. + */ +@Immutable +public class AcsRouterEventData implements JsonSerializable { + /* + * Router Event Job ID + */ + @Generated + private String jobId; + + /* + * Router Event Channel Reference + */ + @Generated + private String channelReference; + + /* + * Router Event Channel ID + */ + @Generated + private String channelId; + + /** + * Creates an instance of AcsRouterEventData class. + */ + @Generated + protected AcsRouterEventData() { + } + + /** + * Get the jobId property: Router Event Job ID. + * + * @return the jobId value. + */ + @Generated + public String getJobId() { + return this.jobId; + } + + /** + * Set the jobId property: Router Event Job ID. + * + * @param jobId the jobId value to set. + * @return the AcsRouterEventData object itself. + */ + @Generated + AcsRouterEventData setJobId(String jobId) { + this.jobId = jobId; + return this; + } + + /** + * Get the channelReference property: Router Event Channel Reference. + * + * @return the channelReference value. + */ + @Generated + public String getChannelReference() { + return this.channelReference; + } + + /** + * Set the channelReference property: Router Event Channel Reference. + * + * @param channelReference the channelReference value to set. + * @return the AcsRouterEventData object itself. + */ + @Generated + AcsRouterEventData setChannelReference(String channelReference) { + this.channelReference = channelReference; + return this; + } + + /** + * Get the channelId property: Router Event Channel ID. + * + * @return the channelId value. + */ + @Generated + public String getChannelId() { + return this.channelId; + } + + /** + * Set the channelId property: Router Event Channel ID. + * + * @param channelId the channelId value to set. + * @return the AcsRouterEventData object itself. + */ + @Generated + AcsRouterEventData setChannelId(String channelId) { + this.channelId = channelId; + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("jobId", this.jobId); + jsonWriter.writeStringField("channelReference", this.channelReference); + jsonWriter.writeStringField("channelId", this.channelId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRouterEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRouterEventData 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 AcsRouterEventData. + */ + @Generated + public static AcsRouterEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AcsRouterEventData deserializedAcsRouterEventData = new AcsRouterEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("jobId".equals(fieldName)) { + deserializedAcsRouterEventData.jobId = reader.getString(); + } else if ("channelReference".equals(fieldName)) { + deserializedAcsRouterEventData.channelReference = reader.getString(); + } else if ("channelId".equals(fieldName)) { + deserializedAcsRouterEventData.channelId = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAcsRouterEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobCancelledEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobCancelledEventData.java new file mode 100644 index 000000000000..91374c749f0a --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobCancelledEventData.java @@ -0,0 +1,205 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobCancelled event. + */ +@Immutable +public final class AcsRouterJobCancelledEventData extends AcsRouterJobEventData { + /* + * Router Job Note + */ + @Generated + private String note; + + /* + * Router Job Disposition Code + */ + @Generated + private String dispositionCode; + + /* + * Router Job events Queue Id + */ + @Generated + private String queueId; + + /* + * Router Event Channel ID + */ + @Generated + private String channelId; + + /* + * Router Event Channel Reference + */ + @Generated + private String channelReference; + + /* + * Router Event Job ID + */ + @Generated + private String jobId; + + /** + * Creates an instance of AcsRouterJobCancelledEventData class. + * + * @param labels the labels value to set. + * @param tags the tags value to set. + */ + @Generated + private AcsRouterJobCancelledEventData(Map labels, Map tags) { + super(labels, tags); + } + + /** + * Get the note property: Router Job Note. + * + * @return the note value. + */ + @Generated + public String getNote() { + return this.note; + } + + /** + * Get the dispositionCode property: Router Job Disposition Code. + * + * @return the dispositionCode value. + */ + @Generated + public String getDispositionCode() { + return this.dispositionCode; + } + + /** + * Get the queueId property: Router Job events Queue Id. + * + * @return the queueId value. + */ + @Generated + @Override + public String getQueueId() { + return this.queueId; + } + + /** + * Get the channelId property: Router Event Channel ID. + * + * @return the channelId value. + */ + @Generated + @Override + public String getChannelId() { + return this.channelId; + } + + /** + * Get the channelReference property: Router Event Channel Reference. + * + * @return the channelReference value. + */ + @Generated + @Override + public String getChannelReference() { + return this.channelReference; + } + + /** + * Get the jobId property: Router Event Job ID. + * + * @return the jobId value. + */ + @Generated + @Override + public String getJobId() { + return this.jobId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("labels", getLabels(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeMapField("tags", getTags(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("jobId", getJobId()); + jsonWriter.writeStringField("channelReference", getChannelReference()); + jsonWriter.writeStringField("channelId", getChannelId()); + jsonWriter.writeStringField("queueId", getQueueId()); + jsonWriter.writeStringField("note", this.note); + jsonWriter.writeStringField("dispositionCode", this.dispositionCode); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRouterJobCancelledEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRouterJobCancelledEventData 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 AcsRouterJobCancelledEventData. + */ + @Generated + public static AcsRouterJobCancelledEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Map labels = null; + Map tags = null; + String jobId = null; + String channelReference = null; + String channelId = null; + String queueId = null; + String note = null; + String dispositionCode = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("labels".equals(fieldName)) { + labels = reader.readMap(reader1 -> reader1.getString()); + } else if ("tags".equals(fieldName)) { + tags = reader.readMap(reader1 -> reader1.getString()); + } else if ("jobId".equals(fieldName)) { + jobId = reader.getString(); + } else if ("channelReference".equals(fieldName)) { + channelReference = reader.getString(); + } else if ("channelId".equals(fieldName)) { + channelId = reader.getString(); + } else if ("queueId".equals(fieldName)) { + queueId = reader.getString(); + } else if ("note".equals(fieldName)) { + note = reader.getString(); + } else if ("dispositionCode".equals(fieldName)) { + dispositionCode = reader.getString(); + } else { + reader.skipChildren(); + } + } + AcsRouterJobCancelledEventData deserializedAcsRouterJobCancelledEventData + = new AcsRouterJobCancelledEventData(labels, tags); + deserializedAcsRouterJobCancelledEventData.jobId = jobId; + deserializedAcsRouterJobCancelledEventData.channelReference = channelReference; + deserializedAcsRouterJobCancelledEventData.channelId = channelId; + deserializedAcsRouterJobCancelledEventData.queueId = queueId; + deserializedAcsRouterJobCancelledEventData.note = note; + deserializedAcsRouterJobCancelledEventData.dispositionCode = dispositionCode; + + return deserializedAcsRouterJobCancelledEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobClassificationFailedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobClassificationFailedEventData.java new file mode 100644 index 000000000000..d762e3d7f84e --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobClassificationFailedEventData.java @@ -0,0 +1,211 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.models.ResponseError; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.messaging.eventgrid.implementation.models.AcsRouterCommunicationError; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobClassificationFailed event. + */ +@Immutable +public final class AcsRouterJobClassificationFailedEventData extends AcsRouterJobEventData { + + /* + * Router Job Classification Policy Id + */ + @Generated + private String classificationPolicyId; + + /* + * Router Job Classification Failed Errors + */ + @Generated + private final List errors; + + /* + * Router Job events Queue Id + */ + @Generated + private String queueId; + + /* + * Router Event Channel ID + */ + @Generated + private String channelId; + + /* + * Router Event Channel Reference + */ + @Generated + private String channelReference; + + /* + * Router Event Job ID + */ + @Generated + private String jobId; + + /** + * Creates an instance of AcsRouterJobClassificationFailedEventData class. + * + * @param labels the labels value to set. + * @param tags the tags value to set. + * @param errors the errors value to set. + */ + @Generated + private AcsRouterJobClassificationFailedEventData(Map labels, Map tags, + List errors) { + super(labels, tags); + this.errors = errors; + } + + /** + * Get the classificationPolicyId property: Router Job Classification Policy Id. + * + * @return the classificationPolicyId value. + */ + @Generated + public String getClassificationPolicyId() { + return this.classificationPolicyId; + } + + /** + * Get the errors property: Router Job Classification Failed Errors. + * + * @return the errors value. + */ + @Generated + public List getErrors() { + return this.errors.stream() + .map(e -> new ResponseError(e.getCode(), e.getMessage())) + .collect(Collectors.toList()); + } + + /** + * Get the queueId property: Router Job events Queue Id. + * + * @return the queueId value. + */ + @Generated + @Override + public String getQueueId() { + return this.queueId; + } + + /** + * Get the channelId property: Router Event Channel ID. + * + * @return the channelId value. + */ + @Generated + @Override + public String getChannelId() { + return this.channelId; + } + + /** + * Get the channelReference property: Router Event Channel Reference. + * + * @return the channelReference value. + */ + @Generated + @Override + public String getChannelReference() { + return this.channelReference; + } + + /** + * Get the jobId property: Router Event Job ID. + * + * @return the jobId value. + */ + @Generated + @Override + public String getJobId() { + return this.jobId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("labels", getLabels(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeMapField("tags", getTags(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("jobId", getJobId()); + jsonWriter.writeStringField("channelReference", getChannelReference()); + jsonWriter.writeStringField("channelId", getChannelId()); + jsonWriter.writeStringField("queueId", getQueueId()); + jsonWriter.writeArrayField("errors", this.errors, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("classificationPolicyId", this.classificationPolicyId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRouterJobClassificationFailedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRouterJobClassificationFailedEventData 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 AcsRouterJobClassificationFailedEventData. + */ + @Generated + public static AcsRouterJobClassificationFailedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Map labels = null; + Map tags = null; + String jobId = null; + String channelReference = null; + String channelId = null; + String queueId = null; + List errors = null; + String classificationPolicyId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("labels".equals(fieldName)) { + labels = reader.readMap(reader1 -> reader1.getString()); + } else if ("tags".equals(fieldName)) { + tags = reader.readMap(reader1 -> reader1.getString()); + } else if ("jobId".equals(fieldName)) { + jobId = reader.getString(); + } else if ("channelReference".equals(fieldName)) { + channelReference = reader.getString(); + } else if ("channelId".equals(fieldName)) { + channelId = reader.getString(); + } else if ("queueId".equals(fieldName)) { + queueId = reader.getString(); + } else if ("errors".equals(fieldName)) { + errors = reader.readArray(reader1 -> AcsRouterCommunicationError.fromJson(reader1)); + } else if ("classificationPolicyId".equals(fieldName)) { + classificationPolicyId = reader.getString(); + } else { + reader.skipChildren(); + } + } + AcsRouterJobClassificationFailedEventData deserializedAcsRouterJobClassificationFailedEventData + = new AcsRouterJobClassificationFailedEventData(labels, tags, errors); + deserializedAcsRouterJobClassificationFailedEventData.jobId = jobId; + deserializedAcsRouterJobClassificationFailedEventData.channelReference = channelReference; + deserializedAcsRouterJobClassificationFailedEventData.channelId = channelId; + deserializedAcsRouterJobClassificationFailedEventData.queueId = queueId; + deserializedAcsRouterJobClassificationFailedEventData.classificationPolicyId = classificationPolicyId; + return deserializedAcsRouterJobClassificationFailedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobClassifiedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobClassifiedEventData.java new file mode 100644 index 000000000000..92d7e3a0cf69 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobClassifiedEventData.java @@ -0,0 +1,252 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.List; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobClassified event. + */ +@Immutable +public final class AcsRouterJobClassifiedEventData extends AcsRouterJobEventData { + /* + * Router Job Queue Info + */ + @Generated + private final AcsRouterQueueDetails queueDetails; + + /* + * Router Job Classification Policy Id + */ + @Generated + private String classificationPolicyId; + + /* + * Router Job Priority + */ + @Generated + private Integer priority; + + /* + * Router Job Attached Worker Selector + */ + @Generated + private final List attachedWorkerSelectors; + + /* + * Router Job events Queue Id + */ + @Generated + private String queueId; + + /* + * Router Event Channel ID + */ + @Generated + private String channelId; + + /* + * Router Event Channel Reference + */ + @Generated + private String channelReference; + + /* + * Router Event Job ID + */ + @Generated + private String jobId; + + /** + * Creates an instance of AcsRouterJobClassifiedEventData class. + * + * @param labels the labels value to set. + * @param tags the tags value to set. + * @param queueDetails the queueDetails value to set. + * @param attachedWorkerSelectors the attachedWorkerSelectors value to set. + */ + @Generated + private AcsRouterJobClassifiedEventData(Map labels, Map tags, + AcsRouterQueueDetails queueDetails, List attachedWorkerSelectors) { + super(labels, tags); + this.queueDetails = queueDetails; + this.attachedWorkerSelectors = attachedWorkerSelectors; + } + + /** + * Get the queueDetails property: Router Job Queue Info. + * + * @return the queueDetails value. + */ + @Generated + public AcsRouterQueueDetails getQueueDetails() { + return this.queueDetails; + } + + /** + * Get the classificationPolicyId property: Router Job Classification Policy Id. + * + * @return the classificationPolicyId value. + */ + @Generated + public String getClassificationPolicyId() { + return this.classificationPolicyId; + } + + /** + * Get the priority property: Router Job Priority. + * + * @return the priority value. + */ + @Generated + public Integer getPriority() { + return this.priority; + } + + /** + * Get the attachedWorkerSelectors property: Router Job Attached Worker Selector. + * + * @return the attachedWorkerSelectors value. + */ + @Generated + public List getAttachedWorkerSelectors() { + return this.attachedWorkerSelectors; + } + + /** + * Get the queueId property: Router Job events Queue Id. + * + * @return the queueId value. + */ + @Generated + @Override + public String getQueueId() { + return this.queueId; + } + + /** + * Get the channelId property: Router Event Channel ID. + * + * @return the channelId value. + */ + @Generated + @Override + public String getChannelId() { + return this.channelId; + } + + /** + * Get the channelReference property: Router Event Channel Reference. + * + * @return the channelReference value. + */ + @Generated + @Override + public String getChannelReference() { + return this.channelReference; + } + + /** + * Get the jobId property: Router Event Job ID. + * + * @return the jobId value. + */ + @Generated + @Override + public String getJobId() { + return this.jobId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("labels", getLabels(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeMapField("tags", getTags(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("jobId", getJobId()); + jsonWriter.writeStringField("channelReference", getChannelReference()); + jsonWriter.writeStringField("channelId", getChannelId()); + jsonWriter.writeStringField("queueId", getQueueId()); + jsonWriter.writeJsonField("queueDetails", this.queueDetails); + jsonWriter.writeArrayField("attachedWorkerSelectors", this.attachedWorkerSelectors, + (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("classificationPolicyId", this.classificationPolicyId); + jsonWriter.writeNumberField("priority", this.priority); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRouterJobClassifiedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRouterJobClassifiedEventData 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 AcsRouterJobClassifiedEventData. + */ + @Generated + public static AcsRouterJobClassifiedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Map labels = null; + Map tags = null; + String jobId = null; + String channelReference = null; + String channelId = null; + String queueId = null; + AcsRouterQueueDetails queueDetails = null; + List attachedWorkerSelectors = null; + String classificationPolicyId = null; + Integer priority = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("labels".equals(fieldName)) { + labels = reader.readMap(reader1 -> reader1.getString()); + } else if ("tags".equals(fieldName)) { + tags = reader.readMap(reader1 -> reader1.getString()); + } else if ("jobId".equals(fieldName)) { + jobId = reader.getString(); + } else if ("channelReference".equals(fieldName)) { + channelReference = reader.getString(); + } else if ("channelId".equals(fieldName)) { + channelId = reader.getString(); + } else if ("queueId".equals(fieldName)) { + queueId = reader.getString(); + } else if ("queueDetails".equals(fieldName)) { + queueDetails = AcsRouterQueueDetails.fromJson(reader); + } else if ("attachedWorkerSelectors".equals(fieldName)) { + attachedWorkerSelectors = reader.readArray(reader1 -> AcsRouterWorkerSelector.fromJson(reader1)); + } else if ("classificationPolicyId".equals(fieldName)) { + classificationPolicyId = reader.getString(); + } else if ("priority".equals(fieldName)) { + priority = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + AcsRouterJobClassifiedEventData deserializedAcsRouterJobClassifiedEventData + = new AcsRouterJobClassifiedEventData(labels, tags, queueDetails, attachedWorkerSelectors); + deserializedAcsRouterJobClassifiedEventData.jobId = jobId; + deserializedAcsRouterJobClassifiedEventData.channelReference = channelReference; + deserializedAcsRouterJobClassifiedEventData.channelId = channelId; + deserializedAcsRouterJobClassifiedEventData.queueId = queueId; + deserializedAcsRouterJobClassifiedEventData.classificationPolicyId = classificationPolicyId; + deserializedAcsRouterJobClassifiedEventData.priority = priority; + + return deserializedAcsRouterJobClassifiedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobClosedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobClosedEventData.java new file mode 100644 index 000000000000..17bae397c85e --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobClosedEventData.java @@ -0,0 +1,226 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobClosed event. + */ +@Immutable +public final class AcsRouterJobClosedEventData extends AcsRouterJobEventData { + /* + * Router Job Closed Assignment Id + */ + @Generated + private String assignmentId; + + /* + * Router Job Closed Worker Id + */ + @Generated + private String workerId; + + /* + * Router Job Closed Disposition Code + */ + @Generated + private String dispositionCode; + + /* + * Router Job events Queue Id + */ + @Generated + private String queueId; + + /* + * Router Event Channel ID + */ + @Generated + private String channelId; + + /* + * Router Event Channel Reference + */ + @Generated + private String channelReference; + + /* + * Router Event Job ID + */ + @Generated + private String jobId; + + /** + * Creates an instance of AcsRouterJobClosedEventData class. + * + * @param labels the labels value to set. + * @param tags the tags value to set. + */ + @Generated + private AcsRouterJobClosedEventData(Map labels, Map tags) { + super(labels, tags); + } + + /** + * Get the assignmentId property: Router Job Closed Assignment Id. + * + * @return the assignmentId value. + */ + @Generated + public String getAssignmentId() { + return this.assignmentId; + } + + /** + * Get the workerId property: Router Job Closed Worker Id. + * + * @return the workerId value. + */ + @Generated + public String getWorkerId() { + return this.workerId; + } + + /** + * Get the dispositionCode property: Router Job Closed Disposition Code. + * + * @return the dispositionCode value. + */ + @Generated + public String getDispositionCode() { + return this.dispositionCode; + } + + /** + * Get the queueId property: Router Job events Queue Id. + * + * @return the queueId value. + */ + @Generated + @Override + public String getQueueId() { + return this.queueId; + } + + /** + * Get the channelId property: Router Event Channel ID. + * + * @return the channelId value. + */ + @Generated + @Override + public String getChannelId() { + return this.channelId; + } + + /** + * Get the channelReference property: Router Event Channel Reference. + * + * @return the channelReference value. + */ + @Generated + @Override + public String getChannelReference() { + return this.channelReference; + } + + /** + * Get the jobId property: Router Event Job ID. + * + * @return the jobId value. + */ + @Generated + @Override + public String getJobId() { + return this.jobId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("labels", getLabels(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeMapField("tags", getTags(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("jobId", getJobId()); + jsonWriter.writeStringField("channelReference", getChannelReference()); + jsonWriter.writeStringField("channelId", getChannelId()); + jsonWriter.writeStringField("queueId", getQueueId()); + jsonWriter.writeStringField("assignmentId", this.assignmentId); + jsonWriter.writeStringField("workerId", this.workerId); + jsonWriter.writeStringField("dispositionCode", this.dispositionCode); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRouterJobClosedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRouterJobClosedEventData 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 AcsRouterJobClosedEventData. + */ + @Generated + public static AcsRouterJobClosedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Map labels = null; + Map tags = null; + String jobId = null; + String channelReference = null; + String channelId = null; + String queueId = null; + String assignmentId = null; + String workerId = null; + String dispositionCode = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("labels".equals(fieldName)) { + labels = reader.readMap(reader1 -> reader1.getString()); + } else if ("tags".equals(fieldName)) { + tags = reader.readMap(reader1 -> reader1.getString()); + } else if ("jobId".equals(fieldName)) { + jobId = reader.getString(); + } else if ("channelReference".equals(fieldName)) { + channelReference = reader.getString(); + } else if ("channelId".equals(fieldName)) { + channelId = reader.getString(); + } else if ("queueId".equals(fieldName)) { + queueId = reader.getString(); + } else if ("assignmentId".equals(fieldName)) { + assignmentId = reader.getString(); + } else if ("workerId".equals(fieldName)) { + workerId = reader.getString(); + } else if ("dispositionCode".equals(fieldName)) { + dispositionCode = reader.getString(); + } else { + reader.skipChildren(); + } + } + AcsRouterJobClosedEventData deserializedAcsRouterJobClosedEventData + = new AcsRouterJobClosedEventData(labels, tags); + deserializedAcsRouterJobClosedEventData.jobId = jobId; + deserializedAcsRouterJobClosedEventData.channelReference = channelReference; + deserializedAcsRouterJobClosedEventData.channelId = channelId; + deserializedAcsRouterJobClosedEventData.queueId = queueId; + deserializedAcsRouterJobClosedEventData.assignmentId = assignmentId; + deserializedAcsRouterJobClosedEventData.workerId = workerId; + deserializedAcsRouterJobClosedEventData.dispositionCode = dispositionCode; + + return deserializedAcsRouterJobClosedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobCompletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobCompletedEventData.java new file mode 100644 index 000000000000..77319a2b1c27 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobCompletedEventData.java @@ -0,0 +1,205 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobCompleted event. + */ +@Immutable +public final class AcsRouterJobCompletedEventData extends AcsRouterJobEventData { + /* + * Router Job Completed Assignment Id + */ + @Generated + private String assignmentId; + + /* + * Router Job Completed Worker Id + */ + @Generated + private String workerId; + + /* + * Router Job events Queue Id + */ + @Generated + private String queueId; + + /* + * Router Event Channel ID + */ + @Generated + private String channelId; + + /* + * Router Event Channel Reference + */ + @Generated + private String channelReference; + + /* + * Router Event Job ID + */ + @Generated + private String jobId; + + /** + * Creates an instance of AcsRouterJobCompletedEventData class. + * + * @param labels the labels value to set. + * @param tags the tags value to set. + */ + @Generated + private AcsRouterJobCompletedEventData(Map labels, Map tags) { + super(labels, tags); + } + + /** + * Get the assignmentId property: Router Job Completed Assignment Id. + * + * @return the assignmentId value. + */ + @Generated + public String getAssignmentId() { + return this.assignmentId; + } + + /** + * Get the workerId property: Router Job Completed Worker Id. + * + * @return the workerId value. + */ + @Generated + public String getWorkerId() { + return this.workerId; + } + + /** + * Get the queueId property: Router Job events Queue Id. + * + * @return the queueId value. + */ + @Generated + @Override + public String getQueueId() { + return this.queueId; + } + + /** + * Get the channelId property: Router Event Channel ID. + * + * @return the channelId value. + */ + @Generated + @Override + public String getChannelId() { + return this.channelId; + } + + /** + * Get the channelReference property: Router Event Channel Reference. + * + * @return the channelReference value. + */ + @Generated + @Override + public String getChannelReference() { + return this.channelReference; + } + + /** + * Get the jobId property: Router Event Job ID. + * + * @return the jobId value. + */ + @Generated + @Override + public String getJobId() { + return this.jobId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("labels", getLabels(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeMapField("tags", getTags(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("jobId", getJobId()); + jsonWriter.writeStringField("channelReference", getChannelReference()); + jsonWriter.writeStringField("channelId", getChannelId()); + jsonWriter.writeStringField("queueId", getQueueId()); + jsonWriter.writeStringField("assignmentId", this.assignmentId); + jsonWriter.writeStringField("workerId", this.workerId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRouterJobCompletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRouterJobCompletedEventData 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 AcsRouterJobCompletedEventData. + */ + @Generated + public static AcsRouterJobCompletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Map labels = null; + Map tags = null; + String jobId = null; + String channelReference = null; + String channelId = null; + String queueId = null; + String assignmentId = null; + String workerId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("labels".equals(fieldName)) { + labels = reader.readMap(reader1 -> reader1.getString()); + } else if ("tags".equals(fieldName)) { + tags = reader.readMap(reader1 -> reader1.getString()); + } else if ("jobId".equals(fieldName)) { + jobId = reader.getString(); + } else if ("channelReference".equals(fieldName)) { + channelReference = reader.getString(); + } else if ("channelId".equals(fieldName)) { + channelId = reader.getString(); + } else if ("queueId".equals(fieldName)) { + queueId = reader.getString(); + } else if ("assignmentId".equals(fieldName)) { + assignmentId = reader.getString(); + } else if ("workerId".equals(fieldName)) { + workerId = reader.getString(); + } else { + reader.skipChildren(); + } + } + AcsRouterJobCompletedEventData deserializedAcsRouterJobCompletedEventData + = new AcsRouterJobCompletedEventData(labels, tags); + deserializedAcsRouterJobCompletedEventData.jobId = jobId; + deserializedAcsRouterJobCompletedEventData.channelReference = channelReference; + deserializedAcsRouterJobCompletedEventData.channelId = channelId; + deserializedAcsRouterJobCompletedEventData.queueId = queueId; + deserializedAcsRouterJobCompletedEventData.assignmentId = assignmentId; + deserializedAcsRouterJobCompletedEventData.workerId = workerId; + + return deserializedAcsRouterJobCompletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobDeletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobDeletedEventData.java new file mode 100644 index 000000000000..37923cfcd8b9 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobDeletedEventData.java @@ -0,0 +1,163 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobDeleted event. + */ +@Immutable +public final class AcsRouterJobDeletedEventData extends AcsRouterJobEventData { + /* + * Router Job events Queue Id + */ + @Generated + private String queueId; + + /* + * Router Event Channel ID + */ + @Generated + private String channelId; + + /* + * Router Event Channel Reference + */ + @Generated + private String channelReference; + + /* + * Router Event Job ID + */ + @Generated + private String jobId; + + /** + * Creates an instance of AcsRouterJobDeletedEventData class. + * + * @param labels the labels value to set. + * @param tags the tags value to set. + */ + @Generated + private AcsRouterJobDeletedEventData(Map labels, Map tags) { + super(labels, tags); + } + + /** + * Get the queueId property: Router Job events Queue Id. + * + * @return the queueId value. + */ + @Generated + @Override + public String getQueueId() { + return this.queueId; + } + + /** + * Get the channelId property: Router Event Channel ID. + * + * @return the channelId value. + */ + @Generated + @Override + public String getChannelId() { + return this.channelId; + } + + /** + * Get the channelReference property: Router Event Channel Reference. + * + * @return the channelReference value. + */ + @Generated + @Override + public String getChannelReference() { + return this.channelReference; + } + + /** + * Get the jobId property: Router Event Job ID. + * + * @return the jobId value. + */ + @Generated + @Override + public String getJobId() { + return this.jobId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("labels", getLabels(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeMapField("tags", getTags(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("jobId", getJobId()); + jsonWriter.writeStringField("channelReference", getChannelReference()); + jsonWriter.writeStringField("channelId", getChannelId()); + jsonWriter.writeStringField("queueId", getQueueId()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRouterJobDeletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRouterJobDeletedEventData 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 AcsRouterJobDeletedEventData. + */ + @Generated + public static AcsRouterJobDeletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Map labels = null; + Map tags = null; + String jobId = null; + String channelReference = null; + String channelId = null; + String queueId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("labels".equals(fieldName)) { + labels = reader.readMap(reader1 -> reader1.getString()); + } else if ("tags".equals(fieldName)) { + tags = reader.readMap(reader1 -> reader1.getString()); + } else if ("jobId".equals(fieldName)) { + jobId = reader.getString(); + } else if ("channelReference".equals(fieldName)) { + channelReference = reader.getString(); + } else if ("channelId".equals(fieldName)) { + channelId = reader.getString(); + } else if ("queueId".equals(fieldName)) { + queueId = reader.getString(); + } else { + reader.skipChildren(); + } + } + AcsRouterJobDeletedEventData deserializedAcsRouterJobDeletedEventData + = new AcsRouterJobDeletedEventData(labels, tags); + deserializedAcsRouterJobDeletedEventData.jobId = jobId; + deserializedAcsRouterJobDeletedEventData.channelReference = channelReference; + deserializedAcsRouterJobDeletedEventData.channelId = channelId; + deserializedAcsRouterJobDeletedEventData.queueId = queueId; + + return deserializedAcsRouterJobDeletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobEventData.java new file mode 100644 index 000000000000..6952a3112f23 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobEventData.java @@ -0,0 +1,206 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.Map; + +/** + * Schema of common properties of all Router Job events. + */ +@Immutable +public class AcsRouterJobEventData extends AcsRouterEventData { + /* + * Router Job events Queue Id + */ + @Generated + private String queueId; + + /* + * Router Job events Labels + */ + @Generated + private final Map labels; + + /* + * Router Jobs events Tags + */ + @Generated + private final Map tags; + + /* + * Router Event Channel ID + */ + @Generated + private String channelId; + + /* + * Router Event Channel Reference + */ + @Generated + private String channelReference; + + /* + * Router Event Job ID + */ + @Generated + private String jobId; + + /** + * Creates an instance of AcsRouterJobEventData class. + * + * @param labels the labels value to set. + * @param tags the tags value to set. + */ + @Generated + protected AcsRouterJobEventData(Map labels, Map tags) { + this.labels = labels; + this.tags = tags; + } + + /** + * Get the queueId property: Router Job events Queue Id. + * + * @return the queueId value. + */ + @Generated + public String getQueueId() { + return this.queueId; + } + + /** + * Set the queueId property: Router Job events Queue Id. + * + * @param queueId the queueId value to set. + * @return the AcsRouterJobEventData object itself. + */ + @Generated + AcsRouterJobEventData setQueueId(String queueId) { + this.queueId = queueId; + return this; + } + + /** + * Get the labels property: Router Job events Labels. + * + * @return the labels value. + */ + @Generated + public Map getLabels() { + return this.labels; + } + + /** + * Get the tags property: Router Jobs events Tags. + * + * @return the tags value. + */ + @Generated + public Map getTags() { + return this.tags; + } + + /** + * Get the channelId property: Router Event Channel ID. + * + * @return the channelId value. + */ + @Generated + @Override + public String getChannelId() { + return this.channelId; + } + + /** + * Get the channelReference property: Router Event Channel Reference. + * + * @return the channelReference value. + */ + @Generated + @Override + public String getChannelReference() { + return this.channelReference; + } + + /** + * Get the jobId property: Router Event Job ID. + * + * @return the jobId value. + */ + @Generated + @Override + public String getJobId() { + return this.jobId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("jobId", getJobId()); + jsonWriter.writeStringField("channelReference", getChannelReference()); + jsonWriter.writeStringField("channelId", getChannelId()); + jsonWriter.writeMapField("labels", this.labels, (writer, element) -> writer.writeString(element)); + jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("queueId", this.queueId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRouterJobEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRouterJobEventData 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 AcsRouterJobEventData. + */ + @Generated + public static AcsRouterJobEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String jobId = null; + String channelReference = null; + String channelId = null; + Map labels = null; + Map tags = null; + String queueId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("jobId".equals(fieldName)) { + jobId = reader.getString(); + } else if ("channelReference".equals(fieldName)) { + channelReference = reader.getString(); + } else if ("channelId".equals(fieldName)) { + channelId = reader.getString(); + } else if ("labels".equals(fieldName)) { + labels = reader.readMap(reader1 -> reader1.getString()); + } else if ("tags".equals(fieldName)) { + tags = reader.readMap(reader1 -> reader1.getString()); + } else if ("queueId".equals(fieldName)) { + queueId = reader.getString(); + } else { + reader.skipChildren(); + } + } + AcsRouterJobEventData deserializedAcsRouterJobEventData = new AcsRouterJobEventData(labels, tags); + deserializedAcsRouterJobEventData.jobId = jobId; + deserializedAcsRouterJobEventData.channelReference = channelReference; + deserializedAcsRouterJobEventData.channelId = channelId; + deserializedAcsRouterJobEventData.queueId = queueId; + + return deserializedAcsRouterJobEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobExceptionTriggeredEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobExceptionTriggeredEventData.java new file mode 100644 index 000000000000..2138b1fee550 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobExceptionTriggeredEventData.java @@ -0,0 +1,205 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobExceptionTriggered event. + */ +@Immutable +public final class AcsRouterJobExceptionTriggeredEventData extends AcsRouterJobEventData { + /* + * Router Job Exception Triggered Rule Key + */ + @Generated + private String ruleKey; + + /* + * Router Job Exception Triggered Rule Id + */ + @Generated + private String exceptionRuleId; + + /* + * Router Job events Queue Id + */ + @Generated + private String queueId; + + /* + * Router Event Channel ID + */ + @Generated + private String channelId; + + /* + * Router Event Channel Reference + */ + @Generated + private String channelReference; + + /* + * Router Event Job ID + */ + @Generated + private String jobId; + + /** + * Creates an instance of AcsRouterJobExceptionTriggeredEventData class. + * + * @param labels the labels value to set. + * @param tags the tags value to set. + */ + @Generated + private AcsRouterJobExceptionTriggeredEventData(Map labels, Map tags) { + super(labels, tags); + } + + /** + * Get the ruleKey property: Router Job Exception Triggered Rule Key. + * + * @return the ruleKey value. + */ + @Generated + public String getRuleKey() { + return this.ruleKey; + } + + /** + * Get the exceptionRuleId property: Router Job Exception Triggered Rule Id. + * + * @return the exceptionRuleId value. + */ + @Generated + public String getExceptionRuleId() { + return this.exceptionRuleId; + } + + /** + * Get the queueId property: Router Job events Queue Id. + * + * @return the queueId value. + */ + @Generated + @Override + public String getQueueId() { + return this.queueId; + } + + /** + * Get the channelId property: Router Event Channel ID. + * + * @return the channelId value. + */ + @Generated + @Override + public String getChannelId() { + return this.channelId; + } + + /** + * Get the channelReference property: Router Event Channel Reference. + * + * @return the channelReference value. + */ + @Generated + @Override + public String getChannelReference() { + return this.channelReference; + } + + /** + * Get the jobId property: Router Event Job ID. + * + * @return the jobId value. + */ + @Generated + @Override + public String getJobId() { + return this.jobId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("labels", getLabels(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeMapField("tags", getTags(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("jobId", getJobId()); + jsonWriter.writeStringField("channelReference", getChannelReference()); + jsonWriter.writeStringField("channelId", getChannelId()); + jsonWriter.writeStringField("queueId", getQueueId()); + jsonWriter.writeStringField("ruleKey", this.ruleKey); + jsonWriter.writeStringField("exceptionRuleId", this.exceptionRuleId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRouterJobExceptionTriggeredEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRouterJobExceptionTriggeredEventData 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 AcsRouterJobExceptionTriggeredEventData. + */ + @Generated + public static AcsRouterJobExceptionTriggeredEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Map labels = null; + Map tags = null; + String jobId = null; + String channelReference = null; + String channelId = null; + String queueId = null; + String ruleKey = null; + String exceptionRuleId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("labels".equals(fieldName)) { + labels = reader.readMap(reader1 -> reader1.getString()); + } else if ("tags".equals(fieldName)) { + tags = reader.readMap(reader1 -> reader1.getString()); + } else if ("jobId".equals(fieldName)) { + jobId = reader.getString(); + } else if ("channelReference".equals(fieldName)) { + channelReference = reader.getString(); + } else if ("channelId".equals(fieldName)) { + channelId = reader.getString(); + } else if ("queueId".equals(fieldName)) { + queueId = reader.getString(); + } else if ("ruleKey".equals(fieldName)) { + ruleKey = reader.getString(); + } else if ("exceptionRuleId".equals(fieldName)) { + exceptionRuleId = reader.getString(); + } else { + reader.skipChildren(); + } + } + AcsRouterJobExceptionTriggeredEventData deserializedAcsRouterJobExceptionTriggeredEventData + = new AcsRouterJobExceptionTriggeredEventData(labels, tags); + deserializedAcsRouterJobExceptionTriggeredEventData.jobId = jobId; + deserializedAcsRouterJobExceptionTriggeredEventData.channelReference = channelReference; + deserializedAcsRouterJobExceptionTriggeredEventData.channelId = channelId; + deserializedAcsRouterJobExceptionTriggeredEventData.queueId = queueId; + deserializedAcsRouterJobExceptionTriggeredEventData.ruleKey = ruleKey; + deserializedAcsRouterJobExceptionTriggeredEventData.exceptionRuleId = exceptionRuleId; + + return deserializedAcsRouterJobExceptionTriggeredEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobQueuedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobQueuedEventData.java new file mode 100644 index 000000000000..67a1a47194c1 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobQueuedEventData.java @@ -0,0 +1,232 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.List; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobQueued event. + */ +@Immutable +public final class AcsRouterJobQueuedEventData extends AcsRouterJobEventData { + /* + * Router Job Priority + */ + @Generated + private Integer priority; + + /* + * Router Job Queued Attached Worker Selector + */ + @Generated + private final List attachedWorkerSelectors; + + /* + * Router Job Queued Requested Worker Selector + */ + @Generated + private final List requestedWorkerSelectors; + + /* + * Router Job events Queue Id + */ + @Generated + private String queueId; + + /* + * Router Event Channel ID + */ + @Generated + private String channelId; + + /* + * Router Event Channel Reference + */ + @Generated + private String channelReference; + + /* + * Router Event Job ID + */ + @Generated + private String jobId; + + /** + * Creates an instance of AcsRouterJobQueuedEventData class. + * + * @param labels the labels value to set. + * @param tags the tags value to set. + * @param attachedWorkerSelectors the attachedWorkerSelectors value to set. + * @param requestedWorkerSelectors the requestedWorkerSelectors value to set. + */ + @Generated + private AcsRouterJobQueuedEventData(Map labels, Map tags, + List attachedWorkerSelectors, List requestedWorkerSelectors) { + super(labels, tags); + this.attachedWorkerSelectors = attachedWorkerSelectors; + this.requestedWorkerSelectors = requestedWorkerSelectors; + } + + /** + * Get the priority property: Router Job Priority. + * + * @return the priority value. + */ + @Generated + public Integer getPriority() { + return this.priority; + } + + /** + * Get the attachedWorkerSelectors property: Router Job Queued Attached Worker Selector. + * + * @return the attachedWorkerSelectors value. + */ + @Generated + public List getAttachedWorkerSelectors() { + return this.attachedWorkerSelectors; + } + + /** + * Get the requestedWorkerSelectors property: Router Job Queued Requested Worker Selector. + * + * @return the requestedWorkerSelectors value. + */ + @Generated + public List getRequestedWorkerSelectors() { + return this.requestedWorkerSelectors; + } + + /** + * Get the queueId property: Router Job events Queue Id. + * + * @return the queueId value. + */ + @Generated + @Override + public String getQueueId() { + return this.queueId; + } + + /** + * Get the channelId property: Router Event Channel ID. + * + * @return the channelId value. + */ + @Generated + @Override + public String getChannelId() { + return this.channelId; + } + + /** + * Get the channelReference property: Router Event Channel Reference. + * + * @return the channelReference value. + */ + @Generated + @Override + public String getChannelReference() { + return this.channelReference; + } + + /** + * Get the jobId property: Router Event Job ID. + * + * @return the jobId value. + */ + @Generated + @Override + public String getJobId() { + return this.jobId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("labels", getLabels(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeMapField("tags", getTags(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("jobId", getJobId()); + jsonWriter.writeStringField("channelReference", getChannelReference()); + jsonWriter.writeStringField("channelId", getChannelId()); + jsonWriter.writeStringField("queueId", getQueueId()); + jsonWriter.writeArrayField("attachedWorkerSelectors", this.attachedWorkerSelectors, + (writer, element) -> writer.writeJson(element)); + jsonWriter.writeArrayField("requestedWorkerSelectors", this.requestedWorkerSelectors, + (writer, element) -> writer.writeJson(element)); + jsonWriter.writeNumberField("priority", this.priority); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRouterJobQueuedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRouterJobQueuedEventData 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 AcsRouterJobQueuedEventData. + */ + @Generated + public static AcsRouterJobQueuedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Map labels = null; + Map tags = null; + String jobId = null; + String channelReference = null; + String channelId = null; + String queueId = null; + List attachedWorkerSelectors = null; + List requestedWorkerSelectors = null; + Integer priority = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("labels".equals(fieldName)) { + labels = reader.readMap(reader1 -> reader1.getString()); + } else if ("tags".equals(fieldName)) { + tags = reader.readMap(reader1 -> reader1.getString()); + } else if ("jobId".equals(fieldName)) { + jobId = reader.getString(); + } else if ("channelReference".equals(fieldName)) { + channelReference = reader.getString(); + } else if ("channelId".equals(fieldName)) { + channelId = reader.getString(); + } else if ("queueId".equals(fieldName)) { + queueId = reader.getString(); + } else if ("attachedWorkerSelectors".equals(fieldName)) { + attachedWorkerSelectors = reader.readArray(reader1 -> AcsRouterWorkerSelector.fromJson(reader1)); + } else if ("requestedWorkerSelectors".equals(fieldName)) { + requestedWorkerSelectors = reader.readArray(reader1 -> AcsRouterWorkerSelector.fromJson(reader1)); + } else if ("priority".equals(fieldName)) { + priority = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + AcsRouterJobQueuedEventData deserializedAcsRouterJobQueuedEventData + = new AcsRouterJobQueuedEventData(labels, tags, attachedWorkerSelectors, requestedWorkerSelectors); + deserializedAcsRouterJobQueuedEventData.jobId = jobId; + deserializedAcsRouterJobQueuedEventData.channelReference = channelReference; + deserializedAcsRouterJobQueuedEventData.channelId = channelId; + deserializedAcsRouterJobQueuedEventData.queueId = queueId; + deserializedAcsRouterJobQueuedEventData.priority = priority; + + return deserializedAcsRouterJobQueuedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobReceivedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobReceivedEventData.java new file mode 100644 index 000000000000..767d777029b5 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobReceivedEventData.java @@ -0,0 +1,302 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.List; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobReceived event. + */ +@Immutable +public final class AcsRouterJobReceivedEventData extends AcsRouterJobEventData { + /* + * Router Job Received Job Status + */ + @Generated + private final AcsRouterJobStatus jobStatus; + + /* + * Router Job Classification Policy Id + */ + @Generated + private String classificationPolicyId; + + /* + * Router Job Priority + */ + @Generated + private Integer priority; + + /* + * Router Job Received Requested Worker Selectors + */ + @Generated + private final List requestedWorkerSelectors; + + /* + * Router Job Received Scheduled Time in UTC + */ + @Generated + private final OffsetDateTime scheduledOn; + + /* + * Unavailable For Matching for Router Job Received + */ + @Generated + private final boolean unavailableForMatching; + + /* + * Router Job events Queue Id + */ + @Generated + private String queueId; + + /* + * Router Event Channel ID + */ + @Generated + private String channelId; + + /* + * Router Event Channel Reference + */ + @Generated + private String channelReference; + + /* + * Router Event Job ID + */ + @Generated + private String jobId; + + /** + * Creates an instance of AcsRouterJobReceivedEventData class. + * + * @param labels the labels value to set. + * @param tags the tags value to set. + * @param jobStatus the jobStatus value to set. + * @param requestedWorkerSelectors the requestedWorkerSelectors value to set. + * @param scheduledOn the scheduledOn value to set. + * @param unavailableForMatching the unavailableForMatching value to set. + */ + @Generated + private AcsRouterJobReceivedEventData(Map labels, Map tags, + AcsRouterJobStatus jobStatus, List requestedWorkerSelectors, + OffsetDateTime scheduledOn, boolean unavailableForMatching) { + super(labels, tags); + this.jobStatus = jobStatus; + this.requestedWorkerSelectors = requestedWorkerSelectors; + this.scheduledOn = scheduledOn; + this.unavailableForMatching = unavailableForMatching; + } + + /** + * Get the jobStatus property: Router Job Received Job Status. + * + * @return the jobStatus value. + */ + @Generated + public AcsRouterJobStatus getJobStatus() { + return this.jobStatus; + } + + /** + * Get the classificationPolicyId property: Router Job Classification Policy Id. + * + * @return the classificationPolicyId value. + */ + @Generated + public String getClassificationPolicyId() { + return this.classificationPolicyId; + } + + /** + * Get the priority property: Router Job Priority. + * + * @return the priority value. + */ + @Generated + public Integer getPriority() { + return this.priority; + } + + /** + * Get the requestedWorkerSelectors property: Router Job Received Requested Worker Selectors. + * + * @return the requestedWorkerSelectors value. + */ + @Generated + public List getRequestedWorkerSelectors() { + return this.requestedWorkerSelectors; + } + + /** + * Get the scheduledOn property: Router Job Received Scheduled Time in UTC. + * + * @return the scheduledOn value. + */ + @Generated + public OffsetDateTime getScheduledOn() { + return this.scheduledOn; + } + + /** + * Get the unavailableForMatching property: Unavailable For Matching for Router Job Received. + * + * @return the unavailableForMatching value. + */ + @Generated + public boolean isUnavailableForMatching() { + return this.unavailableForMatching; + } + + /** + * Get the queueId property: Router Job events Queue Id. + * + * @return the queueId value. + */ + @Generated + @Override + public String getQueueId() { + return this.queueId; + } + + /** + * Get the channelId property: Router Event Channel ID. + * + * @return the channelId value. + */ + @Generated + @Override + public String getChannelId() { + return this.channelId; + } + + /** + * Get the channelReference property: Router Event Channel Reference. + * + * @return the channelReference value. + */ + @Generated + @Override + public String getChannelReference() { + return this.channelReference; + } + + /** + * Get the jobId property: Router Event Job ID. + * + * @return the jobId value. + */ + @Generated + @Override + public String getJobId() { + return this.jobId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("labels", getLabels(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeMapField("tags", getTags(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("jobId", getJobId()); + jsonWriter.writeStringField("channelReference", getChannelReference()); + jsonWriter.writeStringField("channelId", getChannelId()); + jsonWriter.writeStringField("queueId", getQueueId()); + jsonWriter.writeStringField("jobStatus", this.jobStatus == null ? null : this.jobStatus.toString()); + jsonWriter.writeArrayField("requestedWorkerSelectors", this.requestedWorkerSelectors, + (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("scheduledOn", + this.scheduledOn == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.scheduledOn)); + jsonWriter.writeBooleanField("unavailableForMatching", this.unavailableForMatching); + jsonWriter.writeStringField("classificationPolicyId", this.classificationPolicyId); + jsonWriter.writeNumberField("priority", this.priority); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRouterJobReceivedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRouterJobReceivedEventData 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 AcsRouterJobReceivedEventData. + */ + @Generated + public static AcsRouterJobReceivedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Map labels = null; + Map tags = null; + String jobId = null; + String channelReference = null; + String channelId = null; + String queueId = null; + AcsRouterJobStatus jobStatus = null; + List requestedWorkerSelectors = null; + OffsetDateTime scheduledOn = null; + boolean unavailableForMatching = false; + String classificationPolicyId = null; + Integer priority = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("labels".equals(fieldName)) { + labels = reader.readMap(reader1 -> reader1.getString()); + } else if ("tags".equals(fieldName)) { + tags = reader.readMap(reader1 -> reader1.getString()); + } else if ("jobId".equals(fieldName)) { + jobId = reader.getString(); + } else if ("channelReference".equals(fieldName)) { + channelReference = reader.getString(); + } else if ("channelId".equals(fieldName)) { + channelId = reader.getString(); + } else if ("queueId".equals(fieldName)) { + queueId = reader.getString(); + } else if ("jobStatus".equals(fieldName)) { + jobStatus = AcsRouterJobStatus.fromString(reader.getString()); + } else if ("requestedWorkerSelectors".equals(fieldName)) { + requestedWorkerSelectors = reader.readArray(reader1 -> AcsRouterWorkerSelector.fromJson(reader1)); + } else if ("scheduledOn".equals(fieldName)) { + scheduledOn = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("unavailableForMatching".equals(fieldName)) { + unavailableForMatching = reader.getBoolean(); + } else if ("classificationPolicyId".equals(fieldName)) { + classificationPolicyId = reader.getString(); + } else if ("priority".equals(fieldName)) { + priority = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + AcsRouterJobReceivedEventData deserializedAcsRouterJobReceivedEventData = new AcsRouterJobReceivedEventData( + labels, tags, jobStatus, requestedWorkerSelectors, scheduledOn, unavailableForMatching); + deserializedAcsRouterJobReceivedEventData.jobId = jobId; + deserializedAcsRouterJobReceivedEventData.channelReference = channelReference; + deserializedAcsRouterJobReceivedEventData.channelId = channelId; + deserializedAcsRouterJobReceivedEventData.queueId = queueId; + deserializedAcsRouterJobReceivedEventData.classificationPolicyId = classificationPolicyId; + deserializedAcsRouterJobReceivedEventData.priority = priority; + + return deserializedAcsRouterJobReceivedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobSchedulingFailedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobSchedulingFailedEventData.java new file mode 100644 index 000000000000..b57e9aa989aa --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobSchedulingFailedEventData.java @@ -0,0 +1,284 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.List; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobSchedulingFailed event. + */ +@Immutable +public final class AcsRouterJobSchedulingFailedEventData extends AcsRouterJobEventData { + /* + * Router Job Priority + */ + @Generated + private Integer priority; + + /* + * Router Job Scheduling Failed Attached Worker Selector Expired + */ + @Generated + private final List expiredAttachedWorkerSelectors; + + /* + * Router Job Scheduling Failed Requested Worker Selector Expired + */ + @Generated + private final List expiredRequestedWorkerSelectors; + + /* + * Router Job Scheduling Failed Scheduled Time in UTC + */ + @Generated + private final OffsetDateTime scheduledOn; + + /* + * Router Job Scheduling Failed Reason + */ + @Generated + private String failureReason; + + /* + * Router Job events Queue Id + */ + @Generated + private String queueId; + + /* + * Router Event Channel ID + */ + @Generated + private String channelId; + + /* + * Router Event Channel Reference + */ + @Generated + private String channelReference; + + /* + * Router Event Job ID + */ + @Generated + private String jobId; + + /** + * Creates an instance of AcsRouterJobSchedulingFailedEventData class. + * + * @param labels the labels value to set. + * @param tags the tags value to set. + * @param expiredAttachedWorkerSelectors the expiredAttachedWorkerSelectors value to set. + * @param expiredRequestedWorkerSelectors the expiredRequestedWorkerSelectors value to set. + * @param scheduledOn the scheduledOn value to set. + */ + @Generated + private AcsRouterJobSchedulingFailedEventData(Map labels, Map tags, + List expiredAttachedWorkerSelectors, + List expiredRequestedWorkerSelectors, OffsetDateTime scheduledOn) { + super(labels, tags); + this.expiredAttachedWorkerSelectors = expiredAttachedWorkerSelectors; + this.expiredRequestedWorkerSelectors = expiredRequestedWorkerSelectors; + this.scheduledOn = scheduledOn; + } + + /** + * Get the priority property: Router Job Priority. + * + * @return the priority value. + */ + @Generated + public Integer getPriority() { + return this.priority; + } + + /** + * Get the expiredAttachedWorkerSelectors property: Router Job Scheduling Failed Attached Worker Selector Expired. + * + * @return the expiredAttachedWorkerSelectors value. + */ + @Generated + public List getExpiredAttachedWorkerSelectors() { + return this.expiredAttachedWorkerSelectors; + } + + /** + * Get the expiredRequestedWorkerSelectors property: Router Job Scheduling Failed Requested Worker Selector Expired. + * + * @return the expiredRequestedWorkerSelectors value. + */ + @Generated + public List getExpiredRequestedWorkerSelectors() { + return this.expiredRequestedWorkerSelectors; + } + + /** + * Get the scheduledOn property: Router Job Scheduling Failed Scheduled Time in UTC. + * + * @return the scheduledOn value. + */ + @Generated + public OffsetDateTime getScheduledOn() { + return this.scheduledOn; + } + + /** + * Get the failureReason property: Router Job Scheduling Failed Reason. + * + * @return the failureReason value. + */ + @Generated + public String getFailureReason() { + return this.failureReason; + } + + /** + * Get the queueId property: Router Job events Queue Id. + * + * @return the queueId value. + */ + @Generated + @Override + public String getQueueId() { + return this.queueId; + } + + /** + * Get the channelId property: Router Event Channel ID. + * + * @return the channelId value. + */ + @Generated + @Override + public String getChannelId() { + return this.channelId; + } + + /** + * Get the channelReference property: Router Event Channel Reference. + * + * @return the channelReference value. + */ + @Generated + @Override + public String getChannelReference() { + return this.channelReference; + } + + /** + * Get the jobId property: Router Event Job ID. + * + * @return the jobId value. + */ + @Generated + @Override + public String getJobId() { + return this.jobId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("labels", getLabels(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeMapField("tags", getTags(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("jobId", getJobId()); + jsonWriter.writeStringField("channelReference", getChannelReference()); + jsonWriter.writeStringField("channelId", getChannelId()); + jsonWriter.writeStringField("queueId", getQueueId()); + jsonWriter.writeArrayField("expiredAttachedWorkerSelectors", this.expiredAttachedWorkerSelectors, + (writer, element) -> writer.writeJson(element)); + jsonWriter.writeArrayField("expiredRequestedWorkerSelectors", this.expiredRequestedWorkerSelectors, + (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("scheduledOn", + this.scheduledOn == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.scheduledOn)); + jsonWriter.writeNumberField("priority", this.priority); + jsonWriter.writeStringField("failureReason", this.failureReason); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRouterJobSchedulingFailedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRouterJobSchedulingFailedEventData 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 AcsRouterJobSchedulingFailedEventData. + */ + @Generated + public static AcsRouterJobSchedulingFailedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Map labels = null; + Map tags = null; + String jobId = null; + String channelReference = null; + String channelId = null; + String queueId = null; + List expiredAttachedWorkerSelectors = null; + List expiredRequestedWorkerSelectors = null; + OffsetDateTime scheduledOn = null; + Integer priority = null; + String failureReason = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("labels".equals(fieldName)) { + labels = reader.readMap(reader1 -> reader1.getString()); + } else if ("tags".equals(fieldName)) { + tags = reader.readMap(reader1 -> reader1.getString()); + } else if ("jobId".equals(fieldName)) { + jobId = reader.getString(); + } else if ("channelReference".equals(fieldName)) { + channelReference = reader.getString(); + } else if ("channelId".equals(fieldName)) { + channelId = reader.getString(); + } else if ("queueId".equals(fieldName)) { + queueId = reader.getString(); + } else if ("expiredAttachedWorkerSelectors".equals(fieldName)) { + expiredAttachedWorkerSelectors + = reader.readArray(reader1 -> AcsRouterWorkerSelector.fromJson(reader1)); + } else if ("expiredRequestedWorkerSelectors".equals(fieldName)) { + expiredRequestedWorkerSelectors + = reader.readArray(reader1 -> AcsRouterWorkerSelector.fromJson(reader1)); + } else if ("scheduledOn".equals(fieldName)) { + scheduledOn = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("priority".equals(fieldName)) { + priority = reader.getNullable(JsonReader::getInt); + } else if ("failureReason".equals(fieldName)) { + failureReason = reader.getString(); + } else { + reader.skipChildren(); + } + } + AcsRouterJobSchedulingFailedEventData deserializedAcsRouterJobSchedulingFailedEventData + = new AcsRouterJobSchedulingFailedEventData(labels, tags, expiredAttachedWorkerSelectors, + expiredRequestedWorkerSelectors, scheduledOn); + deserializedAcsRouterJobSchedulingFailedEventData.jobId = jobId; + deserializedAcsRouterJobSchedulingFailedEventData.channelReference = channelReference; + deserializedAcsRouterJobSchedulingFailedEventData.channelId = channelId; + deserializedAcsRouterJobSchedulingFailedEventData.queueId = queueId; + deserializedAcsRouterJobSchedulingFailedEventData.priority = priority; + deserializedAcsRouterJobSchedulingFailedEventData.failureReason = failureReason; + + return deserializedAcsRouterJobSchedulingFailedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobStatus.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobStatus.java new file mode 100644 index 000000000000..2aff99f09048 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobStatus.java @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Acs Router Job Status. + */ +public final class AcsRouterJobStatus extends ExpandableStringEnum { + /** + * Router Job Status Pending Classification. + */ + @Generated + public static final AcsRouterJobStatus PENDING_CLASSIFICATION = fromString("PendingClassification"); + + /** + * Router Job Status Queued. + */ + @Generated + public static final AcsRouterJobStatus QUEUED = fromString("Queued"); + + /** + * Router Job Status Assigned. + */ + @Generated + public static final AcsRouterJobStatus ASSIGNED = fromString("Assigned"); + + /** + * Router Job Status Completed. + */ + @Generated + public static final AcsRouterJobStatus COMPLETED = fromString("Completed"); + + /** + * Router Job Status Closed. + */ + @Generated + public static final AcsRouterJobStatus CLOSED = fromString("Closed"); + + /** + * Router Job Status Cancelled. + */ + @Generated + public static final AcsRouterJobStatus CANCELLED = fromString("Cancelled"); + + /** + * Router Job Status Classification Failed. + */ + @Generated + public static final AcsRouterJobStatus CLASSIFICATION_FAILED = fromString("ClassificationFailed"); + + /** + * Router Job Status Created. + */ + @Generated + public static final AcsRouterJobStatus CREATED = fromString("Created"); + + /** + * Router Job Status Pending Schedule. + */ + @Generated + public static final AcsRouterJobStatus PENDING_SCHEDULE = fromString("PendingSchedule"); + + /** + * Router Job Status Scheduled. + */ + @Generated + public static final AcsRouterJobStatus SCHEDULED = fromString("Scheduled"); + + /** + * Router Job Status Schedule Failed. + */ + @Generated + public static final AcsRouterJobStatus SCHEDULE_FAILED = fromString("ScheduleFailed"); + + /** + * Router Job Status Waiting For Activation. + */ + @Generated + public static final AcsRouterJobStatus WAITING_FOR_ACTIVATION = fromString("WaitingForActivation"); + + /** + * Creates a new instance of AcsRouterJobStatus value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public AcsRouterJobStatus() { + } + + /** + * Creates or finds a AcsRouterJobStatus from its string representation. + * + * @param name a name to look for. + * @return the corresponding AcsRouterJobStatus. + */ + @Generated + public static AcsRouterJobStatus fromString(String name) { + return fromString(name, AcsRouterJobStatus.class); + } + + /** + * Gets known AcsRouterJobStatus values. + * + * @return known AcsRouterJobStatus values. + */ + @Generated + public static Collection values() { + return values(AcsRouterJobStatus.class); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobUnassignedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobUnassignedEventData.java new file mode 100644 index 000000000000..9d79c3e54014 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobUnassignedEventData.java @@ -0,0 +1,205 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobUnassigned event. + */ +@Immutable +public final class AcsRouterJobUnassignedEventData extends AcsRouterJobEventData { + /* + * Router Job Unassigned Assignment Id + */ + @Generated + private String assignmentId; + + /* + * Router Job Unassigned Worker Id + */ + @Generated + private String workerId; + + /* + * Router Job events Queue Id + */ + @Generated + private String queueId; + + /* + * Router Event Channel ID + */ + @Generated + private String channelId; + + /* + * Router Event Channel Reference + */ + @Generated + private String channelReference; + + /* + * Router Event Job ID + */ + @Generated + private String jobId; + + /** + * Creates an instance of AcsRouterJobUnassignedEventData class. + * + * @param labels the labels value to set. + * @param tags the tags value to set. + */ + @Generated + private AcsRouterJobUnassignedEventData(Map labels, Map tags) { + super(labels, tags); + } + + /** + * Get the assignmentId property: Router Job Unassigned Assignment Id. + * + * @return the assignmentId value. + */ + @Generated + public String getAssignmentId() { + return this.assignmentId; + } + + /** + * Get the workerId property: Router Job Unassigned Worker Id. + * + * @return the workerId value. + */ + @Generated + public String getWorkerId() { + return this.workerId; + } + + /** + * Get the queueId property: Router Job events Queue Id. + * + * @return the queueId value. + */ + @Generated + @Override + public String getQueueId() { + return this.queueId; + } + + /** + * Get the channelId property: Router Event Channel ID. + * + * @return the channelId value. + */ + @Generated + @Override + public String getChannelId() { + return this.channelId; + } + + /** + * Get the channelReference property: Router Event Channel Reference. + * + * @return the channelReference value. + */ + @Generated + @Override + public String getChannelReference() { + return this.channelReference; + } + + /** + * Get the jobId property: Router Event Job ID. + * + * @return the jobId value. + */ + @Generated + @Override + public String getJobId() { + return this.jobId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("labels", getLabels(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeMapField("tags", getTags(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("jobId", getJobId()); + jsonWriter.writeStringField("channelReference", getChannelReference()); + jsonWriter.writeStringField("channelId", getChannelId()); + jsonWriter.writeStringField("queueId", getQueueId()); + jsonWriter.writeStringField("assignmentId", this.assignmentId); + jsonWriter.writeStringField("workerId", this.workerId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRouterJobUnassignedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRouterJobUnassignedEventData 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 AcsRouterJobUnassignedEventData. + */ + @Generated + public static AcsRouterJobUnassignedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Map labels = null; + Map tags = null; + String jobId = null; + String channelReference = null; + String channelId = null; + String queueId = null; + String assignmentId = null; + String workerId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("labels".equals(fieldName)) { + labels = reader.readMap(reader1 -> reader1.getString()); + } else if ("tags".equals(fieldName)) { + tags = reader.readMap(reader1 -> reader1.getString()); + } else if ("jobId".equals(fieldName)) { + jobId = reader.getString(); + } else if ("channelReference".equals(fieldName)) { + channelReference = reader.getString(); + } else if ("channelId".equals(fieldName)) { + channelId = reader.getString(); + } else if ("queueId".equals(fieldName)) { + queueId = reader.getString(); + } else if ("assignmentId".equals(fieldName)) { + assignmentId = reader.getString(); + } else if ("workerId".equals(fieldName)) { + workerId = reader.getString(); + } else { + reader.skipChildren(); + } + } + AcsRouterJobUnassignedEventData deserializedAcsRouterJobUnassignedEventData + = new AcsRouterJobUnassignedEventData(labels, tags); + deserializedAcsRouterJobUnassignedEventData.jobId = jobId; + deserializedAcsRouterJobUnassignedEventData.channelReference = channelReference; + deserializedAcsRouterJobUnassignedEventData.channelId = channelId; + deserializedAcsRouterJobUnassignedEventData.queueId = queueId; + deserializedAcsRouterJobUnassignedEventData.assignmentId = assignmentId; + deserializedAcsRouterJobUnassignedEventData.workerId = workerId; + + return deserializedAcsRouterJobUnassignedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobWaitingForActivationEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobWaitingForActivationEventData.java new file mode 100644 index 000000000000..2d165a4a7690 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobWaitingForActivationEventData.java @@ -0,0 +1,287 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.List; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobWaitingForActivation event. + */ +@Immutable +public final class AcsRouterJobWaitingForActivationEventData extends AcsRouterJobEventData { + /* + * Router Job Waiting For Activation Priority + */ + @Generated + private Integer priority; + + /* + * Router Job Waiting For Activation Worker Selector Expired + */ + @Generated + private final List expiredAttachedWorkerSelectors; + + /* + * Router Job Waiting For Activation Requested Worker Selector Expired + */ + @Generated + private final List expiredRequestedWorkerSelectors; + + /* + * Router Job Waiting For Activation Scheduled Time in UTC + */ + @Generated + private final OffsetDateTime scheduledOn; + + /* + * Router Job Waiting For Activation Unavailable For Matching + */ + @Generated + private final boolean unavailableForMatching; + + /* + * Router Job events Queue Id + */ + @Generated + private String queueId; + + /* + * Router Event Channel ID + */ + @Generated + private String channelId; + + /* + * Router Event Channel Reference + */ + @Generated + private String channelReference; + + /* + * Router Event Job ID + */ + @Generated + private String jobId; + + /** + * Creates an instance of AcsRouterJobWaitingForActivationEventData class. + * + * @param labels the labels value to set. + * @param tags the tags value to set. + * @param expiredAttachedWorkerSelectors the expiredAttachedWorkerSelectors value to set. + * @param expiredRequestedWorkerSelectors the expiredRequestedWorkerSelectors value to set. + * @param scheduledOn the scheduledOn value to set. + * @param unavailableForMatching the unavailableForMatching value to set. + */ + @Generated + private AcsRouterJobWaitingForActivationEventData(Map labels, Map tags, + List expiredAttachedWorkerSelectors, + List expiredRequestedWorkerSelectors, OffsetDateTime scheduledOn, + boolean unavailableForMatching) { + super(labels, tags); + this.expiredAttachedWorkerSelectors = expiredAttachedWorkerSelectors; + this.expiredRequestedWorkerSelectors = expiredRequestedWorkerSelectors; + this.scheduledOn = scheduledOn; + this.unavailableForMatching = unavailableForMatching; + } + + /** + * Get the priority property: Router Job Waiting For Activation Priority. + * + * @return the priority value. + */ + @Generated + public Integer getPriority() { + return this.priority; + } + + /** + * Get the expiredAttachedWorkerSelectors property: Router Job Waiting For Activation Worker Selector Expired. + * + * @return the expiredAttachedWorkerSelectors value. + */ + @Generated + public List getExpiredAttachedWorkerSelectors() { + return this.expiredAttachedWorkerSelectors; + } + + /** + * Get the expiredRequestedWorkerSelectors property: Router Job Waiting For Activation Requested Worker Selector + * Expired. + * + * @return the expiredRequestedWorkerSelectors value. + */ + @Generated + public List getExpiredRequestedWorkerSelectors() { + return this.expiredRequestedWorkerSelectors; + } + + /** + * Get the scheduledOn property: Router Job Waiting For Activation Scheduled Time in UTC. + * + * @return the scheduledOn value. + */ + @Generated + public OffsetDateTime getScheduledOn() { + return this.scheduledOn; + } + + /** + * Get the unavailableForMatching property: Router Job Waiting For Activation Unavailable For Matching. + * + * @return the unavailableForMatching value. + */ + @Generated + public boolean isUnavailableForMatching() { + return this.unavailableForMatching; + } + + /** + * Get the queueId property: Router Job events Queue Id. + * + * @return the queueId value. + */ + @Generated + @Override + public String getQueueId() { + return this.queueId; + } + + /** + * Get the channelId property: Router Event Channel ID. + * + * @return the channelId value. + */ + @Generated + @Override + public String getChannelId() { + return this.channelId; + } + + /** + * Get the channelReference property: Router Event Channel Reference. + * + * @return the channelReference value. + */ + @Generated + @Override + public String getChannelReference() { + return this.channelReference; + } + + /** + * Get the jobId property: Router Event Job ID. + * + * @return the jobId value. + */ + @Generated + @Override + public String getJobId() { + return this.jobId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("labels", getLabels(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeMapField("tags", getTags(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("jobId", getJobId()); + jsonWriter.writeStringField("channelReference", getChannelReference()); + jsonWriter.writeStringField("channelId", getChannelId()); + jsonWriter.writeStringField("queueId", getQueueId()); + jsonWriter.writeArrayField("expiredAttachedWorkerSelectors", this.expiredAttachedWorkerSelectors, + (writer, element) -> writer.writeJson(element)); + jsonWriter.writeArrayField("expiredRequestedWorkerSelectors", this.expiredRequestedWorkerSelectors, + (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("scheduledOn", + this.scheduledOn == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.scheduledOn)); + jsonWriter.writeBooleanField("unavailableForMatching", this.unavailableForMatching); + jsonWriter.writeNumberField("priority", this.priority); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRouterJobWaitingForActivationEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRouterJobWaitingForActivationEventData 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 AcsRouterJobWaitingForActivationEventData. + */ + @Generated + public static AcsRouterJobWaitingForActivationEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Map labels = null; + Map tags = null; + String jobId = null; + String channelReference = null; + String channelId = null; + String queueId = null; + List expiredAttachedWorkerSelectors = null; + List expiredRequestedWorkerSelectors = null; + OffsetDateTime scheduledOn = null; + boolean unavailableForMatching = false; + Integer priority = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("labels".equals(fieldName)) { + labels = reader.readMap(reader1 -> reader1.getString()); + } else if ("tags".equals(fieldName)) { + tags = reader.readMap(reader1 -> reader1.getString()); + } else if ("jobId".equals(fieldName)) { + jobId = reader.getString(); + } else if ("channelReference".equals(fieldName)) { + channelReference = reader.getString(); + } else if ("channelId".equals(fieldName)) { + channelId = reader.getString(); + } else if ("queueId".equals(fieldName)) { + queueId = reader.getString(); + } else if ("expiredAttachedWorkerSelectors".equals(fieldName)) { + expiredAttachedWorkerSelectors + = reader.readArray(reader1 -> AcsRouterWorkerSelector.fromJson(reader1)); + } else if ("expiredRequestedWorkerSelectors".equals(fieldName)) { + expiredRequestedWorkerSelectors + = reader.readArray(reader1 -> AcsRouterWorkerSelector.fromJson(reader1)); + } else if ("scheduledOn".equals(fieldName)) { + scheduledOn = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("unavailableForMatching".equals(fieldName)) { + unavailableForMatching = reader.getBoolean(); + } else if ("priority".equals(fieldName)) { + priority = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + AcsRouterJobWaitingForActivationEventData deserializedAcsRouterJobWaitingForActivationEventData + = new AcsRouterJobWaitingForActivationEventData(labels, tags, expiredAttachedWorkerSelectors, + expiredRequestedWorkerSelectors, scheduledOn, unavailableForMatching); + deserializedAcsRouterJobWaitingForActivationEventData.jobId = jobId; + deserializedAcsRouterJobWaitingForActivationEventData.channelReference = channelReference; + deserializedAcsRouterJobWaitingForActivationEventData.channelId = channelId; + deserializedAcsRouterJobWaitingForActivationEventData.queueId = queueId; + deserializedAcsRouterJobWaitingForActivationEventData.priority = priority; + + return deserializedAcsRouterJobWaitingForActivationEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobWorkerSelectorsExpiredEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobWorkerSelectorsExpiredEventData.java new file mode 100644 index 000000000000..1973c2ea88fe --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterJobWorkerSelectorsExpiredEventData.java @@ -0,0 +1,215 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.List; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterJobWorkerSelectorsExpired event. + */ +@Immutable +public final class AcsRouterJobWorkerSelectorsExpiredEventData extends AcsRouterJobEventData { + /* + * Router Job Worker Selectors Expired Requested Worker Selectors + */ + @Generated + private final List expiredRequestedWorkerSelectors; + + /* + * Router Job Worker Selectors Expired Attached Worker Selectors + */ + @Generated + private final List expiredAttachedWorkerSelectors; + + /* + * Router Job events Queue Id + */ + @Generated + private String queueId; + + /* + * Router Event Channel ID + */ + @Generated + private String channelId; + + /* + * Router Event Channel Reference + */ + @Generated + private String channelReference; + + /* + * Router Event Job ID + */ + @Generated + private String jobId; + + /** + * Creates an instance of AcsRouterJobWorkerSelectorsExpiredEventData class. + * + * @param labels the labels value to set. + * @param tags the tags value to set. + * @param expiredRequestedWorkerSelectors the expiredRequestedWorkerSelectors value to set. + * @param expiredAttachedWorkerSelectors the expiredAttachedWorkerSelectors value to set. + */ + @Generated + private AcsRouterJobWorkerSelectorsExpiredEventData(Map labels, Map tags, + List expiredRequestedWorkerSelectors, + List expiredAttachedWorkerSelectors) { + super(labels, tags); + this.expiredRequestedWorkerSelectors = expiredRequestedWorkerSelectors; + this.expiredAttachedWorkerSelectors = expiredAttachedWorkerSelectors; + } + + /** + * Get the expiredRequestedWorkerSelectors property: Router Job Worker Selectors Expired Requested Worker Selectors. + * + * @return the expiredRequestedWorkerSelectors value. + */ + @Generated + public List getExpiredRequestedWorkerSelectors() { + return this.expiredRequestedWorkerSelectors; + } + + /** + * Get the expiredAttachedWorkerSelectors property: Router Job Worker Selectors Expired Attached Worker Selectors. + * + * @return the expiredAttachedWorkerSelectors value. + */ + @Generated + public List getExpiredAttachedWorkerSelectors() { + return this.expiredAttachedWorkerSelectors; + } + + /** + * Get the queueId property: Router Job events Queue Id. + * + * @return the queueId value. + */ + @Generated + @Override + public String getQueueId() { + return this.queueId; + } + + /** + * Get the channelId property: Router Event Channel ID. + * + * @return the channelId value. + */ + @Generated + @Override + public String getChannelId() { + return this.channelId; + } + + /** + * Get the channelReference property: Router Event Channel Reference. + * + * @return the channelReference value. + */ + @Generated + @Override + public String getChannelReference() { + return this.channelReference; + } + + /** + * Get the jobId property: Router Event Job ID. + * + * @return the jobId value. + */ + @Generated + @Override + public String getJobId() { + return this.jobId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("labels", getLabels(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeMapField("tags", getTags(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("jobId", getJobId()); + jsonWriter.writeStringField("channelReference", getChannelReference()); + jsonWriter.writeStringField("channelId", getChannelId()); + jsonWriter.writeStringField("queueId", getQueueId()); + jsonWriter.writeArrayField("expiredRequestedWorkerSelectors", this.expiredRequestedWorkerSelectors, + (writer, element) -> writer.writeJson(element)); + jsonWriter.writeArrayField("expiredAttachedWorkerSelectors", this.expiredAttachedWorkerSelectors, + (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRouterJobWorkerSelectorsExpiredEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRouterJobWorkerSelectorsExpiredEventData 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 AcsRouterJobWorkerSelectorsExpiredEventData. + */ + @Generated + public static AcsRouterJobWorkerSelectorsExpiredEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Map labels = null; + Map tags = null; + String jobId = null; + String channelReference = null; + String channelId = null; + String queueId = null; + List expiredRequestedWorkerSelectors = null; + List expiredAttachedWorkerSelectors = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("labels".equals(fieldName)) { + labels = reader.readMap(reader1 -> reader1.getString()); + } else if ("tags".equals(fieldName)) { + tags = reader.readMap(reader1 -> reader1.getString()); + } else if ("jobId".equals(fieldName)) { + jobId = reader.getString(); + } else if ("channelReference".equals(fieldName)) { + channelReference = reader.getString(); + } else if ("channelId".equals(fieldName)) { + channelId = reader.getString(); + } else if ("queueId".equals(fieldName)) { + queueId = reader.getString(); + } else if ("expiredRequestedWorkerSelectors".equals(fieldName)) { + expiredRequestedWorkerSelectors + = reader.readArray(reader1 -> AcsRouterWorkerSelector.fromJson(reader1)); + } else if ("expiredAttachedWorkerSelectors".equals(fieldName)) { + expiredAttachedWorkerSelectors + = reader.readArray(reader1 -> AcsRouterWorkerSelector.fromJson(reader1)); + } else { + reader.skipChildren(); + } + } + AcsRouterJobWorkerSelectorsExpiredEventData deserializedAcsRouterJobWorkerSelectorsExpiredEventData + = new AcsRouterJobWorkerSelectorsExpiredEventData(labels, tags, expiredRequestedWorkerSelectors, + expiredAttachedWorkerSelectors); + deserializedAcsRouterJobWorkerSelectorsExpiredEventData.jobId = jobId; + deserializedAcsRouterJobWorkerSelectorsExpiredEventData.channelReference = channelReference; + deserializedAcsRouterJobWorkerSelectorsExpiredEventData.channelId = channelId; + deserializedAcsRouterJobWorkerSelectorsExpiredEventData.queueId = queueId; + + return deserializedAcsRouterJobWorkerSelectorsExpiredEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterLabelOperator.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterLabelOperator.java new file mode 100644 index 000000000000..26ff699948a8 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterLabelOperator.java @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Router Job Worker Selector Label Operator. + */ +public final class AcsRouterLabelOperator extends ExpandableStringEnum { + /** + * Router Label Operator Equal. + */ + @Generated + public static final AcsRouterLabelOperator EQUAL = fromString("Equal"); + + /** + * Router Label Operator Not Equal. + */ + @Generated + public static final AcsRouterLabelOperator NOT_EQUAL = fromString("NotEqual"); + + /** + * Router Label Operator Greater. + */ + @Generated + public static final AcsRouterLabelOperator GREATER = fromString("Greater"); + + /** + * Router Label Operator Less. + */ + @Generated + public static final AcsRouterLabelOperator LESS = fromString("Less"); + + /** + * Router Label Operator Greater than or equal. + */ + @Generated + public static final AcsRouterLabelOperator GREATER_THAN_OR_EQUAL = fromString("GreaterThanOrEqual"); + + /** + * Router Label Operator Less than or equal. + */ + @Generated + public static final AcsRouterLabelOperator LESS_THAN_OR_EQUAL = fromString("LessThanOrEqual"); + + /** + * Creates a new instance of AcsRouterLabelOperator value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public AcsRouterLabelOperator() { + } + + /** + * Creates or finds a AcsRouterLabelOperator from its string representation. + * + * @param name a name to look for. + * @return the corresponding AcsRouterLabelOperator. + */ + @Generated + public static AcsRouterLabelOperator fromString(String name) { + return fromString(name, AcsRouterLabelOperator.class); + } + + /** + * Gets known AcsRouterLabelOperator values. + * + * @return known AcsRouterLabelOperator values. + */ + @Generated + public static Collection values() { + return values(AcsRouterLabelOperator.class); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterQueueDetails.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterQueueDetails.java new file mode 100644 index 000000000000..50c0fb86a3ca --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterQueueDetails.java @@ -0,0 +1,128 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.Map; + +/** + * Router Queue Details. + */ +@Immutable +public final class AcsRouterQueueDetails implements JsonSerializable { + /* + * Router Queue Id + */ + @Generated + private String id; + + /* + * Router Queue Name + */ + @Generated + private String name; + + /* + * Router Queue Labels + */ + @Generated + private final Map labels; + + /** + * Creates an instance of AcsRouterQueueDetails class. + * + * @param labels the labels value to set. + */ + @Generated + private AcsRouterQueueDetails(Map labels) { + this.labels = labels; + } + + /** + * Get the id property: Router Queue Id. + * + * @return the id value. + */ + @Generated + public String getId() { + return this.id; + } + + /** + * Get the name property: Router Queue Name. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the labels property: Router Queue Labels. + * + * @return the labels value. + */ + @Generated + public Map getLabels() { + return this.labels; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("labels", this.labels, (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("id", this.id); + jsonWriter.writeStringField("name", this.name); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRouterQueueDetails from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRouterQueueDetails 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 AcsRouterQueueDetails. + */ + @Generated + public static AcsRouterQueueDetails fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Map labels = null; + String id = null; + String name = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("labels".equals(fieldName)) { + labels = reader.readMap(reader1 -> reader1.getString()); + } else if ("id".equals(fieldName)) { + id = reader.getString(); + } else if ("name".equals(fieldName)) { + name = reader.getString(); + } else { + reader.skipChildren(); + } + } + AcsRouterQueueDetails deserializedAcsRouterQueueDetails = new AcsRouterQueueDetails(labels); + deserializedAcsRouterQueueDetails.id = id; + deserializedAcsRouterQueueDetails.name = name; + + return deserializedAcsRouterQueueDetails; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterUpdatedWorkerProperty.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterUpdatedWorkerProperty.java new file mode 100644 index 000000000000..e3e6d0808be5 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterUpdatedWorkerProperty.java @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Worker properties that can be updated. + */ +public final class AcsRouterUpdatedWorkerProperty extends ExpandableStringEnum { + /** + * AvailableForOffers. + */ + @Generated + public static final AcsRouterUpdatedWorkerProperty AVAILABLE_FOR_OFFERS = fromString("AvailableForOffers"); + + /** + * TotalCapacity. + */ + @Generated + public static final AcsRouterUpdatedWorkerProperty TOTAL_CAPACITY = fromString("TotalCapacity"); + + /** + * QueueAssignments. + */ + @Generated + public static final AcsRouterUpdatedWorkerProperty QUEUE_ASSIGNMENTS = fromString("QueueAssignments"); + + /** + * Labels. + */ + @Generated + public static final AcsRouterUpdatedWorkerProperty LABELS = fromString("Labels"); + + /** + * Tags. + */ + @Generated + public static final AcsRouterUpdatedWorkerProperty TAGS = fromString("Tags"); + + /** + * ChannelConfigurations. + */ + @Generated + public static final AcsRouterUpdatedWorkerProperty CHANNEL_CONFIGURATIONS = fromString("ChannelConfigurations"); + + /** + * Creates a new instance of AcsRouterUpdatedWorkerProperty value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public AcsRouterUpdatedWorkerProperty() { + } + + /** + * Creates or finds a AcsRouterUpdatedWorkerProperty from its string representation. + * + * @param name a name to look for. + * @return the corresponding AcsRouterUpdatedWorkerProperty. + */ + @Generated + public static AcsRouterUpdatedWorkerProperty fromString(String name) { + return fromString(name, AcsRouterUpdatedWorkerProperty.class); + } + + /** + * Gets known AcsRouterUpdatedWorkerProperty values. + * + * @return known AcsRouterUpdatedWorkerProperty values. + */ + @Generated + public static Collection values() { + return values(AcsRouterUpdatedWorkerProperty.class); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerDeletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerDeletedEventData.java new file mode 100644 index 000000000000..0bac3df6830c --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerDeletedEventData.java @@ -0,0 +1,141 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterWorkerDeleted event. + */ +@Immutable +public final class AcsRouterWorkerDeletedEventData extends AcsRouterWorkerEventData { + /* + * Router Worker events Worker Id + */ + @Generated + private String workerId; + + /* + * Router Event Channel ID + */ + @Generated + private String channelId; + + /* + * Router Event Channel Reference + */ + @Generated + private String channelReference; + + /* + * Router Event Job ID + */ + @Generated + private String jobId; + + /** + * Creates an instance of AcsRouterWorkerDeletedEventData class. + */ + @Generated + private AcsRouterWorkerDeletedEventData() { + } + + /** + * Get the workerId property: Router Worker events Worker Id. + * + * @return the workerId value. + */ + @Generated + @Override + public String getWorkerId() { + return this.workerId; + } + + /** + * Get the channelId property: Router Event Channel ID. + * + * @return the channelId value. + */ + @Generated + @Override + public String getChannelId() { + return this.channelId; + } + + /** + * Get the channelReference property: Router Event Channel Reference. + * + * @return the channelReference value. + */ + @Generated + @Override + public String getChannelReference() { + return this.channelReference; + } + + /** + * Get the jobId property: Router Event Job ID. + * + * @return the jobId value. + */ + @Generated + @Override + public String getJobId() { + return this.jobId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("jobId", getJobId()); + jsonWriter.writeStringField("channelReference", getChannelReference()); + jsonWriter.writeStringField("channelId", getChannelId()); + jsonWriter.writeStringField("workerId", getWorkerId()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRouterWorkerDeletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRouterWorkerDeletedEventData 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 AcsRouterWorkerDeletedEventData. + */ + @Generated + public static AcsRouterWorkerDeletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AcsRouterWorkerDeletedEventData deserializedAcsRouterWorkerDeletedEventData + = new AcsRouterWorkerDeletedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("jobId".equals(fieldName)) { + deserializedAcsRouterWorkerDeletedEventData.jobId = reader.getString(); + } else if ("channelReference".equals(fieldName)) { + deserializedAcsRouterWorkerDeletedEventData.channelReference = reader.getString(); + } else if ("channelId".equals(fieldName)) { + deserializedAcsRouterWorkerDeletedEventData.channelId = reader.getString(); + } else if ("workerId".equals(fieldName)) { + deserializedAcsRouterWorkerDeletedEventData.workerId = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAcsRouterWorkerDeletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerDeregisteredEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerDeregisteredEventData.java new file mode 100644 index 000000000000..17647e22f39f --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerDeregisteredEventData.java @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterWorkerDeregistered event. + */ +@Immutable +public final class AcsRouterWorkerDeregisteredEventData + implements JsonSerializable { + /* + * Router Worker Deregistered Worker Id + */ + @Generated + private String workerId; + + /** + * Creates an instance of AcsRouterWorkerDeregisteredEventData class. + */ + @Generated + private AcsRouterWorkerDeregisteredEventData() { + } + + /** + * Get the workerId property: Router Worker Deregistered Worker Id. + * + * @return the workerId value. + */ + @Generated + public String getWorkerId() { + return this.workerId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("workerId", this.workerId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRouterWorkerDeregisteredEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRouterWorkerDeregisteredEventData 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 AcsRouterWorkerDeregisteredEventData. + */ + @Generated + public static AcsRouterWorkerDeregisteredEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AcsRouterWorkerDeregisteredEventData deserializedAcsRouterWorkerDeregisteredEventData + = new AcsRouterWorkerDeregisteredEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("workerId".equals(fieldName)) { + deserializedAcsRouterWorkerDeregisteredEventData.workerId = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAcsRouterWorkerDeregisteredEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerEventData.java new file mode 100644 index 000000000000..519053ac7454 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerEventData.java @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of common properties of all Router Worker events. + */ +@Immutable +public class AcsRouterWorkerEventData extends AcsRouterEventData { + /* + * Router Worker events Worker Id + */ + @Generated + private String workerId; + + /* + * Router Event Channel ID + */ + @Generated + private String channelId; + + /* + * Router Event Channel Reference + */ + @Generated + private String channelReference; + + /* + * Router Event Job ID + */ + @Generated + private String jobId; + + /** + * Creates an instance of AcsRouterWorkerEventData class. + */ + @Generated + protected AcsRouterWorkerEventData() { + } + + /** + * Get the workerId property: Router Worker events Worker Id. + * + * @return the workerId value. + */ + @Generated + public String getWorkerId() { + return this.workerId; + } + + /** + * Set the workerId property: Router Worker events Worker Id. + * + * @param workerId the workerId value to set. + * @return the AcsRouterWorkerEventData object itself. + */ + @Generated + AcsRouterWorkerEventData setWorkerId(String workerId) { + this.workerId = workerId; + return this; + } + + /** + * Get the channelId property: Router Event Channel ID. + * + * @return the channelId value. + */ + @Generated + @Override + public String getChannelId() { + return this.channelId; + } + + /** + * Get the channelReference property: Router Event Channel Reference. + * + * @return the channelReference value. + */ + @Generated + @Override + public String getChannelReference() { + return this.channelReference; + } + + /** + * Get the jobId property: Router Event Job ID. + * + * @return the jobId value. + */ + @Generated + @Override + public String getJobId() { + return this.jobId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("jobId", getJobId()); + jsonWriter.writeStringField("channelReference", getChannelReference()); + jsonWriter.writeStringField("channelId", getChannelId()); + jsonWriter.writeStringField("workerId", this.workerId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRouterWorkerEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRouterWorkerEventData 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 AcsRouterWorkerEventData. + */ + @Generated + public static AcsRouterWorkerEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AcsRouterWorkerEventData deserializedAcsRouterWorkerEventData = new AcsRouterWorkerEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("jobId".equals(fieldName)) { + deserializedAcsRouterWorkerEventData.jobId = reader.getString(); + } else if ("channelReference".equals(fieldName)) { + deserializedAcsRouterWorkerEventData.channelReference = reader.getString(); + } else if ("channelId".equals(fieldName)) { + deserializedAcsRouterWorkerEventData.channelId = reader.getString(); + } else if ("workerId".equals(fieldName)) { + deserializedAcsRouterWorkerEventData.workerId = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAcsRouterWorkerEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerOfferAcceptedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerOfferAcceptedEventData.java new file mode 100644 index 000000000000..88a497a1f560 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerOfferAcceptedEventData.java @@ -0,0 +1,325 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterWorkerOfferAccepted event. + */ +@Immutable +public final class AcsRouterWorkerOfferAcceptedEventData extends AcsRouterWorkerEventData { + /* + * Router Worker Offer Accepted Queue Id + */ + @Generated + private String queueId; + + /* + * Router Worker Offer Accepted Offer Id + */ + @Generated + private String offerId; + + /* + * Router Worker Offer Accepted Assignment Id + */ + @Generated + private String assignmentId; + + /* + * Router Worker Offer Accepted Job Priority + */ + @Generated + private Integer jobPriority; + + /* + * Router Worker Offer Accepted Worker Labels + */ + @Generated + private final Map workerLabels; + + /* + * Router Worker Offer Accepted Worker Tags + */ + @Generated + private final Map workerTags; + + /* + * Router Worker Offer Accepted Job Labels + */ + @Generated + private final Map jobLabels; + + /* + * Router Worker Offer Accepted Job Tags + */ + @Generated + private final Map jobTags; + + /* + * Router Worker events Worker Id + */ + @Generated + private String workerId; + + /* + * Router Event Channel ID + */ + @Generated + private String channelId; + + /* + * Router Event Channel Reference + */ + @Generated + private String channelReference; + + /* + * Router Event Job ID + */ + @Generated + private String jobId; + + /** + * Creates an instance of AcsRouterWorkerOfferAcceptedEventData class. + * + * @param workerLabels the workerLabels value to set. + * @param workerTags the workerTags value to set. + * @param jobLabels the jobLabels value to set. + * @param jobTags the jobTags value to set. + */ + @Generated + private AcsRouterWorkerOfferAcceptedEventData(Map workerLabels, Map workerTags, + Map jobLabels, Map jobTags) { + this.workerLabels = workerLabels; + this.workerTags = workerTags; + this.jobLabels = jobLabels; + this.jobTags = jobTags; + } + + /** + * Get the queueId property: Router Worker Offer Accepted Queue Id. + * + * @return the queueId value. + */ + @Generated + public String getQueueId() { + return this.queueId; + } + + /** + * Get the offerId property: Router Worker Offer Accepted Offer Id. + * + * @return the offerId value. + */ + @Generated + public String getOfferId() { + return this.offerId; + } + + /** + * Get the assignmentId property: Router Worker Offer Accepted Assignment Id. + * + * @return the assignmentId value. + */ + @Generated + public String getAssignmentId() { + return this.assignmentId; + } + + /** + * Get the jobPriority property: Router Worker Offer Accepted Job Priority. + * + * @return the jobPriority value. + */ + @Generated + public Integer getJobPriority() { + return this.jobPriority; + } + + /** + * Get the workerLabels property: Router Worker Offer Accepted Worker Labels. + * + * @return the workerLabels value. + */ + @Generated + public Map getWorkerLabels() { + return this.workerLabels; + } + + /** + * Get the workerTags property: Router Worker Offer Accepted Worker Tags. + * + * @return the workerTags value. + */ + @Generated + public Map getWorkerTags() { + return this.workerTags; + } + + /** + * Get the jobLabels property: Router Worker Offer Accepted Job Labels. + * + * @return the jobLabels value. + */ + @Generated + public Map getJobLabels() { + return this.jobLabels; + } + + /** + * Get the jobTags property: Router Worker Offer Accepted Job Tags. + * + * @return the jobTags value. + */ + @Generated + public Map getJobTags() { + return this.jobTags; + } + + /** + * Get the workerId property: Router Worker events Worker Id. + * + * @return the workerId value. + */ + @Generated + @Override + public String getWorkerId() { + return this.workerId; + } + + /** + * Get the channelId property: Router Event Channel ID. + * + * @return the channelId value. + */ + @Generated + @Override + public String getChannelId() { + return this.channelId; + } + + /** + * Get the channelReference property: Router Event Channel Reference. + * + * @return the channelReference value. + */ + @Generated + @Override + public String getChannelReference() { + return this.channelReference; + } + + /** + * Get the jobId property: Router Event Job ID. + * + * @return the jobId value. + */ + @Generated + @Override + public String getJobId() { + return this.jobId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("jobId", getJobId()); + jsonWriter.writeStringField("channelReference", getChannelReference()); + jsonWriter.writeStringField("channelId", getChannelId()); + jsonWriter.writeStringField("workerId", getWorkerId()); + jsonWriter.writeMapField("workerLabels", this.workerLabels, (writer, element) -> writer.writeString(element)); + jsonWriter.writeMapField("workerTags", this.workerTags, (writer, element) -> writer.writeString(element)); + jsonWriter.writeMapField("jobLabels", this.jobLabels, (writer, element) -> writer.writeString(element)); + jsonWriter.writeMapField("jobTags", this.jobTags, (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("queueId", this.queueId); + jsonWriter.writeStringField("offerId", this.offerId); + jsonWriter.writeStringField("assignmentId", this.assignmentId); + jsonWriter.writeNumberField("jobPriority", this.jobPriority); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRouterWorkerOfferAcceptedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRouterWorkerOfferAcceptedEventData 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 AcsRouterWorkerOfferAcceptedEventData. + */ + @Generated + public static AcsRouterWorkerOfferAcceptedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String jobId = null; + String channelReference = null; + String channelId = null; + String workerId = null; + Map workerLabels = null; + Map workerTags = null; + Map jobLabels = null; + Map jobTags = null; + String queueId = null; + String offerId = null; + String assignmentId = null; + Integer jobPriority = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("jobId".equals(fieldName)) { + jobId = reader.getString(); + } else if ("channelReference".equals(fieldName)) { + channelReference = reader.getString(); + } else if ("channelId".equals(fieldName)) { + channelId = reader.getString(); + } else if ("workerId".equals(fieldName)) { + workerId = reader.getString(); + } else if ("workerLabels".equals(fieldName)) { + workerLabels = reader.readMap(reader1 -> reader1.getString()); + } else if ("workerTags".equals(fieldName)) { + workerTags = reader.readMap(reader1 -> reader1.getString()); + } else if ("jobLabels".equals(fieldName)) { + jobLabels = reader.readMap(reader1 -> reader1.getString()); + } else if ("jobTags".equals(fieldName)) { + jobTags = reader.readMap(reader1 -> reader1.getString()); + } else if ("queueId".equals(fieldName)) { + queueId = reader.getString(); + } else if ("offerId".equals(fieldName)) { + offerId = reader.getString(); + } else if ("assignmentId".equals(fieldName)) { + assignmentId = reader.getString(); + } else if ("jobPriority".equals(fieldName)) { + jobPriority = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + AcsRouterWorkerOfferAcceptedEventData deserializedAcsRouterWorkerOfferAcceptedEventData + = new AcsRouterWorkerOfferAcceptedEventData(workerLabels, workerTags, jobLabels, jobTags); + deserializedAcsRouterWorkerOfferAcceptedEventData.jobId = jobId; + deserializedAcsRouterWorkerOfferAcceptedEventData.channelReference = channelReference; + deserializedAcsRouterWorkerOfferAcceptedEventData.channelId = channelId; + deserializedAcsRouterWorkerOfferAcceptedEventData.workerId = workerId; + deserializedAcsRouterWorkerOfferAcceptedEventData.queueId = queueId; + deserializedAcsRouterWorkerOfferAcceptedEventData.offerId = offerId; + deserializedAcsRouterWorkerOfferAcceptedEventData.assignmentId = assignmentId; + deserializedAcsRouterWorkerOfferAcceptedEventData.jobPriority = jobPriority; + + return deserializedAcsRouterWorkerOfferAcceptedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerOfferDeclinedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerOfferDeclinedEventData.java new file mode 100644 index 000000000000..caf994ac9261 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerOfferDeclinedEventData.java @@ -0,0 +1,179 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterWorkerOfferDeclined event. + */ +@Immutable +public final class AcsRouterWorkerOfferDeclinedEventData extends AcsRouterWorkerEventData { + /* + * Router Worker Offer Declined Queue Id + */ + @Generated + private String queueId; + + /* + * Router Worker Offer Declined Offer Id + */ + @Generated + private String offerId; + + /* + * Router Worker events Worker Id + */ + @Generated + private String workerId; + + /* + * Router Event Channel ID + */ + @Generated + private String channelId; + + /* + * Router Event Channel Reference + */ + @Generated + private String channelReference; + + /* + * Router Event Job ID + */ + @Generated + private String jobId; + + /** + * Creates an instance of AcsRouterWorkerOfferDeclinedEventData class. + */ + @Generated + private AcsRouterWorkerOfferDeclinedEventData() { + } + + /** + * Get the queueId property: Router Worker Offer Declined Queue Id. + * + * @return the queueId value. + */ + @Generated + public String getQueueId() { + return this.queueId; + } + + /** + * Get the offerId property: Router Worker Offer Declined Offer Id. + * + * @return the offerId value. + */ + @Generated + public String getOfferId() { + return this.offerId; + } + + /** + * Get the workerId property: Router Worker events Worker Id. + * + * @return the workerId value. + */ + @Generated + @Override + public String getWorkerId() { + return this.workerId; + } + + /** + * Get the channelId property: Router Event Channel ID. + * + * @return the channelId value. + */ + @Generated + @Override + public String getChannelId() { + return this.channelId; + } + + /** + * Get the channelReference property: Router Event Channel Reference. + * + * @return the channelReference value. + */ + @Generated + @Override + public String getChannelReference() { + return this.channelReference; + } + + /** + * Get the jobId property: Router Event Job ID. + * + * @return the jobId value. + */ + @Generated + @Override + public String getJobId() { + return this.jobId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("jobId", getJobId()); + jsonWriter.writeStringField("channelReference", getChannelReference()); + jsonWriter.writeStringField("channelId", getChannelId()); + jsonWriter.writeStringField("workerId", getWorkerId()); + jsonWriter.writeStringField("queueId", this.queueId); + jsonWriter.writeStringField("offerId", this.offerId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRouterWorkerOfferDeclinedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRouterWorkerOfferDeclinedEventData 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 AcsRouterWorkerOfferDeclinedEventData. + */ + @Generated + public static AcsRouterWorkerOfferDeclinedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AcsRouterWorkerOfferDeclinedEventData deserializedAcsRouterWorkerOfferDeclinedEventData + = new AcsRouterWorkerOfferDeclinedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("jobId".equals(fieldName)) { + deserializedAcsRouterWorkerOfferDeclinedEventData.jobId = reader.getString(); + } else if ("channelReference".equals(fieldName)) { + deserializedAcsRouterWorkerOfferDeclinedEventData.channelReference = reader.getString(); + } else if ("channelId".equals(fieldName)) { + deserializedAcsRouterWorkerOfferDeclinedEventData.channelId = reader.getString(); + } else if ("workerId".equals(fieldName)) { + deserializedAcsRouterWorkerOfferDeclinedEventData.workerId = reader.getString(); + } else if ("queueId".equals(fieldName)) { + deserializedAcsRouterWorkerOfferDeclinedEventData.queueId = reader.getString(); + } else if ("offerId".equals(fieldName)) { + deserializedAcsRouterWorkerOfferDeclinedEventData.offerId = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAcsRouterWorkerOfferDeclinedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerOfferExpiredEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerOfferExpiredEventData.java new file mode 100644 index 000000000000..dd78d91c65db --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerOfferExpiredEventData.java @@ -0,0 +1,179 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterWorkerOfferExpired event. + */ +@Immutable +public final class AcsRouterWorkerOfferExpiredEventData extends AcsRouterWorkerEventData { + /* + * Router Worker Offer Expired Queue Id + */ + @Generated + private String queueId; + + /* + * Router Worker Offer Expired Offer Id + */ + @Generated + private String offerId; + + /* + * Router Worker events Worker Id + */ + @Generated + private String workerId; + + /* + * Router Event Channel ID + */ + @Generated + private String channelId; + + /* + * Router Event Channel Reference + */ + @Generated + private String channelReference; + + /* + * Router Event Job ID + */ + @Generated + private String jobId; + + /** + * Creates an instance of AcsRouterWorkerOfferExpiredEventData class. + */ + @Generated + private AcsRouterWorkerOfferExpiredEventData() { + } + + /** + * Get the queueId property: Router Worker Offer Expired Queue Id. + * + * @return the queueId value. + */ + @Generated + public String getQueueId() { + return this.queueId; + } + + /** + * Get the offerId property: Router Worker Offer Expired Offer Id. + * + * @return the offerId value. + */ + @Generated + public String getOfferId() { + return this.offerId; + } + + /** + * Get the workerId property: Router Worker events Worker Id. + * + * @return the workerId value. + */ + @Generated + @Override + public String getWorkerId() { + return this.workerId; + } + + /** + * Get the channelId property: Router Event Channel ID. + * + * @return the channelId value. + */ + @Generated + @Override + public String getChannelId() { + return this.channelId; + } + + /** + * Get the channelReference property: Router Event Channel Reference. + * + * @return the channelReference value. + */ + @Generated + @Override + public String getChannelReference() { + return this.channelReference; + } + + /** + * Get the jobId property: Router Event Job ID. + * + * @return the jobId value. + */ + @Generated + @Override + public String getJobId() { + return this.jobId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("jobId", getJobId()); + jsonWriter.writeStringField("channelReference", getChannelReference()); + jsonWriter.writeStringField("channelId", getChannelId()); + jsonWriter.writeStringField("workerId", getWorkerId()); + jsonWriter.writeStringField("queueId", this.queueId); + jsonWriter.writeStringField("offerId", this.offerId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRouterWorkerOfferExpiredEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRouterWorkerOfferExpiredEventData 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 AcsRouterWorkerOfferExpiredEventData. + */ + @Generated + public static AcsRouterWorkerOfferExpiredEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AcsRouterWorkerOfferExpiredEventData deserializedAcsRouterWorkerOfferExpiredEventData + = new AcsRouterWorkerOfferExpiredEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("jobId".equals(fieldName)) { + deserializedAcsRouterWorkerOfferExpiredEventData.jobId = reader.getString(); + } else if ("channelReference".equals(fieldName)) { + deserializedAcsRouterWorkerOfferExpiredEventData.channelReference = reader.getString(); + } else if ("channelId".equals(fieldName)) { + deserializedAcsRouterWorkerOfferExpiredEventData.channelId = reader.getString(); + } else if ("workerId".equals(fieldName)) { + deserializedAcsRouterWorkerOfferExpiredEventData.workerId = reader.getString(); + } else if ("queueId".equals(fieldName)) { + deserializedAcsRouterWorkerOfferExpiredEventData.queueId = reader.getString(); + } else if ("offerId".equals(fieldName)) { + deserializedAcsRouterWorkerOfferExpiredEventData.offerId = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAcsRouterWorkerOfferExpiredEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerOfferIssuedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerOfferIssuedEventData.java new file mode 100644 index 000000000000..c8d03d8c5774 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerOfferIssuedEventData.java @@ -0,0 +1,357 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterWorkerOfferIssued event. + */ +@Immutable +public final class AcsRouterWorkerOfferIssuedEventData extends AcsRouterWorkerEventData { + /* + * Router Worker Offer Issued Queue Id + */ + @Generated + private String queueId; + + /* + * Router Worker Offer Issued Offer Id + */ + @Generated + private String offerId; + + /* + * Router Worker Offer Issued Job Priority + */ + @Generated + private Integer jobPriority; + + /* + * Router Worker Offer Issued Worker Labels + */ + @Generated + private final Map workerLabels; + + /* + * Router Worker Offer Issued Time in UTC + */ + @Generated + private final OffsetDateTime offeredOn; + + /* + * Router Worker Offer Issued Expiration Time in UTC + */ + @Generated + private final OffsetDateTime expiresOn; + + /* + * Router Worker Offer Issued Worker Tags + */ + @Generated + private final Map workerTags; + + /* + * Router Worker Offer Issued Job Labels + */ + @Generated + private final Map jobLabels; + + /* + * Router Worker Offer Issued Job Tags + */ + @Generated + private final Map jobTags; + + /* + * Router Worker events Worker Id + */ + @Generated + private String workerId; + + /* + * Router Event Channel ID + */ + @Generated + private String channelId; + + /* + * Router Event Channel Reference + */ + @Generated + private String channelReference; + + /* + * Router Event Job ID + */ + @Generated + private String jobId; + + /** + * Creates an instance of AcsRouterWorkerOfferIssuedEventData class. + * + * @param workerLabels the workerLabels value to set. + * @param offeredOn the offeredOn value to set. + * @param expiresOn the expiresOn value to set. + * @param workerTags the workerTags value to set. + * @param jobLabels the jobLabels value to set. + * @param jobTags the jobTags value to set. + */ + @Generated + private AcsRouterWorkerOfferIssuedEventData(Map workerLabels, OffsetDateTime offeredOn, + OffsetDateTime expiresOn, Map workerTags, Map jobLabels, + Map jobTags) { + this.workerLabels = workerLabels; + this.offeredOn = offeredOn; + this.expiresOn = expiresOn; + this.workerTags = workerTags; + this.jobLabels = jobLabels; + this.jobTags = jobTags; + } + + /** + * Get the queueId property: Router Worker Offer Issued Queue Id. + * + * @return the queueId value. + */ + @Generated + public String getQueueId() { + return this.queueId; + } + + /** + * Get the offerId property: Router Worker Offer Issued Offer Id. + * + * @return the offerId value. + */ + @Generated + public String getOfferId() { + return this.offerId; + } + + /** + * Get the jobPriority property: Router Worker Offer Issued Job Priority. + * + * @return the jobPriority value. + */ + @Generated + public Integer getJobPriority() { + return this.jobPriority; + } + + /** + * Get the workerLabels property: Router Worker Offer Issued Worker Labels. + * + * @return the workerLabels value. + */ + @Generated + public Map getWorkerLabels() { + return this.workerLabels; + } + + /** + * Get the offeredOn property: Router Worker Offer Issued Time in UTC. + * + * @return the offeredOn value. + */ + @Generated + public OffsetDateTime getOfferedOn() { + return this.offeredOn; + } + + /** + * Get the expiresOn property: Router Worker Offer Issued Expiration Time in UTC. + * + * @return the expiresOn value. + */ + @Generated + public OffsetDateTime getExpiresOn() { + return this.expiresOn; + } + + /** + * Get the workerTags property: Router Worker Offer Issued Worker Tags. + * + * @return the workerTags value. + */ + @Generated + public Map getWorkerTags() { + return this.workerTags; + } + + /** + * Get the jobLabels property: Router Worker Offer Issued Job Labels. + * + * @return the jobLabels value. + */ + @Generated + public Map getJobLabels() { + return this.jobLabels; + } + + /** + * Get the jobTags property: Router Worker Offer Issued Job Tags. + * + * @return the jobTags value. + */ + @Generated + public Map getJobTags() { + return this.jobTags; + } + + /** + * Get the workerId property: Router Worker events Worker Id. + * + * @return the workerId value. + */ + @Generated + @Override + public String getWorkerId() { + return this.workerId; + } + + /** + * Get the channelId property: Router Event Channel ID. + * + * @return the channelId value. + */ + @Generated + @Override + public String getChannelId() { + return this.channelId; + } + + /** + * Get the channelReference property: Router Event Channel Reference. + * + * @return the channelReference value. + */ + @Generated + @Override + public String getChannelReference() { + return this.channelReference; + } + + /** + * Get the jobId property: Router Event Job ID. + * + * @return the jobId value. + */ + @Generated + @Override + public String getJobId() { + return this.jobId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("jobId", getJobId()); + jsonWriter.writeStringField("channelReference", getChannelReference()); + jsonWriter.writeStringField("channelId", getChannelId()); + jsonWriter.writeStringField("workerId", getWorkerId()); + jsonWriter.writeMapField("workerLabels", this.workerLabels, (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("offeredOn", + this.offeredOn == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.offeredOn)); + jsonWriter.writeStringField("expiresOn", + this.expiresOn == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.expiresOn)); + jsonWriter.writeMapField("workerTags", this.workerTags, (writer, element) -> writer.writeString(element)); + jsonWriter.writeMapField("jobLabels", this.jobLabels, (writer, element) -> writer.writeString(element)); + jsonWriter.writeMapField("jobTags", this.jobTags, (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("queueId", this.queueId); + jsonWriter.writeStringField("offerId", this.offerId); + jsonWriter.writeNumberField("jobPriority", this.jobPriority); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRouterWorkerOfferIssuedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRouterWorkerOfferIssuedEventData 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 AcsRouterWorkerOfferIssuedEventData. + */ + @Generated + public static AcsRouterWorkerOfferIssuedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String jobId = null; + String channelReference = null; + String channelId = null; + String workerId = null; + Map workerLabels = null; + OffsetDateTime offeredOn = null; + OffsetDateTime expiresOn = null; + Map workerTags = null; + Map jobLabels = null; + Map jobTags = null; + String queueId = null; + String offerId = null; + Integer jobPriority = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("jobId".equals(fieldName)) { + jobId = reader.getString(); + } else if ("channelReference".equals(fieldName)) { + channelReference = reader.getString(); + } else if ("channelId".equals(fieldName)) { + channelId = reader.getString(); + } else if ("workerId".equals(fieldName)) { + workerId = reader.getString(); + } else if ("workerLabels".equals(fieldName)) { + workerLabels = reader.readMap(reader1 -> reader1.getString()); + } else if ("offeredOn".equals(fieldName)) { + offeredOn = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("expiresOn".equals(fieldName)) { + expiresOn = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("workerTags".equals(fieldName)) { + workerTags = reader.readMap(reader1 -> reader1.getString()); + } else if ("jobLabels".equals(fieldName)) { + jobLabels = reader.readMap(reader1 -> reader1.getString()); + } else if ("jobTags".equals(fieldName)) { + jobTags = reader.readMap(reader1 -> reader1.getString()); + } else if ("queueId".equals(fieldName)) { + queueId = reader.getString(); + } else if ("offerId".equals(fieldName)) { + offerId = reader.getString(); + } else if ("jobPriority".equals(fieldName)) { + jobPriority = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + AcsRouterWorkerOfferIssuedEventData deserializedAcsRouterWorkerOfferIssuedEventData + = new AcsRouterWorkerOfferIssuedEventData(workerLabels, offeredOn, expiresOn, workerTags, jobLabels, + jobTags); + deserializedAcsRouterWorkerOfferIssuedEventData.jobId = jobId; + deserializedAcsRouterWorkerOfferIssuedEventData.channelReference = channelReference; + deserializedAcsRouterWorkerOfferIssuedEventData.channelId = channelId; + deserializedAcsRouterWorkerOfferIssuedEventData.workerId = workerId; + deserializedAcsRouterWorkerOfferIssuedEventData.queueId = queueId; + deserializedAcsRouterWorkerOfferIssuedEventData.offerId = offerId; + deserializedAcsRouterWorkerOfferIssuedEventData.jobPriority = jobPriority; + + return deserializedAcsRouterWorkerOfferIssuedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerOfferRevokedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerOfferRevokedEventData.java new file mode 100644 index 000000000000..9c4ca1304cd7 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerOfferRevokedEventData.java @@ -0,0 +1,179 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterWorkerOfferRevoked event. + */ +@Immutable +public final class AcsRouterWorkerOfferRevokedEventData extends AcsRouterWorkerEventData { + /* + * Router Worker Offer Revoked Queue Id + */ + @Generated + private String queueId; + + /* + * Router Worker Offer Revoked Offer Id + */ + @Generated + private String offerId; + + /* + * Router Worker events Worker Id + */ + @Generated + private String workerId; + + /* + * Router Event Channel ID + */ + @Generated + private String channelId; + + /* + * Router Event Channel Reference + */ + @Generated + private String channelReference; + + /* + * Router Event Job ID + */ + @Generated + private String jobId; + + /** + * Creates an instance of AcsRouterWorkerOfferRevokedEventData class. + */ + @Generated + private AcsRouterWorkerOfferRevokedEventData() { + } + + /** + * Get the queueId property: Router Worker Offer Revoked Queue Id. + * + * @return the queueId value. + */ + @Generated + public String getQueueId() { + return this.queueId; + } + + /** + * Get the offerId property: Router Worker Offer Revoked Offer Id. + * + * @return the offerId value. + */ + @Generated + public String getOfferId() { + return this.offerId; + } + + /** + * Get the workerId property: Router Worker events Worker Id. + * + * @return the workerId value. + */ + @Generated + @Override + public String getWorkerId() { + return this.workerId; + } + + /** + * Get the channelId property: Router Event Channel ID. + * + * @return the channelId value. + */ + @Generated + @Override + public String getChannelId() { + return this.channelId; + } + + /** + * Get the channelReference property: Router Event Channel Reference. + * + * @return the channelReference value. + */ + @Generated + @Override + public String getChannelReference() { + return this.channelReference; + } + + /** + * Get the jobId property: Router Event Job ID. + * + * @return the jobId value. + */ + @Generated + @Override + public String getJobId() { + return this.jobId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("jobId", getJobId()); + jsonWriter.writeStringField("channelReference", getChannelReference()); + jsonWriter.writeStringField("channelId", getChannelId()); + jsonWriter.writeStringField("workerId", getWorkerId()); + jsonWriter.writeStringField("queueId", this.queueId); + jsonWriter.writeStringField("offerId", this.offerId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRouterWorkerOfferRevokedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRouterWorkerOfferRevokedEventData 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 AcsRouterWorkerOfferRevokedEventData. + */ + @Generated + public static AcsRouterWorkerOfferRevokedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AcsRouterWorkerOfferRevokedEventData deserializedAcsRouterWorkerOfferRevokedEventData + = new AcsRouterWorkerOfferRevokedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("jobId".equals(fieldName)) { + deserializedAcsRouterWorkerOfferRevokedEventData.jobId = reader.getString(); + } else if ("channelReference".equals(fieldName)) { + deserializedAcsRouterWorkerOfferRevokedEventData.channelReference = reader.getString(); + } else if ("channelId".equals(fieldName)) { + deserializedAcsRouterWorkerOfferRevokedEventData.channelId = reader.getString(); + } else if ("workerId".equals(fieldName)) { + deserializedAcsRouterWorkerOfferRevokedEventData.workerId = reader.getString(); + } else if ("queueId".equals(fieldName)) { + deserializedAcsRouterWorkerOfferRevokedEventData.queueId = reader.getString(); + } else if ("offerId".equals(fieldName)) { + deserializedAcsRouterWorkerOfferRevokedEventData.offerId = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAcsRouterWorkerOfferRevokedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerRegisteredEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerRegisteredEventData.java new file mode 100644 index 000000000000..590ee62e84d0 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerRegisteredEventData.java @@ -0,0 +1,201 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.List; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterWorkerRegistered event. + */ +@Immutable +public final class AcsRouterWorkerRegisteredEventData implements JsonSerializable { + /* + * Router Worker Registered Worker Id + */ + @Generated + private String workerId; + + /* + * Router Worker Registered Queue Info + */ + @Generated + private final List queueAssignments; + + /* + * Router Worker Registered Channel Configuration + */ + @Generated + private final List channelConfigurations; + + /* + * Router Worker Register Total Capacity + */ + @Generated + private Integer totalCapacity; + + /* + * Router Worker Registered Labels + */ + @Generated + private final Map labels; + + /* + * Router Worker Registered Tags + */ + @Generated + private final Map tags; + + /** + * Creates an instance of AcsRouterWorkerRegisteredEventData class. + * + * @param queueAssignments the queueAssignments value to set. + * @param channelConfigurations the channelConfigurations value to set. + * @param labels the labels value to set. + * @param tags the tags value to set. + */ + @Generated + private AcsRouterWorkerRegisteredEventData(List queueAssignments, + List channelConfigurations, Map labels, + Map tags) { + this.queueAssignments = queueAssignments; + this.channelConfigurations = channelConfigurations; + this.labels = labels; + this.tags = tags; + } + + /** + * Get the workerId property: Router Worker Registered Worker Id. + * + * @return the workerId value. + */ + @Generated + public String getWorkerId() { + return this.workerId; + } + + /** + * Get the queueAssignments property: Router Worker Registered Queue Info. + * + * @return the queueAssignments value. + */ + @Generated + public List getQueueAssignments() { + return this.queueAssignments; + } + + /** + * Get the channelConfigurations property: Router Worker Registered Channel Configuration. + * + * @return the channelConfigurations value. + */ + @Generated + public List getChannelConfigurations() { + return this.channelConfigurations; + } + + /** + * Get the totalCapacity property: Router Worker Register Total Capacity. + * + * @return the totalCapacity value. + */ + @Generated + public Integer getTotalCapacity() { + return this.totalCapacity; + } + + /** + * Get the labels property: Router Worker Registered Labels. + * + * @return the labels value. + */ + @Generated + public Map getLabels() { + return this.labels; + } + + /** + * Get the tags property: Router Worker Registered Tags. + * + * @return the tags value. + */ + @Generated + public Map getTags() { + return this.tags; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("queueAssignments", this.queueAssignments, + (writer, element) -> writer.writeJson(element)); + jsonWriter.writeArrayField("channelConfigurations", this.channelConfigurations, + (writer, element) -> writer.writeJson(element)); + jsonWriter.writeMapField("labels", this.labels, (writer, element) -> writer.writeString(element)); + jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("workerId", this.workerId); + jsonWriter.writeNumberField("totalCapacity", this.totalCapacity); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRouterWorkerRegisteredEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRouterWorkerRegisteredEventData 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 AcsRouterWorkerRegisteredEventData. + */ + @Generated + public static AcsRouterWorkerRegisteredEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + List queueAssignments = null; + List channelConfigurations = null; + Map labels = null; + Map tags = null; + String workerId = null; + Integer totalCapacity = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("queueAssignments".equals(fieldName)) { + queueAssignments = reader.readArray(reader1 -> AcsRouterQueueDetails.fromJson(reader1)); + } else if ("channelConfigurations".equals(fieldName)) { + channelConfigurations + = reader.readArray(reader1 -> AcsRouterChannelConfiguration.fromJson(reader1)); + } else if ("labels".equals(fieldName)) { + labels = reader.readMap(reader1 -> reader1.getString()); + } else if ("tags".equals(fieldName)) { + tags = reader.readMap(reader1 -> reader1.getString()); + } else if ("workerId".equals(fieldName)) { + workerId = reader.getString(); + } else if ("totalCapacity".equals(fieldName)) { + totalCapacity = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + AcsRouterWorkerRegisteredEventData deserializedAcsRouterWorkerRegisteredEventData + = new AcsRouterWorkerRegisteredEventData(queueAssignments, channelConfigurations, labels, tags); + deserializedAcsRouterWorkerRegisteredEventData.workerId = workerId; + deserializedAcsRouterWorkerRegisteredEventData.totalCapacity = totalCapacity; + + return deserializedAcsRouterWorkerRegisteredEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerSelector.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerSelector.java new file mode 100644 index 000000000000..27dec6f6cf48 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerSelector.java @@ -0,0 +1,203 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.BinaryData; +import com.azure.core.util.CoreUtils; +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.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Router Job Worker Selector. + */ +@Immutable +public final class AcsRouterWorkerSelector implements JsonSerializable { + + /* + * Router Job Worker Selector Key + */ + @Generated + private String key; + + /* + * Router Job Worker Selector Label Operator + */ + @Generated + private final AcsRouterLabelOperator labelOperator; + + /* + * Router Job Worker Selector Value + */ + @Generated + private final BinaryData labelValue; + + /* + * Router Job Worker Selector Time to Live in Seconds + */ + @Generated + private final double timeToLive; + + /* + * Router Job Worker Selector State + */ + @Generated + private final AcsRouterWorkerSelectorState state; + + /* + * Router Job Worker Selector Expiration Time + */ + @Generated + private final OffsetDateTime expirationTime; + + /** + * Creates an instance of AcsRouterWorkerSelector class. + * + * @param labelOperator the labelOperator value to set. + * @param labelValue the labelValue value to set. + * @param timeToLive the timeToLive value to set. + * @param state the state value to set. + * @param expirationTime the expirationTime value to set. + */ + @Generated + private AcsRouterWorkerSelector(AcsRouterLabelOperator labelOperator, BinaryData labelValue, double timeToLive, + AcsRouterWorkerSelectorState state, OffsetDateTime expirationTime) { + this.labelOperator = labelOperator; + this.labelValue = labelValue; + this.timeToLive = timeToLive; + this.state = state; + this.expirationTime = expirationTime; + } + + /** + * Get the key property: Router Job Worker Selector Key. + * + * @return the key value. + */ + @Generated + public String getKey() { + return this.key; + } + + /** + * Get the labelOperator property: Router Job Worker Selector Label Operator. + * + * @return the labelOperator value. + */ + @Generated + public AcsRouterLabelOperator getLabelOperator() { + return this.labelOperator; + } + + /** + * Get the labelValue property: Router Job Worker Selector Value. + * + * @return the labelValue value. + */ + @Generated + public BinaryData getLabelValue() { + return this.labelValue; + } + + /** + * Get the timeToLive property: Router Job Worker Selector Time to Live in Seconds. + * + * @return the timeToLive value. + */ + @Generated + public Duration getTimeToLive() { + return Duration.ofSeconds((long) timeToLive); + } + + /** + * Get the state property: Router Job Worker Selector State. + * + * @return the state value. + */ + @Generated + public AcsRouterWorkerSelectorState getState() { + return this.state; + } + + /** + * Get the expirationTime property: Router Job Worker Selector Expiration Time. + * + * @return the expirationTime value. + */ + @Generated + public OffsetDateTime getExpirationTime() { + return this.expirationTime; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("labelOperator", this.labelOperator == null ? null : this.labelOperator.toString()); + jsonWriter.writeFieldName("value"); + this.labelValue.writeTo(jsonWriter); + jsonWriter.writeDoubleField("ttlSeconds", this.timeToLive); + jsonWriter.writeStringField("state", this.state == null ? null : this.state.toString()); + jsonWriter.writeStringField("expirationTime", + this.expirationTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.expirationTime)); + jsonWriter.writeStringField("key", this.key); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRouterWorkerSelector from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRouterWorkerSelector 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 AcsRouterWorkerSelector. + */ + @Generated + public static AcsRouterWorkerSelector fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AcsRouterLabelOperator labelOperator = null; + BinaryData labelValue = null; + double timeToLive = 0.0; + AcsRouterWorkerSelectorState state = null; + OffsetDateTime expirationTime = null; + String key = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("labelOperator".equals(fieldName)) { + labelOperator = AcsRouterLabelOperator.fromString(reader.getString()); + } else if ("value".equals(fieldName)) { + labelValue + = reader.getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped())); + } else if ("ttlSeconds".equals(fieldName)) { + timeToLive = reader.getDouble(); + } else if ("state".equals(fieldName)) { + state = AcsRouterWorkerSelectorState.fromString(reader.getString()); + } else if ("expirationTime".equals(fieldName)) { + expirationTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("key".equals(fieldName)) { + key = reader.getString(); + } else { + reader.skipChildren(); + } + } + AcsRouterWorkerSelector deserializedAcsRouterWorkerSelector + = new AcsRouterWorkerSelector(labelOperator, labelValue, timeToLive, state, expirationTime); + deserializedAcsRouterWorkerSelector.key = key; + return deserializedAcsRouterWorkerSelector; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerSelectorState.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerSelectorState.java new file mode 100644 index 000000000000..149d5a866c2a --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerSelectorState.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Router Worker Selector State. + */ +public final class AcsRouterWorkerSelectorState extends ExpandableStringEnum { + /** + * Router Worker Selector State Active. + */ + @Generated + public static final AcsRouterWorkerSelectorState ACTIVE = fromString("active"); + + /** + * Router Worker Selector State Expired. + */ + @Generated + public static final AcsRouterWorkerSelectorState EXPIRED = fromString("expired"); + + /** + * Creates a new instance of AcsRouterWorkerSelectorState value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public AcsRouterWorkerSelectorState() { + } + + /** + * Creates or finds a AcsRouterWorkerSelectorState from its string representation. + * + * @param name a name to look for. + * @return the corresponding AcsRouterWorkerSelectorState. + */ + @Generated + public static AcsRouterWorkerSelectorState fromString(String name) { + return fromString(name, AcsRouterWorkerSelectorState.class); + } + + /** + * Gets known AcsRouterWorkerSelectorState values. + * + * @return known AcsRouterWorkerSelectorState values. + */ + @Generated + public static Collection values() { + return values(AcsRouterWorkerSelectorState.class); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerUpdatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerUpdatedEventData.java new file mode 100644 index 000000000000..a281aa1e6f0b --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRouterWorkerUpdatedEventData.java @@ -0,0 +1,226 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.List; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.RouterWorkerUpdated event. + */ +@Immutable +public final class AcsRouterWorkerUpdatedEventData implements JsonSerializable { + /* + * Router Worker Updated Worker Id + */ + @Generated + private String workerId; + + /* + * Router Worker Updated Queue Info + */ + @Generated + private final List queueAssignments; + + /* + * Router Worker Updated Channel Configuration + */ + @Generated + private final List channelConfigurations; + + /* + * Router Worker Updated Total Capacity + */ + @Generated + private Integer totalCapacity; + + /* + * Router Worker Updated Labels + */ + @Generated + private final Map labels; + + /* + * Router Worker Updated Tags + */ + @Generated + private final Map tags; + + /* + * Router Worker Properties Updated + */ + @Generated + private final List updatedWorkerProperties; + + /** + * Creates an instance of AcsRouterWorkerUpdatedEventData class. + * + * @param queueAssignments the queueAssignments value to set. + * @param channelConfigurations the channelConfigurations value to set. + * @param labels the labels value to set. + * @param tags the tags value to set. + * @param updatedWorkerProperties the updatedWorkerProperties value to set. + */ + @Generated + private AcsRouterWorkerUpdatedEventData(List queueAssignments, + List channelConfigurations, Map labels, Map tags, + List updatedWorkerProperties) { + this.queueAssignments = queueAssignments; + this.channelConfigurations = channelConfigurations; + this.labels = labels; + this.tags = tags; + this.updatedWorkerProperties = updatedWorkerProperties; + } + + /** + * Get the workerId property: Router Worker Updated Worker Id. + * + * @return the workerId value. + */ + @Generated + public String getWorkerId() { + return this.workerId; + } + + /** + * Get the queueAssignments property: Router Worker Updated Queue Info. + * + * @return the queueAssignments value. + */ + @Generated + public List getQueueAssignments() { + return this.queueAssignments; + } + + /** + * Get the channelConfigurations property: Router Worker Updated Channel Configuration. + * + * @return the channelConfigurations value. + */ + @Generated + public List getChannelConfigurations() { + return this.channelConfigurations; + } + + /** + * Get the totalCapacity property: Router Worker Updated Total Capacity. + * + * @return the totalCapacity value. + */ + @Generated + public Integer getTotalCapacity() { + return this.totalCapacity; + } + + /** + * Get the labels property: Router Worker Updated Labels. + * + * @return the labels value. + */ + @Generated + public Map getLabels() { + return this.labels; + } + + /** + * Get the tags property: Router Worker Updated Tags. + * + * @return the tags value. + */ + @Generated + public Map getTags() { + return this.tags; + } + + /** + * Get the updatedWorkerProperties property: Router Worker Properties Updated. + * + * @return the updatedWorkerProperties value. + */ + @Generated + public List getUpdatedWorkerProperties() { + return this.updatedWorkerProperties; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("queueAssignments", this.queueAssignments, + (writer, element) -> writer.writeJson(element)); + jsonWriter.writeArrayField("channelConfigurations", this.channelConfigurations, + (writer, element) -> writer.writeJson(element)); + jsonWriter.writeMapField("labels", this.labels, (writer, element) -> writer.writeString(element)); + jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); + jsonWriter.writeArrayField("updatedWorkerProperties", this.updatedWorkerProperties, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); + jsonWriter.writeStringField("workerId", this.workerId); + jsonWriter.writeNumberField("totalCapacity", this.totalCapacity); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsRouterWorkerUpdatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsRouterWorkerUpdatedEventData 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 AcsRouterWorkerUpdatedEventData. + */ + @Generated + public static AcsRouterWorkerUpdatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + List queueAssignments = null; + List channelConfigurations = null; + Map labels = null; + Map tags = null; + List updatedWorkerProperties = null; + String workerId = null; + Integer totalCapacity = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("queueAssignments".equals(fieldName)) { + queueAssignments = reader.readArray(reader1 -> AcsRouterQueueDetails.fromJson(reader1)); + } else if ("channelConfigurations".equals(fieldName)) { + channelConfigurations + = reader.readArray(reader1 -> AcsRouterChannelConfiguration.fromJson(reader1)); + } else if ("labels".equals(fieldName)) { + labels = reader.readMap(reader1 -> reader1.getString()); + } else if ("tags".equals(fieldName)) { + tags = reader.readMap(reader1 -> reader1.getString()); + } else if ("updatedWorkerProperties".equals(fieldName)) { + updatedWorkerProperties + = reader.readArray(reader1 -> AcsRouterUpdatedWorkerProperty.fromString(reader1.getString())); + } else if ("workerId".equals(fieldName)) { + workerId = reader.getString(); + } else if ("totalCapacity".equals(fieldName)) { + totalCapacity = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + AcsRouterWorkerUpdatedEventData deserializedAcsRouterWorkerUpdatedEventData + = new AcsRouterWorkerUpdatedEventData(queueAssignments, channelConfigurations, labels, tags, + updatedWorkerProperties); + deserializedAcsRouterWorkerUpdatedEventData.workerId = workerId; + deserializedAcsRouterWorkerUpdatedEventData.totalCapacity = totalCapacity; + + return deserializedAcsRouterWorkerUpdatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsSmsDeliveryAttemptProperties.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsSmsDeliveryAttemptProperties.java new file mode 100644 index 000000000000..a9c3c97c35cd --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsSmsDeliveryAttemptProperties.java @@ -0,0 +1,133 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema for details of a delivery attempt. + */ +@Immutable +public final class AcsSmsDeliveryAttemptProperties implements JsonSerializable { + /* + * TimeStamp when delivery was attempted + */ + @Generated + private final OffsetDateTime timestamp; + + /* + * Number of segments that were successfully delivered + */ + @Generated + private Integer segmentsSucceeded; + + /* + * Number of segments whose delivery failed + */ + @Generated + private Integer segmentsFailed; + + /** + * Creates an instance of AcsSmsDeliveryAttemptProperties class. + * + * @param timestamp the timestamp value to set. + */ + @Generated + private AcsSmsDeliveryAttemptProperties(OffsetDateTime timestamp) { + this.timestamp = timestamp; + } + + /** + * Get the timestamp property: TimeStamp when delivery was attempted. + * + * @return the timestamp value. + */ + @Generated + public OffsetDateTime getTimestamp() { + return this.timestamp; + } + + /** + * Get the segmentsSucceeded property: Number of segments that were successfully delivered. + * + * @return the segmentsSucceeded value. + */ + @Generated + public Integer getSegmentsSucceeded() { + return this.segmentsSucceeded; + } + + /** + * Get the segmentsFailed property: Number of segments whose delivery failed. + * + * @return the segmentsFailed value. + */ + @Generated + public Integer getSegmentsFailed() { + return this.segmentsFailed; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("timestamp", + this.timestamp == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.timestamp)); + jsonWriter.writeNumberField("segmentsSucceeded", this.segmentsSucceeded); + jsonWriter.writeNumberField("segmentsFailed", this.segmentsFailed); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsSmsDeliveryAttemptProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsSmsDeliveryAttemptProperties 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 AcsSmsDeliveryAttemptProperties. + */ + @Generated + public static AcsSmsDeliveryAttemptProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OffsetDateTime timestamp = null; + Integer segmentsSucceeded = null; + Integer segmentsFailed = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("timestamp".equals(fieldName)) { + timestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("segmentsSucceeded".equals(fieldName)) { + segmentsSucceeded = reader.getNullable(JsonReader::getInt); + } else if ("segmentsFailed".equals(fieldName)) { + segmentsFailed = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + AcsSmsDeliveryAttemptProperties deserializedAcsSmsDeliveryAttemptProperties + = new AcsSmsDeliveryAttemptProperties(timestamp); + deserializedAcsSmsDeliveryAttemptProperties.segmentsSucceeded = segmentsSucceeded; + deserializedAcsSmsDeliveryAttemptProperties.segmentsFailed = segmentsFailed; + + return deserializedAcsSmsDeliveryAttemptProperties; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsSmsDeliveryReportReceivedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsSmsDeliveryReportReceivedEventData.java new file mode 100644 index 000000000000..9a4b103bcc1e --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsSmsDeliveryReportReceivedEventData.java @@ -0,0 +1,246 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.List; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.SMSDeliveryReportReceived event. + */ +@Immutable +public final class AcsSmsDeliveryReportReceivedEventData extends AcsSmsEventBaseProperties { + /* + * Status of Delivery + */ + @Generated + private String deliveryStatus; + + /* + * Details about Delivery Status + */ + @Generated + private String deliveryStatusDetails; + + /* + * List of details of delivery attempts made + */ + @Generated + private final List deliveryAttempts; + + /* + * The time at which the SMS delivery report was received + */ + @Generated + private final OffsetDateTime receivedTimestamp; + + /* + * Customer Content + */ + @Generated + private String tag; + + /* + * The identity of SMS message receiver + */ + @Generated + private String to; + + /* + * The identity of SMS message sender + */ + @Generated + private String from; + + /* + * The identity of the SMS message + */ + @Generated + private String messageId; + + /** + * Creates an instance of AcsSmsDeliveryReportReceivedEventData class. + * + * @param deliveryAttempts the deliveryAttempts value to set. + * @param receivedTimestamp the receivedTimestamp value to set. + */ + @Generated + private AcsSmsDeliveryReportReceivedEventData(List deliveryAttempts, + OffsetDateTime receivedTimestamp) { + this.deliveryAttempts = deliveryAttempts; + this.receivedTimestamp = receivedTimestamp; + } + + /** + * Get the deliveryStatus property: Status of Delivery. + * + * @return the deliveryStatus value. + */ + @Generated + public String getDeliveryStatus() { + return this.deliveryStatus; + } + + /** + * Get the deliveryStatusDetails property: Details about Delivery Status. + * + * @return the deliveryStatusDetails value. + */ + @Generated + public String getDeliveryStatusDetails() { + return this.deliveryStatusDetails; + } + + /** + * Get the deliveryAttempts property: List of details of delivery attempts made. + * + * @return the deliveryAttempts value. + */ + @Generated + public List getDeliveryAttempts() { + return this.deliveryAttempts; + } + + /** + * Get the receivedTimestamp property: The time at which the SMS delivery report was received. + * + * @return the receivedTimestamp value. + */ + @Generated + public OffsetDateTime getReceivedTimestamp() { + return this.receivedTimestamp; + } + + /** + * Get the tag property: Customer Content. + * + * @return the tag value. + */ + @Generated + public String getTag() { + return this.tag; + } + + /** + * Get the to property: The identity of SMS message receiver. + * + * @return the to value. + */ + @Generated + @Override + public String getTo() { + return this.to; + } + + /** + * Get the from property: The identity of SMS message sender. + * + * @return the from value. + */ + @Generated + @Override + public String getFrom() { + return this.from; + } + + /** + * Get the messageId property: The identity of the SMS message. + * + * @return the messageId value. + */ + @Generated + @Override + public String getMessageId() { + return this.messageId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("messageId", getMessageId()); + jsonWriter.writeStringField("from", getFrom()); + jsonWriter.writeStringField("to", getTo()); + jsonWriter.writeArrayField("deliveryAttempts", this.deliveryAttempts, + (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("receivedTimestamp", + this.receivedTimestamp == null + ? null + : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.receivedTimestamp)); + jsonWriter.writeStringField("deliveryStatus", this.deliveryStatus); + jsonWriter.writeStringField("deliveryStatusDetails", this.deliveryStatusDetails); + jsonWriter.writeStringField("tag", this.tag); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsSmsDeliveryReportReceivedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsSmsDeliveryReportReceivedEventData 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 AcsSmsDeliveryReportReceivedEventData. + */ + @Generated + public static AcsSmsDeliveryReportReceivedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String messageId = null; + String from = null; + String to = null; + List deliveryAttempts = null; + OffsetDateTime receivedTimestamp = null; + String deliveryStatus = null; + String deliveryStatusDetails = null; + String tag = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("messageId".equals(fieldName)) { + messageId = reader.getString(); + } else if ("from".equals(fieldName)) { + from = reader.getString(); + } else if ("to".equals(fieldName)) { + to = reader.getString(); + } else if ("deliveryAttempts".equals(fieldName)) { + deliveryAttempts = reader.readArray(reader1 -> AcsSmsDeliveryAttemptProperties.fromJson(reader1)); + } else if ("receivedTimestamp".equals(fieldName)) { + receivedTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("deliveryStatus".equals(fieldName)) { + deliveryStatus = reader.getString(); + } else if ("deliveryStatusDetails".equals(fieldName)) { + deliveryStatusDetails = reader.getString(); + } else if ("tag".equals(fieldName)) { + tag = reader.getString(); + } else { + reader.skipChildren(); + } + } + AcsSmsDeliveryReportReceivedEventData deserializedAcsSmsDeliveryReportReceivedEventData + = new AcsSmsDeliveryReportReceivedEventData(deliveryAttempts, receivedTimestamp); + deserializedAcsSmsDeliveryReportReceivedEventData.messageId = messageId; + deserializedAcsSmsDeliveryReportReceivedEventData.from = from; + deserializedAcsSmsDeliveryReportReceivedEventData.to = to; + deserializedAcsSmsDeliveryReportReceivedEventData.deliveryStatus = deliveryStatus; + deserializedAcsSmsDeliveryReportReceivedEventData.deliveryStatusDetails = deliveryStatusDetails; + deserializedAcsSmsDeliveryReportReceivedEventData.tag = tag; + + return deserializedAcsSmsDeliveryReportReceivedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsSmsEventBaseProperties.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsSmsEventBaseProperties.java new file mode 100644 index 000000000000..eadb6458fd8d --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsSmsEventBaseProperties.java @@ -0,0 +1,154 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of common properties of all SMS events. + */ +@Immutable +public class AcsSmsEventBaseProperties implements JsonSerializable { + /* + * The identity of the SMS message + */ + @Generated + private String messageId; + + /* + * The identity of SMS message sender + */ + @Generated + private String from; + + /* + * The identity of SMS message receiver + */ + @Generated + private String to; + + /** + * Creates an instance of AcsSmsEventBaseProperties class. + */ + @Generated + protected AcsSmsEventBaseProperties() { + } + + /** + * Get the messageId property: The identity of the SMS message. + * + * @return the messageId value. + */ + @Generated + public String getMessageId() { + return this.messageId; + } + + /** + * Set the messageId property: The identity of the SMS message. + * + * @param messageId the messageId value to set. + * @return the AcsSmsEventBaseProperties object itself. + */ + @Generated + AcsSmsEventBaseProperties setMessageId(String messageId) { + this.messageId = messageId; + return this; + } + + /** + * Get the from property: The identity of SMS message sender. + * + * @return the from value. + */ + @Generated + public String getFrom() { + return this.from; + } + + /** + * Set the from property: The identity of SMS message sender. + * + * @param from the from value to set. + * @return the AcsSmsEventBaseProperties object itself. + */ + @Generated + AcsSmsEventBaseProperties setFrom(String from) { + this.from = from; + return this; + } + + /** + * Get the to property: The identity of SMS message receiver. + * + * @return the to value. + */ + @Generated + public String getTo() { + return this.to; + } + + /** + * Set the to property: The identity of SMS message receiver. + * + * @param to the to value to set. + * @return the AcsSmsEventBaseProperties object itself. + */ + @Generated + AcsSmsEventBaseProperties setTo(String to) { + this.to = to; + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("messageId", this.messageId); + jsonWriter.writeStringField("from", this.from); + jsonWriter.writeStringField("to", this.to); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsSmsEventBaseProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsSmsEventBaseProperties 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 AcsSmsEventBaseProperties. + */ + @Generated + public static AcsSmsEventBaseProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AcsSmsEventBaseProperties deserializedAcsSmsEventBaseProperties = new AcsSmsEventBaseProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("messageId".equals(fieldName)) { + deserializedAcsSmsEventBaseProperties.messageId = reader.getString(); + } else if ("from".equals(fieldName)) { + deserializedAcsSmsEventBaseProperties.from = reader.getString(); + } else if ("to".equals(fieldName)) { + deserializedAcsSmsEventBaseProperties.to = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAcsSmsEventBaseProperties; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsSmsReceivedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsSmsReceivedEventData.java new file mode 100644 index 000000000000..a9f228817d1c --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsSmsReceivedEventData.java @@ -0,0 +1,201 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Communication.SMSReceived event. + */ +@Immutable +public final class AcsSmsReceivedEventData extends AcsSmsEventBaseProperties { + /* + * The SMS content + */ + @Generated + private String message; + + /* + * The time at which the SMS was received + */ + @Generated + private final OffsetDateTime receivedTimestamp; + + /* + * Number of segments in the message + */ + @Generated + private final int segmentCount; + + /* + * The identity of SMS message receiver + */ + @Generated + private String to; + + /* + * The identity of SMS message sender + */ + @Generated + private String from; + + /* + * The identity of the SMS message + */ + @Generated + private String messageId; + + /** + * Creates an instance of AcsSmsReceivedEventData class. + * + * @param receivedTimestamp the receivedTimestamp value to set. + * @param segmentCount the segmentCount value to set. + */ + @Generated + private AcsSmsReceivedEventData(OffsetDateTime receivedTimestamp, int segmentCount) { + this.receivedTimestamp = receivedTimestamp; + this.segmentCount = segmentCount; + } + + /** + * Get the message property: The SMS content. + * + * @return the message value. + */ + @Generated + public String getMessage() { + return this.message; + } + + /** + * Get the receivedTimestamp property: The time at which the SMS was received. + * + * @return the receivedTimestamp value. + */ + @Generated + public OffsetDateTime getReceivedTimestamp() { + return this.receivedTimestamp; + } + + /** + * Get the segmentCount property: Number of segments in the message. + * + * @return the segmentCount value. + */ + @Generated + public int getSegmentCount() { + return this.segmentCount; + } + + /** + * Get the to property: The identity of SMS message receiver. + * + * @return the to value. + */ + @Generated + @Override + public String getTo() { + return this.to; + } + + /** + * Get the from property: The identity of SMS message sender. + * + * @return the from value. + */ + @Generated + @Override + public String getFrom() { + return this.from; + } + + /** + * Get the messageId property: The identity of the SMS message. + * + * @return the messageId value. + */ + @Generated + @Override + public String getMessageId() { + return this.messageId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("messageId", getMessageId()); + jsonWriter.writeStringField("from", getFrom()); + jsonWriter.writeStringField("to", getTo()); + jsonWriter.writeStringField("receivedTimestamp", + this.receivedTimestamp == null + ? null + : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.receivedTimestamp)); + jsonWriter.writeIntField("segmentCount", this.segmentCount); + jsonWriter.writeStringField("message", this.message); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsSmsReceivedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsSmsReceivedEventData 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 AcsSmsReceivedEventData. + */ + @Generated + public static AcsSmsReceivedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String messageId = null; + String from = null; + String to = null; + OffsetDateTime receivedTimestamp = null; + int segmentCount = 0; + String message = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("messageId".equals(fieldName)) { + messageId = reader.getString(); + } else if ("from".equals(fieldName)) { + from = reader.getString(); + } else if ("to".equals(fieldName)) { + to = reader.getString(); + } else if ("receivedTimestamp".equals(fieldName)) { + receivedTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("segmentCount".equals(fieldName)) { + segmentCount = reader.getInt(); + } else if ("message".equals(fieldName)) { + message = reader.getString(); + } else { + reader.skipChildren(); + } + } + AcsSmsReceivedEventData deserializedAcsSmsReceivedEventData + = new AcsSmsReceivedEventData(receivedTimestamp, segmentCount); + deserializedAcsSmsReceivedEventData.messageId = messageId; + deserializedAcsSmsReceivedEventData.from = from; + deserializedAcsSmsReceivedEventData.to = to; + deserializedAcsSmsReceivedEventData.message = message; + + return deserializedAcsSmsReceivedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsUserDisconnectedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsUserDisconnectedEventData.java new file mode 100644 index 000000000000..34aa60121c68 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsUserDisconnectedEventData.java @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for an Microsoft.Communication.UserDisconnected event. + */ +@Immutable +public final class AcsUserDisconnectedEventData implements JsonSerializable { + /* + * The communication identifier of the user who was disconnected + */ + @Generated + private final CommunicationIdentifierModel userCommunicationIdentifier; + + /** + * Creates an instance of AcsUserDisconnectedEventData class. + * + * @param userCommunicationIdentifier the userCommunicationIdentifier value to set. + */ + @Generated + private AcsUserDisconnectedEventData(CommunicationIdentifierModel userCommunicationIdentifier) { + this.userCommunicationIdentifier = userCommunicationIdentifier; + } + + /** + * Get the userCommunicationIdentifier property: The communication identifier of the user who was disconnected. + * + * @return the userCommunicationIdentifier value. + */ + @Generated + public CommunicationIdentifierModel getUserCommunicationIdentifier() { + return this.userCommunicationIdentifier; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("userCommunicationIdentifier", this.userCommunicationIdentifier); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsUserDisconnectedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsUserDisconnectedEventData 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 AcsUserDisconnectedEventData. + */ + @Generated + public static AcsUserDisconnectedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CommunicationIdentifierModel userCommunicationIdentifier = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("userCommunicationIdentifier".equals(fieldName)) { + userCommunicationIdentifier = CommunicationIdentifierModel.fromJson(reader); + } else { + reader.skipChildren(); + } + } + return new AcsUserDisconnectedEventData(userCommunicationIdentifier); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsUserEngagement.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsUserEngagement.java new file mode 100644 index 000000000000..f61d8b9830fb --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsUserEngagement.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The type of engagement user have with email. + */ +public final class AcsUserEngagement extends ExpandableStringEnum { + /** + * View. + */ + @Generated + public static final AcsUserEngagement VIEW = fromString("view"); + + /** + * Click. + */ + @Generated + public static final AcsUserEngagement CLICK = fromString("click"); + + /** + * Creates a new instance of AcsUserEngagement value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public AcsUserEngagement() { + } + + /** + * Creates or finds a AcsUserEngagement from its string representation. + * + * @param name a name to look for. + * @return the corresponding AcsUserEngagement. + */ + @Generated + public static AcsUserEngagement fromString(String name) { + return fromString(name, AcsUserEngagement.class); + } + + /** + * Gets known AcsUserEngagement values. + * + * @return known AcsUserEngagement values. + */ + @Generated + public static Collection values() { + return values(AcsUserEngagement.class); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiCenterApiDefinitionAddedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiCenterApiDefinitionAddedEventData.java new file mode 100644 index 000000000000..bbef058bfb22 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiCenterApiDefinitionAddedEventData.java @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the data property of an EventGridEvent for a Microsoft.ApiCenter.ApiDefinitionAdded event. + */ +@Immutable +public final class ApiCenterApiDefinitionAddedEventData + implements JsonSerializable { + /* + * API definition title. + */ + @Generated + private final String title; + + /* + * API definition description. + */ + @Generated + private String description; + + /* + * API definition specification. + */ + @Generated + private ApiCenterApiSpecification specification; + + /** + * Creates an instance of ApiCenterApiDefinitionAddedEventData class. + * + * @param title the title value to set. + */ + @Generated + private ApiCenterApiDefinitionAddedEventData(String title) { + this.title = title; + } + + /** + * Get the title property: API definition title. + * + * @return the title value. + */ + @Generated + public String getTitle() { + return this.title; + } + + /** + * Get the description property: API definition description. + * + * @return the description value. + */ + @Generated + public String getDescription() { + return this.description; + } + + /** + * Get the specification property: API definition specification. + * + * @return the specification value. + */ + @Generated + public ApiCenterApiSpecification getSpecification() { + return this.specification; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("title", this.title); + jsonWriter.writeStringField("description", this.description); + jsonWriter.writeJsonField("specification", this.specification); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiCenterApiDefinitionAddedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiCenterApiDefinitionAddedEventData 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 ApiCenterApiDefinitionAddedEventData. + */ + @Generated + public static ApiCenterApiDefinitionAddedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String title = null; + String description = null; + ApiCenterApiSpecification specification = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("title".equals(fieldName)) { + title = reader.getString(); + } else if ("description".equals(fieldName)) { + description = reader.getString(); + } else if ("specification".equals(fieldName)) { + specification = ApiCenterApiSpecification.fromJson(reader); + } else { + reader.skipChildren(); + } + } + ApiCenterApiDefinitionAddedEventData deserializedApiCenterApiDefinitionAddedEventData + = new ApiCenterApiDefinitionAddedEventData(title); + deserializedApiCenterApiDefinitionAddedEventData.description = description; + deserializedApiCenterApiDefinitionAddedEventData.specification = specification; + + return deserializedApiCenterApiDefinitionAddedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiCenterApiDefinitionUpdatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiCenterApiDefinitionUpdatedEventData.java new file mode 100644 index 000000000000..c6554c6238a0 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiCenterApiDefinitionUpdatedEventData.java @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the data property of an EventGridEvent for a Microsoft.ApiCenter.ApiDefinitionUpdated event. + */ +@Immutable +public final class ApiCenterApiDefinitionUpdatedEventData + implements JsonSerializable { + /* + * API definition title. + */ + @Generated + private final String title; + + /* + * API definition description. + */ + @Generated + private String description; + + /* + * API definition specification. + */ + @Generated + private ApiCenterApiSpecification specification; + + /** + * Creates an instance of ApiCenterApiDefinitionUpdatedEventData class. + * + * @param title the title value to set. + */ + @Generated + private ApiCenterApiDefinitionUpdatedEventData(String title) { + this.title = title; + } + + /** + * Get the title property: API definition title. + * + * @return the title value. + */ + @Generated + public String getTitle() { + return this.title; + } + + /** + * Get the description property: API definition description. + * + * @return the description value. + */ + @Generated + public String getDescription() { + return this.description; + } + + /** + * Get the specification property: API definition specification. + * + * @return the specification value. + */ + @Generated + public ApiCenterApiSpecification getSpecification() { + return this.specification; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("title", this.title); + jsonWriter.writeStringField("description", this.description); + jsonWriter.writeJsonField("specification", this.specification); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiCenterApiDefinitionUpdatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiCenterApiDefinitionUpdatedEventData 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 ApiCenterApiDefinitionUpdatedEventData. + */ + @Generated + public static ApiCenterApiDefinitionUpdatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String title = null; + String description = null; + ApiCenterApiSpecification specification = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("title".equals(fieldName)) { + title = reader.getString(); + } else if ("description".equals(fieldName)) { + description = reader.getString(); + } else if ("specification".equals(fieldName)) { + specification = ApiCenterApiSpecification.fromJson(reader); + } else { + reader.skipChildren(); + } + } + ApiCenterApiDefinitionUpdatedEventData deserializedApiCenterApiDefinitionUpdatedEventData + = new ApiCenterApiDefinitionUpdatedEventData(title); + deserializedApiCenterApiDefinitionUpdatedEventData.description = description; + deserializedApiCenterApiDefinitionUpdatedEventData.specification = specification; + + return deserializedApiCenterApiDefinitionUpdatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiCenterApiSpecification.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiCenterApiSpecification.java new file mode 100644 index 000000000000..cf9c7dfd9a26 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiCenterApiSpecification.java @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * API specification details. + */ +@Immutable +public final class ApiCenterApiSpecification implements JsonSerializable { + /* + * Specification name. + */ + @Generated + private final String name; + + /* + * Specification version. + */ + @Generated + private String version; + + /** + * Creates an instance of ApiCenterApiSpecification class. + * + * @param name the name value to set. + */ + @Generated + private ApiCenterApiSpecification(String name) { + this.name = name; + } + + /** + * Get the name property: Specification name. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the version property: Specification version. + * + * @return the version value. + */ + @Generated + public String getVersion() { + return this.version; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("version", this.version); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiCenterApiSpecification from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiCenterApiSpecification 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 ApiCenterApiSpecification. + */ + @Generated + public static ApiCenterApiSpecification fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String name = null; + String version = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("name".equals(fieldName)) { + name = reader.getString(); + } else if ("version".equals(fieldName)) { + version = reader.getString(); + } else { + reader.skipChildren(); + } + } + ApiCenterApiSpecification deserializedApiCenterApiSpecification = new ApiCenterApiSpecification(name); + deserializedApiCenterApiSpecification.version = version; + + return deserializedApiCenterApiSpecification; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementApiCreatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementApiCreatedEventData.java new file mode 100644 index 000000000000..766c2584f942 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementApiCreatedEventData.java @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.APICreated event. + */ +@Immutable +public final class ApiManagementApiCreatedEventData implements JsonSerializable { + /* + * The fully qualified ID of the resource that the compliance state change is for, including the resource name and + * resource type. Uses the format, + * `/subscriptions//resourceGroups//Microsoft.ApiManagement/service//< + * ResourceType>/` + */ + @Generated + private String resourceUri; + + /** + * Creates an instance of ApiManagementApiCreatedEventData class. + */ + @Generated + private ApiManagementApiCreatedEventData() { + } + + /** + * Get the resourceUri property: The fully qualified ID of the resource that the compliance state change is for, + * including the resource name and resource type. Uses the format, + * `/subscriptions/<SubscriptionID>/resourceGroups/<ResourceGroup>/Microsoft.ApiManagement/service/<ServiceName>/<ResourceType>/<ResourceName>`. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiManagementApiCreatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiManagementApiCreatedEventData 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 ApiManagementApiCreatedEventData. + */ + @Generated + public static ApiManagementApiCreatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ApiManagementApiCreatedEventData deserializedApiManagementApiCreatedEventData + = new ApiManagementApiCreatedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceUri".equals(fieldName)) { + deserializedApiManagementApiCreatedEventData.resourceUri = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedApiManagementApiCreatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementApiDeletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementApiDeletedEventData.java new file mode 100644 index 000000000000..7195a5e4e646 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementApiDeletedEventData.java @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.APIDeleted event. + */ +@Immutable +public final class ApiManagementApiDeletedEventData implements JsonSerializable { + /* + * The fully qualified ID of the resource that the compliance state change is for, including the resource name and + * resource type. Uses the format, + * `/subscriptions//resourceGroups//Microsoft.ApiManagement/service//< + * ResourceType>/` + */ + @Generated + private String resourceUri; + + /** + * Creates an instance of ApiManagementApiDeletedEventData class. + */ + @Generated + private ApiManagementApiDeletedEventData() { + } + + /** + * Get the resourceUri property: The fully qualified ID of the resource that the compliance state change is for, + * including the resource name and resource type. Uses the format, + * `/subscriptions/<SubscriptionID>/resourceGroups/<ResourceGroup>/Microsoft.ApiManagement/service/<ServiceName>/<ResourceType>/<ResourceName>`. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiManagementApiDeletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiManagementApiDeletedEventData 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 ApiManagementApiDeletedEventData. + */ + @Generated + public static ApiManagementApiDeletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ApiManagementApiDeletedEventData deserializedApiManagementApiDeletedEventData + = new ApiManagementApiDeletedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceUri".equals(fieldName)) { + deserializedApiManagementApiDeletedEventData.resourceUri = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedApiManagementApiDeletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementApiReleaseCreatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementApiReleaseCreatedEventData.java new file mode 100644 index 000000000000..2f2e298140b4 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementApiReleaseCreatedEventData.java @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.APIReleaseCreated event. + */ +@Immutable +public final class ApiManagementApiReleaseCreatedEventData + implements JsonSerializable { + /* + * The fully qualified ID of the resource that the compliance state change is for, including the resource name and + * resource type. Uses the format, + * `/subscriptions//resourceGroups//Microsoft.ApiManagement/service//< + * ResourceType>/` + */ + @Generated + private String resourceUri; + + /** + * Creates an instance of ApiManagementApiReleaseCreatedEventData class. + */ + @Generated + private ApiManagementApiReleaseCreatedEventData() { + } + + /** + * Get the resourceUri property: The fully qualified ID of the resource that the compliance state change is for, + * including the resource name and resource type. Uses the format, + * `/subscriptions/<SubscriptionID>/resourceGroups/<ResourceGroup>/Microsoft.ApiManagement/service/<ServiceName>/<ResourceType>/<ResourceName>`. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiManagementApiReleaseCreatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiManagementApiReleaseCreatedEventData 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 ApiManagementApiReleaseCreatedEventData. + */ + @Generated + public static ApiManagementApiReleaseCreatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ApiManagementApiReleaseCreatedEventData deserializedApiManagementApiReleaseCreatedEventData + = new ApiManagementApiReleaseCreatedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceUri".equals(fieldName)) { + deserializedApiManagementApiReleaseCreatedEventData.resourceUri = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedApiManagementApiReleaseCreatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementApiReleaseDeletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementApiReleaseDeletedEventData.java new file mode 100644 index 000000000000..42b308fbd505 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementApiReleaseDeletedEventData.java @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.APIReleaseDeleted event. + */ +@Immutable +public final class ApiManagementApiReleaseDeletedEventData + implements JsonSerializable { + /* + * The fully qualified ID of the resource that the compliance state change is for, including the resource name and + * resource type. Uses the format, + * `/subscriptions//resourceGroups//Microsoft.ApiManagement/service//< + * ResourceType>/` + */ + @Generated + private String resourceUri; + + /** + * Creates an instance of ApiManagementApiReleaseDeletedEventData class. + */ + @Generated + private ApiManagementApiReleaseDeletedEventData() { + } + + /** + * Get the resourceUri property: The fully qualified ID of the resource that the compliance state change is for, + * including the resource name and resource type. Uses the format, + * `/subscriptions/<SubscriptionID>/resourceGroups/<ResourceGroup>/Microsoft.ApiManagement/service/<ServiceName>/<ResourceType>/<ResourceName>`. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiManagementApiReleaseDeletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiManagementApiReleaseDeletedEventData 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 ApiManagementApiReleaseDeletedEventData. + */ + @Generated + public static ApiManagementApiReleaseDeletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ApiManagementApiReleaseDeletedEventData deserializedApiManagementApiReleaseDeletedEventData + = new ApiManagementApiReleaseDeletedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceUri".equals(fieldName)) { + deserializedApiManagementApiReleaseDeletedEventData.resourceUri = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedApiManagementApiReleaseDeletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementApiReleaseUpdatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementApiReleaseUpdatedEventData.java new file mode 100644 index 000000000000..4be54a1471f5 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementApiReleaseUpdatedEventData.java @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.APIReleaseUpdated event. + */ +@Immutable +public final class ApiManagementApiReleaseUpdatedEventData + implements JsonSerializable { + /* + * The fully qualified ID of the resource that the compliance state change is for, including the resource name and + * resource type. Uses the format, + * `/subscriptions//resourceGroups//Microsoft.ApiManagement/service//< + * ResourceType>/` + */ + @Generated + private String resourceUri; + + /** + * Creates an instance of ApiManagementApiReleaseUpdatedEventData class. + */ + @Generated + private ApiManagementApiReleaseUpdatedEventData() { + } + + /** + * Get the resourceUri property: The fully qualified ID of the resource that the compliance state change is for, + * including the resource name and resource type. Uses the format, + * `/subscriptions/<SubscriptionID>/resourceGroups/<ResourceGroup>/Microsoft.ApiManagement/service/<ServiceName>/<ResourceType>/<ResourceName>`. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiManagementApiReleaseUpdatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiManagementApiReleaseUpdatedEventData 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 ApiManagementApiReleaseUpdatedEventData. + */ + @Generated + public static ApiManagementApiReleaseUpdatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ApiManagementApiReleaseUpdatedEventData deserializedApiManagementApiReleaseUpdatedEventData + = new ApiManagementApiReleaseUpdatedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceUri".equals(fieldName)) { + deserializedApiManagementApiReleaseUpdatedEventData.resourceUri = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedApiManagementApiReleaseUpdatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementApiUpdatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementApiUpdatedEventData.java new file mode 100644 index 000000000000..cd9190c9a7b5 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementApiUpdatedEventData.java @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.APIUpdated event. + */ +@Immutable +public final class ApiManagementApiUpdatedEventData implements JsonSerializable { + /* + * The fully qualified ID of the resource that the compliance state change is for, including the resource name and + * resource type. Uses the format, + * `/subscriptions//resourceGroups//Microsoft.ApiManagement/service//< + * ResourceType>/` + */ + @Generated + private String resourceUri; + + /** + * Creates an instance of ApiManagementApiUpdatedEventData class. + */ + @Generated + private ApiManagementApiUpdatedEventData() { + } + + /** + * Get the resourceUri property: The fully qualified ID of the resource that the compliance state change is for, + * including the resource name and resource type. Uses the format, + * `/subscriptions/<SubscriptionID>/resourceGroups/<ResourceGroup>/Microsoft.ApiManagement/service/<ServiceName>/<ResourceType>/<ResourceName>`. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiManagementApiUpdatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiManagementApiUpdatedEventData 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 ApiManagementApiUpdatedEventData. + */ + @Generated + public static ApiManagementApiUpdatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ApiManagementApiUpdatedEventData deserializedApiManagementApiUpdatedEventData + = new ApiManagementApiUpdatedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceUri".equals(fieldName)) { + deserializedApiManagementApiUpdatedEventData.resourceUri = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedApiManagementApiUpdatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayApiAddedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayApiAddedEventData.java new file mode 100644 index 000000000000..0b1bea5c7abd --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayApiAddedEventData.java @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.GatewayAPIAdded event. + */ +@Immutable +public final class ApiManagementGatewayApiAddedEventData + implements JsonSerializable { + /* + * The fully qualified ID of the resource that the compliance state change is for, including the resource name and + * resource type. Uses the format, + * `/subscriptions//resourceGroups//Microsoft.ApiManagement/service// + * gateways//apis/` + */ + @Generated + private String resourceUri; + + /** + * Creates an instance of ApiManagementGatewayApiAddedEventData class. + */ + @Generated + private ApiManagementGatewayApiAddedEventData() { + } + + /** + * Get the resourceUri property: The fully qualified ID of the resource that the compliance state change is for, + * including the resource name and resource type. Uses the format, + * `/subscriptions/<SubscriptionID>/resourceGroups/<ResourceGroup>/Microsoft.ApiManagement/service/<ServiceName>/gateways/<GatewayName>/apis/<ResourceName>`. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiManagementGatewayApiAddedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiManagementGatewayApiAddedEventData 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 ApiManagementGatewayApiAddedEventData. + */ + @Generated + public static ApiManagementGatewayApiAddedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ApiManagementGatewayApiAddedEventData deserializedApiManagementGatewayApiAddedEventData + = new ApiManagementGatewayApiAddedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceUri".equals(fieldName)) { + deserializedApiManagementGatewayApiAddedEventData.resourceUri = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedApiManagementGatewayApiAddedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayApiRemovedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayApiRemovedEventData.java new file mode 100644 index 000000000000..7ff99f4a1cef --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayApiRemovedEventData.java @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.GatewayAPIRemoved event. + */ +@Immutable +public final class ApiManagementGatewayApiRemovedEventData + implements JsonSerializable { + /* + * The fully qualified ID of the resource that the compliance state change is for, including the resource name and + * resource type. Uses the format, + * `/subscriptions//resourceGroups//Microsoft.ApiManagement/service// + * gateways//apis/` + */ + @Generated + private String resourceUri; + + /** + * Creates an instance of ApiManagementGatewayApiRemovedEventData class. + */ + @Generated + private ApiManagementGatewayApiRemovedEventData() { + } + + /** + * Get the resourceUri property: The fully qualified ID of the resource that the compliance state change is for, + * including the resource name and resource type. Uses the format, + * `/subscriptions/<SubscriptionID>/resourceGroups/<ResourceGroup>/Microsoft.ApiManagement/service/<ServiceName>/gateways/<GatewayName>/apis/<ResourceName>`. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiManagementGatewayApiRemovedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiManagementGatewayApiRemovedEventData 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 ApiManagementGatewayApiRemovedEventData. + */ + @Generated + public static ApiManagementGatewayApiRemovedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ApiManagementGatewayApiRemovedEventData deserializedApiManagementGatewayApiRemovedEventData + = new ApiManagementGatewayApiRemovedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceUri".equals(fieldName)) { + deserializedApiManagementGatewayApiRemovedEventData.resourceUri = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedApiManagementGatewayApiRemovedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayCertificateAuthorityCreatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayCertificateAuthorityCreatedEventData.java new file mode 100644 index 000000000000..050c8639ed88 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayCertificateAuthorityCreatedEventData.java @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.GatewayCertificateAuthorityCreated + * event. + */ +@Immutable +public final class ApiManagementGatewayCertificateAuthorityCreatedEventData + implements JsonSerializable { + /* + * The fully qualified ID of the resource that the compliance state change is for, including the resource name and + * resource type. Uses the format, + * `/subscriptions//resourceGroups//Microsoft.ApiManagement/service// + * gateways//certificateAuthorities/` + */ + @Generated + private String resourceUri; + + /** + * Creates an instance of ApiManagementGatewayCertificateAuthorityCreatedEventData class. + */ + @Generated + private ApiManagementGatewayCertificateAuthorityCreatedEventData() { + } + + /** + * Get the resourceUri property: The fully qualified ID of the resource that the compliance state change is for, + * including the resource name and resource type. Uses the format, + * `/subscriptions/<SubscriptionID>/resourceGroups/<ResourceGroup>/Microsoft.ApiManagement/service/<ServiceName>/gateways/<GatewayName>/certificateAuthorities/<ResourceName>`. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiManagementGatewayCertificateAuthorityCreatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiManagementGatewayCertificateAuthorityCreatedEventData 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 + * ApiManagementGatewayCertificateAuthorityCreatedEventData. + */ + @Generated + public static ApiManagementGatewayCertificateAuthorityCreatedEventData fromJson(JsonReader jsonReader) + throws IOException { + return jsonReader.readObject(reader -> { + ApiManagementGatewayCertificateAuthorityCreatedEventData deserializedApiManagementGatewayCertificateAuthorityCreatedEventData + = new ApiManagementGatewayCertificateAuthorityCreatedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceUri".equals(fieldName)) { + deserializedApiManagementGatewayCertificateAuthorityCreatedEventData.resourceUri + = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedApiManagementGatewayCertificateAuthorityCreatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayCertificateAuthorityDeletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayCertificateAuthorityDeletedEventData.java new file mode 100644 index 000000000000..35ca00ef2692 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayCertificateAuthorityDeletedEventData.java @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.GatewayCertificateAuthorityDeleted + * event. + */ +@Immutable +public final class ApiManagementGatewayCertificateAuthorityDeletedEventData + implements JsonSerializable { + /* + * The fully qualified ID of the resource that the compliance state change is for, including the resource name and + * resource type. Uses the format, + * `/subscriptions//resourceGroups//Microsoft.ApiManagement/service// + * gateways//certificateAuthorities/` + */ + @Generated + private String resourceUri; + + /** + * Creates an instance of ApiManagementGatewayCertificateAuthorityDeletedEventData class. + */ + @Generated + private ApiManagementGatewayCertificateAuthorityDeletedEventData() { + } + + /** + * Get the resourceUri property: The fully qualified ID of the resource that the compliance state change is for, + * including the resource name and resource type. Uses the format, + * `/subscriptions/<SubscriptionID>/resourceGroups/<ResourceGroup>/Microsoft.ApiManagement/service/<ServiceName>/gateways/<GatewayName>/certificateAuthorities/<ResourceName>`. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiManagementGatewayCertificateAuthorityDeletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiManagementGatewayCertificateAuthorityDeletedEventData 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 + * ApiManagementGatewayCertificateAuthorityDeletedEventData. + */ + @Generated + public static ApiManagementGatewayCertificateAuthorityDeletedEventData fromJson(JsonReader jsonReader) + throws IOException { + return jsonReader.readObject(reader -> { + ApiManagementGatewayCertificateAuthorityDeletedEventData deserializedApiManagementGatewayCertificateAuthorityDeletedEventData + = new ApiManagementGatewayCertificateAuthorityDeletedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceUri".equals(fieldName)) { + deserializedApiManagementGatewayCertificateAuthorityDeletedEventData.resourceUri + = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedApiManagementGatewayCertificateAuthorityDeletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayCertificateAuthorityUpdatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayCertificateAuthorityUpdatedEventData.java new file mode 100644 index 000000000000..ccb432d8acab --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayCertificateAuthorityUpdatedEventData.java @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.GatewayCertificateAuthorityUpdated + * event. + */ +@Immutable +public final class ApiManagementGatewayCertificateAuthorityUpdatedEventData + implements JsonSerializable { + /* + * The fully qualified ID of the resource that the compliance state change is for, including the resource name and + * resource type. Uses the format, + * `/subscriptions//resourceGroups//Microsoft.ApiManagement/service// + * gateways//certificateAuthorities/` + */ + @Generated + private String resourceUri; + + /** + * Creates an instance of ApiManagementGatewayCertificateAuthorityUpdatedEventData class. + */ + @Generated + private ApiManagementGatewayCertificateAuthorityUpdatedEventData() { + } + + /** + * Get the resourceUri property: The fully qualified ID of the resource that the compliance state change is for, + * including the resource name and resource type. Uses the format, + * `/subscriptions/<SubscriptionID>/resourceGroups/<ResourceGroup>/Microsoft.ApiManagement/service/<ServiceName>/gateways/<GatewayName>/certificateAuthorities/<ResourceName>`. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiManagementGatewayCertificateAuthorityUpdatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiManagementGatewayCertificateAuthorityUpdatedEventData 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 + * ApiManagementGatewayCertificateAuthorityUpdatedEventData. + */ + @Generated + public static ApiManagementGatewayCertificateAuthorityUpdatedEventData fromJson(JsonReader jsonReader) + throws IOException { + return jsonReader.readObject(reader -> { + ApiManagementGatewayCertificateAuthorityUpdatedEventData deserializedApiManagementGatewayCertificateAuthorityUpdatedEventData + = new ApiManagementGatewayCertificateAuthorityUpdatedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceUri".equals(fieldName)) { + deserializedApiManagementGatewayCertificateAuthorityUpdatedEventData.resourceUri + = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedApiManagementGatewayCertificateAuthorityUpdatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayCreatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayCreatedEventData.java new file mode 100644 index 000000000000..b2ff1bea5c49 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayCreatedEventData.java @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.GatewayCreated event. + */ +@Immutable +public final class ApiManagementGatewayCreatedEventData + implements JsonSerializable { + /* + * The fully qualified ID of the resource that the compliance state change is for, including the resource name and + * resource type. Uses the format, + * `/subscriptions//resourceGroups//Microsoft.ApiManagement/service// + * gateways/` + */ + @Generated + private String resourceUri; + + /** + * Creates an instance of ApiManagementGatewayCreatedEventData class. + */ + @Generated + private ApiManagementGatewayCreatedEventData() { + } + + /** + * Get the resourceUri property: The fully qualified ID of the resource that the compliance state change is for, + * including the resource name and resource type. Uses the format, + * `/subscriptions/<SubscriptionID>/resourceGroups/<ResourceGroup>/Microsoft.ApiManagement/service/<ServiceName>/gateways/<ResourceName>`. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiManagementGatewayCreatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiManagementGatewayCreatedEventData 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 ApiManagementGatewayCreatedEventData. + */ + @Generated + public static ApiManagementGatewayCreatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ApiManagementGatewayCreatedEventData deserializedApiManagementGatewayCreatedEventData + = new ApiManagementGatewayCreatedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceUri".equals(fieldName)) { + deserializedApiManagementGatewayCreatedEventData.resourceUri = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedApiManagementGatewayCreatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayDeletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayDeletedEventData.java new file mode 100644 index 000000000000..aaa279c281ce --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayDeletedEventData.java @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.GatewayDeleted event. + */ +@Immutable +public final class ApiManagementGatewayDeletedEventData + implements JsonSerializable { + /* + * The fully qualified ID of the resource that the compliance state change is for, including the resource name and + * resource type. Uses the format, + * `/subscriptions//resourceGroups//Microsoft.ApiManagement/service// + * gateways/` + */ + @Generated + private String resourceUri; + + /** + * Creates an instance of ApiManagementGatewayDeletedEventData class. + */ + @Generated + private ApiManagementGatewayDeletedEventData() { + } + + /** + * Get the resourceUri property: The fully qualified ID of the resource that the compliance state change is for, + * including the resource name and resource type. Uses the format, + * `/subscriptions/<SubscriptionID>/resourceGroups/<ResourceGroup>/Microsoft.ApiManagement/service/<ServiceName>/gateways/<ResourceName>`. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiManagementGatewayDeletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiManagementGatewayDeletedEventData 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 ApiManagementGatewayDeletedEventData. + */ + @Generated + public static ApiManagementGatewayDeletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ApiManagementGatewayDeletedEventData deserializedApiManagementGatewayDeletedEventData + = new ApiManagementGatewayDeletedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceUri".equals(fieldName)) { + deserializedApiManagementGatewayDeletedEventData.resourceUri = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedApiManagementGatewayDeletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayHostnameConfigurationCreatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayHostnameConfigurationCreatedEventData.java new file mode 100644 index 000000000000..140b983934e6 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayHostnameConfigurationCreatedEventData.java @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.GatewayHostnameConfigurationCreated + * event. + */ +@Immutable +public final class ApiManagementGatewayHostnameConfigurationCreatedEventData + implements JsonSerializable { + /* + * The fully qualified ID of the resource that the compliance state change is for, including the resource name and + * resource type. Uses the format, + * `/subscriptions//resourceGroups//Microsoft.ApiManagement/service// + * gateways//hostnameConfigurations/` + */ + @Generated + private String resourceUri; + + /** + * Creates an instance of ApiManagementGatewayHostnameConfigurationCreatedEventData class. + */ + @Generated + private ApiManagementGatewayHostnameConfigurationCreatedEventData() { + } + + /** + * Get the resourceUri property: The fully qualified ID of the resource that the compliance state change is for, + * including the resource name and resource type. Uses the format, + * `/subscriptions/<SubscriptionID>/resourceGroups/<ResourceGroup>/Microsoft.ApiManagement/service/<ServiceName>/gateways/<GatewayName>/hostnameConfigurations/<ResourceName>`. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiManagementGatewayHostnameConfigurationCreatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiManagementGatewayHostnameConfigurationCreatedEventData 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 + * ApiManagementGatewayHostnameConfigurationCreatedEventData. + */ + @Generated + public static ApiManagementGatewayHostnameConfigurationCreatedEventData fromJson(JsonReader jsonReader) + throws IOException { + return jsonReader.readObject(reader -> { + ApiManagementGatewayHostnameConfigurationCreatedEventData deserializedApiManagementGatewayHostnameConfigurationCreatedEventData + = new ApiManagementGatewayHostnameConfigurationCreatedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceUri".equals(fieldName)) { + deserializedApiManagementGatewayHostnameConfigurationCreatedEventData.resourceUri + = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedApiManagementGatewayHostnameConfigurationCreatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayHostnameConfigurationDeletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayHostnameConfigurationDeletedEventData.java new file mode 100644 index 000000000000..111e9987fe75 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayHostnameConfigurationDeletedEventData.java @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.GatewayHostnameConfigurationDeleted + * event. + */ +@Immutable +public final class ApiManagementGatewayHostnameConfigurationDeletedEventData + implements JsonSerializable { + /* + * The fully qualified ID of the resource that the compliance state change is for, including the resource name and + * resource type. Uses the format, + * `/subscriptions//resourceGroups//Microsoft.ApiManagement/service// + * gateways//hostnameConfigurations/` + */ + @Generated + private String resourceUri; + + /** + * Creates an instance of ApiManagementGatewayHostnameConfigurationDeletedEventData class. + */ + @Generated + private ApiManagementGatewayHostnameConfigurationDeletedEventData() { + } + + /** + * Get the resourceUri property: The fully qualified ID of the resource that the compliance state change is for, + * including the resource name and resource type. Uses the format, + * `/subscriptions/<SubscriptionID>/resourceGroups/<ResourceGroup>/Microsoft.ApiManagement/service/<ServiceName>/gateways/<GatewayName>/hostnameConfigurations/<ResourceName>`. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiManagementGatewayHostnameConfigurationDeletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiManagementGatewayHostnameConfigurationDeletedEventData 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 + * ApiManagementGatewayHostnameConfigurationDeletedEventData. + */ + @Generated + public static ApiManagementGatewayHostnameConfigurationDeletedEventData fromJson(JsonReader jsonReader) + throws IOException { + return jsonReader.readObject(reader -> { + ApiManagementGatewayHostnameConfigurationDeletedEventData deserializedApiManagementGatewayHostnameConfigurationDeletedEventData + = new ApiManagementGatewayHostnameConfigurationDeletedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceUri".equals(fieldName)) { + deserializedApiManagementGatewayHostnameConfigurationDeletedEventData.resourceUri + = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedApiManagementGatewayHostnameConfigurationDeletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayHostnameConfigurationUpdatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayHostnameConfigurationUpdatedEventData.java new file mode 100644 index 000000000000..2a84f3b6a8cc --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayHostnameConfigurationUpdatedEventData.java @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.GatewayHostnameConfigurationUpdated + * event. + */ +@Immutable +public final class ApiManagementGatewayHostnameConfigurationUpdatedEventData + implements JsonSerializable { + /* + * The fully qualified ID of the resource that the compliance state change is for, including the resource name and + * resource type. Uses the format, + * `/subscriptions//resourceGroups//Microsoft.ApiManagement/service// + * gateways//hostnameConfigurations/` + */ + @Generated + private String resourceUri; + + /** + * Creates an instance of ApiManagementGatewayHostnameConfigurationUpdatedEventData class. + */ + @Generated + private ApiManagementGatewayHostnameConfigurationUpdatedEventData() { + } + + /** + * Get the resourceUri property: The fully qualified ID of the resource that the compliance state change is for, + * including the resource name and resource type. Uses the format, + * `/subscriptions/<SubscriptionID>/resourceGroups/<ResourceGroup>/Microsoft.ApiManagement/service/<ServiceName>/gateways/<GatewayName>/hostnameConfigurations/<ResourceName>`. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiManagementGatewayHostnameConfigurationUpdatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiManagementGatewayHostnameConfigurationUpdatedEventData 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 + * ApiManagementGatewayHostnameConfigurationUpdatedEventData. + */ + @Generated + public static ApiManagementGatewayHostnameConfigurationUpdatedEventData fromJson(JsonReader jsonReader) + throws IOException { + return jsonReader.readObject(reader -> { + ApiManagementGatewayHostnameConfigurationUpdatedEventData deserializedApiManagementGatewayHostnameConfigurationUpdatedEventData + = new ApiManagementGatewayHostnameConfigurationUpdatedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceUri".equals(fieldName)) { + deserializedApiManagementGatewayHostnameConfigurationUpdatedEventData.resourceUri + = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedApiManagementGatewayHostnameConfigurationUpdatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayUpdatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayUpdatedEventData.java new file mode 100644 index 000000000000..df9db8f79f24 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementGatewayUpdatedEventData.java @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.GatewayUpdated event. + */ +@Immutable +public final class ApiManagementGatewayUpdatedEventData + implements JsonSerializable { + /* + * The fully qualified ID of the resource that the compliance state change is for, including the resource name and + * resource type. Uses the format, + * `/subscriptions//resourceGroups//Microsoft.ApiManagement/service// + * gateways/` + */ + @Generated + private String resourceUri; + + /** + * Creates an instance of ApiManagementGatewayUpdatedEventData class. + */ + @Generated + private ApiManagementGatewayUpdatedEventData() { + } + + /** + * Get the resourceUri property: The fully qualified ID of the resource that the compliance state change is for, + * including the resource name and resource type. Uses the format, + * `/subscriptions/<SubscriptionID>/resourceGroups/<ResourceGroup>/Microsoft.ApiManagement/service/<ServiceName>/gateways/<ResourceName>`. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiManagementGatewayUpdatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiManagementGatewayUpdatedEventData 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 ApiManagementGatewayUpdatedEventData. + */ + @Generated + public static ApiManagementGatewayUpdatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ApiManagementGatewayUpdatedEventData deserializedApiManagementGatewayUpdatedEventData + = new ApiManagementGatewayUpdatedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceUri".equals(fieldName)) { + deserializedApiManagementGatewayUpdatedEventData.resourceUri = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedApiManagementGatewayUpdatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementProductCreatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementProductCreatedEventData.java new file mode 100644 index 000000000000..0dfca2f62e0f --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementProductCreatedEventData.java @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.ProductCreated event. + */ +@Immutable +public final class ApiManagementProductCreatedEventData + implements JsonSerializable { + /* + * The fully qualified ID of the resource that the compliance state change is for, including the resource name and + * resource type. Uses the format, + * `/subscriptions//resourceGroups//Microsoft.ApiManagement/service//< + * ResourceType>/` + */ + @Generated + private String resourceUri; + + /** + * Creates an instance of ApiManagementProductCreatedEventData class. + */ + @Generated + private ApiManagementProductCreatedEventData() { + } + + /** + * Get the resourceUri property: The fully qualified ID of the resource that the compliance state change is for, + * including the resource name and resource type. Uses the format, + * `/subscriptions/<SubscriptionID>/resourceGroups/<ResourceGroup>/Microsoft.ApiManagement/service/<ServiceName>/<ResourceType>/<ResourceName>`. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiManagementProductCreatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiManagementProductCreatedEventData 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 ApiManagementProductCreatedEventData. + */ + @Generated + public static ApiManagementProductCreatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ApiManagementProductCreatedEventData deserializedApiManagementProductCreatedEventData + = new ApiManagementProductCreatedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceUri".equals(fieldName)) { + deserializedApiManagementProductCreatedEventData.resourceUri = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedApiManagementProductCreatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementProductDeletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementProductDeletedEventData.java new file mode 100644 index 000000000000..49e7f83bc34f --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementProductDeletedEventData.java @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.ProductDeleted event. + */ +@Immutable +public final class ApiManagementProductDeletedEventData + implements JsonSerializable { + /* + * The fully qualified ID of the resource that the compliance state change is for, including the resource name and + * resource type. Uses the format, + * `/subscriptions//resourceGroups//Microsoft.ApiManagement/service//< + * ResourceType>/` + */ + @Generated + private String resourceUri; + + /** + * Creates an instance of ApiManagementProductDeletedEventData class. + */ + @Generated + private ApiManagementProductDeletedEventData() { + } + + /** + * Get the resourceUri property: The fully qualified ID of the resource that the compliance state change is for, + * including the resource name and resource type. Uses the format, + * `/subscriptions/<SubscriptionID>/resourceGroups/<ResourceGroup>/Microsoft.ApiManagement/service/<ServiceName>/<ResourceType>/<ResourceName>`. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiManagementProductDeletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiManagementProductDeletedEventData 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 ApiManagementProductDeletedEventData. + */ + @Generated + public static ApiManagementProductDeletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ApiManagementProductDeletedEventData deserializedApiManagementProductDeletedEventData + = new ApiManagementProductDeletedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceUri".equals(fieldName)) { + deserializedApiManagementProductDeletedEventData.resourceUri = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedApiManagementProductDeletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementProductUpdatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementProductUpdatedEventData.java new file mode 100644 index 000000000000..e155a51e3deb --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementProductUpdatedEventData.java @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.ProductUpdated event. + */ +@Immutable +public final class ApiManagementProductUpdatedEventData + implements JsonSerializable { + /* + * The fully qualified ID of the resource that the compliance state change is for, including the resource name and + * resource type. Uses the format, + * `/subscriptions//resourceGroups//Microsoft.ApiManagement/service//< + * ResourceType>/` + */ + @Generated + private String resourceUri; + + /** + * Creates an instance of ApiManagementProductUpdatedEventData class. + */ + @Generated + private ApiManagementProductUpdatedEventData() { + } + + /** + * Get the resourceUri property: The fully qualified ID of the resource that the compliance state change is for, + * including the resource name and resource type. Uses the format, + * `/subscriptions/<SubscriptionID>/resourceGroups/<ResourceGroup>/Microsoft.ApiManagement/service/<ServiceName>/<ResourceType>/<ResourceName>`. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiManagementProductUpdatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiManagementProductUpdatedEventData 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 ApiManagementProductUpdatedEventData. + */ + @Generated + public static ApiManagementProductUpdatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ApiManagementProductUpdatedEventData deserializedApiManagementProductUpdatedEventData + = new ApiManagementProductUpdatedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceUri".equals(fieldName)) { + deserializedApiManagementProductUpdatedEventData.resourceUri = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedApiManagementProductUpdatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementSubscriptionCreatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementSubscriptionCreatedEventData.java new file mode 100644 index 000000000000..1286c3ad8c17 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementSubscriptionCreatedEventData.java @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.SubscriptionCreated event. + */ +@Immutable +public final class ApiManagementSubscriptionCreatedEventData + implements JsonSerializable { + /* + * The fully qualified ID of the resource that the compliance state change is for, including the resource name and + * resource type. Uses the format, + * `/subscriptions//resourceGroups//Microsoft.ApiManagement/service//< + * ResourceType>/` + */ + @Generated + private String resourceUri; + + /** + * Creates an instance of ApiManagementSubscriptionCreatedEventData class. + */ + @Generated + private ApiManagementSubscriptionCreatedEventData() { + } + + /** + * Get the resourceUri property: The fully qualified ID of the resource that the compliance state change is for, + * including the resource name and resource type. Uses the format, + * `/subscriptions/<SubscriptionID>/resourceGroups/<ResourceGroup>/Microsoft.ApiManagement/service/<ServiceName>/<ResourceType>/<ResourceName>`. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiManagementSubscriptionCreatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiManagementSubscriptionCreatedEventData 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 ApiManagementSubscriptionCreatedEventData. + */ + @Generated + public static ApiManagementSubscriptionCreatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ApiManagementSubscriptionCreatedEventData deserializedApiManagementSubscriptionCreatedEventData + = new ApiManagementSubscriptionCreatedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceUri".equals(fieldName)) { + deserializedApiManagementSubscriptionCreatedEventData.resourceUri = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedApiManagementSubscriptionCreatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementSubscriptionDeletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementSubscriptionDeletedEventData.java new file mode 100644 index 000000000000..aab2f285c60c --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementSubscriptionDeletedEventData.java @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.SubscriptionDeleted event. + */ +@Immutable +public final class ApiManagementSubscriptionDeletedEventData + implements JsonSerializable { + /* + * The fully qualified ID of the resource that the compliance state change is for, including the resource name and + * resource type. Uses the format, + * `/subscriptions//resourceGroups//Microsoft.ApiManagement/service//< + * ResourceType>/` + */ + @Generated + private String resourceUri; + + /** + * Creates an instance of ApiManagementSubscriptionDeletedEventData class. + */ + @Generated + private ApiManagementSubscriptionDeletedEventData() { + } + + /** + * Get the resourceUri property: The fully qualified ID of the resource that the compliance state change is for, + * including the resource name and resource type. Uses the format, + * `/subscriptions/<SubscriptionID>/resourceGroups/<ResourceGroup>/Microsoft.ApiManagement/service/<ServiceName>/<ResourceType>/<ResourceName>`. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiManagementSubscriptionDeletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiManagementSubscriptionDeletedEventData 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 ApiManagementSubscriptionDeletedEventData. + */ + @Generated + public static ApiManagementSubscriptionDeletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ApiManagementSubscriptionDeletedEventData deserializedApiManagementSubscriptionDeletedEventData + = new ApiManagementSubscriptionDeletedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceUri".equals(fieldName)) { + deserializedApiManagementSubscriptionDeletedEventData.resourceUri = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedApiManagementSubscriptionDeletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementSubscriptionUpdatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementSubscriptionUpdatedEventData.java new file mode 100644 index 000000000000..90d04ea9e11d --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementSubscriptionUpdatedEventData.java @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.SubscriptionUpdated event. + */ +@Immutable +public final class ApiManagementSubscriptionUpdatedEventData + implements JsonSerializable { + /* + * The fully qualified ID of the resource that the compliance state change is for, including the resource name and + * resource type. Uses the format, + * `/subscriptions//resourceGroups//Microsoft.ApiManagement/service//< + * ResourceType>/` + */ + @Generated + private String resourceUri; + + /** + * Creates an instance of ApiManagementSubscriptionUpdatedEventData class. + */ + @Generated + private ApiManagementSubscriptionUpdatedEventData() { + } + + /** + * Get the resourceUri property: The fully qualified ID of the resource that the compliance state change is for, + * including the resource name and resource type. Uses the format, + * `/subscriptions/<SubscriptionID>/resourceGroups/<ResourceGroup>/Microsoft.ApiManagement/service/<ServiceName>/<ResourceType>/<ResourceName>`. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiManagementSubscriptionUpdatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiManagementSubscriptionUpdatedEventData 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 ApiManagementSubscriptionUpdatedEventData. + */ + @Generated + public static ApiManagementSubscriptionUpdatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ApiManagementSubscriptionUpdatedEventData deserializedApiManagementSubscriptionUpdatedEventData + = new ApiManagementSubscriptionUpdatedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceUri".equals(fieldName)) { + deserializedApiManagementSubscriptionUpdatedEventData.resourceUri = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedApiManagementSubscriptionUpdatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementUserCreatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementUserCreatedEventData.java new file mode 100644 index 000000000000..b4dd24b8183b --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementUserCreatedEventData.java @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.UserCreated event. + */ +@Immutable +public final class ApiManagementUserCreatedEventData implements JsonSerializable { + /* + * The fully qualified ID of the resource that the compliance state change is for, including the resource name and + * resource type. Uses the format, + * `/subscriptions//resourceGroups//Microsoft.ApiManagement/service//< + * ResourceType>/` + */ + @Generated + private String resourceUri; + + /** + * Creates an instance of ApiManagementUserCreatedEventData class. + */ + @Generated + private ApiManagementUserCreatedEventData() { + } + + /** + * Get the resourceUri property: The fully qualified ID of the resource that the compliance state change is for, + * including the resource name and resource type. Uses the format, + * `/subscriptions/<SubscriptionID>/resourceGroups/<ResourceGroup>/Microsoft.ApiManagement/service/<ServiceName>/<ResourceType>/<ResourceName>`. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiManagementUserCreatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiManagementUserCreatedEventData 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 ApiManagementUserCreatedEventData. + */ + @Generated + public static ApiManagementUserCreatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ApiManagementUserCreatedEventData deserializedApiManagementUserCreatedEventData + = new ApiManagementUserCreatedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceUri".equals(fieldName)) { + deserializedApiManagementUserCreatedEventData.resourceUri = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedApiManagementUserCreatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementUserDeletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementUserDeletedEventData.java new file mode 100644 index 000000000000..b16353a4038a --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementUserDeletedEventData.java @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.UserDeleted event. + */ +@Immutable +public final class ApiManagementUserDeletedEventData implements JsonSerializable { + /* + * The fully qualified ID of the resource that the compliance state change is for, including the resource name and + * resource type. Uses the format, + * `/subscriptions//resourceGroups//Microsoft.ApiManagement/service//< + * ResourceType>/` + */ + @Generated + private String resourceUri; + + /** + * Creates an instance of ApiManagementUserDeletedEventData class. + */ + @Generated + private ApiManagementUserDeletedEventData() { + } + + /** + * Get the resourceUri property: The fully qualified ID of the resource that the compliance state change is for, + * including the resource name and resource type. Uses the format, + * `/subscriptions/<SubscriptionID>/resourceGroups/<ResourceGroup>/Microsoft.ApiManagement/service/<ServiceName>/<ResourceType>/<ResourceName>`. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiManagementUserDeletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiManagementUserDeletedEventData 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 ApiManagementUserDeletedEventData. + */ + @Generated + public static ApiManagementUserDeletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ApiManagementUserDeletedEventData deserializedApiManagementUserDeletedEventData + = new ApiManagementUserDeletedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceUri".equals(fieldName)) { + deserializedApiManagementUserDeletedEventData.resourceUri = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedApiManagementUserDeletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementUserUpdatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementUserUpdatedEventData.java new file mode 100644 index 000000000000..6c5db7ec6e8f --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ApiManagementUserUpdatedEventData.java @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ApiManagement.UserUpdated event. + */ +@Immutable +public final class ApiManagementUserUpdatedEventData implements JsonSerializable { + /* + * The fully qualified ID of the resource that the compliance state change is for, including the resource name and + * resource type. Uses the format, + * `/subscriptions//resourceGroups//Microsoft.ApiManagement/service//< + * ResourceType>/` + */ + @Generated + private String resourceUri; + + /** + * Creates an instance of ApiManagementUserUpdatedEventData class. + */ + @Generated + private ApiManagementUserUpdatedEventData() { + } + + /** + * Get the resourceUri property: The fully qualified ID of the resource that the compliance state change is for, + * including the resource name and resource type. Uses the format, + * `/subscriptions/<SubscriptionID>/resourceGroups/<ResourceGroup>/Microsoft.ApiManagement/service/<ServiceName>/<ResourceType>/<ResourceName>`. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiManagementUserUpdatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiManagementUserUpdatedEventData 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 ApiManagementUserUpdatedEventData. + */ + @Generated + public static ApiManagementUserUpdatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ApiManagementUserUpdatedEventData deserializedApiManagementUserUpdatedEventData + = new ApiManagementUserUpdatedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceUri".equals(fieldName)) { + deserializedApiManagementUserUpdatedEventData.resourceUri = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedApiManagementUserUpdatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AppAction.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AppAction.java new file mode 100644 index 000000000000..f3204e2ca4d6 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AppAction.java @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Type of action of the operation. + */ +public final class AppAction extends ExpandableStringEnum { + /** + * Web app was restarted. + */ + @Generated + public static final AppAction RESTARTED = fromString("Restarted"); + + /** + * Web app was stopped. + */ + @Generated + public static final AppAction STOPPED = fromString("Stopped"); + + /** + * There was an operation to change app setting on the web app. + */ + @Generated + public static final AppAction CHANGED_APP_SETTINGS = fromString("ChangedAppSettings"); + + /** + * The job has started. + */ + @Generated + public static final AppAction STARTED = fromString("Started"); + + /** + * The job has completed. + */ + @Generated + public static final AppAction COMPLETED = fromString("Completed"); + + /** + * The job has failed to complete. + */ + @Generated + public static final AppAction FAILED = fromString("Failed"); + + /** + * Creates a new instance of AppAction value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public AppAction() { + } + + /** + * Creates or finds a AppAction from its string representation. + * + * @param name a name to look for. + * @return the corresponding AppAction. + */ + @Generated + public static AppAction fromString(String name) { + return fromString(name, AppAction.class); + } + + /** + * Gets known AppAction values. + * + * @return known AppAction values. + */ + @Generated + public static Collection values() { + return values(AppAction.class); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AppConfigurationKeyValueDeletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AppConfigurationKeyValueDeletedEventData.java new file mode 100644 index 000000000000..a28a4a4432da --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AppConfigurationKeyValueDeletedEventData.java @@ -0,0 +1,139 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.AppConfiguration.KeyValueDeleted event. + */ +@Immutable +public final class AppConfigurationKeyValueDeletedEventData + implements JsonSerializable { + /* + * The key used to identify the key-value that was deleted. + */ + @Generated + private String key; + + /* + * The label, if any, used to identify the key-value that was deleted. + */ + @Generated + private String label; + + /* + * The etag representing the key-value that was deleted. + */ + @Generated + private String etag; + + /* + * The sync token representing the server state after the event. + */ + @Generated + private String syncToken; + + /** + * Creates an instance of AppConfigurationKeyValueDeletedEventData class. + */ + @Generated + private AppConfigurationKeyValueDeletedEventData() { + } + + /** + * Get the key property: The key used to identify the key-value that was deleted. + * + * @return the key value. + */ + @Generated + public String getKey() { + return this.key; + } + + /** + * Get the label property: The label, if any, used to identify the key-value that was deleted. + * + * @return the label value. + */ + @Generated + public String getLabel() { + return this.label; + } + + /** + * Get the etag property: The etag representing the key-value that was deleted. + * + * @return the etag value. + */ + @Generated + public String getEtag() { + return this.etag; + } + + /** + * Get the syncToken property: The sync token representing the server state after the event. + * + * @return the syncToken value. + */ + @Generated + public String getSyncToken() { + return this.syncToken; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("key", this.key); + jsonWriter.writeStringField("label", this.label); + jsonWriter.writeStringField("etag", this.etag); + jsonWriter.writeStringField("syncToken", this.syncToken); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AppConfigurationKeyValueDeletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AppConfigurationKeyValueDeletedEventData 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 AppConfigurationKeyValueDeletedEventData. + */ + @Generated + public static AppConfigurationKeyValueDeletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AppConfigurationKeyValueDeletedEventData deserializedAppConfigurationKeyValueDeletedEventData + = new AppConfigurationKeyValueDeletedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("key".equals(fieldName)) { + deserializedAppConfigurationKeyValueDeletedEventData.key = reader.getString(); + } else if ("label".equals(fieldName)) { + deserializedAppConfigurationKeyValueDeletedEventData.label = reader.getString(); + } else if ("etag".equals(fieldName)) { + deserializedAppConfigurationKeyValueDeletedEventData.etag = reader.getString(); + } else if ("syncToken".equals(fieldName)) { + deserializedAppConfigurationKeyValueDeletedEventData.syncToken = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAppConfigurationKeyValueDeletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AppConfigurationKeyValueModifiedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AppConfigurationKeyValueModifiedEventData.java new file mode 100644 index 000000000000..c98f57ba8e95 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AppConfigurationKeyValueModifiedEventData.java @@ -0,0 +1,139 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.AppConfiguration.KeyValueModified event. + */ +@Immutable +public final class AppConfigurationKeyValueModifiedEventData + implements JsonSerializable { + /* + * The key used to identify the key-value that was modified. + */ + @Generated + private String key; + + /* + * The label, if any, used to identify the key-value that was modified. + */ + @Generated + private String label; + + /* + * The etag representing the new state of the key-value. + */ + @Generated + private String etag; + + /* + * The sync token representing the server state after the event. + */ + @Generated + private String syncToken; + + /** + * Creates an instance of AppConfigurationKeyValueModifiedEventData class. + */ + @Generated + private AppConfigurationKeyValueModifiedEventData() { + } + + /** + * Get the key property: The key used to identify the key-value that was modified. + * + * @return the key value. + */ + @Generated + public String getKey() { + return this.key; + } + + /** + * Get the label property: The label, if any, used to identify the key-value that was modified. + * + * @return the label value. + */ + @Generated + public String getLabel() { + return this.label; + } + + /** + * Get the etag property: The etag representing the new state of the key-value. + * + * @return the etag value. + */ + @Generated + public String getEtag() { + return this.etag; + } + + /** + * Get the syncToken property: The sync token representing the server state after the event. + * + * @return the syncToken value. + */ + @Generated + public String getSyncToken() { + return this.syncToken; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("key", this.key); + jsonWriter.writeStringField("label", this.label); + jsonWriter.writeStringField("etag", this.etag); + jsonWriter.writeStringField("syncToken", this.syncToken); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AppConfigurationKeyValueModifiedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AppConfigurationKeyValueModifiedEventData 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 AppConfigurationKeyValueModifiedEventData. + */ + @Generated + public static AppConfigurationKeyValueModifiedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AppConfigurationKeyValueModifiedEventData deserializedAppConfigurationKeyValueModifiedEventData + = new AppConfigurationKeyValueModifiedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("key".equals(fieldName)) { + deserializedAppConfigurationKeyValueModifiedEventData.key = reader.getString(); + } else if ("label".equals(fieldName)) { + deserializedAppConfigurationKeyValueModifiedEventData.label = reader.getString(); + } else if ("etag".equals(fieldName)) { + deserializedAppConfigurationKeyValueModifiedEventData.etag = reader.getString(); + } else if ("syncToken".equals(fieldName)) { + deserializedAppConfigurationKeyValueModifiedEventData.syncToken = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAppConfigurationKeyValueModifiedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AppConfigurationSnapshotCreatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AppConfigurationSnapshotCreatedEventData.java new file mode 100644 index 000000000000..4afe078de4b2 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AppConfigurationSnapshotCreatedEventData.java @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.AppConfiguration.SnapshotCreated event. + */ +@Immutable +public final class AppConfigurationSnapshotCreatedEventData extends AppConfigurationSnapshotEventData { + /* + * The sync token representing the server state after the event. + */ + @Generated + private String syncToken; + + /* + * The etag representing the new state of the snapshot. + */ + @Generated + private String etag; + + /* + * The name of the snapshot. + */ + @Generated + private String name; + + /** + * Creates an instance of AppConfigurationSnapshotCreatedEventData class. + */ + @Generated + private AppConfigurationSnapshotCreatedEventData() { + } + + /** + * Get the syncToken property: The sync token representing the server state after the event. + * + * @return the syncToken value. + */ + @Generated + @Override + public String getSyncToken() { + return this.syncToken; + } + + /** + * Get the etag property: The etag representing the new state of the snapshot. + * + * @return the etag value. + */ + @Generated + @Override + public String getEtag() { + return this.etag; + } + + /** + * Get the name property: The name of the snapshot. + * + * @return the name value. + */ + @Generated + @Override + public String getName() { + return this.name; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("name", getName()); + jsonWriter.writeStringField("etag", getEtag()); + jsonWriter.writeStringField("syncToken", getSyncToken()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AppConfigurationSnapshotCreatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AppConfigurationSnapshotCreatedEventData 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 AppConfigurationSnapshotCreatedEventData. + */ + @Generated + public static AppConfigurationSnapshotCreatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AppConfigurationSnapshotCreatedEventData deserializedAppConfigurationSnapshotCreatedEventData + = new AppConfigurationSnapshotCreatedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("name".equals(fieldName)) { + deserializedAppConfigurationSnapshotCreatedEventData.name = reader.getString(); + } else if ("etag".equals(fieldName)) { + deserializedAppConfigurationSnapshotCreatedEventData.etag = reader.getString(); + } else if ("syncToken".equals(fieldName)) { + deserializedAppConfigurationSnapshotCreatedEventData.syncToken = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAppConfigurationSnapshotCreatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AppConfigurationSnapshotEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AppConfigurationSnapshotEventData.java new file mode 100644 index 000000000000..59067035f131 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AppConfigurationSnapshotEventData.java @@ -0,0 +1,155 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of common properties of snapshot events. + */ +@Immutable +public class AppConfigurationSnapshotEventData implements JsonSerializable { + /* + * The name of the snapshot. + */ + @Generated + private String name; + + /* + * The etag representing the new state of the snapshot. + */ + @Generated + private String etag; + + /* + * The sync token representing the server state after the event. + */ + @Generated + private String syncToken; + + /** + * Creates an instance of AppConfigurationSnapshotEventData class. + */ + @Generated + protected AppConfigurationSnapshotEventData() { + } + + /** + * Get the name property: The name of the snapshot. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Set the name property: The name of the snapshot. + * + * @param name the name value to set. + * @return the AppConfigurationSnapshotEventData object itself. + */ + @Generated + AppConfigurationSnapshotEventData setName(String name) { + this.name = name; + return this; + } + + /** + * Get the etag property: The etag representing the new state of the snapshot. + * + * @return the etag value. + */ + @Generated + public String getEtag() { + return this.etag; + } + + /** + * Set the etag property: The etag representing the new state of the snapshot. + * + * @param etag the etag value to set. + * @return the AppConfigurationSnapshotEventData object itself. + */ + @Generated + AppConfigurationSnapshotEventData setEtag(String etag) { + this.etag = etag; + return this; + } + + /** + * Get the syncToken property: The sync token representing the server state after the event. + * + * @return the syncToken value. + */ + @Generated + public String getSyncToken() { + return this.syncToken; + } + + /** + * Set the syncToken property: The sync token representing the server state after the event. + * + * @param syncToken the syncToken value to set. + * @return the AppConfigurationSnapshotEventData object itself. + */ + @Generated + AppConfigurationSnapshotEventData setSyncToken(String syncToken) { + this.syncToken = syncToken; + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("etag", this.etag); + jsonWriter.writeStringField("syncToken", this.syncToken); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AppConfigurationSnapshotEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AppConfigurationSnapshotEventData 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 AppConfigurationSnapshotEventData. + */ + @Generated + public static AppConfigurationSnapshotEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AppConfigurationSnapshotEventData deserializedAppConfigurationSnapshotEventData + = new AppConfigurationSnapshotEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("name".equals(fieldName)) { + deserializedAppConfigurationSnapshotEventData.name = reader.getString(); + } else if ("etag".equals(fieldName)) { + deserializedAppConfigurationSnapshotEventData.etag = reader.getString(); + } else if ("syncToken".equals(fieldName)) { + deserializedAppConfigurationSnapshotEventData.syncToken = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAppConfigurationSnapshotEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AppConfigurationSnapshotModifiedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AppConfigurationSnapshotModifiedEventData.java new file mode 100644 index 000000000000..0218ea69896f --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AppConfigurationSnapshotModifiedEventData.java @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.AppConfiguration.SnapshotModified event. + */ +@Immutable +public final class AppConfigurationSnapshotModifiedEventData extends AppConfigurationSnapshotEventData { + /* + * The sync token representing the server state after the event. + */ + @Generated + private String syncToken; + + /* + * The etag representing the new state of the snapshot. + */ + @Generated + private String etag; + + /* + * The name of the snapshot. + */ + @Generated + private String name; + + /** + * Creates an instance of AppConfigurationSnapshotModifiedEventData class. + */ + @Generated + private AppConfigurationSnapshotModifiedEventData() { + } + + /** + * Get the syncToken property: The sync token representing the server state after the event. + * + * @return the syncToken value. + */ + @Generated + @Override + public String getSyncToken() { + return this.syncToken; + } + + /** + * Get the etag property: The etag representing the new state of the snapshot. + * + * @return the etag value. + */ + @Generated + @Override + public String getEtag() { + return this.etag; + } + + /** + * Get the name property: The name of the snapshot. + * + * @return the name value. + */ + @Generated + @Override + public String getName() { + return this.name; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("name", getName()); + jsonWriter.writeStringField("etag", getEtag()); + jsonWriter.writeStringField("syncToken", getSyncToken()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AppConfigurationSnapshotModifiedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AppConfigurationSnapshotModifiedEventData 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 AppConfigurationSnapshotModifiedEventData. + */ + @Generated + public static AppConfigurationSnapshotModifiedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AppConfigurationSnapshotModifiedEventData deserializedAppConfigurationSnapshotModifiedEventData + = new AppConfigurationSnapshotModifiedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("name".equals(fieldName)) { + deserializedAppConfigurationSnapshotModifiedEventData.name = reader.getString(); + } else if ("etag".equals(fieldName)) { + deserializedAppConfigurationSnapshotModifiedEventData.etag = reader.getString(); + } else if ("syncToken".equals(fieldName)) { + deserializedAppConfigurationSnapshotModifiedEventData.syncToken = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAppConfigurationSnapshotModifiedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AppEventTypeDetail.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AppEventTypeDetail.java new file mode 100644 index 000000000000..c5e6b9a608ea --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AppEventTypeDetail.java @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Detail of action on the app. + */ +@Immutable +public final class AppEventTypeDetail implements JsonSerializable { + /* + * Type of action of the operation. + */ + @Generated + private final AppAction action; + + /** + * Creates an instance of AppEventTypeDetail class. + * + * @param action the action value to set. + */ + @Generated + private AppEventTypeDetail(AppAction action) { + this.action = action; + } + + /** + * Get the action property: Type of action of the operation. + * + * @return the action value. + */ + @Generated + public AppAction getAction() { + return this.action; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("action", this.action == null ? null : this.action.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AppEventTypeDetail from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AppEventTypeDetail 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 AppEventTypeDetail. + */ + @Generated + public static AppEventTypeDetail fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AppAction action = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("action".equals(fieldName)) { + action = AppAction.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + return new AppEventTypeDetail(action); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AppServicePlanAction.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AppServicePlanAction.java new file mode 100644 index 000000000000..d1015b77d89a --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AppServicePlanAction.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Type of action on the app service plan. + */ +public final class AppServicePlanAction extends ExpandableStringEnum { + /** + * App Service plan is being updated. + */ + @Generated + public static final AppServicePlanAction UPDATED = fromString("Updated"); + + /** + * Creates a new instance of AppServicePlanAction value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public AppServicePlanAction() { + } + + /** + * Creates or finds a AppServicePlanAction from its string representation. + * + * @param name a name to look for. + * @return the corresponding AppServicePlanAction. + */ + @Generated + public static AppServicePlanAction fromString(String name) { + return fromString(name, AppServicePlanAction.class); + } + + /** + * Gets known AppServicePlanAction values. + * + * @return known AppServicePlanAction values. + */ + @Generated + public static Collection values() { + return values(AppServicePlanAction.class); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AppServicePlanEventTypeDetail.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AppServicePlanEventTypeDetail.java new file mode 100644 index 000000000000..f9e0a0055cb0 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AppServicePlanEventTypeDetail.java @@ -0,0 +1,127 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Detail of action on the app service plan. + */ +@Immutable +public final class AppServicePlanEventTypeDetail implements JsonSerializable { + /* + * Kind of environment where app service plan is. + */ + @Generated + private final StampKind stampKind; + + /* + * Type of action on the app service plan. + */ + @Generated + private final AppServicePlanAction action; + + /* + * Asynchronous operation status of the operation on the app service plan. + */ + @Generated + private final AsyncStatus status; + + /** + * Creates an instance of AppServicePlanEventTypeDetail class. + * + * @param stampKind the stampKind value to set. + * @param action the action value to set. + * @param status the status value to set. + */ + @Generated + private AppServicePlanEventTypeDetail(StampKind stampKind, AppServicePlanAction action, AsyncStatus status) { + this.stampKind = stampKind; + this.action = action; + this.status = status; + } + + /** + * Get the stampKind property: Kind of environment where app service plan is. + * + * @return the stampKind value. + */ + @Generated + public StampKind getStampKind() { + return this.stampKind; + } + + /** + * Get the action property: Type of action on the app service plan. + * + * @return the action value. + */ + @Generated + public AppServicePlanAction getAction() { + return this.action; + } + + /** + * Get the status property: Asynchronous operation status of the operation on the app service plan. + * + * @return the status value. + */ + @Generated + public AsyncStatus getStatus() { + return this.status; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("stampKind", this.stampKind == null ? null : this.stampKind.toString()); + jsonWriter.writeStringField("action", this.action == null ? null : this.action.toString()); + jsonWriter.writeStringField("status", this.status == null ? null : this.status.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AppServicePlanEventTypeDetail from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AppServicePlanEventTypeDetail 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 AppServicePlanEventTypeDetail. + */ + @Generated + public static AppServicePlanEventTypeDetail fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + StampKind stampKind = null; + AppServicePlanAction action = null; + AsyncStatus status = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("stampKind".equals(fieldName)) { + stampKind = StampKind.fromString(reader.getString()); + } else if ("action".equals(fieldName)) { + action = AppServicePlanAction.fromString(reader.getString()); + } else if ("status".equals(fieldName)) { + status = AsyncStatus.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + return new AppServicePlanEventTypeDetail(stampKind, action, status); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AsyncStatus.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AsyncStatus.java new file mode 100644 index 000000000000..79826876cd11 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AsyncStatus.java @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Asynchronous operation status of the operation on the app service plan. + */ +public final class AsyncStatus extends ExpandableStringEnum { + /** + * Async operation has started. + */ + @Generated + public static final AsyncStatus STARTED = fromString("Started"); + + /** + * Async operation has completed. + */ + @Generated + public static final AsyncStatus COMPLETED = fromString("Completed"); + + /** + * Async operation failed to complete. + */ + @Generated + public static final AsyncStatus FAILED = fromString("Failed"); + + /** + * Creates a new instance of AsyncStatus value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public AsyncStatus() { + } + + /** + * Creates or finds a AsyncStatus from its string representation. + * + * @param name a name to look for. + * @return the corresponding AsyncStatus. + */ + @Generated + public static AsyncStatus fromString(String name) { + return fromString(name, AsyncStatus.class); + } + + /** + * Gets known AsyncStatus values. + * + * @return known AsyncStatus values. + */ + @Generated + public static Collection values() { + return values(AsyncStatus.class); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsClusterCreatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsClusterCreatedEventData.java new file mode 100644 index 000000000000..154f2fd2ecfc --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsClusterCreatedEventData.java @@ -0,0 +1,139 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.List; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.AVS.ClusterCreated event. + */ +@Immutable +public final class AvsClusterCreatedEventData extends AvsClusterEventData { + /* + * Hosts in Maintenance mode in the cluster, if any. + */ + @Generated + private List inMaintenanceHostNames; + + /* + * Hosts removed from the cluster in this event, if any. + */ + @Generated + private List removedHostNames; + + /* + * Hosts added to the cluster in this event, if any. + */ + @Generated + private List addedHostNames; + + /** + * Creates an instance of AvsClusterCreatedEventData class. + * + * @param operationId the operationId value to set. + */ + @Generated + private AvsClusterCreatedEventData(String operationId) { + super(operationId); + } + + /** + * Get the inMaintenanceHostNames property: Hosts in Maintenance mode in the cluster, if any. + * + * @return the inMaintenanceHostNames value. + */ + @Generated + @Override + public List getInMaintenanceHostNames() { + return this.inMaintenanceHostNames; + } + + /** + * Get the removedHostNames property: Hosts removed from the cluster in this event, if any. + * + * @return the removedHostNames value. + */ + @Generated + @Override + public List getRemovedHostNames() { + return this.removedHostNames; + } + + /** + * Get the addedHostNames property: Hosts added to the cluster in this event, if any. + * + * @return the addedHostNames value. + */ + @Generated + @Override + public List getAddedHostNames() { + return this.addedHostNames; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("operationId", getOperationId()); + jsonWriter.writeArrayField("addedHostNames", getAddedHostNames(), + (writer, element) -> writer.writeString(element)); + jsonWriter.writeArrayField("removedHostNames", getRemovedHostNames(), + (writer, element) -> writer.writeString(element)); + jsonWriter.writeArrayField("inMaintenanceHostNames", getInMaintenanceHostNames(), + (writer, element) -> writer.writeString(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AvsClusterCreatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AvsClusterCreatedEventData 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 AvsClusterCreatedEventData. + */ + @Generated + public static AvsClusterCreatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String operationId = null; + List addedHostNames = null; + List removedHostNames = null; + List inMaintenanceHostNames = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("operationId".equals(fieldName)) { + operationId = reader.getString(); + } else if ("addedHostNames".equals(fieldName)) { + addedHostNames = reader.readArray(reader1 -> reader1.getString()); + } else if ("removedHostNames".equals(fieldName)) { + removedHostNames = reader.readArray(reader1 -> reader1.getString()); + } else if ("inMaintenanceHostNames".equals(fieldName)) { + inMaintenanceHostNames = reader.readArray(reader1 -> reader1.getString()); + } else { + reader.skipChildren(); + } + } + AvsClusterCreatedEventData deserializedAvsClusterCreatedEventData + = new AvsClusterCreatedEventData(operationId); + deserializedAvsClusterCreatedEventData.addedHostNames = addedHostNames; + deserializedAvsClusterCreatedEventData.removedHostNames = removedHostNames; + deserializedAvsClusterCreatedEventData.inMaintenanceHostNames = inMaintenanceHostNames; + + return deserializedAvsClusterCreatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsClusterDeletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsClusterDeletedEventData.java new file mode 100644 index 000000000000..793ba9b08006 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsClusterDeletedEventData.java @@ -0,0 +1,139 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.List; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.AVS.ClusterDeleted event. + */ +@Immutable +public final class AvsClusterDeletedEventData extends AvsClusterEventData { + /* + * Hosts in Maintenance mode in the cluster, if any. + */ + @Generated + private List inMaintenanceHostNames; + + /* + * Hosts removed from the cluster in this event, if any. + */ + @Generated + private List removedHostNames; + + /* + * Hosts added to the cluster in this event, if any. + */ + @Generated + private List addedHostNames; + + /** + * Creates an instance of AvsClusterDeletedEventData class. + * + * @param operationId the operationId value to set. + */ + @Generated + private AvsClusterDeletedEventData(String operationId) { + super(operationId); + } + + /** + * Get the inMaintenanceHostNames property: Hosts in Maintenance mode in the cluster, if any. + * + * @return the inMaintenanceHostNames value. + */ + @Generated + @Override + public List getInMaintenanceHostNames() { + return this.inMaintenanceHostNames; + } + + /** + * Get the removedHostNames property: Hosts removed from the cluster in this event, if any. + * + * @return the removedHostNames value. + */ + @Generated + @Override + public List getRemovedHostNames() { + return this.removedHostNames; + } + + /** + * Get the addedHostNames property: Hosts added to the cluster in this event, if any. + * + * @return the addedHostNames value. + */ + @Generated + @Override + public List getAddedHostNames() { + return this.addedHostNames; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("operationId", getOperationId()); + jsonWriter.writeArrayField("addedHostNames", getAddedHostNames(), + (writer, element) -> writer.writeString(element)); + jsonWriter.writeArrayField("removedHostNames", getRemovedHostNames(), + (writer, element) -> writer.writeString(element)); + jsonWriter.writeArrayField("inMaintenanceHostNames", getInMaintenanceHostNames(), + (writer, element) -> writer.writeString(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AvsClusterDeletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AvsClusterDeletedEventData 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 AvsClusterDeletedEventData. + */ + @Generated + public static AvsClusterDeletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String operationId = null; + List addedHostNames = null; + List removedHostNames = null; + List inMaintenanceHostNames = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("operationId".equals(fieldName)) { + operationId = reader.getString(); + } else if ("addedHostNames".equals(fieldName)) { + addedHostNames = reader.readArray(reader1 -> reader1.getString()); + } else if ("removedHostNames".equals(fieldName)) { + removedHostNames = reader.readArray(reader1 -> reader1.getString()); + } else if ("inMaintenanceHostNames".equals(fieldName)) { + inMaintenanceHostNames = reader.readArray(reader1 -> reader1.getString()); + } else { + reader.skipChildren(); + } + } + AvsClusterDeletedEventData deserializedAvsClusterDeletedEventData + = new AvsClusterDeletedEventData(operationId); + deserializedAvsClusterDeletedEventData.addedHostNames = addedHostNames; + deserializedAvsClusterDeletedEventData.removedHostNames = removedHostNames; + deserializedAvsClusterDeletedEventData.inMaintenanceHostNames = inMaintenanceHostNames; + + return deserializedAvsClusterDeletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsClusterEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsClusterEventData.java new file mode 100644 index 000000000000..701dbee8c081 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsClusterEventData.java @@ -0,0 +1,188 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.List; + +/** + * Schema of the Data property of an EventGridEvent for Microsoft.AVS/clusters events. + */ +@Immutable +public class AvsClusterEventData implements JsonSerializable { + /* + * Id of the operation that caused this event. + */ + @Generated + private final String operationId; + + /* + * Hosts added to the cluster in this event, if any. + */ + @Generated + private List addedHostNames; + + /* + * Hosts removed from the cluster in this event, if any. + */ + @Generated + private List removedHostNames; + + /* + * Hosts in Maintenance mode in the cluster, if any. + */ + @Generated + private List inMaintenanceHostNames; + + /** + * Creates an instance of AvsClusterEventData class. + * + * @param operationId the operationId value to set. + */ + @Generated + protected AvsClusterEventData(String operationId) { + this.operationId = operationId; + } + + /** + * Get the operationId property: Id of the operation that caused this event. + * + * @return the operationId value. + */ + @Generated + public String getOperationId() { + return this.operationId; + } + + /** + * Get the addedHostNames property: Hosts added to the cluster in this event, if any. + * + * @return the addedHostNames value. + */ + @Generated + public List getAddedHostNames() { + return this.addedHostNames; + } + + /** + * Set the addedHostNames property: Hosts added to the cluster in this event, if any. + * + * @param addedHostNames the addedHostNames value to set. + * @return the AvsClusterEventData object itself. + */ + @Generated + AvsClusterEventData setAddedHostNames(List addedHostNames) { + this.addedHostNames = addedHostNames; + return this; + } + + /** + * Get the removedHostNames property: Hosts removed from the cluster in this event, if any. + * + * @return the removedHostNames value. + */ + @Generated + public List getRemovedHostNames() { + return this.removedHostNames; + } + + /** + * Set the removedHostNames property: Hosts removed from the cluster in this event, if any. + * + * @param removedHostNames the removedHostNames value to set. + * @return the AvsClusterEventData object itself. + */ + @Generated + AvsClusterEventData setRemovedHostNames(List removedHostNames) { + this.removedHostNames = removedHostNames; + return this; + } + + /** + * Get the inMaintenanceHostNames property: Hosts in Maintenance mode in the cluster, if any. + * + * @return the inMaintenanceHostNames value. + */ + @Generated + public List getInMaintenanceHostNames() { + return this.inMaintenanceHostNames; + } + + /** + * Set the inMaintenanceHostNames property: Hosts in Maintenance mode in the cluster, if any. + * + * @param inMaintenanceHostNames the inMaintenanceHostNames value to set. + * @return the AvsClusterEventData object itself. + */ + @Generated + AvsClusterEventData setInMaintenanceHostNames(List inMaintenanceHostNames) { + this.inMaintenanceHostNames = inMaintenanceHostNames; + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("operationId", this.operationId); + jsonWriter.writeArrayField("addedHostNames", this.addedHostNames, + (writer, element) -> writer.writeString(element)); + jsonWriter.writeArrayField("removedHostNames", this.removedHostNames, + (writer, element) -> writer.writeString(element)); + jsonWriter.writeArrayField("inMaintenanceHostNames", this.inMaintenanceHostNames, + (writer, element) -> writer.writeString(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AvsClusterEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AvsClusterEventData 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 AvsClusterEventData. + */ + @Generated + public static AvsClusterEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String operationId = null; + List addedHostNames = null; + List removedHostNames = null; + List inMaintenanceHostNames = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("operationId".equals(fieldName)) { + operationId = reader.getString(); + } else if ("addedHostNames".equals(fieldName)) { + addedHostNames = reader.readArray(reader1 -> reader1.getString()); + } else if ("removedHostNames".equals(fieldName)) { + removedHostNames = reader.readArray(reader1 -> reader1.getString()); + } else if ("inMaintenanceHostNames".equals(fieldName)) { + inMaintenanceHostNames = reader.readArray(reader1 -> reader1.getString()); + } else { + reader.skipChildren(); + } + } + AvsClusterEventData deserializedAvsClusterEventData = new AvsClusterEventData(operationId); + deserializedAvsClusterEventData.addedHostNames = addedHostNames; + deserializedAvsClusterEventData.removedHostNames = removedHostNames; + deserializedAvsClusterEventData.inMaintenanceHostNames = inMaintenanceHostNames; + + return deserializedAvsClusterEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsClusterFailedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsClusterFailedEventData.java new file mode 100644 index 000000000000..5249363038a8 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsClusterFailedEventData.java @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.List; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.AVS.ClusterFailed event. + */ +@Immutable +public final class AvsClusterFailedEventData extends AvsClusterEventData { + /* + * Failure reason of an event. + */ + @Generated + private String failureMessage; + + /* + * Hosts in Maintenance mode in the cluster, if any. + */ + @Generated + private List inMaintenanceHostNames; + + /* + * Hosts removed from the cluster in this event, if any. + */ + @Generated + private List removedHostNames; + + /* + * Hosts added to the cluster in this event, if any. + */ + @Generated + private List addedHostNames; + + /** + * Creates an instance of AvsClusterFailedEventData class. + * + * @param operationId the operationId value to set. + */ + @Generated + private AvsClusterFailedEventData(String operationId) { + super(operationId); + } + + /** + * Get the failureMessage property: Failure reason of an event. + * + * @return the failureMessage value. + */ + @Generated + public String getFailureMessage() { + return this.failureMessage; + } + + /** + * Get the inMaintenanceHostNames property: Hosts in Maintenance mode in the cluster, if any. + * + * @return the inMaintenanceHostNames value. + */ + @Generated + @Override + public List getInMaintenanceHostNames() { + return this.inMaintenanceHostNames; + } + + /** + * Get the removedHostNames property: Hosts removed from the cluster in this event, if any. + * + * @return the removedHostNames value. + */ + @Generated + @Override + public List getRemovedHostNames() { + return this.removedHostNames; + } + + /** + * Get the addedHostNames property: Hosts added to the cluster in this event, if any. + * + * @return the addedHostNames value. + */ + @Generated + @Override + public List getAddedHostNames() { + return this.addedHostNames; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("operationId", getOperationId()); + jsonWriter.writeArrayField("addedHostNames", getAddedHostNames(), + (writer, element) -> writer.writeString(element)); + jsonWriter.writeArrayField("removedHostNames", getRemovedHostNames(), + (writer, element) -> writer.writeString(element)); + jsonWriter.writeArrayField("inMaintenanceHostNames", getInMaintenanceHostNames(), + (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("failureMessage", this.failureMessage); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AvsClusterFailedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AvsClusterFailedEventData 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 AvsClusterFailedEventData. + */ + @Generated + public static AvsClusterFailedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String operationId = null; + List addedHostNames = null; + List removedHostNames = null; + List inMaintenanceHostNames = null; + String failureMessage = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("operationId".equals(fieldName)) { + operationId = reader.getString(); + } else if ("addedHostNames".equals(fieldName)) { + addedHostNames = reader.readArray(reader1 -> reader1.getString()); + } else if ("removedHostNames".equals(fieldName)) { + removedHostNames = reader.readArray(reader1 -> reader1.getString()); + } else if ("inMaintenanceHostNames".equals(fieldName)) { + inMaintenanceHostNames = reader.readArray(reader1 -> reader1.getString()); + } else if ("failureMessage".equals(fieldName)) { + failureMessage = reader.getString(); + } else { + reader.skipChildren(); + } + } + AvsClusterFailedEventData deserializedAvsClusterFailedEventData + = new AvsClusterFailedEventData(operationId); + deserializedAvsClusterFailedEventData.addedHostNames = addedHostNames; + deserializedAvsClusterFailedEventData.removedHostNames = removedHostNames; + deserializedAvsClusterFailedEventData.inMaintenanceHostNames = inMaintenanceHostNames; + deserializedAvsClusterFailedEventData.failureMessage = failureMessage; + + return deserializedAvsClusterFailedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsClusterUpdatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsClusterUpdatedEventData.java new file mode 100644 index 000000000000..9a059509d5e3 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsClusterUpdatedEventData.java @@ -0,0 +1,139 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.List; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.AVS.ClusterUpdated event. + */ +@Immutable +public final class AvsClusterUpdatedEventData extends AvsClusterEventData { + /* + * Hosts in Maintenance mode in the cluster, if any. + */ + @Generated + private List inMaintenanceHostNames; + + /* + * Hosts removed from the cluster in this event, if any. + */ + @Generated + private List removedHostNames; + + /* + * Hosts added to the cluster in this event, if any. + */ + @Generated + private List addedHostNames; + + /** + * Creates an instance of AvsClusterUpdatedEventData class. + * + * @param operationId the operationId value to set. + */ + @Generated + private AvsClusterUpdatedEventData(String operationId) { + super(operationId); + } + + /** + * Get the inMaintenanceHostNames property: Hosts in Maintenance mode in the cluster, if any. + * + * @return the inMaintenanceHostNames value. + */ + @Generated + @Override + public List getInMaintenanceHostNames() { + return this.inMaintenanceHostNames; + } + + /** + * Get the removedHostNames property: Hosts removed from the cluster in this event, if any. + * + * @return the removedHostNames value. + */ + @Generated + @Override + public List getRemovedHostNames() { + return this.removedHostNames; + } + + /** + * Get the addedHostNames property: Hosts added to the cluster in this event, if any. + * + * @return the addedHostNames value. + */ + @Generated + @Override + public List getAddedHostNames() { + return this.addedHostNames; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("operationId", getOperationId()); + jsonWriter.writeArrayField("addedHostNames", getAddedHostNames(), + (writer, element) -> writer.writeString(element)); + jsonWriter.writeArrayField("removedHostNames", getRemovedHostNames(), + (writer, element) -> writer.writeString(element)); + jsonWriter.writeArrayField("inMaintenanceHostNames", getInMaintenanceHostNames(), + (writer, element) -> writer.writeString(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AvsClusterUpdatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AvsClusterUpdatedEventData 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 AvsClusterUpdatedEventData. + */ + @Generated + public static AvsClusterUpdatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String operationId = null; + List addedHostNames = null; + List removedHostNames = null; + List inMaintenanceHostNames = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("operationId".equals(fieldName)) { + operationId = reader.getString(); + } else if ("addedHostNames".equals(fieldName)) { + addedHostNames = reader.readArray(reader1 -> reader1.getString()); + } else if ("removedHostNames".equals(fieldName)) { + removedHostNames = reader.readArray(reader1 -> reader1.getString()); + } else if ("inMaintenanceHostNames".equals(fieldName)) { + inMaintenanceHostNames = reader.readArray(reader1 -> reader1.getString()); + } else { + reader.skipChildren(); + } + } + AvsClusterUpdatedEventData deserializedAvsClusterUpdatedEventData + = new AvsClusterUpdatedEventData(operationId); + deserializedAvsClusterUpdatedEventData.addedHostNames = addedHostNames; + deserializedAvsClusterUpdatedEventData.removedHostNames = removedHostNames; + deserializedAvsClusterUpdatedEventData.inMaintenanceHostNames = inMaintenanceHostNames; + + return deserializedAvsClusterUpdatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsClusterUpdatingEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsClusterUpdatingEventData.java new file mode 100644 index 000000000000..83766758e562 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsClusterUpdatingEventData.java @@ -0,0 +1,139 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.List; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.AVS.ClusterUpdating event. + */ +@Immutable +public final class AvsClusterUpdatingEventData extends AvsClusterEventData { + /* + * Hosts in Maintenance mode in the cluster, if any. + */ + @Generated + private List inMaintenanceHostNames; + + /* + * Hosts removed from the cluster in this event, if any. + */ + @Generated + private List removedHostNames; + + /* + * Hosts added to the cluster in this event, if any. + */ + @Generated + private List addedHostNames; + + /** + * Creates an instance of AvsClusterUpdatingEventData class. + * + * @param operationId the operationId value to set. + */ + @Generated + private AvsClusterUpdatingEventData(String operationId) { + super(operationId); + } + + /** + * Get the inMaintenanceHostNames property: Hosts in Maintenance mode in the cluster, if any. + * + * @return the inMaintenanceHostNames value. + */ + @Generated + @Override + public List getInMaintenanceHostNames() { + return this.inMaintenanceHostNames; + } + + /** + * Get the removedHostNames property: Hosts removed from the cluster in this event, if any. + * + * @return the removedHostNames value. + */ + @Generated + @Override + public List getRemovedHostNames() { + return this.removedHostNames; + } + + /** + * Get the addedHostNames property: Hosts added to the cluster in this event, if any. + * + * @return the addedHostNames value. + */ + @Generated + @Override + public List getAddedHostNames() { + return this.addedHostNames; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("operationId", getOperationId()); + jsonWriter.writeArrayField("addedHostNames", getAddedHostNames(), + (writer, element) -> writer.writeString(element)); + jsonWriter.writeArrayField("removedHostNames", getRemovedHostNames(), + (writer, element) -> writer.writeString(element)); + jsonWriter.writeArrayField("inMaintenanceHostNames", getInMaintenanceHostNames(), + (writer, element) -> writer.writeString(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AvsClusterUpdatingEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AvsClusterUpdatingEventData 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 AvsClusterUpdatingEventData. + */ + @Generated + public static AvsClusterUpdatingEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String operationId = null; + List addedHostNames = null; + List removedHostNames = null; + List inMaintenanceHostNames = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("operationId".equals(fieldName)) { + operationId = reader.getString(); + } else if ("addedHostNames".equals(fieldName)) { + addedHostNames = reader.readArray(reader1 -> reader1.getString()); + } else if ("removedHostNames".equals(fieldName)) { + removedHostNames = reader.readArray(reader1 -> reader1.getString()); + } else if ("inMaintenanceHostNames".equals(fieldName)) { + inMaintenanceHostNames = reader.readArray(reader1 -> reader1.getString()); + } else { + reader.skipChildren(); + } + } + AvsClusterUpdatingEventData deserializedAvsClusterUpdatingEventData + = new AvsClusterUpdatingEventData(operationId); + deserializedAvsClusterUpdatingEventData.addedHostNames = addedHostNames; + deserializedAvsClusterUpdatingEventData.removedHostNames = removedHostNames; + deserializedAvsClusterUpdatingEventData.inMaintenanceHostNames = inMaintenanceHostNames; + + return deserializedAvsClusterUpdatingEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsPrivateCloudEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsPrivateCloudEventData.java new file mode 100644 index 000000000000..d6b4a80562a9 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsPrivateCloudEventData.java @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for Microsoft.AVS/privateClouds events. + */ +@Immutable +public class AvsPrivateCloudEventData implements JsonSerializable { + /* + * Id of the operation that caused this event. + */ + @Generated + private final String operationId; + + /** + * Creates an instance of AvsPrivateCloudEventData class. + * + * @param operationId the operationId value to set. + */ + @Generated + protected AvsPrivateCloudEventData(String operationId) { + this.operationId = operationId; + } + + /** + * Get the operationId property: Id of the operation that caused this event. + * + * @return the operationId value. + */ + @Generated + public String getOperationId() { + return this.operationId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("operationId", this.operationId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AvsPrivateCloudEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AvsPrivateCloudEventData 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 AvsPrivateCloudEventData. + */ + @Generated + public static AvsPrivateCloudEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String operationId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("operationId".equals(fieldName)) { + operationId = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new AvsPrivateCloudEventData(operationId); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsPrivateCloudFailedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsPrivateCloudFailedEventData.java new file mode 100644 index 000000000000..34d4d47174f7 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsPrivateCloudFailedEventData.java @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.AVS.PrivateCloudFailed event. + */ +@Immutable +public final class AvsPrivateCloudFailedEventData extends AvsPrivateCloudEventData { + /* + * Failure reason of an event. + */ + @Generated + private String failureMessage; + + /** + * Creates an instance of AvsPrivateCloudFailedEventData class. + * + * @param operationId the operationId value to set. + */ + @Generated + private AvsPrivateCloudFailedEventData(String operationId) { + super(operationId); + } + + /** + * Get the failureMessage property: Failure reason of an event. + * + * @return the failureMessage value. + */ + @Generated + public String getFailureMessage() { + return this.failureMessage; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("operationId", getOperationId()); + jsonWriter.writeStringField("failureMessage", this.failureMessage); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AvsPrivateCloudFailedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AvsPrivateCloudFailedEventData 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 AvsPrivateCloudFailedEventData. + */ + @Generated + public static AvsPrivateCloudFailedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String operationId = null; + String failureMessage = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("operationId".equals(fieldName)) { + operationId = reader.getString(); + } else if ("failureMessage".equals(fieldName)) { + failureMessage = reader.getString(); + } else { + reader.skipChildren(); + } + } + AvsPrivateCloudFailedEventData deserializedAvsPrivateCloudFailedEventData + = new AvsPrivateCloudFailedEventData(operationId); + deserializedAvsPrivateCloudFailedEventData.failureMessage = failureMessage; + + return deserializedAvsPrivateCloudFailedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsPrivateCloudUpdatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsPrivateCloudUpdatedEventData.java new file mode 100644 index 000000000000..3eb23d49405d --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsPrivateCloudUpdatedEventData.java @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.AVS.PrivateCloudUpdated event. + */ +@Immutable +public final class AvsPrivateCloudUpdatedEventData extends AvsPrivateCloudEventData { + /** + * Creates an instance of AvsPrivateCloudUpdatedEventData class. + * + * @param operationId the operationId value to set. + */ + @Generated + private AvsPrivateCloudUpdatedEventData(String operationId) { + super(operationId); + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("operationId", getOperationId()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AvsPrivateCloudUpdatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AvsPrivateCloudUpdatedEventData 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 AvsPrivateCloudUpdatedEventData. + */ + @Generated + public static AvsPrivateCloudUpdatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String operationId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("operationId".equals(fieldName)) { + operationId = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new AvsPrivateCloudUpdatedEventData(operationId); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsPrivateCloudUpdatingEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsPrivateCloudUpdatingEventData.java new file mode 100644 index 000000000000..754de87604f2 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsPrivateCloudUpdatingEventData.java @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.AVS.PrivateCloudUpdating event. + */ +@Immutable +public final class AvsPrivateCloudUpdatingEventData extends AvsPrivateCloudEventData { + /** + * Creates an instance of AvsPrivateCloudUpdatingEventData class. + * + * @param operationId the operationId value to set. + */ + @Generated + private AvsPrivateCloudUpdatingEventData(String operationId) { + super(operationId); + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("operationId", getOperationId()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AvsPrivateCloudUpdatingEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AvsPrivateCloudUpdatingEventData 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 AvsPrivateCloudUpdatingEventData. + */ + @Generated + public static AvsPrivateCloudUpdatingEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String operationId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("operationId".equals(fieldName)) { + operationId = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new AvsPrivateCloudUpdatingEventData(operationId); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsScriptExecutionCancelledEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsScriptExecutionCancelledEventData.java new file mode 100644 index 000000000000..10a80819e149 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsScriptExecutionCancelledEventData.java @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.List; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.AVS.ScriptExecutionCancelled event. + */ +@Immutable +public final class AvsScriptExecutionCancelledEventData extends AvsScriptExecutionEventData { + /* + * Stdout outputs from the execution, if any. + */ + @Generated + private List output; + + /** + * Creates an instance of AvsScriptExecutionCancelledEventData class. + * + * @param operationId the operationId value to set. + * @param cmdletId the cmdletId value to set. + */ + @Generated + private AvsScriptExecutionCancelledEventData(String operationId, String cmdletId) { + super(operationId, cmdletId); + } + + /** + * Get the output property: Stdout outputs from the execution, if any. + * + * @return the output value. + */ + @Generated + @Override + public List getOutput() { + return this.output; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("operationId", getOperationId()); + jsonWriter.writeStringField("cmdletId", getCmdletId()); + jsonWriter.writeArrayField("output", getOutput(), (writer, element) -> writer.writeString(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AvsScriptExecutionCancelledEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AvsScriptExecutionCancelledEventData 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 AvsScriptExecutionCancelledEventData. + */ + @Generated + public static AvsScriptExecutionCancelledEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String operationId = null; + String cmdletId = null; + List output = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("operationId".equals(fieldName)) { + operationId = reader.getString(); + } else if ("cmdletId".equals(fieldName)) { + cmdletId = reader.getString(); + } else if ("output".equals(fieldName)) { + output = reader.readArray(reader1 -> reader1.getString()); + } else { + reader.skipChildren(); + } + } + AvsScriptExecutionCancelledEventData deserializedAvsScriptExecutionCancelledEventData + = new AvsScriptExecutionCancelledEventData(operationId, cmdletId); + deserializedAvsScriptExecutionCancelledEventData.output = output; + + return deserializedAvsScriptExecutionCancelledEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsScriptExecutionEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsScriptExecutionEventData.java new file mode 100644 index 000000000000..84072a16452a --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsScriptExecutionEventData.java @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.List; + +/** + * Schema of the Data property of an EventGridEvent for Microsoft.AVS/scriptExecutions events. + */ +@Immutable +public class AvsScriptExecutionEventData implements JsonSerializable { + /* + * Id of the operation that caused this event. + */ + @Generated + private final String operationId; + + /* + * Cmdlet referenced in the execution that caused this event. + */ + @Generated + private final String cmdletId; + + /* + * Stdout outputs from the execution, if any. + */ + @Generated + private List output; + + /** + * Creates an instance of AvsScriptExecutionEventData class. + * + * @param operationId the operationId value to set. + * @param cmdletId the cmdletId value to set. + */ + @Generated + protected AvsScriptExecutionEventData(String operationId, String cmdletId) { + this.operationId = operationId; + this.cmdletId = cmdletId; + } + + /** + * Get the operationId property: Id of the operation that caused this event. + * + * @return the operationId value. + */ + @Generated + public String getOperationId() { + return this.operationId; + } + + /** + * Get the cmdletId property: Cmdlet referenced in the execution that caused this event. + * + * @return the cmdletId value. + */ + @Generated + public String getCmdletId() { + return this.cmdletId; + } + + /** + * Get the output property: Stdout outputs from the execution, if any. + * + * @return the output value. + */ + @Generated + public List getOutput() { + return this.output; + } + + /** + * Set the output property: Stdout outputs from the execution, if any. + * + * @param output the output value to set. + * @return the AvsScriptExecutionEventData object itself. + */ + @Generated + AvsScriptExecutionEventData setOutput(List output) { + this.output = output; + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("operationId", this.operationId); + jsonWriter.writeStringField("cmdletId", this.cmdletId); + jsonWriter.writeArrayField("output", this.output, (writer, element) -> writer.writeString(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AvsScriptExecutionEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AvsScriptExecutionEventData 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 AvsScriptExecutionEventData. + */ + @Generated + public static AvsScriptExecutionEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String operationId = null; + String cmdletId = null; + List output = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("operationId".equals(fieldName)) { + operationId = reader.getString(); + } else if ("cmdletId".equals(fieldName)) { + cmdletId = reader.getString(); + } else if ("output".equals(fieldName)) { + output = reader.readArray(reader1 -> reader1.getString()); + } else { + reader.skipChildren(); + } + } + AvsScriptExecutionEventData deserializedAvsScriptExecutionEventData + = new AvsScriptExecutionEventData(operationId, cmdletId); + deserializedAvsScriptExecutionEventData.output = output; + + return deserializedAvsScriptExecutionEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsScriptExecutionFailedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsScriptExecutionFailedEventData.java new file mode 100644 index 000000000000..67efb0e91354 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsScriptExecutionFailedEventData.java @@ -0,0 +1,118 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.List; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.AVS.ScriptExecutionFailed event. + */ +@Immutable +public final class AvsScriptExecutionFailedEventData extends AvsScriptExecutionEventData { + /* + * Failure reason of an event. + */ + @Generated + private String failureMessage; + + /* + * Stdout outputs from the execution, if any. + */ + @Generated + private List output; + + /** + * Creates an instance of AvsScriptExecutionFailedEventData class. + * + * @param operationId the operationId value to set. + * @param cmdletId the cmdletId value to set. + */ + @Generated + private AvsScriptExecutionFailedEventData(String operationId, String cmdletId) { + super(operationId, cmdletId); + } + + /** + * Get the failureMessage property: Failure reason of an event. + * + * @return the failureMessage value. + */ + @Generated + public String getFailureMessage() { + return this.failureMessage; + } + + /** + * Get the output property: Stdout outputs from the execution, if any. + * + * @return the output value. + */ + @Generated + @Override + public List getOutput() { + return this.output; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("operationId", getOperationId()); + jsonWriter.writeStringField("cmdletId", getCmdletId()); + jsonWriter.writeArrayField("output", getOutput(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("failureMessage", this.failureMessage); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AvsScriptExecutionFailedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AvsScriptExecutionFailedEventData 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 AvsScriptExecutionFailedEventData. + */ + @Generated + public static AvsScriptExecutionFailedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String operationId = null; + String cmdletId = null; + List output = null; + String failureMessage = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("operationId".equals(fieldName)) { + operationId = reader.getString(); + } else if ("cmdletId".equals(fieldName)) { + cmdletId = reader.getString(); + } else if ("output".equals(fieldName)) { + output = reader.readArray(reader1 -> reader1.getString()); + } else if ("failureMessage".equals(fieldName)) { + failureMessage = reader.getString(); + } else { + reader.skipChildren(); + } + } + AvsScriptExecutionFailedEventData deserializedAvsScriptExecutionFailedEventData + = new AvsScriptExecutionFailedEventData(operationId, cmdletId); + deserializedAvsScriptExecutionFailedEventData.output = output; + deserializedAvsScriptExecutionFailedEventData.failureMessage = failureMessage; + + return deserializedAvsScriptExecutionFailedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsScriptExecutionFinishedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsScriptExecutionFinishedEventData.java new file mode 100644 index 000000000000..d6e9c7affdc6 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsScriptExecutionFinishedEventData.java @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.List; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.AVS.ScriptExecutionFinished event. + */ +@Immutable +public final class AvsScriptExecutionFinishedEventData extends AvsScriptExecutionEventData { + /* + * Named outputs of completed execution, if any. + */ + @Generated + private final Map namedOutputs; + + /* + * Stdout outputs from the execution, if any. + */ + @Generated + private List output; + + /** + * Creates an instance of AvsScriptExecutionFinishedEventData class. + * + * @param operationId the operationId value to set. + * @param cmdletId the cmdletId value to set. + * @param namedOutputs the namedOutputs value to set. + */ + @Generated + private AvsScriptExecutionFinishedEventData(String operationId, String cmdletId, Map namedOutputs) { + super(operationId, cmdletId); + this.namedOutputs = namedOutputs; + } + + /** + * Get the namedOutputs property: Named outputs of completed execution, if any. + * + * @return the namedOutputs value. + */ + @Generated + public Map getNamedOutputs() { + return this.namedOutputs; + } + + /** + * Get the output property: Stdout outputs from the execution, if any. + * + * @return the output value. + */ + @Generated + @Override + public List getOutput() { + return this.output; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("operationId", getOperationId()); + jsonWriter.writeStringField("cmdletId", getCmdletId()); + jsonWriter.writeArrayField("output", getOutput(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeMapField("namedOutputs", this.namedOutputs, (writer, element) -> writer.writeString(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AvsScriptExecutionFinishedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AvsScriptExecutionFinishedEventData 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 AvsScriptExecutionFinishedEventData. + */ + @Generated + public static AvsScriptExecutionFinishedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String operationId = null; + String cmdletId = null; + List output = null; + Map namedOutputs = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("operationId".equals(fieldName)) { + operationId = reader.getString(); + } else if ("cmdletId".equals(fieldName)) { + cmdletId = reader.getString(); + } else if ("output".equals(fieldName)) { + output = reader.readArray(reader1 -> reader1.getString()); + } else if ("namedOutputs".equals(fieldName)) { + namedOutputs = reader.readMap(reader1 -> reader1.getString()); + } else { + reader.skipChildren(); + } + } + AvsScriptExecutionFinishedEventData deserializedAvsScriptExecutionFinishedEventData + = new AvsScriptExecutionFinishedEventData(operationId, cmdletId, namedOutputs); + deserializedAvsScriptExecutionFinishedEventData.output = output; + + return deserializedAvsScriptExecutionFinishedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsScriptExecutionStartedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsScriptExecutionStartedEventData.java new file mode 100644 index 000000000000..5bc14500e88e --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/AvsScriptExecutionStartedEventData.java @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.List; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.AVS.ScriptExecutionStarted event. + */ +@Immutable +public final class AvsScriptExecutionStartedEventData extends AvsScriptExecutionEventData { + /* + * Stdout outputs from the execution, if any. + */ + @Generated + private List output; + + /** + * Creates an instance of AvsScriptExecutionStartedEventData class. + * + * @param operationId the operationId value to set. + * @param cmdletId the cmdletId value to set. + */ + @Generated + private AvsScriptExecutionStartedEventData(String operationId, String cmdletId) { + super(operationId, cmdletId); + } + + /** + * Get the output property: Stdout outputs from the execution, if any. + * + * @return the output value. + */ + @Generated + @Override + public List getOutput() { + return this.output; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("operationId", getOperationId()); + jsonWriter.writeStringField("cmdletId", getCmdletId()); + jsonWriter.writeArrayField("output", getOutput(), (writer, element) -> writer.writeString(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AvsScriptExecutionStartedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AvsScriptExecutionStartedEventData 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 AvsScriptExecutionStartedEventData. + */ + @Generated + public static AvsScriptExecutionStartedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String operationId = null; + String cmdletId = null; + List output = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("operationId".equals(fieldName)) { + operationId = reader.getString(); + } else if ("cmdletId".equals(fieldName)) { + cmdletId = reader.getString(); + } else if ("output".equals(fieldName)) { + output = reader.readArray(reader1 -> reader1.getString()); + } else { + reader.skipChildren(); + } + } + AvsScriptExecutionStartedEventData deserializedAvsScriptExecutionStartedEventData + = new AvsScriptExecutionStartedEventData(operationId, cmdletId); + deserializedAvsScriptExecutionStartedEventData.output = output; + + return deserializedAvsScriptExecutionStartedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/CommunicationCloudEnvironmentModel.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/CommunicationCloudEnvironmentModel.java new file mode 100644 index 000000000000..21371222f9d1 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/CommunicationCloudEnvironmentModel.java @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Communication cloud environment model. + */ +public final class CommunicationCloudEnvironmentModel extends ExpandableStringEnum { + /** + * Public. + */ + @Generated + public static final CommunicationCloudEnvironmentModel PUBLIC = fromString("public"); + + /** + * Dod. + */ + @Generated + public static final CommunicationCloudEnvironmentModel DOD = fromString("dod"); + + /** + * Gcch. + */ + @Generated + public static final CommunicationCloudEnvironmentModel GCCH = fromString("gcch"); + + /** + * Creates a new instance of CommunicationCloudEnvironmentModel value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public CommunicationCloudEnvironmentModel() { + } + + /** + * Creates or finds a CommunicationCloudEnvironmentModel from its string representation. + * + * @param name a name to look for. + * @return the corresponding CommunicationCloudEnvironmentModel. + */ + @Generated + public static CommunicationCloudEnvironmentModel fromString(String name) { + return fromString(name, CommunicationCloudEnvironmentModel.class); + } + + /** + * Gets known CommunicationCloudEnvironmentModel values. + * + * @return known CommunicationCloudEnvironmentModel values. + */ + @Generated + public static Collection values() { + return values(CommunicationCloudEnvironmentModel.class); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/CommunicationIdentifierKind.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/CommunicationIdentifierKind.java new file mode 100644 index 000000000000..874004927efb --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/CommunicationIdentifierKind.java @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Communication model identifier kind. + */ +public final class CommunicationIdentifierKind extends ExpandableStringEnum { + /** + * Unknown. + */ + @Generated + public static final CommunicationIdentifierKind UNKNOWN = fromString("unknown"); + + /** + * Communication User. + */ + @Generated + public static final CommunicationIdentifierKind COMMUNICATION_USER = fromString("communicationUser"); + + /** + * Phone Number. + */ + @Generated + public static final CommunicationIdentifierKind PHONE_NUMBER = fromString("phoneNumber"); + + /** + * Microsoft Teams User. + */ + @Generated + public static final CommunicationIdentifierKind MICROSOFT_TEAMS_USER = fromString("microsoftTeamsUser"); + + /** + * Creates a new instance of CommunicationIdentifierKind value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public CommunicationIdentifierKind() { + } + + /** + * Creates or finds a CommunicationIdentifierKind from its string representation. + * + * @param name a name to look for. + * @return the corresponding CommunicationIdentifierKind. + */ + @Generated + public static CommunicationIdentifierKind fromString(String name) { + return fromString(name, CommunicationIdentifierKind.class); + } + + /** + * Gets known CommunicationIdentifierKind values. + * + * @return known CommunicationIdentifierKind values. + */ + @Generated + public static Collection values() { + return values(CommunicationIdentifierKind.class); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/CommunicationIdentifierModel.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/CommunicationIdentifierModel.java new file mode 100644 index 000000000000..b28b68ee2f47 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/CommunicationIdentifierModel.java @@ -0,0 +1,199 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Identifies a participant in Azure Communication services. A participant is, for example, a phone number or an Azure + * communication user. This model must be interpreted as a union: Apart from rawId, at most one further property may be + * set. + */ +@Immutable +public final class CommunicationIdentifierModel implements JsonSerializable { + /* + * The identifier kind. Only required in responses. + */ + @Generated + private final CommunicationIdentifierKind kind; + + /* + * Raw Id of the identifier. Optional in requests, required in responses. + */ + @Generated + private String rawId; + + /* + * The communication user. + */ + @Generated + private final CommunicationUserIdentifierModel communicationUser; + + /* + * The phone number. + */ + @Generated + private final PhoneNumberIdentifierModel phoneNumber; + + /* + * The Microsoft Teams user. + */ + @Generated + private final MicrosoftTeamsUserIdentifierModel microsoftTeamsUser; + + /* + * The Microsoft Teams application. + */ + @Generated + private final MicrosoftTeamsAppIdentifier microsoftTeamsApp; + + /** + * Creates an instance of CommunicationIdentifierModel class. + * + * @param kind the kind value to set. + * @param communicationUser the communicationUser value to set. + * @param phoneNumber the phoneNumber value to set. + * @param microsoftTeamsUser the microsoftTeamsUser value to set. + * @param microsoftTeamsApp the microsoftTeamsApp value to set. + */ + @Generated + private CommunicationIdentifierModel(CommunicationIdentifierKind kind, + CommunicationUserIdentifierModel communicationUser, PhoneNumberIdentifierModel phoneNumber, + MicrosoftTeamsUserIdentifierModel microsoftTeamsUser, MicrosoftTeamsAppIdentifier microsoftTeamsApp) { + this.kind = kind; + this.communicationUser = communicationUser; + this.phoneNumber = phoneNumber; + this.microsoftTeamsUser = microsoftTeamsUser; + this.microsoftTeamsApp = microsoftTeamsApp; + } + + /** + * Get the kind property: The identifier kind. Only required in responses. + * + * @return the kind value. + */ + @Generated + public CommunicationIdentifierKind getKind() { + return this.kind; + } + + /** + * Get the rawId property: Raw Id of the identifier. Optional in requests, required in responses. + * + * @return the rawId value. + */ + @Generated + public String getRawId() { + return this.rawId; + } + + /** + * Get the communicationUser property: The communication user. + * + * @return the communicationUser value. + */ + @Generated + public CommunicationUserIdentifierModel getCommunicationUser() { + return this.communicationUser; + } + + /** + * Get the phoneNumber property: The phone number. + * + * @return the phoneNumber value. + */ + @Generated + public PhoneNumberIdentifierModel getPhoneNumber() { + return this.phoneNumber; + } + + /** + * Get the microsoftTeamsUser property: The Microsoft Teams user. + * + * @return the microsoftTeamsUser value. + */ + @Generated + public MicrosoftTeamsUserIdentifierModel getMicrosoftTeamsUser() { + return this.microsoftTeamsUser; + } + + /** + * Get the microsoftTeamsApp property: The Microsoft Teams application. + * + * @return the microsoftTeamsApp value. + */ + @Generated + public MicrosoftTeamsAppIdentifier getMicrosoftTeamsApp() { + return this.microsoftTeamsApp; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString()); + jsonWriter.writeJsonField("communicationUser", this.communicationUser); + jsonWriter.writeJsonField("phoneNumber", this.phoneNumber); + jsonWriter.writeJsonField("microsoftTeamsUser", this.microsoftTeamsUser); + jsonWriter.writeJsonField("microsoftTeamsApp", this.microsoftTeamsApp); + jsonWriter.writeStringField("rawId", this.rawId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of CommunicationIdentifierModel from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of CommunicationIdentifierModel 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 CommunicationIdentifierModel. + */ + @Generated + public static CommunicationIdentifierModel fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CommunicationIdentifierKind kind = null; + CommunicationUserIdentifierModel communicationUser = null; + PhoneNumberIdentifierModel phoneNumber = null; + MicrosoftTeamsUserIdentifierModel microsoftTeamsUser = null; + MicrosoftTeamsAppIdentifier microsoftTeamsApp = null; + String rawId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("kind".equals(fieldName)) { + kind = CommunicationIdentifierKind.fromString(reader.getString()); + } else if ("communicationUser".equals(fieldName)) { + communicationUser = CommunicationUserIdentifierModel.fromJson(reader); + } else if ("phoneNumber".equals(fieldName)) { + phoneNumber = PhoneNumberIdentifierModel.fromJson(reader); + } else if ("microsoftTeamsUser".equals(fieldName)) { + microsoftTeamsUser = MicrosoftTeamsUserIdentifierModel.fromJson(reader); + } else if ("microsoftTeamsApp".equals(fieldName)) { + microsoftTeamsApp = MicrosoftTeamsAppIdentifier.fromJson(reader); + } else if ("rawId".equals(fieldName)) { + rawId = reader.getString(); + } else { + reader.skipChildren(); + } + } + CommunicationIdentifierModel deserializedCommunicationIdentifierModel = new CommunicationIdentifierModel( + kind, communicationUser, phoneNumber, microsoftTeamsUser, microsoftTeamsApp); + deserializedCommunicationIdentifierModel.rawId = rawId; + + return deserializedCommunicationIdentifierModel; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/CommunicationUserIdentifierModel.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/CommunicationUserIdentifierModel.java new file mode 100644 index 000000000000..ca3040be4278 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/CommunicationUserIdentifierModel.java @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * A user that got created with an Azure Communication Services resource. + */ +@Immutable +public final class CommunicationUserIdentifierModel implements JsonSerializable { + /* + * The Id of the communication user. + */ + @Generated + private final String id; + + /** + * Creates an instance of CommunicationUserIdentifierModel class. + * + * @param id the id value to set. + */ + @Generated + private CommunicationUserIdentifierModel(String id) { + this.id = id; + } + + /** + * Get the id property: The Id of the communication user. + * + * @return the id value. + */ + @Generated + public String getId() { + return this.id; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("id", this.id); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of CommunicationUserIdentifierModel from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of CommunicationUserIdentifierModel 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 CommunicationUserIdentifierModel. + */ + @Generated + public static CommunicationUserIdentifierModel fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String id = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + id = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new CommunicationUserIdentifierModel(id); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryArtifactEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryArtifactEventData.java new file mode 100644 index 000000000000..d032b3b65c65 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryArtifactEventData.java @@ -0,0 +1,215 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * The content of the event request message. + */ +@Immutable +public class ContainerRegistryArtifactEventData implements JsonSerializable { + /* + * The event ID. + */ + @Generated + private final String id; + + /* + * The time at which the event occurred. + */ + @Generated + private final OffsetDateTime timestamp; + + /* + * The action that encompasses the provided event. + */ + @Generated + private final String action; + + /* + * The location of the event. + */ + @Generated + private final String location; + + /* + * The target of the event. + */ + @Generated + private final ContainerRegistryArtifactEventTarget target; + + /* + * The connected registry information if the event is generated by a connected registry. + */ + @Generated + private ContainerRegistryEventConnectedRegistry connectedRegistry; + + /** + * Creates an instance of ContainerRegistryArtifactEventData class. + * + * @param id the id value to set. + * @param timestamp the timestamp value to set. + * @param action the action value to set. + * @param location the location value to set. + * @param target the target value to set. + */ + @Generated + protected ContainerRegistryArtifactEventData(String id, OffsetDateTime timestamp, String action, String location, + ContainerRegistryArtifactEventTarget target) { + this.id = id; + this.timestamp = timestamp; + this.action = action; + this.location = location; + this.target = target; + } + + /** + * Get the id property: The event ID. + * + * @return the id value. + */ + @Generated + public String getId() { + return this.id; + } + + /** + * Get the timestamp property: The time at which the event occurred. + * + * @return the timestamp value. + */ + @Generated + public OffsetDateTime getTimestamp() { + return this.timestamp; + } + + /** + * Get the action property: The action that encompasses the provided event. + * + * @return the action value. + */ + @Generated + public String getAction() { + return this.action; + } + + /** + * Get the location property: The location of the event. + * + * @return the location value. + */ + @Generated + public String getLocation() { + return this.location; + } + + /** + * Get the target property: The target of the event. + * + * @return the target value. + */ + @Generated + public ContainerRegistryArtifactEventTarget getTarget() { + return this.target; + } + + /** + * Get the connectedRegistry property: The connected registry information if the event is generated by a connected + * registry. + * + * @return the connectedRegistry value. + */ + @Generated + public ContainerRegistryEventConnectedRegistry getConnectedRegistry() { + return this.connectedRegistry; + } + + /** + * Set the connectedRegistry property: The connected registry information if the event is generated by a connected + * registry. + * + * @param connectedRegistry the connectedRegistry value to set. + * @return the ContainerRegistryArtifactEventData object itself. + */ + @Generated + ContainerRegistryArtifactEventData setConnectedRegistry(ContainerRegistryEventConnectedRegistry connectedRegistry) { + this.connectedRegistry = connectedRegistry; + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("id", this.id); + jsonWriter.writeStringField("timestamp", + this.timestamp == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.timestamp)); + jsonWriter.writeStringField("action", this.action); + jsonWriter.writeStringField("location", this.location); + jsonWriter.writeJsonField("target", this.target); + jsonWriter.writeJsonField("connectedRegistry", this.connectedRegistry); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ContainerRegistryArtifactEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ContainerRegistryArtifactEventData 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 ContainerRegistryArtifactEventData. + */ + @Generated + public static ContainerRegistryArtifactEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String id = null; + OffsetDateTime timestamp = null; + String action = null; + String location = null; + ContainerRegistryArtifactEventTarget target = null; + ContainerRegistryEventConnectedRegistry connectedRegistry = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + id = reader.getString(); + } else if ("timestamp".equals(fieldName)) { + timestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("action".equals(fieldName)) { + action = reader.getString(); + } else if ("location".equals(fieldName)) { + location = reader.getString(); + } else if ("target".equals(fieldName)) { + target = ContainerRegistryArtifactEventTarget.fromJson(reader); + } else if ("connectedRegistry".equals(fieldName)) { + connectedRegistry = ContainerRegistryEventConnectedRegistry.fromJson(reader); + } else { + reader.skipChildren(); + } + } + ContainerRegistryArtifactEventData deserializedContainerRegistryArtifactEventData + = new ContainerRegistryArtifactEventData(id, timestamp, action, location, target); + deserializedContainerRegistryArtifactEventData.connectedRegistry = connectedRegistry; + + return deserializedContainerRegistryArtifactEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryArtifactEventTarget.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryArtifactEventTarget.java new file mode 100644 index 000000000000..32ac4c7a877f --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryArtifactEventTarget.java @@ -0,0 +1,214 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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 target of the event. + */ +@Immutable +public final class ContainerRegistryArtifactEventTarget + implements JsonSerializable { + /* + * The MIME type of the artifact. + */ + @Generated + private final String mediaType; + + /* + * The size in bytes of the artifact. + */ + @Generated + private Long size; + + /* + * The digest of the artifact. + */ + @Generated + private String digest; + + /* + * The repository name of the artifact. + */ + @Generated + private final String repository; + + /* + * The tag of the artifact. + */ + @Generated + private String tag; + + /* + * The name of the artifact. + */ + @Generated + private String name; + + /* + * The version of the artifact. + */ + @Generated + private String version; + + /** + * Creates an instance of ContainerRegistryArtifactEventTarget class. + * + * @param mediaType the mediaType value to set. + * @param repository the repository value to set. + */ + @Generated + private ContainerRegistryArtifactEventTarget(String mediaType, String repository) { + this.mediaType = mediaType; + this.repository = repository; + } + + /** + * Get the mediaType property: The MIME type of the artifact. + * + * @return the mediaType value. + */ + @Generated + public String getMediaType() { + return this.mediaType; + } + + /** + * Get the size property: The size in bytes of the artifact. + * + * @return the size value. + */ + @Generated + public Long getSize() { + return this.size; + } + + /** + * Get the digest property: The digest of the artifact. + * + * @return the digest value. + */ + @Generated + public String getDigest() { + return this.digest; + } + + /** + * Get the repository property: The repository name of the artifact. + * + * @return the repository value. + */ + @Generated + public String getRepository() { + return this.repository; + } + + /** + * Get the tag property: The tag of the artifact. + * + * @return the tag value. + */ + @Generated + public String getTag() { + return this.tag; + } + + /** + * Get the name property: The name of the artifact. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the version property: The version of the artifact. + * + * @return the version value. + */ + @Generated + public String getVersion() { + return this.version; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("mediaType", this.mediaType); + jsonWriter.writeStringField("repository", this.repository); + jsonWriter.writeNumberField("size", this.size); + jsonWriter.writeStringField("digest", this.digest); + jsonWriter.writeStringField("tag", this.tag); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("version", this.version); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ContainerRegistryArtifactEventTarget from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ContainerRegistryArtifactEventTarget 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 ContainerRegistryArtifactEventTarget. + */ + @Generated + public static ContainerRegistryArtifactEventTarget fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String mediaType = null; + String repository = null; + Long size = null; + String digest = null; + String tag = null; + String name = null; + String version = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("mediaType".equals(fieldName)) { + mediaType = reader.getString(); + } else if ("repository".equals(fieldName)) { + repository = reader.getString(); + } else if ("size".equals(fieldName)) { + size = reader.getNullable(JsonReader::getLong); + } else if ("digest".equals(fieldName)) { + digest = reader.getString(); + } else if ("tag".equals(fieldName)) { + tag = reader.getString(); + } else if ("name".equals(fieldName)) { + name = reader.getString(); + } else if ("version".equals(fieldName)) { + version = reader.getString(); + } else { + reader.skipChildren(); + } + } + ContainerRegistryArtifactEventTarget deserializedContainerRegistryArtifactEventTarget + = new ContainerRegistryArtifactEventTarget(mediaType, repository); + deserializedContainerRegistryArtifactEventTarget.size = size; + deserializedContainerRegistryArtifactEventTarget.digest = digest; + deserializedContainerRegistryArtifactEventTarget.tag = tag; + deserializedContainerRegistryArtifactEventTarget.name = name; + deserializedContainerRegistryArtifactEventTarget.version = version; + + return deserializedContainerRegistryArtifactEventTarget; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryChartDeletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryChartDeletedEventData.java new file mode 100644 index 000000000000..d2ca78953f7e --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryChartDeletedEventData.java @@ -0,0 +1,118 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ContainerRegistry.ChartDeleted event. + */ +@Immutable +public final class ContainerRegistryChartDeletedEventData extends ContainerRegistryArtifactEventData { + /* + * The connected registry information if the event is generated by a connected registry. + */ + @Generated + private ContainerRegistryEventConnectedRegistry connectedRegistry; + + /** + * Creates an instance of ContainerRegistryChartDeletedEventData class. + * + * @param id the id value to set. + * @param timestamp the timestamp value to set. + * @param action the action value to set. + * @param location the location value to set. + * @param target the target value to set. + */ + @Generated + private ContainerRegistryChartDeletedEventData(String id, OffsetDateTime timestamp, String action, String location, + ContainerRegistryArtifactEventTarget target) { + super(id, timestamp, action, location, target); + } + + /** + * Get the connectedRegistry property: The connected registry information if the event is generated by a connected + * registry. + * + * @return the connectedRegistry value. + */ + @Generated + @Override + public ContainerRegistryEventConnectedRegistry getConnectedRegistry() { + return this.connectedRegistry; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("id", getId()); + jsonWriter.writeStringField("timestamp", + getTimestamp() == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(getTimestamp())); + jsonWriter.writeStringField("action", getAction()); + jsonWriter.writeStringField("location", getLocation()); + jsonWriter.writeJsonField("target", getTarget()); + jsonWriter.writeJsonField("connectedRegistry", getConnectedRegistry()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ContainerRegistryChartDeletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ContainerRegistryChartDeletedEventData 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 ContainerRegistryChartDeletedEventData. + */ + @Generated + public static ContainerRegistryChartDeletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String id = null; + OffsetDateTime timestamp = null; + String action = null; + String location = null; + ContainerRegistryArtifactEventTarget target = null; + ContainerRegistryEventConnectedRegistry connectedRegistry = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + id = reader.getString(); + } else if ("timestamp".equals(fieldName)) { + timestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("action".equals(fieldName)) { + action = reader.getString(); + } else if ("location".equals(fieldName)) { + location = reader.getString(); + } else if ("target".equals(fieldName)) { + target = ContainerRegistryArtifactEventTarget.fromJson(reader); + } else if ("connectedRegistry".equals(fieldName)) { + connectedRegistry = ContainerRegistryEventConnectedRegistry.fromJson(reader); + } else { + reader.skipChildren(); + } + } + ContainerRegistryChartDeletedEventData deserializedContainerRegistryChartDeletedEventData + = new ContainerRegistryChartDeletedEventData(id, timestamp, action, location, target); + deserializedContainerRegistryChartDeletedEventData.connectedRegistry = connectedRegistry; + + return deserializedContainerRegistryChartDeletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryChartPushedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryChartPushedEventData.java new file mode 100644 index 000000000000..1ec8f0bedeed --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryChartPushedEventData.java @@ -0,0 +1,118 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ContainerRegistry.ChartPushed event. + */ +@Immutable +public final class ContainerRegistryChartPushedEventData extends ContainerRegistryArtifactEventData { + /* + * The connected registry information if the event is generated by a connected registry. + */ + @Generated + private ContainerRegistryEventConnectedRegistry connectedRegistry; + + /** + * Creates an instance of ContainerRegistryChartPushedEventData class. + * + * @param id the id value to set. + * @param timestamp the timestamp value to set. + * @param action the action value to set. + * @param location the location value to set. + * @param target the target value to set. + */ + @Generated + private ContainerRegistryChartPushedEventData(String id, OffsetDateTime timestamp, String action, String location, + ContainerRegistryArtifactEventTarget target) { + super(id, timestamp, action, location, target); + } + + /** + * Get the connectedRegistry property: The connected registry information if the event is generated by a connected + * registry. + * + * @return the connectedRegistry value. + */ + @Generated + @Override + public ContainerRegistryEventConnectedRegistry getConnectedRegistry() { + return this.connectedRegistry; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("id", getId()); + jsonWriter.writeStringField("timestamp", + getTimestamp() == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(getTimestamp())); + jsonWriter.writeStringField("action", getAction()); + jsonWriter.writeStringField("location", getLocation()); + jsonWriter.writeJsonField("target", getTarget()); + jsonWriter.writeJsonField("connectedRegistry", getConnectedRegistry()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ContainerRegistryChartPushedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ContainerRegistryChartPushedEventData 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 ContainerRegistryChartPushedEventData. + */ + @Generated + public static ContainerRegistryChartPushedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String id = null; + OffsetDateTime timestamp = null; + String action = null; + String location = null; + ContainerRegistryArtifactEventTarget target = null; + ContainerRegistryEventConnectedRegistry connectedRegistry = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + id = reader.getString(); + } else if ("timestamp".equals(fieldName)) { + timestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("action".equals(fieldName)) { + action = reader.getString(); + } else if ("location".equals(fieldName)) { + location = reader.getString(); + } else if ("target".equals(fieldName)) { + target = ContainerRegistryArtifactEventTarget.fromJson(reader); + } else if ("connectedRegistry".equals(fieldName)) { + connectedRegistry = ContainerRegistryEventConnectedRegistry.fromJson(reader); + } else { + reader.skipChildren(); + } + } + ContainerRegistryChartPushedEventData deserializedContainerRegistryChartPushedEventData + = new ContainerRegistryChartPushedEventData(id, timestamp, action, location, target); + deserializedContainerRegistryChartPushedEventData.connectedRegistry = connectedRegistry; + + return deserializedContainerRegistryChartPushedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryEventActor.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryEventActor.java new file mode 100644 index 000000000000..1bcdc6a5bde2 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryEventActor.java @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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 agent that initiated the event. For most situations, this could be from the authorization context of the request. + */ +@Immutable +public final class ContainerRegistryEventActor implements JsonSerializable { + /* + * The subject or username associated with the request context that generated the event. + */ + @Generated + private String name; + + /** + * Creates an instance of ContainerRegistryEventActor class. + */ + @Generated + private ContainerRegistryEventActor() { + } + + /** + * Get the name property: The subject or username associated with the request context that generated the event. + * + * @return the name value. + */ + @Generated + 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 ContainerRegistryEventActor from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ContainerRegistryEventActor 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 ContainerRegistryEventActor. + */ + @Generated + public static ContainerRegistryEventActor fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ContainerRegistryEventActor deserializedContainerRegistryEventActor = new ContainerRegistryEventActor(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("name".equals(fieldName)) { + deserializedContainerRegistryEventActor.name = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedContainerRegistryEventActor; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryEventConnectedRegistry.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryEventConnectedRegistry.java new file mode 100644 index 000000000000..315d60eb9e69 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryEventConnectedRegistry.java @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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 connected registry information if the event is generated by a connected registry. + */ +@Immutable +public final class ContainerRegistryEventConnectedRegistry + implements JsonSerializable { + /* + * The name of the connected registry that generated this event. + */ + @Generated + private final String name; + + /** + * Creates an instance of ContainerRegistryEventConnectedRegistry class. + * + * @param name the name value to set. + */ + @Generated + private ContainerRegistryEventConnectedRegistry(String name) { + this.name = name; + } + + /** + * Get the name property: The name of the connected registry that generated this event. + * + * @return the name value. + */ + @Generated + 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 ContainerRegistryEventConnectedRegistry from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ContainerRegistryEventConnectedRegistry 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 ContainerRegistryEventConnectedRegistry. + */ + @Generated + public static ContainerRegistryEventConnectedRegistry 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 ContainerRegistryEventConnectedRegistry(name); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryEventData.java new file mode 100644 index 000000000000..302137c24bb7 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryEventData.java @@ -0,0 +1,320 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * The content of the event request message. + */ +@Immutable +public class ContainerRegistryEventData implements JsonSerializable { + /* + * The event ID. + */ + @Generated + private final String id; + + /* + * The time at which the event occurred. + */ + @Generated + private final OffsetDateTime timestamp; + + /* + * The action that encompasses the provided event. + */ + @Generated + private final String action; + + /* + * The location of the event. + */ + @Generated + private final String location; + + /* + * The target of the event. + */ + @Generated + private final ContainerRegistryEventTarget target; + + /* + * The request that generated the event. + */ + @Generated + private ContainerRegistryEventRequest request; + + /* + * The agent that initiated the event. For most situations, this could be from the authorization context of the + * request. + */ + @Generated + private ContainerRegistryEventActor actor; + + /* + * The registry node that generated the event. Put differently, while the actor initiates the event, the source + * generates it. + */ + @Generated + private ContainerRegistryEventSource source; + + /* + * The connected registry information if the event is generated by a connected registry. + */ + @Generated + private ContainerRegistryEventConnectedRegistry connectedRegistry; + + /** + * Creates an instance of ContainerRegistryEventData class. + * + * @param id the id value to set. + * @param timestamp the timestamp value to set. + * @param action the action value to set. + * @param location the location value to set. + * @param target the target value to set. + */ + @Generated + protected ContainerRegistryEventData(String id, OffsetDateTime timestamp, String action, String location, + ContainerRegistryEventTarget target) { + this.id = id; + this.timestamp = timestamp; + this.action = action; + this.location = location; + this.target = target; + } + + /** + * Get the id property: The event ID. + * + * @return the id value. + */ + @Generated + public String getId() { + return this.id; + } + + /** + * Get the timestamp property: The time at which the event occurred. + * + * @return the timestamp value. + */ + @Generated + public OffsetDateTime getTimestamp() { + return this.timestamp; + } + + /** + * Get the action property: The action that encompasses the provided event. + * + * @return the action value. + */ + @Generated + public String getAction() { + return this.action; + } + + /** + * Get the location property: The location of the event. + * + * @return the location value. + */ + @Generated + public String getLocation() { + return this.location; + } + + /** + * Get the target property: The target of the event. + * + * @return the target value. + */ + @Generated + public ContainerRegistryEventTarget getTarget() { + return this.target; + } + + /** + * Get the request property: The request that generated the event. + * + * @return the request value. + */ + @Generated + public ContainerRegistryEventRequest getRequest() { + return this.request; + } + + /** + * Set the request property: The request that generated the event. + * + * @param request the request value to set. + * @return the ContainerRegistryEventData object itself. + */ + @Generated + ContainerRegistryEventData setRequest(ContainerRegistryEventRequest request) { + this.request = request; + return this; + } + + /** + * Get the actor property: The agent that initiated the event. For most situations, this could be from the + * authorization context of the request. + * + * @return the actor value. + */ + @Generated + public ContainerRegistryEventActor getActor() { + return this.actor; + } + + /** + * Set the actor property: The agent that initiated the event. For most situations, this could be from the + * authorization context of the request. + * + * @param actor the actor value to set. + * @return the ContainerRegistryEventData object itself. + */ + @Generated + ContainerRegistryEventData setActor(ContainerRegistryEventActor actor) { + this.actor = actor; + return this; + } + + /** + * Get the source property: The registry node that generated the event. Put differently, while the actor initiates + * the event, the source generates it. + * + * @return the source value. + */ + @Generated + public ContainerRegistryEventSource getSource() { + return this.source; + } + + /** + * Set the source property: The registry node that generated the event. Put differently, while the actor initiates + * the event, the source generates it. + * + * @param source the source value to set. + * @return the ContainerRegistryEventData object itself. + */ + @Generated + ContainerRegistryEventData setSource(ContainerRegistryEventSource source) { + this.source = source; + return this; + } + + /** + * Get the connectedRegistry property: The connected registry information if the event is generated by a connected + * registry. + * + * @return the connectedRegistry value. + */ + @Generated + public ContainerRegistryEventConnectedRegistry getConnectedRegistry() { + return this.connectedRegistry; + } + + /** + * Set the connectedRegistry property: The connected registry information if the event is generated by a connected + * registry. + * + * @param connectedRegistry the connectedRegistry value to set. + * @return the ContainerRegistryEventData object itself. + */ + @Generated + ContainerRegistryEventData setConnectedRegistry(ContainerRegistryEventConnectedRegistry connectedRegistry) { + this.connectedRegistry = connectedRegistry; + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("id", this.id); + jsonWriter.writeStringField("timestamp", + this.timestamp == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.timestamp)); + jsonWriter.writeStringField("action", this.action); + jsonWriter.writeStringField("location", this.location); + jsonWriter.writeJsonField("target", this.target); + jsonWriter.writeJsonField("request", this.request); + jsonWriter.writeJsonField("actor", this.actor); + jsonWriter.writeJsonField("source", this.source); + jsonWriter.writeJsonField("connectedRegistry", this.connectedRegistry); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ContainerRegistryEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ContainerRegistryEventData 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 ContainerRegistryEventData. + */ + @Generated + public static ContainerRegistryEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String id = null; + OffsetDateTime timestamp = null; + String action = null; + String location = null; + ContainerRegistryEventTarget target = null; + ContainerRegistryEventRequest request = null; + ContainerRegistryEventActor actor = null; + ContainerRegistryEventSource source = null; + ContainerRegistryEventConnectedRegistry connectedRegistry = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + id = reader.getString(); + } else if ("timestamp".equals(fieldName)) { + timestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("action".equals(fieldName)) { + action = reader.getString(); + } else if ("location".equals(fieldName)) { + location = reader.getString(); + } else if ("target".equals(fieldName)) { + target = ContainerRegistryEventTarget.fromJson(reader); + } else if ("request".equals(fieldName)) { + request = ContainerRegistryEventRequest.fromJson(reader); + } else if ("actor".equals(fieldName)) { + actor = ContainerRegistryEventActor.fromJson(reader); + } else if ("source".equals(fieldName)) { + source = ContainerRegistryEventSource.fromJson(reader); + } else if ("connectedRegistry".equals(fieldName)) { + connectedRegistry = ContainerRegistryEventConnectedRegistry.fromJson(reader); + } else { + reader.skipChildren(); + } + } + ContainerRegistryEventData deserializedContainerRegistryEventData + = new ContainerRegistryEventData(id, timestamp, action, location, target); + deserializedContainerRegistryEventData.request = request; + deserializedContainerRegistryEventData.actor = actor; + deserializedContainerRegistryEventData.source = source; + deserializedContainerRegistryEventData.connectedRegistry = connectedRegistry; + + return deserializedContainerRegistryEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryEventRequest.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryEventRequest.java new file mode 100644 index 000000000000..b4b4796c976d --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryEventRequest.java @@ -0,0 +1,176 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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 request that generated the event. + */ +@Immutable +public final class ContainerRegistryEventRequest implements JsonSerializable { + /* + * The ID of the request that initiated the event. + */ + @Generated + private final String id; + + /* + * The IP or hostname and possibly port of the client connection that initiated the event. This is the RemoteAddr + * from the standard http request. + */ + @Generated + private String addr; + + /* + * The externally accessible hostname of the registry instance, as specified by the http host header on incoming + * requests. + */ + @Generated + private final String host; + + /* + * The request method that generated the event. + */ + @Generated + private final String method; + + /* + * The user agent header of the request. + */ + @Generated + private String useragent; + + /** + * Creates an instance of ContainerRegistryEventRequest class. + * + * @param id the id value to set. + * @param host the host value to set. + * @param method the method value to set. + */ + @Generated + private ContainerRegistryEventRequest(String id, String host, String method) { + this.id = id; + this.host = host; + this.method = method; + } + + /** + * Get the id property: The ID of the request that initiated the event. + * + * @return the id value. + */ + @Generated + public String getId() { + return this.id; + } + + /** + * Get the addr property: The IP or hostname and possibly port of the client connection that initiated the event. + * This is the RemoteAddr from the standard http request. + * + * @return the addr value. + */ + @Generated + public String getAddr() { + return this.addr; + } + + /** + * Get the host property: The externally accessible hostname of the registry instance, as specified by the http host + * header on incoming requests. + * + * @return the host value. + */ + @Generated + public String getHost() { + return this.host; + } + + /** + * Get the method property: The request method that generated the event. + * + * @return the method value. + */ + @Generated + public String getMethod() { + return this.method; + } + + /** + * Get the useragent property: The user agent header of the request. + * + * @return the useragent value. + */ + @Generated + public String getUseragent() { + return this.useragent; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("id", this.id); + jsonWriter.writeStringField("host", this.host); + jsonWriter.writeStringField("method", this.method); + jsonWriter.writeStringField("addr", this.addr); + jsonWriter.writeStringField("useragent", this.useragent); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ContainerRegistryEventRequest from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ContainerRegistryEventRequest 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 ContainerRegistryEventRequest. + */ + @Generated + public static ContainerRegistryEventRequest fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String id = null; + String host = null; + String method = null; + String addr = null; + String useragent = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + id = reader.getString(); + } else if ("host".equals(fieldName)) { + host = reader.getString(); + } else if ("method".equals(fieldName)) { + method = reader.getString(); + } else if ("addr".equals(fieldName)) { + addr = reader.getString(); + } else if ("useragent".equals(fieldName)) { + useragent = reader.getString(); + } else { + reader.skipChildren(); + } + } + ContainerRegistryEventRequest deserializedContainerRegistryEventRequest + = new ContainerRegistryEventRequest(id, host, method); + deserializedContainerRegistryEventRequest.addr = addr; + deserializedContainerRegistryEventRequest.useragent = useragent; + + return deserializedContainerRegistryEventRequest; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryEventSource.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryEventSource.java new file mode 100644 index 000000000000..a05b232cbc9f --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryEventSource.java @@ -0,0 +1,102 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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 registry node that generated the event. Put differently, while the actor initiates the event, the source + * generates it. + */ +@Immutable +public final class ContainerRegistryEventSource implements JsonSerializable { + /* + * The IP or hostname and the port of the registry node that generated the event. Generally, this will be resolved + * by os.Hostname() along with the running port. + */ + @Generated + private String addr; + + /* + * The running instance of an application. Changes after each restart. + */ + @Generated + private String instanceID; + + /** + * Creates an instance of ContainerRegistryEventSource class. + */ + @Generated + private ContainerRegistryEventSource() { + } + + /** + * Get the addr property: The IP or hostname and the port of the registry node that generated the event. Generally, + * this will be resolved by os.Hostname() along with the running port. + * + * @return the addr value. + */ + @Generated + public String getAddr() { + return this.addr; + } + + /** + * Get the instanceID property: The running instance of an application. Changes after each restart. + * + * @return the instanceID value. + */ + @Generated + public String getInstanceID() { + return this.instanceID; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("addr", this.addr); + jsonWriter.writeStringField("instanceID", this.instanceID); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ContainerRegistryEventSource from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ContainerRegistryEventSource 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 ContainerRegistryEventSource. + */ + @Generated + public static ContainerRegistryEventSource fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ContainerRegistryEventSource deserializedContainerRegistryEventSource = new ContainerRegistryEventSource(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("addr".equals(fieldName)) { + deserializedContainerRegistryEventSource.addr = reader.getString(); + } else if ("instanceID".equals(fieldName)) { + deserializedContainerRegistryEventSource.instanceID = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedContainerRegistryEventSource; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryEventTarget.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryEventTarget.java new file mode 100644 index 000000000000..2983ea463ff2 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryEventTarget.java @@ -0,0 +1,213 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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 target of the event. + */ +@Immutable +public final class ContainerRegistryEventTarget implements JsonSerializable { + /* + * The MIME type of the referenced object. + */ + @Generated + private final String mediaType; + + /* + * The number of bytes of the content. Same as Length field. + */ + @Generated + private Long size; + + /* + * The digest of the content, as defined by the Registry V2 HTTP API Specification. + */ + @Generated + private String digest; + + /* + * The number of bytes of the content. Same as Size field. + */ + @Generated + private Long length; + + /* + * The repository name. + */ + @Generated + private final String repository; + + /* + * The direct URL to the content. + */ + @Generated + private String url; + + /* + * The tag name. + */ + @Generated + private String tag; + + /** + * Creates an instance of ContainerRegistryEventTarget class. + * + * @param mediaType the mediaType value to set. + * @param repository the repository value to set. + */ + @Generated + private ContainerRegistryEventTarget(String mediaType, String repository) { + this.mediaType = mediaType; + this.repository = repository; + } + + /** + * Get the mediaType property: The MIME type of the referenced object. + * + * @return the mediaType value. + */ + @Generated + public String getMediaType() { + return this.mediaType; + } + + /** + * Get the size property: The number of bytes of the content. Same as Length field. + * + * @return the size value. + */ + @Generated + public Long getSize() { + return this.size; + } + + /** + * Get the digest property: The digest of the content, as defined by the Registry V2 HTTP API Specification. + * + * @return the digest value. + */ + @Generated + public String getDigest() { + return this.digest; + } + + /** + * Get the length property: The number of bytes of the content. Same as Size field. + * + * @return the length value. + */ + @Generated + public Long getLength() { + return this.length; + } + + /** + * Get the repository property: The repository name. + * + * @return the repository value. + */ + @Generated + public String getRepository() { + return this.repository; + } + + /** + * Get the url property: The direct URL to the content. + * + * @return the url value. + */ + @Generated + public String getUrl() { + return this.url; + } + + /** + * Get the tag property: The tag name. + * + * @return the tag value. + */ + @Generated + public String getTag() { + return this.tag; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("mediaType", this.mediaType); + jsonWriter.writeStringField("repository", this.repository); + jsonWriter.writeNumberField("size", this.size); + jsonWriter.writeStringField("digest", this.digest); + jsonWriter.writeNumberField("length", this.length); + jsonWriter.writeStringField("url", this.url); + jsonWriter.writeStringField("tag", this.tag); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ContainerRegistryEventTarget from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ContainerRegistryEventTarget 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 ContainerRegistryEventTarget. + */ + @Generated + public static ContainerRegistryEventTarget fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String mediaType = null; + String repository = null; + Long size = null; + String digest = null; + Long length = null; + String url = null; + String tag = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("mediaType".equals(fieldName)) { + mediaType = reader.getString(); + } else if ("repository".equals(fieldName)) { + repository = reader.getString(); + } else if ("size".equals(fieldName)) { + size = reader.getNullable(JsonReader::getLong); + } else if ("digest".equals(fieldName)) { + digest = reader.getString(); + } else if ("length".equals(fieldName)) { + length = reader.getNullable(JsonReader::getLong); + } else if ("url".equals(fieldName)) { + url = reader.getString(); + } else if ("tag".equals(fieldName)) { + tag = reader.getString(); + } else { + reader.skipChildren(); + } + } + ContainerRegistryEventTarget deserializedContainerRegistryEventTarget + = new ContainerRegistryEventTarget(mediaType, repository); + deserializedContainerRegistryEventTarget.size = size; + deserializedContainerRegistryEventTarget.digest = digest; + deserializedContainerRegistryEventTarget.length = length; + deserializedContainerRegistryEventTarget.url = url; + deserializedContainerRegistryEventTarget.tag = tag; + + return deserializedContainerRegistryEventTarget; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryImageDeletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryImageDeletedEventData.java new file mode 100644 index 000000000000..a96798c64cd1 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryImageDeletedEventData.java @@ -0,0 +1,188 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ContainerRegistry.ImageDeleted event. + */ +@Immutable +public final class ContainerRegistryImageDeletedEventData extends ContainerRegistryEventData { + /* + * The connected registry information if the event is generated by a connected registry. + */ + @Generated + private ContainerRegistryEventConnectedRegistry connectedRegistry; + + /* + * The registry node that generated the event. Put differently, while the actor initiates the event, the source + * generates it. + */ + @Generated + private ContainerRegistryEventSource source; + + /* + * The agent that initiated the event. For most situations, this could be from the authorization context of the + * request. + */ + @Generated + private ContainerRegistryEventActor actor; + + /* + * The request that generated the event. + */ + @Generated + private ContainerRegistryEventRequest request; + + /** + * Creates an instance of ContainerRegistryImageDeletedEventData class. + * + * @param id the id value to set. + * @param timestamp the timestamp value to set. + * @param action the action value to set. + * @param location the location value to set. + * @param target the target value to set. + */ + @Generated + private ContainerRegistryImageDeletedEventData(String id, OffsetDateTime timestamp, String action, String location, + ContainerRegistryEventTarget target) { + super(id, timestamp, action, location, target); + } + + /** + * Get the connectedRegistry property: The connected registry information if the event is generated by a connected + * registry. + * + * @return the connectedRegistry value. + */ + @Generated + @Override + public ContainerRegistryEventConnectedRegistry getConnectedRegistry() { + return this.connectedRegistry; + } + + /** + * Get the source property: The registry node that generated the event. Put differently, while the actor initiates + * the event, the source generates it. + * + * @return the source value. + */ + @Generated + @Override + public ContainerRegistryEventSource getSource() { + return this.source; + } + + /** + * Get the actor property: The agent that initiated the event. For most situations, this could be from the + * authorization context of the request. + * + * @return the actor value. + */ + @Generated + @Override + public ContainerRegistryEventActor getActor() { + return this.actor; + } + + /** + * Get the request property: The request that generated the event. + * + * @return the request value. + */ + @Generated + @Override + public ContainerRegistryEventRequest getRequest() { + return this.request; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("id", getId()); + jsonWriter.writeStringField("timestamp", + getTimestamp() == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(getTimestamp())); + jsonWriter.writeStringField("action", getAction()); + jsonWriter.writeStringField("location", getLocation()); + jsonWriter.writeJsonField("target", getTarget()); + jsonWriter.writeJsonField("request", getRequest()); + jsonWriter.writeJsonField("actor", getActor()); + jsonWriter.writeJsonField("source", getSource()); + jsonWriter.writeJsonField("connectedRegistry", getConnectedRegistry()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ContainerRegistryImageDeletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ContainerRegistryImageDeletedEventData 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 ContainerRegistryImageDeletedEventData. + */ + @Generated + public static ContainerRegistryImageDeletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String id = null; + OffsetDateTime timestamp = null; + String action = null; + String location = null; + ContainerRegistryEventTarget target = null; + ContainerRegistryEventRequest request = null; + ContainerRegistryEventActor actor = null; + ContainerRegistryEventSource source = null; + ContainerRegistryEventConnectedRegistry connectedRegistry = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + id = reader.getString(); + } else if ("timestamp".equals(fieldName)) { + timestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("action".equals(fieldName)) { + action = reader.getString(); + } else if ("location".equals(fieldName)) { + location = reader.getString(); + } else if ("target".equals(fieldName)) { + target = ContainerRegistryEventTarget.fromJson(reader); + } else if ("request".equals(fieldName)) { + request = ContainerRegistryEventRequest.fromJson(reader); + } else if ("actor".equals(fieldName)) { + actor = ContainerRegistryEventActor.fromJson(reader); + } else if ("source".equals(fieldName)) { + source = ContainerRegistryEventSource.fromJson(reader); + } else if ("connectedRegistry".equals(fieldName)) { + connectedRegistry = ContainerRegistryEventConnectedRegistry.fromJson(reader); + } else { + reader.skipChildren(); + } + } + ContainerRegistryImageDeletedEventData deserializedContainerRegistryImageDeletedEventData + = new ContainerRegistryImageDeletedEventData(id, timestamp, action, location, target); + deserializedContainerRegistryImageDeletedEventData.request = request; + deserializedContainerRegistryImageDeletedEventData.actor = actor; + deserializedContainerRegistryImageDeletedEventData.source = source; + deserializedContainerRegistryImageDeletedEventData.connectedRegistry = connectedRegistry; + + return deserializedContainerRegistryImageDeletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryImagePushedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryImagePushedEventData.java new file mode 100644 index 000000000000..f6300a7e0d1f --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerRegistryImagePushedEventData.java @@ -0,0 +1,188 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ContainerRegistry.ImagePushed event. + */ +@Immutable +public final class ContainerRegistryImagePushedEventData extends ContainerRegistryEventData { + /* + * The connected registry information if the event is generated by a connected registry. + */ + @Generated + private ContainerRegistryEventConnectedRegistry connectedRegistry; + + /* + * The registry node that generated the event. Put differently, while the actor initiates the event, the source + * generates it. + */ + @Generated + private ContainerRegistryEventSource source; + + /* + * The agent that initiated the event. For most situations, this could be from the authorization context of the + * request. + */ + @Generated + private ContainerRegistryEventActor actor; + + /* + * The request that generated the event. + */ + @Generated + private ContainerRegistryEventRequest request; + + /** + * Creates an instance of ContainerRegistryImagePushedEventData class. + * + * @param id the id value to set. + * @param timestamp the timestamp value to set. + * @param action the action value to set. + * @param location the location value to set. + * @param target the target value to set. + */ + @Generated + private ContainerRegistryImagePushedEventData(String id, OffsetDateTime timestamp, String action, String location, + ContainerRegistryEventTarget target) { + super(id, timestamp, action, location, target); + } + + /** + * Get the connectedRegistry property: The connected registry information if the event is generated by a connected + * registry. + * + * @return the connectedRegistry value. + */ + @Generated + @Override + public ContainerRegistryEventConnectedRegistry getConnectedRegistry() { + return this.connectedRegistry; + } + + /** + * Get the source property: The registry node that generated the event. Put differently, while the actor initiates + * the event, the source generates it. + * + * @return the source value. + */ + @Generated + @Override + public ContainerRegistryEventSource getSource() { + return this.source; + } + + /** + * Get the actor property: The agent that initiated the event. For most situations, this could be from the + * authorization context of the request. + * + * @return the actor value. + */ + @Generated + @Override + public ContainerRegistryEventActor getActor() { + return this.actor; + } + + /** + * Get the request property: The request that generated the event. + * + * @return the request value. + */ + @Generated + @Override + public ContainerRegistryEventRequest getRequest() { + return this.request; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("id", getId()); + jsonWriter.writeStringField("timestamp", + getTimestamp() == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(getTimestamp())); + jsonWriter.writeStringField("action", getAction()); + jsonWriter.writeStringField("location", getLocation()); + jsonWriter.writeJsonField("target", getTarget()); + jsonWriter.writeJsonField("request", getRequest()); + jsonWriter.writeJsonField("actor", getActor()); + jsonWriter.writeJsonField("source", getSource()); + jsonWriter.writeJsonField("connectedRegistry", getConnectedRegistry()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ContainerRegistryImagePushedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ContainerRegistryImagePushedEventData 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 ContainerRegistryImagePushedEventData. + */ + @Generated + public static ContainerRegistryImagePushedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String id = null; + OffsetDateTime timestamp = null; + String action = null; + String location = null; + ContainerRegistryEventTarget target = null; + ContainerRegistryEventRequest request = null; + ContainerRegistryEventActor actor = null; + ContainerRegistryEventSource source = null; + ContainerRegistryEventConnectedRegistry connectedRegistry = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + id = reader.getString(); + } else if ("timestamp".equals(fieldName)) { + timestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("action".equals(fieldName)) { + action = reader.getString(); + } else if ("location".equals(fieldName)) { + location = reader.getString(); + } else if ("target".equals(fieldName)) { + target = ContainerRegistryEventTarget.fromJson(reader); + } else if ("request".equals(fieldName)) { + request = ContainerRegistryEventRequest.fromJson(reader); + } else if ("actor".equals(fieldName)) { + actor = ContainerRegistryEventActor.fromJson(reader); + } else if ("source".equals(fieldName)) { + source = ContainerRegistryEventSource.fromJson(reader); + } else if ("connectedRegistry".equals(fieldName)) { + connectedRegistry = ContainerRegistryEventConnectedRegistry.fromJson(reader); + } else { + reader.skipChildren(); + } + } + ContainerRegistryImagePushedEventData deserializedContainerRegistryImagePushedEventData + = new ContainerRegistryImagePushedEventData(id, timestamp, action, location, target); + deserializedContainerRegistryImagePushedEventData.request = request; + deserializedContainerRegistryImagePushedEventData.actor = actor; + deserializedContainerRegistryImagePushedEventData.source = source; + deserializedContainerRegistryImagePushedEventData.connectedRegistry = connectedRegistry; + + return deserializedContainerRegistryImagePushedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerServiceClusterSupportEndedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerServiceClusterSupportEndedEventData.java new file mode 100644 index 000000000000..437e48a383f7 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerServiceClusterSupportEndedEventData.java @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ContainerService.ClusterSupportEnded event. + */ +@Immutable +public final class ContainerServiceClusterSupportEndedEventData extends ContainerServiceClusterSupportEventData { + /* + * The Kubernetes version of the ManagedCluster resource + */ + @Generated + private String kubernetesVersion; + + /** + * Creates an instance of ContainerServiceClusterSupportEndedEventData class. + */ + @Generated + private ContainerServiceClusterSupportEndedEventData() { + } + + /** + * Get the kubernetesVersion property: The Kubernetes version of the ManagedCluster resource. + * + * @return the kubernetesVersion value. + */ + @Generated + @Override + public String getKubernetesVersion() { + return this.kubernetesVersion; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("kubernetesVersion", getKubernetesVersion()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ContainerServiceClusterSupportEndedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ContainerServiceClusterSupportEndedEventData 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 ContainerServiceClusterSupportEndedEventData. + */ + @Generated + public static ContainerServiceClusterSupportEndedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ContainerServiceClusterSupportEndedEventData deserializedContainerServiceClusterSupportEndedEventData + = new ContainerServiceClusterSupportEndedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("kubernetesVersion".equals(fieldName)) { + deserializedContainerServiceClusterSupportEndedEventData.kubernetesVersion = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedContainerServiceClusterSupportEndedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerServiceClusterSupportEndingEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerServiceClusterSupportEndingEventData.java new file mode 100644 index 000000000000..8158e8238dbb --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerServiceClusterSupportEndingEventData.java @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ContainerService.ClusterSupportEnding event. + */ +@Immutable +public final class ContainerServiceClusterSupportEndingEventData extends ContainerServiceClusterSupportEventData { + /* + * The Kubernetes version of the ManagedCluster resource + */ + @Generated + private String kubernetesVersion; + + /** + * Creates an instance of ContainerServiceClusterSupportEndingEventData class. + */ + @Generated + private ContainerServiceClusterSupportEndingEventData() { + } + + /** + * Get the kubernetesVersion property: The Kubernetes version of the ManagedCluster resource. + * + * @return the kubernetesVersion value. + */ + @Generated + @Override + public String getKubernetesVersion() { + return this.kubernetesVersion; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("kubernetesVersion", getKubernetesVersion()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ContainerServiceClusterSupportEndingEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ContainerServiceClusterSupportEndingEventData 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 ContainerServiceClusterSupportEndingEventData. + */ + @Generated + public static ContainerServiceClusterSupportEndingEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ContainerServiceClusterSupportEndingEventData deserializedContainerServiceClusterSupportEndingEventData + = new ContainerServiceClusterSupportEndingEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("kubernetesVersion".equals(fieldName)) { + deserializedContainerServiceClusterSupportEndingEventData.kubernetesVersion = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedContainerServiceClusterSupportEndingEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerServiceClusterSupportEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerServiceClusterSupportEventData.java new file mode 100644 index 000000000000..a8780d6ac758 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerServiceClusterSupportEventData.java @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of common properties of cluster support events. + */ +@Immutable +public class ContainerServiceClusterSupportEventData + implements JsonSerializable { + /* + * The Kubernetes version of the ManagedCluster resource + */ + @Generated + private String kubernetesVersion; + + /** + * Creates an instance of ContainerServiceClusterSupportEventData class. + */ + @Generated + protected ContainerServiceClusterSupportEventData() { + } + + /** + * Get the kubernetesVersion property: The Kubernetes version of the ManagedCluster resource. + * + * @return the kubernetesVersion value. + */ + @Generated + public String getKubernetesVersion() { + return this.kubernetesVersion; + } + + /** + * Set the kubernetesVersion property: The Kubernetes version of the ManagedCluster resource. + * + * @param kubernetesVersion the kubernetesVersion value to set. + * @return the ContainerServiceClusterSupportEventData object itself. + */ + @Generated + ContainerServiceClusterSupportEventData setKubernetesVersion(String kubernetesVersion) { + this.kubernetesVersion = kubernetesVersion; + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("kubernetesVersion", this.kubernetesVersion); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ContainerServiceClusterSupportEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ContainerServiceClusterSupportEventData 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 ContainerServiceClusterSupportEventData. + */ + @Generated + public static ContainerServiceClusterSupportEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ContainerServiceClusterSupportEventData deserializedContainerServiceClusterSupportEventData + = new ContainerServiceClusterSupportEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("kubernetesVersion".equals(fieldName)) { + deserializedContainerServiceClusterSupportEventData.kubernetesVersion = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedContainerServiceClusterSupportEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerServiceNewKubernetesVersionAvailableEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerServiceNewKubernetesVersionAvailableEventData.java new file mode 100644 index 000000000000..51efdeda1ec5 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerServiceNewKubernetesVersionAvailableEventData.java @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ContainerService.NewKubernetesVersionAvailable + * event. + */ +@Immutable +public final class ContainerServiceNewKubernetesVersionAvailableEventData + implements JsonSerializable { + /* + * The highest PATCH Kubernetes version for the highest MINOR version supported by ManagedCluster resource + */ + @Generated + private String latestSupportedKubernetesVersion; + + /* + * The highest PATCH Kubernetes version for the MINOR version considered stable for the ManagedCluster resource + */ + @Generated + private String latestStableKubernetesVersion; + + /* + * The highest PATCH Kubernetes version for the lowest applicable MINOR version available for the ManagedCluster + * resource + */ + @Generated + private String lowestMinorKubernetesVersion; + + /* + * The highest PATCH Kubernetes version considered preview for the ManagedCluster resource. There might not be any + * version in preview at the time of publishing the event + */ + @Generated + private String latestPreviewKubernetesVersion; + + /** + * Creates an instance of ContainerServiceNewKubernetesVersionAvailableEventData class. + */ + @Generated + private ContainerServiceNewKubernetesVersionAvailableEventData() { + } + + /** + * Get the latestSupportedKubernetesVersion property: The highest PATCH Kubernetes version for the highest MINOR + * version supported by ManagedCluster resource. + * + * @return the latestSupportedKubernetesVersion value. + */ + @Generated + public String getLatestSupportedKubernetesVersion() { + return this.latestSupportedKubernetesVersion; + } + + /** + * Get the latestStableKubernetesVersion property: The highest PATCH Kubernetes version for the MINOR version + * considered stable for the ManagedCluster resource. + * + * @return the latestStableKubernetesVersion value. + */ + @Generated + public String getLatestStableKubernetesVersion() { + return this.latestStableKubernetesVersion; + } + + /** + * Get the lowestMinorKubernetesVersion property: The highest PATCH Kubernetes version for the lowest applicable + * MINOR version available for the ManagedCluster resource. + * + * @return the lowestMinorKubernetesVersion value. + */ + @Generated + public String getLowestMinorKubernetesVersion() { + return this.lowestMinorKubernetesVersion; + } + + /** + * Get the latestPreviewKubernetesVersion property: The highest PATCH Kubernetes version considered preview for the + * ManagedCluster resource. There might not be any version in preview at the time of publishing the event. + * + * @return the latestPreviewKubernetesVersion value. + */ + @Generated + public String getLatestPreviewKubernetesVersion() { + return this.latestPreviewKubernetesVersion; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("latestSupportedKubernetesVersion", this.latestSupportedKubernetesVersion); + jsonWriter.writeStringField("latestStableKubernetesVersion", this.latestStableKubernetesVersion); + jsonWriter.writeStringField("lowestMinorKubernetesVersion", this.lowestMinorKubernetesVersion); + jsonWriter.writeStringField("latestPreviewKubernetesVersion", this.latestPreviewKubernetesVersion); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ContainerServiceNewKubernetesVersionAvailableEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ContainerServiceNewKubernetesVersionAvailableEventData 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 ContainerServiceNewKubernetesVersionAvailableEventData. + */ + @Generated + public static ContainerServiceNewKubernetesVersionAvailableEventData fromJson(JsonReader jsonReader) + throws IOException { + return jsonReader.readObject(reader -> { + ContainerServiceNewKubernetesVersionAvailableEventData deserializedContainerServiceNewKubernetesVersionAvailableEventData + = new ContainerServiceNewKubernetesVersionAvailableEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("latestSupportedKubernetesVersion".equals(fieldName)) { + deserializedContainerServiceNewKubernetesVersionAvailableEventData.latestSupportedKubernetesVersion + = reader.getString(); + } else if ("latestStableKubernetesVersion".equals(fieldName)) { + deserializedContainerServiceNewKubernetesVersionAvailableEventData.latestStableKubernetesVersion + = reader.getString(); + } else if ("lowestMinorKubernetesVersion".equals(fieldName)) { + deserializedContainerServiceNewKubernetesVersionAvailableEventData.lowestMinorKubernetesVersion + = reader.getString(); + } else if ("latestPreviewKubernetesVersion".equals(fieldName)) { + deserializedContainerServiceNewKubernetesVersionAvailableEventData.latestPreviewKubernetesVersion + = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedContainerServiceNewKubernetesVersionAvailableEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerServiceNodePoolRollingEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerServiceNodePoolRollingEventData.java new file mode 100644 index 000000000000..10ff95349b85 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerServiceNodePoolRollingEventData.java @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of common properties of node pool rolling events. + */ +@Immutable +public class ContainerServiceNodePoolRollingEventData + implements JsonSerializable { + /* + * The name of the node pool in the ManagedCluster resource + */ + @Generated + private String nodePoolName; + + /** + * Creates an instance of ContainerServiceNodePoolRollingEventData class. + */ + @Generated + protected ContainerServiceNodePoolRollingEventData() { + } + + /** + * Get the nodePoolName property: The name of the node pool in the ManagedCluster resource. + * + * @return the nodePoolName value. + */ + @Generated + public String getNodePoolName() { + return this.nodePoolName; + } + + /** + * Set the nodePoolName property: The name of the node pool in the ManagedCluster resource. + * + * @param nodePoolName the nodePoolName value to set. + * @return the ContainerServiceNodePoolRollingEventData object itself. + */ + @Generated + ContainerServiceNodePoolRollingEventData setNodePoolName(String nodePoolName) { + this.nodePoolName = nodePoolName; + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("nodePoolName", this.nodePoolName); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ContainerServiceNodePoolRollingEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ContainerServiceNodePoolRollingEventData 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 ContainerServiceNodePoolRollingEventData. + */ + @Generated + public static ContainerServiceNodePoolRollingEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ContainerServiceNodePoolRollingEventData deserializedContainerServiceNodePoolRollingEventData + = new ContainerServiceNodePoolRollingEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("nodePoolName".equals(fieldName)) { + deserializedContainerServiceNodePoolRollingEventData.nodePoolName = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedContainerServiceNodePoolRollingEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerServiceNodePoolRollingFailedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerServiceNodePoolRollingFailedEventData.java new file mode 100644 index 000000000000..54f016d57e85 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerServiceNodePoolRollingFailedEventData.java @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ContainerService.NodePoolRollingFailed event. + */ +@Immutable +public final class ContainerServiceNodePoolRollingFailedEventData extends ContainerServiceNodePoolRollingEventData { + /* + * The name of the node pool in the ManagedCluster resource + */ + @Generated + private String nodePoolName; + + /** + * Creates an instance of ContainerServiceNodePoolRollingFailedEventData class. + */ + @Generated + private ContainerServiceNodePoolRollingFailedEventData() { + } + + /** + * Get the nodePoolName property: The name of the node pool in the ManagedCluster resource. + * + * @return the nodePoolName value. + */ + @Generated + @Override + public String getNodePoolName() { + return this.nodePoolName; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("nodePoolName", getNodePoolName()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ContainerServiceNodePoolRollingFailedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ContainerServiceNodePoolRollingFailedEventData 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 ContainerServiceNodePoolRollingFailedEventData. + */ + @Generated + public static ContainerServiceNodePoolRollingFailedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ContainerServiceNodePoolRollingFailedEventData deserializedContainerServiceNodePoolRollingFailedEventData + = new ContainerServiceNodePoolRollingFailedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("nodePoolName".equals(fieldName)) { + deserializedContainerServiceNodePoolRollingFailedEventData.nodePoolName = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedContainerServiceNodePoolRollingFailedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerServiceNodePoolRollingStartedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerServiceNodePoolRollingStartedEventData.java new file mode 100644 index 000000000000..adaea8393a2d --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerServiceNodePoolRollingStartedEventData.java @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ContainerService.NodePoolRollingStarted event. + */ +@Immutable +public final class ContainerServiceNodePoolRollingStartedEventData extends ContainerServiceNodePoolRollingEventData { + /* + * The name of the node pool in the ManagedCluster resource + */ + @Generated + private String nodePoolName; + + /** + * Creates an instance of ContainerServiceNodePoolRollingStartedEventData class. + */ + @Generated + private ContainerServiceNodePoolRollingStartedEventData() { + } + + /** + * Get the nodePoolName property: The name of the node pool in the ManagedCluster resource. + * + * @return the nodePoolName value. + */ + @Generated + @Override + public String getNodePoolName() { + return this.nodePoolName; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("nodePoolName", getNodePoolName()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ContainerServiceNodePoolRollingStartedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ContainerServiceNodePoolRollingStartedEventData 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 ContainerServiceNodePoolRollingStartedEventData. + */ + @Generated + public static ContainerServiceNodePoolRollingStartedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ContainerServiceNodePoolRollingStartedEventData deserializedContainerServiceNodePoolRollingStartedEventData + = new ContainerServiceNodePoolRollingStartedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("nodePoolName".equals(fieldName)) { + deserializedContainerServiceNodePoolRollingStartedEventData.nodePoolName = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedContainerServiceNodePoolRollingStartedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerServiceNodePoolRollingSucceededEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerServiceNodePoolRollingSucceededEventData.java new file mode 100644 index 000000000000..7a207bf2810d --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ContainerServiceNodePoolRollingSucceededEventData.java @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ContainerService.NodePoolRollingSucceeded event. + */ +@Immutable +public final class ContainerServiceNodePoolRollingSucceededEventData extends ContainerServiceNodePoolRollingEventData { + /* + * The name of the node pool in the ManagedCluster resource + */ + @Generated + private String nodePoolName; + + /** + * Creates an instance of ContainerServiceNodePoolRollingSucceededEventData class. + */ + @Generated + private ContainerServiceNodePoolRollingSucceededEventData() { + } + + /** + * Get the nodePoolName property: The name of the node pool in the ManagedCluster resource. + * + * @return the nodePoolName value. + */ + @Generated + @Override + public String getNodePoolName() { + return this.nodePoolName; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("nodePoolName", getNodePoolName()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ContainerServiceNodePoolRollingSucceededEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ContainerServiceNodePoolRollingSucceededEventData 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 ContainerServiceNodePoolRollingSucceededEventData. + */ + @Generated + public static ContainerServiceNodePoolRollingSucceededEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ContainerServiceNodePoolRollingSucceededEventData deserializedContainerServiceNodePoolRollingSucceededEventData + = new ContainerServiceNodePoolRollingSucceededEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("nodePoolName".equals(fieldName)) { + deserializedContainerServiceNodePoolRollingSucceededEventData.nodePoolName = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedContainerServiceNodePoolRollingSucceededEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DataBoxCopyCompletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DataBoxCopyCompletedEventData.java new file mode 100644 index 000000000000..ad1c677480b2 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DataBoxCopyCompletedEventData.java @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.DataBox.CopyCompleted event. + */ +@Immutable +public final class DataBoxCopyCompletedEventData implements JsonSerializable { + /* + * Serial Number of the device associated with the event. The list is comma separated if more than one serial number + * is associated. + */ + @Generated + private final String serialNumber; + + /* + * Name of the current Stage + */ + @Generated + private final DataBoxStageName stageName; + + /* + * The time at which the stage happened. + */ + @Generated + private final OffsetDateTime stageTime; + + /** + * Creates an instance of DataBoxCopyCompletedEventData class. + * + * @param serialNumber the serialNumber value to set. + * @param stageName the stageName value to set. + * @param stageTime the stageTime value to set. + */ + @Generated + private DataBoxCopyCompletedEventData(String serialNumber, DataBoxStageName stageName, OffsetDateTime stageTime) { + this.serialNumber = serialNumber; + this.stageName = stageName; + this.stageTime = stageTime; + } + + /** + * Get the serialNumber property: Serial Number of the device associated with the event. The list is comma separated + * if more than one serial number is associated. + * + * @return the serialNumber value. + */ + @Generated + public String getSerialNumber() { + return this.serialNumber; + } + + /** + * Get the stageName property: Name of the current Stage. + * + * @return the stageName value. + */ + @Generated + public DataBoxStageName getStageName() { + return this.stageName; + } + + /** + * Get the stageTime property: The time at which the stage happened. + * + * @return the stageTime value. + */ + @Generated + public OffsetDateTime getStageTime() { + return this.stageTime; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("serialNumber", this.serialNumber); + jsonWriter.writeStringField("stageName", this.stageName == null ? null : this.stageName.toString()); + jsonWriter.writeStringField("stageTime", + this.stageTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.stageTime)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of DataBoxCopyCompletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of DataBoxCopyCompletedEventData 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 DataBoxCopyCompletedEventData. + */ + @Generated + public static DataBoxCopyCompletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String serialNumber = null; + DataBoxStageName stageName = null; + OffsetDateTime stageTime = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("serialNumber".equals(fieldName)) { + serialNumber = reader.getString(); + } else if ("stageName".equals(fieldName)) { + stageName = DataBoxStageName.fromString(reader.getString()); + } else if ("stageTime".equals(fieldName)) { + stageTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else { + reader.skipChildren(); + } + } + return new DataBoxCopyCompletedEventData(serialNumber, stageName, stageTime); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DataBoxCopyStartedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DataBoxCopyStartedEventData.java new file mode 100644 index 000000000000..42f16c25f4a5 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DataBoxCopyStartedEventData.java @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.DataBox.CopyStarted event. + */ +@Immutable +public final class DataBoxCopyStartedEventData implements JsonSerializable { + /* + * Serial Number of the device associated with the event. The list is comma separated if more than one serial number + * is associated. + */ + @Generated + private final String serialNumber; + + /* + * Name of the current Stage + */ + @Generated + private final DataBoxStageName stageName; + + /* + * The time at which the stage happened. + */ + @Generated + private final OffsetDateTime stageTime; + + /** + * Creates an instance of DataBoxCopyStartedEventData class. + * + * @param serialNumber the serialNumber value to set. + * @param stageName the stageName value to set. + * @param stageTime the stageTime value to set. + */ + @Generated + private DataBoxCopyStartedEventData(String serialNumber, DataBoxStageName stageName, OffsetDateTime stageTime) { + this.serialNumber = serialNumber; + this.stageName = stageName; + this.stageTime = stageTime; + } + + /** + * Get the serialNumber property: Serial Number of the device associated with the event. The list is comma separated + * if more than one serial number is associated. + * + * @return the serialNumber value. + */ + @Generated + public String getSerialNumber() { + return this.serialNumber; + } + + /** + * Get the stageName property: Name of the current Stage. + * + * @return the stageName value. + */ + @Generated + public DataBoxStageName getStageName() { + return this.stageName; + } + + /** + * Get the stageTime property: The time at which the stage happened. + * + * @return the stageTime value. + */ + @Generated + public OffsetDateTime getStageTime() { + return this.stageTime; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("serialNumber", this.serialNumber); + jsonWriter.writeStringField("stageName", this.stageName == null ? null : this.stageName.toString()); + jsonWriter.writeStringField("stageTime", + this.stageTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.stageTime)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of DataBoxCopyStartedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of DataBoxCopyStartedEventData 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 DataBoxCopyStartedEventData. + */ + @Generated + public static DataBoxCopyStartedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String serialNumber = null; + DataBoxStageName stageName = null; + OffsetDateTime stageTime = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("serialNumber".equals(fieldName)) { + serialNumber = reader.getString(); + } else if ("stageName".equals(fieldName)) { + stageName = DataBoxStageName.fromString(reader.getString()); + } else if ("stageTime".equals(fieldName)) { + stageTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else { + reader.skipChildren(); + } + } + return new DataBoxCopyStartedEventData(serialNumber, stageName, stageTime); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DataBoxOrderCompletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DataBoxOrderCompletedEventData.java new file mode 100644 index 000000000000..9cc8dda8ac40 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DataBoxOrderCompletedEventData.java @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.DataBox.OrderCompleted event. + */ +@Immutable +public final class DataBoxOrderCompletedEventData implements JsonSerializable { + /* + * Serial Number of the device associated with the event. The list is comma separated if more than one serial number + * is associated. + */ + @Generated + private final String serialNumber; + + /* + * Name of the current Stage + */ + @Generated + private final DataBoxStageName stageName; + + /* + * The time at which the stage happened. + */ + @Generated + private final OffsetDateTime stageTime; + + /** + * Creates an instance of DataBoxOrderCompletedEventData class. + * + * @param serialNumber the serialNumber value to set. + * @param stageName the stageName value to set. + * @param stageTime the stageTime value to set. + */ + @Generated + private DataBoxOrderCompletedEventData(String serialNumber, DataBoxStageName stageName, OffsetDateTime stageTime) { + this.serialNumber = serialNumber; + this.stageName = stageName; + this.stageTime = stageTime; + } + + /** + * Get the serialNumber property: Serial Number of the device associated with the event. The list is comma separated + * if more than one serial number is associated. + * + * @return the serialNumber value. + */ + @Generated + public String getSerialNumber() { + return this.serialNumber; + } + + /** + * Get the stageName property: Name of the current Stage. + * + * @return the stageName value. + */ + @Generated + public DataBoxStageName getStageName() { + return this.stageName; + } + + /** + * Get the stageTime property: The time at which the stage happened. + * + * @return the stageTime value. + */ + @Generated + public OffsetDateTime getStageTime() { + return this.stageTime; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("serialNumber", this.serialNumber); + jsonWriter.writeStringField("stageName", this.stageName == null ? null : this.stageName.toString()); + jsonWriter.writeStringField("stageTime", + this.stageTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.stageTime)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of DataBoxOrderCompletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of DataBoxOrderCompletedEventData 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 DataBoxOrderCompletedEventData. + */ + @Generated + public static DataBoxOrderCompletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String serialNumber = null; + DataBoxStageName stageName = null; + OffsetDateTime stageTime = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("serialNumber".equals(fieldName)) { + serialNumber = reader.getString(); + } else if ("stageName".equals(fieldName)) { + stageName = DataBoxStageName.fromString(reader.getString()); + } else if ("stageTime".equals(fieldName)) { + stageTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else { + reader.skipChildren(); + } + } + return new DataBoxOrderCompletedEventData(serialNumber, stageName, stageTime); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DataBoxStageName.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DataBoxStageName.java new file mode 100644 index 000000000000..6d2887821e77 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DataBoxStageName.java @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Schema of DataBox Stage Name enumeration. + */ +public final class DataBoxStageName extends ExpandableStringEnum { + /** + * Copy has started. + */ + @Generated + public static final DataBoxStageName COPY_STARTED = fromString("CopyStarted"); + + /** + * Copy has completed. + */ + @Generated + public static final DataBoxStageName COPY_COMPLETED = fromString("CopyCompleted"); + + /** + * Order has been completed. + */ + @Generated + public static final DataBoxStageName ORDER_COMPLETED = fromString("OrderCompleted"); + + /** + * Creates a new instance of DataBoxStageName value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public DataBoxStageName() { + } + + /** + * Creates or finds a DataBoxStageName from its string representation. + * + * @param name a name to look for. + * @return the corresponding DataBoxStageName. + */ + @Generated + public static DataBoxStageName fromString(String name) { + return fromString(name, DataBoxStageName.class); + } + + /** + * Gets known DataBoxStageName values. + * + * @return known DataBoxStageName values. + */ + @Generated + public static Collection values() { + return values(DataBoxStageName.class); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DeviceConnectionStateEventInfo.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DeviceConnectionStateEventInfo.java new file mode 100644 index 000000000000..0a5e0fa3a6ca --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DeviceConnectionStateEventInfo.java @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Information about the device connection state event. + */ +@Immutable +public final class DeviceConnectionStateEventInfo implements JsonSerializable { + /* + * Sequence number is string representation of a hexadecimal number. string compare can be used to identify the + * larger number because both in ASCII and HEX numbers come after alphabets. If you are converting the string to + * hex, then the number is a 256 bit number. + */ + @Generated + private final String sequenceNumber; + + /** + * Creates an instance of DeviceConnectionStateEventInfo class. + * + * @param sequenceNumber the sequenceNumber value to set. + */ + @Generated + private DeviceConnectionStateEventInfo(String sequenceNumber) { + this.sequenceNumber = sequenceNumber; + } + + /** + * Get the sequenceNumber property: Sequence number is string representation of a hexadecimal number. string compare + * can be used to identify the larger number because both in ASCII and HEX numbers come after alphabets. If you are + * converting the string to hex, then the number is a 256 bit number. + * + * @return the sequenceNumber value. + */ + @Generated + public String getSequenceNumber() { + return this.sequenceNumber; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("sequenceNumber", this.sequenceNumber); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of DeviceConnectionStateEventInfo from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of DeviceConnectionStateEventInfo 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 DeviceConnectionStateEventInfo. + */ + @Generated + public static DeviceConnectionStateEventInfo fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String sequenceNumber = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("sequenceNumber".equals(fieldName)) { + sequenceNumber = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new DeviceConnectionStateEventInfo(sequenceNumber); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DeviceConnectionStateEventProperties.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DeviceConnectionStateEventProperties.java new file mode 100644 index 000000000000..6483e4e328f3 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DeviceConnectionStateEventProperties.java @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a device connection state event (DeviceConnected, + * DeviceDisconnected). + */ +@Immutable +public class DeviceConnectionStateEventProperties implements JsonSerializable { + /* + * The unique identifier of the device. This case-sensitive string can be up to 128 characters long, and supports + * ASCII 7-bit alphanumeric characters plus the following special characters: - : . + % _ # * ? ! ( ) , = `@` ; + * $ '. + */ + @Generated + private final String deviceId; + + /* + * The unique identifier of the module. This case-sensitive string can be up to 128 characters long, and supports + * ASCII 7-bit alphanumeric characters plus the following special characters: - : . + % _ # * ? ! ( ) , = `@` ; + * $ '. + */ + @Generated + private String moduleId; + + /* + * Name of the IoT Hub where the device was created or deleted. + */ + @Generated + private final String hubName; + + /* + * Information about the device connection state event. + */ + @Generated + private final DeviceConnectionStateEventInfo deviceConnectionStateEventInfo; + + /** + * Creates an instance of DeviceConnectionStateEventProperties class. + * + * @param deviceId the deviceId value to set. + * @param hubName the hubName value to set. + * @param deviceConnectionStateEventInfo the deviceConnectionStateEventInfo value to set. + */ + @Generated + protected DeviceConnectionStateEventProperties(String deviceId, String hubName, + DeviceConnectionStateEventInfo deviceConnectionStateEventInfo) { + this.deviceId = deviceId; + this.hubName = hubName; + this.deviceConnectionStateEventInfo = deviceConnectionStateEventInfo; + } + + /** + * Get the deviceId property: The unique identifier of the device. This case-sensitive string can be up to 128 + * characters long, and supports ASCII 7-bit alphanumeric characters plus the following special characters: - : . + + * % _ &#35; * ? ! ( ) , = `@` ; $ '. + * + * @return the deviceId value. + */ + @Generated + public String getDeviceId() { + return this.deviceId; + } + + /** + * Get the moduleId property: The unique identifier of the module. This case-sensitive string can be up to 128 + * characters long, and supports ASCII 7-bit alphanumeric characters plus the following special characters: - : . + + * % _ &#35; * ? ! ( ) , = `@` ; $ '. + * + * @return the moduleId value. + */ + @Generated + public String getModuleId() { + return this.moduleId; + } + + /** + * Set the moduleId property: The unique identifier of the module. This case-sensitive string can be up to 128 + * characters long, and supports ASCII 7-bit alphanumeric characters plus the following special characters: - : . + + * % _ &#35; * ? ! ( ) , = `@` ; $ '. + * + * @param moduleId the moduleId value to set. + * @return the DeviceConnectionStateEventProperties object itself. + */ + @Generated + DeviceConnectionStateEventProperties setModuleId(String moduleId) { + this.moduleId = moduleId; + return this; + } + + /** + * Get the hubName property: Name of the IoT Hub where the device was created or deleted. + * + * @return the hubName value. + */ + @Generated + public String getHubName() { + return this.hubName; + } + + /** + * Get the deviceConnectionStateEventInfo property: Information about the device connection state event. + * + * @return the deviceConnectionStateEventInfo value. + */ + @Generated + public DeviceConnectionStateEventInfo getDeviceConnectionStateEventInfo() { + return this.deviceConnectionStateEventInfo; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("deviceId", this.deviceId); + jsonWriter.writeStringField("hubName", this.hubName); + jsonWriter.writeJsonField("deviceConnectionStateEventInfo", this.deviceConnectionStateEventInfo); + jsonWriter.writeStringField("moduleId", this.moduleId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of DeviceConnectionStateEventProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of DeviceConnectionStateEventProperties 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 DeviceConnectionStateEventProperties. + */ + @Generated + public static DeviceConnectionStateEventProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String deviceId = null; + String hubName = null; + DeviceConnectionStateEventInfo deviceConnectionStateEventInfo = null; + String moduleId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("deviceId".equals(fieldName)) { + deviceId = reader.getString(); + } else if ("hubName".equals(fieldName)) { + hubName = reader.getString(); + } else if ("deviceConnectionStateEventInfo".equals(fieldName)) { + deviceConnectionStateEventInfo = DeviceConnectionStateEventInfo.fromJson(reader); + } else if ("moduleId".equals(fieldName)) { + moduleId = reader.getString(); + } else { + reader.skipChildren(); + } + } + DeviceConnectionStateEventProperties deserializedDeviceConnectionStateEventProperties + = new DeviceConnectionStateEventProperties(deviceId, hubName, deviceConnectionStateEventInfo); + deserializedDeviceConnectionStateEventProperties.moduleId = moduleId; + + return deserializedDeviceConnectionStateEventProperties; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DeviceLifeCycleEventProperties.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DeviceLifeCycleEventProperties.java new file mode 100644 index 000000000000..cc40b9f72621 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DeviceLifeCycleEventProperties.java @@ -0,0 +1,132 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a device life cycle event (DeviceCreated, DeviceDeleted). + */ +@Immutable +public class DeviceLifeCycleEventProperties implements JsonSerializable { + /* + * The unique identifier of the device. This case-sensitive string can be up to 128 characters long, and supports + * ASCII 7-bit alphanumeric characters plus the following special characters: - : . + % _ # * ? ! ( ) , = `@` ; + * $ '. + */ + @Generated + private final String deviceId; + + /* + * Name of the IoT Hub where the device was created or deleted. + */ + @Generated + private final String hubName; + + /* + * Information about the device twin, which is the cloud representation of application device metadata. + */ + @Generated + private final DeviceTwinInfo twin; + + /** + * Creates an instance of DeviceLifeCycleEventProperties class. + * + * @param deviceId the deviceId value to set. + * @param hubName the hubName value to set. + * @param twin the twin value to set. + */ + @Generated + protected DeviceLifeCycleEventProperties(String deviceId, String hubName, DeviceTwinInfo twin) { + this.deviceId = deviceId; + this.hubName = hubName; + this.twin = twin; + } + + /** + * Get the deviceId property: The unique identifier of the device. This case-sensitive string can be up to 128 + * characters long, and supports ASCII 7-bit alphanumeric characters plus the following special characters: - : . + + * % _ &#35; * ? ! ( ) , = `@` ; $ '. + * + * @return the deviceId value. + */ + @Generated + public String getDeviceId() { + return this.deviceId; + } + + /** + * Get the hubName property: Name of the IoT Hub where the device was created or deleted. + * + * @return the hubName value. + */ + @Generated + public String getHubName() { + return this.hubName; + } + + /** + * Get the twin property: Information about the device twin, which is the cloud representation of application device + * metadata. + * + * @return the twin value. + */ + @Generated + public DeviceTwinInfo getTwin() { + return this.twin; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("deviceId", this.deviceId); + jsonWriter.writeStringField("hubName", this.hubName); + jsonWriter.writeJsonField("twin", this.twin); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of DeviceLifeCycleEventProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of DeviceLifeCycleEventProperties 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 DeviceLifeCycleEventProperties. + */ + @Generated + public static DeviceLifeCycleEventProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String deviceId = null; + String hubName = null; + DeviceTwinInfo twin = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("deviceId".equals(fieldName)) { + deviceId = reader.getString(); + } else if ("hubName".equals(fieldName)) { + hubName = reader.getString(); + } else if ("twin".equals(fieldName)) { + twin = DeviceTwinInfo.fromJson(reader); + } else { + reader.skipChildren(); + } + } + return new DeviceLifeCycleEventProperties(deviceId, hubName, twin); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DeviceTelemetryEventProperties.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DeviceTelemetryEventProperties.java new file mode 100644 index 000000000000..2150b95b734d --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DeviceTelemetryEventProperties.java @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.BinaryData; +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.Map; + +/** + * Schema of the Data property of an EventGridEvent for a device telemetry event (DeviceTelemetry). + */ +@Immutable +public class DeviceTelemetryEventProperties implements JsonSerializable { + /* + * The content of the message from the device. + */ + @Generated + private final Map body; + + /* + * Application properties are user-defined strings that can be added to the message. These fields are optional. + */ + @Generated + private final Map properties; + + /* + * System properties help identify contents and source of the messages. + */ + @Generated + private final Map systemProperties; + + /** + * Creates an instance of DeviceTelemetryEventProperties class. + * + * @param body the body value to set. + * @param properties the properties value to set. + * @param systemProperties the systemProperties value to set. + */ + @Generated + protected DeviceTelemetryEventProperties(Map body, Map properties, + Map systemProperties) { + this.body = body; + this.properties = properties; + this.systemProperties = systemProperties; + } + + /** + * Get the body property: The content of the message from the device. + * + * @return the body value. + */ + @Generated + public Map getBody() { + return this.body; + } + + /** + * Get the properties property: Application properties are user-defined strings that can be added to the message. + * These fields are optional. + * + * @return the properties value. + */ + @Generated + public Map getProperties() { + return this.properties; + } + + /** + * Get the systemProperties property: System properties help identify contents and source of the messages. + * + * @return the systemProperties value. + */ + @Generated + public Map getSystemProperties() { + return this.systemProperties; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("body", this.body, + (writer, element) -> writer.writeUntyped(element == null ? null : element.toObject(Object.class))); + jsonWriter.writeMapField("properties", this.properties, (writer, element) -> writer.writeString(element)); + jsonWriter.writeMapField("systemProperties", this.systemProperties, + (writer, element) -> writer.writeString(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of DeviceTelemetryEventProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of DeviceTelemetryEventProperties 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 DeviceTelemetryEventProperties. + */ + @Generated + public static DeviceTelemetryEventProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Map body = null; + Map properties = null; + Map systemProperties = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("body".equals(fieldName)) { + body = reader.readMap(reader1 -> reader1 + .getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); + } else if ("properties".equals(fieldName)) { + properties = reader.readMap(reader1 -> reader1.getString()); + } else if ("systemProperties".equals(fieldName)) { + systemProperties = reader.readMap(reader1 -> reader1.getString()); + } else { + reader.skipChildren(); + } + } + return new DeviceTelemetryEventProperties(body, properties, systemProperties); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DeviceTwinInfo.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DeviceTwinInfo.java new file mode 100644 index 000000000000..f784538f80c8 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DeviceTwinInfo.java @@ -0,0 +1,313 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Information about the device twin, which is the cloud representation of application device metadata. + */ +@Immutable +public final class DeviceTwinInfo implements JsonSerializable { + /* + * Authentication type used for this device: either SAS, SelfSigned, or CertificateAuthority. + */ + @Generated + private final String authenticationType; + + /* + * Count of cloud to device messages sent to this device. + */ + @Generated + private final double cloudToDeviceMessageCount; + + /* + * Whether the device is connected or disconnected. + */ + @Generated + private final String connectionState; + + /* + * The unique identifier of the device twin. + */ + @Generated + private final String deviceId; + + /* + * A piece of information that describes the content of the device twin. Each etag is guaranteed to be unique per + * device twin. + */ + @Generated + private final String etag; + + /* + * The ISO8601 timestamp of the last activity. + */ + @Generated + private final String lastActivityTime; + + /* + * Properties JSON element. + */ + @Generated + private final DeviceTwinInfoProperties properties; + + /* + * Whether the device twin is enabled or disabled. + */ + @Generated + private final String status; + + /* + * The ISO8601 timestamp of the last device twin status update. + */ + @Generated + private final String statusUpdateTime; + + /* + * An integer that is incremented by one each time the device twin is updated. + */ + @Generated + private final double version; + + /* + * The thumbprint is a unique value for the x509 certificate, commonly used to find a particular certificate in a + * certificate store. The thumbprint is dynamically generated using the SHA1 algorithm, and does not physically + * exist in the certificate. + */ + @Generated + private final DeviceTwinInfoX509Thumbprint x509Thumbprint; + + /** + * Creates an instance of DeviceTwinInfo class. + * + * @param authenticationType the authenticationType value to set. + * @param cloudToDeviceMessageCount the cloudToDeviceMessageCount value to set. + * @param connectionState the connectionState value to set. + * @param deviceId the deviceId value to set. + * @param etag the etag value to set. + * @param lastActivityTime the lastActivityTime value to set. + * @param properties the properties value to set. + * @param status the status value to set. + * @param statusUpdateTime the statusUpdateTime value to set. + * @param version the version value to set. + * @param x509Thumbprint the x509Thumbprint value to set. + */ + @Generated + private DeviceTwinInfo(String authenticationType, double cloudToDeviceMessageCount, String connectionState, + String deviceId, String etag, String lastActivityTime, DeviceTwinInfoProperties properties, String status, + String statusUpdateTime, double version, DeviceTwinInfoX509Thumbprint x509Thumbprint) { + this.authenticationType = authenticationType; + this.cloudToDeviceMessageCount = cloudToDeviceMessageCount; + this.connectionState = connectionState; + this.deviceId = deviceId; + this.etag = etag; + this.lastActivityTime = lastActivityTime; + this.properties = properties; + this.status = status; + this.statusUpdateTime = statusUpdateTime; + this.version = version; + this.x509Thumbprint = x509Thumbprint; + } + + /** + * Get the authenticationType property: Authentication type used for this device: either SAS, SelfSigned, or + * CertificateAuthority. + * + * @return the authenticationType value. + */ + @Generated + public String getAuthenticationType() { + return this.authenticationType; + } + + /** + * Get the cloudToDeviceMessageCount property: Count of cloud to device messages sent to this device. + * + * @return the cloudToDeviceMessageCount value. + */ + @Generated + public double getCloudToDeviceMessageCount() { + return this.cloudToDeviceMessageCount; + } + + /** + * Get the connectionState property: Whether the device is connected or disconnected. + * + * @return the connectionState value. + */ + @Generated + public String getConnectionState() { + return this.connectionState; + } + + /** + * Get the deviceId property: The unique identifier of the device twin. + * + * @return the deviceId value. + */ + @Generated + public String getDeviceId() { + return this.deviceId; + } + + /** + * Get the etag property: A piece of information that describes the content of the device twin. Each etag is + * guaranteed to be unique per device twin. + * + * @return the etag value. + */ + @Generated + public String getEtag() { + return this.etag; + } + + /** + * Get the lastActivityTime property: The ISO8601 timestamp of the last activity. + * + * @return the lastActivityTime value. + */ + @Generated + public String getLastActivityTime() { + return this.lastActivityTime; + } + + /** + * Get the properties property: Properties JSON element. + * + * @return the properties value. + */ + @Generated + public DeviceTwinInfoProperties getProperties() { + return this.properties; + } + + /** + * Get the status property: Whether the device twin is enabled or disabled. + * + * @return the status value. + */ + @Generated + public String getStatus() { + return this.status; + } + + /** + * Get the statusUpdateTime property: The ISO8601 timestamp of the last device twin status update. + * + * @return the statusUpdateTime value. + */ + @Generated + public String getStatusUpdateTime() { + return this.statusUpdateTime; + } + + /** + * Get the version property: An integer that is incremented by one each time the device twin is updated. + * + * @return the version value. + */ + @Generated + public double getVersion() { + return this.version; + } + + /** + * Get the x509Thumbprint property: The thumbprint is a unique value for the x509 certificate, commonly used to find + * a particular certificate in a certificate store. The thumbprint is dynamically generated using the SHA1 + * algorithm, and does not physically exist in the certificate. + * + * @return the x509Thumbprint value. + */ + @Generated + public DeviceTwinInfoX509Thumbprint getX509Thumbprint() { + return this.x509Thumbprint; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("authenticationType", this.authenticationType); + jsonWriter.writeDoubleField("cloudToDeviceMessageCount", this.cloudToDeviceMessageCount); + jsonWriter.writeStringField("connectionState", this.connectionState); + jsonWriter.writeStringField("deviceId", this.deviceId); + jsonWriter.writeStringField("etag", this.etag); + jsonWriter.writeStringField("lastActivityTime", this.lastActivityTime); + jsonWriter.writeJsonField("properties", this.properties); + jsonWriter.writeStringField("status", this.status); + jsonWriter.writeStringField("statusUpdateTime", this.statusUpdateTime); + jsonWriter.writeDoubleField("version", this.version); + jsonWriter.writeJsonField("x509Thumbprint", this.x509Thumbprint); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of DeviceTwinInfo from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of DeviceTwinInfo 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 DeviceTwinInfo. + */ + @Generated + public static DeviceTwinInfo fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String authenticationType = null; + double cloudToDeviceMessageCount = 0.0; + String connectionState = null; + String deviceId = null; + String etag = null; + String lastActivityTime = null; + DeviceTwinInfoProperties properties = null; + String status = null; + String statusUpdateTime = null; + double version = 0.0; + DeviceTwinInfoX509Thumbprint x509Thumbprint = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("authenticationType".equals(fieldName)) { + authenticationType = reader.getString(); + } else if ("cloudToDeviceMessageCount".equals(fieldName)) { + cloudToDeviceMessageCount = reader.getDouble(); + } else if ("connectionState".equals(fieldName)) { + connectionState = reader.getString(); + } else if ("deviceId".equals(fieldName)) { + deviceId = reader.getString(); + } else if ("etag".equals(fieldName)) { + etag = reader.getString(); + } else if ("lastActivityTime".equals(fieldName)) { + lastActivityTime = reader.getString(); + } else if ("properties".equals(fieldName)) { + properties = DeviceTwinInfoProperties.fromJson(reader); + } else if ("status".equals(fieldName)) { + status = reader.getString(); + } else if ("statusUpdateTime".equals(fieldName)) { + statusUpdateTime = reader.getString(); + } else if ("version".equals(fieldName)) { + version = reader.getDouble(); + } else if ("x509Thumbprint".equals(fieldName)) { + x509Thumbprint = DeviceTwinInfoX509Thumbprint.fromJson(reader); + } else { + reader.skipChildren(); + } + } + return new DeviceTwinInfo(authenticationType, cloudToDeviceMessageCount, connectionState, deviceId, etag, + lastActivityTime, properties, status, statusUpdateTime, version, x509Thumbprint); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DeviceTwinInfoProperties.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DeviceTwinInfoProperties.java new file mode 100644 index 000000000000..993dd06c1631 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DeviceTwinInfoProperties.java @@ -0,0 +1,107 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Properties JSON element. + */ +@Immutable +public final class DeviceTwinInfoProperties implements JsonSerializable { + /* + * A portion of the properties that can be written only by the application back-end, and read by the device. + */ + @Generated + private final DeviceTwinProperties desired; + + /* + * A portion of the properties that can be written only by the device, and read by the application back-end. + */ + @Generated + private final DeviceTwinProperties reported; + + /** + * Creates an instance of DeviceTwinInfoProperties class. + * + * @param desired the desired value to set. + * @param reported the reported value to set. + */ + @Generated + private DeviceTwinInfoProperties(DeviceTwinProperties desired, DeviceTwinProperties reported) { + this.desired = desired; + this.reported = reported; + } + + /** + * Get the desired property: A portion of the properties that can be written only by the application back-end, and + * read by the device. + * + * @return the desired value. + */ + @Generated + public DeviceTwinProperties getDesired() { + return this.desired; + } + + /** + * Get the reported property: A portion of the properties that can be written only by the device, and read by the + * application back-end. + * + * @return the reported value. + */ + @Generated + public DeviceTwinProperties getReported() { + return this.reported; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("desired", this.desired); + jsonWriter.writeJsonField("reported", this.reported); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of DeviceTwinInfoProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of DeviceTwinInfoProperties 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 DeviceTwinInfoProperties. + */ + @Generated + public static DeviceTwinInfoProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + DeviceTwinProperties desired = null; + DeviceTwinProperties reported = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("desired".equals(fieldName)) { + desired = DeviceTwinProperties.fromJson(reader); + } else if ("reported".equals(fieldName)) { + reported = DeviceTwinProperties.fromJson(reader); + } else { + reader.skipChildren(); + } + } + return new DeviceTwinInfoProperties(desired, reported); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DeviceTwinInfoX509Thumbprint.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DeviceTwinInfoX509Thumbprint.java new file mode 100644 index 000000000000..7f2a49c50fa1 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DeviceTwinInfoX509Thumbprint.java @@ -0,0 +1,107 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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 thumbprint is a unique value for the x509 certificate, commonly used to find a particular certificate in a + * certificate store. The thumbprint is dynamically generated using the SHA1 algorithm, and does not physically exist in + * the certificate. + */ +@Immutable +public final class DeviceTwinInfoX509Thumbprint implements JsonSerializable { + /* + * Primary thumbprint for the x509 certificate. + */ + @Generated + private final String primaryThumbprint; + + /* + * Secondary thumbprint for the x509 certificate. + */ + @Generated + private final String secondaryThumbprint; + + /** + * Creates an instance of DeviceTwinInfoX509Thumbprint class. + * + * @param primaryThumbprint the primaryThumbprint value to set. + * @param secondaryThumbprint the secondaryThumbprint value to set. + */ + @Generated + private DeviceTwinInfoX509Thumbprint(String primaryThumbprint, String secondaryThumbprint) { + this.primaryThumbprint = primaryThumbprint; + this.secondaryThumbprint = secondaryThumbprint; + } + + /** + * Get the primaryThumbprint property: Primary thumbprint for the x509 certificate. + * + * @return the primaryThumbprint value. + */ + @Generated + public String getPrimaryThumbprint() { + return this.primaryThumbprint; + } + + /** + * Get the secondaryThumbprint property: Secondary thumbprint for the x509 certificate. + * + * @return the secondaryThumbprint value. + */ + @Generated + public String getSecondaryThumbprint() { + return this.secondaryThumbprint; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("primaryThumbprint", this.primaryThumbprint); + jsonWriter.writeStringField("secondaryThumbprint", this.secondaryThumbprint); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of DeviceTwinInfoX509Thumbprint from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of DeviceTwinInfoX509Thumbprint 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 DeviceTwinInfoX509Thumbprint. + */ + @Generated + public static DeviceTwinInfoX509Thumbprint fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String primaryThumbprint = null; + String secondaryThumbprint = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("primaryThumbprint".equals(fieldName)) { + primaryThumbprint = reader.getString(); + } else if ("secondaryThumbprint".equals(fieldName)) { + secondaryThumbprint = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new DeviceTwinInfoX509Thumbprint(primaryThumbprint, secondaryThumbprint); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DeviceTwinMetadata.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DeviceTwinMetadata.java new file mode 100644 index 000000000000..e6d62edaf381 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DeviceTwinMetadata.java @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Metadata information for the properties JSON document. + */ +@Immutable +public final class DeviceTwinMetadata implements JsonSerializable { + /* + * The ISO8601 timestamp of the last time the properties were updated. + */ + @Generated + private final String lastUpdated; + + /** + * Creates an instance of DeviceTwinMetadata class. + * + * @param lastUpdated the lastUpdated value to set. + */ + @Generated + private DeviceTwinMetadata(String lastUpdated) { + this.lastUpdated = lastUpdated; + } + + /** + * Get the lastUpdated property: The ISO8601 timestamp of the last time the properties were updated. + * + * @return the lastUpdated value. + */ + @Generated + public String getLastUpdated() { + return this.lastUpdated; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("lastUpdated", this.lastUpdated); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of DeviceTwinMetadata from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of DeviceTwinMetadata 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 DeviceTwinMetadata. + */ + @Generated + public static DeviceTwinMetadata fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String lastUpdated = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("lastUpdated".equals(fieldName)) { + lastUpdated = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new DeviceTwinMetadata(lastUpdated); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DeviceTwinProperties.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DeviceTwinProperties.java new file mode 100644 index 000000000000..0c4835a76991 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/DeviceTwinProperties.java @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * A portion of the properties that can be written only by the application back-end, and read by the device. + */ +@Immutable +public final class DeviceTwinProperties implements JsonSerializable { + /* + * Metadata information for the properties JSON document. + */ + @Generated + private final DeviceTwinMetadata metadata; + + /* + * Version of device twin properties. + */ + @Generated + private final double version; + + /** + * Creates an instance of DeviceTwinProperties class. + * + * @param metadata the metadata value to set. + * @param version the version value to set. + */ + @Generated + private DeviceTwinProperties(DeviceTwinMetadata metadata, double version) { + this.metadata = metadata; + this.version = version; + } + + /** + * Get the metadata property: Metadata information for the properties JSON document. + * + * @return the metadata value. + */ + @Generated + public DeviceTwinMetadata getMetadata() { + return this.metadata; + } + + /** + * Get the version property: Version of device twin properties. + * + * @return the version value. + */ + @Generated + public double getVersion() { + return this.version; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("metadata", this.metadata); + jsonWriter.writeDoubleField("version", this.version); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of DeviceTwinProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of DeviceTwinProperties 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 DeviceTwinProperties. + */ + @Generated + public static DeviceTwinProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + DeviceTwinMetadata metadata = null; + double version = 0.0; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("metadata".equals(fieldName)) { + metadata = DeviceTwinMetadata.fromJson(reader); + } else if ("version".equals(fieldName)) { + version = reader.getDouble(); + } else { + reader.skipChildren(); + } + } + return new DeviceTwinProperties(metadata, version); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/EventGridMqttClientCreatedOrUpdatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/EventGridMqttClientCreatedOrUpdatedEventData.java new file mode 100644 index 000000000000..bf4fddded4cf --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/EventGridMqttClientCreatedOrUpdatedEventData.java @@ -0,0 +1,179 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Map; + +/** + * Event data for Microsoft.EventGrid.MQTTClientCreatedOrUpdated event. + */ +@Immutable +public final class EventGridMqttClientCreatedOrUpdatedEventData extends EventGridMqttClientEventData { + /* + * Configured state of the client. The value could be Enabled or Disabled + */ + @Generated + private final EventGridMqttClientState state; + + /* + * Time the client resource is created based on the provider's UTC time. + */ + @Generated + private final OffsetDateTime createdOn; + + /* + * Time the client resource is last updated based on the provider's UTC time. If + * the client resource was never updated, this value is identical to the value of + * the 'createdOn' property. + */ + @Generated + private final OffsetDateTime updatedOn; + + /* + * The key-value attributes that are assigned to the client resource. + */ + @Generated + private final Map attributes; + + /** + * Creates an instance of EventGridMqttClientCreatedOrUpdatedEventData class. + * + * @param clientAuthenticationName the clientAuthenticationName value to set. + * @param clientName the clientName value to set. + * @param namespaceName the namespaceName value to set. + * @param state the state value to set. + * @param createdOn the createdOn value to set. + * @param updatedOn the updatedOn value to set. + * @param attributes the attributes value to set. + */ + @Generated + private EventGridMqttClientCreatedOrUpdatedEventData(String clientAuthenticationName, String clientName, + String namespaceName, EventGridMqttClientState state, OffsetDateTime createdOn, OffsetDateTime updatedOn, + Map attributes) { + super(clientAuthenticationName, clientName, namespaceName); + this.state = state; + this.createdOn = createdOn; + this.updatedOn = updatedOn; + this.attributes = attributes; + } + + /** + * Get the state property: Configured state of the client. The value could be Enabled or Disabled. + * + * @return the state value. + */ + @Generated + public EventGridMqttClientState getState() { + return this.state; + } + + /** + * Get the createdOn property: Time the client resource is created based on the provider's UTC time. + * + * @return the createdOn value. + */ + @Generated + public OffsetDateTime getCreatedOn() { + return this.createdOn; + } + + /** + * Get the updatedOn property: Time the client resource is last updated based on the provider's UTC time. If + * the client resource was never updated, this value is identical to the value of + * the 'createdOn' property. + * + * @return the updatedOn value. + */ + @Generated + public OffsetDateTime getUpdatedOn() { + return this.updatedOn; + } + + /** + * Get the attributes property: The key-value attributes that are assigned to the client resource. + * + * @return the attributes value. + */ + @Generated + public Map getAttributes() { + return this.attributes; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("clientAuthenticationName", getClientAuthenticationName()); + jsonWriter.writeStringField("clientName", getClientName()); + jsonWriter.writeStringField("namespaceName", getNamespaceName()); + jsonWriter.writeStringField("state", this.state == null ? null : this.state.toString()); + jsonWriter.writeStringField("createdOn", + this.createdOn == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.createdOn)); + jsonWriter.writeStringField("updatedOn", + this.updatedOn == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.updatedOn)); + jsonWriter.writeMapField("attributes", this.attributes, (writer, element) -> writer.writeString(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of EventGridMqttClientCreatedOrUpdatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of EventGridMqttClientCreatedOrUpdatedEventData 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 EventGridMqttClientCreatedOrUpdatedEventData. + */ + @Generated + public static EventGridMqttClientCreatedOrUpdatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String clientAuthenticationName = null; + String clientName = null; + String namespaceName = null; + EventGridMqttClientState state = null; + OffsetDateTime createdOn = null; + OffsetDateTime updatedOn = null; + Map attributes = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("clientAuthenticationName".equals(fieldName)) { + clientAuthenticationName = reader.getString(); + } else if ("clientName".equals(fieldName)) { + clientName = reader.getString(); + } else if ("namespaceName".equals(fieldName)) { + namespaceName = reader.getString(); + } else if ("state".equals(fieldName)) { + state = EventGridMqttClientState.fromString(reader.getString()); + } else if ("createdOn".equals(fieldName)) { + createdOn = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("updatedOn".equals(fieldName)) { + updatedOn = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("attributes".equals(fieldName)) { + attributes = reader.readMap(reader1 -> reader1.getString()); + } else { + reader.skipChildren(); + } + } + return new EventGridMqttClientCreatedOrUpdatedEventData(clientAuthenticationName, clientName, namespaceName, + state, createdOn, updatedOn, attributes); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/EventGridMqttClientDeletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/EventGridMqttClientDeletedEventData.java new file mode 100644 index 000000000000..3c8dae3b90c3 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/EventGridMqttClientDeletedEventData.java @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Event data for Microsoft.EventGrid.MQTTClientDeleted event. + */ +@Immutable +public final class EventGridMqttClientDeletedEventData extends EventGridMqttClientEventData { + /** + * Creates an instance of EventGridMqttClientDeletedEventData class. + * + * @param clientAuthenticationName the clientAuthenticationName value to set. + * @param clientName the clientName value to set. + * @param namespaceName the namespaceName value to set. + */ + @Generated + private EventGridMqttClientDeletedEventData(String clientAuthenticationName, String clientName, + String namespaceName) { + super(clientAuthenticationName, clientName, namespaceName); + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("clientAuthenticationName", getClientAuthenticationName()); + jsonWriter.writeStringField("clientName", getClientName()); + jsonWriter.writeStringField("namespaceName", getNamespaceName()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of EventGridMqttClientDeletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of EventGridMqttClientDeletedEventData 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 EventGridMqttClientDeletedEventData. + */ + @Generated + public static EventGridMqttClientDeletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String clientAuthenticationName = null; + String clientName = null; + String namespaceName = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("clientAuthenticationName".equals(fieldName)) { + clientAuthenticationName = reader.getString(); + } else if ("clientName".equals(fieldName)) { + clientName = reader.getString(); + } else if ("namespaceName".equals(fieldName)) { + namespaceName = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new EventGridMqttClientDeletedEventData(clientAuthenticationName, clientName, namespaceName); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/EventGridMqttClientDisconnectionReason.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/EventGridMqttClientDisconnectionReason.java new file mode 100644 index 000000000000..c22580a33657 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/EventGridMqttClientDisconnectionReason.java @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * EventGrid MQTT Client Disconnection Reason. + */ +public final class EventGridMqttClientDisconnectionReason + extends ExpandableStringEnum { + /** + * The client got disconnected for any authentication reasons (for example, certificate expired, client got + * disabled, or client configuration changed). + */ + @Generated + public static final EventGridMqttClientDisconnectionReason CLIENT_AUTHENTICATION_ERROR + = fromString("ClientAuthenticationError"); + + /** + * The client got disconnected for any authorization reasons (for example, because of a change in the configuration + * of topic spaces, permission bindings, or client groups). + */ + @Generated + public static final EventGridMqttClientDisconnectionReason CLIENT_AUTHORIZATION_ERROR + = fromString("ClientAuthorizationError"); + + /** + * The client sent a bad request or used one of the unsupported features that resulted in a connection termination + * by the service. + */ + @Generated + public static final EventGridMqttClientDisconnectionReason CLIENT_ERROR = fromString("ClientError"); + + /** + * The client initiated a graceful disconnect through a DISCONNECT packet for MQTT or a close frame for MQTT over + * WebSocket. + */ + @Generated + public static final EventGridMqttClientDisconnectionReason CLIENT_INITIATED_DISCONNECT + = fromString("ClientInitiatedDisconnect"); + + /** + * The client-server connection is lost. (EXCHANGE ONLINE PROTECTION). + */ + @Generated + public static final EventGridMqttClientDisconnectionReason CONNECTION_LOST = fromString("ConnectionLost"); + + /** + * The client's IP address is blocked by IP filter or Private links configuration. + */ + @Generated + public static final EventGridMqttClientDisconnectionReason IP_FORBIDDEN = fromString("IpForbidden"); + + /** + * The client exceeded one or more of the throttling limits that resulted in a connection termination by the + * service. + */ + @Generated + public static final EventGridMqttClientDisconnectionReason QUOTA_EXCEEDED = fromString("QuotaExceeded"); + + /** + * The connection got terminated due to an unexpected server error. + */ + @Generated + public static final EventGridMqttClientDisconnectionReason SERVER_ERROR = fromString("ServerError"); + + /** + * The server initiates a graceful disconnect for any operational reason. + */ + @Generated + public static final EventGridMqttClientDisconnectionReason SERVER_INITIATED_DISCONNECT + = fromString("ServerInitiatedDisconnect"); + + /** + * The client's queue for unacknowledged QoS1 messages reached its limit, which resulted in a connection termination + * by the server. + */ + @Generated + public static final EventGridMqttClientDisconnectionReason SESSION_OVERFLOW = fromString("SessionOverflow"); + + /** + * The client reconnected with the same authentication name, which resulted in the termination of the previous + * connection. + */ + @Generated + public static final EventGridMqttClientDisconnectionReason SESSION_TAKEN_OVER = fromString("SessionTakenOver"); + + /** + * Creates a new instance of EventGridMqttClientDisconnectionReason value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public EventGridMqttClientDisconnectionReason() { + } + + /** + * Creates or finds a EventGridMqttClientDisconnectionReason from its string representation. + * + * @param name a name to look for. + * @return the corresponding EventGridMqttClientDisconnectionReason. + */ + @Generated + public static EventGridMqttClientDisconnectionReason fromString(String name) { + return fromString(name, EventGridMqttClientDisconnectionReason.class); + } + + /** + * Gets known EventGridMqttClientDisconnectionReason values. + * + * @return known EventGridMqttClientDisconnectionReason values. + */ + @Generated + public static Collection values() { + return values(EventGridMqttClientDisconnectionReason.class); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/EventGridMqttClientEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/EventGridMqttClientEventData.java new file mode 100644 index 000000000000..6fd2a26cfabe --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/EventGridMqttClientEventData.java @@ -0,0 +1,132 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for MQTT Client state changes. + */ +@Immutable +public class EventGridMqttClientEventData implements JsonSerializable { + /* + * Unique identifier for the MQTT client that the client presents to the service + * for authentication. This case-sensitive string can be up to 128 characters + * long, and supports UTF-8 characters. + */ + @Generated + private final String clientAuthenticationName; + + /* + * Name of the client resource in the Event Grid namespace. + */ + @Generated + private final String clientName; + + /* + * Name of the Event Grid namespace where the MQTT client was created or updated. + */ + @Generated + private final String namespaceName; + + /** + * Creates an instance of EventGridMqttClientEventData class. + * + * @param clientAuthenticationName the clientAuthenticationName value to set. + * @param clientName the clientName value to set. + * @param namespaceName the namespaceName value to set. + */ + @Generated + protected EventGridMqttClientEventData(String clientAuthenticationName, String clientName, String namespaceName) { + this.clientAuthenticationName = clientAuthenticationName; + this.clientName = clientName; + this.namespaceName = namespaceName; + } + + /** + * Get the clientAuthenticationName property: Unique identifier for the MQTT client that the client presents to the + * service + * for authentication. This case-sensitive string can be up to 128 characters + * long, and supports UTF-8 characters. + * + * @return the clientAuthenticationName value. + */ + @Generated + public String getClientAuthenticationName() { + return this.clientAuthenticationName; + } + + /** + * Get the clientName property: Name of the client resource in the Event Grid namespace. + * + * @return the clientName value. + */ + @Generated + public String getClientName() { + return this.clientName; + } + + /** + * Get the namespaceName property: Name of the Event Grid namespace where the MQTT client was created or updated. + * + * @return the namespaceName value. + */ + @Generated + public String getNamespaceName() { + return this.namespaceName; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("clientAuthenticationName", this.clientAuthenticationName); + jsonWriter.writeStringField("clientName", this.clientName); + jsonWriter.writeStringField("namespaceName", this.namespaceName); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of EventGridMqttClientEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of EventGridMqttClientEventData 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 EventGridMqttClientEventData. + */ + @Generated + public static EventGridMqttClientEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String clientAuthenticationName = null; + String clientName = null; + String namespaceName = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("clientAuthenticationName".equals(fieldName)) { + clientAuthenticationName = reader.getString(); + } else if ("clientName".equals(fieldName)) { + clientName = reader.getString(); + } else if ("namespaceName".equals(fieldName)) { + namespaceName = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new EventGridMqttClientEventData(clientAuthenticationName, clientName, namespaceName); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/EventGridMqttClientSessionConnectedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/EventGridMqttClientSessionConnectedEventData.java new file mode 100644 index 000000000000..3112e9c70d4b --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/EventGridMqttClientSessionConnectedEventData.java @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Event data for Microsoft.EventGrid.MQTTClientSessionConnected event. + */ +@Immutable +public final class EventGridMqttClientSessionConnectedEventData extends EventGridMqttClientEventData { + /* + * Unique identifier for the MQTT client's session. This case-sensitive string can + * be up to 128 characters long, and supports UTF-8 characters. + */ + @Generated + private final String clientSessionName; + + /* + * A number that helps indicate order of MQTT client session connected or + * disconnected events. Latest event will have a sequence number that is higher + * than the previous event. + */ + @Generated + private final long sequenceNumber; + + /** + * Creates an instance of EventGridMqttClientSessionConnectedEventData class. + * + * @param clientAuthenticationName the clientAuthenticationName value to set. + * @param clientName the clientName value to set. + * @param namespaceName the namespaceName value to set. + * @param clientSessionName the clientSessionName value to set. + * @param sequenceNumber the sequenceNumber value to set. + */ + @Generated + private EventGridMqttClientSessionConnectedEventData(String clientAuthenticationName, String clientName, + String namespaceName, String clientSessionName, long sequenceNumber) { + super(clientAuthenticationName, clientName, namespaceName); + this.clientSessionName = clientSessionName; + this.sequenceNumber = sequenceNumber; + } + + /** + * Get the clientSessionName property: Unique identifier for the MQTT client's session. This case-sensitive string + * can + * be up to 128 characters long, and supports UTF-8 characters. + * + * @return the clientSessionName value. + */ + @Generated + public String getClientSessionName() { + return this.clientSessionName; + } + + /** + * Get the sequenceNumber property: A number that helps indicate order of MQTT client session connected or + * disconnected events. Latest event will have a sequence number that is higher + * than the previous event. + * + * @return the sequenceNumber value. + */ + @Generated + public long getSequenceNumber() { + return this.sequenceNumber; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("clientAuthenticationName", getClientAuthenticationName()); + jsonWriter.writeStringField("clientName", getClientName()); + jsonWriter.writeStringField("namespaceName", getNamespaceName()); + jsonWriter.writeStringField("clientSessionName", this.clientSessionName); + jsonWriter.writeLongField("sequenceNumber", this.sequenceNumber); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of EventGridMqttClientSessionConnectedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of EventGridMqttClientSessionConnectedEventData 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 EventGridMqttClientSessionConnectedEventData. + */ + @Generated + public static EventGridMqttClientSessionConnectedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String clientAuthenticationName = null; + String clientName = null; + String namespaceName = null; + String clientSessionName = null; + long sequenceNumber = 0L; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("clientAuthenticationName".equals(fieldName)) { + clientAuthenticationName = reader.getString(); + } else if ("clientName".equals(fieldName)) { + clientName = reader.getString(); + } else if ("namespaceName".equals(fieldName)) { + namespaceName = reader.getString(); + } else if ("clientSessionName".equals(fieldName)) { + clientSessionName = reader.getString(); + } else if ("sequenceNumber".equals(fieldName)) { + sequenceNumber = reader.getLong(); + } else { + reader.skipChildren(); + } + } + return new EventGridMqttClientSessionConnectedEventData(clientAuthenticationName, clientName, namespaceName, + clientSessionName, sequenceNumber); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/EventGridMqttClientSessionDisconnectedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/EventGridMqttClientSessionDisconnectedEventData.java new file mode 100644 index 000000000000..fc3fe031c5e5 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/EventGridMqttClientSessionDisconnectedEventData.java @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Event data for Microsoft.EventGrid.MQTTClientSessionDisconnected event. + */ +@Immutable +public final class EventGridMqttClientSessionDisconnectedEventData extends EventGridMqttClientEventData { + /* + * Unique identifier for the MQTT client's session. This case-sensitive string can + * be up to 128 characters long, and supports UTF-8 characters. + */ + @Generated + private final String clientSessionName; + + /* + * A number that helps indicate order of MQTT client session connected or + * disconnected events. Latest event will have a sequence number that is higher + * than the previous event. + */ + @Generated + private final long sequenceNumber; + + /* + * Reason for the disconnection of the MQTT client's session. The value could be + * one of the values in the disconnection reasons table. + */ + @Generated + private final EventGridMqttClientDisconnectionReason disconnectionReason; + + /** + * Creates an instance of EventGridMqttClientSessionDisconnectedEventData class. + * + * @param clientAuthenticationName the clientAuthenticationName value to set. + * @param clientName the clientName value to set. + * @param namespaceName the namespaceName value to set. + * @param clientSessionName the clientSessionName value to set. + * @param sequenceNumber the sequenceNumber value to set. + * @param disconnectionReason the disconnectionReason value to set. + */ + @Generated + private EventGridMqttClientSessionDisconnectedEventData(String clientAuthenticationName, String clientName, + String namespaceName, String clientSessionName, long sequenceNumber, + EventGridMqttClientDisconnectionReason disconnectionReason) { + super(clientAuthenticationName, clientName, namespaceName); + this.clientSessionName = clientSessionName; + this.sequenceNumber = sequenceNumber; + this.disconnectionReason = disconnectionReason; + } + + /** + * Get the clientSessionName property: Unique identifier for the MQTT client's session. This case-sensitive string + * can + * be up to 128 characters long, and supports UTF-8 characters. + * + * @return the clientSessionName value. + */ + @Generated + public String getClientSessionName() { + return this.clientSessionName; + } + + /** + * Get the sequenceNumber property: A number that helps indicate order of MQTT client session connected or + * disconnected events. Latest event will have a sequence number that is higher + * than the previous event. + * + * @return the sequenceNumber value. + */ + @Generated + public long getSequenceNumber() { + return this.sequenceNumber; + } + + /** + * Get the disconnectionReason property: Reason for the disconnection of the MQTT client's session. The value could + * be + * one of the values in the disconnection reasons table. + * + * @return the disconnectionReason value. + */ + @Generated + public EventGridMqttClientDisconnectionReason getDisconnectionReason() { + return this.disconnectionReason; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("clientAuthenticationName", getClientAuthenticationName()); + jsonWriter.writeStringField("clientName", getClientName()); + jsonWriter.writeStringField("namespaceName", getNamespaceName()); + jsonWriter.writeStringField("clientSessionName", this.clientSessionName); + jsonWriter.writeLongField("sequenceNumber", this.sequenceNumber); + jsonWriter.writeStringField("disconnectionReason", + this.disconnectionReason == null ? null : this.disconnectionReason.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of EventGridMqttClientSessionDisconnectedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of EventGridMqttClientSessionDisconnectedEventData 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 EventGridMqttClientSessionDisconnectedEventData. + */ + @Generated + public static EventGridMqttClientSessionDisconnectedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String clientAuthenticationName = null; + String clientName = null; + String namespaceName = null; + String clientSessionName = null; + long sequenceNumber = 0L; + EventGridMqttClientDisconnectionReason disconnectionReason = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("clientAuthenticationName".equals(fieldName)) { + clientAuthenticationName = reader.getString(); + } else if ("clientName".equals(fieldName)) { + clientName = reader.getString(); + } else if ("namespaceName".equals(fieldName)) { + namespaceName = reader.getString(); + } else if ("clientSessionName".equals(fieldName)) { + clientSessionName = reader.getString(); + } else if ("sequenceNumber".equals(fieldName)) { + sequenceNumber = reader.getLong(); + } else if ("disconnectionReason".equals(fieldName)) { + disconnectionReason = EventGridMqttClientDisconnectionReason.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + return new EventGridMqttClientSessionDisconnectedEventData(clientAuthenticationName, clientName, + namespaceName, clientSessionName, sequenceNumber, disconnectionReason); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/EventGridMqttClientState.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/EventGridMqttClientState.java new file mode 100644 index 000000000000..d303d0778da6 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/EventGridMqttClientState.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * EventGrid MQTT Client State. + */ +public final class EventGridMqttClientState extends ExpandableStringEnum { + /** + * Enabled. + */ + @Generated + public static final EventGridMqttClientState ENABLED = fromString("Enabled"); + + /** + * Disabled. + */ + @Generated + public static final EventGridMqttClientState DISABLED = fromString("Disabled"); + + /** + * Creates a new instance of EventGridMqttClientState value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public EventGridMqttClientState() { + } + + /** + * Creates or finds a EventGridMqttClientState from its string representation. + * + * @param name a name to look for. + * @return the corresponding EventGridMqttClientState. + */ + @Generated + public static EventGridMqttClientState fromString(String name) { + return fromString(name, EventGridMqttClientState.class); + } + + /** + * Gets known EventGridMqttClientState values. + * + * @return known EventGridMqttClientState values. + */ + @Generated + public static Collection values() { + return values(EventGridMqttClientState.class); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/EventHubCaptureFileCreatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/EventHubCaptureFileCreatedEventData.java new file mode 100644 index 000000000000..85e9a7ed0884 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/EventHubCaptureFileCreatedEventData.java @@ -0,0 +1,265 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.EventHub.CaptureFileCreated event. + */ +@Immutable +public final class EventHubCaptureFileCreatedEventData + implements JsonSerializable { + /* + * The path to the capture file. + */ + @Generated + private String fileUrl; + + /* + * The file type of the capture file. + */ + @Generated + private String fileType; + + /* + * The shard ID. + */ + @Generated + private String partitionId; + + /* + * The file size. + */ + @Generated + private Integer sizeInBytes; + + /* + * The number of events in the file. + */ + @Generated + private Integer eventCount; + + /* + * The smallest sequence number from the queue. + */ + @Generated + private Integer firstSequenceNumber; + + /* + * The last sequence number from the queue. + */ + @Generated + private Integer lastSequenceNumber; + + /* + * The first time from the queue. + */ + @Generated + private final OffsetDateTime firstEnqueueTime; + + /* + * The last time from the queue. + */ + @Generated + private final OffsetDateTime lastEnqueueTime; + + /** + * Creates an instance of EventHubCaptureFileCreatedEventData class. + * + * @param firstEnqueueTime the firstEnqueueTime value to set. + * @param lastEnqueueTime the lastEnqueueTime value to set. + */ + @Generated + private EventHubCaptureFileCreatedEventData(OffsetDateTime firstEnqueueTime, OffsetDateTime lastEnqueueTime) { + this.firstEnqueueTime = firstEnqueueTime; + this.lastEnqueueTime = lastEnqueueTime; + } + + /** + * Get the fileUrl property: The path to the capture file. + * + * @return the fileUrl value. + */ + @Generated + public String getFileUrl() { + return this.fileUrl; + } + + /** + * Get the fileType property: The file type of the capture file. + * + * @return the fileType value. + */ + @Generated + public String getFileType() { + return this.fileType; + } + + /** + * Get the partitionId property: The shard ID. + * + * @return the partitionId value. + */ + @Generated + public String getPartitionId() { + return this.partitionId; + } + + /** + * Get the sizeInBytes property: The file size. + * + * @return the sizeInBytes value. + */ + @Generated + public Integer getSizeInBytes() { + return this.sizeInBytes; + } + + /** + * Get the eventCount property: The number of events in the file. + * + * @return the eventCount value. + */ + @Generated + public Integer getEventCount() { + return this.eventCount; + } + + /** + * Get the firstSequenceNumber property: The smallest sequence number from the queue. + * + * @return the firstSequenceNumber value. + */ + @Generated + public Integer getFirstSequenceNumber() { + return this.firstSequenceNumber; + } + + /** + * Get the lastSequenceNumber property: The last sequence number from the queue. + * + * @return the lastSequenceNumber value. + */ + @Generated + public Integer getLastSequenceNumber() { + return this.lastSequenceNumber; + } + + /** + * Get the firstEnqueueTime property: The first time from the queue. + * + * @return the firstEnqueueTime value. + */ + @Generated + public OffsetDateTime getFirstEnqueueTime() { + return this.firstEnqueueTime; + } + + /** + * Get the lastEnqueueTime property: The last time from the queue. + * + * @return the lastEnqueueTime value. + */ + @Generated + public OffsetDateTime getLastEnqueueTime() { + return this.lastEnqueueTime; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("firstEnqueueTime", + this.firstEnqueueTime == null + ? null + : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.firstEnqueueTime)); + jsonWriter.writeStringField("lastEnqueueTime", + this.lastEnqueueTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.lastEnqueueTime)); + jsonWriter.writeStringField("fileUrl", this.fileUrl); + jsonWriter.writeStringField("fileType", this.fileType); + jsonWriter.writeStringField("partitionId", this.partitionId); + jsonWriter.writeNumberField("sizeInBytes", this.sizeInBytes); + jsonWriter.writeNumberField("eventCount", this.eventCount); + jsonWriter.writeNumberField("firstSequenceNumber", this.firstSequenceNumber); + jsonWriter.writeNumberField("lastSequenceNumber", this.lastSequenceNumber); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of EventHubCaptureFileCreatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of EventHubCaptureFileCreatedEventData 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 EventHubCaptureFileCreatedEventData. + */ + @Generated + public static EventHubCaptureFileCreatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OffsetDateTime firstEnqueueTime = null; + OffsetDateTime lastEnqueueTime = null; + String fileUrl = null; + String fileType = null; + String partitionId = null; + Integer sizeInBytes = null; + Integer eventCount = null; + Integer firstSequenceNumber = null; + Integer lastSequenceNumber = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("firstEnqueueTime".equals(fieldName)) { + firstEnqueueTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("lastEnqueueTime".equals(fieldName)) { + lastEnqueueTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("fileUrl".equals(fieldName)) { + fileUrl = reader.getString(); + } else if ("fileType".equals(fieldName)) { + fileType = reader.getString(); + } else if ("partitionId".equals(fieldName)) { + partitionId = reader.getString(); + } else if ("sizeInBytes".equals(fieldName)) { + sizeInBytes = reader.getNullable(JsonReader::getInt); + } else if ("eventCount".equals(fieldName)) { + eventCount = reader.getNullable(JsonReader::getInt); + } else if ("firstSequenceNumber".equals(fieldName)) { + firstSequenceNumber = reader.getNullable(JsonReader::getInt); + } else if ("lastSequenceNumber".equals(fieldName)) { + lastSequenceNumber = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + EventHubCaptureFileCreatedEventData deserializedEventHubCaptureFileCreatedEventData + = new EventHubCaptureFileCreatedEventData(firstEnqueueTime, lastEnqueueTime); + deserializedEventHubCaptureFileCreatedEventData.fileUrl = fileUrl; + deserializedEventHubCaptureFileCreatedEventData.fileType = fileType; + deserializedEventHubCaptureFileCreatedEventData.partitionId = partitionId; + deserializedEventHubCaptureFileCreatedEventData.sizeInBytes = sizeInBytes; + deserializedEventHubCaptureFileCreatedEventData.eventCount = eventCount; + deserializedEventHubCaptureFileCreatedEventData.firstSequenceNumber = firstSequenceNumber; + deserializedEventHubCaptureFileCreatedEventData.lastSequenceNumber = lastSequenceNumber; + + return deserializedEventHubCaptureFileCreatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/HealthcareDicomImageCreatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/HealthcareDicomImageCreatedEventData.java new file mode 100644 index 000000000000..9e4c511d0080 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/HealthcareDicomImageCreatedEventData.java @@ -0,0 +1,198 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.HealthcareApis.DicomImageCreated event. + */ +@Immutable +public final class HealthcareDicomImageCreatedEventData + implements JsonSerializable { + /* + * Data partition name + */ + @Generated + private final String partitionName; + + /* + * Unique identifier for the Study + */ + @Generated + private final String imageStudyInstanceUid; + + /* + * Unique identifier for the Series + */ + @Generated + private final String imageSeriesInstanceUid; + + /* + * Unique identifier for the DICOM Image + */ + @Generated + private final String imageSopInstanceUid; + + /* + * Domain name of the DICOM account for this image. + */ + @Generated + private final String serviceHostName; + + /* + * Sequence number of the DICOM Service within Azure Health Data Services. It is unique for every image creation and + * deletion within the service. + */ + @Generated + private final long sequenceNumber; + + /** + * Creates an instance of HealthcareDicomImageCreatedEventData class. + * + * @param partitionName the partitionName value to set. + * @param imageStudyInstanceUid the imageStudyInstanceUid value to set. + * @param imageSeriesInstanceUid the imageSeriesInstanceUid value to set. + * @param imageSopInstanceUid the imageSopInstanceUid value to set. + * @param serviceHostName the serviceHostName value to set. + * @param sequenceNumber the sequenceNumber value to set. + */ + @Generated + private HealthcareDicomImageCreatedEventData(String partitionName, String imageStudyInstanceUid, + String imageSeriesInstanceUid, String imageSopInstanceUid, String serviceHostName, long sequenceNumber) { + this.partitionName = partitionName; + this.imageStudyInstanceUid = imageStudyInstanceUid; + this.imageSeriesInstanceUid = imageSeriesInstanceUid; + this.imageSopInstanceUid = imageSopInstanceUid; + this.serviceHostName = serviceHostName; + this.sequenceNumber = sequenceNumber; + } + + /** + * Get the partitionName property: Data partition name. + * + * @return the partitionName value. + */ + @Generated + public String getPartitionName() { + return this.partitionName; + } + + /** + * Get the imageStudyInstanceUid property: Unique identifier for the Study. + * + * @return the imageStudyInstanceUid value. + */ + @Generated + public String getImageStudyInstanceUid() { + return this.imageStudyInstanceUid; + } + + /** + * Get the imageSeriesInstanceUid property: Unique identifier for the Series. + * + * @return the imageSeriesInstanceUid value. + */ + @Generated + public String getImageSeriesInstanceUid() { + return this.imageSeriesInstanceUid; + } + + /** + * Get the imageSopInstanceUid property: Unique identifier for the DICOM Image. + * + * @return the imageSopInstanceUid value. + */ + @Generated + public String getImageSopInstanceUid() { + return this.imageSopInstanceUid; + } + + /** + * Get the serviceHostName property: Domain name of the DICOM account for this image. + * + * @return the serviceHostName value. + */ + @Generated + public String getServiceHostName() { + return this.serviceHostName; + } + + /** + * Get the sequenceNumber property: Sequence number of the DICOM Service within Azure Health Data Services. It is + * unique for every image creation and deletion within the service. + * + * @return the sequenceNumber value. + */ + @Generated + public long getSequenceNumber() { + return this.sequenceNumber; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("partitionName", this.partitionName); + jsonWriter.writeStringField("imageStudyInstanceUid", this.imageStudyInstanceUid); + jsonWriter.writeStringField("imageSeriesInstanceUid", this.imageSeriesInstanceUid); + jsonWriter.writeStringField("imageSopInstanceUid", this.imageSopInstanceUid); + jsonWriter.writeStringField("serviceHostName", this.serviceHostName); + jsonWriter.writeLongField("sequenceNumber", this.sequenceNumber); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of HealthcareDicomImageCreatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of HealthcareDicomImageCreatedEventData 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 HealthcareDicomImageCreatedEventData. + */ + @Generated + public static HealthcareDicomImageCreatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String partitionName = null; + String imageStudyInstanceUid = null; + String imageSeriesInstanceUid = null; + String imageSopInstanceUid = null; + String serviceHostName = null; + long sequenceNumber = 0L; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("partitionName".equals(fieldName)) { + partitionName = reader.getString(); + } else if ("imageStudyInstanceUid".equals(fieldName)) { + imageStudyInstanceUid = reader.getString(); + } else if ("imageSeriesInstanceUid".equals(fieldName)) { + imageSeriesInstanceUid = reader.getString(); + } else if ("imageSopInstanceUid".equals(fieldName)) { + imageSopInstanceUid = reader.getString(); + } else if ("serviceHostName".equals(fieldName)) { + serviceHostName = reader.getString(); + } else if ("sequenceNumber".equals(fieldName)) { + sequenceNumber = reader.getLong(); + } else { + reader.skipChildren(); + } + } + return new HealthcareDicomImageCreatedEventData(partitionName, imageStudyInstanceUid, + imageSeriesInstanceUid, imageSopInstanceUid, serviceHostName, sequenceNumber); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/HealthcareDicomImageDeletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/HealthcareDicomImageDeletedEventData.java new file mode 100644 index 000000000000..43caa0313625 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/HealthcareDicomImageDeletedEventData.java @@ -0,0 +1,198 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.HealthcareApis.DicomImageDeleted event. + */ +@Immutable +public final class HealthcareDicomImageDeletedEventData + implements JsonSerializable { + /* + * Data partition name + */ + @Generated + private final String partitionName; + + /* + * Unique identifier for the Study + */ + @Generated + private final String imageStudyInstanceUid; + + /* + * Unique identifier for the Series + */ + @Generated + private final String imageSeriesInstanceUid; + + /* + * Unique identifier for the DICOM Image + */ + @Generated + private final String imageSopInstanceUid; + + /* + * Host name of the DICOM account for this image. + */ + @Generated + private final String serviceHostName; + + /* + * Sequence number of the DICOM Service within Azure Health Data Services. It is unique for every image creation and + * deletion within the service. + */ + @Generated + private final long sequenceNumber; + + /** + * Creates an instance of HealthcareDicomImageDeletedEventData class. + * + * @param partitionName the partitionName value to set. + * @param imageStudyInstanceUid the imageStudyInstanceUid value to set. + * @param imageSeriesInstanceUid the imageSeriesInstanceUid value to set. + * @param imageSopInstanceUid the imageSopInstanceUid value to set. + * @param serviceHostName the serviceHostName value to set. + * @param sequenceNumber the sequenceNumber value to set. + */ + @Generated + private HealthcareDicomImageDeletedEventData(String partitionName, String imageStudyInstanceUid, + String imageSeriesInstanceUid, String imageSopInstanceUid, String serviceHostName, long sequenceNumber) { + this.partitionName = partitionName; + this.imageStudyInstanceUid = imageStudyInstanceUid; + this.imageSeriesInstanceUid = imageSeriesInstanceUid; + this.imageSopInstanceUid = imageSopInstanceUid; + this.serviceHostName = serviceHostName; + this.sequenceNumber = sequenceNumber; + } + + /** + * Get the partitionName property: Data partition name. + * + * @return the partitionName value. + */ + @Generated + public String getPartitionName() { + return this.partitionName; + } + + /** + * Get the imageStudyInstanceUid property: Unique identifier for the Study. + * + * @return the imageStudyInstanceUid value. + */ + @Generated + public String getImageStudyInstanceUid() { + return this.imageStudyInstanceUid; + } + + /** + * Get the imageSeriesInstanceUid property: Unique identifier for the Series. + * + * @return the imageSeriesInstanceUid value. + */ + @Generated + public String getImageSeriesInstanceUid() { + return this.imageSeriesInstanceUid; + } + + /** + * Get the imageSopInstanceUid property: Unique identifier for the DICOM Image. + * + * @return the imageSopInstanceUid value. + */ + @Generated + public String getImageSopInstanceUid() { + return this.imageSopInstanceUid; + } + + /** + * Get the serviceHostName property: Host name of the DICOM account for this image. + * + * @return the serviceHostName value. + */ + @Generated + public String getServiceHostName() { + return this.serviceHostName; + } + + /** + * Get the sequenceNumber property: Sequence number of the DICOM Service within Azure Health Data Services. It is + * unique for every image creation and deletion within the service. + * + * @return the sequenceNumber value. + */ + @Generated + public long getSequenceNumber() { + return this.sequenceNumber; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("partitionName", this.partitionName); + jsonWriter.writeStringField("imageStudyInstanceUid", this.imageStudyInstanceUid); + jsonWriter.writeStringField("imageSeriesInstanceUid", this.imageSeriesInstanceUid); + jsonWriter.writeStringField("imageSopInstanceUid", this.imageSopInstanceUid); + jsonWriter.writeStringField("serviceHostName", this.serviceHostName); + jsonWriter.writeLongField("sequenceNumber", this.sequenceNumber); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of HealthcareDicomImageDeletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of HealthcareDicomImageDeletedEventData 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 HealthcareDicomImageDeletedEventData. + */ + @Generated + public static HealthcareDicomImageDeletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String partitionName = null; + String imageStudyInstanceUid = null; + String imageSeriesInstanceUid = null; + String imageSopInstanceUid = null; + String serviceHostName = null; + long sequenceNumber = 0L; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("partitionName".equals(fieldName)) { + partitionName = reader.getString(); + } else if ("imageStudyInstanceUid".equals(fieldName)) { + imageStudyInstanceUid = reader.getString(); + } else if ("imageSeriesInstanceUid".equals(fieldName)) { + imageSeriesInstanceUid = reader.getString(); + } else if ("imageSopInstanceUid".equals(fieldName)) { + imageSopInstanceUid = reader.getString(); + } else if ("serviceHostName".equals(fieldName)) { + serviceHostName = reader.getString(); + } else if ("sequenceNumber".equals(fieldName)) { + sequenceNumber = reader.getLong(); + } else { + reader.skipChildren(); + } + } + return new HealthcareDicomImageDeletedEventData(partitionName, imageStudyInstanceUid, + imageSeriesInstanceUid, imageSopInstanceUid, serviceHostName, sequenceNumber); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/HealthcareDicomImageUpdatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/HealthcareDicomImageUpdatedEventData.java new file mode 100644 index 000000000000..3488c66cda06 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/HealthcareDicomImageUpdatedEventData.java @@ -0,0 +1,198 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.HealthcareApis.DicomImageUpdated event. + */ +@Immutable +public final class HealthcareDicomImageUpdatedEventData + implements JsonSerializable { + /* + * Data partition name + */ + @Generated + private final String partitionName; + + /* + * Unique identifier for the Study + */ + @Generated + private final String imageStudyInstanceUid; + + /* + * Unique identifier for the Series + */ + @Generated + private final String imageSeriesInstanceUid; + + /* + * Unique identifier for the DICOM Image + */ + @Generated + private final String imageSopInstanceUid; + + /* + * Domain name of the DICOM account for this image. + */ + @Generated + private final String serviceHostName; + + /* + * Sequence number of the DICOM Service within Azure Health Data Services. It is unique for every image creation, + * updation and deletion within the service. + */ + @Generated + private final long sequenceNumber; + + /** + * Creates an instance of HealthcareDicomImageUpdatedEventData class. + * + * @param partitionName the partitionName value to set. + * @param imageStudyInstanceUid the imageStudyInstanceUid value to set. + * @param imageSeriesInstanceUid the imageSeriesInstanceUid value to set. + * @param imageSopInstanceUid the imageSopInstanceUid value to set. + * @param serviceHostName the serviceHostName value to set. + * @param sequenceNumber the sequenceNumber value to set. + */ + @Generated + private HealthcareDicomImageUpdatedEventData(String partitionName, String imageStudyInstanceUid, + String imageSeriesInstanceUid, String imageSopInstanceUid, String serviceHostName, long sequenceNumber) { + this.partitionName = partitionName; + this.imageStudyInstanceUid = imageStudyInstanceUid; + this.imageSeriesInstanceUid = imageSeriesInstanceUid; + this.imageSopInstanceUid = imageSopInstanceUid; + this.serviceHostName = serviceHostName; + this.sequenceNumber = sequenceNumber; + } + + /** + * Get the partitionName property: Data partition name. + * + * @return the partitionName value. + */ + @Generated + public String getPartitionName() { + return this.partitionName; + } + + /** + * Get the imageStudyInstanceUid property: Unique identifier for the Study. + * + * @return the imageStudyInstanceUid value. + */ + @Generated + public String getImageStudyInstanceUid() { + return this.imageStudyInstanceUid; + } + + /** + * Get the imageSeriesInstanceUid property: Unique identifier for the Series. + * + * @return the imageSeriesInstanceUid value. + */ + @Generated + public String getImageSeriesInstanceUid() { + return this.imageSeriesInstanceUid; + } + + /** + * Get the imageSopInstanceUid property: Unique identifier for the DICOM Image. + * + * @return the imageSopInstanceUid value. + */ + @Generated + public String getImageSopInstanceUid() { + return this.imageSopInstanceUid; + } + + /** + * Get the serviceHostName property: Domain name of the DICOM account for this image. + * + * @return the serviceHostName value. + */ + @Generated + public String getServiceHostName() { + return this.serviceHostName; + } + + /** + * Get the sequenceNumber property: Sequence number of the DICOM Service within Azure Health Data Services. It is + * unique for every image creation, updation and deletion within the service. + * + * @return the sequenceNumber value. + */ + @Generated + public long getSequenceNumber() { + return this.sequenceNumber; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("partitionName", this.partitionName); + jsonWriter.writeStringField("imageStudyInstanceUid", this.imageStudyInstanceUid); + jsonWriter.writeStringField("imageSeriesInstanceUid", this.imageSeriesInstanceUid); + jsonWriter.writeStringField("imageSopInstanceUid", this.imageSopInstanceUid); + jsonWriter.writeStringField("serviceHostName", this.serviceHostName); + jsonWriter.writeLongField("sequenceNumber", this.sequenceNumber); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of HealthcareDicomImageUpdatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of HealthcareDicomImageUpdatedEventData 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 HealthcareDicomImageUpdatedEventData. + */ + @Generated + public static HealthcareDicomImageUpdatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String partitionName = null; + String imageStudyInstanceUid = null; + String imageSeriesInstanceUid = null; + String imageSopInstanceUid = null; + String serviceHostName = null; + long sequenceNumber = 0L; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("partitionName".equals(fieldName)) { + partitionName = reader.getString(); + } else if ("imageStudyInstanceUid".equals(fieldName)) { + imageStudyInstanceUid = reader.getString(); + } else if ("imageSeriesInstanceUid".equals(fieldName)) { + imageSeriesInstanceUid = reader.getString(); + } else if ("imageSopInstanceUid".equals(fieldName)) { + imageSopInstanceUid = reader.getString(); + } else if ("serviceHostName".equals(fieldName)) { + serviceHostName = reader.getString(); + } else if ("sequenceNumber".equals(fieldName)) { + sequenceNumber = reader.getLong(); + } else { + reader.skipChildren(); + } + } + return new HealthcareDicomImageUpdatedEventData(partitionName, imageStudyInstanceUid, + imageSeriesInstanceUid, imageSopInstanceUid, serviceHostName, sequenceNumber); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/HealthcareFhirResourceCreatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/HealthcareFhirResourceCreatedEventData.java new file mode 100644 index 000000000000..f720f8e588c7 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/HealthcareFhirResourceCreatedEventData.java @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.HealthcareApis.FhirResourceCreated event. + */ +@Immutable +public final class HealthcareFhirResourceCreatedEventData + implements JsonSerializable { + /* + * Type of HL7 FHIR resource. + */ + @Generated + private final HealthcareFhirResourceType resourceType; + + /* + * Domain name of FHIR account for this resource. + */ + @Generated + private final String resourceFhirAccount; + + /* + * Id of HL7 FHIR resource. + */ + @Generated + private final String resourceFhirId; + + /* + * VersionId of HL7 FHIR resource. It changes when the resource is created, updated, or deleted(soft-deletion). + */ + @Generated + private final long resourceVersionId; + + /** + * Creates an instance of HealthcareFhirResourceCreatedEventData class. + * + * @param resourceType the resourceType value to set. + * @param resourceFhirAccount the resourceFhirAccount value to set. + * @param resourceFhirId the resourceFhirId value to set. + * @param resourceVersionId the resourceVersionId value to set. + */ + @Generated + private HealthcareFhirResourceCreatedEventData(HealthcareFhirResourceType resourceType, String resourceFhirAccount, + String resourceFhirId, long resourceVersionId) { + this.resourceType = resourceType; + this.resourceFhirAccount = resourceFhirAccount; + this.resourceFhirId = resourceFhirId; + this.resourceVersionId = resourceVersionId; + } + + /** + * Get the resourceType property: Type of HL7 FHIR resource. + * + * @return the resourceType value. + */ + @Generated + public HealthcareFhirResourceType getResourceType() { + return this.resourceType; + } + + /** + * Get the resourceFhirAccount property: Domain name of FHIR account for this resource. + * + * @return the resourceFhirAccount value. + */ + @Generated + public String getResourceFhirAccount() { + return this.resourceFhirAccount; + } + + /** + * Get the resourceFhirId property: Id of HL7 FHIR resource. + * + * @return the resourceFhirId value. + */ + @Generated + public String getResourceFhirId() { + return this.resourceFhirId; + } + + /** + * Get the resourceVersionId property: VersionId of HL7 FHIR resource. It changes when the resource is created, + * updated, or deleted(soft-deletion). + * + * @return the resourceVersionId value. + */ + @Generated + public long getResourceVersionId() { + return this.resourceVersionId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceType", this.resourceType == null ? null : this.resourceType.toString()); + jsonWriter.writeStringField("resourceFhirAccount", this.resourceFhirAccount); + jsonWriter.writeStringField("resourceFhirId", this.resourceFhirId); + jsonWriter.writeLongField("resourceVersionId", this.resourceVersionId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of HealthcareFhirResourceCreatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of HealthcareFhirResourceCreatedEventData 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 HealthcareFhirResourceCreatedEventData. + */ + @Generated + public static HealthcareFhirResourceCreatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + HealthcareFhirResourceType resourceType = null; + String resourceFhirAccount = null; + String resourceFhirId = null; + long resourceVersionId = 0L; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceType".equals(fieldName)) { + resourceType = HealthcareFhirResourceType.fromString(reader.getString()); + } else if ("resourceFhirAccount".equals(fieldName)) { + resourceFhirAccount = reader.getString(); + } else if ("resourceFhirId".equals(fieldName)) { + resourceFhirId = reader.getString(); + } else if ("resourceVersionId".equals(fieldName)) { + resourceVersionId = reader.getLong(); + } else { + reader.skipChildren(); + } + } + return new HealthcareFhirResourceCreatedEventData(resourceType, resourceFhirAccount, resourceFhirId, + resourceVersionId); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/HealthcareFhirResourceDeletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/HealthcareFhirResourceDeletedEventData.java new file mode 100644 index 000000000000..4988d4f62bba --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/HealthcareFhirResourceDeletedEventData.java @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.HealthcareApis.FhirResourceDeleted event. + */ +@Immutable +public final class HealthcareFhirResourceDeletedEventData + implements JsonSerializable { + /* + * Type of HL7 FHIR resource. + */ + @Generated + private final HealthcareFhirResourceType resourceType; + + /* + * Domain name of FHIR account for this resource. + */ + @Generated + private final String resourceFhirAccount; + + /* + * Id of HL7 FHIR resource. + */ + @Generated + private final String resourceFhirId; + + /* + * VersionId of HL7 FHIR resource. It changes when the resource is created, updated, or deleted(soft-deletion). + */ + @Generated + private final long resourceVersionId; + + /** + * Creates an instance of HealthcareFhirResourceDeletedEventData class. + * + * @param resourceType the resourceType value to set. + * @param resourceFhirAccount the resourceFhirAccount value to set. + * @param resourceFhirId the resourceFhirId value to set. + * @param resourceVersionId the resourceVersionId value to set. + */ + @Generated + private HealthcareFhirResourceDeletedEventData(HealthcareFhirResourceType resourceType, String resourceFhirAccount, + String resourceFhirId, long resourceVersionId) { + this.resourceType = resourceType; + this.resourceFhirAccount = resourceFhirAccount; + this.resourceFhirId = resourceFhirId; + this.resourceVersionId = resourceVersionId; + } + + /** + * Get the resourceType property: Type of HL7 FHIR resource. + * + * @return the resourceType value. + */ + @Generated + public HealthcareFhirResourceType getResourceType() { + return this.resourceType; + } + + /** + * Get the resourceFhirAccount property: Domain name of FHIR account for this resource. + * + * @return the resourceFhirAccount value. + */ + @Generated + public String getResourceFhirAccount() { + return this.resourceFhirAccount; + } + + /** + * Get the resourceFhirId property: Id of HL7 FHIR resource. + * + * @return the resourceFhirId value. + */ + @Generated + public String getResourceFhirId() { + return this.resourceFhirId; + } + + /** + * Get the resourceVersionId property: VersionId of HL7 FHIR resource. It changes when the resource is created, + * updated, or deleted(soft-deletion). + * + * @return the resourceVersionId value. + */ + @Generated + public long getResourceVersionId() { + return this.resourceVersionId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceType", this.resourceType == null ? null : this.resourceType.toString()); + jsonWriter.writeStringField("resourceFhirAccount", this.resourceFhirAccount); + jsonWriter.writeStringField("resourceFhirId", this.resourceFhirId); + jsonWriter.writeLongField("resourceVersionId", this.resourceVersionId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of HealthcareFhirResourceDeletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of HealthcareFhirResourceDeletedEventData 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 HealthcareFhirResourceDeletedEventData. + */ + @Generated + public static HealthcareFhirResourceDeletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + HealthcareFhirResourceType resourceType = null; + String resourceFhirAccount = null; + String resourceFhirId = null; + long resourceVersionId = 0L; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceType".equals(fieldName)) { + resourceType = HealthcareFhirResourceType.fromString(reader.getString()); + } else if ("resourceFhirAccount".equals(fieldName)) { + resourceFhirAccount = reader.getString(); + } else if ("resourceFhirId".equals(fieldName)) { + resourceFhirId = reader.getString(); + } else if ("resourceVersionId".equals(fieldName)) { + resourceVersionId = reader.getLong(); + } else { + reader.skipChildren(); + } + } + return new HealthcareFhirResourceDeletedEventData(resourceType, resourceFhirAccount, resourceFhirId, + resourceVersionId); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/HealthcareFhirResourceType.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/HealthcareFhirResourceType.java new file mode 100644 index 000000000000..228181ef5b98 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/HealthcareFhirResourceType.java @@ -0,0 +1,1025 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Schema of FHIR resource type enumeration. + */ +public final class HealthcareFhirResourceType extends ExpandableStringEnum { + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType ACCOUNT = fromString("Account"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType ACTIVITY_DEFINITION = fromString("ActivityDefinition"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType ADVERSE_EVENT = fromString("AdverseEvent"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType ALLERGY_INTOLERANCE = fromString("AllergyIntolerance"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType APPOINTMENT = fromString("Appointment"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType APPOINTMENT_RESPONSE = fromString("AppointmentResponse"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType AUDIT_EVENT = fromString("AuditEvent"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType BASIC = fromString("Basic"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType BINARY = fromString("Binary"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType BIOLOGICALLY_DERIVED_PRODUCT + = fromString("BiologicallyDerivedProduct"); + + /** + * The FHIR resource type defined in STU3. + */ + @Generated + public static final HealthcareFhirResourceType BODY_SITE = fromString("BodySite"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType BODY_STRUCTURE = fromString("BodyStructure"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType BUNDLE = fromString("Bundle"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType CAPABILITY_STATEMENT = fromString("CapabilityStatement"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType CARE_PLAN = fromString("CarePlan"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType CARE_TEAM = fromString("CareTeam"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType CATALOG_ENTRY = fromString("CatalogEntry"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType CHARGE_ITEM = fromString("ChargeItem"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType CHARGE_ITEM_DEFINITION = fromString("ChargeItemDefinition"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType CLAIM = fromString("Claim"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType CLAIM_RESPONSE = fromString("ClaimResponse"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType CLINICAL_IMPRESSION = fromString("ClinicalImpression"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType CODE_SYSTEM = fromString("CodeSystem"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType COMMUNICATION = fromString("Communication"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType COMMUNICATION_REQUEST = fromString("CommunicationRequest"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType COMPARTMENT_DEFINITION = fromString("CompartmentDefinition"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType COMPOSITION = fromString("Composition"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType CONCEPT_MAP = fromString("ConceptMap"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType CONDITION = fromString("Condition"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType CONSENT = fromString("Consent"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType CONTRACT = fromString("Contract"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType COVERAGE = fromString("Coverage"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType COVERAGE_ELIGIBILITY_REQUEST + = fromString("CoverageEligibilityRequest"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType COVERAGE_ELIGIBILITY_RESPONSE + = fromString("CoverageEligibilityResponse"); + + /** + * The FHIR resource type defined in STU3. + */ + @Generated + public static final HealthcareFhirResourceType DATA_ELEMENT = fromString("DataElement"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType DETECTED_ISSUE = fromString("DetectedIssue"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType DEVICE = fromString("Device"); + + /** + * The FHIR resource type defined in STU3. + */ + @Generated + public static final HealthcareFhirResourceType DEVICE_COMPONENT = fromString("DeviceComponent"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType DEVICE_DEFINITION = fromString("DeviceDefinition"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType DEVICE_METRIC = fromString("DeviceMetric"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType DEVICE_REQUEST = fromString("DeviceRequest"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType DEVICE_USE_STATEMENT = fromString("DeviceUseStatement"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType DIAGNOSTIC_REPORT = fromString("DiagnosticReport"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType DOCUMENT_MANIFEST = fromString("DocumentManifest"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType DOCUMENT_REFERENCE = fromString("DocumentReference"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType DOMAIN_RESOURCE = fromString("DomainResource"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType EFFECT_EVIDENCE_SYNTHESIS = fromString("EffectEvidenceSynthesis"); + + /** + * The FHIR resource type defined in STU3. + */ + @Generated + public static final HealthcareFhirResourceType ELIGIBILITY_REQUEST = fromString("EligibilityRequest"); + + /** + * The FHIR resource type defined in STU3. + */ + @Generated + public static final HealthcareFhirResourceType ELIGIBILITY_RESPONSE = fromString("EligibilityResponse"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType ENCOUNTER = fromString("Encounter"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType ENDPOINT = fromString("Endpoint"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType ENROLLMENT_REQUEST = fromString("EnrollmentRequest"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType ENROLLMENT_RESPONSE = fromString("EnrollmentResponse"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType EPISODE_OF_CARE = fromString("EpisodeOfCare"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType EVENT_DEFINITION = fromString("EventDefinition"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType EVIDENCE = fromString("Evidence"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType EVIDENCE_VARIABLE = fromString("EvidenceVariable"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType EXAMPLE_SCENARIO = fromString("ExampleScenario"); + + /** + * The FHIR resource type defined in STU3. + */ + @Generated + public static final HealthcareFhirResourceType EXPANSION_PROFILE = fromString("ExpansionProfile"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType EXPLANATION_OF_BENEFIT = fromString("ExplanationOfBenefit"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType FAMILY_MEMBER_HISTORY = fromString("FamilyMemberHistory"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType FLAG = fromString("Flag"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType GOAL = fromString("Goal"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType GRAPH_DEFINITION = fromString("GraphDefinition"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType GROUP = fromString("Group"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType GUIDANCE_RESPONSE = fromString("GuidanceResponse"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType HEALTHCARE_SERVICE = fromString("HealthcareService"); + + /** + * The FHIR resource type defined in STU3. + */ + @Generated + public static final HealthcareFhirResourceType IMAGING_MANIFEST = fromString("ImagingManifest"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType IMAGING_STUDY = fromString("ImagingStudy"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType IMMUNIZATION = fromString("Immunization"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType IMMUNIZATION_EVALUATION = fromString("ImmunizationEvaluation"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType IMMUNIZATION_RECOMMENDATION + = fromString("ImmunizationRecommendation"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType IMPLEMENTATION_GUIDE = fromString("ImplementationGuide"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType INSURANCE_PLAN = fromString("InsurancePlan"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType INVOICE = fromString("Invoice"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType LIBRARY = fromString("Library"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType LINKAGE = fromString("Linkage"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType LIST = fromString("List"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType LOCATION = fromString("Location"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType MEASURE = fromString("Measure"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType MEASURE_REPORT = fromString("MeasureReport"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType MEDIA = fromString("Media"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType MEDICATION = fromString("Medication"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType MEDICATION_ADMINISTRATION = fromString("MedicationAdministration"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType MEDICATION_DISPENSE = fromString("MedicationDispense"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType MEDICATION_KNOWLEDGE = fromString("MedicationKnowledge"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType MEDICATION_REQUEST = fromString("MedicationRequest"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType MEDICATION_STATEMENT = fromString("MedicationStatement"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType MEDICINAL_PRODUCT = fromString("MedicinalProduct"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType MEDICINAL_PRODUCT_AUTHORIZATION + = fromString("MedicinalProductAuthorization"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType MEDICINAL_PRODUCT_CONTRAINDICATION + = fromString("MedicinalProductContraindication"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType MEDICINAL_PRODUCT_INDICATION + = fromString("MedicinalProductIndication"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType MEDICINAL_PRODUCT_INGREDIENT + = fromString("MedicinalProductIngredient"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType MEDICINAL_PRODUCT_INTERACTION + = fromString("MedicinalProductInteraction"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType MEDICINAL_PRODUCT_MANUFACTURED + = fromString("MedicinalProductManufactured"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType MEDICINAL_PRODUCT_PACKAGED = fromString("MedicinalProductPackaged"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType MEDICINAL_PRODUCT_PHARMACEUTICAL + = fromString("MedicinalProductPharmaceutical"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType MEDICINAL_PRODUCT_UNDESIRABLE_EFFECT + = fromString("MedicinalProductUndesirableEffect"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType MESSAGE_DEFINITION = fromString("MessageDefinition"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType MESSAGE_HEADER = fromString("MessageHeader"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType MOLECULAR_SEQUENCE = fromString("MolecularSequence"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType NAMING_SYSTEM = fromString("NamingSystem"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType NUTRITION_ORDER = fromString("NutritionOrder"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType OBSERVATION = fromString("Observation"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType OBSERVATION_DEFINITION = fromString("ObservationDefinition"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType OPERATION_DEFINITION = fromString("OperationDefinition"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType OPERATION_OUTCOME = fromString("OperationOutcome"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType ORGANIZATION = fromString("Organization"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType ORGANIZATION_AFFILIATION = fromString("OrganizationAffiliation"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType PARAMETERS = fromString("Parameters"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType PATIENT = fromString("Patient"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType PAYMENT_NOTICE = fromString("PaymentNotice"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType PAYMENT_RECONCILIATION = fromString("PaymentReconciliation"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType PERSON = fromString("Person"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType PLAN_DEFINITION = fromString("PlanDefinition"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType PRACTITIONER = fromString("Practitioner"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType PRACTITIONER_ROLE = fromString("PractitionerRole"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType PROCEDURE = fromString("Procedure"); + + /** + * The FHIR resource type defined in STU3. + */ + @Generated + public static final HealthcareFhirResourceType PROCEDURE_REQUEST = fromString("ProcedureRequest"); + + /** + * The FHIR resource type defined in STU3. + */ + @Generated + public static final HealthcareFhirResourceType PROCESS_REQUEST = fromString("ProcessRequest"); + + /** + * The FHIR resource type defined in STU3. + */ + @Generated + public static final HealthcareFhirResourceType PROCESS_RESPONSE = fromString("ProcessResponse"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType PROVENANCE = fromString("Provenance"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType QUESTIONNAIRE = fromString("Questionnaire"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType QUESTIONNAIRE_RESPONSE = fromString("QuestionnaireResponse"); + + /** + * The FHIR resource type defined in STU3. + */ + @Generated + public static final HealthcareFhirResourceType REFERRAL_REQUEST = fromString("ReferralRequest"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType RELATED_PERSON = fromString("RelatedPerson"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType REQUEST_GROUP = fromString("RequestGroup"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType RESEARCH_DEFINITION = fromString("ResearchDefinition"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType RESEARCH_ELEMENT_DEFINITION + = fromString("ResearchElementDefinition"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType RESEARCH_STUDY = fromString("ResearchStudy"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType RESEARCH_SUBJECT = fromString("ResearchSubject"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType RESOURCE = fromString("Resource"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType RISK_ASSESSMENT = fromString("RiskAssessment"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType RISK_EVIDENCE_SYNTHESIS = fromString("RiskEvidenceSynthesis"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType SCHEDULE = fromString("Schedule"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType SEARCH_PARAMETER = fromString("SearchParameter"); + + /** + * The FHIR resource type defined in STU3. + */ + @Generated + public static final HealthcareFhirResourceType SEQUENCE = fromString("Sequence"); + + /** + * The FHIR resource type defined in STU3. + */ + @Generated + public static final HealthcareFhirResourceType SERVICE_DEFINITION = fromString("ServiceDefinition"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType SERVICE_REQUEST = fromString("ServiceRequest"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType SLOT = fromString("Slot"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType SPECIMEN = fromString("Specimen"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType SPECIMEN_DEFINITION = fromString("SpecimenDefinition"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType STRUCTURE_DEFINITION = fromString("StructureDefinition"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType STRUCTURE_MAP = fromString("StructureMap"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType SUBSCRIPTION = fromString("Subscription"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType SUBSTANCE = fromString("Substance"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType SUBSTANCE_NUCLEIC_ACID = fromString("SubstanceNucleicAcid"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType SUBSTANCE_POLYMER = fromString("SubstancePolymer"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType SUBSTANCE_PROTEIN = fromString("SubstanceProtein"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType SUBSTANCE_REFERENCE_INFORMATION + = fromString("SubstanceReferenceInformation"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType SUBSTANCE_SOURCE_MATERIAL = fromString("SubstanceSourceMaterial"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType SUBSTANCE_SPECIFICATION = fromString("SubstanceSpecification"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType SUPPLY_DELIVERY = fromString("SupplyDelivery"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType SUPPLY_REQUEST = fromString("SupplyRequest"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType TASK = fromString("Task"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType TERMINOLOGY_CAPABILITIES = fromString("TerminologyCapabilities"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType TEST_REPORT = fromString("TestReport"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType TEST_SCRIPT = fromString("TestScript"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType VALUE_SET = fromString("ValueSet"); + + /** + * The FHIR resource type defined in R4. + */ + @Generated + public static final HealthcareFhirResourceType VERIFICATION_RESULT = fromString("VerificationResult"); + + /** + * The FHIR resource type defined in STU3 and R4. + */ + @Generated + public static final HealthcareFhirResourceType VISION_PRESCRIPTION = fromString("VisionPrescription"); + + /** + * Creates a new instance of HealthcareFhirResourceType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public HealthcareFhirResourceType() { + } + + /** + * Creates or finds a HealthcareFhirResourceType from its string representation. + * + * @param name a name to look for. + * @return the corresponding HealthcareFhirResourceType. + */ + @Generated + public static HealthcareFhirResourceType fromString(String name) { + return fromString(name, HealthcareFhirResourceType.class); + } + + /** + * Gets known HealthcareFhirResourceType values. + * + * @return known HealthcareFhirResourceType values. + */ + @Generated + public static Collection values() { + return values(HealthcareFhirResourceType.class); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/HealthcareFhirResourceUpdatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/HealthcareFhirResourceUpdatedEventData.java new file mode 100644 index 000000000000..0d2de7041e87 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/HealthcareFhirResourceUpdatedEventData.java @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.HealthcareApis.FhirResourceUpdated event. + */ +@Immutable +public final class HealthcareFhirResourceUpdatedEventData + implements JsonSerializable { + /* + * Type of HL7 FHIR resource. + */ + @Generated + private final HealthcareFhirResourceType resourceType; + + /* + * Domain name of FHIR account for this resource. + */ + @Generated + private final String resourceFhirAccount; + + /* + * Id of HL7 FHIR resource. + */ + @Generated + private final String resourceFhirId; + + /* + * VersionId of HL7 FHIR resource. It changes when the resource is created, updated, or deleted(soft-deletion). + */ + @Generated + private final long resourceVersionId; + + /** + * Creates an instance of HealthcareFhirResourceUpdatedEventData class. + * + * @param resourceType the resourceType value to set. + * @param resourceFhirAccount the resourceFhirAccount value to set. + * @param resourceFhirId the resourceFhirId value to set. + * @param resourceVersionId the resourceVersionId value to set. + */ + @Generated + private HealthcareFhirResourceUpdatedEventData(HealthcareFhirResourceType resourceType, String resourceFhirAccount, + String resourceFhirId, long resourceVersionId) { + this.resourceType = resourceType; + this.resourceFhirAccount = resourceFhirAccount; + this.resourceFhirId = resourceFhirId; + this.resourceVersionId = resourceVersionId; + } + + /** + * Get the resourceType property: Type of HL7 FHIR resource. + * + * @return the resourceType value. + */ + @Generated + public HealthcareFhirResourceType getResourceType() { + return this.resourceType; + } + + /** + * Get the resourceFhirAccount property: Domain name of FHIR account for this resource. + * + * @return the resourceFhirAccount value. + */ + @Generated + public String getResourceFhirAccount() { + return this.resourceFhirAccount; + } + + /** + * Get the resourceFhirId property: Id of HL7 FHIR resource. + * + * @return the resourceFhirId value. + */ + @Generated + public String getResourceFhirId() { + return this.resourceFhirId; + } + + /** + * Get the resourceVersionId property: VersionId of HL7 FHIR resource. It changes when the resource is created, + * updated, or deleted(soft-deletion). + * + * @return the resourceVersionId value. + */ + @Generated + public long getResourceVersionId() { + return this.resourceVersionId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceType", this.resourceType == null ? null : this.resourceType.toString()); + jsonWriter.writeStringField("resourceFhirAccount", this.resourceFhirAccount); + jsonWriter.writeStringField("resourceFhirId", this.resourceFhirId); + jsonWriter.writeLongField("resourceVersionId", this.resourceVersionId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of HealthcareFhirResourceUpdatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of HealthcareFhirResourceUpdatedEventData 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 HealthcareFhirResourceUpdatedEventData. + */ + @Generated + public static HealthcareFhirResourceUpdatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + HealthcareFhirResourceType resourceType = null; + String resourceFhirAccount = null; + String resourceFhirId = null; + long resourceVersionId = 0L; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceType".equals(fieldName)) { + resourceType = HealthcareFhirResourceType.fromString(reader.getString()); + } else if ("resourceFhirAccount".equals(fieldName)) { + resourceFhirAccount = reader.getString(); + } else if ("resourceFhirId".equals(fieldName)) { + resourceFhirId = reader.getString(); + } else if ("resourceVersionId".equals(fieldName)) { + resourceVersionId = reader.getLong(); + } else { + reader.skipChildren(); + } + } + return new HealthcareFhirResourceUpdatedEventData(resourceType, resourceFhirAccount, resourceFhirId, + resourceVersionId); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/IotHubDeviceConnectedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/IotHubDeviceConnectedEventData.java new file mode 100644 index 000000000000..e33a62cba6bf --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/IotHubDeviceConnectedEventData.java @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Event data for Microsoft.Devices.DeviceConnected event. + */ +@Immutable +public final class IotHubDeviceConnectedEventData extends DeviceConnectionStateEventProperties { + /* + * The unique identifier of the module. This case-sensitive string can be up to 128 characters long, and supports + * ASCII 7-bit alphanumeric characters plus the following special characters: - : . + % _ # * ? ! ( ) , = `@` ; + * $ '. + */ + @Generated + private String moduleId; + + /** + * Creates an instance of IotHubDeviceConnectedEventData class. + * + * @param deviceId the deviceId value to set. + * @param hubName the hubName value to set. + * @param deviceConnectionStateEventInfo the deviceConnectionStateEventInfo value to set. + */ + @Generated + private IotHubDeviceConnectedEventData(String deviceId, String hubName, + DeviceConnectionStateEventInfo deviceConnectionStateEventInfo) { + super(deviceId, hubName, deviceConnectionStateEventInfo); + } + + /** + * Get the moduleId property: The unique identifier of the module. This case-sensitive string can be up to 128 + * characters long, and supports ASCII 7-bit alphanumeric characters plus the following special characters: - : . + + * % _ &#35; * ? ! ( ) , = `@` ; $ '. + * + * @return the moduleId value. + */ + @Generated + @Override + public String getModuleId() { + return this.moduleId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("deviceId", getDeviceId()); + jsonWriter.writeStringField("hubName", getHubName()); + jsonWriter.writeJsonField("deviceConnectionStateEventInfo", getDeviceConnectionStateEventInfo()); + jsonWriter.writeStringField("moduleId", getModuleId()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of IotHubDeviceConnectedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of IotHubDeviceConnectedEventData 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 IotHubDeviceConnectedEventData. + */ + @Generated + public static IotHubDeviceConnectedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String deviceId = null; + String hubName = null; + DeviceConnectionStateEventInfo deviceConnectionStateEventInfo = null; + String moduleId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("deviceId".equals(fieldName)) { + deviceId = reader.getString(); + } else if ("hubName".equals(fieldName)) { + hubName = reader.getString(); + } else if ("deviceConnectionStateEventInfo".equals(fieldName)) { + deviceConnectionStateEventInfo = DeviceConnectionStateEventInfo.fromJson(reader); + } else if ("moduleId".equals(fieldName)) { + moduleId = reader.getString(); + } else { + reader.skipChildren(); + } + } + IotHubDeviceConnectedEventData deserializedIotHubDeviceConnectedEventData + = new IotHubDeviceConnectedEventData(deviceId, hubName, deviceConnectionStateEventInfo); + deserializedIotHubDeviceConnectedEventData.moduleId = moduleId; + + return deserializedIotHubDeviceConnectedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/IotHubDeviceCreatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/IotHubDeviceCreatedEventData.java new file mode 100644 index 000000000000..612d70add891 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/IotHubDeviceCreatedEventData.java @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Event data for Microsoft.Devices.DeviceCreated event. + */ +@Immutable +public final class IotHubDeviceCreatedEventData extends DeviceLifeCycleEventProperties { + /** + * Creates an instance of IotHubDeviceCreatedEventData class. + * + * @param deviceId the deviceId value to set. + * @param hubName the hubName value to set. + * @param twin the twin value to set. + */ + @Generated + private IotHubDeviceCreatedEventData(String deviceId, String hubName, DeviceTwinInfo twin) { + super(deviceId, hubName, twin); + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("deviceId", getDeviceId()); + jsonWriter.writeStringField("hubName", getHubName()); + jsonWriter.writeJsonField("twin", getTwin()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of IotHubDeviceCreatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of IotHubDeviceCreatedEventData 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 IotHubDeviceCreatedEventData. + */ + @Generated + public static IotHubDeviceCreatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String deviceId = null; + String hubName = null; + DeviceTwinInfo twin = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("deviceId".equals(fieldName)) { + deviceId = reader.getString(); + } else if ("hubName".equals(fieldName)) { + hubName = reader.getString(); + } else if ("twin".equals(fieldName)) { + twin = DeviceTwinInfo.fromJson(reader); + } else { + reader.skipChildren(); + } + } + return new IotHubDeviceCreatedEventData(deviceId, hubName, twin); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/IotHubDeviceDeletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/IotHubDeviceDeletedEventData.java new file mode 100644 index 000000000000..db2b9e3321a4 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/IotHubDeviceDeletedEventData.java @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Event data for Microsoft.Devices.DeviceDeleted event. + */ +@Immutable +public final class IotHubDeviceDeletedEventData extends DeviceLifeCycleEventProperties { + /** + * Creates an instance of IotHubDeviceDeletedEventData class. + * + * @param deviceId the deviceId value to set. + * @param hubName the hubName value to set. + * @param twin the twin value to set. + */ + @Generated + private IotHubDeviceDeletedEventData(String deviceId, String hubName, DeviceTwinInfo twin) { + super(deviceId, hubName, twin); + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("deviceId", getDeviceId()); + jsonWriter.writeStringField("hubName", getHubName()); + jsonWriter.writeJsonField("twin", getTwin()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of IotHubDeviceDeletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of IotHubDeviceDeletedEventData 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 IotHubDeviceDeletedEventData. + */ + @Generated + public static IotHubDeviceDeletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String deviceId = null; + String hubName = null; + DeviceTwinInfo twin = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("deviceId".equals(fieldName)) { + deviceId = reader.getString(); + } else if ("hubName".equals(fieldName)) { + hubName = reader.getString(); + } else if ("twin".equals(fieldName)) { + twin = DeviceTwinInfo.fromJson(reader); + } else { + reader.skipChildren(); + } + } + return new IotHubDeviceDeletedEventData(deviceId, hubName, twin); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/IotHubDeviceDisconnectedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/IotHubDeviceDisconnectedEventData.java new file mode 100644 index 000000000000..1d58273652e7 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/IotHubDeviceDisconnectedEventData.java @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Event data for Microsoft.Devices.DeviceDisconnected event. + */ +@Immutable +public final class IotHubDeviceDisconnectedEventData extends DeviceConnectionStateEventProperties { + /* + * The unique identifier of the module. This case-sensitive string can be up to 128 characters long, and supports + * ASCII 7-bit alphanumeric characters plus the following special characters: - : . + % _ # * ? ! ( ) , = `@` ; + * $ '. + */ + @Generated + private String moduleId; + + /** + * Creates an instance of IotHubDeviceDisconnectedEventData class. + * + * @param deviceId the deviceId value to set. + * @param hubName the hubName value to set. + * @param deviceConnectionStateEventInfo the deviceConnectionStateEventInfo value to set. + */ + @Generated + private IotHubDeviceDisconnectedEventData(String deviceId, String hubName, + DeviceConnectionStateEventInfo deviceConnectionStateEventInfo) { + super(deviceId, hubName, deviceConnectionStateEventInfo); + } + + /** + * Get the moduleId property: The unique identifier of the module. This case-sensitive string can be up to 128 + * characters long, and supports ASCII 7-bit alphanumeric characters plus the following special characters: - : . + + * % _ &#35; * ? ! ( ) , = `@` ; $ '. + * + * @return the moduleId value. + */ + @Generated + @Override + public String getModuleId() { + return this.moduleId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("deviceId", getDeviceId()); + jsonWriter.writeStringField("hubName", getHubName()); + jsonWriter.writeJsonField("deviceConnectionStateEventInfo", getDeviceConnectionStateEventInfo()); + jsonWriter.writeStringField("moduleId", getModuleId()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of IotHubDeviceDisconnectedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of IotHubDeviceDisconnectedEventData 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 IotHubDeviceDisconnectedEventData. + */ + @Generated + public static IotHubDeviceDisconnectedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String deviceId = null; + String hubName = null; + DeviceConnectionStateEventInfo deviceConnectionStateEventInfo = null; + String moduleId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("deviceId".equals(fieldName)) { + deviceId = reader.getString(); + } else if ("hubName".equals(fieldName)) { + hubName = reader.getString(); + } else if ("deviceConnectionStateEventInfo".equals(fieldName)) { + deviceConnectionStateEventInfo = DeviceConnectionStateEventInfo.fromJson(reader); + } else if ("moduleId".equals(fieldName)) { + moduleId = reader.getString(); + } else { + reader.skipChildren(); + } + } + IotHubDeviceDisconnectedEventData deserializedIotHubDeviceDisconnectedEventData + = new IotHubDeviceDisconnectedEventData(deviceId, hubName, deviceConnectionStateEventInfo); + deserializedIotHubDeviceDisconnectedEventData.moduleId = moduleId; + + return deserializedIotHubDeviceDisconnectedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/IotHubDeviceTelemetryEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/IotHubDeviceTelemetryEventData.java new file mode 100644 index 000000000000..0bf4c76ef6f6 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/IotHubDeviceTelemetryEventData.java @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.BinaryData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.Map; + +/** + * Event data for Microsoft.Devices.DeviceTelemetry event. + */ +@Immutable +public final class IotHubDeviceTelemetryEventData extends DeviceTelemetryEventProperties { + /** + * Creates an instance of IotHubDeviceTelemetryEventData class. + * + * @param body the body value to set. + * @param properties the properties value to set. + * @param systemProperties the systemProperties value to set. + */ + @Generated + private IotHubDeviceTelemetryEventData(Map body, Map properties, + Map systemProperties) { + super(body, properties, systemProperties); + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("body", getBody(), + (writer, element) -> writer.writeUntyped(element == null ? null : element.toObject(Object.class))); + jsonWriter.writeMapField("properties", getProperties(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeMapField("systemProperties", getSystemProperties(), + (writer, element) -> writer.writeString(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of IotHubDeviceTelemetryEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of IotHubDeviceTelemetryEventData 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 IotHubDeviceTelemetryEventData. + */ + @Generated + public static IotHubDeviceTelemetryEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Map body = null; + Map properties = null; + Map systemProperties = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("body".equals(fieldName)) { + body = reader.readMap(reader1 -> reader1 + .getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); + } else if ("properties".equals(fieldName)) { + properties = reader.readMap(reader1 -> reader1.getString()); + } else if ("systemProperties".equals(fieldName)) { + systemProperties = reader.readMap(reader1 -> reader1.getString()); + } else { + reader.skipChildren(); + } + } + return new IotHubDeviceTelemetryEventData(body, properties, systemProperties); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultAccessPolicyChangedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultAccessPolicyChangedEventData.java new file mode 100644 index 000000000000..d68988cd1534 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultAccessPolicyChangedEventData.java @@ -0,0 +1,217 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.VaultAccessPolicyChanged event. + */ +@Immutable +public final class KeyVaultAccessPolicyChangedEventData + implements JsonSerializable { + /* + * The id of the object that triggered this event. + */ + @Generated + private final String id; + + /* + * Key vault name of the object that triggered this event. + */ + @Generated + private final String vaultName; + + /* + * The type of the object that triggered this event + */ + @Generated + private final String objectType; + + /* + * The name of the object that triggered this event + */ + @Generated + private final String objectName; + + /* + * The version of the object that triggered this event + */ + @Generated + private final String version; + + /* + * Not before date of the object that triggered this event + */ + @Generated + private final double nbf; + + /* + * The expiration date of the object that triggered this event + */ + @Generated + private final double exp; + + /** + * Creates an instance of KeyVaultAccessPolicyChangedEventData class. + * + * @param id the id value to set. + * @param vaultName the vaultName value to set. + * @param objectType the objectType value to set. + * @param objectName the objectName value to set. + * @param version the version value to set. + * @param nbf the nbf value to set. + * @param exp the exp value to set. + */ + @Generated + private KeyVaultAccessPolicyChangedEventData(String id, String vaultName, String objectType, String objectName, + String version, double nbf, double exp) { + this.id = id; + this.vaultName = vaultName; + this.objectType = objectType; + this.objectName = objectName; + this.version = version; + this.nbf = nbf; + this.exp = exp; + } + + /** + * Get the id property: The id of the object that triggered this event. + * + * @return the id value. + */ + @Generated + public String getId() { + return this.id; + } + + /** + * Get the vaultName property: Key vault name of the object that triggered this event. + * + * @return the vaultName value. + */ + @Generated + public String getVaultName() { + return this.vaultName; + } + + /** + * Get the objectType property: The type of the object that triggered this event. + * + * @return the objectType value. + */ + @Generated + public String getObjectType() { + return this.objectType; + } + + /** + * Get the objectName property: The name of the object that triggered this event. + * + * @return the objectName value. + */ + @Generated + public String getObjectName() { + return this.objectName; + } + + /** + * Get the version property: The version of the object that triggered this event. + * + * @return the version value. + */ + @Generated + public String getVersion() { + return this.version; + } + + /** + * Get the nbf property: Not before date of the object that triggered this event. + * + * @return the nbf value. + */ + @Generated + public double getNbf() { + return this.nbf; + } + + /** + * Get the exp property: The expiration date of the object that triggered this event. + * + * @return the exp value. + */ + @Generated + public double getExp() { + return this.exp; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("Id", this.id); + jsonWriter.writeStringField("VaultName", this.vaultName); + jsonWriter.writeStringField("ObjectType", this.objectType); + jsonWriter.writeStringField("ObjectName", this.objectName); + jsonWriter.writeStringField("Version", this.version); + jsonWriter.writeDoubleField("NBF", this.nbf); + jsonWriter.writeDoubleField("EXP", this.exp); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KeyVaultAccessPolicyChangedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KeyVaultAccessPolicyChangedEventData 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 KeyVaultAccessPolicyChangedEventData. + */ + @Generated + public static KeyVaultAccessPolicyChangedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String id = null; + String vaultName = null; + String objectType = null; + String objectName = null; + String version = null; + double nbf = 0.0; + double exp = 0.0; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("Id".equals(fieldName)) { + id = reader.getString(); + } else if ("VaultName".equals(fieldName)) { + vaultName = reader.getString(); + } else if ("ObjectType".equals(fieldName)) { + objectType = reader.getString(); + } else if ("ObjectName".equals(fieldName)) { + objectName = reader.getString(); + } else if ("Version".equals(fieldName)) { + version = reader.getString(); + } else if ("NBF".equals(fieldName)) { + nbf = reader.getDouble(); + } else if ("EXP".equals(fieldName)) { + exp = reader.getDouble(); + } else { + reader.skipChildren(); + } + } + return new KeyVaultAccessPolicyChangedEventData(id, vaultName, objectType, objectName, version, nbf, exp); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultCertificateExpiredEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultCertificateExpiredEventData.java new file mode 100644 index 000000000000..bebe82a071f5 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultCertificateExpiredEventData.java @@ -0,0 +1,217 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.CertificateExpired event. + */ +@Immutable +public final class KeyVaultCertificateExpiredEventData + implements JsonSerializable { + /* + * The id of the object that triggered this event. + */ + @Generated + private final String id; + + /* + * Key vault name of the object that triggered this event. + */ + @Generated + private final String vaultName; + + /* + * The type of the object that triggered this event + */ + @Generated + private final String objectType; + + /* + * The name of the object that triggered this event + */ + @Generated + private final String objectName; + + /* + * The version of the object that triggered this event + */ + @Generated + private final String version; + + /* + * Not before date of the object that triggered this event + */ + @Generated + private final double nbf; + + /* + * The expiration date of the object that triggered this event + */ + @Generated + private final double exp; + + /** + * Creates an instance of KeyVaultCertificateExpiredEventData class. + * + * @param id the id value to set. + * @param vaultName the vaultName value to set. + * @param objectType the objectType value to set. + * @param objectName the objectName value to set. + * @param version the version value to set. + * @param nbf the nbf value to set. + * @param exp the exp value to set. + */ + @Generated + private KeyVaultCertificateExpiredEventData(String id, String vaultName, String objectType, String objectName, + String version, double nbf, double exp) { + this.id = id; + this.vaultName = vaultName; + this.objectType = objectType; + this.objectName = objectName; + this.version = version; + this.nbf = nbf; + this.exp = exp; + } + + /** + * Get the id property: The id of the object that triggered this event. + * + * @return the id value. + */ + @Generated + public String getId() { + return this.id; + } + + /** + * Get the vaultName property: Key vault name of the object that triggered this event. + * + * @return the vaultName value. + */ + @Generated + public String getVaultName() { + return this.vaultName; + } + + /** + * Get the objectType property: The type of the object that triggered this event. + * + * @return the objectType value. + */ + @Generated + public String getObjectType() { + return this.objectType; + } + + /** + * Get the objectName property: The name of the object that triggered this event. + * + * @return the objectName value. + */ + @Generated + public String getObjectName() { + return this.objectName; + } + + /** + * Get the version property: The version of the object that triggered this event. + * + * @return the version value. + */ + @Generated + public String getVersion() { + return this.version; + } + + /** + * Get the nbf property: Not before date of the object that triggered this event. + * + * @return the nbf value. + */ + @Generated + public double getNbf() { + return this.nbf; + } + + /** + * Get the exp property: The expiration date of the object that triggered this event. + * + * @return the exp value. + */ + @Generated + public double getExp() { + return this.exp; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("Id", this.id); + jsonWriter.writeStringField("VaultName", this.vaultName); + jsonWriter.writeStringField("ObjectType", this.objectType); + jsonWriter.writeStringField("ObjectName", this.objectName); + jsonWriter.writeStringField("Version", this.version); + jsonWriter.writeDoubleField("NBF", this.nbf); + jsonWriter.writeDoubleField("EXP", this.exp); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KeyVaultCertificateExpiredEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KeyVaultCertificateExpiredEventData 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 KeyVaultCertificateExpiredEventData. + */ + @Generated + public static KeyVaultCertificateExpiredEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String id = null; + String vaultName = null; + String objectType = null; + String objectName = null; + String version = null; + double nbf = 0.0; + double exp = 0.0; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("Id".equals(fieldName)) { + id = reader.getString(); + } else if ("VaultName".equals(fieldName)) { + vaultName = reader.getString(); + } else if ("ObjectType".equals(fieldName)) { + objectType = reader.getString(); + } else if ("ObjectName".equals(fieldName)) { + objectName = reader.getString(); + } else if ("Version".equals(fieldName)) { + version = reader.getString(); + } else if ("NBF".equals(fieldName)) { + nbf = reader.getDouble(); + } else if ("EXP".equals(fieldName)) { + exp = reader.getDouble(); + } else { + reader.skipChildren(); + } + } + return new KeyVaultCertificateExpiredEventData(id, vaultName, objectType, objectName, version, nbf, exp); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultCertificateNearExpiryEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultCertificateNearExpiryEventData.java new file mode 100644 index 000000000000..9e6c30b0684c --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultCertificateNearExpiryEventData.java @@ -0,0 +1,217 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.CertificateNearExpiry event. + */ +@Immutable +public final class KeyVaultCertificateNearExpiryEventData + implements JsonSerializable { + /* + * The id of the object that triggered this event. + */ + @Generated + private final String id; + + /* + * Key vault name of the object that triggered this event. + */ + @Generated + private final String vaultName; + + /* + * The type of the object that triggered this event + */ + @Generated + private final String objectType; + + /* + * The name of the object that triggered this event + */ + @Generated + private final String objectName; + + /* + * The version of the object that triggered this event + */ + @Generated + private final String version; + + /* + * Not before date of the object that triggered this event + */ + @Generated + private final double nbf; + + /* + * The expiration date of the object that triggered this event + */ + @Generated + private final double exp; + + /** + * Creates an instance of KeyVaultCertificateNearExpiryEventData class. + * + * @param id the id value to set. + * @param vaultName the vaultName value to set. + * @param objectType the objectType value to set. + * @param objectName the objectName value to set. + * @param version the version value to set. + * @param nbf the nbf value to set. + * @param exp the exp value to set. + */ + @Generated + private KeyVaultCertificateNearExpiryEventData(String id, String vaultName, String objectType, String objectName, + String version, double nbf, double exp) { + this.id = id; + this.vaultName = vaultName; + this.objectType = objectType; + this.objectName = objectName; + this.version = version; + this.nbf = nbf; + this.exp = exp; + } + + /** + * Get the id property: The id of the object that triggered this event. + * + * @return the id value. + */ + @Generated + public String getId() { + return this.id; + } + + /** + * Get the vaultName property: Key vault name of the object that triggered this event. + * + * @return the vaultName value. + */ + @Generated + public String getVaultName() { + return this.vaultName; + } + + /** + * Get the objectType property: The type of the object that triggered this event. + * + * @return the objectType value. + */ + @Generated + public String getObjectType() { + return this.objectType; + } + + /** + * Get the objectName property: The name of the object that triggered this event. + * + * @return the objectName value. + */ + @Generated + public String getObjectName() { + return this.objectName; + } + + /** + * Get the version property: The version of the object that triggered this event. + * + * @return the version value. + */ + @Generated + public String getVersion() { + return this.version; + } + + /** + * Get the nbf property: Not before date of the object that triggered this event. + * + * @return the nbf value. + */ + @Generated + public double getNbf() { + return this.nbf; + } + + /** + * Get the exp property: The expiration date of the object that triggered this event. + * + * @return the exp value. + */ + @Generated + public double getExp() { + return this.exp; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("Id", this.id); + jsonWriter.writeStringField("VaultName", this.vaultName); + jsonWriter.writeStringField("ObjectType", this.objectType); + jsonWriter.writeStringField("ObjectName", this.objectName); + jsonWriter.writeStringField("Version", this.version); + jsonWriter.writeDoubleField("NBF", this.nbf); + jsonWriter.writeDoubleField("EXP", this.exp); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KeyVaultCertificateNearExpiryEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KeyVaultCertificateNearExpiryEventData 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 KeyVaultCertificateNearExpiryEventData. + */ + @Generated + public static KeyVaultCertificateNearExpiryEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String id = null; + String vaultName = null; + String objectType = null; + String objectName = null; + String version = null; + double nbf = 0.0; + double exp = 0.0; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("Id".equals(fieldName)) { + id = reader.getString(); + } else if ("VaultName".equals(fieldName)) { + vaultName = reader.getString(); + } else if ("ObjectType".equals(fieldName)) { + objectType = reader.getString(); + } else if ("ObjectName".equals(fieldName)) { + objectName = reader.getString(); + } else if ("Version".equals(fieldName)) { + version = reader.getString(); + } else if ("NBF".equals(fieldName)) { + nbf = reader.getDouble(); + } else if ("EXP".equals(fieldName)) { + exp = reader.getDouble(); + } else { + reader.skipChildren(); + } + } + return new KeyVaultCertificateNearExpiryEventData(id, vaultName, objectType, objectName, version, nbf, exp); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultCertificateNewVersionCreatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultCertificateNewVersionCreatedEventData.java new file mode 100644 index 000000000000..e8e3a39fc045 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultCertificateNewVersionCreatedEventData.java @@ -0,0 +1,218 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.CertificateNewVersionCreated event. + */ +@Immutable +public final class KeyVaultCertificateNewVersionCreatedEventData + implements JsonSerializable { + /* + * The id of the object that triggered this event. + */ + @Generated + private final String id; + + /* + * Key vault name of the object that triggered this event. + */ + @Generated + private final String vaultName; + + /* + * The type of the object that triggered this event + */ + @Generated + private final String objectType; + + /* + * The name of the object that triggered this event + */ + @Generated + private final String objectName; + + /* + * The version of the object that triggered this event + */ + @Generated + private final String version; + + /* + * Not before date of the object that triggered this event + */ + @Generated + private final double nbf; + + /* + * The expiration date of the object that triggered this event + */ + @Generated + private final double exp; + + /** + * Creates an instance of KeyVaultCertificateNewVersionCreatedEventData class. + * + * @param id the id value to set. + * @param vaultName the vaultName value to set. + * @param objectType the objectType value to set. + * @param objectName the objectName value to set. + * @param version the version value to set. + * @param nbf the nbf value to set. + * @param exp the exp value to set. + */ + @Generated + private KeyVaultCertificateNewVersionCreatedEventData(String id, String vaultName, String objectType, + String objectName, String version, double nbf, double exp) { + this.id = id; + this.vaultName = vaultName; + this.objectType = objectType; + this.objectName = objectName; + this.version = version; + this.nbf = nbf; + this.exp = exp; + } + + /** + * Get the id property: The id of the object that triggered this event. + * + * @return the id value. + */ + @Generated + public String getId() { + return this.id; + } + + /** + * Get the vaultName property: Key vault name of the object that triggered this event. + * + * @return the vaultName value. + */ + @Generated + public String getVaultName() { + return this.vaultName; + } + + /** + * Get the objectType property: The type of the object that triggered this event. + * + * @return the objectType value. + */ + @Generated + public String getObjectType() { + return this.objectType; + } + + /** + * Get the objectName property: The name of the object that triggered this event. + * + * @return the objectName value. + */ + @Generated + public String getObjectName() { + return this.objectName; + } + + /** + * Get the version property: The version of the object that triggered this event. + * + * @return the version value. + */ + @Generated + public String getVersion() { + return this.version; + } + + /** + * Get the nbf property: Not before date of the object that triggered this event. + * + * @return the nbf value. + */ + @Generated + public double getNbf() { + return this.nbf; + } + + /** + * Get the exp property: The expiration date of the object that triggered this event. + * + * @return the exp value. + */ + @Generated + public double getExp() { + return this.exp; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("Id", this.id); + jsonWriter.writeStringField("VaultName", this.vaultName); + jsonWriter.writeStringField("ObjectType", this.objectType); + jsonWriter.writeStringField("ObjectName", this.objectName); + jsonWriter.writeStringField("Version", this.version); + jsonWriter.writeDoubleField("NBF", this.nbf); + jsonWriter.writeDoubleField("EXP", this.exp); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KeyVaultCertificateNewVersionCreatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KeyVaultCertificateNewVersionCreatedEventData 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 KeyVaultCertificateNewVersionCreatedEventData. + */ + @Generated + public static KeyVaultCertificateNewVersionCreatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String id = null; + String vaultName = null; + String objectType = null; + String objectName = null; + String version = null; + double nbf = 0.0; + double exp = 0.0; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("Id".equals(fieldName)) { + id = reader.getString(); + } else if ("VaultName".equals(fieldName)) { + vaultName = reader.getString(); + } else if ("ObjectType".equals(fieldName)) { + objectType = reader.getString(); + } else if ("ObjectName".equals(fieldName)) { + objectName = reader.getString(); + } else if ("Version".equals(fieldName)) { + version = reader.getString(); + } else if ("NBF".equals(fieldName)) { + nbf = reader.getDouble(); + } else if ("EXP".equals(fieldName)) { + exp = reader.getDouble(); + } else { + reader.skipChildren(); + } + } + return new KeyVaultCertificateNewVersionCreatedEventData(id, vaultName, objectType, objectName, version, + nbf, exp); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultKeyExpiredEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultKeyExpiredEventData.java new file mode 100644 index 000000000000..cdd23b1add4b --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultKeyExpiredEventData.java @@ -0,0 +1,216 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.KeyExpired event. + */ +@Immutable +public final class KeyVaultKeyExpiredEventData implements JsonSerializable { + /* + * The id of the object that triggered this event. + */ + @Generated + private final String id; + + /* + * Key vault name of the object that triggered this event. + */ + @Generated + private final String vaultName; + + /* + * The type of the object that triggered this event + */ + @Generated + private final String objectType; + + /* + * The name of the object that triggered this event + */ + @Generated + private final String objectName; + + /* + * The version of the object that triggered this event + */ + @Generated + private final String version; + + /* + * Not before date of the object that triggered this event + */ + @Generated + private final double nbf; + + /* + * The expiration date of the object that triggered this event + */ + @Generated + private final double exp; + + /** + * Creates an instance of KeyVaultKeyExpiredEventData class. + * + * @param id the id value to set. + * @param vaultName the vaultName value to set. + * @param objectType the objectType value to set. + * @param objectName the objectName value to set. + * @param version the version value to set. + * @param nbf the nbf value to set. + * @param exp the exp value to set. + */ + @Generated + private KeyVaultKeyExpiredEventData(String id, String vaultName, String objectType, String objectName, + String version, double nbf, double exp) { + this.id = id; + this.vaultName = vaultName; + this.objectType = objectType; + this.objectName = objectName; + this.version = version; + this.nbf = nbf; + this.exp = exp; + } + + /** + * Get the id property: The id of the object that triggered this event. + * + * @return the id value. + */ + @Generated + public String getId() { + return this.id; + } + + /** + * Get the vaultName property: Key vault name of the object that triggered this event. + * + * @return the vaultName value. + */ + @Generated + public String getVaultName() { + return this.vaultName; + } + + /** + * Get the objectType property: The type of the object that triggered this event. + * + * @return the objectType value. + */ + @Generated + public String getObjectType() { + return this.objectType; + } + + /** + * Get the objectName property: The name of the object that triggered this event. + * + * @return the objectName value. + */ + @Generated + public String getObjectName() { + return this.objectName; + } + + /** + * Get the version property: The version of the object that triggered this event. + * + * @return the version value. + */ + @Generated + public String getVersion() { + return this.version; + } + + /** + * Get the nbf property: Not before date of the object that triggered this event. + * + * @return the nbf value. + */ + @Generated + public double getNbf() { + return this.nbf; + } + + /** + * Get the exp property: The expiration date of the object that triggered this event. + * + * @return the exp value. + */ + @Generated + public double getExp() { + return this.exp; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("Id", this.id); + jsonWriter.writeStringField("VaultName", this.vaultName); + jsonWriter.writeStringField("ObjectType", this.objectType); + jsonWriter.writeStringField("ObjectName", this.objectName); + jsonWriter.writeStringField("Version", this.version); + jsonWriter.writeDoubleField("NBF", this.nbf); + jsonWriter.writeDoubleField("EXP", this.exp); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KeyVaultKeyExpiredEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KeyVaultKeyExpiredEventData 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 KeyVaultKeyExpiredEventData. + */ + @Generated + public static KeyVaultKeyExpiredEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String id = null; + String vaultName = null; + String objectType = null; + String objectName = null; + String version = null; + double nbf = 0.0; + double exp = 0.0; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("Id".equals(fieldName)) { + id = reader.getString(); + } else if ("VaultName".equals(fieldName)) { + vaultName = reader.getString(); + } else if ("ObjectType".equals(fieldName)) { + objectType = reader.getString(); + } else if ("ObjectName".equals(fieldName)) { + objectName = reader.getString(); + } else if ("Version".equals(fieldName)) { + version = reader.getString(); + } else if ("NBF".equals(fieldName)) { + nbf = reader.getDouble(); + } else if ("EXP".equals(fieldName)) { + exp = reader.getDouble(); + } else { + reader.skipChildren(); + } + } + return new KeyVaultKeyExpiredEventData(id, vaultName, objectType, objectName, version, nbf, exp); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultKeyNearExpiryEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultKeyNearExpiryEventData.java new file mode 100644 index 000000000000..2ce777c42e90 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultKeyNearExpiryEventData.java @@ -0,0 +1,216 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.KeyNearExpiry event. + */ +@Immutable +public final class KeyVaultKeyNearExpiryEventData implements JsonSerializable { + /* + * The id of the object that triggered this event. + */ + @Generated + private final String id; + + /* + * Key vault name of the object that triggered this event. + */ + @Generated + private final String vaultName; + + /* + * The type of the object that triggered this event + */ + @Generated + private final String objectType; + + /* + * The name of the object that triggered this event + */ + @Generated + private final String objectName; + + /* + * The version of the object that triggered this event + */ + @Generated + private final String version; + + /* + * Not before date of the object that triggered this event + */ + @Generated + private final double nbf; + + /* + * The expiration date of the object that triggered this event + */ + @Generated + private final double exp; + + /** + * Creates an instance of KeyVaultKeyNearExpiryEventData class. + * + * @param id the id value to set. + * @param vaultName the vaultName value to set. + * @param objectType the objectType value to set. + * @param objectName the objectName value to set. + * @param version the version value to set. + * @param nbf the nbf value to set. + * @param exp the exp value to set. + */ + @Generated + private KeyVaultKeyNearExpiryEventData(String id, String vaultName, String objectType, String objectName, + String version, double nbf, double exp) { + this.id = id; + this.vaultName = vaultName; + this.objectType = objectType; + this.objectName = objectName; + this.version = version; + this.nbf = nbf; + this.exp = exp; + } + + /** + * Get the id property: The id of the object that triggered this event. + * + * @return the id value. + */ + @Generated + public String getId() { + return this.id; + } + + /** + * Get the vaultName property: Key vault name of the object that triggered this event. + * + * @return the vaultName value. + */ + @Generated + public String getVaultName() { + return this.vaultName; + } + + /** + * Get the objectType property: The type of the object that triggered this event. + * + * @return the objectType value. + */ + @Generated + public String getObjectType() { + return this.objectType; + } + + /** + * Get the objectName property: The name of the object that triggered this event. + * + * @return the objectName value. + */ + @Generated + public String getObjectName() { + return this.objectName; + } + + /** + * Get the version property: The version of the object that triggered this event. + * + * @return the version value. + */ + @Generated + public String getVersion() { + return this.version; + } + + /** + * Get the nbf property: Not before date of the object that triggered this event. + * + * @return the nbf value. + */ + @Generated + public double getNbf() { + return this.nbf; + } + + /** + * Get the exp property: The expiration date of the object that triggered this event. + * + * @return the exp value. + */ + @Generated + public double getExp() { + return this.exp; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("Id", this.id); + jsonWriter.writeStringField("VaultName", this.vaultName); + jsonWriter.writeStringField("ObjectType", this.objectType); + jsonWriter.writeStringField("ObjectName", this.objectName); + jsonWriter.writeStringField("Version", this.version); + jsonWriter.writeDoubleField("NBF", this.nbf); + jsonWriter.writeDoubleField("EXP", this.exp); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KeyVaultKeyNearExpiryEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KeyVaultKeyNearExpiryEventData 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 KeyVaultKeyNearExpiryEventData. + */ + @Generated + public static KeyVaultKeyNearExpiryEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String id = null; + String vaultName = null; + String objectType = null; + String objectName = null; + String version = null; + double nbf = 0.0; + double exp = 0.0; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("Id".equals(fieldName)) { + id = reader.getString(); + } else if ("VaultName".equals(fieldName)) { + vaultName = reader.getString(); + } else if ("ObjectType".equals(fieldName)) { + objectType = reader.getString(); + } else if ("ObjectName".equals(fieldName)) { + objectName = reader.getString(); + } else if ("Version".equals(fieldName)) { + version = reader.getString(); + } else if ("NBF".equals(fieldName)) { + nbf = reader.getDouble(); + } else if ("EXP".equals(fieldName)) { + exp = reader.getDouble(); + } else { + reader.skipChildren(); + } + } + return new KeyVaultKeyNearExpiryEventData(id, vaultName, objectType, objectName, version, nbf, exp); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultKeyNewVersionCreatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultKeyNewVersionCreatedEventData.java new file mode 100644 index 000000000000..5f592fe9a7dd --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultKeyNewVersionCreatedEventData.java @@ -0,0 +1,217 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.KeyNewVersionCreated event. + */ +@Immutable +public final class KeyVaultKeyNewVersionCreatedEventData + implements JsonSerializable { + /* + * The id of the object that triggered this event. + */ + @Generated + private final String id; + + /* + * Key vault name of the object that triggered this event. + */ + @Generated + private final String vaultName; + + /* + * The type of the object that triggered this event + */ + @Generated + private final String objectType; + + /* + * The name of the object that triggered this event + */ + @Generated + private final String objectName; + + /* + * The version of the object that triggered this event + */ + @Generated + private final String version; + + /* + * Not before date of the object that triggered this event + */ + @Generated + private final double nbf; + + /* + * The expiration date of the object that triggered this event + */ + @Generated + private final double exp; + + /** + * Creates an instance of KeyVaultKeyNewVersionCreatedEventData class. + * + * @param id the id value to set. + * @param vaultName the vaultName value to set. + * @param objectType the objectType value to set. + * @param objectName the objectName value to set. + * @param version the version value to set. + * @param nbf the nbf value to set. + * @param exp the exp value to set. + */ + @Generated + private KeyVaultKeyNewVersionCreatedEventData(String id, String vaultName, String objectType, String objectName, + String version, double nbf, double exp) { + this.id = id; + this.vaultName = vaultName; + this.objectType = objectType; + this.objectName = objectName; + this.version = version; + this.nbf = nbf; + this.exp = exp; + } + + /** + * Get the id property: The id of the object that triggered this event. + * + * @return the id value. + */ + @Generated + public String getId() { + return this.id; + } + + /** + * Get the vaultName property: Key vault name of the object that triggered this event. + * + * @return the vaultName value. + */ + @Generated + public String getVaultName() { + return this.vaultName; + } + + /** + * Get the objectType property: The type of the object that triggered this event. + * + * @return the objectType value. + */ + @Generated + public String getObjectType() { + return this.objectType; + } + + /** + * Get the objectName property: The name of the object that triggered this event. + * + * @return the objectName value. + */ + @Generated + public String getObjectName() { + return this.objectName; + } + + /** + * Get the version property: The version of the object that triggered this event. + * + * @return the version value. + */ + @Generated + public String getVersion() { + return this.version; + } + + /** + * Get the nbf property: Not before date of the object that triggered this event. + * + * @return the nbf value. + */ + @Generated + public double getNbf() { + return this.nbf; + } + + /** + * Get the exp property: The expiration date of the object that triggered this event. + * + * @return the exp value. + */ + @Generated + public double getExp() { + return this.exp; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("Id", this.id); + jsonWriter.writeStringField("VaultName", this.vaultName); + jsonWriter.writeStringField("ObjectType", this.objectType); + jsonWriter.writeStringField("ObjectName", this.objectName); + jsonWriter.writeStringField("Version", this.version); + jsonWriter.writeDoubleField("NBF", this.nbf); + jsonWriter.writeDoubleField("EXP", this.exp); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KeyVaultKeyNewVersionCreatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KeyVaultKeyNewVersionCreatedEventData 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 KeyVaultKeyNewVersionCreatedEventData. + */ + @Generated + public static KeyVaultKeyNewVersionCreatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String id = null; + String vaultName = null; + String objectType = null; + String objectName = null; + String version = null; + double nbf = 0.0; + double exp = 0.0; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("Id".equals(fieldName)) { + id = reader.getString(); + } else if ("VaultName".equals(fieldName)) { + vaultName = reader.getString(); + } else if ("ObjectType".equals(fieldName)) { + objectType = reader.getString(); + } else if ("ObjectName".equals(fieldName)) { + objectName = reader.getString(); + } else if ("Version".equals(fieldName)) { + version = reader.getString(); + } else if ("NBF".equals(fieldName)) { + nbf = reader.getDouble(); + } else if ("EXP".equals(fieldName)) { + exp = reader.getDouble(); + } else { + reader.skipChildren(); + } + } + return new KeyVaultKeyNewVersionCreatedEventData(id, vaultName, objectType, objectName, version, nbf, exp); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultSecretExpiredEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultSecretExpiredEventData.java new file mode 100644 index 000000000000..f62363b08abb --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultSecretExpiredEventData.java @@ -0,0 +1,216 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.SecretExpired event. + */ +@Immutable +public final class KeyVaultSecretExpiredEventData implements JsonSerializable { + /* + * The id of the object that triggered this event. + */ + @Generated + private final String id; + + /* + * Key vault name of the object that triggered this event. + */ + @Generated + private final String vaultName; + + /* + * The type of the object that triggered this event + */ + @Generated + private final String objectType; + + /* + * The name of the object that triggered this event + */ + @Generated + private final String objectName; + + /* + * The version of the object that triggered this event + */ + @Generated + private final String version; + + /* + * Not before date of the object that triggered this event + */ + @Generated + private final double nbf; + + /* + * The expiration date of the object that triggered this event + */ + @Generated + private final double exp; + + /** + * Creates an instance of KeyVaultSecretExpiredEventData class. + * + * @param id the id value to set. + * @param vaultName the vaultName value to set. + * @param objectType the objectType value to set. + * @param objectName the objectName value to set. + * @param version the version value to set. + * @param nbf the nbf value to set. + * @param exp the exp value to set. + */ + @Generated + private KeyVaultSecretExpiredEventData(String id, String vaultName, String objectType, String objectName, + String version, double nbf, double exp) { + this.id = id; + this.vaultName = vaultName; + this.objectType = objectType; + this.objectName = objectName; + this.version = version; + this.nbf = nbf; + this.exp = exp; + } + + /** + * Get the id property: The id of the object that triggered this event. + * + * @return the id value. + */ + @Generated + public String getId() { + return this.id; + } + + /** + * Get the vaultName property: Key vault name of the object that triggered this event. + * + * @return the vaultName value. + */ + @Generated + public String getVaultName() { + return this.vaultName; + } + + /** + * Get the objectType property: The type of the object that triggered this event. + * + * @return the objectType value. + */ + @Generated + public String getObjectType() { + return this.objectType; + } + + /** + * Get the objectName property: The name of the object that triggered this event. + * + * @return the objectName value. + */ + @Generated + public String getObjectName() { + return this.objectName; + } + + /** + * Get the version property: The version of the object that triggered this event. + * + * @return the version value. + */ + @Generated + public String getVersion() { + return this.version; + } + + /** + * Get the nbf property: Not before date of the object that triggered this event. + * + * @return the nbf value. + */ + @Generated + public double getNbf() { + return this.nbf; + } + + /** + * Get the exp property: The expiration date of the object that triggered this event. + * + * @return the exp value. + */ + @Generated + public double getExp() { + return this.exp; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("Id", this.id); + jsonWriter.writeStringField("VaultName", this.vaultName); + jsonWriter.writeStringField("ObjectType", this.objectType); + jsonWriter.writeStringField("ObjectName", this.objectName); + jsonWriter.writeStringField("Version", this.version); + jsonWriter.writeDoubleField("NBF", this.nbf); + jsonWriter.writeDoubleField("EXP", this.exp); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KeyVaultSecretExpiredEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KeyVaultSecretExpiredEventData 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 KeyVaultSecretExpiredEventData. + */ + @Generated + public static KeyVaultSecretExpiredEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String id = null; + String vaultName = null; + String objectType = null; + String objectName = null; + String version = null; + double nbf = 0.0; + double exp = 0.0; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("Id".equals(fieldName)) { + id = reader.getString(); + } else if ("VaultName".equals(fieldName)) { + vaultName = reader.getString(); + } else if ("ObjectType".equals(fieldName)) { + objectType = reader.getString(); + } else if ("ObjectName".equals(fieldName)) { + objectName = reader.getString(); + } else if ("Version".equals(fieldName)) { + version = reader.getString(); + } else if ("NBF".equals(fieldName)) { + nbf = reader.getDouble(); + } else if ("EXP".equals(fieldName)) { + exp = reader.getDouble(); + } else { + reader.skipChildren(); + } + } + return new KeyVaultSecretExpiredEventData(id, vaultName, objectType, objectName, version, nbf, exp); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultSecretNearExpiryEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultSecretNearExpiryEventData.java new file mode 100644 index 000000000000..9e6d6d7be0bb --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultSecretNearExpiryEventData.java @@ -0,0 +1,216 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.SecretNearExpiry event. + */ +@Immutable +public final class KeyVaultSecretNearExpiryEventData implements JsonSerializable { + /* + * The id of the object that triggered this event. + */ + @Generated + private final String id; + + /* + * Key vault name of the object that triggered this event. + */ + @Generated + private final String vaultName; + + /* + * The type of the object that triggered this event + */ + @Generated + private final String objectType; + + /* + * The name of the object that triggered this event + */ + @Generated + private final String objectName; + + /* + * The version of the object that triggered this event + */ + @Generated + private final String version; + + /* + * Not before date of the object that triggered this event + */ + @Generated + private final double nbf; + + /* + * The expiration date of the object that triggered this event + */ + @Generated + private final double exp; + + /** + * Creates an instance of KeyVaultSecretNearExpiryEventData class. + * + * @param id the id value to set. + * @param vaultName the vaultName value to set. + * @param objectType the objectType value to set. + * @param objectName the objectName value to set. + * @param version the version value to set. + * @param nbf the nbf value to set. + * @param exp the exp value to set. + */ + @Generated + private KeyVaultSecretNearExpiryEventData(String id, String vaultName, String objectType, String objectName, + String version, double nbf, double exp) { + this.id = id; + this.vaultName = vaultName; + this.objectType = objectType; + this.objectName = objectName; + this.version = version; + this.nbf = nbf; + this.exp = exp; + } + + /** + * Get the id property: The id of the object that triggered this event. + * + * @return the id value. + */ + @Generated + public String getId() { + return this.id; + } + + /** + * Get the vaultName property: Key vault name of the object that triggered this event. + * + * @return the vaultName value. + */ + @Generated + public String getVaultName() { + return this.vaultName; + } + + /** + * Get the objectType property: The type of the object that triggered this event. + * + * @return the objectType value. + */ + @Generated + public String getObjectType() { + return this.objectType; + } + + /** + * Get the objectName property: The name of the object that triggered this event. + * + * @return the objectName value. + */ + @Generated + public String getObjectName() { + return this.objectName; + } + + /** + * Get the version property: The version of the object that triggered this event. + * + * @return the version value. + */ + @Generated + public String getVersion() { + return this.version; + } + + /** + * Get the nbf property: Not before date of the object that triggered this event. + * + * @return the nbf value. + */ + @Generated + public double getNbf() { + return this.nbf; + } + + /** + * Get the exp property: The expiration date of the object that triggered this event. + * + * @return the exp value. + */ + @Generated + public double getExp() { + return this.exp; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("Id", this.id); + jsonWriter.writeStringField("VaultName", this.vaultName); + jsonWriter.writeStringField("ObjectType", this.objectType); + jsonWriter.writeStringField("ObjectName", this.objectName); + jsonWriter.writeStringField("Version", this.version); + jsonWriter.writeDoubleField("NBF", this.nbf); + jsonWriter.writeDoubleField("EXP", this.exp); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KeyVaultSecretNearExpiryEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KeyVaultSecretNearExpiryEventData 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 KeyVaultSecretNearExpiryEventData. + */ + @Generated + public static KeyVaultSecretNearExpiryEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String id = null; + String vaultName = null; + String objectType = null; + String objectName = null; + String version = null; + double nbf = 0.0; + double exp = 0.0; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("Id".equals(fieldName)) { + id = reader.getString(); + } else if ("VaultName".equals(fieldName)) { + vaultName = reader.getString(); + } else if ("ObjectType".equals(fieldName)) { + objectType = reader.getString(); + } else if ("ObjectName".equals(fieldName)) { + objectName = reader.getString(); + } else if ("Version".equals(fieldName)) { + version = reader.getString(); + } else if ("NBF".equals(fieldName)) { + nbf = reader.getDouble(); + } else if ("EXP".equals(fieldName)) { + exp = reader.getDouble(); + } else { + reader.skipChildren(); + } + } + return new KeyVaultSecretNearExpiryEventData(id, vaultName, objectType, objectName, version, nbf, exp); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultSecretNewVersionCreatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultSecretNewVersionCreatedEventData.java new file mode 100644 index 000000000000..0271d68fd34a --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/KeyVaultSecretNewVersionCreatedEventData.java @@ -0,0 +1,218 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.KeyVault.SecretNewVersionCreated event. + */ +@Immutable +public final class KeyVaultSecretNewVersionCreatedEventData + implements JsonSerializable { + /* + * The id of the object that triggered this event. + */ + @Generated + private final String id; + + /* + * Key vault name of the object that triggered this event. + */ + @Generated + private final String vaultName; + + /* + * The type of the object that triggered this event + */ + @Generated + private final String objectType; + + /* + * The name of the object that triggered this event + */ + @Generated + private final String objectName; + + /* + * The version of the object that triggered this event + */ + @Generated + private final String version; + + /* + * Not before date of the object that triggered this event + */ + @Generated + private final double nbf; + + /* + * The expiration date of the object that triggered this event + */ + @Generated + private final double exp; + + /** + * Creates an instance of KeyVaultSecretNewVersionCreatedEventData class. + * + * @param id the id value to set. + * @param vaultName the vaultName value to set. + * @param objectType the objectType value to set. + * @param objectName the objectName value to set. + * @param version the version value to set. + * @param nbf the nbf value to set. + * @param exp the exp value to set. + */ + @Generated + private KeyVaultSecretNewVersionCreatedEventData(String id, String vaultName, String objectType, String objectName, + String version, double nbf, double exp) { + this.id = id; + this.vaultName = vaultName; + this.objectType = objectType; + this.objectName = objectName; + this.version = version; + this.nbf = nbf; + this.exp = exp; + } + + /** + * Get the id property: The id of the object that triggered this event. + * + * @return the id value. + */ + @Generated + public String getId() { + return this.id; + } + + /** + * Get the vaultName property: Key vault name of the object that triggered this event. + * + * @return the vaultName value. + */ + @Generated + public String getVaultName() { + return this.vaultName; + } + + /** + * Get the objectType property: The type of the object that triggered this event. + * + * @return the objectType value. + */ + @Generated + public String getObjectType() { + return this.objectType; + } + + /** + * Get the objectName property: The name of the object that triggered this event. + * + * @return the objectName value. + */ + @Generated + public String getObjectName() { + return this.objectName; + } + + /** + * Get the version property: The version of the object that triggered this event. + * + * @return the version value. + */ + @Generated + public String getVersion() { + return this.version; + } + + /** + * Get the nbf property: Not before date of the object that triggered this event. + * + * @return the nbf value. + */ + @Generated + public double getNbf() { + return this.nbf; + } + + /** + * Get the exp property: The expiration date of the object that triggered this event. + * + * @return the exp value. + */ + @Generated + public double getExp() { + return this.exp; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("Id", this.id); + jsonWriter.writeStringField("VaultName", this.vaultName); + jsonWriter.writeStringField("ObjectType", this.objectType); + jsonWriter.writeStringField("ObjectName", this.objectName); + jsonWriter.writeStringField("Version", this.version); + jsonWriter.writeDoubleField("NBF", this.nbf); + jsonWriter.writeDoubleField("EXP", this.exp); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KeyVaultSecretNewVersionCreatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KeyVaultSecretNewVersionCreatedEventData 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 KeyVaultSecretNewVersionCreatedEventData. + */ + @Generated + public static KeyVaultSecretNewVersionCreatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String id = null; + String vaultName = null; + String objectType = null; + String objectName = null; + String version = null; + double nbf = 0.0; + double exp = 0.0; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("Id".equals(fieldName)) { + id = reader.getString(); + } else if ("VaultName".equals(fieldName)) { + vaultName = reader.getString(); + } else if ("ObjectType".equals(fieldName)) { + objectType = reader.getString(); + } else if ("ObjectName".equals(fieldName)) { + objectName = reader.getString(); + } else if ("Version".equals(fieldName)) { + version = reader.getString(); + } else if ("NBF".equals(fieldName)) { + nbf = reader.getDouble(); + } else if ("EXP".equals(fieldName)) { + exp = reader.getDouble(); + } else { + reader.skipChildren(); + } + } + return new KeyVaultSecretNewVersionCreatedEventData(id, vaultName, objectType, objectName, version, nbf, + exp); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MachineLearningServicesDatasetDriftDetectedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MachineLearningServicesDatasetDriftDetectedEventData.java new file mode 100644 index 000000000000..0ce920ef8121 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MachineLearningServicesDatasetDriftDetectedEventData.java @@ -0,0 +1,243 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.MachineLearningServices.DatasetDriftDetected event. + */ +@Immutable +public final class MachineLearningServicesDatasetDriftDetectedEventData + implements JsonSerializable { + /* + * The ID of the data drift monitor that triggered the event. + */ + @Generated + private String dataDriftId; + + /* + * The name of the data drift monitor that triggered the event. + */ + @Generated + private String dataDriftName; + + /* + * The ID of the Run that detected data drift. + */ + @Generated + private String runId; + + /* + * The ID of the base Dataset used to detect drift. + */ + @Generated + private String baseDatasetId; + + /* + * The ID of the target Dataset used to detect drift. + */ + @Generated + private String targetDatasetId; + + /* + * The coefficient result that triggered the event. + */ + @Generated + private Double driftCoefficient; + + /* + * The start time of the target dataset time series that resulted in drift detection. + */ + @Generated + private final OffsetDateTime startTime; + + /* + * The end time of the target dataset time series that resulted in drift detection. + */ + @Generated + private final OffsetDateTime endTime; + + /** + * Creates an instance of MachineLearningServicesDatasetDriftDetectedEventData class. + * + * @param startTime the startTime value to set. + * @param endTime the endTime value to set. + */ + @Generated + private MachineLearningServicesDatasetDriftDetectedEventData(OffsetDateTime startTime, OffsetDateTime endTime) { + this.startTime = startTime; + this.endTime = endTime; + } + + /** + * Get the dataDriftId property: The ID of the data drift monitor that triggered the event. + * + * @return the dataDriftId value. + */ + @Generated + public String getDataDriftId() { + return this.dataDriftId; + } + + /** + * Get the dataDriftName property: The name of the data drift monitor that triggered the event. + * + * @return the dataDriftName value. + */ + @Generated + public String getDataDriftName() { + return this.dataDriftName; + } + + /** + * Get the runId property: The ID of the Run that detected data drift. + * + * @return the runId value. + */ + @Generated + public String getRunId() { + return this.runId; + } + + /** + * Get the baseDatasetId property: The ID of the base Dataset used to detect drift. + * + * @return the baseDatasetId value. + */ + @Generated + public String getBaseDatasetId() { + return this.baseDatasetId; + } + + /** + * Get the targetDatasetId property: The ID of the target Dataset used to detect drift. + * + * @return the targetDatasetId value. + */ + @Generated + public String getTargetDatasetId() { + return this.targetDatasetId; + } + + /** + * Get the driftCoefficient property: The coefficient result that triggered the event. + * + * @return the driftCoefficient value. + */ + @Generated + public Double getDriftCoefficient() { + return this.driftCoefficient; + } + + /** + * Get the startTime property: The start time of the target dataset time series that resulted in drift detection. + * + * @return the startTime value. + */ + @Generated + public OffsetDateTime getStartTime() { + return this.startTime; + } + + /** + * Get the endTime property: The end time of the target dataset time series that resulted in drift detection. + * + * @return the endTime value. + */ + @Generated + public OffsetDateTime getEndTime() { + return this.endTime; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("startTime", + this.startTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.startTime)); + jsonWriter.writeStringField("endTime", + this.endTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.endTime)); + jsonWriter.writeStringField("dataDriftId", this.dataDriftId); + jsonWriter.writeStringField("dataDriftName", this.dataDriftName); + jsonWriter.writeStringField("runId", this.runId); + jsonWriter.writeStringField("baseDatasetId", this.baseDatasetId); + jsonWriter.writeStringField("targetDatasetId", this.targetDatasetId); + jsonWriter.writeNumberField("driftCoefficient", this.driftCoefficient); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of MachineLearningServicesDatasetDriftDetectedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of MachineLearningServicesDatasetDriftDetectedEventData 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 MachineLearningServicesDatasetDriftDetectedEventData. + */ + @Generated + public static MachineLearningServicesDatasetDriftDetectedEventData fromJson(JsonReader jsonReader) + throws IOException { + return jsonReader.readObject(reader -> { + OffsetDateTime startTime = null; + OffsetDateTime endTime = null; + String dataDriftId = null; + String dataDriftName = null; + String runId = null; + String baseDatasetId = null; + String targetDatasetId = null; + Double driftCoefficient = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("startTime".equals(fieldName)) { + startTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("endTime".equals(fieldName)) { + endTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("dataDriftId".equals(fieldName)) { + dataDriftId = reader.getString(); + } else if ("dataDriftName".equals(fieldName)) { + dataDriftName = reader.getString(); + } else if ("runId".equals(fieldName)) { + runId = reader.getString(); + } else if ("baseDatasetId".equals(fieldName)) { + baseDatasetId = reader.getString(); + } else if ("targetDatasetId".equals(fieldName)) { + targetDatasetId = reader.getString(); + } else if ("driftCoefficient".equals(fieldName)) { + driftCoefficient = reader.getNullable(JsonReader::getDouble); + } else { + reader.skipChildren(); + } + } + MachineLearningServicesDatasetDriftDetectedEventData deserializedMachineLearningServicesDatasetDriftDetectedEventData + = new MachineLearningServicesDatasetDriftDetectedEventData(startTime, endTime); + deserializedMachineLearningServicesDatasetDriftDetectedEventData.dataDriftId = dataDriftId; + deserializedMachineLearningServicesDatasetDriftDetectedEventData.dataDriftName = dataDriftName; + deserializedMachineLearningServicesDatasetDriftDetectedEventData.runId = runId; + deserializedMachineLearningServicesDatasetDriftDetectedEventData.baseDatasetId = baseDatasetId; + deserializedMachineLearningServicesDatasetDriftDetectedEventData.targetDatasetId = targetDatasetId; + deserializedMachineLearningServicesDatasetDriftDetectedEventData.driftCoefficient = driftCoefficient; + + return deserializedMachineLearningServicesDatasetDriftDetectedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MachineLearningServicesModelDeployedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MachineLearningServicesModelDeployedEventData.java new file mode 100644 index 000000000000..9658156aea30 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MachineLearningServicesModelDeployedEventData.java @@ -0,0 +1,179 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.BinaryData; +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.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.MachineLearningServices.ModelDeployed event. + */ +@Immutable +public final class MachineLearningServicesModelDeployedEventData + implements JsonSerializable { + /* + * The name of the deployed service. + */ + @Generated + private String serviceName; + + /* + * The compute type (e.g. ACI, AKS) of the deployed service. + */ + @Generated + private String serviceComputeType; + + /* + * A common separated list of model IDs. The IDs of the models deployed in the service. + */ + @Generated + private String modelIds; + + /* + * The tags of the deployed service. + */ + @Generated + private final Map serviceTags; + + /* + * The properties of the deployed service. + */ + @Generated + private final Map serviceProperties; + + /** + * Creates an instance of MachineLearningServicesModelDeployedEventData class. + * + * @param serviceTags the serviceTags value to set. + * @param serviceProperties the serviceProperties value to set. + */ + @Generated + private MachineLearningServicesModelDeployedEventData(Map serviceTags, + Map serviceProperties) { + this.serviceTags = serviceTags; + this.serviceProperties = serviceProperties; + } + + /** + * Get the serviceName property: The name of the deployed service. + * + * @return the serviceName value. + */ + @Generated + public String getServiceName() { + return this.serviceName; + } + + /** + * Get the serviceComputeType property: The compute type (e.g. ACI, AKS) of the deployed service. + * + * @return the serviceComputeType value. + */ + @Generated + public String getServiceComputeType() { + return this.serviceComputeType; + } + + /** + * Get the modelIds property: A common separated list of model IDs. The IDs of the models deployed in the service. + * + * @return the modelIds value. + */ + @Generated + public String getModelIds() { + return this.modelIds; + } + + /** + * Get the serviceTags property: The tags of the deployed service. + * + * @return the serviceTags value. + */ + @Generated + public Map getServiceTags() { + return this.serviceTags; + } + + /** + * Get the serviceProperties property: The properties of the deployed service. + * + * @return the serviceProperties value. + */ + @Generated + public Map getServiceProperties() { + return this.serviceProperties; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("serviceTags", this.serviceTags, + (writer, element) -> writer.writeUntyped(element == null ? null : element.toObject(Object.class))); + jsonWriter.writeMapField("serviceProperties", this.serviceProperties, + (writer, element) -> writer.writeUntyped(element == null ? null : element.toObject(Object.class))); + jsonWriter.writeStringField("serviceName", this.serviceName); + jsonWriter.writeStringField("serviceComputeType", this.serviceComputeType); + jsonWriter.writeStringField("modelIds", this.modelIds); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of MachineLearningServicesModelDeployedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of MachineLearningServicesModelDeployedEventData 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 MachineLearningServicesModelDeployedEventData. + */ + @Generated + public static MachineLearningServicesModelDeployedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Map serviceTags = null; + Map serviceProperties = null; + String serviceName = null; + String serviceComputeType = null; + String modelIds = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("serviceTags".equals(fieldName)) { + serviceTags = reader.readMap(reader1 -> reader1 + .getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); + } else if ("serviceProperties".equals(fieldName)) { + serviceProperties = reader.readMap(reader1 -> reader1 + .getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); + } else if ("serviceName".equals(fieldName)) { + serviceName = reader.getString(); + } else if ("serviceComputeType".equals(fieldName)) { + serviceComputeType = reader.getString(); + } else if ("modelIds".equals(fieldName)) { + modelIds = reader.getString(); + } else { + reader.skipChildren(); + } + } + MachineLearningServicesModelDeployedEventData deserializedMachineLearningServicesModelDeployedEventData + = new MachineLearningServicesModelDeployedEventData(serviceTags, serviceProperties); + deserializedMachineLearningServicesModelDeployedEventData.serviceName = serviceName; + deserializedMachineLearningServicesModelDeployedEventData.serviceComputeType = serviceComputeType; + deserializedMachineLearningServicesModelDeployedEventData.modelIds = modelIds; + + return deserializedMachineLearningServicesModelDeployedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MachineLearningServicesModelRegisteredEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MachineLearningServicesModelRegisteredEventData.java new file mode 100644 index 000000000000..5d9564ea271b --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MachineLearningServicesModelRegisteredEventData.java @@ -0,0 +1,158 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.BinaryData; +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.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.MachineLearningServices.ModelRegistered event. + */ +@Immutable +public final class MachineLearningServicesModelRegisteredEventData + implements JsonSerializable { + /* + * The name of the model that was registered. + */ + @Generated + private String modelName; + + /* + * The version of the model that was registered. + */ + @Generated + private String modelVersion; + + /* + * The tags of the model that was registered. + */ + @Generated + private final Map modelTags; + + /* + * The properties of the model that was registered. + */ + @Generated + private final Map modelProperties; + + /** + * Creates an instance of MachineLearningServicesModelRegisteredEventData class. + * + * @param modelTags the modelTags value to set. + * @param modelProperties the modelProperties value to set. + */ + @Generated + private MachineLearningServicesModelRegisteredEventData(Map modelTags, + Map modelProperties) { + this.modelTags = modelTags; + this.modelProperties = modelProperties; + } + + /** + * Get the modelName property: The name of the model that was registered. + * + * @return the modelName value. + */ + @Generated + public String getModelName() { + return this.modelName; + } + + /** + * Get the modelVersion property: The version of the model that was registered. + * + * @return the modelVersion value. + */ + @Generated + public String getModelVersion() { + return this.modelVersion; + } + + /** + * Get the modelTags property: The tags of the model that was registered. + * + * @return the modelTags value. + */ + @Generated + public Map getModelTags() { + return this.modelTags; + } + + /** + * Get the modelProperties property: The properties of the model that was registered. + * + * @return the modelProperties value. + */ + @Generated + public Map getModelProperties() { + return this.modelProperties; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("modelTags", this.modelTags, + (writer, element) -> writer.writeUntyped(element == null ? null : element.toObject(Object.class))); + jsonWriter.writeMapField("modelProperties", this.modelProperties, + (writer, element) -> writer.writeUntyped(element == null ? null : element.toObject(Object.class))); + jsonWriter.writeStringField("modelName", this.modelName); + jsonWriter.writeStringField("modelVersion", this.modelVersion); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of MachineLearningServicesModelRegisteredEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of MachineLearningServicesModelRegisteredEventData 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 MachineLearningServicesModelRegisteredEventData. + */ + @Generated + public static MachineLearningServicesModelRegisteredEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Map modelTags = null; + Map modelProperties = null; + String modelName = null; + String modelVersion = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("modelTags".equals(fieldName)) { + modelTags = reader.readMap(reader1 -> reader1 + .getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); + } else if ("modelProperties".equals(fieldName)) { + modelProperties = reader.readMap(reader1 -> reader1 + .getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); + } else if ("modelName".equals(fieldName)) { + modelName = reader.getString(); + } else if ("modelVersion".equals(fieldName)) { + modelVersion = reader.getString(); + } else { + reader.skipChildren(); + } + } + MachineLearningServicesModelRegisteredEventData deserializedMachineLearningServicesModelRegisteredEventData + = new MachineLearningServicesModelRegisteredEventData(modelTags, modelProperties); + deserializedMachineLearningServicesModelRegisteredEventData.modelName = modelName; + deserializedMachineLearningServicesModelRegisteredEventData.modelVersion = modelVersion; + + return deserializedMachineLearningServicesModelRegisteredEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MachineLearningServicesRunCompletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MachineLearningServicesRunCompletedEventData.java new file mode 100644 index 000000000000..be771e5a4c74 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MachineLearningServicesRunCompletedEventData.java @@ -0,0 +1,200 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.BinaryData; +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.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.MachineLearningServices.RunCompleted event. + */ +@Immutable +public final class MachineLearningServicesRunCompletedEventData + implements JsonSerializable { + /* + * The ID of the experiment that the run belongs to. + */ + @Generated + private String experimentId; + + /* + * The name of the experiment that the run belongs to. + */ + @Generated + private String experimentName; + + /* + * The ID of the Run that was completed. + */ + @Generated + private String runId; + + /* + * The Run Type of the completed Run. + */ + @Generated + private String runType; + + /* + * The tags of the completed Run. + */ + @Generated + private final Map runTags; + + /* + * The properties of the completed Run. + */ + @Generated + private final Map runProperties; + + /** + * Creates an instance of MachineLearningServicesRunCompletedEventData class. + * + * @param runTags the runTags value to set. + * @param runProperties the runProperties value to set. + */ + @Generated + private MachineLearningServicesRunCompletedEventData(Map runTags, + Map runProperties) { + this.runTags = runTags; + this.runProperties = runProperties; + } + + /** + * Get the experimentId property: The ID of the experiment that the run belongs to. + * + * @return the experimentId value. + */ + @Generated + public String getExperimentId() { + return this.experimentId; + } + + /** + * Get the experimentName property: The name of the experiment that the run belongs to. + * + * @return the experimentName value. + */ + @Generated + public String getExperimentName() { + return this.experimentName; + } + + /** + * Get the runId property: The ID of the Run that was completed. + * + * @return the runId value. + */ + @Generated + public String getRunId() { + return this.runId; + } + + /** + * Get the runType property: The Run Type of the completed Run. + * + * @return the runType value. + */ + @Generated + public String getRunType() { + return this.runType; + } + + /** + * Get the runTags property: The tags of the completed Run. + * + * @return the runTags value. + */ + @Generated + public Map getRunTags() { + return this.runTags; + } + + /** + * Get the runProperties property: The properties of the completed Run. + * + * @return the runProperties value. + */ + @Generated + public Map getRunProperties() { + return this.runProperties; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("runTags", this.runTags, + (writer, element) -> writer.writeUntyped(element == null ? null : element.toObject(Object.class))); + jsonWriter.writeMapField("runProperties", this.runProperties, + (writer, element) -> writer.writeUntyped(element == null ? null : element.toObject(Object.class))); + jsonWriter.writeStringField("experimentId", this.experimentId); + jsonWriter.writeStringField("experimentName", this.experimentName); + jsonWriter.writeStringField("runId", this.runId); + jsonWriter.writeStringField("runType", this.runType); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of MachineLearningServicesRunCompletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of MachineLearningServicesRunCompletedEventData 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 MachineLearningServicesRunCompletedEventData. + */ + @Generated + public static MachineLearningServicesRunCompletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Map runTags = null; + Map runProperties = null; + String experimentId = null; + String experimentName = null; + String runId = null; + String runType = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("runTags".equals(fieldName)) { + runTags = reader.readMap(reader1 -> reader1 + .getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); + } else if ("runProperties".equals(fieldName)) { + runProperties = reader.readMap(reader1 -> reader1 + .getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); + } else if ("experimentId".equals(fieldName)) { + experimentId = reader.getString(); + } else if ("experimentName".equals(fieldName)) { + experimentName = reader.getString(); + } else if ("runId".equals(fieldName)) { + runId = reader.getString(); + } else if ("runType".equals(fieldName)) { + runType = reader.getString(); + } else { + reader.skipChildren(); + } + } + MachineLearningServicesRunCompletedEventData deserializedMachineLearningServicesRunCompletedEventData + = new MachineLearningServicesRunCompletedEventData(runTags, runProperties); + deserializedMachineLearningServicesRunCompletedEventData.experimentId = experimentId; + deserializedMachineLearningServicesRunCompletedEventData.experimentName = experimentName; + deserializedMachineLearningServicesRunCompletedEventData.runId = runId; + deserializedMachineLearningServicesRunCompletedEventData.runType = runType; + + return deserializedMachineLearningServicesRunCompletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MachineLearningServicesRunStatusChangedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MachineLearningServicesRunStatusChangedEventData.java new file mode 100644 index 000000000000..f1c0f689b831 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MachineLearningServicesRunStatusChangedEventData.java @@ -0,0 +1,221 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.BinaryData; +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.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.MachineLearningServices.RunStatusChanged event. + */ +@Immutable +public final class MachineLearningServicesRunStatusChangedEventData + implements JsonSerializable { + /* + * The ID of the experiment that the Machine Learning Run belongs to. + */ + @Generated + private String experimentId; + + /* + * The name of the experiment that the Machine Learning Run belongs to. + */ + @Generated + private String experimentName; + + /* + * The ID of the Machine Learning Run. + */ + @Generated + private String runId; + + /* + * The Run Type of the Machine Learning Run. + */ + @Generated + private String runType; + + /* + * The tags of the Machine Learning Run. + */ + @Generated + private final Map runTags; + + /* + * The properties of the Machine Learning Run. + */ + @Generated + private final Map runProperties; + + /* + * The status of the Machine Learning Run. + */ + @Generated + private String runStatus; + + /** + * Creates an instance of MachineLearningServicesRunStatusChangedEventData class. + * + * @param runTags the runTags value to set. + * @param runProperties the runProperties value to set. + */ + @Generated + private MachineLearningServicesRunStatusChangedEventData(Map runTags, + Map runProperties) { + this.runTags = runTags; + this.runProperties = runProperties; + } + + /** + * Get the experimentId property: The ID of the experiment that the Machine Learning Run belongs to. + * + * @return the experimentId value. + */ + @Generated + public String getExperimentId() { + return this.experimentId; + } + + /** + * Get the experimentName property: The name of the experiment that the Machine Learning Run belongs to. + * + * @return the experimentName value. + */ + @Generated + public String getExperimentName() { + return this.experimentName; + } + + /** + * Get the runId property: The ID of the Machine Learning Run. + * + * @return the runId value. + */ + @Generated + public String getRunId() { + return this.runId; + } + + /** + * Get the runType property: The Run Type of the Machine Learning Run. + * + * @return the runType value. + */ + @Generated + public String getRunType() { + return this.runType; + } + + /** + * Get the runTags property: The tags of the Machine Learning Run. + * + * @return the runTags value. + */ + @Generated + public Map getRunTags() { + return this.runTags; + } + + /** + * Get the runProperties property: The properties of the Machine Learning Run. + * + * @return the runProperties value. + */ + @Generated + public Map getRunProperties() { + return this.runProperties; + } + + /** + * Get the runStatus property: The status of the Machine Learning Run. + * + * @return the runStatus value. + */ + @Generated + public String getRunStatus() { + return this.runStatus; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("runTags", this.runTags, + (writer, element) -> writer.writeUntyped(element == null ? null : element.toObject(Object.class))); + jsonWriter.writeMapField("runProperties", this.runProperties, + (writer, element) -> writer.writeUntyped(element == null ? null : element.toObject(Object.class))); + jsonWriter.writeStringField("experimentId", this.experimentId); + jsonWriter.writeStringField("experimentName", this.experimentName); + jsonWriter.writeStringField("runId", this.runId); + jsonWriter.writeStringField("runType", this.runType); + jsonWriter.writeStringField("runStatus", this.runStatus); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of MachineLearningServicesRunStatusChangedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of MachineLearningServicesRunStatusChangedEventData 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 MachineLearningServicesRunStatusChangedEventData. + */ + @Generated + public static MachineLearningServicesRunStatusChangedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Map runTags = null; + Map runProperties = null; + String experimentId = null; + String experimentName = null; + String runId = null; + String runType = null; + String runStatus = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("runTags".equals(fieldName)) { + runTags = reader.readMap(reader1 -> reader1 + .getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); + } else if ("runProperties".equals(fieldName)) { + runProperties = reader.readMap(reader1 -> reader1 + .getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); + } else if ("experimentId".equals(fieldName)) { + experimentId = reader.getString(); + } else if ("experimentName".equals(fieldName)) { + experimentName = reader.getString(); + } else if ("runId".equals(fieldName)) { + runId = reader.getString(); + } else if ("runType".equals(fieldName)) { + runType = reader.getString(); + } else if ("runStatus".equals(fieldName)) { + runStatus = reader.getString(); + } else { + reader.skipChildren(); + } + } + MachineLearningServicesRunStatusChangedEventData deserializedMachineLearningServicesRunStatusChangedEventData + = new MachineLearningServicesRunStatusChangedEventData(runTags, runProperties); + deserializedMachineLearningServicesRunStatusChangedEventData.experimentId = experimentId; + deserializedMachineLearningServicesRunStatusChangedEventData.experimentName = experimentName; + deserializedMachineLearningServicesRunStatusChangedEventData.runId = runId; + deserializedMachineLearningServicesRunStatusChangedEventData.runType = runType; + deserializedMachineLearningServicesRunStatusChangedEventData.runStatus = runStatus; + + return deserializedMachineLearningServicesRunStatusChangedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MapsGeofenceEnteredEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MapsGeofenceEnteredEventData.java new file mode 100644 index 000000000000..c19e4912777c --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MapsGeofenceEnteredEventData.java @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.List; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Maps.GeofenceEntered event. + */ +@Immutable +public final class MapsGeofenceEnteredEventData extends MapsGeofenceEventProperties { + /** + * Creates an instance of MapsGeofenceEnteredEventData class. + * + * @param expiredGeofenceGeometryId the expiredGeofenceGeometryId value to set. + * @param geometries the geometries value to set. + * @param invalidPeriodGeofenceGeometryId the invalidPeriodGeofenceGeometryId value to set. + * @param isEventPublished the isEventPublished value to set. + */ + @Generated + private MapsGeofenceEnteredEventData(List expiredGeofenceGeometryId, List geometries, + List invalidPeriodGeofenceGeometryId, boolean isEventPublished) { + super(expiredGeofenceGeometryId, geometries, invalidPeriodGeofenceGeometryId, isEventPublished); + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("expiredGeofenceGeometryId", getExpiredGeofenceGeometryId(), + (writer, element) -> writer.writeString(element)); + jsonWriter.writeArrayField("geometries", getGeometries(), (writer, element) -> writer.writeJson(element)); + jsonWriter.writeArrayField("invalidPeriodGeofenceGeometryId", getInvalidPeriodGeofenceGeometryId(), + (writer, element) -> writer.writeString(element)); + jsonWriter.writeBooleanField("isEventPublished", isEventPublished()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of MapsGeofenceEnteredEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of MapsGeofenceEnteredEventData 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 MapsGeofenceEnteredEventData. + */ + @Generated + public static MapsGeofenceEnteredEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + List expiredGeofenceGeometryId = null; + List geometries = null; + List invalidPeriodGeofenceGeometryId = null; + boolean isEventPublished = false; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("expiredGeofenceGeometryId".equals(fieldName)) { + expiredGeofenceGeometryId = reader.readArray(reader1 -> reader1.getString()); + } else if ("geometries".equals(fieldName)) { + geometries = reader.readArray(reader1 -> MapsGeofenceGeometry.fromJson(reader1)); + } else if ("invalidPeriodGeofenceGeometryId".equals(fieldName)) { + invalidPeriodGeofenceGeometryId = reader.readArray(reader1 -> reader1.getString()); + } else if ("isEventPublished".equals(fieldName)) { + isEventPublished = reader.getBoolean(); + } else { + reader.skipChildren(); + } + } + return new MapsGeofenceEnteredEventData(expiredGeofenceGeometryId, geometries, + invalidPeriodGeofenceGeometryId, isEventPublished); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MapsGeofenceEventProperties.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MapsGeofenceEventProperties.java new file mode 100644 index 000000000000..eca6f835a502 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MapsGeofenceEventProperties.java @@ -0,0 +1,161 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.List; + +/** + * Schema of the Data property of an EventGridEvent for a Geofence event (GeofenceEntered, GeofenceExited, + * GeofenceResult). + */ +@Immutable +public class MapsGeofenceEventProperties implements JsonSerializable { + /* + * Lists of the geometry ID of the geofence which is expired relative to the user time in the request. + */ + @Generated + private final List expiredGeofenceGeometryId; + + /* + * Lists the fence geometries that either fully contain the coordinate position or have an overlap with the + * searchBuffer around the fence. + */ + @Generated + private final List geometries; + + /* + * Lists of the geometry ID of the geofence which is in invalid period relative to the user time in the request. + */ + @Generated + private final List invalidPeriodGeofenceGeometryId; + + /* + * True if at least one event is published to the Azure Maps event subscriber, false if no event is published to the + * Azure Maps event subscriber. + */ + @Generated + private final boolean isEventPublished; + + /** + * Creates an instance of MapsGeofenceEventProperties class. + * + * @param expiredGeofenceGeometryId the expiredGeofenceGeometryId value to set. + * @param geometries the geometries value to set. + * @param invalidPeriodGeofenceGeometryId the invalidPeriodGeofenceGeometryId value to set. + * @param isEventPublished the isEventPublished value to set. + */ + @Generated + protected MapsGeofenceEventProperties(List expiredGeofenceGeometryId, List geometries, + List invalidPeriodGeofenceGeometryId, boolean isEventPublished) { + this.expiredGeofenceGeometryId = expiredGeofenceGeometryId; + this.geometries = geometries; + this.invalidPeriodGeofenceGeometryId = invalidPeriodGeofenceGeometryId; + this.isEventPublished = isEventPublished; + } + + /** + * Get the expiredGeofenceGeometryId property: Lists of the geometry ID of the geofence which is expired relative to + * the user time in the request. + * + * @return the expiredGeofenceGeometryId value. + */ + @Generated + public List getExpiredGeofenceGeometryId() { + return this.expiredGeofenceGeometryId; + } + + /** + * Get the geometries property: Lists the fence geometries that either fully contain the coordinate position or have + * an overlap with the searchBuffer around the fence. + * + * @return the geometries value. + */ + @Generated + public List getGeometries() { + return this.geometries; + } + + /** + * Get the invalidPeriodGeofenceGeometryId property: Lists of the geometry ID of the geofence which is in invalid + * period relative to the user time in the request. + * + * @return the invalidPeriodGeofenceGeometryId value. + */ + @Generated + public List getInvalidPeriodGeofenceGeometryId() { + return this.invalidPeriodGeofenceGeometryId; + } + + /** + * Get the isEventPublished property: True if at least one event is published to the Azure Maps event subscriber, + * false if no event is published to the Azure Maps event subscriber. + * + * @return the isEventPublished value. + */ + @Generated + public boolean isEventPublished() { + return this.isEventPublished; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("expiredGeofenceGeometryId", this.expiredGeofenceGeometryId, + (writer, element) -> writer.writeString(element)); + jsonWriter.writeArrayField("geometries", this.geometries, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeArrayField("invalidPeriodGeofenceGeometryId", this.invalidPeriodGeofenceGeometryId, + (writer, element) -> writer.writeString(element)); + jsonWriter.writeBooleanField("isEventPublished", this.isEventPublished); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of MapsGeofenceEventProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of MapsGeofenceEventProperties 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 MapsGeofenceEventProperties. + */ + @Generated + public static MapsGeofenceEventProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + List expiredGeofenceGeometryId = null; + List geometries = null; + List invalidPeriodGeofenceGeometryId = null; + boolean isEventPublished = false; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("expiredGeofenceGeometryId".equals(fieldName)) { + expiredGeofenceGeometryId = reader.readArray(reader1 -> reader1.getString()); + } else if ("geometries".equals(fieldName)) { + geometries = reader.readArray(reader1 -> MapsGeofenceGeometry.fromJson(reader1)); + } else if ("invalidPeriodGeofenceGeometryId".equals(fieldName)) { + invalidPeriodGeofenceGeometryId = reader.readArray(reader1 -> reader1.getString()); + } else if ("isEventPublished".equals(fieldName)) { + isEventPublished = reader.getBoolean(); + } else { + reader.skipChildren(); + } + } + return new MapsGeofenceEventProperties(expiredGeofenceGeometryId, geometries, + invalidPeriodGeofenceGeometryId, isEventPublished); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MapsGeofenceExitedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MapsGeofenceExitedEventData.java new file mode 100644 index 000000000000..e2a2a5641235 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MapsGeofenceExitedEventData.java @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.List; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Maps.GeofenceExited event. + */ +@Immutable +public final class MapsGeofenceExitedEventData extends MapsGeofenceEventProperties { + /** + * Creates an instance of MapsGeofenceExitedEventData class. + * + * @param expiredGeofenceGeometryId the expiredGeofenceGeometryId value to set. + * @param geometries the geometries value to set. + * @param invalidPeriodGeofenceGeometryId the invalidPeriodGeofenceGeometryId value to set. + * @param isEventPublished the isEventPublished value to set. + */ + @Generated + private MapsGeofenceExitedEventData(List expiredGeofenceGeometryId, List geometries, + List invalidPeriodGeofenceGeometryId, boolean isEventPublished) { + super(expiredGeofenceGeometryId, geometries, invalidPeriodGeofenceGeometryId, isEventPublished); + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("expiredGeofenceGeometryId", getExpiredGeofenceGeometryId(), + (writer, element) -> writer.writeString(element)); + jsonWriter.writeArrayField("geometries", getGeometries(), (writer, element) -> writer.writeJson(element)); + jsonWriter.writeArrayField("invalidPeriodGeofenceGeometryId", getInvalidPeriodGeofenceGeometryId(), + (writer, element) -> writer.writeString(element)); + jsonWriter.writeBooleanField("isEventPublished", isEventPublished()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of MapsGeofenceExitedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of MapsGeofenceExitedEventData 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 MapsGeofenceExitedEventData. + */ + @Generated + public static MapsGeofenceExitedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + List expiredGeofenceGeometryId = null; + List geometries = null; + List invalidPeriodGeofenceGeometryId = null; + boolean isEventPublished = false; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("expiredGeofenceGeometryId".equals(fieldName)) { + expiredGeofenceGeometryId = reader.readArray(reader1 -> reader1.getString()); + } else if ("geometries".equals(fieldName)) { + geometries = reader.readArray(reader1 -> MapsGeofenceGeometry.fromJson(reader1)); + } else if ("invalidPeriodGeofenceGeometryId".equals(fieldName)) { + invalidPeriodGeofenceGeometryId = reader.readArray(reader1 -> reader1.getString()); + } else if ("isEventPublished".equals(fieldName)) { + isEventPublished = reader.getBoolean(); + } else { + reader.skipChildren(); + } + } + return new MapsGeofenceExitedEventData(expiredGeofenceGeometryId, geometries, + invalidPeriodGeofenceGeometryId, isEventPublished); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MapsGeofenceGeometry.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MapsGeofenceGeometry.java new file mode 100644 index 000000000000..f7aca51095dd --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MapsGeofenceGeometry.java @@ -0,0 +1,209 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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 geofence geometry. + */ +@Immutable +public final class MapsGeofenceGeometry implements JsonSerializable { + /* + * ID of the device. + */ + @Generated + private final String deviceId; + + /* + * Distance from the coordinate to the closest border of the geofence. Positive means the coordinate is outside of + * the geofence. If the coordinate is outside of the geofence, but more than the value of searchBuffer away from the + * closest geofence border, then the value is 999. Negative means the coordinate is inside of the geofence. If the + * coordinate is inside the polygon, but more than the value of searchBuffer away from the closest geofencing + * border,then the value is -999. A value of 999 means that there is great confidence the coordinate is well outside + * the geofence. A value of -999 means that there is great confidence the coordinate is well within the geofence. + */ + @Generated + private final double distance; + + /* + * The unique ID for the geofence geometry. + */ + @Generated + private final String geometryId; + + /* + * Latitude of the nearest point of the geometry. + */ + @Generated + private final double nearestLat; + + /* + * Longitude of the nearest point of the geometry. + */ + @Generated + private final double nearestLon; + + /* + * The unique id returned from user upload service when uploading a geofence. Will not be included in geofencing + * post API. + */ + @Generated + private String udId; + + /** + * Creates an instance of MapsGeofenceGeometry class. + * + * @param deviceId the deviceId value to set. + * @param distance the distance value to set. + * @param geometryId the geometryId value to set. + * @param nearestLat the nearestLat value to set. + * @param nearestLon the nearestLon value to set. + */ + @Generated + private MapsGeofenceGeometry(String deviceId, double distance, String geometryId, double nearestLat, + double nearestLon) { + this.deviceId = deviceId; + this.distance = distance; + this.geometryId = geometryId; + this.nearestLat = nearestLat; + this.nearestLon = nearestLon; + } + + /** + * Get the deviceId property: ID of the device. + * + * @return the deviceId value. + */ + @Generated + public String getDeviceId() { + return this.deviceId; + } + + /** + * Get the distance property: Distance from the coordinate to the closest border of the geofence. Positive means the + * coordinate is outside of the geofence. If the coordinate is outside of the geofence, but more than the value of + * searchBuffer away from the closest geofence border, then the value is 999. Negative means the coordinate is + * inside of the geofence. If the coordinate is inside the polygon, but more than the value of searchBuffer away + * from the closest geofencing border,then the value is -999. A value of 999 means that there is great confidence + * the coordinate is well outside the geofence. A value of -999 means that there is great confidence the coordinate + * is well within the geofence. + * + * @return the distance value. + */ + @Generated + public double getDistance() { + return this.distance; + } + + /** + * Get the geometryId property: The unique ID for the geofence geometry. + * + * @return the geometryId value. + */ + @Generated + public String getGeometryId() { + return this.geometryId; + } + + /** + * Get the nearestLat property: Latitude of the nearest point of the geometry. + * + * @return the nearestLat value. + */ + @Generated + public double getNearestLat() { + return this.nearestLat; + } + + /** + * Get the nearestLon property: Longitude of the nearest point of the geometry. + * + * @return the nearestLon value. + */ + @Generated + public double getNearestLon() { + return this.nearestLon; + } + + /** + * Get the udId property: The unique id returned from user upload service when uploading a geofence. Will not be + * included in geofencing post API. + * + * @return the udId value. + */ + @Generated + public String getUdId() { + return this.udId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("deviceId", this.deviceId); + jsonWriter.writeDoubleField("distance", this.distance); + jsonWriter.writeStringField("geometryId", this.geometryId); + jsonWriter.writeDoubleField("nearestLat", this.nearestLat); + jsonWriter.writeDoubleField("nearestLon", this.nearestLon); + jsonWriter.writeStringField("udId", this.udId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of MapsGeofenceGeometry from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of MapsGeofenceGeometry 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 MapsGeofenceGeometry. + */ + @Generated + public static MapsGeofenceGeometry fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String deviceId = null; + double distance = 0.0; + String geometryId = null; + double nearestLat = 0.0; + double nearestLon = 0.0; + String udId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("deviceId".equals(fieldName)) { + deviceId = reader.getString(); + } else if ("distance".equals(fieldName)) { + distance = reader.getDouble(); + } else if ("geometryId".equals(fieldName)) { + geometryId = reader.getString(); + } else if ("nearestLat".equals(fieldName)) { + nearestLat = reader.getDouble(); + } else if ("nearestLon".equals(fieldName)) { + nearestLon = reader.getDouble(); + } else if ("udId".equals(fieldName)) { + udId = reader.getString(); + } else { + reader.skipChildren(); + } + } + MapsGeofenceGeometry deserializedMapsGeofenceGeometry + = new MapsGeofenceGeometry(deviceId, distance, geometryId, nearestLat, nearestLon); + deserializedMapsGeofenceGeometry.udId = udId; + + return deserializedMapsGeofenceGeometry; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MapsGeofenceResultEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MapsGeofenceResultEventData.java new file mode 100644 index 000000000000..7dbb69dd9378 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MapsGeofenceResultEventData.java @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.List; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Maps.GeofenceResult event. + */ +@Immutable +public final class MapsGeofenceResultEventData extends MapsGeofenceEventProperties { + /** + * Creates an instance of MapsGeofenceResultEventData class. + * + * @param expiredGeofenceGeometryId the expiredGeofenceGeometryId value to set. + * @param geometries the geometries value to set. + * @param invalidPeriodGeofenceGeometryId the invalidPeriodGeofenceGeometryId value to set. + * @param isEventPublished the isEventPublished value to set. + */ + @Generated + private MapsGeofenceResultEventData(List expiredGeofenceGeometryId, List geometries, + List invalidPeriodGeofenceGeometryId, boolean isEventPublished) { + super(expiredGeofenceGeometryId, geometries, invalidPeriodGeofenceGeometryId, isEventPublished); + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("expiredGeofenceGeometryId", getExpiredGeofenceGeometryId(), + (writer, element) -> writer.writeString(element)); + jsonWriter.writeArrayField("geometries", getGeometries(), (writer, element) -> writer.writeJson(element)); + jsonWriter.writeArrayField("invalidPeriodGeofenceGeometryId", getInvalidPeriodGeofenceGeometryId(), + (writer, element) -> writer.writeString(element)); + jsonWriter.writeBooleanField("isEventPublished", isEventPublished()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of MapsGeofenceResultEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of MapsGeofenceResultEventData 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 MapsGeofenceResultEventData. + */ + @Generated + public static MapsGeofenceResultEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + List expiredGeofenceGeometryId = null; + List geometries = null; + List invalidPeriodGeofenceGeometryId = null; + boolean isEventPublished = false; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("expiredGeofenceGeometryId".equals(fieldName)) { + expiredGeofenceGeometryId = reader.readArray(reader1 -> reader1.getString()); + } else if ("geometries".equals(fieldName)) { + geometries = reader.readArray(reader1 -> MapsGeofenceGeometry.fromJson(reader1)); + } else if ("invalidPeriodGeofenceGeometryId".equals(fieldName)) { + invalidPeriodGeofenceGeometryId = reader.readArray(reader1 -> reader1.getString()); + } else if ("isEventPublished".equals(fieldName)) { + isEventPublished = reader.getBoolean(); + } else { + reader.skipChildren(); + } + } + return new MapsGeofenceResultEventData(expiredGeofenceGeometryId, geometries, + invalidPeriodGeofenceGeometryId, isEventPublished); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MicrosoftTeamsAppIdentifier.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MicrosoftTeamsAppIdentifier.java new file mode 100644 index 000000000000..b9be995af2e6 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MicrosoftTeamsAppIdentifier.java @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * A Microsoft Teams application. + */ +@Immutable +public final class MicrosoftTeamsAppIdentifier implements JsonSerializable { + /* + * The Id of the Microsoft Teams application + */ + @Generated + private final String appId; + + /* + * The cloud that the Microsoft Teams application belongs to. By default 'public' if missing. + */ + @Generated + private final CommunicationCloudEnvironmentModel cloud; + + /** + * Creates an instance of MicrosoftTeamsAppIdentifier class. + * + * @param appId the appId value to set. + * @param cloud the cloud value to set. + */ + @Generated + private MicrosoftTeamsAppIdentifier(String appId, CommunicationCloudEnvironmentModel cloud) { + this.appId = appId; + this.cloud = cloud; + } + + /** + * Get the appId property: The Id of the Microsoft Teams application. + * + * @return the appId value. + */ + @Generated + public String getAppId() { + return this.appId; + } + + /** + * Get the cloud property: The cloud that the Microsoft Teams application belongs to. By default 'public' if + * missing. + * + * @return the cloud value. + */ + @Generated + public CommunicationCloudEnvironmentModel getCloud() { + return this.cloud; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("appId", this.appId); + jsonWriter.writeStringField("cloud", this.cloud == null ? null : this.cloud.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of MicrosoftTeamsAppIdentifier from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of MicrosoftTeamsAppIdentifier 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 MicrosoftTeamsAppIdentifier. + */ + @Generated + public static MicrosoftTeamsAppIdentifier fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String appId = null; + CommunicationCloudEnvironmentModel cloud = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("appId".equals(fieldName)) { + appId = reader.getString(); + } else if ("cloud".equals(fieldName)) { + cloud = CommunicationCloudEnvironmentModel.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + return new MicrosoftTeamsAppIdentifier(appId, cloud); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MicrosoftTeamsUserIdentifierModel.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MicrosoftTeamsUserIdentifierModel.java new file mode 100644 index 000000000000..ff5bc20087de --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/MicrosoftTeamsUserIdentifierModel.java @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * A Microsoft Teams user. + */ +@Immutable +public final class MicrosoftTeamsUserIdentifierModel implements JsonSerializable { + /* + * The Id of the Microsoft Teams user. If not anonymous, this is the AAD object Id of the user. + */ + @Generated + private final String userId; + + /* + * True if the Microsoft Teams user is anonymous. By default false if missing. + */ + @Generated + private Boolean isAnonymous; + + /* + * The cloud that the Microsoft Teams user belongs to. By default 'public' if missing. + */ + @Generated + private final CommunicationCloudEnvironmentModel cloud; + + /** + * Creates an instance of MicrosoftTeamsUserIdentifierModel class. + * + * @param userId the userId value to set. + * @param cloud the cloud value to set. + */ + @Generated + private MicrosoftTeamsUserIdentifierModel(String userId, CommunicationCloudEnvironmentModel cloud) { + this.userId = userId; + this.cloud = cloud; + } + + /** + * Get the userId property: The Id of the Microsoft Teams user. If not anonymous, this is the AAD object Id of the + * user. + * + * @return the userId value. + */ + @Generated + public String getUserId() { + return this.userId; + } + + /** + * Get the isAnonymous property: True if the Microsoft Teams user is anonymous. By default false if missing. + * + * @return the isAnonymous value. + */ + @Generated + public Boolean isAnonymous() { + return this.isAnonymous; + } + + /** + * Get the cloud property: The cloud that the Microsoft Teams user belongs to. By default 'public' if missing. + * + * @return the cloud value. + */ + @Generated + public CommunicationCloudEnvironmentModel getCloud() { + return this.cloud; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("userId", this.userId); + jsonWriter.writeStringField("cloud", this.cloud == null ? null : this.cloud.toString()); + jsonWriter.writeBooleanField("isAnonymous", this.isAnonymous); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of MicrosoftTeamsUserIdentifierModel from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of MicrosoftTeamsUserIdentifierModel 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 MicrosoftTeamsUserIdentifierModel. + */ + @Generated + public static MicrosoftTeamsUserIdentifierModel fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String userId = null; + CommunicationCloudEnvironmentModel cloud = null; + Boolean isAnonymous = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("userId".equals(fieldName)) { + userId = reader.getString(); + } else if ("cloud".equals(fieldName)) { + cloud = CommunicationCloudEnvironmentModel.fromString(reader.getString()); + } else if ("isAnonymous".equals(fieldName)) { + isAnonymous = reader.getNullable(JsonReader::getBoolean); + } else { + reader.skipChildren(); + } + } + MicrosoftTeamsUserIdentifierModel deserializedMicrosoftTeamsUserIdentifierModel + = new MicrosoftTeamsUserIdentifierModel(userId, cloud); + deserializedMicrosoftTeamsUserIdentifierModel.isAnonymous = isAnonymous; + + return deserializedMicrosoftTeamsUserIdentifierModel; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/PhoneNumberIdentifierModel.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/PhoneNumberIdentifierModel.java new file mode 100644 index 000000000000..a5eb0f05ebd9 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/PhoneNumberIdentifierModel.java @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * A phone number. + */ +@Immutable +public final class PhoneNumberIdentifierModel implements JsonSerializable { + /* + * The phone number in E.164 format. + */ + @Generated + private final String value; + + /** + * Creates an instance of PhoneNumberIdentifierModel class. + * + * @param value the value value to set. + */ + @Generated + private PhoneNumberIdentifierModel(String value) { + this.value = value; + } + + /** + * Get the value property: The phone number in E.164 format. + * + * @return the value value. + */ + @Generated + public String getValue() { + return this.value; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("value", this.value); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of PhoneNumberIdentifierModel from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of PhoneNumberIdentifierModel 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 PhoneNumberIdentifierModel. + */ + @Generated + public static PhoneNumberIdentifierModel 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 ("value".equals(fieldName)) { + value = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new PhoneNumberIdentifierModel(value); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/PolicyInsightsPolicyStateChangedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/PolicyInsightsPolicyStateChangedEventData.java new file mode 100644 index 000000000000..9b852538f7f6 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/PolicyInsightsPolicyStateChangedEventData.java @@ -0,0 +1,228 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.PolicyInsights.PolicyStateChanged event. + */ +@Immutable +public final class PolicyInsightsPolicyStateChangedEventData + implements JsonSerializable { + /* + * The time that the resource was scanned by Azure Policy in the Universal ISO 8601 DateTime format + * yyyy-MM-ddTHH:mm:ss.fffffffZ. + */ + @Generated + private final OffsetDateTime timestamp; + + /* + * The resource ID of the policy assignment. + */ + @Generated + private final String policyAssignmentId; + + /* + * The resource ID of the policy definition. + */ + @Generated + private final String policyDefinitionId; + + /* + * The reference ID for the policy definition inside the initiative definition, if the policy assignment is for an + * initiative. May be empty. + */ + @Generated + private final String policyDefinitionReferenceId; + + /* + * The compliance state of the resource with respect to the policy assignment. + */ + @Generated + private final String complianceState; + + /* + * The subscription ID of the resource. + */ + @Generated + private final String subscriptionId; + + /* + * The compliance reason code. May be empty. + */ + @Generated + private final String complianceReasonCode; + + /** + * Creates an instance of PolicyInsightsPolicyStateChangedEventData class. + * + * @param timestamp the timestamp value to set. + * @param policyAssignmentId the policyAssignmentId value to set. + * @param policyDefinitionId the policyDefinitionId value to set. + * @param policyDefinitionReferenceId the policyDefinitionReferenceId value to set. + * @param complianceState the complianceState value to set. + * @param subscriptionId the subscriptionId value to set. + * @param complianceReasonCode the complianceReasonCode value to set. + */ + @Generated + private PolicyInsightsPolicyStateChangedEventData(OffsetDateTime timestamp, String policyAssignmentId, + String policyDefinitionId, String policyDefinitionReferenceId, String complianceState, String subscriptionId, + String complianceReasonCode) { + this.timestamp = timestamp; + this.policyAssignmentId = policyAssignmentId; + this.policyDefinitionId = policyDefinitionId; + this.policyDefinitionReferenceId = policyDefinitionReferenceId; + this.complianceState = complianceState; + this.subscriptionId = subscriptionId; + this.complianceReasonCode = complianceReasonCode; + } + + /** + * Get the timestamp property: The time that the resource was scanned by Azure Policy in the Universal ISO 8601 + * DateTime format yyyy-MM-ddTHH:mm:ss.fffffffZ. + * + * @return the timestamp value. + */ + @Generated + public OffsetDateTime getTimestamp() { + return this.timestamp; + } + + /** + * Get the policyAssignmentId property: The resource ID of the policy assignment. + * + * @return the policyAssignmentId value. + */ + @Generated + public String getPolicyAssignmentId() { + return this.policyAssignmentId; + } + + /** + * Get the policyDefinitionId property: The resource ID of the policy definition. + * + * @return the policyDefinitionId value. + */ + @Generated + public String getPolicyDefinitionId() { + return this.policyDefinitionId; + } + + /** + * Get the policyDefinitionReferenceId property: The reference ID for the policy definition inside the initiative + * definition, if the policy assignment is for an initiative. May be empty. + * + * @return the policyDefinitionReferenceId value. + */ + @Generated + public String getPolicyDefinitionReferenceId() { + return this.policyDefinitionReferenceId; + } + + /** + * Get the complianceState property: The compliance state of the resource with respect to the policy assignment. + * + * @return the complianceState value. + */ + @Generated + public String getComplianceState() { + return this.complianceState; + } + + /** + * Get the subscriptionId property: The subscription ID of the resource. + * + * @return the subscriptionId value. + */ + @Generated + public String getSubscriptionId() { + return this.subscriptionId; + } + + /** + * Get the complianceReasonCode property: The compliance reason code. May be empty. + * + * @return the complianceReasonCode value. + */ + @Generated + public String getComplianceReasonCode() { + return this.complianceReasonCode; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("timestamp", + this.timestamp == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.timestamp)); + jsonWriter.writeStringField("policyAssignmentId", this.policyAssignmentId); + jsonWriter.writeStringField("policyDefinitionId", this.policyDefinitionId); + jsonWriter.writeStringField("policyDefinitionReferenceId", this.policyDefinitionReferenceId); + jsonWriter.writeStringField("complianceState", this.complianceState); + jsonWriter.writeStringField("subscriptionId", this.subscriptionId); + jsonWriter.writeStringField("complianceReasonCode", this.complianceReasonCode); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of PolicyInsightsPolicyStateChangedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of PolicyInsightsPolicyStateChangedEventData 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 PolicyInsightsPolicyStateChangedEventData. + */ + @Generated + public static PolicyInsightsPolicyStateChangedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OffsetDateTime timestamp = null; + String policyAssignmentId = null; + String policyDefinitionId = null; + String policyDefinitionReferenceId = null; + String complianceState = null; + String subscriptionId = null; + String complianceReasonCode = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("timestamp".equals(fieldName)) { + timestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("policyAssignmentId".equals(fieldName)) { + policyAssignmentId = reader.getString(); + } else if ("policyDefinitionId".equals(fieldName)) { + policyDefinitionId = reader.getString(); + } else if ("policyDefinitionReferenceId".equals(fieldName)) { + policyDefinitionReferenceId = reader.getString(); + } else if ("complianceState".equals(fieldName)) { + complianceState = reader.getString(); + } else if ("subscriptionId".equals(fieldName)) { + subscriptionId = reader.getString(); + } else if ("complianceReasonCode".equals(fieldName)) { + complianceReasonCode = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new PolicyInsightsPolicyStateChangedEventData(timestamp, policyAssignmentId, policyDefinitionId, + policyDefinitionReferenceId, complianceState, subscriptionId, complianceReasonCode); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/PolicyInsightsPolicyStateCreatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/PolicyInsightsPolicyStateCreatedEventData.java new file mode 100644 index 000000000000..f3f0e6bc7fd8 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/PolicyInsightsPolicyStateCreatedEventData.java @@ -0,0 +1,228 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.PolicyInsights.PolicyStateCreated event. + */ +@Immutable +public final class PolicyInsightsPolicyStateCreatedEventData + implements JsonSerializable { + /* + * The time that the resource was scanned by Azure Policy in the Universal ISO 8601 DateTime format + * yyyy-MM-ddTHH:mm:ss.fffffffZ. + */ + @Generated + private final OffsetDateTime timestamp; + + /* + * The resource ID of the policy assignment. + */ + @Generated + private final String policyAssignmentId; + + /* + * The resource ID of the policy definition. + */ + @Generated + private final String policyDefinitionId; + + /* + * The reference ID for the policy definition inside the initiative definition, if the policy assignment is for an + * initiative. May be empty. + */ + @Generated + private final String policyDefinitionReferenceId; + + /* + * The compliance state of the resource with respect to the policy assignment. + */ + @Generated + private final String complianceState; + + /* + * The subscription ID of the resource. + */ + @Generated + private final String subscriptionId; + + /* + * The compliance reason code. May be empty. + */ + @Generated + private final String complianceReasonCode; + + /** + * Creates an instance of PolicyInsightsPolicyStateCreatedEventData class. + * + * @param timestamp the timestamp value to set. + * @param policyAssignmentId the policyAssignmentId value to set. + * @param policyDefinitionId the policyDefinitionId value to set. + * @param policyDefinitionReferenceId the policyDefinitionReferenceId value to set. + * @param complianceState the complianceState value to set. + * @param subscriptionId the subscriptionId value to set. + * @param complianceReasonCode the complianceReasonCode value to set. + */ + @Generated + private PolicyInsightsPolicyStateCreatedEventData(OffsetDateTime timestamp, String policyAssignmentId, + String policyDefinitionId, String policyDefinitionReferenceId, String complianceState, String subscriptionId, + String complianceReasonCode) { + this.timestamp = timestamp; + this.policyAssignmentId = policyAssignmentId; + this.policyDefinitionId = policyDefinitionId; + this.policyDefinitionReferenceId = policyDefinitionReferenceId; + this.complianceState = complianceState; + this.subscriptionId = subscriptionId; + this.complianceReasonCode = complianceReasonCode; + } + + /** + * Get the timestamp property: The time that the resource was scanned by Azure Policy in the Universal ISO 8601 + * DateTime format yyyy-MM-ddTHH:mm:ss.fffffffZ. + * + * @return the timestamp value. + */ + @Generated + public OffsetDateTime getTimestamp() { + return this.timestamp; + } + + /** + * Get the policyAssignmentId property: The resource ID of the policy assignment. + * + * @return the policyAssignmentId value. + */ + @Generated + public String getPolicyAssignmentId() { + return this.policyAssignmentId; + } + + /** + * Get the policyDefinitionId property: The resource ID of the policy definition. + * + * @return the policyDefinitionId value. + */ + @Generated + public String getPolicyDefinitionId() { + return this.policyDefinitionId; + } + + /** + * Get the policyDefinitionReferenceId property: The reference ID for the policy definition inside the initiative + * definition, if the policy assignment is for an initiative. May be empty. + * + * @return the policyDefinitionReferenceId value. + */ + @Generated + public String getPolicyDefinitionReferenceId() { + return this.policyDefinitionReferenceId; + } + + /** + * Get the complianceState property: The compliance state of the resource with respect to the policy assignment. + * + * @return the complianceState value. + */ + @Generated + public String getComplianceState() { + return this.complianceState; + } + + /** + * Get the subscriptionId property: The subscription ID of the resource. + * + * @return the subscriptionId value. + */ + @Generated + public String getSubscriptionId() { + return this.subscriptionId; + } + + /** + * Get the complianceReasonCode property: The compliance reason code. May be empty. + * + * @return the complianceReasonCode value. + */ + @Generated + public String getComplianceReasonCode() { + return this.complianceReasonCode; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("timestamp", + this.timestamp == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.timestamp)); + jsonWriter.writeStringField("policyAssignmentId", this.policyAssignmentId); + jsonWriter.writeStringField("policyDefinitionId", this.policyDefinitionId); + jsonWriter.writeStringField("policyDefinitionReferenceId", this.policyDefinitionReferenceId); + jsonWriter.writeStringField("complianceState", this.complianceState); + jsonWriter.writeStringField("subscriptionId", this.subscriptionId); + jsonWriter.writeStringField("complianceReasonCode", this.complianceReasonCode); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of PolicyInsightsPolicyStateCreatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of PolicyInsightsPolicyStateCreatedEventData 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 PolicyInsightsPolicyStateCreatedEventData. + */ + @Generated + public static PolicyInsightsPolicyStateCreatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OffsetDateTime timestamp = null; + String policyAssignmentId = null; + String policyDefinitionId = null; + String policyDefinitionReferenceId = null; + String complianceState = null; + String subscriptionId = null; + String complianceReasonCode = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("timestamp".equals(fieldName)) { + timestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("policyAssignmentId".equals(fieldName)) { + policyAssignmentId = reader.getString(); + } else if ("policyDefinitionId".equals(fieldName)) { + policyDefinitionId = reader.getString(); + } else if ("policyDefinitionReferenceId".equals(fieldName)) { + policyDefinitionReferenceId = reader.getString(); + } else if ("complianceState".equals(fieldName)) { + complianceState = reader.getString(); + } else if ("subscriptionId".equals(fieldName)) { + subscriptionId = reader.getString(); + } else if ("complianceReasonCode".equals(fieldName)) { + complianceReasonCode = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new PolicyInsightsPolicyStateCreatedEventData(timestamp, policyAssignmentId, policyDefinitionId, + policyDefinitionReferenceId, complianceState, subscriptionId, complianceReasonCode); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/PolicyInsightsPolicyStateDeletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/PolicyInsightsPolicyStateDeletedEventData.java new file mode 100644 index 000000000000..a53ec96d8a9d --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/PolicyInsightsPolicyStateDeletedEventData.java @@ -0,0 +1,228 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.PolicyInsights.PolicyStateDeleted event. + */ +@Immutable +public final class PolicyInsightsPolicyStateDeletedEventData + implements JsonSerializable { + /* + * The time that the resource was scanned by Azure Policy in the Universal ISO 8601 DateTime format + * yyyy-MM-ddTHH:mm:ss.fffffffZ. + */ + @Generated + private final OffsetDateTime timestamp; + + /* + * The resource ID of the policy assignment. + */ + @Generated + private final String policyAssignmentId; + + /* + * The resource ID of the policy definition. + */ + @Generated + private final String policyDefinitionId; + + /* + * The reference ID for the policy definition inside the initiative definition, if the policy assignment is for an + * initiative. May be empty. + */ + @Generated + private final String policyDefinitionReferenceId; + + /* + * The compliance state of the resource with respect to the policy assignment. + */ + @Generated + private final String complianceState; + + /* + * The subscription ID of the resource. + */ + @Generated + private final String subscriptionId; + + /* + * The compliance reason code. May be empty. + */ + @Generated + private final String complianceReasonCode; + + /** + * Creates an instance of PolicyInsightsPolicyStateDeletedEventData class. + * + * @param timestamp the timestamp value to set. + * @param policyAssignmentId the policyAssignmentId value to set. + * @param policyDefinitionId the policyDefinitionId value to set. + * @param policyDefinitionReferenceId the policyDefinitionReferenceId value to set. + * @param complianceState the complianceState value to set. + * @param subscriptionId the subscriptionId value to set. + * @param complianceReasonCode the complianceReasonCode value to set. + */ + @Generated + private PolicyInsightsPolicyStateDeletedEventData(OffsetDateTime timestamp, String policyAssignmentId, + String policyDefinitionId, String policyDefinitionReferenceId, String complianceState, String subscriptionId, + String complianceReasonCode) { + this.timestamp = timestamp; + this.policyAssignmentId = policyAssignmentId; + this.policyDefinitionId = policyDefinitionId; + this.policyDefinitionReferenceId = policyDefinitionReferenceId; + this.complianceState = complianceState; + this.subscriptionId = subscriptionId; + this.complianceReasonCode = complianceReasonCode; + } + + /** + * Get the timestamp property: The time that the resource was scanned by Azure Policy in the Universal ISO 8601 + * DateTime format yyyy-MM-ddTHH:mm:ss.fffffffZ. + * + * @return the timestamp value. + */ + @Generated + public OffsetDateTime getTimestamp() { + return this.timestamp; + } + + /** + * Get the policyAssignmentId property: The resource ID of the policy assignment. + * + * @return the policyAssignmentId value. + */ + @Generated + public String getPolicyAssignmentId() { + return this.policyAssignmentId; + } + + /** + * Get the policyDefinitionId property: The resource ID of the policy definition. + * + * @return the policyDefinitionId value. + */ + @Generated + public String getPolicyDefinitionId() { + return this.policyDefinitionId; + } + + /** + * Get the policyDefinitionReferenceId property: The reference ID for the policy definition inside the initiative + * definition, if the policy assignment is for an initiative. May be empty. + * + * @return the policyDefinitionReferenceId value. + */ + @Generated + public String getPolicyDefinitionReferenceId() { + return this.policyDefinitionReferenceId; + } + + /** + * Get the complianceState property: The compliance state of the resource with respect to the policy assignment. + * + * @return the complianceState value. + */ + @Generated + public String getComplianceState() { + return this.complianceState; + } + + /** + * Get the subscriptionId property: The subscription ID of the resource. + * + * @return the subscriptionId value. + */ + @Generated + public String getSubscriptionId() { + return this.subscriptionId; + } + + /** + * Get the complianceReasonCode property: The compliance reason code. May be empty. + * + * @return the complianceReasonCode value. + */ + @Generated + public String getComplianceReasonCode() { + return this.complianceReasonCode; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("timestamp", + this.timestamp == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.timestamp)); + jsonWriter.writeStringField("policyAssignmentId", this.policyAssignmentId); + jsonWriter.writeStringField("policyDefinitionId", this.policyDefinitionId); + jsonWriter.writeStringField("policyDefinitionReferenceId", this.policyDefinitionReferenceId); + jsonWriter.writeStringField("complianceState", this.complianceState); + jsonWriter.writeStringField("subscriptionId", this.subscriptionId); + jsonWriter.writeStringField("complianceReasonCode", this.complianceReasonCode); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of PolicyInsightsPolicyStateDeletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of PolicyInsightsPolicyStateDeletedEventData 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 PolicyInsightsPolicyStateDeletedEventData. + */ + @Generated + public static PolicyInsightsPolicyStateDeletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OffsetDateTime timestamp = null; + String policyAssignmentId = null; + String policyDefinitionId = null; + String policyDefinitionReferenceId = null; + String complianceState = null; + String subscriptionId = null; + String complianceReasonCode = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("timestamp".equals(fieldName)) { + timestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("policyAssignmentId".equals(fieldName)) { + policyAssignmentId = reader.getString(); + } else if ("policyDefinitionId".equals(fieldName)) { + policyDefinitionId = reader.getString(); + } else if ("policyDefinitionReferenceId".equals(fieldName)) { + policyDefinitionReferenceId = reader.getString(); + } else if ("complianceState".equals(fieldName)) { + complianceState = reader.getString(); + } else if ("subscriptionId".equals(fieldName)) { + subscriptionId = reader.getString(); + } else if ("complianceReasonCode".equals(fieldName)) { + complianceReasonCode = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new PolicyInsightsPolicyStateDeletedEventData(timestamp, policyAssignmentId, policyDefinitionId, + policyDefinitionReferenceId, complianceState, subscriptionId, complianceReasonCode); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/RecordingChannelType.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/RecordingChannelType.java new file mode 100644 index 000000000000..f6bfbdb52a93 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/RecordingChannelType.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Recording channel type. + */ +public final class RecordingChannelType extends ExpandableStringEnum { + /** + * Mixed channel type. + */ + @Generated + public static final RecordingChannelType MIXED = fromString("Mixed"); + + /** + * Unmixed channel type. + */ + @Generated + public static final RecordingChannelType UNMIXED = fromString("Unmixed"); + + /** + * Creates a new instance of RecordingChannelType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public RecordingChannelType() { + } + + /** + * Creates or finds a RecordingChannelType from its string representation. + * + * @param name a name to look for. + * @return the corresponding RecordingChannelType. + */ + @Generated + public static RecordingChannelType fromString(String name) { + return fromString(name, RecordingChannelType.class); + } + + /** + * Gets known RecordingChannelType values. + * + * @return known RecordingChannelType values. + */ + @Generated + public static Collection values() { + return values(RecordingChannelType.class); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/RecordingContentType.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/RecordingContentType.java new file mode 100644 index 000000000000..964a77ce7aeb --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/RecordingContentType.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Recording content type. + */ +public final class RecordingContentType extends ExpandableStringEnum { + /** + * AudioVideo content type. + */ + @Generated + public static final RecordingContentType AUDIO_VIDEO = fromString("AudioVideo"); + + /** + * Audio content type. + */ + @Generated + public static final RecordingContentType AUDIO = fromString("Audio"); + + /** + * Creates a new instance of RecordingContentType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public RecordingContentType() { + } + + /** + * Creates or finds a RecordingContentType from its string representation. + * + * @param name a name to look for. + * @return the corresponding RecordingContentType. + */ + @Generated + public static RecordingContentType fromString(String name) { + return fromString(name, RecordingContentType.class); + } + + /** + * Gets known RecordingContentType values. + * + * @return known RecordingContentType values. + */ + @Generated + public static Collection values() { + return values(RecordingContentType.class); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/RecordingFormatType.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/RecordingFormatType.java new file mode 100644 index 000000000000..27361eff71bc --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/RecordingFormatType.java @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Recording format type. + */ +public final class RecordingFormatType extends ExpandableStringEnum { + /** + * WAV format. + */ + @Generated + public static final RecordingFormatType WAV = fromString("Wav"); + + /** + * MP3 format. + */ + @Generated + public static final RecordingFormatType MP3 = fromString("Mp3"); + + /** + * MP4 format. + */ + @Generated + public static final RecordingFormatType MP4 = fromString("Mp4"); + + /** + * Creates a new instance of RecordingFormatType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public RecordingFormatType() { + } + + /** + * Creates or finds a RecordingFormatType from its string representation. + * + * @param name a name to look for. + * @return the corresponding RecordingFormatType. + */ + @Generated + public static RecordingFormatType fromString(String name) { + return fromString(name, RecordingFormatType.class); + } + + /** + * Gets known RecordingFormatType values. + * + * @return known RecordingFormatType values. + */ + @Generated + public static Collection values() { + return values(RecordingFormatType.class); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/RedisExportRdbCompletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/RedisExportRdbCompletedEventData.java new file mode 100644 index 000000000000..0dfa9377043e --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/RedisExportRdbCompletedEventData.java @@ -0,0 +1,124 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Cache.ExportRDBCompleted event. + */ +@Immutable +public final class RedisExportRdbCompletedEventData implements JsonSerializable { + /* + * The time at which the event occurred. + */ + @Generated + private OffsetDateTime timestamp; + + /* + * The name of this event. + */ + @Generated + private String name; + + /* + * The status of this event. Failed or succeeded + */ + @Generated + private String status; + + /** + * Creates an instance of RedisExportRdbCompletedEventData class. + */ + @Generated + private RedisExportRdbCompletedEventData() { + } + + /** + * Get the timestamp property: The time at which the event occurred. + * + * @return the timestamp value. + */ + @Generated + public OffsetDateTime getTimestamp() { + return this.timestamp; + } + + /** + * Get the name property: The name of this event. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the status property: The status of this event. Failed or succeeded. + * + * @return the status value. + */ + @Generated + public String getStatus() { + return this.status; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("timestamp", + this.timestamp == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.timestamp)); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("status", this.status); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of RedisExportRdbCompletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of RedisExportRdbCompletedEventData 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 RedisExportRdbCompletedEventData. + */ + @Generated + public static RedisExportRdbCompletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + RedisExportRdbCompletedEventData deserializedRedisExportRdbCompletedEventData + = new RedisExportRdbCompletedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("timestamp".equals(fieldName)) { + deserializedRedisExportRdbCompletedEventData.timestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("name".equals(fieldName)) { + deserializedRedisExportRdbCompletedEventData.name = reader.getString(); + } else if ("status".equals(fieldName)) { + deserializedRedisExportRdbCompletedEventData.status = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedRedisExportRdbCompletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/RedisImportRdbCompletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/RedisImportRdbCompletedEventData.java new file mode 100644 index 000000000000..a03e37bbeafe --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/RedisImportRdbCompletedEventData.java @@ -0,0 +1,124 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Cache.ImportRDBCompleted event. + */ +@Immutable +public final class RedisImportRdbCompletedEventData implements JsonSerializable { + /* + * The time at which the event occurred. + */ + @Generated + private OffsetDateTime timestamp; + + /* + * The name of this event. + */ + @Generated + private String name; + + /* + * The status of this event. Failed or succeeded + */ + @Generated + private String status; + + /** + * Creates an instance of RedisImportRdbCompletedEventData class. + */ + @Generated + private RedisImportRdbCompletedEventData() { + } + + /** + * Get the timestamp property: The time at which the event occurred. + * + * @return the timestamp value. + */ + @Generated + public OffsetDateTime getTimestamp() { + return this.timestamp; + } + + /** + * Get the name property: The name of this event. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the status property: The status of this event. Failed or succeeded. + * + * @return the status value. + */ + @Generated + public String getStatus() { + return this.status; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("timestamp", + this.timestamp == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.timestamp)); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("status", this.status); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of RedisImportRdbCompletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of RedisImportRdbCompletedEventData 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 RedisImportRdbCompletedEventData. + */ + @Generated + public static RedisImportRdbCompletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + RedisImportRdbCompletedEventData deserializedRedisImportRdbCompletedEventData + = new RedisImportRdbCompletedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("timestamp".equals(fieldName)) { + deserializedRedisImportRdbCompletedEventData.timestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("name".equals(fieldName)) { + deserializedRedisImportRdbCompletedEventData.name = reader.getString(); + } else if ("status".equals(fieldName)) { + deserializedRedisImportRdbCompletedEventData.status = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedRedisImportRdbCompletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/RedisPatchingCompletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/RedisPatchingCompletedEventData.java new file mode 100644 index 000000000000..28c4dfc65ebe --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/RedisPatchingCompletedEventData.java @@ -0,0 +1,124 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Cache.PatchingCompleted event. + */ +@Immutable +public final class RedisPatchingCompletedEventData implements JsonSerializable { + /* + * The time at which the event occurred. + */ + @Generated + private OffsetDateTime timestamp; + + /* + * The name of this event. + */ + @Generated + private String name; + + /* + * The status of this event. Failed or succeeded + */ + @Generated + private String status; + + /** + * Creates an instance of RedisPatchingCompletedEventData class. + */ + @Generated + private RedisPatchingCompletedEventData() { + } + + /** + * Get the timestamp property: The time at which the event occurred. + * + * @return the timestamp value. + */ + @Generated + public OffsetDateTime getTimestamp() { + return this.timestamp; + } + + /** + * Get the name property: The name of this event. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the status property: The status of this event. Failed or succeeded. + * + * @return the status value. + */ + @Generated + public String getStatus() { + return this.status; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("timestamp", + this.timestamp == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.timestamp)); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("status", this.status); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of RedisPatchingCompletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of RedisPatchingCompletedEventData 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 RedisPatchingCompletedEventData. + */ + @Generated + public static RedisPatchingCompletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + RedisPatchingCompletedEventData deserializedRedisPatchingCompletedEventData + = new RedisPatchingCompletedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("timestamp".equals(fieldName)) { + deserializedRedisPatchingCompletedEventData.timestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("name".equals(fieldName)) { + deserializedRedisPatchingCompletedEventData.name = reader.getString(); + } else if ("status".equals(fieldName)) { + deserializedRedisPatchingCompletedEventData.status = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedRedisPatchingCompletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/RedisScalingCompletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/RedisScalingCompletedEventData.java new file mode 100644 index 000000000000..a7ca1cca16e1 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/RedisScalingCompletedEventData.java @@ -0,0 +1,124 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Cache.ScalingCompleted event. + */ +@Immutable +public final class RedisScalingCompletedEventData implements JsonSerializable { + /* + * The time at which the event occurred. + */ + @Generated + private OffsetDateTime timestamp; + + /* + * The name of this event. + */ + @Generated + private String name; + + /* + * The status of this event. Failed or succeeded + */ + @Generated + private String status; + + /** + * Creates an instance of RedisScalingCompletedEventData class. + */ + @Generated + private RedisScalingCompletedEventData() { + } + + /** + * Get the timestamp property: The time at which the event occurred. + * + * @return the timestamp value. + */ + @Generated + public OffsetDateTime getTimestamp() { + return this.timestamp; + } + + /** + * Get the name property: The name of this event. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the status property: The status of this event. Failed or succeeded. + * + * @return the status value. + */ + @Generated + public String getStatus() { + return this.status; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("timestamp", + this.timestamp == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.timestamp)); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("status", this.status); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of RedisScalingCompletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of RedisScalingCompletedEventData 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 RedisScalingCompletedEventData. + */ + @Generated + public static RedisScalingCompletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + RedisScalingCompletedEventData deserializedRedisScalingCompletedEventData + = new RedisScalingCompletedEventData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("timestamp".equals(fieldName)) { + deserializedRedisScalingCompletedEventData.timestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("name".equals(fieldName)) { + deserializedRedisScalingCompletedEventData.name = reader.getString(); + } else if ("status".equals(fieldName)) { + deserializedRedisScalingCompletedEventData.status = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedRedisScalingCompletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceActionCancelEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceActionCancelEventData.java new file mode 100644 index 000000000000..ea03f4d57179 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceActionCancelEventData.java @@ -0,0 +1,301 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Resources.ResourceActionCancel event. This is raised + * when a resource action operation is canceled. + */ +@Immutable +public final class ResourceActionCancelEventData implements JsonSerializable { + /* + * The tenant ID of the resource. + */ + @Generated + private String tenantId; + + /* + * The subscription ID of the resource. + */ + @Generated + private String subscriptionId; + + /* + * The resource group of the resource. + */ + @Generated + private String resourceGroup; + + /* + * The resource provider performing the operation. + */ + @Generated + private String resourceProvider; + + /* + * The URI of the resource in the operation. + */ + @Generated + private String resourceUri; + + /* + * The operation that was performed. + */ + @Generated + private String operationName; + + /* + * The status of the operation. + */ + @Generated + private String status; + + /* + * The requested authorization for the operation. + */ + @Generated + private final ResourceAuthorization authorization; + + /* + * The properties of the claims. + */ + @Generated + private final Map claims; + + /* + * An operation ID used for troubleshooting. + */ + @Generated + private String correlationId; + + /* + * The details of the operation. + */ + @Generated + private final ResourceHttpRequest httpRequest; + + /** + * Creates an instance of ResourceActionCancelEventData class. + * + * @param authorization the authorization value to set. + * @param claims the claims value to set. + * @param httpRequest the httpRequest value to set. + */ + @Generated + private ResourceActionCancelEventData(ResourceAuthorization authorization, Map claims, + ResourceHttpRequest httpRequest) { + this.authorization = authorization; + this.claims = claims; + this.httpRequest = httpRequest; + } + + /** + * Get the tenantId property: The tenant ID of the resource. + * + * @return the tenantId value. + */ + @Generated + public String getTenantId() { + return this.tenantId; + } + + /** + * Get the subscriptionId property: The subscription ID of the resource. + * + * @return the subscriptionId value. + */ + @Generated + public String getSubscriptionId() { + return this.subscriptionId; + } + + /** + * Get the resourceGroup property: The resource group of the resource. + * + * @return the resourceGroup value. + */ + @Generated + public String getResourceGroup() { + return this.resourceGroup; + } + + /** + * Get the resourceProvider property: The resource provider performing the operation. + * + * @return the resourceProvider value. + */ + @Generated + public String getResourceProvider() { + return this.resourceProvider; + } + + /** + * Get the resourceUri property: The URI of the resource in the operation. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * Get the operationName property: The operation that was performed. + * + * @return the operationName value. + */ + @Generated + public String getOperationName() { + return this.operationName; + } + + /** + * Get the status property: The status of the operation. + * + * @return the status value. + */ + @Generated + public String getStatus() { + return this.status; + } + + /** + * Get the authorization property: The requested authorization for the operation. + * + * @return the authorization value. + */ + @Generated + public ResourceAuthorization getAuthorization() { + return this.authorization; + } + + /** + * Get the claims property: The properties of the claims. + * + * @return the claims value. + */ + @Generated + public Map getClaims() { + return this.claims; + } + + /** + * Get the correlationId property: An operation ID used for troubleshooting. + * + * @return the correlationId value. + */ + @Generated + public String getCorrelationId() { + return this.correlationId; + } + + /** + * Get the httpRequest property: The details of the operation. + * + * @return the httpRequest value. + */ + @Generated + public ResourceHttpRequest getHttpRequest() { + return this.httpRequest; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("authorization", this.authorization); + jsonWriter.writeMapField("claims", this.claims, (writer, element) -> writer.writeString(element)); + jsonWriter.writeJsonField("httpRequest", this.httpRequest); + jsonWriter.writeStringField("tenantId", this.tenantId); + jsonWriter.writeStringField("subscriptionId", this.subscriptionId); + jsonWriter.writeStringField("resourceGroup", this.resourceGroup); + jsonWriter.writeStringField("resourceProvider", this.resourceProvider); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + jsonWriter.writeStringField("operationName", this.operationName); + jsonWriter.writeStringField("status", this.status); + jsonWriter.writeStringField("correlationId", this.correlationId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ResourceActionCancelEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ResourceActionCancelEventData 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 ResourceActionCancelEventData. + */ + @Generated + public static ResourceActionCancelEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ResourceAuthorization authorization = null; + Map claims = null; + ResourceHttpRequest httpRequest = null; + String tenantId = null; + String subscriptionId = null; + String resourceGroup = null; + String resourceProvider = null; + String resourceUri = null; + String operationName = null; + String status = null; + String correlationId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("authorization".equals(fieldName)) { + authorization = ResourceAuthorization.fromJson(reader); + } else if ("claims".equals(fieldName)) { + claims = reader.readMap(reader1 -> reader1.getString()); + } else if ("httpRequest".equals(fieldName)) { + httpRequest = ResourceHttpRequest.fromJson(reader); + } else if ("tenantId".equals(fieldName)) { + tenantId = reader.getString(); + } else if ("subscriptionId".equals(fieldName)) { + subscriptionId = reader.getString(); + } else if ("resourceGroup".equals(fieldName)) { + resourceGroup = reader.getString(); + } else if ("resourceProvider".equals(fieldName)) { + resourceProvider = reader.getString(); + } else if ("resourceUri".equals(fieldName)) { + resourceUri = reader.getString(); + } else if ("operationName".equals(fieldName)) { + operationName = reader.getString(); + } else if ("status".equals(fieldName)) { + status = reader.getString(); + } else if ("correlationId".equals(fieldName)) { + correlationId = reader.getString(); + } else { + reader.skipChildren(); + } + } + ResourceActionCancelEventData deserializedResourceActionCancelEventData + = new ResourceActionCancelEventData(authorization, claims, httpRequest); + deserializedResourceActionCancelEventData.tenantId = tenantId; + deserializedResourceActionCancelEventData.subscriptionId = subscriptionId; + deserializedResourceActionCancelEventData.resourceGroup = resourceGroup; + deserializedResourceActionCancelEventData.resourceProvider = resourceProvider; + deserializedResourceActionCancelEventData.resourceUri = resourceUri; + deserializedResourceActionCancelEventData.operationName = operationName; + deserializedResourceActionCancelEventData.status = status; + deserializedResourceActionCancelEventData.correlationId = correlationId; + + return deserializedResourceActionCancelEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceActionFailureEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceActionFailureEventData.java new file mode 100644 index 000000000000..21378acb7cdb --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceActionFailureEventData.java @@ -0,0 +1,301 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Resources.ResourceActionFailure event. This is + * raised when a resource action operation fails. + */ +@Immutable +public final class ResourceActionFailureEventData implements JsonSerializable { + /* + * The tenant ID of the resource. + */ + @Generated + private String tenantId; + + /* + * The subscription ID of the resource. + */ + @Generated + private String subscriptionId; + + /* + * The resource group of the resource. + */ + @Generated + private String resourceGroup; + + /* + * The resource provider performing the operation. + */ + @Generated + private String resourceProvider; + + /* + * The URI of the resource in the operation. + */ + @Generated + private String resourceUri; + + /* + * The operation that was performed. + */ + @Generated + private String operationName; + + /* + * The status of the operation. + */ + @Generated + private String status; + + /* + * The requested authorization for the operation. + */ + @Generated + private final ResourceAuthorization authorization; + + /* + * The properties of the claims. + */ + @Generated + private final Map claims; + + /* + * An operation ID used for troubleshooting. + */ + @Generated + private String correlationId; + + /* + * The details of the operation. + */ + @Generated + private final ResourceHttpRequest httpRequest; + + /** + * Creates an instance of ResourceActionFailureEventData class. + * + * @param authorization the authorization value to set. + * @param claims the claims value to set. + * @param httpRequest the httpRequest value to set. + */ + @Generated + private ResourceActionFailureEventData(ResourceAuthorization authorization, Map claims, + ResourceHttpRequest httpRequest) { + this.authorization = authorization; + this.claims = claims; + this.httpRequest = httpRequest; + } + + /** + * Get the tenantId property: The tenant ID of the resource. + * + * @return the tenantId value. + */ + @Generated + public String getTenantId() { + return this.tenantId; + } + + /** + * Get the subscriptionId property: The subscription ID of the resource. + * + * @return the subscriptionId value. + */ + @Generated + public String getSubscriptionId() { + return this.subscriptionId; + } + + /** + * Get the resourceGroup property: The resource group of the resource. + * + * @return the resourceGroup value. + */ + @Generated + public String getResourceGroup() { + return this.resourceGroup; + } + + /** + * Get the resourceProvider property: The resource provider performing the operation. + * + * @return the resourceProvider value. + */ + @Generated + public String getResourceProvider() { + return this.resourceProvider; + } + + /** + * Get the resourceUri property: The URI of the resource in the operation. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * Get the operationName property: The operation that was performed. + * + * @return the operationName value. + */ + @Generated + public String getOperationName() { + return this.operationName; + } + + /** + * Get the status property: The status of the operation. + * + * @return the status value. + */ + @Generated + public String getStatus() { + return this.status; + } + + /** + * Get the authorization property: The requested authorization for the operation. + * + * @return the authorization value. + */ + @Generated + public ResourceAuthorization getAuthorization() { + return this.authorization; + } + + /** + * Get the claims property: The properties of the claims. + * + * @return the claims value. + */ + @Generated + public Map getClaims() { + return this.claims; + } + + /** + * Get the correlationId property: An operation ID used for troubleshooting. + * + * @return the correlationId value. + */ + @Generated + public String getCorrelationId() { + return this.correlationId; + } + + /** + * Get the httpRequest property: The details of the operation. + * + * @return the httpRequest value. + */ + @Generated + public ResourceHttpRequest getHttpRequest() { + return this.httpRequest; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("authorization", this.authorization); + jsonWriter.writeMapField("claims", this.claims, (writer, element) -> writer.writeString(element)); + jsonWriter.writeJsonField("httpRequest", this.httpRequest); + jsonWriter.writeStringField("tenantId", this.tenantId); + jsonWriter.writeStringField("subscriptionId", this.subscriptionId); + jsonWriter.writeStringField("resourceGroup", this.resourceGroup); + jsonWriter.writeStringField("resourceProvider", this.resourceProvider); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + jsonWriter.writeStringField("operationName", this.operationName); + jsonWriter.writeStringField("status", this.status); + jsonWriter.writeStringField("correlationId", this.correlationId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ResourceActionFailureEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ResourceActionFailureEventData 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 ResourceActionFailureEventData. + */ + @Generated + public static ResourceActionFailureEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ResourceAuthorization authorization = null; + Map claims = null; + ResourceHttpRequest httpRequest = null; + String tenantId = null; + String subscriptionId = null; + String resourceGroup = null; + String resourceProvider = null; + String resourceUri = null; + String operationName = null; + String status = null; + String correlationId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("authorization".equals(fieldName)) { + authorization = ResourceAuthorization.fromJson(reader); + } else if ("claims".equals(fieldName)) { + claims = reader.readMap(reader1 -> reader1.getString()); + } else if ("httpRequest".equals(fieldName)) { + httpRequest = ResourceHttpRequest.fromJson(reader); + } else if ("tenantId".equals(fieldName)) { + tenantId = reader.getString(); + } else if ("subscriptionId".equals(fieldName)) { + subscriptionId = reader.getString(); + } else if ("resourceGroup".equals(fieldName)) { + resourceGroup = reader.getString(); + } else if ("resourceProvider".equals(fieldName)) { + resourceProvider = reader.getString(); + } else if ("resourceUri".equals(fieldName)) { + resourceUri = reader.getString(); + } else if ("operationName".equals(fieldName)) { + operationName = reader.getString(); + } else if ("status".equals(fieldName)) { + status = reader.getString(); + } else if ("correlationId".equals(fieldName)) { + correlationId = reader.getString(); + } else { + reader.skipChildren(); + } + } + ResourceActionFailureEventData deserializedResourceActionFailureEventData + = new ResourceActionFailureEventData(authorization, claims, httpRequest); + deserializedResourceActionFailureEventData.tenantId = tenantId; + deserializedResourceActionFailureEventData.subscriptionId = subscriptionId; + deserializedResourceActionFailureEventData.resourceGroup = resourceGroup; + deserializedResourceActionFailureEventData.resourceProvider = resourceProvider; + deserializedResourceActionFailureEventData.resourceUri = resourceUri; + deserializedResourceActionFailureEventData.operationName = operationName; + deserializedResourceActionFailureEventData.status = status; + deserializedResourceActionFailureEventData.correlationId = correlationId; + + return deserializedResourceActionFailureEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceActionSuccessEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceActionSuccessEventData.java new file mode 100644 index 000000000000..1894d4520aa2 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceActionSuccessEventData.java @@ -0,0 +1,301 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Resources.ResourceActionSuccess event. This is + * raised when a resource action operation succeeds. + */ +@Immutable +public final class ResourceActionSuccessEventData implements JsonSerializable { + /* + * The tenant ID of the resource. + */ + @Generated + private String tenantId; + + /* + * The subscription ID of the resource. + */ + @Generated + private String subscriptionId; + + /* + * The resource group of the resource. + */ + @Generated + private String resourceGroup; + + /* + * The resource provider performing the operation. + */ + @Generated + private String resourceProvider; + + /* + * The URI of the resource in the operation. + */ + @Generated + private String resourceUri; + + /* + * The operation that was performed. + */ + @Generated + private String operationName; + + /* + * The status of the operation. + */ + @Generated + private String status; + + /* + * The requested authorization for the operation. + */ + @Generated + private final ResourceAuthorization authorization; + + /* + * The properties of the claims. + */ + @Generated + private final Map claims; + + /* + * An operation ID used for troubleshooting. + */ + @Generated + private String correlationId; + + /* + * The details of the operation. + */ + @Generated + private final ResourceHttpRequest httpRequest; + + /** + * Creates an instance of ResourceActionSuccessEventData class. + * + * @param authorization the authorization value to set. + * @param claims the claims value to set. + * @param httpRequest the httpRequest value to set. + */ + @Generated + private ResourceActionSuccessEventData(ResourceAuthorization authorization, Map claims, + ResourceHttpRequest httpRequest) { + this.authorization = authorization; + this.claims = claims; + this.httpRequest = httpRequest; + } + + /** + * Get the tenantId property: The tenant ID of the resource. + * + * @return the tenantId value. + */ + @Generated + public String getTenantId() { + return this.tenantId; + } + + /** + * Get the subscriptionId property: The subscription ID of the resource. + * + * @return the subscriptionId value. + */ + @Generated + public String getSubscriptionId() { + return this.subscriptionId; + } + + /** + * Get the resourceGroup property: The resource group of the resource. + * + * @return the resourceGroup value. + */ + @Generated + public String getResourceGroup() { + return this.resourceGroup; + } + + /** + * Get the resourceProvider property: The resource provider performing the operation. + * + * @return the resourceProvider value. + */ + @Generated + public String getResourceProvider() { + return this.resourceProvider; + } + + /** + * Get the resourceUri property: The URI of the resource in the operation. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * Get the operationName property: The operation that was performed. + * + * @return the operationName value. + */ + @Generated + public String getOperationName() { + return this.operationName; + } + + /** + * Get the status property: The status of the operation. + * + * @return the status value. + */ + @Generated + public String getStatus() { + return this.status; + } + + /** + * Get the authorization property: The requested authorization for the operation. + * + * @return the authorization value. + */ + @Generated + public ResourceAuthorization getAuthorization() { + return this.authorization; + } + + /** + * Get the claims property: The properties of the claims. + * + * @return the claims value. + */ + @Generated + public Map getClaims() { + return this.claims; + } + + /** + * Get the correlationId property: An operation ID used for troubleshooting. + * + * @return the correlationId value. + */ + @Generated + public String getCorrelationId() { + return this.correlationId; + } + + /** + * Get the httpRequest property: The details of the operation. + * + * @return the httpRequest value. + */ + @Generated + public ResourceHttpRequest getHttpRequest() { + return this.httpRequest; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("authorization", this.authorization); + jsonWriter.writeMapField("claims", this.claims, (writer, element) -> writer.writeString(element)); + jsonWriter.writeJsonField("httpRequest", this.httpRequest); + jsonWriter.writeStringField("tenantId", this.tenantId); + jsonWriter.writeStringField("subscriptionId", this.subscriptionId); + jsonWriter.writeStringField("resourceGroup", this.resourceGroup); + jsonWriter.writeStringField("resourceProvider", this.resourceProvider); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + jsonWriter.writeStringField("operationName", this.operationName); + jsonWriter.writeStringField("status", this.status); + jsonWriter.writeStringField("correlationId", this.correlationId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ResourceActionSuccessEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ResourceActionSuccessEventData 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 ResourceActionSuccessEventData. + */ + @Generated + public static ResourceActionSuccessEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ResourceAuthorization authorization = null; + Map claims = null; + ResourceHttpRequest httpRequest = null; + String tenantId = null; + String subscriptionId = null; + String resourceGroup = null; + String resourceProvider = null; + String resourceUri = null; + String operationName = null; + String status = null; + String correlationId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("authorization".equals(fieldName)) { + authorization = ResourceAuthorization.fromJson(reader); + } else if ("claims".equals(fieldName)) { + claims = reader.readMap(reader1 -> reader1.getString()); + } else if ("httpRequest".equals(fieldName)) { + httpRequest = ResourceHttpRequest.fromJson(reader); + } else if ("tenantId".equals(fieldName)) { + tenantId = reader.getString(); + } else if ("subscriptionId".equals(fieldName)) { + subscriptionId = reader.getString(); + } else if ("resourceGroup".equals(fieldName)) { + resourceGroup = reader.getString(); + } else if ("resourceProvider".equals(fieldName)) { + resourceProvider = reader.getString(); + } else if ("resourceUri".equals(fieldName)) { + resourceUri = reader.getString(); + } else if ("operationName".equals(fieldName)) { + operationName = reader.getString(); + } else if ("status".equals(fieldName)) { + status = reader.getString(); + } else if ("correlationId".equals(fieldName)) { + correlationId = reader.getString(); + } else { + reader.skipChildren(); + } + } + ResourceActionSuccessEventData deserializedResourceActionSuccessEventData + = new ResourceActionSuccessEventData(authorization, claims, httpRequest); + deserializedResourceActionSuccessEventData.tenantId = tenantId; + deserializedResourceActionSuccessEventData.subscriptionId = subscriptionId; + deserializedResourceActionSuccessEventData.resourceGroup = resourceGroup; + deserializedResourceActionSuccessEventData.resourceProvider = resourceProvider; + deserializedResourceActionSuccessEventData.resourceUri = resourceUri; + deserializedResourceActionSuccessEventData.operationName = operationName; + deserializedResourceActionSuccessEventData.status = status; + deserializedResourceActionSuccessEventData.correlationId = correlationId; + + return deserializedResourceActionSuccessEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceAuthorization.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceAuthorization.java new file mode 100644 index 000000000000..0a0e383162a9 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceAuthorization.java @@ -0,0 +1,128 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.Map; + +/** + * The details of the authorization for the resource. + */ +@Immutable +public final class ResourceAuthorization implements JsonSerializable { + /* + * The scope of the authorization. + */ + @Generated + private String scope; + + /* + * The action being requested. + */ + @Generated + private String action; + + /* + * The evidence for the authorization. + */ + @Generated + private final Map evidence; + + /** + * Creates an instance of ResourceAuthorization class. + * + * @param evidence the evidence value to set. + */ + @Generated + private ResourceAuthorization(Map evidence) { + this.evidence = evidence; + } + + /** + * Get the scope property: The scope of the authorization. + * + * @return the scope value. + */ + @Generated + public String getScope() { + return this.scope; + } + + /** + * Get the action property: The action being requested. + * + * @return the action value. + */ + @Generated + public String getAction() { + return this.action; + } + + /** + * Get the evidence property: The evidence for the authorization. + * + * @return the evidence value. + */ + @Generated + public Map getEvidence() { + return this.evidence; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("evidence", this.evidence, (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("scope", this.scope); + jsonWriter.writeStringField("action", this.action); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ResourceAuthorization from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ResourceAuthorization 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 ResourceAuthorization. + */ + @Generated + public static ResourceAuthorization fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Map evidence = null; + String scope = null; + String action = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("evidence".equals(fieldName)) { + evidence = reader.readMap(reader1 -> reader1.getString()); + } else if ("scope".equals(fieldName)) { + scope = reader.getString(); + } else if ("action".equals(fieldName)) { + action = reader.getString(); + } else { + reader.skipChildren(); + } + } + ResourceAuthorization deserializedResourceAuthorization = new ResourceAuthorization(evidence); + deserializedResourceAuthorization.scope = scope; + deserializedResourceAuthorization.action = action; + + return deserializedResourceAuthorization; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceDeleteCancelEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceDeleteCancelEventData.java new file mode 100644 index 000000000000..db6f18b6cb69 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceDeleteCancelEventData.java @@ -0,0 +1,301 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Resources.ResourceDeleteCancel event. This is raised + * when a resource delete operation is canceled. + */ +@Immutable +public final class ResourceDeleteCancelEventData implements JsonSerializable { + /* + * The tenant ID of the resource. + */ + @Generated + private String tenantId; + + /* + * The subscription ID of the resource. + */ + @Generated + private String subscriptionId; + + /* + * The resource group of the resource. + */ + @Generated + private String resourceGroup; + + /* + * The resource provider performing the operation. + */ + @Generated + private String resourceProvider; + + /* + * The URI of the resource in the operation. + */ + @Generated + private String resourceUri; + + /* + * The operation that was performed. + */ + @Generated + private String operationName; + + /* + * The status of the operation. + */ + @Generated + private String status; + + /* + * The requested authorization for the operation. + */ + @Generated + private final ResourceAuthorization authorization; + + /* + * The properties of the claims. + */ + @Generated + private final Map claims; + + /* + * An operation ID used for troubleshooting. + */ + @Generated + private String correlationId; + + /* + * The details of the operation. + */ + @Generated + private final ResourceHttpRequest httpRequest; + + /** + * Creates an instance of ResourceDeleteCancelEventData class. + * + * @param authorization the authorization value to set. + * @param claims the claims value to set. + * @param httpRequest the httpRequest value to set. + */ + @Generated + private ResourceDeleteCancelEventData(ResourceAuthorization authorization, Map claims, + ResourceHttpRequest httpRequest) { + this.authorization = authorization; + this.claims = claims; + this.httpRequest = httpRequest; + } + + /** + * Get the tenantId property: The tenant ID of the resource. + * + * @return the tenantId value. + */ + @Generated + public String getTenantId() { + return this.tenantId; + } + + /** + * Get the subscriptionId property: The subscription ID of the resource. + * + * @return the subscriptionId value. + */ + @Generated + public String getSubscriptionId() { + return this.subscriptionId; + } + + /** + * Get the resourceGroup property: The resource group of the resource. + * + * @return the resourceGroup value. + */ + @Generated + public String getResourceGroup() { + return this.resourceGroup; + } + + /** + * Get the resourceProvider property: The resource provider performing the operation. + * + * @return the resourceProvider value. + */ + @Generated + public String getResourceProvider() { + return this.resourceProvider; + } + + /** + * Get the resourceUri property: The URI of the resource in the operation. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * Get the operationName property: The operation that was performed. + * + * @return the operationName value. + */ + @Generated + public String getOperationName() { + return this.operationName; + } + + /** + * Get the status property: The status of the operation. + * + * @return the status value. + */ + @Generated + public String getStatus() { + return this.status; + } + + /** + * Get the authorization property: The requested authorization for the operation. + * + * @return the authorization value. + */ + @Generated + public ResourceAuthorization getAuthorization() { + return this.authorization; + } + + /** + * Get the claims property: The properties of the claims. + * + * @return the claims value. + */ + @Generated + public Map getClaims() { + return this.claims; + } + + /** + * Get the correlationId property: An operation ID used for troubleshooting. + * + * @return the correlationId value. + */ + @Generated + public String getCorrelationId() { + return this.correlationId; + } + + /** + * Get the httpRequest property: The details of the operation. + * + * @return the httpRequest value. + */ + @Generated + public ResourceHttpRequest getHttpRequest() { + return this.httpRequest; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("authorization", this.authorization); + jsonWriter.writeMapField("claims", this.claims, (writer, element) -> writer.writeString(element)); + jsonWriter.writeJsonField("httpRequest", this.httpRequest); + jsonWriter.writeStringField("tenantId", this.tenantId); + jsonWriter.writeStringField("subscriptionId", this.subscriptionId); + jsonWriter.writeStringField("resourceGroup", this.resourceGroup); + jsonWriter.writeStringField("resourceProvider", this.resourceProvider); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + jsonWriter.writeStringField("operationName", this.operationName); + jsonWriter.writeStringField("status", this.status); + jsonWriter.writeStringField("correlationId", this.correlationId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ResourceDeleteCancelEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ResourceDeleteCancelEventData 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 ResourceDeleteCancelEventData. + */ + @Generated + public static ResourceDeleteCancelEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ResourceAuthorization authorization = null; + Map claims = null; + ResourceHttpRequest httpRequest = null; + String tenantId = null; + String subscriptionId = null; + String resourceGroup = null; + String resourceProvider = null; + String resourceUri = null; + String operationName = null; + String status = null; + String correlationId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("authorization".equals(fieldName)) { + authorization = ResourceAuthorization.fromJson(reader); + } else if ("claims".equals(fieldName)) { + claims = reader.readMap(reader1 -> reader1.getString()); + } else if ("httpRequest".equals(fieldName)) { + httpRequest = ResourceHttpRequest.fromJson(reader); + } else if ("tenantId".equals(fieldName)) { + tenantId = reader.getString(); + } else if ("subscriptionId".equals(fieldName)) { + subscriptionId = reader.getString(); + } else if ("resourceGroup".equals(fieldName)) { + resourceGroup = reader.getString(); + } else if ("resourceProvider".equals(fieldName)) { + resourceProvider = reader.getString(); + } else if ("resourceUri".equals(fieldName)) { + resourceUri = reader.getString(); + } else if ("operationName".equals(fieldName)) { + operationName = reader.getString(); + } else if ("status".equals(fieldName)) { + status = reader.getString(); + } else if ("correlationId".equals(fieldName)) { + correlationId = reader.getString(); + } else { + reader.skipChildren(); + } + } + ResourceDeleteCancelEventData deserializedResourceDeleteCancelEventData + = new ResourceDeleteCancelEventData(authorization, claims, httpRequest); + deserializedResourceDeleteCancelEventData.tenantId = tenantId; + deserializedResourceDeleteCancelEventData.subscriptionId = subscriptionId; + deserializedResourceDeleteCancelEventData.resourceGroup = resourceGroup; + deserializedResourceDeleteCancelEventData.resourceProvider = resourceProvider; + deserializedResourceDeleteCancelEventData.resourceUri = resourceUri; + deserializedResourceDeleteCancelEventData.operationName = operationName; + deserializedResourceDeleteCancelEventData.status = status; + deserializedResourceDeleteCancelEventData.correlationId = correlationId; + + return deserializedResourceDeleteCancelEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceDeleteFailureEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceDeleteFailureEventData.java new file mode 100644 index 000000000000..da718b8e51d3 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceDeleteFailureEventData.java @@ -0,0 +1,301 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Resources.ResourceDeleteFailure event. This is + * raised when a resource delete operation fails. + */ +@Immutable +public final class ResourceDeleteFailureEventData implements JsonSerializable { + /* + * The tenant ID of the resource. + */ + @Generated + private String tenantId; + + /* + * The subscription ID of the resource. + */ + @Generated + private String subscriptionId; + + /* + * The resource group of the resource. + */ + @Generated + private String resourceGroup; + + /* + * The resource provider performing the operation. + */ + @Generated + private String resourceProvider; + + /* + * The URI of the resource in the operation. + */ + @Generated + private String resourceUri; + + /* + * The operation that was performed. + */ + @Generated + private String operationName; + + /* + * The status of the operation. + */ + @Generated + private String status; + + /* + * The requested authorization for the operation. + */ + @Generated + private final ResourceAuthorization authorization; + + /* + * The properties of the claims. + */ + @Generated + private final Map claims; + + /* + * An operation ID used for troubleshooting. + */ + @Generated + private String correlationId; + + /* + * The details of the operation. + */ + @Generated + private final ResourceHttpRequest httpRequest; + + /** + * Creates an instance of ResourceDeleteFailureEventData class. + * + * @param authorization the authorization value to set. + * @param claims the claims value to set. + * @param httpRequest the httpRequest value to set. + */ + @Generated + private ResourceDeleteFailureEventData(ResourceAuthorization authorization, Map claims, + ResourceHttpRequest httpRequest) { + this.authorization = authorization; + this.claims = claims; + this.httpRequest = httpRequest; + } + + /** + * Get the tenantId property: The tenant ID of the resource. + * + * @return the tenantId value. + */ + @Generated + public String getTenantId() { + return this.tenantId; + } + + /** + * Get the subscriptionId property: The subscription ID of the resource. + * + * @return the subscriptionId value. + */ + @Generated + public String getSubscriptionId() { + return this.subscriptionId; + } + + /** + * Get the resourceGroup property: The resource group of the resource. + * + * @return the resourceGroup value. + */ + @Generated + public String getResourceGroup() { + return this.resourceGroup; + } + + /** + * Get the resourceProvider property: The resource provider performing the operation. + * + * @return the resourceProvider value. + */ + @Generated + public String getResourceProvider() { + return this.resourceProvider; + } + + /** + * Get the resourceUri property: The URI of the resource in the operation. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * Get the operationName property: The operation that was performed. + * + * @return the operationName value. + */ + @Generated + public String getOperationName() { + return this.operationName; + } + + /** + * Get the status property: The status of the operation. + * + * @return the status value. + */ + @Generated + public String getStatus() { + return this.status; + } + + /** + * Get the authorization property: The requested authorization for the operation. + * + * @return the authorization value. + */ + @Generated + public ResourceAuthorization getAuthorization() { + return this.authorization; + } + + /** + * Get the claims property: The properties of the claims. + * + * @return the claims value. + */ + @Generated + public Map getClaims() { + return this.claims; + } + + /** + * Get the correlationId property: An operation ID used for troubleshooting. + * + * @return the correlationId value. + */ + @Generated + public String getCorrelationId() { + return this.correlationId; + } + + /** + * Get the httpRequest property: The details of the operation. + * + * @return the httpRequest value. + */ + @Generated + public ResourceHttpRequest getHttpRequest() { + return this.httpRequest; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("authorization", this.authorization); + jsonWriter.writeMapField("claims", this.claims, (writer, element) -> writer.writeString(element)); + jsonWriter.writeJsonField("httpRequest", this.httpRequest); + jsonWriter.writeStringField("tenantId", this.tenantId); + jsonWriter.writeStringField("subscriptionId", this.subscriptionId); + jsonWriter.writeStringField("resourceGroup", this.resourceGroup); + jsonWriter.writeStringField("resourceProvider", this.resourceProvider); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + jsonWriter.writeStringField("operationName", this.operationName); + jsonWriter.writeStringField("status", this.status); + jsonWriter.writeStringField("correlationId", this.correlationId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ResourceDeleteFailureEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ResourceDeleteFailureEventData 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 ResourceDeleteFailureEventData. + */ + @Generated + public static ResourceDeleteFailureEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ResourceAuthorization authorization = null; + Map claims = null; + ResourceHttpRequest httpRequest = null; + String tenantId = null; + String subscriptionId = null; + String resourceGroup = null; + String resourceProvider = null; + String resourceUri = null; + String operationName = null; + String status = null; + String correlationId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("authorization".equals(fieldName)) { + authorization = ResourceAuthorization.fromJson(reader); + } else if ("claims".equals(fieldName)) { + claims = reader.readMap(reader1 -> reader1.getString()); + } else if ("httpRequest".equals(fieldName)) { + httpRequest = ResourceHttpRequest.fromJson(reader); + } else if ("tenantId".equals(fieldName)) { + tenantId = reader.getString(); + } else if ("subscriptionId".equals(fieldName)) { + subscriptionId = reader.getString(); + } else if ("resourceGroup".equals(fieldName)) { + resourceGroup = reader.getString(); + } else if ("resourceProvider".equals(fieldName)) { + resourceProvider = reader.getString(); + } else if ("resourceUri".equals(fieldName)) { + resourceUri = reader.getString(); + } else if ("operationName".equals(fieldName)) { + operationName = reader.getString(); + } else if ("status".equals(fieldName)) { + status = reader.getString(); + } else if ("correlationId".equals(fieldName)) { + correlationId = reader.getString(); + } else { + reader.skipChildren(); + } + } + ResourceDeleteFailureEventData deserializedResourceDeleteFailureEventData + = new ResourceDeleteFailureEventData(authorization, claims, httpRequest); + deserializedResourceDeleteFailureEventData.tenantId = tenantId; + deserializedResourceDeleteFailureEventData.subscriptionId = subscriptionId; + deserializedResourceDeleteFailureEventData.resourceGroup = resourceGroup; + deserializedResourceDeleteFailureEventData.resourceProvider = resourceProvider; + deserializedResourceDeleteFailureEventData.resourceUri = resourceUri; + deserializedResourceDeleteFailureEventData.operationName = operationName; + deserializedResourceDeleteFailureEventData.status = status; + deserializedResourceDeleteFailureEventData.correlationId = correlationId; + + return deserializedResourceDeleteFailureEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceDeleteSuccessEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceDeleteSuccessEventData.java new file mode 100644 index 000000000000..25881f8629ad --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceDeleteSuccessEventData.java @@ -0,0 +1,301 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Resources.ResourceDeleteSuccess event. This is + * raised when a resource delete operation succeeds. + */ +@Immutable +public final class ResourceDeleteSuccessEventData implements JsonSerializable { + /* + * The tenant ID of the resource. + */ + @Generated + private String tenantId; + + /* + * The subscription ID of the resource. + */ + @Generated + private String subscriptionId; + + /* + * The resource group of the resource. + */ + @Generated + private String resourceGroup; + + /* + * The resource provider performing the operation. + */ + @Generated + private String resourceProvider; + + /* + * The URI of the resource in the operation. + */ + @Generated + private String resourceUri; + + /* + * The operation that was performed. + */ + @Generated + private String operationName; + + /* + * The status of the operation. + */ + @Generated + private String status; + + /* + * The requested authorization for the operation. + */ + @Generated + private final ResourceAuthorization authorization; + + /* + * The properties of the claims. + */ + @Generated + private final Map claims; + + /* + * An operation ID used for troubleshooting. + */ + @Generated + private String correlationId; + + /* + * The details of the operation. + */ + @Generated + private final ResourceHttpRequest httpRequest; + + /** + * Creates an instance of ResourceDeleteSuccessEventData class. + * + * @param authorization the authorization value to set. + * @param claims the claims value to set. + * @param httpRequest the httpRequest value to set. + */ + @Generated + private ResourceDeleteSuccessEventData(ResourceAuthorization authorization, Map claims, + ResourceHttpRequest httpRequest) { + this.authorization = authorization; + this.claims = claims; + this.httpRequest = httpRequest; + } + + /** + * Get the tenantId property: The tenant ID of the resource. + * + * @return the tenantId value. + */ + @Generated + public String getTenantId() { + return this.tenantId; + } + + /** + * Get the subscriptionId property: The subscription ID of the resource. + * + * @return the subscriptionId value. + */ + @Generated + public String getSubscriptionId() { + return this.subscriptionId; + } + + /** + * Get the resourceGroup property: The resource group of the resource. + * + * @return the resourceGroup value. + */ + @Generated + public String getResourceGroup() { + return this.resourceGroup; + } + + /** + * Get the resourceProvider property: The resource provider performing the operation. + * + * @return the resourceProvider value. + */ + @Generated + public String getResourceProvider() { + return this.resourceProvider; + } + + /** + * Get the resourceUri property: The URI of the resource in the operation. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * Get the operationName property: The operation that was performed. + * + * @return the operationName value. + */ + @Generated + public String getOperationName() { + return this.operationName; + } + + /** + * Get the status property: The status of the operation. + * + * @return the status value. + */ + @Generated + public String getStatus() { + return this.status; + } + + /** + * Get the authorization property: The requested authorization for the operation. + * + * @return the authorization value. + */ + @Generated + public ResourceAuthorization getAuthorization() { + return this.authorization; + } + + /** + * Get the claims property: The properties of the claims. + * + * @return the claims value. + */ + @Generated + public Map getClaims() { + return this.claims; + } + + /** + * Get the correlationId property: An operation ID used for troubleshooting. + * + * @return the correlationId value. + */ + @Generated + public String getCorrelationId() { + return this.correlationId; + } + + /** + * Get the httpRequest property: The details of the operation. + * + * @return the httpRequest value. + */ + @Generated + public ResourceHttpRequest getHttpRequest() { + return this.httpRequest; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("authorization", this.authorization); + jsonWriter.writeMapField("claims", this.claims, (writer, element) -> writer.writeString(element)); + jsonWriter.writeJsonField("httpRequest", this.httpRequest); + jsonWriter.writeStringField("tenantId", this.tenantId); + jsonWriter.writeStringField("subscriptionId", this.subscriptionId); + jsonWriter.writeStringField("resourceGroup", this.resourceGroup); + jsonWriter.writeStringField("resourceProvider", this.resourceProvider); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + jsonWriter.writeStringField("operationName", this.operationName); + jsonWriter.writeStringField("status", this.status); + jsonWriter.writeStringField("correlationId", this.correlationId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ResourceDeleteSuccessEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ResourceDeleteSuccessEventData 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 ResourceDeleteSuccessEventData. + */ + @Generated + public static ResourceDeleteSuccessEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ResourceAuthorization authorization = null; + Map claims = null; + ResourceHttpRequest httpRequest = null; + String tenantId = null; + String subscriptionId = null; + String resourceGroup = null; + String resourceProvider = null; + String resourceUri = null; + String operationName = null; + String status = null; + String correlationId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("authorization".equals(fieldName)) { + authorization = ResourceAuthorization.fromJson(reader); + } else if ("claims".equals(fieldName)) { + claims = reader.readMap(reader1 -> reader1.getString()); + } else if ("httpRequest".equals(fieldName)) { + httpRequest = ResourceHttpRequest.fromJson(reader); + } else if ("tenantId".equals(fieldName)) { + tenantId = reader.getString(); + } else if ("subscriptionId".equals(fieldName)) { + subscriptionId = reader.getString(); + } else if ("resourceGroup".equals(fieldName)) { + resourceGroup = reader.getString(); + } else if ("resourceProvider".equals(fieldName)) { + resourceProvider = reader.getString(); + } else if ("resourceUri".equals(fieldName)) { + resourceUri = reader.getString(); + } else if ("operationName".equals(fieldName)) { + operationName = reader.getString(); + } else if ("status".equals(fieldName)) { + status = reader.getString(); + } else if ("correlationId".equals(fieldName)) { + correlationId = reader.getString(); + } else { + reader.skipChildren(); + } + } + ResourceDeleteSuccessEventData deserializedResourceDeleteSuccessEventData + = new ResourceDeleteSuccessEventData(authorization, claims, httpRequest); + deserializedResourceDeleteSuccessEventData.tenantId = tenantId; + deserializedResourceDeleteSuccessEventData.subscriptionId = subscriptionId; + deserializedResourceDeleteSuccessEventData.resourceGroup = resourceGroup; + deserializedResourceDeleteSuccessEventData.resourceProvider = resourceProvider; + deserializedResourceDeleteSuccessEventData.resourceUri = resourceUri; + deserializedResourceDeleteSuccessEventData.operationName = operationName; + deserializedResourceDeleteSuccessEventData.status = status; + deserializedResourceDeleteSuccessEventData.correlationId = correlationId; + + return deserializedResourceDeleteSuccessEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceHttpRequest.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceHttpRequest.java new file mode 100644 index 000000000000..7acb3629fc81 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceHttpRequest.java @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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 details of the HTTP request. + */ +@Immutable +public final class ResourceHttpRequest implements JsonSerializable { + /* + * The client request ID. + */ + @Generated + private String clientRequestId; + + /* + * The client IP address. + */ + @Generated + private String clientIpAddress; + + /* + * The request method. + */ + @Generated + private String method; + + /* + * The url used in the request. + */ + @Generated + private String url; + + /** + * Creates an instance of ResourceHttpRequest class. + */ + @Generated + private ResourceHttpRequest() { + } + + /** + * Get the clientRequestId property: The client request ID. + * + * @return the clientRequestId value. + */ + @Generated + public String getClientRequestId() { + return this.clientRequestId; + } + + /** + * Get the clientIpAddress property: The client IP address. + * + * @return the clientIpAddress value. + */ + @Generated + public String getClientIpAddress() { + return this.clientIpAddress; + } + + /** + * Get the method property: The request method. + * + * @return the method value. + */ + @Generated + public String getMethod() { + return this.method; + } + + /** + * Get the url property: The url used in the request. + * + * @return the url value. + */ + @Generated + public String getUrl() { + return this.url; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("clientRequestId", this.clientRequestId); + jsonWriter.writeStringField("clientIpAddress", this.clientIpAddress); + jsonWriter.writeStringField("method", this.method); + jsonWriter.writeStringField("url", this.url); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ResourceHttpRequest from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ResourceHttpRequest 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 ResourceHttpRequest. + */ + @Generated + public static ResourceHttpRequest fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ResourceHttpRequest deserializedResourceHttpRequest = new ResourceHttpRequest(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("clientRequestId".equals(fieldName)) { + deserializedResourceHttpRequest.clientRequestId = reader.getString(); + } else if ("clientIpAddress".equals(fieldName)) { + deserializedResourceHttpRequest.clientIpAddress = reader.getString(); + } else if ("method".equals(fieldName)) { + deserializedResourceHttpRequest.method = reader.getString(); + } else if ("url".equals(fieldName)) { + deserializedResourceHttpRequest.url = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedResourceHttpRequest; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsContainerServiceEventResourcesScheduledEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsContainerServiceEventResourcesScheduledEventData.java new file mode 100644 index 000000000000..83b0d3d39972 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsContainerServiceEventResourcesScheduledEventData.java @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an event grid event for a + * Microsoft.ResourceNotifications.ContainerServiceEventResources.ScheduledEventEmitted preview event. + */ +@Immutable +public final class ResourceNotificationsContainerServiceEventResourcesScheduledEventData + extends ResourceNotificationsResourceUpdatedEventData { + /** + * Creates an instance of ResourceNotificationsContainerServiceEventResourcesScheduledEventData class. + * + * @param resourceDetails the resourceDetails value to set. + * @param operationalDetails the operationalDetails value to set. + * @param apiVersion the apiVersion value to set. + */ + @Generated + private ResourceNotificationsContainerServiceEventResourcesScheduledEventData( + ResourceNotificationsResourceUpdatedDetails resourceDetails, + ResourceNotificationsOperationalDetails operationalDetails, String apiVersion) { + super(resourceDetails, operationalDetails, apiVersion); + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("resourceInfo", getResourceDetails()); + jsonWriter.writeJsonField("operationalInfo", getOperationalDetails()); + jsonWriter.writeStringField("apiVersion", getApiVersion()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ResourceNotificationsContainerServiceEventResourcesScheduledEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ResourceNotificationsContainerServiceEventResourcesScheduledEventData 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 + * ResourceNotificationsContainerServiceEventResourcesScheduledEventData. + */ + @Generated + public static ResourceNotificationsContainerServiceEventResourcesScheduledEventData fromJson(JsonReader jsonReader) + throws IOException { + return jsonReader.readObject(reader -> { + ResourceNotificationsResourceUpdatedDetails resourceDetails = null; + ResourceNotificationsOperationalDetails operationalDetails = null; + String apiVersion = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceInfo".equals(fieldName)) { + resourceDetails = ResourceNotificationsResourceUpdatedDetails.fromJson(reader); + } else if ("operationalInfo".equals(fieldName)) { + operationalDetails = ResourceNotificationsOperationalDetails.fromJson(reader); + } else if ("apiVersion".equals(fieldName)) { + apiVersion = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new ResourceNotificationsContainerServiceEventResourcesScheduledEventData(resourceDetails, + operationalDetails, apiVersion); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsHealthResourcesAnnotatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsHealthResourcesAnnotatedEventData.java new file mode 100644 index 000000000000..86fd9f3f7125 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsHealthResourcesAnnotatedEventData.java @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a + * Microsoft.ResourceNotifications.HealthResources.ResourceAnnotated event. + */ +@Immutable +public final class ResourceNotificationsHealthResourcesAnnotatedEventData + extends ResourceNotificationsResourceUpdatedEventData { + /** + * Creates an instance of ResourceNotificationsHealthResourcesAnnotatedEventData class. + * + * @param resourceDetails the resourceDetails value to set. + * @param operationalDetails the operationalDetails value to set. + * @param apiVersion the apiVersion value to set. + */ + @Generated + private ResourceNotificationsHealthResourcesAnnotatedEventData( + ResourceNotificationsResourceUpdatedDetails resourceDetails, + ResourceNotificationsOperationalDetails operationalDetails, String apiVersion) { + super(resourceDetails, operationalDetails, apiVersion); + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("resourceInfo", getResourceDetails()); + jsonWriter.writeJsonField("operationalInfo", getOperationalDetails()); + jsonWriter.writeStringField("apiVersion", getApiVersion()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ResourceNotificationsHealthResourcesAnnotatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ResourceNotificationsHealthResourcesAnnotatedEventData 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 ResourceNotificationsHealthResourcesAnnotatedEventData. + */ + @Generated + public static ResourceNotificationsHealthResourcesAnnotatedEventData fromJson(JsonReader jsonReader) + throws IOException { + return jsonReader.readObject(reader -> { + ResourceNotificationsResourceUpdatedDetails resourceDetails = null; + ResourceNotificationsOperationalDetails operationalDetails = null; + String apiVersion = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceInfo".equals(fieldName)) { + resourceDetails = ResourceNotificationsResourceUpdatedDetails.fromJson(reader); + } else if ("operationalInfo".equals(fieldName)) { + operationalDetails = ResourceNotificationsOperationalDetails.fromJson(reader); + } else if ("apiVersion".equals(fieldName)) { + apiVersion = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new ResourceNotificationsHealthResourcesAnnotatedEventData(resourceDetails, operationalDetails, + apiVersion); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsHealthResourcesAvailabilityStatusChangedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsHealthResourcesAvailabilityStatusChangedEventData.java new file mode 100644 index 000000000000..ba06529897fc --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsHealthResourcesAvailabilityStatusChangedEventData.java @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a + * Microsoft.ResourceNotifications.HealthResources.AvailabilityStatusChanged + * event. + */ +@Immutable +public final class ResourceNotificationsHealthResourcesAvailabilityStatusChangedEventData + extends ResourceNotificationsResourceUpdatedEventData { + /** + * Creates an instance of ResourceNotificationsHealthResourcesAvailabilityStatusChangedEventData class. + * + * @param resourceDetails the resourceDetails value to set. + * @param operationalDetails the operationalDetails value to set. + * @param apiVersion the apiVersion value to set. + */ + @Generated + private ResourceNotificationsHealthResourcesAvailabilityStatusChangedEventData( + ResourceNotificationsResourceUpdatedDetails resourceDetails, + ResourceNotificationsOperationalDetails operationalDetails, String apiVersion) { + super(resourceDetails, operationalDetails, apiVersion); + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("resourceInfo", getResourceDetails()); + jsonWriter.writeJsonField("operationalInfo", getOperationalDetails()); + jsonWriter.writeStringField("apiVersion", getApiVersion()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ResourceNotificationsHealthResourcesAvailabilityStatusChangedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ResourceNotificationsHealthResourcesAvailabilityStatusChangedEventData 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 + * ResourceNotificationsHealthResourcesAvailabilityStatusChangedEventData. + */ + @Generated + public static ResourceNotificationsHealthResourcesAvailabilityStatusChangedEventData fromJson(JsonReader jsonReader) + throws IOException { + return jsonReader.readObject(reader -> { + ResourceNotificationsResourceUpdatedDetails resourceDetails = null; + ResourceNotificationsOperationalDetails operationalDetails = null; + String apiVersion = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceInfo".equals(fieldName)) { + resourceDetails = ResourceNotificationsResourceUpdatedDetails.fromJson(reader); + } else if ("operationalInfo".equals(fieldName)) { + operationalDetails = ResourceNotificationsOperationalDetails.fromJson(reader); + } else if ("apiVersion".equals(fieldName)) { + apiVersion = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new ResourceNotificationsHealthResourcesAvailabilityStatusChangedEventData(resourceDetails, + operationalDetails, apiVersion); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsOperationalDetails.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsOperationalDetails.java new file mode 100644 index 000000000000..9d3848091369 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsOperationalDetails.java @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * details of operational info. + */ +@Immutable +public final class ResourceNotificationsOperationalDetails + implements JsonSerializable { + /* + * Date and Time when resource was updated + */ + @Generated + private final OffsetDateTime resourceEventTime; + + /** + * Creates an instance of ResourceNotificationsOperationalDetails class. + * + * @param resourceEventTime the resourceEventTime value to set. + */ + @Generated + private ResourceNotificationsOperationalDetails(OffsetDateTime resourceEventTime) { + this.resourceEventTime = resourceEventTime; + } + + /** + * Get the resourceEventTime property: Date and Time when resource was updated. + * + * @return the resourceEventTime value. + */ + @Generated + public OffsetDateTime getResourceEventTime() { + return this.resourceEventTime; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceEventTime", + this.resourceEventTime == null + ? null + : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.resourceEventTime)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ResourceNotificationsOperationalDetails from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ResourceNotificationsOperationalDetails 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 ResourceNotificationsOperationalDetails. + */ + @Generated + public static ResourceNotificationsOperationalDetails fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OffsetDateTime resourceEventTime = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceEventTime".equals(fieldName)) { + resourceEventTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else { + reader.skipChildren(); + } + } + return new ResourceNotificationsOperationalDetails(resourceEventTime); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsResourceDeletedDetails.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsResourceDeletedDetails.java new file mode 100644 index 000000000000..ba1b4aca8a91 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsResourceDeletedDetails.java @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Describes the schema of the properties under resource info which are common + * across all ARN system topic delete events. + */ +@Immutable +public final class ResourceNotificationsResourceDeletedDetails + implements JsonSerializable { + /* + * id of the resource for which the event is being emitted + */ + @Generated + private final String id; + + /* + * name of the resource for which the event is being emitted + */ + @Generated + private final String name; + + /* + * the type of the resource for which the event is being emitted + */ + @Generated + private final String type; + + /** + * Creates an instance of ResourceNotificationsResourceDeletedDetails class. + * + * @param id the id value to set. + * @param name the name value to set. + * @param type the type value to set. + */ + @Generated + private ResourceNotificationsResourceDeletedDetails(String id, String name, String type) { + this.id = id; + this.name = name; + this.type = type; + } + + /** + * Get the id property: id of the resource for which the event is being emitted. + * + * @return the id value. + */ + @Generated + public String getId() { + return this.id; + } + + /** + * Get the name property: name of the resource for which the event is being emitted. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the type property: the type of the resource for which the event is being emitted. + * + * @return the type value. + */ + @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("name", this.name); + jsonWriter.writeStringField("type", this.type); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ResourceNotificationsResourceDeletedDetails from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ResourceNotificationsResourceDeletedDetails 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 ResourceNotificationsResourceDeletedDetails. + */ + @Generated + public static ResourceNotificationsResourceDeletedDetails fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String id = null; + String name = 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 ("name".equals(fieldName)) { + name = reader.getString(); + } else if ("type".equals(fieldName)) { + type = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new ResourceNotificationsResourceDeletedDetails(id, name, type); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsResourceDeletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsResourceDeletedEventData.java new file mode 100644 index 000000000000..4994c083f517 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsResourceDeletedEventData.java @@ -0,0 +1,108 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Describes the schema of the common properties across all ARN system topic + * delete events. + */ +@Immutable +public class ResourceNotificationsResourceDeletedEventData + implements JsonSerializable { + /* + * resourceInfo details for delete event + */ + @Generated + private final ResourceNotificationsResourceDeletedDetails resourceDetails; + + /* + * details about operational info + */ + @Generated + private final ResourceNotificationsOperationalDetails operationalDetails; + + /** + * Creates an instance of ResourceNotificationsResourceDeletedEventData class. + * + * @param resourceDetails the resourceDetails value to set. + * @param operationalDetails the operationalDetails value to set. + */ + @Generated + protected ResourceNotificationsResourceDeletedEventData(ResourceNotificationsResourceDeletedDetails resourceDetails, + ResourceNotificationsOperationalDetails operationalDetails) { + this.resourceDetails = resourceDetails; + this.operationalDetails = operationalDetails; + } + + /** + * Get the resourceDetails property: resourceInfo details for delete event. + * + * @return the resourceDetails value. + */ + @Generated + public ResourceNotificationsResourceDeletedDetails getResourceDetails() { + return this.resourceDetails; + } + + /** + * Get the operationalDetails property: details about operational info. + * + * @return the operationalDetails value. + */ + @Generated + public ResourceNotificationsOperationalDetails getOperationalDetails() { + return this.operationalDetails; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("resourceInfo", this.resourceDetails); + jsonWriter.writeJsonField("operationalInfo", this.operationalDetails); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ResourceNotificationsResourceDeletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ResourceNotificationsResourceDeletedEventData 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 ResourceNotificationsResourceDeletedEventData. + */ + @Generated + public static ResourceNotificationsResourceDeletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ResourceNotificationsResourceDeletedDetails resourceDetails = null; + ResourceNotificationsOperationalDetails operationalDetails = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceInfo".equals(fieldName)) { + resourceDetails = ResourceNotificationsResourceDeletedDetails.fromJson(reader); + } else if ("operationalInfo".equals(fieldName)) { + operationalDetails = ResourceNotificationsOperationalDetails.fromJson(reader); + } else { + reader.skipChildren(); + } + } + return new ResourceNotificationsResourceDeletedEventData(resourceDetails, operationalDetails); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsResourceManagementCreatedOrUpdatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsResourceManagementCreatedOrUpdatedEventData.java new file mode 100644 index 000000000000..300b759effcf --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsResourceManagementCreatedOrUpdatedEventData.java @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a + * Microsoft.ResourceNotifications.Resources.CreatedOrUpdated event. + */ +@Immutable +public final class ResourceNotificationsResourceManagementCreatedOrUpdatedEventData + extends ResourceNotificationsResourceUpdatedEventData { + /** + * Creates an instance of ResourceNotificationsResourceManagementCreatedOrUpdatedEventData class. + * + * @param resourceDetails the resourceDetails value to set. + * @param operationalDetails the operationalDetails value to set. + * @param apiVersion the apiVersion value to set. + */ + @Generated + private ResourceNotificationsResourceManagementCreatedOrUpdatedEventData( + ResourceNotificationsResourceUpdatedDetails resourceDetails, + ResourceNotificationsOperationalDetails operationalDetails, String apiVersion) { + super(resourceDetails, operationalDetails, apiVersion); + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("resourceInfo", getResourceDetails()); + jsonWriter.writeJsonField("operationalInfo", getOperationalDetails()); + jsonWriter.writeStringField("apiVersion", getApiVersion()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ResourceNotificationsResourceManagementCreatedOrUpdatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ResourceNotificationsResourceManagementCreatedOrUpdatedEventData 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 + * ResourceNotificationsResourceManagementCreatedOrUpdatedEventData. + */ + @Generated + public static ResourceNotificationsResourceManagementCreatedOrUpdatedEventData fromJson(JsonReader jsonReader) + throws IOException { + return jsonReader.readObject(reader -> { + ResourceNotificationsResourceUpdatedDetails resourceDetails = null; + ResourceNotificationsOperationalDetails operationalDetails = null; + String apiVersion = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceInfo".equals(fieldName)) { + resourceDetails = ResourceNotificationsResourceUpdatedDetails.fromJson(reader); + } else if ("operationalInfo".equals(fieldName)) { + operationalDetails = ResourceNotificationsOperationalDetails.fromJson(reader); + } else if ("apiVersion".equals(fieldName)) { + apiVersion = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new ResourceNotificationsResourceManagementCreatedOrUpdatedEventData(resourceDetails, + operationalDetails, apiVersion); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsResourceManagementDeletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsResourceManagementDeletedEventData.java new file mode 100644 index 000000000000..05ce0570ab74 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsResourceManagementDeletedEventData.java @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a + * Microsoft.ResourceNotifications.Resources.Deleted event. + */ +@Immutable +public final class ResourceNotificationsResourceManagementDeletedEventData + extends ResourceNotificationsResourceDeletedEventData { + /** + * Creates an instance of ResourceNotificationsResourceManagementDeletedEventData class. + * + * @param resourceDetails the resourceDetails value to set. + * @param operationalDetails the operationalDetails value to set. + */ + @Generated + private ResourceNotificationsResourceManagementDeletedEventData( + ResourceNotificationsResourceDeletedDetails resourceDetails, + ResourceNotificationsOperationalDetails operationalDetails) { + super(resourceDetails, operationalDetails); + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("resourceInfo", getResourceDetails()); + jsonWriter.writeJsonField("operationalInfo", getOperationalDetails()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ResourceNotificationsResourceManagementDeletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ResourceNotificationsResourceManagementDeletedEventData 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 ResourceNotificationsResourceManagementDeletedEventData. + */ + @Generated + public static ResourceNotificationsResourceManagementDeletedEventData fromJson(JsonReader jsonReader) + throws IOException { + return jsonReader.readObject(reader -> { + ResourceNotificationsResourceDeletedDetails resourceDetails = null; + ResourceNotificationsOperationalDetails operationalDetails = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceInfo".equals(fieldName)) { + resourceDetails = ResourceNotificationsResourceDeletedDetails.fromJson(reader); + } else if ("operationalInfo".equals(fieldName)) { + operationalDetails = ResourceNotificationsOperationalDetails.fromJson(reader); + } else { + reader.skipChildren(); + } + } + return new ResourceNotificationsResourceManagementDeletedEventData(resourceDetails, operationalDetails); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsResourceUpdatedDetails.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsResourceUpdatedDetails.java new file mode 100644 index 000000000000..bedfb1abcbdd --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsResourceUpdatedDetails.java @@ -0,0 +1,199 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.BinaryData; +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.Map; + +/** + * Describes the schema of the properties under resource info which are common + * across all ARN system topic events. + */ +@Immutable +public final class ResourceNotificationsResourceUpdatedDetails + implements JsonSerializable { + /* + * id of the resource for which the event is being emitted + */ + @Generated + private final String id; + + /* + * name of the resource for which the event is being emitted + */ + @Generated + private final String name; + + /* + * the type of the resource for which the event is being emitted + */ + @Generated + private final String type; + + /* + * the location of the resource for which the event is being emitted + */ + @Generated + private String location; + + /* + * the tags on the resource for which the event is being emitted + */ + @Generated + private Map tags; + + /* + * properties in the payload of the resource for which the event is being emitted + */ + @Generated + private Map properties; + + /** + * Creates an instance of ResourceNotificationsResourceUpdatedDetails class. + * + * @param id the id value to set. + * @param name the name value to set. + * @param type the type value to set. + */ + @Generated + private ResourceNotificationsResourceUpdatedDetails(String id, String name, String type) { + this.id = id; + this.name = name; + this.type = type; + } + + /** + * Get the id property: id of the resource for which the event is being emitted. + * + * @return the id value. + */ + @Generated + public String getId() { + return this.id; + } + + /** + * Get the name property: name of the resource for which the event is being emitted. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the type property: the type of the resource for which the event is being emitted. + * + * @return the type value. + */ + @Generated + public String getType() { + return this.type; + } + + /** + * Get the location property: the location of the resource for which the event is being emitted. + * + * @return the location value. + */ + @Generated + public String getLocation() { + return this.location; + } + + /** + * Get the tags property: the tags on the resource for which the event is being emitted. + * + * @return the tags value. + */ + @Generated + public Map getTags() { + return this.tags; + } + + /** + * Get the properties property: properties in the payload of the resource for which the event is being emitted. + * + * @return the properties value. + */ + @Generated + public Map getProperties() { + return this.properties; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("id", this.id); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("type", this.type); + jsonWriter.writeStringField("location", this.location); + jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); + jsonWriter.writeMapField("properties", this.properties, + (writer, element) -> writer.writeUntyped(element == null ? null : element.toObject(Object.class))); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ResourceNotificationsResourceUpdatedDetails from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ResourceNotificationsResourceUpdatedDetails 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 ResourceNotificationsResourceUpdatedDetails. + */ + @Generated + public static ResourceNotificationsResourceUpdatedDetails fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String id = null; + String name = null; + String type = null; + String location = null; + Map tags = null; + Map properties = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + id = reader.getString(); + } else if ("name".equals(fieldName)) { + name = reader.getString(); + } else if ("type".equals(fieldName)) { + type = reader.getString(); + } else if ("location".equals(fieldName)) { + location = reader.getString(); + } else if ("tags".equals(fieldName)) { + tags = reader.readMap(reader1 -> reader1.getString()); + } else if ("properties".equals(fieldName)) { + properties = reader.readMap(reader1 -> reader1 + .getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); + } else { + reader.skipChildren(); + } + } + ResourceNotificationsResourceUpdatedDetails deserializedResourceNotificationsResourceUpdatedDetails + = new ResourceNotificationsResourceUpdatedDetails(id, name, type); + deserializedResourceNotificationsResourceUpdatedDetails.location = location; + deserializedResourceNotificationsResourceUpdatedDetails.tags = tags; + deserializedResourceNotificationsResourceUpdatedDetails.properties = properties; + + return deserializedResourceNotificationsResourceUpdatedDetails; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsResourceUpdatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsResourceUpdatedEventData.java new file mode 100644 index 000000000000..b281485f8e50 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceNotificationsResourceUpdatedEventData.java @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Describes the schema of the common properties across all ARN system topic events. + */ +@Immutable +public class ResourceNotificationsResourceUpdatedEventData + implements JsonSerializable { + /* + * resourceInfo details for update event + */ + @Generated + private final ResourceNotificationsResourceUpdatedDetails resourceDetails; + + /* + * details about operational info + */ + @Generated + private final ResourceNotificationsOperationalDetails operationalDetails; + + /* + * api version of the resource properties bag + */ + @Generated + private final String apiVersion; + + /** + * Creates an instance of ResourceNotificationsResourceUpdatedEventData class. + * + * @param resourceDetails the resourceDetails value to set. + * @param operationalDetails the operationalDetails value to set. + * @param apiVersion the apiVersion value to set. + */ + @Generated + protected ResourceNotificationsResourceUpdatedEventData(ResourceNotificationsResourceUpdatedDetails resourceDetails, + ResourceNotificationsOperationalDetails operationalDetails, String apiVersion) { + this.resourceDetails = resourceDetails; + this.operationalDetails = operationalDetails; + this.apiVersion = apiVersion; + } + + /** + * Get the resourceDetails property: resourceInfo details for update event. + * + * @return the resourceDetails value. + */ + @Generated + public ResourceNotificationsResourceUpdatedDetails getResourceDetails() { + return this.resourceDetails; + } + + /** + * Get the operationalDetails property: details about operational info. + * + * @return the operationalDetails value. + */ + @Generated + public ResourceNotificationsOperationalDetails getOperationalDetails() { + return this.operationalDetails; + } + + /** + * Get the apiVersion property: api version of the resource properties bag. + * + * @return the apiVersion value. + */ + @Generated + public String getApiVersion() { + return this.apiVersion; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("resourceInfo", this.resourceDetails); + jsonWriter.writeJsonField("operationalInfo", this.operationalDetails); + jsonWriter.writeStringField("apiVersion", this.apiVersion); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ResourceNotificationsResourceUpdatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ResourceNotificationsResourceUpdatedEventData 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 ResourceNotificationsResourceUpdatedEventData. + */ + @Generated + public static ResourceNotificationsResourceUpdatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ResourceNotificationsResourceUpdatedDetails resourceDetails = null; + ResourceNotificationsOperationalDetails operationalDetails = null; + String apiVersion = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceInfo".equals(fieldName)) { + resourceDetails = ResourceNotificationsResourceUpdatedDetails.fromJson(reader); + } else if ("operationalInfo".equals(fieldName)) { + operationalDetails = ResourceNotificationsOperationalDetails.fromJson(reader); + } else if ("apiVersion".equals(fieldName)) { + apiVersion = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new ResourceNotificationsResourceUpdatedEventData(resourceDetails, operationalDetails, apiVersion); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceWriteCancelEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceWriteCancelEventData.java new file mode 100644 index 000000000000..cfc9cd3eb42a --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceWriteCancelEventData.java @@ -0,0 +1,301 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Resources.ResourceWriteCancel event. This is raised + * when a resource create or update operation is canceled. + */ +@Immutable +public final class ResourceWriteCancelEventData implements JsonSerializable { + /* + * The tenant ID of the resource. + */ + @Generated + private String tenantId; + + /* + * The subscription ID of the resource. + */ + @Generated + private String subscriptionId; + + /* + * The resource group of the resource. + */ + @Generated + private String resourceGroup; + + /* + * The resource provider performing the operation. + */ + @Generated + private String resourceProvider; + + /* + * The URI of the resource in the operation. + */ + @Generated + private String resourceUri; + + /* + * The operation that was performed. + */ + @Generated + private String operationName; + + /* + * The status of the operation. + */ + @Generated + private String status; + + /* + * The requested authorization for the operation. + */ + @Generated + private final ResourceAuthorization authorization; + + /* + * The properties of the claims. + */ + @Generated + private final Map claims; + + /* + * An operation ID used for troubleshooting. + */ + @Generated + private String correlationId; + + /* + * The details of the operation. + */ + @Generated + private final ResourceHttpRequest httpRequest; + + /** + * Creates an instance of ResourceWriteCancelEventData class. + * + * @param authorization the authorization value to set. + * @param claims the claims value to set. + * @param httpRequest the httpRequest value to set. + */ + @Generated + private ResourceWriteCancelEventData(ResourceAuthorization authorization, Map claims, + ResourceHttpRequest httpRequest) { + this.authorization = authorization; + this.claims = claims; + this.httpRequest = httpRequest; + } + + /** + * Get the tenantId property: The tenant ID of the resource. + * + * @return the tenantId value. + */ + @Generated + public String getTenantId() { + return this.tenantId; + } + + /** + * Get the subscriptionId property: The subscription ID of the resource. + * + * @return the subscriptionId value. + */ + @Generated + public String getSubscriptionId() { + return this.subscriptionId; + } + + /** + * Get the resourceGroup property: The resource group of the resource. + * + * @return the resourceGroup value. + */ + @Generated + public String getResourceGroup() { + return this.resourceGroup; + } + + /** + * Get the resourceProvider property: The resource provider performing the operation. + * + * @return the resourceProvider value. + */ + @Generated + public String getResourceProvider() { + return this.resourceProvider; + } + + /** + * Get the resourceUri property: The URI of the resource in the operation. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * Get the operationName property: The operation that was performed. + * + * @return the operationName value. + */ + @Generated + public String getOperationName() { + return this.operationName; + } + + /** + * Get the status property: The status of the operation. + * + * @return the status value. + */ + @Generated + public String getStatus() { + return this.status; + } + + /** + * Get the authorization property: The requested authorization for the operation. + * + * @return the authorization value. + */ + @Generated + public ResourceAuthorization getAuthorization() { + return this.authorization; + } + + /** + * Get the claims property: The properties of the claims. + * + * @return the claims value. + */ + @Generated + public Map getClaims() { + return this.claims; + } + + /** + * Get the correlationId property: An operation ID used for troubleshooting. + * + * @return the correlationId value. + */ + @Generated + public String getCorrelationId() { + return this.correlationId; + } + + /** + * Get the httpRequest property: The details of the operation. + * + * @return the httpRequest value. + */ + @Generated + public ResourceHttpRequest getHttpRequest() { + return this.httpRequest; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("authorization", this.authorization); + jsonWriter.writeMapField("claims", this.claims, (writer, element) -> writer.writeString(element)); + jsonWriter.writeJsonField("httpRequest", this.httpRequest); + jsonWriter.writeStringField("tenantId", this.tenantId); + jsonWriter.writeStringField("subscriptionId", this.subscriptionId); + jsonWriter.writeStringField("resourceGroup", this.resourceGroup); + jsonWriter.writeStringField("resourceProvider", this.resourceProvider); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + jsonWriter.writeStringField("operationName", this.operationName); + jsonWriter.writeStringField("status", this.status); + jsonWriter.writeStringField("correlationId", this.correlationId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ResourceWriteCancelEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ResourceWriteCancelEventData 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 ResourceWriteCancelEventData. + */ + @Generated + public static ResourceWriteCancelEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ResourceAuthorization authorization = null; + Map claims = null; + ResourceHttpRequest httpRequest = null; + String tenantId = null; + String subscriptionId = null; + String resourceGroup = null; + String resourceProvider = null; + String resourceUri = null; + String operationName = null; + String status = null; + String correlationId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("authorization".equals(fieldName)) { + authorization = ResourceAuthorization.fromJson(reader); + } else if ("claims".equals(fieldName)) { + claims = reader.readMap(reader1 -> reader1.getString()); + } else if ("httpRequest".equals(fieldName)) { + httpRequest = ResourceHttpRequest.fromJson(reader); + } else if ("tenantId".equals(fieldName)) { + tenantId = reader.getString(); + } else if ("subscriptionId".equals(fieldName)) { + subscriptionId = reader.getString(); + } else if ("resourceGroup".equals(fieldName)) { + resourceGroup = reader.getString(); + } else if ("resourceProvider".equals(fieldName)) { + resourceProvider = reader.getString(); + } else if ("resourceUri".equals(fieldName)) { + resourceUri = reader.getString(); + } else if ("operationName".equals(fieldName)) { + operationName = reader.getString(); + } else if ("status".equals(fieldName)) { + status = reader.getString(); + } else if ("correlationId".equals(fieldName)) { + correlationId = reader.getString(); + } else { + reader.skipChildren(); + } + } + ResourceWriteCancelEventData deserializedResourceWriteCancelEventData + = new ResourceWriteCancelEventData(authorization, claims, httpRequest); + deserializedResourceWriteCancelEventData.tenantId = tenantId; + deserializedResourceWriteCancelEventData.subscriptionId = subscriptionId; + deserializedResourceWriteCancelEventData.resourceGroup = resourceGroup; + deserializedResourceWriteCancelEventData.resourceProvider = resourceProvider; + deserializedResourceWriteCancelEventData.resourceUri = resourceUri; + deserializedResourceWriteCancelEventData.operationName = operationName; + deserializedResourceWriteCancelEventData.status = status; + deserializedResourceWriteCancelEventData.correlationId = correlationId; + + return deserializedResourceWriteCancelEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceWriteFailureEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceWriteFailureEventData.java new file mode 100644 index 000000000000..d9a1509c1ab2 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceWriteFailureEventData.java @@ -0,0 +1,301 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Resources.ResourceWriteFailure event. This is raised + * when a resource create or update operation fails. + */ +@Immutable +public final class ResourceWriteFailureEventData implements JsonSerializable { + /* + * The tenant ID of the resource. + */ + @Generated + private String tenantId; + + /* + * The subscription ID of the resource. + */ + @Generated + private String subscriptionId; + + /* + * The resource group of the resource. + */ + @Generated + private String resourceGroup; + + /* + * The resource provider performing the operation. + */ + @Generated + private String resourceProvider; + + /* + * The URI of the resource in the operation. + */ + @Generated + private String resourceUri; + + /* + * The operation that was performed. + */ + @Generated + private String operationName; + + /* + * The status of the operation. + */ + @Generated + private String status; + + /* + * The requested authorization for the operation. + */ + @Generated + private final ResourceAuthorization authorization; + + /* + * The properties of the claims. + */ + @Generated + private final Map claims; + + /* + * An operation ID used for troubleshooting. + */ + @Generated + private String correlationId; + + /* + * The details of the operation. + */ + @Generated + private final ResourceHttpRequest httpRequest; + + /** + * Creates an instance of ResourceWriteFailureEventData class. + * + * @param authorization the authorization value to set. + * @param claims the claims value to set. + * @param httpRequest the httpRequest value to set. + */ + @Generated + private ResourceWriteFailureEventData(ResourceAuthorization authorization, Map claims, + ResourceHttpRequest httpRequest) { + this.authorization = authorization; + this.claims = claims; + this.httpRequest = httpRequest; + } + + /** + * Get the tenantId property: The tenant ID of the resource. + * + * @return the tenantId value. + */ + @Generated + public String getTenantId() { + return this.tenantId; + } + + /** + * Get the subscriptionId property: The subscription ID of the resource. + * + * @return the subscriptionId value. + */ + @Generated + public String getSubscriptionId() { + return this.subscriptionId; + } + + /** + * Get the resourceGroup property: The resource group of the resource. + * + * @return the resourceGroup value. + */ + @Generated + public String getResourceGroup() { + return this.resourceGroup; + } + + /** + * Get the resourceProvider property: The resource provider performing the operation. + * + * @return the resourceProvider value. + */ + @Generated + public String getResourceProvider() { + return this.resourceProvider; + } + + /** + * Get the resourceUri property: The URI of the resource in the operation. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * Get the operationName property: The operation that was performed. + * + * @return the operationName value. + */ + @Generated + public String getOperationName() { + return this.operationName; + } + + /** + * Get the status property: The status of the operation. + * + * @return the status value. + */ + @Generated + public String getStatus() { + return this.status; + } + + /** + * Get the authorization property: The requested authorization for the operation. + * + * @return the authorization value. + */ + @Generated + public ResourceAuthorization getAuthorization() { + return this.authorization; + } + + /** + * Get the claims property: The properties of the claims. + * + * @return the claims value. + */ + @Generated + public Map getClaims() { + return this.claims; + } + + /** + * Get the correlationId property: An operation ID used for troubleshooting. + * + * @return the correlationId value. + */ + @Generated + public String getCorrelationId() { + return this.correlationId; + } + + /** + * Get the httpRequest property: The details of the operation. + * + * @return the httpRequest value. + */ + @Generated + public ResourceHttpRequest getHttpRequest() { + return this.httpRequest; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("authorization", this.authorization); + jsonWriter.writeMapField("claims", this.claims, (writer, element) -> writer.writeString(element)); + jsonWriter.writeJsonField("httpRequest", this.httpRequest); + jsonWriter.writeStringField("tenantId", this.tenantId); + jsonWriter.writeStringField("subscriptionId", this.subscriptionId); + jsonWriter.writeStringField("resourceGroup", this.resourceGroup); + jsonWriter.writeStringField("resourceProvider", this.resourceProvider); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + jsonWriter.writeStringField("operationName", this.operationName); + jsonWriter.writeStringField("status", this.status); + jsonWriter.writeStringField("correlationId", this.correlationId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ResourceWriteFailureEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ResourceWriteFailureEventData 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 ResourceWriteFailureEventData. + */ + @Generated + public static ResourceWriteFailureEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ResourceAuthorization authorization = null; + Map claims = null; + ResourceHttpRequest httpRequest = null; + String tenantId = null; + String subscriptionId = null; + String resourceGroup = null; + String resourceProvider = null; + String resourceUri = null; + String operationName = null; + String status = null; + String correlationId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("authorization".equals(fieldName)) { + authorization = ResourceAuthorization.fromJson(reader); + } else if ("claims".equals(fieldName)) { + claims = reader.readMap(reader1 -> reader1.getString()); + } else if ("httpRequest".equals(fieldName)) { + httpRequest = ResourceHttpRequest.fromJson(reader); + } else if ("tenantId".equals(fieldName)) { + tenantId = reader.getString(); + } else if ("subscriptionId".equals(fieldName)) { + subscriptionId = reader.getString(); + } else if ("resourceGroup".equals(fieldName)) { + resourceGroup = reader.getString(); + } else if ("resourceProvider".equals(fieldName)) { + resourceProvider = reader.getString(); + } else if ("resourceUri".equals(fieldName)) { + resourceUri = reader.getString(); + } else if ("operationName".equals(fieldName)) { + operationName = reader.getString(); + } else if ("status".equals(fieldName)) { + status = reader.getString(); + } else if ("correlationId".equals(fieldName)) { + correlationId = reader.getString(); + } else { + reader.skipChildren(); + } + } + ResourceWriteFailureEventData deserializedResourceWriteFailureEventData + = new ResourceWriteFailureEventData(authorization, claims, httpRequest); + deserializedResourceWriteFailureEventData.tenantId = tenantId; + deserializedResourceWriteFailureEventData.subscriptionId = subscriptionId; + deserializedResourceWriteFailureEventData.resourceGroup = resourceGroup; + deserializedResourceWriteFailureEventData.resourceProvider = resourceProvider; + deserializedResourceWriteFailureEventData.resourceUri = resourceUri; + deserializedResourceWriteFailureEventData.operationName = operationName; + deserializedResourceWriteFailureEventData.status = status; + deserializedResourceWriteFailureEventData.correlationId = correlationId; + + return deserializedResourceWriteFailureEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceWriteSuccessEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceWriteSuccessEventData.java new file mode 100644 index 000000000000..97210c226835 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ResourceWriteSuccessEventData.java @@ -0,0 +1,301 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; +import java.util.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Resources.ResourceWriteSuccess event. This is raised + * when a resource create or update operation succeeds. + */ +@Immutable +public final class ResourceWriteSuccessEventData implements JsonSerializable { + /* + * The tenant ID of the resource. + */ + @Generated + private String tenantId; + + /* + * The subscription ID of the resource. + */ + @Generated + private String subscriptionId; + + /* + * The resource group of the resource. + */ + @Generated + private String resourceGroup; + + /* + * The resource provider performing the operation. + */ + @Generated + private String resourceProvider; + + /* + * The URI of the resource in the operation. + */ + @Generated + private String resourceUri; + + /* + * The operation that was performed. + */ + @Generated + private String operationName; + + /* + * The status of the operation. + */ + @Generated + private String status; + + /* + * The requested authorization for the operation. + */ + @Generated + private final ResourceAuthorization authorization; + + /* + * The properties of the claims. + */ + @Generated + private final Map claims; + + /* + * An operation ID used for troubleshooting. + */ + @Generated + private String correlationId; + + /* + * The details of the operation. + */ + @Generated + private final ResourceHttpRequest httpRequest; + + /** + * Creates an instance of ResourceWriteSuccessEventData class. + * + * @param authorization the authorization value to set. + * @param claims the claims value to set. + * @param httpRequest the httpRequest value to set. + */ + @Generated + private ResourceWriteSuccessEventData(ResourceAuthorization authorization, Map claims, + ResourceHttpRequest httpRequest) { + this.authorization = authorization; + this.claims = claims; + this.httpRequest = httpRequest; + } + + /** + * Get the tenantId property: The tenant ID of the resource. + * + * @return the tenantId value. + */ + @Generated + public String getTenantId() { + return this.tenantId; + } + + /** + * Get the subscriptionId property: The subscription ID of the resource. + * + * @return the subscriptionId value. + */ + @Generated + public String getSubscriptionId() { + return this.subscriptionId; + } + + /** + * Get the resourceGroup property: The resource group of the resource. + * + * @return the resourceGroup value. + */ + @Generated + public String getResourceGroup() { + return this.resourceGroup; + } + + /** + * Get the resourceProvider property: The resource provider performing the operation. + * + * @return the resourceProvider value. + */ + @Generated + public String getResourceProvider() { + return this.resourceProvider; + } + + /** + * Get the resourceUri property: The URI of the resource in the operation. + * + * @return the resourceUri value. + */ + @Generated + public String getResourceUri() { + return this.resourceUri; + } + + /** + * Get the operationName property: The operation that was performed. + * + * @return the operationName value. + */ + @Generated + public String getOperationName() { + return this.operationName; + } + + /** + * Get the status property: The status of the operation. + * + * @return the status value. + */ + @Generated + public String getStatus() { + return this.status; + } + + /** + * Get the authorization property: The requested authorization for the operation. + * + * @return the authorization value. + */ + @Generated + public ResourceAuthorization getAuthorization() { + return this.authorization; + } + + /** + * Get the claims property: The properties of the claims. + * + * @return the claims value. + */ + @Generated + public Map getClaims() { + return this.claims; + } + + /** + * Get the correlationId property: An operation ID used for troubleshooting. + * + * @return the correlationId value. + */ + @Generated + public String getCorrelationId() { + return this.correlationId; + } + + /** + * Get the httpRequest property: The details of the operation. + * + * @return the httpRequest value. + */ + @Generated + public ResourceHttpRequest getHttpRequest() { + return this.httpRequest; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("authorization", this.authorization); + jsonWriter.writeMapField("claims", this.claims, (writer, element) -> writer.writeString(element)); + jsonWriter.writeJsonField("httpRequest", this.httpRequest); + jsonWriter.writeStringField("tenantId", this.tenantId); + jsonWriter.writeStringField("subscriptionId", this.subscriptionId); + jsonWriter.writeStringField("resourceGroup", this.resourceGroup); + jsonWriter.writeStringField("resourceProvider", this.resourceProvider); + jsonWriter.writeStringField("resourceUri", this.resourceUri); + jsonWriter.writeStringField("operationName", this.operationName); + jsonWriter.writeStringField("status", this.status); + jsonWriter.writeStringField("correlationId", this.correlationId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ResourceWriteSuccessEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ResourceWriteSuccessEventData 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 ResourceWriteSuccessEventData. + */ + @Generated + public static ResourceWriteSuccessEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ResourceAuthorization authorization = null; + Map claims = null; + ResourceHttpRequest httpRequest = null; + String tenantId = null; + String subscriptionId = null; + String resourceGroup = null; + String resourceProvider = null; + String resourceUri = null; + String operationName = null; + String status = null; + String correlationId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("authorization".equals(fieldName)) { + authorization = ResourceAuthorization.fromJson(reader); + } else if ("claims".equals(fieldName)) { + claims = reader.readMap(reader1 -> reader1.getString()); + } else if ("httpRequest".equals(fieldName)) { + httpRequest = ResourceHttpRequest.fromJson(reader); + } else if ("tenantId".equals(fieldName)) { + tenantId = reader.getString(); + } else if ("subscriptionId".equals(fieldName)) { + subscriptionId = reader.getString(); + } else if ("resourceGroup".equals(fieldName)) { + resourceGroup = reader.getString(); + } else if ("resourceProvider".equals(fieldName)) { + resourceProvider = reader.getString(); + } else if ("resourceUri".equals(fieldName)) { + resourceUri = reader.getString(); + } else if ("operationName".equals(fieldName)) { + operationName = reader.getString(); + } else if ("status".equals(fieldName)) { + status = reader.getString(); + } else if ("correlationId".equals(fieldName)) { + correlationId = reader.getString(); + } else { + reader.skipChildren(); + } + } + ResourceWriteSuccessEventData deserializedResourceWriteSuccessEventData + = new ResourceWriteSuccessEventData(authorization, claims, httpRequest); + deserializedResourceWriteSuccessEventData.tenantId = tenantId; + deserializedResourceWriteSuccessEventData.subscriptionId = subscriptionId; + deserializedResourceWriteSuccessEventData.resourceGroup = resourceGroup; + deserializedResourceWriteSuccessEventData.resourceProvider = resourceProvider; + deserializedResourceWriteSuccessEventData.resourceUri = resourceUri; + deserializedResourceWriteSuccessEventData.operationName = operationName; + deserializedResourceWriteSuccessEventData.status = status; + deserializedResourceWriteSuccessEventData.correlationId = correlationId; + + return deserializedResourceWriteSuccessEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ServiceBusActiveMessagesAvailablePeriodicNotificationsEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ServiceBusActiveMessagesAvailablePeriodicNotificationsEventData.java new file mode 100644 index 000000000000..2c4bc8d5323c --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ServiceBusActiveMessagesAvailablePeriodicNotificationsEventData.java @@ -0,0 +1,205 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a + * Microsoft.ServiceBus.ActiveMessagesAvailablePeriodicNotifications event. + */ +@Immutable +public final class ServiceBusActiveMessagesAvailablePeriodicNotificationsEventData + implements JsonSerializable { + /* + * The namespace name of the Microsoft.ServiceBus resource. + */ + @Generated + private final String namespaceName; + + /* + * The endpoint of the Microsoft.ServiceBus resource. + */ + @Generated + private final String requestUri; + + /* + * The entity type of the Microsoft.ServiceBus resource. Could be one of 'queue' or 'subscriber'. + */ + @Generated + private final String entityType; + + /* + * The name of the Microsoft.ServiceBus queue. If the entity type is of type 'subscriber', then this value will be + * null. + */ + @Generated + private final String queueName; + + /* + * The name of the Microsoft.ServiceBus topic. If the entity type is of type 'queue', then this value will be null. + */ + @Generated + private final String topicName; + + /* + * The name of the Microsoft.ServiceBus topic's subscription. If the entity type is of type 'queue', then this value + * will be null. + */ + @Generated + private final String subscriptionName; + + /** + * Creates an instance of ServiceBusActiveMessagesAvailablePeriodicNotificationsEventData class. + * + * @param namespaceName the namespaceName value to set. + * @param requestUri the requestUri value to set. + * @param entityType the entityType value to set. + * @param queueName the queueName value to set. + * @param topicName the topicName value to set. + * @param subscriptionName the subscriptionName value to set. + */ + @Generated + private ServiceBusActiveMessagesAvailablePeriodicNotificationsEventData(String namespaceName, String requestUri, + String entityType, String queueName, String topicName, String subscriptionName) { + this.namespaceName = namespaceName; + this.requestUri = requestUri; + this.entityType = entityType; + this.queueName = queueName; + this.topicName = topicName; + this.subscriptionName = subscriptionName; + } + + /** + * Get the namespaceName property: The namespace name of the Microsoft.ServiceBus resource. + * + * @return the namespaceName value. + */ + @Generated + public String getNamespaceName() { + return this.namespaceName; + } + + /** + * Get the requestUri property: The endpoint of the Microsoft.ServiceBus resource. + * + * @return the requestUri value. + */ + @Generated + public String getRequestUri() { + return this.requestUri; + } + + /** + * Get the entityType property: The entity type of the Microsoft.ServiceBus resource. Could be one of 'queue' or + * 'subscriber'. + * + * @return the entityType value. + */ + @Generated + public String getEntityType() { + return this.entityType; + } + + /** + * Get the queueName property: The name of the Microsoft.ServiceBus queue. If the entity type is of type + * 'subscriber', then this value will be null. + * + * @return the queueName value. + */ + @Generated + public String getQueueName() { + return this.queueName; + } + + /** + * Get the topicName property: The name of the Microsoft.ServiceBus topic. If the entity type is of type 'queue', + * then this value will be null. + * + * @return the topicName value. + */ + @Generated + public String getTopicName() { + return this.topicName; + } + + /** + * Get the subscriptionName property: The name of the Microsoft.ServiceBus topic's subscription. If the entity type + * is of type 'queue', then this value will be null. + * + * @return the subscriptionName value. + */ + @Generated + public String getSubscriptionName() { + return this.subscriptionName; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("namespaceName", this.namespaceName); + jsonWriter.writeStringField("requestUri", this.requestUri); + jsonWriter.writeStringField("entityType", this.entityType); + jsonWriter.writeStringField("queueName", this.queueName); + jsonWriter.writeStringField("topicName", this.topicName); + jsonWriter.writeStringField("subscriptionName", this.subscriptionName); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ServiceBusActiveMessagesAvailablePeriodicNotificationsEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ServiceBusActiveMessagesAvailablePeriodicNotificationsEventData 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 + * ServiceBusActiveMessagesAvailablePeriodicNotificationsEventData. + */ + @Generated + public static ServiceBusActiveMessagesAvailablePeriodicNotificationsEventData fromJson(JsonReader jsonReader) + throws IOException { + return jsonReader.readObject(reader -> { + String namespaceName = null; + String requestUri = null; + String entityType = null; + String queueName = null; + String topicName = null; + String subscriptionName = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("namespaceName".equals(fieldName)) { + namespaceName = reader.getString(); + } else if ("requestUri".equals(fieldName)) { + requestUri = reader.getString(); + } else if ("entityType".equals(fieldName)) { + entityType = reader.getString(); + } else if ("queueName".equals(fieldName)) { + queueName = reader.getString(); + } else if ("topicName".equals(fieldName)) { + topicName = reader.getString(); + } else if ("subscriptionName".equals(fieldName)) { + subscriptionName = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new ServiceBusActiveMessagesAvailablePeriodicNotificationsEventData(namespaceName, requestUri, + entityType, queueName, topicName, subscriptionName); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ServiceBusActiveMessagesAvailableWithNoListenersEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ServiceBusActiveMessagesAvailableWithNoListenersEventData.java new file mode 100644 index 000000000000..bcbd77e831a9 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ServiceBusActiveMessagesAvailableWithNoListenersEventData.java @@ -0,0 +1,205 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.ServiceBus.ActiveMessagesAvailableWithNoListeners + * event. + */ +@Immutable +public final class ServiceBusActiveMessagesAvailableWithNoListenersEventData + implements JsonSerializable { + /* + * The namespace name of the Microsoft.ServiceBus resource. + */ + @Generated + private final String namespaceName; + + /* + * The endpoint of the Microsoft.ServiceBus resource. + */ + @Generated + private final String requestUri; + + /* + * The entity type of the Microsoft.ServiceBus resource. Could be one of 'queue' or 'subscriber'. + */ + @Generated + private final String entityType; + + /* + * The name of the Microsoft.ServiceBus queue. If the entity type is of type 'subscriber', then this value will be + * null. + */ + @Generated + private final String queueName; + + /* + * The name of the Microsoft.ServiceBus topic. If the entity type is of type 'queue', then this value will be null. + */ + @Generated + private final String topicName; + + /* + * The name of the Microsoft.ServiceBus topic's subscription. If the entity type is of type 'queue', then this value + * will be null. + */ + @Generated + private final String subscriptionName; + + /** + * Creates an instance of ServiceBusActiveMessagesAvailableWithNoListenersEventData class. + * + * @param namespaceName the namespaceName value to set. + * @param requestUri the requestUri value to set. + * @param entityType the entityType value to set. + * @param queueName the queueName value to set. + * @param topicName the topicName value to set. + * @param subscriptionName the subscriptionName value to set. + */ + @Generated + private ServiceBusActiveMessagesAvailableWithNoListenersEventData(String namespaceName, String requestUri, + String entityType, String queueName, String topicName, String subscriptionName) { + this.namespaceName = namespaceName; + this.requestUri = requestUri; + this.entityType = entityType; + this.queueName = queueName; + this.topicName = topicName; + this.subscriptionName = subscriptionName; + } + + /** + * Get the namespaceName property: The namespace name of the Microsoft.ServiceBus resource. + * + * @return the namespaceName value. + */ + @Generated + public String getNamespaceName() { + return this.namespaceName; + } + + /** + * Get the requestUri property: The endpoint of the Microsoft.ServiceBus resource. + * + * @return the requestUri value. + */ + @Generated + public String getRequestUri() { + return this.requestUri; + } + + /** + * Get the entityType property: The entity type of the Microsoft.ServiceBus resource. Could be one of 'queue' or + * 'subscriber'. + * + * @return the entityType value. + */ + @Generated + public String getEntityType() { + return this.entityType; + } + + /** + * Get the queueName property: The name of the Microsoft.ServiceBus queue. If the entity type is of type + * 'subscriber', then this value will be null. + * + * @return the queueName value. + */ + @Generated + public String getQueueName() { + return this.queueName; + } + + /** + * Get the topicName property: The name of the Microsoft.ServiceBus topic. If the entity type is of type 'queue', + * then this value will be null. + * + * @return the topicName value. + */ + @Generated + public String getTopicName() { + return this.topicName; + } + + /** + * Get the subscriptionName property: The name of the Microsoft.ServiceBus topic's subscription. If the entity type + * is of type 'queue', then this value will be null. + * + * @return the subscriptionName value. + */ + @Generated + public String getSubscriptionName() { + return this.subscriptionName; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("namespaceName", this.namespaceName); + jsonWriter.writeStringField("requestUri", this.requestUri); + jsonWriter.writeStringField("entityType", this.entityType); + jsonWriter.writeStringField("queueName", this.queueName); + jsonWriter.writeStringField("topicName", this.topicName); + jsonWriter.writeStringField("subscriptionName", this.subscriptionName); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ServiceBusActiveMessagesAvailableWithNoListenersEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ServiceBusActiveMessagesAvailableWithNoListenersEventData 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 + * ServiceBusActiveMessagesAvailableWithNoListenersEventData. + */ + @Generated + public static ServiceBusActiveMessagesAvailableWithNoListenersEventData fromJson(JsonReader jsonReader) + throws IOException { + return jsonReader.readObject(reader -> { + String namespaceName = null; + String requestUri = null; + String entityType = null; + String queueName = null; + String topicName = null; + String subscriptionName = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("namespaceName".equals(fieldName)) { + namespaceName = reader.getString(); + } else if ("requestUri".equals(fieldName)) { + requestUri = reader.getString(); + } else if ("entityType".equals(fieldName)) { + entityType = reader.getString(); + } else if ("queueName".equals(fieldName)) { + queueName = reader.getString(); + } else if ("topicName".equals(fieldName)) { + topicName = reader.getString(); + } else if ("subscriptionName".equals(fieldName)) { + subscriptionName = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new ServiceBusActiveMessagesAvailableWithNoListenersEventData(namespaceName, requestUri, entityType, + queueName, topicName, subscriptionName); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ServiceBusDeadletterMessagesAvailablePeriodicNotificationsEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ServiceBusDeadletterMessagesAvailablePeriodicNotificationsEventData.java new file mode 100644 index 000000000000..064de03faa7b --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ServiceBusDeadletterMessagesAvailablePeriodicNotificationsEventData.java @@ -0,0 +1,205 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a + * Microsoft.ServiceBus.DeadletterMessagesAvailablePeriodicNotifications event. + */ +@Immutable +public final class ServiceBusDeadletterMessagesAvailablePeriodicNotificationsEventData + implements JsonSerializable { + /* + * The namespace name of the Microsoft.ServiceBus resource. + */ + @Generated + private final String namespaceName; + + /* + * The endpoint of the Microsoft.ServiceBus resource. + */ + @Generated + private final String requestUri; + + /* + * The entity type of the Microsoft.ServiceBus resource. Could be one of 'queue' or 'subscriber'. + */ + @Generated + private final String entityType; + + /* + * The name of the Microsoft.ServiceBus queue. If the entity type is of type 'subscriber', then this value will be + * null. + */ + @Generated + private final String queueName; + + /* + * The name of the Microsoft.ServiceBus topic. If the entity type is of type 'queue', then this value will be null. + */ + @Generated + private final String topicName; + + /* + * The name of the Microsoft.ServiceBus topic's subscription. If the entity type is of type 'queue', then this value + * will be null. + */ + @Generated + private final String subscriptionName; + + /** + * Creates an instance of ServiceBusDeadletterMessagesAvailablePeriodicNotificationsEventData class. + * + * @param namespaceName the namespaceName value to set. + * @param requestUri the requestUri value to set. + * @param entityType the entityType value to set. + * @param queueName the queueName value to set. + * @param topicName the topicName value to set. + * @param subscriptionName the subscriptionName value to set. + */ + @Generated + private ServiceBusDeadletterMessagesAvailablePeriodicNotificationsEventData(String namespaceName, String requestUri, + String entityType, String queueName, String topicName, String subscriptionName) { + this.namespaceName = namespaceName; + this.requestUri = requestUri; + this.entityType = entityType; + this.queueName = queueName; + this.topicName = topicName; + this.subscriptionName = subscriptionName; + } + + /** + * Get the namespaceName property: The namespace name of the Microsoft.ServiceBus resource. + * + * @return the namespaceName value. + */ + @Generated + public String getNamespaceName() { + return this.namespaceName; + } + + /** + * Get the requestUri property: The endpoint of the Microsoft.ServiceBus resource. + * + * @return the requestUri value. + */ + @Generated + public String getRequestUri() { + return this.requestUri; + } + + /** + * Get the entityType property: The entity type of the Microsoft.ServiceBus resource. Could be one of 'queue' or + * 'subscriber'. + * + * @return the entityType value. + */ + @Generated + public String getEntityType() { + return this.entityType; + } + + /** + * Get the queueName property: The name of the Microsoft.ServiceBus queue. If the entity type is of type + * 'subscriber', then this value will be null. + * + * @return the queueName value. + */ + @Generated + public String getQueueName() { + return this.queueName; + } + + /** + * Get the topicName property: The name of the Microsoft.ServiceBus topic. If the entity type is of type 'queue', + * then this value will be null. + * + * @return the topicName value. + */ + @Generated + public String getTopicName() { + return this.topicName; + } + + /** + * Get the subscriptionName property: The name of the Microsoft.ServiceBus topic's subscription. If the entity type + * is of type 'queue', then this value will be null. + * + * @return the subscriptionName value. + */ + @Generated + public String getSubscriptionName() { + return this.subscriptionName; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("namespaceName", this.namespaceName); + jsonWriter.writeStringField("requestUri", this.requestUri); + jsonWriter.writeStringField("entityType", this.entityType); + jsonWriter.writeStringField("queueName", this.queueName); + jsonWriter.writeStringField("topicName", this.topicName); + jsonWriter.writeStringField("subscriptionName", this.subscriptionName); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ServiceBusDeadletterMessagesAvailablePeriodicNotificationsEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ServiceBusDeadletterMessagesAvailablePeriodicNotificationsEventData 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 + * ServiceBusDeadletterMessagesAvailablePeriodicNotificationsEventData. + */ + @Generated + public static ServiceBusDeadletterMessagesAvailablePeriodicNotificationsEventData fromJson(JsonReader jsonReader) + throws IOException { + return jsonReader.readObject(reader -> { + String namespaceName = null; + String requestUri = null; + String entityType = null; + String queueName = null; + String topicName = null; + String subscriptionName = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("namespaceName".equals(fieldName)) { + namespaceName = reader.getString(); + } else if ("requestUri".equals(fieldName)) { + requestUri = reader.getString(); + } else if ("entityType".equals(fieldName)) { + entityType = reader.getString(); + } else if ("queueName".equals(fieldName)) { + queueName = reader.getString(); + } else if ("topicName".equals(fieldName)) { + topicName = reader.getString(); + } else if ("subscriptionName".equals(fieldName)) { + subscriptionName = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new ServiceBusDeadletterMessagesAvailablePeriodicNotificationsEventData(namespaceName, requestUri, + entityType, queueName, topicName, subscriptionName); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ServiceBusDeadletterMessagesAvailableWithNoListenersEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ServiceBusDeadletterMessagesAvailableWithNoListenersEventData.java new file mode 100644 index 000000000000..d8211beb533a --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/ServiceBusDeadletterMessagesAvailableWithNoListenersEventData.java @@ -0,0 +1,205 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a + * Microsoft.ServiceBus.DeadletterMessagesAvailableWithNoListeners event. + */ +@Immutable +public final class ServiceBusDeadletterMessagesAvailableWithNoListenersEventData + implements JsonSerializable { + /* + * The namespace name of the Microsoft.ServiceBus resource. + */ + @Generated + private final String namespaceName; + + /* + * The endpoint of the Microsoft.ServiceBus resource. + */ + @Generated + private final String requestUri; + + /* + * The entity type of the Microsoft.ServiceBus resource. Could be one of 'queue' or 'subscriber'. + */ + @Generated + private final String entityType; + + /* + * The name of the Microsoft.ServiceBus queue. If the entity type is of type 'subscriber', then this value will be + * null. + */ + @Generated + private final String queueName; + + /* + * The name of the Microsoft.ServiceBus topic. If the entity type is of type 'queue', then this value will be null. + */ + @Generated + private final String topicName; + + /* + * The name of the Microsoft.ServiceBus topic's subscription. If the entity type is of type 'queue', then this value + * will be null. + */ + @Generated + private final String subscriptionName; + + /** + * Creates an instance of ServiceBusDeadletterMessagesAvailableWithNoListenersEventData class. + * + * @param namespaceName the namespaceName value to set. + * @param requestUri the requestUri value to set. + * @param entityType the entityType value to set. + * @param queueName the queueName value to set. + * @param topicName the topicName value to set. + * @param subscriptionName the subscriptionName value to set. + */ + @Generated + private ServiceBusDeadletterMessagesAvailableWithNoListenersEventData(String namespaceName, String requestUri, + String entityType, String queueName, String topicName, String subscriptionName) { + this.namespaceName = namespaceName; + this.requestUri = requestUri; + this.entityType = entityType; + this.queueName = queueName; + this.topicName = topicName; + this.subscriptionName = subscriptionName; + } + + /** + * Get the namespaceName property: The namespace name of the Microsoft.ServiceBus resource. + * + * @return the namespaceName value. + */ + @Generated + public String getNamespaceName() { + return this.namespaceName; + } + + /** + * Get the requestUri property: The endpoint of the Microsoft.ServiceBus resource. + * + * @return the requestUri value. + */ + @Generated + public String getRequestUri() { + return this.requestUri; + } + + /** + * Get the entityType property: The entity type of the Microsoft.ServiceBus resource. Could be one of 'queue' or + * 'subscriber'. + * + * @return the entityType value. + */ + @Generated + public String getEntityType() { + return this.entityType; + } + + /** + * Get the queueName property: The name of the Microsoft.ServiceBus queue. If the entity type is of type + * 'subscriber', then this value will be null. + * + * @return the queueName value. + */ + @Generated + public String getQueueName() { + return this.queueName; + } + + /** + * Get the topicName property: The name of the Microsoft.ServiceBus topic. If the entity type is of type 'queue', + * then this value will be null. + * + * @return the topicName value. + */ + @Generated + public String getTopicName() { + return this.topicName; + } + + /** + * Get the subscriptionName property: The name of the Microsoft.ServiceBus topic's subscription. If the entity type + * is of type 'queue', then this value will be null. + * + * @return the subscriptionName value. + */ + @Generated + public String getSubscriptionName() { + return this.subscriptionName; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("namespaceName", this.namespaceName); + jsonWriter.writeStringField("requestUri", this.requestUri); + jsonWriter.writeStringField("entityType", this.entityType); + jsonWriter.writeStringField("queueName", this.queueName); + jsonWriter.writeStringField("topicName", this.topicName); + jsonWriter.writeStringField("subscriptionName", this.subscriptionName); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ServiceBusDeadletterMessagesAvailableWithNoListenersEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ServiceBusDeadletterMessagesAvailableWithNoListenersEventData 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 + * ServiceBusDeadletterMessagesAvailableWithNoListenersEventData. + */ + @Generated + public static ServiceBusDeadletterMessagesAvailableWithNoListenersEventData fromJson(JsonReader jsonReader) + throws IOException { + return jsonReader.readObject(reader -> { + String namespaceName = null; + String requestUri = null; + String entityType = null; + String queueName = null; + String topicName = null; + String subscriptionName = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("namespaceName".equals(fieldName)) { + namespaceName = reader.getString(); + } else if ("requestUri".equals(fieldName)) { + requestUri = reader.getString(); + } else if ("entityType".equals(fieldName)) { + entityType = reader.getString(); + } else if ("queueName".equals(fieldName)) { + queueName = reader.getString(); + } else if ("topicName".equals(fieldName)) { + topicName = reader.getString(); + } else if ("subscriptionName".equals(fieldName)) { + subscriptionName = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new ServiceBusDeadletterMessagesAvailableWithNoListenersEventData(namespaceName, requestUri, + entityType, queueName, topicName, subscriptionName); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/SignalRServiceClientConnectionConnectedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/SignalRServiceClientConnectionConnectedEventData.java new file mode 100644 index 000000000000..e18134ea3457 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/SignalRServiceClientConnectionConnectedEventData.java @@ -0,0 +1,158 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.SignalRService.ClientConnectionConnected event. + */ +@Immutable +public final class SignalRServiceClientConnectionConnectedEventData + implements JsonSerializable { + /* + * The time at which the event occurred. + */ + @Generated + private final OffsetDateTime timestamp; + + /* + * The hub of connected client connection. + */ + @Generated + private final String hubName; + + /* + * The connection Id of connected client connection. + */ + @Generated + private final String connectionId; + + /* + * The user Id of connected client connection. + */ + @Generated + private String userId; + + /** + * Creates an instance of SignalRServiceClientConnectionConnectedEventData class. + * + * @param timestamp the timestamp value to set. + * @param hubName the hubName value to set. + * @param connectionId the connectionId value to set. + */ + @Generated + private SignalRServiceClientConnectionConnectedEventData(OffsetDateTime timestamp, String hubName, + String connectionId) { + this.timestamp = timestamp; + this.hubName = hubName; + this.connectionId = connectionId; + } + + /** + * Get the timestamp property: The time at which the event occurred. + * + * @return the timestamp value. + */ + @Generated + public OffsetDateTime getTimestamp() { + return this.timestamp; + } + + /** + * Get the hubName property: The hub of connected client connection. + * + * @return the hubName value. + */ + @Generated + public String getHubName() { + return this.hubName; + } + + /** + * Get the connectionId property: The connection Id of connected client connection. + * + * @return the connectionId value. + */ + @Generated + public String getConnectionId() { + return this.connectionId; + } + + /** + * Get the userId property: The user Id of connected client connection. + * + * @return the userId value. + */ + @Generated + public String getUserId() { + return this.userId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("timestamp", + this.timestamp == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.timestamp)); + jsonWriter.writeStringField("hubName", this.hubName); + jsonWriter.writeStringField("connectionId", this.connectionId); + jsonWriter.writeStringField("userId", this.userId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SignalRServiceClientConnectionConnectedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SignalRServiceClientConnectionConnectedEventData 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 SignalRServiceClientConnectionConnectedEventData. + */ + @Generated + public static SignalRServiceClientConnectionConnectedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OffsetDateTime timestamp = null; + String hubName = null; + String connectionId = null; + String userId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("timestamp".equals(fieldName)) { + timestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("hubName".equals(fieldName)) { + hubName = reader.getString(); + } else if ("connectionId".equals(fieldName)) { + connectionId = reader.getString(); + } else if ("userId".equals(fieldName)) { + userId = reader.getString(); + } else { + reader.skipChildren(); + } + } + SignalRServiceClientConnectionConnectedEventData deserializedSignalRServiceClientConnectionConnectedEventData + = new SignalRServiceClientConnectionConnectedEventData(timestamp, hubName, connectionId); + deserializedSignalRServiceClientConnectionConnectedEventData.userId = userId; + + return deserializedSignalRServiceClientConnectionConnectedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/SignalRServiceClientConnectionDisconnectedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/SignalRServiceClientConnectionDisconnectedEventData.java new file mode 100644 index 000000000000..9a027da6ac0a --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/SignalRServiceClientConnectionDisconnectedEventData.java @@ -0,0 +1,180 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.SignalRService.ClientConnectionDisconnected event. + */ +@Immutable +public final class SignalRServiceClientConnectionDisconnectedEventData + implements JsonSerializable { + /* + * The time at which the event occurred. + */ + @Generated + private final OffsetDateTime timestamp; + + /* + * The hub of connected client connection. + */ + @Generated + private final String hubName; + + /* + * The connection Id of connected client connection. + */ + @Generated + private final String connectionId; + + /* + * The user Id of connected client connection. + */ + @Generated + private String userId; + + /* + * The message of error that cause the client connection disconnected. + */ + @Generated + private String errorMessage; + + /** + * Creates an instance of SignalRServiceClientConnectionDisconnectedEventData class. + * + * @param timestamp the timestamp value to set. + * @param hubName the hubName value to set. + * @param connectionId the connectionId value to set. + */ + @Generated + private SignalRServiceClientConnectionDisconnectedEventData(OffsetDateTime timestamp, String hubName, + String connectionId) { + this.timestamp = timestamp; + this.hubName = hubName; + this.connectionId = connectionId; + } + + /** + * Get the timestamp property: The time at which the event occurred. + * + * @return the timestamp value. + */ + @Generated + public OffsetDateTime getTimestamp() { + return this.timestamp; + } + + /** + * Get the hubName property: The hub of connected client connection. + * + * @return the hubName value. + */ + @Generated + public String getHubName() { + return this.hubName; + } + + /** + * Get the connectionId property: The connection Id of connected client connection. + * + * @return the connectionId value. + */ + @Generated + public String getConnectionId() { + return this.connectionId; + } + + /** + * Get the userId property: The user Id of connected client connection. + * + * @return the userId value. + */ + @Generated + public String getUserId() { + return this.userId; + } + + /** + * Get the errorMessage property: The message of error that cause the client connection disconnected. + * + * @return the errorMessage value. + */ + @Generated + public String getErrorMessage() { + return this.errorMessage; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("timestamp", + this.timestamp == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.timestamp)); + jsonWriter.writeStringField("hubName", this.hubName); + jsonWriter.writeStringField("connectionId", this.connectionId); + jsonWriter.writeStringField("userId", this.userId); + jsonWriter.writeStringField("errorMessage", this.errorMessage); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SignalRServiceClientConnectionDisconnectedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SignalRServiceClientConnectionDisconnectedEventData 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 SignalRServiceClientConnectionDisconnectedEventData. + */ + @Generated + public static SignalRServiceClientConnectionDisconnectedEventData fromJson(JsonReader jsonReader) + throws IOException { + return jsonReader.readObject(reader -> { + OffsetDateTime timestamp = null; + String hubName = null; + String connectionId = null; + String userId = null; + String errorMessage = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("timestamp".equals(fieldName)) { + timestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("hubName".equals(fieldName)) { + hubName = reader.getString(); + } else if ("connectionId".equals(fieldName)) { + connectionId = reader.getString(); + } else if ("userId".equals(fieldName)) { + userId = reader.getString(); + } else if ("errorMessage".equals(fieldName)) { + errorMessage = reader.getString(); + } else { + reader.skipChildren(); + } + } + SignalRServiceClientConnectionDisconnectedEventData deserializedSignalRServiceClientConnectionDisconnectedEventData + = new SignalRServiceClientConnectionDisconnectedEventData(timestamp, hubName, connectionId); + deserializedSignalRServiceClientConnectionDisconnectedEventData.userId = userId; + deserializedSignalRServiceClientConnectionDisconnectedEventData.errorMessage = errorMessage; + + return deserializedSignalRServiceClientConnectionDisconnectedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StampKind.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StampKind.java new file mode 100644 index 000000000000..ab479dd1b882 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StampKind.java @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Kind of environment where app service plan is. + */ +public final class StampKind extends ExpandableStringEnum { + /** + * App Service Plan is running on a public stamp. + */ + @Generated + public static final StampKind PUBLIC = fromString("Public"); + + /** + * App Service Plan is running on an App Service Environment V1. + */ + @Generated + public static final StampKind ASE_V1 = fromString("AseV1"); + + /** + * App Service Plan is running on an App Service Environment V2. + */ + @Generated + public static final StampKind ASE_V2 = fromString("AseV2"); + + /** + * Creates a new instance of StampKind value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public StampKind() { + } + + /** + * Creates or finds a StampKind from its string representation. + * + * @param name a name to look for. + * @return the corresponding StampKind. + */ + @Generated + public static StampKind fromString(String name) { + return fromString(name, StampKind.class); + } + + /** + * Gets known StampKind values. + * + * @return known StampKind values. + */ + @Generated + public static Collection values() { + return values(StampKind.class); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageAsyncOperationInitiatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageAsyncOperationInitiatedEventData.java new file mode 100644 index 000000000000..1de083c7f5df --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageAsyncOperationInitiatedEventData.java @@ -0,0 +1,291 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.BinaryData; +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.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Storage.AsyncOperationInitiated event. + */ +@Immutable +public final class StorageAsyncOperationInitiatedEventData + implements JsonSerializable { + /* + * The name of the API/operation that triggered this event. + */ + @Generated + private String api; + + /* + * A request id provided by the client of the storage API operation that triggered this event. + */ + @Generated + private String clientRequestId; + + /* + * The request id generated by the storage service for the storage API operation that triggered this event. + */ + @Generated + private String requestId; + + /* + * The content type of the blob. This is the same as what would be returned in the Content-Type header from the + * blob. + */ + @Generated + private String contentType; + + /* + * The size of the blob in bytes. This is the same as what would be returned in the Content-Length header from the + * blob. + */ + @Generated + private Long contentLength; + + /* + * The type of blob. + */ + @Generated + private String blobType; + + /* + * The path to the blob. + */ + @Generated + private String url; + + /* + * An opaque string value representing the logical sequence of events for any particular blob name. Users can use + * standard string comparison to understand the relative sequence of two events on the same blob name. + */ + @Generated + private String sequencer; + + /* + * The identity of the requester that triggered this event. + */ + @Generated + private String identity; + + /* + * For service use only. Diagnostic data occasionally included by the Azure Storage service. This property should be + * ignored by event consumers. + */ + @Generated + private final Map storageDiagnostics; + + /** + * Creates an instance of StorageAsyncOperationInitiatedEventData class. + * + * @param storageDiagnostics the storageDiagnostics value to set. + */ + @Generated + private StorageAsyncOperationInitiatedEventData(Map storageDiagnostics) { + this.storageDiagnostics = storageDiagnostics; + } + + /** + * Get the api property: The name of the API/operation that triggered this event. + * + * @return the api value. + */ + @Generated + public String getApi() { + return this.api; + } + + /** + * Get the clientRequestId property: A request id provided by the client of the storage API operation that triggered + * this event. + * + * @return the clientRequestId value. + */ + @Generated + public String getClientRequestId() { + return this.clientRequestId; + } + + /** + * Get the requestId property: The request id generated by the storage service for the storage API operation that + * triggered this event. + * + * @return the requestId value. + */ + @Generated + public String getRequestId() { + return this.requestId; + } + + /** + * Get the contentType property: The content type of the blob. This is the same as what would be returned in the + * Content-Type header from the blob. + * + * @return the contentType value. + */ + @Generated + public String getContentType() { + return this.contentType; + } + + /** + * Get the contentLength property: The size of the blob in bytes. This is the same as what would be returned in the + * Content-Length header from the blob. + * + * @return the contentLength value. + */ + @Generated + public Long getContentLength() { + return this.contentLength; + } + + /** + * Get the blobType property: The type of blob. + * + * @return the blobType value. + */ + @Generated + public String getBlobType() { + return this.blobType; + } + + /** + * Get the url property: The path to the blob. + * + * @return the url value. + */ + @Generated + public String getUrl() { + return this.url; + } + + /** + * Get the sequencer property: An opaque string value representing the logical sequence of events for any particular + * blob name. Users can use standard string comparison to understand the relative sequence of two events on the same + * blob name. + * + * @return the sequencer value. + */ + @Generated + public String getSequencer() { + return this.sequencer; + } + + /** + * Get the identity property: The identity of the requester that triggered this event. + * + * @return the identity value. + */ + @Generated + public String getIdentity() { + return this.identity; + } + + /** + * Get the storageDiagnostics property: For service use only. Diagnostic data occasionally included by the Azure + * Storage service. This property should be ignored by event consumers. + * + * @return the storageDiagnostics value. + */ + @Generated + public Map getStorageDiagnostics() { + return this.storageDiagnostics; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("storageDiagnostics", this.storageDiagnostics, + (writer, element) -> writer.writeUntyped(element == null ? null : element.toObject(Object.class))); + jsonWriter.writeStringField("api", this.api); + jsonWriter.writeStringField("clientRequestId", this.clientRequestId); + jsonWriter.writeStringField("requestId", this.requestId); + jsonWriter.writeStringField("contentType", this.contentType); + jsonWriter.writeNumberField("contentLength", this.contentLength); + jsonWriter.writeStringField("blobType", this.blobType); + jsonWriter.writeStringField("url", this.url); + jsonWriter.writeStringField("sequencer", this.sequencer); + jsonWriter.writeStringField("identity", this.identity); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of StorageAsyncOperationInitiatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of StorageAsyncOperationInitiatedEventData 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 StorageAsyncOperationInitiatedEventData. + */ + @Generated + public static StorageAsyncOperationInitiatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Map storageDiagnostics = null; + String api = null; + String clientRequestId = null; + String requestId = null; + String contentType = null; + Long contentLength = null; + String blobType = null; + String url = null; + String sequencer = null; + String identity = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("storageDiagnostics".equals(fieldName)) { + storageDiagnostics = reader.readMap(reader1 -> reader1 + .getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); + } else if ("api".equals(fieldName)) { + api = reader.getString(); + } else if ("clientRequestId".equals(fieldName)) { + clientRequestId = reader.getString(); + } else if ("requestId".equals(fieldName)) { + requestId = reader.getString(); + } else if ("contentType".equals(fieldName)) { + contentType = reader.getString(); + } else if ("contentLength".equals(fieldName)) { + contentLength = reader.getNullable(JsonReader::getLong); + } else if ("blobType".equals(fieldName)) { + blobType = reader.getString(); + } else if ("url".equals(fieldName)) { + url = reader.getString(); + } else if ("sequencer".equals(fieldName)) { + sequencer = reader.getString(); + } else if ("identity".equals(fieldName)) { + identity = reader.getString(); + } else { + reader.skipChildren(); + } + } + StorageAsyncOperationInitiatedEventData deserializedStorageAsyncOperationInitiatedEventData + = new StorageAsyncOperationInitiatedEventData(storageDiagnostics); + deserializedStorageAsyncOperationInitiatedEventData.api = api; + deserializedStorageAsyncOperationInitiatedEventData.clientRequestId = clientRequestId; + deserializedStorageAsyncOperationInitiatedEventData.requestId = requestId; + deserializedStorageAsyncOperationInitiatedEventData.contentType = contentType; + deserializedStorageAsyncOperationInitiatedEventData.contentLength = contentLength; + deserializedStorageAsyncOperationInitiatedEventData.blobType = blobType; + deserializedStorageAsyncOperationInitiatedEventData.url = url; + deserializedStorageAsyncOperationInitiatedEventData.sequencer = sequencer; + deserializedStorageAsyncOperationInitiatedEventData.identity = identity; + + return deserializedStorageAsyncOperationInitiatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageBlobAccessTier.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageBlobAccessTier.java new file mode 100644 index 000000000000..293adcca192d --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageBlobAccessTier.java @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The access tier of the blob. + */ +public final class StorageBlobAccessTier extends ExpandableStringEnum { + /** + * The blob is in access tier Hot. + */ + @Generated + public static final StorageBlobAccessTier HOT = fromString("Hot"); + + /** + * The blob is in access tier Cool. + */ + @Generated + public static final StorageBlobAccessTier COOL = fromString("Cool"); + + /** + * The blob is in access tier Cold. + */ + @Generated + public static final StorageBlobAccessTier COLD = fromString("Cold"); + + /** + * The blob is in access tier Archive. + */ + @Generated + public static final StorageBlobAccessTier ARCHIVE = fromString("Archive"); + + /** + * The blob is in access tier Default(Inferred). + */ + @Generated + public static final StorageBlobAccessTier DEFAULT = fromString("Default"); + + /** + * Creates a new instance of StorageBlobAccessTier value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public StorageBlobAccessTier() { + } + + /** + * Creates or finds a StorageBlobAccessTier from its string representation. + * + * @param name a name to look for. + * @return the corresponding StorageBlobAccessTier. + */ + @Generated + public static StorageBlobAccessTier fromString(String name) { + return fromString(name, StorageBlobAccessTier.class); + } + + /** + * Gets known StorageBlobAccessTier values. + * + * @return known StorageBlobAccessTier values. + */ + @Generated + public static Collection values() { + return values(StorageBlobAccessTier.class); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageBlobCreatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageBlobCreatedEventData.java new file mode 100644 index 000000000000..f96aa2e99bad --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageBlobCreatedEventData.java @@ -0,0 +1,354 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.BinaryData; +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.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Storage.BlobCreated event. + */ +@Immutable +public final class StorageBlobCreatedEventData implements JsonSerializable { + /* + * The name of the API/operation that triggered this event. + */ + @Generated + private String api; + + /* + * A request id provided by the client of the storage API operation that triggered this event. + */ + @Generated + private String clientRequestId; + + /* + * The request id generated by the storage service for the storage API operation that triggered this event. + */ + @Generated + private String requestId; + + /* + * The etag of the blob at the time this event was triggered. + */ + @Generated + private String eTag; + + /* + * The content type of the blob. This is the same as what would be returned in the Content-Type header from the + * blob. + */ + @Generated + private String contentType; + + /* + * The size of the blob in bytes. This is the same as what would be returned in the Content-Length header from the + * blob. + */ + @Generated + private Long contentLength; + + /* + * The offset of the blob in bytes. + */ + @Generated + private Long contentOffset; + + /* + * The type of blob. + */ + @Generated + private String blobType; + + /* + * The current tier of the blob. + */ + @Generated + private final StorageBlobAccessTier accessTier; + + /* + * The path to the blob. + */ + @Generated + private String url; + + /* + * An opaque string value representing the logical sequence of events for any particular blob name. Users can use + * standard string comparison to understand the relative sequence of two events on the same blob name. + */ + @Generated + private String sequencer; + + /* + * The identity of the requester that triggered this event. + */ + @Generated + private String identity; + + /* + * For service use only. Diagnostic data occasionally included by the Azure Storage service. This property should be + * ignored by event consumers. + */ + @Generated + private final Map storageDiagnostics; + + /** + * Creates an instance of StorageBlobCreatedEventData class. + * + * @param accessTier the accessTier value to set. + * @param storageDiagnostics the storageDiagnostics value to set. + */ + @Generated + private StorageBlobCreatedEventData(StorageBlobAccessTier accessTier, Map storageDiagnostics) { + this.accessTier = accessTier; + this.storageDiagnostics = storageDiagnostics; + } + + /** + * Get the api property: The name of the API/operation that triggered this event. + * + * @return the api value. + */ + @Generated + public String getApi() { + return this.api; + } + + /** + * Get the clientRequestId property: A request id provided by the client of the storage API operation that triggered + * this event. + * + * @return the clientRequestId value. + */ + @Generated + public String getClientRequestId() { + return this.clientRequestId; + } + + /** + * Get the requestId property: The request id generated by the storage service for the storage API operation that + * triggered this event. + * + * @return the requestId value. + */ + @Generated + public String getRequestId() { + return this.requestId; + } + + /** + * Get the eTag property: The etag of the blob at the time this event was triggered. + * + * @return the eTag value. + */ + @Generated + public String getETag() { + return this.eTag; + } + + /** + * Get the contentType property: The content type of the blob. This is the same as what would be returned in the + * Content-Type header from the blob. + * + * @return the contentType value. + */ + @Generated + public String getContentType() { + return this.contentType; + } + + /** + * Get the contentLength property: The size of the blob in bytes. This is the same as what would be returned in the + * Content-Length header from the blob. + * + * @return the contentLength value. + */ + @Generated + public Long getContentLength() { + return this.contentLength; + } + + /** + * Get the contentOffset property: The offset of the blob in bytes. + * + * @return the contentOffset value. + */ + @Generated + public Long getContentOffset() { + return this.contentOffset; + } + + /** + * Get the blobType property: The type of blob. + * + * @return the blobType value. + */ + @Generated + public String getBlobType() { + return this.blobType; + } + + /** + * Get the accessTier property: The current tier of the blob. + * + * @return the accessTier value. + */ + @Generated + public StorageBlobAccessTier getAccessTier() { + return this.accessTier; + } + + /** + * Get the url property: The path to the blob. + * + * @return the url value. + */ + @Generated + public String getUrl() { + return this.url; + } + + /** + * Get the sequencer property: An opaque string value representing the logical sequence of events for any particular + * blob name. Users can use standard string comparison to understand the relative sequence of two events on the same + * blob name. + * + * @return the sequencer value. + */ + @Generated + public String getSequencer() { + return this.sequencer; + } + + /** + * Get the identity property: The identity of the requester that triggered this event. + * + * @return the identity value. + */ + @Generated + public String getIdentity() { + return this.identity; + } + + /** + * Get the storageDiagnostics property: For service use only. Diagnostic data occasionally included by the Azure + * Storage service. This property should be ignored by event consumers. + * + * @return the storageDiagnostics value. + */ + @Generated + public Map getStorageDiagnostics() { + return this.storageDiagnostics; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("accessTier", this.accessTier == null ? null : this.accessTier.toString()); + jsonWriter.writeMapField("storageDiagnostics", this.storageDiagnostics, + (writer, element) -> writer.writeUntyped(element == null ? null : element.toObject(Object.class))); + jsonWriter.writeStringField("api", this.api); + jsonWriter.writeStringField("clientRequestId", this.clientRequestId); + jsonWriter.writeStringField("requestId", this.requestId); + jsonWriter.writeStringField("eTag", this.eTag); + jsonWriter.writeStringField("contentType", this.contentType); + jsonWriter.writeNumberField("contentLength", this.contentLength); + jsonWriter.writeNumberField("contentOffset", this.contentOffset); + jsonWriter.writeStringField("blobType", this.blobType); + jsonWriter.writeStringField("url", this.url); + jsonWriter.writeStringField("sequencer", this.sequencer); + jsonWriter.writeStringField("identity", this.identity); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of StorageBlobCreatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of StorageBlobCreatedEventData 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 StorageBlobCreatedEventData. + */ + @Generated + public static StorageBlobCreatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + StorageBlobAccessTier accessTier = null; + Map storageDiagnostics = null; + String api = null; + String clientRequestId = null; + String requestId = null; + String eTag = null; + String contentType = null; + Long contentLength = null; + Long contentOffset = null; + String blobType = null; + String url = null; + String sequencer = null; + String identity = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("accessTier".equals(fieldName)) { + accessTier = StorageBlobAccessTier.fromString(reader.getString()); + } else if ("storageDiagnostics".equals(fieldName)) { + storageDiagnostics = reader.readMap(reader1 -> reader1 + .getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); + } else if ("api".equals(fieldName)) { + api = reader.getString(); + } else if ("clientRequestId".equals(fieldName)) { + clientRequestId = reader.getString(); + } else if ("requestId".equals(fieldName)) { + requestId = reader.getString(); + } else if ("eTag".equals(fieldName)) { + eTag = reader.getString(); + } else if ("contentType".equals(fieldName)) { + contentType = reader.getString(); + } else if ("contentLength".equals(fieldName)) { + contentLength = reader.getNullable(JsonReader::getLong); + } else if ("contentOffset".equals(fieldName)) { + contentOffset = reader.getNullable(JsonReader::getLong); + } else if ("blobType".equals(fieldName)) { + blobType = reader.getString(); + } else if ("url".equals(fieldName)) { + url = reader.getString(); + } else if ("sequencer".equals(fieldName)) { + sequencer = reader.getString(); + } else if ("identity".equals(fieldName)) { + identity = reader.getString(); + } else { + reader.skipChildren(); + } + } + StorageBlobCreatedEventData deserializedStorageBlobCreatedEventData + = new StorageBlobCreatedEventData(accessTier, storageDiagnostics); + deserializedStorageBlobCreatedEventData.api = api; + deserializedStorageBlobCreatedEventData.clientRequestId = clientRequestId; + deserializedStorageBlobCreatedEventData.requestId = requestId; + deserializedStorageBlobCreatedEventData.eTag = eTag; + deserializedStorageBlobCreatedEventData.contentType = contentType; + deserializedStorageBlobCreatedEventData.contentLength = contentLength; + deserializedStorageBlobCreatedEventData.contentOffset = contentOffset; + deserializedStorageBlobCreatedEventData.blobType = blobType; + deserializedStorageBlobCreatedEventData.url = url; + deserializedStorageBlobCreatedEventData.sequencer = sequencer; + deserializedStorageBlobCreatedEventData.identity = identity; + + return deserializedStorageBlobCreatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageBlobDeletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageBlobDeletedEventData.java new file mode 100644 index 000000000000..4a9e40ba5458 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageBlobDeletedEventData.java @@ -0,0 +1,267 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.BinaryData; +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.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Storage.BlobDeleted event. + */ +@Immutable +public final class StorageBlobDeletedEventData implements JsonSerializable { + /* + * The name of the API/operation that triggered this event. + */ + @Generated + private String api; + + /* + * A request id provided by the client of the storage API operation that triggered this event. + */ + @Generated + private String clientRequestId; + + /* + * The request id generated by the storage service for the storage API operation that triggered this event. + */ + @Generated + private String requestId; + + /* + * The content type of the blob. This is the same as what would be returned in the Content-Type header from the + * blob. + */ + @Generated + private String contentType; + + /* + * The type of blob. + */ + @Generated + private String blobType; + + /* + * The path to the blob. + */ + @Generated + private String url; + + /* + * An opaque string value representing the logical sequence of events for any particular blob name. Users can use + * standard string comparison to understand the relative sequence of two events on the same blob name. + */ + @Generated + private String sequencer; + + /* + * The identity of the requester that triggered this event. + */ + @Generated + private String identity; + + /* + * For service use only. Diagnostic data occasionally included by the Azure Storage service. This property should be + * ignored by event consumers. + */ + @Generated + private final Map storageDiagnostics; + + /** + * Creates an instance of StorageBlobDeletedEventData class. + * + * @param storageDiagnostics the storageDiagnostics value to set. + */ + @Generated + private StorageBlobDeletedEventData(Map storageDiagnostics) { + this.storageDiagnostics = storageDiagnostics; + } + + /** + * Get the api property: The name of the API/operation that triggered this event. + * + * @return the api value. + */ + @Generated + public String getApi() { + return this.api; + } + + /** + * Get the clientRequestId property: A request id provided by the client of the storage API operation that triggered + * this event. + * + * @return the clientRequestId value. + */ + @Generated + public String getClientRequestId() { + return this.clientRequestId; + } + + /** + * Get the requestId property: The request id generated by the storage service for the storage API operation that + * triggered this event. + * + * @return the requestId value. + */ + @Generated + public String getRequestId() { + return this.requestId; + } + + /** + * Get the contentType property: The content type of the blob. This is the same as what would be returned in the + * Content-Type header from the blob. + * + * @return the contentType value. + */ + @Generated + public String getContentType() { + return this.contentType; + } + + /** + * Get the blobType property: The type of blob. + * + * @return the blobType value. + */ + @Generated + public String getBlobType() { + return this.blobType; + } + + /** + * Get the url property: The path to the blob. + * + * @return the url value. + */ + @Generated + public String getUrl() { + return this.url; + } + + /** + * Get the sequencer property: An opaque string value representing the logical sequence of events for any particular + * blob name. Users can use standard string comparison to understand the relative sequence of two events on the same + * blob name. + * + * @return the sequencer value. + */ + @Generated + public String getSequencer() { + return this.sequencer; + } + + /** + * Get the identity property: The identity of the requester that triggered this event. + * + * @return the identity value. + */ + @Generated + public String getIdentity() { + return this.identity; + } + + /** + * Get the storageDiagnostics property: For service use only. Diagnostic data occasionally included by the Azure + * Storage service. This property should be ignored by event consumers. + * + * @return the storageDiagnostics value. + */ + @Generated + public Map getStorageDiagnostics() { + return this.storageDiagnostics; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("storageDiagnostics", this.storageDiagnostics, + (writer, element) -> writer.writeUntyped(element == null ? null : element.toObject(Object.class))); + jsonWriter.writeStringField("api", this.api); + jsonWriter.writeStringField("clientRequestId", this.clientRequestId); + jsonWriter.writeStringField("requestId", this.requestId); + jsonWriter.writeStringField("contentType", this.contentType); + jsonWriter.writeStringField("blobType", this.blobType); + jsonWriter.writeStringField("url", this.url); + jsonWriter.writeStringField("sequencer", this.sequencer); + jsonWriter.writeStringField("identity", this.identity); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of StorageBlobDeletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of StorageBlobDeletedEventData 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 StorageBlobDeletedEventData. + */ + @Generated + public static StorageBlobDeletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Map storageDiagnostics = null; + String api = null; + String clientRequestId = null; + String requestId = null; + String contentType = null; + String blobType = null; + String url = null; + String sequencer = null; + String identity = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("storageDiagnostics".equals(fieldName)) { + storageDiagnostics = reader.readMap(reader1 -> reader1 + .getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); + } else if ("api".equals(fieldName)) { + api = reader.getString(); + } else if ("clientRequestId".equals(fieldName)) { + clientRequestId = reader.getString(); + } else if ("requestId".equals(fieldName)) { + requestId = reader.getString(); + } else if ("contentType".equals(fieldName)) { + contentType = reader.getString(); + } else if ("blobType".equals(fieldName)) { + blobType = reader.getString(); + } else if ("url".equals(fieldName)) { + url = reader.getString(); + } else if ("sequencer".equals(fieldName)) { + sequencer = reader.getString(); + } else if ("identity".equals(fieldName)) { + identity = reader.getString(); + } else { + reader.skipChildren(); + } + } + StorageBlobDeletedEventData deserializedStorageBlobDeletedEventData + = new StorageBlobDeletedEventData(storageDiagnostics); + deserializedStorageBlobDeletedEventData.api = api; + deserializedStorageBlobDeletedEventData.clientRequestId = clientRequestId; + deserializedStorageBlobDeletedEventData.requestId = requestId; + deserializedStorageBlobDeletedEventData.contentType = contentType; + deserializedStorageBlobDeletedEventData.blobType = blobType; + deserializedStorageBlobDeletedEventData.url = url; + deserializedStorageBlobDeletedEventData.sequencer = sequencer; + deserializedStorageBlobDeletedEventData.identity = identity; + + return deserializedStorageBlobDeletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageBlobInventoryPolicyCompletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageBlobInventoryPolicyCompletedEventData.java new file mode 100644 index 000000000000..625bc38f803e --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageBlobInventoryPolicyCompletedEventData.java @@ -0,0 +1,220 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for an Microsoft.Storage.BlobInventoryPolicyCompleted event. + */ +@Immutable +public final class StorageBlobInventoryPolicyCompletedEventData + implements JsonSerializable { + /* + * The time at which inventory policy was scheduled. + */ + @Generated + private final OffsetDateTime scheduleDateTime; + + /* + * The account name for which inventory policy is registered. + */ + @Generated + private String accountName; + + /* + * The rule name for inventory policy. + */ + @Generated + private String ruleName; + + /* + * The status of inventory run, it can be Succeeded/PartiallySucceeded/Failed. + */ + @Generated + private String policyRunStatus; + + /* + * The status message for inventory run. + */ + @Generated + private String policyRunStatusMessage; + + /* + * The policy run id for inventory run. + */ + @Generated + private String policyRunId; + + /* + * The blob URL for manifest file for inventory run. + */ + @Generated + private String manifestBlobUrl; + + /** + * Creates an instance of StorageBlobInventoryPolicyCompletedEventData class. + * + * @param scheduleDateTime the scheduleDateTime value to set. + */ + @Generated + private StorageBlobInventoryPolicyCompletedEventData(OffsetDateTime scheduleDateTime) { + this.scheduleDateTime = scheduleDateTime; + } + + /** + * Get the scheduleDateTime property: The time at which inventory policy was scheduled. + * + * @return the scheduleDateTime value. + */ + @Generated + public OffsetDateTime getScheduleDateTime() { + return this.scheduleDateTime; + } + + /** + * Get the accountName property: The account name for which inventory policy is registered. + * + * @return the accountName value. + */ + @Generated + public String getAccountName() { + return this.accountName; + } + + /** + * Get the ruleName property: The rule name for inventory policy. + * + * @return the ruleName value. + */ + @Generated + public String getRuleName() { + return this.ruleName; + } + + /** + * Get the policyRunStatus property: The status of inventory run, it can be Succeeded/PartiallySucceeded/Failed. + * + * @return the policyRunStatus value. + */ + @Generated + public String getPolicyRunStatus() { + return this.policyRunStatus; + } + + /** + * Get the policyRunStatusMessage property: The status message for inventory run. + * + * @return the policyRunStatusMessage value. + */ + @Generated + public String getPolicyRunStatusMessage() { + return this.policyRunStatusMessage; + } + + /** + * Get the policyRunId property: The policy run id for inventory run. + * + * @return the policyRunId value. + */ + @Generated + public String getPolicyRunId() { + return this.policyRunId; + } + + /** + * Get the manifestBlobUrl property: The blob URL for manifest file for inventory run. + * + * @return the manifestBlobUrl value. + */ + @Generated + public String getManifestBlobUrl() { + return this.manifestBlobUrl; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("scheduleDateTime", + this.scheduleDateTime == null + ? null + : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.scheduleDateTime)); + jsonWriter.writeStringField("accountName", this.accountName); + jsonWriter.writeStringField("ruleName", this.ruleName); + jsonWriter.writeStringField("policyRunStatus", this.policyRunStatus); + jsonWriter.writeStringField("policyRunStatusMessage", this.policyRunStatusMessage); + jsonWriter.writeStringField("policyRunId", this.policyRunId); + jsonWriter.writeStringField("manifestBlobUrl", this.manifestBlobUrl); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of StorageBlobInventoryPolicyCompletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of StorageBlobInventoryPolicyCompletedEventData 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 StorageBlobInventoryPolicyCompletedEventData. + */ + @Generated + public static StorageBlobInventoryPolicyCompletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OffsetDateTime scheduleDateTime = null; + String accountName = null; + String ruleName = null; + String policyRunStatus = null; + String policyRunStatusMessage = null; + String policyRunId = null; + String manifestBlobUrl = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("scheduleDateTime".equals(fieldName)) { + scheduleDateTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("accountName".equals(fieldName)) { + accountName = reader.getString(); + } else if ("ruleName".equals(fieldName)) { + ruleName = reader.getString(); + } else if ("policyRunStatus".equals(fieldName)) { + policyRunStatus = reader.getString(); + } else if ("policyRunStatusMessage".equals(fieldName)) { + policyRunStatusMessage = reader.getString(); + } else if ("policyRunId".equals(fieldName)) { + policyRunId = reader.getString(); + } else if ("manifestBlobUrl".equals(fieldName)) { + manifestBlobUrl = reader.getString(); + } else { + reader.skipChildren(); + } + } + StorageBlobInventoryPolicyCompletedEventData deserializedStorageBlobInventoryPolicyCompletedEventData + = new StorageBlobInventoryPolicyCompletedEventData(scheduleDateTime); + deserializedStorageBlobInventoryPolicyCompletedEventData.accountName = accountName; + deserializedStorageBlobInventoryPolicyCompletedEventData.ruleName = ruleName; + deserializedStorageBlobInventoryPolicyCompletedEventData.policyRunStatus = policyRunStatus; + deserializedStorageBlobInventoryPolicyCompletedEventData.policyRunStatusMessage = policyRunStatusMessage; + deserializedStorageBlobInventoryPolicyCompletedEventData.policyRunId = policyRunId; + deserializedStorageBlobInventoryPolicyCompletedEventData.manifestBlobUrl = manifestBlobUrl; + + return deserializedStorageBlobInventoryPolicyCompletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageBlobRenamedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageBlobRenamedEventData.java new file mode 100644 index 000000000000..2684f0b02d1c --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageBlobRenamedEventData.java @@ -0,0 +1,244 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.BinaryData; +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.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Storage.BlobRenamed event. + */ +@Immutable +public final class StorageBlobRenamedEventData implements JsonSerializable { + /* + * The name of the API/operation that triggered this event. + */ + @Generated + private String api; + + /* + * A request id provided by the client of the storage API operation that triggered this event. + */ + @Generated + private String clientRequestId; + + /* + * The request id generated by the storage service for the storage API operation that triggered this event. + */ + @Generated + private String requestId; + + /* + * The path to the blob that was renamed. + */ + @Generated + private String sourceUrl; + + /* + * The new path to the blob after the rename operation. + */ + @Generated + private String destinationUrl; + + /* + * An opaque string value representing the logical sequence of events for any particular blob name. Users can use + * standard string comparison to understand the relative sequence of two events on the same blob name. + */ + @Generated + private String sequencer; + + /* + * The identity of the requester that triggered this event. + */ + @Generated + private String identity; + + /* + * For service use only. Diagnostic data occasionally included by the Azure Storage service. This property should be + * ignored by event consumers. + */ + @Generated + private final Map storageDiagnostics; + + /** + * Creates an instance of StorageBlobRenamedEventData class. + * + * @param storageDiagnostics the storageDiagnostics value to set. + */ + @Generated + private StorageBlobRenamedEventData(Map storageDiagnostics) { + this.storageDiagnostics = storageDiagnostics; + } + + /** + * Get the api property: The name of the API/operation that triggered this event. + * + * @return the api value. + */ + @Generated + public String getApi() { + return this.api; + } + + /** + * Get the clientRequestId property: A request id provided by the client of the storage API operation that triggered + * this event. + * + * @return the clientRequestId value. + */ + @Generated + public String getClientRequestId() { + return this.clientRequestId; + } + + /** + * Get the requestId property: The request id generated by the storage service for the storage API operation that + * triggered this event. + * + * @return the requestId value. + */ + @Generated + public String getRequestId() { + return this.requestId; + } + + /** + * Get the sourceUrl property: The path to the blob that was renamed. + * + * @return the sourceUrl value. + */ + @Generated + public String getSourceUrl() { + return this.sourceUrl; + } + + /** + * Get the destinationUrl property: The new path to the blob after the rename operation. + * + * @return the destinationUrl value. + */ + @Generated + public String getDestinationUrl() { + return this.destinationUrl; + } + + /** + * Get the sequencer property: An opaque string value representing the logical sequence of events for any particular + * blob name. Users can use standard string comparison to understand the relative sequence of two events on the same + * blob name. + * + * @return the sequencer value. + */ + @Generated + public String getSequencer() { + return this.sequencer; + } + + /** + * Get the identity property: The identity of the requester that triggered this event. + * + * @return the identity value. + */ + @Generated + public String getIdentity() { + return this.identity; + } + + /** + * Get the storageDiagnostics property: For service use only. Diagnostic data occasionally included by the Azure + * Storage service. This property should be ignored by event consumers. + * + * @return the storageDiagnostics value. + */ + @Generated + public Map getStorageDiagnostics() { + return this.storageDiagnostics; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("storageDiagnostics", this.storageDiagnostics, + (writer, element) -> writer.writeUntyped(element == null ? null : element.toObject(Object.class))); + jsonWriter.writeStringField("api", this.api); + jsonWriter.writeStringField("clientRequestId", this.clientRequestId); + jsonWriter.writeStringField("requestId", this.requestId); + jsonWriter.writeStringField("sourceUrl", this.sourceUrl); + jsonWriter.writeStringField("destinationUrl", this.destinationUrl); + jsonWriter.writeStringField("sequencer", this.sequencer); + jsonWriter.writeStringField("identity", this.identity); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of StorageBlobRenamedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of StorageBlobRenamedEventData 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 StorageBlobRenamedEventData. + */ + @Generated + public static StorageBlobRenamedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Map storageDiagnostics = null; + String api = null; + String clientRequestId = null; + String requestId = null; + String sourceUrl = null; + String destinationUrl = null; + String sequencer = null; + String identity = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("storageDiagnostics".equals(fieldName)) { + storageDiagnostics = reader.readMap(reader1 -> reader1 + .getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); + } else if ("api".equals(fieldName)) { + api = reader.getString(); + } else if ("clientRequestId".equals(fieldName)) { + clientRequestId = reader.getString(); + } else if ("requestId".equals(fieldName)) { + requestId = reader.getString(); + } else if ("sourceUrl".equals(fieldName)) { + sourceUrl = reader.getString(); + } else if ("destinationUrl".equals(fieldName)) { + destinationUrl = reader.getString(); + } else if ("sequencer".equals(fieldName)) { + sequencer = reader.getString(); + } else if ("identity".equals(fieldName)) { + identity = reader.getString(); + } else { + reader.skipChildren(); + } + } + StorageBlobRenamedEventData deserializedStorageBlobRenamedEventData + = new StorageBlobRenamedEventData(storageDiagnostics); + deserializedStorageBlobRenamedEventData.api = api; + deserializedStorageBlobRenamedEventData.clientRequestId = clientRequestId; + deserializedStorageBlobRenamedEventData.requestId = requestId; + deserializedStorageBlobRenamedEventData.sourceUrl = sourceUrl; + deserializedStorageBlobRenamedEventData.destinationUrl = destinationUrl; + deserializedStorageBlobRenamedEventData.sequencer = sequencer; + deserializedStorageBlobRenamedEventData.identity = identity; + + return deserializedStorageBlobRenamedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageBlobTierChangedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageBlobTierChangedEventData.java new file mode 100644 index 000000000000..c4ead0c969dc --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageBlobTierChangedEventData.java @@ -0,0 +1,335 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.BinaryData; +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.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Storage.BlobTierChanged event. + */ +@Immutable +public final class StorageBlobTierChangedEventData implements JsonSerializable { + /* + * The name of the API/operation that triggered this event. + */ + @Generated + private String api; + + /* + * A request id provided by the client of the storage API operation that triggered this event. + */ + @Generated + private String clientRequestId; + + /* + * The request id generated by the storage service for the storage API operation that triggered this event. + */ + @Generated + private String requestId; + + /* + * The content type of the blob. This is the same as what would be returned in the Content-Type header from the + * blob. + */ + @Generated + private String contentType; + + /* + * The size of the blob in bytes. This is the same as what would be returned in the Content-Length header from the + * blob. + */ + @Generated + private Long contentLength; + + /* + * The type of blob. + */ + @Generated + private String blobType; + + /* + * The current tier of the blob. + */ + @Generated + private final StorageBlobAccessTier accessTier; + + /* + * The previous tier of the blob. + */ + @Generated + private final StorageBlobAccessTier previousTier; + + /* + * The path to the blob. + */ + @Generated + private String url; + + /* + * An opaque string value representing the logical sequence of events for any particular blob name. Users can use + * standard string comparison to understand the relative sequence of two events on the same blob name. + */ + @Generated + private String sequencer; + + /* + * The identity of the requester that triggered this event. + */ + @Generated + private String identity; + + /* + * For service use only. Diagnostic data occasionally included by the Azure Storage service. This property should be + * ignored by event consumers. + */ + @Generated + private final Map storageDiagnostics; + + /** + * Creates an instance of StorageBlobTierChangedEventData class. + * + * @param accessTier the accessTier value to set. + * @param previousTier the previousTier value to set. + * @param storageDiagnostics the storageDiagnostics value to set. + */ + @Generated + private StorageBlobTierChangedEventData(StorageBlobAccessTier accessTier, StorageBlobAccessTier previousTier, + Map storageDiagnostics) { + this.accessTier = accessTier; + this.previousTier = previousTier; + this.storageDiagnostics = storageDiagnostics; + } + + /** + * Get the api property: The name of the API/operation that triggered this event. + * + * @return the api value. + */ + @Generated + public String getApi() { + return this.api; + } + + /** + * Get the clientRequestId property: A request id provided by the client of the storage API operation that triggered + * this event. + * + * @return the clientRequestId value. + */ + @Generated + public String getClientRequestId() { + return this.clientRequestId; + } + + /** + * Get the requestId property: The request id generated by the storage service for the storage API operation that + * triggered this event. + * + * @return the requestId value. + */ + @Generated + public String getRequestId() { + return this.requestId; + } + + /** + * Get the contentType property: The content type of the blob. This is the same as what would be returned in the + * Content-Type header from the blob. + * + * @return the contentType value. + */ + @Generated + public String getContentType() { + return this.contentType; + } + + /** + * Get the contentLength property: The size of the blob in bytes. This is the same as what would be returned in the + * Content-Length header from the blob. + * + * @return the contentLength value. + */ + @Generated + public Long getContentLength() { + return this.contentLength; + } + + /** + * Get the blobType property: The type of blob. + * + * @return the blobType value. + */ + @Generated + public String getBlobType() { + return this.blobType; + } + + /** + * Get the accessTier property: The current tier of the blob. + * + * @return the accessTier value. + */ + @Generated + public StorageBlobAccessTier getAccessTier() { + return this.accessTier; + } + + /** + * Get the previousTier property: The previous tier of the blob. + * + * @return the previousTier value. + */ + @Generated + public StorageBlobAccessTier getPreviousTier() { + return this.previousTier; + } + + /** + * Get the url property: The path to the blob. + * + * @return the url value. + */ + @Generated + public String getUrl() { + return this.url; + } + + /** + * Get the sequencer property: An opaque string value representing the logical sequence of events for any particular + * blob name. Users can use standard string comparison to understand the relative sequence of two events on the same + * blob name. + * + * @return the sequencer value. + */ + @Generated + public String getSequencer() { + return this.sequencer; + } + + /** + * Get the identity property: The identity of the requester that triggered this event. + * + * @return the identity value. + */ + @Generated + public String getIdentity() { + return this.identity; + } + + /** + * Get the storageDiagnostics property: For service use only. Diagnostic data occasionally included by the Azure + * Storage service. This property should be ignored by event consumers. + * + * @return the storageDiagnostics value. + */ + @Generated + public Map getStorageDiagnostics() { + return this.storageDiagnostics; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("accessTier", this.accessTier == null ? null : this.accessTier.toString()); + jsonWriter.writeStringField("previousTier", this.previousTier == null ? null : this.previousTier.toString()); + jsonWriter.writeMapField("storageDiagnostics", this.storageDiagnostics, + (writer, element) -> writer.writeUntyped(element == null ? null : element.toObject(Object.class))); + jsonWriter.writeStringField("api", this.api); + jsonWriter.writeStringField("clientRequestId", this.clientRequestId); + jsonWriter.writeStringField("requestId", this.requestId); + jsonWriter.writeStringField("contentType", this.contentType); + jsonWriter.writeNumberField("contentLength", this.contentLength); + jsonWriter.writeStringField("blobType", this.blobType); + jsonWriter.writeStringField("url", this.url); + jsonWriter.writeStringField("sequencer", this.sequencer); + jsonWriter.writeStringField("identity", this.identity); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of StorageBlobTierChangedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of StorageBlobTierChangedEventData 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 StorageBlobTierChangedEventData. + */ + @Generated + public static StorageBlobTierChangedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + StorageBlobAccessTier accessTier = null; + StorageBlobAccessTier previousTier = null; + Map storageDiagnostics = null; + String api = null; + String clientRequestId = null; + String requestId = null; + String contentType = null; + Long contentLength = null; + String blobType = null; + String url = null; + String sequencer = null; + String identity = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("accessTier".equals(fieldName)) { + accessTier = StorageBlobAccessTier.fromString(reader.getString()); + } else if ("previousTier".equals(fieldName)) { + previousTier = StorageBlobAccessTier.fromString(reader.getString()); + } else if ("storageDiagnostics".equals(fieldName)) { + storageDiagnostics = reader.readMap(reader1 -> reader1 + .getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); + } else if ("api".equals(fieldName)) { + api = reader.getString(); + } else if ("clientRequestId".equals(fieldName)) { + clientRequestId = reader.getString(); + } else if ("requestId".equals(fieldName)) { + requestId = reader.getString(); + } else if ("contentType".equals(fieldName)) { + contentType = reader.getString(); + } else if ("contentLength".equals(fieldName)) { + contentLength = reader.getNullable(JsonReader::getLong); + } else if ("blobType".equals(fieldName)) { + blobType = reader.getString(); + } else if ("url".equals(fieldName)) { + url = reader.getString(); + } else if ("sequencer".equals(fieldName)) { + sequencer = reader.getString(); + } else if ("identity".equals(fieldName)) { + identity = reader.getString(); + } else { + reader.skipChildren(); + } + } + StorageBlobTierChangedEventData deserializedStorageBlobTierChangedEventData + = new StorageBlobTierChangedEventData(accessTier, previousTier, storageDiagnostics); + deserializedStorageBlobTierChangedEventData.api = api; + deserializedStorageBlobTierChangedEventData.clientRequestId = clientRequestId; + deserializedStorageBlobTierChangedEventData.requestId = requestId; + deserializedStorageBlobTierChangedEventData.contentType = contentType; + deserializedStorageBlobTierChangedEventData.contentLength = contentLength; + deserializedStorageBlobTierChangedEventData.blobType = blobType; + deserializedStorageBlobTierChangedEventData.url = url; + deserializedStorageBlobTierChangedEventData.sequencer = sequencer; + deserializedStorageBlobTierChangedEventData.identity = identity; + + return deserializedStorageBlobTierChangedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageDirectoryCreatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageDirectoryCreatedEventData.java new file mode 100644 index 000000000000..142b9e7073e5 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageDirectoryCreatedEventData.java @@ -0,0 +1,244 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.BinaryData; +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.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Storage.DirectoryCreated event. + */ +@Immutable +public final class StorageDirectoryCreatedEventData implements JsonSerializable { + /* + * The name of the API/operation that triggered this event. + */ + @Generated + private String api; + + /* + * A request id provided by the client of the storage API operation that triggered this event. + */ + @Generated + private String clientRequestId; + + /* + * The request id generated by the storage service for the storage API operation that triggered this event. + */ + @Generated + private String requestId; + + /* + * The etag of the directory at the time this event was triggered. + */ + @Generated + private String eTag; + + /* + * The path to the directory. + */ + @Generated + private String url; + + /* + * An opaque string value representing the logical sequence of events for any particular directory name. Users can + * use standard string comparison to understand the relative sequence of two events on the same directory name. + */ + @Generated + private String sequencer; + + /* + * The identity of the requester that triggered this event. + */ + @Generated + private String identity; + + /* + * For service use only. Diagnostic data occasionally included by the Azure Storage service. This property should be + * ignored by event consumers. + */ + @Generated + private final Map storageDiagnostics; + + /** + * Creates an instance of StorageDirectoryCreatedEventData class. + * + * @param storageDiagnostics the storageDiagnostics value to set. + */ + @Generated + private StorageDirectoryCreatedEventData(Map storageDiagnostics) { + this.storageDiagnostics = storageDiagnostics; + } + + /** + * Get the api property: The name of the API/operation that triggered this event. + * + * @return the api value. + */ + @Generated + public String getApi() { + return this.api; + } + + /** + * Get the clientRequestId property: A request id provided by the client of the storage API operation that triggered + * this event. + * + * @return the clientRequestId value. + */ + @Generated + public String getClientRequestId() { + return this.clientRequestId; + } + + /** + * Get the requestId property: The request id generated by the storage service for the storage API operation that + * triggered this event. + * + * @return the requestId value. + */ + @Generated + public String getRequestId() { + return this.requestId; + } + + /** + * Get the eTag property: The etag of the directory at the time this event was triggered. + * + * @return the eTag value. + */ + @Generated + public String getETag() { + return this.eTag; + } + + /** + * Get the url property: The path to the directory. + * + * @return the url value. + */ + @Generated + public String getUrl() { + return this.url; + } + + /** + * Get the sequencer property: An opaque string value representing the logical sequence of events for any particular + * directory name. Users can use standard string comparison to understand the relative sequence of two events on the + * same directory name. + * + * @return the sequencer value. + */ + @Generated + public String getSequencer() { + return this.sequencer; + } + + /** + * Get the identity property: The identity of the requester that triggered this event. + * + * @return the identity value. + */ + @Generated + public String getIdentity() { + return this.identity; + } + + /** + * Get the storageDiagnostics property: For service use only. Diagnostic data occasionally included by the Azure + * Storage service. This property should be ignored by event consumers. + * + * @return the storageDiagnostics value. + */ + @Generated + public Map getStorageDiagnostics() { + return this.storageDiagnostics; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("storageDiagnostics", this.storageDiagnostics, + (writer, element) -> writer.writeUntyped(element == null ? null : element.toObject(Object.class))); + jsonWriter.writeStringField("api", this.api); + jsonWriter.writeStringField("clientRequestId", this.clientRequestId); + jsonWriter.writeStringField("requestId", this.requestId); + jsonWriter.writeStringField("eTag", this.eTag); + jsonWriter.writeStringField("url", this.url); + jsonWriter.writeStringField("sequencer", this.sequencer); + jsonWriter.writeStringField("identity", this.identity); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of StorageDirectoryCreatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of StorageDirectoryCreatedEventData 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 StorageDirectoryCreatedEventData. + */ + @Generated + public static StorageDirectoryCreatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Map storageDiagnostics = null; + String api = null; + String clientRequestId = null; + String requestId = null; + String eTag = null; + String url = null; + String sequencer = null; + String identity = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("storageDiagnostics".equals(fieldName)) { + storageDiagnostics = reader.readMap(reader1 -> reader1 + .getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); + } else if ("api".equals(fieldName)) { + api = reader.getString(); + } else if ("clientRequestId".equals(fieldName)) { + clientRequestId = reader.getString(); + } else if ("requestId".equals(fieldName)) { + requestId = reader.getString(); + } else if ("eTag".equals(fieldName)) { + eTag = reader.getString(); + } else if ("url".equals(fieldName)) { + url = reader.getString(); + } else if ("sequencer".equals(fieldName)) { + sequencer = reader.getString(); + } else if ("identity".equals(fieldName)) { + identity = reader.getString(); + } else { + reader.skipChildren(); + } + } + StorageDirectoryCreatedEventData deserializedStorageDirectoryCreatedEventData + = new StorageDirectoryCreatedEventData(storageDiagnostics); + deserializedStorageDirectoryCreatedEventData.api = api; + deserializedStorageDirectoryCreatedEventData.clientRequestId = clientRequestId; + deserializedStorageDirectoryCreatedEventData.requestId = requestId; + deserializedStorageDirectoryCreatedEventData.eTag = eTag; + deserializedStorageDirectoryCreatedEventData.url = url; + deserializedStorageDirectoryCreatedEventData.sequencer = sequencer; + deserializedStorageDirectoryCreatedEventData.identity = identity; + + return deserializedStorageDirectoryCreatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageDirectoryDeletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageDirectoryDeletedEventData.java new file mode 100644 index 000000000000..fc44549e20f8 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageDirectoryDeletedEventData.java @@ -0,0 +1,245 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.BinaryData; +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.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Storage.DirectoryDeleted event. + */ +@Immutable +public final class StorageDirectoryDeletedEventData implements JsonSerializable { + /* + * The name of the API/operation that triggered this event. + */ + @Generated + private String api; + + /* + * A request id provided by the client of the storage API operation that triggered this event. + */ + @Generated + private String clientRequestId; + + /* + * The request id generated by the storage service for the storage API operation that triggered this event. + */ + @Generated + private String requestId; + + /* + * The path to the deleted directory. + */ + @Generated + private String url; + + /* + * Is this event for a recursive delete operation. + */ + @Generated + private String recursive; + + /* + * An opaque string value representing the logical sequence of events for any particular directory name. Users can + * use standard string comparison to understand the relative sequence of two events on the same directory name. + */ + @Generated + private String sequencer; + + /* + * The identity of the requester that triggered this event. + */ + @Generated + private String identity; + + /* + * For service use only. Diagnostic data occasionally included by the Azure Storage service. This property should be + * ignored by event consumers. + */ + @Generated + private final Map storageDiagnostics; + + /** + * Creates an instance of StorageDirectoryDeletedEventData class. + * + * @param storageDiagnostics the storageDiagnostics value to set. + */ + @Generated + private StorageDirectoryDeletedEventData(Map storageDiagnostics) { + this.storageDiagnostics = storageDiagnostics; + } + + /** + * Get the api property: The name of the API/operation that triggered this event. + * + * @return the api value. + */ + @Generated + public String getApi() { + return this.api; + } + + /** + * Get the clientRequestId property: A request id provided by the client of the storage API operation that triggered + * this event. + * + * @return the clientRequestId value. + */ + @Generated + public String getClientRequestId() { + return this.clientRequestId; + } + + /** + * Get the requestId property: The request id generated by the storage service for the storage API operation that + * triggered this event. + * + * @return the requestId value. + */ + @Generated + public String getRequestId() { + return this.requestId; + } + + /** + * Get the url property: The path to the deleted directory. + * + * @return the url value. + */ + @Generated + public String getUrl() { + return this.url; + } + + /** + * Get the recursive property: Is this event for a recursive delete operation. + * + * @return the recursive value. + */ + @Generated + public Boolean isRecursive() { + String returnValue = this.recursive; + return Boolean.getBoolean(returnValue); + } + + /** + * Get the sequencer property: An opaque string value representing the logical sequence of events for any particular + * directory name. Users can use standard string comparison to understand the relative sequence of two events on the + * same directory name. + * + * @return the sequencer value. + */ + @Generated + public String getSequencer() { + return this.sequencer; + } + + /** + * Get the identity property: The identity of the requester that triggered this event. + * + * @return the identity value. + */ + @Generated + public String getIdentity() { + return this.identity; + } + + /** + * Get the storageDiagnostics property: For service use only. Diagnostic data occasionally included by the Azure + * Storage service. This property should be ignored by event consumers. + * + * @return the storageDiagnostics value. + */ + @Generated + public Map getStorageDiagnostics() { + return this.storageDiagnostics; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("storageDiagnostics", this.storageDiagnostics, + (writer, element) -> writer.writeUntyped(element == null ? null : element.toObject(Object.class))); + jsonWriter.writeStringField("api", this.api); + jsonWriter.writeStringField("clientRequestId", this.clientRequestId); + jsonWriter.writeStringField("requestId", this.requestId); + jsonWriter.writeStringField("url", this.url); + jsonWriter.writeStringField("recursive", this.recursive); + jsonWriter.writeStringField("sequencer", this.sequencer); + jsonWriter.writeStringField("identity", this.identity); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of StorageDirectoryDeletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of StorageDirectoryDeletedEventData 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 StorageDirectoryDeletedEventData. + */ + @Generated + public static StorageDirectoryDeletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Map storageDiagnostics = null; + String api = null; + String clientRequestId = null; + String requestId = null; + String url = null; + String recursive = null; + String sequencer = null; + String identity = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("storageDiagnostics".equals(fieldName)) { + storageDiagnostics = reader.readMap(reader1 -> reader1 + .getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); + } else if ("api".equals(fieldName)) { + api = reader.getString(); + } else if ("clientRequestId".equals(fieldName)) { + clientRequestId = reader.getString(); + } else if ("requestId".equals(fieldName)) { + requestId = reader.getString(); + } else if ("url".equals(fieldName)) { + url = reader.getString(); + } else if ("recursive".equals(fieldName)) { + recursive = reader.getString(); + } else if ("sequencer".equals(fieldName)) { + sequencer = reader.getString(); + } else if ("identity".equals(fieldName)) { + identity = reader.getString(); + } else { + reader.skipChildren(); + } + } + StorageDirectoryDeletedEventData deserializedStorageDirectoryDeletedEventData + = new StorageDirectoryDeletedEventData(storageDiagnostics); + deserializedStorageDirectoryDeletedEventData.api = api; + deserializedStorageDirectoryDeletedEventData.clientRequestId = clientRequestId; + deserializedStorageDirectoryDeletedEventData.requestId = requestId; + deserializedStorageDirectoryDeletedEventData.url = url; + deserializedStorageDirectoryDeletedEventData.recursive = recursive; + deserializedStorageDirectoryDeletedEventData.sequencer = sequencer; + deserializedStorageDirectoryDeletedEventData.identity = identity; + + return deserializedStorageDirectoryDeletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageDirectoryRenamedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageDirectoryRenamedEventData.java new file mode 100644 index 000000000000..f1d65c9f2243 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageDirectoryRenamedEventData.java @@ -0,0 +1,244 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.BinaryData; +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.Map; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Storage.DirectoryRenamed event. + */ +@Immutable +public final class StorageDirectoryRenamedEventData implements JsonSerializable { + /* + * The name of the API/operation that triggered this event. + */ + @Generated + private String api; + + /* + * A request id provided by the client of the storage API operation that triggered this event. + */ + @Generated + private String clientRequestId; + + /* + * The request id generated by the storage service for the storage API operation that triggered this event. + */ + @Generated + private String requestId; + + /* + * The path to the directory that was renamed. + */ + @Generated + private String sourceUrl; + + /* + * The new path to the directory after the rename operation. + */ + @Generated + private String destinationUrl; + + /* + * An opaque string value representing the logical sequence of events for any particular directory name. Users can + * use standard string comparison to understand the relative sequence of two events on the same directory name. + */ + @Generated + private String sequencer; + + /* + * The identity of the requester that triggered this event. + */ + @Generated + private String identity; + + /* + * For service use only. Diagnostic data occasionally included by the Azure Storage service. This property should be + * ignored by event consumers. + */ + @Generated + private final Map storageDiagnostics; + + /** + * Creates an instance of StorageDirectoryRenamedEventData class. + * + * @param storageDiagnostics the storageDiagnostics value to set. + */ + @Generated + private StorageDirectoryRenamedEventData(Map storageDiagnostics) { + this.storageDiagnostics = storageDiagnostics; + } + + /** + * Get the api property: The name of the API/operation that triggered this event. + * + * @return the api value. + */ + @Generated + public String getApi() { + return this.api; + } + + /** + * Get the clientRequestId property: A request id provided by the client of the storage API operation that triggered + * this event. + * + * @return the clientRequestId value. + */ + @Generated + public String getClientRequestId() { + return this.clientRequestId; + } + + /** + * Get the requestId property: The request id generated by the storage service for the storage API operation that + * triggered this event. + * + * @return the requestId value. + */ + @Generated + public String getRequestId() { + return this.requestId; + } + + /** + * Get the sourceUrl property: The path to the directory that was renamed. + * + * @return the sourceUrl value. + */ + @Generated + public String getSourceUrl() { + return this.sourceUrl; + } + + /** + * Get the destinationUrl property: The new path to the directory after the rename operation. + * + * @return the destinationUrl value. + */ + @Generated + public String getDestinationUrl() { + return this.destinationUrl; + } + + /** + * Get the sequencer property: An opaque string value representing the logical sequence of events for any particular + * directory name. Users can use standard string comparison to understand the relative sequence of two events on the + * same directory name. + * + * @return the sequencer value. + */ + @Generated + public String getSequencer() { + return this.sequencer; + } + + /** + * Get the identity property: The identity of the requester that triggered this event. + * + * @return the identity value. + */ + @Generated + public String getIdentity() { + return this.identity; + } + + /** + * Get the storageDiagnostics property: For service use only. Diagnostic data occasionally included by the Azure + * Storage service. This property should be ignored by event consumers. + * + * @return the storageDiagnostics value. + */ + @Generated + public Map getStorageDiagnostics() { + return this.storageDiagnostics; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("storageDiagnostics", this.storageDiagnostics, + (writer, element) -> writer.writeUntyped(element == null ? null : element.toObject(Object.class))); + jsonWriter.writeStringField("api", this.api); + jsonWriter.writeStringField("clientRequestId", this.clientRequestId); + jsonWriter.writeStringField("requestId", this.requestId); + jsonWriter.writeStringField("sourceUrl", this.sourceUrl); + jsonWriter.writeStringField("destinationUrl", this.destinationUrl); + jsonWriter.writeStringField("sequencer", this.sequencer); + jsonWriter.writeStringField("identity", this.identity); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of StorageDirectoryRenamedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of StorageDirectoryRenamedEventData 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 StorageDirectoryRenamedEventData. + */ + @Generated + public static StorageDirectoryRenamedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Map storageDiagnostics = null; + String api = null; + String clientRequestId = null; + String requestId = null; + String sourceUrl = null; + String destinationUrl = null; + String sequencer = null; + String identity = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("storageDiagnostics".equals(fieldName)) { + storageDiagnostics = reader.readMap(reader1 -> reader1 + .getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); + } else if ("api".equals(fieldName)) { + api = reader.getString(); + } else if ("clientRequestId".equals(fieldName)) { + clientRequestId = reader.getString(); + } else if ("requestId".equals(fieldName)) { + requestId = reader.getString(); + } else if ("sourceUrl".equals(fieldName)) { + sourceUrl = reader.getString(); + } else if ("destinationUrl".equals(fieldName)) { + destinationUrl = reader.getString(); + } else if ("sequencer".equals(fieldName)) { + sequencer = reader.getString(); + } else if ("identity".equals(fieldName)) { + identity = reader.getString(); + } else { + reader.skipChildren(); + } + } + StorageDirectoryRenamedEventData deserializedStorageDirectoryRenamedEventData + = new StorageDirectoryRenamedEventData(storageDiagnostics); + deserializedStorageDirectoryRenamedEventData.api = api; + deserializedStorageDirectoryRenamedEventData.clientRequestId = clientRequestId; + deserializedStorageDirectoryRenamedEventData.requestId = requestId; + deserializedStorageDirectoryRenamedEventData.sourceUrl = sourceUrl; + deserializedStorageDirectoryRenamedEventData.destinationUrl = destinationUrl; + deserializedStorageDirectoryRenamedEventData.sequencer = sequencer; + deserializedStorageDirectoryRenamedEventData.identity = identity; + + return deserializedStorageDirectoryRenamedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageLifecycleCompletionStatus.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageLifecycleCompletionStatus.java new file mode 100644 index 000000000000..9b4c3c329faa --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageLifecycleCompletionStatus.java @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The status for a LCM policy. + */ +public final class StorageLifecycleCompletionStatus extends ExpandableStringEnum { + /** + * Completed. + */ + @Generated + public static final StorageLifecycleCompletionStatus COMPLETED = fromString("Completed"); + + /** + * CompletedWithError. + */ + @Generated + public static final StorageLifecycleCompletionStatus COMPLETED_WITH_ERROR = fromString("CompletedWithError"); + + /** + * Incomplete. + */ + @Generated + public static final StorageLifecycleCompletionStatus INCOMPLETE = fromString("Incomplete"); + + /** + * Creates a new instance of StorageLifecycleCompletionStatus value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public StorageLifecycleCompletionStatus() { + } + + /** + * Creates or finds a StorageLifecycleCompletionStatus from its string representation. + * + * @param name a name to look for. + * @return the corresponding StorageLifecycleCompletionStatus. + */ + @Generated + public static StorageLifecycleCompletionStatus fromString(String name) { + return fromString(name, StorageLifecycleCompletionStatus.class); + } + + /** + * Gets known StorageLifecycleCompletionStatus values. + * + * @return known StorageLifecycleCompletionStatus values. + */ + @Generated + public static Collection values() { + return values(StorageLifecycleCompletionStatus.class); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageLifecyclePolicyActionSummaryDetail.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageLifecyclePolicyActionSummaryDetail.java new file mode 100644 index 000000000000..fddf90c1fae9 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageLifecyclePolicyActionSummaryDetail.java @@ -0,0 +1,122 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Execution statistics of a specific policy action in a Blob Management cycle. + */ +@Immutable +public final class StorageLifecyclePolicyActionSummaryDetail + implements JsonSerializable { + /* + * Total number of objects to be acted on by this action. + */ + @Generated + private Long totalObjectsCount; + + /* + * Number of success operations of this action. + */ + @Generated + private Long successCount; + + /* + * Error messages of this action if any. + */ + @Generated + private String errorList; + + /** + * Creates an instance of StorageLifecyclePolicyActionSummaryDetail class. + */ + @Generated + private StorageLifecyclePolicyActionSummaryDetail() { + } + + /** + * Get the totalObjectsCount property: Total number of objects to be acted on by this action. + * + * @return the totalObjectsCount value. + */ + @Generated + public Long getTotalObjectsCount() { + return this.totalObjectsCount; + } + + /** + * Get the successCount property: Number of success operations of this action. + * + * @return the successCount value. + */ + @Generated + public Long getSuccessCount() { + return this.successCount; + } + + /** + * Get the errorList property: Error messages of this action if any. + * + * @return the errorList value. + */ + @Generated + public String getErrorList() { + return this.errorList; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeNumberField("totalObjectsCount", this.totalObjectsCount); + jsonWriter.writeNumberField("successCount", this.successCount); + jsonWriter.writeStringField("errorList", this.errorList); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of StorageLifecyclePolicyActionSummaryDetail from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of StorageLifecyclePolicyActionSummaryDetail 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 StorageLifecyclePolicyActionSummaryDetail. + */ + @Generated + public static StorageLifecyclePolicyActionSummaryDetail fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + StorageLifecyclePolicyActionSummaryDetail deserializedStorageLifecyclePolicyActionSummaryDetail + = new StorageLifecyclePolicyActionSummaryDetail(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("totalObjectsCount".equals(fieldName)) { + deserializedStorageLifecyclePolicyActionSummaryDetail.totalObjectsCount + = reader.getNullable(JsonReader::getLong); + } else if ("successCount".equals(fieldName)) { + deserializedStorageLifecyclePolicyActionSummaryDetail.successCount + = reader.getNullable(JsonReader::getLong); + } else if ("errorList".equals(fieldName)) { + deserializedStorageLifecyclePolicyActionSummaryDetail.errorList = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedStorageLifecyclePolicyActionSummaryDetail; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageLifecyclePolicyCompletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageLifecyclePolicyCompletedEventData.java new file mode 100644 index 000000000000..68c8ccce5231 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageLifecyclePolicyCompletedEventData.java @@ -0,0 +1,202 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Storage.LifecyclePolicyCompleted event. + */ +@Immutable +public final class StorageLifecyclePolicyCompletedEventData + implements JsonSerializable { + /* + * The time the policy task was scheduled. + */ + @Generated + private String scheduleTime; + + /* + * Policy execution summary which shows the completion status of a LCM run" + */ + @Generated + private final StorageLifecyclePolicyRunSummary policyRunSummary; + + /* + * Execution statistics of a specific policy action in a Blob Management cycle. + */ + @Generated + private final StorageLifecyclePolicyActionSummaryDetail deleteSummary; + + /* + * Execution statistics of a specific policy action in a Blob Management cycle. + */ + @Generated + private final StorageLifecyclePolicyActionSummaryDetail tierToCoolSummary; + + /* + * Execution statistics of a specific policy action in a Blob Management cycle. + */ + @Generated + private final StorageLifecyclePolicyActionSummaryDetail tierToArchiveSummary; + + /* + * Execution statistics of a specific policy action in a Blob Management cycle. + */ + @Generated + private final StorageLifecyclePolicyActionSummaryDetail tierToColdSummary; + + /** + * Creates an instance of StorageLifecyclePolicyCompletedEventData class. + * + * @param policyRunSummary the policyRunSummary value to set. + * @param deleteSummary the deleteSummary value to set. + * @param tierToCoolSummary the tierToCoolSummary value to set. + * @param tierToArchiveSummary the tierToArchiveSummary value to set. + * @param tierToColdSummary the tierToColdSummary value to set. + */ + @Generated + private StorageLifecyclePolicyCompletedEventData(StorageLifecyclePolicyRunSummary policyRunSummary, + StorageLifecyclePolicyActionSummaryDetail deleteSummary, + StorageLifecyclePolicyActionSummaryDetail tierToCoolSummary, + StorageLifecyclePolicyActionSummaryDetail tierToArchiveSummary, + StorageLifecyclePolicyActionSummaryDetail tierToColdSummary) { + this.policyRunSummary = policyRunSummary; + this.deleteSummary = deleteSummary; + this.tierToCoolSummary = tierToCoolSummary; + this.tierToArchiveSummary = tierToArchiveSummary; + this.tierToColdSummary = tierToColdSummary; + } + + /** + * Get the scheduleTime property: The time the policy task was scheduled. + * + * @return the scheduleTime value. + */ + @Generated + public String getScheduleTime() { + return this.scheduleTime; + } + + /** + * Get the policyRunSummary property: Policy execution summary which shows the completion status of a LCM run". + * + * @return the policyRunSummary value. + */ + @Generated + public StorageLifecyclePolicyRunSummary getPolicyRunSummary() { + return this.policyRunSummary; + } + + /** + * Get the deleteSummary property: Execution statistics of a specific policy action in a Blob Management cycle. + * + * @return the deleteSummary value. + */ + @Generated + public StorageLifecyclePolicyActionSummaryDetail getDeleteSummary() { + return this.deleteSummary; + } + + /** + * Get the tierToCoolSummary property: Execution statistics of a specific policy action in a Blob Management cycle. + * + * @return the tierToCoolSummary value. + */ + @Generated + public StorageLifecyclePolicyActionSummaryDetail getTierToCoolSummary() { + return this.tierToCoolSummary; + } + + /** + * Get the tierToArchiveSummary property: Execution statistics of a specific policy action in a Blob Management + * cycle. + * + * @return the tierToArchiveSummary value. + */ + @Generated + public StorageLifecyclePolicyActionSummaryDetail getTierToArchiveSummary() { + return this.tierToArchiveSummary; + } + + /** + * Get the tierToColdSummary property: Execution statistics of a specific policy action in a Blob Management cycle. + * + * @return the tierToColdSummary value. + */ + @Generated + public StorageLifecyclePolicyActionSummaryDetail getTierToColdSummary() { + return this.tierToColdSummary; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("policyRunSummary", this.policyRunSummary); + jsonWriter.writeJsonField("deleteSummary", this.deleteSummary); + jsonWriter.writeJsonField("tierToCoolSummary", this.tierToCoolSummary); + jsonWriter.writeJsonField("tierToArchiveSummary", this.tierToArchiveSummary); + jsonWriter.writeJsonField("tierToColdSummary", this.tierToColdSummary); + jsonWriter.writeStringField("scheduleTime", this.scheduleTime); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of StorageLifecyclePolicyCompletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of StorageLifecyclePolicyCompletedEventData 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 StorageLifecyclePolicyCompletedEventData. + */ + @Generated + public static StorageLifecyclePolicyCompletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + StorageLifecyclePolicyRunSummary policyRunSummary = null; + StorageLifecyclePolicyActionSummaryDetail deleteSummary = null; + StorageLifecyclePolicyActionSummaryDetail tierToCoolSummary = null; + StorageLifecyclePolicyActionSummaryDetail tierToArchiveSummary = null; + StorageLifecyclePolicyActionSummaryDetail tierToColdSummary = null; + String scheduleTime = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("policyRunSummary".equals(fieldName)) { + policyRunSummary = StorageLifecyclePolicyRunSummary.fromJson(reader); + } else if ("deleteSummary".equals(fieldName)) { + deleteSummary = StorageLifecyclePolicyActionSummaryDetail.fromJson(reader); + } else if ("tierToCoolSummary".equals(fieldName)) { + tierToCoolSummary = StorageLifecyclePolicyActionSummaryDetail.fromJson(reader); + } else if ("tierToArchiveSummary".equals(fieldName)) { + tierToArchiveSummary = StorageLifecyclePolicyActionSummaryDetail.fromJson(reader); + } else if ("tierToColdSummary".equals(fieldName)) { + tierToColdSummary = StorageLifecyclePolicyActionSummaryDetail.fromJson(reader); + } else if ("scheduleTime".equals(fieldName)) { + scheduleTime = reader.getString(); + } else { + reader.skipChildren(); + } + } + StorageLifecyclePolicyCompletedEventData deserializedStorageLifecyclePolicyCompletedEventData + = new StorageLifecyclePolicyCompletedEventData(policyRunSummary, deleteSummary, tierToCoolSummary, + tierToArchiveSummary, tierToColdSummary); + deserializedStorageLifecyclePolicyCompletedEventData.scheduleTime = scheduleTime; + + return deserializedStorageLifecyclePolicyCompletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageLifecyclePolicyRunSummary.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageLifecyclePolicyRunSummary.java new file mode 100644 index 000000000000..e4ff5b343bb8 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageLifecyclePolicyRunSummary.java @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Policy run status of an account in a Blob Management cycle. + */ +@Immutable +public final class StorageLifecyclePolicyRunSummary implements JsonSerializable { + /* + * Policy status can be Completed/CompletedWithError/Incomplete. + */ + @Generated + private final StorageLifecycleCompletionStatus completionStatus; + + /** + * Creates an instance of StorageLifecyclePolicyRunSummary class. + * + * @param completionStatus the completionStatus value to set. + */ + @Generated + private StorageLifecyclePolicyRunSummary(StorageLifecycleCompletionStatus completionStatus) { + this.completionStatus = completionStatus; + } + + /** + * Get the completionStatus property: Policy status can be Completed/CompletedWithError/Incomplete. + * + * @return the completionStatus value. + */ + @Generated + public StorageLifecycleCompletionStatus getCompletionStatus() { + return this.completionStatus; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("completionStatus", + this.completionStatus == null ? null : this.completionStatus.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of StorageLifecyclePolicyRunSummary from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of StorageLifecyclePolicyRunSummary 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 StorageLifecyclePolicyRunSummary. + */ + @Generated + public static StorageLifecyclePolicyRunSummary fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + StorageLifecycleCompletionStatus completionStatus = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("completionStatus".equals(fieldName)) { + completionStatus = StorageLifecycleCompletionStatus.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + return new StorageLifecyclePolicyRunSummary(completionStatus); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageTaskAssignmentCompletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageTaskAssignmentCompletedEventData.java new file mode 100644 index 000000000000..c70263f621f6 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageTaskAssignmentCompletedEventData.java @@ -0,0 +1,181 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for an Microsoft.Storage.StorageTaskAssignmentCompleted event. + */ +@Immutable +public final class StorageTaskAssignmentCompletedEventData + implements JsonSerializable { + /* + * The status for a storage task. + */ + @Generated + private final StorageTaskAssignmentCompletedStatus status; + + /* + * The time at which a storage task was completed. + */ + @Generated + private final OffsetDateTime completedDateTime; + + /* + * The execution id for a storage task. + */ + @Generated + private String taskExecutionId; + + /* + * The task name for a storage task. + */ + @Generated + private String taskName; + + /* + * The summary report blob url for a storage task + */ + @Generated + private final String summaryReportBlobUrl; + + /** + * Creates an instance of StorageTaskAssignmentCompletedEventData class. + * + * @param status the status value to set. + * @param completedDateTime the completedDateTime value to set. + * @param summaryReportBlobUrl the summaryReportBlobUrl value to set. + */ + @Generated + private StorageTaskAssignmentCompletedEventData(StorageTaskAssignmentCompletedStatus status, + OffsetDateTime completedDateTime, String summaryReportBlobUrl) { + this.status = status; + this.completedDateTime = completedDateTime; + this.summaryReportBlobUrl = summaryReportBlobUrl; + } + + /** + * Get the status property: The status for a storage task. + * + * @return the status value. + */ + @Generated + public StorageTaskAssignmentCompletedStatus getStatus() { + return this.status; + } + + /** + * Get the completedDateTime property: The time at which a storage task was completed. + * + * @return the completedDateTime value. + */ + @Generated + public OffsetDateTime getCompletedDateTime() { + return this.completedDateTime; + } + + /** + * Get the taskExecutionId property: The execution id for a storage task. + * + * @return the taskExecutionId value. + */ + @Generated + public String getTaskExecutionId() { + return this.taskExecutionId; + } + + /** + * Get the taskName property: The task name for a storage task. + * + * @return the taskName value. + */ + @Generated + public String getTaskName() { + return this.taskName; + } + + /** + * Get the summaryReportBlobUrl property: The summary report blob url for a storage task. + * + * @return the summaryReportBlobUrl value. + */ + @Generated + public String getSummaryReportBlobUrl() { + return this.summaryReportBlobUrl; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("status", this.status == null ? null : this.status.toString()); + jsonWriter.writeStringField("completedDateTime", + this.completedDateTime == null + ? null + : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.completedDateTime)); + jsonWriter.writeStringField("summaryReportBlobUrl", this.summaryReportBlobUrl); + jsonWriter.writeStringField("taskExecutionId", this.taskExecutionId); + jsonWriter.writeStringField("taskName", this.taskName); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of StorageTaskAssignmentCompletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of StorageTaskAssignmentCompletedEventData 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 StorageTaskAssignmentCompletedEventData. + */ + @Generated + public static StorageTaskAssignmentCompletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + StorageTaskAssignmentCompletedStatus status = null; + OffsetDateTime completedDateTime = null; + String summaryReportBlobUrl = null; + String taskExecutionId = null; + String taskName = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("status".equals(fieldName)) { + status = StorageTaskAssignmentCompletedStatus.fromString(reader.getString()); + } else if ("completedDateTime".equals(fieldName)) { + completedDateTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("summaryReportBlobUrl".equals(fieldName)) { + summaryReportBlobUrl = reader.getString(); + } else if ("taskExecutionId".equals(fieldName)) { + taskExecutionId = reader.getString(); + } else if ("taskName".equals(fieldName)) { + taskName = reader.getString(); + } else { + reader.skipChildren(); + } + } + StorageTaskAssignmentCompletedEventData deserializedStorageTaskAssignmentCompletedEventData + = new StorageTaskAssignmentCompletedEventData(status, completedDateTime, summaryReportBlobUrl); + deserializedStorageTaskAssignmentCompletedEventData.taskExecutionId = taskExecutionId; + deserializedStorageTaskAssignmentCompletedEventData.taskName = taskName; + + return deserializedStorageTaskAssignmentCompletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageTaskAssignmentCompletedStatus.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageTaskAssignmentCompletedStatus.java new file mode 100644 index 000000000000..d134ce2f125f --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageTaskAssignmentCompletedStatus.java @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The status for a storage task. + */ +public final class StorageTaskAssignmentCompletedStatus + extends ExpandableStringEnum { + /** + * Succeeded. + */ + @Generated + public static final StorageTaskAssignmentCompletedStatus SUCCEEDED = fromString("Succeeded"); + + /** + * Failed. + */ + @Generated + public static final StorageTaskAssignmentCompletedStatus FAILED = fromString("Failed"); + + /** + * Creates a new instance of StorageTaskAssignmentCompletedStatus value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public StorageTaskAssignmentCompletedStatus() { + } + + /** + * Creates or finds a StorageTaskAssignmentCompletedStatus from its string representation. + * + * @param name a name to look for. + * @return the corresponding StorageTaskAssignmentCompletedStatus. + */ + @Generated + public static StorageTaskAssignmentCompletedStatus fromString(String name) { + return fromString(name, StorageTaskAssignmentCompletedStatus.class); + } + + /** + * Gets known StorageTaskAssignmentCompletedStatus values. + * + * @return known StorageTaskAssignmentCompletedStatus values. + */ + @Generated + public static Collection values() { + return values(StorageTaskAssignmentCompletedStatus.class); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageTaskAssignmentQueuedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageTaskAssignmentQueuedEventData.java new file mode 100644 index 000000000000..270e8cb713d2 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageTaskAssignmentQueuedEventData.java @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for an Microsoft.Storage.StorageTaskAssignmentQueued event. + */ +@Immutable +public final class StorageTaskAssignmentQueuedEventData + implements JsonSerializable { + /* + * The time at which a storage task was queued. + */ + @Generated + private final OffsetDateTime queuedOn; + + /* + * The execution id for a storage task. + */ + @Generated + private String taskExecutionId; + + /** + * Creates an instance of StorageTaskAssignmentQueuedEventData class. + * + * @param queuedOn the queuedOn value to set. + */ + @Generated + private StorageTaskAssignmentQueuedEventData(OffsetDateTime queuedOn) { + this.queuedOn = queuedOn; + } + + /** + * Get the queuedOn property: The time at which a storage task was queued. + * + * @return the queuedOn value. + */ + @Generated + public OffsetDateTime getQueuedOn() { + return this.queuedOn; + } + + /** + * Get the taskExecutionId property: The execution id for a storage task. + * + * @return the taskExecutionId value. + */ + @Generated + public String getTaskExecutionId() { + return this.taskExecutionId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("queuedDateTime", + this.queuedOn == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.queuedOn)); + jsonWriter.writeStringField("taskExecutionId", this.taskExecutionId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of StorageTaskAssignmentQueuedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of StorageTaskAssignmentQueuedEventData 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 StorageTaskAssignmentQueuedEventData. + */ + @Generated + public static StorageTaskAssignmentQueuedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OffsetDateTime queuedOn = null; + String taskExecutionId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("queuedDateTime".equals(fieldName)) { + queuedOn = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("taskExecutionId".equals(fieldName)) { + taskExecutionId = reader.getString(); + } else { + reader.skipChildren(); + } + } + StorageTaskAssignmentQueuedEventData deserializedStorageTaskAssignmentQueuedEventData + = new StorageTaskAssignmentQueuedEventData(queuedOn); + deserializedStorageTaskAssignmentQueuedEventData.taskExecutionId = taskExecutionId; + + return deserializedStorageTaskAssignmentQueuedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageTaskCompletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageTaskCompletedEventData.java new file mode 100644 index 000000000000..67702977cb21 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageTaskCompletedEventData.java @@ -0,0 +1,180 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for an Microsoft.Storage.StorageTaskCompleted event. + */ +@Immutable +public final class StorageTaskCompletedEventData implements JsonSerializable { + /* + * The status for a storage task. + */ + @Generated + private final StorageTaskCompletedStatus status; + + /* + * The time at which a storage task was completed. + */ + @Generated + private final OffsetDateTime completedDateTime; + + /* + * The execution id for a storage task. + */ + @Generated + private String taskExecutionId; + + /* + * The task name for a storage task. + */ + @Generated + private String taskName; + + /* + * The summary report blob url for a storage task + */ + @Generated + private final String summaryReportBlobUrl; + + /** + * Creates an instance of StorageTaskCompletedEventData class. + * + * @param status the status value to set. + * @param completedDateTime the completedDateTime value to set. + * @param summaryReportBlobUrl the summaryReportBlobUrl value to set. + */ + @Generated + private StorageTaskCompletedEventData(StorageTaskCompletedStatus status, OffsetDateTime completedDateTime, + String summaryReportBlobUrl) { + this.status = status; + this.completedDateTime = completedDateTime; + this.summaryReportBlobUrl = summaryReportBlobUrl; + } + + /** + * Get the status property: The status for a storage task. + * + * @return the status value. + */ + @Generated + public StorageTaskCompletedStatus getStatus() { + return this.status; + } + + /** + * Get the completedDateTime property: The time at which a storage task was completed. + * + * @return the completedDateTime value. + */ + @Generated + public OffsetDateTime getCompletedDateTime() { + return this.completedDateTime; + } + + /** + * Get the taskExecutionId property: The execution id for a storage task. + * + * @return the taskExecutionId value. + */ + @Generated + public String getTaskExecutionId() { + return this.taskExecutionId; + } + + /** + * Get the taskName property: The task name for a storage task. + * + * @return the taskName value. + */ + @Generated + public String getTaskName() { + return this.taskName; + } + + /** + * Get the summaryReportBlobUrl property: The summary report blob url for a storage task. + * + * @return the summaryReportBlobUrl value. + */ + @Generated + public String getSummaryReportBlobUrl() { + return this.summaryReportBlobUrl; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("status", this.status == null ? null : this.status.toString()); + jsonWriter.writeStringField("completedDateTime", + this.completedDateTime == null + ? null + : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.completedDateTime)); + jsonWriter.writeStringField("summaryReportBlobUrl", this.summaryReportBlobUrl); + jsonWriter.writeStringField("taskExecutionId", this.taskExecutionId); + jsonWriter.writeStringField("taskName", this.taskName); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of StorageTaskCompletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of StorageTaskCompletedEventData 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 StorageTaskCompletedEventData. + */ + @Generated + public static StorageTaskCompletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + StorageTaskCompletedStatus status = null; + OffsetDateTime completedDateTime = null; + String summaryReportBlobUrl = null; + String taskExecutionId = null; + String taskName = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("status".equals(fieldName)) { + status = StorageTaskCompletedStatus.fromString(reader.getString()); + } else if ("completedDateTime".equals(fieldName)) { + completedDateTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("summaryReportBlobUrl".equals(fieldName)) { + summaryReportBlobUrl = reader.getString(); + } else if ("taskExecutionId".equals(fieldName)) { + taskExecutionId = reader.getString(); + } else if ("taskName".equals(fieldName)) { + taskName = reader.getString(); + } else { + reader.skipChildren(); + } + } + StorageTaskCompletedEventData deserializedStorageTaskCompletedEventData + = new StorageTaskCompletedEventData(status, completedDateTime, summaryReportBlobUrl); + deserializedStorageTaskCompletedEventData.taskExecutionId = taskExecutionId; + deserializedStorageTaskCompletedEventData.taskName = taskName; + + return deserializedStorageTaskCompletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageTaskCompletedStatus.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageTaskCompletedStatus.java new file mode 100644 index 000000000000..3561a76713f2 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageTaskCompletedStatus.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The status for a storage task. + */ +public final class StorageTaskCompletedStatus extends ExpandableStringEnum { + /** + * Succeeded. + */ + @Generated + public static final StorageTaskCompletedStatus SUCCEEDED = fromString("Succeeded"); + + /** + * Failed. + */ + @Generated + public static final StorageTaskCompletedStatus FAILED = fromString("Failed"); + + /** + * Creates a new instance of StorageTaskCompletedStatus value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public StorageTaskCompletedStatus() { + } + + /** + * Creates or finds a StorageTaskCompletedStatus from its string representation. + * + * @param name a name to look for. + * @return the corresponding StorageTaskCompletedStatus. + */ + @Generated + public static StorageTaskCompletedStatus fromString(String name) { + return fromString(name, StorageTaskCompletedStatus.class); + } + + /** + * Gets known StorageTaskCompletedStatus values. + * + * @return known StorageTaskCompletedStatus values. + */ + @Generated + public static Collection values() { + return values(StorageTaskCompletedStatus.class); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageTaskQueuedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageTaskQueuedEventData.java new file mode 100644 index 000000000000..d4deed4d2b42 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/StorageTaskQueuedEventData.java @@ -0,0 +1,112 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Schema of the Data property of an EventGridEvent for an Microsoft.Storage.StorageTaskQueued event. + */ +@Immutable +public final class StorageTaskQueuedEventData implements JsonSerializable { + /* + * The time at which a storage task was queued. + */ + @Generated + private final OffsetDateTime queuedDateTime; + + /* + * The execution id for a storage task. + */ + @Generated + private String taskExecutionId; + + /** + * Creates an instance of StorageTaskQueuedEventData class. + * + * @param queuedDateTime the queuedDateTime value to set. + */ + @Generated + private StorageTaskQueuedEventData(OffsetDateTime queuedDateTime) { + this.queuedDateTime = queuedDateTime; + } + + /** + * Get the queuedDateTime property: The time at which a storage task was queued. + * + * @return the queuedDateTime value. + */ + @Generated + public OffsetDateTime getQueuedDateTime() { + return this.queuedDateTime; + } + + /** + * Get the taskExecutionId property: The execution id for a storage task. + * + * @return the taskExecutionId value. + */ + @Generated + public String getTaskExecutionId() { + return this.taskExecutionId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("queuedDateTime", + this.queuedDateTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.queuedDateTime)); + jsonWriter.writeStringField("taskExecutionId", this.taskExecutionId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of StorageTaskQueuedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of StorageTaskQueuedEventData 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 StorageTaskQueuedEventData. + */ + @Generated + public static StorageTaskQueuedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OffsetDateTime queuedDateTime = null; + String taskExecutionId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("queuedDateTime".equals(fieldName)) { + queuedDateTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("taskExecutionId".equals(fieldName)) { + taskExecutionId = reader.getString(); + } else { + reader.skipChildren(); + } + } + StorageTaskQueuedEventData deserializedStorageTaskQueuedEventData + = new StorageTaskQueuedEventData(queuedDateTime); + deserializedStorageTaskQueuedEventData.taskExecutionId = taskExecutionId; + + return deserializedStorageTaskQueuedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/SubscriptionDeletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/SubscriptionDeletedEventData.java new file mode 100644 index 000000000000..e7ab21dd21e4 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/SubscriptionDeletedEventData.java @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a + * Microsoft.EventGrid.SubscriptionDeletedEvent event. + */ +@Immutable +public final class SubscriptionDeletedEventData implements JsonSerializable { + /* + * The Azure resource ID of the deleted event subscription. + */ + @Generated + private final String eventSubscriptionId; + + /** + * Creates an instance of SubscriptionDeletedEventData class. + * + * @param eventSubscriptionId the eventSubscriptionId value to set. + */ + @Generated + private SubscriptionDeletedEventData(String eventSubscriptionId) { + this.eventSubscriptionId = eventSubscriptionId; + } + + /** + * Get the eventSubscriptionId property: The Azure resource ID of the deleted event subscription. + * + * @return the eventSubscriptionId value. + */ + @Generated + public String getEventSubscriptionId() { + return this.eventSubscriptionId; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("eventSubscriptionId", this.eventSubscriptionId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SubscriptionDeletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SubscriptionDeletedEventData 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 SubscriptionDeletedEventData. + */ + @Generated + public static SubscriptionDeletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String eventSubscriptionId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("eventSubscriptionId".equals(fieldName)) { + eventSubscriptionId = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new SubscriptionDeletedEventData(eventSubscriptionId); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/SubscriptionValidationEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/SubscriptionValidationEventData.java new file mode 100644 index 000000000000..e41e6fe49155 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/SubscriptionValidationEventData.java @@ -0,0 +1,118 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.EventGrid.SubscriptionValidationEvent event. + */ +@Immutable +public final class SubscriptionValidationEventData implements JsonSerializable { + /* + * The validation code sent by Azure Event Grid to validate an event subscription. + * To complete the validation handshake, the subscriber must either respond with this validation code as part of the + * validation response, + * or perform a GET request on the validationUrl (available starting version 2018-05-01-preview). + */ + @Generated + private final String validationCode; + + /* + * The validation URL sent by Azure Event Grid (available starting version 2018-05-01-preview). + * To complete the validation handshake, the subscriber must either respond with the validationCode as part of the + * validation response, + * or perform a GET request on the validationUrl (available starting version 2018-05-01-preview). + */ + @Generated + private final String validationUrl; + + /** + * Creates an instance of SubscriptionValidationEventData class. + * + * @param validationCode the validationCode value to set. + * @param validationUrl the validationUrl value to set. + */ + @Generated + private SubscriptionValidationEventData(String validationCode, String validationUrl) { + this.validationCode = validationCode; + this.validationUrl = validationUrl; + } + + /** + * Get the validationCode property: The validation code sent by Azure Event Grid to validate an event subscription. + * To complete the validation handshake, the subscriber must either respond with this validation code as part of the + * validation response, + * or perform a GET request on the validationUrl (available starting version 2018-05-01-preview). + * + * @return the validationCode value. + */ + @Generated + public String getValidationCode() { + return this.validationCode; + } + + /** + * Get the validationUrl property: The validation URL sent by Azure Event Grid (available starting version + * 2018-05-01-preview). + * To complete the validation handshake, the subscriber must either respond with the validationCode as part of the + * validation response, + * or perform a GET request on the validationUrl (available starting version 2018-05-01-preview). + * + * @return the validationUrl value. + */ + @Generated + public String getValidationUrl() { + return this.validationUrl; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("validationCode", this.validationCode); + jsonWriter.writeStringField("validationUrl", this.validationUrl); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SubscriptionValidationEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SubscriptionValidationEventData 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 SubscriptionValidationEventData. + */ + @Generated + public static SubscriptionValidationEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String validationCode = null; + String validationUrl = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("validationCode".equals(fieldName)) { + validationCode = reader.getString(); + } else if ("validationUrl".equals(fieldName)) { + validationUrl = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new SubscriptionValidationEventData(validationCode, validationUrl); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/SubscriptionValidationResponse.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/SubscriptionValidationResponse.java new file mode 100644 index 000000000000..5f5720b215ff --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/SubscriptionValidationResponse.java @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * To complete an event subscription validation handshake, a subscriber can use + * either the validationCode or the validationUrl received in a + * SubscriptionValidationEvent. When the validationCode is used, the + * SubscriptionValidationResponse can be used to build the response. + */ +@Immutable +public final class SubscriptionValidationResponse implements JsonSerializable { + /* + * The validation response sent by the subscriber to Azure Event Grid to complete the validation of an event + * subscription. + */ + @Generated + private final String validationResponse; + + /** + * Creates an instance of SubscriptionValidationResponse class. + * + * @param validationResponse the validationResponse value to set. + */ + @Generated + private SubscriptionValidationResponse(String validationResponse) { + this.validationResponse = validationResponse; + } + + /** + * Get the validationResponse property: The validation response sent by the subscriber to Azure Event Grid to + * complete the validation of an event subscription. + * + * @return the validationResponse value. + */ + @Generated + public String getValidationResponse() { + return this.validationResponse; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("validationResponse", this.validationResponse); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SubscriptionValidationResponse from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SubscriptionValidationResponse 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 SubscriptionValidationResponse. + */ + @Generated + public static SubscriptionValidationResponse fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String validationResponse = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("validationResponse".equals(fieldName)) { + validationResponse = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new SubscriptionValidationResponse(validationResponse); + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebAppServicePlanUpdatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebAppServicePlanUpdatedEventData.java new file mode 100644 index 000000000000..30fdfb82ab25 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebAppServicePlanUpdatedEventData.java @@ -0,0 +1,240 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Web.AppServicePlanUpdated event. + */ +@Immutable +public final class WebAppServicePlanUpdatedEventData implements JsonSerializable { + /* + * Detail of action on the app service plan. + */ + @Generated + private final AppServicePlanEventTypeDetail appServicePlanEventTypeDetail; + + /* + * sku of app service plan. + */ + @Generated + private final WebAppServicePlanUpdatedEventDataSku sku; + + /* + * name of the app service plan that had this event. + */ + @Generated + private String name; + + /* + * The client request id generated by the app service for the app service plan API operation that triggered this + * event. + */ + @Generated + private String clientRequestId; + + /* + * The correlation request id generated by the app service for the app service plan API operation that triggered + * this event. + */ + @Generated + private String correlationRequestId; + + /* + * The request id generated by the app service for the app service plan API operation that triggered this event. + */ + @Generated + private String requestId; + + /* + * HTTP request URL of this operation. + */ + @Generated + private String address; + + /* + * HTTP verb of this operation. + */ + @Generated + private String verb; + + /** + * Creates an instance of WebAppServicePlanUpdatedEventData class. + * + * @param appServicePlanEventTypeDetail the appServicePlanEventTypeDetail value to set. + * @param sku the sku value to set. + */ + @Generated + private WebAppServicePlanUpdatedEventData(AppServicePlanEventTypeDetail appServicePlanEventTypeDetail, + WebAppServicePlanUpdatedEventDataSku sku) { + this.appServicePlanEventTypeDetail = appServicePlanEventTypeDetail; + this.sku = sku; + } + + /** + * Get the appServicePlanEventTypeDetail property: Detail of action on the app service plan. + * + * @return the appServicePlanEventTypeDetail value. + */ + @Generated + public AppServicePlanEventTypeDetail getAppServicePlanEventTypeDetail() { + return this.appServicePlanEventTypeDetail; + } + + /** + * Get the sku property: sku of app service plan. + * + * @return the sku value. + */ + @Generated + public WebAppServicePlanUpdatedEventDataSku getSku() { + return this.sku; + } + + /** + * Get the name property: name of the app service plan that had this event. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the clientRequestId property: The client request id generated by the app service for the app service plan API + * operation that triggered this event. + * + * @return the clientRequestId value. + */ + @Generated + public String getClientRequestId() { + return this.clientRequestId; + } + + /** + * Get the correlationRequestId property: The correlation request id generated by the app service for the app + * service plan API operation that triggered this event. + * + * @return the correlationRequestId value. + */ + @Generated + public String getCorrelationRequestId() { + return this.correlationRequestId; + } + + /** + * Get the requestId property: The request id generated by the app service for the app service plan API operation + * that triggered this event. + * + * @return the requestId value. + */ + @Generated + public String getRequestId() { + return this.requestId; + } + + /** + * Get the address property: HTTP request URL of this operation. + * + * @return the address value. + */ + @Generated + public String getAddress() { + return this.address; + } + + /** + * Get the verb property: HTTP verb of this operation. + * + * @return the verb value. + */ + @Generated + public String getVerb() { + return this.verb; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("appServicePlanEventTypeDetail", this.appServicePlanEventTypeDetail); + jsonWriter.writeJsonField("sku", this.sku); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("clientRequestId", this.clientRequestId); + jsonWriter.writeStringField("correlationRequestId", this.correlationRequestId); + jsonWriter.writeStringField("requestId", this.requestId); + jsonWriter.writeStringField("address", this.address); + jsonWriter.writeStringField("verb", this.verb); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of WebAppServicePlanUpdatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of WebAppServicePlanUpdatedEventData 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 WebAppServicePlanUpdatedEventData. + */ + @Generated + public static WebAppServicePlanUpdatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AppServicePlanEventTypeDetail appServicePlanEventTypeDetail = null; + WebAppServicePlanUpdatedEventDataSku sku = null; + String name = null; + String clientRequestId = null; + String correlationRequestId = null; + String requestId = null; + String address = null; + String verb = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("appServicePlanEventTypeDetail".equals(fieldName)) { + appServicePlanEventTypeDetail = AppServicePlanEventTypeDetail.fromJson(reader); + } else if ("sku".equals(fieldName)) { + sku = WebAppServicePlanUpdatedEventDataSku.fromJson(reader); + } else if ("name".equals(fieldName)) { + name = reader.getString(); + } else if ("clientRequestId".equals(fieldName)) { + clientRequestId = reader.getString(); + } else if ("correlationRequestId".equals(fieldName)) { + correlationRequestId = reader.getString(); + } else if ("requestId".equals(fieldName)) { + requestId = reader.getString(); + } else if ("address".equals(fieldName)) { + address = reader.getString(); + } else if ("verb".equals(fieldName)) { + verb = reader.getString(); + } else { + reader.skipChildren(); + } + } + WebAppServicePlanUpdatedEventData deserializedWebAppServicePlanUpdatedEventData + = new WebAppServicePlanUpdatedEventData(appServicePlanEventTypeDetail, sku); + deserializedWebAppServicePlanUpdatedEventData.name = name; + deserializedWebAppServicePlanUpdatedEventData.clientRequestId = clientRequestId; + deserializedWebAppServicePlanUpdatedEventData.correlationRequestId = correlationRequestId; + deserializedWebAppServicePlanUpdatedEventData.requestId = requestId; + deserializedWebAppServicePlanUpdatedEventData.address = address; + deserializedWebAppServicePlanUpdatedEventData.verb = verb; + + return deserializedWebAppServicePlanUpdatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebAppServicePlanUpdatedEventDataSku.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebAppServicePlanUpdatedEventDataSku.java new file mode 100644 index 000000000000..d5e26203ec9c --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebAppServicePlanUpdatedEventDataSku.java @@ -0,0 +1,158 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * sku of app service plan. + */ +@Immutable +public final class WebAppServicePlanUpdatedEventDataSku + implements JsonSerializable { + /* + * name of app service plan sku. + */ + @Generated + private String name; + + /* + * tier of app service plan sku. + */ + @Generated + private String tier; + + /* + * size of app service plan sku. + */ + @Generated + private String size; + + /* + * family of app service plan sku. + */ + @Generated + private String family; + + /* + * capacity of app service plan sku. + */ + @Generated + private String capacity; + + /** + * Creates an instance of WebAppServicePlanUpdatedEventDataSku class. + */ + @Generated + private WebAppServicePlanUpdatedEventDataSku() { + } + + /** + * Get the name property: name of app service plan sku. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the tier property: tier of app service plan sku. + * + * @return the tier value. + */ + @Generated + public String getTier() { + return this.tier; + } + + /** + * Get the size property: size of app service plan sku. + * + * @return the size value. + */ + @Generated + public String getSize() { + return this.size; + } + + /** + * Get the family property: family of app service plan sku. + * + * @return the family value. + */ + @Generated + public String getFamily() { + return this.family; + } + + /** + * Get the capacity property: capacity of app service plan sku. + * + * @return the capacity value. + */ + @Generated + public String getCapacity() { + return this.capacity; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("Tier", this.tier); + jsonWriter.writeStringField("Size", this.size); + jsonWriter.writeStringField("Family", this.family); + jsonWriter.writeStringField("Capacity", this.capacity); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of WebAppServicePlanUpdatedEventDataSku from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of WebAppServicePlanUpdatedEventDataSku 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 WebAppServicePlanUpdatedEventDataSku. + */ + @Generated + public static WebAppServicePlanUpdatedEventDataSku fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + WebAppServicePlanUpdatedEventDataSku deserializedWebAppServicePlanUpdatedEventDataSku + = new WebAppServicePlanUpdatedEventDataSku(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("name".equals(fieldName)) { + deserializedWebAppServicePlanUpdatedEventDataSku.name = reader.getString(); + } else if ("Tier".equals(fieldName)) { + deserializedWebAppServicePlanUpdatedEventDataSku.tier = reader.getString(); + } else if ("Size".equals(fieldName)) { + deserializedWebAppServicePlanUpdatedEventDataSku.size = reader.getString(); + } else if ("Family".equals(fieldName)) { + deserializedWebAppServicePlanUpdatedEventDataSku.family = reader.getString(); + } else if ("Capacity".equals(fieldName)) { + deserializedWebAppServicePlanUpdatedEventDataSku.capacity = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedWebAppServicePlanUpdatedEventDataSku; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebAppUpdatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebAppUpdatedEventData.java new file mode 100644 index 000000000000..a7394cf8d690 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebAppUpdatedEventData.java @@ -0,0 +1,214 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Web.AppUpdated event. + */ +@Immutable +public final class WebAppUpdatedEventData implements JsonSerializable { + /* + * Detail of action on the app. + */ + @Generated + private final AppEventTypeDetail appEventTypeDetail; + + /* + * name of the web site that had this event. + */ + @Generated + private String name; + + /* + * The client request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String clientRequestId; + + /* + * The correlation request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String correlationRequestId; + + /* + * The request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String requestId; + + /* + * HTTP request URL of this operation. + */ + @Generated + private String address; + + /* + * HTTP verb of this operation. + */ + @Generated + private String verb; + + /** + * Creates an instance of WebAppUpdatedEventData class. + * + * @param appEventTypeDetail the appEventTypeDetail value to set. + */ + @Generated + private WebAppUpdatedEventData(AppEventTypeDetail appEventTypeDetail) { + this.appEventTypeDetail = appEventTypeDetail; + } + + /** + * Get the appEventTypeDetail property: Detail of action on the app. + * + * @return the appEventTypeDetail value. + */ + @Generated + public AppEventTypeDetail getAppEventTypeDetail() { + return this.appEventTypeDetail; + } + + /** + * Get the name property: name of the web site that had this event. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the clientRequestId property: The client request id generated by the app service for the site API operation + * that triggered this event. + * + * @return the clientRequestId value. + */ + @Generated + public String getClientRequestId() { + return this.clientRequestId; + } + + /** + * Get the correlationRequestId property: The correlation request id generated by the app service for the site API + * operation that triggered this event. + * + * @return the correlationRequestId value. + */ + @Generated + public String getCorrelationRequestId() { + return this.correlationRequestId; + } + + /** + * Get the requestId property: The request id generated by the app service for the site API operation that triggered + * this event. + * + * @return the requestId value. + */ + @Generated + public String getRequestId() { + return this.requestId; + } + + /** + * Get the address property: HTTP request URL of this operation. + * + * @return the address value. + */ + @Generated + public String getAddress() { + return this.address; + } + + /** + * Get the verb property: HTTP verb of this operation. + * + * @return the verb value. + */ + @Generated + public String getVerb() { + return this.verb; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("appEventTypeDetail", this.appEventTypeDetail); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("clientRequestId", this.clientRequestId); + jsonWriter.writeStringField("correlationRequestId", this.correlationRequestId); + jsonWriter.writeStringField("requestId", this.requestId); + jsonWriter.writeStringField("address", this.address); + jsonWriter.writeStringField("verb", this.verb); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of WebAppUpdatedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of WebAppUpdatedEventData 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 WebAppUpdatedEventData. + */ + @Generated + public static WebAppUpdatedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AppEventTypeDetail appEventTypeDetail = null; + String name = null; + String clientRequestId = null; + String correlationRequestId = null; + String requestId = null; + String address = null; + String verb = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("appEventTypeDetail".equals(fieldName)) { + appEventTypeDetail = AppEventTypeDetail.fromJson(reader); + } else if ("name".equals(fieldName)) { + name = reader.getString(); + } else if ("clientRequestId".equals(fieldName)) { + clientRequestId = reader.getString(); + } else if ("correlationRequestId".equals(fieldName)) { + correlationRequestId = reader.getString(); + } else if ("requestId".equals(fieldName)) { + requestId = reader.getString(); + } else if ("address".equals(fieldName)) { + address = reader.getString(); + } else if ("verb".equals(fieldName)) { + verb = reader.getString(); + } else { + reader.skipChildren(); + } + } + WebAppUpdatedEventData deserializedWebAppUpdatedEventData = new WebAppUpdatedEventData(appEventTypeDetail); + deserializedWebAppUpdatedEventData.name = name; + deserializedWebAppUpdatedEventData.clientRequestId = clientRequestId; + deserializedWebAppUpdatedEventData.correlationRequestId = correlationRequestId; + deserializedWebAppUpdatedEventData.requestId = requestId; + deserializedWebAppUpdatedEventData.address = address; + deserializedWebAppUpdatedEventData.verb = verb; + + return deserializedWebAppUpdatedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebBackupOperationCompletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebBackupOperationCompletedEventData.java new file mode 100644 index 000000000000..7e5643bf0188 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebBackupOperationCompletedEventData.java @@ -0,0 +1,216 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Web.BackupOperationCompleted event. + */ +@Immutable +public final class WebBackupOperationCompletedEventData + implements JsonSerializable { + /* + * Detail of action on the app. + */ + @Generated + private final AppEventTypeDetail appEventTypeDetail; + + /* + * name of the web site that had this event. + */ + @Generated + private String name; + + /* + * The client request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String clientRequestId; + + /* + * The correlation request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String correlationRequestId; + + /* + * The request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String requestId; + + /* + * HTTP request URL of this operation. + */ + @Generated + private String address; + + /* + * HTTP verb of this operation. + */ + @Generated + private String verb; + + /** + * Creates an instance of WebBackupOperationCompletedEventData class. + * + * @param appEventTypeDetail the appEventTypeDetail value to set. + */ + @Generated + private WebBackupOperationCompletedEventData(AppEventTypeDetail appEventTypeDetail) { + this.appEventTypeDetail = appEventTypeDetail; + } + + /** + * Get the appEventTypeDetail property: Detail of action on the app. + * + * @return the appEventTypeDetail value. + */ + @Generated + public AppEventTypeDetail getAppEventTypeDetail() { + return this.appEventTypeDetail; + } + + /** + * Get the name property: name of the web site that had this event. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the clientRequestId property: The client request id generated by the app service for the site API operation + * that triggered this event. + * + * @return the clientRequestId value. + */ + @Generated + public String getClientRequestId() { + return this.clientRequestId; + } + + /** + * Get the correlationRequestId property: The correlation request id generated by the app service for the site API + * operation that triggered this event. + * + * @return the correlationRequestId value. + */ + @Generated + public String getCorrelationRequestId() { + return this.correlationRequestId; + } + + /** + * Get the requestId property: The request id generated by the app service for the site API operation that triggered + * this event. + * + * @return the requestId value. + */ + @Generated + public String getRequestId() { + return this.requestId; + } + + /** + * Get the address property: HTTP request URL of this operation. + * + * @return the address value. + */ + @Generated + public String getAddress() { + return this.address; + } + + /** + * Get the verb property: HTTP verb of this operation. + * + * @return the verb value. + */ + @Generated + public String getVerb() { + return this.verb; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("appEventTypeDetail", this.appEventTypeDetail); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("clientRequestId", this.clientRequestId); + jsonWriter.writeStringField("correlationRequestId", this.correlationRequestId); + jsonWriter.writeStringField("requestId", this.requestId); + jsonWriter.writeStringField("address", this.address); + jsonWriter.writeStringField("verb", this.verb); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of WebBackupOperationCompletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of WebBackupOperationCompletedEventData 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 WebBackupOperationCompletedEventData. + */ + @Generated + public static WebBackupOperationCompletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AppEventTypeDetail appEventTypeDetail = null; + String name = null; + String clientRequestId = null; + String correlationRequestId = null; + String requestId = null; + String address = null; + String verb = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("appEventTypeDetail".equals(fieldName)) { + appEventTypeDetail = AppEventTypeDetail.fromJson(reader); + } else if ("name".equals(fieldName)) { + name = reader.getString(); + } else if ("clientRequestId".equals(fieldName)) { + clientRequestId = reader.getString(); + } else if ("correlationRequestId".equals(fieldName)) { + correlationRequestId = reader.getString(); + } else if ("requestId".equals(fieldName)) { + requestId = reader.getString(); + } else if ("address".equals(fieldName)) { + address = reader.getString(); + } else if ("verb".equals(fieldName)) { + verb = reader.getString(); + } else { + reader.skipChildren(); + } + } + WebBackupOperationCompletedEventData deserializedWebBackupOperationCompletedEventData + = new WebBackupOperationCompletedEventData(appEventTypeDetail); + deserializedWebBackupOperationCompletedEventData.name = name; + deserializedWebBackupOperationCompletedEventData.clientRequestId = clientRequestId; + deserializedWebBackupOperationCompletedEventData.correlationRequestId = correlationRequestId; + deserializedWebBackupOperationCompletedEventData.requestId = requestId; + deserializedWebBackupOperationCompletedEventData.address = address; + deserializedWebBackupOperationCompletedEventData.verb = verb; + + return deserializedWebBackupOperationCompletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebBackupOperationFailedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebBackupOperationFailedEventData.java new file mode 100644 index 000000000000..d112496f76b0 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebBackupOperationFailedEventData.java @@ -0,0 +1,215 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Web.BackupOperationFailed event. + */ +@Immutable +public final class WebBackupOperationFailedEventData implements JsonSerializable { + /* + * Detail of action on the app. + */ + @Generated + private final AppEventTypeDetail appEventTypeDetail; + + /* + * name of the web site that had this event. + */ + @Generated + private String name; + + /* + * The client request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String clientRequestId; + + /* + * The correlation request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String correlationRequestId; + + /* + * The request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String requestId; + + /* + * HTTP request URL of this operation. + */ + @Generated + private String address; + + /* + * HTTP verb of this operation. + */ + @Generated + private String verb; + + /** + * Creates an instance of WebBackupOperationFailedEventData class. + * + * @param appEventTypeDetail the appEventTypeDetail value to set. + */ + @Generated + private WebBackupOperationFailedEventData(AppEventTypeDetail appEventTypeDetail) { + this.appEventTypeDetail = appEventTypeDetail; + } + + /** + * Get the appEventTypeDetail property: Detail of action on the app. + * + * @return the appEventTypeDetail value. + */ + @Generated + public AppEventTypeDetail getAppEventTypeDetail() { + return this.appEventTypeDetail; + } + + /** + * Get the name property: name of the web site that had this event. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the clientRequestId property: The client request id generated by the app service for the site API operation + * that triggered this event. + * + * @return the clientRequestId value. + */ + @Generated + public String getClientRequestId() { + return this.clientRequestId; + } + + /** + * Get the correlationRequestId property: The correlation request id generated by the app service for the site API + * operation that triggered this event. + * + * @return the correlationRequestId value. + */ + @Generated + public String getCorrelationRequestId() { + return this.correlationRequestId; + } + + /** + * Get the requestId property: The request id generated by the app service for the site API operation that triggered + * this event. + * + * @return the requestId value. + */ + @Generated + public String getRequestId() { + return this.requestId; + } + + /** + * Get the address property: HTTP request URL of this operation. + * + * @return the address value. + */ + @Generated + public String getAddress() { + return this.address; + } + + /** + * Get the verb property: HTTP verb of this operation. + * + * @return the verb value. + */ + @Generated + public String getVerb() { + return this.verb; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("appEventTypeDetail", this.appEventTypeDetail); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("clientRequestId", this.clientRequestId); + jsonWriter.writeStringField("correlationRequestId", this.correlationRequestId); + jsonWriter.writeStringField("requestId", this.requestId); + jsonWriter.writeStringField("address", this.address); + jsonWriter.writeStringField("verb", this.verb); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of WebBackupOperationFailedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of WebBackupOperationFailedEventData 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 WebBackupOperationFailedEventData. + */ + @Generated + public static WebBackupOperationFailedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AppEventTypeDetail appEventTypeDetail = null; + String name = null; + String clientRequestId = null; + String correlationRequestId = null; + String requestId = null; + String address = null; + String verb = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("appEventTypeDetail".equals(fieldName)) { + appEventTypeDetail = AppEventTypeDetail.fromJson(reader); + } else if ("name".equals(fieldName)) { + name = reader.getString(); + } else if ("clientRequestId".equals(fieldName)) { + clientRequestId = reader.getString(); + } else if ("correlationRequestId".equals(fieldName)) { + correlationRequestId = reader.getString(); + } else if ("requestId".equals(fieldName)) { + requestId = reader.getString(); + } else if ("address".equals(fieldName)) { + address = reader.getString(); + } else if ("verb".equals(fieldName)) { + verb = reader.getString(); + } else { + reader.skipChildren(); + } + } + WebBackupOperationFailedEventData deserializedWebBackupOperationFailedEventData + = new WebBackupOperationFailedEventData(appEventTypeDetail); + deserializedWebBackupOperationFailedEventData.name = name; + deserializedWebBackupOperationFailedEventData.clientRequestId = clientRequestId; + deserializedWebBackupOperationFailedEventData.correlationRequestId = correlationRequestId; + deserializedWebBackupOperationFailedEventData.requestId = requestId; + deserializedWebBackupOperationFailedEventData.address = address; + deserializedWebBackupOperationFailedEventData.verb = verb; + + return deserializedWebBackupOperationFailedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebBackupOperationStartedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebBackupOperationStartedEventData.java new file mode 100644 index 000000000000..dd723286fb90 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebBackupOperationStartedEventData.java @@ -0,0 +1,215 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Web.BackupOperationStarted event. + */ +@Immutable +public final class WebBackupOperationStartedEventData implements JsonSerializable { + /* + * Detail of action on the app. + */ + @Generated + private final AppEventTypeDetail appEventTypeDetail; + + /* + * name of the web site that had this event. + */ + @Generated + private String name; + + /* + * The client request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String clientRequestId; + + /* + * The correlation request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String correlationRequestId; + + /* + * The request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String requestId; + + /* + * HTTP request URL of this operation. + */ + @Generated + private String address; + + /* + * HTTP verb of this operation. + */ + @Generated + private String verb; + + /** + * Creates an instance of WebBackupOperationStartedEventData class. + * + * @param appEventTypeDetail the appEventTypeDetail value to set. + */ + @Generated + private WebBackupOperationStartedEventData(AppEventTypeDetail appEventTypeDetail) { + this.appEventTypeDetail = appEventTypeDetail; + } + + /** + * Get the appEventTypeDetail property: Detail of action on the app. + * + * @return the appEventTypeDetail value. + */ + @Generated + public AppEventTypeDetail getAppEventTypeDetail() { + return this.appEventTypeDetail; + } + + /** + * Get the name property: name of the web site that had this event. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the clientRequestId property: The client request id generated by the app service for the site API operation + * that triggered this event. + * + * @return the clientRequestId value. + */ + @Generated + public String getClientRequestId() { + return this.clientRequestId; + } + + /** + * Get the correlationRequestId property: The correlation request id generated by the app service for the site API + * operation that triggered this event. + * + * @return the correlationRequestId value. + */ + @Generated + public String getCorrelationRequestId() { + return this.correlationRequestId; + } + + /** + * Get the requestId property: The request id generated by the app service for the site API operation that triggered + * this event. + * + * @return the requestId value. + */ + @Generated + public String getRequestId() { + return this.requestId; + } + + /** + * Get the address property: HTTP request URL of this operation. + * + * @return the address value. + */ + @Generated + public String getAddress() { + return this.address; + } + + /** + * Get the verb property: HTTP verb of this operation. + * + * @return the verb value. + */ + @Generated + public String getVerb() { + return this.verb; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("appEventTypeDetail", this.appEventTypeDetail); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("clientRequestId", this.clientRequestId); + jsonWriter.writeStringField("correlationRequestId", this.correlationRequestId); + jsonWriter.writeStringField("requestId", this.requestId); + jsonWriter.writeStringField("address", this.address); + jsonWriter.writeStringField("verb", this.verb); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of WebBackupOperationStartedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of WebBackupOperationStartedEventData 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 WebBackupOperationStartedEventData. + */ + @Generated + public static WebBackupOperationStartedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AppEventTypeDetail appEventTypeDetail = null; + String name = null; + String clientRequestId = null; + String correlationRequestId = null; + String requestId = null; + String address = null; + String verb = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("appEventTypeDetail".equals(fieldName)) { + appEventTypeDetail = AppEventTypeDetail.fromJson(reader); + } else if ("name".equals(fieldName)) { + name = reader.getString(); + } else if ("clientRequestId".equals(fieldName)) { + clientRequestId = reader.getString(); + } else if ("correlationRequestId".equals(fieldName)) { + correlationRequestId = reader.getString(); + } else if ("requestId".equals(fieldName)) { + requestId = reader.getString(); + } else if ("address".equals(fieldName)) { + address = reader.getString(); + } else if ("verb".equals(fieldName)) { + verb = reader.getString(); + } else { + reader.skipChildren(); + } + } + WebBackupOperationStartedEventData deserializedWebBackupOperationStartedEventData + = new WebBackupOperationStartedEventData(appEventTypeDetail); + deserializedWebBackupOperationStartedEventData.name = name; + deserializedWebBackupOperationStartedEventData.clientRequestId = clientRequestId; + deserializedWebBackupOperationStartedEventData.correlationRequestId = correlationRequestId; + deserializedWebBackupOperationStartedEventData.requestId = requestId; + deserializedWebBackupOperationStartedEventData.address = address; + deserializedWebBackupOperationStartedEventData.verb = verb; + + return deserializedWebBackupOperationStartedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebRestoreOperationCompletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebRestoreOperationCompletedEventData.java new file mode 100644 index 000000000000..b77a4e5172b9 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebRestoreOperationCompletedEventData.java @@ -0,0 +1,216 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Web.RestoreOperationCompleted event. + */ +@Immutable +public final class WebRestoreOperationCompletedEventData + implements JsonSerializable { + /* + * Detail of action on the app. + */ + @Generated + private final AppEventTypeDetail appEventTypeDetail; + + /* + * name of the web site that had this event. + */ + @Generated + private String name; + + /* + * The client request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String clientRequestId; + + /* + * The correlation request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String correlationRequestId; + + /* + * The request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String requestId; + + /* + * HTTP request URL of this operation. + */ + @Generated + private String address; + + /* + * HTTP verb of this operation. + */ + @Generated + private String verb; + + /** + * Creates an instance of WebRestoreOperationCompletedEventData class. + * + * @param appEventTypeDetail the appEventTypeDetail value to set. + */ + @Generated + private WebRestoreOperationCompletedEventData(AppEventTypeDetail appEventTypeDetail) { + this.appEventTypeDetail = appEventTypeDetail; + } + + /** + * Get the appEventTypeDetail property: Detail of action on the app. + * + * @return the appEventTypeDetail value. + */ + @Generated + public AppEventTypeDetail getAppEventTypeDetail() { + return this.appEventTypeDetail; + } + + /** + * Get the name property: name of the web site that had this event. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the clientRequestId property: The client request id generated by the app service for the site API operation + * that triggered this event. + * + * @return the clientRequestId value. + */ + @Generated + public String getClientRequestId() { + return this.clientRequestId; + } + + /** + * Get the correlationRequestId property: The correlation request id generated by the app service for the site API + * operation that triggered this event. + * + * @return the correlationRequestId value. + */ + @Generated + public String getCorrelationRequestId() { + return this.correlationRequestId; + } + + /** + * Get the requestId property: The request id generated by the app service for the site API operation that triggered + * this event. + * + * @return the requestId value. + */ + @Generated + public String getRequestId() { + return this.requestId; + } + + /** + * Get the address property: HTTP request URL of this operation. + * + * @return the address value. + */ + @Generated + public String getAddress() { + return this.address; + } + + /** + * Get the verb property: HTTP verb of this operation. + * + * @return the verb value. + */ + @Generated + public String getVerb() { + return this.verb; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("appEventTypeDetail", this.appEventTypeDetail); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("clientRequestId", this.clientRequestId); + jsonWriter.writeStringField("correlationRequestId", this.correlationRequestId); + jsonWriter.writeStringField("requestId", this.requestId); + jsonWriter.writeStringField("address", this.address); + jsonWriter.writeStringField("verb", this.verb); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of WebRestoreOperationCompletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of WebRestoreOperationCompletedEventData 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 WebRestoreOperationCompletedEventData. + */ + @Generated + public static WebRestoreOperationCompletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AppEventTypeDetail appEventTypeDetail = null; + String name = null; + String clientRequestId = null; + String correlationRequestId = null; + String requestId = null; + String address = null; + String verb = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("appEventTypeDetail".equals(fieldName)) { + appEventTypeDetail = AppEventTypeDetail.fromJson(reader); + } else if ("name".equals(fieldName)) { + name = reader.getString(); + } else if ("clientRequestId".equals(fieldName)) { + clientRequestId = reader.getString(); + } else if ("correlationRequestId".equals(fieldName)) { + correlationRequestId = reader.getString(); + } else if ("requestId".equals(fieldName)) { + requestId = reader.getString(); + } else if ("address".equals(fieldName)) { + address = reader.getString(); + } else if ("verb".equals(fieldName)) { + verb = reader.getString(); + } else { + reader.skipChildren(); + } + } + WebRestoreOperationCompletedEventData deserializedWebRestoreOperationCompletedEventData + = new WebRestoreOperationCompletedEventData(appEventTypeDetail); + deserializedWebRestoreOperationCompletedEventData.name = name; + deserializedWebRestoreOperationCompletedEventData.clientRequestId = clientRequestId; + deserializedWebRestoreOperationCompletedEventData.correlationRequestId = correlationRequestId; + deserializedWebRestoreOperationCompletedEventData.requestId = requestId; + deserializedWebRestoreOperationCompletedEventData.address = address; + deserializedWebRestoreOperationCompletedEventData.verb = verb; + + return deserializedWebRestoreOperationCompletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebRestoreOperationFailedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebRestoreOperationFailedEventData.java new file mode 100644 index 000000000000..6e4c6ed9fb29 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebRestoreOperationFailedEventData.java @@ -0,0 +1,215 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Web.RestoreOperationFailed event. + */ +@Immutable +public final class WebRestoreOperationFailedEventData implements JsonSerializable { + /* + * Detail of action on the app. + */ + @Generated + private final AppEventTypeDetail appEventTypeDetail; + + /* + * name of the web site that had this event. + */ + @Generated + private String name; + + /* + * The client request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String clientRequestId; + + /* + * The correlation request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String correlationRequestId; + + /* + * The request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String requestId; + + /* + * HTTP request URL of this operation. + */ + @Generated + private String address; + + /* + * HTTP verb of this operation. + */ + @Generated + private String verb; + + /** + * Creates an instance of WebRestoreOperationFailedEventData class. + * + * @param appEventTypeDetail the appEventTypeDetail value to set. + */ + @Generated + private WebRestoreOperationFailedEventData(AppEventTypeDetail appEventTypeDetail) { + this.appEventTypeDetail = appEventTypeDetail; + } + + /** + * Get the appEventTypeDetail property: Detail of action on the app. + * + * @return the appEventTypeDetail value. + */ + @Generated + public AppEventTypeDetail getAppEventTypeDetail() { + return this.appEventTypeDetail; + } + + /** + * Get the name property: name of the web site that had this event. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the clientRequestId property: The client request id generated by the app service for the site API operation + * that triggered this event. + * + * @return the clientRequestId value. + */ + @Generated + public String getClientRequestId() { + return this.clientRequestId; + } + + /** + * Get the correlationRequestId property: The correlation request id generated by the app service for the site API + * operation that triggered this event. + * + * @return the correlationRequestId value. + */ + @Generated + public String getCorrelationRequestId() { + return this.correlationRequestId; + } + + /** + * Get the requestId property: The request id generated by the app service for the site API operation that triggered + * this event. + * + * @return the requestId value. + */ + @Generated + public String getRequestId() { + return this.requestId; + } + + /** + * Get the address property: HTTP request URL of this operation. + * + * @return the address value. + */ + @Generated + public String getAddress() { + return this.address; + } + + /** + * Get the verb property: HTTP verb of this operation. + * + * @return the verb value. + */ + @Generated + public String getVerb() { + return this.verb; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("appEventTypeDetail", this.appEventTypeDetail); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("clientRequestId", this.clientRequestId); + jsonWriter.writeStringField("correlationRequestId", this.correlationRequestId); + jsonWriter.writeStringField("requestId", this.requestId); + jsonWriter.writeStringField("address", this.address); + jsonWriter.writeStringField("verb", this.verb); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of WebRestoreOperationFailedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of WebRestoreOperationFailedEventData 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 WebRestoreOperationFailedEventData. + */ + @Generated + public static WebRestoreOperationFailedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AppEventTypeDetail appEventTypeDetail = null; + String name = null; + String clientRequestId = null; + String correlationRequestId = null; + String requestId = null; + String address = null; + String verb = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("appEventTypeDetail".equals(fieldName)) { + appEventTypeDetail = AppEventTypeDetail.fromJson(reader); + } else if ("name".equals(fieldName)) { + name = reader.getString(); + } else if ("clientRequestId".equals(fieldName)) { + clientRequestId = reader.getString(); + } else if ("correlationRequestId".equals(fieldName)) { + correlationRequestId = reader.getString(); + } else if ("requestId".equals(fieldName)) { + requestId = reader.getString(); + } else if ("address".equals(fieldName)) { + address = reader.getString(); + } else if ("verb".equals(fieldName)) { + verb = reader.getString(); + } else { + reader.skipChildren(); + } + } + WebRestoreOperationFailedEventData deserializedWebRestoreOperationFailedEventData + = new WebRestoreOperationFailedEventData(appEventTypeDetail); + deserializedWebRestoreOperationFailedEventData.name = name; + deserializedWebRestoreOperationFailedEventData.clientRequestId = clientRequestId; + deserializedWebRestoreOperationFailedEventData.correlationRequestId = correlationRequestId; + deserializedWebRestoreOperationFailedEventData.requestId = requestId; + deserializedWebRestoreOperationFailedEventData.address = address; + deserializedWebRestoreOperationFailedEventData.verb = verb; + + return deserializedWebRestoreOperationFailedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebRestoreOperationStartedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebRestoreOperationStartedEventData.java new file mode 100644 index 000000000000..b8f540f2f50d --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebRestoreOperationStartedEventData.java @@ -0,0 +1,216 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Web.RestoreOperationStarted event. + */ +@Immutable +public final class WebRestoreOperationStartedEventData + implements JsonSerializable { + /* + * Detail of action on the app. + */ + @Generated + private final AppEventTypeDetail appEventTypeDetail; + + /* + * name of the web site that had this event. + */ + @Generated + private String name; + + /* + * The client request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String clientRequestId; + + /* + * The correlation request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String correlationRequestId; + + /* + * The request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String requestId; + + /* + * HTTP request URL of this operation. + */ + @Generated + private String address; + + /* + * HTTP verb of this operation. + */ + @Generated + private String verb; + + /** + * Creates an instance of WebRestoreOperationStartedEventData class. + * + * @param appEventTypeDetail the appEventTypeDetail value to set. + */ + @Generated + private WebRestoreOperationStartedEventData(AppEventTypeDetail appEventTypeDetail) { + this.appEventTypeDetail = appEventTypeDetail; + } + + /** + * Get the appEventTypeDetail property: Detail of action on the app. + * + * @return the appEventTypeDetail value. + */ + @Generated + public AppEventTypeDetail getAppEventTypeDetail() { + return this.appEventTypeDetail; + } + + /** + * Get the name property: name of the web site that had this event. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the clientRequestId property: The client request id generated by the app service for the site API operation + * that triggered this event. + * + * @return the clientRequestId value. + */ + @Generated + public String getClientRequestId() { + return this.clientRequestId; + } + + /** + * Get the correlationRequestId property: The correlation request id generated by the app service for the site API + * operation that triggered this event. + * + * @return the correlationRequestId value. + */ + @Generated + public String getCorrelationRequestId() { + return this.correlationRequestId; + } + + /** + * Get the requestId property: The request id generated by the app service for the site API operation that triggered + * this event. + * + * @return the requestId value. + */ + @Generated + public String getRequestId() { + return this.requestId; + } + + /** + * Get the address property: HTTP request URL of this operation. + * + * @return the address value. + */ + @Generated + public String getAddress() { + return this.address; + } + + /** + * Get the verb property: HTTP verb of this operation. + * + * @return the verb value. + */ + @Generated + public String getVerb() { + return this.verb; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("appEventTypeDetail", this.appEventTypeDetail); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("clientRequestId", this.clientRequestId); + jsonWriter.writeStringField("correlationRequestId", this.correlationRequestId); + jsonWriter.writeStringField("requestId", this.requestId); + jsonWriter.writeStringField("address", this.address); + jsonWriter.writeStringField("verb", this.verb); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of WebRestoreOperationStartedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of WebRestoreOperationStartedEventData 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 WebRestoreOperationStartedEventData. + */ + @Generated + public static WebRestoreOperationStartedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AppEventTypeDetail appEventTypeDetail = null; + String name = null; + String clientRequestId = null; + String correlationRequestId = null; + String requestId = null; + String address = null; + String verb = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("appEventTypeDetail".equals(fieldName)) { + appEventTypeDetail = AppEventTypeDetail.fromJson(reader); + } else if ("name".equals(fieldName)) { + name = reader.getString(); + } else if ("clientRequestId".equals(fieldName)) { + clientRequestId = reader.getString(); + } else if ("correlationRequestId".equals(fieldName)) { + correlationRequestId = reader.getString(); + } else if ("requestId".equals(fieldName)) { + requestId = reader.getString(); + } else if ("address".equals(fieldName)) { + address = reader.getString(); + } else if ("verb".equals(fieldName)) { + verb = reader.getString(); + } else { + reader.skipChildren(); + } + } + WebRestoreOperationStartedEventData deserializedWebRestoreOperationStartedEventData + = new WebRestoreOperationStartedEventData(appEventTypeDetail); + deserializedWebRestoreOperationStartedEventData.name = name; + deserializedWebRestoreOperationStartedEventData.clientRequestId = clientRequestId; + deserializedWebRestoreOperationStartedEventData.correlationRequestId = correlationRequestId; + deserializedWebRestoreOperationStartedEventData.requestId = requestId; + deserializedWebRestoreOperationStartedEventData.address = address; + deserializedWebRestoreOperationStartedEventData.verb = verb; + + return deserializedWebRestoreOperationStartedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebSlotSwapCompletedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebSlotSwapCompletedEventData.java new file mode 100644 index 000000000000..bdad9b0095a3 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebSlotSwapCompletedEventData.java @@ -0,0 +1,215 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Web.SlotSwapCompleted event. + */ +@Immutable +public final class WebSlotSwapCompletedEventData implements JsonSerializable { + /* + * Detail of action on the app. + */ + @Generated + private final AppEventTypeDetail appEventTypeDetail; + + /* + * name of the web site that had this event. + */ + @Generated + private String name; + + /* + * The client request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String clientRequestId; + + /* + * The correlation request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String correlationRequestId; + + /* + * The request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String requestId; + + /* + * HTTP request URL of this operation. + */ + @Generated + private String address; + + /* + * HTTP verb of this operation. + */ + @Generated + private String verb; + + /** + * Creates an instance of WebSlotSwapCompletedEventData class. + * + * @param appEventTypeDetail the appEventTypeDetail value to set. + */ + @Generated + private WebSlotSwapCompletedEventData(AppEventTypeDetail appEventTypeDetail) { + this.appEventTypeDetail = appEventTypeDetail; + } + + /** + * Get the appEventTypeDetail property: Detail of action on the app. + * + * @return the appEventTypeDetail value. + */ + @Generated + public AppEventTypeDetail getAppEventTypeDetail() { + return this.appEventTypeDetail; + } + + /** + * Get the name property: name of the web site that had this event. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the clientRequestId property: The client request id generated by the app service for the site API operation + * that triggered this event. + * + * @return the clientRequestId value. + */ + @Generated + public String getClientRequestId() { + return this.clientRequestId; + } + + /** + * Get the correlationRequestId property: The correlation request id generated by the app service for the site API + * operation that triggered this event. + * + * @return the correlationRequestId value. + */ + @Generated + public String getCorrelationRequestId() { + return this.correlationRequestId; + } + + /** + * Get the requestId property: The request id generated by the app service for the site API operation that triggered + * this event. + * + * @return the requestId value. + */ + @Generated + public String getRequestId() { + return this.requestId; + } + + /** + * Get the address property: HTTP request URL of this operation. + * + * @return the address value. + */ + @Generated + public String getAddress() { + return this.address; + } + + /** + * Get the verb property: HTTP verb of this operation. + * + * @return the verb value. + */ + @Generated + public String getVerb() { + return this.verb; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("appEventTypeDetail", this.appEventTypeDetail); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("clientRequestId", this.clientRequestId); + jsonWriter.writeStringField("correlationRequestId", this.correlationRequestId); + jsonWriter.writeStringField("requestId", this.requestId); + jsonWriter.writeStringField("address", this.address); + jsonWriter.writeStringField("verb", this.verb); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of WebSlotSwapCompletedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of WebSlotSwapCompletedEventData 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 WebSlotSwapCompletedEventData. + */ + @Generated + public static WebSlotSwapCompletedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AppEventTypeDetail appEventTypeDetail = null; + String name = null; + String clientRequestId = null; + String correlationRequestId = null; + String requestId = null; + String address = null; + String verb = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("appEventTypeDetail".equals(fieldName)) { + appEventTypeDetail = AppEventTypeDetail.fromJson(reader); + } else if ("name".equals(fieldName)) { + name = reader.getString(); + } else if ("clientRequestId".equals(fieldName)) { + clientRequestId = reader.getString(); + } else if ("correlationRequestId".equals(fieldName)) { + correlationRequestId = reader.getString(); + } else if ("requestId".equals(fieldName)) { + requestId = reader.getString(); + } else if ("address".equals(fieldName)) { + address = reader.getString(); + } else if ("verb".equals(fieldName)) { + verb = reader.getString(); + } else { + reader.skipChildren(); + } + } + WebSlotSwapCompletedEventData deserializedWebSlotSwapCompletedEventData + = new WebSlotSwapCompletedEventData(appEventTypeDetail); + deserializedWebSlotSwapCompletedEventData.name = name; + deserializedWebSlotSwapCompletedEventData.clientRequestId = clientRequestId; + deserializedWebSlotSwapCompletedEventData.correlationRequestId = correlationRequestId; + deserializedWebSlotSwapCompletedEventData.requestId = requestId; + deserializedWebSlotSwapCompletedEventData.address = address; + deserializedWebSlotSwapCompletedEventData.verb = verb; + + return deserializedWebSlotSwapCompletedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebSlotSwapFailedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebSlotSwapFailedEventData.java new file mode 100644 index 000000000000..d35f6d53da9e --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebSlotSwapFailedEventData.java @@ -0,0 +1,215 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Web.SlotSwapFailed event. + */ +@Immutable +public final class WebSlotSwapFailedEventData implements JsonSerializable { + /* + * Detail of action on the app. + */ + @Generated + private final AppEventTypeDetail appEventTypeDetail; + + /* + * name of the web site that had this event. + */ + @Generated + private String name; + + /* + * The client request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String clientRequestId; + + /* + * The correlation request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String correlationRequestId; + + /* + * The request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String requestId; + + /* + * HTTP request URL of this operation. + */ + @Generated + private String address; + + /* + * HTTP verb of this operation. + */ + @Generated + private String verb; + + /** + * Creates an instance of WebSlotSwapFailedEventData class. + * + * @param appEventTypeDetail the appEventTypeDetail value to set. + */ + @Generated + private WebSlotSwapFailedEventData(AppEventTypeDetail appEventTypeDetail) { + this.appEventTypeDetail = appEventTypeDetail; + } + + /** + * Get the appEventTypeDetail property: Detail of action on the app. + * + * @return the appEventTypeDetail value. + */ + @Generated + public AppEventTypeDetail getAppEventTypeDetail() { + return this.appEventTypeDetail; + } + + /** + * Get the name property: name of the web site that had this event. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the clientRequestId property: The client request id generated by the app service for the site API operation + * that triggered this event. + * + * @return the clientRequestId value. + */ + @Generated + public String getClientRequestId() { + return this.clientRequestId; + } + + /** + * Get the correlationRequestId property: The correlation request id generated by the app service for the site API + * operation that triggered this event. + * + * @return the correlationRequestId value. + */ + @Generated + public String getCorrelationRequestId() { + return this.correlationRequestId; + } + + /** + * Get the requestId property: The request id generated by the app service for the site API operation that triggered + * this event. + * + * @return the requestId value. + */ + @Generated + public String getRequestId() { + return this.requestId; + } + + /** + * Get the address property: HTTP request URL of this operation. + * + * @return the address value. + */ + @Generated + public String getAddress() { + return this.address; + } + + /** + * Get the verb property: HTTP verb of this operation. + * + * @return the verb value. + */ + @Generated + public String getVerb() { + return this.verb; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("appEventTypeDetail", this.appEventTypeDetail); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("clientRequestId", this.clientRequestId); + jsonWriter.writeStringField("correlationRequestId", this.correlationRequestId); + jsonWriter.writeStringField("requestId", this.requestId); + jsonWriter.writeStringField("address", this.address); + jsonWriter.writeStringField("verb", this.verb); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of WebSlotSwapFailedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of WebSlotSwapFailedEventData 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 WebSlotSwapFailedEventData. + */ + @Generated + public static WebSlotSwapFailedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AppEventTypeDetail appEventTypeDetail = null; + String name = null; + String clientRequestId = null; + String correlationRequestId = null; + String requestId = null; + String address = null; + String verb = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("appEventTypeDetail".equals(fieldName)) { + appEventTypeDetail = AppEventTypeDetail.fromJson(reader); + } else if ("name".equals(fieldName)) { + name = reader.getString(); + } else if ("clientRequestId".equals(fieldName)) { + clientRequestId = reader.getString(); + } else if ("correlationRequestId".equals(fieldName)) { + correlationRequestId = reader.getString(); + } else if ("requestId".equals(fieldName)) { + requestId = reader.getString(); + } else if ("address".equals(fieldName)) { + address = reader.getString(); + } else if ("verb".equals(fieldName)) { + verb = reader.getString(); + } else { + reader.skipChildren(); + } + } + WebSlotSwapFailedEventData deserializedWebSlotSwapFailedEventData + = new WebSlotSwapFailedEventData(appEventTypeDetail); + deserializedWebSlotSwapFailedEventData.name = name; + deserializedWebSlotSwapFailedEventData.clientRequestId = clientRequestId; + deserializedWebSlotSwapFailedEventData.correlationRequestId = correlationRequestId; + deserializedWebSlotSwapFailedEventData.requestId = requestId; + deserializedWebSlotSwapFailedEventData.address = address; + deserializedWebSlotSwapFailedEventData.verb = verb; + + return deserializedWebSlotSwapFailedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebSlotSwapStartedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebSlotSwapStartedEventData.java new file mode 100644 index 000000000000..169382d3958c --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebSlotSwapStartedEventData.java @@ -0,0 +1,215 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Web.SlotSwapStarted event. + */ +@Immutable +public final class WebSlotSwapStartedEventData implements JsonSerializable { + /* + * Detail of action on the app. + */ + @Generated + private final AppEventTypeDetail appEventTypeDetail; + + /* + * name of the web site that had this event. + */ + @Generated + private String name; + + /* + * The client request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String clientRequestId; + + /* + * The correlation request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String correlationRequestId; + + /* + * The request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String requestId; + + /* + * HTTP request URL of this operation. + */ + @Generated + private String address; + + /* + * HTTP verb of this operation. + */ + @Generated + private String verb; + + /** + * Creates an instance of WebSlotSwapStartedEventData class. + * + * @param appEventTypeDetail the appEventTypeDetail value to set. + */ + @Generated + private WebSlotSwapStartedEventData(AppEventTypeDetail appEventTypeDetail) { + this.appEventTypeDetail = appEventTypeDetail; + } + + /** + * Get the appEventTypeDetail property: Detail of action on the app. + * + * @return the appEventTypeDetail value. + */ + @Generated + public AppEventTypeDetail getAppEventTypeDetail() { + return this.appEventTypeDetail; + } + + /** + * Get the name property: name of the web site that had this event. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the clientRequestId property: The client request id generated by the app service for the site API operation + * that triggered this event. + * + * @return the clientRequestId value. + */ + @Generated + public String getClientRequestId() { + return this.clientRequestId; + } + + /** + * Get the correlationRequestId property: The correlation request id generated by the app service for the site API + * operation that triggered this event. + * + * @return the correlationRequestId value. + */ + @Generated + public String getCorrelationRequestId() { + return this.correlationRequestId; + } + + /** + * Get the requestId property: The request id generated by the app service for the site API operation that triggered + * this event. + * + * @return the requestId value. + */ + @Generated + public String getRequestId() { + return this.requestId; + } + + /** + * Get the address property: HTTP request URL of this operation. + * + * @return the address value. + */ + @Generated + public String getAddress() { + return this.address; + } + + /** + * Get the verb property: HTTP verb of this operation. + * + * @return the verb value. + */ + @Generated + public String getVerb() { + return this.verb; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("appEventTypeDetail", this.appEventTypeDetail); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("clientRequestId", this.clientRequestId); + jsonWriter.writeStringField("correlationRequestId", this.correlationRequestId); + jsonWriter.writeStringField("requestId", this.requestId); + jsonWriter.writeStringField("address", this.address); + jsonWriter.writeStringField("verb", this.verb); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of WebSlotSwapStartedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of WebSlotSwapStartedEventData 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 WebSlotSwapStartedEventData. + */ + @Generated + public static WebSlotSwapStartedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AppEventTypeDetail appEventTypeDetail = null; + String name = null; + String clientRequestId = null; + String correlationRequestId = null; + String requestId = null; + String address = null; + String verb = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("appEventTypeDetail".equals(fieldName)) { + appEventTypeDetail = AppEventTypeDetail.fromJson(reader); + } else if ("name".equals(fieldName)) { + name = reader.getString(); + } else if ("clientRequestId".equals(fieldName)) { + clientRequestId = reader.getString(); + } else if ("correlationRequestId".equals(fieldName)) { + correlationRequestId = reader.getString(); + } else if ("requestId".equals(fieldName)) { + requestId = reader.getString(); + } else if ("address".equals(fieldName)) { + address = reader.getString(); + } else if ("verb".equals(fieldName)) { + verb = reader.getString(); + } else { + reader.skipChildren(); + } + } + WebSlotSwapStartedEventData deserializedWebSlotSwapStartedEventData + = new WebSlotSwapStartedEventData(appEventTypeDetail); + deserializedWebSlotSwapStartedEventData.name = name; + deserializedWebSlotSwapStartedEventData.clientRequestId = clientRequestId; + deserializedWebSlotSwapStartedEventData.correlationRequestId = correlationRequestId; + deserializedWebSlotSwapStartedEventData.requestId = requestId; + deserializedWebSlotSwapStartedEventData.address = address; + deserializedWebSlotSwapStartedEventData.verb = verb; + + return deserializedWebSlotSwapStartedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebSlotSwapWithPreviewCancelledEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebSlotSwapWithPreviewCancelledEventData.java new file mode 100644 index 000000000000..967fceb829c7 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebSlotSwapWithPreviewCancelledEventData.java @@ -0,0 +1,216 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Web.SlotSwapWithPreviewCancelled event. + */ +@Immutable +public final class WebSlotSwapWithPreviewCancelledEventData + implements JsonSerializable { + /* + * Detail of action on the app. + */ + @Generated + private final AppEventTypeDetail appEventTypeDetail; + + /* + * name of the web site that had this event. + */ + @Generated + private String name; + + /* + * The client request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String clientRequestId; + + /* + * The correlation request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String correlationRequestId; + + /* + * The request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String requestId; + + /* + * HTTP request URL of this operation. + */ + @Generated + private String address; + + /* + * HTTP verb of this operation. + */ + @Generated + private String verb; + + /** + * Creates an instance of WebSlotSwapWithPreviewCancelledEventData class. + * + * @param appEventTypeDetail the appEventTypeDetail value to set. + */ + @Generated + private WebSlotSwapWithPreviewCancelledEventData(AppEventTypeDetail appEventTypeDetail) { + this.appEventTypeDetail = appEventTypeDetail; + } + + /** + * Get the appEventTypeDetail property: Detail of action on the app. + * + * @return the appEventTypeDetail value. + */ + @Generated + public AppEventTypeDetail getAppEventTypeDetail() { + return this.appEventTypeDetail; + } + + /** + * Get the name property: name of the web site that had this event. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the clientRequestId property: The client request id generated by the app service for the site API operation + * that triggered this event. + * + * @return the clientRequestId value. + */ + @Generated + public String getClientRequestId() { + return this.clientRequestId; + } + + /** + * Get the correlationRequestId property: The correlation request id generated by the app service for the site API + * operation that triggered this event. + * + * @return the correlationRequestId value. + */ + @Generated + public String getCorrelationRequestId() { + return this.correlationRequestId; + } + + /** + * Get the requestId property: The request id generated by the app service for the site API operation that triggered + * this event. + * + * @return the requestId value. + */ + @Generated + public String getRequestId() { + return this.requestId; + } + + /** + * Get the address property: HTTP request URL of this operation. + * + * @return the address value. + */ + @Generated + public String getAddress() { + return this.address; + } + + /** + * Get the verb property: HTTP verb of this operation. + * + * @return the verb value. + */ + @Generated + public String getVerb() { + return this.verb; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("appEventTypeDetail", this.appEventTypeDetail); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("clientRequestId", this.clientRequestId); + jsonWriter.writeStringField("correlationRequestId", this.correlationRequestId); + jsonWriter.writeStringField("requestId", this.requestId); + jsonWriter.writeStringField("address", this.address); + jsonWriter.writeStringField("verb", this.verb); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of WebSlotSwapWithPreviewCancelledEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of WebSlotSwapWithPreviewCancelledEventData 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 WebSlotSwapWithPreviewCancelledEventData. + */ + @Generated + public static WebSlotSwapWithPreviewCancelledEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AppEventTypeDetail appEventTypeDetail = null; + String name = null; + String clientRequestId = null; + String correlationRequestId = null; + String requestId = null; + String address = null; + String verb = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("appEventTypeDetail".equals(fieldName)) { + appEventTypeDetail = AppEventTypeDetail.fromJson(reader); + } else if ("name".equals(fieldName)) { + name = reader.getString(); + } else if ("clientRequestId".equals(fieldName)) { + clientRequestId = reader.getString(); + } else if ("correlationRequestId".equals(fieldName)) { + correlationRequestId = reader.getString(); + } else if ("requestId".equals(fieldName)) { + requestId = reader.getString(); + } else if ("address".equals(fieldName)) { + address = reader.getString(); + } else if ("verb".equals(fieldName)) { + verb = reader.getString(); + } else { + reader.skipChildren(); + } + } + WebSlotSwapWithPreviewCancelledEventData deserializedWebSlotSwapWithPreviewCancelledEventData + = new WebSlotSwapWithPreviewCancelledEventData(appEventTypeDetail); + deserializedWebSlotSwapWithPreviewCancelledEventData.name = name; + deserializedWebSlotSwapWithPreviewCancelledEventData.clientRequestId = clientRequestId; + deserializedWebSlotSwapWithPreviewCancelledEventData.correlationRequestId = correlationRequestId; + deserializedWebSlotSwapWithPreviewCancelledEventData.requestId = requestId; + deserializedWebSlotSwapWithPreviewCancelledEventData.address = address; + deserializedWebSlotSwapWithPreviewCancelledEventData.verb = verb; + + return deserializedWebSlotSwapWithPreviewCancelledEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebSlotSwapWithPreviewStartedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebSlotSwapWithPreviewStartedEventData.java new file mode 100644 index 000000000000..f52c30e97ebf --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/WebSlotSwapWithPreviewStartedEventData.java @@ -0,0 +1,216 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.annotation.Generated; +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; + +/** + * Schema of the Data property of an EventGridEvent for a Microsoft.Web.SlotSwapWithPreviewStarted event. + */ +@Immutable +public final class WebSlotSwapWithPreviewStartedEventData + implements JsonSerializable { + /* + * Detail of action on the app. + */ + @Generated + private final AppEventTypeDetail appEventTypeDetail; + + /* + * name of the web site that had this event. + */ + @Generated + private String name; + + /* + * The client request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String clientRequestId; + + /* + * The correlation request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String correlationRequestId; + + /* + * The request id generated by the app service for the site API operation that triggered this event. + */ + @Generated + private String requestId; + + /* + * HTTP request URL of this operation. + */ + @Generated + private String address; + + /* + * HTTP verb of this operation. + */ + @Generated + private String verb; + + /** + * Creates an instance of WebSlotSwapWithPreviewStartedEventData class. + * + * @param appEventTypeDetail the appEventTypeDetail value to set. + */ + @Generated + private WebSlotSwapWithPreviewStartedEventData(AppEventTypeDetail appEventTypeDetail) { + this.appEventTypeDetail = appEventTypeDetail; + } + + /** + * Get the appEventTypeDetail property: Detail of action on the app. + * + * @return the appEventTypeDetail value. + */ + @Generated + public AppEventTypeDetail getAppEventTypeDetail() { + return this.appEventTypeDetail; + } + + /** + * Get the name property: name of the web site that had this event. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the clientRequestId property: The client request id generated by the app service for the site API operation + * that triggered this event. + * + * @return the clientRequestId value. + */ + @Generated + public String getClientRequestId() { + return this.clientRequestId; + } + + /** + * Get the correlationRequestId property: The correlation request id generated by the app service for the site API + * operation that triggered this event. + * + * @return the correlationRequestId value. + */ + @Generated + public String getCorrelationRequestId() { + return this.correlationRequestId; + } + + /** + * Get the requestId property: The request id generated by the app service for the site API operation that triggered + * this event. + * + * @return the requestId value. + */ + @Generated + public String getRequestId() { + return this.requestId; + } + + /** + * Get the address property: HTTP request URL of this operation. + * + * @return the address value. + */ + @Generated + public String getAddress() { + return this.address; + } + + /** + * Get the verb property: HTTP verb of this operation. + * + * @return the verb value. + */ + @Generated + public String getVerb() { + return this.verb; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("appEventTypeDetail", this.appEventTypeDetail); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("clientRequestId", this.clientRequestId); + jsonWriter.writeStringField("correlationRequestId", this.correlationRequestId); + jsonWriter.writeStringField("requestId", this.requestId); + jsonWriter.writeStringField("address", this.address); + jsonWriter.writeStringField("verb", this.verb); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of WebSlotSwapWithPreviewStartedEventData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of WebSlotSwapWithPreviewStartedEventData 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 WebSlotSwapWithPreviewStartedEventData. + */ + @Generated + public static WebSlotSwapWithPreviewStartedEventData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AppEventTypeDetail appEventTypeDetail = null; + String name = null; + String clientRequestId = null; + String correlationRequestId = null; + String requestId = null; + String address = null; + String verb = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("appEventTypeDetail".equals(fieldName)) { + appEventTypeDetail = AppEventTypeDetail.fromJson(reader); + } else if ("name".equals(fieldName)) { + name = reader.getString(); + } else if ("clientRequestId".equals(fieldName)) { + clientRequestId = reader.getString(); + } else if ("correlationRequestId".equals(fieldName)) { + correlationRequestId = reader.getString(); + } else if ("requestId".equals(fieldName)) { + requestId = reader.getString(); + } else if ("address".equals(fieldName)) { + address = reader.getString(); + } else if ("verb".equals(fieldName)) { + verb = reader.getString(); + } else { + reader.skipChildren(); + } + } + WebSlotSwapWithPreviewStartedEventData deserializedWebSlotSwapWithPreviewStartedEventData + = new WebSlotSwapWithPreviewStartedEventData(appEventTypeDetail); + deserializedWebSlotSwapWithPreviewStartedEventData.name = name; + deserializedWebSlotSwapWithPreviewStartedEventData.clientRequestId = clientRequestId; + deserializedWebSlotSwapWithPreviewStartedEventData.correlationRequestId = correlationRequestId; + deserializedWebSlotSwapWithPreviewStartedEventData.requestId = requestId; + deserializedWebSlotSwapWithPreviewStartedEventData.address = address; + deserializedWebSlotSwapWithPreviewStartedEventData.verb = verb; + + return deserializedWebSlotSwapWithPreviewStartedEventData; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/package-info.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/package-info.java new file mode 100644 index 000000000000..306e173a1e81 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/com/azure/messaging/eventgrid/systemevents/package-info.java @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +/** + * Package containing the data models for SystemEvents. + * Azure Messaging EventGrid SystemEvents. + */ +package com.azure.messaging.eventgrid.systemevents; diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/module-info.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/module-info.java new file mode 100644 index 000000000000..ac83caaedd93 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/java/module-info.java @@ -0,0 +1,12 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +module com.azure.messaging.eventgrid { + requires transitive com.azure.core; + + exports com.azure.messaging.eventgrid.systemevents; + + opens com.azure.messaging.eventgrid.implementation.models to com.azure.core; + opens com.azure.messaging.eventgrid.systemevents to com.azure.core; +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/resources/META-INF/azure-messaging-eventgrid_apiview_properties.json b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/resources/META-INF/azure-messaging-eventgrid_apiview_properties.json new file mode 100644 index 000000000000..93d654c27f4f --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/resources/META-INF/azure-messaging-eventgrid_apiview_properties.json @@ -0,0 +1,299 @@ +{ + "flavor": "azure", + "CrossLanguageDefinitionId": { + "com.azure.messaging.eventgrid.implementation.models.AcsMessageChannelEventError": "Microsoft.EventGrid.SystemEvents.AcsMessageChannelEventError", + "com.azure.messaging.eventgrid.implementation.models.AcsRouterCommunicationError": "Microsoft.EventGrid.SystemEvents.AcsRouterCommunicationError", + "com.azure.messaging.eventgrid.systemevents.AcsChatEventBaseProperties": "Microsoft.EventGrid.SystemEvents.AcsChatEventBaseProperties", + "com.azure.messaging.eventgrid.systemevents.AcsChatEventInThreadBaseProperties": "Microsoft.EventGrid.SystemEvents.AcsChatEventInThreadBaseProperties", + "com.azure.messaging.eventgrid.systemevents.AcsChatMessageDeletedEventData": "Microsoft.EventGrid.SystemEvents.AcsChatMessageDeletedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsChatMessageDeletedInThreadEventData": "Microsoft.EventGrid.SystemEvents.AcsChatMessageDeletedInThreadEventData", + "com.azure.messaging.eventgrid.systemevents.AcsChatMessageEditedEventData": "Microsoft.EventGrid.SystemEvents.AcsChatMessageEditedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsChatMessageEditedInThreadEventData": "Microsoft.EventGrid.SystemEvents.AcsChatMessageEditedInThreadEventData", + "com.azure.messaging.eventgrid.systemevents.AcsChatMessageEventBaseProperties": "Microsoft.EventGrid.SystemEvents.AcsChatMessageEventBaseProperties", + "com.azure.messaging.eventgrid.systemevents.AcsChatMessageEventInThreadBaseProperties": "Microsoft.EventGrid.SystemEvents.AcsChatMessageEventInThreadBaseProperties", + "com.azure.messaging.eventgrid.systemevents.AcsChatMessageReceivedEventData": "Microsoft.EventGrid.SystemEvents.AcsChatMessageReceivedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsChatMessageReceivedInThreadEventData": "Microsoft.EventGrid.SystemEvents.AcsChatMessageReceivedInThreadEventData", + "com.azure.messaging.eventgrid.systemevents.AcsChatParticipantAddedToThreadEventData": "Microsoft.EventGrid.SystemEvents.AcsChatParticipantAddedToThreadEventData", + "com.azure.messaging.eventgrid.systemevents.AcsChatParticipantAddedToThreadWithUserEventData": "Microsoft.EventGrid.SystemEvents.AcsChatParticipantAddedToThreadWithUserEventData", + "com.azure.messaging.eventgrid.systemevents.AcsChatParticipantRemovedFromThreadEventData": "Microsoft.EventGrid.SystemEvents.AcsChatParticipantRemovedFromThreadEventData", + "com.azure.messaging.eventgrid.systemevents.AcsChatParticipantRemovedFromThreadWithUserEventData": "Microsoft.EventGrid.SystemEvents.AcsChatParticipantRemovedFromThreadWithUserEventData", + "com.azure.messaging.eventgrid.systemevents.AcsChatThreadCreatedEventData": "Microsoft.EventGrid.SystemEvents.AcsChatThreadCreatedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsChatThreadCreatedWithUserEventData": "Microsoft.EventGrid.SystemEvents.AcsChatThreadCreatedWithUserEventData", + "com.azure.messaging.eventgrid.systemevents.AcsChatThreadDeletedEventData": "Microsoft.EventGrid.SystemEvents.AcsChatThreadDeletedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsChatThreadEventBaseProperties": "Microsoft.EventGrid.SystemEvents.AcsChatThreadEventBaseProperties", + "com.azure.messaging.eventgrid.systemevents.AcsChatThreadEventInThreadBaseProperties": "Microsoft.EventGrid.SystemEvents.AcsChatThreadEventInThreadBaseProperties", + "com.azure.messaging.eventgrid.systemevents.AcsChatThreadParticipantProperties": "Microsoft.EventGrid.SystemEvents.AcsChatThreadParticipantProperties", + "com.azure.messaging.eventgrid.systemevents.AcsChatThreadPropertiesUpdatedEventData": "Microsoft.EventGrid.SystemEvents.AcsChatThreadPropertiesUpdatedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsChatThreadPropertiesUpdatedPerUserEventData": "Microsoft.EventGrid.SystemEvents.AcsChatThreadPropertiesUpdatedPerUserEventData", + "com.azure.messaging.eventgrid.systemevents.AcsChatThreadWithUserDeletedEventData": "Microsoft.EventGrid.SystemEvents.AcsChatThreadWithUserDeletedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsEmailDeliveryReportReceivedEventData": "Microsoft.EventGrid.SystemEvents.AcsEmailDeliveryReportReceivedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsEmailDeliveryReportStatus": "Microsoft.EventGrid.SystemEvents.AcsEmailDeliveryReportStatus", + "com.azure.messaging.eventgrid.systemevents.AcsEmailDeliveryReportStatusDetails": "Microsoft.EventGrid.SystemEvents.AcsEmailDeliveryReportStatusDetails", + "com.azure.messaging.eventgrid.systemevents.AcsEmailEngagementTrackingReportReceivedEventData": "Microsoft.EventGrid.SystemEvents.AcsEmailEngagementTrackingReportReceivedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsIncomingCallCustomContext": "Microsoft.EventGrid.SystemEvents.AcsIncomingCallCustomContext", + "com.azure.messaging.eventgrid.systemevents.AcsIncomingCallEventData": "Microsoft.EventGrid.SystemEvents.AcsIncomingCallEventData", + "com.azure.messaging.eventgrid.systemevents.AcsInteractiveReplyKind": "Microsoft.EventGrid.SystemEvents.AcsInteractiveReplyKind", + "com.azure.messaging.eventgrid.systemevents.AcsMessageButtonContent": "Microsoft.EventGrid.SystemEvents.AcsMessageButtonContent", + "com.azure.messaging.eventgrid.systemevents.AcsMessageChannelKind": "Microsoft.EventGrid.SystemEvents.AcsMessageChannelKind", + "com.azure.messaging.eventgrid.systemevents.AcsMessageContext": "Microsoft.EventGrid.SystemEvents.AcsMessageContext", + "com.azure.messaging.eventgrid.systemevents.AcsMessageDeliveryStatus": "Microsoft.EventGrid.SystemEvents.AcsMessageDeliveryStatus", + "com.azure.messaging.eventgrid.systemevents.AcsMessageDeliveryStatusUpdatedEventData": "Microsoft.EventGrid.SystemEvents.AcsMessageDeliveryStatusUpdatedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsMessageEventData": "Microsoft.EventGrid.SystemEvents.AcsMessageEventData", + "com.azure.messaging.eventgrid.systemevents.AcsMessageInteractiveButtonReplyContent": "Microsoft.EventGrid.SystemEvents.AcsMessageInteractiveButtonReplyContent", + "com.azure.messaging.eventgrid.systemevents.AcsMessageInteractiveContent": "Microsoft.EventGrid.SystemEvents.AcsMessageInteractiveContent", + "com.azure.messaging.eventgrid.systemevents.AcsMessageInteractiveListReplyContent": "Microsoft.EventGrid.SystemEvents.AcsMessageInteractiveListReplyContent", + "com.azure.messaging.eventgrid.systemevents.AcsMessageMediaContent": "Microsoft.EventGrid.SystemEvents.AcsMessageMediaContent", + "com.azure.messaging.eventgrid.systemevents.AcsMessageReactionContent": "Microsoft.EventGrid.SystemEvents.AcsMessageReactionContent", + "com.azure.messaging.eventgrid.systemevents.AcsMessageReceivedEventData": "Microsoft.EventGrid.SystemEvents.AcsMessageReceivedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsRecordingChunkInfoProperties": "Microsoft.EventGrid.SystemEvents.AcsRecordingChunkInfoProperties", + "com.azure.messaging.eventgrid.systemevents.AcsRecordingFileStatusUpdatedEventData": "Microsoft.EventGrid.SystemEvents.AcsRecordingFileStatusUpdatedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsRecordingStorageInfoProperties": "Microsoft.EventGrid.SystemEvents.AcsRecordingStorageInfoProperties", + "com.azure.messaging.eventgrid.systemevents.AcsRouterChannelConfiguration": "Microsoft.EventGrid.SystemEvents.AcsRouterChannelConfiguration", + "com.azure.messaging.eventgrid.systemevents.AcsRouterEventData": "Microsoft.EventGrid.SystemEvents.AcsRouterEventData", + "com.azure.messaging.eventgrid.systemevents.AcsRouterJobCancelledEventData": "Microsoft.EventGrid.SystemEvents.AcsRouterJobCancelledEventData", + "com.azure.messaging.eventgrid.systemevents.AcsRouterJobClassificationFailedEventData": "Microsoft.EventGrid.SystemEvents.AcsRouterJobClassificationFailedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsRouterJobClassifiedEventData": "Microsoft.EventGrid.SystemEvents.AcsRouterJobClassifiedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsRouterJobClosedEventData": "Microsoft.EventGrid.SystemEvents.AcsRouterJobClosedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsRouterJobCompletedEventData": "Microsoft.EventGrid.SystemEvents.AcsRouterJobCompletedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsRouterJobDeletedEventData": "Microsoft.EventGrid.SystemEvents.AcsRouterJobDeletedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsRouterJobEventData": "Microsoft.EventGrid.SystemEvents.AcsRouterJobEventData", + "com.azure.messaging.eventgrid.systemevents.AcsRouterJobExceptionTriggeredEventData": "Microsoft.EventGrid.SystemEvents.AcsRouterJobExceptionTriggeredEventData", + "com.azure.messaging.eventgrid.systemevents.AcsRouterJobQueuedEventData": "Microsoft.EventGrid.SystemEvents.AcsRouterJobQueuedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsRouterJobReceivedEventData": "Microsoft.EventGrid.SystemEvents.AcsRouterJobReceivedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsRouterJobSchedulingFailedEventData": "Microsoft.EventGrid.SystemEvents.AcsRouterJobSchedulingFailedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsRouterJobStatus": "Microsoft.EventGrid.SystemEvents.AcsRouterJobStatus", + "com.azure.messaging.eventgrid.systemevents.AcsRouterJobUnassignedEventData": "Microsoft.EventGrid.SystemEvents.AcsRouterJobUnassignedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsRouterJobWaitingForActivationEventData": "Microsoft.EventGrid.SystemEvents.AcsRouterJobWaitingForActivationEventData", + "com.azure.messaging.eventgrid.systemevents.AcsRouterJobWorkerSelectorsExpiredEventData": "Microsoft.EventGrid.SystemEvents.AcsRouterJobWorkerSelectorsExpiredEventData", + "com.azure.messaging.eventgrid.systemevents.AcsRouterLabelOperator": "Microsoft.EventGrid.SystemEvents.AcsRouterLabelOperator", + "com.azure.messaging.eventgrid.systemevents.AcsRouterQueueDetails": "Microsoft.EventGrid.SystemEvents.AcsRouterQueueDetails", + "com.azure.messaging.eventgrid.systemevents.AcsRouterUpdatedWorkerProperty": "Microsoft.EventGrid.SystemEvents.AcsRouterUpdatedWorkerProperty", + "com.azure.messaging.eventgrid.systemevents.AcsRouterWorkerDeletedEventData": "Microsoft.EventGrid.SystemEvents.AcsRouterWorkerDeletedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsRouterWorkerDeregisteredEventData": "Microsoft.EventGrid.SystemEvents.AcsRouterWorkerDeregisteredEventData", + "com.azure.messaging.eventgrid.systemevents.AcsRouterWorkerEventData": "Microsoft.EventGrid.SystemEvents.AcsRouterWorkerEventData", + "com.azure.messaging.eventgrid.systemevents.AcsRouterWorkerOfferAcceptedEventData": "Microsoft.EventGrid.SystemEvents.AcsRouterWorkerOfferAcceptedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsRouterWorkerOfferDeclinedEventData": "Microsoft.EventGrid.SystemEvents.AcsRouterWorkerOfferDeclinedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsRouterWorkerOfferExpiredEventData": "Microsoft.EventGrid.SystemEvents.AcsRouterWorkerOfferExpiredEventData", + "com.azure.messaging.eventgrid.systemevents.AcsRouterWorkerOfferIssuedEventData": "Microsoft.EventGrid.SystemEvents.AcsRouterWorkerOfferIssuedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsRouterWorkerOfferRevokedEventData": "Microsoft.EventGrid.SystemEvents.AcsRouterWorkerOfferRevokedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsRouterWorkerRegisteredEventData": "Microsoft.EventGrid.SystemEvents.AcsRouterWorkerRegisteredEventData", + "com.azure.messaging.eventgrid.systemevents.AcsRouterWorkerSelector": "Microsoft.EventGrid.SystemEvents.AcsRouterWorkerSelector", + "com.azure.messaging.eventgrid.systemevents.AcsRouterWorkerSelectorState": "Microsoft.EventGrid.SystemEvents.AcsRouterWorkerSelectorState", + "com.azure.messaging.eventgrid.systemevents.AcsRouterWorkerUpdatedEventData": "Microsoft.EventGrid.SystemEvents.AcsRouterWorkerUpdatedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsSmsDeliveryAttemptProperties": "Microsoft.EventGrid.SystemEvents.AcsSmsDeliveryAttemptProperties", + "com.azure.messaging.eventgrid.systemevents.AcsSmsDeliveryReportReceivedEventData": "Microsoft.EventGrid.SystemEvents.AcsSmsDeliveryReportReceivedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsSmsEventBaseProperties": "Microsoft.EventGrid.SystemEvents.AcsSmsEventBaseProperties", + "com.azure.messaging.eventgrid.systemevents.AcsSmsReceivedEventData": "Microsoft.EventGrid.SystemEvents.AcsSmsReceivedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsUserDisconnectedEventData": "Microsoft.EventGrid.SystemEvents.AcsUserDisconnectedEventData", + "com.azure.messaging.eventgrid.systemevents.AcsUserEngagement": "Microsoft.EventGrid.SystemEvents.AcsUserEngagement", + "com.azure.messaging.eventgrid.systemevents.ApiCenterApiDefinitionAddedEventData": "Microsoft.EventGrid.SystemEvents.ApiCenterApiDefinitionAddedEventData", + "com.azure.messaging.eventgrid.systemevents.ApiCenterApiDefinitionUpdatedEventData": "Microsoft.EventGrid.SystemEvents.ApiCenterApiDefinitionUpdatedEventData", + "com.azure.messaging.eventgrid.systemevents.ApiCenterApiSpecification": "Microsoft.EventGrid.SystemEvents.ApiCenterApiSpecification", + "com.azure.messaging.eventgrid.systemevents.ApiManagementApiCreatedEventData": "Microsoft.EventGrid.SystemEvents.ApiManagementApiCreatedEventData", + "com.azure.messaging.eventgrid.systemevents.ApiManagementApiDeletedEventData": "Microsoft.EventGrid.SystemEvents.ApiManagementApiDeletedEventData", + "com.azure.messaging.eventgrid.systemevents.ApiManagementApiReleaseCreatedEventData": "Microsoft.EventGrid.SystemEvents.ApiManagementApiReleaseCreatedEventData", + "com.azure.messaging.eventgrid.systemevents.ApiManagementApiReleaseDeletedEventData": "Microsoft.EventGrid.SystemEvents.ApiManagementApiReleaseDeletedEventData", + "com.azure.messaging.eventgrid.systemevents.ApiManagementApiReleaseUpdatedEventData": "Microsoft.EventGrid.SystemEvents.ApiManagementApiReleaseUpdatedEventData", + "com.azure.messaging.eventgrid.systemevents.ApiManagementApiUpdatedEventData": "Microsoft.EventGrid.SystemEvents.ApiManagementApiUpdatedEventData", + "com.azure.messaging.eventgrid.systemevents.ApiManagementGatewayApiAddedEventData": "Microsoft.EventGrid.SystemEvents.ApiManagementGatewayApiAddedEventData", + "com.azure.messaging.eventgrid.systemevents.ApiManagementGatewayApiRemovedEventData": "Microsoft.EventGrid.SystemEvents.ApiManagementGatewayApiRemovedEventData", + "com.azure.messaging.eventgrid.systemevents.ApiManagementGatewayCertificateAuthorityCreatedEventData": "Microsoft.EventGrid.SystemEvents.ApiManagementGatewayCertificateAuthorityCreatedEventData", + "com.azure.messaging.eventgrid.systemevents.ApiManagementGatewayCertificateAuthorityDeletedEventData": "Microsoft.EventGrid.SystemEvents.ApiManagementGatewayCertificateAuthorityDeletedEventData", + "com.azure.messaging.eventgrid.systemevents.ApiManagementGatewayCertificateAuthorityUpdatedEventData": "Microsoft.EventGrid.SystemEvents.ApiManagementGatewayCertificateAuthorityUpdatedEventData", + "com.azure.messaging.eventgrid.systemevents.ApiManagementGatewayCreatedEventData": "Microsoft.EventGrid.SystemEvents.ApiManagementGatewayCreatedEventData", + "com.azure.messaging.eventgrid.systemevents.ApiManagementGatewayDeletedEventData": "Microsoft.EventGrid.SystemEvents.ApiManagementGatewayDeletedEventData", + "com.azure.messaging.eventgrid.systemevents.ApiManagementGatewayHostnameConfigurationCreatedEventData": "Microsoft.EventGrid.SystemEvents.ApiManagementGatewayHostnameConfigurationCreatedEventData", + "com.azure.messaging.eventgrid.systemevents.ApiManagementGatewayHostnameConfigurationDeletedEventData": "Microsoft.EventGrid.SystemEvents.ApiManagementGatewayHostnameConfigurationDeletedEventData", + "com.azure.messaging.eventgrid.systemevents.ApiManagementGatewayHostnameConfigurationUpdatedEventData": "Microsoft.EventGrid.SystemEvents.ApiManagementGatewayHostnameConfigurationUpdatedEventData", + "com.azure.messaging.eventgrid.systemevents.ApiManagementGatewayUpdatedEventData": "Microsoft.EventGrid.SystemEvents.ApiManagementGatewayUpdatedEventData", + "com.azure.messaging.eventgrid.systemevents.ApiManagementProductCreatedEventData": "Microsoft.EventGrid.SystemEvents.ApiManagementProductCreatedEventData", + "com.azure.messaging.eventgrid.systemevents.ApiManagementProductDeletedEventData": "Microsoft.EventGrid.SystemEvents.ApiManagementProductDeletedEventData", + "com.azure.messaging.eventgrid.systemevents.ApiManagementProductUpdatedEventData": "Microsoft.EventGrid.SystemEvents.ApiManagementProductUpdatedEventData", + "com.azure.messaging.eventgrid.systemevents.ApiManagementSubscriptionCreatedEventData": "Microsoft.EventGrid.SystemEvents.ApiManagementSubscriptionCreatedEventData", + "com.azure.messaging.eventgrid.systemevents.ApiManagementSubscriptionDeletedEventData": "Microsoft.EventGrid.SystemEvents.ApiManagementSubscriptionDeletedEventData", + "com.azure.messaging.eventgrid.systemevents.ApiManagementSubscriptionUpdatedEventData": "Microsoft.EventGrid.SystemEvents.ApiManagementSubscriptionUpdatedEventData", + "com.azure.messaging.eventgrid.systemevents.ApiManagementUserCreatedEventData": "Microsoft.EventGrid.SystemEvents.ApiManagementUserCreatedEventData", + "com.azure.messaging.eventgrid.systemevents.ApiManagementUserDeletedEventData": "Microsoft.EventGrid.SystemEvents.ApiManagementUserDeletedEventData", + "com.azure.messaging.eventgrid.systemevents.ApiManagementUserUpdatedEventData": "Microsoft.EventGrid.SystemEvents.ApiManagementUserUpdatedEventData", + "com.azure.messaging.eventgrid.systemevents.AppAction": "Microsoft.EventGrid.SystemEvents.AppAction", + "com.azure.messaging.eventgrid.systemevents.AppConfigurationKeyValueDeletedEventData": "Microsoft.EventGrid.SystemEvents.AppConfigurationKeyValueDeletedEventData", + "com.azure.messaging.eventgrid.systemevents.AppConfigurationKeyValueModifiedEventData": "Microsoft.EventGrid.SystemEvents.AppConfigurationKeyValueModifiedEventData", + "com.azure.messaging.eventgrid.systemevents.AppConfigurationSnapshotCreatedEventData": "Microsoft.EventGrid.SystemEvents.AppConfigurationSnapshotCreatedEventData", + "com.azure.messaging.eventgrid.systemevents.AppConfigurationSnapshotEventData": "Microsoft.EventGrid.SystemEvents.AppConfigurationSnapshotEventData", + "com.azure.messaging.eventgrid.systemevents.AppConfigurationSnapshotModifiedEventData": "Microsoft.EventGrid.SystemEvents.AppConfigurationSnapshotModifiedEventData", + "com.azure.messaging.eventgrid.systemevents.AppEventTypeDetail": "Microsoft.EventGrid.SystemEvents.AppEventTypeDetail", + "com.azure.messaging.eventgrid.systemevents.AppServicePlanAction": "Microsoft.EventGrid.SystemEvents.AppServicePlanAction", + "com.azure.messaging.eventgrid.systemevents.AppServicePlanEventTypeDetail": "Microsoft.EventGrid.SystemEvents.AppServicePlanEventTypeDetail", + "com.azure.messaging.eventgrid.systemevents.AsyncStatus": "Microsoft.EventGrid.SystemEvents.AsyncStatus", + "com.azure.messaging.eventgrid.systemevents.AvsClusterCreatedEventData": "Microsoft.EventGrid.SystemEvents.AvsClusterCreatedEventData", + "com.azure.messaging.eventgrid.systemevents.AvsClusterDeletedEventData": "Microsoft.EventGrid.SystemEvents.AvsClusterDeletedEventData", + "com.azure.messaging.eventgrid.systemevents.AvsClusterEventData": "Microsoft.EventGrid.SystemEvents.AvsClusterEventData", + "com.azure.messaging.eventgrid.systemevents.AvsClusterFailedEventData": "Microsoft.EventGrid.SystemEvents.AvsClusterFailedEventData", + "com.azure.messaging.eventgrid.systemevents.AvsClusterUpdatedEventData": "Microsoft.EventGrid.SystemEvents.AvsClusterUpdatedEventData", + "com.azure.messaging.eventgrid.systemevents.AvsClusterUpdatingEventData": "Microsoft.EventGrid.SystemEvents.AvsClusterUpdatingEventData", + "com.azure.messaging.eventgrid.systemevents.AvsPrivateCloudEventData": "Microsoft.EventGrid.SystemEvents.AvsPrivateCloudEventData", + "com.azure.messaging.eventgrid.systemevents.AvsPrivateCloudFailedEventData": "Microsoft.EventGrid.SystemEvents.AvsPrivateCloudFailedEventData", + "com.azure.messaging.eventgrid.systemevents.AvsPrivateCloudUpdatedEventData": "Microsoft.EventGrid.SystemEvents.AvsPrivateCloudUpdatedEventData", + "com.azure.messaging.eventgrid.systemevents.AvsPrivateCloudUpdatingEventData": "Microsoft.EventGrid.SystemEvents.AvsPrivateCloudUpdatingEventData", + "com.azure.messaging.eventgrid.systemevents.AvsScriptExecutionCancelledEventData": "Microsoft.EventGrid.SystemEvents.AvsScriptExecutionCancelledEventData", + "com.azure.messaging.eventgrid.systemevents.AvsScriptExecutionEventData": "Microsoft.EventGrid.SystemEvents.AvsScriptExecutionEventData", + "com.azure.messaging.eventgrid.systemevents.AvsScriptExecutionFailedEventData": "Microsoft.EventGrid.SystemEvents.AvsScriptExecutionFailedEventData", + "com.azure.messaging.eventgrid.systemevents.AvsScriptExecutionFinishedEventData": "Microsoft.EventGrid.SystemEvents.AvsScriptExecutionFinishedEventData", + "com.azure.messaging.eventgrid.systemevents.AvsScriptExecutionStartedEventData": "Microsoft.EventGrid.SystemEvents.AvsScriptExecutionStartedEventData", + "com.azure.messaging.eventgrid.systemevents.CommunicationCloudEnvironmentModel": "Microsoft.EventGrid.SystemEvents.CommunicationCloudEnvironmentModel", + "com.azure.messaging.eventgrid.systemevents.CommunicationIdentifierKind": "Microsoft.EventGrid.SystemEvents.CommunicationIdentifierModelKind", + "com.azure.messaging.eventgrid.systemevents.CommunicationIdentifierModel": "Microsoft.EventGrid.SystemEvents.CommunicationIdentifierModel", + "com.azure.messaging.eventgrid.systemevents.CommunicationUserIdentifierModel": "Microsoft.EventGrid.SystemEvents.CommunicationUserIdentifierModel", + "com.azure.messaging.eventgrid.systemevents.ContainerRegistryArtifactEventData": "Microsoft.EventGrid.SystemEvents.ContainerRegistryArtifactEventData", + "com.azure.messaging.eventgrid.systemevents.ContainerRegistryArtifactEventTarget": "Microsoft.EventGrid.SystemEvents.ContainerRegistryArtifactEventTarget", + "com.azure.messaging.eventgrid.systemevents.ContainerRegistryChartDeletedEventData": "Microsoft.EventGrid.SystemEvents.ContainerRegistryChartDeletedEventData", + "com.azure.messaging.eventgrid.systemevents.ContainerRegistryChartPushedEventData": "Microsoft.EventGrid.SystemEvents.ContainerRegistryChartPushedEventData", + "com.azure.messaging.eventgrid.systemevents.ContainerRegistryEventActor": "Microsoft.EventGrid.SystemEvents.ContainerRegistryEventActor", + "com.azure.messaging.eventgrid.systemevents.ContainerRegistryEventConnectedRegistry": "Microsoft.EventGrid.SystemEvents.ContainerRegistryEventConnectedRegistry", + "com.azure.messaging.eventgrid.systemevents.ContainerRegistryEventData": "Microsoft.EventGrid.SystemEvents.ContainerRegistryEventData", + "com.azure.messaging.eventgrid.systemevents.ContainerRegistryEventRequest": "Microsoft.EventGrid.SystemEvents.ContainerRegistryEventRequest", + "com.azure.messaging.eventgrid.systemevents.ContainerRegistryEventSource": "Microsoft.EventGrid.SystemEvents.ContainerRegistryEventSource", + "com.azure.messaging.eventgrid.systemevents.ContainerRegistryEventTarget": "Microsoft.EventGrid.SystemEvents.ContainerRegistryEventTarget", + "com.azure.messaging.eventgrid.systemevents.ContainerRegistryImageDeletedEventData": "Microsoft.EventGrid.SystemEvents.ContainerRegistryImageDeletedEventData", + "com.azure.messaging.eventgrid.systemevents.ContainerRegistryImagePushedEventData": "Microsoft.EventGrid.SystemEvents.ContainerRegistryImagePushedEventData", + "com.azure.messaging.eventgrid.systemevents.ContainerServiceClusterSupportEndedEventData": "Microsoft.EventGrid.SystemEvents.ContainerServiceClusterSupportEndedEventData", + "com.azure.messaging.eventgrid.systemevents.ContainerServiceClusterSupportEndingEventData": "Microsoft.EventGrid.SystemEvents.ContainerServiceClusterSupportEndingEventData", + "com.azure.messaging.eventgrid.systemevents.ContainerServiceClusterSupportEventData": "Microsoft.EventGrid.SystemEvents.ContainerServiceClusterSupportEventData", + "com.azure.messaging.eventgrid.systemevents.ContainerServiceNewKubernetesVersionAvailableEventData": "Microsoft.EventGrid.SystemEvents.ContainerServiceNewKubernetesVersionAvailableEventData", + "com.azure.messaging.eventgrid.systemevents.ContainerServiceNodePoolRollingEventData": "Microsoft.EventGrid.SystemEvents.ContainerServiceNodePoolRollingEventData", + "com.azure.messaging.eventgrid.systemevents.ContainerServiceNodePoolRollingFailedEventData": "Microsoft.EventGrid.SystemEvents.ContainerServiceNodePoolRollingFailedEventData", + "com.azure.messaging.eventgrid.systemevents.ContainerServiceNodePoolRollingStartedEventData": "Microsoft.EventGrid.SystemEvents.ContainerServiceNodePoolRollingStartedEventData", + "com.azure.messaging.eventgrid.systemevents.ContainerServiceNodePoolRollingSucceededEventData": "Microsoft.EventGrid.SystemEvents.ContainerServiceNodePoolRollingSucceededEventData", + "com.azure.messaging.eventgrid.systemevents.DataBoxCopyCompletedEventData": "Microsoft.EventGrid.SystemEvents.DataBoxCopyCompletedEventData", + "com.azure.messaging.eventgrid.systemevents.DataBoxCopyStartedEventData": "Microsoft.EventGrid.SystemEvents.DataBoxCopyStartedEventData", + "com.azure.messaging.eventgrid.systemevents.DataBoxOrderCompletedEventData": "Microsoft.EventGrid.SystemEvents.DataBoxOrderCompletedEventData", + "com.azure.messaging.eventgrid.systemevents.DataBoxStageName": "Microsoft.EventGrid.SystemEvents.DataBoxStageName", + "com.azure.messaging.eventgrid.systemevents.DeviceConnectionStateEventInfo": "Microsoft.EventGrid.SystemEvents.DeviceConnectionStateEventInfo", + "com.azure.messaging.eventgrid.systemevents.DeviceConnectionStateEventProperties": "Microsoft.EventGrid.SystemEvents.DeviceConnectionStateEventProperties", + "com.azure.messaging.eventgrid.systemevents.DeviceLifeCycleEventProperties": "Microsoft.EventGrid.SystemEvents.DeviceLifeCycleEventProperties", + "com.azure.messaging.eventgrid.systemevents.DeviceTelemetryEventProperties": "Microsoft.EventGrid.SystemEvents.DeviceTelemetryEventProperties", + "com.azure.messaging.eventgrid.systemevents.DeviceTwinInfo": "Microsoft.EventGrid.SystemEvents.DeviceTwinInfo", + "com.azure.messaging.eventgrid.systemevents.DeviceTwinInfoProperties": "Microsoft.EventGrid.SystemEvents.DeviceTwinInfoProperties", + "com.azure.messaging.eventgrid.systemevents.DeviceTwinInfoX509Thumbprint": "Microsoft.EventGrid.SystemEvents.DeviceTwinInfoX509Thumbprint", + "com.azure.messaging.eventgrid.systemevents.DeviceTwinMetadata": "Microsoft.EventGrid.SystemEvents.DeviceTwinMetadata", + "com.azure.messaging.eventgrid.systemevents.DeviceTwinProperties": "Microsoft.EventGrid.SystemEvents.DeviceTwinProperties", + "com.azure.messaging.eventgrid.systemevents.EventGridMqttClientCreatedOrUpdatedEventData": "Microsoft.EventGrid.SystemEvents.EventGridMQTTClientCreatedOrUpdatedEventData", + "com.azure.messaging.eventgrid.systemevents.EventGridMqttClientDeletedEventData": "Microsoft.EventGrid.SystemEvents.EventGridMQTTClientDeletedEventData", + "com.azure.messaging.eventgrid.systemevents.EventGridMqttClientDisconnectionReason": "Microsoft.EventGrid.SystemEvents.EventGridMQTTClientDisconnectionReason", + "com.azure.messaging.eventgrid.systemevents.EventGridMqttClientEventData": "Microsoft.EventGrid.SystemEvents.EventGridMQTTClientEventData", + "com.azure.messaging.eventgrid.systemevents.EventGridMqttClientSessionConnectedEventData": "Microsoft.EventGrid.SystemEvents.EventGridMQTTClientSessionConnectedEventData", + "com.azure.messaging.eventgrid.systemevents.EventGridMqttClientSessionDisconnectedEventData": "Microsoft.EventGrid.SystemEvents.EventGridMQTTClientSessionDisconnectedEventData", + "com.azure.messaging.eventgrid.systemevents.EventGridMqttClientState": "Microsoft.EventGrid.SystemEvents.EventGridMQTTClientState", + "com.azure.messaging.eventgrid.systemevents.EventHubCaptureFileCreatedEventData": "Microsoft.EventGrid.SystemEvents.EventHubCaptureFileCreatedEventData", + "com.azure.messaging.eventgrid.systemevents.HealthcareDicomImageCreatedEventData": "Microsoft.EventGrid.SystemEvents.HealthcareDicomImageCreatedEventData", + "com.azure.messaging.eventgrid.systemevents.HealthcareDicomImageDeletedEventData": "Microsoft.EventGrid.SystemEvents.HealthcareDicomImageDeletedEventData", + "com.azure.messaging.eventgrid.systemevents.HealthcareDicomImageUpdatedEventData": "Microsoft.EventGrid.SystemEvents.HealthcareDicomImageUpdatedEventData", + "com.azure.messaging.eventgrid.systemevents.HealthcareFhirResourceCreatedEventData": "Microsoft.EventGrid.SystemEvents.HealthcareFhirResourceCreatedEventData", + "com.azure.messaging.eventgrid.systemevents.HealthcareFhirResourceDeletedEventData": "Microsoft.EventGrid.SystemEvents.HealthcareFhirResourceDeletedEventData", + "com.azure.messaging.eventgrid.systemevents.HealthcareFhirResourceType": "Microsoft.EventGrid.SystemEvents.HealthcareFhirResourceType", + "com.azure.messaging.eventgrid.systemevents.HealthcareFhirResourceUpdatedEventData": "Microsoft.EventGrid.SystemEvents.HealthcareFhirResourceUpdatedEventData", + "com.azure.messaging.eventgrid.systemevents.IotHubDeviceConnectedEventData": "Microsoft.EventGrid.SystemEvents.IotHubDeviceConnectedEventData", + "com.azure.messaging.eventgrid.systemevents.IotHubDeviceCreatedEventData": "Microsoft.EventGrid.SystemEvents.IotHubDeviceCreatedEventData", + "com.azure.messaging.eventgrid.systemevents.IotHubDeviceDeletedEventData": "Microsoft.EventGrid.SystemEvents.IotHubDeviceDeletedEventData", + "com.azure.messaging.eventgrid.systemevents.IotHubDeviceDisconnectedEventData": "Microsoft.EventGrid.SystemEvents.IotHubDeviceDisconnectedEventData", + "com.azure.messaging.eventgrid.systemevents.IotHubDeviceTelemetryEventData": "Microsoft.EventGrid.SystemEvents.IotHubDeviceTelemetryEventData", + "com.azure.messaging.eventgrid.systemevents.KeyVaultAccessPolicyChangedEventData": "Microsoft.EventGrid.SystemEvents.KeyVaultAccessPolicyChangedEventData", + "com.azure.messaging.eventgrid.systemevents.KeyVaultCertificateExpiredEventData": "Microsoft.EventGrid.SystemEvents.KeyVaultCertificateExpiredEventData", + "com.azure.messaging.eventgrid.systemevents.KeyVaultCertificateNearExpiryEventData": "Microsoft.EventGrid.SystemEvents.KeyVaultCertificateNearExpiryEventData", + "com.azure.messaging.eventgrid.systemevents.KeyVaultCertificateNewVersionCreatedEventData": "Microsoft.EventGrid.SystemEvents.KeyVaultCertificateNewVersionCreatedEventData", + "com.azure.messaging.eventgrid.systemevents.KeyVaultKeyExpiredEventData": "Microsoft.EventGrid.SystemEvents.KeyVaultKeyExpiredEventData", + "com.azure.messaging.eventgrid.systemevents.KeyVaultKeyNearExpiryEventData": "Microsoft.EventGrid.SystemEvents.KeyVaultKeyNearExpiryEventData", + "com.azure.messaging.eventgrid.systemevents.KeyVaultKeyNewVersionCreatedEventData": "Microsoft.EventGrid.SystemEvents.KeyVaultKeyNewVersionCreatedEventData", + "com.azure.messaging.eventgrid.systemevents.KeyVaultSecretExpiredEventData": "Microsoft.EventGrid.SystemEvents.KeyVaultSecretExpiredEventData", + "com.azure.messaging.eventgrid.systemevents.KeyVaultSecretNearExpiryEventData": "Microsoft.EventGrid.SystemEvents.KeyVaultSecretNearExpiryEventData", + "com.azure.messaging.eventgrid.systemevents.KeyVaultSecretNewVersionCreatedEventData": "Microsoft.EventGrid.SystemEvents.KeyVaultSecretNewVersionCreatedEventData", + "com.azure.messaging.eventgrid.systemevents.MachineLearningServicesDatasetDriftDetectedEventData": "Microsoft.EventGrid.SystemEvents.MachineLearningServicesDatasetDriftDetectedEventData", + "com.azure.messaging.eventgrid.systemevents.MachineLearningServicesModelDeployedEventData": "Microsoft.EventGrid.SystemEvents.MachineLearningServicesModelDeployedEventData", + "com.azure.messaging.eventgrid.systemevents.MachineLearningServicesModelRegisteredEventData": "Microsoft.EventGrid.SystemEvents.MachineLearningServicesModelRegisteredEventData", + "com.azure.messaging.eventgrid.systemevents.MachineLearningServicesRunCompletedEventData": "Microsoft.EventGrid.SystemEvents.MachineLearningServicesRunCompletedEventData", + "com.azure.messaging.eventgrid.systemevents.MachineLearningServicesRunStatusChangedEventData": "Microsoft.EventGrid.SystemEvents.MachineLearningServicesRunStatusChangedEventData", + "com.azure.messaging.eventgrid.systemevents.MapsGeofenceEnteredEventData": "Microsoft.EventGrid.SystemEvents.MapsGeofenceEnteredEventData", + "com.azure.messaging.eventgrid.systemevents.MapsGeofenceEventProperties": "Microsoft.EventGrid.SystemEvents.MapsGeofenceEventProperties", + "com.azure.messaging.eventgrid.systemevents.MapsGeofenceExitedEventData": "Microsoft.EventGrid.SystemEvents.MapsGeofenceExitedEventData", + "com.azure.messaging.eventgrid.systemevents.MapsGeofenceGeometry": "Microsoft.EventGrid.SystemEvents.MapsGeofenceGeometry", + "com.azure.messaging.eventgrid.systemevents.MapsGeofenceResultEventData": "Microsoft.EventGrid.SystemEvents.MapsGeofenceResultEventData", + "com.azure.messaging.eventgrid.systemevents.MicrosoftTeamsAppIdentifier": "Microsoft.EventGrid.SystemEvents.MicrosoftTeamsAppIdentifierModel", + "com.azure.messaging.eventgrid.systemevents.MicrosoftTeamsUserIdentifierModel": "Microsoft.EventGrid.SystemEvents.MicrosoftTeamsUserIdentifierModel", + "com.azure.messaging.eventgrid.systemevents.PhoneNumberIdentifierModel": "Microsoft.EventGrid.SystemEvents.PhoneNumberIdentifierModel", + "com.azure.messaging.eventgrid.systemevents.PolicyInsightsPolicyStateChangedEventData": "Microsoft.EventGrid.SystemEvents.PolicyInsightsPolicyStateChangedEventData", + "com.azure.messaging.eventgrid.systemevents.PolicyInsightsPolicyStateCreatedEventData": "Microsoft.EventGrid.SystemEvents.PolicyInsightsPolicyStateCreatedEventData", + "com.azure.messaging.eventgrid.systemevents.PolicyInsightsPolicyStateDeletedEventData": "Microsoft.EventGrid.SystemEvents.PolicyInsightsPolicyStateDeletedEventData", + "com.azure.messaging.eventgrid.systemevents.RecordingChannelType": "Microsoft.EventGrid.SystemEvents.recordingChannelType", + "com.azure.messaging.eventgrid.systemevents.RecordingContentType": "Microsoft.EventGrid.SystemEvents.recordingContentType", + "com.azure.messaging.eventgrid.systemevents.RecordingFormatType": "Microsoft.EventGrid.SystemEvents.recordingFormatType", + "com.azure.messaging.eventgrid.systemevents.RedisExportRdbCompletedEventData": "Microsoft.EventGrid.SystemEvents.RedisExportRDBCompletedEventData", + "com.azure.messaging.eventgrid.systemevents.RedisImportRdbCompletedEventData": "Microsoft.EventGrid.SystemEvents.RedisImportRDBCompletedEventData", + "com.azure.messaging.eventgrid.systemevents.RedisPatchingCompletedEventData": "Microsoft.EventGrid.SystemEvents.RedisPatchingCompletedEventData", + "com.azure.messaging.eventgrid.systemevents.RedisScalingCompletedEventData": "Microsoft.EventGrid.SystemEvents.RedisScalingCompletedEventData", + "com.azure.messaging.eventgrid.systemevents.ResourceActionCancelEventData": "Microsoft.EventGrid.SystemEvents.ResourceActionCancelEventData", + "com.azure.messaging.eventgrid.systemevents.ResourceActionFailureEventData": "Microsoft.EventGrid.SystemEvents.ResourceActionFailureEventData", + "com.azure.messaging.eventgrid.systemevents.ResourceActionSuccessEventData": "Microsoft.EventGrid.SystemEvents.ResourceActionSuccessEventData", + "com.azure.messaging.eventgrid.systemevents.ResourceAuthorization": "Microsoft.EventGrid.SystemEvents.ResourceAuthorization", + "com.azure.messaging.eventgrid.systemevents.ResourceDeleteCancelEventData": "Microsoft.EventGrid.SystemEvents.ResourceDeleteCancelEventData", + "com.azure.messaging.eventgrid.systemevents.ResourceDeleteFailureEventData": "Microsoft.EventGrid.SystemEvents.ResourceDeleteFailureEventData", + "com.azure.messaging.eventgrid.systemevents.ResourceDeleteSuccessEventData": "Microsoft.EventGrid.SystemEvents.ResourceDeleteSuccessEventData", + "com.azure.messaging.eventgrid.systemevents.ResourceHttpRequest": "Microsoft.EventGrid.SystemEvents.ResourceHttpRequest", + "com.azure.messaging.eventgrid.systemevents.ResourceNotificationsContainerServiceEventResourcesScheduledEventData": "Microsoft.EventGrid.SystemEvents.ResourceNotificationsContainerServiceEventResourcesScheduledEventData", + "com.azure.messaging.eventgrid.systemevents.ResourceNotificationsHealthResourcesAnnotatedEventData": "Microsoft.EventGrid.SystemEvents.ResourceNotificationsHealthResourcesAnnotatedEventData", + "com.azure.messaging.eventgrid.systemevents.ResourceNotificationsHealthResourcesAvailabilityStatusChangedEventData": "Microsoft.EventGrid.SystemEvents.ResourceNotificationsHealthResourcesAvailabilityStatusChangedEventData", + "com.azure.messaging.eventgrid.systemevents.ResourceNotificationsOperationalDetails": "Microsoft.EventGrid.SystemEvents.ResourceNotificationsOperationalDetails", + "com.azure.messaging.eventgrid.systemevents.ResourceNotificationsResourceDeletedDetails": "Microsoft.EventGrid.SystemEvents.ResourceNotificationsResourceDeletedDetails", + "com.azure.messaging.eventgrid.systemevents.ResourceNotificationsResourceDeletedEventData": "Microsoft.EventGrid.SystemEvents.ResourceNotificationsResourceDeletedEventData", + "com.azure.messaging.eventgrid.systemevents.ResourceNotificationsResourceManagementCreatedOrUpdatedEventData": "Microsoft.EventGrid.SystemEvents.ResourceNotificationsResourceManagementCreatedOrUpdatedEventData", + "com.azure.messaging.eventgrid.systemevents.ResourceNotificationsResourceManagementDeletedEventData": "Microsoft.EventGrid.SystemEvents.ResourceNotificationsResourceManagementDeletedEventData", + "com.azure.messaging.eventgrid.systemevents.ResourceNotificationsResourceUpdatedDetails": "Microsoft.EventGrid.SystemEvents.ResourceNotificationsResourceUpdatedDetails", + "com.azure.messaging.eventgrid.systemevents.ResourceNotificationsResourceUpdatedEventData": "Microsoft.EventGrid.SystemEvents.ResourceNotificationsResourceUpdatedEventData", + "com.azure.messaging.eventgrid.systemevents.ResourceWriteCancelEventData": "Microsoft.EventGrid.SystemEvents.ResourceWriteCancelEventData", + "com.azure.messaging.eventgrid.systemevents.ResourceWriteFailureEventData": "Microsoft.EventGrid.SystemEvents.ResourceWriteFailureEventData", + "com.azure.messaging.eventgrid.systemevents.ResourceWriteSuccessEventData": "Microsoft.EventGrid.SystemEvents.ResourceWriteSuccessEventData", + "com.azure.messaging.eventgrid.systemevents.ServiceBusActiveMessagesAvailablePeriodicNotificationsEventData": "Microsoft.EventGrid.SystemEvents.ServiceBusActiveMessagesAvailablePeriodicNotificationsEventData", + "com.azure.messaging.eventgrid.systemevents.ServiceBusActiveMessagesAvailableWithNoListenersEventData": "Microsoft.EventGrid.SystemEvents.ServiceBusActiveMessagesAvailableWithNoListenersEventData", + "com.azure.messaging.eventgrid.systemevents.ServiceBusDeadletterMessagesAvailablePeriodicNotificationsEventData": "Microsoft.EventGrid.SystemEvents.ServiceBusDeadletterMessagesAvailablePeriodicNotificationsEventData", + "com.azure.messaging.eventgrid.systemevents.ServiceBusDeadletterMessagesAvailableWithNoListenersEventData": "Microsoft.EventGrid.SystemEvents.ServiceBusDeadletterMessagesAvailableWithNoListenersEventData", + "com.azure.messaging.eventgrid.systemevents.SignalRServiceClientConnectionConnectedEventData": "Microsoft.EventGrid.SystemEvents.SignalRServiceClientConnectionConnectedEventData", + "com.azure.messaging.eventgrid.systemevents.SignalRServiceClientConnectionDisconnectedEventData": "Microsoft.EventGrid.SystemEvents.SignalRServiceClientConnectionDisconnectedEventData", + "com.azure.messaging.eventgrid.systemevents.StampKind": "Microsoft.EventGrid.SystemEvents.StampKind", + "com.azure.messaging.eventgrid.systemevents.StorageAsyncOperationInitiatedEventData": "Microsoft.EventGrid.SystemEvents.StorageAsyncOperationInitiatedEventData", + "com.azure.messaging.eventgrid.systemevents.StorageBlobAccessTier": "Microsoft.EventGrid.SystemEvents.StorageBlobAccessTier", + "com.azure.messaging.eventgrid.systemevents.StorageBlobCreatedEventData": "Microsoft.EventGrid.SystemEvents.StorageBlobCreatedEventData", + "com.azure.messaging.eventgrid.systemevents.StorageBlobDeletedEventData": "Microsoft.EventGrid.SystemEvents.StorageBlobDeletedEventData", + "com.azure.messaging.eventgrid.systemevents.StorageBlobInventoryPolicyCompletedEventData": "Microsoft.EventGrid.SystemEvents.StorageBlobInventoryPolicyCompletedEventData", + "com.azure.messaging.eventgrid.systemevents.StorageBlobRenamedEventData": "Microsoft.EventGrid.SystemEvents.StorageBlobRenamedEventData", + "com.azure.messaging.eventgrid.systemevents.StorageBlobTierChangedEventData": "Microsoft.EventGrid.SystemEvents.StorageBlobTierChangedEventData", + "com.azure.messaging.eventgrid.systemevents.StorageDirectoryCreatedEventData": "Microsoft.EventGrid.SystemEvents.StorageDirectoryCreatedEventData", + "com.azure.messaging.eventgrid.systemevents.StorageDirectoryDeletedEventData": "Microsoft.EventGrid.SystemEvents.StorageDirectoryDeletedEventData", + "com.azure.messaging.eventgrid.systemevents.StorageDirectoryRenamedEventData": "Microsoft.EventGrid.SystemEvents.StorageDirectoryRenamedEventData", + "com.azure.messaging.eventgrid.systemevents.StorageLifecycleCompletionStatus": "Microsoft.EventGrid.SystemEvents.StorageLifecycleCompletionStatus", + "com.azure.messaging.eventgrid.systemevents.StorageLifecyclePolicyActionSummaryDetail": "Microsoft.EventGrid.SystemEvents.StorageLifecyclePolicyActionSummaryDetail", + "com.azure.messaging.eventgrid.systemevents.StorageLifecyclePolicyCompletedEventData": "Microsoft.EventGrid.SystemEvents.StorageLifecyclePolicyCompletedEventData", + "com.azure.messaging.eventgrid.systemevents.StorageLifecyclePolicyRunSummary": "Microsoft.EventGrid.SystemEvents.StorageLifecyclePolicyRunSummary", + "com.azure.messaging.eventgrid.systemevents.StorageTaskAssignmentCompletedEventData": "Microsoft.EventGrid.SystemEvents.StorageTaskAssignmentCompletedEventData", + "com.azure.messaging.eventgrid.systemevents.StorageTaskAssignmentCompletedStatus": "Microsoft.EventGrid.SystemEvents.StorageTaskAssignmentCompletedStatus", + "com.azure.messaging.eventgrid.systemevents.StorageTaskAssignmentQueuedEventData": "Microsoft.EventGrid.SystemEvents.StorageTaskAssignmentQueuedEventData", + "com.azure.messaging.eventgrid.systemevents.StorageTaskCompletedEventData": "Microsoft.EventGrid.SystemEvents.StorageTaskCompletedEventData", + "com.azure.messaging.eventgrid.systemevents.StorageTaskCompletedStatus": "Microsoft.EventGrid.SystemEvents.StorageTaskCompletedStatus", + "com.azure.messaging.eventgrid.systemevents.StorageTaskQueuedEventData": "Microsoft.EventGrid.SystemEvents.StorageTaskQueuedEventData", + "com.azure.messaging.eventgrid.systemevents.SubscriptionDeletedEventData": "Microsoft.EventGrid.SystemEvents.SubscriptionDeletedEventData", + "com.azure.messaging.eventgrid.systemevents.SubscriptionValidationEventData": "Microsoft.EventGrid.SystemEvents.SubscriptionValidationEventData", + "com.azure.messaging.eventgrid.systemevents.SubscriptionValidationResponse": "Microsoft.EventGrid.SystemEvents.SubscriptionValidationResponse", + "com.azure.messaging.eventgrid.systemevents.WebAppServicePlanUpdatedEventData": "Microsoft.EventGrid.SystemEvents.WebAppServicePlanUpdatedEventData", + "com.azure.messaging.eventgrid.systemevents.WebAppServicePlanUpdatedEventDataSku": "Microsoft.EventGrid.SystemEvents.WebAppServicePlanUpdatedEventDataSku", + "com.azure.messaging.eventgrid.systemevents.WebAppUpdatedEventData": "Microsoft.EventGrid.SystemEvents.WebAppUpdatedEventData", + "com.azure.messaging.eventgrid.systemevents.WebBackupOperationCompletedEventData": "Microsoft.EventGrid.SystemEvents.WebBackupOperationCompletedEventData", + "com.azure.messaging.eventgrid.systemevents.WebBackupOperationFailedEventData": "Microsoft.EventGrid.SystemEvents.WebBackupOperationFailedEventData", + "com.azure.messaging.eventgrid.systemevents.WebBackupOperationStartedEventData": "Microsoft.EventGrid.SystemEvents.WebBackupOperationStartedEventData", + "com.azure.messaging.eventgrid.systemevents.WebRestoreOperationCompletedEventData": "Microsoft.EventGrid.SystemEvents.WebRestoreOperationCompletedEventData", + "com.azure.messaging.eventgrid.systemevents.WebRestoreOperationFailedEventData": "Microsoft.EventGrid.SystemEvents.WebRestoreOperationFailedEventData", + "com.azure.messaging.eventgrid.systemevents.WebRestoreOperationStartedEventData": "Microsoft.EventGrid.SystemEvents.WebRestoreOperationStartedEventData", + "com.azure.messaging.eventgrid.systemevents.WebSlotSwapCompletedEventData": "Microsoft.EventGrid.SystemEvents.WebSlotSwapCompletedEventData", + "com.azure.messaging.eventgrid.systemevents.WebSlotSwapFailedEventData": "Microsoft.EventGrid.SystemEvents.WebSlotSwapFailedEventData", + "com.azure.messaging.eventgrid.systemevents.WebSlotSwapStartedEventData": "Microsoft.EventGrid.SystemEvents.WebSlotSwapStartedEventData", + "com.azure.messaging.eventgrid.systemevents.WebSlotSwapWithPreviewCancelledEventData": "Microsoft.EventGrid.SystemEvents.WebSlotSwapWithPreviewCancelledEventData", + "com.azure.messaging.eventgrid.systemevents.WebSlotSwapWithPreviewStartedEventData": "Microsoft.EventGrid.SystemEvents.WebSlotSwapWithPreviewStartedEventData" + } +} diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/resources/azure-key-vault-certificates.properties b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/resources/azure-messaging-eventgrid.properties similarity index 100% rename from sdk/keyvault/azure-security-keyvault-certificates/src/main/resources/azure-key-vault-certificates.properties rename to sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/main/resources/azure-messaging-eventgrid.properties diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/samples/java/com/azure/messaging/eventgrid/ReadmeSamples.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/samples/java/com/azure/messaging/eventgrid/ReadmeSamples.java new file mode 100644 index 000000000000..fbfc2022cd37 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/samples/java/com/azure/messaging/eventgrid/ReadmeSamples.java @@ -0,0 +1,12 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.messaging.eventgrid; + +public final class ReadmeSamples { + public void readmeSamples() { + // BEGIN: com.azure.messaging.eventgrid.readme + // END: com.azure.messaging.eventgrid.readme + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/test/java/com/azure/messaging/eventgrid/systemevents/DeserializationTests.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/test/java/com/azure/messaging/eventgrid/systemevents/DeserializationTests.java new file mode 100644 index 000000000000..02788c450edd --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/test/java/com/azure/messaging/eventgrid/systemevents/DeserializationTests.java @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.core.util.BinaryData; +import com.azure.json.JsonProviders; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.io.InputStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class DeserializationTests { + + @Test + void getStorageDiagnostics() { + try { + String payload = getTestPayloadFromFile("storageBlobCreated.json"); + StorageBlobCreatedEventData storageBlobCreatedEventData + = StorageBlobCreatedEventData.fromJson(JsonProviders.createReader(payload)); + BinaryData data = storageBlobCreatedEventData.getStorageDiagnostics().get("batchId"); + assertEquals("\"23f68872-a006-0065-0049-9240f2000000\"", data.toString()); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private String getTestPayloadFromFile(String fileName) throws IOException { + ClassLoader classLoader = getClass().getClassLoader(); + try (InputStream inputStream = classLoader.getResourceAsStream("testJsons/" + fileName)) { + byte[] bytes = new byte[inputStream.available()]; + inputStream.read(bytes); + return new String(bytes); + } + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/test/java/com/azure/messaging/eventgrid/systemevents/SystemEventNamesTests.java b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/test/java/com/azure/messaging/eventgrid/systemevents/SystemEventNamesTests.java new file mode 100644 index 000000000000..abe3cd58b51d --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/test/java/com/azure/messaging/eventgrid/systemevents/SystemEventNamesTests.java @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.messaging.eventgrid.systemevents; + +import com.azure.messaging.eventgrid.SystemEventNames; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class SystemEventNamesTests { + + @Test + public void testParseEventName() { + // Arrange + String eventTypeName = "Microsoft.Storage.BlobCreated"; + + // Act + Class clazz = SystemEventNames.getSystemEventMappings().get(eventTypeName); + + // Assert + assertEquals(StorageBlobCreatedEventData.class, clazz); + } + +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/test/resources/testJsons/storageBlobCreated.json b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/test/resources/testJsons/storageBlobCreated.json new file mode 100644 index 000000000000..94789b32a284 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/src/test/resources/testJsons/storageBlobCreated.json @@ -0,0 +1,15 @@ +{ + "api": "PutBlob", + "clientRequestId": "89bc72c2-5dfe-4d9f-9706-43612c1bd01b", + "requestId": "beb21a5e-401e-002b-3749-928517000000", + "eTag": "0x8D96060BDA19D9D", + "contentType": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "contentLength": 17555, + "blobType": "BlockBlob", + "accessTier": "Hot", + "url": "https://jolovstorage.blob.core.windows.net/gaocontainer/Template1.xlsx", + "sequencer": "0000000000000000000000000000B00D0000000005b058d3", + "storageDiagnostics": { + "batchId": "23f68872-a006-0065-0049-9240f2000000" + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid-systemevents/tsp-location.yaml b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/tsp-location.yaml new file mode 100644 index 000000000000..14b68a3edfbc --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid-systemevents/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/eventgrid/Azure.Messaging.EventGrid.SystemEvents +commit: 8af03db33a90581edffb8a32fea562f36b7c61a8 +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/eventgrid/azure-messaging-eventgrid/CHANGELOG.md b/sdk/eventgrid/azure-messaging-eventgrid/CHANGELOG.md index b11bea30235c..70daeba7bb1a 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/CHANGELOG.md +++ b/sdk/eventgrid/azure-messaging-eventgrid/CHANGELOG.md @@ -1,5 +1,32 @@ # Release History +## 4.30.0-beta.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + +## 4.29.0 (2025-02-26) + +### Features Added +- Added `MessageId`, `MessageType`, and `Reaction` properties to the `AcsMessageReceivedEventData` event. +- Added the `Animated` property to `AcsMessageMediaContent` event. + +## 4.28.1 (2025-02-25) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`. +- Upgraded `azure-json` from `1.3.0` to version `1.4.0`. +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. + + ## 4.28.0 (2025-01-21) ### Features Added diff --git a/sdk/eventgrid/azure-messaging-eventgrid/README.md b/sdk/eventgrid/azure-messaging-eventgrid/README.md index 2384f8e28afe..5e6a536433cc 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/README.md +++ b/sdk/eventgrid/azure-messaging-eventgrid/README.md @@ -82,7 +82,7 @@ add the direct dependency to your project as follows. com.azure azure-messaging-eventgrid - 4.28.0 + 4.30.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -514,4 +514,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct](https://ope [CloudEvent]: https://github.com/cloudevents/spec/blob/master/spec.md -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Feventgrid%2Fazure-messaging-eventgrid%2FREADME.png) + diff --git a/sdk/eventgrid/azure-messaging-eventgrid/migration-guide.md b/sdk/eventgrid/azure-messaging-eventgrid/migration-guide.md index cd1f48729fae..8be259f32535 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/migration-guide.md +++ b/sdk/eventgrid/azure-messaging-eventgrid/migration-guide.md @@ -187,10 +187,10 @@ More examples can be found at: - [Event Grid samples][README-Samples] -[EventGridPublisherClientBuilder]: https://azuresdkdocs.blob.core.windows.net/$web/java/azure-messaging-eventgrid/latest/com/azure/messaging/eventgrid/EventGridPublisherClientBuilder.html -[EventGridPublisherClient]: https://azuresdkdocs.blob.core.windows.net/$web/java/azure-messaging-eventgrid/latest/com/azure/messaging/eventgrid/EventGridPublisherClient.html -[EventGridPublisherAsyncClient]: https://azuresdkdocs.blob.core.windows.net/$web/java/azure-messaging-eventgrid/latest/com/azure/messaging/eventgrid/EventGridPublisherAsyncClient.html -[EventGridEvent]: https://azuresdkdocs.blob.core.windows.net/$web/java/azure-messaging-eventgrid/latest/com/azure/messaging/eventgrid/EventGridEvent.html +[EventGridPublisherClientBuilder]: https://azuresdkdocs.z19.web.core.windows.net/java/azure-messaging-eventgrid/latest/com/azure/messaging/eventgrid/EventGridPublisherClientBuilder.html +[EventGridPublisherClient]: https://azuresdkdocs.z19.web.core.windows.net/java/azure-messaging-eventgrid/latest/com/azure/messaging/eventgrid/EventGridPublisherClient.html +[EventGridPublisherAsyncClient]: https://azuresdkdocs.z19.web.core.windows.net/java/azure-messaging-eventgrid/latest/com/azure/messaging/eventgrid/EventGridPublisherAsyncClient.html +[EventGridEvent]: https://azuresdkdocs.z19.web.core.windows.net/java/azure-messaging-eventgrid/latest/com/azure/messaging/eventgrid/EventGridEvent.html [Guidelines]: https://azure.github.io/azure-sdk/general_introduction.html [GuidelinesJava]: https://azure.github.io/azure-sdk/java_introduction.html [GuidelinesJavaDesign]: https://azure.github.io/azure-sdk/java_introduction.html#namespaces @@ -198,4 +198,5 @@ More examples can be found at: [README-Samples]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/README.md [README]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/eventgrid/azure-messaging-eventgrid/README.md -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Feventgrid%2Fazure-messaging-eventgrid%2Fmigration-guide.png) + + diff --git a/sdk/eventgrid/azure-messaging-eventgrid/pom.xml b/sdk/eventgrid/azure-messaging-eventgrid/pom.xml index 7152b5a49d1a..e382e426534a 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/pom.xml +++ b/sdk/eventgrid/azure-messaging-eventgrid/pom.xml @@ -12,7 +12,7 @@ com.azure azure-messaging-eventgrid - 4.28.0 + 4.30.0-beta.1 jar Microsoft Azure SDK for eventgrid @@ -75,36 +75,36 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-storage-queue - 12.24.0 + 12.24.1 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageDeliveryStatusUpdatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageDeliveryStatusUpdatedEventData.java index 0553ba9fdaf2..2b1b15766a54 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageDeliveryStatusUpdatedEventData.java +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageDeliveryStatusUpdatedEventData.java @@ -154,6 +154,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @param jsonReader The JsonReader being read. * @return An instance of AcsMessageDeliveryStatusUpdatedEventData 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 AcsMessageDeliveryStatusUpdatedEventData. */ public static AcsMessageDeliveryStatusUpdatedEventData fromJson(JsonReader jsonReader) throws IOException { diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageEventData.java b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageEventData.java index 1a34295186b1..6847d78e64c9 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageEventData.java +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageEventData.java @@ -147,6 +147,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @param jsonReader The JsonReader being read. * @return An instance of AcsMessageEventData 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 AcsMessageEventData. */ public static AcsMessageEventData fromJson(JsonReader jsonReader) throws IOException { diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageMediaContent.java b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageMediaContent.java index 6e4207ca48b4..9f7418442963 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageMediaContent.java +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageMediaContent.java @@ -36,6 +36,11 @@ public final class AcsMessageMediaContent implements JsonSerializable { + /* + * WhatsApp message ID of message you want to apply the emoji to. + */ + private String messageId; + + /* + * Unicode escape sequence of the emoji. + */ + private String emoji; + + /** + * Creates an instance of AcsMessageReactionContent class. + */ + public AcsMessageReactionContent() { + } + + /** + * Get the messageId property: WhatsApp message ID of message you want to apply the emoji to. + * + * @return the messageId value. + */ + public String getMessageId() { + return this.messageId; + } + + /** + * Set the messageId property: WhatsApp message ID of message you want to apply the emoji to. + * + * @param messageId the messageId value to set. + * @return the AcsMessageReactionContent object itself. + */ + public AcsMessageReactionContent setMessageId(String messageId) { + this.messageId = messageId; + return this; + } + + /** + * Get the emoji property: Unicode escape sequence of the emoji. + * + * @return the emoji value. + */ + public String getEmoji() { + return this.emoji; + } + + /** + * Set the emoji property: Unicode escape sequence of the emoji. + * + * @param emoji the emoji value to set. + * @return the AcsMessageReactionContent object itself. + */ + public AcsMessageReactionContent setEmoji(String emoji) { + this.emoji = emoji; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("messageId", this.messageId); + jsonWriter.writeStringField("emoji", this.emoji); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AcsMessageReactionContent from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AcsMessageReactionContent 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 AcsMessageReactionContent. + */ + public static AcsMessageReactionContent fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AcsMessageReactionContent deserializedAcsMessageReactionContent = new AcsMessageReactionContent(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("messageId".equals(fieldName)) { + deserializedAcsMessageReactionContent.messageId = reader.getString(); + } else if ("emoji".equals(fieldName)) { + deserializedAcsMessageReactionContent.emoji = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAcsMessageReactionContent; + }); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageReceivedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageReceivedEventData.java index 4fb368f8b3cc..644cb08c7e07 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageReceivedEventData.java +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMessageReceivedEventData.java @@ -25,16 +25,31 @@ public final class AcsMessageReceivedEventData extends AcsMessageEventData { */ private String content; + /* + * Message ID. Format is Guid as string. + */ + private String messageId; + /* * The received message channel Kind */ private AcsMessageChannelKind channelKind; + /* + * WhatsApp Message Type + */ + private String messageType; + /* * The received message media content */ private AcsMessageMediaContent mediaContent; + /* + * The received message reaction content + */ + private AcsMessageReactionContent reaction; + /* * The received message context */ @@ -76,6 +91,26 @@ public AcsMessageReceivedEventData setContent(String content) { return this; } + /** + * Get the messageId property: Message ID. Format is Guid as string. + * + * @return the messageId value. + */ + public String getMessageId() { + return this.messageId; + } + + /** + * Set the messageId property: Message ID. Format is Guid as string. + * + * @param messageId the messageId value to set. + * @return the AcsMessageReceivedEventData object itself. + */ + public AcsMessageReceivedEventData setMessageId(String messageId) { + this.messageId = messageId; + return this; + } + /** * Get the channelKind property: The received message channel Kind. * @@ -96,6 +131,26 @@ public AcsMessageReceivedEventData setChannelKind(AcsMessageChannelKind channelK return this; } + /** + * Get the messageType property: WhatsApp Message Type. + * + * @return the messageType value. + */ + public String getMessageType() { + return this.messageType; + } + + /** + * Set the messageType property: WhatsApp Message Type. + * + * @param messageType the messageType value to set. + * @return the AcsMessageReceivedEventData object itself. + */ + public AcsMessageReceivedEventData setMessageType(String messageType) { + this.messageType = messageType; + return this; + } + /** * Get the mediaContent property: The received message media content. * @@ -116,6 +171,26 @@ public AcsMessageReceivedEventData setMediaContent(AcsMessageMediaContent mediaC return this; } + /** + * Get the reaction property: The received message reaction content. + * + * @return the reaction value. + */ + public AcsMessageReactionContent getReaction() { + return this.reaction; + } + + /** + * Set the reaction property: The received message reaction content. + * + * @param reaction the reaction value to set. + * @return the AcsMessageReceivedEventData object itself. + */ + public AcsMessageReceivedEventData setReaction(AcsMessageReactionContent reaction) { + this.reaction = reaction; + return this; + } + /** * Get the context property: The received message context. * @@ -216,9 +291,12 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(getReceivedTimestamp())); jsonWriter.writeJsonField("error", getError()); + jsonWriter.writeStringField("messageType", this.messageType); jsonWriter.writeStringField("content", this.content); + jsonWriter.writeStringField("messageId", this.messageId); jsonWriter.writeStringField("channelType", this.channelKind == null ? null : this.channelKind.toString()); jsonWriter.writeJsonField("media", this.mediaContent); + jsonWriter.writeJsonField("reaction", this.reaction); jsonWriter.writeJsonField("context", this.context); jsonWriter.writeJsonField("button", this.button); jsonWriter.writeJsonField("interactive", this.interactiveContent); @@ -231,6 +309,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @param jsonReader The JsonReader being read. * @return An instance of AcsMessageReceivedEventData 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 AcsMessageReceivedEventData. */ public static AcsMessageReceivedEventData fromJson(JsonReader jsonReader) throws IOException { @@ -248,13 +327,19 @@ public static AcsMessageReceivedEventData fromJson(JsonReader jsonReader) throws .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString()))); } else if ("error".equals(fieldName)) { deserializedAcsMessageReceivedEventData.setError(AcsMessageChannelEventError.fromJson(reader)); + } else if ("messageType".equals(fieldName)) { + deserializedAcsMessageReceivedEventData.messageType = reader.getString(); } else if ("content".equals(fieldName)) { deserializedAcsMessageReceivedEventData.content = reader.getString(); + } else if ("messageId".equals(fieldName)) { + deserializedAcsMessageReceivedEventData.messageId = reader.getString(); } else if ("channelType".equals(fieldName)) { deserializedAcsMessageReceivedEventData.channelKind = AcsMessageChannelKind.fromString(reader.getString()); } else if ("media".equals(fieldName)) { deserializedAcsMessageReceivedEventData.mediaContent = AcsMessageMediaContent.fromJson(reader); + } else if ("reaction".equals(fieldName)) { + deserializedAcsMessageReceivedEventData.reaction = AcsMessageReactionContent.fromJson(reader); } else if ("context".equals(fieldName)) { deserializedAcsMessageReceivedEventData.context = AcsMessageContext.fromJson(reader); } else if ("button".equals(fieldName)) { diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMicrosoftTeamsAppIdentifier.java b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMicrosoftTeamsAppIdentifier.java index f7656cff033f..0f72389ec551 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMicrosoftTeamsAppIdentifier.java +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsMicrosoftTeamsAppIdentifier.java @@ -27,7 +27,7 @@ public final class AcsMicrosoftTeamsAppIdentifier implements JsonSerializable { - AcsMicrosoftTeamsAppIdentifier deserializedMicrosoftTeamsAppIdentifier + AcsMicrosoftTeamsAppIdentifier deserializedAcsMicrosoftTeamsAppIdentifier = new AcsMicrosoftTeamsAppIdentifier(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("appId".equals(fieldName)) { - deserializedMicrosoftTeamsAppIdentifier.appId = reader.getString(); + deserializedAcsMicrosoftTeamsAppIdentifier.appId = reader.getString(); } else if ("cloud".equals(fieldName)) { - deserializedMicrosoftTeamsAppIdentifier.cloud + deserializedAcsMicrosoftTeamsAppIdentifier.cloud = CommunicationCloudEnvironmentModel.fromString(reader.getString()); } else { reader.skipChildren(); } } - return deserializedMicrosoftTeamsAppIdentifier; + return deserializedAcsMicrosoftTeamsAppIdentifier; }); } } diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRecordingFileStatusUpdatedEventData.java b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRecordingFileStatusUpdatedEventData.java index e57f0e96361a..da8c4e1d934f 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRecordingFileStatusUpdatedEventData.java +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/AcsRecordingFileStatusUpdatedEventData.java @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. - package com.azure.messaging.eventgrid.systemevents; import com.azure.core.annotation.Fluent; @@ -21,6 +20,7 @@ @Fluent public final class AcsRecordingFileStatusUpdatedEventData implements JsonSerializable { + /* * The details of recording storage information */ @@ -64,7 +64,7 @@ public AcsRecordingFileStatusUpdatedEventData() { /** * Get the recordingStorageInfo property: The details of recording storage information. - * + * * @return the recordingStorageInfo value. */ public AcsRecordingStorageInfoProperties getRecordingStorageInfo() { @@ -73,7 +73,7 @@ public AcsRecordingStorageInfoProperties getRecordingStorageInfo() { /** * Set the recordingStorageInfo property: The details of recording storage information. - * + * * @param recordingStorageInfo the recordingStorageInfo value to set. * @return the AcsRecordingFileStatusUpdatedEventData object itself. */ @@ -85,7 +85,7 @@ public AcsRecordingStorageInfoProperties getRecordingStorageInfo() { /** * Get the recordingStartTime property: The time at which the recording started. - * + * * @return the recordingStartTime value. */ public OffsetDateTime getRecordingStartTime() { @@ -94,7 +94,7 @@ public OffsetDateTime getRecordingStartTime() { /** * Set the recordingStartTime property: The time at which the recording started. - * + * * @param recordingStartTime the recordingStartTime value to set. * @return the AcsRecordingFileStatusUpdatedEventData object itself. */ @@ -105,7 +105,7 @@ public AcsRecordingFileStatusUpdatedEventData setRecordingStartTime(OffsetDateTi /** * Get the recordingDuration property: The recording duration. - * + * * @return the recordingDuration value. */ public Duration getRecordingDuration() { @@ -117,7 +117,7 @@ public Duration getRecordingDuration() { /** * Set the recordingDuration property: The recording duration. - * + * * @param recordingDuration the recordingDuration value to set. * @return the AcsRecordingFileStatusUpdatedEventData object itself. */ @@ -132,7 +132,7 @@ public AcsRecordingFileStatusUpdatedEventData setRecordingDuration(Duration reco /** * Get the recordingContentType property: The recording content type- AudioVideo, or Audio. - * + * * @return the recordingContentType value. */ public RecordingContentType getRecordingContentType() { @@ -141,7 +141,7 @@ public RecordingContentType getRecordingContentType() { /** * Set the recordingContentType property: The recording content type- AudioVideo, or Audio. - * + * * @param recordingContentType the recordingContentType value to set. * @return the AcsRecordingFileStatusUpdatedEventData object itself. */ @@ -152,7 +152,7 @@ public AcsRecordingFileStatusUpdatedEventData setRecordingContentType(RecordingC /** * Get the recordingChannelType property: The recording channel type - Mixed, Unmixed. - * + * * @return the recordingChannelType value. */ public RecordingChannelType getRecordingChannelType() { @@ -161,7 +161,7 @@ public RecordingChannelType getRecordingChannelType() { /** * Set the recordingChannelType property: The recording channel type - Mixed, Unmixed. - * + * * @param recordingChannelType the recordingChannelType value to set. * @return the AcsRecordingFileStatusUpdatedEventData object itself. */ @@ -172,7 +172,7 @@ public AcsRecordingFileStatusUpdatedEventData setRecordingChannelType(RecordingC /** * Get the recordingFormatType property: The recording format type - Mp4, Mp3, Wav. - * + * * @return the recordingFormatType value. */ public RecordingFormatType getRecordingFormatType() { @@ -181,7 +181,7 @@ public RecordingFormatType getRecordingFormatType() { /** * Set the recordingFormatType property: The recording format type - Mp4, Mp3, Wav. - * + * * @param recordingFormatType the recordingFormatType value to set. * @return the AcsRecordingFileStatusUpdatedEventData object itself. */ @@ -192,7 +192,7 @@ public AcsRecordingFileStatusUpdatedEventData setRecordingFormatType(RecordingFo /** * Get the sessionEndReason property: The reason for ending recording session. - * + * * @return the sessionEndReason value. */ public String getSessionEndReason() { @@ -201,7 +201,7 @@ public String getSessionEndReason() { /** * Set the sessionEndReason property: The reason for ending recording session. - * + * * @param sessionEndReason the sessionEndReason value to set. * @return the AcsRecordingFileStatusUpdatedEventData object itself. */ @@ -234,7 +234,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of AcsRecordingFileStatusUpdatedEventData from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of AcsRecordingFileStatusUpdatedEventData if the JsonReader was pointing to an instance of * it, or null if it was pointing to JSON null. @@ -247,7 +247,6 @@ public static AcsRecordingFileStatusUpdatedEventData fromJson(JsonReader jsonRea while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("recordingStorageInfo".equals(fieldName)) { deserializedAcsRecordingFileStatusUpdatedEventData.recordingStorageInfo = AcsRecordingStorageInfoProperties.fromJson(reader); @@ -272,7 +271,6 @@ public static AcsRecordingFileStatusUpdatedEventData fromJson(JsonReader jsonRea reader.skipChildren(); } } - return deserializedAcsRecordingFileStatusUpdatedEventData; }); } diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/MediaLiveEventChannelArchiveHeartbeatEventData.java b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/MediaLiveEventChannelArchiveHeartbeatEventData.java index 308e400f4197..8868c36e8b0c 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/MediaLiveEventChannelArchiveHeartbeatEventData.java +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/MediaLiveEventChannelArchiveHeartbeatEventData.java @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. - package com.azure.messaging.eventgrid.systemevents; import com.azure.core.annotation.Immutable; @@ -20,6 +19,7 @@ @Immutable public final class MediaLiveEventChannelArchiveHeartbeatEventData implements JsonSerializable { + /* * Gets the channel latency in ms. */ @@ -29,7 +29,6 @@ public final class MediaLiveEventChannelArchiveHeartbeatEventData * Gets the latency result code. */ private String latencyResultCode; - static final ClientLogger LOGGER = new ClientLogger(MediaLiveEventChannelArchiveHeartbeatEventData.class); /** * Creates an instance of MediaLiveEventChannelArchiveHeartbeatEventData class. @@ -39,7 +38,7 @@ public MediaLiveEventChannelArchiveHeartbeatEventData() { /** * Gets the duration of channel latency. - * + * * @return the duration of channel latency. */ public Duration getChannelLatency() { @@ -58,7 +57,7 @@ public Duration getChannelLatency() { /** * Get the latencyResultCode property: Gets the latency result code. - * + * * @return the latencyResultCode value. */ public String getLatencyResultCode() { @@ -76,7 +75,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of MediaLiveEventChannelArchiveHeartbeatEventData from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of MediaLiveEventChannelArchiveHeartbeatEventData if the JsonReader was pointing to an * instance of it, or null if it was pointing to JSON null. @@ -90,7 +89,6 @@ public static MediaLiveEventChannelArchiveHeartbeatEventData fromJson(JsonReader while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("channelLatencyMs".equals(fieldName)) { deserializedMediaLiveEventChannelArchiveHeartbeatEventData.channelLatencyMs = reader.getString(); } else if ("latencyResultCode".equals(fieldName)) { @@ -99,8 +97,9 @@ public static MediaLiveEventChannelArchiveHeartbeatEventData fromJson(JsonReader reader.skipChildren(); } } - return deserializedMediaLiveEventChannelArchiveHeartbeatEventData; }); } + + private static final ClientLogger LOGGER = new ClientLogger(MediaLiveEventChannelArchiveHeartbeatEventData.class); } diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/MediaLiveEventIngestHeartbeatEventData.java b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/MediaLiveEventIngestHeartbeatEventData.java index d1914273f370..e06501bea51b 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/MediaLiveEventIngestHeartbeatEventData.java +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/systemevents/MediaLiveEventIngestHeartbeatEventData.java @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. - package com.azure.messaging.eventgrid.systemevents; import com.azure.core.annotation.Immutable; @@ -20,6 +19,7 @@ @Immutable public final class MediaLiveEventIngestHeartbeatEventData implements JsonSerializable { + /* * Gets the type of the track (Audio / Video). */ @@ -99,7 +99,6 @@ public final class MediaLiveEventIngestHeartbeatEventData * Gets a value indicating whether preview is healthy or not. */ private Boolean healthy; - static final ClientLogger LOGGER = new ClientLogger(MediaLiveEventIngestHeartbeatEventData.class); /** * Creates an instance of MediaLiveEventIngestHeartbeatEventData class. @@ -109,7 +108,7 @@ public MediaLiveEventIngestHeartbeatEventData() { /** * Get the trackType property: Gets the type of the track (Audio / Video). - * + * * @return the trackType value. */ public String getTrackType() { @@ -118,7 +117,7 @@ public String getTrackType() { /** * Get the trackName property: Gets the track name. - * + * * @return the trackName value. */ public String getTrackName() { @@ -127,7 +126,7 @@ public String getTrackName() { /** * Get the transcriptionLanguage property: Gets the Live Transcription language. - * + * * @return the transcriptionLanguage value. */ public String getTranscriptionLanguage() { @@ -136,7 +135,7 @@ public String getTranscriptionLanguage() { /** * Get the transcriptionState property: Gets the Live Transcription state. - * + * * @return the transcriptionState value. */ public String getTranscriptionState() { @@ -145,7 +144,7 @@ public String getTranscriptionState() { /** * Get the bitrate property: Gets the bitrate of the track. - * + * * @return the bitrate value. */ public Long getBitrate() { @@ -154,7 +153,7 @@ public Long getBitrate() { /** * Get the incomingBitrate property: Gets the incoming bitrate. - * + * * @return the incomingBitrate value. */ public Long getIncomingBitrate() { @@ -163,7 +162,7 @@ public Long getIncomingBitrate() { /** * Get the ingestDriftValue property: Gets the track ingest drift value. - * + * * @return the ingestDriftValue value. */ public Integer getIngestDriftValue() { @@ -180,7 +179,7 @@ public Integer getIngestDriftValue() { /** * Get the lastFragmentArrivalTime property: Gets the arrival UTC time of the last fragment. - * + * * @return the lastFragmentArrivalTime value. */ public OffsetDateTime getLastFragmentArrivalTime() { @@ -189,7 +188,7 @@ public OffsetDateTime getLastFragmentArrivalTime() { /** * Get the lastTimestamp property: Gets the last timestamp. - * + * * @return the lastTimestamp value. */ public String getLastTimestamp() { @@ -198,7 +197,7 @@ public String getLastTimestamp() { /** * Get the timescale property: Gets the timescale of the last timestamp. - * + * * @return the timescale value. */ public String getTimescale() { @@ -207,7 +206,7 @@ public String getTimescale() { /** * Get the overlapCount property: Gets the fragment Overlap count. - * + * * @return the overlapCount value. */ public Long getOverlapCount() { @@ -216,7 +215,7 @@ public Long getOverlapCount() { /** * Get the discontinuityCount property: Gets the fragment Discontinuity count. - * + * * @return the discontinuityCount value. */ public Long getDiscontinuityCount() { @@ -225,7 +224,7 @@ public Long getDiscontinuityCount() { /** * Get the nonincreasingCount property: Gets Non increasing count. - * + * * @return the nonincreasingCount value. */ public Long getNonincreasingCount() { @@ -234,7 +233,7 @@ public Long getNonincreasingCount() { /** * Get the unexpectedBitrate property: Gets a value indicating whether unexpected bitrate is present or not. - * + * * @return the unexpectedBitrate value. */ public Boolean isUnexpectedBitrate() { @@ -243,7 +242,7 @@ public Boolean isUnexpectedBitrate() { /** * Get the state property: Gets the state of the live event. - * + * * @return the state value. */ public String getState() { @@ -252,7 +251,7 @@ public String getState() { /** * Get the healthy property: Gets a value indicating whether preview is healthy or not. - * + * * @return the healthy value. */ public Boolean isHealthy() { @@ -270,7 +269,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of MediaLiveEventIngestHeartbeatEventData from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of MediaLiveEventIngestHeartbeatEventData if the JsonReader was pointing to an instance of * it, or null if it was pointing to JSON null. @@ -283,7 +282,6 @@ public static MediaLiveEventIngestHeartbeatEventData fromJson(JsonReader jsonRea while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("trackType".equals(fieldName)) { deserializedMediaLiveEventIngestHeartbeatEventData.trackType = reader.getString(); } else if ("trackName".equals(fieldName)) { @@ -327,8 +325,9 @@ public static MediaLiveEventIngestHeartbeatEventData fromJson(JsonReader jsonRea reader.skipChildren(); } } - return deserializedMediaLiveEventIngestHeartbeatEventData; }); } + + private static final ClientLogger LOGGER = new ClientLogger(MediaLiveEventIngestHeartbeatEventData.class); } diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/README.md b/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/README.md index afd9945ecfdb..65a779c9ea6e 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/README.md +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/README.md @@ -69,4 +69,4 @@ Guidelines](https://github.com/Azure/azure-sdk-for-java/blob/main/CONTRIBUTING.m [DeserializeSystemEvent]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/samples/ProcessSystemEvents.java [GenerateSasToken]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/samples/GenerateSasToken.java -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Feventgrid%2Fazure-messaging-eventgrid%2Fsrc%2Fsamples%2FREADME.png) + diff --git a/sdk/eventgrid/azure-messaging-eventgrid/swagger/README.md b/sdk/eventgrid/azure-messaging-eventgrid/swagger/README.md index 55c4eba5f51b..3d3ebc190032 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/swagger/README.md +++ b/sdk/eventgrid/azure-messaging-eventgrid/swagger/README.md @@ -74,7 +74,7 @@ directive: to: RedisExportRdbCompletedEventData - rename-model: from: MicrosoftTeamsAppIdentifierModel - to: MicrosoftTeamsAppIdentifier + to: AcsMicrosoftTeamsAppIdentifier - where-model: AcsIncomingCallEventData rename-property: from: onBehalfOfCallee @@ -86,34 +86,34 @@ custom-types: CloudEvent,EventGridEvent,AcsRouterCommunicationError,AcsMessageCh input-file: -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/c18f249c85d002b7b2ddcc36b648512b574e1f4a/specification/eventgrid/data-plane/Microsoft.Storage/stable/2018-01-01/Storage.json -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/c18f249c85d002b7b2ddcc36b648512b574e1f4a/specification/eventgrid/data-plane/Microsoft.EventHub/stable/2018-01-01/EventHub.json -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/c18f249c85d002b7b2ddcc36b648512b574e1f4a/specification/eventgrid/data-plane/Microsoft.Resources/stable/2018-01-01/Resources.json -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/c18f249c85d002b7b2ddcc36b648512b574e1f4a/specification/eventgrid/data-plane/Microsoft.EventGrid/stable/2018-01-01/EventGrid.json -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/c18f249c85d002b7b2ddcc36b648512b574e1f4a/specification/eventgrid/data-plane/Microsoft.EventGrid/stable/2018-01-01/SystemEvents.json -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/c18f249c85d002b7b2ddcc36b648512b574e1f4a/specification/eventgrid/data-plane/Microsoft.Devices/stable/2018-01-01/IotHub.json -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/c18f249c85d002b7b2ddcc36b648512b574e1f4a/specification/eventgrid/data-plane/Microsoft.ContainerRegistry/stable/2018-01-01/ContainerRegistry.json -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/c18f249c85d002b7b2ddcc36b648512b574e1f4a/specification/eventgrid/data-plane/Microsoft.ServiceBus/stable/2018-01-01/ServiceBus.json -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/c18f249c85d002b7b2ddcc36b648512b574e1f4a/specification/eventgrid/data-plane/Microsoft.Media/stable/2018-01-01/MediaServices.json -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/c18f249c85d002b7b2ddcc36b648512b574e1f4a/specification/eventgrid/data-plane/Microsoft.Maps/stable/2018-01-01/Maps.json -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/c18f249c85d002b7b2ddcc36b648512b574e1f4a/specification/eventgrid/data-plane/Microsoft.AppConfiguration/stable/2018-01-01/AppConfiguration.json -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/c18f249c85d002b7b2ddcc36b648512b574e1f4a/specification/eventgrid/data-plane/Microsoft.SignalRService/stable/2018-01-01/SignalRService.json -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/c18f249c85d002b7b2ddcc36b648512b574e1f4a/specification/eventgrid/data-plane/Microsoft.KeyVault/stable/2018-01-01/KeyVault.json -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/c18f249c85d002b7b2ddcc36b648512b574e1f4a/specification/eventgrid/data-plane/Microsoft.MachineLearningServices/stable/2018-01-01/MachineLearningServices.json -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/c18f249c85d002b7b2ddcc36b648512b574e1f4a/specification/eventgrid/data-plane/Microsoft.Cache/stable/2018-01-01/RedisCache.json -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/c18f249c85d002b7b2ddcc36b648512b574e1f4a/specification/eventgrid/data-plane/Microsoft.Web/stable/2018-01-01/Web.json -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/c18f249c85d002b7b2ddcc36b648512b574e1f4a/specification/eventgrid/data-plane/Microsoft.Communication/stable/2018-01-01/AzureCommunicationServices.json -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/c18f249c85d002b7b2ddcc36b648512b574e1f4a/specification/eventgrid/data-plane/Microsoft.PolicyInsights/stable/2018-01-01/PolicyInsights.json -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/c18f249c85d002b7b2ddcc36b648512b574e1f4a/specification/eventgrid/data-plane/Microsoft.ContainerService/stable/2018-01-01/ContainerService.json -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/c18f249c85d002b7b2ddcc36b648512b574e1f4a/specification/eventgrid/data-plane/Microsoft.ApiManagement/stable/2018-01-01/APIManagement.json -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/c18f249c85d002b7b2ddcc36b648512b574e1f4a/specification/eventgrid/data-plane/Microsoft.HealthcareApis/stable/2018-01-01/HealthcareApis.json -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/c18f249c85d002b7b2ddcc36b648512b574e1f4a/specification/eventgrid/data-plane/Microsoft.DataBox/stable/2018-01-01/DataBox.json -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/c18f249c85d002b7b2ddcc36b648512b574e1f4a/specification/eventgrid/data-plane/Microsoft.ResourceNotifications/stable/2018-01-01/common.json -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/c18f249c85d002b7b2ddcc36b648512b574e1f4a/specification/eventgrid/data-plane/Microsoft.ResourceNotifications/stable/2018-01-01/HealthResources.json -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/c18f249c85d002b7b2ddcc36b648512b574e1f4a/specification/eventgrid/data-plane/Microsoft.ResourceNotifications/stable/2018-01-01/Resources.json -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/c18f249c85d002b7b2ddcc36b648512b574e1f4a/specification/eventgrid/data-plane/Microsoft.AVS/stable/2018-01-01/PrivateCloud.json -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/c18f249c85d002b7b2ddcc36b648512b574e1f4a/specification/eventgrid/data-plane/Microsoft.ApiCenter/stable/2018-01-01/ApiCenter.json -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/c18f249c85d002b7b2ddcc36b648512b574e1f4a/specification/eventgrid/data-plane/Microsoft.ResourceNotifications/stable/2018-01-01/ContainerServiceEventResources.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af03db33a90581edffb8a32fea562f36b7c61a8/specification/eventgrid/data-plane/Microsoft.Storage/stable/2018-01-01/Storage.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af03db33a90581edffb8a32fea562f36b7c61a8/specification/eventgrid/data-plane/Microsoft.EventHub/stable/2018-01-01/EventHub.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af03db33a90581edffb8a32fea562f36b7c61a8/specification/eventgrid/data-plane/Microsoft.Resources/stable/2018-01-01/Resources.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af03db33a90581edffb8a32fea562f36b7c61a8/specification/eventgrid/data-plane/Microsoft.EventGrid/stable/2018-01-01/EventGrid.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af03db33a90581edffb8a32fea562f36b7c61a8/specification/eventgrid/data-plane/Microsoft.EventGrid/stable/2018-01-01/SystemEvents.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af03db33a90581edffb8a32fea562f36b7c61a8/specification/eventgrid/data-plane/Microsoft.Devices/stable/2018-01-01/IotHub.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af03db33a90581edffb8a32fea562f36b7c61a8/specification/eventgrid/data-plane/Microsoft.ContainerRegistry/stable/2018-01-01/ContainerRegistry.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af03db33a90581edffb8a32fea562f36b7c61a8/specification/eventgrid/data-plane/Microsoft.ServiceBus/stable/2018-01-01/ServiceBus.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af03db33a90581edffb8a32fea562f36b7c61a8/specification/eventgrid/data-plane/Microsoft.Media/stable/2018-01-01/MediaServices.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af03db33a90581edffb8a32fea562f36b7c61a8/specification/eventgrid/data-plane/Microsoft.Maps/stable/2018-01-01/Maps.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af03db33a90581edffb8a32fea562f36b7c61a8/specification/eventgrid/data-plane/Microsoft.AppConfiguration/stable/2018-01-01/AppConfiguration.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af03db33a90581edffb8a32fea562f36b7c61a8/specification/eventgrid/data-plane/Microsoft.SignalRService/stable/2018-01-01/SignalRService.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af03db33a90581edffb8a32fea562f36b7c61a8/specification/eventgrid/data-plane/Microsoft.KeyVault/stable/2018-01-01/KeyVault.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af03db33a90581edffb8a32fea562f36b7c61a8/specification/eventgrid/data-plane/Microsoft.MachineLearningServices/stable/2018-01-01/MachineLearningServices.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af03db33a90581edffb8a32fea562f36b7c61a8/specification/eventgrid/data-plane/Microsoft.Cache/stable/2018-01-01/RedisCache.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af03db33a90581edffb8a32fea562f36b7c61a8/specification/eventgrid/data-plane/Microsoft.Web/stable/2018-01-01/Web.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af03db33a90581edffb8a32fea562f36b7c61a8/specification/eventgrid/data-plane/Microsoft.Communication/stable/2018-01-01/AzureCommunicationServices.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af03db33a90581edffb8a32fea562f36b7c61a8/specification/eventgrid/data-plane/Microsoft.PolicyInsights/stable/2018-01-01/PolicyInsights.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af03db33a90581edffb8a32fea562f36b7c61a8/specification/eventgrid/data-plane/Microsoft.ContainerService/stable/2018-01-01/ContainerService.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af03db33a90581edffb8a32fea562f36b7c61a8/specification/eventgrid/data-plane/Microsoft.ApiManagement/stable/2018-01-01/APIManagement.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af03db33a90581edffb8a32fea562f36b7c61a8/specification/eventgrid/data-plane/Microsoft.HealthcareApis/stable/2018-01-01/HealthcareApis.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af03db33a90581edffb8a32fea562f36b7c61a8/specification/eventgrid/data-plane/Microsoft.DataBox/stable/2018-01-01/DataBox.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af03db33a90581edffb8a32fea562f36b7c61a8/specification/eventgrid/data-plane/Microsoft.ResourceNotifications/stable/2018-01-01/common.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af03db33a90581edffb8a32fea562f36b7c61a8/specification/eventgrid/data-plane/Microsoft.ResourceNotifications/stable/2018-01-01/HealthResources.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af03db33a90581edffb8a32fea562f36b7c61a8/specification/eventgrid/data-plane/Microsoft.ResourceNotifications/stable/2018-01-01/Resources.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af03db33a90581edffb8a32fea562f36b7c61a8/specification/eventgrid/data-plane/Microsoft.AVS/stable/2018-01-01/PrivateCloud.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af03db33a90581edffb8a32fea562f36b7c61a8/specification/eventgrid/data-plane/Microsoft.ApiCenter/stable/2018-01-01/ApiCenter.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8af03db33a90581edffb8a32fea562f36b7c61a8/specification/eventgrid/data-plane/Microsoft.ResourceNotifications/stable/2018-01-01/ContainerServiceEventResources.json ``` diff --git a/sdk/eventgrid/azure-messaging-eventgrid/swagger/src/main/java/EventGridCustomization.java b/sdk/eventgrid/azure-messaging-eventgrid/swagger/src/main/java/EventGridCustomization.java index e613d3033176..ae97caec55ae 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/swagger/src/main/java/EventGridCustomization.java +++ b/sdk/eventgrid/azure-messaging-eventgrid/swagger/src/main/java/EventGridCustomization.java @@ -1,3 +1,6 @@ +// 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.Editor; @@ -6,6 +9,7 @@ import com.azure.autorest.customization.PropertyCustomization; import com.github.javaparser.StaticJavaParser; import com.github.javaparser.ast.Modifier.Keyword; +import com.github.javaparser.ast.NodeList; import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; import com.github.javaparser.ast.body.MethodDeclaration; import com.github.javaparser.ast.body.Parameter; @@ -20,7 +24,6 @@ import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.time.ZoneOffset; -import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.time.temporal.TemporalAccessor; import java.time.temporal.TemporalQueries; @@ -233,7 +236,7 @@ public void customize(LibraryCustomization customization, Logger logger) { logger.info("Total number of events with proper description " + validEventDescription.size()); customization.getRawEditor() - .addFile("src/main/java/com/azure/messaging/eventgrid/SystemEventNames.java", sb.toString()); + .addFile("src/main/java/com/azure/messaging/eventgrid/SystemEventNames.java", sb.toString()); customizeMediaJobOutputAsset(customization); @@ -247,7 +250,6 @@ public void customize(LibraryCustomization customization, Logger logger) { customizeResourceNotificationEvents(customization); customizeCommunicationIdentifierModelKind(customization); customizeAcsMessageChannelEventError(customization); - customizeCentralCommuicationEvents(customization); customizeCommuicationSMSEvents(customization); } @@ -271,14 +273,6 @@ public void customizeCommuicationSMSEvents(LibraryCustomization customization) { }); } - public void customizeCentralCommuicationEvents(LibraryCustomization customization) { - // these events come from a json outside of EventGrid so we can't change the swagger - Arrays.asList("MicrosoftTeamsAppIdentifier", "CommunicationIdentifierKind").forEach(name -> { - ClassCustomization classCustomization = customization.getPackage("com.azure.messaging.eventgrid.systemevents").getClass(name); - classCustomization.rename("Acs" + name); - }); - } - public void customizeResourceEvents(LibraryCustomization customization, Logger logger) { PackageCustomization packageModels = customization.getPackage("com.azure.messaging.eventgrid.systemevents"); @@ -433,71 +427,80 @@ public void customizeCommunicationIdentifierModelKind(LibraryCustomization custo ClassCustomization classCustomization = customization .getPackage("com.azure.messaging.eventgrid.systemevents") .getClass("CommunicationIdentifierModelKind") - .rename("CommunicationIdentifierKind"); + .rename("AcsCommunicationIdentifierKind"); } public void customizeMediaLiveEventIngestHeartbeatEventData(LibraryCustomization customization) { PackageCustomization packageModels = customization.getPackage("com.azure.messaging.eventgrid.systemevents"); ClassCustomization classCustomization = packageModels.getClass("MediaLiveEventIngestHeartbeatEventData"); - classCustomization.addStaticBlock("static final ClientLogger LOGGER = new ClientLogger(MediaLiveEventIngestHeartbeatEventData.class);", Arrays.asList("com.azure.core.util.logging.ClientLogger")); - classCustomization.getMethod("getIngestDriftValue") - .setReturnType("Integer", "") - .replaceBody("if (\"n/a\".equals(this.ingestDriftValue)) { return null; } try { return Integer.parseInt(this.ingestDriftValue); } catch (NumberFormatException ex) { LOGGER.logExceptionAsError(ex); return null; }"); + classCustomization.customizeAst(comp -> { + comp.addImport("java.time.OffsetDateTime"); + ClassOrInterfaceDeclaration clazz = comp.getClassByName("MediaLiveEventIngestHeartbeatEventData").get(); + comp.addImport("com.azure.core.util.logging.ClientLogger"); + clazz.addFieldWithInitializer("ClientLogger", "LOGGER", parseExpression("new ClientLogger(MediaLiveEventIngestHeartbeatEventData.class)"), Keyword.PRIVATE, Keyword.STATIC, Keyword.FINAL); - classCustomization.getMethod("getLastFragmentArrivalTime") - .setReturnType("OffsetDateTime", "") - .replaceBody("return OffsetDateTime.parse(this.lastFragmentArrivalTime);", Arrays.asList("java.time.OffsetDateTime")); + clazz.getMethodsByName("getIngestDriftValue").forEach(m -> { + m.setType("Integer") + .setBody(parseBlock("{ if (\"n/a\".equals(this.ingestDriftValue)) { return null; } try { return Integer.parseInt(this.ingestDriftValue); } catch (NumberFormatException ex) { LOGGER.logExceptionAsError(ex); return null; } }")); + }); + clazz.getMethodsByName("getLastFragmentArrivalTime").forEach(m -> { + m.setType("OffsetDateTime") + .setBody(parseBlock("{ return OffsetDateTime.parse(this.lastFragmentArrivalTime); }")); + }); + }); } public void customizeMediaLiveEventChannelArchiveHeartbeatEventDataDuration(LibraryCustomization customization) { PackageCustomization packageModels = customization.getPackage("com.azure.messaging.eventgrid.systemevents"); ClassCustomization classCustomization = packageModels.getClass("MediaLiveEventChannelArchiveHeartbeatEventData"); - classCustomization.addStaticBlock("static final ClientLogger LOGGER = new ClientLogger(MediaLiveEventChannelArchiveHeartbeatEventData.class);"); - - PropertyCustomization property = classCustomization.getProperty("channelLatencyMs"); - property.generateGetterAndSetter(); - classCustomization.getMethod("getChannelLatencyMs") - .rename("getChannelLatency") - .setReturnType("Duration", "") - .replaceBody("if (\"n/a\".equals(this.channelLatencyMs)) { return null; } Long channelLatencyMsLong; try { channelLatencyMsLong = Long.parseLong(this.channelLatencyMs); } catch (NumberFormatException ex) { LOGGER.logExceptionAsError(ex); return null; } return Duration.ofMillis(channelLatencyMsLong);", Arrays.asList("java.time.Duration")) - .getJavadoc() - .setDescription("Gets the duration of channel latency.") - .setReturn("the duration of channel latency."); - - try { - classCustomization.removeMethod("setChannelLatencyMs"); - classCustomization.removeMethod("setLatencyResultCode"); - classCustomization.removeMethod("getLogger"); - } catch (IllegalArgumentException ignored) { + classCustomization.customizeAst(comp -> { + ClassOrInterfaceDeclaration clazz = comp.getClassByName("MediaLiveEventChannelArchiveHeartbeatEventData").get(); + clazz.addFieldWithInitializer("ClientLogger", "LOGGER", parseExpression("new ClientLogger(MediaLiveEventChannelArchiveHeartbeatEventData.class)"), Keyword.PRIVATE, Keyword.STATIC, Keyword.FINAL); + comp.addImport("java.time.Duration"); + comp.addImport("com.azure.core.util.logging.ClientLogger"); + clazz.getMethodsByName("getChannelLatencyMs").forEach(m -> { + m.setName("getChannelLatency") + .setType("Duration") + .setBody(parseBlock("{ if (\"n/a\".equals(this.channelLatencyMs)) { return null; } Long channelLatencyMsLong; try { channelLatencyMsLong = Long.parseLong(this.channelLatencyMs); } catch (NumberFormatException ex) { LOGGER.logExceptionAsError(ex); return null; } return Duration.ofMillis(channelLatencyMsLong); }")) + .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Gets the duration of channel latency.")))) + .addBlockTag("return", "the duration of channel latency.")); + }); - } + clazz.getMethodsByName("setChannelLatencyMs").forEach(m -> m.remove()); + clazz.getMethodsByName("setLatencyResultCode").forEach(m -> m.remove()); + clazz.getMethodsByName("getLogger").forEach(m -> m.remove()); + }); } public void customizeAcsRecordingFileStatusUpdatedEventDataDuration(LibraryCustomization customization) { PackageCustomization packageModels = customization.getPackage("com.azure.messaging.eventgrid.systemevents"); ClassCustomization classCustomization = packageModels.getClass("AcsRecordingFileStatusUpdatedEventData"); - PropertyCustomization property = classCustomization.getProperty("recordingDurationMs"); - property.generateGetterAndSetter(); - - classCustomization.getMethod("getRecordingDurationMs") - .rename("getRecordingDuration") - .setReturnType("Duration", "Duration.ofMillis(%s)") - .replaceBody("if (this.recordingDurationMs != null) { return Duration.ofMillis(this.recordingDurationMs); } return null;", Arrays.asList("java.time.Duration")) - .getJavadoc() - .setDescription("Get the recordingDuration property: The recording duration.") - .setReturn("the recordingDuration value."); - - - classCustomization.getMethod("setRecordingDurationMs") - .rename("setRecordingDuration") - .replaceParameters("Duration recordingDuration") - .replaceBody("if (recordingDuration != null) { this.recordingDurationMs = recordingDuration.toMillis(); } else { this.recordingDurationMs = null; } return this;") - .getJavadoc() - .setDescription("Set the recordingDuration property: The recording duration.") - .setParam("recordingDuration", "the recordingDuration value to set.") - .removeParam("recordingDurationMs"); + classCustomization.customizeAst(compilationUnit -> { + PropertyCustomization property = classCustomization.getProperty("recordingDurationMs"); + property.generateGetterAndSetter(); + + ClassOrInterfaceDeclaration clazz = compilationUnit.getClassByName("AcsRecordingFileStatusUpdatedEventData").get(); + compilationUnit.addImport("java.time.Duration"); + clazz.getMethodsByName("getRecordingDurationMs").forEach(m -> { + m.setName("getRecordingDuration") + .setType("Duration") + .setBody(parseBlock("{ if (this.recordingDurationMs != null) { return Duration.ofMillis(this.recordingDurationMs); } return null; }")) + .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Get the recordingDuration property: The recording duration.")))) + .addBlockTag("return", "the recordingDuration value.")); + }); + + clazz.getMethodsByName("setRecordingDurationMs").forEach(m -> { + m.setName("setRecordingDuration") + .setType("AcsRecordingFileStatusUpdatedEventData") + .setParameters(new NodeList<>( new Parameter().setType("Duration").setName("recordingDuration"))) + .setBody(parseBlock("{ if (recordingDuration != null) { this.recordingDurationMs = recordingDuration.toMillis(); } else { this.recordingDurationMs = null; } return this; }")) + .setJavadocComment(new Javadoc(new JavadocDescription(List.of(new JavadocSnippet("Set the recordingDuration property: The recording duration.")))) + .addBlockTag("param", "recordingDuration the recordingDuration value to set.") + .addBlockTag("return", "the AcsRecordingFileStatusUpdatedEventData object itself.")); + }); + }); } @@ -574,10 +577,10 @@ public void customizeAcsRouterEvents(LibraryCustomization customization) { m.setName("setTimeToLive"); m.getParameter(0).setName("timeToLive"); m.setJavadocComment( - " * Set the timeToLive property: Router Job Worker Selector Time to Live in Seconds.\n" - + " *\n" - + " * @param timeToLive the timeToLive value to set.\n" - + " * @return the AcsRouterWorkerSelector object itself.\n"); + " * Set the timeToLive property: Router Job Worker Selector Time to Live in Seconds.\n" + + " *\n" + + " * @param timeToLive the timeToLive value to set.\n" + + " * @return the AcsRouterWorkerSelector object itself.\n"); }); }); @@ -610,9 +613,9 @@ public void customizeAcsRouterEvents(LibraryCustomization customization) { classCustomization = packageModels.getClass("AcsRouterJobWaitingForActivationEventData"); classCustomization.customizeAst(comp -> { - ClassOrInterfaceDeclaration clazz = comp.getClassByName("AcsRouterJobWaitingForActivationEventData").get(); - clazz.getMethodsByName("setUnavailableForMatching").forEach(m -> m.getParameter(0).setType(Boolean.class)); - clazz.getMethodsByName("isUnavailableForMatching").forEach(m -> m.setType(Boolean.class)); + ClassOrInterfaceDeclaration clazz = comp.getClassByName("AcsRouterJobWaitingForActivationEventData").get(); + clazz.getMethodsByName("setUnavailableForMatching").forEach(m -> m.getParameter(0).setType(Boolean.class)); + clazz.getMethodsByName("isUnavailableForMatching").forEach(m -> m.setType(Boolean.class)); }); } diff --git a/sdk/eventgrid/azure-resourcemanager-eventgrid/README.md b/sdk/eventgrid/azure-resourcemanager-eventgrid/README.md index 876924356edf..2299367e0dc3 100644 --- a/sdk/eventgrid/azure-resourcemanager-eventgrid/README.md +++ b/sdk/eventgrid/azure-resourcemanager-eventgrid/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-eventgrid - 1.2.0-beta.7 + 1.2.0-beta.8 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Feventgrid%2Fazure-resourcemanager-eventgrid%2FREADME.png) + diff --git a/sdk/eventgrid/azure-resourcemanager-eventgrid/pom.xml b/sdk/eventgrid/azure-resourcemanager-eventgrid/pom.xml index bfae16170f67..aee2f4b97b0d 100644 --- a/sdk/eventgrid/azure-resourcemanager-eventgrid/pom.xml +++ b/sdk/eventgrid/azure-resourcemanager-eventgrid/pom.xml @@ -52,41 +52,41 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager - 2.46.0 + 2.48.0 test com.azure azure-messaging-eventgrid - 4.27.0 + 4.29.0 test com.azure azure-messaging-eventhubs - 5.19.2 + 5.20.1 test diff --git a/sdk/eventgrid/ci.yml b/sdk/eventgrid/ci.yml index 1c65fc6db93a..5da55d056c91 100644 --- a/sdk/eventgrid/ci.yml +++ b/sdk/eventgrid/ci.yml @@ -11,11 +11,13 @@ trigger: - sdk/eventgrid/ci.yml - sdk/eventgrid/azure-messaging-eventgrid/ - sdk/eventgrid/azure-messaging-eventgrid-namespaces/ + - sdk/eventgrid/azure-messaging-eventgrid-systemevents/ - sdk/eventgrid/azure-messaging-eventgrid-cloudnative-cloudevents/ exclude: - sdk/eventgrid/pom.xml - sdk/eventgrid/azure-messaging-eventgrid/pom.xml - sdk/eventgrid/azure-messaging-eventgrid-namespaces/pom.xml + - sdk/eventgrid/azure-messaging-eventgrid-systemevents/pom.xml - sdk/eventgrid/azure-messaging-eventgrid-cloudnative-cloudevents/pom.xml - sdk/eventgrid/azure-resourcemanager-eventgrid/ @@ -31,11 +33,13 @@ pr: - sdk/eventgrid/ci.yml - sdk/eventgrid/azure-messaging-eventgrid/ - sdk/eventgrid/azure-messaging-eventgrid-namespaces/ + - sdk/eventgrid/azure-messaging-eventgrid-systemevents/ - sdk/eventgrid/azure-messaging-eventgrid-cloudnative-cloudevents/ exclude: - sdk/eventgrid/pom.xml - sdk/eventgrid/azure-messaging-eventgrid/pom.xml - sdk/eventgrid/azure-messaging-eventgrid-namespaces/pom.xml + - sdk/eventgrid/azure-messaging-eventgrid-systemevents/pom.xml - sdk/eventgrid/azure-messaging-eventgrid-cloudnative-cloudevents/pom.xml - sdk/eventgrid/azure-resourcemanager-eventgrid/ @@ -48,6 +52,10 @@ parameters: displayName: 'azure-messaging-eventgrid-namespaces' type: boolean default: true +- name: release_azuremessagingeventgridsystemevents + displayName: 'azure-messaging-eventgrid-systemevents' + type: boolean + default: true - name: release_azuremessagingeventgridcloudnativecloudevents displayName: 'azure-messaging-eventgrid-cloudnative-cloudevents' type: boolean @@ -66,6 +74,10 @@ extends: groupId: com.azure safeName: azuremessagingeventgridnamespaces releaseInBatch: ${{ parameters.release_azuremessagingeventgridnamespaces }} + - name: azure-messaging-eventgrid-systemevents + groupId: com.azure + safeName: azuremessagingeventgridsystemevents + releaseInBatch: ${{ parameters.release_azuremessagingeventgridsystemevents }} - name: azure-messaging-eventgrid-cloudnative-cloudevents groupId: com.azure safeName: azuremessagingeventgridcloudnativecloudevents diff --git a/sdk/eventgrid/pom.xml b/sdk/eventgrid/pom.xml index 0b26f5f8db79..d975c236829a 100644 --- a/sdk/eventgrid/pom.xml +++ b/sdk/eventgrid/pom.xml @@ -13,6 +13,7 @@ azure-messaging-eventgrid azure-messaging-eventgrid-cloudnative-cloudevents azure-messaging-eventgrid-namespaces + azure-messaging-eventgrid-systemevents azure-resourcemanager-eventgrid diff --git a/sdk/eventgrid/tests.yml b/sdk/eventgrid/tests.yml index 8a94f131e89e..3bfebc5217a9 100644 --- a/sdk/eventgrid/tests.yml +++ b/sdk/eventgrid/tests.yml @@ -14,6 +14,9 @@ extends: - name: azure-messaging-eventgrid-namespaces groupId: com.azure safeName: azuremessagingeventgridnamespaces + - name: azure-messaging-eventgrid-systemevents + groupId: com.azure + safeName: azuremessagingeventgridsystemevents - name: azure-messaging-eventgrid-cloudnative-cloudevents groupId: com.azure safeName: azuremessagingeventgridcloudnativecloudevents diff --git a/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/CHANGELOG.md b/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/CHANGELOG.md index ef0ad7d5d02b..2102cf45e29e 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/CHANGELOG.md +++ b/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.21.0-beta.1 (Unreleased) +## 1.21.0-beta.2 (Unreleased) ### Features Added @@ -10,6 +10,46 @@ ### Other Changes +## 1.20.5 (2025-03-05) + +### Bugs Fixed + +- Fixed dependency conflict between `azure-storage-blob` and `azure-messaging-eventhubs`. + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-storage-blob` from `12.29.0` to version `12.29.1`. + +## 1.20.4 (2025-02-28) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-messaging-eventhubs` from `5.20.0` to version `5.20.1`. + +## 1.21.0-beta.1 (2025-02-21) + +### Features Added + +- Use `getOffsetString()` to persist checkpoints rather than `getOffset()`, which is deprecated. ([44272](https://github.com/Azure/azure-sdk-for-java/pull/44272)) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-messaging-eventhubs` from `5.20.0` to version `5.21.0-beta.1`. + +## 1.20.3 (2025-02-11) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-messaging-eventhubs` from `5.19.2` to version `5.20.0`. + ## 1.20.2 (2024-12-04) ### Other Changes @@ -514,4 +554,4 @@ store checkpoints and balance partition load among all instances of Event Proces - Initial offset provider for each partition is not implemented. - Interoperability with Event Processors of other language SDKs like Python is not supported. -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Feventhubs%2Fazure-messaging-eventhubs-checkpointstore-blob%2FCHANGELOG.png) + diff --git a/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/README.md b/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/README.md index 6f086680ea85..c7986dbb9ebd 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/README.md +++ b/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/README.md @@ -60,7 +60,7 @@ add the direct dependency to your project as follows. com.azure azure-messaging-eventhubs-checkpointstore-blob - 1.20.0 + 1.21.0-beta.2 ``` [//]: # ({x-version-update-end}) @@ -86,9 +86,9 @@ downstream applications, and to provide resiliency if a failover between readers It is possible to return to older data by specifying a lower offset from this checkpointing process. Through this mechanism, checkpointing enables both failover resiliency and event stream replay. -### Offsets & sequence numbers +### Offsets & sequence numbers -Both offset & sequence number refer to the position of an event within a partition. You can think of them as a +Both offset & sequence number refer to the position of an event within a partition. You can think of them as a client-side cursor. The offset is a byte numbering of the event. The offset/sequence number enables an event consumer (reader) to specify a point in the event stream from which they want to begin reading events. You can specify the timestamp such that you receive events that were enqueued only after the given timestamp. Consumers are responsible for @@ -202,4 +202,4 @@ Guidelines](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/eventhubs/ [source_loglevels]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/.https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/core/azure-core/src/main/java/com/azure/core/util/logging/ClientLogger.java [storage_account]: https://learn.microsoft.com/azure/storage/common/storage-quickstart-create-account?tabs=azure-portal -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Feventhubs%2Fazure-messaging-eventhubs-checkpointstore-blob%2FREADME.png) + diff --git a/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/pom.xml b/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/pom.xml index deba90676c05..8a614518d314 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/pom.xml +++ b/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/pom.xml @@ -17,7 +17,7 @@ com.azure azure-messaging-eventhubs-checkpointstore-blob - 1.21.0-beta.1 + 1.21.0-beta.2 Microsoft Azure client library for storing checkpoints in Storage Blobs Library for using storing checkpoints in Storage Blobs @@ -53,25 +53,25 @@ com.azure azure-messaging-eventhubs - 5.20.0-beta.1 + 5.21.0-beta.2 com.azure azure-storage-blob - 12.29.0 + 12.29.1 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/src/samples/README.md b/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/src/samples/README.md index 1c11fc116f6b..81aad9fc3c66 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/src/samples/README.md +++ b/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/src/samples/README.md @@ -48,4 +48,4 @@ Guidelines](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/eventhubs/ [sdk_readme_next_steps]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/README.md#next-steps [sdk_readme_troubleshooting]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/README.md#troubleshooting -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Feventhubs%2Fazure-messaging-eventhubs-checkpointstore-blob%2Fsrc%2Fsamples%2FREADME.png) + diff --git a/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-jedis/README.md b/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-jedis/README.md index 8e479b3fb5b0..d1db078c77e4 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-jedis/README.md +++ b/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-jedis/README.md @@ -60,7 +60,7 @@ add the direct dependency to your project as follows. com.azure azure-messaging-eventhubs-checkpointstore-jedis - 1.0.0-beta.3 + 1.0.0-beta.4 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-jedis/pom.xml b/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-jedis/pom.xml index 61402fb3fd58..1319f3504bd9 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-jedis/pom.xml +++ b/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-jedis/pom.xml @@ -47,7 +47,7 @@ com.azure azure-messaging-eventhubs - 5.20.0-beta.1 + 5.21.0-beta.2 redis.clients @@ -59,7 +59,7 @@ com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/eventhubs/azure-messaging-eventhubs-stress/pom.xml b/sdk/eventhubs/azure-messaging-eventhubs-stress/pom.xml index c3296f8c962a..c9c2b3669a4f 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs-stress/pom.xml +++ b/sdk/eventhubs/azure-messaging-eventhubs-stress/pom.xml @@ -38,44 +38,44 @@ com.azure azure-identity - 1.15.0 + 1.15.4 com.azure azure-messaging-eventhubs - 5.20.0-beta.1 + 5.21.0-beta.2 com.azure azure-messaging-eventhubs-checkpointstore-blob - 1.21.0-beta.1 + 1.21.0-beta.2 com.azure - azure-monitor-opentelemetry-exporter - 1.0.0-beta.31 + azure-monitor-opentelemetry-autoconfigure + 1.0.0 io.opentelemetry.instrumentation opentelemetry-runtime-telemetry-java8 - 2.9.0-alpha + 2.12.0-alpha io.opentelemetry.instrumentation opentelemetry-logback-appender-1.0 - 2.9.0-alpha + 2.12.0-alpha com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.52 + 1.0.0-beta.56 com.azure azure-core-metrics-opentelemetry - 1.0.0-beta.25 + 1.0.0-beta.29 @@ -102,8 +102,8 @@ org.springframework.boot:spring-boot-starter:[2.7.18] - io.opentelemetry.instrumentation:opentelemetry-runtime-telemetry-java8:[2.9.0-alpha] - io.opentelemetry.instrumentation:opentelemetry-logback-appender-1.0:[2.9.0-alpha] + io.opentelemetry.instrumentation:opentelemetry-runtime-telemetry-java8:[2.12.0-alpha] + io.opentelemetry.instrumentation:opentelemetry-logback-appender-1.0:[2.12.0-alpha] diff --git a/sdk/eventhubs/azure-messaging-eventhubs-stress/src/main/java/com/azure/messaging/eventhubs/stress/util/TelemetryHelper.java b/sdk/eventhubs/azure-messaging-eventhubs-stress/src/main/java/com/azure/messaging/eventhubs/stress/util/TelemetryHelper.java index b8b97e28bbb6..2aaa4c248aae 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs-stress/src/main/java/com/azure/messaging/eventhubs/stress/util/TelemetryHelper.java +++ b/sdk/eventhubs/azure-messaging-eventhubs-stress/src/main/java/com/azure/messaging/eventhubs/stress/util/TelemetryHelper.java @@ -8,7 +8,7 @@ import com.azure.messaging.eventhubs.EventHubClientBuilder; import com.azure.messaging.eventhubs.models.CloseContext; import com.azure.messaging.eventhubs.models.InitializationContext; -import com.azure.monitor.opentelemetry.exporter.AzureMonitorExporter; +import com.azure.monitor.opentelemetry.autoconfigure.AzureMonitorAutoConfigure; import io.opentelemetry.api.OpenTelemetry; import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; @@ -95,7 +95,7 @@ private static OpenTelemetry init() { } AutoConfiguredOpenTelemetrySdkBuilder sdkBuilder = AutoConfiguredOpenTelemetrySdk.builder(); - AzureMonitorExporter.customize(sdkBuilder, applicationInsightsConnectionString); + AzureMonitorAutoConfigure.customize(sdkBuilder, applicationInsightsConnectionString); String instanceId = System.getenv("CONTAINER_NAME"); OpenTelemetry otel = sdkBuilder diff --git a/sdk/eventhubs/azure-messaging-eventhubs-track2-perf/pom.xml b/sdk/eventhubs/azure-messaging-eventhubs-track2-perf/pom.xml index 463a23ea1db5..ac1dbbb05469 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs-track2-perf/pom.xml +++ b/sdk/eventhubs/azure-messaging-eventhubs-track2-perf/pom.xml @@ -24,12 +24,12 @@ com.azure azure-messaging-eventhubs - 5.20.0-beta.1 + 5.21.0-beta.2 com.azure azure-messaging-eventhubs-checkpointstore-blob - 1.21.0-beta.1 + 1.21.0-beta.2 com.azure @@ -45,7 +45,7 @@ com.azure azure-core - 1.54.1 + 1.55.3 diff --git a/sdk/eventhubs/azure-messaging-eventhubs/CHANGELOG.md b/sdk/eventhubs/azure-messaging-eventhubs/CHANGELOG.md index 87d057470dc1..5b2522d5da6d 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/CHANGELOG.md +++ b/sdk/eventhubs/azure-messaging-eventhubs/CHANGELOG.md @@ -1,16 +1,51 @@ # Release History -## 5.20.0-beta.1 (Unreleased) +## 5.21.0-beta.2 (Unreleased) ### Features Added -Setting the v2 stack as the default. ([43725](https://github.com/Azure/azure-sdk-for-java/pull/43725)) +### Breaking Changes + +### Bugs Fixed + +- Fixes issue where `EventHubBufferedProducerClient` and `EventHubBufferedProducerAsyncClient` are unable to enqueue events when `SendOptions.getPartitionId()` is set. ([#44392](https://github.com/Azure/azure-sdk-for-java/pull/44392)) +- Fixes issue where `EventHubBufferedProducerClient` and `EventHubBufferedProducerAsyncClient` returns 0 after enqueueing events or calling `getBufferedEventCount()`. ([#44392](https://github.com/Azure/azure-sdk-for-java/pull/44392)) + +## 5.20.1 (2025-02-25) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core-amqp` from `2.9.12` to version `2.9.15`. +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. + +## 5.21.0-beta.1 (2025-02-21) + +### Features Added + +- Added support for geo-replication capability. ([#44272](https://github.com/Azure/azure-sdk-for-java/pull/44272)) + +### Other Changes + +- The `getOffset()` method, which returns a `Long`, has been deprecated in `EventData`, `SystemProperties`, and `Checkpoint`. Replaced with `getOffsetString()`. + +#### Dependency Updates + +- Upgraded `azure-core` from `1.53.0` to version `1.55.2`. +- Upgraded `azure-core-amqp` from `2.9.12` to version `2.9.15`. + +## 5.20.0 (2025-02-11) + +### Features Added + +- Setting the v2 stack as the default. ([43725](https://github.com/Azure/azure-sdk-for-java/pull/43725)) ### Breaking Changes - Do not remove `x-opt-partition-key` message annotation when publishing events. If event is received from an Event Hub, it may contain `x-opt-partition-key` message annotation. If this event is - published to another Event Hub, previous version of the Event Hubs SDK did not pass this annotation to the next Event Hub. + published to another Event Hub, previous version of the Event Hubs SDK did not pass this annotation to the next Event Hub. Starting with this version: - if the event is sent with `SendOptions` or `CreateBatchOptions` containing `null` partition key, the existing `x-opt-partition-key` message annotation will be used when publishing the event. **This is a new behavior.** @@ -29,8 +64,6 @@ Setting the v2 stack as the default. ([43725](https://github.com/Azure/azure-sdk will overwrite these values when the event is published. ([#43039](https://github.com/Azure/azure-sdk-for-java/pull/43039)) -### Other Changes - ## 5.19.2 (2024-12-04) ### Other Changes @@ -815,4 +848,4 @@ For release notes and more information please visit https://aka.ms/azure-sdk-pre - Creating more than two concurrent `EventHubClients` or `EventHubConsumers` does not work. Limit usage of concurrent clients and consumers to two to avoid failures. -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Feventhubs%2Fazure-messaging-eventhubs%2FCHANGELOG.png) + diff --git a/sdk/eventhubs/azure-messaging-eventhubs/README.md b/sdk/eventhubs/azure-messaging-eventhubs/README.md index 836d64bb6d10..2acf253f2921 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/README.md +++ b/sdk/eventhubs/azure-messaging-eventhubs/README.md @@ -95,7 +95,7 @@ add the direct dependency to your project as follows. com.azure azure-messaging-eventhubs - 5.19.0 + 5.21.0-beta.2 ``` [//]: # ({x-version-update-end}) @@ -138,7 +138,7 @@ platform. First, add the package: com.azure azure-identity - 1.14.2 + 1.15.3 ``` [//]: # ({x-version-update-end}) @@ -468,4 +468,4 @@ Guidelines](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/eventhubs/ [wiki_identity]: https://learn.microsoft.com/azure/developer/java/sdk/identity [troubleshooting]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/eventhubs/azure-messaging-eventhubs/TROUBLESHOOTING.md -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Feventhubs%2Fazure-messaging-eventhubs%2FREADME.png) + diff --git a/sdk/eventhubs/azure-messaging-eventhubs/TROUBLESHOOTING.md b/sdk/eventhubs/azure-messaging-eventhubs/TROUBLESHOOTING.md index 50b5a81c3814..eb8b3f5e6a7c 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/TROUBLESHOOTING.md +++ b/sdk/eventhubs/azure-messaging-eventhubs/TROUBLESHOOTING.md @@ -25,4 +25,4 @@ When filing GitHub issues, the following details are requested: [SUPPORT]: https://github.com/Azure/azure-sdk-for-java/blob/main/SUPPORT.md -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Feventhubs%2Fazure-messaging-eventhubs%2FTROUBLESHOOTING.png) + diff --git a/sdk/eventhubs/azure-messaging-eventhubs/docs/pom.xml b/sdk/eventhubs/azure-messaging-eventhubs/docs/pom.xml index bad1eede4b07..3b712f72075c 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/docs/pom.xml +++ b/sdk/eventhubs/azure-messaging-eventhubs/docs/pom.xml @@ -20,7 +20,7 @@ com.azure azure-messaging-eventhubs-checkpointstore-blob - 1.21.0-beta.1 + 1.21.0-beta.2 io.projectreactor diff --git a/sdk/eventhubs/azure-messaging-eventhubs/migration-guide.md b/sdk/eventhubs/azure-messaging-eventhubs/migration-guide.md index 9ba3794f484c..c567981493b4 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/migration-guide.md +++ b/sdk/eventhubs/azure-messaging-eventhubs/migration-guide.md @@ -450,18 +450,18 @@ More examples can be found at: [azure-messaging-eventhubs-checkpointstore-blob]: https://central.sonatype.com/artifact/com.azure/azure-messaging-eventhubs-checkpointstore-blob -[CheckpointStore]: https://azuresdkdocs.blob.core.windows.net/$web/java/azure-messaging-eventhubs/latest/com/azure/messaging/eventhubs/CheckpointStore.html -[CreateBatchOptions]: https://azuresdkdocs.blob.core.windows.net/$web/java/azure-messaging-eventhubs/latest/com/azure/messaging/eventhubs/models/CreateBatchOptions.html -[EventData]: https://azuresdkdocs.blob.core.windows.net/$web/java/azure-messaging-eventhubs/latest/com/azure/messaging/eventhubs/EventData.html -[EventDataBatch]: https://azuresdkdocs.blob.core.windows.net/$web/java/azure-messaging-eventhubs/latest/com/azure/messaging/eventhubs/EventDataBatch.html -[EventHubClientBuilder]: https://azuresdkdocs.blob.core.windows.net/$web/java/azure-messaging-eventhubs/latest/com/azure/messaging/eventhubs/EventHubClientBuilder.html -[EventHubConsumerAsyncClient]: https://azuresdkdocs.blob.core.windows.net/$web/java/azure-messaging-eventhubs/latest/com/azure/messaging/eventhubs/EventHubConsumerAsyncClient.html -[EventHubConsumerClient]: https://azuresdkdocs.blob.core.windows.net/$web/java/azure-messaging-eventhubs/latest/com/azure/messaging/eventhubs/EventHubConsumerClient.html -[EventHubProducerAsyncClient]: https://azuresdkdocs.blob.core.windows.net/$web/java/azure-messaging-eventhubs/latest/com/azure/messaging/eventhubs/EventHubProducerAsyncClient.html -[EventHubProducerClient]: https://azuresdkdocs.blob.core.windows.net/$web/java/azure-messaging-eventhubs/latest/com/azure/messaging/eventhubs/EventHubProducerClient.html -[EventProcessorClient]: https://azuresdkdocs.blob.core.windows.net/$web/java/azure-messaging-eventhubs/latest/com/azure/messaging/eventhubs/EventProcessorClient.html -[EventProcessorClientBuilder]: https://azuresdkdocs.blob.core.windows.net/$web/java/azure-messaging-eventhubs/latest/com/azure/messaging/eventhubs/EventProcessorClientBuilder.html -[EventProcessorClientBuilder-CheckpointStore]: https://azuresdkdocs.blob.core.windows.net/$web/java/azure-messaging-eventhubs/latest/com/azure/messaging/eventhubs/EventProcessorClientBuilder.html#checkpointStore-com.azure.messaging.eventhubs.CheckpointStore- +[CheckpointStore]: https://azuresdkdocs.z19.web.core.windows.net/java/azure-messaging-eventhubs/latest/com/azure/messaging/eventhubs/CheckpointStore.html +[CreateBatchOptions]: https://azuresdkdocs.z19.web.core.windows.net/java/azure-messaging-eventhubs/latest/com/azure/messaging/eventhubs/models/CreateBatchOptions.html +[EventData]: https://azuresdkdocs.z19.web.core.windows.net/java/azure-messaging-eventhubs/latest/com/azure/messaging/eventhubs/EventData.html +[EventDataBatch]: https://azuresdkdocs.z19.web.core.windows.net/java/azure-messaging-eventhubs/latest/com/azure/messaging/eventhubs/EventDataBatch.html +[EventHubClientBuilder]: https://azuresdkdocs.z19.web.core.windows.net/java/azure-messaging-eventhubs/latest/com/azure/messaging/eventhubs/EventHubClientBuilder.html +[EventHubConsumerAsyncClient]: https://azuresdkdocs.z19.web.core.windows.net/java/azure-messaging-eventhubs/latest/com/azure/messaging/eventhubs/EventHubConsumerAsyncClient.html +[EventHubConsumerClient]: https://azuresdkdocs.z19.web.core.windows.net/java/azure-messaging-eventhubs/latest/com/azure/messaging/eventhubs/EventHubConsumerClient.html +[EventHubProducerAsyncClient]: https://azuresdkdocs.z19.web.core.windows.net/java/azure-messaging-eventhubs/latest/com/azure/messaging/eventhubs/EventHubProducerAsyncClient.html +[EventHubProducerClient]: https://azuresdkdocs.z19.web.core.windows.net/java/azure-messaging-eventhubs/latest/com/azure/messaging/eventhubs/EventHubProducerClient.html +[EventProcessorClient]: https://azuresdkdocs.z19.web.core.windows.net/java/azure-messaging-eventhubs/latest/com/azure/messaging/eventhubs/EventProcessorClient.html +[EventProcessorClientBuilder]: https://azuresdkdocs.z19.web.core.windows.net/java/azure-messaging-eventhubs/latest/com/azure/messaging/eventhubs/EventProcessorClientBuilder.html +[EventProcessorClientBuilder-CheckpointStore]: https://azuresdkdocs.z19.web.core.windows.net/java/azure-messaging-eventhubs/latest/com/azure/messaging/eventhubs/EventProcessorClientBuilder.html#checkpointStore-com.azure.messaging.eventhubs.CheckpointStore- [Guidelines]: https://azure.github.io/azure-sdk/general_introduction.html [GuidelinesJava]: https://azure.github.io/azure-sdk/java_introduction.html [GuidelinesJavaDesign]: https://azure.github.io/azure-sdk/java_introduction.html#namespaces @@ -471,4 +471,5 @@ More examples can be found at: [README-Samples]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/eventhubs/azure-messaging-eventhubs/src/samples/README.md [README]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/eventhubs/azure-messaging-eventhubs/README.md -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Feventhubs%2Fazure-messaging-eventhubs%2Fmigration-guide.png) + + diff --git a/sdk/eventhubs/azure-messaging-eventhubs/pom.xml b/sdk/eventhubs/azure-messaging-eventhubs/pom.xml index 8ab5f8bba6e7..6947fe173b90 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/pom.xml +++ b/sdk/eventhubs/azure-messaging-eventhubs/pom.xml @@ -14,7 +14,7 @@ com.azure azure-messaging-eventhubs - 5.20.0-beta.1 + 5.21.0-beta.2 Microsoft Azure client library for Event Hubs Libraries built on Microsoft Azure Event Hubs @@ -48,25 +48,25 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-amqp - 2.9.12 + 2.9.16 com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test @@ -94,35 +94,35 @@ com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.52 + 1.0.0-beta.56 test io.opentelemetry opentelemetry-api - 1.43.0 + 1.46.0 test io.opentelemetry opentelemetry-sdk - 1.43.0 + 1.46.0 test io.opentelemetry opentelemetry-exporter-logging - 1.43.0 + 1.46.0 test com.azure azure-core-experimental - 1.0.0-beta.56 + 1.0.0-beta.60 test diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventDataAggregator.java b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventDataAggregator.java index 179889443d03..d82d5b0db968 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventDataAggregator.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventDataAggregator.java @@ -20,7 +20,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLongFieldUpdater; -import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import java.util.function.Supplier; import static com.azure.messaging.eventhubs.implementation.ClientConstants.PARTITION_ID_KEY; @@ -36,7 +36,11 @@ class EventDataAggregator extends FluxOperator { private static final ClientLogger LOGGER = new ClientLogger(EventDataAggregator.class); - private final AtomicReference downstreamSubscription = new AtomicReference<>(); + private volatile EventDataAggregatorMain downstreamSubscription; + private static final AtomicReferenceFieldUpdater DOWNSTREAM_SUBSCRIPTION + = AtomicReferenceFieldUpdater.newUpdater(EventDataAggregator.class, EventDataAggregatorMain.class, + "downstreamSubscription"); + private final Supplier batchSupplier; private final String namespace; private final BufferedProducerClientOptions options; @@ -68,11 +72,20 @@ public void subscribe(CoreSubscriber actual) { final EventDataAggregatorMain subscription = new EventDataAggregatorMain(actual, namespace, options, batchSupplier, partitionId, LOGGER); - if (!downstreamSubscription.compareAndSet(null, subscription)) { + if (DOWNSTREAM_SUBSCRIPTION.compareAndSet(this, null, subscription)) { + source.subscribe(subscription); + } else { throw LOGGER.logThrowableAsError(new IllegalArgumentException("Cannot resubscribe to multiple upstreams.")); } + } + + int getNumberOfEvents() { + final EventDataAggregatorMain downstream = downstreamSubscription; + if (downstream == null) { + return 0; + } - source.subscribe(subscription); + return downstream.getNumberOfEventsInCurrentBatch(); } /** @@ -125,6 +138,21 @@ static class EventDataAggregatorMain implements Subscription, CoreSubscriber eventSink; private final CreateBatchOptions createBatchOptions; - private final Queue eventQueue; private final AtomicBoolean isFlushing = new AtomicBoolean(false); private final Semaphore flushSemaphore = new Semaphore(1); private final PublishResultSubscriber publishResultSubscriber; private final EventHubsTracer tracer; + private final EventDataAggregator eventDataAggregator; EventHubBufferedPartitionProducer(EventHubProducerAsyncClient client, String partitionId, BufferedProducerClientOptions options, AmqpRetryOptions retryOptions, Sinks.Many eventSink, - Queue eventQueue, Tracer tracer) { + Tracer tracer) { this.client = client; this.partitionId = partitionId; @@ -69,16 +67,14 @@ class EventHubBufferedPartitionProducer implements Closeable { this.createBatchOptions = new CreateBatchOptions().setPartitionId(partitionId); this.retryOptions = retryOptions; this.eventSink = eventSink; - this.eventQueue = eventQueue; - final Flux eventDataBatchFlux = new EventDataAggregator(eventSink.asFlux(), - this::createNewBatch, client.getFullyQualifiedNamespace(), options, partitionId); + this.eventDataAggregator = new EventDataAggregator(this.eventSink.asFlux(), this::createNewBatch, + client.getFullyQualifiedNamespace(), options, partitionId); this.publishResultSubscriber = new PublishResultSubscriber(partitionId, options.getSendSucceededContext(), - options.getSendFailedContext(), eventQueue, flushSemaphore, isFlushing, retryOptions.getTryTimeout(), - LOGGER); + options.getSendFailedContext(), flushSemaphore, isFlushing, retryOptions.getTryTimeout(), LOGGER); - this.publishSubscription = publishEvents(eventDataBatchFlux).publishOn(Schedulers.boundedElastic(), 1) + this.publishSubscription = publishEvents(eventDataAggregator).publishOn(Schedulers.boundedElastic(), 1) .subscribeWith(publishResultSubscriber); this.tracer = new EventHubsTracer(tracer, client.getFullyQualifiedNamespace(), client.getEventHubName(), null); @@ -123,6 +119,8 @@ Mono enqueueEvent(EventData eventData) { } tracer.reportMessageSpan(eventData, eventData.getContext()); + + //TODO (conniey): Is this the right time to emit success. Or should we wait until it is added to batch? final Sinks.EmitResult emitResult = eventSink.tryEmitNext(eventData); if (emitResult.isSuccess()) { sink.success(); @@ -166,7 +164,12 @@ String getPartitionId() { * @return the number of events in the queue. */ int getBufferedEventCount() { - return eventQueue.size(); + // The number of events waiting to be pushed downstream to the EventDataAggregator. + final int value = eventSink.scanOrDefault(Scannable.Attr.BUFFERED, 0); + + // The number of events in the current batch. + final int currentBatch = eventDataAggregator.getNumberOfEvents(); + return value + currentBatch; } /** @@ -242,11 +245,13 @@ private static class PublishResult { } } + /** + * Subscribes to the results of a send {@link EventDataBatch} operation. + */ private static class PublishResultSubscriber extends BaseSubscriber { private final String partitionId; private final Consumer onSucceed; private final Consumer onFailed; - private final Queue dataQueue; private final Duration operationTimeout; private final ClientLogger logger; @@ -255,12 +260,11 @@ private static class PublishResultSubscriber extends BaseSubscriber flushSink; PublishResultSubscriber(String partitionId, Consumer onSucceed, - Consumer onFailed, Queue dataQueue, Semaphore flushSemaphore, - AtomicBoolean flush, Duration operationTimeout, ClientLogger logger) { + Consumer onFailed, Semaphore flushSemaphore, AtomicBoolean flush, + Duration operationTimeout, ClientLogger logger) { this.partitionId = partitionId; this.onSucceed = onSucceed; this.onFailed = onFailed; - this.dataQueue = dataQueue; this.flushSemaphore = flushSemaphore; this.isFlushing = flush; this.operationTimeout = operationTimeout; @@ -296,14 +300,7 @@ protected void hookOnError(Throwable throwable) { @Override protected void hookOnComplete() { - logger.atInfo() - .addKeyValue(PARTITION_ID_KEY, partitionId) - .log("Publishing subscription completed. Clearing rest of queue."); - - final List events = new ArrayList<>(this.dataQueue); - this.dataQueue.clear(); - - onFailed.accept(new SendBatchFailedContext(events, partitionId, null)); + logger.atInfo().addKeyValue(PARTITION_ID_KEY, partitionId).log("Publishing subscription completed."); tryCompleteFlush(); } @@ -349,13 +346,6 @@ private void tryCompleteFlush() { return; } - if (!dataQueue.isEmpty()) { - logger.atVerbose() - .addKeyValue(PARTITION_ID_KEY, partitionId) - .log("Data queue is not empty. Not completing flush."); - return; - } - logger.atVerbose().addKeyValue(PARTITION_ID_KEY, partitionId).log("Completing flush operation."); if (flushSemaphore != null) { diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubBufferedProducerAsyncClient.java b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubBufferedProducerAsyncClient.java index b774e9e7581b..4f04854240b2 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubBufferedProducerAsyncClient.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubBufferedProducerAsyncClient.java @@ -337,15 +337,17 @@ public Mono enqueueEvent(EventData eventData, SendOptions options) { } if (!CoreUtils.isNullOrEmpty(options.getPartitionId())) { - if (!partitionProducers.containsKey(options.getPartitionId())) { - return monoError(logger, new IllegalArgumentException( - "partitionId is not valid. Available ones: " + String.join(",", partitionProducers.keySet()))); - } + return partitionIdsMono.flatMap(ids -> { + if (!partitionProducers.containsKey(options.getPartitionId())) { + return monoError(logger, new IllegalArgumentException( + "partitionId is not valid. Available ones: " + String.join(",", partitionProducers.keySet()))); + } - final EventHubBufferedPartitionProducer producer - = partitionProducers.computeIfAbsent(options.getPartitionId(), key -> createPartitionProducer(key)); + final EventHubBufferedPartitionProducer producer + = partitionProducers.computeIfAbsent(options.getPartitionId(), key -> createPartitionProducer(key)); - return producer.enqueueEvent(eventData).thenReturn(getBufferedEventCount()); + return producer.enqueueEvent(eventData).then(Mono.fromCallable(() -> getBufferedEventCount())); + }); } if (options.getPartitionKey() != null) { @@ -362,7 +364,7 @@ public Mono enqueueEvent(EventData eventData, SendOptions options) { } eventData.setPartitionKeyAnnotation(options.getPartitionKey()); - return producer.enqueueEvent(eventData).thenReturn(getBufferedEventCount()); + return producer.enqueueEvent(eventData).then(Mono.fromCallable(() -> getBufferedEventCount())); }); } else { return partitionIdsMono.flatMap(ids -> { @@ -371,7 +373,7 @@ public Mono enqueueEvent(EventData eventData, SendOptions options) { = partitionProducers.computeIfAbsent(partitionId, key -> createPartitionProducer(key)); eventData.setPartitionKeyAnnotation(options.getPartitionKey()); - return producer.enqueueEvent(eventData).thenReturn(getBufferedEventCount()); + return producer.enqueueEvent(eventData).then(Mono.fromCallable(() -> getBufferedEventCount())); }); } } @@ -467,7 +469,7 @@ private EventHubBufferedPartitionProducer createPartitionProducer(String partiti final Sinks.Many eventSink = Sinks.many().unicast().onBackpressureBuffer(eventQueue); return new EventHubBufferedPartitionProducer(client, partitionId, clientOptions, retryOptions, eventSink, - eventQueue, tracer); + tracer); } /** diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/samples/README.md b/sdk/eventhubs/azure-messaging-eventhubs/src/samples/README.md index f7ea7fcf7287..17936690b2da 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/samples/README.md +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/samples/README.md @@ -84,4 +84,4 @@ Guidelines](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/eventhubs/ [sdk_readme_next_steps]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/eventhubs/azure-messaging-eventhubs/README.md#next-steps [sdk_readme_troubleshooting]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/eventhubs/azure-messaging-eventhubs/README.md#troubleshooting -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Feventhubs%2Fazure-messaging-eventhubs%2Fsrc%2Fsamples%2README.png) + diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubAsyncClientIntegrationTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubAsyncClientIntegrationTest.java index 52f8e68c4463..3aaa612db3a9 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubAsyncClientIntegrationTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubAsyncClientIntegrationTest.java @@ -109,7 +109,7 @@ void parallelEventHubClients(AmqpTransportType transportType) throws Interrupted // Assert // Wait for all the events we sent to be received by each of the consumers. - Assertions.assertTrue(countDownLatch.await(TIMEOUT.getSeconds(), TimeUnit.SECONDS)); + Assertions.assertTrue(countDownLatch.await(TIMEOUT.getSeconds() * 2, TimeUnit.SECONDS)); logger.info("Completed successfully."); } 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 2cbc1631fade..c719998cd4c7 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 @@ -148,7 +148,7 @@ public void publishesEvents() throws InterruptedException { when(client.send(any(EventDataBatch.class))).thenReturn(Mono.empty()); final EventHubBufferedPartitionProducer producer = new EventHubBufferedPartitionProducer(client, PARTITION_ID, - options, DEFAULT_RETRY_OPTIONS, eventSink, eventQueue, null); + options, DEFAULT_RETRY_OPTIONS, eventSink, null); // Act & Assert StepVerifier.create(producer.enqueueEvent(event1)) @@ -198,7 +198,7 @@ public void publishesErrors() throws InterruptedException { when(client.send(any(EventDataBatch.class))).thenReturn(Mono.empty(), Mono.error(error)); final EventHubBufferedPartitionProducer producer = new EventHubBufferedPartitionProducer(client, PARTITION_ID, - options, DEFAULT_RETRY_OPTIONS, eventSink, eventQueue, null); + options, DEFAULT_RETRY_OPTIONS, eventSink, null); // Act & Assert StepVerifier.create(Mono.when(producer.enqueueEvent(event1), producer.enqueueEvent(event2))) @@ -268,7 +268,7 @@ public void canPublishAfterErrors() throws InterruptedException { }); final EventHubBufferedPartitionProducer producer = new EventHubBufferedPartitionProducer(client, PARTITION_ID, - options, DEFAULT_RETRY_OPTIONS, eventSink, eventQueue, null); + options, DEFAULT_RETRY_OPTIONS, eventSink, null); // Act & Assert StepVerifier.create(Mono.when(producer.enqueueEvent(event1), producer.enqueueEvent(event2))) @@ -343,7 +343,7 @@ public void getBufferedEventCounts() throws InterruptedException { .thenAnswer(invocation -> Mono.delay(options.getMaxWaitTime()).then()); final EventHubBufferedPartitionProducer producer = new EventHubBufferedPartitionProducer(client, PARTITION_ID, - options, DEFAULT_RETRY_OPTIONS, eventSink, eventQueue, null); + options, DEFAULT_RETRY_OPTIONS, eventSink, null); // Act & Assert StepVerifier @@ -353,10 +353,8 @@ public void getBufferedEventCounts() throws InterruptedException { .then(() -> { // event1 was enqueued, event2 is in a batch, and event3 is currently in the queue waiting to be // pushed downstream. - // batch1 (with event1) is being sent at the moment with the delay of options.getMaxWaitTime(), so the - // buffer doesn't drain so quickly. final int bufferedEventCount = producer.getBufferedEventCount(); - assertEquals(1, bufferedEventCount); + assertEquals(2, bufferedEventCount); }) .expectComplete() .verify(DEFAULT_RETRY_OPTIONS.getTryTimeout()); @@ -414,7 +412,7 @@ public void retryAfterEmitResultError(Sinks.EmitResult emitResult) { when(client.send(any(EventDataBatch.class))).thenAnswer(invocation -> Mono.empty()); final EventHubBufferedPartitionProducer producer = new EventHubBufferedPartitionProducer(client, PARTITION_ID, - options, DEFAULT_RETRY_OPTIONS, mockedEventSink, eventQueue, null); + options, DEFAULT_RETRY_OPTIONS, mockedEventSink, null); // Act & Assert StepVerifier.create(producer.enqueueEvent(event1)) @@ -459,8 +457,8 @@ public void exhaustsRetries() { final AmqpRetryOptions retryOptions = new AmqpRetryOptions().setMaxRetries(2).setDelay(Duration.ofSeconds(2)); - final EventHubBufferedPartitionProducer producer = new EventHubBufferedPartitionProducer(client, PARTITION_ID, - options, retryOptions, mockedEventSink, eventQueue, null); + final EventHubBufferedPartitionProducer producer + = new EventHubBufferedPartitionProducer(client, PARTITION_ID, options, retryOptions, mockedEventSink, null); // Act & Assert StepVerifier.create(producer.enqueueEvent(event1)) 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 99adb074f839..4884e456233e 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 @@ -114,11 +114,14 @@ public void publishRoundRobin() throws InterruptedException { final List eventsToPublish = IntStream.range(0, numberOfEvents) .mapToObj(index -> new EventData(String.valueOf(index))) .collect(Collectors.toList()); + final int expectedBufferSize = eventsToPublish.size(); // Waiting for at least maxWaitTime because events will get published by then. - StepVerifier.create(producer.enqueueEvents(eventsToPublish)).assertNext(integer -> { - assertEquals(0, integer, "Do not expect anymore events in queue."); - }).thenAwait(maxWaitTime).expectComplete().verify(TIMEOUT); + StepVerifier.create(producer.enqueueEvents(eventsToPublish)) + .assertNext(actual -> assertEquals(expectedBufferSize, actual)) + .thenAwait(maxWaitTime) + .expectComplete() + .verify(TIMEOUT); assertTrue(countDownLatch.await(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS), "Did not get enough messages."); @@ -139,6 +142,97 @@ public void publishRoundRobin() throws InterruptedException { assertPropertiesUpdated(partitionPropertiesMap, propertiesAfterMap); } + /** + * Checks that sending an iterable with multiple partition keys is successful. + */ + @Test + public void publishWithPartitionId() throws InterruptedException { + // Arrange + final int numberOfEvents = partitionPropertiesMap.size() * 4; + + final AtomicBoolean anyFailures = new AtomicBoolean(false); + final List succeededContexts = new ArrayList<>(); + final CountDownLatch eventCountdown = new CountDownLatch(numberOfEvents); + + final Duration maxWaitTime = Duration.ofSeconds(15); + final int queueSize = 10; + + final EventHubClientBuilder builder = createBuilder(); + producer = new EventHubBufferedProducerClientBuilder() + .credential(builder.getFullyQualifiedNamespace(), builder.getEventHubName(), builder.getCredentials()) + .retryOptions(builder.getRetryOptions()) + .onSendBatchFailed(failed -> { + anyFailures.set(true); + fail("Exception occurred while sending messages." + failed.getThrowable()); + }) + .onSendBatchSucceeded(succeeded -> { + succeededContexts.add(succeeded); + succeeded.getEvents().forEach(e -> eventCountdown.countDown()); + }) + .maxEventBufferLengthPerPartition(queueSize) + .maxWaitTime(maxWaitTime) + .buildAsyncClient(); + + final Random randomInterval = new Random(10); + final Map> expectedPartitionIdsMap = new HashMap<>(); + + final List> publishEventMono = IntStream.range(0, numberOfEvents).mapToObj(index -> { + final int partitionId = index % this.partitionIds.length; + final String partitionIdString = String.valueOf(partitionId); + final String body = "-" + index + " Event sent to partition-" + partitionId; + final EventData eventData = new EventData(body); + eventData.getRawAmqpMessage() + .getMessageAnnotations() + .put(PARTITION_KEY_ANNOTATION_NAME.getValue(), "old partition key - should not be used"); + + final SendOptions sendOptions = new SendOptions().setPartitionId(partitionIdString); + final int delay = randomInterval.nextInt(20); + + expectedPartitionIdsMap.compute(partitionIdString, (key, existing) -> { + if (existing == null) { + List events = new ArrayList<>(); + events.add(body); + return events; + } else { + existing.add(body); + return existing; + } + }); + + return Mono.delay(Duration.ofSeconds(delay)) + .then(producer.enqueueEvent(eventData, sendOptions) + .doFinally(signal -> logger.log(LogLevel.VERBOSE, () -> String + .format("\t[%s] %s Published event.%n", partitionIdString, formatter.format(Instant.now()))))); + }).collect(Collectors.toList()); + + // Waiting for at least maxWaitTime because events will get published by then. + StepVerifier.create(Mono.when(publishEventMono)).expectComplete().verify(TIMEOUT); + + final boolean await = eventCountdown.await(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); + + assertTrue(await); + assertFalse(anyFailures.get(), "Should not have encountered any failures."); + assertFalse(succeededContexts.isEmpty(), "Should have successfully sent some messages."); + + for (SendBatchSucceededContext context : succeededContexts) { + final List expected = expectedPartitionIdsMap.get(context.getPartitionId()); + assertNotNull(expected, "Did not find any expected for partitionId: " + context.getPartitionId()); + + context.getEvents().forEach(eventData -> { + final boolean success = expected.removeIf(key -> key.equals(eventData.getBodyAsString())); + assertTrue(success, + "Unable to find key " + eventData.getBodyAsString() + " in partition id: " + context.getEvents()); + }); + } + + expectedPartitionIdsMap.forEach((key, value) -> { + assertTrue(value.isEmpty(), key + ": There should be no more partition keys. " + String.join(",", value)); + }); + + final Map finalProperties = getPartitionProperties(); + assertPropertiesUpdated(partitionPropertiesMap, finalProperties); + } + /** * Checks that sending an iterable with multiple partition keys is successful. */ @@ -280,7 +374,7 @@ public void publishAndReceiveWithPartitionKeys() throws InterruptedException { }).subscribe()); StepVerifier.create(producer.enqueueEvent(eventData, sendOptions)) - .expectNext(0) + .expectNext(1) .expectComplete() .verify(TIMEOUT); diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubBufferedProducerAsyncClientTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubBufferedProducerAsyncClientTest.java new file mode 100644 index 000000000000..2dc7861b343b --- /dev/null +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubBufferedProducerAsyncClientTest.java @@ -0,0 +1,239 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.messaging.eventhubs; + +import com.azure.core.amqp.AmqpRetryOptions; +import com.azure.core.util.tracing.Tracer; +import com.azure.messaging.eventhubs.EventHubBufferedProducerAsyncClient.BufferedProducerClientOptions; +import com.azure.messaging.eventhubs.models.CreateBatchOptions; +import com.azure.messaging.eventhubs.models.SendOptions; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import java.time.Duration; +import java.time.Instant; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class EventHubBufferedProducerAsyncClientTest { + private static final String PARTITION_ID = "10"; + private static final String NAMESPACE = "test-eventhubs-namespace"; + private static final String EVENT_HUB_NAME = "test-hub"; + private static final String[] PARTITION_IDS = new String[] { "one", "two", PARTITION_ID, "four" }; + + private AutoCloseable mockCloseable; + + private final Queue returnedBatches = new LinkedList<>(); + + @Mock + private Tracer tracer; + + @Mock + private EventHubClientBuilder clientBuilder; + + @Mock + private EventHubProducerAsyncClient asyncClient; + + @Mock + private EventDataBatch batch; + + @Mock + private EventDataBatch batch2; + + @Mock + private EventDataBatch batch3; + + @Mock + private EventDataBatch batch4; + + @Mock + private EventDataBatch batch5; + + @BeforeEach + public void beforeEach() { + mockCloseable = MockitoAnnotations.openMocks(this); + returnedBatches.add(batch); + returnedBatches.add(batch2); + returnedBatches.add(batch3); + returnedBatches.add(batch4); + returnedBatches.add(batch5); + + when(clientBuilder.buildAsyncProducerClient()).thenReturn(asyncClient); + + when(asyncClient.getFullyQualifiedNamespace()).thenReturn(NAMESPACE); + when(asyncClient.getEventHubName()).thenReturn(EVENT_HUB_NAME); + when(asyncClient.getPartitionIds()).thenReturn(Flux.fromArray(PARTITION_IDS)); + + when(asyncClient.createBatch(any(CreateBatchOptions.class))).thenAnswer(invocation -> { + final EventDataBatch returned = returnedBatches.poll(); + assertNotNull(returned, "there should be more batches to be returned."); + return Mono.just(returned); + }); + } + + @AfterEach + public void afterEach() throws Exception { + if (mockCloseable != null) { + mockCloseable.close(); + } + + Mockito.framework().clearInlineMock(this); + } + + @Test + public void enqueuesEvent() { + // Arrange + final BufferedProducerClientOptions clientOptions = new BufferedProducerClientOptions(); + + clientOptions.setMaxWaitTime(Duration.ofSeconds(5)); + clientOptions.setSendSucceededContext(succeedContext -> { + + }); + clientOptions.setSendFailedContext(failedContext -> { + + }); + + final PartitionResolver partitionResolver = new PartitionResolver(); + final AmqpRetryOptions retryOptions + = new AmqpRetryOptions().setMaxRetries(0).setTryTimeout(clientOptions.getMaxWaitTime()); + + // Range some assumptions about the producer client. + final List partitionIds + = IntStream.range(0, 1).mapToObj(index -> Integer.toString(index)).collect(Collectors.toList()); + final EventHubProperties eventHubProperties + = new EventHubProperties("test", Instant.ofEpochSecond(1740431270L), partitionIds.toArray(new String[0])); + final EventData eventData = new EventData("foo-bar"); + + when(asyncClient.getEventHubProperties()).thenReturn(Mono.fromSupplier(() -> eventHubProperties)); + when(batch.tryAdd(eventData)).thenReturn(true); + + try (EventHubBufferedProducerAsyncClient bufferedClient = new EventHubBufferedProducerAsyncClient(clientBuilder, + clientOptions, partitionResolver, retryOptions, tracer)) { + + // Don't assert the count of events count because EventDataBatch is mocked. + StepVerifier.create(bufferedClient.enqueueEvent(eventData)).expectNextCount(1).expectComplete().verify(); + } + + verify(batch).tryAdd(eventData); + } + + @Test + public void enqueuesEventWithPartitionKey() { + // Arrange + final BufferedProducerClientOptions clientOptions = new BufferedProducerClientOptions(); + + clientOptions.setMaxWaitTime(Duration.ofSeconds(5)); + clientOptions.setSendSucceededContext(succeedContext -> { + }); + clientOptions.setSendFailedContext(failedContext -> { + }); + + final PartitionResolver partitionResolver = new PartitionResolver(); + final AmqpRetryOptions retryOptions + = new AmqpRetryOptions().setMaxRetries(0).setTryTimeout(clientOptions.getMaxWaitTime()); + final EventHubProperties eventHubProperties + = new EventHubProperties("test", Instant.ofEpochSecond(1740431270L), PARTITION_IDS); + final SendOptions sendOptions = new SendOptions().setPartitionKey("my-partition-key"); + final EventData eventData = new EventData("foo-bar"); + + when(asyncClient.getEventHubProperties()).thenReturn(Mono.fromSupplier(() -> eventHubProperties)); + when(batch.tryAdd(eventData)).thenReturn(true); + + try (EventHubBufferedProducerAsyncClient bufferedClient = new EventHubBufferedProducerAsyncClient(clientBuilder, + clientOptions, partitionResolver, retryOptions, tracer)) { + + // Don't assert the count of events count because EventDataBatch is mocked. + StepVerifier.create(bufferedClient.enqueueEvent(eventData, sendOptions)) + .expectNextCount(1) + .expectComplete() + .verify(); + } + } + + @Test + public void enqueuesEventWithPartitionId() { + // Arrange + final BufferedProducerClientOptions clientOptions = new BufferedProducerClientOptions(); + + clientOptions.setMaxWaitTime(Duration.ofSeconds(5)); + clientOptions.setSendSucceededContext(succeedContext -> { + + }); + clientOptions.setSendFailedContext(failedContext -> { + + }); + + final PartitionResolver partitionResolver = new PartitionResolver(); + final AmqpRetryOptions retryOptions + = new AmqpRetryOptions().setMaxRetries(0).setTryTimeout(clientOptions.getMaxWaitTime()); + + final EventHubProperties eventHubProperties + = new EventHubProperties("test", Instant.ofEpochSecond(1740431270L), PARTITION_IDS); + final SendOptions sendOptions = new SendOptions().setPartitionId(PARTITION_ID); + final EventData eventData = new EventData("foo-bar"); + + when(asyncClient.getEventHubProperties()).thenReturn(Mono.fromSupplier(() -> eventHubProperties)); + when(batch.tryAdd(eventData)).thenReturn(true); + + try (EventHubBufferedProducerAsyncClient bufferedClient = new EventHubBufferedProducerAsyncClient(clientBuilder, + clientOptions, partitionResolver, retryOptions, tracer)) { + + // Don't assert the count of events count because EventDataBatch is mocked. + StepVerifier.create(bufferedClient.enqueueEvent(eventData, sendOptions)) + .expectNextCount(1) + .expectComplete() + .verify(); + } + } + + @Test + public void receivesEventHubProperties() { + // Arrange + final BufferedProducerClientOptions clientOptions = new BufferedProducerClientOptions(); + final PartitionResolver partitionResolver = new PartitionResolver(); + final String[] partitionIds = new String[5]; + for (int i = 0; i < partitionIds.length; i++) { + partitionIds[i] = Integer.toString(i); + } + + final String firstPartitionId = partitionIds[0]; + final PartitionProperties expectedPartitionProperties = new PartitionProperties(EVENT_HUB_NAME, + firstPartitionId, 0L, 120L, "1256S", Instant.ofEpochSecond(1740431210L), true); + final EventHubProperties eventHubProperties + = new EventHubProperties(EVENT_HUB_NAME, Instant.ofEpochSecond(1740431270L), partitionIds); + + when(asyncClient.getPartitionProperties(firstPartitionId)) + .thenReturn(Mono.defer(() -> Mono.just(expectedPartitionProperties))); + when(asyncClient.getEventHubProperties()).thenReturn(Mono.fromSupplier(() -> eventHubProperties)); + + try (EventHubBufferedProducerAsyncClient bufferedClient = new EventHubBufferedProducerAsyncClient(clientBuilder, + clientOptions, partitionResolver, new AmqpRetryOptions(), tracer)) { + + Assertions.assertEquals(EVENT_HUB_NAME, bufferedClient.getEventHubName()); + Assertions.assertEquals(NAMESPACE, bufferedClient.getFullyQualifiedNamespace()); + + StepVerifier.create(bufferedClient.getPartitionIds()).expectNext(partitionIds).expectComplete().verify(); + + StepVerifier.create(bufferedClient.getPartitionProperties(firstPartitionId)).assertNext(actual -> { + Assertions.assertEquals(expectedPartitionProperties, actual); + }).expectComplete().verify(); + } + } +} diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubProducerAsyncClientIntegrationTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubProducerAsyncClientIntegrationTest.java index f0d3f92cd932..103e2591da65 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubProducerAsyncClientIntegrationTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubProducerAsyncClientIntegrationTest.java @@ -117,14 +117,22 @@ void sendEventsWithKeyAndPartition() { final List events = Arrays.asList(new EventData("Event 1".getBytes(UTF_8)), new EventData("Event 2".getBytes(UTF_8)), new EventData("Event 3".getBytes(UTF_8))); - // Act - final Mono onComplete = Mono.when(producer.send(events), producer.send(Flux.just(events.get(0))), - producer.send(Flux.fromIterable(events), new SendOptions().setPartitionId("3")), - producer.send(Flux.fromIterable(events), new SendOptions().setPartitionId("4")), - producer.send(Flux.fromIterable(events), new SendOptions().setPartitionKey("sandwiches"))); - - // Assert - StepVerifier.create(onComplete).expectComplete().verify(TIMEOUT); + // Act & Assert + StepVerifier.create(producer.send(events)).expectComplete().verify(TIMEOUT); + + StepVerifier.create(producer.send(Flux.just(events.get(0)))).expectComplete().verify(TIMEOUT); + + StepVerifier.create(producer.send(Flux.fromIterable(events), new SendOptions().setPartitionId("3"))) + .expectComplete() + .verify(TIMEOUT); + + StepVerifier.create(producer.send(Flux.fromIterable(events), new SendOptions().setPartitionId("4"))) + .expectComplete() + .verify(TIMEOUT); + + StepVerifier.create(producer.send(Flux.fromIterable(events), new SendOptions().setPartitionKey("sandwiches"))) + .expectComplete() + .verify(TIMEOUT); } @Test 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 35dc9b9dde23..ca37f003a406 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 @@ -15,11 +15,9 @@ import com.azure.core.util.ConfigurationBuilder; import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; -import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.messaging.eventhubs.models.SendOptions; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.BeforeEach; import org.mockito.Mockito; import reactor.core.Disposable; @@ -38,6 +36,11 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; +import static com.azure.messaging.eventhubs.TestUtils.AZURE_EVENTHUBS_EVENT_HUB_NAME; +import static com.azure.messaging.eventhubs.TestUtils.AZURE_EVENTHUBS_FULLY_QUALIFIED_DOMAIN_NAME; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + /** * Test base for running integration tests. */ @@ -61,9 +64,6 @@ public abstract class IntegrationTestBase extends TestBase { protected String testName; - private static final ClientOptions OPTIONS_WITH_TRACING - = new ClientOptions().setTracingOptions(new LoggingTracerProvider.LoggingTracingOptions()); - private Scheduler scheduler; private static Map testEventData; private List toClose = new ArrayList<>(); @@ -81,7 +81,7 @@ public void setupTest(TestContextManager testContextManager) { testContextManager.getTestPlaybackRecordingName()); testName = testContextManager.getTrackerTestName(); - skipIfNotRecordMode(); + skipIfNotRecordOrLiveMode(); toClose = new ArrayList<>(); scheduler = Schedulers.newParallel("eh-integration"); @@ -116,62 +116,56 @@ public void teardownTest() { } /** - * Creates a new instance of {@link EventHubClientBuilder} with the default integration test settings and uses a - * connection string to authenticate. + * Creates a new instance of {@link EventHubClientBuilder} with the default integration test settings and does not + * share a connection string. */ protected EventHubClientBuilder createBuilder() { return createBuilder(false); } /** - * Creates a new instance of {@link EventHubClientBuilder} with the default integration test settings and uses a - * connection string to authenticate if {@code useCredentials} is false. Otherwise, uses a service principal through - * {@link com.azure.identity.ClientSecretCredential}. + * Creates a new instance of {@link EventHubClientBuilder} with the default integration test settings. Assumes test + * mode is not {@link TestMode#PLAYBACK}. */ protected EventHubClientBuilder createBuilder(boolean shareConnection) { + skipIfNotRecordOrLiveMode(); + + // Enables tracing. + final ClientOptions clientOptions + = new ClientOptions().setTracingOptions(new LoggingTracerProvider.LoggingTracingOptions()); + final EventHubClientBuilder builder = new EventHubClientBuilder().proxyOptions(ProxyOptions.SYSTEM_DEFAULTS) .retryOptions(RETRY_OPTIONS) - .clientOptions(OPTIONS_WITH_TRACING) + .clientOptions(clientOptions) .transportType(AmqpTransportType.AMQP) .scheduler(scheduler) .configuration(new ConfigurationBuilder().putProperty("com.azure.messaging.eventhubs.v2", "true").build()); - final String fullyQualifiedDomainName = TestUtils.getFullyQualifiedDomainName(); - final String eventHubName = TestUtils.getEventHubName(); - if (shareConnection) { builder.shareConnection(); } - switch (getTestMode()) { - case PLAYBACK: - Assumptions.assumeTrue(false, "Integration tests are not enabled in playback mode."); - return null; - - case LIVE: - Assumptions.assumeTrue(!CoreUtils.isNullOrEmpty(fullyQualifiedDomainName), - "FullyQualifiedDomainName is not set."); - Assumptions.assumeTrue(!CoreUtils.isNullOrEmpty(fullyQualifiedDomainName), "EventHubName is not set."); - - final TokenCredential credential = TestUtils.getPipelineCredential(credentialCached); - return builder.credential(fullyQualifiedDomainName, eventHubName, credential); - - case RECORD: - final String connectionString = TestUtils.getConnectionString(false); - - Assumptions.assumeTrue(!CoreUtils.isNullOrEmpty(eventHubName), "EventHubName is not set."); - Assumptions.assumeTrue(!CoreUtils.isNullOrEmpty(fullyQualifiedDomainName), - "FullyQualifiedDomainName is not set."); - - if (CoreUtils.isNullOrEmpty(connectionString)) { - final TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); - return builder.credential(fullyQualifiedDomainName, eventHubName, tokenCredential); - } else { - return builder.connectionString(connectionString).eventHubName(eventHubName); - } - default: - return null; + final TokenCredential tokenCredential = TestUtils.getTokenCredential(getTestMode(), credentialCached); + + assumeTrue(tokenCredential != null, "Token credential could not be created using " + getTestMode()); + + if (getTestMode() == TestMode.PLAYBACK) { + return builder.credential(tokenCredential); } + + final String fullyQualifiedDomainName = TestUtils.getFullyQualifiedDomainName(); + final String eventHubName = TestUtils.getEventHubName(); + + assumeFalse(CoreUtils.isNullOrEmpty(fullyQualifiedDomainName), + "Env variable: '" + AZURE_EVENTHUBS_FULLY_QUALIFIED_DOMAIN_NAME + "' must be set."); + assumeFalse(CoreUtils.isNullOrEmpty(eventHubName), + "Env variable: '" + AZURE_EVENTHUBS_EVENT_HUB_NAME + "' must be set."); + + return builder.credential(fullyQualifiedDomainName, eventHubName, tokenCredential); + } + + protected TokenCredential getOrCreateTokenCredential() { + return TestUtils.getTokenCredential(getTestMode(), credentialCached); } /** @@ -247,8 +241,7 @@ protected void dispose() { toClose.clear(); } - private void skipIfNotRecordMode() { - Assumptions.assumeTrue(getTestMode() != TestMode.PLAYBACK, "Is not in RECORD/LIVE mode."); + private void skipIfNotRecordOrLiveMode() { + assumeTrue(getTestMode() != TestMode.PLAYBACK, "Is not in RECORD/LIVE mode."); } - } diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/NonFederatedIntegrationTests.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/NonFederatedIntegrationTests.java index 561bb5a74ff8..58db1f1c76af 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/NonFederatedIntegrationTests.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/NonFederatedIntegrationTests.java @@ -15,6 +15,7 @@ import com.azure.messaging.eventhubs.models.SendOptions; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import reactor.test.StepVerifier; @@ -23,6 +24,7 @@ import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.jupiter.api.Assertions.assertTrue; +@Tag("integration") public class NonFederatedIntegrationTests extends IntegrationTestBase { private static final ClientLogger LOGGER = new ClientLogger(NonFederatedIntegrationTests.class); private static final String PARTITION_ID = "2"; @@ -34,8 +36,8 @@ public class NonFederatedIntegrationTests extends IntegrationTestBase { @Test @EnabledIfEnvironmentVariable( named = "AZURE_EVENTHUBS_CONNECTION_STRING_WITH_SAS", - matches = ".*ShadAccessSignature .*") - void sendWithSasConnectionString() { + matches = ".*SharedAccessSignature.*") + public void sendWithSasConnectionString() { final String eventHubName = TestUtils.getEventHubName(); final EventData event = new EventData("body"); final SendOptions options = new SendOptions().setPartitionId(PARTITION_ID); @@ -54,6 +56,7 @@ void sendWithSasConnectionString() { } @Test + @EnabledIfEnvironmentVariable(named = "AZURE_EVENTHUBS_CONNECTION_STRING", matches = ".*SharedAccessKey.*") public void sendAndReceiveEventByAzureSasCredential() { Assumptions.assumeTrue(TestUtils.getConnectionString(true) != null, "SAS was not set. Can't run test scenario."); @@ -76,6 +79,7 @@ public void sendAndReceiveEventByAzureSasCredential() { } @Test + @EnabledIfEnvironmentVariable(named = "AZURE_EVENTHUBS_CONNECTION_STRING", matches = ".*SharedAccessKey.*") public void sendAndReceiveEventByAzureNameKeyCredential() { ConnectionStringProperties properties = getConnectionStringProperties(); String fullyQualifiedNamespace = properties.getEndpoint().getHost(); @@ -101,6 +105,7 @@ public void sendAndReceiveEventByAzureNameKeyCredential() { * Verifies that error conditions are handled for fetching Event Hub metadata. */ @Test + @EnabledIfEnvironmentVariable(named = "AZURE_EVENTHUBS_CONNECTION_STRING", matches = ".*SharedAccessKey.*") public void getPartitionPropertiesInvalidToken() { // Arrange final ConnectionStringProperties original = getConnectionStringProperties(); @@ -127,6 +132,7 @@ public void getPartitionPropertiesInvalidToken() { * Verifies that error conditions are handled for fetching partition metadata. */ @Test + @EnabledIfEnvironmentVariable(named = "AZURE_EVENTHUBS_CONNECTION_STRING", matches = ".*SharedAccessKey.*") public void getPartitionPropertiesNonExistentHub() { // Arrange final ConnectionStringProperties original = getConnectionStringProperties(); diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/TestUtils.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/TestUtils.java index 3ad058b6ef5d..52e1f9e71341 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/TestUtils.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/TestUtils.java @@ -7,14 +7,19 @@ import com.azure.core.amqp.ProxyAuthenticationType; import com.azure.core.amqp.ProxyOptions; import com.azure.core.amqp.implementation.ConnectionStringProperties; +import com.azure.core.amqp.models.AmqpAnnotatedMessage; import com.azure.core.credential.TokenCredential; +import com.azure.core.test.TestMode; +import com.azure.core.test.utils.MockTokenCredential; import com.azure.core.util.Configuration; +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.identity.AzurePipelinesCredentialBuilder; -import com.azure.core.amqp.models.AmqpAnnotatedMessage; -import com.azure.core.util.Context; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.messaging.eventhubs.implementation.ClientConstants; +import com.azure.messaging.eventhubs.implementation.EventHubSharedKeyCredential; import com.azure.messaging.eventhubs.implementation.instrumentation.OperationName; import com.azure.messaging.eventhubs.models.PartitionEvent; import io.opentelemetry.api.common.Attributes; @@ -42,6 +47,7 @@ import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.util.Base64; +import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; @@ -58,11 +64,9 @@ import static com.azure.core.amqp.ProxyOptions.PROXY_AUTHENTICATION_TYPE; import static com.azure.core.amqp.ProxyOptions.PROXY_PASSWORD; import static com.azure.core.amqp.ProxyOptions.PROXY_USERNAME; -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.jupiter.api.Assumptions.assumeTrue; import static com.azure.messaging.eventhubs.implementation.instrumentation.InstrumentationUtils.ERROR_TYPE; -import static com.azure.messaging.eventhubs.implementation.instrumentation.InstrumentationUtils.MESSAGING_DESTINATION_NAME; import static com.azure.messaging.eventhubs.implementation.instrumentation.InstrumentationUtils.MESSAGING_CONSUMER_GROUP_NAME; +import static com.azure.messaging.eventhubs.implementation.instrumentation.InstrumentationUtils.MESSAGING_DESTINATION_NAME; import static com.azure.messaging.eventhubs.implementation.instrumentation.InstrumentationUtils.MESSAGING_DESTINATION_PARTITION_ID; import static com.azure.messaging.eventhubs.implementation.instrumentation.InstrumentationUtils.MESSAGING_OPERATION_NAME; import static com.azure.messaging.eventhubs.implementation.instrumentation.InstrumentationUtils.MESSAGING_OPERATION_TYPE; @@ -70,19 +74,16 @@ import static com.azure.messaging.eventhubs.implementation.instrumentation.InstrumentationUtils.MESSAGING_SYSTEM_VALUE; import static com.azure.messaging.eventhubs.implementation.instrumentation.InstrumentationUtils.SERVER_ADDRESS; import static com.azure.messaging.eventhubs.implementation.instrumentation.InstrumentationUtils.getOperationType; +import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * Contains helper methods for working with AMQP messages */ public final class TestUtils { private static final ClientLogger LOGGER = new ClientLogger(TestUtils.class); - - private static final String AZURE_EVENTHUBS_FULLY_QUALIFIED_DOMAIN_NAME - = "AZURE_EVENTHUBS_FULLY_QUALIFIED_DOMAIN_NAME"; - private static final String AZURE_EVENTHUBS_EVENT_HUB_NAME = "AZURE_EVENTHUBS_EVENT_HUB_NAME"; - private static final String AZURE_EVENTHUBS_CONNECTION_STRING = "AZURE_EVENTHUBS_CONNECTION_STRING"; private static final Configuration GLOBAL_CONFIGURATION = Configuration.getGlobalConfiguration(); // System and application properties from the generated test message. @@ -104,6 +105,12 @@ public final class TestUtils { */ public static final String INTEGRATION = "integration"; + public static final String AZURE_EVENTHUBS_FULLY_QUALIFIED_DOMAIN_NAME + = "AZURE_EVENTHUBS_FULLY_QUALIFIED_DOMAIN_NAME"; + public static final String AZURE_EVENTHUBS_EVENT_HUB_NAME = "AZURE_EVENTHUBS_EVENT_HUB_NAME"; + + public static final String AZURE_EVENTHUBS_CONNECTION_STRING = "AZURE_EVENTHUBS_CONNECTION_STRING"; + static { APPLICATION_PROPERTIES.put("test-name", EventDataTest.class.getName()); APPLICATION_PROPERTIES.put("a-number", 10L); @@ -163,7 +170,33 @@ public static String getEventHubName() { * Creates a mock message with the contents provided. */ static Message getMessage(byte[] contents, String messageTrackingValue) { - return getMessage(contents, messageTrackingValue, SEQUENCE_NUMBER, OFFSET, Date.from(ENQUEUED_TIME)); + return getMessage(contents, messageTrackingValue, Collections.emptyMap()); + } + + /** + * Creates a message with the given contents, default system properties, and adds a {@code messageTrackingValue} in + * the application properties. Useful for helping filter messages. + */ + static Message getMessage(byte[] contents, String messageTrackingValue, Map additionalProperties) { + final Message message + = getMessage(contents, messageTrackingValue, SEQUENCE_NUMBER, OFFSET, Date.from(ENQUEUED_TIME)); + + Map value = message.getMessageAnnotations().getValue(); + value.put(Symbol.getSymbol(OTHER_SYSTEM_PROPERTY), OTHER_SYSTEM_PROPERTY_VALUE); + + Map applicationProperties = new HashMap<>(APPLICATION_PROPERTIES); + + if (!CoreUtils.isNullOrEmpty(messageTrackingValue)) { + applicationProperties.put(MESSAGE_ID, messageTrackingValue); + } + + if (additionalProperties != null) { + applicationProperties.putAll(additionalProperties); + } + + message.setApplicationProperties(new ApplicationProperties(applicationProperties)); + + return message; } /** @@ -212,6 +245,20 @@ static EventData getEvent(String body, String messageTrackingValue, int position return eventData; } + public static EventData getEvent(AmqpAnnotatedMessage amqpAnnotatedMessage, Long offset, long sequenceNumber, + Instant enqueuedTime) { + + amqpAnnotatedMessage.getMessageAnnotations() + .put(AmqpMessageConstant.SEQUENCE_NUMBER_ANNOTATION_NAME.getValue(), sequenceNumber); + amqpAnnotatedMessage.getMessageAnnotations() + .put(AmqpMessageConstant.ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue(), enqueuedTime); + + SystemProperties systemProperties + = new SystemProperties(amqpAnnotatedMessage, offset, enqueuedTime, sequenceNumber, null); + + return new EventData(amqpAnnotatedMessage, systemProperties, Context.NONE); + } + /** * Checks the {@link #MESSAGE_ID} to see if it matches the {@code expectedValue}. */ @@ -283,8 +330,52 @@ public static TokenCredential getPipelineCredential(AtomicReference + *

      1. {@link TestMode#PLAYBACK} will create a {@link MockTokenCredential}
      2. + *
      3. {@link TestMode#LIVE} will try to create a federated pipeline credential, else will use the + * {@link com.azure.identity.DefaultAzureCredential}.
      4. + *
      5. {@link TestMode#RECORD} will try using the connection string set via environment variable + * {@link TestUtils#AZURE_EVENTHUBS_CONNECTION_STRING}, else will use the + * {@link com.azure.identity.DefaultAzureCredential}.
      6. + * + * + * @param testMode Test mode test is running in. + * @param credentialCached If there is a cached credential to also query. + * + * @return The token credential or {@code null} if one could not be found. + */ + public static TokenCredential getTokenCredential(TestMode testMode, + AtomicReference credentialCached) { + + switch (testMode) { + case PLAYBACK: + return new MockTokenCredential(); + + case LIVE: + return TestUtils.getPipelineCredential(credentialCached); + + case RECORD: + final String connectionString = TestUtils.getConnectionString(false); + + if (CoreUtils.isNullOrEmpty(connectionString)) { + return new DefaultAzureCredentialBuilder().build(); + } else { + final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); + return properties.getSharedAccessSignature() == null + ? new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(), + properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY) + : new EventHubSharedKeyCredential(properties.getSharedAccessSignature()); + } + default: + return null; + } + } + public static String getConnectionString(boolean withSas) { - String connectionString = Configuration.getGlobalConfiguration().get("AZURE_EVENTHUBS_CONNECTION_STRING"); + String connectionString = Configuration.getGlobalConfiguration().get(AZURE_EVENTHUBS_CONNECTION_STRING); if (withSas) { String shareAccessSignatureFormat = "SharedAccessSignature sr=%s&sig=%s&se=%s&skn=%s"; String connectionStringWithSasAndEntityFormat = "Endpoint=%s;SharedAccessSignature=%s;EntityPath=%s"; @@ -293,7 +384,7 @@ public static String getConnectionString(boolean withSas) { ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); URI endpoint = properties.getEndpoint(); String entityPath = properties.getEntityPath(); - String resourceUrl = entityPath == null || entityPath.trim().length() == 0 + String resourceUrl = entityPath == null || entityPath.trim().isEmpty() ? endpoint.toString() : endpoint.toString() + entityPath; @@ -373,19 +464,6 @@ public static void assertSpanStatus(String description, SpanData span) { } } - public static EventData createEventData(AmqpAnnotatedMessage amqpAnnotatedMessage, long offset, long sequenceNumber, - Instant enqueuedTime) { - amqpAnnotatedMessage.getMessageAnnotations().put(AmqpMessageConstant.OFFSET_ANNOTATION_NAME.getValue(), offset); - amqpAnnotatedMessage.getMessageAnnotations() - .put(AmqpMessageConstant.SEQUENCE_NUMBER_ANNOTATION_NAME.getValue(), sequenceNumber); - amqpAnnotatedMessage.getMessageAnnotations() - .put(AmqpMessageConstant.ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue(), enqueuedTime); - - SystemProperties systemProperties - = new SystemProperties(amqpAnnotatedMessage, offset, enqueuedTime, sequenceNumber, null); - return new EventData(amqpAnnotatedMessage, systemProperties, Context.NONE); - } - private TestUtils() { } } diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/NonFederatedCBSChannelTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/NonFederatedCBSChannelTest.java index 64f4a7073e2a..ab513eef4f36 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/NonFederatedCBSChannelTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/NonFederatedCBSChannelTest.java @@ -35,6 +35,7 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import reactor.core.publisher.Mono; @@ -122,7 +123,8 @@ protected void afterTest() { } @Test - void successfullyAuthorizes() { + @EnabledIfEnvironmentVariable(named = "AZURE_EVENTHUBS_CONNECTION_STRING", matches = ".*SharedAccessKey.*") + public void successfullyAuthorizes() { // Arrange TokenCredential tokenCredential = new EventHubSharedKeyCredential(connectionProperties.getSharedAccessKeyName(), connectionProperties.getSharedAccessKey()); @@ -145,7 +147,8 @@ void successfullyAuthorizes() { } @Test - void unsuccessfulAuthorize() { + @EnabledIfEnvironmentVariable(named = "AZURE_EVENTHUBS_CONNECTION_STRING", matches = ".*SharedAccessKey.*") + public void unsuccessfulAuthorize() { // Arrange final TokenCredential invalidToken = new EventHubSharedKeyCredential( connectionProperties.getSharedAccessKeyName(), "Invalid shared access key."); diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/instrumentation/EventHubsConsumerInstrumentationTests.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/instrumentation/EventHubsConsumerInstrumentationTests.java index ce8d7afe879e..4a2aa4d81952 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/instrumentation/EventHubsConsumerInstrumentationTests.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/instrumentation/EventHubsConsumerInstrumentationTests.java @@ -568,7 +568,7 @@ private static EventData createEventData(Instant enqueuedTime, String traceparen annotatedMessage.getApplicationProperties().put("traceparent", traceparent); annotatedMessage.getMessageAnnotations() .put(AmqpMessageConstant.ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue(), enqueuedTime); - return TestUtils.createEventData(annotatedMessage, 25L, 14L, enqueuedTime); + return TestUtils.getEvent(annotatedMessage, 25L, 14L, enqueuedTime); } private SpanData assertReceiveSpan(int expectedBatchSize, String partitionId, String expectedErrorType, diff --git a/sdk/eventhubs/microsoft-azure-eventhubs-eph/README.md b/sdk/eventhubs/microsoft-azure-eventhubs-eph/README.md index 39082b532655..968000a4f3c6 100644 --- a/sdk/eventhubs/microsoft-azure-eventhubs-eph/README.md +++ b/sdk/eventhubs/microsoft-azure-eventhubs-eph/README.md @@ -11,4 +11,4 @@ not present in that lower layer. See the [README for Azure Event Hubs Client for include Event Processor Host in your project. See the [overview](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/eventhubs/microsoft-azure-eventhubs-eph/Overview.md) for details of the functionality that Event Processor Host offers and how to use it. -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Feventhubs%2Fmicrosoft-azure-eventhubs-eph%2FReadme.png) + diff --git a/sdk/eventhubs/microsoft-azure-eventhubs-eph/pom.xml b/sdk/eventhubs/microsoft-azure-eventhubs-eph/pom.xml index 0076d56c2036..5ec0b9e7c2d9 100644 --- a/sdk/eventhubs/microsoft-azure-eventhubs-eph/pom.xml +++ b/sdk/eventhubs/microsoft-azure-eventhubs-eph/pom.xml @@ -64,7 +64,7 @@ com.microsoft.azure msal4j - 1.17.2 + 1.19.1 test @@ -82,7 +82,7 @@ org.apache.maven.plugins maven-checkstyle-plugin - 3.5.0 + 3.6.0 true true diff --git a/sdk/eventhubs/microsoft-azure-eventhubs/README.md b/sdk/eventhubs/microsoft-azure-eventhubs/README.md index be3602a749cd..900c756c0ecc 100644 --- a/sdk/eventhubs/microsoft-azure-eventhubs/README.md +++ b/sdk/eventhubs/microsoft-azure-eventhubs/README.md @@ -129,4 +129,4 @@ Set the following two Environment variables to be able to run unit tests targeti For more details on this visit - [how to create an Azure Storage account connection string](https://learn.microsoft.com/azure/storage/common/storage-configure-connection-string#create-a-connection-string-for-an-azure-storage-account). -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Feventhubs%2Fmicrosoft-azure-eventhubs%2FREADME.png) + diff --git a/sdk/eventhubs/microsoft-azure-eventhubs/pom.xml b/sdk/eventhubs/microsoft-azure-eventhubs/pom.xml index 709e4b2b6b5e..58a59733201e 100644 --- a/sdk/eventhubs/microsoft-azure-eventhubs/pom.xml +++ b/sdk/eventhubs/microsoft-azure-eventhubs/pom.xml @@ -77,7 +77,7 @@ com.microsoft.azure msal4j - 1.17.2 + 1.19.1 test @@ -115,7 +115,7 @@ - + diff --git a/sdk/eventhubs/test-resources.json b/sdk/eventhubs/test-resources.json index 065c38924d1b..7d86a60811d5 100644 --- a/sdk/eventhubs/test-resources.json +++ b/sdk/eventhubs/test-resources.json @@ -49,6 +49,7 @@ "zoneRedundant": false, "isAutoInflateEnabled": false, "maximumThroughputUnits": 0, + "disableLocalAuth": true, "kafkaEnabled": true } }, @@ -68,10 +69,6 @@ } ], "outputs": { - "AZURE_EVENTHUBS_CONNECTION_STRING": { - "type": "string", - "value": "[concat(listKeys(resourceId('Microsoft.EventHub/namespaces/authorizationRules', variables('eventHubsNamespaceName'), 'RootManageSharedAccessKey'), variables('eventHubsApiVersion')).primaryConnectionString)]" - }, "AZURE_EVENTHUBS_EVENT_HUB_NAME": { "type": "string", "value": "[parameters('eventHubName')]" diff --git a/sdk/extendedlocation/azure-resourcemanager-extendedlocation/README.md b/sdk/extendedlocation/azure-resourcemanager-extendedlocation/README.md index 642db9fe4a8f..29e890677246 100644 --- a/sdk/extendedlocation/azure-resourcemanager-extendedlocation/README.md +++ b/sdk/extendedlocation/azure-resourcemanager-extendedlocation/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-extendedlocation - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fextendedlocation%2Fazure-resourcemanager-extendedlocation%2FREADME.png) + diff --git a/sdk/extendedlocation/azure-resourcemanager-extendedlocation/pom.xml b/sdk/extendedlocation/azure-resourcemanager-extendedlocation/pom.xml index 01ff0119aeb2..a61f9e8f9715 100644 --- a/sdk/extendedlocation/azure-resourcemanager-extendedlocation/pom.xml +++ b/sdk/extendedlocation/azure-resourcemanager-extendedlocation/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/fabric/azure-resourcemanager-fabric/README.md b/sdk/fabric/azure-resourcemanager-fabric/README.md index edfd2cb538ee..5020c43bebb3 100644 --- a/sdk/fabric/azure-resourcemanager-fabric/README.md +++ b/sdk/fabric/azure-resourcemanager-fabric/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-fabric - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Ffabric%2Fazure-resourcemanager-fabric%2FREADME.png) + diff --git a/sdk/fabric/azure-resourcemanager-fabric/pom.xml b/sdk/fabric/azure-resourcemanager-fabric/pom.xml index 72fea2f76c63..abf674c7dff4 100644 --- a/sdk/fabric/azure-resourcemanager-fabric/pom.xml +++ b/sdk/fabric/azure-resourcemanager-fabric/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/fabric/azure-resourcemanager-fabric/src/main/java/com/azure/resourcemanager/fabric/FabricManager.java b/sdk/fabric/azure-resourcemanager-fabric/src/main/java/com/azure/resourcemanager/fabric/FabricManager.java index 6d7a898a1555..8b314bcd053b 100644 --- a/sdk/fabric/azure-resourcemanager-fabric/src/main/java/com/azure/resourcemanager/fabric/FabricManager.java +++ b/sdk/fabric/azure-resourcemanager-fabric/src/main/java/com/azure/resourcemanager/fabric/FabricManager.java @@ -22,6 +22,7 @@ import com.azure.core.http.policy.UserAgentPolicy; import com.azure.core.management.profile.AzureProfile; import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.fabric.fluent.FabricManagementClient; import com.azure.resourcemanager.fabric.implementation.FabricCapacitiesImpl; @@ -33,6 +34,7 @@ import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; @@ -96,6 +98,9 @@ public static Configurable configure() { */ public static final class Configurable { private static final ClientLogger LOGGER = new ClientLogger(Configurable.class); + private static final String SDK_VERSION = "version"; + private static final Map PROPERTIES + = CoreUtils.getProperties("azure-resourcemanager-fabric.properties"); private HttpClient httpClient; private HttpLogOptions httpLogOptions; @@ -203,12 +208,14 @@ public FabricManager authenticate(TokenCredential credential, AzureProfile profi Objects.requireNonNull(credential, "'credential' cannot be null."); Objects.requireNonNull(profile, "'profile' cannot be null."); + String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); + StringBuilder userAgentBuilder = new StringBuilder(); userAgentBuilder.append("azsdk-java") .append("-") .append("com.azure.resourcemanager.fabric") .append("/") - .append("1.0.0-beta.1"); + .append(clientVersion); if (!Configuration.getGlobalConfiguration().get("AZURE_TELEMETRY_DISABLED", false)) { userAgentBuilder.append(" (") .append(Configuration.getGlobalConfiguration().get("java.version")) diff --git a/sdk/fabric/azure-resourcemanager-fabric/src/main/resources/azure-resourcemanager-fabric.properties b/sdk/fabric/azure-resourcemanager-fabric/src/main/resources/azure-resourcemanager-fabric.properties new file mode 100644 index 000000000000..defbd48204e4 --- /dev/null +++ b/sdk/fabric/azure-resourcemanager-fabric/src/main/resources/azure-resourcemanager-fabric.properties @@ -0,0 +1 @@ +version=${project.version} diff --git a/sdk/face/azure-ai-vision-face/README.md b/sdk/face/azure-ai-vision-face/README.md index 482d8bae8c81..8f42ce02023e 100644 --- a/sdk/face/azure-ai-vision-face/README.md +++ b/sdk/face/azure-ai-vision-face/README.md @@ -39,7 +39,7 @@ Azure AI Face supports both [multi-service][azure_cognitive_service_account] and com.azure azure-ai-vision-face - 1.0.0-beta.1 + 1.0.0-beta.3 ``` [//]: # ({x-version-update-end}) @@ -89,7 +89,7 @@ To use the [DefaultAzureCredential][azure_sdk_java_default_azure_credential] typ com.azure azure-identity - 1.14.2 + 1.15.3 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/face/azure-ai-vision-face/pom.xml b/sdk/face/azure-ai-vision-face/pom.xml index 9778e0027b98..84a933df74d1 100644 --- a/sdk/face/azure-ai-vision-face/pom.xml +++ b/sdk/face/azure-ai-vision-face/pom.xml @@ -54,28 +54,28 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/face/azure-ai-vision-face/src/main/java/com/azure/ai/vision/face/FaceSessionAsyncClient.java b/sdk/face/azure-ai-vision-face/src/main/java/com/azure/ai/vision/face/FaceSessionAsyncClient.java index 88d35243a913..8aa67438dbd9 100644 --- a/sdk/face/azure-ai-vision-face/src/main/java/com/azure/ai/vision/face/FaceSessionAsyncClient.java +++ b/sdk/face/azure-ai-vision-face/src/main/java/com/azure/ai/vision/face/FaceSessionAsyncClient.java @@ -437,8 +437,8 @@ Mono> createLivenessWithVerifySessionWithResponse(BinaryDat @ServiceMethod(returns = ReturnType.SINGLE) Mono> createLivenessWithVerifySessionWithVerifyImageWithResponse(BinaryData body, RequestOptions requestOptions) { - // Protocol API requires serialization of parts with content-disposition and data, as operation - // 'createLivenessWithVerifySessionWithVerifyImage' is 'multipart/form-data' + // Operation 'createLivenessWithVerifySessionWithVerifyImage' is of content-type 'multipart/form-data'. Protocol + // API is not usable and hence not generated. return this.serviceClient.createLivenessWithVerifySessionWithVerifyImageWithResponseAsync(body, requestOptions); } diff --git a/sdk/face/azure-ai-vision-face/src/main/java/com/azure/ai/vision/face/FaceSessionClient.java b/sdk/face/azure-ai-vision-face/src/main/java/com/azure/ai/vision/face/FaceSessionClient.java index 390429c84c08..dceef3d438cd 100644 --- a/sdk/face/azure-ai-vision-face/src/main/java/com/azure/ai/vision/face/FaceSessionClient.java +++ b/sdk/face/azure-ai-vision-face/src/main/java/com/azure/ai/vision/face/FaceSessionClient.java @@ -429,8 +429,8 @@ Response createLivenessWithVerifySessionWithResponse(BinaryData body @ServiceMethod(returns = ReturnType.SINGLE) Response createLivenessWithVerifySessionWithVerifyImageWithResponse(BinaryData body, RequestOptions requestOptions) { - // Protocol API requires serialization of parts with content-disposition and data, as operation - // 'createLivenessWithVerifySessionWithVerifyImage' is 'multipart/form-data' + // Operation 'createLivenessWithVerifySessionWithVerifyImage' is of content-type 'multipart/form-data'. Protocol + // API is not usable and hence not generated. return this.serviceClient.createLivenessWithVerifySessionWithVerifyImageWithResponse(body, requestOptions); } diff --git a/sdk/fluidrelay/azure-resourcemanager-fluidrelay/README.md b/sdk/fluidrelay/azure-resourcemanager-fluidrelay/README.md index 420e54c0e64a..8e62998840bd 100644 --- a/sdk/fluidrelay/azure-resourcemanager-fluidrelay/README.md +++ b/sdk/fluidrelay/azure-resourcemanager-fluidrelay/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-fluidrelay - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -108,4 +108,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Ffluidrelay%2Fazure-resourcemanager-fluidrelay%2FREADME.png) + diff --git a/sdk/fluidrelay/azure-resourcemanager-fluidrelay/pom.xml b/sdk/fluidrelay/azure-resourcemanager-fluidrelay/pom.xml index 76ac72e724df..75f493c43e4f 100644 --- a/sdk/fluidrelay/azure-resourcemanager-fluidrelay/pom.xml +++ b/sdk/fluidrelay/azure-resourcemanager-fluidrelay/pom.xml @@ -51,29 +51,29 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/formrecognizer/azure-ai-formrecognizer-perf/pom.xml b/sdk/formrecognizer/azure-ai-formrecognizer-perf/pom.xml index 23ac4ecbd171..95623e271e85 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.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/CHANGELOG.md b/sdk/formrecognizer/azure-ai-formrecognizer/CHANGELOG.md index 08ddc929bcf5..c0184a7f1c9c 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/CHANGELOG.md +++ b/sdk/formrecognizer/azure-ai-formrecognizer/CHANGELOG.md @@ -10,6 +10,18 @@ ### Other Changes +## 4.1.13 (2025-02-24) + +### Bugs Fixed +- Fixed a bug to set the code currency and symbol for CurrencyValue correctly. + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.54.0` to version `1.55.2`. +- Upgraded `azure-core-http-netty` from `1.15.6` to version `1.15.10`. + ## 4.1.12 (2024-11-08) ### Bugs Fixed diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/README.md b/sdk/formrecognizer/azure-ai-formrecognizer/README.md index 303df7f0ffec..a8f231e10c6a 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/README.md +++ b/sdk/formrecognizer/azure-ai-formrecognizer/README.md @@ -60,7 +60,7 @@ add the direct dependency to your project as follows. com.azure azure-ai-formrecognizer - 4.1.12 + 4.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -168,7 +168,7 @@ Authentication with AAD requires some initial setup: com.azure azure-identity - 1.14.2 + 1.15.3 ``` [//]: # ({x-version-update-end}) @@ -740,4 +740,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [quickstart_training]: https://learn.microsoft.com/azure/applied-ai-services/form-recognizer/quickstarts/get-started-sdks-rest-api?view=form-recog-3.0.0&pivots=programming-language-java [wiki_identity]: https://learn.microsoft.com/azure/developer/java/sdk/identity -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fformrecognizer%2Fazure-ai-formrecognizer%2FREADME.png) + diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/migration-guide.md b/sdk/formrecognizer/azure-ai-formrecognizer/migration-guide.md index ac4edd7affbe..a69fbb6e96c9 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/migration-guide.md +++ b/sdk/formrecognizer/azure-ai-formrecognizer/migration-guide.md @@ -581,4 +581,4 @@ For additional samples please take a look at the [Form Recognizer samples][READM [README]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/formrecognizer/azure-ai-formrecognizer/README.md [service_supported_models]: https://aka.ms/azsdk/formrecognizer/models -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fformrecognizer%2Fazure-ai-formrecognizer%2Fmigration-guide.png) + diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/pom.xml b/sdk/formrecognizer/azure-ai-formrecognizer/pom.xml index a13a66a1bbc2..9f718f5d4f93 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/pom.xml +++ b/sdk/formrecognizer/azure-ai-formrecognizer/pom.xml @@ -50,30 +50,30 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/src/samples/README.md b/sdk/formrecognizer/azure-ai-formrecognizer/src/samples/README.md index 7fd9d19da0c6..2bec52b54ece 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/src/samples/README.md +++ b/sdk/formrecognizer/azure-ai-formrecognizer/src/samples/README.md @@ -107,4 +107,4 @@ Guidelines][SDK_README_CONTRIBUTING] for more information. [build_classifier]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/formrecognizer/azure-ai-formrecognizer/src/samples/java/com/azure/ai/formrecognizer/administration/BuildDocumentClassifier.java [build_classifier_async]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/formrecognizer/azure-ai-formrecognizer/src/samples/java/com/azure/ai/formrecognizer/administration/BuildDocumentClassifierAsync.java -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fformrecognizer%2Fazure-ai-formrecognizer%2FREADME.png) + diff --git a/sdk/frontdoor/azure-resourcemanager-frontdoor/README.md b/sdk/frontdoor/azure-resourcemanager-frontdoor/README.md index 4bebdcabd543..a6b65a83ed01 100644 --- a/sdk/frontdoor/azure-resourcemanager-frontdoor/README.md +++ b/sdk/frontdoor/azure-resourcemanager-frontdoor/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-frontdoor - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -166,4 +166,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Ffrontdoor%2Fazure-resourcemanager-frontdoor%2FREADME.png) + diff --git a/sdk/frontdoor/azure-resourcemanager-frontdoor/pom.xml b/sdk/frontdoor/azure-resourcemanager-frontdoor/pom.xml index 4aae58e68888..7ae217689b38 100644 --- a/sdk/frontdoor/azure-resourcemanager-frontdoor/pom.xml +++ b/sdk/frontdoor/azure-resourcemanager-frontdoor/pom.xml @@ -51,35 +51,35 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test com.azure.resourcemanager azure-resourcemanager-storage - 2.46.0 + 2.48.0 test diff --git a/sdk/graphservices/azure-resourcemanager-graphservices/README.md b/sdk/graphservices/azure-resourcemanager-graphservices/README.md index ad85c6ef1f08..b0af5aa726ca 100644 --- a/sdk/graphservices/azure-resourcemanager-graphservices/README.md +++ b/sdk/graphservices/azure-resourcemanager-graphservices/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-graphservices - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fgraphservices%2Fazure-resourcemanager-graphservices%2FREADME.png) + diff --git a/sdk/graphservices/azure-resourcemanager-graphservices/pom.xml b/sdk/graphservices/azure-resourcemanager-graphservices/pom.xml index dbd4981e11db..bc202fc7f307 100644 --- a/sdk/graphservices/azure-resourcemanager-graphservices/pom.xml +++ b/sdk/graphservices/azure-resourcemanager-graphservices/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/hanaonazure/azure-resourcemanager-hanaonazure/README.md b/sdk/hanaonazure/azure-resourcemanager-hanaonazure/README.md index 862b336a91a7..4130ebb631e2 100644 --- a/sdk/hanaonazure/azure-resourcemanager-hanaonazure/README.md +++ b/sdk/hanaonazure/azure-resourcemanager-hanaonazure/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-hanaonazure - 1.0.0-beta.3 + 1.0.0-beta.4 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fhanaonazure%2Fazure-resourcemanager-hanaonazure%2FREADME.png) + diff --git a/sdk/hanaonazure/azure-resourcemanager-hanaonazure/pom.xml b/sdk/hanaonazure/azure-resourcemanager-hanaonazure/pom.xml index e9ce6f3f275d..e2a21e55a447 100644 --- a/sdk/hanaonazure/azure-resourcemanager-hanaonazure/pom.xml +++ b/sdk/hanaonazure/azure-resourcemanager-hanaonazure/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/hardwaresecuritymodules/azure-resourcemanager-hardwaresecuritymodules/README.md b/sdk/hardwaresecuritymodules/azure-resourcemanager-hardwaresecuritymodules/README.md index cc81d86a86bf..a1355e5d0764 100644 --- a/sdk/hardwaresecuritymodules/azure-resourcemanager-hardwaresecuritymodules/README.md +++ b/sdk/hardwaresecuritymodules/azure-resourcemanager-hardwaresecuritymodules/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-hardwaresecuritymodules - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fhardwaresecuritymodules%2Fazure-resourcemanager-hardwaresecuritymodules%2FREADME.png) + diff --git a/sdk/hardwaresecuritymodules/azure-resourcemanager-hardwaresecuritymodules/pom.xml b/sdk/hardwaresecuritymodules/azure-resourcemanager-hardwaresecuritymodules/pom.xml index ff465c0232d1..6ef367c2cc93 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.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/hdinsight/azure-resourcemanager-hdinsight-containers/README.md b/sdk/hdinsight/azure-resourcemanager-hdinsight-containers/README.md index da157e7c2bb0..e6781b7f47ae 100644 --- a/sdk/hdinsight/azure-resourcemanager-hdinsight-containers/README.md +++ b/sdk/hdinsight/azure-resourcemanager-hdinsight-containers/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-hdinsight-containers - 1.0.0-beta.3 + 1.0.0-beta.4 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fhdinsight%2Fazure-resourcemanager-hdinsight-containers%2FREADME.png) + diff --git a/sdk/hdinsight/azure-resourcemanager-hdinsight-containers/pom.xml b/sdk/hdinsight/azure-resourcemanager-hdinsight-containers/pom.xml index 6b36bafa1809..c0c036cbefda 100644 --- a/sdk/hdinsight/azure-resourcemanager-hdinsight-containers/pom.xml +++ b/sdk/hdinsight/azure-resourcemanager-hdinsight-containers/pom.xml @@ -51,28 +51,28 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/hdinsight/azure-resourcemanager-hdinsight/README.md b/sdk/hdinsight/azure-resourcemanager-hdinsight/README.md index bc2ea3146938..4f58d141f653 100644 --- a/sdk/hdinsight/azure-resourcemanager-hdinsight/README.md +++ b/sdk/hdinsight/azure-resourcemanager-hdinsight/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-hdinsight - 1.1.0-beta.2 + 1.1.0-beta.3 ``` [//]: # ({x-version-update-end}) @@ -172,4 +172,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fhdinsight%2Fazure-resourcemanager-hdinsight%2FREADME.png) + diff --git a/sdk/hdinsight/azure-resourcemanager-hdinsight/pom.xml b/sdk/hdinsight/azure-resourcemanager-hdinsight/pom.xml index b9f031293752..f96e9d389cfb 100644 --- a/sdk/hdinsight/azure-resourcemanager-hdinsight/pom.xml +++ b/sdk/hdinsight/azure-resourcemanager-hdinsight/pom.xml @@ -51,46 +51,46 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-storage - 2.46.0 + 2.48.0 test com.azure.resourcemanager azure-resourcemanager-network - 2.46.0 + 2.48.0 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/healthbot/azure-resourcemanager-healthbot/README.md b/sdk/healthbot/azure-resourcemanager-healthbot/README.md index 3f8f19a221b2..45d44c361cb5 100644 --- a/sdk/healthbot/azure-resourcemanager-healthbot/README.md +++ b/sdk/healthbot/azure-resourcemanager-healthbot/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-healthbot - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fhealthbot%2Fazure-resourcemanager-healthbot%2FREADME.png) + diff --git a/sdk/healthbot/azure-resourcemanager-healthbot/pom.xml b/sdk/healthbot/azure-resourcemanager-healthbot/pom.xml index 4a5561debee4..64dc48bce08c 100644 --- a/sdk/healthbot/azure-resourcemanager-healthbot/pom.xml +++ b/sdk/healthbot/azure-resourcemanager-healthbot/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/healthcareapis/azure-resourcemanager-healthcareapis/README.md b/sdk/healthcareapis/azure-resourcemanager-healthcareapis/README.md index 0499e2dfa41d..14903f5327c8 100644 --- a/sdk/healthcareapis/azure-resourcemanager-healthcareapis/README.md +++ b/sdk/healthcareapis/azure-resourcemanager-healthcareapis/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-healthcareapis - 1.2.0 + 1.3.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -109,4 +109,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fhealthcareapis%2Fazure-resourcemanager-healthcareapis%2FREADME.png) + diff --git a/sdk/healthcareapis/azure-resourcemanager-healthcareapis/pom.xml b/sdk/healthcareapis/azure-resourcemanager-healthcareapis/pom.xml index 30e95b303390..a43f699a1464 100644 --- a/sdk/healthcareapis/azure-resourcemanager-healthcareapis/pom.xml +++ b/sdk/healthcareapis/azure-resourcemanager-healthcareapis/pom.xml @@ -51,29 +51,29 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/healthdataaiservices/azure-health-deidentification/README.md b/sdk/healthdataaiservices/azure-health-deidentification/README.md index 45e9ab6eb2fa..1f97c97baa77 100644 --- a/sdk/healthdataaiservices/azure-health-deidentification/README.md +++ b/sdk/healthdataaiservices/azure-health-deidentification/README.md @@ -25,7 +25,7 @@ Various documentation is available to help you get started com.azure azure-health-deidentification - 1.0.0-beta.1 + 1.0.0-beta.2 ``` [//]: # ({x-version-update-end}) @@ -158,4 +158,4 @@ For details on contributing to this repository, see the [contributing guide](htt [azure_subscription]: https://azure.microsoft.com/free/ [azure_identity]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/identity/azure-identity -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fhealthdataaiservices%2Fazure-health-deidentification%2FREADME.png) + diff --git a/sdk/healthdataaiservices/azure-health-deidentification/pom.xml b/sdk/healthdataaiservices/azure-health-deidentification/pom.xml index 3640488fd752..2def65d374d3 100644 --- a/sdk/healthdataaiservices/azure-health-deidentification/pom.xml +++ b/sdk/healthdataaiservices/azure-health-deidentification/pom.xml @@ -52,33 +52,33 @@ Code generated by Microsoft (R) TypeSpec Code Generator. com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-xml - 1.1.0 + 1.2.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/healthdataaiservices/azure-resourcemanager-healthdataaiservices/README.md b/sdk/healthdataaiservices/azure-resourcemanager-healthdataaiservices/README.md index 3f169363efd9..8eed2568d34f 100644 --- a/sdk/healthdataaiservices/azure-resourcemanager-healthdataaiservices/README.md +++ b/sdk/healthdataaiservices/azure-resourcemanager-healthdataaiservices/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-healthdataaiservices - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fhealthdataaiservices%2Fazure-resourcemanager-healthdataaiservices%2FREADME.png) + diff --git a/sdk/healthdataaiservices/azure-resourcemanager-healthdataaiservices/pom.xml b/sdk/healthdataaiservices/azure-resourcemanager-healthdataaiservices/pom.xml index da9811fb728a..777d5944fdc8 100644 --- a/sdk/healthdataaiservices/azure-resourcemanager-healthdataaiservices/pom.xml +++ b/sdk/healthdataaiservices/azure-resourcemanager-healthdataaiservices/pom.xml @@ -52,29 +52,29 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-json - 1.3.0 + 1.5.0 diff --git a/sdk/healthdataaiservices/azure-resourcemanager-healthdataaiservices/src/main/java/com/azure/resourcemanager/healthdataaiservices/HealthDataAIServicesManager.java b/sdk/healthdataaiservices/azure-resourcemanager-healthdataaiservices/src/main/java/com/azure/resourcemanager/healthdataaiservices/HealthDataAIServicesManager.java index a9f1d13f7cff..e6f9ddf601f4 100644 --- a/sdk/healthdataaiservices/azure-resourcemanager-healthdataaiservices/src/main/java/com/azure/resourcemanager/healthdataaiservices/HealthDataAIServicesManager.java +++ b/sdk/healthdataaiservices/azure-resourcemanager-healthdataaiservices/src/main/java/com/azure/resourcemanager/healthdataaiservices/HealthDataAIServicesManager.java @@ -22,6 +22,7 @@ import com.azure.core.http.policy.UserAgentPolicy; import com.azure.core.management.profile.AzureProfile; import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.healthdataaiservices.fluent.HealthDataAIServicesClient; import com.azure.resourcemanager.healthdataaiservices.implementation.DeidServicesImpl; @@ -37,6 +38,7 @@ import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; @@ -104,6 +106,9 @@ public static Configurable configure() { */ public static final class Configurable { private static final ClientLogger LOGGER = new ClientLogger(Configurable.class); + private static final String SDK_VERSION = "version"; + private static final Map PROPERTIES + = CoreUtils.getProperties("azure-resourcemanager-healthdataaiservices.properties"); private HttpClient httpClient; private HttpLogOptions httpLogOptions; @@ -211,12 +216,14 @@ public HealthDataAIServicesManager authenticate(TokenCredential credential, Azur Objects.requireNonNull(credential, "'credential' cannot be null."); Objects.requireNonNull(profile, "'profile' cannot be null."); + String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); + StringBuilder userAgentBuilder = new StringBuilder(); userAgentBuilder.append("azsdk-java") .append("-") .append("com.azure.resourcemanager.healthdataaiservices") .append("/") - .append("1.0.0-beta.1"); + .append(clientVersion); if (!Configuration.getGlobalConfiguration().get("AZURE_TELEMETRY_DISABLED", false)) { userAgentBuilder.append(" (") .append(Configuration.getGlobalConfiguration().get("java.version")) diff --git a/sdk/healthdataaiservices/azure-resourcemanager-healthdataaiservices/src/main/java/com/azure/resourcemanager/healthdataaiservices/models/UserAssignedIdentity.java b/sdk/healthdataaiservices/azure-resourcemanager-healthdataaiservices/src/main/java/com/azure/resourcemanager/healthdataaiservices/models/UserAssignedIdentity.java index 4658af88d57c..7d6b5a040768 100644 --- a/sdk/healthdataaiservices/azure-resourcemanager-healthdataaiservices/src/main/java/com/azure/resourcemanager/healthdataaiservices/models/UserAssignedIdentity.java +++ b/sdk/healthdataaiservices/azure-resourcemanager-healthdataaiservices/src/main/java/com/azure/resourcemanager/healthdataaiservices/models/UserAssignedIdentity.java @@ -17,14 +17,14 @@ @Immutable public final class UserAssignedIdentity implements JsonSerializable { /* - * The principal ID of the assigned identity. + * The client ID of the assigned identity. */ - private String principalId; + private String clientId; /* - * The client ID of the assigned identity. + * The principal ID of the assigned identity. */ - private String clientId; + private String principalId; /** * Creates an instance of UserAssignedIdentity class. @@ -33,21 +33,21 @@ public UserAssignedIdentity() { } /** - * Get the principalId property: The principal ID of the assigned identity. + * Get the clientId property: The client ID of the assigned identity. * - * @return the principalId value. + * @return the clientId value. */ - public String principalId() { - return this.principalId; + public String clientId() { + return this.clientId; } /** - * Get the clientId property: The client ID of the assigned identity. + * Get the principalId property: The principal ID of the assigned identity. * - * @return the clientId value. + * @return the principalId value. */ - public String clientId() { - return this.clientId; + public String principalId() { + return this.principalId; } /** @@ -82,10 +82,10 @@ public static UserAssignedIdentity fromJson(JsonReader jsonReader) throws IOExce String fieldName = reader.getFieldName(); reader.nextToken(); - if ("principalId".equals(fieldName)) { - deserializedUserAssignedIdentity.principalId = reader.getString(); - } else if ("clientId".equals(fieldName)) { + if ("clientId".equals(fieldName)) { deserializedUserAssignedIdentity.clientId = reader.getString(); + } else if ("principalId".equals(fieldName)) { + deserializedUserAssignedIdentity.principalId = reader.getString(); } else { reader.skipChildren(); } diff --git a/sdk/healthdataaiservices/azure-resourcemanager-healthdataaiservices/src/main/resources/azure-resourcemanager-healthdataaiservices.properties b/sdk/healthdataaiservices/azure-resourcemanager-healthdataaiservices/src/main/resources/azure-resourcemanager-healthdataaiservices.properties new file mode 100644 index 000000000000..defbd48204e4 --- /dev/null +++ b/sdk/healthdataaiservices/azure-resourcemanager-healthdataaiservices/src/main/resources/azure-resourcemanager-healthdataaiservices.properties @@ -0,0 +1 @@ +version=${project.version} diff --git a/sdk/healthinsights/azure-health-insights-cancerprofiling/README.md b/sdk/healthinsights/azure-health-insights-cancerprofiling/README.md index 5b817d0b6cdb..88b3a0847645 100644 --- a/sdk/healthinsights/azure-health-insights-cancerprofiling/README.md +++ b/sdk/healthinsights/azure-health-insights-cancerprofiling/README.md @@ -24,7 +24,7 @@ For more information about creating the resource or how to get the location and com.azure azure-health-insights-cancerprofiling - 1.0.0-beta.1 + 1.0.0-beta.2 ``` @@ -217,4 +217,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][code_of_con [cancer_profiling_api_documentation]: https://learn.microsoft.com/rest/api/cognitiveservices/healthinsights/onco-phenotype [product_documentation]: https://learn.microsoft.com/azure/azure-health-insights/oncophenotype/ [samples_location]: https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/healthinsights/azure-health-insights-cancerprofiling/src/samples/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%healthinsights%2Fazure-health-insights-cancerprofiling%2FREADME.png) + diff --git a/sdk/healthinsights/azure-health-insights-cancerprofiling/pom.xml b/sdk/healthinsights/azure-health-insights-cancerprofiling/pom.xml index 552bd2e571d2..7589bd7265f4 100644 --- a/sdk/healthinsights/azure-health-insights-cancerprofiling/pom.xml +++ b/sdk/healthinsights/azure-health-insights-cancerprofiling/pom.xml @@ -56,28 +56,28 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/healthinsights/azure-health-insights-clinicalmatching/README.md b/sdk/healthinsights/azure-health-insights-clinicalmatching/README.md index d5670cbb1432..f16e901345b4 100644 --- a/sdk/healthinsights/azure-health-insights-clinicalmatching/README.md +++ b/sdk/healthinsights/azure-health-insights-clinicalmatching/README.md @@ -25,7 +25,7 @@ For more information about creating the resource or how to get the location and com.azure azure-health-insights-clinicalmatching - 1.0.0-beta.1 + 1.0.0-beta.2 ``` @@ -164,4 +164,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][code_of_con [clinical_matching_api_documentation]: https://learn.microsoft.com/rest/api/cognitiveservices/healthinsights/trial-matcher [product_documentation]: https://learn.microsoft.com/azure/azure-health-insights/trial-matcher/ [samples_location]: https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/healthinsights/azure-health-insights-clinicalmatching/src/samples -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%healthinsights%2Fazure-health-insights-clinicalmatching%2FREADME.png) + diff --git a/sdk/healthinsights/azure-health-insights-clinicalmatching/pom.xml b/sdk/healthinsights/azure-health-insights-clinicalmatching/pom.xml index 68b21c99dbf8..bc098f208352 100644 --- a/sdk/healthinsights/azure-health-insights-clinicalmatching/pom.xml +++ b/sdk/healthinsights/azure-health-insights-clinicalmatching/pom.xml @@ -56,28 +56,28 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/healthinsights/azure-health-insights-radiologyinsights/README.md b/sdk/healthinsights/azure-health-insights-radiologyinsights/README.md index 0a1d98e96a09..6e054ad8866d 100644 --- a/sdk/healthinsights/azure-health-insights-radiologyinsights/README.md +++ b/sdk/healthinsights/azure-health-insights-radiologyinsights/README.md @@ -25,7 +25,7 @@ For more information about creating the resource or how to get the location and com.azure azure-health-insights-radiologyinsights - 1.0.0 + 1.1.0-beta.1 ``` diff --git a/sdk/healthinsights/azure-health-insights-radiologyinsights/pom.xml b/sdk/healthinsights/azure-health-insights-radiologyinsights/pom.xml index 5d44c8fbd709..182fda74844c 100644 --- a/sdk/healthinsights/azure-health-insights-radiologyinsights/pom.xml +++ b/sdk/healthinsights/azure-health-insights-radiologyinsights/pom.xml @@ -54,28 +54,28 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/hybridcompute/azure-resourcemanager-hybridcompute/README.md b/sdk/hybridcompute/azure-resourcemanager-hybridcompute/README.md index cc5fd189003c..887b493271a2 100644 --- a/sdk/hybridcompute/azure-resourcemanager-hybridcompute/README.md +++ b/sdk/hybridcompute/azure-resourcemanager-hybridcompute/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-hybridcompute - 1.1.0-beta.1 + 1.1.0-beta.2 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fhybridcompute%2Fazure-resourcemanager-hybridcompute%2FREADME.png) + diff --git a/sdk/hybridcompute/azure-resourcemanager-hybridcompute/pom.xml b/sdk/hybridcompute/azure-resourcemanager-hybridcompute/pom.xml index 893eb82e9489..bc12f834301f 100644 --- a/sdk/hybridcompute/azure-resourcemanager-hybridcompute/pom.xml +++ b/sdk/hybridcompute/azure-resourcemanager-hybridcompute/pom.xml @@ -52,29 +52,29 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-json - 1.3.0 + 1.5.0 diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/CHANGELOG.md b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/CHANGELOG.md index d4fc45aa4b63..a49d74db2374 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/CHANGELOG.md +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.2.0-beta.1 (Unreleased) +## 1.2.0-beta.2 (Unreleased) ### Features Added @@ -10,6 +10,110 @@ ### Other Changes +## 1.2.0-beta.1 (2025-02-26) + +- Azure Resource Manager Hybrid Connectivity client library for Java. This package contains Microsoft Azure SDK for Hybrid Connectivity Management SDK. REST API for public clouds. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). + +### Breaking Changes + +#### `models.EndpointsList` was removed + +#### `models.OperationListResult` was removed + +#### `models.ServiceConfigurationList` was removed + +#### `HybridConnectivityManager` was modified + +* `fluent.HybridConnectivityManagementApi serviceClient()` -> `fluent.HybridConnectivityMgmtClient serviceClient()` + +### Features Added + +* `models.SolutionConfiguration` was added + +* `models.GenerateAwsTemplateRequest` was added + +* `models.PublicCloudConnector` was added + +* `models.SolutionSettings` was added + +* `models.Inventories` was added + +* `models.SolutionConfiguration$Definition` was added + +* `implementation.models.ServiceConfigurationList` was added + +* `models.OperationStatusResult` was added + +* `models.SolutionTypeSettingsProperties` was added + +* `models.SolutionTypeResource` was added + +* `models.AwsCloudProfile` was added + +* `implementation.models.SolutionConfigurationListResult` was added + +* `implementation.models.SolutionTypeResourceListResult` was added + +* `models.InventoryResource` was added + +* `implementation.models.EndpointsList` was added + +* `models.SolutionTypeSettings` was added + +* `models.SolutionConfigurationStatus` was added + +* `models.SolutionConfigurations` was added + +* `models.SolutionConfigurationProperties` was added + +* `models.ResourceProvisioningState` was added + +* `models.HostType` was added + +* `models.PublicCloudConnectors` was added + +* `models.PublicCloudConnectorProperties` was added + +* `models.SolutionConfiguration$Update` was added + +* `models.PublicCloudConnector$Definition` was added + +* `models.SolutionTypes` was added + +* `implementation.models.PublicCloudConnectorListResult` was added + +* `models.PublicCloudConnector$DefinitionStages` was added + +* `models.PublicCloudConnector$Update` was added + +* `models.SolutionTypeProperties` was added + +* `models.PostResponse` was added + +* `models.PublicCloudConnector$UpdateStages` was added + +* `models.SolutionConfiguration$DefinitionStages` was added + +* `implementation.models.OperationListResult` was added + +* `models.InventoryProperties` was added + +* `implementation.models.InventoryResourceListResult` was added + +* `models.CloudNativeType` was added + +* `models.GenerateAwsTemplates` was added + +* `models.SolutionConfiguration$UpdateStages` was added + +#### `HybridConnectivityManager` was modified + +* `publicCloudConnectors()` was added +* `inventories()` was added +* `solutionConfigurations()` was added +* `solutionTypes()` was added +* `generateAwsTemplates()` was added + ## 1.1.0 (2024-12-11) - Azure Resource Manager HybridConnectivity client library for Java. This package contains Microsoft Azure SDK for HybridConnectivity Management SDK. REST API for Hybrid Connectivity. Package tag package-2023-03. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/README.md b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/README.md index bf5349cd1f81..204ea34f920f 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/README.md +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/README.md @@ -1,8 +1,8 @@ -# Azure Resource Manager HybridConnectivity client library for Java +# Azure Resource Manager Hybrid Connectivity client library for Java -Azure Resource Manager HybridConnectivity client library for Java. +Azure Resource Manager Hybrid Connectivity client library for Java. -This package contains Microsoft Azure SDK for HybridConnectivity Management SDK. REST API for Hybrid Connectivity. Package tag package-2023-03. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). +This package contains Microsoft Azure SDK for Hybrid Connectivity Management SDK. REST API for public clouds. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). ## We'd love to hear your feedback @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-hybridconnectivity - 1.1.0 + 1.2.0-beta.2 ``` [//]: # ({x-version-update-end}) @@ -52,7 +52,7 @@ Azure subscription ID can be configured via `AZURE_SUBSCRIPTION_ID` environment Assuming the use of the `DefaultAzureCredential` credential class, the client can be authenticated using the following code: ```java -AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); +AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); @@ -60,7 +60,7 @@ HybridConnectivityManager manager = HybridConnectivityManager .authenticate(credential, profile); ``` -The sample code assumes global Azure. Please change `AzureEnvironment.AZURE` variable if otherwise. +The sample code assumes global Azure. Please change the `AzureCloud.AZURE_PUBLIC_CLOUD` variable if otherwise. See [Authentication][authenticate] for more options. @@ -100,5 +100,3 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [cg]: https://github.com/Azure/azure-sdk-for-java/blob/main/CONTRIBUTING.md [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ - -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fhybridconnectivity%2Fazure-resourcemanager-hybridconnectivity%2FREADME.png) diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/SAMPLE.md b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/SAMPLE.md index 93b4260fccf5..e11ba7bbfe98 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/SAMPLE.md +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/SAMPLE.md @@ -12,10 +12,29 @@ - [ListManagedProxyDetails](#endpoints_listmanagedproxydetails) - [Update](#endpoints_update) +## GenerateAwsTemplate + +- [Post](#generateawstemplate_post) + +## Inventory + +- [Get](#inventory_get) +- [ListBySolutionConfiguration](#inventory_listbysolutionconfiguration) + ## Operations - [List](#operations_list) +## PublicCloudConnectors + +- [CreateOrUpdate](#publiccloudconnectors_createorupdate) +- [Delete](#publiccloudconnectors_delete) +- [GetByResourceGroup](#publiccloudconnectors_getbyresourcegroup) +- [List](#publiccloudconnectors_list) +- [ListByResourceGroup](#publiccloudconnectors_listbyresourcegroup) +- [TestPermissions](#publiccloudconnectors_testpermissions) +- [Update](#publiccloudconnectors_update) + ## ServiceConfigurations - [CreateOrupdate](#serviceconfigurations_createorupdate) @@ -23,6 +42,21 @@ - [Get](#serviceconfigurations_get) - [ListByEndpointResource](#serviceconfigurations_listbyendpointresource) - [Update](#serviceconfigurations_update) + +## SolutionConfigurations + +- [CreateOrUpdate](#solutionconfigurations_createorupdate) +- [Delete](#solutionconfigurations_delete) +- [Get](#solutionconfigurations_get) +- [List](#solutionconfigurations_list) +- [SyncNow](#solutionconfigurations_syncnow) +- [Update](#solutionconfigurations_update) + +## SolutionTypes + +- [GetByResourceGroup](#solutiontypes_getbyresourcegroup) +- [List](#solutiontypes_list) +- [ListByResourceGroup](#solutiontypes_listbyresourcegroup) ### Endpoints_CreateOrUpdate ```java @@ -34,9 +68,7 @@ import com.azure.resourcemanager.hybridconnectivity.models.Type; */ public final class EndpointsCreateOrUpdateSamples { /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * EndpointsPutCustom.json + * x-ms-original-file: 2024-12-01/EndpointsPutCustom.json */ /** * Sample code: HybridConnectivityEndpointsPutCustom. @@ -56,9 +88,7 @@ public final class EndpointsCreateOrUpdateSamples { } /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * EndpointsPutDefault.json + * x-ms-original-file: 2024-12-01/EndpointsPutDefault.json */ /** * Sample code: HybridConnectivityEndpointsPutDefault. @@ -85,9 +115,7 @@ public final class EndpointsCreateOrUpdateSamples { */ public final class EndpointsDeleteSamples { /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * EndpointsDeleteDefault.json + * x-ms-original-file: 2024-12-01/EndpointsDeleteDefault.json */ /** * Sample code: HybridConnectivityEndpointsDeleteDefault. @@ -112,9 +140,7 @@ public final class EndpointsDeleteSamples { */ public final class EndpointsGetSamples { /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * EndpointsGetDefault.json + * x-ms-original-file: 2024-12-01/EndpointsGetDefault.json */ /** * Sample code: HybridConnectivityEndpointsGetDefault. @@ -130,9 +156,7 @@ public final class EndpointsGetSamples { } /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * EndpointsGetCustom.json + * x-ms-original-file: 2024-12-01/EndpointsGetCustom.json */ /** * Sample code: HybridConnectivityEndpointsGetCustom. @@ -157,9 +181,7 @@ public final class EndpointsGetSamples { */ public final class EndpointsListSamples { /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * EndpointsList.json + * x-ms-original-file: 2024-12-01/EndpointsList.json */ /** * Sample code: HybridConnectivityEndpointsGet. @@ -187,9 +209,7 @@ import com.azure.resourcemanager.hybridconnectivity.models.ServiceName; */ public final class EndpointsListCredentialsSamples { /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * EndpointsPostListCredentials.json + * x-ms-original-file: 2024-12-01/EndpointsPostListCredentials.json */ /** * Sample code: HybridConnectivityEndpointsPostListCredentials. @@ -216,9 +236,7 @@ public final class EndpointsListCredentialsSamples { */ public final class EndpointsListIngressGatewayCredentialsSamples { /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * EndpointsPostListIngressGatewayCredentials.json + * x-ms-original-file: 2024-12-01/EndpointsPostListIngressGatewayCredentials.json */ /** * Sample code: HybridConnectivityEndpointsPostListIngressGatewayCredentials. @@ -246,9 +264,7 @@ import com.azure.resourcemanager.hybridconnectivity.models.ServiceName; */ public final class EndpointsListManagedProxyDetailsSamples { /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * EndpointsPostListManagedProxyDetails.json + * x-ms-original-file: 2024-12-01/EndpointsPostListManagedProxyDetails.json */ /** * Sample code: HybridConnectivityEndpointsPostListManagedProxyDetails. @@ -281,9 +297,7 @@ import com.azure.resourcemanager.hybridconnectivity.models.Type; */ public final class EndpointsUpdateSamples { /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * EndpointsPatchDefault.json + * x-ms-original-file: 2024-12-01/EndpointsPatchDefault.json */ /** * Sample code: HybridConnectivityEndpointsPatchDefault. @@ -302,6 +316,96 @@ public final class EndpointsUpdateSamples { } ``` +### GenerateAwsTemplate_Post + +```java +import com.azure.resourcemanager.hybridconnectivity.models.GenerateAwsTemplateRequest; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionSettings; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionTypeSettings; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * Samples for GenerateAwsTemplate Post. + */ +public final class GenerateAwsTemplatePostSamples { + /* + * x-ms-original-file: 2024-12-01/GenerateAwsTemplate_Post.json + */ + /** + * Sample code: GenerateAwsTemplate_Post. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void + generateAwsTemplatePost(com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.generateAwsTemplates() + .postWithResponse( + new GenerateAwsTemplateRequest().withConnectorId("pnxcfjidglabnwxit") + .withSolutionTypes(Arrays.asList(new SolutionTypeSettings().withSolutionType("hjyownzpfxwiufmd") + .withSolutionSettings(new SolutionSettings().withAdditionalProperties(mapOf())))), + com.azure.core.util.Context.NONE); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} +``` + +### Inventory_Get + +```java +/** + * Samples for Inventory Get. + */ +public final class InventoryGetSamples { + /* + * x-ms-original-file: 2024-12-01/Inventory_Get.json + */ + /** + * Sample code: Inventory_Get. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void inventoryGet(com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.inventories() + .getWithResponse("ymuj", "zarfsraogroxlaqjjnwixtn", "xofprmcboosrbd", com.azure.core.util.Context.NONE); + } +} +``` + +### Inventory_ListBySolutionConfiguration + +```java +/** + * Samples for Inventory ListBySolutionConfiguration. + */ +public final class InventoryListBySolutionConfigurationSamples { + /* + * x-ms-original-file: 2024-12-01/Inventory_ListBySolutionConfiguration.json + */ + /** + * Sample code: Inventory_ListBySolutionConfiguration. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void inventoryListBySolutionConfiguration( + com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.inventories().listBySolutionConfiguration("ymuj", "wsxt", com.azure.core.util.Context.NONE); + } +} +``` + ### Operations_List ```java @@ -310,9 +414,7 @@ public final class EndpointsUpdateSamples { */ public final class OperationsListSamples { /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * OperationsList.json + * x-ms-original-file: 2024-12-01/OperationsList.json */ /** * Sample code: HybridConnectivityOperationsList. @@ -326,6 +428,221 @@ public final class OperationsListSamples { } ``` +### PublicCloudConnectors_CreateOrUpdate + +```java +import com.azure.resourcemanager.hybridconnectivity.models.AwsCloudProfile; +import com.azure.resourcemanager.hybridconnectivity.models.HostType; +import com.azure.resourcemanager.hybridconnectivity.models.PublicCloudConnectorProperties; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * Samples for PublicCloudConnectors CreateOrUpdate. + */ +public final class PublicCloudConnectorsCreateOrUpdateSamples { + /* + * x-ms-original-file: 2024-12-01/PublicCloudConnectors_CreateOrUpdate.json + */ + /** + * Sample code: PublicCloudConnectors_CreateOrUpdate. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void publicCloudConnectorsCreateOrUpdate( + com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.publicCloudConnectors() + .define("advjwoakdusalamomg") + .withRegion("jpiglusfxynfcewcjwvvnn") + .withExistingResourceGroup("rgpublicCloud") + .withTags(mapOf()) + .withProperties(new PublicCloudConnectorProperties() + .withAwsCloudProfile(new AwsCloudProfile().withAccountId("snbnuxckevyqpm") + .withExcludedAccounts(Arrays.asList("rwgqpukglvbqmogqcliqolucp")) + .withIsOrganizationalAccount(true)) + .withHostType(HostType.AWS)) + .create(); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} +``` + +### PublicCloudConnectors_Delete + +```java +/** + * Samples for PublicCloudConnectors Delete. + */ +public final class PublicCloudConnectorsDeleteSamples { + /* + * x-ms-original-file: 2024-12-01/PublicCloudConnectors_Delete.json + */ + /** + * Sample code: PublicCloudConnectors_Delete. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void + publicCloudConnectorsDelete(com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.publicCloudConnectors() + .deleteByResourceGroupWithResponse("rgpublicCloud", "skcfyjvflkhibdywjay", + com.azure.core.util.Context.NONE); + } +} +``` + +### PublicCloudConnectors_GetByResourceGroup + +```java +/** + * Samples for PublicCloudConnectors GetByResourceGroup. + */ +public final class PublicCloudConnectorsGetByResourceGroupSamples { + /* + * x-ms-original-file: 2024-12-01/PublicCloudConnectors_Get.json + */ + /** + * Sample code: PublicCloudConnectors_Get. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void + publicCloudConnectorsGet(com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.publicCloudConnectors() + .getByResourceGroupWithResponse("rgpublicCloud", "rzygvnpsnrdylwzdbsscjazvamyxmh", + com.azure.core.util.Context.NONE); + } +} +``` + +### PublicCloudConnectors_List + +```java +/** + * Samples for PublicCloudConnectors List. + */ +public final class PublicCloudConnectorsListSamples { + /* + * x-ms-original-file: 2024-12-01/PublicCloudConnectors_ListBySubscription.json + */ + /** + * Sample code: PublicCloudConnectors_ListBySubscription. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void publicCloudConnectorsListBySubscription( + com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.publicCloudConnectors().list(com.azure.core.util.Context.NONE); + } +} +``` + +### PublicCloudConnectors_ListByResourceGroup + +```java +/** + * Samples for PublicCloudConnectors ListByResourceGroup. + */ +public final class PublicCloudConnectorsListByResourceGroupSamples { + /* + * x-ms-original-file: 2024-12-01/PublicCloudConnectors_ListByResourceGroup.json + */ + /** + * Sample code: PublicCloudConnectors_ListByResourceGroup. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void publicCloudConnectorsListByResourceGroup( + com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.publicCloudConnectors().listByResourceGroup("rgpublicCloud", com.azure.core.util.Context.NONE); + } +} +``` + +### PublicCloudConnectors_TestPermissions + +```java +/** + * Samples for PublicCloudConnectors TestPermissions. + */ +public final class PublicCloudConnectorsTestPermissionsSamples { + /* + * x-ms-original-file: 2024-12-01/PublicCloudConnectors_TestPermissions.json + */ + /** + * Sample code: PublicCloudConnectors_TestPermissions. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void publicCloudConnectorsTestPermissions( + com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.publicCloudConnectors() + .testPermissions("rgpublicCloud", "rzygvnpsnrdylwzdbsscjazvamyxmh", com.azure.core.util.Context.NONE); + } +} +``` + +### PublicCloudConnectors_Update + +```java +import com.azure.resourcemanager.hybridconnectivity.models.AwsCloudProfile; +import com.azure.resourcemanager.hybridconnectivity.models.PublicCloudConnector; +import com.azure.resourcemanager.hybridconnectivity.models.PublicCloudConnectorProperties; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * Samples for PublicCloudConnectors Update. + */ +public final class PublicCloudConnectorsUpdateSamples { + /* + * x-ms-original-file: 2024-12-01/PublicCloudConnectors_Update.json + */ + /** + * Sample code: PublicCloudConnectors_Update. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void + publicCloudConnectorsUpdate(com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + PublicCloudConnector resource = manager.publicCloudConnectors() + .getByResourceGroupWithResponse("rgpublicCloud", "svtirlbyqpepbzyessjenlueeznhg", + com.azure.core.util.Context.NONE) + .getValue(); + resource.update() + .withTags(mapOf()) + .withProperties(new PublicCloudConnectorProperties() + .withAwsCloudProfile(new AwsCloudProfile().withExcludedAccounts(Arrays.asList("zrbtd")))) + .apply(); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} +``` + ### ServiceConfigurations_CreateOrupdate ```java @@ -336,9 +653,7 @@ import com.azure.resourcemanager.hybridconnectivity.models.ServiceName; */ public final class ServiceConfigurationsCreateOrupdateSamples { /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * ServiceConfigurationsPutWAC.json + * x-ms-original-file: 2024-12-01/ServiceConfigurationsPutWAC.json */ /** * Sample code: ServiceConfigurationsPutWAC. @@ -358,9 +673,7 @@ public final class ServiceConfigurationsCreateOrupdateSamples { } /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * ServiceConfigurationsPutSSH.json + * x-ms-original-file: 2024-12-01/ServiceConfigurationsPutSSH.json */ /** * Sample code: ServiceConfigurationsPutSSH. @@ -389,9 +702,7 @@ public final class ServiceConfigurationsCreateOrupdateSamples { */ public final class ServiceConfigurationsDeleteSamples { /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * ServiceConfigurationsDeleteSSH.json + * x-ms-original-file: 2024-12-01/ServiceConfigurationsDeleteSSH.json */ /** * Sample code: ServiceConfigurationsDeleteSSH. @@ -416,9 +727,7 @@ public final class ServiceConfigurationsDeleteSamples { */ public final class ServiceConfigurationsGetSamples { /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * ServiceConfigurationsGetWAC.json + * x-ms-original-file: 2024-12-01/ServiceConfigurationsGetWAC.json */ /** * Sample code: HybridConnectivityEndpointsServiceconfigurationsGetWAC. @@ -434,9 +743,7 @@ public final class ServiceConfigurationsGetSamples { } /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * ServiceConfigurationsGetSSH.json + * x-ms-original-file: 2024-12-01/ServiceConfigurationsGetSSH.json */ /** * Sample code: HybridConnectivityEndpointsServiceconfigurationsGetSSH. @@ -461,9 +768,7 @@ public final class ServiceConfigurationsGetSamples { */ public final class ServiceConfigurationsListByEndpointResourceSamples { /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * ServiceConfigurationsList.json + * x-ms-original-file: 2024-12-01/ServiceConfigurationsList.json */ /** * Sample code: GetClustersExample. @@ -490,9 +795,7 @@ import com.azure.resourcemanager.hybridconnectivity.models.ServiceConfigurationR */ public final class ServiceConfigurationsUpdateSamples { /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * ServiceConfigurationsPatchSSH.json + * x-ms-original-file: 2024-12-01/ServiceConfigurationsPatchSSH.json */ /** * Sample code: ServiceConfigurationsPatchSSH. @@ -511,3 +814,249 @@ public final class ServiceConfigurationsUpdateSamples { } ``` +### SolutionConfigurations_CreateOrUpdate + +```java +import com.azure.resourcemanager.hybridconnectivity.models.SolutionConfigurationProperties; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionSettings; +import java.util.HashMap; +import java.util.Map; + +/** + * Samples for SolutionConfigurations CreateOrUpdate. + */ +public final class SolutionConfigurationsCreateOrUpdateSamples { + /* + * x-ms-original-file: 2024-12-01/SolutionConfigurations_CreateOrUpdate.json + */ + /** + * Sample code: SolutionConfigurations_CreateOrUpdate. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void solutionConfigurationsCreateOrUpdate( + com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.solutionConfigurations() + .define("keebwujt") + .withExistingResourceUri("ymuj") + .withProperties(new SolutionConfigurationProperties().withSolutionType("nmtqllkyohwtsthxaimsye") + .withSolutionSettings(new SolutionSettings().withAdditionalProperties(mapOf()))) + .create(); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} +``` + +### SolutionConfigurations_Delete + +```java +/** + * Samples for SolutionConfigurations Delete. + */ +public final class SolutionConfigurationsDeleteSamples { + /* + * x-ms-original-file: 2024-12-01/SolutionConfigurations_Delete.json + */ + /** + * Sample code: SolutionConfigurations_Delete. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void + solutionConfigurationsDelete(com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.solutionConfigurations() + .deleteByResourceGroupWithResponse("ymuj", "stu", com.azure.core.util.Context.NONE); + } +} +``` + +### SolutionConfigurations_Get + +```java +/** + * Samples for SolutionConfigurations Get. + */ +public final class SolutionConfigurationsGetSamples { + /* + * x-ms-original-file: 2024-12-01/SolutionConfigurations_Get.json + */ + /** + * Sample code: SolutionConfigurations_Get. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void + solutionConfigurationsGet(com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.solutionConfigurations().getWithResponse("ymuj", "tks", com.azure.core.util.Context.NONE); + } +} +``` + +### SolutionConfigurations_List + +```java +/** + * Samples for SolutionConfigurations List. + */ +public final class SolutionConfigurationsListSamples { + /* + * x-ms-original-file: 2024-12-01/SolutionConfigurations_List.json + */ + /** + * Sample code: SolutionConfigurations_List. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void + solutionConfigurationsList(com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.solutionConfigurations().list("ymuj", com.azure.core.util.Context.NONE); + } +} +``` + +### SolutionConfigurations_SyncNow + +```java +/** + * Samples for SolutionConfigurations SyncNow. + */ +public final class SolutionConfigurationsSyncNowSamples { + /* + * x-ms-original-file: 2024-12-01/SolutionConfigurations_SyncNow.json + */ + /** + * Sample code: SolutionConfigurations_SyncNow. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void + solutionConfigurationsSyncNow(com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.solutionConfigurations().syncNow("ymuj", "tks", com.azure.core.util.Context.NONE); + } +} +``` + +### SolutionConfigurations_Update + +```java +import com.azure.resourcemanager.hybridconnectivity.models.SolutionConfiguration; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionConfigurationProperties; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionSettings; +import java.util.HashMap; +import java.util.Map; + +/** + * Samples for SolutionConfigurations Update. + */ +public final class SolutionConfigurationsUpdateSamples { + /* + * x-ms-original-file: 2024-12-01/SolutionConfigurations_Update.json + */ + /** + * Sample code: SolutionConfigurations_Update. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void + solutionConfigurationsUpdate(com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + SolutionConfiguration resource = manager.solutionConfigurations() + .getWithResponse("ymuj", "dxt", com.azure.core.util.Context.NONE) + .getValue(); + resource.update() + .withProperties(new SolutionConfigurationProperties().withSolutionType("myzljlstvmgkp") + .withSolutionSettings(new SolutionSettings().withAdditionalProperties(mapOf()))) + .apply(); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} +``` + +### SolutionTypes_GetByResourceGroup + +```java +/** + * Samples for SolutionTypes GetByResourceGroup. + */ +public final class SolutionTypesGetByResourceGroupSamples { + /* + * x-ms-original-file: 2024-12-01/SolutionTypes_Get.json + */ + /** + * Sample code: SolutionTypes_Get. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void + solutionTypesGet(com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.solutionTypes() + .getByResourceGroupWithResponse("rgpublicCloud", "lulzqllpu", com.azure.core.util.Context.NONE); + } +} +``` + +### SolutionTypes_List + +```java +/** + * Samples for SolutionTypes List. + */ +public final class SolutionTypesListSamples { + /* + * x-ms-original-file: 2024-12-01/SolutionTypes_ListBySubscription.json + */ + /** + * Sample code: SolutionTypes_ListBySubscription. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void solutionTypesListBySubscription( + com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.solutionTypes().list(com.azure.core.util.Context.NONE); + } +} +``` + +### SolutionTypes_ListByResourceGroup + +```java +/** + * Samples for SolutionTypes ListByResourceGroup. + */ +public final class SolutionTypesListByResourceGroupSamples { + /* + * x-ms-original-file: 2024-12-01/SolutionTypes_ListByResourceGroup.json + */ + /** + * Sample code: SolutionTypes_ListByResourceGroup. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void solutionTypesListByResourceGroup( + com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.solutionTypes().listByResourceGroup("rgpublicCloud", com.azure.core.util.Context.NONE); + } +} +``` + diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/pom.xml b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/pom.xml index 583638eb69e1..ef918478ccdd 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/pom.xml +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/pom.xml @@ -1,7 +1,7 @@ 4.0.0 @@ -14,11 +14,11 @@ com.azure.resourcemanager azure-resourcemanager-hybridconnectivity - 1.2.0-beta.1 + 1.2.0-beta.2 jar - Microsoft Azure SDK for HybridConnectivity Management - This package contains Microsoft Azure SDK for HybridConnectivity Management SDK. For documentation on how to use this package, please see https://aka.ms/azsdk/java/mgmt. REST API for Hybrid Connectivity. Package tag package-2023-03. + Microsoft Azure SDK for Hybrid Connectivity Management + This package contains Microsoft Azure SDK for Hybrid Connectivity Management SDK. For documentation on how to use this package, please see https://aka.ms/azsdk/java/mgmt. REST API for public clouds. https://github.com/Azure/azure-sdk-for-java @@ -45,29 +45,30 @@ UTF-8 0 0 + true false com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/HybridConnectivityManager.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/HybridConnectivityManager.java index b4c53ea39683..d2381b4adbf6 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/HybridConnectivityManager.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/HybridConnectivityManager.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity; @@ -22,25 +22,37 @@ import com.azure.core.http.policy.UserAgentPolicy; import com.azure.core.management.profile.AzureProfile; import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; -import com.azure.resourcemanager.hybridconnectivity.fluent.HybridConnectivityManagementApi; +import com.azure.resourcemanager.hybridconnectivity.fluent.HybridConnectivityMgmtClient; import com.azure.resourcemanager.hybridconnectivity.implementation.EndpointsImpl; -import com.azure.resourcemanager.hybridconnectivity.implementation.HybridConnectivityManagementApiBuilder; +import com.azure.resourcemanager.hybridconnectivity.implementation.GenerateAwsTemplatesImpl; +import com.azure.resourcemanager.hybridconnectivity.implementation.HybridConnectivityMgmtClientBuilder; +import com.azure.resourcemanager.hybridconnectivity.implementation.InventoriesImpl; import com.azure.resourcemanager.hybridconnectivity.implementation.OperationsImpl; +import com.azure.resourcemanager.hybridconnectivity.implementation.PublicCloudConnectorsImpl; import com.azure.resourcemanager.hybridconnectivity.implementation.ServiceConfigurationsImpl; +import com.azure.resourcemanager.hybridconnectivity.implementation.SolutionConfigurationsImpl; +import com.azure.resourcemanager.hybridconnectivity.implementation.SolutionTypesImpl; import com.azure.resourcemanager.hybridconnectivity.models.Endpoints; +import com.azure.resourcemanager.hybridconnectivity.models.GenerateAwsTemplates; +import com.azure.resourcemanager.hybridconnectivity.models.Inventories; import com.azure.resourcemanager.hybridconnectivity.models.Operations; +import com.azure.resourcemanager.hybridconnectivity.models.PublicCloudConnectors; import com.azure.resourcemanager.hybridconnectivity.models.ServiceConfigurations; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionConfigurations; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionTypes; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; /** * Entry point to HybridConnectivityManager. - * REST API for Hybrid Connectivity. + * REST API for public clouds. */ public final class HybridConnectivityManager { private Operations operations; @@ -49,23 +61,34 @@ public final class HybridConnectivityManager { private ServiceConfigurations serviceConfigurations; - private final HybridConnectivityManagementApi clientObject; + private GenerateAwsTemplates generateAwsTemplates; + + private PublicCloudConnectors publicCloudConnectors; + + private SolutionConfigurations solutionConfigurations; + + private Inventories inventories; + + private SolutionTypes solutionTypes; + + private final HybridConnectivityMgmtClient clientObject; private HybridConnectivityManager(HttpPipeline httpPipeline, AzureProfile profile, Duration defaultPollInterval) { Objects.requireNonNull(httpPipeline, "'httpPipeline' cannot be null."); Objects.requireNonNull(profile, "'profile' cannot be null."); - this.clientObject = new HybridConnectivityManagementApiBuilder().pipeline(httpPipeline) + this.clientObject = new HybridConnectivityMgmtClientBuilder().pipeline(httpPipeline) .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) + .subscriptionId(profile.getSubscriptionId()) .defaultPollInterval(defaultPollInterval) .buildClient(); } /** - * Creates an instance of HybridConnectivity service API entry point. + * Creates an instance of Hybrid Connectivity service API entry point. * * @param credential the credential to use. * @param profile the Azure profile for client. - * @return the HybridConnectivity service API instance. + * @return the Hybrid Connectivity service API instance. */ public static HybridConnectivityManager authenticate(TokenCredential credential, AzureProfile profile) { Objects.requireNonNull(credential, "'credential' cannot be null."); @@ -74,11 +97,11 @@ public static HybridConnectivityManager authenticate(TokenCredential credential, } /** - * Creates an instance of HybridConnectivity service API entry point. + * Creates an instance of Hybrid Connectivity service API entry point. * * @param httpPipeline the {@link HttpPipeline} configured with Azure authentication credential. * @param profile the Azure profile for client. - * @return the HybridConnectivity service API instance. + * @return the Hybrid Connectivity service API instance. */ public static HybridConnectivityManager authenticate(HttpPipeline httpPipeline, AzureProfile profile) { Objects.requireNonNull(httpPipeline, "'httpPipeline' cannot be null."); @@ -100,6 +123,9 @@ public static Configurable configure() { */ public static final class Configurable { private static final ClientLogger LOGGER = new ClientLogger(Configurable.class); + private static final String SDK_VERSION = "version"; + private static final Map PROPERTIES + = CoreUtils.getProperties("azure-resourcemanager-hybridconnectivity.properties"); private HttpClient httpClient; private HttpLogOptions httpLogOptions; @@ -197,22 +223,24 @@ public Configurable withDefaultPollInterval(Duration defaultPollInterval) { } /** - * Creates an instance of HybridConnectivity service API entry point. + * Creates an instance of Hybrid Connectivity service API entry point. * * @param credential the credential to use. * @param profile the Azure profile for client. - * @return the HybridConnectivity service API instance. + * @return the Hybrid Connectivity service API instance. */ public HybridConnectivityManager authenticate(TokenCredential credential, AzureProfile profile) { Objects.requireNonNull(credential, "'credential' cannot be null."); Objects.requireNonNull(profile, "'profile' cannot be null."); + String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); + StringBuilder userAgentBuilder = new StringBuilder(); userAgentBuilder.append("azsdk-java") .append("-") .append("com.azure.resourcemanager.hybridconnectivity") .append("/") - .append("1.1.0"); + .append(clientVersion); if (!Configuration.getGlobalConfiguration().get("AZURE_TELEMETRY_DISABLED", false)) { userAgentBuilder.append(" (") .append(Configuration.getGlobalConfiguration().get("java.version")) @@ -295,12 +323,73 @@ public ServiceConfigurations serviceConfigurations() { } /** - * Gets wrapped service client HybridConnectivityManagementApi providing direct access to the underlying - * auto-generated API implementation, based on Azure REST API. + * Gets the resource collection API of GenerateAwsTemplates. + * + * @return Resource collection API of GenerateAwsTemplates. + */ + public GenerateAwsTemplates generateAwsTemplates() { + if (this.generateAwsTemplates == null) { + this.generateAwsTemplates = new GenerateAwsTemplatesImpl(clientObject.getGenerateAwsTemplates(), this); + } + return generateAwsTemplates; + } + + /** + * Gets the resource collection API of PublicCloudConnectors. It manages PublicCloudConnector. + * + * @return Resource collection API of PublicCloudConnectors. + */ + public PublicCloudConnectors publicCloudConnectors() { + if (this.publicCloudConnectors == null) { + this.publicCloudConnectors = new PublicCloudConnectorsImpl(clientObject.getPublicCloudConnectors(), this); + } + return publicCloudConnectors; + } + + /** + * Gets the resource collection API of SolutionConfigurations. It manages SolutionConfiguration. + * + * @return Resource collection API of SolutionConfigurations. + */ + public SolutionConfigurations solutionConfigurations() { + if (this.solutionConfigurations == null) { + this.solutionConfigurations + = new SolutionConfigurationsImpl(clientObject.getSolutionConfigurations(), this); + } + return solutionConfigurations; + } + + /** + * Gets the resource collection API of Inventories. + * + * @return Resource collection API of Inventories. + */ + public Inventories inventories() { + if (this.inventories == null) { + this.inventories = new InventoriesImpl(clientObject.getInventories(), this); + } + return inventories; + } + + /** + * Gets the resource collection API of SolutionTypes. + * + * @return Resource collection API of SolutionTypes. + */ + public SolutionTypes solutionTypes() { + if (this.solutionTypes == null) { + this.solutionTypes = new SolutionTypesImpl(clientObject.getSolutionTypes(), this); + } + return solutionTypes; + } + + /** + * Gets wrapped service client HybridConnectivityMgmtClient providing direct access to the underlying auto-generated + * API implementation, based on Azure REST API. * - * @return Wrapped service client HybridConnectivityManagementApi. + * @return Wrapped service client HybridConnectivityMgmtClient. */ - public HybridConnectivityManagementApi serviceClient() { + public HybridConnectivityMgmtClient serviceClient() { return this.clientObject; } } diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/EndpointsClient.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/EndpointsClient.java index 6b5984063fe4..07c88c47b28c 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/EndpointsClient.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/EndpointsClient.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.fluent; @@ -21,35 +21,10 @@ * An instance of this class provides access to all the operations defined in EndpointsClient. */ public interface EndpointsClient { - /** - * List of endpoints to the target resource. - * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the list of endpoints as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable list(String resourceUri); - - /** - * List of endpoints to the target resource. - * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the list of endpoints as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable list(String resourceUri, Context context); - /** * Gets the endpoint to the resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -63,7 +38,7 @@ public interface EndpointsClient { /** * Gets the endpoint to the resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. @@ -76,7 +51,7 @@ public interface EndpointsClient { /** * Create or update the endpoint to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param endpointResource Endpoint details. * @param context The context to associate with this operation. @@ -92,7 +67,7 @@ Response createOrUpdateWithResponse(String resourceUri, S /** * Create or update the endpoint to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param endpointResource Endpoint details. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -107,7 +82,7 @@ EndpointResourceInner createOrUpdate(String resourceUri, String endpointName, /** * Update the endpoint to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param endpointResource Endpoint details. * @param context The context to associate with this operation. @@ -123,7 +98,7 @@ Response updateWithResponse(String resourceUri, String en /** * Update the endpoint to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param endpointResource Endpoint details. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -137,7 +112,7 @@ Response updateWithResponse(String resourceUri, String en /** * Deletes the endpoint access to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -151,7 +126,7 @@ Response updateWithResponse(String resourceUri, String en /** * Deletes the endpoint access to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. @@ -160,10 +135,35 @@ Response updateWithResponse(String resourceUri, String en @ServiceMethod(returns = ReturnType.SINGLE) void delete(String resourceUri, String endpointName); + /** + * List of endpoints to the target resource. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the list of endpoints as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(String resourceUri); + + /** + * List of endpoints to the target resource. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the list of endpoints as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(String resourceUri, Context context); + /** * Gets the endpoint access credentials to the resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param expiresin The is how long the endpoint access token is valid (in seconds). * @param listCredentialsRequest Object of type ListCredentialsRequest. @@ -180,7 +180,7 @@ Response listCredentialsWithResponse(String resourc /** * Gets the endpoint access credentials to the resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. @@ -193,7 +193,7 @@ Response listCredentialsWithResponse(String resourc /** * Gets the ingress gateway endpoint credentials. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param expiresin The is how long the endpoint access token is valid (in seconds). * @param listIngressGatewayCredentialsRequest Object of type ListIngressGatewayCredentialsRequest. @@ -211,7 +211,7 @@ Response listIngressGatewayCredentialsWithResponse( /** * Gets the ingress gateway endpoint credentials. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. @@ -224,7 +224,7 @@ Response listIngressGatewayCredentialsWithResponse( /** * Fetches the managed proxy details. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param managedProxyRequest Object of type ManagedProxyRequest. * @param context The context to associate with this operation. @@ -240,7 +240,7 @@ Response listManagedProxyDetailsWithResponse(String r /** * Fetches the managed proxy details. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param managedProxyRequest Object of type ManagedProxyRequest. * @throws IllegalArgumentException thrown if parameters fail the validation. diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/GenerateAwsTemplatesClient.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/GenerateAwsTemplatesClient.java new file mode 100644 index 000000000000..c78e8ad22d7e --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/GenerateAwsTemplatesClient.java @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.PostResponseInner; +import com.azure.resourcemanager.hybridconnectivity.models.GenerateAwsTemplateRequest; + +/** + * An instance of this class provides access to all the operations defined in GenerateAwsTemplatesClient. + */ +public interface GenerateAwsTemplatesClient { + /** + * Retrieve AWS Cloud Formation template. + * + * @param generateAwsTemplateRequest ConnectorId and SolutionTypes and their properties to Generate AWS CFT + * Template. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response postWithResponse(GenerateAwsTemplateRequest generateAwsTemplateRequest, + Context context); + + /** + * Retrieve AWS Cloud Formation template. + * + * @param generateAwsTemplateRequest ConnectorId and SolutionTypes and their properties to Generate AWS CFT + * Template. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + PostResponseInner post(GenerateAwsTemplateRequest generateAwsTemplateRequest); +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/HybridConnectivityManagementApi.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/HybridConnectivityManagementApi.java deleted file mode 100644 index e5b7ddf848fc..000000000000 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/HybridConnectivityManagementApi.java +++ /dev/null @@ -1,62 +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.resourcemanager.hybridconnectivity.fluent; - -import com.azure.core.http.HttpPipeline; -import java.time.Duration; - -/** - * The interface for HybridConnectivityManagementApi class. - */ -public interface HybridConnectivityManagementApi { - /** - * Gets server parameter. - * - * @return the endpoint value. - */ - String getEndpoint(); - - /** - * Gets Api Version. - * - * @return the apiVersion value. - */ - String getApiVersion(); - - /** - * Gets The HTTP pipeline to send requests through. - * - * @return the httpPipeline value. - */ - HttpPipeline getHttpPipeline(); - - /** - * Gets The default poll interval for long-running operation. - * - * @return the defaultPollInterval value. - */ - Duration getDefaultPollInterval(); - - /** - * Gets the OperationsClient object to access its operations. - * - * @return the OperationsClient object. - */ - OperationsClient getOperations(); - - /** - * Gets the EndpointsClient object to access its operations. - * - * @return the EndpointsClient object. - */ - EndpointsClient getEndpoints(); - - /** - * Gets the ServiceConfigurationsClient object to access its operations. - * - * @return the ServiceConfigurationsClient object. - */ - ServiceConfigurationsClient getServiceConfigurations(); -} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/HybridConnectivityMgmtClient.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/HybridConnectivityMgmtClient.java new file mode 100644 index 000000000000..2c551213b9e8 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/HybridConnectivityMgmtClient.java @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.fluent; + +import com.azure.core.http.HttpPipeline; +import java.time.Duration; + +/** + * The interface for HybridConnectivityMgmtClient class. + */ +public interface HybridConnectivityMgmtClient { + /** + * Gets Service host. + * + * @return the endpoint value. + */ + String getEndpoint(); + + /** + * Gets Version parameter. + * + * @return the apiVersion value. + */ + String getApiVersion(); + + /** + * Gets The ID of the target subscription. The value must be an UUID. + * + * @return the subscriptionId value. + */ + String getSubscriptionId(); + + /** + * Gets The HTTP pipeline to send requests through. + * + * @return the httpPipeline value. + */ + HttpPipeline getHttpPipeline(); + + /** + * Gets The default poll interval for long-running operation. + * + * @return the defaultPollInterval value. + */ + Duration getDefaultPollInterval(); + + /** + * Gets the OperationsClient object to access its operations. + * + * @return the OperationsClient object. + */ + OperationsClient getOperations(); + + /** + * Gets the EndpointsClient object to access its operations. + * + * @return the EndpointsClient object. + */ + EndpointsClient getEndpoints(); + + /** + * Gets the ServiceConfigurationsClient object to access its operations. + * + * @return the ServiceConfigurationsClient object. + */ + ServiceConfigurationsClient getServiceConfigurations(); + + /** + * Gets the GenerateAwsTemplatesClient object to access its operations. + * + * @return the GenerateAwsTemplatesClient object. + */ + GenerateAwsTemplatesClient getGenerateAwsTemplates(); + + /** + * Gets the PublicCloudConnectorsClient object to access its operations. + * + * @return the PublicCloudConnectorsClient object. + */ + PublicCloudConnectorsClient getPublicCloudConnectors(); + + /** + * Gets the SolutionConfigurationsClient object to access its operations. + * + * @return the SolutionConfigurationsClient object. + */ + SolutionConfigurationsClient getSolutionConfigurations(); + + /** + * Gets the InventoriesClient object to access its operations. + * + * @return the InventoriesClient object. + */ + InventoriesClient getInventories(); + + /** + * Gets the SolutionTypesClient object to access its operations. + * + * @return the SolutionTypesClient object. + */ + SolutionTypesClient getSolutionTypes(); +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/InventoriesClient.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/InventoriesClient.java new file mode 100644 index 000000000000..64097824e2d3 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/InventoriesClient.java @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.InventoryResourceInner; + +/** + * An instance of this class provides access to all the operations defined in InventoriesClient. + */ +public interface InventoriesClient { + /** + * Get a InventoryResource. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param inventoryId Inventory resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a InventoryResource along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceUri, String solutionConfiguration, + String inventoryId, Context context); + + /** + * Get a InventoryResource. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param inventoryId Inventory resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a InventoryResource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + InventoryResourceInner get(String resourceUri, String solutionConfiguration, String inventoryId); + + /** + * List InventoryResource resources by SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a InventoryResource list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listBySolutionConfiguration(String resourceUri, String solutionConfiguration); + + /** + * List InventoryResource resources by SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a InventoryResource list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listBySolutionConfiguration(String resourceUri, String solutionConfiguration, + Context context); +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/OperationsClient.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/OperationsClient.java index d8c9fc8cb011..fc11b01f3b90 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/OperationsClient.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/OperationsClient.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.fluent; @@ -15,7 +15,7 @@ */ public interface OperationsClient { /** - * Lists the available Hybrid Connectivity REST API operations. + * List the operations for the provider. * * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -26,7 +26,7 @@ public interface OperationsClient { PagedIterable list(); /** - * Lists the available Hybrid Connectivity REST API operations. + * List the operations for the provider. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/PublicCloudConnectorsClient.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/PublicCloudConnectorsClient.java new file mode 100644 index 000000000000..83728ede6a4a --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/PublicCloudConnectorsClient.java @@ -0,0 +1,270 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.OperationStatusResultInner; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.PublicCloudConnectorInner; + +/** + * An instance of this class provides access to all the operations defined in PublicCloudConnectorsClient. + */ +public interface PublicCloudConnectorsClient { + /** + * Get a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a PublicCloudConnector along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getByResourceGroupWithResponse(String resourceGroupName, + String publicCloudConnector, Context context); + + /** + * Get a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a PublicCloudConnector. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + PublicCloudConnectorInner getByResourceGroup(String resourceGroupName, String publicCloudConnector); + + /** + * Create a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of public Cloud Connector. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, PublicCloudConnectorInner> + beginCreateOrUpdate(String resourceGroupName, String publicCloudConnector, PublicCloudConnectorInner resource); + + /** + * Create a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of public Cloud Connector. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, PublicCloudConnectorInner> beginCreateOrUpdate( + String resourceGroupName, String publicCloudConnector, PublicCloudConnectorInner resource, Context context); + + /** + * Create a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return public Cloud Connector. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + PublicCloudConnectorInner createOrUpdate(String resourceGroupName, String publicCloudConnector, + PublicCloudConnectorInner resource); + + /** + * Create a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return public Cloud Connector. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + PublicCloudConnectorInner createOrUpdate(String resourceGroupName, String publicCloudConnector, + PublicCloudConnectorInner resource, Context context); + + /** + * Update a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param properties The resource properties to be updated. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return public Cloud Connector along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response updateWithResponse(String resourceGroupName, String publicCloudConnector, + PublicCloudConnectorInner properties, Context context); + + /** + * Update a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return public Cloud Connector. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + PublicCloudConnectorInner update(String resourceGroupName, String publicCloudConnector, + PublicCloudConnectorInner properties); + + /** + * Delete a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response deleteWithResponse(String resourceGroupName, String publicCloudConnector, Context context); + + /** + * Delete a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void delete(String resourceGroupName, String publicCloudConnector); + + /** + * List PublicCloudConnector resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PublicCloudConnector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByResourceGroup(String resourceGroupName); + + /** + * List PublicCloudConnector resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PublicCloudConnector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByResourceGroup(String resourceGroupName, Context context); + + /** + * List PublicCloudConnector resources by subscription ID. + * + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PublicCloudConnector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(); + + /** + * List PublicCloudConnector resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PublicCloudConnector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(Context context); + + /** + * A long-running resource action. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, OperationStatusResultInner> + beginTestPermissions(String resourceGroupName, String publicCloudConnector); + + /** + * A long-running resource action. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, OperationStatusResultInner> + beginTestPermissions(String resourceGroupName, String publicCloudConnector, Context context); + + /** + * A long-running resource action. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + OperationStatusResultInner testPermissions(String resourceGroupName, String publicCloudConnector); + + /** + * A long-running resource action. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + OperationStatusResultInner testPermissions(String resourceGroupName, String publicCloudConnector, Context context); +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/ServiceConfigurationsClient.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/ServiceConfigurationsClient.java index a78e41e97562..ca4b20a11775 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/ServiceConfigurationsClient.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/ServiceConfigurationsClient.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.fluent; @@ -16,42 +16,10 @@ * An instance of this class provides access to all the operations defined in ServiceConfigurationsClient. */ public interface ServiceConfigurationsClient { - /** - * Lists of all the services associated with endpoint resource. - * - * API to enumerate registered services in service configurations under a Endpoint Resource. - * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. - * @param endpointName The endpoint name. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the paginated list of serviceConfigurations as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable listByEndpointResource(String resourceUri, String endpointName); - - /** - * Lists of all the services associated with endpoint resource. - * - * API to enumerate registered services in service configurations under a Endpoint Resource. - * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. - * @param endpointName The endpoint name. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the paginated list of serviceConfigurations as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable listByEndpointResource(String resourceUri, String endpointName, - Context context); - /** * Gets the details about the service to the resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @param context The context to associate with this operation. @@ -67,7 +35,7 @@ Response getWithResponse(String resourceUri, /** * Gets the details about the service to the resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -81,7 +49,7 @@ Response getWithResponse(String resourceUri, /** * Create or update a service in serviceConfiguration for the endpoint resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @param serviceConfigurationResource Service details. @@ -99,7 +67,7 @@ Response createOrupdateWithResponse(String re /** * Create or update a service in serviceConfiguration for the endpoint resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @param serviceConfigurationResource Service details. @@ -115,7 +83,7 @@ ServiceConfigurationResourceInner createOrupdate(String resourceUri, String endp /** * Update the service details in the service configurations of the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @param serviceConfigurationResource Service details. @@ -133,7 +101,7 @@ Response updateWithResponse(String resourceUr /** * Update the service details in the service configurations of the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @param serviceConfigurationResource Service details. @@ -149,7 +117,7 @@ ServiceConfigurationResourceInner update(String resourceUri, String endpointName /** * Deletes the service details to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @param context The context to associate with this operation. @@ -165,7 +133,7 @@ Response deleteWithResponse(String resourceUri, String endpointName, Strin /** * Deletes the service details to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -174,4 +142,36 @@ Response deleteWithResponse(String resourceUri, String endpointName, Strin */ @ServiceMethod(returns = ReturnType.SINGLE) void delete(String resourceUri, String endpointName, String serviceConfigurationName); + + /** + * Lists of all the services associated with endpoint resource. + * + * API to enumerate registered services in service configurations under a Endpoint Resource. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param endpointName The endpoint name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the paginated list of serviceConfigurations as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByEndpointResource(String resourceUri, String endpointName); + + /** + * Lists of all the services associated with endpoint resource. + * + * API to enumerate registered services in service configurations under a Endpoint Resource. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param endpointName The endpoint name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the paginated list of serviceConfigurations as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByEndpointResource(String resourceUri, String endpointName, + Context context); } diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/SolutionConfigurationsClient.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/SolutionConfigurationsClient.java new file mode 100644 index 000000000000..d94675e0a2bc --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/SolutionConfigurationsClient.java @@ -0,0 +1,217 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.OperationStatusResultInner; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.SolutionConfigurationInner; + +/** + * An instance of this class provides access to all the operations defined in SolutionConfigurationsClient. + */ +public interface SolutionConfigurationsClient { + /** + * Get a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SolutionConfiguration along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceUri, String solutionConfiguration, + Context context); + + /** + * Get a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SolutionConfiguration. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + SolutionConfigurationInner get(String resourceUri, String solutionConfiguration); + + /** + * Create a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return solution Configuration along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response createOrUpdateWithResponse(String resourceUri, String solutionConfiguration, + SolutionConfigurationInner resource, Context context); + + /** + * Create a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return solution Configuration. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + SolutionConfigurationInner createOrUpdate(String resourceUri, String solutionConfiguration, + SolutionConfigurationInner resource); + + /** + * Update a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param properties The resource properties to be updated. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return solution Configuration along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response updateWithResponse(String resourceUri, String solutionConfiguration, + SolutionConfigurationInner properties, Context context); + + /** + * Update a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return solution Configuration. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + SolutionConfigurationInner update(String resourceUri, String solutionConfiguration, + SolutionConfigurationInner properties); + + /** + * Delete a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response deleteWithResponse(String resourceUri, String solutionConfiguration, Context context); + + /** + * Delete a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void delete(String resourceUri, String solutionConfiguration); + + /** + * List SolutionConfiguration resources by parent. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionConfiguration list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(String resourceUri); + + /** + * List SolutionConfiguration resources by parent. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionConfiguration list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(String resourceUri, Context context); + + /** + * Trigger immediate sync with source cloud. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, OperationStatusResultInner> beginSyncNow(String resourceUri, + String solutionConfiguration); + + /** + * Trigger immediate sync with source cloud. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, OperationStatusResultInner> beginSyncNow(String resourceUri, + String solutionConfiguration, Context context); + + /** + * Trigger immediate sync with source cloud. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + OperationStatusResultInner syncNow(String resourceUri, String solutionConfiguration); + + /** + * Trigger immediate sync with source cloud. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + OperationStatusResultInner syncNow(String resourceUri, String solutionConfiguration, Context context); +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/SolutionTypesClient.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/SolutionTypesClient.java new file mode 100644 index 000000000000..831abca474a4 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/SolutionTypesClient.java @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.SolutionTypeResourceInner; + +/** + * An instance of this class provides access to all the operations defined in SolutionTypesClient. + */ +public interface SolutionTypesClient { + /** + * Get a SolutionTypeResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param solutionType Solution Type resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SolutionTypeResource along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getByResourceGroupWithResponse(String resourceGroupName, String solutionType, + Context context); + + /** + * Get a SolutionTypeResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param solutionType Solution Type resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SolutionTypeResource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + SolutionTypeResourceInner getByResourceGroup(String resourceGroupName, String solutionType); + + /** + * List SolutionTypeResource resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionTypeResource list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByResourceGroup(String resourceGroupName); + + /** + * List SolutionTypeResource resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionTypeResource list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByResourceGroup(String resourceGroupName, Context context); + + /** + * List SolutionTypeResource resources by subscription ID. + * + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionTypeResource list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(); + + /** + * List SolutionTypeResource resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionTypeResource list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(Context context); +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/AADProfileProperties.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/AADProfileProperties.java new file mode 100644 index 000000000000..b78ff8831abb --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/AADProfileProperties.java @@ -0,0 +1,111 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.fluent.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.logging.ClientLogger; +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 AAD Profile. + */ +@Immutable +public final class AADProfileProperties implements JsonSerializable { + /* + * The arc ingress gateway server app id. + */ + private String serverId; + + /* + * The target resource home tenant id. + */ + private String tenantId; + + /** + * Creates an instance of AADProfileProperties class. + */ + private AADProfileProperties() { + } + + /** + * Get the serverId property: The arc ingress gateway server app id. + * + * @return the serverId value. + */ + public String serverId() { + return this.serverId; + } + + /** + * Get the tenantId property: The target resource home tenant id. + * + * @return the tenantId value. + */ + public String tenantId() { + return this.tenantId; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (serverId() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property serverId in model AADProfileProperties")); + } + if (tenantId() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property tenantId in model AADProfileProperties")); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(AADProfileProperties.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("serverId", this.serverId); + jsonWriter.writeStringField("tenantId", this.tenantId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AADProfileProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AADProfileProperties 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 AADProfileProperties. + */ + public static AADProfileProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AADProfileProperties deserializedAADProfileProperties = new AADProfileProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("serverId".equals(fieldName)) { + deserializedAADProfileProperties.serverId = reader.getString(); + } else if ("tenantId".equals(fieldName)) { + deserializedAADProfileProperties.tenantId = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAADProfileProperties; + }); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/AadProfileProperties.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/AadProfileProperties.java deleted file mode 100644 index 2ae68ae3d4b2..000000000000 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/AadProfileProperties.java +++ /dev/null @@ -1,133 +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.resourcemanager.hybridconnectivity.fluent.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.util.logging.ClientLogger; -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 AAD Profile. - */ -@Fluent -public final class AadProfileProperties implements JsonSerializable { - /* - * The arc ingress gateway server app id. - */ - private String serverId; - - /* - * The target resource home tenant id. - */ - private String tenantId; - - /** - * Creates an instance of AadProfileProperties class. - */ - public AadProfileProperties() { - } - - /** - * Get the serverId property: The arc ingress gateway server app id. - * - * @return the serverId value. - */ - public String serverId() { - return this.serverId; - } - - /** - * Set the serverId property: The arc ingress gateway server app id. - * - * @param serverId the serverId value to set. - * @return the AadProfileProperties object itself. - */ - public AadProfileProperties withServerId(String serverId) { - this.serverId = serverId; - return this; - } - - /** - * Get the tenantId property: The target resource home tenant id. - * - * @return the tenantId value. - */ - public String tenantId() { - return this.tenantId; - } - - /** - * Set the tenantId property: The target resource home tenant id. - * - * @param tenantId the tenantId value to set. - * @return the AadProfileProperties object itself. - */ - public AadProfileProperties withTenantId(String tenantId) { - this.tenantId = tenantId; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (serverId() == null) { - throw LOGGER.atError() - .log(new IllegalArgumentException("Missing required property serverId in model AadProfileProperties")); - } - if (tenantId() == null) { - throw LOGGER.atError() - .log(new IllegalArgumentException("Missing required property tenantId in model AadProfileProperties")); - } - } - - private static final ClientLogger LOGGER = new ClientLogger(AadProfileProperties.class); - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("serverId", this.serverId); - jsonWriter.writeStringField("tenantId", this.tenantId); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of AadProfileProperties from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of AadProfileProperties 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 AadProfileProperties. - */ - public static AadProfileProperties fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - AadProfileProperties deserializedAadProfileProperties = new AadProfileProperties(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("serverId".equals(fieldName)) { - deserializedAadProfileProperties.serverId = reader.getString(); - } else if ("tenantId".equals(fieldName)) { - deserializedAadProfileProperties.tenantId = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedAadProfileProperties; - }); - } -} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/EndpointAccessResourceInner.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/EndpointAccessResourceInner.java index 1c8ad551579e..aacd41ab3838 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/EndpointAccessResourceInner.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/EndpointAccessResourceInner.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.fluent.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -14,7 +14,7 @@ /** * The endpoint access for the target resource. */ -@Fluent +@Immutable public final class EndpointAccessResourceInner implements JsonSerializable { /* * Azure relay hybrid connection access properties @@ -24,7 +24,7 @@ public final class EndpointAccessResourceInner implements JsonSerializable { /* * Azure relay hybrid connection access properties @@ -29,7 +29,7 @@ public final class IngressGatewayResourceInner implements JsonSerializable { /* * The ingress hostname. @@ -25,12 +25,12 @@ public final class IngressProfileProperties implements JsonSerializable { + InventoryResourceInner deserializedInventoryResourceInner = new InventoryResourceInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedInventoryResourceInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedInventoryResourceInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedInventoryResourceInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedInventoryResourceInner.properties = InventoryProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedInventoryResourceInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedInventoryResourceInner; + }); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/ManagedProxyResourceInner.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/ManagedProxyResourceInner.java index da4767dd13a4..1dd10e971eef 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/ManagedProxyResourceInner.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/ManagedProxyResourceInner.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.fluent.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Immutable; import com.azure.core.util.logging.ClientLogger; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -15,7 +15,7 @@ /** * Managed Proxy. */ -@Fluent +@Immutable public final class ManagedProxyResourceInner implements JsonSerializable { /* * The short lived proxy name. @@ -30,7 +30,7 @@ public final class ManagedProxyResourceInner implements JsonSerializable { /* * The name of the operation, as per Resource-Based Access Control (RBAC). Examples: @@ -28,8 +26,8 @@ public final class OperationInner implements JsonSerializable { private String name; /* - * Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for - * ARM/control-plane operations. + * Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure + * Resource Manager/control-plane operations. */ private Boolean isDataAction; @@ -45,14 +43,14 @@ public final class OperationInner implements JsonSerializable { private Origin origin; /* - * Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + * Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. */ private ActionType actionType; /** * Creates an instance of OperationInner class. */ - public OperationInner() { + private OperationInner() { } /** @@ -67,7 +65,7 @@ public String name() { /** * Get the isDataAction property: Whether the operation applies to data-plane. This is "true" for data-plane - * operations and "false" for ARM/control-plane operations. + * operations and "false" for Azure Resource Manager/control-plane operations. * * @return the isDataAction value. */ @@ -84,17 +82,6 @@ public OperationDisplay display() { return this.display; } - /** - * Set the display property: Localized display information for this particular operation. - * - * @param display the display value to set. - * @return the OperationInner object itself. - */ - public OperationInner withDisplay(OperationDisplay display) { - this.display = display; - return this; - } - /** * Get the origin property: The intended executor of the operation; as in Resource Based Access Control (RBAC) and * audit logs UX. Default value is "user,system". @@ -106,8 +93,8 @@ public Origin origin() { } /** - * Get the actionType property: Enum. Indicates the action type. "Internal" refers to actions that are for internal - * only APIs. + * Get the actionType property: Extensible enum. Indicates the action type. "Internal" refers to actions that are + * for internal only APIs. * * @return the actionType value. */ diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/OperationStatusResultInner.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/OperationStatusResultInner.java new file mode 100644 index 000000000000..4e7c59629b20 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/OperationStatusResultInner.java @@ -0,0 +1,241 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.fluent.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.management.exception.ManagementError; +import com.azure.core.util.CoreUtils; +import com.azure.core.util.logging.ClientLogger; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.List; + +/** + * The current status of an async operation. + */ +@Immutable +public final class OperationStatusResultInner implements JsonSerializable { + /* + * Fully qualified ID for the async operation. + */ + private String id; + + /* + * Name of the async operation. + */ + private String name; + + /* + * Operation status. + */ + private String status; + + /* + * Percent of the operation that is complete. + */ + private Double percentComplete; + + /* + * The start time of the operation. + */ + private OffsetDateTime startTime; + + /* + * The end time of the operation. + */ + private OffsetDateTime endTime; + + /* + * The operations list. + */ + private List operations; + + /* + * If present, details of the operation error. + */ + private ManagementError error; + + /* + * Fully qualified ID of the resource against which the original async operation was started. + */ + private String resourceId; + + /** + * Creates an instance of OperationStatusResultInner class. + */ + private OperationStatusResultInner() { + } + + /** + * Get the id property: Fully qualified ID for the async operation. + * + * @return the id value. + */ + public String id() { + return this.id; + } + + /** + * Get the name property: Name of the async operation. + * + * @return the name value. + */ + public String name() { + return this.name; + } + + /** + * Get the status property: Operation status. + * + * @return the status value. + */ + public String status() { + return this.status; + } + + /** + * Get the percentComplete property: Percent of the operation that is complete. + * + * @return the percentComplete value. + */ + public Double percentComplete() { + return this.percentComplete; + } + + /** + * Get the startTime property: The start time of the operation. + * + * @return the startTime value. + */ + public OffsetDateTime startTime() { + return this.startTime; + } + + /** + * Get the endTime property: The end time of the operation. + * + * @return the endTime value. + */ + public OffsetDateTime endTime() { + return this.endTime; + } + + /** + * Get the operations property: The operations list. + * + * @return the operations value. + */ + public List operations() { + return this.operations; + } + + /** + * Get the error property: If present, details of the operation error. + * + * @return the error value. + */ + public ManagementError error() { + return this.error; + } + + /** + * Get the resourceId property: Fully qualified ID of the resource against which the original async operation was + * started. + * + * @return the resourceId value. + */ + public String resourceId() { + return this.resourceId; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (status() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property status in model OperationStatusResultInner")); + } + if (operations() != null) { + operations().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(OperationStatusResultInner.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("status", this.status); + jsonWriter.writeStringField("id", this.id); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeNumberField("percentComplete", this.percentComplete); + jsonWriter.writeStringField("startTime", + this.startTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.startTime)); + jsonWriter.writeStringField("endTime", + this.endTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.endTime)); + jsonWriter.writeArrayField("operations", this.operations, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeJsonField("error", this.error); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OperationStatusResultInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OperationStatusResultInner 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 OperationStatusResultInner. + */ + public static OperationStatusResultInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OperationStatusResultInner deserializedOperationStatusResultInner = new OperationStatusResultInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("status".equals(fieldName)) { + deserializedOperationStatusResultInner.status = reader.getString(); + } else if ("id".equals(fieldName)) { + deserializedOperationStatusResultInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedOperationStatusResultInner.name = reader.getString(); + } else if ("percentComplete".equals(fieldName)) { + deserializedOperationStatusResultInner.percentComplete = reader.getNullable(JsonReader::getDouble); + } else if ("startTime".equals(fieldName)) { + deserializedOperationStatusResultInner.startTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("endTime".equals(fieldName)) { + deserializedOperationStatusResultInner.endTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("operations".equals(fieldName)) { + List operations + = reader.readArray(reader1 -> OperationStatusResultInner.fromJson(reader1)); + deserializedOperationStatusResultInner.operations = operations; + } else if ("error".equals(fieldName)) { + deserializedOperationStatusResultInner.error = ManagementError.fromJson(reader); + } else if ("resourceId".equals(fieldName)) { + deserializedOperationStatusResultInner.resourceId = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedOperationStatusResultInner; + }); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/PostResponseInner.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/PostResponseInner.java new file mode 100644 index 000000000000..d27c7840aa58 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/PostResponseInner.java @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.fluent.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 PostResponse model. + */ +@Immutable +public final class PostResponseInner implements JsonSerializable { + /** + * Creates an instance of PostResponseInner class. + */ + private PostResponseInner() { + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of PostResponseInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of PostResponseInner 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 PostResponseInner. + */ + public static PostResponseInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + PostResponseInner deserializedPostResponseInner = new PostResponseInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + reader.skipChildren(); + } + + return deserializedPostResponseInner; + }); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/PublicCloudConnectorInner.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/PublicCloudConnectorInner.java new file mode 100644 index 000000000000..8654efebb8a1 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/PublicCloudConnectorInner.java @@ -0,0 +1,192 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.Resource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.hybridconnectivity.models.PublicCloudConnectorProperties; +import java.io.IOException; +import java.util.Map; + +/** + * Public Cloud Connector. + */ +@Fluent +public final class PublicCloudConnectorInner extends Resource { + /* + * The resource-specific properties for this resource. + */ + private PublicCloudConnectorProperties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of PublicCloudConnectorInner class. + */ + public PublicCloudConnectorInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public PublicCloudConnectorProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the PublicCloudConnectorInner object itself. + */ + public PublicCloudConnectorInner withProperties(PublicCloudConnectorProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * {@inheritDoc} + */ + @Override + public PublicCloudConnectorInner withLocation(String location) { + super.withLocation(location); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public PublicCloudConnectorInner withTags(Map tags) { + super.withTags(tags); + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("location", location()); + jsonWriter.writeMapField("tags", tags(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of PublicCloudConnectorInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of PublicCloudConnectorInner 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 PublicCloudConnectorInner. + */ + public static PublicCloudConnectorInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + PublicCloudConnectorInner deserializedPublicCloudConnectorInner = new PublicCloudConnectorInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedPublicCloudConnectorInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedPublicCloudConnectorInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedPublicCloudConnectorInner.type = reader.getString(); + } else if ("location".equals(fieldName)) { + deserializedPublicCloudConnectorInner.withLocation(reader.getString()); + } else if ("tags".equals(fieldName)) { + Map tags = reader.readMap(reader1 -> reader1.getString()); + deserializedPublicCloudConnectorInner.withTags(tags); + } else if ("properties".equals(fieldName)) { + deserializedPublicCloudConnectorInner.properties = PublicCloudConnectorProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedPublicCloudConnectorInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedPublicCloudConnectorInner; + }); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/RelayNamespaceAccessProperties.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/RelayNamespaceAccessProperties.java index 0a07d209624f..f421fd1ff3c7 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/RelayNamespaceAccessProperties.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/RelayNamespaceAccessProperties.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.fluent.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Immutable; import com.azure.core.util.logging.ClientLogger; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -15,7 +15,7 @@ /** * Azure relay hybrid connection access properties. */ -@Fluent +@Immutable public final class RelayNamespaceAccessProperties implements JsonSerializable { /* * The namespace name. @@ -50,7 +50,7 @@ public final class RelayNamespaceAccessProperties implements JsonSerializable { + SolutionConfigurationInner deserializedSolutionConfigurationInner = new SolutionConfigurationInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedSolutionConfigurationInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedSolutionConfigurationInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedSolutionConfigurationInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedSolutionConfigurationInner.properties + = SolutionConfigurationProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedSolutionConfigurationInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedSolutionConfigurationInner; + }); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/SolutionTypeResourceInner.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/SolutionTypeResourceInner.java new file mode 100644 index 000000000000..432ff6ea9ac0 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/SolutionTypeResourceInner.java @@ -0,0 +1,155 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.fluent.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionTypeProperties; +import java.io.IOException; + +/** + * Concrete proxy resource types can be created by aliasing this type using a specific property type. + */ +@Immutable +public final class SolutionTypeResourceInner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private SolutionTypeProperties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of SolutionTypeResourceInner class. + */ + private SolutionTypeResourceInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public SolutionTypeProperties properties() { + return this.properties; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SolutionTypeResourceInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SolutionTypeResourceInner 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 SolutionTypeResourceInner. + */ + public static SolutionTypeResourceInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SolutionTypeResourceInner deserializedSolutionTypeResourceInner = new SolutionTypeResourceInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedSolutionTypeResourceInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedSolutionTypeResourceInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedSolutionTypeResourceInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedSolutionTypeResourceInner.properties = SolutionTypeProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedSolutionTypeResourceInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedSolutionTypeResourceInner; + }); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/package-info.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/package-info.java index aa6bc5c99f6c..1840f241e629 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/package-info.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/models/package-info.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. /** - * Package containing the inner data models for HybridConnectivityManagementApi. - * REST API for Hybrid Connectivity. + * Package containing the inner data models for HybridConnectivity. + * REST API for public clouds. */ package com.azure.resourcemanager.hybridconnectivity.fluent.models; diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/package-info.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/package-info.java index 24f3bcda921c..be29af200175 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/package-info.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/fluent/package-info.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. /** - * Package containing the service clients for HybridConnectivityManagementApi. - * REST API for Hybrid Connectivity. + * Package containing the service clients for HybridConnectivity. + * REST API for public clouds. */ package com.azure.resourcemanager.hybridconnectivity.fluent; diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/EndpointAccessResourceImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/EndpointAccessResourceImpl.java index 4cc8742ec19f..0fbed932f7cb 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/EndpointAccessResourceImpl.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/EndpointAccessResourceImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.implementation; diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/EndpointResourceImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/EndpointResourceImpl.java index e699235fc1d8..b7f8f4f7b55f 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/EndpointResourceImpl.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/EndpointResourceImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.implementation; diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/EndpointsClientImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/EndpointsClientImpl.java index 8193f5668425..cbaab4192626 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/EndpointsClientImpl.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/EndpointsClientImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.implementation; @@ -35,7 +35,7 @@ import com.azure.resourcemanager.hybridconnectivity.fluent.models.EndpointResourceInner; import com.azure.resourcemanager.hybridconnectivity.fluent.models.IngressGatewayResourceInner; import com.azure.resourcemanager.hybridconnectivity.fluent.models.ManagedProxyResourceInner; -import com.azure.resourcemanager.hybridconnectivity.models.EndpointsList; +import com.azure.resourcemanager.hybridconnectivity.implementation.models.EndpointsList; import com.azure.resourcemanager.hybridconnectivity.models.ListCredentialsRequest; import com.azure.resourcemanager.hybridconnectivity.models.ListIngressGatewayCredentialsRequest; import com.azure.resourcemanager.hybridconnectivity.models.ManagedProxyRequest; @@ -53,235 +53,120 @@ public final class EndpointsClientImpl implements EndpointsClient { /** * The service client containing this operation class. */ - private final HybridConnectivityManagementApiImpl client; + private final HybridConnectivityMgmtClientImpl client; /** * Initializes an instance of EndpointsClientImpl. * * @param client the instance of the service client containing this operation class. */ - EndpointsClientImpl(HybridConnectivityManagementApiImpl client) { + EndpointsClientImpl(HybridConnectivityMgmtClientImpl client) { this.service = RestProxy.create(EndpointsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); this.client = client; } /** - * The interface defining all the services for HybridConnectivityManagementApiEndpoints to be used by the proxy - * service to perform REST calls. + * The interface defining all the services for HybridConnectivityMgmtClientEndpoints to be used by the proxy service + * to perform REST calls. */ - @Host("{$host}") - @ServiceInterface(name = "HybridConnectivityMa") + @Host("{endpoint}") + @ServiceInterface(name = "HybridConnectivityMg") public interface EndpointsService { - @Headers({ "Content-Type: application/json" }) - @Get("/{resourceUri}/providers/Microsoft.HybridConnectivity/endpoints") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> list(@HostParam("$host") String endpoint, - @QueryParam("api-version") String apiVersion, - @PathParam(value = "resourceUri", encoded = true) String resourceUri, @HeaderParam("Accept") String accept, - Context context); - @Headers({ "Content-Type: application/json" }) @Get("/{resourceUri}/providers/Microsoft.HybridConnectivity/endpoints/{endpointName}") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono> get(@HostParam("$host") String endpoint, + Mono> get(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @PathParam(value = "resourceUri", encoded = true) String resourceUri, @PathParam(value = "endpointName", encoded = true) String endpointName, @HeaderParam("Accept") String accept, Context context); - @Headers({ "Content-Type: application/json" }) @Put("/{resourceUri}/providers/Microsoft.HybridConnectivity/endpoints/{endpointName}") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono> createOrUpdate(@HostParam("$host") String endpoint, + Mono> createOrUpdate(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @PathParam(value = "resourceUri", encoded = true) String resourceUri, @PathParam(value = "endpointName", encoded = true) String endpointName, - @BodyParam("application/json") EndpointResourceInner endpointResource, @HeaderParam("Accept") String accept, - Context context); + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") EndpointResourceInner endpointResource, Context context); - @Headers({ "Content-Type: application/json" }) @Patch("/{resourceUri}/providers/Microsoft.HybridConnectivity/endpoints/{endpointName}") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono> update(@HostParam("$host") String endpoint, + Mono> update(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @PathParam(value = "resourceUri", encoded = true) String resourceUri, @PathParam(value = "endpointName", encoded = true) String endpointName, - @BodyParam("application/json") EndpointResourceInner endpointResource, @HeaderParam("Accept") String accept, - Context context); + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") EndpointResourceInner endpointResource, Context context); @Headers({ "Content-Type: application/json" }) @Delete("/{resourceUri}/providers/Microsoft.HybridConnectivity/endpoints/{endpointName}") @ExpectedResponses({ 200, 204 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono> delete(@HostParam("$host") String endpoint, @QueryParam("api-version") String apiVersion, + Mono> delete(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam(value = "resourceUri", encoded = true) String resourceUri, @PathParam(value = "endpointName", encoded = true) String endpointName, @HeaderParam("Accept") String accept, Context context); + @Headers({ "Content-Type: application/json" }) + @Get("/{resourceUri}/providers/Microsoft.HybridConnectivity/endpoints") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> list(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, + @PathParam(value = "resourceUri", encoded = true) String resourceUri, @HeaderParam("Accept") String accept, + Context context); + @Headers({ "Content-Type: application/json" }) @Post("/{resourceUri}/providers/Microsoft.HybridConnectivity/endpoints/{endpointName}/listCredentials") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono> listCredentials(@HostParam("$host") String endpoint, + Mono> listCredentials(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @PathParam(value = "resourceUri", encoded = true) String resourceUri, @PathParam(value = "endpointName", encoded = true) String endpointName, - @QueryParam("expiresin") Long expiresin, - @BodyParam("application/json") ListCredentialsRequest listCredentialsRequest, - @HeaderParam("Accept") String accept, Context context); + @QueryParam("expiresin") Long expiresin, @HeaderParam("Accept") String accept, + @BodyParam("application/json") ListCredentialsRequest listCredentialsRequest, Context context); @Headers({ "Content-Type: application/json" }) @Post("/{resourceUri}/providers/Microsoft.HybridConnectivity/endpoints/{endpointName}/listIngressGatewayCredentials") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono> listIngressGatewayCredentials(@HostParam("$host") String endpoint, - @QueryParam("api-version") String apiVersion, + Mono> listIngressGatewayCredentials( + @HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @PathParam(value = "resourceUri", encoded = true) String resourceUri, @PathParam(value = "endpointName", encoded = true) String endpointName, - @QueryParam("expiresin") Long expiresin, + @QueryParam("expiresin") Long expiresin, @HeaderParam("Accept") String accept, @BodyParam("application/json") ListIngressGatewayCredentialsRequest listIngressGatewayCredentialsRequest, - @HeaderParam("Accept") String accept, Context context); + Context context); - @Headers({ "Content-Type: application/json" }) @Post("/{resourceUri}/providers/Microsoft.HybridConnectivity/endpoints/{endpointName}/listManagedProxyDetails") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono> listManagedProxyDetails(@HostParam("$host") String endpoint, + Mono> listManagedProxyDetails(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @PathParam(value = "resourceUri", encoded = true) String resourceUri, @PathParam(value = "endpointName", encoded = true) String endpointName, - @BodyParam("application/json") ManagedProxyRequest managedProxyRequest, - @HeaderParam("Accept") String accept, Context context); + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") ManagedProxyRequest managedProxyRequest, Context context); @Headers({ "Content-Type: application/json" }) @Get("{nextLink}") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) Mono> listNext(@PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("$host") String endpoint, @HeaderParam("Accept") String accept, Context context); - } - - /** - * List of endpoints to the target resource. - * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the list of endpoints along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listSinglePageAsync(String resourceUri) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (resourceUri == null) { - return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.list(this.client.getEndpoint(), this.client.getApiVersion(), resourceUri, - accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), - res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * List of endpoints to the target resource. - * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the list of endpoints along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listSinglePageAsync(String resourceUri, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (resourceUri == null) { - return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.list(this.client.getEndpoint(), this.client.getApiVersion(), resourceUri, accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } - - /** - * List of endpoints to the target resource. - * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the list of endpoints as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listAsync(String resourceUri) { - return new PagedFlux<>(() -> listSinglePageAsync(resourceUri), nextLink -> listNextSinglePageAsync(nextLink)); - } - - /** - * List of endpoints to the target resource. - * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the list of endpoints as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listAsync(String resourceUri, Context context) { - return new PagedFlux<>(() -> listSinglePageAsync(resourceUri, context), - nextLink -> listNextSinglePageAsync(nextLink, context)); - } - - /** - * List of endpoints to the target resource. - * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the list of endpoints as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list(String resourceUri) { - return new PagedIterable<>(listAsync(resourceUri)); - } - - /** - * List of endpoints to the target resource. - * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the list of endpoints as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list(String resourceUri, Context context) { - return new PagedIterable<>(listAsync(resourceUri, context)); + @HostParam("endpoint") String endpoint, @HeaderParam("Accept") String accept, Context context); } /** * Gets the endpoint to the resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. @@ -310,7 +195,7 @@ private Mono> getWithResponseAsync(String resour /** * Gets the endpoint to the resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -340,7 +225,7 @@ private Mono> getWithResponseAsync(String resour /** * Gets the endpoint to the resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. @@ -355,7 +240,7 @@ private Mono getAsync(String resourceUri, String endpoint /** * Gets the endpoint to the resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -371,7 +256,7 @@ public Response getWithResponse(String resourceUri, Strin /** * Gets the endpoint to the resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. @@ -386,7 +271,7 @@ public EndpointResourceInner get(String resourceUri, String endpointName) { /** * Create or update the endpoint to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param endpointResource Endpoint details. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -414,17 +299,18 @@ private Mono> createOrUpdateWithResponseAsync(St } else { endpointResource.validate(); } + final String contentType = "application/json"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.createOrUpdate(this.client.getEndpoint(), this.client.getApiVersion(), - resourceUri, endpointName, endpointResource, accept, context)) + resourceUri, endpointName, contentType, accept, endpointResource, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Create or update the endpoint to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param endpointResource Endpoint details. * @param context The context to associate with this operation. @@ -453,16 +339,17 @@ private Mono> createOrUpdateWithResponseAsync(St } else { endpointResource.validate(); } + final String contentType = "application/json"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.createOrUpdate(this.client.getEndpoint(), this.client.getApiVersion(), resourceUri, endpointName, - endpointResource, accept, context); + contentType, accept, endpointResource, context); } /** * Create or update the endpoint to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param endpointResource Endpoint details. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -480,7 +367,7 @@ private Mono createOrUpdateAsync(String resourceUri, Stri /** * Create or update the endpoint to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param endpointResource Endpoint details. * @param context The context to associate with this operation. @@ -498,7 +385,7 @@ public Response createOrUpdateWithResponse(String resourc /** * Create or update the endpoint to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param endpointResource Endpoint details. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -515,7 +402,7 @@ public EndpointResourceInner createOrUpdate(String resourceUri, String endpointN /** * Update the endpoint to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param endpointResource Endpoint details. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -543,17 +430,18 @@ private Mono> updateWithResponseAsync(String res } else { endpointResource.validate(); } + final String contentType = "application/json"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.update(this.client.getEndpoint(), this.client.getApiVersion(), resourceUri, - endpointName, endpointResource, accept, context)) + endpointName, contentType, accept, endpointResource, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Update the endpoint to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param endpointResource Endpoint details. * @param context The context to associate with this operation. @@ -582,16 +470,17 @@ private Mono> updateWithResponseAsync(String res } else { endpointResource.validate(); } + final String contentType = "application/json"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.update(this.client.getEndpoint(), this.client.getApiVersion(), resourceUri, endpointName, - endpointResource, accept, context); + contentType, accept, endpointResource, context); } /** * Update the endpoint to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param endpointResource Endpoint details. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -609,7 +498,7 @@ private Mono updateAsync(String resourceUri, String endpo /** * Update the endpoint to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param endpointResource Endpoint details. * @param context The context to associate with this operation. @@ -627,7 +516,7 @@ public Response updateWithResponse(String resourceUri, St /** * Update the endpoint to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param endpointResource Endpoint details. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -644,7 +533,7 @@ public EndpointResourceInner update(String resourceUri, String endpointName, /** * Deletes the endpoint access to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. @@ -673,7 +562,7 @@ private Mono> deleteWithResponseAsync(String resourceUri, String /** * Deletes the endpoint access to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -702,7 +591,7 @@ private Mono> deleteWithResponseAsync(String resourceUri, String /** * Deletes the endpoint access to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. @@ -717,7 +606,7 @@ private Mono deleteAsync(String resourceUri, String endpointName) { /** * Deletes the endpoint access to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -733,7 +622,7 @@ public Response deleteWithResponse(String resourceUri, String endpointName /** * Deletes the endpoint access to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. @@ -744,10 +633,122 @@ public void delete(String resourceUri, String endpointName) { deleteWithResponse(resourceUri, endpointName, Context.NONE); } + /** + * List of endpoints to the target resource. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the list of endpoints along with {@link PagedResponse} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync(String resourceUri) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceUri == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.list(this.client.getEndpoint(), this.client.getApiVersion(), resourceUri, + accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List of endpoints to the target resource. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the list of endpoints along with {@link PagedResponse} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync(String resourceUri, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceUri == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.list(this.client.getEndpoint(), this.client.getApiVersion(), resourceUri, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List of endpoints to the target resource. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the list of endpoints as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync(String resourceUri) { + return new PagedFlux<>(() -> listSinglePageAsync(resourceUri), nextLink -> listNextSinglePageAsync(nextLink)); + } + + /** + * List of endpoints to the target resource. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the list of endpoints as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync(String resourceUri, Context context) { + return new PagedFlux<>(() -> listSinglePageAsync(resourceUri, context), + nextLink -> listNextSinglePageAsync(nextLink, context)); + } + + /** + * List of endpoints to the target resource. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the list of endpoints as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(String resourceUri) { + return new PagedIterable<>(listAsync(resourceUri)); + } + + /** + * List of endpoints to the target resource. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the list of endpoints as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(String resourceUri, Context context) { + return new PagedIterable<>(listAsync(resourceUri, context)); + } + /** * Gets the endpoint access credentials to the resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param expiresin The is how long the endpoint access token is valid (in seconds). * @param listCredentialsRequest Object of type ListCredentialsRequest. @@ -776,14 +777,14 @@ private Mono> listCredentialsWithResponseA final String accept = "application/json"; return FluxUtil .withContext(context -> service.listCredentials(this.client.getEndpoint(), this.client.getApiVersion(), - resourceUri, endpointName, expiresin, listCredentialsRequest, accept, context)) + resourceUri, endpointName, expiresin, accept, listCredentialsRequest, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Gets the endpoint access credentials to the resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param expiresin The is how long the endpoint access token is valid (in seconds). * @param listCredentialsRequest Object of type ListCredentialsRequest. @@ -813,13 +814,13 @@ private Mono> listCredentialsWithResponseA final String accept = "application/json"; context = this.client.mergeContext(context); return service.listCredentials(this.client.getEndpoint(), this.client.getApiVersion(), resourceUri, - endpointName, expiresin, listCredentialsRequest, accept, context); + endpointName, expiresin, accept, listCredentialsRequest, context); } /** * Gets the endpoint access credentials to the resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. @@ -837,7 +838,7 @@ private Mono listCredentialsAsync(String resourceUr /** * Gets the endpoint access credentials to the resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param expiresin The is how long the endpoint access token is valid (in seconds). * @param listCredentialsRequest Object of type ListCredentialsRequest. @@ -857,7 +858,7 @@ public Response listCredentialsWithResponse(String /** * Gets the endpoint access credentials to the resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. @@ -875,7 +876,7 @@ public EndpointAccessResourceInner listCredentials(String resourceUri, String en /** * Gets the ingress gateway endpoint credentials. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param expiresin The is how long the endpoint access token is valid (in seconds). * @param listIngressGatewayCredentialsRequest Object of type ListIngressGatewayCredentialsRequest. @@ -906,14 +907,14 @@ private Mono> listIngressGatewayCredential return FluxUtil .withContext( context -> service.listIngressGatewayCredentials(this.client.getEndpoint(), this.client.getApiVersion(), - resourceUri, endpointName, expiresin, listIngressGatewayCredentialsRequest, accept, context)) + resourceUri, endpointName, expiresin, accept, listIngressGatewayCredentialsRequest, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Gets the ingress gateway endpoint credentials. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param expiresin The is how long the endpoint access token is valid (in seconds). * @param listIngressGatewayCredentialsRequest Object of type ListIngressGatewayCredentialsRequest. @@ -944,13 +945,13 @@ private Mono> listIngressGatewayCredential final String accept = "application/json"; context = this.client.mergeContext(context); return service.listIngressGatewayCredentials(this.client.getEndpoint(), this.client.getApiVersion(), - resourceUri, endpointName, expiresin, listIngressGatewayCredentialsRequest, accept, context); + resourceUri, endpointName, expiresin, accept, listIngressGatewayCredentialsRequest, context); } /** * Gets the ingress gateway endpoint credentials. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. @@ -969,7 +970,7 @@ private Mono listIngressGatewayCredentialsAsync(Str /** * Gets the ingress gateway endpoint credentials. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param expiresin The is how long the endpoint access token is valid (in seconds). * @param listIngressGatewayCredentialsRequest Object of type ListIngressGatewayCredentialsRequest. @@ -990,7 +991,7 @@ public Response listIngressGatewayCredentialsWithRe /** * Gets the ingress gateway endpoint credentials. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. @@ -1008,7 +1009,7 @@ public IngressGatewayResourceInner listIngressGatewayCredentials(String resource /** * Fetches the managed proxy details. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param managedProxyRequest Object of type ManagedProxyRequest. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -1035,17 +1036,19 @@ private Mono> listManagedProxyDetailsWithRes } else { managedProxyRequest.validate(); } + final String contentType = "application/json"; final String accept = "application/json"; return FluxUtil - .withContext(context -> service.listManagedProxyDetails(this.client.getEndpoint(), - this.client.getApiVersion(), resourceUri, endpointName, managedProxyRequest, accept, context)) + .withContext( + context -> service.listManagedProxyDetails(this.client.getEndpoint(), this.client.getApiVersion(), + resourceUri, endpointName, contentType, accept, managedProxyRequest, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Fetches the managed proxy details. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param managedProxyRequest Object of type ManagedProxyRequest. * @param context The context to associate with this operation. @@ -1073,16 +1076,17 @@ private Mono> listManagedProxyDetailsWithRes } else { managedProxyRequest.validate(); } + final String contentType = "application/json"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.listManagedProxyDetails(this.client.getEndpoint(), this.client.getApiVersion(), resourceUri, - endpointName, managedProxyRequest, accept, context); + endpointName, contentType, accept, managedProxyRequest, context); } /** * Fetches the managed proxy details. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param managedProxyRequest Object of type ManagedProxyRequest. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -1100,7 +1104,7 @@ private Mono listManagedProxyDetailsAsync(String reso /** * Fetches the managed proxy details. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param managedProxyRequest Object of type ManagedProxyRequest. * @param context The context to associate with this operation. @@ -1119,7 +1123,7 @@ public Response listManagedProxyDetailsWithResponse(S /** * Fetches the managed proxy details. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param managedProxyRequest Object of type ManagedProxyRequest. * @throws IllegalArgumentException thrown if parameters fail the validation. diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/EndpointsImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/EndpointsImpl.java index 57831e4e540f..29f8477629ab 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/EndpointsImpl.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/EndpointsImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.implementation; @@ -36,16 +36,6 @@ public EndpointsImpl(EndpointsClient innerClient, this.serviceManager = serviceManager; } - public PagedIterable list(String resourceUri) { - PagedIterable inner = this.serviceClient().list(resourceUri); - return ResourceManagerUtils.mapPage(inner, inner1 -> new EndpointResourceImpl(inner1, this.manager())); - } - - public PagedIterable list(String resourceUri, Context context) { - PagedIterable inner = this.serviceClient().list(resourceUri, context); - return ResourceManagerUtils.mapPage(inner, inner1 -> new EndpointResourceImpl(inner1, this.manager())); - } - public Response getWithResponse(String resourceUri, String endpointName, Context context) { Response inner = this.serviceClient().getWithResponse(resourceUri, endpointName, context); @@ -74,6 +64,16 @@ public void deleteByResourceGroup(String resourceUri, String endpointName) { this.serviceClient().delete(resourceUri, endpointName); } + public PagedIterable list(String resourceUri) { + PagedIterable inner = this.serviceClient().list(resourceUri); + return ResourceManagerUtils.mapPage(inner, inner1 -> new EndpointResourceImpl(inner1, this.manager())); + } + + public PagedIterable list(String resourceUri, Context context) { + PagedIterable inner = this.serviceClient().list(resourceUri, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new EndpointResourceImpl(inner1, this.manager())); + } + public Response listCredentialsWithResponse(String resourceUri, String endpointName, Long expiresin, ListCredentialsRequest listCredentialsRequest, Context context) { Response inner = this.serviceClient() diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/GenerateAwsTemplatesClientImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/GenerateAwsTemplatesClientImpl.java new file mode 100644 index 000000000000..ca8a9603de6d --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/GenerateAwsTemplatesClientImpl.java @@ -0,0 +1,186 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.implementation; + +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.PathParam; +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.management.exception.ManagementException; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.resourcemanager.hybridconnectivity.fluent.GenerateAwsTemplatesClient; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.PostResponseInner; +import com.azure.resourcemanager.hybridconnectivity.models.GenerateAwsTemplateRequest; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in GenerateAwsTemplatesClient. + */ +public final class GenerateAwsTemplatesClientImpl implements GenerateAwsTemplatesClient { + /** + * The proxy service used to perform REST calls. + */ + private final GenerateAwsTemplatesService service; + + /** + * The service client containing this operation class. + */ + private final HybridConnectivityMgmtClientImpl client; + + /** + * Initializes an instance of GenerateAwsTemplatesClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + GenerateAwsTemplatesClientImpl(HybridConnectivityMgmtClientImpl client) { + this.service = RestProxy.create(GenerateAwsTemplatesService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for HybridConnectivityMgmtClientGenerateAwsTemplates to be used by the + * proxy service to perform REST calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "HybridConnectivityMg") + public interface GenerateAwsTemplatesService { + @Post("/subscriptions/{subscriptionId}/providers/Microsoft.HybridConnectivity/generateAwsTemplate") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> post(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") GenerateAwsTemplateRequest generateAwsTemplateRequest, Context context); + } + + /** + * Retrieve AWS Cloud Formation template. + * + * @param generateAwsTemplateRequest ConnectorId and SolutionTypes and their properties to Generate AWS CFT + * Template. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> + postWithResponseAsync(GenerateAwsTemplateRequest generateAwsTemplateRequest) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (generateAwsTemplateRequest == null) { + return Mono.error( + new IllegalArgumentException("Parameter generateAwsTemplateRequest is required and cannot be null.")); + } else { + generateAwsTemplateRequest.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.post(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), contentType, accept, generateAwsTemplateRequest, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Retrieve AWS Cloud Formation template. + * + * @param generateAwsTemplateRequest ConnectorId and SolutionTypes and their properties to Generate AWS CFT + * Template. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> + postWithResponseAsync(GenerateAwsTemplateRequest generateAwsTemplateRequest, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (generateAwsTemplateRequest == null) { + return Mono.error( + new IllegalArgumentException("Parameter generateAwsTemplateRequest is required and cannot be null.")); + } else { + generateAwsTemplateRequest.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.post(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + contentType, accept, generateAwsTemplateRequest, context); + } + + /** + * Retrieve AWS Cloud Formation template. + * + * @param generateAwsTemplateRequest ConnectorId and SolutionTypes and their properties to Generate AWS CFT + * Template. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono postAsync(GenerateAwsTemplateRequest generateAwsTemplateRequest) { + return postWithResponseAsync(generateAwsTemplateRequest).flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Retrieve AWS Cloud Formation template. + * + * @param generateAwsTemplateRequest ConnectorId and SolutionTypes and their properties to Generate AWS CFT + * Template. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response postWithResponse(GenerateAwsTemplateRequest generateAwsTemplateRequest, + Context context) { + return postWithResponseAsync(generateAwsTemplateRequest, context).block(); + } + + /** + * Retrieve AWS Cloud Formation template. + * + * @param generateAwsTemplateRequest ConnectorId and SolutionTypes and their properties to Generate AWS CFT + * Template. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public PostResponseInner post(GenerateAwsTemplateRequest generateAwsTemplateRequest) { + return postWithResponse(generateAwsTemplateRequest, Context.NONE).getValue(); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/GenerateAwsTemplatesImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/GenerateAwsTemplatesImpl.java new file mode 100644 index 000000000000..c06e80a63fd2 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/GenerateAwsTemplatesImpl.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.implementation; + +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.hybridconnectivity.fluent.GenerateAwsTemplatesClient; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.PostResponseInner; +import com.azure.resourcemanager.hybridconnectivity.models.GenerateAwsTemplateRequest; +import com.azure.resourcemanager.hybridconnectivity.models.GenerateAwsTemplates; +import com.azure.resourcemanager.hybridconnectivity.models.PostResponse; + +public final class GenerateAwsTemplatesImpl implements GenerateAwsTemplates { + private static final ClientLogger LOGGER = new ClientLogger(GenerateAwsTemplatesImpl.class); + + private final GenerateAwsTemplatesClient innerClient; + + private final com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager serviceManager; + + public GenerateAwsTemplatesImpl(GenerateAwsTemplatesClient innerClient, + com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public Response postWithResponse(GenerateAwsTemplateRequest generateAwsTemplateRequest, + Context context) { + Response inner = this.serviceClient().postWithResponse(generateAwsTemplateRequest, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new PostResponseImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public PostResponse post(GenerateAwsTemplateRequest generateAwsTemplateRequest) { + PostResponseInner inner = this.serviceClient().post(generateAwsTemplateRequest); + if (inner != null) { + return new PostResponseImpl(inner, this.manager()); + } else { + return null; + } + } + + private GenerateAwsTemplatesClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/HybridConnectivityManagementApiBuilder.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/HybridConnectivityManagementApiBuilder.java deleted file mode 100644 index b55c5f896862..000000000000 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/HybridConnectivityManagementApiBuilder.java +++ /dev/null @@ -1,122 +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.resourcemanager.hybridconnectivity.implementation; - -import com.azure.core.annotation.ServiceClientBuilder; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.HttpPipelineBuilder; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.http.policy.UserAgentPolicy; -import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.serializer.SerializerFactory; -import com.azure.core.util.serializer.SerializerAdapter; -import java.time.Duration; - -/** - * A builder for creating a new instance of the HybridConnectivityManagementApiImpl type. - */ -@ServiceClientBuilder(serviceClients = { HybridConnectivityManagementApiImpl.class }) -public final class HybridConnectivityManagementApiBuilder { - /* - * server parameter - */ - private String endpoint; - - /** - * Sets server parameter. - * - * @param endpoint the endpoint value. - * @return the HybridConnectivityManagementApiBuilder. - */ - public HybridConnectivityManagementApiBuilder endpoint(String endpoint) { - this.endpoint = endpoint; - return this; - } - - /* - * The environment to connect to - */ - private AzureEnvironment environment; - - /** - * Sets The environment to connect to. - * - * @param environment the environment value. - * @return the HybridConnectivityManagementApiBuilder. - */ - public HybridConnectivityManagementApiBuilder environment(AzureEnvironment environment) { - this.environment = environment; - 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 HybridConnectivityManagementApiBuilder. - */ - public HybridConnectivityManagementApiBuilder pipeline(HttpPipeline pipeline) { - this.pipeline = pipeline; - return this; - } - - /* - * The default poll interval for long-running operation - */ - private Duration defaultPollInterval; - - /** - * Sets The default poll interval for long-running operation. - * - * @param defaultPollInterval the defaultPollInterval value. - * @return the HybridConnectivityManagementApiBuilder. - */ - public HybridConnectivityManagementApiBuilder defaultPollInterval(Duration defaultPollInterval) { - this.defaultPollInterval = defaultPollInterval; - 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 HybridConnectivityManagementApiBuilder. - */ - public HybridConnectivityManagementApiBuilder serializerAdapter(SerializerAdapter serializerAdapter) { - this.serializerAdapter = serializerAdapter; - return this; - } - - /** - * Builds an instance of HybridConnectivityManagementApiImpl with the provided parameters. - * - * @return an instance of HybridConnectivityManagementApiImpl. - */ - public HybridConnectivityManagementApiImpl buildClient() { - String localEndpoint = (endpoint != null) ? endpoint : "https://management.azure.com"; - AzureEnvironment localEnvironment = (environment != null) ? environment : AzureEnvironment.AZURE; - HttpPipeline localPipeline = (pipeline != null) - ? pipeline - : new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build(); - Duration localDefaultPollInterval - = (defaultPollInterval != null) ? defaultPollInterval : Duration.ofSeconds(30); - SerializerAdapter localSerializerAdapter = (serializerAdapter != null) - ? serializerAdapter - : SerializerFactory.createDefaultManagementSerializerAdapter(); - HybridConnectivityManagementApiImpl client = new HybridConnectivityManagementApiImpl(localPipeline, - localSerializerAdapter, localDefaultPollInterval, localEnvironment, localEndpoint); - return client; - } -} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/HybridConnectivityManagementApiImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/HybridConnectivityManagementApiImpl.java deleted file mode 100644 index fb5238c63857..000000000000 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/HybridConnectivityManagementApiImpl.java +++ /dev/null @@ -1,304 +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.resourcemanager.hybridconnectivity.implementation; - -import com.azure.core.annotation.ServiceClient; -import com.azure.core.http.HttpHeaderName; -import com.azure.core.http.HttpHeaders; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.HttpResponse; -import com.azure.core.http.rest.Response; -import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.exception.ManagementError; -import com.azure.core.management.exception.ManagementException; -import com.azure.core.management.polling.PollResult; -import com.azure.core.management.polling.PollerFactory; -import com.azure.core.util.Context; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.polling.AsyncPollResponse; -import com.azure.core.util.polling.LongRunningOperationStatus; -import com.azure.core.util.polling.PollerFlux; -import com.azure.core.util.serializer.SerializerAdapter; -import com.azure.core.util.serializer.SerializerEncoding; -import com.azure.resourcemanager.hybridconnectivity.fluent.EndpointsClient; -import com.azure.resourcemanager.hybridconnectivity.fluent.HybridConnectivityManagementApi; -import com.azure.resourcemanager.hybridconnectivity.fluent.OperationsClient; -import com.azure.resourcemanager.hybridconnectivity.fluent.ServiceConfigurationsClient; -import java.io.IOException; -import java.lang.reflect.Type; -import java.nio.ByteBuffer; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -/** - * Initializes a new instance of the HybridConnectivityManagementApiImpl type. - */ -@ServiceClient(builder = HybridConnectivityManagementApiBuilder.class) -public final class HybridConnectivityManagementApiImpl implements HybridConnectivityManagementApi { - /** - * server parameter. - */ - private final String endpoint; - - /** - * Gets server parameter. - * - * @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. - */ - SerializerAdapter getSerializerAdapter() { - return this.serializerAdapter; - } - - /** - * The default poll interval for long-running operation. - */ - private final Duration defaultPollInterval; - - /** - * Gets The default poll interval for long-running operation. - * - * @return the defaultPollInterval value. - */ - public Duration getDefaultPollInterval() { - return this.defaultPollInterval; - } - - /** - * The OperationsClient object to access its operations. - */ - private final OperationsClient operations; - - /** - * Gets the OperationsClient object to access its operations. - * - * @return the OperationsClient object. - */ - public OperationsClient getOperations() { - return this.operations; - } - - /** - * The EndpointsClient object to access its operations. - */ - private final EndpointsClient endpoints; - - /** - * Gets the EndpointsClient object to access its operations. - * - * @return the EndpointsClient object. - */ - public EndpointsClient getEndpoints() { - return this.endpoints; - } - - /** - * The ServiceConfigurationsClient object to access its operations. - */ - private final ServiceConfigurationsClient serviceConfigurations; - - /** - * Gets the ServiceConfigurationsClient object to access its operations. - * - * @return the ServiceConfigurationsClient object. - */ - public ServiceConfigurationsClient getServiceConfigurations() { - return this.serviceConfigurations; - } - - /** - * Initializes an instance of HybridConnectivityManagementApi client. - * - * @param httpPipeline The HTTP pipeline to send requests through. - * @param serializerAdapter The serializer to serialize an object into a string. - * @param defaultPollInterval The default poll interval for long-running operation. - * @param environment The Azure environment. - * @param endpoint server parameter. - */ - HybridConnectivityManagementApiImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, - Duration defaultPollInterval, AzureEnvironment environment, String endpoint) { - this.httpPipeline = httpPipeline; - this.serializerAdapter = serializerAdapter; - this.defaultPollInterval = defaultPollInterval; - this.endpoint = endpoint; - this.apiVersion = "2023-03-15"; - this.operations = new OperationsClientImpl(this); - this.endpoints = new EndpointsClientImpl(this); - this.serviceConfigurations = new ServiceConfigurationsClientImpl(this); - } - - /** - * Gets default client context. - * - * @return the default client context. - */ - public Context getContext() { - return Context.NONE; - } - - /** - * Merges default client context with provided context. - * - * @param context the context to be merged with default client context. - * @return the merged context. - */ - public Context mergeContext(Context context) { - return CoreUtils.mergeContexts(this.getContext(), context); - } - - /** - * Gets long running operation result. - * - * @param activationResponse the response of activation operation. - * @param httpPipeline the http pipeline. - * @param pollResultType type of poll result. - * @param finalResultType type of final result. - * @param context the context shared by all requests. - * @param type of poll result. - * @param type of final result. - * @return poller flux for poll result and final result. - */ - public PollerFlux, U> getLroResult(Mono>> activationResponse, - HttpPipeline httpPipeline, Type pollResultType, Type finalResultType, Context context) { - return PollerFactory.create(serializerAdapter, httpPipeline, pollResultType, finalResultType, - defaultPollInterval, activationResponse, context); - } - - /** - * Gets the final result, or an error, based on last async poll response. - * - * @param response the last async poll response. - * @param type of poll result. - * @param type of final result. - * @return the final result, or an error. - */ - public Mono getLroFinalResultOrError(AsyncPollResponse, U> response) { - if (response.getStatus() != LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { - String errorMessage; - ManagementError managementError = null; - HttpResponse errorResponse = null; - PollResult.Error lroError = response.getValue().getError(); - if (lroError != null) { - errorResponse = new HttpResponseImpl(lroError.getResponseStatusCode(), lroError.getResponseHeaders(), - lroError.getResponseBody()); - - errorMessage = response.getValue().getError().getMessage(); - String errorBody = response.getValue().getError().getResponseBody(); - if (errorBody != null) { - // try to deserialize error body to ManagementError - try { - managementError = this.getSerializerAdapter() - .deserialize(errorBody, ManagementError.class, SerializerEncoding.JSON); - if (managementError.getCode() == null || managementError.getMessage() == null) { - managementError = null; - } - } catch (IOException | RuntimeException ioe) { - LOGGER.logThrowableAsWarning(ioe); - } - } - } else { - // fallback to default error message - errorMessage = "Long running operation failed."; - } - if (managementError == null) { - // fallback to default ManagementError - managementError = new ManagementError(response.getStatus().toString(), errorMessage); - } - return Mono.error(new ManagementException(errorMessage, errorResponse, managementError)); - } else { - return response.getFinalResult(); - } - } - - private static final class HttpResponseImpl extends HttpResponse { - private final int statusCode; - - private final byte[] responseBody; - - private final HttpHeaders httpHeaders; - - HttpResponseImpl(int statusCode, HttpHeaders httpHeaders, String responseBody) { - super(null); - this.statusCode = statusCode; - this.httpHeaders = httpHeaders; - this.responseBody = responseBody == null ? null : responseBody.getBytes(StandardCharsets.UTF_8); - } - - public int getStatusCode() { - return statusCode; - } - - public String getHeaderValue(String s) { - return httpHeaders.getValue(HttpHeaderName.fromString(s)); - } - - public HttpHeaders getHeaders() { - return httpHeaders; - } - - public Flux getBody() { - return Flux.just(ByteBuffer.wrap(responseBody)); - } - - public Mono getBodyAsByteArray() { - return Mono.just(responseBody); - } - - public Mono getBodyAsString() { - return Mono.just(new String(responseBody, StandardCharsets.UTF_8)); - } - - public Mono getBodyAsString(Charset charset) { - return Mono.just(new String(responseBody, charset)); - } - } - - private static final ClientLogger LOGGER = new ClientLogger(HybridConnectivityManagementApiImpl.class); -} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/HybridConnectivityMgmtClientBuilder.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/HybridConnectivityMgmtClientBuilder.java new file mode 100644 index 000000000000..98c4e5347941 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/HybridConnectivityMgmtClientBuilder.java @@ -0,0 +1,138 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.implementation; + +import com.azure.core.annotation.ServiceClientBuilder; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.policy.RetryPolicy; +import com.azure.core.http.policy.UserAgentPolicy; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.serializer.SerializerFactory; +import com.azure.core.util.serializer.SerializerAdapter; +import java.time.Duration; + +/** + * A builder for creating a new instance of the HybridConnectivityMgmtClientImpl type. + */ +@ServiceClientBuilder(serviceClients = { HybridConnectivityMgmtClientImpl.class }) +public final class HybridConnectivityMgmtClientBuilder { + /* + * Service host + */ + private String endpoint; + + /** + * Sets Service host. + * + * @param endpoint the endpoint value. + * @return the HybridConnectivityMgmtClientBuilder. + */ + public HybridConnectivityMgmtClientBuilder endpoint(String endpoint) { + this.endpoint = endpoint; + return this; + } + + /* + * The ID of the target subscription. The value must be an UUID. + */ + private String subscriptionId; + + /** + * Sets The ID of the target subscription. The value must be an UUID. + * + * @param subscriptionId the subscriptionId value. + * @return the HybridConnectivityMgmtClientBuilder. + */ + public HybridConnectivityMgmtClientBuilder subscriptionId(String subscriptionId) { + this.subscriptionId = subscriptionId; + return this; + } + + /* + * The environment to connect to + */ + private AzureEnvironment environment; + + /** + * Sets The environment to connect to. + * + * @param environment the environment value. + * @return the HybridConnectivityMgmtClientBuilder. + */ + public HybridConnectivityMgmtClientBuilder environment(AzureEnvironment environment) { + this.environment = environment; + 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 HybridConnectivityMgmtClientBuilder. + */ + public HybridConnectivityMgmtClientBuilder pipeline(HttpPipeline pipeline) { + this.pipeline = pipeline; + return this; + } + + /* + * The default poll interval for long-running operation + */ + private Duration defaultPollInterval; + + /** + * Sets The default poll interval for long-running operation. + * + * @param defaultPollInterval the defaultPollInterval value. + * @return the HybridConnectivityMgmtClientBuilder. + */ + public HybridConnectivityMgmtClientBuilder defaultPollInterval(Duration defaultPollInterval) { + this.defaultPollInterval = defaultPollInterval; + 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 HybridConnectivityMgmtClientBuilder. + */ + public HybridConnectivityMgmtClientBuilder serializerAdapter(SerializerAdapter serializerAdapter) { + this.serializerAdapter = serializerAdapter; + return this; + } + + /** + * Builds an instance of HybridConnectivityMgmtClientImpl with the provided parameters. + * + * @return an instance of HybridConnectivityMgmtClientImpl. + */ + public HybridConnectivityMgmtClientImpl buildClient() { + String localEndpoint = (endpoint != null) ? endpoint : "https://management.azure.com"; + AzureEnvironment localEnvironment = (environment != null) ? environment : AzureEnvironment.AZURE; + HttpPipeline localPipeline = (pipeline != null) + ? pipeline + : new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build(); + Duration localDefaultPollInterval + = (defaultPollInterval != null) ? defaultPollInterval : Duration.ofSeconds(30); + SerializerAdapter localSerializerAdapter = (serializerAdapter != null) + ? serializerAdapter + : SerializerFactory.createDefaultManagementSerializerAdapter(); + HybridConnectivityMgmtClientImpl client = new HybridConnectivityMgmtClientImpl(localPipeline, + localSerializerAdapter, localDefaultPollInterval, localEnvironment, localEndpoint, this.subscriptionId); + return client; + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/HybridConnectivityMgmtClientImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/HybridConnectivityMgmtClientImpl.java new file mode 100644 index 000000000000..f326763b6239 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/HybridConnectivityMgmtClientImpl.java @@ -0,0 +1,400 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.implementation; + +import com.azure.core.annotation.ServiceClient; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.HttpHeaders; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpResponse; +import com.azure.core.http.rest.Response; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.exception.ManagementError; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.management.polling.PollResult; +import com.azure.core.management.polling.PollerFactory; +import com.azure.core.util.Context; +import com.azure.core.util.CoreUtils; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.polling.AsyncPollResponse; +import com.azure.core.util.polling.LongRunningOperationStatus; +import com.azure.core.util.polling.PollerFlux; +import com.azure.core.util.serializer.SerializerAdapter; +import com.azure.core.util.serializer.SerializerEncoding; +import com.azure.resourcemanager.hybridconnectivity.fluent.EndpointsClient; +import com.azure.resourcemanager.hybridconnectivity.fluent.GenerateAwsTemplatesClient; +import com.azure.resourcemanager.hybridconnectivity.fluent.HybridConnectivityMgmtClient; +import com.azure.resourcemanager.hybridconnectivity.fluent.InventoriesClient; +import com.azure.resourcemanager.hybridconnectivity.fluent.OperationsClient; +import com.azure.resourcemanager.hybridconnectivity.fluent.PublicCloudConnectorsClient; +import com.azure.resourcemanager.hybridconnectivity.fluent.ServiceConfigurationsClient; +import com.azure.resourcemanager.hybridconnectivity.fluent.SolutionConfigurationsClient; +import com.azure.resourcemanager.hybridconnectivity.fluent.SolutionTypesClient; +import java.io.IOException; +import java.lang.reflect.Type; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * Initializes a new instance of the HybridConnectivityMgmtClientImpl type. + */ +@ServiceClient(builder = HybridConnectivityMgmtClientBuilder.class) +public final class HybridConnectivityMgmtClientImpl implements HybridConnectivityMgmtClient { + /** + * Service host. + */ + private final String endpoint; + + /** + * Gets Service host. + * + * @return the endpoint value. + */ + public String getEndpoint() { + return this.endpoint; + } + + /** + * Version parameter. + */ + private final String apiVersion; + + /** + * Gets Version parameter. + * + * @return the apiVersion value. + */ + public String getApiVersion() { + return this.apiVersion; + } + + /** + * The ID of the target subscription. The value must be an UUID. + */ + private final String subscriptionId; + + /** + * Gets The ID of the target subscription. The value must be an UUID. + * + * @return the subscriptionId value. + */ + public String getSubscriptionId() { + return this.subscriptionId; + } + + /** + * 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. + */ + SerializerAdapter getSerializerAdapter() { + return this.serializerAdapter; + } + + /** + * The default poll interval for long-running operation. + */ + private final Duration defaultPollInterval; + + /** + * Gets The default poll interval for long-running operation. + * + * @return the defaultPollInterval value. + */ + public Duration getDefaultPollInterval() { + return this.defaultPollInterval; + } + + /** + * The OperationsClient object to access its operations. + */ + private final OperationsClient operations; + + /** + * Gets the OperationsClient object to access its operations. + * + * @return the OperationsClient object. + */ + public OperationsClient getOperations() { + return this.operations; + } + + /** + * The EndpointsClient object to access its operations. + */ + private final EndpointsClient endpoints; + + /** + * Gets the EndpointsClient object to access its operations. + * + * @return the EndpointsClient object. + */ + public EndpointsClient getEndpoints() { + return this.endpoints; + } + + /** + * The ServiceConfigurationsClient object to access its operations. + */ + private final ServiceConfigurationsClient serviceConfigurations; + + /** + * Gets the ServiceConfigurationsClient object to access its operations. + * + * @return the ServiceConfigurationsClient object. + */ + public ServiceConfigurationsClient getServiceConfigurations() { + return this.serviceConfigurations; + } + + /** + * The GenerateAwsTemplatesClient object to access its operations. + */ + private final GenerateAwsTemplatesClient generateAwsTemplates; + + /** + * Gets the GenerateAwsTemplatesClient object to access its operations. + * + * @return the GenerateAwsTemplatesClient object. + */ + public GenerateAwsTemplatesClient getGenerateAwsTemplates() { + return this.generateAwsTemplates; + } + + /** + * The PublicCloudConnectorsClient object to access its operations. + */ + private final PublicCloudConnectorsClient publicCloudConnectors; + + /** + * Gets the PublicCloudConnectorsClient object to access its operations. + * + * @return the PublicCloudConnectorsClient object. + */ + public PublicCloudConnectorsClient getPublicCloudConnectors() { + return this.publicCloudConnectors; + } + + /** + * The SolutionConfigurationsClient object to access its operations. + */ + private final SolutionConfigurationsClient solutionConfigurations; + + /** + * Gets the SolutionConfigurationsClient object to access its operations. + * + * @return the SolutionConfigurationsClient object. + */ + public SolutionConfigurationsClient getSolutionConfigurations() { + return this.solutionConfigurations; + } + + /** + * The InventoriesClient object to access its operations. + */ + private final InventoriesClient inventories; + + /** + * Gets the InventoriesClient object to access its operations. + * + * @return the InventoriesClient object. + */ + public InventoriesClient getInventories() { + return this.inventories; + } + + /** + * The SolutionTypesClient object to access its operations. + */ + private final SolutionTypesClient solutionTypes; + + /** + * Gets the SolutionTypesClient object to access its operations. + * + * @return the SolutionTypesClient object. + */ + public SolutionTypesClient getSolutionTypes() { + return this.solutionTypes; + } + + /** + * Initializes an instance of HybridConnectivityMgmtClient client. + * + * @param httpPipeline The HTTP pipeline to send requests through. + * @param serializerAdapter The serializer to serialize an object into a string. + * @param defaultPollInterval The default poll interval for long-running operation. + * @param environment The Azure environment. + * @param endpoint Service host. + * @param subscriptionId The ID of the target subscription. The value must be an UUID. + */ + HybridConnectivityMgmtClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, + Duration defaultPollInterval, AzureEnvironment environment, String endpoint, String subscriptionId) { + this.httpPipeline = httpPipeline; + this.serializerAdapter = serializerAdapter; + this.defaultPollInterval = defaultPollInterval; + this.endpoint = endpoint; + this.subscriptionId = subscriptionId; + this.apiVersion = "2024-12-01"; + this.operations = new OperationsClientImpl(this); + this.endpoints = new EndpointsClientImpl(this); + this.serviceConfigurations = new ServiceConfigurationsClientImpl(this); + this.generateAwsTemplates = new GenerateAwsTemplatesClientImpl(this); + this.publicCloudConnectors = new PublicCloudConnectorsClientImpl(this); + this.solutionConfigurations = new SolutionConfigurationsClientImpl(this); + this.inventories = new InventoriesClientImpl(this); + this.solutionTypes = new SolutionTypesClientImpl(this); + } + + /** + * Gets default client context. + * + * @return the default client context. + */ + public Context getContext() { + return Context.NONE; + } + + /** + * Merges default client context with provided context. + * + * @param context the context to be merged with default client context. + * @return the merged context. + */ + public Context mergeContext(Context context) { + return CoreUtils.mergeContexts(this.getContext(), context); + } + + /** + * Gets long running operation result. + * + * @param activationResponse the response of activation operation. + * @param httpPipeline the http pipeline. + * @param pollResultType type of poll result. + * @param finalResultType type of final result. + * @param context the context shared by all requests. + * @param type of poll result. + * @param type of final result. + * @return poller flux for poll result and final result. + */ + public PollerFlux, U> getLroResult(Mono>> activationResponse, + HttpPipeline httpPipeline, Type pollResultType, Type finalResultType, Context context) { + return PollerFactory.create(serializerAdapter, httpPipeline, pollResultType, finalResultType, + defaultPollInterval, activationResponse, context); + } + + /** + * Gets the final result, or an error, based on last async poll response. + * + * @param response the last async poll response. + * @param type of poll result. + * @param type of final result. + * @return the final result, or an error. + */ + public Mono getLroFinalResultOrError(AsyncPollResponse, U> response) { + if (response.getStatus() != LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { + String errorMessage; + ManagementError managementError = null; + HttpResponse errorResponse = null; + PollResult.Error lroError = response.getValue().getError(); + if (lroError != null) { + errorResponse = new HttpResponseImpl(lroError.getResponseStatusCode(), lroError.getResponseHeaders(), + lroError.getResponseBody()); + + errorMessage = response.getValue().getError().getMessage(); + String errorBody = response.getValue().getError().getResponseBody(); + if (errorBody != null) { + // try to deserialize error body to ManagementError + try { + managementError = this.getSerializerAdapter() + .deserialize(errorBody, ManagementError.class, SerializerEncoding.JSON); + if (managementError.getCode() == null || managementError.getMessage() == null) { + managementError = null; + } + } catch (IOException | RuntimeException ioe) { + LOGGER.logThrowableAsWarning(ioe); + } + } + } else { + // fallback to default error message + errorMessage = "Long running operation failed."; + } + if (managementError == null) { + // fallback to default ManagementError + managementError = new ManagementError(response.getStatus().toString(), errorMessage); + } + return Mono.error(new ManagementException(errorMessage, errorResponse, managementError)); + } else { + return response.getFinalResult(); + } + } + + private static final class HttpResponseImpl extends HttpResponse { + private final int statusCode; + + private final byte[] responseBody; + + private final HttpHeaders httpHeaders; + + HttpResponseImpl(int statusCode, HttpHeaders httpHeaders, String responseBody) { + super(null); + this.statusCode = statusCode; + this.httpHeaders = httpHeaders; + this.responseBody = responseBody == null ? null : responseBody.getBytes(StandardCharsets.UTF_8); + } + + public int getStatusCode() { + return statusCode; + } + + public String getHeaderValue(String s) { + return httpHeaders.getValue(HttpHeaderName.fromString(s)); + } + + public HttpHeaders getHeaders() { + return httpHeaders; + } + + public Flux getBody() { + return Flux.just(ByteBuffer.wrap(responseBody)); + } + + public Mono getBodyAsByteArray() { + return Mono.just(responseBody); + } + + public Mono getBodyAsString() { + return Mono.just(new String(responseBody, StandardCharsets.UTF_8)); + } + + public Mono getBodyAsString(Charset charset) { + return Mono.just(new String(responseBody, charset)); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(HybridConnectivityMgmtClientImpl.class); +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/IngressGatewayResourceImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/IngressGatewayResourceImpl.java index 540f39e91aaf..6dcfe82e8516 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/IngressGatewayResourceImpl.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/IngressGatewayResourceImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.implementation; diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/InventoriesClientImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/InventoriesClientImpl.java new file mode 100644 index 000000000000..dec3d111ce5c --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/InventoriesClientImpl.java @@ -0,0 +1,409 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.implementation; + +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.resourcemanager.hybridconnectivity.fluent.InventoriesClient; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.InventoryResourceInner; +import com.azure.resourcemanager.hybridconnectivity.implementation.models.InventoryResourceListResult; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in InventoriesClient. + */ +public final class InventoriesClientImpl implements InventoriesClient { + /** + * The proxy service used to perform REST calls. + */ + private final InventoriesService service; + + /** + * The service client containing this operation class. + */ + private final HybridConnectivityMgmtClientImpl client; + + /** + * Initializes an instance of InventoriesClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + InventoriesClientImpl(HybridConnectivityMgmtClientImpl client) { + this.service + = RestProxy.create(InventoriesService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for HybridConnectivityMgmtClientInventories to be used by the proxy + * service to perform REST calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "HybridConnectivityMg") + public interface InventoriesService { + @Headers({ "Content-Type: application/json" }) + @Get("/{resourceUri}/providers/Microsoft.HybridConnectivity/solutionConfigurations/{solutionConfiguration}/inventory/{inventoryId}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, + @PathParam(value = "resourceUri", encoded = true) String resourceUri, + @PathParam("solutionConfiguration") String solutionConfiguration, + @PathParam("inventoryId") String inventoryId, @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/{resourceUri}/providers/Microsoft.HybridConnectivity/solutionConfigurations/{solutionConfiguration}/inventory") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listBySolutionConfiguration(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, + @PathParam(value = "resourceUri", encoded = true) String resourceUri, + @PathParam("solutionConfiguration") String solutionConfiguration, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listBySolutionConfigurationNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * Get a InventoryResource. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param inventoryId Inventory resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a InventoryResource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceUri, + String solutionConfiguration, String inventoryId) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceUri == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null.")); + } + if (solutionConfiguration == null) { + return Mono + .error(new IllegalArgumentException("Parameter solutionConfiguration is required and cannot be null.")); + } + if (inventoryId == null) { + return Mono.error(new IllegalArgumentException("Parameter inventoryId is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), resourceUri, + solutionConfiguration, inventoryId, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a InventoryResource. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param inventoryId Inventory resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a InventoryResource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceUri, + String solutionConfiguration, String inventoryId, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceUri == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null.")); + } + if (solutionConfiguration == null) { + return Mono + .error(new IllegalArgumentException("Parameter solutionConfiguration is required and cannot be null.")); + } + if (inventoryId == null) { + return Mono.error(new IllegalArgumentException("Parameter inventoryId is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), resourceUri, solutionConfiguration, + inventoryId, accept, context); + } + + /** + * Get a InventoryResource. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param inventoryId Inventory resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a InventoryResource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceUri, String solutionConfiguration, + String inventoryId) { + return getWithResponseAsync(resourceUri, solutionConfiguration, inventoryId) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a InventoryResource. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param inventoryId Inventory resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a InventoryResource along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceUri, String solutionConfiguration, + String inventoryId, Context context) { + return getWithResponseAsync(resourceUri, solutionConfiguration, inventoryId, context).block(); + } + + /** + * Get a InventoryResource. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param inventoryId Inventory resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a InventoryResource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public InventoryResourceInner get(String resourceUri, String solutionConfiguration, String inventoryId) { + return getWithResponse(resourceUri, solutionConfiguration, inventoryId, Context.NONE).getValue(); + } + + /** + * List InventoryResource resources by SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a InventoryResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySolutionConfigurationSinglePageAsync(String resourceUri, + String solutionConfiguration) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceUri == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null.")); + } + if (solutionConfiguration == null) { + return Mono + .error(new IllegalArgumentException("Parameter solutionConfiguration is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listBySolutionConfiguration(this.client.getEndpoint(), + this.client.getApiVersion(), resourceUri, solutionConfiguration, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List InventoryResource resources by SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a InventoryResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySolutionConfigurationSinglePageAsync(String resourceUri, + String solutionConfiguration, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceUri == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null.")); + } + if (solutionConfiguration == null) { + return Mono + .error(new IllegalArgumentException("Parameter solutionConfiguration is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listBySolutionConfiguration(this.client.getEndpoint(), this.client.getApiVersion(), resourceUri, + solutionConfiguration, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List InventoryResource resources by SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a InventoryResource list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listBySolutionConfigurationAsync(String resourceUri, + String solutionConfiguration) { + return new PagedFlux<>(() -> listBySolutionConfigurationSinglePageAsync(resourceUri, solutionConfiguration), + nextLink -> listBySolutionConfigurationNextSinglePageAsync(nextLink)); + } + + /** + * List InventoryResource resources by SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a InventoryResource list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listBySolutionConfigurationAsync(String resourceUri, + String solutionConfiguration, Context context) { + return new PagedFlux<>( + () -> listBySolutionConfigurationSinglePageAsync(resourceUri, solutionConfiguration, context), + nextLink -> listBySolutionConfigurationNextSinglePageAsync(nextLink, context)); + } + + /** + * List InventoryResource resources by SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a InventoryResource list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listBySolutionConfiguration(String resourceUri, + String solutionConfiguration) { + return new PagedIterable<>(listBySolutionConfigurationAsync(resourceUri, solutionConfiguration)); + } + + /** + * List InventoryResource resources by SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a InventoryResource list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listBySolutionConfiguration(String resourceUri, + String solutionConfiguration, Context context) { + return new PagedIterable<>(listBySolutionConfigurationAsync(resourceUri, solutionConfiguration, context)); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a InventoryResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> + listBySolutionConfigurationNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil.withContext( + context -> service.listBySolutionConfigurationNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a InventoryResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySolutionConfigurationNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listBySolutionConfigurationNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/InventoriesImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/InventoriesImpl.java new file mode 100644 index 000000000000..908f29249791 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/InventoriesImpl.java @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.hybridconnectivity.fluent.InventoriesClient; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.InventoryResourceInner; +import com.azure.resourcemanager.hybridconnectivity.models.Inventories; +import com.azure.resourcemanager.hybridconnectivity.models.InventoryResource; + +public final class InventoriesImpl implements Inventories { + private static final ClientLogger LOGGER = new ClientLogger(InventoriesImpl.class); + + private final InventoriesClient innerClient; + + private final com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager serviceManager; + + public InventoriesImpl(InventoriesClient innerClient, + com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public Response getWithResponse(String resourceUri, String solutionConfiguration, + String inventoryId, Context context) { + Response inner + = this.serviceClient().getWithResponse(resourceUri, solutionConfiguration, inventoryId, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new InventoryResourceImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public InventoryResource get(String resourceUri, String solutionConfiguration, String inventoryId) { + InventoryResourceInner inner = this.serviceClient().get(resourceUri, solutionConfiguration, inventoryId); + if (inner != null) { + return new InventoryResourceImpl(inner, this.manager()); + } else { + return null; + } + } + + public PagedIterable listBySolutionConfiguration(String resourceUri, + String solutionConfiguration) { + PagedIterable inner + = this.serviceClient().listBySolutionConfiguration(resourceUri, solutionConfiguration); + return ResourceManagerUtils.mapPage(inner, inner1 -> new InventoryResourceImpl(inner1, this.manager())); + } + + public PagedIterable listBySolutionConfiguration(String resourceUri, + String solutionConfiguration, Context context) { + PagedIterable inner + = this.serviceClient().listBySolutionConfiguration(resourceUri, solutionConfiguration, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new InventoryResourceImpl(inner1, this.manager())); + } + + private InventoriesClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/InventoryResourceImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/InventoryResourceImpl.java new file mode 100644 index 000000000000..e99a742182c6 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/InventoryResourceImpl.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.implementation; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.InventoryResourceInner; +import com.azure.resourcemanager.hybridconnectivity.models.InventoryProperties; +import com.azure.resourcemanager.hybridconnectivity.models.InventoryResource; + +public final class InventoryResourceImpl implements InventoryResource { + private InventoryResourceInner innerObject; + + private final com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager serviceManager; + + InventoryResourceImpl(InventoryResourceInner innerObject, + com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public InventoryProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public InventoryResourceInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/ManagedProxyResourceImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/ManagedProxyResourceImpl.java index 45fea8c5ee05..996553a32722 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/ManagedProxyResourceImpl.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/ManagedProxyResourceImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.implementation; diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/OperationImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/OperationImpl.java index 4635bf6f3a48..7636a86955a1 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/OperationImpl.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/OperationImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.implementation; diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/OperationStatusResultImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/OperationStatusResultImpl.java new file mode 100644 index 000000000000..2e428236e92c --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/OperationStatusResultImpl.java @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.implementation; + +import com.azure.core.management.exception.ManagementError; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.OperationStatusResultInner; +import com.azure.resourcemanager.hybridconnectivity.models.OperationStatusResult; +import java.time.OffsetDateTime; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +public final class OperationStatusResultImpl implements OperationStatusResult { + private OperationStatusResultInner innerObject; + + private final com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager serviceManager; + + OperationStatusResultImpl(OperationStatusResultInner innerObject, + com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String status() { + return this.innerModel().status(); + } + + public Double percentComplete() { + return this.innerModel().percentComplete(); + } + + public OffsetDateTime startTime() { + return this.innerModel().startTime(); + } + + public OffsetDateTime endTime() { + return this.innerModel().endTime(); + } + + public List operations() { + List inner = this.innerModel().operations(); + if (inner != null) { + return Collections.unmodifiableList(inner.stream() + .map(inner1 -> new OperationStatusResultImpl(inner1, this.manager())) + .collect(Collectors.toList())); + } else { + return Collections.emptyList(); + } + } + + public ManagementError error() { + return this.innerModel().error(); + } + + public String resourceId() { + return this.innerModel().resourceId(); + } + + public OperationStatusResultInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/OperationsClientImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/OperationsClientImpl.java index 2db698ca13c8..0a550f841e6f 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/OperationsClientImpl.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/OperationsClientImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.implementation; @@ -27,7 +27,7 @@ import com.azure.core.util.FluxUtil; import com.azure.resourcemanager.hybridconnectivity.fluent.OperationsClient; import com.azure.resourcemanager.hybridconnectivity.fluent.models.OperationInner; -import com.azure.resourcemanager.hybridconnectivity.models.OperationListResult; +import com.azure.resourcemanager.hybridconnectivity.implementation.models.OperationListResult; import reactor.core.publisher.Mono; /** @@ -42,31 +42,31 @@ public final class OperationsClientImpl implements OperationsClient { /** * The service client containing this operation class. */ - private final HybridConnectivityManagementApiImpl client; + private final HybridConnectivityMgmtClientImpl client; /** * Initializes an instance of OperationsClientImpl. * * @param client the instance of the service client containing this operation class. */ - OperationsClientImpl(HybridConnectivityManagementApiImpl client) { + OperationsClientImpl(HybridConnectivityMgmtClientImpl client) { this.service = RestProxy.create(OperationsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); this.client = client; } /** - * The interface defining all the services for HybridConnectivityManagementApiOperations to be used by the proxy + * The interface defining all the services for HybridConnectivityMgmtClientOperations to be used by the proxy * service to perform REST calls. */ - @Host("{$host}") - @ServiceInterface(name = "HybridConnectivityMa") + @Host("{endpoint}") + @ServiceInterface(name = "HybridConnectivityMg") public interface OperationsService { @Headers({ "Content-Type: application/json" }) @Get("/providers/Microsoft.HybridConnectivity/operations") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono> list(@HostParam("$host") String endpoint, + Mono> list(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); @Headers({ "Content-Type: application/json" }) @@ -74,11 +74,11 @@ Mono> list(@HostParam("$host") String endpoint, @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) Mono> listNext(@PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("$host") String endpoint, @HeaderParam("Accept") String accept, Context context); + @HostParam("endpoint") String endpoint, @HeaderParam("Accept") String accept, Context context); } /** - * Lists the available Hybrid Connectivity REST API operations. + * List the operations for the provider. * * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -101,7 +101,7 @@ private Mono> listSinglePageAsync() { } /** - * Lists the available Hybrid Connectivity REST API operations. + * List the operations for the provider. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -124,7 +124,7 @@ private Mono> listSinglePageAsync(Context context) } /** - * Lists the available Hybrid Connectivity REST API operations. + * List the operations for the provider. * * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -137,7 +137,7 @@ private PagedFlux listAsync() { } /** - * Lists the available Hybrid Connectivity REST API operations. + * List the operations for the provider. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -153,7 +153,7 @@ private PagedFlux listAsync(Context context) { } /** - * Lists the available Hybrid Connectivity REST API operations. + * List the operations for the provider. * * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -166,7 +166,7 @@ public PagedIterable list() { } /** - * Lists the available Hybrid Connectivity REST API operations. + * List the operations for the provider. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/OperationsImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/OperationsImpl.java index 0f09d81cd1e4..c82b2f9fa90d 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/OperationsImpl.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/OperationsImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.implementation; diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/PostResponseImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/PostResponseImpl.java new file mode 100644 index 000000000000..73f74d0ef7e6 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/PostResponseImpl.java @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.implementation; + +import com.azure.resourcemanager.hybridconnectivity.fluent.models.PostResponseInner; +import com.azure.resourcemanager.hybridconnectivity.models.PostResponse; + +public final class PostResponseImpl implements PostResponse { + private PostResponseInner innerObject; + + private final com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager serviceManager; + + PostResponseImpl(PostResponseInner innerObject, + com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public PostResponseInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/PublicCloudConnectorImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/PublicCloudConnectorImpl.java new file mode 100644 index 000000000000..60d2a6047738 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/PublicCloudConnectorImpl.java @@ -0,0 +1,178 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.implementation; + +import com.azure.core.management.Region; +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.PublicCloudConnectorInner; +import com.azure.resourcemanager.hybridconnectivity.models.OperationStatusResult; +import com.azure.resourcemanager.hybridconnectivity.models.PublicCloudConnector; +import com.azure.resourcemanager.hybridconnectivity.models.PublicCloudConnectorProperties; +import java.util.Collections; +import java.util.Map; + +public final class PublicCloudConnectorImpl + implements PublicCloudConnector, PublicCloudConnector.Definition, PublicCloudConnector.Update { + private PublicCloudConnectorInner innerObject; + + private final com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager serviceManager; + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public String location() { + return this.innerModel().location(); + } + + public Map tags() { + Map inner = this.innerModel().tags(); + if (inner != null) { + return Collections.unmodifiableMap(inner); + } else { + return Collections.emptyMap(); + } + } + + public PublicCloudConnectorProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public Region region() { + return Region.fromName(this.regionName()); + } + + public String regionName() { + return this.location(); + } + + public String resourceGroupName() { + return resourceGroupName; + } + + public PublicCloudConnectorInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager() { + return this.serviceManager; + } + + private String resourceGroupName; + + private String publicCloudConnector; + + public PublicCloudConnectorImpl withExistingResourceGroup(String resourceGroupName) { + this.resourceGroupName = resourceGroupName; + return this; + } + + public PublicCloudConnector create() { + this.innerObject = serviceManager.serviceClient() + .getPublicCloudConnectors() + .createOrUpdate(resourceGroupName, publicCloudConnector, this.innerModel(), Context.NONE); + return this; + } + + public PublicCloudConnector create(Context context) { + this.innerObject = serviceManager.serviceClient() + .getPublicCloudConnectors() + .createOrUpdate(resourceGroupName, publicCloudConnector, this.innerModel(), context); + return this; + } + + PublicCloudConnectorImpl(String name, + com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager serviceManager) { + this.innerObject = new PublicCloudConnectorInner(); + this.serviceManager = serviceManager; + this.publicCloudConnector = name; + } + + public PublicCloudConnectorImpl update() { + return this; + } + + public PublicCloudConnector apply() { + this.innerObject = serviceManager.serviceClient() + .getPublicCloudConnectors() + .updateWithResponse(resourceGroupName, publicCloudConnector, this.innerModel(), Context.NONE) + .getValue(); + return this; + } + + public PublicCloudConnector apply(Context context) { + this.innerObject = serviceManager.serviceClient() + .getPublicCloudConnectors() + .updateWithResponse(resourceGroupName, publicCloudConnector, this.innerModel(), context) + .getValue(); + return this; + } + + PublicCloudConnectorImpl(PublicCloudConnectorInner innerObject, + com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + this.resourceGroupName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "resourceGroups"); + this.publicCloudConnector + = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "publicCloudConnectors"); + } + + public PublicCloudConnector refresh() { + this.innerObject = serviceManager.serviceClient() + .getPublicCloudConnectors() + .getByResourceGroupWithResponse(resourceGroupName, publicCloudConnector, Context.NONE) + .getValue(); + return this; + } + + public PublicCloudConnector refresh(Context context) { + this.innerObject = serviceManager.serviceClient() + .getPublicCloudConnectors() + .getByResourceGroupWithResponse(resourceGroupName, publicCloudConnector, context) + .getValue(); + return this; + } + + public OperationStatusResult testPermissions() { + return serviceManager.publicCloudConnectors().testPermissions(resourceGroupName, publicCloudConnector); + } + + public OperationStatusResult testPermissions(Context context) { + return serviceManager.publicCloudConnectors().testPermissions(resourceGroupName, publicCloudConnector, context); + } + + public PublicCloudConnectorImpl withRegion(Region location) { + this.innerModel().withLocation(location.toString()); + return this; + } + + public PublicCloudConnectorImpl withRegion(String location) { + this.innerModel().withLocation(location); + return this; + } + + public PublicCloudConnectorImpl withTags(Map tags) { + this.innerModel().withTags(tags); + return this; + } + + public PublicCloudConnectorImpl withProperties(PublicCloudConnectorProperties properties) { + this.innerModel().withProperties(properties); + return this; + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/PublicCloudConnectorsClientImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/PublicCloudConnectorsClientImpl.java new file mode 100644 index 000000000000..ab25daa14f06 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/PublicCloudConnectorsClientImpl.java @@ -0,0 +1,1339 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.Patch; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Post; +import com.azure.core.annotation.Put; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.core.util.polling.PollerFlux; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.hybridconnectivity.fluent.PublicCloudConnectorsClient; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.OperationStatusResultInner; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.PublicCloudConnectorInner; +import com.azure.resourcemanager.hybridconnectivity.implementation.models.PublicCloudConnectorListResult; +import java.nio.ByteBuffer; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in PublicCloudConnectorsClient. + */ +public final class PublicCloudConnectorsClientImpl implements PublicCloudConnectorsClient { + /** + * The proxy service used to perform REST calls. + */ + private final PublicCloudConnectorsService service; + + /** + * The service client containing this operation class. + */ + private final HybridConnectivityMgmtClientImpl client; + + /** + * Initializes an instance of PublicCloudConnectorsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + PublicCloudConnectorsClientImpl(HybridConnectivityMgmtClientImpl client) { + this.service = RestProxy.create(PublicCloudConnectorsService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for HybridConnectivityMgmtClientPublicCloudConnectors to be used by the + * proxy service to perform REST calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "HybridConnectivityMg") + public interface PublicCloudConnectorsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HybridConnectivity/publicCloudConnectors/{publicCloudConnector}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> getByResourceGroup(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, + @PathParam("publicCloudConnector") String publicCloudConnector, @HeaderParam("Accept") String accept, + Context context); + + @Put("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HybridConnectivity/publicCloudConnectors/{publicCloudConnector}") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> createOrUpdate(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, + @PathParam("publicCloudConnector") String publicCloudConnector, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") PublicCloudConnectorInner resource, Context context); + + @Patch("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HybridConnectivity/publicCloudConnectors/{publicCloudConnector}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> update(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, + @PathParam("publicCloudConnector") String publicCloudConnector, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") PublicCloudConnectorInner properties, Context context); + + @Headers({ "Content-Type: application/json" }) + @Delete("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HybridConnectivity/publicCloudConnectors/{publicCloudConnector}") + @ExpectedResponses({ 200, 204 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> delete(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, + @PathParam("publicCloudConnector") String publicCloudConnector, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HybridConnectivity/publicCloudConnectors") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByResourceGroup(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/providers/Microsoft.HybridConnectivity/publicCloudConnectors") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> list(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Post("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HybridConnectivity/publicCloudConnectors/{publicCloudConnector}/testPermissions") + @ExpectedResponses({ 200, 202 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> testPermissions(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, + @PathParam("publicCloudConnector") String publicCloudConnector, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByResourceGroupNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listBySubscriptionNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * Get a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a PublicCloudConnector along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getByResourceGroupWithResponseAsync(String resourceGroupName, + String publicCloudConnector) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (publicCloudConnector == null) { + return Mono + .error(new IllegalArgumentException("Parameter publicCloudConnector is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.getByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, publicCloudConnector, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a PublicCloudConnector along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getByResourceGroupWithResponseAsync(String resourceGroupName, + String publicCloudConnector, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (publicCloudConnector == null) { + return Mono + .error(new IllegalArgumentException("Parameter publicCloudConnector is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.getByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, publicCloudConnector, accept, context); + } + + /** + * Get a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a PublicCloudConnector on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getByResourceGroupAsync(String resourceGroupName, + String publicCloudConnector) { + return getByResourceGroupWithResponseAsync(resourceGroupName, publicCloudConnector) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a PublicCloudConnector along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getByResourceGroupWithResponse(String resourceGroupName, + String publicCloudConnector, Context context) { + return getByResourceGroupWithResponseAsync(resourceGroupName, publicCloudConnector, context).block(); + } + + /** + * Get a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a PublicCloudConnector. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public PublicCloudConnectorInner getByResourceGroup(String resourceGroupName, String publicCloudConnector) { + return getByResourceGroupWithResponse(resourceGroupName, publicCloudConnector, Context.NONE).getValue(); + } + + /** + * Create a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return public Cloud Connector along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createOrUpdateWithResponseAsync(String resourceGroupName, + String publicCloudConnector, PublicCloudConnectorInner resource) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (publicCloudConnector == null) { + return Mono + .error(new IllegalArgumentException("Parameter publicCloudConnector is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.createOrUpdate(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, publicCloudConnector, contentType, accept, resource, + context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Create a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return public Cloud Connector along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createOrUpdateWithResponseAsync(String resourceGroupName, + String publicCloudConnector, PublicCloudConnectorInner resource, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (publicCloudConnector == null) { + return Mono + .error(new IllegalArgumentException("Parameter publicCloudConnector is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.createOrUpdate(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, publicCloudConnector, contentType, accept, resource, + context); + } + + /** + * Create a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of public Cloud Connector. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, PublicCloudConnectorInner> beginCreateOrUpdateAsync( + String resourceGroupName, String publicCloudConnector, PublicCloudConnectorInner resource) { + Mono>> mono + = createOrUpdateWithResponseAsync(resourceGroupName, publicCloudConnector, resource); + return this.client.getLroResult(mono, + this.client.getHttpPipeline(), PublicCloudConnectorInner.class, PublicCloudConnectorInner.class, + this.client.getContext()); + } + + /** + * Create a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of public Cloud Connector. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, PublicCloudConnectorInner> beginCreateOrUpdateAsync( + String resourceGroupName, String publicCloudConnector, PublicCloudConnectorInner resource, Context context) { + context = this.client.mergeContext(context); + Mono>> mono + = createOrUpdateWithResponseAsync(resourceGroupName, publicCloudConnector, resource, context); + return this.client.getLroResult(mono, + this.client.getHttpPipeline(), PublicCloudConnectorInner.class, PublicCloudConnectorInner.class, context); + } + + /** + * Create a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of public Cloud Connector. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, PublicCloudConnectorInner> + beginCreateOrUpdate(String resourceGroupName, String publicCloudConnector, PublicCloudConnectorInner resource) { + return this.beginCreateOrUpdateAsync(resourceGroupName, publicCloudConnector, resource).getSyncPoller(); + } + + /** + * Create a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of public Cloud Connector. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, PublicCloudConnectorInner> beginCreateOrUpdate( + String resourceGroupName, String publicCloudConnector, PublicCloudConnectorInner resource, Context context) { + return this.beginCreateOrUpdateAsync(resourceGroupName, publicCloudConnector, resource, context) + .getSyncPoller(); + } + + /** + * Create a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return public Cloud Connector on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createOrUpdateAsync(String resourceGroupName, String publicCloudConnector, + PublicCloudConnectorInner resource) { + return beginCreateOrUpdateAsync(resourceGroupName, publicCloudConnector, resource).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return public Cloud Connector on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createOrUpdateAsync(String resourceGroupName, String publicCloudConnector, + PublicCloudConnectorInner resource, Context context) { + return beginCreateOrUpdateAsync(resourceGroupName, publicCloudConnector, resource, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return public Cloud Connector. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public PublicCloudConnectorInner createOrUpdate(String resourceGroupName, String publicCloudConnector, + PublicCloudConnectorInner resource) { + return createOrUpdateAsync(resourceGroupName, publicCloudConnector, resource).block(); + } + + /** + * Create a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return public Cloud Connector. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public PublicCloudConnectorInner createOrUpdate(String resourceGroupName, String publicCloudConnector, + PublicCloudConnectorInner resource, Context context) { + return createOrUpdateAsync(resourceGroupName, publicCloudConnector, resource, context).block(); + } + + /** + * Update a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return public Cloud Connector along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> updateWithResponseAsync(String resourceGroupName, + String publicCloudConnector, PublicCloudConnectorInner properties) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (publicCloudConnector == null) { + return Mono + .error(new IllegalArgumentException("Parameter publicCloudConnector is required and cannot be null.")); + } + if (properties == null) { + return Mono.error(new IllegalArgumentException("Parameter properties is required and cannot be null.")); + } else { + properties.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.update(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, publicCloudConnector, contentType, accept, + properties, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Update a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param properties The resource properties to be updated. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return public Cloud Connector along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> updateWithResponseAsync(String resourceGroupName, + String publicCloudConnector, PublicCloudConnectorInner properties, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (publicCloudConnector == null) { + return Mono + .error(new IllegalArgumentException("Parameter publicCloudConnector is required and cannot be null.")); + } + if (properties == null) { + return Mono.error(new IllegalArgumentException("Parameter properties is required and cannot be null.")); + } else { + properties.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.update(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, publicCloudConnector, contentType, accept, properties, context); + } + + /** + * Update a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return public Cloud Connector on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono updateAsync(String resourceGroupName, String publicCloudConnector, + PublicCloudConnectorInner properties) { + return updateWithResponseAsync(resourceGroupName, publicCloudConnector, properties) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Update a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param properties The resource properties to be updated. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return public Cloud Connector along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response updateWithResponse(String resourceGroupName, String publicCloudConnector, + PublicCloudConnectorInner properties, Context context) { + return updateWithResponseAsync(resourceGroupName, publicCloudConnector, properties, context).block(); + } + + /** + * Update a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return public Cloud Connector. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public PublicCloudConnectorInner update(String resourceGroupName, String publicCloudConnector, + PublicCloudConnectorInner properties) { + return updateWithResponse(resourceGroupName, publicCloudConnector, properties, Context.NONE).getValue(); + } + + /** + * Delete a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String publicCloudConnector) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (publicCloudConnector == null) { + return Mono + .error(new IllegalArgumentException("Parameter publicCloudConnector is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.delete(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, publicCloudConnector, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Delete a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String publicCloudConnector, + Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (publicCloudConnector == null) { + return Mono + .error(new IllegalArgumentException("Parameter publicCloudConnector is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.delete(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, publicCloudConnector, accept, context); + } + + /** + * Delete a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono deleteAsync(String resourceGroupName, String publicCloudConnector) { + return deleteWithResponseAsync(resourceGroupName, publicCloudConnector).flatMap(ignored -> Mono.empty()); + } + + /** + * Delete a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String resourceGroupName, String publicCloudConnector, Context context) { + return deleteWithResponseAsync(resourceGroupName, publicCloudConnector, context).block(); + } + + /** + * Delete a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String resourceGroupName, String publicCloudConnector) { + deleteWithResponse(resourceGroupName, publicCloudConnector, Context.NONE); + } + + /** + * List PublicCloudConnector resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PublicCloudConnector list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> + listByResourceGroupSinglePageAsync(String resourceGroupName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List PublicCloudConnector resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PublicCloudConnector list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByResourceGroupSinglePageAsync(String resourceGroupName, + Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List PublicCloudConnector resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PublicCloudConnector list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByResourceGroupAsync(String resourceGroupName) { + return new PagedFlux<>(() -> listByResourceGroupSinglePageAsync(resourceGroupName), + nextLink -> listByResourceGroupNextSinglePageAsync(nextLink)); + } + + /** + * List PublicCloudConnector resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PublicCloudConnector list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByResourceGroupAsync(String resourceGroupName, Context context) { + return new PagedFlux<>(() -> listByResourceGroupSinglePageAsync(resourceGroupName, context), + nextLink -> listByResourceGroupNextSinglePageAsync(nextLink, context)); + } + + /** + * List PublicCloudConnector resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PublicCloudConnector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByResourceGroup(String resourceGroupName) { + return new PagedIterable<>(listByResourceGroupAsync(resourceGroupName)); + } + + /** + * List PublicCloudConnector resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PublicCloudConnector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByResourceGroup(String resourceGroupName, Context context) { + return new PagedIterable<>(listByResourceGroupAsync(resourceGroupName, context)); + } + + /** + * List PublicCloudConnector resources by subscription ID. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PublicCloudConnector list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync() { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.list(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List PublicCloudConnector resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PublicCloudConnector list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync(Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .list(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), accept, + context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List PublicCloudConnector resources by subscription ID. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PublicCloudConnector list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync() { + return new PagedFlux<>(() -> listSinglePageAsync(), + nextLink -> listBySubscriptionNextSinglePageAsync(nextLink)); + } + + /** + * List PublicCloudConnector resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PublicCloudConnector list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync(Context context) { + return new PagedFlux<>(() -> listSinglePageAsync(context), + nextLink -> listBySubscriptionNextSinglePageAsync(nextLink, context)); + } + + /** + * List PublicCloudConnector resources by subscription ID. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PublicCloudConnector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list() { + return new PagedIterable<>(listAsync()); + } + + /** + * List PublicCloudConnector resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PublicCloudConnector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(Context context) { + return new PagedIterable<>(listAsync(context)); + } + + /** + * A long-running resource action. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> testPermissionsWithResponseAsync(String resourceGroupName, + String publicCloudConnector) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (publicCloudConnector == null) { + return Mono + .error(new IllegalArgumentException("Parameter publicCloudConnector is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.testPermissions(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, publicCloudConnector, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * A long-running resource action. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> testPermissionsWithResponseAsync(String resourceGroupName, + String publicCloudConnector, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (publicCloudConnector == null) { + return Mono + .error(new IllegalArgumentException("Parameter publicCloudConnector is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.testPermissions(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, publicCloudConnector, accept, context); + } + + /** + * A long-running resource action. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, OperationStatusResultInner> + beginTestPermissionsAsync(String resourceGroupName, String publicCloudConnector) { + Mono>> mono + = testPermissionsWithResponseAsync(resourceGroupName, publicCloudConnector); + return this.client.getLroResult(mono, + this.client.getHttpPipeline(), OperationStatusResultInner.class, OperationStatusResultInner.class, + this.client.getContext()); + } + + /** + * A long-running resource action. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, OperationStatusResultInner> + beginTestPermissionsAsync(String resourceGroupName, String publicCloudConnector, Context context) { + context = this.client.mergeContext(context); + Mono>> mono + = testPermissionsWithResponseAsync(resourceGroupName, publicCloudConnector, context); + return this.client.getLroResult(mono, + this.client.getHttpPipeline(), OperationStatusResultInner.class, OperationStatusResultInner.class, context); + } + + /** + * A long-running resource action. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, OperationStatusResultInner> + beginTestPermissions(String resourceGroupName, String publicCloudConnector) { + return this.beginTestPermissionsAsync(resourceGroupName, publicCloudConnector).getSyncPoller(); + } + + /** + * A long-running resource action. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, OperationStatusResultInner> + beginTestPermissions(String resourceGroupName, String publicCloudConnector, Context context) { + return this.beginTestPermissionsAsync(resourceGroupName, publicCloudConnector, context).getSyncPoller(); + } + + /** + * A long-running resource action. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono testPermissionsAsync(String resourceGroupName, + String publicCloudConnector) { + return beginTestPermissionsAsync(resourceGroupName, publicCloudConnector).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * A long-running resource action. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono testPermissionsAsync(String resourceGroupName, String publicCloudConnector, + Context context) { + return beginTestPermissionsAsync(resourceGroupName, publicCloudConnector, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * A long-running resource action. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public OperationStatusResultInner testPermissions(String resourceGroupName, String publicCloudConnector) { + return testPermissionsAsync(resourceGroupName, publicCloudConnector).block(); + } + + /** + * A long-running resource action. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public OperationStatusResultInner testPermissions(String resourceGroupName, String publicCloudConnector, + Context context) { + return testPermissionsAsync(resourceGroupName, publicCloudConnector, context).block(); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PublicCloudConnector list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByResourceGroupNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByResourceGroupNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PublicCloudConnector list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByResourceGroupNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listByResourceGroupNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PublicCloudConnector list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySubscriptionNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PublicCloudConnector list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySubscriptionNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/PublicCloudConnectorsImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/PublicCloudConnectorsImpl.java new file mode 100644 index 000000000000..56c6db377b23 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/PublicCloudConnectorsImpl.java @@ -0,0 +1,172 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.hybridconnectivity.fluent.PublicCloudConnectorsClient; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.OperationStatusResultInner; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.PublicCloudConnectorInner; +import com.azure.resourcemanager.hybridconnectivity.models.OperationStatusResult; +import com.azure.resourcemanager.hybridconnectivity.models.PublicCloudConnector; +import com.azure.resourcemanager.hybridconnectivity.models.PublicCloudConnectors; + +public final class PublicCloudConnectorsImpl implements PublicCloudConnectors { + private static final ClientLogger LOGGER = new ClientLogger(PublicCloudConnectorsImpl.class); + + private final PublicCloudConnectorsClient innerClient; + + private final com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager serviceManager; + + public PublicCloudConnectorsImpl(PublicCloudConnectorsClient innerClient, + com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public Response getByResourceGroupWithResponse(String resourceGroupName, + String publicCloudConnector, Context context) { + Response inner + = this.serviceClient().getByResourceGroupWithResponse(resourceGroupName, publicCloudConnector, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new PublicCloudConnectorImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public PublicCloudConnector getByResourceGroup(String resourceGroupName, String publicCloudConnector) { + PublicCloudConnectorInner inner + = this.serviceClient().getByResourceGroup(resourceGroupName, publicCloudConnector); + if (inner != null) { + return new PublicCloudConnectorImpl(inner, this.manager()); + } else { + return null; + } + } + + public Response deleteByResourceGroupWithResponse(String resourceGroupName, String publicCloudConnector, + Context context) { + return this.serviceClient().deleteWithResponse(resourceGroupName, publicCloudConnector, context); + } + + public void deleteByResourceGroup(String resourceGroupName, String publicCloudConnector) { + this.serviceClient().delete(resourceGroupName, publicCloudConnector); + } + + public PagedIterable listByResourceGroup(String resourceGroupName) { + PagedIterable inner = this.serviceClient().listByResourceGroup(resourceGroupName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new PublicCloudConnectorImpl(inner1, this.manager())); + } + + public PagedIterable listByResourceGroup(String resourceGroupName, Context context) { + PagedIterable inner + = this.serviceClient().listByResourceGroup(resourceGroupName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new PublicCloudConnectorImpl(inner1, this.manager())); + } + + public PagedIterable list() { + PagedIterable inner = this.serviceClient().list(); + return ResourceManagerUtils.mapPage(inner, inner1 -> new PublicCloudConnectorImpl(inner1, this.manager())); + } + + public PagedIterable list(Context context) { + PagedIterable inner = this.serviceClient().list(context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new PublicCloudConnectorImpl(inner1, this.manager())); + } + + public OperationStatusResult testPermissions(String resourceGroupName, String publicCloudConnector) { + OperationStatusResultInner inner + = this.serviceClient().testPermissions(resourceGroupName, publicCloudConnector); + if (inner != null) { + return new OperationStatusResultImpl(inner, this.manager()); + } else { + return null; + } + } + + public OperationStatusResult testPermissions(String resourceGroupName, String publicCloudConnector, + Context context) { + OperationStatusResultInner inner + = this.serviceClient().testPermissions(resourceGroupName, publicCloudConnector, context); + if (inner != null) { + return new OperationStatusResultImpl(inner, this.manager()); + } else { + return null; + } + } + + public PublicCloudConnector getById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String publicCloudConnector = ResourceManagerUtils.getValueFromIdByName(id, "publicCloudConnectors"); + if (publicCloudConnector == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'publicCloudConnectors'.", id))); + } + return this.getByResourceGroupWithResponse(resourceGroupName, publicCloudConnector, Context.NONE).getValue(); + } + + public Response getByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String publicCloudConnector = ResourceManagerUtils.getValueFromIdByName(id, "publicCloudConnectors"); + if (publicCloudConnector == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'publicCloudConnectors'.", id))); + } + return this.getByResourceGroupWithResponse(resourceGroupName, publicCloudConnector, context); + } + + public void deleteById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String publicCloudConnector = ResourceManagerUtils.getValueFromIdByName(id, "publicCloudConnectors"); + if (publicCloudConnector == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'publicCloudConnectors'.", id))); + } + this.deleteByResourceGroupWithResponse(resourceGroupName, publicCloudConnector, Context.NONE); + } + + public Response deleteByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String publicCloudConnector = ResourceManagerUtils.getValueFromIdByName(id, "publicCloudConnectors"); + if (publicCloudConnector == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'publicCloudConnectors'.", id))); + } + return this.deleteByResourceGroupWithResponse(resourceGroupName, publicCloudConnector, context); + } + + private PublicCloudConnectorsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager() { + return this.serviceManager; + } + + public PublicCloudConnectorImpl define(String name) { + return new PublicCloudConnectorImpl(name, this.manager()); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/ResourceManagerUtils.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/ResourceManagerUtils.java index ec8ed0a60227..19f53f0117a2 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/ResourceManagerUtils.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/ResourceManagerUtils.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.implementation; diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/ServiceConfigurationResourceImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/ServiceConfigurationResourceImpl.java index 477c046eecdd..28e646a82a71 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/ServiceConfigurationResourceImpl.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/ServiceConfigurationResourceImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.implementation; diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/ServiceConfigurationsClientImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/ServiceConfigurationsClientImpl.java index 5f42301482e4..ef27fe36707c 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/ServiceConfigurationsClientImpl.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/ServiceConfigurationsClientImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.implementation; @@ -31,7 +31,7 @@ import com.azure.core.util.FluxUtil; import com.azure.resourcemanager.hybridconnectivity.fluent.ServiceConfigurationsClient; import com.azure.resourcemanager.hybridconnectivity.fluent.models.ServiceConfigurationResourceInner; -import com.azure.resourcemanager.hybridconnectivity.models.ServiceConfigurationList; +import com.azure.resourcemanager.hybridconnectivity.implementation.models.ServiceConfigurationList; import com.azure.resourcemanager.hybridconnectivity.models.ServiceConfigurationResourcePatch; import reactor.core.publisher.Mono; @@ -47,241 +47,95 @@ public final class ServiceConfigurationsClientImpl implements ServiceConfigurati /** * The service client containing this operation class. */ - private final HybridConnectivityManagementApiImpl client; + private final HybridConnectivityMgmtClientImpl client; /** * Initializes an instance of ServiceConfigurationsClientImpl. * * @param client the instance of the service client containing this operation class. */ - ServiceConfigurationsClientImpl(HybridConnectivityManagementApiImpl client) { + ServiceConfigurationsClientImpl(HybridConnectivityMgmtClientImpl client) { this.service = RestProxy.create(ServiceConfigurationsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); this.client = client; } /** - * The interface defining all the services for HybridConnectivityManagementApiServiceConfigurations to be used by - * the proxy service to perform REST calls. + * The interface defining all the services for HybridConnectivityMgmtClientServiceConfigurations to be used by the + * proxy service to perform REST calls. */ - @Host("{$host}") - @ServiceInterface(name = "HybridConnectivityMa") + @Host("{endpoint}") + @ServiceInterface(name = "HybridConnectivityMg") public interface ServiceConfigurationsService { - @Headers({ "Content-Type: application/json" }) - @Get("/{resourceUri}/providers/Microsoft.HybridConnectivity/endpoints/{endpointName}/serviceConfigurations") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> listByEndpointResource(@HostParam("$host") String endpoint, - @QueryParam("api-version") String apiVersion, - @PathParam(value = "resourceUri", encoded = true) String resourceUri, - @PathParam(value = "endpointName", encoded = true) String endpointName, - @HeaderParam("Accept") String accept, Context context); - @Headers({ "Content-Type: application/json" }) @Get("/{resourceUri}/providers/Microsoft.HybridConnectivity/endpoints/{endpointName}/serviceConfigurations/{serviceConfigurationName}") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono> get(@HostParam("$host") String endpoint, + Mono> get(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @PathParam(value = "resourceUri", encoded = true) String resourceUri, @PathParam(value = "endpointName", encoded = true) String endpointName, @PathParam(value = "serviceConfigurationName", encoded = true) String serviceConfigurationName, @HeaderParam("Accept") String accept, Context context); - @Headers({ "Content-Type: application/json" }) @Put("/{resourceUri}/providers/Microsoft.HybridConnectivity/endpoints/{endpointName}/serviceConfigurations/{serviceConfigurationName}") @ExpectedResponses({ 200, 201 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono> createOrupdate(@HostParam("$host") String endpoint, + Mono> createOrupdate(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @PathParam(value = "resourceUri", encoded = true) String resourceUri, @PathParam(value = "endpointName", encoded = true) String endpointName, @PathParam(value = "serviceConfigurationName", encoded = true) String serviceConfigurationName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, @BodyParam("application/json") ServiceConfigurationResourceInner serviceConfigurationResource, - @HeaderParam("Accept") String accept, Context context); + Context context); - @Headers({ "Content-Type: application/json" }) @Patch("/{resourceUri}/providers/Microsoft.HybridConnectivity/endpoints/{endpointName}/serviceConfigurations/{serviceConfigurationName}") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono> update(@HostParam("$host") String endpoint, + Mono> update(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @PathParam(value = "resourceUri", encoded = true) String resourceUri, @PathParam(value = "endpointName", encoded = true) String endpointName, @PathParam(value = "serviceConfigurationName", encoded = true) String serviceConfigurationName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, @BodyParam("application/json") ServiceConfigurationResourcePatch serviceConfigurationResource, - @HeaderParam("Accept") String accept, Context context); + Context context); @Headers({ "Content-Type: application/json" }) @Delete("/{resourceUri}/providers/Microsoft.HybridConnectivity/endpoints/{endpointName}/serviceConfigurations/{serviceConfigurationName}") @ExpectedResponses({ 200, 204 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono> delete(@HostParam("$host") String endpoint, @QueryParam("api-version") String apiVersion, + Mono> delete(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam(value = "resourceUri", encoded = true) String resourceUri, @PathParam(value = "endpointName", encoded = true) String endpointName, @PathParam(value = "serviceConfigurationName", encoded = true) String serviceConfigurationName, @HeaderParam("Accept") String accept, Context context); + @Headers({ "Content-Type: application/json" }) + @Get("/{resourceUri}/providers/Microsoft.HybridConnectivity/endpoints/{endpointName}/serviceConfigurations") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByEndpointResource(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, + @PathParam(value = "resourceUri", encoded = true) String resourceUri, + @PathParam(value = "endpointName", encoded = true) String endpointName, + @HeaderParam("Accept") String accept, Context context); + @Headers({ "Content-Type: application/json" }) @Get("{nextLink}") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) Mono> listByEndpointResourceNext( - @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, @HeaderParam("Accept") String accept, Context context); } - /** - * Lists of all the services associated with endpoint resource. - * - * API to enumerate registered services in service configurations under a Endpoint Resource. - * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. - * @param endpointName The endpoint name. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the paginated list of serviceConfigurations along with {@link PagedResponse} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> - listByEndpointResourceSinglePageAsync(String resourceUri, String endpointName) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (resourceUri == null) { - return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null.")); - } - if (endpointName == null) { - return Mono.error(new IllegalArgumentException("Parameter endpointName is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.listByEndpointResource(this.client.getEndpoint(), - this.client.getApiVersion(), resourceUri, endpointName, accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), - res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Lists of all the services associated with endpoint resource. - * - * API to enumerate registered services in service configurations under a Endpoint Resource. - * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. - * @param endpointName The endpoint name. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the paginated list of serviceConfigurations along with {@link PagedResponse} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> - listByEndpointResourceSinglePageAsync(String resourceUri, String endpointName, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (resourceUri == null) { - return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null.")); - } - if (endpointName == null) { - return Mono.error(new IllegalArgumentException("Parameter endpointName is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service - .listByEndpointResource(this.client.getEndpoint(), this.client.getApiVersion(), resourceUri, endpointName, - accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } - - /** - * Lists of all the services associated with endpoint resource. - * - * API to enumerate registered services in service configurations under a Endpoint Resource. - * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. - * @param endpointName The endpoint name. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the paginated list of serviceConfigurations as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listByEndpointResourceAsync(String resourceUri, - String endpointName) { - return new PagedFlux<>(() -> listByEndpointResourceSinglePageAsync(resourceUri, endpointName), - nextLink -> listByEndpointResourceNextSinglePageAsync(nextLink)); - } - - /** - * Lists of all the services associated with endpoint resource. - * - * API to enumerate registered services in service configurations under a Endpoint Resource. - * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. - * @param endpointName The endpoint name. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the paginated list of serviceConfigurations as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listByEndpointResourceAsync(String resourceUri, - String endpointName, Context context) { - return new PagedFlux<>(() -> listByEndpointResourceSinglePageAsync(resourceUri, endpointName, context), - nextLink -> listByEndpointResourceNextSinglePageAsync(nextLink, context)); - } - - /** - * Lists of all the services associated with endpoint resource. - * - * API to enumerate registered services in service configurations under a Endpoint Resource. - * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. - * @param endpointName The endpoint name. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the paginated list of serviceConfigurations as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listByEndpointResource(String resourceUri, - String endpointName) { - return new PagedIterable<>(listByEndpointResourceAsync(resourceUri, endpointName)); - } - - /** - * Lists of all the services associated with endpoint resource. - * - * API to enumerate registered services in service configurations under a Endpoint Resource. - * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. - * @param endpointName The endpoint name. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the paginated list of serviceConfigurations as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listByEndpointResource(String resourceUri, - String endpointName, Context context) { - return new PagedIterable<>(listByEndpointResourceAsync(resourceUri, endpointName, context)); - } - /** * Gets the details about the service to the resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -317,7 +171,7 @@ private Mono> getWithResponseAsync(S /** * Gets the details about the service to the resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @param context The context to associate with this operation. @@ -353,7 +207,7 @@ private Mono> getWithResponseAsync(S /** * Gets the details about the service to the resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -371,7 +225,7 @@ private Mono getAsync(String resourceUri, Str /** * Gets the details about the service to the resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @param context The context to associate with this operation. @@ -389,7 +243,7 @@ public Response getWithResponse(String resour /** * Gets the details about the service to the resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -406,7 +260,7 @@ public ServiceConfigurationResourceInner get(String resourceUri, String endpoint /** * Create or update a service in serviceConfiguration for the endpoint resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @param serviceConfigurationResource Service details. @@ -440,17 +294,19 @@ private Mono> createOrupdateWithResp } else { serviceConfigurationResource.validate(); } + final String contentType = "application/json"; final String accept = "application/json"; return FluxUtil - .withContext(context -> service.createOrupdate(this.client.getEndpoint(), this.client.getApiVersion(), - resourceUri, endpointName, serviceConfigurationName, serviceConfigurationResource, accept, context)) + .withContext( + context -> service.createOrupdate(this.client.getEndpoint(), this.client.getApiVersion(), resourceUri, + endpointName, serviceConfigurationName, contentType, accept, serviceConfigurationResource, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Create or update a service in serviceConfiguration for the endpoint resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @param serviceConfigurationResource Service details. @@ -485,16 +341,17 @@ private Mono> createOrupdateWithResp } else { serviceConfigurationResource.validate(); } + final String contentType = "application/json"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.createOrupdate(this.client.getEndpoint(), this.client.getApiVersion(), resourceUri, endpointName, - serviceConfigurationName, serviceConfigurationResource, accept, context); + serviceConfigurationName, contentType, accept, serviceConfigurationResource, context); } /** * Create or update a service in serviceConfiguration for the endpoint resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @param serviceConfigurationResource Service details. @@ -514,7 +371,7 @@ private Mono createOrupdateAsync(String resou /** * Create or update a service in serviceConfiguration for the endpoint resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @param serviceConfigurationResource Service details. @@ -535,7 +392,7 @@ public Response createOrupdateWithResponse(St /** * Create or update a service in serviceConfiguration for the endpoint resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @param serviceConfigurationResource Service details. @@ -554,7 +411,7 @@ public ServiceConfigurationResourceInner createOrupdate(String resourceUri, Stri /** * Update the service details in the service configurations of the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @param serviceConfigurationResource Service details. @@ -588,17 +445,18 @@ private Mono> updateWithResponseAsyn } else { serviceConfigurationResource.validate(); } + final String contentType = "application/json"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.update(this.client.getEndpoint(), this.client.getApiVersion(), resourceUri, - endpointName, serviceConfigurationName, serviceConfigurationResource, accept, context)) + endpointName, serviceConfigurationName, contentType, accept, serviceConfigurationResource, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Update the service details in the service configurations of the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @param serviceConfigurationResource Service details. @@ -633,16 +491,17 @@ private Mono> updateWithResponseAsyn } else { serviceConfigurationResource.validate(); } + final String contentType = "application/json"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.update(this.client.getEndpoint(), this.client.getApiVersion(), resourceUri, endpointName, - serviceConfigurationName, serviceConfigurationResource, accept, context); + serviceConfigurationName, contentType, accept, serviceConfigurationResource, context); } /** * Update the service details in the service configurations of the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @param serviceConfigurationResource Service details. @@ -662,7 +521,7 @@ private Mono updateAsync(String resourceUri, /** * Update the service details in the service configurations of the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @param serviceConfigurationResource Service details. @@ -683,7 +542,7 @@ public Response updateWithResponse(String res /** * Update the service details in the service configurations of the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @param serviceConfigurationResource Service details. @@ -702,7 +561,7 @@ public ServiceConfigurationResourceInner update(String resourceUri, String endpo /** * Deletes the service details to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -737,7 +596,7 @@ private Mono> deleteWithResponseAsync(String resourceUri, String /** * Deletes the service details to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @param context The context to associate with this operation. @@ -772,7 +631,7 @@ private Mono> deleteWithResponseAsync(String resourceUri, String /** * Deletes the service details to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -789,7 +648,7 @@ private Mono deleteAsync(String resourceUri, String endpointName, String s /** * Deletes the service details to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @param context The context to associate with this operation. @@ -807,7 +666,7 @@ public Response deleteWithResponse(String resourceUri, String endpointName /** * Deletes the service details to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -820,6 +679,155 @@ public void delete(String resourceUri, String endpointName, String serviceConfig } /** + * Lists of all the services associated with endpoint resource. + * + * API to enumerate registered services in service configurations under a Endpoint Resource. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param endpointName The endpoint name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the paginated list of serviceConfigurations along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> + listByEndpointResourceSinglePageAsync(String resourceUri, String endpointName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceUri == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null.")); + } + if (endpointName == null) { + return Mono.error(new IllegalArgumentException("Parameter endpointName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listByEndpointResource(this.client.getEndpoint(), + this.client.getApiVersion(), resourceUri, endpointName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Lists of all the services associated with endpoint resource. + * + * API to enumerate registered services in service configurations under a Endpoint Resource. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param endpointName The endpoint name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the paginated list of serviceConfigurations along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> + listByEndpointResourceSinglePageAsync(String resourceUri, String endpointName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceUri == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null.")); + } + if (endpointName == null) { + return Mono.error(new IllegalArgumentException("Parameter endpointName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByEndpointResource(this.client.getEndpoint(), this.client.getApiVersion(), resourceUri, endpointName, + accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * Lists of all the services associated with endpoint resource. + * + * API to enumerate registered services in service configurations under a Endpoint Resource. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param endpointName The endpoint name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the paginated list of serviceConfigurations as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByEndpointResourceAsync(String resourceUri, + String endpointName) { + return new PagedFlux<>(() -> listByEndpointResourceSinglePageAsync(resourceUri, endpointName), + nextLink -> listByEndpointResourceNextSinglePageAsync(nextLink)); + } + + /** + * Lists of all the services associated with endpoint resource. + * + * API to enumerate registered services in service configurations under a Endpoint Resource. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param endpointName The endpoint name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the paginated list of serviceConfigurations as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByEndpointResourceAsync(String resourceUri, + String endpointName, Context context) { + return new PagedFlux<>(() -> listByEndpointResourceSinglePageAsync(resourceUri, endpointName, context), + nextLink -> listByEndpointResourceNextSinglePageAsync(nextLink, context)); + } + + /** + * Lists of all the services associated with endpoint resource. + * + * API to enumerate registered services in service configurations under a Endpoint Resource. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param endpointName The endpoint name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the paginated list of serviceConfigurations as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByEndpointResource(String resourceUri, + String endpointName) { + return new PagedIterable<>(listByEndpointResourceAsync(resourceUri, endpointName)); + } + + /** + * Lists of all the services associated with endpoint resource. + * + * API to enumerate registered services in service configurations under a Endpoint Resource. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param endpointName The endpoint name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the paginated list of serviceConfigurations as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByEndpointResource(String resourceUri, + String endpointName, Context context) { + return new PagedIterable<>(listByEndpointResourceAsync(resourceUri, endpointName, context)); + } + + /** + * Lists of all the services associated with endpoint resource. + * * Get the next page of items. * * @param nextLink The URL to get the next list of items. @@ -849,6 +857,8 @@ public void delete(String resourceUri, String endpointName, String serviceConfig } /** + * Lists of all the services associated with endpoint resource. + * * Get the next page of items. * * @param nextLink The URL to get the next list of items. diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/ServiceConfigurationsImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/ServiceConfigurationsImpl.java index ff80043d5040..8db1b277d94d 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/ServiceConfigurationsImpl.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/ServiceConfigurationsImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.implementation; @@ -27,21 +27,6 @@ public ServiceConfigurationsImpl(ServiceConfigurationsClient innerClient, this.serviceManager = serviceManager; } - public PagedIterable listByEndpointResource(String resourceUri, String endpointName) { - PagedIterable inner - = this.serviceClient().listByEndpointResource(resourceUri, endpointName); - return ResourceManagerUtils.mapPage(inner, - inner1 -> new ServiceConfigurationResourceImpl(inner1, this.manager())); - } - - public PagedIterable listByEndpointResource(String resourceUri, String endpointName, - Context context) { - PagedIterable inner - = this.serviceClient().listByEndpointResource(resourceUri, endpointName, context); - return ResourceManagerUtils.mapPage(inner, - inner1 -> new ServiceConfigurationResourceImpl(inner1, this.manager())); - } - public Response getWithResponse(String resourceUri, String endpointName, String serviceConfigurationName, Context context) { Response inner @@ -73,6 +58,21 @@ public void delete(String resourceUri, String endpointName, String serviceConfig this.serviceClient().delete(resourceUri, endpointName, serviceConfigurationName); } + public PagedIterable listByEndpointResource(String resourceUri, String endpointName) { + PagedIterable inner + = this.serviceClient().listByEndpointResource(resourceUri, endpointName); + return ResourceManagerUtils.mapPage(inner, + inner1 -> new ServiceConfigurationResourceImpl(inner1, this.manager())); + } + + public PagedIterable listByEndpointResource(String resourceUri, String endpointName, + Context context) { + PagedIterable inner + = this.serviceClient().listByEndpointResource(resourceUri, endpointName, context); + return ResourceManagerUtils.mapPage(inner, + inner1 -> new ServiceConfigurationResourceImpl(inner1, this.manager())); + } + public ServiceConfigurationResource getById(String id) { String resourceUri = ResourceManagerUtils.getValueFromIdByParameterName(id, "/{resourceUri}/providers/Microsoft.HybridConnectivity/endpoints/{endpointName}/serviceConfigurations/{serviceConfigurationName}", diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/SolutionConfigurationImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/SolutionConfigurationImpl.java new file mode 100644 index 000000000000..60f03dc607c6 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/SolutionConfigurationImpl.java @@ -0,0 +1,140 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.implementation; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.SolutionConfigurationInner; +import com.azure.resourcemanager.hybridconnectivity.models.OperationStatusResult; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionConfiguration; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionConfigurationProperties; + +public final class SolutionConfigurationImpl + implements SolutionConfiguration, SolutionConfiguration.Definition, SolutionConfiguration.Update { + private SolutionConfigurationInner innerObject; + + private final com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager serviceManager; + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public SolutionConfigurationProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public SolutionConfigurationInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager() { + return this.serviceManager; + } + + private String resourceUri; + + private String solutionConfiguration; + + public SolutionConfigurationImpl withExistingResourceUri(String resourceUri) { + this.resourceUri = resourceUri; + return this; + } + + public SolutionConfiguration create() { + this.innerObject = serviceManager.serviceClient() + .getSolutionConfigurations() + .createOrUpdateWithResponse(resourceUri, solutionConfiguration, this.innerModel(), Context.NONE) + .getValue(); + return this; + } + + public SolutionConfiguration create(Context context) { + this.innerObject = serviceManager.serviceClient() + .getSolutionConfigurations() + .createOrUpdateWithResponse(resourceUri, solutionConfiguration, this.innerModel(), context) + .getValue(); + return this; + } + + SolutionConfigurationImpl(String name, + com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager serviceManager) { + this.innerObject = new SolutionConfigurationInner(); + this.serviceManager = serviceManager; + this.solutionConfiguration = name; + } + + public SolutionConfigurationImpl update() { + return this; + } + + public SolutionConfiguration apply() { + this.innerObject = serviceManager.serviceClient() + .getSolutionConfigurations() + .updateWithResponse(resourceUri, solutionConfiguration, this.innerModel(), Context.NONE) + .getValue(); + return this; + } + + public SolutionConfiguration apply(Context context) { + this.innerObject = serviceManager.serviceClient() + .getSolutionConfigurations() + .updateWithResponse(resourceUri, solutionConfiguration, this.innerModel(), context) + .getValue(); + return this; + } + + SolutionConfigurationImpl(SolutionConfigurationInner innerObject, + com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + this.resourceUri = ResourceManagerUtils.getValueFromIdByParameterName(innerObject.id(), + "/{resourceUri}/providers/Microsoft.HybridConnectivity/solutionConfigurations/{solutionConfiguration}", + "resourceUri"); + this.solutionConfiguration = ResourceManagerUtils.getValueFromIdByParameterName(innerObject.id(), + "/{resourceUri}/providers/Microsoft.HybridConnectivity/solutionConfigurations/{solutionConfiguration}", + "solutionConfiguration"); + } + + public SolutionConfiguration refresh() { + this.innerObject = serviceManager.serviceClient() + .getSolutionConfigurations() + .getWithResponse(resourceUri, solutionConfiguration, Context.NONE) + .getValue(); + return this; + } + + public SolutionConfiguration refresh(Context context) { + this.innerObject = serviceManager.serviceClient() + .getSolutionConfigurations() + .getWithResponse(resourceUri, solutionConfiguration, context) + .getValue(); + return this; + } + + public OperationStatusResult syncNow() { + return serviceManager.solutionConfigurations().syncNow(resourceUri, solutionConfiguration); + } + + public OperationStatusResult syncNow(Context context) { + return serviceManager.solutionConfigurations().syncNow(resourceUri, solutionConfiguration, context); + } + + public SolutionConfigurationImpl withProperties(SolutionConfigurationProperties properties) { + this.innerModel().withProperties(properties); + return this; + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/SolutionConfigurationsClientImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/SolutionConfigurationsClientImpl.java new file mode 100644 index 000000000000..3f717acb8272 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/SolutionConfigurationsClientImpl.java @@ -0,0 +1,983 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.Patch; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Post; +import com.azure.core.annotation.Put; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.core.util.polling.PollerFlux; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.hybridconnectivity.fluent.SolutionConfigurationsClient; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.OperationStatusResultInner; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.SolutionConfigurationInner; +import com.azure.resourcemanager.hybridconnectivity.implementation.models.SolutionConfigurationListResult; +import java.nio.ByteBuffer; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in SolutionConfigurationsClient. + */ +public final class SolutionConfigurationsClientImpl implements SolutionConfigurationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final SolutionConfigurationsService service; + + /** + * The service client containing this operation class. + */ + private final HybridConnectivityMgmtClientImpl client; + + /** + * Initializes an instance of SolutionConfigurationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + SolutionConfigurationsClientImpl(HybridConnectivityMgmtClientImpl client) { + this.service = RestProxy.create(SolutionConfigurationsService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for HybridConnectivityMgmtClientSolutionConfigurations to be used by the + * proxy service to perform REST calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "HybridConnectivityMg") + public interface SolutionConfigurationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/{resourceUri}/providers/Microsoft.HybridConnectivity/solutionConfigurations/{solutionConfiguration}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, + @PathParam(value = "resourceUri", encoded = true) String resourceUri, + @PathParam("solutionConfiguration") String solutionConfiguration, @HeaderParam("Accept") String accept, + Context context); + + @Put("/{resourceUri}/providers/Microsoft.HybridConnectivity/solutionConfigurations/{solutionConfiguration}") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> createOrUpdate(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, + @PathParam(value = "resourceUri", encoded = true) String resourceUri, + @PathParam("solutionConfiguration") String solutionConfiguration, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") SolutionConfigurationInner resource, Context context); + + @Patch("/{resourceUri}/providers/Microsoft.HybridConnectivity/solutionConfigurations/{solutionConfiguration}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> update(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, + @PathParam(value = "resourceUri", encoded = true) String resourceUri, + @PathParam("solutionConfiguration") String solutionConfiguration, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") SolutionConfigurationInner properties, Context context); + + @Headers({ "Content-Type: application/json" }) + @Delete("/{resourceUri}/providers/Microsoft.HybridConnectivity/solutionConfigurations/{solutionConfiguration}") + @ExpectedResponses({ 200, 204 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> delete(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, + @PathParam(value = "resourceUri", encoded = true) String resourceUri, + @PathParam("solutionConfiguration") String solutionConfiguration, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/{resourceUri}/providers/Microsoft.HybridConnectivity/solutionConfigurations") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> list(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, + @PathParam(value = "resourceUri", encoded = true) String resourceUri, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Post("/{resourceUri}/providers/Microsoft.HybridConnectivity/solutionConfigurations/{solutionConfiguration}/syncNow") + @ExpectedResponses({ 200, 202 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> syncNow(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, + @PathParam(value = "resourceUri", encoded = true) String resourceUri, + @PathParam("solutionConfiguration") String solutionConfiguration, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * Get a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SolutionConfiguration along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceUri, + String solutionConfiguration) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceUri == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null.")); + } + if (solutionConfiguration == null) { + return Mono + .error(new IllegalArgumentException("Parameter solutionConfiguration is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), resourceUri, + solutionConfiguration, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SolutionConfiguration along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceUri, + String solutionConfiguration, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceUri == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null.")); + } + if (solutionConfiguration == null) { + return Mono + .error(new IllegalArgumentException("Parameter solutionConfiguration is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), resourceUri, solutionConfiguration, + accept, context); + } + + /** + * Get a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SolutionConfiguration on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceUri, String solutionConfiguration) { + return getWithResponseAsync(resourceUri, solutionConfiguration) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SolutionConfiguration along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceUri, String solutionConfiguration, + Context context) { + return getWithResponseAsync(resourceUri, solutionConfiguration, context).block(); + } + + /** + * Get a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SolutionConfiguration. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public SolutionConfigurationInner get(String resourceUri, String solutionConfiguration) { + return getWithResponse(resourceUri, solutionConfiguration, Context.NONE).getValue(); + } + + /** + * Create a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return solution Configuration along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> createOrUpdateWithResponseAsync(String resourceUri, + String solutionConfiguration, SolutionConfigurationInner resource) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceUri == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null.")); + } + if (solutionConfiguration == null) { + return Mono + .error(new IllegalArgumentException("Parameter solutionConfiguration is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.createOrUpdate(this.client.getEndpoint(), this.client.getApiVersion(), + resourceUri, solutionConfiguration, contentType, accept, resource, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Create a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return solution Configuration along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> createOrUpdateWithResponseAsync(String resourceUri, + String solutionConfiguration, SolutionConfigurationInner resource, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceUri == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null.")); + } + if (solutionConfiguration == null) { + return Mono + .error(new IllegalArgumentException("Parameter solutionConfiguration is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.createOrUpdate(this.client.getEndpoint(), this.client.getApiVersion(), resourceUri, + solutionConfiguration, contentType, accept, resource, context); + } + + /** + * Create a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return solution Configuration on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createOrUpdateAsync(String resourceUri, String solutionConfiguration, + SolutionConfigurationInner resource) { + return createOrUpdateWithResponseAsync(resourceUri, solutionConfiguration, resource) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Create a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return solution Configuration along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createOrUpdateWithResponse(String resourceUri, + String solutionConfiguration, SolutionConfigurationInner resource, Context context) { + return createOrUpdateWithResponseAsync(resourceUri, solutionConfiguration, resource, context).block(); + } + + /** + * Create a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return solution Configuration. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public SolutionConfigurationInner createOrUpdate(String resourceUri, String solutionConfiguration, + SolutionConfigurationInner resource) { + return createOrUpdateWithResponse(resourceUri, solutionConfiguration, resource, Context.NONE).getValue(); + } + + /** + * Update a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return solution Configuration along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> updateWithResponseAsync(String resourceUri, + String solutionConfiguration, SolutionConfigurationInner properties) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceUri == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null.")); + } + if (solutionConfiguration == null) { + return Mono + .error(new IllegalArgumentException("Parameter solutionConfiguration is required and cannot be null.")); + } + if (properties == null) { + return Mono.error(new IllegalArgumentException("Parameter properties is required and cannot be null.")); + } else { + properties.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.update(this.client.getEndpoint(), this.client.getApiVersion(), resourceUri, + solutionConfiguration, contentType, accept, properties, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Update a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param properties The resource properties to be updated. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return solution Configuration along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> updateWithResponseAsync(String resourceUri, + String solutionConfiguration, SolutionConfigurationInner properties, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceUri == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null.")); + } + if (solutionConfiguration == null) { + return Mono + .error(new IllegalArgumentException("Parameter solutionConfiguration is required and cannot be null.")); + } + if (properties == null) { + return Mono.error(new IllegalArgumentException("Parameter properties is required and cannot be null.")); + } else { + properties.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.update(this.client.getEndpoint(), this.client.getApiVersion(), resourceUri, + solutionConfiguration, contentType, accept, properties, context); + } + + /** + * Update a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return solution Configuration on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono updateAsync(String resourceUri, String solutionConfiguration, + SolutionConfigurationInner properties) { + return updateWithResponseAsync(resourceUri, solutionConfiguration, properties) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Update a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param properties The resource properties to be updated. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return solution Configuration along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response updateWithResponse(String resourceUri, String solutionConfiguration, + SolutionConfigurationInner properties, Context context) { + return updateWithResponseAsync(resourceUri, solutionConfiguration, properties, context).block(); + } + + /** + * Update a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return solution Configuration. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public SolutionConfigurationInner update(String resourceUri, String solutionConfiguration, + SolutionConfigurationInner properties) { + return updateWithResponse(resourceUri, solutionConfiguration, properties, Context.NONE).getValue(); + } + + /** + * Delete a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceUri, String solutionConfiguration) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceUri == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null.")); + } + if (solutionConfiguration == null) { + return Mono + .error(new IllegalArgumentException("Parameter solutionConfiguration is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.delete(this.client.getEndpoint(), this.client.getApiVersion(), resourceUri, + solutionConfiguration, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Delete a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceUri, String solutionConfiguration, + Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceUri == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null.")); + } + if (solutionConfiguration == null) { + return Mono + .error(new IllegalArgumentException("Parameter solutionConfiguration is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.delete(this.client.getEndpoint(), this.client.getApiVersion(), resourceUri, + solutionConfiguration, accept, context); + } + + /** + * Delete a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono deleteAsync(String resourceUri, String solutionConfiguration) { + return deleteWithResponseAsync(resourceUri, solutionConfiguration).flatMap(ignored -> Mono.empty()); + } + + /** + * Delete a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String resourceUri, String solutionConfiguration, Context context) { + return deleteWithResponseAsync(resourceUri, solutionConfiguration, context).block(); + } + + /** + * Delete a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String resourceUri, String solutionConfiguration) { + deleteWithResponse(resourceUri, solutionConfiguration, Context.NONE); + } + + /** + * List SolutionConfiguration resources by parent. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionConfiguration list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync(String resourceUri) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceUri == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.list(this.client.getEndpoint(), this.client.getApiVersion(), resourceUri, + accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List SolutionConfiguration resources by parent. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionConfiguration list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync(String resourceUri, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceUri == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.list(this.client.getEndpoint(), this.client.getApiVersion(), resourceUri, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List SolutionConfiguration resources by parent. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionConfiguration list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync(String resourceUri) { + return new PagedFlux<>(() -> listSinglePageAsync(resourceUri), nextLink -> listNextSinglePageAsync(nextLink)); + } + + /** + * List SolutionConfiguration resources by parent. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionConfiguration list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync(String resourceUri, Context context) { + return new PagedFlux<>(() -> listSinglePageAsync(resourceUri, context), + nextLink -> listNextSinglePageAsync(nextLink, context)); + } + + /** + * List SolutionConfiguration resources by parent. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionConfiguration list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(String resourceUri) { + return new PagedIterable<>(listAsync(resourceUri)); + } + + /** + * List SolutionConfiguration resources by parent. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionConfiguration list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(String resourceUri, Context context) { + return new PagedIterable<>(listAsync(resourceUri, context)); + } + + /** + * Trigger immediate sync with source cloud. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> syncNowWithResponseAsync(String resourceUri, + String solutionConfiguration) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceUri == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null.")); + } + if (solutionConfiguration == null) { + return Mono + .error(new IllegalArgumentException("Parameter solutionConfiguration is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.syncNow(this.client.getEndpoint(), this.client.getApiVersion(), resourceUri, + solutionConfiguration, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Trigger immediate sync with source cloud. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> syncNowWithResponseAsync(String resourceUri, String solutionConfiguration, + Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceUri == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null.")); + } + if (solutionConfiguration == null) { + return Mono + .error(new IllegalArgumentException("Parameter solutionConfiguration is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.syncNow(this.client.getEndpoint(), this.client.getApiVersion(), resourceUri, + solutionConfiguration, accept, context); + } + + /** + * Trigger immediate sync with source cloud. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, OperationStatusResultInner> + beginSyncNowAsync(String resourceUri, String solutionConfiguration) { + Mono>> mono = syncNowWithResponseAsync(resourceUri, solutionConfiguration); + return this.client.getLroResult(mono, + this.client.getHttpPipeline(), OperationStatusResultInner.class, OperationStatusResultInner.class, + this.client.getContext()); + } + + /** + * Trigger immediate sync with source cloud. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, OperationStatusResultInner> + beginSyncNowAsync(String resourceUri, String solutionConfiguration, Context context) { + context = this.client.mergeContext(context); + Mono>> mono = syncNowWithResponseAsync(resourceUri, solutionConfiguration, context); + return this.client.getLroResult(mono, + this.client.getHttpPipeline(), OperationStatusResultInner.class, OperationStatusResultInner.class, context); + } + + /** + * Trigger immediate sync with source cloud. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, OperationStatusResultInner> + beginSyncNow(String resourceUri, String solutionConfiguration) { + return this.beginSyncNowAsync(resourceUri, solutionConfiguration).getSyncPoller(); + } + + /** + * Trigger immediate sync with source cloud. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, OperationStatusResultInner> + beginSyncNow(String resourceUri, String solutionConfiguration, Context context) { + return this.beginSyncNowAsync(resourceUri, solutionConfiguration, context).getSyncPoller(); + } + + /** + * Trigger immediate sync with source cloud. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono syncNowAsync(String resourceUri, String solutionConfiguration) { + return beginSyncNowAsync(resourceUri, solutionConfiguration).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Trigger immediate sync with source cloud. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono syncNowAsync(String resourceUri, String solutionConfiguration, + Context context) { + return beginSyncNowAsync(resourceUri, solutionConfiguration, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Trigger immediate sync with source cloud. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public OperationStatusResultInner syncNow(String resourceUri, String solutionConfiguration) { + return syncNowAsync(resourceUri, solutionConfiguration).block(); + } + + /** + * Trigger immediate sync with source cloud. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public OperationStatusResultInner syncNow(String resourceUri, String solutionConfiguration, Context context) { + return syncNowAsync(resourceUri, solutionConfiguration, context).block(); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionConfiguration list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.listNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionConfiguration list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listNextSinglePageAsync(String nextLink, Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/SolutionConfigurationsImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/SolutionConfigurationsImpl.java new file mode 100644 index 000000000000..811f5575d394 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/SolutionConfigurationsImpl.java @@ -0,0 +1,173 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.hybridconnectivity.fluent.SolutionConfigurationsClient; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.OperationStatusResultInner; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.SolutionConfigurationInner; +import com.azure.resourcemanager.hybridconnectivity.models.OperationStatusResult; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionConfiguration; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionConfigurations; + +public final class SolutionConfigurationsImpl implements SolutionConfigurations { + private static final ClientLogger LOGGER = new ClientLogger(SolutionConfigurationsImpl.class); + + private final SolutionConfigurationsClient innerClient; + + private final com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager serviceManager; + + public SolutionConfigurationsImpl(SolutionConfigurationsClient innerClient, + com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public Response getWithResponse(String resourceUri, String solutionConfiguration, + Context context) { + Response inner + = this.serviceClient().getWithResponse(resourceUri, solutionConfiguration, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new SolutionConfigurationImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public SolutionConfiguration get(String resourceUri, String solutionConfiguration) { + SolutionConfigurationInner inner = this.serviceClient().get(resourceUri, solutionConfiguration); + if (inner != null) { + return new SolutionConfigurationImpl(inner, this.manager()); + } else { + return null; + } + } + + public Response deleteByResourceGroupWithResponse(String resourceUri, String solutionConfiguration, + Context context) { + return this.serviceClient().deleteWithResponse(resourceUri, solutionConfiguration, context); + } + + public void deleteByResourceGroup(String resourceUri, String solutionConfiguration) { + this.serviceClient().delete(resourceUri, solutionConfiguration); + } + + public PagedIterable list(String resourceUri) { + PagedIterable inner = this.serviceClient().list(resourceUri); + return ResourceManagerUtils.mapPage(inner, inner1 -> new SolutionConfigurationImpl(inner1, this.manager())); + } + + public PagedIterable list(String resourceUri, Context context) { + PagedIterable inner = this.serviceClient().list(resourceUri, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new SolutionConfigurationImpl(inner1, this.manager())); + } + + public OperationStatusResult syncNow(String resourceUri, String solutionConfiguration) { + OperationStatusResultInner inner = this.serviceClient().syncNow(resourceUri, solutionConfiguration); + if (inner != null) { + return new OperationStatusResultImpl(inner, this.manager()); + } else { + return null; + } + } + + public OperationStatusResult syncNow(String resourceUri, String solutionConfiguration, Context context) { + OperationStatusResultInner inner = this.serviceClient().syncNow(resourceUri, solutionConfiguration, context); + if (inner != null) { + return new OperationStatusResultImpl(inner, this.manager()); + } else { + return null; + } + } + + public SolutionConfiguration getById(String id) { + String resourceUri = ResourceManagerUtils.getValueFromIdByParameterName(id, + "/{resourceUri}/providers/Microsoft.HybridConnectivity/solutionConfigurations/{solutionConfiguration}", + "resourceUri"); + if (resourceUri == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceUri'.", id))); + } + String solutionConfiguration = ResourceManagerUtils.getValueFromIdByParameterName(id, + "/{resourceUri}/providers/Microsoft.HybridConnectivity/solutionConfigurations/{solutionConfiguration}", + "solutionConfiguration"); + if (solutionConfiguration == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException(String + .format("The resource ID '%s' is not valid. Missing path segment 'solutionConfigurations'.", id))); + } + return this.getWithResponse(resourceUri, solutionConfiguration, Context.NONE).getValue(); + } + + public Response getByIdWithResponse(String id, Context context) { + String resourceUri = ResourceManagerUtils.getValueFromIdByParameterName(id, + "/{resourceUri}/providers/Microsoft.HybridConnectivity/solutionConfigurations/{solutionConfiguration}", + "resourceUri"); + if (resourceUri == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceUri'.", id))); + } + String solutionConfiguration = ResourceManagerUtils.getValueFromIdByParameterName(id, + "/{resourceUri}/providers/Microsoft.HybridConnectivity/solutionConfigurations/{solutionConfiguration}", + "solutionConfiguration"); + if (solutionConfiguration == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException(String + .format("The resource ID '%s' is not valid. Missing path segment 'solutionConfigurations'.", id))); + } + return this.getWithResponse(resourceUri, solutionConfiguration, context); + } + + public void deleteById(String id) { + String resourceUri = ResourceManagerUtils.getValueFromIdByParameterName(id, + "/{resourceUri}/providers/Microsoft.HybridConnectivity/solutionConfigurations/{solutionConfiguration}", + "resourceUri"); + if (resourceUri == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceUri'.", id))); + } + String solutionConfiguration = ResourceManagerUtils.getValueFromIdByParameterName(id, + "/{resourceUri}/providers/Microsoft.HybridConnectivity/solutionConfigurations/{solutionConfiguration}", + "solutionConfiguration"); + if (solutionConfiguration == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException(String + .format("The resource ID '%s' is not valid. Missing path segment 'solutionConfigurations'.", id))); + } + this.deleteByResourceGroupWithResponse(resourceUri, solutionConfiguration, Context.NONE); + } + + public Response deleteByIdWithResponse(String id, Context context) { + String resourceUri = ResourceManagerUtils.getValueFromIdByParameterName(id, + "/{resourceUri}/providers/Microsoft.HybridConnectivity/solutionConfigurations/{solutionConfiguration}", + "resourceUri"); + if (resourceUri == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceUri'.", id))); + } + String solutionConfiguration = ResourceManagerUtils.getValueFromIdByParameterName(id, + "/{resourceUri}/providers/Microsoft.HybridConnectivity/solutionConfigurations/{solutionConfiguration}", + "solutionConfiguration"); + if (solutionConfiguration == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException(String + .format("The resource ID '%s' is not valid. Missing path segment 'solutionConfigurations'.", id))); + } + return this.deleteByResourceGroupWithResponse(resourceUri, solutionConfiguration, context); + } + + private SolutionConfigurationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager() { + return this.serviceManager; + } + + public SolutionConfigurationImpl define(String name) { + return new SolutionConfigurationImpl(name, this.manager()); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/SolutionTypeResourceImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/SolutionTypeResourceImpl.java new file mode 100644 index 000000000000..fc77725ee5c1 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/SolutionTypeResourceImpl.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.implementation; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.SolutionTypeResourceInner; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionTypeProperties; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionTypeResource; + +public final class SolutionTypeResourceImpl implements SolutionTypeResource { + private SolutionTypeResourceInner innerObject; + + private final com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager serviceManager; + + SolutionTypeResourceImpl(SolutionTypeResourceInner innerObject, + com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public SolutionTypeProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public SolutionTypeResourceInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/SolutionTypesClientImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/SolutionTypesClientImpl.java new file mode 100644 index 000000000000..056bfb8dad00 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/SolutionTypesClientImpl.java @@ -0,0 +1,576 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.implementation; + +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.resourcemanager.hybridconnectivity.fluent.SolutionTypesClient; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.SolutionTypeResourceInner; +import com.azure.resourcemanager.hybridconnectivity.implementation.models.SolutionTypeResourceListResult; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in SolutionTypesClient. + */ +public final class SolutionTypesClientImpl implements SolutionTypesClient { + /** + * The proxy service used to perform REST calls. + */ + private final SolutionTypesService service; + + /** + * The service client containing this operation class. + */ + private final HybridConnectivityMgmtClientImpl client; + + /** + * Initializes an instance of SolutionTypesClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + SolutionTypesClientImpl(HybridConnectivityMgmtClientImpl client) { + this.service + = RestProxy.create(SolutionTypesService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for HybridConnectivityMgmtClientSolutionTypes to be used by the proxy + * service to perform REST calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "HybridConnectivityMg") + public interface SolutionTypesService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HybridConnectivity/solutionTypes/{solutionType}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> getByResourceGroup(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("solutionType") String solutionType, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HybridConnectivity/solutionTypes") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByResourceGroup(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/providers/Microsoft.HybridConnectivity/solutionTypes") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> list(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByResourceGroupNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listBySubscriptionNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * Get a SolutionTypeResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param solutionType Solution Type resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SolutionTypeResource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getByResourceGroupWithResponseAsync(String resourceGroupName, + String solutionType) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (solutionType == null) { + return Mono.error(new IllegalArgumentException("Parameter solutionType is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.getByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, solutionType, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a SolutionTypeResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param solutionType Solution Type resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SolutionTypeResource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getByResourceGroupWithResponseAsync(String resourceGroupName, + String solutionType, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (solutionType == null) { + return Mono.error(new IllegalArgumentException("Parameter solutionType is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.getByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, solutionType, accept, context); + } + + /** + * Get a SolutionTypeResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param solutionType Solution Type resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SolutionTypeResource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getByResourceGroupAsync(String resourceGroupName, String solutionType) { + return getByResourceGroupWithResponseAsync(resourceGroupName, solutionType) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a SolutionTypeResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param solutionType Solution Type resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SolutionTypeResource along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getByResourceGroupWithResponse(String resourceGroupName, + String solutionType, Context context) { + return getByResourceGroupWithResponseAsync(resourceGroupName, solutionType, context).block(); + } + + /** + * Get a SolutionTypeResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param solutionType Solution Type resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SolutionTypeResource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public SolutionTypeResourceInner getByResourceGroup(String resourceGroupName, String solutionType) { + return getByResourceGroupWithResponse(resourceGroupName, solutionType, Context.NONE).getValue(); + } + + /** + * List SolutionTypeResource resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionTypeResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> + listByResourceGroupSinglePageAsync(String resourceGroupName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List SolutionTypeResource resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionTypeResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByResourceGroupSinglePageAsync(String resourceGroupName, + Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List SolutionTypeResource resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionTypeResource list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByResourceGroupAsync(String resourceGroupName) { + return new PagedFlux<>(() -> listByResourceGroupSinglePageAsync(resourceGroupName), + nextLink -> listByResourceGroupNextSinglePageAsync(nextLink)); + } + + /** + * List SolutionTypeResource resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionTypeResource list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByResourceGroupAsync(String resourceGroupName, Context context) { + return new PagedFlux<>(() -> listByResourceGroupSinglePageAsync(resourceGroupName, context), + nextLink -> listByResourceGroupNextSinglePageAsync(nextLink, context)); + } + + /** + * List SolutionTypeResource resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionTypeResource list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByResourceGroup(String resourceGroupName) { + return new PagedIterable<>(listByResourceGroupAsync(resourceGroupName)); + } + + /** + * List SolutionTypeResource resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionTypeResource list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByResourceGroup(String resourceGroupName, Context context) { + return new PagedIterable<>(listByResourceGroupAsync(resourceGroupName, context)); + } + + /** + * List SolutionTypeResource resources by subscription ID. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionTypeResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync() { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.list(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List SolutionTypeResource resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionTypeResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync(Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .list(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), accept, + context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List SolutionTypeResource resources by subscription ID. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionTypeResource list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync() { + return new PagedFlux<>(() -> listSinglePageAsync(), + nextLink -> listBySubscriptionNextSinglePageAsync(nextLink)); + } + + /** + * List SolutionTypeResource resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionTypeResource list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync(Context context) { + return new PagedFlux<>(() -> listSinglePageAsync(context), + nextLink -> listBySubscriptionNextSinglePageAsync(nextLink, context)); + } + + /** + * List SolutionTypeResource resources by subscription ID. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionTypeResource list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list() { + return new PagedIterable<>(listAsync()); + } + + /** + * List SolutionTypeResource resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionTypeResource list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(Context context) { + return new PagedIterable<>(listAsync(context)); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionTypeResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByResourceGroupNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByResourceGroupNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionTypeResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByResourceGroupNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listByResourceGroupNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionTypeResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySubscriptionNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionTypeResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySubscriptionNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/SolutionTypesImpl.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/SolutionTypesImpl.java new file mode 100644 index 000000000000..a85fbbf3e57b --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/SolutionTypesImpl.java @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.hybridconnectivity.fluent.SolutionTypesClient; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.SolutionTypeResourceInner; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionTypeResource; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionTypes; + +public final class SolutionTypesImpl implements SolutionTypes { + private static final ClientLogger LOGGER = new ClientLogger(SolutionTypesImpl.class); + + private final SolutionTypesClient innerClient; + + private final com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager serviceManager; + + public SolutionTypesImpl(SolutionTypesClient innerClient, + com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public Response getByResourceGroupWithResponse(String resourceGroupName, String solutionType, + Context context) { + Response inner + = this.serviceClient().getByResourceGroupWithResponse(resourceGroupName, solutionType, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new SolutionTypeResourceImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public SolutionTypeResource getByResourceGroup(String resourceGroupName, String solutionType) { + SolutionTypeResourceInner inner = this.serviceClient().getByResourceGroup(resourceGroupName, solutionType); + if (inner != null) { + return new SolutionTypeResourceImpl(inner, this.manager()); + } else { + return null; + } + } + + public PagedIterable listByResourceGroup(String resourceGroupName) { + PagedIterable inner = this.serviceClient().listByResourceGroup(resourceGroupName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new SolutionTypeResourceImpl(inner1, this.manager())); + } + + public PagedIterable listByResourceGroup(String resourceGroupName, Context context) { + PagedIterable inner + = this.serviceClient().listByResourceGroup(resourceGroupName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new SolutionTypeResourceImpl(inner1, this.manager())); + } + + public PagedIterable list() { + PagedIterable inner = this.serviceClient().list(); + return ResourceManagerUtils.mapPage(inner, inner1 -> new SolutionTypeResourceImpl(inner1, this.manager())); + } + + public PagedIterable list(Context context) { + PagedIterable inner = this.serviceClient().list(context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new SolutionTypeResourceImpl(inner1, this.manager())); + } + + private SolutionTypesClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/EndpointsList.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/models/EndpointsList.java similarity index 75% rename from sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/EndpointsList.java rename to sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/models/EndpointsList.java index 1943bc757109..d1643e9ed988 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/EndpointsList.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/models/EndpointsList.java @@ -1,10 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.resourcemanager.hybridconnectivity.models; +package com.azure.resourcemanager.hybridconnectivity.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.logging.ClientLogger; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -16,42 +17,22 @@ /** * The list of endpoints. */ -@Fluent +@Immutable public final class EndpointsList implements JsonSerializable { - /* - * The link used to get the next page of endpoints list. - */ - private String nextLink; - /* * The list of endpoint. */ private List value; - /** - * Creates an instance of EndpointsList class. - */ - public EndpointsList() { - } - - /** - * Get the nextLink property: The link used to get the next page of endpoints list. - * - * @return the nextLink value. + /* + * The link used to get the next page of endpoints list. */ - public String nextLink() { - return this.nextLink; - } + private String nextLink; /** - * Set the nextLink property: The link used to get the next page of endpoints list. - * - * @param nextLink the nextLink value to set. - * @return the EndpointsList object itself. + * Creates an instance of EndpointsList class. */ - public EndpointsList withNextLink(String nextLink) { - this.nextLink = nextLink; - return this; + private EndpointsList() { } /** @@ -64,14 +45,12 @@ public List value() { } /** - * Set the value property: The list of endpoint. + * Get the nextLink property: The link used to get the next page of endpoints list. * - * @param value the value value to set. - * @return the EndpointsList object itself. + * @return the nextLink value. */ - public EndpointsList withValue(List value) { - this.value = value; - return this; + public String nextLink() { + return this.nextLink; } /** @@ -80,19 +59,24 @@ public EndpointsList withValue(List value) { * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { - if (value() != null) { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property value in model EndpointsList")); + } else { value().forEach(e -> e.validate()); } } + private static final ClientLogger LOGGER = new ClientLogger(EndpointsList.class); + /** * {@inheritDoc} */ @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeStringField("nextLink", this.nextLink); jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); return jsonWriter.writeEndObject(); } @@ -102,6 +86,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @param jsonReader The JsonReader being read. * @return An instance of EndpointsList 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 EndpointsList. */ public static EndpointsList fromJson(JsonReader jsonReader) throws IOException { @@ -111,12 +96,12 @@ public static EndpointsList fromJson(JsonReader jsonReader) throws IOException { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("nextLink".equals(fieldName)) { - deserializedEndpointsList.nextLink = reader.getString(); - } else if ("value".equals(fieldName)) { + if ("value".equals(fieldName)) { List value = reader.readArray(reader1 -> EndpointResourceInner.fromJson(reader1)); deserializedEndpointsList.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedEndpointsList.nextLink = reader.getString(); } else { reader.skipChildren(); } diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/models/InventoryResourceListResult.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/models/InventoryResourceListResult.java new file mode 100644 index 000000000000..c53e4feb5313 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/models/InventoryResourceListResult.java @@ -0,0 +1,114 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.implementation.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.InventoryResourceInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a InventoryResource list operation. + */ +@Immutable +public final class InventoryResourceListResult implements JsonSerializable { + /* + * The InventoryResource items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of InventoryResourceListResult class. + */ + private InventoryResourceListResult() { + } + + /** + * Get the value property: The InventoryResource items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property value in model InventoryResourceListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(InventoryResourceListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of InventoryResourceListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of InventoryResourceListResult 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 InventoryResourceListResult. + */ + public static InventoryResourceListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + InventoryResourceListResult deserializedInventoryResourceListResult = new InventoryResourceListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> InventoryResourceInner.fromJson(reader1)); + deserializedInventoryResourceListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedInventoryResourceListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedInventoryResourceListResult; + }); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/models/OperationListResult.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/models/OperationListResult.java new file mode 100644 index 000000000000..32d044e0057b --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/models/OperationListResult.java @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.implementation.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.OperationInner; +import java.io.IOException; +import java.util.List; + +/** + * A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + * results. + */ +@Immutable +public final class OperationListResult implements JsonSerializable { + /* + * The Operation items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of OperationListResult class. + */ + private OperationListResult() { + } + + /** + * Get the value property: The Operation items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property value in model OperationListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(OperationListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OperationListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OperationListResult 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 OperationListResult. + */ + public static OperationListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OperationListResult deserializedOperationListResult = new OperationListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value = reader.readArray(reader1 -> OperationInner.fromJson(reader1)); + deserializedOperationListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedOperationListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedOperationListResult; + }); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/models/PublicCloudConnectorListResult.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/models/PublicCloudConnectorListResult.java new file mode 100644 index 000000000000..f092aa82d9e3 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/models/PublicCloudConnectorListResult.java @@ -0,0 +1,115 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.implementation.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.PublicCloudConnectorInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a PublicCloudConnector list operation. + */ +@Immutable +public final class PublicCloudConnectorListResult implements JsonSerializable { + /* + * The PublicCloudConnector items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of PublicCloudConnectorListResult class. + */ + private PublicCloudConnectorListResult() { + } + + /** + * Get the value property: The PublicCloudConnector items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property value in model PublicCloudConnectorListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(PublicCloudConnectorListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of PublicCloudConnectorListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of PublicCloudConnectorListResult 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 PublicCloudConnectorListResult. + */ + public static PublicCloudConnectorListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + PublicCloudConnectorListResult deserializedPublicCloudConnectorListResult + = new PublicCloudConnectorListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> PublicCloudConnectorInner.fromJson(reader1)); + deserializedPublicCloudConnectorListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedPublicCloudConnectorListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedPublicCloudConnectorListResult; + }); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ServiceConfigurationList.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/models/ServiceConfigurationList.java similarity index 78% rename from sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ServiceConfigurationList.java rename to sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/models/ServiceConfigurationList.java index a4b5dd767d6e..80d3a20f6611 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ServiceConfigurationList.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/models/ServiceConfigurationList.java @@ -1,10 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.resourcemanager.hybridconnectivity.models; +package com.azure.resourcemanager.hybridconnectivity.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.logging.ClientLogger; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -16,7 +17,7 @@ /** * The paginated list of serviceConfigurations. */ -@Fluent +@Immutable public final class ServiceConfigurationList implements JsonSerializable { /* * The list of service configuration @@ -31,7 +32,7 @@ public final class ServiceConfigurationList implements JsonSerializable value() { return this.value; } - /** - * Set the value property: The list of service configuration. - * - * @param value the value value to set. - * @return the ServiceConfigurationList object itself. - */ - public ServiceConfigurationList withValue(List value) { - this.value = value; - return this; - } - /** * Get the nextLink property: The link to fetch the next page of connected cluster. * @@ -63,28 +53,22 @@ public String nextLink() { return this.nextLink; } - /** - * Set the nextLink property: The link to fetch the next page of connected cluster. - * - * @param nextLink the nextLink value to set. - * @return the ServiceConfigurationList object itself. - */ - public ServiceConfigurationList withNextLink(String nextLink) { - this.nextLink = nextLink; - return this; - } - /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { - if (value() != null) { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property value in model ServiceConfigurationList")); + } else { value().forEach(e -> e.validate()); } } + private static final ClientLogger LOGGER = new ClientLogger(ServiceConfigurationList.class); + /** * {@inheritDoc} */ @@ -102,6 +86,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @param jsonReader The JsonReader being read. * @return An instance of ServiceConfigurationList 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 ServiceConfigurationList. */ public static ServiceConfigurationList fromJson(JsonReader jsonReader) throws IOException { diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/models/SolutionConfigurationListResult.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/models/SolutionConfigurationListResult.java new file mode 100644 index 000000000000..4af9ad13ce70 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/models/SolutionConfigurationListResult.java @@ -0,0 +1,115 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.implementation.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.SolutionConfigurationInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a SolutionConfiguration list operation. + */ +@Immutable +public final class SolutionConfigurationListResult implements JsonSerializable { + /* + * The SolutionConfiguration items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of SolutionConfigurationListResult class. + */ + private SolutionConfigurationListResult() { + } + + /** + * Get the value property: The SolutionConfiguration items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property value in model SolutionConfigurationListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(SolutionConfigurationListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SolutionConfigurationListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SolutionConfigurationListResult 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 SolutionConfigurationListResult. + */ + public static SolutionConfigurationListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SolutionConfigurationListResult deserializedSolutionConfigurationListResult + = new SolutionConfigurationListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> SolutionConfigurationInner.fromJson(reader1)); + deserializedSolutionConfigurationListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedSolutionConfigurationListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedSolutionConfigurationListResult; + }); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/models/SolutionTypeResourceListResult.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/models/SolutionTypeResourceListResult.java new file mode 100644 index 000000000000..c6ddc761018c --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/models/SolutionTypeResourceListResult.java @@ -0,0 +1,115 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.implementation.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.SolutionTypeResourceInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a SolutionTypeResource list operation. + */ +@Immutable +public final class SolutionTypeResourceListResult implements JsonSerializable { + /* + * The SolutionTypeResource items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of SolutionTypeResourceListResult class. + */ + private SolutionTypeResourceListResult() { + } + + /** + * Get the value property: The SolutionTypeResource items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property value in model SolutionTypeResourceListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(SolutionTypeResourceListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SolutionTypeResourceListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SolutionTypeResourceListResult 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 SolutionTypeResourceListResult. + */ + public static SolutionTypeResourceListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SolutionTypeResourceListResult deserializedSolutionTypeResourceListResult + = new SolutionTypeResourceListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> SolutionTypeResourceInner.fromJson(reader1)); + deserializedSolutionTypeResourceListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedSolutionTypeResourceListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedSolutionTypeResourceListResult; + }); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/package-info.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/package-info.java index fc14fa0d3394..9d23737ce4e8 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/package-info.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/implementation/package-info.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. /** - * Package containing the implementations for HybridConnectivityManagementApi. - * REST API for Hybrid Connectivity. + * Package containing the implementations for HybridConnectivity. + * REST API for public clouds. */ package com.azure.resourcemanager.hybridconnectivity.implementation; diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ActionType.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ActionType.java index 96ce075f4c5a..59e2b0b56e32 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ActionType.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ActionType.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.models; @@ -8,11 +8,11 @@ import java.util.Collection; /** - * Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + * Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. */ public final class ActionType extends ExpandableStringEnum { /** - * Static value Internal for ActionType. + * Actions are for internal-only APIs. */ public static final ActionType INTERNAL = fromString("Internal"); diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/AwsCloudProfile.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/AwsCloudProfile.java new file mode 100644 index 000000000000..c185fdd0e5ea --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/AwsCloudProfile.java @@ -0,0 +1,163 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +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; + +/** + * cloud profile for AWS. + */ +@Fluent +public final class AwsCloudProfile implements JsonSerializable { + /* + * Account id for the AWS account. + */ + private String accountId; + + /* + * List of AWS accounts which need to be excluded. + */ + private List excludedAccounts; + + /* + * Boolean value that indicates whether the account is organizational or not. True represents organization account, + * whereas false represents a single account. + */ + private Boolean isOrganizationalAccount; + + /** + * Creates an instance of AwsCloudProfile class. + */ + public AwsCloudProfile() { + } + + /** + * Get the accountId property: Account id for the AWS account. + * + * @return the accountId value. + */ + public String accountId() { + return this.accountId; + } + + /** + * Set the accountId property: Account id for the AWS account. + * + * @param accountId the accountId value to set. + * @return the AwsCloudProfile object itself. + */ + public AwsCloudProfile withAccountId(String accountId) { + this.accountId = accountId; + return this; + } + + /** + * Get the excludedAccounts property: List of AWS accounts which need to be excluded. + * + * @return the excludedAccounts value. + */ + public List excludedAccounts() { + return this.excludedAccounts; + } + + /** + * Set the excludedAccounts property: List of AWS accounts which need to be excluded. + * + * @param excludedAccounts the excludedAccounts value to set. + * @return the AwsCloudProfile object itself. + */ + public AwsCloudProfile withExcludedAccounts(List excludedAccounts) { + this.excludedAccounts = excludedAccounts; + return this; + } + + /** + * Get the isOrganizationalAccount property: Boolean value that indicates whether the account is organizational or + * not. True represents organization account, whereas false represents a single account. + * + * @return the isOrganizationalAccount value. + */ + public Boolean isOrganizationalAccount() { + return this.isOrganizationalAccount; + } + + /** + * Set the isOrganizationalAccount property: Boolean value that indicates whether the account is organizational or + * not. True represents organization account, whereas false represents a single account. + * + * @param isOrganizationalAccount the isOrganizationalAccount value to set. + * @return the AwsCloudProfile object itself. + */ + public AwsCloudProfile withIsOrganizationalAccount(Boolean isOrganizationalAccount) { + this.isOrganizationalAccount = isOrganizationalAccount; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (accountId() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property accountId in model AwsCloudProfile")); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(AwsCloudProfile.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("accountId", this.accountId); + jsonWriter.writeArrayField("excludedAccounts", this.excludedAccounts, + (writer, element) -> writer.writeString(element)); + jsonWriter.writeBooleanField("isOrganizationalAccount", this.isOrganizationalAccount); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AwsCloudProfile from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AwsCloudProfile 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 AwsCloudProfile. + */ + public static AwsCloudProfile fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AwsCloudProfile deserializedAwsCloudProfile = new AwsCloudProfile(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("accountId".equals(fieldName)) { + deserializedAwsCloudProfile.accountId = reader.getString(); + } else if ("excludedAccounts".equals(fieldName)) { + List excludedAccounts = reader.readArray(reader1 -> reader1.getString()); + deserializedAwsCloudProfile.excludedAccounts = excludedAccounts; + } else if ("isOrganizationalAccount".equals(fieldName)) { + deserializedAwsCloudProfile.isOrganizationalAccount = reader.getNullable(JsonReader::getBoolean); + } else { + reader.skipChildren(); + } + } + + return deserializedAwsCloudProfile; + }); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/CloudNativeType.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/CloudNativeType.java new file mode 100644 index 000000000000..7da3af6e30cb --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/CloudNativeType.java @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Cloud Native Type enum. + */ +public final class CloudNativeType extends ExpandableStringEnum { + /** + * ec2 enum. + */ + public static final CloudNativeType EC2 = fromString("ec2"); + + /** + * Creates a new instance of CloudNativeType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public CloudNativeType() { + } + + /** + * Creates or finds a CloudNativeType from its string representation. + * + * @param name a name to look for. + * @return the corresponding CloudNativeType. + */ + public static CloudNativeType fromString(String name) { + return fromString(name, CloudNativeType.class); + } + + /** + * Gets known CloudNativeType values. + * + * @return known CloudNativeType values. + */ + public static Collection values() { + return values(CloudNativeType.class); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/EndpointAccessResource.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/EndpointAccessResource.java index 12b9ad84f7aa..95952b9bcf92 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/EndpointAccessResource.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/EndpointAccessResource.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.models; diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/EndpointProperties.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/EndpointProperties.java index 3f23a147a9a6..5b28d6c7f8f2 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/EndpointProperties.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/EndpointProperties.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.models; diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/EndpointResource.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/EndpointResource.java index 4a121639230b..72e1d305f860 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/EndpointResource.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/EndpointResource.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.models; @@ -78,7 +78,7 @@ interface WithScope { /** * Specifies resourceUri. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @return the next definition stage. */ WithCreate withExistingResourceUri(String resourceUri); diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/Endpoints.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/Endpoints.java index 4b75fbfabae6..76e23c8a9c15 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/Endpoints.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/Endpoints.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.models; @@ -12,33 +12,10 @@ * Resource collection API of Endpoints. */ public interface Endpoints { - /** - * List of endpoints to the target resource. - * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the list of endpoints as paginated response with {@link PagedIterable}. - */ - PagedIterable list(String resourceUri); - - /** - * List of endpoints to the target resource. - * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the list of endpoints as paginated response with {@link PagedIterable}. - */ - PagedIterable list(String resourceUri, Context context); - /** * Gets the endpoint to the resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -51,7 +28,7 @@ public interface Endpoints { /** * Gets the endpoint to the resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. @@ -63,7 +40,7 @@ public interface Endpoints { /** * Deletes the endpoint access to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -76,7 +53,7 @@ public interface Endpoints { /** * Deletes the endpoint access to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. @@ -84,10 +61,33 @@ public interface Endpoints { */ void deleteByResourceGroup(String resourceUri, String endpointName); + /** + * List of endpoints to the target resource. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the list of endpoints as paginated response with {@link PagedIterable}. + */ + PagedIterable list(String resourceUri); + + /** + * List of endpoints to the target resource. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the list of endpoints as paginated response with {@link PagedIterable}. + */ + PagedIterable list(String resourceUri, Context context); + /** * Gets the endpoint access credentials to the resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param expiresin The is how long the endpoint access token is valid (in seconds). * @param listCredentialsRequest Object of type ListCredentialsRequest. @@ -103,7 +103,7 @@ Response listCredentialsWithResponse(String resourceUri, /** * Gets the endpoint access credentials to the resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. @@ -115,7 +115,7 @@ Response listCredentialsWithResponse(String resourceUri, /** * Gets the ingress gateway endpoint credentials. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param expiresin The is how long the endpoint access token is valid (in seconds). * @param listIngressGatewayCredentialsRequest Object of type ListIngressGatewayCredentialsRequest. @@ -131,7 +131,7 @@ Response listIngressGatewayCredentialsWithResponse(Strin /** * Gets the ingress gateway endpoint credentials. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. @@ -143,7 +143,7 @@ Response listIngressGatewayCredentialsWithResponse(Strin /** * Fetches the managed proxy details. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param managedProxyRequest Object of type ManagedProxyRequest. * @param context The context to associate with this operation. @@ -158,7 +158,7 @@ Response listManagedProxyDetailsWithResponse(String resour /** * Fetches the managed proxy details. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param managedProxyRequest Object of type ManagedProxyRequest. * @throws IllegalArgumentException thrown if parameters fail the validation. diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/GenerateAwsTemplateRequest.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/GenerateAwsTemplateRequest.java new file mode 100644 index 000000000000..6622b09eadb3 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/GenerateAwsTemplateRequest.java @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +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; + +/** + * ConnectorId and SolutionTypes and their properties to Generate AWS CFT Template. + */ +@Fluent +public final class GenerateAwsTemplateRequest implements JsonSerializable { + /* + * The name of public cloud connector + */ + private String connectorId; + + /* + * The list of solution types and their settings + */ + private List solutionTypes; + + /** + * Creates an instance of GenerateAwsTemplateRequest class. + */ + public GenerateAwsTemplateRequest() { + } + + /** + * Get the connectorId property: The name of public cloud connector. + * + * @return the connectorId value. + */ + public String connectorId() { + return this.connectorId; + } + + /** + * Set the connectorId property: The name of public cloud connector. + * + * @param connectorId the connectorId value to set. + * @return the GenerateAwsTemplateRequest object itself. + */ + public GenerateAwsTemplateRequest withConnectorId(String connectorId) { + this.connectorId = connectorId; + return this; + } + + /** + * Get the solutionTypes property: The list of solution types and their settings. + * + * @return the solutionTypes value. + */ + public List solutionTypes() { + return this.solutionTypes; + } + + /** + * Set the solutionTypes property: The list of solution types and their settings. + * + * @param solutionTypes the solutionTypes value to set. + * @return the GenerateAwsTemplateRequest object itself. + */ + public GenerateAwsTemplateRequest withSolutionTypes(List solutionTypes) { + this.solutionTypes = solutionTypes; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (connectorId() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property connectorId in model GenerateAwsTemplateRequest")); + } + if (solutionTypes() != null) { + solutionTypes().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(GenerateAwsTemplateRequest.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("connectorId", this.connectorId); + jsonWriter.writeArrayField("solutionTypes", this.solutionTypes, (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of GenerateAwsTemplateRequest from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of GenerateAwsTemplateRequest 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 GenerateAwsTemplateRequest. + */ + public static GenerateAwsTemplateRequest fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + GenerateAwsTemplateRequest deserializedGenerateAwsTemplateRequest = new GenerateAwsTemplateRequest(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("connectorId".equals(fieldName)) { + deserializedGenerateAwsTemplateRequest.connectorId = reader.getString(); + } else if ("solutionTypes".equals(fieldName)) { + List solutionTypes + = reader.readArray(reader1 -> SolutionTypeSettings.fromJson(reader1)); + deserializedGenerateAwsTemplateRequest.solutionTypes = solutionTypes; + } else { + reader.skipChildren(); + } + } + + return deserializedGenerateAwsTemplateRequest; + }); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/GenerateAwsTemplates.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/GenerateAwsTemplates.java new file mode 100644 index 000000000000..e06ad7fbd618 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/GenerateAwsTemplates.java @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.models; + +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of GenerateAwsTemplates. + */ +public interface GenerateAwsTemplates { + /** + * Retrieve AWS Cloud Formation template. + * + * @param generateAwsTemplateRequest ConnectorId and SolutionTypes and their properties to Generate AWS CFT + * Template. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response}. + */ + Response postWithResponse(GenerateAwsTemplateRequest generateAwsTemplateRequest, Context context); + + /** + * Retrieve AWS Cloud Formation template. + * + * @param generateAwsTemplateRequest ConnectorId and SolutionTypes and their properties to Generate AWS CFT + * Template. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + PostResponse post(GenerateAwsTemplateRequest generateAwsTemplateRequest); +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/HostType.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/HostType.java new file mode 100644 index 000000000000..ea835bda3691 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/HostType.java @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Enum of host cloud the public cloud connector is referencing. + */ +public final class HostType extends ExpandableStringEnum { + /** + * AWS state. + */ + public static final HostType AWS = fromString("AWS"); + + /** + * Creates a new instance of HostType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public HostType() { + } + + /** + * Creates or finds a HostType from its string representation. + * + * @param name a name to look for. + * @return the corresponding HostType. + */ + public static HostType fromString(String name) { + return fromString(name, HostType.class); + } + + /** + * Gets known HostType values. + * + * @return known HostType values. + */ + public static Collection values() { + return values(HostType.class); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/IngressGatewayResource.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/IngressGatewayResource.java index 397fc18e31e8..112f2f038acd 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/IngressGatewayResource.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/IngressGatewayResource.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.models; diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/Inventories.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/Inventories.java new file mode 100644 index 000000000000..05b02f65b483 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/Inventories.java @@ -0,0 +1,68 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of Inventories. + */ +public interface Inventories { + /** + * Get a InventoryResource. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param inventoryId Inventory resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a InventoryResource along with {@link Response}. + */ + Response getWithResponse(String resourceUri, String solutionConfiguration, String inventoryId, + Context context); + + /** + * Get a InventoryResource. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param inventoryId Inventory resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a InventoryResource. + */ + InventoryResource get(String resourceUri, String solutionConfiguration, String inventoryId); + + /** + * List InventoryResource resources by SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a InventoryResource list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listBySolutionConfiguration(String resourceUri, String solutionConfiguration); + + /** + * List InventoryResource resources by SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a InventoryResource list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listBySolutionConfiguration(String resourceUri, String solutionConfiguration, + Context context); +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/InventoryProperties.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/InventoryProperties.java new file mode 100644 index 000000000000..ed726c4727db --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/InventoryProperties.java @@ -0,0 +1,168 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.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; + +/** + * Definition of inventory. + */ +@Immutable +public final class InventoryProperties implements JsonSerializable { + /* + * Gets or sets the cloud native resource type. + */ + private CloudNativeType cloudNativeType; + + /* + * Gets or sets the cloud native resource name. + */ + private String cloudNativeResourceId; + + /* + * Gets or sets the mapped azure resource id. + */ + private String azureResourceId; + + /* + * Gets or sets the status of the inventory. + */ + private SolutionConfigurationStatus status; + + /* + * Gets or sets the status details. + */ + private String statusDetails; + + /* + * The resource provisioning state. + */ + private ResourceProvisioningState provisioningState; + + /** + * Creates an instance of InventoryProperties class. + */ + private InventoryProperties() { + } + + /** + * Get the cloudNativeType property: Gets or sets the cloud native resource type. + * + * @return the cloudNativeType value. + */ + public CloudNativeType cloudNativeType() { + return this.cloudNativeType; + } + + /** + * Get the cloudNativeResourceId property: Gets or sets the cloud native resource name. + * + * @return the cloudNativeResourceId value. + */ + public String cloudNativeResourceId() { + return this.cloudNativeResourceId; + } + + /** + * Get the azureResourceId property: Gets or sets the mapped azure resource id. + * + * @return the azureResourceId value. + */ + public String azureResourceId() { + return this.azureResourceId; + } + + /** + * Get the status property: Gets or sets the status of the inventory. + * + * @return the status value. + */ + public SolutionConfigurationStatus status() { + return this.status; + } + + /** + * Get the statusDetails property: Gets or sets the status details. + * + * @return the statusDetails value. + */ + public String statusDetails() { + return this.statusDetails; + } + + /** + * Get the provisioningState property: The resource provisioning state. + * + * @return the provisioningState value. + */ + public ResourceProvisioningState provisioningState() { + return this.provisioningState; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("cloudNativeType", + this.cloudNativeType == null ? null : this.cloudNativeType.toString()); + jsonWriter.writeStringField("cloudNativeResourceId", this.cloudNativeResourceId); + jsonWriter.writeStringField("azureResourceId", this.azureResourceId); + jsonWriter.writeStringField("status", this.status == null ? null : this.status.toString()); + jsonWriter.writeStringField("statusDetails", this.statusDetails); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of InventoryProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of InventoryProperties 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 InventoryProperties. + */ + public static InventoryProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + InventoryProperties deserializedInventoryProperties = new InventoryProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("cloudNativeType".equals(fieldName)) { + deserializedInventoryProperties.cloudNativeType = CloudNativeType.fromString(reader.getString()); + } else if ("cloudNativeResourceId".equals(fieldName)) { + deserializedInventoryProperties.cloudNativeResourceId = reader.getString(); + } else if ("azureResourceId".equals(fieldName)) { + deserializedInventoryProperties.azureResourceId = reader.getString(); + } else if ("status".equals(fieldName)) { + deserializedInventoryProperties.status = SolutionConfigurationStatus.fromString(reader.getString()); + } else if ("statusDetails".equals(fieldName)) { + deserializedInventoryProperties.statusDetails = reader.getString(); + } else if ("provisioningState".equals(fieldName)) { + deserializedInventoryProperties.provisioningState + = ResourceProvisioningState.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedInventoryProperties; + }); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/InventoryResource.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/InventoryResource.java new file mode 100644 index 000000000000..331692e93ab9 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/InventoryResource.java @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.models; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.InventoryResourceInner; + +/** + * An immutable client-side representation of InventoryResource. + */ +public interface InventoryResource { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + InventoryProperties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.hybridconnectivity.fluent.models.InventoryResourceInner object. + * + * @return the inner object. + */ + InventoryResourceInner innerModel(); +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ListCredentialsRequest.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ListCredentialsRequest.java index e2cb16ff1270..4bbaee69830d 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ListCredentialsRequest.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ListCredentialsRequest.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.models; diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ListIngressGatewayCredentialsRequest.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ListIngressGatewayCredentialsRequest.java index ce8cb9ee6f29..ba5b13ee6568 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ListIngressGatewayCredentialsRequest.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ListIngressGatewayCredentialsRequest.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.models; @@ -18,7 +18,7 @@ public final class ListIngressGatewayCredentialsRequest implements JsonSerializable { /* - * The name of the service. + * The name of the service. If not provided, the request will by pass the generation of service configuration token. */ private ServiceName serviceName; @@ -29,7 +29,8 @@ public ListIngressGatewayCredentialsRequest() { } /** - * Get the serviceName property: The name of the service. + * Get the serviceName property: The name of the service. If not provided, the request will by pass the generation + * of service configuration token. * * @return the serviceName value. */ @@ -38,7 +39,8 @@ public ServiceName serviceName() { } /** - * Set the serviceName property: The name of the service. + * Set the serviceName property: The name of the service. If not provided, the request will by pass the generation + * of service configuration token. * * @param serviceName the serviceName value to set. * @return the ListIngressGatewayCredentialsRequest object itself. diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ManagedProxyRequest.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ManagedProxyRequest.java index 531420c8987b..887d8936d9b8 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ManagedProxyRequest.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ManagedProxyRequest.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.models; diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ManagedProxyResource.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ManagedProxyResource.java index ad8629e9f987..2ea83d8da64a 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ManagedProxyResource.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ManagedProxyResource.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.models; diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/Operation.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/Operation.java index 72dc659c428b..aeae2217e2b9 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/Operation.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/Operation.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.models; @@ -20,7 +20,7 @@ public interface Operation { /** * Gets the isDataAction property: Whether the operation applies to data-plane. This is "true" for data-plane - * operations and "false" for ARM/control-plane operations. + * operations and "false" for Azure Resource Manager/control-plane operations. * * @return the isDataAction value. */ @@ -42,8 +42,8 @@ public interface Operation { Origin origin(); /** - * Gets the actionType property: Enum. Indicates the action type. "Internal" refers to actions that are for internal - * only APIs. + * Gets the actionType property: Extensible enum. Indicates the action type. "Internal" refers to actions that are + * for internal only APIs. * * @return the actionType value. */ diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/OperationDisplay.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/OperationDisplay.java index 2de9eeff3e6c..01a140813039 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/OperationDisplay.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/OperationDisplay.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.models; @@ -12,7 +12,7 @@ import java.io.IOException; /** - * Localized display information for this particular operation. + * Localized display information for and operation. */ @Immutable public final class OperationDisplay implements JsonSerializable { @@ -42,7 +42,7 @@ public final class OperationDisplay implements JsonSerializable { - /* - * List of operations supported by the resource provider - */ - private List value; - - /* - * URL to get the next set of operation list results (if there are any). - */ - private String nextLink; - - /** - * Creates an instance of OperationListResult class. - */ - public OperationListResult() { - } - - /** - * Get the value property: List of operations supported by the resource provider. - * - * @return the value value. - */ - public List value() { - return this.value; - } - - /** - * Get the nextLink property: URL to get the next set of operation list results (if there are any). - * - * @return the nextLink value. - */ - public String nextLink() { - return this.nextLink; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (value() != null) { - value().forEach(e -> e.validate()); - } - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of OperationListResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of OperationListResult 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 OperationListResult. - */ - public static OperationListResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - OperationListResult deserializedOperationListResult = new OperationListResult(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - List value = reader.readArray(reader1 -> OperationInner.fromJson(reader1)); - deserializedOperationListResult.value = value; - } else if ("nextLink".equals(fieldName)) { - deserializedOperationListResult.nextLink = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedOperationListResult; - }); - } -} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/OperationStatusResult.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/OperationStatusResult.java new file mode 100644 index 000000000000..3cb3dfdd899e --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/OperationStatusResult.java @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.models; + +import com.azure.core.management.exception.ManagementError; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.OperationStatusResultInner; +import java.time.OffsetDateTime; +import java.util.List; + +/** + * An immutable client-side representation of OperationStatusResult. + */ +public interface OperationStatusResult { + /** + * Gets the id property: Fully qualified ID for the async operation. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: Name of the async operation. + * + * @return the name value. + */ + String name(); + + /** + * Gets the status property: Operation status. + * + * @return the status value. + */ + String status(); + + /** + * Gets the percentComplete property: Percent of the operation that is complete. + * + * @return the percentComplete value. + */ + Double percentComplete(); + + /** + * Gets the startTime property: The start time of the operation. + * + * @return the startTime value. + */ + OffsetDateTime startTime(); + + /** + * Gets the endTime property: The end time of the operation. + * + * @return the endTime value. + */ + OffsetDateTime endTime(); + + /** + * Gets the operations property: The operations list. + * + * @return the operations value. + */ + List operations(); + + /** + * Gets the error property: If present, details of the operation error. + * + * @return the error value. + */ + ManagementError error(); + + /** + * Gets the resourceId property: Fully qualified ID of the resource against which the original async operation was + * started. + * + * @return the resourceId value. + */ + String resourceId(); + + /** + * Gets the inner com.azure.resourcemanager.hybridconnectivity.fluent.models.OperationStatusResultInner object. + * + * @return the inner object. + */ + OperationStatusResultInner innerModel(); +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/Operations.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/Operations.java index a1ce9526b738..c9ffebf25698 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/Operations.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/Operations.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.models; @@ -12,7 +12,7 @@ */ public interface Operations { /** - * Lists the available Hybrid Connectivity REST API operations. + * List the operations for the provider. * * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -22,7 +22,7 @@ public interface Operations { PagedIterable list(); /** - * Lists the available Hybrid Connectivity REST API operations. + * List the operations for the provider. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/Origin.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/Origin.java index ad108562cafc..9d24ff5fbfa3 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/Origin.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/Origin.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.models; @@ -13,17 +13,17 @@ */ public final class Origin extends ExpandableStringEnum { /** - * Static value user for Origin. + * Indicates the operation is initiated by a user. */ public static final Origin USER = fromString("user"); /** - * Static value system for Origin. + * Indicates the operation is initiated by a system. */ public static final Origin SYSTEM = fromString("system"); /** - * Static value user,system for Origin. + * Indicates the operation is initiated by a user or system. */ public static final Origin USER_SYSTEM = fromString("user,system"); diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/PostResponse.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/PostResponse.java new file mode 100644 index 000000000000..59d400102ccc --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/PostResponse.java @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.models; + +import com.azure.resourcemanager.hybridconnectivity.fluent.models.PostResponseInner; + +/** + * An immutable client-side representation of PostResponse. + */ +public interface PostResponse { + /** + * Gets the inner com.azure.resourcemanager.hybridconnectivity.fluent.models.PostResponseInner object. + * + * @return the inner object. + */ + PostResponseInner innerModel(); +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ProvisioningState.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ProvisioningState.java index 90f8a04ac62b..45dbc52a5141 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ProvisioningState.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ProvisioningState.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.models; diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/PublicCloudConnector.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/PublicCloudConnector.java new file mode 100644 index 000000000000..db2895033391 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/PublicCloudConnector.java @@ -0,0 +1,285 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.models; + +import com.azure.core.management.Region; +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.PublicCloudConnectorInner; +import java.util.Map; + +/** + * An immutable client-side representation of PublicCloudConnector. + */ +public interface PublicCloudConnector { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the location property: The geo-location where the resource lives. + * + * @return the location value. + */ + String location(); + + /** + * Gets the tags property: Resource tags. + * + * @return the tags value. + */ + Map tags(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + PublicCloudConnectorProperties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the region of the resource. + * + * @return the region of the resource. + */ + Region region(); + + /** + * Gets the name of the resource region. + * + * @return the name of the resource region. + */ + String regionName(); + + /** + * Gets the name of the resource group. + * + * @return the name of the resource group. + */ + String resourceGroupName(); + + /** + * Gets the inner com.azure.resourcemanager.hybridconnectivity.fluent.models.PublicCloudConnectorInner object. + * + * @return the inner object. + */ + PublicCloudConnectorInner innerModel(); + + /** + * The entirety of the PublicCloudConnector definition. + */ + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithLocation, + DefinitionStages.WithResourceGroup, DefinitionStages.WithCreate { + } + + /** + * The PublicCloudConnector definition stages. + */ + interface DefinitionStages { + /** + * The first stage of the PublicCloudConnector definition. + */ + interface Blank extends WithLocation { + } + + /** + * The stage of the PublicCloudConnector definition allowing to specify location. + */ + interface WithLocation { + /** + * Specifies the region for the resource. + * + * @param location The geo-location where the resource lives. + * @return the next definition stage. + */ + WithResourceGroup withRegion(Region location); + + /** + * Specifies the region for the resource. + * + * @param location The geo-location where the resource lives. + * @return the next definition stage. + */ + WithResourceGroup withRegion(String location); + } + + /** + * The stage of the PublicCloudConnector definition allowing to specify parent resource. + */ + interface WithResourceGroup { + /** + * Specifies resourceGroupName. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @return the next definition stage. + */ + WithCreate withExistingResourceGroup(String resourceGroupName); + } + + /** + * The stage of the PublicCloudConnector definition which contains all the minimum required properties for the + * resource to be created, but also allows for any other optional properties to be specified. + */ + interface WithCreate extends DefinitionStages.WithTags, DefinitionStages.WithProperties { + /** + * Executes the create request. + * + * @return the created resource. + */ + PublicCloudConnector create(); + + /** + * Executes the create request. + * + * @param context The context to associate with this operation. + * @return the created resource. + */ + PublicCloudConnector create(Context context); + } + + /** + * The stage of the PublicCloudConnector definition allowing to specify tags. + */ + interface WithTags { + /** + * Specifies the tags property: Resource tags.. + * + * @param tags Resource tags. + * @return the next definition stage. + */ + WithCreate withTags(Map tags); + } + + /** + * The stage of the PublicCloudConnector definition allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The resource-specific properties for this resource.. + * + * @param properties The resource-specific properties for this resource. + * @return the next definition stage. + */ + WithCreate withProperties(PublicCloudConnectorProperties properties); + } + } + + /** + * Begins update for the PublicCloudConnector resource. + * + * @return the stage of resource update. + */ + PublicCloudConnector.Update update(); + + /** + * The template for PublicCloudConnector update. + */ + interface Update extends UpdateStages.WithTags, UpdateStages.WithProperties { + /** + * Executes the update request. + * + * @return the updated resource. + */ + PublicCloudConnector apply(); + + /** + * Executes the update request. + * + * @param context The context to associate with this operation. + * @return the updated resource. + */ + PublicCloudConnector apply(Context context); + } + + /** + * The PublicCloudConnector update stages. + */ + interface UpdateStages { + /** + * The stage of the PublicCloudConnector update allowing to specify tags. + */ + interface WithTags { + /** + * Specifies the tags property: Resource tags.. + * + * @param tags Resource tags. + * @return the next definition stage. + */ + Update withTags(Map tags); + } + + /** + * The stage of the PublicCloudConnector update allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The resource-specific properties for this resource.. + * + * @param properties The resource-specific properties for this resource. + * @return the next definition stage. + */ + Update withProperties(PublicCloudConnectorProperties properties); + } + } + + /** + * Refreshes the resource to sync with Azure. + * + * @return the refreshed resource. + */ + PublicCloudConnector refresh(); + + /** + * Refreshes the resource to sync with Azure. + * + * @param context The context to associate with this operation. + * @return the refreshed resource. + */ + PublicCloudConnector refresh(Context context); + + /** + * A long-running resource action. + * + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + OperationStatusResult testPermissions(); + + /** + * A long-running resource action. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + OperationStatusResult testPermissions(Context context); +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/PublicCloudConnectorProperties.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/PublicCloudConnectorProperties.java new file mode 100644 index 000000000000..56074ea114e4 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/PublicCloudConnectorProperties.java @@ -0,0 +1,171 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Properties of public cloud connectors. + */ +@Fluent +public final class PublicCloudConnectorProperties implements JsonSerializable { + /* + * Cloud profile for AWS. + */ + private AwsCloudProfile awsCloudProfile; + + /* + * Host cloud the public cloud connector. + */ + private HostType hostType; + + /* + * The resource provisioning state. + */ + private ResourceProvisioningState provisioningState; + + /* + * Connector primary identifier. + */ + private String connectorPrimaryIdentifier; + + /** + * Creates an instance of PublicCloudConnectorProperties class. + */ + public PublicCloudConnectorProperties() { + } + + /** + * Get the awsCloudProfile property: Cloud profile for AWS. + * + * @return the awsCloudProfile value. + */ + public AwsCloudProfile awsCloudProfile() { + return this.awsCloudProfile; + } + + /** + * Set the awsCloudProfile property: Cloud profile for AWS. + * + * @param awsCloudProfile the awsCloudProfile value to set. + * @return the PublicCloudConnectorProperties object itself. + */ + public PublicCloudConnectorProperties withAwsCloudProfile(AwsCloudProfile awsCloudProfile) { + this.awsCloudProfile = awsCloudProfile; + return this; + } + + /** + * Get the hostType property: Host cloud the public cloud connector. + * + * @return the hostType value. + */ + public HostType hostType() { + return this.hostType; + } + + /** + * Set the hostType property: Host cloud the public cloud connector. + * + * @param hostType the hostType value to set. + * @return the PublicCloudConnectorProperties object itself. + */ + public PublicCloudConnectorProperties withHostType(HostType hostType) { + this.hostType = hostType; + return this; + } + + /** + * Get the provisioningState property: The resource provisioning state. + * + * @return the provisioningState value. + */ + public ResourceProvisioningState provisioningState() { + return this.provisioningState; + } + + /** + * Get the connectorPrimaryIdentifier property: Connector primary identifier. + * + * @return the connectorPrimaryIdentifier value. + */ + public String connectorPrimaryIdentifier() { + return this.connectorPrimaryIdentifier; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (awsCloudProfile() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property awsCloudProfile in model PublicCloudConnectorProperties")); + } else { + awsCloudProfile().validate(); + } + if (hostType() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property hostType in model PublicCloudConnectorProperties")); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(PublicCloudConnectorProperties.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("awsCloudProfile", this.awsCloudProfile); + jsonWriter.writeStringField("hostType", this.hostType == null ? null : this.hostType.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of PublicCloudConnectorProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of PublicCloudConnectorProperties 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 PublicCloudConnectorProperties. + */ + public static PublicCloudConnectorProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + PublicCloudConnectorProperties deserializedPublicCloudConnectorProperties + = new PublicCloudConnectorProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("awsCloudProfile".equals(fieldName)) { + deserializedPublicCloudConnectorProperties.awsCloudProfile = AwsCloudProfile.fromJson(reader); + } else if ("hostType".equals(fieldName)) { + deserializedPublicCloudConnectorProperties.hostType = HostType.fromString(reader.getString()); + } else if ("provisioningState".equals(fieldName)) { + deserializedPublicCloudConnectorProperties.provisioningState + = ResourceProvisioningState.fromString(reader.getString()); + } else if ("connectorPrimaryIdentifier".equals(fieldName)) { + deserializedPublicCloudConnectorProperties.connectorPrimaryIdentifier = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedPublicCloudConnectorProperties; + }); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/PublicCloudConnectors.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/PublicCloudConnectors.java new file mode 100644 index 000000000000..b6d42a98c902 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/PublicCloudConnectors.java @@ -0,0 +1,186 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of PublicCloudConnectors. + */ +public interface PublicCloudConnectors { + /** + * Get a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a PublicCloudConnector along with {@link Response}. + */ + Response getByResourceGroupWithResponse(String resourceGroupName, String publicCloudConnector, + Context context); + + /** + * Get a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a PublicCloudConnector. + */ + PublicCloudConnector getByResourceGroup(String resourceGroupName, String publicCloudConnector); + + /** + * Delete a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteByResourceGroupWithResponse(String resourceGroupName, String publicCloudConnector, + Context context); + + /** + * Delete a PublicCloudConnector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteByResourceGroup(String resourceGroupName, String publicCloudConnector); + + /** + * List PublicCloudConnector resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PublicCloudConnector list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByResourceGroup(String resourceGroupName); + + /** + * List PublicCloudConnector resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PublicCloudConnector list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByResourceGroup(String resourceGroupName, Context context); + + /** + * List PublicCloudConnector resources by subscription ID. + * + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PublicCloudConnector list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable list(); + + /** + * List PublicCloudConnector resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PublicCloudConnector list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable list(Context context); + + /** + * A long-running resource action. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + OperationStatusResult testPermissions(String resourceGroupName, String publicCloudConnector); + + /** + * A long-running resource action. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param publicCloudConnector Represent public cloud connectors resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + OperationStatusResult testPermissions(String resourceGroupName, String publicCloudConnector, Context context); + + /** + * Get a PublicCloudConnector. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a PublicCloudConnector along with {@link Response}. + */ + PublicCloudConnector getById(String id); + + /** + * Get a PublicCloudConnector. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a PublicCloudConnector along with {@link Response}. + */ + Response getByIdWithResponse(String id, Context context); + + /** + * Delete a PublicCloudConnector. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteById(String id); + + /** + * Delete a PublicCloudConnector. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteByIdWithResponse(String id, Context context); + + /** + * Begins definition for a new PublicCloudConnector resource. + * + * @param name resource name. + * @return the first stage of the new PublicCloudConnector definition. + */ + PublicCloudConnector.DefinitionStages.Blank define(String name); +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ResourceProvisioningState.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ResourceProvisioningState.java new file mode 100644 index 000000000000..ce44995603e1 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ResourceProvisioningState.java @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The provisioning state of a resource type. + */ +public final class ResourceProvisioningState extends ExpandableStringEnum { + /** + * Resource has been created. + */ + public static final ResourceProvisioningState SUCCEEDED = fromString("Succeeded"); + + /** + * Resource creation failed. + */ + public static final ResourceProvisioningState FAILED = fromString("Failed"); + + /** + * Resource creation was canceled. + */ + public static final ResourceProvisioningState CANCELED = fromString("Canceled"); + + /** + * Creates a new instance of ResourceProvisioningState value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public ResourceProvisioningState() { + } + + /** + * Creates or finds a ResourceProvisioningState from its string representation. + * + * @param name a name to look for. + * @return the corresponding ResourceProvisioningState. + */ + public static ResourceProvisioningState fromString(String name) { + return fromString(name, ResourceProvisioningState.class); + } + + /** + * Gets known ResourceProvisioningState values. + * + * @return known ResourceProvisioningState values. + */ + public static Collection values() { + return values(ResourceProvisioningState.class); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ServiceConfigurationResource.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ServiceConfigurationResource.java index f0d58fa10827..2b4b8dbe2486 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ServiceConfigurationResource.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ServiceConfigurationResource.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.models; @@ -100,7 +100,7 @@ interface WithParentResource { /** * Specifies resourceUri, endpointName. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @return the next definition stage. */ diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ServiceConfigurationResourcePatch.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ServiceConfigurationResourcePatch.java index da4c2d78c342..ba2d0de21722 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ServiceConfigurationResourcePatch.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ServiceConfigurationResourcePatch.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.models; diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ServiceConfigurations.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ServiceConfigurations.java index 8140846203fd..a74f543bafce 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ServiceConfigurations.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ServiceConfigurations.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.models; @@ -12,40 +12,10 @@ * Resource collection API of ServiceConfigurations. */ public interface ServiceConfigurations { - /** - * Lists of all the services associated with endpoint resource. - * - * API to enumerate registered services in service configurations under a Endpoint Resource. - * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. - * @param endpointName The endpoint name. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the paginated list of serviceConfigurations as paginated response with {@link PagedIterable}. - */ - PagedIterable listByEndpointResource(String resourceUri, String endpointName); - - /** - * Lists of all the services associated with endpoint resource. - * - * API to enumerate registered services in service configurations under a Endpoint Resource. - * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. - * @param endpointName The endpoint name. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the paginated list of serviceConfigurations as paginated response with {@link PagedIterable}. - */ - PagedIterable listByEndpointResource(String resourceUri, String endpointName, - Context context); - /** * Gets the details about the service to the resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @param context The context to associate with this operation. @@ -60,7 +30,7 @@ Response getWithResponse(String resourceUri, Strin /** * Gets the details about the service to the resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -73,7 +43,7 @@ Response getWithResponse(String resourceUri, Strin /** * Deletes the service details to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @param context The context to associate with this operation. @@ -88,7 +58,7 @@ Response deleteWithResponse(String resourceUri, String endpointName, Strin /** * Deletes the service details to the target resource. * - * @param resourceUri The fully qualified Azure Resource manager identifier of the resource to be connected. + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. * @param endpointName The endpoint name. * @param serviceConfigurationName The service name. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -97,6 +67,36 @@ Response deleteWithResponse(String resourceUri, String endpointName, Strin */ void delete(String resourceUri, String endpointName, String serviceConfigurationName); + /** + * Lists of all the services associated with endpoint resource. + * + * API to enumerate registered services in service configurations under a Endpoint Resource. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param endpointName The endpoint name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the paginated list of serviceConfigurations as paginated response with {@link PagedIterable}. + */ + PagedIterable listByEndpointResource(String resourceUri, String endpointName); + + /** + * Lists of all the services associated with endpoint resource. + * + * API to enumerate registered services in service configurations under a Endpoint Resource. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param endpointName The endpoint name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the paginated list of serviceConfigurations as paginated response with {@link PagedIterable}. + */ + PagedIterable listByEndpointResource(String resourceUri, String endpointName, + Context context); + /** * Gets the details about the service to the resource. * diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ServiceName.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ServiceName.java index 19087d431d0d..4e5092b859cb 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ServiceName.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/ServiceName.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.models; diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionConfiguration.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionConfiguration.java new file mode 100644 index 000000000000..751cdfb555e2 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionConfiguration.java @@ -0,0 +1,200 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.models; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.SolutionConfigurationInner; + +/** + * An immutable client-side representation of SolutionConfiguration. + */ +public interface SolutionConfiguration { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + SolutionConfigurationProperties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.hybridconnectivity.fluent.models.SolutionConfigurationInner object. + * + * @return the inner object. + */ + SolutionConfigurationInner innerModel(); + + /** + * The entirety of the SolutionConfiguration definition. + */ + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithScope, DefinitionStages.WithCreate { + } + + /** + * The SolutionConfiguration definition stages. + */ + interface DefinitionStages { + /** + * The first stage of the SolutionConfiguration definition. + */ + interface Blank extends WithScope { + } + + /** + * The stage of the SolutionConfiguration definition allowing to specify parent resource. + */ + interface WithScope { + /** + * Specifies resourceUri. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @return the next definition stage. + */ + WithCreate withExistingResourceUri(String resourceUri); + } + + /** + * The stage of the SolutionConfiguration definition which contains all the minimum required properties for the + * resource to be created, but also allows for any other optional properties to be specified. + */ + interface WithCreate extends DefinitionStages.WithProperties { + /** + * Executes the create request. + * + * @return the created resource. + */ + SolutionConfiguration create(); + + /** + * Executes the create request. + * + * @param context The context to associate with this operation. + * @return the created resource. + */ + SolutionConfiguration create(Context context); + } + + /** + * The stage of the SolutionConfiguration definition allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The resource-specific properties for this resource.. + * + * @param properties The resource-specific properties for this resource. + * @return the next definition stage. + */ + WithCreate withProperties(SolutionConfigurationProperties properties); + } + } + + /** + * Begins update for the SolutionConfiguration resource. + * + * @return the stage of resource update. + */ + SolutionConfiguration.Update update(); + + /** + * The template for SolutionConfiguration update. + */ + interface Update extends UpdateStages.WithProperties { + /** + * Executes the update request. + * + * @return the updated resource. + */ + SolutionConfiguration apply(); + + /** + * Executes the update request. + * + * @param context The context to associate with this operation. + * @return the updated resource. + */ + SolutionConfiguration apply(Context context); + } + + /** + * The SolutionConfiguration update stages. + */ + interface UpdateStages { + /** + * The stage of the SolutionConfiguration update allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The resource-specific properties for this resource.. + * + * @param properties The resource-specific properties for this resource. + * @return the next definition stage. + */ + Update withProperties(SolutionConfigurationProperties properties); + } + } + + /** + * Refreshes the resource to sync with Azure. + * + * @return the refreshed resource. + */ + SolutionConfiguration refresh(); + + /** + * Refreshes the resource to sync with Azure. + * + * @param context The context to associate with this operation. + * @return the refreshed resource. + */ + SolutionConfiguration refresh(Context context); + + /** + * Trigger immediate sync with source cloud. + * + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + OperationStatusResult syncNow(); + + /** + * Trigger immediate sync with source cloud. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + OperationStatusResult syncNow(Context context); +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionConfigurationProperties.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionConfigurationProperties.java new file mode 100644 index 000000000000..1438050d85a1 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionConfigurationProperties.java @@ -0,0 +1,203 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; +import com.azure.core.util.logging.ClientLogger; +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.OffsetDateTime; + +/** + * Solution configuration resource. + */ +@Fluent +public final class SolutionConfigurationProperties implements JsonSerializable { + /* + * The resource provisioning state. + */ + private ResourceProvisioningState provisioningState; + + /* + * The type of the solution + */ + private String solutionType; + + /* + * Solution settings + */ + private SolutionSettings solutionSettings; + + /* + * The status of solution configurations + */ + private SolutionConfigurationStatus status; + + /* + * The detailed message of status details + */ + private String statusDetails; + + /* + * The last time resources were inventoried + */ + private OffsetDateTime lastSyncTime; + + /** + * Creates an instance of SolutionConfigurationProperties class. + */ + public SolutionConfigurationProperties() { + } + + /** + * Get the provisioningState property: The resource provisioning state. + * + * @return the provisioningState value. + */ + public ResourceProvisioningState provisioningState() { + return this.provisioningState; + } + + /** + * Get the solutionType property: The type of the solution. + * + * @return the solutionType value. + */ + public String solutionType() { + return this.solutionType; + } + + /** + * Set the solutionType property: The type of the solution. + * + * @param solutionType the solutionType value to set. + * @return the SolutionConfigurationProperties object itself. + */ + public SolutionConfigurationProperties withSolutionType(String solutionType) { + this.solutionType = solutionType; + return this; + } + + /** + * Get the solutionSettings property: Solution settings. + * + * @return the solutionSettings value. + */ + public SolutionSettings solutionSettings() { + return this.solutionSettings; + } + + /** + * Set the solutionSettings property: Solution settings. + * + * @param solutionSettings the solutionSettings value to set. + * @return the SolutionConfigurationProperties object itself. + */ + public SolutionConfigurationProperties withSolutionSettings(SolutionSettings solutionSettings) { + this.solutionSettings = solutionSettings; + return this; + } + + /** + * Get the status property: The status of solution configurations. + * + * @return the status value. + */ + public SolutionConfigurationStatus status() { + return this.status; + } + + /** + * Get the statusDetails property: The detailed message of status details. + * + * @return the statusDetails value. + */ + public String statusDetails() { + return this.statusDetails; + } + + /** + * Get the lastSyncTime property: The last time resources were inventoried. + * + * @return the lastSyncTime value. + */ + public OffsetDateTime lastSyncTime() { + return this.lastSyncTime; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (solutionType() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property solutionType in model SolutionConfigurationProperties")); + } + if (solutionSettings() != null) { + solutionSettings().validate(); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(SolutionConfigurationProperties.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("solutionType", this.solutionType); + jsonWriter.writeJsonField("solutionSettings", this.solutionSettings); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SolutionConfigurationProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SolutionConfigurationProperties 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 SolutionConfigurationProperties. + */ + public static SolutionConfigurationProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SolutionConfigurationProperties deserializedSolutionConfigurationProperties + = new SolutionConfigurationProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("solutionType".equals(fieldName)) { + deserializedSolutionConfigurationProperties.solutionType = reader.getString(); + } else if ("provisioningState".equals(fieldName)) { + deserializedSolutionConfigurationProperties.provisioningState + = ResourceProvisioningState.fromString(reader.getString()); + } else if ("solutionSettings".equals(fieldName)) { + deserializedSolutionConfigurationProperties.solutionSettings = SolutionSettings.fromJson(reader); + } else if ("status".equals(fieldName)) { + deserializedSolutionConfigurationProperties.status + = SolutionConfigurationStatus.fromString(reader.getString()); + } else if ("statusDetails".equals(fieldName)) { + deserializedSolutionConfigurationProperties.statusDetails = reader.getString(); + } else if ("lastSyncTime".equals(fieldName)) { + deserializedSolutionConfigurationProperties.lastSyncTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else { + reader.skipChildren(); + } + } + + return deserializedSolutionConfigurationProperties; + }); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionConfigurationStatus.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionConfigurationStatus.java new file mode 100644 index 000000000000..35eae393ccd9 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionConfigurationStatus.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Solution Configuration Status. + */ +public final class SolutionConfigurationStatus extends ExpandableStringEnum { + /** + * New status. + */ + public static final SolutionConfigurationStatus NEW = fromString("New"); + + /** + * InProgress status. + */ + public static final SolutionConfigurationStatus IN_PROGRESS = fromString("InProgress"); + + /** + * Canceled status. + */ + public static final SolutionConfigurationStatus COMPLETED = fromString("Completed"); + + /** + * Failed status. + */ + public static final SolutionConfigurationStatus FAILED = fromString("Failed"); + + /** + * Creates a new instance of SolutionConfigurationStatus value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public SolutionConfigurationStatus() { + } + + /** + * Creates or finds a SolutionConfigurationStatus from its string representation. + * + * @param name a name to look for. + * @return the corresponding SolutionConfigurationStatus. + */ + public static SolutionConfigurationStatus fromString(String name) { + return fromString(name, SolutionConfigurationStatus.class); + } + + /** + * Gets known SolutionConfigurationStatus values. + * + * @return known SolutionConfigurationStatus values. + */ + public static Collection values() { + return values(SolutionConfigurationStatus.class); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionConfigurations.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionConfigurations.java new file mode 100644 index 000000000000..ad412bb72983 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionConfigurations.java @@ -0,0 +1,164 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of SolutionConfigurations. + */ +public interface SolutionConfigurations { + /** + * Get a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SolutionConfiguration along with {@link Response}. + */ + Response getWithResponse(String resourceUri, String solutionConfiguration, Context context); + + /** + * Get a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SolutionConfiguration. + */ + SolutionConfiguration get(String resourceUri, String solutionConfiguration); + + /** + * Delete a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteByResourceGroupWithResponse(String resourceUri, String solutionConfiguration, Context context); + + /** + * Delete a SolutionConfiguration. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteByResourceGroup(String resourceUri, String solutionConfiguration); + + /** + * List SolutionConfiguration resources by parent. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionConfiguration list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable list(String resourceUri); + + /** + * List SolutionConfiguration resources by parent. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionConfiguration list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable list(String resourceUri, Context context); + + /** + * Trigger immediate sync with source cloud. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + OperationStatusResult syncNow(String resourceUri, String solutionConfiguration); + + /** + * Trigger immediate sync with source cloud. + * + * @param resourceUri The fully qualified Azure Resource manager identifier of the resource. + * @param solutionConfiguration Represent Solution Configuration Resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + OperationStatusResult syncNow(String resourceUri, String solutionConfiguration, Context context); + + /** + * Get a SolutionConfiguration. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SolutionConfiguration along with {@link Response}. + */ + SolutionConfiguration getById(String id); + + /** + * Get a SolutionConfiguration. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SolutionConfiguration along with {@link Response}. + */ + Response getByIdWithResponse(String id, Context context); + + /** + * Delete a SolutionConfiguration. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteById(String id); + + /** + * Delete a SolutionConfiguration. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteByIdWithResponse(String id, Context context); + + /** + * Begins definition for a new SolutionConfiguration resource. + * + * @param name resource name. + * @return the first stage of the new SolutionConfiguration definition. + */ + SolutionConfiguration.DefinitionStages.Blank define(String name); +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionSettings.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionSettings.java new file mode 100644 index 000000000000..2e82aa6a1a68 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionSettings.java @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.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.LinkedHashMap; +import java.util.Map; + +/** + * Solution settings. + */ +@Fluent +public final class SolutionSettings implements JsonSerializable { + /* + * Solution settings + */ + private Map additionalProperties; + + /** + * Creates an instance of SolutionSettings class. + */ + public SolutionSettings() { + } + + /** + * Get the additionalProperties property: Solution settings. + * + * @return the additionalProperties value. + */ + public Map additionalProperties() { + return this.additionalProperties; + } + + /** + * Set the additionalProperties property: Solution settings. + * + * @param additionalProperties the additionalProperties value to set. + * @return the SolutionSettings object itself. + */ + public SolutionSettings withAdditionalProperties(Map additionalProperties) { + this.additionalProperties = additionalProperties; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + if (additionalProperties != null) { + for (Map.Entry additionalProperty : additionalProperties.entrySet()) { + jsonWriter.writeUntypedField(additionalProperty.getKey(), additionalProperty.getValue()); + } + } + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SolutionSettings from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SolutionSettings 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 SolutionSettings. + */ + public static SolutionSettings fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SolutionSettings deserializedSolutionSettings = new SolutionSettings(); + Map additionalProperties = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if (additionalProperties == null) { + additionalProperties = new LinkedHashMap<>(); + } + + additionalProperties.put(fieldName, reader.getString()); + } + deserializedSolutionSettings.additionalProperties = additionalProperties; + + return deserializedSolutionSettings; + }); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionTypeProperties.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionTypeProperties.java new file mode 100644 index 000000000000..f492a05e0b09 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionTypeProperties.java @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.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; +import java.util.List; + +/** + * Definition of Solution type resource. + */ +@Immutable +public final class SolutionTypeProperties implements JsonSerializable { + /* + * The name of the solution type. + */ + private String solutionType; + + /* + * Short description of solution type. + */ + private String description; + + /* + * The locations this solution is supported in. + */ + private List supportedAzureRegions; + + /* + * Array of solution settings and its description. + */ + private List solutionSettings; + + /** + * Creates an instance of SolutionTypeProperties class. + */ + private SolutionTypeProperties() { + } + + /** + * Get the solutionType property: The name of the solution type. + * + * @return the solutionType value. + */ + public String solutionType() { + return this.solutionType; + } + + /** + * Get the description property: Short description of solution type. + * + * @return the description value. + */ + public String description() { + return this.description; + } + + /** + * Get the supportedAzureRegions property: The locations this solution is supported in. + * + * @return the supportedAzureRegions value. + */ + public List supportedAzureRegions() { + return this.supportedAzureRegions; + } + + /** + * Get the solutionSettings property: Array of solution settings and its description. + * + * @return the solutionSettings value. + */ + public List solutionSettings() { + return this.solutionSettings; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (solutionSettings() != null) { + solutionSettings().forEach(e -> e.validate()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("solutionType", this.solutionType); + jsonWriter.writeStringField("description", this.description); + jsonWriter.writeArrayField("supportedAzureRegions", this.supportedAzureRegions, + (writer, element) -> writer.writeString(element)); + jsonWriter.writeArrayField("solutionSettings", this.solutionSettings, + (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SolutionTypeProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SolutionTypeProperties 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 SolutionTypeProperties. + */ + public static SolutionTypeProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SolutionTypeProperties deserializedSolutionTypeProperties = new SolutionTypeProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("solutionType".equals(fieldName)) { + deserializedSolutionTypeProperties.solutionType = reader.getString(); + } else if ("description".equals(fieldName)) { + deserializedSolutionTypeProperties.description = reader.getString(); + } else if ("supportedAzureRegions".equals(fieldName)) { + List supportedAzureRegions = reader.readArray(reader1 -> reader1.getString()); + deserializedSolutionTypeProperties.supportedAzureRegions = supportedAzureRegions; + } else if ("solutionSettings".equals(fieldName)) { + List solutionSettings + = reader.readArray(reader1 -> SolutionTypeSettingsProperties.fromJson(reader1)); + deserializedSolutionTypeProperties.solutionSettings = solutionSettings; + } else { + reader.skipChildren(); + } + } + + return deserializedSolutionTypeProperties; + }); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionTypeResource.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionTypeResource.java new file mode 100644 index 000000000000..b22e39274215 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionTypeResource.java @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.models; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.SolutionTypeResourceInner; + +/** + * An immutable client-side representation of SolutionTypeResource. + */ +public interface SolutionTypeResource { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + SolutionTypeProperties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.hybridconnectivity.fluent.models.SolutionTypeResourceInner object. + * + * @return the inner object. + */ + SolutionTypeResourceInner innerModel(); +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionTypeSettings.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionTypeSettings.java new file mode 100644 index 000000000000..fe552bcc02e5 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionTypeSettings.java @@ -0,0 +1,133 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +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 properties of Solution Type. + */ +@Fluent +public final class SolutionTypeSettings implements JsonSerializable { + /* + * The type of the solution + */ + private String solutionType; + + /* + * Solution settings + */ + private SolutionSettings solutionSettings; + + /** + * Creates an instance of SolutionTypeSettings class. + */ + public SolutionTypeSettings() { + } + + /** + * Get the solutionType property: The type of the solution. + * + * @return the solutionType value. + */ + public String solutionType() { + return this.solutionType; + } + + /** + * Set the solutionType property: The type of the solution. + * + * @param solutionType the solutionType value to set. + * @return the SolutionTypeSettings object itself. + */ + public SolutionTypeSettings withSolutionType(String solutionType) { + this.solutionType = solutionType; + return this; + } + + /** + * Get the solutionSettings property: Solution settings. + * + * @return the solutionSettings value. + */ + public SolutionSettings solutionSettings() { + return this.solutionSettings; + } + + /** + * Set the solutionSettings property: Solution settings. + * + * @param solutionSettings the solutionSettings value to set. + * @return the SolutionTypeSettings object itself. + */ + public SolutionTypeSettings withSolutionSettings(SolutionSettings solutionSettings) { + this.solutionSettings = solutionSettings; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (solutionType() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property solutionType in model SolutionTypeSettings")); + } + if (solutionSettings() != null) { + solutionSettings().validate(); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(SolutionTypeSettings.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("solutionType", this.solutionType); + jsonWriter.writeJsonField("solutionSettings", this.solutionSettings); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SolutionTypeSettings from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SolutionTypeSettings 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 SolutionTypeSettings. + */ + public static SolutionTypeSettings fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SolutionTypeSettings deserializedSolutionTypeSettings = new SolutionTypeSettings(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("solutionType".equals(fieldName)) { + deserializedSolutionTypeSettings.solutionType = reader.getString(); + } else if ("solutionSettings".equals(fieldName)) { + deserializedSolutionTypeSettings.solutionSettings = SolutionSettings.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedSolutionTypeSettings; + }); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionTypeSettingsProperties.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionTypeSettingsProperties.java new file mode 100644 index 000000000000..53c36b2085e6 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionTypeSettingsProperties.java @@ -0,0 +1,205 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.logging.ClientLogger; +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; + +/** + * Represent Solution settings properties description array. + */ +@Immutable +public final class SolutionTypeSettingsProperties implements JsonSerializable { + /* + * The name of the solution setting property. + */ + private String name; + + /* + * The UI friendly name of the solution setting property. + */ + private String displayName; + + /* + * Type of the solution setting property, represented as a string. + */ + private String type; + + /* + * Description of solution setting property. + */ + private String description; + + /* + * Array of allowed values for this solution settings property. + */ + private List allowedValues; + + /* + * Default value for this solution settings property. + */ + private String defaultValue; + + /** + * Creates an instance of SolutionTypeSettingsProperties class. + */ + private SolutionTypeSettingsProperties() { + } + + /** + * Get the name property: The name of the solution setting property. + * + * @return the name value. + */ + public String name() { + return this.name; + } + + /** + * Get the displayName property: The UI friendly name of the solution setting property. + * + * @return the displayName value. + */ + public String displayName() { + return this.displayName; + } + + /** + * Get the type property: Type of the solution setting property, represented as a string. + * + * @return the type value. + */ + public String type() { + return this.type; + } + + /** + * Get the description property: Description of solution setting property. + * + * @return the description value. + */ + public String description() { + return this.description; + } + + /** + * Get the allowedValues property: Array of allowed values for this solution settings property. + * + * @return the allowedValues value. + */ + public List allowedValues() { + return this.allowedValues; + } + + /** + * Get the defaultValue property: Default value for this solution settings property. + * + * @return the defaultValue value. + */ + public String defaultValue() { + return this.defaultValue; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (name() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property name in model SolutionTypeSettingsProperties")); + } + if (displayName() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property displayName in model SolutionTypeSettingsProperties")); + } + if (type() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property type in model SolutionTypeSettingsProperties")); + } + if (description() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property description in model SolutionTypeSettingsProperties")); + } + if (allowedValues() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property allowedValues in model SolutionTypeSettingsProperties")); + } + if (defaultValue() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property defaultValue in model SolutionTypeSettingsProperties")); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(SolutionTypeSettingsProperties.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("displayName", this.displayName); + jsonWriter.writeStringField("type", this.type); + jsonWriter.writeStringField("description", this.description); + jsonWriter.writeArrayField("allowedValues", this.allowedValues, + (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("defaultValue", this.defaultValue); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SolutionTypeSettingsProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SolutionTypeSettingsProperties 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 SolutionTypeSettingsProperties. + */ + public static SolutionTypeSettingsProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SolutionTypeSettingsProperties deserializedSolutionTypeSettingsProperties + = new SolutionTypeSettingsProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("name".equals(fieldName)) { + deserializedSolutionTypeSettingsProperties.name = reader.getString(); + } else if ("displayName".equals(fieldName)) { + deserializedSolutionTypeSettingsProperties.displayName = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedSolutionTypeSettingsProperties.type = reader.getString(); + } else if ("description".equals(fieldName)) { + deserializedSolutionTypeSettingsProperties.description = reader.getString(); + } else if ("allowedValues".equals(fieldName)) { + List allowedValues = reader.readArray(reader1 -> reader1.getString()); + deserializedSolutionTypeSettingsProperties.allowedValues = allowedValues; + } else if ("defaultValue".equals(fieldName)) { + deserializedSolutionTypeSettingsProperties.defaultValue = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedSolutionTypeSettingsProperties; + }); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionTypes.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionTypes.java new file mode 100644 index 000000000000..5b192d7219dc --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/SolutionTypes.java @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of SolutionTypes. + */ +public interface SolutionTypes { + /** + * Get a SolutionTypeResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param solutionType Solution Type resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SolutionTypeResource along with {@link Response}. + */ + Response getByResourceGroupWithResponse(String resourceGroupName, String solutionType, + Context context); + + /** + * Get a SolutionTypeResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param solutionType Solution Type resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SolutionTypeResource. + */ + SolutionTypeResource getByResourceGroup(String resourceGroupName, String solutionType); + + /** + * List SolutionTypeResource resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionTypeResource list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByResourceGroup(String resourceGroupName); + + /** + * List SolutionTypeResource resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionTypeResource list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByResourceGroup(String resourceGroupName, Context context); + + /** + * List SolutionTypeResource resources by subscription ID. + * + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionTypeResource list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable list(); + + /** + * List SolutionTypeResource resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SolutionTypeResource list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable list(Context context); +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/Type.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/Type.java index f8763a4cd4e2..9a0ac44b1c92 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/Type.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/Type.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.models; diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/package-info.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/package-info.java index 14ddfc473818..6ce6280d6a1e 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/package-info.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/models/package-info.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. /** - * Package containing the data models for HybridConnectivityManagementApi. - * REST API for Hybrid Connectivity. + * Package containing the data models for HybridConnectivity. + * REST API for public clouds. */ package com.azure.resourcemanager.hybridconnectivity.models; diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/package-info.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/package-info.java index 1bd401a1fd87..c3ee3f0630f7 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/package-info.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/com/azure/resourcemanager/hybridconnectivity/package-info.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. /** - * Package containing the classes for HybridConnectivityManagementApi. - * REST API for Hybrid Connectivity. + * Package containing the classes for HybridConnectivity. + * REST API for public clouds. */ package com.azure.resourcemanager.hybridconnectivity; diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/module-info.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/module-info.java index a95a678626d6..eaa43c9c09d3 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/module-info.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/java/module-info.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. module com.azure.resourcemanager.hybridconnectivity { requires transitive com.azure.core.management; @@ -12,4 +12,5 @@ opens com.azure.resourcemanager.hybridconnectivity.fluent.models to com.azure.core; opens com.azure.resourcemanager.hybridconnectivity.models to com.azure.core; + opens com.azure.resourcemanager.hybridconnectivity.implementation.models to com.azure.core; } diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-hybridconnectivity/proxy-config.json b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-hybridconnectivity/proxy-config.json index 505c27f4c42c..958c91562fd4 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-hybridconnectivity/proxy-config.json +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-hybridconnectivity/proxy-config.json @@ -1 +1 @@ -[["com.azure.resourcemanager.hybridconnectivity.implementation.EndpointsClientImpl$EndpointsService"],["com.azure.resourcemanager.hybridconnectivity.implementation.OperationsClientImpl$OperationsService"],["com.azure.resourcemanager.hybridconnectivity.implementation.ServiceConfigurationsClientImpl$ServiceConfigurationsService"]] \ No newline at end of file +[["com.azure.resourcemanager.hybridconnectivity.implementation.EndpointsClientImpl$EndpointsService"],["com.azure.resourcemanager.hybridconnectivity.implementation.GenerateAwsTemplatesClientImpl$GenerateAwsTemplatesService"],["com.azure.resourcemanager.hybridconnectivity.implementation.InventoriesClientImpl$InventoriesService"],["com.azure.resourcemanager.hybridconnectivity.implementation.OperationsClientImpl$OperationsService"],["com.azure.resourcemanager.hybridconnectivity.implementation.PublicCloudConnectorsClientImpl$PublicCloudConnectorsService"],["com.azure.resourcemanager.hybridconnectivity.implementation.ServiceConfigurationsClientImpl$ServiceConfigurationsService"],["com.azure.resourcemanager.hybridconnectivity.implementation.SolutionConfigurationsClientImpl$SolutionConfigurationsService"],["com.azure.resourcemanager.hybridconnectivity.implementation.SolutionTypesClientImpl$SolutionTypesService"]] \ No newline at end of file diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/resources/azure-resourcemanager-hybridconnectivity.properties b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/resources/azure-resourcemanager-hybridconnectivity.properties new file mode 100644 index 000000000000..defbd48204e4 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/main/resources/azure-resourcemanager-hybridconnectivity.properties @@ -0,0 +1 @@ +version=${project.version} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsCreateOrUpdateSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsCreateOrUpdateSamples.java index 88f45fa82310..837987915a58 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsCreateOrUpdateSamples.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsCreateOrUpdateSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; @@ -12,9 +12,7 @@ */ public final class EndpointsCreateOrUpdateSamples { /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * EndpointsPutCustom.json + * x-ms-original-file: 2024-12-01/EndpointsPutCustom.json */ /** * Sample code: HybridConnectivityEndpointsPutCustom. @@ -34,9 +32,7 @@ public static void hybridConnectivityEndpointsPutCustom( } /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * EndpointsPutDefault.json + * x-ms-original-file: 2024-12-01/EndpointsPutDefault.json */ /** * Sample code: HybridConnectivityEndpointsPutDefault. diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsDeleteSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsDeleteSamples.java index 58ac0a4832bf..737a26f35ab4 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsDeleteSamples.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsDeleteSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; @@ -9,9 +9,7 @@ */ public final class EndpointsDeleteSamples { /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * EndpointsDeleteDefault.json + * x-ms-original-file: 2024-12-01/EndpointsDeleteDefault.json */ /** * Sample code: HybridConnectivityEndpointsDeleteDefault. diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsGetSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsGetSamples.java index 70daa2ec4327..f11d469cdad0 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsGetSamples.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsGetSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; @@ -9,9 +9,7 @@ */ public final class EndpointsGetSamples { /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * EndpointsGetDefault.json + * x-ms-original-file: 2024-12-01/EndpointsGetDefault.json */ /** * Sample code: HybridConnectivityEndpointsGetDefault. @@ -27,9 +25,7 @@ public static void hybridConnectivityEndpointsGetDefault( } /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * EndpointsGetCustom.json + * x-ms-original-file: 2024-12-01/EndpointsGetCustom.json */ /** * Sample code: HybridConnectivityEndpointsGetCustom. diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsListCredentialsSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsListCredentialsSamples.java index ec0144f177ec..3e158198d7f9 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsListCredentialsSamples.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsListCredentialsSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; @@ -12,9 +12,7 @@ */ public final class EndpointsListCredentialsSamples { /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * EndpointsPostListCredentials.json + * x-ms-original-file: 2024-12-01/EndpointsPostListCredentials.json */ /** * Sample code: HybridConnectivityEndpointsPostListCredentials. diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsListIngressGatewayCredentialsSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsListIngressGatewayCredentialsSamples.java index 22071a54731f..cdddb542c6f0 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsListIngressGatewayCredentialsSamples.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsListIngressGatewayCredentialsSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; @@ -9,9 +9,7 @@ */ public final class EndpointsListIngressGatewayCredentialsSamples { /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * EndpointsPostListIngressGatewayCredentials.json + * x-ms-original-file: 2024-12-01/EndpointsPostListIngressGatewayCredentials.json */ /** * Sample code: HybridConnectivityEndpointsPostListIngressGatewayCredentials. diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsListManagedProxyDetailsSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsListManagedProxyDetailsSamples.java index 6b5f35c1a9af..056d89afc5bd 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsListManagedProxyDetailsSamples.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsListManagedProxyDetailsSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; @@ -12,9 +12,7 @@ */ public final class EndpointsListManagedProxyDetailsSamples { /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * EndpointsPostListManagedProxyDetails.json + * x-ms-original-file: 2024-12-01/EndpointsPostListManagedProxyDetails.json */ /** * Sample code: HybridConnectivityEndpointsPostListManagedProxyDetails. diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsListSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsListSamples.java index 7fa3d4eee27f..1f4d9cda0acf 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsListSamples.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsListSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; @@ -9,9 +9,7 @@ */ public final class EndpointsListSamples { /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * EndpointsList.json + * x-ms-original-file: 2024-12-01/EndpointsList.json */ /** * Sample code: HybridConnectivityEndpointsGet. diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsUpdateSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsUpdateSamples.java index 1da067d9da22..c669efc228b7 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsUpdateSamples.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsUpdateSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; @@ -13,9 +13,7 @@ */ public final class EndpointsUpdateSamples { /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * EndpointsPatchDefault.json + * x-ms-original-file: 2024-12-01/EndpointsPatchDefault.json */ /** * Sample code: HybridConnectivityEndpointsPatchDefault. diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/GenerateAwsTemplatePostSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/GenerateAwsTemplatePostSamples.java new file mode 100644 index 000000000000..8f569a8db86e --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/GenerateAwsTemplatePostSamples.java @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.resourcemanager.hybridconnectivity.models.GenerateAwsTemplateRequest; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionSettings; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionTypeSettings; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * Samples for GenerateAwsTemplate Post. + */ +public final class GenerateAwsTemplatePostSamples { + /* + * x-ms-original-file: 2024-12-01/GenerateAwsTemplate_Post.json + */ + /** + * Sample code: GenerateAwsTemplate_Post. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void + generateAwsTemplatePost(com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.generateAwsTemplates() + .postWithResponse( + new GenerateAwsTemplateRequest().withConnectorId("pnxcfjidglabnwxit") + .withSolutionTypes(Arrays.asList(new SolutionTypeSettings().withSolutionType("hjyownzpfxwiufmd") + .withSolutionSettings(new SolutionSettings().withAdditionalProperties(mapOf())))), + com.azure.core.util.Context.NONE); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/InventoryGetSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/InventoryGetSamples.java new file mode 100644 index 000000000000..0ac2cc657b5a --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/InventoryGetSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +/** + * Samples for Inventory Get. + */ +public final class InventoryGetSamples { + /* + * x-ms-original-file: 2024-12-01/Inventory_Get.json + */ + /** + * Sample code: Inventory_Get. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void inventoryGet(com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.inventories() + .getWithResponse("ymuj", "zarfsraogroxlaqjjnwixtn", "xofprmcboosrbd", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/InventoryListBySolutionConfigurationSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/InventoryListBySolutionConfigurationSamples.java new file mode 100644 index 000000000000..d721efdc05fe --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/InventoryListBySolutionConfigurationSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +/** + * Samples for Inventory ListBySolutionConfiguration. + */ +public final class InventoryListBySolutionConfigurationSamples { + /* + * x-ms-original-file: 2024-12-01/Inventory_ListBySolutionConfiguration.json + */ + /** + * Sample code: Inventory_ListBySolutionConfiguration. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void inventoryListBySolutionConfiguration( + com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.inventories().listBySolutionConfiguration("ymuj", "wsxt", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/OperationsListSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/OperationsListSamples.java index d4978d29e288..cf13aad39e93 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/OperationsListSamples.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/OperationsListSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; @@ -9,9 +9,7 @@ */ public final class OperationsListSamples { /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * OperationsList.json + * x-ms-original-file: 2024-12-01/OperationsList.json */ /** * Sample code: HybridConnectivityOperationsList. diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsCreateOrUpdateSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsCreateOrUpdateSamples.java new file mode 100644 index 000000000000..c549e8bc5cf3 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsCreateOrUpdateSamples.java @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.resourcemanager.hybridconnectivity.models.AwsCloudProfile; +import com.azure.resourcemanager.hybridconnectivity.models.HostType; +import com.azure.resourcemanager.hybridconnectivity.models.PublicCloudConnectorProperties; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * Samples for PublicCloudConnectors CreateOrUpdate. + */ +public final class PublicCloudConnectorsCreateOrUpdateSamples { + /* + * x-ms-original-file: 2024-12-01/PublicCloudConnectors_CreateOrUpdate.json + */ + /** + * Sample code: PublicCloudConnectors_CreateOrUpdate. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void publicCloudConnectorsCreateOrUpdate( + com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.publicCloudConnectors() + .define("advjwoakdusalamomg") + .withRegion("jpiglusfxynfcewcjwvvnn") + .withExistingResourceGroup("rgpublicCloud") + .withTags(mapOf()) + .withProperties(new PublicCloudConnectorProperties() + .withAwsCloudProfile(new AwsCloudProfile().withAccountId("snbnuxckevyqpm") + .withExcludedAccounts(Arrays.asList("rwgqpukglvbqmogqcliqolucp")) + .withIsOrganizationalAccount(true)) + .withHostType(HostType.AWS)) + .create(); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsDeleteSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsDeleteSamples.java new file mode 100644 index 000000000000..46016a19193e --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsDeleteSamples.java @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +/** + * Samples for PublicCloudConnectors Delete. + */ +public final class PublicCloudConnectorsDeleteSamples { + /* + * x-ms-original-file: 2024-12-01/PublicCloudConnectors_Delete.json + */ + /** + * Sample code: PublicCloudConnectors_Delete. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void + publicCloudConnectorsDelete(com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.publicCloudConnectors() + .deleteByResourceGroupWithResponse("rgpublicCloud", "skcfyjvflkhibdywjay", + com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsGetByResourceGroupSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsGetByResourceGroupSamples.java new file mode 100644 index 000000000000..4fd95a71ce04 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsGetByResourceGroupSamples.java @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +/** + * Samples for PublicCloudConnectors GetByResourceGroup. + */ +public final class PublicCloudConnectorsGetByResourceGroupSamples { + /* + * x-ms-original-file: 2024-12-01/PublicCloudConnectors_Get.json + */ + /** + * Sample code: PublicCloudConnectors_Get. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void + publicCloudConnectorsGet(com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.publicCloudConnectors() + .getByResourceGroupWithResponse("rgpublicCloud", "rzygvnpsnrdylwzdbsscjazvamyxmh", + com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsListByResourceGroupSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsListByResourceGroupSamples.java new file mode 100644 index 000000000000..1576b5aa647f --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsListByResourceGroupSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +/** + * Samples for PublicCloudConnectors ListByResourceGroup. + */ +public final class PublicCloudConnectorsListByResourceGroupSamples { + /* + * x-ms-original-file: 2024-12-01/PublicCloudConnectors_ListByResourceGroup.json + */ + /** + * Sample code: PublicCloudConnectors_ListByResourceGroup. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void publicCloudConnectorsListByResourceGroup( + com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.publicCloudConnectors().listByResourceGroup("rgpublicCloud", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsListSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsListSamples.java new file mode 100644 index 000000000000..d9a4b2f7f823 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsListSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +/** + * Samples for PublicCloudConnectors List. + */ +public final class PublicCloudConnectorsListSamples { + /* + * x-ms-original-file: 2024-12-01/PublicCloudConnectors_ListBySubscription.json + */ + /** + * Sample code: PublicCloudConnectors_ListBySubscription. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void publicCloudConnectorsListBySubscription( + com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.publicCloudConnectors().list(com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsTestPermissionsSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsTestPermissionsSamples.java new file mode 100644 index 000000000000..19344a13dc02 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsTestPermissionsSamples.java @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +/** + * Samples for PublicCloudConnectors TestPermissions. + */ +public final class PublicCloudConnectorsTestPermissionsSamples { + /* + * x-ms-original-file: 2024-12-01/PublicCloudConnectors_TestPermissions.json + */ + /** + * Sample code: PublicCloudConnectors_TestPermissions. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void publicCloudConnectorsTestPermissions( + com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.publicCloudConnectors() + .testPermissions("rgpublicCloud", "rzygvnpsnrdylwzdbsscjazvamyxmh", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsUpdateSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsUpdateSamples.java new file mode 100644 index 000000000000..073c11dadca0 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsUpdateSamples.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.resourcemanager.hybridconnectivity.models.AwsCloudProfile; +import com.azure.resourcemanager.hybridconnectivity.models.PublicCloudConnector; +import com.azure.resourcemanager.hybridconnectivity.models.PublicCloudConnectorProperties; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * Samples for PublicCloudConnectors Update. + */ +public final class PublicCloudConnectorsUpdateSamples { + /* + * x-ms-original-file: 2024-12-01/PublicCloudConnectors_Update.json + */ + /** + * Sample code: PublicCloudConnectors_Update. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void + publicCloudConnectorsUpdate(com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + PublicCloudConnector resource = manager.publicCloudConnectors() + .getByResourceGroupWithResponse("rgpublicCloud", "svtirlbyqpepbzyessjenlueeznhg", + com.azure.core.util.Context.NONE) + .getValue(); + resource.update() + .withTags(mapOf()) + .withProperties(new PublicCloudConnectorProperties() + .withAwsCloudProfile(new AwsCloudProfile().withExcludedAccounts(Arrays.asList("zrbtd")))) + .apply(); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsCreateOrupdateSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsCreateOrupdateSamples.java index fc090aeb1a18..1290ee2e619c 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsCreateOrupdateSamples.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsCreateOrupdateSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; @@ -11,9 +11,7 @@ */ public final class ServiceConfigurationsCreateOrupdateSamples { /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * ServiceConfigurationsPutWAC.json + * x-ms-original-file: 2024-12-01/ServiceConfigurationsPutWAC.json */ /** * Sample code: ServiceConfigurationsPutWAC. @@ -33,9 +31,7 @@ public final class ServiceConfigurationsCreateOrupdateSamples { } /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * ServiceConfigurationsPutSSH.json + * x-ms-original-file: 2024-12-01/ServiceConfigurationsPutSSH.json */ /** * Sample code: ServiceConfigurationsPutSSH. diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsDeleteSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsDeleteSamples.java index 14c076621920..0b049de5ce74 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsDeleteSamples.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsDeleteSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; @@ -9,9 +9,7 @@ */ public final class ServiceConfigurationsDeleteSamples { /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * ServiceConfigurationsDeleteSSH.json + * x-ms-original-file: 2024-12-01/ServiceConfigurationsDeleteSSH.json */ /** * Sample code: ServiceConfigurationsDeleteSSH. diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsGetSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsGetSamples.java index c4823ce4012d..5ad94fa877eb 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsGetSamples.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsGetSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; @@ -9,9 +9,7 @@ */ public final class ServiceConfigurationsGetSamples { /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * ServiceConfigurationsGetWAC.json + * x-ms-original-file: 2024-12-01/ServiceConfigurationsGetWAC.json */ /** * Sample code: HybridConnectivityEndpointsServiceconfigurationsGetWAC. @@ -27,9 +25,7 @@ public static void hybridConnectivityEndpointsServiceconfigurationsGetWAC( } /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * ServiceConfigurationsGetSSH.json + * x-ms-original-file: 2024-12-01/ServiceConfigurationsGetSSH.json */ /** * Sample code: HybridConnectivityEndpointsServiceconfigurationsGetSSH. diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsListByEndpointResourceSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsListByEndpointResourceSamples.java index c7ef7257e311..4cb4db565bfc 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsListByEndpointResourceSamples.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsListByEndpointResourceSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; @@ -9,9 +9,7 @@ */ public final class ServiceConfigurationsListByEndpointResourceSamples { /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * ServiceConfigurationsList.json + * x-ms-original-file: 2024-12-01/ServiceConfigurationsList.json */ /** * Sample code: GetClustersExample. diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsUpdateSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsUpdateSamples.java index bb5d73c521fc..892ed1ebbca2 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsUpdateSamples.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsUpdateSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; @@ -11,9 +11,7 @@ */ public final class ServiceConfigurationsUpdateSamples { /* - * x-ms-original-file: - * specification/hybridconnectivity/resource-manager/Microsoft.HybridConnectivity/stable/2023-03-15/examples/ - * ServiceConfigurationsPatchSSH.json + * x-ms-original-file: 2024-12-01/ServiceConfigurationsPatchSSH.json */ /** * Sample code: ServiceConfigurationsPatchSSH. diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsCreateOrUpdateSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsCreateOrUpdateSamples.java new file mode 100644 index 000000000000..0844d06be360 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsCreateOrUpdateSamples.java @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.resourcemanager.hybridconnectivity.models.SolutionConfigurationProperties; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionSettings; +import java.util.HashMap; +import java.util.Map; + +/** + * Samples for SolutionConfigurations CreateOrUpdate. + */ +public final class SolutionConfigurationsCreateOrUpdateSamples { + /* + * x-ms-original-file: 2024-12-01/SolutionConfigurations_CreateOrUpdate.json + */ + /** + * Sample code: SolutionConfigurations_CreateOrUpdate. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void solutionConfigurationsCreateOrUpdate( + com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.solutionConfigurations() + .define("keebwujt") + .withExistingResourceUri("ymuj") + .withProperties(new SolutionConfigurationProperties().withSolutionType("nmtqllkyohwtsthxaimsye") + .withSolutionSettings(new SolutionSettings().withAdditionalProperties(mapOf()))) + .create(); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsDeleteSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsDeleteSamples.java new file mode 100644 index 000000000000..aec4a6ef13dd --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsDeleteSamples.java @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +/** + * Samples for SolutionConfigurations Delete. + */ +public final class SolutionConfigurationsDeleteSamples { + /* + * x-ms-original-file: 2024-12-01/SolutionConfigurations_Delete.json + */ + /** + * Sample code: SolutionConfigurations_Delete. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void + solutionConfigurationsDelete(com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.solutionConfigurations() + .deleteByResourceGroupWithResponse("ymuj", "stu", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsGetSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsGetSamples.java new file mode 100644 index 000000000000..32cebf524f6b --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsGetSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +/** + * Samples for SolutionConfigurations Get. + */ +public final class SolutionConfigurationsGetSamples { + /* + * x-ms-original-file: 2024-12-01/SolutionConfigurations_Get.json + */ + /** + * Sample code: SolutionConfigurations_Get. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void + solutionConfigurationsGet(com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.solutionConfigurations().getWithResponse("ymuj", "tks", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsListSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsListSamples.java new file mode 100644 index 000000000000..6f560d2c5063 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsListSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +/** + * Samples for SolutionConfigurations List. + */ +public final class SolutionConfigurationsListSamples { + /* + * x-ms-original-file: 2024-12-01/SolutionConfigurations_List.json + */ + /** + * Sample code: SolutionConfigurations_List. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void + solutionConfigurationsList(com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.solutionConfigurations().list("ymuj", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsSyncNowSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsSyncNowSamples.java new file mode 100644 index 000000000000..769eab60830f --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsSyncNowSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +/** + * Samples for SolutionConfigurations SyncNow. + */ +public final class SolutionConfigurationsSyncNowSamples { + /* + * x-ms-original-file: 2024-12-01/SolutionConfigurations_SyncNow.json + */ + /** + * Sample code: SolutionConfigurations_SyncNow. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void + solutionConfigurationsSyncNow(com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.solutionConfigurations().syncNow("ymuj", "tks", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsUpdateSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsUpdateSamples.java new file mode 100644 index 000000000000..09d8cb028cc0 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsUpdateSamples.java @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.resourcemanager.hybridconnectivity.models.SolutionConfiguration; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionConfigurationProperties; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionSettings; +import java.util.HashMap; +import java.util.Map; + +/** + * Samples for SolutionConfigurations Update. + */ +public final class SolutionConfigurationsUpdateSamples { + /* + * x-ms-original-file: 2024-12-01/SolutionConfigurations_Update.json + */ + /** + * Sample code: SolutionConfigurations_Update. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void + solutionConfigurationsUpdate(com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + SolutionConfiguration resource = manager.solutionConfigurations() + .getWithResponse("ymuj", "dxt", com.azure.core.util.Context.NONE) + .getValue(); + resource.update() + .withProperties(new SolutionConfigurationProperties().withSolutionType("myzljlstvmgkp") + .withSolutionSettings(new SolutionSettings().withAdditionalProperties(mapOf()))) + .apply(); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypesGetByResourceGroupSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypesGetByResourceGroupSamples.java new file mode 100644 index 000000000000..4f2a63534989 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypesGetByResourceGroupSamples.java @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +/** + * Samples for SolutionTypes GetByResourceGroup. + */ +public final class SolutionTypesGetByResourceGroupSamples { + /* + * x-ms-original-file: 2024-12-01/SolutionTypes_Get.json + */ + /** + * Sample code: SolutionTypes_Get. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void + solutionTypesGet(com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.solutionTypes() + .getByResourceGroupWithResponse("rgpublicCloud", "lulzqllpu", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypesListByResourceGroupSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypesListByResourceGroupSamples.java new file mode 100644 index 000000000000..a074bba19d9e --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypesListByResourceGroupSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +/** + * Samples for SolutionTypes ListByResourceGroup. + */ +public final class SolutionTypesListByResourceGroupSamples { + /* + * x-ms-original-file: 2024-12-01/SolutionTypes_ListByResourceGroup.json + */ + /** + * Sample code: SolutionTypes_ListByResourceGroup. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void solutionTypesListByResourceGroup( + com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.solutionTypes().listByResourceGroup("rgpublicCloud", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypesListSamples.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypesListSamples.java new file mode 100644 index 000000000000..c9d34cfc970e --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/samples/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypesListSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +/** + * Samples for SolutionTypes List. + */ +public final class SolutionTypesListSamples { + /* + * x-ms-original-file: 2024-12-01/SolutionTypes_ListBySubscription.json + */ + /** + * Sample code: SolutionTypes_ListBySubscription. + * + * @param manager Entry point to HybridConnectivityManager. + */ + public static void solutionTypesListBySubscription( + com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager manager) { + manager.solutionTypes().list(com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/AADProfilePropertiesTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/AADProfilePropertiesTests.java new file mode 100644 index 000000000000..b774e10940fa --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/AADProfilePropertiesTests.java @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.AADProfileProperties; +import org.junit.jupiter.api.Assertions; + +public final class AADProfilePropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AADProfileProperties model = BinaryData.fromString("{\"serverId\":\"qtrgqjbpfzfsinzg\",\"tenantId\":\"f\"}") + .toObject(AADProfileProperties.class); + Assertions.assertEquals("qtrgqjbpfzfsinzg", model.serverId()); + Assertions.assertEquals("f", model.tenantId()); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/AadProfilePropertiesTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/AadProfilePropertiesTests.java deleted file mode 100644 index 792e5f976820..000000000000 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/AadProfilePropertiesTests.java +++ /dev/null @@ -1,27 +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.resourcemanager.hybridconnectivity.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.hybridconnectivity.fluent.models.AadProfileProperties; -import org.junit.jupiter.api.Assertions; - -public final class AadProfilePropertiesTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - AadProfileProperties model = BinaryData.fromString("{\"serverId\":\"czdzev\",\"tenantId\":\"dhkrwpdappdsbdk\"}") - .toObject(AadProfileProperties.class); - Assertions.assertEquals("czdzev", model.serverId()); - Assertions.assertEquals("dhkrwpdappdsbdk", model.tenantId()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - AadProfileProperties model = new AadProfileProperties().withServerId("czdzev").withTenantId("dhkrwpdappdsbdk"); - model = BinaryData.fromObject(model).toObject(AadProfileProperties.class); - Assertions.assertEquals("czdzev", model.serverId()); - Assertions.assertEquals("dhkrwpdappdsbdk", model.tenantId()); - } -} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/AwsCloudProfileTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/AwsCloudProfileTests.java new file mode 100644 index 000000000000..d1ae9384eb7d --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/AwsCloudProfileTests.java @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.hybridconnectivity.models.AwsCloudProfile; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class AwsCloudProfileTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AwsCloudProfile model = BinaryData.fromString( + "{\"accountId\":\"i\",\"excludedAccounts\":[\"npvswjdkirso\",\"dqxhcrmnohjtckwh\",\"soifiyipjxsqw\",\"gr\"],\"isOrganizationalAccount\":false}") + .toObject(AwsCloudProfile.class); + Assertions.assertEquals("i", model.accountId()); + Assertions.assertEquals("npvswjdkirso", model.excludedAccounts().get(0)); + Assertions.assertEquals(false, model.isOrganizationalAccount()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AwsCloudProfile model = new AwsCloudProfile().withAccountId("i") + .withExcludedAccounts(Arrays.asList("npvswjdkirso", "dqxhcrmnohjtckwh", "soifiyipjxsqw", "gr")) + .withIsOrganizationalAccount(false); + model = BinaryData.fromObject(model).toObject(AwsCloudProfile.class); + Assertions.assertEquals("i", model.accountId()); + Assertions.assertEquals("npvswjdkirso", model.excludedAccounts().get(0)); + Assertions.assertEquals(false, model.isOrganizationalAccount()); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointPropertiesTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointPropertiesTests.java index a8cbb6504127..bb9a5493dff4 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointPropertiesTests.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointPropertiesTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; @@ -13,17 +13,17 @@ public final class EndpointPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { EndpointProperties model = BinaryData - .fromString("{\"type\":\"custom\",\"resourceId\":\"dmailzydehojw\",\"provisioningState\":\"huxinpmqnj\"}") + .fromString("{\"type\":\"default\",\"resourceId\":\"ithxqhabifpi\",\"provisioningState\":\"wczbys\"}") .toObject(EndpointProperties.class); - Assertions.assertEquals(Type.CUSTOM, model.type()); - Assertions.assertEquals("dmailzydehojw", model.resourceId()); + Assertions.assertEquals(Type.DEFAULT, model.type()); + Assertions.assertEquals("ithxqhabifpi", model.resourceId()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - EndpointProperties model = new EndpointProperties().withType(Type.CUSTOM).withResourceId("dmailzydehojw"); + EndpointProperties model = new EndpointProperties().withType(Type.DEFAULT).withResourceId("ithxqhabifpi"); model = BinaryData.fromObject(model).toObject(EndpointProperties.class); - Assertions.assertEquals(Type.CUSTOM, model.type()); - Assertions.assertEquals("dmailzydehojw", model.resourceId()); + Assertions.assertEquals(Type.DEFAULT, model.type()); + Assertions.assertEquals("ithxqhabifpi", model.resourceId()); } } diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointResourceInnerTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointResourceInnerTests.java index 9ce9b62810d0..996b570e8239 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointResourceInnerTests.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointResourceInnerTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; @@ -14,18 +14,18 @@ public final class EndpointResourceInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { EndpointResourceInner model = BinaryData.fromString( - "{\"properties\":{\"type\":\"custom\",\"resourceId\":\"s\",\"provisioningState\":\"nyejhkryhtnap\"},\"id\":\"wlokjyem\",\"name\":\"kvnipjoxz\",\"type\":\"nchgej\"}") + "{\"properties\":{\"type\":\"custom\",\"resourceId\":\"bpzvgn\",\"provisioningState\":\"symglzufcyz\"},\"id\":\"hdbihan\",\"name\":\"fhfcb\",\"type\":\"y\"}") .toObject(EndpointResourceInner.class); Assertions.assertEquals(Type.CUSTOM, model.properties().type()); - Assertions.assertEquals("s", model.properties().resourceId()); + Assertions.assertEquals("bpzvgn", model.properties().resourceId()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { EndpointResourceInner model = new EndpointResourceInner() - .withProperties(new EndpointProperties().withType(Type.CUSTOM).withResourceId("s")); + .withProperties(new EndpointProperties().withType(Type.CUSTOM).withResourceId("bpzvgn")); model = BinaryData.fromObject(model).toObject(EndpointResourceInner.class); Assertions.assertEquals(Type.CUSTOM, model.properties().type()); - Assertions.assertEquals("s", model.properties().resourceId()); + Assertions.assertEquals("bpzvgn", model.properties().resourceId()); } } diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsCreateOrUpdateWithResponseMockTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsCreateOrUpdateWithResponseMockTests.java index 950d6f9abf6b..98713cc83b98 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsCreateOrUpdateWithResponseMockTests.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsCreateOrUpdateWithResponseMockTests.java @@ -1,13 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager; import com.azure.resourcemanager.hybridconnectivity.models.EndpointProperties; @@ -23,22 +23,22 @@ public final class EndpointsCreateOrUpdateWithResponseMockTests { @Test public void testCreateOrUpdateWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"type\":\"default\",\"resourceId\":\"qrimzinpv\",\"provisioningState\":\"jdkirsoodqx\"},\"id\":\"rmnohj\",\"name\":\"ckwhds\",\"type\":\"ifiyipjxsqwpgrj\"}"; + = "{\"properties\":{\"type\":\"custom\",\"resourceId\":\"dowwquuvxzxclvit\",\"provisioningState\":\"qzonosggbhcohf\"},\"id\":\"sjnkal\",\"name\":\"utiiswacf\",\"type\":\"gdkz\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); HybridConnectivityManager manager = HybridConnectivityManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); EndpointResource response = manager.endpoints() - .define("opvkmijcm") - .withExistingResourceUri("isdkfthwxmnteiw") - .withProperties(new EndpointProperties().withType(Type.DEFAULT).withResourceId("ufufsrp")) + .define("zxb") + .withExistingResourceUri("uwz") + .withProperties(new EndpointProperties().withType(Type.DEFAULT).withResourceId("jefuzmuvpbttdumo")) .create(); - Assertions.assertEquals(Type.DEFAULT, response.properties().type()); - Assertions.assertEquals("qrimzinpv", response.properties().resourceId()); + Assertions.assertEquals(Type.CUSTOM, response.properties().type()); + Assertions.assertEquals("dowwquuvxzxclvit", response.properties().resourceId()); } } diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsDeleteByResourceGroupWithResponseMockTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsDeleteByResourceGroupWithResponseMockTests.java index 834c8bbf5c57..8be41c9a9812 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsDeleteByResourceGroupWithResponseMockTests.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsDeleteByResourceGroupWithResponseMockTests.java @@ -1,13 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager; import java.nio.charset.StandardCharsets; @@ -25,10 +25,9 @@ public void testDeleteWithResponse() throws Exception { HybridConnectivityManager manager = HybridConnectivityManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); - manager.endpoints() - .deleteByResourceGroupWithResponse("rtumkdosvq", "hbmdgbbjfdd", com.azure.core.util.Context.NONE); + manager.endpoints().deleteByResourceGroupWithResponse("lqlfm", "dnbbglzps", com.azure.core.util.Context.NONE); } } diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsGetWithResponseMockTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsGetWithResponseMockTests.java index ad192a748b6c..9d435d324443 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsGetWithResponseMockTests.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsGetWithResponseMockTests.java @@ -1,13 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager; import com.azure.resourcemanager.hybridconnectivity.models.EndpointResource; @@ -22,19 +22,19 @@ public final class EndpointsGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"type\":\"custom\",\"resourceId\":\"dqytbciqfouflmm\",\"provisioningState\":\"zsm\"},\"id\":\"mglougpbkw\",\"name\":\"mutduqktaps\",\"type\":\"wgcu\"}"; + = "{\"properties\":{\"type\":\"default\",\"resourceId\":\"ndoygmifthnzdnd\",\"provisioningState\":\"gnayqigynduh\"},\"id\":\"hqlkthumaqo\",\"name\":\"bgycduiertgccym\",\"type\":\"aolps\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); HybridConnectivityManager manager = HybridConnectivityManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); EndpointResource response - = manager.endpoints().getWithResponse("gakeqsr", "yb", com.azure.core.util.Context.NONE).getValue(); + = manager.endpoints().getWithResponse("ewgdrjervn", "enq", com.azure.core.util.Context.NONE).getValue(); - Assertions.assertEquals(Type.CUSTOM, response.properties().type()); - Assertions.assertEquals("dqytbciqfouflmm", response.properties().resourceId()); + Assertions.assertEquals(Type.DEFAULT, response.properties().type()); + Assertions.assertEquals("ndoygmifthnzdnd", response.properties().resourceId()); } } diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsListManagedProxyDetailsWithResponseMockTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsListManagedProxyDetailsWithResponseMockTests.java index 7f4399eb9c28..bddc696233b3 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsListManagedProxyDetailsWithResponseMockTests.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsListManagedProxyDetailsWithResponseMockTests.java @@ -1,13 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager; import com.azure.resourcemanager.hybridconnectivity.models.ManagedProxyRequest; @@ -22,24 +22,24 @@ public final class EndpointsListManagedProxyDetailsWithResponseMockTests { @Test public void testListManagedProxyDetailsWithResponse() throws Exception { - String responseStr = "{\"proxy\":\"uht\",\"expiresOn\":6116347242940995661}"; + String responseStr = "{\"proxy\":\"otgqrlltmu\",\"expiresOn\":8105546637199671811}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); HybridConnectivityManager manager = HybridConnectivityManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); ManagedProxyResource response = manager.endpoints() - .listManagedProxyDetailsWithResponse("uitnwuiz", "a", - new ManagedProxyRequest().withService("x") - .withHostname("izuckyfihrfidfvz") - .withServiceName(ServiceName.WAC), + .listManagedProxyDetailsWithResponse("dlkzgxhuri", "lbpodxunk", + new ManagedProxyRequest().withService("ebxmubyynt") + .withHostname("rbqtkoie") + .withServiceName(ServiceName.SSH), com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("uht", response.proxy()); - Assertions.assertEquals(6116347242940995661L, response.expiresOn()); + Assertions.assertEquals("otgqrlltmu", response.proxy()); + Assertions.assertEquals(8105546637199671811L, response.expiresOn()); } } diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsListMockTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsListMockTests.java index a8b9ff8e3b44..3b1632886f9e 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsListMockTests.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsListMockTests.java @@ -1,14 +1,14 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager; import com.azure.resourcemanager.hybridconnectivity.models.EndpointResource; @@ -23,19 +23,19 @@ public final class EndpointsListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"type\":\"custom\",\"resourceId\":\"kgiawxklryplwck\",\"provisioningState\":\"syyp\"},\"id\":\"dhsgcba\",\"name\":\"phejkotynqgoulz\",\"type\":\"dlikwyqkgfgibma\"}]}"; + = "{\"value\":[{\"properties\":{\"type\":\"default\",\"resourceId\":\"zmnvdfznudaod\",\"provisioningState\":\"zbn\"},\"id\":\"lylpstdb\",\"name\":\"hxsrzdzucersc\",\"type\":\"ntnev\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); HybridConnectivityManager manager = HybridConnectivityManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response - = manager.endpoints().list("tyxolniwpwc", com.azure.core.util.Context.NONE); + = manager.endpoints().list("iydmcwyhzdxs", com.azure.core.util.Context.NONE); - Assertions.assertEquals(Type.CUSTOM, response.iterator().next().properties().type()); - Assertions.assertEquals("kgiawxklryplwck", response.iterator().next().properties().resourceId()); + Assertions.assertEquals(Type.DEFAULT, response.iterator().next().properties().type()); + Assertions.assertEquals("zmnvdfznudaod", response.iterator().next().properties().resourceId()); } } diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsListTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsListTests.java index c3d889a3345e..022b9958bc41 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsListTests.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/EndpointsListTests.java @@ -1,36 +1,22 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.hybridconnectivity.fluent.models.EndpointResourceInner; -import com.azure.resourcemanager.hybridconnectivity.models.EndpointProperties; -import com.azure.resourcemanager.hybridconnectivity.models.EndpointsList; +import com.azure.resourcemanager.hybridconnectivity.implementation.models.EndpointsList; import com.azure.resourcemanager.hybridconnectivity.models.Type; -import java.util.Arrays; import org.junit.jupiter.api.Assertions; public final class EndpointsListTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { EndpointsList model = BinaryData.fromString( - "{\"nextLink\":\"a\",\"value\":[{\"properties\":{\"type\":\"default\",\"resourceId\":\"hab\",\"provisioningState\":\"pikxwczbyscnpqxu\"},\"id\":\"vyq\",\"name\":\"iwbybrkxvdumjg\",\"type\":\"tfwvukxgaudc\"}]}") + "{\"value\":[{\"properties\":{\"type\":\"default\",\"resourceId\":\"uhivyqniw\",\"provisioningState\":\"br\"},\"id\":\"vd\",\"name\":\"mjgr\",\"type\":\"fwvuk\"},{\"properties\":{\"type\":\"custom\",\"resourceId\":\"dcc\",\"provisioningState\":\"h\"},\"id\":\"cnyejhkryhtnapcz\",\"name\":\"lokjyemkk\",\"type\":\"ni\"}],\"nextLink\":\"oxzjnchgejspod\"}") .toObject(EndpointsList.class); - Assertions.assertEquals("a", model.nextLink()); Assertions.assertEquals(Type.DEFAULT, model.value().get(0).properties().type()); - Assertions.assertEquals("hab", model.value().get(0).properties().resourceId()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - EndpointsList model = new EndpointsList().withNextLink("a") - .withValue(Arrays.asList(new EndpointResourceInner() - .withProperties(new EndpointProperties().withType(Type.DEFAULT).withResourceId("hab")))); - model = BinaryData.fromObject(model).toObject(EndpointsList.class); - Assertions.assertEquals("a", model.nextLink()); - Assertions.assertEquals(Type.DEFAULT, model.value().get(0).properties().type()); - Assertions.assertEquals("hab", model.value().get(0).properties().resourceId()); + Assertions.assertEquals("uhivyqniw", model.value().get(0).properties().resourceId()); + Assertions.assertEquals("oxzjnchgejspod", model.nextLink()); } } diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/GenerateAwsTemplateRequestTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/GenerateAwsTemplateRequestTests.java new file mode 100644 index 000000000000..c2c2bc32b13b --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/GenerateAwsTemplateRequestTests.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.hybridconnectivity.models.GenerateAwsTemplateRequest; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionSettings; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionTypeSettings; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Assertions; + +public final class GenerateAwsTemplateRequestTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + GenerateAwsTemplateRequest model = BinaryData.fromString( + "{\"connectorId\":\"dhkrwpdappdsbdk\",\"solutionTypes\":[{\"solutionType\":\"wjfeusnhutjel\",\"solutionSettings\":{\"tyxolniwpwc\":\"k\",\"eablg\":\"dhugjzzdatqxhocd\",\"wyiftyhxhur\":\"huticndvkao\",\"awxklr\":\"kjfkg\"}},{\"solutionType\":\"plwckbas\",\"solutionSettings\":{\"dgak\":\"wyqkgfgibm\",\"i\":\"qgoulznd\",\"koty\":\"ddhsgcbacphe\"}}]}") + .toObject(GenerateAwsTemplateRequest.class); + Assertions.assertEquals("dhkrwpdappdsbdk", model.connectorId()); + Assertions.assertEquals("wjfeusnhutjel", model.solutionTypes().get(0).solutionType()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + GenerateAwsTemplateRequest model = new GenerateAwsTemplateRequest().withConnectorId("dhkrwpdappdsbdk") + .withSolutionTypes(Arrays.asList( + new SolutionTypeSettings().withSolutionType("wjfeusnhutjel") + .withSolutionSettings(new SolutionSettings().withAdditionalProperties(mapOf())), + new SolutionTypeSettings().withSolutionType("plwckbas") + .withSolutionSettings(new SolutionSettings().withAdditionalProperties(mapOf())))); + model = BinaryData.fromObject(model).toObject(GenerateAwsTemplateRequest.class); + Assertions.assertEquals("dhkrwpdappdsbdk", model.connectorId()); + Assertions.assertEquals("wjfeusnhutjel", model.solutionTypes().get(0).solutionType()); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/GenerateAwsTemplatesPostWithResponseMockTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/GenerateAwsTemplatesPostWithResponseMockTests.java new file mode 100644 index 000000000000..8a07985d12fd --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/GenerateAwsTemplatesPostWithResponseMockTests.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager; +import com.azure.resourcemanager.hybridconnectivity.models.GenerateAwsTemplateRequest; +import com.azure.resourcemanager.hybridconnectivity.models.PostResponse; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionSettings; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionTypeSettings; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class GenerateAwsTemplatesPostWithResponseMockTests { + @Test + public void testPostWithResponse() throws Exception { + String responseStr = "{}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + HybridConnectivityManager manager = HybridConnectivityManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PostResponse response = manager.generateAwsTemplates() + .postWithResponse( + new GenerateAwsTemplateRequest().withConnectorId("qyib") + .withSolutionTypes(Arrays.asList( + new SolutionTypeSettings().withSolutionType("fluszdtm") + .withSolutionSettings(new SolutionSettings().withAdditionalProperties(mapOf())), + new SolutionTypeSettings().withSolutionType("dbutauvfbtkuwhh") + .withSolutionSettings(new SolutionSettings().withAdditionalProperties(mapOf())))), + com.azure.core.util.Context.NONE) + .getValue(); + + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/IngressProfilePropertiesTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/IngressProfilePropertiesTests.java index a008cdad5068..6e176a177b3c 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/IngressProfilePropertiesTests.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/IngressProfilePropertiesTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; @@ -11,22 +11,11 @@ public final class IngressProfilePropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - IngressProfileProperties model = BinaryData - .fromString( - "{\"hostname\":\"fmppe\",\"aadProfile\":{\"serverId\":\"bvmgxsabkyqduuji\",\"tenantId\":\"c\"}}") + IngressProfileProperties model = BinaryData.fromString( + "{\"hostname\":\"dfdosygexp\",\"aadProfile\":{\"serverId\":\"ojakhmsbzjhcrze\",\"tenantId\":\"dphlxaolt\"}}") .toObject(IngressProfileProperties.class); - Assertions.assertEquals("fmppe", model.hostname()); - Assertions.assertEquals("bvmgxsabkyqduuji", model.serverId()); - Assertions.assertEquals("c", model.tenantId()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - IngressProfileProperties model - = new IngressProfileProperties().withHostname("fmppe").withServerId("bvmgxsabkyqduuji").withTenantId("c"); - model = BinaryData.fromObject(model).toObject(IngressProfileProperties.class); - Assertions.assertEquals("fmppe", model.hostname()); - Assertions.assertEquals("bvmgxsabkyqduuji", model.serverId()); - Assertions.assertEquals("c", model.tenantId()); + Assertions.assertEquals("dfdosygexp", model.hostname()); + Assertions.assertEquals("ojakhmsbzjhcrze", model.serverId()); + Assertions.assertEquals("dphlxaolt", model.tenantId()); } } diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/InventoriesGetWithResponseMockTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/InventoriesGetWithResponseMockTests.java new file mode 100644 index 000000000000..a4856c144669 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/InventoriesGetWithResponseMockTests.java @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager; +import com.azure.resourcemanager.hybridconnectivity.models.CloudNativeType; +import com.azure.resourcemanager.hybridconnectivity.models.InventoryResource; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionConfigurationStatus; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class InventoriesGetWithResponseMockTests { + @Test + public void testGetWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"cloudNativeType\":\"ec2\",\"cloudNativeResourceId\":\"tqs\",\"azureResourceId\":\"qxujxukndxd\",\"status\":\"Failed\",\"statusDetails\":\"guufzd\",\"provisioningState\":\"Succeeded\"},\"id\":\"tfih\",\"name\":\"hbotzingamvppho\",\"type\":\"zqzudph\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + HybridConnectivityManager manager = HybridConnectivityManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + InventoryResource response = manager.inventories() + .getWithResponse("hfkvtvsexsowuel", "qhhahhxvrhmzkwpj", "wws", com.azure.core.util.Context.NONE) + .getValue(); + + Assertions.assertEquals(CloudNativeType.EC2, response.properties().cloudNativeType()); + Assertions.assertEquals("tqs", response.properties().cloudNativeResourceId()); + Assertions.assertEquals("qxujxukndxd", response.properties().azureResourceId()); + Assertions.assertEquals(SolutionConfigurationStatus.FAILED, response.properties().status()); + Assertions.assertEquals("guufzd", response.properties().statusDetails()); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/InventoriesListBySolutionConfigurationMockTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/InventoriesListBySolutionConfigurationMockTests.java new file mode 100644 index 000000000000..b819da5b8f28 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/InventoriesListBySolutionConfigurationMockTests.java @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager; +import com.azure.resourcemanager.hybridconnectivity.models.CloudNativeType; +import com.azure.resourcemanager.hybridconnectivity.models.InventoryResource; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionConfigurationStatus; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class InventoriesListBySolutionConfigurationMockTests { + @Test + public void testListBySolutionConfiguration() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"cloudNativeType\":\"ec2\",\"cloudNativeResourceId\":\"wzcjaesgvvsccy\",\"azureResourceId\":\"g\",\"status\":\"Failed\",\"statusDetails\":\"wygzlvdnkfxusem\",\"provisioningState\":\"Canceled\"},\"id\":\"muhapfcqdpsqxqv\",\"name\":\"svuo\",\"type\":\"mgccelvezrypq\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + HybridConnectivityManager manager = HybridConnectivityManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response = manager.inventories() + .listBySolutionConfiguration("amvdkfwynwcvtbv", "ayhmtnvyqiatkz", com.azure.core.util.Context.NONE); + + Assertions.assertEquals(CloudNativeType.EC2, response.iterator().next().properties().cloudNativeType()); + Assertions.assertEquals("wzcjaesgvvsccy", response.iterator().next().properties().cloudNativeResourceId()); + Assertions.assertEquals("g", response.iterator().next().properties().azureResourceId()); + Assertions.assertEquals(SolutionConfigurationStatus.FAILED, response.iterator().next().properties().status()); + Assertions.assertEquals("wygzlvdnkfxusem", response.iterator().next().properties().statusDetails()); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/InventoryPropertiesTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/InventoryPropertiesTests.java new file mode 100644 index 000000000000..2250a3e4c95c --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/InventoryPropertiesTests.java @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.hybridconnectivity.models.CloudNativeType; +import com.azure.resourcemanager.hybridconnectivity.models.InventoryProperties; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionConfigurationStatus; +import org.junit.jupiter.api.Assertions; + +public final class InventoryPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + InventoryProperties model = BinaryData.fromString( + "{\"cloudNativeType\":\"ec2\",\"cloudNativeResourceId\":\"jzicwifsjt\",\"azureResourceId\":\"zfbishcbkhaj\",\"status\":\"Failed\",\"statusDetails\":\"a\",\"provisioningState\":\"Failed\"}") + .toObject(InventoryProperties.class); + Assertions.assertEquals(CloudNativeType.EC2, model.cloudNativeType()); + Assertions.assertEquals("jzicwifsjt", model.cloudNativeResourceId()); + Assertions.assertEquals("zfbishcbkhaj", model.azureResourceId()); + Assertions.assertEquals(SolutionConfigurationStatus.FAILED, model.status()); + Assertions.assertEquals("a", model.statusDetails()); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/InventoryResourceInnerTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/InventoryResourceInnerTests.java new file mode 100644 index 000000000000..a0701f40dfcf --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/InventoryResourceInnerTests.java @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.InventoryResourceInner; +import com.azure.resourcemanager.hybridconnectivity.models.CloudNativeType; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionConfigurationStatus; +import org.junit.jupiter.api.Assertions; + +public final class InventoryResourceInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + InventoryResourceInner model = BinaryData.fromString( + "{\"properties\":{\"cloudNativeType\":\"ec2\",\"cloudNativeResourceId\":\"rvjx\",\"azureResourceId\":\"nspydptkoenkoukn\",\"status\":\"Failed\",\"statusDetails\":\"tiukbldngkpoci\",\"provisioningState\":\"Succeeded\"},\"id\":\"xoegukgjnpiucgy\",\"name\":\"evqzntypmrbp\",\"type\":\"zcdrqjsdpydnfyhx\"}") + .toObject(InventoryResourceInner.class); + Assertions.assertEquals(CloudNativeType.EC2, model.properties().cloudNativeType()); + Assertions.assertEquals("rvjx", model.properties().cloudNativeResourceId()); + Assertions.assertEquals("nspydptkoenkoukn", model.properties().azureResourceId()); + Assertions.assertEquals(SolutionConfigurationStatus.FAILED, model.properties().status()); + Assertions.assertEquals("tiukbldngkpoci", model.properties().statusDetails()); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/InventoryResourceListResultTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/InventoryResourceListResultTests.java new file mode 100644 index 000000000000..5775e062360e --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/InventoryResourceListResultTests.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.hybridconnectivity.implementation.models.InventoryResourceListResult; +import com.azure.resourcemanager.hybridconnectivity.models.CloudNativeType; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionConfigurationStatus; +import org.junit.jupiter.api.Assertions; + +public final class InventoryResourceListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + InventoryResourceListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"cloudNativeType\":\"ec2\",\"cloudNativeResourceId\":\"pbuxwgipwhon\",\"azureResourceId\":\"kgshwa\",\"status\":\"Failed\",\"statusDetails\":\"zbinjeputtm\",\"provisioningState\":\"Succeeded\"},\"id\":\"uzoqft\",\"name\":\"yqzrnkcqvyxlw\",\"type\":\"zlsico\"},{\"properties\":{\"cloudNativeType\":\"ec2\",\"cloudNativeResourceId\":\"wvl\",\"azureResourceId\":\"avwhheunm\",\"status\":\"Completed\",\"statusDetails\":\"yxzk\",\"provisioningState\":\"Failed\"},\"id\":\"uko\",\"name\":\"lyaxuc\",\"type\":\"nuqszfkbey\"},{\"properties\":{\"cloudNativeType\":\"ec2\",\"cloudNativeResourceId\":\"jmwvvj\",\"azureResourceId\":\"tcxsenhwlrs\",\"status\":\"Failed\",\"statusDetails\":\"pwvlqdq\",\"provisioningState\":\"Failed\"},\"id\":\"ylihkaetckt\",\"name\":\"fcivfsnkym\",\"type\":\"ctq\"},{\"properties\":{\"cloudNativeType\":\"ec2\",\"cloudNativeResourceId\":\"brjcxe\",\"azureResourceId\":\"uwutttxfvjrbi\",\"status\":\"Failed\",\"statusDetails\":\"epcyvahfnlj\",\"provisioningState\":\"Canceled\"},\"id\":\"j\",\"name\":\"uujqgidokgjljyo\",\"type\":\"gvcl\"}],\"nextLink\":\"gsncghkjeszz\"}") + .toObject(InventoryResourceListResult.class); + Assertions.assertEquals(CloudNativeType.EC2, model.value().get(0).properties().cloudNativeType()); + Assertions.assertEquals("pbuxwgipwhon", model.value().get(0).properties().cloudNativeResourceId()); + Assertions.assertEquals("kgshwa", model.value().get(0).properties().azureResourceId()); + Assertions.assertEquals(SolutionConfigurationStatus.FAILED, model.value().get(0).properties().status()); + Assertions.assertEquals("zbinjeputtm", model.value().get(0).properties().statusDetails()); + Assertions.assertEquals("gsncghkjeszz", model.nextLink()); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ListCredentialsRequestTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ListCredentialsRequestTests.java index b5ad3864bbac..ce8e831a57a4 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ListCredentialsRequestTests.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ListCredentialsRequestTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; @@ -13,14 +13,14 @@ public final class ListCredentialsRequestTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ListCredentialsRequest model - = BinaryData.fromString("{\"serviceName\":\"WAC\"}").toObject(ListCredentialsRequest.class); - Assertions.assertEquals(ServiceName.WAC, model.serviceName()); + = BinaryData.fromString("{\"serviceName\":\"SSH\"}").toObject(ListCredentialsRequest.class); + Assertions.assertEquals(ServiceName.SSH, model.serviceName()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - ListCredentialsRequest model = new ListCredentialsRequest().withServiceName(ServiceName.WAC); + ListCredentialsRequest model = new ListCredentialsRequest().withServiceName(ServiceName.SSH); model = BinaryData.fromObject(model).toObject(ListCredentialsRequest.class); - Assertions.assertEquals(ServiceName.WAC, model.serviceName()); + Assertions.assertEquals(ServiceName.SSH, model.serviceName()); } } diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ListIngressGatewayCredentialsRequestTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ListIngressGatewayCredentialsRequestTests.java index 611edb84ef9f..450478ee041e 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ListIngressGatewayCredentialsRequestTests.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ListIngressGatewayCredentialsRequestTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ManagedProxyRequestTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ManagedProxyRequestTests.java index c43504b29b39..c08c16e67060 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ManagedProxyRequestTests.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ManagedProxyRequestTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; @@ -13,20 +13,20 @@ public final class ManagedProxyRequestTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ManagedProxyRequest model - = BinaryData.fromString("{\"service\":\"wrwjfeu\",\"hostname\":\"hutje\",\"serviceName\":\"SSH\"}") + = BinaryData.fromString("{\"service\":\"jrwzox\",\"hostname\":\"tfell\",\"serviceName\":\"SSH\"}") .toObject(ManagedProxyRequest.class); - Assertions.assertEquals("wrwjfeu", model.service()); - Assertions.assertEquals("hutje", model.hostname()); + Assertions.assertEquals("jrwzox", model.service()); + Assertions.assertEquals("tfell", model.hostname()); Assertions.assertEquals(ServiceName.SSH, model.serviceName()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { ManagedProxyRequest model - = new ManagedProxyRequest().withService("wrwjfeu").withHostname("hutje").withServiceName(ServiceName.SSH); + = new ManagedProxyRequest().withService("jrwzox").withHostname("tfell").withServiceName(ServiceName.SSH); model = BinaryData.fromObject(model).toObject(ManagedProxyRequest.class); - Assertions.assertEquals("wrwjfeu", model.service()); - Assertions.assertEquals("hutje", model.hostname()); + Assertions.assertEquals("jrwzox", model.service()); + Assertions.assertEquals("tfell", model.hostname()); Assertions.assertEquals(ServiceName.SSH, model.serviceName()); } } diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ManagedProxyResourceInnerTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ManagedProxyResourceInnerTests.java index 25be04a9ab64..889507d61efa 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ManagedProxyResourceInnerTests.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ManagedProxyResourceInnerTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; @@ -11,18 +11,10 @@ public final class ManagedProxyResourceInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - ManagedProxyResourceInner model = BinaryData.fromString("{\"proxy\":\"rl\",\"expiresOn\":6676746623961683086}") - .toObject(ManagedProxyResourceInner.class); - Assertions.assertEquals("rl", model.proxy()); - Assertions.assertEquals(6676746623961683086L, model.expiresOn()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { ManagedProxyResourceInner model - = new ManagedProxyResourceInner().withProxy("rl").withExpiresOn(6676746623961683086L); - model = BinaryData.fromObject(model).toObject(ManagedProxyResourceInner.class); - Assertions.assertEquals("rl", model.proxy()); - Assertions.assertEquals(6676746623961683086L, model.expiresOn()); + = BinaryData.fromString("{\"proxy\":\"zitonpeqfpjkjl\",\"expiresOn\":6527642903227935685}") + .toObject(ManagedProxyResourceInner.class); + Assertions.assertEquals("zitonpeqfpjkjl", model.proxy()); + Assertions.assertEquals(6527642903227935685L, model.expiresOn()); } } diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/OperationDisplayTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/OperationDisplayTests.java index 210d226a0b04..14ce8816d32d 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/OperationDisplayTests.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/OperationDisplayTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; @@ -11,13 +11,7 @@ public final class OperationDisplayTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { OperationDisplay model = BinaryData.fromString( - "{\"provider\":\"yrtih\",\"resource\":\"tijbpzvgnwzsymgl\",\"operation\":\"fcyzkohdbihanufh\",\"description\":\"bj\"}") + "{\"provider\":\"cdm\",\"resource\":\"rcryuanzwuxzdxta\",\"operation\":\"lhmwhfpmrqobm\",\"description\":\"kknryrtihf\"}") .toObject(OperationDisplay.class); } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - OperationDisplay model = new OperationDisplay(); - model = BinaryData.fromObject(model).toObject(OperationDisplay.class); - } } diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/OperationInnerTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/OperationInnerTests.java index 6fb0af2c2ef0..08e0ecb5d7df 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/OperationInnerTests.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/OperationInnerTests.java @@ -1,24 +1,17 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; import com.azure.core.util.BinaryData; import com.azure.resourcemanager.hybridconnectivity.fluent.models.OperationInner; -import com.azure.resourcemanager.hybridconnectivity.models.OperationDisplay; public final class OperationInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { OperationInner model = BinaryData.fromString( - "{\"name\":\"usarhmofc\",\"isDataAction\":false,\"display\":{\"provider\":\"urkdtmlx\",\"resource\":\"kuksjtxukcdm\",\"operation\":\"rcryuanzwuxzdxta\",\"description\":\"lhmwhfpmrqobm\"},\"origin\":\"user,system\",\"actionType\":\"Internal\"}") + "{\"name\":\"nygj\",\"isDataAction\":true,\"display\":{\"provider\":\"eqsrdeupewnwreit\",\"resource\":\"yflusarhmofc\",\"operation\":\"smy\",\"description\":\"kdtmlxhekuk\"},\"origin\":\"user,system\",\"actionType\":\"Internal\"}") .toObject(OperationInner.class); } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - OperationInner model = new OperationInner().withDisplay(new OperationDisplay()); - model = BinaryData.fromObject(model).toObject(OperationInner.class); - } } diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/OperationListResultTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/OperationListResultTests.java index e62601c805de..9633098ef96a 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/OperationListResultTests.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/OperationListResultTests.java @@ -1,23 +1,19 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.hybridconnectivity.models.OperationListResult; +import com.azure.resourcemanager.hybridconnectivity.implementation.models.OperationListResult; +import org.junit.jupiter.api.Assertions; public final class OperationListResultTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { OperationListResult model = BinaryData.fromString( - "{\"value\":[{\"name\":\"quvgjxpybczme\",\"isDataAction\":true,\"display\":{\"provider\":\"pbsphrupidgs\",\"resource\":\"bejhphoycmsxa\",\"operation\":\"hdxbmtqio\",\"description\":\"zehtbmu\"},\"origin\":\"user,system\",\"actionType\":\"Internal\"},{\"name\":\"izhwlrxy\",\"isDataAction\":false,\"display\":{\"provider\":\"ijgkdm\",\"resource\":\"azlobcufpdznrbt\",\"operation\":\"qjnqglhqgnufoooj\",\"description\":\"ifsqesaagdfmg\"},\"origin\":\"user,system\",\"actionType\":\"Internal\"},{\"name\":\"rifkwm\",\"isDataAction\":true,\"display\":{\"provider\":\"izntocipao\",\"resource\":\"jpsq\",\"operation\":\"mpoyfd\",\"description\":\"ogknygjofjdd\"},\"origin\":\"user,system\",\"actionType\":\"Internal\"}],\"nextLink\":\"upewnwreitjzy\"}") + "{\"value\":[{\"name\":\"hq\",\"isDataAction\":true,\"display\":{\"provider\":\"pybczmehmtzopb\",\"resource\":\"h\",\"operation\":\"pidgsybbejhphoyc\",\"description\":\"xaobhdxbmtqioqjz\"},\"origin\":\"system\",\"actionType\":\"Internal\"},{\"name\":\"fpownoizhwlr\",\"isDataAction\":false,\"display\":{\"provider\":\"oqijgkdmbpaz\",\"resource\":\"bc\",\"operation\":\"pdznrbtcqqjnqgl\",\"description\":\"gnufoooj\"},\"origin\":\"system\",\"actionType\":\"Internal\"},{\"name\":\"esaagdfm\",\"isDataAction\":true,\"display\":{\"provider\":\"j\",\"resource\":\"ifkwmrvktsizntoc\",\"operation\":\"a\",\"description\":\"ajpsquc\"},\"origin\":\"system\",\"actionType\":\"Internal\"}],\"nextLink\":\"kfo\"}") .toObject(OperationListResult.class); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - OperationListResult model = new OperationListResult(); - model = BinaryData.fromObject(model).toObject(OperationListResult.class); + Assertions.assertEquals("kfo", model.nextLink()); } } diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/OperationsListMockTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/OperationsListMockTests.java index e63c9072dd17..9991765683e6 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/OperationsListMockTests.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/OperationsListMockTests.java @@ -1,14 +1,14 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager; import com.azure.resourcemanager.hybridconnectivity.models.Operation; @@ -21,14 +21,14 @@ public final class OperationsListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"name\":\"jzzd\",\"isDataAction\":true,\"display\":{\"provider\":\"oc\",\"resource\":\"eablg\",\"operation\":\"uticndvkaozwyif\",\"description\":\"hxh\"},\"origin\":\"user,system\",\"actionType\":\"Internal\"}]}"; + = "{\"value\":[{\"name\":\"l\",\"isDataAction\":false,\"display\":{\"provider\":\"q\",\"resource\":\"wpmqt\",\"operation\":\"uoujmkcjhwqy\",\"description\":\"r\"},\"origin\":\"user\",\"actionType\":\"Internal\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); HybridConnectivityManager manager = HybridConnectivityManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.operations().list(com.azure.core.util.Context.NONE); diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/PostResponseInnerTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/PostResponseInnerTests.java new file mode 100644 index 000000000000..5da017d32257 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/PostResponseInnerTests.java @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.PostResponseInner; + +public final class PostResponseInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + PostResponseInner model = BinaryData.fromString("{}").toObject(PostResponseInner.class); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorInnerTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorInnerTests.java new file mode 100644 index 000000000000..7646113e1afc --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorInnerTests.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.PublicCloudConnectorInner; +import com.azure.resourcemanager.hybridconnectivity.models.AwsCloudProfile; +import com.azure.resourcemanager.hybridconnectivity.models.HostType; +import com.azure.resourcemanager.hybridconnectivity.models.PublicCloudConnectorProperties; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Assertions; + +public final class PublicCloudConnectorInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + PublicCloudConnectorInner model = BinaryData.fromString( + "{\"properties\":{\"awsCloudProfile\":{\"accountId\":\"lgbquxig\",\"excludedAccounts\":[\"gzjaoyfhrtxilne\",\"kujysvlejuvfq\",\"wrlyxwjkcprb\"],\"isOrganizationalAccount\":false},\"hostType\":\"AWS\",\"provisioningState\":\"Canceled\",\"connectorPrimaryIdentifier\":\"tbvpysszdnru\"},\"location\":\"guhmuouqfpr\",\"tags\":{\"nwui\":\"bngui\",\"zuckyfi\":\"gazxuf\",\"htymw\":\"rfidfvzwdz\"},\"id\":\"sdkf\",\"name\":\"hwxmnteiwa\",\"type\":\"pvkmijcmmxdcuf\"}") + .toObject(PublicCloudConnectorInner.class); + Assertions.assertEquals("guhmuouqfpr", model.location()); + Assertions.assertEquals("bngui", model.tags().get("nwui")); + Assertions.assertEquals("lgbquxig", model.properties().awsCloudProfile().accountId()); + Assertions.assertEquals("gzjaoyfhrtxilne", model.properties().awsCloudProfile().excludedAccounts().get(0)); + Assertions.assertEquals(false, model.properties().awsCloudProfile().isOrganizationalAccount()); + Assertions.assertEquals(HostType.AWS, model.properties().hostType()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + PublicCloudConnectorInner model + = new PublicCloudConnectorInner().withLocation("guhmuouqfpr") + .withTags(mapOf("nwui", "bngui", "zuckyfi", "gazxuf", "htymw", "rfidfvzwdz")) + .withProperties(new PublicCloudConnectorProperties() + .withAwsCloudProfile(new AwsCloudProfile().withAccountId("lgbquxig") + .withExcludedAccounts(Arrays.asList("gzjaoyfhrtxilne", "kujysvlejuvfq", "wrlyxwjkcprb")) + .withIsOrganizationalAccount(false)) + .withHostType(HostType.AWS)); + model = BinaryData.fromObject(model).toObject(PublicCloudConnectorInner.class); + Assertions.assertEquals("guhmuouqfpr", model.location()); + Assertions.assertEquals("bngui", model.tags().get("nwui")); + Assertions.assertEquals("lgbquxig", model.properties().awsCloudProfile().accountId()); + Assertions.assertEquals("gzjaoyfhrtxilne", model.properties().awsCloudProfile().excludedAccounts().get(0)); + Assertions.assertEquals(false, model.properties().awsCloudProfile().isOrganizationalAccount()); + Assertions.assertEquals(HostType.AWS, model.properties().hostType()); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorListResultTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorListResultTests.java new file mode 100644 index 000000000000..cf76ff22e7d4 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorListResultTests.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.hybridconnectivity.implementation.models.PublicCloudConnectorListResult; +import com.azure.resourcemanager.hybridconnectivity.models.HostType; +import org.junit.jupiter.api.Assertions; + +public final class PublicCloudConnectorListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + PublicCloudConnectorListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"awsCloudProfile\":{\"accountId\":\"rcjxvsnbyxqabn\",\"excludedAccounts\":[\"pcyshu\"],\"isOrganizationalAccount\":true},\"hostType\":\"AWS\",\"provisioningState\":\"Canceled\",\"connectorPrimaryIdentifier\":\"j\"},\"location\":\"btoqcjmkljavbqid\",\"tags\":{\"dj\":\"jzyulpk\",\"xzlocxscp\":\"rlkhbzhfepgzgq\"},\"id\":\"ierhhbcsglummaj\",\"name\":\"j\",\"type\":\"odxobnbdxkqpxok\"},{\"properties\":{\"awsCloudProfile\":{\"accountId\":\"ionpimexg\",\"excludedAccounts\":[\"gcpo\"],\"isOrganizationalAccount\":true},\"hostType\":\"AWS\",\"provisioningState\":\"Canceled\",\"connectorPrimaryIdentifier\":\"mvdjwzrlovmc\"},\"location\":\"hijco\",\"tags\":{\"ukdkexxppofmxa\":\"tbzaqsqsycbkbfk\",\"jpgd\":\"c\"},\"id\":\"toc\",\"name\":\"j\",\"type\":\"hvpmoue\"},{\"properties\":{\"awsCloudProfile\":{\"accountId\":\"dzxibqeojnxqbzvd\",\"excludedAccounts\":[\"wndeicbtwnp\"],\"isOrganizationalAccount\":false},\"hostType\":\"AWS\",\"provisioningState\":\"Succeeded\",\"connectorPrimaryIdentifier\":\"rhcffcydd\"},\"location\":\"mjthjqkwp\",\"tags\":{\"igdtopbob\":\"cxmqciwqvhkhix\"},\"id\":\"og\",\"name\":\"m\",\"type\":\"w\"},{\"properties\":{\"awsCloudProfile\":{\"accountId\":\"m\",\"excludedAccounts\":[\"rzayv\",\"t\",\"gvdfgiotkftutq\",\"ln\"],\"isOrganizationalAccount\":true},\"hostType\":\"AWS\",\"provisioningState\":\"Canceled\",\"connectorPrimaryIdentifier\":\"gnxkrxdqmidtth\"},\"location\":\"vqdra\",\"tags\":{\"gehoqfbowskany\":\"yb\",\"rvynhzgpph\":\"tzlcuiywgqywgn\"},\"id\":\"cgyncocpecf\",\"name\":\"m\",\"type\":\"coofsxlzev\"}],\"nextLink\":\"m\"}") + .toObject(PublicCloudConnectorListResult.class); + Assertions.assertEquals("btoqcjmkljavbqid", model.value().get(0).location()); + Assertions.assertEquals("jzyulpk", model.value().get(0).tags().get("dj")); + Assertions.assertEquals("rcjxvsnbyxqabn", model.value().get(0).properties().awsCloudProfile().accountId()); + Assertions.assertEquals("pcyshu", + model.value().get(0).properties().awsCloudProfile().excludedAccounts().get(0)); + Assertions.assertEquals(true, model.value().get(0).properties().awsCloudProfile().isOrganizationalAccount()); + Assertions.assertEquals(HostType.AWS, model.value().get(0).properties().hostType()); + Assertions.assertEquals("m", model.nextLink()); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorPropertiesTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorPropertiesTests.java new file mode 100644 index 000000000000..a270d2e37618 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorPropertiesTests.java @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.hybridconnectivity.models.AwsCloudProfile; +import com.azure.resourcemanager.hybridconnectivity.models.HostType; +import com.azure.resourcemanager.hybridconnectivity.models.PublicCloudConnectorProperties; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class PublicCloudConnectorPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + PublicCloudConnectorProperties model = BinaryData.fromString( + "{\"awsCloudProfile\":{\"accountId\":\"fsrpymzidnse\",\"excludedAccounts\":[\"tbzsgfyccs\",\"ewmdw\",\"jeiachboosfl\",\"ro\"],\"isOrganizationalAccount\":false},\"hostType\":\"AWS\",\"provisioningState\":\"Canceled\",\"connectorPrimaryIdentifier\":\"hzzvypyq\"}") + .toObject(PublicCloudConnectorProperties.class); + Assertions.assertEquals("fsrpymzidnse", model.awsCloudProfile().accountId()); + Assertions.assertEquals("tbzsgfyccs", model.awsCloudProfile().excludedAccounts().get(0)); + Assertions.assertEquals(false, model.awsCloudProfile().isOrganizationalAccount()); + Assertions.assertEquals(HostType.AWS, model.hostType()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + PublicCloudConnectorProperties model = new PublicCloudConnectorProperties() + .withAwsCloudProfile(new AwsCloudProfile().withAccountId("fsrpymzidnse") + .withExcludedAccounts(Arrays.asList("tbzsgfyccs", "ewmdw", "jeiachboosfl", "ro")) + .withIsOrganizationalAccount(false)) + .withHostType(HostType.AWS); + model = BinaryData.fromObject(model).toObject(PublicCloudConnectorProperties.class); + Assertions.assertEquals("fsrpymzidnse", model.awsCloudProfile().accountId()); + Assertions.assertEquals("tbzsgfyccs", model.awsCloudProfile().excludedAccounts().get(0)); + Assertions.assertEquals(false, model.awsCloudProfile().isOrganizationalAccount()); + Assertions.assertEquals(HostType.AWS, model.hostType()); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsCreateOrUpdateMockTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsCreateOrUpdateMockTests.java new file mode 100644 index 000000000000..3512a49f0e34 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsCreateOrUpdateMockTests.java @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager; +import com.azure.resourcemanager.hybridconnectivity.models.AwsCloudProfile; +import com.azure.resourcemanager.hybridconnectivity.models.HostType; +import com.azure.resourcemanager.hybridconnectivity.models.PublicCloudConnector; +import com.azure.resourcemanager.hybridconnectivity.models.PublicCloudConnectorProperties; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class PublicCloudConnectorsCreateOrUpdateMockTests { + @Test + public void testCreateOrUpdate() throws Exception { + String responseStr + = "{\"properties\":{\"awsCloudProfile\":{\"accountId\":\"twwaezkojvdcpzf\",\"excludedAccounts\":[\"uicybxarzgszuf\",\"x\",\"iqopidoamciod\",\"khazxkhnzbonlwn\"],\"isOrganizationalAccount\":true},\"hostType\":\"AWS\",\"provisioningState\":\"Succeeded\",\"connectorPrimaryIdentifier\":\"wbw\"},\"location\":\"szzcmrvexztv\",\"tags\":{\"lmnguxaw\":\"gsfraoyzkoow\",\"uximerqfobw\":\"aldsy\",\"r\":\"znkbykutwpfhpagm\",\"kkze\":\"kdsnfdsdoakgtdl\"},\"id\":\"dlhewp\",\"name\":\"sdsttwvog\",\"type\":\"bbejdcngqqm\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + HybridConnectivityManager manager = HybridConnectivityManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PublicCloudConnector response = manager.publicCloudConnectors() + .define("or") + .withRegion("f") + .withExistingResourceGroup("ppriol") + .withTags(mapOf("bgdknnqv", "gj", "sgsahmkycgr", "aznqntoru", "s", "uwjuetaeburuvdmo", "tpuqujmq", + "zlxwabmqoefkifr")) + .withProperties( + new PublicCloudConnectorProperties().withAwsCloudProfile(new AwsCloudProfile().withAccountId("lt") + .withExcludedAccounts(Arrays.asList("ncwsob", "wcsdbnwdcfhucq", "pfuvglsbjjca", "vxb")) + .withIsOrganizationalAccount(true)).withHostType(HostType.AWS)) + .create(); + + Assertions.assertEquals("szzcmrvexztv", response.location()); + Assertions.assertEquals("gsfraoyzkoow", response.tags().get("lmnguxaw")); + Assertions.assertEquals("twwaezkojvdcpzf", response.properties().awsCloudProfile().accountId()); + Assertions.assertEquals("uicybxarzgszuf", response.properties().awsCloudProfile().excludedAccounts().get(0)); + Assertions.assertEquals(true, response.properties().awsCloudProfile().isOrganizationalAccount()); + Assertions.assertEquals(HostType.AWS, response.properties().hostType()); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsDeleteByResourceGroupWithResponseMockTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsDeleteByResourceGroupWithResponseMockTests.java new file mode 100644 index 000000000000..5d191c166fa8 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsDeleteByResourceGroupWithResponseMockTests.java @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class PublicCloudConnectorsDeleteByResourceGroupWithResponseMockTests { + @Test + public void testDeleteWithResponse() throws Exception { + String responseStr = "{}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + HybridConnectivityManager manager = HybridConnectivityManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + manager.publicCloudConnectors() + .deleteByResourceGroupWithResponse("rwyhqmibzyhwitsm", "pyy", com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsGetByResourceGroupWithResponseMockTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsGetByResourceGroupWithResponseMockTests.java new file mode 100644 index 000000000000..1063091b4c33 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsGetByResourceGroupWithResponseMockTests.java @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager; +import com.azure.resourcemanager.hybridconnectivity.models.HostType; +import com.azure.resourcemanager.hybridconnectivity.models.PublicCloudConnector; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class PublicCloudConnectorsGetByResourceGroupWithResponseMockTests { + @Test + public void testGetByResourceGroupWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"awsCloudProfile\":{\"accountId\":\"xywsuws\",\"excludedAccounts\":[\"ndsytgadg\"],\"isOrganizationalAccount\":true},\"hostType\":\"AWS\",\"provisioningState\":\"Succeeded\",\"connectorPrimaryIdentifier\":\"e\"},\"location\":\"zar\",\"tags\":{\"uijfqk\":\"q\",\"ibwwiftohqkv\":\"cewiipfpub\",\"ljphuopxodl\":\"uvksgplsaknynfsy\",\"sjswsrms\":\"iyntorzihle\"},\"id\":\"yzrpzbchckqqzq\",\"name\":\"ox\",\"type\":\"ysuiizynkedya\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + HybridConnectivityManager manager = HybridConnectivityManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PublicCloudConnector response = manager.publicCloudConnectors() + .getByResourceGroupWithResponse("pkkpw", "reqnovvqfov", com.azure.core.util.Context.NONE) + .getValue(); + + Assertions.assertEquals("zar", response.location()); + Assertions.assertEquals("q", response.tags().get("uijfqk")); + Assertions.assertEquals("xywsuws", response.properties().awsCloudProfile().accountId()); + Assertions.assertEquals("ndsytgadg", response.properties().awsCloudProfile().excludedAccounts().get(0)); + Assertions.assertEquals(true, response.properties().awsCloudProfile().isOrganizationalAccount()); + Assertions.assertEquals(HostType.AWS, response.properties().hostType()); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsListByResourceGroupMockTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsListByResourceGroupMockTests.java new file mode 100644 index 000000000000..7da1767258e8 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsListByResourceGroupMockTests.java @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager; +import com.azure.resourcemanager.hybridconnectivity.models.HostType; +import com.azure.resourcemanager.hybridconnectivity.models.PublicCloudConnector; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class PublicCloudConnectorsListByResourceGroupMockTests { + @Test + public void testListByResourceGroup() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"awsCloudProfile\":{\"accountId\":\"wznm\",\"excludedAccounts\":[\"knso\",\"gj\",\"xbldtlwwrlkdmtn\"],\"isOrganizationalAccount\":false},\"hostType\":\"AWS\",\"provisioningState\":\"Failed\",\"connectorPrimaryIdentifier\":\"lxdy\"},\"location\":\"syocogjltdtbnnha\",\"tags\":{\"amqgxqquezikyw\":\"crkvcikhnv\",\"lla\":\"gxk\",\"z\":\"melwuipiccjz\"},\"id\":\"v\",\"name\":\"vvcnayr\",\"type\":\"yrnxxmueedn\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + HybridConnectivityManager manager = HybridConnectivityManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response + = manager.publicCloudConnectors().listByResourceGroup("pcdpumnz", com.azure.core.util.Context.NONE); + + Assertions.assertEquals("syocogjltdtbnnha", response.iterator().next().location()); + Assertions.assertEquals("crkvcikhnv", response.iterator().next().tags().get("amqgxqquezikyw")); + Assertions.assertEquals("wznm", response.iterator().next().properties().awsCloudProfile().accountId()); + Assertions.assertEquals("knso", + response.iterator().next().properties().awsCloudProfile().excludedAccounts().get(0)); + Assertions.assertEquals(false, + response.iterator().next().properties().awsCloudProfile().isOrganizationalAccount()); + Assertions.assertEquals(HostType.AWS, response.iterator().next().properties().hostType()); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsListMockTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsListMockTests.java new file mode 100644 index 000000000000..a5bc209d22eb --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/PublicCloudConnectorsListMockTests.java @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager; +import com.azure.resourcemanager.hybridconnectivity.models.HostType; +import com.azure.resourcemanager.hybridconnectivity.models.PublicCloudConnector; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class PublicCloudConnectorsListMockTests { + @Test + public void testList() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"awsCloudProfile\":{\"accountId\":\"dvstkw\",\"excludedAccounts\":[\"chea\",\"mfmtdaaygdvw\"],\"isOrganizationalAccount\":true},\"hostType\":\"AWS\",\"provisioningState\":\"Succeeded\",\"connectorPrimaryIdentifier\":\"wxrt\"},\"location\":\"dxepxgyq\",\"tags\":{\"wi\":\"rvmnpkukghimdblx\",\"rey\":\"fnjhfjxwmszkkfo\",\"elpcirelsfeaenwa\":\"kzikfjawneaivxwc\",\"xbjhwuaanozjosph\":\"fatkld\"},\"id\":\"oulpjrv\",\"name\":\"ag\",\"type\":\"rvimjwosytxitcsk\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + HybridConnectivityManager manager = HybridConnectivityManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response + = manager.publicCloudConnectors().list(com.azure.core.util.Context.NONE); + + Assertions.assertEquals("dxepxgyq", response.iterator().next().location()); + Assertions.assertEquals("rvmnpkukghimdblx", response.iterator().next().tags().get("wi")); + Assertions.assertEquals("dvstkw", response.iterator().next().properties().awsCloudProfile().accountId()); + Assertions.assertEquals("chea", + response.iterator().next().properties().awsCloudProfile().excludedAccounts().get(0)); + Assertions.assertEquals(true, + response.iterator().next().properties().awsCloudProfile().isOrganizationalAccount()); + Assertions.assertEquals(HostType.AWS, response.iterator().next().properties().hostType()); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationListTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationListTests.java index 4ed33dcfacbc..e0b2688a4d4a 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationListTests.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationListTests.java @@ -1,45 +1,23 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.hybridconnectivity.fluent.models.ServiceConfigurationResourceInner; -import com.azure.resourcemanager.hybridconnectivity.models.ServiceConfigurationList; +import com.azure.resourcemanager.hybridconnectivity.implementation.models.ServiceConfigurationList; import com.azure.resourcemanager.hybridconnectivity.models.ServiceName; -import java.util.Arrays; import org.junit.jupiter.api.Assertions; public final class ServiceConfigurationListTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ServiceConfigurationList model = BinaryData.fromString( - "{\"value\":[{\"properties\":{\"serviceName\":\"SSH\",\"resourceId\":\"sprozvcput\",\"port\":7394887039726775075,\"provisioningState\":\"Creating\"},\"id\":\"datscmd\",\"name\":\"pjhulsuuvmkj\",\"type\":\"zkrwfn\"},{\"properties\":{\"serviceName\":\"WAC\",\"resourceId\":\"jpslwejd\",\"port\":2711659806667039097,\"provisioningState\":\"Succeeded\"},\"id\":\"psoacctazakljl\",\"name\":\"hbcryffdfdosyge\",\"type\":\"paojakhmsbzjh\"},{\"properties\":{\"serviceName\":\"SSH\",\"resourceId\":\"vdphlxaolthqtr\",\"port\":2607282935918519139,\"provisioningState\":\"Failed\"},\"id\":\"fsinzgvfcjrwzoxx\",\"name\":\"tfell\",\"type\":\"wfzitonpeqfpjk\"}],\"nextLink\":\"xofpdvhpfxxypi\"}") + "{\"value\":[{\"properties\":{\"serviceName\":\"WAC\",\"resourceId\":\"gxg\",\"port\":8990974861860259667,\"provisioningState\":\"Failed\"},\"id\":\"zfkufubljofx\",\"name\":\"eofjaeqjh\",\"type\":\"jbasvmsmjqulngs\"},{\"properties\":{\"serviceName\":\"WAC\",\"resourceId\":\"ybkzgcwr\",\"port\":4988388139114001122,\"provisioningState\":\"Failed\"},\"id\":\"ljdousk\",\"name\":\"qvkoc\",\"type\":\"cjdkwtnhxbnjbi\"},{\"properties\":{\"serviceName\":\"WAC\",\"resourceId\":\"gls\",\"port\":1203415892502867376,\"provisioningState\":\"Failed\"},\"id\":\"wnzlljfmppeeb\",\"name\":\"mgxsab\",\"type\":\"yqduujit\"}],\"nextLink\":\"czdzev\"}") .toObject(ServiceConfigurationList.class); - Assertions.assertEquals(ServiceName.SSH, model.value().get(0).serviceName()); - Assertions.assertEquals("sprozvcput", model.value().get(0).resourceId()); - Assertions.assertEquals(7394887039726775075L, model.value().get(0).port()); - Assertions.assertEquals("xofpdvhpfxxypi", model.nextLink()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - ServiceConfigurationList model = new ServiceConfigurationList().withValue(Arrays.asList( - new ServiceConfigurationResourceInner().withServiceName(ServiceName.SSH) - .withResourceId("sprozvcput") - .withPort(7394887039726775075L), - new ServiceConfigurationResourceInner().withServiceName(ServiceName.WAC) - .withResourceId("jpslwejd") - .withPort(2711659806667039097L), - new ServiceConfigurationResourceInner().withServiceName(ServiceName.SSH) - .withResourceId("vdphlxaolthqtr") - .withPort(2607282935918519139L))) - .withNextLink("xofpdvhpfxxypi"); - model = BinaryData.fromObject(model).toObject(ServiceConfigurationList.class); - Assertions.assertEquals(ServiceName.SSH, model.value().get(0).serviceName()); - Assertions.assertEquals("sprozvcput", model.value().get(0).resourceId()); - Assertions.assertEquals(7394887039726775075L, model.value().get(0).port()); - Assertions.assertEquals("xofpdvhpfxxypi", model.nextLink()); + Assertions.assertEquals(ServiceName.WAC, model.value().get(0).serviceName()); + Assertions.assertEquals("gxg", model.value().get(0).resourceId()); + Assertions.assertEquals(8990974861860259667L, model.value().get(0).port()); + Assertions.assertEquals("czdzev", model.nextLink()); } } diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationPropertiesPatchTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationPropertiesPatchTests.java index 53f7d0410a1e..e01f9a809542 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationPropertiesPatchTests.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationPropertiesPatchTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; @@ -11,16 +11,16 @@ public final class ServiceConfigurationPropertiesPatchTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - ServiceConfigurationPropertiesPatch model = BinaryData.fromString("{\"port\":9010569490634453588}") + ServiceConfigurationPropertiesPatch model = BinaryData.fromString("{\"port\":5507217577010646686}") .toObject(ServiceConfigurationPropertiesPatch.class); - Assertions.assertEquals(9010569490634453588L, model.port()); + Assertions.assertEquals(5507217577010646686L, model.port()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { ServiceConfigurationPropertiesPatch model - = new ServiceConfigurationPropertiesPatch().withPort(9010569490634453588L); + = new ServiceConfigurationPropertiesPatch().withPort(5507217577010646686L); model = BinaryData.fromObject(model).toObject(ServiceConfigurationPropertiesPatch.class); - Assertions.assertEquals(9010569490634453588L, model.port()); + Assertions.assertEquals(5507217577010646686L, model.port()); } } diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationPropertiesTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationPropertiesTests.java index 171b11d8e77e..4935f4e64e0e 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationPropertiesTests.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationPropertiesTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; @@ -13,21 +13,21 @@ public final class ServiceConfigurationPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ServiceConfigurationProperties model = BinaryData.fromString( - "{\"serviceName\":\"WAC\",\"resourceId\":\"evcciqihnhun\",\"port\":4957035002722095413,\"provisioningState\":\"Failed\"}") + "{\"serviceName\":\"SSH\",\"resourceId\":\"zxtheotusivyevcc\",\"port\":6538190661575268065,\"provisioningState\":\"Creating\"}") .toObject(ServiceConfigurationProperties.class); - Assertions.assertEquals(ServiceName.WAC, model.serviceName()); - Assertions.assertEquals("evcciqihnhun", model.resourceId()); - Assertions.assertEquals(4957035002722095413L, model.port()); + Assertions.assertEquals(ServiceName.SSH, model.serviceName()); + Assertions.assertEquals("zxtheotusivyevcc", model.resourceId()); + Assertions.assertEquals(6538190661575268065L, model.port()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - ServiceConfigurationProperties model = new ServiceConfigurationProperties().withServiceName(ServiceName.WAC) - .withResourceId("evcciqihnhun") - .withPort(4957035002722095413L); + ServiceConfigurationProperties model = new ServiceConfigurationProperties().withServiceName(ServiceName.SSH) + .withResourceId("zxtheotusivyevcc") + .withPort(6538190661575268065L); model = BinaryData.fromObject(model).toObject(ServiceConfigurationProperties.class); - Assertions.assertEquals(ServiceName.WAC, model.serviceName()); - Assertions.assertEquals("evcciqihnhun", model.resourceId()); - Assertions.assertEquals(4957035002722095413L, model.port()); + Assertions.assertEquals(ServiceName.SSH, model.serviceName()); + Assertions.assertEquals("zxtheotusivyevcc", model.resourceId()); + Assertions.assertEquals(6538190661575268065L, model.port()); } } diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationResourceInnerTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationResourceInnerTests.java index ad07d89aae4e..a186c50ac29f 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationResourceInnerTests.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationResourceInnerTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; @@ -13,22 +13,22 @@ public final class ServiceConfigurationResourceInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ServiceConfigurationResourceInner model = BinaryData.fromString( - "{\"properties\":{\"serviceName\":\"WAC\",\"resourceId\":\"ayhuy\",\"port\":5121116175733126512,\"provisioningState\":\"Canceled\"},\"id\":\"po\",\"name\":\"ginuvamih\",\"type\":\"ognarxzxtheotus\"}") + "{\"properties\":{\"serviceName\":\"WAC\",\"resourceId\":\"hpf\",\"port\":7217061435098836741,\"provisioningState\":\"Creating\"},\"id\":\"nmayhuybb\",\"name\":\"podepoo\",\"type\":\"inuvamiheogn\"}") .toObject(ServiceConfigurationResourceInner.class); Assertions.assertEquals(ServiceName.WAC, model.serviceName()); - Assertions.assertEquals("ayhuy", model.resourceId()); - Assertions.assertEquals(5121116175733126512L, model.port()); + Assertions.assertEquals("hpf", model.resourceId()); + Assertions.assertEquals(7217061435098836741L, model.port()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { ServiceConfigurationResourceInner model = new ServiceConfigurationResourceInner().withServiceName(ServiceName.WAC) - .withResourceId("ayhuy") - .withPort(5121116175733126512L); + .withResourceId("hpf") + .withPort(7217061435098836741L); model = BinaryData.fromObject(model).toObject(ServiceConfigurationResourceInner.class); Assertions.assertEquals(ServiceName.WAC, model.serviceName()); - Assertions.assertEquals("ayhuy", model.resourceId()); - Assertions.assertEquals(5121116175733126512L, model.port()); + Assertions.assertEquals("hpf", model.resourceId()); + Assertions.assertEquals(7217061435098836741L, model.port()); } } diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationResourcePatchTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationResourcePatchTests.java index 9d852c08a1c5..01c33c4d75c7 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationResourcePatchTests.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationResourcePatchTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; @@ -12,16 +12,16 @@ public final class ServiceConfigurationResourcePatchTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ServiceConfigurationResourcePatch model - = BinaryData.fromString("{\"properties\":{\"port\":4533506116683097889}}") + = BinaryData.fromString("{\"properties\":{\"port\":8475415208772100172}}") .toObject(ServiceConfigurationResourcePatch.class); - Assertions.assertEquals(4533506116683097889L, model.port()); + Assertions.assertEquals(8475415208772100172L, model.port()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { ServiceConfigurationResourcePatch model - = new ServiceConfigurationResourcePatch().withPort(4533506116683097889L); + = new ServiceConfigurationResourcePatch().withPort(8475415208772100172L); model = BinaryData.fromObject(model).toObject(ServiceConfigurationResourcePatch.class); - Assertions.assertEquals(4533506116683097889L, model.port()); + Assertions.assertEquals(8475415208772100172L, model.port()); } } diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsCreateOrupdateWithResponseMockTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsCreateOrupdateWithResponseMockTests.java index ba2a1c732d37..27b0c5a9c889 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsCreateOrupdateWithResponseMockTests.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsCreateOrupdateWithResponseMockTests.java @@ -1,13 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager; import com.azure.resourcemanager.hybridconnectivity.models.ServiceConfigurationResource; @@ -22,25 +22,25 @@ public final class ServiceConfigurationsCreateOrupdateWithResponseMockTests { @Test public void testCreateOrupdateWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"serviceName\":\"WAC\",\"resourceId\":\"jjxhvpmo\",\"port\":5563523584093599698,\"provisioningState\":\"Failed\"},\"id\":\"i\",\"name\":\"qeojnxqbzvddntw\",\"type\":\"deicbtwnpzao\"}"; + = "{\"properties\":{\"serviceName\":\"SSH\",\"resourceId\":\"kcbcue\",\"port\":1999500267063441667,\"provisioningState\":\"Succeeded\"},\"id\":\"qibrhosxsdqrhzoy\",\"name\":\"i\",\"type\":\"m\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); HybridConnectivityManager manager = HybridConnectivityManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); ServiceConfigurationResource response = manager.serviceConfigurations() - .define("jctbza") - .withExistingEndpoint("mcl", "hijco") + .define("quxvypomgkop") + .withExistingEndpoint("nubexk", "zksmondj") .withServiceName(ServiceName.WAC) - .withResourceId("y") - .withPort(5593632114623401437L) + .withResourceId("jvp") + .withPort(4279032137659144852L) .create(); - Assertions.assertEquals(ServiceName.WAC, response.serviceName()); - Assertions.assertEquals("jjxhvpmo", response.resourceId()); - Assertions.assertEquals(5563523584093599698L, response.port()); + Assertions.assertEquals(ServiceName.SSH, response.serviceName()); + Assertions.assertEquals("kcbcue", response.resourceId()); + Assertions.assertEquals(1999500267063441667L, response.port()); } } diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsDeleteWithResponseMockTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsDeleteWithResponseMockTests.java index 94b73dff5725..e045a8428e4a 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsDeleteWithResponseMockTests.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsDeleteWithResponseMockTests.java @@ -1,13 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager; import java.nio.charset.StandardCharsets; @@ -25,11 +25,10 @@ public void testDeleteWithResponse() throws Exception { HybridConnectivityManager manager = HybridConnectivityManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); manager.serviceConfigurations() - .deleteWithResponse("bnbdxkqpxokajion", "imexgstxgcpodgma", "jrmvdjwzrlo", - com.azure.core.util.Context.NONE); + .deleteWithResponse("pcjwv", "hdldwmgxcxrsl", "mutwuoe", com.azure.core.util.Context.NONE); } } diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsGetWithResponseMockTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsGetWithResponseMockTests.java index 4b995fa958bb..1b390842024a 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsGetWithResponseMockTests.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsGetWithResponseMockTests.java @@ -1,13 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager; import com.azure.resourcemanager.hybridconnectivity.models.ServiceConfigurationResource; @@ -22,21 +22,21 @@ public final class ServiceConfigurationsGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"serviceName\":\"SSH\",\"resourceId\":\"c\",\"port\":643106143486636349,\"provisioningState\":\"Creating\"},\"id\":\"rhhbcs\",\"name\":\"l\",\"type\":\"mmajtjaodx\"}"; + = "{\"properties\":{\"serviceName\":\"SSH\",\"resourceId\":\"xyjrxsagafcnih\",\"port\":3130876298104392093,\"provisioningState\":\"Failed\"},\"id\":\"dgfbcvkcvqvpke\",\"name\":\"dcvd\",\"type\":\"hvoodsotbobzd\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); HybridConnectivityManager manager = HybridConnectivityManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); ServiceConfigurationResource response = manager.serviceConfigurations() - .getWithResponse("qajzyulpkudjkr", "khbzhfepgzg", "e", com.azure.core.util.Context.NONE) + .getWithResponse("ewkfvhqcrai", "vpnpp", "uflrwd", com.azure.core.util.Context.NONE) .getValue(); Assertions.assertEquals(ServiceName.SSH, response.serviceName()); - Assertions.assertEquals("c", response.resourceId()); - Assertions.assertEquals(643106143486636349L, response.port()); + Assertions.assertEquals("xyjrxsagafcnih", response.resourceId()); + Assertions.assertEquals(3130876298104392093L, response.port()); } } diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsListByEndpointResourceMockTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsListByEndpointResourceMockTests.java index c6492bbf8984..d883a2d846c1 100644 --- a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsListByEndpointResourceMockTests.java +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/ServiceConfigurationsListByEndpointResourceMockTests.java @@ -1,14 +1,14 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.hybridconnectivity.generated; import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager; import com.azure.resourcemanager.hybridconnectivity.models.ServiceConfigurationResource; @@ -23,20 +23,20 @@ public final class ServiceConfigurationsListByEndpointResourceMockTests { @Test public void testListByEndpointResource() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"serviceName\":\"SSH\",\"resourceId\":\"bnmo\",\"port\":7164396751895305600,\"provisioningState\":\"Updating\"},\"id\":\"rzafbljjgpbtoqcj\",\"name\":\"klj\",\"type\":\"vbqid\"}]}"; + = "{\"value\":[{\"properties\":{\"serviceName\":\"WAC\",\"resourceId\":\"kzzlvmbmpaxmodf\",\"port\":3624195401715068445,\"provisioningState\":\"Creating\"},\"id\":\"bpfvm\",\"name\":\"yhrfouyftaakcpw\",\"type\":\"yzvqt\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); HybridConnectivityManager manager = HybridConnectivityManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.serviceConfigurations() - .listByEndpointResource("znorcj", "vsnb", com.azure.core.util.Context.NONE); + .listByEndpointResource("rpkhjwn", "yqsluic", com.azure.core.util.Context.NONE); - Assertions.assertEquals(ServiceName.SSH, response.iterator().next().serviceName()); - Assertions.assertEquals("bnmo", response.iterator().next().resourceId()); - Assertions.assertEquals(7164396751895305600L, response.iterator().next().port()); + Assertions.assertEquals(ServiceName.WAC, response.iterator().next().serviceName()); + Assertions.assertEquals("kzzlvmbmpaxmodf", response.iterator().next().resourceId()); + Assertions.assertEquals(3624195401715068445L, response.iterator().next().port()); } } diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationInnerTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationInnerTests.java new file mode 100644 index 000000000000..094e3d72127d --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationInnerTests.java @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.SolutionConfigurationInner; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionConfigurationProperties; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionSettings; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Assertions; + +public final class SolutionConfigurationInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SolutionConfigurationInner model = BinaryData.fromString( + "{\"properties\":{\"provisioningState\":\"Canceled\",\"solutionType\":\"npwlbjnpg\",\"solutionSettings\":{\"\":{\"suesnzw\":\"adehxnltyfsopp\",\"avo\":\"ej\",\"vudwx\":\"xzdmohctb\",\"gujjugwdkcglh\":\"ndnvo\"}},\"status\":\"InProgress\",\"statusDetails\":\"jdyggdtji\",\"lastSyncTime\":\"2021-08-21T20:33:35Z\"},\"id\":\"uofqwe\",\"name\":\"kh\",\"type\":\"enevfyexfwhybci\"}") + .toObject(SolutionConfigurationInner.class); + Assertions.assertEquals("npwlbjnpg", model.properties().solutionType()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SolutionConfigurationInner model = new SolutionConfigurationInner() + .withProperties(new SolutionConfigurationProperties().withSolutionType("npwlbjnpg") + .withSolutionSettings(new SolutionSettings().withAdditionalProperties(mapOf()))); + model = BinaryData.fromObject(model).toObject(SolutionConfigurationInner.class); + Assertions.assertEquals("npwlbjnpg", model.properties().solutionType()); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationListResultTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationListResultTests.java new file mode 100644 index 000000000000..d9ec684fcf8a --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationListResultTests.java @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.hybridconnectivity.implementation.models.SolutionConfigurationListResult; +import org.junit.jupiter.api.Assertions; + +public final class SolutionConfigurationListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SolutionConfigurationListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"provisioningState\":\"Canceled\",\"solutionType\":\"ysou\",\"solutionSettings\":{\"oaeupfhyhltrpmo\":\"a\",\"uaodsfcpk\":\"jmcmatuokthfu\",\"xbezyiuokktwh\":\"xodpuozmyzydagfu\"},\"status\":\"New\",\"statusDetails\":\"zywqsmbsu\",\"lastSyncTime\":\"2021-04-26T13:01:12Z\"},\"id\":\"moryocfsfksym\",\"name\":\"dystkiiuxhqyud\",\"type\":\"o\"},{\"properties\":{\"provisioningState\":\"Succeeded\",\"solutionType\":\"b\",\"solutionSettings\":{\"rm\":\"vyifqrvkdvjsl\",\"ulexxbczwtr\":\"vdfwatkpn\",\"acspkwl\":\"wiqzbqjvsovmyo\"},\"status\":\"Failed\",\"statusDetails\":\"bpxjmfl\",\"lastSyncTime\":\"2021-10-06T08:44:01Z\"},\"id\":\"chrkcciwwzjuqk\",\"name\":\"rsa\",\"type\":\"iwkuofos\"},{\"properties\":{\"provisioningState\":\"Canceled\",\"solutionType\":\"auu\",\"solutionSettings\":{\"rfbyaosvexcso\":\"vxieduugidyj\"},\"status\":\"Completed\",\"statusDetails\":\"hocohslkev\",\"lastSyncTime\":\"2021-07-27T15:45:18Z\"},\"id\":\"zfbuhf\",\"name\":\"vfaxkffeiith\",\"type\":\"vmezy\"}],\"nextLink\":\"hxmzsbbzoggig\"}") + .toObject(SolutionConfigurationListResult.class); + Assertions.assertEquals("ysou", model.value().get(0).properties().solutionType()); + Assertions.assertEquals("hxmzsbbzoggig", model.nextLink()); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationPropertiesTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationPropertiesTests.java new file mode 100644 index 000000000000..e4512536bc66 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationPropertiesTests.java @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionConfigurationProperties; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionSettings; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Assertions; + +public final class SolutionConfigurationPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SolutionConfigurationProperties model = BinaryData.fromString( + "{\"provisioningState\":\"Canceled\",\"solutionType\":\"vdcsitynn\",\"solutionSettings\":{\"\":{\"qsc\":\"ectehf\",\"hcjrefovgmk\":\"eypvhezrkg\",\"yvxyqjp\":\"sle\"}},\"status\":\"Failed\",\"statusDetails\":\"tpngjcrcczsqpjh\",\"lastSyncTime\":\"2021-11-23T05:20:04Z\"}") + .toObject(SolutionConfigurationProperties.class); + Assertions.assertEquals("vdcsitynn", model.solutionType()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SolutionConfigurationProperties model = new SolutionConfigurationProperties().withSolutionType("vdcsitynn") + .withSolutionSettings(new SolutionSettings().withAdditionalProperties(mapOf())); + model = BinaryData.fromObject(model).toObject(SolutionConfigurationProperties.class); + Assertions.assertEquals("vdcsitynn", model.solutionType()); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsCreateOrUpdateWithResponseMockTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsCreateOrUpdateWithResponseMockTests.java new file mode 100644 index 000000000000..3bc54399f4a7 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsCreateOrUpdateWithResponseMockTests.java @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionConfiguration; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionConfigurationProperties; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionSettings; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class SolutionConfigurationsCreateOrUpdateWithResponseMockTests { + @Test + public void testCreateOrUpdateWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"provisioningState\":\"Failed\",\"solutionType\":\"mbzonokix\",\"solutionSettings\":{\"\":{\"rlazszrnw\":\"irgzp\",\"fpwpjylwbt\":\"iin\"}},\"status\":\"InProgress\",\"statusDetails\":\"sj\",\"lastSyncTime\":\"2021-10-21T17:47:33Z\"},\"id\":\"zfjvfbgofe\",\"name\":\"jagrqmqhldvr\",\"type\":\"iiojnal\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + HybridConnectivityManager manager = HybridConnectivityManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + SolutionConfiguration response = manager.solutionConfigurations() + .define("jabudurgkakmo") + .withExistingResourceUri("jxbkzbzkdvn") + .withProperties(new SolutionConfigurationProperties().withSolutionType("jk") + .withSolutionSettings(new SolutionSettings().withAdditionalProperties(mapOf()))) + .create(); + + Assertions.assertEquals("mbzonokix", response.properties().solutionType()); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsDeleteByResourceGroupWithResponseMockTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsDeleteByResourceGroupWithResponseMockTests.java new file mode 100644 index 000000000000..f12e1d7b11be --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsDeleteByResourceGroupWithResponseMockTests.java @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class SolutionConfigurationsDeleteByResourceGroupWithResponseMockTests { + @Test + public void testDeleteWithResponse() throws Exception { + String responseStr = "{}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + HybridConnectivityManager manager = HybridConnectivityManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + manager.solutionConfigurations() + .deleteByResourceGroupWithResponse("scywuggwoluhc", "bwemhairs", com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsGetWithResponseMockTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsGetWithResponseMockTests.java new file mode 100644 index 000000000000..d917907d60e9 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsGetWithResponseMockTests.java @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionConfiguration; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class SolutionConfigurationsGetWithResponseMockTests { + @Test + public void testGetWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"provisioningState\":\"Failed\",\"solutionType\":\"wae\",\"solutionSettings\":{\"\":{\"woyuhhziuief\":\"kopbminrf\",\"smlmzqhoftrm\":\"zbhd\"}},\"status\":\"New\",\"statusDetails\":\"iahxicsl\",\"lastSyncTime\":\"2021-03-06T05:00:38Z\"},\"id\":\"z\",\"name\":\"iyylhalnswhccsp\",\"type\":\"kaivwit\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + HybridConnectivityManager manager = HybridConnectivityManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + SolutionConfiguration response = manager.solutionConfigurations() + .getWithResponse("akufgmjz", "wr", com.azure.core.util.Context.NONE) + .getValue(); + + Assertions.assertEquals("wae", response.properties().solutionType()); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsListMockTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsListMockTests.java new file mode 100644 index 000000000000..9d6bc3e83fb9 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionConfigurationsListMockTests.java @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionConfiguration; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class SolutionConfigurationsListMockTests { + @Test + public void testList() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"provisioningState\":\"Canceled\",\"solutionType\":\"ggicccnxqhue\",\"solutionSettings\":{\"zrncsdt\":\"tlstvlzywem\",\"bsfgytguslfea\":\"lusiy\",\"qukyhejhzi\":\"cy\",\"srp\":\"xgfpelolppv\"},\"status\":\"InProgress\",\"statusDetails\":\"zraehtwd\",\"lastSyncTime\":\"2021-10-09T15:06:55Z\"},\"id\":\"swibyr\",\"name\":\"dl\",\"type\":\"h\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + HybridConnectivityManager manager = HybridConnectivityManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response + = manager.solutionConfigurations().list("rgzdwmsweyp", com.azure.core.util.Context.NONE); + + Assertions.assertEquals("ggicccnxqhue", response.iterator().next().properties().solutionType()); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionSettingsTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionSettingsTests.java new file mode 100644 index 000000000000..9e037110e247 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionSettingsTests.java @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionSettings; +import java.util.HashMap; +import java.util.Map; + +public final class SolutionSettingsTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SolutionSettings model = BinaryData.fromString("{\"\":{\"f\":\"dgbb\",\"bexppb\":\"dgmb\",\"rolfpfp\":\"tq\"}}") + .toObject(SolutionSettings.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SolutionSettings model = new SolutionSettings().withAdditionalProperties(mapOf()); + model = BinaryData.fromObject(model).toObject(SolutionSettings.class); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypePropertiesTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypePropertiesTests.java new file mode 100644 index 000000000000..16e6989a3aa9 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypePropertiesTests.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionTypeProperties; +import org.junit.jupiter.api.Assertions; + +public final class SolutionTypePropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SolutionTypeProperties model = BinaryData.fromString( + "{\"solutionType\":\"cuh\",\"description\":\"tcty\",\"supportedAzureRegions\":[\"lbbovplw\"],\"solutionSettings\":[{\"name\":\"vgyuguos\",\"displayName\":\"mkfssxqukkfplgm\",\"type\":\"sxnkjzkdeslpvlo\",\"description\":\"wiyighxpkdw\",\"allowedValues\":[\"aiuebbaumnyqu\",\"edeojnabc\",\"hsmtxpsiebtfhvp\"],\"defaultValue\":\"sapskr\"},{\"name\":\"qmhjjdhtld\",\"displayName\":\"kyzxuutk\",\"type\":\"cwscwsvlx\",\"description\":\"togt\",\"allowedValues\":[\"upqsx\",\"nmic\",\"kvceoveilovnotyf\"],\"defaultValue\":\"fcnj\"},{\"name\":\"k\",\"displayName\":\"nxdhbt\",\"type\":\"kphywpnvjto\",\"description\":\"nermcl\",\"allowedValues\":[\"lphox\",\"scrpabgyepsbjt\"],\"defaultValue\":\"zq\"}]}") + .toObject(SolutionTypeProperties.class); + Assertions.assertEquals("cuh", model.solutionType()); + Assertions.assertEquals("tcty", model.description()); + Assertions.assertEquals("lbbovplw", model.supportedAzureRegions().get(0)); + Assertions.assertEquals("vgyuguos", model.solutionSettings().get(0).name()); + Assertions.assertEquals("mkfssxqukkfplgm", model.solutionSettings().get(0).displayName()); + Assertions.assertEquals("sxnkjzkdeslpvlo", model.solutionSettings().get(0).type()); + Assertions.assertEquals("wiyighxpkdw", model.solutionSettings().get(0).description()); + Assertions.assertEquals("aiuebbaumnyqu", model.solutionSettings().get(0).allowedValues().get(0)); + Assertions.assertEquals("sapskr", model.solutionSettings().get(0).defaultValue()); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypeResourceInnerTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypeResourceInnerTests.java new file mode 100644 index 000000000000..ec3596419a70 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypeResourceInnerTests.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.hybridconnectivity.fluent.models.SolutionTypeResourceInner; +import org.junit.jupiter.api.Assertions; + +public final class SolutionTypeResourceInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SolutionTypeResourceInner model = BinaryData.fromString( + "{\"properties\":{\"solutionType\":\"jhtxfvgxbfsmxne\",\"description\":\"pvecxgodeb\",\"supportedAzureRegions\":[\"krbm\"],\"solutionSettings\":[{\"name\":\"gr\",\"displayName\":\"wflzlfbxzpuzy\",\"type\":\"ispnqzahmgkbrp\",\"description\":\"y\",\"allowedValues\":[\"ibnuqqkpik\",\"drgvtqagn\",\"uynhijg\"],\"defaultValue\":\"mebf\"},{\"name\":\"iarbutrcvpna\",\"displayName\":\"zmhjrunmp\",\"type\":\"ttdbhrbnl\",\"description\":\"nkxmyskpbhenbtk\",\"allowedValues\":[\"ywn\",\"tnrsyn\",\"qidybyx\",\"zfcl\"],\"defaultValue\":\"aaxdbabphlwrq\"},{\"name\":\"fkts\",\"displayName\":\"hsucoc\",\"type\":\"nyyazttbtwwrqpue\",\"description\":\"ckzywbiexzfeyue\",\"allowedValues\":[\"ibx\",\"jwbhqwalmuz\",\"oxaepd\",\"zjancuxr\"],\"defaultValue\":\"d\"}]},\"id\":\"avxbniwdjswztsdb\",\"name\":\"gnxytxhpzxbz\",\"type\":\"fzab\"}") + .toObject(SolutionTypeResourceInner.class); + Assertions.assertEquals("jhtxfvgxbfsmxne", model.properties().solutionType()); + Assertions.assertEquals("pvecxgodeb", model.properties().description()); + Assertions.assertEquals("krbm", model.properties().supportedAzureRegions().get(0)); + Assertions.assertEquals("gr", model.properties().solutionSettings().get(0).name()); + Assertions.assertEquals("wflzlfbxzpuzy", model.properties().solutionSettings().get(0).displayName()); + Assertions.assertEquals("ispnqzahmgkbrp", model.properties().solutionSettings().get(0).type()); + Assertions.assertEquals("y", model.properties().solutionSettings().get(0).description()); + Assertions.assertEquals("ibnuqqkpik", model.properties().solutionSettings().get(0).allowedValues().get(0)); + Assertions.assertEquals("mebf", model.properties().solutionSettings().get(0).defaultValue()); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypeResourceListResultTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypeResourceListResultTests.java new file mode 100644 index 000000000000..ac77858608bc --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypeResourceListResultTests.java @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.hybridconnectivity.implementation.models.SolutionTypeResourceListResult; +import org.junit.jupiter.api.Assertions; + +public final class SolutionTypeResourceListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SolutionTypeResourceListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"solutionType\":\"dw\",\"description\":\"ntxhdzhlrqjbhck\",\"supportedAzureRegions\":[\"hrxsbk\",\"vpycanuzbp\",\"kafkuwbcrnwbm\"],\"solutionSettings\":[{\"name\":\"seyvj\",\"displayName\":\"srtslhspkdeem\",\"type\":\"ofmxagkvtmelmqkr\",\"description\":\"ahvljuaha\",\"allowedValues\":[\"hcdhmdual\",\"exq\"],\"defaultValue\":\"vfadmws\"},{\"name\":\"crgvxpvgom\",\"displayName\":\"lf\",\"type\":\"isgwbnbbeldawkz\",\"description\":\"ali\",\"allowedValues\":[\"rqhakauha\",\"hsfwxosowzxcug\"],\"defaultValue\":\"cjooxdjebwpucwwf\"}]},\"id\":\"vbvmeu\",\"name\":\"civyhzceuo\",\"type\":\"gjrwjueiotwmcdyt\"},{\"properties\":{\"solutionType\":\"it\",\"description\":\"rjaw\",\"supportedAzureRegions\":[\"gxhnisk\",\"fbkp\"],\"solutionSettings\":[{\"name\":\"klwndnhjdauwhv\",\"displayName\":\"l\",\"type\":\"zbtd\",\"description\":\"xujznbmpowu\",\"allowedValues\":[\"rzqlveu\",\"lupj\"],\"defaultValue\":\"khfxobbcswsrt\"},{\"name\":\"riplrbpbewtg\",\"displayName\":\"fgb\",\"type\":\"c\",\"description\":\"wxzvlvqhjkb\",\"allowedValues\":[\"ibtnmxiebwwaloay\",\"cgwrtzjuz\"],\"defaultValue\":\"wyzmhtxon\"}]},\"id\":\"ts\",\"name\":\"vjcbpwxqpsrknf\",\"type\":\"guvriuhprwmd\"},{\"properties\":{\"solutionType\":\"qtayri\",\"description\":\"ro\",\"supportedAzureRegions\":[\"exrmcqibycnojvk\",\"mefqsgzvahapjyzh\"],\"solutionSettings\":[{\"name\":\"qzcjrvxdj\",\"displayName\":\"lmwlxkvugfhzo\",\"type\":\"awjvzunluthnnp\",\"description\":\"nxipeil\",\"allowedValues\":[\"zuaejxd\",\"ltskzbbtd\",\"umveekgpwozuhkf\",\"bsjyofdx\"],\"defaultValue\":\"uusdttouwa\"},{\"name\":\"oekqvk\",\"displayName\":\"lns\",\"type\":\"vbxwyjsflhh\",\"description\":\"aalnjixi\",\"allowedValues\":[\"yaw\",\"oyaqcslyjpkiid\"],\"defaultValue\":\"yexz\"}]},\"id\":\"lixhnrztfol\",\"name\":\"bnxknalaulppg\",\"type\":\"dtpnapnyiropuhp\"},{\"properties\":{\"solutionType\":\"pgylg\",\"description\":\"itxmedjvcslynqww\",\"supportedAzureRegions\":[\"zzhxgktrm\"],\"solutionSettings\":[{\"name\":\"napkteoellw\",\"displayName\":\"tfdygpfqb\",\"type\":\"ac\",\"description\":\"op\",\"allowedValues\":[\"qrhhu\",\"opppcqeq\",\"ol\"],\"defaultValue\":\"dahzxctobg\"},{\"name\":\"kdmoi\",\"displayName\":\"postmgrcfbunrm\",\"type\":\"qjhhkxbpv\",\"description\":\"ymjhxxjyngudivkr\",\"allowedValues\":[\"wbxqzvszjfau\",\"j\"],\"defaultValue\":\"dxxiv\"},{\"name\":\"tvtc\",\"displayName\":\"aqtdoqmcbx\",\"type\":\"wvxysl\",\"description\":\"bhsfxob\",\"allowedValues\":[\"tkblmpewww\",\"bkrvrnsvshqj\",\"hxcr\"],\"defaultValue\":\"bfovasrruvwbhsq\"}]},\"id\":\"ubcgjbirxb\",\"name\":\"ybsrfbjfdtwss\",\"type\":\"t\"}],\"nextLink\":\"pvjzbe\"}") + .toObject(SolutionTypeResourceListResult.class); + Assertions.assertEquals("dw", model.value().get(0).properties().solutionType()); + Assertions.assertEquals("ntxhdzhlrqjbhck", model.value().get(0).properties().description()); + Assertions.assertEquals("hrxsbk", model.value().get(0).properties().supportedAzureRegions().get(0)); + Assertions.assertEquals("seyvj", model.value().get(0).properties().solutionSettings().get(0).name()); + Assertions.assertEquals("srtslhspkdeem", + model.value().get(0).properties().solutionSettings().get(0).displayName()); + Assertions.assertEquals("ofmxagkvtmelmqkr", model.value().get(0).properties().solutionSettings().get(0).type()); + Assertions.assertEquals("ahvljuaha", model.value().get(0).properties().solutionSettings().get(0).description()); + Assertions.assertEquals("hcdhmdual", + model.value().get(0).properties().solutionSettings().get(0).allowedValues().get(0)); + Assertions.assertEquals("vfadmws", model.value().get(0).properties().solutionSettings().get(0).defaultValue()); + Assertions.assertEquals("pvjzbe", model.nextLink()); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypeSettingsPropertiesTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypeSettingsPropertiesTests.java new file mode 100644 index 000000000000..3318a2a4586b --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypeSettingsPropertiesTests.java @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionTypeSettingsProperties; +import org.junit.jupiter.api.Assertions; + +public final class SolutionTypeSettingsPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SolutionTypeSettingsProperties model = BinaryData.fromString( + "{\"name\":\"gxywpmue\",\"displayName\":\"fjz\",\"type\":\"fqkquj\",\"description\":\"dsuyonobgla\",\"allowedValues\":[\"qxtccmgyudx\"],\"defaultValue\":\"tlmoyrx\"}") + .toObject(SolutionTypeSettingsProperties.class); + Assertions.assertEquals("gxywpmue", model.name()); + Assertions.assertEquals("fjz", model.displayName()); + Assertions.assertEquals("fqkquj", model.type()); + Assertions.assertEquals("dsuyonobgla", model.description()); + Assertions.assertEquals("qxtccmgyudx", model.allowedValues().get(0)); + Assertions.assertEquals("tlmoyrx", model.defaultValue()); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypeSettingsTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypeSettingsTests.java new file mode 100644 index 000000000000..6226ff991523 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypeSettingsTests.java @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionSettings; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionTypeSettings; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Assertions; + +public final class SolutionTypeSettingsTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SolutionTypeSettings model = BinaryData.fromString( + "{\"solutionType\":\"qsrxybzqqed\",\"solutionSettings\":{\"\":{\"lmmnkzsmodmglo\":\"ciqfou\",\"uqktap\":\"gpbkwtmut\",\"kdosvqw\":\"pwgcuertu\"}}}") + .toObject(SolutionTypeSettings.class); + Assertions.assertEquals("qsrxybzqqed", model.solutionType()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SolutionTypeSettings model = new SolutionTypeSettings().withSolutionType("qsrxybzqqed") + .withSolutionSettings(new SolutionSettings().withAdditionalProperties(mapOf())); + model = BinaryData.fromObject(model).toObject(SolutionTypeSettings.class); + Assertions.assertEquals("qsrxybzqqed", model.solutionType()); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypesGetByResourceGroupWithResponseMockTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypesGetByResourceGroupWithResponseMockTests.java new file mode 100644 index 000000000000..06e250ba2000 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypesGetByResourceGroupWithResponseMockTests.java @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionTypeResource; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class SolutionTypesGetByResourceGroupWithResponseMockTests { + @Test + public void testGetByResourceGroupWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"solutionType\":\"opgxedkowepb\",\"description\":\"cr\",\"supportedAzureRegions\":[\"wccsnjvcdwxlpqek\",\"tn\",\"htjsying\",\"fq\"],\"solutionSettings\":[{\"name\":\"tdhtmdvyp\",\"displayName\":\"ikdgszywkbir\",\"type\":\"yuzhlhkjoqrvq\",\"description\":\"aatjinrvgoupmfi\",\"allowedValues\":[\"fggjioolvr\",\"x\",\"v\"],\"defaultValue\":\"kkgll\"}]},\"id\":\"jygvjayvbl\",\"name\":\"hvkzuh\",\"type\":\"xvvy\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + HybridConnectivityManager manager = HybridConnectivityManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + SolutionTypeResource response = manager.solutionTypes() + .getByResourceGroupWithResponse("mfe", "kerqwkyh", com.azure.core.util.Context.NONE) + .getValue(); + + Assertions.assertEquals("opgxedkowepb", response.properties().solutionType()); + Assertions.assertEquals("cr", response.properties().description()); + Assertions.assertEquals("wccsnjvcdwxlpqek", response.properties().supportedAzureRegions().get(0)); + Assertions.assertEquals("tdhtmdvyp", response.properties().solutionSettings().get(0).name()); + Assertions.assertEquals("ikdgszywkbir", response.properties().solutionSettings().get(0).displayName()); + Assertions.assertEquals("yuzhlhkjoqrvq", response.properties().solutionSettings().get(0).type()); + Assertions.assertEquals("aatjinrvgoupmfi", response.properties().solutionSettings().get(0).description()); + Assertions.assertEquals("fggjioolvr", response.properties().solutionSettings().get(0).allowedValues().get(0)); + Assertions.assertEquals("kkgll", response.properties().solutionSettings().get(0).defaultValue()); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypesListByResourceGroupMockTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypesListByResourceGroupMockTests.java new file mode 100644 index 000000000000..49ae4bbb4a3d --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypesListByResourceGroupMockTests.java @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionTypeResource; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class SolutionTypesListByResourceGroupMockTests { + @Test + public void testListByResourceGroup() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"solutionType\":\"fbn\",\"description\":\"mctlpdngitv\",\"supportedAzureRegions\":[\"hrixkwmy\",\"jejveg\",\"hbpnaixexccbd\",\"eaxhcexdrrvqahqk\"],\"solutionSettings\":[{\"name\":\"pwijnhy\",\"displayName\":\"svfycxzbfv\",\"type\":\"owvrvmtgjqppyos\",\"description\":\"ronzmyhgfip\",\"allowedValues\":[\"xkmcwaekrrjre\"],\"defaultValue\":\"fxtsgum\"},{\"name\":\"jglikkxwslolb\",\"displayName\":\"pvuzlmv\",\"type\":\"elfk\",\"description\":\"gplcrpwjxeznoigb\",\"allowedValues\":[\"jwmwkpnbs\",\"zejjoqk\",\"gfhsxttaugzxn\",\"aa\"],\"defaultValue\":\"pxdtnkdmkq\"}]},\"id\":\"lwuenvrkp\",\"name\":\"ou\",\"type\":\"ibreb\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + HybridConnectivityManager manager = HybridConnectivityManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response + = manager.solutionTypes().listByResourceGroup("gsopbyrqufegxu", com.azure.core.util.Context.NONE); + + Assertions.assertEquals("fbn", response.iterator().next().properties().solutionType()); + Assertions.assertEquals("mctlpdngitv", response.iterator().next().properties().description()); + Assertions.assertEquals("hrixkwmy", response.iterator().next().properties().supportedAzureRegions().get(0)); + Assertions.assertEquals("pwijnhy", response.iterator().next().properties().solutionSettings().get(0).name()); + Assertions.assertEquals("svfycxzbfv", + response.iterator().next().properties().solutionSettings().get(0).displayName()); + Assertions.assertEquals("owvrvmtgjqppyos", + response.iterator().next().properties().solutionSettings().get(0).type()); + Assertions.assertEquals("ronzmyhgfip", + response.iterator().next().properties().solutionSettings().get(0).description()); + Assertions.assertEquals("xkmcwaekrrjre", + response.iterator().next().properties().solutionSettings().get(0).allowedValues().get(0)); + Assertions.assertEquals("fxtsgum", + response.iterator().next().properties().solutionSettings().get(0).defaultValue()); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypesListMockTests.java b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypesListMockTests.java new file mode 100644 index 000000000000..a8126a484a58 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/src/test/java/com/azure/resourcemanager/hybridconnectivity/generated/SolutionTypesListMockTests.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.hybridconnectivity.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.hybridconnectivity.HybridConnectivityManager; +import com.azure.resourcemanager.hybridconnectivity.models.SolutionTypeResource; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class SolutionTypesListMockTests { + @Test + public void testList() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"solutionType\":\"ysjkixqtnqttez\",\"description\":\"fffiak\",\"supportedAzureRegions\":[\"qqmtedltmmji\",\"yeozphvwauyqncy\"],\"solutionSettings\":[{\"name\":\"kvi\",\"displayName\":\"mdscwxqupev\",\"type\":\"hfstotxhojujbyp\",\"description\":\"lmcuvhixb\",\"allowedValues\":[\"yfwnylr\",\"ool\",\"ttpkiwkkbnujrywv\"],\"defaultValue\":\"y\"}]},\"id\":\"fpncurdo\",\"name\":\"wiithtywub\",\"type\":\"cbihwqk\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + HybridConnectivityManager manager = HybridConnectivityManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response = manager.solutionTypes().list(com.azure.core.util.Context.NONE); + + Assertions.assertEquals("ysjkixqtnqttez", response.iterator().next().properties().solutionType()); + Assertions.assertEquals("fffiak", response.iterator().next().properties().description()); + Assertions.assertEquals("qqmtedltmmji", response.iterator().next().properties().supportedAzureRegions().get(0)); + Assertions.assertEquals("kvi", response.iterator().next().properties().solutionSettings().get(0).name()); + Assertions.assertEquals("mdscwxqupev", + response.iterator().next().properties().solutionSettings().get(0).displayName()); + Assertions.assertEquals("hfstotxhojujbyp", + response.iterator().next().properties().solutionSettings().get(0).type()); + Assertions.assertEquals("lmcuvhixb", + response.iterator().next().properties().solutionSettings().get(0).description()); + Assertions.assertEquals("yfwnylr", + response.iterator().next().properties().solutionSettings().get(0).allowedValues().get(0)); + Assertions.assertEquals("y", response.iterator().next().properties().solutionSettings().get(0).defaultValue()); + } +} diff --git a/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/tsp-location.yaml b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/tsp-location.yaml new file mode 100644 index 000000000000..db0257133a83 --- /dev/null +++ b/sdk/hybridconnectivity/azure-resourcemanager-hybridconnectivity/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/hybridconnectivity/HybridConnectivity.Management +commit: 5eebf11c2c98feded3199df1a68ccf6d2c626d63 +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/hybridcontainerservice/azure-resourcemanager-hybridcontainerservice/README.md b/sdk/hybridcontainerservice/azure-resourcemanager-hybridcontainerservice/README.md index 63e7343a512d..3f84919ec014 100644 --- a/sdk/hybridcontainerservice/azure-resourcemanager-hybridcontainerservice/README.md +++ b/sdk/hybridcontainerservice/azure-resourcemanager-hybridcontainerservice/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-hybridcontainerservice - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fhybridcontainerservice%2Fazure-resourcemanager-hybridcontainerservice%2FREADME.png) + diff --git a/sdk/hybridcontainerservice/azure-resourcemanager-hybridcontainerservice/pom.xml b/sdk/hybridcontainerservice/azure-resourcemanager-hybridcontainerservice/pom.xml index 3f3df7f19d82..9a86e56cdaea 100644 --- a/sdk/hybridcontainerservice/azure-resourcemanager-hybridcontainerservice/pom.xml +++ b/sdk/hybridcontainerservice/azure-resourcemanager-hybridcontainerservice/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/hybridkubernetes/azure-resourcemanager-hybridkubernetes/README.md b/sdk/hybridkubernetes/azure-resourcemanager-hybridkubernetes/README.md index 02412a1b83c0..c55add89dcc3 100644 --- a/sdk/hybridkubernetes/azure-resourcemanager-hybridkubernetes/README.md +++ b/sdk/hybridkubernetes/azure-resourcemanager-hybridkubernetes/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-hybridkubernetes - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fhybridkubernetes%2Fazure-resourcemanager-hybridkubernetes%2FREADME.png) + diff --git a/sdk/hybridkubernetes/azure-resourcemanager-hybridkubernetes/pom.xml b/sdk/hybridkubernetes/azure-resourcemanager-hybridkubernetes/pom.xml index 8efc45aeca51..3634e945e3ad 100644 --- a/sdk/hybridkubernetes/azure-resourcemanager-hybridkubernetes/pom.xml +++ b/sdk/hybridkubernetes/azure-resourcemanager-hybridkubernetes/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/hybridnetwork/azure-resourcemanager-hybridnetwork/README.md b/sdk/hybridnetwork/azure-resourcemanager-hybridnetwork/README.md index f94adedff4da..a42150eddfd6 100644 --- a/sdk/hybridnetwork/azure-resourcemanager-hybridnetwork/README.md +++ b/sdk/hybridnetwork/azure-resourcemanager-hybridnetwork/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-hybridnetwork - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fhybridnetwork%2Fazure-resourcemanager-hybridnetwork%2FREADME.png) + diff --git a/sdk/hybridnetwork/azure-resourcemanager-hybridnetwork/pom.xml b/sdk/hybridnetwork/azure-resourcemanager-hybridnetwork/pom.xml index 281111750396..ddbb8f7b50c2 100644 --- a/sdk/hybridnetwork/azure-resourcemanager-hybridnetwork/pom.xml +++ b/sdk/hybridnetwork/azure-resourcemanager-hybridnetwork/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/identity/azure-identity-broker-samples/pom.xml b/sdk/identity/azure-identity-broker-samples/pom.xml index fe03d38d615b..30c04b35cc0f 100644 --- a/sdk/identity/azure-identity-broker-samples/pom.xml +++ b/sdk/identity/azure-identity-broker-samples/pom.xml @@ -129,7 +129,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 true @@ -156,7 +156,7 @@ org.apache.maven.plugins maven-checkstyle-plugin - 3.5.0 + 3.6.0 true diff --git a/sdk/identity/azure-identity-broker/CHANGELOG.md b/sdk/identity/azure-identity-broker/CHANGELOG.md index ed0424489d0e..fe588527219d 100644 --- a/sdk/identity/azure-identity-broker/CHANGELOG.md +++ b/sdk/identity/azure-identity-broker/CHANGELOG.md @@ -10,6 +10,37 @@ ### Other Changes +## 1.1.13 (2025-03-11) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-identity` from `1.15.3` to version `1.15.4`. +- Upgraded `msal4j` from `1.19.0` to version `1.19.1 + +## 1.1.12 (2025-02-20) + +### Breaking Changes + +#### Dependency Updates + +- Upgraded `azure-identity` from `1.15.2` to `1.15.3` + +## 1.1.11 (2025-02-07) + +### Other Changes + +#### Dependency Updates +- Upgraded `azure-identity` from `1.15.1` to `1.15.2` + +## 1.1.10 (2025-02-07) + +### Other Changes +- +- Upgraded `azure-identity` from `1.15.0` to `1.15.1` +- Upgraded `msal4j` from `1.17.2` to `1.19.0` + ## 1.1.9 (2025-01-10) ### Other Changes diff --git a/sdk/identity/azure-identity-broker/README.md b/sdk/identity/azure-identity-broker/README.md index da3b9134536d..92d6804f9f64 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.1.8 + 1.1.13 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/identity/azure-identity-broker/pom.xml b/sdk/identity/azure-identity-broker/pom.xml index 0f482706a74f..6f765a534b1a 100644 --- a/sdk/identity/azure-identity-broker/pom.xml +++ b/sdk/identity/azure-identity-broker/pom.xml @@ -44,7 +44,7 @@ com.microsoft.azure msal4j - 1.17.2 + 1.19.1 com.microsoft.azure @@ -69,7 +69,7 @@ - com.microsoft.azure:msal4j:[1.17.2] + com.microsoft.azure:msal4j:[1.19.1] com.microsoft.azure:msal4j-brokers:[1.0.0] diff --git a/sdk/identity/azure-identity-extensions/Azure-Database-for-MySQL-README.md b/sdk/identity/azure-identity-extensions/Azure-Database-for-MySQL-README.md index 3390bd8feb6b..15e6df9e8dfc 100644 --- a/sdk/identity/azure-identity-extensions/Azure-Database-for-MySQL-README.md +++ b/sdk/identity/azure-identity-extensions/Azure-Database-for-MySQL-README.md @@ -55,7 +55,7 @@ The package is not part of the `azure-sdk-bom` now, so it can only be included v com.azure azure-identity-extensions - 1.2.0 + 1.3.0-beta.1 ``` diff --git a/sdk/identity/azure-identity-extensions/Azure-Database-for-PostgreSQL-README.md b/sdk/identity/azure-identity-extensions/Azure-Database-for-PostgreSQL-README.md index d9cdedac352c..4cc5d2282a7b 100644 --- a/sdk/identity/azure-identity-extensions/Azure-Database-for-PostgreSQL-README.md +++ b/sdk/identity/azure-identity-extensions/Azure-Database-for-PostgreSQL-README.md @@ -55,7 +55,7 @@ The package is not part of the `azure-sdk-bom` now, so it can only be included v com.azure azure-identity-extensions - 1.2.0 + 1.3.0-beta.1 ``` diff --git a/sdk/identity/azure-identity-extensions/CHANGELOG.md b/sdk/identity/azure-identity-extensions/CHANGELOG.md index 5a7ea60e6f0b..a15e8341bda5 100644 --- a/sdk/identity/azure-identity-extensions/CHANGELOG.md +++ b/sdk/identity/azure-identity-extensions/CHANGELOG.md @@ -10,6 +10,15 @@ ### Other Changes +## 1.2.1 (2025-02-25) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-identity` from `1.15.0` to version `1.15.3`. + + ## 1.2.0 (2025-01-16) ### Features Added diff --git a/sdk/identity/azure-identity-extensions/README.md b/sdk/identity/azure-identity-extensions/README.md index 343ade3824d5..20d116245451 100644 --- a/sdk/identity/azure-identity-extensions/README.md +++ b/sdk/identity/azure-identity-extensions/README.md @@ -1,14 +1,3 @@ -- [Azure identity authentication extensions plugin library for Java](#azure-identity-authentication-extensions-plugin-library-for-java) - - [Getting started](#getting-started) - - [Prerequisites](#prerequisites) - - [Key concepts](#key-concepts) - - [Architecture](#architecture) - - [Authenticating with JDBC](#authenticating-with-jdbc) - - [Examples](#examples) - - [Troubleshooting](#troubleshooting) - - [Next steps](#next-steps) - - [Contributing](#contributing) - # Azure identity authentication extensions plugin library for Java This package contains authentication extensions to get a token from Microsoft Entra ID for Azure services, like Azure Database for MySQL. @@ -33,7 +22,7 @@ token as a password to connect with MySQL. ### Authenticating with JDBC This picture shows how the JDBC authentication plugins provided by Azure Identity Extensions authenticate with managed identity. -![Architecture](img/passwordless-connections-from-java-apps-to-data-services.jpg) +![Architecture](https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/identity/azure-identity-extensions/img/passwordless-connections-from-java-apps-to-data-services.jpg) ## Examples For documentation on how to use this package, please refer to [Quickstart:Use Java and JDBC with Azure Database for MySQL](https://aka.ms/passwordless/quickstart/mysql) and [Quickstart:Use Java and JDBC with Azure Database for PostgreSQL](https://aka.ms/passwordless/quickstart/postgresql). diff --git a/sdk/identity/azure-identity-extensions/pom.xml b/sdk/identity/azure-identity-extensions/pom.xml index 43b1f7cbd8c8..a78d6fdb7ef6 100644 --- a/sdk/identity/azure-identity-extensions/pom.xml +++ b/sdk/identity/azure-identity-extensions/pom.xml @@ -41,7 +41,7 @@ com.azure azure-identity - 1.15.0 + 1.15.4 @@ -108,7 +108,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 false diff --git a/sdk/identity/azure-identity-extensions/src/main/java/com/azure/identity/extensions/implementation/credential/provider/CachingTokenCredentialProvider.java b/sdk/identity/azure-identity-extensions/src/main/java/com/azure/identity/extensions/implementation/credential/provider/CachingTokenCredentialProvider.java index 40df900f2ce1..32df03f08bbc 100644 --- a/sdk/identity/azure-identity-extensions/src/main/java/com/azure/identity/extensions/implementation/credential/provider/CachingTokenCredentialProvider.java +++ b/sdk/identity/azure-identity-extensions/src/main/java/com/azure/identity/extensions/implementation/credential/provider/CachingTokenCredentialProvider.java @@ -58,7 +58,7 @@ private static TokenCredential getOrCreate(Map cache, LOGGER.verbose("Retrieving token credential from cache."); } else { LOGGER.verbose("Caching token credential."); - cache.put(tokenCredentialCacheKey, fn.apply(delegate)); + cache.putIfAbsent(tokenCredentialCacheKey, fn.apply(delegate)); } return cache.get(tokenCredentialCacheKey); diff --git a/sdk/identity/azure-identity-extensions/src/main/java/com/azure/identity/extensions/implementation/credential/provider/DefaultTokenCredentialProvider.java b/sdk/identity/azure-identity-extensions/src/main/java/com/azure/identity/extensions/implementation/credential/provider/DefaultTokenCredentialProvider.java index 0ebfb4c525e9..e30ce7700164 100644 --- a/sdk/identity/azure-identity-extensions/src/main/java/com/azure/identity/extensions/implementation/credential/provider/DefaultTokenCredentialProvider.java +++ b/sdk/identity/azure-identity-extensions/src/main/java/com/azure/identity/extensions/implementation/credential/provider/DefaultTokenCredentialProvider.java @@ -15,6 +15,7 @@ /** * Default tokenCredentialProvider implementation that provides tokenCredential instance. */ +@SuppressWarnings("deprecation") public class DefaultTokenCredentialProvider implements TokenCredentialProvider { private final TokenCredentialProviderOptions options; diff --git a/sdk/identity/azure-identity-extensions/src/test/java/com/azure/identity/extensions/implementation/template/AzureAuthenticationTemplateTest.java b/sdk/identity/azure-identity-extensions/src/test/java/com/azure/identity/extensions/implementation/template/AzureAuthenticationTemplateTest.java index 67280d158407..e6d63c583056 100644 --- a/sdk/identity/azure-identity-extensions/src/test/java/com/azure/identity/extensions/implementation/template/AzureAuthenticationTemplateTest.java +++ b/sdk/identity/azure-identity-extensions/src/test/java/com/azure/identity/extensions/implementation/template/AzureAuthenticationTemplateTest.java @@ -117,7 +117,7 @@ void nonCacheTokenCredential() { } @Test - void getTokenAsPasswordWithDefaultCredentialProvider() throws InterruptedException { + void verityTokeWithDefaultCredentialProvider() throws InterruptedException { // setup String token1 = "token1"; String token2 = "token2"; @@ -152,7 +152,7 @@ void getTokenAsPasswordWithDefaultCredentialProvider() throws InterruptedExcepti } @Test - void getTokenAsPasswordWithCachingCredentialProvider() throws InterruptedException { + void verityTokenWithCachingCredentialProvider() throws InterruptedException { int tokenExpireSeconds = 2; AtomicInteger tokenIndex1 = new AtomicInteger(); AtomicInteger tokenIndex2 = new AtomicInteger(1); @@ -180,7 +180,7 @@ void getTokenAsPasswordWithCachingCredentialProvider() throws InterruptedExcepti verifyToken("token1-", 0, template); TimeUnit.SECONDS.sleep(tokenExpireSeconds + 1); - verifyToken("token2-", 1, template); + verifyToken("token2-", 1, template2); assertNotNull(credentialProviderMock); } } diff --git a/sdk/identity/azure-identity-perf/pom.xml b/sdk/identity/azure-identity-perf/pom.xml index ea64e57cb04d..0267cd832bae 100644 --- a/sdk/identity/azure-identity-perf/pom.xml +++ b/sdk/identity/azure-identity-perf/pom.xml @@ -36,13 +36,13 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 diff --git a/sdk/identity/azure-identity-v2/CHANGELOG.md b/sdk/identity/azure-identity-v2/CHANGELOG.md new file mode 100644 index 000000000000..567d6975765a --- /dev/null +++ b/sdk/identity/azure-identity-v2/CHANGELOG.md @@ -0,0 +1,11 @@ +# Release History + +## 2.0.0-beta.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes diff --git a/sdk/identity/azure-identity-v2/README.md b/sdk/identity/azure-identity-v2/README.md new file mode 100644 index 000000000000..e870ac427c59 --- /dev/null +++ b/sdk/identity/azure-identity-v2/README.md @@ -0,0 +1,49 @@ +# Azure Identity client library for Java + +The Azure Identity V2 library provides [Microsoft Entra ID](https://learn.microsoft.com/entra/fundamentals/whatis) ([formerly Azure Active Directory](https://learn.microsoft.com/entra/fundamentals/new-name)) token authentication support across the Azure SDK. + +## Getting started + +### Include the package + +#### Include the BOM file + +#### Include direct dependency + +To take dependency on a particular version of the library that isn't present in the BOM, add the direct dependency to your project as follows: + +[//]: # ({x-version-update-start;com.azure:azure-identity-v2;dependency}) +```xml + + com.azure + azure-identity-v2 + 2.0.0-beta.1 + +``` +[//]: # ({x-version-update-end}) + +### Prerequisites + +### Authenticate the client + +## Key concepts + +## Examples + + +## Troubleshooting + + +## Next steps + + +## Contributing + +This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com. + +When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. + +This project has adopted the [Microsoft Open Source Code of Conduct][code_of_conduct]. For more information, see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments. + + +[code_of_conduct]: https://opensource.microsoft.com/codeofconduct/ diff --git a/sdk/identity/azure-identity-v2/pom.xml b/sdk/identity/azure-identity-v2/pom.xml new file mode 100644 index 000000000000..0aa870bad0e1 --- /dev/null +++ b/sdk/identity/azure-identity-v2/pom.xml @@ -0,0 +1,133 @@ + + 4.0.0 + + + com.azure.v2 + azure-client-sdk-parent + 2.0.0-beta.1 + ../../parents/azure-client-sdk-parent-v2 + + + com.azure + azure-identity-v2 + jar + 2.0.0-beta.1 + + Microsoft Azure Identity V2 Library + This package contains core types for Azure Java V2 clients. + https://github.com/Azure/azure-sdk-for-java + + + + The MIT License (MIT) + http://opensource.org/licenses/MIT + repo + + + + + + azure-java-build-docs + ${site.url}/site/${project.artifactId} + + + + + https://github.com/Azure/azure-sdk-for-java + scm:git:https://github.com/Azure/azure-sdk-for-java.git + scm:git:https://github.com/Azure/azure-sdk-for-java.git + + + + UTF-8 + + 0.10 + 0.10 + + + + + microsoft + Microsoft + + + + + + + com.azure.v2 + azure-core + 2.0.0-beta.1 + + + + com.microsoft.azure + msal4j-persistence-extension + 1.3.0 + + + + com.microsoft.azure + msal4j + 1.19.1 + + + + org.junit.jupiter + junit-jupiter-api + 5.11.2 + test + + + + org.junit.jupiter + junit-jupiter-engine + 5.11.2 + test + + + + org.junit.jupiter + junit-jupiter-params + 5.11.2 + test + + + + org.mockito + mockito-inline + 4.11.0 + test + + + + net.bytebuddy + byte-buddy + 1.14.10 + test + + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.5.0 + + + + + com.microsoft.azure:msal4j:[1.19.1] + com.microsoft.azure:msal4j-persistence-extension:[1.3.0] + + + + + + + + + diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/AuthenticationRecord.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/AuthenticationRecord.java new file mode 100644 index 000000000000..fae103109740 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/AuthenticationRecord.java @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2; + +import com.microsoft.aad.msal4j.IAuthenticationResult; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.serialization.json.JsonWriter; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +/** + *

        Authentication Record represents the account information of the authenticated account. + * This is helpful in scenarios where applications require brokered authentication via + * {@link InteractiveBrowserCredential}.

        + * + *

        Authentication record is returned when {@link InteractiveBrowserCredential#authenticate()} api is invoked. + * The returned auth record can be stored/persisted in the user application. Further, this record can be configured on + * the {@link InteractiveBrowserCredentialBuilder#authenticationRecord(AuthenticationRecord)} to proactively indicate + * that a previously authenticated account should be used from the persisted cache instead of authenticating again.

        + * + * @see InteractiveBrowserCredential + */ +public final class AuthenticationRecord { + + static final ClientLogger LOGGER = new ClientLogger(AuthenticationRecord.class); + + private String authority; + + private String homeAccountId; + + private String tenantId; + + private String username; + + private String clientId; + + AuthenticationRecord() { + } + + AuthenticationRecord(IAuthenticationResult authenticationResult, String tenantId, String clientId) { + this(authenticationResult.account().environment(), authenticationResult.account().homeAccountId(), + authenticationResult.account().username(), tenantId, clientId); + } + + AuthenticationRecord(String authority, String homeAccountId, String userName, String tenantId, String clientId) { + this.authority = authority; + this.homeAccountId = homeAccountId; + this.tenantId = tenantId; + this.username = userName; + this.clientId = clientId; + } + + /** + * Get the authority host used to authenticate the account. + * + * @return the authority host. + */ + public String getAuthority() { + return authority; + } + + /** + * Get the unique identifier of the account. + * + * @return the account id. + */ + public String getHomeAccountId() { + return homeAccountId; + } + + /** + * Get the tenant, which the account authenticated in. + * + * @return the tenant id. + */ + public String getTenantId() { + return tenantId; + } + + /** + * Get the client id of the application used for authentication. + * + * @return the client id. + */ + public String getClientId() { + return clientId; + } + + /** + * Get the user principal name of the account. + * + * @return the username. + */ + public String getUsername() { + return username; + } + + /** + * Serializes the {@link AuthenticationRecord} to the specified {@link OutputStream} + * + * @param outputStream The {@link OutputStream} to which the serialized record will be written to. + */ + public void serialize(OutputStream outputStream) { + try (JsonWriter writer = JsonWriter.toStream(outputStream)) { + writer.writeStartObject(); + writer.writeStringField("authority", authority); + writer.writeStringField("homeAccountId", homeAccountId); + writer.writeStringField("tenantId", tenantId); + writer.writeStringField("username", username); + writer.writeStringField("clientId", clientId); + writer.writeEndObject(); + } catch (IOException e) { + throw LOGGER.logThrowableAsError(new RuntimeException(e)); + } + } + + /** + * Deserializes the {@link AuthenticationRecord} from the specified {@link InputStream} + * + * @param inputStream The {@link InputStream} from which the serialized record will be read. + * @return the {@link AuthenticationRecord} object. + */ + public static AuthenticationRecord deserialize(InputStream inputStream) { + try (JsonReader jsonReader = JsonReader.fromStream(inputStream)) { + return jsonReader.readObject(reader -> { + String authority = null; + String homeAccountId = null; + String tenantId = null; + String username = null; + String clientId = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("authority".equals(fieldName)) { + authority = reader.getString(); + } else if ("homeAccountId".equals(fieldName)) { + homeAccountId = reader.getString(); + } else if ("tenantId".equals(fieldName)) { + tenantId = reader.getString(); + } else if ("username".equals(fieldName)) { + username = reader.getString(); + } else if ("clientId".equals(fieldName)) { + clientId = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new AuthenticationRecord(authority, homeAccountId, username, tenantId, clientId); + }); + } catch (IOException e) { + throw LOGGER.logThrowableAsError(new RuntimeException(e)); + } + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/AuthenticationRequiredException.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/AuthenticationRequiredException.java new file mode 100644 index 000000000000..92f08a89fa39 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/AuthenticationRequiredException.java @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2; + +import com.azure.v2.core.credentials.TokenRequestContext; + +/** + *

        The Authentication Required Exception is thrown by {@link InteractiveBrowserCredential} + * to indicate to the user that automatic authentication is disabled and authentication + * needs to be initiated via {@link InteractiveBrowserCredential#authenticate()} or + * {@link InteractiveBrowserCredential#authenticate()} APIs respectively before fetching an access token.

        + * + * @see com.azure.identity + * @see InteractiveBrowserCredential + */ +public final class AuthenticationRequiredException extends CredentialUnavailableException { + + private final transient TokenRequestContext request; + + /** + * Initializes a new instance of the {@link AuthenticationRequiredException} class. + * + * @param message The exception message. + * @param request The details of the authentication request. + */ + public AuthenticationRequiredException(String message, TokenRequestContext request) { + super(message); + this.request = request; + } + + /** + * Initializes a new instance of the {@link AuthenticationRequiredException} class. + * + * @param message The exception message. + * @param request The details of the authentication request. + * @param cause The {@link Throwable} which caused the creation of this exception. + */ + public AuthenticationRequiredException(String message, TokenRequestContext request, Throwable cause) { + super(message, cause); + this.request = request; + } + + /** + * Get the details of the authentication request which resulted in the authentication failure. + * + * @return the token request context. + */ + public TokenRequestContext getTokenRequestContext() { + return request; + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/AzureAuthorityHosts.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/AzureAuthorityHosts.java new file mode 100644 index 000000000000..6e5a17023edc --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/AzureAuthorityHosts.java @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2; + +/** + *

        Defines fields exposing the well known authority hosts for the Azure Public Cloud and sovereign clouds.

        + * + *

        Users looking to target a specific cloud instance of Azure, can pass an instance of Azure Authority Hosts + * as a parameter to the {@link EntraIdCredentialBuilderBase#authorityHost(String)}. The authentication requests + * will be routed accordingly to the specified target authority host.

        + * + * @see EntraIdCredentialBuilderBase + */ +//TODO: @g2vinay, Move to Azure-Core-V2. +public final class AzureAuthorityHosts { + + private AzureAuthorityHosts() { + } + + /** + * The host of the Microsoft Entra authority for tenants in the Azure Public Cloud. + */ + public static final String AZURE_PUBLIC_CLOUD = "https://login.microsoftonline.com/"; + + /** + * The host of the Microsoft Entra authority for tenants in the Azure China Cloud. + */ + public static final String AZURE_CHINA = "https://login.chinacloudapi.cn/"; + + /** + * The host of the Microsoft Entra authority for tenants in the Azure German Cloud. + * + * @deprecated Microsoft Cloud Germany was closed on October 29th, 2021. + */ + @Deprecated + public static final String AZURE_GERMANY = "https://login.microsoftonline.de/"; + + /** + * The host of the Microsoft Entra authority for tenants in the Azure US Government Cloud. + */ + public static final String AZURE_GOVERNMENT = "https://login.microsoftonline.us/"; + + static String getDefaultScope(String authorityHost) { + switch (authorityHost) { + case AZURE_PUBLIC_CLOUD: + return "https://management.core.windows.net//.default"; + + case AZURE_CHINA: + return "https://management.core.chinacloudapi.cn//.default"; + + case AZURE_GERMANY: + return "https://management.core.cloudapi.de//.default"; + + case AZURE_GOVERNMENT: + return "https://management.core.usgovcloudapi.net//.default"; + + default: + return null; + } + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/AzurePipelinesCredential.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/AzurePipelinesCredential.java new file mode 100644 index 000000000000..7a17b6fb9ac1 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/AzurePipelinesCredential.java @@ -0,0 +1,112 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2; + +import com.azure.identity.v2.implementation.client.ConfidentialClient; +import com.azure.identity.v2.implementation.models.ConfidentialClientOptions; +import com.azure.identity.v2.implementation.models.OidcTokenResponse; +import com.azure.identity.v2.implementation.util.IdentityUtil; +import com.azure.identity.v2.implementation.util.LoggingUtil; +import com.azure.v2.core.credentials.TokenCredential; +import com.azure.v2.core.credentials.TokenRequestContext; +import io.clientcore.core.credentials.oauth.AccessToken; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpHeaders; +import io.clientcore.core.http.models.HttpMethod; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.serialization.json.JsonReader; + +import java.io.IOException; + +/** + * The {@link AzurePipelinesCredential} acquires a token using the Azure Pipelines service connection. + *

        + * To construct an instance of this credential, use the {@link AzurePipelinesCredentialBuilder}: + *

        + * // serviceConnectionId is retrieved from the portal.
        + * // systemAccessToken is retrieved from the pipeline environment as shown.
        + * // You may choose another name for this variable.
        + *
        + * String systemAccessToken = System.getenv("SYSTEM_ACCESSTOKEN");
        + * AzurePipelinesCredential credential = new AzurePipelinesCredentialBuilder().clientId(clientId)
        + *     .tenantId(tenantId)
        + *     .serviceConnectionId(serviceConnectionId)
        + *     .systemAccessToken(systemAccessToken)
        + *     .build();
        + * 
        + */ +public class AzurePipelinesCredential implements TokenCredential { + private static final ClientLogger LOGGER = new ClientLogger(AzurePipelinesCredential.class); + private final ConfidentialClient confidentialClient; + + /** + * Creates an instance of {@link AzurePipelinesCredential}. + * + * @param requestUrl the request url to get the client assertion token + * @param systemAccessToken the system access token + * @param confidentialClientOptions the options for configuring the confidential client + */ + AzurePipelinesCredential(String requestUrl, String systemAccessToken, + ConfidentialClientOptions confidentialClientOptions) { + + confidentialClientOptions.setClientAssertionFunction((httpPipeline) -> { + try { + HttpRequest request = new HttpRequest().setMethod(HttpMethod.POST).setUri(requestUrl); + HttpHeaders httpHeaders = new HttpHeaders(); + httpHeaders.add(HttpHeaderName.AUTHORIZATION, "Bearer " + systemAccessToken); + httpHeaders.add(HttpHeaderName.CONTENT_TYPE, "application/json"); + // Prevents the service from responding with a redirect HTTP status code (useful for automation). + httpHeaders.add(IdentityUtil.X_TFS_FED_AUTH_REDIRECT, "Suppress"); + try (Response response = httpPipeline.send(request)) { + String responseBody = response.getValue().toString(); + if (response.getStatusCode() != 200) { + String xVssHeader = response.getHeaders().getValue(IdentityUtil.X_VSS_E2EID); + String xMsEdgeRefHeader = response.getHeaders().getValue(IdentityUtil.X_MSEDGE_REF); + String message = "Failed to get the client assertion token " + responseBody + "."; + if (xVssHeader != null) { + message += " x-vss-e2eid: " + xVssHeader + "."; + } + if (xMsEdgeRefHeader != null) { + message += " x-msedge-ref: " + xMsEdgeRefHeader + "."; + } + message + += "For troubleshooting information see https://aka.ms/azsdk/java/identity/azurepipelinescredential/troubleshoot."; + throw LOGGER.logThrowableAsError(new CredentialAuthenticationException(message)); + } + try (JsonReader reader = JsonReader.fromString(responseBody)) { + return OidcTokenResponse.fromJson(reader).getOidcToken(); + } + } + } catch (IOException e) { + throw LOGGER.logThrowableAsError( + new CredentialAuthenticationException("Failed to get the client assertion token", e)); + } + }); + this.confidentialClient = new ConfidentialClient(confidentialClientOptions); + } + + @Override + public AccessToken getToken(TokenRequestContext request) { + try { + AccessToken token = confidentialClient.authenticateWithCache(request); + if (token != null) { + LoggingUtil.logTokenSuccess(LOGGER, request); + return token; + } + } catch (Exception ignored) { + } + + try { + AccessToken token = confidentialClient.authenticate(request); + LoggingUtil.logTokenSuccess(LOGGER, request); + return token; + } catch (Exception e) { + LoggingUtil.logTokenError(LOGGER, request, e); + throw LOGGER.logThrowableAsError(new RuntimeException(e)); + } + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/AzurePipelinesCredentialBuilder.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/AzurePipelinesCredentialBuilder.java new file mode 100644 index 000000000000..4af7392455e8 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/AzurePipelinesCredentialBuilder.java @@ -0,0 +1,138 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2; + +import com.azure.identity.v2.implementation.models.ClientOptions; +import com.azure.identity.v2.implementation.models.ConfidentialClientOptions; +import com.azure.identity.v2.implementation.util.ValidationUtil; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.pipeline.HttpInstrumentationOptions; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.utils.configuration.Configuration; + +import java.util.Arrays; + +/** + * The {@link AzurePipelinesCredentialBuilder} provides a fluent builder for {@link AzurePipelinesCredential}. + * + *
        + * // serviceConnectionId is retrieved from the portal.
        + * // systemAccessToken is retrieved from the pipeline environment as shown.
        + * // You may choose another name for this variable.
        + *
        + * String systemAccessToken = System.getenv("SYSTEM_ACCESSTOKEN");
        + * AzurePipelinesCredential credential = new AzurePipelinesCredentialBuilder().clientId(clientId)
        + *     .tenantId(tenantId)
        + *     .serviceConnectionId(serviceConnectionId)
        + *     .systemAccessToken(systemAccessToken)
        + *     .build();
        + * 
        + */ +public class AzurePipelinesCredentialBuilder extends EntraIdCredentialBuilderBase { + private static final ClientLogger LOGGER = new ClientLogger(AzurePipelinesCredentialBuilder.class); + private static final String OIDC_API_VERSION = "7.1"; + private String serviceConnectionId; + private String systemAccessToken; + + private final ConfidentialClientOptions confidentialClientOptions; + + /** + * Creates an instance of the {@link AzurePipelinesCredentialBuilder}. + */ + public AzurePipelinesCredentialBuilder() { + super(); + confidentialClientOptions = new ConfidentialClientOptions(); + } + + @Override + ClientOptions getClientOptions() { + return this.confidentialClientOptions; + } + + /** + * Sets the service connection id for the Azure Pipelines service connection. The service connection ID is + * retrieved from the Service Connection in the portal. + * + * @param serviceConnectionId The service connection ID, as found in the query string's resourceId key. + * @return the updated instance of the builder. + */ + public AzurePipelinesCredentialBuilder serviceConnectionId(String serviceConnectionId) { + this.serviceConnectionId = serviceConnectionId; + return this; + } + + /** + * Sets the System Access Token for the Azure Pipelines service connection. The system access token is + * retrieved from the pipeline variables by assigning it to an environment variable and reading it. + * See {@link AzurePipelinesCredential} for more information. + * + * @param systemAccessToken the system access token for the Azure Pipelines service connection. + * @return The updated instance of the builder. + */ + public AzurePipelinesCredentialBuilder systemAccessToken(String systemAccessToken) { + this.systemAccessToken = systemAccessToken; + return this; + } + + /** + * Configures the persistent shared token cache options and enables the persistent token cache which is disabled + * by default. If configured, the credential will store tokens in a cache persisted to the machine, protected to + * the current user, which can be shared by other credentials and processes. + * + * @param tokenCachePersistenceOptions the token cache configuration options + * @return An updated instance of this builder with the token cache options configured. + */ + public AzurePipelinesCredentialBuilder + tokenCachePersistenceOptions(TokenCachePersistenceOptions tokenCachePersistenceOptions) { + this.confidentialClientOptions.setTokenCacheOptions(tokenCachePersistenceOptions); + return this; + } + + /** + * Builds an instance of the {@link AzurePipelinesCredential} with the current configurations. Requires setting + * the following parameters: + *
          + *
        • Client ID via {@link #clientId(String)}
        • + *
        • Tenant ID via {@link #tenantId(String)}
        • + *
        • Service Connection ID via {@link #serviceConnectionId(String)}
        • + *
        • System Access Token via {@link #systemAccessToken(String)}
        • + *
        + * Requires the {@code SYSTEM_OIDCREQUESTURI} environment variable to be set. + * + * @throws IllegalArgumentException Thrown when required parameters are set or the environment is not correctly + * configured. + * @return an instance of the {@link AzurePipelinesCredential}. + */ + public AzurePipelinesCredential build() { + Configuration configuration = confidentialClientOptions.getConfiguration(); + if (configuration == null) { + configuration = Configuration.getGlobalConfiguration(); + } + + String oidcEndpoint = configuration.get("SYSTEM_OIDCREQUESTURI"); + + ValidationUtil.validate(getClass().getSimpleName(), LOGGER, + Arrays.asList("clientId", "tenantId", "serviceConnectionId", "systemAccessToken", "oidcEndpoint"), + Arrays.asList(confidentialClientOptions.getClientId(), confidentialClientOptions.getTenantId(), + serviceConnectionId, this.systemAccessToken, oidcEndpoint)); + + String requestUrl = String.format("%s?api-version=%s&serviceConnectionId=%s", oidcEndpoint, OIDC_API_VERSION, + serviceConnectionId); + + // We need to make a best effort to log these headers. + // If the user gives us options, we'll sneak the headers in, or make an options with them. + // If the user gave us a pipeline none of this matters as we can't change a user created pipeline. + if (confidentialClientOptions.getHttpPipelineOptions().getHttpPipeline() != null) { + HttpInstrumentationOptions options + = confidentialClientOptions.getHttpPipelineOptions().getHttpInstrumentationOptions(); + if (options == null) { + options = new HttpInstrumentationOptions(); + } + options.addAllowedHeaderName(HttpHeaderName.fromString("x-vss-e2eid")); + options.addAllowedHeaderName(HttpHeaderName.fromString("x-msedge-ref")); + confidentialClientOptions.getHttpPipelineOptions().setHttpInstrumentationOptions(options); + } + return new AzurePipelinesCredential(requestUrl, systemAccessToken, confidentialClientOptions.clone()); + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/BrowserCustomizationOptions.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/BrowserCustomizationOptions.java new file mode 100644 index 000000000000..2a472effc646 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/BrowserCustomizationOptions.java @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2; + +/** + * Represent Options to customize browser view. + */ +public class BrowserCustomizationOptions { + private String successMessage; + private String errorMessage; + + /** + * Creates an instance of BrowserCustomizationOptions. + */ + public BrowserCustomizationOptions() { + } + + /** + * Configures the property to set the success message which the browser will show to the user upon successful + * authentication. + * + * @param successMessage the message to display when user finishes authenticating. + * @return the updated options. + */ + public BrowserCustomizationOptions setSuccessMessage(String successMessage) { + this.successMessage = successMessage; + return this; + } + + /** + * Configure the property to set error message which the browser will show to the user upon failed to acquire an + * access token. + * You can use a string format e.g. + * "An error has occurred: {0} details: {1}.", the details will be populated by the library. + * + * @param errorMessage the message to display when user finishes authenticating, but an error occurred. + * @return the updated options. + */ + public BrowserCustomizationOptions setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + return this; + } + + /** + * Get the configured message which the browser will show to the user when the user + * finishes authenticating successfully. + * + * @return the string message. + */ + public String getSuccessMessage() { + return this.successMessage; + } + + /** + * Get the configured message which the browser will show to the user when the user + * finishes authenticating, but an error occurred. + * + * @return the string message. + */ + public String getErrorMessage() { + return this.errorMessage; + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/ClientSecretCredential.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/ClientSecretCredential.java new file mode 100644 index 000000000000..c55aa8dfc78d --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/ClientSecretCredential.java @@ -0,0 +1,95 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2; + +import com.azure.identity.v2.implementation.client.ConfidentialClient; +import com.azure.identity.v2.implementation.models.ConfidentialClientOptions; +import com.azure.identity.v2.implementation.util.LoggingUtil; +import com.azure.v2.core.credentials.TokenCredential; +import com.azure.v2.core.credentials.TokenRequestContext; +import io.clientcore.core.credentials.oauth.AccessToken; +import io.clientcore.core.instrumentation.logging.ClientLogger; + +import java.util.Objects; + +/** + *

        The ClientSecretCredential acquires a token via service principal authentication. It is a type of authentication + * in Azure that enables a non-interactive login to + * Microsoft Entra ID, allowing an + * application or service to authenticate itself with Azure resources. + * A Service Principal is essentially an identity created for an application in Microsoft Entra ID that can be used to + * authenticate with Azure resources. It's like a "user identity" for the application or service, and it provides + * a way for the application to authenticate itself with Azure resources without needing to use a user's credentials. + * Microsoft Entra ID allows users to + * register service principals which can be used as an identity for authentication. + * A client secret associated with the registered service principal is used as the password when authenticating the + * service principal. + * The ClientSecretCredential acquires an access token with a client secret for a service principal/registered + * Microsoft Entra application. The tenantId, clientId and clientSecret of the service principal are required for this credential + * to acquire an access token. It can be used both in Azure hosted and local development environments for + * authentication. For more information refer to the + * conceptual knowledge and configuration + * details.

        + * + *

        As a pre-requisite, a service principal is required to use this authentication mechanism. If you don't have + * a service principal, refer to + * create a service principal with Azure CLI. + *

        + * + *

        Sample: Construct a simple ClientSecretCredential

        + * + *

        The following code sample demonstrates the creation of a {@link com.azure.identity.v2.ClientSecretCredential}, + * using the {@link ClientSecretCredentialBuilder} to configure it. The {@code tenantId}, + * {@code clientId} and {@code clientSecret} parameters are required to create + * {@link com.azure.identity.v2.ClientSecretCredential} .Once this credential is created, it may be passed into the + * builder of many of the Azure SDK for Java client builders as the 'credential' parameter.

        + * + *
        + * TokenCredential clientSecretCredential = new ClientSecretCredentialBuilder().tenantId(tenantId)
        + *     .clientId(clientId)
        + *     .clientSecret(clientSecret)
        + *     .build();
        + * 
        + * + * @see com.azure.identity.v2 + * @see ClientSecretCredentialBuilder + */ +public class ClientSecretCredential implements TokenCredential { + private static final ClientLogger LOGGER = new ClientLogger(ClientSecretCredential.class); + + private final ConfidentialClient confidentialClient; + + /** + * Creates a ClientSecretCredential with the given identity client options. + * + * @param confidentialClientOptions the options for configuring the confidential client + */ + ClientSecretCredential(ConfidentialClientOptions confidentialClientOptions) { + Objects.requireNonNull(confidentialClientOptions, "'confidentialClientOptions' cannot be null."); + Objects.requireNonNull(confidentialClientOptions.getClientSecret(), "'clientSecret' cannot be null."); + + confidentialClient = new ConfidentialClient(confidentialClientOptions); + } + + @Override + public AccessToken getToken(TokenRequestContext request) { + try { + AccessToken token = confidentialClient.authenticateWithCache(request); + if (token != null) { + LoggingUtil.logTokenSuccess(LOGGER, request); + return token; + } + } catch (Exception e) { + } + + try { + AccessToken token = confidentialClient.authenticate(request); + LoggingUtil.logTokenSuccess(LOGGER, request); + return token; + } catch (Exception e) { + LoggingUtil.logTokenError(LOGGER, request, e); + throw LOGGER.logThrowableAsError(new CredentialAuthenticationException(e.getMessage(), e)); + } + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/ClientSecretCredentialBuilder.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/ClientSecretCredentialBuilder.java new file mode 100644 index 000000000000..69463b5ffdd6 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/ClientSecretCredentialBuilder.java @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2; + +import com.azure.identity.v2.implementation.models.ClientOptions; +import com.azure.identity.v2.implementation.models.ConfidentialClientOptions; +import com.azure.identity.v2.implementation.util.ValidationUtil; +import io.clientcore.core.instrumentation.logging.ClientLogger; + +/** + * Fluent credential builder for instantiating a {@link ClientSecretCredential}. + * + *

        The {@link ClientSecretCredential} acquires a token via service principal authentication. It is a type of + * authentication in Azure that enables a non-interactive login to + * Microsoft Entra ID, allowing an + * application or service to authenticate itself with Azure resources. + * A Service Principal is essentially an identity created for an application in Microsoft Entra ID that can be used to + * authenticate with Azure resources. It's like a "user identity" for the application or service, and it provides + * a way for the application to authenticate itself with Azure resources without needing to use a user's credentials. + * Microsoft Entra ID allows users to + * register service principals which can be used as an identity for authentication. + * A client secret associated with the registered service principal is used as the password when authenticating the + * service principal. + * The {@link ClientSecretCredential} acquires an access token with a client secret for a service principal/registered + * Microsoft Entra application. The tenantId, clientId and clientSecret of the service principal are required for this credential + * to acquire an access token. It can be used both in Azure hosted and local development environments for + * authentication. For more information refer to the + * conceptual knowledge and configuration + * details.

        + * + *

        Sample: Construct a simple ClientSecretCredential

        + * + *

        The following code sample demonstrates the creation of a {@link ClientSecretCredential}, + * using the {@link com.azure.identity.v2.ClientSecretCredentialBuilder} to configure it. The {@code tenantId}, + * {@code clientId} and {@code clientSecret} parameters are required to create + * {@link com.azure.identity.v2.ClientSecretCredential} .Once this credential is created, it may be passed into the + * builder of many of the Azure SDK for Java client builders as the 'credential' parameter.

        + * + *
        + * TokenCredential clientSecretCredential = new ClientSecretCredentialBuilder().tenantId(tenantId)
        + *     .clientId(clientId)
        + *     .clientSecret(clientSecret)
        + *     .build();
        + * 
        + * + * @see ClientSecretCredential + */ +public class ClientSecretCredentialBuilder extends EntraIdCredentialBuilderBase { + private static final ClientLogger LOGGER = new ClientLogger(ClientSecretCredentialBuilder.class); + private final ConfidentialClientOptions confidentialClientOptions; + + /** + * Constructs an instance of ClientSecretCredentialBuilder. + */ + public ClientSecretCredentialBuilder() { + super(); + confidentialClientOptions = new ConfidentialClientOptions(); + } + + @Override + ClientOptions getClientOptions() { + return confidentialClientOptions; + } + + /** + * Sets the client secret for the authentication. + * @param clientSecret the secret value of the Microsoft Entra application. + * @return An updated instance of this builder. + */ + public ClientSecretCredentialBuilder clientSecret(String clientSecret) { + confidentialClientOptions.setClientSecret(clientSecret); + return this; + } + + /** + * Configures the persistent shared token cache options and enables the persistent token cache which is disabled + * by default. If configured, the credential will store tokens in a cache persisted to the machine, protected to + * the current user, which can be shared by other credentials and processes. + * + * @param tokenCachePersistenceOptions the token cache configuration options + * @return An updated instance of this builder with the token cache options configured. + */ + public ClientSecretCredentialBuilder + tokenCachePersistenceOptions(TokenCachePersistenceOptions tokenCachePersistenceOptions) { + getClientOptions().setTokenCacheOptions(tokenCachePersistenceOptions); + return this; + } + + /** + * Creates a new {@link ClientSecretCredential} with the current configurations. + * + * @return a {@link ClientSecretCredentialBuilder} with the current configurations. + */ + public ClientSecretCredential build() { + ValidationUtil.validate(LOGGER, "clientId", getClientOptions().getClientId(), "tenantId", + getClientOptions().getTenantId(), "clientSecret", confidentialClientOptions.getClientSecret()); + + return new ClientSecretCredential(confidentialClientOptions); + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/CredentialAuthenticationException.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/CredentialAuthenticationException.java new file mode 100644 index 000000000000..0d758dfd8ce3 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/CredentialAuthenticationException.java @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2; + +import com.azure.v2.core.credentials.TokenCredential; +import io.clientcore.core.credentials.oauth.AccessToken; + +/** + * The exception thrown when a {@link TokenCredential} attempted to authenticate and retrieve {@link AccessToken}, + * but failed to do so. + * + *

        + * This exception breaks the chained authentication flow of chained credentials. + *

        + * + * @see com.azure.identity.v2 + */ +public class CredentialAuthenticationException extends RuntimeException { + + /** + * Initializes a new instance of the {@link CredentialAuthenticationException} class. + * + * @param message The exception message. + */ + public CredentialAuthenticationException(String message) { + super(message); + } + + /** + * Initializes a new instance of the {@link CredentialAuthenticationException} class. + * + * @param message The exception message. + * @param cause The {@link Throwable} which caused the creation of this exception. + */ + public CredentialAuthenticationException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/CredentialBuilderBase.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/CredentialBuilderBase.java new file mode 100644 index 000000000000..d4494cd51b61 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/CredentialBuilderBase.java @@ -0,0 +1,68 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2; + +import com.azure.identity.v2.implementation.models.ClientOptions; +import com.azure.identity.v2.implementation.models.HttpPipelineOptions; +import com.azure.identity.v2.implementation.util.ValidationUtil; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.utils.configuration.Configuration; + +/** + * The base class for all the credential builders. + * @param the type of the credential builder + */ +public abstract class CredentialBuilderBase> { + private static final ClientLogger LOGGER = new ClientLogger(CredentialBuilderBase.class); + + CredentialBuilderBase() { + } + + /** + * Sets the configuration store that is used during construction of the credential. + * + * The default configuration store is a clone of the {@link Configuration#getGlobalConfiguration() global + * configuration store}. + * + * @param configuration The configuration store used to load Env variables and/or properties from. + * + * @return An updated instance of this builder with the configuration store set as specified. + */ + @SuppressWarnings("unchecked") + public T configuration(Configuration configuration) { + getClientOptions().setConfigurationStore(configuration); + return (T) this; + } + + /** + * Sets the client ID of the application. + * + * @param clientId the client ID of the application. + * @return An updated instance of this builder with the client id set as specified. + */ + @SuppressWarnings("unchecked") + public T clientId(String clientId) { + getClientOptions().setClientId(clientId); + return (T) this; + } + + /** + * Sets the tenant ID of the application. + * + * @param tenantId the tenant ID of the application. + * @return An updated instance of this builder with the tenant id set as specified. + */ + @SuppressWarnings("unchecked") + public T tenantId(String tenantId) { + ValidationUtil.validateTenantIdCharacterRange(tenantId, LOGGER); + getClientOptions().setTenantId(tenantId); + return (T) this; + } + + abstract ClientOptions getClientOptions(); + + HttpPipelineOptions getHttpPipelineOptions() { + return getClientOptions().getHttpPipelineOptions(); + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/CredentialUnavailableException.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/CredentialUnavailableException.java new file mode 100644 index 000000000000..26dbfef6cde1 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/CredentialUnavailableException.java @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2; + +import com.azure.v2.core.credentials.TokenCredential; +import io.clientcore.core.credentials.oauth.AccessToken; + +/** + * The exception thrown when a {@link TokenCredential} did not attempt to authenticate and retrieve {@link AccessToken}, + * as its prerequisite information or state was not available. + * + * @see com.azure.identity.v2 + */ +public class CredentialUnavailableException extends RuntimeException { + + /** + * Initializes a new instance of the {@link CredentialUnavailableException} class. + * + * @param message The exception message. + */ + public CredentialUnavailableException(String message) { + super(message); + } + + /** + * Initializes a new instance of the {@link CredentialUnavailableException} class. + * + * @param message The exception message. + * @param cause The {@link Throwable} which caused the creation of this exception. + */ + public CredentialUnavailableException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/EntraIdCredentialBuilderBase.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/EntraIdCredentialBuilderBase.java new file mode 100644 index 000000000000..2f52705399a4 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/EntraIdCredentialBuilderBase.java @@ -0,0 +1,164 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2; + +import com.azure.identity.v2.implementation.util.IdentityUtil; +import com.azure.identity.v2.implementation.util.ValidationUtil; +import io.clientcore.core.http.client.HttpClient; +import io.clientcore.core.http.pipeline.HttpPipeline; +import io.clientcore.core.http.pipeline.HttpPipelinePolicy; +import io.clientcore.core.http.pipeline.HttpInstrumentationOptions; +import io.clientcore.core.http.pipeline.HttpRedirectOptions; +import io.clientcore.core.http.pipeline.HttpRetryOptions; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.traits.HttpTrait; + +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.ExecutorService; + +/** + *

        The base class for credential builders that allow specifying a client ID, tenant ID, authority host, and + * additionally allowed tenants for Microsoft Entra ID.

        + * + * @param the type of the credential builder + */ +public abstract class EntraIdCredentialBuilderBase> + extends CredentialBuilderBase implements HttpTrait { + private static final ClientLogger LOGGER = new ClientLogger(EntraIdCredentialBuilderBase.class); + + /** + * Constructs an instance of AadCredentialBuilderBase. + */ + public EntraIdCredentialBuilderBase() { + super(); + } + + /** + * Specifies the Microsoft Entra endpoint to acquire tokens. + * @param authorityHost the Microsoft Entra endpoint + * @return An updated instance of this builder with the authority host set as specified. + */ + @SuppressWarnings("unchecked") + public T authorityHost(String authorityHost) { + ValidationUtil.validateAuthHost(authorityHost, LOGGER); + getClientOptions().setAuthorityHost(authorityHost); + return (T) this; + } + + /** + * Specifies the ExecutorService to be used to execute the authentication requests. + * Developer is responsible for maintaining the lifecycle of the ExecutorService. + * + *

        The executor service and can be safely shutdown if the TokenCredential is no longer being used by the + * Azure SDK clients and should be shutdown before the application exits.

        + * + * @param executorService the executor service to use for executing authentication requests. + * @return An updated instance of this builder with the executor service set as specified. + */ + @SuppressWarnings("unchecked") + public T executorService(ExecutorService executorService) { + getClientOptions().setExecutorService(executorService); + return (T) this; + } + + /** + * Disables the setting which determines whether or not instance discovery is performed when attempting to + * authenticate. This will completely disable both instance discovery and authority validation. + * This functionality is intended for use in scenarios where the metadata endpoint cannot be reached, such as in + * private clouds or Azure Stack. The process of instance discovery entails retrieving authority metadata from + * https://login.microsoft.com/ to validate the authority. By utilizing this API, the validation of the authority + * is disabled. As a result, it is crucial to ensure that the configured authority host is valid and trustworthy. + * + * @return An updated instance of this builder with instance discovery disabled. + */ + @SuppressWarnings("unchecked") + public T disableInstanceDiscovery() { + getClientOptions().disableInstanceDiscovery(); + return (T) 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.

        + * + * @param pipeline {@link HttpPipeline} to use for sending service requests and receiving responses. + * @return An updated instance of this builder with the http pipeline set as specified. + */ + @SuppressWarnings("unchecked") + @Override + public T httpPipeline(HttpPipeline pipeline) { + getHttpPipelineOptions().setHttpPipeline(pipeline); + return (T) this; + } + + @SuppressWarnings("unchecked") + @Override + public T addHttpPipelinePolicy(HttpPipelinePolicy pipelinePolicy) { + getHttpPipelineOptions().addHttpPipelinePolicy(pipelinePolicy); + return (T) this; + } + + @SuppressWarnings("unchecked") + @Override + public T httpRetryOptions(HttpRetryOptions retryOptions) { + getHttpPipelineOptions().setHttpRetryOptions(retryOptions); + return (T) this; + } + + @SuppressWarnings("unchecked") + @Override + public T httpInstrumentationOptions(HttpInstrumentationOptions instrumentationOptions) { + getHttpPipelineOptions().setHttpInstrumentationOptions(instrumentationOptions); + return (T) this; + } + + @SuppressWarnings("unchecked") + @Override + public T httpRedirectOptions(HttpRedirectOptions redirectOptions) { + getHttpPipelineOptions().setHttpRedirectOptions(redirectOptions); + return (T) this; + } + + @SuppressWarnings("unchecked") + @Override + public T httpClient(HttpClient client) { + getHttpPipelineOptions().setHttpClient(client); + return (T) this; + } + + /** + * For multi-tenant applications, specifies additional tenants for which the credential may acquire tokens. + * Add the wildcard value "*" to allow the credential to acquire tokens for any tenant on which the application is installed. + * + * @param additionallyAllowedTenants the additionally allowed tenants. + * @return An updated instance of this builder with the additional tenants configured. + */ + @SuppressWarnings("unchecked") + public T additionallyAllowedTenants(String... additionallyAllowedTenants) { + getClientOptions().setAdditionallyAllowedTenants( + IdentityUtil.resolveAdditionalTenants(Arrays.asList(additionallyAllowedTenants))); + return (T) this; + } + + /** + * For multi-tenant applications, specifies additional tenants for which the credential may acquire tokens. + * Add the wildcard value "*" to allow the credential to acquire tokens for any tenant on which the application is installed. + * + * @param additionallyAllowedTenants the additionally allowed tenants. + * @return An updated instance of this builder with the additional tenants configured. + */ + @SuppressWarnings("unchecked") + public T additionallyAllowedTenants(List additionallyAllowedTenants) { + getClientOptions() + .setAdditionallyAllowedTenants(IdentityUtil.resolveAdditionalTenants(additionallyAllowedTenants)); + return (T) this; + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/InteractiveBrowserCredential.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/InteractiveBrowserCredential.java new file mode 100644 index 000000000000..c2e3570bd8b6 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/InteractiveBrowserCredential.java @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2; + +import com.azure.identity.v2.implementation.client.PublicClient; +import com.azure.identity.v2.implementation.models.MsalAuthenticationAccount; +import com.azure.identity.v2.implementation.models.MsalToken; +import com.azure.identity.v2.implementation.models.PublicClientOptions; +import com.azure.identity.v2.implementation.util.LoggingUtil; +import com.azure.v2.core.credentials.TokenCredential; +import com.azure.v2.core.credentials.TokenRequestContext; +import io.clientcore.core.credentials.oauth.AccessToken; +import io.clientcore.core.instrumentation.logging.ClientLogger; + +import java.util.concurrent.atomic.AtomicReference; + +/** + *

        Interactive browser authentication is a type of authentication flow offered by + * Microsoft Entra ID + * that enables users to sign in to applications and services using a web browser. + * With interactive browser authentication, the user is directed to a sign-in webpage and is prompted to enter their + * credentials. After the user successfully authenticates, Microsoft Entra ID issues a + * security token that the application can use to authorize the user's access to its resources. For more information refer to the + * interactive browser authentication + * documentation.

        + + *

        Required configuration:

        + * + *

        To use InteractiveBrowserCredential, you need to register an application in Microsoft Entra ID with + * permissions to log in on behalf of a user. Follow the steps below to configure your registered application.

        + * + *
          + *
        1. Go to Microsoft Entra ID in Azure portal and find your app registration.
        2. + *
        3. Navigate to the Authentication section.
        4. + *
        5. Under Suggested Redirected URIs, check the URI that ends with /common/oauth2/nativeclient.
        6. + *
        7. Under Authentication->Advanced settings, enable "Allow public client flows."
        8. + *
        + * + *

        These steps will let the application authenticate, but it still won't have permission to log you into + * Active Directory, or access resources on your behalf. To address this issue, navigate to API Permissions, and enable + * Microsoft Graph and the resources you want to access, such as Azure Service Management, Key Vault, and so on. + * You also need to be the admin of your tenant to grant consent to your application when you log in for the first time. + * In {@link InteractiveBrowserCredentialBuilder#redirectUrl(String)}, a redirect URL can be specified. It configures + * the Redirect URL where STS will callback the application with the security code. It is required if a custom + * client id is specified via {@link InteractiveBrowserCredentialBuilder#clientId(String)} and must match the + * redirect URL specified during the application registration. You can add the redirect URL to the Redirect URIs + * subsection under the Authentication section of your registered Microsoft Entra application.

        + * + *

        Sample: Construct InteractiveBrowserCredential

        + * + *

        The following code sample demonstrates the creation of a {@link com.azure.identity.v2.InteractiveBrowserCredential}, + * using the {@link com.azure.identity.v2.InteractiveBrowserCredentialBuilder} to configure it. By default, the credential + * targets a localhost redirect URL, to override that behaviour a + * {@link InteractiveBrowserCredentialBuilder#redirectUrl(String)} can be optionally specified. Once this credential is + * created, it may be passed into the builder of many of the Azure SDK for Java client builders as the 'credential' + * parameter.

        + * + * @see com.azure.identity + * @see InteractiveBrowserCredentialBuilder + */ +public class InteractiveBrowserCredential implements TokenCredential { + private static final ClientLogger LOGGER = new ClientLogger(InteractiveBrowserCredential.class); + + private final Integer port; + private final PublicClient publicClient; + private final AtomicReference cachedToken; + private final boolean automaticAuthentication; + private final String authorityHost; + private final String redirectUrl; + private final String loginHint; + private boolean isCaeEnabledRequestCached; + private boolean isCaeDisabledRequestCached; + private boolean isCachePopulated; + private final PublicClientOptions publicClientOptions; + + /** + * Creates a InteractiveBrowserCredential with the given identity client options and a listening port, for which + * {@code http://localhost:{port}} must be registered as a valid reply URL on the application. + * + * @param port the port on which the credential will listen for the browser authentication result + * @param redirectUrl the redirect URL to listen on and receive security code. + * @param automaticAuthentication indicates whether automatic authentication should be attempted or not. + * @param publicClientOptions the options for configuring the public client + */ + InteractiveBrowserCredential(Integer port, String redirectUrl, boolean automaticAuthentication, String loginHint, + PublicClientOptions publicClientOptions) { + this.port = port; + this.redirectUrl = redirectUrl; + this.publicClient = new PublicClient(publicClientOptions); + this.publicClientOptions = publicClientOptions; + + cachedToken = new AtomicReference<>(); + this.authorityHost = publicClientOptions.getAuthorityHost(); + this.automaticAuthentication = automaticAuthentication; + this.loginHint = loginHint; + if (publicClientOptions.getAuthenticationRecord() != null) { + cachedToken.set(new MsalAuthenticationAccount(publicClientOptions.getAuthenticationRecord())); + } + } + + @Override + public AccessToken getToken(TokenRequestContext request) { + isCachePopulated = isCachePopulated(request); + if (isCachePopulated) { + try { + MsalToken token = publicClient.authenticateWithPublicClientCache(request, cachedToken.get()); + if (token != null) { + LoggingUtil.logTokenSuccess(LOGGER, request); + return token; + } + } catch (Exception e) { + } + } + try { + if (!automaticAuthentication) { + throw LOGGER.logThrowableAsError(new AuthenticationRequiredException("Interactive " + + "authentication is needed to acquire token. Call Authenticate to initiate the device " + + "code authentication.", request)); + } + MsalToken accessToken + = publicClient.authenticateWithBrowserInteraction(request, port, redirectUrl, loginHint); + updateCache(accessToken); + if (request.isCaeEnabled()) { + isCaeEnabledRequestCached = true; + } else { + isCaeDisabledRequestCached = true; + } + LoggingUtil.logTokenSuccess(LOGGER, request); + return accessToken; + } catch (Exception e) { + LoggingUtil.logTokenError(LOGGER, request, e); + throw LOGGER.logThrowableAsError(new RuntimeException(e)); + } + } + + /** + * Interactively authenticates a user via the default browser. This method will always generate a challenge to the + * user. + * + * @param request The details of the authentication request. + * + * @return The {@link AuthenticationRecord} which can be used to silently authenticate the account + * on future execution if persistent caching was configured via + * {@link InteractiveBrowserCredentialBuilder#tokenCachePersistenceOptions(TokenCachePersistenceOptions)} + * when credential was instantiated. + */ + public AuthenticationRecord authenticate(TokenRequestContext request) { + MsalToken msalToken = publicClient.authenticateWithBrowserInteraction(request, port, redirectUrl, loginHint); + this.updateCache(msalToken); + return cachedToken.get().getAuthenticationRecord(); + } + + /** + * Interactively authenticates a user via the default browser. This method will always generate a challenge to the + * user. + * + * @return The {@link AuthenticationRecord} which can be used to silently authenticate the account + * on future execution if persistent caching was enabled via + * {@link InteractiveBrowserCredentialBuilder#tokenCachePersistenceOptions(TokenCachePersistenceOptions)} + * when credential was instantiated. + */ + public AuthenticationRecord authenticate() { + String defaultScope = AzureAuthorityHosts.getDefaultScope(authorityHost); + if (defaultScope == null) { + LoggingUtil.logCredentialUnavailableException(LOGGER, new CredentialUnavailableException( + "Authenticating in this " + "environment requires specifying a TokenRequestContext.")); + } + return authenticate(new TokenRequestContext().addScopes(defaultScope)); + } + + private AccessToken updateCache(MsalToken msalToken) { + cachedToken.set(new MsalAuthenticationAccount(new AuthenticationRecord(msalToken.getAuthenticationResult(), + publicClientOptions.getTenantId(), publicClientOptions.getClientId()), + msalToken.getAccount().getTenantProfiles())); + return msalToken; + } + + private boolean isCachePopulated(TokenRequestContext request) { + return (cachedToken.get() != null) + && ((request.isCaeEnabled() && isCaeEnabledRequestCached) + || (!request.isCaeEnabled() && isCaeDisabledRequestCached)); + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/InteractiveBrowserCredentialBuilder.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/InteractiveBrowserCredentialBuilder.java new file mode 100644 index 000000000000..71ee812086e1 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/InteractiveBrowserCredentialBuilder.java @@ -0,0 +1,224 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2; + +import com.azure.identity.v2.implementation.models.ClientOptions; +import com.azure.identity.v2.implementation.models.PublicClientOptions; +import com.azure.identity.v2.implementation.util.IdentityConstants; +import com.azure.identity.v2.implementation.util.IdentityUtil; +import com.azure.identity.v2.implementation.util.ValidationUtil; +import com.azure.v2.core.credentials.TokenRequestContext; +import io.clientcore.core.instrumentation.logging.ClientLogger; + +import java.util.Arrays; +import java.util.List; + +/** + * Fluent credential builder for instantiating a {@link InteractiveBrowserCredential}. + * + *

        Interactive browser authentication is a type of authentication flow offered by + * Microsoft Entra ID + * that enables users to sign in to applications and services using a web browser. This authentication method is + * commonly used for web applications, where users enter their credentials directly into a web page. + * With interactive browser authentication, the user navigates to a web application and is prompted to enter their + * username and password credentials. The application then redirects the user to the Microsoft Entra ID sign-in page, where + * they are prompted to enter their credentials again. After the user successfully authenticates, Microsoft Entra ID issues a + * security token that the application can use to authorize the user's access to its resources. + * The {@link InteractiveBrowserCredential} interactively authenticates a user and acquires a token with the default + * system browser and offers a smooth authentication experience by letting a user use their own credentials to + * authenticate the application. When authenticated, the oauth2 flow notifies the credential of the authentication + * code through the reply URL. For more information refer to the + * conceptual knowledge and + * configuration details.

        + * + *

        Sample: Construct InteractiveBrowserCredential

        + * + *

        The following code sample demonstrates the creation of a {@link InteractiveBrowserCredential}, + * using the {@link InteractiveBrowserCredentialBuilder} to configure it. By default, the credential + * targets a localhost redirect URL, to override that behaviour a + * {@link InteractiveBrowserCredentialBuilder#redirectUrl(String)} can be optionally specified. Once this credential is + * created, it may be passed into the builder of many of the Azure SDK for Java client builders as the 'credential' + * parameter.

        + + * @see InteractiveBrowserCredential + */ +public class InteractiveBrowserCredentialBuilder + extends EntraIdCredentialBuilderBase { + private static final ClientLogger LOGGER = new ClientLogger(InteractiveBrowserCredentialBuilder.class); + private Integer port; + private boolean automaticAuthentication = true; + private String redirectUrl; + private String loginHint; + + private PublicClientOptions publicClientOptions; + + /** + * Constructs an instance of InteractiveBrowserCredentialBuilder. + */ + public InteractiveBrowserCredentialBuilder() { + super(); + publicClientOptions = new PublicClientOptions(); + } + + /** + * Sets the client ID of the Microsoft Entra application that users will sign in to. It is recommended + * that developers register their applications and assign appropriate roles. For more information, + * visit this doc for app registration. + * If not specified, users will authenticate to an Azure development application, which is not recommended + * for production scenarios. + * @param clientId the client ID of the application. + * @return An updated instance of this builder with the client id configured. + */ + @Override + public InteractiveBrowserCredentialBuilder clientId(String clientId) { + return super.clientId(clientId); + } + + /** + * Sets the port for the local HTTP server, for which {@code http://localhost:{port}} must be + * registered as a valid reply URL on the application. + * + * @deprecated Configure the redirect URL as {@code http://localhost:{port}} via + * {@link InteractiveBrowserCredentialBuilder#redirectUrl(String)} instead. + * + * @param port the port on which the credential will listen for the browser authentication result + * @return An updated instance of this builder with the port configured. + */ + @Deprecated + public InteractiveBrowserCredentialBuilder port(int port) { + this.port = port; + return this; + } + + /** + * Sets the {@link AuthenticationRecord} captured from a previous authentication. + * + * @param authenticationRecord The Authentication record to be configured. + * + * @return An updated instance of this builder with the configured authentication record. + */ + public InteractiveBrowserCredentialBuilder authenticationRecord(AuthenticationRecord authenticationRecord) { + this.publicClientOptions.setAuthenticationRecord(authenticationRecord); + return this; + } + + /** + * Configures the persistent shared token cache options and enables the persistent token cache which is disabled + * by default. If configured, the credential will store tokens in a cache persisted to the machine, protected to + * the current user, which can be shared by other credentials and processes. + * + * @param tokenCachePersistenceOptions the token cache configuration options + * @return An updated instance of this builder with the token cache options configured. + */ + public InteractiveBrowserCredentialBuilder + tokenCachePersistenceOptions(TokenCachePersistenceOptions tokenCachePersistenceOptions) { + this.publicClientOptions.setTokenCacheOptions(tokenCachePersistenceOptions); + return this; + } + + /** + * Sets the Redirect URL where STS will callback the application with the security code. It is required if a custom + * client id is specified via {@link InteractiveBrowserCredentialBuilder#clientId(String)} and must match the + * redirect URL specified during the application registration. + * + * @param redirectUrl the redirect URL to listen on and receive security code. + * + * @return An updated instance of this builder with the configured redirect URL. + */ + public InteractiveBrowserCredentialBuilder redirectUrl(String redirectUrl) { + this.redirectUrl = redirectUrl; + return this; + } + + /** + * Disables the automatic authentication and prevents the {@link InteractiveBrowserCredential} from automatically + * prompting the user. If automatic authentication is disabled a {@link AuthenticationRequiredException} + * will be thrown from {@link InteractiveBrowserCredential#getToken(TokenRequestContext)} in the case that + * user interaction is necessary. The application is responsible for handling this exception, and + * calling {@link InteractiveBrowserCredential#authenticate()} or + * {@link InteractiveBrowserCredential#authenticate(TokenRequestContext)} to authenticate the user interactively. + * + * @return An updated instance of this builder with automatic authentication disabled. + */ + public InteractiveBrowserCredentialBuilder disableAutomaticAuthentication() { + this.automaticAuthentication = false; + return this; + } + + /** + * Sets the username suggestion to pre-fill the login page's username/email address field. A user may still log in + * with a different username. + * + * @param loginHint the username suggestion to pre-fill the login page's username/email address field. + * + * @return An updated instance of this builder with login hint configured. + */ + public InteractiveBrowserCredentialBuilder loginHint(String loginHint) { + this.loginHint = loginHint; + return this; + } + + /** + * For multi-tenant applications, specifies additional tenants for which the credential may acquire tokens. + * Add the wildcard value "*" to allow the credential to acquire tokens for any tenant on which the application is installed. + * If no value is specified for TenantId this option will have no effect, and the credential will + * acquire tokens for any requested tenant. + * + * @param additionallyAllowedTenants the additionally allowed tenants. + * @return An updated instance of this builder with the additional tenants configured. + */ + @Override + public InteractiveBrowserCredentialBuilder additionallyAllowedTenants(String... additionallyAllowedTenants) { + publicClientOptions.setAdditionallyAllowedTenants( + IdentityUtil.resolveAdditionalTenants(Arrays.asList(additionallyAllowedTenants))); + return this; + } + + /** + * For multi-tenant applications, specifies additional tenants for which the credential may acquire tokens. + * Add the wildcard value "*" to allow the credential to acquire tokens for any tenant on which the application is installed. + * If no value is specified for TenantId this option will have no effect, and the credential will + * acquire tokens for any requested tenant. + * + * @param additionallyAllowedTenants the additionally allowed tenants. + * @return An updated instance of this builder with the additional tenants configured. + */ + @Override + public InteractiveBrowserCredentialBuilder additionallyAllowedTenants(List additionallyAllowedTenants) { + publicClientOptions + .setAdditionallyAllowedTenants(IdentityUtil.resolveAdditionalTenants(additionallyAllowedTenants)); + return this; + } + + /** + * Configures the options for customizing the browser for interactive authentication. + * @param browserCustomizationOptions the browser customization options + * @return An updated instance of this builder with the browser customization options configured. + */ + public InteractiveBrowserCredentialBuilder + browserCustomizationOptions(BrowserCustomizationOptions browserCustomizationOptions) { + this.publicClientOptions.setBrowserCustomizationOptions(browserCustomizationOptions); + return this; + } + + /** + * Creates a new {@link InteractiveBrowserCredential} with the current configurations. + * + * @return a {@link InteractiveBrowserCredential} with the current configurations. + */ + public InteractiveBrowserCredential build() { + ValidationUtil.validateInteractiveBrowserRedirectUrlSetup(port, redirectUrl, LOGGER); + + String clientId = this.publicClientOptions.getClientId(); + + publicClientOptions.setClientId(clientId != null ? clientId : IdentityConstants.DEVELOPER_SINGLE_SIGN_ON_ID); + return new InteractiveBrowserCredential(port, redirectUrl, automaticAuthentication, loginHint, + publicClientOptions); + } + + @Override + ClientOptions getClientOptions() { + return publicClientOptions; + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/ManagedIdentityCredential.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/ManagedIdentityCredential.java new file mode 100644 index 000000000000..8a0a5eda842a --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/ManagedIdentityCredential.java @@ -0,0 +1,133 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2; + +import com.azure.identity.v2.implementation.client.ManagedIdentityClient; +import com.azure.identity.v2.implementation.models.ManagedIdentityClientOptions; +import com.azure.identity.v2.implementation.util.LoggingUtil; +import com.azure.v2.core.credentials.TokenCredential; +import com.azure.v2.core.credentials.TokenRequestContext; +import com.microsoft.aad.msal4j.ManagedIdentityApplication; +import com.microsoft.aad.msal4j.ManagedIdentitySourceType; +import io.clientcore.core.credentials.oauth.AccessToken; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.utils.CoreUtils; + +/** + *

        Azure + * Managed Identity is a feature in + * Microsoft Entra ID + * that provides a way for applications running on Azure to authenticate themselves with Azure resources without + * needing to manage or store any secrets like passwords or keys. + * The ManagedIdentityCredential authenticates the configured managed identity (system or user assigned) of an + * Azure resource. So, if the application is running inside an Azure resource that supports Managed Identity through + * IDENTITY/MSI, IMDS endpoints, or both, then this credential will get your application authenticated, and offers a + * great secretless authentication experience. For more information refer to the + * managed identity authentication + * documentation.

        + * + *

        The Managed Identity credential supports managed identity authentication for the following Azure Services:

        + * + *
          + *
        1. Azure App Service
        2. + *
        3. Azure Arc
        4. + *
        5. Azure Cloud Shell
        6. + *
        7. Azure Functions
        8. + *
        9. Azure Kubernetes Service
        10. + *
        11. Azure Service Fabric
        12. + *
        13. Azure Virtual Machines
        14. + *
        15. Azure Virtual Machines Scale + * Sets
        16. + *
        + * + *

        Sample: Construct a simple ManagedIdentityCredential

        + * + *

        The following code sample demonstrates the creation of a ManagedIdentityCredential, + * using the {@link com.azure.identity.v2.ManagedIdentityCredentialBuilder} to configure it. Once this credential is + * created, it may be passed into the builder of many of the Azure SDK for Java client builders as the + * 'credential' parameter.

        + * + *
        + * TokenCredential managedIdentityCredential = new ManagedIdentityCredentialBuilder().build();
        + * 
        + * + *

        Sample: Construct a User Assigned ManagedIdentityCredential

        + * + *

        User-Assigned Managed Identity (UAMI) in Azure is a feature that allows you to create an identity in + * Microsoft Entra ID + * that is associated with one or more Azure resources. This identity can then be + * used to authenticate and authorize access to various Azure services and resources. The following code sample + * demonstrates the creation of a ManagedIdentityCredential to target a user assigned managed identity, using the + * {@link com.azure.identity.v2.ManagedIdentityCredentialBuilder} to configure it. Once this credential is created, it + * may be passed into the builder of many of the Azure SDK for Java client builders as the 'credential' parameter.

        + * + *
        + * TokenCredential managedIdentityCredentialUserAssigned = new ManagedIdentityCredentialBuilder().clientId(
        + *         clientId) // specify client id of user-assigned managed identity.
        + *     .build();
        + * 
        + * + * @see com.azure.identity + */ +public final class ManagedIdentityCredential implements TokenCredential { + private static final ClientLogger LOGGER = new ClientLogger(ManagedIdentityCredential.class); + + private final ManagedIdentityClientOptions miClientOptions; + private final ManagedIdentityClient managedIdentityClient; + private final String managedIdentityId; + + /** + * Creates an instance of the ManagedIdentityCredential with the client ID of a + * user-assigned identity, or app registration (when working with AKS pod-identity). + * + * @param miClientOptions the options for configuring the identity client. + */ + ManagedIdentityCredential(ManagedIdentityClientOptions miClientOptions) { + this.miClientOptions = miClientOptions; + + this.managedIdentityId = fetchManagedIdentityId(miClientOptions); + + this.managedIdentityClient = new ManagedIdentityClient(miClientOptions); + } + + @Override + public AccessToken getToken(TokenRequestContext request) { + + if (!CoreUtils.isNullOrEmpty(managedIdentityId)) { + ManagedIdentitySourceType managedIdentitySourceType = ManagedIdentityApplication.getManagedIdentitySource(); + if (ManagedIdentitySourceType.CLOUD_SHELL.equals(managedIdentitySourceType) + || ManagedIdentitySourceType.AZURE_ARC.equals(managedIdentitySourceType)) { + LoggingUtil.logCredentialUnavailableException(LOGGER, + new CredentialUnavailableException("ManagedIdentityCredential authentication unavailable. " + + "User-assigned managed identity is not supported in " + managedIdentitySourceType + + ". To use system-assigned managed identity, remove the configured client ID on " + + "the ManagedIdentityCredentialBuilder.")); + } + } + + try { + AccessToken token = managedIdentityClient.authenticate(request); + LoggingUtil.logTokenSuccess(LOGGER, request); + return token; + } catch (Exception e) { + LoggingUtil.logTokenError(LOGGER, request, e); + throw LOGGER.logThrowableAsError(new RuntimeException(e)); + } + } + + String fetchManagedIdentityId(ManagedIdentityClientOptions miClientOptions) { + String clientId = miClientOptions.getClientId(); + String resourceId = miClientOptions.getResourceId(); + String objectId = miClientOptions.getObjectId(); + if (clientId != null) { + return clientId; + } else if (resourceId != null) { + return resourceId; + } else if (objectId != null) { + return objectId; + } else { + return null; + } + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/ManagedIdentityCredentialBuilder.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/ManagedIdentityCredentialBuilder.java new file mode 100644 index 000000000000..920d1f1a7561 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/ManagedIdentityCredentialBuilder.java @@ -0,0 +1,146 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2; + +import com.azure.identity.v2.implementation.models.ClientOptions; +import com.azure.identity.v2.implementation.models.ManagedIdentityClientOptions; +import com.azure.identity.v2.implementation.util.ValidationUtil; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.utils.SharedExecutorService; + +import java.util.concurrent.ExecutorService; + +/** + *

        Fluent credential builder for instantiating a {@link ManagedIdentityCredential}.

        + * + *

        Azure + * Managed Identity is a feature in + * Microsoft Entra ID + * that provides a way for applications running on Azure to authenticate themselves with Azure resources without + * needing to manage or store any secrets like passwords or keys. + * The {@link ManagedIdentityCredential} authenticates the configured managed identity (system or user assigned) of an + * Azure resource. So, if the application is running inside an Azure resource that supports Managed Identity through + * IDENTITY/MSI, IMDS endpoints, or both, then this credential will get your application authenticated, and offers a + * great secretless authentication experience. For more information refer to the + * managed identity authentication + * documentation.

        + * + *

        Sample: Construct a simple ManagedIdentityCredential

        + * + *

        The following code sample demonstrates the creation of a {@link ManagedIdentityCredential}, + * using the ManagedIdentityCredentialBuilder to configure it. Once this credential is created, it may be passed into + * the builder of many of the Azure SDK for Java client builders as the 'credential' parameter.

        + * + *
        + * TokenCredential managedIdentityCredential = new ManagedIdentityCredentialBuilder().build();
        + * 
        + * + *

        Sample: Construct a User Assigned ManagedIdentityCredential

        + * + *

        User-Assigned Managed Identity (UAMI) in Azure is a feature that allows you to create an identity in + * Microsoft Entra ID + * that is associated with one or more Azure resources. This identity can then be used to authenticate and + * authorize access to various Azure services and resources. The following code sample demonstrates the creation of a + * {@link ManagedIdentityCredential} to target a user assigned managed identity, using the + * ManagedIdentityCredentialBuilder to configure it. Once this credential is created, it may be passed into the + * builder of many of the Azure SDK for Java client builders as the 'credential' parameter.

        + * + *
        + * TokenCredential managedIdentityCredentialUserAssigned = new ManagedIdentityCredentialBuilder().clientId(
        + *         clientId) // specify client id of user-assigned managed identity.
        + *     .build();
        + * 
        + * + * @see ManagedIdentityCredential + */ +public class ManagedIdentityCredentialBuilder extends EntraIdCredentialBuilderBase { + private static final ClientLogger LOGGER = new ClientLogger(ManagedIdentityCredentialBuilder.class); + + private final ManagedIdentityClientOptions miClientOptions; + + /** + * Constructs an instance of ManagedIdentityCredentialBuilder. + */ + public ManagedIdentityCredentialBuilder() { + super(); + this.miClientOptions = new ManagedIdentityClientOptions(); + } + + /** + * Specifies the client ID of a user-assigned or system-assigned managed identity. + * + * Only one of clientId, resourceId, or objectId can be specified. + * + * @param clientId the client ID + * @return the ManagedIdentityCredentialBuilder itself + */ + public ManagedIdentityCredentialBuilder clientId(String clientId) { + getClientOptions().setClientId(clientId); + return this; + } + + /** + * Specifies the resource ID of a user-assigned or system-assigned managed identity. + * + * Only one of clientId, resourceId, or objectId can be specified. + * + * @param resourceId the resource ID + * @return the ManagedIdentityCredentialBuilder itself + */ + public ManagedIdentityCredentialBuilder resourceId(String resourceId) { + miClientOptions.setResourceId(resourceId); + return this; + } + + /** + * Specifies the object ID of a user-assigned or system-assigned managed identity. + * + * Only one of clientId, resourceId, or objectId can be specified. + * + * @param objectId the object ID + * @return the ManagedIdentityCredentialBuilder itself + */ + public ManagedIdentityCredentialBuilder objectId(String objectId) { + miClientOptions.setObjectId(objectId); + return this; + } + + /** + * Specifies the ExecutorService to be used to execute the authentication requests. + * Developer is responsible for maintaining the lifecycle of the ExecutorService. + * + *

        + * If this is not configured, the {@link SharedExecutorService} will be used which is + * also shared with other SDK libraries. If there are many concurrent SDK tasks occurring, authentication + * requests might starve and configuring a separate executor service should be considered. + *

        + * + *

        The executor service and can be safely shutdown if the TokenCredential is no longer being used by the + * Azure SDK clients and should be shutdown before the application exits.

        + * + * @param executorService the executor service to use for executing authentication requests. + * @return the ManagedIdentityCredentialBuilder itself + */ + public ManagedIdentityCredentialBuilder executorService(ExecutorService executorService) { + getClientOptions().setExecutorService(executorService); + return this; + } + + /** + * Creates a new {@link ManagedIdentityCredential} with the current configurations. + * + * @return a {@link ManagedIdentityCredential} with the current configurations. + * @throws IllegalStateException if clientId and resourceId are both set. + */ + public ManagedIdentityCredential build() { + ValidationUtil.validateManagedIdentityIdParams(miClientOptions, LOGGER); + + return new ManagedIdentityCredential(miClientOptions); + } + + @Override + ClientOptions getClientOptions() { + return miClientOptions; + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/TokenCachePersistenceOptions.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/TokenCachePersistenceOptions.java new file mode 100644 index 000000000000..39bb988d85e5 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/TokenCachePersistenceOptions.java @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.identity.v2; + +/** + * Represents the Persistence Token Cache options used to setup the persistent access token cache. + * It allows users to enable the persistent token cache and optionally configure its name. The + * TokenCachePersistenceOptions can be configured directly on the Token Credential builders for the Token Credentials + * that support it. + * + * @see com.azure.identity.v2 + */ +public final class TokenCachePersistenceOptions { + private boolean unencryptedStorageAllowed; + private String name; + + /** + * Constructs an instance of TokenCachePersistenceOptions. + */ + public TokenCachePersistenceOptions() { + } + + /** + * Allows to use an unprotected file specified by cacheFileLocation() instead of + * Gnome keyring on Linux. This is restricted by default. For other platforms this setting currently doesn't apply. + * + * @param unencryptedStorageAllowed The flag indicating if unencrypted storage is allowed for the cache or not. + * @return An updated instance of the options bag. + */ + public TokenCachePersistenceOptions setUnencryptedStorageAllowed(boolean unencryptedStorageAllowed) { + this.unencryptedStorageAllowed = unencryptedStorageAllowed; + return this; + } + + /** + * Gets the status whether unencrypted storage is allowed for the persistent token cache. + * + * @return The status indicating if unencrypted storage is allowed for the persistent token cache. + */ + public boolean isUnencryptedStorageAllowed() { + return this.unencryptedStorageAllowed; + } + + /** + * Set the name uniquely identifying the cache. + * + * @param name the name of the cache + * @return the updated instance of the cache. + */ + public TokenCachePersistenceOptions setName(String name) { + this.name = name; + return this; + } + + /** + * Get the name uniquely identifying the cache. + * + * @return the name of the cache. + */ + public String getName() { + return this.name; + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/client/ClientBase.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/client/ClientBase.java new file mode 100644 index 000000000000..836596ec4d93 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/client/ClientBase.java @@ -0,0 +1,74 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2.implementation.client; + +import com.azure.identity.v2.implementation.models.ClientOptions; +import com.azure.identity.v2.implementation.models.HttpPipelineOptions; +import com.azure.identity.v2.implementation.util.IdentityUtil; +import io.clientcore.core.http.pipeline.HttpPipeline; +import io.clientcore.core.http.pipeline.HttpPipelineBuilder; +import io.clientcore.core.http.pipeline.HttpPipelinePolicy; +import io.clientcore.core.http.pipeline.HttpRetryPolicy; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +public abstract class ClientBase { + + final ClientOptions clientOptions; + final String tenantId; + final String clientId; + HttpPipelineAdapter httpPipelineAdapter; + HttpPipeline httpPipeline; + + /** + * Creates an IdentityClient with the given options. + * + * @param options the options configuring the client. + */ + public ClientBase(ClientOptions options) { + Objects.requireNonNull(options, "The Client options cannot be null."); + this.clientOptions = options; + this.tenantId = clientOptions.getTenantId() == null ? IdentityUtil.DEFAULT_TENANT : clientOptions.getTenantId(); + this.clientId = clientOptions.getClientId(); + } + + HttpPipeline getPipeline() { + // if we've already initialized, return the pipeline + if (this.httpPipeline != null) { + return httpPipeline; + } + + // if the user has supplied a pipeline, use it + HttpPipeline httpPipeline = getHttpPipelineOptions().getHttpPipeline(); + if (httpPipeline != null) { + this.httpPipeline = httpPipeline; + return this.httpPipeline; + } + + // setupPipeline will use the user's HttpClient and HttpClientOptions if they're set + // otherwise it will use defaults. + this.httpPipeline = setupPipeline(); + return this.httpPipeline; + } + + HttpPipeline setupPipeline() { + //TODO (g2vinay): Wire the HttpPipelineOptions in Pipeline construction. + List policies = new ArrayList<>(); + policies.add(new HttpRetryPolicy()); + HttpPipeline httpPipeline = new HttpPipelineBuilder().addPolicy(policies.get(0)) + .httpClient(getHttpPipelineOptions().getHttpClient()) + .build(); + return httpPipeline; + } + + void initializeHttpPipelineAdapter() { + httpPipelineAdapter = new HttpPipelineAdapter(getPipeline(), getHttpPipelineOptions()); + } + + HttpPipelineOptions getHttpPipelineOptions() { + return clientOptions.getHttpPipelineOptions(); + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/client/ConfidentialClient.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/client/ConfidentialClient.java new file mode 100644 index 000000000000..7373706e27b0 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/client/ConfidentialClient.java @@ -0,0 +1,200 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2.implementation.client; + +import com.azure.identity.v2.CredentialAuthenticationException; +import com.azure.identity.v2.TokenCachePersistenceOptions; +import com.azure.identity.v2.implementation.models.ConfidentialClientOptions; +import com.azure.identity.v2.implementation.models.MsalToken; +import com.azure.identity.v2.implementation.util.IdentityUtil; +import com.azure.v2.core.credentials.TokenRequestContext; +import com.microsoft.aad.msal4j.ClientCredentialParameters; +import com.microsoft.aad.msal4j.ConfidentialClientApplication; +import com.microsoft.aad.msal4j.SilentParameters; +import com.microsoft.aad.msal4j.ClaimsRequest; +import com.microsoft.aad.msal4j.IAuthenticationResult; +import com.microsoft.aad.msal4j.IClientCredential; +import com.microsoft.aad.msal4j.ClientCredentialFactory; +import io.clientcore.core.credentials.oauth.AccessToken; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.instrumentation.logging.LogLevel; +import io.clientcore.core.utils.SharedExecutorService; + +import java.net.MalformedURLException; +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.ExecutionException; +import java.util.regex.Pattern; + +public class ConfidentialClient extends ClientBase { + + static final ClientLogger LOGGER = new ClientLogger(ConfidentialClient.class); + static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); + static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); + final ConfidentialClientOptions confidentialClientOptions; + + private final SynchronousAccessor confidentialClientApplicationAccessor; + private final SynchronousAccessor confidentialClientApplicationAccessorWithCae; + + /** + * Creates an IdentityClient with the given options. + * + * @param options the options configuring the client. + */ + public ConfidentialClient(ConfidentialClientOptions options) { + super(options); + this.confidentialClientOptions = options == null ? new ConfidentialClientOptions() : options; + + this.confidentialClientApplicationAccessor = new SynchronousAccessor<>(() -> this.getClient(false)); + + this.confidentialClientApplicationAccessorWithCae = new SynchronousAccessor<>(() -> this.getClient(true)); + } + + /** + * Asynchronously acquire a token from Active Directory with a client secret. + * + * @param request the details of the token request + * @return a Publisher that emits an AccessToken + */ + public AccessToken authenticate(TokenRequestContext request) { + ConfidentialClientApplication confidentialClient = getConfidentialClientInstance(request).getValue(); + ClientCredentialParameters.ClientCredentialParametersBuilder builder + = ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) + .tenant(IdentityUtil.resolveTenantId(tenantId, request, clientOptions)); + + if (confidentialClientOptions.getClientAssertionFunction() != null) { + builder.clientCredential(ClientCredentialFactory.createFromClientAssertion( + confidentialClientOptions.getClientAssertionFunction().apply(getPipeline()))); + } + try { + return new MsalToken(confidentialClient.acquireToken(builder.build()).get()); + } catch (InterruptedException | ExecutionException e) { + throw LOGGER.logThrowableAsError(new RuntimeException(e)); + } + } + + /** + * Acquire a token from the confidential client. + * + * @param request the details of the token request + * @return An access token, or null if no token exists in the cache. + */ + @SuppressWarnings("deprecation") + public AccessToken authenticateWithCache(TokenRequestContext request) { + ConfidentialClientApplication confidentialClientApplication = getConfidentialClientInstance(request).getValue(); + SilentParameters.SilentParametersBuilder parametersBuilder + = SilentParameters.builder(new HashSet<>(request.getScopes())) + .tenant(IdentityUtil.resolveTenantId(tenantId, request, clientOptions)); + + if (request.isCaeEnabled() && request.getClaims() != null) { + ClaimsRequest claimsRequest = ClaimsRequest.formatAsClaimsRequest(request.getClaims()); + parametersBuilder.claims(claimsRequest); + parametersBuilder.forceRefresh(true); + } + + try { + IAuthenticationResult authenticationResult + = confidentialClientApplication.acquireTokenSilently(parametersBuilder.build()).get(); + AccessToken accessToken = new MsalToken(authenticationResult); + if (OffsetDateTime.now().isBefore(accessToken.getExpiresAt().minus(REFRESH_OFFSET))) { + return accessToken; + } else { + throw new IllegalStateException("Received token is close to expiry."); + } + } catch (MalformedURLException e) { + throw LOGGER.logThrowableAsError(new RuntimeException(e)); + } catch (ExecutionException | InterruptedException e) { + // Cache misses should not throw an exception, but should log. + if (e.getMessage().contains("Token not found in the cache")) { + LOGGER.atLevel(LogLevel.VERBOSE).log("Token not found in the MSAL cache."); + return null; + } else { + throw LOGGER.logThrowableAsError(new CredentialAuthenticationException(e.getMessage())); + } + } + } + + ConfidentialClientApplication getClient(boolean enableCae) { + if (clientId == null) { + throw LOGGER.logThrowableAsError(new IllegalArgumentException( + "A non-null value for client ID must be provided for user authentication.")); + } + String authorityUrl + = TRAILING_FORWARD_SLASHES.matcher(clientOptions.getAuthorityHost()).replaceAll("") + "/" + tenantId; + IClientCredential credential; + + if (confidentialClientOptions.getClientSecret() != null) { + credential = ClientCredentialFactory.createFromSecret(confidentialClientOptions.getClientSecret()); + } else { + throw LOGGER.logThrowableAsError( + new IllegalArgumentException("Must provide client secret or client certificate path." + + " To mitigate this issue, please refer to the troubleshooting guidelines here at " + + "https://aka.ms/azsdk/java/identity/serviceprincipalauthentication/troubleshoot")); + } + + ConfidentialClientApplication.Builder applicationBuilder + = ConfidentialClientApplication.builder(clientId, credential); + try { + applicationBuilder = applicationBuilder.authority(authorityUrl) + .instanceDiscovery(clientOptions.isInstanceDiscoveryEnabled()); + + if (!clientOptions.isInstanceDiscoveryEnabled()) { + LOGGER.atLevel(LogLevel.VERBOSE) + .log("Instance discovery and authority validation is disabled. In this" + + " state, the library will not fetch metadata to validate the specified authority host. As a" + + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); + } + } catch (MalformedURLException e) { + throw LOGGER.logThrowableAsError(new IllegalStateException(e)); + } + + if (enableCae) { + Set set = new HashSet<>(1); + set.add("CP1"); + applicationBuilder.clientCapabilities(set); + } + + initializeHttpPipelineAdapter(); + + if (httpPipelineAdapter != null) { + applicationBuilder.httpClient(httpPipelineAdapter); + } + + if (clientOptions.getExecutorService() != null) { + applicationBuilder.executorService(clientOptions.getExecutorService()); + } else { + applicationBuilder.executorService(SharedExecutorService.getInstance()); + } + + TokenCachePersistenceOptions tokenCachePersistenceOptions = clientOptions.getTokenCacheOptions(); + PersistentTokenCacheImpl tokenCache = null; + if (tokenCachePersistenceOptions != null) { + try { + tokenCache = new PersistentTokenCacheImpl(enableCae) + .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) + .setName(tokenCachePersistenceOptions.getName()); + applicationBuilder.setTokenCacheAccessAspect(tokenCache); + } catch (Throwable t) { + throw LOGGER.logThrowableAsError( + new CredentialAuthenticationException("Shared token cache is unavailable in this environment.", t)); + } + } + + ConfidentialClientApplication confidentialClientApplication = applicationBuilder.build(); + + if (tokenCache != null) { + tokenCache.registerCache(); + } + return confidentialClientApplication; + } + + private SynchronousAccessor + getConfidentialClientInstance(TokenRequestContext request) { + return request.isCaeEnabled() + ? confidentialClientApplicationAccessorWithCae + : confidentialClientApplicationAccessor; + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/client/HttpPipelineAdapter.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/client/HttpPipelineAdapter.java new file mode 100644 index 000000000000..b574959e7be6 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/client/HttpPipelineAdapter.java @@ -0,0 +1,125 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2.implementation.client; + +import com.azure.identity.v2.implementation.models.HttpPipelineOptions; +import com.azure.identity.v2.implementation.util.IdentityUtil; +import com.microsoft.aad.msal4j.IHttpClient; +import com.microsoft.aad.msal4j.IHttpResponse; +import com.microsoft.aad.msal4j.HttpRequest; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpHeaders; +import io.clientcore.core.http.models.HttpMethod; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.http.models.HttpHeader; +import io.clientcore.core.http.pipeline.HttpPipeline; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.instrumentation.logging.LogLevel; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.utils.CoreUtils; + +import java.io.IOException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.text.MessageFormat; +import java.util.Base64; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * Adapts an HttpPipeline to an instance of IHttpClient in the MSAL4j pipeline. + */ +class HttpPipelineAdapter implements IHttpClient { + private static final ClientLogger CLIENT_LOGGER = new ClientLogger(HttpPipelineAdapter.class); + private static final String ACCOUNT_IDENTIFIER_LOG_MESSAGE + = "[Authenticated account] Client ID: {0}, Tenant ID: {1}" + + ", User Principal Name: {2}, Object ID (user): {3})"; + private static final String APPLICATION_IDENTIFIER = "Application Identifier"; + private static final String OBJECT_ID = "Object Id"; + private static final String TENANT_ID = "Tenant Id"; + private static final String USER_PRINCIPAL_NAME = "User Principal Name"; + private static final String APPLICATION_ID_JSON_KEY = "appid"; + private static final String OBJECT_ID_JSON_KEY = "oid"; + private static final String TENANT_ID_JSON_KEY = "tid"; + private static final String USER_PRINCIPAL_NAME_JSON_KEY = "upn"; + private final HttpPipeline httpPipeline; + private HttpPipelineOptions identityClientOptions; + + HttpPipelineAdapter(HttpPipeline httpPipeline, HttpPipelineOptions identityClientOptions) { + this.httpPipeline = httpPipeline; + this.identityClientOptions = identityClientOptions; + } + + @Override + public IHttpResponse send(HttpRequest httpRequest) { + // convert request + io.clientcore.core.http.models.HttpRequest request = new io.clientcore.core.http.models.HttpRequest(); + + if (httpRequest.headers() != null) { + HttpHeaders httpHeaders = new HttpHeaders(httpRequest.headers().size()); + httpRequest.headers().forEach((k, v) -> httpHeaders.add(HttpHeaderName.fromString(k), v)); + request.setHeaders(httpHeaders); + } + + request.setMethod(HttpMethod.valueOf(httpRequest.httpMethod().name())); + request.setUri(URI.create(httpRequest.url().toString())); + + if (httpRequest.body() != null) { + request.setBody(BinaryData.fromString(httpRequest.body())); + } + + Response response = httpPipeline.send(request); + String body = response.getValue().toString(); + + logAccountIdentifiersIfConfigured(body); + com.microsoft.aad.msal4j.HttpResponse httpResponse + = new com.microsoft.aad.msal4j.HttpResponse().statusCode(response.getStatusCode()); + if (!CoreUtils.isNullOrEmpty(body)) { + httpResponse.body(body); + } + httpResponse.addHeaders(response.getHeaders() + .stream() + .collect(Collectors.toMap(header -> header.getName().toString(), HttpHeader::getValues))); + return httpResponse; + } + + private void logAccountIdentifiersIfConfigured(String body) { + try { + String accessToken = IdentityUtil.getAccessToken(body); + if (accessToken != null) { + String[] base64Metadata = accessToken.split("\\."); + if (base64Metadata.length > 1) { + byte[] decoded = Base64.getDecoder().decode(base64Metadata[1]); + String data = new String(decoded, StandardCharsets.UTF_8); + + Map jsonMap = IdentityUtil.parseJsonIntoMap(data); + + String appId + = jsonMap.containsKey(APPLICATION_ID_JSON_KEY) ? jsonMap.get(APPLICATION_ID_JSON_KEY) : null; + String objectId = jsonMap.containsKey(OBJECT_ID_JSON_KEY) ? jsonMap.get(OBJECT_ID_JSON_KEY) : null; + String tenantId = jsonMap.containsKey(TENANT_ID_JSON_KEY) ? jsonMap.get(TENANT_ID_JSON_KEY) : null; + String userPrincipalName = jsonMap.containsKey(USER_PRINCIPAL_NAME_JSON_KEY) + ? jsonMap.get(USER_PRINCIPAL_NAME_JSON_KEY) + : null; + + CLIENT_LOGGER.atLevel(LogLevel.INFORMATIONAL) + .log(MessageFormat.format(ACCOUNT_IDENTIFIER_LOG_MESSAGE, + getAccountIdentifierMessage(APPLICATION_IDENTIFIER, appId), + getAccountIdentifierMessage(TENANT_ID, tenantId), + getAccountIdentifierMessage(USER_PRINCIPAL_NAME, userPrincipalName), + getAccountIdentifierMessage(OBJECT_ID, objectId))); + } + } + } catch (IOException e) { + CLIENT_LOGGER.logThrowableAsWarning(e); + } + } + + private String getAccountIdentifierMessage(String identifierName, String identifierValue) { + if (identifierValue == null) { + return "No " + identifierName + " available."; + } + return identifierValue; + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/client/ManagedIdentityClient.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/client/ManagedIdentityClient.java new file mode 100644 index 000000000000..c54acd820d83 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/client/ManagedIdentityClient.java @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2.implementation.client; + +import com.azure.identity.v2.CredentialAuthenticationException; +import com.azure.identity.v2.implementation.models.MsalToken; +import com.azure.identity.v2.implementation.models.ManagedIdentityClientOptions; +import com.azure.identity.v2.implementation.util.ScopeUtil; +import com.azure.v2.core.credentials.TokenRequestContext; +import com.microsoft.aad.msal4j.ManagedIdentityApplication; +import com.microsoft.aad.msal4j.ManagedIdentityId; +import io.clientcore.core.credentials.oauth.AccessToken; +import io.clientcore.core.utils.CoreUtils; +import io.clientcore.core.utils.SharedExecutorService; + +public class ManagedIdentityClient extends ClientBase { + final ManagedIdentityClientOptions managedIdentityClientOptions; + final String resourceId; + final String objectId; + + private final SynchronousAccessor miClientApplicationAccessor; + + /** + * Creates an IdentityClient with the given options. + * + * @param options the options configuring the client. + */ + public ManagedIdentityClient(ManagedIdentityClientOptions options) { + super(options); + this.managedIdentityClientOptions = options == null ? new ManagedIdentityClientOptions() : options; + this.resourceId = managedIdentityClientOptions.getResourceId(); + this.objectId = managedIdentityClientOptions.getObjectId(); + + this.miClientApplicationAccessor = new SynchronousAccessor<>(() -> this.getManagedIdentityClient()); + } + + public AccessToken authenticate(TokenRequestContext request) { + String resource = ScopeUtil.scopesToResource(request.getScopes()); + + ManagedIdentityApplication managedIdentityApplication = miClientApplicationAccessor.getValue(); + + com.microsoft.aad.msal4j.ManagedIdentityParameters.ManagedIdentityParametersBuilder builder + = com.microsoft.aad.msal4j.ManagedIdentityParameters.builder(resource); + try { + return new MsalToken(managedIdentityApplication.acquireTokenForManagedIdentity(builder.build()).get()); + } catch (Exception e) { + throw new CredentialAuthenticationException("Managed Identity authentication is not available.", e); + } + } + + ManagedIdentityApplication getManagedIdentityClient() { + + ManagedIdentityId managedIdentityId; + + if (!CoreUtils.isNullOrEmpty(clientId)) { + managedIdentityId = ManagedIdentityId.userAssignedClientId(clientId); + } else if (!CoreUtils.isNullOrEmpty(managedIdentityClientOptions.getResourceId())) { + managedIdentityId = ManagedIdentityId.userAssignedResourceId(resourceId); + } else if (!CoreUtils.isNullOrEmpty(objectId)) { + managedIdentityId = ManagedIdentityId.userAssignedObjectId(objectId); + } else { + managedIdentityId = ManagedIdentityId.systemAssigned(); + } + + ManagedIdentityApplication.Builder miBuilder = ManagedIdentityApplication.builder(managedIdentityId); + + initializeHttpPipelineAdapter(); + miBuilder.httpClient(httpPipelineAdapter); + + if (clientOptions.getExecutorService() != null) { + miBuilder.executorService(clientOptions.getExecutorService()); + } else { + miBuilder.executorService(SharedExecutorService.getInstance()); + } + + return miBuilder.build(); + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/client/PersistentTokenCacheImpl.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/client/PersistentTokenCacheImpl.java new file mode 100644 index 000000000000..768dffb1cd9d --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/client/PersistentTokenCacheImpl.java @@ -0,0 +1,108 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2.implementation.client; + +import com.azure.identity.v2.CredentialAuthenticationException; +import com.azure.identity.v2.implementation.util.IdentityUtil; +import com.microsoft.aad.msal4j.ITokenCacheAccessAspect; +import com.microsoft.aad.msal4j.ITokenCacheAccessContext; +import com.microsoft.aad.msal4jextensions.PersistenceSettings; +import com.microsoft.aad.msal4jextensions.PersistenceTokenCacheAccessAspect; +import com.microsoft.aad.msal4jextensions.persistence.linux.KeyRingAccessException; +import io.clientcore.core.instrumentation.logging.ClientLogger; + +import java.nio.file.Path; +import java.nio.file.Paths; + +public class PersistentTokenCacheImpl implements ITokenCacheAccessAspect { + private static final String DEFAULT_CACHE_FILE_NAME = "msal.cache"; + private static final String CAE_ENABLED_CACHE_SUFFIX = ".cae"; + private static final String CAE_DISABLED_CACHE_SUFFIX = ".nocae"; + private static final String DEFAULT_CONFIDENTIAL_CACHE_FILE_NAME = "msal.confidential.cache"; + static final Path DEFAULT_CACHE_FILE_PATH = IdentityUtil.isWindowsPlatform() + ? Paths.get(System.getProperty("user.home"), "AppData", "Local", ".IdentityService") + : Paths.get(System.getProperty("user.home"), ".IdentityService"); + private static final String DEFAULT_KEYCHAIN_SERVICE = "Microsoft.Developer.IdentityService"; + private static final String DEFAULT_KEYCHAIN_ACCOUNT = "MSALCache"; + private static final String DEFAULT_CONFIDENTIAL_KEYCHAIN_ACCOUNT = "MSALConfidentialCache"; + private static final String DEFAULT_KEYRING_NAME = "default"; + private static final String DEFAULT_KEYRING_SCHEMA = "msal.cache"; + private static final String DEFAULT_KEYRING_ITEM_NAME = DEFAULT_KEYCHAIN_ACCOUNT; + private static final String DEFAULT_CONFIDENTIAL_KEYRING_ITEM_NAME = DEFAULT_CONFIDENTIAL_KEYCHAIN_ACCOUNT; + private static final String DEFAULT_KEYRING_ATTR_NAME = "MsalClientID"; + private static final String DEFAULT_KEYRING_ATTR_VALUE = "Microsoft.Developer.IdentityService"; + + private static final ClientLogger LOGGER = new ClientLogger(PersistentTokenCacheImpl.class); + private boolean allowUnencryptedStorage; + private String name; + private PersistenceTokenCacheAccessAspect cacheAccessAspect; + + private boolean caeEnabled; + + public PersistentTokenCacheImpl(boolean caeEnabled) { + super(); + this.caeEnabled = caeEnabled; + } + + public PersistentTokenCacheImpl setAllowUnencryptedStorage(boolean allowUnencryptedStorage) { + this.allowUnencryptedStorage = allowUnencryptedStorage; + return this; + } + + public PersistentTokenCacheImpl setName(String name) { + this.name = name; + return this; + } + + boolean registerCache() { + try { + PersistenceSettings persistenceSettings = getPersistenceSettings(); + cacheAccessAspect = new PersistenceTokenCacheAccessAspect(persistenceSettings); + return true; + } catch (Throwable t) { + throw LOGGER.logThrowableAsError( + new CredentialAuthenticationException("Shared token cache is unavailable in this environment.", t)); + } + } + + public void beforeCacheAccess(ITokenCacheAccessContext iTokenCacheAccessContext) { + cacheAccessAspect.beforeCacheAccess(iTokenCacheAccessContext); + } + + public void afterCacheAccess(ITokenCacheAccessContext iTokenCacheAccessContext) { + cacheAccessAspect.afterCacheAccess(iTokenCacheAccessContext); + } + + private PersistenceSettings getPersistenceSettings() { + PersistenceSettings.Builder persistenceSettingsBuilder = PersistenceSettings + .builder(getCacheName(name != null ? name : DEFAULT_CACHE_FILE_NAME), DEFAULT_CACHE_FILE_PATH); + if (IdentityUtil.isMacPlatform()) { + persistenceSettingsBuilder.setMacKeychain(DEFAULT_KEYCHAIN_SERVICE, + getCacheName(name != null ? name : DEFAULT_KEYCHAIN_ACCOUNT)); + return persistenceSettingsBuilder.build(); + } else if (IdentityUtil.isLinuxPlatform()) { + try { + persistenceSettingsBuilder.setLinuxKeyring(DEFAULT_KEYRING_NAME, DEFAULT_KEYRING_SCHEMA, + getCacheName(name != null ? name : DEFAULT_KEYRING_ITEM_NAME), DEFAULT_KEYRING_ATTR_NAME, + DEFAULT_KEYRING_ATTR_VALUE, null, null); + return persistenceSettingsBuilder.build(); + } catch (KeyRingAccessException e) { + if (!allowUnencryptedStorage) { + throw LOGGER.logThrowableAsError(e); + } + persistenceSettingsBuilder.setLinuxUseUnprotectedFileAsCacheStorage(true); + return persistenceSettingsBuilder.build(); + } + } + return persistenceSettingsBuilder.build(); + } + + private String getCacheName(String name) { + if (caeEnabled) { + return name + CAE_ENABLED_CACHE_SUFFIX; + } else { + return name + CAE_DISABLED_CACHE_SUFFIX; + } + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/client/PublicClient.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/client/PublicClient.java new file mode 100644 index 000000000000..88a4a5e97fd7 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/client/PublicClient.java @@ -0,0 +1,253 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2.implementation.client; + +import com.azure.identity.v2.BrowserCustomizationOptions; +import com.azure.identity.v2.CredentialAuthenticationException; +import com.azure.identity.v2.TokenCachePersistenceOptions; +import com.azure.identity.v2.implementation.models.MsalToken; +import com.azure.identity.v2.implementation.models.PublicClientOptions; +import com.azure.identity.v2.implementation.util.IdentityUtil; +import com.azure.v2.core.credentials.TokenRequestContext; +import com.microsoft.aad.msal4j.ClaimsRequest; +import com.microsoft.aad.msal4j.IAccount; +import com.microsoft.aad.msal4j.PublicClientApplication; +import com.microsoft.aad.msal4j.SilentParameters; +import com.microsoft.aad.msal4j.InteractiveRequestParameters; +import com.microsoft.aad.msal4j.SystemBrowserOptions; +import com.microsoft.aad.msal4j.Prompt; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.instrumentation.logging.LogLevel; +import io.clientcore.core.utils.CoreUtils; +import io.clientcore.core.utils.SharedExecutorService; + +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.ExecutionException; +import java.util.regex.Pattern; + +public class PublicClient extends ClientBase { + + static final ClientLogger LOGGER = new ClientLogger(PublicClient.class); + static final Pattern TRAILING_FORWARD_SLASHES = Pattern.compile("/+$"); + static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); + static final String HTTP_LOCALHOST = "http://localhost"; + + final PublicClientOptions options; + + private final SynchronousAccessor clientAccessor; + private final SynchronousAccessor clientAccessorWithCae; + + /** + * Creates an IdentityClient with the given options. + * + * @param options the options configuring the client. + */ + public PublicClient(PublicClientOptions options) { + super(options); + this.options = options == null ? new PublicClientOptions() : options; + + this.clientAccessor = new SynchronousAccessor<>(() -> this.getClient(false)); + + this.clientAccessorWithCae = new SynchronousAccessor<>(() -> this.getClient(true)); + } + + private SynchronousAccessor getClientInstance(TokenRequestContext request) { + return request.isCaeEnabled() ? clientAccessorWithCae : clientAccessor; + } + + /** + * Acquire a token from the currently logged in client. + * + * @param request the details of the token request + * @param account the account used to log in to acquire the last token + * @return An access token, or null if no token exists in the cache. + */ + @SuppressWarnings("deprecation") + public MsalToken authenticateWithPublicClientCache(TokenRequestContext request, IAccount account) { + PublicClientApplication pc = getClientInstance(request).getValue(); + MsalToken token = acquireTokenFromPublicClientSilently(request, pc, account, false); + if (OffsetDateTime.now().isAfter(token.getExpiresAt().minus(REFRESH_OFFSET))) { + token = acquireTokenFromPublicClientSilently(request, pc, account, true); + } + return token; + } + + private MsalToken acquireTokenFromPublicClientSilently(TokenRequestContext request, PublicClientApplication pc, + IAccount account, boolean forceRefresh) { + SilentParameters.SilentParametersBuilder parametersBuilder + = SilentParameters.builder(new HashSet<>(request.getScopes())); + + if (forceRefresh) { + parametersBuilder.forceRefresh(true); + } + + if (request.isCaeEnabled() && request.getClaims() != null) { + ClaimsRequest claimsRequest = ClaimsRequest.formatAsClaimsRequest(request.getClaims()); + parametersBuilder.claims(claimsRequest); + parametersBuilder.forceRefresh(true); + } + + if (account != null) { + parametersBuilder = parametersBuilder.account(account); + } + parametersBuilder.tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); + try { + return new MsalToken(pc.acquireTokenSilently(parametersBuilder.build()).get()); + } catch (MalformedURLException e) { + throw LOGGER.logThrowableAsError(new RuntimeException(e.getMessage(), e)); + } catch (ExecutionException | InterruptedException e) { + // Cache misses should not throw an exception, but should log. + if (e.getMessage().contains("Token not found in the cache")) { + LOGGER.atLevel(LogLevel.VERBOSE).log("Token not found in the MSAL cache."); + return null; + } else { + throw LOGGER.logThrowableAsError(new CredentialAuthenticationException(e.getMessage(), e)); + } + } + } + + PublicClientApplication getClient(boolean enableCae) { + if (clientId == null) { + throw LOGGER.logThrowableAsError(new IllegalArgumentException( + "A non-null value for client ID must be provided for user authentication.")); + } + String authorityUrl + = TRAILING_FORWARD_SLASHES.matcher(options.getAuthorityHost()).replaceAll("") + "/" + tenantId; + PublicClientApplication.Builder builder = PublicClientApplication.builder(clientId); + try { + builder = builder.authority(authorityUrl).instanceDiscovery(options.isInstanceDiscoveryEnabled()); + + if (!options.isInstanceDiscoveryEnabled()) { + LOGGER.atLevel(LogLevel.VERBOSE) + .log("Instance discovery and authority validation is disabled. In this" + + " state, the library will not fetch metadata to validate the specified authority host. As a" + + " result, it is crucial to ensure that the configured authority host is valid and trustworthy."); + } + } catch (MalformedURLException e) { + throw LOGGER.logThrowableAsWarning(new IllegalStateException(e)); + } + + initializeHttpPipelineAdapter(); + builder.httpClient(httpPipelineAdapter); + + if (options.getExecutorService() != null) { + builder.executorService(options.getExecutorService()); + } else { + builder.executorService(SharedExecutorService.getInstance()); + } + + if (enableCae) { + Set set = new HashSet<>(1); + set.add("CP1"); + builder.clientCapabilities(set); + } + + TokenCachePersistenceOptions tokenCachePersistenceOptions = options.getTokenCacheOptions(); + PersistentTokenCacheImpl tokenCache = null; + if (tokenCachePersistenceOptions != null) { + try { + tokenCache = new PersistentTokenCacheImpl(enableCae) + .setAllowUnencryptedStorage(tokenCachePersistenceOptions.isUnencryptedStorageAllowed()) + .setName(tokenCachePersistenceOptions.getName()); + builder.setTokenCacheAccessAspect(tokenCache); + } catch (Throwable t) { + throw LOGGER.logThrowableAsError( + new CredentialAuthenticationException("Shared token cache is unavailable in this environment.", t)); + } + } + PublicClientApplication publicClientApplication = builder.build(); + + if (tokenCache != null) { + tokenCache.registerCache(); + } + return publicClientApplication; + } + + /** + * Synchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The + * credential will run a minimal local HttpServer at the given port, so {@code http://localhost:{port}} must be + * listed as a valid reply URL for the application. + * + * @param request the details of the token request + * @param port the port on which the HTTP server is listening + * @param redirectUrl the redirect URL to listen on and receive security code + * @param loginHint the username suggestion to pre-fill the login page's username/email address field + * @return a Publisher that emits an AccessToken + */ + public MsalToken authenticateWithBrowserInteraction(TokenRequestContext request, Integer port, String redirectUrl, + String loginHint) { + URI redirectUri; + String redirect; + + if (port != null) { + redirect = HTTP_LOCALHOST + ":" + port; + } else if (redirectUrl != null) { + redirect = redirectUrl; + } else { + redirect = HTTP_LOCALHOST; + } + + try { + redirectUri = new URI(redirect); + } catch (URISyntaxException e) { + throw LOGGER.logThrowableAsError(new RuntimeException(e)); + } + PublicClientApplication pc = getClientInstance(request).getValue(); + + // If the broker is enabled, try to get the token for the default account by passing + // a null account to MSAL. If that fails, show the dialog. + MsalToken token = null; + if (token == null) { + InteractiveRequestParameters.InteractiveRequestParametersBuilder builder + = buildInteractiveRequestParameters(request, loginHint, redirectUri); + + try { + return new MsalToken(pc.acquireToken(builder.build()).get()); + } catch (Exception e) { + throw LOGGER.logThrowableAsError(new CredentialAuthenticationException( + "Failed to acquire token with Interactive Browser Authentication.", e)); + } + } + return token; + } + + InteractiveRequestParameters.InteractiveRequestParametersBuilder + buildInteractiveRequestParameters(TokenRequestContext request, String loginHint, URI redirectUri) { + InteractiveRequestParameters.InteractiveRequestParametersBuilder builder + = InteractiveRequestParameters.builder(redirectUri) + .scopes(new HashSet<>(request.getScopes())) + .prompt(Prompt.SELECT_ACCOUNT) + .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); + + if (request.isCaeEnabled() && request.getClaims() != null) { + ClaimsRequest claimsRequest = ClaimsRequest.formatAsClaimsRequest(request.getClaims()); + builder.claims(claimsRequest); + } + + BrowserCustomizationOptions browserCustomizationOptions = options.getBrowserCustomizationOptions(); + + if (IdentityUtil.browserCustomizationOptionsPresent(browserCustomizationOptions)) { + SystemBrowserOptions.SystemBrowserOptionsBuilder browserOptionsBuilder = SystemBrowserOptions.builder(); + if (!CoreUtils.isNullOrEmpty(browserCustomizationOptions.getSuccessMessage())) { + browserOptionsBuilder.htmlMessageSuccess(browserCustomizationOptions.getSuccessMessage()); + } + + if (!CoreUtils.isNullOrEmpty(browserCustomizationOptions.getErrorMessage())) { + browserOptionsBuilder.htmlMessageError(browserCustomizationOptions.getErrorMessage()); + } + builder.systemBrowserOptions(browserOptionsBuilder.build()); + } + + if (loginHint != null) { + builder.loginHint(loginHint); + } + return builder; + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/client/SynchronousAccessor.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/client/SynchronousAccessor.java new file mode 100644 index 000000000000..26f2ffa5ac74 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/client/SynchronousAccessor.java @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2.implementation.client; + +import java.time.Duration; +import java.util.concurrent.locks.ReentrantLock; +import java.util.function.Supplier; + +/** + * Synchronizes reactor threads accessing/instantiating a common value {@code T}. + * + * @param The value being instantiated / accessed. + */ +public class SynchronousAccessor { + private volatile T cache; + private Supplier cacheSupplier; + private ReentrantLock lock; + private Duration cacheTimeout; + + private long startTimeInMillis; + + public SynchronousAccessor(Supplier supplier) { + cacheSupplier = supplier; + startTimeInMillis = System.currentTimeMillis(); + lock = new ReentrantLock(); + } + + public SynchronousAccessor(Supplier supplier, Duration cacheTimeout) { + cacheSupplier = supplier; + startTimeInMillis = System.currentTimeMillis(); + this.cacheTimeout = cacheTimeout; + lock = new ReentrantLock(); + } + + /** + * Get the value from the configured supplier. + * + * @return the output {@code T} + */ + public T getValue() { + if (cache == null || shouldRefreshCache()) { + lock.lock(); + try { + cache = cacheSupplier.get(); + } finally { + lock.unlock(); + } + } + return cache; + } + + private boolean shouldRefreshCache() { + return cacheTimeout != null + ? (System.currentTimeMillis() - startTimeInMillis) >= cacheTimeout.toMillis() + : false; + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/client/package-info.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/client/package-info.java new file mode 100644 index 000000000000..a40ba2f23b3d --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/client/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing client classes for credentials. + */ +package com.azure.identity.v2.implementation.client; diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/models/ClientOptions.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/models/ClientOptions.java new file mode 100644 index 000000000000..ba4be98e0e98 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/models/ClientOptions.java @@ -0,0 +1,243 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2.implementation.models; + +import com.azure.identity.v2.AzureAuthorityHosts; +import com.azure.identity.v2.TokenCachePersistenceOptions; +import com.azure.identity.v2.implementation.util.ValidationUtil; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.utils.configuration.Configuration; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import java.util.concurrent.ExecutorService; + +/** + * Represents abstract base for Client Options used in Managed Identity OAuth Flow . + */ +public abstract class ClientOptions implements Cloneable { + private static final ClientLogger LOGGER = new ClientLogger(ClientOptions.class); + private HttpPipelineOptions httpPipelineOptions; + private String authorityHost; + private ExecutorService executorService; + private TokenCachePersistenceOptions tokenCachePersistenceOptions; + private boolean instanceDiscovery; + private Set additionallyAllowedTenants; + private Configuration configuration; + private String tenantId; + private String clientId; + + /** + * Creates an instance of IdentityClientOptions with default settings. + */ + public ClientOptions() { + configuration = Configuration.getGlobalConfiguration(); + loadFromConfiguration(configuration); + instanceDiscovery = true; + additionallyAllowedTenants = new HashSet<>(); + } + + /** + * Gets the configured configuration store. + * + * @return the configured {@link Configuration} store. + */ + public Configuration getConfiguration() { + return this.configuration; + } + + /** + * Sets the configuration store. + * + * @param configuration the configuration store + * @return the ClientOptionsBase itself. + */ + public ClientOptions setConfigurationStore(Configuration configuration) { + this.configuration = configuration; + return this; + } + + /** + * Gets the Http pipeline options. + * @return the http pipeline options. + */ + public HttpPipelineOptions getHttpPipelineOptions() { + if (this.httpPipelineOptions == null) { + this.httpPipelineOptions = new HttpPipelineOptions(); + } + return this.httpPipelineOptions; + } + + /** + * Sets the Http pipeline options. + * + * @param pipelineOptions the http pipeline options. + * @return the ClientOptionsBase itself. + */ + ClientOptions setHttpPipelineOptions(HttpPipelineOptions pipelineOptions) { + this.httpPipelineOptions = pipelineOptions; + return this; + } + + /** + * @return the Microsoft Entra endpoint to acquire tokens. + */ + public String getAuthorityHost() { + return authorityHost; + } + + /** + * Specifies the Microsoft Entra endpoint to acquire tokens. + * @param authorityHost the Microsoft Entra endpoint + * @return IdentityClientOptions + */ + public ClientOptions setAuthorityHost(String authorityHost) { + this.authorityHost = authorityHost; + return this; + } + + /** + * Specifies the ExecutorService to be used to execute the authentication requests. + * Developer is responsible for maintaining the lifecycle of the ExecutorService. + * + *

        The executor service and can be safely shutdown if the TokenCredential is no longer being used by the + * Azure SDK clients and should be shutdown before the application exits.

        + * + * @param executorService the executor service to use for executing authentication requests. + * @return IdentityClientOptions + */ + public ClientOptions setExecutorService(ExecutorService executorService) { + this.executorService = executorService; + return this; + } + + /** + * @return the ExecutorService to execute authentication requests. + */ + public ExecutorService getExecutorService() { + return executorService; + } + + /** + * Specifies the {@link TokenCachePersistenceOptions} to be used for token cache persistence. + * + * @param tokenCachePersistenceOptions the options configuration + * @return the updated identity client options + */ + public ClientOptions setTokenCacheOptions(TokenCachePersistenceOptions tokenCachePersistenceOptions) { + this.tokenCachePersistenceOptions = tokenCachePersistenceOptions; + return this; + } + + /** + * Get the configured {@link TokenCachePersistenceOptions} + * + * @return the {@link TokenCachePersistenceOptions} + */ + public TokenCachePersistenceOptions getTokenCacheOptions() { + return this.tokenCachePersistenceOptions; + } + + /** + * Disables authority validation and instance discovery. + * Instance discovery is acquiring metadata about an authority from https://login.microsoft.com + * to validate that authority. This may need to be disabled in private cloud or ADFS scenarios. + * + * @return the updated client options + */ + public ClientOptions disableInstanceDiscovery() { + this.instanceDiscovery = false; + return this; + } + + /** + * Gets the instance discovery policy. + * @return boolean indicating if instance discovery is enabled. + */ + public boolean isInstanceDiscoveryEnabled() { + return this.instanceDiscovery; + } + + /** + * Loads the details from the specified Configuration Store. + */ + private void loadFromConfiguration(Configuration configuration) { + this.configuration = configuration; + authorityHost = AzureAuthorityHosts.AZURE_PUBLIC_CLOUD; + ValidationUtil.validateAuthHost(authorityHost, LOGGER); + } + + /** + * For multi-tenant applications, specifies additional tenants for which the credential may acquire tokens. + * Add the wildcard value "*" to allow the credential to acquire tokens for any tenant the application is installed. + * + * @param additionallyAllowedTenants the additionally allowed Tenants. + * @return An updated instance of this builder with the tenant id set as specified. + */ + @SuppressWarnings("unchecked") + public ClientOptions setAdditionallyAllowedTenants(List additionallyAllowedTenants) { + this.additionallyAllowedTenants = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); + this.additionallyAllowedTenants.addAll(additionallyAllowedTenants); + return this; + } + + /** + * Internal helper method for clone. + * + * @param additionallyAllowedTenants the additionally allowed Tenants. + * @return An updated instance of this builder with the tenant id set as specified. + */ + ClientOptions setAdditionallyAllowedTenants(Set additionallyAllowedTenants) { + this.additionallyAllowedTenants = additionallyAllowedTenants; + return this; + } + + /** + * Get the Additionally Allowed Tenants. + * @return the List containing additionally allowed tenants. + */ + public Set getAdditionallyAllowedTenants() { + return this.additionallyAllowedTenants; + } + + /** + * Gets the Client ID. + * @return The Client ID. + */ + public String getClientId() { + return this.clientId; + } + + /** + * Sets the Client ID. + * @param clientId The client ID. + * @return the MsalConfigurationOptions itself. + */ + public ClientOptions setClientId(String clientId) { + this.clientId = clientId; + return this; + } + + /** + * Gets the Tenant ID. + * @return The Tenant ID. + */ + public String getTenantId() { + return this.tenantId; + } + + /** + * Sets the Tenant ID. + * @param tenantId The tenant ID. + * @return the MsalConfigurationOptions itself. + */ + public ClientOptions setTenantId(String tenantId) { + this.tenantId = tenantId; + return this; + } + + public abstract ClientOptions clone(); +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/models/ConfidentialClientOptions.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/models/ConfidentialClientOptions.java new file mode 100644 index 000000000000..0a90c35c77fd --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/models/ConfidentialClientOptions.java @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2.implementation.models; + +import io.clientcore.core.http.pipeline.HttpPipeline; + +import java.util.function.Function; + +/** + * Represents Confidential Client Options used in Confidential Client OAuth Flow . + */ +public class ConfidentialClientOptions extends ClientOptions { + private String clientSecret; + private Function clientAssertionFunction; + + /** + * Creates an instance of IdentityClientOptions with default settings. + */ + public ConfidentialClientOptions() { + super(); + } + + /** + * Gets the configured client secret. + * @return the client secret + */ + public String getClientSecret() { + return this.clientSecret; + } + + /** + * Sets the client secret + * @param clientSecret The client secret + * @return the ConfidentialClientOptions itself. + */ + public ConfidentialClientOptions setClientSecret(String clientSecret) { + this.clientSecret = clientSecret; + return this; + } + + public ConfidentialClientOptions + setClientAssertionFunction(Function clientAssertionFunction) { + this.clientAssertionFunction = clientAssertionFunction; + return this; + } + + public Function getClientAssertionFunction() { + return this.clientAssertionFunction; + } + + @Override + public ConfidentialClientOptions clone() { + ConfidentialClientOptions clone + = (ConfidentialClientOptions) new ConfidentialClientOptions().setClientSecret(this.clientSecret) + .setClientAssertionFunction(this.clientAssertionFunction) + .setClientId(this.getClientId()) + .setTenantId(this.getTenantId()) + .setHttpPipelineOptions(this.getHttpPipelineOptions().clone()) + .setExecutorService(this.getExecutorService()) + .setAuthorityHost(this.getAuthorityHost()) + .setAdditionallyAllowedTenants(this.getAdditionallyAllowedTenants()) + .setTokenCacheOptions(this.getTokenCacheOptions()); + return clone; + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/models/HttpPipelineOptions.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/models/HttpPipelineOptions.java new file mode 100644 index 000000000000..1284e3fb0dc2 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/models/HttpPipelineOptions.java @@ -0,0 +1,152 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2.implementation.models; + +import io.clientcore.core.http.client.HttpClient; +import io.clientcore.core.http.pipeline.HttpInstrumentationOptions; +import io.clientcore.core.http.pipeline.HttpPipeline; +import io.clientcore.core.http.pipeline.HttpPipelinePolicy; +import io.clientcore.core.http.pipeline.HttpRetryOptions; +import io.clientcore.core.http.pipeline.HttpRedirectOptions; + +import java.util.List; + +/** + * Represents Http Pipeline Options used when constructing the Http Pipeline. + */ +public class HttpPipelineOptions implements Cloneable { + + private HttpPipeline httpPipeline; + private HttpClient httpClient; + private HttpInstrumentationOptions httpInstrumentationOptions; + private HttpRetryOptions httpRetryOptions; + private HttpRedirectOptions httpRedirectOptions; + private List httpPipelinePolicy; + + /** + * Creates an instance of HttpOptions with default settings. + */ + public HttpPipelineOptions() { + } + + /** + * @return the HttpPipeline to send all requests + */ + public HttpPipeline getHttpPipeline() { + return httpPipeline; + } + + /** + * @return the HttpClient to use for requests + */ + public HttpClient getHttpClient() { + return httpClient; + } + + /** + * Specifies the HttpPipeline to send all requests. This setting overrides the others. + * @param httpPipeline the HttpPipeline to send all requests + * @return The HttpOptions object itself + */ + public HttpPipelineOptions setHttpPipeline(HttpPipeline httpPipeline) { + this.httpPipeline = httpPipeline; + return this; + } + + /** + * Specifies the HttpClient to send use for requests. + * @param httpClient the http client to use for requests + * @return The HttpOptions object itself + */ + public HttpPipelineOptions setHttpClient(HttpClient httpClient) { + this.httpClient = httpClient; + return this; + } + + /** + * Gets the Http Instrumentation options. + * + * @return the Http Instrumentation options. + */ + public HttpInstrumentationOptions getHttpInstrumentationOptions() { + return httpInstrumentationOptions; + } + + /** + * Sets the Http Instrumentation Options. + * + * @param httpInstrumentationOptions the Http instrumentation options to set. + */ + public HttpPipelineOptions setHttpInstrumentationOptions(HttpInstrumentationOptions httpInstrumentationOptions) { + this.httpInstrumentationOptions = httpInstrumentationOptions; + return this; + } + + /** + * Gets the Http Retry Options. + * + * @return The Http Retry Options. + */ + public HttpRetryOptions getHttpRetryOptions() { + return httpRetryOptions; + } + + /** + * Sets the Http Retry Options. + * + * @param httpRetryOptions the Http Retry Options. + */ + public HttpPipelineOptions setHttpRetryOptions(HttpRetryOptions httpRetryOptions) { + this.httpRetryOptions = httpRetryOptions; + return this; + } + + /** + * Gets the Http Redirect Options. + * + * @return The Http Redirect Options. + */ + public HttpRedirectOptions getHttpRedirectOptions() { + return httpRedirectOptions; + } + + /** + * Sets the Http Redirect Options. + * + * @param httpRedirectOptions the Http Redirect Options. + */ + public HttpPipelineOptions setHttpRedirectOptions(HttpRedirectOptions httpRedirectOptions) { + this.httpRedirectOptions = httpRedirectOptions; + return this; + } + + /** + * Gets the Http Pipeline Policy list. + * + * @return The Http Pipeline Policy List. + */ + public List getHttpPipelinePolicy() { + return httpPipelinePolicy; + } + + /** + * Adds the Http Pipeline Policy. + * + * @param httpPipelinePolicy The Http Pipeline Policy. + * @return The HttpPipelineOptions itself. + */ + public HttpPipelineOptions addHttpPipelinePolicy(HttpPipelinePolicy httpPipelinePolicy) { + this.httpPipelinePolicy.add(httpPipelinePolicy); + return this; + } + + public HttpPipelineOptions clone() { + HttpPipelineOptions clone = new HttpPipelineOptions().setHttpClient(this.httpClient) + .setHttpPipeline(this.httpPipeline) + .setHttpInstrumentationOptions(this.httpInstrumentationOptions) + .setHttpRetryOptions(this.httpRetryOptions) + .setHttpRedirectOptions(this.httpRedirectOptions); + return clone; + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/models/ManagedIdentityClientOptions.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/models/ManagedIdentityClientOptions.java new file mode 100644 index 000000000000..2f1637c34bc6 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/models/ManagedIdentityClientOptions.java @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2.implementation.models; + +/** + * Represents Managed Identity Client Options used in Managed Identity OAuth Flow . + */ +public class ManagedIdentityClientOptions extends ClientOptions { + private String resourceId; + private String objectId; + + /** + * Creates an instance of IdentityClientOptions with default settings. + */ + public ManagedIdentityClientOptions() { + super(); + } + + /** + * Gets the configured resource ID. + * @return the client secret + */ + public String getResourceId() { + return this.resourceId; + } + + /** + * Sets the resource ID. + * @param resourceId The resource ID + * @return the ConfidentialClientOptions itself. + */ + public ManagedIdentityClientOptions setResourceId(String resourceId) { + this.resourceId = resourceId; + return this; + } + + /** + * Gets the configured object ID. + * @return the client secret + */ + public String getObjectId() { + return this.objectId; + } + + /** + * Sets the object ID. + * @param objectId The object ID + * @return the ConfidentialClientOptions itself. + */ + public ManagedIdentityClientOptions setObjectId(String objectId) { + this.objectId = objectId; + return this; + } + + @Override + public ManagedIdentityClientOptions clone() { + ManagedIdentityClientOptions clone + = (ManagedIdentityClientOptions) new ManagedIdentityClientOptions().setResourceId(resourceId) + .setObjectId(objectId) + .setClientId(this.getClientId()) + .setTenantId(this.getTenantId()) + .setHttpPipelineOptions(this.getHttpPipelineOptions().clone()) + .setExecutorService(this.getExecutorService()) + .setAuthorityHost(this.getAuthorityHost()) + .setAdditionallyAllowedTenants(this.getAdditionallyAllowedTenants()) + .setTokenCacheOptions(this.getTokenCacheOptions()); + return clone; + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/models/MsalAuthenticationAccount.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/models/MsalAuthenticationAccount.java new file mode 100644 index 000000000000..7faa61c2c726 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/models/MsalAuthenticationAccount.java @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2.implementation.models; + +import com.azure.identity.v2.AuthenticationRecord; +import com.microsoft.aad.msal4j.IAccount; +import com.microsoft.aad.msal4j.ITenantProfile; + +import java.util.Map; + +public class MsalAuthenticationAccount implements IAccount { + private static final long serialVersionUID = 7563908089175663756L; + private transient AuthenticationRecord authenticationRecord; + private Map tenantProfiles; + private String homeAccountId; + private String environment; + private String username; + + public MsalAuthenticationAccount(AuthenticationRecord authenticationRecord) { + this.authenticationRecord = authenticationRecord; + this.homeAccountId = authenticationRecord.getHomeAccountId(); + this.environment = authenticationRecord.getAuthority(); + this.username = authenticationRecord.getUsername(); + } + + public MsalAuthenticationAccount(AuthenticationRecord authenticationRecord, + Map tenantProfiles) { + this.authenticationRecord = authenticationRecord; + this.tenantProfiles = tenantProfiles; + this.homeAccountId = authenticationRecord.getHomeAccountId(); + this.environment = authenticationRecord.getAuthority(); + this.username = authenticationRecord.getUsername(); + } + + @Override + public String homeAccountId() { + return homeAccountId; + } + + @Override + public String environment() { + return environment; + } + + @Override + public String username() { + return username; + } + + @Override + public Map getTenantProfiles() { + return tenantProfiles; + } + + public AuthenticationRecord getAuthenticationRecord() { + return authenticationRecord; + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/models/MsalToken.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/models/MsalToken.java new file mode 100644 index 000000000000..8eabbf99e54c --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/models/MsalToken.java @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2.implementation.models; + +import com.microsoft.aad.msal4j.IAccount; +import com.microsoft.aad.msal4j.IAuthenticationResult; +import io.clientcore.core.credentials.oauth.AccessToken; +import io.clientcore.core.credentials.oauth.AccessTokenType; + +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; + +/** + * Type representing authentication result from the MSAL (Microsoft Authentication Library). + */ +public final class MsalToken extends AccessToken { + + private IAuthenticationResult authenticationResult; + + /** + * Creates an access token instance. + * + * @param authenticationResult the raw authentication result returned by MSAL + */ + public MsalToken(IAuthenticationResult authenticationResult) { + super(authenticationResult.accessToken(), + OffsetDateTime.ofInstant(authenticationResult.expiresOnDate().toInstant(), ZoneOffset.UTC), + authenticationResult.metadata() != null + ? authenticationResult.metadata().refreshOn() == null + ? null + : OffsetDateTime.ofInstant(Instant.ofEpochSecond(authenticationResult.metadata().refreshOn()), + ZoneOffset.UTC) + : null); + this.authenticationResult = authenticationResult; + } + + public MsalToken(IAuthenticationResult msalResult, String tokenType) { + super(msalResult.accessToken(), + OffsetDateTime.ofInstant(msalResult.expiresOnDate().toInstant(), ZoneOffset.UTC), + msalResult.metadata() != null + ? msalResult.metadata().refreshOn() == null + ? null + : OffsetDateTime.ofInstant(Instant.ofEpochSecond(msalResult.metadata().refreshOn()), ZoneOffset.UTC) + : null, + AccessTokenType.fromString(tokenType)); + authenticationResult = msalResult; + } + + /** + * @return the signed in account + */ + public IAccount getAccount() { + return authenticationResult.account(); + } + + /** + * Get the MSAL Authentication result. + * + * @return the authentication result. + */ + public IAuthenticationResult getAuthenticationResult() { + return authenticationResult; + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/models/OidcTokenResponse.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/models/OidcTokenResponse.java new file mode 100644 index 000000000000..08afb307331d --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/models/OidcTokenResponse.java @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2.implementation.models; + +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonSerializable; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.serialization.json.JsonWriter; + +import java.io.IOException; + +public class OidcTokenResponse implements JsonSerializable { + private String oidcToken; + + public String getOidcToken() { + return oidcToken; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject().writeStringField("oidcToken", oidcToken).writeEndObject(); + } + + public static OidcTokenResponse fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OidcTokenResponse oidcTokenResponse = new OidcTokenResponse(); + while (JsonToken.END_OBJECT != reader.nextToken()) { + String fieldName = reader.getFieldName(); + if ("oidcToken".equals(fieldName)) { + oidcTokenResponse.oidcToken = reader.getString(); + } else { + reader.skipChildren(); + } + } + return oidcTokenResponse; + }); + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/models/PublicClientOptions.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/models/PublicClientOptions.java new file mode 100644 index 000000000000..fe2c3a4fc524 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/models/PublicClientOptions.java @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2.implementation.models; + +import com.azure.identity.v2.AuthenticationRecord; +import com.azure.identity.v2.BrowserCustomizationOptions; + +/** + * Options to configure the IdentityClient. + */ +public class PublicClientOptions extends ClientOptions { + private BrowserCustomizationOptions browserCustomizationOptions; + private AuthenticationRecord authenticationRecord; + + /** + * Creates an instance of IdentityClientOptions with default settings. + */ + public PublicClientOptions() { + super(); + this.browserCustomizationOptions = new BrowserCustomizationOptions(); + } + + /** + * Gets the configured client secret. + * + * @return the browser customization options + */ + public BrowserCustomizationOptions getBrowserCustomizationOptions() { + return this.browserCustomizationOptions; + } + + /** + * Sets the browser customization options for {@link com.azure.identity.v2.InteractiveBrowserCredential} authentication. + * + * @param browserCustomizationOptions The browser customization options + * @return the ConfidentialClientOptions itself. + */ + public PublicClientOptions setBrowserCustomizationOptions(BrowserCustomizationOptions browserCustomizationOptions) { + this.browserCustomizationOptions = browserCustomizationOptions; + return this; + } + + /** + * Sets the {@link AuthenticationRecord} captured from a previous authentication. + * + * @param authenticationRecord The Authentication record to be configured. + * + * @return An updated instance of this builder with the configured authentication record. + */ + public PublicClientOptions setAuthenticationRecord(AuthenticationRecord authenticationRecord) { + this.authenticationRecord = authenticationRecord; + return this; + } + + /** + * Get the configured {@link AuthenticationRecord}. + * + * @return {@link AuthenticationRecord}. + */ + public AuthenticationRecord getAuthenticationRecord() { + return authenticationRecord; + } + + public PublicClientOptions clone() { + PublicClientOptions clone = (PublicClientOptions) new PublicClientOptions() + .setBrowserCustomizationOptions(browserCustomizationOptions) + .setClientId(this.getClientId()) + .setTenantId(this.getTenantId()) + .setHttpPipelineOptions(this.getHttpPipelineOptions().clone()) + .setExecutorService(this.getExecutorService()) + .setAuthorityHost(this.getAuthorityHost()) + .setAdditionallyAllowedTenants(this.getAdditionallyAllowedTenants()) + .setTokenCacheOptions(this.getTokenCacheOptions()); + return clone; + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/models/package-info.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/models/package-info.java new file mode 100644 index 000000000000..24c5b4574bfb --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/models/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing model classes for credentials and clients + */ +package com.azure.identity.v2.implementation.models; diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/util/IdentityConstants.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/util/IdentityConstants.java new file mode 100644 index 000000000000..fab3130157b0 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/util/IdentityConstants.java @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2.implementation.util; + +public class IdentityConstants { + /** + * The Single Sign On ID. + */ + public static final String DEVELOPER_SINGLE_SIGN_ON_ID = "04b07795-8ddb-461a-bbee-02f9e1bf7b46"; + + /** + * The default IMDS authentication endpoint. + */ + public static final String DEFAULT_IMDS_ENDPOINT = "http://169.254.169.254"; + + public static final String DEFAULT_IMDS_TOKENPATH = "/metadata/identity/oauth2/token"; +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/util/IdentityUtil.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/util/IdentityUtil.java new file mode 100644 index 000000000000..a2b4446cd51c --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/util/IdentityUtil.java @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2.implementation.util; + +import com.azure.identity.v2.BrowserCustomizationOptions; +import com.azure.identity.v2.implementation.models.ClientOptions; +import com.azure.v2.core.credentials.TokenRequestContext; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.utils.CoreUtils; + +import java.io.IOException; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import static io.clientcore.core.serialization.json.JsonToken.END_OBJECT; + +public final class IdentityUtil { + private static final ClientLogger LOGGER = new ClientLogger(IdentityUtil.class); + public static final String ALL_TENANTS = "*"; + public static final String DEFAULT_TENANT = "organizations"; + public static final HttpHeaderName X_TFS_FED_AUTH_REDIRECT = HttpHeaderName.fromString("X-TFS-FedAuthRedirect"); + public static final HttpHeaderName X_VSS_E2EID = HttpHeaderName.fromString("x-vss-e2eid"); + public static final HttpHeaderName X_MSEDGE_REF = HttpHeaderName.fromString("x-msedge-ref"); + + private IdentityUtil() { + } + + /** + * Resolve the Tenant Id to be used in the authentication requests. + * @param currentTenantId the current tenant Id. + * @param requestContext the user passed in {@link TokenRequestContext} + * @param options the identity client options bag. + * on the credential or not. + */ + public static String resolveTenantId(String currentTenantId, TokenRequestContext requestContext, + ClientOptions options) { + + String contextTenantId = requestContext.getTenantId(); + + if (contextTenantId != null && currentTenantId != null && !currentTenantId.equalsIgnoreCase(contextTenantId)) { + + String resolvedTenantId = CoreUtils.isNullOrEmpty(contextTenantId) ? currentTenantId : contextTenantId; + + return resolvedTenantId; + } + return currentTenantId; + } + + public static List resolveAdditionalTenants(List additionallyAllowedTenants) { + if (additionallyAllowedTenants == null) { + return Collections.emptyList(); + } + + if (additionallyAllowedTenants.contains(ALL_TENANTS)) { + return Collections.singletonList(ALL_TENANTS); + } + + return additionallyAllowedTenants; + } + + /** + * Parses the "access_token" field out of a response body. + * @param json the response body to parse. + * @return the access_token value + * @throws IOException + */ + public static String getAccessToken(String json) throws IOException { + try (JsonReader jsonReader = JsonReader.fromString(json)) { + return jsonReader.readObject(reader -> { + while (reader.nextToken() != END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("access_token".equals(fieldName)) { + return reader.getString(); + } + } + return null; + }); + } + } + + /** + * Parses a json string into a key:value map. Doesn't do anything smart for nested objects or arrays. + * @param json + * @return a map of the json fields + * @throws IOException + */ + public static Map parseJsonIntoMap(String json) throws IOException { + try (JsonReader jsonReader = JsonReader.fromString(json)) { + + return jsonReader.readObject(reader -> jsonReader.readMap(mapReader -> { + if (mapReader.currentToken() == JsonToken.START_ARRAY + || mapReader.currentToken() == JsonToken.START_OBJECT) { + return mapReader.readChildren(); + } else { + return mapReader.getString(); + } + })); + } + } + + public static boolean isWindowsPlatform() { + return System.getProperty("os.name").contains("Windows"); + } + + public static boolean isLinuxPlatform() { + return System.getProperty("os.name").contains("Linux"); + } + + public static boolean isMacPlatform() { + return System.getProperty("os.name").contains("Mac"); + } + + public static boolean browserCustomizationOptionsPresent(BrowserCustomizationOptions browserCustomizationOptions) { + return !CoreUtils.isNullOrEmpty(browserCustomizationOptions.getErrorMessage()) + || !CoreUtils.isNullOrEmpty(browserCustomizationOptions.getSuccessMessage()); + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/util/LoggingUtil.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/util/LoggingUtil.java new file mode 100644 index 000000000000..bf26c35cc840 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/util/LoggingUtil.java @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2.implementation.util; + +import com.azure.identity.v2.CredentialUnavailableException; +import com.azure.v2.core.credentials.TokenRequestContext; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.instrumentation.logging.LogLevel; +import io.clientcore.core.utils.CoreUtils; + +import java.util.function.Supplier; + +/** + * Utilities to handle logging for credentials. + */ +public final class LoggingUtil { + /** + * Log a success message for a getToken() call. + * @param logger the logger to output the log message + * @param context the context of the getToken() request + */ + public static void logTokenSuccess(ClientLogger logger, TokenRequestContext context) { + logger.atLevel(LogLevel.VERBOSE) + .log(String.format("Azure Identity => SUCCESS getToken() result for scopes [%s]", + CoreUtils.stringJoin(", ", context.getScopes()))); + } + + /** + * Log an error message for a getToken() call. + * @param logger the logger to output the log message + * @param context the context of the getToken() request + * @param error the error thrown during getToken() + */ + public static void logTokenError(ClientLogger logger, TokenRequestContext context, Throwable error) { + logger.atLevel(LogLevel.ERROR) + .log(String.format("Azure Identity => ERROR in getToken() call for scopes [%s]: %s", + CoreUtils.stringJoin(", ", context.getScopes()), error == null ? "" : error.getMessage())); + } + + private LoggingUtil() { + } + + public static CredentialUnavailableException logCredentialUnavailableException(ClientLogger logger, + CredentialUnavailableException exception) { + throw logger.logThrowableAsError(exception); + } + + public static void logError(ClientLogger logger, String message) { + logger.atLevel(LogLevel.ERROR).log(message); + } + + public static void logError(ClientLogger logger, Supplier messageSupplier) { + logger.atLevel(LogLevel.ERROR).log(messageSupplier.get()); + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/util/ScopeUtil.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/util/ScopeUtil.java new file mode 100644 index 000000000000..3b678f51a969 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/util/ScopeUtil.java @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2.implementation.util; + +import java.util.List; +import java.util.Objects; +import java.util.regex.Pattern; + +/** + * Utilities to convert between scopes and resources for connecting to Microsoft Entra ID. + */ +public final class ScopeUtil { + + private static final String DEFAULT_SUFFIX = "/.default"; + private static final Pattern SCOPE_PATTERN = Pattern.compile("^[0-9a-zA-Z-.:/]+$"); + + /** + * Convert a list of scopes to a resource for Microsoft Entra ID. + * @param scopes the list of scopes to authenticate to + * @return the resource to authenticate with Microsoft Entra ID. + * @throws IllegalArgumentException if scopes is empty or has more than 1 items + */ + public static String scopesToResource(List scopes) { + Objects.requireNonNull(scopes); + if (scopes.size() != 1) { + throw new IllegalArgumentException( + "To convert to a resource string the specified array must be exactly length 1"); + } + + if (!scopes.get(0).endsWith(DEFAULT_SUFFIX)) { + return scopes.get(0); + } + + return scopes.get(0).substring(0, scopes.get(0).lastIndexOf(DEFAULT_SUFFIX)); + } + + /** + * Convert a resource to a list of scopes. + * @param resource the resource for Microsoft Entra ID + * @return the list of scopes + */ + public static String[] resourceToScopes(String resource) { + Objects.requireNonNull(resource); + return new String[] { resource + DEFAULT_SUFFIX }; + } + + /** + * Validate the format of the input scope. + * @param scope the scope input + * @throws IllegalArgumentException if a scope with invalid format is provided. + */ + public static void validateScope(String scope) { + boolean isScopeMatch = SCOPE_PATTERN.matcher(scope).matches(); + + if (!isScopeMatch) { + throw new IllegalArgumentException("The specified scope is not in expected format." + + " Only alphanumeric characters, '.', '-', ':', and '/' are allowed"); + } + } + + private ScopeUtil() { + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/util/ValidationUtil.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/util/ValidationUtil.java new file mode 100644 index 000000000000..319d5ce391f3 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/util/ValidationUtil.java @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2.implementation.util; + +import com.azure.identity.v2.implementation.models.ManagedIdentityClientOptions; +import io.clientcore.core.instrumentation.logging.ClientLogger; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; + +/** + * Utility class for validating parameters. + */ +public final class ValidationUtil { + + public static void validate(String className, ClientLogger logger, List names, List values) { + String missing = ""; + + for (int i = 0; i < values.size(); i++) { + if (values.get(i) == null) { + missing += missing.isEmpty() ? names.get(i) : ", " + names.get(i); + } + } + + if (!missing.isEmpty()) { + throw logger.logThrowableAsWarning(new IllegalArgumentException( + "Must provide non-null values for " + missing + " properties in " + className)); + } + } + + public static void validate(ClientLogger logger, String param1Name, Object param1, String param2Name, + Object param2) { + String missing = ""; + + if (param1 == null) { + missing += param1Name; + } + + if (param2 == null) { + missing += missing.isEmpty() ? param2Name : ", " + param2Name; + } + + if (!missing.isEmpty()) { + throw logger.logThrowableAsWarning( + new IllegalArgumentException("Must provide non-null values for " + missing + " properties.")); + } + } + + public static void validate(ClientLogger logger, String param1Name, Object param1, String param2Name, Object param2, + String param3Name, Object param3) { + String missing = ""; + + if (param1 == null) { + missing += param1Name; + } + + if (param2 == null) { + missing += missing.isEmpty() ? param2Name : ", " + param2Name; + } + + if (param3 == null) { + missing += missing.isEmpty() ? param3Name : ", " + param3Name; + } + + if (!missing.isEmpty()) { + throw logger.logThrowableAsWarning( + new IllegalArgumentException("Must provide non-null values for " + missing + " properties.")); + } + } + + public static void validateAuthHost(String authHost, ClientLogger logger) { + try { + new URI(authHost); + } catch (URISyntaxException e) { + throw logger + .logThrowableAsError(new IllegalArgumentException("Must provide a valid URI for authority host.", e)); + } + if (!authHost.startsWith("https")) { + throw logger.logThrowableAsError(new IllegalArgumentException("Authority host must use https scheme.")); + } + } + + public static void validateTenantIdCharacterRange(String id, ClientLogger logger) { + if (id != null) { + for (int i = 0; i < id.length(); i++) { + if (!isValidTenantCharacter(id.charAt(i))) { + throw logger.logThrowableAsError(new IllegalArgumentException( + "Invalid tenant id provided. You can locate your tenant id by following the instructions" + + " listed here: https://learn.microsoft.com/partner-center/find-ids-and-domain-names")); + } + } + } + } + + public static void validateInteractiveBrowserRedirectUrlSetup(Integer port, String redirectUrl, + ClientLogger logger) { + if (port != null && redirectUrl != null) { + throw logger.logThrowableAsError( + new IllegalArgumentException("Port and Redirect URL cannot be configured at the same time. " + + "Port is deprecated now. Use the redirectUrl setter to specify" + + " the redirect URL on the builder.")); + } + } + + private static boolean isValidTenantCharacter(char c) { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c == '.') || (c == '-'); + } + + public static void validateManagedIdentityIdParams(ManagedIdentityClientOptions miClientOptions, + ClientLogger logger) { + + String clientId = miClientOptions.getClientId(); + String objectId = miClientOptions.getObjectId(); + String resourceId = miClientOptions.getResourceId(); + + int nonNullIdCount = 0; + + if (clientId != null) { + nonNullIdCount++; + } + if (resourceId != null) { + nonNullIdCount++; + } + if (objectId != null) { + nonNullIdCount++; + } + + if (nonNullIdCount > 1) { + throw logger.logThrowableAsError( + new IllegalStateException("Only one of clientId, resourceId, or objectId can be specified.")); + } + } +} diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/util/package-info.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/util/package-info.java new file mode 100644 index 000000000000..4dcaf011c1d7 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/implementation/util/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing utility classes for credentials and clients + */ +package com.azure.identity.v2.implementation.util; diff --git a/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/package-info.java b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/package-info.java new file mode 100644 index 000000000000..dc55d4184e7a --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/java/com/azure/identity/v2/package-info.java @@ -0,0 +1,14 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + *

        The Azure Identity library provides + * Microsoft Entra ID token + * authentication support across the + * Azure SDK. The library focuses on + * OAuth authentication with Microsoft Entra ID, and it offers various credential classes capable of acquiring a Microsoft Entra token + * to authenticate service requests. All the credential classes in this package are implementations of the + * TokenCredential interface offered by azure-core, and any of them can be used to construct service clients capable + * of authenticating with a TokenCredential.

        + */ +package com.azure.identity.v2; diff --git a/sdk/identity/azure-identity-v2/src/main/module-info.java b/sdk/identity/azure-identity-v2/src/main/module-info.java new file mode 100644 index 000000000000..56d199a3b344 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/main/module-info.java @@ -0,0 +1,12 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +module com.azure.identity { + requires transitive com.azure.core; + + requires com.microsoft.aad.msal4j; + requires msal4j.persistence.extension; + requires java.xml; + + exports com.azure.identity.v2; +} diff --git a/sdk/identity/azure-identity-v2/src/test/java/com/azure/identity/v2/AzurePipelinesCredentialBuilderTest.java b/sdk/identity/azure-identity-v2/src/test/java/com/azure/identity/v2/AzurePipelinesCredentialBuilderTest.java new file mode 100644 index 000000000000..01bfdfc066e2 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/test/java/com/azure/identity/v2/AzurePipelinesCredentialBuilderTest.java @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2; + +import io.clientcore.core.utils.configuration.Configuration; +import io.clientcore.core.utils.configuration.ConfigurationSource; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class AzurePipelinesCredentialBuilderTest { + + @Test + public void testRequiredParameters() { + // setup + String clientId = "clientId"; + String tenantId = "tenantId"; + String serviceConnectionId = "serviceConnectionId"; + String systemAccessToken = "FakeToken"; + Configuration configuration = new Configuration(new ConfigurationSource() { + @Override + public String getProperty(String name) { + return null; + } + + @Override + public boolean isMutable() { + return false; + } + }); + + // test + assertThrows(IllegalArgumentException.class, () -> new AzurePipelinesCredentialBuilder().build()); + + // This assert validates the one required parameter from the environment, SYSTEM_OIDCREQUESTURI, exists. + assertThrows(IllegalArgumentException.class, + () -> new AzurePipelinesCredentialBuilder().clientId(clientId) + .tenantId(tenantId) + .serviceConnectionId(serviceConnectionId) + .systemAccessToken(systemAccessToken) + .configuration(configuration) + .build()); + } +} diff --git a/sdk/identity/azure-identity-v2/src/test/java/com/azure/identity/v2/ClientSecretCredentialTest.java b/sdk/identity/azure-identity-v2/src/test/java/com/azure/identity/v2/ClientSecretCredentialTest.java new file mode 100644 index 000000000000..58ec532f035d --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/test/java/com/azure/identity/v2/ClientSecretCredentialTest.java @@ -0,0 +1,195 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2; + +import com.azure.identity.v2.implementation.client.ConfidentialClient; +import com.azure.identity.v2.util.TestUtils; +import com.azure.v2.core.credentials.TokenRequestContext; +import com.microsoft.aad.msal4j.MsalServiceException; +import io.clientcore.core.credentials.oauth.AccessToken; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.MockedConstruction; +import org.mockito.exceptions.misusing.InvalidUseOfMatchersException; + +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.when; + +public class ClientSecretCredentialTest { + + private static final String TENANT_ID = "contoso.com"; + private static final String CLIENT_ID = UUID.randomUUID().toString(); + + @Test + public void testValidSecrets() throws Exception { + // setup + String secret = "secret"; + String token1 = "token1"; + String token2 = "token2"; + TokenRequestContext request1 = new TokenRequestContext().addScopes("https://management.azure.com"); + TokenRequestContext request2 = new TokenRequestContext().addScopes("https://vault.azure.net"); + OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); + + // mock + try (MockedConstruction identityClientMock + = mockConstruction(ConfidentialClient.class, (identitySyncClient, context) -> { + when(identitySyncClient.authenticateWithCache(any())).thenThrow(new IllegalStateException("Test")); + when(identitySyncClient.authenticate(request1)) + .thenReturn(TestUtils.getMockAccessToken(token1, expiresAt)); + when(identitySyncClient.authenticate(request2)) + .thenReturn(TestUtils.getMockAccessToken(token2, expiresAt)); + })) { + // test + ClientSecretCredential credential = new ClientSecretCredentialBuilder().tenantId(TENANT_ID) + .clientId(CLIENT_ID) + .clientSecret(secret) + .additionallyAllowedTenants("*") + .build(); + + AccessToken accessToken = credential.getToken(request1); + Assertions.assertEquals(token1, accessToken.getToken()); + Assertions.assertTrue(expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()); + + accessToken = credential.getToken(request2); + Assertions.assertEquals(token2, accessToken.getToken()); + Assertions.assertTrue(expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()); + Assertions.assertNotNull(identityClientMock); + } + } + + @Test + public void testValidSecretsCAE() throws Exception { + // setup + String secret = "secret"; + String token1 = "token1"; + String token2 = "token2"; + TokenRequestContext request1 + = new TokenRequestContext().addScopes("https://management.azure.com").setCaeEnabled(true); + TokenRequestContext request2 + = new TokenRequestContext().addScopes("https://vault.azure.net").setCaeEnabled(true); + OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); + + // mock + try (MockedConstruction identityClientMock + = mockConstruction(ConfidentialClient.class, (identitySyncClient, context) -> { + when(identitySyncClient.authenticateWithCache(any())).thenThrow(new IllegalStateException("Test")); + when(identitySyncClient.authenticate(request1)).thenAnswer(invocation -> { + TokenRequestContext argument = (TokenRequestContext) invocation.getArguments()[0]; + if (argument.getScopes().size() == 1 && argument.isCaeEnabled()) { + return TestUtils.getMockMsalToken(token1, expiresAt); + } else { + throw new InvalidUseOfMatchersException( + String.format("Argument %s does not match", (Object) argument)); + } + }); + when(identitySyncClient.authenticate(request2)).thenAnswer(invocation -> { + TokenRequestContext argument = (TokenRequestContext) invocation.getArguments()[0]; + if (argument.getScopes().size() == 1 && argument.isCaeEnabled()) { + return TestUtils.getMockMsalToken(token2, expiresAt); + } else { + throw new InvalidUseOfMatchersException( + String.format("Argument %s does not match", (Object) argument)); + } + }); + })) { + // test + ClientSecretCredential credential = new ClientSecretCredentialBuilder().tenantId(TENANT_ID) + .clientId(CLIENT_ID) + .clientSecret(secret) + .additionallyAllowedTenants("*") + .build(); + + AccessToken accessToken = credential.getToken(request1); + Assertions.assertEquals(token1, accessToken.getToken()); + Assertions.assertTrue(expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()); + + accessToken = credential.getToken(request2); + Assertions.assertEquals(token2, accessToken.getToken()); + Assertions.assertTrue(expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()); + Assertions.assertNotNull(identityClientMock); + } + } + + @Test + public void testInvalidSecrets() throws Exception { + // setup + String secret = "secret"; + String badSecret = "badsecret"; + String token1 = "token1"; + TokenRequestContext request = new TokenRequestContext().addScopes("https://management.azure.com"); + + try (MockedConstruction identityClientMock + = mockConstruction(ConfidentialClient.class, (confidentialClient, context) -> { + when(confidentialClient.authenticateWithCache(any())).thenThrow(new IllegalStateException("Test")); + when(confidentialClient.authenticate(request)) + .thenThrow(new MsalServiceException("bad secret", "BadSecret")); + })) { + // test + ClientSecretCredential credential = new ClientSecretCredentialBuilder().tenantId(TENANT_ID) + .clientId(CLIENT_ID) + .clientSecret(badSecret) + .additionallyAllowedTenants("*") + .build(); + try { + credential.getToken(request); + } catch (Exception e) { + Assertions + .assertTrue(e instanceof CredentialAuthenticationException && "bad secret".equals(e.getMessage())); + } + Assertions.assertNotNull(identityClientMock); + } + } + + @Test + public void testInvalidParameters() throws Exception { + // setup + String secret = "secret"; + String token1 = "token1"; + TokenRequestContext request = new TokenRequestContext().addScopes("https://management.azure.com"); + OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); + + // mock + try (MockedConstruction identityClientMock + = mockConstruction(ConfidentialClient.class, (identityClient, context) -> { + when(identityClient.authenticateWithCache(any())).thenReturn(null); + when(identityClient.authenticate(request)).thenReturn(TestUtils.getMockAccessToken(token1, expiresOn)); + })) { + // test + try { + new ClientSecretCredentialBuilder().clientId(CLIENT_ID) + .clientSecret(secret) + .additionallyAllowedTenants("*") + .build(); + fail(); + } catch (IllegalArgumentException e) { + Assertions.assertTrue(e.getMessage().contains("tenantId")); + } + try { + new ClientSecretCredentialBuilder().tenantId(TENANT_ID) + .clientSecret(secret) + .additionallyAllowedTenants("*") + .build(); + fail(); + } catch (IllegalArgumentException e) { + Assertions.assertTrue(e.getMessage().contains("clientId")); + } + try { + new ClientSecretCredentialBuilder().tenantId(TENANT_ID) + .clientId(CLIENT_ID) + .additionallyAllowedTenants("*") + .build(); + fail(); + } catch (IllegalArgumentException e) { + Assertions.assertTrue(e.getMessage().contains("clientSecret")); + } + Assertions.assertNotNull(identityClientMock); + } + } +} diff --git a/sdk/identity/azure-identity-v2/src/test/java/com/azure/identity/v2/InteractiveBrowserCredentialTest.java b/sdk/identity/azure-identity-v2/src/test/java/com/azure/identity/v2/InteractiveBrowserCredentialTest.java new file mode 100644 index 000000000000..5229c4d21b01 --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/test/java/com/azure/identity/v2/InteractiveBrowserCredentialTest.java @@ -0,0 +1,240 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2; + +import com.azure.identity.v2.implementation.client.PublicClient; +import com.azure.identity.v2.util.TestUtils; +import com.azure.v2.core.credentials.TokenRequestContext; +import io.clientcore.core.credentials.oauth.AccessToken; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.MockedConstruction; +import org.mockito.exceptions.misusing.InvalidUseOfMatchersException; + +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Random; +import java.util.UUID; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.when; + +public class InteractiveBrowserCredentialTest { + + private static final String CLIENT_ID = UUID.randomUUID().toString(); + + @Test + public void testValidInteractive() throws Exception { + Random random = new Random(); + + // setup + String token1 = "token1"; + String token2 = "token2"; + TokenRequestContext request1 = new TokenRequestContext().addScopes("https://management.azure.com"); + TokenRequestContext request2 = new TokenRequestContext().addScopes("https://vault.azure.net"); + OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); + int port = random.nextInt(10000) + 10000; + + // mock + + try (MockedConstruction identityClientMock + = mockConstruction(PublicClient.class, (identitySyncClient, context) -> { + when(identitySyncClient.authenticateWithBrowserInteraction(eq(request1), eq(port), eq(null), eq(null))) + .thenReturn(TestUtils.getMockMsalToken(token1, expiresAt)); + when(identitySyncClient.authenticateWithPublicClientCache(any(), any())).thenAnswer(invocation -> { + TokenRequestContext argument = (TokenRequestContext) invocation.getArguments()[0]; + if (argument.getScopes().size() == 1 + && argument.getScopes().get(0).equals(request2.getScopes().get(0))) { + return TestUtils.getMockMsalToken(token2, expiresAt); + } else if (argument.getScopes().size() == 1 + && argument.getScopes().get(0).equals(request1.getScopes().get(0))) { + throw new UnsupportedOperationException("nothing cached"); + } else { + throw new InvalidUseOfMatchersException( + String.format("Argument %s does not match", (Object) argument)); + } + }); + })) { + // test + InteractiveBrowserCredential credential + = new InteractiveBrowserCredentialBuilder().port(port).clientId(CLIENT_ID).build(); + AccessToken accessToken = credential.getToken(request1); + Assertions.assertEquals(token1, accessToken.getToken()); + Assertions.assertTrue(expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()); + accessToken = credential.getToken(request2); + Assertions.assertEquals(token2, accessToken.getToken()); + Assertions.assertTrue(expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()); + Assertions.assertNotNull(identityClientMock); + } + } + + @Test + public void testValidInteractiveCAE() throws Exception { + Random random = new Random(); + + // setup + String token1 = "token1"; + String token2 = "token2"; + TokenRequestContext request1 + = new TokenRequestContext().addScopes("https://management.azure.com").setCaeEnabled(true); + TokenRequestContext request2 + = new TokenRequestContext().addScopes("https://vault.azure.net").setCaeEnabled(true); + OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); + int port = random.nextInt(10000) + 10000; + + try (MockedConstruction identityClientMock + = mockConstruction(PublicClient.class, (publicClient, context) -> { + when(publicClient.authenticateWithBrowserInteraction(eq(request1), eq(port), eq(null), eq(null))) + .thenReturn(TestUtils.getMockMsalToken(token1, expiresAt)); + when(publicClient.authenticateWithPublicClientCache(any(), any())).thenAnswer(invocation -> { + TokenRequestContext argument = (TokenRequestContext) invocation.getArguments()[0]; + if (argument.getScopes().size() == 1 + && argument.getScopes().get(0).equals(request2.getScopes().get(0)) + && argument.isCaeEnabled()) { + return TestUtils.getMockMsalToken(token2, expiresAt); + } else if (argument.getScopes().size() == 1 + && argument.getScopes().get(0).equals(request1.getScopes().get(0))) { + throw new UnsupportedOperationException("nothing cached"); + } else { + throw new InvalidUseOfMatchersException( + String.format("Argument %s does not match", (Object) argument)); + } + }); + })) { + // test + InteractiveBrowserCredential credential + = new InteractiveBrowserCredentialBuilder().port(port).clientId(CLIENT_ID).build(); + AccessToken accessToken = credential.getToken(request1); + Assertions.assertEquals(token1, accessToken.getToken()); + Assertions.assertTrue(expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()); + accessToken = credential.getToken(request2); + Assertions.assertEquals(token2, accessToken.getToken()); + Assertions.assertTrue(expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()); + Assertions.assertNotNull(identityClientMock); + } + } + + @Test + public void testValidInteractiveViaRedirectUri() throws Exception { + // setup + String token1 = "token1"; + String token2 = "token2"; + TokenRequestContext request1 = new TokenRequestContext().addScopes("https://management.azure.com"); + TokenRequestContext request2 = new TokenRequestContext().addScopes("https://vault.azure.net"); + OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); + String redirectUrl = "http://localhost:3761"; + + try (MockedConstruction identityClientMock + = mockConstruction(PublicClient.class, (identitySyncClient, context) -> { + when(identitySyncClient.authenticateWithBrowserInteraction(eq(request1), eq(null), eq(redirectUrl), + eq(null))).thenReturn(TestUtils.getMockMsalToken(token1, expiresAt)); + when(identitySyncClient.authenticateWithPublicClientCache(any(), any())).thenAnswer(invocation -> { + TokenRequestContext argument = (TokenRequestContext) invocation.getArguments()[0]; + if (argument.getScopes().size() == 1 + && argument.getScopes().get(0).equals(request2.getScopes().get(0))) { + return TestUtils.getMockMsalToken(token2, expiresAt); + } else if (argument.getScopes().size() == 1 + && argument.getScopes().get(0).equals(request1.getScopes().get(0))) { + throw new UnsupportedOperationException("nothing cached"); + } else { + throw new InvalidUseOfMatchersException( + String.format("Argument %s does not match", (Object) argument)); + } + }); + })) { + // test + InteractiveBrowserCredential credential + = new InteractiveBrowserCredentialBuilder().redirectUrl(redirectUrl).clientId(CLIENT_ID).build(); + AccessToken accessToken = credential.getToken(request1); + Assertions.assertEquals(token1, accessToken.getToken()); + Assertions.assertTrue(expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()); + accessToken = credential.getToken(request2); + Assertions.assertEquals(token2, accessToken.getToken()); + Assertions.assertTrue(expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()); + Assertions.assertNotNull(identityClientMock); + } + } + + @Test + public void testValidInteractiveWithLoginHint() throws Exception { + // setup + String token1 = "token1"; + String token2 = "token2"; + TokenRequestContext request1 = new TokenRequestContext().addScopes("https://management.azure.com"); + TokenRequestContext request2 = new TokenRequestContext().addScopes("https://vault.azure.net"); + OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); + String username = "user@foo.com"; + + // mock + try (MockedConstruction identityClientMock + = mockConstruction(PublicClient.class, (identitySyncClient, context) -> { + when(identitySyncClient.authenticateWithBrowserInteraction(eq(request1), eq(null), eq(null), + eq(username))).thenReturn(TestUtils.getMockMsalToken(token1, expiresAt)); + when(identitySyncClient.authenticateWithPublicClientCache(any(), any())).thenAnswer(invocation -> { + TokenRequestContext argument = (TokenRequestContext) invocation.getArguments()[0]; + if (argument.getScopes().size() == 1 + && argument.getScopes().get(0).equals(request2.getScopes().get(0))) { + return TestUtils.getMockMsalToken(token2, expiresAt); + } else if (argument.getScopes().size() == 1 + && argument.getScopes().get(0).equals(request1.getScopes().get(0))) { + throw new UnsupportedOperationException("nothing cached"); + } else { + throw new InvalidUseOfMatchersException( + String.format("Argument %s does not match", (Object) argument)); + } + }); + })) { + // test + InteractiveBrowserCredential credential + = new InteractiveBrowserCredentialBuilder().loginHint(username).clientId(CLIENT_ID).build(); + AccessToken accessToken = credential.getToken(request1); + Assertions.assertEquals(token1, accessToken.getToken()); + Assertions.assertTrue(expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()); + accessToken = credential.getToken(request2); + Assertions.assertEquals(token2, accessToken.getToken()); + Assertions.assertTrue(expiresAt.getSecond() == accessToken.getExpiresAt().getSecond()); + Assertions.assertNotNull(identityClientMock); + } + } + + @Test + public void testCredentialDoesnWorkWIthPortAndRedirectUrlConfigured() throws Exception { + // setup + Assertions.assertThrows(IllegalArgumentException.class, + () -> new InteractiveBrowserCredentialBuilder().clientId(CLIENT_ID) + .port(8080) + .redirectUrl("http://localhost:8080") + .build()); + } + + @Test + public void testValidAuthenticate() throws Exception { + Random random = new Random(); + + // setup + String token1 = "token1"; + TokenRequestContext request1 = new TokenRequestContext().addScopes("https://management.azure.com"); + OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1); + int port = random.nextInt(10000) + 10000; + + // mock + try (MockedConstruction identityClientMock + = mockConstruction(PublicClient.class, (identityClient, context) -> { + when(identityClient.authenticateWithBrowserInteraction(eq(request1), eq(port), eq(null), eq(null))) + .thenReturn(TestUtils.getMockMsalToken(token1, expiresAt)); + })) { + // test + InteractiveBrowserCredential credential + = new InteractiveBrowserCredentialBuilder().port(port).clientId(CLIENT_ID).build(); + AuthenticationRecord authenticationRecord = credential.authenticate(request1); + + Assertions.assertTrue(authenticationRecord.getAuthority().equals("http://login.microsoftonline.com") + && authenticationRecord.getUsername().equals("testuser") + && authenticationRecord.getHomeAccountId() != null); + Assertions.assertNotNull(identityClientMock); + } + } +} diff --git a/sdk/identity/azure-identity-v2/src/test/java/com/azure/identity/v2/util/TestUtils.java b/sdk/identity/azure-identity-v2/src/test/java/com/azure/identity/v2/util/TestUtils.java new file mode 100644 index 000000000000..2b1f94935a4b --- /dev/null +++ b/sdk/identity/azure-identity-v2/src/test/java/com/azure/identity/v2/util/TestUtils.java @@ -0,0 +1,181 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.v2.util; + +import com.azure.identity.v2.implementation.models.MsalToken; +import com.microsoft.aad.msal4j.AuthenticationResultMetadata; +import com.microsoft.aad.msal4j.IAccount; +import com.microsoft.aad.msal4j.IAuthenticationResult; +import com.microsoft.aad.msal4j.ITenantProfile; +import io.clientcore.core.credentials.oauth.AccessToken; +import io.clientcore.core.utils.configuration.Configuration; +import io.clientcore.core.utils.configuration.ConfigurationSource; + +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Date; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; + +/** + * Utilities for identity tests. + */ +public final class TestUtils { + private static final ConfigurationSource EMPTY_SOURCE = new ConfigurationSource() { + @Override + public String getProperty(String name) { + return null; + } + + @Override + public boolean isMutable() { + return true; + } + }; + + /** + * Creates a mock {@link IAuthenticationResult} instance. + * @param accessToken the access token to return + * @param expiresOn the expiration time + * @return a completable future of the result + */ + public static CompletableFuture getMockAuthenticationResult(String accessToken, + OffsetDateTime expiresOn) { + return CompletableFuture.completedFuture(getMockIAuthenticationResult(accessToken, expiresOn)); + } + + private static IAuthenticationResult getMockIAuthenticationResult(String accessToken, OffsetDateTime expiresOn) { + return new IAuthenticationResult() { + @Override + public String accessToken() { + return accessToken; + } + + @Override + public String idToken() { + return null; + } + + @Override + public IAccount account() { + return new Account(); + } + + @Override + public ITenantProfile tenantProfile() { + return null; + } + + @Override + public String environment() { + return "http://login.microsoftonline.com"; + } + + @Override + public String scopes() { + return null; + } + + @Override + public Date expiresOnDate() { + // Access token dials back 2 minutes + return Date.from(expiresOn.plusMinutes(2).toInstant()); + } + + @Override + public AuthenticationResultMetadata metadata() { + return null; + } + }; + } + + /** + * Creates a mock {@link MsalToken} instance. + * @param accessToken the access token to return + * @param expiresOn the expiration time + * @return a Mono publisher of the result + */ + public static MsalToken getMockMsalToken(String accessToken, OffsetDateTime expiresOn) { + return new MsalToken(getMockIAuthenticationResult(accessToken, expiresOn)); + + } + + /** + * Creates a mock {@link IAccount} instance. + * @param accessToken the access token to return + * @param expiresOn the expiration time + * @return a Mono publisher of the result + */ + public static IAccount getMockMsalAccount(String accessToken, OffsetDateTime expiresOn) { + try { + return getMockAuthenticationResult(accessToken, expiresOn).get().account(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } catch (ExecutionException e) { + throw new RuntimeException(e); + } + } + + /** + * Creates a mock {@link AccessToken} instance. + * @param accessToken the access token to return + * @param expiresOn the expiration time + * @return a Mono publisher of the result + */ + public static AccessToken getMockAccessToken(String accessToken, OffsetDateTime expiresOn) { + return new AccessToken(accessToken, expiresOn.plusMinutes(2)); + } + + /** + * Creates a mock {@link AccessToken} instance. + * @param accessToken the access token to return + * @param expiresOn the expiration time + * @param tokenRefreshOffset how long before the actual expiry to refresh the token + * @return a Mono publisher of the result + */ + public static AccessToken getMockAccessToken(String accessToken, OffsetDateTime expiresOn, + Duration tokenRefreshOffset) { + return new AccessToken(accessToken, expiresOn.plusMinutes(2).minus(tokenRefreshOffset)); + } + + /** + * Creates a {@link Configuration} with the specified {@link ConfigurationSource} as the only source of + * configurations. + * + * @param configurationSource The configuration source. + * @return A configuration used for testing. + */ + public static Configuration createTestConfiguration(ConfigurationSource configurationSource) { + return new Configuration(EMPTY_SOURCE, EMPTY_SOURCE, configurationSource); + } + + private TestUtils() { + } + + static class Account implements IAccount { + static final long serialVersionUID = 1L; + + @Override + public String homeAccountId() { + return UUID.randomUUID().toString(); + } + + @Override + public String environment() { + return "http://login.microsoftonline.com"; + } + + @Override + public String username() { + return "testuser"; + } + + @Override + public Map getTenantProfiles() { + return null; + } + } +} diff --git a/sdk/identity/azure-identity/CHANGELOG.md b/sdk/identity/azure-identity/CHANGELOG.md index 204f96165c15..f1870c6735c1 100644 --- a/sdk/identity/azure-identity/CHANGELOG.md +++ b/sdk/identity/azure-identity/CHANGELOG.md @@ -10,6 +10,47 @@ ### Other Changes + - Marked `UsernamePasswordCredential` and `UsernamePasswordCredentialBuilder` as deprecated. See https://aka.ms/azsdk/identity/mfa for details about MFA enforcement and migration guidance. [#44381](https://github.com/Azure/azure-sdk-for-java/pull/44381) + +## 1.15.4 (2025-03-11) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.55.2` to version `1.55.3`. +- Upgraded `azure-core-http-netty` from `1.15.10` to version `1.15.11`. +- Upgraded `azure-json` from `1.4.0` to version `1.5.0`. +- Upgraded `msal4j` from `1.19.0` to version `1.19.1`. + +## 1.15.3 (2025-02-20) + +### Other Changes + +## Dependency Updates + +- Upgraded `azure-core` from `1.55.1` to version `1.55.2`. +- Upgraded `azure-core-http-netty` from `1.15.9` to version `1.15.10`. + +## 1.15.2 (2025-02-13) + +### Other Changes + +- Upgraded `azure-core` from `1.55.0` to version `1.55.1`. +- Upgraded `azure-core-http-netty` from `1.15.8` to version `1.15.9`. + +## 1.15.1 (2025-02-07) + +### Bugs Fixed + +- Fixed an issue preventing scopes with underscores from working properly. [#44040](https://github.com/Azure/azure-sdk-for-java/pull/44040) + +### Other Changes + +- Upgraded `azure-core` from `1.54.1` to version `1.55.0`. +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.8`. +- Upgraded `msal4j` from `1.17.1` to version `1.19.0`. + ## 1.15.0 (2025-01-10) ### Features Added diff --git a/sdk/identity/azure-identity/README.md b/sdk/identity/azure-identity/README.md index 1b6f8bafab57..18508b2b92fd 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.14.2 + 1.15.4 ``` [//]: # ({x-version-update-end}) @@ -301,13 +301,12 @@ Not all credentials honor this configuration. Credentials that authenticate thro ### Authenticate users -|Credential|Usage|Example|Reference| -|-|-|-|-| -|[AuthorizationCodeCredential][cred_acc]|Authenticates a user with a previously obtained authorization code as part of an OAuth 2.0 auth code flow||[OAuth 2.0 auth code][cred_acc_ref]| -|[DeviceCodeCredential][cred_dcc]|Interactively authenticates a user on devices with limited UI|[example][cred_dcc_example]|[device code authentication][cred_dcc_ref]| -|[InteractiveBrowserCredential][cred_ibc]|Interactively authenticates a user with the default system browser|[example][cred_ibc_example]|[OAuth 2.0 auth code][cred_acc_ref]| -|[OnBehalfOfCredential][cred_obo]|Propagates the delegated user identity and permissions through the request chain||[On-behalf-of authentication][cred_obo_ref]| -|[UsernamePasswordCredential][cred_upc]|Authenticates a user with a username and password without multi-factor auth|[example][cred_upc_example]|[Username + password authentication][cred_upc_ref]| +|Credential| Usage |Example|Reference| +|-|-----------------------------------------------------------------------------------------------------------|-|-| +|[AuthorizationCodeCredential][cred_acc]| Authenticates a user with a previously obtained authorization code as part of an OAuth 2.0 auth code flow ||[OAuth 2.0 auth code][cred_acc_ref]| +|[DeviceCodeCredential][cred_dcc]| Interactively authenticates a user on devices with limited UI |[example][cred_dcc_example]|[device code authentication][cred_dcc_ref]| +|[InteractiveBrowserCredential][cred_ibc]| Interactively authenticates a user with the default system browser |[example][cred_ibc_example]|[OAuth 2.0 auth code][cred_acc_ref]| +|[OnBehalfOfCredential][cred_obo]| Propagates the delegated user identity and permissions through the request chain ||[On-behalf-of authentication][cred_obo_ref]| ### Authenticate via development tools @@ -344,15 +343,6 @@ Credentials can be chained together to be tried in turn until one succeeds using |`AZURE_CLIENT_CERTIFICATE_PATH`|path to a PFX or PEM-encoded certificate file including private key| |`AZURE_CLIENT_CERTIFICATE_PASSWORD`|(optional) password for certificate. The certificate can't be password-protected unless this value is specified.| -### Username and password - -|Variable name|Value| -|-|-| -|`AZURE_CLIENT_ID`|ID of a Microsoft Entra application| -|`AZURE_TENANT_ID`|(optional) ID of the application's Microsoft Entra tenant| -|`AZURE_USERNAME`|a username (usually an email address)| -|`AZURE_PASSWORD`|that user's password| - ### Managed identity (`DefaultAzureCredential`) |Variable name|Value| @@ -441,9 +431,6 @@ This project has adopted the [Microsoft Open Source Code of Conduct][code_of_con [cred_mic_example]: https://github.com/Azure/azure-sdk-for-java/wiki/Azure-Identity-Examples#authenticating-in-azure-with-managed-identity [cred_obo]: https://learn.microsoft.com/java/api/com.azure.identity.onbehalfofcredential?view=azure-java-stable [cred_obo_ref]: https://learn.microsoft.com/entra/identity-platform/v2-oauth2-on-behalf-of-flow -[cred_upc]: https://learn.microsoft.com/java/api/com.azure.identity.usernamepasswordcredential?view=azure-java-stable -[cred_upc_example]: https://github.com/Azure/azure-sdk-for-java/wiki/Azure-Identity-Examples#authenticating-a-user-account-with-username-and-password -[cred_upc_ref]: https://learn.microsoft.com/entra/identity-platform/v2-oauth-ropc [cred_vsc]: https://learn.microsoft.com/java/api/com.azure.identity.visualstudiocodecredential?view=azure-java-stable [cred_vsc_example]: https://github.com/Azure/azure-sdk-for-java/wiki/Azure-Identity-Examples#authenticating-a-user-account-with-visual-studio-code [cred_vsc_ref]: https://marketplace.visualstudio.com/items?itemName=ms-vscode.azure-account @@ -460,4 +447,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][code_of_con [source]: https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/identity/azure-identity [sp]: https://learn.microsoft.com/entra/identity-platform/app-objects-and-service-principals -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fidentity%2Fazure-identity%2FREADME.png) + diff --git a/sdk/identity/azure-identity/pom.xml b/sdk/identity/azure-identity/pom.xml index 8a706bbcde0a..1d086d8b8bad 100644 --- a/sdk/identity/azure-identity/pom.xml +++ b/sdk/identity/azure-identity/pom.xml @@ -38,24 +38,24 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-json - 1.3.0 + 1.5.0 com.microsoft.azure msal4j - 1.17.2 + 1.19.1 com.microsoft.azure @@ -65,7 +65,7 @@ com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test @@ -136,7 +136,7 @@ - com.microsoft.azure:msal4j:[1.17.2] + com.microsoft.azure:msal4j:[1.19.1] com.microsoft.azure:msal4j-persistence-extension:[1.3.0] net.java.dev.jna:jna-platform:[5.13.0] diff --git a/sdk/identity/azure-identity/src/main/java/com/azure/identity/EnvironmentCredential.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/EnvironmentCredential.java index 710fa17053b4..f212e31204c8 100644 --- a/sdk/identity/azure-identity/src/main/java/com/azure/identity/EnvironmentCredential.java +++ b/sdk/identity/azure-identity/src/main/java/com/azure/identity/EnvironmentCredential.java @@ -38,6 +38,8 @@ * * *

        The required environment variables for username password authentication are as follows:

        + *

        Deprecated: Username and password authentication doesn't support multifactor authentication (MFA). + * For more details on Microsoft Entra MFA enforcement, see here.

        *
          *
        • {@link Configuration#PROPERTY_AZURE_CLIENT_ID AZURE_CLIENT_ID}
        • *
        • {@link Configuration#PROPERTY_AZURE_USERNAME AZURE_USERNAME}
        • @@ -65,6 +67,7 @@ * @see EnvironmentCredentialBuilder */ @Immutable +@SuppressWarnings("deprecation") public class EnvironmentCredential implements TokenCredential { private static final ClientLogger LOGGER = new ClientLogger(EnvironmentCredential.class); private final TokenCredential tokenCredential; diff --git a/sdk/identity/azure-identity/src/main/java/com/azure/identity/ManagedIdentityCredential.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/ManagedIdentityCredential.java index 7837cfbcc715..9556f923e608 100644 --- a/sdk/identity/azure-identity/src/main/java/com/azure/identity/ManagedIdentityCredential.java +++ b/sdk/identity/azure-identity/src/main/java/com/azure/identity/ManagedIdentityCredential.java @@ -199,6 +199,7 @@ public Mono getToken(TokenRequestContext request) { + " https://aka.ms/azsdk/java/identity/managedidentitycredential/troubleshoot"))); } + // Not having a managedIdentityId at this point means it is a system-assigned managed identity. if (!CoreUtils.isNullOrEmpty(managedIdentityId)) { ManagedIdentitySourceType managedIdentitySourceType = ManagedIdentityApplication.getManagedIdentitySource(); if (ManagedIdentitySourceType.CLOUD_SHELL.equals(managedIdentitySourceType) @@ -211,6 +212,8 @@ public Mono getToken(TokenRequestContext request) { ? "DefaultAzureCredentialBuilder." : "ManagedIdentityCredentialBuilder.")))); } + + LOGGER.info("User-assigned Managed Identity ID: " + getClientId()); } return managedIdentityServiceCredential.authenticate(request) diff --git a/sdk/identity/azure-identity/src/main/java/com/azure/identity/UsernamePasswordCredential.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/UsernamePasswordCredential.java index cd9349ef88bb..e960a09c63e4 100644 --- a/sdk/identity/azure-identity/src/main/java/com/azure/identity/UsernamePasswordCredential.java +++ b/sdk/identity/azure-identity/src/main/java/com/azure/identity/UsernamePasswordCredential.java @@ -52,8 +52,11 @@ * @see UsernamePasswordCredentialBuilder * @see DeviceCodeCredential * @see InteractiveBrowserCredential + * + * @deprecated This credential is deprecated because it doesn't support multifactor authentication (MFA). See here for details about MFA enforcement for Microsoft Entra ID and migration guidance. */ @Immutable +@Deprecated public class UsernamePasswordCredential implements TokenCredential { private static final ClientLogger LOGGER = new ClientLogger(UsernamePasswordCredential.class); diff --git a/sdk/identity/azure-identity/src/main/java/com/azure/identity/UsernamePasswordCredentialBuilder.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/UsernamePasswordCredentialBuilder.java index d369f9b6c2fb..bfd342b842a9 100644 --- a/sdk/identity/azure-identity/src/main/java/com/azure/identity/UsernamePasswordCredentialBuilder.java +++ b/sdk/identity/azure-identity/src/main/java/com/azure/identity/UsernamePasswordCredentialBuilder.java @@ -38,7 +38,11 @@ * * * @see UsernamePasswordCredential + * + * @deprecated This credential is deprecated because it doesn't support multifactor authentication (MFA). See here for details about MFA enforcement for Microsoft Entra ID and migration guidance. + * */ +@Deprecated public class UsernamePasswordCredentialBuilder extends AadCredentialBuilderBase { private static final ClientLogger LOGGER = new ClientLogger(UsernamePasswordCredentialBuilder.class); private static final String CLASS_NAME = UsernamePasswordCredentialBuilder.class.getSimpleName(); diff --git a/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/util/ScopeUtil.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/util/ScopeUtil.java index 23fab0926e5b..dbe2c758eda2 100644 --- a/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/util/ScopeUtil.java +++ b/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/util/ScopeUtil.java @@ -13,7 +13,7 @@ public final class ScopeUtil { private static final String DEFAULT_SUFFIX = "/.default"; - private static final Pattern SCOPE_PATTERN = Pattern.compile("^[0-9a-zA-Z-.:/]+$"); + private static final Pattern SCOPE_PATTERN = Pattern.compile("^[0-9a-zA-Z-.:/_]+$"); /** * Convert a list of scopes to a resource for Microsoft Entra ID. @@ -55,7 +55,7 @@ public static void validateScope(String scope) { if (!isScopeMatch) { throw new IllegalArgumentException("The specified scope is not in expected format." - + " Only alphanumeric characters, '.', '-', ':', and '/' are allowed"); + + " Only alphanumeric characters, '.', '-', ':', '_', and '/' are allowed"); } } diff --git a/sdk/identity/azure-identity/src/test/java/com/azure/identity/OnBehalfOfCredentialTest.java b/sdk/identity/azure-identity/src/test/java/com/azure/identity/OnBehalfOfCredentialTest.java index ca086dbe5c4e..a22b42919a99 100644 --- a/sdk/identity/azure-identity/src/test/java/com/azure/identity/OnBehalfOfCredentialTest.java +++ b/sdk/identity/azure-identity/src/test/java/com/azure/identity/OnBehalfOfCredentialTest.java @@ -187,6 +187,7 @@ public void testInvalidAdditionalTenant() throws Exception { OnBehalfOfCredential credential = new OnBehalfOfCredentialBuilder().tenantId(TENANT_ID) .clientId(CLIENT_ID) + .userAssertion("assertion") .clientSecret(badSecret) .additionallyAllowedTenants("RANDOM") .build(); @@ -203,8 +204,11 @@ public void testInvalidMultiTenantAuth() throws Exception { TokenRequestContext request = new TokenRequestContext().addScopes("https://vault.azure.net/.default").setTenantId("newTenant"); - OnBehalfOfCredential credential - = new OnBehalfOfCredentialBuilder().tenantId(TENANT_ID).clientId(CLIENT_ID).clientSecret(badSecret).build(); + OnBehalfOfCredential credential = new OnBehalfOfCredentialBuilder().tenantId(TENANT_ID) + .clientId(CLIENT_ID) + .clientSecret(badSecret) + .userAssertion("assertion") + .build(); StepVerifier.create(credential.getToken(request)) .expectErrorMatches(e -> e instanceof ClientAuthenticationException && (e.getMessage().startsWith("The current credential is not configured to"))) diff --git a/sdk/identity/azure-identity/src/test/java/com/azure/identity/UsernamePasswordCredentialTest.java b/sdk/identity/azure-identity/src/test/java/com/azure/identity/UsernamePasswordCredentialTest.java index e333a52320dc..6f3754900d02 100644 --- a/sdk/identity/azure-identity/src/test/java/com/azure/identity/UsernamePasswordCredentialTest.java +++ b/sdk/identity/azure-identity/src/test/java/com/azure/identity/UsernamePasswordCredentialTest.java @@ -29,6 +29,7 @@ import static org.mockito.Mockito.mockConstruction; import static org.mockito.Mockito.when; +@SuppressWarnings("deprecation") public class UsernamePasswordCredentialTest { private final String clientId = UUID.randomUUID().toString(); diff --git a/sdk/identity/azure-identity/src/test/java/com/azure/identity/implementation/ScopeUtilTests.java b/sdk/identity/azure-identity/src/test/java/com/azure/identity/implementation/ScopeUtilTests.java new file mode 100644 index 000000000000..a826e7cdb652 --- /dev/null +++ b/sdk/identity/azure-identity/src/test/java/com/azure/identity/implementation/ScopeUtilTests.java @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.implementation; + +import com.azure.identity.implementation.util.ScopeUtil; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class ScopeUtilTests { + + @ParameterizedTest + @MethodSource("validScopes") + public void validScopes(String scope) { + assertDoesNotThrow(() -> ScopeUtil.validateScope(scope)); + + } + + @ParameterizedTest + @MethodSource("invalidScopes") + public void validInvalidScopes(String scope) { + assertThrows(IllegalArgumentException.class, () -> ScopeUtil.validateScope(scope)); + + } + + static Stream validScopes() { + return Stream.of("https://vaults.azure.net/.default", "https://management.core.windows.net//.default", + "https://graph.microsoft.com/User.Read", "api://app-id-has-hyphens-and-1234567890s/user_impersonation"); + } + + static Stream invalidScopes() { + return Stream.of("api://app-id-has-hyphens-and-1234567890s/invalid scope", + "api://app-id-has-hyphens-and-1234567890s/invalid\"scope", + "api://app-id-has-hyphens-and-1234567890s/invalid\\scope"); + } +} diff --git a/sdk/identity/ci.v2.yml b/sdk/identity/ci.v2.yml new file mode 100644 index 000000000000..5e529a4c4921 --- /dev/null +++ b/sdk/identity/ci.v2.yml @@ -0,0 +1,77 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. + +trigger: + branches: + include: + - main + - hotfix/* + - release/* + paths: + include: + - sdk/identity/ci.v2.yml + - sdk/identity/azure-identity-v2/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/identity/ci.v2.yml + - sdk/identity/azure-identity-v2/ + +parameters: + - name: release_dependsonlivetests + displayName: 'Release depends on live tests' + type: boolean + default: true + - name: release_azureidentityv2 + displayName: 'azure-identity-v2' + type: boolean + default: true + +extends: + template: /eng/pipelines/templates/stages/archetype-sdk-client.yml + parameters: + ServiceDirectory: identity + TimeoutInMinutes: 90 + ReleaseDependsOnLiveTests: ${{ parameters.release_dependsonlivetests }} + Artifacts: + - name: azure-identity-v2 + groupId: com.azure + safeName: azureidentityv2 + releaseInBatch: ${{ parameters.release_azureidentityv2 }} + LiveTestStages: + - template: /eng/pipelines/templates/stages/archetype-sdk-tests-isolated.yml + parameters: + PreTestRunSteps: + - task: AzureCLI@2 + displayName: Refresh OIDC token + env: + ARM_OIDC_TOKEN: $(ARM_OIDC_TOKEN) + inputs: + azureSubscription: azure-sdk-tests-public + addSpnToEnvironment: true + scriptLocation: inlineScript + scriptType: pscore + inlineScript: | + Write-Host "##vso[task.setvariable variable=ARM_OIDC_TOKEN;issecret=true]$($env:idToken)" + PersistOidcToken: true + Location: 'westus2' + CalledFromClient: true + ServiceDirectory: identity + EnvVars: + AZ_OIDC_TOKEN: $(ARM_OIDC_TOKEN) + AZURE_IDENTITY_MULTI_TENANT_CLIENT_SECRET: $(AZURE-IDENTITY-MULTI-TENANT-CLIENT-SECRET) + CloudConfig: + Public: + SubscriptionConfigurations: + - $(sub-config-identity-test-resources) + Artifacts: + - name: azure-identity-v2 + groupId: com.azure + safeName: azureidentityv2 + diff --git a/sdk/identity/ci.yml b/sdk/identity/ci.yml index ff571e869cce..9dc5816b6e01 100644 --- a/sdk/identity/ci.yml +++ b/sdk/identity/ci.yml @@ -15,6 +15,8 @@ trigger: - sdk/identity/azure-identity-perf/pom.xml - sdk/identity/azure-identity-broker/pom.xml - sdk/identity/azure-identity-extensions/ + - sdk/identity/ci.v2.yml + - sdk/identity/azure-identity-v2/ pr: branches: @@ -32,6 +34,8 @@ pr: - sdk/identity/azure-identity-perf/pom.xml - sdk/identity/azure-identity-broker/pom.xml - sdk/identity/azure-identity-extensions/ + - sdk/identity/ci.v2.yml + - sdk/identity/azure-identity-v2/ parameters: - name: release_dependsonlivetests diff --git a/sdk/identity/live-test-apps/identity-test-function/pom.xml b/sdk/identity/live-test-apps/identity-test-function/pom.xml index c674477afc0a..b4864acda838 100644 --- a/sdk/identity/live-test-apps/identity-test-function/pom.xml +++ b/sdk/identity/live-test-apps/identity-test-function/pom.xml @@ -29,7 +29,7 @@ com.azure azure-storage-blob - 12.29.0 + 12.29.1 diff --git a/sdk/identity/live-test-apps/identity-test-webapp/pom.xml b/sdk/identity/live-test-apps/identity-test-webapp/pom.xml index 4e87c6bdec0a..fe1d9bee9d56 100644 --- a/sdk/identity/live-test-apps/identity-test-webapp/pom.xml +++ b/sdk/identity/live-test-apps/identity-test-webapp/pom.xml @@ -34,7 +34,7 @@ com.azure azure-storage-blob - 12.29.0 + 12.29.1 diff --git a/sdk/identity/pom.xml b/sdk/identity/pom.xml index 0529fb94765c..34a760bb4b45 100644 --- a/sdk/identity/pom.xml +++ b/sdk/identity/pom.xml @@ -16,6 +16,7 @@ azure-identity + azure-identity-v2 azure-identity-perf azure-identity-extensions azure-identity-broker diff --git a/sdk/imagebuilder/azure-resourcemanager-imagebuilder/README.md b/sdk/imagebuilder/azure-resourcemanager-imagebuilder/README.md index fb005d9a7201..8742dd23b131 100644 --- a/sdk/imagebuilder/azure-resourcemanager-imagebuilder/README.md +++ b/sdk/imagebuilder/azure-resourcemanager-imagebuilder/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-imagebuilder - 1.2.0 + 1.3.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fimagebuilder%2Fazure-resourcemanager-imagebuilder%2FREADME.png) + diff --git a/sdk/imagebuilder/azure-resourcemanager-imagebuilder/pom.xml b/sdk/imagebuilder/azure-resourcemanager-imagebuilder/pom.xml index 85f8b6c1bf63..a9dd3d84ac41 100644 --- a/sdk/imagebuilder/azure-resourcemanager-imagebuilder/pom.xml +++ b/sdk/imagebuilder/azure-resourcemanager-imagebuilder/pom.xml @@ -51,40 +51,40 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-json - 1.3.0 + 1.5.0 com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test com.azure.resourcemanager azure-resourcemanager-msi - 2.46.0 + 2.48.0 test diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/CHANGELOG.md b/sdk/impactreporting/azure-resourcemanager-impactreporting/CHANGELOG.md new file mode 100644 index 000000000000..41184a680703 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/CHANGELOG.md @@ -0,0 +1,18 @@ +# Release History + +## 1.0.0-beta.2 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + +## 1.0.0-beta.1 (2025-02-19) + +- Azure Resource Manager Impact Reporting client library for Java. This package contains Microsoft Azure SDK for Impact Reporting Management SDK. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). +### Features Added + +- Initial release for the azure-resourcemanager-impactreporting Java SDK. diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/README.md b/sdk/impactreporting/azure-resourcemanager-impactreporting/README.md new file mode 100644 index 000000000000..db502d548eea --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/README.md @@ -0,0 +1,102 @@ +# Azure Resource Manager Impact Reporting client library for Java + +Azure Resource Manager Impact Reporting client library for Java. + +This package contains Microsoft Azure SDK for Impact Reporting Management SDK. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). + +## We'd love to hear your feedback + +We're always working on improving our products and the way we communicate with our users. So we'd love to learn what's working and how we can do better. + +If you haven't already, please take a few minutes to [complete this short survey][survey] we have put together. + +Thank you in advance for your collaboration. We really appreciate your time! + +## Documentation + +Various documentation is available to help you get started + +- [API reference documentation][docs] + +## Getting started + +### Prerequisites + +- [Java Development Kit (JDK)][jdk] with version 8 or above +- [Azure Subscription][azure_subscription] + +### Adding the package to your product + +[//]: # ({x-version-update-start;com.azure.resourcemanager:azure-resourcemanager-impactreporting;current}) +```xml + + com.azure.resourcemanager + azure-resourcemanager-impactreporting + 1.0.0-beta.2 + +``` +[//]: # ({x-version-update-end}) + +### Include the recommended packages + +Azure Management Libraries require a `TokenCredential` implementation for authentication and an `HttpClient` implementation for HTTP client. + +[Azure Identity][azure_identity] and [Azure Core Netty HTTP][azure_core_http_netty] packages provide the default implementation. + +### Authentication + +Microsoft Entra ID token authentication relies on the [credential class][azure_identity_credentials] from [Azure Identity][azure_identity] package. + +Azure subscription ID can be configured via `AZURE_SUBSCRIPTION_ID` environment variable. + +Assuming the use of the `DefaultAzureCredential` credential class, the client can be authenticated using the following code: + +```java +AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); +TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); +ImpactReportingManager manager = ImpactReportingManager + .authenticate(credential, profile); +``` + +The sample code assumes global Azure. Please change the `AzureCloud.AZURE_PUBLIC_CLOUD` variable if otherwise. + +See [Authentication][authenticate] for more options. + +## Key concepts + +See [API design][design] for general introduction on design and key concepts on Azure Management Libraries. + +## Examples + +[Code snippets and samples](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/impactreporting/azure-resourcemanager-impactreporting/SAMPLE.md) + + +## Troubleshooting + +## Next steps + +## Contributing + +For details on contributing to this repository, see the [contributing guide][cg]. + +This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit . + +When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repositories using our CLA. + +This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For more information see the [Code of Conduct FAQ][coc_faq] or contact with any additional questions or comments. + + +[survey]: https://microsoft.qualtrics.com/jfe/form/SV_ehN0lIk2FKEBkwd?Q_CHL=DOCS +[docs]: https://azure.github.io/azure-sdk-for-java/ +[jdk]: https://learn.microsoft.com/azure/developer/java/fundamentals/ +[azure_subscription]: https://azure.microsoft.com/free/ +[azure_identity]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/identity/azure-identity +[azure_identity_credentials]: https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/identity/azure-identity#credentials +[azure_core_http_netty]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/core/azure-core-http-netty +[authenticate]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/resourcemanager/docs/AUTH.md +[design]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/resourcemanager/docs/DESIGN.md +[cg]: https://github.com/Azure/azure-sdk-for-java/blob/main/CONTRIBUTING.md +[coc]: https://opensource.microsoft.com/codeofconduct/ +[coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/SAMPLE.md b/sdk/impactreporting/azure-resourcemanager-impactreporting/SAMPLE.md new file mode 100644 index 000000000000..a98fc000c631 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/SAMPLE.md @@ -0,0 +1,547 @@ +# Code snippets and samples + + +## Connectors + +- [CreateOrUpdate](#connectors_createorupdate) +- [Delete](#connectors_delete) +- [Get](#connectors_get) +- [List](#connectors_list) +- [Update](#connectors_update) + +## ImpactCategories + +- [Get](#impactcategories_get) +- [List](#impactcategories_list) + +## Insights + +- [Create](#insights_create) +- [Delete](#insights_delete) +- [Get](#insights_get) +- [ListBySubscription](#insights_listbysubscription) + +## Operations + +- [List](#operations_list) + +## WorkloadImpacts + +- [Create](#workloadimpacts_create) +- [Delete](#workloadimpacts_delete) +- [Get](#workloadimpacts_get) +- [List](#workloadimpacts_list) +### Connectors_CreateOrUpdate + +```java +import com.azure.resourcemanager.impactreporting.models.ConnectorProperties; +import com.azure.resourcemanager.impactreporting.models.Platform; + +/** + * Samples for Connectors CreateOrUpdate. + */ +public final class ConnectorsCreateOrUpdateSamples { + /* + * x-ms-original-file: 2024-05-01-preview/Connectors_CreateOrUpdate.json + */ + /** + * Sample code: Connectors_CreateOrUpdate. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void + connectorsCreateOrUpdate(com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.connectors() + .define("testconnector1") + .withProperties(new ConnectorProperties().withConnectorType(Platform.AZURE_MONITOR)) + .create(); + } +} +``` + +### Connectors_Delete + +```java +/** + * Samples for Connectors Delete. + */ +public final class ConnectorsDeleteSamples { + /* + * x-ms-original-file: 2024-05-01-preview/Connectors_Delete.json + */ + /** + * Sample code: Connectors_Delete. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void connectorsDelete(com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.connectors().deleteWithResponse("testconnector1", com.azure.core.util.Context.NONE); + } +} +``` + +### Connectors_Get + +```java +/** + * Samples for Connectors Get. + */ +public final class ConnectorsGetSamples { + /* + * x-ms-original-file: 2024-05-01-preview/Connectors_Get.json + */ + /** + * Sample code: Connectors_Get. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void connectorsGet(com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.connectors().getWithResponse("testconnector1", com.azure.core.util.Context.NONE); + } +} +``` + +### Connectors_List + +```java +/** + * Samples for Connectors List. + */ +public final class ConnectorsListSamples { + /* + * x-ms-original-file: 2024-05-01-preview/Connectors_ListBySubscription.json + */ + /** + * Sample code: Connectors_ListBySubscription. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void + connectorsListBySubscription(com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.connectors().list(com.azure.core.util.Context.NONE); + } +} +``` + +### Connectors_Update + +```java +import com.azure.resourcemanager.impactreporting.models.Connector; +import com.azure.resourcemanager.impactreporting.models.ConnectorUpdateProperties; +import com.azure.resourcemanager.impactreporting.models.Platform; + +/** + * Samples for Connectors Update. + */ +public final class ConnectorsUpdateSamples { + /* + * x-ms-original-file: 2024-05-01-preview/Connectors_Update.json + */ + /** + * Sample code: Connectors_Update. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void connectorsUpdate(com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + Connector resource + = manager.connectors().getWithResponse("testconnector1", com.azure.core.util.Context.NONE).getValue(); + resource.update() + .withProperties(new ConnectorUpdateProperties().withConnectorType(Platform.AZURE_MONITOR)) + .apply(); + } +} +``` + +### ImpactCategories_Get + +```java +/** + * Samples for ImpactCategories Get. + */ +public final class ImpactCategoriesGetSamples { + /* + * x-ms-original-file: 2024-05-01-preview/ImpactCategories_Get.json + */ + /** + * Sample code: Get WorkloadImpact Resource by name. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void + getWorkloadImpactResourceByName(com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.impactCategories().getWithResponse("ARMOperation.Create", com.azure.core.util.Context.NONE); + } +} +``` + +### ImpactCategories_List + +```java +/** + * Samples for ImpactCategories List. + */ +public final class ImpactCategoriesListSamples { + /* + * x-ms-original-file: 2024-05-01-preview/ImpactCategories_ListBySubscription.json + */ + /** + * Sample code: Get ImpactCategories list by subscription. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void getImpactCategoriesListBySubscription( + com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.impactCategories().list("microsoft.compute/virtualmachines", null, com.azure.core.util.Context.NONE); + } +} +``` + +### Insights_Create + +```java +import com.azure.resourcemanager.impactreporting.models.Content; +import com.azure.resourcemanager.impactreporting.models.ImpactDetails; +import com.azure.resourcemanager.impactreporting.models.InsightProperties; +import java.time.OffsetDateTime; + +/** + * Samples for Insights Create. + */ +public final class InsightsCreateSamples { + /* + * x-ms-original-file: 2024-05-01-preview/Insights_Create.json + */ + /** + * Sample code: Creating an insight. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void creatingAnInsight(com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.insights() + .define("insightId12") + .withExistingWorkloadImpact("impactid22") + .withProperties(new InsightProperties().withCategory("repair") + .withStatus("resolved") + .withContent(new Content().withTitle("Impact Has been correlated to an outage") + .withDescription( + "At 2018-11-08T00:00:00Z UTC, your services dependent on these resources VM1 may have experienced an issue.
          We have identified an outage that affected these resources(s). You can look at outage information on NL2W-VCZ link.
          ")) + .withEventTime(OffsetDateTime.parse("2023-06-15T04:00:00.009223Z")) + .withInsightUniqueId("00000000-0000-0000-0000-000000000000") + .withImpact(new ImpactDetails().withImpactedResourceId( + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resource-rg/providers/Microsoft.Sql/sqlserver/dbservername") + .withStartTime(OffsetDateTime.parse("2023-06-15T01:00:00.009223Z")) + .withImpactId( + "/subscriptions/00000000-0000-0000-0000-000000000000/providers/microsoft.Impact/workloadImpacts/impactid22"))) + .create(); + } +} +``` + +### Insights_Delete + +```java +/** + * Samples for Insights Delete. + */ +public final class InsightsDeleteSamples { + /* + * x-ms-original-file: 2024-05-01-preview/Insights_Delete.json + */ + /** + * Sample code: Delete an Insight. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void deleteAnInsight(com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.insights() + .deleteByResourceGroupWithResponse("impactid22", "insightId12", com.azure.core.util.Context.NONE); + } +} +``` + +### Insights_Get + +```java +/** + * Samples for Insights Get. + */ +public final class InsightsGetSamples { + /* + * x-ms-original-file: 2024-05-01-preview/Insights_Get_mitigationAction.json + */ + /** + * Sample code: Get Insight sample for MitigationAction category. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void getInsightSampleForMitigationActionCategory( + com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.insights().getWithResponse("impactId", "HPCUASucceeded", com.azure.core.util.Context.NONE); + } + + /* + * x-ms-original-file: 2024-05-01-preview/Insights_Get_diagnostics.json + */ + /** + * Sample code: Get Insight sample for Diagnostics category. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void getInsightSampleForDiagnosticsCategory( + com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.insights().getWithResponse("impactid", "insight1", com.azure.core.util.Context.NONE); + } + + /* + * x-ms-original-file: 2024-05-01-preview/Insights_Get_servicehealth.json + */ + /** + * Sample code: Get Insight sample for service health category. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void getInsightSampleForServiceHealthCategory( + com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.insights().getWithResponse("impactid", "insightname", com.azure.core.util.Context.NONE); + } +} +``` + +### Insights_ListBySubscription + +```java +/** + * Samples for Insights ListBySubscription. + */ +public final class InsightsListBySubscriptionSamples { + /* + * x-ms-original-file: 2024-05-01-preview/Insights_ListBySubscription.json + */ + /** + * Sample code: List Insight resources by workloadImpactName. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void listInsightResourcesByWorkloadImpactName( + com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.insights().listBySubscription("impactid22", com.azure.core.util.Context.NONE); + } +} +``` + +### Operations_List + +```java +/** + * Samples for Operations List. + */ +public final class OperationsListSamples { + /* + * x-ms-original-file: 2024-05-01-preview/Operations_List.json + */ + /** + * Sample code: OperationsList. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void operationsList(com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.operations().list(com.azure.core.util.Context.NONE); + } +} +``` + +### WorkloadImpacts_Create + +```java +import com.azure.resourcemanager.impactreporting.models.ClientIncidentDetails; +import com.azure.resourcemanager.impactreporting.models.Connectivity; +import com.azure.resourcemanager.impactreporting.models.IncidentSource; +import com.azure.resourcemanager.impactreporting.models.MetricUnit; +import com.azure.resourcemanager.impactreporting.models.Performance; +import com.azure.resourcemanager.impactreporting.models.Protocol; +import com.azure.resourcemanager.impactreporting.models.SourceOrTarget; +import com.azure.resourcemanager.impactreporting.models.Toolset; +import com.azure.resourcemanager.impactreporting.models.Workload; +import com.azure.resourcemanager.impactreporting.models.WorkloadImpactProperties; +import java.time.OffsetDateTime; +import java.util.Arrays; + +/** + * Samples for WorkloadImpacts Create. + */ +public final class WorkloadImpactsCreateSamples { + /* + * x-ms-original-file: 2024-05-01-preview/WorkloadAvailability_Create.json + */ + /** + * Sample code: Reporting availability related impact. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void + reportingAvailabilityRelatedImpact(com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.workloadImpacts() + .define("impact-002") + .withProperties(new WorkloadImpactProperties() + .withStartDateTime(OffsetDateTime.parse("2022-06-15T05:59:46.6517821Z")) + .withImpactedResourceId( + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resource-rg/providers/Microsoft.Sql/sqlserver/dbservercontext") + .withImpactCategory("Availability") + .withImpactDescription("read calls failed") + .withWorkload(new Workload().withContext("webapp/scenario1").withToolset(Toolset.OTHER)) + .withClientIncidentDetails(new ClientIncidentDetails().withClientIncidentId("AA123") + .withClientIncidentSource(IncidentSource.JIRA))) + .create(); + } + + /* + * x-ms-original-file: 2024-05-01-preview/WorkloadConnectivityImpact_Create.json + */ + /** + * Sample code: Reporting a connectivity impact. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void + reportingAConnectivityImpact(com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.workloadImpacts() + .define("impact-001") + .withProperties(new WorkloadImpactProperties() + .withStartDateTime(OffsetDateTime.parse("2022-06-15T05:59:46.6517821Z")) + .withImpactedResourceId( + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resource-rg/providers/Microsoft.Sql/sqlserver/dbservercontext") + .withImpactCategory("Resource.Connectivity") + .withImpactDescription("conection failure") + .withConnectivity(new Connectivity().withProtocol(Protocol.TCP) + .withPort(1443) + .withSource(new SourceOrTarget().withAzureResourceId( + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resourceSub/providers/Microsoft.compute/virtualmachines/vm1")) + .withTarget(new SourceOrTarget().withAzureResourceId( + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resourceSub/providers/Microsoft.compute/virtualmachines/vm2"))) + .withWorkload(new Workload().withContext("webapp/scenario1").withToolset(Toolset.OTHER)) + .withClientIncidentDetails(new ClientIncidentDetails().withClientIncidentId("AA123") + .withClientIncidentSource(IncidentSource.JIRA))) + .create(); + } + + /* + * x-ms-original-file: 2024-05-01-preview/WorkloadArmOperation_create.json + */ + /** + * Sample code: Reporting Arm operation failure. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void + reportingArmOperationFailure(com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.workloadImpacts() + .define("impact-002") + .withProperties(new WorkloadImpactProperties() + .withStartDateTime(OffsetDateTime.parse("2022-06-15T05:59:46.6517821Z")) + .withImpactedResourceId( + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resource-rg/providers/Microsoft.Sql/sqlserver/dbservercontext") + .withImpactCategory("ArmOperation") + .withImpactDescription("deletion of resource failed") + .withArmCorrelationIds(Arrays.asList("00000000-0000-0000-0000-000000000000")) + .withWorkload(new Workload().withContext("webapp/scenario1").withToolset(Toolset.OTHER)) + .withClientIncidentDetails(new ClientIncidentDetails().withClientIncidentId("AA123") + .withClientIncidentSource(IncidentSource.JIRA))) + .create(); + } + + /* + * x-ms-original-file: 2024-05-01-preview/WorkloadPerformance_Create.json + */ + /** + * Sample code: Reporting performance related impact. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void + reportingPerformanceRelatedImpact(com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.workloadImpacts() + .define("impact-002") + .withProperties(new WorkloadImpactProperties() + .withStartDateTime(OffsetDateTime.parse("2022-06-15T05:59:46.6517821Z")) + .withImpactedResourceId( + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resource-rg/providers/Microsoft.Sql/sqlserver/dbservercontext") + .withImpactCategory("Resource.Performance") + .withImpactDescription("high cpu utilization") + .withPerformance(Arrays.asList(new Performance().withMetricName("CPU") + .withExpected(60.0D) + .withActual(90.0D) + .withUnit(MetricUnit.fromString("garbage")))) + .withWorkload(new Workload().withContext("webapp/scenario1").withToolset(Toolset.OTHER)) + .withClientIncidentDetails(new ClientIncidentDetails().withClientIncidentId("AA123") + .withClientIncidentSource(IncidentSource.JIRA))) + .create(); + } +} +``` + +### WorkloadImpacts_Delete + +```java +/** + * Samples for WorkloadImpacts Delete. + */ +public final class WorkloadImpactsDeleteSamples { + /* + * x-ms-original-file: 2024-05-01-preview/WorkloadImpact_Delete.json + */ + /** + * Sample code: Delete WorkloadImpact Resource by name example. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void deleteWorkloadImpactResourceByNameExample( + com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.workloadImpacts().deleteWithResponse("impact-001", com.azure.core.util.Context.NONE); + } +} +``` + +### WorkloadImpacts_Get + +```java +/** + * Samples for WorkloadImpacts Get. + */ +public final class WorkloadImpactsGetSamples { + /* + * x-ms-original-file: 2024-05-01-preview/WorkloadImpact_Get.json + */ + /** + * Sample code: Get WorkloadImpact Resource by name example. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void getWorkloadImpactResourceByNameExample( + com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.workloadImpacts().getWithResponse("impact-001", com.azure.core.util.Context.NONE); + } +} +``` + +### WorkloadImpacts_List + +```java +/** + * Samples for WorkloadImpacts List. + */ +public final class WorkloadImpactsListSamples { + /* + * x-ms-original-file: 2024-05-01-preview/WorkloadImpacts_ListBySubscription.json + */ + /** + * Sample code: List WorkloadImpact resources by subscription. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void listWorkloadImpactResourcesBySubscription( + com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.workloadImpacts().list(com.azure.core.util.Context.NONE); + } +} +``` + diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/pom.xml b/sdk/impactreporting/azure-resourcemanager-impactreporting/pom.xml new file mode 100644 index 000000000000..a0f46847aa6b --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/pom.xml @@ -0,0 +1,75 @@ + + + 4.0.0 + + com.azure + azure-client-sdk-parent + 1.7.0 + ../../parents/azure-client-sdk-parent + + + com.azure.resourcemanager + azure-resourcemanager-impactreporting + 1.0.0-beta.2 + jar + + Microsoft Azure SDK for Impact Reporting Management + This package contains Microsoft Azure SDK for Impact Reporting Management SDK. For documentation on how to use this package, please see https://aka.ms/azsdk/java/mgmt. + https://github.com/Azure/azure-sdk-for-java + + + + The MIT License (MIT) + http://opensource.org/licenses/MIT + repo + + + + + https://github.com/Azure/azure-sdk-for-java + scm:git:git@github.com:Azure/azure-sdk-for-java.git + scm:git:git@github.com:Azure/azure-sdk-for-java.git + HEAD + + + + microsoft + Microsoft + + + + UTF-8 + 0 + 0 + true + false + + + + com.azure + azure-core + 1.55.3 + + + com.azure + azure-core-management + 1.17.0 + + + com.azure + azure-core-test + 1.27.0-beta.8 + test + + + com.azure + azure-identity + 1.15.4 + test + + + diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/ImpactReportingManager.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/ImpactReportingManager.java new file mode 100644 index 000000000000..a031e1c3c8a5 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/ImpactReportingManager.java @@ -0,0 +1,345 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.HttpPipelinePosition; +import com.azure.core.http.policy.AddDatePolicy; +import com.azure.core.http.policy.AddHeadersFromContextPolicy; +import com.azure.core.http.policy.BearerTokenAuthenticationPolicy; +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.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.management.profile.AzureProfile; +import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.impactreporting.fluent.ImpactReportingMgmtClient; +import com.azure.resourcemanager.impactreporting.implementation.ConnectorsImpl; +import com.azure.resourcemanager.impactreporting.implementation.ImpactCategoriesImpl; +import com.azure.resourcemanager.impactreporting.implementation.ImpactReportingMgmtClientBuilder; +import com.azure.resourcemanager.impactreporting.implementation.InsightsImpl; +import com.azure.resourcemanager.impactreporting.implementation.OperationsImpl; +import com.azure.resourcemanager.impactreporting.implementation.WorkloadImpactsImpl; +import com.azure.resourcemanager.impactreporting.models.Connectors; +import com.azure.resourcemanager.impactreporting.models.ImpactCategories; +import com.azure.resourcemanager.impactreporting.models.Insights; +import com.azure.resourcemanager.impactreporting.models.Operations; +import com.azure.resourcemanager.impactreporting.models.WorkloadImpacts; +import java.time.Duration; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +/** + * Entry point to ImpactReportingManager. + */ +public final class ImpactReportingManager { + private Operations operations; + + private WorkloadImpacts workloadImpacts; + + private ImpactCategories impactCategories; + + private Insights insights; + + private Connectors connectors; + + private final ImpactReportingMgmtClient clientObject; + + private ImpactReportingManager(HttpPipeline httpPipeline, AzureProfile profile, Duration defaultPollInterval) { + Objects.requireNonNull(httpPipeline, "'httpPipeline' cannot be null."); + Objects.requireNonNull(profile, "'profile' cannot be null."); + this.clientObject = new ImpactReportingMgmtClientBuilder().pipeline(httpPipeline) + .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) + .subscriptionId(profile.getSubscriptionId()) + .defaultPollInterval(defaultPollInterval) + .buildClient(); + } + + /** + * Creates an instance of Impact Reporting service API entry point. + * + * @param credential the credential to use. + * @param profile the Azure profile for client. + * @return the Impact Reporting service API instance. + */ + public static ImpactReportingManager authenticate(TokenCredential credential, AzureProfile profile) { + Objects.requireNonNull(credential, "'credential' cannot be null."); + Objects.requireNonNull(profile, "'profile' cannot be null."); + return configure().authenticate(credential, profile); + } + + /** + * Creates an instance of Impact Reporting service API entry point. + * + * @param httpPipeline the {@link HttpPipeline} configured with Azure authentication credential. + * @param profile the Azure profile for client. + * @return the Impact Reporting service API instance. + */ + public static ImpactReportingManager authenticate(HttpPipeline httpPipeline, AzureProfile profile) { + Objects.requireNonNull(httpPipeline, "'httpPipeline' cannot be null."); + Objects.requireNonNull(profile, "'profile' cannot be null."); + return new ImpactReportingManager(httpPipeline, profile, null); + } + + /** + * Gets a Configurable instance that can be used to create ImpactReportingManager with optional configuration. + * + * @return the Configurable instance allowing configurations. + */ + public static Configurable configure() { + return new ImpactReportingManager.Configurable(); + } + + /** + * The Configurable allowing configurations to be set. + */ + public static final class Configurable { + private static final ClientLogger LOGGER = new ClientLogger(Configurable.class); + private static final String SDK_VERSION = "version"; + private static final Map PROPERTIES + = CoreUtils.getProperties("azure-resourcemanager-impactreporting.properties"); + + private HttpClient httpClient; + private HttpLogOptions httpLogOptions; + private final List policies = new ArrayList<>(); + private final List scopes = new ArrayList<>(); + private RetryPolicy retryPolicy; + private RetryOptions retryOptions; + private Duration defaultPollInterval; + + private Configurable() { + } + + /** + * Sets the http client. + * + * @param httpClient the HTTP client. + * @return the configurable object itself. + */ + public Configurable withHttpClient(HttpClient httpClient) { + this.httpClient = Objects.requireNonNull(httpClient, "'httpClient' cannot be null."); + return this; + } + + /** + * Sets the logging options to the HTTP pipeline. + * + * @param httpLogOptions the HTTP log options. + * @return the configurable object itself. + */ + public Configurable withLogOptions(HttpLogOptions httpLogOptions) { + this.httpLogOptions = Objects.requireNonNull(httpLogOptions, "'httpLogOptions' cannot be null."); + return this; + } + + /** + * Adds the pipeline policy to the HTTP pipeline. + * + * @param policy the HTTP pipeline policy. + * @return the configurable object itself. + */ + public Configurable withPolicy(HttpPipelinePolicy policy) { + this.policies.add(Objects.requireNonNull(policy, "'policy' cannot be null.")); + return this; + } + + /** + * Adds the scope to permission sets. + * + * @param scope the scope. + * @return the configurable object itself. + */ + public Configurable withScope(String scope) { + this.scopes.add(Objects.requireNonNull(scope, "'scope' cannot be null.")); + return this; + } + + /** + * Sets the retry policy to the HTTP pipeline. + * + * @param retryPolicy the HTTP pipeline retry policy. + * @return the configurable object itself. + */ + public Configurable withRetryPolicy(RetryPolicy retryPolicy) { + this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null."); + return this; + } + + /** + * Sets the retry options for the HTTP pipeline retry policy. + *

          + * This setting has no effect, if retry policy is set via {@link #withRetryPolicy(RetryPolicy)}. + * + * @param retryOptions the retry options for the HTTP pipeline retry policy. + * @return the configurable object itself. + */ + public Configurable withRetryOptions(RetryOptions retryOptions) { + this.retryOptions = Objects.requireNonNull(retryOptions, "'retryOptions' cannot be null."); + return this; + } + + /** + * Sets the default poll interval, used when service does not provide "Retry-After" header. + * + * @param defaultPollInterval the default poll interval. + * @return the configurable object itself. + */ + public Configurable withDefaultPollInterval(Duration defaultPollInterval) { + this.defaultPollInterval + = Objects.requireNonNull(defaultPollInterval, "'defaultPollInterval' cannot be null."); + if (this.defaultPollInterval.isNegative()) { + throw LOGGER + .logExceptionAsError(new IllegalArgumentException("'defaultPollInterval' cannot be negative")); + } + return this; + } + + /** + * Creates an instance of Impact Reporting service API entry point. + * + * @param credential the credential to use. + * @param profile the Azure profile for client. + * @return the Impact Reporting service API instance. + */ + public ImpactReportingManager authenticate(TokenCredential credential, AzureProfile profile) { + Objects.requireNonNull(credential, "'credential' cannot be null."); + Objects.requireNonNull(profile, "'profile' cannot be null."); + + String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); + + StringBuilder userAgentBuilder = new StringBuilder(); + userAgentBuilder.append("azsdk-java") + .append("-") + .append("com.azure.resourcemanager.impactreporting") + .append("/") + .append(clientVersion); + if (!Configuration.getGlobalConfiguration().get("AZURE_TELEMETRY_DISABLED", false)) { + userAgentBuilder.append(" (") + .append(Configuration.getGlobalConfiguration().get("java.version")) + .append("; ") + .append(Configuration.getGlobalConfiguration().get("os.name")) + .append("; ") + .append(Configuration.getGlobalConfiguration().get("os.version")) + .append("; auto-generated)"); + } else { + userAgentBuilder.append(" (auto-generated)"); + } + + if (scopes.isEmpty()) { + scopes.add(profile.getEnvironment().getManagementEndpoint() + "/.default"); + } + if (retryPolicy == null) { + if (retryOptions != null) { + retryPolicy = new RetryPolicy(retryOptions); + } else { + retryPolicy = new RetryPolicy("Retry-After", ChronoUnit.SECONDS); + } + } + List policies = new ArrayList<>(); + policies.add(new UserAgentPolicy(userAgentBuilder.toString())); + policies.add(new AddHeadersFromContextPolicy()); + policies.add(new RequestIdPolicy()); + policies.addAll(this.policies.stream() + .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) + .collect(Collectors.toList())); + HttpPolicyProviders.addBeforeRetryPolicies(policies); + policies.add(retryPolicy); + policies.add(new AddDatePolicy()); + policies.add(new BearerTokenAuthenticationPolicy(credential, scopes.toArray(new String[0]))); + policies.addAll(this.policies.stream() + .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) + .collect(Collectors.toList())); + HttpPolicyProviders.addAfterRetryPolicies(policies); + policies.add(new HttpLoggingPolicy(httpLogOptions)); + HttpPipeline httpPipeline = new HttpPipelineBuilder().httpClient(httpClient) + .policies(policies.toArray(new HttpPipelinePolicy[0])) + .build(); + return new ImpactReportingManager(httpPipeline, profile, defaultPollInterval); + } + } + + /** + * Gets the resource collection API of Operations. + * + * @return Resource collection API of Operations. + */ + public Operations operations() { + if (this.operations == null) { + this.operations = new OperationsImpl(clientObject.getOperations(), this); + } + return operations; + } + + /** + * Gets the resource collection API of WorkloadImpacts. It manages WorkloadImpact. + * + * @return Resource collection API of WorkloadImpacts. + */ + public WorkloadImpacts workloadImpacts() { + if (this.workloadImpacts == null) { + this.workloadImpacts = new WorkloadImpactsImpl(clientObject.getWorkloadImpacts(), this); + } + return workloadImpacts; + } + + /** + * Gets the resource collection API of ImpactCategories. + * + * @return Resource collection API of ImpactCategories. + */ + public ImpactCategories impactCategories() { + if (this.impactCategories == null) { + this.impactCategories = new ImpactCategoriesImpl(clientObject.getImpactCategories(), this); + } + return impactCategories; + } + + /** + * Gets the resource collection API of Insights. It manages Insight. + * + * @return Resource collection API of Insights. + */ + public Insights insights() { + if (this.insights == null) { + this.insights = new InsightsImpl(clientObject.getInsights(), this); + } + return insights; + } + + /** + * Gets the resource collection API of Connectors. It manages Connector. + * + * @return Resource collection API of Connectors. + */ + public Connectors connectors() { + if (this.connectors == null) { + this.connectors = new ConnectorsImpl(clientObject.getConnectors(), this); + } + return connectors; + } + + /** + * Gets wrapped service client ImpactReportingMgmtClient providing direct access to the underlying auto-generated + * API implementation, based on Azure REST API. + * + * @return Wrapped service client ImpactReportingMgmtClient. + */ + public ImpactReportingMgmtClient serviceClient() { + return this.clientObject; + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/ConnectorsClient.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/ConnectorsClient.java new file mode 100644 index 000000000000..56c431c39ac4 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/ConnectorsClient.java @@ -0,0 +1,180 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.impactreporting.fluent.models.ConnectorInner; +import com.azure.resourcemanager.impactreporting.models.ConnectorUpdate; + +/** + * An instance of this class provides access to all the operations defined in ConnectorsClient. + */ +public interface ConnectorsClient { + /** + * Get a Connector. + * + * @param connectorName The name of the connector. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Connector along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String connectorName, Context context); + + /** + * Get a Connector. + * + * @param connectorName The name of the connector. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Connector. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + ConnectorInner get(String connectorName); + + /** + * Create a Connector. + * + * @param connectorName The name of the connector. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of a connector is a resource that can be used to proactively report + * impacts against workloads in Azure to Microsoft. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, ConnectorInner> beginCreateOrUpdate(String connectorName, + ConnectorInner resource); + + /** + * Create a Connector. + * + * @param connectorName The name of the connector. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of a connector is a resource that can be used to proactively report + * impacts against workloads in Azure to Microsoft. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, ConnectorInner> beginCreateOrUpdate(String connectorName, + ConnectorInner resource, Context context); + + /** + * Create a Connector. + * + * @param connectorName The name of the connector. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a connector is a resource that can be used to proactively report impacts against workloads in Azure to + * Microsoft. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + ConnectorInner createOrUpdate(String connectorName, ConnectorInner resource); + + /** + * Create a Connector. + * + * @param connectorName The name of the connector. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a connector is a resource that can be used to proactively report impacts against workloads in Azure to + * Microsoft. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + ConnectorInner createOrUpdate(String connectorName, ConnectorInner resource, Context context); + + /** + * Update a Connector. + * + * @param connectorName The name of the connector. + * @param properties The resource properties to be updated. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a connector is a resource that can be used to proactively report impacts against workloads in Azure to + * Microsoft along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response updateWithResponse(String connectorName, ConnectorUpdate properties, Context context); + + /** + * Update a Connector. + * + * @param connectorName The name of the connector. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a connector is a resource that can be used to proactively report impacts against workloads in Azure to + * Microsoft. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + ConnectorInner update(String connectorName, ConnectorUpdate properties); + + /** + * Delete a Connector. + * + * @param connectorName The name of the connector. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response deleteWithResponse(String connectorName, Context context); + + /** + * Delete a Connector. + * + * @param connectorName The name of the connector. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void delete(String connectorName); + + /** + * List Connector resources by subscription ID. + * + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Connector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(); + + /** + * List Connector resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Connector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(Context context); +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/ImpactCategoriesClient.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/ImpactCategoriesClient.java new file mode 100644 index 000000000000..0cf5e082289e --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/ImpactCategoriesClient.java @@ -0,0 +1,68 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.resourcemanager.impactreporting.fluent.models.ImpactCategoryInner; + +/** + * An instance of this class provides access to all the operations defined in ImpactCategoriesClient. + */ +public interface ImpactCategoriesClient { + /** + * Get a ImpactCategory. + * + * @param impactCategoryName Name of the impact category. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ImpactCategory along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String impactCategoryName, Context context); + + /** + * Get a ImpactCategory. + * + * @param impactCategoryName Name of the impact category. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ImpactCategory. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + ImpactCategoryInner get(String impactCategoryName); + + /** + * List ImpactCategory resources by subscription. + * + * @param resourceType Filter by resource type. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ImpactCategory list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(String resourceType); + + /** + * List ImpactCategory resources by subscription. + * + * @param resourceType Filter by resource type. + * @param categoryName Filter by category name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ImpactCategory list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(String resourceType, String categoryName, Context context); +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/ImpactReportingMgmtClient.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/ImpactReportingMgmtClient.java new file mode 100644 index 000000000000..1d34aa3d6a2f --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/ImpactReportingMgmtClient.java @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.fluent; + +import com.azure.core.http.HttpPipeline; +import java.time.Duration; + +/** + * The interface for ImpactReportingMgmtClient class. + */ +public interface ImpactReportingMgmtClient { + /** + * Gets Service host. + * + * @return the endpoint value. + */ + String getEndpoint(); + + /** + * Gets Version parameter. + * + * @return the apiVersion value. + */ + String getApiVersion(); + + /** + * Gets The ID of the target subscription. The value must be an UUID. + * + * @return the subscriptionId value. + */ + String getSubscriptionId(); + + /** + * Gets The HTTP pipeline to send requests through. + * + * @return the httpPipeline value. + */ + HttpPipeline getHttpPipeline(); + + /** + * Gets The default poll interval for long-running operation. + * + * @return the defaultPollInterval value. + */ + Duration getDefaultPollInterval(); + + /** + * Gets the OperationsClient object to access its operations. + * + * @return the OperationsClient object. + */ + OperationsClient getOperations(); + + /** + * Gets the WorkloadImpactsClient object to access its operations. + * + * @return the WorkloadImpactsClient object. + */ + WorkloadImpactsClient getWorkloadImpacts(); + + /** + * Gets the ImpactCategoriesClient object to access its operations. + * + * @return the ImpactCategoriesClient object. + */ + ImpactCategoriesClient getImpactCategories(); + + /** + * Gets the InsightsClient object to access its operations. + * + * @return the InsightsClient object. + */ + InsightsClient getInsights(); + + /** + * Gets the ConnectorsClient object to access its operations. + * + * @return the ConnectorsClient object. + */ + ConnectorsClient getConnectors(); +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/InsightsClient.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/InsightsClient.java new file mode 100644 index 000000000000..3a1f688d725c --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/InsightsClient.java @@ -0,0 +1,125 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.resourcemanager.impactreporting.fluent.models.InsightInner; + +/** + * An instance of this class provides access to all the operations defined in InsightsClient. + */ +public interface InsightsClient { + /** + * Get Insight resources by workloadImpactName and insightName. + * + * @param workloadImpactName workloadImpact resource. + * @param insightName Name of the insight. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return insight resources by workloadImpactName and insightName along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String workloadImpactName, String insightName, Context context); + + /** + * Get Insight resources by workloadImpactName and insightName. + * + * @param workloadImpactName workloadImpact resource. + * @param insightName Name of the insight. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return insight resources by workloadImpactName and insightName. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + InsightInner get(String workloadImpactName, String insightName); + + /** + * List Insight resources by workloadImpactName. + * + * @param workloadImpactName workloadImpact resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Insight list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listBySubscription(String workloadImpactName); + + /** + * List Insight resources by workloadImpactName. + * + * @param workloadImpactName workloadImpact resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Insight list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listBySubscription(String workloadImpactName, Context context); + + /** + * Create Insight resource, This is Admin only operation. + * + * @param workloadImpactName workloadImpact resource. + * @param insightName Name of the insight. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return insight resource along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response createWithResponse(String workloadImpactName, String insightName, InsightInner resource, + Context context); + + /** + * Create Insight resource, This is Admin only operation. + * + * @param workloadImpactName workloadImpact resource. + * @param insightName Name of the insight. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return insight resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + InsightInner create(String workloadImpactName, String insightName, InsightInner resource); + + /** + * Delete Insight resource, This is Admin only operation. + * + * @param workloadImpactName workloadImpact resource. + * @param insightName Name of the insight. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response deleteWithResponse(String workloadImpactName, String insightName, Context context); + + /** + * Delete Insight resource, This is Admin only operation. + * + * @param workloadImpactName workloadImpact resource. + * @param insightName Name of the insight. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void delete(String workloadImpactName, String insightName); +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/OperationsClient.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/OperationsClient.java new file mode 100644 index 000000000000..880eab5fac15 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/OperationsClient.java @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.Context; +import com.azure.resourcemanager.impactreporting.fluent.models.OperationInner; + +/** + * An instance of this class provides access to all the operations defined in OperationsClient. + */ +public interface OperationsClient { + /** + * List the operations for the provider. + * + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(); + + /** + * List the operations for the provider. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(Context context); +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/WorkloadImpactsClient.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/WorkloadImpactsClient.java new file mode 100644 index 000000000000..9417005d6308 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/WorkloadImpactsClient.java @@ -0,0 +1,146 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.impactreporting.fluent.models.WorkloadImpactInner; + +/** + * An instance of this class provides access to all the operations defined in WorkloadImpactsClient. + */ +public interface WorkloadImpactsClient { + /** + * Create a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of workload Impact properties. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, WorkloadImpactInner> beginCreate(String workloadImpactName, + WorkloadImpactInner resource); + + /** + * Create a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of workload Impact properties. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, WorkloadImpactInner> beginCreate(String workloadImpactName, + WorkloadImpactInner resource, Context context); + + /** + * Create a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return workload Impact properties. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + WorkloadImpactInner create(String workloadImpactName, WorkloadImpactInner resource); + + /** + * Create a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return workload Impact properties. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + WorkloadImpactInner create(String workloadImpactName, WorkloadImpactInner resource, Context context); + + /** + * Get a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a WorkloadImpact along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String workloadImpactName, Context context); + + /** + * Get a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a WorkloadImpact. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + WorkloadImpactInner get(String workloadImpactName); + + /** + * Delete a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response deleteWithResponse(String workloadImpactName, Context context); + + /** + * Delete a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void delete(String workloadImpactName); + + /** + * List WorkloadImpact resources by subscription ID. + * + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a WorkloadImpact list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(); + + /** + * List WorkloadImpact resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a WorkloadImpact list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(Context context); +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/models/ConnectorInner.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/models/ConnectorInner.java new file mode 100644 index 000000000000..66cb36af1478 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/models/ConnectorInner.java @@ -0,0 +1,166 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.impactreporting.models.ConnectorProperties; +import java.io.IOException; + +/** + * A connector is a resource that can be used to proactively report impacts against workloads in Azure to Microsoft. + */ +@Fluent +public final class ConnectorInner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private ConnectorProperties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of ConnectorInner class. + */ + public ConnectorInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public ConnectorProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the ConnectorInner object itself. + */ + public ConnectorInner withProperties(ConnectorProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ConnectorInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ConnectorInner 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 ConnectorInner. + */ + public static ConnectorInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ConnectorInner deserializedConnectorInner = new ConnectorInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedConnectorInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedConnectorInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedConnectorInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedConnectorInner.properties = ConnectorProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedConnectorInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedConnectorInner; + }); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/models/ImpactCategoryInner.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/models/ImpactCategoryInner.java new file mode 100644 index 000000000000..2390fdd2ec81 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/models/ImpactCategoryInner.java @@ -0,0 +1,155 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.fluent.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.impactreporting.models.ImpactCategoryProperties; +import java.io.IOException; + +/** + * ImpactCategory resource. + */ +@Immutable +public final class ImpactCategoryInner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private ImpactCategoryProperties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of ImpactCategoryInner class. + */ + private ImpactCategoryInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public ImpactCategoryProperties properties() { + return this.properties; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ImpactCategoryInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ImpactCategoryInner 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 ImpactCategoryInner. + */ + public static ImpactCategoryInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ImpactCategoryInner deserializedImpactCategoryInner = new ImpactCategoryInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedImpactCategoryInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedImpactCategoryInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedImpactCategoryInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedImpactCategoryInner.properties = ImpactCategoryProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedImpactCategoryInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedImpactCategoryInner; + }); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/models/InsightInner.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/models/InsightInner.java new file mode 100644 index 000000000000..cd435fbfa377 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/models/InsightInner.java @@ -0,0 +1,166 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.impactreporting.models.InsightProperties; +import java.io.IOException; + +/** + * Insight resource. + */ +@Fluent +public final class InsightInner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private InsightProperties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of InsightInner class. + */ + public InsightInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public InsightProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the InsightInner object itself. + */ + public InsightInner withProperties(InsightProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of InsightInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of InsightInner 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 InsightInner. + */ + public static InsightInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + InsightInner deserializedInsightInner = new InsightInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedInsightInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedInsightInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedInsightInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedInsightInner.properties = InsightProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedInsightInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedInsightInner; + }); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/models/OperationInner.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/models/OperationInner.java new file mode 100644 index 000000000000..58e51e8657bd --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/models/OperationInner.java @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.fluent.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 com.azure.resourcemanager.impactreporting.models.ActionType; +import com.azure.resourcemanager.impactreporting.models.OperationDisplay; +import com.azure.resourcemanager.impactreporting.models.Origin; +import java.io.IOException; + +/** + * Details of a REST API operation, returned from the Resource Provider Operations API. + */ +@Immutable +public final class OperationInner implements JsonSerializable { + /* + * The name of the operation, as per Resource-Based Access Control (RBAC). Examples: + * "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action" + */ + private String name; + + /* + * Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure + * Resource Manager/control-plane operations. + */ + private Boolean isDataAction; + + /* + * Localized display information for this particular operation. + */ + private OperationDisplay display; + + /* + * The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default + * value is "user,system" + */ + private Origin origin; + + /* + * Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + */ + private ActionType actionType; + + /** + * Creates an instance of OperationInner class. + */ + private OperationInner() { + } + + /** + * Get the name property: The name of the operation, as per Resource-Based Access Control (RBAC). Examples: + * "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action". + * + * @return the name value. + */ + public String name() { + return this.name; + } + + /** + * Get the isDataAction property: Whether the operation applies to data-plane. This is "true" for data-plane + * operations and "false" for Azure Resource Manager/control-plane operations. + * + * @return the isDataAction value. + */ + public Boolean isDataAction() { + return this.isDataAction; + } + + /** + * Get the display property: Localized display information for this particular operation. + * + * @return the display value. + */ + public OperationDisplay display() { + return this.display; + } + + /** + * Get the origin property: The intended executor of the operation; as in Resource Based Access Control (RBAC) and + * audit logs UX. Default value is "user,system". + * + * @return the origin value. + */ + public Origin origin() { + return this.origin; + } + + /** + * Get the actionType property: Extensible enum. Indicates the action type. "Internal" refers to actions that are + * for internal only APIs. + * + * @return the actionType value. + */ + public ActionType actionType() { + return this.actionType; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (display() != null) { + display().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("display", this.display); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OperationInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OperationInner 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 OperationInner. + */ + public static OperationInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OperationInner deserializedOperationInner = new OperationInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("name".equals(fieldName)) { + deserializedOperationInner.name = reader.getString(); + } else if ("isDataAction".equals(fieldName)) { + deserializedOperationInner.isDataAction = reader.getNullable(JsonReader::getBoolean); + } else if ("display".equals(fieldName)) { + deserializedOperationInner.display = OperationDisplay.fromJson(reader); + } else if ("origin".equals(fieldName)) { + deserializedOperationInner.origin = Origin.fromString(reader.getString()); + } else if ("actionType".equals(fieldName)) { + deserializedOperationInner.actionType = ActionType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedOperationInner; + }); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/models/WorkloadImpactInner.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/models/WorkloadImpactInner.java new file mode 100644 index 000000000000..8b88dcdcd46d --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/models/WorkloadImpactInner.java @@ -0,0 +1,166 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.impactreporting.models.WorkloadImpactProperties; +import java.io.IOException; + +/** + * Workload Impact properties. + */ +@Fluent +public final class WorkloadImpactInner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private WorkloadImpactProperties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of WorkloadImpactInner class. + */ + public WorkloadImpactInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public WorkloadImpactProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the WorkloadImpactInner object itself. + */ + public WorkloadImpactInner withProperties(WorkloadImpactProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of WorkloadImpactInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of WorkloadImpactInner 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 WorkloadImpactInner. + */ + public static WorkloadImpactInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + WorkloadImpactInner deserializedWorkloadImpactInner = new WorkloadImpactInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedWorkloadImpactInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedWorkloadImpactInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedWorkloadImpactInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedWorkloadImpactInner.properties = WorkloadImpactProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedWorkloadImpactInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedWorkloadImpactInner; + }); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/models/package-info.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/models/package-info.java new file mode 100644 index 000000000000..2b5139f0ee9d --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/models/package-info.java @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +/** + * Package containing the inner data models for ImpactReporting. + */ +package com.azure.resourcemanager.impactreporting.fluent.models; diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/package-info.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/package-info.java new file mode 100644 index 000000000000..9c52d46eb405 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/fluent/package-info.java @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +/** + * Package containing the service clients for ImpactReporting. + */ +package com.azure.resourcemanager.impactreporting.fluent; diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/ConnectorImpl.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/ConnectorImpl.java new file mode 100644 index 000000000000..f85d8649399d --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/ConnectorImpl.java @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.implementation; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.impactreporting.fluent.models.ConnectorInner; +import com.azure.resourcemanager.impactreporting.models.Connector; +import com.azure.resourcemanager.impactreporting.models.ConnectorProperties; +import com.azure.resourcemanager.impactreporting.models.ConnectorUpdate; +import com.azure.resourcemanager.impactreporting.models.ConnectorUpdateProperties; + +public final class ConnectorImpl implements Connector, Connector.Definition, Connector.Update { + private ConnectorInner innerObject; + + private final com.azure.resourcemanager.impactreporting.ImpactReportingManager serviceManager; + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public ConnectorProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public ConnectorInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.impactreporting.ImpactReportingManager manager() { + return this.serviceManager; + } + + private String connectorName; + + private ConnectorUpdate updateProperties; + + public Connector create() { + this.innerObject = serviceManager.serviceClient() + .getConnectors() + .createOrUpdate(connectorName, this.innerModel(), Context.NONE); + return this; + } + + public Connector create(Context context) { + this.innerObject + = serviceManager.serviceClient().getConnectors().createOrUpdate(connectorName, this.innerModel(), context); + return this; + } + + ConnectorImpl(String name, com.azure.resourcemanager.impactreporting.ImpactReportingManager serviceManager) { + this.innerObject = new ConnectorInner(); + this.serviceManager = serviceManager; + this.connectorName = name; + } + + public ConnectorImpl update() { + this.updateProperties = new ConnectorUpdate(); + return this; + } + + public Connector apply() { + this.innerObject = serviceManager.serviceClient() + .getConnectors() + .updateWithResponse(connectorName, updateProperties, Context.NONE) + .getValue(); + return this; + } + + public Connector apply(Context context) { + this.innerObject = serviceManager.serviceClient() + .getConnectors() + .updateWithResponse(connectorName, updateProperties, context) + .getValue(); + return this; + } + + ConnectorImpl(ConnectorInner innerObject, + com.azure.resourcemanager.impactreporting.ImpactReportingManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + this.connectorName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "connectors"); + } + + public Connector refresh() { + this.innerObject + = serviceManager.serviceClient().getConnectors().getWithResponse(connectorName, Context.NONE).getValue(); + return this; + } + + public Connector refresh(Context context) { + this.innerObject + = serviceManager.serviceClient().getConnectors().getWithResponse(connectorName, context).getValue(); + return this; + } + + public ConnectorImpl withProperties(ConnectorProperties properties) { + this.innerModel().withProperties(properties); + return this; + } + + public ConnectorImpl withProperties(ConnectorUpdateProperties properties) { + this.updateProperties.withProperties(properties); + return this; + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/ConnectorsClientImpl.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/ConnectorsClientImpl.java new file mode 100644 index 000000000000..6880ac54028c --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/ConnectorsClientImpl.java @@ -0,0 +1,835 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.Patch; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Put; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.core.util.polling.PollerFlux; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.impactreporting.fluent.ConnectorsClient; +import com.azure.resourcemanager.impactreporting.fluent.models.ConnectorInner; +import com.azure.resourcemanager.impactreporting.implementation.models.ConnectorListResult; +import com.azure.resourcemanager.impactreporting.models.ConnectorUpdate; +import java.nio.ByteBuffer; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in ConnectorsClient. + */ +public final class ConnectorsClientImpl implements ConnectorsClient { + /** + * The proxy service used to perform REST calls. + */ + private final ConnectorsService service; + + /** + * The service client containing this operation class. + */ + private final ImpactReportingMgmtClientImpl client; + + /** + * Initializes an instance of ConnectorsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + ConnectorsClientImpl(ImpactReportingMgmtClientImpl client) { + this.service + = RestProxy.create(ConnectorsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for ImpactReportingMgmtClientConnectors to be used by the proxy service + * to perform REST calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "ImpactReportingMgmtC") + public interface ConnectorsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/providers/Microsoft.Impact/connectors/{connectorName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("connectorName") String connectorName, @HeaderParam("Accept") String accept, Context context); + + @Put("/subscriptions/{subscriptionId}/providers/Microsoft.Impact/connectors/{connectorName}") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> createOrUpdate(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("connectorName") String connectorName, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") ConnectorInner resource, + Context context); + + @Patch("/subscriptions/{subscriptionId}/providers/Microsoft.Impact/connectors/{connectorName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> update(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("connectorName") String connectorName, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") ConnectorUpdate properties, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Delete("/subscriptions/{subscriptionId}/providers/Microsoft.Impact/connectors/{connectorName}") + @ExpectedResponses({ 200, 204 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> delete(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("connectorName") String connectorName, @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/providers/Microsoft.Impact/connectors") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> list(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listBySubscriptionNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * Get a Connector. + * + * @param connectorName The name of the connector. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Connector along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String connectorName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (connectorName == null) { + return Mono.error(new IllegalArgumentException("Parameter connectorName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), connectorName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a Connector. + * + * @param connectorName The name of the connector. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Connector along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String connectorName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (connectorName == null) { + return Mono.error(new IllegalArgumentException("Parameter connectorName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + connectorName, accept, context); + } + + /** + * Get a Connector. + * + * @param connectorName The name of the connector. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Connector on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String connectorName) { + return getWithResponseAsync(connectorName).flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a Connector. + * + * @param connectorName The name of the connector. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Connector along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String connectorName, Context context) { + return getWithResponseAsync(connectorName, context).block(); + } + + /** + * Get a Connector. + * + * @param connectorName The name of the connector. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Connector. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public ConnectorInner get(String connectorName) { + return getWithResponse(connectorName, Context.NONE).getValue(); + } + + /** + * Create a Connector. + * + * @param connectorName The name of the connector. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a connector is a resource that can be used to proactively report impacts against workloads in Azure to + * Microsoft along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createOrUpdateWithResponseAsync(String connectorName, + ConnectorInner resource) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (connectorName == null) { + return Mono.error(new IllegalArgumentException("Parameter connectorName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.createOrUpdate(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), connectorName, contentType, accept, resource, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Create a Connector. + * + * @param connectorName The name of the connector. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a connector is a resource that can be used to proactively report impacts against workloads in Azure to + * Microsoft along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createOrUpdateWithResponseAsync(String connectorName, + ConnectorInner resource, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (connectorName == null) { + return Mono.error(new IllegalArgumentException("Parameter connectorName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.createOrUpdate(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), connectorName, contentType, accept, resource, context); + } + + /** + * Create a Connector. + * + * @param connectorName The name of the connector. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of a connector is a resource that can be used to proactively report + * impacts against workloads in Azure to Microsoft. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, ConnectorInner> beginCreateOrUpdateAsync(String connectorName, + ConnectorInner resource) { + Mono>> mono = createOrUpdateWithResponseAsync(connectorName, resource); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + ConnectorInner.class, ConnectorInner.class, this.client.getContext()); + } + + /** + * Create a Connector. + * + * @param connectorName The name of the connector. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of a connector is a resource that can be used to proactively report + * impacts against workloads in Azure to Microsoft. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, ConnectorInner> beginCreateOrUpdateAsync(String connectorName, + ConnectorInner resource, Context context) { + context = this.client.mergeContext(context); + Mono>> mono = createOrUpdateWithResponseAsync(connectorName, resource, context); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + ConnectorInner.class, ConnectorInner.class, context); + } + + /** + * Create a Connector. + * + * @param connectorName The name of the connector. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of a connector is a resource that can be used to proactively report + * impacts against workloads in Azure to Microsoft. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, ConnectorInner> beginCreateOrUpdate(String connectorName, + ConnectorInner resource) { + return this.beginCreateOrUpdateAsync(connectorName, resource).getSyncPoller(); + } + + /** + * Create a Connector. + * + * @param connectorName The name of the connector. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of a connector is a resource that can be used to proactively report + * impacts against workloads in Azure to Microsoft. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, ConnectorInner> beginCreateOrUpdate(String connectorName, + ConnectorInner resource, Context context) { + return this.beginCreateOrUpdateAsync(connectorName, resource, context).getSyncPoller(); + } + + /** + * Create a Connector. + * + * @param connectorName The name of the connector. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a connector is a resource that can be used to proactively report impacts against workloads in Azure to + * Microsoft on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createOrUpdateAsync(String connectorName, ConnectorInner resource) { + return beginCreateOrUpdateAsync(connectorName, resource).last().flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a Connector. + * + * @param connectorName The name of the connector. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a connector is a resource that can be used to proactively report impacts against workloads in Azure to + * Microsoft on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createOrUpdateAsync(String connectorName, ConnectorInner resource, Context context) { + return beginCreateOrUpdateAsync(connectorName, resource, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a Connector. + * + * @param connectorName The name of the connector. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a connector is a resource that can be used to proactively report impacts against workloads in Azure to + * Microsoft. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public ConnectorInner createOrUpdate(String connectorName, ConnectorInner resource) { + return createOrUpdateAsync(connectorName, resource).block(); + } + + /** + * Create a Connector. + * + * @param connectorName The name of the connector. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a connector is a resource that can be used to proactively report impacts against workloads in Azure to + * Microsoft. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public ConnectorInner createOrUpdate(String connectorName, ConnectorInner resource, Context context) { + return createOrUpdateAsync(connectorName, resource, context).block(); + } + + /** + * Update a Connector. + * + * @param connectorName The name of the connector. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a connector is a resource that can be used to proactively report impacts against workloads in Azure to + * Microsoft along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> updateWithResponseAsync(String connectorName, ConnectorUpdate properties) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (connectorName == null) { + return Mono.error(new IllegalArgumentException("Parameter connectorName is required and cannot be null.")); + } + if (properties == null) { + return Mono.error(new IllegalArgumentException("Parameter properties is required and cannot be null.")); + } else { + properties.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.update(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), connectorName, contentType, accept, properties, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Update a Connector. + * + * @param connectorName The name of the connector. + * @param properties The resource properties to be updated. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a connector is a resource that can be used to proactively report impacts against workloads in Azure to + * Microsoft along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> updateWithResponseAsync(String connectorName, ConnectorUpdate properties, + Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (connectorName == null) { + return Mono.error(new IllegalArgumentException("Parameter connectorName is required and cannot be null.")); + } + if (properties == null) { + return Mono.error(new IllegalArgumentException("Parameter properties is required and cannot be null.")); + } else { + properties.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.update(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + connectorName, contentType, accept, properties, context); + } + + /** + * Update a Connector. + * + * @param connectorName The name of the connector. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a connector is a resource that can be used to proactively report impacts against workloads in Azure to + * Microsoft on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono updateAsync(String connectorName, ConnectorUpdate properties) { + return updateWithResponseAsync(connectorName, properties).flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Update a Connector. + * + * @param connectorName The name of the connector. + * @param properties The resource properties to be updated. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a connector is a resource that can be used to proactively report impacts against workloads in Azure to + * Microsoft along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response updateWithResponse(String connectorName, ConnectorUpdate properties, + Context context) { + return updateWithResponseAsync(connectorName, properties, context).block(); + } + + /** + * Update a Connector. + * + * @param connectorName The name of the connector. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a connector is a resource that can be used to proactively report impacts against workloads in Azure to + * Microsoft. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public ConnectorInner update(String connectorName, ConnectorUpdate properties) { + return updateWithResponse(connectorName, properties, Context.NONE).getValue(); + } + + /** + * Delete a Connector. + * + * @param connectorName The name of the connector. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String connectorName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (connectorName == null) { + return Mono.error(new IllegalArgumentException("Parameter connectorName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.delete(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), connectorName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Delete a Connector. + * + * @param connectorName The name of the connector. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String connectorName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (connectorName == null) { + return Mono.error(new IllegalArgumentException("Parameter connectorName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.delete(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + connectorName, accept, context); + } + + /** + * Delete a Connector. + * + * @param connectorName The name of the connector. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono deleteAsync(String connectorName) { + return deleteWithResponseAsync(connectorName).flatMap(ignored -> Mono.empty()); + } + + /** + * Delete a Connector. + * + * @param connectorName The name of the connector. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String connectorName, Context context) { + return deleteWithResponseAsync(connectorName, context).block(); + } + + /** + * Delete a Connector. + * + * @param connectorName The name of the connector. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String connectorName) { + deleteWithResponse(connectorName, Context.NONE); + } + + /** + * List Connector resources by subscription ID. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Connector list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync() { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.list(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), + res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List Connector resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Connector list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync(Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .list(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), accept, + context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List Connector resources by subscription ID. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Connector list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync() { + return new PagedFlux<>(() -> listSinglePageAsync(), + nextLink -> listBySubscriptionNextSinglePageAsync(nextLink)); + } + + /** + * List Connector resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Connector list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync(Context context) { + return new PagedFlux<>(() -> listSinglePageAsync(context), + nextLink -> listBySubscriptionNextSinglePageAsync(nextLink, context)); + } + + /** + * List Connector resources by subscription ID. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Connector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list() { + return new PagedIterable<>(listAsync()); + } + + /** + * List Connector resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Connector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(Context context) { + return new PagedIterable<>(listAsync(context)); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Connector list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySubscriptionNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), + res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Connector list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySubscriptionNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/ConnectorsImpl.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/ConnectorsImpl.java new file mode 100644 index 000000000000..8eb583879c8c --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/ConnectorsImpl.java @@ -0,0 +1,114 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.impactreporting.fluent.ConnectorsClient; +import com.azure.resourcemanager.impactreporting.fluent.models.ConnectorInner; +import com.azure.resourcemanager.impactreporting.models.Connector; +import com.azure.resourcemanager.impactreporting.models.Connectors; + +public final class ConnectorsImpl implements Connectors { + private static final ClientLogger LOGGER = new ClientLogger(ConnectorsImpl.class); + + private final ConnectorsClient innerClient; + + private final com.azure.resourcemanager.impactreporting.ImpactReportingManager serviceManager; + + public ConnectorsImpl(ConnectorsClient innerClient, + com.azure.resourcemanager.impactreporting.ImpactReportingManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public Response getWithResponse(String connectorName, Context context) { + Response inner = this.serviceClient().getWithResponse(connectorName, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new ConnectorImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public Connector get(String connectorName) { + ConnectorInner inner = this.serviceClient().get(connectorName); + if (inner != null) { + return new ConnectorImpl(inner, this.manager()); + } else { + return null; + } + } + + public Response deleteWithResponse(String connectorName, Context context) { + return this.serviceClient().deleteWithResponse(connectorName, context); + } + + public void delete(String connectorName) { + this.serviceClient().delete(connectorName); + } + + public PagedIterable list() { + PagedIterable inner = this.serviceClient().list(); + return ResourceManagerUtils.mapPage(inner, inner1 -> new ConnectorImpl(inner1, this.manager())); + } + + public PagedIterable list(Context context) { + PagedIterable inner = this.serviceClient().list(context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new ConnectorImpl(inner1, this.manager())); + } + + public Connector getById(String id) { + String connectorName = ResourceManagerUtils.getValueFromIdByName(id, "connectors"); + if (connectorName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'connectors'.", id))); + } + return this.getWithResponse(connectorName, Context.NONE).getValue(); + } + + public Response getByIdWithResponse(String id, Context context) { + String connectorName = ResourceManagerUtils.getValueFromIdByName(id, "connectors"); + if (connectorName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'connectors'.", id))); + } + return this.getWithResponse(connectorName, context); + } + + public void deleteById(String id) { + String connectorName = ResourceManagerUtils.getValueFromIdByName(id, "connectors"); + if (connectorName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'connectors'.", id))); + } + this.deleteWithResponse(connectorName, Context.NONE); + } + + public Response deleteByIdWithResponse(String id, Context context) { + String connectorName = ResourceManagerUtils.getValueFromIdByName(id, "connectors"); + if (connectorName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'connectors'.", id))); + } + return this.deleteWithResponse(connectorName, context); + } + + private ConnectorsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.impactreporting.ImpactReportingManager manager() { + return this.serviceManager; + } + + public ConnectorImpl define(String name) { + return new ConnectorImpl(name, this.manager()); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/ImpactCategoriesClientImpl.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/ImpactCategoriesClientImpl.java new file mode 100644 index 000000000000..4d69f803ec17 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/ImpactCategoriesClientImpl.java @@ -0,0 +1,398 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.implementation; + +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.resourcemanager.impactreporting.fluent.ImpactCategoriesClient; +import com.azure.resourcemanager.impactreporting.fluent.models.ImpactCategoryInner; +import com.azure.resourcemanager.impactreporting.implementation.models.ImpactCategoryListResult; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in ImpactCategoriesClient. + */ +public final class ImpactCategoriesClientImpl implements ImpactCategoriesClient { + /** + * The proxy service used to perform REST calls. + */ + private final ImpactCategoriesService service; + + /** + * The service client containing this operation class. + */ + private final ImpactReportingMgmtClientImpl client; + + /** + * Initializes an instance of ImpactCategoriesClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + ImpactCategoriesClientImpl(ImpactReportingMgmtClientImpl client) { + this.service + = RestProxy.create(ImpactCategoriesService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for ImpactReportingMgmtClientImpactCategories to be used by the proxy + * service to perform REST calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "ImpactReportingMgmtC") + public interface ImpactCategoriesService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/providers/Microsoft.Impact/impactCategories/{impactCategoryName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("impactCategoryName") String impactCategoryName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/providers/Microsoft.Impact/impactCategories") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> list(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @QueryParam("categoryName") String categoryName, @QueryParam("resourceType") String resourceType, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listBySubscriptionNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * Get a ImpactCategory. + * + * @param impactCategoryName Name of the impact category. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ImpactCategory along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String impactCategoryName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (impactCategoryName == null) { + return Mono + .error(new IllegalArgumentException("Parameter impactCategoryName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), impactCategoryName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a ImpactCategory. + * + * @param impactCategoryName Name of the impact category. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ImpactCategory along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String impactCategoryName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (impactCategoryName == null) { + return Mono + .error(new IllegalArgumentException("Parameter impactCategoryName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + impactCategoryName, accept, context); + } + + /** + * Get a ImpactCategory. + * + * @param impactCategoryName Name of the impact category. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ImpactCategory on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String impactCategoryName) { + return getWithResponseAsync(impactCategoryName).flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a ImpactCategory. + * + * @param impactCategoryName Name of the impact category. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ImpactCategory along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String impactCategoryName, Context context) { + return getWithResponseAsync(impactCategoryName, context).block(); + } + + /** + * Get a ImpactCategory. + * + * @param impactCategoryName Name of the impact category. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ImpactCategory. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public ImpactCategoryInner get(String impactCategoryName) { + return getWithResponse(impactCategoryName, Context.NONE).getValue(); + } + + /** + * List ImpactCategory resources by subscription. + * + * @param resourceType Filter by resource type. + * @param categoryName Filter by category name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ImpactCategory list operation along with {@link PagedResponse} on successful completion + * of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync(String resourceType, String categoryName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceType == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceType is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.list(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), categoryName, resourceType, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List ImpactCategory resources by subscription. + * + * @param resourceType Filter by resource type. + * @param categoryName Filter by category name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ImpactCategory list operation along with {@link PagedResponse} on successful completion + * of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync(String resourceType, String categoryName, + Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceType == null) { + return Mono.error(new IllegalArgumentException("Parameter resourceType is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .list(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), categoryName, + resourceType, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List ImpactCategory resources by subscription. + * + * @param resourceType Filter by resource type. + * @param categoryName Filter by category name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ImpactCategory list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync(String resourceType, String categoryName) { + return new PagedFlux<>(() -> listSinglePageAsync(resourceType, categoryName), + nextLink -> listBySubscriptionNextSinglePageAsync(nextLink)); + } + + /** + * List ImpactCategory resources by subscription. + * + * @param resourceType Filter by resource type. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ImpactCategory list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync(String resourceType) { + final String categoryName = null; + return new PagedFlux<>(() -> listSinglePageAsync(resourceType, categoryName), + nextLink -> listBySubscriptionNextSinglePageAsync(nextLink)); + } + + /** + * List ImpactCategory resources by subscription. + * + * @param resourceType Filter by resource type. + * @param categoryName Filter by category name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ImpactCategory list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync(String resourceType, String categoryName, Context context) { + return new PagedFlux<>(() -> listSinglePageAsync(resourceType, categoryName, context), + nextLink -> listBySubscriptionNextSinglePageAsync(nextLink, context)); + } + + /** + * List ImpactCategory resources by subscription. + * + * @param resourceType Filter by resource type. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ImpactCategory list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(String resourceType) { + final String categoryName = null; + return new PagedIterable<>(listAsync(resourceType, categoryName)); + } + + /** + * List ImpactCategory resources by subscription. + * + * @param resourceType Filter by resource type. + * @param categoryName Filter by category name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ImpactCategory list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(String resourceType, String categoryName, Context context) { + return new PagedIterable<>(listAsync(resourceType, categoryName, context)); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ImpactCategory list operation along with {@link PagedResponse} on successful completion + * of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySubscriptionNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ImpactCategory list operation along with {@link PagedResponse} on successful completion + * of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySubscriptionNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/ImpactCategoriesImpl.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/ImpactCategoriesImpl.java new file mode 100644 index 000000000000..17e528efc89a --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/ImpactCategoriesImpl.java @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.impactreporting.fluent.ImpactCategoriesClient; +import com.azure.resourcemanager.impactreporting.fluent.models.ImpactCategoryInner; +import com.azure.resourcemanager.impactreporting.models.ImpactCategories; +import com.azure.resourcemanager.impactreporting.models.ImpactCategory; + +public final class ImpactCategoriesImpl implements ImpactCategories { + private static final ClientLogger LOGGER = new ClientLogger(ImpactCategoriesImpl.class); + + private final ImpactCategoriesClient innerClient; + + private final com.azure.resourcemanager.impactreporting.ImpactReportingManager serviceManager; + + public ImpactCategoriesImpl(ImpactCategoriesClient innerClient, + com.azure.resourcemanager.impactreporting.ImpactReportingManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public Response getWithResponse(String impactCategoryName, Context context) { + Response inner = this.serviceClient().getWithResponse(impactCategoryName, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new ImpactCategoryImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public ImpactCategory get(String impactCategoryName) { + ImpactCategoryInner inner = this.serviceClient().get(impactCategoryName); + if (inner != null) { + return new ImpactCategoryImpl(inner, this.manager()); + } else { + return null; + } + } + + public PagedIterable list(String resourceType) { + PagedIterable inner = this.serviceClient().list(resourceType); + return ResourceManagerUtils.mapPage(inner, inner1 -> new ImpactCategoryImpl(inner1, this.manager())); + } + + public PagedIterable list(String resourceType, String categoryName, Context context) { + PagedIterable inner = this.serviceClient().list(resourceType, categoryName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new ImpactCategoryImpl(inner1, this.manager())); + } + + private ImpactCategoriesClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.impactreporting.ImpactReportingManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/ImpactCategoryImpl.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/ImpactCategoryImpl.java new file mode 100644 index 000000000000..a6d34573da34 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/ImpactCategoryImpl.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.implementation; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.impactreporting.fluent.models.ImpactCategoryInner; +import com.azure.resourcemanager.impactreporting.models.ImpactCategory; +import com.azure.resourcemanager.impactreporting.models.ImpactCategoryProperties; + +public final class ImpactCategoryImpl implements ImpactCategory { + private ImpactCategoryInner innerObject; + + private final com.azure.resourcemanager.impactreporting.ImpactReportingManager serviceManager; + + ImpactCategoryImpl(ImpactCategoryInner innerObject, + com.azure.resourcemanager.impactreporting.ImpactReportingManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public ImpactCategoryProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public ImpactCategoryInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.impactreporting.ImpactReportingManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/ImpactReportingMgmtClientBuilder.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/ImpactReportingMgmtClientBuilder.java new file mode 100644 index 000000000000..013177e0c82d --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/ImpactReportingMgmtClientBuilder.java @@ -0,0 +1,138 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.implementation; + +import com.azure.core.annotation.ServiceClientBuilder; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.policy.RetryPolicy; +import com.azure.core.http.policy.UserAgentPolicy; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.serializer.SerializerFactory; +import com.azure.core.util.serializer.SerializerAdapter; +import java.time.Duration; + +/** + * A builder for creating a new instance of the ImpactReportingMgmtClientImpl type. + */ +@ServiceClientBuilder(serviceClients = { ImpactReportingMgmtClientImpl.class }) +public final class ImpactReportingMgmtClientBuilder { + /* + * Service host + */ + private String endpoint; + + /** + * Sets Service host. + * + * @param endpoint the endpoint value. + * @return the ImpactReportingMgmtClientBuilder. + */ + public ImpactReportingMgmtClientBuilder endpoint(String endpoint) { + this.endpoint = endpoint; + return this; + } + + /* + * The ID of the target subscription. The value must be an UUID. + */ + private String subscriptionId; + + /** + * Sets The ID of the target subscription. The value must be an UUID. + * + * @param subscriptionId the subscriptionId value. + * @return the ImpactReportingMgmtClientBuilder. + */ + public ImpactReportingMgmtClientBuilder subscriptionId(String subscriptionId) { + this.subscriptionId = subscriptionId; + return this; + } + + /* + * The environment to connect to + */ + private AzureEnvironment environment; + + /** + * Sets The environment to connect to. + * + * @param environment the environment value. + * @return the ImpactReportingMgmtClientBuilder. + */ + public ImpactReportingMgmtClientBuilder environment(AzureEnvironment environment) { + this.environment = environment; + 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 ImpactReportingMgmtClientBuilder. + */ + public ImpactReportingMgmtClientBuilder pipeline(HttpPipeline pipeline) { + this.pipeline = pipeline; + return this; + } + + /* + * The default poll interval for long-running operation + */ + private Duration defaultPollInterval; + + /** + * Sets The default poll interval for long-running operation. + * + * @param defaultPollInterval the defaultPollInterval value. + * @return the ImpactReportingMgmtClientBuilder. + */ + public ImpactReportingMgmtClientBuilder defaultPollInterval(Duration defaultPollInterval) { + this.defaultPollInterval = defaultPollInterval; + 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 ImpactReportingMgmtClientBuilder. + */ + public ImpactReportingMgmtClientBuilder serializerAdapter(SerializerAdapter serializerAdapter) { + this.serializerAdapter = serializerAdapter; + return this; + } + + /** + * Builds an instance of ImpactReportingMgmtClientImpl with the provided parameters. + * + * @return an instance of ImpactReportingMgmtClientImpl. + */ + public ImpactReportingMgmtClientImpl buildClient() { + String localEndpoint = (endpoint != null) ? endpoint : "https://management.azure.com"; + AzureEnvironment localEnvironment = (environment != null) ? environment : AzureEnvironment.AZURE; + HttpPipeline localPipeline = (pipeline != null) + ? pipeline + : new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build(); + Duration localDefaultPollInterval + = (defaultPollInterval != null) ? defaultPollInterval : Duration.ofSeconds(30); + SerializerAdapter localSerializerAdapter = (serializerAdapter != null) + ? serializerAdapter + : SerializerFactory.createDefaultManagementSerializerAdapter(); + ImpactReportingMgmtClientImpl client = new ImpactReportingMgmtClientImpl(localPipeline, localSerializerAdapter, + localDefaultPollInterval, localEnvironment, localEndpoint, this.subscriptionId); + return client; + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/ImpactReportingMgmtClientImpl.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/ImpactReportingMgmtClientImpl.java new file mode 100644 index 000000000000..768eba148077 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/ImpactReportingMgmtClientImpl.java @@ -0,0 +1,352 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.implementation; + +import com.azure.core.annotation.ServiceClient; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.HttpHeaders; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpResponse; +import com.azure.core.http.rest.Response; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.exception.ManagementError; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.management.polling.PollResult; +import com.azure.core.management.polling.PollerFactory; +import com.azure.core.util.Context; +import com.azure.core.util.CoreUtils; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.polling.AsyncPollResponse; +import com.azure.core.util.polling.LongRunningOperationStatus; +import com.azure.core.util.polling.PollerFlux; +import com.azure.core.util.serializer.SerializerAdapter; +import com.azure.core.util.serializer.SerializerEncoding; +import com.azure.resourcemanager.impactreporting.fluent.ConnectorsClient; +import com.azure.resourcemanager.impactreporting.fluent.ImpactCategoriesClient; +import com.azure.resourcemanager.impactreporting.fluent.ImpactReportingMgmtClient; +import com.azure.resourcemanager.impactreporting.fluent.InsightsClient; +import com.azure.resourcemanager.impactreporting.fluent.OperationsClient; +import com.azure.resourcemanager.impactreporting.fluent.WorkloadImpactsClient; +import java.io.IOException; +import java.lang.reflect.Type; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * Initializes a new instance of the ImpactReportingMgmtClientImpl type. + */ +@ServiceClient(builder = ImpactReportingMgmtClientBuilder.class) +public final class ImpactReportingMgmtClientImpl implements ImpactReportingMgmtClient { + /** + * Service host. + */ + private final String endpoint; + + /** + * Gets Service host. + * + * @return the endpoint value. + */ + public String getEndpoint() { + return this.endpoint; + } + + /** + * Version parameter. + */ + private final String apiVersion; + + /** + * Gets Version parameter. + * + * @return the apiVersion value. + */ + public String getApiVersion() { + return this.apiVersion; + } + + /** + * The ID of the target subscription. The value must be an UUID. + */ + private final String subscriptionId; + + /** + * Gets The ID of the target subscription. The value must be an UUID. + * + * @return the subscriptionId value. + */ + public String getSubscriptionId() { + return this.subscriptionId; + } + + /** + * 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. + */ + SerializerAdapter getSerializerAdapter() { + return this.serializerAdapter; + } + + /** + * The default poll interval for long-running operation. + */ + private final Duration defaultPollInterval; + + /** + * Gets The default poll interval for long-running operation. + * + * @return the defaultPollInterval value. + */ + public Duration getDefaultPollInterval() { + return this.defaultPollInterval; + } + + /** + * The OperationsClient object to access its operations. + */ + private final OperationsClient operations; + + /** + * Gets the OperationsClient object to access its operations. + * + * @return the OperationsClient object. + */ + public OperationsClient getOperations() { + return this.operations; + } + + /** + * The WorkloadImpactsClient object to access its operations. + */ + private final WorkloadImpactsClient workloadImpacts; + + /** + * Gets the WorkloadImpactsClient object to access its operations. + * + * @return the WorkloadImpactsClient object. + */ + public WorkloadImpactsClient getWorkloadImpacts() { + return this.workloadImpacts; + } + + /** + * The ImpactCategoriesClient object to access its operations. + */ + private final ImpactCategoriesClient impactCategories; + + /** + * Gets the ImpactCategoriesClient object to access its operations. + * + * @return the ImpactCategoriesClient object. + */ + public ImpactCategoriesClient getImpactCategories() { + return this.impactCategories; + } + + /** + * The InsightsClient object to access its operations. + */ + private final InsightsClient insights; + + /** + * Gets the InsightsClient object to access its operations. + * + * @return the InsightsClient object. + */ + public InsightsClient getInsights() { + return this.insights; + } + + /** + * The ConnectorsClient object to access its operations. + */ + private final ConnectorsClient connectors; + + /** + * Gets the ConnectorsClient object to access its operations. + * + * @return the ConnectorsClient object. + */ + public ConnectorsClient getConnectors() { + return this.connectors; + } + + /** + * Initializes an instance of ImpactReportingMgmtClient client. + * + * @param httpPipeline The HTTP pipeline to send requests through. + * @param serializerAdapter The serializer to serialize an object into a string. + * @param defaultPollInterval The default poll interval for long-running operation. + * @param environment The Azure environment. + * @param endpoint Service host. + * @param subscriptionId The ID of the target subscription. The value must be an UUID. + */ + ImpactReportingMgmtClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, + Duration defaultPollInterval, AzureEnvironment environment, String endpoint, String subscriptionId) { + this.httpPipeline = httpPipeline; + this.serializerAdapter = serializerAdapter; + this.defaultPollInterval = defaultPollInterval; + this.endpoint = endpoint; + this.subscriptionId = subscriptionId; + this.apiVersion = "2024-05-01-preview"; + this.operations = new OperationsClientImpl(this); + this.workloadImpacts = new WorkloadImpactsClientImpl(this); + this.impactCategories = new ImpactCategoriesClientImpl(this); + this.insights = new InsightsClientImpl(this); + this.connectors = new ConnectorsClientImpl(this); + } + + /** + * Gets default client context. + * + * @return the default client context. + */ + public Context getContext() { + return Context.NONE; + } + + /** + * Merges default client context with provided context. + * + * @param context the context to be merged with default client context. + * @return the merged context. + */ + public Context mergeContext(Context context) { + return CoreUtils.mergeContexts(this.getContext(), context); + } + + /** + * Gets long running operation result. + * + * @param activationResponse the response of activation operation. + * @param httpPipeline the http pipeline. + * @param pollResultType type of poll result. + * @param finalResultType type of final result. + * @param context the context shared by all requests. + * @param type of poll result. + * @param type of final result. + * @return poller flux for poll result and final result. + */ + public PollerFlux, U> getLroResult(Mono>> activationResponse, + HttpPipeline httpPipeline, Type pollResultType, Type finalResultType, Context context) { + return PollerFactory.create(serializerAdapter, httpPipeline, pollResultType, finalResultType, + defaultPollInterval, activationResponse, context); + } + + /** + * Gets the final result, or an error, based on last async poll response. + * + * @param response the last async poll response. + * @param type of poll result. + * @param type of final result. + * @return the final result, or an error. + */ + public Mono getLroFinalResultOrError(AsyncPollResponse, U> response) { + if (response.getStatus() != LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { + String errorMessage; + ManagementError managementError = null; + HttpResponse errorResponse = null; + PollResult.Error lroError = response.getValue().getError(); + if (lroError != null) { + errorResponse = new HttpResponseImpl(lroError.getResponseStatusCode(), lroError.getResponseHeaders(), + lroError.getResponseBody()); + + errorMessage = response.getValue().getError().getMessage(); + String errorBody = response.getValue().getError().getResponseBody(); + if (errorBody != null) { + // try to deserialize error body to ManagementError + try { + managementError = this.getSerializerAdapter() + .deserialize(errorBody, ManagementError.class, SerializerEncoding.JSON); + if (managementError.getCode() == null || managementError.getMessage() == null) { + managementError = null; + } + } catch (IOException | RuntimeException ioe) { + LOGGER.logThrowableAsWarning(ioe); + } + } + } else { + // fallback to default error message + errorMessage = "Long running operation failed."; + } + if (managementError == null) { + // fallback to default ManagementError + managementError = new ManagementError(response.getStatus().toString(), errorMessage); + } + return Mono.error(new ManagementException(errorMessage, errorResponse, managementError)); + } else { + return response.getFinalResult(); + } + } + + private static final class HttpResponseImpl extends HttpResponse { + private final int statusCode; + + private final byte[] responseBody; + + private final HttpHeaders httpHeaders; + + HttpResponseImpl(int statusCode, HttpHeaders httpHeaders, String responseBody) { + super(null); + this.statusCode = statusCode; + this.httpHeaders = httpHeaders; + this.responseBody = responseBody == null ? null : responseBody.getBytes(StandardCharsets.UTF_8); + } + + public int getStatusCode() { + return statusCode; + } + + public String getHeaderValue(String s) { + return httpHeaders.getValue(HttpHeaderName.fromString(s)); + } + + public HttpHeaders getHeaders() { + return httpHeaders; + } + + public Flux getBody() { + return Flux.just(ByteBuffer.wrap(responseBody)); + } + + public Mono getBodyAsByteArray() { + return Mono.just(responseBody); + } + + public Mono getBodyAsString() { + return Mono.just(new String(responseBody, StandardCharsets.UTF_8)); + } + + public Mono getBodyAsString(Charset charset) { + return Mono.just(new String(responseBody, charset)); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(ImpactReportingMgmtClientImpl.class); +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/InsightImpl.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/InsightImpl.java new file mode 100644 index 000000000000..8d2eb66a417a --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/InsightImpl.java @@ -0,0 +1,103 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.implementation; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.impactreporting.fluent.models.InsightInner; +import com.azure.resourcemanager.impactreporting.models.Insight; +import com.azure.resourcemanager.impactreporting.models.InsightProperties; + +public final class InsightImpl implements Insight, Insight.Definition { + private InsightInner innerObject; + + private final com.azure.resourcemanager.impactreporting.ImpactReportingManager serviceManager; + + InsightImpl(InsightInner innerObject, + com.azure.resourcemanager.impactreporting.ImpactReportingManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public InsightProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public InsightInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.impactreporting.ImpactReportingManager manager() { + return this.serviceManager; + } + + private String workloadImpactName; + + private String insightName; + + public InsightImpl withExistingWorkloadImpact(String workloadImpactName) { + this.workloadImpactName = workloadImpactName; + return this; + } + + public Insight create() { + this.innerObject = serviceManager.serviceClient() + .getInsights() + .createWithResponse(workloadImpactName, insightName, this.innerModel(), Context.NONE) + .getValue(); + return this; + } + + public Insight create(Context context) { + this.innerObject = serviceManager.serviceClient() + .getInsights() + .createWithResponse(workloadImpactName, insightName, this.innerModel(), context) + .getValue(); + return this; + } + + InsightImpl(String name, com.azure.resourcemanager.impactreporting.ImpactReportingManager serviceManager) { + this.innerObject = new InsightInner(); + this.serviceManager = serviceManager; + this.insightName = name; + } + + public Insight refresh() { + this.innerObject = serviceManager.serviceClient() + .getInsights() + .getWithResponse(workloadImpactName, insightName, Context.NONE) + .getValue(); + return this; + } + + public Insight refresh(Context context) { + this.innerObject = serviceManager.serviceClient() + .getInsights() + .getWithResponse(workloadImpactName, insightName, context) + .getValue(); + return this; + } + + public InsightImpl withProperties(InsightProperties properties) { + this.innerModel().withProperties(properties); + return this; + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/InsightsClientImpl.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/InsightsClientImpl.java new file mode 100644 index 000000000000..6b86ad7f095a --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/InsightsClientImpl.java @@ -0,0 +1,659 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Put; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.resourcemanager.impactreporting.fluent.InsightsClient; +import com.azure.resourcemanager.impactreporting.fluent.models.InsightInner; +import com.azure.resourcemanager.impactreporting.implementation.models.InsightListResult; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in InsightsClient. + */ +public final class InsightsClientImpl implements InsightsClient { + /** + * The proxy service used to perform REST calls. + */ + private final InsightsService service; + + /** + * The service client containing this operation class. + */ + private final ImpactReportingMgmtClientImpl client; + + /** + * Initializes an instance of InsightsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + InsightsClientImpl(ImpactReportingMgmtClientImpl client) { + this.service = RestProxy.create(InsightsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for ImpactReportingMgmtClientInsights to be used by the proxy service to + * perform REST calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "ImpactReportingMgmtC") + public interface InsightsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/providers/Microsoft.Impact/workloadImpacts/{workloadImpactName}/insights/{insightName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("workloadImpactName") String workloadImpactName, @PathParam("insightName") String insightName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/providers/Microsoft.Impact/workloadImpacts/{workloadImpactName}/insights") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listBySubscription(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("workloadImpactName") String workloadImpactName, @HeaderParam("Accept") String accept, + Context context); + + @Put("/subscriptions/{subscriptionId}/providers/Microsoft.Impact/workloadImpacts/{workloadImpactName}/insights/{insightName}") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> create(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("workloadImpactName") String workloadImpactName, @PathParam("insightName") String insightName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") InsightInner resource, Context context); + + @Headers({ "Content-Type: application/json" }) + @Delete("/subscriptions/{subscriptionId}/providers/Microsoft.Impact/workloadImpacts/{workloadImpactName}/insights/{insightName}") + @ExpectedResponses({ 200, 204 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> delete(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("workloadImpactName") String workloadImpactName, @PathParam("insightName") String insightName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listBySubscriptionNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * Get Insight resources by workloadImpactName and insightName. + * + * @param workloadImpactName workloadImpact resource. + * @param insightName Name of the insight. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return insight resources by workloadImpactName and insightName along with {@link Response} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String workloadImpactName, String insightName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (workloadImpactName == null) { + return Mono + .error(new IllegalArgumentException("Parameter workloadImpactName is required and cannot be null.")); + } + if (insightName == null) { + return Mono.error(new IllegalArgumentException("Parameter insightName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), workloadImpactName, insightName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get Insight resources by workloadImpactName and insightName. + * + * @param workloadImpactName workloadImpact resource. + * @param insightName Name of the insight. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return insight resources by workloadImpactName and insightName along with {@link Response} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String workloadImpactName, String insightName, + Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (workloadImpactName == null) { + return Mono + .error(new IllegalArgumentException("Parameter workloadImpactName is required and cannot be null.")); + } + if (insightName == null) { + return Mono.error(new IllegalArgumentException("Parameter insightName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + workloadImpactName, insightName, accept, context); + } + + /** + * Get Insight resources by workloadImpactName and insightName. + * + * @param workloadImpactName workloadImpact resource. + * @param insightName Name of the insight. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return insight resources by workloadImpactName and insightName on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String workloadImpactName, String insightName) { + return getWithResponseAsync(workloadImpactName, insightName).flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get Insight resources by workloadImpactName and insightName. + * + * @param workloadImpactName workloadImpact resource. + * @param insightName Name of the insight. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return insight resources by workloadImpactName and insightName along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String workloadImpactName, String insightName, Context context) { + return getWithResponseAsync(workloadImpactName, insightName, context).block(); + } + + /** + * Get Insight resources by workloadImpactName and insightName. + * + * @param workloadImpactName workloadImpact resource. + * @param insightName Name of the insight. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return insight resources by workloadImpactName and insightName. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public InsightInner get(String workloadImpactName, String insightName) { + return getWithResponse(workloadImpactName, insightName, Context.NONE).getValue(); + } + + /** + * List Insight resources by workloadImpactName. + * + * @param workloadImpactName workloadImpact resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Insight list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySubscriptionSinglePageAsync(String workloadImpactName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (workloadImpactName == null) { + return Mono + .error(new IllegalArgumentException("Parameter workloadImpactName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listBySubscription(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), workloadImpactName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), + res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List Insight resources by workloadImpactName. + * + * @param workloadImpactName workloadImpact resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Insight list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySubscriptionSinglePageAsync(String workloadImpactName, + Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (workloadImpactName == null) { + return Mono + .error(new IllegalArgumentException("Parameter workloadImpactName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listBySubscription(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + workloadImpactName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List Insight resources by workloadImpactName. + * + * @param workloadImpactName workloadImpact resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Insight list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listBySubscriptionAsync(String workloadImpactName) { + return new PagedFlux<>(() -> listBySubscriptionSinglePageAsync(workloadImpactName), + nextLink -> listBySubscriptionNextSinglePageAsync(nextLink)); + } + + /** + * List Insight resources by workloadImpactName. + * + * @param workloadImpactName workloadImpact resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Insight list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listBySubscriptionAsync(String workloadImpactName, Context context) { + return new PagedFlux<>(() -> listBySubscriptionSinglePageAsync(workloadImpactName, context), + nextLink -> listBySubscriptionNextSinglePageAsync(nextLink, context)); + } + + /** + * List Insight resources by workloadImpactName. + * + * @param workloadImpactName workloadImpact resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Insight list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listBySubscription(String workloadImpactName) { + return new PagedIterable<>(listBySubscriptionAsync(workloadImpactName)); + } + + /** + * List Insight resources by workloadImpactName. + * + * @param workloadImpactName workloadImpact resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Insight list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listBySubscription(String workloadImpactName, Context context) { + return new PagedIterable<>(listBySubscriptionAsync(workloadImpactName, context)); + } + + /** + * Create Insight resource, This is Admin only operation. + * + * @param workloadImpactName workloadImpact resource. + * @param insightName Name of the insight. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return insight resource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> createWithResponseAsync(String workloadImpactName, String insightName, + InsightInner resource) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (workloadImpactName == null) { + return Mono + .error(new IllegalArgumentException("Parameter workloadImpactName is required and cannot be null.")); + } + if (insightName == null) { + return Mono.error(new IllegalArgumentException("Parameter insightName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.create(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), workloadImpactName, insightName, contentType, accept, resource, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Create Insight resource, This is Admin only operation. + * + * @param workloadImpactName workloadImpact resource. + * @param insightName Name of the insight. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return insight resource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> createWithResponseAsync(String workloadImpactName, String insightName, + InsightInner resource, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (workloadImpactName == null) { + return Mono + .error(new IllegalArgumentException("Parameter workloadImpactName is required and cannot be null.")); + } + if (insightName == null) { + return Mono.error(new IllegalArgumentException("Parameter insightName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.create(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + workloadImpactName, insightName, contentType, accept, resource, context); + } + + /** + * Create Insight resource, This is Admin only operation. + * + * @param workloadImpactName workloadImpact resource. + * @param insightName Name of the insight. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return insight resource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createAsync(String workloadImpactName, String insightName, InsightInner resource) { + return createWithResponseAsync(workloadImpactName, insightName, resource) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Create Insight resource, This is Admin only operation. + * + * @param workloadImpactName workloadImpact resource. + * @param insightName Name of the insight. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return insight resource along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createWithResponse(String workloadImpactName, String insightName, + InsightInner resource, Context context) { + return createWithResponseAsync(workloadImpactName, insightName, resource, context).block(); + } + + /** + * Create Insight resource, This is Admin only operation. + * + * @param workloadImpactName workloadImpact resource. + * @param insightName Name of the insight. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return insight resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public InsightInner create(String workloadImpactName, String insightName, InsightInner resource) { + return createWithResponse(workloadImpactName, insightName, resource, Context.NONE).getValue(); + } + + /** + * Delete Insight resource, This is Admin only operation. + * + * @param workloadImpactName workloadImpact resource. + * @param insightName Name of the insight. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String workloadImpactName, String insightName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (workloadImpactName == null) { + return Mono + .error(new IllegalArgumentException("Parameter workloadImpactName is required and cannot be null.")); + } + if (insightName == null) { + return Mono.error(new IllegalArgumentException("Parameter insightName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.delete(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), workloadImpactName, insightName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Delete Insight resource, This is Admin only operation. + * + * @param workloadImpactName workloadImpact resource. + * @param insightName Name of the insight. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String workloadImpactName, String insightName, + Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (workloadImpactName == null) { + return Mono + .error(new IllegalArgumentException("Parameter workloadImpactName is required and cannot be null.")); + } + if (insightName == null) { + return Mono.error(new IllegalArgumentException("Parameter insightName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.delete(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + workloadImpactName, insightName, accept, context); + } + + /** + * Delete Insight resource, This is Admin only operation. + * + * @param workloadImpactName workloadImpact resource. + * @param insightName Name of the insight. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono deleteAsync(String workloadImpactName, String insightName) { + return deleteWithResponseAsync(workloadImpactName, insightName).flatMap(ignored -> Mono.empty()); + } + + /** + * Delete Insight resource, This is Admin only operation. + * + * @param workloadImpactName workloadImpact resource. + * @param insightName Name of the insight. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String workloadImpactName, String insightName, Context context) { + return deleteWithResponseAsync(workloadImpactName, insightName, context).block(); + } + + /** + * Delete Insight resource, This is Admin only operation. + * + * @param workloadImpactName workloadImpact resource. + * @param insightName Name of the insight. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String workloadImpactName, String insightName) { + deleteWithResponse(workloadImpactName, insightName, Context.NONE); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Insight list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySubscriptionNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), + res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Insight list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySubscriptionNextSinglePageAsync(String nextLink, Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/InsightsImpl.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/InsightsImpl.java new file mode 100644 index 000000000000..d415cd8a4e97 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/InsightsImpl.java @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.impactreporting.fluent.InsightsClient; +import com.azure.resourcemanager.impactreporting.fluent.models.InsightInner; +import com.azure.resourcemanager.impactreporting.models.Insight; +import com.azure.resourcemanager.impactreporting.models.Insights; + +public final class InsightsImpl implements Insights { + private static final ClientLogger LOGGER = new ClientLogger(InsightsImpl.class); + + private final InsightsClient innerClient; + + private final com.azure.resourcemanager.impactreporting.ImpactReportingManager serviceManager; + + public InsightsImpl(InsightsClient innerClient, + com.azure.resourcemanager.impactreporting.ImpactReportingManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public Response getWithResponse(String workloadImpactName, String insightName, Context context) { + Response inner = this.serviceClient().getWithResponse(workloadImpactName, insightName, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new InsightImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public Insight get(String workloadImpactName, String insightName) { + InsightInner inner = this.serviceClient().get(workloadImpactName, insightName); + if (inner != null) { + return new InsightImpl(inner, this.manager()); + } else { + return null; + } + } + + public PagedIterable listBySubscription(String workloadImpactName) { + PagedIterable inner = this.serviceClient().listBySubscription(workloadImpactName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new InsightImpl(inner1, this.manager())); + } + + public PagedIterable listBySubscription(String workloadImpactName, Context context) { + PagedIterable inner = this.serviceClient().listBySubscription(workloadImpactName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new InsightImpl(inner1, this.manager())); + } + + public Response deleteByResourceGroupWithResponse(String workloadImpactName, String insightName, + Context context) { + return this.serviceClient().deleteWithResponse(workloadImpactName, insightName, context); + } + + public void deleteByResourceGroup(String workloadImpactName, String insightName) { + this.serviceClient().delete(workloadImpactName, insightName); + } + + public Insight getById(String id) { + String workloadImpactName = ResourceManagerUtils.getValueFromIdByName(id, "workloadImpacts"); + if (workloadImpactName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'workloadImpacts'.", id))); + } + String insightName = ResourceManagerUtils.getValueFromIdByName(id, "insights"); + if (insightName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'insights'.", id))); + } + return this.getWithResponse(workloadImpactName, insightName, Context.NONE).getValue(); + } + + public Response getByIdWithResponse(String id, Context context) { + String workloadImpactName = ResourceManagerUtils.getValueFromIdByName(id, "workloadImpacts"); + if (workloadImpactName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'workloadImpacts'.", id))); + } + String insightName = ResourceManagerUtils.getValueFromIdByName(id, "insights"); + if (insightName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'insights'.", id))); + } + return this.getWithResponse(workloadImpactName, insightName, context); + } + + public void deleteById(String id) { + String workloadImpactName = ResourceManagerUtils.getValueFromIdByName(id, "workloadImpacts"); + if (workloadImpactName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'workloadImpacts'.", id))); + } + String insightName = ResourceManagerUtils.getValueFromIdByName(id, "insights"); + if (insightName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'insights'.", id))); + } + this.deleteByResourceGroupWithResponse(workloadImpactName, insightName, Context.NONE); + } + + public Response deleteByIdWithResponse(String id, Context context) { + String workloadImpactName = ResourceManagerUtils.getValueFromIdByName(id, "workloadImpacts"); + if (workloadImpactName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'workloadImpacts'.", id))); + } + String insightName = ResourceManagerUtils.getValueFromIdByName(id, "insights"); + if (insightName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'insights'.", id))); + } + return this.deleteByResourceGroupWithResponse(workloadImpactName, insightName, context); + } + + private InsightsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.impactreporting.ImpactReportingManager manager() { + return this.serviceManager; + } + + public InsightImpl define(String name) { + return new InsightImpl(name, this.manager()); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/OperationImpl.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/OperationImpl.java new file mode 100644 index 000000000000..3d84b0cf6c66 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/OperationImpl.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.implementation; + +import com.azure.resourcemanager.impactreporting.fluent.models.OperationInner; +import com.azure.resourcemanager.impactreporting.models.ActionType; +import com.azure.resourcemanager.impactreporting.models.Operation; +import com.azure.resourcemanager.impactreporting.models.OperationDisplay; +import com.azure.resourcemanager.impactreporting.models.Origin; + +public final class OperationImpl implements Operation { + private OperationInner innerObject; + + private final com.azure.resourcemanager.impactreporting.ImpactReportingManager serviceManager; + + OperationImpl(OperationInner innerObject, + com.azure.resourcemanager.impactreporting.ImpactReportingManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String name() { + return this.innerModel().name(); + } + + public Boolean isDataAction() { + return this.innerModel().isDataAction(); + } + + public OperationDisplay display() { + return this.innerModel().display(); + } + + public Origin origin() { + return this.innerModel().origin(); + } + + public ActionType actionType() { + return this.innerModel().actionType(); + } + + public OperationInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.impactreporting.ImpactReportingManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/OperationsClientImpl.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/OperationsClientImpl.java new file mode 100644 index 000000000000..4eb39456e100 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/OperationsClientImpl.java @@ -0,0 +1,235 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.implementation; + +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.resourcemanager.impactreporting.fluent.OperationsClient; +import com.azure.resourcemanager.impactreporting.fluent.models.OperationInner; +import com.azure.resourcemanager.impactreporting.implementation.models.OperationListResult; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in OperationsClient. + */ +public final class OperationsClientImpl implements OperationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final OperationsService service; + + /** + * The service client containing this operation class. + */ + private final ImpactReportingMgmtClientImpl client; + + /** + * Initializes an instance of OperationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + OperationsClientImpl(ImpactReportingMgmtClientImpl client) { + this.service + = RestProxy.create(OperationsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for ImpactReportingMgmtClientOperations to be used by the proxy service + * to perform REST calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "ImpactReportingMgmtC") + public interface OperationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/providers/Microsoft.Impact/operations") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> list(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listNext(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("endpoint") String endpoint, @HeaderParam("Accept") String accept, Context context); + } + + /** + * List the operations for the provider. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider along with {@link PagedResponse} on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync() { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.list(this.client.getEndpoint(), this.client.getApiVersion(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), + res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List the operations for the provider. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider along with {@link PagedResponse} on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync(Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.list(this.client.getEndpoint(), this.client.getApiVersion(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List the operations for the provider. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync() { + return new PagedFlux<>(() -> listSinglePageAsync(), nextLink -> listNextSinglePageAsync(nextLink)); + } + + /** + * List the operations for the provider. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync(Context context) { + return new PagedFlux<>(() -> listSinglePageAsync(context), + nextLink -> listNextSinglePageAsync(nextLink, context)); + } + + /** + * List the operations for the provider. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list() { + return new PagedIterable<>(listAsync()); + } + + /** + * List the operations for the provider. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(Context context) { + return new PagedIterable<>(listAsync(context)); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider along with {@link PagedResponse} on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.listNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), + res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider along with {@link PagedResponse} on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listNextSinglePageAsync(String nextLink, Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/OperationsImpl.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/OperationsImpl.java new file mode 100644 index 000000000000..14c161dd7801 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/OperationsImpl.java @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.impactreporting.fluent.OperationsClient; +import com.azure.resourcemanager.impactreporting.fluent.models.OperationInner; +import com.azure.resourcemanager.impactreporting.models.Operation; +import com.azure.resourcemanager.impactreporting.models.Operations; + +public final class OperationsImpl implements Operations { + private static final ClientLogger LOGGER = new ClientLogger(OperationsImpl.class); + + private final OperationsClient innerClient; + + private final com.azure.resourcemanager.impactreporting.ImpactReportingManager serviceManager; + + public OperationsImpl(OperationsClient innerClient, + com.azure.resourcemanager.impactreporting.ImpactReportingManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public PagedIterable list() { + PagedIterable inner = this.serviceClient().list(); + return ResourceManagerUtils.mapPage(inner, inner1 -> new OperationImpl(inner1, this.manager())); + } + + public PagedIterable list(Context context) { + PagedIterable inner = this.serviceClient().list(context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new OperationImpl(inner1, this.manager())); + } + + private OperationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.impactreporting.ImpactReportingManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/ResourceManagerUtils.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/ResourceManagerUtils.java new file mode 100644 index 000000000000..a37c59d0f405 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/ResourceManagerUtils.java @@ -0,0 +1,195 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.implementation; + +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.util.CoreUtils; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import reactor.core.publisher.Flux; + +final class ResourceManagerUtils { + private ResourceManagerUtils() { + } + + static String getValueFromIdByName(String id, String name) { + if (id == null) { + return null; + } + Iterator itr = Arrays.stream(id.split("/")).iterator(); + while (itr.hasNext()) { + String part = itr.next(); + if (part != null && !part.trim().isEmpty()) { + if (part.equalsIgnoreCase(name)) { + if (itr.hasNext()) { + return itr.next(); + } else { + return null; + } + } + } + } + return null; + } + + static String getValueFromIdByParameterName(String id, String pathTemplate, String parameterName) { + if (id == null || pathTemplate == null) { + return null; + } + String parameterNameParentheses = "{" + parameterName + "}"; + List idSegmentsReverted = Arrays.asList(id.split("/")); + List pathSegments = Arrays.asList(pathTemplate.split("/")); + Collections.reverse(idSegmentsReverted); + Iterator idItrReverted = idSegmentsReverted.iterator(); + int pathIndex = pathSegments.size(); + while (idItrReverted.hasNext() && pathIndex > 0) { + String idSegment = idItrReverted.next(); + String pathSegment = pathSegments.get(--pathIndex); + if (!CoreUtils.isNullOrEmpty(idSegment) && !CoreUtils.isNullOrEmpty(pathSegment)) { + if (pathSegment.equalsIgnoreCase(parameterNameParentheses)) { + if (pathIndex == 0 || (pathIndex == 1 && pathSegments.get(0).isEmpty())) { + List segments = new ArrayList<>(); + segments.add(idSegment); + idItrReverted.forEachRemaining(segments::add); + Collections.reverse(segments); + if (!segments.isEmpty() && segments.get(0).isEmpty()) { + segments.remove(0); + } + return String.join("/", segments); + } else { + return idSegment; + } + } + } + } + return null; + } + + static PagedIterable mapPage(PagedIterable pageIterable, Function mapper) { + return new PagedIterableImpl<>(pageIterable, mapper); + } + + private static final class PagedIterableImpl extends PagedIterable { + + private final PagedIterable pagedIterable; + private final Function mapper; + private final Function, PagedResponse> pageMapper; + + private PagedIterableImpl(PagedIterable pagedIterable, Function mapper) { + super(PagedFlux.create(() -> (continuationToken, pageSize) -> Flux + .fromStream(pagedIterable.streamByPage().map(getPageMapper(mapper))))); + this.pagedIterable = pagedIterable; + this.mapper = mapper; + this.pageMapper = getPageMapper(mapper); + } + + private static Function, PagedResponse> getPageMapper(Function mapper) { + return page -> new PagedResponseBase(page.getRequest(), page.getStatusCode(), page.getHeaders(), + page.getElements().stream().map(mapper).collect(Collectors.toList()), page.getContinuationToken(), + null); + } + + @Override + public Stream stream() { + return pagedIterable.stream().map(mapper); + } + + @Override + public Stream> streamByPage() { + return pagedIterable.streamByPage().map(pageMapper); + } + + @Override + public Stream> streamByPage(String continuationToken) { + return pagedIterable.streamByPage(continuationToken).map(pageMapper); + } + + @Override + public Stream> streamByPage(int preferredPageSize) { + return pagedIterable.streamByPage(preferredPageSize).map(pageMapper); + } + + @Override + public Stream> streamByPage(String continuationToken, int preferredPageSize) { + return pagedIterable.streamByPage(continuationToken, preferredPageSize).map(pageMapper); + } + + @Override + public Iterator iterator() { + return new IteratorImpl<>(pagedIterable.iterator(), mapper); + } + + @Override + public Iterable> iterableByPage() { + return new IterableImpl<>(pagedIterable.iterableByPage(), pageMapper); + } + + @Override + public Iterable> iterableByPage(String continuationToken) { + return new IterableImpl<>(pagedIterable.iterableByPage(continuationToken), pageMapper); + } + + @Override + public Iterable> iterableByPage(int preferredPageSize) { + return new IterableImpl<>(pagedIterable.iterableByPage(preferredPageSize), pageMapper); + } + + @Override + public Iterable> iterableByPage(String continuationToken, int preferredPageSize) { + return new IterableImpl<>(pagedIterable.iterableByPage(continuationToken, preferredPageSize), pageMapper); + } + } + + private static final class IteratorImpl implements Iterator { + + private final Iterator iterator; + private final Function mapper; + + private IteratorImpl(Iterator iterator, Function mapper) { + this.iterator = iterator; + this.mapper = mapper; + } + + @Override + public boolean hasNext() { + return iterator.hasNext(); + } + + @Override + public S next() { + return mapper.apply(iterator.next()); + } + + @Override + public void remove() { + iterator.remove(); + } + } + + private static final class IterableImpl implements Iterable { + + private final Iterable iterable; + private final Function mapper; + + private IterableImpl(Iterable iterable, Function mapper) { + this.iterable = iterable; + this.mapper = mapper; + } + + @Override + public Iterator iterator() { + return new IteratorImpl<>(iterable.iterator(), mapper); + } + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/WorkloadImpactImpl.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/WorkloadImpactImpl.java new file mode 100644 index 000000000000..84c849dd98e1 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/WorkloadImpactImpl.java @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.implementation; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.impactreporting.fluent.models.WorkloadImpactInner; +import com.azure.resourcemanager.impactreporting.models.WorkloadImpact; +import com.azure.resourcemanager.impactreporting.models.WorkloadImpactProperties; + +public final class WorkloadImpactImpl implements WorkloadImpact, WorkloadImpact.Definition { + private WorkloadImpactInner innerObject; + + private final com.azure.resourcemanager.impactreporting.ImpactReportingManager serviceManager; + + WorkloadImpactImpl(WorkloadImpactInner innerObject, + com.azure.resourcemanager.impactreporting.ImpactReportingManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public WorkloadImpactProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public WorkloadImpactInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.impactreporting.ImpactReportingManager manager() { + return this.serviceManager; + } + + private String workloadImpactName; + + public WorkloadImpact create() { + this.innerObject = serviceManager.serviceClient() + .getWorkloadImpacts() + .create(workloadImpactName, this.innerModel(), Context.NONE); + return this; + } + + public WorkloadImpact create(Context context) { + this.innerObject = serviceManager.serviceClient() + .getWorkloadImpacts() + .create(workloadImpactName, this.innerModel(), context); + return this; + } + + WorkloadImpactImpl(String name, com.azure.resourcemanager.impactreporting.ImpactReportingManager serviceManager) { + this.innerObject = new WorkloadImpactInner(); + this.serviceManager = serviceManager; + this.workloadImpactName = name; + } + + public WorkloadImpact refresh() { + this.innerObject = serviceManager.serviceClient() + .getWorkloadImpacts() + .getWithResponse(workloadImpactName, Context.NONE) + .getValue(); + return this; + } + + public WorkloadImpact refresh(Context context) { + this.innerObject = serviceManager.serviceClient() + .getWorkloadImpacts() + .getWithResponse(workloadImpactName, context) + .getValue(); + return this; + } + + public WorkloadImpactImpl withProperties(WorkloadImpactProperties properties) { + this.innerModel().withProperties(properties); + return this; + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/WorkloadImpactsClientImpl.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/WorkloadImpactsClientImpl.java new file mode 100644 index 000000000000..0129ea172d3e --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/WorkloadImpactsClientImpl.java @@ -0,0 +1,698 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Put; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.core.util.polling.PollerFlux; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.impactreporting.fluent.WorkloadImpactsClient; +import com.azure.resourcemanager.impactreporting.fluent.models.WorkloadImpactInner; +import com.azure.resourcemanager.impactreporting.implementation.models.WorkloadImpactListResult; +import java.nio.ByteBuffer; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in WorkloadImpactsClient. + */ +public final class WorkloadImpactsClientImpl implements WorkloadImpactsClient { + /** + * The proxy service used to perform REST calls. + */ + private final WorkloadImpactsService service; + + /** + * The service client containing this operation class. + */ + private final ImpactReportingMgmtClientImpl client; + + /** + * Initializes an instance of WorkloadImpactsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + WorkloadImpactsClientImpl(ImpactReportingMgmtClientImpl client) { + this.service + = RestProxy.create(WorkloadImpactsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for ImpactReportingMgmtClientWorkloadImpacts to be used by the proxy + * service to perform REST calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "ImpactReportingMgmtC") + public interface WorkloadImpactsService { + @Put("/subscriptions/{subscriptionId}/providers/Microsoft.Impact/workloadImpacts/{workloadImpactName}") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> create(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("workloadImpactName") String workloadImpactName, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") WorkloadImpactInner resource, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/providers/Microsoft.Impact/workloadImpacts/{workloadImpactName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("workloadImpactName") String workloadImpactName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Delete("/subscriptions/{subscriptionId}/providers/Microsoft.Impact/workloadImpacts/{workloadImpactName}") + @ExpectedResponses({ 200, 204 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> delete(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("workloadImpactName") String workloadImpactName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/providers/Microsoft.Impact/workloadImpacts") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> list(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listBySubscriptionNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * Create a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return workload Impact properties along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createWithResponseAsync(String workloadImpactName, + WorkloadImpactInner resource) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (workloadImpactName == null) { + return Mono + .error(new IllegalArgumentException("Parameter workloadImpactName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.create(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), workloadImpactName, contentType, accept, resource, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Create a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return workload Impact properties along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createWithResponseAsync(String workloadImpactName, + WorkloadImpactInner resource, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (workloadImpactName == null) { + return Mono + .error(new IllegalArgumentException("Parameter workloadImpactName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.create(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + workloadImpactName, contentType, accept, resource, context); + } + + /** + * Create a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of workload Impact properties. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, WorkloadImpactInner> beginCreateAsync(String workloadImpactName, + WorkloadImpactInner resource) { + Mono>> mono = createWithResponseAsync(workloadImpactName, resource); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + WorkloadImpactInner.class, WorkloadImpactInner.class, this.client.getContext()); + } + + /** + * Create a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of workload Impact properties. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, WorkloadImpactInner> beginCreateAsync(String workloadImpactName, + WorkloadImpactInner resource, Context context) { + context = this.client.mergeContext(context); + Mono>> mono = createWithResponseAsync(workloadImpactName, resource, context); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + WorkloadImpactInner.class, WorkloadImpactInner.class, context); + } + + /** + * Create a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of workload Impact properties. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, WorkloadImpactInner> beginCreate(String workloadImpactName, + WorkloadImpactInner resource) { + return this.beginCreateAsync(workloadImpactName, resource).getSyncPoller(); + } + + /** + * Create a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of workload Impact properties. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, WorkloadImpactInner> beginCreate(String workloadImpactName, + WorkloadImpactInner resource, Context context) { + return this.beginCreateAsync(workloadImpactName, resource, context).getSyncPoller(); + } + + /** + * Create a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return workload Impact properties on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createAsync(String workloadImpactName, WorkloadImpactInner resource) { + return beginCreateAsync(workloadImpactName, resource).last().flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return workload Impact properties on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createAsync(String workloadImpactName, WorkloadImpactInner resource, + Context context) { + return beginCreateAsync(workloadImpactName, resource, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return workload Impact properties. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public WorkloadImpactInner create(String workloadImpactName, WorkloadImpactInner resource) { + return createAsync(workloadImpactName, resource).block(); + } + + /** + * Create a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return workload Impact properties. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public WorkloadImpactInner create(String workloadImpactName, WorkloadImpactInner resource, Context context) { + return createAsync(workloadImpactName, resource, context).block(); + } + + /** + * Get a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a WorkloadImpact along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String workloadImpactName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (workloadImpactName == null) { + return Mono + .error(new IllegalArgumentException("Parameter workloadImpactName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), workloadImpactName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a WorkloadImpact along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String workloadImpactName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (workloadImpactName == null) { + return Mono + .error(new IllegalArgumentException("Parameter workloadImpactName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + workloadImpactName, accept, context); + } + + /** + * Get a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a WorkloadImpact on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String workloadImpactName) { + return getWithResponseAsync(workloadImpactName).flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a WorkloadImpact along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String workloadImpactName, Context context) { + return getWithResponseAsync(workloadImpactName, context).block(); + } + + /** + * Get a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a WorkloadImpact. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public WorkloadImpactInner get(String workloadImpactName) { + return getWithResponse(workloadImpactName, Context.NONE).getValue(); + } + + /** + * Delete a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String workloadImpactName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (workloadImpactName == null) { + return Mono + .error(new IllegalArgumentException("Parameter workloadImpactName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.delete(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), workloadImpactName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Delete a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String workloadImpactName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (workloadImpactName == null) { + return Mono + .error(new IllegalArgumentException("Parameter workloadImpactName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.delete(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + workloadImpactName, accept, context); + } + + /** + * Delete a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono deleteAsync(String workloadImpactName) { + return deleteWithResponseAsync(workloadImpactName).flatMap(ignored -> Mono.empty()); + } + + /** + * Delete a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String workloadImpactName, Context context) { + return deleteWithResponseAsync(workloadImpactName, context).block(); + } + + /** + * Delete a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String workloadImpactName) { + deleteWithResponse(workloadImpactName, Context.NONE); + } + + /** + * List WorkloadImpact resources by subscription ID. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a WorkloadImpact list operation along with {@link PagedResponse} on successful completion + * of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync() { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.list(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List WorkloadImpact resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a WorkloadImpact list operation along with {@link PagedResponse} on successful completion + * of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync(Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .list(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), accept, + context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List WorkloadImpact resources by subscription ID. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a WorkloadImpact list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync() { + return new PagedFlux<>(() -> listSinglePageAsync(), + nextLink -> listBySubscriptionNextSinglePageAsync(nextLink)); + } + + /** + * List WorkloadImpact resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a WorkloadImpact list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync(Context context) { + return new PagedFlux<>(() -> listSinglePageAsync(context), + nextLink -> listBySubscriptionNextSinglePageAsync(nextLink, context)); + } + + /** + * List WorkloadImpact resources by subscription ID. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a WorkloadImpact list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list() { + return new PagedIterable<>(listAsync()); + } + + /** + * List WorkloadImpact resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a WorkloadImpact list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(Context context) { + return new PagedIterable<>(listAsync(context)); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a WorkloadImpact list operation along with {@link PagedResponse} on successful completion + * of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySubscriptionNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a WorkloadImpact list operation along with {@link PagedResponse} on successful completion + * of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySubscriptionNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/WorkloadImpactsImpl.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/WorkloadImpactsImpl.java new file mode 100644 index 000000000000..c327f38438d4 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/WorkloadImpactsImpl.java @@ -0,0 +1,114 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.impactreporting.fluent.WorkloadImpactsClient; +import com.azure.resourcemanager.impactreporting.fluent.models.WorkloadImpactInner; +import com.azure.resourcemanager.impactreporting.models.WorkloadImpact; +import com.azure.resourcemanager.impactreporting.models.WorkloadImpacts; + +public final class WorkloadImpactsImpl implements WorkloadImpacts { + private static final ClientLogger LOGGER = new ClientLogger(WorkloadImpactsImpl.class); + + private final WorkloadImpactsClient innerClient; + + private final com.azure.resourcemanager.impactreporting.ImpactReportingManager serviceManager; + + public WorkloadImpactsImpl(WorkloadImpactsClient innerClient, + com.azure.resourcemanager.impactreporting.ImpactReportingManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public Response getWithResponse(String workloadImpactName, Context context) { + Response inner = this.serviceClient().getWithResponse(workloadImpactName, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new WorkloadImpactImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public WorkloadImpact get(String workloadImpactName) { + WorkloadImpactInner inner = this.serviceClient().get(workloadImpactName); + if (inner != null) { + return new WorkloadImpactImpl(inner, this.manager()); + } else { + return null; + } + } + + public Response deleteWithResponse(String workloadImpactName, Context context) { + return this.serviceClient().deleteWithResponse(workloadImpactName, context); + } + + public void delete(String workloadImpactName) { + this.serviceClient().delete(workloadImpactName); + } + + public PagedIterable list() { + PagedIterable inner = this.serviceClient().list(); + return ResourceManagerUtils.mapPage(inner, inner1 -> new WorkloadImpactImpl(inner1, this.manager())); + } + + public PagedIterable list(Context context) { + PagedIterable inner = this.serviceClient().list(context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new WorkloadImpactImpl(inner1, this.manager())); + } + + public WorkloadImpact getById(String id) { + String workloadImpactName = ResourceManagerUtils.getValueFromIdByName(id, "workloadImpacts"); + if (workloadImpactName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'workloadImpacts'.", id))); + } + return this.getWithResponse(workloadImpactName, Context.NONE).getValue(); + } + + public Response getByIdWithResponse(String id, Context context) { + String workloadImpactName = ResourceManagerUtils.getValueFromIdByName(id, "workloadImpacts"); + if (workloadImpactName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'workloadImpacts'.", id))); + } + return this.getWithResponse(workloadImpactName, context); + } + + public void deleteById(String id) { + String workloadImpactName = ResourceManagerUtils.getValueFromIdByName(id, "workloadImpacts"); + if (workloadImpactName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'workloadImpacts'.", id))); + } + this.deleteWithResponse(workloadImpactName, Context.NONE); + } + + public Response deleteByIdWithResponse(String id, Context context) { + String workloadImpactName = ResourceManagerUtils.getValueFromIdByName(id, "workloadImpacts"); + if (workloadImpactName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'workloadImpacts'.", id))); + } + return this.deleteWithResponse(workloadImpactName, context); + } + + private WorkloadImpactsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.impactreporting.ImpactReportingManager manager() { + return this.serviceManager; + } + + public WorkloadImpactImpl define(String name) { + return new WorkloadImpactImpl(name, this.manager()); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/models/ConnectorListResult.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/models/ConnectorListResult.java new file mode 100644 index 000000000000..dd51787c161d --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/models/ConnectorListResult.java @@ -0,0 +1,112 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.implementation.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.impactreporting.fluent.models.ConnectorInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a Connector list operation. + */ +@Immutable +public final class ConnectorListResult implements JsonSerializable { + /* + * The Connector items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of ConnectorListResult class. + */ + private ConnectorListResult() { + } + + /** + * Get the value property: The Connector items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property value in model ConnectorListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(ConnectorListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ConnectorListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ConnectorListResult 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 ConnectorListResult. + */ + public static ConnectorListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ConnectorListResult deserializedConnectorListResult = new ConnectorListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value = reader.readArray(reader1 -> ConnectorInner.fromJson(reader1)); + deserializedConnectorListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedConnectorListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedConnectorListResult; + }); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/models/ImpactCategoryListResult.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/models/ImpactCategoryListResult.java new file mode 100644 index 000000000000..122fcdc89ac3 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/models/ImpactCategoryListResult.java @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.implementation.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.impactreporting.fluent.models.ImpactCategoryInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a ImpactCategory list operation. + */ +@Immutable +public final class ImpactCategoryListResult implements JsonSerializable { + /* + * The ImpactCategory items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of ImpactCategoryListResult class. + */ + private ImpactCategoryListResult() { + } + + /** + * Get the value property: The ImpactCategory items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property value in model ImpactCategoryListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(ImpactCategoryListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ImpactCategoryListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ImpactCategoryListResult 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 ImpactCategoryListResult. + */ + public static ImpactCategoryListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ImpactCategoryListResult deserializedImpactCategoryListResult = new ImpactCategoryListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> ImpactCategoryInner.fromJson(reader1)); + deserializedImpactCategoryListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedImpactCategoryListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedImpactCategoryListResult; + }); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/models/InsightListResult.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/models/InsightListResult.java new file mode 100644 index 000000000000..6eacfed03534 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/models/InsightListResult.java @@ -0,0 +1,112 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.implementation.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.impactreporting.fluent.models.InsightInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a Insight list operation. + */ +@Immutable +public final class InsightListResult implements JsonSerializable { + /* + * The Insight items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of InsightListResult class. + */ + private InsightListResult() { + } + + /** + * Get the value property: The Insight items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property value in model InsightListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(InsightListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of InsightListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of InsightListResult 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 InsightListResult. + */ + public static InsightListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + InsightListResult deserializedInsightListResult = new InsightListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value = reader.readArray(reader1 -> InsightInner.fromJson(reader1)); + deserializedInsightListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedInsightListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedInsightListResult; + }); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/models/OperationListResult.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/models/OperationListResult.java new file mode 100644 index 000000000000..7584a3ddfde4 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/models/OperationListResult.java @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.implementation.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.impactreporting.fluent.models.OperationInner; +import java.io.IOException; +import java.util.List; + +/** + * A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + * results. + */ +@Immutable +public final class OperationListResult implements JsonSerializable { + /* + * The Operation items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of OperationListResult class. + */ + private OperationListResult() { + } + + /** + * Get the value property: The Operation items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property value in model OperationListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(OperationListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OperationListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OperationListResult 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 OperationListResult. + */ + public static OperationListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OperationListResult deserializedOperationListResult = new OperationListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value = reader.readArray(reader1 -> OperationInner.fromJson(reader1)); + deserializedOperationListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedOperationListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedOperationListResult; + }); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/models/WorkloadImpactListResult.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/models/WorkloadImpactListResult.java new file mode 100644 index 000000000000..7501385eb6f7 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/models/WorkloadImpactListResult.java @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.implementation.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.impactreporting.fluent.models.WorkloadImpactInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a WorkloadImpact list operation. + */ +@Immutable +public final class WorkloadImpactListResult implements JsonSerializable { + /* + * The WorkloadImpact items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of WorkloadImpactListResult class. + */ + private WorkloadImpactListResult() { + } + + /** + * Get the value property: The WorkloadImpact items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property value in model WorkloadImpactListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(WorkloadImpactListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of WorkloadImpactListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of WorkloadImpactListResult 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 WorkloadImpactListResult. + */ + public static WorkloadImpactListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + WorkloadImpactListResult deserializedWorkloadImpactListResult = new WorkloadImpactListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> WorkloadImpactInner.fromJson(reader1)); + deserializedWorkloadImpactListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedWorkloadImpactListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedWorkloadImpactListResult; + }); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/package-info.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/package-info.java new file mode 100644 index 000000000000..264627c5cc0b --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/implementation/package-info.java @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +/** + * Package containing the implementations for ImpactReporting. + */ +package com.azure.resourcemanager.impactreporting.implementation; diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ActionType.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ActionType.java new file mode 100644 index 000000000000..d3ae5bc1dd10 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ActionType.java @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + */ +public final class ActionType extends ExpandableStringEnum { + /** + * Actions are for internal-only APIs. + */ + public static final ActionType INTERNAL = fromString("Internal"); + + /** + * Creates a new instance of ActionType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public ActionType() { + } + + /** + * Creates or finds a ActionType from its string representation. + * + * @param name a name to look for. + * @return the corresponding ActionType. + */ + public static ActionType fromString(String name) { + return fromString(name, ActionType.class); + } + + /** + * Gets known ActionType values. + * + * @return known ActionType values. + */ + public static Collection values() { + return values(ActionType.class); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ClientIncidentDetails.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ClientIncidentDetails.java new file mode 100644 index 000000000000..9e3c4310eac7 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ClientIncidentDetails.java @@ -0,0 +1,127 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.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; + +/** + * Client incident details ex: incidentId , incident source. + */ +@Fluent +public final class ClientIncidentDetails implements JsonSerializable { + /* + * Client incident id. ex : id of the incident created to investigate and address the impact if any. + */ + private String clientIncidentId; + + /* + * Client incident source. ex : source system name where the incident is created + */ + private IncidentSource clientIncidentSource; + + /** + * Creates an instance of ClientIncidentDetails class. + */ + public ClientIncidentDetails() { + } + + /** + * Get the clientIncidentId property: Client incident id. ex : id of the incident created to investigate and address + * the impact if any. + * + * @return the clientIncidentId value. + */ + public String clientIncidentId() { + return this.clientIncidentId; + } + + /** + * Set the clientIncidentId property: Client incident id. ex : id of the incident created to investigate and address + * the impact if any. + * + * @param clientIncidentId the clientIncidentId value to set. + * @return the ClientIncidentDetails object itself. + */ + public ClientIncidentDetails withClientIncidentId(String clientIncidentId) { + this.clientIncidentId = clientIncidentId; + return this; + } + + /** + * Get the clientIncidentSource property: Client incident source. ex : source system name where the incident is + * created. + * + * @return the clientIncidentSource value. + */ + public IncidentSource clientIncidentSource() { + return this.clientIncidentSource; + } + + /** + * Set the clientIncidentSource property: Client incident source. ex : source system name where the incident is + * created. + * + * @param clientIncidentSource the clientIncidentSource value to set. + * @return the ClientIncidentDetails object itself. + */ + public ClientIncidentDetails withClientIncidentSource(IncidentSource clientIncidentSource) { + this.clientIncidentSource = clientIncidentSource; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("clientIncidentId", this.clientIncidentId); + jsonWriter.writeStringField("clientIncidentSource", + this.clientIncidentSource == null ? null : this.clientIncidentSource.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ClientIncidentDetails from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ClientIncidentDetails 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 ClientIncidentDetails. + */ + public static ClientIncidentDetails fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ClientIncidentDetails deserializedClientIncidentDetails = new ClientIncidentDetails(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("clientIncidentId".equals(fieldName)) { + deserializedClientIncidentDetails.clientIncidentId = reader.getString(); + } else if ("clientIncidentSource".equals(fieldName)) { + deserializedClientIncidentDetails.clientIncidentSource + = IncidentSource.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedClientIncidentDetails; + }); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ConfidenceLevel.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ConfidenceLevel.java new file mode 100644 index 000000000000..739746f5b470 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ConfidenceLevel.java @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Degree of confidence on the impact being a platform issue. + */ +public final class ConfidenceLevel extends ExpandableStringEnum { + /** + * Low confidence on azure being the source of impact. + */ + public static final ConfidenceLevel LOW = fromString("Low"); + + /** + * Medium confidence on azure being the source of impact. + */ + public static final ConfidenceLevel MEDIUM = fromString("Medium"); + + /** + * High confidence on azure being the source of impact. + */ + public static final ConfidenceLevel HIGH = fromString("High"); + + /** + * Creates a new instance of ConfidenceLevel value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public ConfidenceLevel() { + } + + /** + * Creates or finds a ConfidenceLevel from its string representation. + * + * @param name a name to look for. + * @return the corresponding ConfidenceLevel. + */ + public static ConfidenceLevel fromString(String name) { + return fromString(name, ConfidenceLevel.class); + } + + /** + * Gets known ConfidenceLevel values. + * + * @return known ConfidenceLevel values. + */ + public static Collection values() { + return values(ConfidenceLevel.class); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Connectivity.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Connectivity.java new file mode 100644 index 000000000000..640b361bb75a --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Connectivity.java @@ -0,0 +1,185 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.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; + +/** + * Details about connectivity issue. Applicable when root resource causing the issue is not identified. For example, + * when a VM is impacted due to a network issue, the impacted resource could be VM or the network. In such cases, the + * connectivity field will have the details about both VM and network. + */ +@Fluent +public final class Connectivity implements JsonSerializable { + /* + * Protocol used for the connection + */ + private Protocol protocol; + + /* + * Port number for the connection + */ + private Integer port; + + /* + * Source from which the connection was attempted + */ + private SourceOrTarget source; + + /* + * target which connection was attempted + */ + private SourceOrTarget target; + + /** + * Creates an instance of Connectivity class. + */ + public Connectivity() { + } + + /** + * Get the protocol property: Protocol used for the connection. + * + * @return the protocol value. + */ + public Protocol protocol() { + return this.protocol; + } + + /** + * Set the protocol property: Protocol used for the connection. + * + * @param protocol the protocol value to set. + * @return the Connectivity object itself. + */ + public Connectivity withProtocol(Protocol protocol) { + this.protocol = protocol; + return this; + } + + /** + * Get the port property: Port number for the connection. + * + * @return the port value. + */ + public Integer port() { + return this.port; + } + + /** + * Set the port property: Port number for the connection. + * + * @param port the port value to set. + * @return the Connectivity object itself. + */ + public Connectivity withPort(Integer port) { + this.port = port; + return this; + } + + /** + * Get the source property: Source from which the connection was attempted. + * + * @return the source value. + */ + public SourceOrTarget source() { + return this.source; + } + + /** + * Set the source property: Source from which the connection was attempted. + * + * @param source the source value to set. + * @return the Connectivity object itself. + */ + public Connectivity withSource(SourceOrTarget source) { + this.source = source; + return this; + } + + /** + * Get the target property: target which connection was attempted. + * + * @return the target value. + */ + public SourceOrTarget target() { + return this.target; + } + + /** + * Set the target property: target which connection was attempted. + * + * @param target the target value to set. + * @return the Connectivity object itself. + */ + public Connectivity withTarget(SourceOrTarget target) { + this.target = target; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (source() != null) { + source().validate(); + } + if (target() != null) { + target().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("protocol", this.protocol == null ? null : this.protocol.toString()); + jsonWriter.writeNumberField("port", this.port); + jsonWriter.writeJsonField("source", this.source); + jsonWriter.writeJsonField("target", this.target); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of Connectivity from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of Connectivity 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 Connectivity. + */ + public static Connectivity fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Connectivity deserializedConnectivity = new Connectivity(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("protocol".equals(fieldName)) { + deserializedConnectivity.protocol = Protocol.fromString(reader.getString()); + } else if ("port".equals(fieldName)) { + deserializedConnectivity.port = reader.getNullable(JsonReader::getInt); + } else if ("source".equals(fieldName)) { + deserializedConnectivity.source = SourceOrTarget.fromJson(reader); + } else if ("target".equals(fieldName)) { + deserializedConnectivity.target = SourceOrTarget.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedConnectivity; + }); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Connector.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Connector.java new file mode 100644 index 000000000000..14ca638e2cd3 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Connector.java @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.models; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.impactreporting.fluent.models.ConnectorInner; + +/** + * An immutable client-side representation of Connector. + */ +public interface Connector { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + ConnectorProperties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.impactreporting.fluent.models.ConnectorInner object. + * + * @return the inner object. + */ + ConnectorInner innerModel(); + + /** + * The entirety of the Connector definition. + */ + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithCreate { + } + + /** + * The Connector definition stages. + */ + interface DefinitionStages { + /** + * The first stage of the Connector definition. + */ + interface Blank extends WithCreate { + } + + /** + * The stage of the Connector definition which contains all the minimum required properties for the resource to + * be created, but also allows for any other optional properties to be specified. + */ + interface WithCreate extends DefinitionStages.WithProperties { + /** + * Executes the create request. + * + * @return the created resource. + */ + Connector create(); + + /** + * Executes the create request. + * + * @param context The context to associate with this operation. + * @return the created resource. + */ + Connector create(Context context); + } + + /** + * The stage of the Connector definition allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The resource-specific properties for this resource.. + * + * @param properties The resource-specific properties for this resource. + * @return the next definition stage. + */ + WithCreate withProperties(ConnectorProperties properties); + } + } + + /** + * Begins update for the Connector resource. + * + * @return the stage of resource update. + */ + Connector.Update update(); + + /** + * The template for Connector update. + */ + interface Update extends UpdateStages.WithProperties { + /** + * Executes the update request. + * + * @return the updated resource. + */ + Connector apply(); + + /** + * Executes the update request. + * + * @param context The context to associate with this operation. + * @return the updated resource. + */ + Connector apply(Context context); + } + + /** + * The Connector update stages. + */ + interface UpdateStages { + /** + * The stage of the Connector update allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The resource-specific properties for this resource.. + * + * @param properties The resource-specific properties for this resource. + * @return the next definition stage. + */ + Update withProperties(ConnectorUpdateProperties properties); + } + } + + /** + * Refreshes the resource to sync with Azure. + * + * @return the refreshed resource. + */ + Connector refresh(); + + /** + * Refreshes the resource to sync with Azure. + * + * @param context The context to associate with this operation. + * @return the refreshed resource. + */ + Connector refresh(Context context); +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ConnectorProperties.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ConnectorProperties.java new file mode 100644 index 000000000000..8489c453cdef --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ConnectorProperties.java @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; +import com.azure.core.util.logging.ClientLogger; +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.OffsetDateTime; + +/** + * Details of the Connector. + */ +@Fluent +public final class ConnectorProperties implements JsonSerializable { + /* + * Resource provisioning state. + */ + private ProvisioningState provisioningState; + + /* + * unique id of the connector. + */ + private String connectorId; + + /* + * tenant id of this connector + */ + private String tenantId; + + /* + * connector type + */ + private Platform connectorType; + + /* + * last run time stamp of this connector in UTC time zone + */ + private OffsetDateTime lastRunTimeStamp; + + /** + * Creates an instance of ConnectorProperties class. + */ + public ConnectorProperties() { + } + + /** + * Get the provisioningState property: Resource provisioning state. + * + * @return the provisioningState value. + */ + public ProvisioningState provisioningState() { + return this.provisioningState; + } + + /** + * Get the connectorId property: unique id of the connector. + * + * @return the connectorId value. + */ + public String connectorId() { + return this.connectorId; + } + + /** + * Get the tenantId property: tenant id of this connector. + * + * @return the tenantId value. + */ + public String tenantId() { + return this.tenantId; + } + + /** + * Get the connectorType property: connector type. + * + * @return the connectorType value. + */ + public Platform connectorType() { + return this.connectorType; + } + + /** + * Set the connectorType property: connector type. + * + * @param connectorType the connectorType value to set. + * @return the ConnectorProperties object itself. + */ + public ConnectorProperties withConnectorType(Platform connectorType) { + this.connectorType = connectorType; + return this; + } + + /** + * Get the lastRunTimeStamp property: last run time stamp of this connector in UTC time zone. + * + * @return the lastRunTimeStamp value. + */ + public OffsetDateTime lastRunTimeStamp() { + return this.lastRunTimeStamp; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (connectorType() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property connectorType in model ConnectorProperties")); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(ConnectorProperties.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("connectorType", this.connectorType == null ? null : this.connectorType.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ConnectorProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ConnectorProperties 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 ConnectorProperties. + */ + public static ConnectorProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ConnectorProperties deserializedConnectorProperties = new ConnectorProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("connectorId".equals(fieldName)) { + deserializedConnectorProperties.connectorId = reader.getString(); + } else if ("tenantId".equals(fieldName)) { + deserializedConnectorProperties.tenantId = reader.getString(); + } else if ("connectorType".equals(fieldName)) { + deserializedConnectorProperties.connectorType = Platform.fromString(reader.getString()); + } else if ("lastRunTimeStamp".equals(fieldName)) { + deserializedConnectorProperties.lastRunTimeStamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("provisioningState".equals(fieldName)) { + deserializedConnectorProperties.provisioningState + = ProvisioningState.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedConnectorProperties; + }); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ConnectorUpdate.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ConnectorUpdate.java new file mode 100644 index 000000000000..e1aad6bac126 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ConnectorUpdate.java @@ -0,0 +1,96 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.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; + +/** + * The type used for update operations of the Connector. + */ +@Fluent +public final class ConnectorUpdate implements JsonSerializable { + /* + * The resource-specific properties for this resource. + */ + private ConnectorUpdateProperties properties; + + /** + * Creates an instance of ConnectorUpdate class. + */ + public ConnectorUpdate() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public ConnectorUpdateProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the ConnectorUpdate object itself. + */ + public ConnectorUpdate withProperties(ConnectorUpdateProperties properties) { + this.properties = properties; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ConnectorUpdate from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ConnectorUpdate 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 ConnectorUpdate. + */ + public static ConnectorUpdate fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ConnectorUpdate deserializedConnectorUpdate = new ConnectorUpdate(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("properties".equals(fieldName)) { + deserializedConnectorUpdate.properties = ConnectorUpdateProperties.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedConnectorUpdate; + }); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ConnectorUpdateProperties.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ConnectorUpdateProperties.java new file mode 100644 index 000000000000..daaebed8efcf --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ConnectorUpdateProperties.java @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.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; + +/** + * The updatable properties of the Connector. + */ +@Fluent +public final class ConnectorUpdateProperties implements JsonSerializable { + /* + * connector type + */ + private Platform connectorType; + + /** + * Creates an instance of ConnectorUpdateProperties class. + */ + public ConnectorUpdateProperties() { + } + + /** + * Get the connectorType property: connector type. + * + * @return the connectorType value. + */ + public Platform connectorType() { + return this.connectorType; + } + + /** + * Set the connectorType property: connector type. + * + * @param connectorType the connectorType value to set. + * @return the ConnectorUpdateProperties object itself. + */ + public ConnectorUpdateProperties withConnectorType(Platform connectorType) { + this.connectorType = connectorType; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("connectorType", this.connectorType == null ? null : this.connectorType.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ConnectorUpdateProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ConnectorUpdateProperties 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 ConnectorUpdateProperties. + */ + public static ConnectorUpdateProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ConnectorUpdateProperties deserializedConnectorUpdateProperties = new ConnectorUpdateProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("connectorType".equals(fieldName)) { + deserializedConnectorUpdateProperties.connectorType = Platform.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedConnectorUpdateProperties; + }); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Connectors.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Connectors.java new file mode 100644 index 000000000000..33048e759177 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Connectors.java @@ -0,0 +1,132 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of Connectors. + */ +public interface Connectors { + /** + * Get a Connector. + * + * @param connectorName The name of the connector. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Connector along with {@link Response}. + */ + Response getWithResponse(String connectorName, Context context); + + /** + * Get a Connector. + * + * @param connectorName The name of the connector. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Connector. + */ + Connector get(String connectorName); + + /** + * Delete a Connector. + * + * @param connectorName The name of the connector. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteWithResponse(String connectorName, Context context); + + /** + * Delete a Connector. + * + * @param connectorName The name of the connector. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void delete(String connectorName); + + /** + * List Connector resources by subscription ID. + * + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Connector list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable list(); + + /** + * List Connector resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Connector list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable list(Context context); + + /** + * Get a Connector. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Connector along with {@link Response}. + */ + Connector getById(String id); + + /** + * Get a Connector. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Connector along with {@link Response}. + */ + Response getByIdWithResponse(String id, Context context); + + /** + * Delete a Connector. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteById(String id); + + /** + * Delete a Connector. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteByIdWithResponse(String id, Context context); + + /** + * Begins definition for a new Connector resource. + * + * @param name resource name. + * @return the first stage of the new Connector definition. + */ + Connector.DefinitionStages.Blank define(String name); +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Content.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Content.java new file mode 100644 index 000000000000..00ebe7dd1a40 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Content.java @@ -0,0 +1,133 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Article details of the insight like title, description etc. + */ +@Fluent +public final class Content implements JsonSerializable { + /* + * Title of the insight + */ + private String title; + + /* + * Description of the insight + */ + private String description; + + /** + * Creates an instance of Content class. + */ + public Content() { + } + + /** + * Get the title property: Title of the insight. + * + * @return the title value. + */ + public String title() { + return this.title; + } + + /** + * Set the title property: Title of the insight. + * + * @param title the title value to set. + * @return the Content object itself. + */ + public Content withTitle(String title) { + this.title = title; + return this; + } + + /** + * Get the description property: Description of the insight. + * + * @return the description value. + */ + public String description() { + return this.description; + } + + /** + * Set the description property: Description of the insight. + * + * @param description the description value to set. + * @return the Content object itself. + */ + public Content withDescription(String description) { + this.description = description; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (title() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property title in model Content")); + } + if (description() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property description in model Content")); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(Content.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("title", this.title); + jsonWriter.writeStringField("description", this.description); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of Content from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of Content 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 Content. + */ + public static Content fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Content deserializedContent = new Content(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("title".equals(fieldName)) { + deserializedContent.title = reader.getString(); + } else if ("description".equals(fieldName)) { + deserializedContent.description = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedContent; + }); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ErrorDetailProperties.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ErrorDetailProperties.java new file mode 100644 index 000000000000..88bb9519c2bb --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ErrorDetailProperties.java @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.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; + +/** + * ARM error code and error message associated with the impact. + */ +@Fluent +public final class ErrorDetailProperties implements JsonSerializable { + /* + * ARM Error code associated with the impact. + */ + private String errorCode; + + /* + * ARM Error Message associated with the impact + */ + private String errorMessage; + + /** + * Creates an instance of ErrorDetailProperties class. + */ + public ErrorDetailProperties() { + } + + /** + * Get the errorCode property: ARM Error code associated with the impact. + * + * @return the errorCode value. + */ + public String errorCode() { + return this.errorCode; + } + + /** + * Set the errorCode property: ARM Error code associated with the impact. + * + * @param errorCode the errorCode value to set. + * @return the ErrorDetailProperties object itself. + */ + public ErrorDetailProperties withErrorCode(String errorCode) { + this.errorCode = errorCode; + return this; + } + + /** + * Get the errorMessage property: ARM Error Message associated with the impact. + * + * @return the errorMessage value. + */ + public String errorMessage() { + return this.errorMessage; + } + + /** + * Set the errorMessage property: ARM Error Message associated with the impact. + * + * @param errorMessage the errorMessage value to set. + * @return the ErrorDetailProperties object itself. + */ + public ErrorDetailProperties withErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("errorCode", this.errorCode); + jsonWriter.writeStringField("errorMessage", this.errorMessage); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ErrorDetailProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ErrorDetailProperties 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 ErrorDetailProperties. + */ + public static ErrorDetailProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ErrorDetailProperties deserializedErrorDetailProperties = new ErrorDetailProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("errorCode".equals(fieldName)) { + deserializedErrorDetailProperties.errorCode = reader.getString(); + } else if ("errorMessage".equals(fieldName)) { + deserializedErrorDetailProperties.errorMessage = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedErrorDetailProperties; + }); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ExpectedValueRange.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ExpectedValueRange.java new file mode 100644 index 000000000000..13d2e17db7c8 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ExpectedValueRange.java @@ -0,0 +1,122 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.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; + +/** + * Max and Min Threshold values for the metric. + */ +@Fluent +public final class ExpectedValueRange implements JsonSerializable { + /* + * Min threshold value for the metric + */ + private double min; + + /* + * Max threshold value for the metric + */ + private double max; + + /** + * Creates an instance of ExpectedValueRange class. + */ + public ExpectedValueRange() { + } + + /** + * Get the min property: Min threshold value for the metric. + * + * @return the min value. + */ + public double min() { + return this.min; + } + + /** + * Set the min property: Min threshold value for the metric. + * + * @param min the min value to set. + * @return the ExpectedValueRange object itself. + */ + public ExpectedValueRange withMin(double min) { + this.min = min; + return this; + } + + /** + * Get the max property: Max threshold value for the metric. + * + * @return the max value. + */ + public double max() { + return this.max; + } + + /** + * Set the max property: Max threshold value for the metric. + * + * @param max the max value to set. + * @return the ExpectedValueRange object itself. + */ + public ExpectedValueRange withMax(double max) { + this.max = max; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeDoubleField("min", this.min); + jsonWriter.writeDoubleField("max", this.max); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ExpectedValueRange from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ExpectedValueRange 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 ExpectedValueRange. + */ + public static ExpectedValueRange fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ExpectedValueRange deserializedExpectedValueRange = new ExpectedValueRange(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("min".equals(fieldName)) { + deserializedExpectedValueRange.min = reader.getDouble(); + } else if ("max".equals(fieldName)) { + deserializedExpectedValueRange.max = reader.getDouble(); + } else { + reader.skipChildren(); + } + } + + return deserializedExpectedValueRange; + }); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ImpactCategories.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ImpactCategories.java new file mode 100644 index 000000000000..f9ca7e2f9e7b --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ImpactCategories.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of ImpactCategories. + */ +public interface ImpactCategories { + /** + * Get a ImpactCategory. + * + * @param impactCategoryName Name of the impact category. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ImpactCategory along with {@link Response}. + */ + Response getWithResponse(String impactCategoryName, Context context); + + /** + * Get a ImpactCategory. + * + * @param impactCategoryName Name of the impact category. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ImpactCategory. + */ + ImpactCategory get(String impactCategoryName); + + /** + * List ImpactCategory resources by subscription. + * + * @param resourceType Filter by resource type. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ImpactCategory list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable list(String resourceType); + + /** + * List ImpactCategory resources by subscription. + * + * @param resourceType Filter by resource type. + * @param categoryName Filter by category name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ImpactCategory list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable list(String resourceType, String categoryName, Context context); +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ImpactCategory.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ImpactCategory.java new file mode 100644 index 000000000000..5477070356ff --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ImpactCategory.java @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.models; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.impactreporting.fluent.models.ImpactCategoryInner; + +/** + * An immutable client-side representation of ImpactCategory. + */ +public interface ImpactCategory { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + ImpactCategoryProperties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.impactreporting.fluent.models.ImpactCategoryInner object. + * + * @return the inner object. + */ + ImpactCategoryInner innerModel(); +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ImpactCategoryProperties.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ImpactCategoryProperties.java new file mode 100644 index 000000000000..5399431a19bf --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ImpactCategoryProperties.java @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.logging.ClientLogger; +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; + +/** + * Impact category properties. + */ +@Immutable +public final class ImpactCategoryProperties implements JsonSerializable { + /* + * Resource provisioning state. + */ + private ProvisioningState provisioningState; + + /* + * Unique ID of the category + */ + private String categoryId; + + /* + * Unique ID of the parent category + */ + private String parentCategoryId; + + /* + * Description of the category + */ + private String description; + + /* + * The workloadImpact properties which are required when reporting with the impact category + */ + private List requiredImpactProperties; + + /** + * Creates an instance of ImpactCategoryProperties class. + */ + private ImpactCategoryProperties() { + } + + /** + * Get the provisioningState property: Resource provisioning state. + * + * @return the provisioningState value. + */ + public ProvisioningState provisioningState() { + return this.provisioningState; + } + + /** + * Get the categoryId property: Unique ID of the category. + * + * @return the categoryId value. + */ + public String categoryId() { + return this.categoryId; + } + + /** + * Get the parentCategoryId property: Unique ID of the parent category. + * + * @return the parentCategoryId value. + */ + public String parentCategoryId() { + return this.parentCategoryId; + } + + /** + * Get the description property: Description of the category. + * + * @return the description value. + */ + public String description() { + return this.description; + } + + /** + * Get the requiredImpactProperties property: The workloadImpact properties which are required when reporting with + * the impact category. + * + * @return the requiredImpactProperties value. + */ + public List requiredImpactProperties() { + return this.requiredImpactProperties; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (categoryId() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property categoryId in model ImpactCategoryProperties")); + } + if (requiredImpactProperties() != null) { + requiredImpactProperties().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(ImpactCategoryProperties.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("categoryId", this.categoryId); + jsonWriter.writeStringField("parentCategoryId", this.parentCategoryId); + jsonWriter.writeStringField("description", this.description); + jsonWriter.writeArrayField("requiredImpactProperties", this.requiredImpactProperties, + (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ImpactCategoryProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ImpactCategoryProperties 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 ImpactCategoryProperties. + */ + public static ImpactCategoryProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ImpactCategoryProperties deserializedImpactCategoryProperties = new ImpactCategoryProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("categoryId".equals(fieldName)) { + deserializedImpactCategoryProperties.categoryId = reader.getString(); + } else if ("provisioningState".equals(fieldName)) { + deserializedImpactCategoryProperties.provisioningState + = ProvisioningState.fromString(reader.getString()); + } else if ("parentCategoryId".equals(fieldName)) { + deserializedImpactCategoryProperties.parentCategoryId = reader.getString(); + } else if ("description".equals(fieldName)) { + deserializedImpactCategoryProperties.description = reader.getString(); + } else if ("requiredImpactProperties".equals(fieldName)) { + List requiredImpactProperties + = reader.readArray(reader1 -> RequiredImpactProperties.fromJson(reader1)); + deserializedImpactCategoryProperties.requiredImpactProperties = requiredImpactProperties; + } else { + reader.skipChildren(); + } + } + + return deserializedImpactCategoryProperties; + }); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ImpactDetails.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ImpactDetails.java new file mode 100644 index 000000000000..401d9748666a --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ImpactDetails.java @@ -0,0 +1,201 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; +import com.azure.core.util.logging.ClientLogger; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * details of of the impact for which insight has been generated. + */ +@Fluent +public final class ImpactDetails implements JsonSerializable { + /* + * List of impacted Azure resources. + */ + private String impactedResourceId; + + /* + * Time at which impact was started according to reported impact. + */ + private OffsetDateTime startTime; + + /* + * Time at which impact was ended according to reported impact. + */ + private OffsetDateTime endTime; + + /* + * Azure Id of the impact. + */ + private String impactId; + + /** + * Creates an instance of ImpactDetails class. + */ + public ImpactDetails() { + } + + /** + * Get the impactedResourceId property: List of impacted Azure resources. + * + * @return the impactedResourceId value. + */ + public String impactedResourceId() { + return this.impactedResourceId; + } + + /** + * Set the impactedResourceId property: List of impacted Azure resources. + * + * @param impactedResourceId the impactedResourceId value to set. + * @return the ImpactDetails object itself. + */ + public ImpactDetails withImpactedResourceId(String impactedResourceId) { + this.impactedResourceId = impactedResourceId; + return this; + } + + /** + * Get the startTime property: Time at which impact was started according to reported impact. + * + * @return the startTime value. + */ + public OffsetDateTime startTime() { + return this.startTime; + } + + /** + * Set the startTime property: Time at which impact was started according to reported impact. + * + * @param startTime the startTime value to set. + * @return the ImpactDetails object itself. + */ + public ImpactDetails withStartTime(OffsetDateTime startTime) { + this.startTime = startTime; + return this; + } + + /** + * Get the endTime property: Time at which impact was ended according to reported impact. + * + * @return the endTime value. + */ + public OffsetDateTime endTime() { + return this.endTime; + } + + /** + * Set the endTime property: Time at which impact was ended according to reported impact. + * + * @param endTime the endTime value to set. + * @return the ImpactDetails object itself. + */ + public ImpactDetails withEndTime(OffsetDateTime endTime) { + this.endTime = endTime; + return this; + } + + /** + * Get the impactId property: Azure Id of the impact. + * + * @return the impactId value. + */ + public String impactId() { + return this.impactId; + } + + /** + * Set the impactId property: Azure Id of the impact. + * + * @param impactId the impactId value to set. + * @return the ImpactDetails object itself. + */ + public ImpactDetails withImpactId(String impactId) { + this.impactId = impactId; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (impactedResourceId() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property impactedResourceId in model ImpactDetails")); + } + if (startTime() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property startTime in model ImpactDetails")); + } + if (impactId() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property impactId in model ImpactDetails")); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(ImpactDetails.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("impactedResourceId", this.impactedResourceId); + jsonWriter.writeStringField("startTime", + this.startTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.startTime)); + jsonWriter.writeStringField("impactId", this.impactId); + jsonWriter.writeStringField("endTime", + this.endTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.endTime)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ImpactDetails from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ImpactDetails 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 ImpactDetails. + */ + public static ImpactDetails fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ImpactDetails deserializedImpactDetails = new ImpactDetails(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("impactedResourceId".equals(fieldName)) { + deserializedImpactDetails.impactedResourceId = reader.getString(); + } else if ("startTime".equals(fieldName)) { + deserializedImpactDetails.startTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("impactId".equals(fieldName)) { + deserializedImpactDetails.impactId = reader.getString(); + } else if ("endTime".equals(fieldName)) { + deserializedImpactDetails.endTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else { + reader.skipChildren(); + } + } + + return deserializedImpactDetails; + }); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/IncidentSource.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/IncidentSource.java new file mode 100644 index 000000000000..81031c3b2af7 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/IncidentSource.java @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * List of incident interfaces. + */ +public final class IncidentSource extends ExpandableStringEnum { + /** + * When source of Incident is AzureDevops. + */ + public static final IncidentSource AZURE_DEVOPS = fromString("AzureDevops"); + + /** + * When source of Incident is Microsoft ICM. + */ + public static final IncidentSource ICM = fromString("ICM"); + + /** + * When source of Incident is Jira. + */ + public static final IncidentSource JIRA = fromString("Jira"); + + /** + * When source of Incident is ServiceNow. + */ + public static final IncidentSource SERVICE_NOW = fromString("ServiceNow"); + + /** + * When source of Incident is Other. + */ + public static final IncidentSource OTHER = fromString("Other"); + + /** + * Creates a new instance of IncidentSource value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public IncidentSource() { + } + + /** + * Creates or finds a IncidentSource from its string representation. + * + * @param name a name to look for. + * @return the corresponding IncidentSource. + */ + public static IncidentSource fromString(String name) { + return fromString(name, IncidentSource.class); + } + + /** + * Gets known IncidentSource values. + * + * @return known IncidentSource values. + */ + public static Collection values() { + return values(IncidentSource.class); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Insight.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Insight.java new file mode 100644 index 000000000000..d8e58179c386 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Insight.java @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.models; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.impactreporting.fluent.models.InsightInner; + +/** + * An immutable client-side representation of Insight. + */ +public interface Insight { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + InsightProperties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.impactreporting.fluent.models.InsightInner object. + * + * @return the inner object. + */ + InsightInner innerModel(); + + /** + * The entirety of the Insight definition. + */ + interface Definition + extends DefinitionStages.Blank, DefinitionStages.WithParentResource, DefinitionStages.WithCreate { + } + + /** + * The Insight definition stages. + */ + interface DefinitionStages { + /** + * The first stage of the Insight definition. + */ + interface Blank extends WithParentResource { + } + + /** + * The stage of the Insight definition allowing to specify parent resource. + */ + interface WithParentResource { + /** + * Specifies workloadImpactName. + * + * @param workloadImpactName workloadImpact resource. + * @return the next definition stage. + */ + WithCreate withExistingWorkloadImpact(String workloadImpactName); + } + + /** + * The stage of the Insight definition which contains all the minimum required properties for the resource to be + * created, but also allows for any other optional properties to be specified. + */ + interface WithCreate extends DefinitionStages.WithProperties { + /** + * Executes the create request. + * + * @return the created resource. + */ + Insight create(); + + /** + * Executes the create request. + * + * @param context The context to associate with this operation. + * @return the created resource. + */ + Insight create(Context context); + } + + /** + * The stage of the Insight definition allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The resource-specific properties for this resource.. + * + * @param properties The resource-specific properties for this resource. + * @return the next definition stage. + */ + WithCreate withProperties(InsightProperties properties); + } + } + + /** + * Refreshes the resource to sync with Azure. + * + * @return the refreshed resource. + */ + Insight refresh(); + + /** + * Refreshes the resource to sync with Azure. + * + * @param context The context to associate with this operation. + * @return the refreshed resource. + */ + Insight refresh(Context context); +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/InsightProperties.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/InsightProperties.java new file mode 100644 index 000000000000..d2cb5ff8c403 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/InsightProperties.java @@ -0,0 +1,370 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; +import com.azure.core.util.logging.ClientLogger; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Impact category properties. + */ +@Fluent +public final class InsightProperties implements JsonSerializable { + /* + * Resource provisioning state. + */ + private ProvisioningState provisioningState; + + /* + * category of the insight. + */ + private String category; + + /* + * status of the insight. example resolved, repaired, other. + */ + private String status; + + /* + * Identifier of the event that has been correlated with this insight. This can be used to aggregate insights for + * the same event. + */ + private String eventId; + + /* + * Identifier that can be used to group similar insights. + */ + private String groupId; + + /* + * Contains title & description for the insight + */ + private Content content; + + /* + * Time of the event, which has been correlated the impact. + */ + private OffsetDateTime eventTime; + + /* + * unique id of the insight. + */ + private String insightUniqueId; + + /* + * details of of the impact for which insight has been generated. + */ + private ImpactDetails impact; + + /* + * additional details of the insight. + */ + private InsightPropertiesAdditionalDetails additionalDetails; + + /** + * Creates an instance of InsightProperties class. + */ + public InsightProperties() { + } + + /** + * Get the provisioningState property: Resource provisioning state. + * + * @return the provisioningState value. + */ + public ProvisioningState provisioningState() { + return this.provisioningState; + } + + /** + * Get the category property: category of the insight. + * + * @return the category value. + */ + public String category() { + return this.category; + } + + /** + * Set the category property: category of the insight. + * + * @param category the category value to set. + * @return the InsightProperties object itself. + */ + public InsightProperties withCategory(String category) { + this.category = category; + return this; + } + + /** + * Get the status property: status of the insight. example resolved, repaired, other. + * + * @return the status value. + */ + public String status() { + return this.status; + } + + /** + * Set the status property: status of the insight. example resolved, repaired, other. + * + * @param status the status value to set. + * @return the InsightProperties object itself. + */ + public InsightProperties withStatus(String status) { + this.status = status; + return this; + } + + /** + * Get the eventId property: Identifier of the event that has been correlated with this insight. This can be used to + * aggregate insights for the same event. + * + * @return the eventId value. + */ + public String eventId() { + return this.eventId; + } + + /** + * Set the eventId property: Identifier of the event that has been correlated with this insight. This can be used to + * aggregate insights for the same event. + * + * @param eventId the eventId value to set. + * @return the InsightProperties object itself. + */ + public InsightProperties withEventId(String eventId) { + this.eventId = eventId; + return this; + } + + /** + * Get the groupId property: Identifier that can be used to group similar insights. + * + * @return the groupId value. + */ + public String groupId() { + return this.groupId; + } + + /** + * Set the groupId property: Identifier that can be used to group similar insights. + * + * @param groupId the groupId value to set. + * @return the InsightProperties object itself. + */ + public InsightProperties withGroupId(String groupId) { + this.groupId = groupId; + return this; + } + + /** + * Get the content property: Contains title & description for the insight. + * + * @return the content value. + */ + public Content content() { + return this.content; + } + + /** + * Set the content property: Contains title & description for the insight. + * + * @param content the content value to set. + * @return the InsightProperties object itself. + */ + public InsightProperties withContent(Content content) { + this.content = content; + return this; + } + + /** + * Get the eventTime property: Time of the event, which has been correlated the impact. + * + * @return the eventTime value. + */ + public OffsetDateTime eventTime() { + return this.eventTime; + } + + /** + * Set the eventTime property: Time of the event, which has been correlated the impact. + * + * @param eventTime the eventTime value to set. + * @return the InsightProperties object itself. + */ + public InsightProperties withEventTime(OffsetDateTime eventTime) { + this.eventTime = eventTime; + return this; + } + + /** + * Get the insightUniqueId property: unique id of the insight. + * + * @return the insightUniqueId value. + */ + public String insightUniqueId() { + return this.insightUniqueId; + } + + /** + * Set the insightUniqueId property: unique id of the insight. + * + * @param insightUniqueId the insightUniqueId value to set. + * @return the InsightProperties object itself. + */ + public InsightProperties withInsightUniqueId(String insightUniqueId) { + this.insightUniqueId = insightUniqueId; + return this; + } + + /** + * Get the impact property: details of of the impact for which insight has been generated. + * + * @return the impact value. + */ + public ImpactDetails impact() { + return this.impact; + } + + /** + * Set the impact property: details of of the impact for which insight has been generated. + * + * @param impact the impact value to set. + * @return the InsightProperties object itself. + */ + public InsightProperties withImpact(ImpactDetails impact) { + this.impact = impact; + return this; + } + + /** + * Get the additionalDetails property: additional details of the insight. + * + * @return the additionalDetails value. + */ + public InsightPropertiesAdditionalDetails additionalDetails() { + return this.additionalDetails; + } + + /** + * Set the additionalDetails property: additional details of the insight. + * + * @param additionalDetails the additionalDetails value to set. + * @return the InsightProperties object itself. + */ + public InsightProperties withAdditionalDetails(InsightPropertiesAdditionalDetails additionalDetails) { + this.additionalDetails = additionalDetails; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (category() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property category in model InsightProperties")); + } + if (content() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property content in model InsightProperties")); + } else { + content().validate(); + } + if (insightUniqueId() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property insightUniqueId in model InsightProperties")); + } + if (impact() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property impact in model InsightProperties")); + } else { + impact().validate(); + } + if (additionalDetails() != null) { + additionalDetails().validate(); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(InsightProperties.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("category", this.category); + jsonWriter.writeJsonField("content", this.content); + jsonWriter.writeStringField("insightUniqueId", this.insightUniqueId); + jsonWriter.writeJsonField("impact", this.impact); + jsonWriter.writeStringField("status", this.status); + jsonWriter.writeStringField("eventId", this.eventId); + jsonWriter.writeStringField("groupId", this.groupId); + jsonWriter.writeStringField("eventTime", + this.eventTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.eventTime)); + jsonWriter.writeJsonField("additionalDetails", this.additionalDetails); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of InsightProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of InsightProperties 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 InsightProperties. + */ + public static InsightProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + InsightProperties deserializedInsightProperties = new InsightProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("category".equals(fieldName)) { + deserializedInsightProperties.category = reader.getString(); + } else if ("content".equals(fieldName)) { + deserializedInsightProperties.content = Content.fromJson(reader); + } else if ("insightUniqueId".equals(fieldName)) { + deserializedInsightProperties.insightUniqueId = reader.getString(); + } else if ("impact".equals(fieldName)) { + deserializedInsightProperties.impact = ImpactDetails.fromJson(reader); + } else if ("provisioningState".equals(fieldName)) { + deserializedInsightProperties.provisioningState = ProvisioningState.fromString(reader.getString()); + } else if ("status".equals(fieldName)) { + deserializedInsightProperties.status = reader.getString(); + } else if ("eventId".equals(fieldName)) { + deserializedInsightProperties.eventId = reader.getString(); + } else if ("groupId".equals(fieldName)) { + deserializedInsightProperties.groupId = reader.getString(); + } else if ("eventTime".equals(fieldName)) { + deserializedInsightProperties.eventTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("additionalDetails".equals(fieldName)) { + deserializedInsightProperties.additionalDetails + = InsightPropertiesAdditionalDetails.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedInsightProperties; + }); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/InsightPropertiesAdditionalDetails.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/InsightPropertiesAdditionalDetails.java new file mode 100644 index 000000000000..d55d2626b092 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/InsightPropertiesAdditionalDetails.java @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.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 InsightPropertiesAdditionalDetails model. + */ +@Immutable +public final class InsightPropertiesAdditionalDetails implements JsonSerializable { + /** + * Creates an instance of InsightPropertiesAdditionalDetails class. + */ + public InsightPropertiesAdditionalDetails() { + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of InsightPropertiesAdditionalDetails from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of InsightPropertiesAdditionalDetails 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 InsightPropertiesAdditionalDetails. + */ + public static InsightPropertiesAdditionalDetails fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + InsightPropertiesAdditionalDetails deserializedInsightPropertiesAdditionalDetails + = new InsightPropertiesAdditionalDetails(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + reader.skipChildren(); + } + + return deserializedInsightPropertiesAdditionalDetails; + }); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Insights.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Insights.java new file mode 100644 index 000000000000..77772e0942f4 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Insights.java @@ -0,0 +1,139 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of Insights. + */ +public interface Insights { + /** + * Get Insight resources by workloadImpactName and insightName. + * + * @param workloadImpactName workloadImpact resource. + * @param insightName Name of the insight. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return insight resources by workloadImpactName and insightName along with {@link Response}. + */ + Response getWithResponse(String workloadImpactName, String insightName, Context context); + + /** + * Get Insight resources by workloadImpactName and insightName. + * + * @param workloadImpactName workloadImpact resource. + * @param insightName Name of the insight. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return insight resources by workloadImpactName and insightName. + */ + Insight get(String workloadImpactName, String insightName); + + /** + * List Insight resources by workloadImpactName. + * + * @param workloadImpactName workloadImpact resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Insight list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listBySubscription(String workloadImpactName); + + /** + * List Insight resources by workloadImpactName. + * + * @param workloadImpactName workloadImpact resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Insight list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listBySubscription(String workloadImpactName, Context context); + + /** + * Delete Insight resource, This is Admin only operation. + * + * @param workloadImpactName workloadImpact resource. + * @param insightName Name of the insight. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteByResourceGroupWithResponse(String workloadImpactName, String insightName, Context context); + + /** + * Delete Insight resource, This is Admin only operation. + * + * @param workloadImpactName workloadImpact resource. + * @param insightName Name of the insight. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteByResourceGroup(String workloadImpactName, String insightName); + + /** + * Get Insight resources by workloadImpactName and insightName. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return insight resources by workloadImpactName and insightName along with {@link Response}. + */ + Insight getById(String id); + + /** + * Get Insight resources by workloadImpactName and insightName. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return insight resources by workloadImpactName and insightName along with {@link Response}. + */ + Response getByIdWithResponse(String id, Context context); + + /** + * Delete Insight resource, This is Admin only operation. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteById(String id); + + /** + * Delete Insight resource, This is Admin only operation. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteByIdWithResponse(String id, Context context); + + /** + * Begins definition for a new Insight resource. + * + * @param name resource name. + * @return the first stage of the new Insight definition. + */ + Insight.DefinitionStages.Blank define(String name); +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/MetricUnit.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/MetricUnit.java new file mode 100644 index 000000000000..b2ace50e5f30 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/MetricUnit.java @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * List of unit of the metric. + */ +public final class MetricUnit extends ExpandableStringEnum { + /** + * When measurement is in ByteSeconds. + */ + public static final MetricUnit BYTE_SECONDS = fromString("ByteSeconds"); + + /** + * When measurement is in Bytes. + */ + public static final MetricUnit BYTES = fromString("Bytes"); + + /** + * When measurement is in BytesPerSecond. + */ + public static final MetricUnit BYTES_PER_SECOND = fromString("BytesPerSecond"); + + /** + * When measurement is in Cores. + */ + public static final MetricUnit CORES = fromString("Cores"); + + /** + * When measurement is in Count. + */ + public static final MetricUnit COUNT = fromString("Count"); + + /** + * When measurement is in CountPerSecond. + */ + public static final MetricUnit COUNT_PER_SECOND = fromString("CountPerSecond"); + + /** + * When measurement is in MilliCores. + */ + public static final MetricUnit MILLI_CORES = fromString("MilliCores"); + + /** + * When measurement is in MilliSeconds. + */ + public static final MetricUnit MILLI_SECONDS = fromString("MilliSeconds"); + + /** + * When measurement is in NanoCores. + */ + public static final MetricUnit NANO_CORES = fromString("NanoCores"); + + /** + * When measurement is in Percent. + */ + public static final MetricUnit PERCENT = fromString("Percent"); + + /** + * When measurement is in Seconds. + */ + public static final MetricUnit SECONDS = fromString("Seconds"); + + /** + * When measurement is in Other than listed. + */ + public static final MetricUnit OTHER = fromString("Other"); + + /** + * Creates a new instance of MetricUnit value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public MetricUnit() { + } + + /** + * Creates or finds a MetricUnit from its string representation. + * + * @param name a name to look for. + * @return the corresponding MetricUnit. + */ + public static MetricUnit fromString(String name) { + return fromString(name, MetricUnit.class); + } + + /** + * Gets known MetricUnit values. + * + * @return known MetricUnit values. + */ + public static Collection values() { + return values(MetricUnit.class); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Operation.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Operation.java new file mode 100644 index 000000000000..929ad7b6e171 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Operation.java @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.models; + +import com.azure.resourcemanager.impactreporting.fluent.models.OperationInner; + +/** + * An immutable client-side representation of Operation. + */ +public interface Operation { + /** + * Gets the name property: The name of the operation, as per Resource-Based Access Control (RBAC). Examples: + * "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action". + * + * @return the name value. + */ + String name(); + + /** + * Gets the isDataAction property: Whether the operation applies to data-plane. This is "true" for data-plane + * operations and "false" for Azure Resource Manager/control-plane operations. + * + * @return the isDataAction value. + */ + Boolean isDataAction(); + + /** + * Gets the display property: Localized display information for this particular operation. + * + * @return the display value. + */ + OperationDisplay display(); + + /** + * Gets the origin property: The intended executor of the operation; as in Resource Based Access Control (RBAC) and + * audit logs UX. Default value is "user,system". + * + * @return the origin value. + */ + Origin origin(); + + /** + * Gets the actionType property: Extensible enum. Indicates the action type. "Internal" refers to actions that are + * for internal only APIs. + * + * @return the actionType value. + */ + ActionType actionType(); + + /** + * Gets the inner com.azure.resourcemanager.impactreporting.fluent.models.OperationInner object. + * + * @return the inner object. + */ + OperationInner innerModel(); +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/OperationDisplay.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/OperationDisplay.java new file mode 100644 index 000000000000..1a47aeb3f0dd --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/OperationDisplay.java @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.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; + +/** + * Localized display information for and operation. + */ +@Immutable +public final class OperationDisplay implements JsonSerializable { + /* + * The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or + * "Microsoft Compute". + */ + private String provider; + + /* + * The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or + * "Job Schedule Collections". + */ + private String resource; + + /* + * The concise, localized friendly name for the operation; suitable for dropdowns. E.g. + * "Create or Update Virtual Machine", "Restart Virtual Machine". + */ + private String operation; + + /* + * The short, localized friendly description of the operation; suitable for tool tips and detailed views. + */ + private String description; + + /** + * Creates an instance of OperationDisplay class. + */ + private OperationDisplay() { + } + + /** + * Get the provider property: The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring + * Insights" or "Microsoft Compute". + * + * @return the provider value. + */ + public String provider() { + return this.provider; + } + + /** + * Get the resource property: The localized friendly name of the resource type related to this operation. E.g. + * "Virtual Machines" or "Job Schedule Collections". + * + * @return the resource value. + */ + public String resource() { + return this.resource; + } + + /** + * Get the operation property: The concise, localized friendly name for the operation; suitable for dropdowns. E.g. + * "Create or Update Virtual Machine", "Restart Virtual Machine". + * + * @return the operation value. + */ + public String operation() { + return this.operation; + } + + /** + * Get the description property: The short, localized friendly description of the operation; suitable for tool tips + * and detailed views. + * + * @return the description value. + */ + public String description() { + return this.description; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OperationDisplay from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OperationDisplay 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 OperationDisplay. + */ + public static OperationDisplay fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OperationDisplay deserializedOperationDisplay = new OperationDisplay(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("provider".equals(fieldName)) { + deserializedOperationDisplay.provider = reader.getString(); + } else if ("resource".equals(fieldName)) { + deserializedOperationDisplay.resource = reader.getString(); + } else if ("operation".equals(fieldName)) { + deserializedOperationDisplay.operation = reader.getString(); + } else if ("description".equals(fieldName)) { + deserializedOperationDisplay.description = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedOperationDisplay; + }); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Operations.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Operations.java new file mode 100644 index 000000000000..3f13aaceba29 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Operations.java @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.Context; + +/** + * Resource collection API of Operations. + */ +public interface Operations { + /** + * List the operations for the provider. + * + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedIterable}. + */ + PagedIterable list(); + + /** + * List the operations for the provider. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedIterable}. + */ + PagedIterable list(Context context); +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Origin.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Origin.java new file mode 100644 index 000000000000..9667d7994b69 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Origin.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value + * is "user,system". + */ +public final class Origin extends ExpandableStringEnum { + /** + * Indicates the operation is initiated by a user. + */ + public static final Origin USER = fromString("user"); + + /** + * Indicates the operation is initiated by a system. + */ + public static final Origin SYSTEM = fromString("system"); + + /** + * Indicates the operation is initiated by a user or system. + */ + public static final Origin USER_SYSTEM = fromString("user,system"); + + /** + * Creates a new instance of Origin value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public Origin() { + } + + /** + * Creates or finds a Origin from its string representation. + * + * @param name a name to look for. + * @return the corresponding Origin. + */ + public static Origin fromString(String name) { + return fromString(name, Origin.class); + } + + /** + * Gets known Origin values. + * + * @return known Origin values. + */ + public static Collection values() { + return values(Origin.class); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Performance.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Performance.java new file mode 100644 index 000000000000..3381a87020c5 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Performance.java @@ -0,0 +1,212 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.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; + +/** + * Details about impacted performance metrics. Applicable for performance related impact. + */ +@Fluent +public final class Performance implements JsonSerializable { + /* + * Name of the Metric examples: Disk, IOPs, CPU, GPU, Memory, details can be found from /impactCategories API + */ + private String metricName; + + /* + * Threshold value for the metric + */ + private Double expected; + + /* + * Observed value for the metric + */ + private Double actual; + + /* + * Max and Min Threshold values for the metric + */ + private ExpectedValueRange expectedValueRange; + + /* + * Unit of the metric ex: Bytes, Percentage, Count, Seconds, Milliseconds, Bytes/Second, Count/Second, etc.., Other + */ + private MetricUnit unit; + + /** + * Creates an instance of Performance class. + */ + public Performance() { + } + + /** + * Get the metricName property: Name of the Metric examples: Disk, IOPs, CPU, GPU, Memory, details can be found from + * /impactCategories API. + * + * @return the metricName value. + */ + public String metricName() { + return this.metricName; + } + + /** + * Set the metricName property: Name of the Metric examples: Disk, IOPs, CPU, GPU, Memory, details can be found from + * /impactCategories API. + * + * @param metricName the metricName value to set. + * @return the Performance object itself. + */ + public Performance withMetricName(String metricName) { + this.metricName = metricName; + return this; + } + + /** + * Get the expected property: Threshold value for the metric. + * + * @return the expected value. + */ + public Double expected() { + return this.expected; + } + + /** + * Set the expected property: Threshold value for the metric. + * + * @param expected the expected value to set. + * @return the Performance object itself. + */ + public Performance withExpected(Double expected) { + this.expected = expected; + return this; + } + + /** + * Get the actual property: Observed value for the metric. + * + * @return the actual value. + */ + public Double actual() { + return this.actual; + } + + /** + * Set the actual property: Observed value for the metric. + * + * @param actual the actual value to set. + * @return the Performance object itself. + */ + public Performance withActual(Double actual) { + this.actual = actual; + return this; + } + + /** + * Get the expectedValueRange property: Max and Min Threshold values for the metric. + * + * @return the expectedValueRange value. + */ + public ExpectedValueRange expectedValueRange() { + return this.expectedValueRange; + } + + /** + * Set the expectedValueRange property: Max and Min Threshold values for the metric. + * + * @param expectedValueRange the expectedValueRange value to set. + * @return the Performance object itself. + */ + public Performance withExpectedValueRange(ExpectedValueRange expectedValueRange) { + this.expectedValueRange = expectedValueRange; + return this; + } + + /** + * Get the unit property: Unit of the metric ex: Bytes, Percentage, Count, Seconds, Milliseconds, Bytes/Second, + * Count/Second, etc.., Other. + * + * @return the unit value. + */ + public MetricUnit unit() { + return this.unit; + } + + /** + * Set the unit property: Unit of the metric ex: Bytes, Percentage, Count, Seconds, Milliseconds, Bytes/Second, + * Count/Second, etc.., Other. + * + * @param unit the unit value to set. + * @return the Performance object itself. + */ + public Performance withUnit(MetricUnit unit) { + this.unit = unit; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (expectedValueRange() != null) { + expectedValueRange().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("metricName", this.metricName); + jsonWriter.writeNumberField("expected", this.expected); + jsonWriter.writeNumberField("actual", this.actual); + jsonWriter.writeJsonField("expectedValueRange", this.expectedValueRange); + jsonWriter.writeStringField("unit", this.unit == null ? null : this.unit.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of Performance from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of Performance 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 Performance. + */ + public static Performance fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Performance deserializedPerformance = new Performance(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("metricName".equals(fieldName)) { + deserializedPerformance.metricName = reader.getString(); + } else if ("expected".equals(fieldName)) { + deserializedPerformance.expected = reader.getNullable(JsonReader::getDouble); + } else if ("actual".equals(fieldName)) { + deserializedPerformance.actual = reader.getNullable(JsonReader::getDouble); + } else if ("expectedValueRange".equals(fieldName)) { + deserializedPerformance.expectedValueRange = ExpectedValueRange.fromJson(reader); + } else if ("unit".equals(fieldName)) { + deserializedPerformance.unit = MetricUnit.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedPerformance; + }); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Platform.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Platform.java new file mode 100644 index 000000000000..c6f888c8ce96 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Platform.java @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Enum for connector types. + */ +public final class Platform extends ExpandableStringEnum { + /** + * Type of Azure Monitor. + */ + public static final Platform AZURE_MONITOR = fromString("AzureMonitor"); + + /** + * Creates a new instance of Platform value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public Platform() { + } + + /** + * Creates or finds a Platform from its string representation. + * + * @param name a name to look for. + * @return the corresponding Platform. + */ + public static Platform fromString(String name) { + return fromString(name, Platform.class); + } + + /** + * Gets known Platform values. + * + * @return known Platform values. + */ + public static Collection values() { + return values(Platform.class); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Protocol.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Protocol.java new file mode 100644 index 000000000000..258fe7ff7597 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Protocol.java @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * List of protocols. + */ +public final class Protocol extends ExpandableStringEnum { + /** + * When communication protocol is TCP. + */ + public static final Protocol TCP = fromString("TCP"); + + /** + * When communication protocol is UDP. + */ + public static final Protocol UDP = fromString("UDP"); + + /** + * When communication protocol is HTTP. + */ + public static final Protocol HTTP = fromString("HTTP"); + + /** + * When communication protocol is HTTPS. + */ + public static final Protocol HTTPS = fromString("HTTPS"); + + /** + * When communication protocol is RDP. + */ + public static final Protocol RDP = fromString("RDP"); + + /** + * When communication protocol is FTP. + */ + public static final Protocol FTP = fromString("FTP"); + + /** + * When communication protocol is SSH. + */ + public static final Protocol SSH = fromString("SSH"); + + /** + * When communication protocol is Other. + */ + public static final Protocol OTHER = fromString("Other"); + + /** + * Creates a new instance of Protocol value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public Protocol() { + } + + /** + * Creates or finds a Protocol from its string representation. + * + * @param name a name to look for. + * @return the corresponding Protocol. + */ + public static Protocol fromString(String name) { + return fromString(name, Protocol.class); + } + + /** + * Gets known Protocol values. + * + * @return known Protocol values. + */ + public static Collection values() { + return values(Protocol.class); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ProvisioningState.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ProvisioningState.java new file mode 100644 index 000000000000..0abb3dda78ab --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/ProvisioningState.java @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Provisioning state of the resource. + */ +public final class ProvisioningState extends ExpandableStringEnum { + /** + * Provisioning Succeeded. + */ + public static final ProvisioningState SUCCEEDED = fromString("Succeeded"); + + /** + * Provisioning Failed. + */ + public static final ProvisioningState FAILED = fromString("Failed"); + + /** + * Provisioning Canceled. + */ + public static final ProvisioningState CANCELED = fromString("Canceled"); + + /** + * Creates a new instance of ProvisioningState value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public ProvisioningState() { + } + + /** + * Creates or finds a ProvisioningState from its string representation. + * + * @param name a name to look for. + * @return the corresponding ProvisioningState. + */ + public static ProvisioningState fromString(String name) { + return fromString(name, ProvisioningState.class); + } + + /** + * Gets known ProvisioningState values. + * + * @return known ProvisioningState values. + */ + public static Collection values() { + return values(ProvisioningState.class); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/RequiredImpactProperties.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/RequiredImpactProperties.java new file mode 100644 index 000000000000..030f4dea1d3e --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/RequiredImpactProperties.java @@ -0,0 +1,110 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.logging.ClientLogger; +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; + +/** + * Required impact properties. + */ +@Immutable +public final class RequiredImpactProperties implements JsonSerializable { + /* + * Name of the property + */ + private String name; + + /* + * Allowed values values for the property + */ + private List allowedValues; + + /** + * Creates an instance of RequiredImpactProperties class. + */ + private RequiredImpactProperties() { + } + + /** + * Get the name property: Name of the property. + * + * @return the name value. + */ + public String name() { + return this.name; + } + + /** + * Get the allowedValues property: Allowed values values for the property. + * + * @return the allowedValues value. + */ + public List allowedValues() { + return this.allowedValues; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (name() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property name in model RequiredImpactProperties")); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(RequiredImpactProperties.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeArrayField("allowedValues", this.allowedValues, + (writer, element) -> writer.writeString(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of RequiredImpactProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of RequiredImpactProperties 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 RequiredImpactProperties. + */ + public static RequiredImpactProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + RequiredImpactProperties deserializedRequiredImpactProperties = new RequiredImpactProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("name".equals(fieldName)) { + deserializedRequiredImpactProperties.name = reader.getString(); + } else if ("allowedValues".equals(fieldName)) { + List allowedValues = reader.readArray(reader1 -> reader1.getString()); + deserializedRequiredImpactProperties.allowedValues = allowedValues; + } else { + reader.skipChildren(); + } + } + + return deserializedRequiredImpactProperties; + }); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/SourceOrTarget.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/SourceOrTarget.java new file mode 100644 index 000000000000..aa4899e72c72 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/SourceOrTarget.java @@ -0,0 +1,96 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.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; + +/** + * Resource details. + */ +@Fluent +public final class SourceOrTarget implements JsonSerializable { + /* + * Azure resource id, example + * /subscription/{subscription}/resourceGroup/{rg}/Microsoft.compute/virtualMachine/{vmName} + */ + private String azureResourceId; + + /** + * Creates an instance of SourceOrTarget class. + */ + public SourceOrTarget() { + } + + /** + * Get the azureResourceId property: Azure resource id, example + * /subscription/{subscription}/resourceGroup/{rg}/Microsoft.compute/virtualMachine/{vmName}. + * + * @return the azureResourceId value. + */ + public String azureResourceId() { + return this.azureResourceId; + } + + /** + * Set the azureResourceId property: Azure resource id, example + * /subscription/{subscription}/resourceGroup/{rg}/Microsoft.compute/virtualMachine/{vmName}. + * + * @param azureResourceId the azureResourceId value to set. + * @return the SourceOrTarget object itself. + */ + public SourceOrTarget withAzureResourceId(String azureResourceId) { + this.azureResourceId = azureResourceId; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("azureResourceId", this.azureResourceId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SourceOrTarget from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SourceOrTarget 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 SourceOrTarget. + */ + public static SourceOrTarget fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SourceOrTarget deserializedSourceOrTarget = new SourceOrTarget(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("azureResourceId".equals(fieldName)) { + deserializedSourceOrTarget.azureResourceId = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedSourceOrTarget; + }); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Toolset.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Toolset.java new file mode 100644 index 000000000000..f1700f2e5b3a --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Toolset.java @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * List of azure interfaces. + */ +public final class Toolset extends ExpandableStringEnum { + /** + * If communication toolset is Terraform. + */ + public static final Toolset TERRAFORM = fromString("Terraform"); + + /** + * If communication toolset is Puppet. + */ + public static final Toolset PUPPET = fromString("Puppet"); + + /** + * If communication toolset is Chef. + */ + public static final Toolset CHEF = fromString("Chef"); + + /** + * If communication toolset is SDK. + */ + public static final Toolset SDK = fromString("SDK"); + + /** + * If communication toolset is Ansible. + */ + public static final Toolset ANSIBLE = fromString("Ansible"); + + /** + * If communication toolset is ARM. + */ + public static final Toolset ARM = fromString("ARM"); + + /** + * If communication toolset is Portal. + */ + public static final Toolset PORTAL = fromString("Portal"); + + /** + * If communication toolset is Shell. + */ + public static final Toolset SHELL = fromString("Shell"); + + /** + * If communication toolset is Other. + */ + public static final Toolset OTHER = fromString("Other"); + + /** + * Creates a new instance of Toolset value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public Toolset() { + } + + /** + * Creates or finds a Toolset from its string representation. + * + * @param name a name to look for. + * @return the corresponding Toolset. + */ + public static Toolset fromString(String name) { + return fromString(name, Toolset.class); + } + + /** + * Gets known Toolset values. + * + * @return known Toolset values. + */ + public static Collection values() { + return values(Toolset.class); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Workload.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Workload.java new file mode 100644 index 000000000000..66b6c760d0e9 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/Workload.java @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.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; + +/** + * Information about the impacted workload. + */ +@Fluent +public final class Workload implements JsonSerializable { + /* + * the scenario for the workload + */ + private String context; + + /* + * Tool used to interact with Azure. SDK, AzPortal, etc.., Other + */ + private Toolset toolset; + + /** + * Creates an instance of Workload class. + */ + public Workload() { + } + + /** + * Get the context property: the scenario for the workload. + * + * @return the context value. + */ + public String context() { + return this.context; + } + + /** + * Set the context property: the scenario for the workload. + * + * @param context the context value to set. + * @return the Workload object itself. + */ + public Workload withContext(String context) { + this.context = context; + return this; + } + + /** + * Get the toolset property: Tool used to interact with Azure. SDK, AzPortal, etc.., Other. + * + * @return the toolset value. + */ + public Toolset toolset() { + return this.toolset; + } + + /** + * Set the toolset property: Tool used to interact with Azure. SDK, AzPortal, etc.., Other. + * + * @param toolset the toolset value to set. + * @return the Workload object itself. + */ + public Workload withToolset(Toolset toolset) { + this.toolset = toolset; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("context", this.context); + jsonWriter.writeStringField("toolset", this.toolset == null ? null : this.toolset.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of Workload from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of Workload 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 Workload. + */ + public static Workload fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Workload deserializedWorkload = new Workload(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("context".equals(fieldName)) { + deserializedWorkload.context = reader.getString(); + } else if ("toolset".equals(fieldName)) { + deserializedWorkload.toolset = Toolset.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedWorkload; + }); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/WorkloadImpact.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/WorkloadImpact.java new file mode 100644 index 000000000000..45571986419d --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/WorkloadImpact.java @@ -0,0 +1,122 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.models; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.impactreporting.fluent.models.WorkloadImpactInner; + +/** + * An immutable client-side representation of WorkloadImpact. + */ +public interface WorkloadImpact { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + WorkloadImpactProperties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.impactreporting.fluent.models.WorkloadImpactInner object. + * + * @return the inner object. + */ + WorkloadImpactInner innerModel(); + + /** + * The entirety of the WorkloadImpact definition. + */ + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithCreate { + } + + /** + * The WorkloadImpact definition stages. + */ + interface DefinitionStages { + /** + * The first stage of the WorkloadImpact definition. + */ + interface Blank extends WithCreate { + } + + /** + * The stage of the WorkloadImpact definition which contains all the minimum required properties for the + * resource to be created, but also allows for any other optional properties to be specified. + */ + interface WithCreate extends DefinitionStages.WithProperties { + /** + * Executes the create request. + * + * @return the created resource. + */ + WorkloadImpact create(); + + /** + * Executes the create request. + * + * @param context The context to associate with this operation. + * @return the created resource. + */ + WorkloadImpact create(Context context); + } + + /** + * The stage of the WorkloadImpact definition allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The resource-specific properties for this resource.. + * + * @param properties The resource-specific properties for this resource. + * @return the next definition stage. + */ + WithCreate withProperties(WorkloadImpactProperties properties); + } + } + + /** + * Refreshes the resource to sync with Azure. + * + * @return the refreshed resource. + */ + WorkloadImpact refresh(); + + /** + * Refreshes the resource to sync with Azure. + * + * @param context The context to associate with this operation. + * @return the refreshed resource. + */ + WorkloadImpact refresh(Context context); +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/WorkloadImpactProperties.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/WorkloadImpactProperties.java new file mode 100644 index 000000000000..ccc8edac7eb2 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/WorkloadImpactProperties.java @@ -0,0 +1,571 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; +import com.azure.core.util.logging.ClientLogger; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.List; + +/** + * Workload impact properties. + */ +@Fluent +public final class WorkloadImpactProperties implements JsonSerializable { + /* + * Resource provisioning state. + */ + private ProvisioningState provisioningState; + + /* + * Time at which impact was observed + */ + private OffsetDateTime startDateTime; + + /* + * Time at which impact has ended + */ + private OffsetDateTime endDateTime; + + /* + * Azure resource id of the impacted resource + */ + private String impactedResourceId; + + /* + * Unique ID of the impact (UUID) + */ + private String impactUniqueId; + + /* + * Time at which impact is reported + */ + private OffsetDateTime reportedTimeUtc; + + /* + * Category of the impact, details can found from /impactCategories API + */ + private String impactCategory; + + /* + * A detailed description of the impact + */ + private String impactDescription; + + /* + * The ARM correlation ids, this is important field for control plane related impacts + */ + private List armCorrelationIds; + + /* + * Details about performance issue. Applicable for performance impacts. + */ + private List performance; + + /* + * Details about connectivity issue. Applicable when root resource causing the issue is not identified. For example, + * when a VM is impacted due to a network issue, the impacted resource is identified as the VM, but the root cause + * is the network. In such cases, the connectivity field will have the details about the network issue + */ + private Connectivity connectivity; + + /* + * Additional fields related to impact, applicable fields per resource type are list under /impactCategories API + */ + private WorkloadImpactPropertiesAdditionalProperties additionalProperties; + + /* + * ARM error code and error message associated with the impact + */ + private ErrorDetailProperties errorDetails; + + /* + * Information about the impacted workload + */ + private Workload workload; + + /* + * Use this field to group impacts + */ + private String impactGroupId; + + /* + * Degree of confidence on the impact being a platform issue + */ + private ConfidenceLevel confidenceLevel; + + /* + * Client incident details ex: incidentId , incident source + */ + private ClientIncidentDetails clientIncidentDetails; + + /** + * Creates an instance of WorkloadImpactProperties class. + */ + public WorkloadImpactProperties() { + } + + /** + * Get the provisioningState property: Resource provisioning state. + * + * @return the provisioningState value. + */ + public ProvisioningState provisioningState() { + return this.provisioningState; + } + + /** + * Get the startDateTime property: Time at which impact was observed. + * + * @return the startDateTime value. + */ + public OffsetDateTime startDateTime() { + return this.startDateTime; + } + + /** + * Set the startDateTime property: Time at which impact was observed. + * + * @param startDateTime the startDateTime value to set. + * @return the WorkloadImpactProperties object itself. + */ + public WorkloadImpactProperties withStartDateTime(OffsetDateTime startDateTime) { + this.startDateTime = startDateTime; + return this; + } + + /** + * Get the endDateTime property: Time at which impact has ended. + * + * @return the endDateTime value. + */ + public OffsetDateTime endDateTime() { + return this.endDateTime; + } + + /** + * Set the endDateTime property: Time at which impact has ended. + * + * @param endDateTime the endDateTime value to set. + * @return the WorkloadImpactProperties object itself. + */ + public WorkloadImpactProperties withEndDateTime(OffsetDateTime endDateTime) { + this.endDateTime = endDateTime; + return this; + } + + /** + * Get the impactedResourceId property: Azure resource id of the impacted resource. + * + * @return the impactedResourceId value. + */ + public String impactedResourceId() { + return this.impactedResourceId; + } + + /** + * Set the impactedResourceId property: Azure resource id of the impacted resource. + * + * @param impactedResourceId the impactedResourceId value to set. + * @return the WorkloadImpactProperties object itself. + */ + public WorkloadImpactProperties withImpactedResourceId(String impactedResourceId) { + this.impactedResourceId = impactedResourceId; + return this; + } + + /** + * Get the impactUniqueId property: Unique ID of the impact (UUID). + * + * @return the impactUniqueId value. + */ + public String impactUniqueId() { + return this.impactUniqueId; + } + + /** + * Get the reportedTimeUtc property: Time at which impact is reported. + * + * @return the reportedTimeUtc value. + */ + public OffsetDateTime reportedTimeUtc() { + return this.reportedTimeUtc; + } + + /** + * Get the impactCategory property: Category of the impact, details can found from /impactCategories API. + * + * @return the impactCategory value. + */ + public String impactCategory() { + return this.impactCategory; + } + + /** + * Set the impactCategory property: Category of the impact, details can found from /impactCategories API. + * + * @param impactCategory the impactCategory value to set. + * @return the WorkloadImpactProperties object itself. + */ + public WorkloadImpactProperties withImpactCategory(String impactCategory) { + this.impactCategory = impactCategory; + return this; + } + + /** + * Get the impactDescription property: A detailed description of the impact. + * + * @return the impactDescription value. + */ + public String impactDescription() { + return this.impactDescription; + } + + /** + * Set the impactDescription property: A detailed description of the impact. + * + * @param impactDescription the impactDescription value to set. + * @return the WorkloadImpactProperties object itself. + */ + public WorkloadImpactProperties withImpactDescription(String impactDescription) { + this.impactDescription = impactDescription; + return this; + } + + /** + * Get the armCorrelationIds property: The ARM correlation ids, this is important field for control plane related + * impacts. + * + * @return the armCorrelationIds value. + */ + public List armCorrelationIds() { + return this.armCorrelationIds; + } + + /** + * Set the armCorrelationIds property: The ARM correlation ids, this is important field for control plane related + * impacts. + * + * @param armCorrelationIds the armCorrelationIds value to set. + * @return the WorkloadImpactProperties object itself. + */ + public WorkloadImpactProperties withArmCorrelationIds(List armCorrelationIds) { + this.armCorrelationIds = armCorrelationIds; + return this; + } + + /** + * Get the performance property: Details about performance issue. Applicable for performance impacts. + * + * @return the performance value. + */ + public List performance() { + return this.performance; + } + + /** + * Set the performance property: Details about performance issue. Applicable for performance impacts. + * + * @param performance the performance value to set. + * @return the WorkloadImpactProperties object itself. + */ + public WorkloadImpactProperties withPerformance(List performance) { + this.performance = performance; + return this; + } + + /** + * Get the connectivity property: Details about connectivity issue. Applicable when root resource causing the issue + * is not identified. For example, when a VM is impacted due to a network issue, the impacted resource is identified + * as the VM, but the root cause is the network. In such cases, the connectivity field will have the details about + * the network issue. + * + * @return the connectivity value. + */ + public Connectivity connectivity() { + return this.connectivity; + } + + /** + * Set the connectivity property: Details about connectivity issue. Applicable when root resource causing the issue + * is not identified. For example, when a VM is impacted due to a network issue, the impacted resource is identified + * as the VM, but the root cause is the network. In such cases, the connectivity field will have the details about + * the network issue. + * + * @param connectivity the connectivity value to set. + * @return the WorkloadImpactProperties object itself. + */ + public WorkloadImpactProperties withConnectivity(Connectivity connectivity) { + this.connectivity = connectivity; + return this; + } + + /** + * Get the additionalProperties property: Additional fields related to impact, applicable fields per resource type + * are list under /impactCategories API. + * + * @return the additionalProperties value. + */ + public WorkloadImpactPropertiesAdditionalProperties additionalProperties() { + return this.additionalProperties; + } + + /** + * Set the additionalProperties property: Additional fields related to impact, applicable fields per resource type + * are list under /impactCategories API. + * + * @param additionalProperties the additionalProperties value to set. + * @return the WorkloadImpactProperties object itself. + */ + public WorkloadImpactProperties + withAdditionalProperties(WorkloadImpactPropertiesAdditionalProperties additionalProperties) { + this.additionalProperties = additionalProperties; + return this; + } + + /** + * Get the errorDetails property: ARM error code and error message associated with the impact. + * + * @return the errorDetails value. + */ + public ErrorDetailProperties errorDetails() { + return this.errorDetails; + } + + /** + * Set the errorDetails property: ARM error code and error message associated with the impact. + * + * @param errorDetails the errorDetails value to set. + * @return the WorkloadImpactProperties object itself. + */ + public WorkloadImpactProperties withErrorDetails(ErrorDetailProperties errorDetails) { + this.errorDetails = errorDetails; + return this; + } + + /** + * Get the workload property: Information about the impacted workload. + * + * @return the workload value. + */ + public Workload workload() { + return this.workload; + } + + /** + * Set the workload property: Information about the impacted workload. + * + * @param workload the workload value to set. + * @return the WorkloadImpactProperties object itself. + */ + public WorkloadImpactProperties withWorkload(Workload workload) { + this.workload = workload; + return this; + } + + /** + * Get the impactGroupId property: Use this field to group impacts. + * + * @return the impactGroupId value. + */ + public String impactGroupId() { + return this.impactGroupId; + } + + /** + * Set the impactGroupId property: Use this field to group impacts. + * + * @param impactGroupId the impactGroupId value to set. + * @return the WorkloadImpactProperties object itself. + */ + public WorkloadImpactProperties withImpactGroupId(String impactGroupId) { + this.impactGroupId = impactGroupId; + return this; + } + + /** + * Get the confidenceLevel property: Degree of confidence on the impact being a platform issue. + * + * @return the confidenceLevel value. + */ + public ConfidenceLevel confidenceLevel() { + return this.confidenceLevel; + } + + /** + * Set the confidenceLevel property: Degree of confidence on the impact being a platform issue. + * + * @param confidenceLevel the confidenceLevel value to set. + * @return the WorkloadImpactProperties object itself. + */ + public WorkloadImpactProperties withConfidenceLevel(ConfidenceLevel confidenceLevel) { + this.confidenceLevel = confidenceLevel; + return this; + } + + /** + * Get the clientIncidentDetails property: Client incident details ex: incidentId , incident source. + * + * @return the clientIncidentDetails value. + */ + public ClientIncidentDetails clientIncidentDetails() { + return this.clientIncidentDetails; + } + + /** + * Set the clientIncidentDetails property: Client incident details ex: incidentId , incident source. + * + * @param clientIncidentDetails the clientIncidentDetails value to set. + * @return the WorkloadImpactProperties object itself. + */ + public WorkloadImpactProperties withClientIncidentDetails(ClientIncidentDetails clientIncidentDetails) { + this.clientIncidentDetails = clientIncidentDetails; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (startDateTime() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property startDateTime in model WorkloadImpactProperties")); + } + if (impactedResourceId() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property impactedResourceId in model WorkloadImpactProperties")); + } + if (impactCategory() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property impactCategory in model WorkloadImpactProperties")); + } + if (performance() != null) { + performance().forEach(e -> e.validate()); + } + if (connectivity() != null) { + connectivity().validate(); + } + if (additionalProperties() != null) { + additionalProperties().validate(); + } + if (errorDetails() != null) { + errorDetails().validate(); + } + if (workload() != null) { + workload().validate(); + } + if (clientIncidentDetails() != null) { + clientIncidentDetails().validate(); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(WorkloadImpactProperties.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("startDateTime", + this.startDateTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.startDateTime)); + jsonWriter.writeStringField("impactedResourceId", this.impactedResourceId); + jsonWriter.writeStringField("impactCategory", this.impactCategory); + jsonWriter.writeStringField("endDateTime", + this.endDateTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.endDateTime)); + jsonWriter.writeStringField("impactDescription", this.impactDescription); + jsonWriter.writeArrayField("armCorrelationIds", this.armCorrelationIds, + (writer, element) -> writer.writeString(element)); + jsonWriter.writeArrayField("performance", this.performance, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeJsonField("connectivity", this.connectivity); + jsonWriter.writeJsonField("additionalProperties", this.additionalProperties); + jsonWriter.writeJsonField("errorDetails", this.errorDetails); + jsonWriter.writeJsonField("workload", this.workload); + jsonWriter.writeStringField("impactGroupId", this.impactGroupId); + jsonWriter.writeStringField("confidenceLevel", + this.confidenceLevel == null ? null : this.confidenceLevel.toString()); + jsonWriter.writeJsonField("clientIncidentDetails", this.clientIncidentDetails); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of WorkloadImpactProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of WorkloadImpactProperties 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 WorkloadImpactProperties. + */ + public static WorkloadImpactProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + WorkloadImpactProperties deserializedWorkloadImpactProperties = new WorkloadImpactProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("startDateTime".equals(fieldName)) { + deserializedWorkloadImpactProperties.startDateTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("impactedResourceId".equals(fieldName)) { + deserializedWorkloadImpactProperties.impactedResourceId = reader.getString(); + } else if ("impactCategory".equals(fieldName)) { + deserializedWorkloadImpactProperties.impactCategory = reader.getString(); + } else if ("provisioningState".equals(fieldName)) { + deserializedWorkloadImpactProperties.provisioningState + = ProvisioningState.fromString(reader.getString()); + } else if ("endDateTime".equals(fieldName)) { + deserializedWorkloadImpactProperties.endDateTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("impactUniqueId".equals(fieldName)) { + deserializedWorkloadImpactProperties.impactUniqueId = reader.getString(); + } else if ("reportedTimeUtc".equals(fieldName)) { + deserializedWorkloadImpactProperties.reportedTimeUtc = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("impactDescription".equals(fieldName)) { + deserializedWorkloadImpactProperties.impactDescription = reader.getString(); + } else if ("armCorrelationIds".equals(fieldName)) { + List armCorrelationIds = reader.readArray(reader1 -> reader1.getString()); + deserializedWorkloadImpactProperties.armCorrelationIds = armCorrelationIds; + } else if ("performance".equals(fieldName)) { + List performance = reader.readArray(reader1 -> Performance.fromJson(reader1)); + deserializedWorkloadImpactProperties.performance = performance; + } else if ("connectivity".equals(fieldName)) { + deserializedWorkloadImpactProperties.connectivity = Connectivity.fromJson(reader); + } else if ("additionalProperties".equals(fieldName)) { + deserializedWorkloadImpactProperties.additionalProperties + = WorkloadImpactPropertiesAdditionalProperties.fromJson(reader); + } else if ("errorDetails".equals(fieldName)) { + deserializedWorkloadImpactProperties.errorDetails = ErrorDetailProperties.fromJson(reader); + } else if ("workload".equals(fieldName)) { + deserializedWorkloadImpactProperties.workload = Workload.fromJson(reader); + } else if ("impactGroupId".equals(fieldName)) { + deserializedWorkloadImpactProperties.impactGroupId = reader.getString(); + } else if ("confidenceLevel".equals(fieldName)) { + deserializedWorkloadImpactProperties.confidenceLevel + = ConfidenceLevel.fromString(reader.getString()); + } else if ("clientIncidentDetails".equals(fieldName)) { + deserializedWorkloadImpactProperties.clientIncidentDetails = ClientIncidentDetails.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedWorkloadImpactProperties; + }); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/WorkloadImpactPropertiesAdditionalProperties.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/WorkloadImpactPropertiesAdditionalProperties.java new file mode 100644 index 000000000000..0c72a73b4ede --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/WorkloadImpactPropertiesAdditionalProperties.java @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.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 WorkloadImpactPropertiesAdditionalProperties model. + */ +@Immutable +public final class WorkloadImpactPropertiesAdditionalProperties + implements JsonSerializable { + /** + * Creates an instance of WorkloadImpactPropertiesAdditionalProperties class. + */ + public WorkloadImpactPropertiesAdditionalProperties() { + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of WorkloadImpactPropertiesAdditionalProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of WorkloadImpactPropertiesAdditionalProperties 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 WorkloadImpactPropertiesAdditionalProperties. + */ + public static WorkloadImpactPropertiesAdditionalProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + WorkloadImpactPropertiesAdditionalProperties deserializedWorkloadImpactPropertiesAdditionalProperties + = new WorkloadImpactPropertiesAdditionalProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + reader.skipChildren(); + } + + return deserializedWorkloadImpactPropertiesAdditionalProperties; + }); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/WorkloadImpacts.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/WorkloadImpacts.java new file mode 100644 index 000000000000..ce236683bc4f --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/WorkloadImpacts.java @@ -0,0 +1,132 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of WorkloadImpacts. + */ +public interface WorkloadImpacts { + /** + * Get a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a WorkloadImpact along with {@link Response}. + */ + Response getWithResponse(String workloadImpactName, Context context); + + /** + * Get a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a WorkloadImpact. + */ + WorkloadImpact get(String workloadImpactName); + + /** + * Delete a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteWithResponse(String workloadImpactName, Context context); + + /** + * Delete a WorkloadImpact. + * + * @param workloadImpactName workloadImpact resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void delete(String workloadImpactName); + + /** + * List WorkloadImpact resources by subscription ID. + * + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a WorkloadImpact list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable list(); + + /** + * List WorkloadImpact resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a WorkloadImpact list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable list(Context context); + + /** + * Get a WorkloadImpact. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a WorkloadImpact along with {@link Response}. + */ + WorkloadImpact getById(String id); + + /** + * Get a WorkloadImpact. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a WorkloadImpact along with {@link Response}. + */ + Response getByIdWithResponse(String id, Context context); + + /** + * Delete a WorkloadImpact. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteById(String id); + + /** + * Delete a WorkloadImpact. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteByIdWithResponse(String id, Context context); + + /** + * Begins definition for a new WorkloadImpact resource. + * + * @param name resource name. + * @return the first stage of the new WorkloadImpact definition. + */ + WorkloadImpact.DefinitionStages.Blank define(String name); +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/package-info.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/package-info.java new file mode 100644 index 000000000000..421ccec5be1d --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/models/package-info.java @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +/** + * Package containing the data models for ImpactReporting. + */ +package com.azure.resourcemanager.impactreporting.models; diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/package-info.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/package-info.java new file mode 100644 index 000000000000..f82adf6831d5 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/com/azure/resourcemanager/impactreporting/package-info.java @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +/** + * Package containing the classes for ImpactReporting. + */ +package com.azure.resourcemanager.impactreporting; diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/module-info.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/module-info.java new file mode 100644 index 000000000000..bb127a178314 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/java/module-info.java @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +module com.azure.resourcemanager.impactreporting { + requires transitive com.azure.core.management; + + exports com.azure.resourcemanager.impactreporting; + exports com.azure.resourcemanager.impactreporting.fluent; + exports com.azure.resourcemanager.impactreporting.fluent.models; + exports com.azure.resourcemanager.impactreporting.models; + + opens com.azure.resourcemanager.impactreporting.fluent.models to com.azure.core; + opens com.azure.resourcemanager.impactreporting.models to com.azure.core; + opens com.azure.resourcemanager.impactreporting.implementation.models to com.azure.core; +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-impactreporting/proxy-config.json b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-impactreporting/proxy-config.json new file mode 100644 index 000000000000..eb4e0ce39eae --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-impactreporting/proxy-config.json @@ -0,0 +1 @@ +[["com.azure.resourcemanager.impactreporting.implementation.ConnectorsClientImpl$ConnectorsService"],["com.azure.resourcemanager.impactreporting.implementation.ImpactCategoriesClientImpl$ImpactCategoriesService"],["com.azure.resourcemanager.impactreporting.implementation.InsightsClientImpl$InsightsService"],["com.azure.resourcemanager.impactreporting.implementation.OperationsClientImpl$OperationsService"],["com.azure.resourcemanager.impactreporting.implementation.WorkloadImpactsClientImpl$WorkloadImpactsService"]] \ No newline at end of file diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-impactreporting/reflect-config.json b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-impactreporting/reflect-config.json new file mode 100644 index 000000000000..0637a088a01e --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-impactreporting/reflect-config.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/resources/azure-resourcemanager-impactreporting.properties b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/resources/azure-resourcemanager-impactreporting.properties new file mode 100644 index 000000000000..defbd48204e4 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/main/resources/azure-resourcemanager-impactreporting.properties @@ -0,0 +1 @@ +version=${project.version} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/ConnectorsCreateOrUpdateSamples.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/ConnectorsCreateOrUpdateSamples.java new file mode 100644 index 000000000000..8ed23c54adcb --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/ConnectorsCreateOrUpdateSamples.java @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.resourcemanager.impactreporting.models.ConnectorProperties; +import com.azure.resourcemanager.impactreporting.models.Platform; + +/** + * Samples for Connectors CreateOrUpdate. + */ +public final class ConnectorsCreateOrUpdateSamples { + /* + * x-ms-original-file: 2024-05-01-preview/Connectors_CreateOrUpdate.json + */ + /** + * Sample code: Connectors_CreateOrUpdate. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void + connectorsCreateOrUpdate(com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.connectors() + .define("testconnector1") + .withProperties(new ConnectorProperties().withConnectorType(Platform.AZURE_MONITOR)) + .create(); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/ConnectorsDeleteSamples.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/ConnectorsDeleteSamples.java new file mode 100644 index 000000000000..9a2d35946e3a --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/ConnectorsDeleteSamples.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +/** + * Samples for Connectors Delete. + */ +public final class ConnectorsDeleteSamples { + /* + * x-ms-original-file: 2024-05-01-preview/Connectors_Delete.json + */ + /** + * Sample code: Connectors_Delete. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void connectorsDelete(com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.connectors().deleteWithResponse("testconnector1", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/ConnectorsGetSamples.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/ConnectorsGetSamples.java new file mode 100644 index 000000000000..b02baec079d8 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/ConnectorsGetSamples.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +/** + * Samples for Connectors Get. + */ +public final class ConnectorsGetSamples { + /* + * x-ms-original-file: 2024-05-01-preview/Connectors_Get.json + */ + /** + * Sample code: Connectors_Get. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void connectorsGet(com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.connectors().getWithResponse("testconnector1", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/ConnectorsListSamples.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/ConnectorsListSamples.java new file mode 100644 index 000000000000..41d5a931403d --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/ConnectorsListSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +/** + * Samples for Connectors List. + */ +public final class ConnectorsListSamples { + /* + * x-ms-original-file: 2024-05-01-preview/Connectors_ListBySubscription.json + */ + /** + * Sample code: Connectors_ListBySubscription. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void + connectorsListBySubscription(com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.connectors().list(com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/ConnectorsUpdateSamples.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/ConnectorsUpdateSamples.java new file mode 100644 index 000000000000..839b8b728efb --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/ConnectorsUpdateSamples.java @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.resourcemanager.impactreporting.models.Connector; +import com.azure.resourcemanager.impactreporting.models.ConnectorUpdateProperties; +import com.azure.resourcemanager.impactreporting.models.Platform; + +/** + * Samples for Connectors Update. + */ +public final class ConnectorsUpdateSamples { + /* + * x-ms-original-file: 2024-05-01-preview/Connectors_Update.json + */ + /** + * Sample code: Connectors_Update. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void connectorsUpdate(com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + Connector resource + = manager.connectors().getWithResponse("testconnector1", com.azure.core.util.Context.NONE).getValue(); + resource.update() + .withProperties(new ConnectorUpdateProperties().withConnectorType(Platform.AZURE_MONITOR)) + .apply(); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/ImpactCategoriesGetSamples.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/ImpactCategoriesGetSamples.java new file mode 100644 index 000000000000..63320c777052 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/ImpactCategoriesGetSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +/** + * Samples for ImpactCategories Get. + */ +public final class ImpactCategoriesGetSamples { + /* + * x-ms-original-file: 2024-05-01-preview/ImpactCategories_Get.json + */ + /** + * Sample code: Get WorkloadImpact Resource by name. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void + getWorkloadImpactResourceByName(com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.impactCategories().getWithResponse("ARMOperation.Create", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/ImpactCategoriesListSamples.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/ImpactCategoriesListSamples.java new file mode 100644 index 000000000000..74224527d07b --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/ImpactCategoriesListSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +/** + * Samples for ImpactCategories List. + */ +public final class ImpactCategoriesListSamples { + /* + * x-ms-original-file: 2024-05-01-preview/ImpactCategories_ListBySubscription.json + */ + /** + * Sample code: Get ImpactCategories list by subscription. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void getImpactCategoriesListBySubscription( + com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.impactCategories().list("microsoft.compute/virtualmachines", null, com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/InsightsCreateSamples.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/InsightsCreateSamples.java new file mode 100644 index 000000000000..723c0619ebd9 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/InsightsCreateSamples.java @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.resourcemanager.impactreporting.models.Content; +import com.azure.resourcemanager.impactreporting.models.ImpactDetails; +import com.azure.resourcemanager.impactreporting.models.InsightProperties; +import java.time.OffsetDateTime; + +/** + * Samples for Insights Create. + */ +public final class InsightsCreateSamples { + /* + * x-ms-original-file: 2024-05-01-preview/Insights_Create.json + */ + /** + * Sample code: Creating an insight. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void creatingAnInsight(com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.insights() + .define("insightId12") + .withExistingWorkloadImpact("impactid22") + .withProperties(new InsightProperties().withCategory("repair") + .withStatus("resolved") + .withContent(new Content().withTitle("Impact Has been correlated to an outage") + .withDescription( + "At 2018-11-08T00:00:00Z UTC, your services dependent on these resources VM1 may have experienced an issue.

          We have identified an outage that affected these resources(s). You can look at outage information on NL2W-VCZ link.
          ")) + .withEventTime(OffsetDateTime.parse("2023-06-15T04:00:00.009223Z")) + .withInsightUniqueId("00000000-0000-0000-0000-000000000000") + .withImpact(new ImpactDetails().withImpactedResourceId( + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resource-rg/providers/Microsoft.Sql/sqlserver/dbservername") + .withStartTime(OffsetDateTime.parse("2023-06-15T01:00:00.009223Z")) + .withImpactId( + "/subscriptions/00000000-0000-0000-0000-000000000000/providers/microsoft.Impact/workloadImpacts/impactid22"))) + .create(); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/InsightsDeleteSamples.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/InsightsDeleteSamples.java new file mode 100644 index 000000000000..305b07a10425 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/InsightsDeleteSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +/** + * Samples for Insights Delete. + */ +public final class InsightsDeleteSamples { + /* + * x-ms-original-file: 2024-05-01-preview/Insights_Delete.json + */ + /** + * Sample code: Delete an Insight. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void deleteAnInsight(com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.insights() + .deleteByResourceGroupWithResponse("impactid22", "insightId12", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/InsightsGetSamples.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/InsightsGetSamples.java new file mode 100644 index 000000000000..b6dd0a730ab8 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/InsightsGetSamples.java @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +/** + * Samples for Insights Get. + */ +public final class InsightsGetSamples { + /* + * x-ms-original-file: 2024-05-01-preview/Insights_Get_mitigationAction.json + */ + /** + * Sample code: Get Insight sample for MitigationAction category. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void getInsightSampleForMitigationActionCategory( + com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.insights().getWithResponse("impactId", "HPCUASucceeded", com.azure.core.util.Context.NONE); + } + + /* + * x-ms-original-file: 2024-05-01-preview/Insights_Get_diagnostics.json + */ + /** + * Sample code: Get Insight sample for Diagnostics category. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void getInsightSampleForDiagnosticsCategory( + com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.insights().getWithResponse("impactid", "insight1", com.azure.core.util.Context.NONE); + } + + /* + * x-ms-original-file: 2024-05-01-preview/Insights_Get_servicehealth.json + */ + /** + * Sample code: Get Insight sample for service health category. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void getInsightSampleForServiceHealthCategory( + com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.insights().getWithResponse("impactid", "insightname", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/InsightsListBySubscriptionSamples.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/InsightsListBySubscriptionSamples.java new file mode 100644 index 000000000000..967732924ee5 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/InsightsListBySubscriptionSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +/** + * Samples for Insights ListBySubscription. + */ +public final class InsightsListBySubscriptionSamples { + /* + * x-ms-original-file: 2024-05-01-preview/Insights_ListBySubscription.json + */ + /** + * Sample code: List Insight resources by workloadImpactName. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void listInsightResourcesByWorkloadImpactName( + com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.insights().listBySubscription("impactid22", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/OperationsListSamples.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/OperationsListSamples.java new file mode 100644 index 000000000000..c8ee32de6373 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/OperationsListSamples.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +/** + * Samples for Operations List. + */ +public final class OperationsListSamples { + /* + * x-ms-original-file: 2024-05-01-preview/Operations_List.json + */ + /** + * Sample code: OperationsList. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void operationsList(com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.operations().list(com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/WorkloadImpactsCreateSamples.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/WorkloadImpactsCreateSamples.java new file mode 100644 index 000000000000..2ac9d210caa1 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/WorkloadImpactsCreateSamples.java @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.resourcemanager.impactreporting.models.ClientIncidentDetails; +import com.azure.resourcemanager.impactreporting.models.Connectivity; +import com.azure.resourcemanager.impactreporting.models.IncidentSource; +import com.azure.resourcemanager.impactreporting.models.MetricUnit; +import com.azure.resourcemanager.impactreporting.models.Performance; +import com.azure.resourcemanager.impactreporting.models.Protocol; +import com.azure.resourcemanager.impactreporting.models.SourceOrTarget; +import com.azure.resourcemanager.impactreporting.models.Toolset; +import com.azure.resourcemanager.impactreporting.models.Workload; +import com.azure.resourcemanager.impactreporting.models.WorkloadImpactProperties; +import java.time.OffsetDateTime; +import java.util.Arrays; + +/** + * Samples for WorkloadImpacts Create. + */ +public final class WorkloadImpactsCreateSamples { + /* + * x-ms-original-file: 2024-05-01-preview/WorkloadAvailability_Create.json + */ + /** + * Sample code: Reporting availability related impact. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void + reportingAvailabilityRelatedImpact(com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.workloadImpacts() + .define("impact-002") + .withProperties(new WorkloadImpactProperties() + .withStartDateTime(OffsetDateTime.parse("2022-06-15T05:59:46.6517821Z")) + .withImpactedResourceId( + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resource-rg/providers/Microsoft.Sql/sqlserver/dbservercontext") + .withImpactCategory("Availability") + .withImpactDescription("read calls failed") + .withWorkload(new Workload().withContext("webapp/scenario1").withToolset(Toolset.OTHER)) + .withClientIncidentDetails(new ClientIncidentDetails().withClientIncidentId("AA123") + .withClientIncidentSource(IncidentSource.JIRA))) + .create(); + } + + /* + * x-ms-original-file: 2024-05-01-preview/WorkloadConnectivityImpact_Create.json + */ + /** + * Sample code: Reporting a connectivity impact. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void + reportingAConnectivityImpact(com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.workloadImpacts() + .define("impact-001") + .withProperties(new WorkloadImpactProperties() + .withStartDateTime(OffsetDateTime.parse("2022-06-15T05:59:46.6517821Z")) + .withImpactedResourceId( + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resource-rg/providers/Microsoft.Sql/sqlserver/dbservercontext") + .withImpactCategory("Resource.Connectivity") + .withImpactDescription("conection failure") + .withConnectivity(new Connectivity().withProtocol(Protocol.TCP) + .withPort(1443) + .withSource(new SourceOrTarget().withAzureResourceId( + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resourceSub/providers/Microsoft.compute/virtualmachines/vm1")) + .withTarget(new SourceOrTarget().withAzureResourceId( + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resourceSub/providers/Microsoft.compute/virtualmachines/vm2"))) + .withWorkload(new Workload().withContext("webapp/scenario1").withToolset(Toolset.OTHER)) + .withClientIncidentDetails(new ClientIncidentDetails().withClientIncidentId("AA123") + .withClientIncidentSource(IncidentSource.JIRA))) + .create(); + } + + /* + * x-ms-original-file: 2024-05-01-preview/WorkloadArmOperation_create.json + */ + /** + * Sample code: Reporting Arm operation failure. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void + reportingArmOperationFailure(com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.workloadImpacts() + .define("impact-002") + .withProperties(new WorkloadImpactProperties() + .withStartDateTime(OffsetDateTime.parse("2022-06-15T05:59:46.6517821Z")) + .withImpactedResourceId( + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resource-rg/providers/Microsoft.Sql/sqlserver/dbservercontext") + .withImpactCategory("ArmOperation") + .withImpactDescription("deletion of resource failed") + .withArmCorrelationIds(Arrays.asList("00000000-0000-0000-0000-000000000000")) + .withWorkload(new Workload().withContext("webapp/scenario1").withToolset(Toolset.OTHER)) + .withClientIncidentDetails(new ClientIncidentDetails().withClientIncidentId("AA123") + .withClientIncidentSource(IncidentSource.JIRA))) + .create(); + } + + /* + * x-ms-original-file: 2024-05-01-preview/WorkloadPerformance_Create.json + */ + /** + * Sample code: Reporting performance related impact. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void + reportingPerformanceRelatedImpact(com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.workloadImpacts() + .define("impact-002") + .withProperties(new WorkloadImpactProperties() + .withStartDateTime(OffsetDateTime.parse("2022-06-15T05:59:46.6517821Z")) + .withImpactedResourceId( + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resource-rg/providers/Microsoft.Sql/sqlserver/dbservercontext") + .withImpactCategory("Resource.Performance") + .withImpactDescription("high cpu utilization") + .withPerformance(Arrays.asList(new Performance().withMetricName("CPU") + .withExpected(60.0D) + .withActual(90.0D) + .withUnit(MetricUnit.fromString("garbage")))) + .withWorkload(new Workload().withContext("webapp/scenario1").withToolset(Toolset.OTHER)) + .withClientIncidentDetails(new ClientIncidentDetails().withClientIncidentId("AA123") + .withClientIncidentSource(IncidentSource.JIRA))) + .create(); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/WorkloadImpactsDeleteSamples.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/WorkloadImpactsDeleteSamples.java new file mode 100644 index 000000000000..bb33e167221e --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/WorkloadImpactsDeleteSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +/** + * Samples for WorkloadImpacts Delete. + */ +public final class WorkloadImpactsDeleteSamples { + /* + * x-ms-original-file: 2024-05-01-preview/WorkloadImpact_Delete.json + */ + /** + * Sample code: Delete WorkloadImpact Resource by name example. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void deleteWorkloadImpactResourceByNameExample( + com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.workloadImpacts().deleteWithResponse("impact-001", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/WorkloadImpactsGetSamples.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/WorkloadImpactsGetSamples.java new file mode 100644 index 000000000000..20510a61a851 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/WorkloadImpactsGetSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +/** + * Samples for WorkloadImpacts Get. + */ +public final class WorkloadImpactsGetSamples { + /* + * x-ms-original-file: 2024-05-01-preview/WorkloadImpact_Get.json + */ + /** + * Sample code: Get WorkloadImpact Resource by name example. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void getWorkloadImpactResourceByNameExample( + com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.workloadImpacts().getWithResponse("impact-001", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/WorkloadImpactsListSamples.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/WorkloadImpactsListSamples.java new file mode 100644 index 000000000000..5628add781de --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/samples/java/com/azure/resourcemanager/impactreporting/generated/WorkloadImpactsListSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +/** + * Samples for WorkloadImpacts List. + */ +public final class WorkloadImpactsListSamples { + /* + * x-ms-original-file: 2024-05-01-preview/WorkloadImpacts_ListBySubscription.json + */ + /** + * Sample code: List WorkloadImpact resources by subscription. + * + * @param manager Entry point to ImpactReportingManager. + */ + public static void listWorkloadImpactResourcesBySubscription( + com.azure.resourcemanager.impactreporting.ImpactReportingManager manager) { + manager.workloadImpacts().list(com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ClientIncidentDetailsTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ClientIncidentDetailsTests.java new file mode 100644 index 000000000000..519f23fe5f30 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ClientIncidentDetailsTests.java @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.impactreporting.models.ClientIncidentDetails; +import com.azure.resourcemanager.impactreporting.models.IncidentSource; +import org.junit.jupiter.api.Assertions; + +public final class ClientIncidentDetailsTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + ClientIncidentDetails model + = BinaryData.fromString("{\"clientIncidentId\":\"iheogna\",\"clientIncidentSource\":\"Other\"}") + .toObject(ClientIncidentDetails.class); + Assertions.assertEquals("iheogna", model.clientIncidentId()); + Assertions.assertEquals(IncidentSource.OTHER, model.clientIncidentSource()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + ClientIncidentDetails model = new ClientIncidentDetails().withClientIncidentId("iheogna") + .withClientIncidentSource(IncidentSource.OTHER); + model = BinaryData.fromObject(model).toObject(ClientIncidentDetails.class); + Assertions.assertEquals("iheogna", model.clientIncidentId()); + Assertions.assertEquals(IncidentSource.OTHER, model.clientIncidentSource()); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectivityTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectivityTests.java new file mode 100644 index 000000000000..47eb3c14a335 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectivityTests.java @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.impactreporting.models.Connectivity; +import com.azure.resourcemanager.impactreporting.models.Protocol; +import com.azure.resourcemanager.impactreporting.models.SourceOrTarget; +import org.junit.jupiter.api.Assertions; + +public final class ConnectivityTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + Connectivity model = BinaryData.fromString( + "{\"protocol\":\"HTTP\",\"port\":751944111,\"source\":{\"azureResourceId\":\"xxjtfe\"},\"target\":{\"azureResourceId\":\"wfzitonpeqfpjk\"}}") + .toObject(Connectivity.class); + Assertions.assertEquals(Protocol.HTTP, model.protocol()); + Assertions.assertEquals(751944111, model.port()); + Assertions.assertEquals("xxjtfe", model.source().azureResourceId()); + Assertions.assertEquals("wfzitonpeqfpjk", model.target().azureResourceId()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + Connectivity model = new Connectivity().withProtocol(Protocol.HTTP) + .withPort(751944111) + .withSource(new SourceOrTarget().withAzureResourceId("xxjtfe")) + .withTarget(new SourceOrTarget().withAzureResourceId("wfzitonpeqfpjk")); + model = BinaryData.fromObject(model).toObject(Connectivity.class); + Assertions.assertEquals(Protocol.HTTP, model.protocol()); + Assertions.assertEquals(751944111, model.port()); + Assertions.assertEquals("xxjtfe", model.source().azureResourceId()); + Assertions.assertEquals("wfzitonpeqfpjk", model.target().azureResourceId()); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectorInnerTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectorInnerTests.java new file mode 100644 index 000000000000..9c2e3e0a7e2c --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectorInnerTests.java @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.impactreporting.fluent.models.ConnectorInner; +import com.azure.resourcemanager.impactreporting.models.ConnectorProperties; +import com.azure.resourcemanager.impactreporting.models.Platform; +import org.junit.jupiter.api.Assertions; + +public final class ConnectorInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + ConnectorInner model = BinaryData.fromString( + "{\"properties\":{\"provisioningState\":\"Succeeded\",\"connectorId\":\"ae\",\"tenantId\":\"pfhyhl\",\"connectorType\":\"AzureMonitor\",\"lastRunTimeStamp\":\"2021-04-18T06:05:11Z\"},\"id\":\"opjmcmatuokthfui\",\"name\":\"aodsfcpkv\",\"type\":\"odpuozmyzydag\"}") + .toObject(ConnectorInner.class); + Assertions.assertEquals(Platform.AZURE_MONITOR, model.properties().connectorType()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + ConnectorInner model + = new ConnectorInner().withProperties(new ConnectorProperties().withConnectorType(Platform.AZURE_MONITOR)); + model = BinaryData.fromObject(model).toObject(ConnectorInner.class); + Assertions.assertEquals(Platform.AZURE_MONITOR, model.properties().connectorType()); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectorListResultTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectorListResultTests.java new file mode 100644 index 000000000000..e3662c578088 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectorListResultTests.java @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.impactreporting.implementation.models.ConnectorListResult; +import com.azure.resourcemanager.impactreporting.models.Platform; +import org.junit.jupiter.api.Assertions; + +public final class ConnectorListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + ConnectorListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"provisioningState\":\"Succeeded\",\"connectorId\":\"mddystkiiux\",\"tenantId\":\"qyud\",\"connectorType\":\"AzureMonitor\",\"lastRunTimeStamp\":\"2021-08-19T10:45:17Z\"},\"id\":\"nbpoczvyifqrvkdv\",\"name\":\"sllr\",\"type\":\"vvdfwatkpnpul\"},{\"properties\":{\"provisioningState\":\"Failed\",\"connectorId\":\"czwtruwiqzbqjv\",\"tenantId\":\"ovm\",\"connectorType\":\"AzureMonitor\",\"lastRunTimeStamp\":\"2020-12-31T07:20:30Z\"},\"id\":\"cspkwlhzdobpxjmf\",\"name\":\"bvvnchrkcciw\",\"type\":\"zjuqkhrsaj\"},{\"properties\":{\"provisioningState\":\"Canceled\",\"connectorId\":\"ofoskghs\",\"tenantId\":\"uuimjmvxieduug\",\"connectorType\":\"AzureMonitor\",\"lastRunTimeStamp\":\"2021-10-23T08:30:29Z\"},\"id\":\"rrfbyaosvexcson\",\"name\":\"clhocohsl\",\"type\":\"ev\"}],\"nextLink\":\"ggzfbu\"}") + .toObject(ConnectorListResult.class); + Assertions.assertEquals(Platform.AZURE_MONITOR, model.value().get(0).properties().connectorType()); + Assertions.assertEquals("ggzfbu", model.nextLink()); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectorPropertiesTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectorPropertiesTests.java new file mode 100644 index 000000000000..3f3586944f9f --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectorPropertiesTests.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.impactreporting.models.ConnectorProperties; +import com.azure.resourcemanager.impactreporting.models.Platform; +import org.junit.jupiter.api.Assertions; + +public final class ConnectorPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + ConnectorProperties model = BinaryData.fromString( + "{\"provisioningState\":\"Failed\",\"connectorId\":\"xbezyiuokktwh\",\"tenantId\":\"dxwzywqsmbsurexi\",\"connectorType\":\"AzureMonitor\",\"lastRunTimeStamp\":\"2021-01-06T03:50:02Z\"}") + .toObject(ConnectorProperties.class); + Assertions.assertEquals(Platform.AZURE_MONITOR, model.connectorType()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + ConnectorProperties model = new ConnectorProperties().withConnectorType(Platform.AZURE_MONITOR); + model = BinaryData.fromObject(model).toObject(ConnectorProperties.class); + Assertions.assertEquals(Platform.AZURE_MONITOR, model.connectorType()); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectorUpdatePropertiesTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectorUpdatePropertiesTests.java new file mode 100644 index 000000000000..a7be22a4659a --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectorUpdatePropertiesTests.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.impactreporting.models.ConnectorUpdateProperties; +import com.azure.resourcemanager.impactreporting.models.Platform; +import org.junit.jupiter.api.Assertions; + +public final class ConnectorUpdatePropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + ConnectorUpdateProperties model + = BinaryData.fromString("{\"connectorType\":\"AzureMonitor\"}").toObject(ConnectorUpdateProperties.class); + Assertions.assertEquals(Platform.AZURE_MONITOR, model.connectorType()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + ConnectorUpdateProperties model = new ConnectorUpdateProperties().withConnectorType(Platform.AZURE_MONITOR); + model = BinaryData.fromObject(model).toObject(ConnectorUpdateProperties.class); + Assertions.assertEquals(Platform.AZURE_MONITOR, model.connectorType()); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectorUpdateTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectorUpdateTests.java new file mode 100644 index 000000000000..58a8c7682a96 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectorUpdateTests.java @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.impactreporting.models.ConnectorUpdate; +import com.azure.resourcemanager.impactreporting.models.ConnectorUpdateProperties; +import com.azure.resourcemanager.impactreporting.models.Platform; +import org.junit.jupiter.api.Assertions; + +public final class ConnectorUpdateTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + ConnectorUpdate model = BinaryData.fromString("{\"properties\":{\"connectorType\":\"AzureMonitor\"}}") + .toObject(ConnectorUpdate.class); + Assertions.assertEquals(Platform.AZURE_MONITOR, model.properties().connectorType()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + ConnectorUpdate model = new ConnectorUpdate() + .withProperties(new ConnectorUpdateProperties().withConnectorType(Platform.AZURE_MONITOR)); + model = BinaryData.fromObject(model).toObject(ConnectorUpdate.class); + Assertions.assertEquals(Platform.AZURE_MONITOR, model.properties().connectorType()); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectorsCreateOrUpdateMockTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectorsCreateOrUpdateMockTests.java new file mode 100644 index 000000000000..9daa120b80f3 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectorsCreateOrUpdateMockTests.java @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.impactreporting.ImpactReportingManager; +import com.azure.resourcemanager.impactreporting.models.Connector; +import com.azure.resourcemanager.impactreporting.models.ConnectorProperties; +import com.azure.resourcemanager.impactreporting.models.Platform; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class ConnectorsCreateOrUpdateMockTests { + @Test + public void testCreateOrUpdate() throws Exception { + String responseStr + = "{\"properties\":{\"provisioningState\":\"Succeeded\",\"connectorId\":\"xhnrztfolhb\",\"tenantId\":\"xknalaulppg\",\"connectorType\":\"AzureMonitor\",\"lastRunTimeStamp\":\"2021-03-08T22:58:09Z\"},\"id\":\"napnyiropuhpigv\",\"name\":\"gylgqgitxmedjvcs\",\"type\":\"ynqwwncwzzhxgk\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + ImpactReportingManager manager = ImpactReportingManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + Connector response = manager.connectors() + .define("bsjyofdx") + .withProperties(new ConnectorProperties().withConnectorType(Platform.AZURE_MONITOR)) + .create(); + + Assertions.assertEquals(Platform.AZURE_MONITOR, response.properties().connectorType()); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectorsDeleteWithResponseMockTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectorsDeleteWithResponseMockTests.java new file mode 100644 index 000000000000..cfd1c78dd4db --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectorsDeleteWithResponseMockTests.java @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.impactreporting.ImpactReportingManager; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class ConnectorsDeleteWithResponseMockTests { + @Test + public void testDeleteWithResponse() throws Exception { + String responseStr = "{}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + ImpactReportingManager manager = ImpactReportingManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + manager.connectors().deleteWithResponse("vawjvzunlu", com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectorsGetWithResponseMockTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectorsGetWithResponseMockTests.java new file mode 100644 index 000000000000..a4171acb2e4c --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectorsGetWithResponseMockTests.java @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.impactreporting.ImpactReportingManager; +import com.azure.resourcemanager.impactreporting.models.Connector; +import com.azure.resourcemanager.impactreporting.models.Platform; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class ConnectorsGetWithResponseMockTests { + @Test + public void testGetWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"provisioningState\":\"Canceled\",\"connectorId\":\"qbex\",\"tenantId\":\"mcqibycnojv\",\"connectorType\":\"AzureMonitor\",\"lastRunTimeStamp\":\"2021-02-06T03:19:14Z\"},\"id\":\"qsgzvahapj\",\"name\":\"zhpvgqzcjrvxd\",\"type\":\"zlmwlxkvugfhz\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + ImpactReportingManager manager = ImpactReportingManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + Connector response + = manager.connectors().getWithResponse("mdyvxqtayriw", com.azure.core.util.Context.NONE).getValue(); + + Assertions.assertEquals(Platform.AZURE_MONITOR, response.properties().connectorType()); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectorsListMockTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectorsListMockTests.java new file mode 100644 index 000000000000..890427a05bc4 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ConnectorsListMockTests.java @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.impactreporting.ImpactReportingManager; +import com.azure.resourcemanager.impactreporting.models.Connector; +import com.azure.resourcemanager.impactreporting.models.Platform; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class ConnectorsListMockTests { + @Test + public void testList() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"provisioningState\":\"Failed\",\"connectorId\":\"prnxipeil\",\"tenantId\":\"jzuaejxdultskzbb\",\"connectorType\":\"AzureMonitor\",\"lastRunTimeStamp\":\"2021-08-12T02:58:19Z\"},\"id\":\"mv\",\"name\":\"ekg\",\"type\":\"wozuhkf\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + ImpactReportingManager manager = ImpactReportingManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response = manager.connectors().list(com.azure.core.util.Context.NONE); + + Assertions.assertEquals(Platform.AZURE_MONITOR, response.iterator().next().properties().connectorType()); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ContentTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ContentTests.java new file mode 100644 index 000000000000..600cbf20c9e6 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ContentTests.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.impactreporting.models.Content; +import org.junit.jupiter.api.Assertions; + +public final class ContentTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + Content model + = BinaryData.fromString("{\"title\":\"a\",\"description\":\"hrzayvvtpgvdf\"}").toObject(Content.class); + Assertions.assertEquals("a", model.title()); + Assertions.assertEquals("hrzayvvtpgvdf", model.description()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + Content model = new Content().withTitle("a").withDescription("hrzayvvtpgvdf"); + model = BinaryData.fromObject(model).toObject(Content.class); + Assertions.assertEquals("a", model.title()); + Assertions.assertEquals("hrzayvvtpgvdf", model.description()); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ExpectedValueRangeTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ExpectedValueRangeTests.java new file mode 100644 index 000000000000..d6f84eea7c2b --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ExpectedValueRangeTests.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.impactreporting.models.ExpectedValueRange; +import org.junit.jupiter.api.Assertions; + +public final class ExpectedValueRangeTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + ExpectedValueRange model = BinaryData.fromString("{\"min\":52.25217379811007,\"max\":1.3281524552774537}") + .toObject(ExpectedValueRange.class); + Assertions.assertEquals(52.25217379811007, model.min()); + Assertions.assertEquals(1.3281524552774537, model.max()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + ExpectedValueRange model = new ExpectedValueRange().withMin(52.25217379811007).withMax(1.3281524552774537); + model = BinaryData.fromObject(model).toObject(ExpectedValueRange.class); + Assertions.assertEquals(52.25217379811007, model.min()); + Assertions.assertEquals(1.3281524552774537, model.max()); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ImpactCategoriesGetWithResponseMockTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ImpactCategoriesGetWithResponseMockTests.java new file mode 100644 index 000000000000..483790b78bbc --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ImpactCategoriesGetWithResponseMockTests.java @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.impactreporting.ImpactReportingManager; +import com.azure.resourcemanager.impactreporting.models.ImpactCategory; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class ImpactCategoriesGetWithResponseMockTests { + @Test + public void testGetWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"provisioningState\":\"Succeeded\",\"categoryId\":\"mnyyazt\",\"parentCategoryId\":\"twwrqp\",\"description\":\"dckzywbiexz\",\"requiredImpactProperties\":[{\"name\":\"ue\",\"allowedValues\":[\"bxu\"]},{\"name\":\"wbhqwal\",\"allowedValues\":[\"yoxa\",\"pdkzjancuxr\",\"d\",\"bavxbniwdjswzt\"]},{\"name\":\"dbpgnxytxhp\",\"allowedValues\":[\"zpfzabglc\",\"hxw\"]}]},\"id\":\"tyq\",\"name\":\"klbb\",\"type\":\"vplwzbhv\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + ImpactReportingManager manager = ImpactReportingManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + ImpactCategory response + = manager.impactCategories().getWithResponse("qlfktsths", com.azure.core.util.Context.NONE).getValue(); + + Assertions.assertEquals("mnyyazt", response.properties().categoryId()); + Assertions.assertEquals("twwrqp", response.properties().parentCategoryId()); + Assertions.assertEquals("dckzywbiexz", response.properties().description()); + Assertions.assertEquals("ue", response.properties().requiredImpactProperties().get(0).name()); + Assertions.assertEquals("bxu", response.properties().requiredImpactProperties().get(0).allowedValues().get(0)); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ImpactCategoriesListMockTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ImpactCategoriesListMockTests.java new file mode 100644 index 000000000000..f8becf08a63d --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ImpactCategoriesListMockTests.java @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.impactreporting.ImpactReportingManager; +import com.azure.resourcemanager.impactreporting.models.ImpactCategory; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class ImpactCategoriesListMockTests { + @Test + public void testList() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"provisioningState\":\"Canceled\",\"categoryId\":\"zkd\",\"parentCategoryId\":\"lpvlopw\",\"description\":\"ighxpk\",\"requiredImpactProperties\":[{\"name\":\"baiuebbaumny\",\"allowedValues\":[\"edeojnabc\"]}]},\"id\":\"smtxpsieb\",\"name\":\"fhvpesaps\",\"type\":\"rdqmhjjdhtldwkyz\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + ImpactReportingManager manager = ImpactReportingManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response + = manager.impactCategories().list("yuguosvmkfssx", "ukkfplgmgs", com.azure.core.util.Context.NONE); + + Assertions.assertEquals("zkd", response.iterator().next().properties().categoryId()); + Assertions.assertEquals("lpvlopw", response.iterator().next().properties().parentCategoryId()); + Assertions.assertEquals("ighxpk", response.iterator().next().properties().description()); + Assertions.assertEquals("baiuebbaumny", + response.iterator().next().properties().requiredImpactProperties().get(0).name()); + Assertions.assertEquals("edeojnabc", + response.iterator().next().properties().requiredImpactProperties().get(0).allowedValues().get(0)); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ImpactCategoryInnerTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ImpactCategoryInnerTests.java new file mode 100644 index 000000000000..744a58d8f2b0 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ImpactCategoryInnerTests.java @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.impactreporting.fluent.models.ImpactCategoryInner; +import org.junit.jupiter.api.Assertions; + +public final class ImpactCategoryInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + ImpactCategoryInner model = BinaryData.fromString( + "{\"properties\":{\"provisioningState\":\"Failed\",\"categoryId\":\"sqrglssainq\",\"parentCategoryId\":\"wnzlljfmppeeb\",\"description\":\"gxsabkyq\",\"requiredImpactProperties\":[{\"name\":\"jitcjczdzevn\",\"allowedValues\":[\"rwpdappdsbdkvwrw\",\"feusnhut\"]},{\"name\":\"eltmrldhugjzzdat\",\"allowedValues\":[\"oc\",\"geablgphuticndvk\"]}]},\"id\":\"zwyiftyhxhur\",\"name\":\"k\",\"type\":\"tyxolniwpwc\"}") + .toObject(ImpactCategoryInner.class); + Assertions.assertEquals("sqrglssainq", model.properties().categoryId()); + Assertions.assertEquals("wnzlljfmppeeb", model.properties().parentCategoryId()); + Assertions.assertEquals("gxsabkyq", model.properties().description()); + Assertions.assertEquals("jitcjczdzevn", model.properties().requiredImpactProperties().get(0).name()); + Assertions.assertEquals("rwpdappdsbdkvwrw", + model.properties().requiredImpactProperties().get(0).allowedValues().get(0)); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ImpactCategoryListResultTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ImpactCategoryListResultTests.java new file mode 100644 index 000000000000..676231c28c62 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ImpactCategoryListResultTests.java @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.impactreporting.implementation.models.ImpactCategoryListResult; +import org.junit.jupiter.api.Assertions; + +public final class ImpactCategoryListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + ImpactCategoryListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"provisioningState\":\"Canceled\",\"categoryId\":\"yxwjkcp\",\"parentCategoryId\":\"nwbxgjvtbvpyssz\",\"description\":\"rujqg\",\"requiredImpactProperties\":[{\"name\":\"uouq\",\"allowedValues\":[\"wzwbnguitn\",\"uizga\"]},{\"name\":\"x\",\"allowedValues\":[\"zuckyfi\",\"rfidfvzwdz\",\"htymw\",\"sdkf\"]}]},\"id\":\"wxmnteiwao\",\"name\":\"vkmijcmmxdcuf\",\"type\":\"fsrpymzidnse\"},{\"properties\":{\"provisioningState\":\"Failed\",\"categoryId\":\"bzsgfyccsne\",\"parentCategoryId\":\"dwzjeiach\",\"description\":\"osfln\",\"requiredImpactProperties\":[{\"name\":\"fqpte\",\"allowedValues\":[\"zvypyqrimzinp\",\"swjdkirso\",\"dqxhcrmnohjtckwh\",\"soifiyipjxsqw\"]},{\"name\":\"gr\",\"allowedValues\":[\"norcjxvsnbyxqab\",\"mocpc\"]},{\"name\":\"shurzafbljjgpbto\",\"allowedValues\":[\"mkljavb\",\"idtqajzyu\",\"pku\",\"jkrlkhbzhfepg\"]}]},\"id\":\"qex\",\"name\":\"locx\",\"type\":\"c\"}],\"nextLink\":\"ierhhbcsglummaj\"}") + .toObject(ImpactCategoryListResult.class); + Assertions.assertEquals("yxwjkcp", model.value().get(0).properties().categoryId()); + Assertions.assertEquals("nwbxgjvtbvpyssz", model.value().get(0).properties().parentCategoryId()); + Assertions.assertEquals("rujqg", model.value().get(0).properties().description()); + Assertions.assertEquals("uouq", model.value().get(0).properties().requiredImpactProperties().get(0).name()); + Assertions.assertEquals("wzwbnguitn", + model.value().get(0).properties().requiredImpactProperties().get(0).allowedValues().get(0)); + Assertions.assertEquals("ierhhbcsglummaj", model.nextLink()); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ImpactCategoryPropertiesTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ImpactCategoryPropertiesTests.java new file mode 100644 index 000000000000..556e42c7250c --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ImpactCategoryPropertiesTests.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.impactreporting.models.ImpactCategoryProperties; +import org.junit.jupiter.api.Assertions; + +public final class ImpactCategoryPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + ImpactCategoryProperties model = BinaryData.fromString( + "{\"provisioningState\":\"Failed\",\"categoryId\":\"fkgiawxk\",\"parentCategoryId\":\"ypl\",\"description\":\"kbasyypn\",\"requiredImpactProperties\":[{\"name\":\"sgcbac\",\"allowedValues\":[\"jkot\"]},{\"name\":\"nqgoulzndli\",\"allowedValues\":[\"qkgfgibma\",\"gakeqsr\"]},{\"name\":\"yb\",\"allowedValues\":[\"e\",\"qytbciq\",\"ouf\",\"mmnkzsmodmgl\"]},{\"name\":\"ugpbkw\",\"allowedValues\":[\"tduqktapspwgcuer\",\"umkdosvqwhbmd\",\"bbjfddgmbmbexp\",\"bhtqqrolfpfpsa\"]}]}") + .toObject(ImpactCategoryProperties.class); + Assertions.assertEquals("fkgiawxk", model.categoryId()); + Assertions.assertEquals("ypl", model.parentCategoryId()); + Assertions.assertEquals("kbasyypn", model.description()); + Assertions.assertEquals("sgcbac", model.requiredImpactProperties().get(0).name()); + Assertions.assertEquals("jkot", model.requiredImpactProperties().get(0).allowedValues().get(0)); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ImpactDetailsTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ImpactDetailsTests.java new file mode 100644 index 000000000000..18a1557930ea --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/ImpactDetailsTests.java @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.impactreporting.models.ImpactDetails; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; + +public final class ImpactDetailsTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + ImpactDetails model = BinaryData.fromString( + "{\"impactedResourceId\":\"iotkftutqxl\",\"startTime\":\"2021-02-26T05:04:17Z\",\"endTime\":\"2021-02-04T14:09:29Z\",\"impactId\":\"efgugnxk\"}") + .toObject(ImpactDetails.class); + Assertions.assertEquals("iotkftutqxl", model.impactedResourceId()); + Assertions.assertEquals(OffsetDateTime.parse("2021-02-26T05:04:17Z"), model.startTime()); + Assertions.assertEquals(OffsetDateTime.parse("2021-02-04T14:09:29Z"), model.endTime()); + Assertions.assertEquals("efgugnxk", model.impactId()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + ImpactDetails model = new ImpactDetails().withImpactedResourceId("iotkftutqxl") + .withStartTime(OffsetDateTime.parse("2021-02-26T05:04:17Z")) + .withEndTime(OffsetDateTime.parse("2021-02-04T14:09:29Z")) + .withImpactId("efgugnxk"); + model = BinaryData.fromObject(model).toObject(ImpactDetails.class); + Assertions.assertEquals("iotkftutqxl", model.impactedResourceId()); + Assertions.assertEquals(OffsetDateTime.parse("2021-02-26T05:04:17Z"), model.startTime()); + Assertions.assertEquals(OffsetDateTime.parse("2021-02-04T14:09:29Z"), model.endTime()); + Assertions.assertEquals("efgugnxk", model.impactId()); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/InsightInnerTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/InsightInnerTests.java new file mode 100644 index 000000000000..6b7858bfca1b --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/InsightInnerTests.java @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.impactreporting.fluent.models.InsightInner; +import com.azure.resourcemanager.impactreporting.models.Content; +import com.azure.resourcemanager.impactreporting.models.ImpactDetails; +import com.azure.resourcemanager.impactreporting.models.InsightProperties; +import com.azure.resourcemanager.impactreporting.models.InsightPropertiesAdditionalDetails; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; + +public final class InsightInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + InsightInner model = BinaryData.fromString( + "{\"properties\":{\"provisioningState\":\"Canceled\",\"category\":\"dxob\",\"status\":\"dxkqpx\",\"eventId\":\"ajionpimexgstxg\",\"groupId\":\"odgmaajrmvdjwz\",\"content\":{\"title\":\"lovmclwhijcoe\",\"description\":\"ctbzaq\"},\"eventTime\":\"2021-02-04T17:33:10Z\",\"insightUniqueId\":\"y\",\"impact\":{\"impactedResourceId\":\"bkbfkgukdkex\",\"startTime\":\"2021-01-19T06:43:15Z\",\"endTime\":\"2020-12-21T14:35:19Z\",\"impactId\":\"fmxa\"},\"additionalDetails\":{}},\"id\":\"jpgd\",\"name\":\"toc\",\"type\":\"j\"}") + .toObject(InsightInner.class); + Assertions.assertEquals("dxob", model.properties().category()); + Assertions.assertEquals("dxkqpx", model.properties().status()); + Assertions.assertEquals("ajionpimexgstxg", model.properties().eventId()); + Assertions.assertEquals("odgmaajrmvdjwz", model.properties().groupId()); + Assertions.assertEquals("lovmclwhijcoe", model.properties().content().title()); + Assertions.assertEquals("ctbzaq", model.properties().content().description()); + Assertions.assertEquals(OffsetDateTime.parse("2021-02-04T17:33:10Z"), model.properties().eventTime()); + Assertions.assertEquals("y", model.properties().insightUniqueId()); + Assertions.assertEquals("bkbfkgukdkex", model.properties().impact().impactedResourceId()); + Assertions.assertEquals(OffsetDateTime.parse("2021-01-19T06:43:15Z"), model.properties().impact().startTime()); + Assertions.assertEquals(OffsetDateTime.parse("2020-12-21T14:35:19Z"), model.properties().impact().endTime()); + Assertions.assertEquals("fmxa", model.properties().impact().impactId()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + InsightInner model = new InsightInner().withProperties(new InsightProperties().withCategory("dxob") + .withStatus("dxkqpx") + .withEventId("ajionpimexgstxg") + .withGroupId("odgmaajrmvdjwz") + .withContent(new Content().withTitle("lovmclwhijcoe").withDescription("ctbzaq")) + .withEventTime(OffsetDateTime.parse("2021-02-04T17:33:10Z")) + .withInsightUniqueId("y") + .withImpact(new ImpactDetails().withImpactedResourceId("bkbfkgukdkex") + .withStartTime(OffsetDateTime.parse("2021-01-19T06:43:15Z")) + .withEndTime(OffsetDateTime.parse("2020-12-21T14:35:19Z")) + .withImpactId("fmxa")) + .withAdditionalDetails(new InsightPropertiesAdditionalDetails())); + model = BinaryData.fromObject(model).toObject(InsightInner.class); + Assertions.assertEquals("dxob", model.properties().category()); + Assertions.assertEquals("dxkqpx", model.properties().status()); + Assertions.assertEquals("ajionpimexgstxg", model.properties().eventId()); + Assertions.assertEquals("odgmaajrmvdjwz", model.properties().groupId()); + Assertions.assertEquals("lovmclwhijcoe", model.properties().content().title()); + Assertions.assertEquals("ctbzaq", model.properties().content().description()); + Assertions.assertEquals(OffsetDateTime.parse("2021-02-04T17:33:10Z"), model.properties().eventTime()); + Assertions.assertEquals("y", model.properties().insightUniqueId()); + Assertions.assertEquals("bkbfkgukdkex", model.properties().impact().impactedResourceId()); + Assertions.assertEquals(OffsetDateTime.parse("2021-01-19T06:43:15Z"), model.properties().impact().startTime()); + Assertions.assertEquals(OffsetDateTime.parse("2020-12-21T14:35:19Z"), model.properties().impact().endTime()); + Assertions.assertEquals("fmxa", model.properties().impact().impactId()); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/InsightListResultTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/InsightListResultTests.java new file mode 100644 index 000000000000..c6d95e8574d9 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/InsightListResultTests.java @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.impactreporting.implementation.models.InsightListResult; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; + +public final class InsightListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + InsightListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"provisioningState\":\"Succeeded\",\"category\":\"i\",\"status\":\"thz\",\"eventId\":\"qdrabhjybigehoqf\",\"groupId\":\"wska\",\"content\":{\"title\":\"yktz\",\"description\":\"cuiywgqyw\"},\"eventTime\":\"2021-08-21T22:10:57Z\",\"insightUniqueId\":\"rvynhzgpph\",\"impact\":{\"impactedResourceId\":\"cgyncocpecf\",\"startTime\":\"2021-04-07T09:06:55Z\",\"endTime\":\"2021-07-15T06:39:32Z\",\"impactId\":\"oo\"},\"additionalDetails\":{}},\"id\":\"lzevgbmqjqab\",\"name\":\"y\",\"type\":\"mivkwlzuvcc\"},{\"properties\":{\"provisioningState\":\"Succeeded\",\"category\":\"nbacfi\",\"status\":\"l\",\"eventId\":\"x\",\"groupId\":\"qgtz\",\"content\":{\"title\":\"dpnqbq\",\"description\":\"wxrjfeallnwsub\"},\"eventTime\":\"2021-08-13T08:02:10Z\",\"insightUniqueId\":\"jampmngnzscxaqw\",\"impact\":{\"impactedResourceId\":\"ochcbonqvpkvl\",\"startTime\":\"2020-12-31T09:27:55Z\",\"endTime\":\"2021-10-21T12:09:05Z\",\"impactId\":\"ea\"},\"additionalDetails\":{}},\"id\":\"pheoflokeyy\",\"name\":\"enjbdlwtgrhp\",\"type\":\"jp\"},{\"properties\":{\"provisioningState\":\"Canceled\",\"category\":\"sxazjpq\",\"status\":\"gual\",\"eventId\":\"xxhejjzzvd\",\"groupId\":\"gwdslfhotwm\",\"content\":{\"title\":\"ynpwlbj\",\"description\":\"pgacftadehxnlty\"},\"eventTime\":\"2021-11-02T18:56:54Z\",\"insightUniqueId\":\"ppusuesnzwdejba\",\"impact\":{\"impactedResourceId\":\"orxzdmohctbqvud\",\"startTime\":\"2021-02-11T14:48:18Z\",\"endTime\":\"2021-10-27T15:38:07Z\",\"impactId\":\"dnvowg\"},\"additionalDetails\":{}},\"id\":\"ugw\",\"name\":\"kcglhslaz\",\"type\":\"dyggdtjixhbku\"},{\"properties\":{\"provisioningState\":\"Failed\",\"category\":\"e\",\"status\":\"hmenevfyexfwhybc\",\"eventId\":\"vyvdcs\",\"groupId\":\"ynnaam\",\"content\":{\"title\":\"ectehf\",\"description\":\"qsc\"},\"eventTime\":\"2021-08-12T09:29:36Z\",\"insightUniqueId\":\"pvhez\",\"impact\":{\"impactedResourceId\":\"kgqhcjrefovg\",\"startTime\":\"2021-02-23T16:39:14Z\",\"endTime\":\"2021-10-23T19:11:46Z\",\"impactId\":\"leyyvx\"},\"additionalDetails\":{}},\"id\":\"pkc\",\"name\":\"t\",\"type\":\"pngjcrcczsqpjhvm\"}],\"nextLink\":\"jvnysounqe\"}") + .toObject(InsightListResult.class); + Assertions.assertEquals("i", model.value().get(0).properties().category()); + Assertions.assertEquals("thz", model.value().get(0).properties().status()); + Assertions.assertEquals("qdrabhjybigehoqf", model.value().get(0).properties().eventId()); + Assertions.assertEquals("wska", model.value().get(0).properties().groupId()); + Assertions.assertEquals("yktz", model.value().get(0).properties().content().title()); + Assertions.assertEquals("cuiywgqyw", model.value().get(0).properties().content().description()); + Assertions.assertEquals(OffsetDateTime.parse("2021-08-21T22:10:57Z"), + model.value().get(0).properties().eventTime()); + Assertions.assertEquals("rvynhzgpph", model.value().get(0).properties().insightUniqueId()); + Assertions.assertEquals("cgyncocpecf", model.value().get(0).properties().impact().impactedResourceId()); + Assertions.assertEquals(OffsetDateTime.parse("2021-04-07T09:06:55Z"), + model.value().get(0).properties().impact().startTime()); + Assertions.assertEquals(OffsetDateTime.parse("2021-07-15T06:39:32Z"), + model.value().get(0).properties().impact().endTime()); + Assertions.assertEquals("oo", model.value().get(0).properties().impact().impactId()); + Assertions.assertEquals("jvnysounqe", model.nextLink()); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/InsightPropertiesAdditionalDetailsTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/InsightPropertiesAdditionalDetailsTests.java new file mode 100644 index 000000000000..c59df81a937d --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/InsightPropertiesAdditionalDetailsTests.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.impactreporting.models.InsightPropertiesAdditionalDetails; + +public final class InsightPropertiesAdditionalDetailsTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + InsightPropertiesAdditionalDetails model + = BinaryData.fromString("{}").toObject(InsightPropertiesAdditionalDetails.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + InsightPropertiesAdditionalDetails model = new InsightPropertiesAdditionalDetails(); + model = BinaryData.fromObject(model).toObject(InsightPropertiesAdditionalDetails.class); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/InsightPropertiesTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/InsightPropertiesTests.java new file mode 100644 index 000000000000..f8490b5db704 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/InsightPropertiesTests.java @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.impactreporting.models.Content; +import com.azure.resourcemanager.impactreporting.models.ImpactDetails; +import com.azure.resourcemanager.impactreporting.models.InsightProperties; +import com.azure.resourcemanager.impactreporting.models.InsightPropertiesAdditionalDetails; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; + +public final class InsightPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + InsightProperties model = BinaryData.fromString( + "{\"provisioningState\":\"Succeeded\",\"category\":\"pmouexhdz\",\"status\":\"bqe\",\"eventId\":\"nxqbzvddn\",\"groupId\":\"ndei\",\"content\":{\"title\":\"btwnpzaoqvuhrhcf\",\"description\":\"cyddglmjthjqk\"},\"eventTime\":\"2021-10-06T02:03:45Z\",\"insightUniqueId\":\"eicxmqciwqvhkhi\",\"impact\":{\"impactedResourceId\":\"uigdtopbobjog\",\"startTime\":\"2021-02-17T14:37:23Z\",\"endTime\":\"2021-04-17T11:58:30Z\",\"impactId\":\"u\"},\"additionalDetails\":{}}") + .toObject(InsightProperties.class); + Assertions.assertEquals("pmouexhdz", model.category()); + Assertions.assertEquals("bqe", model.status()); + Assertions.assertEquals("nxqbzvddn", model.eventId()); + Assertions.assertEquals("ndei", model.groupId()); + Assertions.assertEquals("btwnpzaoqvuhrhcf", model.content().title()); + Assertions.assertEquals("cyddglmjthjqk", model.content().description()); + Assertions.assertEquals(OffsetDateTime.parse("2021-10-06T02:03:45Z"), model.eventTime()); + Assertions.assertEquals("eicxmqciwqvhkhi", model.insightUniqueId()); + Assertions.assertEquals("uigdtopbobjog", model.impact().impactedResourceId()); + Assertions.assertEquals(OffsetDateTime.parse("2021-02-17T14:37:23Z"), model.impact().startTime()); + Assertions.assertEquals(OffsetDateTime.parse("2021-04-17T11:58:30Z"), model.impact().endTime()); + Assertions.assertEquals("u", model.impact().impactId()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + InsightProperties model = new InsightProperties().withCategory("pmouexhdz") + .withStatus("bqe") + .withEventId("nxqbzvddn") + .withGroupId("ndei") + .withContent(new Content().withTitle("btwnpzaoqvuhrhcf").withDescription("cyddglmjthjqk")) + .withEventTime(OffsetDateTime.parse("2021-10-06T02:03:45Z")) + .withInsightUniqueId("eicxmqciwqvhkhi") + .withImpact(new ImpactDetails().withImpactedResourceId("uigdtopbobjog") + .withStartTime(OffsetDateTime.parse("2021-02-17T14:37:23Z")) + .withEndTime(OffsetDateTime.parse("2021-04-17T11:58:30Z")) + .withImpactId("u")) + .withAdditionalDetails(new InsightPropertiesAdditionalDetails()); + model = BinaryData.fromObject(model).toObject(InsightProperties.class); + Assertions.assertEquals("pmouexhdz", model.category()); + Assertions.assertEquals("bqe", model.status()); + Assertions.assertEquals("nxqbzvddn", model.eventId()); + Assertions.assertEquals("ndei", model.groupId()); + Assertions.assertEquals("btwnpzaoqvuhrhcf", model.content().title()); + Assertions.assertEquals("cyddglmjthjqk", model.content().description()); + Assertions.assertEquals(OffsetDateTime.parse("2021-10-06T02:03:45Z"), model.eventTime()); + Assertions.assertEquals("eicxmqciwqvhkhi", model.insightUniqueId()); + Assertions.assertEquals("uigdtopbobjog", model.impact().impactedResourceId()); + Assertions.assertEquals(OffsetDateTime.parse("2021-02-17T14:37:23Z"), model.impact().startTime()); + Assertions.assertEquals(OffsetDateTime.parse("2021-04-17T11:58:30Z"), model.impact().endTime()); + Assertions.assertEquals("u", model.impact().impactId()); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/InsightsCreateWithResponseMockTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/InsightsCreateWithResponseMockTests.java new file mode 100644 index 000000000000..8759426977d5 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/InsightsCreateWithResponseMockTests.java @@ -0,0 +1,68 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.impactreporting.ImpactReportingManager; +import com.azure.resourcemanager.impactreporting.models.Content; +import com.azure.resourcemanager.impactreporting.models.ImpactDetails; +import com.azure.resourcemanager.impactreporting.models.Insight; +import com.azure.resourcemanager.impactreporting.models.InsightProperties; +import com.azure.resourcemanager.impactreporting.models.InsightPropertiesAdditionalDetails; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class InsightsCreateWithResponseMockTests { + @Test + public void testCreateWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"provisioningState\":\"Canceled\",\"category\":\"pow\",\"status\":\"przqlveu\",\"eventId\":\"upjm\",\"groupId\":\"fxobbcsws\",\"content\":{\"title\":\"tjrip\",\"description\":\"rbpbewtghfgblcg\"},\"eventTime\":\"2021-05-16T18:46:25Z\",\"insightUniqueId\":\"vlvqhjkbegi\",\"impact\":{\"impactedResourceId\":\"t\",\"startTime\":\"2021-07-17T08:56:43Z\",\"endTime\":\"2021-10-10T05:49:23Z\",\"impactId\":\"ebwwaloayqc\"},\"additionalDetails\":{}},\"id\":\"tzjuzgwyzmhtxo\",\"name\":\"gmtsavjcbpwxqpsr\",\"type\":\"nftguvriuhpr\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + ImpactReportingManager manager = ImpactReportingManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + Insight response = manager.insights() + .define("bnbbeldawkz") + .withExistingWorkloadImpact("fmisg") + .withProperties(new InsightProperties().withCategory("ourqhakau") + .withStatus("shsfwxosowzxcu") + .withEventId("cjooxdjebwpucwwf") + .withGroupId("vbvmeu") + .withContent(new Content().withTitle("civyhzceuo").withDescription("gjrwjueiotwmcdyt")) + .withEventTime(OffsetDateTime.parse("2021-09-27T21:02:03Z")) + .withInsightUniqueId("it") + .withImpact(new ImpactDetails().withImpactedResourceId("nrjawgqwg") + .withStartTime(OffsetDateTime.parse("2021-10-10T15:46:25Z")) + .withEndTime(OffsetDateTime.parse("2021-12-08T22:59:31Z")) + .withImpactId("skxfbk")) + .withAdditionalDetails(new InsightPropertiesAdditionalDetails())) + .create(); + + Assertions.assertEquals("pow", response.properties().category()); + Assertions.assertEquals("przqlveu", response.properties().status()); + Assertions.assertEquals("upjm", response.properties().eventId()); + Assertions.assertEquals("fxobbcsws", response.properties().groupId()); + Assertions.assertEquals("tjrip", response.properties().content().title()); + Assertions.assertEquals("rbpbewtghfgblcg", response.properties().content().description()); + Assertions.assertEquals(OffsetDateTime.parse("2021-05-16T18:46:25Z"), response.properties().eventTime()); + Assertions.assertEquals("vlvqhjkbegi", response.properties().insightUniqueId()); + Assertions.assertEquals("t", response.properties().impact().impactedResourceId()); + Assertions.assertEquals(OffsetDateTime.parse("2021-07-17T08:56:43Z"), + response.properties().impact().startTime()); + Assertions.assertEquals(OffsetDateTime.parse("2021-10-10T05:49:23Z"), response.properties().impact().endTime()); + Assertions.assertEquals("ebwwaloayqc", response.properties().impact().impactId()); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/InsightsDeleteByResourceGroupWithResponseMockTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/InsightsDeleteByResourceGroupWithResponseMockTests.java new file mode 100644 index 000000000000..50c8905ecafe --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/InsightsDeleteByResourceGroupWithResponseMockTests.java @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.impactreporting.ImpactReportingManager; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class InsightsDeleteByResourceGroupWithResponseMockTests { + @Test + public void testDeleteWithResponse() throws Exception { + String responseStr = "{}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + ImpactReportingManager manager = ImpactReportingManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + manager.insights().deleteByResourceGroupWithResponse("rcrgvx", "vgomz", com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/InsightsGetWithResponseMockTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/InsightsGetWithResponseMockTests.java new file mode 100644 index 000000000000..a1fb04eece13 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/InsightsGetWithResponseMockTests.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.impactreporting.ImpactReportingManager; +import com.azure.resourcemanager.impactreporting.models.Insight; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class InsightsGetWithResponseMockTests { + @Test + public void testGetWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"provisioningState\":\"Canceled\",\"category\":\"pqsxvnmicy\",\"status\":\"ceoveilovno\",\"eventId\":\"fj\",\"groupId\":\"njbkcnxdhbttkph\",\"content\":{\"title\":\"wpn\",\"description\":\"jtoqne\"},\"eventTime\":\"2021-01-17T17:58:48Z\",\"insightUniqueId\":\"lfplp\",\"impact\":{\"impactedResourceId\":\"oxuscrpabgyepsbj\",\"startTime\":\"2021-01-26T13:24:27Z\",\"endTime\":\"2021-02-16T09:59:01Z\",\"impactId\":\"ugxywpmueef\"},\"additionalDetails\":{}},\"id\":\"fqkquj\",\"name\":\"dsuyonobgla\",\"type\":\"cq\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + ImpactReportingManager manager = ImpactReportingManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + Insight response + = manager.insights().getWithResponse("uutkncw", "cwsvlxotog", com.azure.core.util.Context.NONE).getValue(); + + Assertions.assertEquals("pqsxvnmicy", response.properties().category()); + Assertions.assertEquals("ceoveilovno", response.properties().status()); + Assertions.assertEquals("fj", response.properties().eventId()); + Assertions.assertEquals("njbkcnxdhbttkph", response.properties().groupId()); + Assertions.assertEquals("wpn", response.properties().content().title()); + Assertions.assertEquals("jtoqne", response.properties().content().description()); + Assertions.assertEquals(OffsetDateTime.parse("2021-01-17T17:58:48Z"), response.properties().eventTime()); + Assertions.assertEquals("lfplp", response.properties().insightUniqueId()); + Assertions.assertEquals("oxuscrpabgyepsbj", response.properties().impact().impactedResourceId()); + Assertions.assertEquals(OffsetDateTime.parse("2021-01-26T13:24:27Z"), + response.properties().impact().startTime()); + Assertions.assertEquals(OffsetDateTime.parse("2021-02-16T09:59:01Z"), response.properties().impact().endTime()); + Assertions.assertEquals("ugxywpmueef", response.properties().impact().impactId()); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/InsightsListBySubscriptionMockTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/InsightsListBySubscriptionMockTests.java new file mode 100644 index 000000000000..cc4b9a1fbd8c --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/InsightsListBySubscriptionMockTests.java @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.impactreporting.ImpactReportingManager; +import com.azure.resourcemanager.impactreporting.models.Insight; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class InsightsListBySubscriptionMockTests { + @Test + public void testListBySubscription() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"provisioningState\":\"Canceled\",\"category\":\"dxyt\",\"status\":\"oyrxvwfudwpzntxh\",\"eventId\":\"hl\",\"groupId\":\"jbhckfrlhr\",\"content\":{\"title\":\"sbkyvpycanuzbp\",\"description\":\"kafkuwbcrnwbm\"},\"eventTime\":\"2021-05-28T09:26:13Z\",\"insightUniqueId\":\"seyvj\",\"impact\":{\"impactedResourceId\":\"srtslhspkdeem\",\"startTime\":\"2021-08-19T13:55:08Z\",\"endTime\":\"2021-05-26T11:51:11Z\",\"impactId\":\"xagkvtmelmqkrh\"},\"additionalDetails\":{}},\"id\":\"ljuahaquhcdh\",\"name\":\"duala\",\"type\":\"xqpvfadmw\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + ImpactReportingManager manager = ImpactReportingManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response + = manager.insights().listBySubscription("tcc", com.azure.core.util.Context.NONE); + + Assertions.assertEquals("dxyt", response.iterator().next().properties().category()); + Assertions.assertEquals("oyrxvwfudwpzntxh", response.iterator().next().properties().status()); + Assertions.assertEquals("hl", response.iterator().next().properties().eventId()); + Assertions.assertEquals("jbhckfrlhr", response.iterator().next().properties().groupId()); + Assertions.assertEquals("sbkyvpycanuzbp", response.iterator().next().properties().content().title()); + Assertions.assertEquals("kafkuwbcrnwbm", response.iterator().next().properties().content().description()); + Assertions.assertEquals(OffsetDateTime.parse("2021-05-28T09:26:13Z"), + response.iterator().next().properties().eventTime()); + Assertions.assertEquals("seyvj", response.iterator().next().properties().insightUniqueId()); + Assertions.assertEquals("srtslhspkdeem", response.iterator().next().properties().impact().impactedResourceId()); + Assertions.assertEquals(OffsetDateTime.parse("2021-08-19T13:55:08Z"), + response.iterator().next().properties().impact().startTime()); + Assertions.assertEquals(OffsetDateTime.parse("2021-05-26T11:51:11Z"), + response.iterator().next().properties().impact().endTime()); + Assertions.assertEquals("xagkvtmelmqkrh", response.iterator().next().properties().impact().impactId()); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/OperationDisplayTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/OperationDisplayTests.java new file mode 100644 index 000000000000..ee3d23ef08d9 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/OperationDisplayTests.java @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.impactreporting.models.OperationDisplay; + +public final class OperationDisplayTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + OperationDisplay model = BinaryData.fromString( + "{\"provider\":\"cdm\",\"resource\":\"rcryuanzwuxzdxta\",\"operation\":\"lhmwhfpmrqobm\",\"description\":\"kknryrtihf\"}") + .toObject(OperationDisplay.class); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/OperationInnerTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/OperationInnerTests.java new file mode 100644 index 000000000000..1c82d09273ed --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/OperationInnerTests.java @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.impactreporting.fluent.models.OperationInner; + +public final class OperationInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + OperationInner model = BinaryData.fromString( + "{\"name\":\"nygj\",\"isDataAction\":true,\"display\":{\"provider\":\"eqsrdeupewnwreit\",\"resource\":\"yflusarhmofc\",\"operation\":\"smy\",\"description\":\"kdtmlxhekuk\"},\"origin\":\"user,system\",\"actionType\":\"Internal\"}") + .toObject(OperationInner.class); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/OperationListResultTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/OperationListResultTests.java new file mode 100644 index 000000000000..32fa6f1b4231 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/OperationListResultTests.java @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.impactreporting.implementation.models.OperationListResult; +import org.junit.jupiter.api.Assertions; + +public final class OperationListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + OperationListResult model = BinaryData.fromString( + "{\"value\":[{\"name\":\"hq\",\"isDataAction\":true,\"display\":{\"provider\":\"pybczmehmtzopb\",\"resource\":\"h\",\"operation\":\"pidgsybbejhphoyc\",\"description\":\"xaobhdxbmtqioqjz\"},\"origin\":\"system\",\"actionType\":\"Internal\"},{\"name\":\"fpownoizhwlr\",\"isDataAction\":false,\"display\":{\"provider\":\"oqijgkdmbpaz\",\"resource\":\"bc\",\"operation\":\"pdznrbtcqqjnqgl\",\"description\":\"gnufoooj\"},\"origin\":\"system\",\"actionType\":\"Internal\"},{\"name\":\"esaagdfm\",\"isDataAction\":true,\"display\":{\"provider\":\"j\",\"resource\":\"ifkwmrvktsizntoc\",\"operation\":\"a\",\"description\":\"ajpsquc\"},\"origin\":\"system\",\"actionType\":\"Internal\"}],\"nextLink\":\"kfo\"}") + .toObject(OperationListResult.class); + Assertions.assertEquals("kfo", model.nextLink()); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/OperationsListMockTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/OperationsListMockTests.java new file mode 100644 index 000000000000..325add73dd66 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/OperationsListMockTests.java @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.impactreporting.ImpactReportingManager; +import com.azure.resourcemanager.impactreporting.models.Operation; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class OperationsListMockTests { + @Test + public void testList() throws Exception { + String responseStr + = "{\"value\":[{\"name\":\"mvfaxkffeiith\",\"isDataAction\":false,\"display\":{\"provider\":\"yvshxmz\",\"resource\":\"bzoggigrx\",\"operation\":\"ur\",\"description\":\"xxjnspydptk\"},\"origin\":\"system\",\"actionType\":\"Internal\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + ImpactReportingManager manager = ImpactReportingManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response = manager.operations().list(com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/PerformanceTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/PerformanceTests.java new file mode 100644 index 000000000000..478fcfd0c667 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/PerformanceTests.java @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.impactreporting.models.ExpectedValueRange; +import com.azure.resourcemanager.impactreporting.models.MetricUnit; +import com.azure.resourcemanager.impactreporting.models.Performance; +import org.junit.jupiter.api.Assertions; + +public final class PerformanceTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + Performance model = BinaryData.fromString( + "{\"metricName\":\"xaolth\",\"expected\":84.89547912335365,\"actual\":14.134109255164462,\"expectedValueRange\":{\"min\":3.243842052228818,\"max\":95.85514226537904},\"unit\":\"Count\"}") + .toObject(Performance.class); + Assertions.assertEquals("xaolth", model.metricName()); + Assertions.assertEquals(84.89547912335365D, model.expected()); + Assertions.assertEquals(14.134109255164462D, model.actual()); + Assertions.assertEquals(3.243842052228818, model.expectedValueRange().min()); + Assertions.assertEquals(95.85514226537904, model.expectedValueRange().max()); + Assertions.assertEquals(MetricUnit.COUNT, model.unit()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + Performance model = new Performance().withMetricName("xaolth") + .withExpected(84.89547912335365D) + .withActual(14.134109255164462D) + .withExpectedValueRange(new ExpectedValueRange().withMin(3.243842052228818).withMax(95.85514226537904)) + .withUnit(MetricUnit.COUNT); + model = BinaryData.fromObject(model).toObject(Performance.class); + Assertions.assertEquals("xaolth", model.metricName()); + Assertions.assertEquals(84.89547912335365D, model.expected()); + Assertions.assertEquals(14.134109255164462D, model.actual()); + Assertions.assertEquals(3.243842052228818, model.expectedValueRange().min()); + Assertions.assertEquals(95.85514226537904, model.expectedValueRange().max()); + Assertions.assertEquals(MetricUnit.COUNT, model.unit()); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/RequiredImpactPropertiesTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/RequiredImpactPropertiesTests.java new file mode 100644 index 000000000000..d3ae2b86bdb5 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/RequiredImpactPropertiesTests.java @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.impactreporting.models.RequiredImpactProperties; +import org.junit.jupiter.api.Assertions; + +public final class RequiredImpactPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + RequiredImpactProperties model = BinaryData + .fromString("{\"name\":\"gbquxigj\",\"allowedValues\":[\"zjaoyfhrtxil\",\"erkujys\",\"l\",\"juvf\"]}") + .toObject(RequiredImpactProperties.class); + Assertions.assertEquals("gbquxigj", model.name()); + Assertions.assertEquals("zjaoyfhrtxil", model.allowedValues().get(0)); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/SourceOrTargetTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/SourceOrTargetTests.java new file mode 100644 index 000000000000..21b6a19fe07f --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/SourceOrTargetTests.java @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.impactreporting.models.SourceOrTarget; +import org.junit.jupiter.api.Assertions; + +public final class SourceOrTargetTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SourceOrTarget model + = BinaryData.fromString("{\"azureResourceId\":\"xofpdvhpfxxypi\"}").toObject(SourceOrTarget.class); + Assertions.assertEquals("xofpdvhpfxxypi", model.azureResourceId()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SourceOrTarget model = new SourceOrTarget().withAzureResourceId("xofpdvhpfxxypi"); + model = BinaryData.fromObject(model).toObject(SourceOrTarget.class); + Assertions.assertEquals("xofpdvhpfxxypi", model.azureResourceId()); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/WorkloadImpactPropertiesAdditionalPropertiesTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/WorkloadImpactPropertiesAdditionalPropertiesTests.java new file mode 100644 index 000000000000..827de6d785d3 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/WorkloadImpactPropertiesAdditionalPropertiesTests.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.impactreporting.models.WorkloadImpactPropertiesAdditionalProperties; + +public final class WorkloadImpactPropertiesAdditionalPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + WorkloadImpactPropertiesAdditionalProperties model + = BinaryData.fromString("{}").toObject(WorkloadImpactPropertiesAdditionalProperties.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + WorkloadImpactPropertiesAdditionalProperties model = new WorkloadImpactPropertiesAdditionalProperties(); + model = BinaryData.fromObject(model).toObject(WorkloadImpactPropertiesAdditionalProperties.class); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/WorkloadImpactsDeleteWithResponseMockTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/WorkloadImpactsDeleteWithResponseMockTests.java new file mode 100644 index 000000000000..b6041737611a --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/WorkloadImpactsDeleteWithResponseMockTests.java @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.impactreporting.ImpactReportingManager; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class WorkloadImpactsDeleteWithResponseMockTests { + @Test + public void testDeleteWithResponse() throws Exception { + String responseStr = "{}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + ImpactReportingManager manager = ImpactReportingManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + manager.workloadImpacts().deleteWithResponse("vjektcxsenh", com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/WorkloadTests.java b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/WorkloadTests.java new file mode 100644 index 000000000000..48156b2b6174 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/src/test/java/com/azure/resourcemanager/impactreporting/generated/WorkloadTests.java @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.impactreporting.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.impactreporting.models.Toolset; +import com.azure.resourcemanager.impactreporting.models.Workload; +import org.junit.jupiter.api.Assertions; + +public final class WorkloadTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + Workload model + = BinaryData.fromString("{\"context\":\"odepoogin\",\"toolset\":\"Portal\"}").toObject(Workload.class); + Assertions.assertEquals("odepoogin", model.context()); + Assertions.assertEquals(Toolset.PORTAL, model.toolset()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + Workload model = new Workload().withContext("odepoogin").withToolset(Toolset.PORTAL); + model = BinaryData.fromObject(model).toObject(Workload.class); + Assertions.assertEquals("odepoogin", model.context()); + Assertions.assertEquals(Toolset.PORTAL, model.toolset()); + } +} diff --git a/sdk/impactreporting/azure-resourcemanager-impactreporting/tsp-location.yaml b/sdk/impactreporting/azure-resourcemanager-impactreporting/tsp-location.yaml new file mode 100644 index 000000000000..f077b3260131 --- /dev/null +++ b/sdk/impactreporting/azure-resourcemanager-impactreporting/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/impact/Impact.Management +commit: 2ed1d371e3519553cd527c1f9f2c316f9ed58f47 +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/impactreporting/ci.yml b/sdk/impactreporting/ci.yml new file mode 100644 index 000000000000..12b26b041be9 --- /dev/null +++ b/sdk/impactreporting/ci.yml @@ -0,0 +1,46 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. + +trigger: + branches: + include: + - main + - hotfix/* + - release/* + paths: + include: + - sdk/impactreporting/ci.yml + - sdk/impactreporting/azure-resourcemanager-impactreporting/ + exclude: + - sdk/impactreporting/pom.xml + - sdk/impactreporting/azure-resourcemanager-impactreporting/pom.xml + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/impactreporting/ci.yml + - sdk/impactreporting/azure-resourcemanager-impactreporting/ + exclude: + - sdk/impactreporting/pom.xml + - sdk/impactreporting/azure-resourcemanager-impactreporting/pom.xml + +parameters: + - name: release_azureresourcemanagerimpactreporting + displayName: azure-resourcemanager-impactreporting + type: boolean + default: false + +extends: + template: ../../eng/pipelines/templates/stages/archetype-sdk-client.yml + parameters: + ServiceDirectory: impactreporting + Artifacts: + - name: azure-resourcemanager-impactreporting + groupId: com.azure.resourcemanager + safeName: azureresourcemanagerimpactreporting + releaseInBatch: ${{ parameters.release_azureresourcemanagerimpactreporting }} diff --git a/sdk/impactreporting/pom.xml b/sdk/impactreporting/pom.xml new file mode 100644 index 000000000000..1f83deab55fe --- /dev/null +++ b/sdk/impactreporting/pom.xml @@ -0,0 +1,15 @@ + + + 4.0.0 + com.azure + azure-impactreporting-service + pom + 1.0.0 + + + azure-resourcemanager-impactreporting + + diff --git a/sdk/informaticadatamanagement/azure-resourcemanager-informaticadatamanagement/README.md b/sdk/informaticadatamanagement/azure-resourcemanager-informaticadatamanagement/README.md index 96aa0a594b2e..ea426d9b9af8 100644 --- a/sdk/informaticadatamanagement/azure-resourcemanager-informaticadatamanagement/README.md +++ b/sdk/informaticadatamanagement/azure-resourcemanager-informaticadatamanagement/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-informaticadatamanagement - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Finformaticadatamanagement%2Fazure-resourcemanager-informaticadatamanagement%2FREADME.png) + diff --git a/sdk/informaticadatamanagement/azure-resourcemanager-informaticadatamanagement/pom.xml b/sdk/informaticadatamanagement/azure-resourcemanager-informaticadatamanagement/pom.xml index 35fa5a9d8cf0..9cf3a6a8a899 100644 --- a/sdk/informaticadatamanagement/azure-resourcemanager-informaticadatamanagement/pom.xml +++ b/sdk/informaticadatamanagement/azure-resourcemanager-informaticadatamanagement/pom.xml @@ -50,28 +50,28 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/iotcentral/azure-resourcemanager-iotcentral/README.md b/sdk/iotcentral/azure-resourcemanager-iotcentral/README.md index 61e41fc846d0..3fd1cd0184d3 100644 --- a/sdk/iotcentral/azure-resourcemanager-iotcentral/README.md +++ b/sdk/iotcentral/azure-resourcemanager-iotcentral/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-iotcentral - 1.1.0-beta.2 + 1.1.0-beta.3 ``` [//]: # ({x-version-update-end}) @@ -119,4 +119,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fiotcentral%2Fazure-resourcemanager-iotcentral%2FREADME.png) + diff --git a/sdk/iotcentral/azure-resourcemanager-iotcentral/pom.xml b/sdk/iotcentral/azure-resourcemanager-iotcentral/pom.xml index 06a5df3093b7..14832d9a2fd8 100644 --- a/sdk/iotcentral/azure-resourcemanager-iotcentral/pom.xml +++ b/sdk/iotcentral/azure-resourcemanager-iotcentral/pom.xml @@ -51,29 +51,29 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/iotfirmwaredefense/azure-resourcemanager-iotfirmwaredefense/README.md b/sdk/iotfirmwaredefense/azure-resourcemanager-iotfirmwaredefense/README.md index dd1cc7d5785d..fba6de519151 100644 --- a/sdk/iotfirmwaredefense/azure-resourcemanager-iotfirmwaredefense/README.md +++ b/sdk/iotfirmwaredefense/azure-resourcemanager-iotfirmwaredefense/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-iotfirmwaredefense - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -108,4 +108,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fiotfirmwaredefense%2Fazure-resourcemanager-iotfirmwaredefense%2FREADME.png) + diff --git a/sdk/iotfirmwaredefense/azure-resourcemanager-iotfirmwaredefense/pom.xml b/sdk/iotfirmwaredefense/azure-resourcemanager-iotfirmwaredefense/pom.xml index 1c73c2444d98..c866cbfbddd9 100644 --- a/sdk/iotfirmwaredefense/azure-resourcemanager-iotfirmwaredefense/pom.xml +++ b/sdk/iotfirmwaredefense/azure-resourcemanager-iotfirmwaredefense/pom.xml @@ -51,29 +51,29 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/iothub/azure-resourcemanager-iothub/README.md b/sdk/iothub/azure-resourcemanager-iothub/README.md index 82fa2ab1a4ef..9624f529ebff 100644 --- a/sdk/iothub/azure-resourcemanager-iothub/README.md +++ b/sdk/iothub/azure-resourcemanager-iothub/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-iothub - 1.3.0 + 1.4.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -144,4 +144,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fiothub%2Fazure-resourcemanager-iothub%2FREADME.png) + diff --git a/sdk/iothub/azure-resourcemanager-iothub/pom.xml b/sdk/iothub/azure-resourcemanager-iothub/pom.xml index ffaaae2347eb..30124d5749b5 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.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test @@ -91,7 +91,7 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/iotoperations/azure-resourcemanager-iotoperations/README.md b/sdk/iotoperations/azure-resourcemanager-iotoperations/README.md index c8a20b97f7ef..49714b1f5fe9 100644 --- a/sdk/iotoperations/azure-resourcemanager-iotoperations/README.md +++ b/sdk/iotoperations/azure-resourcemanager-iotoperations/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-iotoperations - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fiotoperations%2Fazure-resourcemanager-iotoperations%2FREADME.png) + diff --git a/sdk/iotoperations/azure-resourcemanager-iotoperations/pom.xml b/sdk/iotoperations/azure-resourcemanager-iotoperations/pom.xml index 9dec39a208a7..1998f026844b 100644 --- a/sdk/iotoperations/azure-resourcemanager-iotoperations/pom.xml +++ b/sdk/iotoperations/azure-resourcemanager-iotoperations/pom.xml @@ -52,23 +52,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/iotoperations/azure-resourcemanager-iotoperations/src/main/java/com/azure/resourcemanager/iotoperations/IoTOperationsManager.java b/sdk/iotoperations/azure-resourcemanager-iotoperations/src/main/java/com/azure/resourcemanager/iotoperations/IoTOperationsManager.java index 7b7c523f67c3..d08e1250d38f 100644 --- a/sdk/iotoperations/azure-resourcemanager-iotoperations/src/main/java/com/azure/resourcemanager/iotoperations/IoTOperationsManager.java +++ b/sdk/iotoperations/azure-resourcemanager-iotoperations/src/main/java/com/azure/resourcemanager/iotoperations/IoTOperationsManager.java @@ -22,6 +22,7 @@ import com.azure.core.http.policy.UserAgentPolicy; import com.azure.core.management.profile.AzureProfile; import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.iotoperations.fluent.IoTOperationsManagementClient; import com.azure.resourcemanager.iotoperations.implementation.BrokerAuthenticationsImpl; @@ -47,6 +48,7 @@ import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; @@ -125,6 +127,9 @@ public static Configurable configure() { */ public static final class Configurable { private static final ClientLogger LOGGER = new ClientLogger(Configurable.class); + private static final String SDK_VERSION = "version"; + private static final Map PROPERTIES + = CoreUtils.getProperties("azure-resourcemanager-iotoperations.properties"); private HttpClient httpClient; private HttpLogOptions httpLogOptions; @@ -232,12 +237,14 @@ public IoTOperationsManager authenticate(TokenCredential credential, AzureProfil Objects.requireNonNull(credential, "'credential' cannot be null."); Objects.requireNonNull(profile, "'profile' cannot be null."); + String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); + StringBuilder userAgentBuilder = new StringBuilder(); userAgentBuilder.append("azsdk-java") .append("-") .append("com.azure.resourcemanager.iotoperations") .append("/") - .append("1.0.0-beta.1"); + .append(clientVersion); if (!Configuration.getGlobalConfiguration().get("AZURE_TELEMETRY_DISABLED", false)) { userAgentBuilder.append(" (") .append(Configuration.getGlobalConfiguration().get("java.version")) diff --git a/sdk/iotoperations/azure-resourcemanager-iotoperations/src/main/java/com/azure/resourcemanager/iotoperations/models/UserAssignedIdentity.java b/sdk/iotoperations/azure-resourcemanager-iotoperations/src/main/java/com/azure/resourcemanager/iotoperations/models/UserAssignedIdentity.java index f27913bc4ecc..366ad8efcfb2 100644 --- a/sdk/iotoperations/azure-resourcemanager-iotoperations/src/main/java/com/azure/resourcemanager/iotoperations/models/UserAssignedIdentity.java +++ b/sdk/iotoperations/azure-resourcemanager-iotoperations/src/main/java/com/azure/resourcemanager/iotoperations/models/UserAssignedIdentity.java @@ -17,14 +17,14 @@ @Immutable public final class UserAssignedIdentity implements JsonSerializable { /* - * The principal ID of the assigned identity. + * The client ID of the assigned identity. */ - private String principalId; + private String clientId; /* - * The client ID of the assigned identity. + * The principal ID of the assigned identity. */ - private String clientId; + private String principalId; /** * Creates an instance of UserAssignedIdentity class. @@ -33,21 +33,21 @@ public UserAssignedIdentity() { } /** - * Get the principalId property: The principal ID of the assigned identity. + * Get the clientId property: The client ID of the assigned identity. * - * @return the principalId value. + * @return the clientId value. */ - public String principalId() { - return this.principalId; + public String clientId() { + return this.clientId; } /** - * Get the clientId property: The client ID of the assigned identity. + * Get the principalId property: The principal ID of the assigned identity. * - * @return the clientId value. + * @return the principalId value. */ - public String clientId() { - return this.clientId; + public String principalId() { + return this.principalId; } /** @@ -82,10 +82,10 @@ public static UserAssignedIdentity fromJson(JsonReader jsonReader) throws IOExce String fieldName = reader.getFieldName(); reader.nextToken(); - if ("principalId".equals(fieldName)) { - deserializedUserAssignedIdentity.principalId = reader.getString(); - } else if ("clientId".equals(fieldName)) { + if ("clientId".equals(fieldName)) { deserializedUserAssignedIdentity.clientId = reader.getString(); + } else if ("principalId".equals(fieldName)) { + deserializedUserAssignedIdentity.principalId = reader.getString(); } else { reader.skipChildren(); } diff --git a/sdk/iotoperations/azure-resourcemanager-iotoperations/src/main/resources/azure-resourcemanager-iotoperations.properties b/sdk/iotoperations/azure-resourcemanager-iotoperations/src/main/resources/azure-resourcemanager-iotoperations.properties new file mode 100644 index 000000000000..defbd48204e4 --- /dev/null +++ b/sdk/iotoperations/azure-resourcemanager-iotoperations/src/main/resources/azure-resourcemanager-iotoperations.properties @@ -0,0 +1 @@ +version=${project.version} diff --git a/sdk/keyvault/README.md b/sdk/keyvault/README.md index 1f64521477e3..bf5673a720c7 100644 --- a/sdk/keyvault/README.md +++ b/sdk/keyvault/README.md @@ -19,4 +19,4 @@ To get started with a specific library, see the **README.md** file located in th - The [Azure Key Vault Administration](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md) library clients support administrative tasks such as full backup/restore and key-level role-based access control (RBAC) for Azure Key Vault Managed HSM. - [Azure Key Vault JCA](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-jca/README.md) is a Java Cryptography Architecture provider for certificates in Azure Key Vault. -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fkeyvault%2FREADME.png) + diff --git a/sdk/keyvault/azure-security-keyvault-administration/CHANGELOG.md b/sdk/keyvault/azure-security-keyvault-administration/CHANGELOG.md index f6289b43c79e..cabbec80325b 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/CHANGELOG.md +++ b/sdk/keyvault/azure-security-keyvault-administration/CHANGELOG.md @@ -11,6 +11,20 @@ ### Other Changes +## 4.6.3 (2025-03-04) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. +- Upgraded `azure-json` from `1.3.0` to version `1.4.0`. +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`. + +## 4.6.2 (2025-01-14) + +### Bugs Fixed +- Fixed issue where certain `toString()` calls could cause a `NullPointerException`. ([#43776](https://github.com/Azure/azure-sdk-for-java/pull/43776)) ## 4.6.1 (2024-12-04) diff --git a/sdk/keyvault/azure-security-keyvault-administration/README.md b/sdk/keyvault/azure-security-keyvault-administration/README.md index fba8602e2778..f77ff8ab65c8 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/README.md +++ b/sdk/keyvault/azure-security-keyvault-administration/README.md @@ -43,7 +43,7 @@ If you want to take dependency on a particular version of the library that is no com.azure azure-security-keyvault-administration - 4.6.0 + 4.7.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -711,4 +711,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][microsoft_c [http_clients_wiki]: https://learn.microsoft.com/azure/developer/java/sdk/http-client-pipeline#http-clients [microsoft_code_of_conduct]: https://opensource.microsoft.com/codeofconduct/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fkeyvault%2Fazure-security-keyvault-administration%2FREADME.png) + diff --git a/sdk/keyvault/azure-security-keyvault-administration/checkstyle-suppressions.xml b/sdk/keyvault/azure-security-keyvault-administration/checkstyle-suppressions.xml index f071cf3b319d..da8b5dca4da3 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/checkstyle-suppressions.xml +++ b/sdk/keyvault/azure-security-keyvault-administration/checkstyle-suppressions.xml @@ -3,12 +3,14 @@ + - + - - + + + diff --git a/sdk/keyvault/azure-security-keyvault-administration/pom.xml b/sdk/keyvault/azure-security-keyvault-administration/pom.xml index 945143ab0b07..ee18a56f5000 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/pom.xml +++ b/sdk/keyvault/azure-security-keyvault-administration/pom.xml @@ -52,17 +52,17 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 @@ -74,7 +74,7 @@ com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test @@ -86,13 +86,13 @@ com.azure azure-storage-blob - 12.29.0 + 12.29.1 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAccessControlAsyncClient.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAccessControlAsyncClient.java index e78d53c9c42d..2170aa64d7be 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAccessControlAsyncClient.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAccessControlAsyncClient.java @@ -8,16 +8,18 @@ import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.HttpPipeline; import com.azure.core.http.rest.PagedFlux; -import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.RequestOptions; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.SimpleResponse; +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.security.keyvault.administration.implementation.KeyVaultAccessControlClientImpl; +import com.azure.security.keyvault.administration.implementation.KeyVaultAdministrationClientImpl; import com.azure.security.keyvault.administration.implementation.KeyVaultAdministrationUtils; -import com.azure.security.keyvault.administration.implementation.KeyVaultErrorCodeStrings; +import com.azure.security.keyvault.administration.implementation.models.RoleAssignment; import com.azure.security.keyvault.administration.implementation.models.RoleAssignmentCreateParameters; +import com.azure.security.keyvault.administration.implementation.models.RoleDefinition; import com.azure.security.keyvault.administration.implementation.models.RoleDefinitionCreateParameters; import com.azure.security.keyvault.administration.models.KeyVaultAdministrationException; import com.azure.security.keyvault.administration.models.KeyVaultRoleAssignment; @@ -31,7 +33,9 @@ import java.util.UUID; import static com.azure.core.util.FluxUtil.monoError; +import static com.azure.core.util.FluxUtil.pagedFluxError; import static com.azure.core.util.FluxUtil.withContext; +import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.mapPagedResponse; import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.swallowExceptionForStatusCodeAsync; import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.validateAndGetRoleAssignmentCreateParameters; import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.validateAndGetRoleDefinitionCreateParameters; @@ -225,18 +229,13 @@ public final class KeyVaultAccessControlAsyncClient { /** * The underlying AutoRest client used to interact with the Key Vault service. */ - private final KeyVaultAccessControlClientImpl clientImpl; + private final KeyVaultAdministrationClientImpl clientImpl; /** * The Key Vault URL this client is associated to. */ private final String vaultUrl; - /** - * The Key Vault Administration Service version to use with this client. - */ - private final String serviceVersion; - /** * The {@link HttpPipeline} powering this client. */ @@ -247,13 +246,13 @@ public final class KeyVaultAccessControlAsyncClient { */ KeyVaultAccessControlAsyncClient(URL vaultUrl, HttpPipeline httpPipeline, KeyVaultAdministrationServiceVersion serviceVersion) { - Objects.requireNonNull(vaultUrl, KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED); + + Objects.requireNonNull(vaultUrl, KeyVaultAdministrationUtil.VAULT_END_POINT_REQUIRED); this.vaultUrl = vaultUrl.toString(); - this.serviceVersion = serviceVersion.getVersion(); this.pipeline = httpPipeline; - clientImpl = new KeyVaultAccessControlClientImpl(httpPipeline, this.serviceVersion); + clientImpl = new KeyVaultAdministrationClientImpl(httpPipeline, this.vaultUrl, serviceVersion); } /** @@ -299,89 +298,24 @@ HttpPipeline getHttpPipeline() { */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux listRoleDefinitions(KeyVaultRoleScope roleScope) { - return new PagedFlux<>(() -> withContext(context -> listRoleDefinitionsFirstPage(vaultUrl, roleScope, context)), - continuationToken -> withContext(context -> listRoleDefinitionsNextPage(continuationToken, context))); - } - - /** - * Lists all {@link KeyVaultRoleDefinition role definitions} that are applicable at the given - * {@link KeyVaultRoleScope role scope} and above. - * - * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleDefinition role definitions}. - * @param context Additional {@link Context} that is passed through the HTTP pipeline during the service call. - * - * @return A {@link PagedFlux} containing the {@link KeyVaultRoleDefinition role definitions} for the given - * {@link KeyVaultRoleScope role scope}. - * - * @throws KeyVaultAdministrationException If the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} is {@code null}. - */ - PagedFlux listRoleDefinitions(KeyVaultRoleScope roleScope, Context context) { - return new PagedFlux<>(() -> listRoleDefinitionsFirstPage(vaultUrl, roleScope, context), - continuationToken -> listRoleDefinitionsNextPage(continuationToken, context)); - } - - /** - * Lists all {@link KeyVaultRoleDefinition role definitions} in the first page that are applicable at the given - * {@link KeyVaultRoleScope role scope} and above. - * - * @param vaultUrl The URL for the Key Vault this client is associated with. - * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleDefinition role definition}. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link Mono} containing a {@link PagedResponse} of {@link KeyVaultRoleDefinition role definitions} - * for the given {@link KeyVaultRoleScope role scope} from the first page of results. - * - * @throws KeyVaultAdministrationException If the given {@code vaultUrl} or {@code roleScope} are invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} is {@code null}. - */ - Mono> listRoleDefinitionsFirstPage(String vaultUrl, - KeyVaultRoleScope roleScope, Context context) { try { Objects.requireNonNull(roleScope, - String.format(KeyVaultErrorCodeStrings.PARAMETER_REQUIRED, "'roleScope'")); + String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'roleScope'")); - return clientImpl.getRoleDefinitions() - .listSinglePageAsync(vaultUrl, roleScope.toString(), null, context) - .doOnRequest(ignored -> LOGGER.verbose("Listing role definitions for roleScope - {}", roleScope)) - .doOnSuccess(response -> LOGGER.verbose("Listed role definitions for roleScope - {}", roleScope)) - .doOnError( - error -> LOGGER.warning("Failed to list role definitions for roleScope - {}", roleScope, error)) - .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) - .map(KeyVaultAdministrationUtil::transformRoleDefinitionsPagedResponse); + return new PagedFlux<>( + () -> withContext(context -> clientImpl.getRoleDefinitions() + .listSinglePageAsync(roleScope.toString(), new RequestOptions().setContext(context)) + .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) + .map(pagedResponse -> mapPagedResponse(pagedResponse, + binaryData -> KeyVaultAdministrationUtil + .roleDefinitionToKeyVaultRoleDefinition(binaryData.toObject(RoleDefinition.class))))), + nextLink -> withContext(context -> clientImpl.getRoleDefinitions() + .listNextSinglePageAsync(nextLink, new RequestOptions().setContext(context)) + .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) + .map(pagedResponse -> mapPagedResponse(pagedResponse, binaryData -> KeyVaultAdministrationUtil + .roleDefinitionToKeyVaultRoleDefinition(binaryData.toObject(RoleDefinition.class)))))); } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - } - - /** - * Lists all {@link KeyVaultRoleDefinition role definitions} given by the {@code nextPageLink} that was retrieved - * from a call to - * {@link KeyVaultAccessControlAsyncClient#listRoleDefinitionsFirstPage(String, KeyVaultRoleScope, Context)}. - * - * @param continuationToken The {@link PagedResponse#getContinuationToken() continuationToken} from a previous, - * successful call to one of the {@code listKeyVaultRoleDefinitions} operations. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link Mono} containing a {@link PagedResponse} of {@link KeyVaultRoleDefinition role definitions} - * for the given {@link KeyVaultRoleScope role scope} from the next page of results. - * - * @throws KeyVaultAdministrationException If the given {@code continuationToken} is invalid. - */ - Mono> listRoleDefinitionsNextPage(String continuationToken, Context context) { - try { - return clientImpl.getRoleDefinitions() - .listNextSinglePageAsync(continuationToken, vaultUrl, context) - .doOnRequest( - ignored -> LOGGER.verbose("Listing next role definitions page - Page {}", continuationToken)) - .doOnSuccess( - response -> LOGGER.verbose("Listed next role definitions page - Page {}", continuationToken)) - .doOnError(error -> LOGGER.warning("Failed to list next role definitions page - Page {}", - continuationToken, error)) - .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) - .map(KeyVaultAdministrationUtil::transformRoleDefinitionsPagedResponse); - } catch (RuntimeException e) { - return monoError(LOGGER, e); + return pagedFluxError(LOGGER, e); } } @@ -519,19 +453,17 @@ public Mono> setRoleDefinitionWithResponse(SetR */ Mono> setRoleDefinitionWithResponse(SetRoleDefinitionOptions options, Context context) { + try { RoleDefinitionCreateParameters parameters = validateAndGetRoleDefinitionCreateParameters(options); return clientImpl.getRoleDefinitions() - .createOrUpdateWithResponseAsync(vaultUrl, options.getRoleScope().toString(), - options.getRoleDefinitionName(), parameters, context) - .doOnRequest( - ignored -> LOGGER.verbose("Creating role definition - {}", options.getRoleDefinitionName())) - .doOnSuccess(response -> LOGGER.verbose("Created role definition - {}", response.getValue().getName())) - .doOnError(error -> LOGGER.warning("Failed to create role definition - {}", - options.getRoleDefinitionName(), error)) + .createOrUpdateWithResponseAsync(options.getRoleScope().toString(), options.getRoleDefinitionName(), + BinaryData.fromObject(parameters), new RequestOptions().setContext(context)) .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) - .map(KeyVaultAdministrationUtil::transformRoleDefinitionResponse); + .map(response -> KeyVaultAdministrationUtil.transformBinaryDataResponse(response, + binaryData -> KeyVaultAdministrationUtil + .roleDefinitionToKeyVaultRoleDefinition(binaryData.toObject(RoleDefinition.class)))); } catch (RuntimeException e) { return monoError(LOGGER, e); } @@ -621,18 +553,17 @@ public Mono> getRoleDefinitionWithResponse(KeyV */ Mono> getRoleDefinitionWithResponse(KeyVaultRoleScope roleScope, String roleDefinitionName, Context context) { + try { validateRoleDefinitionParameters(roleScope, roleDefinitionName); return clientImpl.getRoleDefinitions() - .getWithResponseAsync(vaultUrl, roleScope.toString(), roleDefinitionName, context) - .doOnRequest(ignored -> LOGGER.verbose("Retrieving role definition - {}", roleDefinitionName)) - .doOnSuccess( - response -> LOGGER.verbose("Retrieved role definition - {}", response.getValue().getName())) - .doOnError( - error -> LOGGER.warning("Failed to retrieved role definition - {}", roleDefinitionName, error)) + .getWithResponseAsync(roleScope.toString(), roleDefinitionName, + new RequestOptions().setContext(context)) .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) - .map(KeyVaultAdministrationUtil::transformRoleDefinitionResponse); + .map(response -> KeyVaultAdministrationUtil.transformBinaryDataResponse(response, + binaryData -> KeyVaultAdministrationUtil + .roleDefinitionToKeyVaultRoleDefinition(binaryData.toObject(RoleDefinition.class)))); } catch (RuntimeException e) { return monoError(LOGGER, e); } @@ -696,6 +627,7 @@ public Mono deleteRoleDefinition(KeyVaultRoleScope roleScope, String roleD @ServiceMethod(returns = ReturnType.SINGLE) public Mono> deleteRoleDefinitionWithResponse(KeyVaultRoleScope roleScope, String roleDefinitionName) { + return withContext(context -> deleteRoleDefinitionWithResponse(roleScope, roleDefinitionName, context)); } @@ -714,14 +646,13 @@ public Mono> deleteRoleDefinitionWithResponse(KeyVaultRoleScope r */ Mono> deleteRoleDefinitionWithResponse(KeyVaultRoleScope roleScope, String roleDefinitionName, Context context) { + try { validateRoleDefinitionParameters(roleScope, roleDefinitionName); return clientImpl.getRoleDefinitions() - .deleteWithResponseAsync(vaultUrl, roleScope.toString(), roleDefinitionName, context) - .doOnRequest(ignored -> LOGGER.verbose("Deleting role definition - {}", roleDefinitionName)) - .doOnSuccess(response -> LOGGER.verbose("Deleted role definition - {}", response.getValue().getName())) - .doOnError(error -> LOGGER.warning("Failed to delete role definition - {}", roleDefinitionName, error)) + .deleteWithResponseAsync(roleScope.toString(), roleDefinitionName, + new RequestOptions().setContext(context)) .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) .map(response -> (Response) new SimpleResponse(response, null)) .onErrorResume(KeyVaultAdministrationException.class, @@ -745,88 +676,24 @@ Mono> deleteRoleDefinitionWithResponse(KeyVaultRoleScope roleScop */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux listRoleAssignments(KeyVaultRoleScope roleScope) { - return new PagedFlux<>(() -> withContext(context -> listRoleAssignmentsFirstPage(vaultUrl, roleScope, context)), - continuationToken -> withContext(context -> listRoleAssignmentsNextPage(continuationToken, context))); - } - - /** - * Lists all {@link KeyVaultRoleAssignment role assignments} that are applicable at the given - * {@link KeyVaultRoleScope role scope} and above. - * - * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleAssignment role assignment}. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link PagedFlux} containing the {@link KeyVaultRoleAssignment role assignments} for the given - * {@link KeyVaultRoleScope role scope}. - * - * @throws KeyVaultAdministrationException If the given {@code roleScope} is invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} is {@code null}. - */ - PagedFlux listRoleAssignments(KeyVaultRoleScope roleScope, Context context) { - return new PagedFlux<>(() -> listRoleAssignmentsFirstPage(vaultUrl, roleScope, context), - continuationToken -> listRoleAssignmentsNextPage(continuationToken, context)); - } - - /** - * Lists all {@link KeyVaultRoleAssignment role assignments} in the first page that are applicable at the given - * {@link KeyVaultRoleScope role scope} and above. - * - * @param vaultUrl The URL for the Key Vault this client is associated with. - * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleAssignment role assignment}. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link Mono} containing a {@link PagedResponse} of {@link KeyVaultRoleAssignment role assignments} - * in the given {@link KeyVaultRoleScope role scope} from the first page of results. - * - * @throws KeyVaultAdministrationException If the given {@code vaultUrl} or {@code roleScope} are invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} is {@code null}. - */ - Mono> listRoleAssignmentsFirstPage(String vaultUrl, - KeyVaultRoleScope roleScope, Context context) { try { Objects.requireNonNull(roleScope, - String.format(KeyVaultErrorCodeStrings.PARAMETER_REQUIRED, "'roleScope'")); + String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'roleScope'")); - return clientImpl.getRoleAssignments() - .listForScopeSinglePageAsync(vaultUrl, roleScope.toString(), null, context) - .doOnRequest(ignored -> LOGGER.verbose("Listing role assignments for roleScope - {}", roleScope)) - .doOnSuccess(response -> LOGGER.verbose("Listed role assignments for roleScope - {}", roleScope)) - .doOnError( - error -> LOGGER.warning("Failed to list role assignments for roleScope - {}", roleScope, error)) - .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) - .map(KeyVaultAdministrationUtil::transformRoleAssignmentsPagedResponse); + return new PagedFlux<>( + () -> withContext(context -> clientImpl.getRoleAssignments() + .listForScopeSinglePageAsync(roleScope.toString(), new RequestOptions().setContext(context)) + .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) + .map(pagedResponse -> mapPagedResponse(pagedResponse, + binaryData -> KeyVaultAdministrationUtil + .roleAssignmentToKeyVaultRoleAssignment(binaryData.toObject(RoleAssignment.class))))), + nextLink -> withContext(context -> clientImpl.getRoleAssignments() + .listForScopeNextSinglePageAsync(nextLink, new RequestOptions().setContext(context)) + .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) + .map(pagedResponse -> mapPagedResponse(pagedResponse, binaryData -> KeyVaultAdministrationUtil + .roleAssignmentToKeyVaultRoleAssignment(binaryData.toObject(RoleAssignment.class)))))); } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - } - - /** - * Lists all {@link KeyVaultRoleAssignment role assignments} given by the {@code nextPageLink} that was - * retrieved from a call to {@link KeyVaultAccessControlAsyncClient#listRoleAssignments(KeyVaultRoleScope)}. - * - * @param continuationToken The {@link PagedResponse#getContinuationToken() continuationToken} from a previous, - * successful call to one of the {@code listKeyVaultRoleAssignments} operations. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link Mono} containing a {@link PagedResponse} of {@link KeyVaultRoleAssignment role assignments} - * for the given {@link KeyVaultRoleScope role scope} from the first page of results. - * - * @throws KeyVaultAdministrationException If the given {@code continuationToken} is invalid. - */ - Mono> listRoleAssignmentsNextPage(String continuationToken, Context context) { - try { - return clientImpl.getRoleAssignments() - .listForScopeNextSinglePageAsync(continuationToken, vaultUrl, context) - .doOnRequest( - ignored -> LOGGER.verbose("Listing next role assignments page - Page {}", continuationToken)) - .doOnSuccess( - response -> LOGGER.verbose("Listed next role assignments page - Page {}", continuationToken)) - .doOnError(error -> LOGGER.warning("Failed to list next role assignments page - Page {}", - continuationToken, error)) - .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) - .map(KeyVaultAdministrationUtil::transformRoleAssignmentsPagedResponse); - } catch (RuntimeException e) { - return monoError(LOGGER, e); + return pagedFluxError(LOGGER, e); } } @@ -863,6 +730,7 @@ Mono> listRoleAssignmentsNextPage(String c @ServiceMethod(returns = ReturnType.SINGLE) public Mono createRoleAssignment(KeyVaultRoleScope roleScope, String roleDefinitionId, String principalId) { + return createRoleAssignment(roleScope, roleDefinitionId, principalId, UUID.randomUUID().toString()); } @@ -902,6 +770,7 @@ public Mono createRoleAssignment(KeyVaultRoleScope roleS @ServiceMethod(returns = ReturnType.SINGLE) public Mono createRoleAssignment(KeyVaultRoleScope roleScope, String roleDefinitionId, String principalId, String roleAssignmentName) { + return createRoleAssignmentWithResponse(roleScope, roleDefinitionId, principalId, roleAssignmentName) .flatMap(FluxUtil::toMono); } @@ -947,6 +816,7 @@ public Mono createRoleAssignment(KeyVaultRoleScope roleS @ServiceMethod(returns = ReturnType.SINGLE) public Mono> createRoleAssignmentWithResponse(KeyVaultRoleScope roleScope, String roleDefinitionId, String principalId, String roleAssignmentName) { + return withContext(context -> createRoleAssignmentWithResponse(roleScope, roleDefinitionId, principalId, roleAssignmentName, context)); } @@ -972,17 +842,18 @@ public Mono> createRoleAssignmentWithResponse(K */ Mono> createRoleAssignmentWithResponse(KeyVaultRoleScope roleScope, String roleDefinitionId, String principalId, String roleAssignmentName, Context context) { + try { RoleAssignmentCreateParameters parameters = validateAndGetRoleAssignmentCreateParameters(roleScope, roleDefinitionId, principalId, roleAssignmentName); return clientImpl.getRoleAssignments() - .createWithResponseAsync(vaultUrl, roleScope.toString(), roleAssignmentName, parameters, context) - .doOnRequest(ignored -> LOGGER.verbose("Creating role assignment - {}", roleAssignmentName)) - .doOnSuccess(response -> LOGGER.verbose("Created role assignment - {}", response.getValue().getName())) - .doOnError(error -> LOGGER.warning("Failed to create role assignment - {}", roleAssignmentName, error)) + .createWithResponseAsync(roleScope.toString(), roleAssignmentName, BinaryData.fromObject(parameters), + new RequestOptions().setContext(context)) .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) - .map(KeyVaultAdministrationUtil::transformRoleAssignmentResponse); + .map(response -> KeyVaultAdministrationUtil.transformBinaryDataResponse(response, + binaryData -> KeyVaultAdministrationUtil + .roleAssignmentToKeyVaultRoleAssignment(binaryData.toObject(RoleAssignment.class)))); } catch (RuntimeException e) { return monoError(LOGGER, e); } @@ -1050,6 +921,7 @@ public Mono getRoleAssignment(KeyVaultRoleScope roleScop @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getRoleAssignmentWithResponse(KeyVaultRoleScope roleScope, String roleAssignmentName) { + return withContext(context -> getRoleAssignmentWithResponse(roleScope, roleAssignmentName, context)); } @@ -1070,17 +942,17 @@ public Mono> getRoleAssignmentWithResponse(KeyV */ Mono> getRoleAssignmentWithResponse(KeyVaultRoleScope roleScope, String roleAssignmentName, Context context) { + try { validateRoleAssignmentParameters(roleScope, roleAssignmentName); + return clientImpl.getRoleAssignments() - .getWithResponseAsync(vaultUrl, roleScope.toString(), roleAssignmentName, context) - .doOnRequest(ignored -> LOGGER.verbose("Retrieving role assignment - {}", roleAssignmentName)) - .doOnSuccess( - response -> LOGGER.verbose("Retrieved role assignment - {}", response.getValue().getName())) - .doOnError( - error -> LOGGER.warning("Failed to retrieve role assignment - {}", roleAssignmentName, error)) + .getWithResponseAsync(roleScope.toString(), roleAssignmentName, + new RequestOptions().setContext(context)) .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) - .map(KeyVaultAdministrationUtil::transformRoleAssignmentResponse); + .map(response -> KeyVaultAdministrationUtil.transformBinaryDataResponse(response, + binaryData -> KeyVaultAdministrationUtil + .roleAssignmentToKeyVaultRoleAssignment(binaryData.toObject(RoleAssignment.class)))); } catch (RuntimeException e) { return monoError(LOGGER, e); } @@ -1144,6 +1016,7 @@ public Mono deleteRoleAssignment(KeyVaultRoleScope roleScope, String roleA @ServiceMethod(returns = ReturnType.SINGLE) public Mono> deleteRoleAssignmentWithResponse(KeyVaultRoleScope roleScope, String roleAssignmentName) { + return withContext(context -> deleteRoleAssignmentWithResponse(roleScope, roleAssignmentName, context)); } @@ -1162,14 +1035,13 @@ public Mono> deleteRoleAssignmentWithResponse(KeyVaultRoleScope r */ Mono> deleteRoleAssignmentWithResponse(KeyVaultRoleScope roleScope, String roleAssignmentName, Context context) { + try { validateRoleAssignmentParameters(roleScope, roleAssignmentName); return clientImpl.getRoleAssignments() - .deleteWithResponseAsync(vaultUrl, roleScope.toString(), roleAssignmentName, context) - .doOnRequest(ignored -> LOGGER.verbose("Deleting role assignment - {}", roleAssignmentName)) - .doOnSuccess(response -> LOGGER.verbose("Deleted role assignment - {}", response.getValue().getName())) - .doOnError(error -> LOGGER.warning("Failed to delete role assignment - {}", roleAssignmentName, error)) + .deleteWithResponseAsync(roleScope.toString(), roleAssignmentName, + new RequestOptions().setContext(context)) .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException) .map(response -> (Response) new SimpleResponse(response, null)) .onErrorResume(KeyVaultAdministrationException.class, diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAccessControlClient.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAccessControlClient.java index ca9152da65f9..372b8a627a7d 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAccessControlClient.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAccessControlClient.java @@ -6,17 +6,16 @@ import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceClient; import com.azure.core.annotation.ServiceMethod; +import com.azure.core.exception.HttpResponseException; import com.azure.core.http.HttpPipeline; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.RequestOptions; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.BinaryData; import com.azure.core.util.Context; import com.azure.core.util.logging.ClientLogger; -import com.azure.security.keyvault.administration.implementation.KeyVaultAccessControlClientImpl; -import com.azure.security.keyvault.administration.implementation.KeyVaultAdministrationUtils; -import com.azure.security.keyvault.administration.implementation.KeyVaultErrorCodeStrings; -import com.azure.security.keyvault.administration.implementation.models.KeyVaultErrorException; +import com.azure.security.keyvault.administration.implementation.KeyVaultAdministrationClientImpl; import com.azure.security.keyvault.administration.implementation.models.RoleAssignment; import com.azure.security.keyvault.administration.implementation.models.RoleAssignmentCreateParameters; import com.azure.security.keyvault.administration.implementation.models.RoleDefinition; @@ -32,12 +31,15 @@ import java.util.Objects; import java.util.UUID; -import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.enableSyncRestProxy; +import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.roleAssignmentToKeyVaultRoleAssignment; +import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.roleDefinitionToKeyVaultRoleDefinition; import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.swallowExceptionForStatusCodeSync; +import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.transformBinaryDataResponse; import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.validateAndGetRoleAssignmentCreateParameters; import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.validateAndGetRoleDefinitionCreateParameters; import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.validateRoleAssignmentParameters; import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.validateRoleDefinitionParameters; +import static com.azure.security.keyvault.administration.implementation.KeyVaultAdministrationUtils.toKeyVaultAdministrationException; /** * The {@link KeyVaultAccessControlClient} provides synchronous methods to view and manage Role Based Access for a @@ -225,35 +227,23 @@ public final class KeyVaultAccessControlClient { /** * The underlying AutoRest client used to interact with the Key Vault service. */ - private final KeyVaultAccessControlClientImpl clientImpl; + private final KeyVaultAdministrationClientImpl implClient; /** * The Key Vault URL this client is associated to. */ private final String vaultUrl; - /** - * The Key Vault Administration Service version to use with this client. - */ - private final String serviceVersion; - - /** - * The {@link HttpPipeline} powering this client. - */ - private final HttpPipeline pipeline; - /** * Package private constructor to be used by {@link KeyVaultAccessControlClientBuilder}. */ KeyVaultAccessControlClient(URL vaultUrl, HttpPipeline httpPipeline, KeyVaultAdministrationServiceVersion serviceVersion) { - Objects.requireNonNull(vaultUrl, KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED); - this.vaultUrl = vaultUrl.toString(); - this.serviceVersion = serviceVersion.getVersion(); - this.pipeline = httpPipeline; + Objects.requireNonNull(vaultUrl, KeyVaultAdministrationUtil.VAULT_END_POINT_REQUIRED); - clientImpl = new KeyVaultAccessControlClientImpl(httpPipeline, this.serviceVersion); + this.vaultUrl = vaultUrl.toString(); + implClient = new KeyVaultAdministrationClientImpl(httpPipeline, this.vaultUrl, serviceVersion); } /** @@ -323,60 +313,15 @@ public PagedIterable listRoleDefinitions(KeyVaultRoleSco */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable listRoleDefinitions(KeyVaultRoleScope roleScope, Context context) { - final Context contextToUse = enableSyncRestProxy(context); - return new PagedIterable<>(() -> listRoleDefinitionsFirstPage(vaultUrl, roleScope, contextToUse), - continuationToken -> listRoleDefinitionsNextPage(continuationToken, contextToUse)); - } + Objects.requireNonNull(roleScope, String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'roleScope'")); - /** - * Lists all {@link KeyVaultRoleDefinition role definitions} in the first page that are applicable at the given - * {@link KeyVaultRoleScope role scope} and above. - * - * @param vaultUrl The URL for the Key Vault this client is associated with. - * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleDefinition role definition}. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link Mono} containing a {@link PagedResponse} of {@link KeyVaultRoleDefinition role definitions} - * for the given {@link KeyVaultRoleScope role scope} from the first page of results. - * - * @throws KeyVaultAdministrationException If the given {@code vaultUrl} or {@code roleScope} are invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} is {@code null}. - */ - PagedResponse listRoleDefinitionsFirstPage(String vaultUrl, KeyVaultRoleScope roleScope, - Context context) { - Objects.requireNonNull(roleScope, String.format(KeyVaultErrorCodeStrings.PARAMETER_REQUIRED, "'roleScope'")); try { - PagedResponse roleDefinitionPagedResponse - = clientImpl.getRoleDefinitions().listSinglePage(vaultUrl, roleScope.toString(), null, context); - return KeyVaultAdministrationUtil.transformRoleDefinitionsPagedResponse(roleDefinitionPagedResponse); - } catch (KeyVaultErrorException e) { - throw LOGGER.logExceptionAsError(KeyVaultAdministrationUtils.toKeyVaultAdministrationException(e)); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } - - /** - * Lists all {@link KeyVaultRoleDefinition role definitions} given by the {@code nextPageLink} that was retrieved - * from a call to - * {@link KeyVaultAccessControlClient#listRoleDefinitionsFirstPage(String, KeyVaultRoleScope, Context)}. - * - * @param continuationToken The {@link PagedResponse#getContinuationToken() continuationToken} from a previous, - * successful call to one of the {@code listKeyVaultRoleDefinitions} operations. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link Mono} containing a {@link PagedResponse} of {@link KeyVaultRoleDefinition role definitions} - * for the given {@link KeyVaultRoleScope role scope} from the next page of results. - * - * @throws KeyVaultAdministrationException If the given {@code continuationToken} is invalid. - */ - PagedResponse listRoleDefinitionsNextPage(String continuationToken, Context context) { - try { - PagedResponse roleDefinitionPagedResponse - = clientImpl.getRoleDefinitions().listNextSinglePage(continuationToken, vaultUrl, context); - return KeyVaultAdministrationUtil.transformRoleDefinitionsPagedResponse(roleDefinitionPagedResponse); - } catch (KeyVaultErrorException e) { - throw LOGGER.logExceptionAsError(KeyVaultAdministrationUtils.toKeyVaultAdministrationException(e)); + return implClient.getRoleDefinitions() + .list(roleScope.toString(), new RequestOptions().setContext(context)) + .mapPage( + binaryData -> roleDefinitionToKeyVaultRoleDefinition(binaryData.toObject(RoleDefinition.class))); + } catch (HttpResponseException e) { + throw LOGGER.logExceptionAsError(toKeyVaultAdministrationException(e)); } catch (RuntimeException e) { throw LOGGER.logExceptionAsError(e); } @@ -500,15 +445,18 @@ public KeyVaultRoleDefinition setRoleDefinition(KeyVaultRoleScope roleScope, Str @ServiceMethod(returns = ReturnType.SINGLE) public Response setRoleDefinitionWithResponse(SetRoleDefinitionOptions options, Context context) { - context = enableSyncRestProxy(context); + RoleDefinitionCreateParameters parameters = validateAndGetRoleDefinitionCreateParameters(options); + try { - Response roleDefinitionResponse = clientImpl.getRoleDefinitions() - .createOrUpdateWithResponse(vaultUrl, options.getRoleScope().toString(), - options.getRoleDefinitionName(), parameters, context); - return KeyVaultAdministrationUtil.transformRoleDefinitionResponse(roleDefinitionResponse); - } catch (KeyVaultErrorException e) { - throw LOGGER.logExceptionAsError(KeyVaultAdministrationUtils.toKeyVaultAdministrationException(e)); + Response roleDefinitionResponse = implClient.getRoleDefinitions() + .createOrUpdateWithResponse(options.getRoleScope().toString(), options.getRoleDefinitionName(), + BinaryData.fromObject(parameters), new RequestOptions().setContext(context)); + + return transformBinaryDataResponse(roleDefinitionResponse, + binaryData -> roleDefinitionToKeyVaultRoleDefinition(binaryData.toObject(RoleDefinition.class))); + } catch (HttpResponseException e) { + throw LOGGER.logExceptionAsError(toKeyVaultAdministrationException(e)); } catch (RuntimeException e) { throw LOGGER.logExceptionAsError(e); } @@ -580,14 +528,17 @@ public KeyVaultRoleDefinition getRoleDefinition(KeyVaultRoleScope roleScope, Str @ServiceMethod(returns = ReturnType.SINGLE) public Response getRoleDefinitionWithResponse(KeyVaultRoleScope roleScope, String roleDefinitionName, Context context) { + validateRoleDefinitionParameters(roleScope, roleDefinitionName); + try { - context = enableSyncRestProxy(context); - Response roleDefinitionResponse = clientImpl.getRoleDefinitions() - .getWithResponse(vaultUrl, roleScope.toString(), roleDefinitionName, context); - return KeyVaultAdministrationUtil.transformRoleDefinitionResponse(roleDefinitionResponse); - } catch (KeyVaultErrorException e) { - throw LOGGER.logExceptionAsError(KeyVaultAdministrationUtils.toKeyVaultAdministrationException(e)); + Response roleDefinitionResponse = implClient.getRoleDefinitions() + .getWithResponse(roleScope.toString(), roleDefinitionName, new RequestOptions().setContext(context)); + + return transformBinaryDataResponse(roleDefinitionResponse, + binaryData -> roleDefinitionToKeyVaultRoleDefinition(binaryData.toObject(RoleDefinition.class))); + } catch (HttpResponseException e) { + throw LOGGER.logExceptionAsError(toKeyVaultAdministrationException(e)); } catch (RuntimeException e) { throw LOGGER.logExceptionAsError(e); } @@ -652,16 +603,16 @@ public void deleteRoleDefinition(KeyVaultRoleScope roleScope, String roleDefinit @ServiceMethod(returns = ReturnType.SINGLE) public Response deleteRoleDefinitionWithResponse(KeyVaultRoleScope roleScope, String roleDefinitionName, Context context) { + validateRoleDefinitionParameters(roleScope, roleDefinitionName); + try { - context = enableSyncRestProxy(context); - Response roleDefinitionResponse = clientImpl.getRoleDefinitions() - .deleteWithResponse(vaultUrl, roleScope.toString(), roleDefinitionName, context); - return new SimpleResponse<>(roleDefinitionResponse, null); + Response roleDefinitionResponse = implClient.getRoleDefinitions() + .deleteWithResponse(roleScope.toString(), roleDefinitionName, new RequestOptions().setContext(context)); - } catch (KeyVaultErrorException e) { - KeyVaultAdministrationException mappedException - = KeyVaultAdministrationUtils.toKeyVaultAdministrationException(e); + return new SimpleResponse<>(roleDefinitionResponse, null); + } catch (HttpResponseException e) { + KeyVaultAdministrationException mappedException = toKeyVaultAdministrationException(e); return swallowExceptionForStatusCodeSync(404, mappedException, LOGGER); } catch (RuntimeException e) { throw LOGGER.logExceptionAsError(e); @@ -726,59 +677,15 @@ public PagedIterable listRoleAssignments(KeyVaultRoleSco */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable listRoleAssignments(KeyVaultRoleScope roleScope, Context context) { - final Context contextToUse = enableSyncRestProxy(context); - return new PagedIterable<>(() -> listRoleAssignmentsFirstPage(vaultUrl, roleScope, contextToUse), - continuationToken -> listRoleAssignmentsNextPage(continuationToken, context)); - } - - /** - * Lists all {@link KeyVaultRoleAssignment role assignments} in the first page that are applicable at the given - * {@link KeyVaultRoleScope role scope} and above. - * - * @param vaultUrl The URL for the Key Vault this client is associated with. - * @param roleScope The {@link KeyVaultRoleScope role scope} of the {@link KeyVaultRoleAssignment role assignment}. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link Mono} containing a {@link PagedResponse} of {@link KeyVaultRoleAssignment role assignments} - * in the given {@link KeyVaultRoleScope role scope} from the first page of results. - * - * @throws KeyVaultAdministrationException If the given {@code vaultUrl} or {@code roleScope} are invalid. - * @throws NullPointerException If the {@link KeyVaultRoleScope role scope} is {@code null}. - */ - PagedResponse listRoleAssignmentsFirstPage(String vaultUrl, KeyVaultRoleScope roleScope, - Context context) { - Objects.requireNonNull(roleScope, String.format(KeyVaultErrorCodeStrings.PARAMETER_REQUIRED, "'roleScope'")); - try { - PagedResponse roleAssignmentPagedResponse - = clientImpl.getRoleAssignments().listForScopeSinglePage(vaultUrl, roleScope.toString(), null, context); - return KeyVaultAdministrationUtil.transformRoleAssignmentsPagedResponse(roleAssignmentPagedResponse); - } catch (KeyVaultErrorException e) { - throw LOGGER.logExceptionAsError(KeyVaultAdministrationUtils.toKeyVaultAdministrationException(e)); - } catch (RuntimeException e) { - throw LOGGER.logExceptionAsError(e); - } - } + Objects.requireNonNull(roleScope, String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'roleScope'")); - /** - * Lists all {@link KeyVaultRoleAssignment role assignments} given by the {@code nextPageLink} that was - * retrieved from a call to {@link KeyVaultAccessControlClient#listRoleAssignments(KeyVaultRoleScope)}. - * - * @param continuationToken The {@link PagedResponse#getContinuationToken() continuationToken} from a previous, - * successful call to one of the {@code listKeyVaultRoleAssignments} operations. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * - * @return A {@link Mono} containing a {@link PagedResponse} of {@link KeyVaultRoleAssignment role assignments} - * for the given {@link KeyVaultRoleScope role scope} from the first page of results. - * - * @throws KeyVaultAdministrationException If the given {@code continuationToken} is invalid. - */ - PagedResponse listRoleAssignmentsNextPage(String continuationToken, Context context) { try { - PagedResponse roleAssignmentPagedResponse - = clientImpl.getRoleAssignments().listForScopeNextSinglePage(continuationToken, vaultUrl, context); - return KeyVaultAdministrationUtil.transformRoleAssignmentsPagedResponse(roleAssignmentPagedResponse); - } catch (KeyVaultErrorException e) { - throw LOGGER.logExceptionAsError(KeyVaultAdministrationUtils.toKeyVaultAdministrationException(e)); + return implClient.getRoleAssignments() + .listForScope(roleScope.toString(), new RequestOptions().setContext(context)) + .mapPage( + binaryData -> roleAssignmentToKeyVaultRoleAssignment(binaryData.toObject(RoleAssignment.class))); + } catch (HttpResponseException e) { + throw LOGGER.logExceptionAsError(toKeyVaultAdministrationException(e)); } catch (RuntimeException e) { throw LOGGER.logExceptionAsError(e); } @@ -818,6 +725,7 @@ PagedResponse listRoleAssignmentsNextPage(String continu @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultRoleAssignment createRoleAssignment(KeyVaultRoleScope roleScope, String roleDefinitionId, String principalId) { + return createRoleAssignmentWithResponse(roleScope, roleDefinitionId, principalId, UUID.randomUUID().toString(), Context.NONE).getValue(); } @@ -859,6 +767,7 @@ public KeyVaultRoleAssignment createRoleAssignment(KeyVaultRoleScope roleScope, @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultRoleAssignment createRoleAssignment(KeyVaultRoleScope roleScope, String roleDefinitionId, String principalId, String roleAssignmentName) { + return createRoleAssignmentWithResponse(roleScope, roleDefinitionId, principalId, roleAssignmentName, Context.NONE).getValue(); } @@ -906,15 +815,19 @@ public KeyVaultRoleAssignment createRoleAssignment(KeyVaultRoleScope roleScope, @ServiceMethod(returns = ReturnType.SINGLE) public Response createRoleAssignmentWithResponse(KeyVaultRoleScope roleScope, String roleDefinitionId, String principalId, String roleAssignmentName, Context context) { + RoleAssignmentCreateParameters parameters = validateAndGetRoleAssignmentCreateParameters(roleScope, roleDefinitionId, principalId, roleAssignmentName); - context = enableSyncRestProxy(context); + try { - Response roleAssignmentResponse = clientImpl.getRoleAssignments() - .createWithResponse(vaultUrl, roleScope.toString(), roleAssignmentName, parameters, context); - return KeyVaultAdministrationUtil.transformRoleAssignmentResponse(roleAssignmentResponse); - } catch (KeyVaultErrorException e) { - throw LOGGER.logExceptionAsError(KeyVaultAdministrationUtils.toKeyVaultAdministrationException(e)); + Response roleAssignmentResponse = implClient.getRoleAssignments() + .createWithResponse(roleScope.toString(), roleAssignmentName, BinaryData.fromObject(parameters), + new RequestOptions().setContext(context)); + + return transformBinaryDataResponse(roleAssignmentResponse, + binaryData -> roleAssignmentToKeyVaultRoleAssignment(binaryData.toObject(RoleAssignment.class))); + } catch (HttpResponseException e) { + throw LOGGER.logExceptionAsError(toKeyVaultAdministrationException(e)); } catch (RuntimeException e) { throw LOGGER.logExceptionAsError(e); } @@ -983,14 +896,17 @@ public KeyVaultRoleAssignment getRoleAssignment(KeyVaultRoleScope roleScope, Str @ServiceMethod(returns = ReturnType.SINGLE) public Response getRoleAssignmentWithResponse(KeyVaultRoleScope roleScope, String roleAssignmentName, Context context) { + validateRoleAssignmentParameters(roleScope, roleAssignmentName); + try { - context = enableSyncRestProxy(context); - Response roleAssignmentResponse = clientImpl.getRoleAssignments() - .getWithResponse(vaultUrl, roleScope.toString(), roleAssignmentName, context); - return KeyVaultAdministrationUtil.transformRoleAssignmentResponse(roleAssignmentResponse); - } catch (KeyVaultErrorException e) { - throw LOGGER.logExceptionAsError(KeyVaultAdministrationUtils.toKeyVaultAdministrationException(e)); + Response roleAssignmentResponse = implClient.getRoleAssignments() + .getWithResponse(roleScope.toString(), roleAssignmentName, new RequestOptions().setContext(context)); + + return transformBinaryDataResponse(roleAssignmentResponse, + binaryData -> roleAssignmentToKeyVaultRoleAssignment(binaryData.toObject(RoleAssignment.class))); + } catch (HttpResponseException e) { + throw LOGGER.logExceptionAsError(toKeyVaultAdministrationException(e)); } catch (RuntimeException e) { throw LOGGER.logExceptionAsError(e); } @@ -1054,15 +970,16 @@ public void deleteRoleAssignment(KeyVaultRoleScope roleScope, String roleAssignm @ServiceMethod(returns = ReturnType.SINGLE) public Response deleteRoleAssignmentWithResponse(KeyVaultRoleScope roleScope, String roleAssignmentName, Context context) { + validateRoleAssignmentParameters(roleScope, roleAssignmentName); + try { - context = enableSyncRestProxy(context); - Response roleAssignmentResponse = clientImpl.getRoleAssignments() - .deleteWithResponse(vaultUrl, roleScope.toString(), roleAssignmentName, context); + Response roleAssignmentResponse = implClient.getRoleAssignments() + .deleteWithResponse(roleScope.toString(), roleAssignmentName, new RequestOptions().setContext(context)); + return new SimpleResponse<>(roleAssignmentResponse, null); - } catch (KeyVaultErrorException e) { - KeyVaultAdministrationException mappedException - = KeyVaultAdministrationUtils.toKeyVaultAdministrationException(e); + } catch (HttpResponseException e) { + KeyVaultAdministrationException mappedException = toKeyVaultAdministrationException(e); return swallowExceptionForStatusCodeSync(404, mappedException, LOGGER); } catch (RuntimeException e) { throw LOGGER.logExceptionAsError(e); diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAccessControlClientBuilder.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAccessControlClientBuilder.java index af7a45d1f967..679067a67aaf 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAccessControlClientBuilder.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAccessControlClientBuilder.java @@ -34,7 +34,6 @@ import com.azure.core.util.tracing.Tracer; import com.azure.core.util.tracing.TracerProvider; import com.azure.security.keyvault.administration.implementation.KeyVaultCredentialPolicy; -import com.azure.security.keyvault.administration.implementation.KeyVaultErrorCodeStrings; import java.net.MalformedURLException; import java.net.URL; @@ -95,9 +94,10 @@ public final class KeyVaultAccessControlClientBuilder implements TokenCredentialTrait, HttpTrait, ConfigurationTrait { + // This is the properties file name. private static final ClientLogger LOGGER = new ClientLogger(KeyVaultAccessControlClientBuilder.class); - private static final String AZURE_KEY_VAULT_RBAC = "azure-key-vault-administration.properties"; + private static final String AZURE_KEY_VAULT_RBAC = "azure-security-keyvault-administration.properties"; private static final String SDK_NAME = "name"; private static final String SDK_VERSION = "version"; private static final ClientOptions DEFAULT_CLIENT_OPTIONS = new ClientOptions(); @@ -150,11 +150,14 @@ public KeyVaultAccessControlClientBuilder() { public KeyVaultAccessControlClient buildClient() { Configuration buildConfiguration = validateEndpointAndGetConfiguration(); serviceVersion = getServiceVersion(); + if (pipeline != null) { return new KeyVaultAccessControlClient(vaultUrl, pipeline, serviceVersion); } - HttpPipeline buildPipeline = getPipeline(buildConfiguration, serviceVersion); - return new KeyVaultAccessControlClient(vaultUrl, buildPipeline, serviceVersion); + + HttpPipeline builtPipeline = getPipeline(buildConfiguration, serviceVersion); + + return new KeyVaultAccessControlClient(vaultUrl, builtPipeline, serviceVersion); } /** @@ -174,23 +177,26 @@ public KeyVaultAccessControlClient buildClient() { public KeyVaultAccessControlAsyncClient buildAsyncClient() { Configuration buildConfiguration = validateEndpointAndGetConfiguration(); serviceVersion = getServiceVersion(); + if (pipeline != null) { return new KeyVaultAccessControlAsyncClient(vaultUrl, pipeline, serviceVersion); } - HttpPipeline buildPipeline = getPipeline(buildConfiguration, serviceVersion); - return new KeyVaultAccessControlAsyncClient(vaultUrl, buildPipeline, serviceVersion); + + HttpPipeline builtPipeline = getPipeline(buildConfiguration, serviceVersion); + + return new KeyVaultAccessControlAsyncClient(vaultUrl, builtPipeline, serviceVersion); } private Configuration validateEndpointAndGetConfiguration() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; - URL buildEndpoint = getBuildEndpoint(buildConfiguration); if (buildEndpoint == null) { throw LOGGER - .logExceptionAsError(new IllegalStateException(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED)); + .logExceptionAsError(new IllegalStateException(KeyVaultAdministrationUtil.VAULT_END_POINT_REQUIRED)); } + return buildConfiguration; } @@ -438,6 +444,7 @@ public KeyVaultAccessControlClientBuilder retryPolicy(RetryPolicy retryPolicy) { @Override public KeyVaultAccessControlClientBuilder retryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; + return this; } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAdministrationUtil.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAdministrationUtil.java index e2e4d74c994d..3677431898f1 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAdministrationUtil.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultAdministrationUtil.java @@ -8,13 +8,14 @@ import com.azure.core.http.HttpRequest; import com.azure.core.http.HttpResponse; import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.RequestOptions; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.SimpleResponse; -import com.azure.core.util.Context; +import com.azure.core.util.BinaryData; import com.azure.core.util.IterableStream; import com.azure.core.util.logging.ClientLogger; import com.azure.core.util.polling.LongRunningOperationStatus; -import com.azure.security.keyvault.administration.implementation.KeyVaultErrorCodeStrings; import com.azure.security.keyvault.administration.implementation.models.FullBackupOperation; import com.azure.security.keyvault.administration.implementation.models.Permission; import com.azure.security.keyvault.administration.implementation.models.RestoreOperation; @@ -45,9 +46,10 @@ import java.util.ArrayList; import java.util.List; import java.util.Objects; +import java.util.function.Function; import java.util.stream.Collectors; -import static com.azure.security.keyvault.administration.implementation.KeyVaultAdministrationUtils.createKeyVaultErrorFromError; +import static com.azure.security.keyvault.administration.implementation.KeyVaultAdministrationUtils.toKeyVaultAdministrationError; /** * Internal utility class for KeyVault Administration clients. @@ -55,6 +57,11 @@ class KeyVaultAdministrationUtil { private static final String HTTP_REST_PROXY_SYNC_PROXY_ENABLE = "com.azure.core.http.restproxy.syncproxy.enable"; + static final String VAULT_END_POINT_REQUIRED = "Azure Key Vault endpoint url is required."; + static final String PARAMETER_REQUIRED = "%s cannot be null."; + + public static final RequestOptions EMPTY_OPTIONS = new RequestOptions(); + /** * Deserializes a given {@link Response HTTP response} including headers to a given class. * @@ -86,22 +93,22 @@ static Mono> swallowExceptionFo */ static Response swallowExceptionForStatusCodeSync(int statusCode, E httpResponseException, ClientLogger logger) { + HttpResponse httpResponse = httpResponseException.getResponse(); if (httpResponse.getStatusCode() == statusCode) { return new SimpleResponse<>(httpResponse.getRequest(), httpResponse.getStatusCode(), httpResponse.getHeaders(), null); } + throw logger.logExceptionAsError(httpResponseException); } static RoleAssignmentCreateParameters validateAndGetRoleAssignmentCreateParameters(KeyVaultRoleScope roleScope, String roleDefinitionId, String principalId, String roleAssignmentName) { validateRoleAssignmentParameters(roleScope, roleAssignmentName); - Objects.requireNonNull(principalId, - String.format(KeyVaultErrorCodeStrings.PARAMETER_REQUIRED, "'principalId'")); - Objects.requireNonNull(roleDefinitionId, - String.format(KeyVaultErrorCodeStrings.PARAMETER_REQUIRED, "'roleDefinitionId'")); + Objects.requireNonNull(principalId, String.format(PARAMETER_REQUIRED, "'principalId'")); + Objects.requireNonNull(roleDefinitionId, String.format(PARAMETER_REQUIRED, "'roleDefinitionId'")); RoleAssignmentProperties roleAssignmentProperties = new RoleAssignmentProperties(roleDefinitionId, principalId); return new RoleAssignmentCreateParameters(roleAssignmentProperties); @@ -109,11 +116,10 @@ static RoleAssignmentCreateParameters validateAndGetRoleAssignmentCreateParamete static RoleDefinitionCreateParameters validateAndGetRoleDefinitionCreateParameters(SetRoleDefinitionOptions options) { - Objects.requireNonNull(options, String.format(KeyVaultErrorCodeStrings.PARAMETER_REQUIRED, "'options'")); - Objects.requireNonNull(options.getRoleScope(), - String.format(KeyVaultErrorCodeStrings.PARAMETER_REQUIRED, "'options.getRoleScope()'")); + Objects.requireNonNull(options, String.format(PARAMETER_REQUIRED, "'options'")); + Objects.requireNonNull(options.getRoleScope(), String.format(PARAMETER_REQUIRED, "'options.getRoleScope()'")); Objects.requireNonNull(options.getRoleDefinitionName(), - String.format(KeyVaultErrorCodeStrings.PARAMETER_REQUIRED, "'options.getRoleDefinitionName()'")); + String.format(PARAMETER_REQUIRED, "'options.getRoleDefinitionName()'")); List permissions = null; @@ -136,15 +142,13 @@ static RoleAssignmentCreateParameters validateAndGetRoleAssignmentCreateParamete } static void validateRoleAssignmentParameters(KeyVaultRoleScope roleScope, String roleAssignmentName) { - Objects.requireNonNull(roleScope, String.format(KeyVaultErrorCodeStrings.PARAMETER_REQUIRED, "'roleScope'")); - Objects.requireNonNull(roleAssignmentName, - String.format(KeyVaultErrorCodeStrings.PARAMETER_REQUIRED, "'roleAssignmentName'")); + Objects.requireNonNull(roleScope, String.format(PARAMETER_REQUIRED, "'roleScope'")); + Objects.requireNonNull(roleAssignmentName, String.format(PARAMETER_REQUIRED, "'roleAssignmentName'")); } static void validateRoleDefinitionParameters(KeyVaultRoleScope roleScope, String roleDefinitionName) { - Objects.requireNonNull(roleScope, String.format(KeyVaultErrorCodeStrings.PARAMETER_REQUIRED, "'roleScope'")); - Objects.requireNonNull(roleDefinitionName, - String.format(KeyVaultErrorCodeStrings.PARAMETER_REQUIRED, "'roleDefinitionName'")); + Objects.requireNonNull(roleScope, String.format(PARAMETER_REQUIRED, "'roleScope'")); + Objects.requireNonNull(roleDefinitionName, String.format(PARAMETER_REQUIRED, "'roleDefinitionName'")); } @SuppressWarnings("BoundedWildcard") @@ -160,16 +164,39 @@ static void validateRoleDefinitionParameters(KeyVaultRoleScope roleScope, String return new TransformedPagedResponse<>(keyVaultRoleDefinitions, pagedResponse); } - static Response transformRoleDefinitionResponse(Response response) { - KeyVaultRoleDefinition keyVaultRoleDefinition = roleDefinitionToKeyVaultRoleDefinition(response.getValue()); + static Response transformBinaryDataResponse(Response response, Class clazz) { + if (response == null) { + return null; + } + + BinaryData binaryData = response.getValue(); + + if (binaryData == null) { + return new SimpleResponse<>(response, null); + } + + return new SimpleResponse<>(response, BinaryData.fromObject(response.getValue()).toObject(clazz)); + } + + static Response transformBinaryDataResponse(Response response, + Function transformationFunction) { + if (response == null) { + return null; + } + + BinaryData binaryData = response.getValue(); + + if (binaryData == null) { + return new SimpleResponse<>(response, null); + } - return new TransformedResponse<>(keyVaultRoleDefinition, response); + return new SimpleResponse<>(response, transformationFunction.apply(binaryData)); } static KeyVaultRoleDefinition roleDefinitionToKeyVaultRoleDefinition(RoleDefinition roleDefinition) { List keyVaultPermissions = new ArrayList<>(); - for (Permission permission : roleDefinition.getPermissions()) { + for (Permission permission : roleDefinition.getProperties().getPermissions()) { keyVaultPermissions.add(new KeyVaultPermission(permission.getActions(), permission.getNotActions(), permission.getDataActions() .stream() @@ -182,33 +209,16 @@ static KeyVaultRoleDefinition roleDefinitionToKeyVaultRoleDefinition(RoleDefinit } return new KeyVaultRoleDefinition(roleDefinition.getId(), roleDefinition.getName(), - KeyVaultRoleDefinitionType.fromString(roleDefinition.getType().toString()), roleDefinition.getRoleName(), - roleDefinition.getDescription(), KeyVaultRoleType.fromString(roleDefinition.getRoleType().toString()), - keyVaultPermissions, - roleDefinition.getAssignableScopes() + KeyVaultRoleDefinitionType.fromString(roleDefinition.getType().toString()), + roleDefinition.getProperties().getRoleName(), roleDefinition.getProperties().getDescription(), + KeyVaultRoleType.fromString(roleDefinition.getProperties().getRoleType().toString()), keyVaultPermissions, + roleDefinition.getProperties() + .getAssignableScopes() .stream() .map(roleScope -> KeyVaultRoleScope.fromString(roleScope.toString())) .collect(Collectors.toList())); } - static PagedResponse - transformRoleAssignmentsPagedResponse(PagedResponse pagedResponse) { - - List keyVaultRoleAssignments = new ArrayList<>(); - - for (RoleAssignment roleAssignment : pagedResponse.getValue()) { - keyVaultRoleAssignments.add(roleAssignmentToKeyVaultRoleAssignment(roleAssignment)); - } - - return new TransformedPagedResponse<>(keyVaultRoleAssignments, pagedResponse); - } - - static Response transformRoleAssignmentResponse(Response response) { - KeyVaultRoleAssignment keyVaultRoleAssignment = roleAssignmentToKeyVaultRoleAssignment(response.getValue()); - - return new TransformedResponse<>(keyVaultRoleAssignment, response); - } - static KeyVaultRoleAssignment roleAssignmentToKeyVaultRoleAssignment(RoleAssignment roleAssignment) { RoleAssignmentPropertiesWithScope propertiesWithScope = roleAssignment.getProperties(); @@ -262,36 +272,6 @@ public List getValue() { } } - private static final class TransformedResponse implements Response { - private final T output; - private final Response response; - - TransformedResponse(T output, Response response) { - this.output = output; - this.response = response; - } - - @Override - public int getStatusCode() { - return response.getStatusCode(); - } - - @Override - public HttpHeaders getHeaders() { - return response.getHeaders(); - } - - @Override - public HttpRequest getRequest() { - return response.getRequest(); - } - - @Override - public T getValue() { - return output; - } - } - static LongRunningOperationStatus toLongRunningOperationStatus(String operationStatus) { switch (operationStatus) { case "inprogress": @@ -313,30 +293,37 @@ static KeyVaultLongRunningOperation transformToLongRunningOperation(O operat if (operation instanceof RestoreOperation) { RestoreOperation restoreOperation = (RestoreOperation) operation; - return new KeyVaultRestoreOperation(restoreOperation.getStatus(), restoreOperation.getStatusDetails(), - createKeyVaultErrorFromError(restoreOperation.getError()), restoreOperation.getJobId(), - restoreOperation.getStartTime(), restoreOperation.getEndTime()); + return new KeyVaultRestoreOperation(restoreOperation.getStatus().getValue(), + restoreOperation.getStatusDetails(), toKeyVaultAdministrationError(restoreOperation.getError()), + restoreOperation.getJobId(), restoreOperation.getStartTime(), restoreOperation.getEndTime()); } else if (operation instanceof SelectiveKeyRestoreOperation) { SelectiveKeyRestoreOperation selectiveKeyRestoreOperation = (SelectiveKeyRestoreOperation) operation; - return new KeyVaultSelectiveKeyRestoreOperation(selectiveKeyRestoreOperation.getStatus(), + return new KeyVaultSelectiveKeyRestoreOperation(selectiveKeyRestoreOperation.getStatus().getValue(), selectiveKeyRestoreOperation.getStatusDetails(), - createKeyVaultErrorFromError(selectiveKeyRestoreOperation.getError()), + toKeyVaultAdministrationError(selectiveKeyRestoreOperation.getError()), selectiveKeyRestoreOperation.getJobId(), selectiveKeyRestoreOperation.getStartTime(), selectiveKeyRestoreOperation.getEndTime()); } else if (operation instanceof FullBackupOperation) { FullBackupOperation fullBackupOperation = (FullBackupOperation) operation; - return new KeyVaultBackupOperation(fullBackupOperation.getStatus(), fullBackupOperation.getStatusDetails(), - createKeyVaultErrorFromError(fullBackupOperation.getError()), fullBackupOperation.getJobId(), - fullBackupOperation.getStartTime(), fullBackupOperation.getEndTime(), + return new KeyVaultBackupOperation(fullBackupOperation.getStatus().getValue(), + fullBackupOperation.getStatusDetails(), toKeyVaultAdministrationError(fullBackupOperation.getError()), + fullBackupOperation.getJobId(), fullBackupOperation.getStartTime(), fullBackupOperation.getEndTime(), fullBackupOperation.getAzureStorageBlobContainerUri()); } else { throw new UnsupportedOperationException(); } } - static Context enableSyncRestProxy(Context context) { - return context.addData(HTTP_REST_PROXY_SYNC_PROXY_ENABLE, true); + static PagedResponse mapPagedResponse(PagedResponse page, Function itemMapper) { + List mappedValues = new ArrayList<>(page.getValue().size()); + + for (T item : page.getValue()) { + mappedValues.add(itemMapper.apply(item)); + } + + return new PagedResponseBase<>(page.getRequest(), page.getStatusCode(), page.getHeaders(), mappedValues, + page.getContinuationToken(), null); } } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultBackupAsyncClient.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultBackupAsyncClient.java index 3b1b8201f8e1..eda835557883 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultBackupAsyncClient.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultBackupAsyncClient.java @@ -8,25 +8,27 @@ import com.azure.core.annotation.ServiceMethod; import com.azure.core.exception.HttpResponseException; import com.azure.core.http.HttpPipeline; +import com.azure.core.http.rest.RequestOptions; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.BinaryData; import com.azure.core.util.Context; import com.azure.core.util.logging.ClientLogger; import com.azure.core.util.polling.LongRunningOperationStatus; import com.azure.core.util.polling.PollResponse; import com.azure.core.util.polling.PollerFlux; import com.azure.core.util.polling.PollingContext; -import com.azure.security.keyvault.administration.implementation.KeyVaultBackupClientImpl; -import com.azure.security.keyvault.administration.implementation.KeyVaultErrorCodeStrings; +import com.azure.security.keyvault.administration.implementation.KeyVaultAdministrationClientImpl; +import com.azure.security.keyvault.administration.implementation.models.FullBackupOperation; import com.azure.security.keyvault.administration.implementation.models.PreBackupOperationParameters; import com.azure.security.keyvault.administration.implementation.models.PreRestoreOperationParameters; import com.azure.security.keyvault.administration.implementation.models.RestoreOperation; import com.azure.security.keyvault.administration.implementation.models.RestoreOperationParameters; import com.azure.security.keyvault.administration.implementation.models.SASTokenParameter; +import com.azure.security.keyvault.administration.implementation.models.SelectiveKeyRestoreOperation; import com.azure.security.keyvault.administration.implementation.models.SelectiveKeyRestoreOperationParameters; import com.azure.security.keyvault.administration.models.KeyVaultAdministrationException; import com.azure.security.keyvault.administration.models.KeyVaultBackupOperation; -import com.azure.security.keyvault.administration.models.KeyVaultLongRunningOperation; import com.azure.security.keyvault.administration.models.KeyVaultRestoreOperation; import com.azure.security.keyvault.administration.models.KeyVaultRestoreResult; import com.azure.security.keyvault.administration.models.KeyVaultSelectiveKeyRestoreOperation; @@ -43,7 +45,6 @@ import static com.azure.core.util.FluxUtil.withContext; import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.toLongRunningOperationStatus; import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.transformToLongRunningOperation; -import static com.azure.security.keyvault.administration.implementation.KeyVaultAdministrationUtils.createKeyVaultErrorFromError; /** * The {@link KeyVaultBackupAsyncClient} provides asynchronous methods to perform full a backup and restore of a key @@ -112,11 +113,11 @@ *
          * *

          Restore a Collection of Keys

          - * The {@link KeyVaultBackupClient} can be used to restore an entire collection of keys from a backup. + * The {@link KeyVaultBackupAsyncClient} can be used to restore an entire collection of keys from a backup. * *

          Code Sample:

          *

          The following code sample demonstrates how to asynchronously restore an entire collection of keys from a backup, - * using the {@link KeyVaultBackupClient#beginRestore(String, String)} API.

          + * using the {@link KeyVaultBackupAsyncClient#beginRestore(String, String)} API.

          * * *
          @@ -185,18 +186,13 @@ public final class KeyVaultBackupAsyncClient {
               /**
                * The underlying AutoRest client used to interact with the Key Vault service.
                */
          -    private final KeyVaultBackupClientImpl clientImpl;
          +    private final KeyVaultAdministrationClientImpl clientImpl;
           
               /**
                * The Key Vault URL this client is associated to.
                */
               private final String vaultUrl;
           
          -    /**
          -     * The Key Vault Administration Service version to use with this client.
          -     */
          -    private final String serviceVersion;
          -
               /**
                * The {@link HttpPipeline} powering this client.
                */
          @@ -211,13 +207,12 @@ Duration getDefaultPollingInterval() {
                */
               KeyVaultBackupAsyncClient(URL vaultUrl, HttpPipeline httpPipeline,
                   KeyVaultAdministrationServiceVersion serviceVersion) {
          -        Objects.requireNonNull(vaultUrl, KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED);
          +        Objects.requireNonNull(vaultUrl, KeyVaultAdministrationUtil.VAULT_END_POINT_REQUIRED);
           
                   this.vaultUrl = vaultUrl.toString();
          -        this.serviceVersion = serviceVersion.getVersion();
                   this.pipeline = httpPipeline;
           
          -        clientImpl = new KeyVaultBackupClientImpl(httpPipeline, this.serviceVersion);
          +        clientImpl = new KeyVaultAdministrationClientImpl(httpPipeline, this.vaultUrl, serviceVersion);
               }
           
               /**
          @@ -275,7 +270,7 @@ HttpPipeline getHttpPipeline() {
               public PollerFlux beginBackup(String blobStorageUrl, String sasToken) {
                   if (blobStorageUrl == null) {
                       throw LOGGER.logExceptionAsError(new NullPointerException(
          -                String.format(KeyVaultErrorCodeStrings.PARAMETER_REQUIRED, "'blobStorageUrl'")));
          +                String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'blobStorageUrl'")));
                   }
           
                   return new PollerFlux<>(getDefaultPollingInterval(), backupActivationOperation(blobStorageUrl, sasToken),
          @@ -299,18 +294,18 @@ public PollerFlux beginBackup(String blobStorag
                */
               Mono> backupWithResponse(String blobStorageUrl, String sasToken,
                   Context context) {
          +
                   SASTokenParameter sasTokenParameter
                       = new SASTokenParameter(blobStorageUrl).setToken(sasToken).setUseManagedIdentity(sasToken == null);
           
                   try {
          -            return clientImpl.fullBackupWithResponseAsync(vaultUrl, sasTokenParameter, context)
          -                .doOnRequest(ignored -> LOGGER.verbose("Backing up at URL - {}", blobStorageUrl))
          -                .doOnSuccess(response -> LOGGER.verbose("Backed up at URL - {}",
          -                    response.getValue().getAzureStorageBlobContainerUri()))
          -                .doOnError(error -> LOGGER.warning("Failed to backup at URL - {}", blobStorageUrl, error))
          +            return clientImpl
          +                .fullBackupWithResponseAsync(BinaryData.fromObject(sasTokenParameter),
          +                    new RequestOptions().setContext(context))
                           .map(backupOperationResponse -> new SimpleResponse<>(backupOperationResponse.getRequest(),
                               backupOperationResponse.getStatusCode(), backupOperationResponse.getHeaders(),
          -                    (KeyVaultBackupOperation) transformToLongRunningOperation(backupOperationResponse.getValue())));
          +                    (KeyVaultBackupOperation) transformToLongRunningOperation(
          +                        backupOperationResponse.getValue().toObject(FullBackupOperation.class))));
                   } catch (RuntimeException e) {
                       return monoError(LOGGER, e);
                   }
          @@ -331,6 +326,7 @@ Mono> backupWithResponse(String blobStorageUrl
           
               private Function, Mono>>
                   backupPollOperation() {
          +
                   return (pollingContext) -> {
                       try {
                           PollResponse pollResponse = pollingContext.getLatestResponse();
          @@ -351,10 +347,12 @@ Mono> backupWithResponse(String blobStorageUrl
           
                           final String jobId = keyVaultBackupOperation.getOperationId();
           
          -                return withContext(context -> clientImpl.fullBackupStatusWithResponseAsync(vaultUrl, jobId, context))
          -                    .map(response -> new SimpleResponse<>(response,
          -                        (KeyVaultBackupOperation) transformToLongRunningOperation(response.getValue())))
          -                    .flatMap(KeyVaultBackupAsyncClient::processBackupOperationResponse);
          +                return withContext(context -> clientImpl.fullBackupStatusWithResponseAsync(jobId,
          +                    new RequestOptions().setContext(context)))
          +                        .map(response -> new SimpleResponse<>(response,
          +                            (KeyVaultBackupOperation) transformToLongRunningOperation(
          +                                response.getValue().toObject(FullBackupOperation.class))))
          +                        .flatMap(KeyVaultBackupAsyncClient::processBackupOperationResponse);
                       } catch (HttpResponseException e) {
                           //noinspection ThrowableNotThrown
                           LOGGER.logExceptionAsError(e);
          @@ -429,7 +427,7 @@ private Function, Mono> backupFe
               public PollerFlux beginPreBackup(String blobStorageUrl, String sasToken) {
                   if (blobStorageUrl == null) {
                       throw LOGGER.logExceptionAsError(new NullPointerException(
          -                String.format(KeyVaultErrorCodeStrings.PARAMETER_REQUIRED, "'blobStorageUrl'")));
          +                String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'blobStorageUrl'")));
                   }
           
                   return new PollerFlux<>(getDefaultPollingInterval(), preBackupActivationOperation(blobStorageUrl, sasToken),
          @@ -454,20 +452,20 @@ public PollerFlux beginPreBackup(String blobSto
                */
               Mono> preBackupWithResponse(String blobStorageUrl, String sasToken,
                   Context context) {
          +
                   PreBackupOperationParameters preBackupOperationParameters
                       = new PreBackupOperationParameters().setStorageResourceUri(blobStorageUrl)
                           .setToken(sasToken)
                           .setUseManagedIdentity(sasToken == null);
           
                   try {
          -            return clientImpl.preFullBackupWithResponseAsync(vaultUrl, preBackupOperationParameters, context)
          -                .doOnRequest(ignored -> LOGGER.verbose("Backing up at URL - {}", blobStorageUrl))
          -                .doOnSuccess(response -> LOGGER.verbose("Backed up at URL - {}",
          -                    response.getValue().getAzureStorageBlobContainerUri()))
          -                .doOnError(error -> LOGGER.warning("Failed to backup at URL - {}", blobStorageUrl, error))
          +            return clientImpl
          +                .preFullBackupWithResponseAsync(BinaryData.fromObject(preBackupOperationParameters),
          +                    new RequestOptions().setContext(context))
                           .map(backupOperationResponse -> new SimpleResponse<>(backupOperationResponse.getRequest(),
                               backupOperationResponse.getStatusCode(), backupOperationResponse.getHeaders(),
          -                    (KeyVaultBackupOperation) transformToLongRunningOperation(backupOperationResponse.getValue())));
          +                    (KeyVaultBackupOperation) transformToLongRunningOperation(
          +                        backupOperationResponse.getValue().toObject(FullBackupOperation.class))));
                   } catch (RuntimeException e) {
                       return monoError(LOGGER, e);
                   }
          @@ -475,6 +473,7 @@ Mono> preBackupWithResponse(String blobStorage
           
               private Function, Mono>
                   preBackupActivationOperation(String blobStorageUrl, String sasToken) {
          +
                   return (pollingContext) -> {
                       try {
                           return withContext(context -> preBackupWithResponse(blobStorageUrl, sasToken, context))
          @@ -523,7 +522,7 @@ Mono> preBackupWithResponse(String blobStorage
               public PollerFlux beginRestore(String folderUrl, String sasToken) {
                   if (folderUrl == null) {
                       throw LOGGER.logExceptionAsError(
          -                new NullPointerException(String.format(KeyVaultErrorCodeStrings.PARAMETER_REQUIRED, "'folderUrl'")));
          +                new NullPointerException(String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'folderUrl'")));
                   }
           
                   return new PollerFlux<>(getDefaultPollingInterval(), restoreActivationOperation(folderUrl, sasToken),
          @@ -560,13 +559,13 @@ Mono> restoreWithResponse(String folderUrl, S
                       = new RestoreOperationParameters(sasTokenParameter, folderName);
           
                   try {
          -            return clientImpl.fullRestoreOperationWithResponseAsync(vaultUrl, restoreOperationParameters, context)
          -                .doOnRequest(ignored -> LOGGER.verbose("Restoring from location - {}", folderUrl))
          -                .doOnSuccess(response -> LOGGER.verbose("Restored from location - {}", folderUrl))
          -                .doOnError(error -> LOGGER.warning("Failed to restore from location - {}", folderUrl, error))
          +            return clientImpl
          +                .fullRestoreOperationWithResponseAsync(BinaryData.fromObject(restoreOperationParameters),
          +                    new RequestOptions().setContext(context))
                           .map(restoreOperationResponse -> new SimpleResponse<>(restoreOperationResponse.getRequest(),
                               restoreOperationResponse.getStatusCode(), restoreOperationResponse.getHeaders(),
          -                    (KeyVaultRestoreOperation) transformToLongRunningOperation(restoreOperationResponse.getValue())));
          +                    (KeyVaultRestoreOperation) transformToLongRunningOperation(
          +                        restoreOperationResponse.getValue().toObject(RestoreOperation.class))));
                   } catch (RuntimeException e) {
                       return monoError(LOGGER, e);
                   }
          @@ -574,6 +573,7 @@ Mono> restoreWithResponse(String folderUrl, S
           
               private Function, Mono>
                   restoreActivationOperation(String folderUrl, String sasToken) {
          +
                   return (pollingContext) -> {
                       try {
                           return withContext(context -> restoreWithResponse(folderUrl, sasToken, context))
          @@ -586,6 +586,7 @@ Mono> restoreWithResponse(String folderUrl, S
           
               private Function, Mono>>
                   restorePollOperation() {
          +
                   return (pollingContext) -> {
                       try {
                           PollResponse pollResponse = pollingContext.getLatestResponse();
          @@ -607,10 +608,12 @@ Mono> restoreWithResponse(String folderUrl, S
           
                           final String jobId = keyVaultRestoreOperation.getOperationId();
           
          -                return withContext(context -> clientImpl.restoreStatusWithResponseAsync(vaultUrl, jobId, context))
          +                return withContext(context -> clientImpl
          +                    .restoreStatusWithResponseAsync(jobId, new RequestOptions().setContext(context))
                               .map(response -> new SimpleResponse<>(response,
          -                        (KeyVaultRestoreOperation) transformToLongRunningOperation(response.getValue())))
          -                    .flatMap(KeyVaultBackupAsyncClient::processRestoreOperationResponse);
          +                        (KeyVaultRestoreOperation) transformToLongRunningOperation(
          +                            response.getValue().toObject(RestoreOperation.class))))
          +                    .flatMap(KeyVaultBackupAsyncClient::processRestoreOperationResponse));
                       } catch (HttpResponseException e) {
                           //noinspection ThrowableNotThrown
                           LOGGER.logExceptionAsError(e);
          @@ -669,9 +672,10 @@ Mono> restoreWithResponse(String folderUrl, S
               @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
               public PollerFlux beginPreRestore(String folderUrl,
                   String sasToken) {
          +
                   if (folderUrl == null) {
                       throw LOGGER.logExceptionAsError(
          -                new NullPointerException(String.format(KeyVaultErrorCodeStrings.PARAMETER_REQUIRED, "'folderUrl'")));
          +                new NullPointerException(String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'folderUrl'")));
                   }
           
                   return new PollerFlux<>(getDefaultPollingInterval(), preRestoreActivationOperation(folderUrl, sasToken),
          @@ -699,6 +703,7 @@ public PollerFlux beginPreResto
                */
               Mono> preRestoreWithResponse(String folderUrl, String sasToken,
                   Context context) {
          +
                   String[] segments = folderUrl.split("/");
                   String folderName = segments[segments.length - 1];
                   String containerUrl = folderUrl.substring(0, folderUrl.length() - folderName.length());
          @@ -711,13 +716,13 @@ Mono> preRestoreWithResponse(String folderUrl
                           .setSasTokenParameters(sasTokenParameter);
           
                   try {
          -            return clientImpl.preFullRestoreOperationWithResponseAsync(vaultUrl, preRestoreOperationParameters, context)
          -                .doOnRequest(ignored -> LOGGER.verbose("Restoring from location - {}", folderUrl))
          -                .doOnSuccess(response -> LOGGER.verbose("Restored from location - {}", folderUrl))
          -                .doOnError(error -> LOGGER.warning("Failed to restore from location - {}", folderUrl, error))
          +            return clientImpl
          +                .preFullRestoreOperationWithResponseAsync(BinaryData.fromObject(preRestoreOperationParameters),
          +                    new RequestOptions().setContext(context))
                           .map(restoreOperationResponse -> new SimpleResponse<>(restoreOperationResponse.getRequest(),
                               restoreOperationResponse.getStatusCode(), restoreOperationResponse.getHeaders(),
          -                    (KeyVaultRestoreOperation) transformToLongRunningOperation(restoreOperationResponse.getValue())));
          +                    (KeyVaultRestoreOperation) transformToLongRunningOperation(
          +                        restoreOperationResponse.getValue().toObject(RestoreOperation.class))));
                   } catch (RuntimeException e) {
                       return monoError(LOGGER, e);
                   }
          @@ -725,6 +730,7 @@ Mono> preRestoreWithResponse(String folderUrl
           
               private Function, Mono>
                   preRestoreActivationOperation(String folderUrl, String sasToken) {
          +
                   return (pollingContext) -> {
                       try {
                           return withContext(context -> preRestoreWithResponse(folderUrl, sasToken, context))
          @@ -776,14 +782,15 @@ Mono> preRestoreWithResponse(String folderUrl
               @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
               public PollerFlux
                   beginSelectiveKeyRestore(String keyName, String folderUrl, String sasToken) {
          +
                   if (keyName == null) {
                       throw LOGGER.logExceptionAsError(
          -                new NullPointerException(String.format(KeyVaultErrorCodeStrings.PARAMETER_REQUIRED, "'keyName'")));
          +                new NullPointerException(String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'keyName'")));
                   }
           
                   if (folderUrl == null) {
                       throw LOGGER.logExceptionAsError(
          -                new NullPointerException(String.format(KeyVaultErrorCodeStrings.PARAMETER_REQUIRED, "'folderUrl'")));
          +                new NullPointerException(String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'folderUrl'")));
                   }
           
                   return new PollerFlux<>(getDefaultPollingInterval(),
          @@ -810,6 +817,7 @@ Mono> preRestoreWithResponse(String folderUrl
                */
               Mono> selectiveKeyRestoreWithResponse(String keyName,
                   String folderUrl, String sasToken, Context context) {
          +
                   String[] segments = folderUrl.split("/");
                   String folderName = segments[segments.length - 1];
                   String containerUrl = folderUrl.substring(0, folderUrl.length() - folderName.length());
          @@ -820,17 +828,14 @@ Mono> selectiveKeyRestoreWithResp
                       = new SelectiveKeyRestoreOperationParameters(sasTokenParameter, folderName);
           
                   try {
          -            return clientImpl
          -                .selectiveKeyRestoreOperationWithResponseAsync(vaultUrl, keyName,
          -                    selectiveKeyRestoreOperationParameters, context)
          -                .doOnRequest(ignored -> LOGGER.verbose("Restoring key \"{}\" from location - {}", keyName, folderUrl))
          -                .doOnSuccess(response -> LOGGER.verbose("Restored key \"{}\" from location - {}", keyName, folderUrl))
          -                .doOnError(error -> LOGGER.warning("Failed to restore key \"{}\" from location - {}", keyName,
          -                    folderUrl, error))
          -                .map(restoreOperationResponse -> new SimpleResponse<>(restoreOperationResponse.getRequest(),
          -                    restoreOperationResponse.getStatusCode(), restoreOperationResponse.getHeaders(),
          +            return clientImpl.selectiveKeyRestoreOperationWithResponseAsync(keyName,
          +                BinaryData.fromObject(selectiveKeyRestoreOperationParameters), new RequestOptions().setContext(context))
          +                .map(selectiveKeyRestoreOperationResponse -> new SimpleResponse<>(
          +                    selectiveKeyRestoreOperationResponse.getRequest(),
          +                    selectiveKeyRestoreOperationResponse.getStatusCode(),
          +                    selectiveKeyRestoreOperationResponse.getHeaders(),
                               (KeyVaultSelectiveKeyRestoreOperation) transformToLongRunningOperation(
          -                        restoreOperationResponse.getValue())));
          +                        selectiveKeyRestoreOperationResponse.getValue().toObject(SelectiveKeyRestoreOperation.class))));
                   } catch (RuntimeException e) {
                       return monoError(LOGGER, e);
                   }
          @@ -838,6 +843,7 @@ Mono> selectiveKeyRestoreWithResp
           
               private Function, Mono>
                   selectiveKeyRestoreActivationOperation(String keyName, String folderUrl, String sasToken) {
          +
                   return (pollingContext) -> {
                       try {
                           return withContext(context -> selectiveKeyRestoreWithResponse(keyName, folderUrl, sasToken, context))
          @@ -851,6 +857,7 @@ Mono> selectiveKeyRestoreWithResp
               private
                   Function, Mono>>
                   selectiveKeyRestorePollOperation() {
          +
                   return (pollingContext) -> {
                       try {
                           PollResponse pollResponse = pollingContext.getLatestResponse();
          @@ -873,11 +880,12 @@ Mono> selectiveKeyRestoreWithResp
           
                           final String jobId = keyVaultSelectiveKeyRestoreOperation.getOperationId();
           
          -                return withContext(context -> clientImpl.restoreStatusWithResponseAsync(vaultUrl, jobId, context))
          +                return withContext(context -> clientImpl
          +                    .selectiveKeyRestoreStatusWithResponseAsync(jobId, new RequestOptions().setContext(context))
                               .map(response -> new SimpleResponse<>(response,
          -                        (KeyVaultSelectiveKeyRestoreOperation) restoreOperationToSelectiveKeyRestoreOperation(
          -                            response.getValue())))
          -                    .flatMap(KeyVaultBackupAsyncClient::processSelectiveKeyRestoreOperationResponse);
          +                        (KeyVaultSelectiveKeyRestoreOperation) transformToLongRunningOperation(
          +                            response.getValue().toObject(SelectiveKeyRestoreOperation.class))))
          +                    .flatMap(KeyVaultBackupAsyncClient::processSelectiveKeyRestoreOperationResponse));
                       } catch (HttpResponseException e) {
                           //noinspection ThrowableNotThrown
                           LOGGER.logExceptionAsError(e);
          @@ -897,10 +905,4 @@ Mono> selectiveKeyRestoreWithResp
                   return Mono.just(new PollResponse<>(toLongRunningOperationStatus(operationStatus.toLowerCase(Locale.US)),
                       response.getValue()));
               }
          -
          -    static KeyVaultLongRunningOperation restoreOperationToSelectiveKeyRestoreOperation(RestoreOperation operation) {
          -        return new KeyVaultSelectiveKeyRestoreOperation(operation.getStatus(), operation.getStatusDetails(),
          -            createKeyVaultErrorFromError(operation.getError()), operation.getJobId(), operation.getStartTime(),
          -            operation.getEndTime());
          -    }
           }
          diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultBackupClient.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultBackupClient.java
          index 8aa0d20d52c7..1282747dda11 100644
          --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultBackupClient.java
          +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultBackupClient.java
          @@ -8,29 +8,24 @@
           import com.azure.core.annotation.ServiceMethod;
           import com.azure.core.exception.HttpResponseException;
           import com.azure.core.http.HttpPipeline;
          +import com.azure.core.http.rest.RequestOptions;
           import com.azure.core.http.rest.Response;
          -import com.azure.core.http.rest.ResponseBase;
           import com.azure.core.http.rest.SimpleResponse;
          +import com.azure.core.util.BinaryData;
           import com.azure.core.util.Context;
           import com.azure.core.util.logging.ClientLogger;
           import com.azure.core.util.polling.LongRunningOperationStatus;
           import com.azure.core.util.polling.PollResponse;
           import com.azure.core.util.polling.PollingContext;
           import com.azure.core.util.polling.SyncPoller;
          -import com.azure.security.keyvault.administration.implementation.KeyVaultBackupClientImpl;
          -import com.azure.security.keyvault.administration.implementation.KeyVaultErrorCodeStrings;
          -import com.azure.security.keyvault.administration.implementation.models.FullBackupHeaders;
          +import com.azure.security.keyvault.administration.implementation.KeyVaultAdministrationClientImpl;
           import com.azure.security.keyvault.administration.implementation.models.FullBackupOperation;
          -import com.azure.security.keyvault.administration.implementation.models.FullRestoreOperationHeaders;
           import com.azure.security.keyvault.administration.implementation.models.PreBackupOperationParameters;
          -import com.azure.security.keyvault.administration.implementation.models.PreFullBackupHeaders;
          -import com.azure.security.keyvault.administration.implementation.models.PreFullRestoreOperationHeaders;
           import com.azure.security.keyvault.administration.implementation.models.PreRestoreOperationParameters;
           import com.azure.security.keyvault.administration.implementation.models.RestoreOperation;
           import com.azure.security.keyvault.administration.implementation.models.RestoreOperationParameters;
           import com.azure.security.keyvault.administration.implementation.models.SASTokenParameter;
           import com.azure.security.keyvault.administration.implementation.models.SelectiveKeyRestoreOperation;
          -import com.azure.security.keyvault.administration.implementation.models.SelectiveKeyRestoreOperationHeaders;
           import com.azure.security.keyvault.administration.implementation.models.SelectiveKeyRestoreOperationParameters;
           import com.azure.security.keyvault.administration.models.KeyVaultAdministrationException;
           import com.azure.security.keyvault.administration.models.KeyVaultBackupOperation;
          @@ -45,10 +40,8 @@
           import java.util.Objects;
           import java.util.function.Function;
           
          -import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.enableSyncRestProxy;
           import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.toLongRunningOperationStatus;
           import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.transformToLongRunningOperation;
          -import static com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient.restoreOperationToSelectiveKeyRestoreOperation;
           
           /**
            * The {@link KeyVaultBackupClient} provides synchronous methods to perform full a backup and restore of a key vault,
          @@ -208,28 +201,16 @@ public final class KeyVaultBackupClient {
           
               private static final Duration DEFAULT_POLLING_INTERVAL = Duration.ofSeconds(1);
           
          -    private final KeyVaultBackupAsyncClient asyncClient;
          -
               /**
                * The underlying AutoRest client used to interact with the Key Vault service.
                */
          -    private final KeyVaultBackupClientImpl clientImpl;
          +    private final KeyVaultAdministrationClientImpl clientImpl;
           
               /**
                * The Key Vault URL this client is associated to.
                */
               private final String vaultUrl;
           
          -    /**
          -     * The Key Vault Administration Service version to use with this client.
          -     */
          -    private final String serviceVersion;
          -
          -    /**
          -     * The {@link HttpPipeline} powering this client.
          -     */
          -    private final HttpPipeline pipeline;
          -
               Duration getDefaultPollingInterval() {
                   return DEFAULT_POLLING_INTERVAL;
               }
          @@ -238,14 +219,11 @@ Duration getDefaultPollingInterval() {
                * Package private constructor to be used by {@link KeyVaultBackupClientBuilder}.
                */
               KeyVaultBackupClient(URL vaultUrl, HttpPipeline httpPipeline, KeyVaultAdministrationServiceVersion serviceVersion) {
          -        Objects.requireNonNull(vaultUrl, KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED);
          +        Objects.requireNonNull(vaultUrl, KeyVaultAdministrationUtil.VAULT_END_POINT_REQUIRED);
           
                   this.vaultUrl = vaultUrl.toString();
          -        this.serviceVersion = serviceVersion.getVersion();
          -        this.pipeline = httpPipeline;
          -        this.asyncClient = null;
           
          -        clientImpl = new KeyVaultBackupClientImpl(httpPipeline, this.serviceVersion);
          +        clientImpl = new KeyVaultAdministrationClientImpl(httpPipeline, this.vaultUrl, serviceVersion);
               }
           
               /**
          @@ -254,7 +232,7 @@ Duration getDefaultPollingInterval() {
                * @return The vault endpoint URL.
                */
               public String getVaultUrl() {
          -        return asyncClient.getVaultUrl();
          +        return this.vaultUrl;
               }
           
               /**
          @@ -301,14 +279,13 @@ public String getVaultUrl() {
               public SyncPoller beginBackup(String blobStorageUrl, String sasToken) {
                   if (blobStorageUrl == null) {
                       throw LOGGER.logExceptionAsError(new NullPointerException(
          -                String.format(KeyVaultErrorCodeStrings.PARAMETER_REQUIRED, "'blobStorageUrl'")));
          +                String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'blobStorageUrl'")));
                   }
           
          -        Context context = Context.NONE;
                   return SyncPoller.createPoller(getDefaultPollingInterval(),
                       cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED,
          -                backupActivationOperation(blobStorageUrl, sasToken, context).apply(cxt)),
          -            backupPollOperation(context), (pollingContext, firstResponse) -> {
          +                backupActivationOperation(blobStorageUrl, sasToken, Context.NONE).apply(cxt)),
          +            backupPollOperation(Context.NONE), (pollingContext, firstResponse) -> {
                           throw LOGGER.logExceptionAsError(new RuntimeException("Cancellation is not supported"));
                       }, backupFetchOperation());
               }
          @@ -328,14 +305,14 @@ public SyncPoller beginBackup(String blobStorag
               Response backupWithResponse(String blobStorageUrl, String sasToken, Context context) {
                   SASTokenParameter sasTokenParameter
                       = new SASTokenParameter(blobStorageUrl).setToken(sasToken).setUseManagedIdentity(sasToken == null);
          -        context = enableSyncRestProxy(context);
           
                   try {
          -            ResponseBase backupOperationResponse
          -                = clientImpl.fullBackupWithResponse(vaultUrl, sasTokenParameter, context);
          +            Response backupOperationResponse = clientImpl.fullBackupWithResponse(
          +                BinaryData.fromObject(sasTokenParameter), new RequestOptions().setContext(context));
          +
                       return new SimpleResponse<>(backupOperationResponse.getRequest(), backupOperationResponse.getStatusCode(),
          -                backupOperationResponse.getHeaders(),
          -                (KeyVaultBackupOperation) transformToLongRunningOperation(backupOperationResponse.getValue()));
          +                backupOperationResponse.getHeaders(), (KeyVaultBackupOperation) transformToLongRunningOperation(
          +                    backupOperationResponse.getValue().toObject(FullBackupOperation.class)));
                   } catch (RuntimeException e) {
                       throw LOGGER.logExceptionAsError(e);
                   }
          @@ -343,6 +320,7 @@ Response backupWithResponse(String blobStorageUrl, Stri
           
               private Function, KeyVaultBackupOperation>
                   backupActivationOperation(String blobStorageUrl, String sasToken, Context context) {
          +
                   return (pollingContext) -> {
                       try {
                           return backupWithResponse(blobStorageUrl, sasToken, context).getValue();
          @@ -354,12 +332,14 @@ Response backupWithResponse(String blobStorageUrl, Stri
           
               private Function, PollResponse>
                   backupPollOperation(Context context) {
          +
                   return (pollingContext) -> {
                       try {
                           PollResponse pollResponse = pollingContext.getLatestResponse();
           
                           if (pollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED
                               || pollResponse.getStatus() == LongRunningOperationStatus.FAILED) {
          +
                               return pollResponse;
                           }
           
          @@ -367,20 +347,21 @@ Response backupWithResponse(String blobStorageUrl, Stri
           
                           if (keyVaultBackupOperation == null) {
                               LOGGER.warning("Backup operation does not exist. Activation operation failed.");
          -                    return new PollResponse(
          -                        LongRunningOperationStatus.fromString("BACKUP_START_FAILED", true), null);
          +
          +                    return new PollResponse<>(LongRunningOperationStatus.fromString("BACKUP_START_FAILED", true), null);
                           }
           
                           final String jobId = keyVaultBackupOperation.getOperationId();
          -                Context contextToUse = enableSyncRestProxy(context);
          +                Response backupOperationResponse
          +                    = clientImpl.fullBackupStatusWithResponse(jobId, new RequestOptions().setContext(context));
           
          -                Response backupOperationResponse
          -                    = clientImpl.fullBackupStatusWithResponse(vaultUrl, jobId, contextToUse);
                           return processBackupOperationResponse(new SimpleResponse<>(backupOperationResponse,
          -                    (KeyVaultBackupOperation) transformToLongRunningOperation(backupOperationResponse.getValue())));
          +                    (KeyVaultBackupOperation) transformToLongRunningOperation(
          +                        backupOperationResponse.getValue().toObject(FullBackupOperation.class))));
                       } catch (HttpResponseException e) {
                           //noinspection ThrowableNotThrown
                           LOGGER.logExceptionAsError(e);
          +
                           return new PollResponse<>(LongRunningOperationStatus.FAILED, null);
                       } catch (RuntimeException e) {
                           throw LOGGER.logExceptionAsError(e);
          @@ -400,7 +381,9 @@ private Function, String> backupFetchOpe
           
               private static PollResponse
                   processBackupOperationResponse(Response response) {
          +
                   String operationStatus = response.getValue().getStatus().toLowerCase(Locale.US);
          +
                   return new PollResponse<>(toLongRunningOperationStatus(operationStatus.toLowerCase(Locale.US)),
                       response.getValue());
               }
          @@ -448,15 +431,13 @@ private Function, String> backupFetchOpe
               public SyncPoller beginPreBackup(String blobStorageUrl, String sasToken) {
                   if (blobStorageUrl == null) {
                       throw LOGGER.logExceptionAsError(new NullPointerException(
          -                String.format(KeyVaultErrorCodeStrings.PARAMETER_REQUIRED, "'blobStorageUrl'")));
          +                String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'blobStorageUrl'")));
                   }
           
          -        Context context = Context.NONE;
          -
                   return SyncPoller.createPoller(getDefaultPollingInterval(),
                       cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED,
          -                preBackupActivationOperation(blobStorageUrl, sasToken, context).apply(cxt)),
          -            backupPollOperation(context), (pollingContext, firstResponse) -> {
          +                preBackupActivationOperation(blobStorageUrl, sasToken, Context.NONE).apply(cxt)),
          +            backupPollOperation(Context.NONE), (pollingContext, firstResponse) -> {
                           throw LOGGER.logExceptionAsError(new RuntimeException("Cancellation is not supported"));
                       }, backupFetchOperation());
               }
          @@ -491,15 +472,14 @@ Response preBackupWithResponse(String blobStorageUrl, S
                       = new PreBackupOperationParameters().setStorageResourceUri(blobStorageUrl)
                           .setToken(sasToken)
                           .setUseManagedIdentity(sasToken == null);
          -        context = enableSyncRestProxy(context);
           
                   try {
          -            ResponseBase backupOperationResponse
          -                = clientImpl.preFullBackupWithResponse(vaultUrl, preBackupOperationParameters, context);
          +            Response backupOperationResponse = clientImpl.preFullBackupWithResponse(
          +                BinaryData.fromObject(preBackupOperationParameters), new RequestOptions().setContext(context));
           
                       return new SimpleResponse<>(backupOperationResponse.getRequest(), backupOperationResponse.getStatusCode(),
          -                backupOperationResponse.getHeaders(),
          -                (KeyVaultBackupOperation) transformToLongRunningOperation(backupOperationResponse.getValue()));
          +                backupOperationResponse.getHeaders(), (KeyVaultBackupOperation) transformToLongRunningOperation(
          +                    backupOperationResponse.getValue().toObject(FullBackupOperation.class)));
                   } catch (RuntimeException e) {
                       throw LOGGER.logExceptionAsError(e);
                   }
          @@ -551,15 +531,13 @@ Response preBackupWithResponse(String blobStorageUrl, S
               public SyncPoller beginRestore(String folderUrl, String sasToken) {
                   if (folderUrl == null) {
                       throw LOGGER.logExceptionAsError(
          -                new NullPointerException(String.format(KeyVaultErrorCodeStrings.PARAMETER_REQUIRED, "'folderUrl'")));
          +                new NullPointerException(String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'folderUrl'")));
                   }
           
          -        Context context = Context.NONE;
          -
                   return SyncPoller.createPoller(getDefaultPollingInterval(),
          -            cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED,
          -                restoreActivationOperation(folderUrl, sasToken, context).apply(cxt)),
          -            restorePollOperation(context), (pollingContext, firstResponse) -> {
          +            context -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED,
          +                restoreActivationOperation(folderUrl, sasToken, Context.NONE).apply(context)),
          +            restorePollOperation(Context.NONE), (pollingContext, firstResponse) -> {
                           throw LOGGER.logExceptionAsError(new RuntimeException("Cancellation is not supported"));
                       }, (pollingContext) -> new KeyVaultRestoreResult());
               }
          @@ -588,14 +566,14 @@ Response restoreWithResponse(String folderUrl, String
                       = new SASTokenParameter(containerUrl).setToken(sasToken).setUseManagedIdentity(sasToken == null);
                   RestoreOperationParameters restoreOperationParameters
                       = new RestoreOperationParameters(sasTokenParameter, folderName);
          -        context = enableSyncRestProxy(context);
           
                   try {
          -            ResponseBase restoreOperationResponse
          -                = clientImpl.fullRestoreOperationWithResponse(vaultUrl, restoreOperationParameters, context);
          +            Response restoreOperationResponse = clientImpl.fullRestoreOperationWithResponse(
          +                BinaryData.fromObject(restoreOperationParameters), new RequestOptions().setContext(context));
          +
                       return new SimpleResponse<>(restoreOperationResponse.getRequest(), restoreOperationResponse.getStatusCode(),
          -                restoreOperationResponse.getHeaders(),
          -                (KeyVaultRestoreOperation) transformToLongRunningOperation(restoreOperationResponse.getValue()));
          +                restoreOperationResponse.getHeaders(), (KeyVaultRestoreOperation) transformToLongRunningOperation(
          +                    restoreOperationResponse.getValue().toObject(RestoreOperation.class)));
                   } catch (RuntimeException e) {
                       throw LOGGER.logExceptionAsError(e);
                   }
          @@ -603,6 +581,7 @@ Response restoreWithResponse(String folderUrl, String
           
               private Function, KeyVaultRestoreOperation>
                   restoreActivationOperation(String folderUrl, String sasToken, Context context) {
          +
                   return (pollingContext) -> {
                       try {
                           return restoreWithResponse(folderUrl, sasToken, context).getValue();
          @@ -614,6 +593,7 @@ Response restoreWithResponse(String folderUrl, String
           
               private Function, PollResponse>
                   restorePollOperation(Context context) {
          +
                   return (pollingContext) -> {
                       try {
                           PollResponse pollResponse = pollingContext.getLatestResponse();
          @@ -634,16 +614,16 @@ Response restoreWithResponse(String folderUrl, String
                           }
           
                           final String jobId = keyVaultRestoreOperation.getOperationId();
          -                Context contextToUse = enableSyncRestProxy(context);
          -
          -                Response response
          -                    = clientImpl.restoreStatusWithResponse(vaultUrl, jobId, contextToUse);
          -                return processRestoreOperationResponse(new SimpleResponse<>(response,
          -                    (KeyVaultRestoreOperation) transformToLongRunningOperation(response.getValue())));
          +                Response response
          +                    = clientImpl.restoreStatusWithResponse(jobId, new RequestOptions().setContext(context));
           
          +                return processRestoreOperationResponse(
          +                    new SimpleResponse<>(response, (KeyVaultRestoreOperation) transformToLongRunningOperation(
          +                        response.getValue().toObject(RestoreOperation.class))));
                       } catch (HttpResponseException e) {
                           //noinspection ThrowableNotThrown
                           LOGGER.logExceptionAsError(e);
          +
                           return new PollResponse<>(LongRunningOperationStatus.FAILED, null);
                       } catch (RuntimeException e) {
                           throw LOGGER.logExceptionAsError(e);
          @@ -653,7 +633,9 @@ Response restoreWithResponse(String folderUrl, String
           
               private static PollResponse
                   processRestoreOperationResponse(Response response) {
          +
                   String operationStatus = response.getValue().getStatus().toLowerCase(Locale.US);
          +
                   return new PollResponse<>(toLongRunningOperationStatus(operationStatus.toLowerCase(Locale.US)),
                       response.getValue());
               }
          @@ -705,7 +687,7 @@ public SyncPoller beginPreResto
                   String sasToken) {
                   if (folderUrl == null) {
                       throw LOGGER.logExceptionAsError(
          -                new NullPointerException(String.format(KeyVaultErrorCodeStrings.PARAMETER_REQUIRED, "'folderUrl'")));
          +                new NullPointerException(String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'folderUrl'")));
                   }
           
                   Context context = Context.NONE;
          @@ -744,14 +726,14 @@ Response preRestoreWithResponse(String folderUrl, Stri
                   PreRestoreOperationParameters restoreOperationParameters
                       = new PreRestoreOperationParameters().setFolderToRestore(folderName)
                           .setSasTokenParameters(sasTokenParameter);
          -        context = enableSyncRestProxy(context);
           
                   try {
          -            ResponseBase restoreOperationResponse
          -                = clientImpl.preFullRestoreOperationWithResponse(vaultUrl, restoreOperationParameters, context);
          +            Response restoreOperationResponse = clientImpl.preFullRestoreOperationWithResponse(
          +                BinaryData.fromObject(restoreOperationParameters), new RequestOptions().setContext(context));
          +
                       return new SimpleResponse<>(restoreOperationResponse.getRequest(), restoreOperationResponse.getStatusCode(),
          -                restoreOperationResponse.getHeaders(),
          -                (KeyVaultRestoreOperation) transformToLongRunningOperation(restoreOperationResponse.getValue()));
          +                restoreOperationResponse.getHeaders(), (KeyVaultRestoreOperation) transformToLongRunningOperation(
          +                    restoreOperationResponse.getValue().toObject(RestoreOperation.class)));
                   } catch (RuntimeException e) {
                       throw LOGGER.logExceptionAsError(e);
                   }
          @@ -759,6 +741,7 @@ Response preRestoreWithResponse(String folderUrl, Stri
           
               private Function, KeyVaultRestoreOperation>
                   preRestoreActivationOperation(String folderUrl, String sasToken, Context context) {
          +
                   return (pollingContext) -> {
                       try {
                           return preRestoreWithResponse(folderUrl, sasToken, context).getValue();
          @@ -815,22 +798,21 @@ Response preRestoreWithResponse(String folderUrl, Stri
               @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION)
               public SyncPoller
                   beginSelectiveKeyRestore(String keyName, String folderUrl, String sasToken) {
          +
                   if (keyName == null) {
                       throw LOGGER.logExceptionAsError(
          -                new NullPointerException(String.format(KeyVaultErrorCodeStrings.PARAMETER_REQUIRED, "'keyName'")));
          +                new NullPointerException(String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'keyName'")));
                   }
           
                   if (folderUrl == null) {
                       throw LOGGER.logExceptionAsError(
          -                new NullPointerException(String.format(KeyVaultErrorCodeStrings.PARAMETER_REQUIRED, "'folderUrl'")));
          +                new NullPointerException(String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'folderUrl'")));
                   }
           
          -        Context context = Context.NONE;
          -
                   return SyncPoller.createPoller(getDefaultPollingInterval(),
          -            cxt -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED,
          -                selectiveKeyRestoreActivationOperation(keyName, folderUrl, sasToken, context).apply(cxt)),
          -            selectiveKeyRestorePollOperation(context), (pollingContext, firstResponse) -> {
          +            context -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED,
          +                selectiveKeyRestoreActivationOperation(keyName, folderUrl, sasToken, Context.NONE).apply(context)),
          +            selectiveKeyRestorePollOperation(Context.NONE), (pollingContext, firstResponse) -> {
                           throw LOGGER.logExceptionAsError(new RuntimeException("Cancellation is not supported"));
                       }, (pollingContext) -> new KeyVaultSelectiveKeyRestoreResult());
               }
          @@ -852,6 +834,7 @@ Response preRestoreWithResponse(String folderUrl, Stri
                */
               Response selectiveKeyRestoreWithResponse(String keyName, String folderUrl,
                   String sasToken, Context context) {
          +
                   String[] segments = folderUrl.split("/");
                   String folderName = segments[segments.length - 1];
                   String containerUrl = folderUrl.substring(0, folderUrl.length() - folderName.length());
          @@ -860,16 +843,17 @@ Response selectiveKeyRestoreWithResponse(S
                       = new SASTokenParameter(containerUrl).setToken(sasToken).setUseManagedIdentity(sasToken == null);
                   SelectiveKeyRestoreOperationParameters selectiveKeyRestoreOperationParameters
                       = new SelectiveKeyRestoreOperationParameters(sasTokenParameter, folderName);
          -        context = enableSyncRestProxy(context);
           
                   try {
          -            ResponseBase restoreOperationResponse
          -                = clientImpl.selectiveKeyRestoreOperationWithResponse(vaultUrl, keyName,
          -                    selectiveKeyRestoreOperationParameters, context);
          -            return new SimpleResponse<>(restoreOperationResponse.getRequest(), restoreOperationResponse.getStatusCode(),
          -                restoreOperationResponse.getHeaders(),
          +            Response selectiveKeyRestoreOperationResponse
          +                = clientImpl.selectiveKeyRestoreOperationWithResponse(keyName,
          +                    BinaryData.fromObject(selectiveKeyRestoreOperationParameters),
          +                    new RequestOptions().setContext(context));
          +
          +            return new SimpleResponse<>(selectiveKeyRestoreOperationResponse.getRequest(),
          +                selectiveKeyRestoreOperationResponse.getStatusCode(), selectiveKeyRestoreOperationResponse.getHeaders(),
                           (KeyVaultSelectiveKeyRestoreOperation) transformToLongRunningOperation(
          -                    restoreOperationResponse.getValue()));
          +                    selectiveKeyRestoreOperationResponse.getValue().toObject(SelectiveKeyRestoreOperation.class)));
                   } catch (RuntimeException e) {
                       throw LOGGER.logExceptionAsError(e);
                   }
          @@ -877,6 +861,7 @@ Response selectiveKeyRestoreWithResponse(S
           
               private Function, KeyVaultSelectiveKeyRestoreOperation>
                   selectiveKeyRestoreActivationOperation(String keyName, String folderUrl, String sasToken, Context context) {
          +
                   return (pollingContext) -> {
                       try {
                           return selectiveKeyRestoreWithResponse(keyName, folderUrl, sasToken, context).getValue();
          @@ -889,12 +874,14 @@ Response selectiveKeyRestoreWithResponse(S
               private
                   Function, PollResponse>
                   selectiveKeyRestorePollOperation(Context context) {
          +
                   return (pollingContext) -> {
                       try {
                           PollResponse pollResponse = pollingContext.getLatestResponse();
           
                           if (pollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED
                               || pollResponse.getStatus() == LongRunningOperationStatus.FAILED) {
          +
                               return pollResponse;
                           }
           
          @@ -907,13 +894,15 @@ Response selectiveKeyRestoreWithResponse(S
                               return new PollResponse<>(
                                   LongRunningOperationStatus.fromString("SELECTIVE_RESTORE_START_FAILED", true), null);
                           }
          +
                           final String jobId = keyVaultSelectiveKeyRestoreOperation.getOperationId();
          -                Context contextToUse = enableSyncRestProxy(context);
          -                Response response
          -                    = clientImpl.restoreStatusWithResponse(vaultUrl, jobId, contextToUse);
          +
          +                Response response
          +                    = clientImpl.selectiveKeyRestoreStatusWithResponse(jobId, new RequestOptions().setContext(context));
          +
                           return processSelectiveKeyRestoreOperationResponse(new SimpleResponse<>(response,
          -                    (KeyVaultSelectiveKeyRestoreOperation) restoreOperationToSelectiveKeyRestoreOperation(
          -                        response.getValue())));
          +                    (KeyVaultSelectiveKeyRestoreOperation) transformToLongRunningOperation(
          +                        response.getValue().toObject(SelectiveKeyRestoreOperation.class))));
                       } catch (HttpResponseException e) {
                           //noinspection ThrowableNotThrown
                           LOGGER.logExceptionAsError(e);
          @@ -927,7 +916,9 @@ Response selectiveKeyRestoreWithResponse(S
           
               private static PollResponse
                   processSelectiveKeyRestoreOperationResponse(Response response) {
          +
                   String operationStatus = response.getValue().getStatus().toLowerCase(Locale.US);
          +
                   return new PollResponse<>(toLongRunningOperationStatus(operationStatus.toLowerCase(Locale.US)),
                       response.getValue());
               }
          diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultBackupClientBuilder.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultBackupClientBuilder.java
          index aefabcda500c..a4365be92552 100644
          --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultBackupClientBuilder.java
          +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultBackupClientBuilder.java
          @@ -33,7 +33,6 @@
           import com.azure.core.util.tracing.Tracer;
           import com.azure.core.util.tracing.TracerProvider;
           import com.azure.security.keyvault.administration.implementation.KeyVaultCredentialPolicy;
          -import com.azure.security.keyvault.administration.implementation.KeyVaultErrorCodeStrings;
           
           import java.net.MalformedURLException;
           import java.net.URL;
          @@ -94,7 +93,7 @@ public final class KeyVaultBackupClientBuilder implements TokenCredentialTrait, ConfigurationTrait {
               // This is the properties file name.
               private static final ClientLogger LOGGER = new ClientLogger(KeyVaultBackupClientBuilder.class);
          -    private static final String AZURE_KEY_VAULT_RBAC = "azure-key-vault-administration.properties";
          +    private static final String AZURE_KEY_VAULT_RBAC = "azure-security-keyvault-administration.properties";
               private static final String SDK_NAME = "name";
               private static final String SDK_VERSION = "version";
           
          @@ -186,7 +185,7 @@ private Configuration validateEndpointAndGetBuildConfiguration() {
           
                   if (buildEndpoint == null) {
                       throw LOGGER
          -                .logExceptionAsError(new IllegalStateException(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED));
          +                .logExceptionAsError(new IllegalStateException(KeyVaultAdministrationUtil.VAULT_END_POINT_REQUIRED));
                   }
                   return buildConfiguration;
               }
          diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultSettingsAsyncClient.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultSettingsAsyncClient.java
          index 09bdc5d82bb0..7f00b581c6a1 100644
          --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultSettingsAsyncClient.java
          +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultSettingsAsyncClient.java
          @@ -9,23 +9,25 @@
           import com.azure.core.http.HttpPipeline;
           import com.azure.core.http.rest.Response;
           import com.azure.core.http.rest.SimpleResponse;
          +import com.azure.core.util.BinaryData;
           import com.azure.core.util.logging.ClientLogger;
          +import com.azure.security.keyvault.administration.implementation.KeyVaultAdministrationClientImpl;
           import com.azure.security.keyvault.administration.implementation.KeyVaultAdministrationUtils;
          -import com.azure.security.keyvault.administration.implementation.KeyVaultErrorCodeStrings;
          -import com.azure.security.keyvault.administration.implementation.KeyVaultSettingsClientImpl;
          -import com.azure.security.keyvault.administration.implementation.models.KeyVaultErrorException;
           import com.azure.security.keyvault.administration.implementation.models.Setting;
          +import com.azure.security.keyvault.administration.implementation.models.SettingsListResult;
          +import com.azure.security.keyvault.administration.models.KeyVaultAdministrationException;
           import com.azure.security.keyvault.administration.models.KeyVaultGetSettingsResult;
           import com.azure.security.keyvault.administration.models.KeyVaultRoleDefinition;
           import com.azure.security.keyvault.administration.models.KeyVaultSetting;
           import com.azure.security.keyvault.administration.models.KeyVaultSettingType;
           import reactor.core.publisher.Mono;
           
          -import java.util.ArrayList;
           import java.util.List;
           import java.util.Objects;
          +import java.util.stream.Collectors;
           
           import static com.azure.core.util.FluxUtil.monoError;
          +import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.EMPTY_OPTIONS;
           
           /**
            * The {@link KeyVaultSettingsAsyncClient} provides asynchronous methods to create, update, get and list
          @@ -136,20 +138,17 @@
           @ServiceClient(
               builder = KeyVaultSettingsClientBuilder.class,
               isAsync = true,
          -    serviceInterfaces = KeyVaultSettingsClientImpl.KeyVaultSettingsClientService.class)
          +    serviceInterfaces = KeyVaultAdministrationClientImpl.KeyVaultAdministrationClientService.class)
           public final class KeyVaultSettingsAsyncClient {
               private static final ClientLogger LOGGER = new ClientLogger(KeyVaultSettingsAsyncClient.class);
          -    private final String vaultUrl;
          -    private final KeyVaultSettingsClientImpl implClient;
          +    private final KeyVaultAdministrationClientImpl implClient;
           
               /**
          -     * Creates a {@link KeyVaultSettingsAsyncClient} that uses a {@link KeyVaultSettingsClientImpl} to service requests.
          +     * Creates a {@link KeyVaultSettingsAsyncClient} that uses a {@link KeyVaultAdministrationClientImpl} to service requests.
                *
          -     * @param vaultUrl The URL of the key vault this client will act on.
                * @param implClient The implementation client used to service requests.
                */
          -    KeyVaultSettingsAsyncClient(String vaultUrl, KeyVaultSettingsClientImpl implClient) {
          -        this.vaultUrl = vaultUrl;
          +    KeyVaultSettingsAsyncClient(KeyVaultAdministrationClientImpl implClient) {
                   this.implClient = implClient;
               }
           
          @@ -184,11 +183,11 @@ HttpPipeline getHttpPipeline() {
                * @return A {@link Mono} containing the updated {@link KeyVaultSetting account setting}.
                *
                * @throws NullPointerException if {@code setting} is {@code null}.
          -     * @throws KeyVaultErrorException thrown if the request is rejected by the server.
          +     * @throws KeyVaultAdministrationException thrown if the request is rejected by the server.
                */
               @ServiceMethod(returns = ReturnType.SINGLE)
               public Mono updateSetting(KeyVaultSetting setting) {
          -        Objects.requireNonNull(setting, String.format(KeyVaultErrorCodeStrings.PARAMETER_REQUIRED, "'setting'"));
          +        Objects.requireNonNull(setting, String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'setting'"));
           
                   try {
                       String settingValue = null;
          @@ -197,12 +196,10 @@ public Mono updateSetting(KeyVaultSetting setting) {
                           settingValue = Boolean.toString(setting.asBoolean());
                       }
           
          -            return implClient.updateSettingAsync(vaultUrl, setting.getName(), settingValue)
          -                .doOnRequest(ignored -> LOGGER.verbose("Updating account setting - {}", setting.getName()))
          -                .doOnSuccess(response -> LOGGER.verbose("Updated account setting - {}", setting.getName()))
          -                .doOnError(error -> LOGGER.warning("Failed updating account setting - {}", setting.getName(), error))
          +            return implClient
          +                .updateSettingWithResponseAsync(setting.getName(), BinaryData.fromObject(settingValue), EMPTY_OPTIONS)
                           .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException)
          -                .map(KeyVaultSettingsAsyncClient::transformToKeyVaultSetting);
          +                .map(response -> transformToKeyVaultSetting(response.getValue().toObject(Setting.class)));
                   } catch (RuntimeException e) {
                       return monoError(LOGGER, e);
                   }
          @@ -231,11 +228,11 @@ public Mono updateSetting(KeyVaultSetting setting) {
                * {@link KeyVaultSetting account setting}.
                *
                * @throws NullPointerException if {@code setting} is {@code null}.
          -     * @throws KeyVaultErrorException thrown if the request is rejected by the server.
          +     * @throws KeyVaultAdministrationException thrown if the request is rejected by the server.
                */
               @ServiceMethod(returns = ReturnType.SINGLE)
               public Mono> updateSettingWithResponse(KeyVaultSetting setting) {
          -        Objects.requireNonNull(setting, String.format(KeyVaultErrorCodeStrings.PARAMETER_REQUIRED, "'setting'"));
          +        Objects.requireNonNull(setting, String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'setting'"));
           
                   try {
                       String settingValue = null;
          @@ -244,12 +241,11 @@ public Mono> updateSettingWithResponse(KeyVaultSetting
                           settingValue = Boolean.toString(setting.asBoolean());
                       }
           
          -            return implClient.updateSettingWithResponseAsync(vaultUrl, setting.getName(), settingValue)
          -                .doOnRequest(ignored -> LOGGER.verbose("Updating account setting - {}", setting.getName()))
          -                .doOnSuccess(response -> LOGGER.verbose("Updated account setting - {}", setting.getName()))
          -                .doOnError(error -> LOGGER.warning("Failed updating account setting - {}", setting.getName(), error))
          +            return implClient
          +                .updateSettingWithResponseAsync(setting.getName(), BinaryData.fromObject(settingValue), EMPTY_OPTIONS)
                           .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException)
          -                .map(response -> new SimpleResponse<>(response, transformToKeyVaultSetting(response.getValue())));
          +                .map(response -> new SimpleResponse<>(response,
          +                    transformToKeyVaultSetting(response.getValue().toObject(Setting.class))));
                   } catch (RuntimeException e) {
                       return monoError(LOGGER, e);
                   }
          @@ -274,17 +270,14 @@ public Mono> updateSettingWithResponse(KeyVaultSetting
                * @return A {@link Mono} containing the {@link KeyVaultSetting account setting}.
                *
                * @throws IllegalArgumentException thrown if the setting type is not supported.
          -     * @throws KeyVaultErrorException thrown if the request is rejected by the server.
          +     * @throws KeyVaultAdministrationException thrown if the request is rejected by the server.
                */
               @ServiceMethod(returns = ReturnType.SINGLE)
               public Mono getSetting(String name) {
                   try {
          -            return implClient.getSettingAsync(vaultUrl, name)
          -                .doOnRequest(ignored -> LOGGER.verbose("Retrieving account setting - {}", name))
          -                .doOnSuccess(response -> LOGGER.verbose("Retrieved account setting - {}", name))
          -                .doOnError(error -> LOGGER.warning("Failed retrieving account setting - {}", name, error))
          +            return implClient.getSettingWithResponseAsync(name, EMPTY_OPTIONS)
                           .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException)
          -                .map(KeyVaultSettingsAsyncClient::transformToKeyVaultSetting);
          +                .map(response -> transformToKeyVaultSetting(response.getValue().toObject(Setting.class)));
                   } catch (RuntimeException e) {
                       return monoError(LOGGER, e);
                   }
          @@ -311,17 +304,15 @@ public Mono getSetting(String name) {
                * {@link KeyVaultSetting account setting}.
                *
                * @throws IllegalArgumentException thrown if the setting type is not supported.
          -     * @throws KeyVaultErrorException thrown if the request is rejected by the server.
          +     * @throws KeyVaultAdministrationException thrown if the request is rejected by the server.
                */
               @ServiceMethod(returns = ReturnType.SINGLE)
               public Mono> getSettingWithResponse(String name) {
                   try {
          -            return implClient.getSettingWithResponseAsync(vaultUrl, name)
          -                .doOnRequest(ignored -> LOGGER.verbose("Retrieving account setting - {}", name))
          -                .doOnSuccess(response -> LOGGER.verbose("Retrieved account setting - {}", name))
          -                .doOnError(error -> LOGGER.warning("Failed retrieving account setting - {}", name, error))
          +            return implClient.getSettingWithResponseAsync(name, EMPTY_OPTIONS)
                           .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException)
          -                .map(response -> new SimpleResponse<>(response, transformToKeyVaultSetting(response.getValue())));
          +                .map(response -> new SimpleResponse<>(response,
          +                    transformToKeyVaultSetting(response.getValue().toObject(Setting.class))));
                   } catch (RuntimeException e) {
                       return monoError(LOGGER, e);
                   }
          @@ -346,21 +337,20 @@ public Mono> getSettingWithResponse(String name) {
                * {@link KeyVaultSetting account settings}.
                *
                * @throws IllegalArgumentException thrown if a setting type in the list is not supported.
          -     * @throws KeyVaultErrorException thrown if the request is rejected by the server.
          +     * @throws KeyVaultAdministrationException thrown if the request is rejected by the server.
                */
               @ServiceMethod(returns = ReturnType.SINGLE)
               public Mono getSettings() {
                   try {
          -            return implClient.getSettingsAsync(vaultUrl)
          -                .doOnRequest(ignored -> LOGGER.verbose("Listing account settings"))
          -                .doOnSuccess(response -> LOGGER.verbose("Listed account settings successfully"))
          -                .doOnError(error -> LOGGER.warning("Failed retrieving account settings", error))
          +            return implClient.getSettingsWithResponseAsync(EMPTY_OPTIONS)
                           .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException)
          -                .map(settingsListResult -> {
          -                    List keyVaultSettings = new ArrayList<>();
          -
          -                    settingsListResult.getSettings()
          -                        .forEach(setting -> keyVaultSettings.add(transformToKeyVaultSetting(setting)));
          +                .map(response -> {
          +                    List keyVaultSettings = response.getValue()
          +                        .toObject(SettingsListResult.class)
          +                        .getSettings()
          +                        .stream()
          +                        .map(KeyVaultSettingsAsyncClient::transformToKeyVaultSetting)
          +                        .collect(Collectors.toList());
           
                               return new KeyVaultGetSettingsResult(keyVaultSettings);
                           });
          @@ -395,22 +385,20 @@ public Mono getSettings() {
                * {@link KeyVaultGetSettingsResult result object} wrapping the list of {@link KeyVaultSetting account settings}.
                *
                * @throws IllegalArgumentException thrown if a setting type in the list is not supported.
          -     * @throws KeyVaultErrorException thrown if the request is rejected by the server.
          +     * @throws KeyVaultAdministrationException thrown if the request is rejected by the server.
                */
               @ServiceMethod(returns = ReturnType.SINGLE)
               public Mono> getSettingsWithResponse() {
                   try {
          -            return implClient.getSettingsWithResponseAsync(vaultUrl)
          -                .doOnRequest(ignored -> LOGGER.verbose("Listing account settings"))
          -                .doOnSuccess(response -> LOGGER.verbose("Listed account settings successfully"))
          -                .doOnError(error -> LOGGER.warning("Failed retrieving account settings", error))
          +            return implClient.getSettingsWithResponseAsync(EMPTY_OPTIONS)
                           .onErrorMap(KeyVaultAdministrationUtils::mapThrowableToKeyVaultAdministrationException)
                           .map(response -> {
          -                    List keyVaultSettings = new ArrayList<>();
          -
          -                    response.getValue()
          +                    List keyVaultSettings = response.getValue()
          +                        .toObject(SettingsListResult.class)
                                   .getSettings()
          -                        .forEach(setting -> keyVaultSettings.add(transformToKeyVaultSetting(setting)));
          +                        .stream()
          +                        .map(KeyVaultSettingsAsyncClient::transformToKeyVaultSetting)
          +                        .collect(Collectors.toList());
           
                               return new SimpleResponse<>(response, new KeyVaultGetSettingsResult(keyVaultSettings));
                           });
          diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultSettingsClient.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultSettingsClient.java
          index d1c745af3fd2..9dc632580de2 100644
          --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultSettingsClient.java
          +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultSettingsClient.java
          @@ -6,23 +6,26 @@
           import com.azure.core.annotation.ReturnType;
           import com.azure.core.annotation.ServiceClient;
           import com.azure.core.annotation.ServiceMethod;
          +import com.azure.core.http.rest.RequestOptions;
           import com.azure.core.http.rest.Response;
           import com.azure.core.http.rest.SimpleResponse;
          +import com.azure.core.util.BinaryData;
           import com.azure.core.util.Context;
           import com.azure.core.util.logging.ClientLogger;
          -import com.azure.security.keyvault.administration.implementation.KeyVaultErrorCodeStrings;
          -import com.azure.security.keyvault.administration.implementation.KeyVaultSettingsClientImpl;
          -import com.azure.security.keyvault.administration.implementation.models.KeyVaultErrorException;
          +import com.azure.security.keyvault.administration.implementation.KeyVaultAdministrationClientImpl;
           import com.azure.security.keyvault.administration.implementation.models.Setting;
           import com.azure.security.keyvault.administration.implementation.models.SettingsListResult;
          +import com.azure.security.keyvault.administration.models.KeyVaultAdministrationException;
           import com.azure.security.keyvault.administration.models.KeyVaultGetSettingsResult;
           import com.azure.security.keyvault.administration.models.KeyVaultRoleDefinition;
           import com.azure.security.keyvault.administration.models.KeyVaultSetting;
           import com.azure.security.keyvault.administration.models.KeyVaultSettingType;
           
          -import java.util.ArrayList;
           import java.util.List;
           import java.util.Objects;
          +import java.util.stream.Collectors;
          +
          +import static com.azure.security.keyvault.administration.KeyVaultAdministrationUtil.EMPTY_OPTIONS;
           
           /**
            * The {@link KeyVaultSettingsClient} provides synchronous methods to create, update, get and list
          @@ -133,17 +136,14 @@
           @ServiceClient(builder = KeyVaultSettingsClientBuilder.class)
           public final class KeyVaultSettingsClient {
               private static final ClientLogger LOGGER = new ClientLogger(KeyVaultSettingsClient.class);
          -    private final String vaultUrl;
          -    private final KeyVaultSettingsClientImpl implClient;
          +    private final KeyVaultAdministrationClientImpl implClient;
           
               /**
                * Initializes an instance of {@link KeyVaultSettingsClient} class.
                *
          -     * @param vaultUrl The URL of the key vault this client will act on.
                * @param implClient The implementation client used to service requests.
                */
          -    KeyVaultSettingsClient(String vaultUrl, KeyVaultSettingsClientImpl implClient) {
          -        this.vaultUrl = vaultUrl;
          +    KeyVaultSettingsClient(KeyVaultAdministrationClientImpl implClient) {
                   this.implClient = implClient;
               }
           
          @@ -167,11 +167,11 @@ public final class KeyVaultSettingsClient {
                * @return The updated {@link KeyVaultSetting account setting}.
                *
                * @throws NullPointerException if {@code setting} is {@code null}.
          -     * @throws KeyVaultErrorException thrown if the request is rejected by the server.
          +     * @throws KeyVaultAdministrationException thrown if the request is rejected by the server.
                */
               @ServiceMethod(returns = ReturnType.SINGLE)
               public KeyVaultSetting updateSetting(KeyVaultSetting setting) {
          -        Objects.requireNonNull(setting, String.format(KeyVaultErrorCodeStrings.PARAMETER_REQUIRED, "'setting'"));
          +        Objects.requireNonNull(setting, String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'setting'"));
           
                   try {
                       String settingValue = null;
          @@ -180,8 +180,10 @@ public KeyVaultSetting updateSetting(KeyVaultSetting setting) {
                           settingValue = Boolean.toString(setting.asBoolean());
                       }
           
          -            return KeyVaultSettingsAsyncClient
          -                .transformToKeyVaultSetting(implClient.updateSetting(vaultUrl, setting.getName(), settingValue));
          +            return KeyVaultSettingsAsyncClient.transformToKeyVaultSetting(implClient
          +                .updateSettingWithResponse(setting.getName(), BinaryData.fromObject(settingValue), EMPTY_OPTIONS)
          +                .getValue()
          +                .toObject(Setting.class));
                   } catch (RuntimeException e) {
                       throw LOGGER.logExceptionAsError(e);
                   }
          @@ -211,11 +213,11 @@ public KeyVaultSetting updateSetting(KeyVaultSetting setting) {
                * {@link KeyVaultSetting account setting}.
                *
                * @throws NullPointerException if {@code setting} is {@code null}.
          -     * @throws KeyVaultErrorException thrown if the request is rejected by the server.
          +     * @throws KeyVaultAdministrationException thrown if the request is rejected by the server.
                */
               @ServiceMethod(returns = ReturnType.SINGLE)
               public Response updateSettingWithResponse(KeyVaultSetting setting, Context context) {
          -        Objects.requireNonNull(setting, String.format(KeyVaultErrorCodeStrings.PARAMETER_REQUIRED, "'setting'"));
          +        Objects.requireNonNull(setting, String.format(KeyVaultAdministrationUtil.PARAMETER_REQUIRED, "'setting'"));
           
                   try {
                       String settingValue = null;
          @@ -224,11 +226,11 @@ public Response updateSettingWithResponse(KeyVaultSetting setti
                           settingValue = Boolean.toString(setting.asBoolean());
                       }
           
          -            Response response
          -                = implClient.updateSettingWithResponse(vaultUrl, setting.getName(), settingValue, context);
          +            Response response = implClient.updateSettingWithResponse(setting.getName(),
          +                BinaryData.fromObject(settingValue), new RequestOptions().setContext(context));
           
                       return new SimpleResponse<>(response,
          -                KeyVaultSettingsAsyncClient.transformToKeyVaultSetting(response.getValue()));
          +                KeyVaultSettingsAsyncClient.transformToKeyVaultSetting(response.getValue().toObject(Setting.class)));
                   } catch (RuntimeException e) {
                       throw LOGGER.logExceptionAsError(e);
                   }
          @@ -253,12 +255,13 @@ public Response updateSettingWithResponse(KeyVaultSetting setti
                * @return The {@link KeyVaultSetting account setting}.
                *
                * @throws IllegalArgumentException thrown if the setting type is not supported.
          -     * @throws KeyVaultErrorException thrown if the request is rejected by the server.
          +     * @throws KeyVaultAdministrationException thrown if the request is rejected by the server.
                */
               @ServiceMethod(returns = ReturnType.SINGLE)
               public KeyVaultSetting getSetting(String name) {
                   try {
          -            return KeyVaultSettingsAsyncClient.transformToKeyVaultSetting(this.implClient.getSetting(vaultUrl, name));
          +            return KeyVaultSettingsAsyncClient.transformToKeyVaultSetting(
          +                implClient.getSettingWithResponse(name, EMPTY_OPTIONS).getValue().toObject(Setting.class));
                   } catch (RuntimeException e) {
                       throw LOGGER.logExceptionAsError(e);
                   }
          @@ -287,15 +290,16 @@ public KeyVaultSetting getSetting(String name) {
                * {@link KeyVaultSetting account setting}.
                *
                * @throws IllegalArgumentException thrown if the setting type is not supported.
          -     * @throws KeyVaultErrorException thrown if the request is rejected by the server.
          +     * @throws KeyVaultAdministrationException thrown if the request is rejected by the server.
                */
               @ServiceMethod(returns = ReturnType.SINGLE)
               public Response getSettingWithResponse(String name, Context context) {
                   try {
          -            Response response = implClient.getSettingWithResponse(vaultUrl, name, context);
          +            Response response
          +                = implClient.getSettingWithResponse(name, new RequestOptions().setContext(context));
           
                       return new SimpleResponse<>(response,
          -                KeyVaultSettingsAsyncClient.transformToKeyVaultSetting(response.getValue()));
          +                KeyVaultSettingsAsyncClient.transformToKeyVaultSetting(response.getValue().toObject(Setting.class)));
                   } catch (RuntimeException e) {
                       throw LOGGER.logExceptionAsError(e);
                   }
          @@ -322,17 +326,18 @@ public Response getSettingWithResponse(String name, Context con
                * {@link KeyVaultSetting account settings}.
                *
                * @throws IllegalArgumentException thrown if a setting type in the list is not supported.
          -     * @throws KeyVaultErrorException thrown if the request is rejected by the server.
          +     * @throws KeyVaultAdministrationException thrown if the request is rejected by the server.
                */
               @ServiceMethod(returns = ReturnType.SINGLE)
               public KeyVaultGetSettingsResult getSettings() {
          -        List keyVaultSettings = new ArrayList<>();
          -
                   try {
          -            implClient.getSettings(vaultUrl)
          +            List keyVaultSettings = implClient.getSettingsWithResponse(EMPTY_OPTIONS)
          +                .getValue()
          +                .toObject(SettingsListResult.class)
                           .getSettings()
          -                .forEach(
          -                    setting -> keyVaultSettings.add(KeyVaultSettingsAsyncClient.transformToKeyVaultSetting(setting)));
          +                .stream()
          +                .map(KeyVaultSettingsAsyncClient::transformToKeyVaultSetting)
          +                .collect(Collectors.toList());
           
                       return new KeyVaultGetSettingsResult(keyVaultSettings);
                   } catch (RuntimeException e) {
          @@ -368,18 +373,19 @@ public KeyVaultGetSettingsResult getSettings() {
                * {@link KeyVaultGetSettingsResult result object} wrapping the list of {@link KeyVaultSetting account settings}.
                *
                * @throws IllegalArgumentException thrown if a setting type in the list is not supported.
          -     * @throws KeyVaultErrorException thrown if the request is rejected by the server.
          +     * @throws KeyVaultAdministrationException thrown if the request is rejected by the server.
                */
               @ServiceMethod(returns = ReturnType.SINGLE)
               public Response getSettingsWithResponse(Context context) {
                   try {
          -            Response response = implClient.getSettingsWithResponse(vaultUrl, context);
          -            List keyVaultSettings = new ArrayList<>();
          -
          -            response.getValue()
          +            Response response
          +                = implClient.getSettingsWithResponse(new RequestOptions().setContext(context));
          +            List keyVaultSettings = response.getValue()
          +                .toObject(SettingsListResult.class)
                           .getSettings()
          -                .forEach(
          -                    setting -> keyVaultSettings.add(KeyVaultSettingsAsyncClient.transformToKeyVaultSetting(setting)));
          +                .stream()
          +                .map(KeyVaultSettingsAsyncClient::transformToKeyVaultSetting)
          +                .collect(Collectors.toList());
           
                       return new SimpleResponse<>(response, new KeyVaultGetSettingsResult(keyVaultSettings));
                   } catch (RuntimeException e) {
          diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultSettingsClientBuilder.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultSettingsClientBuilder.java
          index a6216486db45..3fc4cd90f706 100644
          --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultSettingsClientBuilder.java
          +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/KeyVaultSettingsClientBuilder.java
          @@ -35,9 +35,8 @@
           import com.azure.core.util.logging.ClientLogger;
           import com.azure.core.util.tracing.Tracer;
           import com.azure.core.util.tracing.TracerProvider;
          +import com.azure.security.keyvault.administration.implementation.KeyVaultAdministrationClientImpl;
           import com.azure.security.keyvault.administration.implementation.KeyVaultCredentialPolicy;
          -import com.azure.security.keyvault.administration.implementation.KeyVaultErrorCodeStrings;
          -import com.azure.security.keyvault.administration.implementation.KeyVaultSettingsClientImpl;
           
           import java.net.MalformedURLException;
           import java.net.URL;
          @@ -99,7 +98,7 @@ public final class KeyVaultSettingsClientBuilder implements TokenCredentialTrait
               HttpTrait, ConfigurationTrait {
           
               private static final ClientLogger LOGGER = new ClientLogger(KeyVaultSettingsClientBuilder.class);
          -    private static final String AZURE_KEY_VAULT_RBAC = "azure-key-vault-administration.properties";
          +    private static final String AZURE_KEY_VAULT_RBAC = "azure-security-keyvault-administration.properties";
               private static final String SDK_NAME = "name";
               private static final String SDK_VERSION = "version";
           
          @@ -395,11 +394,13 @@ public KeyVaultSettingsClientBuilder disableChallengeResourceVerification() {
                *
                * @return an instance of KeyVaultSettingsClientImpl.
                */
          -    private KeyVaultSettingsClientImpl buildImplClient() {
          +    private KeyVaultAdministrationClientImpl buildImplClient() {
                   HttpPipeline buildPipeline = (pipeline != null) ? pipeline : createHttpPipeline();
          +
                   KeyVaultAdministrationServiceVersion version
                       = (serviceVersion != null) ? serviceVersion : KeyVaultAdministrationServiceVersion.getLatest();
          -        return new KeyVaultSettingsClientImpl(buildPipeline, version.getVersion());
          +
          +        return new KeyVaultAdministrationClientImpl(buildPipeline, vaultUrl, version);
               }
           
               private HttpPipeline createHttpPipeline() {
          @@ -412,7 +413,7 @@ private HttpPipeline createHttpPipeline() {
           
                   if (vaultUrl == null) {
                       throw LOGGER
          -                .logExceptionAsError(new IllegalStateException(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED));
          +                .logExceptionAsError(new IllegalStateException(KeyVaultAdministrationUtil.VAULT_END_POINT_REQUIRED));
                   }
           
                   serviceVersion = serviceVersion != null ? serviceVersion : KeyVaultAdministrationServiceVersion.getLatest();
          @@ -471,7 +472,7 @@ private HttpPipeline createHttpPipeline() {
                * @return an instance of KeyVaultSettingsAsyncClient.
                */
               public KeyVaultSettingsAsyncClient buildAsyncClient() {
          -        return new KeyVaultSettingsAsyncClient(vaultUrl, buildImplClient());
          +        return new KeyVaultSettingsAsyncClient(buildImplClient());
               }
           
               /**
          @@ -480,6 +481,6 @@ public KeyVaultSettingsAsyncClient buildAsyncClient() {
                * @return an instance of KeyVaultSettingsClient.
                */
               public KeyVaultSettingsClient buildClient() {
          -        return new KeyVaultSettingsClient(vaultUrl, buildImplClient());
          +        return new KeyVaultSettingsClient(buildImplClient());
               }
           }
          diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultAccessControlClientImpl.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultAccessControlClientImpl.java
          deleted file mode 100644
          index 2a9be911c1ad..000000000000
          --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultAccessControlClientImpl.java
          +++ /dev/null
          @@ -1,123 +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.security.keyvault.administration.implementation;
          -
          -import com.azure.core.http.HttpPipeline;
          -import com.azure.core.http.HttpPipelineBuilder;
          -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 KeyVaultAccessControlClient type.
          - */
          -public final class KeyVaultAccessControlClientImpl {
          -    /**
          -     * 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 RoleDefinitionsImpl object to access its operations.
          -     */
          -    private final RoleDefinitionsImpl roleDefinitions;
          -
          -    /**
          -     * Gets the RoleDefinitionsImpl object to access its operations.
          -     * 
          -     * @return the RoleDefinitionsImpl object.
          -     */
          -    public RoleDefinitionsImpl getRoleDefinitions() {
          -        return this.roleDefinitions;
          -    }
          -
          -    /**
          -     * The RoleAssignmentsImpl object to access its operations.
          -     */
          -    private final RoleAssignmentsImpl roleAssignments;
          -
          -    /**
          -     * Gets the RoleAssignmentsImpl object to access its operations.
          -     * 
          -     * @return the RoleAssignmentsImpl object.
          -     */
          -    public RoleAssignmentsImpl getRoleAssignments() {
          -        return this.roleAssignments;
          -    }
          -
          -    /**
          -     * Initializes an instance of KeyVaultAccessControlClient client.
          -     * 
          -     * @param apiVersion Api Version.
          -     */
          -    public KeyVaultAccessControlClientImpl(String apiVersion) {
          -        this(new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build(),
          -            JacksonAdapter.createDefaultSerializerAdapter(), apiVersion);
          -    }
          -
          -    /**
          -     * Initializes an instance of KeyVaultAccessControlClient client.
          -     * 
          -     * @param httpPipeline The HTTP pipeline to send requests through.
          -     * @param apiVersion Api Version.
          -     */
          -    public KeyVaultAccessControlClientImpl(HttpPipeline httpPipeline, String apiVersion) {
          -        this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), apiVersion);
          -    }
          -
          -    /**
          -     * Initializes an instance of KeyVaultAccessControlClient client.
          -     * 
          -     * @param httpPipeline The HTTP pipeline to send requests through.
          -     * @param serializerAdapter The serializer to serialize an object into a string.
          -     * @param apiVersion Api Version.
          -     */
          -    public KeyVaultAccessControlClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter,
          -        String apiVersion) {
          -        this.httpPipeline = httpPipeline;
          -        this.serializerAdapter = serializerAdapter;
          -        this.apiVersion = apiVersion;
          -        this.roleDefinitions = new RoleDefinitionsImpl(this);
          -        this.roleAssignments = new RoleAssignmentsImpl(this);
          -    }
          -}
          diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultAdministrationClientImpl.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultAdministrationClientImpl.java
          new file mode 100644
          index 000000000000..6dc41591da8b
          --- /dev/null
          +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultAdministrationClientImpl.java
          @@ -0,0 +1,2596 @@
          +// Copyright (c) Microsoft Corporation. All rights reserved.
          +// Licensed under the MIT License.
          +// Code generated by Microsoft (R) TypeSpec Code Generator.
          +
          +package com.azure.security.keyvault.administration.implementation;
          +
          +import com.azure.core.annotation.BodyParam;
          +import com.azure.core.annotation.ExpectedResponses;
          +import com.azure.core.annotation.Get;
          +import com.azure.core.annotation.HeaderParam;
          +import com.azure.core.annotation.Host;
          +import com.azure.core.annotation.HostParam;
          +import com.azure.core.annotation.Patch;
          +import com.azure.core.annotation.PathParam;
          +import com.azure.core.annotation.Post;
          +import com.azure.core.annotation.Put;
          +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.exception.ClientAuthenticationException;
          +import com.azure.core.exception.HttpResponseException;
          +import com.azure.core.exception.ResourceModifiedException;
          +import com.azure.core.exception.ResourceNotFoundException;
          +import com.azure.core.http.HttpPipeline;
          +import com.azure.core.http.HttpPipelineBuilder;
          +import com.azure.core.http.policy.RetryPolicy;
          +import com.azure.core.http.policy.UserAgentPolicy;
          +import com.azure.core.http.rest.RequestOptions;
          +import com.azure.core.http.rest.Response;
          +import com.azure.core.http.rest.RestProxy;
          +import com.azure.core.util.BinaryData;
          +import com.azure.core.util.Context;
          +import com.azure.core.util.FluxUtil;
          +import com.azure.core.util.polling.DefaultPollingStrategy;
          +import com.azure.core.util.polling.PollerFlux;
          +import com.azure.core.util.polling.PollingStrategyOptions;
          +import com.azure.core.util.polling.SyncDefaultPollingStrategy;
          +import com.azure.core.util.polling.SyncPoller;
          +import com.azure.core.util.serializer.JacksonAdapter;
          +import com.azure.core.util.serializer.SerializerAdapter;
          +import com.azure.core.util.serializer.TypeReference;
          +import com.azure.security.keyvault.administration.KeyVaultAdministrationServiceVersion;
          +import com.azure.security.keyvault.administration.implementation.models.FullBackupOperation;
          +import com.azure.security.keyvault.administration.implementation.models.RestoreOperation;
          +import com.azure.security.keyvault.administration.implementation.models.SelectiveKeyRestoreOperation;
          +import java.time.Duration;
          +import reactor.core.publisher.Mono;
          +
          +/**
          + * Initializes a new instance of the KeyVaultAdministrationClient type.
          + */
          +public final class KeyVaultAdministrationClientImpl {
          +    /**
          +     * The proxy service used to perform REST calls.
          +     */
          +    private final KeyVaultAdministrationClientService service;
          +
          +    /**
          +     */
          +    private final String vaultBaseUrl;
          +
          +    /**
          +     * Gets.
          +     * 
          +     * @return the vaultBaseUrl value.
          +     */
          +    public String getVaultBaseUrl() {
          +        return this.vaultBaseUrl;
          +    }
          +
          +    /**
          +     * Service version.
          +     */
          +    private final KeyVaultAdministrationServiceVersion serviceVersion;
          +
          +    /**
          +     * Gets Service version.
          +     * 
          +     * @return the serviceVersion value.
          +     */
          +    public KeyVaultAdministrationServiceVersion getServiceVersion() {
          +        return this.serviceVersion;
          +    }
          +
          +    /**
          +     * 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 RoleAssignmentsImpl object to access its operations.
          +     */
          +    private final RoleAssignmentsImpl roleAssignments;
          +
          +    /**
          +     * Gets the RoleAssignmentsImpl object to access its operations.
          +     * 
          +     * @return the RoleAssignmentsImpl object.
          +     */
          +    public RoleAssignmentsImpl getRoleAssignments() {
          +        return this.roleAssignments;
          +    }
          +
          +    /**
          +     * The RoleDefinitionsImpl object to access its operations.
          +     */
          +    private final RoleDefinitionsImpl roleDefinitions;
          +
          +    /**
          +     * Gets the RoleDefinitionsImpl object to access its operations.
          +     * 
          +     * @return the RoleDefinitionsImpl object.
          +     */
          +    public RoleDefinitionsImpl getRoleDefinitions() {
          +        return this.roleDefinitions;
          +    }
          +
          +    /**
          +     * Initializes an instance of KeyVaultAdministrationClient client.
          +     * 
          +     * @param vaultBaseUrl
          +     * @param serviceVersion Service version.
          +     */
          +    public KeyVaultAdministrationClientImpl(String vaultBaseUrl, KeyVaultAdministrationServiceVersion serviceVersion) {
          +        this(new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build(),
          +            JacksonAdapter.createDefaultSerializerAdapter(), vaultBaseUrl, serviceVersion);
          +    }
          +
          +    /**
          +     * Initializes an instance of KeyVaultAdministrationClient client.
          +     * 
          +     * @param httpPipeline The HTTP pipeline to send requests through.
          +     * @param vaultBaseUrl
          +     * @param serviceVersion Service version.
          +     */
          +    public KeyVaultAdministrationClientImpl(HttpPipeline httpPipeline, String vaultBaseUrl,
          +        KeyVaultAdministrationServiceVersion serviceVersion) {
          +        this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), vaultBaseUrl, serviceVersion);
          +    }
          +
          +    /**
          +     * Initializes an instance of KeyVaultAdministrationClient client.
          +     * 
          +     * @param httpPipeline The HTTP pipeline to send requests through.
          +     * @param serializerAdapter The serializer to serialize an object into a string.
          +     * @param vaultBaseUrl
          +     * @param serviceVersion Service version.
          +     */
          +    public KeyVaultAdministrationClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter,
          +        String vaultBaseUrl, KeyVaultAdministrationServiceVersion serviceVersion) {
          +        this.httpPipeline = httpPipeline;
          +        this.serializerAdapter = serializerAdapter;
          +        this.vaultBaseUrl = vaultBaseUrl;
          +        this.serviceVersion = serviceVersion;
          +        this.roleAssignments = new RoleAssignmentsImpl(this);
          +        this.roleDefinitions = new RoleDefinitionsImpl(this);
          +        this.service = RestProxy.create(KeyVaultAdministrationClientService.class, this.httpPipeline,
          +            this.getSerializerAdapter());
          +    }
          +
          +    /**
          +     * The interface defining all the services for KeyVaultAdministrationClient to be used by the proxy service to
          +     * perform REST calls.
          +     */
          +    @Host("{vaultBaseUrl}")
          +    @ServiceInterface(name = "KeyVaultAdministrationClient")
          +    public interface KeyVaultAdministrationClientService {
          +        @Get("/backup/{jobId}/pending")
          +        @ExpectedResponses({ 200 })
          +        @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
          +        @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
          +        @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
          +        @UnexpectedResponseExceptionType(HttpResponseException.class)
          +        Mono> fullBackupStatus(@HostParam("vaultBaseUrl") String vaultBaseUrl,
          +            @QueryParam("api-version") String apiVersion, @PathParam("jobId") String jobId,
          +            @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context);
          +
          +        @Get("/backup/{jobId}/pending")
          +        @ExpectedResponses({ 200 })
          +        @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
          +        @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
          +        @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
          +        @UnexpectedResponseExceptionType(HttpResponseException.class)
          +        Response fullBackupStatusSync(@HostParam("vaultBaseUrl") String vaultBaseUrl,
          +            @QueryParam("api-version") String apiVersion, @PathParam("jobId") String jobId,
          +            @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context);
          +
          +        @Post("/backup")
          +        @ExpectedResponses({ 202 })
          +        @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
          +        @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
          +        @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
          +        @UnexpectedResponseExceptionType(HttpResponseException.class)
          +        Mono> fullBackup(@HostParam("vaultBaseUrl") String vaultBaseUrl,
          +            @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType,
          +            @HeaderParam("Accept") String accept,
          +            @BodyParam("application/json") BinaryData azureStorageBlobContainerUri, RequestOptions requestOptions,
          +            Context context);
          +
          +        @Post("/backup")
          +        @ExpectedResponses({ 202 })
          +        @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
          +        @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
          +        @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
          +        @UnexpectedResponseExceptionType(HttpResponseException.class)
          +        Response fullBackupSync(@HostParam("vaultBaseUrl") String vaultBaseUrl,
          +            @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType,
          +            @HeaderParam("Accept") String accept,
          +            @BodyParam("application/json") BinaryData azureStorageBlobContainerUri, RequestOptions requestOptions,
          +            Context context);
          +
          +        @Post("/prebackup")
          +        @ExpectedResponses({ 202 })
          +        @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
          +        @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
          +        @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
          +        @UnexpectedResponseExceptionType(HttpResponseException.class)
          +        Mono> preFullBackup(@HostParam("vaultBaseUrl") String vaultBaseUrl,
          +            @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType,
          +            @HeaderParam("Accept") String accept,
          +            @BodyParam("application/json") BinaryData preBackupOperationParameters, RequestOptions requestOptions,
          +            Context context);
          +
          +        @Post("/prebackup")
          +        @ExpectedResponses({ 202 })
          +        @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
          +        @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
          +        @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
          +        @UnexpectedResponseExceptionType(HttpResponseException.class)
          +        Response preFullBackupSync(@HostParam("vaultBaseUrl") String vaultBaseUrl,
          +            @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType,
          +            @HeaderParam("Accept") String accept,
          +            @BodyParam("application/json") BinaryData preBackupOperationParameters, RequestOptions requestOptions,
          +            Context context);
          +
          +        @Get("/restore/{jobId}/pending")
          +        @ExpectedResponses({ 200 })
          +        @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
          +        @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
          +        @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
          +        @UnexpectedResponseExceptionType(HttpResponseException.class)
          +        Mono> restoreStatus(@HostParam("vaultBaseUrl") String vaultBaseUrl,
          +            @QueryParam("api-version") String apiVersion, @PathParam("jobId") String jobId,
          +            @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context);
          +
          +        @Get("/restore/{jobId}/pending")
          +        @ExpectedResponses({ 200 })
          +        @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
          +        @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
          +        @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
          +        @UnexpectedResponseExceptionType(HttpResponseException.class)
          +        Response restoreStatusSync(@HostParam("vaultBaseUrl") String vaultBaseUrl,
          +            @QueryParam("api-version") String apiVersion, @PathParam("jobId") String jobId,
          +            @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context);
          +
          +        @Put("/prerestore")
          +        @ExpectedResponses({ 202 })
          +        @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
          +        @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
          +        @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
          +        @UnexpectedResponseExceptionType(HttpResponseException.class)
          +        Mono> preFullRestoreOperation(@HostParam("vaultBaseUrl") String vaultBaseUrl,
          +            @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType,
          +            @HeaderParam("Accept") String accept,
          +            @BodyParam("application/json") BinaryData preRestoreOperationParameters, RequestOptions requestOptions,
          +            Context context);
          +
          +        @Put("/prerestore")
          +        @ExpectedResponses({ 202 })
          +        @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
          +        @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
          +        @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
          +        @UnexpectedResponseExceptionType(HttpResponseException.class)
          +        Response preFullRestoreOperationSync(@HostParam("vaultBaseUrl") String vaultBaseUrl,
          +            @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType,
          +            @HeaderParam("Accept") String accept,
          +            @BodyParam("application/json") BinaryData preRestoreOperationParameters, RequestOptions requestOptions,
          +            Context context);
          +
          +        @Put("/restore")
          +        @ExpectedResponses({ 202 })
          +        @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
          +        @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
          +        @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
          +        @UnexpectedResponseExceptionType(HttpResponseException.class)
          +        Mono> fullRestoreOperation(@HostParam("vaultBaseUrl") String vaultBaseUrl,
          +            @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType,
          +            @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData restoreBlobDetails,
          +            RequestOptions requestOptions, Context context);
          +
          +        @Put("/restore")
          +        @ExpectedResponses({ 202 })
          +        @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
          +        @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
          +        @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
          +        @UnexpectedResponseExceptionType(HttpResponseException.class)
          +        Response fullRestoreOperationSync(@HostParam("vaultBaseUrl") String vaultBaseUrl,
          +            @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType,
          +            @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData restoreBlobDetails,
          +            RequestOptions requestOptions, Context context);
          +
          +        @Get("/restore/{jobId}/pending")
          +        @ExpectedResponses({ 200 })
          +        @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
          +        @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
          +        @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
          +        @UnexpectedResponseExceptionType(HttpResponseException.class)
          +        Mono> selectiveKeyRestoreStatus(@HostParam("vaultBaseUrl") String vaultBaseUrl,
          +            @QueryParam("api-version") String apiVersion, @PathParam("jobId") String jobId,
          +            @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context);
          +
          +        @Get("/restore/{jobId}/pending")
          +        @ExpectedResponses({ 200 })
          +        @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
          +        @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
          +        @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
          +        @UnexpectedResponseExceptionType(HttpResponseException.class)
          +        Response selectiveKeyRestoreStatusSync(@HostParam("vaultBaseUrl") String vaultBaseUrl,
          +            @QueryParam("api-version") String apiVersion, @PathParam("jobId") String jobId,
          +            @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context);
          +
          +        @Put("/keys/{keyName}/restore")
          +        @ExpectedResponses({ 202 })
          +        @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
          +        @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
          +        @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
          +        @UnexpectedResponseExceptionType(HttpResponseException.class)
          +        Mono> selectiveKeyRestoreOperation(@HostParam("vaultBaseUrl") String vaultBaseUrl,
          +            @QueryParam("api-version") String apiVersion, @PathParam("keyName") String keyName,
          +            @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept,
          +            @BodyParam("application/json") BinaryData restoreBlobDetails, RequestOptions requestOptions,
          +            Context context);
          +
          +        @Put("/keys/{keyName}/restore")
          +        @ExpectedResponses({ 202 })
          +        @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
          +        @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
          +        @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
          +        @UnexpectedResponseExceptionType(HttpResponseException.class)
          +        Response selectiveKeyRestoreOperationSync(@HostParam("vaultBaseUrl") String vaultBaseUrl,
          +            @QueryParam("api-version") String apiVersion, @PathParam("keyName") String keyName,
          +            @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept,
          +            @BodyParam("application/json") BinaryData restoreBlobDetails, RequestOptions requestOptions,
          +            Context context);
          +
          +        @Patch("/settings/{setting-name}")
          +        @ExpectedResponses({ 200 })
          +        @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
          +        @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
          +        @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
          +        @UnexpectedResponseExceptionType(HttpResponseException.class)
          +        Mono> updateSetting(@HostParam("vaultBaseUrl") String vaultBaseUrl,
          +            @QueryParam("api-version") String apiVersion, @PathParam("setting-name") String settingName,
          +            @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept,
          +            @BodyParam("application/json") BinaryData parameters, RequestOptions requestOptions, Context context);
          +
          +        @Patch("/settings/{setting-name}")
          +        @ExpectedResponses({ 200 })
          +        @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
          +        @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
          +        @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
          +        @UnexpectedResponseExceptionType(HttpResponseException.class)
          +        Response updateSettingSync(@HostParam("vaultBaseUrl") String vaultBaseUrl,
          +            @QueryParam("api-version") String apiVersion, @PathParam("setting-name") String settingName,
          +            @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept,
          +            @BodyParam("application/json") BinaryData parameters, RequestOptions requestOptions, Context context);
          +
          +        @Get("/settings/{setting-name}")
          +        @ExpectedResponses({ 200 })
          +        @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
          +        @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
          +        @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
          +        @UnexpectedResponseExceptionType(HttpResponseException.class)
          +        Mono> getSetting(@HostParam("vaultBaseUrl") String vaultBaseUrl,
          +            @QueryParam("api-version") String apiVersion, @PathParam("setting-name") String settingName,
          +            @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context);
          +
          +        @Get("/settings/{setting-name}")
          +        @ExpectedResponses({ 200 })
          +        @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
          +        @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
          +        @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
          +        @UnexpectedResponseExceptionType(HttpResponseException.class)
          +        Response getSettingSync(@HostParam("vaultBaseUrl") String vaultBaseUrl,
          +            @QueryParam("api-version") String apiVersion, @PathParam("setting-name") String settingName,
          +            @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context);
          +
          +        @Get("/settings")
          +        @ExpectedResponses({ 200 })
          +        @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
          +        @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
          +        @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
          +        @UnexpectedResponseExceptionType(HttpResponseException.class)
          +        Mono> getSettings(@HostParam("vaultBaseUrl") String vaultBaseUrl,
          +            @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept,
          +            RequestOptions requestOptions, Context context);
          +
          +        @Get("/settings")
          +        @ExpectedResponses({ 200 })
          +        @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 })
          +        @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 })
          +        @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 })
          +        @UnexpectedResponseExceptionType(HttpResponseException.class)
          +        Response getSettingsSync(@HostParam("vaultBaseUrl") String vaultBaseUrl,
          +            @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept,
          +            RequestOptions requestOptions, Context context);
          +    }
          +
          +    /**
          +     * Returns the status of full backup operation.
          +     * 

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     *     jobId: String (Optional)
          +     *     azureStorageBlobContainerUri: String (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param jobId The id returned as part of the backup request. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return full backup operation along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> fullBackupStatusWithResponseAsync(String jobId, RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.fullBackupStatus(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), jobId, accept, requestOptions, context)); + } + + /** + * Returns the status of full backup operation. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     *     jobId: String (Optional)
          +     *     azureStorageBlobContainerUri: String (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param jobId The id returned as part of the backup request. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return full backup operation along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response fullBackupStatusWithResponse(String jobId, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.fullBackupStatusSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), jobId, + accept, requestOptions, Context.NONE); + } + + /** + * Creates a full backup using a user-provided SAS token to an Azure blob storage container. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     storageResourceUri: String (Required)
          +     *     token: String (Optional)
          +     *     useManagedIdentity: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     *     jobId: String (Optional)
          +     *     azureStorageBlobContainerUri: String (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param azureStorageBlobContainerUri Azure blob shared access signature token pointing to a valid Azure blob + * container where full backup needs to be stored. This token needs to be valid for at least next 24 hours from the + * time of making this call. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return full backup operation along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> fullBackupWithResponseAsync(BinaryData azureStorageBlobContainerUri, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.fullBackup(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + contentType, accept, azureStorageBlobContainerUri, requestOptions, context)); + } + + /** + * Creates a full backup using a user-provided SAS token to an Azure blob storage container. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     storageResourceUri: String (Required)
          +     *     token: String (Optional)
          +     *     useManagedIdentity: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     *     jobId: String (Optional)
          +     *     azureStorageBlobContainerUri: String (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param azureStorageBlobContainerUri Azure blob shared access signature token pointing to a valid Azure blob + * container where full backup needs to be stored. This token needs to be valid for at least next 24 hours from the + * time of making this call. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return full backup operation along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response fullBackupWithResponse(BinaryData azureStorageBlobContainerUri, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return service.fullBackupSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), contentType, + accept, azureStorageBlobContainerUri, requestOptions, Context.NONE); + } + + /** + * Creates a full backup using a user-provided SAS token to an Azure blob storage container. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     storageResourceUri: String (Required)
          +     *     token: String (Optional)
          +     *     useManagedIdentity: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     *     jobId: String (Optional)
          +     *     azureStorageBlobContainerUri: String (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param azureStorageBlobContainerUri Azure blob shared access signature token pointing to a valid Azure blob + * container where full backup needs to be stored. This token needs to be valid for at least next 24 hours from the + * time of making this call. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link PollerFlux} for polling of full backup operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public PollerFlux beginFullBackupAsync(BinaryData azureStorageBlobContainerUri, + RequestOptions requestOptions) { + return PollerFlux.create(Duration.ofSeconds(1), + () -> this.fullBackupWithResponseAsync(azureStorageBlobContainerUri, requestOptions), + new DefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) + + .setContext(requestOptions != null && requestOptions.getContext() != null + ? requestOptions.getContext() + : Context.NONE) + .setServiceVersion(this.getServiceVersion().getVersion())), + TypeReference.createInstance(BinaryData.class), TypeReference.createInstance(BinaryData.class)); + } + + /** + * Creates a full backup using a user-provided SAS token to an Azure blob storage container. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     storageResourceUri: String (Required)
          +     *     token: String (Optional)
          +     *     useManagedIdentity: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     *     jobId: String (Optional)
          +     *     azureStorageBlobContainerUri: String (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param azureStorageBlobContainerUri Azure blob shared access signature token pointing to a valid Azure blob + * container where full backup needs to be stored. This token needs to be valid for at least next 24 hours from the + * time of making this call. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link SyncPoller} for polling of full backup operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller beginFullBackup(BinaryData azureStorageBlobContainerUri, + RequestOptions requestOptions) { + return SyncPoller.createPoller(Duration.ofSeconds(1), + () -> this.fullBackupWithResponse(azureStorageBlobContainerUri, requestOptions), + new SyncDefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) + + .setContext(requestOptions != null && requestOptions.getContext() != null + ? requestOptions.getContext() + : Context.NONE) + .setServiceVersion(this.getServiceVersion().getVersion())), + TypeReference.createInstance(BinaryData.class), TypeReference.createInstance(BinaryData.class)); + } + + /** + * Creates a full backup using a user-provided SAS token to an Azure blob storage container. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     storageResourceUri: String (Required)
          +     *     token: String (Optional)
          +     *     useManagedIdentity: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     *     jobId: String (Optional)
          +     *     azureStorageBlobContainerUri: String (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param azureStorageBlobContainerUri Azure blob shared access signature token pointing to a valid Azure blob + * container where full backup needs to be stored. This token needs to be valid for at least next 24 hours from the + * time of making this call. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link PollerFlux} for polling of full backup operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public PollerFlux + beginFullBackupWithModelAsync(BinaryData azureStorageBlobContainerUri, RequestOptions requestOptions) { + return PollerFlux.create(Duration.ofSeconds(1), + () -> this.fullBackupWithResponseAsync(azureStorageBlobContainerUri, requestOptions), + new DefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) + + .setContext(requestOptions != null && requestOptions.getContext() != null + ? requestOptions.getContext() + : Context.NONE) + .setServiceVersion(this.getServiceVersion().getVersion())), + TypeReference.createInstance(FullBackupOperation.class), + TypeReference.createInstance(FullBackupOperation.class)); + } + + /** + * Creates a full backup using a user-provided SAS token to an Azure blob storage container. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     storageResourceUri: String (Required)
          +     *     token: String (Optional)
          +     *     useManagedIdentity: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     *     jobId: String (Optional)
          +     *     azureStorageBlobContainerUri: String (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param azureStorageBlobContainerUri Azure blob shared access signature token pointing to a valid Azure blob + * container where full backup needs to be stored. This token needs to be valid for at least next 24 hours from the + * time of making this call. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link SyncPoller} for polling of full backup operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller + beginFullBackupWithModel(BinaryData azureStorageBlobContainerUri, RequestOptions requestOptions) { + return SyncPoller.createPoller(Duration.ofSeconds(1), + () -> this.fullBackupWithResponse(azureStorageBlobContainerUri, requestOptions), + new SyncDefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) + + .setContext(requestOptions != null && requestOptions.getContext() != null + ? requestOptions.getContext() + : Context.NONE) + .setServiceVersion(this.getServiceVersion().getVersion())), + TypeReference.createInstance(FullBackupOperation.class), + TypeReference.createInstance(FullBackupOperation.class)); + } + + /** + * Pre-backup operation for checking whether the customer can perform a full backup operation. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     storageResourceUri: String (Optional)
          +     *     token: String (Optional)
          +     *     useManagedIdentity: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     *     jobId: String (Optional)
          +     *     azureStorageBlobContainerUri: String (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param preBackupOperationParameters Optional parameters to validate prior to performing a full backup operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return full backup operation along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> preFullBackupWithResponseAsync(BinaryData preBackupOperationParameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.preFullBackup(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + contentType, accept, preBackupOperationParameters, requestOptions, context)); + } + + /** + * Pre-backup operation for checking whether the customer can perform a full backup operation. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     storageResourceUri: String (Optional)
          +     *     token: String (Optional)
          +     *     useManagedIdentity: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     *     jobId: String (Optional)
          +     *     azureStorageBlobContainerUri: String (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param preBackupOperationParameters Optional parameters to validate prior to performing a full backup operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return full backup operation along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response preFullBackupWithResponse(BinaryData preBackupOperationParameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return service.preFullBackupSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), contentType, + accept, preBackupOperationParameters, requestOptions, Context.NONE); + } + + /** + * Pre-backup operation for checking whether the customer can perform a full backup operation. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     storageResourceUri: String (Optional)
          +     *     token: String (Optional)
          +     *     useManagedIdentity: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     *     jobId: String (Optional)
          +     *     azureStorageBlobContainerUri: String (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param preBackupOperationParameters Optional parameters to validate prior to performing a full backup operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link PollerFlux} for polling of full backup operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public PollerFlux beginPreFullBackupAsync(BinaryData preBackupOperationParameters, + RequestOptions requestOptions) { + return PollerFlux.create(Duration.ofSeconds(1), + () -> this.preFullBackupWithResponseAsync(preBackupOperationParameters, requestOptions), + new DefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) + + .setContext(requestOptions != null && requestOptions.getContext() != null + ? requestOptions.getContext() + : Context.NONE) + .setServiceVersion(this.getServiceVersion().getVersion())), + TypeReference.createInstance(BinaryData.class), TypeReference.createInstance(BinaryData.class)); + } + + /** + * Pre-backup operation for checking whether the customer can perform a full backup operation. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     storageResourceUri: String (Optional)
          +     *     token: String (Optional)
          +     *     useManagedIdentity: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     *     jobId: String (Optional)
          +     *     azureStorageBlobContainerUri: String (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param preBackupOperationParameters Optional parameters to validate prior to performing a full backup operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link SyncPoller} for polling of full backup operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller beginPreFullBackup(BinaryData preBackupOperationParameters, + RequestOptions requestOptions) { + return SyncPoller.createPoller(Duration.ofSeconds(1), + () -> this.preFullBackupWithResponse(preBackupOperationParameters, requestOptions), + new SyncDefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) + + .setContext(requestOptions != null && requestOptions.getContext() != null + ? requestOptions.getContext() + : Context.NONE) + .setServiceVersion(this.getServiceVersion().getVersion())), + TypeReference.createInstance(BinaryData.class), TypeReference.createInstance(BinaryData.class)); + } + + /** + * Pre-backup operation for checking whether the customer can perform a full backup operation. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     storageResourceUri: String (Optional)
          +     *     token: String (Optional)
          +     *     useManagedIdentity: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     *     jobId: String (Optional)
          +     *     azureStorageBlobContainerUri: String (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param preBackupOperationParameters Optional parameters to validate prior to performing a full backup operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link PollerFlux} for polling of full backup operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public PollerFlux + beginPreFullBackupWithModelAsync(BinaryData preBackupOperationParameters, RequestOptions requestOptions) { + return PollerFlux.create(Duration.ofSeconds(1), + () -> this.preFullBackupWithResponseAsync(preBackupOperationParameters, requestOptions), + new DefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) + + .setContext(requestOptions != null && requestOptions.getContext() != null + ? requestOptions.getContext() + : Context.NONE) + .setServiceVersion(this.getServiceVersion().getVersion())), + TypeReference.createInstance(FullBackupOperation.class), + TypeReference.createInstance(FullBackupOperation.class)); + } + + /** + * Pre-backup operation for checking whether the customer can perform a full backup operation. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     storageResourceUri: String (Optional)
          +     *     token: String (Optional)
          +     *     useManagedIdentity: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     *     jobId: String (Optional)
          +     *     azureStorageBlobContainerUri: String (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param preBackupOperationParameters Optional parameters to validate prior to performing a full backup operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link SyncPoller} for polling of full backup operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller + beginPreFullBackupWithModel(BinaryData preBackupOperationParameters, RequestOptions requestOptions) { + return SyncPoller.createPoller(Duration.ofSeconds(1), + () -> this.preFullBackupWithResponse(preBackupOperationParameters, requestOptions), + new SyncDefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) + + .setContext(requestOptions != null && requestOptions.getContext() != null + ? requestOptions.getContext() + : Context.NONE) + .setServiceVersion(this.getServiceVersion().getVersion())), + TypeReference.createInstance(FullBackupOperation.class), + TypeReference.createInstance(FullBackupOperation.class)); + } + + /** + * Returns the status of restore operation. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     jobId: String (Optional)
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param jobId The Job Id returned part of the restore operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return restore operation along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> restoreStatusWithResponseAsync(String jobId, RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.restoreStatus(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), jobId, accept, requestOptions, context)); + } + + /** + * Returns the status of restore operation. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     jobId: String (Optional)
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param jobId The Job Id returned part of the restore operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return restore operation along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response restoreStatusWithResponse(String jobId, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.restoreStatusSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), jobId, accept, + requestOptions, Context.NONE); + } + + /** + * Pre-restore operation for checking whether the customer can perform a full restore operation. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     sasTokenParameters (Optional): {
          +     *         storageResourceUri: String (Required)
          +     *         token: String (Optional)
          +     *         useManagedIdentity: Boolean (Optional)
          +     *     }
          +     *     folderToRestore: String (Optional)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     jobId: String (Optional)
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param preRestoreOperationParameters Optional pre restore parameters to validate prior to performing a full + * restore operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return restore operation along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> preFullRestoreOperationWithResponseAsync(BinaryData preRestoreOperationParameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext( + context -> service.preFullRestoreOperation(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + contentType, accept, preRestoreOperationParameters, requestOptions, context)); + } + + /** + * Pre-restore operation for checking whether the customer can perform a full restore operation. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     sasTokenParameters (Optional): {
          +     *         storageResourceUri: String (Required)
          +     *         token: String (Optional)
          +     *         useManagedIdentity: Boolean (Optional)
          +     *     }
          +     *     folderToRestore: String (Optional)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     jobId: String (Optional)
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param preRestoreOperationParameters Optional pre restore parameters to validate prior to performing a full + * restore operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return restore operation along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response preFullRestoreOperationWithResponse(BinaryData preRestoreOperationParameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return service.preFullRestoreOperationSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + contentType, accept, preRestoreOperationParameters, requestOptions, Context.NONE); + } + + /** + * Pre-restore operation for checking whether the customer can perform a full restore operation. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     sasTokenParameters (Optional): {
          +     *         storageResourceUri: String (Required)
          +     *         token: String (Optional)
          +     *         useManagedIdentity: Boolean (Optional)
          +     *     }
          +     *     folderToRestore: String (Optional)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     jobId: String (Optional)
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param preRestoreOperationParameters Optional pre restore parameters to validate prior to performing a full + * restore operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link PollerFlux} for polling of restore operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public PollerFlux + beginPreFullRestoreOperationAsync(BinaryData preRestoreOperationParameters, RequestOptions requestOptions) { + return PollerFlux.create(Duration.ofSeconds(1), + () -> this.preFullRestoreOperationWithResponseAsync(preRestoreOperationParameters, requestOptions), + new DefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) + + .setContext(requestOptions != null && requestOptions.getContext() != null + ? requestOptions.getContext() + : Context.NONE) + .setServiceVersion(this.getServiceVersion().getVersion())), + TypeReference.createInstance(BinaryData.class), TypeReference.createInstance(BinaryData.class)); + } + + /** + * Pre-restore operation for checking whether the customer can perform a full restore operation. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     sasTokenParameters (Optional): {
          +     *         storageResourceUri: String (Required)
          +     *         token: String (Optional)
          +     *         useManagedIdentity: Boolean (Optional)
          +     *     }
          +     *     folderToRestore: String (Optional)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     jobId: String (Optional)
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param preRestoreOperationParameters Optional pre restore parameters to validate prior to performing a full + * restore operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link SyncPoller} for polling of restore operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller beginPreFullRestoreOperation(BinaryData preRestoreOperationParameters, + RequestOptions requestOptions) { + return SyncPoller.createPoller(Duration.ofSeconds(1), + () -> this.preFullRestoreOperationWithResponse(preRestoreOperationParameters, requestOptions), + new SyncDefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) + + .setContext(requestOptions != null && requestOptions.getContext() != null + ? requestOptions.getContext() + : Context.NONE) + .setServiceVersion(this.getServiceVersion().getVersion())), + TypeReference.createInstance(BinaryData.class), TypeReference.createInstance(BinaryData.class)); + } + + /** + * Pre-restore operation for checking whether the customer can perform a full restore operation. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     sasTokenParameters (Optional): {
          +     *         storageResourceUri: String (Required)
          +     *         token: String (Optional)
          +     *         useManagedIdentity: Boolean (Optional)
          +     *     }
          +     *     folderToRestore: String (Optional)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     jobId: String (Optional)
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param preRestoreOperationParameters Optional pre restore parameters to validate prior to performing a full + * restore operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link PollerFlux} for polling of restore operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public PollerFlux beginPreFullRestoreOperationWithModelAsync( + BinaryData preRestoreOperationParameters, RequestOptions requestOptions) { + return PollerFlux.create(Duration.ofSeconds(1), + () -> this.preFullRestoreOperationWithResponseAsync(preRestoreOperationParameters, requestOptions), + new DefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) + + .setContext(requestOptions != null && requestOptions.getContext() != null + ? requestOptions.getContext() + : Context.NONE) + .setServiceVersion(this.getServiceVersion().getVersion())), + TypeReference.createInstance(RestoreOperation.class), TypeReference.createInstance(RestoreOperation.class)); + } + + /** + * Pre-restore operation for checking whether the customer can perform a full restore operation. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     sasTokenParameters (Optional): {
          +     *         storageResourceUri: String (Required)
          +     *         token: String (Optional)
          +     *         useManagedIdentity: Boolean (Optional)
          +     *     }
          +     *     folderToRestore: String (Optional)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     jobId: String (Optional)
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param preRestoreOperationParameters Optional pre restore parameters to validate prior to performing a full + * restore operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link SyncPoller} for polling of restore operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller + beginPreFullRestoreOperationWithModel(BinaryData preRestoreOperationParameters, RequestOptions requestOptions) { + return SyncPoller.createPoller(Duration.ofSeconds(1), + () -> this.preFullRestoreOperationWithResponse(preRestoreOperationParameters, requestOptions), + new SyncDefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) + + .setContext(requestOptions != null && requestOptions.getContext() != null + ? requestOptions.getContext() + : Context.NONE) + .setServiceVersion(this.getServiceVersion().getVersion())), + TypeReference.createInstance(RestoreOperation.class), TypeReference.createInstance(RestoreOperation.class)); + } + + /** + * Restores all key materials using the SAS token pointing to a previously stored Azure Blob storage backup folder. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     sasTokenParameters (Required): {
          +     *         storageResourceUri: String (Required)
          +     *         token: String (Optional)
          +     *         useManagedIdentity: Boolean (Optional)
          +     *     }
          +     *     folderToRestore: String (Required)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     jobId: String (Optional)
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup + * was stored. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return restore operation along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> fullRestoreOperationWithResponseAsync(BinaryData restoreBlobDetails, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.fullRestoreOperation(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), contentType, accept, restoreBlobDetails, requestOptions, context)); + } + + /** + * Restores all key materials using the SAS token pointing to a previously stored Azure Blob storage backup folder. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     sasTokenParameters (Required): {
          +     *         storageResourceUri: String (Required)
          +     *         token: String (Optional)
          +     *         useManagedIdentity: Boolean (Optional)
          +     *     }
          +     *     folderToRestore: String (Required)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     jobId: String (Optional)
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup + * was stored. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return restore operation along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response fullRestoreOperationWithResponse(BinaryData restoreBlobDetails, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return service.fullRestoreOperationSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + contentType, accept, restoreBlobDetails, requestOptions, Context.NONE); + } + + /** + * Restores all key materials using the SAS token pointing to a previously stored Azure Blob storage backup folder. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     sasTokenParameters (Required): {
          +     *         storageResourceUri: String (Required)
          +     *         token: String (Optional)
          +     *         useManagedIdentity: Boolean (Optional)
          +     *     }
          +     *     folderToRestore: String (Required)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     jobId: String (Optional)
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup + * was stored. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link PollerFlux} for polling of restore operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public PollerFlux beginFullRestoreOperationAsync(BinaryData restoreBlobDetails, + RequestOptions requestOptions) { + return PollerFlux.create(Duration.ofSeconds(1), + () -> this.fullRestoreOperationWithResponseAsync(restoreBlobDetails, requestOptions), + new DefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) + + .setContext(requestOptions != null && requestOptions.getContext() != null + ? requestOptions.getContext() + : Context.NONE) + .setServiceVersion(this.getServiceVersion().getVersion())), + TypeReference.createInstance(BinaryData.class), TypeReference.createInstance(BinaryData.class)); + } + + /** + * Restores all key materials using the SAS token pointing to a previously stored Azure Blob storage backup folder. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     sasTokenParameters (Required): {
          +     *         storageResourceUri: String (Required)
          +     *         token: String (Optional)
          +     *         useManagedIdentity: Boolean (Optional)
          +     *     }
          +     *     folderToRestore: String (Required)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     jobId: String (Optional)
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup + * was stored. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link SyncPoller} for polling of restore operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller beginFullRestoreOperation(BinaryData restoreBlobDetails, + RequestOptions requestOptions) { + return SyncPoller.createPoller(Duration.ofSeconds(1), + () -> this.fullRestoreOperationWithResponse(restoreBlobDetails, requestOptions), + new SyncDefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) + + .setContext(requestOptions != null && requestOptions.getContext() != null + ? requestOptions.getContext() + : Context.NONE) + .setServiceVersion(this.getServiceVersion().getVersion())), + TypeReference.createInstance(BinaryData.class), TypeReference.createInstance(BinaryData.class)); + } + + /** + * Restores all key materials using the SAS token pointing to a previously stored Azure Blob storage backup folder. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     sasTokenParameters (Required): {
          +     *         storageResourceUri: String (Required)
          +     *         token: String (Optional)
          +     *         useManagedIdentity: Boolean (Optional)
          +     *     }
          +     *     folderToRestore: String (Required)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     jobId: String (Optional)
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup + * was stored. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link PollerFlux} for polling of restore operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public PollerFlux + beginFullRestoreOperationWithModelAsync(BinaryData restoreBlobDetails, RequestOptions requestOptions) { + return PollerFlux.create(Duration.ofSeconds(1), + () -> this.fullRestoreOperationWithResponseAsync(restoreBlobDetails, requestOptions), + new DefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) + + .setContext(requestOptions != null && requestOptions.getContext() != null + ? requestOptions.getContext() + : Context.NONE) + .setServiceVersion(this.getServiceVersion().getVersion())), + TypeReference.createInstance(RestoreOperation.class), TypeReference.createInstance(RestoreOperation.class)); + } + + /** + * Restores all key materials using the SAS token pointing to a previously stored Azure Blob storage backup folder. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     sasTokenParameters (Required): {
          +     *         storageResourceUri: String (Required)
          +     *         token: String (Optional)
          +     *         useManagedIdentity: Boolean (Optional)
          +     *     }
          +     *     folderToRestore: String (Required)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     jobId: String (Optional)
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup + * was stored. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link SyncPoller} for polling of restore operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller + beginFullRestoreOperationWithModel(BinaryData restoreBlobDetails, RequestOptions requestOptions) { + return SyncPoller.createPoller(Duration.ofSeconds(1), + () -> this.fullRestoreOperationWithResponse(restoreBlobDetails, requestOptions), + new SyncDefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) + + .setContext(requestOptions != null && requestOptions.getContext() != null + ? requestOptions.getContext() + : Context.NONE) + .setServiceVersion(this.getServiceVersion().getVersion())), + TypeReference.createInstance(RestoreOperation.class), TypeReference.createInstance(RestoreOperation.class)); + } + + /** + * Returns the status of the selective key restore operation. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     jobId: String (Optional)
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param jobId The Job Id returned part of the restore operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return selective Key Restore operation along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> selectiveKeyRestoreStatusWithResponseAsync(String jobId, + RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.selectiveKeyRestoreStatus(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), jobId, accept, requestOptions, context)); + } + + /** + * Returns the status of the selective key restore operation. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     jobId: String (Optional)
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param jobId The Job Id returned part of the restore operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return selective Key Restore operation along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response selectiveKeyRestoreStatusWithResponse(String jobId, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.selectiveKeyRestoreStatusSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + jobId, accept, requestOptions, Context.NONE); + } + + /** + * Restores all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob + * storage backup folder. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     sasTokenParameters (Required): {
          +     *         storageResourceUri: String (Required)
          +     *         token: String (Optional)
          +     *         useManagedIdentity: Boolean (Optional)
          +     *     }
          +     *     folder: String (Required)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     jobId: String (Optional)
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param keyName The name of the key to be restored from the user supplied backup. + * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup + * was stored. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return selective Key Restore operation along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> selectiveKeyRestoreOperationWithResponseAsync(String keyName, + BinaryData restoreBlobDetails, RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.selectiveKeyRestoreOperation(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), keyName, contentType, accept, restoreBlobDetails, requestOptions, + context)); + } + + /** + * Restores all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob + * storage backup folder. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     sasTokenParameters (Required): {
          +     *         storageResourceUri: String (Required)
          +     *         token: String (Optional)
          +     *         useManagedIdentity: Boolean (Optional)
          +     *     }
          +     *     folder: String (Required)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     jobId: String (Optional)
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param keyName The name of the key to be restored from the user supplied backup. + * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup + * was stored. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return selective Key Restore operation along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response selectiveKeyRestoreOperationWithResponse(String keyName, BinaryData restoreBlobDetails, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return service.selectiveKeyRestoreOperationSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + keyName, contentType, accept, restoreBlobDetails, requestOptions, Context.NONE); + } + + /** + * Restores all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob + * storage backup folder. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     sasTokenParameters (Required): {
          +     *         storageResourceUri: String (Required)
          +     *         token: String (Optional)
          +     *         useManagedIdentity: Boolean (Optional)
          +     *     }
          +     *     folder: String (Required)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     jobId: String (Optional)
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param keyName The name of the key to be restored from the user supplied backup. + * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup + * was stored. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link PollerFlux} for polling of selective Key Restore operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public PollerFlux beginSelectiveKeyRestoreOperationAsync(String keyName, + BinaryData restoreBlobDetails, RequestOptions requestOptions) { + return PollerFlux.create(Duration.ofSeconds(1), + () -> this.selectiveKeyRestoreOperationWithResponseAsync(keyName, restoreBlobDetails, requestOptions), + new DefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) + + .setContext(requestOptions != null && requestOptions.getContext() != null + ? requestOptions.getContext() + : Context.NONE) + .setServiceVersion(this.getServiceVersion().getVersion())), + TypeReference.createInstance(BinaryData.class), TypeReference.createInstance(BinaryData.class)); + } + + /** + * Restores all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob + * storage backup folder. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     sasTokenParameters (Required): {
          +     *         storageResourceUri: String (Required)
          +     *         token: String (Optional)
          +     *         useManagedIdentity: Boolean (Optional)
          +     *     }
          +     *     folder: String (Required)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     jobId: String (Optional)
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param keyName The name of the key to be restored from the user supplied backup. + * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup + * was stored. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link SyncPoller} for polling of selective Key Restore operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller beginSelectiveKeyRestoreOperation(String keyName, + BinaryData restoreBlobDetails, RequestOptions requestOptions) { + return SyncPoller.createPoller(Duration.ofSeconds(1), + () -> this.selectiveKeyRestoreOperationWithResponse(keyName, restoreBlobDetails, requestOptions), + new SyncDefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) + + .setContext(requestOptions != null && requestOptions.getContext() != null + ? requestOptions.getContext() + : Context.NONE) + .setServiceVersion(this.getServiceVersion().getVersion())), + TypeReference.createInstance(BinaryData.class), TypeReference.createInstance(BinaryData.class)); + } + + /** + * Restores all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob + * storage backup folder. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     sasTokenParameters (Required): {
          +     *         storageResourceUri: String (Required)
          +     *         token: String (Optional)
          +     *         useManagedIdentity: Boolean (Optional)
          +     *     }
          +     *     folder: String (Required)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     jobId: String (Optional)
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param keyName The name of the key to be restored from the user supplied backup. + * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup + * was stored. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link PollerFlux} for polling of selective Key Restore operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public PollerFlux + beginSelectiveKeyRestoreOperationWithModelAsync(String keyName, BinaryData restoreBlobDetails, + RequestOptions requestOptions) { + return PollerFlux.create(Duration.ofSeconds(1), + () -> this.selectiveKeyRestoreOperationWithResponseAsync(keyName, restoreBlobDetails, requestOptions), + new DefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) + + .setContext(requestOptions != null && requestOptions.getContext() != null + ? requestOptions.getContext() + : Context.NONE) + .setServiceVersion(this.getServiceVersion().getVersion())), + TypeReference.createInstance(SelectiveKeyRestoreOperation.class), + TypeReference.createInstance(SelectiveKeyRestoreOperation.class)); + } + + /** + * Restores all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob + * storage backup folder. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     sasTokenParameters (Required): {
          +     *         storageResourceUri: String (Required)
          +     *         token: String (Optional)
          +     *         useManagedIdentity: Boolean (Optional)
          +     *     }
          +     *     folder: String (Required)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     status: String(InProgress/Succeeded/Canceled/Failed) (Optional)
          +     *     statusDetails: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     jobId: String (Optional)
          +     *     startTime: Long (Optional)
          +     *     endTime: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param keyName The name of the key to be restored from the user supplied backup. + * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup + * was stored. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link SyncPoller} for polling of selective Key Restore operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller + beginSelectiveKeyRestoreOperationWithModel(String keyName, BinaryData restoreBlobDetails, + RequestOptions requestOptions) { + return SyncPoller.createPoller(Duration.ofSeconds(1), + () -> this.selectiveKeyRestoreOperationWithResponse(keyName, restoreBlobDetails, requestOptions), + new SyncDefaultPollingStrategy<>(new PollingStrategyOptions(this.getHttpPipeline()) + + .setContext(requestOptions != null && requestOptions.getContext() != null + ? requestOptions.getContext() + : Context.NONE) + .setServiceVersion(this.getServiceVersion().getVersion())), + TypeReference.createInstance(SelectiveKeyRestoreOperation.class), + TypeReference.createInstance(SelectiveKeyRestoreOperation.class)); + } + + /** + * Updates key vault account setting, stores it, then returns the setting name and value to the client. + * + * Description of the pool setting to be updated. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: String (Required)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     name: String (Required)
          +     *     value: String (Required)
          +     *     type: String(boolean) (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param settingName The name of the account setting. Must be a valid settings option. + * @param parameters The parameters to update an account setting. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a Key Vault account setting along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> updateSettingWithResponseAsync(String settingName, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.updateSetting(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + settingName, contentType, accept, parameters, requestOptions, context)); + } + + /** + * Updates key vault account setting, stores it, then returns the setting name and value to the client. + * + * Description of the pool setting to be updated. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: String (Required)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     name: String (Required)
          +     *     value: String (Required)
          +     *     type: String(boolean) (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param settingName The name of the account setting. Must be a valid settings option. + * @param parameters The parameters to update an account setting. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a Key Vault account setting along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response updateSettingWithResponse(String settingName, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return service.updateSettingSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), settingName, + contentType, accept, parameters, requestOptions, Context.NONE); + } + + /** + * Get specified account setting object. + * + * Retrieves the setting object of a specified setting name. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     name: String (Required)
          +     *     value: String (Required)
          +     *     type: String(boolean) (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param settingName The name of the account setting. Must be a valid settings option. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return specified account setting object. + * + * Retrieves the setting object of a specified setting name along with {@link Response} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getSettingWithResponseAsync(String settingName, RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.getSetting(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), settingName, accept, requestOptions, context)); + } + + /** + * Get specified account setting object. + * + * Retrieves the setting object of a specified setting name. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     name: String (Required)
          +     *     value: String (Required)
          +     *     type: String(boolean) (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param settingName The name of the account setting. Must be a valid settings option. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return specified account setting object. + * + * Retrieves the setting object of a specified setting name along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getSettingWithResponse(String settingName, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.getSettingSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), settingName, + accept, requestOptions, Context.NONE); + } + + /** + * List account settings. + * + * Retrieves a list of all the available account settings that can be configured. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     settings (Optional): [
          +     *          (Optional){
          +     *             name: String (Required)
          +     *             value: String (Required)
          +     *             type: String(boolean) (Optional)
          +     *         }
          +     *     ]
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the settings list result along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getSettingsWithResponseAsync(RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.getSettings(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), accept, requestOptions, context)); + } + + /** + * List account settings. + * + * Retrieves a list of all the available account settings that can be configured. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     settings (Optional): [
          +     *          (Optional){
          +     *             name: String (Required)
          +     *             value: String (Required)
          +     *             type: String(boolean) (Optional)
          +     *         }
          +     *     ]
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the settings list result along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getSettingsWithResponse(RequestOptions requestOptions) { + final String accept = "application/json"; + return service.getSettingsSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), accept, + requestOptions, Context.NONE); + } +} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultAdministrationUtils.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultAdministrationUtils.java index d93d1e746518..9e995b461f80 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultAdministrationUtils.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultAdministrationUtils.java @@ -3,9 +3,8 @@ package com.azure.security.keyvault.administration.implementation; +import com.azure.core.exception.HttpResponseException; import com.azure.security.keyvault.administration.implementation.models.Error; -import com.azure.security.keyvault.administration.implementation.models.KeyVaultError; -import com.azure.security.keyvault.administration.implementation.models.KeyVaultErrorException; import com.azure.security.keyvault.administration.models.KeyVaultAdministrationError; import com.azure.security.keyvault.administration.models.KeyVaultAdministrationException; @@ -18,57 +17,46 @@ private KeyVaultAdministrationUtils() { } /** - * Convert a {@link KeyVaultErrorException} to a {@link KeyVaultAdministrationException}. + * Convert a {@link HttpResponseException} to a {@link KeyVaultAdministrationException}. * - * @param exception The {@link KeyVaultErrorException}. + * @param exception The {@link HttpResponseException}. * * @return An instance of the public {@link KeyVaultAdministrationException}. */ - public static KeyVaultAdministrationException toKeyVaultAdministrationException(KeyVaultErrorException exception) { + public static KeyVaultAdministrationException toKeyVaultAdministrationException(HttpResponseException exception) { if (exception == null) { return null; } return new KeyVaultAdministrationException(exception.getMessage(), exception.getResponse(), - toKeyVaultError(exception.getValue())); + toKeyVaultAdministrationError(exception.getValue())); } /** - * Convert an implementation {@link KeyVaultError} to a public {@link KeyVaultAdministrationError}. + * Convert an implementation {@link Error} to a public {@link KeyVaultAdministrationError}. * - * @param keyVaultError The {@link KeyVaultError} returned by the service. + * @param value The {@link Error} returned by the service. * * @return An instance of the public {@link KeyVaultAdministrationError}. */ - public static KeyVaultAdministrationError toKeyVaultError(KeyVaultError keyVaultError) { - - if (keyVaultError == null) { + public static KeyVaultAdministrationError toKeyVaultAdministrationError(Object value) { + if (value == null) { return null; - } - - return createKeyVaultErrorFromError(keyVaultError.getError()); - } + } else { + if (value instanceof Error) { + Error error = (Error) value; - /** - * Convert an error {@link Error} internal to an implementation {@link KeyVaultError} to a public - * {@link KeyVaultAdministrationError}. - * - * @param error The {@link Error} internal to an implementation {@link KeyVaultError} returned by the service. - * - * @return An instance of the public {@link KeyVaultAdministrationError}. - */ - public static KeyVaultAdministrationError createKeyVaultErrorFromError(Error error) { - if (error == null) { - return null; + return new KeyVaultAdministrationError(error.getCode(), error.getMessage(), + toKeyVaultAdministrationError(error.getInnerError())); + } else { + return new KeyVaultAdministrationError("ServiceError", value.toString(), null); + } } - - return new KeyVaultAdministrationError(error.getCode(), error.getMessage(), - createKeyVaultErrorFromError(error.getInnerError())); } /** * Maps a {@link Throwable} to {@link KeyVaultAdministrationException} if it's an instance of - * {@link KeyVaultErrorException}, else it returns the original throwable. + * {@link HttpResponseException}, else it returns the original throwable. * * @param throwable A {@link Throwable}. * @@ -76,8 +64,8 @@ public static KeyVaultAdministrationError createKeyVaultErrorFromError(Error err * original {@link Throwable}. */ public static Throwable mapThrowableToKeyVaultAdministrationException(Throwable throwable) { - if (throwable instanceof KeyVaultErrorException) { - return toKeyVaultAdministrationException((KeyVaultErrorException) throwable); + if (throwable instanceof HttpResponseException) { + return toKeyVaultAdministrationException((HttpResponseException) throwable); } else { return throwable; } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultBackupClientImpl.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultBackupClientImpl.java deleted file mode 100644 index 099301425f25..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultBackupClientImpl.java +++ /dev/null @@ -1,1401 +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.security.keyvault.administration.implementation; - -import com.azure.core.annotation.BodyParam; -import com.azure.core.annotation.ExpectedResponses; -import com.azure.core.annotation.Get; -import com.azure.core.annotation.HeaderParam; -import com.azure.core.annotation.Host; -import com.azure.core.annotation.HostParam; -import com.azure.core.annotation.PathParam; -import com.azure.core.annotation.Post; -import com.azure.core.annotation.Put; -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.HttpPipeline; -import com.azure.core.http.HttpPipelineBuilder; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.http.policy.UserAgentPolicy; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.ResponseBase; -import com.azure.core.http.rest.RestProxy; -import com.azure.core.util.Context; -import com.azure.core.util.FluxUtil; -import com.azure.core.util.serializer.JacksonAdapter; -import com.azure.core.util.serializer.SerializerAdapter; -import com.azure.security.keyvault.administration.implementation.models.FullBackupHeaders; -import com.azure.security.keyvault.administration.implementation.models.FullBackupOperation; -import com.azure.security.keyvault.administration.implementation.models.FullRestoreOperationHeaders; -import com.azure.security.keyvault.administration.implementation.models.KeyVaultErrorException; -import com.azure.security.keyvault.administration.implementation.models.PreBackupOperationParameters; -import com.azure.security.keyvault.administration.implementation.models.PreFullBackupHeaders; -import com.azure.security.keyvault.administration.implementation.models.PreFullRestoreOperationHeaders; -import com.azure.security.keyvault.administration.implementation.models.PreRestoreOperationParameters; -import com.azure.security.keyvault.administration.implementation.models.RestoreOperation; -import com.azure.security.keyvault.administration.implementation.models.RestoreOperationParameters; -import com.azure.security.keyvault.administration.implementation.models.SASTokenParameter; -import com.azure.security.keyvault.administration.implementation.models.SelectiveKeyRestoreOperation; -import com.azure.security.keyvault.administration.implementation.models.SelectiveKeyRestoreOperationHeaders; -import com.azure.security.keyvault.administration.implementation.models.SelectiveKeyRestoreOperationParameters; -import reactor.core.publisher.Mono; - -/** - * Initializes a new instance of the KeyVaultBackupClient type. - */ -public final class KeyVaultBackupClientImpl { - /** - * The proxy service used to perform REST calls. - */ - private final KeyVaultBackupClientService service; - - /** - * 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; - } - - /** - * Initializes an instance of KeyVaultBackupClient client. - * - * @param apiVersion Api Version. - */ - public KeyVaultBackupClientImpl(String apiVersion) { - this(new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build(), - JacksonAdapter.createDefaultSerializerAdapter(), apiVersion); - } - - /** - * Initializes an instance of KeyVaultBackupClient client. - * - * @param httpPipeline The HTTP pipeline to send requests through. - * @param apiVersion Api Version. - */ - public KeyVaultBackupClientImpl(HttpPipeline httpPipeline, String apiVersion) { - this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), apiVersion); - } - - /** - * Initializes an instance of KeyVaultBackupClient client. - * - * @param httpPipeline The HTTP pipeline to send requests through. - * @param serializerAdapter The serializer to serialize an object into a string. - * @param apiVersion Api Version. - */ - public KeyVaultBackupClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String apiVersion) { - this.httpPipeline = httpPipeline; - this.serializerAdapter = serializerAdapter; - this.apiVersion = apiVersion; - this.service - = RestProxy.create(KeyVaultBackupClientService.class, this.httpPipeline, this.getSerializerAdapter()); - } - - /** - * The interface defining all the services for KeyVaultBackupClient to be used by the proxy service to perform REST - * calls. - */ - @Host("{vaultBaseUrl}") - @ServiceInterface(name = "KeyVaultBackupClient") - public interface KeyVaultBackupClientService { - @Post("/backup") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> fullBackup( - @HostParam("vaultBaseUrl") String vaultBaseUrl, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") SASTokenParameter azureStorageBlobContainerUri, - @HeaderParam("Accept") String accept, Context context); - - @Post("/backup") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> fullBackupNoCustomHeaders(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") SASTokenParameter azureStorageBlobContainerUri, - @HeaderParam("Accept") String accept, Context context); - - @Post("/backup") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - ResponseBase fullBackupSync( - @HostParam("vaultBaseUrl") String vaultBaseUrl, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") SASTokenParameter azureStorageBlobContainerUri, - @HeaderParam("Accept") String accept, Context context); - - @Post("/backup") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response fullBackupNoCustomHeadersSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") SASTokenParameter azureStorageBlobContainerUri, - @HeaderParam("Accept") String accept, Context context); - - @Post("/prebackup") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> preFullBackup( - @HostParam("vaultBaseUrl") String vaultBaseUrl, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") PreBackupOperationParameters preBackupOperationParameters, - @HeaderParam("Accept") String accept, Context context); - - @Post("/prebackup") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> preFullBackupNoCustomHeaders(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") PreBackupOperationParameters preBackupOperationParameters, - @HeaderParam("Accept") String accept, Context context); - - @Post("/prebackup") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - ResponseBase preFullBackupSync( - @HostParam("vaultBaseUrl") String vaultBaseUrl, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") PreBackupOperationParameters preBackupOperationParameters, - @HeaderParam("Accept") String accept, Context context); - - @Post("/prebackup") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response preFullBackupNoCustomHeadersSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") PreBackupOperationParameters preBackupOperationParameters, - @HeaderParam("Accept") String accept, Context context); - - @Get("/backup/{jobId}/pending") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> fullBackupStatus(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("jobId") String jobId, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Get("/backup/{jobId}/pending") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response fullBackupStatusSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("jobId") String jobId, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Put("/prerestore") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> preFullRestoreOperation( - @HostParam("vaultBaseUrl") String vaultBaseUrl, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") PreRestoreOperationParameters preRestoreOperationParameters, - @HeaderParam("Accept") String accept, Context context); - - @Put("/prerestore") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> preFullRestoreOperationNoCustomHeaders( - @HostParam("vaultBaseUrl") String vaultBaseUrl, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") PreRestoreOperationParameters preRestoreOperationParameters, - @HeaderParam("Accept") String accept, Context context); - - @Put("/prerestore") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - ResponseBase preFullRestoreOperationSync( - @HostParam("vaultBaseUrl") String vaultBaseUrl, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") PreRestoreOperationParameters preRestoreOperationParameters, - @HeaderParam("Accept") String accept, Context context); - - @Put("/prerestore") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response preFullRestoreOperationNoCustomHeadersSync( - @HostParam("vaultBaseUrl") String vaultBaseUrl, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") PreRestoreOperationParameters preRestoreOperationParameters, - @HeaderParam("Accept") String accept, Context context); - - @Put("/restore") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> fullRestoreOperation( - @HostParam("vaultBaseUrl") String vaultBaseUrl, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") RestoreOperationParameters restoreBlobDetails, - @HeaderParam("Accept") String accept, Context context); - - @Put("/restore") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> fullRestoreOperationNoCustomHeaders( - @HostParam("vaultBaseUrl") String vaultBaseUrl, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") RestoreOperationParameters restoreBlobDetails, - @HeaderParam("Accept") String accept, Context context); - - @Put("/restore") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - ResponseBase fullRestoreOperationSync( - @HostParam("vaultBaseUrl") String vaultBaseUrl, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") RestoreOperationParameters restoreBlobDetails, - @HeaderParam("Accept") String accept, Context context); - - @Put("/restore") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response fullRestoreOperationNoCustomHeadersSync( - @HostParam("vaultBaseUrl") String vaultBaseUrl, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") RestoreOperationParameters restoreBlobDetails, - @HeaderParam("Accept") String accept, Context context); - - @Get("/restore/{jobId}/pending") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> restoreStatus(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("jobId") String jobId, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Get("/restore/{jobId}/pending") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response restoreStatusSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("jobId") String jobId, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Put("/keys/{keyName}/restore") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> - selectiveKeyRestoreOperation(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("keyName") String keyName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") SelectiveKeyRestoreOperationParameters restoreBlobDetails, - @HeaderParam("Accept") String accept, Context context); - - @Put("/keys/{keyName}/restore") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> selectiveKeyRestoreOperationNoCustomHeaders( - @HostParam("vaultBaseUrl") String vaultBaseUrl, @PathParam("keyName") String keyName, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") SelectiveKeyRestoreOperationParameters restoreBlobDetails, - @HeaderParam("Accept") String accept, Context context); - - @Put("/keys/{keyName}/restore") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - ResponseBase - selectiveKeyRestoreOperationSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("keyName") String keyName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") SelectiveKeyRestoreOperationParameters restoreBlobDetails, - @HeaderParam("Accept") String accept, Context context); - - @Put("/keys/{keyName}/restore") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response selectiveKeyRestoreOperationNoCustomHeadersSync( - @HostParam("vaultBaseUrl") String vaultBaseUrl, @PathParam("keyName") String keyName, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") SelectiveKeyRestoreOperationParameters restoreBlobDetails, - @HeaderParam("Accept") String accept, Context context); - } - - /** - * Creates a full backup using a user-provided SAS token to an Azure blob storage container. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param azureStorageBlobContainerUri Azure blob shared access signature token pointing to a valid Azure blob - * container where full backup needs to be stored. This token needs to be valid for at least next 24 hours from the - * time of making this call. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return full backup operation along with {@link ResponseBase} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> fullBackupWithResponseAsync(String vaultBaseUrl, - SASTokenParameter azureStorageBlobContainerUri) { - return FluxUtil - .withContext(context -> fullBackupWithResponseAsync(vaultBaseUrl, azureStorageBlobContainerUri, context)); - } - - /** - * Creates a full backup using a user-provided SAS token to an Azure blob storage container. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param azureStorageBlobContainerUri Azure blob shared access signature token pointing to a valid Azure blob - * container where full backup needs to be stored. This token needs to be valid for at least next 24 hours from the - * time of making this call. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return full backup operation along with {@link ResponseBase} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> fullBackupWithResponseAsync(String vaultBaseUrl, - SASTokenParameter azureStorageBlobContainerUri, Context context) { - final String accept = "application/json"; - return service.fullBackup(vaultBaseUrl, this.getApiVersion(), azureStorageBlobContainerUri, accept, context); - } - - /** - * Creates a full backup using a user-provided SAS token to an Azure blob storage container. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param azureStorageBlobContainerUri Azure blob shared access signature token pointing to a valid Azure blob - * container where full backup needs to be stored. This token needs to be valid for at least next 24 hours from the - * time of making this call. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return full backup operation on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono fullBackupAsync(String vaultBaseUrl, - SASTokenParameter azureStorageBlobContainerUri) { - return fullBackupWithResponseAsync(vaultBaseUrl, azureStorageBlobContainerUri) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a full backup using a user-provided SAS token to an Azure blob storage container. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param azureStorageBlobContainerUri Azure blob shared access signature token pointing to a valid Azure blob - * container where full backup needs to be stored. This token needs to be valid for at least next 24 hours from the - * time of making this call. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return full backup operation on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono fullBackupAsync(String vaultBaseUrl, - SASTokenParameter azureStorageBlobContainerUri, Context context) { - return fullBackupWithResponseAsync(vaultBaseUrl, azureStorageBlobContainerUri, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a full backup using a user-provided SAS token to an Azure blob storage container. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param azureStorageBlobContainerUri Azure blob shared access signature token pointing to a valid Azure blob - * container where full backup needs to be stored. This token needs to be valid for at least next 24 hours from the - * time of making this call. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return full backup operation along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> fullBackupNoCustomHeadersWithResponseAsync(String vaultBaseUrl, - SASTokenParameter azureStorageBlobContainerUri) { - return FluxUtil.withContext( - context -> fullBackupNoCustomHeadersWithResponseAsync(vaultBaseUrl, azureStorageBlobContainerUri, context)); - } - - /** - * Creates a full backup using a user-provided SAS token to an Azure blob storage container. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param azureStorageBlobContainerUri Azure blob shared access signature token pointing to a valid Azure blob - * container where full backup needs to be stored. This token needs to be valid for at least next 24 hours from the - * time of making this call. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return full backup operation along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> fullBackupNoCustomHeadersWithResponseAsync(String vaultBaseUrl, - SASTokenParameter azureStorageBlobContainerUri, Context context) { - final String accept = "application/json"; - return service.fullBackupNoCustomHeaders(vaultBaseUrl, this.getApiVersion(), azureStorageBlobContainerUri, - accept, context); - } - - /** - * Creates a full backup using a user-provided SAS token to an Azure blob storage container. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param azureStorageBlobContainerUri Azure blob shared access signature token pointing to a valid Azure blob - * container where full backup needs to be stored. This token needs to be valid for at least next 24 hours from the - * time of making this call. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return full backup operation along with {@link ResponseBase}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public ResponseBase fullBackupWithResponse(String vaultBaseUrl, - SASTokenParameter azureStorageBlobContainerUri, Context context) { - final String accept = "application/json"; - return service.fullBackupSync(vaultBaseUrl, this.getApiVersion(), azureStorageBlobContainerUri, accept, - context); - } - - /** - * Creates a full backup using a user-provided SAS token to an Azure blob storage container. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param azureStorageBlobContainerUri Azure blob shared access signature token pointing to a valid Azure blob - * container where full backup needs to be stored. This token needs to be valid for at least next 24 hours from the - * time of making this call. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return full backup operation. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public FullBackupOperation fullBackup(String vaultBaseUrl, SASTokenParameter azureStorageBlobContainerUri) { - return fullBackupWithResponse(vaultBaseUrl, azureStorageBlobContainerUri, Context.NONE).getValue(); - } - - /** - * Creates a full backup using a user-provided SAS token to an Azure blob storage container. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param azureStorageBlobContainerUri Azure blob shared access signature token pointing to a valid Azure blob - * container where full backup needs to be stored. This token needs to be valid for at least next 24 hours from the - * time of making this call. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return full backup operation along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response fullBackupNoCustomHeadersWithResponse(String vaultBaseUrl, - SASTokenParameter azureStorageBlobContainerUri, Context context) { - final String accept = "application/json"; - return service.fullBackupNoCustomHeadersSync(vaultBaseUrl, this.getApiVersion(), azureStorageBlobContainerUri, - accept, context); - } - - /** - * Pre-backup operation for checking whether the customer can perform a full backup operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param preBackupOperationParameters Optional parameters to validate prior to performing a full backup operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return full backup operation along with {@link ResponseBase} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> - preFullBackupWithResponseAsync(String vaultBaseUrl, PreBackupOperationParameters preBackupOperationParameters) { - return FluxUtil.withContext( - context -> preFullBackupWithResponseAsync(vaultBaseUrl, preBackupOperationParameters, context)); - } - - /** - * Pre-backup operation for checking whether the customer can perform a full backup operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param preBackupOperationParameters Optional parameters to validate prior to performing a full backup operation. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return full backup operation along with {@link ResponseBase} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> preFullBackupWithResponseAsync( - String vaultBaseUrl, PreBackupOperationParameters preBackupOperationParameters, Context context) { - final String accept = "application/json"; - return service.preFullBackup(vaultBaseUrl, this.getApiVersion(), preBackupOperationParameters, accept, context); - } - - /** - * Pre-backup operation for checking whether the customer can perform a full backup operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param preBackupOperationParameters Optional parameters to validate prior to performing a full backup operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return full backup operation on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono preFullBackupAsync(String vaultBaseUrl, - PreBackupOperationParameters preBackupOperationParameters) { - return preFullBackupWithResponseAsync(vaultBaseUrl, preBackupOperationParameters) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Pre-backup operation for checking whether the customer can perform a full backup operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param preBackupOperationParameters Optional parameters to validate prior to performing a full backup operation. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return full backup operation on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono preFullBackupAsync(String vaultBaseUrl, - PreBackupOperationParameters preBackupOperationParameters, Context context) { - return preFullBackupWithResponseAsync(vaultBaseUrl, preBackupOperationParameters, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Pre-backup operation for checking whether the customer can perform a full backup operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param preBackupOperationParameters Optional parameters to validate prior to performing a full backup operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return full backup operation along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> preFullBackupNoCustomHeadersWithResponseAsync(String vaultBaseUrl, - PreBackupOperationParameters preBackupOperationParameters) { - return FluxUtil.withContext(context -> preFullBackupNoCustomHeadersWithResponseAsync(vaultBaseUrl, - preBackupOperationParameters, context)); - } - - /** - * Pre-backup operation for checking whether the customer can perform a full backup operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param preBackupOperationParameters Optional parameters to validate prior to performing a full backup operation. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return full backup operation along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> preFullBackupNoCustomHeadersWithResponseAsync(String vaultBaseUrl, - PreBackupOperationParameters preBackupOperationParameters, Context context) { - final String accept = "application/json"; - return service.preFullBackupNoCustomHeaders(vaultBaseUrl, this.getApiVersion(), preBackupOperationParameters, - accept, context); - } - - /** - * Pre-backup operation for checking whether the customer can perform a full backup operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param preBackupOperationParameters Optional parameters to validate prior to performing a full backup operation. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return full backup operation along with {@link ResponseBase}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public ResponseBase preFullBackupWithResponse(String vaultBaseUrl, - PreBackupOperationParameters preBackupOperationParameters, Context context) { - final String accept = "application/json"; - return service.preFullBackupSync(vaultBaseUrl, this.getApiVersion(), preBackupOperationParameters, accept, - context); - } - - /** - * Pre-backup operation for checking whether the customer can perform a full backup operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param preBackupOperationParameters Optional parameters to validate prior to performing a full backup operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return full backup operation. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public FullBackupOperation preFullBackup(String vaultBaseUrl, - PreBackupOperationParameters preBackupOperationParameters) { - return preFullBackupWithResponse(vaultBaseUrl, preBackupOperationParameters, Context.NONE).getValue(); - } - - /** - * Pre-backup operation for checking whether the customer can perform a full backup operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param preBackupOperationParameters Optional parameters to validate prior to performing a full backup operation. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return full backup operation along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response preFullBackupNoCustomHeadersWithResponse(String vaultBaseUrl, - PreBackupOperationParameters preBackupOperationParameters, Context context) { - final String accept = "application/json"; - return service.preFullBackupNoCustomHeadersSync(vaultBaseUrl, this.getApiVersion(), - preBackupOperationParameters, accept, context); - } - - /** - * Returns the status of full backup operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param jobId The id returned as part of the backup request. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return full backup operation along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> fullBackupStatusWithResponseAsync(String vaultBaseUrl, String jobId) { - return FluxUtil.withContext(context -> fullBackupStatusWithResponseAsync(vaultBaseUrl, jobId, context)); - } - - /** - * Returns the status of full backup operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param jobId The id returned as part of the backup request. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return full backup operation along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> fullBackupStatusWithResponseAsync(String vaultBaseUrl, String jobId, - Context context) { - final String accept = "application/json"; - return service.fullBackupStatus(vaultBaseUrl, jobId, this.getApiVersion(), accept, context); - } - - /** - * Returns the status of full backup operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param jobId The id returned as part of the backup request. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return full backup operation on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono fullBackupStatusAsync(String vaultBaseUrl, String jobId) { - return fullBackupStatusWithResponseAsync(vaultBaseUrl, jobId).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Returns the status of full backup operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param jobId The id returned as part of the backup request. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return full backup operation on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono fullBackupStatusAsync(String vaultBaseUrl, String jobId, Context context) { - return fullBackupStatusWithResponseAsync(vaultBaseUrl, jobId, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Returns the status of full backup operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param jobId The id returned as part of the backup request. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return full backup operation along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response fullBackupStatusWithResponse(String vaultBaseUrl, String jobId, - Context context) { - final String accept = "application/json"; - return service.fullBackupStatusSync(vaultBaseUrl, jobId, this.getApiVersion(), accept, context); - } - - /** - * Returns the status of full backup operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param jobId The id returned as part of the backup request. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return full backup operation. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public FullBackupOperation fullBackupStatus(String vaultBaseUrl, String jobId) { - return fullBackupStatusWithResponse(vaultBaseUrl, jobId, Context.NONE).getValue(); - } - - /** - * Pre-restore operation for checking whether the customer can perform a full restore operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param preRestoreOperationParameters Optional pre restore parameters to validate prior to performing a full - * restore operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return restore operation along with {@link ResponseBase} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> - preFullRestoreOperationWithResponseAsync(String vaultBaseUrl, - PreRestoreOperationParameters preRestoreOperationParameters) { - return FluxUtil.withContext( - context -> preFullRestoreOperationWithResponseAsync(vaultBaseUrl, preRestoreOperationParameters, context)); - } - - /** - * Pre-restore operation for checking whether the customer can perform a full restore operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param preRestoreOperationParameters Optional pre restore parameters to validate prior to performing a full - * restore operation. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return restore operation along with {@link ResponseBase} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> - preFullRestoreOperationWithResponseAsync(String vaultBaseUrl, - PreRestoreOperationParameters preRestoreOperationParameters, Context context) { - final String accept = "application/json"; - return service.preFullRestoreOperation(vaultBaseUrl, this.getApiVersion(), preRestoreOperationParameters, - accept, context); - } - - /** - * Pre-restore operation for checking whether the customer can perform a full restore operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param preRestoreOperationParameters Optional pre restore parameters to validate prior to performing a full - * restore operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return restore operation on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono preFullRestoreOperationAsync(String vaultBaseUrl, - PreRestoreOperationParameters preRestoreOperationParameters) { - return preFullRestoreOperationWithResponseAsync(vaultBaseUrl, preRestoreOperationParameters) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Pre-restore operation for checking whether the customer can perform a full restore operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param preRestoreOperationParameters Optional pre restore parameters to validate prior to performing a full - * restore operation. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return restore operation on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono preFullRestoreOperationAsync(String vaultBaseUrl, - PreRestoreOperationParameters preRestoreOperationParameters, Context context) { - return preFullRestoreOperationWithResponseAsync(vaultBaseUrl, preRestoreOperationParameters, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Pre-restore operation for checking whether the customer can perform a full restore operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param preRestoreOperationParameters Optional pre restore parameters to validate prior to performing a full - * restore operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return restore operation along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> preFullRestoreOperationNoCustomHeadersWithResponseAsync(String vaultBaseUrl, - PreRestoreOperationParameters preRestoreOperationParameters) { - return FluxUtil.withContext(context -> preFullRestoreOperationNoCustomHeadersWithResponseAsync(vaultBaseUrl, - preRestoreOperationParameters, context)); - } - - /** - * Pre-restore operation for checking whether the customer can perform a full restore operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param preRestoreOperationParameters Optional pre restore parameters to validate prior to performing a full - * restore operation. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return restore operation along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> preFullRestoreOperationNoCustomHeadersWithResponseAsync(String vaultBaseUrl, - PreRestoreOperationParameters preRestoreOperationParameters, Context context) { - final String accept = "application/json"; - return service.preFullRestoreOperationNoCustomHeaders(vaultBaseUrl, this.getApiVersion(), - preRestoreOperationParameters, accept, context); - } - - /** - * Pre-restore operation for checking whether the customer can perform a full restore operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param preRestoreOperationParameters Optional pre restore parameters to validate prior to performing a full - * restore operation. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return restore operation along with {@link ResponseBase}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public ResponseBase preFullRestoreOperationWithResponse( - String vaultBaseUrl, PreRestoreOperationParameters preRestoreOperationParameters, Context context) { - final String accept = "application/json"; - return service.preFullRestoreOperationSync(vaultBaseUrl, this.getApiVersion(), preRestoreOperationParameters, - accept, context); - } - - /** - * Pre-restore operation for checking whether the customer can perform a full restore operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param preRestoreOperationParameters Optional pre restore parameters to validate prior to performing a full - * restore operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return restore operation. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public RestoreOperation preFullRestoreOperation(String vaultBaseUrl, - PreRestoreOperationParameters preRestoreOperationParameters) { - return preFullRestoreOperationWithResponse(vaultBaseUrl, preRestoreOperationParameters, Context.NONE) - .getValue(); - } - - /** - * Pre-restore operation for checking whether the customer can perform a full restore operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param preRestoreOperationParameters Optional pre restore parameters to validate prior to performing a full - * restore operation. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return restore operation along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response preFullRestoreOperationNoCustomHeadersWithResponse(String vaultBaseUrl, - PreRestoreOperationParameters preRestoreOperationParameters, Context context) { - final String accept = "application/json"; - return service.preFullRestoreOperationNoCustomHeadersSync(vaultBaseUrl, this.getApiVersion(), - preRestoreOperationParameters, accept, context); - } - - /** - * Restores all key materials using the SAS token pointing to a previously stored Azure Blob storage backup folder. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return restore operation along with {@link ResponseBase} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> - fullRestoreOperationWithResponseAsync(String vaultBaseUrl, RestoreOperationParameters restoreBlobDetails) { - return FluxUtil - .withContext(context -> fullRestoreOperationWithResponseAsync(vaultBaseUrl, restoreBlobDetails, context)); - } - - /** - * Restores all key materials using the SAS token pointing to a previously stored Azure Blob storage backup folder. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return restore operation along with {@link ResponseBase} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> fullRestoreOperationWithResponseAsync( - String vaultBaseUrl, RestoreOperationParameters restoreBlobDetails, Context context) { - final String accept = "application/json"; - return service.fullRestoreOperation(vaultBaseUrl, this.getApiVersion(), restoreBlobDetails, accept, context); - } - - /** - * Restores all key materials using the SAS token pointing to a previously stored Azure Blob storage backup folder. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return restore operation on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono fullRestoreOperationAsync(String vaultBaseUrl, - RestoreOperationParameters restoreBlobDetails) { - return fullRestoreOperationWithResponseAsync(vaultBaseUrl, restoreBlobDetails) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Restores all key materials using the SAS token pointing to a previously stored Azure Blob storage backup folder. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return restore operation on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono fullRestoreOperationAsync(String vaultBaseUrl, - RestoreOperationParameters restoreBlobDetails, Context context) { - return fullRestoreOperationWithResponseAsync(vaultBaseUrl, restoreBlobDetails, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Restores all key materials using the SAS token pointing to a previously stored Azure Blob storage backup folder. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return restore operation along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> fullRestoreOperationNoCustomHeadersWithResponseAsync(String vaultBaseUrl, - RestoreOperationParameters restoreBlobDetails) { - return FluxUtil.withContext( - context -> fullRestoreOperationNoCustomHeadersWithResponseAsync(vaultBaseUrl, restoreBlobDetails, context)); - } - - /** - * Restores all key materials using the SAS token pointing to a previously stored Azure Blob storage backup folder. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return restore operation along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> fullRestoreOperationNoCustomHeadersWithResponseAsync(String vaultBaseUrl, - RestoreOperationParameters restoreBlobDetails, Context context) { - final String accept = "application/json"; - return service.fullRestoreOperationNoCustomHeaders(vaultBaseUrl, this.getApiVersion(), restoreBlobDetails, - accept, context); - } - - /** - * Restores all key materials using the SAS token pointing to a previously stored Azure Blob storage backup folder. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return restore operation along with {@link ResponseBase}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public ResponseBase fullRestoreOperationWithResponse( - String vaultBaseUrl, RestoreOperationParameters restoreBlobDetails, Context context) { - final String accept = "application/json"; - return service.fullRestoreOperationSync(vaultBaseUrl, this.getApiVersion(), restoreBlobDetails, accept, - context); - } - - /** - * Restores all key materials using the SAS token pointing to a previously stored Azure Blob storage backup folder. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return restore operation. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public RestoreOperation fullRestoreOperation(String vaultBaseUrl, RestoreOperationParameters restoreBlobDetails) { - return fullRestoreOperationWithResponse(vaultBaseUrl, restoreBlobDetails, Context.NONE).getValue(); - } - - /** - * Restores all key materials using the SAS token pointing to a previously stored Azure Blob storage backup folder. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return restore operation along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response fullRestoreOperationNoCustomHeadersWithResponse(String vaultBaseUrl, - RestoreOperationParameters restoreBlobDetails, Context context) { - final String accept = "application/json"; - return service.fullRestoreOperationNoCustomHeadersSync(vaultBaseUrl, this.getApiVersion(), restoreBlobDetails, - accept, context); - } - - /** - * Returns the status of restore operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param jobId The Job Id returned part of the restore operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return restore operation along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> restoreStatusWithResponseAsync(String vaultBaseUrl, String jobId) { - return FluxUtil.withContext(context -> restoreStatusWithResponseAsync(vaultBaseUrl, jobId, context)); - } - - /** - * Returns the status of restore operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param jobId The Job Id returned part of the restore operation. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return restore operation along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> restoreStatusWithResponseAsync(String vaultBaseUrl, String jobId, - Context context) { - final String accept = "application/json"; - return service.restoreStatus(vaultBaseUrl, jobId, this.getApiVersion(), accept, context); - } - - /** - * Returns the status of restore operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param jobId The Job Id returned part of the restore operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return restore operation on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono restoreStatusAsync(String vaultBaseUrl, String jobId) { - return restoreStatusWithResponseAsync(vaultBaseUrl, jobId).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Returns the status of restore operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param jobId The Job Id returned part of the restore operation. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return restore operation on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono restoreStatusAsync(String vaultBaseUrl, String jobId, Context context) { - return restoreStatusWithResponseAsync(vaultBaseUrl, jobId, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Returns the status of restore operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param jobId The Job Id returned part of the restore operation. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return restore operation along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response restoreStatusWithResponse(String vaultBaseUrl, String jobId, Context context) { - final String accept = "application/json"; - return service.restoreStatusSync(vaultBaseUrl, jobId, this.getApiVersion(), accept, context); - } - - /** - * Returns the status of restore operation. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param jobId The Job Id returned part of the restore operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return restore operation. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public RestoreOperation restoreStatus(String vaultBaseUrl, String jobId) { - return restoreStatusWithResponse(vaultBaseUrl, jobId, Context.NONE).getValue(); - } - - /** - * Restores all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob - * storage backup folder. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to be restored from the user supplied backup. - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return selective Key Restore operation along with {@link ResponseBase} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> - selectiveKeyRestoreOperationWithResponseAsync(String vaultBaseUrl, String keyName, - SelectiveKeyRestoreOperationParameters restoreBlobDetails) { - return FluxUtil.withContext(context -> selectiveKeyRestoreOperationWithResponseAsync(vaultBaseUrl, keyName, - restoreBlobDetails, context)); - } - - /** - * Restores all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob - * storage backup folder. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to be restored from the user supplied backup. - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return selective Key Restore operation along with {@link ResponseBase} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> - selectiveKeyRestoreOperationWithResponseAsync(String vaultBaseUrl, String keyName, - SelectiveKeyRestoreOperationParameters restoreBlobDetails, Context context) { - final String accept = "application/json"; - return service.selectiveKeyRestoreOperation(vaultBaseUrl, keyName, this.getApiVersion(), restoreBlobDetails, - accept, context); - } - - /** - * Restores all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob - * storage backup folder. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to be restored from the user supplied backup. - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return selective Key Restore operation on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono selectiveKeyRestoreOperationAsync(String vaultBaseUrl, String keyName, - SelectiveKeyRestoreOperationParameters restoreBlobDetails) { - return selectiveKeyRestoreOperationWithResponseAsync(vaultBaseUrl, keyName, restoreBlobDetails) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Restores all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob - * storage backup folder. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to be restored from the user supplied backup. - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return selective Key Restore operation on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono selectiveKeyRestoreOperationAsync(String vaultBaseUrl, String keyName, - SelectiveKeyRestoreOperationParameters restoreBlobDetails, Context context) { - return selectiveKeyRestoreOperationWithResponseAsync(vaultBaseUrl, keyName, restoreBlobDetails, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Restores all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob - * storage backup folder. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to be restored from the user supplied backup. - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return selective Key Restore operation along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> selectiveKeyRestoreOperationNoCustomHeadersWithResponseAsync( - String vaultBaseUrl, String keyName, SelectiveKeyRestoreOperationParameters restoreBlobDetails) { - return FluxUtil - .withContext(context -> selectiveKeyRestoreOperationNoCustomHeadersWithResponseAsync(vaultBaseUrl, keyName, - restoreBlobDetails, context)); - } - - /** - * Restores all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob - * storage backup folder. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to be restored from the user supplied backup. - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return selective Key Restore operation along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> selectiveKeyRestoreOperationNoCustomHeadersWithResponseAsync( - String vaultBaseUrl, String keyName, SelectiveKeyRestoreOperationParameters restoreBlobDetails, - Context context) { - final String accept = "application/json"; - return service.selectiveKeyRestoreOperationNoCustomHeaders(vaultBaseUrl, keyName, this.getApiVersion(), - restoreBlobDetails, accept, context); - } - - /** - * Restores all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob - * storage backup folder. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to be restored from the user supplied backup. - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return selective Key Restore operation along with {@link ResponseBase}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public ResponseBase - selectiveKeyRestoreOperationWithResponse(String vaultBaseUrl, String keyName, - SelectiveKeyRestoreOperationParameters restoreBlobDetails, Context context) { - final String accept = "application/json"; - return service.selectiveKeyRestoreOperationSync(vaultBaseUrl, keyName, this.getApiVersion(), restoreBlobDetails, - accept, context); - } - - /** - * Restores all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob - * storage backup folder. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to be restored from the user supplied backup. - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return selective Key Restore operation. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SelectiveKeyRestoreOperation selectiveKeyRestoreOperation(String vaultBaseUrl, String keyName, - SelectiveKeyRestoreOperationParameters restoreBlobDetails) { - return selectiveKeyRestoreOperationWithResponse(vaultBaseUrl, keyName, restoreBlobDetails, Context.NONE) - .getValue(); - } - - /** - * Restores all key versions of a given key using user supplied SAS token pointing to a previously stored Azure Blob - * storage backup folder. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to be restored from the user supplied backup. - * @param restoreBlobDetails The Azure blob SAS token pointing to a folder where the previous successful full backup - * was stored. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return selective Key Restore operation along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response selectiveKeyRestoreOperationNoCustomHeadersWithResponse( - String vaultBaseUrl, String keyName, SelectiveKeyRestoreOperationParameters restoreBlobDetails, - Context context) { - final String accept = "application/json"; - return service.selectiveKeyRestoreOperationNoCustomHeadersSync(vaultBaseUrl, keyName, this.getApiVersion(), - restoreBlobDetails, accept, context); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultErrorCodeStrings.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultErrorCodeStrings.java deleted file mode 100644 index 9c3a2c7e0bab..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultErrorCodeStrings.java +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.security.keyvault.administration.implementation; - -public final class KeyVaultErrorCodeStrings { - public static final String CREDENTIALS_REQUIRED = "Azure Key Vault credentials are required."; - public static final String VAULT_END_POINT_REQUIRED = "Azure Key Vault endpoint url is required."; - public static final String PARAMETER_REQUIRED = "%s cannot be null."; -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultSettingsClientImpl.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultSettingsClientImpl.java deleted file mode 100644 index 91f3b6875128..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultSettingsClientImpl.java +++ /dev/null @@ -1,505 +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.security.keyvault.administration.implementation; - -import com.azure.core.annotation.BodyParam; -import com.azure.core.annotation.ExpectedResponses; -import com.azure.core.annotation.Get; -import com.azure.core.annotation.HeaderParam; -import com.azure.core.annotation.Host; -import com.azure.core.annotation.HostParam; -import com.azure.core.annotation.Patch; -import com.azure.core.annotation.PathParam; -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.HttpPipeline; -import com.azure.core.http.HttpPipelineBuilder; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.http.policy.UserAgentPolicy; -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 com.azure.core.util.serializer.JacksonAdapter; -import com.azure.core.util.serializer.SerializerAdapter; -import com.azure.security.keyvault.administration.implementation.models.KeyVaultErrorException; -import com.azure.security.keyvault.administration.implementation.models.Setting; -import com.azure.security.keyvault.administration.implementation.models.SettingsListResult; -import com.azure.security.keyvault.administration.implementation.models.UpdateSettingRequest; -import reactor.core.publisher.Mono; - -/** - * Initializes a new instance of the KeyVaultSettingsClient type. - */ -public final class KeyVaultSettingsClientImpl { - /** - * The proxy service used to perform REST calls. - */ - private final KeyVaultSettingsClientService service; - - /** - * 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; - } - - /** - * Initializes an instance of KeyVaultSettingsClient client. - * - * @param apiVersion Api Version. - */ - public KeyVaultSettingsClientImpl(String apiVersion) { - this(new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build(), - JacksonAdapter.createDefaultSerializerAdapter(), apiVersion); - } - - /** - * Initializes an instance of KeyVaultSettingsClient client. - * - * @param httpPipeline The HTTP pipeline to send requests through. - * @param apiVersion Api Version. - */ - public KeyVaultSettingsClientImpl(HttpPipeline httpPipeline, String apiVersion) { - this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), apiVersion); - } - - /** - * Initializes an instance of KeyVaultSettingsClient client. - * - * @param httpPipeline The HTTP pipeline to send requests through. - * @param serializerAdapter The serializer to serialize an object into a string. - * @param apiVersion Api Version. - */ - public KeyVaultSettingsClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, - String apiVersion) { - this.httpPipeline = httpPipeline; - this.serializerAdapter = serializerAdapter; - this.apiVersion = apiVersion; - this.service - = RestProxy.create(KeyVaultSettingsClientService.class, this.httpPipeline, this.getSerializerAdapter()); - } - - /** - * The interface defining all the services for KeyVaultSettingsClient to be used by the proxy service to perform - * REST calls. - */ - @Host("{vaultBaseUrl}") - @ServiceInterface(name = "KeyVaultSettingsClie") - public interface KeyVaultSettingsClientService { - @Patch("/settings/{setting-name}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> updateSetting(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("setting-name") String settingName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") UpdateSettingRequest parameters, @HeaderParam("Accept") String accept, - Context context); - - @Patch("/settings/{setting-name}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response updateSettingSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("setting-name") String settingName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") UpdateSettingRequest parameters, @HeaderParam("Accept") String accept, - Context context); - - @Get("/settings/{setting-name}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getSetting(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("setting-name") String settingName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Get("/settings/{setting-name}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getSettingSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("setting-name") String settingName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Get("/settings") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getSettings(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/settings") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getSettingsSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - } - - /** - * Updates key vault account setting, stores it, then returns the setting name and value to the client. - * - * Description of the pool setting to be updated. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param settingName The name of the account setting. Must be a valid settings option. - * @param value The value of the pool setting. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response body along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> updateSettingWithResponseAsync(String vaultBaseUrl, String settingName, - String value) { - return FluxUtil - .withContext(context -> updateSettingWithResponseAsync(vaultBaseUrl, settingName, value, context)); - } - - /** - * Updates key vault account setting, stores it, then returns the setting name and value to the client. - * - * Description of the pool setting to be updated. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param settingName The name of the account setting. Must be a valid settings option. - * @param value The value of the pool setting. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response body along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> updateSettingWithResponseAsync(String vaultBaseUrl, String settingName, String value, - Context context) { - final String accept = "application/json"; - UpdateSettingRequest parameters = new UpdateSettingRequest(); - parameters.setValue(value); - return service.updateSetting(vaultBaseUrl, settingName, this.getApiVersion(), parameters, accept, context); - } - - /** - * Updates key vault account setting, stores it, then returns the setting name and value to the client. - * - * Description of the pool setting to be updated. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param settingName The name of the account setting. Must be a valid settings option. - * @param value The value of the pool setting. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response body on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono updateSettingAsync(String vaultBaseUrl, String settingName, String value) { - return updateSettingWithResponseAsync(vaultBaseUrl, settingName, value) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Updates key vault account setting, stores it, then returns the setting name and value to the client. - * - * Description of the pool setting to be updated. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param settingName The name of the account setting. Must be a valid settings option. - * @param value The value of the pool setting. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response body on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono updateSettingAsync(String vaultBaseUrl, String settingName, String value, Context context) { - return updateSettingWithResponseAsync(vaultBaseUrl, settingName, value, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Updates key vault account setting, stores it, then returns the setting name and value to the client. - * - * Description of the pool setting to be updated. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param settingName The name of the account setting. Must be a valid settings option. - * @param value The value of the pool setting. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response body along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response updateSettingWithResponse(String vaultBaseUrl, String settingName, String value, - Context context) { - final String accept = "application/json"; - UpdateSettingRequest parameters = new UpdateSettingRequest(); - parameters.setValue(value); - return service.updateSettingSync(vaultBaseUrl, settingName, this.getApiVersion(), parameters, accept, context); - } - - /** - * Updates key vault account setting, stores it, then returns the setting name and value to the client. - * - * Description of the pool setting to be updated. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param settingName The name of the account setting. Must be a valid settings option. - * @param value The value of the pool setting. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Setting updateSetting(String vaultBaseUrl, String settingName, String value) { - return updateSettingWithResponse(vaultBaseUrl, settingName, value, Context.NONE).getValue(); - } - - /** - * Get specified account setting object. - * - * Retrieves the setting object of a specified setting name. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param settingName The name of the account setting. Must be a valid settings option. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response body along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSettingWithResponseAsync(String vaultBaseUrl, String settingName) { - return FluxUtil.withContext(context -> getSettingWithResponseAsync(vaultBaseUrl, settingName, context)); - } - - /** - * Get specified account setting object. - * - * Retrieves the setting object of a specified setting name. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param settingName The name of the account setting. Must be a valid settings option. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response body along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSettingWithResponseAsync(String vaultBaseUrl, String settingName, - Context context) { - final String accept = "application/json"; - return service.getSetting(vaultBaseUrl, settingName, this.getApiVersion(), accept, context); - } - - /** - * Get specified account setting object. - * - * Retrieves the setting object of a specified setting name. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param settingName The name of the account setting. Must be a valid settings option. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response body on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSettingAsync(String vaultBaseUrl, String settingName) { - return getSettingWithResponseAsync(vaultBaseUrl, settingName).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Get specified account setting object. - * - * Retrieves the setting object of a specified setting name. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param settingName The name of the account setting. Must be a valid settings option. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response body on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSettingAsync(String vaultBaseUrl, String settingName, Context context) { - return getSettingWithResponseAsync(vaultBaseUrl, settingName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Get specified account setting object. - * - * Retrieves the setting object of a specified setting name. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param settingName The name of the account setting. Must be a valid settings option. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response body along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getSettingWithResponse(String vaultBaseUrl, String settingName, Context context) { - final String accept = "application/json"; - return service.getSettingSync(vaultBaseUrl, settingName, this.getApiVersion(), accept, context); - } - - /** - * Get specified account setting object. - * - * Retrieves the setting object of a specified setting name. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param settingName The name of the account setting. Must be a valid settings option. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Setting getSetting(String vaultBaseUrl, String settingName) { - return getSettingWithResponse(vaultBaseUrl, settingName, Context.NONE).getValue(); - } - - /** - * List account settings. - * - * Retrieves a list of all the available account settings that can be configured. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the settings list result along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSettingsWithResponseAsync(String vaultBaseUrl) { - return FluxUtil.withContext(context -> getSettingsWithResponseAsync(vaultBaseUrl, context)); - } - - /** - * List account settings. - * - * Retrieves a list of all the available account settings that can be configured. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the settings list result along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSettingsWithResponseAsync(String vaultBaseUrl, Context context) { - final String accept = "application/json"; - return service.getSettings(vaultBaseUrl, this.getApiVersion(), accept, context); - } - - /** - * List account settings. - * - * Retrieves a list of all the available account settings that can be configured. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the settings list result on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSettingsAsync(String vaultBaseUrl) { - return getSettingsWithResponseAsync(vaultBaseUrl).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * List account settings. - * - * Retrieves a list of all the available account settings that can be configured. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the settings list result on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSettingsAsync(String vaultBaseUrl, Context context) { - return getSettingsWithResponseAsync(vaultBaseUrl, context).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * List account settings. - * - * Retrieves a list of all the available account settings that can be configured. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the settings list result along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getSettingsWithResponse(String vaultBaseUrl, Context context) { - final String accept = "application/json"; - return service.getSettingsSync(vaultBaseUrl, this.getApiVersion(), accept, context); - } - - /** - * List account settings. - * - * Retrieves a list of all the available account settings that can be configured. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the settings list result. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SettingsListResult getSettings(String vaultBaseUrl) { - return getSettingsWithResponse(vaultBaseUrl, Context.NONE).getValue(); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/RoleAssignmentsImpl.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/RoleAssignmentsImpl.java index 2e4a7b5c6cc7..c7044e3839df 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/RoleAssignmentsImpl.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/RoleAssignmentsImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.administration.implementation; @@ -18,18 +18,24 @@ import com.azure.core.annotation.ServiceInterface; import com.azure.core.annotation.ServiceMethod; import com.azure.core.annotation.UnexpectedResponseExceptionType; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; import com.azure.core.http.rest.PagedFlux; import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.PagedResponse; import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.RequestOptions; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.RestProxy; +import com.azure.core.util.BinaryData; import com.azure.core.util.Context; import com.azure.core.util.FluxUtil; -import com.azure.security.keyvault.administration.implementation.models.KeyVaultErrorException; -import com.azure.security.keyvault.administration.implementation.models.RoleAssignment; -import com.azure.security.keyvault.administration.implementation.models.RoleAssignmentCreateParameters; -import com.azure.security.keyvault.administration.implementation.models.RoleAssignmentListResult; +import com.azure.security.keyvault.administration.KeyVaultAdministrationServiceVersion; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; import reactor.core.publisher.Mono; /** @@ -44,687 +50,663 @@ public final class RoleAssignmentsImpl { /** * The service client containing this operation class. */ - private final KeyVaultAccessControlClientImpl client; + private final KeyVaultAdministrationClientImpl client; /** * Initializes an instance of RoleAssignmentsImpl. * * @param client the instance of the service client containing this operation class. */ - RoleAssignmentsImpl(KeyVaultAccessControlClientImpl client) { + RoleAssignmentsImpl(KeyVaultAdministrationClientImpl client) { this.service = RestProxy.create(RoleAssignmentsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); this.client = client; } /** - * The interface defining all the services for KeyVaultAccessControlClientRoleAssignments to be used by the proxy + * Gets Service version. + * + * @return the serviceVersion value. + */ + public KeyVaultAdministrationServiceVersion getServiceVersion() { + return client.getServiceVersion(); + } + + /** + * The interface defining all the services for KeyVaultAdministrationClientRoleAssignments to be used by the proxy * service to perform REST calls. */ @Host("{vaultBaseUrl}") - @ServiceInterface(name = "KeyVaultAccessContro") + @ServiceInterface(name = "KeyVaultAdministrationClientRoleAs") public interface RoleAssignmentsService { @Delete("/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> delete(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam(value = "scope", encoded = true) String scope, - @PathParam("roleAssignmentName") String roleAssignmentName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> delete(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, + @PathParam("roleAssignmentName") String roleAssignmentName, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Delete("/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response deleteSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam(value = "scope", encoded = true) String scope, - @PathParam("roleAssignmentName") String roleAssignmentName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response deleteSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, + @PathParam("roleAssignmentName") String roleAssignmentName, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Put("/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") @ExpectedResponses({ 201 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> create(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam(value = "scope", encoded = true) String scope, - @PathParam("roleAssignmentName") String roleAssignmentName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") RoleAssignmentCreateParameters parameters, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> create(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, + @PathParam("roleAssignmentName") String roleAssignmentName, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Put("/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") @ExpectedResponses({ 201 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response createSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam(value = "scope", encoded = true) String scope, - @PathParam("roleAssignmentName") String roleAssignmentName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") RoleAssignmentCreateParameters parameters, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response createSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, + @PathParam("roleAssignmentName") String roleAssignmentName, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Get("/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> get(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam(value = "scope", encoded = true) String scope, - @PathParam("roleAssignmentName") String roleAssignmentName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> get(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, + @PathParam("roleAssignmentName") String roleAssignmentName, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam(value = "scope", encoded = true) String scope, - @PathParam("roleAssignmentName") String roleAssignmentName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, + @PathParam("roleAssignmentName") String roleAssignmentName, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("/{scope}/providers/Microsoft.Authorization/roleAssignments") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> listForScope(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam(value = "scope", encoded = true) String scope, @QueryParam("$filter") String filter, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> listForScope(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Get("/{scope}/providers/Microsoft.Authorization/roleAssignments") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response listForScopeSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam(value = "scope", encoded = true) String scope, @QueryParam("$filter") String filter, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response listForScopeSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Get("{nextLink}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> listForScopeNext( - @PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> listForScopeNext(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("{nextLink}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response listForScopeNextSync( - @PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response listForScopeNextSync(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); } /** * Deletes a role assignment. + *

          Response Body Schema

          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role assignment to delete. - * @param roleAssignmentName The name of the role assignment to delete. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return role Assignments along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteWithResponseAsync(String vaultBaseUrl, String scope, - String roleAssignmentName) { - return FluxUtil - .withContext(context -> deleteWithResponseAsync(vaultBaseUrl, scope, roleAssignmentName, context)); - } - - /** - * Deletes a role assignment. + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     name: String (Optional)
          +     *     type: String (Optional)
          +     *     properties (Optional): {
          +     *         scope: String(///keys) (Optional)
          +     *         roleDefinitionId: String (Optional)
          +     *         principalId: String (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param scope The scope of the role assignment to delete. * @param roleAssignmentName The name of the role assignment to delete. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return role Assignments along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteWithResponseAsync(String vaultBaseUrl, String scope, - String roleAssignmentName, Context context) { + public Mono> deleteWithResponseAsync(String scope, String roleAssignmentName, + RequestOptions requestOptions) { final String accept = "application/json"; - return service.delete(vaultBaseUrl, scope, roleAssignmentName, this.client.getApiVersion(), accept, context); + return FluxUtil.withContext(context -> service.delete(this.client.getVaultBaseUrl(), + this.client.getServiceVersion().getVersion(), scope, roleAssignmentName, accept, requestOptions, context)); } /** * Deletes a role assignment. + *

          Response Body Schema

          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role assignment to delete. - * @param roleAssignmentName The name of the role assignment to delete. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return role Assignments on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteAsync(String vaultBaseUrl, String scope, String roleAssignmentName) { - return deleteWithResponseAsync(vaultBaseUrl, scope, roleAssignmentName) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Deletes a role assignment. + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     name: String (Optional)
          +     *     type: String (Optional)
          +     *     properties (Optional): {
          +     *         scope: String(///keys) (Optional)
          +     *         roleDefinitionId: String (Optional)
          +     *         principalId: String (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param scope The scope of the role assignment to delete. * @param roleAssignmentName The name of the role assignment to delete. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return role Assignments on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteAsync(String vaultBaseUrl, String scope, String roleAssignmentName, - Context context) { - return deleteWithResponseAsync(vaultBaseUrl, scope, roleAssignmentName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Deletes a role assignment. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role assignment to delete. - * @param roleAssignmentName The name of the role assignment to delete. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return role Assignments along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteWithResponse(String vaultBaseUrl, String scope, String roleAssignmentName, - Context context) { + public Response deleteWithResponse(String scope, String roleAssignmentName, + RequestOptions requestOptions) { final String accept = "application/json"; - return service.deleteSync(vaultBaseUrl, scope, roleAssignmentName, this.client.getApiVersion(), accept, - context); - } - - /** - * Deletes a role assignment. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role assignment to delete. - * @param roleAssignmentName The name of the role assignment to delete. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return role Assignments. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public RoleAssignment delete(String vaultBaseUrl, String scope, String roleAssignmentName) { - return deleteWithResponse(vaultBaseUrl, scope, roleAssignmentName, Context.NONE).getValue(); + return service.deleteSync(this.client.getVaultBaseUrl(), this.client.getServiceVersion().getVersion(), scope, + roleAssignmentName, accept, requestOptions, Context.NONE); } /** * Creates a role assignment. + *

          Request Body Schema

          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role assignment to create. - * @param roleAssignmentName The name of the role assignment to create. It can be any valid GUID. - * @param parameters Parameters for the role assignment. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return role Assignments along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createWithResponseAsync(String vaultBaseUrl, String scope, - String roleAssignmentName, RoleAssignmentCreateParameters parameters) { - return FluxUtil.withContext( - context -> createWithResponseAsync(vaultBaseUrl, scope, roleAssignmentName, parameters, context)); - } - - /** - * Creates a role assignment. + *
          +     * {@code
          +     * {
          +     *     properties (Required): {
          +     *         roleDefinitionId: String (Required)
          +     *         principalId: String (Required)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     name: String (Optional)
          +     *     type: String (Optional)
          +     *     properties (Optional): {
          +     *         scope: String(///keys) (Optional)
          +     *         roleDefinitionId: String (Optional)
          +     *         principalId: String (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param scope The scope of the role assignment to create. * @param roleAssignmentName The name of the role assignment to create. It can be any valid GUID. * @param parameters Parameters for the role assignment. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return role Assignments along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createWithResponseAsync(String vaultBaseUrl, String scope, - String roleAssignmentName, RoleAssignmentCreateParameters parameters, Context context) { + public Mono> createWithResponseAsync(String scope, String roleAssignmentName, + BinaryData parameters, RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - return service.create(vaultBaseUrl, scope, roleAssignmentName, this.client.getApiVersion(), parameters, accept, - context); + return FluxUtil.withContext( + context -> service.create(this.client.getVaultBaseUrl(), this.client.getServiceVersion().getVersion(), + scope, roleAssignmentName, contentType, accept, parameters, requestOptions, context)); } /** * Creates a role assignment. + *

          Request Body Schema

          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role assignment to create. - * @param roleAssignmentName The name of the role assignment to create. It can be any valid GUID. - * @param parameters Parameters for the role assignment. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return role Assignments on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createAsync(String vaultBaseUrl, String scope, String roleAssignmentName, - RoleAssignmentCreateParameters parameters) { - return createWithResponseAsync(vaultBaseUrl, scope, roleAssignmentName, parameters) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a role assignment. + *
          +     * {@code
          +     * {
          +     *     properties (Required): {
          +     *         roleDefinitionId: String (Required)
          +     *         principalId: String (Required)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role assignment to create. - * @param roleAssignmentName The name of the role assignment to create. It can be any valid GUID. - * @param parameters Parameters for the role assignment. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return role Assignments on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createAsync(String vaultBaseUrl, String scope, String roleAssignmentName, - RoleAssignmentCreateParameters parameters, Context context) { - return createWithResponseAsync(vaultBaseUrl, scope, roleAssignmentName, parameters, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a role assignment. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     name: String (Optional)
          +     *     type: String (Optional)
          +     *     properties (Optional): {
          +     *         scope: String(///keys) (Optional)
          +     *         roleDefinitionId: String (Optional)
          +     *         principalId: String (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param scope The scope of the role assignment to create. * @param roleAssignmentName The name of the role assignment to create. It can be any valid GUID. * @param parameters Parameters for the role assignment. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return role Assignments along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response createWithResponse(String vaultBaseUrl, String scope, String roleAssignmentName, - RoleAssignmentCreateParameters parameters, Context context) { + public Response createWithResponse(String scope, String roleAssignmentName, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - return service.createSync(vaultBaseUrl, scope, roleAssignmentName, this.client.getApiVersion(), parameters, - accept, context); - } - - /** - * Creates a role assignment. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role assignment to create. - * @param roleAssignmentName The name of the role assignment to create. It can be any valid GUID. - * @param parameters Parameters for the role assignment. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return role Assignments. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public RoleAssignment create(String vaultBaseUrl, String scope, String roleAssignmentName, - RoleAssignmentCreateParameters parameters) { - return createWithResponse(vaultBaseUrl, scope, roleAssignmentName, parameters, Context.NONE).getValue(); + return service.createSync(this.client.getVaultBaseUrl(), this.client.getServiceVersion().getVersion(), scope, + roleAssignmentName, contentType, accept, parameters, requestOptions, Context.NONE); } /** * Get the specified role assignment. + *

          Response Body Schema

          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role assignment. - * @param roleAssignmentName The name of the role assignment to get. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the specified role assignment along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getWithResponseAsync(String vaultBaseUrl, String scope, - String roleAssignmentName) { - return FluxUtil.withContext(context -> getWithResponseAsync(vaultBaseUrl, scope, roleAssignmentName, context)); - } - - /** - * Get the specified role assignment. + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     name: String (Optional)
          +     *     type: String (Optional)
          +     *     properties (Optional): {
          +     *         scope: String(///keys) (Optional)
          +     *         roleDefinitionId: String (Optional)
          +     *         principalId: String (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param scope The scope of the role assignment. * @param roleAssignmentName The name of the role assignment to get. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the specified role assignment along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getWithResponseAsync(String vaultBaseUrl, String scope, - String roleAssignmentName, Context context) { + public Mono> getWithResponseAsync(String scope, String roleAssignmentName, + RequestOptions requestOptions) { final String accept = "application/json"; - return service.get(vaultBaseUrl, scope, roleAssignmentName, this.client.getApiVersion(), accept, context); + return FluxUtil.withContext(context -> service.get(this.client.getVaultBaseUrl(), + this.client.getServiceVersion().getVersion(), scope, roleAssignmentName, accept, requestOptions, context)); } /** * Get the specified role assignment. + *

          Response Body Schema

          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role assignment. - * @param roleAssignmentName The name of the role assignment to get. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the specified role assignment on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getAsync(String vaultBaseUrl, String scope, String roleAssignmentName) { - return getWithResponseAsync(vaultBaseUrl, scope, roleAssignmentName) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Get the specified role assignment. + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     name: String (Optional)
          +     *     type: String (Optional)
          +     *     properties (Optional): {
          +     *         scope: String(///keys) (Optional)
          +     *         roleDefinitionId: String (Optional)
          +     *         principalId: String (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param scope The scope of the role assignment. * @param roleAssignmentName The name of the role assignment to get. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the specified role assignment on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getAsync(String vaultBaseUrl, String scope, String roleAssignmentName, - Context context) { - return getWithResponseAsync(vaultBaseUrl, scope, roleAssignmentName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Get the specified role assignment. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role assignment. - * @param roleAssignmentName The name of the role assignment to get. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the specified role assignment along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response getWithResponse(String vaultBaseUrl, String scope, String roleAssignmentName, - Context context) { + public Response getWithResponse(String scope, String roleAssignmentName, + RequestOptions requestOptions) { final String accept = "application/json"; - return service.getSync(vaultBaseUrl, scope, roleAssignmentName, this.client.getApiVersion(), accept, context); - } - - /** - * Get the specified role assignment. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role assignment. - * @param roleAssignmentName The name of the role assignment to get. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the specified role assignment. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public RoleAssignment get(String vaultBaseUrl, String scope, String roleAssignmentName) { - return getWithResponse(vaultBaseUrl, scope, roleAssignmentName, Context.NONE).getValue(); + return service.getSync(this.client.getVaultBaseUrl(), this.client.getServiceVersion().getVersion(), scope, + roleAssignmentName, accept, requestOptions, Context.NONE); } /** * Gets role assignments for a scope. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          $filterStringNoThe filter to apply on the operation. Use $filter=atScope() to + * return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments + * at, above or below the scope for the specified principal.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role assignments. - * @param filter The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or - * above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for - * the specified principal. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return role assignments for a scope along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> listForScopeSinglePageAsync(String vaultBaseUrl, String scope, - String filter) { - final String accept = "application/json"; - return FluxUtil.withContext( - context -> service.listForScope(vaultBaseUrl, scope, filter, this.client.getApiVersion(), accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * Gets role assignments for a scope. + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     name: String (Optional)
          +     *     type: String (Optional)
          +     *     properties (Optional): {
          +     *         scope: String(///keys) (Optional)
          +     *         roleDefinitionId: String (Optional)
          +     *         principalId: String (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param scope The scope of the role assignments. - * @param filter The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or - * above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for - * the specified principal. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return role assignments for a scope along with {@link PagedResponse} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> listForScopeSinglePageAsync(String vaultBaseUrl, String scope, - String filter, Context context) { + public Mono> listForScopeSinglePageAsync(String scope, RequestOptions requestOptions) { final String accept = "application/json"; - return service.listForScope(vaultBaseUrl, scope, filter, this.client.getApiVersion(), accept, context) + return FluxUtil + .withContext(context -> service.listForScope(this.client.getVaultBaseUrl(), + this.client.getServiceVersion().getVersion(), scope, accept, requestOptions, context)) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } /** * Gets role assignments for a scope. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          $filterStringNoThe filter to apply on the operation. Use $filter=atScope() to + * return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments + * at, above or below the scope for the specified principal.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role assignments. - * @param filter The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or - * above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for - * the specified principal. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return role assignments for a scope as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listForScopeAsync(String vaultBaseUrl, String scope, String filter) { - return new PagedFlux<>(() -> listForScopeSinglePageAsync(vaultBaseUrl, scope, filter), - nextLink -> listForScopeNextSinglePageAsync(nextLink, vaultBaseUrl)); - } - - /** - * Gets role assignments for a scope. + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     name: String (Optional)
          +     *     type: String (Optional)
          +     *     properties (Optional): {
          +     *         scope: String(///keys) (Optional)
          +     *         roleDefinitionId: String (Optional)
          +     *         principalId: String (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param scope The scope of the role assignments. - * @param filter The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or - * above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for - * the specified principal. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return role assignments for a scope as paginated response with {@link PagedFlux}. */ @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listForScopeAsync(String vaultBaseUrl, String scope, String filter, - Context context) { - return new PagedFlux<>(() -> listForScopeSinglePageAsync(vaultBaseUrl, scope, filter, context), - nextLink -> listForScopeNextSinglePageAsync(nextLink, vaultBaseUrl, context)); + public PagedFlux listForScopeAsync(String scope, RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedFlux<>(() -> listForScopeSinglePageAsync(scope, requestOptions), + nextLink -> listForScopeNextSinglePageAsync(nextLink, requestOptionsForNextPage)); } /** * Gets role assignments for a scope. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          $filterStringNoThe filter to apply on the operation. Use $filter=atScope() to + * return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments + * at, above or below the scope for the specified principal.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role assignments. - * @param filter The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or - * above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for - * the specified principal. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return role assignments for a scope along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse listForScopeSinglePage(String vaultBaseUrl, String scope, String filter) { - final String accept = "application/json"; - Response res - = service.listForScopeSync(vaultBaseUrl, scope, filter, this.client.getApiVersion(), accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * Gets role assignments for a scope. + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     name: String (Optional)
          +     *     type: String (Optional)
          +     *     properties (Optional): {
          +     *         scope: String(///keys) (Optional)
          +     *         roleDefinitionId: String (Optional)
          +     *         principalId: String (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param scope The scope of the role assignments. - * @param filter The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or - * above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for - * the specified principal. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return role assignments for a scope along with {@link PagedResponse}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse listForScopeSinglePage(String vaultBaseUrl, String scope, String filter, - Context context) { + private PagedResponse listForScopeSinglePage(String scope, RequestOptions requestOptions) { final String accept = "application/json"; - Response res - = service.listForScopeSync(vaultBaseUrl, scope, filter, this.client.getApiVersion(), accept, context); + Response res = service.listForScopeSync(this.client.getVaultBaseUrl(), + this.client.getServiceVersion().getVersion(), scope, accept, requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } /** * Gets role assignments for a scope. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          $filterStringNoThe filter to apply on the operation. Use $filter=atScope() to + * return all role assignments at or above the scope. Use $filter=principalId eq {id} to return all role assignments + * at, above or below the scope for the specified principal.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role assignments. - * @param filter The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or - * above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for - * the specified principal. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return role assignments for a scope as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listForScope(String vaultBaseUrl, String scope, String filter) { - return new PagedIterable<>(() -> listForScopeSinglePage(vaultBaseUrl, scope, filter, Context.NONE), - nextLink -> listForScopeNextSinglePage(nextLink, vaultBaseUrl)); - } - - /** - * Gets role assignments for a scope. + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     name: String (Optional)
          +     *     type: String (Optional)
          +     *     properties (Optional): {
          +     *         scope: String(///keys) (Optional)
          +     *         roleDefinitionId: String (Optional)
          +     *         principalId: String (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param scope The scope of the role assignments. - * @param filter The filter to apply on the operation. Use $filter=atScope() to return all role assignments at or - * above the scope. Use $filter=principalId eq {id} to return all role assignments at, above or below the scope for - * the specified principal. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return role assignments for a scope as paginated response with {@link PagedIterable}. */ @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listForScope(String vaultBaseUrl, String scope, String filter, - Context context) { - return new PagedIterable<>(() -> listForScopeSinglePage(vaultBaseUrl, scope, filter, context), - nextLink -> listForScopeNextSinglePage(nextLink, vaultBaseUrl, context)); + public PagedIterable listForScope(String scope, RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedIterable<>(() -> listForScopeSinglePage(scope, requestOptions), + nextLink -> listForScopeNextSinglePage(nextLink, requestOptionsForNextPage)); } /** * Get the next page of items. + *

          Response Body Schema

          * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return role assignment list operation result along with {@link PagedResponse} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> listForScopeNextSinglePageAsync(String nextLink, String vaultBaseUrl) { - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.listForScopeNext(nextLink, vaultBaseUrl, accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * Get the next page of items. + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     name: String (Optional)
          +     *     type: String (Optional)
          +     *     properties (Optional): {
          +     *         scope: String(///keys) (Optional)
          +     *         roleDefinitionId: String (Optional)
          +     *         principalId: String (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          * * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return role assignment list operation result along with {@link PagedResponse} on successful completion of * {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> listForScopeNextSinglePageAsync(String nextLink, String vaultBaseUrl, - Context context) { + public Mono> listForScopeNextSinglePageAsync(String nextLink, + RequestOptions requestOptions) { final String accept = "application/json"; - return service.listForScopeNext(nextLink, vaultBaseUrl, accept, context) + return FluxUtil + .withContext(context -> service.listForScopeNext(nextLink, this.client.getVaultBaseUrl(), accept, + requestOptions, context)) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } /** * Get the next page of items. + *

          Response Body Schema

          * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return role assignment list operation result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse listForScopeNextSinglePage(String nextLink, String vaultBaseUrl) { - final String accept = "application/json"; - Response res - = service.listForScopeNextSync(nextLink, vaultBaseUrl, accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * Get the next page of items. + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     name: String (Optional)
          +     *     type: String (Optional)
          +     *     properties (Optional): {
          +     *         scope: String(///keys) (Optional)
          +     *         roleDefinitionId: String (Optional)
          +     *         principalId: String (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          * * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return role assignment list operation result along with {@link PagedResponse}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse listForScopeNextSinglePage(String nextLink, String vaultBaseUrl, - Context context) { + private PagedResponse listForScopeNextSinglePage(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; - Response res = service.listForScopeNextSync(nextLink, vaultBaseUrl, accept, context); + Response res = service.listForScopeNextSync(nextLink, this.client.getVaultBaseUrl(), accept, + requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); + } + + private List getValues(BinaryData binaryData, String path) { + try { + Map obj = binaryData.toObject(Map.class); + List values = (List) obj.get(path); + return values.stream().map(BinaryData::fromObject).collect(Collectors.toList()); + } catch (RuntimeException e) { + return null; + } + } + + private String getNextLink(BinaryData binaryData, String path) { + try { + Map obj = binaryData.toObject(Map.class); + return (String) obj.get(path); + } catch (RuntimeException e) { + return null; + } } } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/RoleDefinitionsImpl.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/RoleDefinitionsImpl.java index d1d9ddb2132c..4a6e020fff6d 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/RoleDefinitionsImpl.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/RoleDefinitionsImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.administration.implementation; @@ -18,18 +18,24 @@ import com.azure.core.annotation.ServiceInterface; import com.azure.core.annotation.ServiceMethod; import com.azure.core.annotation.UnexpectedResponseExceptionType; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; import com.azure.core.http.rest.PagedFlux; import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.PagedResponse; import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.RequestOptions; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.RestProxy; +import com.azure.core.util.BinaryData; import com.azure.core.util.Context; import com.azure.core.util.FluxUtil; -import com.azure.security.keyvault.administration.implementation.models.KeyVaultErrorException; -import com.azure.security.keyvault.administration.implementation.models.RoleDefinition; -import com.azure.security.keyvault.administration.implementation.models.RoleDefinitionCreateParameters; -import com.azure.security.keyvault.administration.implementation.models.RoleDefinitionListResult; +import com.azure.security.keyvault.administration.KeyVaultAdministrationServiceVersion; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; import reactor.core.publisher.Mono; /** @@ -44,678 +50,928 @@ public final class RoleDefinitionsImpl { /** * The service client containing this operation class. */ - private final KeyVaultAccessControlClientImpl client; + private final KeyVaultAdministrationClientImpl client; /** * Initializes an instance of RoleDefinitionsImpl. * * @param client the instance of the service client containing this operation class. */ - RoleDefinitionsImpl(KeyVaultAccessControlClientImpl client) { + RoleDefinitionsImpl(KeyVaultAdministrationClientImpl client) { this.service = RestProxy.create(RoleDefinitionsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); this.client = client; } /** - * The interface defining all the services for KeyVaultAccessControlClientRoleDefinitions to be used by the proxy + * Gets Service version. + * + * @return the serviceVersion value. + */ + public KeyVaultAdministrationServiceVersion getServiceVersion() { + return client.getServiceVersion(); + } + + /** + * The interface defining all the services for KeyVaultAdministrationClientRoleDefinitions to be used by the proxy * service to perform REST calls. */ @Host("{vaultBaseUrl}") - @ServiceInterface(name = "KeyVaultAccessContro") + @ServiceInterface(name = "KeyVaultAdministrationClientRoleDe") public interface RoleDefinitionsService { @Delete("/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionName}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> delete(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam(value = "scope", encoded = true) String scope, - @PathParam("roleDefinitionName") String roleDefinitionName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> delete(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, + @PathParam("roleDefinitionName") String roleDefinitionName, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Delete("/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionName}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response deleteSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam(value = "scope", encoded = true) String scope, - @PathParam("roleDefinitionName") String roleDefinitionName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response deleteSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, + @PathParam("roleDefinitionName") String roleDefinitionName, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Put("/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionName}") @ExpectedResponses({ 201 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> createOrUpdate(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam(value = "scope", encoded = true) String scope, - @PathParam("roleDefinitionName") String roleDefinitionName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") RoleDefinitionCreateParameters parameters, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> createOrUpdate(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, + @PathParam("roleDefinitionName") String roleDefinitionName, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Put("/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionName}") @ExpectedResponses({ 201 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response createOrUpdateSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam(value = "scope", encoded = true) String scope, - @PathParam("roleDefinitionName") String roleDefinitionName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") RoleDefinitionCreateParameters parameters, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response createOrUpdateSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, + @PathParam("roleDefinitionName") String roleDefinitionName, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Get("/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionName}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> get(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam(value = "scope", encoded = true) String scope, - @PathParam("roleDefinitionName") String roleDefinitionName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> get(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, + @PathParam("roleDefinitionName") String roleDefinitionName, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionName}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam(value = "scope", encoded = true) String scope, - @PathParam("roleDefinitionName") String roleDefinitionName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, + @PathParam("roleDefinitionName") String roleDefinitionName, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("/{scope}/providers/Microsoft.Authorization/roleDefinitions") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> list(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam(value = "scope", encoded = true) String scope, @QueryParam("$filter") String filter, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> list(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Get("/{scope}/providers/Microsoft.Authorization/roleDefinitions") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response listSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam(value = "scope", encoded = true) String scope, @QueryParam("$filter") String filter, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response listSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam(value = "scope", encoded = true) String scope, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Get("{nextLink}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> listNext( - @PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> listNext(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("{nextLink}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response listNextSync(@PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response listNextSync(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); } /** * Deletes a custom role definition. + *

          Response Body Schema

          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role definition to delete. Managed HSM only supports '/'. - * @param roleDefinitionName The name (GUID) of the role definition to delete. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return role definition along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteWithResponseAsync(String vaultBaseUrl, String scope, - String roleDefinitionName) { - return FluxUtil - .withContext(context -> deleteWithResponseAsync(vaultBaseUrl, scope, roleDefinitionName, context)); - } - - /** - * Deletes a custom role definition. + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     name: String (Optional)
          +     *     type: String(Microsoft.Authorization/roleDefinitions) (Optional)
          +     *     properties (Optional): {
          +     *         roleName: String (Optional)
          +     *         description: String (Optional)
          +     *         type: String(AKVBuiltInRole/CustomRole) (Optional)
          +     *         permissions (Optional): [
          +     *              (Optional){
          +     *                 actions (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 notActions (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dataActions (Optional): [
          +     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
          +     *                 ]
          +     *                 notDataActions (Optional): [
          +     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
          +     *                 ]
          +     *             }
          +     *         ]
          +     *         assignableScopes (Optional): [
          +     *             String(///keys) (Optional)
          +     *         ]
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param scope The scope of the role definition to delete. Managed HSM only supports '/'. * @param roleDefinitionName The name (GUID) of the role definition to delete. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return role definition along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteWithResponseAsync(String vaultBaseUrl, String scope, - String roleDefinitionName, Context context) { + public Mono> deleteWithResponseAsync(String scope, String roleDefinitionName, + RequestOptions requestOptions) { final String accept = "application/json"; - return service.delete(vaultBaseUrl, scope, roleDefinitionName, this.client.getApiVersion(), accept, context); - } - - /** - * Deletes a custom role definition. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role definition to delete. Managed HSM only supports '/'. - * @param roleDefinitionName The name (GUID) of the role definition to delete. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return role definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteAsync(String vaultBaseUrl, String scope, String roleDefinitionName) { - return deleteWithResponseAsync(vaultBaseUrl, scope, roleDefinitionName) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + return FluxUtil.withContext(context -> service.delete(this.client.getVaultBaseUrl(), + this.client.getServiceVersion().getVersion(), scope, roleDefinitionName, accept, requestOptions, context)); } /** * Deletes a custom role definition. + *

          Response Body Schema

          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role definition to delete. Managed HSM only supports '/'. - * @param roleDefinitionName The name (GUID) of the role definition to delete. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return role definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteAsync(String vaultBaseUrl, String scope, String roleDefinitionName, - Context context) { - return deleteWithResponseAsync(vaultBaseUrl, scope, roleDefinitionName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Deletes a custom role definition. + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     name: String (Optional)
          +     *     type: String(Microsoft.Authorization/roleDefinitions) (Optional)
          +     *     properties (Optional): {
          +     *         roleName: String (Optional)
          +     *         description: String (Optional)
          +     *         type: String(AKVBuiltInRole/CustomRole) (Optional)
          +     *         permissions (Optional): [
          +     *              (Optional){
          +     *                 actions (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 notActions (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dataActions (Optional): [
          +     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
          +     *                 ]
          +     *                 notDataActions (Optional): [
          +     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
          +     *                 ]
          +     *             }
          +     *         ]
          +     *         assignableScopes (Optional): [
          +     *             String(///keys) (Optional)
          +     *         ]
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param scope The scope of the role definition to delete. Managed HSM only supports '/'. * @param roleDefinitionName The name (GUID) of the role definition to delete. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return role definition along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteWithResponse(String vaultBaseUrl, String scope, String roleDefinitionName, - Context context) { + public Response deleteWithResponse(String scope, String roleDefinitionName, + RequestOptions requestOptions) { final String accept = "application/json"; - return service.deleteSync(vaultBaseUrl, scope, roleDefinitionName, this.client.getApiVersion(), accept, - context); - } - - /** - * Deletes a custom role definition. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role definition to delete. Managed HSM only supports '/'. - * @param roleDefinitionName The name (GUID) of the role definition to delete. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return role definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public RoleDefinition delete(String vaultBaseUrl, String scope, String roleDefinitionName) { - return deleteWithResponse(vaultBaseUrl, scope, roleDefinitionName, Context.NONE).getValue(); + return service.deleteSync(this.client.getVaultBaseUrl(), this.client.getServiceVersion().getVersion(), scope, + roleDefinitionName, accept, requestOptions, Context.NONE); } /** * Creates or updates a custom role definition. + *

          Request Body Schema

          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role definition to create or update. Managed HSM only supports '/'. - * @param roleDefinitionName The name of the role definition to create or update. It can be any valid GUID. - * @param parameters Parameters for the role definition. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return role definition along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createOrUpdateWithResponseAsync(String vaultBaseUrl, String scope, - String roleDefinitionName, RoleDefinitionCreateParameters parameters) { - return FluxUtil.withContext( - context -> createOrUpdateWithResponseAsync(vaultBaseUrl, scope, roleDefinitionName, parameters, context)); - } - - /** - * Creates or updates a custom role definition. + *
          +     * {@code
          +     * {
          +     *     properties (Required): {
          +     *         roleName: String (Optional)
          +     *         description: String (Optional)
          +     *         type: String(AKVBuiltInRole/CustomRole) (Optional)
          +     *         permissions (Optional): [
          +     *              (Optional){
          +     *                 actions (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 notActions (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dataActions (Optional): [
          +     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
          +     *                 ]
          +     *                 notDataActions (Optional): [
          +     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
          +     *                 ]
          +     *             }
          +     *         ]
          +     *         assignableScopes (Optional): [
          +     *             String(///keys) (Optional)
          +     *         ]
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     name: String (Optional)
          +     *     type: String(Microsoft.Authorization/roleDefinitions) (Optional)
          +     *     properties (Optional): {
          +     *         roleName: String (Optional)
          +     *         description: String (Optional)
          +     *         type: String(AKVBuiltInRole/CustomRole) (Optional)
          +     *         permissions (Optional): [
          +     *              (Optional){
          +     *                 actions (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 notActions (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dataActions (Optional): [
          +     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
          +     *                 ]
          +     *                 notDataActions (Optional): [
          +     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
          +     *                 ]
          +     *             }
          +     *         ]
          +     *         assignableScopes (Optional): [
          +     *             String(///keys) (Optional)
          +     *         ]
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param scope The scope of the role definition to create or update. Managed HSM only supports '/'. * @param roleDefinitionName The name of the role definition to create or update. It can be any valid GUID. * @param parameters Parameters for the role definition. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return role definition along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createOrUpdateWithResponseAsync(String vaultBaseUrl, String scope, - String roleDefinitionName, RoleDefinitionCreateParameters parameters, Context context) { + public Mono> createOrUpdateWithResponseAsync(String scope, String roleDefinitionName, + BinaryData parameters, RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - return service.createOrUpdate(vaultBaseUrl, scope, roleDefinitionName, this.client.getApiVersion(), parameters, - accept, context); + return FluxUtil.withContext(context -> service.createOrUpdate(this.client.getVaultBaseUrl(), + this.client.getServiceVersion().getVersion(), scope, roleDefinitionName, contentType, accept, parameters, + requestOptions, context)); } /** * Creates or updates a custom role definition. + *

          Request Body Schema

          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role definition to create or update. Managed HSM only supports '/'. - * @param roleDefinitionName The name of the role definition to create or update. It can be any valid GUID. - * @param parameters Parameters for the role definition. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return role definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createOrUpdateAsync(String vaultBaseUrl, String scope, String roleDefinitionName, - RoleDefinitionCreateParameters parameters) { - return createOrUpdateWithResponseAsync(vaultBaseUrl, scope, roleDefinitionName, parameters) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates or updates a custom role definition. + *
          +     * {@code
          +     * {
          +     *     properties (Required): {
          +     *         roleName: String (Optional)
          +     *         description: String (Optional)
          +     *         type: String(AKVBuiltInRole/CustomRole) (Optional)
          +     *         permissions (Optional): [
          +     *              (Optional){
          +     *                 actions (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 notActions (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dataActions (Optional): [
          +     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
          +     *                 ]
          +     *                 notDataActions (Optional): [
          +     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
          +     *                 ]
          +     *             }
          +     *         ]
          +     *         assignableScopes (Optional): [
          +     *             String(///keys) (Optional)
          +     *         ]
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role definition to create or update. Managed HSM only supports '/'. - * @param roleDefinitionName The name of the role definition to create or update. It can be any valid GUID. - * @param parameters Parameters for the role definition. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return role definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createOrUpdateAsync(String vaultBaseUrl, String scope, String roleDefinitionName, - RoleDefinitionCreateParameters parameters, Context context) { - return createOrUpdateWithResponseAsync(vaultBaseUrl, scope, roleDefinitionName, parameters, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates or updates a custom role definition. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     name: String (Optional)
          +     *     type: String(Microsoft.Authorization/roleDefinitions) (Optional)
          +     *     properties (Optional): {
          +     *         roleName: String (Optional)
          +     *         description: String (Optional)
          +     *         type: String(AKVBuiltInRole/CustomRole) (Optional)
          +     *         permissions (Optional): [
          +     *              (Optional){
          +     *                 actions (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 notActions (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dataActions (Optional): [
          +     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
          +     *                 ]
          +     *                 notDataActions (Optional): [
          +     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
          +     *                 ]
          +     *             }
          +     *         ]
          +     *         assignableScopes (Optional): [
          +     *             String(///keys) (Optional)
          +     *         ]
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param scope The scope of the role definition to create or update. Managed HSM only supports '/'. * @param roleDefinitionName The name of the role definition to create or update. It can be any valid GUID. * @param parameters Parameters for the role definition. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return role definition along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response createOrUpdateWithResponse(String vaultBaseUrl, String scope, - String roleDefinitionName, RoleDefinitionCreateParameters parameters, Context context) { + public Response createOrUpdateWithResponse(String scope, String roleDefinitionName, + BinaryData parameters, RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - return service.createOrUpdateSync(vaultBaseUrl, scope, roleDefinitionName, this.client.getApiVersion(), - parameters, accept, context); - } - - /** - * Creates or updates a custom role definition. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role definition to create or update. Managed HSM only supports '/'. - * @param roleDefinitionName The name of the role definition to create or update. It can be any valid GUID. - * @param parameters Parameters for the role definition. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return role definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public RoleDefinition createOrUpdate(String vaultBaseUrl, String scope, String roleDefinitionName, - RoleDefinitionCreateParameters parameters) { - return createOrUpdateWithResponse(vaultBaseUrl, scope, roleDefinitionName, parameters, Context.NONE).getValue(); + return service.createOrUpdateSync(this.client.getVaultBaseUrl(), this.client.getServiceVersion().getVersion(), + scope, roleDefinitionName, contentType, accept, parameters, requestOptions, Context.NONE); } /** * Get the specified role definition. + *

          Response Body Schema

          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role definition to get. Managed HSM only supports '/'. - * @param roleDefinitionName The name of the role definition to get. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the specified role definition along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getWithResponseAsync(String vaultBaseUrl, String scope, - String roleDefinitionName) { - return FluxUtil.withContext(context -> getWithResponseAsync(vaultBaseUrl, scope, roleDefinitionName, context)); - } - - /** - * Get the specified role definition. + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     name: String (Optional)
          +     *     type: String(Microsoft.Authorization/roleDefinitions) (Optional)
          +     *     properties (Optional): {
          +     *         roleName: String (Optional)
          +     *         description: String (Optional)
          +     *         type: String(AKVBuiltInRole/CustomRole) (Optional)
          +     *         permissions (Optional): [
          +     *              (Optional){
          +     *                 actions (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 notActions (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dataActions (Optional): [
          +     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
          +     *                 ]
          +     *                 notDataActions (Optional): [
          +     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
          +     *                 ]
          +     *             }
          +     *         ]
          +     *         assignableScopes (Optional): [
          +     *             String(///keys) (Optional)
          +     *         ]
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param scope The scope of the role definition to get. Managed HSM only supports '/'. * @param roleDefinitionName The name of the role definition to get. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the specified role definition along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getWithResponseAsync(String vaultBaseUrl, String scope, - String roleDefinitionName, Context context) { + public Mono> getWithResponseAsync(String scope, String roleDefinitionName, + RequestOptions requestOptions) { final String accept = "application/json"; - return service.get(vaultBaseUrl, scope, roleDefinitionName, this.client.getApiVersion(), accept, context); + return FluxUtil.withContext(context -> service.get(this.client.getVaultBaseUrl(), + this.client.getServiceVersion().getVersion(), scope, roleDefinitionName, accept, requestOptions, context)); } /** * Get the specified role definition. + *

          Response Body Schema

          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role definition to get. Managed HSM only supports '/'. - * @param roleDefinitionName The name of the role definition to get. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the specified role definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getAsync(String vaultBaseUrl, String scope, String roleDefinitionName) { - return getWithResponseAsync(vaultBaseUrl, scope, roleDefinitionName) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Get the specified role definition. + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     name: String (Optional)
          +     *     type: String(Microsoft.Authorization/roleDefinitions) (Optional)
          +     *     properties (Optional): {
          +     *         roleName: String (Optional)
          +     *         description: String (Optional)
          +     *         type: String(AKVBuiltInRole/CustomRole) (Optional)
          +     *         permissions (Optional): [
          +     *              (Optional){
          +     *                 actions (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 notActions (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dataActions (Optional): [
          +     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
          +     *                 ]
          +     *                 notDataActions (Optional): [
          +     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
          +     *                 ]
          +     *             }
          +     *         ]
          +     *         assignableScopes (Optional): [
          +     *             String(///keys) (Optional)
          +     *         ]
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param scope The scope of the role definition to get. Managed HSM only supports '/'. * @param roleDefinitionName The name of the role definition to get. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the specified role definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getAsync(String vaultBaseUrl, String scope, String roleDefinitionName, - Context context) { - return getWithResponseAsync(vaultBaseUrl, scope, roleDefinitionName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Get the specified role definition. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role definition to get. Managed HSM only supports '/'. - * @param roleDefinitionName The name of the role definition to get. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the specified role definition along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response getWithResponse(String vaultBaseUrl, String scope, String roleDefinitionName, - Context context) { + public Response getWithResponse(String scope, String roleDefinitionName, + RequestOptions requestOptions) { final String accept = "application/json"; - return service.getSync(vaultBaseUrl, scope, roleDefinitionName, this.client.getApiVersion(), accept, context); - } - - /** - * Get the specified role definition. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role definition to get. Managed HSM only supports '/'. - * @param roleDefinitionName The name of the role definition to get. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the specified role definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public RoleDefinition get(String vaultBaseUrl, String scope, String roleDefinitionName) { - return getWithResponse(vaultBaseUrl, scope, roleDefinitionName, Context.NONE).getValue(); + return service.getSync(this.client.getVaultBaseUrl(), this.client.getServiceVersion().getVersion(), scope, + roleDefinitionName, accept, requestOptions, Context.NONE); } /** * Get all role definitions that are applicable at scope and above. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          $filterStringNoThe filter to apply on the operation. Use atScopeAndBelow + * filter to search below the given scope as well.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role definition. - * @param filter The filter to apply on the operation. Use atScopeAndBelow filter to search below the given scope as - * well. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all role definitions that are applicable at scope and above along with {@link PagedResponse} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> listSinglePageAsync(String vaultBaseUrl, String scope, String filter) { - final String accept = "application/json"; - return FluxUtil - .withContext( - context -> service.list(vaultBaseUrl, scope, filter, this.client.getApiVersion(), accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * Get all role definitions that are applicable at scope and above. + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     name: String (Optional)
          +     *     type: String(Microsoft.Authorization/roleDefinitions) (Optional)
          +     *     properties (Optional): {
          +     *         roleName: String (Optional)
          +     *         description: String (Optional)
          +     *         type: String(AKVBuiltInRole/CustomRole) (Optional)
          +     *         permissions (Optional): [
          +     *              (Optional){
          +     *                 actions (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 notActions (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dataActions (Optional): [
          +     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
          +     *                 ]
          +     *                 notDataActions (Optional): [
          +     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
          +     *                 ]
          +     *             }
          +     *         ]
          +     *         assignableScopes (Optional): [
          +     *             String(///keys) (Optional)
          +     *         ]
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param scope The scope of the role definition. - * @param filter The filter to apply on the operation. Use atScopeAndBelow filter to search below the given scope as - * well. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return all role definitions that are applicable at scope and above along with {@link PagedResponse} on * successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> listSinglePageAsync(String vaultBaseUrl, String scope, String filter, - Context context) { + public Mono> listSinglePageAsync(String scope, RequestOptions requestOptions) { final String accept = "application/json"; - return service.list(vaultBaseUrl, scope, filter, this.client.getApiVersion(), accept, context) + return FluxUtil + .withContext(context -> service.list(this.client.getVaultBaseUrl(), + this.client.getServiceVersion().getVersion(), scope, accept, requestOptions, context)) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } /** * Get all role definitions that are applicable at scope and above. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          $filterStringNoThe filter to apply on the operation. Use atScopeAndBelow + * filter to search below the given scope as well.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role definition. - * @param filter The filter to apply on the operation. Use atScopeAndBelow filter to search below the given scope as - * well. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all role definitions that are applicable at scope and above as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listAsync(String vaultBaseUrl, String scope, String filter) { - return new PagedFlux<>(() -> listSinglePageAsync(vaultBaseUrl, scope, filter), - nextLink -> listNextSinglePageAsync(nextLink, vaultBaseUrl)); - } - - /** - * Get all role definitions that are applicable at scope and above. + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     name: String (Optional)
          +     *     type: String(Microsoft.Authorization/roleDefinitions) (Optional)
          +     *     properties (Optional): {
          +     *         roleName: String (Optional)
          +     *         description: String (Optional)
          +     *         type: String(AKVBuiltInRole/CustomRole) (Optional)
          +     *         permissions (Optional): [
          +     *              (Optional){
          +     *                 actions (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 notActions (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dataActions (Optional): [
          +     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
          +     *                 ]
          +     *                 notDataActions (Optional): [
          +     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
          +     *                 ]
          +     *             }
          +     *         ]
          +     *         assignableScopes (Optional): [
          +     *             String(///keys) (Optional)
          +     *         ]
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param scope The scope of the role definition. - * @param filter The filter to apply on the operation. Use atScopeAndBelow filter to search below the given scope as - * well. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return all role definitions that are applicable at scope and above as paginated response with {@link PagedFlux}. */ @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listAsync(String vaultBaseUrl, String scope, String filter, Context context) { - return new PagedFlux<>(() -> listSinglePageAsync(vaultBaseUrl, scope, filter, context), - nextLink -> listNextSinglePageAsync(nextLink, vaultBaseUrl, context)); + public PagedFlux listAsync(String scope, RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedFlux<>(() -> listSinglePageAsync(scope, requestOptions), + nextLink -> listNextSinglePageAsync(nextLink, requestOptionsForNextPage)); } /** * Get all role definitions that are applicable at scope and above. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          $filterStringNoThe filter to apply on the operation. Use atScopeAndBelow + * filter to search below the given scope as well.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role definition. - * @param filter The filter to apply on the operation. Use atScopeAndBelow filter to search below the given scope as - * well. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all role definitions that are applicable at scope and above along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse listSinglePage(String vaultBaseUrl, String scope, String filter) { - final String accept = "application/json"; - Response res - = service.listSync(vaultBaseUrl, scope, filter, this.client.getApiVersion(), accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * Get all role definitions that are applicable at scope and above. + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     name: String (Optional)
          +     *     type: String(Microsoft.Authorization/roleDefinitions) (Optional)
          +     *     properties (Optional): {
          +     *         roleName: String (Optional)
          +     *         description: String (Optional)
          +     *         type: String(AKVBuiltInRole/CustomRole) (Optional)
          +     *         permissions (Optional): [
          +     *              (Optional){
          +     *                 actions (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 notActions (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dataActions (Optional): [
          +     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
          +     *                 ]
          +     *                 notDataActions (Optional): [
          +     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
          +     *                 ]
          +     *             }
          +     *         ]
          +     *         assignableScopes (Optional): [
          +     *             String(///keys) (Optional)
          +     *         ]
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param scope The scope of the role definition. - * @param filter The filter to apply on the operation. Use atScopeAndBelow filter to search below the given scope as - * well. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return all role definitions that are applicable at scope and above along with {@link PagedResponse}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse listSinglePage(String vaultBaseUrl, String scope, String filter, - Context context) { + private PagedResponse listSinglePage(String scope, RequestOptions requestOptions) { final String accept = "application/json"; - Response res - = service.listSync(vaultBaseUrl, scope, filter, this.client.getApiVersion(), accept, context); + Response res = service.listSync(this.client.getVaultBaseUrl(), + this.client.getServiceVersion().getVersion(), scope, accept, requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } /** * Get all role definitions that are applicable at scope and above. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          $filterStringNoThe filter to apply on the operation. Use atScopeAndBelow + * filter to search below the given scope as well.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param scope The scope of the role definition. - * @param filter The filter to apply on the operation. Use atScopeAndBelow filter to search below the given scope as - * well. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all role definitions that are applicable at scope and above as paginated response with - * {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list(String vaultBaseUrl, String scope, String filter) { - return new PagedIterable<>(() -> listSinglePage(vaultBaseUrl, scope, filter, Context.NONE), - nextLink -> listNextSinglePage(nextLink, vaultBaseUrl)); - } - - /** - * Get all role definitions that are applicable at scope and above. + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     name: String (Optional)
          +     *     type: String(Microsoft.Authorization/roleDefinitions) (Optional)
          +     *     properties (Optional): {
          +     *         roleName: String (Optional)
          +     *         description: String (Optional)
          +     *         type: String(AKVBuiltInRole/CustomRole) (Optional)
          +     *         permissions (Optional): [
          +     *              (Optional){
          +     *                 actions (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 notActions (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dataActions (Optional): [
          +     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
          +     *                 ]
          +     *                 notDataActions (Optional): [
          +     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
          +     *                 ]
          +     *             }
          +     *         ]
          +     *         assignableScopes (Optional): [
          +     *             String(///keys) (Optional)
          +     *         ]
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param scope The scope of the role definition. - * @param filter The filter to apply on the operation. Use atScopeAndBelow filter to search below the given scope as - * well. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return all role definitions that are applicable at scope and above as paginated response with * {@link PagedIterable}. */ @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list(String vaultBaseUrl, String scope, String filter, Context context) { - return new PagedIterable<>(() -> listSinglePage(vaultBaseUrl, scope, filter, context), - nextLink -> listNextSinglePage(nextLink, vaultBaseUrl, context)); + public PagedIterable list(String scope, RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedIterable<>(() -> listSinglePage(scope, requestOptions), + nextLink -> listNextSinglePage(nextLink, requestOptionsForNextPage)); } /** * Get the next page of items. + *

          Response Body Schema

          * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return role definition list operation result along with {@link PagedResponse} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> listNextSinglePageAsync(String nextLink, String vaultBaseUrl) { - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.listNext(nextLink, vaultBaseUrl, accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * Get the next page of items. + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     name: String (Optional)
          +     *     type: String(Microsoft.Authorization/roleDefinitions) (Optional)
          +     *     properties (Optional): {
          +     *         roleName: String (Optional)
          +     *         description: String (Optional)
          +     *         type: String(AKVBuiltInRole/CustomRole) (Optional)
          +     *         permissions (Optional): [
          +     *              (Optional){
          +     *                 actions (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 notActions (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dataActions (Optional): [
          +     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
          +     *                 ]
          +     *                 notDataActions (Optional): [
          +     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
          +     *                 ]
          +     *             }
          +     *         ]
          +     *         assignableScopes (Optional): [
          +     *             String(///keys) (Optional)
          +     *         ]
          +     *     }
          +     * }
          +     * }
          +     * 
          * * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return role definition list operation result along with {@link PagedResponse} on successful completion of * {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> listNextSinglePageAsync(String nextLink, String vaultBaseUrl, - Context context) { + public Mono> listNextSinglePageAsync(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; - return service.listNext(nextLink, vaultBaseUrl, accept, context) + return FluxUtil + .withContext( + context -> service.listNext(nextLink, this.client.getVaultBaseUrl(), accept, requestOptions, context)) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } /** * Get the next page of items. + *

          Response Body Schema

          * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return role definition list operation result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse listNextSinglePage(String nextLink, String vaultBaseUrl) { - final String accept = "application/json"; - Response res = service.listNextSync(nextLink, vaultBaseUrl, accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * Get the next page of items. + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     name: String (Optional)
          +     *     type: String(Microsoft.Authorization/roleDefinitions) (Optional)
          +     *     properties (Optional): {
          +     *         roleName: String (Optional)
          +     *         description: String (Optional)
          +     *         type: String(AKVBuiltInRole/CustomRole) (Optional)
          +     *         permissions (Optional): [
          +     *              (Optional){
          +     *                 actions (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 notActions (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dataActions (Optional): [
          +     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
          +     *                 ]
          +     *                 notDataActions (Optional): [
          +     *                     String(Microsoft.KeyVaultAdministration/managedHsm/keys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/write/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/read/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/recover/action/Microsoft.KeyVaultAdministration/managedHsm/keys/backup/action/Microsoft.KeyVaultAdministration/managedHsm/keys/restore/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/delete/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleAssignments/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/read/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/write/action/Microsoft.KeyVaultAdministration/managedHsm/roleDefinitions/delete/action/Microsoft.KeyVaultAdministration/managedHsm/keys/encrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/decrypt/action/Microsoft.KeyVaultAdministration/managedHsm/keys/wrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/unwrap/action/Microsoft.KeyVaultAdministration/managedHsm/keys/sign/action/Microsoft.KeyVaultAdministration/managedHsm/keys/verify/action/Microsoft.KeyVaultAdministration/managedHsm/keys/create/Microsoft.KeyVaultAdministration/managedHsm/keys/delete/Microsoft.KeyVaultAdministration/managedHsm/keys/export/action/Microsoft.KeyVaultAdministration/managedHsm/keys/release/action/Microsoft.KeyVaultAdministration/managedHsm/keys/import/action/Microsoft.KeyVaultAdministration/managedHsm/keys/deletedKeys/delete/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/download/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/action/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/upload/read/Microsoft.KeyVaultAdministration/managedHsm/securitydomain/transferkey/read/Microsoft.KeyVaultAdministration/managedHsm/backup/start/action/Microsoft.KeyVaultAdministration/managedHsm/restore/start/action/Microsoft.KeyVaultAdministration/managedHsm/backup/status/action/Microsoft.KeyVaultAdministration/managedHsm/restore/status/action/Microsoft.KeyVaultAdministration/managedHsm/rng/action) (Optional)
          +     *                 ]
          +     *             }
          +     *         ]
          +     *         assignableScopes (Optional): [
          +     *             String(///keys) (Optional)
          +     *         ]
          +     *     }
          +     * }
          +     * }
          +     * 
          * * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return role definition list operation result along with {@link PagedResponse}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse listNextSinglePage(String nextLink, String vaultBaseUrl, Context context) { + private PagedResponse listNextSinglePage(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; - Response res = service.listNextSync(nextLink, vaultBaseUrl, accept, context); + Response res + = service.listNextSync(nextLink, this.client.getVaultBaseUrl(), accept, requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); + } + + private List getValues(BinaryData binaryData, String path) { + try { + Map obj = binaryData.toObject(Map.class); + List values = (List) obj.get(path); + return values.stream().map(BinaryData::fromObject).collect(Collectors.toList()); + } catch (RuntimeException e) { + return null; + } + } + + private String getNextLink(BinaryData binaryData, String path) { + try { + Map obj = binaryData.toObject(Map.class); + return (String) obj.get(path); + } catch (RuntimeException e) { + return null; + } } } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/Error.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/Error.java index c9a4e1eeffe0..11a8af359290 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/Error.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/Error.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.administration.implementation.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -16,50 +16,58 @@ */ @Immutable public final class Error implements JsonSerializable { + /* * The error code. */ + @Generated private String code; /* * The error message. */ + @Generated private String message; /* * The key vault server error. */ + @Generated private Error innerError; /** * Creates an instance of Error class. */ - public Error() { + @Generated + private Error() { } /** * Get the code property: The error code. - * + * * @return the code value. */ + @Generated public String getCode() { return this.code; } /** * Get the message property: The error message. - * + * * @return the message value. */ + @Generated public String getMessage() { return this.message; } /** * Get the innerError property: The key vault server error. - * + * * @return the innerError value. */ + @Generated public Error getInnerError() { return this.innerError; } @@ -67,6 +75,7 @@ public Error getInnerError() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -75,19 +84,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of Error from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of Error 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 Error. */ + @Generated public static Error fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { Error deserializedError = new Error(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("code".equals(fieldName)) { deserializedError.code = reader.getString(); } else if ("message".equals(fieldName)) { @@ -98,7 +107,6 @@ public static Error fromJson(JsonReader jsonReader) throws IOException { reader.skipChildren(); } } - return deserializedError; }); } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/FullBackupHeaders.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/FullBackupHeaders.java deleted file mode 100644 index 714329401dd7..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/FullBackupHeaders.java +++ /dev/null @@ -1,79 +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.security.keyvault.administration.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.http.HttpHeaderName; -import com.azure.core.http.HttpHeaders; - -/** - * The FullBackupHeaders model. - */ -@Fluent -public final class FullBackupHeaders { - /* - * The Retry-After property. - */ - private Integer retryAfter; - - /* - * The Azure-AsyncOperation property. - */ - private String azureAsyncOperation; - - // HttpHeaders containing the raw property values. - /** - * Creates an instance of FullBackupHeaders class. - * - * @param rawHeaders The raw HttpHeaders that will be used to create the property values. - */ - public FullBackupHeaders(HttpHeaders rawHeaders) { - String retryAfter = rawHeaders.getValue(HttpHeaderName.RETRY_AFTER); - if (retryAfter != null) { - this.retryAfter = Integer.parseInt(retryAfter); - } - this.azureAsyncOperation = rawHeaders.getValue(HttpHeaderName.AZURE_ASYNCOPERATION); - } - - /** - * Get the retryAfter property: The Retry-After property. - * - * @return the retryAfter value. - */ - public Integer getRetryAfter() { - return this.retryAfter; - } - - /** - * Set the retryAfter property: The Retry-After property. - * - * @param retryAfter the retryAfter value to set. - * @return the FullBackupHeaders object itself. - */ - public FullBackupHeaders setRetryAfter(Integer retryAfter) { - this.retryAfter = retryAfter; - return this; - } - - /** - * Get the azureAsyncOperation property: The Azure-AsyncOperation property. - * - * @return the azureAsyncOperation value. - */ - public String getAzureAsyncOperation() { - return this.azureAsyncOperation; - } - - /** - * Set the azureAsyncOperation property: The Azure-AsyncOperation property. - * - * @param azureAsyncOperation the azureAsyncOperation value to set. - * @return the FullBackupHeaders object itself. - */ - public FullBackupHeaders setAzureAsyncOperation(String azureAsyncOperation) { - this.azureAsyncOperation = azureAsyncOperation; - return this; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/FullBackupOperation.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/FullBackupOperation.java index 6dde8ddfa1b3..9e80b74d3953 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/FullBackupOperation.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/FullBackupOperation.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.administration.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -17,114 +17,94 @@ /** * Full backup operation. */ -@Fluent +@Immutable public final class FullBackupOperation implements JsonSerializable { + /* * Status of the backup operation. */ - private String status; + @Generated + private OperationStatus status; /* * The status details of backup operation. */ + @Generated private String statusDetails; /* * Error encountered, if any, during the full backup operation. */ - private Error error; + @Generated + private FullBackupOperationError error; /* * The start time of the backup operation in UTC */ + @Generated private Long startTime; /* * The end time of the backup operation in UTC */ + @Generated private Long endTime; /* * Identifier for the full backup operation. */ + @Generated private String jobId; /* * The Azure blob storage container Uri which contains the full backup */ + @Generated private String azureStorageBlobContainerUri; /** * Creates an instance of FullBackupOperation class. */ - public FullBackupOperation() { + @Generated + private FullBackupOperation() { } /** * Get the status property: Status of the backup operation. - * + * * @return the status value. */ - public String getStatus() { + @Generated + public OperationStatus getStatus() { return this.status; } - /** - * Set the status property: Status of the backup operation. - * - * @param status the status value to set. - * @return the FullBackupOperation object itself. - */ - public FullBackupOperation setStatus(String status) { - this.status = status; - return this; - } - /** * Get the statusDetails property: The status details of backup operation. - * + * * @return the statusDetails value. */ + @Generated public String getStatusDetails() { return this.statusDetails; } - /** - * Set the statusDetails property: The status details of backup operation. - * - * @param statusDetails the statusDetails value to set. - * @return the FullBackupOperation object itself. - */ - public FullBackupOperation setStatusDetails(String statusDetails) { - this.statusDetails = statusDetails; - return this; - } - /** * Get the error property: Error encountered, if any, during the full backup operation. - * + * * @return the error value. */ - public Error getError() { + @Generated + public FullBackupOperationError getError() { return this.error; } - /** - * Set the error property: Error encountered, if any, during the full backup operation. - * - * @param error the error value to set. - * @return the FullBackupOperation object itself. - */ - public FullBackupOperation setError(Error error) { - this.error = error; - return this; - } - /** * Get the startTime property: The start time of the backup operation in UTC. - * + * * @return the startTime value. */ + @Generated public OffsetDateTime getStartTime() { if (this.startTime == null) { return null; @@ -132,26 +112,12 @@ public OffsetDateTime getStartTime() { return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.startTime), ZoneOffset.UTC); } - /** - * Set the startTime property: The start time of the backup operation in UTC. - * - * @param startTime the startTime value to set. - * @return the FullBackupOperation object itself. - */ - public FullBackupOperation setStartTime(OffsetDateTime startTime) { - if (startTime == null) { - this.startTime = null; - } else { - this.startTime = startTime.toEpochSecond(); - } - return this; - } - /** * Get the endTime property: The end time of the backup operation in UTC. - * + * * @return the endTime value. */ + @Generated public OffsetDateTime getEndTime() { if (this.endTime == null) { return null; @@ -159,70 +125,35 @@ public OffsetDateTime getEndTime() { return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.endTime), ZoneOffset.UTC); } - /** - * Set the endTime property: The end time of the backup operation in UTC. - * - * @param endTime the endTime value to set. - * @return the FullBackupOperation object itself. - */ - public FullBackupOperation setEndTime(OffsetDateTime endTime) { - if (endTime == null) { - this.endTime = null; - } else { - this.endTime = endTime.toEpochSecond(); - } - return this; - } - /** * Get the jobId property: Identifier for the full backup operation. - * + * * @return the jobId value. */ + @Generated public String getJobId() { return this.jobId; } - /** - * Set the jobId property: Identifier for the full backup operation. - * - * @param jobId the jobId value to set. - * @return the FullBackupOperation object itself. - */ - public FullBackupOperation setJobId(String jobId) { - this.jobId = jobId; - return this; - } - /** * Get the azureStorageBlobContainerUri property: The Azure blob storage container Uri which contains the full * backup. - * + * * @return the azureStorageBlobContainerUri value. */ + @Generated public String getAzureStorageBlobContainerUri() { return this.azureStorageBlobContainerUri; } - /** - * Set the azureStorageBlobContainerUri property: The Azure blob storage container Uri which contains the full - * backup. - * - * @param azureStorageBlobContainerUri the azureStorageBlobContainerUri value to set. - * @return the FullBackupOperation object itself. - */ - public FullBackupOperation setAzureStorageBlobContainerUri(String azureStorageBlobContainerUri) { - this.azureStorageBlobContainerUri = azureStorageBlobContainerUri; - return this; - } - /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeStringField("status", this.status); + jsonWriter.writeStringField("status", this.status == null ? null : this.status.toString()); jsonWriter.writeStringField("statusDetails", this.statusDetails); jsonWriter.writeJsonField("error", this.error); jsonWriter.writeNumberField("startTime", this.startTime); @@ -234,25 +165,25 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of FullBackupOperation from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of FullBackupOperation 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 FullBackupOperation. */ + @Generated public static FullBackupOperation fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { FullBackupOperation deserializedFullBackupOperation = new FullBackupOperation(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("status".equals(fieldName)) { - deserializedFullBackupOperation.status = reader.getString(); + deserializedFullBackupOperation.status = OperationStatus.fromString(reader.getString()); } else if ("statusDetails".equals(fieldName)) { deserializedFullBackupOperation.statusDetails = reader.getString(); } else if ("error".equals(fieldName)) { - deserializedFullBackupOperation.error = Error.fromJson(reader); + deserializedFullBackupOperation.error = FullBackupOperationError.fromJson(reader); } else if ("startTime".equals(fieldName)) { deserializedFullBackupOperation.startTime = reader.getNullable(JsonReader::getLong); } else if ("endTime".equals(fieldName)) { @@ -265,7 +196,6 @@ public static FullBackupOperation fromJson(JsonReader jsonReader) throws IOExcep reader.skipChildren(); } } - return deserializedFullBackupOperation; }); } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/FullBackupOperationError.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/FullBackupOperationError.java new file mode 100644 index 000000000000..04d1ce8d1244 --- /dev/null +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/FullBackupOperationError.java @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.security.keyvault.administration.implementation.models; + +import com.azure.core.annotation.Generated; +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 FullBackupOperationError model. + */ +@Immutable +public final class FullBackupOperationError implements JsonSerializable { + + /* + * The error code. + */ + @Generated + private String code; + + /* + * The error message. + */ + @Generated + private String message; + + /* + * The key vault server error. + */ + @Generated + private FullBackupOperationError innerError; + + /** + * Creates an instance of FullBackupOperationError class. + */ + @Generated + private FullBackupOperationError() { + } + + /** + * Get the code property: The error code. + * + * @return the code value. + */ + @Generated + public String getCode() { + return this.code; + } + + /** + * Get the message property: The error message. + * + * @return the message value. + */ + @Generated + public String getMessage() { + return this.message; + } + + /** + * Get the innerError property: The key vault server error. + * + * @return the innerError value. + */ + @Generated + public FullBackupOperationError getInnerError() { + return this.innerError; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of FullBackupOperationError from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of FullBackupOperationError 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 FullBackupOperationError. + */ + @Generated + public static FullBackupOperationError fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + FullBackupOperationError deserializedFullBackupOperationError = new FullBackupOperationError(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("code".equals(fieldName)) { + deserializedFullBackupOperationError.code = reader.getString(); + } else if ("message".equals(fieldName)) { + deserializedFullBackupOperationError.message = reader.getString(); + } else if ("innererror".equals(fieldName)) { + deserializedFullBackupOperationError.innerError = FullBackupOperationError.fromJson(reader); + } else { + reader.skipChildren(); + } + } + return deserializedFullBackupOperationError; + }); + } +} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/FullRestoreOperationHeaders.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/FullRestoreOperationHeaders.java deleted file mode 100644 index 889ee5c03bc6..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/FullRestoreOperationHeaders.java +++ /dev/null @@ -1,79 +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.security.keyvault.administration.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.http.HttpHeaderName; -import com.azure.core.http.HttpHeaders; - -/** - * The FullRestoreOperationHeaders model. - */ -@Fluent -public final class FullRestoreOperationHeaders { - /* - * The Retry-After property. - */ - private Integer retryAfter; - - /* - * The Azure-AsyncOperation property. - */ - private String azureAsyncOperation; - - // HttpHeaders containing the raw property values. - /** - * Creates an instance of FullRestoreOperationHeaders class. - * - * @param rawHeaders The raw HttpHeaders that will be used to create the property values. - */ - public FullRestoreOperationHeaders(HttpHeaders rawHeaders) { - String retryAfter = rawHeaders.getValue(HttpHeaderName.RETRY_AFTER); - if (retryAfter != null) { - this.retryAfter = Integer.parseInt(retryAfter); - } - this.azureAsyncOperation = rawHeaders.getValue(HttpHeaderName.AZURE_ASYNCOPERATION); - } - - /** - * Get the retryAfter property: The Retry-After property. - * - * @return the retryAfter value. - */ - public Integer getRetryAfter() { - return this.retryAfter; - } - - /** - * Set the retryAfter property: The Retry-After property. - * - * @param retryAfter the retryAfter value to set. - * @return the FullRestoreOperationHeaders object itself. - */ - public FullRestoreOperationHeaders setRetryAfter(Integer retryAfter) { - this.retryAfter = retryAfter; - return this; - } - - /** - * Get the azureAsyncOperation property: The Azure-AsyncOperation property. - * - * @return the azureAsyncOperation value. - */ - public String getAzureAsyncOperation() { - return this.azureAsyncOperation; - } - - /** - * Set the azureAsyncOperation property: The Azure-AsyncOperation property. - * - * @param azureAsyncOperation the azureAsyncOperation value to set. - * @return the FullRestoreOperationHeaders object itself. - */ - public FullRestoreOperationHeaders setAzureAsyncOperation(String azureAsyncOperation) { - this.azureAsyncOperation = azureAsyncOperation; - return this; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/KeyVaultError.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/KeyVaultError.java deleted file mode 100644 index f60a6751110a..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/KeyVaultError.java +++ /dev/null @@ -1,73 +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.security.keyvault.administration.implementation.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 key vault error exception. - */ -@Immutable -public final class KeyVaultError implements JsonSerializable { - /* - * The key vault server error. - */ - private Error error; - - /** - * Creates an instance of KeyVaultError class. - */ - public KeyVaultError() { - } - - /** - * Get the error property: The key vault server error. - * - * @return the error value. - */ - public Error getError() { - return this.error; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KeyVaultError from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KeyVaultError 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 KeyVaultError. - */ - public static KeyVaultError fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeyVaultError deserializedKeyVaultError = new KeyVaultError(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("error".equals(fieldName)) { - deserializedKeyVaultError.error = Error.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedKeyVaultError; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/KeyVaultErrorException.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/KeyVaultErrorException.java deleted file mode 100644 index 77c335a8caf9..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/KeyVaultErrorException.java +++ /dev/null @@ -1,42 +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.security.keyvault.administration.implementation.models; - -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpResponse; - -/** - * Exception thrown for an invalid response with KeyVaultError information. - */ -public final class KeyVaultErrorException extends HttpResponseException { - /** - * Initializes a new instance of the KeyVaultErrorException class. - * - * @param message the exception message or the response content if a message is not available. - * @param response the HTTP response. - */ - public KeyVaultErrorException(String message, HttpResponse response) { - super(message, response); - } - - /** - * Initializes a new instance of the KeyVaultErrorException 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 KeyVaultErrorException(String message, HttpResponse response, KeyVaultError value) { - super(message, response, value); - } - - /** - * {@inheritDoc} - */ - @Override - public KeyVaultError getValue() { - return (KeyVaultError) super.getValue(); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/OperationStatus.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/OperationStatus.java new file mode 100644 index 000000000000..3177a6fdba2f --- /dev/null +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/OperationStatus.java @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.security.keyvault.administration.implementation.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The status of a long-running operation. + */ +public final class OperationStatus extends ExpandableStringEnum { + + /** + * The operation is in progress. + */ + @Generated + public static final OperationStatus IN_PROGRESS = fromString("InProgress"); + + /** + * The operation successfully completed. + */ + @Generated + public static final OperationStatus SUCCEEDED = fromString("Succeeded"); + + /** + * The operation was canceled. + */ + @Generated + public static final OperationStatus CANCELED = fromString("Canceled"); + + /** + * The operation failed. + */ + @Generated + public static final OperationStatus FAILED = fromString("Failed"); + + /** + * Creates a new instance of OperationStatus value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public OperationStatus() { + } + + /** + * Creates or finds a OperationStatus from its string representation. + * + * @param name a name to look for. + * @return the corresponding OperationStatus. + */ + @Generated + public static OperationStatus fromString(String name) { + return fromString(name, OperationStatus.class); + } + + /** + * Gets known OperationStatus values. + * + * @return known OperationStatus values. + */ + @Generated + public static Collection values() { + return values(OperationStatus.class); + } +} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/Permission.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/Permission.java index 8efde6e2cc6b..c66cfa63bf54 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/Permission.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/Permission.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.administration.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -18,49 +18,57 @@ */ @Fluent public final class Permission implements JsonSerializable { + /* * Action permissions that are granted. */ + @Generated private List actions; /* * Action permissions that are excluded but not denied. They may be granted by other role definitions assigned to a * principal. */ + @Generated private List notActions; /* * Data action permissions that are granted. */ + @Generated private List dataActions; /* * Data action permissions that are excluded but not denied. They may be granted by other role definitions assigned * to a principal. */ + @Generated private List notDataActions; /** * Creates an instance of Permission class. */ + @Generated public Permission() { } /** * Get the actions property: Action permissions that are granted. - * + * * @return the actions value. */ + @Generated public List getActions() { return this.actions; } /** * Set the actions property: Action permissions that are granted. - * + * * @param actions the actions value to set. * @return the Permission object itself. */ + @Generated public Permission setActions(List actions) { this.actions = actions; return this; @@ -69,9 +77,10 @@ public Permission setActions(List actions) { /** * Get the notActions property: Action permissions that are excluded but not denied. They may be granted by other * role definitions assigned to a principal. - * + * * @return the notActions value. */ + @Generated public List getNotActions() { return this.notActions; } @@ -79,10 +88,11 @@ public List getNotActions() { /** * Set the notActions property: Action permissions that are excluded but not denied. They may be granted by other * role definitions assigned to a principal. - * + * * @param notActions the notActions value to set. * @return the Permission object itself. */ + @Generated public Permission setNotActions(List notActions) { this.notActions = notActions; return this; @@ -90,19 +100,21 @@ public Permission setNotActions(List notActions) { /** * Get the dataActions property: Data action permissions that are granted. - * + * * @return the dataActions value. */ + @Generated public List getDataActions() { return this.dataActions; } /** * Set the dataActions property: Data action permissions that are granted. - * + * * @param dataActions the dataActions value to set. * @return the Permission object itself. */ + @Generated public Permission setDataActions(List dataActions) { this.dataActions = dataActions; return this; @@ -111,9 +123,10 @@ public Permission setDataActions(List dataActions) { /** * Get the notDataActions property: Data action permissions that are excluded but not denied. They may be granted by * other role definitions assigned to a principal. - * + * * @return the notDataActions value. */ + @Generated public List getNotDataActions() { return this.notDataActions; } @@ -121,10 +134,11 @@ public List getNotDataActions() { /** * Set the notDataActions property: Data action permissions that are excluded but not denied. They may be granted by * other role definitions assigned to a principal. - * + * * @param notDataActions the notDataActions value to set. * @return the Permission object itself. */ + @Generated public Permission setNotDataActions(List notDataActions) { this.notDataActions = notDataActions; return this; @@ -133,6 +147,7 @@ public Permission setNotDataActions(List notDataActions) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -147,19 +162,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of Permission from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of Permission 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 Permission. */ + @Generated public static Permission fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { Permission deserializedPermission = new Permission(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("actions".equals(fieldName)) { List actions = reader.readArray(reader1 -> reader1.getString()); deserializedPermission.actions = actions; @@ -178,7 +193,6 @@ public static Permission fromJson(JsonReader jsonReader) throws IOException { reader.skipChildren(); } } - return deserializedPermission; }); } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/PreBackupOperationParameters.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/PreBackupOperationParameters.java index bb15bcc438ee..82e2a4dc67ea 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/PreBackupOperationParameters.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/PreBackupOperationParameters.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.administration.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -12,47 +12,54 @@ import java.io.IOException; /** - * The PreBackupOperationParameters model. + * The authentication method and location for the backup operation. */ @Fluent public final class PreBackupOperationParameters implements JsonSerializable { + /* * Azure Blob storage container Uri */ + @Generated private String storageResourceUri; /* * The SAS token pointing to an Azure Blob storage container */ + @Generated private String token; /* * Indicates which authentication method should be used. If set to true, Managed HSM will use the configured * user-assigned managed identity to authenticate with Azure Storage. Otherwise, a SAS token has to be specified. */ + @Generated private Boolean useManagedIdentity; /** * Creates an instance of PreBackupOperationParameters class. */ + @Generated public PreBackupOperationParameters() { } /** * Get the storageResourceUri property: Azure Blob storage container Uri. - * + * * @return the storageResourceUri value. */ + @Generated public String getStorageResourceUri() { return this.storageResourceUri; } /** * Set the storageResourceUri property: Azure Blob storage container Uri. - * + * * @param storageResourceUri the storageResourceUri value to set. * @return the PreBackupOperationParameters object itself. */ + @Generated public PreBackupOperationParameters setStorageResourceUri(String storageResourceUri) { this.storageResourceUri = storageResourceUri; return this; @@ -60,19 +67,21 @@ public PreBackupOperationParameters setStorageResourceUri(String storageResource /** * Get the token property: The SAS token pointing to an Azure Blob storage container. - * + * * @return the token value. */ + @Generated public String getToken() { return this.token; } /** * Set the token property: The SAS token pointing to an Azure Blob storage container. - * + * * @param token the token value to set. * @return the PreBackupOperationParameters object itself. */ + @Generated public PreBackupOperationParameters setToken(String token) { this.token = token; return this; @@ -82,9 +91,10 @@ public PreBackupOperationParameters setToken(String token) { * Get the useManagedIdentity property: Indicates which authentication method should be used. If set to true, * Managed HSM will use the configured user-assigned managed identity to authenticate with Azure Storage. Otherwise, * a SAS token has to be specified. - * + * * @return the useManagedIdentity value. */ + @Generated public Boolean isUseManagedIdentity() { return this.useManagedIdentity; } @@ -93,10 +103,11 @@ public Boolean isUseManagedIdentity() { * Set the useManagedIdentity property: Indicates which authentication method should be used. If set to true, * Managed HSM will use the configured user-assigned managed identity to authenticate with Azure Storage. Otherwise, * a SAS token has to be specified. - * + * * @param useManagedIdentity the useManagedIdentity value to set. * @return the PreBackupOperationParameters object itself. */ + @Generated public PreBackupOperationParameters setUseManagedIdentity(Boolean useManagedIdentity) { this.useManagedIdentity = useManagedIdentity; return this; @@ -105,6 +116,7 @@ public PreBackupOperationParameters setUseManagedIdentity(Boolean useManagedIden /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -116,19 +128,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of PreBackupOperationParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of PreBackupOperationParameters 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 PreBackupOperationParameters. */ + @Generated public static PreBackupOperationParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { PreBackupOperationParameters deserializedPreBackupOperationParameters = new PreBackupOperationParameters(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("storageResourceUri".equals(fieldName)) { deserializedPreBackupOperationParameters.storageResourceUri = reader.getString(); } else if ("token".equals(fieldName)) { @@ -140,7 +152,6 @@ public static PreBackupOperationParameters fromJson(JsonReader jsonReader) throw reader.skipChildren(); } } - return deserializedPreBackupOperationParameters; }); } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/PreFullBackupHeaders.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/PreFullBackupHeaders.java deleted file mode 100644 index 1c5df0a59cc4..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/PreFullBackupHeaders.java +++ /dev/null @@ -1,79 +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.security.keyvault.administration.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.http.HttpHeaderName; -import com.azure.core.http.HttpHeaders; - -/** - * The PreFullBackupHeaders model. - */ -@Fluent -public final class PreFullBackupHeaders { - /* - * The Retry-After property. - */ - private Long retryAfter; - - /* - * The Azure-AsyncOperation property. - */ - private String azureAsyncOperation; - - // HttpHeaders containing the raw property values. - /** - * Creates an instance of PreFullBackupHeaders class. - * - * @param rawHeaders The raw HttpHeaders that will be used to create the property values. - */ - public PreFullBackupHeaders(HttpHeaders rawHeaders) { - String retryAfter = rawHeaders.getValue(HttpHeaderName.RETRY_AFTER); - if (retryAfter != null) { - this.retryAfter = Long.parseLong(retryAfter); - } - this.azureAsyncOperation = rawHeaders.getValue(HttpHeaderName.AZURE_ASYNCOPERATION); - } - - /** - * Get the retryAfter property: The Retry-After property. - * - * @return the retryAfter value. - */ - public Long getRetryAfter() { - return this.retryAfter; - } - - /** - * Set the retryAfter property: The Retry-After property. - * - * @param retryAfter the retryAfter value to set. - * @return the PreFullBackupHeaders object itself. - */ - public PreFullBackupHeaders setRetryAfter(Long retryAfter) { - this.retryAfter = retryAfter; - return this; - } - - /** - * Get the azureAsyncOperation property: The Azure-AsyncOperation property. - * - * @return the azureAsyncOperation value. - */ - public String getAzureAsyncOperation() { - return this.azureAsyncOperation; - } - - /** - * Set the azureAsyncOperation property: The Azure-AsyncOperation property. - * - * @param azureAsyncOperation the azureAsyncOperation value to set. - * @return the PreFullBackupHeaders object itself. - */ - public PreFullBackupHeaders setAzureAsyncOperation(String azureAsyncOperation) { - this.azureAsyncOperation = azureAsyncOperation; - return this; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/PreFullRestoreOperationHeaders.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/PreFullRestoreOperationHeaders.java deleted file mode 100644 index 690e0eabd41e..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/PreFullRestoreOperationHeaders.java +++ /dev/null @@ -1,79 +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.security.keyvault.administration.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.http.HttpHeaderName; -import com.azure.core.http.HttpHeaders; - -/** - * The PreFullRestoreOperationHeaders model. - */ -@Fluent -public final class PreFullRestoreOperationHeaders { - /* - * The Retry-After property. - */ - private Long retryAfter; - - /* - * The Azure-AsyncOperation property. - */ - private String azureAsyncOperation; - - // HttpHeaders containing the raw property values. - /** - * Creates an instance of PreFullRestoreOperationHeaders class. - * - * @param rawHeaders The raw HttpHeaders that will be used to create the property values. - */ - public PreFullRestoreOperationHeaders(HttpHeaders rawHeaders) { - String retryAfter = rawHeaders.getValue(HttpHeaderName.RETRY_AFTER); - if (retryAfter != null) { - this.retryAfter = Long.parseLong(retryAfter); - } - this.azureAsyncOperation = rawHeaders.getValue(HttpHeaderName.AZURE_ASYNCOPERATION); - } - - /** - * Get the retryAfter property: The Retry-After property. - * - * @return the retryAfter value. - */ - public Long getRetryAfter() { - return this.retryAfter; - } - - /** - * Set the retryAfter property: The Retry-After property. - * - * @param retryAfter the retryAfter value to set. - * @return the PreFullRestoreOperationHeaders object itself. - */ - public PreFullRestoreOperationHeaders setRetryAfter(Long retryAfter) { - this.retryAfter = retryAfter; - return this; - } - - /** - * Get the azureAsyncOperation property: The Azure-AsyncOperation property. - * - * @return the azureAsyncOperation value. - */ - public String getAzureAsyncOperation() { - return this.azureAsyncOperation; - } - - /** - * Set the azureAsyncOperation property: The Azure-AsyncOperation property. - * - * @param azureAsyncOperation the azureAsyncOperation value to set. - * @return the PreFullRestoreOperationHeaders object itself. - */ - public PreFullRestoreOperationHeaders setAzureAsyncOperation(String azureAsyncOperation) { - this.azureAsyncOperation = azureAsyncOperation; - return this; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/PreRestoreOperationParameters.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/PreRestoreOperationParameters.java index 4381d9c75835..bc6c4cc9456e 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/PreRestoreOperationParameters.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/PreRestoreOperationParameters.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.administration.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -12,41 +12,47 @@ import java.io.IOException; /** - * The PreRestoreOperationParameters model. + * The authentication method and location for the restore operation. */ @Fluent public final class PreRestoreOperationParameters implements JsonSerializable { + /* - * The sasTokenParameters property. + * A user-provided SAS token to an Azure blob storage container. */ + @Generated private SASTokenParameter sasTokenParameters; /* * The Folder name of the blob where the previous successful full backup was stored */ + @Generated private String folderToRestore; /** * Creates an instance of PreRestoreOperationParameters class. */ + @Generated public PreRestoreOperationParameters() { } /** - * Get the sasTokenParameters property: The sasTokenParameters property. - * + * Get the sasTokenParameters property: A user-provided SAS token to an Azure blob storage container. + * * @return the sasTokenParameters value. */ + @Generated public SASTokenParameter getSasTokenParameters() { return this.sasTokenParameters; } /** - * Set the sasTokenParameters property: The sasTokenParameters property. - * + * Set the sasTokenParameters property: A user-provided SAS token to an Azure blob storage container. + * * @param sasTokenParameters the sasTokenParameters value to set. * @return the PreRestoreOperationParameters object itself. */ + @Generated public PreRestoreOperationParameters setSasTokenParameters(SASTokenParameter sasTokenParameters) { this.sasTokenParameters = sasTokenParameters; return this; @@ -55,9 +61,10 @@ public PreRestoreOperationParameters setSasTokenParameters(SASTokenParameter sas /** * Get the folderToRestore property: The Folder name of the blob where the previous successful full backup was * stored. - * + * * @return the folderToRestore value. */ + @Generated public String getFolderToRestore() { return this.folderToRestore; } @@ -65,10 +72,11 @@ public String getFolderToRestore() { /** * Set the folderToRestore property: The Folder name of the blob where the previous successful full backup was * stored. - * + * * @param folderToRestore the folderToRestore value to set. * @return the PreRestoreOperationParameters object itself. */ + @Generated public PreRestoreOperationParameters setFolderToRestore(String folderToRestore) { this.folderToRestore = folderToRestore; return this; @@ -77,6 +85,7 @@ public PreRestoreOperationParameters setFolderToRestore(String folderToRestore) /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -87,12 +96,13 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of PreRestoreOperationParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of PreRestoreOperationParameters 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 PreRestoreOperationParameters. */ + @Generated public static PreRestoreOperationParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { PreRestoreOperationParameters deserializedPreRestoreOperationParameters @@ -100,7 +110,6 @@ public static PreRestoreOperationParameters fromJson(JsonReader jsonReader) thro while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("sasTokenParameters".equals(fieldName)) { deserializedPreRestoreOperationParameters.sasTokenParameters = SASTokenParameter.fromJson(reader); } else if ("folderToRestore".equals(fieldName)) { @@ -109,7 +118,6 @@ public static PreRestoreOperationParameters fromJson(JsonReader jsonReader) thro reader.skipChildren(); } } - return deserializedPreRestoreOperationParameters; }); } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RestoreOperation.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RestoreOperation.java index 82c0ab7da718..c6da7ae001ad 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RestoreOperation.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RestoreOperation.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.administration.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -17,129 +17,98 @@ /** * Restore operation. */ -@Fluent +@Immutable public final class RestoreOperation implements JsonSerializable { + /* * Status of the restore operation. */ - private String status; + @Generated + private OperationStatus status; /* * The status details of restore operation. */ + @Generated private String statusDetails; /* * Error encountered, if any, during the restore operation. */ - private Error error; + @Generated + private FullBackupOperationError error; /* * Identifier for the restore operation. */ + @Generated private String jobId; /* * The start time of the restore operation */ + @Generated private Long startTime; /* * The end time of the restore operation */ + @Generated private Long endTime; /** * Creates an instance of RestoreOperation class. */ - public RestoreOperation() { + @Generated + private RestoreOperation() { } /** * Get the status property: Status of the restore operation. - * + * * @return the status value. */ - public String getStatus() { + @Generated + public OperationStatus getStatus() { return this.status; } - /** - * Set the status property: Status of the restore operation. - * - * @param status the status value to set. - * @return the RestoreOperation object itself. - */ - public RestoreOperation setStatus(String status) { - this.status = status; - return this; - } - /** * Get the statusDetails property: The status details of restore operation. - * + * * @return the statusDetails value. */ + @Generated public String getStatusDetails() { return this.statusDetails; } - /** - * Set the statusDetails property: The status details of restore operation. - * - * @param statusDetails the statusDetails value to set. - * @return the RestoreOperation object itself. - */ - public RestoreOperation setStatusDetails(String statusDetails) { - this.statusDetails = statusDetails; - return this; - } - /** * Get the error property: Error encountered, if any, during the restore operation. - * + * * @return the error value. */ - public Error getError() { + @Generated + public FullBackupOperationError getError() { return this.error; } - /** - * Set the error property: Error encountered, if any, during the restore operation. - * - * @param error the error value to set. - * @return the RestoreOperation object itself. - */ - public RestoreOperation setError(Error error) { - this.error = error; - return this; - } - /** * Get the jobId property: Identifier for the restore operation. - * + * * @return the jobId value. */ + @Generated public String getJobId() { return this.jobId; } - /** - * Set the jobId property: Identifier for the restore operation. - * - * @param jobId the jobId value to set. - * @return the RestoreOperation object itself. - */ - public RestoreOperation setJobId(String jobId) { - this.jobId = jobId; - return this; - } - /** * Get the startTime property: The start time of the restore operation. - * + * * @return the startTime value. */ + @Generated public OffsetDateTime getStartTime() { if (this.startTime == null) { return null; @@ -147,26 +116,12 @@ public OffsetDateTime getStartTime() { return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.startTime), ZoneOffset.UTC); } - /** - * Set the startTime property: The start time of the restore operation. - * - * @param startTime the startTime value to set. - * @return the RestoreOperation object itself. - */ - public RestoreOperation setStartTime(OffsetDateTime startTime) { - if (startTime == null) { - this.startTime = null; - } else { - this.startTime = startTime.toEpochSecond(); - } - return this; - } - /** * Get the endTime property: The end time of the restore operation. - * + * * @return the endTime value. */ + @Generated public OffsetDateTime getEndTime() { if (this.endTime == null) { return null; @@ -174,28 +129,14 @@ public OffsetDateTime getEndTime() { return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.endTime), ZoneOffset.UTC); } - /** - * Set the endTime property: The end time of the restore operation. - * - * @param endTime the endTime value to set. - * @return the RestoreOperation object itself. - */ - public RestoreOperation setEndTime(OffsetDateTime endTime) { - if (endTime == null) { - this.endTime = null; - } else { - this.endTime = endTime.toEpochSecond(); - } - return this; - } - /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeStringField("status", this.status); + jsonWriter.writeStringField("status", this.status == null ? null : this.status.toString()); jsonWriter.writeStringField("statusDetails", this.statusDetails); jsonWriter.writeJsonField("error", this.error); jsonWriter.writeStringField("jobId", this.jobId); @@ -206,25 +147,25 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of RestoreOperation from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of RestoreOperation 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 RestoreOperation. */ + @Generated public static RestoreOperation fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { RestoreOperation deserializedRestoreOperation = new RestoreOperation(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("status".equals(fieldName)) { - deserializedRestoreOperation.status = reader.getString(); + deserializedRestoreOperation.status = OperationStatus.fromString(reader.getString()); } else if ("statusDetails".equals(fieldName)) { deserializedRestoreOperation.statusDetails = reader.getString(); } else if ("error".equals(fieldName)) { - deserializedRestoreOperation.error = Error.fromJson(reader); + deserializedRestoreOperation.error = FullBackupOperationError.fromJson(reader); } else if ("jobId".equals(fieldName)) { deserializedRestoreOperation.jobId = reader.getString(); } else if ("startTime".equals(fieldName)) { @@ -235,7 +176,6 @@ public static RestoreOperation fromJson(JsonReader jsonReader) throws IOExceptio reader.skipChildren(); } } - return deserializedRestoreOperation; }); } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RestoreOperationParameters.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RestoreOperationParameters.java index 0c9cf3bfb2b8..014035a12613 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RestoreOperationParameters.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RestoreOperationParameters.java @@ -1,49 +1,52 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.administration.implementation.models; +import com.azure.core.annotation.Generated; 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; -import java.util.ArrayList; -import java.util.List; /** - * The RestoreOperationParameters model. + * The authentication method and location for the restore operation. */ @Immutable public final class RestoreOperationParameters implements JsonSerializable { + /* - * The sasTokenParameters property. + * A user-provided SAS token to an Azure blob storage container. */ + @Generated private final SASTokenParameter sasTokenParameters; /* * The Folder name of the blob where the previous successful full backup was stored */ + @Generated private final String folderToRestore; /** * Creates an instance of RestoreOperationParameters class. - * + * * @param sasTokenParameters the sasTokenParameters value to set. * @param folderToRestore the folderToRestore value to set. */ + @Generated public RestoreOperationParameters(SASTokenParameter sasTokenParameters, String folderToRestore) { this.sasTokenParameters = sasTokenParameters; this.folderToRestore = folderToRestore; } /** - * Get the sasTokenParameters property: The sasTokenParameters property. - * + * Get the sasTokenParameters property: A user-provided SAS token to an Azure blob storage container. + * * @return the sasTokenParameters value. */ + @Generated public SASTokenParameter getSasTokenParameters() { return this.sasTokenParameters; } @@ -51,9 +54,10 @@ public SASTokenParameter getSasTokenParameters() { /** * Get the folderToRestore property: The Folder name of the blob where the previous successful full backup was * stored. - * + * * @return the folderToRestore value. */ + @Generated public String getFolderToRestore() { return this.folderToRestore; } @@ -61,6 +65,7 @@ public String getFolderToRestore() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -71,46 +76,30 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of RestoreOperationParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of RestoreOperationParameters 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 RestoreOperationParameters. */ + @Generated public static RestoreOperationParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean sasTokenParametersFound = false; SASTokenParameter sasTokenParameters = null; - boolean folderToRestoreFound = false; String folderToRestore = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("sasTokenParameters".equals(fieldName)) { sasTokenParameters = SASTokenParameter.fromJson(reader); - sasTokenParametersFound = true; } else if ("folderToRestore".equals(fieldName)) { folderToRestore = reader.getString(); - folderToRestoreFound = true; } else { reader.skipChildren(); } } - if (sasTokenParametersFound && folderToRestoreFound) { - return new RestoreOperationParameters(sasTokenParameters, folderToRestore); - } - List missingProperties = new ArrayList<>(); - if (!sasTokenParametersFound) { - missingProperties.add("sasTokenParameters"); - } - if (!folderToRestoreFound) { - missingProperties.add("folderToRestore"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return new RestoreOperationParameters(sasTokenParameters, folderToRestore); }); } } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignment.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignment.java index 7aaf6d3e3147..163d5116e52f 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignment.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignment.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.administration.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -14,84 +14,84 @@ /** * Role Assignments. */ -@Fluent +@Immutable public final class RoleAssignment implements JsonSerializable { + /* * The role assignment ID. */ + @Generated private String id; /* * The role assignment name. */ + @Generated private String name; /* * The role assignment type. */ + @Generated private String type; /* * Role assignment properties. */ + @Generated private RoleAssignmentPropertiesWithScope properties; /** * Creates an instance of RoleAssignment class. */ - public RoleAssignment() { + @Generated + private RoleAssignment() { } /** * Get the id property: The role assignment ID. - * + * * @return the id value. */ + @Generated public String getId() { return this.id; } /** * Get the name property: The role assignment name. - * + * * @return the name value. */ + @Generated public String getName() { return this.name; } /** * Get the type property: The role assignment type. - * + * * @return the type value. */ + @Generated public String getType() { return this.type; } /** * Get the properties property: Role assignment properties. - * + * * @return the properties value. */ + @Generated public RoleAssignmentPropertiesWithScope getProperties() { return this.properties; } - /** - * Set the properties property: Role assignment properties. - * - * @param properties the properties value to set. - * @return the RoleAssignment object itself. - */ - public RoleAssignment setProperties(RoleAssignmentPropertiesWithScope properties) { - this.properties = properties; - return this; - } - /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -101,19 +101,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of RoleAssignment from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of RoleAssignment 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 RoleAssignment. */ + @Generated public static RoleAssignment fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { RoleAssignment deserializedRoleAssignment = new RoleAssignment(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("id".equals(fieldName)) { deserializedRoleAssignment.id = reader.getString(); } else if ("name".equals(fieldName)) { @@ -126,7 +126,6 @@ public static RoleAssignment fromJson(JsonReader jsonReader) throws IOException reader.skipChildren(); } } - return deserializedRoleAssignment; }); } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignmentCreateParameters.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignmentCreateParameters.java index f16eb863dec7..4eb1e9dfb4d5 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignmentCreateParameters.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignmentCreateParameters.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.administration.implementation.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -16,25 +16,29 @@ */ @Immutable public final class RoleAssignmentCreateParameters implements JsonSerializable { + /* * Role assignment properties. */ + @Generated private final RoleAssignmentProperties properties; /** * Creates an instance of RoleAssignmentCreateParameters class. - * + * * @param properties the properties value to set. */ + @Generated public RoleAssignmentCreateParameters(RoleAssignmentProperties properties) { this.properties = properties; } /** * Get the properties property: Role assignment properties. - * + * * @return the properties value. */ + @Generated public RoleAssignmentProperties getProperties() { return this.properties; } @@ -42,6 +46,7 @@ public RoleAssignmentProperties getProperties() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -51,32 +56,27 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of RoleAssignmentCreateParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of RoleAssignmentCreateParameters 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 RoleAssignmentCreateParameters. */ + @Generated public static RoleAssignmentCreateParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean propertiesFound = false; RoleAssignmentProperties properties = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("properties".equals(fieldName)) { properties = RoleAssignmentProperties.fromJson(reader); - propertiesFound = true; } else { reader.skipChildren(); } } - if (propertiesFound) { - return new RoleAssignmentCreateParameters(properties); - } - throw new IllegalStateException("Missing required property: properties"); + return new RoleAssignmentCreateParameters(properties); }); } } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignmentFilter.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignmentFilter.java deleted file mode 100644 index e260ddccafc4..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignmentFilter.java +++ /dev/null @@ -1,85 +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.security.keyvault.administration.implementation.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; - -/** - * Role Assignments filter. - */ -@Fluent -public final class RoleAssignmentFilter implements JsonSerializable { - /* - * Returns role assignment of the specific principal. - */ - private String principalId; - - /** - * Creates an instance of RoleAssignmentFilter class. - */ - public RoleAssignmentFilter() { - } - - /** - * Get the principalId property: Returns role assignment of the specific principal. - * - * @return the principalId value. - */ - public String getPrincipalId() { - return this.principalId; - } - - /** - * Set the principalId property: Returns role assignment of the specific principal. - * - * @param principalId the principalId value to set. - * @return the RoleAssignmentFilter object itself. - */ - public RoleAssignmentFilter setPrincipalId(String principalId) { - this.principalId = principalId; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("principalId", this.principalId); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of RoleAssignmentFilter from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of RoleAssignmentFilter 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 RoleAssignmentFilter. - */ - public static RoleAssignmentFilter fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - RoleAssignmentFilter deserializedRoleAssignmentFilter = new RoleAssignmentFilter(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("principalId".equals(fieldName)) { - deserializedRoleAssignmentFilter.principalId = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedRoleAssignmentFilter; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignmentListResult.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignmentListResult.java deleted file mode 100644 index 290f201374be..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignmentListResult.java +++ /dev/null @@ -1,115 +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.security.keyvault.administration.implementation.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.List; - -/** - * Role assignment list operation result. - */ -@Fluent -public final class RoleAssignmentListResult implements JsonSerializable { - /* - * Role assignment list. - */ - private List value; - - /* - * The URL to use for getting the next set of results. - */ - private String nextLink; - - /** - * Creates an instance of RoleAssignmentListResult class. - */ - public RoleAssignmentListResult() { - } - - /** - * Get the value property: Role assignment list. - * - * @return the value value. - */ - public List getValue() { - return this.value; - } - - /** - * Set the value property: Role assignment list. - * - * @param value the value value to set. - * @return the RoleAssignmentListResult object itself. - */ - public RoleAssignmentListResult setValue(List value) { - this.value = value; - return this; - } - - /** - * Get the nextLink property: The URL to use for getting the next set of results. - * - * @return the nextLink value. - */ - public String getNextLink() { - return this.nextLink; - } - - /** - * Set the nextLink property: The URL to use for getting the next set of results. - * - * @param nextLink the nextLink value to set. - * @return the RoleAssignmentListResult object itself. - */ - public RoleAssignmentListResult setNextLink(String nextLink) { - this.nextLink = nextLink; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); - jsonWriter.writeStringField("nextLink", this.nextLink); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of RoleAssignmentListResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of RoleAssignmentListResult 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 RoleAssignmentListResult. - */ - public static RoleAssignmentListResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - RoleAssignmentListResult deserializedRoleAssignmentListResult = new RoleAssignmentListResult(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - List value = reader.readArray(reader1 -> RoleAssignment.fromJson(reader1)); - deserializedRoleAssignmentListResult.value = value; - } else if ("nextLink".equals(fieldName)) { - deserializedRoleAssignmentListResult.nextLink = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedRoleAssignmentListResult; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignmentProperties.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignmentProperties.java index 382516e73fad..a48930e5df97 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignmentProperties.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignmentProperties.java @@ -1,40 +1,42 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.administration.implementation.models; +import com.azure.core.annotation.Generated; 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; -import java.util.ArrayList; -import java.util.List; /** * Role assignment properties. */ @Immutable public final class RoleAssignmentProperties implements JsonSerializable { + /* * The role definition ID used in the role assignment. */ + @Generated private final String roleDefinitionId; /* * The principal ID assigned to the role. This maps to the ID inside the Active Directory. It can point to a user, * service principal, or security group. */ + @Generated private final String principalId; /** * Creates an instance of RoleAssignmentProperties class. - * + * * @param roleDefinitionId the roleDefinitionId value to set. * @param principalId the principalId value to set. */ + @Generated public RoleAssignmentProperties(String roleDefinitionId, String principalId) { this.roleDefinitionId = roleDefinitionId; this.principalId = principalId; @@ -42,9 +44,10 @@ public RoleAssignmentProperties(String roleDefinitionId, String principalId) { /** * Get the roleDefinitionId property: The role definition ID used in the role assignment. - * + * * @return the roleDefinitionId value. */ + @Generated public String getRoleDefinitionId() { return this.roleDefinitionId; } @@ -52,9 +55,10 @@ public String getRoleDefinitionId() { /** * Get the principalId property: The principal ID assigned to the role. This maps to the ID inside the Active * Directory. It can point to a user, service principal, or security group. - * + * * @return the principalId value. */ + @Generated public String getPrincipalId() { return this.principalId; } @@ -62,6 +66,7 @@ public String getPrincipalId() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -72,46 +77,30 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of RoleAssignmentProperties from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of RoleAssignmentProperties 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 RoleAssignmentProperties. */ + @Generated public static RoleAssignmentProperties fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean roleDefinitionIdFound = false; String roleDefinitionId = null; - boolean principalIdFound = false; String principalId = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("roleDefinitionId".equals(fieldName)) { roleDefinitionId = reader.getString(); - roleDefinitionIdFound = true; } else if ("principalId".equals(fieldName)) { principalId = reader.getString(); - principalIdFound = true; } else { reader.skipChildren(); } } - if (roleDefinitionIdFound && principalIdFound) { - return new RoleAssignmentProperties(roleDefinitionId, principalId); - } - List missingProperties = new ArrayList<>(); - if (!roleDefinitionIdFound) { - missingProperties.add("roleDefinitionId"); - } - if (!principalIdFound) { - missingProperties.add("principalId"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return new RoleAssignmentProperties(roleDefinitionId, principalId); }); } } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignmentPropertiesWithScope.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignmentPropertiesWithScope.java index f675aa492ccb..3258393151fc 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignmentPropertiesWithScope.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleAssignmentPropertiesWithScope.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.administration.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -15,92 +15,68 @@ /** * Role assignment properties with scope. */ -@Fluent +@Immutable public final class RoleAssignmentPropertiesWithScope implements JsonSerializable { + /* * The role scope. */ + @Generated private KeyVaultRoleScope scope; /* * The role definition ID. */ + @Generated private String roleDefinitionId; /* * The principal ID. */ + @Generated private String principalId; /** * Creates an instance of RoleAssignmentPropertiesWithScope class. */ - public RoleAssignmentPropertiesWithScope() { + @Generated + private RoleAssignmentPropertiesWithScope() { } /** * Get the scope property: The role scope. - * + * * @return the scope value. */ + @Generated public KeyVaultRoleScope getScope() { return this.scope; } - /** - * Set the scope property: The role scope. - * - * @param scope the scope value to set. - * @return the RoleAssignmentPropertiesWithScope object itself. - */ - public RoleAssignmentPropertiesWithScope setScope(KeyVaultRoleScope scope) { - this.scope = scope; - return this; - } - /** * Get the roleDefinitionId property: The role definition ID. - * + * * @return the roleDefinitionId value. */ + @Generated public String getRoleDefinitionId() { return this.roleDefinitionId; } - /** - * Set the roleDefinitionId property: The role definition ID. - * - * @param roleDefinitionId the roleDefinitionId value to set. - * @return the RoleAssignmentPropertiesWithScope object itself. - */ - public RoleAssignmentPropertiesWithScope setRoleDefinitionId(String roleDefinitionId) { - this.roleDefinitionId = roleDefinitionId; - return this; - } - /** * Get the principalId property: The principal ID. - * + * * @return the principalId value. */ + @Generated public String getPrincipalId() { return this.principalId; } - /** - * Set the principalId property: The principal ID. - * - * @param principalId the principalId value to set. - * @return the RoleAssignmentPropertiesWithScope object itself. - */ - public RoleAssignmentPropertiesWithScope setPrincipalId(String principalId) { - this.principalId = principalId; - return this; - } - /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -112,12 +88,13 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of RoleAssignmentPropertiesWithScope from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of RoleAssignmentPropertiesWithScope 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 RoleAssignmentPropertiesWithScope. */ + @Generated public static RoleAssignmentPropertiesWithScope fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { RoleAssignmentPropertiesWithScope deserializedRoleAssignmentPropertiesWithScope @@ -125,7 +102,6 @@ public static RoleAssignmentPropertiesWithScope fromJson(JsonReader jsonReader) while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("scope".equals(fieldName)) { deserializedRoleAssignmentPropertiesWithScope.scope = KeyVaultRoleScope.fromString(reader.getString()); @@ -137,7 +113,6 @@ public static RoleAssignmentPropertiesWithScope fromJson(JsonReader jsonReader) reader.skipChildren(); } } - return deserializedRoleAssignmentPropertiesWithScope; }); } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleDefinition.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleDefinition.java index 3506b0ac7660..bc45f215b469 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleDefinition.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleDefinition.java @@ -1,269 +1,132 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.administration.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +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 com.azure.security.keyvault.administration.models.KeyVaultRoleDefinitionType; -import com.azure.security.keyvault.administration.models.KeyVaultRoleScope; -import com.azure.security.keyvault.administration.models.KeyVaultRoleType; import java.io.IOException; -import java.util.List; /** * Role definition. */ -@Fluent -public class RoleDefinition implements JsonSerializable { +@Immutable +public final class RoleDefinition implements JsonSerializable { + /* * The role definition ID. */ + @Generated private String id; /* * The role definition name. */ + @Generated private String name; /* * The role definition type. */ + @Generated private KeyVaultRoleDefinitionType type; /* - * The role name. - */ - private String roleName; - - /* - * The role definition description. - */ - private String description; - - /* - * The role type. - */ - private KeyVaultRoleType roleType; - - /* - * Role definition permissions. - */ - private List permissions; - - /* - * Role definition assignable scopes. + * Role definition properties. */ - private List assignableScopes; + @Generated + private RoleDefinitionProperties properties; /** * Creates an instance of RoleDefinition class. */ - public RoleDefinition() { + @Generated + private RoleDefinition() { } /** * Get the id property: The role definition ID. - * + * * @return the id value. */ + @Generated public String getId() { return this.id; } /** * Get the name property: The role definition name. - * + * * @return the name value. */ + @Generated public String getName() { return this.name; } /** * Get the type property: The role definition type. - * + * * @return the type value. */ + @Generated public KeyVaultRoleDefinitionType getType() { return this.type; } /** - * Get the roleName property: The role name. - * - * @return the roleName value. + * Get the properties property: Role definition properties. + * + * @return the properties value. */ - public String getRoleName() { - return this.roleName; - } - - /** - * Set the roleName property: The role name. - * - * @param roleName the roleName value to set. - * @return the RoleDefinition object itself. - */ - public RoleDefinition setRoleName(String roleName) { - this.roleName = roleName; - return this; - } - - /** - * Get the description property: The role definition description. - * - * @return the description value. - */ - public String getDescription() { - return this.description; - } - - /** - * Set the description property: The role definition description. - * - * @param description the description value to set. - * @return the RoleDefinition object itself. - */ - public RoleDefinition setDescription(String description) { - this.description = description; - return this; - } - - /** - * Get the roleType property: The role type. - * - * @return the roleType value. - */ - public KeyVaultRoleType getRoleType() { - return this.roleType; - } - - /** - * Set the roleType property: The role type. - * - * @param roleType the roleType value to set. - * @return the RoleDefinition object itself. - */ - public RoleDefinition setRoleType(KeyVaultRoleType roleType) { - this.roleType = roleType; - return this; - } - - /** - * Get the permissions property: Role definition permissions. - * - * @return the permissions value. - */ - public List getPermissions() { - return this.permissions; - } - - /** - * Set the permissions property: Role definition permissions. - * - * @param permissions the permissions value to set. - * @return the RoleDefinition object itself. - */ - public RoleDefinition setPermissions(List permissions) { - this.permissions = permissions; - return this; - } - - /** - * Get the assignableScopes property: Role definition assignable scopes. - * - * @return the assignableScopes value. - */ - public List getAssignableScopes() { - return this.assignableScopes; - } - - /** - * Set the assignableScopes property: Role definition assignable scopes. - * - * @param assignableScopes the assignableScopes value to set. - * @return the RoleDefinition object itself. - */ - public RoleDefinition setAssignableScopes(List assignableScopes) { - this.assignableScopes = assignableScopes; - return this; + @Generated + public RoleDefinitionProperties getProperties() { + return this.properties; } /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - if (roleName != null - || description != null - || roleType != null - || permissions != null - || assignableScopes != null) { - jsonWriter.writeStartObject("properties"); - jsonWriter.writeStringField("roleName", this.roleName); - jsonWriter.writeStringField("description", this.description); - jsonWriter.writeStringField("type", this.roleType == null ? null : this.roleType.toString()); - jsonWriter.writeArrayField("permissions", this.permissions, (writer, element) -> writer.writeJson(element)); - jsonWriter.writeArrayField("assignableScopes", this.assignableScopes, - (writer, element) -> writer.writeString(element == null ? null : element.toString())); - jsonWriter.writeEndObject(); - } + jsonWriter.writeJsonField("properties", this.properties); return jsonWriter.writeEndObject(); } /** * Reads an instance of RoleDefinition from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of RoleDefinition 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 RoleDefinition. */ + @Generated public static RoleDefinition fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { RoleDefinition deserializedRoleDefinition = new RoleDefinition(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("id".equals(fieldName)) { deserializedRoleDefinition.id = reader.getString(); } else if ("name".equals(fieldName)) { deserializedRoleDefinition.name = reader.getString(); } else if ("type".equals(fieldName)) { deserializedRoleDefinition.type = KeyVaultRoleDefinitionType.fromString(reader.getString()); - } else if ("properties".equals(fieldName) && reader.currentToken() == JsonToken.START_OBJECT) { - while (reader.nextToken() != JsonToken.END_OBJECT) { - fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("roleName".equals(fieldName)) { - deserializedRoleDefinition.roleName = reader.getString(); - } else if ("description".equals(fieldName)) { - deserializedRoleDefinition.description = reader.getString(); - } else if ("type".equals(fieldName)) { - deserializedRoleDefinition.roleType = KeyVaultRoleType.fromString(reader.getString()); - } else if ("permissions".equals(fieldName)) { - List permissions = reader.readArray(reader1 -> Permission.fromJson(reader1)); - deserializedRoleDefinition.permissions = permissions; - } else if ("assignableScopes".equals(fieldName)) { - List assignableScopes - = reader.readArray(reader1 -> KeyVaultRoleScope.fromString(reader1.getString())); - deserializedRoleDefinition.assignableScopes = assignableScopes; - } else { - reader.skipChildren(); - } - } + } else if ("properties".equals(fieldName)) { + deserializedRoleDefinition.properties = RoleDefinitionProperties.fromJson(reader); } else { reader.skipChildren(); } } - return deserializedRoleDefinition; }); } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleDefinitionCreateParameters.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleDefinitionCreateParameters.java index f78a0b8e6ca2..eb4d7aa4dd43 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleDefinitionCreateParameters.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleDefinitionCreateParameters.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.administration.implementation.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -16,25 +16,29 @@ */ @Immutable public final class RoleDefinitionCreateParameters implements JsonSerializable { + /* * Role definition properties. */ + @Generated private final RoleDefinitionProperties properties; /** * Creates an instance of RoleDefinitionCreateParameters class. - * + * * @param properties the properties value to set. */ + @Generated public RoleDefinitionCreateParameters(RoleDefinitionProperties properties) { this.properties = properties; } /** * Get the properties property: Role definition properties. - * + * * @return the properties value. */ + @Generated public RoleDefinitionProperties getProperties() { return this.properties; } @@ -42,6 +46,7 @@ public RoleDefinitionProperties getProperties() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -51,32 +56,27 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of RoleDefinitionCreateParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of RoleDefinitionCreateParameters 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 RoleDefinitionCreateParameters. */ + @Generated public static RoleDefinitionCreateParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean propertiesFound = false; RoleDefinitionProperties properties = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("properties".equals(fieldName)) { properties = RoleDefinitionProperties.fromJson(reader); - propertiesFound = true; } else { reader.skipChildren(); } } - if (propertiesFound) { - return new RoleDefinitionCreateParameters(properties); - } - throw new IllegalStateException("Missing required property: properties"); + return new RoleDefinitionCreateParameters(properties); }); } } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleDefinitionFilter.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleDefinitionFilter.java deleted file mode 100644 index e9c6953625a0..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleDefinitionFilter.java +++ /dev/null @@ -1,85 +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.security.keyvault.administration.implementation.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; - -/** - * Role Definitions filter. - */ -@Fluent -public final class RoleDefinitionFilter implements JsonSerializable { - /* - * Returns role definition with the specific name. - */ - private String roleName; - - /** - * Creates an instance of RoleDefinitionFilter class. - */ - public RoleDefinitionFilter() { - } - - /** - * Get the roleName property: Returns role definition with the specific name. - * - * @return the roleName value. - */ - public String getRoleName() { - return this.roleName; - } - - /** - * Set the roleName property: Returns role definition with the specific name. - * - * @param roleName the roleName value to set. - * @return the RoleDefinitionFilter object itself. - */ - public RoleDefinitionFilter setRoleName(String roleName) { - this.roleName = roleName; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("roleName", this.roleName); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of RoleDefinitionFilter from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of RoleDefinitionFilter 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 RoleDefinitionFilter. - */ - public static RoleDefinitionFilter fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - RoleDefinitionFilter deserializedRoleDefinitionFilter = new RoleDefinitionFilter(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("roleName".equals(fieldName)) { - deserializedRoleDefinitionFilter.roleName = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedRoleDefinitionFilter; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleDefinitionListResult.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleDefinitionListResult.java deleted file mode 100644 index 09b346848d2b..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleDefinitionListResult.java +++ /dev/null @@ -1,115 +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.security.keyvault.administration.implementation.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.List; - -/** - * Role definition list operation result. - */ -@Fluent -public final class RoleDefinitionListResult implements JsonSerializable { - /* - * Role definition list. - */ - private List value; - - /* - * The URL to use for getting the next set of results. - */ - private String nextLink; - - /** - * Creates an instance of RoleDefinitionListResult class. - */ - public RoleDefinitionListResult() { - } - - /** - * Get the value property: Role definition list. - * - * @return the value value. - */ - public List getValue() { - return this.value; - } - - /** - * Set the value property: Role definition list. - * - * @param value the value value to set. - * @return the RoleDefinitionListResult object itself. - */ - public RoleDefinitionListResult setValue(List value) { - this.value = value; - return this; - } - - /** - * Get the nextLink property: The URL to use for getting the next set of results. - * - * @return the nextLink value. - */ - public String getNextLink() { - return this.nextLink; - } - - /** - * Set the nextLink property: The URL to use for getting the next set of results. - * - * @param nextLink the nextLink value to set. - * @return the RoleDefinitionListResult object itself. - */ - public RoleDefinitionListResult setNextLink(String nextLink) { - this.nextLink = nextLink; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); - jsonWriter.writeStringField("nextLink", this.nextLink); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of RoleDefinitionListResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of RoleDefinitionListResult 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 RoleDefinitionListResult. - */ - public static RoleDefinitionListResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - RoleDefinitionListResult deserializedRoleDefinitionListResult = new RoleDefinitionListResult(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - List value = reader.readArray(reader1 -> RoleDefinition.fromJson(reader1)); - deserializedRoleDefinitionListResult.value = value; - } else if ("nextLink".equals(fieldName)) { - deserializedRoleDefinitionListResult.nextLink = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedRoleDefinitionListResult; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleDefinitionProperties.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleDefinitionProperties.java index cdbf014c2678..8817dfb863f3 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleDefinitionProperties.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/RoleDefinitionProperties.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.administration.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -19,52 +19,61 @@ */ @Fluent public final class RoleDefinitionProperties implements JsonSerializable { + /* * The role name. */ + @Generated private String roleName; /* * The role definition description. */ + @Generated private String description; /* * The role type. */ + @Generated private KeyVaultRoleType roleType; /* * Role definition permissions. */ + @Generated private List permissions; /* * Role definition assignable scopes. */ + @Generated private List assignableScopes; /** * Creates an instance of RoleDefinitionProperties class. */ + @Generated public RoleDefinitionProperties() { } /** * Get the roleName property: The role name. - * + * * @return the roleName value. */ + @Generated public String getRoleName() { return this.roleName; } /** * Set the roleName property: The role name. - * + * * @param roleName the roleName value to set. * @return the RoleDefinitionProperties object itself. */ + @Generated public RoleDefinitionProperties setRoleName(String roleName) { this.roleName = roleName; return this; @@ -72,19 +81,21 @@ public RoleDefinitionProperties setRoleName(String roleName) { /** * Get the description property: The role definition description. - * + * * @return the description value. */ + @Generated public String getDescription() { return this.description; } /** * Set the description property: The role definition description. - * + * * @param description the description value to set. * @return the RoleDefinitionProperties object itself. */ + @Generated public RoleDefinitionProperties setDescription(String description) { this.description = description; return this; @@ -92,19 +103,21 @@ public RoleDefinitionProperties setDescription(String description) { /** * Get the roleType property: The role type. - * + * * @return the roleType value. */ + @Generated public KeyVaultRoleType getRoleType() { return this.roleType; } /** * Set the roleType property: The role type. - * + * * @param roleType the roleType value to set. * @return the RoleDefinitionProperties object itself. */ + @Generated public RoleDefinitionProperties setRoleType(KeyVaultRoleType roleType) { this.roleType = roleType; return this; @@ -112,19 +125,21 @@ public RoleDefinitionProperties setRoleType(KeyVaultRoleType roleType) { /** * Get the permissions property: Role definition permissions. - * + * * @return the permissions value. */ + @Generated public List getPermissions() { return this.permissions; } /** * Set the permissions property: Role definition permissions. - * + * * @param permissions the permissions value to set. * @return the RoleDefinitionProperties object itself. */ + @Generated public RoleDefinitionProperties setPermissions(List permissions) { this.permissions = permissions; return this; @@ -132,19 +147,21 @@ public RoleDefinitionProperties setPermissions(List permissions) { /** * Get the assignableScopes property: Role definition assignable scopes. - * + * * @return the assignableScopes value. */ + @Generated public List getAssignableScopes() { return this.assignableScopes; } /** * Set the assignableScopes property: Role definition assignable scopes. - * + * * @param assignableScopes the assignableScopes value to set. * @return the RoleDefinitionProperties object itself. */ + @Generated public RoleDefinitionProperties setAssignableScopes(List assignableScopes) { this.assignableScopes = assignableScopes; return this; @@ -153,6 +170,7 @@ public RoleDefinitionProperties setAssignableScopes(List assi /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -167,19 +185,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of RoleDefinitionProperties from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of RoleDefinitionProperties 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 RoleDefinitionProperties. */ + @Generated public static RoleDefinitionProperties fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { RoleDefinitionProperties deserializedRoleDefinitionProperties = new RoleDefinitionProperties(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("roleName".equals(fieldName)) { deserializedRoleDefinitionProperties.roleName = reader.getString(); } else if ("description".equals(fieldName)) { @@ -197,7 +215,6 @@ public static RoleDefinitionProperties fromJson(JsonReader jsonReader) throws IO reader.skipChildren(); } } - return deserializedRoleDefinitionProperties; }); } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SASTokenParameter.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SASTokenParameter.java index 36f095e8ec66..763f8b45d21d 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SASTokenParameter.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SASTokenParameter.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.administration.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -12,59 +12,67 @@ import java.io.IOException; /** - * The SASTokenParameter model. + * An authentication method and location for the operation. */ @Fluent public final class SASTokenParameter implements JsonSerializable { + /* * Azure Blob storage container Uri */ + @Generated private final String storageResourceUri; /* * The SAS token pointing to an Azure Blob storage container */ + @Generated private String token; /* * Indicates which authentication method should be used. If set to true, Managed HSM will use the configured * user-assigned managed identity to authenticate with Azure Storage. Otherwise, a SAS token has to be specified. */ + @Generated private Boolean useManagedIdentity; /** * Creates an instance of SASTokenParameter class. - * + * * @param storageResourceUri the storageResourceUri value to set. */ + @Generated public SASTokenParameter(String storageResourceUri) { this.storageResourceUri = storageResourceUri; } /** * Get the storageResourceUri property: Azure Blob storage container Uri. - * + * * @return the storageResourceUri value. */ + @Generated public String getStorageResourceUri() { return this.storageResourceUri; } /** * Get the token property: The SAS token pointing to an Azure Blob storage container. - * + * * @return the token value. */ + @Generated public String getToken() { return this.token; } /** * Set the token property: The SAS token pointing to an Azure Blob storage container. - * + * * @param token the token value to set. * @return the SASTokenParameter object itself. */ + @Generated public SASTokenParameter setToken(String token) { this.token = token; return this; @@ -74,9 +82,10 @@ public SASTokenParameter setToken(String token) { * Get the useManagedIdentity property: Indicates which authentication method should be used. If set to true, * Managed HSM will use the configured user-assigned managed identity to authenticate with Azure Storage. Otherwise, * a SAS token has to be specified. - * + * * @return the useManagedIdentity value. */ + @Generated public Boolean isUseManagedIdentity() { return this.useManagedIdentity; } @@ -85,10 +94,11 @@ public Boolean isUseManagedIdentity() { * Set the useManagedIdentity property: Indicates which authentication method should be used. If set to true, * Managed HSM will use the configured user-assigned managed identity to authenticate with Azure Storage. Otherwise, * a SAS token has to be specified. - * + * * @param useManagedIdentity the useManagedIdentity value to set. * @return the SASTokenParameter object itself. */ + @Generated public SASTokenParameter setUseManagedIdentity(Boolean useManagedIdentity) { this.useManagedIdentity = useManagedIdentity; return this; @@ -97,6 +107,7 @@ public SASTokenParameter setUseManagedIdentity(Boolean useManagedIdentity) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -108,26 +119,24 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SASTokenParameter from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SASTokenParameter 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 SASTokenParameter. */ + @Generated public static SASTokenParameter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean storageResourceUriFound = false; String storageResourceUri = null; String token = null; Boolean useManagedIdentity = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("storageResourceUri".equals(fieldName)) { storageResourceUri = reader.getString(); - storageResourceUriFound = true; } else if ("token".equals(fieldName)) { token = reader.getString(); } else if ("useManagedIdentity".equals(fieldName)) { @@ -136,14 +145,10 @@ public static SASTokenParameter fromJson(JsonReader jsonReader) throws IOExcepti reader.skipChildren(); } } - if (storageResourceUriFound) { - SASTokenParameter deserializedSASTokenParameter = new SASTokenParameter(storageResourceUri); - deserializedSASTokenParameter.token = token; - deserializedSASTokenParameter.useManagedIdentity = useManagedIdentity; - - return deserializedSASTokenParameter; - } - throw new IllegalStateException("Missing required property: storageResourceUri"); + SASTokenParameter deserializedSASTokenParameter = new SASTokenParameter(storageResourceUri); + deserializedSASTokenParameter.token = token; + deserializedSASTokenParameter.useManagedIdentity = useManagedIdentity; + return deserializedSASTokenParameter; }); } } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SelectiveKeyRestoreOperation.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SelectiveKeyRestoreOperation.java index 8633af07a097..a6b22b7e24c7 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SelectiveKeyRestoreOperation.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SelectiveKeyRestoreOperation.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.administration.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -17,129 +17,98 @@ /** * Selective Key Restore operation. */ -@Fluent +@Immutable public final class SelectiveKeyRestoreOperation implements JsonSerializable { + /* * Status of the restore operation. */ - private String status; + @Generated + private OperationStatus status; /* * The status details of restore operation. */ + @Generated private String statusDetails; /* * Error encountered, if any, during the selective key restore operation. */ - private Error error; + @Generated + private FullBackupOperationError error; /* * Identifier for the selective key restore operation. */ + @Generated private String jobId; /* * The start time of the restore operation */ + @Generated private Long startTime; /* * The end time of the restore operation */ + @Generated private Long endTime; /** * Creates an instance of SelectiveKeyRestoreOperation class. */ - public SelectiveKeyRestoreOperation() { + @Generated + private SelectiveKeyRestoreOperation() { } /** * Get the status property: Status of the restore operation. - * + * * @return the status value. */ - public String getStatus() { + @Generated + public OperationStatus getStatus() { return this.status; } - /** - * Set the status property: Status of the restore operation. - * - * @param status the status value to set. - * @return the SelectiveKeyRestoreOperation object itself. - */ - public SelectiveKeyRestoreOperation setStatus(String status) { - this.status = status; - return this; - } - /** * Get the statusDetails property: The status details of restore operation. - * + * * @return the statusDetails value. */ + @Generated public String getStatusDetails() { return this.statusDetails; } - /** - * Set the statusDetails property: The status details of restore operation. - * - * @param statusDetails the statusDetails value to set. - * @return the SelectiveKeyRestoreOperation object itself. - */ - public SelectiveKeyRestoreOperation setStatusDetails(String statusDetails) { - this.statusDetails = statusDetails; - return this; - } - /** * Get the error property: Error encountered, if any, during the selective key restore operation. - * + * * @return the error value. */ - public Error getError() { + @Generated + public FullBackupOperationError getError() { return this.error; } - /** - * Set the error property: Error encountered, if any, during the selective key restore operation. - * - * @param error the error value to set. - * @return the SelectiveKeyRestoreOperation object itself. - */ - public SelectiveKeyRestoreOperation setError(Error error) { - this.error = error; - return this; - } - /** * Get the jobId property: Identifier for the selective key restore operation. - * + * * @return the jobId value. */ + @Generated public String getJobId() { return this.jobId; } - /** - * Set the jobId property: Identifier for the selective key restore operation. - * - * @param jobId the jobId value to set. - * @return the SelectiveKeyRestoreOperation object itself. - */ - public SelectiveKeyRestoreOperation setJobId(String jobId) { - this.jobId = jobId; - return this; - } - /** * Get the startTime property: The start time of the restore operation. - * + * * @return the startTime value. */ + @Generated public OffsetDateTime getStartTime() { if (this.startTime == null) { return null; @@ -147,26 +116,12 @@ public OffsetDateTime getStartTime() { return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.startTime), ZoneOffset.UTC); } - /** - * Set the startTime property: The start time of the restore operation. - * - * @param startTime the startTime value to set. - * @return the SelectiveKeyRestoreOperation object itself. - */ - public SelectiveKeyRestoreOperation setStartTime(OffsetDateTime startTime) { - if (startTime == null) { - this.startTime = null; - } else { - this.startTime = startTime.toEpochSecond(); - } - return this; - } - /** * Get the endTime property: The end time of the restore operation. - * + * * @return the endTime value. */ + @Generated public OffsetDateTime getEndTime() { if (this.endTime == null) { return null; @@ -174,28 +129,14 @@ public OffsetDateTime getEndTime() { return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.endTime), ZoneOffset.UTC); } - /** - * Set the endTime property: The end time of the restore operation. - * - * @param endTime the endTime value to set. - * @return the SelectiveKeyRestoreOperation object itself. - */ - public SelectiveKeyRestoreOperation setEndTime(OffsetDateTime endTime) { - if (endTime == null) { - this.endTime = null; - } else { - this.endTime = endTime.toEpochSecond(); - } - return this; - } - /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeStringField("status", this.status); + jsonWriter.writeStringField("status", this.status == null ? null : this.status.toString()); jsonWriter.writeStringField("statusDetails", this.statusDetails); jsonWriter.writeJsonField("error", this.error); jsonWriter.writeStringField("jobId", this.jobId); @@ -206,25 +147,25 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SelectiveKeyRestoreOperation from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SelectiveKeyRestoreOperation 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 SelectiveKeyRestoreOperation. */ + @Generated public static SelectiveKeyRestoreOperation fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { SelectiveKeyRestoreOperation deserializedSelectiveKeyRestoreOperation = new SelectiveKeyRestoreOperation(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("status".equals(fieldName)) { - deserializedSelectiveKeyRestoreOperation.status = reader.getString(); + deserializedSelectiveKeyRestoreOperation.status = OperationStatus.fromString(reader.getString()); } else if ("statusDetails".equals(fieldName)) { deserializedSelectiveKeyRestoreOperation.statusDetails = reader.getString(); } else if ("error".equals(fieldName)) { - deserializedSelectiveKeyRestoreOperation.error = Error.fromJson(reader); + deserializedSelectiveKeyRestoreOperation.error = FullBackupOperationError.fromJson(reader); } else if ("jobId".equals(fieldName)) { deserializedSelectiveKeyRestoreOperation.jobId = reader.getString(); } else if ("startTime".equals(fieldName)) { @@ -235,7 +176,6 @@ public static SelectiveKeyRestoreOperation fromJson(JsonReader jsonReader) throw reader.skipChildren(); } } - return deserializedSelectiveKeyRestoreOperation; }); } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SelectiveKeyRestoreOperationHeaders.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SelectiveKeyRestoreOperationHeaders.java deleted file mode 100644 index 06f70a46edb1..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SelectiveKeyRestoreOperationHeaders.java +++ /dev/null @@ -1,79 +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.security.keyvault.administration.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.http.HttpHeaderName; -import com.azure.core.http.HttpHeaders; - -/** - * The SelectiveKeyRestoreOperationHeaders model. - */ -@Fluent -public final class SelectiveKeyRestoreOperationHeaders { - /* - * The Retry-After property. - */ - private Integer retryAfter; - - /* - * The Azure-AsyncOperation property. - */ - private String azureAsyncOperation; - - // HttpHeaders containing the raw property values. - /** - * Creates an instance of SelectiveKeyRestoreOperationHeaders class. - * - * @param rawHeaders The raw HttpHeaders that will be used to create the property values. - */ - public SelectiveKeyRestoreOperationHeaders(HttpHeaders rawHeaders) { - String retryAfter = rawHeaders.getValue(HttpHeaderName.RETRY_AFTER); - if (retryAfter != null) { - this.retryAfter = Integer.parseInt(retryAfter); - } - this.azureAsyncOperation = rawHeaders.getValue(HttpHeaderName.AZURE_ASYNCOPERATION); - } - - /** - * Get the retryAfter property: The Retry-After property. - * - * @return the retryAfter value. - */ - public Integer getRetryAfter() { - return this.retryAfter; - } - - /** - * Set the retryAfter property: The Retry-After property. - * - * @param retryAfter the retryAfter value to set. - * @return the SelectiveKeyRestoreOperationHeaders object itself. - */ - public SelectiveKeyRestoreOperationHeaders setRetryAfter(Integer retryAfter) { - this.retryAfter = retryAfter; - return this; - } - - /** - * Get the azureAsyncOperation property: The Azure-AsyncOperation property. - * - * @return the azureAsyncOperation value. - */ - public String getAzureAsyncOperation() { - return this.azureAsyncOperation; - } - - /** - * Set the azureAsyncOperation property: The Azure-AsyncOperation property. - * - * @param azureAsyncOperation the azureAsyncOperation value to set. - * @return the SelectiveKeyRestoreOperationHeaders object itself. - */ - public SelectiveKeyRestoreOperationHeaders setAzureAsyncOperation(String azureAsyncOperation) { - this.azureAsyncOperation = azureAsyncOperation; - return this; - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SelectiveKeyRestoreOperationParameters.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SelectiveKeyRestoreOperationParameters.java index 06830e496eba..b1218fec61df 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SelectiveKeyRestoreOperationParameters.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SelectiveKeyRestoreOperationParameters.java @@ -1,59 +1,63 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.administration.implementation.models; +import com.azure.core.annotation.Generated; 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; -import java.util.ArrayList; -import java.util.List; /** - * The SelectiveKeyRestoreOperationParameters model. + * The authentication method and location for the selective key restore operation. */ @Immutable public final class SelectiveKeyRestoreOperationParameters implements JsonSerializable { + /* - * The sasTokenParameters property. + * A user-provided SAS token to an Azure blob storage container. */ + @Generated private final SASTokenParameter sasTokenParameters; /* * The Folder name of the blob where the previous successful full backup was stored */ + @Generated private final String folder; /** * Creates an instance of SelectiveKeyRestoreOperationParameters class. - * + * * @param sasTokenParameters the sasTokenParameters value to set. * @param folder the folder value to set. */ + @Generated public SelectiveKeyRestoreOperationParameters(SASTokenParameter sasTokenParameters, String folder) { this.sasTokenParameters = sasTokenParameters; this.folder = folder; } /** - * Get the sasTokenParameters property: The sasTokenParameters property. - * + * Get the sasTokenParameters property: A user-provided SAS token to an Azure blob storage container. + * * @return the sasTokenParameters value. */ + @Generated public SASTokenParameter getSasTokenParameters() { return this.sasTokenParameters; } /** * Get the folder property: The Folder name of the blob where the previous successful full backup was stored. - * + * * @return the folder value. */ + @Generated public String getFolder() { return this.folder; } @@ -61,6 +65,7 @@ public String getFolder() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -71,46 +76,30 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SelectiveKeyRestoreOperationParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SelectiveKeyRestoreOperationParameters 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 SelectiveKeyRestoreOperationParameters. */ + @Generated public static SelectiveKeyRestoreOperationParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean sasTokenParametersFound = false; SASTokenParameter sasTokenParameters = null; - boolean folderFound = false; String folder = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("sasTokenParameters".equals(fieldName)) { sasTokenParameters = SASTokenParameter.fromJson(reader); - sasTokenParametersFound = true; } else if ("folder".equals(fieldName)) { folder = reader.getString(); - folderFound = true; } else { reader.skipChildren(); } } - if (sasTokenParametersFound && folderFound) { - return new SelectiveKeyRestoreOperationParameters(sasTokenParameters, folder); - } - List missingProperties = new ArrayList<>(); - if (!sasTokenParametersFound) { - missingProperties.add("sasTokenParameters"); - } - if (!folderFound) { - missingProperties.add("folder"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return new SelectiveKeyRestoreOperationParameters(sasTokenParameters, folder); }); } } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SelectiveKeyRestoreOperationResponse.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SelectiveKeyRestoreOperationResponse.java deleted file mode 100644 index bcc29dd895c3..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SelectiveKeyRestoreOperationResponse.java +++ /dev/null @@ -1,37 +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.security.keyvault.administration.implementation.models; - -import com.azure.core.http.HttpHeaders; -import com.azure.core.http.HttpRequest; -import com.azure.core.http.rest.ResponseBase; - -/** Contains all response data for the selectiveKeyRestoreOperation operation. */ -public final class SelectiveKeyRestoreOperationResponse - extends ResponseBase { - /** - * Creates an instance of SelectiveKeyRestoreOperationResponse. - * - * @param request the request which resulted in this SelectiveKeyRestoreOperationResponse. - * @param statusCode the status code of the HTTP response. - * @param rawHeaders the raw headers of the HTTP response. - * @param value the deserialized value of the HTTP response. - * @param headers the deserialized headers of the HTTP response. - */ - public SelectiveKeyRestoreOperationResponse(HttpRequest request, int statusCode, HttpHeaders rawHeaders, - SelectiveKeyRestoreOperation value, SelectiveKeyRestoreOperationHeaders headers) { - super(request, statusCode, rawHeaders, value, headers); - } - - /** - * Gets the deserialized response body. - * - * @return the deserialized response body. - */ - @Override - public SelectiveKeyRestoreOperation getValue() { - return super.getValue(); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/Setting.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/Setting.java index 27b94f5f426e..4695e1257f6c 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/Setting.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/Setting.java @@ -1,91 +1,87 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.administration.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +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 com.azure.security.keyvault.administration.models.KeyVaultSettingType; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** - * The Setting model. + * A Key Vault account setting. */ -@Fluent +@Immutable public final class Setting implements JsonSerializable { + /* * The account setting to be updated */ + @Generated private final String name; /* * The value of the pool setting. */ + @Generated private final String value; /* * The type specifier of the value. */ + @Generated private KeyVaultSettingType type; /** * Creates an instance of Setting class. - * + * * @param name the name value to set. * @param value the value value to set. */ - public Setting(String name, String value) { + @Generated + private Setting(String name, String value) { this.name = name; this.value = value; } /** * Get the name property: The account setting to be updated. - * + * * @return the name value. */ + @Generated public String getName() { return this.name; } /** * Get the value property: The value of the pool setting. - * + * * @return the value value. */ + @Generated public String getValue() { return this.value; } /** * Get the type property: The type specifier of the value. - * + * * @return the type value. */ + @Generated public KeyVaultSettingType getType() { return this.type; } - /** - * Set the type property: The type specifier of the value. - * - * @param type the type value to set. - * @return the Setting object itself. - */ - public Setting setType(KeyVaultSettingType type) { - this.type = type; - return this; - } - /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -97,52 +93,35 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of Setting from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of Setting 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 Setting. */ + @Generated public static Setting fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; - boolean valueFound = false; String value = null; KeyVaultSettingType type = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("value".equals(fieldName)) { value = reader.getString(); - valueFound = true; } else if ("type".equals(fieldName)) { type = KeyVaultSettingType.fromString(reader.getString()); } else { reader.skipChildren(); } } - if (nameFound && valueFound) { - Setting deserializedSetting = new Setting(name, value); - deserializedSetting.type = type; - - return deserializedSetting; - } - List missingProperties = new ArrayList<>(); - if (!nameFound) { - missingProperties.add("name"); - } - if (!valueFound) { - missingProperties.add("value"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + Setting deserializedSetting = new Setting(name, value); + deserializedSetting.type = type; + return deserializedSetting; }); } } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SettingsListResult.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SettingsListResult.java index e5e654afb3e6..271dc4ac283c 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SettingsListResult.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/SettingsListResult.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.administration.implementation.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -17,22 +17,26 @@ */ @Immutable public final class SettingsListResult implements JsonSerializable { + /* * A response message containing a list of account settings with their associated value. */ + @Generated private List settings; /** * Creates an instance of SettingsListResult class. */ - public SettingsListResult() { + @Generated + private SettingsListResult() { } /** * Get the settings property: A response message containing a list of account settings with their associated value. - * + * * @return the settings value. */ + @Generated public List getSettings() { return this.settings; } @@ -40,6 +44,7 @@ public List getSettings() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -48,19 +53,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SettingsListResult from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SettingsListResult 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 SettingsListResult. */ + @Generated public static SettingsListResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { SettingsListResult deserializedSettingsListResult = new SettingsListResult(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("settings".equals(fieldName)) { List settings = reader.readArray(reader1 -> Setting.fromJson(reader1)); deserializedSettingsListResult.settings = settings; @@ -68,7 +73,6 @@ public static SettingsListResult fromJson(JsonReader jsonReader) throws IOExcept reader.skipChildren(); } } - return deserializedSettingsListResult; }); } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/UpdateSettingRequest.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/UpdateSettingRequest.java index 4220de7836bd..81eff3d0a138 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/UpdateSettingRequest.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/UpdateSettingRequest.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.administration.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -14,42 +14,39 @@ /** * The update settings request object. */ -@Fluent +@Immutable public final class UpdateSettingRequest implements JsonSerializable { + /* * The value of the pool setting. */ - private String value; + @Generated + private final String value; /** * Creates an instance of UpdateSettingRequest class. + * + * @param value the value value to set. */ - public UpdateSettingRequest() { + @Generated + public UpdateSettingRequest(String value) { + this.value = value; } /** * Get the value property: The value of the pool setting. - * + * * @return the value value. */ + @Generated public String getValue() { return this.value; } - /** - * Set the value property: The value of the pool setting. - * - * @param value the value value to set. - * @return the UpdateSettingRequest object itself. - */ - public UpdateSettingRequest setValue(String value) { - this.value = value; - return this; - } - /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -59,27 +56,27 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of UpdateSettingRequest from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of UpdateSettingRequest 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 UpdateSettingRequest. */ + @Generated public static UpdateSettingRequest fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - UpdateSettingRequest deserializedUpdateSettingRequest = new UpdateSettingRequest(); + String value = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("value".equals(fieldName)) { - deserializedUpdateSettingRequest.value = reader.getString(); + value = reader.getString(); } else { reader.skipChildren(); } } - - return deserializedUpdateSettingRequest; + return new UpdateSettingRequest(value); }); } } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/package-info.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/package-info.java index d6f943b4cd93..f49191054b5b 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/package-info.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/models/package-info.java @@ -1,8 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. /** - * Package containing the data models for KeyVaultAccessControlClient, KeyVaultBackupClient, and KeyVaultSettingsClient. + * + * Package containing the data models for KeyVault. * The key vault client performs cryptographic key operations and vault operations against the Key Vault service. + * */ package com.azure.security.keyvault.administration.implementation.models; diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultDataAction.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultDataAction.java index 2388fe87bded..dd945292c216 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultDataAction.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultDataAction.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.administration.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -11,229 +11,267 @@ * Supported permissions for data actions. */ public final class KeyVaultDataAction extends ExpandableStringEnum { + /** * Read HSM key metadata. */ + @Generated public static final KeyVaultDataAction READ_HSM_KEY = fromString("Microsoft.KeyVault/managedHsm/keys/read/action"); /** * Update an HSM key. */ + @Generated public static final KeyVaultDataAction WRITE_HSM_KEY = fromString("Microsoft.KeyVault/managedHsm/keys/write/action"); /** * Read deleted HSM key. */ + @Generated public static final KeyVaultDataAction READ_DELETED_HSM_KEY = fromString("Microsoft.KeyVault/managedHsm/keys/deletedKeys/read/action"); /** * Recover deleted HSM key. */ + @Generated public static final KeyVaultDataAction RECOVER_DELETED_HSM_KEY = fromString("Microsoft.KeyVault/managedHsm/keys/deletedKeys/recover/action"); /** * Backup HSM keys. */ + @Generated public static final KeyVaultDataAction BACKUP_HSM_KEYS = fromString("Microsoft.KeyVault/managedHsm/keys/backup/action"); /** * Restore HSM keys. */ + @Generated public static final KeyVaultDataAction RESTORE_HSM_KEYS = fromString("Microsoft.KeyVault/managedHsm/keys/restore/action"); /** * Delete role assignment. */ + @Generated public static final KeyVaultDataAction DELETE_ROLE_ASSIGNMENT = fromString("Microsoft.KeyVault/managedHsm/roleAssignments/delete/action"); /** * Get role assignment. */ + @Generated public static final KeyVaultDataAction GET_ROLE_ASSIGNMENT = fromString("Microsoft.KeyVault/managedHsm/roleAssignments/read/action"); /** * Create or update role assignment. */ + @Generated public static final KeyVaultDataAction WRITE_ROLE_ASSIGNMENT = fromString("Microsoft.KeyVault/managedHsm/roleAssignments/write/action"); /** * Get role definition. */ + @Generated public static final KeyVaultDataAction READ_ROLE_DEFINITION = fromString("Microsoft.KeyVault/managedHsm/roleDefinitions/read/action"); /** * Create or update role definition. */ + @Generated public static final KeyVaultDataAction WRITE_ROLE_DEFINITION = fromString("Microsoft.KeyVault/managedHsm/roleDefinitions/write/action"); /** * Delete role definition. */ + @Generated public static final KeyVaultDataAction DELETE_ROLE_DEFINITION = fromString("Microsoft.KeyVault/managedHsm/roleDefinitions/delete/action"); /** * Encrypt using an HSM key. */ + @Generated public static final KeyVaultDataAction ENCRYPT_HSM_KEY = fromString("Microsoft.KeyVault/managedHsm/keys/encrypt/action"); /** * Decrypt using an HSM key. */ + @Generated public static final KeyVaultDataAction DECRYPT_HSM_KEY = fromString("Microsoft.KeyVault/managedHsm/keys/decrypt/action"); /** * Wrap using an HSM key. */ + @Generated public static final KeyVaultDataAction WRAP_HSM_KEY = fromString("Microsoft.KeyVault/managedHsm/keys/wrap/action"); /** * Unwrap using an HSM key. */ + @Generated public static final KeyVaultDataAction UNWRAP_HSM_KEY = fromString("Microsoft.KeyVault/managedHsm/keys/unwrap/action"); /** * Sign using an HSM key. */ + @Generated public static final KeyVaultDataAction SIGN_HSM_KEY = fromString("Microsoft.KeyVault/managedHsm/keys/sign/action"); /** * Verify using an HSM key. */ + @Generated public static final KeyVaultDataAction VERIFY_HSM_KEY = fromString("Microsoft.KeyVault/managedHsm/keys/verify/action"); /** * Create an HSM key. */ + @Generated public static final KeyVaultDataAction CREATE_HSM_KEY = fromString("Microsoft.KeyVault/managedHsm/keys/create"); /** * Delete an HSM key. */ + @Generated public static final KeyVaultDataAction DELETE_HSM_KEY = fromString("Microsoft.KeyVault/managedHsm/keys/delete"); /** * Export an HSM key. */ + @Generated public static final KeyVaultDataAction EXPORT_HSM_KEY = fromString("Microsoft.KeyVault/managedHsm/keys/export/action"); /** * Release an HSM key using Secure Key Release. */ + @Generated public static final KeyVaultDataAction RELEASE_KEY = fromString("Microsoft.KeyVault/managedHsm/keys/release/action"); /** * Import an HSM key. */ + @Generated public static final KeyVaultDataAction IMPORT_HSM_KEY = fromString("Microsoft.KeyVault/managedHsm/keys/import/action"); /** * Purge a deleted HSM key. */ + @Generated public static final KeyVaultDataAction PURGE_DELETED_HSM_KEY = fromString("Microsoft.KeyVault/managedHsm/keys/deletedKeys/delete"); /** * Download an HSM security domain. */ + @Generated public static final KeyVaultDataAction DOWNLOAD_HSM_SECURITY_DOMAIN = fromString("Microsoft.KeyVault/managedHsm/securitydomain/download/action"); /** * Check status of HSM security domain download. */ + @Generated public static final KeyVaultDataAction DOWNLOAD_HSM_SECURITY_DOMAIN_STATUS = fromString("Microsoft.KeyVault/managedHsm/securitydomain/download/read"); /** * Upload an HSM security domain. */ + @Generated public static final KeyVaultDataAction UPLOAD_HSM_SECURITY_DOMAIN = fromString("Microsoft.KeyVault/managedHsm/securitydomain/upload/action"); /** * Check the status of the HSM security domain exchange file. */ + @Generated public static final KeyVaultDataAction READ_HSM_SECURITY_DOMAIN_STATUS = fromString("Microsoft.KeyVault/managedHsm/securitydomain/upload/read"); /** * Download an HSM security domain transfer key. */ + @Generated public static final KeyVaultDataAction READ_HSM_SECURITY_DOMAIN_TRANSFER_KEY = fromString("Microsoft.KeyVault/managedHsm/securitydomain/transferkey/read"); /** * Start an HSM backup. */ + @Generated public static final KeyVaultDataAction START_HSM_BACKUP = fromString("Microsoft.KeyVault/managedHsm/backup/start/action"); /** * Start an HSM restore. */ + @Generated public static final KeyVaultDataAction START_HSM_RESTORE = fromString("Microsoft.KeyVault/managedHsm/restore/start/action"); /** * Read an HSM backup status. */ + @Generated public static final KeyVaultDataAction READ_HSM_BACKUP_STATUS = fromString("Microsoft.KeyVault/managedHsm/backup/status/action"); /** * Read an HSM restore status. */ + @Generated public static final KeyVaultDataAction READ_HSM_RESTORE_STATUS = fromString("Microsoft.KeyVault/managedHsm/restore/status/action"); /** * Generate random numbers. */ + @Generated public static final KeyVaultDataAction RANDOM_NUMBERS_GENERATE = fromString("Microsoft.KeyVault/managedHsm/rng/action"); /** * Creates a new instance of KeyVaultDataAction value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ + @Generated @Deprecated public KeyVaultDataAction() { } /** * Creates or finds a KeyVaultDataAction from its string representation. - * + * * @param name a name to look for. * @return the corresponding KeyVaultDataAction. */ + @Generated public static KeyVaultDataAction fromString(String name) { return fromString(name, KeyVaultDataAction.class); } /** * Gets known KeyVaultDataAction values. - * + * * @return known KeyVaultDataAction values. */ + @Generated public static Collection values() { return values(KeyVaultDataAction.class); } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleDefinitionType.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleDefinitionType.java index 238d093d4065..d07ae50971d6 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleDefinitionType.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleDefinitionType.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.administration.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -11,36 +11,41 @@ * The role definition type. */ public final class KeyVaultRoleDefinitionType extends ExpandableStringEnum { + /** - * Static value Microsoft.Authorization/roleDefinitions for KeyVaultRoleDefinitionType. + * Microsoft-defined role definitions. */ + @Generated public static final KeyVaultRoleDefinitionType MICROSOFT_AUTHORIZATION_ROLE_DEFINITIONS = fromString("Microsoft.Authorization/roleDefinitions"); /** * Creates a new instance of KeyVaultRoleDefinitionType value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ + @Generated @Deprecated public KeyVaultRoleDefinitionType() { } /** * Creates or finds a KeyVaultRoleDefinitionType from its string representation. - * + * * @param name a name to look for. * @return the corresponding KeyVaultRoleDefinitionType. */ + @Generated public static KeyVaultRoleDefinitionType fromString(String name) { return fromString(name, KeyVaultRoleDefinitionType.class); } /** * Gets known KeyVaultRoleDefinitionType values. - * + * * @return known KeyVaultRoleDefinitionType values. */ + @Generated public static Collection values() { return values(KeyVaultRoleDefinitionType.class); } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleScope.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleScope.java index 7a6982894ec9..0e9b2888b797 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleScope.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleScope.java @@ -1,8 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.administration.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.net.MalformedURLException; import java.net.URL; @@ -16,11 +17,13 @@ public final class KeyVaultRoleScope extends ExpandableStringEnum values() { return values(KeyVaultRoleScope.class); } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleType.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleType.java index 9c1e15febea5..5ee5f40965f4 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleType.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultRoleType.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.administration.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -11,40 +11,46 @@ * The role type. */ public final class KeyVaultRoleType extends ExpandableStringEnum { + /** * Built in role. */ + @Generated public static final KeyVaultRoleType BUILT_IN_ROLE = fromString("AKVBuiltInRole"); /** * Custom role. */ + @Generated public static final KeyVaultRoleType CUSTOM_ROLE = fromString("CustomRole"); /** * Creates a new instance of KeyVaultRoleType value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ + @Generated @Deprecated public KeyVaultRoleType() { } /** * Creates or finds a KeyVaultRoleType from its string representation. - * + * * @param name a name to look for. * @return the corresponding KeyVaultRoleType. */ + @Generated public static KeyVaultRoleType fromString(String name) { return fromString(name, KeyVaultRoleType.class); } /** * Gets known KeyVaultRoleType values. - * + * * @return known KeyVaultRoleType values. */ + @Generated public static Collection values() { return values(KeyVaultRoleType.class); } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultSettingType.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultSettingType.java index aa36c703d341..3ac0c0742a61 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultSettingType.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/models/KeyVaultSettingType.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.administration.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -11,35 +11,40 @@ * The type specifier of the value. */ public final class KeyVaultSettingType extends ExpandableStringEnum { + /** - * Static value boolean for KeyVaultSettingType. + * A boolean setting value. */ + @Generated public static final KeyVaultSettingType BOOLEAN = fromString("boolean"); /** * Creates a new instance of KeyVaultSettingType value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ + @Generated @Deprecated public KeyVaultSettingType() { } /** * Creates or finds a KeyVaultSettingType from its string representation. - * + * * @param name a name to look for. * @return the corresponding KeyVaultSettingType. */ + @Generated public static KeyVaultSettingType fromString(String name) { return fromString(name, KeyVaultSettingType.class); } /** * Gets known KeyVaultSettingType values. - * + * * @return known KeyVaultSettingType values. */ + @Generated public static Collection values() { return values(KeyVaultSettingType.class); } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/package-info.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/package-info.java index b8718f3df4b3..15a757e7787a 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/package-info.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/package-info.java @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. /** + * * Azure Key Vault Managed HSM is a * fully-managed, highly-available, single-tenant, standards-compliant cloud service that enables you to safeguard * cryptographic keys for your cloud applications using FIPS 140-2 Level 3 validated HSMs. diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/module-info.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/module-info.java index 7a298e5e81bc..dd114f04e740 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/module-info.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/module-info.java @@ -1,5 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. module com.azure.security.keyvault.administration { requires transitive com.azure.core; @@ -8,8 +9,8 @@ exports com.azure.security.keyvault.administration; exports com.azure.security.keyvault.administration.models; - opens com.azure.security.keyvault.administration to com.azure.core; opens com.azure.security.keyvault.administration.models to com.azure.core; - opens com.azure.security.keyvault.administration.implementation to com.azure.core; opens com.azure.security.keyvault.administration.implementation.models to com.azure.core; + opens com.azure.security.keyvault.administration to com.azure.core; + opens com.azure.security.keyvault.administration.implementation to com.azure.core; } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/resources/azure-key-vault-keys.properties b/sdk/keyvault/azure-security-keyvault-administration/src/main/resources/azure-security-keyvault-administration.properties similarity index 100% rename from sdk/keyvault/azure-security-keyvault-keys/src/main/resources/azure-key-vault-keys.properties rename to sdk/keyvault/azure-security-keyvault-administration/src/main/resources/azure-security-keyvault-administration.properties diff --git a/sdk/keyvault/azure-security-keyvault-administration/swagger/src/main/java/AdministrationCustomizations.java b/sdk/keyvault/azure-security-keyvault-administration/swagger/src/main/java/AdministrationCustomizations.java new file mode 100644 index 000000000000..0023a0500015 --- /dev/null +++ b/sdk/keyvault/azure-security-keyvault-administration/swagger/src/main/java/AdministrationCustomizations.java @@ -0,0 +1,165 @@ +// 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.Editor; +import com.azure.autorest.customization.LibraryCustomization; +import com.azure.autorest.customization.PackageCustomization; +import com.github.javaparser.StaticJavaParser; +import com.github.javaparser.ast.Modifier; +import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import org.slf4j.Logger; + +import java.net.MalformedURLException; +import java.net.URL; + +/** + * Contains customizations for Azure Key Vault Administration code generation. + */ +public class AdministrationCustomizations extends Customization { + @Override + public void customize(LibraryCustomization libraryCustomization, Logger logger) { + Editor rawEditor = libraryCustomization.getRawEditor(); + + // Remove unnecessary files. + removeFiles(rawEditor); + + // Customize the client impl classes. + PackageCustomization implPackageCustomization = libraryCustomization.getPackage( + "com.azure.security.keyvault.administration.implementation"); + String implPath = "src/main/java/com/azure/security/keyvault/administration/implementation/"; + + replaceInFile(implPackageCustomization.getClass("KeyVaultClientImpl"), implPath + "KeyVaultClientImpl.java", + new String[] { + "KeyVault", + "private Mono> fullBackupWithResponseAsync", + "private Response fullBackupWithResponse", + "private Mono> preFullBackupWithResponseAsync", + "private Response preFullBackupWithResponse", + "private Mono> preFullRestoreOperationWithResponseAsync", + "private Response preFullRestoreOperationWithResponse", + "private Mono> fullRestoreOperationWithResponseAsync", + "private Response fullRestoreOperationWithResponse", + "private Mono> selectiveKeyRestoreOperationWithResponseAsync", + "private Response selectiveKeyRestoreOperationWithResponse" }, new String[] { + "KeyVaultAdministration", + "public Mono> fullBackupWithResponseAsync", + "public Response fullBackupWithResponse", + "public Mono> preFullBackupWithResponseAsync", + "public Response preFullBackupWithResponse", + "public Mono> preFullRestoreOperationWithResponseAsync", + "public Response preFullRestoreOperationWithResponse", + "public Mono> fullRestoreOperationWithResponseAsync", + "public Response fullRestoreOperationWithResponse", + "public Mono> selectiveKeyRestoreOperationWithResponseAsync", + "public Response selectiveKeyRestoreOperationWithResponse" }); + replaceInFile(implPackageCustomization.getClass("RoleAssignmentsImpl"), implPath + "RoleAssignmentsImpl.java", + new String[] { + "KeyVault", + "private Mono> listForScopeSinglePageAsync", + "private Mono> listForScopeNextSinglePageAsync" }, new String[] { + "KeyVaultAdministration", + "public Mono> listForScopeSinglePageAsync", + "public Mono> listForScopeNextSinglePageAsync" }); + replaceInFile(implPackageCustomization.getClass("RoleDefinitionsImpl"), implPath + "RoleDefinitionsImpl.java", + new String[] { + "KeyVault", + "private Mono> listSinglePageAsync", + "private Mono> listNextSinglePageAsync" }, new String[] { + "KeyVaultAdministration", + "public Mono> listSinglePageAsync", + "public Mono> listNextSinglePageAsync" }); + + // Rename base client impl. + rawEditor.renameFile(implPath + "KeyVaultClientImpl.java", implPath + "KeyVaultAdministrationClientImpl.java"); + + // Change the names of generated + ClassCustomization keyVaultRoleScopeCustomization = libraryCustomization.getPackage( + "com.azure.security.keyvault.administration.models").getClass("KeyVaultRoleScope"); + + customizeKeyVaultRoleScope(keyVaultRoleScopeCustomization); + } + + private static void removeFiles(Editor editor) { + // Remove the next line in favor of renaming to KeyServiceVersion once the TSP spec includes all service + // versions. + editor.removeFile("src/main/java/com/azure/security/keyvault/administration/KeyVaultServiceVersion.java"); + editor.removeFile("src/main/java/com/azure/security/keyvault/administration/KeyVaultAsyncClient.java"); + editor.removeFile("src/main/java/com/azure/security/keyvault/administration/KeyVaultClient.java"); + editor.removeFile("src/main/java/com/azure/security/keyvault/administration/KeyVaultClientBuilder.java"); + editor.removeFile("src/main/java/com/azure/security/keyvault/administration/RoleAssignmentsAsyncClient.java"); + editor.removeFile("src/main/java/com/azure/security/keyvault/administration/RoleAssignmentsClient.java"); + editor.removeFile("src/main/java/com/azure/security/keyvault/administration/RoleDefinitionsAsyncClient.java"); + editor.removeFile("src/main/java/com/azure/security/keyvault/administration/RoleDefinitionsClient.java"); + } + + private static void customizeKeyVaultRoleScope(ClassCustomization classCustomization) { + classCustomization.customizeAst(ast -> { + ast.addImport(IllegalArgumentException.class).addImport(URL.class).addImport(MalformedURLException.class); + + ClassOrInterfaceDeclaration clazz = ast.getClassByName(classCustomization.getClassName()).get(); + + clazz.addMethod("fromUrl", Modifier.Keyword.PUBLIC, Modifier.Keyword.STATIC) + .setType("KeyVaultRoleScope") + .addParameter("String", "url") + .setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline("/**", + " * Creates of finds a {@link KeyVaultRoleScope} from its string representation.", " *", + " * @param url A string representing a URL containing the name of the scope to look for.", + " * @return The corresponding {@link KeyVaultRoleScope}.", + " * @throws IllegalArgumentException If the given {@code url} is malformed.", " */"))) + .setBody(StaticJavaParser.parseBlock( + joinWithNewline("{", "try {", " return fromString(new URL(url).getPath());", + "} catch (MalformedURLException e) {", " throw new IllegalArgumentException(e);", "}", + "}"))); + + clazz.addMethod("fromUrl", Modifier.Keyword.PUBLIC, Modifier.Keyword.STATIC) + .setType("KeyVaultRoleScope") + .addParameter("URL", "url") + .setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline("/**", + " * Creates of finds a {@link KeyVaultRoleScope} from its string representation.", " *", + " * @param url A URL containing the name of the scope to look for.", + " * @return The corresponding {@link KeyVaultRoleScope}.", " */"))) + .setBody(StaticJavaParser.parseBlock("{return fromString(url.getPath());}")); + }); + } + + /** + * This method replaces all the provided strings in the specified file with new strings provided in the latter half + * of the 'strings' parameter. + * + * @param classCustomization The class customization to use to edit the file. + * @param classPath The path to the file to edit. + * @param stringsToReplace The strings to replace. + * @param replacementStrings The strings to replace with. + */ + private static void replaceInFile(ClassCustomization classCustomization, String classPath, + String[] stringsToReplace, String[] replacementStrings) { + + if (stringsToReplace != null && replacementStrings != null) { + // Replace all instances of KeyVaultServiceVersion with KeyVaultAdministrationServiceVersion. We'll remove this + // once the TSP spec includes all service versions. + Editor editor = classCustomization.getEditor(); + String fileContent = editor.getFileContent(classPath); + + // Ensure names has an even length. + if (stringsToReplace.length != replacementStrings.length) { + throw new IllegalArgumentException( + "'stringsToReplace' must have the same number of elements as 'replacementStrings'."); + } + + for (int i = 0; i < stringsToReplace.length; i++) { + fileContent = fileContent.replace(stringsToReplace[i], replacementStrings[i]); + } + + editor.replaceFile(classPath, fileContent); + } else if (stringsToReplace != null || replacementStrings != null) { + throw new IllegalArgumentException( + "'stringsToReplace' must have the same number of elements as 'replacementStrings'."); + } + } + + private static String joinWithNewline(String... lines) { + return String.join("\n", lines); + } +} diff --git a/sdk/keyvault/azure-security-keyvault-administration/swagger/src/main/java/BackupRestoreCustomizations.java b/sdk/keyvault/azure-security-keyvault-administration/swagger/src/main/java/BackupRestoreCustomizations.java deleted file mode 100644 index bf75188f666e..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/swagger/src/main/java/BackupRestoreCustomizations.java +++ /dev/null @@ -1,557 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -import com.azure.autorest.customization.Customization; -import com.azure.autorest.customization.Editor; -import com.azure.autorest.customization.LibraryCustomization; -import org.slf4j.Logger; - -/** - * Contains customizations for Azure KeyVault's Backup Restore swagger code generation. - */ -public class BackupRestoreCustomizations extends Customization { - @Override - public void customize(LibraryCustomization libraryCustomization, Logger logger) { - customizePackageInfos(libraryCustomization.getRawEditor()); - } - - private static void customizePackageInfos(Editor editor) { - editor.replaceFile("src/main/java/com/azure/security/keyvault/administration/package-info.java", - joinWithNewline( - "// Copyright (c) Microsoft Corporation. All rights reserved.", - "// Licensed under the MIT License.", - "", - "/**", - " *

          Azure Key Vault Managed HSM is a", - " * fully-managed, highly-available, single-tenant, standards-compliant cloud service that enables you to safeguard", - " * cryptographic keys for your cloud applications using FIPS 140-2 Level 3 validated HSMs.

          ", - " *", - " *

          The Azure Key Vault Administration client library allows developers to interact with the Azure Key Vault Managed", - " * HSM service from their applications. The library provides a set of APIs that enable developers to perform", - " * administrative tasks such as full backup/restore, key-level role-based access control (RBAC), and account settings", - " * management.

          ", - " *", - " *

          Key Concepts:

          ", - " *", - " *

          What is a Key Vault Access Control Client?

          ", - " *

          The Key Vault Access Control client performs the interactions with the Azure Key Vault service for getting,", - " * setting, deleting, and listing role assignments, as well as listing role definitions. Asynchronous", - " * (KeyVaultAccessControlAsyncClient) and synchronous (KeyVaultAccessControlClient) clients exist in the SDK allowing", - " * for the selection of a client based on an application's use case. Once you've initialized a role assignment, you can", - " * interact with the primary resource types in Key Vault.

          ", - " *", - " *

          What is a Role Definition?

          ", - " *

          A role definition is a collection of permissions. It defines the operations that can be performed, such as", - " * read, write, and delete. It can also define the operations that are excluded from allowed operations.

          ", - " *", - " *

          Role definitions can be listed and specified as part of a role assignment.

          ", - " *", - " *

          What is a Role Assignment?

          ", - " *

          A role assignment is the association of a role definition to a service principal. They can be created, listed,", - " * fetched individually, and deleted.

          ", - " *", - " *

          What is a Key Vault Backup Client

          ", - " *

          The Key Vault Backup Client provides both synchronous and asynchronous operations for performing full key", - " * backups, full key restores, and selective key restores. Asynchronous (KeyVaultBackupAsyncClient) and synchronous", - " * (KeyVaultBackupClient) clients exist in the SDK allowing for the selection of a client based on an application's use", - " * case.

          ", - " *", - " *

          NOTE: The backing store for key backups is a blob storage container using Shared Access Signature", - " * authentication. For more details on creating a SAS token using the BlobServiceClient, see the", - " * Azure", - " * Storage Blobs client README. Alternatively, it is possible to", - " * ", - " * generate a SAS token in Storage Explorer.

          ", - " *", - " *

          What is a Backup Operation?

          ", - " *

          A backup operation represents a long-running operation for a full key backup.

          ", - " *", - " *

          What is a Restore Operation

          ", - " *

          A restore operation represents a long-running operation for both a full key and", - " * selective key restore.

          ", - " *", - " *

          What is a Key Vault Settings Client?

          ", - " *

          The Key Vault Access Control client allows manipulation of an Azure Key Vault account's settings, with", - " * operations such as: getting, updating, and listing. Asynchronous (KeyVaultSettingsAsyncClient) and synchronous", - " * (KeyVaultSettingsClient) clients exist in the SDK allowing for the selection of a client based on an application's", - " * use case.

          ", - " *", - " *

          Getting Started

          ", - " *", - " * In order to interact with the Azure Key Vault service, you will need to create an instance of the", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient} class, a vault url and a", - " * credential object.", - " *", - " *

          The examples shown in this document use a credential object named DefaultAzureCredential for authentication,", - " * which is appropriate for most scenarios, including local development and production environments. Additionally, we", - " * recommend using a", - " * ", - " * managed identity for authentication in production environments. You can find more information on different ways", - " * of authenticating and their corresponding credential types in the", - " * ", - " * Azure Identity documentation\".

          ", - " *", - " *

          Sample: Construct Synchronous Access Control Client

          ", - " *", - " *

          The following code sample demonstrates the creation of a", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient}, using the", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClientBuilder} to configure it.

          ", - " *", - " * ", - " *
          ",
          -                " * KeyVaultAccessControlClient keyVaultAccessControlClient = new KeyVaultAccessControlClientBuilder()",
          -                " *     .vaultUrl("<your-managed-hsm-url>")",
          -                " *     .credential(new DefaultAzureCredentialBuilder().build())",
          -                " *     .buildClient();",
          -                " * 
          ", - " * ", - " *", - " *

          Sample: Construct Asynchronous Access Control Client

          ", - " *", - " *

          The following code sample demonstrates the creation of a", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient}, using the", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClientBuilder} to configure it.

          ", - " *", - " * ", - " *
          ",
          -                " * KeyVaultAccessControlAsyncClient keyVaultAccessControlAsyncClient = new KeyVaultAccessControlClientBuilder()",
          -                " *     .vaultUrl("<your-managed-hsm-url>")",
          -                " *     .credential(new DefaultAzureCredentialBuilder().build())",
          -                " *     .buildAsyncClient();",
          -                " * 
          ", - " * ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Set a Role Definition

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient} can be used to set a role", - " * definition in the key vault.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to asynchronously create a role definition in the key vault, using the", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient#setRoleDefinition(com.azure.security.keyvault.administration.models.KeyVaultRoleScope, java.lang.String) KeyVaultAccessControlClient.setRoleDefinition(KeyVaultRoleScope, String)}", - " * API.

          ", - " *", - " * ", - " *
          ",
          -                " * KeyVaultRoleDefinition roleDefinition = keyVaultAccessControlClient.setRoleDefinition(KeyVaultRoleScope.GLOBAL);",
          -                " *",
          -                " * System.out.printf("Created role definition with randomly generated name '%s' and role name '%s'.%n",",
          -                " *     roleDefinition.getName(), roleDefinition.getRoleName());",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Get a Role Definition

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient} can be used to retrieve a role", - " * definition from the key vault.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to asynchronously retrieve a role definition from the key vault, using", - " * the", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient#getRoleDefinition(com.azure.security.keyvault.administration.models.KeyVaultRoleScope, java.lang.String) KeyVaultAccessControlClient.getRoleDefinition(KeyVaultRoleScope, String)}", - " * API.

          ", - " *", - " * ", - " *
          ",
          -                " * String roleDefinitionName = "de8df120-987e-4477-b9cc-570fd219a62c";",
          -                " * KeyVaultRoleDefinition roleDefinition =",
          -                " *     keyVaultAccessControlClient.getRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName);",
          -                " *",
          -                " * System.out.printf("Retrieved role definition with name '%s' and role name '%s'.%n", roleDefinition.getName(),",
          -                " *     roleDefinition.getRoleName());",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Delete a Role Definition

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient} can be used to delete a role", - " * definition from the key vault.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to asynchronously delete a role definition from the key vault, using", - " * the", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient#deleteRoleDefinition(com.azure.security.keyvault.administration.models.KeyVaultRoleScope, java.lang.String) KeyVaultAccessControlClient.deleteRoleDefinition(KeyVaultRoleScope, String)}", - " * API.

          ", - " *", - " * ", - " *
          ",
          -                " * String roleDefinitionName = "6a709e6e-8964-4012-a99b-6b0131e8ce40";",
          -                " *",
          -                " * keyVaultAccessControlClient.deleteRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName);",
          -                " *",
          -                " * System.out.printf("Deleted role definition with name '%s'.%n", roleDefinitionName);",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Create a Role Assignment

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient} can be used to set a role", - " * assignment in the key vault.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to asynchronously create a role assignment in the key vault, using the", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient#createRoleAssignment(com.azure.security.keyvault.administration.models.KeyVaultRoleScope, java.lang.String, java.lang.String) KeyVaultAccessControlClient.createRoleAssignment(KeyVaultRoleScope, String, String)}", - " * API.

          ", - " *", - " * ", - " *
          ",
          -                " * String roleDefinitionId = "b0b43a39-920c-475b-b34c-32ecc2bbb0ea";",
          -                " * String servicePrincipalId = "169d6a86-61b3-4615-ac7e-2da09edfeed4";",
          -                " * KeyVaultRoleAssignment roleAssignment =",
          -                " *     keyVaultAccessControlClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinitionId,",
          -                " *         servicePrincipalId);",
          -                " *",
          -                " * System.out.printf("Created role assignment with randomly generated name '%s' for principal with id '%s'.%n",",
          -                " *     roleAssignment.getName(), roleAssignment.getProperties().getPrincipalId());",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Get a Role Definition

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient} can be used to retrieve a role", - " * definition from the key vault.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to asynchronously retrieve a role definition from the key vault, using", - " * the", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient#getRoleDefinition(com.azure.security.keyvault.administration.models.KeyVaultRoleScope, java.lang.String) KeyVaultAccessControlClient.getRoleDefinition(KeyVaultRoleScope, String)}", - " * API.

          ", - " *", - " * ", - " *
          ",
          -                " * String roleAssignmentName = "06d1ae8b-0791-4f02-b976-f631251f5a95";",
          -                " * KeyVaultRoleAssignment roleAssignment =",
          -                " *     keyVaultAccessControlClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName);",
          -                " *",
          -                " * System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName());",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Delete a Role Definition

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient} can be used to delete a role", - " * definition from an Azure Key Vault account.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to asynchronously delete a role definition from the key vault, using", - " * the", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient#deleteRoleDefinition(com.azure.security.keyvault.administration.models.KeyVaultRoleScope, java.lang.String) KeyVaultAccessControlClient.deleteRoleDefinition(KeyVaultRoleScope, String)}", - " * API.

          ", - " *", - " * ", - " *
          ",
          -                " * String roleAssignmentName = "c3ed874a-64a9-4a87-8581-2a1ad84b9ddb";",
          -                " *",
          -                " * keyVaultAccessControlClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName);",
          -                " *",
          -                " * System.out.printf("Deleted role assignment with name '%s'.%n", roleAssignmentName);",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Back Up a Collection of Keys

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultBackupClient} can be used to back up the entire", - " * collection of keys from a key vault.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to synchronously back up an entire collection of keys using, using the", - " * {@link com.azure.security.keyvault.administration.KeyVaultBackupClient#beginBackup(String, String)} API.

          ", - " *", - " * ", - " *
          ",
          -                " * String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer";",
          -                " * String sasToken = "sv=2020-02-10&ss=b&srt=o&sp=rwdlactfx&se=2021-06-17T07:13:07Z&st=2021-06-16T23:13:07Z"",
          -                " *     "&spr=https&sig=n5V6fnlkViEF9b7ij%2FttTHNwO2BdFIHKHppRxGAyJdc%3D";",
          -                " *",
          -                " * SyncPoller<KeyVaultBackupOperation, String> backupPoller = client.beginBackup(blobStorageUrl, sasToken);",
          -                " *",
          -                " * PollResponse<KeyVaultBackupOperation> pollResponse = backupPoller.poll();",
          -                " *",
          -                " * System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus());",
          -                " *",
          -                " * PollResponse<KeyVaultBackupOperation> finalPollResponse = backupPoller.waitForCompletion();",
          -                " *",
          -                " * if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) {",
          -                " *     String folderUrl = backupPoller.getFinalResult();",
          -                " *",
          -                " *     System.out.printf("Backup completed. The storage location of this backup is: %s.%n", folderUrl);",
          -                " * } else {",
          -                " *     KeyVaultBackupOperation operation = backupPoller.poll().getValue();",
          -                " *",
          -                " *     System.out.printf("Backup failed with error: %s.%n", operation.getError().getMessage());",
          -                " * }",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Restore a Collection of Keys

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultBackupClient} can be used to restore an entire", - " * collection of keys from a backup.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to synchronously restore an entire collection of keys from a backup,", - " * using the {@link com.azure.security.keyvault.administration.KeyVaultBackupClient#beginRestore(String, String)}", - " * API.

          ", - " *", - " * ", - " *
          ",
          -                " * String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313";",
          -                " * String sasToken = "sv=2020-02-10&ss=b&srt=o&sp=rwdlactfx&se=2021-06-17T07:13:07Z&st=2021-06-16T23:13:07Z"",
          -                " *     "&spr=https&sig=n5V6fnlkViEF9b7ij%2FttTHNwO2BdFIHKHppRxGAyJdc%3D";",
          -                " *",
          -                " * SyncPoller<KeyVaultRestoreOperation, KeyVaultRestoreResult> backupPoller =",
          -                " *     client.beginRestore(folderUrl, sasToken);",
          -                " *",
          -                " * PollResponse<KeyVaultRestoreOperation> pollResponse = backupPoller.poll();",
          -                " *",
          -                " * System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus());",
          -                " *",
          -                " * PollResponse<KeyVaultRestoreOperation> finalPollResponse = backupPoller.waitForCompletion();",
          -                " *",
          -                " * if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) {",
          -                " *     System.out.printf("Backup restored successfully.%n");",
          -                " * } else {",
          -                " *     KeyVaultRestoreOperation operation = backupPoller.poll().getValue();",
          -                " *",
          -                " *     System.out.printf("Restore failed with error: %s.%n", operation.getError().getMessage());",
          -                " * }",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Selectively Restore a Key

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultBackupClient} can be used to restore a specific key", - " * from a backup.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to synchronously restore a specific key from a backup, using", - " * the", - " * {@link com.azure.security.keyvault.administration.KeyVaultBackupClient#beginSelectiveKeyRestore(String, String, String)}", - " * API.

          ", - " *", - " * ", - " *
          ",
          -                " * String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313";",
          -                " * String sasToken = "sv=2020-02-10&ss=b&srt=o&sp=rwdlactfx&se=2021-06-17T07:13:07Z&st=2021-06-16T23:13:07Z"",
          -                " *     "&spr=https&sig=n5V6fnlkViEF9b7ij%2FttTHNwO2BdFIHKHppRxGAyJdc%3D";",
          -                " * String keyName = "myKey";",
          -                " *",
          -                " * SyncPoller<KeyVaultSelectiveKeyRestoreOperation, KeyVaultSelectiveKeyRestoreResult> backupPoller =",
          -                " *     client.beginSelectiveKeyRestore(folderUrl, sasToken, keyName);",
          -                " *",
          -                " * PollResponse<KeyVaultSelectiveKeyRestoreOperation> pollResponse = backupPoller.poll();",
          -                " *",
          -                " * System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus());",
          -                " *",
          -                " * PollResponse<KeyVaultSelectiveKeyRestoreOperation> finalPollResponse = backupPoller.waitForCompletion();",
          -                " *",
          -                " * if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) {",
          -                " *     System.out.printf("Key restored successfully.%n");",
          -                " * } else {",
          -                " *     KeyVaultSelectiveKeyRestoreOperation operation = backupPoller.poll().getValue();",
          -                " *",
          -                " *     System.out.printf("Key restore failed with error: %s.%n", operation.getError().getMessage());",
          -                " * }",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Get All Settings

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultSettingsClient} can be used to list all the settings", - " * for an Azure Key Vault account.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to synchronously back up an entire collection of keys using, using the", - " * {@link com.azure.security.keyvault.administration.KeyVaultSettingsClient#getSettings()} API.

          ", - " *", - " * ", - " *
          ",
          -                " * KeyVaultGetSettingsResult getSettingsResult = keyVaultSettingsClient.getSettings();",
          -                " * List<KeyVaultSetting> settings = getSettingsResult.getSettings();",
          -                " *",
          -                " * settings.forEach(setting ->",
          -                " *     System.out.printf("Retrieved setting with name '%s' and value %s'.%n", setting.getName(),",
          -                " *         setting.asBoolean()));",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Retrieve a Specific Setting

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultSettingsClient} can be used to retrieve a specific", - " * setting.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to synchronously restore an entire collection of keys from a backup,", - " * using the {@link com.azure.security.keyvault.administration.KeyVaultSettingsClient#getSetting(String)} API.

          ", - " *", - " * ", - " *
          ",
          -                " * KeyVaultSetting setting = keyVaultSettingsClient.getSetting(settingName);",
          -                " *",
          -                " * System.out.printf("Retrieved setting '%s' with value '%s'.%n", setting.getName(), setting.asBoolean());",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Update a Specific Setting

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultSettingsClient} can be used to restore a specific key", - " * from a backup.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to synchronously restore a specific key from a backup, using", - " * the", - " * {@link com.azure.security.keyvault.administration.KeyVaultSettingsClient#updateSetting(com.azure.security.keyvault.administration.models.KeyVaultSetting) KeyVaultSettingsClient.updateSetting(KeyVaultSetting)}", - " *", - " * ", - " *

          ",
          -                " * KeyVaultSetting settingToUpdate = new KeyVaultSetting(settingName, true);",
          -                " * KeyVaultSetting updatedSetting = keyVaultSettingsClient.updateSetting(settingToUpdate);",
          -                " *",
          -                " * System.out.printf("Updated setting '%s' to '%s'.%n", updatedSetting.getName(), updatedSetting.asBoolean());",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " * @see com.azure.security.keyvault.administration.KeyVaultAccessControlClient", - " * @see com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient", - " * @see com.azure.security.keyvault.administration.KeyVaultAccessControlClientBuilder", - " * @see com.azure.security.keyvault.administration.KeyVaultBackupClient", - " * @see com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient", - " * @see com.azure.security.keyvault.administration.KeyVaultBackupClientBuilder", - " * @see com.azure.security.keyvault.administration.KeyVaultSettingsClient", - " * @see com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient", - " * @see com.azure.security.keyvault.administration.KeyVaultSettingsClientBuilder", - " */", - "package com.azure.security.keyvault.administration;", - "" - )); - - editor.replaceFile("src/main/java/com/azure/security/keyvault/administration/models/package-info.java", - joinWithNewline( - "// Copyright (c) Microsoft Corporation. All rights reserved.", - "// Licensed under the MIT License.", - "// Code generated by Microsoft (R) AutoRest Code Generator.", - "", - "/**", - " * Package containing classes used by {@link", - " * com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient} and {@link", - " * com.azure.security.keyvault.administration.KeyVaultAccessControlClient} to perform access control operations on Azure", - " * Key Vault resources, as well as classes used by {@link", - " * com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient} and {@link", - " * com.azure.security.keyvault.administration.KeyVaultBackupClient} to perform backup and restore operations on Azure", - " * Key Vault keys.", - " */", - "package com.azure.security.keyvault.administration.models;", - "" - )); - - editor.replaceFile("src/main/java/com/azure/security/keyvault/administration/implementation/package-info.java", - joinWithNewline( - "// 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 KeyVaultAccessControlClient, KeyVaultBackupClient, and", - " * KeyVaultSettingsClient. The key vault client performs cryptographic key operations and vault operations against the", - " * Key Vault service.", - " */", - "package com.azure.security.keyvault.administration.implementation;", - "" - )); - - editor.replaceFile("src/main/java/com/azure/security/keyvault/administration/implementation/models/package-info.java", - joinWithNewline( - "// 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 KeyVaultAccessControlClient, KeyVaultBackupClient, and KeyVaultSettingsClient.", - " * The key vault client performs cryptographic key operations and vault operations against the Key Vault service.", - " */", - "package com.azure.security.keyvault.administration.implementation.models;", - "" - )); - } - - private static String joinWithNewline(String... lines) { - return String.join("\n", lines); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/swagger/src/main/java/RbacCustomizations.java b/sdk/keyvault/azure-security-keyvault-administration/swagger/src/main/java/RbacCustomizations.java deleted file mode 100644 index 5351eec06d66..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/swagger/src/main/java/RbacCustomizations.java +++ /dev/null @@ -1,615 +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.Editor; -import com.azure.autorest.customization.LibraryCustomization; -import com.azure.autorest.customization.PackageCustomization; -import com.github.javaparser.StaticJavaParser; -import com.github.javaparser.ast.Modifier; -import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; -import org.slf4j.Logger; - -import java.net.MalformedURLException; -import java.net.URL; - -/** - * Contains customizations for Azure KeyVault's RBAC swagger code generation. - */ -public class RbacCustomizations extends Customization { - @Override - public void customize(LibraryCustomization libraryCustomization, Logger logger) { - customizeModels(libraryCustomization.getPackage("com.azure.security.keyvault.administration.models")); - customizePackageInfos(libraryCustomization.getRawEditor()); - } - - private static void customizeModels(PackageCustomization packageCustomization) { - customizeKeyVaultRoleScope(packageCustomization.getClass("KeyVaultRoleScope")); - } - - private static void customizeKeyVaultRoleScope(ClassCustomization classCustomization) { - classCustomization.customizeAst(ast -> { - ast.addImport(IllegalArgumentException.class) - .addImport(URL.class) - .addImport(MalformedURLException.class); - - ClassOrInterfaceDeclaration clazz = ast.getClassByName(classCustomization.getClassName()).get(); - - clazz.addMethod("fromUrl", Modifier.Keyword.PUBLIC, Modifier.Keyword.STATIC) - .setType("KeyVaultRoleScope") - .addParameter("String", "url") - .setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline( - "/**", - " * Creates of finds a {@link KeyVaultRoleScope} from its string representation.", - " *", - " * @param url A string representing a URL containing the name of the scope to look for.", - " * @return The corresponding {@link KeyVaultRoleScope}.", - " * @throws IllegalArgumentException If the given {@code url} is malformed.", - " */" - ))) - .setBody(StaticJavaParser.parseBlock(joinWithNewline( - "{", - "try {", - " return fromString(new URL(url).getPath());", - "} catch (MalformedURLException e) {", - " throw new IllegalArgumentException(e);", - "}", - "}" - ))); - - clazz.addMethod("fromUrl", Modifier.Keyword.PUBLIC, Modifier.Keyword.STATIC) - .setType("KeyVaultRoleScope") - .addParameter("URL", "url") - .setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline( - "/**", - " * Creates of finds a {@link KeyVaultRoleScope} from its string representation.", - " *", - " * @param url A URL containing the name of the scope to look for.", - " * @return The corresponding {@link KeyVaultRoleScope}.", - " */" - ))) - .setBody(StaticJavaParser.parseBlock("{return fromString(url.getPath());}")); - }); - } - - private static void customizePackageInfos(Editor editor) { - editor.replaceFile("src/main/java/com/azure/security/keyvault/administration/package-info.java", - joinWithNewline( - "// Copyright (c) Microsoft Corporation. All rights reserved.", - "// Licensed under the MIT License.", - "", - "/**", - " *

          Azure Key Vault Managed HSM is a", - " * fully-managed, highly-available, single-tenant, standards-compliant cloud service that enables you to safeguard", - " * cryptographic keys for your cloud applications using FIPS 140-2 Level 3 validated HSMs.

          ", - " *", - " *

          The Azure Key Vault Administration client library allows developers to interact with the Azure Key Vault Managed", - " * HSM service from their applications. The library provides a set of APIs that enable developers to perform", - " * administrative tasks such as full backup/restore, key-level role-based access control (RBAC), and account settings", - " * management.

          ", - " *", - " *

          Key Concepts:

          ", - " *", - " *

          What is a Key Vault Access Control Client?

          ", - " *

          The Key Vault Access Control client performs the interactions with the Azure Key Vault service for getting,", - " * setting, deleting, and listing role assignments, as well as listing role definitions. Asynchronous", - " * (KeyVaultAccessControlAsyncClient) and synchronous (KeyVaultAccessControlClient) clients exist in the SDK allowing", - " * for the selection of a client based on an application's use case. Once you've initialized a role assignment, you can", - " * interact with the primary resource types in Key Vault.

          ", - " *", - " *

          What is a Role Definition?

          ", - " *

          A role definition is a collection of permissions. It defines the operations that can be performed, such as", - " * read, write, and delete. It can also define the operations that are excluded from allowed operations.

          ", - " *", - " *

          Role definitions can be listed and specified as part of a role assignment.

          ", - " *", - " *

          What is a Role Assignment?

          ", - " *

          A role assignment is the association of a role definition to a service principal. They can be created, listed,", - " * fetched individually, and deleted.

          ", - " *", - " *

          What is a Key Vault Backup Client

          ", - " *

          The Key Vault Backup Client provides both synchronous and asynchronous operations for performing full key", - " * backups, full key restores, and selective key restores. Asynchronous (KeyVaultBackupAsyncClient) and synchronous", - " * (KeyVaultBackupClient) clients exist in the SDK allowing for the selection of a client based on an application's use", - " * case.

          ", - " *", - " *

          NOTE: The backing store for key backups is a blob storage container using Shared Access Signature", - " * authentication. For more details on creating a SAS token using the BlobServiceClient, see the", - " * Azure", - " * Storage Blobs client README. Alternatively, it is possible to", - " * ", - " * generate a SAS token in Storage Explorer.

          ", - " *", - " *

          What is a Backup Operation?

          ", - " *

          A backup operation represents a long-running operation for a full key backup.

          ", - " *", - " *

          What is a Restore Operation

          ", - " *

          A restore operation represents a long-running operation for both a full key and", - " * selective key restore.

          ", - " *", - " *

          What is a Key Vault Settings Client?

          ", - " *

          The Key Vault Access Control client allows manipulation of an Azure Key Vault account's settings, with", - " * operations such as: getting, updating, and listing. Asynchronous (KeyVaultSettingsAsyncClient) and synchronous", - " * (KeyVaultSettingsClient) clients exist in the SDK allowing for the selection of a client based on an application's", - " * use case.

          ", - " *", - " *

          Getting Started

          ", - " *", - " * In order to interact with the Azure Key Vault service, you will need to create an instance of the", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient} class, a vault url and a", - " * credential object.", - " *", - " *

          The examples shown in this document use a credential object named DefaultAzureCredential for authentication,", - " * which is appropriate for most scenarios, including local development and production environments. Additionally, we", - " * recommend using a", - " * ", - " * managed identity for authentication in production environments. You can find more information on different ways", - " * of authenticating and their corresponding credential types in the", - " * ", - " * Azure Identity documentation\".

          ", - " *", - " *

          Sample: Construct Synchronous Access Control Client

          ", - " *", - " *

          The following code sample demonstrates the creation of a", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient}, using the", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClientBuilder} to configure it.

          ", - " *", - " * ", - " *
          ",
          -                " * KeyVaultAccessControlClient keyVaultAccessControlClient = new KeyVaultAccessControlClientBuilder()",
          -                " *     .vaultUrl("<your-managed-hsm-url>")",
          -                " *     .credential(new DefaultAzureCredentialBuilder().build())",
          -                " *     .buildClient();",
          -                " * 
          ", - " * ", - " *", - " *

          Sample: Construct Asynchronous Access Control Client

          ", - " *", - " *

          The following code sample demonstrates the creation of a", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient}, using the", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClientBuilder} to configure it.

          ", - " *", - " * ", - " *
          ",
          -                " * KeyVaultAccessControlAsyncClient keyVaultAccessControlAsyncClient = new KeyVaultAccessControlClientBuilder()",
          -                " *     .vaultUrl("<your-managed-hsm-url>")",
          -                " *     .credential(new DefaultAzureCredentialBuilder().build())",
          -                " *     .buildAsyncClient();",
          -                " * 
          ", - " * ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Set a Role Definition

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient} can be used to set a role", - " * definition in the key vault.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to asynchronously create a role definition in the key vault, using the", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient#setRoleDefinition(com.azure.security.keyvault.administration.models.KeyVaultRoleScope, java.lang.String) KeyVaultAccessControlClient.setRoleDefinition(KeyVaultRoleScope, String)}", - " * API.

          ", - " *", - " * ", - " *
          ",
          -                " * KeyVaultRoleDefinition roleDefinition = keyVaultAccessControlClient.setRoleDefinition(KeyVaultRoleScope.GLOBAL);",
          -                " *",
          -                " * System.out.printf("Created role definition with randomly generated name '%s' and role name '%s'.%n",",
          -                " *     roleDefinition.getName(), roleDefinition.getRoleName());",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Get a Role Definition

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient} can be used to retrieve a role", - " * definition from the key vault.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to asynchronously retrieve a role definition from the key vault, using", - " * the", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient#getRoleDefinition(com.azure.security.keyvault.administration.models.KeyVaultRoleScope, java.lang.String) KeyVaultAccessControlClient.getRoleDefinition(KeyVaultRoleScope, String)}", - " * API.

          ", - " *", - " * ", - " *
          ",
          -                " * String roleDefinitionName = "de8df120-987e-4477-b9cc-570fd219a62c";",
          -                " * KeyVaultRoleDefinition roleDefinition =",
          -                " *     keyVaultAccessControlClient.getRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName);",
          -                " *",
          -                " * System.out.printf("Retrieved role definition with name '%s' and role name '%s'.%n", roleDefinition.getName(),",
          -                " *     roleDefinition.getRoleName());",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Delete a Role Definition

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient} can be used to delete a role", - " * definition from the key vault.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to asynchronously delete a role definition from the key vault, using", - " * the", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient#deleteRoleDefinition(com.azure.security.keyvault.administration.models.KeyVaultRoleScope, java.lang.String) KeyVaultAccessControlClient.deleteRoleDefinition(KeyVaultRoleScope, String)}", - " * API.

          ", - " *", - " * ", - " *
          ",
          -                " * String roleDefinitionName = "6a709e6e-8964-4012-a99b-6b0131e8ce40";",
          -                " *",
          -                " * keyVaultAccessControlClient.deleteRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName);",
          -                " *",
          -                " * System.out.printf("Deleted role definition with name '%s'.%n", roleDefinitionName);",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Create a Role Assignment

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient} can be used to set a role", - " * assignment in the key vault.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to asynchronously create a role assignment in the key vault, using the", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient#createRoleAssignment(com.azure.security.keyvault.administration.models.KeyVaultRoleScope, java.lang.String, java.lang.String) KeyVaultAccessControlClient.createRoleAssignment(KeyVaultRoleScope, String, String)}", - " * API.

          ", - " *", - " * ", - " *
          ",
          -                " * String roleDefinitionId = "b0b43a39-920c-475b-b34c-32ecc2bbb0ea";",
          -                " * String servicePrincipalId = "169d6a86-61b3-4615-ac7e-2da09edfeed4";",
          -                " * KeyVaultRoleAssignment roleAssignment =",
          -                " *     keyVaultAccessControlClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinitionId,",
          -                " *         servicePrincipalId);",
          -                " *",
          -                " * System.out.printf("Created role assignment with randomly generated name '%s' for principal with id '%s'.%n",",
          -                " *     roleAssignment.getName(), roleAssignment.getProperties().getPrincipalId());",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Get a Role Definition

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient} can be used to retrieve a role", - " * definition from the key vault.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to asynchronously retrieve a role definition from the key vault, using", - " * the", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient#getRoleDefinition(com.azure.security.keyvault.administration.models.KeyVaultRoleScope, java.lang.String) KeyVaultAccessControlClient.getRoleDefinition(KeyVaultRoleScope, String)}", - " * API.

          ", - " *", - " * ", - " *
          ",
          -                " * String roleAssignmentName = "06d1ae8b-0791-4f02-b976-f631251f5a95";",
          -                " * KeyVaultRoleAssignment roleAssignment =",
          -                " *     keyVaultAccessControlClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName);",
          -                " *",
          -                " * System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName());",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Delete a Role Definition

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient} can be used to delete a role", - " * definition from an Azure Key Vault account.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to asynchronously delete a role definition from the key vault, using", - " * the", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient#deleteRoleDefinition(com.azure.security.keyvault.administration.models.KeyVaultRoleScope, java.lang.String) KeyVaultAccessControlClient.deleteRoleDefinition(KeyVaultRoleScope, String)}", - " * API.

          ", - " *", - " * ", - " *
          ",
          -                " * String roleAssignmentName = "c3ed874a-64a9-4a87-8581-2a1ad84b9ddb";",
          -                " *",
          -                " * keyVaultAccessControlClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName);",
          -                " *",
          -                " * System.out.printf("Deleted role assignment with name '%s'.%n", roleAssignmentName);",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Back Up a Collection of Keys

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultBackupClient} can be used to back up the entire", - " * collection of keys from a key vault.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to synchronously back up an entire collection of keys using, using the", - " * {@link com.azure.security.keyvault.administration.KeyVaultBackupClient#beginBackup(String, String)} API.

          ", - " *", - " * ", - " *
          ",
          -                " * String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer";",
          -                " * String sasToken = "sv=2020-02-10&ss=b&srt=o&sp=rwdlactfx&se=2021-06-17T07:13:07Z&st=2021-06-16T23:13:07Z"",
          -                " *     "&spr=https&sig=n5V6fnlkViEF9b7ij%2FttTHNwO2BdFIHKHppRxGAyJdc%3D";",
          -                " *",
          -                " * SyncPoller<KeyVaultBackupOperation, String> backupPoller = client.beginBackup(blobStorageUrl, sasToken);",
          -                " *",
          -                " * PollResponse<KeyVaultBackupOperation> pollResponse = backupPoller.poll();",
          -                " *",
          -                " * System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus());",
          -                " *",
          -                " * PollResponse<KeyVaultBackupOperation> finalPollResponse = backupPoller.waitForCompletion();",
          -                " *",
          -                " * if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) {",
          -                " *     String folderUrl = backupPoller.getFinalResult();",
          -                " *",
          -                " *     System.out.printf("Backup completed. The storage location of this backup is: %s.%n", folderUrl);",
          -                " * } else {",
          -                " *     KeyVaultBackupOperation operation = backupPoller.poll().getValue();",
          -                " *",
          -                " *     System.out.printf("Backup failed with error: %s.%n", operation.getError().getMessage());",
          -                " * }",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Restore a Collection of Keys

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultBackupClient} can be used to restore an entire", - " * collection of keys from a backup.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to synchronously restore an entire collection of keys from a backup,", - " * using the {@link com.azure.security.keyvault.administration.KeyVaultBackupClient#beginRestore(String, String)}", - " * API.

          ", - " *", - " * ", - " *
          ",
          -                " * String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313";",
          -                " * String sasToken = "sv=2020-02-10&ss=b&srt=o&sp=rwdlactfx&se=2021-06-17T07:13:07Z&st=2021-06-16T23:13:07Z"",
          -                " *     "&spr=https&sig=n5V6fnlkViEF9b7ij%2FttTHNwO2BdFIHKHppRxGAyJdc%3D";",
          -                " *",
          -                " * SyncPoller<KeyVaultRestoreOperation, KeyVaultRestoreResult> backupPoller =",
          -                " *     client.beginRestore(folderUrl, sasToken);",
          -                " *",
          -                " * PollResponse<KeyVaultRestoreOperation> pollResponse = backupPoller.poll();",
          -                " *",
          -                " * System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus());",
          -                " *",
          -                " * PollResponse<KeyVaultRestoreOperation> finalPollResponse = backupPoller.waitForCompletion();",
          -                " *",
          -                " * if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) {",
          -                " *     System.out.printf("Backup restored successfully.%n");",
          -                " * } else {",
          -                " *     KeyVaultRestoreOperation operation = backupPoller.poll().getValue();",
          -                " *",
          -                " *     System.out.printf("Restore failed with error: %s.%n", operation.getError().getMessage());",
          -                " * }",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Selectively Restore a Key

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultBackupClient} can be used to restore a specific key", - " * from a backup.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to synchronously restore a specific key from a backup, using", - " * the", - " * {@link com.azure.security.keyvault.administration.KeyVaultBackupClient#beginSelectiveKeyRestore(String, String, String)}", - " * API.

          ", - " *", - " * ", - " *
          ",
          -                " * String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313";",
          -                " * String sasToken = "sv=2020-02-10&ss=b&srt=o&sp=rwdlactfx&se=2021-06-17T07:13:07Z&st=2021-06-16T23:13:07Z"",
          -                " *     "&spr=https&sig=n5V6fnlkViEF9b7ij%2FttTHNwO2BdFIHKHppRxGAyJdc%3D";",
          -                " * String keyName = "myKey";",
          -                " *",
          -                " * SyncPoller<KeyVaultSelectiveKeyRestoreOperation, KeyVaultSelectiveKeyRestoreResult> backupPoller =",
          -                " *     client.beginSelectiveKeyRestore(folderUrl, sasToken, keyName);",
          -                " *",
          -                " * PollResponse<KeyVaultSelectiveKeyRestoreOperation> pollResponse = backupPoller.poll();",
          -                " *",
          -                " * System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus());",
          -                " *",
          -                " * PollResponse<KeyVaultSelectiveKeyRestoreOperation> finalPollResponse = backupPoller.waitForCompletion();",
          -                " *",
          -                " * if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) {",
          -                " *     System.out.printf("Key restored successfully.%n");",
          -                " * } else {",
          -                " *     KeyVaultSelectiveKeyRestoreOperation operation = backupPoller.poll().getValue();",
          -                " *",
          -                " *     System.out.printf("Key restore failed with error: %s.%n", operation.getError().getMessage());",
          -                " * }",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Get All Settings

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultSettingsClient} can be used to list all the settings", - " * for an Azure Key Vault account.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to synchronously back up an entire collection of keys using, using the", - " * {@link com.azure.security.keyvault.administration.KeyVaultSettingsClient#getSettings()} API.

          ", - " *", - " * ", - " *
          ",
          -                " * KeyVaultGetSettingsResult getSettingsResult = keyVaultSettingsClient.getSettings();",
          -                " * List<KeyVaultSetting> settings = getSettingsResult.getSettings();",
          -                " *",
          -                " * settings.forEach(setting ->",
          -                " *     System.out.printf("Retrieved setting with name '%s' and value %s'.%n", setting.getName(),",
          -                " *         setting.asBoolean()));",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Retrieve a Specific Setting

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultSettingsClient} can be used to retrieve a specific", - " * setting.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to synchronously restore an entire collection of keys from a backup,", - " * using the {@link com.azure.security.keyvault.administration.KeyVaultSettingsClient#getSetting(String)} API.

          ", - " *", - " * ", - " *
          ",
          -                " * KeyVaultSetting setting = keyVaultSettingsClient.getSetting(settingName);",
          -                " *",
          -                " * System.out.printf("Retrieved setting '%s' with value '%s'.%n", setting.getName(), setting.asBoolean());",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Update a Specific Setting

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultSettingsClient} can be used to restore a specific key", - " * from a backup.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to synchronously restore a specific key from a backup, using", - " * the", - " * {@link com.azure.security.keyvault.administration.KeyVaultSettingsClient#updateSetting(com.azure.security.keyvault.administration.models.KeyVaultSetting) KeyVaultSettingsClient.updateSetting(KeyVaultSetting)}", - " *", - " * ", - " *

          ",
          -                " * KeyVaultSetting settingToUpdate = new KeyVaultSetting(settingName, true);",
          -                " * KeyVaultSetting updatedSetting = keyVaultSettingsClient.updateSetting(settingToUpdate);",
          -                " *",
          -                " * System.out.printf("Updated setting '%s' to '%s'.%n", updatedSetting.getName(), updatedSetting.asBoolean());",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " * @see com.azure.security.keyvault.administration.KeyVaultAccessControlClient", - " * @see com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient", - " * @see com.azure.security.keyvault.administration.KeyVaultAccessControlClientBuilder", - " * @see com.azure.security.keyvault.administration.KeyVaultBackupClient", - " * @see com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient", - " * @see com.azure.security.keyvault.administration.KeyVaultBackupClientBuilder", - " * @see com.azure.security.keyvault.administration.KeyVaultSettingsClient", - " * @see com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient", - " * @see com.azure.security.keyvault.administration.KeyVaultSettingsClientBuilder", - " */", - "package com.azure.security.keyvault.administration;", - "" - )); - - editor.replaceFile("src/main/java/com/azure/security/keyvault/administration/models/package-info.java", - joinWithNewline( - "// Copyright (c) Microsoft Corporation. All rights reserved.", - "// Licensed under the MIT License.", - "// Code generated by Microsoft (R) AutoRest Code Generator.", - "", - "/**", - " * Package containing classes used by {@link", - " * com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient} and {@link", - " * com.azure.security.keyvault.administration.KeyVaultAccessControlClient} to perform access control operations on Azure", - " * Key Vault resources, as well as classes used by {@link", - " * com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient} and {@link", - " * com.azure.security.keyvault.administration.KeyVaultBackupClient} to perform backup and restore operations on Azure", - " * Key Vault keys.", - " */", - "package com.azure.security.keyvault.administration.models;", - "" - )); - - editor.replaceFile("src/main/java/com/azure/security/keyvault/administration/implementation/package-info.java", - joinWithNewline( - "// 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 KeyVaultAccessControlClient, KeyVaultBackupClient, and", - " * KeyVaultSettingsClient. The key vault client performs cryptographic key operations and vault operations against the", - " * Key Vault service.", - " */", - "package com.azure.security.keyvault.administration.implementation;", - "" - )); - - editor.replaceFile("src/main/java/com/azure/security/keyvault/administration/implementation/models/package-info.java", - joinWithNewline( - "// 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 KeyVaultAccessControlClient, KeyVaultBackupClient, and KeyVaultSettingsClient.", - " * The key vault client performs cryptographic key operations and vault operations against the Key Vault service.", - " */", - "package com.azure.security.keyvault.administration.implementation.models;", - "" - )); - } - - private static String joinWithNewline(String... lines) { - return String.join("\n", lines); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/swagger/src/main/java/SettingsCustomizations.java b/sdk/keyvault/azure-security-keyvault-administration/swagger/src/main/java/SettingsCustomizations.java deleted file mode 100644 index c04de74ca5fd..000000000000 --- a/sdk/keyvault/azure-security-keyvault-administration/swagger/src/main/java/SettingsCustomizations.java +++ /dev/null @@ -1,557 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -import com.azure.autorest.customization.Customization; -import com.azure.autorest.customization.Editor; -import com.azure.autorest.customization.LibraryCustomization; -import org.slf4j.Logger; - -/** - * Contains customizations for Azure KeyVault's Settings swagger code generation. - */ -public class SettingsCustomizations extends Customization { - @Override - public void customize(LibraryCustomization libraryCustomization, Logger logger) { - customizePackageInfos(libraryCustomization.getRawEditor()); - } - - private static void customizePackageInfos(Editor editor) { - editor.replaceFile("src/main/java/com/azure/security/keyvault/administration/package-info.java", - joinWithNewline( - "// Copyright (c) Microsoft Corporation. All rights reserved.", - "// Licensed under the MIT License.", - "", - "/**", - " *

          Azure Key Vault Managed HSM is a", - " * fully-managed, highly-available, single-tenant, standards-compliant cloud service that enables you to safeguard", - " * cryptographic keys for your cloud applications using FIPS 140-2 Level 3 validated HSMs.

          ", - " *", - " *

          The Azure Key Vault Administration client library allows developers to interact with the Azure Key Vault Managed", - " * HSM service from their applications. The library provides a set of APIs that enable developers to perform", - " * administrative tasks such as full backup/restore, key-level role-based access control (RBAC), and account settings", - " * management.

          ", - " *", - " *

          Key Concepts:

          ", - " *", - " *

          What is a Key Vault Access Control Client?

          ", - " *

          The Key Vault Access Control client performs the interactions with the Azure Key Vault service for getting,", - " * setting, deleting, and listing role assignments, as well as listing role definitions. Asynchronous", - " * (KeyVaultAccessControlAsyncClient) and synchronous (KeyVaultAccessControlClient) clients exist in the SDK allowing", - " * for the selection of a client based on an application's use case. Once you've initialized a role assignment, you can", - " * interact with the primary resource types in Key Vault.

          ", - " *", - " *

          What is a Role Definition?

          ", - " *

          A role definition is a collection of permissions. It defines the operations that can be performed, such as", - " * read, write, and delete. It can also define the operations that are excluded from allowed operations.

          ", - " *", - " *

          Role definitions can be listed and specified as part of a role assignment.

          ", - " *", - " *

          What is a Role Assignment?

          ", - " *

          A role assignment is the association of a role definition to a service principal. They can be created, listed,", - " * fetched individually, and deleted.

          ", - " *", - " *

          What is a Key Vault Backup Client

          ", - " *

          The Key Vault Backup Client provides both synchronous and asynchronous operations for performing full key", - " * backups, full key restores, and selective key restores. Asynchronous (KeyVaultBackupAsyncClient) and synchronous", - " * (KeyVaultBackupClient) clients exist in the SDK allowing for the selection of a client based on an application's use", - " * case.

          ", - " *", - " *

          NOTE: The backing store for key backups is a blob storage container using Shared Access Signature", - " * authentication. For more details on creating a SAS token using the BlobServiceClient, see the", - " * Azure", - " * Storage Blobs client README. Alternatively, it is possible to", - " * ", - " * generate a SAS token in Storage Explorer.

          ", - " *", - " *

          What is a Backup Operation?

          ", - " *

          A backup operation represents a long-running operation for a full key backup.

          ", - " *", - " *

          What is a Restore Operation

          ", - " *

          A restore operation represents a long-running operation for both a full key and", - " * selective key restore.

          ", - " *", - " *

          What is a Key Vault Settings Client?

          ", - " *

          The Key Vault Access Control client allows manipulation of an Azure Key Vault account's settings, with", - " * operations such as: getting, updating, and listing. Asynchronous (KeyVaultSettingsAsyncClient) and synchronous", - " * (KeyVaultSettingsClient) clients exist in the SDK allowing for the selection of a client based on an application's", - " * use case.

          ", - " *", - " *

          Getting Started

          ", - " *", - " * In order to interact with the Azure Key Vault service, you will need to create an instance of the", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient} class, a vault url and a", - " * credential object.", - " *", - " *

          The examples shown in this document use a credential object named DefaultAzureCredential for authentication,", - " * which is appropriate for most scenarios, including local development and production environments. Additionally, we", - " * recommend using a", - " * ", - " * managed identity for authentication in production environments. You can find more information on different ways", - " * of authenticating and their corresponding credential types in the", - " * ", - " * Azure Identity documentation\".

          ", - " *", - " *

          Sample: Construct Synchronous Access Control Client

          ", - " *", - " *

          The following code sample demonstrates the creation of a", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient}, using the", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClientBuilder} to configure it.

          ", - " *", - " * ", - " *
          ",
          -                " * KeyVaultAccessControlClient keyVaultAccessControlClient = new KeyVaultAccessControlClientBuilder()",
          -                " *     .vaultUrl("<your-managed-hsm-url>")",
          -                " *     .credential(new DefaultAzureCredentialBuilder().build())",
          -                " *     .buildClient();",
          -                " * 
          ", - " * ", - " *", - " *

          Sample: Construct Asynchronous Access Control Client

          ", - " *", - " *

          The following code sample demonstrates the creation of a", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient}, using the", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClientBuilder} to configure it.

          ", - " *", - " * ", - " *
          ",
          -                " * KeyVaultAccessControlAsyncClient keyVaultAccessControlAsyncClient = new KeyVaultAccessControlClientBuilder()",
          -                " *     .vaultUrl("<your-managed-hsm-url>")",
          -                " *     .credential(new DefaultAzureCredentialBuilder().build())",
          -                " *     .buildAsyncClient();",
          -                " * 
          ", - " * ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Set a Role Definition

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient} can be used to set a role", - " * definition in the key vault.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to asynchronously create a role definition in the key vault, using the", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient#setRoleDefinition(com.azure.security.keyvault.administration.models.KeyVaultRoleScope, java.lang.String) KeyVaultAccessControlClient.setRoleDefinition(KeyVaultRoleScope, String)}", - " * API.

          ", - " *", - " * ", - " *
          ",
          -                " * KeyVaultRoleDefinition roleDefinition = keyVaultAccessControlClient.setRoleDefinition(KeyVaultRoleScope.GLOBAL);",
          -                " *",
          -                " * System.out.printf("Created role definition with randomly generated name '%s' and role name '%s'.%n",",
          -                " *     roleDefinition.getName(), roleDefinition.getRoleName());",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Get a Role Definition

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient} can be used to retrieve a role", - " * definition from the key vault.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to asynchronously retrieve a role definition from the key vault, using", - " * the", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient#getRoleDefinition(com.azure.security.keyvault.administration.models.KeyVaultRoleScope, java.lang.String) KeyVaultAccessControlClient.getRoleDefinition(KeyVaultRoleScope, String)}", - " * API.

          ", - " *", - " * ", - " *
          ",
          -                " * String roleDefinitionName = "de8df120-987e-4477-b9cc-570fd219a62c";",
          -                " * KeyVaultRoleDefinition roleDefinition =",
          -                " *     keyVaultAccessControlClient.getRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName);",
          -                " *",
          -                " * System.out.printf("Retrieved role definition with name '%s' and role name '%s'.%n", roleDefinition.getName(),",
          -                " *     roleDefinition.getRoleName());",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Delete a Role Definition

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient} can be used to delete a role", - " * definition from the key vault.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to asynchronously delete a role definition from the key vault, using", - " * the", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient#deleteRoleDefinition(com.azure.security.keyvault.administration.models.KeyVaultRoleScope, java.lang.String) KeyVaultAccessControlClient.deleteRoleDefinition(KeyVaultRoleScope, String)}", - " * API.

          ", - " *", - " * ", - " *
          ",
          -                " * String roleDefinitionName = "6a709e6e-8964-4012-a99b-6b0131e8ce40";",
          -                " *",
          -                " * keyVaultAccessControlClient.deleteRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName);",
          -                " *",
          -                " * System.out.printf("Deleted role definition with name '%s'.%n", roleDefinitionName);",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Create a Role Assignment

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient} can be used to set a role", - " * assignment in the key vault.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to asynchronously create a role assignment in the key vault, using the", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient#createRoleAssignment(com.azure.security.keyvault.administration.models.KeyVaultRoleScope, java.lang.String, java.lang.String) KeyVaultAccessControlClient.createRoleAssignment(KeyVaultRoleScope, String, String)}", - " * API.

          ", - " *", - " * ", - " *
          ",
          -                " * String roleDefinitionId = "b0b43a39-920c-475b-b34c-32ecc2bbb0ea";",
          -                " * String servicePrincipalId = "169d6a86-61b3-4615-ac7e-2da09edfeed4";",
          -                " * KeyVaultRoleAssignment roleAssignment =",
          -                " *     keyVaultAccessControlClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinitionId,",
          -                " *         servicePrincipalId);",
          -                " *",
          -                " * System.out.printf("Created role assignment with randomly generated name '%s' for principal with id '%s'.%n",",
          -                " *     roleAssignment.getName(), roleAssignment.getProperties().getPrincipalId());",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Get a Role Definition

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient} can be used to retrieve a role", - " * definition from the key vault.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to asynchronously retrieve a role definition from the key vault, using", - " * the", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient#getRoleDefinition(com.azure.security.keyvault.administration.models.KeyVaultRoleScope, java.lang.String) KeyVaultAccessControlClient.getRoleDefinition(KeyVaultRoleScope, String)}", - " * API.

          ", - " *", - " * ", - " *
          ",
          -                " * String roleAssignmentName = "06d1ae8b-0791-4f02-b976-f631251f5a95";",
          -                " * KeyVaultRoleAssignment roleAssignment =",
          -                " *     keyVaultAccessControlClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName);",
          -                " *",
          -                " * System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName());",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Delete a Role Definition

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient} can be used to delete a role", - " * definition from an Azure Key Vault account.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to asynchronously delete a role definition from the key vault, using", - " * the", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlClient#deleteRoleDefinition(com.azure.security.keyvault.administration.models.KeyVaultRoleScope, java.lang.String) KeyVaultAccessControlClient.deleteRoleDefinition(KeyVaultRoleScope, String)}", - " * API.

          ", - " *", - " * ", - " *
          ",
          -                " * String roleAssignmentName = "c3ed874a-64a9-4a87-8581-2a1ad84b9ddb";",
          -                " *",
          -                " * keyVaultAccessControlClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName);",
          -                " *",
          -                " * System.out.printf("Deleted role assignment with name '%s'.%n", roleAssignmentName);",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Back Up a Collection of Keys

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultBackupClient} can be used to back up the entire", - " * collection of keys from a key vault.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to synchronously back up an entire collection of keys using, using the", - " * {@link com.azure.security.keyvault.administration.KeyVaultBackupClient#beginBackup(String, String)} API.

          ", - " *", - " * ", - " *
          ",
          -                " * String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer";",
          -                " * String sasToken = "sv=2020-02-10&ss=b&srt=o&sp=rwdlactfx&se=2021-06-17T07:13:07Z&st=2021-06-16T23:13:07Z"",
          -                " *     "&spr=https&sig=n5V6fnlkViEF9b7ij%2FttTHNwO2BdFIHKHppRxGAyJdc%3D";",
          -                " *",
          -                " * SyncPoller<KeyVaultBackupOperation, String> backupPoller = client.beginBackup(blobStorageUrl, sasToken);",
          -                " *",
          -                " * PollResponse<KeyVaultBackupOperation> pollResponse = backupPoller.poll();",
          -                " *",
          -                " * System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus());",
          -                " *",
          -                " * PollResponse<KeyVaultBackupOperation> finalPollResponse = backupPoller.waitForCompletion();",
          -                " *",
          -                " * if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) {",
          -                " *     String folderUrl = backupPoller.getFinalResult();",
          -                " *",
          -                " *     System.out.printf("Backup completed. The storage location of this backup is: %s.%n", folderUrl);",
          -                " * } else {",
          -                " *     KeyVaultBackupOperation operation = backupPoller.poll().getValue();",
          -                " *",
          -                " *     System.out.printf("Backup failed with error: %s.%n", operation.getError().getMessage());",
          -                " * }",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Restore a Collection of Keys

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultBackupClient} can be used to restore an entire", - " * collection of keys from a backup.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to synchronously restore an entire collection of keys from a backup,", - " * using the {@link com.azure.security.keyvault.administration.KeyVaultBackupClient#beginRestore(String, String)}", - " * API.

          ", - " *", - " * ", - " *
          ",
          -                " * String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313";",
          -                " * String sasToken = "sv=2020-02-10&ss=b&srt=o&sp=rwdlactfx&se=2021-06-17T07:13:07Z&st=2021-06-16T23:13:07Z"",
          -                " *     "&spr=https&sig=n5V6fnlkViEF9b7ij%2FttTHNwO2BdFIHKHppRxGAyJdc%3D";",
          -                " *",
          -                " * SyncPoller<KeyVaultRestoreOperation, KeyVaultRestoreResult> backupPoller =",
          -                " *     client.beginRestore(folderUrl, sasToken);",
          -                " *",
          -                " * PollResponse<KeyVaultRestoreOperation> pollResponse = backupPoller.poll();",
          -                " *",
          -                " * System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus());",
          -                " *",
          -                " * PollResponse<KeyVaultRestoreOperation> finalPollResponse = backupPoller.waitForCompletion();",
          -                " *",
          -                " * if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) {",
          -                " *     System.out.printf("Backup restored successfully.%n");",
          -                " * } else {",
          -                " *     KeyVaultRestoreOperation operation = backupPoller.poll().getValue();",
          -                " *",
          -                " *     System.out.printf("Restore failed with error: %s.%n", operation.getError().getMessage());",
          -                " * }",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Selectively Restore a Key

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultBackupClient} can be used to restore a specific key", - " * from a backup.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to synchronously restore a specific key from a backup, using", - " * the", - " * {@link com.azure.security.keyvault.administration.KeyVaultBackupClient#beginSelectiveKeyRestore(String, String, String)}", - " * API.

          ", - " *", - " * ", - " *
          ",
          -                " * String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313";",
          -                " * String sasToken = "sv=2020-02-10&ss=b&srt=o&sp=rwdlactfx&se=2021-06-17T07:13:07Z&st=2021-06-16T23:13:07Z"",
          -                " *     "&spr=https&sig=n5V6fnlkViEF9b7ij%2FttTHNwO2BdFIHKHppRxGAyJdc%3D";",
          -                " * String keyName = "myKey";",
          -                " *",
          -                " * SyncPoller<KeyVaultSelectiveKeyRestoreOperation, KeyVaultSelectiveKeyRestoreResult> backupPoller =",
          -                " *     client.beginSelectiveKeyRestore(folderUrl, sasToken, keyName);",
          -                " *",
          -                " * PollResponse<KeyVaultSelectiveKeyRestoreOperation> pollResponse = backupPoller.poll();",
          -                " *",
          -                " * System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus());",
          -                " *",
          -                " * PollResponse<KeyVaultSelectiveKeyRestoreOperation> finalPollResponse = backupPoller.waitForCompletion();",
          -                " *",
          -                " * if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) {",
          -                " *     System.out.printf("Key restored successfully.%n");",
          -                " * } else {",
          -                " *     KeyVaultSelectiveKeyRestoreOperation operation = backupPoller.poll().getValue();",
          -                " *",
          -                " *     System.out.printf("Key restore failed with error: %s.%n", operation.getError().getMessage());",
          -                " * }",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Get All Settings

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultSettingsClient} can be used to list all the settings", - " * for an Azure Key Vault account.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to synchronously back up an entire collection of keys using, using the", - " * {@link com.azure.security.keyvault.administration.KeyVaultSettingsClient#getSettings()} API.

          ", - " *", - " * ", - " *
          ",
          -                " * KeyVaultGetSettingsResult getSettingsResult = keyVaultSettingsClient.getSettings();",
          -                " * List<KeyVaultSetting> settings = getSettingsResult.getSettings();",
          -                " *",
          -                " * settings.forEach(setting ->",
          -                " *     System.out.printf("Retrieved setting with name '%s' and value %s'.%n", setting.getName(),",
          -                " *         setting.asBoolean()));",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Retrieve a Specific Setting

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultSettingsClient} can be used to retrieve a specific", - " * setting.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to synchronously restore an entire collection of keys from a backup,", - " * using the {@link com.azure.security.keyvault.administration.KeyVaultSettingsClient#getSetting(String)} API.

          ", - " *", - " * ", - " *
          ",
          -                " * KeyVaultSetting setting = keyVaultSettingsClient.getSetting(settingName);",
          -                " *",
          -                " * System.out.printf("Retrieved setting '%s' with value '%s'.%n", setting.getName(), setting.asBoolean());",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " *

          Update a Specific Setting

          ", - " * The {@link com.azure.security.keyvault.administration.KeyVaultSettingsClient} can be used to restore a specific key", - " * from a backup.", - " *", - " *

          Code Sample:

          ", - " *

          The following code sample demonstrates how to synchronously restore a specific key from a backup, using", - " * the", - " * {@link com.azure.security.keyvault.administration.KeyVaultSettingsClient#updateSetting(com.azure.security.keyvault.administration.models.KeyVaultSetting) KeyVaultSettingsClient.updateSetting(KeyVaultSetting)}", - " *", - " * ", - " *

          ",
          -                " * KeyVaultSetting settingToUpdate = new KeyVaultSetting(settingName, true);",
          -                " * KeyVaultSetting updatedSetting = keyVaultSettingsClient.updateSetting(settingToUpdate);",
          -                " *",
          -                " * System.out.printf("Updated setting '%s' to '%s'.%n", updatedSetting.getName(), updatedSetting.asBoolean());",
          -                " * 
          ", - " * ", - " *", - " *

          Note: For the asynchronous sample, refer to", - " * {@link com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient}.

          ", - " *", - " *
          ", - " *", - " *
          ", - " *", - " * @see com.azure.security.keyvault.administration.KeyVaultAccessControlClient", - " * @see com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient", - " * @see com.azure.security.keyvault.administration.KeyVaultAccessControlClientBuilder", - " * @see com.azure.security.keyvault.administration.KeyVaultBackupClient", - " * @see com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient", - " * @see com.azure.security.keyvault.administration.KeyVaultBackupClientBuilder", - " * @see com.azure.security.keyvault.administration.KeyVaultSettingsClient", - " * @see com.azure.security.keyvault.administration.KeyVaultSettingsAsyncClient", - " * @see com.azure.security.keyvault.administration.KeyVaultSettingsClientBuilder", - " */", - "package com.azure.security.keyvault.administration;", - "" - )); - - editor.replaceFile("src/main/java/com/azure/security/keyvault/administration/models/package-info.java", - joinWithNewline( - "// Copyright (c) Microsoft Corporation. All rights reserved.", - "// Licensed under the MIT License.", - "// Code generated by Microsoft (R) AutoRest Code Generator.", - "", - "/**", - " * Package containing classes used by {@link", - " * com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient} and {@link", - " * com.azure.security.keyvault.administration.KeyVaultAccessControlClient} to perform access control operations on Azure", - " * Key Vault resources, as well as classes used by {@link", - " * com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient} and {@link", - " * com.azure.security.keyvault.administration.KeyVaultBackupClient} to perform backup and restore operations on Azure", - " * Key Vault keys.", - " */", - "package com.azure.security.keyvault.administration.models;", - "" - )); - - editor.replaceFile("src/main/java/com/azure/security/keyvault/administration/implementation/package-info.java", - joinWithNewline( - "// 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 KeyVaultAccessControlClient, KeyVaultBackupClient, and", - " * KeyVaultSettingsClient. The key vault client performs cryptographic key operations and vault operations against the", - " * Key Vault service.", - " */", - "package com.azure.security.keyvault.administration.implementation;", - "" - )); - - editor.replaceFile("src/main/java/com/azure/security/keyvault/administration/implementation/models/package-info.java", - joinWithNewline( - "// 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 KeyVaultAccessControlClient, KeyVaultBackupClient, and KeyVaultSettingsClient.", - " * The key vault client performs cryptographic key operations and vault operations against the Key Vault service.", - " */", - "package com.azure.security.keyvault.administration.implementation.models;", - "" - )); - } - - private static String joinWithNewline(String... lines) { - return String.join("\n", lines); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-administration/tsp-location.yaml b/sdk/keyvault/azure-security-keyvault-administration/tsp-location.yaml new file mode 100644 index 000000000000..9ac5ab99988b --- /dev/null +++ b/sdk/keyvault/azure-security-keyvault-administration/tsp-location.yaml @@ -0,0 +1,9 @@ +directory: specification/keyvault/Security.KeyVault.Administration +commit: 70672ea0a1a550ee608aa4718598b71550d361df +repo: Azure/azure-rest-api-specs +additionalDirectories: +- specification/keyvault/Security.KeyVault.BackupRestore/ +- specification/keyvault/Security.KeyVault.Common/ +- specification/keyvault/Security.KeyVault.RBAC/ +- specification/keyvault/Security.KeyVault.Settings/ +cleanup: true diff --git a/sdk/keyvault/azure-security-keyvault-certificates/CHANGELOG.md b/sdk/keyvault/azure-security-keyvault-certificates/CHANGELOG.md index 19bfd96f1856..3d1bbbc67903 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/CHANGELOG.md +++ b/sdk/keyvault/azure-security-keyvault-certificates/CHANGELOG.md @@ -10,6 +10,21 @@ ### Other Changes +## 4.7.3 (2025-03-04) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. +- Upgraded `azure-json` from `1.3.0` to version `1.4.0`. +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`. + +## 4.7.2 (2025-01-14) + +### Bugs Fixed +- Fixed issue where certain `toString()` calls could cause a `NullPointerException`. ([#43776](https://github.com/Azure/azure-sdk-for-java/pull/43776)) + ## 4.7.1 (2024-12-04) ### Other Changes diff --git a/sdk/keyvault/azure-security-keyvault-certificates/README.md b/sdk/keyvault/azure-security-keyvault-certificates/README.md index 64578ec4fe3d..66b1267d96f9 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/README.md +++ b/sdk/keyvault/azure-security-keyvault-certificates/README.md @@ -43,7 +43,7 @@ If you want to take dependency on a particular version of the library that is no com.azure azure-security-keyvault-certificates - 4.7.0 + 4.8.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -287,4 +287,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][microsoft_c [http_clients_wiki]: https://learn.microsoft.com/azure/developer/java/sdk/http-client-pipeline#http-clients [microsoft_code_of_conduct]: https://opensource.microsoft.com/codeofconduct/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fkeyvault%2Fazure-security-keyvault-certificates%2FREADME.png) + diff --git a/sdk/keyvault/azure-security-keyvault-certificates/assets.json b/sdk/keyvault/azure-security-keyvault-certificates/assets.json index 7235a61b39fc..844a429cde24 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/assets.json +++ b/sdk/keyvault/azure-security-keyvault-certificates/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "java", "TagPrefix": "java/keyvault/azure-security-keyvault-certificates", - "Tag": "java/keyvault/azure-security-keyvault-certificates_e018897fab" + "Tag": "java/keyvault/azure-security-keyvault-certificates_f79afcd807" } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/checkstyle-suppressions.xml b/sdk/keyvault/azure-security-keyvault-certificates/checkstyle-suppressions.xml index 5c4942a1773d..a8c684ad9237 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/checkstyle-suppressions.xml +++ b/sdk/keyvault/azure-security-keyvault-certificates/checkstyle-suppressions.xml @@ -3,6 +3,7 @@ + diff --git a/sdk/keyvault/azure-security-keyvault-certificates/pom.xml b/sdk/keyvault/azure-security-keyvault-certificates/pom.xml index 3a6f821ea902..e03e71e711af 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/pom.xml +++ b/sdk/keyvault/azure-security-keyvault-certificates/pom.xml @@ -51,31 +51,31 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/keyvault/azure-security-keyvault-certificates/spotbugs-exclude.xml b/sdk/keyvault/azure-security-keyvault-certificates/spotbugs-exclude.xml index 4c1d8e4609b6..81d4f396414a 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/spotbugs-exclude.xml +++ b/sdk/keyvault/azure-security-keyvault-certificates/spotbugs-exclude.xml @@ -20,6 +20,8 @@ + + @@ -59,6 +61,7 @@ + diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/CertificateAsyncClient.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/CertificateAsyncClient.java index 826e0b66ab37..9eac01c0fd6f 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/CertificateAsyncClient.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/CertificateAsyncClient.java @@ -13,8 +13,10 @@ import com.azure.core.http.rest.PagedFlux; import com.azure.core.http.rest.PagedResponse; import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.RequestOptions; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.BinaryData; import com.azure.core.util.FluxUtil; import com.azure.core.util.logging.ClientLogger; import com.azure.core.util.polling.LongRunningOperationStatus; @@ -29,13 +31,23 @@ import com.azure.security.keyvault.certificates.implementation.DeletedCertificateHelper; import com.azure.security.keyvault.certificates.implementation.IssuerPropertiesHelper; import com.azure.security.keyvault.certificates.implementation.KeyVaultCertificateWithPolicyHelper; +import com.azure.security.keyvault.certificates.implementation.models.BackupCertificateResult; import com.azure.security.keyvault.certificates.implementation.models.CertificateAttributes; +import com.azure.security.keyvault.certificates.implementation.models.CertificateBundle; +import com.azure.security.keyvault.certificates.implementation.models.CertificateCreateParameters; +import com.azure.security.keyvault.certificates.implementation.models.CertificateImportParameters; import com.azure.security.keyvault.certificates.implementation.models.CertificateIssuerItem; +import com.azure.security.keyvault.certificates.implementation.models.CertificateIssuerSetParameters; +import com.azure.security.keyvault.certificates.implementation.models.CertificateIssuerUpdateParameters; import com.azure.security.keyvault.certificates.implementation.models.CertificateItem; +import com.azure.security.keyvault.certificates.implementation.models.CertificateMergeParameters; +import com.azure.security.keyvault.certificates.implementation.models.CertificateOperationUpdateParameter; +import com.azure.security.keyvault.certificates.implementation.models.CertificateRestoreParameters; +import com.azure.security.keyvault.certificates.implementation.models.CertificateUpdateParameters; import com.azure.security.keyvault.certificates.implementation.models.Contacts; +import com.azure.security.keyvault.certificates.implementation.models.DeletedCertificateBundle; import com.azure.security.keyvault.certificates.implementation.models.DeletedCertificateItem; import com.azure.security.keyvault.certificates.implementation.models.IssuerBundle; -import com.azure.security.keyvault.certificates.implementation.models.KeyVaultErrorException; import com.azure.security.keyvault.certificates.models.CertificateContact; import com.azure.security.keyvault.certificates.models.CertificateContentType; import com.azure.security.keyvault.certificates.models.CertificateIssuer; @@ -63,13 +75,13 @@ import java.util.function.Function; import static com.azure.core.util.FluxUtil.monoError; +import static com.azure.core.util.FluxUtil.pagedFluxError; import static com.azure.security.keyvault.certificates.implementation.CertificateIssuerHelper.createCertificateIssuer; import static com.azure.security.keyvault.certificates.implementation.CertificateIssuerHelper.getIssuerBundle; import static com.azure.security.keyvault.certificates.implementation.CertificateOperationHelper.createCertificateOperation; import static com.azure.security.keyvault.certificates.implementation.CertificatePolicyHelper.createCertificatePolicy; import static com.azure.security.keyvault.certificates.implementation.CertificatePolicyHelper.getImplCertificatePolicy; import static com.azure.security.keyvault.certificates.implementation.DeletedCertificateHelper.createDeletedCertificate; -import static com.azure.security.keyvault.certificates.implementation.IssuerPropertiesHelper.createIssuerProperties; import static com.azure.security.keyvault.certificates.implementation.KeyVaultCertificateWithPolicyHelper.createCertificateWithPolicy; /** @@ -194,6 +206,7 @@ serviceInterfaces = CertificateClientImpl.CertificateClientService.class) public final class CertificateAsyncClient { private static final ClientLogger LOGGER = new ClientLogger(CertificateAsyncClient.class); + static final RequestOptions EMPTY_OPTIONS = new RequestOptions(); private final CertificateClientImpl implClient; private final String vaultUrl; @@ -261,52 +274,79 @@ HttpPipeline getHttpPipeline() { @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) public PollerFlux beginCreateCertificate( String certificateName, CertificatePolicy policy, Boolean isEnabled, Map tags) { - if (policy == null) { - return PollerFlux.error(LOGGER.logExceptionAsError(new NullPointerException("'policy' cannot be null."))); - } - return new PollerFlux<>(Duration.ofSeconds(1), - ignored -> createCertificateActivation(certificateName, policy, isEnabled, tags), - ignored -> certificatePollOperation(certificateName), - (ignored1, ignored2) -> certificateCancellationOperation(certificateName), - ignored -> fetchCertificateOperation(certificateName)); + try { + if (policy == null) { + return PollerFlux + .error(LOGGER.logExceptionAsError(new NullPointerException("'policy' cannot be null."))); + } + + return new PollerFlux<>(Duration.ofSeconds(1), + ignored -> createCertificateActivation(certificateName, policy, isEnabled, tags), + ignored -> certificatePollOperation(certificateName), + (ignored1, ignored2) -> certificateCancellationOperation(certificateName), + ignored -> fetchCertificateOperation(certificateName)); + } catch (RuntimeException e) { + return PollerFlux.error(e); + } } private Mono createCertificateActivation(String certificateName, CertificatePolicy policy, Boolean isEnabled, Map tags) { - com.azure.security.keyvault.certificates.implementation.models.CertificatePolicy implPolicy - = CertificatePolicyHelper.getImplCertificatePolicy(policy); - return implClient - .createCertificateAsync(vaultUrl, certificateName, implPolicy, - new CertificateAttributes().setEnabled(isEnabled), tags) - .onErrorMap(KeyVaultErrorException.class, CertificateAsyncClient::mapCreateCertificateException) - .map(CertificateOperationHelper::createCertificateOperation); + + CertificateCreateParameters certificateCreateParameters = new CertificateCreateParameters() + .setCertificatePolicy(CertificatePolicyHelper.getImplCertificatePolicy(policy)) + .setCertificateAttributes(new CertificateAttributes().setEnabled(isEnabled)) + .setTags(tags); + + try { + return implClient + .createCertificateWithResponseAsync(certificateName, BinaryData.fromObject(certificateCreateParameters), + EMPTY_OPTIONS) + .onErrorMap(HttpResponseException.class, CertificateAsyncClient::mapCreateCertificateException) + .flatMap(FluxUtil::toMono) + .map(binaryData -> CertificateOperationHelper.createCertificateOperation(binaryData.toObject( + com.azure.security.keyvault.certificates.implementation.models.CertificateOperation.class))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); + } } - static HttpResponseException mapCreateCertificateException(KeyVaultErrorException ex) { - return ex.getResponse().getStatusCode() == 400 - ? new ResourceModifiedException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; + /** + * Maps a {@link HttpResponseException} to a {@link ResourceModifiedException} when the status code is 400. + * + * @param e The {@link HttpResponseException} to map. + * @return A {@link ResourceModifiedException} created from the {@link HttpResponseException}. + */ + static HttpResponseException mapCreateCertificateException(HttpResponseException e) { + return e.getResponse().getStatusCode() == 400 + ? new ResourceModifiedException(e.getMessage(), e.getResponse(), e.getValue()) + : e; } private Mono> certificatePollOperation(String certificateName) { - return implClient.getCertificateOperationAsync(vaultUrl, certificateName) - .onErrorMap(KeyVaultErrorException.class, CertificateAsyncClient::mapGetCertificateOperationException) - .map(CertificateAsyncClient::processCertificateOperationResponse); - } - - static HttpResponseException mapGetCertificateOperationException(KeyVaultErrorException ex) { - if (ex.getResponse().getStatusCode() == 404) { - return new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()); - } else if (ex.getResponse().getStatusCode() == 400) { - return new ResourceModifiedException(ex.getMessage(), ex.getResponse(), ex.getValue()); - } else { - return ex; - } + return implClient.getCertificateOperationWithResponseAsync(certificateName, EMPTY_OPTIONS) + .onErrorMap(HttpResponseException.class, CertificateAsyncClient::mapGetCertificateOperationException) + .flatMap(FluxUtil::toMono) + .map(binaryData -> CertificateAsyncClient.processCertificateOperationResponse(binaryData + .toObject(com.azure.security.keyvault.certificates.implementation.models.CertificateOperation.class))); + } + + /** + * Maps a {@link HttpResponseException} to a {@link ResourceModifiedException} when the status code is 400. + * + * @param e The {@link HttpResponseException} to map. + * @return A {@link ResourceModifiedException} created from the {@link HttpResponseException}. + */ + static HttpResponseException mapGetCertificateOperationException(HttpResponseException e) { + return e.getResponse().getStatusCode() == 400 + ? new ResourceModifiedException(e.getMessage(), e.getResponse(), e.getValue()) + : e; } static PollResponse processCertificateOperationResponse( com.azure.security.keyvault.certificates.implementation.models.CertificateOperation impl) { + return new PollResponse<>(mapStatus(impl.getStatus()), CertificateOperationHelper.createCertificateOperation(impl)); } @@ -328,35 +368,36 @@ private static LongRunningOperationStatus mapStatus(String status) { } private Mono certificateCancellationOperation(String certificateName) { - return implClient.updateCertificateOperationAsync(vaultUrl, certificateName, true) - .onErrorMap(KeyVaultErrorException.class, CertificateAsyncClient::mapUpdateCertificateOperationException) - .map(CertificateOperationHelper::createCertificateOperation); - } - - static HttpResponseException mapUpdateCertificateOperationException(KeyVaultErrorException ex) { - if (ex.getResponse().getStatusCode() == 404) { - return new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()); - } else if (ex.getResponse().getStatusCode() == 400) { - return new ResourceModifiedException(ex.getMessage(), ex.getResponse(), ex.getValue()); - } else { - return ex; - } + CertificateOperationUpdateParameter certificateOperationUpdateParameter + = new CertificateOperationUpdateParameter(true); + + return implClient + .updateCertificateOperationWithResponseAsync(certificateName, + BinaryData.fromObject(certificateOperationUpdateParameter), EMPTY_OPTIONS) + .onErrorMap(HttpResponseException.class, CertificateAsyncClient::mapUpdateCertificateOperationException) + .flatMap(FluxUtil::toMono) + .map(binaryData -> CertificateOperationHelper.createCertificateOperation(binaryData + .toObject(com.azure.security.keyvault.certificates.implementation.models.CertificateOperation.class))); + } + + static HttpResponseException mapUpdateCertificateOperationException(HttpResponseException e) { + return e.getResponse().getStatusCode() == 400 + ? new ResourceModifiedException(e.getMessage(), e.getResponse(), e.getValue()) + : e; } private Mono fetchCertificateOperation(String certificateName) { - return implClient.getCertificateAsync(vaultUrl, certificateName, null) - .onErrorMap(KeyVaultErrorException.class, CertificateAsyncClient::mapGetCertificateException) - .map(KeyVaultCertificateWithPolicyHelper::createCertificateWithPolicy); - } - - static HttpResponseException mapGetCertificateException(KeyVaultErrorException ex) { - if (ex.getResponse().getStatusCode() == 404) { - return new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()); - } else if (ex.getResponse().getStatusCode() == 403) { - return new ResourceModifiedException(ex.getMessage(), ex.getResponse(), ex.getValue()); - } else { - return ex; - } + return implClient.getCertificateWithResponseAsync(certificateName, null, EMPTY_OPTIONS) + .onErrorMap(HttpResponseException.class, CertificateAsyncClient::mapGetCertificateException) + .flatMap(FluxUtil::toMono) + .map(binaryData -> KeyVaultCertificateWithPolicyHelper + .createCertificateWithPolicy(binaryData.toObject(CertificateBundle.class))); + } + + static HttpResponseException mapGetCertificateException(HttpResponseException e) { + return e.getResponse().getStatusCode() == 403 + ? new ResourceModifiedException(e.getMessage(), e.getResponse(), e.getValue()) + : e; } /** @@ -390,6 +431,7 @@ static HttpResponseException mapGetCertificateException(KeyVaultErrorException e @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) public PollerFlux beginCreateCertificate(String certificateName, CertificatePolicy policy) { + return beginCreateCertificate(certificateName, policy, true, null); } @@ -422,10 +464,15 @@ static HttpResponseException mapGetCertificateException(KeyVaultErrorException e @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) public PollerFlux getCertificateOperation(String certificateName) { - return new PollerFlux<>(Duration.ofSeconds(1), pollingContext -> Mono.empty(), - ignored -> certificatePollOperation(certificateName), - (ignored1, ignored2) -> certificateCancellationOperation(certificateName), - ignored -> fetchCertificateOperation(certificateName)); + + try { + return new PollerFlux<>(Duration.ofSeconds(1), pollingContext -> Mono.empty(), + ignored -> certificatePollOperation(certificateName), + (ignored1, ignored2) -> certificateCancellationOperation(certificateName), + ignored -> fetchCertificateOperation(certificateName)); + } catch (RuntimeException e) { + return PollerFlux.error(e); + } } /** @@ -484,11 +531,12 @@ public Mono getCertificate(String certificateName @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getCertificateWithResponse(String certificateName) { try { - return implClient.getCertificateWithResponseAsync(vaultUrl, certificateName, null) - .onErrorMap(KeyVaultErrorException.class, CertificateAsyncClient::mapGetCertificateException) - .map(response -> new SimpleResponse<>(response, createCertificateWithPolicy(response.getValue()))); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + return implClient.getCertificateWithResponseAsync(certificateName, null, EMPTY_OPTIONS) + .onErrorMap(HttpResponseException.class, CertificateAsyncClient::mapGetCertificateException) + .map(response -> new SimpleResponse<>(response, + createCertificateWithPolicy(response.getValue().toObject(CertificateBundle.class)))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); } } @@ -523,12 +571,14 @@ public Mono> getCertificateWithResponse( @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getCertificateVersionWithResponse(String certificateName, String version) { + try { - return implClient.getCertificateWithResponseAsync(vaultUrl, certificateName, version) - .onErrorMap(KeyVaultErrorException.class, CertificateAsyncClient::mapGetCertificateException) - .map(response -> new SimpleResponse<>(response, createCertificateWithPolicy(response.getValue()))); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + return implClient.getCertificateWithResponseAsync(certificateName, version, EMPTY_OPTIONS) + .onErrorMap(HttpResponseException.class, CertificateAsyncClient::mapGetCertificateException) + .map(response -> new SimpleResponse<>(response, + createCertificateWithPolicy(response.getValue().toObject(CertificateBundle.class)))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); } } @@ -637,6 +687,7 @@ public Mono updateCertificateProperties(CertificateProperti @ServiceMethod(returns = ReturnType.SINGLE) public Mono> updateCertificatePropertiesWithResponse(CertificateProperties properties) { + if (properties == null) { return monoError(LOGGER, new NullPointerException("'properties' cannot be null.")); } @@ -646,12 +697,17 @@ public Mono updateCertificateProperties(CertificateProperti .setExpires(properties.getExpiresOn()) .setNotBefore(properties.getNotBefore()); + CertificateUpdateParameters certificateUpdateParameters + = new CertificateUpdateParameters().setCertificateAttributes(certificateAttributes) + .setTags(properties.getTags()); + return implClient - .updateCertificateWithResponseAsync(vaultUrl, properties.getName(), properties.getVersion(), null, - certificateAttributes, properties.getTags()) - .map(response -> new SimpleResponse<>(response, createCertificateWithPolicy(response.getValue()))); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + .updateCertificateWithResponseAsync(properties.getName(), properties.getVersion(), + BinaryData.fromObject(certificateUpdateParameters), EMPTY_OPTIONS) + .map(response -> new SimpleResponse<>(response, + createCertificateWithPolicy(response.getValue().toObject(CertificateBundle.class)))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); } } @@ -684,30 +740,36 @@ public Mono updateCertificateProperties(CertificateProperti */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) public PollerFlux beginDeleteCertificate(String certificateName) { - return new PollerFlux<>(Duration.ofSeconds(1), ignored -> deleteCertificateActivation(certificateName), - pollingContext -> deleteCertificatePollOperation(certificateName, pollingContext), - (pollingContext, firstResponse) -> Mono.empty(), pollingContext -> Mono.empty()); + try { + return new PollerFlux<>(Duration.ofSeconds(1), ignored -> deleteCertificateActivation(certificateName), + pollingContext -> deleteCertificatePollOperation(certificateName, pollingContext), + (pollingContext, firstResponse) -> Mono.empty(), pollingContext -> Mono.empty()); + } catch (RuntimeException e) { + return PollerFlux.error(e); + } } private Mono deleteCertificateActivation(String certificateName) { - return implClient.deleteCertificateAsync(vaultUrl, certificateName) - .onErrorMap(KeyVaultErrorException.class, CertificateAsyncClient::mapDeleteCertificateException) - .map(DeletedCertificateHelper::createDeletedCertificate); + return implClient.deleteCertificateWithResponseAsync(certificateName, EMPTY_OPTIONS) + .flatMap(FluxUtil::toMono) + .map(binaryData -> DeletedCertificateHelper + .createDeletedCertificate(binaryData.toObject(DeletedCertificateBundle.class))); } - static HttpResponseException mapDeleteCertificateException(KeyVaultErrorException ex) { - return ex.getResponse().getStatusCode() == 404 - ? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; + static HttpResponseException mapDeleteCertificateException(HttpResponseException e) { + return e.getResponse().getStatusCode() == 404 + ? new ResourceNotFoundException(e.getMessage(), e.getResponse(), e.getValue()) + : e; } private Mono> deleteCertificatePollOperation(String certificateName, PollingContext pollingContext) { - return implClient.getDeletedCertificateAsync(vaultUrl, certificateName) - .map(bundle -> new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, - createDeletedCertificate(bundle))) - .onErrorResume(KeyVaultErrorException.class, ex -> { - if (ex.getResponse().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { + return implClient.getDeletedCertificateWithResponseAsync(certificateName, EMPTY_OPTIONS) + .flatMap(FluxUtil::toMono) + .map(binaryData -> new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, + createDeletedCertificate(binaryData.toObject(DeletedCertificateBundle.class)))) + .onErrorResume(HttpResponseException.class, e -> { + if (e.getResponse().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { return Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue())); } else { @@ -783,20 +845,14 @@ public Mono getDeletedCertificate(String certificateName) { @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getDeletedCertificateWithResponse(String certificateName) { try { - return implClient.getDeletedCertificateWithResponseAsync(vaultUrl, certificateName) - .onErrorMap(KeyVaultErrorException.class, CertificateAsyncClient::mapGetDeletedCertificateException) - .map(response -> new SimpleResponse<>(response, createDeletedCertificate(response.getValue()))); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + return implClient.getDeletedCertificateWithResponseAsync(certificateName, EMPTY_OPTIONS) + .map(response -> new SimpleResponse<>(response, + createDeletedCertificate(response.getValue().toObject(DeletedCertificateBundle.class)))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); } } - static HttpResponseException mapGetDeletedCertificateException(KeyVaultErrorException ex) { - return ex.getResponse().getStatusCode() == 404 - ? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; - } - /** * Permanently deletes the specified deleted certificate without possibility for recovery. The Purge Deleted * Certificate operation is applicable for soft-delete enabled vaults and is not available if the recovery level @@ -851,19 +907,12 @@ public Mono purgeDeletedCertificate(String certificateName) { @ServiceMethod(returns = ReturnType.SINGLE) public Mono> purgeDeletedCertificateWithResponse(String certificateName) { try { - return implClient.purgeDeletedCertificateWithResponseAsync(vaultUrl, certificateName) - .onErrorMap(KeyVaultErrorException.class, CertificateAsyncClient::mapPurgeDeletedCertificateException); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + return implClient.purgeDeletedCertificateWithResponseAsync(certificateName, EMPTY_OPTIONS); + } catch (RuntimeException e) { + return monoError(LOGGER, e); } } - static HttpResponseException mapPurgeDeletedCertificateException(KeyVaultErrorException ex) { - return ex.getResponse().getStatusCode() == 404 - ? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; - } - /** * Recovers the deleted certificate back to its current version under /certificates and can only be performed on a * soft-delete enabled vault. The RecoverDeletedCertificate operation performs the reversal of the Delete operation @@ -899,24 +948,24 @@ public PollerFlux beginRecoverDeletedCertif } private Mono recoverDeletedCertificateActivation(String certificateName) { - return implClient.recoverDeletedCertificateAsync(vaultUrl, certificateName) - .onErrorMap(KeyVaultErrorException.class, CertificateAsyncClient::mapRecoverDeletedCertificateException) - .map(KeyVaultCertificateWithPolicyHelper::createCertificateWithPolicy); - } - - static HttpResponseException mapRecoverDeletedCertificateException(KeyVaultErrorException ex) { - return ex.getResponse().getStatusCode() == 404 - ? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; + try { + return implClient.recoverDeletedCertificateWithResponseAsync(certificateName, EMPTY_OPTIONS) + .flatMap(FluxUtil::toMono) + .map(binaryData -> KeyVaultCertificateWithPolicyHelper + .createCertificateWithPolicy(binaryData.toObject(CertificateBundle.class))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); + } } private Mono> recoverDeletedCertificatePollOperation( String certificateName, PollingContext pollingContext) { - return implClient.getCertificateAsync(vaultUrl, certificateName, null) - .map(bundle -> new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, - createCertificateWithPolicy(bundle))) - .onErrorResume(KeyVaultErrorException.class, ex -> { - if (ex.getResponse().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { + return implClient.getCertificateWithResponseAsync(certificateName, null, EMPTY_OPTIONS) + .flatMap(FluxUtil::toMono) + .map(binaryData -> new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, + createCertificateWithPolicy(binaryData.toObject(CertificateBundle.class)))) + .onErrorResume(HttpResponseException.class, e -> { + if (e.getResponse().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { return Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue())); } else { @@ -988,20 +1037,14 @@ public Mono backupCertificate(String certificateName) { @ServiceMethod(returns = ReturnType.SINGLE) public Mono> backupCertificateWithResponse(String certificateName) { try { - return implClient.backupCertificateWithResponseAsync(vaultUrl, certificateName) - .onErrorMap(KeyVaultErrorException.class, CertificateAsyncClient::mapBackupCertificateException) - .map(response -> new SimpleResponse<>(response, response.getValue().getValue())); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + return implClient.backupCertificateWithResponseAsync(certificateName, EMPTY_OPTIONS) + .map(response -> new SimpleResponse<>(response, + response.getValue().toObject(BackupCertificateResult.class).getValue())); + } catch (RuntimeException e) { + return monoError(LOGGER, e); } } - static HttpResponseException mapBackupCertificateException(KeyVaultErrorException ex) { - return ex.getResponse().getStatusCode() == 404 - ? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; - } - /** * Restores a backed up certificate to the vault. All the versions of the certificate are restored to the vault. * This operation requires the certificates/restore permission. @@ -1055,18 +1098,22 @@ public Mono restoreCertificateBackup(byte[] backu @ServiceMethod(returns = ReturnType.SINGLE) public Mono> restoreCertificateBackupWithResponse(byte[] backup) { try { - return implClient.restoreCertificateWithResponseAsync(vaultUrl, backup) - .onErrorMap(KeyVaultErrorException.class, CertificateAsyncClient::mapRestoreCertificateException) - .map(response -> new SimpleResponse<>(response, createCertificateWithPolicy(response.getValue()))); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + CertificateRestoreParameters certificateRestoreParameters = new CertificateRestoreParameters(backup); + + return implClient + .restoreCertificateWithResponseAsync(BinaryData.fromObject(certificateRestoreParameters), EMPTY_OPTIONS) + .onErrorMap(HttpResponseException.class, CertificateAsyncClient::mapRestoreCertificateException) + .map(response -> new SimpleResponse<>(response, + createCertificateWithPolicy(response.getValue().toObject(CertificateBundle.class)))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); } } - static HttpResponseException mapRestoreCertificateException(KeyVaultErrorException ex) { - return ex.getResponse().getStatusCode() == 400 - ? new ResourceModifiedException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; + static HttpResponseException mapRestoreCertificateException(HttpResponseException e) { + return e.getResponse().getStatusCode() == 400 + ? new ResourceModifiedException(e.getMessage(), e.getResponse(), e.getValue()) + : e; } /** @@ -1097,12 +1144,24 @@ static HttpResponseException mapRestoreCertificateException(KeyVaultErrorExcepti */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux listPropertiesOfCertificates(boolean includePending) { - return new PagedFlux<>( - maxResults -> implClient.getCertificatesSinglePageAsync(vaultUrl, maxResults, includePending) - .map(CertificateAsyncClient::mapCertificateItemPage), - (continuationToken, maxResults) -> implClient - .getCertificatesNextSinglePageAsync(continuationToken, vaultUrl) - .map(CertificateAsyncClient::mapCertificateItemPage)); + try { + RequestOptions requestOptions + = new RequestOptions().addQueryParam("includePending", String.valueOf(includePending), false); + + PagedFlux pagedFluxResponse = implClient.getCertificatesAsync(requestOptions); + + return PagedFlux.create(() -> (continuationTokenParam, pageSizeParam) -> { + Flux> pagedResponseFlux = (continuationTokenParam == null) + ? pagedFluxResponse.byPage().take(1) + : pagedFluxResponse.byPage(continuationTokenParam).take(1); + + return pagedResponseFlux + .map(pagedResponse -> mapPagedResponse(pagedResponse, binaryData -> CertificatePropertiesHelper + .createCertificateProperties(binaryData.toObject(CertificateItem.class)))); + }); + } catch (RuntimeException e) { + return pagedFluxError(LOGGER, e); + } } /** @@ -1183,16 +1242,24 @@ public PagedFlux listDeletedCertificates() { */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux listDeletedCertificates(boolean includePending) { - return new PagedFlux<>( - maxResults -> implClient.getDeletedCertificatesSinglePageAsync(vaultUrl, maxResults, includePending) - .map(CertificateAsyncClient::mapDeletedCertificateItemPage), - (continuationToken, maxResults) -> implClient - .getDeletedCertificatesNextSinglePageAsync(continuationToken, vaultUrl) - .map(CertificateAsyncClient::mapDeletedCertificateItemPage)); - } - - static PagedResponse mapDeletedCertificateItemPage(PagedResponse page) { - return mapPagedResponse(page, DeletedCertificateHelper::createDeletedCertificate); + try { + RequestOptions requestOptions + = new RequestOptions().addQueryParam("includePending", String.valueOf(includePending), false); + + PagedFlux pagedFluxResponse = implClient.getDeletedCertificatesAsync(requestOptions); + + return PagedFlux.create(() -> (continuationTokenParam, pageSizeParam) -> { + Flux> pagedResponseFlux = (continuationTokenParam == null) + ? pagedFluxResponse.byPage().take(1) + : pagedFluxResponse.byPage(continuationTokenParam).take(1); + + return pagedResponseFlux + .map(pagedResponse -> mapPagedResponse(pagedResponse, binaryData -> DeletedCertificateHelper + .createDeletedCertificate(binaryData.toObject(DeletedCertificateItem.class)))); + }); + } catch (RuntimeException e) { + return pagedFluxError(LOGGER, e); + } } /** @@ -1225,20 +1292,27 @@ static PagedResponse mapDeletedCertificateItemPage(PagedResp */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux listPropertiesOfCertificateVersions(String certificateName) { - return new PagedFlux<>( - maxResults -> implClient.getCertificateVersionsSinglePageAsync(vaultUrl, certificateName, maxResults) - .map(CertificateAsyncClient::mapCertificateItemPage), - (continuationToken, maxResults) -> implClient - .getCertificateVersionsNextSinglePageAsync(continuationToken, vaultUrl) - .map(CertificateAsyncClient::mapCertificateItemPage)); - } - - static PagedResponse mapCertificateItemPage(PagedResponse page) { - return mapPagedResponse(page, CertificatePropertiesHelper::createCertificateProperties); + try { + PagedFlux pagedFluxResponse + = implClient.getCertificateVersionsAsync(certificateName, EMPTY_OPTIONS); + + return PagedFlux.create(() -> (continuationTokenParam, pageSizeParam) -> { + Flux> pagedResponseFlux = (continuationTokenParam == null) + ? pagedFluxResponse.byPage().take(1) + : pagedFluxResponse.byPage(continuationTokenParam).take(1); + + return pagedResponseFlux + .map(pagedResponse -> mapPagedResponse(pagedResponse, binaryData -> CertificatePropertiesHelper + .createCertificateProperties(binaryData.toObject(CertificateItem.class)))); + }); + } catch (RuntimeException e) { + return pagedFluxError(LOGGER, e); + } } private static PagedResponse mapPagedResponse(PagedResponse page, Function itemMapper) { List mappedValues = new ArrayList<>(page.getValue().size()); + for (T item : page.getValue()) { mappedValues.add(itemMapper.apply(item)); } @@ -1304,19 +1378,25 @@ public Mono mergeCertificate(MergeCertificateOptions mergeC @ServiceMethod(returns = ReturnType.SINGLE) public Mono> mergeCertificateWithResponse(MergeCertificateOptions mergeCertificateOptions) { + if (mergeCertificateOptions == null) { return monoError(LOGGER, new NullPointerException("'mergeCertificateOptions' cannot be null.")); } try { + CertificateMergeParameters certificateMergeParameters + = new CertificateMergeParameters(mergeCertificateOptions.getX509Certificates()) + .setCertificateAttributes( + new CertificateAttributes().setEnabled(mergeCertificateOptions.isEnabled())) + .setTags(mergeCertificateOptions.getTags()); + return implClient - .mergeCertificateWithResponseAsync(vaultUrl, mergeCertificateOptions.getName(), - mergeCertificateOptions.getX509Certificates(), - new CertificateAttributes().setEnabled(mergeCertificateOptions.isEnabled()), - mergeCertificateOptions.getTags()) - .map(response -> new SimpleResponse<>(response, createCertificateWithPolicy(response.getValue()))); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + .mergeCertificateWithResponseAsync(mergeCertificateOptions.getName(), + BinaryData.fromObject(certificateMergeParameters), EMPTY_OPTIONS) + .map(response -> new SimpleResponse<>(response, + createCertificateWithPolicy(response.getValue().toObject(CertificateBundle.class)))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); } } @@ -1375,22 +1455,21 @@ public Mono getCertificatePolicy(String certificateName) { @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getCertificatePolicyWithResponse(String certificateName) { try { - return implClient.getCertificatePolicyWithResponseAsync(vaultUrl, certificateName) - .onErrorMap(KeyVaultErrorException.class, CertificateAsyncClient::mapGetCertificatePolicyException) - .map(response -> new SimpleResponse<>(response, createCertificatePolicy(response.getValue()))); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + return implClient.getCertificatePolicyWithResponseAsync(certificateName, EMPTY_OPTIONS) + .onErrorMap(HttpResponseException.class, CertificateAsyncClient::mapGetCertificatePolicyException) + .map(response -> new SimpleResponse<>(response, + createCertificatePolicy(response.getValue() + .toObject( + com.azure.security.keyvault.certificates.implementation.models.CertificatePolicy.class)))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); } } - static HttpResponseException mapGetCertificatePolicyException(KeyVaultErrorException ex) { - if (ex.getResponse().getStatusCode() == 404) { - return new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()); - } else if (ex.getResponse().getStatusCode() == 403) { - return new ResourceModifiedException(ex.getMessage(), ex.getResponse(), ex.getValue()); - } else { - return ex; - } + static HttpResponseException mapGetCertificatePolicyException(HttpResponseException e) { + return e.getResponse().getStatusCode() == 403 + ? new ResourceModifiedException(e.getMessage(), e.getResponse(), e.getValue()) + : e; } /** @@ -1467,26 +1546,27 @@ public Mono updateCertificatePolicy(String certificateName, C @ServiceMethod(returns = ReturnType.SINGLE) public Mono> updateCertificatePolicyWithResponse(String certificateName, CertificatePolicy policy) { + if (policy == null) { return monoError(LOGGER, new NullPointerException("'policy' cannot be null.")); } try { + CertificateUpdateParameters certificateUpdateParameters + = new CertificateUpdateParameters().setCertificatePolicy(getImplCertificatePolicy(policy)); + return implClient - .updateCertificatePolicyWithResponseAsync(vaultUrl, certificateName, getImplCertificatePolicy(policy)) - .onErrorMap(KeyVaultErrorException.class, CertificateAsyncClient::mapUpdateCertificatePolicyException) - .map(response -> new SimpleResponse<>(response, createCertificatePolicy(response.getValue()))); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + .updateCertificatePolicyWithResponseAsync(certificateName, + BinaryData.fromObject(certificateUpdateParameters), EMPTY_OPTIONS) + .map(response -> new SimpleResponse<>(response, + createCertificatePolicy(response.getValue() + .toObject( + com.azure.security.keyvault.certificates.implementation.models.CertificatePolicy.class)))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); } } - static HttpResponseException mapUpdateCertificatePolicyException(KeyVaultErrorException ex) { - return (ex.getResponse().getStatusCode() == 404) - ? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; - } - /** * Creates the specified certificate issuer. The SetCertificateIssuer operation updates the specified certificate * issuer if it already exists or adds it if it doesn't exist. This operation requires the certificates/setissuers @@ -1561,12 +1641,18 @@ public Mono> createIssuerWithResponse(CertificateIss try { IssuerBundle issuerBundle = getIssuerBundle(issuer); + CertificateIssuerSetParameters certificateIssuerSetParameters + = new CertificateIssuerSetParameters(issuer.getProvider()).setAttributes(issuerBundle.getAttributes()) + .setCredentials(issuerBundle.getCredentials()) + .setOrganizationDetails(issuerBundle.getOrganizationDetails()); + return implClient - .setCertificateIssuerWithResponseAsync(vaultUrl, issuer.getName(), issuer.getProvider(), - issuerBundle.getCredentials(), issuerBundle.getOrganizationDetails(), issuerBundle.getAttributes()) - .map(response -> new SimpleResponse<>(response, createCertificateIssuer(response.getValue()))); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + .setCertificateIssuerWithResponseAsync(issuer.getName(), + BinaryData.fromObject(certificateIssuerSetParameters), EMPTY_OPTIONS) + .map(response -> new SimpleResponse<>(response, + createCertificateIssuer(response.getValue().toObject(IssuerBundle.class)))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); } } @@ -1599,10 +1685,11 @@ public Mono> createIssuerWithResponse(CertificateIss @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getIssuerWithResponse(String issuerName) { try { - return implClient.getCertificateIssuerWithResponseAsync(vaultUrl, issuerName) - .map(response -> new SimpleResponse<>(response, createCertificateIssuer(response.getValue()))); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + return implClient.getCertificateIssuerWithResponseAsync(issuerName, EMPTY_OPTIONS) + .map(response -> new SimpleResponse<>(response, + createCertificateIssuer(response.getValue().toObject(IssuerBundle.class)))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); } } @@ -1664,20 +1751,14 @@ public Mono getIssuer(String issuerName) { @ServiceMethod(returns = ReturnType.SINGLE) public Mono> deleteIssuerWithResponse(String issuerName) { try { - return implClient.deleteCertificateIssuerWithResponseAsync(vaultUrl, issuerName) - .onErrorMap(KeyVaultErrorException.class, CertificateAsyncClient::mapDeleteCertificateIssuerException) - .map(response -> new SimpleResponse<>(response, createCertificateIssuer(response.getValue()))); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + return implClient.deleteCertificateIssuerWithResponseAsync(issuerName, EMPTY_OPTIONS) + .map(response -> new SimpleResponse<>(response, + createCertificateIssuer(response.getValue().toObject(IssuerBundle.class)))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); } } - static HttpResponseException mapDeleteCertificateIssuerException(KeyVaultErrorException ex) { - return (ex.getResponse().getStatusCode() == 404) - ? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; - } - /** * Deletes the specified certificate issuer. The DeleteCertificateIssuer operation permanently removes the specified * certificate issuer from the key vault. This operation requires the certificates/manageissuers/deleteissuers @@ -1730,16 +1811,21 @@ public Mono deleteIssuer(String issuerName) { */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux listPropertiesOfIssuers() { - return new PagedFlux<>( - maxResults -> implClient.getCertificateIssuersSinglePageAsync(vaultUrl, maxResults) - .map(CertificateAsyncClient::mapIssuersPagedResponse), - (continuationToken, maxResults) -> implClient - .getCertificateIssuersNextSinglePageAsync(continuationToken, vaultUrl) - .map(CertificateAsyncClient::mapIssuersPagedResponse)); - } - - static PagedResponse mapIssuersPagedResponse(PagedResponse page) { - return mapPagedResponse(page, IssuerPropertiesHelper::createIssuerProperties); + try { + PagedFlux pagedFluxResponse = implClient.getCertificateIssuersAsync(EMPTY_OPTIONS); + + return PagedFlux.create(() -> (continuationTokenParam, pageSizeParam) -> { + Flux> pagedResponseFlux = (continuationTokenParam == null) + ? pagedFluxResponse.byPage().take(1) + : pagedFluxResponse.byPage(continuationTokenParam).take(1); + + return pagedResponseFlux + .map(pagedResponse -> mapPagedResponse(pagedResponse, binaryData -> IssuerPropertiesHelper + .createIssuerProperties(binaryData.toObject(CertificateIssuerItem.class)))); + }); + } catch (RuntimeException e) { + return pagedFluxError(LOGGER, e); + } } /** @@ -1819,12 +1905,19 @@ public Mono> updateIssuerWithResponse(CertificateIss try { IssuerBundle issuerBundle = CertificateIssuerHelper.getIssuerBundle(issuer); + CertificateIssuerUpdateParameters certificateIssuerUpdateParameters + = new CertificateIssuerUpdateParameters().setProvider(issuer.getProvider()) + .setAttributes(issuerBundle.getAttributes()) + .setCredentials(issuerBundle.getCredentials()) + .setOrganizationDetails(issuerBundle.getOrganizationDetails()); + return implClient - .updateCertificateIssuerWithResponseAsync(vaultUrl, issuer.getName(), issuer.getProvider(), - issuerBundle.getCredentials(), issuerBundle.getOrganizationDetails(), issuerBundle.getAttributes()) - .map(response -> new SimpleResponse<>(response, createCertificateIssuer(response.getValue()))); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + .updateCertificateIssuerWithResponseAsync(issuer.getName(), + BinaryData.fromObject(certificateIssuerUpdateParameters), EMPTY_OPTIONS) + .map(response -> new SimpleResponse<>(response, + createCertificateIssuer(response.getValue().toObject(IssuerBundle.class)))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); } } @@ -1854,7 +1947,9 @@ public Mono> updateIssuerWithResponse(CertificateIss @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux setContacts(List contacts) { return new PagedFlux<>( - () -> implClient.setCertificateContactsWithResponseAsync(vaultUrl, new Contacts().setContactList(contacts)) + () -> implClient + .setCertificateContactsWithResponseAsync(BinaryData.fromObject(new Contacts().setContactList(contacts)), + EMPTY_OPTIONS) .map(CertificateAsyncClient::mapContactsToPagedResponse)); } @@ -1877,7 +1972,7 @@ public PagedFlux setContacts(List contac */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux listContacts() { - return new PagedFlux<>(() -> implClient.getCertificateContactsWithResponseAsync(vaultUrl) + return new PagedFlux<>(() -> implClient.getCertificateContactsWithResponseAsync(EMPTY_OPTIONS) .map(CertificateAsyncClient::mapContactsToPagedResponse)); } @@ -1901,13 +1996,13 @@ public PagedFlux listContacts() { */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux deleteContacts() { - return new PagedFlux<>(() -> implClient.deleteCertificateContactsWithResponseAsync(vaultUrl) + return new PagedFlux<>(() -> implClient.deleteCertificateContactsWithResponseAsync(EMPTY_OPTIONS) .map(CertificateAsyncClient::mapContactsToPagedResponse)); } - static PagedResponse mapContactsToPagedResponse(Response response) { + static PagedResponse mapContactsToPagedResponse(Response response) { return new PagedResponseBase<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), - response.getValue().getContactList(), null, null); + response.getValue().toObject(Contacts.class).getContactList(), null, null); } /** @@ -1963,23 +2058,19 @@ public Mono deleteCertificateOperation(String certificateN @ServiceMethod(returns = ReturnType.SINGLE) public Mono> deleteCertificateOperationWithResponse(String certificateName) { try { - return implClient.deleteCertificateOperationWithResponseAsync(vaultUrl, certificateName) - .onErrorMap(KeyVaultErrorException.class, - CertificateAsyncClient::mapDeleteCertificateOperationException) - .map(response -> new SimpleResponse<>(response, createCertificateOperation(response.getValue()))); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + return implClient.deleteCertificateOperationWithResponseAsync(certificateName, EMPTY_OPTIONS) + .map(response -> new SimpleResponse<>(response, createCertificateOperation(response.getValue() + .toObject( + com.azure.security.keyvault.certificates.implementation.models.CertificateOperation.class)))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); } } - static HttpResponseException mapDeleteCertificateOperationException(KeyVaultErrorException ex) { - if (ex.getResponse().getStatusCode() == 400) { - return new ResourceModifiedException(ex.getMessage(), ex.getResponse(), ex.getValue()); - } else if (ex.getResponse().getStatusCode() == 404) { - return new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()); - } else { - return ex; - } + static HttpResponseException mapDeleteCertificateOperationException(HttpResponseException e) { + return e.getResponse().getStatusCode() == 400 + ? new ResourceModifiedException(e.getMessage(), e.getResponse(), e.getValue()) + : e; } /** @@ -2036,12 +2127,18 @@ public Mono cancelCertificateOperation(String certificateN @ServiceMethod(returns = ReturnType.SINGLE) public Mono> cancelCertificateOperationWithResponse(String certificateName) { try { - return implClient.updateCertificateOperationWithResponseAsync(vaultUrl, certificateName, true) - .onErrorMap(KeyVaultErrorException.class, - CertificateAsyncClient::mapUpdateCertificateOperationException) - .map(response -> new SimpleResponse<>(response, createCertificateOperation(response.getValue()))); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + CertificateOperationUpdateParameter certificateOperationUpdateParameter + = new CertificateOperationUpdateParameter(true); + + return implClient + .updateCertificateOperationWithResponseAsync(certificateName, + BinaryData.fromObject(certificateOperationUpdateParameter), EMPTY_OPTIONS) + .onErrorMap(HttpResponseException.class, CertificateAsyncClient::mapUpdateCertificateOperationException) + .map(response -> new SimpleResponse<>(response, createCertificateOperation(response.getValue() + .toObject( + com.azure.security.keyvault.certificates.implementation.models.CertificateOperation.class)))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); } } @@ -2104,20 +2201,27 @@ public Mono importCertificate(ImportCertificateOp @ServiceMethod(returns = ReturnType.SINGLE) public Mono> importCertificateWithResponse(ImportCertificateOptions importCertificateOptions) { + if (importCertificateOptions == null) { return monoError(LOGGER, new NullPointerException("'importCertificateOptions' cannot be null.")); } try { - com.azure.security.keyvault.certificates.implementation.models.CertificatePolicy implPolicy - = getImplCertificatePolicy(importCertificateOptions.getPolicy()); - - return implClient.importCertificateWithResponseAsync(vaultUrl, importCertificateOptions.getName(), - transformCertificateForImport(importCertificateOptions), importCertificateOptions.getPassword(), - implPolicy, implPolicy == null ? null : implPolicy.getAttributes(), importCertificateOptions.getTags()) - .map(response -> new SimpleResponse<>(response, createCertificateWithPolicy(response.getValue()))); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + CertificateImportParameters certificateImportParameters + = new CertificateImportParameters(transformCertificateForImport(importCertificateOptions)) + .setCertificatePolicy(getImplCertificatePolicy(importCertificateOptions.getPolicy())) + .setPassword(importCertificateOptions.getPassword()) + .setTags(importCertificateOptions.getTags()) + .setCertificateAttributes( + new CertificateAttributes().setEnabled(importCertificateOptions.isEnabled())); + + return implClient + .importCertificateWithResponseAsync(importCertificateOptions.getName(), + BinaryData.fromObject(certificateImportParameters), EMPTY_OPTIONS) + .map(response -> new SimpleResponse<>(response, + createCertificateWithPolicy(response.getValue().toObject(CertificateBundle.class)))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); } } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/CertificateClient.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/CertificateClient.java index 4b9f28fde155..0b27db28a3c8 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/CertificateClient.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/CertificateClient.java @@ -11,8 +11,10 @@ import com.azure.core.exception.ResourceModifiedException; import com.azure.core.exception.ResourceNotFoundException; import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.RequestOptions; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.BinaryData; import com.azure.core.util.Context; import com.azure.core.util.logging.ClientLogger; import com.azure.core.util.polling.LongRunningOperationStatus; @@ -21,16 +23,24 @@ import com.azure.core.util.polling.SyncPoller; import com.azure.security.keyvault.certificates.implementation.CertificateClientImpl; import com.azure.security.keyvault.certificates.implementation.CertificateIssuerHelper; -import com.azure.security.keyvault.certificates.implementation.CertificateOperationHelper; -import com.azure.security.keyvault.certificates.implementation.CertificatePolicyHelper; +import com.azure.security.keyvault.certificates.implementation.CertificatePropertiesHelper; import com.azure.security.keyvault.certificates.implementation.DeletedCertificateHelper; -import com.azure.security.keyvault.certificates.implementation.KeyVaultCertificateWithPolicyHelper; import com.azure.security.keyvault.certificates.implementation.models.BackupCertificateResult; import com.azure.security.keyvault.certificates.implementation.models.CertificateAttributes; import com.azure.security.keyvault.certificates.implementation.models.CertificateBundle; +import com.azure.security.keyvault.certificates.implementation.models.CertificateCreateParameters; +import com.azure.security.keyvault.certificates.implementation.models.CertificateImportParameters; +import com.azure.security.keyvault.certificates.implementation.models.CertificateIssuerSetParameters; +import com.azure.security.keyvault.certificates.implementation.models.CertificateIssuerUpdateParameters; +import com.azure.security.keyvault.certificates.implementation.models.CertificateItem; +import com.azure.security.keyvault.certificates.implementation.models.CertificateMergeParameters; +import com.azure.security.keyvault.certificates.implementation.models.CertificateOperationUpdateParameter; +import com.azure.security.keyvault.certificates.implementation.models.CertificateRestoreParameters; +import com.azure.security.keyvault.certificates.implementation.models.CertificateUpdateParameters; import com.azure.security.keyvault.certificates.implementation.models.Contacts; +import com.azure.security.keyvault.certificates.implementation.models.DeletedCertificateBundle; +import com.azure.security.keyvault.certificates.implementation.models.DeletedCertificateItem; import com.azure.security.keyvault.certificates.implementation.models.IssuerBundle; -import com.azure.security.keyvault.certificates.implementation.models.KeyVaultErrorException; import com.azure.security.keyvault.certificates.models.CertificateContact; import com.azure.security.keyvault.certificates.models.CertificateIssuer; import com.azure.security.keyvault.certificates.models.CertificateOperation; @@ -52,14 +62,14 @@ import java.util.function.Function; import java.util.function.Supplier; -import static com.azure.security.keyvault.certificates.CertificateAsyncClient.mapCertificateItemPage; +import static com.azure.security.keyvault.certificates.CertificateAsyncClient.EMPTY_OPTIONS; import static com.azure.security.keyvault.certificates.CertificateAsyncClient.mapContactsToPagedResponse; -import static com.azure.security.keyvault.certificates.CertificateAsyncClient.mapDeletedCertificateItemPage; -import static com.azure.security.keyvault.certificates.CertificateAsyncClient.mapIssuersPagedResponse; import static com.azure.security.keyvault.certificates.CertificateAsyncClient.processCertificateOperationResponse; import static com.azure.security.keyvault.certificates.CertificateAsyncClient.transformCertificateForImport; +import static com.azure.security.keyvault.certificates.implementation.CertificateIssuerHelper.createCertificateIssuer; import static com.azure.security.keyvault.certificates.implementation.CertificateIssuerHelper.getIssuerBundle; import static com.azure.security.keyvault.certificates.implementation.CertificateOperationHelper.createCertificateOperation; +import static com.azure.security.keyvault.certificates.implementation.CertificatePolicyHelper.createCertificatePolicy; import static com.azure.security.keyvault.certificates.implementation.CertificatePolicyHelper.getImplCertificatePolicy; import static com.azure.security.keyvault.certificates.implementation.DeletedCertificateHelper.createDeletedCertificate; import static com.azure.security.keyvault.certificates.implementation.KeyVaultCertificateWithPolicyHelper.createCertificateWithPolicy; @@ -239,6 +249,7 @@ public String getVaultUrl() { @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) public SyncPoller beginCreateCertificate( String certificateName, CertificatePolicy policy, Boolean isEnabled, Map tags) { + if (policy == null) { throw LOGGER.logExceptionAsError(new NullPointerException("'policy' cannot be null.")); } @@ -252,32 +263,49 @@ public SyncPoller beginCrea private PollResponse createCertificateActivation(String certificateName, CertificatePolicy policy, Boolean isEnabled, Map tags) { - com.azure.security.keyvault.certificates.implementation.models.CertificatePolicy implPolicy - = getImplCertificatePolicy(policy); + + CertificateCreateParameters certificateCreateParameters + = new CertificateCreateParameters().setCertificatePolicy(getImplCertificatePolicy(policy)) + .setCertificateAttributes(new CertificateAttributes().setEnabled(isEnabled)) + .setTags(tags); return new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, createCertificateOperation(callWithMappedException( - () -> implClient.createCertificate(vaultUrl, certificateName, implPolicy, - new CertificateAttributes().setEnabled(isEnabled), tags), + () -> implClient + .createCertificateWithResponse(certificateName, BinaryData.fromObject(certificateCreateParameters), + EMPTY_OPTIONS) + .getValue() + .toObject( + com.azure.security.keyvault.certificates.implementation.models.CertificateOperation.class), CertificateAsyncClient::mapCreateCertificateException))); } private PollResponse certificatePollOperation(String certificateName) { - return processCertificateOperationResponse( - callWithMappedException(() -> implClient.getCertificateOperation(vaultUrl, certificateName), - CertificateAsyncClient::mapGetCertificateOperationException)); + return processCertificateOperationResponse(callWithMappedException( + () -> implClient.getCertificateOperationWithResponse(certificateName, EMPTY_OPTIONS) + .getValue() + .toObject(com.azure.security.keyvault.certificates.implementation.models.CertificateOperation.class), + CertificateAsyncClient::mapGetCertificateOperationException)); } private CertificateOperation certificateCancellationOperation(String certificateName) { - return createCertificateOperation( - callWithMappedException(() -> implClient.updateCertificateOperation(vaultUrl, certificateName, true), - CertificateAsyncClient::mapUpdateCertificateOperationException)); + CertificateOperationUpdateParameter certificateOperationUpdateParameter + = new CertificateOperationUpdateParameter(true); + + return createCertificateOperation(callWithMappedException( + () -> implClient + .updateCertificateOperationWithResponse(certificateName, + BinaryData.fromObject(certificateOperationUpdateParameter), EMPTY_OPTIONS) + .getValue() + .toObject(com.azure.security.keyvault.certificates.implementation.models.CertificateOperation.class), + CertificateAsyncClient::mapUpdateCertificateOperationException)); } private KeyVaultCertificateWithPolicy fetchCertificateOperation(String certificateName) { return createCertificateWithPolicy( - callWithMappedException(() -> implClient.getCertificate(vaultUrl, certificateName, null), - CertificateAsyncClient::mapGetCertificateException)); + callWithMappedException(() -> implClient.getCertificateWithResponse(certificateName, null, EMPTY_OPTIONS) + .getValue() + .toObject(CertificateBundle.class), CertificateAsyncClient::mapGetCertificateException)); } /** @@ -313,6 +341,7 @@ private KeyVaultCertificateWithPolicy fetchCertificateOperation(String certifica @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) public SyncPoller beginCreateCertificate(String certificateName, CertificatePolicy policy) { + return beginCreateCertificate(certificateName, policy, true, null); } @@ -342,6 +371,7 @@ private KeyVaultCertificateWithPolicy fetchCertificateOperation(String certifica @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) public SyncPoller getCertificateOperation(String certificateName) { + return SyncPoller.createPoller(Duration.ofSeconds(1), ignored -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, null), ignored -> certificatePollOperation(certificateName), @@ -404,8 +434,9 @@ public KeyVaultCertificateWithPolicy getCertificate(String certificateName) { @ServiceMethod(returns = ReturnType.SINGLE) public Response getCertificateWithResponse(String certificateName, Context context) { return callWithMappedResponseAndException( - () -> implClient.getCertificateWithResponse(vaultUrl, certificateName, null, context), - KeyVaultCertificateWithPolicyHelper::createCertificateWithPolicy, + () -> implClient.getCertificateWithResponse(certificateName, null, + new RequestOptions().setContext(context)), + binaryData -> createCertificateWithPolicy(binaryData.toObject(CertificateBundle.class)), CertificateAsyncClient::mapGetCertificateException); } @@ -442,8 +473,9 @@ public Response getCertificateWithResponse(String public Response getCertificateVersionWithResponse(String certificateName, String version, Context context) { return callWithMappedResponseAndException( - () -> implClient.getCertificateWithResponse(vaultUrl, certificateName, version, context), - KeyVaultCertificateWithPolicyHelper::createCertificateWithPolicy, + () -> implClient.getCertificateWithResponse(certificateName, version, + new RequestOptions().setContext(context)), + binaryData -> createCertificateWithPolicy(binaryData.toObject(CertificateBundle.class)), CertificateAsyncClient::mapGetCertificateException); } @@ -544,6 +576,7 @@ public KeyVaultCertificate updateCertificateProperties(CertificateProperties pro @ServiceMethod(returns = ReturnType.SINGLE) public Response updateCertificatePropertiesWithResponse(CertificateProperties properties, Context context) { + if (properties == null) { throw LOGGER.logExceptionAsError(new NullPointerException("'properties' cannot be null.")); } @@ -552,10 +585,16 @@ public Response updateCertificatePropertiesWithResponse(Cer .setExpires(properties.getExpiresOn()) .setNotBefore(properties.getNotBefore()); - Response response = implClient.updateCertificateWithResponse(vaultUrl, properties.getName(), - properties.getVersion(), null, certificateAttributes, properties.getTags(), context); + CertificateUpdateParameters certificateUpdateParameters + = new CertificateUpdateParameters().setCertificateAttributes(certificateAttributes) + .setTags(properties.getTags()); - return new SimpleResponse<>(response, createCertificateWithPolicy(response.getValue())); + Response response + = implClient.updateCertificateWithResponse(properties.getName(), properties.getVersion(), + BinaryData.fromObject(certificateUpdateParameters), new RequestOptions().setContext(context)); + + return new SimpleResponse<>(response, + createCertificateWithPolicy(response.getValue().toObject(CertificateBundle.class))); } /** @@ -596,7 +635,10 @@ public SyncPoller beginDeleteCertificate(String certif private PollResponse deleteCertificateActivation(String certificateName) { return new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, createDeletedCertificate( - callWithMappedException(() -> implClient.deleteCertificate(vaultUrl, certificateName), + callWithMappedException( + () -> implClient.deleteCertificateWithResponse(certificateName, EMPTY_OPTIONS) + .getValue() + .toObject(DeletedCertificateBundle.class), CertificateAsyncClient::mapDeleteCertificateException))); } @@ -604,9 +646,11 @@ private PollResponse deleteCertificatePollOperation(String c PollingContext pollingContext) { try { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, - createDeletedCertificate(implClient.getDeletedCertificate(vaultUrl, certificateName))); - } catch (KeyVaultErrorException ex) { - if (ex.getResponse().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { + createDeletedCertificate(implClient.getDeletedCertificateWithResponse(certificateName, EMPTY_OPTIONS) + .getValue() + .toObject(DeletedCertificateBundle.class))); + } catch (HttpResponseException e) { + if (e.getResponse().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { return new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()); } else { @@ -616,7 +660,7 @@ private PollResponse deleteCertificatePollOperation(String c return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } - } catch (Exception ex) { + } catch (Exception e) { // This means either vault has soft-delete disabled or permission is not granted for the get deleted // certificate operation. In both cases deletion operation was successful when activation operation // succeeded before reaching here. @@ -682,10 +726,11 @@ public DeletedCertificate getDeletedCertificate(String certificateName) { */ @ServiceMethod(returns = ReturnType.SINGLE) public Response getDeletedCertificateWithResponse(String certificateName, Context context) { - return callWithMappedResponseAndException( - () -> implClient.getDeletedCertificateWithResponse(vaultUrl, certificateName, context), - DeletedCertificateHelper::createDeletedCertificate, - CertificateAsyncClient::mapGetDeletedCertificateException); + Response response + = implClient.getDeletedCertificateWithResponse(certificateName, new RequestOptions().setContext(context)); + + return new SimpleResponse<>(response, + createDeletedCertificate(response.getValue().toObject(DeletedCertificateBundle.class))); } /** @@ -737,9 +782,8 @@ public void purgeDeletedCertificate(String certificateName) { */ @ServiceMethod(returns = ReturnType.SINGLE) public Response purgeDeletedCertificateWithResponse(String certificateName, Context context) { - return callWithMappedResponseAndException( - () -> implClient.purgeDeletedCertificateWithResponse(vaultUrl, certificateName, context), t -> t, - CertificateAsyncClient::mapPurgeDeletedCertificateException); + return implClient.purgeDeletedCertificateWithResponse(certificateName, + new RequestOptions().setContext(context)); } /** @@ -781,18 +825,20 @@ public SyncPoller beginRecoverDeletedCertif private PollResponse recoverDeletedCertificateActivation(String certificateName) { return new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, - createCertificateWithPolicy( - callWithMappedException(() -> implClient.recoverDeletedCertificate(vaultUrl, certificateName), - CertificateAsyncClient::mapRecoverDeletedCertificateException))); + createCertificateWithPolicy(implClient.recoverDeletedCertificateWithResponse(certificateName, EMPTY_OPTIONS) + .getValue() + .toObject(CertificateBundle.class))); } private PollResponse recoverDeletedCertificatePollOperation(String certificateName, PollingContext pollingContext) { try { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, - createCertificateWithPolicy(implClient.getCertificate(vaultUrl, certificateName, null))); - } catch (KeyVaultErrorException ex) { - if (ex.getResponse().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { + createCertificateWithPolicy(implClient.getCertificateWithResponse(certificateName, null, EMPTY_OPTIONS) + .getValue() + .toObject(CertificateBundle.class))); + } catch (HttpResponseException e) { + if (e.getResponse().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { return new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()); } else { @@ -802,7 +848,7 @@ private PollResponse recoverDeletedCertificatePol return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } - } catch (Exception ex) { + } catch (Exception e) { // This means permission is not granted for the get deleted key operation. // In both cases deletion operation was successful when activation operation succeeded before reaching // here. @@ -861,9 +907,10 @@ public byte[] backupCertificate(String certificateName) { */ @ServiceMethod(returns = ReturnType.SINGLE) public Response backupCertificateWithResponse(String certificateName, Context context) { - return callWithMappedResponseAndException( - () -> implClient.backupCertificateWithResponse(vaultUrl, certificateName, context), - BackupCertificateResult::getValue, CertificateAsyncClient::mapBackupCertificateException); + Response response + = implClient.backupCertificateWithResponse(certificateName, new RequestOptions().setContext(context)); + + return new SimpleResponse<>(response, response.getValue().toObject(BackupCertificateResult.class).getValue()); } /** @@ -920,9 +967,13 @@ public KeyVaultCertificateWithPolicy restoreCertificateBackup(byte[] backup) { @ServiceMethod(returns = ReturnType.SINGLE) public Response restoreCertificateBackupWithResponse(byte[] backup, Context context) { + + CertificateRestoreParameters certificateRestoreParameters = new CertificateRestoreParameters(backup); + return callWithMappedResponseAndException( - () -> implClient.restoreCertificateWithResponse(vaultUrl, backup, context), - KeyVaultCertificateWithPolicyHelper::createCertificateWithPolicy, + () -> implClient.restoreCertificateWithResponse(BinaryData.fromObject(certificateRestoreParameters), + new RequestOptions().setContext(context)), + binaryData -> createCertificateWithPolicy(binaryData.toObject(CertificateBundle.class)), CertificateAsyncClient::mapRestoreCertificateException); } @@ -986,11 +1037,12 @@ public PagedIterable listPropertiesOfCertificates() { */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable listPropertiesOfCertificates(boolean includePending, Context context) { - return new PagedIterable<>( - maxResults -> mapCertificateItemPage( - implClient.getCertificatesSinglePage(vaultUrl, maxResults, includePending, context)), - (continuationToken, maxResults) -> mapCertificateItemPage( - implClient.getCertificatesNextSinglePage(continuationToken, vaultUrl, context))); + RequestOptions requestOptions = new RequestOptions().setContext(context) + .addQueryParam("includePending", String.valueOf(includePending), false); + + return implClient.getCertificates(requestOptions) + .mapPage(binaryData -> CertificatePropertiesHelper + .createCertificateProperties(binaryData.toObject(CertificateItem.class))); } /** @@ -1043,11 +1095,12 @@ public PagedIterable listDeletedCertificates() { */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable listDeletedCertificates(boolean includePending, Context context) { - return new PagedIterable<>( - maxResults -> mapDeletedCertificateItemPage( - implClient.getDeletedCertificatesSinglePage(vaultUrl, maxResults, includePending, context)), - (continuationToken, maxResults) -> mapDeletedCertificateItemPage( - implClient.getDeletedCertificatesNextSinglePage(continuationToken, vaultUrl, context))); + RequestOptions requestOptions = new RequestOptions().setContext(context) + .addQueryParam("includePending", String.valueOf(includePending), false); + + return implClient.getDeletedCertificates(requestOptions) + .mapPage(binaryData -> DeletedCertificateHelper + .createDeletedCertificate(binaryData.toObject(DeletedCertificateItem.class))); } /** @@ -1121,11 +1174,10 @@ public PagedIterable listPropertiesOfCertificateVersions( @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable listPropertiesOfCertificateVersions(String certificateName, Context context) { - return new PagedIterable<>( - maxResults -> mapCertificateItemPage( - implClient.getCertificateVersionsSinglePage(vaultUrl, certificateName, maxResults, context)), - (continuationToken, maxResults) -> mapCertificateItemPage( - implClient.getCertificateVersionsNextSinglePage(continuationToken, vaultUrl, context))); + + return implClient.getCertificateVersions(certificateName, new RequestOptions().setContext(context)) + .mapPage(binaryData -> CertificatePropertiesHelper + .createCertificateProperties(binaryData.toObject(CertificateItem.class))); } /** @@ -1172,16 +1224,19 @@ public CertificatePolicy getCertificatePolicy(String certificateName) { * * @param certificateName The name of the certificate whose policy is to be retrieved, cannot be null * @param context Additional context that is passed through the Http pipeline during the service call. - * @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault. - * @throws HttpRequestException if {@code certificateName} is empty string. * @return A {@link Response} whose {@link Response#getValue() value} contains the requested * {@link CertificatePolicy certificate policy}. + * @throws ResourceNotFoundException when a certificate with {@code certificateName} doesn't exist in the key vault. + * @throws HttpRequestException if {@code certificateName} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response getCertificatePolicyWithResponse(String certificateName, Context context) { return callWithMappedResponseAndException( - () -> implClient.getCertificatePolicyWithResponse(vaultUrl, certificateName, context), - CertificatePolicyHelper::createCertificatePolicy, CertificateAsyncClient::mapGetCertificatePolicyException); + () -> implClient.getCertificatePolicyWithResponse(certificateName, + new RequestOptions().setContext(context)), + binaryData -> createCertificatePolicy(binaryData + .toObject(com.azure.security.keyvault.certificates.implementation.models.CertificatePolicy.class)), + CertificateAsyncClient::mapGetCertificatePolicyException); } /** @@ -1251,15 +1306,19 @@ public CertificatePolicy updateCertificatePolicy(String certificateName, Certifi @ServiceMethod(returns = ReturnType.SINGLE) public Response updateCertificatePolicyWithResponse(String certificateName, CertificatePolicy policy, Context context) { + if (policy == null) { throw LOGGER.logExceptionAsError(new NullPointerException("'policy' cannot be null.")); } - return callWithMappedResponseAndException( - () -> implClient.updateCertificatePolicyWithResponse(vaultUrl, certificateName, - getImplCertificatePolicy(policy), context), - CertificatePolicyHelper::createCertificatePolicy, - CertificateAsyncClient::mapUpdateCertificatePolicyException); + CertificateUpdateParameters certificateUpdateParameters + = new CertificateUpdateParameters().setCertificatePolicy(getImplCertificatePolicy(policy)); + + Response response = implClient.updateCertificatePolicyWithResponse(certificateName, + BinaryData.fromObject(certificateUpdateParameters), new RequestOptions().setContext(context)); + + return new SimpleResponse<>(response, createCertificatePolicy(response.getValue() + .toObject(com.azure.security.keyvault.certificates.implementation.models.CertificatePolicy.class))); } /** @@ -1333,10 +1392,17 @@ public Response createIssuerWithResponse(CertificateIssuer is } IssuerBundle issuerBundle = getIssuerBundle(issuer); - return callWithMappedResponseAndException(() -> implClient.setCertificateIssuerWithResponse(vaultUrl, - issuer.getName(), issuer.getProvider(), issuerBundle.getCredentials(), - issuerBundle.getOrganizationDetails(), issuerBundle.getAttributes(), context), - CertificateIssuerHelper::createCertificateIssuer, ex -> ex); + CertificateIssuerSetParameters certificateIssuerSetParameters + = new CertificateIssuerSetParameters(issuerBundle.getProvider()) + .setOrganizationDetails(issuerBundle.getOrganizationDetails()) + .setCredentials(issuerBundle.getCredentials()) + .setAttributes(issuerBundle.getAttributes()); + + Response response = implClient.setCertificateIssuerWithResponse(issuer.getName(), + BinaryData.fromObject(certificateIssuerSetParameters), new RequestOptions().setContext(context)); + + return new SimpleResponse<>(response, createCertificateIssuer(response.getValue() + .toObject(com.azure.security.keyvault.certificates.implementation.models.IssuerBundle.class))); } /** @@ -1366,9 +1432,11 @@ public Response createIssuerWithResponse(CertificateIssuer is */ @ServiceMethod(returns = ReturnType.SINGLE) public Response getIssuerWithResponse(String issuerName, Context context) { - return callWithMappedResponseAndException( - () -> implClient.getCertificateIssuerWithResponse(vaultUrl, issuerName, context), - CertificateIssuerHelper::createCertificateIssuer, ex -> ex); + Response response + = implClient.getCertificateIssuerWithResponse(issuerName, new RequestOptions().setContext(context)); + + return new SimpleResponse<>(response, + createCertificateIssuer(response.getValue().toObject(IssuerBundle.class))); } /** @@ -1425,10 +1493,11 @@ public CertificateIssuer getIssuer(String issuerName) { */ @ServiceMethod(returns = ReturnType.SINGLE) public Response deleteIssuerWithResponse(String issuerName, Context context) { - return callWithMappedResponseAndException( - () -> implClient.deleteCertificateIssuerWithResponse(vaultUrl, issuerName, context), - CertificateIssuerHelper::createCertificateIssuer, - CertificateAsyncClient::mapDeleteCertificateIssuerException); + Response response + = implClient.deleteCertificateIssuerWithResponse(issuerName, new RequestOptions().setContext(context)); + + return new SimpleResponse<>(response, + createCertificateIssuer(response.getValue().toObject(IssuerBundle.class))); } /** @@ -1511,11 +1580,8 @@ public PagedIterable listPropertiesOfIssuers() { */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable listPropertiesOfIssuers(Context context) { - return new PagedIterable<>( - maxResults -> mapIssuersPagedResponse( - implClient.getCertificateIssuersSinglePage(vaultUrl, maxResults, context)), - (continuationToken, maxResults) -> mapIssuersPagedResponse( - implClient.getCertificateIssuersNextSinglePage(continuationToken, vaultUrl, context))); + return implClient.getCertificateIssuers(new RequestOptions().setContext(context)) + .mapPage(issuer -> issuer.toObject(IssuerProperties.class)); } /** @@ -1585,10 +1651,17 @@ public Response updateIssuerWithResponse(CertificateIssuer is } IssuerBundle issuerBundle = CertificateIssuerHelper.getIssuerBundle(issuer); - return callWithMappedResponseAndException(() -> implClient.updateCertificateIssuerWithResponse(vaultUrl, - issuer.getName(), issuer.getProvider(), issuerBundle.getCredentials(), - issuerBundle.getOrganizationDetails(), issuerBundle.getAttributes(), context), - CertificateIssuerHelper::createCertificateIssuer, ex -> ex); + CertificateIssuerUpdateParameters certificateIssuerUpdateParameters + = new CertificateIssuerUpdateParameters().setProvider(issuerBundle.getProvider()) + .setAttributes(issuerBundle.getAttributes()) + .setCredentials(issuerBundle.getCredentials()) + .setOrganizationDetails(issuerBundle.getOrganizationDetails()); + + Response response = implClient.updateCertificateIssuerWithResponse(issuer.getName(), + BinaryData.fromObject(certificateIssuerUpdateParameters), new RequestOptions().setContext(context)); + + return new SimpleResponse<>(response, + createCertificateIssuer(response.getValue().toObject(IssuerBundle.class))); } /** @@ -1650,8 +1723,8 @@ public PagedIterable setContacts(List co */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable setContacts(List contacts, Context context) { - return new PagedIterable<>(() -> mapContactsToPagedResponse( - implClient.setCertificateContactsWithResponse(vaultUrl, new Contacts().setContactList(contacts), context))); + return new PagedIterable<>(() -> mapContactsToPagedResponse(implClient.setCertificateContactsWithResponse( + BinaryData.fromObject(new Contacts().setContactList(contacts)), new RequestOptions().setContext(context)))); } /** @@ -1702,8 +1775,8 @@ public PagedIterable listContacts() { */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable listContacts(Context context) { - return new PagedIterable<>( - () -> mapContactsToPagedResponse(implClient.getCertificateContactsWithResponse(vaultUrl, context))); + return new PagedIterable<>(() -> mapContactsToPagedResponse( + implClient.getCertificateContactsWithResponse(new RequestOptions().setContext(context)))); } /** @@ -1754,8 +1827,8 @@ public PagedIterable deleteContacts() { */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable deleteContacts(Context context) { - return new PagedIterable<>( - () -> mapContactsToPagedResponse(implClient.deleteCertificateContactsWithResponse(vaultUrl, context))); + return new PagedIterable<>(() -> mapContactsToPagedResponse( + implClient.deleteCertificateContactsWithResponse(new RequestOptions().setContext(context)))); } /** @@ -1815,9 +1888,12 @@ public CertificateOperation deleteCertificateOperation(String certificateName) { @ServiceMethod(returns = ReturnType.SINGLE) public Response deleteCertificateOperationWithResponse(String certificateName, Context context) { + return callWithMappedResponseAndException( - () -> implClient.deleteCertificateOperationWithResponse(vaultUrl, certificateName, context), - CertificateOperationHelper::createCertificateOperation, + () -> implClient.deleteCertificateOperationWithResponse(certificateName, + new RequestOptions().setContext(context)), + binaryData -> createCertificateOperation(binaryData + .toObject(com.azure.security.keyvault.certificates.implementation.models.CertificateOperation.class)), CertificateAsyncClient::mapDeleteCertificateOperationException); } @@ -1878,9 +1954,15 @@ public CertificateOperation cancelCertificateOperation(String certificateName) { @ServiceMethod(returns = ReturnType.SINGLE) public Response cancelCertificateOperationWithResponse(String certificateName, Context context) { + + CertificateOperationUpdateParameter certificateOperationUpdateParameter + = new CertificateOperationUpdateParameter(true); + return callWithMappedResponseAndException( - () -> implClient.updateCertificateOperationWithResponse(vaultUrl, certificateName, true, context), - CertificateOperationHelper::createCertificateOperation, + () -> implClient.updateCertificateOperationWithResponse(certificateName, + BinaryData.fromObject(certificateOperationUpdateParameter), new RequestOptions().setContext(context)), + binaryData -> createCertificateOperation(binaryData + .toObject(com.azure.security.keyvault.certificates.implementation.models.CertificateOperation.class)), CertificateAsyncClient::mapUpdateCertificateOperationException); } @@ -1943,16 +2025,21 @@ public KeyVaultCertificateWithPolicy mergeCertificate(MergeCertificateOptions me @ServiceMethod(returns = ReturnType.SINGLE) public Response mergeCertificateWithResponse(MergeCertificateOptions mergeCertificateOptions, Context context) { + if (mergeCertificateOptions == null) { throw LOGGER.logExceptionAsError(new NullPointerException("'mergeCertificateOptions' cannot be null.")); } - return callWithMappedResponseAndException( - () -> implClient.mergeCertificateWithResponse(vaultUrl, mergeCertificateOptions.getName(), - mergeCertificateOptions.getX509Certificates(), - new CertificateAttributes().setEnabled(mergeCertificateOptions.isEnabled()), - mergeCertificateOptions.getTags(), context), - KeyVaultCertificateWithPolicyHelper::createCertificateWithPolicy, ex -> ex); + CertificateMergeParameters certificateMergeParameters + = new CertificateMergeParameters(mergeCertificateOptions.getX509Certificates()) + .setTags(mergeCertificateOptions.getTags()) + .setCertificateAttributes(new CertificateAttributes().setEnabled(mergeCertificateOptions.isEnabled())); + + Response response = implClient.mergeCertificateWithResponse(mergeCertificateOptions.getName(), + BinaryData.fromObject(certificateMergeParameters), new RequestOptions().setContext(context)); + + return new SimpleResponse<>(response, createCertificateWithPolicy(response.getValue() + .toObject(com.azure.security.keyvault.certificates.implementation.models.CertificateBundle.class))); } /** @@ -2022,29 +2109,39 @@ public KeyVaultCertificateWithPolicy importCertificate(ImportCertificateOptions com.azure.security.keyvault.certificates.implementation.models.CertificatePolicy implPolicy = getImplCertificatePolicy(importCertificateOptions.getPolicy()); - return callWithMappedResponseAndException(() -> implClient.importCertificateWithResponse(vaultUrl, - importCertificateOptions.getName(), transformCertificateForImport(importCertificateOptions), - importCertificateOptions.getPassword(), implPolicy, implPolicy == null ? null : implPolicy.getAttributes(), - importCertificateOptions.getTags(), context), - KeyVaultCertificateWithPolicyHelper::createCertificateWithPolicy, ex -> ex); + CertificateImportParameters certificateImportParameters + = new CertificateImportParameters(transformCertificateForImport(importCertificateOptions)) + .setPassword(importCertificateOptions.getPassword()) + .setCertificatePolicy(implPolicy) + .setTags(importCertificateOptions.getTags()) + .setCertificateAttributes(new CertificateAttributes().setEnabled(importCertificateOptions.isEnabled())); + + Response response = implClient.importCertificateWithResponse(importCertificateOptions.getName(), + BinaryData.fromObject(certificateImportParameters), new RequestOptions().setContext(context)); + + return new SimpleResponse<>(response, createCertificateWithPolicy(response.getValue() + .toObject(com.azure.security.keyvault.certificates.implementation.models.CertificateBundle.class))); } private static T callWithMappedException(Supplier apiCall, - Function exceptionMapper) { + Function exceptionMapper) { + try { return apiCall.get(); - } catch (KeyVaultErrorException ex) { - throw exceptionMapper.apply(ex); + } catch (HttpResponseException e) { + throw exceptionMapper.apply(e); } } private static Response callWithMappedResponseAndException(Supplier> apiCall, - Function responseValueMapper, Function exceptionMapper) { + Function responseValueMapper, Function exceptionMapper) { + try { - Response responseInn = apiCall.get(); - return new SimpleResponse<>(responseInn, responseValueMapper.apply(responseInn.getValue())); - } catch (KeyVaultErrorException ex) { - throw exceptionMapper.apply(ex); + Response response = apiCall.get(); + + return new SimpleResponse<>(response, responseValueMapper.apply(response.getValue())); + } catch (HttpResponseException e) { + throw exceptionMapper.apply(e); } } } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/CertificateClientBuilder.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/CertificateClientBuilder.java index d84a98fed951..42334ade3304 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/CertificateClientBuilder.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/CertificateClientBuilder.java @@ -161,7 +161,7 @@ public CertificateClientBuilder() { * and {@link #retryPolicy(RetryPolicy)} have been set. */ public CertificateClient buildClient() { - return new CertificateClient(buildInnerClient(), vaultUrl); + return new CertificateClient(buildImplClient(), vaultUrl); } /** @@ -183,10 +183,10 @@ public CertificateClient buildClient() { * and {@link #retryPolicy(RetryPolicy)} have been set. */ public CertificateAsyncClient buildAsyncClient() { - return new CertificateAsyncClient(buildInnerClient(), vaultUrl); + return new CertificateAsyncClient(buildImplClient(), vaultUrl); } - private CertificateClientImpl buildInnerClient() { + private CertificateClientImpl buildImplClient() { Configuration buildConfiguration = (configuration != null) ? configuration : Configuration.getGlobalConfiguration().clone(); @@ -197,10 +197,12 @@ private CertificateClientImpl buildInnerClient() { .logExceptionAsError(new IllegalStateException(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED)); } - CertificateServiceVersion serviceVersion = version != null ? version : CertificateServiceVersion.getLatest(); + if (version == null) { + version = CertificateServiceVersion.getLatest(); + } if (pipeline != null) { - return new CertificateClientImpl(pipeline, serviceVersion.getVersion()); + return new CertificateClientImpl(pipeline, vaultUrl, version); } if (credential == null) { @@ -240,13 +242,13 @@ private CertificateClientImpl buildInnerClient() { Tracer tracer = TracerProvider.getDefaultProvider() .createTracer(CLIENT_NAME, CLIENT_VERSION, KEYVAULT_TRACING_NAMESPACE_VALUE, tracingOptions); - HttpPipeline pipeline = new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) + HttpPipeline builtPipeline = new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .tracer(tracer) .clientOptions(localClientOptions) .build(); - return new CertificateClientImpl(pipeline, serviceVersion.getVersion()); + return new CertificateClientImpl(builtPipeline, vaultUrl, version); } /** diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/CertificateClientImpl.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/CertificateClientImpl.java index a47916467488..199ebe4fa6db 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/CertificateClientImpl.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/CertificateClientImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation; @@ -20,6 +20,10 @@ import com.azure.core.annotation.ServiceInterface; import com.azure.core.annotation.ServiceMethod; import com.azure.core.annotation.UnexpectedResponseExceptionType; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; import com.azure.core.http.HttpPipeline; import com.azure.core.http.HttpPipelineBuilder; import com.azure.core.http.policy.RetryPolicy; @@ -28,40 +32,18 @@ import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.PagedResponse; import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.RequestOptions; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.RestProxy; +import com.azure.core.util.BinaryData; import com.azure.core.util.Context; import com.azure.core.util.FluxUtil; import com.azure.core.util.serializer.JacksonAdapter; import com.azure.core.util.serializer.SerializerAdapter; -import com.azure.security.keyvault.certificates.implementation.models.BackupCertificateResult; -import com.azure.security.keyvault.certificates.implementation.models.CertificateAttributes; -import com.azure.security.keyvault.certificates.implementation.models.CertificateBundle; -import com.azure.security.keyvault.certificates.implementation.models.CertificateCreateParameters; -import com.azure.security.keyvault.certificates.implementation.models.CertificateImportParameters; -import com.azure.security.keyvault.certificates.implementation.models.CertificateIssuerItem; -import com.azure.security.keyvault.certificates.implementation.models.CertificateIssuerListResult; -import com.azure.security.keyvault.certificates.implementation.models.CertificateIssuerSetParameters; -import com.azure.security.keyvault.certificates.implementation.models.CertificateIssuerUpdateParameters; -import com.azure.security.keyvault.certificates.implementation.models.CertificateItem; -import com.azure.security.keyvault.certificates.implementation.models.CertificateListResult; -import com.azure.security.keyvault.certificates.implementation.models.CertificateMergeParameters; -import com.azure.security.keyvault.certificates.implementation.models.CertificateOperation; -import com.azure.security.keyvault.certificates.implementation.models.CertificateOperationUpdateParameter; -import com.azure.security.keyvault.certificates.implementation.models.CertificatePolicy; -import com.azure.security.keyvault.certificates.implementation.models.CertificateRestoreParameters; -import com.azure.security.keyvault.certificates.implementation.models.CertificateUpdateParameters; -import com.azure.security.keyvault.certificates.implementation.models.Contacts; -import com.azure.security.keyvault.certificates.implementation.models.DeletedCertificateBundle; -import com.azure.security.keyvault.certificates.implementation.models.DeletedCertificateItem; -import com.azure.security.keyvault.certificates.implementation.models.DeletedCertificateListResult; -import com.azure.security.keyvault.certificates.implementation.models.IssuerAttributes; -import com.azure.security.keyvault.certificates.implementation.models.IssuerBundle; -import com.azure.security.keyvault.certificates.implementation.models.IssuerCredentials; -import com.azure.security.keyvault.certificates.implementation.models.KeyVaultErrorException; -import com.azure.security.keyvault.certificates.implementation.models.OrganizationDetails; +import com.azure.security.keyvault.certificates.CertificateServiceVersion; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; import reactor.core.publisher.Mono; /** @@ -74,17 +56,30 @@ public final class CertificateClientImpl { private final CertificateClientService service; /** - * Api Version. */ - private final String apiVersion; + private final String vaultBaseUrl; /** - * Gets Api Version. + * Gets. * - * @return the apiVersion value. + * @return the vaultBaseUrl value. */ - public String getApiVersion() { - return this.apiVersion; + public String getVaultBaseUrl() { + return this.vaultBaseUrl; + } + + /** + * Service version. + */ + private final CertificateServiceVersion serviceVersion; + + /** + * Gets Service version. + * + * @return the serviceVersion value. + */ + public CertificateServiceVersion getServiceVersion() { + return this.serviceVersion; } /** @@ -118,21 +113,24 @@ public SerializerAdapter getSerializerAdapter() { /** * Initializes an instance of CertificateClient client. * - * @param apiVersion Api Version. + * @param vaultBaseUrl + * @param serviceVersion Service version. */ - public CertificateClientImpl(String apiVersion) { + public CertificateClientImpl(String vaultBaseUrl, CertificateServiceVersion serviceVersion) { this(new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build(), - JacksonAdapter.createDefaultSerializerAdapter(), apiVersion); + JacksonAdapter.createDefaultSerializerAdapter(), vaultBaseUrl, serviceVersion); } /** * Initializes an instance of CertificateClient client. * * @param httpPipeline The HTTP pipeline to send requests through. - * @param apiVersion Api Version. + * @param vaultBaseUrl + * @param serviceVersion Service version. */ - public CertificateClientImpl(HttpPipeline httpPipeline, String apiVersion) { - this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), apiVersion); + public CertificateClientImpl(HttpPipeline httpPipeline, String vaultBaseUrl, + CertificateServiceVersion serviceVersion) { + this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), vaultBaseUrl, serviceVersion); } /** @@ -140,12 +138,15 @@ public CertificateClientImpl(HttpPipeline httpPipeline, String apiVersion) { * * @param httpPipeline The HTTP pipeline to send requests through. * @param serializerAdapter The serializer to serialize an object into a string. - * @param apiVersion Api Version. + * @param vaultBaseUrl + * @param serviceVersion Service version. */ - public CertificateClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String apiVersion) { + public CertificateClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String vaultBaseUrl, + CertificateServiceVersion serviceVersion) { this.httpPipeline = httpPipeline; this.serializerAdapter = serializerAdapter; - this.apiVersion = apiVersion; + this.vaultBaseUrl = vaultBaseUrl; + this.serviceVersion = serviceVersion; this.service = RestProxy.create(CertificateClientService.class, this.httpPipeline, this.getSerializerAdapter()); } @@ -158,457 +159,657 @@ public CertificateClientImpl(HttpPipeline httpPipeline, SerializerAdapter serial public interface CertificateClientService { @Get("/certificates") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getCertificates(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("maxresults") Integer maxresults, @QueryParam("includePending") Boolean includePending, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getCertificates(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("/certificates") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getCertificatesSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("maxresults") Integer maxresults, @QueryParam("includePending") Boolean includePending, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getCertificatesSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Delete("/certificates/{certificate-name}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> deleteCertificate(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> deleteCertificate(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Delete("/certificates/{certificate-name}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response deleteCertificateSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response deleteCertificateSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Put("/certificates/contacts") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> setCertificateContacts(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @BodyParam("application/json") Contacts contacts, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> setCertificateContacts(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData contacts, + RequestOptions requestOptions, Context context); @Put("/certificates/contacts") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response setCertificateContactsSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @BodyParam("application/json") Contacts contacts, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response setCertificateContactsSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData contacts, + RequestOptions requestOptions, Context context); @Get("/certificates/contacts") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getCertificateContacts(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getCertificateContacts(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("/certificates/contacts") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getCertificateContactsSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getCertificateContactsSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Delete("/certificates/contacts") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> deleteCertificateContacts(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> deleteCertificateContacts(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Delete("/certificates/contacts") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response deleteCertificateContactsSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response deleteCertificateContactsSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("/certificates/issuers") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getCertificateIssuers( - @HostParam("vaultBaseUrl") String vaultBaseUrl, @QueryParam("maxresults") Integer maxresults, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getCertificateIssuers(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("/certificates/issuers") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getCertificateIssuersSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("maxresults") Integer maxresults, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getCertificateIssuersSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Put("/certificates/issuers/{issuer-name}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> setCertificateIssuer(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("issuer-name") String issuerName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") CertificateIssuerSetParameters parameter, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> setCertificateIssuer(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("issuer-name") String issuerName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData parameter, RequestOptions requestOptions, Context context); @Put("/certificates/issuers/{issuer-name}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response setCertificateIssuerSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("issuer-name") String issuerName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") CertificateIssuerSetParameters parameter, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response setCertificateIssuerSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("issuer-name") String issuerName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData parameter, RequestOptions requestOptions, Context context); @Patch("/certificates/issuers/{issuer-name}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> updateCertificateIssuer(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("issuer-name") String issuerName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") CertificateIssuerUpdateParameters parameter, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> updateCertificateIssuer(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("issuer-name") String issuerName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData parameter, RequestOptions requestOptions, Context context); @Patch("/certificates/issuers/{issuer-name}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response updateCertificateIssuerSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("issuer-name") String issuerName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") CertificateIssuerUpdateParameters parameter, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response updateCertificateIssuerSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("issuer-name") String issuerName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData parameter, RequestOptions requestOptions, Context context); @Get("/certificates/issuers/{issuer-name}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getCertificateIssuer(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("issuer-name") String issuerName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getCertificateIssuer(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("issuer-name") String issuerName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Get("/certificates/issuers/{issuer-name}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getCertificateIssuerSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("issuer-name") String issuerName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getCertificateIssuerSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("issuer-name") String issuerName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Delete("/certificates/issuers/{issuer-name}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> deleteCertificateIssuer(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("issuer-name") String issuerName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> deleteCertificateIssuer(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("issuer-name") String issuerName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Delete("/certificates/issuers/{issuer-name}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response deleteCertificateIssuerSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("issuer-name") String issuerName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response deleteCertificateIssuerSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("issuer-name") String issuerName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Post("/certificates/{certificate-name}/create") @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> createCertificate(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") CertificateCreateParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> createCertificate(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData parameters, RequestOptions requestOptions, Context context); @Post("/certificates/{certificate-name}/create") @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response createCertificateSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") CertificateCreateParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response createCertificateSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData parameters, RequestOptions requestOptions, Context context); @Post("/certificates/{certificate-name}/import") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> importCertificate(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") CertificateImportParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> importCertificate(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData parameters, RequestOptions requestOptions, Context context); @Post("/certificates/{certificate-name}/import") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response importCertificateSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") CertificateImportParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response importCertificateSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData parameters, RequestOptions requestOptions, Context context); @Get("/certificates/{certificate-name}/versions") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getCertificateVersions(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, @QueryParam("maxresults") Integer maxresults, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getCertificateVersions(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Get("/certificates/{certificate-name}/versions") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getCertificateVersionsSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, @QueryParam("maxresults") Integer maxresults, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getCertificateVersionsSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Get("/certificates/{certificate-name}/policy") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getCertificatePolicy(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getCertificatePolicy(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Get("/certificates/{certificate-name}/policy") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getCertificatePolicySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getCertificatePolicySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Patch("/certificates/{certificate-name}/policy") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> updateCertificatePolicy(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") CertificatePolicy certificatePolicy, @HeaderParam("Accept") String accept, + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> updateCertificatePolicy(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData certificatePolicy, RequestOptions requestOptions, Context context); @Patch("/certificates/{certificate-name}/policy") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response updateCertificatePolicySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") CertificatePolicy certificatePolicy, @HeaderParam("Accept") String accept, + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response updateCertificatePolicySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData certificatePolicy, RequestOptions requestOptions, Context context); @Patch("/certificates/{certificate-name}/{certificate-version}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> updateCertificate(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, - @PathParam("certificate-version") String certificateVersion, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") CertificateUpdateParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> updateCertificate(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @PathParam("certificate-version") String certificateVersion, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData parameters, RequestOptions requestOptions, Context context); @Patch("/certificates/{certificate-name}/{certificate-version}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response updateCertificateSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, - @PathParam("certificate-version") String certificateVersion, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") CertificateUpdateParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response updateCertificateSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @PathParam("certificate-version") String certificateVersion, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData parameters, RequestOptions requestOptions, Context context); @Get("/certificates/{certificate-name}/{certificate-version}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getCertificate(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, - @PathParam("certificate-version") String certificateVersion, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getCertificate(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @PathParam("certificate-version") String certificateVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("/certificates/{certificate-name}/{certificate-version}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getCertificateSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, - @PathParam("certificate-version") String certificateVersion, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getCertificateSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @PathParam("certificate-version") String certificateVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Patch("/certificates/{certificate-name}/pending") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> updateCertificateOperation(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") CertificateOperationUpdateParameter certificateOperation, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> updateCertificateOperation(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData certificateOperation, RequestOptions requestOptions, + Context context); @Patch("/certificates/{certificate-name}/pending") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response updateCertificateOperationSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") CertificateOperationUpdateParameter certificateOperation, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response updateCertificateOperationSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData certificateOperation, RequestOptions requestOptions, + Context context); @Get("/certificates/{certificate-name}/pending") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getCertificateOperation(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getCertificateOperation(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Get("/certificates/{certificate-name}/pending") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getCertificateOperationSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getCertificateOperationSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Delete("/certificates/{certificate-name}/pending") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> deleteCertificateOperation(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> deleteCertificateOperation(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Delete("/certificates/{certificate-name}/pending") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response deleteCertificateOperationSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response deleteCertificateOperationSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Post("/certificates/{certificate-name}/pending/merge") @ExpectedResponses({ 201 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> mergeCertificate(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") CertificateMergeParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> mergeCertificate(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData parameters, RequestOptions requestOptions, Context context); @Post("/certificates/{certificate-name}/pending/merge") @ExpectedResponses({ 201 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response mergeCertificateSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") CertificateMergeParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response mergeCertificateSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData parameters, RequestOptions requestOptions, Context context); @Post("/certificates/{certificate-name}/backup") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> backupCertificate(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> backupCertificate(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Post("/certificates/{certificate-name}/backup") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response backupCertificateSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response backupCertificateSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Post("/certificates/restore") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> restoreCertificate(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") CertificateRestoreParameters parameters, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> restoreCertificate(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Post("/certificates/restore") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response restoreCertificateSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") CertificateRestoreParameters parameters, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response restoreCertificateSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Get("/deletedcertificates") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getDeletedCertificates( - @HostParam("vaultBaseUrl") String vaultBaseUrl, @QueryParam("maxresults") Integer maxresults, - @QueryParam("includePending") Boolean includePending, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getDeletedCertificates(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("/deletedcertificates") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getDeletedCertificatesSync( - @HostParam("vaultBaseUrl") String vaultBaseUrl, @QueryParam("maxresults") Integer maxresults, - @QueryParam("includePending") Boolean includePending, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getDeletedCertificatesSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("/deletedcertificates/{certificate-name}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getDeletedCertificate(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getDeletedCertificate(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Get("/deletedcertificates/{certificate-name}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getDeletedCertificateSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getDeletedCertificateSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Delete("/deletedcertificates/{certificate-name}") @ExpectedResponses({ 204 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) Mono> purgeDeletedCertificate(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Delete("/deletedcertificates/{certificate-name}") @ExpectedResponses({ 204 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) Response purgeDeletedCertificateSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Post("/deletedcertificates/{certificate-name}/recover") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> recoverDeletedCertificate(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> recoverDeletedCertificate(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Post("/deletedcertificates/{certificate-name}/recover") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response recoverDeletedCertificateSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("certificate-name") String certificateName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response recoverDeletedCertificateSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("certificate-name") String certificateName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Get("{nextLink}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getCertificatesNext( - @PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getCertificatesNext(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("{nextLink}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getCertificatesNextSync( - @PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getCertificatesNextSync(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("{nextLink}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getCertificateIssuersNext( + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getCertificateIssuersNext( @PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); + @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("{nextLink}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getCertificateIssuersNextSync( + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getCertificateIssuersNextSync( @PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); + @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("{nextLink}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getCertificateVersionsNext( + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getCertificateVersionsNext( @PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); + @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("{nextLink}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getCertificateVersionsNextSync( + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getCertificateVersionsNextSync( @PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); + @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("{nextLink}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getDeletedCertificatesNext( + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getDeletedCertificatesNext( @PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); + @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("{nextLink}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getDeletedCertificatesNextSync( + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getDeletedCertificatesNextSync( @PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); + @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); } /** @@ -616,72 +817,54 @@ Response getDeletedCertificatesNextSync( * * The GetCertificates operation returns the set of certificates resources in the specified key vault. This * operation requires the certificates/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param includePending Specifies whether to include certificates which are not completely provisioned. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + *

          Query Parameters

          + * + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          includePendingBooleanNoSpecifies whether to include certificates which are not + * completely provisioned.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     x5t: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the certificate list result along with {@link PagedResponse} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getCertificatesSinglePageAsync(String vaultBaseUrl, Integer maxresults, - Boolean includePending) { + private Mono> getCertificatesSinglePageAsync(RequestOptions requestOptions) { final String accept = "application/json"; return FluxUtil - .withContext(context -> service.getCertificates(vaultBaseUrl, maxresults, includePending, - this.getApiVersion(), accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * List certificates in a specified key vault - * - * The GetCertificates operation returns the set of certificates resources in the specified key vault. This - * operation requires the certificates/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param includePending Specifies whether to include certificates which are not completely provisioned. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the certificate list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getCertificatesSinglePageAsync(String vaultBaseUrl, Integer maxresults, - Boolean includePending, Context context) { - final String accept = "application/json"; - return service.getCertificates(vaultBaseUrl, maxresults, includePending, this.getApiVersion(), accept, context) + .withContext(context -> service.getCertificates(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), accept, requestOptions, context)) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * List certificates in a specified key vault - * - * The GetCertificates operation returns the set of certificates resources in the specified key vault. This - * operation requires the certificates/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param includePending Specifies whether to include certificates which are not completely provisioned. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the certificate list result as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getCertificatesAsync(String vaultBaseUrl, Integer maxresults, - Boolean includePending) { - return new PagedFlux<>(() -> getCertificatesSinglePageAsync(vaultBaseUrl, maxresults, includePending), - nextLink -> getCertificatesNextSinglePageAsync(nextLink, vaultBaseUrl)); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } /** @@ -689,47 +872,53 @@ public PagedFlux getCertificatesAsync(String vaultBaseUrl, Inte * * The GetCertificates operation returns the set of certificates resources in the specified key vault. This * operation requires the certificates/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param includePending Specifies whether to include certificates which are not completely provisioned. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + *

          Query Parameters

          + * + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          includePendingBooleanNoSpecifies whether to include certificates which are not + * completely provisioned.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     x5t: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the certificate list result as paginated response with {@link PagedFlux}. */ @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getCertificatesAsync(String vaultBaseUrl, Integer maxresults, - Boolean includePending, Context context) { - return new PagedFlux<>(() -> getCertificatesSinglePageAsync(vaultBaseUrl, maxresults, includePending, context), - nextLink -> getCertificatesNextSinglePageAsync(nextLink, vaultBaseUrl, context)); - } - - /** - * List certificates in a specified key vault - * - * The GetCertificates operation returns the set of certificates resources in the specified key vault. This - * operation requires the certificates/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param includePending Specifies whether to include certificates which are not completely provisioned. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the certificate list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getCertificatesSinglePage(String vaultBaseUrl, Integer maxresults, - Boolean includePending) { - final String accept = "application/json"; - Response res = service.getCertificatesSync(vaultBaseUrl, maxresults, includePending, - this.getApiVersion(), accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); + public PagedFlux getCertificatesAsync(RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedFlux<>(() -> getCertificatesSinglePageAsync(requestOptions), + nextLink -> getCertificatesNextSinglePageAsync(nextLink, requestOptionsForNextPage)); } /** @@ -737,48 +926,53 @@ public PagedResponse getCertificatesSinglePage(String vaultBase * * The GetCertificates operation returns the set of certificates resources in the specified key vault. This * operation requires the certificates/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param includePending Specifies whether to include certificates which are not completely provisioned. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + *

          Query Parameters

          + * + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          includePendingBooleanNoSpecifies whether to include certificates which are not + * completely provisioned.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     x5t: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the certificate list result along with {@link PagedResponse}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getCertificatesSinglePage(String vaultBaseUrl, Integer maxresults, - Boolean includePending, Context context) { + private PagedResponse getCertificatesSinglePage(RequestOptions requestOptions) { final String accept = "application/json"; - Response res = service.getCertificatesSync(vaultBaseUrl, maxresults, includePending, - this.getApiVersion(), accept, context); + Response res = service.getCertificatesSync(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), accept, requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * List certificates in a specified key vault - * - * The GetCertificates operation returns the set of certificates resources in the specified key vault. This - * operation requires the certificates/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param includePending Specifies whether to include certificates which are not completely provisioned. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the certificate list result as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getCertificates(String vaultBaseUrl, Integer maxresults, - Boolean includePending) { - return new PagedIterable<>( - () -> getCertificatesSinglePage(vaultBaseUrl, maxresults, includePending, Context.NONE), - nextLink -> getCertificatesNextSinglePage(nextLink, vaultBaseUrl)); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } /** @@ -786,22 +980,53 @@ public PagedIterable getCertificates(String vaultBaseUrl, Integ * * The GetCertificates operation returns the set of certificates resources in the specified key vault. This * operation requires the certificates/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param includePending Specifies whether to include certificates which are not completely provisioned. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + *

          Query Parameters

          + * + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          includePendingBooleanNoSpecifies whether to include certificates which are not + * completely provisioned.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     x5t: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the certificate list result as paginated response with {@link PagedIterable}. */ @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getCertificates(String vaultBaseUrl, Integer maxresults, - Boolean includePending, Context context) { - return new PagedIterable<>(() -> getCertificatesSinglePage(vaultBaseUrl, maxresults, includePending, context), - nextLink -> getCertificatesNextSinglePage(nextLink, vaultBaseUrl, context)); + public PagedIterable getCertificates(RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedIterable<>(() -> getCertificatesSinglePage(requestOptions), + nextLink -> getCertificatesNextSinglePage(nextLink, requestOptionsForNextPage)); } /** @@ -810,20 +1035,102 @@ public PagedIterable getCertificates(String vaultBaseUrl, Integ * Deletes all versions of a certificate object along with its associated policy. Delete certificate cannot be used * to remove individual versions of a certificate object. This operation requires the certificates/delete * permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     kid: String (Optional)
          +     *     sid: String (Optional)
          +     *     x5t: Base64Url (Optional)
          +     *     policy (Optional): {
          +     *         id: String (Optional)
          +     *         key_props (Optional): {
          +     *             exportable: Boolean (Optional)
          +     *             kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *             key_size: Integer (Optional)
          +     *             reuse_key: Boolean (Optional)
          +     *             crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         }
          +     *         secret_props (Optional): {
          +     *             contentType: String (Optional)
          +     *         }
          +     *         x509_props (Optional): {
          +     *             subject: String (Optional)
          +     *             ekus (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             sans (Optional): {
          +     *                 emails (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dns_names (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 upns (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *             }
          +     *             key_usage (Optional): [
          +     *                 String(digitalSignature/nonRepudiation/keyEncipherment/dataEncipherment/keyAgreement/keyCertSign/cRLSign/encipherOnly/decipherOnly) (Optional)
          +     *             ]
          +     *             validity_months: Integer (Optional)
          +     *         }
          +     *         lifetime_actions (Optional): [
          +     *              (Optional){
          +     *                 trigger (Optional): {
          +     *                     lifetime_percentage: Integer (Optional)
          +     *                     days_before_expiry: Integer (Optional)
          +     *                 }
          +     *                 action (Optional): {
          +     *                     action_type: String(EmailContacts/AutoRenew) (Optional)
          +     *                 }
          +     *             }
          +     *         ]
          +     *         issuer (Optional): {
          +     *             name: String (Optional)
          +     *             cty: String (Optional)
          +     *             cert_transparency: Boolean (Optional)
          +     *         }
          +     *         attributes (Optional): {
          +     *             enabled: Boolean (Optional)
          +     *             nbf: Long (Optional)
          +     *             exp: Long (Optional)
          +     *             created: Long (Optional)
          +     *             updated: Long (Optional)
          +     *             recoverableDays: Integer (Optional)
          +     *             recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         }
          +     *     }
          +     *     cer: byte[] (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): (recursive schema, see attributes above)
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param certificateName The name of the certificate. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a Deleted Certificate consisting of its previous id, attributes and its tags, as well as information on * when it will be purged along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteCertificateWithResponseAsync(String vaultBaseUrl, - String certificateName) { - return FluxUtil - .withContext(context -> deleteCertificateWithResponseAsync(vaultBaseUrl, certificateName, context)); + public Mono> deleteCertificateWithResponseAsync(String certificateName, + RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.deleteCertificate(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), certificateName, accept, requestOptions, context)); } /** @@ -832,3559 +1139,4222 @@ public Mono> deleteCertificateWithResponseAsy * Deletes all versions of a certificate object along with its associated policy. Delete certificate cannot be used * to remove individual versions of a certificate object. This operation requires the certificates/delete * permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     kid: String (Optional)
          +     *     sid: String (Optional)
          +     *     x5t: Base64Url (Optional)
          +     *     policy (Optional): {
          +     *         id: String (Optional)
          +     *         key_props (Optional): {
          +     *             exportable: Boolean (Optional)
          +     *             kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *             key_size: Integer (Optional)
          +     *             reuse_key: Boolean (Optional)
          +     *             crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         }
          +     *         secret_props (Optional): {
          +     *             contentType: String (Optional)
          +     *         }
          +     *         x509_props (Optional): {
          +     *             subject: String (Optional)
          +     *             ekus (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             sans (Optional): {
          +     *                 emails (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dns_names (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 upns (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *             }
          +     *             key_usage (Optional): [
          +     *                 String(digitalSignature/nonRepudiation/keyEncipherment/dataEncipherment/keyAgreement/keyCertSign/cRLSign/encipherOnly/decipherOnly) (Optional)
          +     *             ]
          +     *             validity_months: Integer (Optional)
          +     *         }
          +     *         lifetime_actions (Optional): [
          +     *              (Optional){
          +     *                 trigger (Optional): {
          +     *                     lifetime_percentage: Integer (Optional)
          +     *                     days_before_expiry: Integer (Optional)
          +     *                 }
          +     *                 action (Optional): {
          +     *                     action_type: String(EmailContacts/AutoRenew) (Optional)
          +     *                 }
          +     *             }
          +     *         ]
          +     *         issuer (Optional): {
          +     *             name: String (Optional)
          +     *             cty: String (Optional)
          +     *             cert_transparency: Boolean (Optional)
          +     *         }
          +     *         attributes (Optional): {
          +     *             enabled: Boolean (Optional)
          +     *             nbf: Long (Optional)
          +     *             exp: Long (Optional)
          +     *             created: Long (Optional)
          +     *             updated: Long (Optional)
          +     *             recoverableDays: Integer (Optional)
          +     *             recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         }
          +     *     }
          +     *     cer: byte[] (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): (recursive schema, see attributes above)
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param certificateName The name of the certificate. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a Deleted Certificate consisting of its previous id, attributes and its tags, as well as information on - * when it will be purged along with {@link Response} on successful completion of {@link Mono}. + * when it will be purged along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteCertificateWithResponseAsync(String vaultBaseUrl, - String certificateName, Context context) { + public Response deleteCertificateWithResponse(String certificateName, RequestOptions requestOptions) { final String accept = "application/json"; - return service.deleteCertificate(vaultBaseUrl, certificateName, this.getApiVersion(), accept, context); + return service.deleteCertificateSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + certificateName, accept, requestOptions, Context.NONE); } /** - * Deletes a certificate from a specified key vault. + * Sets the certificate contacts for the specified key vault. * - * Deletes all versions of a certificate object along with its associated policy. Delete certificate cannot be used - * to remove individual versions of a certificate object. This operation requires the certificates/delete - * permission. + * Sets the certificate contacts for the specified key vault. This operation requires the + * certificates/managecontacts permission. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     contacts (Optional): [
          +     *          (Optional){
          +     *             email: String (Optional)
          +     *             name: String (Optional)
          +     *             phone: String (Optional)
          +     *         }
          +     *     ]
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     contacts (Optional): [
          +     *          (Optional){
          +     *             email: String (Optional)
          +     *             name: String (Optional)
          +     *             phone: String (Optional)
          +     *         }
          +     *     ]
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Certificate consisting of its previous id, attributes and its tags, as well as information on - * when it will be purged on successful completion of {@link Mono}. + * @param contacts The contacts for the key vault certificate. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the contacts for the vault certificates along with {@link Response} on successful completion of + * {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteCertificateAsync(String vaultBaseUrl, String certificateName) { - return deleteCertificateWithResponseAsync(vaultBaseUrl, certificateName) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + public Mono> setCertificateContactsWithResponseAsync(BinaryData contacts, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.setCertificateContacts(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), contentType, accept, contacts, requestOptions, context)); } /** - * Deletes a certificate from a specified key vault. + * Sets the certificate contacts for the specified key vault. * - * Deletes all versions of a certificate object along with its associated policy. Delete certificate cannot be used - * to remove individual versions of a certificate object. This operation requires the certificates/delete - * permission. + * Sets the certificate contacts for the specified key vault. This operation requires the + * certificates/managecontacts permission. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     contacts (Optional): [
          +     *          (Optional){
          +     *             email: String (Optional)
          +     *             name: String (Optional)
          +     *             phone: String (Optional)
          +     *         }
          +     *     ]
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     contacts (Optional): [
          +     *          (Optional){
          +     *             email: String (Optional)
          +     *             name: String (Optional)
          +     *             phone: String (Optional)
          +     *         }
          +     *     ]
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Certificate consisting of its previous id, attributes and its tags, as well as information on - * when it will be purged on successful completion of {@link Mono}. + * @param contacts The contacts for the key vault certificate. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the contacts for the vault certificates along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteCertificateAsync(String vaultBaseUrl, String certificateName, - Context context) { - return deleteCertificateWithResponseAsync(vaultBaseUrl, certificateName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + public Response setCertificateContactsWithResponse(BinaryData contacts, RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return service.setCertificateContactsSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + contentType, accept, contacts, requestOptions, Context.NONE); } /** - * Deletes a certificate from a specified key vault. - * - * Deletes all versions of a certificate object along with its associated policy. Delete certificate cannot be used - * to remove individual versions of a certificate object. This operation requires the certificates/delete - * permission. + * Lists the certificate contacts for a specified key vault. * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Certificate consisting of its previous id, attributes and its tags, as well as information on - * when it will be purged along with {@link Response}. + * The GetCertificateContacts operation returns the set of certificate contact resources in the specified key vault. + * This operation requires the certificates/managecontacts permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     contacts (Optional): [
          +     *          (Optional){
          +     *             email: String (Optional)
          +     *             name: String (Optional)
          +     *             phone: String (Optional)
          +     *         }
          +     *     ]
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the contacts for the vault certificates along with {@link Response} on successful completion of + * {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteCertificateWithResponse(String vaultBaseUrl, String certificateName, - Context context) { + public Mono> getCertificateContactsWithResponseAsync(RequestOptions requestOptions) { final String accept = "application/json"; - return service.deleteCertificateSync(vaultBaseUrl, certificateName, this.getApiVersion(), accept, context); + return FluxUtil.withContext(context -> service.getCertificateContacts(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), accept, requestOptions, context)); } /** - * Deletes a certificate from a specified key vault. - * - * Deletes all versions of a certificate object along with its associated policy. Delete certificate cannot be used - * to remove individual versions of a certificate object. This operation requires the certificates/delete - * permission. + * Lists the certificate contacts for a specified key vault. * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Certificate consisting of its previous id, attributes and its tags, as well as information on - * when it will be purged. + * The GetCertificateContacts operation returns the set of certificate contact resources in the specified key vault. + * This operation requires the certificates/managecontacts permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     contacts (Optional): [
          +     *          (Optional){
          +     *             email: String (Optional)
          +     *             name: String (Optional)
          +     *             phone: String (Optional)
          +     *         }
          +     *     ]
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the contacts for the vault certificates along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public DeletedCertificateBundle deleteCertificate(String vaultBaseUrl, String certificateName) { - return deleteCertificateWithResponse(vaultBaseUrl, certificateName, Context.NONE).getValue(); + public Response getCertificateContactsWithResponse(RequestOptions requestOptions) { + final String accept = "application/json"; + return service.getCertificateContactsSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), accept, + requestOptions, Context.NONE); } /** - * Sets the certificate contacts for the specified key vault. + * Deletes the certificate contacts for a specified key vault. * - * Sets the certificate contacts for the specified key vault. This operation requires the + * Deletes the certificate contacts for a specified key vault certificate. This operation requires the * certificates/managecontacts permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param contacts The contacts for the key vault certificate. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     contacts (Optional): [
          +     *          (Optional){
          +     *             email: String (Optional)
          +     *             name: String (Optional)
          +     *             phone: String (Optional)
          +     *         }
          +     *     ]
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the contacts for the vault certificates along with {@link Response} on successful completion of * {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> setCertificateContactsWithResponseAsync(String vaultBaseUrl, Contacts contacts) { - return FluxUtil - .withContext(context -> setCertificateContactsWithResponseAsync(vaultBaseUrl, contacts, context)); + public Mono> deleteCertificateContactsWithResponseAsync(RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.deleteCertificateContacts(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), accept, requestOptions, context)); } /** - * Sets the certificate contacts for the specified key vault. + * Deletes the certificate contacts for a specified key vault. * - * Sets the certificate contacts for the specified key vault. This operation requires the + * Deletes the certificate contacts for a specified key vault certificate. This operation requires the * certificates/managecontacts permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param contacts The contacts for the key vault certificate. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the contacts for the vault certificates along with {@link Response} on successful completion of - * {@link Mono}. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     contacts (Optional): [
          +     *          (Optional){
          +     *             email: String (Optional)
          +     *             name: String (Optional)
          +     *             phone: String (Optional)
          +     *         }
          +     *     ]
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the contacts for the vault certificates along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> setCertificateContactsWithResponseAsync(String vaultBaseUrl, Contacts contacts, - Context context) { + public Response deleteCertificateContactsWithResponse(RequestOptions requestOptions) { final String accept = "application/json"; - return service.setCertificateContacts(vaultBaseUrl, this.getApiVersion(), contacts, accept, context); + return service.deleteCertificateContactsSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + accept, requestOptions, Context.NONE); } /** - * Sets the certificate contacts for the specified key vault. - * - * Sets the certificate contacts for the specified key vault. This operation requires the - * certificates/managecontacts permission. + * List certificate issuers for a specified key vault. * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param contacts The contacts for the key vault certificate. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the contacts for the vault certificates on successful completion of {@link Mono}. + * The GetCertificateIssuers operation returns the set of certificate issuer resources in the specified key vault. + * This operation requires the certificates/manageissuers/getissuers permission. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     provider: String (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the certificate issuer list result along with {@link PagedResponse} on successful completion of + * {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono setCertificateContactsAsync(String vaultBaseUrl, Contacts contacts) { - return setCertificateContactsWithResponseAsync(vaultBaseUrl, contacts) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + private Mono> getCertificateIssuersSinglePageAsync(RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.getCertificateIssuers(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), accept, requestOptions, context)) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } /** - * Sets the certificate contacts for the specified key vault. - * - * Sets the certificate contacts for the specified key vault. This operation requires the - * certificates/managecontacts permission. + * List certificate issuers for a specified key vault. * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param contacts The contacts for the key vault certificate. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the contacts for the vault certificates on successful completion of {@link Mono}. + * The GetCertificateIssuers operation returns the set of certificate issuer resources in the specified key vault. + * This operation requires the certificates/manageissuers/getissuers permission. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     provider: String (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the certificate issuer list result as paginated response with {@link PagedFlux}. */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono setCertificateContactsAsync(String vaultBaseUrl, Contacts contacts, Context context) { - return setCertificateContactsWithResponseAsync(vaultBaseUrl, contacts, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux getCertificateIssuersAsync(RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedFlux<>(() -> getCertificateIssuersSinglePageAsync(requestOptions), + nextLink -> getCertificateIssuersNextSinglePageAsync(nextLink, requestOptionsForNextPage)); } /** - * Sets the certificate contacts for the specified key vault. - * - * Sets the certificate contacts for the specified key vault. This operation requires the - * certificates/managecontacts permission. + * List certificate issuers for a specified key vault. * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param contacts The contacts for the key vault certificate. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the contacts for the vault certificates along with {@link Response}. + * The GetCertificateIssuers operation returns the set of certificate issuer resources in the specified key vault. + * This operation requires the certificates/manageissuers/getissuers permission. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     provider: String (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the certificate issuer list result along with {@link PagedResponse}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response setCertificateContactsWithResponse(String vaultBaseUrl, Contacts contacts, - Context context) { + private PagedResponse getCertificateIssuersSinglePage(RequestOptions requestOptions) { final String accept = "application/json"; - return service.setCertificateContactsSync(vaultBaseUrl, this.getApiVersion(), contacts, accept, context); + Response res = service.getCertificateIssuersSync(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), accept, requestOptions, Context.NONE); + return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } /** - * Sets the certificate contacts for the specified key vault. - * - * Sets the certificate contacts for the specified key vault. This operation requires the - * certificates/managecontacts permission. + * List certificate issuers for a specified key vault. * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param contacts The contacts for the key vault certificate. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the contacts for the vault certificates. + * The GetCertificateIssuers operation returns the set of certificate issuer resources in the specified key vault. + * This operation requires the certificates/manageissuers/getissuers permission. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     provider: String (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the certificate issuer list result as paginated response with {@link PagedIterable}. */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Contacts setCertificateContacts(String vaultBaseUrl, Contacts contacts) { - return setCertificateContactsWithResponse(vaultBaseUrl, contacts, Context.NONE).getValue(); + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable getCertificateIssuers(RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedIterable<>(() -> getCertificateIssuersSinglePage(requestOptions), + nextLink -> getCertificateIssuersNextSinglePage(nextLink, requestOptionsForNextPage)); } /** - * Lists the certificate contacts for a specified key vault. + * Sets the specified certificate issuer. * - * The GetCertificateContacts operation returns the set of certificate contact resources in the specified key vault. - * This operation requires the certificates/managecontacts permission. + * The SetCertificateIssuer operation adds or updates the specified certificate issuer. This operation requires the + * certificates/setissuers permission. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     provider: String (Required)
          +     *     credentials (Optional): {
          +     *         account_id: String (Optional)
          +     *         pwd: String (Optional)
          +     *     }
          +     *     org_details (Optional): {
          +     *         id: String (Optional)
          +     *         admin_details (Optional): [
          +     *              (Optional){
          +     *                 first_name: String (Optional)
          +     *                 last_name: String (Optional)
          +     *                 email: String (Optional)
          +     *                 phone: String (Optional)
          +     *             }
          +     *         ]
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     provider: String (Optional)
          +     *     credentials (Optional): {
          +     *         account_id: String (Optional)
          +     *         pwd: String (Optional)
          +     *     }
          +     *     org_details (Optional): {
          +     *         id: String (Optional)
          +     *         admin_details (Optional): [
          +     *              (Optional){
          +     *                 first_name: String (Optional)
          +     *                 last_name: String (Optional)
          +     *                 email: String (Optional)
          +     *                 phone: String (Optional)
          +     *             }
          +     *         ]
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the contacts for the vault certificates along with {@link Response} on successful completion of + * @param issuerName The name of the issuer. The value you provide may be copied globally for the purpose of running + * the service. The value provided should not include personally identifiable or sensitive information. + * @param parameter Certificate issuer set parameter. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the issuer for Key Vault certificate along with {@link Response} on successful completion of * {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getCertificateContactsWithResponseAsync(String vaultBaseUrl) { - return FluxUtil.withContext(context -> getCertificateContactsWithResponseAsync(vaultBaseUrl, context)); + public Mono> setCertificateIssuerWithResponseAsync(String issuerName, BinaryData parameter, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext( + context -> service.setCertificateIssuer(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + issuerName, contentType, accept, parameter, requestOptions, context)); } /** - * Lists the certificate contacts for a specified key vault. + * Sets the specified certificate issuer. * - * The GetCertificateContacts operation returns the set of certificate contact resources in the specified key vault. - * This operation requires the certificates/managecontacts permission. + * The SetCertificateIssuer operation adds or updates the specified certificate issuer. This operation requires the + * certificates/setissuers permission. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     provider: String (Required)
          +     *     credentials (Optional): {
          +     *         account_id: String (Optional)
          +     *         pwd: String (Optional)
          +     *     }
          +     *     org_details (Optional): {
          +     *         id: String (Optional)
          +     *         admin_details (Optional): [
          +     *              (Optional){
          +     *                 first_name: String (Optional)
          +     *                 last_name: String (Optional)
          +     *                 email: String (Optional)
          +     *                 phone: String (Optional)
          +     *             }
          +     *         ]
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     provider: String (Optional)
          +     *     credentials (Optional): {
          +     *         account_id: String (Optional)
          +     *         pwd: String (Optional)
          +     *     }
          +     *     org_details (Optional): {
          +     *         id: String (Optional)
          +     *         admin_details (Optional): [
          +     *              (Optional){
          +     *                 first_name: String (Optional)
          +     *                 last_name: String (Optional)
          +     *                 email: String (Optional)
          +     *                 phone: String (Optional)
          +     *             }
          +     *         ]
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the contacts for the vault certificates along with {@link Response} on successful completion of - * {@link Mono}. + * @param issuerName The name of the issuer. The value you provide may be copied globally for the purpose of running + * the service. The value provided should not include personally identifiable or sensitive information. + * @param parameter Certificate issuer set parameter. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the issuer for Key Vault certificate along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getCertificateContactsWithResponseAsync(String vaultBaseUrl, Context context) { + public Response setCertificateIssuerWithResponse(String issuerName, BinaryData parameter, + RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - return service.getCertificateContacts(vaultBaseUrl, this.getApiVersion(), accept, context); + return service.setCertificateIssuerSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + issuerName, contentType, accept, parameter, requestOptions, Context.NONE); } /** - * Lists the certificate contacts for a specified key vault. + * Updates the specified certificate issuer. * - * The GetCertificateContacts operation returns the set of certificate contact resources in the specified key vault. - * This operation requires the certificates/managecontacts permission. + * The UpdateCertificateIssuer operation performs an update on the specified certificate issuer entity. This + * operation requires the certificates/setissuers permission. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     provider: String (Optional)
          +     *     credentials (Optional): {
          +     *         account_id: String (Optional)
          +     *         pwd: String (Optional)
          +     *     }
          +     *     org_details (Optional): {
          +     *         id: String (Optional)
          +     *         admin_details (Optional): [
          +     *              (Optional){
          +     *                 first_name: String (Optional)
          +     *                 last_name: String (Optional)
          +     *                 email: String (Optional)
          +     *                 phone: String (Optional)
          +     *             }
          +     *         ]
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     provider: String (Optional)
          +     *     credentials (Optional): {
          +     *         account_id: String (Optional)
          +     *         pwd: String (Optional)
          +     *     }
          +     *     org_details (Optional): {
          +     *         id: String (Optional)
          +     *         admin_details (Optional): [
          +     *              (Optional){
          +     *                 first_name: String (Optional)
          +     *                 last_name: String (Optional)
          +     *                 email: String (Optional)
          +     *                 phone: String (Optional)
          +     *             }
          +     *         ]
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the contacts for the vault certificates on successful completion of {@link Mono}. + * @param issuerName The name of the issuer. + * @param parameter Certificate issuer update parameter. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the issuer for Key Vault certificate along with {@link Response} on successful completion of + * {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getCertificateContactsAsync(String vaultBaseUrl) { - return getCertificateContactsWithResponseAsync(vaultBaseUrl).flatMap(res -> Mono.justOrEmpty(res.getValue())); + public Mono> updateCertificateIssuerWithResponseAsync(String issuerName, BinaryData parameter, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext( + context -> service.updateCertificateIssuer(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + issuerName, contentType, accept, parameter, requestOptions, context)); } /** - * Lists the certificate contacts for a specified key vault. + * Updates the specified certificate issuer. * - * The GetCertificateContacts operation returns the set of certificate contact resources in the specified key vault. - * This operation requires the certificates/managecontacts permission. + * The UpdateCertificateIssuer operation performs an update on the specified certificate issuer entity. This + * operation requires the certificates/setissuers permission. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     provider: String (Optional)
          +     *     credentials (Optional): {
          +     *         account_id: String (Optional)
          +     *         pwd: String (Optional)
          +     *     }
          +     *     org_details (Optional): {
          +     *         id: String (Optional)
          +     *         admin_details (Optional): [
          +     *              (Optional){
          +     *                 first_name: String (Optional)
          +     *                 last_name: String (Optional)
          +     *                 email: String (Optional)
          +     *                 phone: String (Optional)
          +     *             }
          +     *         ]
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     provider: String (Optional)
          +     *     credentials (Optional): {
          +     *         account_id: String (Optional)
          +     *         pwd: String (Optional)
          +     *     }
          +     *     org_details (Optional): {
          +     *         id: String (Optional)
          +     *         admin_details (Optional): [
          +     *              (Optional){
          +     *                 first_name: String (Optional)
          +     *                 last_name: String (Optional)
          +     *                 email: String (Optional)
          +     *                 phone: String (Optional)
          +     *             }
          +     *         ]
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the contacts for the vault certificates on successful completion of {@link Mono}. + * @param issuerName The name of the issuer. + * @param parameter Certificate issuer update parameter. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the issuer for Key Vault certificate along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getCertificateContactsAsync(String vaultBaseUrl, Context context) { - return getCertificateContactsWithResponseAsync(vaultBaseUrl, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + public Response updateCertificateIssuerWithResponse(String issuerName, BinaryData parameter, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return service.updateCertificateIssuerSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + issuerName, contentType, accept, parameter, requestOptions, Context.NONE); } /** - * Lists the certificate contacts for a specified key vault. + * Lists the specified certificate issuer. * - * The GetCertificateContacts operation returns the set of certificate contact resources in the specified key vault. - * This operation requires the certificates/managecontacts permission. + * The GetCertificateIssuer operation returns the specified certificate issuer resources in the specified key vault. + * This operation requires the certificates/manageissuers/getissuers permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     provider: String (Optional)
          +     *     credentials (Optional): {
          +     *         account_id: String (Optional)
          +     *         pwd: String (Optional)
          +     *     }
          +     *     org_details (Optional): {
          +     *         id: String (Optional)
          +     *         admin_details (Optional): [
          +     *              (Optional){
          +     *                 first_name: String (Optional)
          +     *                 last_name: String (Optional)
          +     *                 email: String (Optional)
          +     *                 phone: String (Optional)
          +     *             }
          +     *         ]
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the contacts for the vault certificates along with {@link Response}. + * @param issuerName The name of the issuer. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the issuer for Key Vault certificate along with {@link Response} on successful completion of + * {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response getCertificateContactsWithResponse(String vaultBaseUrl, Context context) { + public Mono> getCertificateIssuerWithResponseAsync(String issuerName, + RequestOptions requestOptions) { final String accept = "application/json"; - return service.getCertificateContactsSync(vaultBaseUrl, this.getApiVersion(), accept, context); + return FluxUtil.withContext(context -> service.getCertificateIssuer(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), issuerName, accept, requestOptions, context)); } /** - * Lists the certificate contacts for a specified key vault. + * Lists the specified certificate issuer. * - * The GetCertificateContacts operation returns the set of certificate contact resources in the specified key vault. - * This operation requires the certificates/managecontacts permission. + * The GetCertificateIssuer operation returns the specified certificate issuer resources in the specified key vault. + * This operation requires the certificates/manageissuers/getissuers permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     provider: String (Optional)
          +     *     credentials (Optional): {
          +     *         account_id: String (Optional)
          +     *         pwd: String (Optional)
          +     *     }
          +     *     org_details (Optional): {
          +     *         id: String (Optional)
          +     *         admin_details (Optional): [
          +     *              (Optional){
          +     *                 first_name: String (Optional)
          +     *                 last_name: String (Optional)
          +     *                 email: String (Optional)
          +     *                 phone: String (Optional)
          +     *             }
          +     *         ]
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the contacts for the vault certificates. + * @param issuerName The name of the issuer. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the issuer for Key Vault certificate along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Contacts getCertificateContacts(String vaultBaseUrl) { - return getCertificateContactsWithResponse(vaultBaseUrl, Context.NONE).getValue(); + public Response getCertificateIssuerWithResponse(String issuerName, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.getCertificateIssuerSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + issuerName, accept, requestOptions, Context.NONE); } /** - * Deletes the certificate contacts for a specified key vault. - * - * Deletes the certificate contacts for a specified key vault certificate. This operation requires the - * certificates/managecontacts permission. + * Deletes the specified certificate issuer. * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the contacts for the vault certificates along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteCertificateContactsWithResponseAsync(String vaultBaseUrl) { - return FluxUtil.withContext(context -> deleteCertificateContactsWithResponseAsync(vaultBaseUrl, context)); - } - - /** - * Deletes the certificate contacts for a specified key vault. - * - * Deletes the certificate contacts for a specified key vault certificate. This operation requires the - * certificates/managecontacts permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the contacts for the vault certificates along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteCertificateContactsWithResponseAsync(String vaultBaseUrl, Context context) { - final String accept = "application/json"; - return service.deleteCertificateContacts(vaultBaseUrl, this.getApiVersion(), accept, context); - } - - /** - * Deletes the certificate contacts for a specified key vault. - * - * Deletes the certificate contacts for a specified key vault certificate. This operation requires the - * certificates/managecontacts permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the contacts for the vault certificates on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteCertificateContactsAsync(String vaultBaseUrl) { - return deleteCertificateContactsWithResponseAsync(vaultBaseUrl) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Deletes the certificate contacts for a specified key vault. - * - * Deletes the certificate contacts for a specified key vault certificate. This operation requires the - * certificates/managecontacts permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the contacts for the vault certificates on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteCertificateContactsAsync(String vaultBaseUrl, Context context) { - return deleteCertificateContactsWithResponseAsync(vaultBaseUrl, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Deletes the certificate contacts for a specified key vault. - * - * Deletes the certificate contacts for a specified key vault certificate. This operation requires the - * certificates/managecontacts permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the contacts for the vault certificates along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteCertificateContactsWithResponse(String vaultBaseUrl, Context context) { - final String accept = "application/json"; - return service.deleteCertificateContactsSync(vaultBaseUrl, this.getApiVersion(), accept, context); - } - - /** - * Deletes the certificate contacts for a specified key vault. - * - * Deletes the certificate contacts for a specified key vault certificate. This operation requires the - * certificates/managecontacts permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the contacts for the vault certificates. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Contacts deleteCertificateContacts(String vaultBaseUrl) { - return deleteCertificateContactsWithResponse(vaultBaseUrl, Context.NONE).getValue(); - } - - /** - * List certificate issuers for a specified key vault. - * - * The GetCertificateIssuers operation returns the set of certificate issuer resources in the specified key vault. - * This operation requires the certificates/manageissuers/getissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the certificate issuer list result along with {@link PagedResponse} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getCertificateIssuersSinglePageAsync(String vaultBaseUrl, - Integer maxresults) { - final String accept = "application/json"; - return FluxUtil.withContext( - context -> service.getCertificateIssuers(vaultBaseUrl, maxresults, this.getApiVersion(), accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * List certificate issuers for a specified key vault. - * - * The GetCertificateIssuers operation returns the set of certificate issuer resources in the specified key vault. - * This operation requires the certificates/manageissuers/getissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the certificate issuer list result along with {@link PagedResponse} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getCertificateIssuersSinglePageAsync(String vaultBaseUrl, - Integer maxresults, Context context) { - final String accept = "application/json"; - return service.getCertificateIssuers(vaultBaseUrl, maxresults, this.getApiVersion(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * List certificate issuers for a specified key vault. - * - * The GetCertificateIssuers operation returns the set of certificate issuer resources in the specified key vault. - * This operation requires the certificates/manageissuers/getissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the certificate issuer list result as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getCertificateIssuersAsync(String vaultBaseUrl, Integer maxresults) { - return new PagedFlux<>(() -> getCertificateIssuersSinglePageAsync(vaultBaseUrl, maxresults), - nextLink -> getCertificateIssuersNextSinglePageAsync(nextLink, vaultBaseUrl)); - } - - /** - * List certificate issuers for a specified key vault. - * - * The GetCertificateIssuers operation returns the set of certificate issuer resources in the specified key vault. - * This operation requires the certificates/manageissuers/getissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the certificate issuer list result as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getCertificateIssuersAsync(String vaultBaseUrl, Integer maxresults, - Context context) { - return new PagedFlux<>(() -> getCertificateIssuersSinglePageAsync(vaultBaseUrl, maxresults, context), - nextLink -> getCertificateIssuersNextSinglePageAsync(nextLink, vaultBaseUrl, context)); - } - - /** - * List certificate issuers for a specified key vault. - * - * The GetCertificateIssuers operation returns the set of certificate issuer resources in the specified key vault. - * This operation requires the certificates/manageissuers/getissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the certificate issuer list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getCertificateIssuersSinglePage(String vaultBaseUrl, - Integer maxresults) { - final String accept = "application/json"; - Response res - = service.getCertificateIssuersSync(vaultBaseUrl, maxresults, this.getApiVersion(), accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * List certificate issuers for a specified key vault. - * - * The GetCertificateIssuers operation returns the set of certificate issuer resources in the specified key vault. - * This operation requires the certificates/manageissuers/getissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the certificate issuer list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getCertificateIssuersSinglePage(String vaultBaseUrl, Integer maxresults, - Context context) { - final String accept = "application/json"; - Response res - = service.getCertificateIssuersSync(vaultBaseUrl, maxresults, this.getApiVersion(), accept, context); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * List certificate issuers for a specified key vault. - * - * The GetCertificateIssuers operation returns the set of certificate issuer resources in the specified key vault. - * This operation requires the certificates/manageissuers/getissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the certificate issuer list result as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getCertificateIssuers(String vaultBaseUrl, Integer maxresults) { - return new PagedIterable<>(() -> getCertificateIssuersSinglePage(vaultBaseUrl, maxresults, Context.NONE), - nextLink -> getCertificateIssuersNextSinglePage(nextLink, vaultBaseUrl)); - } - - /** - * List certificate issuers for a specified key vault. - * - * The GetCertificateIssuers operation returns the set of certificate issuer resources in the specified key vault. - * This operation requires the certificates/manageissuers/getissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the certificate issuer list result as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getCertificateIssuers(String vaultBaseUrl, Integer maxresults, - Context context) { - return new PagedIterable<>(() -> getCertificateIssuersSinglePage(vaultBaseUrl, maxresults, context), - nextLink -> getCertificateIssuersNextSinglePage(nextLink, vaultBaseUrl, context)); - } - - /** - * Sets the specified certificate issuer. - * - * The SetCertificateIssuer operation adds or updates the specified certificate issuer. This operation requires the - * certificates/setissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param issuerName The name of the issuer. The value you provide may be copied globally for the purpose of running - * the service. The value provided should not include personally identifiable or sensitive information. - * @param provider The issuer provider. - * @param credentials The credentials to be used for the issuer. - * @param organizationDetails Details of the organization as provided to the issuer. - * @param attributes Attributes of the issuer object. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the issuer for Key Vault certificate along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> setCertificateIssuerWithResponseAsync(String vaultBaseUrl, String issuerName, - String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, - IssuerAttributes attributes) { - return FluxUtil.withContext(context -> setCertificateIssuerWithResponseAsync(vaultBaseUrl, issuerName, provider, - credentials, organizationDetails, attributes, context)); - } - - /** - * Sets the specified certificate issuer. - * - * The SetCertificateIssuer operation adds or updates the specified certificate issuer. This operation requires the - * certificates/setissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param issuerName The name of the issuer. The value you provide may be copied globally for the purpose of running - * the service. The value provided should not include personally identifiable or sensitive information. - * @param provider The issuer provider. - * @param credentials The credentials to be used for the issuer. - * @param organizationDetails Details of the organization as provided to the issuer. - * @param attributes Attributes of the issuer object. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the issuer for Key Vault certificate along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> setCertificateIssuerWithResponseAsync(String vaultBaseUrl, String issuerName, - String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, - IssuerAttributes attributes, Context context) { - final String accept = "application/json"; - CertificateIssuerSetParameters parameter = new CertificateIssuerSetParameters(); - parameter.setProvider(provider); - parameter.setCredentials(credentials); - parameter.setOrganizationDetails(organizationDetails); - parameter.setAttributes(attributes); - return service.setCertificateIssuer(vaultBaseUrl, issuerName, this.getApiVersion(), parameter, accept, context); - } - - /** - * Sets the specified certificate issuer. - * - * The SetCertificateIssuer operation adds or updates the specified certificate issuer. This operation requires the - * certificates/setissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param issuerName The name of the issuer. The value you provide may be copied globally for the purpose of running - * the service. The value provided should not include personally identifiable or sensitive information. - * @param provider The issuer provider. - * @param credentials The credentials to be used for the issuer. - * @param organizationDetails Details of the organization as provided to the issuer. - * @param attributes Attributes of the issuer object. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the issuer for Key Vault certificate on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono setCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider, - IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes) { - return setCertificateIssuerWithResponseAsync(vaultBaseUrl, issuerName, provider, credentials, - organizationDetails, attributes).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Sets the specified certificate issuer. - * - * The SetCertificateIssuer operation adds or updates the specified certificate issuer. This operation requires the - * certificates/setissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param issuerName The name of the issuer. The value you provide may be copied globally for the purpose of running - * the service. The value provided should not include personally identifiable or sensitive information. - * @param provider The issuer provider. - * @param credentials The credentials to be used for the issuer. - * @param organizationDetails Details of the organization as provided to the issuer. - * @param attributes Attributes of the issuer object. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the issuer for Key Vault certificate on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono setCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider, - IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes, - Context context) { - return setCertificateIssuerWithResponseAsync(vaultBaseUrl, issuerName, provider, credentials, - organizationDetails, attributes, context).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Sets the specified certificate issuer. - * - * The SetCertificateIssuer operation adds or updates the specified certificate issuer. This operation requires the - * certificates/setissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param issuerName The name of the issuer. The value you provide may be copied globally for the purpose of running - * the service. The value provided should not include personally identifiable or sensitive information. - * @param provider The issuer provider. - * @param credentials The credentials to be used for the issuer. - * @param organizationDetails Details of the organization as provided to the issuer. - * @param attributes Attributes of the issuer object. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the issuer for Key Vault certificate along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response setCertificateIssuerWithResponse(String vaultBaseUrl, String issuerName, - String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, - IssuerAttributes attributes, Context context) { - final String accept = "application/json"; - CertificateIssuerSetParameters parameter = new CertificateIssuerSetParameters(); - parameter.setProvider(provider); - parameter.setCredentials(credentials); - parameter.setOrganizationDetails(organizationDetails); - parameter.setAttributes(attributes); - return service.setCertificateIssuerSync(vaultBaseUrl, issuerName, this.getApiVersion(), parameter, accept, - context); - } - - /** - * Sets the specified certificate issuer. - * - * The SetCertificateIssuer operation adds or updates the specified certificate issuer. This operation requires the - * certificates/setissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param issuerName The name of the issuer. The value you provide may be copied globally for the purpose of running - * the service. The value provided should not include personally identifiable or sensitive information. - * @param provider The issuer provider. - * @param credentials The credentials to be used for the issuer. - * @param organizationDetails Details of the organization as provided to the issuer. - * @param attributes Attributes of the issuer object. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the issuer for Key Vault certificate. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public IssuerBundle setCertificateIssuer(String vaultBaseUrl, String issuerName, String provider, - IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes) { - return setCertificateIssuerWithResponse(vaultBaseUrl, issuerName, provider, credentials, organizationDetails, - attributes, Context.NONE).getValue(); - } - - /** - * Updates the specified certificate issuer. - * - * The UpdateCertificateIssuer operation performs an update on the specified certificate issuer entity. This - * operation requires the certificates/setissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param issuerName The name of the issuer. - * @param provider The issuer provider. - * @param credentials The credentials to be used for the issuer. - * @param organizationDetails Details of the organization as provided to the issuer. - * @param attributes Attributes of the issuer object. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the issuer for Key Vault certificate along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> updateCertificateIssuerWithResponseAsync(String vaultBaseUrl, String issuerName, - String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, - IssuerAttributes attributes) { - return FluxUtil.withContext(context -> updateCertificateIssuerWithResponseAsync(vaultBaseUrl, issuerName, - provider, credentials, organizationDetails, attributes, context)); - } - - /** - * Updates the specified certificate issuer. - * - * The UpdateCertificateIssuer operation performs an update on the specified certificate issuer entity. This - * operation requires the certificates/setissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param issuerName The name of the issuer. - * @param provider The issuer provider. - * @param credentials The credentials to be used for the issuer. - * @param organizationDetails Details of the organization as provided to the issuer. - * @param attributes Attributes of the issuer object. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the issuer for Key Vault certificate along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> updateCertificateIssuerWithResponseAsync(String vaultBaseUrl, String issuerName, - String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, - IssuerAttributes attributes, Context context) { - final String accept = "application/json"; - CertificateIssuerUpdateParameters parameter = new CertificateIssuerUpdateParameters(); - parameter.setProvider(provider); - parameter.setCredentials(credentials); - parameter.setOrganizationDetails(organizationDetails); - parameter.setAttributes(attributes); - return service.updateCertificateIssuer(vaultBaseUrl, issuerName, this.getApiVersion(), parameter, accept, - context); - } - - /** - * Updates the specified certificate issuer. - * - * The UpdateCertificateIssuer operation performs an update on the specified certificate issuer entity. This - * operation requires the certificates/setissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param issuerName The name of the issuer. - * @param provider The issuer provider. - * @param credentials The credentials to be used for the issuer. - * @param organizationDetails Details of the organization as provided to the issuer. - * @param attributes Attributes of the issuer object. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the issuer for Key Vault certificate on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono updateCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider, - IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes) { - return updateCertificateIssuerWithResponseAsync(vaultBaseUrl, issuerName, provider, credentials, - organizationDetails, attributes).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Updates the specified certificate issuer. - * - * The UpdateCertificateIssuer operation performs an update on the specified certificate issuer entity. This - * operation requires the certificates/setissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param issuerName The name of the issuer. - * @param provider The issuer provider. - * @param credentials The credentials to be used for the issuer. - * @param organizationDetails Details of the organization as provided to the issuer. - * @param attributes Attributes of the issuer object. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the issuer for Key Vault certificate on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono updateCertificateIssuerAsync(String vaultBaseUrl, String issuerName, String provider, - IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes, - Context context) { - return updateCertificateIssuerWithResponseAsync(vaultBaseUrl, issuerName, provider, credentials, - organizationDetails, attributes, context).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Updates the specified certificate issuer. - * - * The UpdateCertificateIssuer operation performs an update on the specified certificate issuer entity. This - * operation requires the certificates/setissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param issuerName The name of the issuer. - * @param provider The issuer provider. - * @param credentials The credentials to be used for the issuer. - * @param organizationDetails Details of the organization as provided to the issuer. - * @param attributes Attributes of the issuer object. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the issuer for Key Vault certificate along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response updateCertificateIssuerWithResponse(String vaultBaseUrl, String issuerName, - String provider, IssuerCredentials credentials, OrganizationDetails organizationDetails, - IssuerAttributes attributes, Context context) { - final String accept = "application/json"; - CertificateIssuerUpdateParameters parameter = new CertificateIssuerUpdateParameters(); - parameter.setProvider(provider); - parameter.setCredentials(credentials); - parameter.setOrganizationDetails(organizationDetails); - parameter.setAttributes(attributes); - return service.updateCertificateIssuerSync(vaultBaseUrl, issuerName, this.getApiVersion(), parameter, accept, - context); - } - - /** - * Updates the specified certificate issuer. - * - * The UpdateCertificateIssuer operation performs an update on the specified certificate issuer entity. This - * operation requires the certificates/setissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param issuerName The name of the issuer. - * @param provider The issuer provider. - * @param credentials The credentials to be used for the issuer. - * @param organizationDetails Details of the organization as provided to the issuer. - * @param attributes Attributes of the issuer object. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the issuer for Key Vault certificate. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public IssuerBundle updateCertificateIssuer(String vaultBaseUrl, String issuerName, String provider, - IssuerCredentials credentials, OrganizationDetails organizationDetails, IssuerAttributes attributes) { - return updateCertificateIssuerWithResponse(vaultBaseUrl, issuerName, provider, credentials, organizationDetails, - attributes, Context.NONE).getValue(); - } - - /** - * Lists the specified certificate issuer. - * - * The GetCertificateIssuer operation returns the specified certificate issuer resources in the specified key vault. - * This operation requires the certificates/manageissuers/getissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param issuerName The name of the issuer. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the issuer for Key Vault certificate along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getCertificateIssuerWithResponseAsync(String vaultBaseUrl, String issuerName) { - return FluxUtil - .withContext(context -> getCertificateIssuerWithResponseAsync(vaultBaseUrl, issuerName, context)); - } - - /** - * Lists the specified certificate issuer. - * - * The GetCertificateIssuer operation returns the specified certificate issuer resources in the specified key vault. - * This operation requires the certificates/manageissuers/getissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param issuerName The name of the issuer. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the issuer for Key Vault certificate along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getCertificateIssuerWithResponseAsync(String vaultBaseUrl, String issuerName, - Context context) { - final String accept = "application/json"; - return service.getCertificateIssuer(vaultBaseUrl, issuerName, this.getApiVersion(), accept, context); - } - - /** - * Lists the specified certificate issuer. - * - * The GetCertificateIssuer operation returns the specified certificate issuer resources in the specified key vault. - * This operation requires the certificates/manageissuers/getissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param issuerName The name of the issuer. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the issuer for Key Vault certificate on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getCertificateIssuerAsync(String vaultBaseUrl, String issuerName) { - return getCertificateIssuerWithResponseAsync(vaultBaseUrl, issuerName) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Lists the specified certificate issuer. - * - * The GetCertificateIssuer operation returns the specified certificate issuer resources in the specified key vault. - * This operation requires the certificates/manageissuers/getissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param issuerName The name of the issuer. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the issuer for Key Vault certificate on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getCertificateIssuerAsync(String vaultBaseUrl, String issuerName, Context context) { - return getCertificateIssuerWithResponseAsync(vaultBaseUrl, issuerName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Lists the specified certificate issuer. - * - * The GetCertificateIssuer operation returns the specified certificate issuer resources in the specified key vault. - * This operation requires the certificates/manageissuers/getissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param issuerName The name of the issuer. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the issuer for Key Vault certificate along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getCertificateIssuerWithResponse(String vaultBaseUrl, String issuerName, - Context context) { - final String accept = "application/json"; - return service.getCertificateIssuerSync(vaultBaseUrl, issuerName, this.getApiVersion(), accept, context); - } - - /** - * Lists the specified certificate issuer. - * - * The GetCertificateIssuer operation returns the specified certificate issuer resources in the specified key vault. - * This operation requires the certificates/manageissuers/getissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param issuerName The name of the issuer. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the issuer for Key Vault certificate. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public IssuerBundle getCertificateIssuer(String vaultBaseUrl, String issuerName) { - return getCertificateIssuerWithResponse(vaultBaseUrl, issuerName, Context.NONE).getValue(); - } - - /** - * Deletes the specified certificate issuer. - * - * The DeleteCertificateIssuer operation permanently removes the specified certificate issuer from the vault. This - * operation requires the certificates/manageissuers/deleteissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param issuerName The name of the issuer. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the issuer for Key Vault certificate along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteCertificateIssuerWithResponseAsync(String vaultBaseUrl, - String issuerName) { - return FluxUtil - .withContext(context -> deleteCertificateIssuerWithResponseAsync(vaultBaseUrl, issuerName, context)); - } - - /** - * Deletes the specified certificate issuer. - * - * The DeleteCertificateIssuer operation permanently removes the specified certificate issuer from the vault. This - * operation requires the certificates/manageissuers/deleteissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param issuerName The name of the issuer. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the issuer for Key Vault certificate along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteCertificateIssuerWithResponseAsync(String vaultBaseUrl, String issuerName, - Context context) { - final String accept = "application/json"; - return service.deleteCertificateIssuer(vaultBaseUrl, issuerName, this.getApiVersion(), accept, context); - } - - /** - * Deletes the specified certificate issuer. - * - * The DeleteCertificateIssuer operation permanently removes the specified certificate issuer from the vault. This - * operation requires the certificates/manageissuers/deleteissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param issuerName The name of the issuer. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the issuer for Key Vault certificate on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteCertificateIssuerAsync(String vaultBaseUrl, String issuerName) { - return deleteCertificateIssuerWithResponseAsync(vaultBaseUrl, issuerName) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Deletes the specified certificate issuer. - * - * The DeleteCertificateIssuer operation permanently removes the specified certificate issuer from the vault. This - * operation requires the certificates/manageissuers/deleteissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param issuerName The name of the issuer. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the issuer for Key Vault certificate on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteCertificateIssuerAsync(String vaultBaseUrl, String issuerName, Context context) { - return deleteCertificateIssuerWithResponseAsync(vaultBaseUrl, issuerName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Deletes the specified certificate issuer. - * - * The DeleteCertificateIssuer operation permanently removes the specified certificate issuer from the vault. This - * operation requires the certificates/manageissuers/deleteissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param issuerName The name of the issuer. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the issuer for Key Vault certificate along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteCertificateIssuerWithResponse(String vaultBaseUrl, String issuerName, - Context context) { - final String accept = "application/json"; - return service.deleteCertificateIssuerSync(vaultBaseUrl, issuerName, this.getApiVersion(), accept, context); - } - - /** - * Deletes the specified certificate issuer. - * - * The DeleteCertificateIssuer operation permanently removes the specified certificate issuer from the vault. This - * operation requires the certificates/manageissuers/deleteissuers permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param issuerName The name of the issuer. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the issuer for Key Vault certificate. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public IssuerBundle deleteCertificateIssuer(String vaultBaseUrl, String issuerName) { - return deleteCertificateIssuerWithResponse(vaultBaseUrl, issuerName, Context.NONE).getValue(); - } - - /** - * Creates a new certificate. - * - * If this is the first version, the certificate resource is created. This operation requires the - * certificates/create permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. The value you provide may be copied globally for the purpose - * of running the service. The value provided should not include personally identifiable or sensitive information. - * @param certificatePolicy The management policy for the certificate. - * @param certificateAttributes The attributes of the certificate (optional). - * @param tags Application specific metadata in the form of key-value pairs. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate operation is returned in case of asynchronous requests along with {@link Response} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createCertificateWithResponseAsync(String vaultBaseUrl, - String certificateName, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, - Map tags) { - return FluxUtil.withContext(context -> createCertificateWithResponseAsync(vaultBaseUrl, certificateName, - certificatePolicy, certificateAttributes, tags, context)); - } - - /** - * Creates a new certificate. - * - * If this is the first version, the certificate resource is created. This operation requires the - * certificates/create permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. The value you provide may be copied globally for the purpose - * of running the service. The value provided should not include personally identifiable or sensitive information. - * @param certificatePolicy The management policy for the certificate. - * @param certificateAttributes The attributes of the certificate (optional). - * @param tags Application specific metadata in the form of key-value pairs. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate operation is returned in case of asynchronous requests along with {@link Response} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createCertificateWithResponseAsync(String vaultBaseUrl, - String certificateName, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, - Map tags, Context context) { - final String accept = "application/json"; - CertificateCreateParameters parameters = new CertificateCreateParameters(); - parameters.setCertificatePolicy(certificatePolicy); - parameters.setCertificateAttributes(certificateAttributes); - parameters.setTags(tags); - return service.createCertificate(vaultBaseUrl, certificateName, this.getApiVersion(), parameters, accept, - context); - } - - /** - * Creates a new certificate. - * - * If this is the first version, the certificate resource is created. This operation requires the - * certificates/create permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. The value you provide may be copied globally for the purpose - * of running the service. The value provided should not include personally identifiable or sensitive information. - * @param certificatePolicy The management policy for the certificate. - * @param certificateAttributes The attributes of the certificate (optional). - * @param tags Application specific metadata in the form of key-value pairs. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate operation is returned in case of asynchronous requests on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createCertificateAsync(String vaultBaseUrl, String certificateName, - CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) { - return createCertificateWithResponseAsync(vaultBaseUrl, certificateName, certificatePolicy, - certificateAttributes, tags).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new certificate. - * - * If this is the first version, the certificate resource is created. This operation requires the - * certificates/create permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. The value you provide may be copied globally for the purpose - * of running the service. The value provided should not include personally identifiable or sensitive information. - * @param certificatePolicy The management policy for the certificate. - * @param certificateAttributes The attributes of the certificate (optional). - * @param tags Application specific metadata in the form of key-value pairs. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate operation is returned in case of asynchronous requests on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createCertificateAsync(String vaultBaseUrl, String certificateName, - CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags, - Context context) { - return createCertificateWithResponseAsync(vaultBaseUrl, certificateName, certificatePolicy, - certificateAttributes, tags, context).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new certificate. - * - * If this is the first version, the certificate resource is created. This operation requires the - * certificates/create permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. The value you provide may be copied globally for the purpose - * of running the service. The value provided should not include personally identifiable or sensitive information. - * @param certificatePolicy The management policy for the certificate. - * @param certificateAttributes The attributes of the certificate (optional). - * @param tags Application specific metadata in the form of key-value pairs. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate operation is returned in case of asynchronous requests along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createCertificateWithResponse(String vaultBaseUrl, String certificateName, - CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags, - Context context) { - final String accept = "application/json"; - CertificateCreateParameters parameters = new CertificateCreateParameters(); - parameters.setCertificatePolicy(certificatePolicy); - parameters.setCertificateAttributes(certificateAttributes); - parameters.setTags(tags); - return service.createCertificateSync(vaultBaseUrl, certificateName, this.getApiVersion(), parameters, accept, - context); - } - - /** - * Creates a new certificate. - * - * If this is the first version, the certificate resource is created. This operation requires the - * certificates/create permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. The value you provide may be copied globally for the purpose - * of running the service. The value provided should not include personally identifiable or sensitive information. - * @param certificatePolicy The management policy for the certificate. - * @param certificateAttributes The attributes of the certificate (optional). - * @param tags Application specific metadata in the form of key-value pairs. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate operation is returned in case of asynchronous requests. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public CertificateOperation createCertificate(String vaultBaseUrl, String certificateName, - CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) { - return createCertificateWithResponse(vaultBaseUrl, certificateName, certificatePolicy, certificateAttributes, - tags, Context.NONE).getValue(); - } - - /** - * Imports a certificate into a specified key vault. - * - * Imports an existing valid certificate, containing a private key, into Azure Key Vault. This operation requires - * the certificates/import permission. The certificate to be imported can be in either PFX or PEM format. If the - * certificate is in PEM format the PEM file must contain the key as well as x509 certificates. Key Vault will only - * accept a key in PKCS#8 format. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. The value you provide may be copied globally for the purpose - * of running the service. The value provided should not include personally identifiable or sensitive information. - * @param base64EncodedCertificate Base64 encoded representation of the certificate object to import. This - * certificate needs to contain the private key. - * @param password If the private key in base64EncodedCertificate is encrypted, the password used for encryption. - * @param certificatePolicy The management policy for the certificate. - * @param certificateAttributes The attributes of the certificate (optional). - * @param tags Application specific metadata in the form of key-value pairs. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate bundle consists of a certificate (X509) plus its attributes along with {@link Response} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> importCertificateWithResponseAsync(String vaultBaseUrl, - String certificateName, String base64EncodedCertificate, String password, CertificatePolicy certificatePolicy, - CertificateAttributes certificateAttributes, Map tags) { - return FluxUtil.withContext(context -> importCertificateWithResponseAsync(vaultBaseUrl, certificateName, - base64EncodedCertificate, password, certificatePolicy, certificateAttributes, tags, context)); - } - - /** - * Imports a certificate into a specified key vault. - * - * Imports an existing valid certificate, containing a private key, into Azure Key Vault. This operation requires - * the certificates/import permission. The certificate to be imported can be in either PFX or PEM format. If the - * certificate is in PEM format the PEM file must contain the key as well as x509 certificates. Key Vault will only - * accept a key in PKCS#8 format. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. The value you provide may be copied globally for the purpose - * of running the service. The value provided should not include personally identifiable or sensitive information. - * @param base64EncodedCertificate Base64 encoded representation of the certificate object to import. This - * certificate needs to contain the private key. - * @param password If the private key in base64EncodedCertificate is encrypted, the password used for encryption. - * @param certificatePolicy The management policy for the certificate. - * @param certificateAttributes The attributes of the certificate (optional). - * @param tags Application specific metadata in the form of key-value pairs. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate bundle consists of a certificate (X509) plus its attributes along with {@link Response} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> importCertificateWithResponseAsync(String vaultBaseUrl, - String certificateName, String base64EncodedCertificate, String password, CertificatePolicy certificatePolicy, - CertificateAttributes certificateAttributes, Map tags, Context context) { - final String accept = "application/json"; - CertificateImportParameters parameters = new CertificateImportParameters(); - parameters.setBase64EncodedCertificate(base64EncodedCertificate); - parameters.setPassword(password); - parameters.setCertificatePolicy(certificatePolicy); - parameters.setCertificateAttributes(certificateAttributes); - parameters.setTags(tags); - return service.importCertificate(vaultBaseUrl, certificateName, this.getApiVersion(), parameters, accept, - context); - } - - /** - * Imports a certificate into a specified key vault. - * - * Imports an existing valid certificate, containing a private key, into Azure Key Vault. This operation requires - * the certificates/import permission. The certificate to be imported can be in either PFX or PEM format. If the - * certificate is in PEM format the PEM file must contain the key as well as x509 certificates. Key Vault will only - * accept a key in PKCS#8 format. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. The value you provide may be copied globally for the purpose - * of running the service. The value provided should not include personally identifiable or sensitive information. - * @param base64EncodedCertificate Base64 encoded representation of the certificate object to import. This - * certificate needs to contain the private key. - * @param password If the private key in base64EncodedCertificate is encrypted, the password used for encryption. - * @param certificatePolicy The management policy for the certificate. - * @param certificateAttributes The attributes of the certificate (optional). - * @param tags Application specific metadata in the form of key-value pairs. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate bundle consists of a certificate (X509) plus its attributes on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono importCertificateAsync(String vaultBaseUrl, String certificateName, - String base64EncodedCertificate, String password, CertificatePolicy certificatePolicy, - CertificateAttributes certificateAttributes, Map tags) { - return importCertificateWithResponseAsync(vaultBaseUrl, certificateName, base64EncodedCertificate, password, - certificatePolicy, certificateAttributes, tags).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Imports a certificate into a specified key vault. - * - * Imports an existing valid certificate, containing a private key, into Azure Key Vault. This operation requires - * the certificates/import permission. The certificate to be imported can be in either PFX or PEM format. If the - * certificate is in PEM format the PEM file must contain the key as well as x509 certificates. Key Vault will only - * accept a key in PKCS#8 format. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. The value you provide may be copied globally for the purpose - * of running the service. The value provided should not include personally identifiable or sensitive information. - * @param base64EncodedCertificate Base64 encoded representation of the certificate object to import. This - * certificate needs to contain the private key. - * @param password If the private key in base64EncodedCertificate is encrypted, the password used for encryption. - * @param certificatePolicy The management policy for the certificate. - * @param certificateAttributes The attributes of the certificate (optional). - * @param tags Application specific metadata in the form of key-value pairs. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate bundle consists of a certificate (X509) plus its attributes on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono importCertificateAsync(String vaultBaseUrl, String certificateName, - String base64EncodedCertificate, String password, CertificatePolicy certificatePolicy, - CertificateAttributes certificateAttributes, Map tags, Context context) { - return importCertificateWithResponseAsync(vaultBaseUrl, certificateName, base64EncodedCertificate, password, - certificatePolicy, certificateAttributes, tags, context).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Imports a certificate into a specified key vault. - * - * Imports an existing valid certificate, containing a private key, into Azure Key Vault. This operation requires - * the certificates/import permission. The certificate to be imported can be in either PFX or PEM format. If the - * certificate is in PEM format the PEM file must contain the key as well as x509 certificates. Key Vault will only - * accept a key in PKCS#8 format. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. The value you provide may be copied globally for the purpose - * of running the service. The value provided should not include personally identifiable or sensitive information. - * @param base64EncodedCertificate Base64 encoded representation of the certificate object to import. This - * certificate needs to contain the private key. - * @param password If the private key in base64EncodedCertificate is encrypted, the password used for encryption. - * @param certificatePolicy The management policy for the certificate. - * @param certificateAttributes The attributes of the certificate (optional). - * @param tags Application specific metadata in the form of key-value pairs. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate bundle consists of a certificate (X509) plus its attributes along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response importCertificateWithResponse(String vaultBaseUrl, String certificateName, - String base64EncodedCertificate, String password, CertificatePolicy certificatePolicy, - CertificateAttributes certificateAttributes, Map tags, Context context) { - final String accept = "application/json"; - CertificateImportParameters parameters = new CertificateImportParameters(); - parameters.setBase64EncodedCertificate(base64EncodedCertificate); - parameters.setPassword(password); - parameters.setCertificatePolicy(certificatePolicy); - parameters.setCertificateAttributes(certificateAttributes); - parameters.setTags(tags); - return service.importCertificateSync(vaultBaseUrl, certificateName, this.getApiVersion(), parameters, accept, - context); - } - - /** - * Imports a certificate into a specified key vault. - * - * Imports an existing valid certificate, containing a private key, into Azure Key Vault. This operation requires - * the certificates/import permission. The certificate to be imported can be in either PFX or PEM format. If the - * certificate is in PEM format the PEM file must contain the key as well as x509 certificates. Key Vault will only - * accept a key in PKCS#8 format. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. The value you provide may be copied globally for the purpose - * of running the service. The value provided should not include personally identifiable or sensitive information. - * @param base64EncodedCertificate Base64 encoded representation of the certificate object to import. This - * certificate needs to contain the private key. - * @param password If the private key in base64EncodedCertificate is encrypted, the password used for encryption. - * @param certificatePolicy The management policy for the certificate. - * @param certificateAttributes The attributes of the certificate (optional). - * @param tags Application specific metadata in the form of key-value pairs. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate bundle consists of a certificate (X509) plus its attributes. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public CertificateBundle importCertificate(String vaultBaseUrl, String certificateName, - String base64EncodedCertificate, String password, CertificatePolicy certificatePolicy, - CertificateAttributes certificateAttributes, Map tags) { - return importCertificateWithResponse(vaultBaseUrl, certificateName, base64EncodedCertificate, password, - certificatePolicy, certificateAttributes, tags, Context.NONE).getValue(); - } - - /** - * List the versions of a certificate. - * - * The GetCertificateVersions operation returns the versions of a certificate in the specified key vault. This - * operation requires the certificates/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the certificate list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getCertificateVersionsSinglePageAsync(String vaultBaseUrl, - String certificateName, Integer maxresults) { - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.getCertificateVersions(vaultBaseUrl, certificateName, maxresults, - this.getApiVersion(), accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * List the versions of a certificate. - * - * The GetCertificateVersions operation returns the versions of a certificate in the specified key vault. This - * operation requires the certificates/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the certificate list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getCertificateVersionsSinglePageAsync(String vaultBaseUrl, - String certificateName, Integer maxresults, Context context) { - final String accept = "application/json"; - return service - .getCertificateVersions(vaultBaseUrl, certificateName, maxresults, this.getApiVersion(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * List the versions of a certificate. - * - * The GetCertificateVersions operation returns the versions of a certificate in the specified key vault. This - * operation requires the certificates/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the certificate list result as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getCertificateVersionsAsync(String vaultBaseUrl, String certificateName, - Integer maxresults) { - return new PagedFlux<>(() -> getCertificateVersionsSinglePageAsync(vaultBaseUrl, certificateName, maxresults), - nextLink -> getCertificateVersionsNextSinglePageAsync(nextLink, vaultBaseUrl)); - } - - /** - * List the versions of a certificate. - * - * The GetCertificateVersions operation returns the versions of a certificate in the specified key vault. This - * operation requires the certificates/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the certificate list result as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getCertificateVersionsAsync(String vaultBaseUrl, String certificateName, - Integer maxresults, Context context) { - return new PagedFlux<>( - () -> getCertificateVersionsSinglePageAsync(vaultBaseUrl, certificateName, maxresults, context), - nextLink -> getCertificateVersionsNextSinglePageAsync(nextLink, vaultBaseUrl, context)); - } - - /** - * List the versions of a certificate. - * - * The GetCertificateVersions operation returns the versions of a certificate in the specified key vault. This - * operation requires the certificates/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the certificate list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getCertificateVersionsSinglePage(String vaultBaseUrl, String certificateName, - Integer maxresults) { - final String accept = "application/json"; - Response res = service.getCertificateVersionsSync(vaultBaseUrl, certificateName, - maxresults, this.getApiVersion(), accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * List the versions of a certificate. - * - * The GetCertificateVersions operation returns the versions of a certificate in the specified key vault. This - * operation requires the certificates/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the certificate list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getCertificateVersionsSinglePage(String vaultBaseUrl, String certificateName, - Integer maxresults, Context context) { - final String accept = "application/json"; - Response res = service.getCertificateVersionsSync(vaultBaseUrl, certificateName, - maxresults, this.getApiVersion(), accept, context); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * List the versions of a certificate. - * - * The GetCertificateVersions operation returns the versions of a certificate in the specified key vault. This - * operation requires the certificates/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the certificate list result as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getCertificateVersions(String vaultBaseUrl, String certificateName, - Integer maxresults) { - return new PagedIterable<>( - () -> getCertificateVersionsSinglePage(vaultBaseUrl, certificateName, maxresults, Context.NONE), - nextLink -> getCertificateVersionsNextSinglePage(nextLink, vaultBaseUrl)); - } - - /** - * List the versions of a certificate. - * - * The GetCertificateVersions operation returns the versions of a certificate in the specified key vault. This - * operation requires the certificates/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the certificate list result as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getCertificateVersions(String vaultBaseUrl, String certificateName, - Integer maxresults, Context context) { - return new PagedIterable<>( - () -> getCertificateVersionsSinglePage(vaultBaseUrl, certificateName, maxresults, context), - nextLink -> getCertificateVersionsNextSinglePage(nextLink, vaultBaseUrl, context)); - } - - /** - * Lists the policy for a certificate. - * - * The GetCertificatePolicy operation returns the specified certificate policy resources in the specified key vault. - * This operation requires the certificates/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate in a given key vault. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a certificate along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getCertificatePolicyWithResponseAsync(String vaultBaseUrl, - String certificateName) { - return FluxUtil - .withContext(context -> getCertificatePolicyWithResponseAsync(vaultBaseUrl, certificateName, context)); - } - - /** - * Lists the policy for a certificate. - * - * The GetCertificatePolicy operation returns the specified certificate policy resources in the specified key vault. - * This operation requires the certificates/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate in a given key vault. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a certificate along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getCertificatePolicyWithResponseAsync(String vaultBaseUrl, - String certificateName, Context context) { - final String accept = "application/json"; - return service.getCertificatePolicy(vaultBaseUrl, certificateName, this.getApiVersion(), accept, context); - } - - /** - * Lists the policy for a certificate. - * - * The GetCertificatePolicy operation returns the specified certificate policy resources in the specified key vault. - * This operation requires the certificates/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate in a given key vault. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a certificate on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getCertificatePolicyAsync(String vaultBaseUrl, String certificateName) { - return getCertificatePolicyWithResponseAsync(vaultBaseUrl, certificateName) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Lists the policy for a certificate. - * - * The GetCertificatePolicy operation returns the specified certificate policy resources in the specified key vault. - * This operation requires the certificates/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate in a given key vault. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a certificate on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getCertificatePolicyAsync(String vaultBaseUrl, String certificateName, - Context context) { - return getCertificatePolicyWithResponseAsync(vaultBaseUrl, certificateName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Lists the policy for a certificate. - * - * The GetCertificatePolicy operation returns the specified certificate policy resources in the specified key vault. - * This operation requires the certificates/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate in a given key vault. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a certificate along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getCertificatePolicyWithResponse(String vaultBaseUrl, String certificateName, - Context context) { - final String accept = "application/json"; - return service.getCertificatePolicySync(vaultBaseUrl, certificateName, this.getApiVersion(), accept, context); - } - - /** - * Lists the policy for a certificate. - * - * The GetCertificatePolicy operation returns the specified certificate policy resources in the specified key vault. - * This operation requires the certificates/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate in a given key vault. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a certificate. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public CertificatePolicy getCertificatePolicy(String vaultBaseUrl, String certificateName) { - return getCertificatePolicyWithResponse(vaultBaseUrl, certificateName, Context.NONE).getValue(); - } - - /** - * Updates the policy for a certificate. - * - * Set specified members in the certificate policy. Leave others as null. This operation requires the - * certificates/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate in the given vault. - * @param certificatePolicy The policy for the certificate. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a certificate along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> updateCertificatePolicyWithResponseAsync(String vaultBaseUrl, - String certificateName, CertificatePolicy certificatePolicy) { - return FluxUtil.withContext(context -> updateCertificatePolicyWithResponseAsync(vaultBaseUrl, certificateName, - certificatePolicy, context)); - } - - /** - * Updates the policy for a certificate. - * - * Set specified members in the certificate policy. Leave others as null. This operation requires the - * certificates/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate in the given vault. - * @param certificatePolicy The policy for the certificate. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a certificate along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> updateCertificatePolicyWithResponseAsync(String vaultBaseUrl, - String certificateName, CertificatePolicy certificatePolicy, Context context) { - final String accept = "application/json"; - return service.updateCertificatePolicy(vaultBaseUrl, certificateName, this.getApiVersion(), certificatePolicy, - accept, context); - } - - /** - * Updates the policy for a certificate. - * - * Set specified members in the certificate policy. Leave others as null. This operation requires the - * certificates/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate in the given vault. - * @param certificatePolicy The policy for the certificate. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a certificate on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono updateCertificatePolicyAsync(String vaultBaseUrl, String certificateName, - CertificatePolicy certificatePolicy) { - return updateCertificatePolicyWithResponseAsync(vaultBaseUrl, certificateName, certificatePolicy) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Updates the policy for a certificate. - * - * Set specified members in the certificate policy. Leave others as null. This operation requires the - * certificates/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate in the given vault. - * @param certificatePolicy The policy for the certificate. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a certificate on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono updateCertificatePolicyAsync(String vaultBaseUrl, String certificateName, - CertificatePolicy certificatePolicy, Context context) { - return updateCertificatePolicyWithResponseAsync(vaultBaseUrl, certificateName, certificatePolicy, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Updates the policy for a certificate. - * - * Set specified members in the certificate policy. Leave others as null. This operation requires the - * certificates/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate in the given vault. - * @param certificatePolicy The policy for the certificate. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a certificate along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response updateCertificatePolicyWithResponse(String vaultBaseUrl, String certificateName, - CertificatePolicy certificatePolicy, Context context) { - final String accept = "application/json"; - return service.updateCertificatePolicySync(vaultBaseUrl, certificateName, this.getApiVersion(), - certificatePolicy, accept, context); - } - - /** - * Updates the policy for a certificate. - * - * Set specified members in the certificate policy. Leave others as null. This operation requires the - * certificates/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate in the given vault. - * @param certificatePolicy The policy for the certificate. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a certificate. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public CertificatePolicy updateCertificatePolicy(String vaultBaseUrl, String certificateName, - CertificatePolicy certificatePolicy) { - return updateCertificatePolicyWithResponse(vaultBaseUrl, certificateName, certificatePolicy, Context.NONE) - .getValue(); - } - - /** - * Updates the specified attributes associated with the given certificate. - * - * The UpdateCertificate operation applies the specified update on the given certificate; the only elements updated - * are the certificate's attributes. This operation requires the certificates/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate in the given key vault. - * @param certificateVersion The version of the certificate. - * @param certificatePolicy The management policy for the certificate. - * @param certificateAttributes The attributes of the certificate (optional). - * @param tags Application specific metadata in the form of key-value pairs. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate bundle consists of a certificate (X509) plus its attributes along with {@link Response} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> updateCertificateWithResponseAsync(String vaultBaseUrl, - String certificateName, String certificateVersion, CertificatePolicy certificatePolicy, - CertificateAttributes certificateAttributes, Map tags) { - return FluxUtil.withContext(context -> updateCertificateWithResponseAsync(vaultBaseUrl, certificateName, - certificateVersion, certificatePolicy, certificateAttributes, tags, context)); - } - - /** - * Updates the specified attributes associated with the given certificate. - * - * The UpdateCertificate operation applies the specified update on the given certificate; the only elements updated - * are the certificate's attributes. This operation requires the certificates/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate in the given key vault. - * @param certificateVersion The version of the certificate. - * @param certificatePolicy The management policy for the certificate. - * @param certificateAttributes The attributes of the certificate (optional). - * @param tags Application specific metadata in the form of key-value pairs. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate bundle consists of a certificate (X509) plus its attributes along with {@link Response} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> updateCertificateWithResponseAsync(String vaultBaseUrl, - String certificateName, String certificateVersion, CertificatePolicy certificatePolicy, - CertificateAttributes certificateAttributes, Map tags, Context context) { - final String accept = "application/json"; - CertificateUpdateParameters parameters = new CertificateUpdateParameters(); - parameters.setCertificatePolicy(certificatePolicy); - parameters.setCertificateAttributes(certificateAttributes); - parameters.setTags(tags); - return service.updateCertificate(vaultBaseUrl, certificateName, certificateVersion, this.getApiVersion(), - parameters, accept, context); - } - - /** - * Updates the specified attributes associated with the given certificate. - * - * The UpdateCertificate operation applies the specified update on the given certificate; the only elements updated - * are the certificate's attributes. This operation requires the certificates/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate in the given key vault. - * @param certificateVersion The version of the certificate. - * @param certificatePolicy The management policy for the certificate. - * @param certificateAttributes The attributes of the certificate (optional). - * @param tags Application specific metadata in the form of key-value pairs. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate bundle consists of a certificate (X509) plus its attributes on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono updateCertificateAsync(String vaultBaseUrl, String certificateName, - String certificateVersion, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, - Map tags) { - return updateCertificateWithResponseAsync(vaultBaseUrl, certificateName, certificateVersion, certificatePolicy, - certificateAttributes, tags).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Updates the specified attributes associated with the given certificate. - * - * The UpdateCertificate operation applies the specified update on the given certificate; the only elements updated - * are the certificate's attributes. This operation requires the certificates/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate in the given key vault. - * @param certificateVersion The version of the certificate. - * @param certificatePolicy The management policy for the certificate. - * @param certificateAttributes The attributes of the certificate (optional). - * @param tags Application specific metadata in the form of key-value pairs. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate bundle consists of a certificate (X509) plus its attributes on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono updateCertificateAsync(String vaultBaseUrl, String certificateName, - String certificateVersion, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, - Map tags, Context context) { - return updateCertificateWithResponseAsync(vaultBaseUrl, certificateName, certificateVersion, certificatePolicy, - certificateAttributes, tags, context).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Updates the specified attributes associated with the given certificate. - * - * The UpdateCertificate operation applies the specified update on the given certificate; the only elements updated - * are the certificate's attributes. This operation requires the certificates/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate in the given key vault. - * @param certificateVersion The version of the certificate. - * @param certificatePolicy The management policy for the certificate. - * @param certificateAttributes The attributes of the certificate (optional). - * @param tags Application specific metadata in the form of key-value pairs. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate bundle consists of a certificate (X509) plus its attributes along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response updateCertificateWithResponse(String vaultBaseUrl, String certificateName, - String certificateVersion, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, - Map tags, Context context) { - final String accept = "application/json"; - CertificateUpdateParameters parameters = new CertificateUpdateParameters(); - parameters.setCertificatePolicy(certificatePolicy); - parameters.setCertificateAttributes(certificateAttributes); - parameters.setTags(tags); - return service.updateCertificateSync(vaultBaseUrl, certificateName, certificateVersion, this.getApiVersion(), - parameters, accept, context); - } - - /** - * Updates the specified attributes associated with the given certificate. - * - * The UpdateCertificate operation applies the specified update on the given certificate; the only elements updated - * are the certificate's attributes. This operation requires the certificates/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate in the given key vault. - * @param certificateVersion The version of the certificate. - * @param certificatePolicy The management policy for the certificate. - * @param certificateAttributes The attributes of the certificate (optional). - * @param tags Application specific metadata in the form of key-value pairs. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate bundle consists of a certificate (X509) plus its attributes. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public CertificateBundle updateCertificate(String vaultBaseUrl, String certificateName, String certificateVersion, - CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map tags) { - return updateCertificateWithResponse(vaultBaseUrl, certificateName, certificateVersion, certificatePolicy, - certificateAttributes, tags, Context.NONE).getValue(); - } - - /** - * Gets information about a certificate. - * - * Gets information about a specific certificate. This operation requires the certificates/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate in the given vault. - * @param certificateVersion The version of the certificate. This URI fragment is optional. If not specified, the - * latest version of the certificate is returned. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return information about a specific certificate along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getCertificateWithResponseAsync(String vaultBaseUrl, - String certificateName, String certificateVersion) { - return FluxUtil.withContext( - context -> getCertificateWithResponseAsync(vaultBaseUrl, certificateName, certificateVersion, context)); - } - - /** - * Gets information about a certificate. - * - * Gets information about a specific certificate. This operation requires the certificates/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate in the given vault. - * @param certificateVersion The version of the certificate. This URI fragment is optional. If not specified, the - * latest version of the certificate is returned. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return information about a specific certificate along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getCertificateWithResponseAsync(String vaultBaseUrl, - String certificateName, String certificateVersion, Context context) { - final String accept = "application/json"; - return service.getCertificate(vaultBaseUrl, certificateName, certificateVersion, this.getApiVersion(), accept, - context); - } - - /** - * Gets information about a certificate. - * - * Gets information about a specific certificate. This operation requires the certificates/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate in the given vault. - * @param certificateVersion The version of the certificate. This URI fragment is optional. If not specified, the - * latest version of the certificate is returned. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return information about a specific certificate on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getCertificateAsync(String vaultBaseUrl, String certificateName, - String certificateVersion) { - return getCertificateWithResponseAsync(vaultBaseUrl, certificateName, certificateVersion) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Gets information about a certificate. - * - * Gets information about a specific certificate. This operation requires the certificates/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate in the given vault. - * @param certificateVersion The version of the certificate. This URI fragment is optional. If not specified, the - * latest version of the certificate is returned. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return information about a specific certificate on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getCertificateAsync(String vaultBaseUrl, String certificateName, - String certificateVersion, Context context) { - return getCertificateWithResponseAsync(vaultBaseUrl, certificateName, certificateVersion, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Gets information about a certificate. - * - * Gets information about a specific certificate. This operation requires the certificates/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate in the given vault. - * @param certificateVersion The version of the certificate. This URI fragment is optional. If not specified, the - * latest version of the certificate is returned. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return information about a specific certificate along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getCertificateWithResponse(String vaultBaseUrl, String certificateName, - String certificateVersion, Context context) { - final String accept = "application/json"; - return service.getCertificateSync(vaultBaseUrl, certificateName, certificateVersion, this.getApiVersion(), - accept, context); - } - - /** - * Gets information about a certificate. - * - * Gets information about a specific certificate. This operation requires the certificates/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate in the given vault. - * @param certificateVersion The version of the certificate. This URI fragment is optional. If not specified, the - * latest version of the certificate is returned. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return information about a specific certificate. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public CertificateBundle getCertificate(String vaultBaseUrl, String certificateName, String certificateVersion) { - return getCertificateWithResponse(vaultBaseUrl, certificateName, certificateVersion, Context.NONE).getValue(); - } - - /** - * Updates a certificate operation. - * - * Updates a certificate creation operation that is already in progress. This operation requires the - * certificates/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param cancellationRequested Indicates if cancellation was requested on the certificate operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate operation is returned in case of asynchronous requests along with {@link Response} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> updateCertificateOperationWithResponseAsync(String vaultBaseUrl, - String certificateName, boolean cancellationRequested) { - return FluxUtil.withContext(context -> updateCertificateOperationWithResponseAsync(vaultBaseUrl, - certificateName, cancellationRequested, context)); - } - - /** - * Updates a certificate operation. - * - * Updates a certificate creation operation that is already in progress. This operation requires the - * certificates/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param cancellationRequested Indicates if cancellation was requested on the certificate operation. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate operation is returned in case of asynchronous requests along with {@link Response} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> updateCertificateOperationWithResponseAsync(String vaultBaseUrl, - String certificateName, boolean cancellationRequested, Context context) { - final String accept = "application/json"; - CertificateOperationUpdateParameter certificateOperation = new CertificateOperationUpdateParameter(); - certificateOperation.setCancellationRequested(cancellationRequested); - return service.updateCertificateOperation(vaultBaseUrl, certificateName, this.getApiVersion(), - certificateOperation, accept, context); - } - - /** - * Updates a certificate operation. - * - * Updates a certificate creation operation that is already in progress. This operation requires the - * certificates/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param cancellationRequested Indicates if cancellation was requested on the certificate operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate operation is returned in case of asynchronous requests on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono updateCertificateOperationAsync(String vaultBaseUrl, String certificateName, - boolean cancellationRequested) { - return updateCertificateOperationWithResponseAsync(vaultBaseUrl, certificateName, cancellationRequested) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Updates a certificate operation. - * - * Updates a certificate creation operation that is already in progress. This operation requires the - * certificates/update permission. + * The DeleteCertificateIssuer operation permanently removes the specified certificate issuer from the vault. This + * operation requires the certificates/manageissuers/deleteissuers permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     provider: String (Optional)
          +     *     credentials (Optional): {
          +     *         account_id: String (Optional)
          +     *         pwd: String (Optional)
          +     *     }
          +     *     org_details (Optional): {
          +     *         id: String (Optional)
          +     *         admin_details (Optional): [
          +     *              (Optional){
          +     *                 first_name: String (Optional)
          +     *                 last_name: String (Optional)
          +     *                 email: String (Optional)
          +     *                 phone: String (Optional)
          +     *             }
          +     *         ]
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param cancellationRequested Indicates if cancellation was requested on the certificate operation. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate operation is returned in case of asynchronous requests on successful completion of + * @param issuerName The name of the issuer. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the issuer for Key Vault certificate along with {@link Response} on successful completion of * {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono updateCertificateOperationAsync(String vaultBaseUrl, String certificateName, - boolean cancellationRequested, Context context) { - return updateCertificateOperationWithResponseAsync(vaultBaseUrl, certificateName, cancellationRequested, - context).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Updates a certificate operation. - * - * Updates a certificate creation operation that is already in progress. This operation requires the - * certificates/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param cancellationRequested Indicates if cancellation was requested on the certificate operation. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate operation is returned in case of asynchronous requests along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response updateCertificateOperationWithResponse(String vaultBaseUrl, - String certificateName, boolean cancellationRequested, Context context) { - final String accept = "application/json"; - CertificateOperationUpdateParameter certificateOperation = new CertificateOperationUpdateParameter(); - certificateOperation.setCancellationRequested(cancellationRequested); - return service.updateCertificateOperationSync(vaultBaseUrl, certificateName, this.getApiVersion(), - certificateOperation, accept, context); - } - - /** - * Updates a certificate operation. - * - * Updates a certificate creation operation that is already in progress. This operation requires the - * certificates/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param cancellationRequested Indicates if cancellation was requested on the certificate operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate operation is returned in case of asynchronous requests. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public CertificateOperation updateCertificateOperation(String vaultBaseUrl, String certificateName, - boolean cancellationRequested) { - return updateCertificateOperationWithResponse(vaultBaseUrl, certificateName, cancellationRequested, - Context.NONE).getValue(); - } - - /** - * Gets the creation operation of a certificate. - * - * Gets the creation operation associated with a specified certificate. This operation requires the certificates/get - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the creation operation associated with a specified certificate along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getCertificateOperationWithResponseAsync(String vaultBaseUrl, - String certificateName) { - return FluxUtil - .withContext(context -> getCertificateOperationWithResponseAsync(vaultBaseUrl, certificateName, context)); - } - - /** - * Gets the creation operation of a certificate. - * - * Gets the creation operation associated with a specified certificate. This operation requires the certificates/get - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the creation operation associated with a specified certificate along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getCertificateOperationWithResponseAsync(String vaultBaseUrl, - String certificateName, Context context) { + public Mono> deleteCertificateIssuerWithResponseAsync(String issuerName, + RequestOptions requestOptions) { final String accept = "application/json"; - return service.getCertificateOperation(vaultBaseUrl, certificateName, this.getApiVersion(), accept, context); - } - - /** - * Gets the creation operation of a certificate. - * - * Gets the creation operation associated with a specified certificate. This operation requires the certificates/get - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the creation operation associated with a specified certificate on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getCertificateOperationAsync(String vaultBaseUrl, String certificateName) { - return getCertificateOperationWithResponseAsync(vaultBaseUrl, certificateName) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Gets the creation operation of a certificate. - * - * Gets the creation operation associated with a specified certificate. This operation requires the certificates/get - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the creation operation associated with a specified certificate on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getCertificateOperationAsync(String vaultBaseUrl, String certificateName, - Context context) { - return getCertificateOperationWithResponseAsync(vaultBaseUrl, certificateName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + return FluxUtil.withContext(context -> service.deleteCertificateIssuer(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), issuerName, accept, requestOptions, context)); } /** - * Gets the creation operation of a certificate. + * Deletes the specified certificate issuer. * - * Gets the creation operation associated with a specified certificate. This operation requires the certificates/get - * permission. + * The DeleteCertificateIssuer operation permanently removes the specified certificate issuer from the vault. This + * operation requires the certificates/manageissuers/deleteissuers permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     provider: String (Optional)
          +     *     credentials (Optional): {
          +     *         account_id: String (Optional)
          +     *         pwd: String (Optional)
          +     *     }
          +     *     org_details (Optional): {
          +     *         id: String (Optional)
          +     *         admin_details (Optional): [
          +     *              (Optional){
          +     *                 first_name: String (Optional)
          +     *                 last_name: String (Optional)
          +     *                 email: String (Optional)
          +     *                 phone: String (Optional)
          +     *             }
          +     *         ]
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the creation operation associated with a specified certificate along with {@link Response}. + * @param issuerName The name of the issuer. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the issuer for Key Vault certificate along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response getCertificateOperationWithResponse(String vaultBaseUrl, - String certificateName, Context context) { + public Response deleteCertificateIssuerWithResponse(String issuerName, RequestOptions requestOptions) { final String accept = "application/json"; - return service.getCertificateOperationSync(vaultBaseUrl, certificateName, this.getApiVersion(), accept, - context); - } - - /** - * Gets the creation operation of a certificate. - * - * Gets the creation operation associated with a specified certificate. This operation requires the certificates/get - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the creation operation associated with a specified certificate. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public CertificateOperation getCertificateOperation(String vaultBaseUrl, String certificateName) { - return getCertificateOperationWithResponse(vaultBaseUrl, certificateName, Context.NONE).getValue(); - } - - /** - * Deletes the creation operation for a specific certificate. - * - * Deletes the creation operation for a specified certificate that is in the process of being created. The - * certificate is no longer created. This operation requires the certificates/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate operation is returned in case of asynchronous requests along with {@link Response} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteCertificateOperationWithResponseAsync(String vaultBaseUrl, - String certificateName) { - return FluxUtil.withContext( - context -> deleteCertificateOperationWithResponseAsync(vaultBaseUrl, certificateName, context)); + return service.deleteCertificateIssuerSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + issuerName, accept, requestOptions, Context.NONE); } /** - * Deletes the creation operation for a specific certificate. + * Creates a new certificate. * - * Deletes the creation operation for a specified certificate that is in the process of being created. The - * certificate is no longer created. This operation requires the certificates/update permission. + * If this is the first version, the certificate resource is created. This operation requires the + * certificates/create permission. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     policy (Optional): {
          +     *         id: String (Optional)
          +     *         key_props (Optional): {
          +     *             exportable: Boolean (Optional)
          +     *             kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *             key_size: Integer (Optional)
          +     *             reuse_key: Boolean (Optional)
          +     *             crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         }
          +     *         secret_props (Optional): {
          +     *             contentType: String (Optional)
          +     *         }
          +     *         x509_props (Optional): {
          +     *             subject: String (Optional)
          +     *             ekus (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             sans (Optional): {
          +     *                 emails (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dns_names (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 upns (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *             }
          +     *             key_usage (Optional): [
          +     *                 String(digitalSignature/nonRepudiation/keyEncipherment/dataEncipherment/keyAgreement/keyCertSign/cRLSign/encipherOnly/decipherOnly) (Optional)
          +     *             ]
          +     *             validity_months: Integer (Optional)
          +     *         }
          +     *         lifetime_actions (Optional): [
          +     *              (Optional){
          +     *                 trigger (Optional): {
          +     *                     lifetime_percentage: Integer (Optional)
          +     *                     days_before_expiry: Integer (Optional)
          +     *                 }
          +     *                 action (Optional): {
          +     *                     action_type: String(EmailContacts/AutoRenew) (Optional)
          +     *                 }
          +     *             }
          +     *         ]
          +     *         issuer (Optional): {
          +     *             name: String (Optional)
          +     *             cty: String (Optional)
          +     *             cert_transparency: Boolean (Optional)
          +     *         }
          +     *         attributes (Optional): {
          +     *             enabled: Boolean (Optional)
          +     *             nbf: Long (Optional)
          +     *             exp: Long (Optional)
          +     *             created: Long (Optional)
          +     *             updated: Long (Optional)
          +     *             recoverableDays: Integer (Optional)
          +     *             recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         }
          +     *     }
          +     *     attributes (Optional): (recursive schema, see attributes above)
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     issuer (Optional): {
          +     *         name: String (Optional)
          +     *         cty: String (Optional)
          +     *         cert_transparency: Boolean (Optional)
          +     *     }
          +     *     csr: byte[] (Optional)
          +     *     cancellation_requested: Boolean (Optional)
          +     *     status: String (Optional)
          +     *     status_details: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     target: String (Optional)
          +     *     request_id: String (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param certificateName The name of the certificate. The value you provide may be copied globally for the purpose + * of running the service. The value provided should not include personally identifiable or sensitive information. + * @param parameters The parameters to create a certificate. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a certificate operation is returned in case of asynchronous requests along with {@link Response} on * successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteCertificateOperationWithResponseAsync(String vaultBaseUrl, - String certificateName, Context context) { + public Mono> createCertificateWithResponseAsync(String certificateName, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - return service.deleteCertificateOperation(vaultBaseUrl, certificateName, this.getApiVersion(), accept, context); - } - - /** - * Deletes the creation operation for a specific certificate. - * - * Deletes the creation operation for a specified certificate that is in the process of being created. The - * certificate is no longer created. This operation requires the certificates/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate operation is returned in case of asynchronous requests on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteCertificateOperationAsync(String vaultBaseUrl, String certificateName) { - return deleteCertificateOperationWithResponseAsync(vaultBaseUrl, certificateName) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Deletes the creation operation for a specific certificate. - * - * Deletes the creation operation for a specified certificate that is in the process of being created. The - * certificate is no longer created. This operation requires the certificates/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate operation is returned in case of asynchronous requests on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteCertificateOperationAsync(String vaultBaseUrl, String certificateName, - Context context) { - return deleteCertificateOperationWithResponseAsync(vaultBaseUrl, certificateName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + return FluxUtil.withContext( + context -> service.createCertificate(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + certificateName, contentType, accept, parameters, requestOptions, context)); } /** - * Deletes the creation operation for a specific certificate. + * Creates a new certificate. * - * Deletes the creation operation for a specified certificate that is in the process of being created. The - * certificate is no longer created. This operation requires the certificates/update permission. + * If this is the first version, the certificate resource is created. This operation requires the + * certificates/create permission. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     policy (Optional): {
          +     *         id: String (Optional)
          +     *         key_props (Optional): {
          +     *             exportable: Boolean (Optional)
          +     *             kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *             key_size: Integer (Optional)
          +     *             reuse_key: Boolean (Optional)
          +     *             crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         }
          +     *         secret_props (Optional): {
          +     *             contentType: String (Optional)
          +     *         }
          +     *         x509_props (Optional): {
          +     *             subject: String (Optional)
          +     *             ekus (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             sans (Optional): {
          +     *                 emails (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dns_names (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 upns (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *             }
          +     *             key_usage (Optional): [
          +     *                 String(digitalSignature/nonRepudiation/keyEncipherment/dataEncipherment/keyAgreement/keyCertSign/cRLSign/encipherOnly/decipherOnly) (Optional)
          +     *             ]
          +     *             validity_months: Integer (Optional)
          +     *         }
          +     *         lifetime_actions (Optional): [
          +     *              (Optional){
          +     *                 trigger (Optional): {
          +     *                     lifetime_percentage: Integer (Optional)
          +     *                     days_before_expiry: Integer (Optional)
          +     *                 }
          +     *                 action (Optional): {
          +     *                     action_type: String(EmailContacts/AutoRenew) (Optional)
          +     *                 }
          +     *             }
          +     *         ]
          +     *         issuer (Optional): {
          +     *             name: String (Optional)
          +     *             cty: String (Optional)
          +     *             cert_transparency: Boolean (Optional)
          +     *         }
          +     *         attributes (Optional): {
          +     *             enabled: Boolean (Optional)
          +     *             nbf: Long (Optional)
          +     *             exp: Long (Optional)
          +     *             created: Long (Optional)
          +     *             updated: Long (Optional)
          +     *             recoverableDays: Integer (Optional)
          +     *             recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         }
          +     *     }
          +     *     attributes (Optional): (recursive schema, see attributes above)
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     issuer (Optional): {
          +     *         name: String (Optional)
          +     *         cty: String (Optional)
          +     *         cert_transparency: Boolean (Optional)
          +     *     }
          +     *     csr: byte[] (Optional)
          +     *     cancellation_requested: Boolean (Optional)
          +     *     status: String (Optional)
          +     *     status_details: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     target: String (Optional)
          +     *     request_id: String (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param certificateName The name of the certificate. The value you provide may be copied globally for the purpose + * of running the service. The value provided should not include personally identifiable or sensitive information. + * @param parameters The parameters to create a certificate. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a certificate operation is returned in case of asynchronous requests along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteCertificateOperationWithResponse(String vaultBaseUrl, - String certificateName, Context context) { + public Response createCertificateWithResponse(String certificateName, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - return service.deleteCertificateOperationSync(vaultBaseUrl, certificateName, this.getApiVersion(), accept, - context); + return service.createCertificateSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + certificateName, contentType, accept, parameters, requestOptions, Context.NONE); } /** - * Deletes the creation operation for a specific certificate. - * - * Deletes the creation operation for a specified certificate that is in the process of being created. The - * certificate is no longer created. This operation requires the certificates/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate operation is returned in case of asynchronous requests. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public CertificateOperation deleteCertificateOperation(String vaultBaseUrl, String certificateName) { - return deleteCertificateOperationWithResponse(vaultBaseUrl, certificateName, Context.NONE).getValue(); - } - - /** - * Merges a certificate or a certificate chain with a key pair existing on the server. - * - * The MergeCertificate operation performs the merging of a certificate or certificate chain with a key pair - * currently available in the service. This operation requires the certificates/create permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param x509Certificates The certificate or the certificate chain to merge. - * @param certificateAttributes The attributes of the certificate (optional). - * @param tags Application specific metadata in the form of key-value pairs. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate bundle consists of a certificate (X509) plus its attributes along with {@link Response} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> mergeCertificateWithResponseAsync(String vaultBaseUrl, - String certificateName, List x509Certificates, CertificateAttributes certificateAttributes, - Map tags) { - return FluxUtil.withContext(context -> mergeCertificateWithResponseAsync(vaultBaseUrl, certificateName, - x509Certificates, certificateAttributes, tags, context)); - } - - /** - * Merges a certificate or a certificate chain with a key pair existing on the server. + * Imports a certificate into a specified key vault. * - * The MergeCertificate operation performs the merging of a certificate or certificate chain with a key pair - * currently available in the service. This operation requires the certificates/create permission. + * Imports an existing valid certificate, containing a private key, into Azure Key Vault. This operation requires + * the certificates/import permission. The certificate to be imported can be in either PFX or PEM format. If the + * certificate is in PEM format the PEM file must contain the key as well as x509 certificates. Key Vault will only + * accept a key in PKCS#8 format. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: String (Required)
          +     *     pwd: String (Optional)
          +     *     policy (Optional): {
          +     *         id: String (Optional)
          +     *         key_props (Optional): {
          +     *             exportable: Boolean (Optional)
          +     *             kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *             key_size: Integer (Optional)
          +     *             reuse_key: Boolean (Optional)
          +     *             crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         }
          +     *         secret_props (Optional): {
          +     *             contentType: String (Optional)
          +     *         }
          +     *         x509_props (Optional): {
          +     *             subject: String (Optional)
          +     *             ekus (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             sans (Optional): {
          +     *                 emails (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dns_names (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 upns (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *             }
          +     *             key_usage (Optional): [
          +     *                 String(digitalSignature/nonRepudiation/keyEncipherment/dataEncipherment/keyAgreement/keyCertSign/cRLSign/encipherOnly/decipherOnly) (Optional)
          +     *             ]
          +     *             validity_months: Integer (Optional)
          +     *         }
          +     *         lifetime_actions (Optional): [
          +     *              (Optional){
          +     *                 trigger (Optional): {
          +     *                     lifetime_percentage: Integer (Optional)
          +     *                     days_before_expiry: Integer (Optional)
          +     *                 }
          +     *                 action (Optional): {
          +     *                     action_type: String(EmailContacts/AutoRenew) (Optional)
          +     *                 }
          +     *             }
          +     *         ]
          +     *         issuer (Optional): {
          +     *             name: String (Optional)
          +     *             cty: String (Optional)
          +     *             cert_transparency: Boolean (Optional)
          +     *         }
          +     *         attributes (Optional): {
          +     *             enabled: Boolean (Optional)
          +     *             nbf: Long (Optional)
          +     *             exp: Long (Optional)
          +     *             created: Long (Optional)
          +     *             updated: Long (Optional)
          +     *             recoverableDays: Integer (Optional)
          +     *             recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         }
          +     *     }
          +     *     attributes (Optional): (recursive schema, see attributes above)
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     kid: String (Optional)
          +     *     sid: String (Optional)
          +     *     x5t: Base64Url (Optional)
          +     *     policy (Optional): {
          +     *         id: String (Optional)
          +     *         key_props (Optional): {
          +     *             exportable: Boolean (Optional)
          +     *             kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *             key_size: Integer (Optional)
          +     *             reuse_key: Boolean (Optional)
          +     *             crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         }
          +     *         secret_props (Optional): {
          +     *             contentType: String (Optional)
          +     *         }
          +     *         x509_props (Optional): {
          +     *             subject: String (Optional)
          +     *             ekus (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             sans (Optional): {
          +     *                 emails (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dns_names (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 upns (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *             }
          +     *             key_usage (Optional): [
          +     *                 String(digitalSignature/nonRepudiation/keyEncipherment/dataEncipherment/keyAgreement/keyCertSign/cRLSign/encipherOnly/decipherOnly) (Optional)
          +     *             ]
          +     *             validity_months: Integer (Optional)
          +     *         }
          +     *         lifetime_actions (Optional): [
          +     *              (Optional){
          +     *                 trigger (Optional): {
          +     *                     lifetime_percentage: Integer (Optional)
          +     *                     days_before_expiry: Integer (Optional)
          +     *                 }
          +     *                 action (Optional): {
          +     *                     action_type: String(EmailContacts/AutoRenew) (Optional)
          +     *                 }
          +     *             }
          +     *         ]
          +     *         issuer (Optional): {
          +     *             name: String (Optional)
          +     *             cty: String (Optional)
          +     *             cert_transparency: Boolean (Optional)
          +     *         }
          +     *         attributes (Optional): {
          +     *             enabled: Boolean (Optional)
          +     *             nbf: Long (Optional)
          +     *             exp: Long (Optional)
          +     *             created: Long (Optional)
          +     *             updated: Long (Optional)
          +     *             recoverableDays: Integer (Optional)
          +     *             recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         }
          +     *     }
          +     *     cer: byte[] (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): (recursive schema, see attributes above)
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param x509Certificates The certificate or the certificate chain to merge. - * @param certificateAttributes The attributes of the certificate (optional). - * @param tags Application specific metadata in the form of key-value pairs. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param certificateName The name of the certificate. The value you provide may be copied globally for the purpose + * of running the service. The value provided should not include personally identifiable or sensitive information. + * @param parameters The parameters to import the certificate. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a certificate bundle consists of a certificate (X509) plus its attributes along with {@link Response} on * successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> mergeCertificateWithResponseAsync(String vaultBaseUrl, - String certificateName, List x509Certificates, CertificateAttributes certificateAttributes, - Map tags, Context context) { + public Mono> importCertificateWithResponseAsync(String certificateName, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - CertificateMergeParameters parameters = new CertificateMergeParameters(); - parameters.setX509Certificates(x509Certificates); - parameters.setCertificateAttributes(certificateAttributes); - parameters.setTags(tags); - return service.mergeCertificate(vaultBaseUrl, certificateName, this.getApiVersion(), parameters, accept, - context); - } - - /** - * Merges a certificate or a certificate chain with a key pair existing on the server. - * - * The MergeCertificate operation performs the merging of a certificate or certificate chain with a key pair - * currently available in the service. This operation requires the certificates/create permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param x509Certificates The certificate or the certificate chain to merge. - * @param certificateAttributes The attributes of the certificate (optional). - * @param tags Application specific metadata in the form of key-value pairs. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate bundle consists of a certificate (X509) plus its attributes on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono mergeCertificateAsync(String vaultBaseUrl, String certificateName, - List x509Certificates, CertificateAttributes certificateAttributes, Map tags) { - return mergeCertificateWithResponseAsync(vaultBaseUrl, certificateName, x509Certificates, certificateAttributes, - tags).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Merges a certificate or a certificate chain with a key pair existing on the server. - * - * The MergeCertificate operation performs the merging of a certificate or certificate chain with a key pair - * currently available in the service. This operation requires the certificates/create permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param x509Certificates The certificate or the certificate chain to merge. - * @param certificateAttributes The attributes of the certificate (optional). - * @param tags Application specific metadata in the form of key-value pairs. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate bundle consists of a certificate (X509) plus its attributes on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono mergeCertificateAsync(String vaultBaseUrl, String certificateName, - List x509Certificates, CertificateAttributes certificateAttributes, Map tags, - Context context) { - return mergeCertificateWithResponseAsync(vaultBaseUrl, certificateName, x509Certificates, certificateAttributes, - tags, context).flatMap(res -> Mono.justOrEmpty(res.getValue())); + return FluxUtil.withContext( + context -> service.importCertificate(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + certificateName, contentType, accept, parameters, requestOptions, context)); } /** - * Merges a certificate or a certificate chain with a key pair existing on the server. + * Imports a certificate into a specified key vault. * - * The MergeCertificate operation performs the merging of a certificate or certificate chain with a key pair - * currently available in the service. This operation requires the certificates/create permission. + * Imports an existing valid certificate, containing a private key, into Azure Key Vault. This operation requires + * the certificates/import permission. The certificate to be imported can be in either PFX or PEM format. If the + * certificate is in PEM format the PEM file must contain the key as well as x509 certificates. Key Vault will only + * accept a key in PKCS#8 format. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: String (Required)
          +     *     pwd: String (Optional)
          +     *     policy (Optional): {
          +     *         id: String (Optional)
          +     *         key_props (Optional): {
          +     *             exportable: Boolean (Optional)
          +     *             kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *             key_size: Integer (Optional)
          +     *             reuse_key: Boolean (Optional)
          +     *             crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         }
          +     *         secret_props (Optional): {
          +     *             contentType: String (Optional)
          +     *         }
          +     *         x509_props (Optional): {
          +     *             subject: String (Optional)
          +     *             ekus (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             sans (Optional): {
          +     *                 emails (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dns_names (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 upns (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *             }
          +     *             key_usage (Optional): [
          +     *                 String(digitalSignature/nonRepudiation/keyEncipherment/dataEncipherment/keyAgreement/keyCertSign/cRLSign/encipherOnly/decipherOnly) (Optional)
          +     *             ]
          +     *             validity_months: Integer (Optional)
          +     *         }
          +     *         lifetime_actions (Optional): [
          +     *              (Optional){
          +     *                 trigger (Optional): {
          +     *                     lifetime_percentage: Integer (Optional)
          +     *                     days_before_expiry: Integer (Optional)
          +     *                 }
          +     *                 action (Optional): {
          +     *                     action_type: String(EmailContacts/AutoRenew) (Optional)
          +     *                 }
          +     *             }
          +     *         ]
          +     *         issuer (Optional): {
          +     *             name: String (Optional)
          +     *             cty: String (Optional)
          +     *             cert_transparency: Boolean (Optional)
          +     *         }
          +     *         attributes (Optional): {
          +     *             enabled: Boolean (Optional)
          +     *             nbf: Long (Optional)
          +     *             exp: Long (Optional)
          +     *             created: Long (Optional)
          +     *             updated: Long (Optional)
          +     *             recoverableDays: Integer (Optional)
          +     *             recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         }
          +     *     }
          +     *     attributes (Optional): (recursive schema, see attributes above)
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     kid: String (Optional)
          +     *     sid: String (Optional)
          +     *     x5t: Base64Url (Optional)
          +     *     policy (Optional): {
          +     *         id: String (Optional)
          +     *         key_props (Optional): {
          +     *             exportable: Boolean (Optional)
          +     *             kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *             key_size: Integer (Optional)
          +     *             reuse_key: Boolean (Optional)
          +     *             crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         }
          +     *         secret_props (Optional): {
          +     *             contentType: String (Optional)
          +     *         }
          +     *         x509_props (Optional): {
          +     *             subject: String (Optional)
          +     *             ekus (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             sans (Optional): {
          +     *                 emails (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dns_names (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 upns (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *             }
          +     *             key_usage (Optional): [
          +     *                 String(digitalSignature/nonRepudiation/keyEncipherment/dataEncipherment/keyAgreement/keyCertSign/cRLSign/encipherOnly/decipherOnly) (Optional)
          +     *             ]
          +     *             validity_months: Integer (Optional)
          +     *         }
          +     *         lifetime_actions (Optional): [
          +     *              (Optional){
          +     *                 trigger (Optional): {
          +     *                     lifetime_percentage: Integer (Optional)
          +     *                     days_before_expiry: Integer (Optional)
          +     *                 }
          +     *                 action (Optional): {
          +     *                     action_type: String(EmailContacts/AutoRenew) (Optional)
          +     *                 }
          +     *             }
          +     *         ]
          +     *         issuer (Optional): {
          +     *             name: String (Optional)
          +     *             cty: String (Optional)
          +     *             cert_transparency: Boolean (Optional)
          +     *         }
          +     *         attributes (Optional): {
          +     *             enabled: Boolean (Optional)
          +     *             nbf: Long (Optional)
          +     *             exp: Long (Optional)
          +     *             created: Long (Optional)
          +     *             updated: Long (Optional)
          +     *             recoverableDays: Integer (Optional)
          +     *             recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         }
          +     *     }
          +     *     cer: byte[] (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): (recursive schema, see attributes above)
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param x509Certificates The certificate or the certificate chain to merge. - * @param certificateAttributes The attributes of the certificate (optional). - * @param tags Application specific metadata in the form of key-value pairs. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param certificateName The name of the certificate. The value you provide may be copied globally for the purpose + * of running the service. The value provided should not include personally identifiable or sensitive information. + * @param parameters The parameters to import the certificate. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a certificate bundle consists of a certificate (X509) plus its attributes along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response mergeCertificateWithResponse(String vaultBaseUrl, String certificateName, - List x509Certificates, CertificateAttributes certificateAttributes, Map tags, - Context context) { - final String accept = "application/json"; - CertificateMergeParameters parameters = new CertificateMergeParameters(); - parameters.setX509Certificates(x509Certificates); - parameters.setCertificateAttributes(certificateAttributes); - parameters.setTags(tags); - return service.mergeCertificateSync(vaultBaseUrl, certificateName, this.getApiVersion(), parameters, accept, - context); - } - - /** - * Merges a certificate or a certificate chain with a key pair existing on the server. - * - * The MergeCertificate operation performs the merging of a certificate or certificate chain with a key pair - * currently available in the service. This operation requires the certificates/create permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param x509Certificates The certificate or the certificate chain to merge. - * @param certificateAttributes The attributes of the certificate (optional). - * @param tags Application specific metadata in the form of key-value pairs. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate bundle consists of a certificate (X509) plus its attributes. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public CertificateBundle mergeCertificate(String vaultBaseUrl, String certificateName, - List x509Certificates, CertificateAttributes certificateAttributes, Map tags) { - return mergeCertificateWithResponse(vaultBaseUrl, certificateName, x509Certificates, certificateAttributes, - tags, Context.NONE).getValue(); - } - - /** - * Backs up the specified certificate. - * - * Requests that a backup of the specified certificate be downloaded to the client. All versions of the certificate - * will be downloaded. This operation requires the certificates/backup permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the backup certificate result, containing the backup blob along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> backupCertificateWithResponseAsync(String vaultBaseUrl, - String certificateName) { - return FluxUtil - .withContext(context -> backupCertificateWithResponseAsync(vaultBaseUrl, certificateName, context)); + public Response importCertificateWithResponse(String certificateName, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return service.importCertificateSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + certificateName, contentType, accept, parameters, requestOptions, Context.NONE); } /** - * Backs up the specified certificate. + * List the versions of a certificate. * - * Requests that a backup of the specified certificate be downloaded to the client. All versions of the certificate - * will be downloaded. This operation requires the certificates/backup permission. + * The GetCertificateVersions operation returns the versions of a certificate in the specified key vault. This + * operation requires the certificates/list permission. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     x5t: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param certificateName The name of the certificate. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the backup certificate result, containing the backup blob along with {@link Response} on successful - * completion of {@link Mono}. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the certificate list result along with {@link PagedResponse} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> backupCertificateWithResponseAsync(String vaultBaseUrl, - String certificateName, Context context) { + private Mono> getCertificateVersionsSinglePageAsync(String certificateName, + RequestOptions requestOptions) { final String accept = "application/json"; - return service.backupCertificate(vaultBaseUrl, certificateName, this.getApiVersion(), accept, context); + return FluxUtil + .withContext(context -> service.getCertificateVersions(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), certificateName, accept, requestOptions, context)) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } /** - * Backs up the specified certificate. + * List the versions of a certificate. * - * Requests that a backup of the specified certificate be downloaded to the client. All versions of the certificate - * will be downloaded. This operation requires the certificates/backup permission. + * The GetCertificateVersions operation returns the versions of a certificate in the specified key vault. This + * operation requires the certificates/list permission. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     x5t: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param certificateName The name of the certificate. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the backup certificate result, containing the backup blob on successful completion of {@link Mono}. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the certificate list result as paginated response with {@link PagedFlux}. */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono backupCertificateAsync(String vaultBaseUrl, String certificateName) { - return backupCertificateWithResponseAsync(vaultBaseUrl, certificateName) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux getCertificateVersionsAsync(String certificateName, RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedFlux<>(() -> getCertificateVersionsSinglePageAsync(certificateName, requestOptions), + nextLink -> getCertificateVersionsNextSinglePageAsync(nextLink, requestOptionsForNextPage)); } /** - * Backs up the specified certificate. + * List the versions of a certificate. * - * Requests that a backup of the specified certificate be downloaded to the client. All versions of the certificate - * will be downloaded. This operation requires the certificates/backup permission. + * The GetCertificateVersions operation returns the versions of a certificate in the specified key vault. This + * operation requires the certificates/list permission. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     x5t: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param certificateName The name of the certificate. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the backup certificate result, containing the backup blob on successful completion of {@link Mono}. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the certificate list result along with {@link PagedResponse}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono backupCertificateAsync(String vaultBaseUrl, String certificateName, - Context context) { - return backupCertificateWithResponseAsync(vaultBaseUrl, certificateName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + private PagedResponse getCertificateVersionsSinglePage(String certificateName, + RequestOptions requestOptions) { + final String accept = "application/json"; + Response res = service.getCertificateVersionsSync(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), certificateName, accept, requestOptions, Context.NONE); + return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } /** - * Backs up the specified certificate. + * List the versions of a certificate. * - * Requests that a backup of the specified certificate be downloaded to the client. All versions of the certificate - * will be downloaded. This operation requires the certificates/backup permission. + * The GetCertificateVersions operation returns the versions of a certificate in the specified key vault. This + * operation requires the certificates/list permission. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     x5t: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param certificateName The name of the certificate. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the backup certificate result, containing the backup blob along with {@link Response}. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the certificate list result as paginated response with {@link PagedIterable}. */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response backupCertificateWithResponse(String vaultBaseUrl, String certificateName, - Context context) { - final String accept = "application/json"; - return service.backupCertificateSync(vaultBaseUrl, certificateName, this.getApiVersion(), accept, context); + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable getCertificateVersions(String certificateName, RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedIterable<>(() -> getCertificateVersionsSinglePage(certificateName, requestOptions), + nextLink -> getCertificateVersionsNextSinglePage(nextLink, requestOptionsForNextPage)); } /** - * Backs up the specified certificate. + * Lists the policy for a certificate. * - * Requests that a backup of the specified certificate be downloaded to the client. All versions of the certificate - * will be downloaded. This operation requires the certificates/backup permission. + * The GetCertificatePolicy operation returns the specified certificate policy resources in the specified key vault. + * This operation requires the certificates/get permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     key_props (Optional): {
          +     *         exportable: Boolean (Optional)
          +     *         kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *         key_size: Integer (Optional)
          +     *         reuse_key: Boolean (Optional)
          +     *         crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *     }
          +     *     secret_props (Optional): {
          +     *         contentType: String (Optional)
          +     *     }
          +     *     x509_props (Optional): {
          +     *         subject: String (Optional)
          +     *         ekus (Optional): [
          +     *             String (Optional)
          +     *         ]
          +     *         sans (Optional): {
          +     *             emails (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             dns_names (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             upns (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *         }
          +     *         key_usage (Optional): [
          +     *             String(digitalSignature/nonRepudiation/keyEncipherment/dataEncipherment/keyAgreement/keyCertSign/cRLSign/encipherOnly/decipherOnly) (Optional)
          +     *         ]
          +     *         validity_months: Integer (Optional)
          +     *     }
          +     *     lifetime_actions (Optional): [
          +     *          (Optional){
          +     *             trigger (Optional): {
          +     *                 lifetime_percentage: Integer (Optional)
          +     *                 days_before_expiry: Integer (Optional)
          +     *             }
          +     *             action (Optional): {
          +     *                 action_type: String(EmailContacts/AutoRenew) (Optional)
          +     *             }
          +     *         }
          +     *     ]
          +     *     issuer (Optional): {
          +     *         name: String (Optional)
          +     *         cty: String (Optional)
          +     *         cert_transparency: Boolean (Optional)
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the backup certificate result, containing the backup blob. + * @param certificateName The name of the certificate in a given key vault. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return management policy for a certificate along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public BackupCertificateResult backupCertificate(String vaultBaseUrl, String certificateName) { - return backupCertificateWithResponse(vaultBaseUrl, certificateName, Context.NONE).getValue(); + public Mono> getCertificatePolicyWithResponseAsync(String certificateName, + RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.getCertificatePolicy(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), certificateName, accept, requestOptions, context)); } /** - * Restores a backed up certificate to a vault. + * Lists the policy for a certificate. * - * Restores a backed up certificate, and all its versions, to a vault. This operation requires the - * certificates/restore permission. + * The GetCertificatePolicy operation returns the specified certificate policy resources in the specified key vault. + * This operation requires the certificates/get permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     key_props (Optional): {
          +     *         exportable: Boolean (Optional)
          +     *         kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *         key_size: Integer (Optional)
          +     *         reuse_key: Boolean (Optional)
          +     *         crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *     }
          +     *     secret_props (Optional): {
          +     *         contentType: String (Optional)
          +     *     }
          +     *     x509_props (Optional): {
          +     *         subject: String (Optional)
          +     *         ekus (Optional): [
          +     *             String (Optional)
          +     *         ]
          +     *         sans (Optional): {
          +     *             emails (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             dns_names (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             upns (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *         }
          +     *         key_usage (Optional): [
          +     *             String(digitalSignature/nonRepudiation/keyEncipherment/dataEncipherment/keyAgreement/keyCertSign/cRLSign/encipherOnly/decipherOnly) (Optional)
          +     *         ]
          +     *         validity_months: Integer (Optional)
          +     *     }
          +     *     lifetime_actions (Optional): [
          +     *          (Optional){
          +     *             trigger (Optional): {
          +     *                 lifetime_percentage: Integer (Optional)
          +     *                 days_before_expiry: Integer (Optional)
          +     *             }
          +     *             action (Optional): {
          +     *                 action_type: String(EmailContacts/AutoRenew) (Optional)
          +     *             }
          +     *         }
          +     *     ]
          +     *     issuer (Optional): {
          +     *         name: String (Optional)
          +     *         cty: String (Optional)
          +     *         cert_transparency: Boolean (Optional)
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateBundleBackup The backup blob associated with a certificate bundle. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate bundle consists of a certificate (X509) plus its attributes along with {@link Response} on - * successful completion of {@link Mono}. + * @param certificateName The name of the certificate in a given key vault. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return management policy for a certificate along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> restoreCertificateWithResponseAsync(String vaultBaseUrl, - byte[] certificateBundleBackup) { - return FluxUtil.withContext( - context -> restoreCertificateWithResponseAsync(vaultBaseUrl, certificateBundleBackup, context)); + public Response getCertificatePolicyWithResponse(String certificateName, + RequestOptions requestOptions) { + final String accept = "application/json"; + return service.getCertificatePolicySync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + certificateName, accept, requestOptions, Context.NONE); } /** - * Restores a backed up certificate to a vault. + * Updates the policy for a certificate. * - * Restores a backed up certificate, and all its versions, to a vault. This operation requires the - * certificates/restore permission. + * Set specified members in the certificate policy. Leave others as null. This operation requires the + * certificates/update permission. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     key_props (Optional): {
          +     *         exportable: Boolean (Optional)
          +     *         kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *         key_size: Integer (Optional)
          +     *         reuse_key: Boolean (Optional)
          +     *         crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *     }
          +     *     secret_props (Optional): {
          +     *         contentType: String (Optional)
          +     *     }
          +     *     x509_props (Optional): {
          +     *         subject: String (Optional)
          +     *         ekus (Optional): [
          +     *             String (Optional)
          +     *         ]
          +     *         sans (Optional): {
          +     *             emails (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             dns_names (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             upns (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *         }
          +     *         key_usage (Optional): [
          +     *             String(digitalSignature/nonRepudiation/keyEncipherment/dataEncipherment/keyAgreement/keyCertSign/cRLSign/encipherOnly/decipherOnly) (Optional)
          +     *         ]
          +     *         validity_months: Integer (Optional)
          +     *     }
          +     *     lifetime_actions (Optional): [
          +     *          (Optional){
          +     *             trigger (Optional): {
          +     *                 lifetime_percentage: Integer (Optional)
          +     *                 days_before_expiry: Integer (Optional)
          +     *             }
          +     *             action (Optional): {
          +     *                 action_type: String(EmailContacts/AutoRenew) (Optional)
          +     *             }
          +     *         }
          +     *     ]
          +     *     issuer (Optional): {
          +     *         name: String (Optional)
          +     *         cty: String (Optional)
          +     *         cert_transparency: Boolean (Optional)
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     key_props (Optional): {
          +     *         exportable: Boolean (Optional)
          +     *         kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *         key_size: Integer (Optional)
          +     *         reuse_key: Boolean (Optional)
          +     *         crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *     }
          +     *     secret_props (Optional): {
          +     *         contentType: String (Optional)
          +     *     }
          +     *     x509_props (Optional): {
          +     *         subject: String (Optional)
          +     *         ekus (Optional): [
          +     *             String (Optional)
          +     *         ]
          +     *         sans (Optional): {
          +     *             emails (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             dns_names (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             upns (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *         }
          +     *         key_usage (Optional): [
          +     *             String(digitalSignature/nonRepudiation/keyEncipherment/dataEncipherment/keyAgreement/keyCertSign/cRLSign/encipherOnly/decipherOnly) (Optional)
          +     *         ]
          +     *         validity_months: Integer (Optional)
          +     *     }
          +     *     lifetime_actions (Optional): [
          +     *          (Optional){
          +     *             trigger (Optional): {
          +     *                 lifetime_percentage: Integer (Optional)
          +     *                 days_before_expiry: Integer (Optional)
          +     *             }
          +     *             action (Optional): {
          +     *                 action_type: String(EmailContacts/AutoRenew) (Optional)
          +     *             }
          +     *         }
          +     *     ]
          +     *     issuer (Optional): {
          +     *         name: String (Optional)
          +     *         cty: String (Optional)
          +     *         cert_transparency: Boolean (Optional)
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateBundleBackup The backup blob associated with a certificate bundle. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate bundle consists of a certificate (X509) plus its attributes along with {@link Response} on - * successful completion of {@link Mono}. + * @param certificateName The name of the certificate in the given vault. + * @param certificatePolicy The policy for the certificate. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return management policy for a certificate along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> restoreCertificateWithResponseAsync(String vaultBaseUrl, - byte[] certificateBundleBackup, Context context) { + public Mono> updateCertificatePolicyWithResponseAsync(String certificateName, + BinaryData certificatePolicy, RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - CertificateRestoreParameters parameters = new CertificateRestoreParameters(); - parameters.setCertificateBundleBackup(certificateBundleBackup); - return service.restoreCertificate(vaultBaseUrl, this.getApiVersion(), parameters, accept, context); + return FluxUtil.withContext( + context -> service.updateCertificatePolicy(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + certificateName, contentType, accept, certificatePolicy, requestOptions, context)); } /** - * Restores a backed up certificate to a vault. + * Updates the policy for a certificate. * - * Restores a backed up certificate, and all its versions, to a vault. This operation requires the - * certificates/restore permission. + * Set specified members in the certificate policy. Leave others as null. This operation requires the + * certificates/update permission. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     key_props (Optional): {
          +     *         exportable: Boolean (Optional)
          +     *         kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *         key_size: Integer (Optional)
          +     *         reuse_key: Boolean (Optional)
          +     *         crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *     }
          +     *     secret_props (Optional): {
          +     *         contentType: String (Optional)
          +     *     }
          +     *     x509_props (Optional): {
          +     *         subject: String (Optional)
          +     *         ekus (Optional): [
          +     *             String (Optional)
          +     *         ]
          +     *         sans (Optional): {
          +     *             emails (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             dns_names (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             upns (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *         }
          +     *         key_usage (Optional): [
          +     *             String(digitalSignature/nonRepudiation/keyEncipherment/dataEncipherment/keyAgreement/keyCertSign/cRLSign/encipherOnly/decipherOnly) (Optional)
          +     *         ]
          +     *         validity_months: Integer (Optional)
          +     *     }
          +     *     lifetime_actions (Optional): [
          +     *          (Optional){
          +     *             trigger (Optional): {
          +     *                 lifetime_percentage: Integer (Optional)
          +     *                 days_before_expiry: Integer (Optional)
          +     *             }
          +     *             action (Optional): {
          +     *                 action_type: String(EmailContacts/AutoRenew) (Optional)
          +     *             }
          +     *         }
          +     *     ]
          +     *     issuer (Optional): {
          +     *         name: String (Optional)
          +     *         cty: String (Optional)
          +     *         cert_transparency: Boolean (Optional)
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     key_props (Optional): {
          +     *         exportable: Boolean (Optional)
          +     *         kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *         key_size: Integer (Optional)
          +     *         reuse_key: Boolean (Optional)
          +     *         crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *     }
          +     *     secret_props (Optional): {
          +     *         contentType: String (Optional)
          +     *     }
          +     *     x509_props (Optional): {
          +     *         subject: String (Optional)
          +     *         ekus (Optional): [
          +     *             String (Optional)
          +     *         ]
          +     *         sans (Optional): {
          +     *             emails (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             dns_names (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             upns (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *         }
          +     *         key_usage (Optional): [
          +     *             String(digitalSignature/nonRepudiation/keyEncipherment/dataEncipherment/keyAgreement/keyCertSign/cRLSign/encipherOnly/decipherOnly) (Optional)
          +     *         ]
          +     *         validity_months: Integer (Optional)
          +     *     }
          +     *     lifetime_actions (Optional): [
          +     *          (Optional){
          +     *             trigger (Optional): {
          +     *                 lifetime_percentage: Integer (Optional)
          +     *                 days_before_expiry: Integer (Optional)
          +     *             }
          +     *             action (Optional): {
          +     *                 action_type: String(EmailContacts/AutoRenew) (Optional)
          +     *             }
          +     *         }
          +     *     ]
          +     *     issuer (Optional): {
          +     *         name: String (Optional)
          +     *         cty: String (Optional)
          +     *         cert_transparency: Boolean (Optional)
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateBundleBackup The backup blob associated with a certificate bundle. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate bundle consists of a certificate (X509) plus its attributes on successful completion of - * {@link Mono}. + * @param certificateName The name of the certificate in the given vault. + * @param certificatePolicy The policy for the certificate. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return management policy for a certificate along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono restoreCertificateAsync(String vaultBaseUrl, byte[] certificateBundleBackup) { - return restoreCertificateWithResponseAsync(vaultBaseUrl, certificateBundleBackup) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + public Response updateCertificatePolicyWithResponse(String certificateName, + BinaryData certificatePolicy, RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return service.updateCertificatePolicySync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + certificateName, contentType, accept, certificatePolicy, requestOptions, Context.NONE); } /** - * Restores a backed up certificate to a vault. + * Updates the specified attributes associated with the given certificate. * - * Restores a backed up certificate, and all its versions, to a vault. This operation requires the - * certificates/restore permission. + * The UpdateCertificate operation applies the specified update on the given certificate; the only elements updated + * are the certificate's attributes. This operation requires the certificates/update permission. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     policy (Optional): {
          +     *         id: String (Optional)
          +     *         key_props (Optional): {
          +     *             exportable: Boolean (Optional)
          +     *             kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *             key_size: Integer (Optional)
          +     *             reuse_key: Boolean (Optional)
          +     *             crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         }
          +     *         secret_props (Optional): {
          +     *             contentType: String (Optional)
          +     *         }
          +     *         x509_props (Optional): {
          +     *             subject: String (Optional)
          +     *             ekus (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             sans (Optional): {
          +     *                 emails (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dns_names (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 upns (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *             }
          +     *             key_usage (Optional): [
          +     *                 String(digitalSignature/nonRepudiation/keyEncipherment/dataEncipherment/keyAgreement/keyCertSign/cRLSign/encipherOnly/decipherOnly) (Optional)
          +     *             ]
          +     *             validity_months: Integer (Optional)
          +     *         }
          +     *         lifetime_actions (Optional): [
          +     *              (Optional){
          +     *                 trigger (Optional): {
          +     *                     lifetime_percentage: Integer (Optional)
          +     *                     days_before_expiry: Integer (Optional)
          +     *                 }
          +     *                 action (Optional): {
          +     *                     action_type: String(EmailContacts/AutoRenew) (Optional)
          +     *                 }
          +     *             }
          +     *         ]
          +     *         issuer (Optional): {
          +     *             name: String (Optional)
          +     *             cty: String (Optional)
          +     *             cert_transparency: Boolean (Optional)
          +     *         }
          +     *         attributes (Optional): {
          +     *             enabled: Boolean (Optional)
          +     *             nbf: Long (Optional)
          +     *             exp: Long (Optional)
          +     *             created: Long (Optional)
          +     *             updated: Long (Optional)
          +     *             recoverableDays: Integer (Optional)
          +     *             recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         }
          +     *     }
          +     *     attributes (Optional): (recursive schema, see attributes above)
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     kid: String (Optional)
          +     *     sid: String (Optional)
          +     *     x5t: Base64Url (Optional)
          +     *     policy (Optional): {
          +     *         id: String (Optional)
          +     *         key_props (Optional): {
          +     *             exportable: Boolean (Optional)
          +     *             kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *             key_size: Integer (Optional)
          +     *             reuse_key: Boolean (Optional)
          +     *             crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         }
          +     *         secret_props (Optional): {
          +     *             contentType: String (Optional)
          +     *         }
          +     *         x509_props (Optional): {
          +     *             subject: String (Optional)
          +     *             ekus (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             sans (Optional): {
          +     *                 emails (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dns_names (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 upns (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *             }
          +     *             key_usage (Optional): [
          +     *                 String(digitalSignature/nonRepudiation/keyEncipherment/dataEncipherment/keyAgreement/keyCertSign/cRLSign/encipherOnly/decipherOnly) (Optional)
          +     *             ]
          +     *             validity_months: Integer (Optional)
          +     *         }
          +     *         lifetime_actions (Optional): [
          +     *              (Optional){
          +     *                 trigger (Optional): {
          +     *                     lifetime_percentage: Integer (Optional)
          +     *                     days_before_expiry: Integer (Optional)
          +     *                 }
          +     *                 action (Optional): {
          +     *                     action_type: String(EmailContacts/AutoRenew) (Optional)
          +     *                 }
          +     *             }
          +     *         ]
          +     *         issuer (Optional): {
          +     *             name: String (Optional)
          +     *             cty: String (Optional)
          +     *             cert_transparency: Boolean (Optional)
          +     *         }
          +     *         attributes (Optional): {
          +     *             enabled: Boolean (Optional)
          +     *             nbf: Long (Optional)
          +     *             exp: Long (Optional)
          +     *             created: Long (Optional)
          +     *             updated: Long (Optional)
          +     *             recoverableDays: Integer (Optional)
          +     *             recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         }
          +     *     }
          +     *     cer: byte[] (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): (recursive schema, see attributes above)
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateBundleBackup The backup blob associated with a certificate bundle. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate bundle consists of a certificate (X509) plus its attributes on successful completion of - * {@link Mono}. + * @param certificateName The name of the certificate in the given key vault. + * @param certificateVersion The version of the certificate. + * @param parameters The parameters for certificate update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a certificate bundle consists of a certificate (X509) plus its attributes along with {@link Response} on + * successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono restoreCertificateAsync(String vaultBaseUrl, byte[] certificateBundleBackup, - Context context) { - return restoreCertificateWithResponseAsync(vaultBaseUrl, certificateBundleBackup, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + public Mono> updateCertificateWithResponseAsync(String certificateName, + String certificateVersion, BinaryData parameters, RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext( + context -> service.updateCertificate(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + certificateName, certificateVersion, contentType, accept, parameters, requestOptions, context)); } /** - * Restores a backed up certificate to a vault. + * Updates the specified attributes associated with the given certificate. * - * Restores a backed up certificate, and all its versions, to a vault. This operation requires the - * certificates/restore permission. + * The UpdateCertificate operation applies the specified update on the given certificate; the only elements updated + * are the certificate's attributes. This operation requires the certificates/update permission. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     policy (Optional): {
          +     *         id: String (Optional)
          +     *         key_props (Optional): {
          +     *             exportable: Boolean (Optional)
          +     *             kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *             key_size: Integer (Optional)
          +     *             reuse_key: Boolean (Optional)
          +     *             crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         }
          +     *         secret_props (Optional): {
          +     *             contentType: String (Optional)
          +     *         }
          +     *         x509_props (Optional): {
          +     *             subject: String (Optional)
          +     *             ekus (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             sans (Optional): {
          +     *                 emails (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dns_names (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 upns (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *             }
          +     *             key_usage (Optional): [
          +     *                 String(digitalSignature/nonRepudiation/keyEncipherment/dataEncipherment/keyAgreement/keyCertSign/cRLSign/encipherOnly/decipherOnly) (Optional)
          +     *             ]
          +     *             validity_months: Integer (Optional)
          +     *         }
          +     *         lifetime_actions (Optional): [
          +     *              (Optional){
          +     *                 trigger (Optional): {
          +     *                     lifetime_percentage: Integer (Optional)
          +     *                     days_before_expiry: Integer (Optional)
          +     *                 }
          +     *                 action (Optional): {
          +     *                     action_type: String(EmailContacts/AutoRenew) (Optional)
          +     *                 }
          +     *             }
          +     *         ]
          +     *         issuer (Optional): {
          +     *             name: String (Optional)
          +     *             cty: String (Optional)
          +     *             cert_transparency: Boolean (Optional)
          +     *         }
          +     *         attributes (Optional): {
          +     *             enabled: Boolean (Optional)
          +     *             nbf: Long (Optional)
          +     *             exp: Long (Optional)
          +     *             created: Long (Optional)
          +     *             updated: Long (Optional)
          +     *             recoverableDays: Integer (Optional)
          +     *             recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         }
          +     *     }
          +     *     attributes (Optional): (recursive schema, see attributes above)
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     kid: String (Optional)
          +     *     sid: String (Optional)
          +     *     x5t: Base64Url (Optional)
          +     *     policy (Optional): {
          +     *         id: String (Optional)
          +     *         key_props (Optional): {
          +     *             exportable: Boolean (Optional)
          +     *             kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *             key_size: Integer (Optional)
          +     *             reuse_key: Boolean (Optional)
          +     *             crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         }
          +     *         secret_props (Optional): {
          +     *             contentType: String (Optional)
          +     *         }
          +     *         x509_props (Optional): {
          +     *             subject: String (Optional)
          +     *             ekus (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             sans (Optional): {
          +     *                 emails (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dns_names (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 upns (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *             }
          +     *             key_usage (Optional): [
          +     *                 String(digitalSignature/nonRepudiation/keyEncipherment/dataEncipherment/keyAgreement/keyCertSign/cRLSign/encipherOnly/decipherOnly) (Optional)
          +     *             ]
          +     *             validity_months: Integer (Optional)
          +     *         }
          +     *         lifetime_actions (Optional): [
          +     *              (Optional){
          +     *                 trigger (Optional): {
          +     *                     lifetime_percentage: Integer (Optional)
          +     *                     days_before_expiry: Integer (Optional)
          +     *                 }
          +     *                 action (Optional): {
          +     *                     action_type: String(EmailContacts/AutoRenew) (Optional)
          +     *                 }
          +     *             }
          +     *         ]
          +     *         issuer (Optional): {
          +     *             name: String (Optional)
          +     *             cty: String (Optional)
          +     *             cert_transparency: Boolean (Optional)
          +     *         }
          +     *         attributes (Optional): {
          +     *             enabled: Boolean (Optional)
          +     *             nbf: Long (Optional)
          +     *             exp: Long (Optional)
          +     *             created: Long (Optional)
          +     *             updated: Long (Optional)
          +     *             recoverableDays: Integer (Optional)
          +     *             recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         }
          +     *     }
          +     *     cer: byte[] (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): (recursive schema, see attributes above)
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateBundleBackup The backup blob associated with a certificate bundle. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param certificateName The name of the certificate in the given key vault. + * @param certificateVersion The version of the certificate. + * @param parameters The parameters for certificate update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a certificate bundle consists of a certificate (X509) plus its attributes along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response restoreCertificateWithResponse(String vaultBaseUrl, - byte[] certificateBundleBackup, Context context) { + public Response updateCertificateWithResponse(String certificateName, String certificateVersion, + BinaryData parameters, RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - CertificateRestoreParameters parameters = new CertificateRestoreParameters(); - parameters.setCertificateBundleBackup(certificateBundleBackup); - return service.restoreCertificateSync(vaultBaseUrl, this.getApiVersion(), parameters, accept, context); + return service.updateCertificateSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + certificateName, certificateVersion, contentType, accept, parameters, requestOptions, Context.NONE); } /** - * Restores a backed up certificate to a vault. + * Gets information about a certificate. * - * Restores a backed up certificate, and all its versions, to a vault. This operation requires the - * certificates/restore permission. + * Gets information about a specific certificate. This operation requires the certificates/get permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     kid: String (Optional)
          +     *     sid: String (Optional)
          +     *     x5t: Base64Url (Optional)
          +     *     policy (Optional): {
          +     *         id: String (Optional)
          +     *         key_props (Optional): {
          +     *             exportable: Boolean (Optional)
          +     *             kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *             key_size: Integer (Optional)
          +     *             reuse_key: Boolean (Optional)
          +     *             crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         }
          +     *         secret_props (Optional): {
          +     *             contentType: String (Optional)
          +     *         }
          +     *         x509_props (Optional): {
          +     *             subject: String (Optional)
          +     *             ekus (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             sans (Optional): {
          +     *                 emails (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dns_names (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 upns (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *             }
          +     *             key_usage (Optional): [
          +     *                 String(digitalSignature/nonRepudiation/keyEncipherment/dataEncipherment/keyAgreement/keyCertSign/cRLSign/encipherOnly/decipherOnly) (Optional)
          +     *             ]
          +     *             validity_months: Integer (Optional)
          +     *         }
          +     *         lifetime_actions (Optional): [
          +     *              (Optional){
          +     *                 trigger (Optional): {
          +     *                     lifetime_percentage: Integer (Optional)
          +     *                     days_before_expiry: Integer (Optional)
          +     *                 }
          +     *                 action (Optional): {
          +     *                     action_type: String(EmailContacts/AutoRenew) (Optional)
          +     *                 }
          +     *             }
          +     *         ]
          +     *         issuer (Optional): {
          +     *             name: String (Optional)
          +     *             cty: String (Optional)
          +     *             cert_transparency: Boolean (Optional)
          +     *         }
          +     *         attributes (Optional): {
          +     *             enabled: Boolean (Optional)
          +     *             nbf: Long (Optional)
          +     *             exp: Long (Optional)
          +     *             created: Long (Optional)
          +     *             updated: Long (Optional)
          +     *             recoverableDays: Integer (Optional)
          +     *             recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         }
          +     *     }
          +     *     cer: byte[] (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): (recursive schema, see attributes above)
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateBundleBackup The backup blob associated with a certificate bundle. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate bundle consists of a certificate (X509) plus its attributes. + * @param certificateName The name of the certificate in the given vault. + * @param certificateVersion The version of the certificate. This URI fragment is optional. If not specified, the + * latest version of the certificate is returned. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return information about a certificate. + * + * Gets information about a specific certificate along with {@link Response} on successful completion of + * {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public CertificateBundle restoreCertificate(String vaultBaseUrl, byte[] certificateBundleBackup) { - return restoreCertificateWithResponse(vaultBaseUrl, certificateBundleBackup, Context.NONE).getValue(); + public Mono> getCertificateWithResponseAsync(String certificateName, String certificateVersion, + RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext( + context -> service.getCertificate(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + certificateName, certificateVersion, accept, requestOptions, context)); } /** - * Lists the deleted certificates in the specified vault currently available for recovery. + * Gets information about a certificate. * - * The GetDeletedCertificates operation retrieves the certificates in the current vault which are in a deleted state - * and ready for recovery or purging. This operation includes deletion-specific information. This operation requires - * the certificates/get/list permission. This operation can only be enabled on soft-delete enabled vaults. + * Gets information about a specific certificate. This operation requires the certificates/get permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     kid: String (Optional)
          +     *     sid: String (Optional)
          +     *     x5t: Base64Url (Optional)
          +     *     policy (Optional): {
          +     *         id: String (Optional)
          +     *         key_props (Optional): {
          +     *             exportable: Boolean (Optional)
          +     *             kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *             key_size: Integer (Optional)
          +     *             reuse_key: Boolean (Optional)
          +     *             crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         }
          +     *         secret_props (Optional): {
          +     *             contentType: String (Optional)
          +     *         }
          +     *         x509_props (Optional): {
          +     *             subject: String (Optional)
          +     *             ekus (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             sans (Optional): {
          +     *                 emails (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dns_names (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 upns (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *             }
          +     *             key_usage (Optional): [
          +     *                 String(digitalSignature/nonRepudiation/keyEncipherment/dataEncipherment/keyAgreement/keyCertSign/cRLSign/encipherOnly/decipherOnly) (Optional)
          +     *             ]
          +     *             validity_months: Integer (Optional)
          +     *         }
          +     *         lifetime_actions (Optional): [
          +     *              (Optional){
          +     *                 trigger (Optional): {
          +     *                     lifetime_percentage: Integer (Optional)
          +     *                     days_before_expiry: Integer (Optional)
          +     *                 }
          +     *                 action (Optional): {
          +     *                     action_type: String(EmailContacts/AutoRenew) (Optional)
          +     *                 }
          +     *             }
          +     *         ]
          +     *         issuer (Optional): {
          +     *             name: String (Optional)
          +     *             cty: String (Optional)
          +     *             cert_transparency: Boolean (Optional)
          +     *         }
          +     *         attributes (Optional): {
          +     *             enabled: Boolean (Optional)
          +     *             nbf: Long (Optional)
          +     *             exp: Long (Optional)
          +     *             created: Long (Optional)
          +     *             updated: Long (Optional)
          +     *             recoverableDays: Integer (Optional)
          +     *             recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         }
          +     *     }
          +     *     cer: byte[] (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): (recursive schema, see attributes above)
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param includePending Specifies whether to include certificates which are not completely provisioned. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of certificates that have been deleted in this vault along with {@link PagedResponse} on - * successful completion of {@link Mono}. + * @param certificateName The name of the certificate in the given vault. + * @param certificateVersion The version of the certificate. This URI fragment is optional. If not specified, the + * latest version of the certificate is returned. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return information about a certificate. + * + * Gets information about a specific certificate along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedCertificatesSinglePageAsync(String vaultBaseUrl, - Integer maxresults, Boolean includePending) { + public Response getCertificateWithResponse(String certificateName, String certificateVersion, + RequestOptions requestOptions) { final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.getDeletedCertificates(vaultBaseUrl, maxresults, includePending, - this.getApiVersion(), accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); + return service.getCertificateSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + certificateName, certificateVersion, accept, requestOptions, Context.NONE); } /** - * Lists the deleted certificates in the specified vault currently available for recovery. + * Updates a certificate operation. * - * The GetDeletedCertificates operation retrieves the certificates in the current vault which are in a deleted state - * and ready for recovery or purging. This operation includes deletion-specific information. This operation requires - * the certificates/get/list permission. This operation can only be enabled on soft-delete enabled vaults. + * Updates a certificate creation operation that is already in progress. This operation requires the + * certificates/update permission. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     cancellation_requested: boolean (Required)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     issuer (Optional): {
          +     *         name: String (Optional)
          +     *         cty: String (Optional)
          +     *         cert_transparency: Boolean (Optional)
          +     *     }
          +     *     csr: byte[] (Optional)
          +     *     cancellation_requested: Boolean (Optional)
          +     *     status: String (Optional)
          +     *     status_details: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     target: String (Optional)
          +     *     request_id: String (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param includePending Specifies whether to include certificates which are not completely provisioned. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of certificates that have been deleted in this vault along with {@link PagedResponse} on + * @param certificateName The name of the certificate. + * @param certificateOperation The certificate operation response. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a certificate operation is returned in case of asynchronous requests along with {@link Response} on * successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedCertificatesSinglePageAsync(String vaultBaseUrl, - Integer maxresults, Boolean includePending, Context context) { + public Mono> updateCertificateOperationWithResponseAsync(String certificateName, + BinaryData certificateOperation, RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - return service - .getDeletedCertificates(vaultBaseUrl, maxresults, includePending, this.getApiVersion(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); + return FluxUtil.withContext( + context -> service.updateCertificateOperation(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + certificateName, contentType, accept, certificateOperation, requestOptions, context)); } /** - * Lists the deleted certificates in the specified vault currently available for recovery. + * Updates a certificate operation. * - * The GetDeletedCertificates operation retrieves the certificates in the current vault which are in a deleted state - * and ready for recovery or purging. This operation includes deletion-specific information. This operation requires - * the certificates/get/list permission. This operation can only be enabled on soft-delete enabled vaults. + * Updates a certificate creation operation that is already in progress. This operation requires the + * certificates/update permission. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     cancellation_requested: boolean (Required)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     issuer (Optional): {
          +     *         name: String (Optional)
          +     *         cty: String (Optional)
          +     *         cert_transparency: Boolean (Optional)
          +     *     }
          +     *     csr: byte[] (Optional)
          +     *     cancellation_requested: Boolean (Optional)
          +     *     status: String (Optional)
          +     *     status_details: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     target: String (Optional)
          +     *     request_id: String (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param includePending Specifies whether to include certificates which are not completely provisioned. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of certificates that have been deleted in this vault as paginated response with {@link PagedFlux}. + * @param certificateName The name of the certificate. + * @param certificateOperation The certificate operation response. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a certificate operation is returned in case of asynchronous requests along with {@link Response}. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getDeletedCertificatesAsync(String vaultBaseUrl, Integer maxresults, - Boolean includePending) { - return new PagedFlux<>(() -> getDeletedCertificatesSinglePageAsync(vaultBaseUrl, maxresults, includePending), - nextLink -> getDeletedCertificatesNextSinglePageAsync(nextLink, vaultBaseUrl)); + @ServiceMethod(returns = ReturnType.SINGLE) + public Response updateCertificateOperationWithResponse(String certificateName, + BinaryData certificateOperation, RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return service.updateCertificateOperationSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + certificateName, contentType, accept, certificateOperation, requestOptions, Context.NONE); } /** - * Lists the deleted certificates in the specified vault currently available for recovery. + * Gets the creation operation of a certificate. * - * The GetDeletedCertificates operation retrieves the certificates in the current vault which are in a deleted state - * and ready for recovery or purging. This operation includes deletion-specific information. This operation requires - * the certificates/get/list permission. This operation can only be enabled on soft-delete enabled vaults. + * Gets the creation operation associated with a specified certificate. This operation requires the certificates/get + * permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     issuer (Optional): {
          +     *         name: String (Optional)
          +     *         cty: String (Optional)
          +     *         cert_transparency: Boolean (Optional)
          +     *     }
          +     *     csr: byte[] (Optional)
          +     *     cancellation_requested: Boolean (Optional)
          +     *     status: String (Optional)
          +     *     status_details: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     target: String (Optional)
          +     *     request_id: String (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param includePending Specifies whether to include certificates which are not completely provisioned. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of certificates that have been deleted in this vault as paginated response with {@link PagedFlux}. + * @param certificateName The name of the certificate. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the creation operation of a certificate. + * + * Gets the creation operation associated with a specified certificate along with {@link Response} on successful + * completion of {@link Mono}. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getDeletedCertificatesAsync(String vaultBaseUrl, Integer maxresults, - Boolean includePending, Context context) { - return new PagedFlux<>( - () -> getDeletedCertificatesSinglePageAsync(vaultBaseUrl, maxresults, includePending, context), - nextLink -> getDeletedCertificatesNextSinglePageAsync(nextLink, vaultBaseUrl, context)); + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getCertificateOperationWithResponseAsync(String certificateName, + RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.getCertificateOperation(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), certificateName, accept, requestOptions, context)); } /** - * Lists the deleted certificates in the specified vault currently available for recovery. + * Gets the creation operation of a certificate. * - * The GetDeletedCertificates operation retrieves the certificates in the current vault which are in a deleted state - * and ready for recovery or purging. This operation includes deletion-specific information. This operation requires - * the certificates/get/list permission. This operation can only be enabled on soft-delete enabled vaults. + * Gets the creation operation associated with a specified certificate. This operation requires the certificates/get + * permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     issuer (Optional): {
          +     *         name: String (Optional)
          +     *         cty: String (Optional)
          +     *         cert_transparency: Boolean (Optional)
          +     *     }
          +     *     csr: byte[] (Optional)
          +     *     cancellation_requested: Boolean (Optional)
          +     *     status: String (Optional)
          +     *     status_details: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     target: String (Optional)
          +     *     request_id: String (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param includePending Specifies whether to include certificates which are not completely provisioned. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of certificates that have been deleted in this vault along with {@link PagedResponse}. + * @param certificateName The name of the certificate. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the creation operation of a certificate. + * + * Gets the creation operation associated with a specified certificate along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getDeletedCertificatesSinglePage(String vaultBaseUrl, - Integer maxresults, Boolean includePending) { + public Response getCertificateOperationWithResponse(String certificateName, + RequestOptions requestOptions) { final String accept = "application/json"; - Response res = service.getDeletedCertificatesSync(vaultBaseUrl, maxresults, - includePending, this.getApiVersion(), accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); + return service.getCertificateOperationSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + certificateName, accept, requestOptions, Context.NONE); } /** - * Lists the deleted certificates in the specified vault currently available for recovery. + * Deletes the creation operation for a specific certificate. * - * The GetDeletedCertificates operation retrieves the certificates in the current vault which are in a deleted state - * and ready for recovery or purging. This operation includes deletion-specific information. This operation requires - * the certificates/get/list permission. This operation can only be enabled on soft-delete enabled vaults. + * Deletes the creation operation for a specified certificate that is in the process of being created. The + * certificate is no longer created. This operation requires the certificates/update permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     issuer (Optional): {
          +     *         name: String (Optional)
          +     *         cty: String (Optional)
          +     *         cert_transparency: Boolean (Optional)
          +     *     }
          +     *     csr: byte[] (Optional)
          +     *     cancellation_requested: Boolean (Optional)
          +     *     status: String (Optional)
          +     *     status_details: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     target: String (Optional)
          +     *     request_id: String (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param includePending Specifies whether to include certificates which are not completely provisioned. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of certificates that have been deleted in this vault along with {@link PagedResponse}. + * @param certificateName The name of the certificate. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a certificate operation is returned in case of asynchronous requests along with {@link Response} on + * successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getDeletedCertificatesSinglePage(String vaultBaseUrl, - Integer maxresults, Boolean includePending, Context context) { + public Mono> deleteCertificateOperationWithResponseAsync(String certificateName, + RequestOptions requestOptions) { final String accept = "application/json"; - Response res = service.getDeletedCertificatesSync(vaultBaseUrl, maxresults, - includePending, this.getApiVersion(), accept, context); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); + return FluxUtil.withContext(context -> service.deleteCertificateOperation(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), certificateName, accept, requestOptions, context)); } /** - * Lists the deleted certificates in the specified vault currently available for recovery. + * Deletes the creation operation for a specific certificate. * - * The GetDeletedCertificates operation retrieves the certificates in the current vault which are in a deleted state - * and ready for recovery or purging. This operation includes deletion-specific information. This operation requires - * the certificates/get/list permission. This operation can only be enabled on soft-delete enabled vaults. + * Deletes the creation operation for a specified certificate that is in the process of being created. The + * certificate is no longer created. This operation requires the certificates/update permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     issuer (Optional): {
          +     *         name: String (Optional)
          +     *         cty: String (Optional)
          +     *         cert_transparency: Boolean (Optional)
          +     *     }
          +     *     csr: byte[] (Optional)
          +     *     cancellation_requested: Boolean (Optional)
          +     *     status: String (Optional)
          +     *     status_details: String (Optional)
          +     *     error (Optional): {
          +     *         code: String (Optional)
          +     *         message: String (Optional)
          +     *         innererror (Optional): (recursive schema, see innererror above)
          +     *     }
          +     *     target: String (Optional)
          +     *     request_id: String (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param includePending Specifies whether to include certificates which are not completely provisioned. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of certificates that have been deleted in this vault as paginated response with - * {@link PagedIterable}. + * @param certificateName The name of the certificate. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a certificate operation is returned in case of asynchronous requests along with {@link Response}. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getDeletedCertificates(String vaultBaseUrl, Integer maxresults, - Boolean includePending) { - return new PagedIterable<>( - () -> getDeletedCertificatesSinglePage(vaultBaseUrl, maxresults, includePending, Context.NONE), - nextLink -> getDeletedCertificatesNextSinglePage(nextLink, vaultBaseUrl)); + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteCertificateOperationWithResponse(String certificateName, + RequestOptions requestOptions) { + final String accept = "application/json"; + return service.deleteCertificateOperationSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + certificateName, accept, requestOptions, Context.NONE); } /** - * Lists the deleted certificates in the specified vault currently available for recovery. + * Merges a certificate or a certificate chain with a key pair existing on the server. * - * The GetDeletedCertificates operation retrieves the certificates in the current vault which are in a deleted state - * and ready for recovery or purging. This operation includes deletion-specific information. This operation requires - * the certificates/get/list permission. This operation can only be enabled on soft-delete enabled vaults. + * The MergeCertificate operation performs the merging of a certificate or certificate chain with a key pair + * currently available in the service. This operation requires the certificates/create permission. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     x5c (Required): [
          +     *         byte[] (Required)
          +     *     ]
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     kid: String (Optional)
          +     *     sid: String (Optional)
          +     *     x5t: Base64Url (Optional)
          +     *     policy (Optional): {
          +     *         id: String (Optional)
          +     *         key_props (Optional): {
          +     *             exportable: Boolean (Optional)
          +     *             kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *             key_size: Integer (Optional)
          +     *             reuse_key: Boolean (Optional)
          +     *             crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         }
          +     *         secret_props (Optional): {
          +     *             contentType: String (Optional)
          +     *         }
          +     *         x509_props (Optional): {
          +     *             subject: String (Optional)
          +     *             ekus (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             sans (Optional): {
          +     *                 emails (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dns_names (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 upns (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *             }
          +     *             key_usage (Optional): [
          +     *                 String(digitalSignature/nonRepudiation/keyEncipherment/dataEncipherment/keyAgreement/keyCertSign/cRLSign/encipherOnly/decipherOnly) (Optional)
          +     *             ]
          +     *             validity_months: Integer (Optional)
          +     *         }
          +     *         lifetime_actions (Optional): [
          +     *              (Optional){
          +     *                 trigger (Optional): {
          +     *                     lifetime_percentage: Integer (Optional)
          +     *                     days_before_expiry: Integer (Optional)
          +     *                 }
          +     *                 action (Optional): {
          +     *                     action_type: String(EmailContacts/AutoRenew) (Optional)
          +     *                 }
          +     *             }
          +     *         ]
          +     *         issuer (Optional): {
          +     *             name: String (Optional)
          +     *             cty: String (Optional)
          +     *             cert_transparency: Boolean (Optional)
          +     *         }
          +     *         attributes (Optional): {
          +     *             enabled: Boolean (Optional)
          +     *             nbf: Long (Optional)
          +     *             exp: Long (Optional)
          +     *             created: Long (Optional)
          +     *             updated: Long (Optional)
          +     *             recoverableDays: Integer (Optional)
          +     *             recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         }
          +     *     }
          +     *     cer: byte[] (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): (recursive schema, see attributes above)
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param includePending Specifies whether to include certificates which are not completely provisioned. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of certificates that have been deleted in this vault as paginated response with - * {@link PagedIterable}. + * @param certificateName The name of the certificate. + * @param parameters The parameters to merge certificate. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a certificate bundle consists of a certificate (X509) plus its attributes along with {@link Response} on + * successful completion of {@link Mono}. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getDeletedCertificates(String vaultBaseUrl, Integer maxresults, - Boolean includePending, Context context) { - return new PagedIterable<>( - () -> getDeletedCertificatesSinglePage(vaultBaseUrl, maxresults, includePending, context), - nextLink -> getDeletedCertificatesNextSinglePage(nextLink, vaultBaseUrl, context)); + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> mergeCertificateWithResponseAsync(String certificateName, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext( + context -> service.mergeCertificate(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + certificateName, contentType, accept, parameters, requestOptions, context)); } /** - * Retrieves information about the specified deleted certificate. + * Merges a certificate or a certificate chain with a key pair existing on the server. * - * The GetDeletedCertificate operation retrieves the deleted certificate information plus its attributes, such as - * retention interval, scheduled permanent deletion and the current deletion recovery level. This operation requires - * the certificates/get permission. + * The MergeCertificate operation performs the merging of a certificate or certificate chain with a key pair + * currently available in the service. This operation requires the certificates/create permission. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     x5c (Required): [
          +     *         byte[] (Required)
          +     *     ]
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     kid: String (Optional)
          +     *     sid: String (Optional)
          +     *     x5t: Base64Url (Optional)
          +     *     policy (Optional): {
          +     *         id: String (Optional)
          +     *         key_props (Optional): {
          +     *             exportable: Boolean (Optional)
          +     *             kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *             key_size: Integer (Optional)
          +     *             reuse_key: Boolean (Optional)
          +     *             crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         }
          +     *         secret_props (Optional): {
          +     *             contentType: String (Optional)
          +     *         }
          +     *         x509_props (Optional): {
          +     *             subject: String (Optional)
          +     *             ekus (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             sans (Optional): {
          +     *                 emails (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dns_names (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 upns (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *             }
          +     *             key_usage (Optional): [
          +     *                 String(digitalSignature/nonRepudiation/keyEncipherment/dataEncipherment/keyAgreement/keyCertSign/cRLSign/encipherOnly/decipherOnly) (Optional)
          +     *             ]
          +     *             validity_months: Integer (Optional)
          +     *         }
          +     *         lifetime_actions (Optional): [
          +     *              (Optional){
          +     *                 trigger (Optional): {
          +     *                     lifetime_percentage: Integer (Optional)
          +     *                     days_before_expiry: Integer (Optional)
          +     *                 }
          +     *                 action (Optional): {
          +     *                     action_type: String(EmailContacts/AutoRenew) (Optional)
          +     *                 }
          +     *             }
          +     *         ]
          +     *         issuer (Optional): {
          +     *             name: String (Optional)
          +     *             cty: String (Optional)
          +     *             cert_transparency: Boolean (Optional)
          +     *         }
          +     *         attributes (Optional): {
          +     *             enabled: Boolean (Optional)
          +     *             nbf: Long (Optional)
          +     *             exp: Long (Optional)
          +     *             created: Long (Optional)
          +     *             updated: Long (Optional)
          +     *             recoverableDays: Integer (Optional)
          +     *             recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         }
          +     *     }
          +     *     cer: byte[] (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): (recursive schema, see attributes above)
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param certificateName The name of the certificate. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Certificate consisting of its previous id, attributes and its tags, as well as information on - * when it will be purged along with {@link Response} on successful completion of {@link Mono}. + * @param parameters The parameters to merge certificate. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a certificate bundle consists of a certificate (X509) plus its attributes along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedCertificateWithResponseAsync(String vaultBaseUrl, - String certificateName) { - return FluxUtil - .withContext(context -> getDeletedCertificateWithResponseAsync(vaultBaseUrl, certificateName, context)); + public Response mergeCertificateWithResponse(String certificateName, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return service.mergeCertificateSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + certificateName, contentType, accept, parameters, requestOptions, Context.NONE); } /** - * Retrieves information about the specified deleted certificate. + * Backs up the specified certificate. * - * The GetDeletedCertificate operation retrieves the deleted certificate information plus its attributes, such as - * retention interval, scheduled permanent deletion and the current deletion recovery level. This operation requires - * the certificates/get permission. + * Requests that a backup of the specified certificate be downloaded to the client. All versions of the certificate + * will be downloaded. This operation requires the certificates/backup permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param certificateName The name of the certificate. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Certificate consisting of its previous id, attributes and its tags, as well as information on - * when it will be purged along with {@link Response} on successful completion of {@link Mono}. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the backup certificate result, containing the backup blob along with {@link Response} on successful + * completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedCertificateWithResponseAsync(String vaultBaseUrl, - String certificateName, Context context) { + public Mono> backupCertificateWithResponseAsync(String certificateName, + RequestOptions requestOptions) { final String accept = "application/json"; - return service.getDeletedCertificate(vaultBaseUrl, certificateName, this.getApiVersion(), accept, context); + return FluxUtil.withContext(context -> service.backupCertificate(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), certificateName, accept, requestOptions, context)); } /** - * Retrieves information about the specified deleted certificate. + * Backs up the specified certificate. * - * The GetDeletedCertificate operation retrieves the deleted certificate information plus its attributes, such as - * retention interval, scheduled permanent deletion and the current deletion recovery level. This operation requires - * the certificates/get permission. + * Requests that a backup of the specified certificate be downloaded to the client. All versions of the certificate + * will be downloaded. This operation requires the certificates/backup permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param certificateName The name of the certificate. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Certificate consisting of its previous id, attributes and its tags, as well as information on - * when it will be purged on successful completion of {@link Mono}. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the backup certificate result, containing the backup blob along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getDeletedCertificateAsync(String vaultBaseUrl, String certificateName) { - return getDeletedCertificateWithResponseAsync(vaultBaseUrl, certificateName) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + public Response backupCertificateWithResponse(String certificateName, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.backupCertificateSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + certificateName, accept, requestOptions, Context.NONE); } /** - * Retrieves information about the specified deleted certificate. - * - * The GetDeletedCertificate operation retrieves the deleted certificate information plus its attributes, such as - * retention interval, scheduled permanent deletion and the current deletion recovery level. This operation requires - * the certificates/get permission. + * Restores a backed up certificate to a vault. * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Certificate consisting of its previous id, attributes and its tags, as well as information on - * when it will be purged on successful completion of {@link Mono}. + * Restores a backed up certificate, and all its versions, to a vault. This operation requires the + * certificates/restore permission. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: Base64Url (Required)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     kid: String (Optional)
          +     *     sid: String (Optional)
          +     *     x5t: Base64Url (Optional)
          +     *     policy (Optional): {
          +     *         id: String (Optional)
          +     *         key_props (Optional): {
          +     *             exportable: Boolean (Optional)
          +     *             kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *             key_size: Integer (Optional)
          +     *             reuse_key: Boolean (Optional)
          +     *             crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         }
          +     *         secret_props (Optional): {
          +     *             contentType: String (Optional)
          +     *         }
          +     *         x509_props (Optional): {
          +     *             subject: String (Optional)
          +     *             ekus (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             sans (Optional): {
          +     *                 emails (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dns_names (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 upns (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *             }
          +     *             key_usage (Optional): [
          +     *                 String(digitalSignature/nonRepudiation/keyEncipherment/dataEncipherment/keyAgreement/keyCertSign/cRLSign/encipherOnly/decipherOnly) (Optional)
          +     *             ]
          +     *             validity_months: Integer (Optional)
          +     *         }
          +     *         lifetime_actions (Optional): [
          +     *              (Optional){
          +     *                 trigger (Optional): {
          +     *                     lifetime_percentage: Integer (Optional)
          +     *                     days_before_expiry: Integer (Optional)
          +     *                 }
          +     *                 action (Optional): {
          +     *                     action_type: String(EmailContacts/AutoRenew) (Optional)
          +     *                 }
          +     *             }
          +     *         ]
          +     *         issuer (Optional): {
          +     *             name: String (Optional)
          +     *             cty: String (Optional)
          +     *             cert_transparency: Boolean (Optional)
          +     *         }
          +     *         attributes (Optional): {
          +     *             enabled: Boolean (Optional)
          +     *             nbf: Long (Optional)
          +     *             exp: Long (Optional)
          +     *             created: Long (Optional)
          +     *             updated: Long (Optional)
          +     *             recoverableDays: Integer (Optional)
          +     *             recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         }
          +     *     }
          +     *     cer: byte[] (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): (recursive schema, see attributes above)
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + * @param parameters The parameters to restore the certificate. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a certificate bundle consists of a certificate (X509) plus its attributes along with {@link Response} on + * successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getDeletedCertificateAsync(String vaultBaseUrl, String certificateName, - Context context) { - return getDeletedCertificateWithResponseAsync(vaultBaseUrl, certificateName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + public Mono> restoreCertificateWithResponseAsync(BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.restoreCertificate(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), contentType, accept, parameters, requestOptions, context)); } /** - * Retrieves information about the specified deleted certificate. - * - * The GetDeletedCertificate operation retrieves the deleted certificate information plus its attributes, such as - * retention interval, scheduled permanent deletion and the current deletion recovery level. This operation requires - * the certificates/get permission. + * Restores a backed up certificate to a vault. * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Certificate consisting of its previous id, attributes and its tags, as well as information on - * when it will be purged along with {@link Response}. + * Restores a backed up certificate, and all its versions, to a vault. This operation requires the + * certificates/restore permission. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: Base64Url (Required)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     kid: String (Optional)
          +     *     sid: String (Optional)
          +     *     x5t: Base64Url (Optional)
          +     *     policy (Optional): {
          +     *         id: String (Optional)
          +     *         key_props (Optional): {
          +     *             exportable: Boolean (Optional)
          +     *             kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *             key_size: Integer (Optional)
          +     *             reuse_key: Boolean (Optional)
          +     *             crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         }
          +     *         secret_props (Optional): {
          +     *             contentType: String (Optional)
          +     *         }
          +     *         x509_props (Optional): {
          +     *             subject: String (Optional)
          +     *             ekus (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             sans (Optional): {
          +     *                 emails (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dns_names (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 upns (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *             }
          +     *             key_usage (Optional): [
          +     *                 String(digitalSignature/nonRepudiation/keyEncipherment/dataEncipherment/keyAgreement/keyCertSign/cRLSign/encipherOnly/decipherOnly) (Optional)
          +     *             ]
          +     *             validity_months: Integer (Optional)
          +     *         }
          +     *         lifetime_actions (Optional): [
          +     *              (Optional){
          +     *                 trigger (Optional): {
          +     *                     lifetime_percentage: Integer (Optional)
          +     *                     days_before_expiry: Integer (Optional)
          +     *                 }
          +     *                 action (Optional): {
          +     *                     action_type: String(EmailContacts/AutoRenew) (Optional)
          +     *                 }
          +     *             }
          +     *         ]
          +     *         issuer (Optional): {
          +     *             name: String (Optional)
          +     *             cty: String (Optional)
          +     *             cert_transparency: Boolean (Optional)
          +     *         }
          +     *         attributes (Optional): {
          +     *             enabled: Boolean (Optional)
          +     *             nbf: Long (Optional)
          +     *             exp: Long (Optional)
          +     *             created: Long (Optional)
          +     *             updated: Long (Optional)
          +     *             recoverableDays: Integer (Optional)
          +     *             recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         }
          +     *     }
          +     *     cer: byte[] (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): (recursive schema, see attributes above)
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + * @param parameters The parameters to restore the certificate. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a certificate bundle consists of a certificate (X509) plus its attributes along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response getDeletedCertificateWithResponse(String vaultBaseUrl, - String certificateName, Context context) { + public Response restoreCertificateWithResponse(BinaryData parameters, RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - return service.getDeletedCertificateSync(vaultBaseUrl, certificateName, this.getApiVersion(), accept, context); + return service.restoreCertificateSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + contentType, accept, parameters, requestOptions, Context.NONE); } /** - * Retrieves information about the specified deleted certificate. - * - * The GetDeletedCertificate operation retrieves the deleted certificate information plus its attributes, such as - * retention interval, scheduled permanent deletion and the current deletion recovery level. This operation requires - * the certificates/get permission. + * Lists the deleted certificates in the specified vault currently available for recovery. * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Certificate consisting of its previous id, attributes and its tags, as well as information on - * when it will be purged. + * The GetDeletedCertificates operation retrieves the certificates in the current vault which are in a deleted state + * and ready for recovery or purging. This operation includes deletion-specific information. This operation requires + * the certificates/get/list permission. This operation can only be enabled on soft-delete enabled vaults. + *

          Query Parameters

          + * + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          includePendingBooleanNoSpecifies whether to include certificates which are not + * completely provisioned.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     x5t: Base64Url (Optional)
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a list of certificates that have been deleted in this vault along with {@link PagedResponse} on + * successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public DeletedCertificateBundle getDeletedCertificate(String vaultBaseUrl, String certificateName) { - return getDeletedCertificateWithResponse(vaultBaseUrl, certificateName, Context.NONE).getValue(); + private Mono> getDeletedCertificatesSinglePageAsync(RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.getDeletedCertificates(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), accept, requestOptions, context)) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } /** - * Permanently deletes the specified deleted certificate. - * - * The PurgeDeletedCertificate operation performs an irreversible deletion of the specified certificate, without - * possibility for recovery. The operation is not available if the recovery level does not specify 'Purgeable'. This - * operation requires the certificate/purge permission. + * Lists the deleted certificates in the specified vault currently available for recovery. * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. + * The GetDeletedCertificates operation retrieves the certificates in the current vault which are in a deleted state + * and ready for recovery or purging. This operation includes deletion-specific information. This operation requires + * the certificates/get/list permission. This operation can only be enabled on soft-delete enabled vaults. + *

          Query Parameters

          + * + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          includePendingBooleanNoSpecifies whether to include certificates which are not + * completely provisioned.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     x5t: Base64Url (Optional)
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a list of certificates that have been deleted in this vault as paginated response with {@link PagedFlux}. */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> purgeDeletedCertificateWithResponseAsync(String vaultBaseUrl, String certificateName) { - return FluxUtil - .withContext(context -> purgeDeletedCertificateWithResponseAsync(vaultBaseUrl, certificateName, context)); + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux getDeletedCertificatesAsync(RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedFlux<>(() -> getDeletedCertificatesSinglePageAsync(requestOptions), + nextLink -> getDeletedCertificatesNextSinglePageAsync(nextLink, requestOptionsForNextPage)); } /** - * Permanently deletes the specified deleted certificate. - * - * The PurgeDeletedCertificate operation performs an irreversible deletion of the specified certificate, without - * possibility for recovery. The operation is not available if the recovery level does not specify 'Purgeable'. This - * operation requires the certificate/purge permission. + * Lists the deleted certificates in the specified vault currently available for recovery. * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. + * The GetDeletedCertificates operation retrieves the certificates in the current vault which are in a deleted state + * and ready for recovery or purging. This operation includes deletion-specific information. This operation requires + * the certificates/get/list permission. This operation can only be enabled on soft-delete enabled vaults. + *

          Query Parameters

          + * + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          includePendingBooleanNoSpecifies whether to include certificates which are not + * completely provisioned.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     x5t: Base64Url (Optional)
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a list of certificates that have been deleted in this vault along with {@link PagedResponse}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> purgeDeletedCertificateWithResponseAsync(String vaultBaseUrl, String certificateName, - Context context) { + private PagedResponse getDeletedCertificatesSinglePage(RequestOptions requestOptions) { final String accept = "application/json"; - return service.purgeDeletedCertificate(vaultBaseUrl, certificateName, this.getApiVersion(), accept, context); + Response res = service.getDeletedCertificatesSync(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), accept, requestOptions, Context.NONE); + return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } /** - * Permanently deletes the specified deleted certificate. - * - * The PurgeDeletedCertificate operation performs an irreversible deletion of the specified certificate, without - * possibility for recovery. The operation is not available if the recovery level does not specify 'Purgeable'. This - * operation requires the certificate/purge permission. + * Lists the deleted certificates in the specified vault currently available for recovery. * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the certificate. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. + * The GetDeletedCertificates operation retrieves the certificates in the current vault which are in a deleted state + * and ready for recovery or purging. This operation includes deletion-specific information. This operation requires + * the certificates/get/list permission. This operation can only be enabled on soft-delete enabled vaults. + *

          Query Parameters

          + * + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          includePendingBooleanNoSpecifies whether to include certificates which are not + * completely provisioned.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     x5t: Base64Url (Optional)
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a list of certificates that have been deleted in this vault as paginated response with + * {@link PagedIterable}. */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono purgeDeletedCertificateAsync(String vaultBaseUrl, String certificateName) { - return purgeDeletedCertificateWithResponseAsync(vaultBaseUrl, certificateName).flatMap(ignored -> Mono.empty()); + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable getDeletedCertificates(RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedIterable<>(() -> getDeletedCertificatesSinglePage(requestOptions), + nextLink -> getDeletedCertificatesNextSinglePage(nextLink, requestOptionsForNextPage)); } /** - * Permanently deletes the specified deleted certificate. + * Retrieves information about the specified deleted certificate. * - * The PurgeDeletedCertificate operation performs an irreversible deletion of the specified certificate, without - * possibility for recovery. The operation is not available if the recovery level does not specify 'Purgeable'. This - * operation requires the certificate/purge permission. + * The GetDeletedCertificate operation retrieves the deleted certificate information plus its attributes, such as + * retention interval, scheduled permanent deletion and the current deletion recovery level. This operation requires + * the certificates/get permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     kid: String (Optional)
          +     *     sid: String (Optional)
          +     *     x5t: Base64Url (Optional)
          +     *     policy (Optional): {
          +     *         id: String (Optional)
          +     *         key_props (Optional): {
          +     *             exportable: Boolean (Optional)
          +     *             kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *             key_size: Integer (Optional)
          +     *             reuse_key: Boolean (Optional)
          +     *             crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         }
          +     *         secret_props (Optional): {
          +     *             contentType: String (Optional)
          +     *         }
          +     *         x509_props (Optional): {
          +     *             subject: String (Optional)
          +     *             ekus (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             sans (Optional): {
          +     *                 emails (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dns_names (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 upns (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *             }
          +     *             key_usage (Optional): [
          +     *                 String(digitalSignature/nonRepudiation/keyEncipherment/dataEncipherment/keyAgreement/keyCertSign/cRLSign/encipherOnly/decipherOnly) (Optional)
          +     *             ]
          +     *             validity_months: Integer (Optional)
          +     *         }
          +     *         lifetime_actions (Optional): [
          +     *              (Optional){
          +     *                 trigger (Optional): {
          +     *                     lifetime_percentage: Integer (Optional)
          +     *                     days_before_expiry: Integer (Optional)
          +     *                 }
          +     *                 action (Optional): {
          +     *                     action_type: String(EmailContacts/AutoRenew) (Optional)
          +     *                 }
          +     *             }
          +     *         ]
          +     *         issuer (Optional): {
          +     *             name: String (Optional)
          +     *             cty: String (Optional)
          +     *             cert_transparency: Boolean (Optional)
          +     *         }
          +     *         attributes (Optional): {
          +     *             enabled: Boolean (Optional)
          +     *             nbf: Long (Optional)
          +     *             exp: Long (Optional)
          +     *             created: Long (Optional)
          +     *             updated: Long (Optional)
          +     *             recoverableDays: Integer (Optional)
          +     *             recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         }
          +     *     }
          +     *     cer: byte[] (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): (recursive schema, see attributes above)
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param certificateName The name of the certificate. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a Deleted Certificate consisting of its previous id, attributes and its tags, as well as information on + * when it will be purged along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono purgeDeletedCertificateAsync(String vaultBaseUrl, String certificateName, Context context) { - return purgeDeletedCertificateWithResponseAsync(vaultBaseUrl, certificateName, context) - .flatMap(ignored -> Mono.empty()); + public Mono> getDeletedCertificateWithResponseAsync(String certificateName, + RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.getDeletedCertificate(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), certificateName, accept, requestOptions, context)); } /** - * Permanently deletes the specified deleted certificate. + * Retrieves information about the specified deleted certificate. * - * The PurgeDeletedCertificate operation performs an irreversible deletion of the specified certificate, without - * possibility for recovery. The operation is not available if the recovery level does not specify 'Purgeable'. This - * operation requires the certificate/purge permission. + * The GetDeletedCertificate operation retrieves the deleted certificate information plus its attributes, such as + * retention interval, scheduled permanent deletion and the current deletion recovery level. This operation requires + * the certificates/get permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     kid: String (Optional)
          +     *     sid: String (Optional)
          +     *     x5t: Base64Url (Optional)
          +     *     policy (Optional): {
          +     *         id: String (Optional)
          +     *         key_props (Optional): {
          +     *             exportable: Boolean (Optional)
          +     *             kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *             key_size: Integer (Optional)
          +     *             reuse_key: Boolean (Optional)
          +     *             crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         }
          +     *         secret_props (Optional): {
          +     *             contentType: String (Optional)
          +     *         }
          +     *         x509_props (Optional): {
          +     *             subject: String (Optional)
          +     *             ekus (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             sans (Optional): {
          +     *                 emails (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dns_names (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 upns (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *             }
          +     *             key_usage (Optional): [
          +     *                 String(digitalSignature/nonRepudiation/keyEncipherment/dataEncipherment/keyAgreement/keyCertSign/cRLSign/encipherOnly/decipherOnly) (Optional)
          +     *             ]
          +     *             validity_months: Integer (Optional)
          +     *         }
          +     *         lifetime_actions (Optional): [
          +     *              (Optional){
          +     *                 trigger (Optional): {
          +     *                     lifetime_percentage: Integer (Optional)
          +     *                     days_before_expiry: Integer (Optional)
          +     *                 }
          +     *                 action (Optional): {
          +     *                     action_type: String(EmailContacts/AutoRenew) (Optional)
          +     *                 }
          +     *             }
          +     *         ]
          +     *         issuer (Optional): {
          +     *             name: String (Optional)
          +     *             cty: String (Optional)
          +     *             cert_transparency: Boolean (Optional)
          +     *         }
          +     *         attributes (Optional): {
          +     *             enabled: Boolean (Optional)
          +     *             nbf: Long (Optional)
          +     *             exp: Long (Optional)
          +     *             created: Long (Optional)
          +     *             updated: Long (Optional)
          +     *             recoverableDays: Integer (Optional)
          +     *             recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         }
          +     *     }
          +     *     cer: byte[] (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): (recursive schema, see attributes above)
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param certificateName The name of the certificate. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response}. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a Deleted Certificate consisting of its previous id, attributes and its tags, as well as information on + * when it will be purged along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response purgeDeletedCertificateWithResponse(String vaultBaseUrl, String certificateName, - Context context) { + public Response getDeletedCertificateWithResponse(String certificateName, + RequestOptions requestOptions) { final String accept = "application/json"; - return service.purgeDeletedCertificateSync(vaultBaseUrl, certificateName, this.getApiVersion(), accept, - context); + return service.getDeletedCertificateSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + certificateName, accept, requestOptions, Context.NONE); } /** @@ -4394,37 +5364,42 @@ public Response purgeDeletedCertificateWithResponse(String vaultBaseUrl, S * possibility for recovery. The operation is not available if the recovery level does not specify 'Purgeable'. This * operation requires the certificate/purge permission. * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param certificateName The name of the certificate. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public void purgeDeletedCertificate(String vaultBaseUrl, String certificateName) { - purgeDeletedCertificateWithResponse(vaultBaseUrl, certificateName, Context.NONE); + public Mono> purgeDeletedCertificateWithResponseAsync(String certificateName, + RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.purgeDeletedCertificate(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), certificateName, accept, requestOptions, context)); } /** - * Recovers the deleted certificate back to its current version under /certificates. + * Permanently deletes the specified deleted certificate. * - * The RecoverDeletedCertificate operation performs the reversal of the Delete operation. The operation is - * applicable in vaults enabled for soft-delete, and must be issued during the retention interval (available in the - * deleted certificate's attributes). This operation requires the certificates/recover permission. + * The PurgeDeletedCertificate operation performs an irreversible deletion of the specified certificate, without + * possibility for recovery. The operation is not available if the recovery level does not specify 'Purgeable'. This + * operation requires the certificate/purge permission. * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the deleted certificate. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate bundle consists of a certificate (X509) plus its attributes along with {@link Response} on - * successful completion of {@link Mono}. + * @param certificateName The name of the certificate. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> recoverDeletedCertificateWithResponseAsync(String vaultBaseUrl, - String certificateName) { - return FluxUtil - .withContext(context -> recoverDeletedCertificateWithResponseAsync(vaultBaseUrl, certificateName, context)); + public Response purgeDeletedCertificateWithResponse(String certificateName, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.purgeDeletedCertificateSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + certificateName, accept, requestOptions, Context.NONE); } /** @@ -4433,65 +5408,99 @@ public Mono> recoverDeletedCertificateWithResponseAs * The RecoverDeletedCertificate operation performs the reversal of the Delete operation. The operation is * applicable in vaults enabled for soft-delete, and must be issued during the retention interval (available in the * deleted certificate's attributes). This operation requires the certificates/recover permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     kid: String (Optional)
          +     *     sid: String (Optional)
          +     *     x5t: Base64Url (Optional)
          +     *     policy (Optional): {
          +     *         id: String (Optional)
          +     *         key_props (Optional): {
          +     *             exportable: Boolean (Optional)
          +     *             kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *             key_size: Integer (Optional)
          +     *             reuse_key: Boolean (Optional)
          +     *             crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         }
          +     *         secret_props (Optional): {
          +     *             contentType: String (Optional)
          +     *         }
          +     *         x509_props (Optional): {
          +     *             subject: String (Optional)
          +     *             ekus (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             sans (Optional): {
          +     *                 emails (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dns_names (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 upns (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *             }
          +     *             key_usage (Optional): [
          +     *                 String(digitalSignature/nonRepudiation/keyEncipherment/dataEncipherment/keyAgreement/keyCertSign/cRLSign/encipherOnly/decipherOnly) (Optional)
          +     *             ]
          +     *             validity_months: Integer (Optional)
          +     *         }
          +     *         lifetime_actions (Optional): [
          +     *              (Optional){
          +     *                 trigger (Optional): {
          +     *                     lifetime_percentage: Integer (Optional)
          +     *                     days_before_expiry: Integer (Optional)
          +     *                 }
          +     *                 action (Optional): {
          +     *                     action_type: String(EmailContacts/AutoRenew) (Optional)
          +     *                 }
          +     *             }
          +     *         ]
          +     *         issuer (Optional): {
          +     *             name: String (Optional)
          +     *             cty: String (Optional)
          +     *             cert_transparency: Boolean (Optional)
          +     *         }
          +     *         attributes (Optional): {
          +     *             enabled: Boolean (Optional)
          +     *             nbf: Long (Optional)
          +     *             exp: Long (Optional)
          +     *             created: Long (Optional)
          +     *             updated: Long (Optional)
          +     *             recoverableDays: Integer (Optional)
          +     *             recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         }
          +     *     }
          +     *     cer: byte[] (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): (recursive schema, see attributes above)
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param certificateName The name of the deleted certificate. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a certificate bundle consists of a certificate (X509) plus its attributes along with {@link Response} on * successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> recoverDeletedCertificateWithResponseAsync(String vaultBaseUrl, - String certificateName, Context context) { + public Mono> recoverDeletedCertificateWithResponseAsync(String certificateName, + RequestOptions requestOptions) { final String accept = "application/json"; - return service.recoverDeletedCertificate(vaultBaseUrl, certificateName, this.getApiVersion(), accept, context); - } - - /** - * Recovers the deleted certificate back to its current version under /certificates. - * - * The RecoverDeletedCertificate operation performs the reversal of the Delete operation. The operation is - * applicable in vaults enabled for soft-delete, and must be issued during the retention interval (available in the - * deleted certificate's attributes). This operation requires the certificates/recover permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the deleted certificate. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate bundle consists of a certificate (X509) plus its attributes on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono recoverDeletedCertificateAsync(String vaultBaseUrl, String certificateName) { - return recoverDeletedCertificateWithResponseAsync(vaultBaseUrl, certificateName) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Recovers the deleted certificate back to its current version under /certificates. - * - * The RecoverDeletedCertificate operation performs the reversal of the Delete operation. The operation is - * applicable in vaults enabled for soft-delete, and must be issued during the retention interval (available in the - * deleted certificate's attributes). This operation requires the certificates/recover permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the deleted certificate. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate bundle consists of a certificate (X509) plus its attributes on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono recoverDeletedCertificateAsync(String vaultBaseUrl, String certificateName, - Context context) { - return recoverDeletedCertificateWithResponseAsync(vaultBaseUrl, certificateName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + return FluxUtil.withContext(context -> service.recoverDeletedCertificate(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), certificateName, accept, requestOptions, context)); } /** @@ -4500,363 +5509,462 @@ public Mono recoverDeletedCertificateAsync(String vaultBaseUr * The RecoverDeletedCertificate operation performs the reversal of the Delete operation. The operation is * applicable in vaults enabled for soft-delete, and must be issued during the retention interval (available in the * deleted certificate's attributes). This operation requires the certificates/recover permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     kid: String (Optional)
          +     *     sid: String (Optional)
          +     *     x5t: Base64Url (Optional)
          +     *     policy (Optional): {
          +     *         id: String (Optional)
          +     *         key_props (Optional): {
          +     *             exportable: Boolean (Optional)
          +     *             kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *             key_size: Integer (Optional)
          +     *             reuse_key: Boolean (Optional)
          +     *             crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         }
          +     *         secret_props (Optional): {
          +     *             contentType: String (Optional)
          +     *         }
          +     *         x509_props (Optional): {
          +     *             subject: String (Optional)
          +     *             ekus (Optional): [
          +     *                 String (Optional)
          +     *             ]
          +     *             sans (Optional): {
          +     *                 emails (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 dns_names (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *                 upns (Optional): [
          +     *                     String (Optional)
          +     *                 ]
          +     *             }
          +     *             key_usage (Optional): [
          +     *                 String(digitalSignature/nonRepudiation/keyEncipherment/dataEncipherment/keyAgreement/keyCertSign/cRLSign/encipherOnly/decipherOnly) (Optional)
          +     *             ]
          +     *             validity_months: Integer (Optional)
          +     *         }
          +     *         lifetime_actions (Optional): [
          +     *              (Optional){
          +     *                 trigger (Optional): {
          +     *                     lifetime_percentage: Integer (Optional)
          +     *                     days_before_expiry: Integer (Optional)
          +     *                 }
          +     *                 action (Optional): {
          +     *                     action_type: String(EmailContacts/AutoRenew) (Optional)
          +     *                 }
          +     *             }
          +     *         ]
          +     *         issuer (Optional): {
          +     *             name: String (Optional)
          +     *             cty: String (Optional)
          +     *             cert_transparency: Boolean (Optional)
          +     *         }
          +     *         attributes (Optional): {
          +     *             enabled: Boolean (Optional)
          +     *             nbf: Long (Optional)
          +     *             exp: Long (Optional)
          +     *             created: Long (Optional)
          +     *             updated: Long (Optional)
          +     *             recoverableDays: Integer (Optional)
          +     *             recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         }
          +     *     }
          +     *     cer: byte[] (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): (recursive schema, see attributes above)
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param certificateName The name of the deleted certificate. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a certificate bundle consists of a certificate (X509) plus its attributes along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response recoverDeletedCertificateWithResponse(String vaultBaseUrl, - String certificateName, Context context) { + public Response recoverDeletedCertificateWithResponse(String certificateName, + RequestOptions requestOptions) { final String accept = "application/json"; - return service.recoverDeletedCertificateSync(vaultBaseUrl, certificateName, this.getApiVersion(), accept, - context); + return service.recoverDeletedCertificateSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + certificateName, accept, requestOptions, Context.NONE); } /** - * Recovers the deleted certificate back to its current version under /certificates. - * - * The RecoverDeletedCertificate operation performs the reversal of the Delete operation. The operation is - * applicable in vaults enabled for soft-delete, and must be issued during the retention interval (available in the - * deleted certificate's attributes). This operation requires the certificates/recover permission. + * List certificates in a specified key vault * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param certificateName The name of the deleted certificate. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a certificate bundle consists of a certificate (X509) plus its attributes. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public CertificateBundle recoverDeletedCertificate(String vaultBaseUrl, String certificateName) { - return recoverDeletedCertificateWithResponse(vaultBaseUrl, certificateName, Context.NONE).getValue(); - } - - /** * Get the next page of items. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     x5t: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          * * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the certificate list result along with {@link PagedResponse} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getCertificatesNextSinglePageAsync(String nextLink, - String vaultBaseUrl) { + private Mono> getCertificatesNextSinglePageAsync(String nextLink, + RequestOptions requestOptions) { final String accept = "application/json"; - return FluxUtil.withContext(context -> service.getCertificatesNext(nextLink, vaultBaseUrl, accept, context)) + return FluxUtil.withContext( + context -> service.getCertificatesNext(nextLink, this.getVaultBaseUrl(), accept, requestOptions, context)) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } /** - * Get the next page of items. + * List certificates in a specified key vault * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the certificate list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getCertificatesNextSinglePageAsync(String nextLink, String vaultBaseUrl, - Context context) { - final String accept = "application/json"; - return service.getCertificatesNext(nextLink, vaultBaseUrl, accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** * Get the next page of items. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     x5t: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          * * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the certificate list result along with {@link PagedResponse}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getCertificatesNextSinglePage(String nextLink, String vaultBaseUrl) { + private PagedResponse getCertificatesNextSinglePage(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; - Response res - = service.getCertificatesNextSync(nextLink, vaultBaseUrl, accept, Context.NONE); + Response res + = service.getCertificatesNextSync(nextLink, this.getVaultBaseUrl(), accept, requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } /** - * Get the next page of items. + * List certificate issuers for a specified key vault. * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the certificate list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getCertificatesNextSinglePage(String nextLink, String vaultBaseUrl, - Context context) { - final String accept = "application/json"; - Response res = service.getCertificatesNextSync(nextLink, vaultBaseUrl, accept, context); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** * Get the next page of items. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     provider: String (Optional)
          +     * }
          +     * }
          +     * 
          * * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the certificate issuer list result along with {@link PagedResponse} on successful completion of * {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getCertificateIssuersNextSinglePageAsync(String nextLink, - String vaultBaseUrl) { + private Mono> getCertificateIssuersNextSinglePageAsync(String nextLink, + RequestOptions requestOptions) { final String accept = "application/json"; return FluxUtil - .withContext(context -> service.getCertificateIssuersNext(nextLink, vaultBaseUrl, accept, context)) + .withContext(context -> service.getCertificateIssuersNext(nextLink, this.getVaultBaseUrl(), accept, + requestOptions, context)) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } /** - * Get the next page of items. + * List certificate issuers for a specified key vault. * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the certificate issuer list result along with {@link PagedResponse} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getCertificateIssuersNextSinglePageAsync(String nextLink, - String vaultBaseUrl, Context context) { - final String accept = "application/json"; - return service.getCertificateIssuersNext(nextLink, vaultBaseUrl, accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** * Get the next page of items. + *

          Response Body Schema

          * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the certificate issuer list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getCertificateIssuersNextSinglePage(String nextLink, - String vaultBaseUrl) { - final String accept = "application/json"; - Response res - = service.getCertificateIssuersNextSync(nextLink, vaultBaseUrl, accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * Get the next page of items. + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     provider: String (Optional)
          +     * }
          +     * }
          +     * 
          * * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the certificate issuer list result along with {@link PagedResponse}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getCertificateIssuersNextSinglePage(String nextLink, - String vaultBaseUrl, Context context) { + private PagedResponse getCertificateIssuersNextSinglePage(String nextLink, + RequestOptions requestOptions) { final String accept = "application/json"; - Response res - = service.getCertificateIssuersNextSync(nextLink, vaultBaseUrl, accept, context); + Response res = service.getCertificateIssuersNextSync(nextLink, this.getVaultBaseUrl(), accept, + requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } /** + * List the versions of a certificate. + * * Get the next page of items. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     x5t: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          * * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the certificate list result along with {@link PagedResponse} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getCertificateVersionsNextSinglePageAsync(String nextLink, - String vaultBaseUrl) { + private Mono> getCertificateVersionsNextSinglePageAsync(String nextLink, + RequestOptions requestOptions) { final String accept = "application/json"; return FluxUtil - .withContext(context -> service.getCertificateVersionsNext(nextLink, vaultBaseUrl, accept, context)) + .withContext(context -> service.getCertificateVersionsNext(nextLink, this.getVaultBaseUrl(), accept, + requestOptions, context)) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } /** - * Get the next page of items. + * List the versions of a certificate. * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the certificate list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getCertificateVersionsNextSinglePageAsync(String nextLink, - String vaultBaseUrl, Context context) { - final String accept = "application/json"; - return service.getCertificateVersionsNext(nextLink, vaultBaseUrl, accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** * Get the next page of items. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     x5t: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          * * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the certificate list result along with {@link PagedResponse}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getCertificateVersionsNextSinglePage(String nextLink, String vaultBaseUrl) { + private PagedResponse getCertificateVersionsNextSinglePage(String nextLink, + RequestOptions requestOptions) { final String accept = "application/json"; - Response res - = service.getCertificateVersionsNextSync(nextLink, vaultBaseUrl, accept, Context.NONE); + Response res = service.getCertificateVersionsNextSync(nextLink, this.getVaultBaseUrl(), accept, + requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } /** - * Get the next page of items. + * Lists the deleted certificates in the specified vault currently available for recovery. * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the certificate list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getCertificateVersionsNextSinglePage(String nextLink, String vaultBaseUrl, - Context context) { - final String accept = "application/json"; - Response res - = service.getCertificateVersionsNextSync(nextLink, vaultBaseUrl, accept, context); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** * Get the next page of items. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     x5t: Base64Url (Optional)
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          * * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a list of certificates that have been deleted in this vault along with {@link PagedResponse} on * successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedCertificatesNextSinglePageAsync(String nextLink, - String vaultBaseUrl) { + private Mono> getDeletedCertificatesNextSinglePageAsync(String nextLink, + RequestOptions requestOptions) { final String accept = "application/json"; return FluxUtil - .withContext(context -> service.getDeletedCertificatesNext(nextLink, vaultBaseUrl, accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of certificates that have been deleted in this vault along with {@link PagedResponse} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedCertificatesNextSinglePageAsync(String nextLink, - String vaultBaseUrl, Context context) { - final String accept = "application/json"; - return service.getDeletedCertificatesNext(nextLink, vaultBaseUrl, accept, context) + .withContext(context -> service.getDeletedCertificatesNext(nextLink, this.getVaultBaseUrl(), accept, + requestOptions, context)) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } /** - * Get the next page of items. + * Lists the deleted certificates in the specified vault currently available for recovery. * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of certificates that have been deleted in this vault along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getDeletedCertificatesNextSinglePage(String nextLink, - String vaultBaseUrl) { - final String accept = "application/json"; - Response res - = service.getDeletedCertificatesNextSync(nextLink, vaultBaseUrl, accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** * Get the next page of items. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     x5t: Base64Url (Optional)
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          * * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a list of certificates that have been deleted in this vault along with {@link PagedResponse}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getDeletedCertificatesNextSinglePage(String nextLink, - String vaultBaseUrl, Context context) { + private PagedResponse getDeletedCertificatesNextSinglePage(String nextLink, + RequestOptions requestOptions) { final String accept = "application/json"; - Response res - = service.getDeletedCertificatesNextSync(nextLink, vaultBaseUrl, accept, context); + Response res = service.getDeletedCertificatesNextSync(nextLink, this.getVaultBaseUrl(), accept, + requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); + } + + private List getValues(BinaryData binaryData, String path) { + try { + Map obj = binaryData.toObject(Map.class); + List values = (List) obj.get(path); + return values.stream().map(BinaryData::fromObject).collect(Collectors.toList()); + } catch (RuntimeException e) { + return null; + } + } + + private String getNextLink(BinaryData binaryData, String path) { + try { + Map obj = binaryData.toObject(Map.class); + return (String) obj.get(path); + } catch (RuntimeException e) { + return null; + } } } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/CertificateIssuerHelper.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/CertificateIssuerHelper.java index 9bd27f53f596..2435dbbfeda1 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/CertificateIssuerHelper.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/CertificateIssuerHelper.java @@ -9,18 +9,18 @@ public final class CertificateIssuerHelper { private static CertificateIssuerAccessor accessor; public interface CertificateIssuerAccessor { - CertificateIssuer createCertificateIssuer(IssuerBundle impl); + CertificateIssuer createCertificateIssuer(IssuerBundle issuerBundle); - IssuerBundle getImpl(CertificateIssuer certificateIssuer); + IssuerBundle getIssuerBundle(CertificateIssuer certificateIssuer); } - public static CertificateIssuer createCertificateIssuer(IssuerBundle impl) { + public static CertificateIssuer createCertificateIssuer(IssuerBundle issuerBundle) { if (accessor == null) { new CertificateIssuer(""); } assert accessor != null; - return accessor.createCertificateIssuer(impl); + return accessor.createCertificateIssuer(issuerBundle); } public static IssuerBundle getIssuerBundle(CertificateIssuer certificateIssuer) { @@ -29,7 +29,7 @@ public static IssuerBundle getIssuerBundle(CertificateIssuer certificateIssuer) } assert accessor != null; - return accessor.getImpl(certificateIssuer); + return accessor.getIssuerBundle(certificateIssuer); } public static void setAccessor(CertificateIssuerAccessor accessor) { diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/CertificatePropertiesHelper.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/CertificatePropertiesHelper.java index 690dd442f312..6d4842dbfa83 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/CertificatePropertiesHelper.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/CertificatePropertiesHelper.java @@ -3,6 +3,7 @@ package com.azure.security.keyvault.certificates.implementation; import com.azure.security.keyvault.certificates.implementation.models.CertificateItem; +import com.azure.security.keyvault.certificates.implementation.models.DeletedCertificateItem; import com.azure.security.keyvault.certificates.models.CertificateProperties; import com.azure.security.keyvault.certificates.models.DeletedCertificate; @@ -11,6 +12,8 @@ public final class CertificatePropertiesHelper { public interface CertificatePropertiesAccessor { CertificateProperties createCertificateProperties(CertificateItem item); + + CertificateProperties createCertificateProperties(DeletedCertificateItem item); } public static CertificateProperties createCertificateProperties(CertificateItem item) { @@ -25,6 +28,18 @@ public static CertificateProperties createCertificateProperties(CertificateItem return accessor.createCertificateProperties(item); } + public static CertificateProperties createCertificateProperties(DeletedCertificateItem item) { + if (accessor == null) { + // CertificateProperties doesn't have a public constructor but DeletedCertificate does and creates an + // instance of CertificateProperties. This will result in CertificateProperties being loaded by the class + // loader. + new DeletedCertificate(); + } + + assert accessor != null; + return accessor.createCertificateProperties(item); + } + public static void setAccessor(CertificatePropertiesAccessor accessor) { CertificatePropertiesHelper.accessor = accessor; } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/Action.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/Action.java index 1d2be598f24a..9ca627df60d5 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/Action.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/Action.java @@ -1,15 +1,14 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.azure.security.keyvault.certificates.models.CertificatePolicyAction; import java.io.IOException; /** @@ -17,32 +16,37 @@ */ @Fluent public final class Action implements JsonSerializable { + /* * The type of the action. */ + @Generated private CertificatePolicyAction actionType; /** * Creates an instance of Action class. */ + @Generated public Action() { } /** * Get the actionType property: The type of the action. - * + * * @return the actionType value. */ + @Generated public CertificatePolicyAction getActionType() { return this.actionType; } /** * Set the actionType property: The type of the action. - * + * * @param actionType the actionType value to set. * @return the Action object itself. */ + @Generated public Action setActionType(CertificatePolicyAction actionType) { this.actionType = actionType; return this; @@ -51,6 +55,7 @@ public Action setActionType(CertificatePolicyAction actionType) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -60,26 +65,25 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of Action from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of Action 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 Action. */ + @Generated public static Action fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { Action deserializedAction = new Action(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("action_type".equals(fieldName)) { deserializedAction.actionType = CertificatePolicyAction.fromString(reader.getString()); } else { reader.skipChildren(); } } - return deserializedAction; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/Attributes.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/Attributes.java deleted file mode 100644 index 28ec25a8a0c1..000000000000 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/Attributes.java +++ /dev/null @@ -1,226 +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.security.keyvault.certificates.implementation.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.time.Instant; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; - -/** - * The object attributes managed by the KeyVault service. - */ -@Fluent -public class Attributes implements JsonSerializable { - /* - * Determines whether the object is enabled. - */ - private Boolean enabled; - - /* - * Not before date in UTC. - */ - private Long notBefore; - - /* - * Expiry date in UTC. - */ - private Long expires; - - /* - * Creation time in UTC. - */ - private Long created; - - /* - * Last updated time in UTC. - */ - private Long updated; - - /** - * Creates an instance of Attributes class. - */ - public Attributes() { - } - - /** - * Get the enabled property: Determines whether the object is enabled. - * - * @return the enabled value. - */ - public Boolean isEnabled() { - return this.enabled; - } - - /** - * Set the enabled property: Determines whether the object is enabled. - * - * @param enabled the enabled value to set. - * @return the Attributes object itself. - */ - public Attributes setEnabled(Boolean enabled) { - this.enabled = enabled; - return this; - } - - /** - * Get the notBefore property: Not before date in UTC. - * - * @return the notBefore value. - */ - public OffsetDateTime getNotBefore() { - if (this.notBefore == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.notBefore), ZoneOffset.UTC); - } - - /** - * Set the notBefore property: Not before date in UTC. - * - * @param notBefore the notBefore value to set. - * @return the Attributes object itself. - */ - public Attributes setNotBefore(OffsetDateTime notBefore) { - if (notBefore == null) { - this.notBefore = null; - } else { - this.notBefore = notBefore.toEpochSecond(); - } - return this; - } - - /** - * Get the expires property: Expiry date in UTC. - * - * @return the expires value. - */ - public OffsetDateTime getExpires() { - if (this.expires == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.expires), ZoneOffset.UTC); - } - - /** - * Set the expires property: Expiry date in UTC. - * - * @param expires the expires value to set. - * @return the Attributes object itself. - */ - public Attributes setExpires(OffsetDateTime expires) { - if (expires == null) { - this.expires = null; - } else { - this.expires = expires.toEpochSecond(); - } - return this; - } - - /** - * Get the created property: Creation time in UTC. - * - * @return the created value. - */ - public OffsetDateTime getCreated() { - if (this.created == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.created), ZoneOffset.UTC); - } - - /** - * Set the created property: Creation time in UTC. - * - * @param created the created value to set. - * @return the Attributes object itself. - */ - Attributes setCreated(OffsetDateTime created) { - if (created == null) { - this.created = null; - } else { - this.created = created.toEpochSecond(); - } - return this; - } - - /** - * Get the updated property: Last updated time in UTC. - * - * @return the updated value. - */ - public OffsetDateTime getUpdated() { - if (this.updated == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.updated), ZoneOffset.UTC); - } - - /** - * Set the updated property: Last updated time in UTC. - * - * @param updated the updated value to set. - * @return the Attributes object itself. - */ - Attributes setUpdated(OffsetDateTime updated) { - if (updated == null) { - this.updated = null; - } else { - this.updated = updated.toEpochSecond(); - } - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeBooleanField("enabled", this.enabled); - jsonWriter.writeNumberField("nbf", this.notBefore); - jsonWriter.writeNumberField("exp", this.expires); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of Attributes from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of Attributes 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 Attributes. - */ - public static Attributes fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - Attributes deserializedAttributes = new Attributes(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("enabled".equals(fieldName)) { - deserializedAttributes.enabled = reader.getNullable(JsonReader::getBoolean); - } else if ("nbf".equals(fieldName)) { - deserializedAttributes.notBefore = reader.getNullable(JsonReader::getLong); - } else if ("exp".equals(fieldName)) { - deserializedAttributes.expires = reader.getNullable(JsonReader::getLong); - } else if ("created".equals(fieldName)) { - deserializedAttributes.created = reader.getNullable(JsonReader::getLong); - } else if ("updated".equals(fieldName)) { - deserializedAttributes.updated = reader.getNullable(JsonReader::getLong); - } else { - reader.skipChildren(); - } - } - - return deserializedAttributes; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/BackupCertificateResult.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/BackupCertificateResult.java index 3031631df13a..9386e8909136 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/BackupCertificateResult.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/BackupCertificateResult.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.core.util.Base64Url; import com.azure.json.JsonReader; @@ -17,22 +17,26 @@ */ @Immutable public final class BackupCertificateResult implements JsonSerializable { + /* * The backup blob containing the backed up certificate. */ + @Generated private Base64Url value; /** * Creates an instance of BackupCertificateResult class. */ - public BackupCertificateResult() { + @Generated + private BackupCertificateResult() { } /** * Get the value property: The backup blob containing the backed up certificate. - * + * * @return the value value. */ + @Generated public byte[] getValue() { if (this.value == null) { return null; @@ -43,6 +47,7 @@ public byte[] getValue() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -51,19 +56,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of BackupCertificateResult from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of BackupCertificateResult 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 BackupCertificateResult. */ + @Generated public static BackupCertificateResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { BackupCertificateResult deserializedBackupCertificateResult = new BackupCertificateResult(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("value".equals(fieldName)) { deserializedBackupCertificateResult.value = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); @@ -71,7 +76,6 @@ public static BackupCertificateResult fromJson(JsonReader jsonReader) throws IOE reader.skipChildren(); } } - return deserializedBackupCertificateResult; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateAttributes.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateAttributes.java index d7e7a407d66c..0b5533a95c3b 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateAttributes.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateAttributes.java @@ -1,11 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; @@ -17,75 +18,145 @@ * The certificate management attributes. */ @Fluent -public final class CertificateAttributes extends Attributes { +public final class CertificateAttributes implements JsonSerializable { + /* - * softDelete data retention days. Value should be >=7 and <=90 when softDelete enabled, otherwise 0. + * Determines whether the object is enabled. */ - private Integer recoverableDays; + @Generated + private Boolean enabled; /* - * Reflects the deletion recovery level currently in effect for certificates in the current vault. If it contains - * 'Purgeable', the certificate can be permanently deleted by a privileged user; otherwise, only the system can - * purge the certificate, at the end of the retention interval. + * Not before date in UTC. */ - private DeletionRecoveryLevel recoveryLevel; + @Generated + private Long notBefore; /* - * Last updated time in UTC. + * Expiry date in UTC. */ - private Long updated; + @Generated + private Long expires; /* * Creation time in UTC. */ + @Generated private Long created; + /* + * Last updated time in UTC. + */ + @Generated + private Long updated; + + /* + * softDelete data retention days. Value should be >=7 and <=90 when softDelete enabled, otherwise 0. + */ + @Generated + private Integer recoverableDays; + + /* + * Reflects the deletion recovery level currently in effect for certificates in the current vault. If it contains + * 'Purgeable', the certificate can be permanently deleted by a privileged user; otherwise, only the system can + * purge the certificate, at the end of the retention interval. + */ + @Generated + private DeletionRecoveryLevel adminContacts; + /** * Creates an instance of CertificateAttributes class. */ + @Generated public CertificateAttributes() { } /** - * Get the recoverableDays property: softDelete data retention days. Value should be >=7 and <=90 when - * softDelete enabled, otherwise 0. - * - * @return the recoverableDays value. + * Get the enabled property: Determines whether the object is enabled. + * + * @return the enabled value. */ - public Integer getRecoverableDays() { - return this.recoverableDays; + @Generated + public Boolean isEnabled() { + return this.enabled; } /** - * Get the recoveryLevel property: Reflects the deletion recovery level currently in effect for certificates in the - * current vault. If it contains 'Purgeable', the certificate can be permanently deleted by a privileged user; - * otherwise, only the system can purge the certificate, at the end of the retention interval. - * - * @return the recoveryLevel value. + * Set the enabled property: Determines whether the object is enabled. + * + * @param enabled the enabled value to set. + * @return the CertificateAttributes object itself. */ - public DeletionRecoveryLevel getRecoveryLevel() { - return this.recoveryLevel; + @Generated + public CertificateAttributes setEnabled(Boolean enabled) { + this.enabled = enabled; + return this; } /** - * Get the updated property: Last updated time in UTC. - * - * @return the updated value. + * Get the notBefore property: Not before date in UTC. + * + * @return the notBefore value. */ - @Override - public OffsetDateTime getUpdated() { - if (this.updated == null) { + @Generated + public OffsetDateTime getNotBefore() { + if (this.notBefore == null) { return null; } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.updated), ZoneOffset.UTC); + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.notBefore), ZoneOffset.UTC); + } + + /** + * Set the notBefore property: Not before date in UTC. + * + * @param notBefore the notBefore value to set. + * @return the CertificateAttributes object itself. + */ + @Generated + public CertificateAttributes setNotBefore(OffsetDateTime notBefore) { + if (notBefore == null) { + this.notBefore = null; + } else { + this.notBefore = notBefore.toEpochSecond(); + } + return this; + } + + /** + * Get the expires property: Expiry date in UTC. + * + * @return the expires value. + */ + @Generated + public OffsetDateTime getExpires() { + if (this.expires == null) { + return null; + } + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.expires), ZoneOffset.UTC); + } + + /** + * Set the expires property: Expiry date in UTC. + * + * @param expires the expires value to set. + * @return the CertificateAttributes object itself. + */ + @Generated + public CertificateAttributes setExpires(OffsetDateTime expires) { + if (expires == null) { + this.expires = null; + } else { + this.expires = expires.toEpochSecond(); + } + return this; } /** * Get the created property: Creation time in UTC. - * + * * @return the created value. */ - @Override + @Generated public OffsetDateTime getCreated() { if (this.created == null) { return null; @@ -94,77 +165,75 @@ public OffsetDateTime getCreated() { } /** - * {@inheritDoc} + * Get the updated property: Last updated time in UTC. + * + * @return the updated value. */ - @Override - public CertificateAttributes setEnabled(Boolean enabled) { - super.setEnabled(enabled); - return this; + @Generated + public OffsetDateTime getUpdated() { + if (this.updated == null) { + return null; + } + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.updated), ZoneOffset.UTC); } /** - * {@inheritDoc} + * Get the recoverableDays property: softDelete data retention days. Value should be >=7 and <=90 when + * softDelete enabled, otherwise 0. + * + * @return the recoverableDays value. */ - @Override - public CertificateAttributes setNotBefore(OffsetDateTime notBefore) { - super.setNotBefore(notBefore); - return this; + @Generated + public Integer getRecoverableDays() { + return this.recoverableDays; } /** - * {@inheritDoc} + * Get the adminContacts property: Reflects the deletion recovery level currently in effect for certificates in the + * current vault. If it contains 'Purgeable', the certificate can be permanently deleted by a privileged user; + * otherwise, only the system can purge the certificate, at the end of the retention interval. + * + * @return the adminContacts value. */ - @Override - public CertificateAttributes setExpires(OffsetDateTime expires) { - super.setExpires(expires); - return this; + @Generated + public DeletionRecoveryLevel getAdminContacts() { + return this.adminContacts; } /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeBooleanField("enabled", isEnabled()); - if (getNotBefore() != null) { - jsonWriter.writeNumberField("nbf", getNotBefore().toEpochSecond()); - } - if (getExpires() != null) { - jsonWriter.writeNumberField("exp", getExpires().toEpochSecond()); - } + jsonWriter.writeBooleanField("enabled", this.enabled); + jsonWriter.writeNumberField("nbf", this.notBefore); + jsonWriter.writeNumberField("exp", this.expires); return jsonWriter.writeEndObject(); } /** * Reads an instance of CertificateAttributes from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of CertificateAttributes 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 CertificateAttributes. */ + @Generated public static CertificateAttributes fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { CertificateAttributes deserializedCertificateAttributes = new CertificateAttributes(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("enabled".equals(fieldName)) { - deserializedCertificateAttributes.setEnabled(reader.getNullable(JsonReader::getBoolean)); + deserializedCertificateAttributes.enabled = reader.getNullable(JsonReader::getBoolean); } else if ("nbf".equals(fieldName)) { - Long notBeforeHolder = reader.getNullable(JsonReader::getLong); - if (notBeforeHolder != null) { - deserializedCertificateAttributes.setNotBefore( - OffsetDateTime.ofInstant(Instant.ofEpochSecond(notBeforeHolder), ZoneOffset.UTC)); - } + deserializedCertificateAttributes.notBefore = reader.getNullable(JsonReader::getLong); } else if ("exp".equals(fieldName)) { - Long expiresHolder = reader.getNullable(JsonReader::getLong); - if (expiresHolder != null) { - deserializedCertificateAttributes - .setExpires(OffsetDateTime.ofInstant(Instant.ofEpochSecond(expiresHolder), ZoneOffset.UTC)); - } + deserializedCertificateAttributes.expires = reader.getNullable(JsonReader::getLong); } else if ("created".equals(fieldName)) { deserializedCertificateAttributes.created = reader.getNullable(JsonReader::getLong); } else if ("updated".equals(fieldName)) { @@ -172,13 +241,12 @@ public static CertificateAttributes fromJson(JsonReader jsonReader) throws IOExc } else if ("recoverableDays".equals(fieldName)) { deserializedCertificateAttributes.recoverableDays = reader.getNullable(JsonReader::getInt); } else if ("recoveryLevel".equals(fieldName)) { - deserializedCertificateAttributes.recoveryLevel + deserializedCertificateAttributes.adminContacts = DeletionRecoveryLevel.fromString(reader.getString()); } else { reader.skipChildren(); } } - return deserializedCertificateAttributes; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateBundle.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateBundle.java index 06c7d4101038..e2d13f30bc25 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateBundle.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateBundle.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; import com.azure.core.util.Base64Url; import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; @@ -17,124 +17,106 @@ /** * A certificate bundle consists of a certificate (X509) plus its attributes. */ -@Fluent -public class CertificateBundle implements JsonSerializable { +@Immutable +public final class CertificateBundle implements JsonSerializable { + /* * The certificate id. */ + @Generated private String id; /* * The key id. */ + @Generated private String kid; /* * The secret id. */ + @Generated private String sid; /* * Thumbprint of the certificate. */ + @Generated private Base64Url x509Thumbprint; /* * The management policy. */ + @Generated private CertificatePolicy policy; /* * CER contents of x509 certificate. */ + @Generated private byte[] cer; /* * The content type of the secret. eg. 'application/x-pem-file' or 'application/x-pkcs12', */ + @Generated private String contentType; /* * The certificate attributes. */ + @Generated private CertificateAttributes attributes; /* * Application specific metadata in the form of key-value pairs */ + @Generated private Map tags; /** * Creates an instance of CertificateBundle class. */ - public CertificateBundle() { + @Generated + private CertificateBundle() { } /** * Get the id property: The certificate id. - * + * * @return the id value. */ + @Generated public String getId() { return this.id; } - /** - * Set the id property: The certificate id. - * - * @param id the id value to set. - * @return the CertificateBundle object itself. - */ - CertificateBundle setId(String id) { - this.id = id; - return this; - } - /** * Get the kid property: The key id. - * + * * @return the kid value. */ + @Generated public String getKid() { return this.kid; } - /** - * Set the kid property: The key id. - * - * @param kid the kid value to set. - * @return the CertificateBundle object itself. - */ - CertificateBundle setKid(String kid) { - this.kid = kid; - return this; - } - /** * Get the sid property: The secret id. - * + * * @return the sid value. */ + @Generated public String getSid() { return this.sid; } - /** - * Set the sid property: The secret id. - * - * @param sid the sid value to set. - * @return the CertificateBundle object itself. - */ - CertificateBundle setSid(String sid) { - this.sid = sid; - return this; - } - /** * Get the x509Thumbprint property: Thumbprint of the certificate. - * + * * @return the x509Thumbprint value. */ + @Generated public byte[] getX509Thumbprint() { if (this.x509Thumbprint == null) { return null; @@ -142,126 +124,61 @@ public byte[] getX509Thumbprint() { return this.x509Thumbprint.decodedBytes(); } - /** - * Set the x509Thumbprint property: Thumbprint of the certificate. - * - * @param x509Thumbprint the x509Thumbprint value to set. - * @return the CertificateBundle object itself. - */ - CertificateBundle setX509Thumbprint(byte[] x509Thumbprint) { - if (x509Thumbprint == null) { - this.x509Thumbprint = null; - } else { - this.x509Thumbprint = Base64Url.encode(CoreUtils.clone(x509Thumbprint)); - } - return this; - } - /** * Get the policy property: The management policy. - * + * * @return the policy value. */ + @Generated public CertificatePolicy getPolicy() { return this.policy; } - /** - * Set the policy property: The management policy. - * - * @param policy the policy value to set. - * @return the CertificateBundle object itself. - */ - CertificateBundle setPolicy(CertificatePolicy policy) { - this.policy = policy; - return this; - } - /** * Get the cer property: CER contents of x509 certificate. - * + * * @return the cer value. */ + @Generated public byte[] getCer() { return CoreUtils.clone(this.cer); } - /** - * Set the cer property: CER contents of x509 certificate. - * - * @param cer the cer value to set. - * @return the CertificateBundle object itself. - */ - public CertificateBundle setCer(byte[] cer) { - this.cer = CoreUtils.clone(cer); - return this; - } - /** * Get the contentType property: The content type of the secret. eg. 'application/x-pem-file' or * 'application/x-pkcs12',. - * + * * @return the contentType value. */ + @Generated public String getContentType() { return this.contentType; } - /** - * Set the contentType property: The content type of the secret. eg. 'application/x-pem-file' or - * 'application/x-pkcs12',. - * - * @param contentType the contentType value to set. - * @return the CertificateBundle object itself. - */ - public CertificateBundle setContentType(String contentType) { - this.contentType = contentType; - return this; - } - /** * Get the attributes property: The certificate attributes. - * + * * @return the attributes value. */ + @Generated public CertificateAttributes getAttributes() { return this.attributes; } - /** - * Set the attributes property: The certificate attributes. - * - * @param attributes the attributes value to set. - * @return the CertificateBundle object itself. - */ - public CertificateBundle setAttributes(CertificateAttributes attributes) { - this.attributes = attributes; - return this; - } - /** * Get the tags property: Application specific metadata in the form of key-value pairs. - * + * * @return the tags value. */ + @Generated public Map getTags() { return this.tags; } - /** - * Set the tags property: Application specific metadata in the form of key-value pairs. - * - * @param tags the tags value to set. - * @return the CertificateBundle object itself. - */ - public CertificateBundle setTags(Map tags) { - this.tags = tags; - return this; - } - /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -274,19 +191,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of CertificateBundle from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of CertificateBundle 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 CertificateBundle. */ + @Generated public static CertificateBundle fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { CertificateBundle deserializedCertificateBundle = new CertificateBundle(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("id".equals(fieldName)) { deserializedCertificateBundle.id = reader.getString(); } else if ("kid".equals(fieldName)) { @@ -311,7 +228,6 @@ public static CertificateBundle fromJson(JsonReader jsonReader) throws IOExcepti reader.skipChildren(); } } - return deserializedCertificateBundle; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateCreateParameters.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateCreateParameters.java index b2f4d960f564..7909480e5959 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateCreateParameters.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateCreateParameters.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -17,42 +17,49 @@ */ @Fluent public final class CertificateCreateParameters implements JsonSerializable { + /* * The management policy for the certificate. */ + @Generated private CertificatePolicy certificatePolicy; /* * The attributes of the certificate (optional). */ + @Generated private CertificateAttributes certificateAttributes; /* * Application specific metadata in the form of key-value pairs. */ + @Generated private Map tags; /** * Creates an instance of CertificateCreateParameters class. */ + @Generated public CertificateCreateParameters() { } /** * Get the certificatePolicy property: The management policy for the certificate. - * + * * @return the certificatePolicy value. */ + @Generated public CertificatePolicy getCertificatePolicy() { return this.certificatePolicy; } /** * Set the certificatePolicy property: The management policy for the certificate. - * + * * @param certificatePolicy the certificatePolicy value to set. * @return the CertificateCreateParameters object itself. */ + @Generated public CertificateCreateParameters setCertificatePolicy(CertificatePolicy certificatePolicy) { this.certificatePolicy = certificatePolicy; return this; @@ -60,19 +67,21 @@ public CertificateCreateParameters setCertificatePolicy(CertificatePolicy certif /** * Get the certificateAttributes property: The attributes of the certificate (optional). - * + * * @return the certificateAttributes value. */ + @Generated public CertificateAttributes getCertificateAttributes() { return this.certificateAttributes; } /** * Set the certificateAttributes property: The attributes of the certificate (optional). - * + * * @param certificateAttributes the certificateAttributes value to set. * @return the CertificateCreateParameters object itself. */ + @Generated public CertificateCreateParameters setCertificateAttributes(CertificateAttributes certificateAttributes) { this.certificateAttributes = certificateAttributes; return this; @@ -80,19 +89,21 @@ public CertificateCreateParameters setCertificateAttributes(CertificateAttribute /** * Get the tags property: Application specific metadata in the form of key-value pairs. - * + * * @return the tags value. */ + @Generated public Map getTags() { return this.tags; } /** * Set the tags property: Application specific metadata in the form of key-value pairs. - * + * * @param tags the tags value to set. * @return the CertificateCreateParameters object itself. */ + @Generated public CertificateCreateParameters setTags(Map tags) { this.tags = tags; return this; @@ -101,6 +112,7 @@ public CertificateCreateParameters setTags(Map tags) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -112,19 +124,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of CertificateCreateParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of CertificateCreateParameters 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 CertificateCreateParameters. */ + @Generated public static CertificateCreateParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { CertificateCreateParameters deserializedCertificateCreateParameters = new CertificateCreateParameters(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("policy".equals(fieldName)) { deserializedCertificateCreateParameters.certificatePolicy = CertificatePolicy.fromJson(reader); } else if ("attributes".equals(fieldName)) { @@ -137,7 +149,6 @@ public static CertificateCreateParameters fromJson(JsonReader jsonReader) throws reader.skipChildren(); } } - return deserializedCertificateCreateParameters; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateImportParameters.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateImportParameters.java index 63c062bced7a..41f6b8cb13f6 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateImportParameters.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateImportParameters.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -17,66 +17,66 @@ */ @Fluent public final class CertificateImportParameters implements JsonSerializable { + /* * Base64 encoded representation of the certificate object to import. This certificate needs to contain the private * key. */ - private String base64EncodedCertificate; + @Generated + private final String base64EncodedCertificate; /* * If the private key in base64EncodedCertificate is encrypted, the password used for encryption. */ + @Generated private String password; /* * The management policy for the certificate. */ + @Generated private CertificatePolicy certificatePolicy; /* * The attributes of the certificate (optional). */ + @Generated private CertificateAttributes certificateAttributes; /* * Application specific metadata in the form of key-value pairs. */ + @Generated private Map tags; /** * Creates an instance of CertificateImportParameters class. + * + * @param base64EncodedCertificate the base64EncodedCertificate value to set. */ - public CertificateImportParameters() { + @Generated + public CertificateImportParameters(String base64EncodedCertificate) { + this.base64EncodedCertificate = base64EncodedCertificate; } /** * Get the base64EncodedCertificate property: Base64 encoded representation of the certificate object to import. * This certificate needs to contain the private key. - * + * * @return the base64EncodedCertificate value. */ + @Generated public String getBase64EncodedCertificate() { return this.base64EncodedCertificate; } - /** - * Set the base64EncodedCertificate property: Base64 encoded representation of the certificate object to import. - * This certificate needs to contain the private key. - * - * @param base64EncodedCertificate the base64EncodedCertificate value to set. - * @return the CertificateImportParameters object itself. - */ - public CertificateImportParameters setBase64EncodedCertificate(String base64EncodedCertificate) { - this.base64EncodedCertificate = base64EncodedCertificate; - return this; - } - /** * Get the password property: If the private key in base64EncodedCertificate is encrypted, the password used for * encryption. - * + * * @return the password value. */ + @Generated public String getPassword() { return this.password; } @@ -84,10 +84,11 @@ public String getPassword() { /** * Set the password property: If the private key in base64EncodedCertificate is encrypted, the password used for * encryption. - * + * * @param password the password value to set. * @return the CertificateImportParameters object itself. */ + @Generated public CertificateImportParameters setPassword(String password) { this.password = password; return this; @@ -95,19 +96,21 @@ public CertificateImportParameters setPassword(String password) { /** * Get the certificatePolicy property: The management policy for the certificate. - * + * * @return the certificatePolicy value. */ + @Generated public CertificatePolicy getCertificatePolicy() { return this.certificatePolicy; } /** * Set the certificatePolicy property: The management policy for the certificate. - * + * * @param certificatePolicy the certificatePolicy value to set. * @return the CertificateImportParameters object itself. */ + @Generated public CertificateImportParameters setCertificatePolicy(CertificatePolicy certificatePolicy) { this.certificatePolicy = certificatePolicy; return this; @@ -115,19 +118,21 @@ public CertificateImportParameters setCertificatePolicy(CertificatePolicy certif /** * Get the certificateAttributes property: The attributes of the certificate (optional). - * + * * @return the certificateAttributes value. */ + @Generated public CertificateAttributes getCertificateAttributes() { return this.certificateAttributes; } /** * Set the certificateAttributes property: The attributes of the certificate (optional). - * + * * @param certificateAttributes the certificateAttributes value to set. * @return the CertificateImportParameters object itself. */ + @Generated public CertificateImportParameters setCertificateAttributes(CertificateAttributes certificateAttributes) { this.certificateAttributes = certificateAttributes; return this; @@ -135,19 +140,21 @@ public CertificateImportParameters setCertificateAttributes(CertificateAttribute /** * Get the tags property: Application specific metadata in the form of key-value pairs. - * + * * @return the tags value. */ + @Generated public Map getTags() { return this.tags; } /** * Set the tags property: Application specific metadata in the form of key-value pairs. - * + * * @param tags the tags value to set. * @return the CertificateImportParameters object itself. */ + @Generated public CertificateImportParameters setTags(Map tags) { this.tags = tags; return this; @@ -156,6 +163,7 @@ public CertificateImportParameters setTags(Map tags) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -169,37 +177,44 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of CertificateImportParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of CertificateImportParameters 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 CertificateImportParameters. */ + @Generated public static CertificateImportParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - CertificateImportParameters deserializedCertificateImportParameters = new CertificateImportParameters(); + String base64EncodedCertificate = null; + String password = null; + CertificatePolicy certificatePolicy = null; + CertificateAttributes certificateAttributes = null; + Map tags = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("value".equals(fieldName)) { - deserializedCertificateImportParameters.base64EncodedCertificate = reader.getString(); + base64EncodedCertificate = reader.getString(); } else if ("pwd".equals(fieldName)) { - deserializedCertificateImportParameters.password = reader.getString(); + password = reader.getString(); } else if ("policy".equals(fieldName)) { - deserializedCertificateImportParameters.certificatePolicy = CertificatePolicy.fromJson(reader); + certificatePolicy = CertificatePolicy.fromJson(reader); } else if ("attributes".equals(fieldName)) { - deserializedCertificateImportParameters.certificateAttributes - = CertificateAttributes.fromJson(reader); + certificateAttributes = CertificateAttributes.fromJson(reader); } else if ("tags".equals(fieldName)) { - Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedCertificateImportParameters.tags = tags; + tags = reader.readMap(reader1 -> reader1.getString()); } else { reader.skipChildren(); } } - + CertificateImportParameters deserializedCertificateImportParameters + = new CertificateImportParameters(base64EncodedCertificate); + deserializedCertificateImportParameters.password = password; + deserializedCertificateImportParameters.certificatePolicy = certificatePolicy; + deserializedCertificateImportParameters.certificateAttributes = certificateAttributes; + deserializedCertificateImportParameters.tags = tags; return deserializedCertificateImportParameters; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateIssuerItem.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateIssuerItem.java index b3a82fd210d3..edd21217bfeb 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateIssuerItem.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateIssuerItem.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -16,65 +16,50 @@ */ @Fluent public final class CertificateIssuerItem implements JsonSerializable { + /* * Certificate Identifier. */ + @Generated private String id; /* * The issuer provider. */ + @Generated private String provider; /** * Creates an instance of CertificateIssuerItem class. */ + @Generated public CertificateIssuerItem() { } /** * Get the id property: Certificate Identifier. - * + * * @return the id value. */ + @Generated public String getId() { return this.id; } - /** - * Set the id property: Certificate Identifier. - * - * @param id the id value to set. - * @return the CertificateIssuerItem object itself. - */ - public CertificateIssuerItem setId(String id) { - this.id = id; - return this; - } - /** * Get the provider property: The issuer provider. - * + * * @return the provider value. */ + @Generated public String getProvider() { return this.provider; } - /** - * Set the provider property: The issuer provider. - * - * @param provider the provider value to set. - * @return the CertificateIssuerItem object itself. - */ - public CertificateIssuerItem setProvider(String provider) { - this.provider = provider; - return this; - } - /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -85,19 +70,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of CertificateIssuerItem from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of CertificateIssuerItem 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 CertificateIssuerItem. */ + @Generated public static CertificateIssuerItem fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { CertificateIssuerItem deserializedCertificateIssuerItem = new CertificateIssuerItem(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("id".equals(fieldName)) { deserializedCertificateIssuerItem.id = reader.getString(); } else if ("provider".equals(fieldName)) { @@ -106,8 +91,31 @@ public static CertificateIssuerItem fromJson(JsonReader jsonReader) throws IOExc reader.skipChildren(); } } - return deserializedCertificateIssuerItem; }); } + + /** + * Set the id property: Certificate Identifier. + * + * @param id the id value to set. + * @return the CertificateIssuerItem object itself. + */ + @Generated + public CertificateIssuerItem setId(String id) { + this.id = id; + return this; + } + + /** + * Set the provider property: The issuer provider. + * + * @param provider the provider value to set. + * @return the CertificateIssuerItem object itself. + */ + @Generated + public CertificateIssuerItem setProvider(String provider) { + this.provider = provider; + return this; + } } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateIssuerListResult.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateIssuerListResult.java index 73495be17c0a..8fa3b04b4347 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateIssuerListResult.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateIssuerListResult.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -17,38 +17,44 @@ */ @Immutable public final class CertificateIssuerListResult implements JsonSerializable { + /* * A response message containing a list of certificate issuers in the key vault along with a link to the next page * of certificate issuers. */ + @Generated private List value; /* * The URL to get the next set of certificate issuers. */ + @Generated private String nextLink; /** * Creates an instance of CertificateIssuerListResult class. */ - public CertificateIssuerListResult() { + @Generated + private CertificateIssuerListResult() { } /** * Get the value property: A response message containing a list of certificate issuers in the key vault along with a * link to the next page of certificate issuers. - * + * * @return the value value. */ + @Generated public List getValue() { return this.value; } /** * Get the nextLink property: The URL to get the next set of certificate issuers. - * + * * @return the nextLink value. */ + @Generated public String getNextLink() { return this.nextLink; } @@ -56,6 +62,7 @@ public String getNextLink() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -64,19 +71,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of CertificateIssuerListResult from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of CertificateIssuerListResult 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 CertificateIssuerListResult. */ + @Generated public static CertificateIssuerListResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { CertificateIssuerListResult deserializedCertificateIssuerListResult = new CertificateIssuerListResult(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("value".equals(fieldName)) { List value = reader.readArray(reader1 -> CertificateIssuerItem.fromJson(reader1)); @@ -87,7 +94,6 @@ public static CertificateIssuerListResult fromJson(JsonReader jsonReader) throws reader.skipChildren(); } } - return deserializedCertificateIssuerListResult; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateIssuerSetParameters.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateIssuerSetParameters.java index ce6e00c1243e..5b7507879b37 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateIssuerSetParameters.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateIssuerSetParameters.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -16,67 +16,68 @@ */ @Fluent public final class CertificateIssuerSetParameters implements JsonSerializable { + /* * The issuer provider. */ - private String provider; + @Generated + private final String provider; /* * The credentials to be used for the issuer. */ + @Generated private IssuerCredentials credentials; /* * Details of the organization as provided to the issuer. */ + @Generated private OrganizationDetails organizationDetails; /* * Attributes of the issuer object. */ + @Generated private IssuerAttributes attributes; /** * Creates an instance of CertificateIssuerSetParameters class. + * + * @param provider the provider value to set. */ - public CertificateIssuerSetParameters() { + @Generated + public CertificateIssuerSetParameters(String provider) { + this.provider = provider; } /** * Get the provider property: The issuer provider. - * + * * @return the provider value. */ + @Generated public String getProvider() { return this.provider; } - /** - * Set the provider property: The issuer provider. - * - * @param provider the provider value to set. - * @return the CertificateIssuerSetParameters object itself. - */ - public CertificateIssuerSetParameters setProvider(String provider) { - this.provider = provider; - return this; - } - /** * Get the credentials property: The credentials to be used for the issuer. - * + * * @return the credentials value. */ + @Generated public IssuerCredentials getCredentials() { return this.credentials; } /** * Set the credentials property: The credentials to be used for the issuer. - * + * * @param credentials the credentials value to set. * @return the CertificateIssuerSetParameters object itself. */ + @Generated public CertificateIssuerSetParameters setCredentials(IssuerCredentials credentials) { this.credentials = credentials; return this; @@ -84,19 +85,21 @@ public CertificateIssuerSetParameters setCredentials(IssuerCredentials credentia /** * Get the organizationDetails property: Details of the organization as provided to the issuer. - * + * * @return the organizationDetails value. */ + @Generated public OrganizationDetails getOrganizationDetails() { return this.organizationDetails; } /** * Set the organizationDetails property: Details of the organization as provided to the issuer. - * + * * @param organizationDetails the organizationDetails value to set. * @return the CertificateIssuerSetParameters object itself. */ + @Generated public CertificateIssuerSetParameters setOrganizationDetails(OrganizationDetails organizationDetails) { this.organizationDetails = organizationDetails; return this; @@ -104,19 +107,21 @@ public CertificateIssuerSetParameters setOrganizationDetails(OrganizationDetails /** * Get the attributes property: Attributes of the issuer object. - * + * * @return the attributes value. */ + @Generated public IssuerAttributes getAttributes() { return this.attributes; } /** * Set the attributes property: Attributes of the issuer object. - * + * * @param attributes the attributes value to set. * @return the CertificateIssuerSetParameters object itself. */ + @Generated public CertificateIssuerSetParameters setAttributes(IssuerAttributes attributes) { this.attributes = attributes; return this; @@ -125,6 +130,7 @@ public CertificateIssuerSetParameters setAttributes(IssuerAttributes attributes) /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -137,35 +143,40 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of CertificateIssuerSetParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of CertificateIssuerSetParameters 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 CertificateIssuerSetParameters. */ + @Generated public static CertificateIssuerSetParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - CertificateIssuerSetParameters deserializedCertificateIssuerSetParameters - = new CertificateIssuerSetParameters(); + String provider = null; + IssuerCredentials credentials = null; + OrganizationDetails organizationDetails = null; + IssuerAttributes attributes = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("provider".equals(fieldName)) { - deserializedCertificateIssuerSetParameters.provider = reader.getString(); + provider = reader.getString(); } else if ("credentials".equals(fieldName)) { - deserializedCertificateIssuerSetParameters.credentials = IssuerCredentials.fromJson(reader); + credentials = IssuerCredentials.fromJson(reader); } else if ("org_details".equals(fieldName)) { - deserializedCertificateIssuerSetParameters.organizationDetails - = OrganizationDetails.fromJson(reader); + organizationDetails = OrganizationDetails.fromJson(reader); } else if ("attributes".equals(fieldName)) { - deserializedCertificateIssuerSetParameters.attributes = IssuerAttributes.fromJson(reader); + attributes = IssuerAttributes.fromJson(reader); } else { reader.skipChildren(); } } - + CertificateIssuerSetParameters deserializedCertificateIssuerSetParameters + = new CertificateIssuerSetParameters(provider); + deserializedCertificateIssuerSetParameters.credentials = credentials; + deserializedCertificateIssuerSetParameters.organizationDetails = organizationDetails; + deserializedCertificateIssuerSetParameters.attributes = attributes; return deserializedCertificateIssuerSetParameters; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateIssuerUpdateParameters.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateIssuerUpdateParameters.java index 4109a4a35ce1..413e8bce850a 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateIssuerUpdateParameters.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateIssuerUpdateParameters.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -16,47 +16,55 @@ */ @Fluent public final class CertificateIssuerUpdateParameters implements JsonSerializable { + /* * The issuer provider. */ + @Generated private String provider; /* * The credentials to be used for the issuer. */ + @Generated private IssuerCredentials credentials; /* * Details of the organization as provided to the issuer. */ + @Generated private OrganizationDetails organizationDetails; /* * Attributes of the issuer object. */ + @Generated private IssuerAttributes attributes; /** * Creates an instance of CertificateIssuerUpdateParameters class. */ + @Generated public CertificateIssuerUpdateParameters() { } /** * Get the provider property: The issuer provider. - * + * * @return the provider value. */ + @Generated public String getProvider() { return this.provider; } /** * Set the provider property: The issuer provider. - * + * * @param provider the provider value to set. * @return the CertificateIssuerUpdateParameters object itself. */ + @Generated public CertificateIssuerUpdateParameters setProvider(String provider) { this.provider = provider; return this; @@ -64,19 +72,21 @@ public CertificateIssuerUpdateParameters setProvider(String provider) { /** * Get the credentials property: The credentials to be used for the issuer. - * + * * @return the credentials value. */ + @Generated public IssuerCredentials getCredentials() { return this.credentials; } /** * Set the credentials property: The credentials to be used for the issuer. - * + * * @param credentials the credentials value to set. * @return the CertificateIssuerUpdateParameters object itself. */ + @Generated public CertificateIssuerUpdateParameters setCredentials(IssuerCredentials credentials) { this.credentials = credentials; return this; @@ -84,19 +94,21 @@ public CertificateIssuerUpdateParameters setCredentials(IssuerCredentials creden /** * Get the organizationDetails property: Details of the organization as provided to the issuer. - * + * * @return the organizationDetails value. */ + @Generated public OrganizationDetails getOrganizationDetails() { return this.organizationDetails; } /** * Set the organizationDetails property: Details of the organization as provided to the issuer. - * + * * @param organizationDetails the organizationDetails value to set. * @return the CertificateIssuerUpdateParameters object itself. */ + @Generated public CertificateIssuerUpdateParameters setOrganizationDetails(OrganizationDetails organizationDetails) { this.organizationDetails = organizationDetails; return this; @@ -104,19 +116,21 @@ public CertificateIssuerUpdateParameters setOrganizationDetails(OrganizationDeta /** * Get the attributes property: Attributes of the issuer object. - * + * * @return the attributes value. */ + @Generated public IssuerAttributes getAttributes() { return this.attributes; } /** * Set the attributes property: Attributes of the issuer object. - * + * * @param attributes the attributes value to set. * @return the CertificateIssuerUpdateParameters object itself. */ + @Generated public CertificateIssuerUpdateParameters setAttributes(IssuerAttributes attributes) { this.attributes = attributes; return this; @@ -125,6 +139,7 @@ public CertificateIssuerUpdateParameters setAttributes(IssuerAttributes attribut /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -137,12 +152,13 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of CertificateIssuerUpdateParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of CertificateIssuerUpdateParameters 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 CertificateIssuerUpdateParameters. */ + @Generated public static CertificateIssuerUpdateParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { CertificateIssuerUpdateParameters deserializedCertificateIssuerUpdateParameters @@ -150,7 +166,6 @@ public static CertificateIssuerUpdateParameters fromJson(JsonReader jsonReader) while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("provider".equals(fieldName)) { deserializedCertificateIssuerUpdateParameters.provider = reader.getString(); } else if ("credentials".equals(fieldName)) { @@ -164,7 +179,6 @@ public static CertificateIssuerUpdateParameters fromJson(JsonReader jsonReader) reader.skipChildren(); } } - return deserializedCertificateIssuerUpdateParameters; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateItem.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateItem.java index c10dd8809e71..53c7a9ca81fd 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateItem.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateItem.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; import com.azure.core.util.Base64Url; -import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -18,32 +17,38 @@ /** * The certificate item containing certificate metadata. */ -@Fluent -public class CertificateItem implements JsonSerializable { +@Immutable +public final class CertificateItem implements JsonSerializable { + /* * Certificate identifier. */ + @Generated private String id; /* * The certificate management attributes. */ + @Generated private CertificateAttributes attributes; /* * Application specific metadata in the form of key-value pairs. */ + @Generated private Map tags; /* * Thumbprint of the certificate. */ + @Generated private Base64Url x509Thumbprint; /** * Creates an instance of CertificateItem class. */ - public CertificateItem() { + @Generated + private CertificateItem() { } /** @@ -51,66 +56,37 @@ public CertificateItem() { * * @return the id value. */ + @Generated public String getId() { return this.id; } - /** - * Set the id property: Certificate identifier. - * - * @param id the id value to set. - * @return the CertificateItem object itself. - */ - public CertificateItem setId(String id) { - this.id = id; - return this; - } - /** * Get the attributes property: The certificate management attributes. * * @return the attributes value. */ + @Generated public CertificateAttributes getAttributes() { return this.attributes; } - /** - * Set the attributes property: The certificate management attributes. - * - * @param attributes the attributes value to set. - * @return the CertificateItem object itself. - */ - public CertificateItem setAttributes(CertificateAttributes attributes) { - this.attributes = attributes; - return this; - } - /** * Get the tags property: Application specific metadata in the form of key-value pairs. * * @return the tags value. */ + @Generated public Map getTags() { return this.tags; } - /** - * Set the tags property: Application specific metadata in the form of key-value pairs. - * - * @param tags the tags value to set. - * @return the CertificateItem object itself. - */ - public CertificateItem setTags(Map tags) { - this.tags = tags; - return this; - } - /** * Get the x509Thumbprint property: Thumbprint of the certificate. * * @return the x509Thumbprint value. */ + @Generated public byte[] getX509Thumbprint() { if (this.x509Thumbprint == null) { return null; @@ -118,30 +94,16 @@ public byte[] getX509Thumbprint() { return this.x509Thumbprint.decodedBytes(); } - /** - * Set the x509Thumbprint property: Thumbprint of the certificate. - * - * @param x509Thumbprint the x509Thumbprint value to set. - * @return the CertificateItem object itself. - */ - public CertificateItem setX509Thumbprint(byte[] x509Thumbprint) { - if (x509Thumbprint == null) { - this.x509Thumbprint = null; - } else { - this.x509Thumbprint = Base64Url.encode(CoreUtils.clone(x509Thumbprint)); - } - return this; - } - /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("id", this.id); jsonWriter.writeJsonField("attributes", this.attributes); - jsonWriter.writeMapField("tags", this.tags, JsonWriter::writeString); + jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); jsonWriter.writeStringField("x5t", Objects.toString(this.x509Thumbprint, null)); return jsonWriter.writeEndObject(); } @@ -154,13 +116,13 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * pointing to JSON null. * @throws IOException If an error occurs while reading the CertificateItem. */ + @Generated public static CertificateItem fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { CertificateItem deserializedCertificateItem = new CertificateItem(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("id".equals(fieldName)) { deserializedCertificateItem.id = reader.getString(); } else if ("attributes".equals(fieldName)) { @@ -175,7 +137,6 @@ public static CertificateItem fromJson(JsonReader jsonReader) throws IOException reader.skipChildren(); } } - return deserializedCertificateItem; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateListResult.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateListResult.java index f5ac96a82b6b..305532ee2a7a 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateListResult.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateListResult.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -17,38 +17,44 @@ */ @Immutable public final class CertificateListResult implements JsonSerializable { + /* * A response message containing a list of certificates in the key vault along with a link to the next page of * certificates. */ + @Generated private List value; /* * The URL to get the next set of certificates. */ + @Generated private String nextLink; /** * Creates an instance of CertificateListResult class. */ - public CertificateListResult() { + @Generated + private CertificateListResult() { } /** * Get the value property: A response message containing a list of certificates in the key vault along with a link * to the next page of certificates. - * + * * @return the value value. */ + @Generated public List getValue() { return this.value; } /** * Get the nextLink property: The URL to get the next set of certificates. - * + * * @return the nextLink value. */ + @Generated public String getNextLink() { return this.nextLink; } @@ -56,27 +62,29 @@ public String getNextLink() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); return jsonWriter.writeEndObject(); } /** * Reads an instance of CertificateListResult from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of CertificateListResult 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 CertificateListResult. */ + @Generated public static CertificateListResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { CertificateListResult deserializedCertificateListResult = new CertificateListResult(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("value".equals(fieldName)) { List value = reader.readArray(reader1 -> CertificateItem.fromJson(reader1)); deserializedCertificateListResult.value = value; @@ -86,7 +94,6 @@ public static CertificateListResult fromJson(JsonReader jsonReader) throws IOExc reader.skipChildren(); } } - return deserializedCertificateListResult; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateMergeParameters.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateMergeParameters.java index c5aa619ba09a..33de6ce0378d 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateMergeParameters.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateMergeParameters.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -18,62 +18,62 @@ */ @Fluent public final class CertificateMergeParameters implements JsonSerializable { + /* * The certificate or the certificate chain to merge. */ - private List x509Certificates; + @Generated + private final List x509Certificates; /* * The attributes of the certificate (optional). */ + @Generated private CertificateAttributes certificateAttributes; /* * Application specific metadata in the form of key-value pairs. */ + @Generated private Map tags; /** * Creates an instance of CertificateMergeParameters class. + * + * @param x509Certificates the x509Certificates value to set. */ - public CertificateMergeParameters() { + @Generated + public CertificateMergeParameters(List x509Certificates) { + this.x509Certificates = x509Certificates; } /** * Get the x509Certificates property: The certificate or the certificate chain to merge. - * + * * @return the x509Certificates value. */ + @Generated public List getX509Certificates() { return this.x509Certificates; } - /** - * Set the x509Certificates property: The certificate or the certificate chain to merge. - * - * @param x509Certificates the x509Certificates value to set. - * @return the CertificateMergeParameters object itself. - */ - public CertificateMergeParameters setX509Certificates(List x509Certificates) { - this.x509Certificates = x509Certificates; - return this; - } - /** * Get the certificateAttributes property: The attributes of the certificate (optional). - * + * * @return the certificateAttributes value. */ + @Generated public CertificateAttributes getCertificateAttributes() { return this.certificateAttributes; } /** * Set the certificateAttributes property: The attributes of the certificate (optional). - * + * * @param certificateAttributes the certificateAttributes value to set. * @return the CertificateMergeParameters object itself. */ + @Generated public CertificateMergeParameters setCertificateAttributes(CertificateAttributes certificateAttributes) { this.certificateAttributes = certificateAttributes; return this; @@ -81,19 +81,21 @@ public CertificateMergeParameters setCertificateAttributes(CertificateAttributes /** * Get the tags property: Application specific metadata in the form of key-value pairs. - * + * * @return the tags value. */ + @Generated public Map getTags() { return this.tags; } /** * Set the tags property: Application specific metadata in the form of key-value pairs. - * + * * @param tags the tags value to set. * @return the CertificateMergeParameters object itself. */ + @Generated public CertificateMergeParameters setTags(Map tags) { this.tags = tags; return this; @@ -102,6 +104,7 @@ public CertificateMergeParameters setTags(Map tags) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -113,34 +116,36 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of CertificateMergeParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of CertificateMergeParameters 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 CertificateMergeParameters. */ + @Generated public static CertificateMergeParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - CertificateMergeParameters deserializedCertificateMergeParameters = new CertificateMergeParameters(); + List x509Certificates = null; + CertificateAttributes certificateAttributes = null; + Map tags = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("x5c".equals(fieldName)) { - List x509Certificates = reader.readArray(reader1 -> reader1.getBinary()); - deserializedCertificateMergeParameters.x509Certificates = x509Certificates; + x509Certificates = reader.readArray(reader1 -> reader1.getBinary()); } else if ("attributes".equals(fieldName)) { - deserializedCertificateMergeParameters.certificateAttributes - = CertificateAttributes.fromJson(reader); + certificateAttributes = CertificateAttributes.fromJson(reader); } else if ("tags".equals(fieldName)) { - Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedCertificateMergeParameters.tags = tags; + tags = reader.readMap(reader1 -> reader1.getString()); } else { reader.skipChildren(); } } - + CertificateMergeParameters deserializedCertificateMergeParameters + = new CertificateMergeParameters(x509Certificates); + deserializedCertificateMergeParameters.certificateAttributes = certificateAttributes; + deserializedCertificateMergeParameters.tags = tags; return deserializedCertificateMergeParameters; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateOperation.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateOperation.java index eb1a7d147d5a..0d399afae340 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateOperation.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateOperation.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -18,229 +18,162 @@ */ @Fluent public final class CertificateOperation implements JsonSerializable { + /* * The certificate id. */ + @Generated private String id; /* * Parameters for the issuer of the X509 component of a certificate. */ + @Generated private IssuerParameters issuerParameters; /* * The certificate signing request (CSR) that is being used in the certificate operation. */ + @Generated private byte[] csr; /* * Indicates if cancellation was requested on the certificate operation. */ + @Generated private Boolean cancellationRequested; /* * Status of the certificate operation. */ + @Generated private String status; /* * The status details of the certificate operation. */ + @Generated private String statusDetails; /* * Error encountered, if any, during the certificate operation. */ + @Generated private CertificateOperationError error; /* * Location which contains the result of the certificate operation. */ + @Generated private String target; /* * Identifier for the certificate operation. */ + @Generated private String requestId; /** * Creates an instance of CertificateOperation class. */ + @Generated public CertificateOperation() { } /** * Get the id property: The certificate id. - * + * * @return the id value. */ + @Generated public String getId() { return this.id; } /** * Get the issuerParameters property: Parameters for the issuer of the X509 component of a certificate. - * + * * @return the issuerParameters value. */ + @Generated public IssuerParameters getIssuerParameters() { return this.issuerParameters; } - /** - * Set the issuerParameters property: Parameters for the issuer of the X509 component of a certificate. - * - * @param issuerParameters the issuerParameters value to set. - * @return the CertificateOperation object itself. - */ - public CertificateOperation setIssuerParameters(IssuerParameters issuerParameters) { - this.issuerParameters = issuerParameters; - return this; - } - /** * Get the csr property: The certificate signing request (CSR) that is being used in the certificate operation. - * + * * @return the csr value. */ + @Generated public byte[] getCsr() { return CoreUtils.clone(this.csr); } - /** - * Set the csr property: The certificate signing request (CSR) that is being used in the certificate operation. - * - * @param csr the csr value to set. - * @return the CertificateOperation object itself. - */ - public CertificateOperation setCsr(byte[] csr) { - this.csr = CoreUtils.clone(csr); - return this; - } - /** * Get the cancellationRequested property: Indicates if cancellation was requested on the certificate operation. - * + * * @return the cancellationRequested value. */ + @Generated public Boolean isCancellationRequested() { return this.cancellationRequested; } - /** - * Set the cancellationRequested property: Indicates if cancellation was requested on the certificate operation. - * - * @param cancellationRequested the cancellationRequested value to set. - * @return the CertificateOperation object itself. - */ - public CertificateOperation setCancellationRequested(Boolean cancellationRequested) { - this.cancellationRequested = cancellationRequested; - return this; - } - /** * Get the status property: Status of the certificate operation. - * + * * @return the status value. */ + @Generated public String getStatus() { return this.status; } - /** - * Set the status property: Status of the certificate operation. - * - * @param status the status value to set. - * @return the CertificateOperation object itself. - */ - public CertificateOperation setStatus(String status) { - this.status = status; - return this; - } - /** * Get the statusDetails property: The status details of the certificate operation. - * + * * @return the statusDetails value. */ + @Generated public String getStatusDetails() { return this.statusDetails; } - /** - * Set the statusDetails property: The status details of the certificate operation. - * - * @param statusDetails the statusDetails value to set. - * @return the CertificateOperation object itself. - */ - public CertificateOperation setStatusDetails(String statusDetails) { - this.statusDetails = statusDetails; - return this; - } - /** * Get the error property: Error encountered, if any, during the certificate operation. - * + * * @return the error value. */ + @Generated public CertificateOperationError getError() { return this.error; } - /** - * Set the error property: Error encountered, if any, during the certificate operation. - * - * @param error the error value to set. - * @return the CertificateOperation object itself. - */ - public CertificateOperation setError(CertificateOperationError error) { - this.error = error; - return this; - } - /** * Get the target property: Location which contains the result of the certificate operation. - * + * * @return the target value. */ + @Generated public String getTarget() { return this.target; } - /** - * Set the target property: Location which contains the result of the certificate operation. - * - * @param target the target value to set. - * @return the CertificateOperation object itself. - */ - public CertificateOperation setTarget(String target) { - this.target = target; - return this; - } - /** * Get the requestId property: Identifier for the certificate operation. - * + * * @return the requestId value. */ + @Generated public String getRequestId() { return this.requestId; } - /** - * Set the requestId property: Identifier for the certificate operation. - * - * @param requestId the requestId value to set. - * @return the CertificateOperation object itself. - */ - public CertificateOperation setRequestId(String requestId) { - this.requestId = requestId; - return this; - } - /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -257,19 +190,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of CertificateOperation from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of CertificateOperation 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 CertificateOperation. */ + @Generated public static CertificateOperation fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { CertificateOperation deserializedCertificateOperation = new CertificateOperation(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("id".equals(fieldName)) { deserializedCertificateOperation.id = reader.getString(); } else if ("issuer".equals(fieldName)) { @@ -292,8 +225,103 @@ public static CertificateOperation fromJson(JsonReader jsonReader) throws IOExce reader.skipChildren(); } } - return deserializedCertificateOperation; }); } + + /** + * Set the issuerParameters property: Parameters for the issuer of the X509 component of a certificate. + * + * @param issuerParameters the issuerParameters value to set. + * @return the CertificateOperation object itself. + */ + @Generated + public CertificateOperation setIssuerParameters(IssuerParameters issuerParameters) { + this.issuerParameters = issuerParameters; + return this; + } + + /** + * Set the csr property: The certificate signing request (CSR) that is being used in the certificate operation. + * + * @param csr the csr value to set. + * @return the CertificateOperation object itself. + */ + @Generated + public CertificateOperation setCsr(byte[] csr) { + this.csr = CoreUtils.clone(csr); + return this; + } + + /** + * Set the cancellationRequested property: Indicates if cancellation was requested on the certificate operation. + * + * @param cancellationRequested the cancellationRequested value to set. + * @return the CertificateOperation object itself. + */ + @Generated + public CertificateOperation setCancellationRequested(Boolean cancellationRequested) { + this.cancellationRequested = cancellationRequested; + return this; + } + + /** + * Set the status property: Status of the certificate operation. + * + * @param status the status value to set. + * @return the CertificateOperation object itself. + */ + @Generated + public CertificateOperation setStatus(String status) { + this.status = status; + return this; + } + + /** + * Set the statusDetails property: The status details of the certificate operation. + * + * @param statusDetails the statusDetails value to set. + * @return the CertificateOperation object itself. + */ + @Generated + public CertificateOperation setStatusDetails(String statusDetails) { + this.statusDetails = statusDetails; + return this; + } + + /** + * Set the target property: Location which contains the result of the certificate operation. + * + * @param target the target value to set. + * @return the CertificateOperation object itself. + */ + @Generated + public CertificateOperation setTarget(String target) { + this.target = target; + return this; + } + + /** + * Set the requestId property: Identifier for the certificate operation. + * + * @param requestId the requestId value to set. + * @return the CertificateOperation object itself. + */ + @Generated + public CertificateOperation setRequestId(String requestId) { + this.requestId = requestId; + return this; + } + + /** + * Set the error property: Error encountered, if any, during the certificate operation. + * + * @param error the error value to set. + * @return the CertificateOperation object itself. + */ + @Generated + public CertificateOperation setError(CertificateOperationError error) { + this.error = error; + return this; + } } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateOperationUpdateParameter.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateOperationUpdateParameter.java index c2aeea4bb2a6..d659e5c01a99 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateOperationUpdateParameter.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateOperationUpdateParameter.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -14,43 +14,40 @@ /** * The certificate operation update parameters. */ -@Fluent +@Immutable public final class CertificateOperationUpdateParameter implements JsonSerializable { + /* * Indicates if cancellation was requested on the certificate operation. */ - private boolean cancellationRequested; + @Generated + private final boolean cancellationRequested; /** * Creates an instance of CertificateOperationUpdateParameter class. + * + * @param cancellationRequested the cancellationRequested value to set. */ - public CertificateOperationUpdateParameter() { + @Generated + public CertificateOperationUpdateParameter(boolean cancellationRequested) { + this.cancellationRequested = cancellationRequested; } /** * Get the cancellationRequested property: Indicates if cancellation was requested on the certificate operation. - * + * * @return the cancellationRequested value. */ + @Generated public boolean isCancellationRequested() { return this.cancellationRequested; } - /** - * Set the cancellationRequested property: Indicates if cancellation was requested on the certificate operation. - * - * @param cancellationRequested the cancellationRequested value to set. - * @return the CertificateOperationUpdateParameter object itself. - */ - public CertificateOperationUpdateParameter setCancellationRequested(boolean cancellationRequested) { - this.cancellationRequested = cancellationRequested; - return this; - } - /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -60,29 +57,27 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of CertificateOperationUpdateParameter from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of CertificateOperationUpdateParameter 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 CertificateOperationUpdateParameter. */ + @Generated public static CertificateOperationUpdateParameter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - CertificateOperationUpdateParameter deserializedCertificateOperationUpdateParameter - = new CertificateOperationUpdateParameter(); + boolean cancellationRequested = false; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("cancellation_requested".equals(fieldName)) { - deserializedCertificateOperationUpdateParameter.cancellationRequested = reader.getBoolean(); + cancellationRequested = reader.getBoolean(); } else { reader.skipChildren(); } } - - return deserializedCertificateOperationUpdateParameter; + return new CertificateOperationUpdateParameter(cancellationRequested); }); } } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificatePolicy.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificatePolicy.java index 3e6670a1fee3..e16ea8f5900b 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificatePolicy.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificatePolicy.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -17,71 +17,83 @@ */ @Fluent public final class CertificatePolicy implements JsonSerializable { + /* * The certificate id. */ + @Generated private String id; /* * Properties of the key backing a certificate. */ + @Generated private KeyProperties keyProperties; /* * Properties of the secret backing a certificate. */ + @Generated private SecretProperties secretProperties; /* * Properties of the X509 component of a certificate. */ + @Generated private X509CertificateProperties x509CertificateProperties; /* * Actions that will be performed by Key Vault over the lifetime of a certificate. */ + @Generated private List lifetimeActions; /* * Parameters for the issuer of the X509 component of a certificate. */ + @Generated private IssuerParameters issuerParameters; /* * The certificate attributes. */ + @Generated private CertificateAttributes attributes; /** * Creates an instance of CertificatePolicy class. */ + @Generated public CertificatePolicy() { } /** * Get the id property: The certificate id. - * + * * @return the id value. */ + @Generated public String getId() { return this.id; } /** * Get the keyProperties property: Properties of the key backing a certificate. - * + * * @return the keyProperties value. */ + @Generated public KeyProperties getKeyProperties() { return this.keyProperties; } /** * Set the keyProperties property: Properties of the key backing a certificate. - * + * * @param keyProperties the keyProperties value to set. * @return the CertificatePolicy object itself. */ + @Generated public CertificatePolicy setKeyProperties(KeyProperties keyProperties) { this.keyProperties = keyProperties; return this; @@ -89,19 +101,21 @@ public CertificatePolicy setKeyProperties(KeyProperties keyProperties) { /** * Get the secretProperties property: Properties of the secret backing a certificate. - * + * * @return the secretProperties value. */ + @Generated public SecretProperties getSecretProperties() { return this.secretProperties; } /** * Set the secretProperties property: Properties of the secret backing a certificate. - * + * * @param secretProperties the secretProperties value to set. * @return the CertificatePolicy object itself. */ + @Generated public CertificatePolicy setSecretProperties(SecretProperties secretProperties) { this.secretProperties = secretProperties; return this; @@ -109,19 +123,21 @@ public CertificatePolicy setSecretProperties(SecretProperties secretProperties) /** * Get the x509CertificateProperties property: Properties of the X509 component of a certificate. - * + * * @return the x509CertificateProperties value. */ + @Generated public X509CertificateProperties getX509CertificateProperties() { return this.x509CertificateProperties; } /** * Set the x509CertificateProperties property: Properties of the X509 component of a certificate. - * + * * @param x509CertificateProperties the x509CertificateProperties value to set. * @return the CertificatePolicy object itself. */ + @Generated public CertificatePolicy setX509CertificateProperties(X509CertificateProperties x509CertificateProperties) { this.x509CertificateProperties = x509CertificateProperties; return this; @@ -129,19 +145,21 @@ public CertificatePolicy setX509CertificateProperties(X509CertificateProperties /** * Get the lifetimeActions property: Actions that will be performed by Key Vault over the lifetime of a certificate. - * + * * @return the lifetimeActions value. */ + @Generated public List getLifetimeActions() { return this.lifetimeActions; } /** * Set the lifetimeActions property: Actions that will be performed by Key Vault over the lifetime of a certificate. - * + * * @param lifetimeActions the lifetimeActions value to set. * @return the CertificatePolicy object itself. */ + @Generated public CertificatePolicy setLifetimeActions(List lifetimeActions) { this.lifetimeActions = lifetimeActions; return this; @@ -149,19 +167,21 @@ public CertificatePolicy setLifetimeActions(List lifetimeActions /** * Get the issuerParameters property: Parameters for the issuer of the X509 component of a certificate. - * + * * @return the issuerParameters value. */ + @Generated public IssuerParameters getIssuerParameters() { return this.issuerParameters; } /** * Set the issuerParameters property: Parameters for the issuer of the X509 component of a certificate. - * + * * @param issuerParameters the issuerParameters value to set. * @return the CertificatePolicy object itself. */ + @Generated public CertificatePolicy setIssuerParameters(IssuerParameters issuerParameters) { this.issuerParameters = issuerParameters; return this; @@ -169,19 +189,21 @@ public CertificatePolicy setIssuerParameters(IssuerParameters issuerParameters) /** * Get the attributes property: The certificate attributes. - * + * * @return the attributes value. */ + @Generated public CertificateAttributes getAttributes() { return this.attributes; } /** * Set the attributes property: The certificate attributes. - * + * * @param attributes the attributes value to set. * @return the CertificatePolicy object itself. */ + @Generated public CertificatePolicy setAttributes(CertificateAttributes attributes) { this.attributes = attributes; return this; @@ -190,6 +212,7 @@ public CertificatePolicy setAttributes(CertificateAttributes attributes) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -205,19 +228,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of CertificatePolicy from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of CertificatePolicy 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 CertificatePolicy. */ + @Generated public static CertificatePolicy fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { CertificatePolicy deserializedCertificatePolicy = new CertificatePolicy(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("id".equals(fieldName)) { deserializedCertificatePolicy.id = reader.getString(); } else if ("key_props".equals(fieldName)) { @@ -239,7 +262,6 @@ public static CertificatePolicy fromJson(JsonReader jsonReader) throws IOExcepti reader.skipChildren(); } } - return deserializedCertificatePolicy; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificatePolicyAction.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificatePolicyAction.java index 3a66756b5c94..f53c55b9feec 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificatePolicyAction.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificatePolicyAction.java @@ -1,18 +1,26 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; -/** The type of the action. */ +/** + * The type of the action. + */ public enum CertificatePolicyAction { - /** Enum value EmailContacts. */ + /** + * A certificate policy that will email certificate contacts. + */ EMAIL_CONTACTS("EmailContacts"), - /** Enum value AutoRenew. */ + /** + * A certificate policy that will auto-renew a certificate. + */ AUTO_RENEW("AutoRenew"); - /** The actual serialized value for a CertificatePolicyAction instance. */ + /** + * The actual serialized value for a CertificatePolicyAction instance. + */ private final String value; CertificatePolicyAction(String value) { @@ -21,7 +29,7 @@ public enum CertificatePolicyAction { /** * Parses a serialized value to a CertificatePolicyAction instance. - * + * * @param value the serialized value to parse. * @return the parsed CertificatePolicyAction object, or null if unable to parse. */ @@ -38,7 +46,9 @@ public static CertificatePolicyAction fromString(String value) { return null; } - /** {@inheritDoc} */ + /** + * {@inheritDoc} + */ @Override public String toString() { return this.value; diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateRestoreParameters.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateRestoreParameters.java index 9f85f49d7f06..343aab993eaa 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateRestoreParameters.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateRestoreParameters.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; import com.azure.core.util.Base64Url; -import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -17,24 +16,35 @@ /** * The certificate restore parameters. */ -@Fluent +@Immutable public final class CertificateRestoreParameters implements JsonSerializable { + /* * The backup blob associated with a certificate bundle. */ - private Base64Url certificateBundleBackup; + @Generated + private final Base64Url certificateBundleBackup; /** * Creates an instance of CertificateRestoreParameters class. + * + * @param certificateBundleBackup the certificateBundleBackup value to set. */ - public CertificateRestoreParameters() { + @Generated + public CertificateRestoreParameters(byte[] certificateBundleBackup) { + if (certificateBundleBackup == null) { + this.certificateBundleBackup = null; + } else { + this.certificateBundleBackup = Base64Url.encode(certificateBundleBackup); + } } /** * Get the certificateBundleBackup property: The backup blob associated with a certificate bundle. - * + * * @return the certificateBundleBackup value. */ + @Generated public byte[] getCertificateBundleBackup() { if (this.certificateBundleBackup == null) { return null; @@ -42,24 +52,10 @@ public byte[] getCertificateBundleBackup() { return this.certificateBundleBackup.decodedBytes(); } - /** - * Set the certificateBundleBackup property: The backup blob associated with a certificate bundle. - * - * @param certificateBundleBackup the certificateBundleBackup value to set. - * @return the CertificateRestoreParameters object itself. - */ - public CertificateRestoreParameters setCertificateBundleBackup(byte[] certificateBundleBackup) { - if (certificateBundleBackup == null) { - this.certificateBundleBackup = null; - } else { - this.certificateBundleBackup = Base64Url.encode(CoreUtils.clone(certificateBundleBackup)); - } - return this; - } - /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -69,29 +65,31 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of CertificateRestoreParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of CertificateRestoreParameters 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 CertificateRestoreParameters. */ + @Generated public static CertificateRestoreParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - CertificateRestoreParameters deserializedCertificateRestoreParameters = new CertificateRestoreParameters(); + byte[] certificateBundleBackup = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("value".equals(fieldName)) { - deserializedCertificateRestoreParameters.certificateBundleBackup + Base64Url certificateBundleBackupHolder = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); + if (certificateBundleBackupHolder != null) { + certificateBundleBackup = certificateBundleBackupHolder.decodedBytes(); + } } else { reader.skipChildren(); } } - - return deserializedCertificateRestoreParameters; + return new CertificateRestoreParameters(certificateBundleBackup); }); } } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateUpdateParameters.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateUpdateParameters.java index c461ed051123..be8cdb0395be 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateUpdateParameters.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateUpdateParameters.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -17,42 +17,49 @@ */ @Fluent public final class CertificateUpdateParameters implements JsonSerializable { + /* * The management policy for the certificate. */ + @Generated private CertificatePolicy certificatePolicy; /* * The attributes of the certificate (optional). */ + @Generated private CertificateAttributes certificateAttributes; /* * Application specific metadata in the form of key-value pairs. */ + @Generated private Map tags; /** * Creates an instance of CertificateUpdateParameters class. */ + @Generated public CertificateUpdateParameters() { } /** * Get the certificatePolicy property: The management policy for the certificate. - * + * * @return the certificatePolicy value. */ + @Generated public CertificatePolicy getCertificatePolicy() { return this.certificatePolicy; } /** * Set the certificatePolicy property: The management policy for the certificate. - * + * * @param certificatePolicy the certificatePolicy value to set. * @return the CertificateUpdateParameters object itself. */ + @Generated public CertificateUpdateParameters setCertificatePolicy(CertificatePolicy certificatePolicy) { this.certificatePolicy = certificatePolicy; return this; @@ -60,19 +67,21 @@ public CertificateUpdateParameters setCertificatePolicy(CertificatePolicy certif /** * Get the certificateAttributes property: The attributes of the certificate (optional). - * + * * @return the certificateAttributes value. */ + @Generated public CertificateAttributes getCertificateAttributes() { return this.certificateAttributes; } /** * Set the certificateAttributes property: The attributes of the certificate (optional). - * + * * @param certificateAttributes the certificateAttributes value to set. * @return the CertificateUpdateParameters object itself. */ + @Generated public CertificateUpdateParameters setCertificateAttributes(CertificateAttributes certificateAttributes) { this.certificateAttributes = certificateAttributes; return this; @@ -80,19 +89,21 @@ public CertificateUpdateParameters setCertificateAttributes(CertificateAttribute /** * Get the tags property: Application specific metadata in the form of key-value pairs. - * + * * @return the tags value. */ + @Generated public Map getTags() { return this.tags; } /** * Set the tags property: Application specific metadata in the form of key-value pairs. - * + * * @param tags the tags value to set. * @return the CertificateUpdateParameters object itself. */ + @Generated public CertificateUpdateParameters setTags(Map tags) { this.tags = tags; return this; @@ -101,6 +112,7 @@ public CertificateUpdateParameters setTags(Map tags) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -112,19 +124,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of CertificateUpdateParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of CertificateUpdateParameters 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 CertificateUpdateParameters. */ + @Generated public static CertificateUpdateParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { CertificateUpdateParameters deserializedCertificateUpdateParameters = new CertificateUpdateParameters(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("policy".equals(fieldName)) { deserializedCertificateUpdateParameters.certificatePolicy = CertificatePolicy.fromJson(reader); } else if ("attributes".equals(fieldName)) { @@ -137,7 +149,6 @@ public static CertificateUpdateParameters fromJson(JsonReader jsonReader) throws reader.skipChildren(); } } - return deserializedCertificateUpdateParameters; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/Contacts.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/Contacts.java index b8140faf4520..3a24fbf7bd78 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/Contacts.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/Contacts.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -18,46 +18,53 @@ */ @Fluent public final class Contacts implements JsonSerializable { + /* * Identifier for the contacts collection. */ + @Generated private String id; /* * The contact list for the vault certificates. */ + @Generated private List contactList; /** * Creates an instance of Contacts class. */ + @Generated public Contacts() { } /** * Get the id property: Identifier for the contacts collection. - * + * * @return the id value. */ + @Generated public String getId() { return this.id; } /** * Get the contactList property: The contact list for the vault certificates. - * + * * @return the contactList value. */ + @Generated public List getContactList() { return this.contactList; } /** * Set the contactList property: The contact list for the vault certificates. - * + * * @param contactList the contactList value to set. * @return the Contacts object itself. */ + @Generated public Contacts setContactList(List contactList) { this.contactList = contactList; return this; @@ -66,6 +73,7 @@ public Contacts setContactList(List contactList) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -75,19 +83,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of Contacts from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of Contacts 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 Contacts. */ + @Generated public static Contacts fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { Contacts deserializedContacts = new Contacts(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("id".equals(fieldName)) { deserializedContacts.id = reader.getString(); } else if ("contacts".equals(fieldName)) { @@ -98,7 +106,6 @@ public static Contacts fromJson(JsonReader jsonReader) throws IOException { reader.skipChildren(); } } - return deserializedContacts; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/DeletedCertificateBundle.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/DeletedCertificateBundle.java index a03211e2d06d..36fb5b044f98 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/DeletedCertificateBundle.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/DeletedCertificateBundle.java @@ -1,12 +1,14 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; import com.azure.core.util.Base64Url; +import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; @@ -19,116 +21,124 @@ * A Deleted Certificate consisting of its previous id, attributes and its tags, as well as information on when it will * be purged. */ -@Fluent -public final class DeletedCertificateBundle extends CertificateBundle { +@Immutable +public final class DeletedCertificateBundle implements JsonSerializable { + /* - * The url of the recovery object, used to identify and recover the deleted certificate. + * The certificate id. */ - private String recoveryId; + @Generated + private String id; /* - * The time when the certificate is scheduled to be purged, in UTC + * The key id. */ - private Long scheduledPurgeDate; + @Generated + private String kid; /* - * The time when the certificate was deleted, in UTC + * The secret id. */ - private Long deletedDate; + @Generated + private String sid; + + /* + * Thumbprint of the certificate. + */ + @Generated + private Base64Url x509Thumbprint; /* * The management policy. */ + @Generated private CertificatePolicy policy; /* - * Thumbprint of the certificate. + * CER contents of x509 certificate. */ - private Base64Url x509Thumbprint; + @Generated + private byte[] cer; /* - * The secret id. + * The content type of the secret. eg. 'application/x-pem-file' or 'application/x-pkcs12', */ - private String sid; + @Generated + private String contentType; /* - * The key id. + * The certificate attributes. */ - private String kid; + @Generated + private CertificateAttributes attributes; /* - * The certificate id. + * Application specific metadata in the form of key-value pairs */ - private String id; + @Generated + private Map tags; - /** - * Creates an instance of DeletedCertificateBundle class. + /* + * The url of the recovery object, used to identify and recover the deleted certificate. */ - public DeletedCertificateBundle() { - } + @Generated + private String recoveryId; - /** - * Get the recoveryId property: The url of the recovery object, used to identify and recover the deleted - * certificate. - * - * @return the recoveryId value. + /* + * The time when the certificate is scheduled to be purged, in UTC */ - public String getRecoveryId() { - return this.recoveryId; - } + @Generated + private Long scheduledPurgeDate; + + /* + * The time when the certificate was deleted, in UTC + */ + @Generated + private Long deletedDate; /** - * Set the recoveryId property: The url of the recovery object, used to identify and recover the deleted - * certificate. - * - * @param recoveryId the recoveryId value to set. - * @return the DeletedCertificateBundle object itself. + * Creates an instance of DeletedCertificateBundle class. */ - public DeletedCertificateBundle setRecoveryId(String recoveryId) { - this.recoveryId = recoveryId; - return this; + @Generated + private DeletedCertificateBundle() { } /** - * Get the scheduledPurgeDate property: The time when the certificate is scheduled to be purged, in UTC. - * - * @return the scheduledPurgeDate value. + * Get the id property: The certificate id. + * + * @return the id value. */ - public OffsetDateTime getScheduledPurgeDate() { - if (this.scheduledPurgeDate == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.scheduledPurgeDate), ZoneOffset.UTC); + @Generated + public String getId() { + return this.id; } /** - * Get the deletedDate property: The time when the certificate was deleted, in UTC. - * - * @return the deletedDate value. + * Get the kid property: The key id. + * + * @return the kid value. */ - public OffsetDateTime getDeletedDate() { - if (this.deletedDate == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.deletedDate), ZoneOffset.UTC); + @Generated + public String getKid() { + return this.kid; } /** - * Get the policy property: The management policy. - * - * @return the policy value. + * Get the sid property: The secret id. + * + * @return the sid value. */ - @Override - public CertificatePolicy getPolicy() { - return this.policy; + @Generated + public String getSid() { + return this.sid; } /** * Get the x509Thumbprint property: Thumbprint of the certificate. - * + * * @return the x509Thumbprint value. */ - @Override + @Generated public byte[] getX509Thumbprint() { if (this.x509Thumbprint == null) { return null; @@ -137,100 +147,123 @@ public byte[] getX509Thumbprint() { } /** - * Get the sid property: The secret id. - * - * @return the sid value. + * Get the policy property: The management policy. + * + * @return the policy value. */ - @Override - public String getSid() { - return this.sid; + @Generated + public CertificatePolicy getPolicy() { + return this.policy; } /** - * Get the kid property: The key id. - * - * @return the kid value. + * Get the cer property: CER contents of x509 certificate. + * + * @return the cer value. */ - @Override - public String getKid() { - return this.kid; + @Generated + public byte[] getCer() { + return CoreUtils.clone(this.cer); } /** - * Get the id property: The certificate id. - * - * @return the id value. + * Get the contentType property: The content type of the secret. eg. 'application/x-pem-file' or + * 'application/x-pkcs12',. + * + * @return the contentType value. */ - @Override - public String getId() { - return this.id; + @Generated + public String getContentType() { + return this.contentType; } /** - * {@inheritDoc} + * Get the attributes property: The certificate attributes. + * + * @return the attributes value. */ - @Override - public DeletedCertificateBundle setCer(byte[] cer) { - super.setCer(cer); - return this; + @Generated + public CertificateAttributes getAttributes() { + return this.attributes; } /** - * {@inheritDoc} + * Get the tags property: Application specific metadata in the form of key-value pairs. + * + * @return the tags value. */ - @Override - public DeletedCertificateBundle setContentType(String contentType) { - super.setContentType(contentType); - return this; + @Generated + public Map getTags() { + return this.tags; } /** - * {@inheritDoc} + * Get the recoveryId property: The url of the recovery object, used to identify and recover the deleted + * certificate. + * + * @return the recoveryId value. */ - @Override - public DeletedCertificateBundle setAttributes(CertificateAttributes attributes) { - super.setAttributes(attributes); - return this; + @Generated + public String getRecoveryId() { + return this.recoveryId; } /** - * {@inheritDoc} + * Get the scheduledPurgeDate property: The time when the certificate is scheduled to be purged, in UTC. + * + * @return the scheduledPurgeDate value. */ - @Override - public DeletedCertificateBundle setTags(Map tags) { - super.setTags(tags); - return this; + @Generated + public OffsetDateTime getScheduledPurgeDate() { + if (this.scheduledPurgeDate == null) { + return null; + } + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.scheduledPurgeDate), ZoneOffset.UTC); + } + + /** + * Get the deletedDate property: The time when the certificate was deleted, in UTC. + * + * @return the deletedDate value. + */ + @Generated + public OffsetDateTime getDeletedDate() { + if (this.deletedDate == null) { + return null; + } + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.deletedDate), ZoneOffset.UTC); } /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeBinaryField("cer", getCer()); - jsonWriter.writeStringField("contentType", getContentType()); - jsonWriter.writeJsonField("attributes", getAttributes()); - jsonWriter.writeMapField("tags", getTags(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeBinaryField("cer", this.cer); + jsonWriter.writeStringField("contentType", this.contentType); + jsonWriter.writeJsonField("attributes", this.attributes); + jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); jsonWriter.writeStringField("recoveryId", this.recoveryId); return jsonWriter.writeEndObject(); } /** * Reads an instance of DeletedCertificateBundle from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of DeletedCertificateBundle 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 DeletedCertificateBundle. */ + @Generated public static DeletedCertificateBundle fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { DeletedCertificateBundle deserializedDeletedCertificateBundle = new DeletedCertificateBundle(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("id".equals(fieldName)) { deserializedDeletedCertificateBundle.id = reader.getString(); } else if ("kid".equals(fieldName)) { @@ -243,14 +276,14 @@ public static DeletedCertificateBundle fromJson(JsonReader jsonReader) throws IO } else if ("policy".equals(fieldName)) { deserializedDeletedCertificateBundle.policy = CertificatePolicy.fromJson(reader); } else if ("cer".equals(fieldName)) { - deserializedDeletedCertificateBundle.setCer(reader.getBinary()); + deserializedDeletedCertificateBundle.cer = reader.getBinary(); } else if ("contentType".equals(fieldName)) { - deserializedDeletedCertificateBundle.setContentType(reader.getString()); + deserializedDeletedCertificateBundle.contentType = reader.getString(); } else if ("attributes".equals(fieldName)) { - deserializedDeletedCertificateBundle.setAttributes(CertificateAttributes.fromJson(reader)); + deserializedDeletedCertificateBundle.attributes = CertificateAttributes.fromJson(reader); } else if ("tags".equals(fieldName)) { Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedDeletedCertificateBundle.setTags(tags); + deserializedDeletedCertificateBundle.tags = tags; } else if ("recoveryId".equals(fieldName)) { deserializedDeletedCertificateBundle.recoveryId = reader.getString(); } else if ("scheduledPurgeDate".equals(fieldName)) { @@ -261,7 +294,6 @@ public static DeletedCertificateBundle fromJson(JsonReader jsonReader) throws IO reader.skipChildren(); } } - return deserializedDeletedCertificateBundle; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/DeletedCertificateItem.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/DeletedCertificateItem.java index 6aa9797e6620..7d8e57a38048 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/DeletedCertificateItem.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/DeletedCertificateItem.java @@ -1,67 +1,129 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; import com.azure.core.util.Base64Url; 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; import java.util.Map; +import java.util.Objects; /** * The deleted certificate item containing metadata about the deleted certificate. */ -@Fluent -public final class DeletedCertificateItem extends CertificateItem { +@Immutable +public final class DeletedCertificateItem implements JsonSerializable { + + /* + * Certificate identifier. + */ + @Generated + private String id; + + /* + * The certificate management attributes. + */ + @Generated + private CertificateAttributes attributes; + + /* + * Application specific metadata in the form of key-value pairs. + */ + @Generated + private Map tags; + + /* + * Thumbprint of the certificate. + */ + @Generated + private Base64Url x509Thumbprint; + /* * The url of the recovery object, used to identify and recover the deleted certificate. */ + @Generated private String recoveryId; /* * The time when the certificate is scheduled to be purged, in UTC */ + @Generated private Long scheduledPurgeDate; /* * The time when the certificate was deleted, in UTC */ + @Generated private Long deletedDate; /** * Creates an instance of DeletedCertificateItem class. */ - public DeletedCertificateItem() { + @Generated + private DeletedCertificateItem() { } /** - * Get the recoveryId property: The url of the recovery object, used to identify and recover the deleted - * certificate. + * Get the id property: Certificate identifier. * - * @return the recoveryId value. + * @return the id value. */ - public String getRecoveryId() { - return this.recoveryId; + @Generated + public String getId() { + return this.id; + } + + /** + * Get the attributes property: The certificate management attributes. + * + * @return the attributes value. + */ + @Generated + public CertificateAttributes getAttributes() { + return this.attributes; + } + + /** + * Get the tags property: Application specific metadata in the form of key-value pairs. + * + * @return the tags value. + */ + @Generated + public Map getTags() { + return this.tags; } /** - * Set the recoveryId property: The url of the recovery object, used to identify and recover the deleted + * Get the x509Thumbprint property: Thumbprint of the certificate. + * + * @return the x509Thumbprint value. + */ + @Generated + public byte[] getX509Thumbprint() { + if (this.x509Thumbprint == null) { + return null; + } + return this.x509Thumbprint.decodedBytes(); + } + + /** + * Get the recoveryId property: The url of the recovery object, used to identify and recover the deleted * certificate. * - * @param recoveryId the recoveryId value to set. - * @return the DeletedCertificateItem object itself. + * @return the recoveryId value. */ - public DeletedCertificateItem setRecoveryId(String recoveryId) { - this.recoveryId = recoveryId; - return this; + @Generated + public String getRecoveryId() { + return this.recoveryId; } /** @@ -69,6 +131,7 @@ public DeletedCertificateItem setRecoveryId(String recoveryId) { * * @return the scheduledPurgeDate value. */ + @Generated public OffsetDateTime getScheduledPurgeDate() { if (this.scheduledPurgeDate == null) { return null; @@ -81,6 +144,7 @@ public OffsetDateTime getScheduledPurgeDate() { * * @return the deletedDate value. */ + @Generated public OffsetDateTime getDeletedDate() { if (this.deletedDate == null) { return null; @@ -91,55 +155,15 @@ public OffsetDateTime getDeletedDate() { /** * {@inheritDoc} */ - @Override - public DeletedCertificateItem setId(String id) { - super.setId(id); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public DeletedCertificateItem setAttributes(CertificateAttributes attributes) { - super.setAttributes(attributes); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public DeletedCertificateItem setTags(Map tags) { - super.setTags(tags); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public DeletedCertificateItem setX509Thumbprint(byte[] x509Thumbprint) { - super.setX509Thumbprint(x509Thumbprint); - return this; - } - - /** - * {@inheritDoc} - */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeStringField("id", getId()); - jsonWriter.writeJsonField("attributes", getAttributes()); - jsonWriter.writeMapField("tags", getTags(), JsonWriter::writeString); - - if (getX509Thumbprint() != null) { - jsonWriter.writeStringField("x5t", Base64Url.encode(getX509Thumbprint()).toString()); - } - + jsonWriter.writeStringField("id", this.id); + jsonWriter.writeJsonField("attributes", this.attributes); + jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("x5t", Objects.toString(this.x509Thumbprint, null)); jsonWriter.writeStringField("recoveryId", this.recoveryId); - return jsonWriter.writeEndObject(); } @@ -151,26 +175,23 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * was pointing to JSON null. * @throws IOException If an error occurs while reading the DeletedCertificateItem. */ + @Generated public static DeletedCertificateItem fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { DeletedCertificateItem deserializedDeletedCertificateItem = new DeletedCertificateItem(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("id".equals(fieldName)) { - deserializedDeletedCertificateItem.setId(reader.getString()); + deserializedDeletedCertificateItem.id = reader.getString(); } else if ("attributes".equals(fieldName)) { - deserializedDeletedCertificateItem.setAttributes(CertificateAttributes.fromJson(reader)); + deserializedDeletedCertificateItem.attributes = CertificateAttributes.fromJson(reader); } else if ("tags".equals(fieldName)) { Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedDeletedCertificateItem.setTags(tags); + deserializedDeletedCertificateItem.tags = tags; } else if ("x5t".equals(fieldName)) { - Base64Url x509ThumbprintHolder + deserializedDeletedCertificateItem.x509Thumbprint = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); - if (x509ThumbprintHolder != null) { - deserializedDeletedCertificateItem.setX509Thumbprint(x509ThumbprintHolder.decodedBytes()); - } } else if ("recoveryId".equals(fieldName)) { deserializedDeletedCertificateItem.recoveryId = reader.getString(); } else if ("scheduledPurgeDate".equals(fieldName)) { @@ -181,7 +202,6 @@ public static DeletedCertificateItem fromJson(JsonReader jsonReader) throws IOEx reader.skipChildren(); } } - return deserializedDeletedCertificateItem; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/DeletedCertificateListResult.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/DeletedCertificateListResult.java index f3ba01e6a799..aa8ddaf01c4c 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/DeletedCertificateListResult.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/DeletedCertificateListResult.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -17,38 +17,44 @@ */ @Immutable public final class DeletedCertificateListResult implements JsonSerializable { + /* * A response message containing a list of deleted certificates in the vault along with a link to the next page of - * deleted certificates + * deleted certificates. */ + @Generated private List value; /* * The URL to get the next set of deleted certificates. */ + @Generated private String nextLink; /** * Creates an instance of DeletedCertificateListResult class. */ - public DeletedCertificateListResult() { + @Generated + private DeletedCertificateListResult() { } /** * Get the value property: A response message containing a list of deleted certificates in the vault along with a * link to the next page of deleted certificates. - * + * * @return the value value. */ + @Generated public List getValue() { return this.value; } /** * Get the nextLink property: The URL to get the next set of deleted certificates. - * + * * @return the nextLink value. */ + @Generated public String getNextLink() { return this.nextLink; } @@ -56,6 +62,7 @@ public String getNextLink() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -64,19 +71,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of DeletedCertificateListResult from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of DeletedCertificateListResult 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 DeletedCertificateListResult. */ + @Generated public static DeletedCertificateListResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { DeletedCertificateListResult deserializedDeletedCertificateListResult = new DeletedCertificateListResult(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("value".equals(fieldName)) { List value = reader.readArray(reader1 -> DeletedCertificateItem.fromJson(reader1)); @@ -87,7 +94,6 @@ public static DeletedCertificateListResult fromJson(JsonReader jsonReader) throw reader.skipChildren(); } } - return deserializedDeletedCertificateListResult; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/DeletionRecoveryLevel.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/DeletionRecoveryLevel.java index 788f8a757837..0f90cf600ece 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/DeletionRecoveryLevel.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/DeletionRecoveryLevel.java @@ -1,23 +1,25 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; /** - * Reflects the deletion recovery level currently in effect for certificates in the current vault. If it contains - * 'Purgeable', the certificate can be permanently deleted by a privileged user; otherwise, only the system can purge - * the certificate, at the end of the retention interval. + * Reflects the deletion recovery level currently in effect for secrets in the current vault. If it contains + * 'Purgeable', the secret can be permanently deleted by a privileged user; otherwise, only the system can purge the + * secret, at the end of the retention interval. */ public final class DeletionRecoveryLevel extends ExpandableStringEnum { + /** * Denotes a vault state in which deletion is an irreversible operation, without the possibility for recovery. This * level corresponds to no protection being available against a Delete operation; the data is irretrievably lost * upon accepting a Delete operation at the entity level or higher (vault, resource group, subscription etc.). */ + @Generated public static final DeletionRecoveryLevel PURGEABLE = fromString("Purgeable"); /** @@ -26,14 +28,16 @@ public final class DeletionRecoveryLevel extends ExpandableStringEnum values() { return values(DeletionRecoveryLevel.class); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/IssuerAttributes.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/IssuerAttributes.java index baeff12b4efc..aacbd1f15ee5 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/IssuerAttributes.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/IssuerAttributes.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -19,42 +19,49 @@ */ @Fluent public final class IssuerAttributes implements JsonSerializable { + /* * Determines whether the issuer is enabled. */ + @Generated private Boolean enabled; /* * Creation time in UTC. */ + @Generated private Long created; /* * Last updated time in UTC. */ + @Generated private Long updated; /** * Creates an instance of IssuerAttributes class. */ + @Generated public IssuerAttributes() { } /** * Get the enabled property: Determines whether the issuer is enabled. - * + * * @return the enabled value. */ + @Generated public Boolean isEnabled() { return this.enabled; } /** * Set the enabled property: Determines whether the issuer is enabled. - * + * * @param enabled the enabled value to set. * @return the IssuerAttributes object itself. */ + @Generated public IssuerAttributes setEnabled(Boolean enabled) { this.enabled = enabled; return this; @@ -62,9 +69,10 @@ public IssuerAttributes setEnabled(Boolean enabled) { /** * Get the created property: Creation time in UTC. - * + * * @return the created value. */ + @Generated public OffsetDateTime getCreated() { if (this.created == null) { return null; @@ -74,9 +82,10 @@ public OffsetDateTime getCreated() { /** * Get the updated property: Last updated time in UTC. - * + * * @return the updated value. */ + @Generated public OffsetDateTime getUpdated() { if (this.updated == null) { return null; @@ -87,6 +96,7 @@ public OffsetDateTime getUpdated() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -96,19 +106,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of IssuerAttributes from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of IssuerAttributes 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 IssuerAttributes. */ + @Generated public static IssuerAttributes fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { IssuerAttributes deserializedIssuerAttributes = new IssuerAttributes(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("enabled".equals(fieldName)) { deserializedIssuerAttributes.enabled = reader.getNullable(JsonReader::getBoolean); } else if ("created".equals(fieldName)) { @@ -119,7 +129,6 @@ public static IssuerAttributes fromJson(JsonReader jsonReader) throws IOExceptio reader.skipChildren(); } } - return deserializedIssuerAttributes; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/IssuerBundle.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/IssuerBundle.java index 395bbce737d3..c490541f439b 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/IssuerBundle.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/IssuerBundle.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -16,129 +16,98 @@ */ @Fluent public final class IssuerBundle implements JsonSerializable { + /* * Identifier for the issuer object. */ + @Generated private String id; /* * The issuer provider. */ + @Generated private String provider; /* * The credentials to be used for the issuer. */ + @Generated private IssuerCredentials credentials; /* * Details of the organization as provided to the issuer. */ + @Generated private OrganizationDetails organizationDetails; /* * Attributes of the issuer object. */ + @Generated private IssuerAttributes attributes; /** * Creates an instance of IssuerBundle class. */ + @Generated public IssuerBundle() { } /** * Get the id property: Identifier for the issuer object. - * + * * @return the id value. */ + @Generated public String getId() { return this.id; } /** * Get the provider property: The issuer provider. - * + * * @return the provider value. */ + @Generated public String getProvider() { return this.provider; } - /** - * Set the provider property: The issuer provider. - * - * @param provider the provider value to set. - * @return the IssuerBundle object itself. - */ - public IssuerBundle setProvider(String provider) { - this.provider = provider; - return this; - } - /** * Get the credentials property: The credentials to be used for the issuer. - * + * * @return the credentials value. */ + @Generated public IssuerCredentials getCredentials() { return this.credentials; } - /** - * Set the credentials property: The credentials to be used for the issuer. - * - * @param credentials the credentials value to set. - * @return the IssuerBundle object itself. - */ - public IssuerBundle setCredentials(IssuerCredentials credentials) { - this.credentials = credentials; - return this; - } - /** * Get the organizationDetails property: Details of the organization as provided to the issuer. - * + * * @return the organizationDetails value. */ + @Generated public OrganizationDetails getOrganizationDetails() { return this.organizationDetails; } - /** - * Set the organizationDetails property: Details of the organization as provided to the issuer. - * - * @param organizationDetails the organizationDetails value to set. - * @return the IssuerBundle object itself. - */ - public IssuerBundle setOrganizationDetails(OrganizationDetails organizationDetails) { - this.organizationDetails = organizationDetails; - return this; - } - /** * Get the attributes property: Attributes of the issuer object. - * + * * @return the attributes value. */ + @Generated public IssuerAttributes getAttributes() { return this.attributes; } - /** - * Set the attributes property: Attributes of the issuer object. - * - * @param attributes the attributes value to set. - * @return the IssuerBundle object itself. - */ - public IssuerBundle setAttributes(IssuerAttributes attributes) { - this.attributes = attributes; - return this; - } - /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -151,19 +120,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of IssuerBundle from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of IssuerBundle 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 IssuerBundle. */ + @Generated public static IssuerBundle fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { IssuerBundle deserializedIssuerBundle = new IssuerBundle(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("id".equals(fieldName)) { deserializedIssuerBundle.id = reader.getString(); } else if ("provider".equals(fieldName)) { @@ -178,8 +147,55 @@ public static IssuerBundle fromJson(JsonReader jsonReader) throws IOException { reader.skipChildren(); } } - return deserializedIssuerBundle; }); } + + /** + * Set the provider property: The issuer provider. + * + * @param provider the provider value to set. + * @return the IssuerBundle object itself. + */ + @Generated + public IssuerBundle setProvider(String provider) { + this.provider = provider; + return this; + } + + /** + * Set the credentials property: The credentials to be used for the issuer. + * + * @param credentials the credentials value to set. + * @return the IssuerBundle object itself. + */ + @Generated + public IssuerBundle setCredentials(IssuerCredentials credentials) { + this.credentials = credentials; + return this; + } + + /** + * Set the organizationDetails property: Details of the organization as provided to the issuer. + * + * @param organizationDetails the organizationDetails value to set. + * @return the IssuerBundle object itself. + */ + @Generated + public IssuerBundle setOrganizationDetails(OrganizationDetails organizationDetails) { + this.organizationDetails = organizationDetails; + return this; + } + + /** + * Set the attributes property: Attributes of the issuer object. + * + * @param attributes the attributes value to set. + * @return the IssuerBundle object itself. + */ + @Generated + public IssuerBundle setAttributes(IssuerAttributes attributes) { + this.attributes = attributes; + return this; + } } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/IssuerCredentials.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/IssuerCredentials.java index f6904d67e66b..f765b5cf2829 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/IssuerCredentials.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/IssuerCredentials.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -16,37 +16,43 @@ */ @Fluent public final class IssuerCredentials implements JsonSerializable { + /* * The user name/account name/account id. */ + @Generated private String accountId; /* * The password/secret/account key. */ + @Generated private String password; /** * Creates an instance of IssuerCredentials class. */ + @Generated public IssuerCredentials() { } /** * Get the accountId property: The user name/account name/account id. - * + * * @return the accountId value. */ + @Generated public String getAccountId() { return this.accountId; } /** * Set the accountId property: The user name/account name/account id. - * + * * @param accountId the accountId value to set. * @return the IssuerCredentials object itself. */ + @Generated public IssuerCredentials setAccountId(String accountId) { this.accountId = accountId; return this; @@ -54,19 +60,21 @@ public IssuerCredentials setAccountId(String accountId) { /** * Get the password property: The password/secret/account key. - * + * * @return the password value. */ + @Generated public String getPassword() { return this.password; } /** * Set the password property: The password/secret/account key. - * + * * @param password the password value to set. * @return the IssuerCredentials object itself. */ + @Generated public IssuerCredentials setPassword(String password) { this.password = password; return this; @@ -75,6 +83,7 @@ public IssuerCredentials setPassword(String password) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -85,19 +94,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of IssuerCredentials from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of IssuerCredentials 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 IssuerCredentials. */ + @Generated public static IssuerCredentials fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { IssuerCredentials deserializedIssuerCredentials = new IssuerCredentials(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("account_id".equals(fieldName)) { deserializedIssuerCredentials.accountId = reader.getString(); } else if ("pwd".equals(fieldName)) { @@ -106,7 +115,6 @@ public static IssuerCredentials fromJson(JsonReader jsonReader) throws IOExcepti reader.skipChildren(); } } - return deserializedIssuerCredentials; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/IssuerParameters.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/IssuerParameters.java index 18d3de76f283..79b5bf2711c2 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/IssuerParameters.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/IssuerParameters.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -16,42 +16,49 @@ */ @Fluent public final class IssuerParameters implements JsonSerializable { + /* * Name of the referenced issuer object or reserved names; for example, 'Self' or 'Unknown'. */ + @Generated private String name; /* * Certificate type as supported by the provider (optional); for example 'OV-SSL', 'EV-SSL' */ + @Generated private String certificateType; /* * Indicates if the certificates generated under this policy should be published to certificate transparency logs. */ + @Generated private Boolean certificateTransparency; /** * Creates an instance of IssuerParameters class. */ + @Generated public IssuerParameters() { } /** * Get the name property: Name of the referenced issuer object or reserved names; for example, 'Self' or 'Unknown'. - * + * * @return the name value. */ + @Generated public String getName() { return this.name; } /** * Set the name property: Name of the referenced issuer object or reserved names; for example, 'Self' or 'Unknown'. - * + * * @param name the name value to set. * @return the IssuerParameters object itself. */ + @Generated public IssuerParameters setName(String name) { this.name = name; return this; @@ -60,9 +67,10 @@ public IssuerParameters setName(String name) { /** * Get the certificateType property: Certificate type as supported by the provider (optional); for example 'OV-SSL', * 'EV-SSL'. - * + * * @return the certificateType value. */ + @Generated public String getCertificateType() { return this.certificateType; } @@ -70,10 +78,11 @@ public String getCertificateType() { /** * Set the certificateType property: Certificate type as supported by the provider (optional); for example 'OV-SSL', * 'EV-SSL'. - * + * * @param certificateType the certificateType value to set. * @return the IssuerParameters object itself. */ + @Generated public IssuerParameters setCertificateType(String certificateType) { this.certificateType = certificateType; return this; @@ -82,9 +91,10 @@ public IssuerParameters setCertificateType(String certificateType) { /** * Get the certificateTransparency property: Indicates if the certificates generated under this policy should be * published to certificate transparency logs. - * + * * @return the certificateTransparency value. */ + @Generated public Boolean isCertificateTransparency() { return this.certificateTransparency; } @@ -92,10 +102,11 @@ public Boolean isCertificateTransparency() { /** * Set the certificateTransparency property: Indicates if the certificates generated under this policy should be * published to certificate transparency logs. - * + * * @param certificateTransparency the certificateTransparency value to set. * @return the IssuerParameters object itself. */ + @Generated public IssuerParameters setCertificateTransparency(Boolean certificateTransparency) { this.certificateTransparency = certificateTransparency; return this; @@ -104,6 +115,7 @@ public IssuerParameters setCertificateTransparency(Boolean certificateTransparen /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -115,19 +127,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of IssuerParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of IssuerParameters 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 IssuerParameters. */ + @Generated public static IssuerParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { IssuerParameters deserializedIssuerParameters = new IssuerParameters(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("name".equals(fieldName)) { deserializedIssuerParameters.name = reader.getString(); } else if ("cty".equals(fieldName)) { @@ -138,7 +150,6 @@ public static IssuerParameters fromJson(JsonReader jsonReader) throws IOExceptio reader.skipChildren(); } } - return deserializedIssuerParameters; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/KeyProperties.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/KeyProperties.java index 2c49b2a5d6af..587cc6f80039 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/KeyProperties.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/KeyProperties.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -18,44 +18,52 @@ */ @Fluent public final class KeyProperties implements JsonSerializable { + /* * Indicates if the private key can be exported. Release policy must be provided when creating the first version of * an exportable key. */ + @Generated private Boolean exportable; + /* + * The type of key pair to be used for the certificate. + */ + @Generated + private CertificateKeyType keyType; + /* * The key size in bits. For example: 2048, 3072, or 4096 for RSA. */ + @Generated private Integer keySize; /* * Indicates if the same key pair will be used on certificate renewal. */ + @Generated private Boolean reuseKey; - /* - * JsonWebKey Key Type (kty), as defined in https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - */ - private CertificateKeyType kty; - /* * Elliptic curve name. For valid values, see JsonWebKeyCurveName. */ - private CertificateKeyCurveName crv; + @Generated + private CertificateKeyCurveName curve; /** * Creates an instance of KeyProperties class. */ + @Generated public KeyProperties() { } /** * Get the exportable property: Indicates if the private key can be exported. Release policy must be provided when * creating the first version of an exportable key. - * + * * @return the exportable value. */ + @Generated public Boolean isExportable() { return this.exportable; } @@ -63,30 +71,55 @@ public Boolean isExportable() { /** * Set the exportable property: Indicates if the private key can be exported. Release policy must be provided when * creating the first version of an exportable key. - * + * * @param exportable the exportable value to set. * @return the KeyProperties object itself. */ + @Generated public KeyProperties setExportable(Boolean exportable) { this.exportable = exportable; return this; } + /** + * Get the keyType property: The type of key pair to be used for the certificate. + * + * @return the keyType value. + */ + @Generated + public CertificateKeyType getKeyType() { + return this.keyType; + } + + /** + * Set the keyType property: The type of key pair to be used for the certificate. + * + * @param keyType the keyType value to set. + * @return the KeyProperties object itself. + */ + @Generated + public KeyProperties setKeyType(CertificateKeyType keyType) { + this.keyType = keyType; + return this; + } + /** * Get the keySize property: The key size in bits. For example: 2048, 3072, or 4096 for RSA. - * + * * @return the keySize value. */ + @Generated public Integer getKeySize() { return this.keySize; } /** * Set the keySize property: The key size in bits. For example: 2048, 3072, or 4096 for RSA. - * + * * @param keySize the keySize value to set. * @return the KeyProperties object itself. */ + @Generated public KeyProperties setKeySize(Integer keySize) { this.keySize = keySize; return this; @@ -94,110 +127,92 @@ public KeyProperties setKeySize(Integer keySize) { /** * Get the reuseKey property: Indicates if the same key pair will be used on certificate renewal. - * + * * @return the reuseKey value. */ + @Generated public Boolean isReuseKey() { return this.reuseKey; } /** * Set the reuseKey property: Indicates if the same key pair will be used on certificate renewal. - * + * * @param reuseKey the reuseKey value to set. * @return the KeyProperties object itself. */ + @Generated public KeyProperties setReuseKey(Boolean reuseKey) { this.reuseKey = reuseKey; return this; } /** - * Get the kty property: JsonWebKey Key Type (kty), as defined in - * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - * - * @return the kty value. - */ - public CertificateKeyType getKty() { - return this.kty; - } - - /** - * Set the kty property: JsonWebKey Key Type (kty), as defined in - * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - * - * @param kty the kty value to set. - * @return the KeyProperties object itself. - */ - public KeyProperties setKty(CertificateKeyType kty) { - this.kty = kty; - return this; - } - - /** - * Get the crv property: Elliptic curve name. For valid values, see JsonWebKeyCurveName. - * - * @return the crv value. + * Get the curve property: Elliptic curve name. For valid values, see JsonWebKeyCurveName. + * + * @return the curve value. */ - public CertificateKeyCurveName getCrv() { - return this.crv; + @Generated + public CertificateKeyCurveName getCurve() { + return this.curve; } /** - * Set the crv property: Elliptic curve name. For valid values, see JsonWebKeyCurveName. - * - * @param crv the crv value to set. + * Set the curve property: Elliptic curve name. For valid values, see JsonWebKeyCurveName. + * + * @param curve the curve value to set. * @return the KeyProperties object itself. */ - public KeyProperties setCrv(CertificateKeyCurveName crv) { - this.crv = crv; + @Generated + public KeyProperties setCurve(CertificateKeyCurveName curve) { + this.curve = curve; return this; } /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeBooleanField("exportable", this.exportable); + jsonWriter.writeStringField("kty", this.keyType == null ? null : this.keyType.toString()); jsonWriter.writeNumberField("key_size", this.keySize); jsonWriter.writeBooleanField("reuse_key", this.reuseKey); - jsonWriter.writeStringField("kty", this.kty == null ? null : this.kty.toString()); - jsonWriter.writeStringField("crv", this.crv == null ? null : this.crv.toString()); + jsonWriter.writeStringField("crv", this.curve == null ? null : this.curve.toString()); return jsonWriter.writeEndObject(); } /** * Reads an instance of KeyProperties from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KeyProperties 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 KeyProperties. */ + @Generated public static KeyProperties fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { KeyProperties deserializedKeyProperties = new KeyProperties(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("exportable".equals(fieldName)) { deserializedKeyProperties.exportable = reader.getNullable(JsonReader::getBoolean); + } else if ("kty".equals(fieldName)) { + deserializedKeyProperties.keyType = CertificateKeyType.fromString(reader.getString()); } else if ("key_size".equals(fieldName)) { deserializedKeyProperties.keySize = reader.getNullable(JsonReader::getInt); } else if ("reuse_key".equals(fieldName)) { deserializedKeyProperties.reuseKey = reader.getNullable(JsonReader::getBoolean); - } else if ("kty".equals(fieldName)) { - deserializedKeyProperties.kty = CertificateKeyType.fromString(reader.getString()); } else if ("crv".equals(fieldName)) { - deserializedKeyProperties.crv = CertificateKeyCurveName.fromString(reader.getString()); + deserializedKeyProperties.curve = CertificateKeyCurveName.fromString(reader.getString()); } else { reader.skipChildren(); } } - return deserializedKeyProperties; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/KeyVaultError.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/KeyVaultError.java deleted file mode 100644 index cf3c57b0108b..000000000000 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/KeyVaultError.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.security.keyvault.certificates.implementation.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 com.azure.security.keyvault.certificates.models.CertificateOperationError; -import java.io.IOException; - -/** - * The key vault error exception. - */ -@Immutable -public final class KeyVaultError implements JsonSerializable { - /* - * The key vault server error. - */ - private CertificateOperationError error; - - /** - * Creates an instance of KeyVaultError class. - */ - public KeyVaultError() { - } - - /** - * Get the error property: The key vault server error. - * - * @return the error value. - */ - public CertificateOperationError getError() { - return this.error; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KeyVaultError from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KeyVaultError 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 KeyVaultError. - */ - public static KeyVaultError fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeyVaultError deserializedKeyVaultError = new KeyVaultError(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("error".equals(fieldName)) { - deserializedKeyVaultError.error = CertificateOperationError.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedKeyVaultError; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/KeyVaultErrorException.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/KeyVaultErrorException.java deleted file mode 100644 index 56278adcfef1..000000000000 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/KeyVaultErrorException.java +++ /dev/null @@ -1,42 +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.security.keyvault.certificates.implementation.models; - -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpResponse; - -/** - * Exception thrown for an invalid response with KeyVaultError information. - */ -public final class KeyVaultErrorException extends HttpResponseException { - /** - * Initializes a new instance of the KeyVaultErrorException class. - * - * @param message the exception message or the response content if a message is not available. - * @param response the HTTP response. - */ - public KeyVaultErrorException(String message, HttpResponse response) { - super(message, response); - } - - /** - * Initializes a new instance of the KeyVaultErrorException 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 KeyVaultErrorException(String message, HttpResponse response, KeyVaultError value) { - super(message, response, value); - } - - /** - * {@inheritDoc} - */ - @Override - public KeyVaultError getValue() { - return (KeyVaultError) super.getValue(); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/LifetimeAction.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/LifetimeAction.java index e4b934b07da2..ba5effd80e85 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/LifetimeAction.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/LifetimeAction.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -16,37 +16,43 @@ */ @Fluent public final class LifetimeAction implements JsonSerializable { + /* * The condition that will execute the action. */ + @Generated private Trigger trigger; /* * The action that will be executed. */ + @Generated private Action action; /** * Creates an instance of LifetimeAction class. */ + @Generated public LifetimeAction() { } /** * Get the trigger property: The condition that will execute the action. - * + * * @return the trigger value. */ + @Generated public Trigger getTrigger() { return this.trigger; } /** * Set the trigger property: The condition that will execute the action. - * + * * @param trigger the trigger value to set. * @return the LifetimeAction object itself. */ + @Generated public LifetimeAction setTrigger(Trigger trigger) { this.trigger = trigger; return this; @@ -54,19 +60,21 @@ public LifetimeAction setTrigger(Trigger trigger) { /** * Get the action property: The action that will be executed. - * + * * @return the action value. */ + @Generated public Action getAction() { return this.action; } /** * Set the action property: The action that will be executed. - * + * * @param action the action value to set. * @return the LifetimeAction object itself. */ + @Generated public LifetimeAction setAction(Action action) { this.action = action; return this; @@ -75,6 +83,7 @@ public LifetimeAction setAction(Action action) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -85,19 +94,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of LifetimeAction from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of LifetimeAction 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 LifetimeAction. */ + @Generated public static LifetimeAction fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { LifetimeAction deserializedLifetimeAction = new LifetimeAction(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("trigger".equals(fieldName)) { deserializedLifetimeAction.trigger = Trigger.fromJson(reader); } else if ("action".equals(fieldName)) { @@ -106,7 +115,6 @@ public static LifetimeAction fromJson(JsonReader jsonReader) throws IOException reader.skipChildren(); } } - return deserializedLifetimeAction; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/OrganizationDetails.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/OrganizationDetails.java index 013853e98f60..9524511e8383 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/OrganizationDetails.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/OrganizationDetails.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -18,37 +18,43 @@ */ @Fluent public final class OrganizationDetails implements JsonSerializable { + /* * Id of the organization. */ + @Generated private String id; /* * Details of the organization administrator. */ + @Generated private List adminDetails; /** * Creates an instance of OrganizationDetails class. */ + @Generated public OrganizationDetails() { } /** * Get the id property: Id of the organization. - * + * * @return the id value. */ + @Generated public String getId() { return this.id; } /** * Set the id property: Id of the organization. - * + * * @param id the id value to set. * @return the OrganizationDetails object itself. */ + @Generated public OrganizationDetails setId(String id) { this.id = id; return this; @@ -56,19 +62,21 @@ public OrganizationDetails setId(String id) { /** * Get the adminDetails property: Details of the organization administrator. - * + * * @return the adminDetails value. */ + @Generated public List getAdminDetails() { return this.adminDetails; } /** * Set the adminDetails property: Details of the organization administrator. - * + * * @param adminDetails the adminDetails value to set. * @return the OrganizationDetails object itself. */ + @Generated public OrganizationDetails setAdminDetails(List adminDetails) { this.adminDetails = adminDetails; return this; @@ -77,6 +85,7 @@ public OrganizationDetails setAdminDetails(List adminDetai /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -87,19 +96,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of OrganizationDetails from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of OrganizationDetails 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 OrganizationDetails. */ + @Generated public static OrganizationDetails fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { OrganizationDetails deserializedOrganizationDetails = new OrganizationDetails(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("id".equals(fieldName)) { deserializedOrganizationDetails.id = reader.getString(); } else if ("admin_details".equals(fieldName)) { @@ -110,7 +119,6 @@ public static OrganizationDetails fromJson(JsonReader jsonReader) throws IOExcep reader.skipChildren(); } } - return deserializedOrganizationDetails; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/PendingCertificateSigningRequestResult.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/PendingCertificateSigningRequestResult.java deleted file mode 100644 index 043e9a17e5ee..000000000000 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/PendingCertificateSigningRequestResult.java +++ /dev/null @@ -1,75 +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.security.keyvault.certificates.implementation.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 pending certificate signing request result. - */ -@Immutable -public final class PendingCertificateSigningRequestResult - implements JsonSerializable { - /* - * The pending certificate signing request as Base64 encoded string. - */ - private String value; - - /** - * Creates an instance of PendingCertificateSigningRequestResult class. - */ - public PendingCertificateSigningRequestResult() { - } - - /** - * Get the value property: The pending certificate signing request as Base64 encoded string. - * - * @return the value value. - */ - public String getValue() { - return this.value; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of PendingCertificateSigningRequestResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of PendingCertificateSigningRequestResult 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 PendingCertificateSigningRequestResult. - */ - public static PendingCertificateSigningRequestResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - PendingCertificateSigningRequestResult deserializedPendingCertificateSigningRequestResult - = new PendingCertificateSigningRequestResult(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - deserializedPendingCertificateSigningRequestResult.value = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedPendingCertificateSigningRequestResult; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/SecretProperties.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/SecretProperties.java index 018493f104b7..dbf80de20b10 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/SecretProperties.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/SecretProperties.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -16,32 +16,37 @@ */ @Fluent public final class SecretProperties implements JsonSerializable { + /* * The media type (MIME type). */ + @Generated private String contentType; /** * Creates an instance of SecretProperties class. */ + @Generated public SecretProperties() { } /** * Get the contentType property: The media type (MIME type). - * + * * @return the contentType value. */ + @Generated public String getContentType() { return this.contentType; } /** * Set the contentType property: The media type (MIME type). - * + * * @param contentType the contentType value to set. * @return the SecretProperties object itself. */ + @Generated public SecretProperties setContentType(String contentType) { this.contentType = contentType; return this; @@ -50,6 +55,7 @@ public SecretProperties setContentType(String contentType) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -59,26 +65,25 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SecretProperties from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SecretProperties 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 SecretProperties. */ + @Generated public static SecretProperties fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { SecretProperties deserializedSecretProperties = new SecretProperties(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("contentType".equals(fieldName)) { deserializedSecretProperties.contentType = reader.getString(); } else { reader.skipChildren(); } } - return deserializedSecretProperties; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/Trigger.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/Trigger.java index 5db6c3e060df..7e1a5c6b9132 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/Trigger.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/Trigger.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -16,29 +16,34 @@ */ @Fluent public final class Trigger implements JsonSerializable { + /* * Percentage of lifetime at which to trigger. Value should be between 1 and 99. */ + @Generated private Integer lifetimePercentage; /* * Days before expiry to attempt renewal. Value should be between 1 and validity_in_months multiplied by 27. If * validity_in_months is 36, then value should be between 1 and 972 (36 * 27). */ + @Generated private Integer daysBeforeExpiry; /** * Creates an instance of Trigger class. */ + @Generated public Trigger() { } /** * Get the lifetimePercentage property: Percentage of lifetime at which to trigger. Value should be between 1 and * 99. - * + * * @return the lifetimePercentage value. */ + @Generated public Integer getLifetimePercentage() { return this.lifetimePercentage; } @@ -46,10 +51,11 @@ public Integer getLifetimePercentage() { /** * Set the lifetimePercentage property: Percentage of lifetime at which to trigger. Value should be between 1 and * 99. - * + * * @param lifetimePercentage the lifetimePercentage value to set. * @return the Trigger object itself. */ + @Generated public Trigger setLifetimePercentage(Integer lifetimePercentage) { this.lifetimePercentage = lifetimePercentage; return this; @@ -59,9 +65,10 @@ public Trigger setLifetimePercentage(Integer lifetimePercentage) { * Get the daysBeforeExpiry property: Days before expiry to attempt renewal. Value should be between 1 and * validity_in_months multiplied by 27. If validity_in_months is 36, then value should be between 1 and 972 (36 * * 27). - * + * * @return the daysBeforeExpiry value. */ + @Generated public Integer getDaysBeforeExpiry() { return this.daysBeforeExpiry; } @@ -70,10 +77,11 @@ public Integer getDaysBeforeExpiry() { * Set the daysBeforeExpiry property: Days before expiry to attempt renewal. Value should be between 1 and * validity_in_months multiplied by 27. If validity_in_months is 36, then value should be between 1 and 972 (36 * * 27). - * + * * @param daysBeforeExpiry the daysBeforeExpiry value to set. * @return the Trigger object itself. */ + @Generated public Trigger setDaysBeforeExpiry(Integer daysBeforeExpiry) { this.daysBeforeExpiry = daysBeforeExpiry; return this; @@ -82,6 +90,7 @@ public Trigger setDaysBeforeExpiry(Integer daysBeforeExpiry) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -92,19 +101,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of Trigger from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of Trigger 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 Trigger. */ + @Generated public static Trigger fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { Trigger deserializedTrigger = new Trigger(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("lifetime_percentage".equals(fieldName)) { deserializedTrigger.lifetimePercentage = reader.getNullable(JsonReader::getInt); } else if ("days_before_expiry".equals(fieldName)) { @@ -113,7 +122,6 @@ public static Trigger fromJson(JsonReader jsonReader) throws IOException { reader.skipChildren(); } } - return deserializedTrigger; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/X509CertificateProperties.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/X509CertificateProperties.java index 3ffccc1c717a..e8393bc1d7f5 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/X509CertificateProperties.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/X509CertificateProperties.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -19,52 +19,61 @@ */ @Fluent public final class X509CertificateProperties implements JsonSerializable { + /* * The subject name. Should be a valid X509 distinguished Name. */ + @Generated private String subject; /* * The enhanced key usage. */ + @Generated private List ekus; /* * The subject alternative names. */ + @Generated private SubjectAlternativeNames subjectAlternativeNames; /* * Defines how the certificate's key may be used. */ + @Generated private List keyUsage; /* * The duration that the certificate is valid in months. */ + @Generated private Integer validityInMonths; /** * Creates an instance of X509CertificateProperties class. */ + @Generated public X509CertificateProperties() { } /** * Get the subject property: The subject name. Should be a valid X509 distinguished Name. - * + * * @return the subject value. */ + @Generated public String getSubject() { return this.subject; } /** * Set the subject property: The subject name. Should be a valid X509 distinguished Name. - * + * * @param subject the subject value to set. * @return the X509CertificateProperties object itself. */ + @Generated public X509CertificateProperties setSubject(String subject) { this.subject = subject; return this; @@ -72,19 +81,21 @@ public X509CertificateProperties setSubject(String subject) { /** * Get the ekus property: The enhanced key usage. - * + * * @return the ekus value. */ + @Generated public List getEkus() { return this.ekus; } /** * Set the ekus property: The enhanced key usage. - * + * * @param ekus the ekus value to set. * @return the X509CertificateProperties object itself. */ + @Generated public X509CertificateProperties setEkus(List ekus) { this.ekus = ekus; return this; @@ -92,19 +103,21 @@ public X509CertificateProperties setEkus(List ekus) { /** * Get the subjectAlternativeNames property: The subject alternative names. - * + * * @return the subjectAlternativeNames value. */ + @Generated public SubjectAlternativeNames getSubjectAlternativeNames() { return this.subjectAlternativeNames; } /** * Set the subjectAlternativeNames property: The subject alternative names. - * + * * @param subjectAlternativeNames the subjectAlternativeNames value to set. * @return the X509CertificateProperties object itself. */ + @Generated public X509CertificateProperties setSubjectAlternativeNames(SubjectAlternativeNames subjectAlternativeNames) { this.subjectAlternativeNames = subjectAlternativeNames; return this; @@ -112,19 +125,21 @@ public X509CertificateProperties setSubjectAlternativeNames(SubjectAlternativeNa /** * Get the keyUsage property: Defines how the certificate's key may be used. - * + * * @return the keyUsage value. */ + @Generated public List getKeyUsage() { return this.keyUsage; } /** * Set the keyUsage property: Defines how the certificate's key may be used. - * + * * @param keyUsage the keyUsage value to set. * @return the X509CertificateProperties object itself. */ + @Generated public X509CertificateProperties setKeyUsage(List keyUsage) { this.keyUsage = keyUsage; return this; @@ -132,19 +147,21 @@ public X509CertificateProperties setKeyUsage(List keyUsage) /** * Get the validityInMonths property: The duration that the certificate is valid in months. - * + * * @return the validityInMonths value. */ + @Generated public Integer getValidityInMonths() { return this.validityInMonths; } /** * Set the validityInMonths property: The duration that the certificate is valid in months. - * + * * @param validityInMonths the validityInMonths value to set. * @return the X509CertificateProperties object itself. */ + @Generated public X509CertificateProperties setValidityInMonths(Integer validityInMonths) { this.validityInMonths = validityInMonths; return this; @@ -153,6 +170,7 @@ public X509CertificateProperties setValidityInMonths(Integer validityInMonths) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -167,19 +185,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of X509CertificateProperties from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of X509CertificateProperties 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 X509CertificateProperties. */ + @Generated public static X509CertificateProperties fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { X509CertificateProperties deserializedX509CertificateProperties = new X509CertificateProperties(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("subject".equals(fieldName)) { deserializedX509CertificateProperties.subject = reader.getString(); } else if ("ekus".equals(fieldName)) { @@ -198,7 +216,6 @@ public static X509CertificateProperties fromJson(JsonReader jsonReader) throws I reader.skipChildren(); } } - return deserializedX509CertificateProperties; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/package-info.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/package-info.java index c26554b225b6..c69ed5d6b381 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/package-info.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/models/package-info.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. /** - * Package containing the data models for CertificateClient. - * The key vault client performs cryptographic key operations and vault operations against the Key Vault service. + * + * Package containing the data models for CertificateClient. The key vault client performs cryptographic key operations + * and vault operations against the Key Vault service. */ package com.azure.security.keyvault.certificates.implementation.models; diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/package-info.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/package-info.java index 843b387e49ad..bb5cc1df52e6 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/package-info.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/package-info.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. /** - * Package containing the implementations for CertificateClient. - * The key vault client performs cryptographic key operations and vault operations against the Key Vault service. + * + * Package containing the implementations for CertificateClient. The key vault client performs cryptographic key + * operations and vault operations against the Key Vault service. */ package com.azure.security.keyvault.certificates.implementation; diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/AdministratorContact.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/AdministratorContact.java index acdbf81bbe92..4144a7a0eb2a 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/AdministratorContact.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/AdministratorContact.java @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.models; import com.azure.core.annotation.Fluent; @@ -16,6 +15,7 @@ */ @Fluent public final class AdministratorContact implements JsonSerializable { + /* * First name. */ @@ -44,7 +44,7 @@ public AdministratorContact() { /** * Get the firstName property: First name. - * + * * @return the firstName value. */ public String getFirstName() { @@ -53,7 +53,7 @@ public String getFirstName() { /** * Set the firstName property: First name. - * + * * @param firstName the firstName value to set. * @return the AdministratorContact object itself. */ @@ -64,7 +64,7 @@ public AdministratorContact setFirstName(String firstName) { /** * Get the lastName property: Last name. - * + * * @return the lastName value. */ public String getLastName() { @@ -73,7 +73,7 @@ public String getLastName() { /** * Set the lastName property: Last name. - * + * * @param lastName the lastName value to set. * @return the AdministratorContact object itself. */ @@ -84,7 +84,7 @@ public AdministratorContact setLastName(String lastName) { /** * Get the email property: Email address. - * + * * @return the email value. */ public String getEmail() { @@ -93,7 +93,7 @@ public String getEmail() { /** * Set the email property: Email address. - * + * * @param email the email value to set. * @return the AdministratorContact object itself. */ @@ -104,7 +104,7 @@ public AdministratorContact setEmail(String email) { /** * Get the phone property: Phone number. - * + * * @return the phone value. */ public String getPhone() { @@ -113,7 +113,7 @@ public String getPhone() { /** * Set the phone property: Phone number. - * + * * @param phone the phone value to set. * @return the AdministratorContact object itself. */ @@ -137,7 +137,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of AdministratorContact from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of AdministratorContact if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. @@ -149,7 +149,6 @@ public static AdministratorContact fromJson(JsonReader jsonReader) throws IOExce while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("first_name".equals(fieldName)) { deserializedAdministratorContact.firstName = reader.getString(); } else if ("last_name".equals(fieldName)) { @@ -162,7 +161,6 @@ public static AdministratorContact fromJson(JsonReader jsonReader) throws IOExce reader.skipChildren(); } } - return deserializedAdministratorContact; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificateContact.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificateContact.java index a256a84dd06a..1a389c0db494 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificateContact.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificateContact.java @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.models; import com.azure.core.annotation.Fluent; @@ -16,6 +15,7 @@ */ @Fluent public final class CertificateContact implements JsonSerializable { + /* * Email address. */ @@ -39,7 +39,7 @@ public CertificateContact() { /** * Get the email property: Email address. - * + * * @return the email value. */ public String getEmail() { @@ -48,7 +48,7 @@ public String getEmail() { /** * Set the email property: Email address. - * + * * @param email the email value to set. * @return the CertificateContact object itself. */ @@ -59,7 +59,7 @@ public CertificateContact setEmail(String email) { /** * Get the name property: Name. - * + * * @return the name value. */ public String getName() { @@ -68,7 +68,7 @@ public String getName() { /** * Set the name property: Name. - * + * * @param name the name value to set. * @return the CertificateContact object itself. */ @@ -79,7 +79,7 @@ public CertificateContact setName(String name) { /** * Get the phone property: Phone number. - * + * * @return the phone value. */ public String getPhone() { @@ -88,7 +88,7 @@ public String getPhone() { /** * Set the phone property: Phone number. - * + * * @param phone the phone value to set. * @return the CertificateContact object itself. */ @@ -111,7 +111,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of CertificateContact from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of CertificateContact if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -123,7 +123,6 @@ public static CertificateContact fromJson(JsonReader jsonReader) throws IOExcept while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("email".equals(fieldName)) { deserializedCertificateContact.email = reader.getString(); } else if ("name".equals(fieldName)) { @@ -134,7 +133,6 @@ public static CertificateContact fromJson(JsonReader jsonReader) throws IOExcept reader.skipChildren(); } } - return deserializedCertificateContact; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificateIssuer.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificateIssuer.java index fccf699a2213..33eb0c40fb93 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificateIssuer.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificateIssuer.java @@ -28,18 +28,18 @@ public final class CertificateIssuer implements JsonSerializable getAdministratorContacts() { - return impl.getOrganizationDetails() == null ? null : impl.getOrganizationDetails().getAdminDetails(); + return issuerBundle.getOrganizationDetails() == null + ? null + : issuerBundle.getOrganizationDetails().getAdminDetails(); } /** @@ -176,11 +178,11 @@ public List getAdministratorContacts() { * @return the Issuer object itself. */ public CertificateIssuer setAdministratorContacts(List administratorContacts) { - if (impl.getOrganizationDetails() == null) { - impl.setOrganizationDetails(new OrganizationDetails()); + if (issuerBundle.getOrganizationDetails() == null) { + issuerBundle.setOrganizationDetails(new OrganizationDetails()); } - impl.getOrganizationDetails().setAdminDetails(administratorContacts); + issuerBundle.getOrganizationDetails().setAdminDetails(administratorContacts); return this; } @@ -189,7 +191,7 @@ public CertificateIssuer setAdministratorContacts(List adm * @return the enabled status */ public Boolean isEnabled() { - return impl.getAttributes() == null ? null : impl.getAttributes().isEnabled(); + return issuerBundle.getAttributes() == null ? null : issuerBundle.getAttributes().isEnabled(); } /** @@ -198,11 +200,11 @@ public Boolean isEnabled() { * @return the Issuer object itself. */ public CertificateIssuer setEnabled(Boolean enabled) { - if (impl.getAttributes() == null) { - impl.setAttributes(new IssuerAttributes()); + if (issuerBundle.getAttributes() == null) { + issuerBundle.setAttributes(new IssuerAttributes()); } - impl.getAttributes().setEnabled(enabled); + issuerBundle.getAttributes().setEnabled(enabled); return this; } @@ -211,7 +213,7 @@ public CertificateIssuer setEnabled(Boolean enabled) { * @return the created UTC time. */ public OffsetDateTime getCreatedOn() { - return impl.getAttributes() == null ? null : impl.getAttributes().getCreated(); + return issuerBundle.getAttributes() == null ? null : issuerBundle.getAttributes().getCreated(); } /** @@ -219,12 +221,12 @@ public OffsetDateTime getCreatedOn() { * @return the updated UTC time. */ public OffsetDateTime getUpdatedOn() { - return impl.getAttributes() == null ? null : impl.getAttributes().getUpdated(); + return issuerBundle.getAttributes() == null ? null : issuerBundle.getAttributes().getUpdated(); } @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return impl.toJson(jsonWriter); + return issuerBundle.toJson(jsonWriter); } /** diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificateKeyCurveName.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificateKeyCurveName.java index 023bcbb7845b..86edfd9cab09 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificateKeyCurveName.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificateKeyCurveName.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.models; import com.azure.core.util.ExpandableStringEnum; diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificateKeyType.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificateKeyType.java index 82019be3f0d1..713760059ba0 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificateKeyType.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificateKeyType.java @@ -1,16 +1,16 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.models; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; /** - * JsonWebKey Key Type (kty), as defined in https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. + * The type of key pair to be used for the certificate. */ public final class CertificateKeyType extends ExpandableStringEnum { + /** * Elliptic Curve. */ @@ -33,7 +33,7 @@ public final class CertificateKeyType extends ExpandableStringEnum values() { return values(CertificateKeyType.class); } + + /** + * Octet sequence (used to represent symmetric keys). + */ + static final CertificateKeyType OCT = fromString("oct"); + + /** + * Octet sequence with a private key which is not exportable from the HSM. + */ + static final CertificateKeyType OCT_HSM = fromString("oct-HSM"); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificateKeyUsage.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificateKeyUsage.java index 150976d3ad2d..009fb299b13c 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificateKeyUsage.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificateKeyUsage.java @@ -1,16 +1,16 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.models; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; /** - * Defines values for CertificateKeyUsage. + * Supported usages of a certificate key. */ public final class CertificateKeyUsage extends ExpandableStringEnum { + /** * Static value digitalSignature for CertificateKeyUsage. */ @@ -58,7 +58,7 @@ public final class CertificateKeyUsage extends ExpandableStringEnum values() { return values(CertificateKeyUsage.class); } + + /** + * Indicates that the certificate key can be used to sign a certificate revocation list. + */ + static final CertificateKeyUsage C_RLSIGN = fromString("cRLSign"); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificateOperationError.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificateOperationError.java index 46421d747091..81598171e99d 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificateOperationError.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificateOperationError.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.certificates.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -12,54 +12,62 @@ import java.io.IOException; /** - * The key vault server error. + * The CertificateOperationError model. */ @Immutable public final class CertificateOperationError implements JsonSerializable { + /* * The error code. */ + @Generated private String code; /* * The error message. */ + @Generated private String message; /* * The key vault server error. */ + @Generated private CertificateOperationError innerError; /** * Creates an instance of CertificateOperationError class. */ + @Generated public CertificateOperationError() { } /** * Get the code property: The error code. - * + * * @return the code value. */ + @Generated public String getCode() { return this.code; } /** * Get the message property: The error message. - * + * * @return the message value. */ + @Generated public String getMessage() { return this.message; } /** * Get the innerError property: The key vault server error. - * + * * @return the innerError value. */ + @Generated public CertificateOperationError getInnerError() { return this.innerError; } @@ -67,6 +75,7 @@ public CertificateOperationError getInnerError() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -75,19 +84,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of CertificateOperationError from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of CertificateOperationError 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 CertificateOperationError. */ + @Generated public static CertificateOperationError fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { CertificateOperationError deserializedCertificateOperationError = new CertificateOperationError(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("code".equals(fieldName)) { deserializedCertificateOperationError.code = reader.getString(); } else if ("message".equals(fieldName)) { @@ -98,7 +107,6 @@ public static CertificateOperationError fromJson(JsonReader jsonReader) throws I reader.skipChildren(); } } - return deserializedCertificateOperationError; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificatePolicy.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificatePolicy.java index c4021d98f41e..09f1abc13dde 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificatePolicy.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificatePolicy.java @@ -160,7 +160,7 @@ public CertificatePolicy setExportable(Boolean exportable) { * @return the key type value */ public CertificateKeyType getKeyType() { - return impl.getKeyProperties() == null ? null : impl.getKeyProperties().getKty(); + return impl.getKeyProperties() == null ? null : impl.getKeyProperties().getKeyType(); } /** @@ -174,7 +174,7 @@ public CertificatePolicy setKeyType(CertificateKeyType keyType) { impl.setKeyProperties(new KeyProperties()); } - impl.getKeyProperties().setKty(keyType); + impl.getKeyProperties().setKeyType(keyType); return this; } @@ -217,7 +217,7 @@ public CertificatePolicy setKeyReusable(Boolean keyReusable) { * @return the curve value */ public CertificateKeyCurveName getKeyCurveName() { - return impl.getKeyProperties() == null ? null : impl.getKeyProperties().getCrv(); + return impl.getKeyProperties() == null ? null : impl.getKeyProperties().getCurve(); } /** @@ -355,7 +355,7 @@ public CertificatePolicy setKeyCurveName(CertificateKeyCurveName keyCurveName) { impl.setKeyProperties(new KeyProperties()); } - impl.getKeyProperties().setCrv(keyCurveName); + impl.getKeyProperties().setCurve(keyCurveName); return this; } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificatePolicyAction.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificatePolicyAction.java index 6b78b9423b5e..f73b8cff7865 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificatePolicyAction.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificatePolicyAction.java @@ -5,6 +5,7 @@ package com.azure.security.keyvault.certificates.models; import com.azure.core.util.ExpandableStringEnum; + import java.util.Collection; /** @@ -23,7 +24,7 @@ public final class CertificatePolicyAction extends ExpandableStringEnum values() { diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificateProperties.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificateProperties.java index 1e18bc526668..96e1d36d54be 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificateProperties.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/CertificateProperties.java @@ -14,6 +14,8 @@ import com.azure.security.keyvault.certificates.implementation.models.CertificateAttributes; import com.azure.security.keyvault.certificates.implementation.models.CertificateBundle; import com.azure.security.keyvault.certificates.implementation.models.CertificateItem; +import com.azure.security.keyvault.certificates.implementation.models.DeletedCertificateBundle; +import com.azure.security.keyvault.certificates.implementation.models.DeletedCertificateItem; import java.io.IOException; import java.time.OffsetDateTime; @@ -30,7 +32,17 @@ public class CertificateProperties implements JsonSerializable tags, byte[] wireThumbprint, Integer recoverableDays) { + IdMetadata idMetadata = getIdMetadata(id, 1, 2, 3, LOGGER); this.id = idMetadata.getId(); this.vaultUrl = idMetadata.getVaultUrl(); @@ -129,7 +152,7 @@ public class CertificateProperties implements JsonSerializable { + /* * Email addresses. */ @@ -40,7 +40,7 @@ public SubjectAlternativeNames() { /** * Get the emails property: Email addresses. - * + * * @return the emails value. */ public List getEmails() { @@ -49,7 +49,7 @@ public List getEmails() { /** * Set the emails property: Email addresses. - * + * * @param emails the emails value to set. * @return the SubjectAlternativeNames object itself. */ @@ -60,7 +60,7 @@ public SubjectAlternativeNames setEmails(List emails) { /** * Get the dnsNames property: Domain names. - * + * * @return the dnsNames value. */ public List getDnsNames() { @@ -69,7 +69,7 @@ public List getDnsNames() { /** * Set the dnsNames property: Domain names. - * + * * @param dnsNames the dnsNames value to set. * @return the SubjectAlternativeNames object itself. */ @@ -80,7 +80,7 @@ public SubjectAlternativeNames setDnsNames(List dnsNames) { /** * Get the userPrincipalNames property: User principal names. - * + * * @return the userPrincipalNames value. */ public List getUserPrincipalNames() { @@ -89,7 +89,7 @@ public List getUserPrincipalNames() { /** * Set the userPrincipalNames property: User principal names. - * + * * @param userPrincipalNames the userPrincipalNames value to set. * @return the SubjectAlternativeNames object itself. */ @@ -112,7 +112,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SubjectAlternativeNames from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SubjectAlternativeNames if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. @@ -124,7 +124,6 @@ public static SubjectAlternativeNames fromJson(JsonReader jsonReader) throws IOE while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("emails".equals(fieldName)) { List emails = reader.readArray(reader1 -> reader1.getString()); deserializedSubjectAlternativeNames.emails = emails; @@ -138,7 +137,6 @@ public static SubjectAlternativeNames fromJson(JsonReader jsonReader) throws IOE reader.skipChildren(); } } - return deserializedSubjectAlternativeNames; }); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/package-info.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/package-info.java index a863a78a1c37..bff5a479a45b 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/package-info.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/models/package-info.java @@ -1,9 +1,8 @@ // 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 CertificateClient. - * The key vault client performs cryptographic key operations and vault operations against the Key Vault service. + * + * Package containing the data models for CertificateClient. The key vault client performs cryptographic key operations + * and vault operations against the Key Vault service. */ package com.azure.security.keyvault.certificates.models; diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/package-info.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/package-info.java index c562087d17d8..f281f1001d17 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/package-info.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/package-info.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. - /** + * *

          Azure Key Vault is a cloud-based service * provided by Microsoft Azure that allows users to securely store and manage cryptographic certificates used for encrypting * and decrypting data. It is a part of Azure Key Vault, which is a cloud-based service for managing cryptographic certificates, diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/module-info.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/module-info.java index edacc9974f28..04d4b5167bb6 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/module-info.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/module-info.java @@ -1,5 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. module com.azure.security.keyvault.certificates { requires transitive com.azure.core; @@ -8,8 +9,8 @@ exports com.azure.security.keyvault.certificates; exports com.azure.security.keyvault.certificates.models; - opens com.azure.security.keyvault.certificates to com.azure.core; - opens com.azure.security.keyvault.certificates.implementation to com.azure.core; opens com.azure.security.keyvault.certificates.implementation.models to com.azure.core; opens com.azure.security.keyvault.certificates.models to com.azure.core; + opens com.azure.security.keyvault.certificates to com.azure.core; + opens com.azure.security.keyvault.certificates.implementation to com.azure.core; } diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/resources/azure-key-vault-secrets.properties b/sdk/keyvault/azure-security-keyvault-certificates/src/main/resources/azure-security-keyvault-certificates.properties similarity index 100% rename from sdk/keyvault/azure-security-keyvault-secrets/src/main/resources/azure-key-vault-secrets.properties rename to sdk/keyvault/azure-security-keyvault-certificates/src/main/resources/azure-security-keyvault-certificates.properties diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/samples/README.md b/sdk/keyvault/azure-security-keyvault-certificates/src/samples/README.md index f1f04c7c55aa..d0cf013e0c3f 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/samples/README.md +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/samples/README.md @@ -85,4 +85,4 @@ This project welcomes contributions and suggestions. Find [more contributing][SD [sample_ManageDeleted]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-certificates/src/samples/java/com/azure/security/keyvault/certificates/ManagingDeletedCertificates.java [sample_ManageDeletedAsync]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-certificates/src/samples/java/com/azure/security/keyvault/certificates/ManagingDeletedCertificatesAsync.java -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fkeyvault%2Fazure-security-keyvault-certificates%2Fsrc%2Fsamples%2FREADME.png) + diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certificates/CertificateAsyncClientTest.java b/sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certificates/CertificateAsyncClientTest.java index 73c3073c8960..914cb606829b 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certificates/CertificateAsyncClientTest.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certificates/CertificateAsyncClientTest.java @@ -3,16 +3,17 @@ package com.azure.security.keyvault.certificates; +import com.azure.core.exception.HttpResponseException; import com.azure.core.exception.ResourceModifiedException; import com.azure.core.exception.ResourceNotFoundException; import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedFlux; import com.azure.core.test.http.AssertingHttpClientBuilder; import com.azure.core.util.CoreUtils; import com.azure.core.util.polling.AsyncPollResponse; import com.azure.core.util.polling.LongRunningOperationStatus; import com.azure.core.util.polling.PollerFlux; import com.azure.security.keyvault.certificates.implementation.KeyVaultCredentialPolicy; -import com.azure.security.keyvault.certificates.implementation.models.KeyVaultErrorException; import com.azure.security.keyvault.certificates.models.CertificateContact; import com.azure.security.keyvault.certificates.models.CertificateContentType; import com.azure.security.keyvault.certificates.models.CertificateIssuer; @@ -147,7 +148,7 @@ public void createCertificateEmptyName(HttpClient httpClient, CertificateService StepVerifier.create(certificateAsyncClient.beginCreateCertificate("", CertificatePolicy.getDefault())) .verifyErrorSatisfies( - e -> assertResponseException(e, KeyVaultErrorException.class, HttpURLConnection.HTTP_BAD_METHOD)); + e -> assertResponseException(e, HttpResponseException.class, HttpURLConnection.HTTP_BAD_METHOD)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @@ -647,7 +648,7 @@ public void createIssuerEmptyName(HttpClient httpClient, CertificateServiceVersi StepVerifier.create(certificateAsyncClient.createIssuer(new CertificateIssuer("", ""))) .verifyErrorSatisfies( - e -> assertResponseException(e, KeyVaultErrorException.class, HttpURLConnection.HTTP_BAD_METHOD)); + e -> assertResponseException(e, HttpResponseException.class, HttpURLConnection.HTTP_BAD_METHOD)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @@ -657,7 +658,7 @@ public void createIssuerNullProvider(HttpClient httpClient, CertificateServiceVe StepVerifier.create(certificateAsyncClient.createIssuer(new CertificateIssuer("", null))) .verifyErrorSatisfies( - e -> assertResponseException(e, KeyVaultErrorException.class, HttpURLConnection.HTTP_BAD_METHOD)); + e -> assertResponseException(e, HttpResponseException.class, HttpURLConnection.HTTP_BAD_METHOD)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @@ -882,9 +883,14 @@ public void listDeletedCertificates(HttpClient httpClient, CertificateServiceVer sleepIfRunningAgainstService(30000); - StepVerifier.create(certificateAsyncClient.listDeletedCertificates() - .doOnNext(deletedCertificate -> certificatesToDelete.remove(deletedCertificate.getName())) - .last()).assertNext(ignored -> assertEquals(0, certificatesToDelete.size())).verifyComplete(); + PagedFlux pagedFlux = certificateAsyncClient.listDeletedCertificates(); + + StepVerifier + .create( + pagedFlux.doOnNext(deletedCertificate -> certificatesToDelete.remove(deletedCertificate.getName())) + .last()) + .assertNext(ignored -> assertEquals(0, certificatesToDelete.size())) + .verifyComplete(); }); } @@ -985,7 +991,7 @@ public void mergeCertificateNotFound(HttpClient httpClient, CertificateServiceVe .create(certificateAsyncClient.mergeCertificate(new MergeCertificateOptions( testResourceNamer.randomName("testCert", 20), Collections.singletonList("test".getBytes())))) .verifyErrorSatisfies( - e -> assertResponseException(e, KeyVaultErrorException.class, HttpURLConnection.HTTP_NOT_FOUND)); + e -> assertResponseException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) 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 0e5e361955fb..72179c678ca4 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 @@ -3,6 +3,7 @@ package com.azure.security.keyvault.certificates; +import com.azure.core.exception.HttpResponseException; import com.azure.core.exception.ResourceModifiedException; import com.azure.core.exception.ResourceNotFoundException; import com.azure.core.http.HttpClient; @@ -15,7 +16,6 @@ import com.azure.core.util.polling.PollResponse; import com.azure.core.util.polling.SyncPoller; import com.azure.security.keyvault.certificates.implementation.KeyVaultCredentialPolicy; -import com.azure.security.keyvault.certificates.implementation.models.KeyVaultErrorException; import com.azure.security.keyvault.certificates.models.CertificateContact; import com.azure.security.keyvault.certificates.models.CertificateContentType; import com.azure.security.keyvault.certificates.models.CertificateIssuer; @@ -169,7 +169,7 @@ public void createCertificateEmptyName(HttpClient httpClient, CertificateService createCertificateClient(httpClient, serviceVersion); assertResponseException(() -> certificateClient.beginCreateCertificate("", CertificatePolicy.getDefault()), - KeyVaultErrorException.class, HttpURLConnection.HTTP_BAD_METHOD); + HttpResponseException.class, HttpURLConnection.HTTP_BAD_METHOD); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @@ -651,7 +651,7 @@ public void createIssuerEmptyName(HttpClient httpClient, CertificateServiceVersi createCertificateClient(httpClient, serviceVersion); assertResponseException(() -> certificateClient.createIssuer(new CertificateIssuer("", "")), - KeyVaultErrorException.class, HttpURLConnection.HTTP_BAD_METHOD); + HttpResponseException.class, HttpURLConnection.HTTP_BAD_METHOD); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @@ -660,7 +660,7 @@ public void createIssuerNullProvider(HttpClient httpClient, CertificateServiceVe createCertificateClient(httpClient, serviceVersion); assertResponseException(() -> certificateClient.createIssuer(new CertificateIssuer("", null)), - KeyVaultErrorException.class, HttpURLConnection.HTTP_BAD_METHOD); + HttpResponseException.class, HttpURLConnection.HTTP_BAD_METHOD); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @@ -964,7 +964,7 @@ public void mergeCertificateNotFound(HttpClient httpClient, CertificateServiceVe assertResponseException( () -> certificateClient.mergeCertificate(new MergeCertificateOptions( testResourceNamer.randomName("testCert", 20), Collections.singletonList("test".getBytes()))), - KeyVaultErrorException.class, HttpURLConnection.HTTP_NOT_FOUND); + ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) diff --git a/sdk/keyvault/azure-security-keyvault-certificates/swagger/src/main/java/CertificatesCustomizations.java b/sdk/keyvault/azure-security-keyvault-certificates/swagger/src/main/java/CertificatesCustomizations.java index 1a5799d6be19..d8a34e1eb438 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/swagger/src/main/java/CertificatesCustomizations.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/swagger/src/main/java/CertificatesCustomizations.java @@ -1,20 +1,114 @@ // 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.Editor; import com.azure.autorest.customization.LibraryCustomization; import org.slf4j.Logger; +/** + * Contains customizations for Azure KeyVault's Certificates swagger code generation. + */ public class CertificatesCustomizations extends Customization { @Override public void customize(LibraryCustomization libraryCustomization, Logger logger) { - libraryCustomization.getPackage("com.azure.security.keyvault.certificates.models") - .getClass("CertificateKeyCurveName") - .customizeAst(ast -> ast.getClassByName("CertificateKeyCurveName").ifPresent(clazz -> { - clazz.getFieldByName("P256K").ifPresent(field -> field.getVariable(0).setName("P_256K")); - clazz.getFieldByName("P256").ifPresent(field -> field.getVariable(0).setName("P_256")); - clazz.getFieldByName("P384").ifPresent(field -> field.getVariable(0).setName("P_384")); - clazz.getFieldByName("P521").ifPresent(field -> field.getVariable(0).setName("P_521")); - })); + Editor rawEditor = libraryCustomization.getRawEditor(); + + // Remove unnecessary files. + removeFiles(rawEditor); + + customizeError(libraryCustomization); + customizeClientImpl(libraryCustomization); + } + + private static void removeFiles(Editor editor) { + // Remove the next line in favor of renaming to CertificateServiceVersion once the TSP spec includes all service + // versions. + editor.removeFile("src/main/java/com/azure/security/keyvault/certificates/KeyVaultServiceVersion.java"); + editor.removeFile("src/main/java/com/azure/security/keyvault/certificates/CertificateAsyncClient.java"); + editor.removeFile("src/main/java/com/azure/security/keyvault/certificates/CertificateClient.java"); + editor.removeFile("src/main/java/com/azure/security/keyvault/certificates/CertificateClientBuilder.java"); + } + + private static void customizeError(LibraryCustomization libraryCustomization) { + // Rename error class. + ClassCustomization classCustomization = libraryCustomization + .getPackage("com.azure.security.keyvault.certificates.implementation.models") + .getClass("KeyVaultErrorError") + .rename("CertificateOperationError") + .customizeAst(ast -> + ast.getPackageDeclaration().ifPresent(packageDeclaration -> + packageDeclaration.setName("com.azure.security.keyvault.certificates.models"))); + + String classPath = "src/main/java/com/azure/security/keyvault/certificates/implementation/models/" + + "CertificateOperationError.java"; + + replaceInFile(classCustomization, classPath, + new String[] { "KeyVaultErrorError" }, + new String[] { "CertificateOperationError" }); + + // Move it to public package. + libraryCustomization + .getRawEditor() + .renameFile(classPath, + "src/main/java/com/azure/security/keyvault/certificates/models/CertificateOperationError.java"); + + // Replace instances in impl CertificateOperationError and add import statement. + classCustomization = libraryCustomization + .getPackage("com.azure.security.keyvault.certificates.implementation.models") + .getClass("CertificateOperation") + .addImports("com.azure.security.keyvault.certificates.models.CertificateOperationError"); + classPath = + "src/main/java/com/azure/security/keyvault/certificates/implementation/models/CertificateOperation.java"; + + replaceInFile(classCustomization, classPath, + new String[] { "KeyVaultErrorError" }, + new String[] { "CertificateOperationError" }); + } + + private static void customizeClientImpl(LibraryCustomization libraryCustomization) { + // Rename the class. + ClassCustomization classCustomization = libraryCustomization + .getPackage("com.azure.security.keyvault.certificates.implementation") + .getClass("CertificateClientImpl"); + String classPath = + "src/main/java/com/azure/security/keyvault/certificates/implementation/CertificateClientImpl.java"; + + // Rename class references and add imports. + replaceInFile(classCustomization, classPath, new String[] { "KeyVault" }, new String[] { "Certificate" }); + } + + /** + * This method replaces all the provided strings in the specified file with new strings provided in the latter half + * of the 'strings' parameter. + * + * @param classCustomization The class customization to use to edit the file. + * @param classPath The path to the file to edit. + * @param stringsToReplace The strings to replace. + * @param replacementStrings The strings to replace with. + */ + private static void replaceInFile(ClassCustomization classCustomization, String classPath, + String[] stringsToReplace, String[] replacementStrings) { + + if (stringsToReplace != null && replacementStrings != null) { + Editor editor = classCustomization.getEditor(); + String fileContent = editor.getFileContent(classPath); + + // Ensure names has an even length. + if (stringsToReplace.length != replacementStrings.length) { + throw new IllegalArgumentException( + "'stringsToReplace' must have the same number of elements as 'replacementStrings'."); + } + + for (int i = 0; i < stringsToReplace.length; i++) { + fileContent = fileContent.replace(stringsToReplace[i], replacementStrings[i]); + } + + editor.replaceFile(classPath, fileContent); + } else if (stringsToReplace != null || replacementStrings != null) { + throw new IllegalArgumentException( + "'stringsToReplace' must have the same number of elements as 'replacementStrings'."); + } } } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/tsp-location.yaml b/sdk/keyvault/azure-security-keyvault-certificates/tsp-location.yaml new file mode 100644 index 000000000000..f67f5c5940a8 --- /dev/null +++ b/sdk/keyvault/azure-security-keyvault-certificates/tsp-location.yaml @@ -0,0 +1,6 @@ +directory: specification/keyvault/Security.KeyVault.Certificates +commit: 4744046cdc26b7e60ba4615bc79dc1fdfce4ea71 +repo: Azure/azure-rest-api-specs +cleanup: true +additionalDirectories: +- specification/keyvault/Security.KeyVault.Common/ diff --git a/sdk/keyvault/azure-security-keyvault-jca/CHANGELOG.md b/sdk/keyvault/azure-security-keyvault-jca/CHANGELOG.md index e4af2c41e517..0fade9f7a743 100644 --- a/sdk/keyvault/azure-security-keyvault-jca/CHANGELOG.md +++ b/sdk/keyvault/azure-security-keyvault-jca/CHANGELOG.md @@ -7,6 +7,7 @@ ### Breaking Changes ### Bugs Fixed +- Fixed bug: Missing logging for abnormal http status codes when processing HTTP responses. [#42859](https://github.com/Azure/azure-sdk-for-java/issues/42859). ### Other Changes diff --git a/sdk/keyvault/azure-security-keyvault-jca/README.md b/sdk/keyvault/azure-security-keyvault-jca/README.md index f719c9566775..93506bbd1f2e 100644 --- a/sdk/keyvault/azure-security-keyvault-jca/README.md +++ b/sdk/keyvault/azure-security-keyvault-jca/README.md @@ -10,6 +10,20 @@ Azure Key Vault. It is built on four principles: [Source code] | [API reference documentation] | [Product documentation] | [Samples] ## Getting started + +### Prerequisites +- A [Java Development Kit (JDK)][jdk_link], version 8 or later. + - Here are details about [Java 8 client compatibility with Azure Certificate Authority](https://learn.microsoft.com/azure/security/fundamentals/azure-ca-details?tabs=root-and-subordinate-cas-list#client-compatibility-for-public-pkis). +- [Azure Subscription][azure_subscription] +- An existing [Azure Key Vault][azure_keyvault]. If you need to create a Key Vault, you can use the [Azure Cloud Shell][azure_cloud_shell] to create one with this Azure CLI command. Replace `` and `` with your own, unique names: + + ```Bash + az keyvault create --resource-group --name + ``` +- Access configuration: + - If using [role-based](https://learn.microsoft.com/azure/key-vault/general/rbac-guide) access, assign the roles: `Key Vault Secrets User` and `Key Vault Certificate User`. If used for Jar signing, add role `Key Vault Crypto User`. + - If using [access policy](https://learn.microsoft.com/azure/key-vault/general/assign-access-policy), add the permissions: `get` and `list` Secret permissions, `get` and `list` Certificate permissions. If used for Jar signing, add `Sign` Cryptographic Operations. + ### Include the package #### Include the BOM file @@ -50,28 +64,52 @@ add the direct dependency to your project as follows. com.azure azure-security-keyvault-jca - 2.10.0 + 2.11.0-beta.1 ``` [//]: # ({x-version-update-end}) -### Prerequisites -- A [Java Development Kit (JDK)][jdk_link], version 8 or later. - - Here are details about [Java 8 client compatibility with Azure Certificate Authority](https://learn.microsoft.com/azure/security/fundamentals/azure-ca-details?tabs=root-and-subordinate-cas-list#client-compatibility-for-public-pkis). -- [Azure Subscription][azure_subscription] -- An existing [Azure Key Vault][azure_keyvault]. If you need to create a Key Vault, you can use the [Azure Cloud Shell][azure_cloud_shell] to create one with this Azure CLI command. Replace `` and `` with your own, unique names: - -```Bash -az keyvault create --resource-group --name -``` - ## Key concepts +### SSL/TLS and mTLS +The JCA library supports SSL/TLS and mTLS (Mutual TLS) to enhance security in secure communication channels. It enables applications to securely retrieve certificates from Azure Key Vault and use them for TLS-related operations. + +### Jar Signer +The JCA library provides support for Java Archive (JAR) signing, ensuring the integrity and authenticity of JAR files using certificates stored in Azure Key Vault. ## Examples -### Server side SSL +### Exposed Options +The JCA library supports configuring the following options: +* `azure.keyvault.uri`: The Azure Key Vault endpoint to retrieve certificates. +* `azure.keyvault.tenant-id`: The Microsoft Entra ID tenant ID required for authentication. +* `azure.keyvault.client-id`: The client/application ID used for authentication. +* `azure.keyvault.client-secret`: The client secret for authentication when using client credentials. +* `azure.keyvault.managed-identity`: Indicates whether Managed Identity authentication is enabled. +* `azure.cert-path.well-known`: The path where the well-known certificate is stored. +* `azure.cert-path.custom`: The path where the custom certificate is stored. +* `azure.keyvault.jca.refresh-certificates-when-have-un-trust-certificate`: Indicates whether to refresh certificates when have untrusted certificate. +* `azure.keyvault.jca.certificates-refresh-interval`: The refresh interval time. +* `azure.keyvault.jca.certificates-refresh-interval-in-ms`: The refresh interval time. +* `azure.keyvault.disable-challenge-resource-verification`: Indicates whether to disable verification that the authentication challenge resource matches the Key Vault or Managed HSM domain. + +You can configure these properties using: +```java +System.setProperty("azure.keyvault.uri", ""); +``` +or as a JVM argument: +```shell +-Dazure.keyvault.uri= +``` + +### SSL/TLS +#### Server side SSL If you are looking to integrate the JCA provider to create an SSLServerSocket see the example below. ```java readme-sample-serverSSL +System.setProperty("azure.keyvault.uri", ""); +System.setProperty("azure.keyvault.tenant-id", ""); +System.setProperty("azure.keyvault.client-id", ""); +System.setProperty("azure.keyvault.client-secret", ""); + KeyVaultJcaProvider provider = new KeyVaultJcaProvider(); Security.addProvider(provider); @@ -85,14 +123,33 @@ context.init(managerFactory.getKeyManagers(), null, null); SSLServerSocketFactory socketFactory = context.getServerSocketFactory(); SSLServerSocket serverSocket = (SSLServerSocket) socketFactory.createServerSocket(8765); + +while (true) { + SSLSocket socket = (SSLSocket) serverSocket.accept(); + System.out.println("Client connected: " + socket.getInetAddress()); + BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); + + String body = "Hello, this is server."; + String response = + "HTTP/1.1 200 OK\r\n" + "Content-Type: text/plain\r\n" + "Content-Length: " + body.getBytes("UTF-8").length + "\r\n" + "Connection: close\r\n" + "\r\n" + body; + + out.write(response); + out.flush(); + socket.close(); +} ``` Note if you want to use Azure Managed Identity, you should set the value of `azure.keyvault.uri`, and the rest of the parameters would be `null`. -### Client side SSL +#### Client side SSL If you are looking to integrate the JCA provider for client side socket connections, see the Apache HTTP client example below. ```java readme-sample-clientSSL +System.setProperty("azure.keyvault.uri", ""); +System.setProperty("azure.keyvault.tenant-id", ""); +System.setProperty("azure.keyvault.client-id", ""); +System.setProperty("azure.keyvault.client-secret", ""); + KeyVaultJcaProvider provider = new KeyVaultJcaProvider(); Security.addProvider(provider); @@ -114,12 +171,12 @@ PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionMana String result = null; try (CloseableHttpClient client = HttpClients.custom().setConnectionManager(manager).build()) { - HttpGet httpGet = new HttpGet("https://localhost:8766"); + HttpGet httpGet = new HttpGet("https://localhost:8765"); ResponseHandler responseHandler = (HttpResponse response) -> { int status = response.getStatusLine().getStatusCode(); String result1 = "Not success"; - if (status == 204) { - result1 = "Success"; + if (status == 200) { + result1 = EntityUtils.toString(response.getEntity()); } return result1; }; @@ -127,26 +184,148 @@ try (CloseableHttpClient client = HttpClients.custom().setConnectionManager(mana } catch (IOException ioe) { ioe.printStackTrace(); } +System.out.println(result); ``` Note if you want to use Azure managed identity, you should set the value of `azure.keyvault.uri`, and the rest of the parameters would be `null`. -### File-System certificates -You can load the certificate in the file system as a trusted certificate by configure the following properties. +### mTLS +#### Server side mTLS +If you are looking to integrate the JCA provider to create an SSLServerSocket see the example below. + +```java readme-sample-serverMTLS +KeyVaultJcaProvider provider = new KeyVaultJcaProvider(); +Security.addProvider(provider); + +System.setProperty("azure.keyvault.uri", ""); +System.setProperty("azure.keyvault.tenant-id", ""); +System.setProperty("azure.keyvault.client-id", ""); +System.setProperty("azure.keyvault.client-secret", ""); +KeyStore keyStore = KeyVaultKeyStore.getKeyVaultKeyStoreBySystemProperty(); -```yaml -azure: - cert-path: - well-known: # The file location where you store the well-known certificate - custom: # The file location where you store the custom certificate +KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); +kmf.init(keyStore, "".toCharArray()); + +System.setProperty("azure.keyvault.uri", ""); +System.setProperty("azure.keyvault.tenant-id", ""); +System.setProperty("azure.keyvault.client-id", ""); +System.setProperty("azure.keyvault.client-secret", ""); +KeyStore trustStore = KeyVaultKeyStore.getKeyVaultKeyStoreBySystemProperty(); + +TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); +tmf.init(trustStore); + +SSLContext context = SSLContext.getInstance("TLS"); +context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); + +SSLServerSocketFactory socketFactory = context.getServerSocketFactory(); +SSLServerSocket serverSocket = (SSLServerSocket) socketFactory.createServerSocket(8765); +serverSocket.setNeedClientAuth(true); + +while (true) { + SSLSocket socket = (SSLSocket) serverSocket.accept(); + System.out.println("Client connected: " + socket.getInetAddress()); + BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); + + String body = "Hello, this is server."; + String response = + "HTTP/1.1 200 OK\r\n" + "Content-Type: text/plain\r\n" + "Content-Length: " + body.getBytes("UTF-8").length + "\r\n" + "Connection: close\r\n" + "\r\n" + body; + + out.write(response); + out.flush(); + socket.close(); +} ``` +Note if you want to use Azure Managed Identity, you should set the value of `azure.keyvault.uri`, and the rest of the parameters would be `null`. + +#### Client side mTLS +If you are looking to integrate the JCA provider for client side socket connections, see the Apache HTTP client example below. + +```java readme-sample-clientMTLS +KeyVaultJcaProvider provider = new KeyVaultJcaProvider(); +Security.addProvider(provider); + +System.setProperty("azure.keyvault.uri", ""); +System.setProperty("azure.keyvault.tenant-id", ""); +System.setProperty("azure.keyvault.client-id", ""); +System.setProperty("azure.keyvault.client-secret", ""); +KeyStore keyStore = KeyVaultKeyStore.getKeyVaultKeyStoreBySystemProperty(); + +System.setProperty("azure.keyvault.uri", ""); +System.setProperty("azure.keyvault.tenant-id", ""); +System.setProperty("azure.keyvault.client-id", ""); +System.setProperty("azure.keyvault.client-secret", ""); +KeyStore trustStore = KeyVaultKeyStore.getKeyVaultKeyStoreBySystemProperty(); + +SSLContext sslContext = SSLContexts + .custom() + .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()) + .loadKeyMaterial(keyStore, "".toCharArray()) + .build(); + +SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory( + sslContext, (hostname, session) -> true); + +PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager( + RegistryBuilder.create() + .register("https", sslConnectionSocketFactory) + .build()); + +String result = null; + +try (CloseableHttpClient client = HttpClients.custom().setConnectionManager(manager).build()) { + HttpGet httpGet = new HttpGet("https://localhost:8765"); + ResponseHandler responseHandler = (HttpResponse response) -> { + int status = response.getStatusLine().getStatusCode(); + String result1 = "Not success"; + if (status == 200) { + result1 = EntityUtils.toString(response.getEntity()); + } + return result1; + }; + result = client.execute(httpGet, responseHandler); +} catch (IOException ioe) { + ioe.printStackTrace(); +} +System.out.println(result); +``` + +Note if you want to use Azure managed identity, you should set the value of `azure.keyvault.uri`, and the rest of the parameters would be `null`. + +### Jarsigner +You can use the JCA provider to sign JAR files using certificates stored in Azure Key Vault by the following commands: +```bash + jarsigner -keystore NONE -storetype AzureKeyVault \ + -signedjar signerjar.jar ${PARAM_YOUR_JAR_FILE_PATH} "${CERT_NAME}" \ + -verbose -storepass "" \ + -providerName AzureKeyVault \ + -providerClass com.azure.security.keyvault.jca.KeyVaultJcaProvider \ + -J--module-path="${PARAM_JCA_PROVIDER_JAR_PATH}" \ + -J--add-modules="com.azure.security.keyvault.jca" \ + -J-Dazure.keyvault.uri=${KEYVAULT_URL} \ + -J-Dazure.keyvault.tenant-id=${TENANT} \ + -J-Dazure.keyvault.client-id=${CLIENT_ID} \ + -J-Dazure.keyvault.client-secret=${CLIENT_SECRET} +``` +You can find completed steps [here](#using-jarsigner-with-azure-key-vault-jca) + +### File-System certificates +You can load the certificate in the file system as a trusted certificate by configuring the following properties. + +| Certificate Type | Description | Usage | +|------------------------|---------------------------------------------|-------------------------------------------------------------------------------------------| +| Well-Known Certificate | The file path to the well-known certificate | `System.setProperty("azure.cert-path.well-known", "")]` | +| Custom Certificate | The file path to the custom certificate | `System.setProperty("azure.cert-path.custom", "")` | + +Note: These properties support certificate files only (e.g., `.cer`, `.pem`, `.der`, `.crt`). Private keys are not supported. + ### Key-Less certificates You can set the private key as [non-exportable] to ensure the security of the key. Note if you want to use key less certificate, you must add `sign` permission. -You can add permission in portal: ![Sign To Principal](resources/SignToPrincipal.png) +You can add permission in portal: ![Sign To Principal](https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/keyvault/azure-security-keyvault-jca/resources/SignToPrincipal.png) Or add permission by cli command: ```shell @@ -190,6 +369,149 @@ Please replace `${KEY_VAULT}` with your key vault name and replace `${MANAGED_ID | PEM | EC-HSM | P-521 | SHA512withECDSA | ✔ | | PEM | EC-HSM | P-256K | | ✘ | +## Using jarsigner with Azure Key Vault JCA +The integration of Azure Key Vault JCA provider can be used with jarsigner to sign JAR files using certificates stored in Azure Key Vault. Below are the steps to configure and use jarsigner with this library. + +### Download and Configure JCA Provider Jar +1. Download the latest [JCA](https://repo1.maven.org/maven2/com/azure/azure-security-keyvault-jca) Provider Jar. +2. If you are using Java8, you need to add the JCA provider jar to the class path. + 1. Place the jar under the folder `${JAVA_HOME}/jre/lib/ext` + - ![place-jar.jpg](https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/keyvault/azure-security-keyvault-jca/resources/place-jar.png) +3. If you are using Java9 or higher, just place the jar in a folder that jarsigner can access. + +### Prepare Azure Resources +Follow these steps carefully to achieve successful integration: + +1. Prepare your parameters +```shell +DATE_STRING=$(date +%H%M%S) +RESOURCE_GROUP_NAME=jarsigner-rg-$DATE_STRING +KEYVAULT_NAME=jarsigner-kv-$DATE_STRING +CERT_NAME=jarsigner-cert-$DATE_STRING +SERVICE_PRINCIPAL_NAME=jarsigner-sp-$DATE_STRING +SUBSCRIPTION_ID=$(az account show --query id -o tsv) +``` + +2. Create a resource group +```shell +az group create --name $RESOURCE_GROUP_NAME --location "EastUS" +``` + +3. Create a key vault +```shell +az keyvault create --name $KEYVAULT_NAME --resource-group $RESOURCE_GROUP_NAME --location "EastUS" +``` + +4. Assign role to create certificates in the Key Vault. +```shell +# Get your user object ID (if you're using a user account) +USER_OBJECTID=$(az ad signed-in-user show --query id -o tsv) + +# Or if you're using a service principal, get its object ID +# SP_OBJECTID=$(az ad sp show --id --query id -o tsv) + +# Assign Key Vault Certificates Officer role +az role assignment create \ + --role "Key Vault Certificates Officer" \ + --assignee $USER_OBJECTID \ + --scope "/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP_NAME/providers/Microsoft.KeyVault/vaults/$KEYVAULT_NAME" +``` + +5. Get the Key Vault URL +```shell +KEYVAULT_URL=$(az keyvault show --name $KEYVAULT_NAME --query "properties.vaultUri" --resource-group $RESOURCE_GROUP_NAME -o tsv| tr -d '\r\n') +echo $KEYVAULT_URL +``` + +6. Add a certificate to Key Vault +```shell +az keyvault certificate create --vault-name $KEYVAULT_NAME -n $CERT_NAME -p "$(az keyvault certificate get-default-policy)" +``` + +7. Create a Service Principal +```shell +SP_JSON=$(az ad sp create-for-rbac --name $SERVICE_PRINCIPAL_NAME) + +CLIENT_ID=$(echo $SP_JSON | jq -r '.appId') +CLIENT_SECRET=$(echo $SP_JSON | jq -r '.password') +TENANT=$(echo $SP_JSON | jq -r '.tenant') + +echo "CLIENT_ID:"$CLIENT_ID +echo "CLIENT_SECRET:"$CLIENT_SECRET +echo "TENANT:"$TENANT +``` +Note the appId and password from the output, you'll need them later. + +8. Get the objectId +```shell +OBJECTID=$(az ad sp show --id "$CLIENT_ID" --query id -o tsv | tr -d '\r\n') +echo $OBJECTID +``` + +9. Assign Roles to Service Principal: +```shell +# Assign Key Vault Secrets Officer role to Service Principal +az role assignment create \ + --role "Key Vault Secrets Officer" \ + --assignee $OBJECTID \ + --scope "/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP_NAME/providers/Microsoft.KeyVault/vaults/$KEYVAULT_NAME" + +# Assign Key Vault Certificates Officer role Service Principal +az role assignment create \ + --role "Key Vault Certificates Officer" \ + --assignee $OBJECTID \ + --scope "/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP_NAME/providers/Microsoft.KeyVault/vaults/$KEYVAULT_NAME" +``` + +### Sign with Jarsigner +1. If you are using Java8, try to sign the jar using below command + ```bash + jarsigner -keystore NONE -storetype AzureKeyVault \ + -signedjar signerjar.jar ${PARAM_YOUR_JAR_FILE_PATH} "${CERT_NAME}" \ + -verbose -storepass "" \ + -providerName AzureKeyVault \ + -providerClass com.azure.security.keyvault.jca.KeyVaultJcaProvider \ + -J-Dazure.keyvault.uri=${KEYVAULT_URL} \ + -J-Dazure.keyvault.tenant-id=${TENANT} \ + -J-Dazure.keyvault.client-id=${CLIENT_ID} \ + -J-Dazure.keyvault.client-secret=${CLIENT_SECRET} + ``` + +2. If you are using Java9 or higher, try to sign the jar using below command + ```bash + jarsigner -keystore NONE -storetype AzureKeyVault \ + -signedjar signerjar.jar ${PARAM_YOUR_JAR_FILE_PATH} "${CERT_NAME}" \ + -verbose -storepass "" \ + -providerName AzureKeyVault \ + -providerClass com.azure.security.keyvault.jca.KeyVaultJcaProvider \ + -J--module-path="${PARAM_JCA_PROVIDER_JAR_PATH}" \ + -J--add-modules="com.azure.security.keyvault.jca" \ + -J-Dazure.keyvault.uri=${KEYVAULT_URL} \ + -J-Dazure.keyvault.tenant-id=${TENANT} \ + -J-Dazure.keyvault.client-id=${CLIENT_ID} \ + -J-Dazure.keyvault.client-secret=${CLIENT_SECRET} + ``` + +replace ${PARAM_YOUR_JAR_FILE_PATH} with the path of your jar file, replace ${PARAM_JCA_PROVIDER_JAR_PATH} with the path of the jca provider jar. + +Check your output, if you see the `jar signed` message, it means the jar is signed successfully. + ![Jar Signed](https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/keyvault/azure-security-keyvault-jca/resources/jarsigned.png) + +### Verify with Jarsigner +After signing, you can verify the JAR file with: +```bash +jarsigner -verify -verbose -certs signerjar.jar +``` + +Check your output, if you see the `jar verified` message, it means the jar is verified successfully. + ![Jar Verified](https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/keyvault/azure-security-keyvault-jca/resources/jarverified.png) + +### Clean up Resources +```bash +az group delete --name $RESOURCE_GROUP_NAME --yes --no-wait +az ad app delete --id $CLIENT_ID +``` + ## Troubleshooting ### Debug Key Vault Provider @@ -221,15 +543,15 @@ Before you start debugging, make sure the code of your JCA jar is the same as yo After execution, you will see the following output information: - ![start jarsigner command for debug](resources/start-jarsigner-command-for-debug.png) + ![start jarsigner command for debug](https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/keyvault/azure-security-keyvault-jca/resources/start-jarsigner-command-for-debug.png) 2. Create a Remote JVM Debug configuration in your IDE tool, such as in Intellij IDEA: - ![add remote JVM Debug configuration](./resources/add-remote-jvm-debug-configuration.png) + ![add remote JVM Debug configuration](https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/keyvault/azure-security-keyvault-jca/resources/add-remote-jvm-debug-configuration.png) 3. Click the `Debug` button to debug in your IDE: - ![debug breakpoints](resources/debug-breakpoints.png) + ![debug breakpoints](https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/keyvault/azure-security-keyvault-jca/resources/debug-breakpoints.png) ## Configure logging This module uses JUL (`java.util.logging`), so to configure things like the logging level you can directly modify the JUL configuration. @@ -308,4 +630,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][microsoft_c [microsoft_code_of_conduct]: https://opensource.microsoft.com/codeofconduct/ [non-exportable]: https://learn.microsoft.com/azure/key-vault/certificates/about-certificates#exportable-or-non-exportable-key -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fkeyvault%2Fazure-security-keyvault-jca%2FREADME.png) + diff --git a/sdk/keyvault/azure-security-keyvault-jca/pom.xml b/sdk/keyvault/azure-security-keyvault-jca/pom.xml index fbce9b2fd04b..9919f09c9a8c 100644 --- a/sdk/keyvault/azure-security-keyvault-jca/pom.xml +++ b/sdk/keyvault/azure-security-keyvault-jca/pom.xml @@ -54,7 +54,7 @@ com.azure azure-json - 1.3.0 + 1.5.0 true @@ -94,7 +94,7 @@ com.azure azure-core - 1.54.1 + 1.55.3 test diff --git a/sdk/keyvault/azure-security-keyvault-jca/resources/jarsigned.png b/sdk/keyvault/azure-security-keyvault-jca/resources/jarsigned.png new file mode 100644 index 000000000000..418a546a7db1 Binary files /dev/null and b/sdk/keyvault/azure-security-keyvault-jca/resources/jarsigned.png differ diff --git a/sdk/keyvault/azure-security-keyvault-jca/resources/jarverified.png b/sdk/keyvault/azure-security-keyvault-jca/resources/jarverified.png new file mode 100644 index 000000000000..25cbde43edbf Binary files /dev/null and b/sdk/keyvault/azure-security-keyvault-jca/resources/jarverified.png differ diff --git a/sdk/keyvault/azure-security-keyvault-jca/resources/place-jar.png b/sdk/keyvault/azure-security-keyvault-jca/resources/place-jar.png new file mode 100644 index 000000000000..5011ffa25ad9 Binary files /dev/null and b/sdk/keyvault/azure-security-keyvault-jca/resources/place-jar.png differ diff --git a/sdk/keyvault/azure-security-keyvault-jca/src/main/java/com/azure/security/keyvault/jca/KeyVaultKeyStore.java b/sdk/keyvault/azure-security-keyvault-jca/src/main/java/com/azure/security/keyvault/jca/KeyVaultKeyStore.java index 5d69e63a5f6f..4a9fd191562a 100644 --- a/sdk/keyvault/azure-security-keyvault-jca/src/main/java/com/azure/security/keyvault/jca/KeyVaultKeyStore.java +++ b/sdk/keyvault/azure-security-keyvault-jca/src/main/java/com/azure/security/keyvault/jca/KeyVaultKeyStore.java @@ -111,7 +111,6 @@ public final class KeyVaultKeyStore extends KeyStoreSpi { *

          * The constructor uses System.getProperty for * azure.keyvault.uri, - * azure.keyvault.aadAuthenticationUrl, * azure.keyvault.tenantId, * azure.keyvault.clientId, * azure.keyvault.clientSecret and diff --git a/sdk/keyvault/azure-security-keyvault-jca/src/main/java/com/azure/security/keyvault/jca/implementation/utils/HttpUtil.java b/sdk/keyvault/azure-security-keyvault-jca/src/main/java/com/azure/security/keyvault/jca/implementation/utils/HttpUtil.java index 97899f8f18f0..b8623507e0cf 100644 --- a/sdk/keyvault/azure-security-keyvault-jca/src/main/java/com/azure/security/keyvault/jca/implementation/utils/HttpUtil.java +++ b/sdk/keyvault/azure-security-keyvault-jca/src/main/java/com/azure/security/keyvault/jca/implementation/utils/HttpUtil.java @@ -36,6 +36,7 @@ import java.util.logging.Logger; import java.util.stream.Stream; +import static java.util.logging.Level.SEVERE; import static java.util.logging.Level.WARNING; /** @@ -139,11 +140,18 @@ public static HttpResponse getWithResponse(String uri, Map heade private static ResponseHandler createResponseHandler() { return (HttpResponse response) -> { int status = response.getStatusLine().getStatusCode(); - String result = null; + String result; if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); result = entity != null ? EntityUtils.toString(entity) : null; + } else { + String errorMessage = "Fail to get response from Key Vault because return http status code is " + status + + ". It " + + "can be caused by missing permissions or roles. To know how to add permissions or roles, see " + + "https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/keyvault/azure-security-keyvault-jca#prerequisites."; + LOGGER.log(SEVERE, errorMessage); + throw new RuntimeException(errorMessage); } return result; diff --git a/sdk/keyvault/azure-security-keyvault-jca/src/samples/java/com/azure/security/keyvault/jca/mtls/ClientMTLSSample.java b/sdk/keyvault/azure-security-keyvault-jca/src/samples/java/com/azure/security/keyvault/jca/mtls/ClientMTLSSample.java new file mode 100644 index 000000000000..17b5615d7524 --- /dev/null +++ b/sdk/keyvault/azure-security-keyvault-jca/src/samples/java/com/azure/security/keyvault/jca/mtls/ClientMTLSSample.java @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.security.keyvault.jca.mtls; + +import com.azure.security.keyvault.jca.KeyVaultJcaProvider; +import com.azure.security.keyvault.jca.KeyVaultKeyStore; +import org.apache.http.HttpResponse; +import org.apache.http.client.ResponseHandler; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.TrustSelfSignedStrategy; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.ssl.SSLContexts; +import org.apache.http.util.EntityUtils; + +import javax.net.ssl.SSLContext; +import java.io.IOException; +import java.security.KeyStore; +import java.security.Security; + +/** + * The ClientMTLS sample. + */ +public class ClientMTLSSample { + + public static void main(String[] args) throws Exception { + // BEGIN: readme-sample-clientMTLS + KeyVaultJcaProvider provider = new KeyVaultJcaProvider(); + Security.addProvider(provider); + + System.setProperty("azure.keyvault.uri", ""); + System.setProperty("azure.keyvault.tenant-id", ""); + System.setProperty("azure.keyvault.client-id", ""); + System.setProperty("azure.keyvault.client-secret", ""); + KeyStore keyStore = KeyVaultKeyStore.getKeyVaultKeyStoreBySystemProperty(); + + System.setProperty("azure.keyvault.uri", ""); + System.setProperty("azure.keyvault.tenant-id", ""); + System.setProperty("azure.keyvault.client-id", ""); + System.setProperty("azure.keyvault.client-secret", ""); + KeyStore trustStore = KeyVaultKeyStore.getKeyVaultKeyStoreBySystemProperty(); + + SSLContext sslContext = SSLContexts + .custom() + .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()) + .loadKeyMaterial(keyStore, "".toCharArray()) + .build(); + + SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory( + sslContext, (hostname, session) -> true); + + PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager( + RegistryBuilder.create() + .register("https", sslConnectionSocketFactory) + .build()); + + String result = null; + + try (CloseableHttpClient client = HttpClients.custom().setConnectionManager(manager).build()) { + HttpGet httpGet = new HttpGet("https://localhost:8765"); + ResponseHandler responseHandler = (HttpResponse response) -> { + int status = response.getStatusLine().getStatusCode(); + String result1 = "Not success"; + if (status == 200) { + result1 = EntityUtils.toString(response.getEntity()); + } + return result1; + }; + result = client.execute(httpGet, responseHandler); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + System.out.println(result); + // END: readme-sample-clientMTLS + } + +} diff --git a/sdk/keyvault/azure-security-keyvault-jca/src/samples/java/com/azure/security/keyvault/jca/mtls/ServerMTLSSample.java b/sdk/keyvault/azure-security-keyvault-jca/src/samples/java/com/azure/security/keyvault/jca/mtls/ServerMTLSSample.java new file mode 100644 index 000000000000..119272fa6edd --- /dev/null +++ b/sdk/keyvault/azure-security-keyvault-jca/src/samples/java/com/azure/security/keyvault/jca/mtls/ServerMTLSSample.java @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.security.keyvault.jca.mtls; + +import com.azure.security.keyvault.jca.KeyVaultJcaProvider; +import com.azure.security.keyvault.jca.KeyVaultKeyStore; + +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLServerSocket; +import javax.net.ssl.SSLServerSocketFactory; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.TrustManagerFactory; +import java.io.BufferedWriter; +import java.io.OutputStreamWriter; +import java.security.KeyStore; +import java.security.Security; + +/** + * The ServerMTLS sample. + */ +public class ServerMTLSSample { + + public static void main(String[] args) throws Exception { + // BEGIN: readme-sample-serverMTLS + KeyVaultJcaProvider provider = new KeyVaultJcaProvider(); + Security.addProvider(provider); + + System.setProperty("azure.keyvault.uri", ""); + System.setProperty("azure.keyvault.tenant-id", ""); + System.setProperty("azure.keyvault.client-id", ""); + System.setProperty("azure.keyvault.client-secret", ""); + KeyStore keyStore = KeyVaultKeyStore.getKeyVaultKeyStoreBySystemProperty(); + + KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + kmf.init(keyStore, "".toCharArray()); + + System.setProperty("azure.keyvault.uri", ""); + System.setProperty("azure.keyvault.tenant-id", ""); + System.setProperty("azure.keyvault.client-id", ""); + System.setProperty("azure.keyvault.client-secret", ""); + KeyStore trustStore = KeyVaultKeyStore.getKeyVaultKeyStoreBySystemProperty(); + + TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + tmf.init(trustStore); + + SSLContext context = SSLContext.getInstance("TLS"); + context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); + + SSLServerSocketFactory socketFactory = context.getServerSocketFactory(); + SSLServerSocket serverSocket = (SSLServerSocket) socketFactory.createServerSocket(8765); + serverSocket.setNeedClientAuth(true); + + while (true) { + SSLSocket socket = (SSLSocket) serverSocket.accept(); + System.out.println("Client connected: " + socket.getInetAddress()); + BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); + + String body = "Hello, this is server."; + String response = + "HTTP/1.1 200 OK\r\n" + "Content-Type: text/plain\r\n" + "Content-Length: " + body.getBytes("UTF-8").length + "\r\n" + "Connection: close\r\n" + "\r\n" + body; + + out.write(response); + out.flush(); + socket.close(); + } + // END: readme-sample-serverMTLS + } + +} diff --git a/sdk/keyvault/azure-security-keyvault-jca/src/samples/java/com/azure/security/keyvault/jca/tls/ClientSSLSample.java b/sdk/keyvault/azure-security-keyvault-jca/src/samples/java/com/azure/security/keyvault/jca/tls/ClientSSLSample.java new file mode 100644 index 000000000000..6c8058831872 --- /dev/null +++ b/sdk/keyvault/azure-security-keyvault-jca/src/samples/java/com/azure/security/keyvault/jca/tls/ClientSSLSample.java @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.security.keyvault.jca.tls; + +import com.azure.security.keyvault.jca.KeyVaultJcaProvider; +import com.azure.security.keyvault.jca.KeyVaultKeyStore; +import org.apache.http.HttpResponse; +import org.apache.http.client.ResponseHandler; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.ssl.SSLContexts; +import org.apache.http.conn.ssl.TrustSelfSignedStrategy; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.util.EntityUtils; + +import javax.net.ssl.SSLContext; + +import java.io.IOException; +import java.security.KeyStore; +import java.security.Security; + +/** + * The ClientSSL sample. + */ +public class ClientSSLSample { + + public static void main(String[] args) throws Exception { + // BEGIN: readme-sample-clientSSL + System.setProperty("azure.keyvault.uri", ""); + System.setProperty("azure.keyvault.tenant-id", ""); + System.setProperty("azure.keyvault.client-id", ""); + System.setProperty("azure.keyvault.client-secret", ""); + + KeyVaultJcaProvider provider = new KeyVaultJcaProvider(); + Security.addProvider(provider); + + KeyStore keyStore = KeyVaultKeyStore.getKeyVaultKeyStoreBySystemProperty(); + + SSLContext sslContext = SSLContexts + .custom() + .loadTrustMaterial(keyStore, new TrustSelfSignedStrategy()) + .build(); + + SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory( + sslContext, (hostname, session) -> true); + + PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager( + RegistryBuilder.create() + .register("https", sslConnectionSocketFactory) + .build()); + + String result = null; + + try (CloseableHttpClient client = HttpClients.custom().setConnectionManager(manager).build()) { + HttpGet httpGet = new HttpGet("https://localhost:8765"); + ResponseHandler responseHandler = (HttpResponse response) -> { + int status = response.getStatusLine().getStatusCode(); + String result1 = "Not success"; + if (status == 200) { + result1 = EntityUtils.toString(response.getEntity()); + } + return result1; + }; + result = client.execute(httpGet, responseHandler); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + System.out.println(result); + // END: readme-sample-clientSSL + } + +} diff --git a/sdk/keyvault/azure-security-keyvault-jca/src/samples/java/com/azure/security/keyvault/jca/tls/ServerSSLSample.java b/sdk/keyvault/azure-security-keyvault-jca/src/samples/java/com/azure/security/keyvault/jca/tls/ServerSSLSample.java new file mode 100644 index 000000000000..f925dd04a75c --- /dev/null +++ b/sdk/keyvault/azure-security-keyvault-jca/src/samples/java/com/azure/security/keyvault/jca/tls/ServerSSLSample.java @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.security.keyvault.jca.tls; + +import com.azure.security.keyvault.jca.KeyVaultJcaProvider; +import com.azure.security.keyvault.jca.KeyVaultKeyStore; + +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLServerSocket; +import javax.net.ssl.SSLServerSocketFactory; +import javax.net.ssl.SSLSocket; +import java.io.BufferedWriter; +import java.io.OutputStreamWriter; +import java.security.KeyStore; +import java.security.Security; + +/** + * The ServerSSL sample. + */ +public class ServerSSLSample { + + public static void main(String[] args) throws Exception { + // BEGIN: readme-sample-serverSSL + System.setProperty("azure.keyvault.uri", ""); + System.setProperty("azure.keyvault.tenant-id", ""); + System.setProperty("azure.keyvault.client-id", ""); + System.setProperty("azure.keyvault.client-secret", ""); + + KeyVaultJcaProvider provider = new KeyVaultJcaProvider(); + Security.addProvider(provider); + + KeyStore keyStore = KeyVaultKeyStore.getKeyVaultKeyStoreBySystemProperty(); + + KeyManagerFactory managerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + managerFactory.init(keyStore, "".toCharArray()); + + SSLContext context = SSLContext.getInstance("TLS"); + context.init(managerFactory.getKeyManagers(), null, null); + + SSLServerSocketFactory socketFactory = context.getServerSocketFactory(); + SSLServerSocket serverSocket = (SSLServerSocket) socketFactory.createServerSocket(8765); + + while (true) { + SSLSocket socket = (SSLSocket) serverSocket.accept(); + System.out.println("Client connected: " + socket.getInetAddress()); + BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); + + String body = "Hello, this is server."; + String response = + "HTTP/1.1 200 OK\r\n" + "Content-Type: text/plain\r\n" + "Content-Length: " + body.getBytes("UTF-8").length + "\r\n" + "Connection: close\r\n" + "\r\n" + body; + + out.write(response); + out.flush(); + socket.close(); + } + // END: readme-sample-serverSSL + } + +} diff --git a/sdk/keyvault/azure-security-keyvault-keys/CHANGELOG.md b/sdk/keyvault/azure-security-keyvault-keys/CHANGELOG.md index de7b660a8401..04d6d492c52f 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/CHANGELOG.md +++ b/sdk/keyvault/azure-security-keyvault-keys/CHANGELOG.md @@ -10,6 +10,21 @@ ### Other Changes +## 4.9.3 (2025-03-04) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. +- Upgraded `azure-json` from `1.3.0` to version `1.4.0`. +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`. + +## 4.9.2 (2025-01-14) + +### Bugs Fixed +- Fixed issue where certain `toString()` calls could cause a `NullPointerException`. ([#43776](https://github.com/Azure/azure-sdk-for-java/pull/43776)) + ## 4.9.1 (2024-12-04) ### Other Changes diff --git a/sdk/keyvault/azure-security-keyvault-keys/README.md b/sdk/keyvault/azure-security-keyvault-keys/README.md index 6d2ebee3b75e..7103e85f57a9 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/README.md +++ b/sdk/keyvault/azure-security-keyvault-keys/README.md @@ -45,7 +45,7 @@ If you want to take dependency on a particular version of the library that is no com.azure azure-security-keyvault-keys - 4.9.0 + 4.10.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -370,4 +370,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][microsoft_c [http_clients_wiki]: https://learn.microsoft.com/azure/developer/java/sdk/http-client-pipeline#http-clients [microsoft_code_of_conduct]: https://opensource.microsoft.com/codeofconduct/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fkeyvault%2Fazure-security-keyvault-keys%2FREADME.png) + diff --git a/sdk/keyvault/azure-security-keyvault-keys/checkstyle-suppressions.xml b/sdk/keyvault/azure-security-keyvault-keys/checkstyle-suppressions.xml index 7366f6709444..d36abc98e84c 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/checkstyle-suppressions.xml +++ b/sdk/keyvault/azure-security-keyvault-keys/checkstyle-suppressions.xml @@ -3,6 +3,7 @@ + diff --git a/sdk/keyvault/azure-security-keyvault-keys/pom.xml b/sdk/keyvault/azure-security-keyvault-keys/pom.xml index fcbca46a4935..2797c76b299d 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/pom.xml +++ b/sdk/keyvault/azure-security-keyvault-keys/pom.xml @@ -54,32 +54,32 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyAsyncClient.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyAsyncClient.java index b5024f510285..c5c063693e49 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyAsyncClient.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyAsyncClient.java @@ -15,6 +15,7 @@ import com.azure.core.http.rest.PagedResponseBase; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.BinaryData; import com.azure.core.util.CoreUtils; import com.azure.core.util.FluxUtil; import com.azure.core.util.logging.ClientLogger; @@ -26,10 +27,19 @@ import com.azure.security.keyvault.keys.cryptography.CryptographyClientBuilder; import com.azure.security.keyvault.keys.implementation.KeyClientImpl; import com.azure.security.keyvault.keys.implementation.KeyVaultKeysUtils; +import com.azure.security.keyvault.keys.implementation.models.BackupKeyResult; +import com.azure.security.keyvault.keys.implementation.models.DeletedKeyBundle; import com.azure.security.keyvault.keys.implementation.models.DeletedKeyItem; +import com.azure.security.keyvault.keys.implementation.models.GetRandomBytesRequest; +import com.azure.security.keyvault.keys.implementation.models.KeyBundle; +import com.azure.security.keyvault.keys.implementation.models.KeyCreateParameters; +import com.azure.security.keyvault.keys.implementation.models.KeyImportParameters; import com.azure.security.keyvault.keys.implementation.models.KeyItem; -import com.azure.security.keyvault.keys.implementation.models.KeyVaultErrorException; +import com.azure.security.keyvault.keys.implementation.models.KeyReleaseParameters; +import com.azure.security.keyvault.keys.implementation.models.KeyRestoreParameters; +import com.azure.security.keyvault.keys.implementation.models.KeyUpdateParameters; import com.azure.security.keyvault.keys.implementation.models.KeyVaultKeysModelsUtils; +import com.azure.security.keyvault.keys.implementation.models.RandomBytes; import com.azure.security.keyvault.keys.models.CreateEcKeyOptions; import com.azure.security.keyvault.keys.models.CreateKeyOptions; import com.azure.security.keyvault.keys.models.CreateOctKeyOptions; @@ -58,6 +68,7 @@ import static com.azure.core.util.FluxUtil.monoError; import static com.azure.core.util.FluxUtil.withContext; +import static com.azure.security.keyvault.keys.implementation.KeyVaultKeysUtils.EMPTY_OPTIONS; import static com.azure.security.keyvault.keys.implementation.models.KeyVaultKeysModelsUtils.createDeletedKey; import static com.azure.security.keyvault.keys.implementation.models.KeyVaultKeysModelsUtils.createKeyAttributes; import static com.azure.security.keyvault.keys.implementation.models.KeyVaultKeysModelsUtils.createKeyVaultKey; @@ -336,21 +347,27 @@ public Mono> createKeyWithResponse(CreateKeyOptions create return monoError(LOGGER, new NullPointerException("'createKeyOptions' cannot be null.")); } + KeyCreateParameters keyCreateParameters + = new KeyCreateParameters(createKeyOptions.getKeyType()).setKeyOps(createKeyOptions.getKeyOperations()) + .setKeyAttributes(createKeyAttributes(createKeyOptions)) + .setTags(createKeyOptions.getTags()) + .setReleasePolicy(mapKeyReleasePolicy(createKeyOptions.getReleasePolicy())); + return implClient - .createKeyWithResponseAsync(vaultUrl, createKeyOptions.getName(), createKeyOptions.getKeyType(), null, - null, createKeyOptions.getKeyOperations(), createKeyAttributes(createKeyOptions), - createKeyOptions.getTags(), null, mapKeyReleasePolicy(createKeyOptions.getReleasePolicy())) - .onErrorMap(KeyVaultErrorException.class, KeyAsyncClient::mapCreateKeyException) - .map(response -> new SimpleResponse<>(response, createKeyVaultKey(response.getValue()))); + .createKeyWithResponseAsync(createKeyOptions.getName(), BinaryData.fromObject(keyCreateParameters), + EMPTY_OPTIONS) + .onErrorMap(HttpResponseException.class, KeyAsyncClient::mapCreateKeyException) + .map(response -> new SimpleResponse<>(response, + createKeyVaultKey(response.getValue().toObject(KeyBundle.class)))); } catch (RuntimeException e) { return monoError(LOGGER, e); } } - static HttpResponseException mapCreateKeyException(KeyVaultErrorException exception) { - return (exception.getResponse().getStatusCode() == 400) - ? new ResourceModifiedException(exception.getMessage(), exception.getResponse(), exception.getValue()) - : exception; + static HttpResponseException mapCreateKeyException(HttpResponseException e) { + return (e.getResponse().getStatusCode() == 400) + ? new ResourceModifiedException(e.getMessage(), e.getResponse(), e.getValue()) + : e; } /** @@ -500,13 +517,20 @@ public Mono> createRsaKeyWithResponse(CreateRsaKeyOptions return monoError(LOGGER, new NullPointerException("'createRsaKeyOptions' cannot be null.")); } + KeyCreateParameters keyCreateParameters + = new KeyCreateParameters(createRsaKeyOptions.getKeyType()).setKeySize(createRsaKeyOptions.getKeySize()) + .setPublicExponent(createRsaKeyOptions.getPublicExponent()) + .setKeyOps(createRsaKeyOptions.getKeyOperations()) + .setKeyAttributes(createKeyAttributes(createRsaKeyOptions)) + .setTags(createRsaKeyOptions.getTags()) + .setReleasePolicy(mapKeyReleasePolicy(createRsaKeyOptions.getReleasePolicy())); + return implClient - .createKeyWithResponseAsync(vaultUrl, createRsaKeyOptions.getName(), createRsaKeyOptions.getKeyType(), - createRsaKeyOptions.getKeySize(), createRsaKeyOptions.getPublicExponent(), - createRsaKeyOptions.getKeyOperations(), createKeyAttributes(createRsaKeyOptions), - createRsaKeyOptions.getTags(), null, mapKeyReleasePolicy(createRsaKeyOptions.getReleasePolicy())) - .onErrorMap(KeyVaultErrorException.class, KeyAsyncClient::mapCreateKeyException) - .map(response -> new SimpleResponse<>(response, createKeyVaultKey(response.getValue()))); + .createKeyWithResponseAsync(createRsaKeyOptions.getName(), BinaryData.fromObject(keyCreateParameters), + EMPTY_OPTIONS) + .onErrorMap(HttpResponseException.class, KeyAsyncClient::mapCreateKeyException) + .map(response -> new SimpleResponse<>(response, + createKeyVaultKey(response.getValue().toObject(KeyBundle.class)))); } catch (RuntimeException e) { return monoError(LOGGER, e); } @@ -614,13 +638,19 @@ public Mono> createEcKeyWithResponse(CreateEcKeyOptions cr return monoError(LOGGER, new NullPointerException("'createEcKeyOptions' cannot be null.")); } + KeyCreateParameters keyCreateParameters = new KeyCreateParameters(createEcKeyOptions.getKeyType()) + .setKeyOps(createEcKeyOptions.getKeyOperations()) + .setKeyAttributes(createKeyAttributes(createEcKeyOptions)) + .setTags(createEcKeyOptions.getTags()) + .setCurve(createEcKeyOptions.getCurveName()) + .setReleasePolicy(mapKeyReleasePolicy(createEcKeyOptions.getReleasePolicy())); + return implClient - .createKeyWithResponseAsync(vaultUrl, createEcKeyOptions.getName(), createEcKeyOptions.getKeyType(), - null, null, createEcKeyOptions.getKeyOperations(), createKeyAttributes(createEcKeyOptions), - createEcKeyOptions.getTags(), createEcKeyOptions.getCurveName(), - mapKeyReleasePolicy(createEcKeyOptions.getReleasePolicy())) - .onErrorMap(KeyVaultErrorException.class, KeyAsyncClient::mapCreateKeyException) - .map(response -> new SimpleResponse<>(response, createKeyVaultKey(response.getValue()))); + .createKeyWithResponseAsync(createEcKeyOptions.getName(), BinaryData.fromObject(keyCreateParameters), + EMPTY_OPTIONS) + .onErrorMap(HttpResponseException.class, KeyAsyncClient::mapCreateKeyException) + .map(response -> new SimpleResponse<>(response, + createKeyVaultKey(response.getValue().toObject(KeyBundle.class)))); } catch (RuntimeException e) { return monoError(LOGGER, e); } @@ -719,13 +749,19 @@ public Mono> createOctKeyWithResponse(CreateOctKeyOptions return monoError(LOGGER, new NullPointerException("'createOctKeyOptions' cannot be null.")); } + KeyCreateParameters keyCreateParameters + = new KeyCreateParameters(createOctKeyOptions.getKeyType()).setKeySize(createOctKeyOptions.getKeySize()) + .setKeyOps(createOctKeyOptions.getKeyOperations()) + .setKeyAttributes(createKeyAttributes(createOctKeyOptions)) + .setTags(createOctKeyOptions.getTags()) + .setReleasePolicy(mapKeyReleasePolicy(createOctKeyOptions.getReleasePolicy())); + return implClient - .createKeyWithResponseAsync(vaultUrl, createOctKeyOptions.getName(), createOctKeyOptions.getKeyType(), - createOctKeyOptions.getKeySize(), null, createOctKeyOptions.getKeyOperations(), - createKeyAttributes(createOctKeyOptions), createOctKeyOptions.getTags(), null, - mapKeyReleasePolicy(createOctKeyOptions.getReleasePolicy())) - .onErrorMap(KeyVaultErrorException.class, KeyAsyncClient::mapCreateKeyException) - .map(response -> new SimpleResponse<>(response, createKeyVaultKey(response.getValue()))); + .createKeyWithResponseAsync(createOctKeyOptions.getName(), BinaryData.fromObject(keyCreateParameters), + EMPTY_OPTIONS) + .onErrorMap(HttpResponseException.class, KeyAsyncClient::mapCreateKeyException) + .map(response -> new SimpleResponse<>(response, + createKeyVaultKey(response.getValue().toObject(KeyBundle.class)))); } catch (RuntimeException e) { return monoError(LOGGER, e); } @@ -846,12 +882,17 @@ public Mono> importKeyWithResponse(ImportKeyOptions import return monoError(LOGGER, new RuntimeException("'importKeyOptions' cannot be null.")); } + KeyImportParameters keyImportParameters = new KeyImportParameters(mapJsonWebKey(importKeyOptions.getKey())) + .setHsm(importKeyOptions.isHardwareProtected()) + .setKeyAttributes(createKeyAttributes(importKeyOptions)) + .setTags(importKeyOptions.getTags()) + .setReleasePolicy(mapKeyReleasePolicy(importKeyOptions.getReleasePolicy())); + return implClient - .importKeyWithResponseAsync(vaultUrl, importKeyOptions.getName(), - mapJsonWebKey(importKeyOptions.getKey()), importKeyOptions.isHardwareProtected(), - createKeyAttributes(importKeyOptions), importKeyOptions.getTags(), - mapKeyReleasePolicy(importKeyOptions.getReleasePolicy())) - .map(response -> new SimpleResponse<>(response, createKeyVaultKey(response.getValue()))); + .importKeyWithResponseAsync(importKeyOptions.getName(), BinaryData.fromObject(keyImportParameters), + EMPTY_OPTIONS) + .map(response -> new SimpleResponse<>(response, + createKeyVaultKey(response.getValue().toObject(KeyBundle.class)))); } catch (RuntimeException e) { return monoError(LOGGER, e); } @@ -926,14 +967,27 @@ public Mono getKey(String name, String version) { @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getKeyWithResponse(String name, String version) { try { - return implClient.getKeyWithResponseAsync(vaultUrl, name, version) - .onErrorMap(KeyVaultErrorException.class, KeyVaultKeysUtils::mapGetKeyException) - .map(response -> new SimpleResponse<>(response, createKeyVaultKey(response.getValue()))); + return implClient.getKeyWithResponseAsync(name, version, EMPTY_OPTIONS) + .onErrorMap(HttpResponseException.class, KeyAsyncClient::mapGetKeyException) + .map(response -> new SimpleResponse<>(response, + createKeyVaultKey(response.getValue().toObject(KeyBundle.class)))); } catch (RuntimeException e) { return monoError(LOGGER, e); } } + /** + * Maps a {@link HttpResponseException} to an {@link HttpResponseException} for get key operations. + * + * @param e The {@link HttpResponseException} to map. + * @return The {@link HttpResponseException} that maps from the {@link HttpResponseException}. + */ + public static HttpResponseException mapGetKeyException(HttpResponseException e) { + return e.getResponse().getStatusCode() == 403 + ? new ResourceModifiedException(e.getMessage(), e.getResponse(), e.getValue()) + : e; + } + /** * Gets the public part of the specified {@link KeyVaultKey key} and key version. The get key operation is * applicable to all {@link KeyType key types} and it requires the {@code keys/get} permission. @@ -1009,16 +1063,23 @@ public Mono getKey(String name) { @ServiceMethod(returns = ReturnType.SINGLE) public Mono> updateKeyPropertiesWithResponse(KeyProperties keyProperties, KeyOperation... keyOperations) { + try { if (keyProperties == null) { return monoError(LOGGER, new NullPointerException("'keyProperties' cannot be null.")); } + KeyUpdateParameters keyUpdateParameters + = new KeyUpdateParameters().setKeyOps(keyOperations == null ? null : Arrays.asList(keyOperations)) + .setKeyAttributes(createKeyAttributes(keyProperties)) + .setTags(keyProperties.getTags()) + .setReleasePolicy(mapKeyReleasePolicy(keyProperties.getReleasePolicy())); + return implClient - .updateKeyWithResponseAsync(vaultUrl, keyProperties.getName(), keyProperties.getVersion(), - keyOperations == null ? null : Arrays.asList(keyOperations), createKeyAttributes(keyProperties), - keyProperties.getTags(), mapKeyReleasePolicy(keyProperties.getReleasePolicy())) - .map(response -> new SimpleResponse<>(response, createKeyVaultKey(response.getValue()))); + .updateKeyWithResponseAsync(keyProperties.getName(), keyProperties.getVersion(), + BinaryData.fromObject(keyUpdateParameters), EMPTY_OPTIONS) + .map(response -> new SimpleResponse<>(response, + createKeyVaultKey(response.getValue().toObject(KeyBundle.class)))); } catch (RuntimeException e) { return monoError(LOGGER, e); } @@ -1107,23 +1168,16 @@ public PollerFlux beginDeleteKey(String name) { } private Function, Mono> deleteActivationOperation(String name) { - return pollingContext -> implClient.deleteKeyAsync(vaultUrl, name) - .onErrorMap(KeyVaultErrorException.class, KeyAsyncClient::mapDeleteKeyException) - .map(KeyVaultKeysModelsUtils::createDeletedKey); - } - - static HttpResponseException mapDeleteKeyException(KeyVaultErrorException ex) { - return (ex.getResponse().getStatusCode() == 404) - ? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; + return pollingContext -> implClient.deleteKeyWithResponseAsync(name, EMPTY_OPTIONS) + .map(response -> createDeletedKey(response.getValue().toObject(DeletedKeyBundle.class))); } private Function, Mono>> deletePollOperation(String name) { - return pollingContext -> implClient.getDeletedKeyAsync(vaultUrl, name) - .map(bundle -> new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, - createDeletedKey(bundle))) - .onErrorResume(HttpResponseException.class, ex -> { - if (ex.getResponse().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { + return pollingContext -> implClient.getDeletedKeyWithResponseAsync(name, EMPTY_OPTIONS) + .map(response -> new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, + createDeletedKey(response.getValue().toObject(DeletedKeyBundle.class)))) + .onErrorResume(HttpResponseException.class, e -> { + if (e.getResponse().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { return Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue())); } else { @@ -1196,20 +1250,14 @@ public Mono getDeletedKey(String name) { @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getDeletedKeyWithResponse(String name) { try { - return implClient.getDeletedKeyWithResponseAsync(vaultUrl, name) - .onErrorMap(KeyVaultErrorException.class, KeyAsyncClient::mapGetDeletedKeyException) - .map(response -> new SimpleResponse<>(response, createDeletedKey(response.getValue()))); + return implClient.getDeletedKeyWithResponseAsync(name, EMPTY_OPTIONS) + .map(response -> new SimpleResponse<>(response, + createDeletedKey(response.getValue().toObject(DeletedKeyBundle.class)))); } catch (RuntimeException e) { return monoError(LOGGER, e); } } - static HttpResponseException mapGetDeletedKeyException(KeyVaultErrorException ex) { - return (ex.getResponse().getStatusCode() == 404) - ? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; - } - /** * Permanently deletes the specified {@link KeyVaultKey key} without the possibility of recovery. The purge * deleted key operation is applicable for soft-delete enabled vaults. This operation requires the @@ -1265,19 +1313,12 @@ public Mono purgeDeletedKey(String name) { @ServiceMethod(returns = ReturnType.SINGLE) public Mono> purgeDeletedKeyWithResponse(String name) { try { - return implClient.purgeDeletedKeyWithResponseAsync(vaultUrl, name) - .onErrorMap(KeyVaultErrorException.class, KeyAsyncClient::mapPurgeDeletedKeyException); + return implClient.purgeDeletedKeyWithResponseAsync(name, EMPTY_OPTIONS); } catch (RuntimeException e) { return monoError(LOGGER, e); } } - static HttpResponseException mapPurgeDeletedKeyException(KeyVaultErrorException ex) { - return (ex.getResponse().getStatusCode() == 404) - ? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; - } - /** * Recovers the {@link KeyVaultKey deleted key} in the key vault to its latest version and can only be performed * on a soft-delete enabled vault. An attempt to recover an {@link KeyVaultKey non-deleted key} will return an @@ -1312,24 +1353,18 @@ public PollerFlux beginRecoverDeletedKey(String name) { } private Function, Mono> recoverActivationOperation(String name) { - return pollingContext -> implClient.recoverDeletedKeyAsync(vaultUrl, name) - .onErrorMap(KeyVaultErrorException.class, KeyAsyncClient::mapRecoverDeletedKeyException) - .map(KeyVaultKeysModelsUtils::createKeyVaultKey); - } - - static HttpResponseException mapRecoverDeletedKeyException(KeyVaultErrorException ex) { - return (ex.getResponse().getStatusCode() == 404) - ? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; + return pollingContext -> implClient.recoverDeletedKeyWithResponseAsync(name, EMPTY_OPTIONS) + .map(response -> KeyVaultKeysModelsUtils.createKeyVaultKey(response.getValue().toObject(KeyBundle.class))); } private Function, Mono>> recoverPollOperation(String keyName) { - return pollingContext -> implClient.getKeyAsync(vaultUrl, keyName, null) - .map(keyResponse -> new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, - createKeyVaultKey(keyResponse))) - .onErrorResume(KeyVaultErrorException.class, ex -> { - if (ex.getResponse().getStatusCode() == 404) { + + return pollingContext -> implClient.getKeyWithResponseAsync(keyName, null, EMPTY_OPTIONS) + .map(response -> new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, + createKeyVaultKey(response.getValue().toObject(KeyBundle.class)))) + .onErrorResume(HttpResponseException.class, e -> { + if (e.getResponse().getStatusCode() == 404) { return Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue())); } else { @@ -1418,20 +1453,14 @@ public Mono backupKey(String name) { @ServiceMethod(returns = ReturnType.SINGLE) public Mono> backupKeyWithResponse(String name) { try { - return implClient.backupKeyWithResponseAsync(vaultUrl, name) - .onErrorMap(KeyVaultErrorException.class, KeyAsyncClient::mapBackupKeyException) - .map(response -> new SimpleResponse<>(response, response.getValue().getValue())); + return implClient.backupKeyWithResponseAsync(name, EMPTY_OPTIONS) + .map(response -> new SimpleResponse<>(response, + response.getValue().toObject(BackupKeyResult.class).getValue())); } catch (RuntimeException e) { return monoError(LOGGER, e); } } - static HttpResponseException mapBackupKeyException(KeyVaultErrorException ex) { - return (ex.getResponse().getStatusCode() == 404) - ? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; - } - /** * Restores a backed up {@link KeyVaultKey key} to a vault. Imports a previously backed up {@link KeyVaultKey key} * into Azure Key Vault, restoring the {@link KeyVaultKey key}, its key identifier, attributes and access control @@ -1507,18 +1536,21 @@ public Mono restoreKeyBackup(byte[] backup) { @ServiceMethod(returns = ReturnType.SINGLE) public Mono> restoreKeyBackupWithResponse(byte[] backup) { try { - return implClient.restoreKeyWithResponseAsync(vaultUrl, backup) - .onErrorMap(KeyVaultErrorException.class, KeyAsyncClient::mapRestoreKeyException) - .map(response -> new SimpleResponse<>(response, createKeyVaultKey(response.getValue()))); + KeyRestoreParameters keyRestoreParameters = new KeyRestoreParameters(backup); + + return implClient.restoreKeyWithResponseAsync(BinaryData.fromObject(keyRestoreParameters), EMPTY_OPTIONS) + .onErrorMap(HttpResponseException.class, KeyAsyncClient::mapRestoreKeyException) + .map(response -> new SimpleResponse<>(response, + createKeyVaultKey(response.getValue().toObject(KeyBundle.class)))); } catch (RuntimeException e) { return monoError(LOGGER, e); } } - static HttpResponseException mapRestoreKeyException(KeyVaultErrorException ex) { - return (ex.getResponse().getStatusCode() == 400) - ? new ResourceModifiedException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; + static HttpResponseException mapRestoreKeyException(HttpResponseException e) { + return (e.getResponse().getStatusCode() == 400) + ? new ResourceModifiedException(e.getMessage(), e.getResponse(), e.getValue()) + : e; } /** @@ -1549,21 +1581,26 @@ static HttpResponseException mapRestoreKeyException(KeyVaultErrorException ex) { */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux listPropertiesOfKeys() { - return new PagedFlux<>( - maxResults -> implClient.getKeysSinglePageAsync(vaultUrl, maxResults) - .map(KeyAsyncClient::mapKeyItemPagedResponse), - (continuationToken, maxResults) -> implClient.getKeysNextSinglePageAsync(continuationToken, vaultUrl) - .map(KeyAsyncClient::mapKeyItemPagedResponse)); + PagedFlux pagedFlux = implClient.getKeysAsync(EMPTY_OPTIONS); + + return PagedFlux.create(() -> (continuationTokenParam, pageSizeParam) -> { + Flux> pagedResponseFlux = (continuationTokenParam == null) + ? pagedFlux.byPage().take(1) + : pagedFlux.byPage(continuationTokenParam).take(1); + + return pagedResponseFlux.map(pagedResponse -> mapPagedResponse(pagedResponse, + binaryData -> KeyVaultKeysModelsUtils.createKeyProperties(binaryData.toObject(KeyItem.class)))); + }); } - static PagedResponse mapKeyItemPagedResponse(PagedResponse page) { - List properties = new ArrayList<>(page.getValue().size()); + private static PagedResponse mapPagedResponse(PagedResponse page, Function itemMapper) { + List mappedValues = new ArrayList<>(page.getValue().size()); - for (KeyItem keyItem : page.getValue()) { - properties.add(KeyVaultKeysModelsUtils.createKeyProperties(keyItem)); + for (T item : page.getValue()) { + mappedValues.add(itemMapper.apply(item)); } - return new PagedResponseBase<>(page.getRequest(), page.getStatusCode(), page.getHeaders(), properties, + return new PagedResponseBase<>(page.getRequest(), page.getStatusCode(), page.getHeaders(), mappedValues, page.getContinuationToken(), null); } @@ -1589,22 +1626,16 @@ static PagedResponse mapKeyItemPagedResponse(PagedResponse listDeletedKeys() { - return new PagedFlux<>( - maxResults -> implClient.getDeletedKeysSinglePageAsync(vaultUrl, maxResults) - .map(KeyAsyncClient::mapDeletedKeyItemPagedResponse), - (continuationToken, maxResults) -> implClient.getDeletedKeysNextSinglePageAsync(continuationToken, vaultUrl) - .map(KeyAsyncClient::mapDeletedKeyItemPagedResponse)); - } + PagedFlux pagedFlux = implClient.getDeletedKeysAsync(EMPTY_OPTIONS); - static PagedResponse mapDeletedKeyItemPagedResponse(PagedResponse page) { - List properties = new ArrayList<>(page.getValue().size()); + return PagedFlux.create(() -> (continuationTokenParam, pageSizeParam) -> { + Flux> pagedResponseFlux = (continuationTokenParam == null) + ? pagedFlux.byPage().take(1) + : pagedFlux.byPage(continuationTokenParam).take(1); - for (DeletedKeyItem keyItem : page.getValue()) { - properties.add(KeyVaultKeysModelsUtils.createDeletedKey(keyItem)); - } - - return new PagedResponseBase<>(page.getRequest(), page.getStatusCode(), page.getHeaders(), properties, - page.getContinuationToken(), null); + return pagedResponseFlux.map(pagedResponse -> mapPagedResponse(pagedResponse, + binaryData -> createDeletedKey(binaryData.toObject(DeletedKeyItem.class)))); + }); } /** @@ -1639,11 +1670,16 @@ static PagedResponse mapDeletedKeyItemPagedResponse(PagedResponse listPropertiesOfKeyVersions(String name) { - return new PagedFlux<>( - maxResults -> implClient.getKeyVersionsSinglePageAsync(vaultUrl, name, maxResults) - .map(KeyAsyncClient::mapKeyItemPagedResponse), - (continuationToken, maxResults) -> implClient.getKeyVersionsNextSinglePageAsync(continuationToken, vaultUrl) - .map(KeyAsyncClient::mapKeyItemPagedResponse)); + PagedFlux pagedFlux = implClient.getKeyVersionsAsync(name, EMPTY_OPTIONS); + + return PagedFlux.create(() -> (continuationTokenParam, pageSizeParam) -> { + Flux> pagedResponseFlux = (continuationTokenParam == null) + ? pagedFlux.byPage().take(1) + : pagedFlux.byPage(continuationTokenParam).take(1); + + return pagedResponseFlux.map(pagedResponse -> mapPagedResponse(pagedResponse, + binaryData -> KeyVaultKeysModelsUtils.createKeyProperties(binaryData.toObject(KeyItem.class)))); + }); } /** @@ -1693,8 +1729,12 @@ public Mono getRandomBytes(int count) { @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getRandomBytesWithResponse(int count) { try { - return withContext(context -> implClient.getRandomBytesWithResponseAsync(vaultUrl, count)) - .map(response -> new SimpleResponse<>(response, response.getValue().getValue())); + GetRandomBytesRequest getRandomBytesRequest = new GetRandomBytesRequest(count); + + return withContext(context -> implClient + .getRandomBytesWithResponseAsync(BinaryData.fromObject(getRandomBytesRequest), EMPTY_OPTIONS) + .map(response -> new SimpleResponse<>(response, + response.getValue().toObject(RandomBytes.class).getValue()))); } catch (RuntimeException e) { return monoError(LOGGER, e); } @@ -1808,6 +1848,7 @@ public Mono releaseKey(String name, String version, String tar @ServiceMethod(returns = ReturnType.SINGLE) public Mono> releaseKeyWithResponse(String name, String version, String targetAttestationToken, ReleaseKeyOptions releaseKeyOptions) { + try { if (CoreUtils.isNullOrEmpty(name) || CoreUtils.isNullOrEmpty(targetAttestationToken)) { return monoError(LOGGER, @@ -1818,20 +1859,18 @@ public Mono> releaseKeyWithResponse(String name, Stri KeyExportEncryptionAlgorithm algorithm = releaseKeyOptions == null ? null : releaseKeyOptions.getAlgorithm(); + KeyReleaseParameters keyReleaseParameters + = new KeyReleaseParameters(targetAttestationToken).setNonce(nonce).setEnc(algorithm); + return implClient - .releaseWithResponseAsync(vaultUrl, name, version, targetAttestationToken, nonce, algorithm) - .onErrorMap(KeyVaultErrorException.class, KeyAsyncClient::mapReleaseKeyException); + .releaseWithResponseAsync(name, version, BinaryData.fromObject(keyReleaseParameters), EMPTY_OPTIONS) + .map(binaryData -> new SimpleResponse<>(binaryData, + binaryData.getValue().toObject(ReleaseKeyResult.class))); } catch (RuntimeException e) { return monoError(LOGGER, e); } } - static HttpResponseException mapReleaseKeyException(KeyVaultErrorException ex) { - return (ex.getResponse().getStatusCode() == 404) - ? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; - } - /** * Rotates a {@link KeyVaultKey key}. The rotate key operation will do so based on * {@link KeyRotationPolicy key's rotation policy}. This operation requires the {@code keys/rotate} permission. @@ -1889,20 +1928,14 @@ public Mono rotateKey(String name) { @ServiceMethod(returns = ReturnType.SINGLE) public Mono> rotateKeyWithResponse(String name) { try { - return implClient.rotateKeyWithResponseAsync(vaultUrl, name) - .onErrorMap(KeyVaultErrorException.class, KeyAsyncClient::mapRotateKeyException) - .map(response -> new SimpleResponse<>(response, createKeyVaultKey(response.getValue()))); + return implClient.rotateKeyWithResponseAsync(name, EMPTY_OPTIONS) + .map(response -> new SimpleResponse<>(response, + createKeyVaultKey(response.getValue().toObject(KeyBundle.class)))); } catch (RuntimeException e) { return monoError(LOGGER, e); } } - static HttpResponseException mapRotateKeyException(KeyVaultErrorException ex) { - return (ex.getResponse().getStatusCode() == 404) - ? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; - } - /** * Gets the {@link KeyRotationPolicy} for the {@link KeyVaultKey key} with the provided name. This operation * requires the {@code keys/get} permission. @@ -1960,20 +1993,14 @@ public Mono getKeyRotationPolicy(String keyName) { @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getKeyRotationPolicyWithResponse(String keyName) { try { - return implClient.getKeyRotationPolicyWithResponseAsync(vaultUrl, keyName) - .onErrorMap(KeyVaultErrorException.class, KeyAsyncClient::mapGetKeyRotationPolicyException) - .map(response -> new SimpleResponse<>(response, mapKeyRotationPolicyImpl(response.getValue()))); + return implClient.getKeyRotationPolicyWithResponseAsync(keyName, EMPTY_OPTIONS) + .map(response -> new SimpleResponse<>(response, mapKeyRotationPolicyImpl(response.getValue() + .toObject(com.azure.security.keyvault.keys.implementation.models.KeyRotationPolicy.class)))); } catch (RuntimeException e) { return monoError(LOGGER, e); } } - static HttpResponseException mapGetKeyRotationPolicyException(KeyVaultErrorException ex) { - return (ex.getResponse().getStatusCode() == 404) - ? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; - } - /** * Updates the {@link KeyRotationPolicy} of the key with the provided name. This operation requires the * {@code keys/update} permission. @@ -2060,18 +2087,14 @@ public Mono updateKeyRotationPolicy(String keyName, KeyRotati public Mono> updateKeyRotationPolicyWithResponse(String keyName, KeyRotationPolicy keyRotationPolicy) { try { + return implClient - .updateKeyRotationPolicyWithResponseAsync(vaultUrl, keyName, mapKeyRotationPolicy(keyRotationPolicy)) - .onErrorMap(KeyVaultErrorException.class, KeyAsyncClient::mapUpdateKeyRotationPolicyException) - .map(response -> new SimpleResponse<>(response, mapKeyRotationPolicyImpl(response.getValue()))); + .updateKeyRotationPolicyWithResponseAsync(keyName, + BinaryData.fromObject(mapKeyRotationPolicy(keyRotationPolicy)), EMPTY_OPTIONS) + .map(response -> new SimpleResponse<>(response, mapKeyRotationPolicyImpl(response.getValue() + .toObject(com.azure.security.keyvault.keys.implementation.models.KeyRotationPolicy.class)))); } catch (RuntimeException e) { return monoError(LOGGER, e); } } - - static HttpResponseException mapUpdateKeyRotationPolicyException(KeyVaultErrorException ex) { - return (ex.getResponse().getStatusCode() == 404) - ? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; - } } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyClient.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyClient.java index 14c7f6e48fb1..dc7fe0429af0 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyClient.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyClient.java @@ -11,8 +11,10 @@ import com.azure.core.exception.ResourceNotFoundException; import com.azure.core.http.HttpPipeline; import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.RequestOptions; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.BinaryData; import com.azure.core.util.Context; import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; @@ -26,8 +28,16 @@ import com.azure.security.keyvault.keys.implementation.KeyVaultKeysUtils; import com.azure.security.keyvault.keys.implementation.models.BackupKeyResult; import com.azure.security.keyvault.keys.implementation.models.DeletedKeyBundle; +import com.azure.security.keyvault.keys.implementation.models.DeletedKeyItem; +import com.azure.security.keyvault.keys.implementation.models.GetRandomBytesRequest; import com.azure.security.keyvault.keys.implementation.models.KeyBundle; -import com.azure.security.keyvault.keys.implementation.models.KeyVaultErrorException; +import com.azure.security.keyvault.keys.implementation.models.KeyCreateParameters; +import com.azure.security.keyvault.keys.implementation.models.KeyImportParameters; +import com.azure.security.keyvault.keys.implementation.models.KeyItem; +import com.azure.security.keyvault.keys.implementation.models.KeyReleaseParameters; +import com.azure.security.keyvault.keys.implementation.models.KeyRestoreParameters; +import com.azure.security.keyvault.keys.implementation.models.KeyUpdateParameters; +import com.azure.security.keyvault.keys.implementation.models.KeyVaultKeysModelsUtils; import com.azure.security.keyvault.keys.implementation.models.RandomBytes; import com.azure.security.keyvault.keys.models.CreateEcKeyOptions; import com.azure.security.keyvault.keys.models.CreateKeyOptions; @@ -51,8 +61,7 @@ import java.util.Arrays; import java.util.function.Function; -import static com.azure.security.keyvault.keys.KeyAsyncClient.mapDeletedKeyItemPagedResponse; -import static com.azure.security.keyvault.keys.KeyAsyncClient.mapKeyItemPagedResponse; +import static com.azure.security.keyvault.keys.implementation.KeyVaultKeysUtils.EMPTY_OPTIONS; import static com.azure.security.keyvault.keys.implementation.KeyVaultKeysUtils.callWithMappedException; import static com.azure.security.keyvault.keys.implementation.models.KeyVaultKeysModelsUtils.createDeletedKey; import static com.azure.security.keyvault.keys.implementation.models.KeyVaultKeysModelsUtils.createKeyAttributes; @@ -368,13 +377,19 @@ public Response createKeyWithResponse(CreateKeyOptions createKeyOpt throw LOGGER.logExceptionAsError(new NullPointerException("'createKeyOptions' cannot be null.")); } - Response response = callWithMappedException( - () -> implClient.createKeyWithResponse(vaultUrl, createKeyOptions.getName(), createKeyOptions.getKeyType(), - null, null, createKeyOptions.getKeyOperations(), createKeyAttributes(createKeyOptions), - createKeyOptions.getTags(), null, mapKeyReleasePolicy(createKeyOptions.getReleasePolicy()), context), + KeyCreateParameters keyCreateParameters = new KeyCreateParameters(createKeyOptions.getKeyType()) + .setKeyAttributes(createKeyAttributes(createKeyOptions)) + .setKeyOps(createKeyOptions.getKeyOperations()) + .setReleasePolicy(mapKeyReleasePolicy(createKeyOptions.getReleasePolicy())) + .setTags(createKeyOptions.getTags()) + .setReleasePolicy(mapKeyReleasePolicy(createKeyOptions.getReleasePolicy())); + + Response response = callWithMappedException( + () -> implClient.createKeyWithResponse(createKeyOptions.getName(), + BinaryData.fromObject(keyCreateParameters), new RequestOptions().setContext(context)), KeyAsyncClient::mapCreateKeyException); - return new SimpleResponse<>(response, createKeyVaultKey(response.getValue())); + return new SimpleResponse<>(response, createKeyVaultKey(response.getValue().toObject(KeyBundle.class))); } /** @@ -470,15 +485,20 @@ public Response createRsaKeyWithResponse(CreateRsaKeyOptions create throw LOGGER.logExceptionAsError(new NullPointerException("'createRsaKeyOptions' cannot be null.")); } - Response response = callWithMappedException( - () -> implClient.createKeyWithResponse(vaultUrl, createRsaKeyOptions.getName(), - createRsaKeyOptions.getKeyType(), createRsaKeyOptions.getKeySize(), - createRsaKeyOptions.getPublicExponent(), createRsaKeyOptions.getKeyOperations(), - createKeyAttributes(createRsaKeyOptions), createRsaKeyOptions.getTags(), null, - mapKeyReleasePolicy(createRsaKeyOptions.getReleasePolicy()), context), + KeyCreateParameters keyCreateParameters + = new KeyCreateParameters(createRsaKeyOptions.getKeyType()).setKeySize(createRsaKeyOptions.getKeySize()) + .setPublicExponent(createRsaKeyOptions.getPublicExponent()) + .setKeyOps(createRsaKeyOptions.getKeyOperations()) + .setKeyAttributes(createKeyAttributes(createRsaKeyOptions)) + .setTags(createRsaKeyOptions.getTags()) + .setReleasePolicy(mapKeyReleasePolicy(createRsaKeyOptions.getReleasePolicy())); + + Response response = callWithMappedException( + () -> implClient.createKeyWithResponse(createRsaKeyOptions.getName(), + BinaryData.fromObject(keyCreateParameters), new RequestOptions().setContext(context)), KeyAsyncClient::mapCreateKeyException); - return new SimpleResponse<>(response, createKeyVaultKey(response.getValue())); + return new SimpleResponse<>(response, createKeyVaultKey(response.getValue().toObject(KeyBundle.class))); } /** @@ -577,14 +597,19 @@ public Response createEcKeyWithResponse(CreateEcKeyOptions createEc throw LOGGER.logExceptionAsError(new NullPointerException("'createEcKeyOptions' cannot be null.")); } - Response response = callWithMappedException( - () -> implClient.createKeyWithResponse(vaultUrl, createEcKeyOptions.getName(), - createEcKeyOptions.getKeyType(), null, null, createEcKeyOptions.getKeyOperations(), - createKeyAttributes(createEcKeyOptions), createEcKeyOptions.getTags(), - createEcKeyOptions.getCurveName(), mapKeyReleasePolicy(createEcKeyOptions.getReleasePolicy()), context), + KeyCreateParameters keyCreateParameters + = new KeyCreateParameters(createEcKeyOptions.getKeyType()).setKeyOps(createEcKeyOptions.getKeyOperations()) + .setKeyAttributes(createKeyAttributes(createEcKeyOptions)) + .setTags(createEcKeyOptions.getTags()) + .setCurve(createEcKeyOptions.getCurveName()) + .setReleasePolicy(mapKeyReleasePolicy(createEcKeyOptions.getReleasePolicy())); + + Response response = callWithMappedException( + () -> implClient.createKeyWithResponse(createEcKeyOptions.getName(), + BinaryData.fromObject(keyCreateParameters), new RequestOptions().setContext(context)), KeyAsyncClient::mapCreateKeyException); - return new SimpleResponse<>(response, createKeyVaultKey(response.getValue())); + return new SimpleResponse<>(response, createKeyVaultKey(response.getValue().toObject(KeyBundle.class))); } /** @@ -674,13 +699,19 @@ public Response createOctKeyWithResponse(CreateOctKeyOptions create throw LOGGER.logExceptionAsError(new NullPointerException("'createOctKeyOptions' cannot be null.")); } - Response response = callWithMappedException(() -> implClient.createKeyWithResponse(vaultUrl, - createOctKeyOptions.getName(), createOctKeyOptions.getKeyType(), createOctKeyOptions.getKeySize(), null, - createOctKeyOptions.getKeyOperations(), createKeyAttributes(createOctKeyOptions), - createOctKeyOptions.getTags(), null, mapKeyReleasePolicy(createOctKeyOptions.getReleasePolicy()), context), + KeyCreateParameters keyCreateParameters + = new KeyCreateParameters(createOctKeyOptions.getKeyType()).setKeySize(createOctKeyOptions.getKeySize()) + .setKeyOps(createOctKeyOptions.getKeyOperations()) + .setKeyAttributes(createKeyAttributes(createOctKeyOptions)) + .setTags(createOctKeyOptions.getTags()) + .setReleasePolicy(mapKeyReleasePolicy(createOctKeyOptions.getReleasePolicy())); + + Response response = callWithMappedException( + () -> implClient.createKeyWithResponse(createOctKeyOptions.getName(), + BinaryData.fromObject(keyCreateParameters), new RequestOptions().setContext(context)), KeyAsyncClient::mapCreateKeyException); - return new SimpleResponse<>(response, createKeyVaultKey(response.getValue())); + return new SimpleResponse<>(response, createKeyVaultKey(response.getValue().toObject(KeyBundle.class))); } /** @@ -798,12 +829,16 @@ public Response importKeyWithResponse(ImportKeyOptions importKeyOpt throw LOGGER.logExceptionAsError(new RuntimeException("'importKeyOptions' cannot be null.")); } - Response response = implClient.importKeyWithResponse(vaultUrl, importKeyOptions.getName(), - mapJsonWebKey(importKeyOptions.getKey()), importKeyOptions.isHardwareProtected(), - createKeyAttributes(importKeyOptions), importKeyOptions.getTags(), - mapKeyReleasePolicy(importKeyOptions.getReleasePolicy()), context); + KeyImportParameters keyImportParameters = new KeyImportParameters(mapJsonWebKey(importKeyOptions.getKey())) + .setHsm(importKeyOptions.isHardwareProtected()) + .setKeyAttributes(createKeyAttributes(importKeyOptions)) + .setTags(importKeyOptions.getTags()) + .setReleasePolicy(mapKeyReleasePolicy(importKeyOptions.getReleasePolicy())); - return new SimpleResponse<>(response, createKeyVaultKey(response.getValue())); + Response response = implClient.importKeyWithResponse(importKeyOptions.getName(), + BinaryData.fromObject(keyImportParameters), new RequestOptions().setContext(context)); + + return new SimpleResponse<>(response, createKeyVaultKey(response.getValue().toObject(KeyBundle.class))); } /** @@ -875,11 +910,11 @@ public KeyVaultKey getKey(String name, String version) { */ @ServiceMethod(returns = ReturnType.SINGLE) public Response getKeyWithResponse(String name, String version, Context context) { - Response response - = callWithMappedException(() -> implClient.getKeyWithResponse(vaultUrl, name, version, context), - KeyVaultKeysUtils::mapGetKeyException); + Response response = callWithMappedException( + () -> implClient.getKeyWithResponse(name, version, new RequestOptions().setContext(context)), + KeyAsyncClient::mapGetKeyException); - return new SimpleResponse<>(response, createKeyVaultKey(response.getValue())); + return new SimpleResponse<>(response, createKeyVaultKey(response.getValue().toObject(KeyBundle.class))); } /** @@ -995,16 +1030,22 @@ public KeyVaultKey updateKeyProperties(KeyProperties keyProperties, KeyOperation @ServiceMethod(returns = ReturnType.SINGLE) public Response updateKeyPropertiesWithResponse(KeyProperties keyProperties, Context context, KeyOperation... keyOperations) { + if (keyProperties == null) { throw LOGGER.logExceptionAsError(new NullPointerException("'keyProperties' cannot be null.")); } - Response response - = implClient.updateKeyWithResponse(vaultUrl, keyProperties.getName(), keyProperties.getVersion(), - keyOperations == null ? null : Arrays.asList(keyOperations), createKeyAttributes(keyProperties), - keyProperties.getTags(), mapKeyReleasePolicy(keyProperties.getReleasePolicy()), context); + KeyUpdateParameters keyUpdateParameters + = new KeyUpdateParameters().setKeyOps(keyOperations == null ? null : Arrays.asList(keyOperations)) + .setKeyAttributes(createKeyAttributes(keyProperties)) + .setTags(keyProperties.getTags()) + .setReleasePolicy(mapKeyReleasePolicy(keyProperties.getReleasePolicy())); + + Response response + = implClient.updateKeyWithResponse(keyProperties.getName(), keyProperties.getVersion(), + BinaryData.fromObject(keyUpdateParameters), new RequestOptions().setContext(context)); - return new SimpleResponse<>(response, createKeyVaultKey(response.getValue())); + return new SimpleResponse<>(response, createKeyVaultKey(response.getValue().toObject(KeyBundle.class))); } /** @@ -1051,17 +1092,19 @@ public SyncPoller beginDeleteKey(String name) { } private Function, PollResponse> deleteActivationOperation(String name) { - return pollingContext -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, callWithMappedException( - () -> createDeletedKey(implClient.deleteKey(vaultUrl, name)), KeyAsyncClient::mapDeleteKeyException)); + return pollingContext -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, createDeletedKey( + implClient.deleteKeyWithResponse(name, EMPTY_OPTIONS).getValue().toObject(DeletedKeyBundle.class))); } private Function, PollResponse> deletePollOperation(String name) { return pollingContext -> { try { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, - createDeletedKey(implClient.getDeletedKey(vaultUrl, name))); - } catch (KeyVaultErrorException ex) { - if (ex.getResponse().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { + createDeletedKey(implClient.getDeletedKeyWithResponse(name, EMPTY_OPTIONS) + .getValue() + .toObject(DeletedKeyBundle.class))); + } catch (HttpResponseException e) { + if (e.getResponse().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { return new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()); } else { @@ -1071,7 +1114,7 @@ private Function, PollResponse> deletePol return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } - } catch (RuntimeException ex) { + } catch (RuntimeException e) { // This means either vault has soft-delete disabled or permission is not granted for the get deleted key // operation. In both cases deletion operation was successful when activation operation succeeded before // reaching here. @@ -1135,11 +1178,10 @@ public DeletedKey getDeletedKey(String name) { */ @ServiceMethod(returns = ReturnType.SINGLE) public Response getDeletedKeyWithResponse(String name, Context context) { - Response response - = callWithMappedException(() -> implClient.getDeletedKeyWithResponse(vaultUrl, name, context), - KeyAsyncClient::mapGetDeletedKeyException); + Response response + = implClient.getDeletedKeyWithResponse(name, new RequestOptions().setContext(context)); - return new SimpleResponse<>(response, createDeletedKey(response.getValue())); + return new SimpleResponse<>(response, createDeletedKey(response.getValue().toObject(DeletedKeyBundle.class))); } /** @@ -1192,8 +1234,7 @@ public void purgeDeletedKey(String name) { */ @ServiceMethod(returns = ReturnType.SINGLE) public Response purgeDeletedKeyWithResponse(String name, Context context) { - return callWithMappedException(() -> implClient.purgeDeletedKeyWithResponse(vaultUrl, name, context), - KeyAsyncClient::mapPurgeDeletedKeyException); + return implClient.purgeDeletedKeyWithResponse(name, new RequestOptions().setContext(context)); } /** @@ -1234,18 +1275,17 @@ public SyncPoller beginRecoverDeletedKey(String name) { } private Function, PollResponse> recoverActivationOperation(String name) { - return pollingContext -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, - createKeyVaultKey(callWithMappedException(() -> implClient.recoverDeletedKey(vaultUrl, name), - KeyAsyncClient::mapRecoverDeletedKeyException))); + return pollingContext -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, createKeyVaultKey( + implClient.recoverDeletedKeyWithResponse(name, EMPTY_OPTIONS).getValue().toObject(KeyBundle.class))); } private Function, PollResponse> recoverPollOperation(String keyName) { return pollingContext -> { try { - return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, - createKeyVaultKey(implClient.getKey(vaultUrl, keyName, null))); - } catch (KeyVaultErrorException ex) { - if (ex.getResponse().getStatusCode() == 404) { + return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, createKeyVaultKey( + implClient.getKeyWithResponse(keyName, null, EMPTY_OPTIONS).getValue().toObject(KeyBundle.class))); + } catch (HttpResponseException e) { + if (e.getResponse().getStatusCode() == 404) { return new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()); } else { @@ -1254,7 +1294,7 @@ private Function, PollResponse> recover return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } - } catch (RuntimeException ex) { + } catch (RuntimeException e) { // This means permission is not granted for the get deleted key operation. In both cases deletion // operation was successful when activation operation succeeded before reaching here. return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, @@ -1333,10 +1373,10 @@ public byte[] backupKey(String name) { */ @ServiceMethod(returns = ReturnType.SINGLE) public Response backupKeyWithResponse(String name, Context context) { - Response response = callWithMappedException( - () -> implClient.backupKeyWithResponse(vaultUrl, name, context), KeyAsyncClient::mapBackupKeyException); + Response response + = implClient.backupKeyWithResponse(name, new RequestOptions().setContext(context)); - return new SimpleResponse<>(response, response.getValue().getValue()); + return new SimpleResponse<>(response, response.getValue().toObject(BackupKeyResult.class).getValue()); } /** @@ -1411,10 +1451,14 @@ public KeyVaultKey restoreKeyBackup(byte[] backup) { */ @ServiceMethod(returns = ReturnType.SINGLE) public Response restoreKeyBackupWithResponse(byte[] backup, Context context) { - Response response = callWithMappedException( - () -> implClient.restoreKeyWithResponse(vaultUrl, backup, context), KeyAsyncClient::mapRestoreKeyException); + KeyRestoreParameters keyRestoreParameters = new KeyRestoreParameters(backup); + + Response response = callWithMappedException( + () -> implClient.restoreKeyWithResponse(BinaryData.fromObject(keyRestoreParameters), + new RequestOptions().setContext(context)), + KeyAsyncClient::mapRestoreKeyException); - return new SimpleResponse<>(response, createKeyVaultKey(response.getValue())); + return new SimpleResponse<>(response, createKeyVaultKey(response.getValue().toObject(KeyBundle.class))); } /** @@ -1514,10 +1558,8 @@ public PagedIterable listPropertiesOfKeys() { */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable listPropertiesOfKeys(Context context) { - return new PagedIterable<>( - maxResults -> mapKeyItemPagedResponse(implClient.getKeysSinglePage(vaultUrl, maxResults, context)), - (continuationToken, maxResults) -> mapKeyItemPagedResponse( - implClient.getKeysNextSinglePage(continuationToken, vaultUrl, context))); + return implClient.getKeys(new RequestOptions().setContext(context)) + .mapPage(binaryData -> KeyVaultKeysModelsUtils.createKeyProperties(binaryData.toObject(KeyItem.class))); } /** @@ -1596,11 +1638,8 @@ public PagedIterable listDeletedKeys() { */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable listDeletedKeys(Context context) { - return new PagedIterable<>( - maxResults -> mapDeletedKeyItemPagedResponse( - implClient.getDeletedKeysSinglePage(vaultUrl, maxResults, context)), - (continuationToken, maxResults) -> mapDeletedKeyItemPagedResponse( - implClient.getDeletedKeysNextSinglePage(continuationToken, vaultUrl, context))); + return implClient.getDeletedKeys(new RequestOptions().setContext(context)) + .mapPage(binaryData -> KeyVaultKeysModelsUtils.createDeletedKey(binaryData.toObject(DeletedKeyItem.class))); } /** @@ -1699,11 +1738,8 @@ public PagedIterable listPropertiesOfKeyVersions(String name) { */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable listPropertiesOfKeyVersions(String name, Context context) { - return new PagedIterable<>( - maxResults -> mapKeyItemPagedResponse( - implClient.getKeyVersionsSinglePage(vaultUrl, name, maxResults, context)), - (continuationToken, maxResults) -> mapKeyItemPagedResponse( - implClient.getKeyVersionsNextSinglePage(continuationToken, vaultUrl, context))); + return implClient.getKeyVersions(name, new RequestOptions().setContext(context)) + .mapPage(binaryData -> KeyVaultKeysModelsUtils.createKeyProperties(binaryData.toObject(KeyItem.class))); } /** @@ -1756,9 +1792,12 @@ public byte[] getRandomBytes(int count) { */ @ServiceMethod(returns = ReturnType.SINGLE) public Response getRandomBytesWithResponse(int count, Context context) { - Response response = implClient.getRandomBytesWithResponse(vaultUrl, count, context); + GetRandomBytesRequest getRandomBytesRequest = new GetRandomBytesRequest(count); + + Response response = implClient.getRandomBytesWithResponse( + BinaryData.fromObject(getRandomBytesRequest), new RequestOptions().setContext(context)); - return new SimpleResponse<>(response, response.getValue().getValue()); + return new SimpleResponse<>(response, response.getValue().toObject(RandomBytes.class).getValue()); } /** @@ -1878,9 +1917,13 @@ public Response releaseKeyWithResponse(String name, String ver String nonce = releaseKeyOptions == null ? null : releaseKeyOptions.getNonce(); KeyExportEncryptionAlgorithm algorithm = releaseKeyOptions == null ? null : releaseKeyOptions.getAlgorithm(); + KeyReleaseParameters keyReleaseParameters + = new KeyReleaseParameters(targetAttestationToken).setEnc(algorithm).setNonce(nonce); - return callWithMappedException(() -> implClient.releaseWithResponse(vaultUrl, name, version, - targetAttestationToken, nonce, algorithm, context), KeyAsyncClient::mapReleaseKeyException); + Response response = implClient.releaseWithResponse(name, version, + BinaryData.fromObject(keyReleaseParameters), new RequestOptions().setContext(context)); + + return new SimpleResponse<>(response, response.getValue().toObject(ReleaseKeyResult.class)); } /** @@ -1941,10 +1984,10 @@ public KeyVaultKey rotateKey(String name) { */ @ServiceMethod(returns = ReturnType.SINGLE) public Response rotateKeyWithResponse(String name, Context context) { - Response response = callWithMappedException( - () -> implClient.rotateKeyWithResponse(vaultUrl, name, context), KeyAsyncClient::mapRotateKeyException); + Response response + = implClient.rotateKeyWithResponse(name, new RequestOptions().setContext(context)); - return new SimpleResponse<>(response, createKeyVaultKey(response.getValue())); + return new SimpleResponse<>(response, createKeyVaultKey(response.getValue().toObject(KeyBundle.class))); } /** @@ -2003,11 +2046,11 @@ public KeyRotationPolicy getKeyRotationPolicy(String keyName) { */ @ServiceMethod(returns = ReturnType.SINGLE) public Response getKeyRotationPolicyWithResponse(String keyName, Context context) { - Response response - = callWithMappedException(() -> implClient.getKeyRotationPolicyWithResponse(vaultUrl, keyName, context), - KeyAsyncClient::mapGetKeyRotationPolicyException); + Response response + = implClient.getKeyRotationPolicyWithResponse(keyName, new RequestOptions().setContext(context)); - return new SimpleResponse<>(response, mapKeyRotationPolicyImpl(response.getValue())); + return new SimpleResponse<>(response, mapKeyRotationPolicyImpl(response.getValue() + .toObject(com.azure.security.keyvault.keys.implementation.models.KeyRotationPolicy.class))); } /** @@ -2096,12 +2139,11 @@ public KeyRotationPolicy updateKeyRotationPolicy(String keyName, KeyRotationPoli @ServiceMethod(returns = ReturnType.SINGLE) public Response updateKeyRotationPolicyWithResponse(String keyName, KeyRotationPolicy keyRotationPolicy, Context context) { - Response response - = callWithMappedException( - () -> implClient.updateKeyRotationPolicyWithResponse(vaultUrl, keyName, - mapKeyRotationPolicy(keyRotationPolicy), context), - KeyAsyncClient::mapUpdateKeyRotationPolicyException); - return new SimpleResponse<>(response, mapKeyRotationPolicyImpl(response.getValue())); + Response response = implClient.updateKeyRotationPolicyWithResponse(keyName, + BinaryData.fromObject(mapKeyRotationPolicy(keyRotationPolicy)), new RequestOptions().setContext(context)); + + return new SimpleResponse<>(response, mapKeyRotationPolicyImpl(response.getValue() + .toObject(com.azure.security.keyvault.keys.implementation.models.KeyRotationPolicy.class))); } } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyClientBuilder.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyClientBuilder.java index 2756c32164cf..8e546acc00a6 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyClientBuilder.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyClientBuilder.java @@ -98,7 +98,7 @@ public final class KeyClientBuilder implements TokenCredentialTrait properties = CoreUtils.getProperties("azure-key-vault-keys.properties"); + Map properties = CoreUtils.getProperties("azure-security-keyvault-keys.properties"); CLIENT_NAME = properties.getOrDefault("name", "UnknownName"); CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion"); } @@ -150,7 +150,7 @@ public KeyClientBuilder() { * and {@link #retryPolicy(RetryPolicy)} have been set. */ public KeyClient buildClient() { - return new KeyClient(buildInnerClient(), vaultUrl, version != null ? version : KeyServiceVersion.getLatest()); + return new KeyClient(buildImplClient(), vaultUrl, version); } /** @@ -171,11 +171,10 @@ public KeyClient buildClient() { * and {@link #retryPolicy(RetryPolicy)} have been set. */ public KeyAsyncClient buildAsyncClient() { - return new KeyAsyncClient(buildInnerClient(), vaultUrl, - version != null ? version : KeyServiceVersion.getLatest()); + return new KeyAsyncClient(buildImplClient(), vaultUrl, version); } - private KeyClientImpl buildInnerClient() { + private KeyClientImpl buildImplClient() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; String buildEndpoint = getBuildEndpoint(buildConfiguration); @@ -185,10 +184,12 @@ private KeyClientImpl buildInnerClient() { .logExceptionAsError(new IllegalStateException(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED)); } - KeyServiceVersion serviceVersion = version != null ? version : KeyServiceVersion.getLatest(); + if (version == null) { + version = KeyServiceVersion.getLatest(); + } if (pipeline != null) { - return new KeyClientImpl(pipeline, serviceVersion.getVersion()); + return new KeyClientImpl(pipeline, vaultUrl, version); } if (credential == null) { @@ -228,13 +229,13 @@ private KeyClientImpl buildInnerClient() { Tracer tracer = TracerProvider.getDefaultProvider() .createTracer(CLIENT_NAME, CLIENT_VERSION, KEYVAULT_TRACING_NAMESPACE_VALUE, tracingOptions); - HttpPipeline pipeline = new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) + HttpPipeline builtPipeline = new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .tracer(tracer) .clientOptions(localClientOptions) .build(); - return new KeyClientImpl(pipeline, serviceVersion.getVersion()); + return new KeyClientImpl(builtPipeline, vaultUrl, version); } /** diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientBuilder.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientBuilder.java index 5f7a136fbb3b..e80da595489a 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientBuilder.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyClientBuilder.java @@ -124,7 +124,7 @@ public final class CryptographyClientBuilder implements TokenCredentialTrait properties = CoreUtils.getProperties("azure-key-vault-keys.properties"); + Map properties = CoreUtils.getProperties("azure-security-keyvault-keys.properties"); CLIENT_NAME = properties.getOrDefault("name", "UnknownName"); CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion"); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/CryptographyClientImpl.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/CryptographyClientImpl.java index 46684f48ad4a..ac4236b2316f 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/CryptographyClientImpl.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/implementation/CryptographyClientImpl.java @@ -3,11 +3,16 @@ package com.azure.security.keyvault.keys.cryptography.implementation; +import com.azure.core.exception.HttpResponseException; import com.azure.core.http.HttpPipeline; +import com.azure.core.http.rest.RequestOptions; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.BinaryData; import com.azure.core.util.Context; import com.azure.core.util.logging.ClientLogger; +import com.azure.security.keyvault.keys.KeyAsyncClient; +import com.azure.security.keyvault.keys.KeyServiceVersion; import com.azure.security.keyvault.keys.cryptography.CryptographyServiceVersion; import com.azure.security.keyvault.keys.cryptography.models.DecryptParameters; import com.azure.security.keyvault.keys.cryptography.models.DecryptResult; @@ -21,11 +26,12 @@ import com.azure.security.keyvault.keys.cryptography.models.VerifyResult; import com.azure.security.keyvault.keys.cryptography.models.WrapResult; import com.azure.security.keyvault.keys.implementation.KeyClientImpl; -import com.azure.security.keyvault.keys.implementation.KeyVaultKeysUtils; import com.azure.security.keyvault.keys.implementation.SecretMinClientImpl; import com.azure.security.keyvault.keys.implementation.models.KeyBundle; import com.azure.security.keyvault.keys.implementation.models.KeyOperationResult; -import com.azure.security.keyvault.keys.implementation.models.KeyVaultErrorException; +import com.azure.security.keyvault.keys.implementation.models.KeyOperationsParameters; +import com.azure.security.keyvault.keys.implementation.models.KeySignParameters; +import com.azure.security.keyvault.keys.implementation.models.KeyVerifyParameters; import com.azure.security.keyvault.keys.implementation.models.KeyVerifyResult; import com.azure.security.keyvault.keys.implementation.models.SecretKey; import com.azure.security.keyvault.keys.implementation.models.SecretRequestAttributes; @@ -44,7 +50,7 @@ import static com.azure.security.keyvault.keys.cryptography.implementation.CryptographyUtils.mapWrapAlgorithm; import static com.azure.security.keyvault.keys.cryptography.implementation.CryptographyUtils.transformSecretKey; import static com.azure.security.keyvault.keys.cryptography.implementation.CryptographyUtils.unpackAndValidateId; -import static com.azure.security.keyvault.keys.implementation.KeyVaultKeysUtils.callWithMappedException; +import static com.azure.security.keyvault.keys.implementation.KeyVaultKeysUtils.EMPTY_OPTIONS; import static com.azure.security.keyvault.keys.implementation.models.KeyVaultKeysModelsUtils.createKeyVaultKey; public final class CryptographyClientImpl { @@ -72,7 +78,7 @@ public CryptographyClientImpl(String keyId, HttpPipeline pipeline, CryptographyS this.keyId = keyId; - this.keyClient = new KeyClientImpl(pipeline, serviceVersion.getVersion()); + this.keyClient = new KeyClientImpl(pipeline, vaultUrl, KeyServiceVersion.valueOf(serviceVersion.toString())); this.secretClient = new SecretMinClientImpl(pipeline, serviceVersion.getVersion()); } @@ -85,27 +91,21 @@ public String getKeyCollection() { } public Mono> getKeyAsync() { - return keyClient.getKeyWithResponseAsync(vaultUrl, keyName, keyVersion) - .doOnRequest(ignored -> LOGGER.verbose("Retrieving key - {}", keyName)) - .doOnSuccess(response -> LOGGER.verbose("Retrieved key - {}", keyName)) - .doOnError(error -> LOGGER.warning("Failed to get key - {}", keyName, error)) - .onErrorMap(KeyVaultErrorException.class, KeyVaultKeysUtils::mapGetKeyException) - .map(response -> new SimpleResponse<>(response, createKeyVaultKey(response.getValue()))); + return keyClient.getKeyWithResponseAsync(keyName, keyVersion, EMPTY_OPTIONS) + .onErrorMap(HttpResponseException.class, KeyAsyncClient::mapGetKeyException) + .map(response -> new SimpleResponse<>(response, + createKeyVaultKey(response.getValue().toObject(KeyBundle.class)))); } public Response getKey(Context context) { - Response response - = callWithMappedException(() -> keyClient.getKeyWithResponse(vaultUrl, keyName, keyVersion, context), - KeyVaultKeysUtils::mapGetKeyException); + Response response + = keyClient.getKeyWithResponse(keyName, keyVersion, new RequestOptions().setContext(context)); - return new SimpleResponse<>(response, createKeyVaultKey(response.getValue())); + return new SimpleResponse<>(response, createKeyVaultKey(response.getValue().toObject(KeyBundle.class))); } public Mono getSecretKeyAsync() { return withContext(context -> secretClient.getSecretWithResponseAsync(vaultUrl, keyName, keyVersion, context)) - .doOnRequest(ignored -> LOGGER.verbose("Retrieving key - {}", keyName)) - .doOnSuccess(response -> LOGGER.verbose("Retrieved key - {}", response.getValue().getName())) - .doOnError(error -> LOGGER.warning("Failed to get key - {}", keyName, error)) .map(response -> transformSecretKey(response.getValue())); } @@ -117,12 +117,9 @@ public JsonWebKey getSecretKey() { public Mono> setSecretKeyAsync(SecretKey secret, Context context) { Objects.requireNonNull(secret, "The secret key cannot be null."); - return secretClient - .setSecretWithResponseAsync(vaultUrl, secret.getName(), secret.getValue(), secret.getProperties().getTags(), - secret.getProperties().getContentType(), new SecretRequestAttributes(secret.getProperties()), context) - .doOnRequest(ignored -> LOGGER.verbose("Setting secret - {}", secret.getName())) - .doOnSuccess(response -> LOGGER.verbose("Set secret - {}", response.getValue().getName())) - .doOnError(error -> LOGGER.warning("Failed to set secret - {}", secret.getName(), error)); + return secretClient.setSecretWithResponseAsync(vaultUrl, secret.getName(), secret.getValue(), + secret.getProperties().getTags(), secret.getProperties().getContentType(), + new SecretRequestAttributes(secret.getProperties()), context); } public Response setSecretKey(SecretKey secret, Context context) { @@ -149,14 +146,19 @@ public Mono encryptAsync(EncryptParameters encryptParameters, Con private Mono encryptAsync(EncryptionAlgorithm algorithm, byte[] plainText, byte[] iv, byte[] additionalAuthenticatedData, Context context) { + KeyOperationsParameters keyOperationsParameters + = new KeyOperationsParameters(mapKeyEncryptionAlgorithm(algorithm), plainText).setIv(iv) + .setAad(additionalAuthenticatedData); + return keyClient - .encryptAsync(vaultUrl, keyName, keyVersion, mapKeyEncryptionAlgorithm(algorithm), plainText, iv, - additionalAuthenticatedData, null, context) - .doOnRequest(ignored -> LOGGER.verbose("Encrypting content with algorithm - {}", algorithm)) - .doOnSuccess(response -> LOGGER.verbose("Retrieved encrypted content with algorithm - {}", algorithm)) - .doOnError(error -> LOGGER.warning("Failed to encrypt content with algorithm - {}", algorithm, error)) - .map(result -> new EncryptResult(result.getResult(), algorithm, keyId, result.getIv(), - result.getAuthenticationTag(), result.getAdditionalAuthenticatedData())); + .encryptWithResponseAsync(keyName, keyVersion, BinaryData.fromObject(keyOperationsParameters), + new RequestOptions().setContext(context)) + .map(response -> { + KeyOperationResult result = response.getValue().toObject(KeyOperationResult.class); + + return new EncryptResult(result.getResult(), algorithm, keyId, result.getIv(), + result.getAuthenticationTag(), result.getAdditionalAuthenticatedData()); + }); } public EncryptResult encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context) { @@ -175,11 +177,16 @@ public EncryptResult encrypt(EncryptParameters encryptParameters, Context contex private EncryptResult encrypt(EncryptionAlgorithm algorithm, byte[] plainText, byte[] iv, byte[] additionalAuthenticatedData, Context context) { + KeyOperationsParameters keyOperationsParameters + = new KeyOperationsParameters(mapKeyEncryptionAlgorithm(algorithm), plainText).setIv(iv) + .setAad(additionalAuthenticatedData); + KeyOperationResult result = keyClient - .encryptWithResponse(vaultUrl, keyName, keyVersion, mapKeyEncryptionAlgorithm(algorithm), plainText, iv, - additionalAuthenticatedData, null, context) - .getValue(); + .encryptWithResponse(keyName, keyVersion, BinaryData.fromObject(keyOperationsParameters), + new RequestOptions().setContext(context)) + .getValue() + .toObject(KeyOperationResult.class); return new EncryptResult(result.getResult(), algorithm, keyId, result.getIv(), result.getAuthenticationTag(), result.getAdditionalAuthenticatedData()); @@ -202,13 +209,20 @@ public Mono decryptAsync(DecryptParameters decryptParameters, Con private Mono decryptAsync(EncryptionAlgorithm algorithm, byte[] ciphertext, byte[] iv, byte[] additionalAuthenticatedData, byte[] authenticationTag, Context context) { + + KeyOperationsParameters keyOperationsParameters + = new KeyOperationsParameters(mapKeyEncryptionAlgorithm(algorithm), ciphertext).setIv(iv) + .setAad(additionalAuthenticatedData) + .setTag(authenticationTag); + return keyClient - .decryptAsync(vaultUrl, keyName, keyVersion, mapKeyEncryptionAlgorithm(algorithm), ciphertext, iv, - additionalAuthenticatedData, authenticationTag, context) - .map(result -> new DecryptResult(result.getResult(), algorithm, keyId)) - .doOnRequest(ignored -> LOGGER.verbose("Decrypting content with algorithm - {}", algorithm)) - .doOnSuccess(response -> LOGGER.verbose("Retrieved decrypted content with algorithm - {}", algorithm)) - .doOnError(error -> LOGGER.warning("Failed to decrypt content with algorithm - {}", algorithm, error)); + .decryptWithResponseAsync(keyName, keyVersion, BinaryData.fromObject(keyOperationsParameters), + new RequestOptions().setContext(context)) + .map(response -> { + KeyOperationResult result = response.getValue().toObject(KeyOperationResult.class); + + return new DecryptResult(result.getResult(), algorithm, keyId); + }); } public DecryptResult decrypt(EncryptionAlgorithm algorithm, byte[] ciphertext, Context context) { @@ -227,11 +241,18 @@ public DecryptResult decrypt(DecryptParameters decryptParameters, Context contex private DecryptResult decrypt(EncryptionAlgorithm algorithm, byte[] ciphertext, byte[] iv, byte[] additionalAuthenticatedData, byte[] authenticationTag, Context context) { + + KeyOperationsParameters keyOperationsParameters + = new KeyOperationsParameters(mapKeyEncryptionAlgorithm(algorithm), ciphertext).setIv(iv) + .setAad(additionalAuthenticatedData) + .setTag(authenticationTag); + KeyOperationResult result = keyClient - .decryptWithResponse(vaultUrl, keyName, keyVersion, mapKeyEncryptionAlgorithm(algorithm), ciphertext, - iv, additionalAuthenticatedData, authenticationTag, context) - .getValue(); + .decryptWithResponse(keyName, keyVersion, BinaryData.fromObject(keyOperationsParameters), + new RequestOptions().setContext(context)) + .getValue() + .toObject(KeyOperationResult.class); return new DecryptResult(result.getResult(), algorithm, keyId); } @@ -240,20 +261,30 @@ public Mono signAsync(SignatureAlgorithm algorithm, byte[] digest, C Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content cannot be null."); - return keyClient.signAsync(vaultUrl, keyName, keyVersion, mapKeySignatureAlgorithm(algorithm), digest, context) - .map(result -> new SignResult(result.getResult(), algorithm, keyId)) - .doOnRequest(ignored -> LOGGER.verbose("Signing content with algorithm - {}", algorithm)) - .doOnSuccess(response -> LOGGER.verbose("Retrieved signed content with algorithm - {}", algorithm)) - .doOnError(error -> LOGGER.warning("Failed to sign content with algorithm - {}", algorithm, error)); + KeySignParameters keyOperationsParameters = new KeySignParameters(mapKeySignatureAlgorithm(algorithm), digest); + + return keyClient + .signWithResponseAsync(keyName, keyVersion, BinaryData.fromObject(keyOperationsParameters), + new RequestOptions().setContext(context)) + .map(response -> { + KeyOperationResult result = response.getValue().toObject(KeyOperationResult.class); + + return new SignResult(result.getResult(), algorithm, keyId); + }); } public SignResult sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content cannot be null."); - KeyOperationResult result = keyClient - .signWithResponse(vaultUrl, keyName, keyVersion, mapKeySignatureAlgorithm(algorithm), digest, context) - .getValue(); + KeySignParameters keyOperationsParameters = new KeySignParameters(mapKeySignatureAlgorithm(algorithm), digest); + + KeyOperationResult result + = keyClient + .signWithResponse(keyName, keyVersion, BinaryData.fromObject(keyOperationsParameters), + new RequestOptions().setContext(context)) + .getValue() + .toObject(KeyOperationResult.class); return new SignResult(result.getResult(), algorithm, keyId); } @@ -264,12 +295,17 @@ public Mono verifyAsync(SignatureAlgorithm algorithm, byte[] diges Objects.requireNonNull(digest, "Digest content cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); + KeyVerifyParameters keyVerifyParameters + = new KeyVerifyParameters(mapKeySignatureAlgorithm(algorithm), digest, signature); + return keyClient - .verifyAsync(vaultUrl, keyName, keyVersion, mapKeySignatureAlgorithm(algorithm), digest, signature, context) - .map(result -> new VerifyResult(result.isValue(), algorithm, keyId)) - .doOnRequest(ignored -> LOGGER.verbose("Verifying content with algorithm - {}", algorithm)) - .doOnSuccess(response -> LOGGER.verbose("Retrieved verified content with algorithm - {}", algorithm)) - .doOnError(error -> LOGGER.warning("Failed to verify content with algorithm - {}", algorithm, error)); + .verifyWithResponseAsync(keyName, keyVersion, BinaryData.fromObject(keyVerifyParameters), + new RequestOptions().setContext(context)) + .map(response -> { + KeyVerifyResult result = response.getValue().toObject(KeyVerifyResult.class); + + return new VerifyResult(result.isValue(), algorithm, keyId); + }); } public VerifyResult verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { @@ -277,11 +313,15 @@ public VerifyResult verify(SignatureAlgorithm algorithm, byte[] digest, byte[] s Objects.requireNonNull(digest, "Digest content cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); + KeyVerifyParameters keyVerifyParameters + = new KeyVerifyParameters(mapKeySignatureAlgorithm(algorithm), digest, signature); + KeyVerifyResult result = keyClient - .verifyWithResponse(vaultUrl, keyName, keyVersion, mapKeySignatureAlgorithm(algorithm), digest, - signature, context) - .getValue(); + .verifyWithResponse(keyName, keyVersion, BinaryData.fromObject(keyVerifyParameters), + new RequestOptions().setContext(context)) + .getValue() + .toObject(KeyVerifyResult.class); return new VerifyResult(result.isValue(), algorithm, keyId); } @@ -290,23 +330,30 @@ public Mono wrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] key, Con Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); Objects.requireNonNull(key, "Key content to be wrapped cannot be null."); + KeyOperationsParameters keyOperationsParameters = new KeyOperationsParameters(mapWrapAlgorithm(algorithm), key); + return keyClient - .wrapKeyAsync(vaultUrl, keyName, keyVersion, mapWrapAlgorithm(algorithm), key, null, null, null, context) - .map(result -> new WrapResult(result.getResult(), algorithm, keyId)) - .doOnRequest(ignored -> LOGGER.verbose("Wrapping key content with algorithm - {}", algorithm)) - .doOnSuccess(response -> LOGGER.verbose("Retrieved wrapped key content with algorithm - {}", algorithm)) - .doOnError(error -> LOGGER.warning("Failed to verify content with algorithm - {}", algorithm, error)); + .wrapKeyWithResponseAsync(keyName, keyVersion, BinaryData.fromObject(keyOperationsParameters), + new RequestOptions().setContext(context)) + .map(response -> { + KeyOperationResult result = response.getValue().toObject(KeyOperationResult.class); + + return new WrapResult(result.getResult(), algorithm, keyId); + }); } public WrapResult wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); Objects.requireNonNull(key, "Key content to be wrapped cannot be null."); + KeyOperationsParameters keyOperationsParameters = new KeyOperationsParameters(mapWrapAlgorithm(algorithm), key); + KeyOperationResult result = keyClient - .wrapKeyWithResponse(vaultUrl, keyName, keyVersion, mapWrapAlgorithm(algorithm), key, null, null, null, - context) - .getValue(); + .wrapKeyWithResponse(keyName, keyVersion, BinaryData.fromObject(keyOperationsParameters), + new RequestOptions().setContext(context)) + .getValue() + .toObject(KeyOperationResult.class); return new WrapResult(result.getResult(), algorithm, keyId); } @@ -315,23 +362,32 @@ public Mono unwrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] encr Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); + KeyOperationsParameters keyOperationsParameters + = new KeyOperationsParameters(mapWrapAlgorithm(algorithm), encryptedKey); + return keyClient - .unwrapKeyAsync(vaultUrl, keyName, keyVersion, mapWrapAlgorithm(algorithm), encryptedKey, null, null, null, - context) - .map(result -> new UnwrapResult(result.getResult(), algorithm, keyId)) - .doOnRequest(ignored -> LOGGER.verbose("Unwrapping key content with algorithm - {}", algorithm)) - .doOnSuccess(response -> LOGGER.verbose("Retrieved unwrapped key content with algorithm - {}", algorithm)) - .doOnError(error -> LOGGER.warning("Failed to unwrap key content with algorithm - {}", algorithm, error)); + .unwrapKeyWithResponseAsync(keyName, keyVersion, BinaryData.fromObject(keyOperationsParameters), + new RequestOptions().setContext(context)) + .map(response -> { + KeyOperationResult result = response.getValue().toObject(KeyOperationResult.class); + + return new UnwrapResult(result.getResult(), algorithm, keyId); + }); } public UnwrapResult unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm, "Key wrap algorithm cannot be null."); Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); - KeyOperationResult result = keyClient - .unwrapKeyWithResponse(vaultUrl, keyName, keyVersion, mapWrapAlgorithm(algorithm), encryptedKey, null, null, - null, context) - .getValue(); + KeyOperationsParameters keyOperationsParameters + = new KeyOperationsParameters(mapWrapAlgorithm(algorithm), encryptedKey); + + KeyOperationResult result + = keyClient + .unwrapKeyWithResponse(keyName, keyVersion, BinaryData.fromObject(keyOperationsParameters), + new RequestOptions().setContext(context)) + .getValue() + .toObject(KeyOperationResult.class); return new UnwrapResult(result.getResult(), algorithm, keyId); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyClientImpl.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyClientImpl.java index 2f370bbc639a..b7a8d62d50fb 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyClientImpl.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyClientImpl.java @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.implementation; import com.azure.core.annotation.BodyParam; @@ -20,6 +19,10 @@ import com.azure.core.annotation.ServiceInterface; import com.azure.core.annotation.ServiceMethod; import com.azure.core.annotation.UnexpectedResponseExceptionType; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; import com.azure.core.http.HttpPipeline; import com.azure.core.http.HttpPipelineBuilder; import com.azure.core.http.policy.RetryPolicy; @@ -28,68 +31,55 @@ import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.PagedResponse; import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.RequestOptions; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.RestProxy; +import com.azure.core.util.BinaryData; import com.azure.core.util.Context; import com.azure.core.util.FluxUtil; import com.azure.core.util.serializer.JacksonAdapter; import com.azure.core.util.serializer.SerializerAdapter; -import com.azure.security.keyvault.keys.implementation.models.BackupKeyResult; -import com.azure.security.keyvault.keys.implementation.models.DeletedKeyBundle; -import com.azure.security.keyvault.keys.implementation.models.DeletedKeyItem; -import com.azure.security.keyvault.keys.implementation.models.DeletedKeyListResult; -import com.azure.security.keyvault.keys.implementation.models.GetRandomBytesRequest; -import com.azure.security.keyvault.keys.implementation.models.JsonWebKey; -import com.azure.security.keyvault.keys.implementation.models.JsonWebKeyEncryptionAlgorithm; -import com.azure.security.keyvault.keys.implementation.models.JsonWebKeySignatureAlgorithm; -import com.azure.security.keyvault.keys.implementation.models.KeyAttributes; -import com.azure.security.keyvault.keys.implementation.models.KeyBundle; -import com.azure.security.keyvault.keys.implementation.models.KeyCreateParameters; -import com.azure.security.keyvault.keys.implementation.models.KeyImportParameters; -import com.azure.security.keyvault.keys.implementation.models.KeyItem; -import com.azure.security.keyvault.keys.implementation.models.KeyListResult; -import com.azure.security.keyvault.keys.implementation.models.KeyOperationResult; -import com.azure.security.keyvault.keys.implementation.models.KeyOperationsParameters; -import com.azure.security.keyvault.keys.implementation.models.KeyReleaseParameters; -import com.azure.security.keyvault.keys.implementation.models.KeyReleasePolicy; -import com.azure.security.keyvault.keys.implementation.models.KeyRestoreParameters; -import com.azure.security.keyvault.keys.implementation.models.KeyRotationPolicy; -import com.azure.security.keyvault.keys.implementation.models.KeySignParameters; -import com.azure.security.keyvault.keys.implementation.models.KeyUpdateParameters; -import com.azure.security.keyvault.keys.implementation.models.KeyVaultErrorException; -import com.azure.security.keyvault.keys.implementation.models.KeyVerifyParameters; -import com.azure.security.keyvault.keys.implementation.models.KeyVerifyResult; -import com.azure.security.keyvault.keys.implementation.models.RandomBytes; -import com.azure.security.keyvault.keys.models.KeyCurveName; -import com.azure.security.keyvault.keys.models.KeyExportEncryptionAlgorithm; -import com.azure.security.keyvault.keys.models.KeyOperation; -import com.azure.security.keyvault.keys.models.KeyType; -import com.azure.security.keyvault.keys.models.ReleaseKeyResult; +import com.azure.security.keyvault.keys.KeyServiceVersion; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; import reactor.core.publisher.Mono; /** * Initializes a new instance of the KeyClient type. */ public final class KeyClientImpl { + /** * The proxy service used to perform REST calls. */ private final KeyClientService service; /** - * Api Version. */ - private final String apiVersion; + private final String vaultBaseUrl; /** - * Gets Api Version. - * - * @return the apiVersion value. + * Gets. + * + * @return the vaultBaseUrl value. + */ + public String getVaultBaseUrl() { + return this.vaultBaseUrl; + } + + /** + * Service version. + */ + private final KeyServiceVersion serviceVersion; + + /** + * Gets Service version. + * + * @return the serviceVersion value. */ - public String getApiVersion() { - return this.apiVersion; + public KeyServiceVersion getServiceVersion() { + return this.serviceVersion; } /** @@ -99,7 +89,7 @@ public String getApiVersion() { /** * Gets The HTTP pipeline to send requests through. - * + * * @return the httpPipeline value. */ public HttpPipeline getHttpPipeline() { @@ -113,7 +103,7 @@ public HttpPipeline getHttpPipeline() { /** * Gets The serializer to serialize an object into a string. - * + * * @return the serializerAdapter value. */ public SerializerAdapter getSerializerAdapter() { @@ -122,35 +112,40 @@ public SerializerAdapter getSerializerAdapter() { /** * Initializes an instance of KeyClient client. - * - * @param apiVersion Api Version. + * + * @param vaultBaseUrl + * @param serviceVersion Service version. */ - public KeyClientImpl(String apiVersion) { + public KeyClientImpl(String vaultBaseUrl, KeyServiceVersion serviceVersion) { this(new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build(), - JacksonAdapter.createDefaultSerializerAdapter(), apiVersion); + JacksonAdapter.createDefaultSerializerAdapter(), vaultBaseUrl, serviceVersion); } /** * Initializes an instance of KeyClient client. - * + * * @param httpPipeline The HTTP pipeline to send requests through. - * @param apiVersion Api Version. + * @param vaultBaseUrl + * @param serviceVersion Service version. */ - public KeyClientImpl(HttpPipeline httpPipeline, String apiVersion) { - this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), apiVersion); + public KeyClientImpl(HttpPipeline httpPipeline, String vaultBaseUrl, KeyServiceVersion serviceVersion) { + this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), vaultBaseUrl, serviceVersion); } /** * Initializes an instance of KeyClient client. - * + * * @param httpPipeline The HTTP pipeline to send requests through. * @param serializerAdapter The serializer to serialize an object into a string. - * @param apiVersion Api Version. + * @param vaultBaseUrl + * @param serviceVersion Service version. */ - public KeyClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String apiVersion) { + public KeyClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String vaultBaseUrl, + KeyServiceVersion serviceVersion) { this.httpPipeline = httpPipeline; this.serializerAdapter = serializerAdapter; - this.apiVersion = apiVersion; + this.vaultBaseUrl = vaultBaseUrl; + this.serviceVersion = serviceVersion; this.service = RestProxy.create(KeyClientService.class, this.httpPipeline, this.getSerializerAdapter()); } @@ -160,1733 +155,2153 @@ public KeyClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdap @Host("{vaultBaseUrl}") @ServiceInterface(name = "KeyClient") public interface KeyClientService { + @Post("/keys/{key-name}/create") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> createKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyCreateParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> createKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData parameters, RequestOptions requestOptions, Context context); @Post("/keys/{key-name}/create") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response createKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyCreateParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response createKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData parameters, RequestOptions requestOptions, Context context); @Post("/keys/{key-name}/rotate") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> rotateKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> rotateKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Post("/keys/{key-name}/rotate") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response rotateKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response rotateKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Put("/keys/{key-name}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> importKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyImportParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> importKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData parameters, RequestOptions requestOptions, Context context); @Put("/keys/{key-name}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response importKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyImportParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response importKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData parameters, RequestOptions requestOptions, Context context); @Delete("/keys/{key-name}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> deleteKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> deleteKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Delete("/keys/{key-name}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response deleteKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response deleteKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Patch("/keys/{key-name}/{key-version}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> updateKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, @BodyParam("application/json") KeyUpdateParameters parameters, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> updateKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @PathParam("key-version") String keyVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Patch("/keys/{key-name}/{key-version}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response updateKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, @BodyParam("application/json") KeyUpdateParameters parameters, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response updateKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @PathParam("key-version") String keyVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Get("/keys/{key-name}/{key-version}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @PathParam("key-version") String keyVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("/keys/{key-name}/{key-version}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @PathParam("key-version") String keyVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("/keys/{key-name}/versions") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getKeyVersions(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("maxresults") Integer maxresults, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getKeyVersions(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Get("/keys/{key-name}/versions") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getKeyVersionsSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("maxresults") Integer maxresults, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getKeyVersionsSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Get("/keys") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getKeys(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("maxresults") Integer maxresults, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getKeys(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("/keys") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getKeysSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("maxresults") Integer maxresults, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getKeysSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Post("/keys/{key-name}/backup") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> backupKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> backupKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Post("/keys/{key-name}/backup") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response backupKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response backupKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Post("/keys/restore") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> restoreKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyRestoreParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> restoreKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Post("/keys/restore") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response restoreKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyRestoreParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response restoreKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Post("/keys/{key-name}/{key-version}/encrypt") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> encrypt(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyOperationsParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> encrypt(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @PathParam("key-version") String keyVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Post("/keys/{key-name}/{key-version}/encrypt") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response encryptSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyOperationsParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response encryptSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @PathParam("key-version") String keyVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Post("/keys/{key-name}/{key-version}/decrypt") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> decrypt(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyOperationsParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> decrypt(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @PathParam("key-version") String keyVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Post("/keys/{key-name}/{key-version}/decrypt") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response decryptSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyOperationsParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response decryptSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @PathParam("key-version") String keyVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Post("/keys/{key-name}/{key-version}/sign") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> sign(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, @BodyParam("application/json") KeySignParameters parameters, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> sign(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @PathParam("key-version") String keyVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Post("/keys/{key-name}/{key-version}/sign") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response signSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, @BodyParam("application/json") KeySignParameters parameters, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response signSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @PathParam("key-version") String keyVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Post("/keys/{key-name}/{key-version}/verify") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> verify(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, @BodyParam("application/json") KeyVerifyParameters parameters, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> verify(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @PathParam("key-version") String keyVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Post("/keys/{key-name}/{key-version}/verify") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response verifySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, @BodyParam("application/json") KeyVerifyParameters parameters, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response verifySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @PathParam("key-version") String keyVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Post("/keys/{key-name}/{key-version}/wrapkey") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> wrapKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyOperationsParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> wrapKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @PathParam("key-version") String keyVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Post("/keys/{key-name}/{key-version}/wrapkey") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response wrapKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyOperationsParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response wrapKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @PathParam("key-version") String keyVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Post("/keys/{key-name}/{key-version}/unwrapkey") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> unwrapKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyOperationsParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> unwrapKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @PathParam("key-version") String keyVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Post("/keys/{key-name}/{key-version}/unwrapkey") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response unwrapKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyOperationsParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response unwrapKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @PathParam("key-version") String keyVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Post("/keys/{key-name}/{key-version}/release") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> release(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyReleaseParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> release(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @PathParam("key-version") String keyVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Post("/keys/{key-name}/{key-version}/release") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response releaseSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @PathParam("key-version") String keyVersion, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyReleaseParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response releaseSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @PathParam("key-version") String keyVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Get("/deletedkeys") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getDeletedKeys(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("maxresults") Integer maxresults, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getDeletedKeys(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("/deletedkeys") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getDeletedKeysSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("maxresults") Integer maxresults, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getDeletedKeysSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("/deletedkeys/{key-name}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getDeletedKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getDeletedKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Get("/deletedkeys/{key-name}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getDeletedKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getDeletedKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Delete("/deletedkeys/{key-name}") @ExpectedResponses({ 204 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) Mono> purgeDeletedKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Delete("/deletedkeys/{key-name}") @ExpectedResponses({ 204 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) Response purgeDeletedKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Post("/deletedkeys/{key-name}/recover") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> recoverDeletedKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> recoverDeletedKey(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Post("/deletedkeys/{key-name}/recover") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response recoverDeletedKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response recoverDeletedKeySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Get("/keys/{key-name}/rotationpolicy") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getKeyRotationPolicy(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getKeyRotationPolicy(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Get("/keys/{key-name}/rotationpolicy") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getKeyRotationPolicySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getKeyRotationPolicySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Put("/keys/{key-name}/rotationpolicy") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> updateKeyRotationPolicy(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyRotationPolicy keyRotationPolicy, @HeaderParam("Accept") String accept, + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> updateKeyRotationPolicy(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData keyRotationPolicy, RequestOptions requestOptions, Context context); @Put("/keys/{key-name}/rotationpolicy") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response updateKeyRotationPolicySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("key-name") String keyName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") KeyRotationPolicy keyRotationPolicy, @HeaderParam("Accept") String accept, + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response updateKeyRotationPolicySync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("key-name") String keyName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData keyRotationPolicy, RequestOptions requestOptions, Context context); @Post("/rng") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getRandomBytes(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") GetRandomBytesRequest parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getRandomBytes(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Post("/rng") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getRandomBytesSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") GetRandomBytesRequest parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getRandomBytesSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Get("{nextLink}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getKeyVersionsNext(@PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getKeyVersionsNext(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("{nextLink}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getKeyVersionsNextSync(@PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getKeyVersionsNextSync(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("{nextLink}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getKeysNext(@PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getKeysNext(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("{nextLink}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getKeysNextSync(@PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getKeysNextSync(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("{nextLink}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getDeletedKeysNext( - @PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getDeletedKeysNext(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("{nextLink}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getDeletedKeysNextSync( - @PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); - } - - /** - * Creates a new key, stores it, then returns key parameters and attributes to the client. - * - * The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, - * Azure Key Vault creates a new version of the key. It requires the keys/create permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name for the new key. The system will generate the version name for the new key. The value you - * provide may be copied globally for the purpose of running the service. The value provided should not include - * personally identifiable or sensitive information. - * @param kty JsonWebKey Key Type (kty), as defined in - * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - * @param keySize The key size in bits. For example: 2048, 3072, or 4096 for RSA. - * @param publicExponent The public exponent for a RSA key. - * @param keyOps The keyOps parameter. - * @param keyAttributes The attributes of a key managed by the key vault service. - * @param tags Application specific metadata in the form of key-value pairs. - * @param crv Elliptic curve name. - * @param releasePolicy The policy rules under which the key can be exported. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createKeyWithResponseAsync(String vaultBaseUrl, String keyName, KeyType kty, - Integer keySize, Integer publicExponent, List keyOps, KeyAttributes keyAttributes, - Map tags, KeyCurveName crv, KeyReleasePolicy releasePolicy) { - return FluxUtil.withContext(context -> createKeyWithResponseAsync(vaultBaseUrl, keyName, kty, keySize, - publicExponent, keyOps, keyAttributes, tags, crv, releasePolicy, context)); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getDeletedKeysNextSync(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); } /** * Creates a new key, stores it, then returns key parameters and attributes to the client. - * + * * The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, * Azure Key Vault creates a new version of the key. It requires the keys/create permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Required)
          +     *     key_size: Integer (Optional)
          +     *     public_exponent: Integer (Optional)
          +     *     key_ops (Optional): [
          +     *         String(encrypt/decrypt/sign/verify/wrapKey/unwrapKey/import/export) (Optional)
          +     *     ]
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *     release_policy (Optional): {
          +     *         contentType: String (Optional)
          +     *         immutable: Boolean (Optional)
          +     *         data: Base64Url (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     key (Optional): {
          +     *         kid: String (Optional)
          +     *         kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *         key_ops (Optional): [
          +     *             String (Optional)
          +     *         ]
          +     *         n: Base64Url (Optional)
          +     *         e: Base64Url (Optional)
          +     *         d: Base64Url (Optional)
          +     *         dp: Base64Url (Optional)
          +     *         dq: Base64Url (Optional)
          +     *         qi: Base64Url (Optional)
          +     *         p: Base64Url (Optional)
          +     *         q: Base64Url (Optional)
          +     *         k: Base64Url (Optional)
          +     *         key_hsm: Base64Url (Optional)
          +     *         crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         x: Base64Url (Optional)
          +     *         y: Base64Url (Optional)
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     *     release_policy (Optional): {
          +     *         contentType: String (Optional)
          +     *         immutable: Boolean (Optional)
          +     *         data: Base64Url (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * * @param keyName The name for the new key. The system will generate the version name for the new key. The value you * provide may be copied globally for the purpose of running the service. The value provided should not include * personally identifiable or sensitive information. - * @param kty JsonWebKey Key Type (kty), as defined in - * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - * @param keySize The key size in bits. For example: 2048, 3072, or 4096 for RSA. - * @param publicExponent The public exponent for a RSA key. - * @param keyOps The keyOps parameter. - * @param keyAttributes The attributes of a key managed by the key vault service. - * @param tags Application specific metadata in the form of key-value pairs. - * @param crv Elliptic curve name. - * @param releasePolicy The policy rules under which the key can be exported. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param parameters The parameters to create a key. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response} on successful * completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createKeyWithResponseAsync(String vaultBaseUrl, String keyName, KeyType kty, - Integer keySize, Integer publicExponent, List keyOps, KeyAttributes keyAttributes, - Map tags, KeyCurveName crv, KeyReleasePolicy releasePolicy, Context context) { + public Mono> createKeyWithResponseAsync(String keyName, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - KeyCreateParameters parameters = new KeyCreateParameters(); - parameters.setKty(kty); - parameters.setKeySize(keySize); - parameters.setPublicExponent(publicExponent); - parameters.setKeyOps(keyOps); - parameters.setKeyAttributes(keyAttributes); - parameters.setTags(tags); - parameters.setCrv(crv); - parameters.setReleasePolicy(releasePolicy); - return service.createKey(vaultBaseUrl, keyName, this.getApiVersion(), parameters, accept, context); - } - - /** - * Creates a new key, stores it, then returns key parameters and attributes to the client. - * - * The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, - * Azure Key Vault creates a new version of the key. It requires the keys/create permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name for the new key. The system will generate the version name for the new key. The value you - * provide may be copied globally for the purpose of running the service. The value provided should not include - * personally identifiable or sensitive information. - * @param kty JsonWebKey Key Type (kty), as defined in - * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - * @param keySize The key size in bits. For example: 2048, 3072, or 4096 for RSA. - * @param publicExponent The public exponent for a RSA key. - * @param keyOps The keyOps parameter. - * @param keyAttributes The attributes of a key managed by the key vault service. - * @param tags Application specific metadata in the form of key-value pairs. - * @param crv Elliptic curve name. - * @param releasePolicy The policy rules under which the key can be exported. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createKeyAsync(String vaultBaseUrl, String keyName, KeyType kty, Integer keySize, - Integer publicExponent, List keyOps, KeyAttributes keyAttributes, Map tags, - KeyCurveName crv, KeyReleasePolicy releasePolicy) { - return createKeyWithResponseAsync(vaultBaseUrl, keyName, kty, keySize, publicExponent, keyOps, keyAttributes, - tags, crv, releasePolicy).flatMap(res -> Mono.justOrEmpty(res.getValue())); + return FluxUtil.withContext(context -> service.createKey(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), keyName, contentType, accept, parameters, requestOptions, context)); } /** * Creates a new key, stores it, then returns key parameters and attributes to the client. - * - * The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, - * Azure Key Vault creates a new version of the key. It requires the keys/create permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name for the new key. The system will generate the version name for the new key. The value you - * provide may be copied globally for the purpose of running the service. The value provided should not include - * personally identifiable or sensitive information. - * @param kty JsonWebKey Key Type (kty), as defined in - * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - * @param keySize The key size in bits. For example: 2048, 3072, or 4096 for RSA. - * @param publicExponent The public exponent for a RSA key. - * @param keyOps The keyOps parameter. - * @param keyAttributes The attributes of a key managed by the key vault service. - * @param tags Application specific metadata in the form of key-value pairs. - * @param crv Elliptic curve name. - * @param releasePolicy The policy rules under which the key can be exported. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createKeyAsync(String vaultBaseUrl, String keyName, KeyType kty, Integer keySize, - Integer publicExponent, List keyOps, KeyAttributes keyAttributes, Map tags, - KeyCurveName crv, KeyReleasePolicy releasePolicy, Context context) { - return createKeyWithResponseAsync(vaultBaseUrl, keyName, kty, keySize, publicExponent, keyOps, keyAttributes, - tags, crv, releasePolicy, context).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new key, stores it, then returns key parameters and attributes to the client. - * + * * The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, * Azure Key Vault creates a new version of the key. It requires the keys/create permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Required)
          +     *     key_size: Integer (Optional)
          +     *     public_exponent: Integer (Optional)
          +     *     key_ops (Optional): [
          +     *         String(encrypt/decrypt/sign/verify/wrapKey/unwrapKey/import/export) (Optional)
          +     *     ]
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *     release_policy (Optional): {
          +     *         contentType: String (Optional)
          +     *         immutable: Boolean (Optional)
          +     *         data: Base64Url (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     key (Optional): {
          +     *         kid: String (Optional)
          +     *         kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *         key_ops (Optional): [
          +     *             String (Optional)
          +     *         ]
          +     *         n: Base64Url (Optional)
          +     *         e: Base64Url (Optional)
          +     *         d: Base64Url (Optional)
          +     *         dp: Base64Url (Optional)
          +     *         dq: Base64Url (Optional)
          +     *         qi: Base64Url (Optional)
          +     *         p: Base64Url (Optional)
          +     *         q: Base64Url (Optional)
          +     *         k: Base64Url (Optional)
          +     *         key_hsm: Base64Url (Optional)
          +     *         crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         x: Base64Url (Optional)
          +     *         y: Base64Url (Optional)
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     *     release_policy (Optional): {
          +     *         contentType: String (Optional)
          +     *         immutable: Boolean (Optional)
          +     *         data: Base64Url (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * * @param keyName The name for the new key. The system will generate the version name for the new key. The value you * provide may be copied globally for the purpose of running the service. The value provided should not include * personally identifiable or sensitive information. - * @param kty JsonWebKey Key Type (kty), as defined in - * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - * @param keySize The key size in bits. For example: 2048, 3072, or 4096 for RSA. - * @param publicExponent The public exponent for a RSA key. - * @param keyOps The keyOps parameter. - * @param keyAttributes The attributes of a key managed by the key vault service. - * @param tags Application specific metadata in the form of key-value pairs. - * @param crv Elliptic curve name. - * @param releasePolicy The policy rules under which the key can be exported. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param parameters The parameters to create a key. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response createKeyWithResponse(String vaultBaseUrl, String keyName, KeyType kty, Integer keySize, - Integer publicExponent, List keyOps, KeyAttributes keyAttributes, Map tags, - KeyCurveName crv, KeyReleasePolicy releasePolicy, Context context) { + public Response createKeyWithResponse(String keyName, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - KeyCreateParameters parameters = new KeyCreateParameters(); - parameters.setKty(kty); - parameters.setKeySize(keySize); - parameters.setPublicExponent(publicExponent); - parameters.setKeyOps(keyOps); - parameters.setKeyAttributes(keyAttributes); - parameters.setTags(tags); - parameters.setCrv(crv); - parameters.setReleasePolicy(releasePolicy); - return service.createKeySync(vaultBaseUrl, keyName, this.getApiVersion(), parameters, accept, context); - } - - /** - * Creates a new key, stores it, then returns key parameters and attributes to the client. - * - * The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, - * Azure Key Vault creates a new version of the key. It requires the keys/create permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name for the new key. The system will generate the version name for the new key. The value you - * provide may be copied globally for the purpose of running the service. The value provided should not include - * personally identifiable or sensitive information. - * @param kty JsonWebKey Key Type (kty), as defined in - * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - * @param keySize The key size in bits. For example: 2048, 3072, or 4096 for RSA. - * @param publicExponent The public exponent for a RSA key. - * @param keyOps The keyOps parameter. - * @param keyAttributes The attributes of a key managed by the key vault service. - * @param tags Application specific metadata in the form of key-value pairs. - * @param crv Elliptic curve name. - * @param releasePolicy The policy rules under which the key can be exported. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyBundle createKey(String vaultBaseUrl, String keyName, KeyType kty, Integer keySize, - Integer publicExponent, List keyOps, KeyAttributes keyAttributes, Map tags, - KeyCurveName crv, KeyReleasePolicy releasePolicy) { - return createKeyWithResponse(vaultBaseUrl, keyName, kty, keySize, publicExponent, keyOps, keyAttributes, tags, - crv, releasePolicy, Context.NONE).getValue(); - } - - /** - * Creates a new key version, stores it, then returns key parameters, attributes and policy to the client. - * - * The operation will rotate the key based on the key policy. It requires the keys/rotate permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of key to be rotated. The system will generate a new version in the specified key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> rotateKeyWithResponseAsync(String vaultBaseUrl, String keyName) { - return FluxUtil.withContext(context -> rotateKeyWithResponseAsync(vaultBaseUrl, keyName, context)); + return service.createKeySync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), keyName, + contentType, accept, parameters, requestOptions, Context.NONE); } /** * Creates a new key version, stores it, then returns key parameters, attributes and policy to the client. - * + * * The operation will rotate the key based on the key policy. It requires the keys/rotate permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     key (Optional): {
          +     *         kid: String (Optional)
          +     *         kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *         key_ops (Optional): [
          +     *             String (Optional)
          +     *         ]
          +     *         n: Base64Url (Optional)
          +     *         e: Base64Url (Optional)
          +     *         d: Base64Url (Optional)
          +     *         dp: Base64Url (Optional)
          +     *         dq: Base64Url (Optional)
          +     *         qi: Base64Url (Optional)
          +     *         p: Base64Url (Optional)
          +     *         q: Base64Url (Optional)
          +     *         k: Base64Url (Optional)
          +     *         key_hsm: Base64Url (Optional)
          +     *         crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         x: Base64Url (Optional)
          +     *         y: Base64Url (Optional)
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     *     release_policy (Optional): {
          +     *         contentType: String (Optional)
          +     *         immutable: Boolean (Optional)
          +     *         data: Base64Url (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * * @param keyName The name of key to be rotated. The system will generate a new version in the specified key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response} on successful * completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> rotateKeyWithResponseAsync(String vaultBaseUrl, String keyName, Context context) { + public Mono> rotateKeyWithResponseAsync(String keyName, RequestOptions requestOptions) { final String accept = "application/json"; - return service.rotateKey(vaultBaseUrl, keyName, this.getApiVersion(), accept, context); - } - - /** - * Creates a new key version, stores it, then returns key parameters, attributes and policy to the client. - * - * The operation will rotate the key based on the key policy. It requires the keys/rotate permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of key to be rotated. The system will generate a new version in the specified key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono rotateKeyAsync(String vaultBaseUrl, String keyName) { - return rotateKeyWithResponseAsync(vaultBaseUrl, keyName).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new key version, stores it, then returns key parameters, attributes and policy to the client. - * - * The operation will rotate the key based on the key policy. It requires the keys/rotate permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of key to be rotated. The system will generate a new version in the specified key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono rotateKeyAsync(String vaultBaseUrl, String keyName, Context context) { - return rotateKeyWithResponseAsync(vaultBaseUrl, keyName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + return FluxUtil.withContext(context -> service.rotateKey(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), keyName, accept, requestOptions, context)); } /** * Creates a new key version, stores it, then returns key parameters, attributes and policy to the client. - * + * * The operation will rotate the key based on the key policy. It requires the keys/rotate permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     key (Optional): {
          +     *         kid: String (Optional)
          +     *         kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *         key_ops (Optional): [
          +     *             String (Optional)
          +     *         ]
          +     *         n: Base64Url (Optional)
          +     *         e: Base64Url (Optional)
          +     *         d: Base64Url (Optional)
          +     *         dp: Base64Url (Optional)
          +     *         dq: Base64Url (Optional)
          +     *         qi: Base64Url (Optional)
          +     *         p: Base64Url (Optional)
          +     *         q: Base64Url (Optional)
          +     *         k: Base64Url (Optional)
          +     *         key_hsm: Base64Url (Optional)
          +     *         crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         x: Base64Url (Optional)
          +     *         y: Base64Url (Optional)
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     *     release_policy (Optional): {
          +     *         contentType: String (Optional)
          +     *         immutable: Boolean (Optional)
          +     *         data: Base64Url (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * * @param keyName The name of key to be rotated. The system will generate a new version in the specified key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response rotateKeyWithResponse(String vaultBaseUrl, String keyName, Context context) { + public Response rotateKeyWithResponse(String keyName, RequestOptions requestOptions) { final String accept = "application/json"; - return service.rotateKeySync(vaultBaseUrl, keyName, this.getApiVersion(), accept, context); - } - - /** - * Creates a new key version, stores it, then returns key parameters, attributes and policy to the client. - * - * The operation will rotate the key based on the key policy. It requires the keys/rotate permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of key to be rotated. The system will generate a new version in the specified key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyBundle rotateKey(String vaultBaseUrl, String keyName) { - return rotateKeyWithResponse(vaultBaseUrl, keyName, Context.NONE).getValue(); - } - - /** - * Imports an externally created key, stores it, and returns key parameters and attributes to the client. - * - * The import key operation may be used to import any key type into an Azure Key Vault. If the named key already - * exists, Azure Key Vault creates a new version of the key. This operation requires the keys/import permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName Name for the imported key. The value you provide may be copied globally for the purpose of running - * the service. The value provided should not include personally identifiable or sensitive information. - * @param key The Json web key. - * @param hsm Whether to import as a hardware key (HSM) or software key. - * @param keyAttributes The key management attributes. - * @param tags Application specific metadata in the form of key-value pairs. - * @param releasePolicy The policy rules under which the key can be exported. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> importKeyWithResponseAsync(String vaultBaseUrl, String keyName, JsonWebKey key, - Boolean hsm, KeyAttributes keyAttributes, Map tags, KeyReleasePolicy releasePolicy) { - return FluxUtil.withContext(context -> importKeyWithResponseAsync(vaultBaseUrl, keyName, key, hsm, - keyAttributes, tags, releasePolicy, context)); + return service.rotateKeySync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), keyName, accept, + requestOptions, Context.NONE); } /** * Imports an externally created key, stores it, and returns key parameters and attributes to the client. - * + * * The import key operation may be used to import any key type into an Azure Key Vault. If the named key already * exists, Azure Key Vault creates a new version of the key. This operation requires the keys/import permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     Hsm: Boolean (Optional)
          +     *     key (Required): {
          +     *         kid: String (Optional)
          +     *         kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *         key_ops (Optional): [
          +     *             String (Optional)
          +     *         ]
          +     *         n: Base64Url (Optional)
          +     *         e: Base64Url (Optional)
          +     *         d: Base64Url (Optional)
          +     *         dp: Base64Url (Optional)
          +     *         dq: Base64Url (Optional)
          +     *         qi: Base64Url (Optional)
          +     *         p: Base64Url (Optional)
          +     *         q: Base64Url (Optional)
          +     *         k: Base64Url (Optional)
          +     *         key_hsm: Base64Url (Optional)
          +     *         crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         x: Base64Url (Optional)
          +     *         y: Base64Url (Optional)
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     release_policy (Optional): {
          +     *         contentType: String (Optional)
          +     *         immutable: Boolean (Optional)
          +     *         data: Base64Url (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     key (Optional): {
          +     *         kid: String (Optional)
          +     *         kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *         key_ops (Optional): [
          +     *             String (Optional)
          +     *         ]
          +     *         n: Base64Url (Optional)
          +     *         e: Base64Url (Optional)
          +     *         d: Base64Url (Optional)
          +     *         dp: Base64Url (Optional)
          +     *         dq: Base64Url (Optional)
          +     *         qi: Base64Url (Optional)
          +     *         p: Base64Url (Optional)
          +     *         q: Base64Url (Optional)
          +     *         k: Base64Url (Optional)
          +     *         key_hsm: Base64Url (Optional)
          +     *         crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         x: Base64Url (Optional)
          +     *         y: Base64Url (Optional)
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     *     release_policy (Optional): {
          +     *         contentType: String (Optional)
          +     *         immutable: Boolean (Optional)
          +     *         data: Base64Url (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * * @param keyName Name for the imported key. The value you provide may be copied globally for the purpose of running * the service. The value provided should not include personally identifiable or sensitive information. - * @param key The Json web key. - * @param hsm Whether to import as a hardware key (HSM) or software key. - * @param keyAttributes The key management attributes. - * @param tags Application specific metadata in the form of key-value pairs. - * @param releasePolicy The policy rules under which the key can be exported. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param parameters The parameters to import a key. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response} on successful * completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> importKeyWithResponseAsync(String vaultBaseUrl, String keyName, JsonWebKey key, - Boolean hsm, KeyAttributes keyAttributes, Map tags, KeyReleasePolicy releasePolicy, - Context context) { + public Mono> importKeyWithResponseAsync(String keyName, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - KeyImportParameters parameters = new KeyImportParameters(); - parameters.setHsm(hsm); - parameters.setKey(key); - parameters.setKeyAttributes(keyAttributes); - parameters.setTags(tags); - parameters.setReleasePolicy(releasePolicy); - return service.importKey(vaultBaseUrl, keyName, this.getApiVersion(), parameters, accept, context); - } - - /** - * Imports an externally created key, stores it, and returns key parameters and attributes to the client. - * - * The import key operation may be used to import any key type into an Azure Key Vault. If the named key already - * exists, Azure Key Vault creates a new version of the key. This operation requires the keys/import permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName Name for the imported key. The value you provide may be copied globally for the purpose of running - * the service. The value provided should not include personally identifiable or sensitive information. - * @param key The Json web key. - * @param hsm Whether to import as a hardware key (HSM) or software key. - * @param keyAttributes The key management attributes. - * @param tags Application specific metadata in the form of key-value pairs. - * @param releasePolicy The policy rules under which the key can be exported. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono importKeyAsync(String vaultBaseUrl, String keyName, JsonWebKey key, Boolean hsm, - KeyAttributes keyAttributes, Map tags, KeyReleasePolicy releasePolicy) { - return importKeyWithResponseAsync(vaultBaseUrl, keyName, key, hsm, keyAttributes, tags, releasePolicy) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Imports an externally created key, stores it, and returns key parameters and attributes to the client. - * - * The import key operation may be used to import any key type into an Azure Key Vault. If the named key already - * exists, Azure Key Vault creates a new version of the key. This operation requires the keys/import permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName Name for the imported key. The value you provide may be copied globally for the purpose of running - * the service. The value provided should not include personally identifiable or sensitive information. - * @param key The Json web key. - * @param hsm Whether to import as a hardware key (HSM) or software key. - * @param keyAttributes The key management attributes. - * @param tags Application specific metadata in the form of key-value pairs. - * @param releasePolicy The policy rules under which the key can be exported. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono importKeyAsync(String vaultBaseUrl, String keyName, JsonWebKey key, Boolean hsm, - KeyAttributes keyAttributes, Map tags, KeyReleasePolicy releasePolicy, Context context) { - return importKeyWithResponseAsync(vaultBaseUrl, keyName, key, hsm, keyAttributes, tags, releasePolicy, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + return FluxUtil.withContext(context -> service.importKey(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), keyName, contentType, accept, parameters, requestOptions, context)); } /** * Imports an externally created key, stores it, and returns key parameters and attributes to the client. - * + * * The import key operation may be used to import any key type into an Azure Key Vault. If the named key already * exists, Azure Key Vault creates a new version of the key. This operation requires the keys/import permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     Hsm: Boolean (Optional)
          +     *     key (Required): {
          +     *         kid: String (Optional)
          +     *         kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *         key_ops (Optional): [
          +     *             String (Optional)
          +     *         ]
          +     *         n: Base64Url (Optional)
          +     *         e: Base64Url (Optional)
          +     *         d: Base64Url (Optional)
          +     *         dp: Base64Url (Optional)
          +     *         dq: Base64Url (Optional)
          +     *         qi: Base64Url (Optional)
          +     *         p: Base64Url (Optional)
          +     *         q: Base64Url (Optional)
          +     *         k: Base64Url (Optional)
          +     *         key_hsm: Base64Url (Optional)
          +     *         crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         x: Base64Url (Optional)
          +     *         y: Base64Url (Optional)
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     release_policy (Optional): {
          +     *         contentType: String (Optional)
          +     *         immutable: Boolean (Optional)
          +     *         data: Base64Url (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     key (Optional): {
          +     *         kid: String (Optional)
          +     *         kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *         key_ops (Optional): [
          +     *             String (Optional)
          +     *         ]
          +     *         n: Base64Url (Optional)
          +     *         e: Base64Url (Optional)
          +     *         d: Base64Url (Optional)
          +     *         dp: Base64Url (Optional)
          +     *         dq: Base64Url (Optional)
          +     *         qi: Base64Url (Optional)
          +     *         p: Base64Url (Optional)
          +     *         q: Base64Url (Optional)
          +     *         k: Base64Url (Optional)
          +     *         key_hsm: Base64Url (Optional)
          +     *         crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         x: Base64Url (Optional)
          +     *         y: Base64Url (Optional)
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     *     release_policy (Optional): {
          +     *         contentType: String (Optional)
          +     *         immutable: Boolean (Optional)
          +     *         data: Base64Url (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * * @param keyName Name for the imported key. The value you provide may be copied globally for the purpose of running * the service. The value provided should not include personally identifiable or sensitive information. - * @param key The Json web key. - * @param hsm Whether to import as a hardware key (HSM) or software key. - * @param keyAttributes The key management attributes. - * @param tags Application specific metadata in the form of key-value pairs. - * @param releasePolicy The policy rules under which the key can be exported. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param parameters The parameters to import a key. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response importKeyWithResponse(String vaultBaseUrl, String keyName, JsonWebKey key, Boolean hsm, - KeyAttributes keyAttributes, Map tags, KeyReleasePolicy releasePolicy, Context context) { + public Response importKeyWithResponse(String keyName, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - KeyImportParameters parameters = new KeyImportParameters(); - parameters.setHsm(hsm); - parameters.setKey(key); - parameters.setKeyAttributes(keyAttributes); - parameters.setTags(tags); - parameters.setReleasePolicy(releasePolicy); - return service.importKeySync(vaultBaseUrl, keyName, this.getApiVersion(), parameters, accept, context); - } - - /** - * Imports an externally created key, stores it, and returns key parameters and attributes to the client. - * - * The import key operation may be used to import any key type into an Azure Key Vault. If the named key already - * exists, Azure Key Vault creates a new version of the key. This operation requires the keys/import permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName Name for the imported key. The value you provide may be copied globally for the purpose of running - * the service. The value provided should not include personally identifiable or sensitive information. - * @param key The Json web key. - * @param hsm Whether to import as a hardware key (HSM) or software key. - * @param keyAttributes The key management attributes. - * @param tags Application specific metadata in the form of key-value pairs. - * @param releasePolicy The policy rules under which the key can be exported. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyBundle importKey(String vaultBaseUrl, String keyName, JsonWebKey key, Boolean hsm, - KeyAttributes keyAttributes, Map tags, KeyReleasePolicy releasePolicy) { - return importKeyWithResponse(vaultBaseUrl, keyName, key, hsm, keyAttributes, tags, releasePolicy, Context.NONE) - .getValue(); + return service.importKeySync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), keyName, + contentType, accept, parameters, requestOptions, Context.NONE); } /** * Deletes a key of any type from storage in Azure Key Vault. - * - * The delete key operation cannot be used to remove individual versions of a key. This operation removes the - * cryptographic material associated with the key, which means the key is not usable for Sign/Verify, Wrap/Unwrap or - * Encrypt/Decrypt operations. This operation requires the keys/delete permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to delete. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info along with - * {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteKeyWithResponseAsync(String vaultBaseUrl, String keyName) { - return FluxUtil.withContext(context -> deleteKeyWithResponseAsync(vaultBaseUrl, keyName, context)); - } - - /** - * Deletes a key of any type from storage in Azure Key Vault. - * + * * The delete key operation cannot be used to remove individual versions of a key. This operation removes the * cryptographic material associated with the key, which means the key is not usable for Sign/Verify, Wrap/Unwrap or * Encrypt/Decrypt operations. This operation requires the keys/delete permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     key (Optional): {
          +     *         kid: String (Optional)
          +     *         kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *         key_ops (Optional): [
          +     *             String (Optional)
          +     *         ]
          +     *         n: Base64Url (Optional)
          +     *         e: Base64Url (Optional)
          +     *         d: Base64Url (Optional)
          +     *         dp: Base64Url (Optional)
          +     *         dq: Base64Url (Optional)
          +     *         qi: Base64Url (Optional)
          +     *         p: Base64Url (Optional)
          +     *         q: Base64Url (Optional)
          +     *         k: Base64Url (Optional)
          +     *         key_hsm: Base64Url (Optional)
          +     *         crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         x: Base64Url (Optional)
          +     *         y: Base64Url (Optional)
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     *     release_policy (Optional): {
          +     *         contentType: String (Optional)
          +     *         immutable: Boolean (Optional)
          +     *         data: Base64Url (Optional)
          +     *     }
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * * @param keyName The name of the key to delete. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info along with * {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteKeyWithResponseAsync(String vaultBaseUrl, String keyName, - Context context) { + public Mono> deleteKeyWithResponseAsync(String keyName, RequestOptions requestOptions) { final String accept = "application/json"; - return service.deleteKey(vaultBaseUrl, keyName, this.getApiVersion(), accept, context); - } - - /** - * Deletes a key of any type from storage in Azure Key Vault. - * - * The delete key operation cannot be used to remove individual versions of a key. This operation removes the - * cryptographic material associated with the key, which means the key is not usable for Sign/Verify, Wrap/Unwrap or - * Encrypt/Decrypt operations. This operation requires the keys/delete permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to delete. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteKeyAsync(String vaultBaseUrl, String keyName) { - return deleteKeyWithResponseAsync(vaultBaseUrl, keyName).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Deletes a key of any type from storage in Azure Key Vault. - * - * The delete key operation cannot be used to remove individual versions of a key. This operation removes the - * cryptographic material associated with the key, which means the key is not usable for Sign/Verify, Wrap/Unwrap or - * Encrypt/Decrypt operations. This operation requires the keys/delete permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to delete. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteKeyAsync(String vaultBaseUrl, String keyName, Context context) { - return deleteKeyWithResponseAsync(vaultBaseUrl, keyName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + return FluxUtil.withContext(context -> service.deleteKey(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), keyName, accept, requestOptions, context)); } /** * Deletes a key of any type from storage in Azure Key Vault. - * + * * The delete key operation cannot be used to remove individual versions of a key. This operation removes the * cryptographic material associated with the key, which means the key is not usable for Sign/Verify, Wrap/Unwrap or * Encrypt/Decrypt operations. This operation requires the keys/delete permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     key (Optional): {
          +     *         kid: String (Optional)
          +     *         kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *         key_ops (Optional): [
          +     *             String (Optional)
          +     *         ]
          +     *         n: Base64Url (Optional)
          +     *         e: Base64Url (Optional)
          +     *         d: Base64Url (Optional)
          +     *         dp: Base64Url (Optional)
          +     *         dq: Base64Url (Optional)
          +     *         qi: Base64Url (Optional)
          +     *         p: Base64Url (Optional)
          +     *         q: Base64Url (Optional)
          +     *         k: Base64Url (Optional)
          +     *         key_hsm: Base64Url (Optional)
          +     *         crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         x: Base64Url (Optional)
          +     *         y: Base64Url (Optional)
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     *     release_policy (Optional): {
          +     *         contentType: String (Optional)
          +     *         immutable: Boolean (Optional)
          +     *         data: Base64Url (Optional)
          +     *     }
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * * @param keyName The name of the key to delete. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info along with * {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteKeyWithResponse(String vaultBaseUrl, String keyName, Context context) { + public Response deleteKeyWithResponse(String keyName, RequestOptions requestOptions) { final String accept = "application/json"; - return service.deleteKeySync(vaultBaseUrl, keyName, this.getApiVersion(), accept, context); - } - - /** - * Deletes a key of any type from storage in Azure Key Vault. - * - * The delete key operation cannot be used to remove individual versions of a key. This operation removes the - * cryptographic material associated with the key, which means the key is not usable for Sign/Verify, Wrap/Unwrap or - * Encrypt/Decrypt operations. This operation requires the keys/delete permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to delete. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public DeletedKeyBundle deleteKey(String vaultBaseUrl, String keyName) { - return deleteKeyWithResponse(vaultBaseUrl, keyName, Context.NONE).getValue(); + return service.deleteKeySync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), keyName, accept, + requestOptions, Context.NONE); } /** * The update key operation changes specified attributes of a stored key and can be applied to any key type and key * version stored in Azure Key Vault. - * + * * In order to perform this operation, the key must already exist in the Key Vault. Note: The cryptographic material * of a key itself cannot be changed. This operation requires the keys/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     key_ops (Optional): [
          +     *         String(encrypt/decrypt/sign/verify/wrapKey/unwrapKey/import/export) (Optional)
          +     *     ]
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     release_policy (Optional): {
          +     *         contentType: String (Optional)
          +     *         immutable: Boolean (Optional)
          +     *         data: Base64Url (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     key (Optional): {
          +     *         kid: String (Optional)
          +     *         kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *         key_ops (Optional): [
          +     *             String (Optional)
          +     *         ]
          +     *         n: Base64Url (Optional)
          +     *         e: Base64Url (Optional)
          +     *         d: Base64Url (Optional)
          +     *         dp: Base64Url (Optional)
          +     *         dq: Base64Url (Optional)
          +     *         qi: Base64Url (Optional)
          +     *         p: Base64Url (Optional)
          +     *         q: Base64Url (Optional)
          +     *         k: Base64Url (Optional)
          +     *         key_hsm: Base64Url (Optional)
          +     *         crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         x: Base64Url (Optional)
          +     *         y: Base64Url (Optional)
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     *     release_policy (Optional): {
          +     *         contentType: String (Optional)
          +     *         immutable: Boolean (Optional)
          +     *         data: Base64Url (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * * @param keyName The name of key to update. * @param keyVersion The version of the key to update. - * @param keyOps Json web key operations. For more information on possible key operations, see JsonWebKeyOperation. - * @param keyAttributes The attributes of a key managed by the key vault service. - * @param tags Application specific metadata in the form of key-value pairs. - * @param releasePolicy The policy rules under which the key can be exported. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param parameters The parameters of the key to update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response} on successful * completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> updateKeyWithResponseAsync(String vaultBaseUrl, String keyName, String keyVersion, - List keyOps, KeyAttributes keyAttributes, Map tags, - KeyReleasePolicy releasePolicy) { - return FluxUtil.withContext(context -> updateKeyWithResponseAsync(vaultBaseUrl, keyName, keyVersion, keyOps, - keyAttributes, tags, releasePolicy, context)); + public Mono> updateKeyWithResponseAsync(String keyName, String keyVersion, + BinaryData parameters, RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.updateKey(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + keyName, keyVersion, contentType, accept, parameters, requestOptions, context)); } /** * The update key operation changes specified attributes of a stored key and can be applied to any key type and key * version stored in Azure Key Vault. - * + * * In order to perform this operation, the key must already exist in the Key Vault. Note: The cryptographic material * of a key itself cannot be changed. This operation requires the keys/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     key_ops (Optional): [
          +     *         String(encrypt/decrypt/sign/verify/wrapKey/unwrapKey/import/export) (Optional)
          +     *     ]
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     release_policy (Optional): {
          +     *         contentType: String (Optional)
          +     *         immutable: Boolean (Optional)
          +     *         data: Base64Url (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     key (Optional): {
          +     *         kid: String (Optional)
          +     *         kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *         key_ops (Optional): [
          +     *             String (Optional)
          +     *         ]
          +     *         n: Base64Url (Optional)
          +     *         e: Base64Url (Optional)
          +     *         d: Base64Url (Optional)
          +     *         dp: Base64Url (Optional)
          +     *         dq: Base64Url (Optional)
          +     *         qi: Base64Url (Optional)
          +     *         p: Base64Url (Optional)
          +     *         q: Base64Url (Optional)
          +     *         k: Base64Url (Optional)
          +     *         key_hsm: Base64Url (Optional)
          +     *         crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         x: Base64Url (Optional)
          +     *         y: Base64Url (Optional)
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     *     release_policy (Optional): {
          +     *         contentType: String (Optional)
          +     *         immutable: Boolean (Optional)
          +     *         data: Base64Url (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * * @param keyName The name of key to update. * @param keyVersion The version of the key to update. - * @param keyOps Json web key operations. For more information on possible key operations, see JsonWebKeyOperation. - * @param keyAttributes The attributes of a key managed by the key vault service. - * @param tags Application specific metadata in the form of key-value pairs. - * @param releasePolicy The policy rules under which the key can be exported. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response} on successful - * completion of {@link Mono}. + * @param parameters The parameters of the key to update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> updateKeyWithResponseAsync(String vaultBaseUrl, String keyName, String keyVersion, - List keyOps, KeyAttributes keyAttributes, Map tags, - KeyReleasePolicy releasePolicy, Context context) { + public Response updateKeyWithResponse(String keyName, String keyVersion, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - KeyUpdateParameters parameters = new KeyUpdateParameters(); - parameters.setKeyOps(keyOps); - parameters.setKeyAttributes(keyAttributes); - parameters.setTags(tags); - parameters.setReleasePolicy(releasePolicy); - return service.updateKey(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, context); - } - - /** - * The update key operation changes specified attributes of a stored key and can be applied to any key type and key - * version stored in Azure Key Vault. - * - * In order to perform this operation, the key must already exist in the Key Vault. Note: The cryptographic material - * of a key itself cannot be changed. This operation requires the keys/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of key to update. - * @param keyVersion The version of the key to update. - * @param keyOps Json web key operations. For more information on possible key operations, see JsonWebKeyOperation. - * @param keyAttributes The attributes of a key managed by the key vault service. - * @param tags Application specific metadata in the form of key-value pairs. - * @param releasePolicy The policy rules under which the key can be exported. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono updateKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, - List keyOps, KeyAttributes keyAttributes, Map tags, - KeyReleasePolicy releasePolicy) { - return updateKeyWithResponseAsync(vaultBaseUrl, keyName, keyVersion, keyOps, keyAttributes, tags, releasePolicy) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * The update key operation changes specified attributes of a stored key and can be applied to any key type and key - * version stored in Azure Key Vault. - * - * In order to perform this operation, the key must already exist in the Key Vault. Note: The cryptographic material - * of a key itself cannot be changed. This operation requires the keys/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of key to update. - * @param keyVersion The version of the key to update. - * @param keyOps Json web key operations. For more information on possible key operations, see JsonWebKeyOperation. - * @param keyAttributes The attributes of a key managed by the key vault service. - * @param tags Application specific metadata in the form of key-value pairs. - * @param releasePolicy The policy rules under which the key can be exported. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono updateKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, - List keyOps, KeyAttributes keyAttributes, Map tags, - KeyReleasePolicy releasePolicy, Context context) { - return updateKeyWithResponseAsync(vaultBaseUrl, keyName, keyVersion, keyOps, keyAttributes, tags, releasePolicy, - context).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * The update key operation changes specified attributes of a stored key and can be applied to any key type and key - * version stored in Azure Key Vault. - * - * In order to perform this operation, the key must already exist in the Key Vault. Note: The cryptographic material - * of a key itself cannot be changed. This operation requires the keys/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of key to update. - * @param keyVersion The version of the key to update. - * @param keyOps Json web key operations. For more information on possible key operations, see JsonWebKeyOperation. - * @param keyAttributes The attributes of a key managed by the key vault service. - * @param tags Application specific metadata in the form of key-value pairs. - * @param releasePolicy The policy rules under which the key can be exported. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response updateKeyWithResponse(String vaultBaseUrl, String keyName, String keyVersion, - List keyOps, KeyAttributes keyAttributes, Map tags, - KeyReleasePolicy releasePolicy, Context context) { - final String accept = "application/json"; - KeyUpdateParameters parameters = new KeyUpdateParameters(); - parameters.setKeyOps(keyOps); - parameters.setKeyAttributes(keyAttributes); - parameters.setTags(tags); - parameters.setReleasePolicy(releasePolicy); - return service.updateKeySync(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, - context); - } - - /** - * The update key operation changes specified attributes of a stored key and can be applied to any key type and key - * version stored in Azure Key Vault. - * - * In order to perform this operation, the key must already exist in the Key Vault. Note: The cryptographic material - * of a key itself cannot be changed. This operation requires the keys/update permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of key to update. - * @param keyVersion The version of the key to update. - * @param keyOps Json web key operations. For more information on possible key operations, see JsonWebKeyOperation. - * @param keyAttributes The attributes of a key managed by the key vault service. - * @param tags Application specific metadata in the form of key-value pairs. - * @param releasePolicy The policy rules under which the key can be exported. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyBundle updateKey(String vaultBaseUrl, String keyName, String keyVersion, List keyOps, - KeyAttributes keyAttributes, Map tags, KeyReleasePolicy releasePolicy) { - return updateKeyWithResponse(vaultBaseUrl, keyName, keyVersion, keyOps, keyAttributes, tags, releasePolicy, - Context.NONE).getValue(); - } - - /** - * Gets the public part of a stored key. - * - * The get key operation is applicable to all key types. If the requested key is symmetric, then no key material is - * released in the response. This operation requires the keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to get. - * @param keyVersion Adding the version parameter retrieves a specific version of a key. This URI fragment is - * optional. If not specified, the latest version of the key is returned. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getKeyWithResponseAsync(String vaultBaseUrl, String keyName, String keyVersion) { - return FluxUtil.withContext(context -> getKeyWithResponseAsync(vaultBaseUrl, keyName, keyVersion, context)); - } - - /** - * Gets the public part of a stored key. - * - * The get key operation is applicable to all key types. If the requested key is symmetric, then no key material is - * released in the response. This operation requires the keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to get. - * @param keyVersion Adding the version parameter retrieves a specific version of a key. This URI fragment is - * optional. If not specified, the latest version of the key is returned. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getKeyWithResponseAsync(String vaultBaseUrl, String keyName, String keyVersion, - Context context) { - final String accept = "application/json"; - return service.getKey(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), accept, context); - } - - /** - * Gets the public part of a stored key. - * - * The get key operation is applicable to all key types. If the requested key is symmetric, then no key material is - * released in the response. This operation requires the keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to get. - * @param keyVersion Adding the version parameter retrieves a specific version of a key. This URI fragment is - * optional. If not specified, the latest version of the key is returned. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getKeyAsync(String vaultBaseUrl, String keyName, String keyVersion) { - return getKeyWithResponseAsync(vaultBaseUrl, keyName, keyVersion) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Gets the public part of a stored key. - * - * The get key operation is applicable to all key types. If the requested key is symmetric, then no key material is - * released in the response. This operation requires the keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to get. - * @param keyVersion Adding the version parameter retrieves a specific version of a key. This URI fragment is - * optional. If not specified, the latest version of the key is returned. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, Context context) { - return getKeyWithResponseAsync(vaultBaseUrl, keyName, keyVersion, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + return service.updateKeySync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), keyName, keyVersion, + contentType, accept, parameters, requestOptions, Context.NONE); } /** * Gets the public part of a stored key. - * + * * The get key operation is applicable to all key types. If the requested key is symmetric, then no key material is * released in the response. This operation requires the keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     key (Optional): {
          +     *         kid: String (Optional)
          +     *         kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *         key_ops (Optional): [
          +     *             String (Optional)
          +     *         ]
          +     *         n: Base64Url (Optional)
          +     *         e: Base64Url (Optional)
          +     *         d: Base64Url (Optional)
          +     *         dp: Base64Url (Optional)
          +     *         dq: Base64Url (Optional)
          +     *         qi: Base64Url (Optional)
          +     *         p: Base64Url (Optional)
          +     *         q: Base64Url (Optional)
          +     *         k: Base64Url (Optional)
          +     *         key_hsm: Base64Url (Optional)
          +     *         crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         x: Base64Url (Optional)
          +     *         y: Base64Url (Optional)
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     *     release_policy (Optional): {
          +     *         contentType: String (Optional)
          +     *         immutable: Boolean (Optional)
          +     *         data: Base64Url (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * * @param keyName The name of the key to get. * @param keyVersion Adding the version parameter retrieves a specific version of a key. This URI fragment is * optional. If not specified, the latest version of the key is returned. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response}. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the public part of a stored key. + * + * The get key operation is applicable to all key types along with {@link Response} on successful completion of + * {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response getKeyWithResponse(String vaultBaseUrl, String keyName, String keyVersion, - Context context) { + public Mono> getKeyWithResponseAsync(String keyName, String keyVersion, + RequestOptions requestOptions) { final String accept = "application/json"; - return service.getKeySync(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), accept, context); + return FluxUtil.withContext(context -> service.getKey(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), keyName, keyVersion, accept, requestOptions, context)); } /** * Gets the public part of a stored key. - * + * * The get key operation is applicable to all key types. If the requested key is symmetric, then no key material is * released in the response. This operation requires the keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     key (Optional): {
          +     *         kid: String (Optional)
          +     *         kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *         key_ops (Optional): [
          +     *             String (Optional)
          +     *         ]
          +     *         n: Base64Url (Optional)
          +     *         e: Base64Url (Optional)
          +     *         d: Base64Url (Optional)
          +     *         dp: Base64Url (Optional)
          +     *         dq: Base64Url (Optional)
          +     *         qi: Base64Url (Optional)
          +     *         p: Base64Url (Optional)
          +     *         q: Base64Url (Optional)
          +     *         k: Base64Url (Optional)
          +     *         key_hsm: Base64Url (Optional)
          +     *         crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         x: Base64Url (Optional)
          +     *         y: Base64Url (Optional)
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     *     release_policy (Optional): {
          +     *         contentType: String (Optional)
          +     *         immutable: Boolean (Optional)
          +     *         data: Base64Url (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * * @param keyName The name of the key to get. * @param keyVersion Adding the version parameter retrieves a specific version of a key. This URI fragment is * optional. If not specified, the latest version of the key is returned. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyBundle getKey(String vaultBaseUrl, String keyName, String keyVersion) { - return getKeyWithResponse(vaultBaseUrl, keyName, keyVersion, Context.NONE).getValue(); - } - - /** - * Retrieves a list of individual key versions with the same key name. - * - * The full key identifier, attributes, and tags are provided in the response. This operation requires the keys/list - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result along with {@link PagedResponse} on successful completion of {@link Mono}. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the public part of a stored key. + * + * The get key operation is applicable to all key types along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getKeyVersionsSinglePageAsync(String vaultBaseUrl, String keyName, - Integer maxresults) { + public Response getKeyWithResponse(String keyName, String keyVersion, RequestOptions requestOptions) { final String accept = "application/json"; - return FluxUtil.withContext( - context -> service.getKeyVersions(vaultBaseUrl, keyName, maxresults, this.getApiVersion(), accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); + return service.getKeySync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), keyName, keyVersion, + accept, requestOptions, Context.NONE); } /** * Retrieves a list of individual key versions with the same key name. - * + * * The full key identifier, attributes, and tags are provided in the response. This operation requires the keys/list * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kid: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * * @param keyName The name of the key. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the key list result along with {@link PagedResponse} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getKeyVersionsSinglePageAsync(String vaultBaseUrl, String keyName, - Integer maxresults, Context context) { + private Mono> getKeyVersionsSinglePageAsync(String keyName, + RequestOptions requestOptions) { final String accept = "application/json"; - return service.getKeyVersions(vaultBaseUrl, keyName, maxresults, this.getApiVersion(), accept, context) + return FluxUtil + .withContext(context -> service.getKeyVersions(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), keyName, accept, requestOptions, context)) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * Retrieves a list of individual key versions with the same key name. - * - * The full key identifier, attributes, and tags are provided in the response. This operation requires the keys/list - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getKeyVersionsAsync(String vaultBaseUrl, String keyName, Integer maxresults) { - return new PagedFlux<>(() -> getKeyVersionsSinglePageAsync(vaultBaseUrl, keyName, maxresults), - nextLink -> getKeyVersionsNextSinglePageAsync(nextLink, vaultBaseUrl)); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } /** * Retrieves a list of individual key versions with the same key name. - * + * * The full key identifier, attributes, and tags are provided in the response. This operation requires the keys/list * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kid: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * * @param keyName The name of the key. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the key list result as paginated response with {@link PagedFlux}. */ @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getKeyVersionsAsync(String vaultBaseUrl, String keyName, Integer maxresults, - Context context) { - return new PagedFlux<>(() -> getKeyVersionsSinglePageAsync(vaultBaseUrl, keyName, maxresults, context), - nextLink -> getKeyVersionsNextSinglePageAsync(nextLink, vaultBaseUrl, context)); - } - - /** - * Retrieves a list of individual key versions with the same key name. - * - * The full key identifier, attributes, and tags are provided in the response. This operation requires the keys/list - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getKeyVersionsSinglePage(String vaultBaseUrl, String keyName, Integer maxresults) { - final String accept = "application/json"; - Response res - = service.getKeyVersionsSync(vaultBaseUrl, keyName, maxresults, this.getApiVersion(), accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); + public PagedFlux getKeyVersionsAsync(String keyName, RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedFlux<>(() -> getKeyVersionsSinglePageAsync(keyName, requestOptions), + nextLink -> getKeyVersionsNextSinglePageAsync(nextLink, requestOptionsForNextPage)); } /** * Retrieves a list of individual key versions with the same key name. - * + * * The full key identifier, attributes, and tags are provided in the response. This operation requires the keys/list * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kid: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * * @param keyName The name of the key. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the key list result along with {@link PagedResponse}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getKeyVersionsSinglePage(String vaultBaseUrl, String keyName, Integer maxresults, - Context context) { + private PagedResponse getKeyVersionsSinglePage(String keyName, RequestOptions requestOptions) { final String accept = "application/json"; - Response res - = service.getKeyVersionsSync(vaultBaseUrl, keyName, maxresults, this.getApiVersion(), accept, context); + Response res = service.getKeyVersionsSync(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), keyName, accept, requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * Retrieves a list of individual key versions with the same key name. - * - * The full key identifier, attributes, and tags are provided in the response. This operation requires the keys/list - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getKeyVersions(String vaultBaseUrl, String keyName, Integer maxresults) { - return new PagedIterable<>(() -> getKeyVersionsSinglePage(vaultBaseUrl, keyName, maxresults, Context.NONE), - nextLink -> getKeyVersionsNextSinglePage(nextLink, vaultBaseUrl)); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } /** * Retrieves a list of individual key versions with the same key name. - * + * * The full key identifier, attributes, and tags are provided in the response. This operation requires the keys/list * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kid: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * * @param keyName The name of the key. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the key list result as paginated response with {@link PagedIterable}. */ @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getKeyVersions(String vaultBaseUrl, String keyName, Integer maxresults, - Context context) { - return new PagedIterable<>(() -> getKeyVersionsSinglePage(vaultBaseUrl, keyName, maxresults, context), - nextLink -> getKeyVersionsNextSinglePage(nextLink, vaultBaseUrl, context)); + public PagedIterable getKeyVersions(String keyName, RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedIterable<>(() -> getKeyVersionsSinglePage(keyName, requestOptions), + nextLink -> getKeyVersionsNextSinglePage(nextLink, requestOptionsForNextPage)); } /** * List keys in the specified vault. - * + * * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a stored * key. The LIST operation is applicable to all key types, however only the base key identifier, attributes, and * tags are provided in the response. Individual versions of a key are not listed in the response. This operation * requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kid: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the key list result along with {@link PagedResponse} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getKeysSinglePageAsync(String vaultBaseUrl, Integer maxresults) { + private Mono> getKeysSinglePageAsync(RequestOptions requestOptions) { final String accept = "application/json"; return FluxUtil - .withContext(context -> service.getKeys(vaultBaseUrl, maxresults, this.getApiVersion(), accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * List keys in the specified vault. - * - * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a stored - * key. The LIST operation is applicable to all key types, however only the base key identifier, attributes, and - * tags are provided in the response. Individual versions of a key are not listed in the response. This operation - * requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getKeysSinglePageAsync(String vaultBaseUrl, Integer maxresults, - Context context) { - final String accept = "application/json"; - return service.getKeys(vaultBaseUrl, maxresults, this.getApiVersion(), accept, context) + .withContext(context -> service.getKeys(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + accept, requestOptions, context)) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * List keys in the specified vault. - * - * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a stored - * key. The LIST operation is applicable to all key types, however only the base key identifier, attributes, and - * tags are provided in the response. Individual versions of a key are not listed in the response. This operation - * requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getKeysAsync(String vaultBaseUrl, Integer maxresults) { - return new PagedFlux<>(() -> getKeysSinglePageAsync(vaultBaseUrl, maxresults), - nextLink -> getKeysNextSinglePageAsync(nextLink, vaultBaseUrl)); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } /** * List keys in the specified vault. - * + * * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a stored * key. The LIST operation is applicable to all key types, however only the base key identifier, attributes, and * tags are provided in the response. Individual versions of a key are not listed in the response. This operation * requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kid: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the key list result as paginated response with {@link PagedFlux}. */ @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getKeysAsync(String vaultBaseUrl, Integer maxresults, Context context) { - return new PagedFlux<>(() -> getKeysSinglePageAsync(vaultBaseUrl, maxresults, context), - nextLink -> getKeysNextSinglePageAsync(nextLink, vaultBaseUrl, context)); - } - - /** - * List keys in the specified vault. - * - * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a stored - * key. The LIST operation is applicable to all key types, however only the base key identifier, attributes, and - * tags are provided in the response. Individual versions of a key are not listed in the response. This operation - * requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getKeysSinglePage(String vaultBaseUrl, Integer maxresults) { - final String accept = "application/json"; - Response res - = service.getKeysSync(vaultBaseUrl, maxresults, this.getApiVersion(), accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); + public PagedFlux getKeysAsync(RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedFlux<>(() -> getKeysSinglePageAsync(requestOptions), + nextLink -> getKeysNextSinglePageAsync(nextLink, requestOptionsForNextPage)); } /** * List keys in the specified vault. - * + * * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a stored * key. The LIST operation is applicable to all key types, however only the base key identifier, attributes, and * tags are provided in the response. Individual versions of a key are not listed in the response. This operation * requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kid: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the key list result along with {@link PagedResponse}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getKeysSinglePage(String vaultBaseUrl, Integer maxresults, Context context) { + private PagedResponse getKeysSinglePage(RequestOptions requestOptions) { final String accept = "application/json"; - Response res - = service.getKeysSync(vaultBaseUrl, maxresults, this.getApiVersion(), accept, context); + Response res = service.getKeysSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + accept, requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * List keys in the specified vault. - * - * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a stored - * key. The LIST operation is applicable to all key types, however only the base key identifier, attributes, and - * tags are provided in the response. Individual versions of a key are not listed in the response. This operation - * requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getKeys(String vaultBaseUrl, Integer maxresults) { - return new PagedIterable<>(() -> getKeysSinglePage(vaultBaseUrl, maxresults, Context.NONE), - nextLink -> getKeysNextSinglePage(nextLink, vaultBaseUrl)); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } /** * List keys in the specified vault. - * + * * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a stored * key. The LIST operation is applicable to all key types, however only the base key identifier, attributes, and * tags are provided in the response. Individual versions of a key are not listed in the response. This operation * requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kid: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the key list result as paginated response with {@link PagedIterable}. */ @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getKeys(String vaultBaseUrl, Integer maxresults, Context context) { - return new PagedIterable<>(() -> getKeysSinglePage(vaultBaseUrl, maxresults, context), - nextLink -> getKeysNextSinglePage(nextLink, vaultBaseUrl, context)); + public PagedIterable getKeys(RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedIterable<>(() -> getKeysSinglePage(requestOptions), + nextLink -> getKeysNextSinglePage(nextLink, requestOptionsForNextPage)); } /** * Requests that a backup of the specified key be downloaded to the client. - * + * * The Key Backup operation exports a key from Azure Key Vault in a protected form. Note that this operation does * NOT return key material in a form that can be used outside the Azure Key Vault system, the returned key material * is either protected to a Azure Key Vault HSM or to Azure Key Vault itself. The intent of this operation is to @@ -1896,23 +2311,35 @@ public PagedIterable getKeys(String vaultBaseUrl, Integer maxresults, C * geographical boundaries only; meaning that a BACKUP from one geographical area cannot be restored to another * geographical area. For example, a backup from the US geographical area cannot be restored in an EU geographical * area. This operation requires the key/backup permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          + * * @param keyName The name of the key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the backup key result, containing the backup blob along with {@link Response} on successful completion of * {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> backupKeyWithResponseAsync(String vaultBaseUrl, String keyName) { - return FluxUtil.withContext(context -> backupKeyWithResponseAsync(vaultBaseUrl, keyName, context)); + public Mono> backupKeyWithResponseAsync(String keyName, RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.backupKey(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), keyName, accept, requestOptions, context)); } /** * Requests that a backup of the specified key be downloaded to the client. - * + * * The Key Backup operation exports a key from Azure Key Vault in a protected form. Note that this operation does * NOT return key material in a form that can be used outside the Azure Key Vault system, the returned key material * is either protected to a Azure Key Vault HSM or to Azure Key Vault itself. The intent of this operation is to @@ -1922,156 +2349,34 @@ public Mono> backupKeyWithResponseAsync(String vaultBa * geographical boundaries only; meaning that a BACKUP from one geographical area cannot be restored to another * geographical area. For example, a backup from the US geographical area cannot be restored in an EU geographical * area. This operation requires the key/backup permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          + * * @param keyName The name of the key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the backup key result, containing the backup blob along with {@link Response} on successful completion of - * {@link Mono}. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the backup key result, containing the backup blob along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> backupKeyWithResponseAsync(String vaultBaseUrl, String keyName, - Context context) { + public Response backupKeyWithResponse(String keyName, RequestOptions requestOptions) { final String accept = "application/json"; - return service.backupKey(vaultBaseUrl, keyName, this.getApiVersion(), accept, context); - } - - /** - * Requests that a backup of the specified key be downloaded to the client. - * - * The Key Backup operation exports a key from Azure Key Vault in a protected form. Note that this operation does - * NOT return key material in a form that can be used outside the Azure Key Vault system, the returned key material - * is either protected to a Azure Key Vault HSM or to Azure Key Vault itself. The intent of this operation is to - * allow a client to GENERATE a key in one Azure Key Vault instance, BACKUP the key, and then RESTORE it into - * another Azure Key Vault instance. The BACKUP operation may be used to export, in protected form, any key type - * from Azure Key Vault. Individual versions of a key cannot be backed up. BACKUP / RESTORE can be performed within - * geographical boundaries only; meaning that a BACKUP from one geographical area cannot be restored to another - * geographical area. For example, a backup from the US geographical area cannot be restored in an EU geographical - * area. This operation requires the key/backup permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the backup key result, containing the backup blob on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono backupKeyAsync(String vaultBaseUrl, String keyName) { - return backupKeyWithResponseAsync(vaultBaseUrl, keyName).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Requests that a backup of the specified key be downloaded to the client. - * - * The Key Backup operation exports a key from Azure Key Vault in a protected form. Note that this operation does - * NOT return key material in a form that can be used outside the Azure Key Vault system, the returned key material - * is either protected to a Azure Key Vault HSM or to Azure Key Vault itself. The intent of this operation is to - * allow a client to GENERATE a key in one Azure Key Vault instance, BACKUP the key, and then RESTORE it into - * another Azure Key Vault instance. The BACKUP operation may be used to export, in protected form, any key type - * from Azure Key Vault. Individual versions of a key cannot be backed up. BACKUP / RESTORE can be performed within - * geographical boundaries only; meaning that a BACKUP from one geographical area cannot be restored to another - * geographical area. For example, a backup from the US geographical area cannot be restored in an EU geographical - * area. This operation requires the key/backup permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the backup key result, containing the backup blob on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono backupKeyAsync(String vaultBaseUrl, String keyName, Context context) { - return backupKeyWithResponseAsync(vaultBaseUrl, keyName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Requests that a backup of the specified key be downloaded to the client. - * - * The Key Backup operation exports a key from Azure Key Vault in a protected form. Note that this operation does - * NOT return key material in a form that can be used outside the Azure Key Vault system, the returned key material - * is either protected to a Azure Key Vault HSM or to Azure Key Vault itself. The intent of this operation is to - * allow a client to GENERATE a key in one Azure Key Vault instance, BACKUP the key, and then RESTORE it into - * another Azure Key Vault instance. The BACKUP operation may be used to export, in protected form, any key type - * from Azure Key Vault. Individual versions of a key cannot be backed up. BACKUP / RESTORE can be performed within - * geographical boundaries only; meaning that a BACKUP from one geographical area cannot be restored to another - * geographical area. For example, a backup from the US geographical area cannot be restored in an EU geographical - * area. This operation requires the key/backup permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the backup key result, containing the backup blob along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response backupKeyWithResponse(String vaultBaseUrl, String keyName, Context context) { - final String accept = "application/json"; - return service.backupKeySync(vaultBaseUrl, keyName, this.getApiVersion(), accept, context); - } - - /** - * Requests that a backup of the specified key be downloaded to the client. - * - * The Key Backup operation exports a key from Azure Key Vault in a protected form. Note that this operation does - * NOT return key material in a form that can be used outside the Azure Key Vault system, the returned key material - * is either protected to a Azure Key Vault HSM or to Azure Key Vault itself. The intent of this operation is to - * allow a client to GENERATE a key in one Azure Key Vault instance, BACKUP the key, and then RESTORE it into - * another Azure Key Vault instance. The BACKUP operation may be used to export, in protected form, any key type - * from Azure Key Vault. Individual versions of a key cannot be backed up. BACKUP / RESTORE can be performed within - * geographical boundaries only; meaning that a BACKUP from one geographical area cannot be restored to another - * geographical area. For example, a backup from the US geographical area cannot be restored in an EU geographical - * area. This operation requires the key/backup permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the backup key result, containing the backup blob. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public BackupKeyResult backupKey(String vaultBaseUrl, String keyName) { - return backupKeyWithResponse(vaultBaseUrl, keyName, Context.NONE).getValue(); - } - - /** - * Restores a backed up key to a vault. - * - * Imports a previously backed up key into Azure Key Vault, restoring the key, its key identifier, attributes and - * access control policies. The RESTORE operation may be used to import a previously backed up key. Individual - * versions of a key cannot be restored. The key is restored in its entirety with the same key name as it had when - * it was backed up. If the key name is not available in the target Key Vault, the RESTORE operation will be - * rejected. While the key name is retained during restore, the final key identifier will change if the key is - * restored to a different vault. Restore will restore all versions and preserve version identifiers. The RESTORE - * operation is subject to security constraints: The target Key Vault must be owned by the same Microsoft Azure - * Subscription as the source Key Vault The user must have RESTORE permission in the target Key Vault. This - * operation requires the keys/restore permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyBundleBackup The backup blob associated with a key bundle. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> restoreKeyWithResponseAsync(String vaultBaseUrl, byte[] keyBundleBackup) { - return FluxUtil.withContext(context -> restoreKeyWithResponseAsync(vaultBaseUrl, keyBundleBackup, context)); + return service.backupKeySync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), keyName, accept, + requestOptions, Context.NONE); } /** * Restores a backed up key to a vault. - * + * * Imports a previously backed up key into Azure Key Vault, restoring the key, its key identifier, attributes and * access control policies. The RESTORE operation may be used to import a previously backed up key. Individual * versions of a key cannot be restored. The key is restored in its entirety with the same key name as it had when @@ -2081,81 +2386,86 @@ public Mono> restoreKeyWithResponseAsync(String vaultBaseUrl * operation is subject to security constraints: The target Key Vault must be owned by the same Microsoft Azure * Subscription as the source Key Vault The user must have RESTORE permission in the target Key Vault. This * operation requires the keys/restore permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyBundleBackup The backup blob associated with a key bundle. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: Base64Url (Required)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     key (Optional): {
          +     *         kid: String (Optional)
          +     *         kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *         key_ops (Optional): [
          +     *             String (Optional)
          +     *         ]
          +     *         n: Base64Url (Optional)
          +     *         e: Base64Url (Optional)
          +     *         d: Base64Url (Optional)
          +     *         dp: Base64Url (Optional)
          +     *         dq: Base64Url (Optional)
          +     *         qi: Base64Url (Optional)
          +     *         p: Base64Url (Optional)
          +     *         q: Base64Url (Optional)
          +     *         k: Base64Url (Optional)
          +     *         key_hsm: Base64Url (Optional)
          +     *         crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         x: Base64Url (Optional)
          +     *         y: Base64Url (Optional)
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     *     release_policy (Optional): {
          +     *         contentType: String (Optional)
          +     *         immutable: Boolean (Optional)
          +     *         data: Base64Url (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + * @param parameters The parameters to restore the key. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response} on successful * completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> restoreKeyWithResponseAsync(String vaultBaseUrl, byte[] keyBundleBackup, - Context context) { + public Mono> restoreKeyWithResponseAsync(BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - KeyRestoreParameters parameters = new KeyRestoreParameters(); - parameters.setKeyBundleBackup(keyBundleBackup); - return service.restoreKey(vaultBaseUrl, this.getApiVersion(), parameters, accept, context); - } - - /** - * Restores a backed up key to a vault. - * - * Imports a previously backed up key into Azure Key Vault, restoring the key, its key identifier, attributes and - * access control policies. The RESTORE operation may be used to import a previously backed up key. Individual - * versions of a key cannot be restored. The key is restored in its entirety with the same key name as it had when - * it was backed up. If the key name is not available in the target Key Vault, the RESTORE operation will be - * rejected. While the key name is retained during restore, the final key identifier will change if the key is - * restored to a different vault. Restore will restore all versions and preserve version identifiers. The RESTORE - * operation is subject to security constraints: The target Key Vault must be owned by the same Microsoft Azure - * Subscription as the source Key Vault The user must have RESTORE permission in the target Key Vault. This - * operation requires the keys/restore permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyBundleBackup The backup blob associated with a key bundle. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono restoreKeyAsync(String vaultBaseUrl, byte[] keyBundleBackup) { - return restoreKeyWithResponseAsync(vaultBaseUrl, keyBundleBackup) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Restores a backed up key to a vault. - * - * Imports a previously backed up key into Azure Key Vault, restoring the key, its key identifier, attributes and - * access control policies. The RESTORE operation may be used to import a previously backed up key. Individual - * versions of a key cannot be restored. The key is restored in its entirety with the same key name as it had when - * it was backed up. If the key name is not available in the target Key Vault, the RESTORE operation will be - * rejected. While the key name is retained during restore, the final key identifier will change if the key is - * restored to a different vault. Restore will restore all versions and preserve version identifiers. The RESTORE - * operation is subject to security constraints: The target Key Vault must be owned by the same Microsoft Azure - * Subscription as the source Key Vault The user must have RESTORE permission in the target Key Vault. This - * operation requires the keys/restore permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyBundleBackup The backup blob associated with a key bundle. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono restoreKeyAsync(String vaultBaseUrl, byte[] keyBundleBackup, Context context) { - return restoreKeyWithResponseAsync(vaultBaseUrl, keyBundleBackup, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + return FluxUtil.withContext(context -> service.restoreKey(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), contentType, accept, parameters, requestOptions, context)); } /** * Restores a backed up key to a vault. - * + * * Imports a previously backed up key into Azure Key Vault, restoring the key, its key identifier, attributes and * access control policies. The RESTORE operation may be used to import a previously backed up key. Individual * versions of a key cannot be restored. The key is restored in its entirety with the same key name as it had when @@ -2165,82 +2475,84 @@ public Mono restoreKeyAsync(String vaultBaseUrl, byte[] keyBundleBack * operation is subject to security constraints: The target Key Vault must be owned by the same Microsoft Azure * Subscription as the source Key Vault The user must have RESTORE permission in the target Key Vault. This * operation requires the keys/restore permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyBundleBackup The backup blob associated with a key bundle. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: Base64Url (Required)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     key (Optional): {
          +     *         kid: String (Optional)
          +     *         kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *         key_ops (Optional): [
          +     *             String (Optional)
          +     *         ]
          +     *         n: Base64Url (Optional)
          +     *         e: Base64Url (Optional)
          +     *         d: Base64Url (Optional)
          +     *         dp: Base64Url (Optional)
          +     *         dq: Base64Url (Optional)
          +     *         qi: Base64Url (Optional)
          +     *         p: Base64Url (Optional)
          +     *         q: Base64Url (Optional)
          +     *         k: Base64Url (Optional)
          +     *         key_hsm: Base64Url (Optional)
          +     *         crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         x: Base64Url (Optional)
          +     *         y: Base64Url (Optional)
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     *     release_policy (Optional): {
          +     *         contentType: String (Optional)
          +     *         immutable: Boolean (Optional)
          +     *         data: Base64Url (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + * @param parameters The parameters to restore the key. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response restoreKeyWithResponse(String vaultBaseUrl, byte[] keyBundleBackup, Context context) { + public Response restoreKeyWithResponse(BinaryData parameters, RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - KeyRestoreParameters parameters = new KeyRestoreParameters(); - parameters.setKeyBundleBackup(keyBundleBackup); - return service.restoreKeySync(vaultBaseUrl, this.getApiVersion(), parameters, accept, context); - } - - /** - * Restores a backed up key to a vault. - * - * Imports a previously backed up key into Azure Key Vault, restoring the key, its key identifier, attributes and - * access control policies. The RESTORE operation may be used to import a previously backed up key. Individual - * versions of a key cannot be restored. The key is restored in its entirety with the same key name as it had when - * it was backed up. If the key name is not available in the target Key Vault, the RESTORE operation will be - * rejected. While the key name is retained during restore, the final key identifier will change if the key is - * restored to a different vault. Restore will restore all versions and preserve version identifiers. The RESTORE - * operation is subject to security constraints: The target Key Vault must be owned by the same Microsoft Azure - * Subscription as the source Key Vault The user must have RESTORE permission in the target Key Vault. This - * operation requires the keys/restore permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyBundleBackup The backup blob associated with a key bundle. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyBundle restoreKey(String vaultBaseUrl, byte[] keyBundleBackup) { - return restoreKeyWithResponse(vaultBaseUrl, keyBundleBackup, Context.NONE).getValue(); - } - - /** - * Encrypts an arbitrary sequence of bytes using an encryption key that is stored in a key vault. - * - * The ENCRYPT operation encrypts an arbitrary sequence of bytes using an encryption key that is stored in Azure Key - * Vault. Note that the ENCRYPT operation only supports a single block of data, the size of which is dependent on - * the target key and the encryption algorithm to be used. The ENCRYPT operation is only strictly necessary for - * symmetric keys stored in Azure Key Vault since protection with an asymmetric key can be performed using public - * portion of the key. This operation is supported for asymmetric keys as a convenience for callers that have a - * key-reference but do not have access to the public key material. This operation requires the keys/encrypt - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> encryptWithResponseAsync(String vaultBaseUrl, String keyName, - String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag) { - return FluxUtil.withContext(context -> encryptWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, - value, iv, aad, tag, context)); + return service.restoreKeySync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), contentType, + accept, parameters, requestOptions, Context.NONE); } /** * Encrypts an arbitrary sequence of bytes using an encryption key that is stored in a key vault. - * + * * The ENCRYPT operation encrypts an arbitrary sequence of bytes using an encryption key that is stored in Azure Key * Vault. Note that the ENCRYPT operation only supports a single block of data, the size of which is dependent on * the target key and the encryption algorithm to be used. The ENCRYPT operation is only strictly necessary for @@ -2248,101 +2560,57 @@ public Mono> encryptWithResponseAsync(String vaultB * portion of the key. This operation is supported for asymmetric keys as a convenience for callers that have a * key-reference but do not have access to the public key material. This operation requires the keys/encrypt * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     alg: String(RSA-OAEP/RSA-OAEP-256/RSA1_5/A128GCM/A192GCM/A256GCM/A128KW/A192KW/A256KW/A128CBC/A192CBC/A256CBC/A128CBCPAD/A192CBCPAD/A256CBCPAD/CKM_AES_KEY_WRAP/CKM_AES_KEY_WRAP_PAD) (Required)
          +     *     value: Base64Url (Required)
          +     *     iv: Base64Url (Optional)
          +     *     aad: Base64Url (Optional)
          +     *     tag: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kid: String (Optional)
          +     *     value: Base64Url (Optional)
          +     *     iv: Base64Url (Optional)
          +     *     tag: Base64Url (Optional)
          +     *     aad: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          + * * @param keyName The name of the key. * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param parameters The parameters for the encryption operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the key operation result along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> encryptWithResponseAsync(String vaultBaseUrl, String keyName, - String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag, - Context context) { + public Mono> encryptWithResponseAsync(String keyName, String keyVersion, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - KeyOperationsParameters parameters = new KeyOperationsParameters(); - parameters.setAlgorithm(algorithm); - parameters.setValue(value); - parameters.setIv(iv); - parameters.setAad(aad); - parameters.setTag(tag); - return service.encrypt(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, context); - } - - /** - * Encrypts an arbitrary sequence of bytes using an encryption key that is stored in a key vault. - * - * The ENCRYPT operation encrypts an arbitrary sequence of bytes using an encryption key that is stored in Azure Key - * Vault. Note that the ENCRYPT operation only supports a single block of data, the size of which is dependent on - * the target key and the encryption algorithm to be used. The ENCRYPT operation is only strictly necessary for - * symmetric keys stored in Azure Key Vault since protection with an asymmetric key can be performed using public - * portion of the key. This operation is supported for asymmetric keys as a convenience for callers that have a - * key-reference but do not have access to the public key material. This operation requires the keys/encrypt - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono encryptAsync(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag) { - return encryptWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value, iv, aad, tag) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Encrypts an arbitrary sequence of bytes using an encryption key that is stored in a key vault. - * - * The ENCRYPT operation encrypts an arbitrary sequence of bytes using an encryption key that is stored in Azure Key - * Vault. Note that the ENCRYPT operation only supports a single block of data, the size of which is dependent on - * the target key and the encryption algorithm to be used. The ENCRYPT operation is only strictly necessary for - * symmetric keys stored in Azure Key Vault since protection with an asymmetric key can be performed using public - * portion of the key. This operation is supported for asymmetric keys as a convenience for callers that have a - * key-reference but do not have access to the public key material. This operation requires the keys/encrypt - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono encryptAsync(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag, Context context) { - return encryptWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value, iv, aad, tag, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + return FluxUtil + .withContext(context -> service.encrypt(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + keyName, keyVersion, contentType, accept, parameters, requestOptions, context)); } /** * Encrypts an arbitrary sequence of bytes using an encryption key that is stored in a key vault. - * + * * The ENCRYPT operation encrypts an arbitrary sequence of bytes using an encryption key that is stored in Azure Key * Vault. Note that the ENCRYPT operation only supports a single block of data, the size of which is dependent on * the target key and the encryption algorithm to be used. The ENCRYPT operation is only strictly necessary for @@ -2350,69 +2618,56 @@ public Mono encryptAsync(String vaultBaseUrl, String keyName * portion of the key. This operation is supported for asymmetric keys as a convenience for callers that have a * key-reference but do not have access to the public key material. This operation requires the keys/encrypt * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     alg: String(RSA-OAEP/RSA-OAEP-256/RSA1_5/A128GCM/A192GCM/A256GCM/A128KW/A192KW/A256KW/A128CBC/A192CBC/A256CBC/A128CBCPAD/A192CBCPAD/A256CBCPAD/CKM_AES_KEY_WRAP/CKM_AES_KEY_WRAP_PAD) (Required)
          +     *     value: Base64Url (Required)
          +     *     iv: Base64Url (Optional)
          +     *     aad: Base64Url (Optional)
          +     *     tag: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kid: String (Optional)
          +     *     value: Base64Url (Optional)
          +     *     iv: Base64Url (Optional)
          +     *     tag: Base64Url (Optional)
          +     *     aad: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          + * * @param keyName The name of the key. * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param parameters The parameters for the encryption operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the key operation result along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response encryptWithResponse(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag, Context context) { + public Response encryptWithResponse(String keyName, String keyVersion, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - KeyOperationsParameters parameters = new KeyOperationsParameters(); - parameters.setAlgorithm(algorithm); - parameters.setValue(value); - parameters.setIv(iv); - parameters.setAad(aad); - parameters.setTag(tag); - return service.encryptSync(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, - context); - } - - /** - * Encrypts an arbitrary sequence of bytes using an encryption key that is stored in a key vault. - * - * The ENCRYPT operation encrypts an arbitrary sequence of bytes using an encryption key that is stored in Azure Key - * Vault. Note that the ENCRYPT operation only supports a single block of data, the size of which is dependent on - * the target key and the encryption algorithm to be used. The ENCRYPT operation is only strictly necessary for - * symmetric keys stored in Azure Key Vault since protection with an asymmetric key can be performed using public - * portion of the key. This operation is supported for asymmetric keys as a convenience for callers that have a - * key-reference but do not have access to the public key material. This operation requires the keys/encrypt - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyOperationResult encrypt(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag) { - return encryptWithResponse(vaultBaseUrl, keyName, keyVersion, algorithm, value, iv, aad, tag, Context.NONE) - .getValue(); + return service.encryptSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), keyName, keyVersion, + contentType, accept, parameters, requestOptions, Context.NONE); } /** * Decrypts a single block of encrypted data. - * + * * The DECRYPT operation decrypts a well-formed block of ciphertext using the target encryption key and specified * algorithm. This operation is the reverse of the ENCRYPT operation; only a single block of data may be decrypted, * the size of this block is dependent on the target key and the algorithm to be used. The DECRYPT operation applies @@ -2420,30 +2675,57 @@ public KeyOperationResult encrypt(String vaultBaseUrl, String keyName, String ke * operation requires the keys/decrypt permission. Microsoft recommends not to use CBC algorithms for decryption * without first ensuring the integrity of the ciphertext using an HMAC, for example. See * https://docs.microsoft.com/dotnet/standard/security/vulnerabilities-cbc-mode for more information. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     alg: String(RSA-OAEP/RSA-OAEP-256/RSA1_5/A128GCM/A192GCM/A256GCM/A128KW/A192KW/A256KW/A128CBC/A192CBC/A256CBC/A128CBCPAD/A192CBCPAD/A256CBCPAD/CKM_AES_KEY_WRAP/CKM_AES_KEY_WRAP_PAD) (Required)
          +     *     value: Base64Url (Required)
          +     *     iv: Base64Url (Optional)
          +     *     aad: Base64Url (Optional)
          +     *     tag: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kid: String (Optional)
          +     *     value: Base64Url (Optional)
          +     *     iv: Base64Url (Optional)
          +     *     tag: Base64Url (Optional)
          +     *     aad: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          + * * @param keyName The name of the key. * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param parameters The parameters for the decryption operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the key operation result along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> decryptWithResponseAsync(String vaultBaseUrl, String keyName, - String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag) { - return FluxUtil.withContext(context -> decryptWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, - value, iv, aad, tag, context)); + public Mono> decryptWithResponseAsync(String keyName, String keyVersion, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.decrypt(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + keyName, keyVersion, contentType, accept, parameters, requestOptions, context)); } /** * Decrypts a single block of encrypted data. - * + * * The DECRYPT operation decrypts a well-formed block of ciphertext using the target encryption key and specified * algorithm. This operation is the reverse of the ENCRYPT operation; only a single block of data may be decrypted, * the size of this block is dependent on the target key and the algorithm to be used. The DECRYPT operation applies @@ -2451,2189 +2733,1772 @@ public Mono> decryptWithResponseAsync(String vaultB * operation requires the keys/decrypt permission. Microsoft recommends not to use CBC algorithms for decryption * without first ensuring the integrity of the ciphertext using an HMAC, for example. See * https://docs.microsoft.com/dotnet/standard/security/vulnerabilities-cbc-mode for more information. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     alg: String(RSA-OAEP/RSA-OAEP-256/RSA1_5/A128GCM/A192GCM/A256GCM/A128KW/A192KW/A256KW/A128CBC/A192CBC/A256CBC/A128CBCPAD/A192CBCPAD/A256CBCPAD/CKM_AES_KEY_WRAP/CKM_AES_KEY_WRAP_PAD) (Required)
          +     *     value: Base64Url (Required)
          +     *     iv: Base64Url (Optional)
          +     *     aad: Base64Url (Optional)
          +     *     tag: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kid: String (Optional)
          +     *     value: Base64Url (Optional)
          +     *     iv: Base64Url (Optional)
          +     *     tag: Base64Url (Optional)
          +     *     aad: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          + * * @param keyName The name of the key. * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result along with {@link Response} on successful completion of {@link Mono}. + * @param parameters The parameters for the decryption operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the key operation result along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> decryptWithResponseAsync(String vaultBaseUrl, String keyName, - String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag, - Context context) { + public Response decryptWithResponse(String keyName, String keyVersion, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - KeyOperationsParameters parameters = new KeyOperationsParameters(); - parameters.setAlgorithm(algorithm); - parameters.setValue(value); - parameters.setIv(iv); - parameters.setAad(aad); - parameters.setTag(tag); - return service.decrypt(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, context); + return service.decryptSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), keyName, keyVersion, + contentType, accept, parameters, requestOptions, Context.NONE); } /** - * Decrypts a single block of encrypted data. - * - * The DECRYPT operation decrypts a well-formed block of ciphertext using the target encryption key and specified - * algorithm. This operation is the reverse of the ENCRYPT operation; only a single block of data may be decrypted, - * the size of this block is dependent on the target key and the algorithm to be used. The DECRYPT operation applies - * to asymmetric and symmetric keys stored in Azure Key Vault since it uses the private portion of the key. This - * operation requires the keys/decrypt permission. Microsoft recommends not to use CBC algorithms for decryption - * without first ensuring the integrity of the ciphertext using an HMAC, for example. See - * https://docs.microsoft.com/dotnet/standard/security/vulnerabilities-cbc-mode for more information. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * Creates a signature from a digest using the specified key. + * + * The SIGN operation is applicable to asymmetric and symmetric keys stored in Azure Key Vault since this operation + * uses the private portion of the key. This operation requires the keys/sign permission. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     alg: String(PS256/PS384/PS512/RS256/RS384/RS512/RSNULL/ES256/ES384/ES512/ES256K) (Required)
          +     *     value: Base64Url (Required)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kid: String (Optional)
          +     *     value: Base64Url (Optional)
          +     *     iv: Base64Url (Optional)
          +     *     tag: Base64Url (Optional)
          +     *     aad: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          + * * @param keyName The name of the key. * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result on successful completion of {@link Mono}. + * @param parameters The parameters for the signing operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the key operation result along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono decryptAsync(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag) { - return decryptWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value, iv, aad, tag) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + public Mono> signWithResponseAsync(String keyName, String keyVersion, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.sign(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), keyName, + keyVersion, contentType, accept, parameters, requestOptions, context)); } /** - * Decrypts a single block of encrypted data. - * - * The DECRYPT operation decrypts a well-formed block of ciphertext using the target encryption key and specified - * algorithm. This operation is the reverse of the ENCRYPT operation; only a single block of data may be decrypted, - * the size of this block is dependent on the target key and the algorithm to be used. The DECRYPT operation applies - * to asymmetric and symmetric keys stored in Azure Key Vault since it uses the private portion of the key. This - * operation requires the keys/decrypt permission. Microsoft recommends not to use CBC algorithms for decryption - * without first ensuring the integrity of the ciphertext using an HMAC, for example. See - * https://docs.microsoft.com/dotnet/standard/security/vulnerabilities-cbc-mode for more information. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + * Creates a signature from a digest using the specified key. + * + * The SIGN operation is applicable to asymmetric and symmetric keys stored in Azure Key Vault since this operation + * uses the private portion of the key. This operation requires the keys/sign permission. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     alg: String(PS256/PS384/PS512/RS256/RS384/RS512/RSNULL/ES256/ES384/ES512/ES256K) (Required)
          +     *     value: Base64Url (Required)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kid: String (Optional)
          +     *     value: Base64Url (Optional)
          +     *     iv: Base64Url (Optional)
          +     *     tag: Base64Url (Optional)
          +     *     aad: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          + * * @param keyName The name of the key. * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result on successful completion of {@link Mono}. + * @param parameters The parameters for the signing operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the key operation result along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono decryptAsync(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag, Context context) { - return decryptWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value, iv, aad, tag, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Decrypts a single block of encrypted data. - * - * The DECRYPT operation decrypts a well-formed block of ciphertext using the target encryption key and specified - * algorithm. This operation is the reverse of the ENCRYPT operation; only a single block of data may be decrypted, - * the size of this block is dependent on the target key and the algorithm to be used. The DECRYPT operation applies - * to asymmetric and symmetric keys stored in Azure Key Vault since it uses the private portion of the key. This - * operation requires the keys/decrypt permission. Microsoft recommends not to use CBC algorithms for decryption - * without first ensuring the integrity of the ciphertext using an HMAC, for example. See - * https://docs.microsoft.com/dotnet/standard/security/vulnerabilities-cbc-mode for more information. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response decryptWithResponse(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag, Context context) { - final String accept = "application/json"; - KeyOperationsParameters parameters = new KeyOperationsParameters(); - parameters.setAlgorithm(algorithm); - parameters.setValue(value); - parameters.setIv(iv); - parameters.setAad(aad); - parameters.setTag(tag); - return service.decryptSync(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, - context); - } - - /** - * Decrypts a single block of encrypted data. - * - * The DECRYPT operation decrypts a well-formed block of ciphertext using the target encryption key and specified - * algorithm. This operation is the reverse of the ENCRYPT operation; only a single block of data may be decrypted, - * the size of this block is dependent on the target key and the algorithm to be used. The DECRYPT operation applies - * to asymmetric and symmetric keys stored in Azure Key Vault since it uses the private portion of the key. This - * operation requires the keys/decrypt permission. Microsoft recommends not to use CBC algorithms for decryption - * without first ensuring the integrity of the ciphertext using an HMAC, for example. See - * https://docs.microsoft.com/dotnet/standard/security/vulnerabilities-cbc-mode for more information. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyOperationResult decrypt(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag) { - return decryptWithResponse(vaultBaseUrl, keyName, keyVersion, algorithm, value, iv, aad, tag, Context.NONE) - .getValue(); - } - - /** - * Creates a signature from a digest using the specified key. - * - * The SIGN operation is applicable to asymmetric and symmetric keys stored in Azure Key Vault since this operation - * uses the private portion of the key. This operation requires the keys/sign permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm The signing/verification algorithm identifier. For more information on possible algorithm types, - * see JsonWebKeySignatureAlgorithm. - * @param value The value parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> signWithResponseAsync(String vaultBaseUrl, String keyName, - String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] value) { - return FluxUtil.withContext( - context -> signWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value, context)); - } - - /** - * Creates a signature from a digest using the specified key. - * - * The SIGN operation is applicable to asymmetric and symmetric keys stored in Azure Key Vault since this operation - * uses the private portion of the key. This operation requires the keys/sign permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm The signing/verification algorithm identifier. For more information on possible algorithm types, - * see JsonWebKeySignatureAlgorithm. - * @param value The value parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> signWithResponseAsync(String vaultBaseUrl, String keyName, - String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] value, Context context) { - final String accept = "application/json"; - KeySignParameters parameters = new KeySignParameters(); - parameters.setAlgorithm(algorithm); - parameters.setValue(value); - return service.sign(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, context); - } - - /** - * Creates a signature from a digest using the specified key. - * - * The SIGN operation is applicable to asymmetric and symmetric keys stored in Azure Key Vault since this operation - * uses the private portion of the key. This operation requires the keys/sign permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm The signing/verification algorithm identifier. For more information on possible algorithm types, - * see JsonWebKeySignatureAlgorithm. - * @param value The value parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono signAsync(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeySignatureAlgorithm algorithm, byte[] value) { - return signWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a signature from a digest using the specified key. - * - * The SIGN operation is applicable to asymmetric and symmetric keys stored in Azure Key Vault since this operation - * uses the private portion of the key. This operation requires the keys/sign permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm The signing/verification algorithm identifier. For more information on possible algorithm types, - * see JsonWebKeySignatureAlgorithm. - * @param value The value parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono signAsync(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeySignatureAlgorithm algorithm, byte[] value, Context context) { - return signWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a signature from a digest using the specified key. - * - * The SIGN operation is applicable to asymmetric and symmetric keys stored in Azure Key Vault since this operation - * uses the private portion of the key. This operation requires the keys/sign permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm The signing/verification algorithm identifier. For more information on possible algorithm types, - * see JsonWebKeySignatureAlgorithm. - * @param value The value parameter. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response signWithResponse(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeySignatureAlgorithm algorithm, byte[] value, Context context) { - final String accept = "application/json"; - KeySignParameters parameters = new KeySignParameters(); - parameters.setAlgorithm(algorithm); - parameters.setValue(value); - return service.signSync(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, context); - } - - /** - * Creates a signature from a digest using the specified key. - * - * The SIGN operation is applicable to asymmetric and symmetric keys stored in Azure Key Vault since this operation - * uses the private portion of the key. This operation requires the keys/sign permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm The signing/verification algorithm identifier. For more information on possible algorithm types, - * see JsonWebKeySignatureAlgorithm. - * @param value The value parameter. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyOperationResult sign(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeySignatureAlgorithm algorithm, byte[] value) { - return signWithResponse(vaultBaseUrl, keyName, keyVersion, algorithm, value, Context.NONE).getValue(); + public Response signWithResponse(String keyName, String keyVersion, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return service.signSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), keyName, keyVersion, + contentType, accept, parameters, requestOptions, Context.NONE); } /** * Verifies a signature using a specified key. - * - * The VERIFY operation is applicable to symmetric keys stored in Azure Key Vault. VERIFY is not strictly necessary - * for asymmetric keys stored in Azure Key Vault since signature verification can be performed using the public - * portion of the key but this operation is supported as a convenience for callers that only have a key-reference - * and not the public portion of the key. This operation requires the keys/verify permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm The signing/verification algorithm. For more information on possible algorithm types, see - * JsonWebKeySignatureAlgorithm. - * @param digest The digest used for signing. - * @param signature The signature to be verified. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key verify result along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> verifyWithResponseAsync(String vaultBaseUrl, String keyName, - String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature) { - return FluxUtil.withContext(context -> verifyWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, - digest, signature, context)); - } - - /** - * Verifies a signature using a specified key. - * + * * The VERIFY operation is applicable to symmetric keys stored in Azure Key Vault. VERIFY is not strictly necessary * for asymmetric keys stored in Azure Key Vault since signature verification can be performed using the public * portion of the key but this operation is supported as a convenience for callers that only have a key-reference * and not the public portion of the key. This operation requires the keys/verify permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     alg: String(PS256/PS384/PS512/RS256/RS384/RS512/RSNULL/ES256/ES384/ES512/ES256K) (Required)
          +     *     digest: Base64Url (Required)
          +     *     value: Base64Url (Required)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * * @param keyName The name of the key. * @param keyVersion The version of the key. - * @param algorithm The signing/verification algorithm. For more information on possible algorithm types, see - * JsonWebKeySignatureAlgorithm. - * @param digest The digest used for signing. - * @param signature The signature to be verified. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param parameters The parameters for verify operations. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the key verify result along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> verifyWithResponseAsync(String vaultBaseUrl, String keyName, - String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { + public Mono> verifyWithResponseAsync(String keyName, String keyVersion, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - KeyVerifyParameters parameters = new KeyVerifyParameters(); - parameters.setAlgorithm(algorithm); - parameters.setDigest(digest); - parameters.setSignature(signature); - return service.verify(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, context); - } - - /** - * Verifies a signature using a specified key. - * - * The VERIFY operation is applicable to symmetric keys stored in Azure Key Vault. VERIFY is not strictly necessary - * for asymmetric keys stored in Azure Key Vault since signature verification can be performed using the public - * portion of the key but this operation is supported as a convenience for callers that only have a key-reference - * and not the public portion of the key. This operation requires the keys/verify permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm The signing/verification algorithm. For more information on possible algorithm types, see - * JsonWebKeySignatureAlgorithm. - * @param digest The digest used for signing. - * @param signature The signature to be verified. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key verify result on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono verifyAsync(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature) { - return verifyWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, digest, signature) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Verifies a signature using a specified key. - * - * The VERIFY operation is applicable to symmetric keys stored in Azure Key Vault. VERIFY is not strictly necessary - * for asymmetric keys stored in Azure Key Vault since signature verification can be performed using the public - * portion of the key but this operation is supported as a convenience for callers that only have a key-reference - * and not the public portion of the key. This operation requires the keys/verify permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm The signing/verification algorithm. For more information on possible algorithm types, see - * JsonWebKeySignatureAlgorithm. - * @param digest The digest used for signing. - * @param signature The signature to be verified. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key verify result on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono verifyAsync(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { - return verifyWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, digest, signature, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + return FluxUtil + .withContext(context -> service.verify(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + keyName, keyVersion, contentType, accept, parameters, requestOptions, context)); } /** * Verifies a signature using a specified key. - * + * * The VERIFY operation is applicable to symmetric keys stored in Azure Key Vault. VERIFY is not strictly necessary * for asymmetric keys stored in Azure Key Vault since signature verification can be performed using the public * portion of the key but this operation is supported as a convenience for callers that only have a key-reference * and not the public portion of the key. This operation requires the keys/verify permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     alg: String(PS256/PS384/PS512/RS256/RS384/RS512/RSNULL/ES256/ES384/ES512/ES256K) (Required)
          +     *     digest: Base64Url (Required)
          +     *     value: Base64Url (Required)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * * @param keyName The name of the key. * @param keyVersion The version of the key. - * @param algorithm The signing/verification algorithm. For more information on possible algorithm types, see - * JsonWebKeySignatureAlgorithm. - * @param digest The digest used for signing. - * @param signature The signature to be verified. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param parameters The parameters for verify operations. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the key verify result along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response verifyWithResponse(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { + public Response verifyWithResponse(String keyName, String keyVersion, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - KeyVerifyParameters parameters = new KeyVerifyParameters(); - parameters.setAlgorithm(algorithm); - parameters.setDigest(digest); - parameters.setSignature(signature); - return service.verifySync(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, context); - } - - /** - * Verifies a signature using a specified key. - * - * The VERIFY operation is applicable to symmetric keys stored in Azure Key Vault. VERIFY is not strictly necessary - * for asymmetric keys stored in Azure Key Vault since signature verification can be performed using the public - * portion of the key but this operation is supported as a convenience for callers that only have a key-reference - * and not the public portion of the key. This operation requires the keys/verify permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm The signing/verification algorithm. For more information on possible algorithm types, see - * JsonWebKeySignatureAlgorithm. - * @param digest The digest used for signing. - * @param signature The signature to be verified. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key verify result. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyVerifyResult verify(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature) { - return verifyWithResponse(vaultBaseUrl, keyName, keyVersion, algorithm, digest, signature, Context.NONE) - .getValue(); - } - - /** - * Wraps a symmetric key using a specified key. - * - * The WRAP operation supports encryption of a symmetric key using a key encryption key that has previously been - * stored in an Azure Key Vault. The WRAP operation is only strictly necessary for symmetric keys stored in Azure - * Key Vault since protection with an asymmetric key can be performed using the public portion of the key. This - * operation is supported for asymmetric keys as a convenience for callers that have a key-reference but do not have - * access to the public key material. This operation requires the keys/wrapKey permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> wrapKeyWithResponseAsync(String vaultBaseUrl, String keyName, - String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag) { - return FluxUtil.withContext(context -> wrapKeyWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, - value, iv, aad, tag, context)); + return service.verifySync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), keyName, keyVersion, + contentType, accept, parameters, requestOptions, Context.NONE); } /** * Wraps a symmetric key using a specified key. - * + * * The WRAP operation supports encryption of a symmetric key using a key encryption key that has previously been * stored in an Azure Key Vault. The WRAP operation is only strictly necessary for symmetric keys stored in Azure * Key Vault since protection with an asymmetric key can be performed using the public portion of the key. This * operation is supported for asymmetric keys as a convenience for callers that have a key-reference but do not have * access to the public key material. This operation requires the keys/wrapKey permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     alg: String(RSA-OAEP/RSA-OAEP-256/RSA1_5/A128GCM/A192GCM/A256GCM/A128KW/A192KW/A256KW/A128CBC/A192CBC/A256CBC/A128CBCPAD/A192CBCPAD/A256CBCPAD/CKM_AES_KEY_WRAP/CKM_AES_KEY_WRAP_PAD) (Required)
          +     *     value: Base64Url (Required)
          +     *     iv: Base64Url (Optional)
          +     *     aad: Base64Url (Optional)
          +     *     tag: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kid: String (Optional)
          +     *     value: Base64Url (Optional)
          +     *     iv: Base64Url (Optional)
          +     *     tag: Base64Url (Optional)
          +     *     aad: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          + * * @param keyName The name of the key. * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param parameters The parameters for wrap operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the key operation result along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> wrapKeyWithResponseAsync(String vaultBaseUrl, String keyName, - String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag, - Context context) { + public Mono> wrapKeyWithResponseAsync(String keyName, String keyVersion, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - KeyOperationsParameters parameters = new KeyOperationsParameters(); - parameters.setAlgorithm(algorithm); - parameters.setValue(value); - parameters.setIv(iv); - parameters.setAad(aad); - parameters.setTag(tag); - return service.wrapKey(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, context); - } - - /** - * Wraps a symmetric key using a specified key. - * - * The WRAP operation supports encryption of a symmetric key using a key encryption key that has previously been - * stored in an Azure Key Vault. The WRAP operation is only strictly necessary for symmetric keys stored in Azure - * Key Vault since protection with an asymmetric key can be performed using the public portion of the key. This - * operation is supported for asymmetric keys as a convenience for callers that have a key-reference but do not have - * access to the public key material. This operation requires the keys/wrapKey permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono wrapKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag) { - return wrapKeyWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value, iv, aad, tag) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Wraps a symmetric key using a specified key. - * - * The WRAP operation supports encryption of a symmetric key using a key encryption key that has previously been - * stored in an Azure Key Vault. The WRAP operation is only strictly necessary for symmetric keys stored in Azure - * Key Vault since protection with an asymmetric key can be performed using the public portion of the key. This - * operation is supported for asymmetric keys as a convenience for callers that have a key-reference but do not have - * access to the public key material. This operation requires the keys/wrapKey permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono wrapKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag, Context context) { - return wrapKeyWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value, iv, aad, tag, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + return FluxUtil + .withContext(context -> service.wrapKey(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + keyName, keyVersion, contentType, accept, parameters, requestOptions, context)); } /** * Wraps a symmetric key using a specified key. - * + * * The WRAP operation supports encryption of a symmetric key using a key encryption key that has previously been * stored in an Azure Key Vault. The WRAP operation is only strictly necessary for symmetric keys stored in Azure * Key Vault since protection with an asymmetric key can be performed using the public portion of the key. This * operation is supported for asymmetric keys as a convenience for callers that have a key-reference but do not have * access to the public key material. This operation requires the keys/wrapKey permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     alg: String(RSA-OAEP/RSA-OAEP-256/RSA1_5/A128GCM/A192GCM/A256GCM/A128KW/A192KW/A256KW/A128CBC/A192CBC/A256CBC/A128CBCPAD/A192CBCPAD/A256CBCPAD/CKM_AES_KEY_WRAP/CKM_AES_KEY_WRAP_PAD) (Required)
          +     *     value: Base64Url (Required)
          +     *     iv: Base64Url (Optional)
          +     *     aad: Base64Url (Optional)
          +     *     tag: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kid: String (Optional)
          +     *     value: Base64Url (Optional)
          +     *     iv: Base64Url (Optional)
          +     *     tag: Base64Url (Optional)
          +     *     aad: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          + * * @param keyName The name of the key. * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param parameters The parameters for wrap operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the key operation result along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response wrapKeyWithResponse(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag, Context context) { + public Response wrapKeyWithResponse(String keyName, String keyVersion, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - KeyOperationsParameters parameters = new KeyOperationsParameters(); - parameters.setAlgorithm(algorithm); - parameters.setValue(value); - parameters.setIv(iv); - parameters.setAad(aad); - parameters.setTag(tag); - return service.wrapKeySync(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, - context); - } - - /** - * Wraps a symmetric key using a specified key. - * - * The WRAP operation supports encryption of a symmetric key using a key encryption key that has previously been - * stored in an Azure Key Vault. The WRAP operation is only strictly necessary for symmetric keys stored in Azure - * Key Vault since protection with an asymmetric key can be performed using the public portion of the key. This - * operation is supported for asymmetric keys as a convenience for callers that have a key-reference but do not have - * access to the public key material. This operation requires the keys/wrapKey permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyOperationResult wrapKey(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag) { - return wrapKeyWithResponse(vaultBaseUrl, keyName, keyVersion, algorithm, value, iv, aad, tag, Context.NONE) - .getValue(); + return service.wrapKeySync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), keyName, keyVersion, + contentType, accept, parameters, requestOptions, Context.NONE); } /** * Unwraps a symmetric key using the specified key that was initially used for wrapping that key. - * + * * The UNWRAP operation supports decryption of a symmetric key using the target key encryption key. This operation * is the reverse of the WRAP operation. The UNWRAP operation applies to asymmetric and symmetric keys stored in * Azure Key Vault since it uses the private portion of the key. This operation requires the keys/unwrapKey * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     alg: String(RSA-OAEP/RSA-OAEP-256/RSA1_5/A128GCM/A192GCM/A256GCM/A128KW/A192KW/A256KW/A128CBC/A192CBC/A256CBC/A128CBCPAD/A192CBCPAD/A256CBCPAD/CKM_AES_KEY_WRAP/CKM_AES_KEY_WRAP_PAD) (Required)
          +     *     value: Base64Url (Required)
          +     *     iv: Base64Url (Optional)
          +     *     aad: Base64Url (Optional)
          +     *     tag: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kid: String (Optional)
          +     *     value: Base64Url (Optional)
          +     *     iv: Base64Url (Optional)
          +     *     tag: Base64Url (Optional)
          +     *     aad: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          + * * @param keyName The name of the key. * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param parameters The parameters for the key operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the key operation result along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> unwrapKeyWithResponseAsync(String vaultBaseUrl, String keyName, - String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag) { - return FluxUtil.withContext(context -> unwrapKeyWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, - value, iv, aad, tag, context)); + public Mono> unwrapKeyWithResponseAsync(String keyName, String keyVersion, + BinaryData parameters, RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.unwrapKey(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + keyName, keyVersion, contentType, accept, parameters, requestOptions, context)); } /** * Unwraps a symmetric key using the specified key that was initially used for wrapping that key. - * + * * The UNWRAP operation supports decryption of a symmetric key using the target key encryption key. This operation * is the reverse of the WRAP operation. The UNWRAP operation applies to asymmetric and symmetric keys stored in * Azure Key Vault since it uses the private portion of the key. This operation requires the keys/unwrapKey * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     alg: String(RSA-OAEP/RSA-OAEP-256/RSA1_5/A128GCM/A192GCM/A256GCM/A128KW/A192KW/A256KW/A128CBC/A192CBC/A256CBC/A128CBCPAD/A192CBCPAD/A256CBCPAD/CKM_AES_KEY_WRAP/CKM_AES_KEY_WRAP_PAD) (Required)
          +     *     value: Base64Url (Required)
          +     *     iv: Base64Url (Optional)
          +     *     aad: Base64Url (Optional)
          +     *     tag: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kid: String (Optional)
          +     *     value: Base64Url (Optional)
          +     *     iv: Base64Url (Optional)
          +     *     tag: Base64Url (Optional)
          +     *     aad: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          + * * @param keyName The name of the key. * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> unwrapKeyWithResponseAsync(String vaultBaseUrl, String keyName, - String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag, - Context context) { - final String accept = "application/json"; - KeyOperationsParameters parameters = new KeyOperationsParameters(); - parameters.setAlgorithm(algorithm); - parameters.setValue(value); - parameters.setIv(iv); - parameters.setAad(aad); - parameters.setTag(tag); - return service.unwrapKey(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, context); - } - - /** - * Unwraps a symmetric key using the specified key that was initially used for wrapping that key. - * - * The UNWRAP operation supports decryption of a symmetric key using the target key encryption key. This operation - * is the reverse of the WRAP operation. The UNWRAP operation applies to asymmetric and symmetric keys stored in - * Azure Key Vault since it uses the private portion of the key. This operation requires the keys/unwrapKey - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono unwrapKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag) { - return unwrapKeyWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value, iv, aad, tag) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Unwraps a symmetric key using the specified key that was initially used for wrapping that key. - * - * The UNWRAP operation supports decryption of a symmetric key using the target key encryption key. This operation - * is the reverse of the WRAP operation. The UNWRAP operation applies to asymmetric and symmetric keys stored in - * Azure Key Vault since it uses the private portion of the key. This operation requires the keys/unwrapKey - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono unwrapKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag, Context context) { - return unwrapKeyWithResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value, iv, aad, tag, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Unwraps a symmetric key using the specified key that was initially used for wrapping that key. - * - * The UNWRAP operation supports decryption of a symmetric key using the target key encryption key. This operation - * is the reverse of the WRAP operation. The UNWRAP operation applies to asymmetric and symmetric keys stored in - * Azure Key Vault since it uses the private portion of the key. This operation requires the keys/unwrapKey - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param parameters The parameters for the key operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the key operation result along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response unwrapKeyWithResponse(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag, Context context) { - final String accept = "application/json"; - KeyOperationsParameters parameters = new KeyOperationsParameters(); - parameters.setAlgorithm(algorithm); - parameters.setValue(value); - parameters.setIv(iv); - parameters.setAad(aad); - parameters.setTag(tag); - return service.unwrapKeySync(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, - context); - } - - /** - * Unwraps a symmetric key using the specified key that was initially used for wrapping that key. - * - * The UNWRAP operation supports decryption of a symmetric key using the target key encryption key. This operation - * is the reverse of the WRAP operation. The UNWRAP operation applies to asymmetric and symmetric keys stored in - * Azure Key Vault since it uses the private portion of the key. This operation requires the keys/unwrapKey - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param keyVersion The version of the key. - * @param algorithm algorithm identifier. - * @param value The value parameter. - * @param iv Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * @param aad Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. - * @param tag The tag to authenticate when performing decryption with an authenticated algorithm. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key operation result. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyOperationResult unwrapKey(String vaultBaseUrl, String keyName, String keyVersion, - JsonWebKeyEncryptionAlgorithm algorithm, byte[] value, byte[] iv, byte[] aad, byte[] tag) { - return unwrapKeyWithResponse(vaultBaseUrl, keyName, keyVersion, algorithm, value, iv, aad, tag, Context.NONE) - .getValue(); - } - - /** - * Releases a key. - * - * The release key operation is applicable to all key types. The target key must be marked exportable. This - * operation requires the keys/release permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to get. - * @param keyVersion Adding the version parameter retrieves a specific version of a key. - * @param targetAttestationToken The attestation assertion for the target of the key release. - * @param nonce A client provided nonce for freshness. - * @param enc The encryption algorithm to use to protected the exported key material. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the release result, containing the released key along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> releaseWithResponseAsync(String vaultBaseUrl, String keyName, - String keyVersion, String targetAttestationToken, String nonce, KeyExportEncryptionAlgorithm enc) { - return FluxUtil.withContext(context -> releaseWithResponseAsync(vaultBaseUrl, keyName, keyVersion, - targetAttestationToken, nonce, enc, context)); - } - - /** - * Releases a key. - * - * The release key operation is applicable to all key types. The target key must be marked exportable. This - * operation requires the keys/release permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to get. - * @param keyVersion Adding the version parameter retrieves a specific version of a key. - * @param targetAttestationToken The attestation assertion for the target of the key release. - * @param nonce A client provided nonce for freshness. - * @param enc The encryption algorithm to use to protected the exported key material. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the release result, containing the released key along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> releaseWithResponseAsync(String vaultBaseUrl, String keyName, - String keyVersion, String targetAttestationToken, String nonce, KeyExportEncryptionAlgorithm enc, - Context context) { - final String accept = "application/json"; - KeyReleaseParameters parameters = new KeyReleaseParameters(); - parameters.setTargetAttestationToken(targetAttestationToken); - parameters.setNonce(nonce); - parameters.setEnc(enc); - return service.release(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, context); - } - - /** - * Releases a key. - * - * The release key operation is applicable to all key types. The target key must be marked exportable. This - * operation requires the keys/release permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to get. - * @param keyVersion Adding the version parameter retrieves a specific version of a key. - * @param targetAttestationToken The attestation assertion for the target of the key release. - * @param nonce A client provided nonce for freshness. - * @param enc The encryption algorithm to use to protected the exported key material. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the release result, containing the released key on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono releaseAsync(String vaultBaseUrl, String keyName, String keyVersion, - String targetAttestationToken, String nonce, KeyExportEncryptionAlgorithm enc) { - return releaseWithResponseAsync(vaultBaseUrl, keyName, keyVersion, targetAttestationToken, nonce, enc) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Releases a key. - * - * The release key operation is applicable to all key types. The target key must be marked exportable. This - * operation requires the keys/release permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to get. - * @param keyVersion Adding the version parameter retrieves a specific version of a key. - * @param targetAttestationToken The attestation assertion for the target of the key release. - * @param nonce A client provided nonce for freshness. - * @param enc The encryption algorithm to use to protected the exported key material. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the release result, containing the released key on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono releaseAsync(String vaultBaseUrl, String keyName, String keyVersion, - String targetAttestationToken, String nonce, KeyExportEncryptionAlgorithm enc, Context context) { - return releaseWithResponseAsync(vaultBaseUrl, keyName, keyVersion, targetAttestationToken, nonce, enc, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Releases a key. - * - * The release key operation is applicable to all key types. The target key must be marked exportable. This - * operation requires the keys/release permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to get. - * @param keyVersion Adding the version parameter retrieves a specific version of a key. - * @param targetAttestationToken The attestation assertion for the target of the key release. - * @param nonce A client provided nonce for freshness. - * @param enc The encryption algorithm to use to protected the exported key material. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the release result, containing the released key along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response releaseWithResponse(String vaultBaseUrl, String keyName, String keyVersion, - String targetAttestationToken, String nonce, KeyExportEncryptionAlgorithm enc, Context context) { - final String accept = "application/json"; - KeyReleaseParameters parameters = new KeyReleaseParameters(); - parameters.setTargetAttestationToken(targetAttestationToken); - parameters.setNonce(nonce); - parameters.setEnc(enc); - return service.releaseSync(vaultBaseUrl, keyName, keyVersion, this.getApiVersion(), parameters, accept, - context); - } - - /** - * Releases a key. - * - * The release key operation is applicable to all key types. The target key must be marked exportable. This - * operation requires the keys/release permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key to get. - * @param keyVersion Adding the version parameter retrieves a specific version of a key. - * @param targetAttestationToken The attestation assertion for the target of the key release. - * @param nonce A client provided nonce for freshness. - * @param enc The encryption algorithm to use to protected the exported key material. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the release result, containing the released key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public ReleaseKeyResult release(String vaultBaseUrl, String keyName, String keyVersion, - String targetAttestationToken, String nonce, KeyExportEncryptionAlgorithm enc) { - return releaseWithResponse(vaultBaseUrl, keyName, keyVersion, targetAttestationToken, nonce, enc, Context.NONE) - .getValue(); - } - - /** - * Lists the deleted keys in the specified vault. - * - * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a - * deleted key. This operation includes deletion-specific information. The Get Deleted Keys operation is applicable - * for vaults enabled for soft-delete. While the operation can be invoked on any vault, it will return an error if - * invoked on a non soft-delete enabled vault. This operation requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of keys that have been deleted in this vault along with {@link PagedResponse} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedKeysSinglePageAsync(String vaultBaseUrl, Integer maxresults) { - final String accept = "application/json"; - return FluxUtil - .withContext( - context -> service.getDeletedKeys(vaultBaseUrl, maxresults, this.getApiVersion(), accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * Lists the deleted keys in the specified vault. - * - * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a - * deleted key. This operation includes deletion-specific information. The Get Deleted Keys operation is applicable - * for vaults enabled for soft-delete. While the operation can be invoked on any vault, it will return an error if - * invoked on a non soft-delete enabled vault. This operation requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of keys that have been deleted in this vault along with {@link PagedResponse} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedKeysSinglePageAsync(String vaultBaseUrl, Integer maxresults, - Context context) { - final String accept = "application/json"; - return service.getDeletedKeys(vaultBaseUrl, maxresults, this.getApiVersion(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * Lists the deleted keys in the specified vault. - * - * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a - * deleted key. This operation includes deletion-specific information. The Get Deleted Keys operation is applicable - * for vaults enabled for soft-delete. While the operation can be invoked on any vault, it will return an error if - * invoked on a non soft-delete enabled vault. This operation requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of keys that have been deleted in this vault as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getDeletedKeysAsync(String vaultBaseUrl, Integer maxresults) { - return new PagedFlux<>(() -> getDeletedKeysSinglePageAsync(vaultBaseUrl, maxresults), - nextLink -> getDeletedKeysNextSinglePageAsync(nextLink, vaultBaseUrl)); - } - - /** - * Lists the deleted keys in the specified vault. - * - * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a - * deleted key. This operation includes deletion-specific information. The Get Deleted Keys operation is applicable - * for vaults enabled for soft-delete. While the operation can be invoked on any vault, it will return an error if - * invoked on a non soft-delete enabled vault. This operation requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of keys that have been deleted in this vault as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getDeletedKeysAsync(String vaultBaseUrl, Integer maxresults, Context context) { - return new PagedFlux<>(() -> getDeletedKeysSinglePageAsync(vaultBaseUrl, maxresults, context), - nextLink -> getDeletedKeysNextSinglePageAsync(nextLink, vaultBaseUrl, context)); - } - - /** - * Lists the deleted keys in the specified vault. - * - * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a - * deleted key. This operation includes deletion-specific information. The Get Deleted Keys operation is applicable - * for vaults enabled for soft-delete. While the operation can be invoked on any vault, it will return an error if - * invoked on a non soft-delete enabled vault. This operation requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of keys that have been deleted in this vault along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getDeletedKeysSinglePage(String vaultBaseUrl, Integer maxresults) { - final String accept = "application/json"; - Response res - = service.getDeletedKeysSync(vaultBaseUrl, maxresults, this.getApiVersion(), accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * Lists the deleted keys in the specified vault. - * - * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a - * deleted key. This operation includes deletion-specific information. The Get Deleted Keys operation is applicable - * for vaults enabled for soft-delete. While the operation can be invoked on any vault, it will return an error if - * invoked on a non soft-delete enabled vault. This operation requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of keys that have been deleted in this vault along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getDeletedKeysSinglePage(String vaultBaseUrl, Integer maxresults, - Context context) { - final String accept = "application/json"; - Response res - = service.getDeletedKeysSync(vaultBaseUrl, maxresults, this.getApiVersion(), accept, context); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * Lists the deleted keys in the specified vault. - * - * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a - * deleted key. This operation includes deletion-specific information. The Get Deleted Keys operation is applicable - * for vaults enabled for soft-delete. While the operation can be invoked on any vault, it will return an error if - * invoked on a non soft-delete enabled vault. This operation requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of keys that have been deleted in this vault as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getDeletedKeys(String vaultBaseUrl, Integer maxresults) { - return new PagedIterable<>(() -> getDeletedKeysSinglePage(vaultBaseUrl, maxresults, Context.NONE), - nextLink -> getDeletedKeysNextSinglePage(nextLink, vaultBaseUrl)); - } - - /** - * Lists the deleted keys in the specified vault. - * - * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a - * deleted key. This operation includes deletion-specific information. The Get Deleted Keys operation is applicable - * for vaults enabled for soft-delete. While the operation can be invoked on any vault, it will return an error if - * invoked on a non soft-delete enabled vault. This operation requires the keys/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of keys that have been deleted in this vault as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getDeletedKeys(String vaultBaseUrl, Integer maxresults, Context context) { - return new PagedIterable<>(() -> getDeletedKeysSinglePage(vaultBaseUrl, maxresults, context), - nextLink -> getDeletedKeysNextSinglePage(nextLink, vaultBaseUrl, context)); - } - - /** - * Gets the public part of a deleted key. - * - * The Get Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked on - * any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the - * keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info along with - * {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedKeyWithResponseAsync(String vaultBaseUrl, String keyName) { - return FluxUtil.withContext(context -> getDeletedKeyWithResponseAsync(vaultBaseUrl, keyName, context)); - } - - /** - * Gets the public part of a deleted key. - * - * The Get Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked on - * any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the - * keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info along with - * {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedKeyWithResponseAsync(String vaultBaseUrl, String keyName, - Context context) { - final String accept = "application/json"; - return service.getDeletedKey(vaultBaseUrl, keyName, this.getApiVersion(), accept, context); - } - - /** - * Gets the public part of a deleted key. - * - * The Get Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked on - * any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the - * keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getDeletedKeyAsync(String vaultBaseUrl, String keyName) { - return getDeletedKeyWithResponseAsync(vaultBaseUrl, keyName).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Gets the public part of a deleted key. - * - * The Get Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked on - * any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the - * keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getDeletedKeyAsync(String vaultBaseUrl, String keyName, Context context) { - return getDeletedKeyWithResponseAsync(vaultBaseUrl, keyName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Gets the public part of a deleted key. - * - * The Get Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked on - * any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the - * keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info along with - * {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getDeletedKeyWithResponse(String vaultBaseUrl, String keyName, Context context) { - final String accept = "application/json"; - return service.getDeletedKeySync(vaultBaseUrl, keyName, this.getApiVersion(), accept, context); - } - - /** - * Gets the public part of a deleted key. - * - * The Get Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked on - * any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the - * keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public DeletedKeyBundle getDeletedKey(String vaultBaseUrl, String keyName) { - return getDeletedKeyWithResponse(vaultBaseUrl, keyName, Context.NONE).getValue(); - } - - /** - * Permanently deletes the specified key. - * - * The Purge Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked - * on any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the - * keys/purge permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> purgeDeletedKeyWithResponseAsync(String vaultBaseUrl, String keyName) { - return FluxUtil.withContext(context -> purgeDeletedKeyWithResponseAsync(vaultBaseUrl, keyName, context)); - } - - /** - * Permanently deletes the specified key. - * - * The Purge Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked - * on any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the - * keys/purge permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> purgeDeletedKeyWithResponseAsync(String vaultBaseUrl, String keyName, Context context) { - final String accept = "application/json"; - return service.purgeDeletedKey(vaultBaseUrl, keyName, this.getApiVersion(), accept, context); - } - - /** - * Permanently deletes the specified key. - * - * The Purge Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked - * on any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the - * keys/purge permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono purgeDeletedKeyAsync(String vaultBaseUrl, String keyName) { - return purgeDeletedKeyWithResponseAsync(vaultBaseUrl, keyName).flatMap(ignored -> Mono.empty()); - } - - /** - * Permanently deletes the specified key. - * - * The Purge Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked - * on any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the - * keys/purge permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono purgeDeletedKeyAsync(String vaultBaseUrl, String keyName, Context context) { - return purgeDeletedKeyWithResponseAsync(vaultBaseUrl, keyName, context).flatMap(ignored -> Mono.empty()); - } - - /** - * Permanently deletes the specified key. - * - * The Purge Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked - * on any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the - * keys/purge permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response purgeDeletedKeyWithResponse(String vaultBaseUrl, String keyName, Context context) { - final String accept = "application/json"; - return service.purgeDeletedKeySync(vaultBaseUrl, keyName, this.getApiVersion(), accept, context); - } - - /** - * Permanently deletes the specified key. - * - * The Purge Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked - * on any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the - * keys/purge permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void purgeDeletedKey(String vaultBaseUrl, String keyName) { - purgeDeletedKeyWithResponse(vaultBaseUrl, keyName, Context.NONE); - } - - /** - * Recovers the deleted key to its latest version. - * - * The Recover Deleted Key operation is applicable for deleted keys in soft-delete enabled vaults. It recovers the - * deleted key back to its latest version under /keys. An attempt to recover an non-deleted key will return an - * error. Consider this the inverse of the delete operation on soft-delete enabled vaults. This operation requires - * the keys/recover permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the deleted key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> recoverDeletedKeyWithResponseAsync(String vaultBaseUrl, String keyName) { - return FluxUtil.withContext(context -> recoverDeletedKeyWithResponseAsync(vaultBaseUrl, keyName, context)); - } - - /** - * Recovers the deleted key to its latest version. - * - * The Recover Deleted Key operation is applicable for deleted keys in soft-delete enabled vaults. It recovers the - * deleted key back to its latest version under /keys. An attempt to recover an non-deleted key will return an - * error. Consider this the inverse of the delete operation on soft-delete enabled vaults. This operation requires - * the keys/recover permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the deleted key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> recoverDeletedKeyWithResponseAsync(String vaultBaseUrl, String keyName, - Context context) { - final String accept = "application/json"; - return service.recoverDeletedKey(vaultBaseUrl, keyName, this.getApiVersion(), accept, context); - } - - /** - * Recovers the deleted key to its latest version. - * - * The Recover Deleted Key operation is applicable for deleted keys in soft-delete enabled vaults. It recovers the - * deleted key back to its latest version under /keys. An attempt to recover an non-deleted key will return an - * error. Consider this the inverse of the delete operation on soft-delete enabled vaults. This operation requires - * the keys/recover permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the deleted key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono recoverDeletedKeyAsync(String vaultBaseUrl, String keyName) { - return recoverDeletedKeyWithResponseAsync(vaultBaseUrl, keyName) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Recovers the deleted key to its latest version. - * - * The Recover Deleted Key operation is applicable for deleted keys in soft-delete enabled vaults. It recovers the - * deleted key back to its latest version under /keys. An attempt to recover an non-deleted key will return an - * error. Consider this the inverse of the delete operation on soft-delete enabled vaults. This operation requires - * the keys/recover permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the deleted key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono recoverDeletedKeyAsync(String vaultBaseUrl, String keyName, Context context) { - return recoverDeletedKeyWithResponseAsync(vaultBaseUrl, keyName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Recovers the deleted key to its latest version. - * - * The Recover Deleted Key operation is applicable for deleted keys in soft-delete enabled vaults. It recovers the - * deleted key back to its latest version under /keys. An attempt to recover an non-deleted key will return an - * error. Consider this the inverse of the delete operation on soft-delete enabled vaults. This operation requires - * the keys/recover permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the deleted key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response recoverDeletedKeyWithResponse(String vaultBaseUrl, String keyName, Context context) { - final String accept = "application/json"; - return service.recoverDeletedKeySync(vaultBaseUrl, keyName, this.getApiVersion(), accept, context); - } - - /** - * Recovers the deleted key to its latest version. - * - * The Recover Deleted Key operation is applicable for deleted keys in soft-delete enabled vaults. It recovers the - * deleted key back to its latest version under /keys. An attempt to recover an non-deleted key will return an - * error. Consider this the inverse of the delete operation on soft-delete enabled vaults. This operation requires - * the keys/recover permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the deleted key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a KeyBundle consisting of a WebKey plus its attributes. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyBundle recoverDeletedKey(String vaultBaseUrl, String keyName) { - return recoverDeletedKeyWithResponse(vaultBaseUrl, keyName, Context.NONE).getValue(); - } - - /** - * Lists the policy for a key. - * - * The GetKeyRotationPolicy operation returns the specified key policy resources in the specified key vault. This - * operation requires the keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key in a given key vault. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a key along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getKeyRotationPolicyWithResponseAsync(String vaultBaseUrl, - String keyName) { - return FluxUtil.withContext(context -> getKeyRotationPolicyWithResponseAsync(vaultBaseUrl, keyName, context)); - } - - /** - * Lists the policy for a key. - * - * The GetKeyRotationPolicy operation returns the specified key policy resources in the specified key vault. This - * operation requires the keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key in a given key vault. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a key along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getKeyRotationPolicyWithResponseAsync(String vaultBaseUrl, String keyName, - Context context) { - final String accept = "application/json"; - return service.getKeyRotationPolicy(vaultBaseUrl, keyName, this.getApiVersion(), accept, context); - } - - /** - * Lists the policy for a key. - * - * The GetKeyRotationPolicy operation returns the specified key policy resources in the specified key vault. This - * operation requires the keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key in a given key vault. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a key on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getKeyRotationPolicyAsync(String vaultBaseUrl, String keyName) { - return getKeyRotationPolicyWithResponseAsync(vaultBaseUrl, keyName) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Lists the policy for a key. - * - * The GetKeyRotationPolicy operation returns the specified key policy resources in the specified key vault. This - * operation requires the keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key in a given key vault. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a key on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getKeyRotationPolicyAsync(String vaultBaseUrl, String keyName, Context context) { - return getKeyRotationPolicyWithResponseAsync(vaultBaseUrl, keyName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Lists the policy for a key. - * - * The GetKeyRotationPolicy operation returns the specified key policy resources in the specified key vault. This - * operation requires the keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key in a given key vault. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a key along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getKeyRotationPolicyWithResponse(String vaultBaseUrl, String keyName, - Context context) { - final String accept = "application/json"; - return service.getKeyRotationPolicySync(vaultBaseUrl, keyName, this.getApiVersion(), accept, context); - } - - /** - * Lists the policy for a key. - * - * The GetKeyRotationPolicy operation returns the specified key policy resources in the specified key vault. This - * operation requires the keys/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key in a given key vault. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a key. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyRotationPolicy getKeyRotationPolicy(String vaultBaseUrl, String keyName) { - return getKeyRotationPolicyWithResponse(vaultBaseUrl, keyName, Context.NONE).getValue(); + public Response unwrapKeyWithResponse(String keyName, String keyVersion, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return service.unwrapKeySync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), keyName, keyVersion, + contentType, accept, parameters, requestOptions, Context.NONE); } /** - * Updates the rotation policy for a key. - * - * Set specified members in the key policy. Leave others as undefined. This operation requires the keys/update - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key in the given vault. - * @param keyRotationPolicy The policy for the key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a key along with {@link Response} on successful completion of {@link Mono}. + * Releases a key. + * + * The release key operation is applicable to all key types. The target key must be marked exportable. This + * operation requires the keys/release permission. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     target: String (Required)
          +     *     nonce: String (Optional)
          +     *     enc: String(CKM_RSA_AES_KEY_WRAP/RSA_AES_KEY_WRAP_256/RSA_AES_KEY_WRAP_384) (Optional)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: String (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param keyName The name of the key to get. + * @param keyVersion Adding the version parameter retrieves a specific version of a key. + * @param parameters The parameters for the key release operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the release result, containing the released key along with {@link Response} on successful completion of + * {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> updateKeyRotationPolicyWithResponseAsync(String vaultBaseUrl, - String keyName, KeyRotationPolicy keyRotationPolicy) { - return FluxUtil.withContext( - context -> updateKeyRotationPolicyWithResponseAsync(vaultBaseUrl, keyName, keyRotationPolicy, context)); + public Mono> releaseWithResponseAsync(String keyName, String keyVersion, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.release(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + keyName, keyVersion, contentType, accept, parameters, requestOptions, context)); } /** - * Updates the rotation policy for a key. - * - * Set specified members in the key policy. Leave others as undefined. This operation requires the keys/update - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key in the given vault. - * @param keyRotationPolicy The policy for the key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a key along with {@link Response} on successful completion of {@link Mono}. + * Releases a key. + * + * The release key operation is applicable to all key types. The target key must be marked exportable. This + * operation requires the keys/release permission. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     target: String (Required)
          +     *     nonce: String (Optional)
          +     *     enc: String(CKM_RSA_AES_KEY_WRAP/RSA_AES_KEY_WRAP_256/RSA_AES_KEY_WRAP_384) (Optional)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: String (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param keyName The name of the key to get. + * @param keyVersion Adding the version parameter retrieves a specific version of a key. + * @param parameters The parameters for the key release operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the release result, containing the released key along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> updateKeyRotationPolicyWithResponseAsync(String vaultBaseUrl, - String keyName, KeyRotationPolicy keyRotationPolicy, Context context) { + public Response releaseWithResponse(String keyName, String keyVersion, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - return service.updateKeyRotationPolicy(vaultBaseUrl, keyName, this.getApiVersion(), keyRotationPolicy, accept, - context); + return service.releaseSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), keyName, keyVersion, + contentType, accept, parameters, requestOptions, Context.NONE); } /** - * Updates the rotation policy for a key. - * - * Set specified members in the key policy. Leave others as undefined. This operation requires the keys/update - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key in the given vault. - * @param keyRotationPolicy The policy for the key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a key on successful completion of {@link Mono}. + * Lists the deleted keys in the specified vault. + * + * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a + * deleted key. This operation includes deletion-specific information. The Get Deleted Keys operation is applicable + * for vaults enabled for soft-delete. While the operation can be invoked on any vault, it will return an error if + * invoked on a non soft-delete enabled vault. This operation requires the keys/list permission. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kid: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a list of keys that have been deleted in this vault along with {@link PagedResponse} on successful + * completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono updateKeyRotationPolicyAsync(String vaultBaseUrl, String keyName, - KeyRotationPolicy keyRotationPolicy) { - return updateKeyRotationPolicyWithResponseAsync(vaultBaseUrl, keyName, keyRotationPolicy) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + private Mono> getDeletedKeysSinglePageAsync(RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.getDeletedKeys(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), accept, requestOptions, context)) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } /** - * Updates the rotation policy for a key. - * - * Set specified members in the key policy. Leave others as undefined. This operation requires the keys/update - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key in the given vault. - * @param keyRotationPolicy The policy for the key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a key on successful completion of {@link Mono}. + * Lists the deleted keys in the specified vault. + * + * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a + * deleted key. This operation includes deletion-specific information. The Get Deleted Keys operation is applicable + * for vaults enabled for soft-delete. While the operation can be invoked on any vault, it will return an error if + * invoked on a non soft-delete enabled vault. This operation requires the keys/list permission. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kid: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a list of keys that have been deleted in this vault as paginated response with {@link PagedFlux}. */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono updateKeyRotationPolicyAsync(String vaultBaseUrl, String keyName, - KeyRotationPolicy keyRotationPolicy, Context context) { - return updateKeyRotationPolicyWithResponseAsync(vaultBaseUrl, keyName, keyRotationPolicy, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux getDeletedKeysAsync(RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedFlux<>(() -> getDeletedKeysSinglePageAsync(requestOptions), + nextLink -> getDeletedKeysNextSinglePageAsync(nextLink, requestOptionsForNextPage)); } /** - * Updates the rotation policy for a key. - * - * Set specified members in the key policy. Leave others as undefined. This operation requires the keys/update - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key in the given vault. - * @param keyRotationPolicy The policy for the key. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a key along with {@link Response}. + * Lists the deleted keys in the specified vault. + * + * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a + * deleted key. This operation includes deletion-specific information. The Get Deleted Keys operation is applicable + * for vaults enabled for soft-delete. While the operation can be invoked on any vault, it will return an error if + * invoked on a non soft-delete enabled vault. This operation requires the keys/list permission. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kid: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a list of keys that have been deleted in this vault along with {@link PagedResponse}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response updateKeyRotationPolicyWithResponse(String vaultBaseUrl, String keyName, - KeyRotationPolicy keyRotationPolicy, Context context) { + private PagedResponse getDeletedKeysSinglePage(RequestOptions requestOptions) { final String accept = "application/json"; - return service.updateKeyRotationPolicySync(vaultBaseUrl, keyName, this.getApiVersion(), keyRotationPolicy, - accept, context); + Response res = service.getDeletedKeysSync(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), accept, requestOptions, Context.NONE); + return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } /** - * Updates the rotation policy for a key. - * - * Set specified members in the key policy. Leave others as undefined. This operation requires the keys/update - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param keyName The name of the key in the given vault. - * @param keyRotationPolicy The policy for the key. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return management policy for a key. + * Lists the deleted keys in the specified vault. + * + * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a + * deleted key. This operation includes deletion-specific information. The Get Deleted Keys operation is applicable + * for vaults enabled for soft-delete. While the operation can be invoked on any vault, it will return an error if + * invoked on a non soft-delete enabled vault. This operation requires the keys/list permission. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kid: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a list of keys that have been deleted in this vault as paginated response with {@link PagedIterable}. */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KeyRotationPolicy updateKeyRotationPolicy(String vaultBaseUrl, String keyName, - KeyRotationPolicy keyRotationPolicy) { - return updateKeyRotationPolicyWithResponse(vaultBaseUrl, keyName, keyRotationPolicy, Context.NONE).getValue(); + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable getDeletedKeys(RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedIterable<>(() -> getDeletedKeysSinglePage(requestOptions), + nextLink -> getDeletedKeysNextSinglePage(nextLink, requestOptionsForNextPage)); } /** - * Get the requested number of bytes containing random values. - * - * Get the requested number of bytes containing random values from a managed HSM. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param count The requested number of random bytes. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the requested number of bytes containing random values from a managed HSM along with {@link Response} on + * Gets the public part of a deleted key. + * + * The Get Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked on + * any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the + * keys/get permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     key (Optional): {
          +     *         kid: String (Optional)
          +     *         kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *         key_ops (Optional): [
          +     *             String (Optional)
          +     *         ]
          +     *         n: Base64Url (Optional)
          +     *         e: Base64Url (Optional)
          +     *         d: Base64Url (Optional)
          +     *         dp: Base64Url (Optional)
          +     *         dq: Base64Url (Optional)
          +     *         qi: Base64Url (Optional)
          +     *         p: Base64Url (Optional)
          +     *         q: Base64Url (Optional)
          +     *         k: Base64Url (Optional)
          +     *         key_hsm: Base64Url (Optional)
          +     *         crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         x: Base64Url (Optional)
          +     *         y: Base64Url (Optional)
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     *     release_policy (Optional): {
          +     *         contentType: String (Optional)
          +     *         immutable: Boolean (Optional)
          +     *         data: Base64Url (Optional)
          +     *     }
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param keyName The name of the key. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the public part of a deleted key. + * + * The Get Deleted Key operation is applicable for soft-delete enabled vaults along with {@link Response} on * successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getRandomBytesWithResponseAsync(String vaultBaseUrl, int count) { - return FluxUtil.withContext(context -> getRandomBytesWithResponseAsync(vaultBaseUrl, count, context)); + public Mono> getDeletedKeyWithResponseAsync(String keyName, RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.getDeletedKey(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), keyName, accept, requestOptions, context)); } /** - * Get the requested number of bytes containing random values. - * - * Get the requested number of bytes containing random values from a managed HSM. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param count The requested number of random bytes. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the requested number of bytes containing random values from a managed HSM along with {@link Response} on - * successful completion of {@link Mono}. + * Gets the public part of a deleted key. + * + * The Get Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked on + * any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the + * keys/get permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     key (Optional): {
          +     *         kid: String (Optional)
          +     *         kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *         key_ops (Optional): [
          +     *             String (Optional)
          +     *         ]
          +     *         n: Base64Url (Optional)
          +     *         e: Base64Url (Optional)
          +     *         d: Base64Url (Optional)
          +     *         dp: Base64Url (Optional)
          +     *         dq: Base64Url (Optional)
          +     *         qi: Base64Url (Optional)
          +     *         p: Base64Url (Optional)
          +     *         q: Base64Url (Optional)
          +     *         k: Base64Url (Optional)
          +     *         key_hsm: Base64Url (Optional)
          +     *         crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         x: Base64Url (Optional)
          +     *         y: Base64Url (Optional)
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     *     release_policy (Optional): {
          +     *         contentType: String (Optional)
          +     *         immutable: Boolean (Optional)
          +     *         data: Base64Url (Optional)
          +     *     }
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param keyName The name of the key. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the public part of a deleted key. + * + * The Get Deleted Key operation is applicable for soft-delete enabled vaults along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getRandomBytesWithResponseAsync(String vaultBaseUrl, int count, - Context context) { + public Response getDeletedKeyWithResponse(String keyName, RequestOptions requestOptions) { final String accept = "application/json"; - GetRandomBytesRequest parameters = new GetRandomBytesRequest(); - parameters.setCount(count); - return service.getRandomBytes(vaultBaseUrl, this.getApiVersion(), parameters, accept, context); + return service.getDeletedKeySync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), keyName, accept, + requestOptions, Context.NONE); } /** - * Get the requested number of bytes containing random values. - * - * Get the requested number of bytes containing random values from a managed HSM. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param count The requested number of random bytes. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the requested number of bytes containing random values from a managed HSM on successful completion of - * {@link Mono}. + * Permanently deletes the specified key. + * + * The Purge Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked + * on any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the + * keys/purge permission. + * + * @param keyName The name of the key. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getRandomBytesAsync(String vaultBaseUrl, int count) { - return getRandomBytesWithResponseAsync(vaultBaseUrl, count).flatMap(res -> Mono.justOrEmpty(res.getValue())); + public Mono> purgeDeletedKeyWithResponseAsync(String keyName, RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.purgeDeletedKey(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), keyName, accept, requestOptions, context)); } /** - * Get the requested number of bytes containing random values. - * - * Get the requested number of bytes containing random values from a managed HSM. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param count The requested number of random bytes. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the requested number of bytes containing random values from a managed HSM on successful completion of - * {@link Mono}. + * Permanently deletes the specified key. + * + * The Purge Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked + * on any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the + * keys/purge permission. + * + * @param keyName The name of the key. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getRandomBytesAsync(String vaultBaseUrl, int count, Context context) { - return getRandomBytesWithResponseAsync(vaultBaseUrl, count, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + public Response purgeDeletedKeyWithResponse(String keyName, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.purgeDeletedKeySync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), keyName, + accept, requestOptions, Context.NONE); } /** - * Get the requested number of bytes containing random values. - * - * Get the requested number of bytes containing random values from a managed HSM. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param count The requested number of random bytes. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the requested number of bytes containing random values from a managed HSM along with {@link Response}. + * Recovers the deleted key to its latest version. + * + * The Recover Deleted Key operation is applicable for deleted keys in soft-delete enabled vaults. It recovers the + * deleted key back to its latest version under /keys. An attempt to recover an non-deleted key will return an + * error. Consider this the inverse of the delete operation on soft-delete enabled vaults. This operation requires + * the keys/recover permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     key (Optional): {
          +     *         kid: String (Optional)
          +     *         kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *         key_ops (Optional): [
          +     *             String (Optional)
          +     *         ]
          +     *         n: Base64Url (Optional)
          +     *         e: Base64Url (Optional)
          +     *         d: Base64Url (Optional)
          +     *         dp: Base64Url (Optional)
          +     *         dq: Base64Url (Optional)
          +     *         qi: Base64Url (Optional)
          +     *         p: Base64Url (Optional)
          +     *         q: Base64Url (Optional)
          +     *         k: Base64Url (Optional)
          +     *         key_hsm: Base64Url (Optional)
          +     *         crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         x: Base64Url (Optional)
          +     *         y: Base64Url (Optional)
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     *     release_policy (Optional): {
          +     *         contentType: String (Optional)
          +     *         immutable: Boolean (Optional)
          +     *         data: Base64Url (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + * @param keyName The name of the deleted key. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response} on successful + * completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response getRandomBytesWithResponse(String vaultBaseUrl, int count, Context context) { + public Mono> recoverDeletedKeyWithResponseAsync(String keyName, + RequestOptions requestOptions) { final String accept = "application/json"; - GetRandomBytesRequest parameters = new GetRandomBytesRequest(); - parameters.setCount(count); - return service.getRandomBytesSync(vaultBaseUrl, this.getApiVersion(), parameters, accept, context); + return FluxUtil.withContext(context -> service.recoverDeletedKey(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), keyName, accept, requestOptions, context)); } /** - * Get the requested number of bytes containing random values. - * - * Get the requested number of bytes containing random values from a managed HSM. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param count The requested number of random bytes. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the requested number of bytes containing random values from a managed HSM. + * Recovers the deleted key to its latest version. + * + * The Recover Deleted Key operation is applicable for deleted keys in soft-delete enabled vaults. It recovers the + * deleted key back to its latest version under /keys. An attempt to recover an non-deleted key will return an + * error. Consider this the inverse of the delete operation on soft-delete enabled vaults. This operation requires + * the keys/recover permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     key (Optional): {
          +     *         kid: String (Optional)
          +     *         kty: String(EC/EC-HSM/RSA/RSA-HSM/oct/oct-HSM) (Optional)
          +     *         key_ops (Optional): [
          +     *             String (Optional)
          +     *         ]
          +     *         n: Base64Url (Optional)
          +     *         e: Base64Url (Optional)
          +     *         d: Base64Url (Optional)
          +     *         dp: Base64Url (Optional)
          +     *         dq: Base64Url (Optional)
          +     *         qi: Base64Url (Optional)
          +     *         p: Base64Url (Optional)
          +     *         q: Base64Url (Optional)
          +     *         k: Base64Url (Optional)
          +     *         key_hsm: Base64Url (Optional)
          +     *         crv: String(P-256/P-384/P-521/P-256K) (Optional)
          +     *         x: Base64Url (Optional)
          +     *         y: Base64Url (Optional)
          +     *     }
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     *     release_policy (Optional): {
          +     *         contentType: String (Optional)
          +     *         immutable: Boolean (Optional)
          +     *         data: Base64Url (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + * @param keyName The name of the deleted key. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a KeyBundle consisting of a WebKey plus its attributes along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public RandomBytes getRandomBytes(String vaultBaseUrl, int count) { - return getRandomBytesWithResponse(vaultBaseUrl, count, Context.NONE).getValue(); + public Response recoverDeletedKeyWithResponse(String keyName, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.recoverDeletedKeySync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), keyName, + accept, requestOptions, Context.NONE); } /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result along with {@link PagedResponse} on successful completion of {@link Mono}. + * Lists the policy for a key. + * + * The GetKeyRotationPolicy operation returns the specified key policy resources in the specified key vault. This + * operation requires the keys/get permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     lifetimeActions (Optional): [
          +     *          (Optional){
          +     *             trigger (Optional): {
          +     *                 timeAfterCreate: String (Optional)
          +     *                 timeBeforeExpiry: String (Optional)
          +     *             }
          +     *             action (Optional): {
          +     *                 type: String(Rotate/Notify) (Optional)
          +     *             }
          +     *         }
          +     *     ]
          +     *     attributes (Optional): {
          +     *         expiryTime: String (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + * @param keyName The name of the key in a given key vault. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return management policy for a key along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getKeyVersionsNextSinglePageAsync(String nextLink, String vaultBaseUrl) { + public Mono> getKeyRotationPolicyWithResponseAsync(String keyName, + RequestOptions requestOptions) { final String accept = "application/json"; - return FluxUtil.withContext(context -> service.getKeyVersionsNext(nextLink, vaultBaseUrl, accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); + return FluxUtil.withContext(context -> service.getKeyRotationPolicy(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), keyName, accept, requestOptions, context)); } /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result along with {@link PagedResponse} on successful completion of {@link Mono}. + * Lists the policy for a key. + * + * The GetKeyRotationPolicy operation returns the specified key policy resources in the specified key vault. This + * operation requires the keys/get permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     lifetimeActions (Optional): [
          +     *          (Optional){
          +     *             trigger (Optional): {
          +     *                 timeAfterCreate: String (Optional)
          +     *                 timeBeforeExpiry: String (Optional)
          +     *             }
          +     *             action (Optional): {
          +     *                 type: String(Rotate/Notify) (Optional)
          +     *             }
          +     *         }
          +     *     ]
          +     *     attributes (Optional): {
          +     *         expiryTime: String (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + * @param keyName The name of the key in a given key vault. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return management policy for a key along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getKeyVersionsNextSinglePageAsync(String nextLink, String vaultBaseUrl, - Context context) { + public Response getKeyRotationPolicyWithResponse(String keyName, RequestOptions requestOptions) { final String accept = "application/json"; - return service.getKeyVersionsNext(nextLink, vaultBaseUrl, accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); + return service.getKeyRotationPolicySync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), keyName, + accept, requestOptions, Context.NONE); } /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result along with {@link PagedResponse}. + * Updates the rotation policy for a key. + * + * Set specified members in the key policy. Leave others as undefined. This operation requires the keys/update + * permission. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     lifetimeActions (Optional): [
          +     *          (Optional){
          +     *             trigger (Optional): {
          +     *                 timeAfterCreate: String (Optional)
          +     *                 timeBeforeExpiry: String (Optional)
          +     *             }
          +     *             action (Optional): {
          +     *                 type: String(Rotate/Notify) (Optional)
          +     *             }
          +     *         }
          +     *     ]
          +     *     attributes (Optional): {
          +     *         expiryTime: String (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     lifetimeActions (Optional): [
          +     *          (Optional){
          +     *             trigger (Optional): {
          +     *                 timeAfterCreate: String (Optional)
          +     *                 timeBeforeExpiry: String (Optional)
          +     *             }
          +     *             action (Optional): {
          +     *                 type: String(Rotate/Notify) (Optional)
          +     *             }
          +     *         }
          +     *     ]
          +     *     attributes (Optional): {
          +     *         expiryTime: String (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + * @param keyName The name of the key in the given vault. + * @param keyRotationPolicy The policy for the key. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return management policy for a key along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getKeyVersionsNextSinglePage(String nextLink, String vaultBaseUrl) { + public Mono> updateKeyRotationPolicyWithResponseAsync(String keyName, + BinaryData keyRotationPolicy, RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - Response res = service.getKeyVersionsNextSync(nextLink, vaultBaseUrl, accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); + return FluxUtil.withContext( + context -> service.updateKeyRotationPolicy(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + keyName, contentType, accept, keyRotationPolicy, requestOptions, context)); } /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result along with {@link PagedResponse}. + * Updates the rotation policy for a key. + * + * Set specified members in the key policy. Leave others as undefined. This operation requires the keys/update + * permission. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     lifetimeActions (Optional): [
          +     *          (Optional){
          +     *             trigger (Optional): {
          +     *                 timeAfterCreate: String (Optional)
          +     *                 timeBeforeExpiry: String (Optional)
          +     *             }
          +     *             action (Optional): {
          +     *                 type: String(Rotate/Notify) (Optional)
          +     *             }
          +     *         }
          +     *     ]
          +     *     attributes (Optional): {
          +     *         expiryTime: String (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     lifetimeActions (Optional): [
          +     *          (Optional){
          +     *             trigger (Optional): {
          +     *                 timeAfterCreate: String (Optional)
          +     *                 timeBeforeExpiry: String (Optional)
          +     *             }
          +     *             action (Optional): {
          +     *                 type: String(Rotate/Notify) (Optional)
          +     *             }
          +     *         }
          +     *     ]
          +     *     attributes (Optional): {
          +     *         expiryTime: String (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + * @param keyName The name of the key in the given vault. + * @param keyRotationPolicy The policy for the key. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return management policy for a key along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getKeyVersionsNextSinglePage(String nextLink, String vaultBaseUrl, Context context) { + public Response updateKeyRotationPolicyWithResponse(String keyName, BinaryData keyRotationPolicy, + RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - Response res = service.getKeyVersionsNextSync(nextLink, vaultBaseUrl, accept, context); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); + return service.updateKeyRotationPolicySync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + keyName, contentType, accept, keyRotationPolicy, requestOptions, Context.NONE); } /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result along with {@link PagedResponse} on successful completion of {@link Mono}. + * Get the requested number of bytes containing random values. + * + * Get the requested number of bytes containing random values from a managed HSM. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     count: int (Required)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: Base64Url (Required)
          +     * }
          +     * }
          +     * 
          + * + * @param parameters The request object to get random bytes. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the requested number of bytes containing random values. + * + * Get the requested number of bytes containing random values from a managed HSM along with {@link Response} on + * successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getKeysNextSinglePageAsync(String nextLink, String vaultBaseUrl) { + public Mono> getRandomBytesWithResponseAsync(BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - return FluxUtil.withContext(context -> service.getKeysNext(nextLink, vaultBaseUrl, accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); + return FluxUtil.withContext(context -> service.getRandomBytes(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), contentType, accept, parameters, requestOptions, context)); } /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getKeysNextSinglePageAsync(String nextLink, String vaultBaseUrl, - Context context) { + * Get the requested number of bytes containing random values. + * + * Get the requested number of bytes containing random values from a managed HSM. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     count: int (Required)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: Base64Url (Required)
          +     * }
          +     * }
          +     * 
          + * + * @param parameters The request object to get random bytes. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the requested number of bytes containing random values. + * + * Get the requested number of bytes containing random values from a managed HSM along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getRandomBytesWithResponse(BinaryData parameters, RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - return service.getKeysNext(nextLink, vaultBaseUrl, accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); + return service.getRandomBytesSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), contentType, + accept, parameters, requestOptions, Context.NONE); } /** + * Retrieves a list of individual key versions with the same key name. + * * Get the next page of items. - * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kid: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the key list result along with {@link PagedResponse}. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the key list result along with {@link PagedResponse} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getKeysNextSinglePage(String nextLink, String vaultBaseUrl) { + private Mono> getKeyVersionsNextSinglePageAsync(String nextLink, + RequestOptions requestOptions) { final String accept = "application/json"; - Response res = service.getKeysNextSync(nextLink, vaultBaseUrl, accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); + return FluxUtil.withContext( + context -> service.getKeyVersionsNext(nextLink, this.getVaultBaseUrl(), accept, requestOptions, context)) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } /** + * Retrieves a list of individual key versions with the same key name. + * * Get the next page of items. - * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kid: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the key list result along with {@link PagedResponse}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getKeysNextSinglePage(String nextLink, String vaultBaseUrl, Context context) { + private PagedResponse getKeyVersionsNextSinglePage(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; - Response res = service.getKeysNextSync(nextLink, vaultBaseUrl, accept, context); + Response res + = service.getKeyVersionsNextSync(nextLink, this.getVaultBaseUrl(), accept, requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } /** + * List keys in the specified vault. + * * Get the next page of items. - * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kid: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of keys that have been deleted in this vault along with {@link PagedResponse} on successful - * completion of {@link Mono}. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the key list result along with {@link PagedResponse} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedKeysNextSinglePageAsync(String nextLink, String vaultBaseUrl) { + private Mono> getKeysNextSinglePageAsync(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; - return FluxUtil.withContext(context -> service.getDeletedKeysNext(nextLink, vaultBaseUrl, accept, context)) + return FluxUtil + .withContext( + context -> service.getKeysNext(nextLink, this.getVaultBaseUrl(), accept, requestOptions, context)) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } /** + * List keys in the specified vault. + * * Get the next page of items. - * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kid: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of keys that have been deleted in this vault along with {@link PagedResponse} on successful - * completion of {@link Mono}. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the key list result along with {@link PagedResponse}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedKeysNextSinglePageAsync(String nextLink, String vaultBaseUrl, - Context context) { + private PagedResponse getKeysNextSinglePage(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; - return service.getDeletedKeysNext(nextLink, vaultBaseUrl, accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); + Response res + = service.getKeysNextSync(nextLink, this.getVaultBaseUrl(), accept, requestOptions, Context.NONE); + return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } /** + * Lists the deleted keys in the specified vault. + * * Get the next page of items. - * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kid: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of keys that have been deleted in this vault along with {@link PagedResponse}. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a list of keys that have been deleted in this vault along with {@link PagedResponse} on successful + * completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getDeletedKeysNextSinglePage(String nextLink, String vaultBaseUrl) { + private Mono> getDeletedKeysNextSinglePageAsync(String nextLink, + RequestOptions requestOptions) { final String accept = "application/json"; - Response res - = service.getDeletedKeysNextSync(nextLink, vaultBaseUrl, accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); + return FluxUtil.withContext( + context -> service.getDeletedKeysNext(nextLink, this.getVaultBaseUrl(), accept, requestOptions, context)) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } /** + * Lists the deleted keys in the specified vault. + * * Get the next page of items. - * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     kid: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *         exportable: Boolean (Optional)
          +     *         hsmPlatform: String (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     managed: Boolean (Optional)
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a list of keys that have been deleted in this vault along with {@link PagedResponse}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getDeletedKeysNextSinglePage(String nextLink, String vaultBaseUrl, - Context context) { + private PagedResponse getDeletedKeysNextSinglePage(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; - Response res = service.getDeletedKeysNextSync(nextLink, vaultBaseUrl, accept, context); + Response res + = service.getDeletedKeysNextSync(nextLink, this.getVaultBaseUrl(), accept, requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); + } + + private List getValues(BinaryData binaryData, String path) { + try { + Map obj = binaryData.toObject(Map.class); + List values = (List) obj.get(path); + return values.stream().map(BinaryData::fromObject).collect(Collectors.toList()); + } catch (RuntimeException e) { + return null; + } + } + + private String getNextLink(BinaryData binaryData, String path) { + try { + Map obj = binaryData.toObject(Map.class); + return (String) obj.get(path); + } catch (RuntimeException e) { + return null; + } } } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultKeysUtils.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultKeysUtils.java index aef4314a5c59..86fc5b89ff71 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultKeysUtils.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultKeysUtils.java @@ -3,16 +3,14 @@ package com.azure.security.keyvault.keys.implementation; import com.azure.core.exception.HttpResponseException; -import com.azure.core.exception.ResourceModifiedException; -import com.azure.core.exception.ResourceNotFoundException; import com.azure.core.http.HttpPipeline; +import com.azure.core.http.rest.RequestOptions; import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.json.JsonReader; import com.azure.security.keyvault.keys.KeyServiceVersion; import com.azure.security.keyvault.keys.cryptography.CryptographyClientBuilder; import com.azure.security.keyvault.keys.cryptography.CryptographyServiceVersion; -import com.azure.security.keyvault.keys.implementation.models.KeyVaultErrorException; import java.io.IOException; import java.net.MalformedURLException; @@ -31,6 +29,8 @@ public final class KeyVaultKeysUtils { private static final ClientLogger LOGGER = new ClientLogger(KeyVaultKeysUtils.class); + public static final RequestOptions EMPTY_OPTIONS = new RequestOptions(); + /** * Creates a {@link CryptographyClientBuilder} based on the values passed from a Keys service client. * @@ -78,35 +78,19 @@ private static String generateKeyId(String keyName, String keyVersion, String va } /** - * Calls a supplier and maps any {@link KeyVaultErrorException} to an {@link HttpResponseException}. + * Calls a supplier and maps any {@link HttpResponseException} to an {@link HttpResponseException}. * * @param The type of the result of the supplier. * @param call The supplier to call. - * @param exceptionMapper The function to map a {@link KeyVaultErrorException} to an {@link HttpResponseException}. + * @param exceptionMapper The function to map a {@link HttpResponseException} to an {@link HttpResponseException}. * @return The result of the supplier. */ public static T callWithMappedException(Supplier call, - Function exceptionMapper) { + Function exceptionMapper) { try { return call.get(); - } catch (KeyVaultErrorException ex) { - throw exceptionMapper.apply(ex); - } - } - - /** - * Maps a {@link KeyVaultErrorException} to an {@link HttpResponseException} for get key operations. - * - * @param ex The {@link KeyVaultErrorException} to map. - * @return The {@link HttpResponseException} that maps from the {@link KeyVaultErrorException}. - */ - public static HttpResponseException mapGetKeyException(KeyVaultErrorException ex) { - if (ex.getResponse().getStatusCode() == 403) { - return new ResourceModifiedException(ex.getMessage(), ex.getResponse(), ex.getValue()); - } else if (ex.getResponse().getStatusCode() == 404) { - return new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()); - } else { - return ex; + } catch (HttpResponseException e) { + throw exceptionMapper.apply(e); } } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/Attributes.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/Attributes.java deleted file mode 100644 index af80db741816..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/Attributes.java +++ /dev/null @@ -1,226 +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.security.keyvault.keys.implementation.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.time.Instant; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; - -/** - * The object attributes managed by the KeyVault service. - */ -@Fluent -public class Attributes implements JsonSerializable { - /* - * Determines whether the object is enabled. - */ - private Boolean enabled; - - /* - * Not before date in UTC. - */ - private Long notBefore; - - /* - * Expiry date in UTC. - */ - private Long expires; - - /* - * Creation time in UTC. - */ - private Long created; - - /* - * Last updated time in UTC. - */ - private Long updated; - - /** - * Creates an instance of Attributes class. - */ - public Attributes() { - } - - /** - * Get the enabled property: Determines whether the object is enabled. - * - * @return the enabled value. - */ - public Boolean isEnabled() { - return this.enabled; - } - - /** - * Set the enabled property: Determines whether the object is enabled. - * - * @param enabled the enabled value to set. - * @return the Attributes object itself. - */ - public Attributes setEnabled(Boolean enabled) { - this.enabled = enabled; - return this; - } - - /** - * Get the notBefore property: Not before date in UTC. - * - * @return the notBefore value. - */ - public OffsetDateTime getNotBefore() { - if (this.notBefore == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.notBefore), ZoneOffset.UTC); - } - - /** - * Set the notBefore property: Not before date in UTC. - * - * @param notBefore the notBefore value to set. - * @return the Attributes object itself. - */ - public Attributes setNotBefore(OffsetDateTime notBefore) { - if (notBefore == null) { - this.notBefore = null; - } else { - this.notBefore = notBefore.toEpochSecond(); - } - return this; - } - - /** - * Get the expires property: Expiry date in UTC. - * - * @return the expires value. - */ - public OffsetDateTime getExpires() { - if (this.expires == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.expires), ZoneOffset.UTC); - } - - /** - * Set the expires property: Expiry date in UTC. - * - * @param expires the expires value to set. - * @return the Attributes object itself. - */ - public Attributes setExpires(OffsetDateTime expires) { - if (expires == null) { - this.expires = null; - } else { - this.expires = expires.toEpochSecond(); - } - return this; - } - - /** - * Get the created property: Creation time in UTC. - * - * @return the created value. - */ - public OffsetDateTime getCreated() { - if (this.created == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.created), ZoneOffset.UTC); - } - - /** - * Set the created property: Creation time in UTC. - * - * @param created the created value to set. - * @return the Attributes object itself. - */ - Attributes setCreated(OffsetDateTime created) { - if (created == null) { - this.created = null; - } else { - this.created = created.toEpochSecond(); - } - return this; - } - - /** - * Get the updated property: Last updated time in UTC. - * - * @return the updated value. - */ - public OffsetDateTime getUpdated() { - if (this.updated == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.updated), ZoneOffset.UTC); - } - - /** - * Set the updated property: Last updated time in UTC. - * - * @param updated the updated value to set. - * @return the Attributes object itself. - */ - Attributes setUpdated(OffsetDateTime updated) { - if (updated == null) { - this.updated = null; - } else { - this.updated = updated.toEpochSecond(); - } - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeBooleanField("enabled", this.enabled); - jsonWriter.writeNumberField("nbf", this.notBefore); - jsonWriter.writeNumberField("exp", this.expires); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of Attributes from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of Attributes 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 Attributes. - */ - public static Attributes fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - Attributes deserializedAttributes = new Attributes(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("enabled".equals(fieldName)) { - deserializedAttributes.enabled = reader.getNullable(JsonReader::getBoolean); - } else if ("nbf".equals(fieldName)) { - deserializedAttributes.notBefore = reader.getNullable(JsonReader::getLong); - } else if ("exp".equals(fieldName)) { - deserializedAttributes.expires = reader.getNullable(JsonReader::getLong); - } else if ("created".equals(fieldName)) { - deserializedAttributes.created = reader.getNullable(JsonReader::getLong); - } else if ("updated".equals(fieldName)) { - deserializedAttributes.updated = reader.getNullable(JsonReader::getLong); - } else { - reader.skipChildren(); - } - } - - return deserializedAttributes; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/BackupKeyResult.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/BackupKeyResult.java index c6cfc35a17c0..f87387eacb55 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/BackupKeyResult.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/BackupKeyResult.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.implementation.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.core.util.Base64Url; import com.azure.json.JsonReader; @@ -17,22 +17,26 @@ */ @Immutable public final class BackupKeyResult implements JsonSerializable { + /* * The backup blob containing the backed up key. */ + @Generated private Base64Url value; /** * Creates an instance of BackupKeyResult class. */ - public BackupKeyResult() { + @Generated + private BackupKeyResult() { } /** * Get the value property: The backup blob containing the backed up key. - * + * * @return the value value. */ + @Generated public byte[] getValue() { if (this.value == null) { return null; @@ -43,6 +47,7 @@ public byte[] getValue() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -51,19 +56,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of BackupKeyResult from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of BackupKeyResult 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 BackupKeyResult. */ + @Generated public static BackupKeyResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { BackupKeyResult deserializedBackupKeyResult = new BackupKeyResult(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("value".equals(fieldName)) { deserializedBackupKeyResult.value = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); @@ -71,7 +76,6 @@ public static BackupKeyResult fromJson(JsonReader jsonReader) throws IOException reader.skipChildren(); } } - return deserializedBackupKeyResult; }); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletedKeyBundle.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletedKeyBundle.java index 9b4365d2c9b2..9ac206aa5ad7 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletedKeyBundle.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletedKeyBundle.java @@ -1,11 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +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; @@ -17,166 +18,193 @@ /** * A DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info. */ -@Fluent -public final class DeletedKeyBundle extends KeyBundle { +@Immutable +public final class DeletedKeyBundle implements JsonSerializable { + /* - * The url of the recovery object, used to identify and recover the deleted key. + * The Json web key. */ - private String recoveryId; + @Generated + private JsonWebKey key; /* - * The time when the key is scheduled to be purged, in UTC + * The key management attributes. */ - private Long scheduledPurgeDate; + @Generated + private KeyAttributes attributes; /* - * The time when the key was deleted, in UTC + * Application specific metadata in the form of key-value pairs. */ - private Long deletedDate; + @Generated + private Map tags; /* * True if the key's lifetime is managed by key vault. If this is a key backing a certificate, then managed will be * true. */ + @Generated private Boolean managed; - /** - * Creates an instance of DeletedKeyBundle class. + /* + * The policy rules under which the key can be exported. */ - public DeletedKeyBundle() { - } + @Generated + private KeyReleasePolicy releasePolicy; + + /* + * The url of the recovery object, used to identify and recover the deleted key. + */ + @Generated + private String recoveryId; + + /* + * The time when the key is scheduled to be purged, in UTC + */ + @Generated + private Long scheduledPurgeDate; + + /* + * The time when the key was deleted, in UTC + */ + @Generated + private Long deletedDate; /** - * Get the recoveryId property: The url of the recovery object, used to identify and recover the deleted key. - * - * @return the recoveryId value. + * Creates an instance of DeletedKeyBundle class. */ - public String getRecoveryId() { - return this.recoveryId; + @Generated + private DeletedKeyBundle() { } /** - * Set the recoveryId property: The url of the recovery object, used to identify and recover the deleted key. - * - * @param recoveryId the recoveryId value to set. - * @return the DeletedKeyBundle object itself. - */ - public DeletedKeyBundle setRecoveryId(String recoveryId) { - this.recoveryId = recoveryId; - return this; + * Get the key property: The Json web key. + * + * @return the key value. + */ + @Generated + public JsonWebKey getKey() { + return this.key; } /** - * Get the scheduledPurgeDate property: The time when the key is scheduled to be purged, in UTC. - * - * @return the scheduledPurgeDate value. + * Get the attributes property: The key management attributes. + * + * @return the attributes value. */ - public OffsetDateTime getScheduledPurgeDate() { - if (this.scheduledPurgeDate == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.scheduledPurgeDate), ZoneOffset.UTC); + @Generated + public KeyAttributes getAttributes() { + return this.attributes; } /** - * Get the deletedDate property: The time when the key was deleted, in UTC. - * - * @return the deletedDate value. + * Get the tags property: Application specific metadata in the form of key-value pairs. + * + * @return the tags value. */ - public OffsetDateTime getDeletedDate() { - if (this.deletedDate == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.deletedDate), ZoneOffset.UTC); + @Generated + public Map getTags() { + return this.tags; } /** * Get the managed property: True if the key's lifetime is managed by key vault. If this is a key backing a * certificate, then managed will be true. - * + * * @return the managed value. */ - @Override + @Generated public Boolean isManaged() { return this.managed; } /** - * {@inheritDoc} + * Get the releasePolicy property: The policy rules under which the key can be exported. + * + * @return the releasePolicy value. */ - @Override - public DeletedKeyBundle setKey(JsonWebKey key) { - super.setKey(key); - return this; + @Generated + public KeyReleasePolicy getReleasePolicy() { + return this.releasePolicy; } /** - * {@inheritDoc} + * Get the recoveryId property: The url of the recovery object, used to identify and recover the deleted key. + * + * @return the recoveryId value. */ - @Override - public DeletedKeyBundle setAttributes(KeyAttributes attributes) { - super.setAttributes(attributes); - return this; + @Generated + public String getRecoveryId() { + return this.recoveryId; } /** - * {@inheritDoc} + * Get the scheduledPurgeDate property: The time when the key is scheduled to be purged, in UTC. + * + * @return the scheduledPurgeDate value. */ - @Override - public DeletedKeyBundle setTags(Map tags) { - super.setTags(tags); - return this; + @Generated + public OffsetDateTime getScheduledPurgeDate() { + if (this.scheduledPurgeDate == null) { + return null; + } + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.scheduledPurgeDate), ZoneOffset.UTC); } /** - * {@inheritDoc} + * Get the deletedDate property: The time when the key was deleted, in UTC. + * + * @return the deletedDate value. */ - @Override - public DeletedKeyBundle setReleasePolicy(KeyReleasePolicy releasePolicy) { - super.setReleasePolicy(releasePolicy); - return this; + @Generated + public OffsetDateTime getDeletedDate() { + if (this.deletedDate == null) { + return null; + } + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.deletedDate), ZoneOffset.UTC); } /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeJsonField("key", getKey()); - jsonWriter.writeJsonField("attributes", getAttributes()); - jsonWriter.writeMapField("tags", getTags(), (writer, element) -> writer.writeString(element)); - jsonWriter.writeJsonField("release_policy", getReleasePolicy()); + jsonWriter.writeJsonField("key", this.key); + jsonWriter.writeJsonField("attributes", this.attributes); + jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); + jsonWriter.writeJsonField("release_policy", this.releasePolicy); jsonWriter.writeStringField("recoveryId", this.recoveryId); return jsonWriter.writeEndObject(); } /** * Reads an instance of DeletedKeyBundle from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of DeletedKeyBundle 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 DeletedKeyBundle. */ + @Generated public static DeletedKeyBundle fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { DeletedKeyBundle deserializedDeletedKeyBundle = new DeletedKeyBundle(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("key".equals(fieldName)) { - deserializedDeletedKeyBundle.setKey(JsonWebKey.fromJson(reader)); + deserializedDeletedKeyBundle.key = JsonWebKey.fromJson(reader); } else if ("attributes".equals(fieldName)) { - deserializedDeletedKeyBundle.setAttributes(KeyAttributes.fromJson(reader)); + deserializedDeletedKeyBundle.attributes = KeyAttributes.fromJson(reader); } else if ("tags".equals(fieldName)) { Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedDeletedKeyBundle.setTags(tags); + deserializedDeletedKeyBundle.tags = tags; } else if ("managed".equals(fieldName)) { deserializedDeletedKeyBundle.managed = reader.getNullable(JsonReader::getBoolean); } else if ("release_policy".equals(fieldName)) { - deserializedDeletedKeyBundle.setReleasePolicy(KeyReleasePolicy.fromJson(reader)); + deserializedDeletedKeyBundle.releasePolicy = KeyReleasePolicy.fromJson(reader); } else if ("recoveryId".equals(fieldName)) { deserializedDeletedKeyBundle.recoveryId = reader.getString(); } else if ("scheduledPurgeDate".equals(fieldName)) { @@ -187,7 +215,6 @@ public static DeletedKeyBundle fromJson(JsonReader jsonReader) throws IOExceptio reader.skipChildren(); } } - return deserializedDeletedKeyBundle; }); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletedKeyItem.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletedKeyItem.java index 6a11612360d6..14cffb331826 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletedKeyItem.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletedKeyItem.java @@ -1,11 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +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; @@ -17,152 +18,172 @@ /** * The deleted key item containing the deleted key metadata and information about deletion. */ -@Fluent -public final class DeletedKeyItem extends KeyItem { +@Immutable +public final class DeletedKeyItem implements JsonSerializable { + /* - * The url of the recovery object, used to identify and recover the deleted key. + * Key identifier. */ - private String recoveryId; + @Generated + private String kid; /* - * The time when the key is scheduled to be purged, in UTC + * The key management attributes. */ - private Long scheduledPurgeDate; + @Generated + private KeyAttributes attributes; /* - * The time when the key was deleted, in UTC + * Application specific metadata in the form of key-value pairs. */ - private Long deletedDate; + @Generated + private Map tags; /* * True if the key's lifetime is managed by key vault. If this is a key backing a certificate, then managed will be * true. */ + @Generated private Boolean managed; - /** - * Creates an instance of DeletedKeyItem class. + /* + * The url of the recovery object, used to identify and recover the deleted key. */ - public DeletedKeyItem() { - } + @Generated + private String recoveryId; + + /* + * The time when the key is scheduled to be purged, in UTC + */ + @Generated + private Long scheduledPurgeDate; + + /* + * The time when the key was deleted, in UTC + */ + @Generated + private Long deletedDate; /** - * Get the recoveryId property: The url of the recovery object, used to identify and recover the deleted key. - * - * @return the recoveryId value. + * Creates an instance of DeletedKeyItem class. */ - public String getRecoveryId() { - return this.recoveryId; + @Generated + private DeletedKeyItem() { } /** - * Set the recoveryId property: The url of the recovery object, used to identify and recover the deleted key. - * - * @param recoveryId the recoveryId value to set. - * @return the DeletedKeyItem object itself. - */ - public DeletedKeyItem setRecoveryId(String recoveryId) { - this.recoveryId = recoveryId; - return this; + * Get the kid property: Key identifier. + * + * @return the kid value. + */ + @Generated + public String getKid() { + return this.kid; } /** - * Get the scheduledPurgeDate property: The time when the key is scheduled to be purged, in UTC. - * - * @return the scheduledPurgeDate value. + * Get the attributes property: The key management attributes. + * + * @return the attributes value. */ - public OffsetDateTime getScheduledPurgeDate() { - if (this.scheduledPurgeDate == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.scheduledPurgeDate), ZoneOffset.UTC); + @Generated + public KeyAttributes getAttributes() { + return this.attributes; } /** - * Get the deletedDate property: The time when the key was deleted, in UTC. - * - * @return the deletedDate value. + * Get the tags property: Application specific metadata in the form of key-value pairs. + * + * @return the tags value. */ - public OffsetDateTime getDeletedDate() { - if (this.deletedDate == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.deletedDate), ZoneOffset.UTC); + @Generated + public Map getTags() { + return this.tags; } /** * Get the managed property: True if the key's lifetime is managed by key vault. If this is a key backing a * certificate, then managed will be true. - * + * * @return the managed value. */ - @Override + @Generated public Boolean isManaged() { return this.managed; } /** - * {@inheritDoc} + * Get the recoveryId property: The url of the recovery object, used to identify and recover the deleted key. + * + * @return the recoveryId value. */ - @Override - public DeletedKeyItem setKid(String kid) { - super.setKid(kid); - return this; + @Generated + public String getRecoveryId() { + return this.recoveryId; } /** - * {@inheritDoc} + * Get the scheduledPurgeDate property: The time when the key is scheduled to be purged, in UTC. + * + * @return the scheduledPurgeDate value. */ - @Override - public DeletedKeyItem setAttributes(KeyAttributes attributes) { - super.setAttributes(attributes); - return this; + @Generated + public OffsetDateTime getScheduledPurgeDate() { + if (this.scheduledPurgeDate == null) { + return null; + } + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.scheduledPurgeDate), ZoneOffset.UTC); } /** - * {@inheritDoc} + * Get the deletedDate property: The time when the key was deleted, in UTC. + * + * @return the deletedDate value. */ - @Override - public DeletedKeyItem setTags(Map tags) { - super.setTags(tags); - return this; + @Generated + public OffsetDateTime getDeletedDate() { + if (this.deletedDate == null) { + return null; + } + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.deletedDate), ZoneOffset.UTC); } /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeStringField("kid", getKid()); - jsonWriter.writeJsonField("attributes", getAttributes()); - jsonWriter.writeMapField("tags", getTags(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("kid", this.kid); + jsonWriter.writeJsonField("attributes", this.attributes); + jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); jsonWriter.writeStringField("recoveryId", this.recoveryId); return jsonWriter.writeEndObject(); } /** * Reads an instance of DeletedKeyItem from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of DeletedKeyItem 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 DeletedKeyItem. */ + @Generated public static DeletedKeyItem fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { DeletedKeyItem deserializedDeletedKeyItem = new DeletedKeyItem(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("kid".equals(fieldName)) { - deserializedDeletedKeyItem.setKid(reader.getString()); + deserializedDeletedKeyItem.kid = reader.getString(); } else if ("attributes".equals(fieldName)) { - deserializedDeletedKeyItem.setAttributes(KeyAttributes.fromJson(reader)); + deserializedDeletedKeyItem.attributes = KeyAttributes.fromJson(reader); } else if ("tags".equals(fieldName)) { Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedDeletedKeyItem.setTags(tags); + deserializedDeletedKeyItem.tags = tags; } else if ("managed".equals(fieldName)) { deserializedDeletedKeyItem.managed = reader.getNullable(JsonReader::getBoolean); } else if ("recoveryId".equals(fieldName)) { @@ -175,7 +196,6 @@ public static DeletedKeyItem fromJson(JsonReader jsonReader) throws IOException reader.skipChildren(); } } - return deserializedDeletedKeyItem; }); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletedKeyListResult.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletedKeyListResult.java deleted file mode 100644 index ea1014033faf..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletedKeyListResult.java +++ /dev/null @@ -1,93 +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.security.keyvault.keys.implementation.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; -import java.util.List; - -/** - * A list of keys that have been deleted in this vault. - */ -@Immutable -public final class DeletedKeyListResult implements JsonSerializable { - /* - * A response message containing a list of deleted keys in the vault along with a link to the next page of deleted - * keys - */ - private List value; - - /* - * The URL to get the next set of deleted keys. - */ - private String nextLink; - - /** - * Creates an instance of DeletedKeyListResult class. - */ - public DeletedKeyListResult() { - } - - /** - * Get the value property: A response message containing a list of deleted keys in the vault along with a link to - * the next page of deleted keys. - * - * @return the value value. - */ - public List getValue() { - return this.value; - } - - /** - * Get the nextLink property: The URL to get the next set of deleted keys. - * - * @return the nextLink value. - */ - public String getNextLink() { - return this.nextLink; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of DeletedKeyListResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of DeletedKeyListResult 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 DeletedKeyListResult. - */ - public static DeletedKeyListResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - DeletedKeyListResult deserializedDeletedKeyListResult = new DeletedKeyListResult(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - List value = reader.readArray(reader1 -> DeletedKeyItem.fromJson(reader1)); - deserializedDeletedKeyListResult.value = value; - } else if ("nextLink".equals(fieldName)) { - deserializedDeletedKeyListResult.nextLink = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedDeletedKeyListResult; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletionRecoveryLevel.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletionRecoveryLevel.java index 73ccff158f27..d9133a4a8916 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletionRecoveryLevel.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/DeletionRecoveryLevel.java @@ -1,23 +1,25 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.implementation.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; /** - * Reflects the deletion recovery level currently in effect for keys in the current vault. If it contains 'Purgeable' - * the key can be permanently deleted by a privileged user; otherwise, only the system can purge the key, at the end of - * the retention interval. + * Reflects the deletion recovery level currently in effect for certificates in the current vault. If it contains + * 'Purgeable', the certificate can be permanently deleted by a privileged user; otherwise, only the system can purge + * the certificate, at the end of the retention interval. */ public final class DeletionRecoveryLevel extends ExpandableStringEnum { + /** * Denotes a vault state in which deletion is an irreversible operation, without the possibility for recovery. This * level corresponds to no protection being available against a Delete operation; the data is irretrievably lost * upon accepting a Delete operation at the entity level or higher (vault, resource group, subscription etc.). */ + @Generated public static final DeletionRecoveryLevel PURGEABLE = fromString("Purgeable"); /** @@ -26,6 +28,7 @@ public final class DeletionRecoveryLevel extends ExpandableStringEnum values() { return values(DeletionRecoveryLevel.class); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/Error.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/Error.java deleted file mode 100644 index 95a6daf023c6..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/Error.java +++ /dev/null @@ -1,105 +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.security.keyvault.keys.implementation.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 key vault server error. - */ -@Immutable -public final class Error implements JsonSerializable { - /* - * The error code. - */ - private String code; - - /* - * The error message. - */ - private String message; - - /* - * The key vault server error. - */ - private Error innerError; - - /** - * Creates an instance of Error class. - */ - public Error() { - } - - /** - * Get the code property: The error code. - * - * @return the code value. - */ - public String getCode() { - return this.code; - } - - /** - * Get the message property: The error message. - * - * @return the message value. - */ - public String getMessage() { - return this.message; - } - - /** - * Get the innerError property: The key vault server error. - * - * @return the innerError value. - */ - public Error getInnerError() { - return this.innerError; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of Error from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of Error 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 Error. - */ - public static Error fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - Error deserializedError = new Error(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("code".equals(fieldName)) { - deserializedError.code = reader.getString(); - } else if ("message".equals(fieldName)) { - deserializedError.message = reader.getString(); - } else if ("innererror".equals(fieldName)) { - deserializedError.innerError = Error.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedError; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/GetRandomBytesRequest.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/GetRandomBytesRequest.java index 34079cb1b7b7..cd972a4471f3 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/GetRandomBytesRequest.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/GetRandomBytesRequest.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -14,42 +14,39 @@ /** * The get random bytes request object. */ -@Fluent +@Immutable public final class GetRandomBytesRequest implements JsonSerializable { + /* * The requested number of random bytes. */ - private int count; + @Generated + private final int count; /** * Creates an instance of GetRandomBytesRequest class. + * + * @param count the count value to set. */ - public GetRandomBytesRequest() { + @Generated + public GetRandomBytesRequest(int count) { + this.count = count; } /** * Get the count property: The requested number of random bytes. - * + * * @return the count value. */ + @Generated public int getCount() { return this.count; } - /** - * Set the count property: The requested number of random bytes. - * - * @param count the count value to set. - * @return the GetRandomBytesRequest object itself. - */ - public GetRandomBytesRequest setCount(int count) { - this.count = count; - return this; - } - /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -59,28 +56,27 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of GetRandomBytesRequest from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of GetRandomBytesRequest 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 GetRandomBytesRequest. */ + @Generated public static GetRandomBytesRequest fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - GetRandomBytesRequest deserializedGetRandomBytesRequest = new GetRandomBytesRequest(); + int count = 0; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("count".equals(fieldName)) { - deserializedGetRandomBytesRequest.count = reader.getInt(); + count = reader.getInt(); } else { reader.skipChildren(); } } - - return deserializedGetRandomBytesRequest; + return new GetRandomBytesRequest(count); }); } } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/JsonWebKey.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/JsonWebKey.java index 3e8ab290f2d7..1971216d13cb 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/JsonWebKey.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/JsonWebKey.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.core.util.Base64Url; import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; @@ -12,7 +12,6 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import com.azure.security.keyvault.keys.models.KeyCurveName; -import com.azure.security.keyvault.keys.models.KeyOperation; import com.azure.security.keyvault.keys.models.KeyType; import java.io.IOException; import java.util.List; @@ -23,107 +22,127 @@ */ @Fluent public final class JsonWebKey implements JsonSerializable { + /* * Key identifier. */ + @Generated private String kid; /* * JsonWebKey Key Type (kty), as defined in https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. */ + @Generated private KeyType kty; /* - * The key_ops property. + * Json web key operations. For more information on possible key operations, see JsonWebKeyOperation. */ - private List keyOps; + @Generated + private List keyOps; /* * RSA modulus. */ + @Generated private Base64Url n; /* * RSA public exponent. */ + @Generated private Base64Url e; /* * RSA private exponent, or the D component of an EC private key. */ + @Generated private Base64Url d; /* * RSA private key parameter. */ + @Generated private Base64Url dp; /* * RSA private key parameter. */ + @Generated private Base64Url dq; /* * RSA private key parameter. */ + @Generated private Base64Url qi; /* * RSA secret prime. */ + @Generated private Base64Url p; /* * RSA secret prime, with p < q. */ + @Generated private Base64Url q; /* * Symmetric key. */ + @Generated private Base64Url k; /* * Protected Key, used with 'Bring Your Own Key'. */ + @Generated private Base64Url t; /* - * Elliptic curve name. + * Elliptic curve name. For valid values, see JsonWebKeyCurveName. */ + @Generated private KeyCurveName crv; /* * X component of an EC public key. */ + @Generated private Base64Url x; /* * Y component of an EC public key. */ + @Generated private Base64Url y; /** * Creates an instance of JsonWebKey class. */ + @Generated public JsonWebKey() { } /** * Get the kid property: Key identifier. - * + * * @return the kid value. */ + @Generated public String getKid() { return this.kid; } /** * Set the kid property: Key identifier. - * + * * @param kid the kid value to set. * @return the JsonWebKey object itself. */ + @Generated public JsonWebKey setKid(String kid) { this.kid = kid; return this; @@ -132,9 +151,10 @@ public JsonWebKey setKid(String kid) { /** * Get the kty property: JsonWebKey Key Type (kty), as defined in * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - * + * * @return the kty value. */ + @Generated public KeyType getKty() { return this.kty; } @@ -142,40 +162,46 @@ public KeyType getKty() { /** * Set the kty property: JsonWebKey Key Type (kty), as defined in * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - * + * * @param kty the kty value to set. * @return the JsonWebKey object itself. */ + @Generated public JsonWebKey setKty(KeyType kty) { this.kty = kty; return this; } /** - * Get the keyOps property: The key_ops property. - * + * Get the keyOps property: Json web key operations. For more information on possible key operations, see + * JsonWebKeyOperation. + * * @return the keyOps value. */ - public List getKeyOps() { + @Generated + public List getKeyOps() { return this.keyOps; } /** - * Set the keyOps property: The key_ops property. - * + * Set the keyOps property: Json web key operations. For more information on possible key operations, see + * JsonWebKeyOperation. + * * @param keyOps the keyOps value to set. * @return the JsonWebKey object itself. */ - public JsonWebKey setKeyOps(List keyOps) { + @Generated + public JsonWebKey setKeyOps(List keyOps) { this.keyOps = keyOps; return this; } /** * Get the n property: RSA modulus. - * + * * @return the n value. */ + @Generated public byte[] getN() { if (this.n == null) { return null; @@ -185,10 +211,11 @@ public byte[] getN() { /** * Set the n property: RSA modulus. - * + * * @param n the n value to set. * @return the JsonWebKey object itself. */ + @Generated public JsonWebKey setN(byte[] n) { if (n == null) { this.n = null; @@ -200,9 +227,10 @@ public JsonWebKey setN(byte[] n) { /** * Get the e property: RSA public exponent. - * + * * @return the e value. */ + @Generated public byte[] getE() { if (this.e == null) { return null; @@ -212,10 +240,11 @@ public byte[] getE() { /** * Set the e property: RSA public exponent. - * + * * @param e the e value to set. * @return the JsonWebKey object itself. */ + @Generated public JsonWebKey setE(byte[] e) { if (e == null) { this.e = null; @@ -227,9 +256,10 @@ public JsonWebKey setE(byte[] e) { /** * Get the d property: RSA private exponent, or the D component of an EC private key. - * + * * @return the d value. */ + @Generated public byte[] getD() { if (this.d == null) { return null; @@ -239,10 +269,11 @@ public byte[] getD() { /** * Set the d property: RSA private exponent, or the D component of an EC private key. - * + * * @param d the d value to set. * @return the JsonWebKey object itself. */ + @Generated public JsonWebKey setD(byte[] d) { if (d == null) { this.d = null; @@ -254,9 +285,10 @@ public JsonWebKey setD(byte[] d) { /** * Get the dp property: RSA private key parameter. - * + * * @return the dp value. */ + @Generated public byte[] getDp() { if (this.dp == null) { return null; @@ -266,10 +298,11 @@ public byte[] getDp() { /** * Set the dp property: RSA private key parameter. - * + * * @param dp the dp value to set. * @return the JsonWebKey object itself. */ + @Generated public JsonWebKey setDp(byte[] dp) { if (dp == null) { this.dp = null; @@ -281,9 +314,10 @@ public JsonWebKey setDp(byte[] dp) { /** * Get the dq property: RSA private key parameter. - * + * * @return the dq value. */ + @Generated public byte[] getDq() { if (this.dq == null) { return null; @@ -293,10 +327,11 @@ public byte[] getDq() { /** * Set the dq property: RSA private key parameter. - * + * * @param dq the dq value to set. * @return the JsonWebKey object itself. */ + @Generated public JsonWebKey setDq(byte[] dq) { if (dq == null) { this.dq = null; @@ -308,9 +343,10 @@ public JsonWebKey setDq(byte[] dq) { /** * Get the qi property: RSA private key parameter. - * + * * @return the qi value. */ + @Generated public byte[] getQi() { if (this.qi == null) { return null; @@ -320,10 +356,11 @@ public byte[] getQi() { /** * Set the qi property: RSA private key parameter. - * + * * @param qi the qi value to set. * @return the JsonWebKey object itself. */ + @Generated public JsonWebKey setQi(byte[] qi) { if (qi == null) { this.qi = null; @@ -335,9 +372,10 @@ public JsonWebKey setQi(byte[] qi) { /** * Get the p property: RSA secret prime. - * + * * @return the p value. */ + @Generated public byte[] getP() { if (this.p == null) { return null; @@ -347,10 +385,11 @@ public byte[] getP() { /** * Set the p property: RSA secret prime. - * + * * @param p the p value to set. * @return the JsonWebKey object itself. */ + @Generated public JsonWebKey setP(byte[] p) { if (p == null) { this.p = null; @@ -362,9 +401,10 @@ public JsonWebKey setP(byte[] p) { /** * Get the q property: RSA secret prime, with p < q. - * + * * @return the q value. */ + @Generated public byte[] getQ() { if (this.q == null) { return null; @@ -374,10 +414,11 @@ public byte[] getQ() { /** * Set the q property: RSA secret prime, with p < q. - * + * * @param q the q value to set. * @return the JsonWebKey object itself. */ + @Generated public JsonWebKey setQ(byte[] q) { if (q == null) { this.q = null; @@ -389,9 +430,10 @@ public JsonWebKey setQ(byte[] q) { /** * Get the k property: Symmetric key. - * + * * @return the k value. */ + @Generated public byte[] getK() { if (this.k == null) { return null; @@ -401,10 +443,11 @@ public byte[] getK() { /** * Set the k property: Symmetric key. - * + * * @param k the k value to set. * @return the JsonWebKey object itself. */ + @Generated public JsonWebKey setK(byte[] k) { if (k == null) { this.k = null; @@ -416,9 +459,10 @@ public JsonWebKey setK(byte[] k) { /** * Get the t property: Protected Key, used with 'Bring Your Own Key'. - * + * * @return the t value. */ + @Generated public byte[] getT() { if (this.t == null) { return null; @@ -428,10 +472,11 @@ public byte[] getT() { /** * Set the t property: Protected Key, used with 'Bring Your Own Key'. - * + * * @param t the t value to set. * @return the JsonWebKey object itself. */ + @Generated public JsonWebKey setT(byte[] t) { if (t == null) { this.t = null; @@ -442,20 +487,22 @@ public JsonWebKey setT(byte[] t) { } /** - * Get the crv property: Elliptic curve name. - * + * Get the crv property: Elliptic curve name. For valid values, see JsonWebKeyCurveName. + * * @return the crv value. */ + @Generated public KeyCurveName getCrv() { return this.crv; } /** - * Set the crv property: Elliptic curve name. - * + * Set the crv property: Elliptic curve name. For valid values, see JsonWebKeyCurveName. + * * @param crv the crv value to set. * @return the JsonWebKey object itself. */ + @Generated public JsonWebKey setCrv(KeyCurveName crv) { this.crv = crv; return this; @@ -463,9 +510,10 @@ public JsonWebKey setCrv(KeyCurveName crv) { /** * Get the x property: X component of an EC public key. - * + * * @return the x value. */ + @Generated public byte[] getX() { if (this.x == null) { return null; @@ -475,10 +523,11 @@ public byte[] getX() { /** * Set the x property: X component of an EC public key. - * + * * @param x the x value to set. * @return the JsonWebKey object itself. */ + @Generated public JsonWebKey setX(byte[] x) { if (x == null) { this.x = null; @@ -490,9 +539,10 @@ public JsonWebKey setX(byte[] x) { /** * Get the y property: Y component of an EC public key. - * + * * @return the y value. */ + @Generated public byte[] getY() { if (this.y == null) { return null; @@ -502,10 +552,11 @@ public byte[] getY() { /** * Set the y property: Y component of an EC public key. - * + * * @param y the y value to set. * @return the JsonWebKey object itself. */ + @Generated public JsonWebKey setY(byte[] y) { if (y == null) { this.y = null; @@ -518,13 +569,13 @@ public JsonWebKey setY(byte[] y) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("kid", this.kid); jsonWriter.writeStringField("kty", this.kty == null ? null : this.kty.toString()); - jsonWriter.writeArrayField("key_ops", this.keyOps, - (writer, element) -> writer.writeString(element == null ? null : element.toString())); + jsonWriter.writeArrayField("key_ops", this.keyOps, (writer, element) -> writer.writeString(element)); jsonWriter.writeStringField("n", Objects.toString(this.n, null)); jsonWriter.writeStringField("e", Objects.toString(this.e, null)); jsonWriter.writeStringField("d", Objects.toString(this.d, null)); @@ -543,26 +594,25 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of JsonWebKey from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of JsonWebKey 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 JsonWebKey. */ + @Generated public static JsonWebKey fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { JsonWebKey deserializedJsonWebKey = new JsonWebKey(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("kid".equals(fieldName)) { deserializedJsonWebKey.kid = reader.getString(); } else if ("kty".equals(fieldName)) { deserializedJsonWebKey.kty = KeyType.fromString(reader.getString()); } else if ("key_ops".equals(fieldName)) { - List keyOps - = reader.readArray(reader1 -> KeyOperation.fromString(reader1.getString())); + List keyOps = reader.readArray(reader1 -> reader1.getString()); deserializedJsonWebKey.keyOps = keyOps; } else if ("n".equals(fieldName)) { deserializedJsonWebKey.n @@ -606,7 +656,6 @@ public static JsonWebKey fromJson(JsonReader jsonReader) throws IOException { reader.skipChildren(); } } - return deserializedJsonWebKey; }); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/JsonWebKeyEncryptionAlgorithm.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/JsonWebKeyEncryptionAlgorithm.java index 3def90a799f4..5227230e2409 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/JsonWebKeyEncryptionAlgorithm.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/JsonWebKeyEncryptionAlgorithm.java @@ -1,115 +1,155 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.implementation.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; /** - * algorithm identifier. + * An algorithm used for encryption and decryption. */ public final class JsonWebKeyEncryptionAlgorithm extends ExpandableStringEnum { + + /** + * [Not recommended] RSAES using Optimal Asymmetric Encryption Padding (OAEP), as described in + * https://tools.ietf.org/html/rfc3447, with the default parameters specified by RFC 3447 in Section A.2.1. Those + * default parameters are using a hash function of SHA-1 and a mask generation function of MGF1 with SHA-1. + * Microsoft recommends using RSA_OAEP_256 or stronger algorithms for enhanced security. Microsoft does *not* + * recommend RSA_OAEP, which is included solely for backwards compatibility. RSA_OAEP utilizes SHA1, which has known + * collision problems. + */ + @Generated + public static final JsonWebKeyEncryptionAlgorithm RSA_OAEP = fromString("RSA-OAEP"); + + /** + * RSAES using Optimal Asymmetric Encryption Padding with a hash function of SHA-256 and a mask generation function + * of MGF1 with SHA-256. + */ + @Generated + public static final JsonWebKeyEncryptionAlgorithm RSA_OAEP256 = fromString("RSA-OAEP-256"); + /** - * Static value RSA-OAEP for JsonWebKeyEncryptionAlgorithm. + * [Not recommended] RSAES-PKCS1-V1_5 key encryption, as described in https://tools.ietf.org/html/rfc3447. Microsoft + * recommends using RSA_OAEP_256 or stronger algorithms for enhanced security. Microsoft does *not* recommend + * RSA_1_5, which is included solely for backwards compatibility. Cryptographic standards no longer consider RSA + * with the PKCS#1 v1.5 padding scheme secure for encryption. */ - public static final JsonWebKeyEncryptionAlgorithm RSAOAEP = fromString("RSA-OAEP"); + @Generated + public static final JsonWebKeyEncryptionAlgorithm RSA1_5 = fromString("RSA1_5"); /** - * Static value RSA-OAEP-256 for JsonWebKeyEncryptionAlgorithm. + * 128-bit AES-GCM. */ - public static final JsonWebKeyEncryptionAlgorithm RSAOAEP256 = fromString("RSA-OAEP-256"); + @Generated + public static final JsonWebKeyEncryptionAlgorithm A128_GCM = fromString("A128GCM"); /** - * Static value RSA1_5 for JsonWebKeyEncryptionAlgorithm. + * 192-bit AES-GCM. */ - public static final JsonWebKeyEncryptionAlgorithm RSA15 = fromString("RSA1_5"); + @Generated + public static final JsonWebKeyEncryptionAlgorithm A192_GCM = fromString("A192GCM"); /** - * Static value A128GCM for JsonWebKeyEncryptionAlgorithm. + * 256-bit AES-GCM. */ - public static final JsonWebKeyEncryptionAlgorithm A128GCM = fromString("A128GCM"); + @Generated + public static final JsonWebKeyEncryptionAlgorithm A256_GCM = fromString("A256GCM"); /** - * Static value A192GCM for JsonWebKeyEncryptionAlgorithm. + * 128-bit AES key wrap. */ - public static final JsonWebKeyEncryptionAlgorithm A192GCM = fromString("A192GCM"); + @Generated + public static final JsonWebKeyEncryptionAlgorithm A128_KW = fromString("A128KW"); /** - * Static value A256GCM for JsonWebKeyEncryptionAlgorithm. + * 192-bit AES key wrap. */ - public static final JsonWebKeyEncryptionAlgorithm A256GCM = fromString("A256GCM"); + @Generated + public static final JsonWebKeyEncryptionAlgorithm A192_KW = fromString("A192KW"); /** - * Static value A128KW for JsonWebKeyEncryptionAlgorithm. + * 256-bit AES key wrap. */ - public static final JsonWebKeyEncryptionAlgorithm A128KW = fromString("A128KW"); + @Generated + public static final JsonWebKeyEncryptionAlgorithm A256_KW = fromString("A256KW"); /** - * Static value A192KW for JsonWebKeyEncryptionAlgorithm. + * 128-bit AES-CBC. */ - public static final JsonWebKeyEncryptionAlgorithm A192KW = fromString("A192KW"); + @Generated + public static final JsonWebKeyEncryptionAlgorithm A128_CBC = fromString("A128CBC"); /** - * Static value A256KW for JsonWebKeyEncryptionAlgorithm. + * 192-bit AES-CBC. */ - public static final JsonWebKeyEncryptionAlgorithm A256KW = fromString("A256KW"); + @Generated + public static final JsonWebKeyEncryptionAlgorithm A192_CBC = fromString("A192CBC"); /** - * Static value A128CBC for JsonWebKeyEncryptionAlgorithm. + * 256-bit AES-CBC. */ - public static final JsonWebKeyEncryptionAlgorithm A128CBC = fromString("A128CBC"); + @Generated + public static final JsonWebKeyEncryptionAlgorithm A256_CBC = fromString("A256CBC"); /** - * Static value A192CBC for JsonWebKeyEncryptionAlgorithm. + * 128-bit AES-CBC with PKCS padding. */ - public static final JsonWebKeyEncryptionAlgorithm A192CBC = fromString("A192CBC"); + @Generated + public static final JsonWebKeyEncryptionAlgorithm A128_CBCPAD = fromString("A128CBCPAD"); /** - * Static value A256CBC for JsonWebKeyEncryptionAlgorithm. + * 192-bit AES-CBC with PKCS padding. */ - public static final JsonWebKeyEncryptionAlgorithm A256CBC = fromString("A256CBC"); + @Generated + public static final JsonWebKeyEncryptionAlgorithm A192_CBCPAD = fromString("A192CBCPAD"); /** - * Static value A128CBCPAD for JsonWebKeyEncryptionAlgorithm. + * 256-bit AES-CBC with PKCS padding. */ - public static final JsonWebKeyEncryptionAlgorithm A128CBCPAD = fromString("A128CBCPAD"); + @Generated + public static final JsonWebKeyEncryptionAlgorithm A256_CBCPAD = fromString("A256CBCPAD"); /** - * Static value A192CBCPAD for JsonWebKeyEncryptionAlgorithm. + * CKM AES key wrap. */ - public static final JsonWebKeyEncryptionAlgorithm A192CBCPAD = fromString("A192CBCPAD"); + @Generated + public static final JsonWebKeyEncryptionAlgorithm CKM_AES_KEY_WRAP = fromString("CKM_AES_KEY_WRAP"); /** - * Static value A256CBCPAD for JsonWebKeyEncryptionAlgorithm. + * CKM AES key wrap with padding. */ - public static final JsonWebKeyEncryptionAlgorithm A256CBCPAD = fromString("A256CBCPAD"); + @Generated + public static final JsonWebKeyEncryptionAlgorithm CKM_AES_KEY_WRAP_PAD = fromString("CKM_AES_KEY_WRAP_PAD"); /** * Creates a new instance of JsonWebKeyEncryptionAlgorithm value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ + @Generated @Deprecated public JsonWebKeyEncryptionAlgorithm() { } /** * Creates or finds a JsonWebKeyEncryptionAlgorithm from its string representation. - * + * * @param name a name to look for. * @return the corresponding JsonWebKeyEncryptionAlgorithm. */ + @Generated public static JsonWebKeyEncryptionAlgorithm fromString(String name) { return fromString(name, JsonWebKeyEncryptionAlgorithm.class); } /** * Gets known JsonWebKeyEncryptionAlgorithm values. - * + * * @return known JsonWebKeyEncryptionAlgorithm values. */ + @Generated public static Collection values() { return values(JsonWebKeyEncryptionAlgorithm.class); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/JsonWebKeySignatureAlgorithm.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/JsonWebKeySignatureAlgorithm.java index 791ca48500c0..087033aa1aeb 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/JsonWebKeySignatureAlgorithm.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/JsonWebKeySignatureAlgorithm.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.implementation.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -12,85 +12,100 @@ * JsonWebKeySignatureAlgorithm. */ public final class JsonWebKeySignatureAlgorithm extends ExpandableStringEnum { + /** * RSASSA-PSS using SHA-256 and MGF1 with SHA-256, as described in https://tools.ietf.org/html/rfc7518. */ + @Generated public static final JsonWebKeySignatureAlgorithm PS256 = fromString("PS256"); /** * RSASSA-PSS using SHA-384 and MGF1 with SHA-384, as described in https://tools.ietf.org/html/rfc7518. */ + @Generated public static final JsonWebKeySignatureAlgorithm PS384 = fromString("PS384"); /** * RSASSA-PSS using SHA-512 and MGF1 with SHA-512, as described in https://tools.ietf.org/html/rfc7518. */ + @Generated public static final JsonWebKeySignatureAlgorithm PS512 = fromString("PS512"); /** * RSASSA-PKCS1-v1_5 using SHA-256, as described in https://tools.ietf.org/html/rfc7518. */ + @Generated public static final JsonWebKeySignatureAlgorithm RS256 = fromString("RS256"); /** * RSASSA-PKCS1-v1_5 using SHA-384, as described in https://tools.ietf.org/html/rfc7518. */ + @Generated public static final JsonWebKeySignatureAlgorithm RS384 = fromString("RS384"); /** * RSASSA-PKCS1-v1_5 using SHA-512, as described in https://tools.ietf.org/html/rfc7518. */ + @Generated public static final JsonWebKeySignatureAlgorithm RS512 = fromString("RS512"); /** * Reserved. */ + @Generated public static final JsonWebKeySignatureAlgorithm RSNULL = fromString("RSNULL"); /** * ECDSA using P-256 and SHA-256, as described in https://tools.ietf.org/html/rfc7518. */ + @Generated public static final JsonWebKeySignatureAlgorithm ES256 = fromString("ES256"); /** * ECDSA using P-384 and SHA-384, as described in https://tools.ietf.org/html/rfc7518. */ + @Generated public static final JsonWebKeySignatureAlgorithm ES384 = fromString("ES384"); /** * ECDSA using P-521 and SHA-512, as described in https://tools.ietf.org/html/rfc7518. */ + @Generated public static final JsonWebKeySignatureAlgorithm ES512 = fromString("ES512"); /** * ECDSA using P-256K and SHA-256, as described in https://tools.ietf.org/html/rfc7518. */ - public static final JsonWebKeySignatureAlgorithm ES256K = fromString("ES256K"); + @Generated + public static final JsonWebKeySignatureAlgorithm ES256_K = fromString("ES256K"); /** * Creates a new instance of JsonWebKeySignatureAlgorithm value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ + @Generated @Deprecated public JsonWebKeySignatureAlgorithm() { } /** * Creates or finds a JsonWebKeySignatureAlgorithm from its string representation. - * + * * @param name a name to look for. * @return the corresponding JsonWebKeySignatureAlgorithm. */ + @Generated public static JsonWebKeySignatureAlgorithm fromString(String name) { return fromString(name, JsonWebKeySignatureAlgorithm.class); } /** * Gets known JsonWebKeySignatureAlgorithm values. - * + * * @return known JsonWebKeySignatureAlgorithm values. */ + @Generated public static Collection values() { return values(JsonWebKeySignatureAlgorithm.class); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyAttributes.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyAttributes.java index 8e207d0f06ee..585b500dd0fc 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyAttributes.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyAttributes.java @@ -1,11 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; @@ -17,10 +18,42 @@ * The attributes of a key managed by the key vault service. */ @Fluent -public final class KeyAttributes extends Attributes { +public final class KeyAttributes implements JsonSerializable { + + /* + * Determines whether the object is enabled. + */ + @Generated + private Boolean enabled; + + /* + * Not before date in UTC. + */ + @Generated + private Long notBefore; + + /* + * Expiry date in UTC. + */ + @Generated + private Long expires; + + /* + * Creation time in UTC. + */ + @Generated + private Long created; + + /* + * Last updated time in UTC. + */ + @Generated + private Long updated; + /* * softDelete data retention days. Value should be >=7 and <=90 when softDelete enabled, otherwise 0. */ + @Generated private Integer recoverableDays; /* @@ -28,93 +61,128 @@ public final class KeyAttributes extends Attributes { * 'Purgeable' the key can be permanently deleted by a privileged user; otherwise, only the system can purge the * key, at the end of the retention interval. */ + @Generated private DeletionRecoveryLevel recoveryLevel; /* * Indicates if the private key can be exported. Release policy must be provided when creating the first version of * an exportable key. */ + @Generated private Boolean exportable; /* * The underlying HSM Platform. */ + @Generated private String hsmPlatform; - /* - * Last updated time in UTC. + /** + * Creates an instance of KeyAttributes class. */ - private Long updated; + @Generated + public KeyAttributes() { + } - /* - * Creation time in UTC. + /** + * Get the enabled property: Determines whether the object is enabled. + * + * @return the enabled value. */ - private Long created; + @Generated + public Boolean isEnabled() { + return this.enabled; + } /** - * Creates an instance of KeyAttributes class. + * Set the enabled property: Determines whether the object is enabled. + * + * @param enabled the enabled value to set. + * @return the KeyAttributes object itself. */ - public KeyAttributes() { + @Generated + public KeyAttributes setEnabled(Boolean enabled) { + this.enabled = enabled; + return this; } /** - * Get the recoverableDays property: softDelete data retention days. Value should be >=7 and <=90 when - * softDelete enabled, otherwise 0. - * - * @return the recoverableDays value. + * Get the notBefore property: Not before date in UTC. + * + * @return the notBefore value. */ - public Integer getRecoverableDays() { - return this.recoverableDays; + @Generated + public OffsetDateTime getNotBefore() { + if (this.notBefore == null) { + return null; + } + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.notBefore), ZoneOffset.UTC); } /** - * Get the recoveryLevel property: Reflects the deletion recovery level currently in effect for keys in the current - * vault. If it contains 'Purgeable' the key can be permanently deleted by a privileged user; otherwise, only the - * system can purge the key, at the end of the retention interval. - * - * @return the recoveryLevel value. + * Set the notBefore property: Not before date in UTC. + * + * @param notBefore the notBefore value to set. + * @return the KeyAttributes object itself. */ - public DeletionRecoveryLevel getRecoveryLevel() { - return this.recoveryLevel; + @Generated + public KeyAttributes setNotBefore(OffsetDateTime notBefore) { + if (notBefore == null) { + this.notBefore = null; + } else { + this.notBefore = notBefore.toEpochSecond(); + } + return this; } /** - * Get the exportable property: Indicates if the private key can be exported. Release policy must be provided when - * creating the first version of an exportable key. - * - * @return the exportable value. + * Get the expires property: Expiry date in UTC. + * + * @return the expires value. */ - public Boolean isExportable() { - return this.exportable; + @Generated + public OffsetDateTime getExpires() { + if (this.expires == null) { + return null; + } + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.expires), ZoneOffset.UTC); } /** - * Set the exportable property: Indicates if the private key can be exported. Release policy must be provided when - * creating the first version of an exportable key. - * - * @param exportable the exportable value to set. + * Set the expires property: Expiry date in UTC. + * + * @param expires the expires value to set. * @return the KeyAttributes object itself. */ - public KeyAttributes setExportable(Boolean exportable) { - this.exportable = exportable; + @Generated + public KeyAttributes setExpires(OffsetDateTime expires) { + if (expires == null) { + this.expires = null; + } else { + this.expires = expires.toEpochSecond(); + } return this; } /** - * Get the hsmPlatform property: The underlying HSM Platform. - * - * @return the hsmPlatform value. + * Get the created property: Creation time in UTC. + * + * @return the created value. */ - public String getHsmPlatform() { - return this.hsmPlatform; + @Generated + public OffsetDateTime getCreated() { + if (this.created == null) { + return null; + } + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.created), ZoneOffset.UTC); } /** * Get the updated property: Last updated time in UTC. - * + * * @return the updated value. */ - @Override + @Generated public OffsetDateTime getUpdated() { if (this.updated == null) { return null; @@ -123,91 +191,97 @@ public OffsetDateTime getUpdated() { } /** - * Get the created property: Creation time in UTC. - * - * @return the created value. + * Get the recoverableDays property: softDelete data retention days. Value should be >=7 and <=90 when + * softDelete enabled, otherwise 0. + * + * @return the recoverableDays value. */ - @Override - public OffsetDateTime getCreated() { - if (this.created == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.created), ZoneOffset.UTC); + @Generated + public Integer getRecoverableDays() { + return this.recoverableDays; } /** - * {@inheritDoc} + * Get the recoveryLevel property: Reflects the deletion recovery level currently in effect for keys in the current + * vault. If it contains 'Purgeable' the key can be permanently deleted by a privileged user; otherwise, only the + * system can purge the key, at the end of the retention interval. + * + * @return the recoveryLevel value. */ - @Override - public KeyAttributes setEnabled(Boolean enabled) { - super.setEnabled(enabled); - return this; + @Generated + public DeletionRecoveryLevel getRecoveryLevel() { + return this.recoveryLevel; } /** - * {@inheritDoc} + * Get the exportable property: Indicates if the private key can be exported. Release policy must be provided when + * creating the first version of an exportable key. + * + * @return the exportable value. */ - @Override - public KeyAttributes setNotBefore(OffsetDateTime notBefore) { - super.setNotBefore(notBefore); - return this; + @Generated + public Boolean isExportable() { + return this.exportable; } /** - * {@inheritDoc} + * Set the exportable property: Indicates if the private key can be exported. Release policy must be provided when + * creating the first version of an exportable key. + * + * @param exportable the exportable value to set. + * @return the KeyAttributes object itself. */ - @Override - public KeyAttributes setExpires(OffsetDateTime expires) { - super.setExpires(expires); + @Generated + public KeyAttributes setExportable(Boolean exportable) { + this.exportable = exportable; return this; } + /** + * Get the hsmPlatform property: The underlying HSM Platform. + * + * @return the hsmPlatform value. + */ + @Generated + public String getHsmPlatform() { + return this.hsmPlatform; + } + /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeBooleanField("enabled", isEnabled()); - if (getNotBefore() != null) { - jsonWriter.writeNumberField("nbf", getNotBefore().toEpochSecond()); - } - if (getExpires() != null) { - jsonWriter.writeNumberField("exp", getExpires().toEpochSecond()); - } + jsonWriter.writeBooleanField("enabled", this.enabled); + jsonWriter.writeNumberField("nbf", this.notBefore); + jsonWriter.writeNumberField("exp", this.expires); jsonWriter.writeBooleanField("exportable", this.exportable); return jsonWriter.writeEndObject(); } /** * Reads an instance of KeyAttributes from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KeyAttributes 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 KeyAttributes. */ + @Generated public static KeyAttributes fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { KeyAttributes deserializedKeyAttributes = new KeyAttributes(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("enabled".equals(fieldName)) { - deserializedKeyAttributes.setEnabled(reader.getNullable(JsonReader::getBoolean)); + deserializedKeyAttributes.enabled = reader.getNullable(JsonReader::getBoolean); } else if ("nbf".equals(fieldName)) { - Long notBeforeHolder = reader.getNullable(JsonReader::getLong); - if (notBeforeHolder != null) { - deserializedKeyAttributes.setNotBefore( - OffsetDateTime.ofInstant(Instant.ofEpochSecond(notBeforeHolder), ZoneOffset.UTC)); - } + deserializedKeyAttributes.notBefore = reader.getNullable(JsonReader::getLong); } else if ("exp".equals(fieldName)) { - Long expiresHolder = reader.getNullable(JsonReader::getLong); - if (expiresHolder != null) { - deserializedKeyAttributes - .setExpires(OffsetDateTime.ofInstant(Instant.ofEpochSecond(expiresHolder), ZoneOffset.UTC)); - } + deserializedKeyAttributes.expires = reader.getNullable(JsonReader::getLong); } else if ("created".equals(fieldName)) { deserializedKeyAttributes.created = reader.getNullable(JsonReader::getLong); } else if ("updated".equals(fieldName)) { @@ -224,7 +298,6 @@ public static KeyAttributes fromJson(JsonReader jsonReader) throws IOException { reader.skipChildren(); } } - return deserializedKeyAttributes; }); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyBundle.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyBundle.java index ca2eb19b893a..8147bec034d7 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyBundle.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyBundle.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -15,145 +15,102 @@ /** * A KeyBundle consisting of a WebKey plus its attributes. */ -@Fluent -public class KeyBundle implements JsonSerializable { +@Immutable +public final class KeyBundle implements JsonSerializable { + /* * The Json web key. */ + @Generated private JsonWebKey key; /* * The key management attributes. */ + @Generated private KeyAttributes attributes; /* * Application specific metadata in the form of key-value pairs. */ + @Generated private Map tags; /* * True if the key's lifetime is managed by key vault. If this is a key backing a certificate, then managed will be * true. */ + @Generated private Boolean managed; /* * The policy rules under which the key can be exported. */ + @Generated private KeyReleasePolicy releasePolicy; /** * Creates an instance of KeyBundle class. */ - public KeyBundle() { + @Generated + private KeyBundle() { } /** * Get the key property: The Json web key. - * + * * @return the key value. */ + @Generated public JsonWebKey getKey() { return this.key; } - /** - * Set the key property: The Json web key. - * - * @param key the key value to set. - * @return the KeyBundle object itself. - */ - public KeyBundle setKey(JsonWebKey key) { - this.key = key; - return this; - } - /** * Get the attributes property: The key management attributes. - * + * * @return the attributes value. */ + @Generated public KeyAttributes getAttributes() { return this.attributes; } - /** - * Set the attributes property: The key management attributes. - * - * @param attributes the attributes value to set. - * @return the KeyBundle object itself. - */ - public KeyBundle setAttributes(KeyAttributes attributes) { - this.attributes = attributes; - return this; - } - /** * Get the tags property: Application specific metadata in the form of key-value pairs. - * + * * @return the tags value. */ + @Generated public Map getTags() { return this.tags; } - /** - * Set the tags property: Application specific metadata in the form of key-value pairs. - * - * @param tags the tags value to set. - * @return the KeyBundle object itself. - */ - public KeyBundle setTags(Map tags) { - this.tags = tags; - return this; - } - /** * Get the managed property: True if the key's lifetime is managed by key vault. If this is a key backing a * certificate, then managed will be true. - * + * * @return the managed value. */ + @Generated public Boolean isManaged() { return this.managed; } - /** - * Set the managed property: True if the key's lifetime is managed by key vault. If this is a key backing a - * certificate, then managed will be true. - * - * @param managed the managed value to set. - * @return the KeyBundle object itself. - */ - KeyBundle setManaged(Boolean managed) { - this.managed = managed; - return this; - } - /** * Get the releasePolicy property: The policy rules under which the key can be exported. - * + * * @return the releasePolicy value. */ + @Generated public KeyReleasePolicy getReleasePolicy() { return this.releasePolicy; } - /** - * Set the releasePolicy property: The policy rules under which the key can be exported. - * - * @param releasePolicy the releasePolicy value to set. - * @return the KeyBundle object itself. - */ - public KeyBundle setReleasePolicy(KeyReleasePolicy releasePolicy) { - this.releasePolicy = releasePolicy; - return this; - } - /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -166,19 +123,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KeyBundle from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KeyBundle 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 KeyBundle. */ + @Generated public static KeyBundle fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { KeyBundle deserializedKeyBundle = new KeyBundle(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("key".equals(fieldName)) { deserializedKeyBundle.key = JsonWebKey.fromJson(reader); } else if ("attributes".equals(fieldName)) { @@ -194,7 +151,6 @@ public static KeyBundle fromJson(JsonReader jsonReader) throws IOException { reader.skipChildren(); } } - return deserializedKeyBundle; }); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyCreateParameters.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyCreateParameters.java index a01382b38fd9..37d767fe5c9d 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyCreateParameters.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyCreateParameters.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -21,89 +21,92 @@ */ @Fluent public final class KeyCreateParameters implements JsonSerializable { + /* - * JsonWebKey Key Type (kty), as defined in https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. + * The type of key to create. For valid values, see JsonWebKeyType. */ - private KeyType kty; + @Generated + private final KeyType kty; /* * The key size in bits. For example: 2048, 3072, or 4096 for RSA. */ + @Generated private Integer keySize; /* * The public exponent for a RSA key. */ + @Generated private Integer publicExponent; /* - * The key_ops property. + * Json web key operations. For more information on possible key operations, see JsonWebKeyOperation. */ + @Generated private List keyOps; /* * The attributes of a key managed by the key vault service. */ + @Generated private KeyAttributes keyAttributes; /* * Application specific metadata in the form of key-value pairs. */ + @Generated private Map tags; /* - * Elliptic curve name. + * Elliptic curve name. For valid values, see JsonWebKeyCurveName. */ - private KeyCurveName crv; + @Generated + private KeyCurveName curve; /* * The policy rules under which the key can be exported. */ + @Generated private KeyReleasePolicy releasePolicy; /** * Creates an instance of KeyCreateParameters class. + * + * @param kty the kty value to set. */ - public KeyCreateParameters() { + @Generated + public KeyCreateParameters(KeyType kty) { + this.kty = kty; } /** - * Get the kty property: JsonWebKey Key Type (kty), as defined in - * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - * + * Get the kty property: The type of key to create. For valid values, see JsonWebKeyType. + * * @return the kty value. */ + @Generated public KeyType getKty() { return this.kty; } - /** - * Set the kty property: JsonWebKey Key Type (kty), as defined in - * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - * - * @param kty the kty value to set. - * @return the KeyCreateParameters object itself. - */ - public KeyCreateParameters setKty(KeyType kty) { - this.kty = kty; - return this; - } - /** * Get the keySize property: The key size in bits. For example: 2048, 3072, or 4096 for RSA. - * + * * @return the keySize value. */ + @Generated public Integer getKeySize() { return this.keySize; } /** * Set the keySize property: The key size in bits. For example: 2048, 3072, or 4096 for RSA. - * + * * @param keySize the keySize value to set. * @return the KeyCreateParameters object itself. */ + @Generated public KeyCreateParameters setKeySize(Integer keySize) { this.keySize = keySize; return this; @@ -111,39 +114,45 @@ public KeyCreateParameters setKeySize(Integer keySize) { /** * Get the publicExponent property: The public exponent for a RSA key. - * + * * @return the publicExponent value. */ + @Generated public Integer getPublicExponent() { return this.publicExponent; } /** * Set the publicExponent property: The public exponent for a RSA key. - * + * * @param publicExponent the publicExponent value to set. * @return the KeyCreateParameters object itself. */ + @Generated public KeyCreateParameters setPublicExponent(Integer publicExponent) { this.publicExponent = publicExponent; return this; } /** - * Get the keyOps property: The key_ops property. - * + * Get the keyOps property: Json web key operations. For more information on possible key operations, see + * JsonWebKeyOperation. + * * @return the keyOps value. */ + @Generated public List getKeyOps() { return this.keyOps; } /** - * Set the keyOps property: The key_ops property. - * + * Set the keyOps property: Json web key operations. For more information on possible key operations, see + * JsonWebKeyOperation. + * * @param keyOps the keyOps value to set. * @return the KeyCreateParameters object itself. */ + @Generated public KeyCreateParameters setKeyOps(List keyOps) { this.keyOps = keyOps; return this; @@ -151,19 +160,21 @@ public KeyCreateParameters setKeyOps(List keyOps) { /** * Get the keyAttributes property: The attributes of a key managed by the key vault service. - * + * * @return the keyAttributes value. */ + @Generated public KeyAttributes getKeyAttributes() { return this.keyAttributes; } /** * Set the keyAttributes property: The attributes of a key managed by the key vault service. - * + * * @param keyAttributes the keyAttributes value to set. * @return the KeyCreateParameters object itself. */ + @Generated public KeyCreateParameters setKeyAttributes(KeyAttributes keyAttributes) { this.keyAttributes = keyAttributes; return this; @@ -171,59 +182,65 @@ public KeyCreateParameters setKeyAttributes(KeyAttributes keyAttributes) { /** * Get the tags property: Application specific metadata in the form of key-value pairs. - * + * * @return the tags value. */ + @Generated public Map getTags() { return this.tags; } /** * Set the tags property: Application specific metadata in the form of key-value pairs. - * + * * @param tags the tags value to set. * @return the KeyCreateParameters object itself. */ + @Generated public KeyCreateParameters setTags(Map tags) { this.tags = tags; return this; } /** - * Get the crv property: Elliptic curve name. - * - * @return the crv value. + * Get the curve property: Elliptic curve name. For valid values, see JsonWebKeyCurveName. + * + * @return the curve value. */ - public KeyCurveName getCrv() { - return this.crv; + @Generated + public KeyCurveName getCurve() { + return this.curve; } /** - * Set the crv property: Elliptic curve name. - * - * @param crv the crv value to set. + * Set the curve property: Elliptic curve name. For valid values, see JsonWebKeyCurveName. + * + * @param curve the curve value to set. * @return the KeyCreateParameters object itself. */ - public KeyCreateParameters setCrv(KeyCurveName crv) { - this.crv = crv; + @Generated + public KeyCreateParameters setCurve(KeyCurveName curve) { + this.curve = curve; return this; } /** * Get the releasePolicy property: The policy rules under which the key can be exported. - * + * * @return the releasePolicy value. */ + @Generated public KeyReleasePolicy getReleasePolicy() { return this.releasePolicy; } /** * Set the releasePolicy property: The policy rules under which the key can be exported. - * + * * @param releasePolicy the releasePolicy value to set. * @return the KeyCreateParameters object itself. */ + @Generated public KeyCreateParameters setReleasePolicy(KeyReleasePolicy releasePolicy) { this.releasePolicy = releasePolicy; return this; @@ -232,6 +249,7 @@ public KeyCreateParameters setReleasePolicy(KeyReleasePolicy releasePolicy) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -242,51 +260,62 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { (writer, element) -> writer.writeString(element == null ? null : element.toString())); jsonWriter.writeJsonField("attributes", this.keyAttributes); jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); - jsonWriter.writeStringField("crv", this.crv == null ? null : this.crv.toString()); + jsonWriter.writeStringField("crv", this.curve == null ? null : this.curve.toString()); jsonWriter.writeJsonField("release_policy", this.releasePolicy); return jsonWriter.writeEndObject(); } /** * Reads an instance of KeyCreateParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KeyCreateParameters 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 KeyCreateParameters. */ + @Generated public static KeyCreateParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - KeyCreateParameters deserializedKeyCreateParameters = new KeyCreateParameters(); + KeyType kty = null; + Integer keySize = null; + Integer publicExponent = null; + List keyOps = null; + KeyAttributes keyAttributes = null; + Map tags = null; + KeyCurveName curve = null; + KeyReleasePolicy releasePolicy = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("kty".equals(fieldName)) { - deserializedKeyCreateParameters.kty = KeyType.fromString(reader.getString()); + kty = KeyType.fromString(reader.getString()); } else if ("key_size".equals(fieldName)) { - deserializedKeyCreateParameters.keySize = reader.getNullable(JsonReader::getInt); + keySize = reader.getNullable(JsonReader::getInt); } else if ("public_exponent".equals(fieldName)) { - deserializedKeyCreateParameters.publicExponent = reader.getNullable(JsonReader::getInt); + publicExponent = reader.getNullable(JsonReader::getInt); } else if ("key_ops".equals(fieldName)) { - List keyOps - = reader.readArray(reader1 -> KeyOperation.fromString(reader1.getString())); - deserializedKeyCreateParameters.keyOps = keyOps; + keyOps = reader.readArray(reader1 -> KeyOperation.fromString(reader1.getString())); } else if ("attributes".equals(fieldName)) { - deserializedKeyCreateParameters.keyAttributes = KeyAttributes.fromJson(reader); + keyAttributes = KeyAttributes.fromJson(reader); } else if ("tags".equals(fieldName)) { - Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedKeyCreateParameters.tags = tags; + tags = reader.readMap(reader1 -> reader1.getString()); } else if ("crv".equals(fieldName)) { - deserializedKeyCreateParameters.crv = KeyCurveName.fromString(reader.getString()); + curve = KeyCurveName.fromString(reader.getString()); } else if ("release_policy".equals(fieldName)) { - deserializedKeyCreateParameters.releasePolicy = KeyReleasePolicy.fromJson(reader); + releasePolicy = KeyReleasePolicy.fromJson(reader); } else { reader.skipChildren(); } } - + KeyCreateParameters deserializedKeyCreateParameters = new KeyCreateParameters(kty); + deserializedKeyCreateParameters.keySize = keySize; + deserializedKeyCreateParameters.publicExponent = publicExponent; + deserializedKeyCreateParameters.keyOps = keyOps; + deserializedKeyCreateParameters.keyAttributes = keyAttributes; + deserializedKeyCreateParameters.tags = tags; + deserializedKeyCreateParameters.curve = curve; + deserializedKeyCreateParameters.releasePolicy = releasePolicy; return deserializedKeyCreateParameters; }); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyExportParameters.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyExportParameters.java deleted file mode 100644 index 97533a27ac5b..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyExportParameters.java +++ /dev/null @@ -1,146 +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.security.keyvault.keys.implementation.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.security.keyvault.keys.models.KeyExportEncryptionAlgorithm; -import java.io.IOException; - -/** - * The export key parameters. - */ -@Fluent -public final class KeyExportParameters implements JsonSerializable { - /* - * The export key encryption Json web key. This key MUST be a RSA key that supports encryption. - */ - private JsonWebKey wrappingKey; - - /* - * The export key encryption key identifier. This key MUST be a RSA key that supports encryption. - */ - private String wrappingKid; - - /* - * The encryption algorithm to use to protected the exported key material - */ - private KeyExportEncryptionAlgorithm enc; - - /** - * Creates an instance of KeyExportParameters class. - */ - public KeyExportParameters() { - } - - /** - * Get the wrappingKey property: The export key encryption Json web key. This key MUST be a RSA key that supports - * encryption. - * - * @return the wrappingKey value. - */ - public JsonWebKey getWrappingKey() { - return this.wrappingKey; - } - - /** - * Set the wrappingKey property: The export key encryption Json web key. This key MUST be a RSA key that supports - * encryption. - * - * @param wrappingKey the wrappingKey value to set. - * @return the KeyExportParameters object itself. - */ - public KeyExportParameters setWrappingKey(JsonWebKey wrappingKey) { - this.wrappingKey = wrappingKey; - return this; - } - - /** - * Get the wrappingKid property: The export key encryption key identifier. This key MUST be a RSA key that supports - * encryption. - * - * @return the wrappingKid value. - */ - public String getWrappingKid() { - return this.wrappingKid; - } - - /** - * Set the wrappingKid property: The export key encryption key identifier. This key MUST be a RSA key that supports - * encryption. - * - * @param wrappingKid the wrappingKid value to set. - * @return the KeyExportParameters object itself. - */ - public KeyExportParameters setWrappingKid(String wrappingKid) { - this.wrappingKid = wrappingKid; - return this; - } - - /** - * Get the enc property: The encryption algorithm to use to protected the exported key material. - * - * @return the enc value. - */ - public KeyExportEncryptionAlgorithm getEnc() { - return this.enc; - } - - /** - * Set the enc property: The encryption algorithm to use to protected the exported key material. - * - * @param enc the enc value to set. - * @return the KeyExportParameters object itself. - */ - public KeyExportParameters setEnc(KeyExportEncryptionAlgorithm enc) { - this.enc = enc; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeJsonField("wrappingKey", this.wrappingKey); - jsonWriter.writeStringField("wrappingKid", this.wrappingKid); - jsonWriter.writeStringField("enc", this.enc == null ? null : this.enc.toString()); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KeyExportParameters from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KeyExportParameters 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 KeyExportParameters. - */ - public static KeyExportParameters fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeyExportParameters deserializedKeyExportParameters = new KeyExportParameters(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("wrappingKey".equals(fieldName)) { - deserializedKeyExportParameters.wrappingKey = JsonWebKey.fromJson(reader); - } else if ("wrappingKid".equals(fieldName)) { - deserializedKeyExportParameters.wrappingKid = reader.getString(); - } else if ("enc".equals(fieldName)) { - deserializedKeyExportParameters.enc = KeyExportEncryptionAlgorithm.fromString(reader.getString()); - } else { - reader.skipChildren(); - } - } - - return deserializedKeyExportParameters; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyImportParameters.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyImportParameters.java index 35bd87eb23ef..b274f3b8ba47 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyImportParameters.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyImportParameters.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -17,52 +17,64 @@ */ @Fluent public final class KeyImportParameters implements JsonSerializable { + /* * Whether to import as a hardware key (HSM) or software key. */ + @Generated private Boolean hsm; /* * The Json web key */ - private JsonWebKey key; + @Generated + private final JsonWebKey key; /* * The key management attributes. */ + @Generated private KeyAttributes keyAttributes; /* * Application specific metadata in the form of key-value pairs. */ + @Generated private Map tags; /* * The policy rules under which the key can be exported. */ + @Generated private KeyReleasePolicy releasePolicy; /** * Creates an instance of KeyImportParameters class. + * + * @param key the key value to set. */ - public KeyImportParameters() { + @Generated + public KeyImportParameters(JsonWebKey key) { + this.key = key; } /** * Get the hsm property: Whether to import as a hardware key (HSM) or software key. - * + * * @return the hsm value. */ + @Generated public Boolean isHsm() { return this.hsm; } /** * Set the hsm property: Whether to import as a hardware key (HSM) or software key. - * + * * @param hsm the hsm value to set. * @return the KeyImportParameters object itself. */ + @Generated public KeyImportParameters setHsm(Boolean hsm) { this.hsm = hsm; return this; @@ -70,39 +82,31 @@ public KeyImportParameters setHsm(Boolean hsm) { /** * Get the key property: The Json web key. - * + * * @return the key value. */ + @Generated public JsonWebKey getKey() { return this.key; } - /** - * Set the key property: The Json web key. - * - * @param key the key value to set. - * @return the KeyImportParameters object itself. - */ - public KeyImportParameters setKey(JsonWebKey key) { - this.key = key; - return this; - } - /** * Get the keyAttributes property: The key management attributes. - * + * * @return the keyAttributes value. */ + @Generated public KeyAttributes getKeyAttributes() { return this.keyAttributes; } /** * Set the keyAttributes property: The key management attributes. - * + * * @param keyAttributes the keyAttributes value to set. * @return the KeyImportParameters object itself. */ + @Generated public KeyImportParameters setKeyAttributes(KeyAttributes keyAttributes) { this.keyAttributes = keyAttributes; return this; @@ -110,19 +114,21 @@ public KeyImportParameters setKeyAttributes(KeyAttributes keyAttributes) { /** * Get the tags property: Application specific metadata in the form of key-value pairs. - * + * * @return the tags value. */ + @Generated public Map getTags() { return this.tags; } /** * Set the tags property: Application specific metadata in the form of key-value pairs. - * + * * @param tags the tags value to set. * @return the KeyImportParameters object itself. */ + @Generated public KeyImportParameters setTags(Map tags) { this.tags = tags; return this; @@ -130,19 +136,21 @@ public KeyImportParameters setTags(Map tags) { /** * Get the releasePolicy property: The policy rules under which the key can be exported. - * + * * @return the releasePolicy value. */ + @Generated public KeyReleasePolicy getReleasePolicy() { return this.releasePolicy; } /** * Set the releasePolicy property: The policy rules under which the key can be exported. - * + * * @param releasePolicy the releasePolicy value to set. * @return the KeyImportParameters object itself. */ + @Generated public KeyImportParameters setReleasePolicy(KeyReleasePolicy releasePolicy) { this.releasePolicy = releasePolicy; return this; @@ -151,6 +159,7 @@ public KeyImportParameters setReleasePolicy(KeyReleasePolicy releasePolicy) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -164,36 +173,43 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KeyImportParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KeyImportParameters 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 KeyImportParameters. */ + @Generated public static KeyImportParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - KeyImportParameters deserializedKeyImportParameters = new KeyImportParameters(); + JsonWebKey key = null; + Boolean hsm = null; + KeyAttributes keyAttributes = null; + Map tags = null; + KeyReleasePolicy releasePolicy = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("key".equals(fieldName)) { - deserializedKeyImportParameters.key = JsonWebKey.fromJson(reader); + key = JsonWebKey.fromJson(reader); } else if ("Hsm".equals(fieldName)) { - deserializedKeyImportParameters.hsm = reader.getNullable(JsonReader::getBoolean); + hsm = reader.getNullable(JsonReader::getBoolean); } else if ("attributes".equals(fieldName)) { - deserializedKeyImportParameters.keyAttributes = KeyAttributes.fromJson(reader); + keyAttributes = KeyAttributes.fromJson(reader); } else if ("tags".equals(fieldName)) { - Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedKeyImportParameters.tags = tags; + tags = reader.readMap(reader1 -> reader1.getString()); } else if ("release_policy".equals(fieldName)) { - deserializedKeyImportParameters.releasePolicy = KeyReleasePolicy.fromJson(reader); + releasePolicy = KeyReleasePolicy.fromJson(reader); } else { reader.skipChildren(); } } - + KeyImportParameters deserializedKeyImportParameters = new KeyImportParameters(key); + deserializedKeyImportParameters.hsm = hsm; + deserializedKeyImportParameters.keyAttributes = keyAttributes; + deserializedKeyImportParameters.tags = tags; + deserializedKeyImportParameters.releasePolicy = releasePolicy; return deserializedKeyImportParameters; }); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyItem.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyItem.java index b21d84785ae1..71b8589b5014 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyItem.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyItem.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -15,120 +15,86 @@ /** * The key item containing key metadata. */ -@Fluent -public class KeyItem implements JsonSerializable { +@Immutable +public final class KeyItem implements JsonSerializable { + /* * Key identifier. */ + @Generated private String kid; /* * The key management attributes. */ + @Generated private KeyAttributes attributes; /* * Application specific metadata in the form of key-value pairs. */ + @Generated private Map tags; /* * True if the key's lifetime is managed by key vault. If this is a key backing a certificate, then managed will be * true. */ + @Generated private Boolean managed; /** * Creates an instance of KeyItem class. */ - public KeyItem() { + @Generated + private KeyItem() { } /** * Get the kid property: Key identifier. - * + * * @return the kid value. */ + @Generated public String getKid() { return this.kid; } - /** - * Set the kid property: Key identifier. - * - * @param kid the kid value to set. - * @return the KeyItem object itself. - */ - public KeyItem setKid(String kid) { - this.kid = kid; - return this; - } - /** * Get the attributes property: The key management attributes. - * + * * @return the attributes value. */ + @Generated public KeyAttributes getAttributes() { return this.attributes; } - /** - * Set the attributes property: The key management attributes. - * - * @param attributes the attributes value to set. - * @return the KeyItem object itself. - */ - public KeyItem setAttributes(KeyAttributes attributes) { - this.attributes = attributes; - return this; - } - /** * Get the tags property: Application specific metadata in the form of key-value pairs. - * + * * @return the tags value. */ + @Generated public Map getTags() { return this.tags; } - /** - * Set the tags property: Application specific metadata in the form of key-value pairs. - * - * @param tags the tags value to set. - * @return the KeyItem object itself. - */ - public KeyItem setTags(Map tags) { - this.tags = tags; - return this; - } - /** * Get the managed property: True if the key's lifetime is managed by key vault. If this is a key backing a * certificate, then managed will be true. - * + * * @return the managed value. */ + @Generated public Boolean isManaged() { return this.managed; } - /** - * Set the managed property: True if the key's lifetime is managed by key vault. If this is a key backing a - * certificate, then managed will be true. - * - * @param managed the managed value to set. - * @return the KeyItem object itself. - */ - KeyItem setManaged(Boolean managed) { - this.managed = managed; - return this; - } - /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -140,19 +106,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KeyItem from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KeyItem 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 KeyItem. */ + @Generated public static KeyItem fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { KeyItem deserializedKeyItem = new KeyItem(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("kid".equals(fieldName)) { deserializedKeyItem.kid = reader.getString(); } else if ("attributes".equals(fieldName)) { @@ -166,7 +132,6 @@ public static KeyItem fromJson(JsonReader jsonReader) throws IOException { reader.skipChildren(); } } - return deserializedKeyItem; }); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyListResult.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyListResult.java deleted file mode 100644 index 10787e79d6fd..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyListResult.java +++ /dev/null @@ -1,92 +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.security.keyvault.keys.implementation.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; -import java.util.List; - -/** - * The key list result. - */ -@Immutable -public final class KeyListResult implements JsonSerializable { - /* - * A response message containing a list of keys in the key vault along with a link to the next page of keys. - */ - private List value; - - /* - * The URL to get the next set of keys. - */ - private String nextLink; - - /** - * Creates an instance of KeyListResult class. - */ - public KeyListResult() { - } - - /** - * Get the value property: A response message containing a list of keys in the key vault along with a link to the - * next page of keys. - * - * @return the value value. - */ - public List getValue() { - return this.value; - } - - /** - * Get the nextLink property: The URL to get the next set of keys. - * - * @return the nextLink value. - */ - public String getNextLink() { - return this.nextLink; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KeyListResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KeyListResult 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 KeyListResult. - */ - public static KeyListResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeyListResult deserializedKeyListResult = new KeyListResult(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - List value = reader.readArray(reader1 -> KeyItem.fromJson(reader1)); - deserializedKeyListResult.value = value; - } else if ("nextLink".equals(fieldName)) { - deserializedKeyListResult.nextLink = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedKeyListResult; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyOperationResult.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyOperationResult.java index 4a32c1bc1a9d..b494ce481408 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyOperationResult.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyOperationResult.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.implementation.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.core.util.Base64Url; import com.azure.json.JsonReader; @@ -17,51 +17,60 @@ */ @Immutable public final class KeyOperationResult implements JsonSerializable { + /* * Key identifier */ + @Generated private String kid; /* - * The value property. + * The result of the operation. */ + @Generated private Base64Url result; /* - * The iv property. + * Cryptographically random, non-repeating initialization vector for symmetric algorithms. */ + @Generated private Base64Url iv; /* - * The tag property. + * The tag to authenticate when performing decryption with an authenticated algorithm. */ + @Generated private Base64Url authenticationTag; /* - * The aad property. + * Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. */ + @Generated private Base64Url additionalAuthenticatedData; /** * Creates an instance of KeyOperationResult class. */ - public KeyOperationResult() { + @Generated + private KeyOperationResult() { } /** * Get the kid property: Key identifier. - * + * * @return the kid value. */ + @Generated public String getKid() { return this.kid; } /** - * Get the result property: The value property. - * + * Get the result property: The result of the operation. + * * @return the result value. */ + @Generated public byte[] getResult() { if (this.result == null) { return null; @@ -70,10 +79,11 @@ public byte[] getResult() { } /** - * Get the iv property: The iv property. - * + * Get the iv property: Cryptographically random, non-repeating initialization vector for symmetric algorithms. + * * @return the iv value. */ + @Generated public byte[] getIv() { if (this.iv == null) { return null; @@ -82,10 +92,12 @@ public byte[] getIv() { } /** - * Get the authenticationTag property: The tag property. - * + * Get the authenticationTag property: The tag to authenticate when performing decryption with an authenticated + * algorithm. + * * @return the authenticationTag value. */ + @Generated public byte[] getAuthenticationTag() { if (this.authenticationTag == null) { return null; @@ -94,10 +106,12 @@ public byte[] getAuthenticationTag() { } /** - * Get the additionalAuthenticatedData property: The aad property. - * + * Get the additionalAuthenticatedData property: Additional data to authenticate but not encrypt/decrypt when using + * authenticated crypto algorithms. + * * @return the additionalAuthenticatedData value. */ + @Generated public byte[] getAdditionalAuthenticatedData() { if (this.additionalAuthenticatedData == null) { return null; @@ -108,6 +122,7 @@ public byte[] getAdditionalAuthenticatedData() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -116,19 +131,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KeyOperationResult from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KeyOperationResult 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 KeyOperationResult. */ + @Generated public static KeyOperationResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { KeyOperationResult deserializedKeyOperationResult = new KeyOperationResult(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("kid".equals(fieldName)) { deserializedKeyOperationResult.kid = reader.getString(); } else if ("value".equals(fieldName)) { @@ -147,7 +162,6 @@ public static KeyOperationResult fromJson(JsonReader jsonReader) throws IOExcept reader.skipChildren(); } } - return deserializedKeyOperationResult; }); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyOperationsParameters.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyOperationsParameters.java index ecb81c28fde7..b84626b4e4a1 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyOperationsParameters.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyOperationsParameters.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.core.util.Base64Url; import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; @@ -19,62 +19,69 @@ */ @Fluent public final class KeyOperationsParameters implements JsonSerializable { + /* * algorithm identifier */ - private JsonWebKeyEncryptionAlgorithm algorithm; + @Generated + private final JsonWebKeyEncryptionAlgorithm algorithm; /* - * The value property. + * The value to operate on. */ - private Base64Url value; + @Generated + private final Base64Url value; /* * Cryptographically random, non-repeating initialization vector for symmetric algorithms. */ + @Generated private Base64Url iv; /* * Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. */ + @Generated private Base64Url aad; /* * The tag to authenticate when performing decryption with an authenticated algorithm. */ + @Generated private Base64Url tag; /** * Creates an instance of KeyOperationsParameters class. + * + * @param algorithm the algorithm value to set. + * @param value the value value to set. */ - public KeyOperationsParameters() { + @Generated + public KeyOperationsParameters(JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) { + this.algorithm = algorithm; + if (value == null) { + this.value = null; + } else { + this.value = Base64Url.encode(value); + } } /** * Get the algorithm property: algorithm identifier. - * + * * @return the algorithm value. */ + @Generated public JsonWebKeyEncryptionAlgorithm getAlgorithm() { return this.algorithm; } /** - * Set the algorithm property: algorithm identifier. - * - * @param algorithm the algorithm value to set. - * @return the KeyOperationsParameters object itself. - */ - public KeyOperationsParameters setAlgorithm(JsonWebKeyEncryptionAlgorithm algorithm) { - this.algorithm = algorithm; - return this; - } - - /** - * Get the value property: The value property. - * + * Get the value property: The value to operate on. + * * @return the value value. */ + @Generated public byte[] getValue() { if (this.value == null) { return null; @@ -82,26 +89,12 @@ public byte[] getValue() { return this.value.decodedBytes(); } - /** - * Set the value property: The value property. - * - * @param value the value value to set. - * @return the KeyOperationsParameters object itself. - */ - public KeyOperationsParameters setValue(byte[] value) { - if (value == null) { - this.value = null; - } else { - this.value = Base64Url.encode(CoreUtils.clone(value)); - } - return this; - } - /** * Get the iv property: Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * + * * @return the iv value. */ + @Generated public byte[] getIv() { if (this.iv == null) { return null; @@ -111,10 +104,11 @@ public byte[] getIv() { /** * Set the iv property: Cryptographically random, non-repeating initialization vector for symmetric algorithms. - * + * * @param iv the iv value to set. * @return the KeyOperationsParameters object itself. */ + @Generated public KeyOperationsParameters setIv(byte[] iv) { if (iv == null) { this.iv = null; @@ -127,9 +121,10 @@ public KeyOperationsParameters setIv(byte[] iv) { /** * Get the aad property: Additional data to authenticate but not encrypt/decrypt when using authenticated crypto * algorithms. - * + * * @return the aad value. */ + @Generated public byte[] getAad() { if (this.aad == null) { return null; @@ -140,10 +135,11 @@ public byte[] getAad() { /** * Set the aad property: Additional data to authenticate but not encrypt/decrypt when using authenticated crypto * algorithms. - * + * * @param aad the aad value to set. * @return the KeyOperationsParameters object itself. */ + @Generated public KeyOperationsParameters setAad(byte[] aad) { if (aad == null) { this.aad = null; @@ -155,9 +151,10 @@ public KeyOperationsParameters setAad(byte[] aad) { /** * Get the tag property: The tag to authenticate when performing decryption with an authenticated algorithm. - * + * * @return the tag value. */ + @Generated public byte[] getTag() { if (this.tag == null) { return null; @@ -167,10 +164,11 @@ public byte[] getTag() { /** * Set the tag property: The tag to authenticate when performing decryption with an authenticated algorithm. - * + * * @param tag the tag value to set. * @return the KeyOperationsParameters object itself. */ + @Generated public KeyOperationsParameters setTag(byte[] tag) { if (tag == null) { this.tag = null; @@ -183,6 +181,7 @@ public KeyOperationsParameters setTag(byte[] tag) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -196,40 +195,46 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KeyOperationsParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KeyOperationsParameters 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 KeyOperationsParameters. */ + @Generated public static KeyOperationsParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - KeyOperationsParameters deserializedKeyOperationsParameters = new KeyOperationsParameters(); + JsonWebKeyEncryptionAlgorithm algorithm = null; + byte[] value = null; + Base64Url iv = null; + Base64Url aad = null; + Base64Url tag = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("alg".equals(fieldName)) { - deserializedKeyOperationsParameters.algorithm - = JsonWebKeyEncryptionAlgorithm.fromString(reader.getString()); + algorithm = JsonWebKeyEncryptionAlgorithm.fromString(reader.getString()); } else if ("value".equals(fieldName)) { - deserializedKeyOperationsParameters.value + Base64Url valueHolder = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); + if (valueHolder != null) { + value = valueHolder.decodedBytes(); + } } else if ("iv".equals(fieldName)) { - deserializedKeyOperationsParameters.iv - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); + iv = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); } else if ("aad".equals(fieldName)) { - deserializedKeyOperationsParameters.aad - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); + aad = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); } else if ("tag".equals(fieldName)) { - deserializedKeyOperationsParameters.tag - = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); + tag = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); } else { reader.skipChildren(); } } - + KeyOperationsParameters deserializedKeyOperationsParameters = new KeyOperationsParameters(algorithm, value); + deserializedKeyOperationsParameters.iv = iv; + deserializedKeyOperationsParameters.aad = aad; + deserializedKeyOperationsParameters.tag = tag; return deserializedKeyOperationsParameters; }); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyProperties.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyProperties.java deleted file mode 100644 index dba8bf629372..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyProperties.java +++ /dev/null @@ -1,204 +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.security.keyvault.keys.implementation.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.security.keyvault.keys.models.KeyCurveName; -import com.azure.security.keyvault.keys.models.KeyType; -import java.io.IOException; - -/** - * Properties of the key pair backing a certificate. - */ -@Fluent -public final class KeyProperties implements JsonSerializable { - /* - * Indicates if the private key can be exported. Release policy must be provided when creating the first version of - * an exportable key. - */ - private Boolean exportable; - - /* - * JsonWebKey Key Type (kty), as defined in https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - */ - private KeyType kty; - - /* - * The key size in bits. For example: 2048, 3072, or 4096 for RSA. - */ - private Integer keySize; - - /* - * Indicates if the same key pair will be used on certificate renewal. - */ - private Boolean reuseKey; - - /* - * Elliptic curve name. - */ - private KeyCurveName crv; - - /** - * Creates an instance of KeyProperties class. - */ - public KeyProperties() { - } - - /** - * Get the exportable property: Indicates if the private key can be exported. Release policy must be provided when - * creating the first version of an exportable key. - * - * @return the exportable value. - */ - public Boolean isExportable() { - return this.exportable; - } - - /** - * Set the exportable property: Indicates if the private key can be exported. Release policy must be provided when - * creating the first version of an exportable key. - * - * @param exportable the exportable value to set. - * @return the KeyProperties object itself. - */ - public KeyProperties setExportable(Boolean exportable) { - this.exportable = exportable; - return this; - } - - /** - * Get the kty property: JsonWebKey Key Type (kty), as defined in - * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - * - * @return the kty value. - */ - public KeyType getKty() { - return this.kty; - } - - /** - * Set the kty property: JsonWebKey Key Type (kty), as defined in - * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. - * - * @param kty the kty value to set. - * @return the KeyProperties object itself. - */ - public KeyProperties setKty(KeyType kty) { - this.kty = kty; - return this; - } - - /** - * Get the keySize property: The key size in bits. For example: 2048, 3072, or 4096 for RSA. - * - * @return the keySize value. - */ - public Integer getKeySize() { - return this.keySize; - } - - /** - * Set the keySize property: The key size in bits. For example: 2048, 3072, or 4096 for RSA. - * - * @param keySize the keySize value to set. - * @return the KeyProperties object itself. - */ - public KeyProperties setKeySize(Integer keySize) { - this.keySize = keySize; - return this; - } - - /** - * Get the reuseKey property: Indicates if the same key pair will be used on certificate renewal. - * - * @return the reuseKey value. - */ - public Boolean isReuseKey() { - return this.reuseKey; - } - - /** - * Set the reuseKey property: Indicates if the same key pair will be used on certificate renewal. - * - * @param reuseKey the reuseKey value to set. - * @return the KeyProperties object itself. - */ - public KeyProperties setReuseKey(Boolean reuseKey) { - this.reuseKey = reuseKey; - return this; - } - - /** - * Get the crv property: Elliptic curve name. - * - * @return the crv value. - */ - public KeyCurveName getCrv() { - return this.crv; - } - - /** - * Set the crv property: Elliptic curve name. - * - * @param crv the crv value to set. - * @return the KeyProperties object itself. - */ - public KeyProperties setCrv(KeyCurveName crv) { - this.crv = crv; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeBooleanField("exportable", this.exportable); - jsonWriter.writeStringField("kty", this.kty == null ? null : this.kty.toString()); - jsonWriter.writeNumberField("key_size", this.keySize); - jsonWriter.writeBooleanField("reuse_key", this.reuseKey); - jsonWriter.writeStringField("crv", this.crv == null ? null : this.crv.toString()); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KeyProperties from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KeyProperties 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 KeyProperties. - */ - public static KeyProperties fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeyProperties deserializedKeyProperties = new KeyProperties(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("exportable".equals(fieldName)) { - deserializedKeyProperties.exportable = reader.getNullable(JsonReader::getBoolean); - } else if ("kty".equals(fieldName)) { - deserializedKeyProperties.kty = KeyType.fromString(reader.getString()); - } else if ("key_size".equals(fieldName)) { - deserializedKeyProperties.keySize = reader.getNullable(JsonReader::getInt); - } else if ("reuse_key".equals(fieldName)) { - deserializedKeyProperties.reuseKey = reader.getNullable(JsonReader::getBoolean); - } else if ("crv".equals(fieldName)) { - deserializedKeyProperties.crv = KeyCurveName.fromString(reader.getString()); - } else { - reader.skipChildren(); - } - } - - return deserializedKeyProperties; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyReleaseParameters.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyReleaseParameters.java index c11dd6fecbb4..c21e0baa2ccf 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyReleaseParameters.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyReleaseParameters.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -17,62 +17,62 @@ */ @Fluent public final class KeyReleaseParameters implements JsonSerializable { + /* * The attestation assertion for the target of the key release. */ - private String targetAttestationToken; + @Generated + private final String targetAttestationToken; /* * A client provided nonce for freshness. */ + @Generated private String nonce; /* * The encryption algorithm to use to protected the exported key material */ + @Generated private KeyExportEncryptionAlgorithm enc; /** * Creates an instance of KeyReleaseParameters class. + * + * @param targetAttestationToken the targetAttestationToken value to set. */ - public KeyReleaseParameters() { + @Generated + public KeyReleaseParameters(String targetAttestationToken) { + this.targetAttestationToken = targetAttestationToken; } /** * Get the targetAttestationToken property: The attestation assertion for the target of the key release. - * + * * @return the targetAttestationToken value. */ + @Generated public String getTargetAttestationToken() { return this.targetAttestationToken; } - /** - * Set the targetAttestationToken property: The attestation assertion for the target of the key release. - * - * @param targetAttestationToken the targetAttestationToken value to set. - * @return the KeyReleaseParameters object itself. - */ - public KeyReleaseParameters setTargetAttestationToken(String targetAttestationToken) { - this.targetAttestationToken = targetAttestationToken; - return this; - } - /** * Get the nonce property: A client provided nonce for freshness. - * + * * @return the nonce value. */ + @Generated public String getNonce() { return this.nonce; } /** * Set the nonce property: A client provided nonce for freshness. - * + * * @param nonce the nonce value to set. * @return the KeyReleaseParameters object itself. */ + @Generated public KeyReleaseParameters setNonce(String nonce) { this.nonce = nonce; return this; @@ -80,19 +80,21 @@ public KeyReleaseParameters setNonce(String nonce) { /** * Get the enc property: The encryption algorithm to use to protected the exported key material. - * + * * @return the enc value. */ + @Generated public KeyExportEncryptionAlgorithm getEnc() { return this.enc; } /** * Set the enc property: The encryption algorithm to use to protected the exported key material. - * + * * @param enc the enc value to set. * @return the KeyReleaseParameters object itself. */ + @Generated public KeyReleaseParameters setEnc(KeyExportEncryptionAlgorithm enc) { this.enc = enc; return this; @@ -101,6 +103,7 @@ public KeyReleaseParameters setEnc(KeyExportEncryptionAlgorithm enc) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -112,31 +115,35 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KeyReleaseParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KeyReleaseParameters 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 KeyReleaseParameters. */ + @Generated public static KeyReleaseParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - KeyReleaseParameters deserializedKeyReleaseParameters = new KeyReleaseParameters(); + String targetAttestationToken = null; + String nonce = null; + KeyExportEncryptionAlgorithm enc = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("target".equals(fieldName)) { - deserializedKeyReleaseParameters.targetAttestationToken = reader.getString(); + targetAttestationToken = reader.getString(); } else if ("nonce".equals(fieldName)) { - deserializedKeyReleaseParameters.nonce = reader.getString(); + nonce = reader.getString(); } else if ("enc".equals(fieldName)) { - deserializedKeyReleaseParameters.enc = KeyExportEncryptionAlgorithm.fromString(reader.getString()); + enc = KeyExportEncryptionAlgorithm.fromString(reader.getString()); } else { reader.skipChildren(); } } - + KeyReleaseParameters deserializedKeyReleaseParameters = new KeyReleaseParameters(targetAttestationToken); + deserializedKeyReleaseParameters.nonce = nonce; + deserializedKeyReleaseParameters.enc = enc; return deserializedKeyReleaseParameters; }); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyReleasePolicy.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyReleasePolicy.java index c5de807bce69..25fab3960f20 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyReleasePolicy.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyReleasePolicy.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.core.util.Base64Url; import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; @@ -19,43 +19,50 @@ */ @Fluent public final class KeyReleasePolicy implements JsonSerializable { + /* * Content type and version of key release policy */ + @Generated private String contentType; /* * Defines the mutability state of the policy. Once marked immutable, this flag cannot be reset and the policy * cannot be changed under any circumstances. */ + @Generated private Boolean immutable; /* * Blob encoding the policy rules under which the key can be released. Blob must be base64 URL encoded. */ + @Generated private Base64Url encodedPolicy; /** * Creates an instance of KeyReleasePolicy class. */ + @Generated public KeyReleasePolicy() { } /** * Get the contentType property: Content type and version of key release policy. - * + * * @return the contentType value. */ + @Generated public String getContentType() { return this.contentType; } /** * Set the contentType property: Content type and version of key release policy. - * + * * @param contentType the contentType value to set. * @return the KeyReleasePolicy object itself. */ + @Generated public KeyReleasePolicy setContentType(String contentType) { this.contentType = contentType; return this; @@ -64,9 +71,10 @@ public KeyReleasePolicy setContentType(String contentType) { /** * Get the immutable property: Defines the mutability state of the policy. Once marked immutable, this flag cannot * be reset and the policy cannot be changed under any circumstances. - * + * * @return the immutable value. */ + @Generated public Boolean isImmutable() { return this.immutable; } @@ -74,10 +82,11 @@ public Boolean isImmutable() { /** * Set the immutable property: Defines the mutability state of the policy. Once marked immutable, this flag cannot * be reset and the policy cannot be changed under any circumstances. - * + * * @param immutable the immutable value to set. * @return the KeyReleasePolicy object itself. */ + @Generated public KeyReleasePolicy setImmutable(Boolean immutable) { this.immutable = immutable; return this; @@ -86,9 +95,10 @@ public KeyReleasePolicy setImmutable(Boolean immutable) { /** * Get the encodedPolicy property: Blob encoding the policy rules under which the key can be released. Blob must be * base64 URL encoded. - * + * * @return the encodedPolicy value. */ + @Generated public byte[] getEncodedPolicy() { if (this.encodedPolicy == null) { return null; @@ -99,10 +109,11 @@ public byte[] getEncodedPolicy() { /** * Set the encodedPolicy property: Blob encoding the policy rules under which the key can be released. Blob must be * base64 URL encoded. - * + * * @param encodedPolicy the encodedPolicy value to set. * @return the KeyReleasePolicy object itself. */ + @Generated public KeyReleasePolicy setEncodedPolicy(byte[] encodedPolicy) { if (encodedPolicy == null) { this.encodedPolicy = null; @@ -115,6 +126,7 @@ public KeyReleasePolicy setEncodedPolicy(byte[] encodedPolicy) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -126,19 +138,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KeyReleasePolicy from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KeyReleasePolicy 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 KeyReleasePolicy. */ + @Generated public static KeyReleasePolicy fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { KeyReleasePolicy deserializedKeyReleasePolicy = new KeyReleasePolicy(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("contentType".equals(fieldName)) { deserializedKeyReleasePolicy.contentType = reader.getString(); } else if ("immutable".equals(fieldName)) { @@ -150,7 +162,6 @@ public static KeyReleasePolicy fromJson(JsonReader jsonReader) throws IOExceptio reader.skipChildren(); } } - return deserializedKeyReleasePolicy; }); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyRestoreParameters.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyRestoreParameters.java index 720b708c6769..ba6bc180c6b2 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyRestoreParameters.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyRestoreParameters.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; import com.azure.core.util.Base64Url; -import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -17,24 +16,35 @@ /** * The key restore parameters. */ -@Fluent +@Immutable public final class KeyRestoreParameters implements JsonSerializable { + /* * The backup blob associated with a key bundle. */ - private Base64Url keyBundleBackup; + @Generated + private final Base64Url keyBundleBackup; /** * Creates an instance of KeyRestoreParameters class. + * + * @param keyBundleBackup the keyBundleBackup value to set. */ - public KeyRestoreParameters() { + @Generated + public KeyRestoreParameters(byte[] keyBundleBackup) { + if (keyBundleBackup == null) { + this.keyBundleBackup = null; + } else { + this.keyBundleBackup = Base64Url.encode(keyBundleBackup); + } } /** * Get the keyBundleBackup property: The backup blob associated with a key bundle. - * + * * @return the keyBundleBackup value. */ + @Generated public byte[] getKeyBundleBackup() { if (this.keyBundleBackup == null) { return null; @@ -42,24 +52,10 @@ public byte[] getKeyBundleBackup() { return this.keyBundleBackup.decodedBytes(); } - /** - * Set the keyBundleBackup property: The backup blob associated with a key bundle. - * - * @param keyBundleBackup the keyBundleBackup value to set. - * @return the KeyRestoreParameters object itself. - */ - public KeyRestoreParameters setKeyBundleBackup(byte[] keyBundleBackup) { - if (keyBundleBackup == null) { - this.keyBundleBackup = null; - } else { - this.keyBundleBackup = Base64Url.encode(CoreUtils.clone(keyBundleBackup)); - } - return this; - } - /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -69,29 +65,31 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KeyRestoreParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KeyRestoreParameters 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 KeyRestoreParameters. */ + @Generated public static KeyRestoreParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - KeyRestoreParameters deserializedKeyRestoreParameters = new KeyRestoreParameters(); + byte[] keyBundleBackup = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("value".equals(fieldName)) { - deserializedKeyRestoreParameters.keyBundleBackup + Base64Url keyBundleBackupHolder = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); + if (keyBundleBackupHolder != null) { + keyBundleBackup = keyBundleBackupHolder.decodedBytes(); + } } else { reader.skipChildren(); } } - - return deserializedKeyRestoreParameters; + return new KeyRestoreParameters(keyBundleBackup); }); } } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyRotationPolicy.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyRotationPolicy.java index d6e6b7517cc2..11044701cbd0 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyRotationPolicy.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyRotationPolicy.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -17,9 +17,11 @@ */ @Fluent public final class KeyRotationPolicy implements JsonSerializable { + /* * The key policy id. */ + @Generated private String id; /* @@ -27,24 +29,28 @@ public final class KeyRotationPolicy implements JsonSerializable lifetimeActions; /* * The key rotation policy attributes. */ + @Generated private KeyRotationPolicyAttributes attributes; /** * Creates an instance of KeyRotationPolicy class. */ + @Generated public KeyRotationPolicy() { } /** * Get the id property: The key policy id. - * + * * @return the id value. */ + @Generated public String getId() { return this.id; } @@ -53,9 +59,10 @@ public String getId() { * Get the lifetimeActions property: Actions that will be performed by Key Vault over the lifetime of a key. For * preview, lifetimeActions can only have two items at maximum: one for rotate, one for notify. Notification time * would be default to 30 days before expiry and it is not configurable. - * + * * @return the lifetimeActions value. */ + @Generated public List getLifetimeActions() { return this.lifetimeActions; } @@ -64,10 +71,11 @@ public List getLifetimeActions() { * Set the lifetimeActions property: Actions that will be performed by Key Vault over the lifetime of a key. For * preview, lifetimeActions can only have two items at maximum: one for rotate, one for notify. Notification time * would be default to 30 days before expiry and it is not configurable. - * + * * @param lifetimeActions the lifetimeActions value to set. * @return the KeyRotationPolicy object itself. */ + @Generated public KeyRotationPolicy setLifetimeActions(List lifetimeActions) { this.lifetimeActions = lifetimeActions; return this; @@ -75,19 +83,21 @@ public KeyRotationPolicy setLifetimeActions(List lifetimeAction /** * Get the attributes property: The key rotation policy attributes. - * + * * @return the attributes value. */ + @Generated public KeyRotationPolicyAttributes getAttributes() { return this.attributes; } /** * Set the attributes property: The key rotation policy attributes. - * + * * @param attributes the attributes value to set. * @return the KeyRotationPolicy object itself. */ + @Generated public KeyRotationPolicy setAttributes(KeyRotationPolicyAttributes attributes) { this.attributes = attributes; return this; @@ -96,6 +106,7 @@ public KeyRotationPolicy setAttributes(KeyRotationPolicyAttributes attributes) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -107,19 +118,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KeyRotationPolicy from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KeyRotationPolicy 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 KeyRotationPolicy. */ + @Generated public static KeyRotationPolicy fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { KeyRotationPolicy deserializedKeyRotationPolicy = new KeyRotationPolicy(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("id".equals(fieldName)) { deserializedKeyRotationPolicy.id = reader.getString(); } else if ("lifetimeActions".equals(fieldName)) { @@ -132,7 +143,6 @@ public static KeyRotationPolicy fromJson(JsonReader jsonReader) throws IOExcepti reader.skipChildren(); } } - return deserializedKeyRotationPolicy; }); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyRotationPolicyAttributes.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyRotationPolicyAttributes.java index b9cfc05d6253..d598c0cbad3a 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyRotationPolicyAttributes.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyRotationPolicyAttributes.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -19,25 +19,30 @@ */ @Fluent public final class KeyRotationPolicyAttributes implements JsonSerializable { + /* * The expiryTime will be applied on the new key version. It should be at least 28 days. It will be in ISO 8601 * Format. Examples: 90 days: P90D, 3 months: P3M, 48 hours: PT48H, 1 year and 10 days: P1Y10D */ + @Generated private String expiryTime; /* * The key rotation policy created time in UTC. */ + @Generated private Long created; /* * The key rotation policy's last updated time in UTC. */ + @Generated private Long updated; /** * Creates an instance of KeyRotationPolicyAttributes class. */ + @Generated public KeyRotationPolicyAttributes() { } @@ -45,9 +50,10 @@ public KeyRotationPolicyAttributes() { * Get the expiryTime property: The expiryTime will be applied on the new key version. It should be at least 28 * days. It will be in ISO 8601 Format. Examples: 90 days: P90D, 3 months: P3M, 48 hours: PT48H, 1 year and 10 days: * P1Y10D. - * + * * @return the expiryTime value. */ + @Generated public String getExpiryTime() { return this.expiryTime; } @@ -56,10 +62,11 @@ public String getExpiryTime() { * Set the expiryTime property: The expiryTime will be applied on the new key version. It should be at least 28 * days. It will be in ISO 8601 Format. Examples: 90 days: P90D, 3 months: P3M, 48 hours: PT48H, 1 year and 10 days: * P1Y10D. - * + * * @param expiryTime the expiryTime value to set. * @return the KeyRotationPolicyAttributes object itself. */ + @Generated public KeyRotationPolicyAttributes setExpiryTime(String expiryTime) { this.expiryTime = expiryTime; return this; @@ -67,9 +74,10 @@ public KeyRotationPolicyAttributes setExpiryTime(String expiryTime) { /** * Get the created property: The key rotation policy created time in UTC. - * + * * @return the created value. */ + @Generated public OffsetDateTime getCreated() { if (this.created == null) { return null; @@ -79,9 +87,10 @@ public OffsetDateTime getCreated() { /** * Get the updated property: The key rotation policy's last updated time in UTC. - * + * * @return the updated value. */ + @Generated public OffsetDateTime getUpdated() { if (this.updated == null) { return null; @@ -92,6 +101,7 @@ public OffsetDateTime getUpdated() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -101,19 +111,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KeyRotationPolicyAttributes from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KeyRotationPolicyAttributes 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 KeyRotationPolicyAttributes. */ + @Generated public static KeyRotationPolicyAttributes fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { KeyRotationPolicyAttributes deserializedKeyRotationPolicyAttributes = new KeyRotationPolicyAttributes(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("expiryTime".equals(fieldName)) { deserializedKeyRotationPolicyAttributes.expiryTime = reader.getString(); } else if ("created".equals(fieldName)) { @@ -124,7 +134,6 @@ public static KeyRotationPolicyAttributes fromJson(JsonReader jsonReader) throws reader.skipChildren(); } } - return deserializedKeyRotationPolicyAttributes; }); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeySignParameters.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeySignParameters.java index fb149d41690a..fa2df11a07fb 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeySignParameters.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeySignParameters.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; import com.azure.core.util.Base64Url; -import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -17,52 +16,55 @@ /** * The key operations parameters. */ -@Fluent +@Immutable public final class KeySignParameters implements JsonSerializable { + /* * The signing/verification algorithm identifier. For more information on possible algorithm types, see * JsonWebKeySignatureAlgorithm. */ - private JsonWebKeySignatureAlgorithm algorithm; + @Generated + private final JsonWebKeySignatureAlgorithm algorithm; /* - * The value property. + * The value to operate on. */ - private Base64Url value; + @Generated + private final Base64Url value; /** * Creates an instance of KeySignParameters class. + * + * @param algorithm the algorithm value to set. + * @param value the value value to set. */ - public KeySignParameters() { + @Generated + public KeySignParameters(JsonWebKeySignatureAlgorithm algorithm, byte[] value) { + this.algorithm = algorithm; + if (value == null) { + this.value = null; + } else { + this.value = Base64Url.encode(value); + } } /** * Get the algorithm property: The signing/verification algorithm identifier. For more information on possible * algorithm types, see JsonWebKeySignatureAlgorithm. - * + * * @return the algorithm value. */ + @Generated public JsonWebKeySignatureAlgorithm getAlgorithm() { return this.algorithm; } /** - * Set the algorithm property: The signing/verification algorithm identifier. For more information on possible - * algorithm types, see JsonWebKeySignatureAlgorithm. - * - * @param algorithm the algorithm value to set. - * @return the KeySignParameters object itself. - */ - public KeySignParameters setAlgorithm(JsonWebKeySignatureAlgorithm algorithm) { - this.algorithm = algorithm; - return this; - } - - /** - * Get the value property: The value property. - * + * Get the value property: The value to operate on. + * * @return the value value. */ + @Generated public byte[] getValue() { if (this.value == null) { return null; @@ -70,24 +72,10 @@ public byte[] getValue() { return this.value.decodedBytes(); } - /** - * Set the value property: The value property. - * - * @param value the value value to set. - * @return the KeySignParameters object itself. - */ - public KeySignParameters setValue(byte[] value) { - if (value == null) { - this.value = null; - } else { - this.value = Base64Url.encode(CoreUtils.clone(value)); - } - return this; - } - /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -98,32 +86,34 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KeySignParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KeySignParameters 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 KeySignParameters. */ + @Generated public static KeySignParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - KeySignParameters deserializedKeySignParameters = new KeySignParameters(); + JsonWebKeySignatureAlgorithm algorithm = null; + byte[] value = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("alg".equals(fieldName)) { - deserializedKeySignParameters.algorithm - = JsonWebKeySignatureAlgorithm.fromString(reader.getString()); + algorithm = JsonWebKeySignatureAlgorithm.fromString(reader.getString()); } else if ("value".equals(fieldName)) { - deserializedKeySignParameters.value + Base64Url valueHolder = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); + if (valueHolder != null) { + value = valueHolder.decodedBytes(); + } } else { reader.skipChildren(); } } - - return deserializedKeySignParameters; + return new KeySignParameters(algorithm, value); }); } } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyUpdateParameters.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyUpdateParameters.java index 16aa11c86eaf..ce09fb3bfc56 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyUpdateParameters.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyUpdateParameters.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -19,38 +19,45 @@ */ @Fluent public final class KeyUpdateParameters implements JsonSerializable { + /* * Json web key operations. For more information on possible key operations, see JsonWebKeyOperation. */ + @Generated private List keyOps; /* * The attributes of a key managed by the key vault service. */ + @Generated private KeyAttributes keyAttributes; /* * Application specific metadata in the form of key-value pairs. */ + @Generated private Map tags; /* * The policy rules under which the key can be exported. */ + @Generated private KeyReleasePolicy releasePolicy; /** * Creates an instance of KeyUpdateParameters class. */ + @Generated public KeyUpdateParameters() { } /** * Get the keyOps property: Json web key operations. For more information on possible key operations, see * JsonWebKeyOperation. - * + * * @return the keyOps value. */ + @Generated public List getKeyOps() { return this.keyOps; } @@ -58,10 +65,11 @@ public List getKeyOps() { /** * Set the keyOps property: Json web key operations. For more information on possible key operations, see * JsonWebKeyOperation. - * + * * @param keyOps the keyOps value to set. * @return the KeyUpdateParameters object itself. */ + @Generated public KeyUpdateParameters setKeyOps(List keyOps) { this.keyOps = keyOps; return this; @@ -69,19 +77,21 @@ public KeyUpdateParameters setKeyOps(List keyOps) { /** * Get the keyAttributes property: The attributes of a key managed by the key vault service. - * + * * @return the keyAttributes value. */ + @Generated public KeyAttributes getKeyAttributes() { return this.keyAttributes; } /** * Set the keyAttributes property: The attributes of a key managed by the key vault service. - * + * * @param keyAttributes the keyAttributes value to set. * @return the KeyUpdateParameters object itself. */ + @Generated public KeyUpdateParameters setKeyAttributes(KeyAttributes keyAttributes) { this.keyAttributes = keyAttributes; return this; @@ -89,19 +99,21 @@ public KeyUpdateParameters setKeyAttributes(KeyAttributes keyAttributes) { /** * Get the tags property: Application specific metadata in the form of key-value pairs. - * + * * @return the tags value. */ + @Generated public Map getTags() { return this.tags; } /** * Set the tags property: Application specific metadata in the form of key-value pairs. - * + * * @param tags the tags value to set. * @return the KeyUpdateParameters object itself. */ + @Generated public KeyUpdateParameters setTags(Map tags) { this.tags = tags; return this; @@ -109,19 +121,21 @@ public KeyUpdateParameters setTags(Map tags) { /** * Get the releasePolicy property: The policy rules under which the key can be exported. - * + * * @return the releasePolicy value. */ + @Generated public KeyReleasePolicy getReleasePolicy() { return this.releasePolicy; } /** * Set the releasePolicy property: The policy rules under which the key can be exported. - * + * * @param releasePolicy the releasePolicy value to set. * @return the KeyUpdateParameters object itself. */ + @Generated public KeyUpdateParameters setReleasePolicy(KeyReleasePolicy releasePolicy) { this.releasePolicy = releasePolicy; return this; @@ -130,6 +144,7 @@ public KeyUpdateParameters setReleasePolicy(KeyReleasePolicy releasePolicy) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -143,19 +158,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KeyUpdateParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KeyUpdateParameters 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 KeyUpdateParameters. */ + @Generated public static KeyUpdateParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { KeyUpdateParameters deserializedKeyUpdateParameters = new KeyUpdateParameters(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("key_ops".equals(fieldName)) { List keyOps = reader.readArray(reader1 -> KeyOperation.fromString(reader1.getString())); @@ -171,7 +186,6 @@ public static KeyUpdateParameters fromJson(JsonReader jsonReader) throws IOExcep reader.skipChildren(); } } - return deserializedKeyUpdateParameters; }); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVaultError.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVaultError.java deleted file mode 100644 index 878f44cec3d8..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVaultError.java +++ /dev/null @@ -1,73 +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.security.keyvault.keys.implementation.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 key vault error exception. - */ -@Immutable -public final class KeyVaultError implements JsonSerializable { - /* - * The key vault server error. - */ - private Error error; - - /** - * Creates an instance of KeyVaultError class. - */ - public KeyVaultError() { - } - - /** - * Get the error property: The key vault server error. - * - * @return the error value. - */ - public Error getError() { - return this.error; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KeyVaultError from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KeyVaultError 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 KeyVaultError. - */ - public static KeyVaultError fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeyVaultError deserializedKeyVaultError = new KeyVaultError(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("error".equals(fieldName)) { - deserializedKeyVaultError.error = Error.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedKeyVaultError; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVaultErrorException.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVaultErrorException.java deleted file mode 100644 index 43c502fea680..000000000000 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVaultErrorException.java +++ /dev/null @@ -1,42 +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.security.keyvault.keys.implementation.models; - -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpResponse; - -/** - * Exception thrown for an invalid response with KeyVaultError information. - */ -public final class KeyVaultErrorException extends HttpResponseException { - /** - * Initializes a new instance of the KeyVaultErrorException class. - * - * @param message the exception message or the response content if a message is not available. - * @param response the HTTP response. - */ - public KeyVaultErrorException(String message, HttpResponse response) { - super(message, response); - } - - /** - * Initializes a new instance of the KeyVaultErrorException 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 KeyVaultErrorException(String message, HttpResponse response, KeyVaultError value) { - super(message, response, value); - } - - /** - * {@inheritDoc} - */ - @Override - public KeyVaultError getValue() { - return (KeyVaultError) super.getValue(); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVaultKeysModelsUtils.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVaultKeysModelsUtils.java index 032031292487..b7e0d43a434d 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVaultKeysModelsUtils.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVaultKeysModelsUtils.java @@ -11,6 +11,7 @@ import com.azure.security.keyvault.keys.models.CreateKeyOptions; import com.azure.security.keyvault.keys.models.DeletedKey; import com.azure.security.keyvault.keys.models.JsonWebKey; +import com.azure.security.keyvault.keys.models.KeyOperation; import com.azure.security.keyvault.keys.models.KeyProperties; import com.azure.security.keyvault.keys.models.KeyReleasePolicy; import com.azure.security.keyvault.keys.models.KeyRotationPolicy; @@ -18,8 +19,10 @@ import java.net.MalformedURLException; import java.net.URL; +import java.util.Map; import java.util.Objects; import java.util.function.Consumer; +import java.util.stream.Collectors; /** * Utility class for KeyVault Keys models. @@ -48,29 +51,16 @@ public static KeyProperties createKeyProperties(KeyItem keyItem) { } private static void populateKeyProperties(KeyItem keyItem, KeyProperties properties) { - if (keyItem == null) { - return; + if (keyItem != null) { + populateKeyProperties(null, keyItem.getTags(), keyItem.isManaged(), keyItem.getKid(), properties, + keyItem.getAttributes()); } + } - properties.setTags(keyItem.getTags()); - KeyPropertiesHelper.setManaged(properties, keyItem.isManaged()); - KeyPropertiesHelper.setId(properties, keyItem.getKid()); - - unpackId(keyItem.getKid(), name -> KeyPropertiesHelper.setName(properties, name), - version -> KeyPropertiesHelper.setVersion(properties, version)); - - KeyAttributes attributes = keyItem.getAttributes(); - if (attributes != null) { - properties.setEnabled(attributes.isEnabled()) - .setExpiresOn(attributes.getExpires()) - .setExportable(attributes.isExportable()) - .setNotBefore(attributes.getNotBefore()); - - KeyPropertiesHelper.setCreatedOn(properties, attributes.getCreated()); - KeyPropertiesHelper.setUpdatedOn(properties, attributes.getUpdated()); - KeyPropertiesHelper.setRecoveryLevel(properties, Objects.toString(attributes.getRecoveryLevel(), null)); - KeyPropertiesHelper.setRecoverableDays(properties, attributes.getRecoverableDays()); - KeyPropertiesHelper.setHsmPlatform(properties, attributes.getHsmPlatform()); + private static void populateKeyProperties(DeletedKeyItem item, KeyProperties properties) { + if (item != null) { + populateKeyProperties(null, item.getTags(), item.isManaged(), item.getKid(), properties, + item.getAttributes()); } } @@ -112,7 +102,7 @@ public static DeletedKey createDeletedKey(DeletedKeyItem item) { return new JsonWebKey().setId(impl.getKid()) .setKeyType(impl.getKty()) - .setKeyOps(impl.getKeyOps()) + .setKeyOps(impl.getKeyOps().stream().map(KeyOperation::fromString).collect(Collectors.toList())) .setN(impl.getN()) .setE(impl.getE()) .setD(impl.getD()) @@ -135,7 +125,7 @@ public static com.azure.security.keyvault.keys.implementation.models.JsonWebKey return new com.azure.security.keyvault.keys.implementation.models.JsonWebKey().setKid(key.getId()) .setKty(key.getKeyType()) - .setKeyOps(key.getKeyOps()) + .setKeyOps(key.getKeyOps().stream().map(KeyOperation::toString).collect(Collectors.toList())) .setN(key.getN()) .setE(key.getE()) .setD(key.getD()) @@ -174,21 +164,32 @@ public static KeyAttributes createKeyAttributes(KeyProperties properties) { } private static void populateKeyProperties(KeyBundle bundle, KeyProperties properties) { - if (bundle == null) { - return; + if (bundle != null) { + populateKeyProperties(mapKeyReleasePolicyImpl(bundle.getReleasePolicy()), bundle.getTags(), + bundle.isManaged(), bundle.getKey().getKid(), properties, bundle.getAttributes()); } + } + + private static void populateKeyProperties(DeletedKeyBundle bundle, KeyProperties properties) { + if (bundle != null) { + populateKeyProperties(mapKeyReleasePolicyImpl(bundle.getReleasePolicy()), bundle.getTags(), + bundle.isManaged(), bundle.getKey().getKid(), properties, bundle.getAttributes()); + } + } + + private static void populateKeyProperties(KeyReleasePolicy keyReleasePolicy, Map tags, + Boolean isManaged, String kid, KeyProperties properties, KeyAttributes attributes) { + + properties.setReleasePolicy(keyReleasePolicy).setTags(tags); - properties.setReleasePolicy(mapKeyReleasePolicyImpl(bundle.getReleasePolicy())).setTags(bundle.getTags()); + KeyPropertiesHelper.setManaged(properties, isManaged); + KeyPropertiesHelper.setId(properties, kid); - KeyPropertiesHelper.setManaged(properties, bundle.isManaged()); - KeyPropertiesHelper.setId(properties, bundle.getKey().getKid()); - unpackId(bundle.getKey().getKid(), name -> KeyPropertiesHelper.setName(properties, name), + unpackId(kid, name -> KeyPropertiesHelper.setName(properties, name), version -> KeyPropertiesHelper.setVersion(properties, version)); - KeyAttributes attributes = bundle.getAttributes(); if (attributes != null) { properties.setEnabled(attributes.isEnabled()) - .setEnabled(attributes.isEnabled()) .setExportable(attributes.isExportable()) .setNotBefore(attributes.getNotBefore()) .setExpiresOn(attributes.getExpires()); diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVerifyParameters.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVerifyParameters.java index 6edf08bbffa4..2c4ca2fbf595 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVerifyParameters.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVerifyParameters.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; import com.azure.core.util.Base64Url; -import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -17,57 +16,67 @@ /** * The key verify parameters. */ -@Fluent +@Immutable public final class KeyVerifyParameters implements JsonSerializable { + /* * The signing/verification algorithm. For more information on possible algorithm types, see * JsonWebKeySignatureAlgorithm. */ - private JsonWebKeySignatureAlgorithm algorithm; + @Generated + private final JsonWebKeySignatureAlgorithm algorithm; /* * The digest used for signing. */ - private Base64Url digest; + @Generated + private final Base64Url digest; /* * The signature to be verified. */ - private Base64Url signature; + @Generated + private final Base64Url signature; /** * Creates an instance of KeyVerifyParameters class. + * + * @param algorithm the algorithm value to set. + * @param digest the digest value to set. + * @param signature the signature value to set. */ - public KeyVerifyParameters() { + @Generated + public KeyVerifyParameters(JsonWebKeySignatureAlgorithm algorithm, byte[] digest, byte[] signature) { + this.algorithm = algorithm; + if (digest == null) { + this.digest = null; + } else { + this.digest = Base64Url.encode(digest); + } + if (signature == null) { + this.signature = null; + } else { + this.signature = Base64Url.encode(signature); + } } /** * Get the algorithm property: The signing/verification algorithm. For more information on possible algorithm types, * see JsonWebKeySignatureAlgorithm. - * + * * @return the algorithm value. */ + @Generated public JsonWebKeySignatureAlgorithm getAlgorithm() { return this.algorithm; } - /** - * Set the algorithm property: The signing/verification algorithm. For more information on possible algorithm types, - * see JsonWebKeySignatureAlgorithm. - * - * @param algorithm the algorithm value to set. - * @return the KeyVerifyParameters object itself. - */ - public KeyVerifyParameters setAlgorithm(JsonWebKeySignatureAlgorithm algorithm) { - this.algorithm = algorithm; - return this; - } - /** * Get the digest property: The digest used for signing. - * + * * @return the digest value. */ + @Generated public byte[] getDigest() { if (this.digest == null) { return null; @@ -75,26 +84,12 @@ public byte[] getDigest() { return this.digest.decodedBytes(); } - /** - * Set the digest property: The digest used for signing. - * - * @param digest the digest value to set. - * @return the KeyVerifyParameters object itself. - */ - public KeyVerifyParameters setDigest(byte[] digest) { - if (digest == null) { - this.digest = null; - } else { - this.digest = Base64Url.encode(CoreUtils.clone(digest)); - } - return this; - } - /** * Get the signature property: The signature to be verified. - * + * * @return the signature value. */ + @Generated public byte[] getSignature() { if (this.signature == null) { return null; @@ -102,24 +97,10 @@ public byte[] getSignature() { return this.signature.decodedBytes(); } - /** - * Set the signature property: The signature to be verified. - * - * @param signature the signature value to set. - * @return the KeyVerifyParameters object itself. - */ - public KeyVerifyParameters setSignature(byte[] signature) { - if (signature == null) { - this.signature = null; - } else { - this.signature = Base64Url.encode(CoreUtils.clone(signature)); - } - return this; - } - /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -131,35 +112,41 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KeyVerifyParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KeyVerifyParameters 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 KeyVerifyParameters. */ + @Generated public static KeyVerifyParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - KeyVerifyParameters deserializedKeyVerifyParameters = new KeyVerifyParameters(); + JsonWebKeySignatureAlgorithm algorithm = null; + byte[] digest = null; + byte[] signature = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("alg".equals(fieldName)) { - deserializedKeyVerifyParameters.algorithm - = JsonWebKeySignatureAlgorithm.fromString(reader.getString()); + algorithm = JsonWebKeySignatureAlgorithm.fromString(reader.getString()); } else if ("digest".equals(fieldName)) { - deserializedKeyVerifyParameters.digest + Base64Url digestHolder = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); + if (digestHolder != null) { + digest = digestHolder.decodedBytes(); + } } else if ("value".equals(fieldName)) { - deserializedKeyVerifyParameters.signature + Base64Url signatureHolder = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); + if (signatureHolder != null) { + signature = signatureHolder.decodedBytes(); + } } else { reader.skipChildren(); } } - - return deserializedKeyVerifyParameters; + return new KeyVerifyParameters(algorithm, digest, signature); }); } } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVerifyResult.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVerifyResult.java index 578a9a1a2509..7435fcf6e4c3 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVerifyResult.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/KeyVerifyResult.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.implementation.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -16,22 +16,26 @@ */ @Immutable public final class KeyVerifyResult implements JsonSerializable { + /* * True if the signature is verified, otherwise false. */ + @Generated private Boolean value; /** * Creates an instance of KeyVerifyResult class. */ - public KeyVerifyResult() { + @Generated + private KeyVerifyResult() { } /** * Get the value property: True if the signature is verified, otherwise false. - * + * * @return the value value. */ + @Generated public Boolean isValue() { return this.value; } @@ -39,6 +43,7 @@ public Boolean isValue() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -47,26 +52,25 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KeyVerifyResult from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KeyVerifyResult 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 KeyVerifyResult. */ + @Generated public static KeyVerifyResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { KeyVerifyResult deserializedKeyVerifyResult = new KeyVerifyResult(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("value".equals(fieldName)) { deserializedKeyVerifyResult.value = reader.getNullable(JsonReader::getBoolean); } else { reader.skipChildren(); } } - return deserializedKeyVerifyResult; }); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/LifetimeActions.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/LifetimeActions.java index 6476fe65a397..a3db179d86ab 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/LifetimeActions.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/LifetimeActions.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -16,37 +16,43 @@ */ @Fluent public final class LifetimeActions implements JsonSerializable { + /* * The condition that will execute the action. */ + @Generated private LifetimeActionsTrigger trigger; /* * The action that will be executed. */ + @Generated private LifetimeActionsType action; /** * Creates an instance of LifetimeActions class. */ + @Generated public LifetimeActions() { } /** * Get the trigger property: The condition that will execute the action. - * + * * @return the trigger value. */ + @Generated public LifetimeActionsTrigger getTrigger() { return this.trigger; } /** * Set the trigger property: The condition that will execute the action. - * + * * @param trigger the trigger value to set. * @return the LifetimeActions object itself. */ + @Generated public LifetimeActions setTrigger(LifetimeActionsTrigger trigger) { this.trigger = trigger; return this; @@ -54,19 +60,21 @@ public LifetimeActions setTrigger(LifetimeActionsTrigger trigger) { /** * Get the action property: The action that will be executed. - * + * * @return the action value. */ + @Generated public LifetimeActionsType getAction() { return this.action; } /** * Set the action property: The action that will be executed. - * + * * @param action the action value to set. * @return the LifetimeActions object itself. */ + @Generated public LifetimeActions setAction(LifetimeActionsType action) { this.action = action; return this; @@ -75,6 +83,7 @@ public LifetimeActions setAction(LifetimeActionsType action) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -85,19 +94,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of LifetimeActions from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of LifetimeActions 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 LifetimeActions. */ + @Generated public static LifetimeActions fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { LifetimeActions deserializedLifetimeActions = new LifetimeActions(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("trigger".equals(fieldName)) { deserializedLifetimeActions.trigger = LifetimeActionsTrigger.fromJson(reader); } else if ("action".equals(fieldName)) { @@ -106,7 +115,6 @@ public static LifetimeActions fromJson(JsonReader jsonReader) throws IOException reader.skipChildren(); } } - return deserializedLifetimeActions; }); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/LifetimeActionsTrigger.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/LifetimeActionsTrigger.java index e5c62cf2053a..1e27af5bf562 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/LifetimeActionsTrigger.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/LifetimeActionsTrigger.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -16,30 +16,35 @@ */ @Fluent public final class LifetimeActionsTrigger implements JsonSerializable { + /* * Time after creation to attempt to rotate. It only applies to rotate. It will be in ISO 8601 duration format. * Example: 90 days : "P90D" */ + @Generated private String timeAfterCreate; /* * Time before expiry to attempt to rotate or notify. It will be in ISO 8601 duration format. Example: 90 days : * "P90D" */ + @Generated private String timeBeforeExpiry; /** * Creates an instance of LifetimeActionsTrigger class. */ + @Generated public LifetimeActionsTrigger() { } /** * Get the timeAfterCreate property: Time after creation to attempt to rotate. It only applies to rotate. It will be * in ISO 8601 duration format. Example: 90 days : "P90D". - * + * * @return the timeAfterCreate value. */ + @Generated public String getTimeAfterCreate() { return this.timeAfterCreate; } @@ -47,10 +52,11 @@ public String getTimeAfterCreate() { /** * Set the timeAfterCreate property: Time after creation to attempt to rotate. It only applies to rotate. It will be * in ISO 8601 duration format. Example: 90 days : "P90D". - * + * * @param timeAfterCreate the timeAfterCreate value to set. * @return the LifetimeActionsTrigger object itself. */ + @Generated public LifetimeActionsTrigger setTimeAfterCreate(String timeAfterCreate) { this.timeAfterCreate = timeAfterCreate; return this; @@ -59,9 +65,10 @@ public LifetimeActionsTrigger setTimeAfterCreate(String timeAfterCreate) { /** * Get the timeBeforeExpiry property: Time before expiry to attempt to rotate or notify. It will be in ISO 8601 * duration format. Example: 90 days : "P90D". - * + * * @return the timeBeforeExpiry value. */ + @Generated public String getTimeBeforeExpiry() { return this.timeBeforeExpiry; } @@ -69,10 +76,11 @@ public String getTimeBeforeExpiry() { /** * Set the timeBeforeExpiry property: Time before expiry to attempt to rotate or notify. It will be in ISO 8601 * duration format. Example: 90 days : "P90D". - * + * * @param timeBeforeExpiry the timeBeforeExpiry value to set. * @return the LifetimeActionsTrigger object itself. */ + @Generated public LifetimeActionsTrigger setTimeBeforeExpiry(String timeBeforeExpiry) { this.timeBeforeExpiry = timeBeforeExpiry; return this; @@ -81,6 +89,7 @@ public LifetimeActionsTrigger setTimeBeforeExpiry(String timeBeforeExpiry) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -91,19 +100,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of LifetimeActionsTrigger from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of LifetimeActionsTrigger 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 LifetimeActionsTrigger. */ + @Generated public static LifetimeActionsTrigger fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { LifetimeActionsTrigger deserializedLifetimeActionsTrigger = new LifetimeActionsTrigger(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("timeAfterCreate".equals(fieldName)) { deserializedLifetimeActionsTrigger.timeAfterCreate = reader.getString(); } else if ("timeBeforeExpiry".equals(fieldName)) { @@ -112,7 +121,6 @@ public static LifetimeActionsTrigger fromJson(JsonReader jsonReader) throws IOEx reader.skipChildren(); } } - return deserializedLifetimeActionsTrigger; }); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/LifetimeActionsType.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/LifetimeActionsType.java index 931bf6d380c0..524a3db53c73 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/LifetimeActionsType.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/LifetimeActionsType.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -17,32 +17,37 @@ */ @Fluent public final class LifetimeActionsType implements JsonSerializable { + /* * The type of the action. The value should be compared case-insensitively. */ + @Generated private KeyRotationPolicyAction type; /** * Creates an instance of LifetimeActionsType class. */ + @Generated public LifetimeActionsType() { } /** * Get the type property: The type of the action. The value should be compared case-insensitively. - * + * * @return the type value. */ + @Generated public KeyRotationPolicyAction getType() { return this.type; } /** * Set the type property: The type of the action. The value should be compared case-insensitively. - * + * * @param type the type value to set. * @return the LifetimeActionsType object itself. */ + @Generated public LifetimeActionsType setType(KeyRotationPolicyAction type) { this.type = type; return this; @@ -51,6 +56,7 @@ public LifetimeActionsType setType(KeyRotationPolicyAction type) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -60,26 +66,25 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of LifetimeActionsType from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of LifetimeActionsType 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 LifetimeActionsType. */ + @Generated public static LifetimeActionsType fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { LifetimeActionsType deserializedLifetimeActionsType = new LifetimeActionsType(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("type".equals(fieldName)) { deserializedLifetimeActionsType.type = KeyRotationPolicyAction.fromString(reader.getString()); } else { reader.skipChildren(); } } - return deserializedLifetimeActionsType; }); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/RandomBytes.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/RandomBytes.java index 78672c3d9dd8..6c2b68f6c0b8 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/RandomBytes.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/RandomBytes.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; import com.azure.core.util.Base64Url; -import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -17,24 +16,35 @@ /** * The get random bytes response object containing the bytes. */ -@Fluent +@Immutable public final class RandomBytes implements JsonSerializable { + /* * The bytes encoded as a base64url string. */ - private Base64Url value; + @Generated + private final Base64Url value; /** * Creates an instance of RandomBytes class. + * + * @param value the value value to set. */ - public RandomBytes() { + @Generated + private RandomBytes(byte[] value) { + if (value == null) { + this.value = null; + } else { + this.value = Base64Url.encode(value); + } } /** * Get the value property: The bytes encoded as a base64url string. - * + * * @return the value value. */ + @Generated public byte[] getValue() { if (this.value == null) { return null; @@ -42,24 +52,10 @@ public byte[] getValue() { return this.value.decodedBytes(); } - /** - * Set the value property: The bytes encoded as a base64url string. - * - * @param value the value value to set. - * @return the RandomBytes object itself. - */ - public RandomBytes setValue(byte[] value) { - if (value == null) { - this.value = null; - } else { - this.value = Base64Url.encode(CoreUtils.clone(value)); - } - return this; - } - /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -69,29 +65,31 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of RandomBytes from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of RandomBytes 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 RandomBytes. */ + @Generated public static RandomBytes fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - RandomBytes deserializedRandomBytes = new RandomBytes(); + byte[] value = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("value".equals(fieldName)) { - deserializedRandomBytes.value + Base64Url valueHolder = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); + if (valueHolder != null) { + value = valueHolder.decodedBytes(); + } } else { reader.skipChildren(); } } - - return deserializedRandomBytes; + return new RandomBytes(value); }); } } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/package-info.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/package-info.java index ea5b08c3e06c..9b0ff3b8750a 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/package-info.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/models/package-info.java @@ -1,9 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. /** - * Package containing the data models for KeyClient. + * + * Package containing the data models for KeyVault. * The key vault client performs cryptographic key operations and vault operations against the Key Vault service. + * */ package com.azure.security.keyvault.keys.implementation.models; diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/package-info.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/package-info.java index d1c0e17672db..ce02c774a060 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/package-info.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/package-info.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. /** - * Package containing the implementations for KeyClient. - * The key vault client performs cryptographic key operations and vault operations against the Key Vault service. + * + * Package containing the implementations for KeyClient. The key vault client performs cryptographic key operations and + * vault operations against the Key Vault service. */ package com.azure.security.keyvault.keys.implementation; diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyCurveName.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyCurveName.java index 6805836416ed..d26689bade4b 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyCurveName.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyCurveName.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.models; import com.azure.core.util.ExpandableStringEnum; diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyExportEncryptionAlgorithm.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyExportEncryptionAlgorithm.java index d62ffec53bdb..31acf2fd6cfc 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyExportEncryptionAlgorithm.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyExportEncryptionAlgorithm.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.models; import com.azure.core.util.ExpandableStringEnum; diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyOperation.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyOperation.java index 4028bd25bb96..a2122df5976e 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyOperation.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyOperation.java @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.models; import com.azure.core.util.ExpandableStringEnum; @@ -11,6 +10,7 @@ * JSON web key operations. For more information, see JsonWebKeyOperation. */ public final class KeyOperation extends ExpandableStringEnum { + /** * Static value encrypt for KeyOperation. */ @@ -48,7 +48,7 @@ public final class KeyOperation extends ExpandableStringEnum { /** * Creates a new instance of KeyOperation value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Deprecated @@ -57,7 +57,7 @@ public KeyOperation() { /** * Creates or finds a KeyOperation from its string representation. - * + * * @param name a name to look for. * @return the corresponding KeyOperation. */ @@ -67,10 +67,15 @@ public static KeyOperation fromString(String name) { /** * Gets known KeyOperation values. - * + * * @return known KeyOperation values. */ public static Collection values() { return values(KeyOperation.class); } + + /** + * Indicates that the private component of the key can be exported. + */ + static final KeyOperation EXPORT = fromString("export"); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyRotationPolicyAction.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyRotationPolicyAction.java index 63246059c599..a237654b3177 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyRotationPolicyAction.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyRotationPolicyAction.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.models; diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyType.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyType.java index 8994aedea1c0..e7f84c2e47f3 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyType.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/KeyType.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.models; import com.azure.core.util.ExpandableStringEnum; diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/ReleaseKeyResult.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/ReleaseKeyResult.java index 738a6c76067e..cebd7082b7b8 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/ReleaseKeyResult.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/ReleaseKeyResult.java @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.keys.models; import com.azure.core.annotation.Immutable; @@ -16,6 +15,7 @@ */ @Immutable public final class ReleaseKeyResult implements JsonSerializable { + /* * A signed object containing the released key. */ @@ -29,7 +29,7 @@ public ReleaseKeyResult() { /** * Get the value property: A signed object containing the released key. - * + * * @return the value value. */ public String getValue() { @@ -47,7 +47,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of ReleaseKeyResult from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of ReleaseKeyResult if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -59,14 +59,12 @@ public static ReleaseKeyResult fromJson(JsonReader jsonReader) throws IOExceptio while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("value".equals(fieldName)) { deserializedReleaseKeyResult.value = reader.getString(); } else { reader.skipChildren(); } } - return deserializedReleaseKeyResult; }); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/package-info.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/package-info.java index 63e0a5265402..0bd801bfb170 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/package-info.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/models/package-info.java @@ -1,9 +1,8 @@ // 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 KeyClient. - * The key vault client performs cryptographic key operations and vault operations against the Key Vault service. + * + * Package containing the data models for KeyClient. The key vault client performs cryptographic key operations and + * vault operations against the Key Vault service. */ package com.azure.security.keyvault.keys.models; diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/package-info.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/package-info.java index 61944b9d9d3c..5210e4a493c7 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/package-info.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/package-info.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. - /** + * *

          Azure Key Vault is a cloud-based service * provided by Microsoft Azure that allows users to securely store and manage cryptographic keys used for encrypting * and decrypting data. It is a part of Azure Key Vault, which is a cloud-based service for managing cryptographic keys, diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/module-info.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/module-info.java index 88148cf46e4a..31eef1ec91e3 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/module-info.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/module-info.java @@ -1,22 +1,22 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. module com.azure.security.keyvault.keys { requires transitive com.azure.core; requires com.azure.json; - requires java.xml.crypto; exports com.azure.security.keyvault.keys; + exports com.azure.security.keyvault.keys.models; exports com.azure.security.keyvault.keys.cryptography; exports com.azure.security.keyvault.keys.cryptography.models; - exports com.azure.security.keyvault.keys.models; + opens com.azure.security.keyvault.keys.implementation.models to com.azure.core; + opens com.azure.security.keyvault.keys.models to com.azure.core; opens com.azure.security.keyvault.keys to com.azure.core; opens com.azure.security.keyvault.keys.cryptography to com.azure.core; opens com.azure.security.keyvault.keys.cryptography.implementation to com.azure.core; opens com.azure.security.keyvault.keys.cryptography.models to com.azure.core; opens com.azure.security.keyvault.keys.implementation to com.azure.core; - opens com.azure.security.keyvault.keys.implementation.models to com.azure.core; - opens com.azure.security.keyvault.keys.models to com.azure.core; } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-keys/resource-config.json b/sdk/keyvault/azure-security-keyvault-keys/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-keys/resource-config.json index 0e369c703295..e370b99bbe2e 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-keys/resource-config.json +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-keys/resource-config.json @@ -2,7 +2,7 @@ "resources": { "includes": [ { - "pattern": "azure-key-vault-keys.properties" + "pattern": "azure-security-keyvault-keys.properties" }, { "pattern": "kvErrorStrings.properties" diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/resources/azure-security-keyvault-keys.properties b/sdk/keyvault/azure-security-keyvault-keys/src/main/resources/azure-security-keyvault-keys.properties new file mode 100644 index 000000000000..ca812989b4f2 --- /dev/null +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/resources/azure-security-keyvault-keys.properties @@ -0,0 +1,2 @@ +name=${project.artifactId} +version=${project.version} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/samples/README.md b/sdk/keyvault/azure-security-keyvault-keys/src/samples/README.md index bf5efc5803dd..665245f72ca7 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/samples/README.md +++ b/sdk/keyvault/azure-security-keyvault-keys/src/samples/README.md @@ -110,4 +110,4 @@ This project welcomes contributions and suggestions. Find [more contributing][SD [sample_wrapUnwrap]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/KeyWrapUnwrapOperations.java [sample_wrapUnwrapAsync]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/src/samples/java/com/azure/security/keyvault/keys/cryptography/KeyWrapUnwrapOperationsAsync.java -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fkeyvault%2Fazure-security-keyvault-keys%2Fsrc%2Fsamples%2FREADME.png) + diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyVaultKeysUserAgentPropertiesTest.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyVaultKeysUserAgentPropertiesTest.java index aa09df2fc221..746249cffc48 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyVaultKeysUserAgentPropertiesTest.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyVaultKeysUserAgentPropertiesTest.java @@ -14,7 +14,7 @@ public class KeyVaultKeysUserAgentPropertiesTest { @Test public void testAzureConfiguration() { - Map properties = CoreUtils.getProperties("azure-key-vault-keys.properties"); + Map properties = CoreUtils.getProperties("azure-security-keyvault-keys.properties"); assertTrue(properties.get("name").matches("azure-security-keyvault-keys")); assertTrue(properties.get("version").matches("(\\d)+.(\\d)+.(\\d)+([-a-zA-Z0-9.])*")); diff --git a/sdk/keyvault/azure-security-keyvault-keys/swagger/src/main/java/KeysCustomizations.java b/sdk/keyvault/azure-security-keyvault-keys/swagger/src/main/java/KeysCustomizations.java index 88500b428b17..9355228a6720 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/swagger/src/main/java/KeysCustomizations.java +++ b/sdk/keyvault/azure-security-keyvault-keys/swagger/src/main/java/KeysCustomizations.java @@ -3,9 +3,12 @@ import com.azure.autorest.customization.ClassCustomization; import com.azure.autorest.customization.Customization; +import com.azure.autorest.customization.Editor; import com.azure.autorest.customization.LibraryCustomization; import com.azure.autorest.customization.PackageCustomization; -import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.ast.ImportDeclaration; +import com.github.javaparser.ast.NodeList; import org.slf4j.Logger; /** @@ -14,26 +17,115 @@ public class KeysCustomizations extends Customization { @Override public void customize(LibraryCustomization libraryCustomization, Logger logger) { - modelsCustomizations(libraryCustomization.getPackage("com.azure.security.keyvault.keys.models")); + Editor rawEditor = libraryCustomization.getRawEditor(); + + // Remove unnecessary files. + removeFiles(rawEditor); + + // Customize the KeyClientImpl class. + PackageCustomization implPackageCustomization = + libraryCustomization.getPackage("com.azure.security.keyvault.keys.implementation"); + ClassCustomization implClientClassCustomization = implPackageCustomization.getClass("KeyClientImpl"); + customizeClientImpl(implClientClassCustomization); + + // Change the names of generated + ClassCustomization keyCurveNameCustomization = + libraryCustomization.getPackage("com.azure.security.keyvault.keys.models") + .getClass("KeyCurveName"); + + customizeKeyCurveName(keyCurveNameCustomization); + } + + private static void removeFiles(Editor editor) { + // Remove the next line in favor of renaming to KeyServiceVersion once the TSP spec includes all service + // versions. + editor.removeFile("src/main/java/com/azure/security/keyvault/keys/KeyVaultServiceVersion.java"); + editor.removeFile("src/main/java/com/azure/security/keyvault/keys/KeyAsyncClient.java"); + editor.removeFile("src/main/java/com/azure/security/keyvault/keys/KeyClient.java"); + editor.removeFile("src/main/java/com/azure/security/keyvault/keys/KeyClientBuilder.java"); + } + + private static void customizeClientImpl(ClassCustomization classCustomization) { + // Remove the KeyVaultServiceVersion import since we will use KeyServiceVersion for now. We'll remove + // this once the TSP spec includes all service versions. + classCustomization.customizeAst(ast -> + replaceImport(ast, "com.azure.security.keyvault.keys.KeyVaultServiceVersion", + "com.azure.security.keyvault.keys.KeyServiceVersion")); + + String classPath = + "src/main/java/com/azure/security/keyvault/keys/implementation/KeyClientImpl.java"; + + replaceInFile(classCustomization, classPath, "KeyVault", "Key"); + } + + private static void customizeKeyCurveName(ClassCustomization classCustomization) { + classCustomization.customizeAst(ast -> + ast.getClassByName("KeyCurveName") + .ifPresent(clazz -> { + clazz.getFieldByName("P256").ifPresent(field -> field.getVariable(0).setName("P_256")); + clazz.getFieldByName("P384").ifPresent(field -> field.getVariable(0).setName("P_384")); + clazz.getFieldByName("P521").ifPresent(field -> field.getVariable(0).setName("P_521")); + clazz.getFieldByName("P256_K").ifPresent(field -> field.getVariable(0).setName("P_256K")); + }) + ); + + String classPath = + "src/main/java/com/azure/security/keyvault/keys/models/KeyCurveName.java"; + + replaceInFile(classCustomization, classPath, " For valid values, see JsonWebKeyCurveName.", ""); + } + + /** + * This method replaces all the provided strings in the specified file with new strings provided in the latter half + * of the 'strings' parameter. + * + * @param classCustomization The class customization to use to edit the file. + * @param classPath The path to the file to edit. + * @param strings The strings to replace. The first half of the strings will be replaced with the second half in the + * order they are provided. + */ + private static void replaceInFile(ClassCustomization classCustomization, String classPath, + String... strings) { + + // Replace all instances of KeyVaultServiceVersion with KeyServiceVersion. We'll remove this once the + // TSP spec includes all service versions. + Editor editor = classCustomization.getEditor(); + String fileContent = editor.getFileContent(classPath); + + // Ensure names has an even length. + if (strings.length % 2 != 0) { + throw new IllegalArgumentException("The 'names' parameter must have an even number of elements."); + } + + for (int i = 0; i < (strings.length / 2); i++) { + fileContent = fileContent.replace(strings[i], strings[i + strings.length / 2]); + } + + editor.replaceFile(classPath, fileContent); + + // Uncomment once there's a new version of the AutoRest library out. + /*List ranges = editor.searchText(classPath, "KeyVaultServiceVersion"); + + for (Range range : ranges) { + editor.replace(classPath, range.getStart(), range.getEnd(), "KeyServiceVersion"); + }*/ + } + + private static void replaceImport(CompilationUnit ast, String originalImport, String newImport) { + NodeList nodeList = ast.getImports(); + + for (ImportDeclaration importDeclaration : nodeList) { + if (importDeclaration.getNameAsString().equals(originalImport)) { + importDeclaration.setName(newImport); + + break; + } + } + + ast.setImports(nodeList); } - private static void modelsCustomizations(PackageCustomization models) { - models.getClass("KeyCurveName").customizeAst(ast -> ast.getClassByName("KeyCurveName").ifPresent(clazz -> { - clazz.getFieldByName("P256K").ifPresent(field -> field.getVariable(0).setName("P_256K")); - clazz.getFieldByName("P256").ifPresent(field -> field.getVariable(0).setName("P_256")); - clazz.getFieldByName("P384").ifPresent(field -> field.getVariable(0).setName("P_384")); - clazz.getFieldByName("P521").ifPresent(field -> field.getVariable(0).setName("P_521")); - })); - - models.getClass("KeyType").customizeAst(ast -> ast.getClassByName("KeyType").ifPresent(clazz -> { - clazz.getFieldByName("ECHSM").ifPresent(field -> field.getVariable(0).setName("EC_HSM")); - clazz.getFieldByName("RSAHSM").ifPresent(field -> field.getVariable(0).setName("RSA_HSM")); - })); - - models.getClass("KeyExportEncryptionAlgorithm").customizeAst(ast -> ast.getClassByName("KeyExportEncryptionAlgorithm").ifPresent(clazz -> { - clazz.getFieldByName("CKMRSAAESKEYWRAP").ifPresent(field -> field.getVariable(0).setName("CKM_RSA_AES_KEY_WRAP")); - clazz.getFieldByName("RSAAESKEYWRAP256").ifPresent(field -> field.getVariable(0).setName("RSA_AES_KEY_WRAP_256")); - clazz.getFieldByName("RSAAESKEYWRAP384").ifPresent(field -> field.getVariable(0).setName("RSA_AES_KEY_WRAP_384")); - })); + private static String joinWithNewline(String... lines) { + return String.join("\n", lines); } } diff --git a/sdk/keyvault/azure-security-keyvault-keys/tsp-location.yaml b/sdk/keyvault/azure-security-keyvault-keys/tsp-location.yaml new file mode 100644 index 000000000000..9e1f9cd44569 --- /dev/null +++ b/sdk/keyvault/azure-security-keyvault-keys/tsp-location.yaml @@ -0,0 +1,6 @@ +directory: specification/keyvault/Security.KeyVault.Keys +commit: a0eb4f02951e8b7dd80e72e108b9cf7618718bc9 +repo: Azure/azure-rest-api-specs +cleanup: true +additionalDirectories: +- specification/keyvault/Security.KeyVault.Common/ diff --git a/sdk/keyvault/azure-security-keyvault-perf/pom.xml b/sdk/keyvault/azure-security-keyvault-perf/pom.xml index 3ec8a8dab14e..1f14683578b7 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.15.0 + 1.15.4 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 com.azure @@ -57,12 +57,12 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 diff --git a/sdk/keyvault/azure-security-keyvault-secrets/CHANGELOG.md b/sdk/keyvault/azure-security-keyvault-secrets/CHANGELOG.md index 5e0f255e7ffe..f473ee07bfea 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/CHANGELOG.md +++ b/sdk/keyvault/azure-security-keyvault-secrets/CHANGELOG.md @@ -10,6 +10,21 @@ ### Other Changes +## 4.9.3 (2025-03-04) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. +- Upgraded `azure-json` from `1.3.0` to version `1.4.0`. +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`. + +## 4.9.2 (2025-01-14) + +### Bugs Fixed +- Fixed issue where certain `toString()` calls could cause a `NullPointerException`. ([#43776](https://github.com/Azure/azure-sdk-for-java/pull/43776)) + ## 4.9.1 (2024-12-04) ### Other Changes diff --git a/sdk/keyvault/azure-security-keyvault-secrets/README.md b/sdk/keyvault/azure-security-keyvault-secrets/README.md index 454266cd9268..006fd63ee6ee 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/README.md +++ b/sdk/keyvault/azure-security-keyvault-secrets/README.md @@ -46,7 +46,7 @@ If you want to take dependency on a particular version of the library that is no com.azure azure-security-keyvault-secrets - 4.9.0 + 4.10.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -277,4 +277,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][microsoft_c [http_clients_wiki]: https://learn.microsoft.com/azure/developer/java/sdk/http-client-pipeline#http-clients [microsoft_code_of_conduct]: https://opensource.microsoft.com/codeofconduct/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fkeyvault%2Fazure-security-keyvault-secrets%2FREADME.png) + diff --git a/sdk/keyvault/azure-security-keyvault-secrets/checkstyle-suppressions.xml b/sdk/keyvault/azure-security-keyvault-secrets/checkstyle-suppressions.xml index 76f2e5b6e1e5..27fa2929b0f3 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/checkstyle-suppressions.xml +++ b/sdk/keyvault/azure-security-keyvault-secrets/checkstyle-suppressions.xml @@ -4,6 +4,7 @@ + diff --git a/sdk/keyvault/azure-security-keyvault-secrets/pom.xml b/sdk/keyvault/azure-security-keyvault-secrets/pom.xml index 7d12c9d2baec..e4f3f57ddaa3 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/pom.xml +++ b/sdk/keyvault/azure-security-keyvault-secrets/pom.xml @@ -50,33 +50,33 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretAsyncClient.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretAsyncClient.java index 7c036867fce0..e295096f9202 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretAsyncClient.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretAsyncClient.java @@ -9,23 +9,28 @@ import com.azure.core.exception.HttpResponseException; import com.azure.core.exception.ResourceModifiedException; import com.azure.core.exception.ResourceNotFoundException; -import com.azure.core.http.HttpPipeline; import com.azure.core.http.rest.PagedFlux; import com.azure.core.http.rest.PagedResponse; import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.RequestOptions; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.BinaryData; import com.azure.core.util.CoreUtils; -import com.azure.core.util.FluxUtil; import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.paging.PageRetriever; import com.azure.core.util.polling.LongRunningOperationStatus; import com.azure.core.util.polling.PollResponse; import com.azure.core.util.polling.PollerFlux; import com.azure.core.util.polling.PollingContext; import com.azure.security.keyvault.secrets.implementation.SecretClientImpl; +import com.azure.security.keyvault.secrets.implementation.models.BackupSecretResult; +import com.azure.security.keyvault.secrets.implementation.models.DeletedSecretBundle; import com.azure.security.keyvault.secrets.implementation.models.DeletedSecretItem; -import com.azure.security.keyvault.secrets.implementation.models.KeyVaultErrorException; +import com.azure.security.keyvault.secrets.implementation.models.SecretBundle; import com.azure.security.keyvault.secrets.implementation.models.SecretItem; +import com.azure.security.keyvault.secrets.implementation.models.SecretRestoreParameters; +import com.azure.security.keyvault.secrets.implementation.models.SecretSetParameters; import com.azure.security.keyvault.secrets.implementation.models.SecretsModelsUtils; import com.azure.security.keyvault.secrets.models.DeletedSecret; import com.azure.security.keyvault.secrets.models.KeyVaultSecret; @@ -35,14 +40,16 @@ import java.time.Duration; import java.time.OffsetDateTime; -import java.util.ArrayList; -import java.util.List; import java.util.function.Function; +import java.util.function.Supplier; +import java.util.stream.Collectors; import static com.azure.core.util.FluxUtil.monoError; +import static com.azure.core.util.FluxUtil.pagedFluxError; +import static com.azure.security.keyvault.secrets.SecretClient.prepareSecretSetParameters; +import static com.azure.security.keyvault.secrets.SecretClient.prepareUpdateSecretParameters; import static com.azure.security.keyvault.secrets.implementation.models.SecretsModelsUtils.createDeletedSecret; import static com.azure.security.keyvault.secrets.implementation.models.SecretsModelsUtils.createKeyVaultSecret; -import static com.azure.security.keyvault.secrets.implementation.models.SecretsModelsUtils.createSecretAttributes; import static com.azure.security.keyvault.secrets.implementation.models.SecretsModelsUtils.createSecretProperties; /** @@ -155,14 +162,16 @@ public final class SecretAsyncClient { private static final ClientLogger LOGGER = new ClientLogger(SecretAsyncClient.class); + static final RequestOptions EMPTY_OPTIONS = new RequestOptions(); + private final SecretClientImpl implClient; private final String vaultUrl; /** * Creates a SecretAsyncClient to service requests * - * @param implClient the implementation client. - * @param vaultUrl the vault url. + * @param implClient The implementation client. + * @param vaultUrl The vault url. */ SecretAsyncClient(SecretClientImpl implClient, String vaultUrl) { this.implClient = implClient; @@ -177,15 +186,6 @@ public String getVaultUrl() { return vaultUrl; } - /** - * Gets the {@link HttpPipeline} powering this client. - * - * @return The pipeline. - */ - HttpPipeline getHttpPipeline() { - return implClient.getHttpPipeline(); - } - /** * Adds a secret to the key vault if it does not exist. If the named secret exists, a new version of the secret is * created. This operation requires the {@code secrets/set} permission. @@ -222,7 +222,15 @@ HttpPipeline getHttpPipeline() { */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono setSecret(KeyVaultSecret secret) { - return setSecretWithResponse(secret).flatMap(FluxUtil::toMono); + try { + return implClient + .setSecretWithResponseAsync(secret.getName(), BinaryData.fromObject(prepareSecretSetParameters(secret)), + EMPTY_OPTIONS) + .onErrorMap(HttpResponseException.class, SecretAsyncClient::mapSetSecretException) + .map(response -> createKeyVaultSecret(response.getValue().toObject(SecretBundle.class))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); + } } /** @@ -249,7 +257,14 @@ public Mono setSecret(KeyVaultSecret secret) { */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono setSecret(String name, String value) { - return setSecretWithResponse(new KeyVaultSecret(name, value)).flatMap(FluxUtil::toMono); + try { + return implClient + .setSecretWithResponseAsync(name, BinaryData.fromObject(new SecretSetParameters(value)), EMPTY_OPTIONS) + .onErrorMap(HttpResponseException.class, SecretAsyncClient::mapSetSecretException) + .map(response -> createKeyVaultSecret(response.getValue().toObject(SecretBundle.class))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); + } } /** @@ -287,34 +302,23 @@ public Mono setSecret(String name, String value) { @ServiceMethod(returns = ReturnType.SINGLE) public Mono> setSecretWithResponse(KeyVaultSecret secret) { try { - SecretProperties secretProperties = secret.getProperties(); - if (secretProperties == null) { - return implClient - .setSecretWithResponseAsync(vaultUrl, secret.getName(), secret.getValue(), null, null, null) - .onErrorMap(KeyVaultErrorException.class, SecretAsyncClient::mapSetSecretException) - .map(response -> new SimpleResponse<>(response, createKeyVaultSecret(response.getValue()))); - } else { - return implClient - .setSecretWithResponseAsync(vaultUrl, secret.getName(), secret.getValue(), - secretProperties.getTags(), secretProperties.getContentType(), - createSecretAttributes(secretProperties)) - .onErrorMap(KeyVaultErrorException.class, SecretAsyncClient::mapSetSecretException) - .map(response -> new SimpleResponse<>(response, createKeyVaultSecret(response.getValue()))); - } - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + return implClient + .setSecretWithResponseAsync(secret.getName(), BinaryData.fromObject(prepareSecretSetParameters(secret)), + EMPTY_OPTIONS) + .onErrorMap(HttpResponseException.class, SecretAsyncClient::mapSetSecretException) + .map(response -> new SimpleResponse<>(response, + createKeyVaultSecret(response.getValue().toObject(SecretBundle.class)))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); } } - // For backwards compatibility with the exception type mapping of the handwritten KeyVault Secrets REST proxy. - // Only specific error codes are mapped to certain HttpResponseException subclasses, the default before was - // HttpResponseException and the new default is KeyVaultErrorException which is a subclass of HttpResponseException - // and is a non-breaking change. Specific error codes used different subclasses of HttpResponseException and that - // is a breaking change, so this mapping preserves the old behavior. - static HttpResponseException mapSetSecretException(KeyVaultErrorException ex) { - return (ex.getResponse().getStatusCode() == 400) - ? new ResourceModifiedException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; + // For some reason, the service does not return a 409 when a secret with the same name exists. Instead, it returns + // a 400. + static HttpResponseException mapSetSecretException(HttpResponseException e) { + return (e.getResponse().getStatusCode() == 400) + ? new ResourceModifiedException(e.getMessage(), e.getResponse(), e.getValue()) + : e; } /** @@ -341,7 +345,7 @@ static HttpResponseException mapSetSecretException(KeyVaultErrorException ex) { */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono getSecret(String name) { - return getSecretWithResponse(name, null).flatMap(FluxUtil::toMono); + return getSecret(name, ""); } /** @@ -377,7 +381,17 @@ public Mono getSecret(String name) { */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono getSecret(String name, String version) { - return getSecretWithResponse(name, version).flatMap(FluxUtil::toMono); + if (CoreUtils.isNullOrEmpty(name)) { + return monoError(LOGGER, new IllegalArgumentException("'name' cannot be null or empty.")); + } + + try { + return implClient.getSecretWithResponseAsync(name, version, EMPTY_OPTIONS) + .onErrorMap(HttpResponseException.class, SecretAsyncClient::mapGetSecretException) + .map(response -> createKeyVaultSecret(response.getValue().toObject(SecretBundle.class))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); + } } /** @@ -417,22 +431,22 @@ public Mono> getSecretWithResponse(String name, String } try { - return implClient.getSecretWithResponseAsync(vaultUrl, name, version) - .onErrorMap(KeyVaultErrorException.class, SecretAsyncClient::mapGetSecretException) - .map(response -> new SimpleResponse<>(response, createKeyVaultSecret(response.getValue()))); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + return implClient.getSecretWithResponseAsync(name, version, EMPTY_OPTIONS) + .onErrorMap(HttpResponseException.class, SecretAsyncClient::mapGetSecretException) + .map(response -> new SimpleResponse<>(response, + createKeyVaultSecret(response.getValue().toObject(SecretBundle.class)))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); } } - // See other map*Exception methods for explanation of why this is done. - static HttpResponseException mapGetSecretException(HttpResponseException ex) { - if (ex.getResponse().getStatusCode() == 404) { - return new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()); - } else if (ex.getResponse().getStatusCode() == 403) { - return new ResourceModifiedException(ex.getMessage(), ex.getResponse(), ex.getValue()); + // For some reason, the service does not return a 409 when a secret with the same name exists. Instead, it returns + // a 403. + static HttpResponseException mapGetSecretException(HttpResponseException e) { + if (e.getResponse().getStatusCode() == 403) { + return new ResourceModifiedException(e.getMessage(), e.getResponse(), e.getValue()); } else { - return ex; + return e; } } @@ -474,7 +488,14 @@ static HttpResponseException mapGetSecretException(HttpResponseException ex) { */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono updateSecretProperties(SecretProperties secretProperties) { - return updateSecretPropertiesWithResponse(secretProperties).flatMap(FluxUtil::toMono); + try { + return implClient + .updateSecretWithResponseAsync(secretProperties.getName(), secretProperties.getVersion(), + BinaryData.fromObject(prepareUpdateSecretParameters(secretProperties)), EMPTY_OPTIONS) + .map(response -> createSecretProperties(response.getValue().toObject(SecretBundle.class))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); + } } /** @@ -518,12 +539,12 @@ public Mono updateSecretProperties(SecretProperties secretProp public Mono> updateSecretPropertiesWithResponse(SecretProperties secretProperties) { try { return implClient - .updateSecretWithResponseAsync(vaultUrl, secretProperties.getName(), secretProperties.getVersion(), - secretProperties.getContentType(), createSecretAttributes(secretProperties), - secretProperties.getTags()) - .map(response -> new SimpleResponse<>(response, createSecretProperties(response.getValue()))); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + .updateSecretWithResponseAsync(secretProperties.getName(), secretProperties.getVersion(), + BinaryData.fromObject(prepareUpdateSecretParameters(secretProperties)), EMPTY_OPTIONS) + .map(response -> new SimpleResponse<>(response, + createSecretProperties(response.getValue().toObject(SecretBundle.class)))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); } } @@ -559,23 +580,22 @@ public PollerFlux beginDeleteSecret(String name) { } private Function, Mono> deleteActivationOperation(String name) { - return pollingContext -> implClient.deleteSecretAsync(vaultUrl, name) - .onErrorMap(KeyVaultErrorException.class, SecretAsyncClient::mapDeleteSecretException) - .map(SecretsModelsUtils::createDeletedSecret); - } - - // See other map*Exception methods for explanation of why this is done. - static HttpResponseException mapDeleteSecretException(HttpResponseException ex) { - return (ex.getResponse().getStatusCode() == 404) - ? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; + return pollingContext -> { + try { + return implClient.deleteSecretWithResponseAsync(name, EMPTY_OPTIONS) + .map(response -> createDeletedSecret(response.getValue().toObject(DeletedSecretBundle.class))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); + } + }; } private Function, Mono>> deletePollOperation(String name) { - return pollingContext -> implClient.getDeletedSecretAsync(vaultUrl, name) - .map(bundle -> new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, - createDeletedSecret(bundle))) + + return pollingContext -> implClient.getDeletedSecretWithResponseAsync(name, EMPTY_OPTIONS) + .map(response -> new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, + createDeletedSecret(response.getValue().toObject(DeletedSecretBundle.class)))) .onErrorResume(HttpResponseException.class, exception -> { if (exception.getResponse().getStatusCode() == 404) { return Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, @@ -618,7 +638,12 @@ static HttpResponseException mapDeleteSecretException(HttpResponseException ex) */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono getDeletedSecret(String name) { - return getDeletedSecretWithResponse(name).flatMap(FluxUtil::toMono); + try { + return implClient.getDeletedSecretWithResponseAsync(name, EMPTY_OPTIONS) + .map(response -> createDeletedSecret(response.getValue().toObject(DeletedSecretBundle.class))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); + } } /** @@ -647,21 +672,14 @@ public Mono getDeletedSecret(String name) { @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getDeletedSecretWithResponse(String name) { try { - return implClient.getDeletedSecretWithResponseAsync(vaultUrl, name) - .onErrorMap(KeyVaultErrorException.class, SecretAsyncClient::mapGetDeletedSecretException) - .map(response -> new SimpleResponse<>(response, createDeletedSecret(response.getValue()))); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + return implClient.getDeletedSecretWithResponseAsync(name, EMPTY_OPTIONS) + .map(response -> new SimpleResponse<>(response, + createDeletedSecret(response.getValue().toObject(DeletedSecretBundle.class)))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); } } - // See other map*Exception methods for explanation of why this is done. - static HttpResponseException mapGetDeletedSecretException(HttpResponseException ex) { - return (ex.getResponse().getStatusCode() == 404) - ? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; - } - /** * Permanently removes a deleted secret, without the possibility of recovery. This operation can only be performed * on a soft-delete enabled. This operation requires the {@code secrets/purge} permission. @@ -686,7 +704,12 @@ static HttpResponseException mapGetDeletedSecretException(HttpResponseException */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono purgeDeletedSecret(String name) { - return purgeDeletedSecretWithResponse(name).flatMap(FluxUtil::toMono); + try { + return implClient.purgeDeletedSecretWithResponseAsync(name, EMPTY_OPTIONS) + .flatMap(response -> Mono.empty()); + } catch (RuntimeException e) { + return monoError(LOGGER, e); + } } /** @@ -713,20 +736,12 @@ public Mono purgeDeletedSecret(String name) { @ServiceMethod(returns = ReturnType.SINGLE) public Mono> purgeDeletedSecretWithResponse(String name) { try { - return implClient.purgeDeletedSecretWithResponseAsync(vaultUrl, name) - .onErrorMap(KeyVaultErrorException.class, SecretAsyncClient::mapPurgeDeletedSecretException); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + return implClient.purgeDeletedSecretWithResponseAsync(name, EMPTY_OPTIONS); + } catch (RuntimeException e) { + return monoError(LOGGER, e); } } - // See other map*Exception methods for explanation of why this is done. - static HttpResponseException mapPurgeDeletedSecretException(HttpResponseException ex) { - return (ex.getResponse().getStatusCode() == 404) - ? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; - } - /** * Recovers the deleted secret in the key vault to its latest version. Can only be performed on a soft-delete * enabled vault. This operation requires the {@code secrets/recover} permission. @@ -758,23 +773,22 @@ public PollerFlux beginRecoverDeletedSecret(String name) { } private Function, Mono> recoverActivationOperation(String name) { - return pollingContext -> implClient.recoverDeletedSecretAsync(vaultUrl, name) - .onErrorMap(KeyVaultErrorException.class, SecretAsyncClient::mapRecoverDeletedSecretException) - .map(SecretsModelsUtils::createKeyVaultSecret); - } - - // See other map*Exception methods for explanation of why this is done. - static HttpResponseException mapRecoverDeletedSecretException(HttpResponseException ex) { - return (ex.getResponse().getStatusCode() == 404) - ? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; + return pollingContext -> { + try { + return implClient.recoverDeletedSecretWithResponseAsync(name, EMPTY_OPTIONS) + .map(response -> createKeyVaultSecret(response.getValue().toObject(SecretBundle.class))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); + } + }; } private Function, Mono>> recoverPollOperation(String name) { - return pollingContext -> implClient.getSecretWithResponseAsync(vaultUrl, name, null) + + return pollingContext -> implClient.getSecretWithResponseAsync(name, "", EMPTY_OPTIONS) .map(response -> new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, - createKeyVaultSecret(response.getValue()))) + createKeyVaultSecret(response.getValue().toObject(SecretBundle.class)))) .onErrorResume(HttpResponseException.class, exception -> { if (exception.getResponse().getStatusCode() == 404) { return Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, @@ -815,7 +829,13 @@ static HttpResponseException mapRecoverDeletedSecretException(HttpResponseExcept */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono backupSecret(String name) { - return backupSecretWithResponse(name).flatMap(FluxUtil::toMono); + try { + return implClient.backupSecretWithResponseAsync(name, EMPTY_OPTIONS) + .map(response -> response.getValue().toObject(BackupSecretResult.class)) + .mapNotNull(BackupSecretResult::getValue); + } catch (RuntimeException e) { + return monoError(LOGGER, e); + } } /** @@ -843,21 +863,13 @@ public Mono backupSecret(String name) { @ServiceMethod(returns = ReturnType.SINGLE) public Mono> backupSecretWithResponse(String name) { try { - return implClient.backupSecretWithResponseAsync(vaultUrl, name) - .onErrorMap(KeyVaultErrorException.class, SecretAsyncClient::mapBackupSecretException) - .map(response -> new SimpleResponse<>(response, response.getValue().getValue())); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + return implClient.backupSecretWithResponseAsync(name, EMPTY_OPTIONS) + .map(response -> new SimpleResponse<>(response, response.getValue().toBytes())); + } catch (RuntimeException e) { + return monoError(LOGGER, e); } } - // See other map*Exception methods for explanation of why this is done. - static HttpResponseException mapBackupSecretException(HttpResponseException ex) { - return (ex.getResponse().getStatusCode() == 404) - ? new ResourceNotFoundException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; - } - /** * Restores a backed up secret, and all its versions, to a vault. This operation requires the * {@code secrets/restore} permission. @@ -882,7 +894,15 @@ static HttpResponseException mapBackupSecretException(HttpResponseException ex) */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono restoreSecretBackup(byte[] backup) { - return restoreSecretBackupWithResponse(backup).flatMap(FluxUtil::toMono); + try { + return implClient + .restoreSecretWithResponseAsync(BinaryData.fromObject(new SecretRestoreParameters(backup)), + EMPTY_OPTIONS) + .onErrorMap(HttpResponseException.class, SecretAsyncClient::mapRestoreSecretException) + .map(response -> createKeyVaultSecret(response.getValue().toObject(SecretBundle.class))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); + } } /** @@ -911,19 +931,22 @@ public Mono restoreSecretBackup(byte[] backup) { @ServiceMethod(returns = ReturnType.SINGLE) public Mono> restoreSecretBackupWithResponse(byte[] backup) { try { - return implClient.restoreSecretWithResponseAsync(vaultUrl, backup) - .onErrorMap(KeyVaultErrorException.class, SecretAsyncClient::mapRestoreSecretException) - .map(response -> new SimpleResponse<>(response, createKeyVaultSecret(response.getValue()))); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + return implClient + .restoreSecretWithResponseAsync(BinaryData.fromObject(new SecretRestoreParameters(backup)), + EMPTY_OPTIONS) + .onErrorMap(HttpResponseException.class, SecretAsyncClient::mapRestoreSecretException) + .map(response -> new SimpleResponse<>(response, + createKeyVaultSecret(response.getValue().toObject(SecretBundle.class)))); + } catch (RuntimeException e) { + return monoError(LOGGER, e); } } - // See other map*Exception methods for explanation of why this is done. - static HttpResponseException mapRestoreSecretException(HttpResponseException ex) { - return (ex.getResponse().getStatusCode() == 400) - ? new ResourceModifiedException(ex.getMessage(), ex.getResponse(), ex.getValue()) - : ex; + // For some reason, the service does not return a 409 but a 400 in this case. + static HttpResponseException mapRestoreSecretException(HttpResponseException e) { + return (e.getResponse().getStatusCode() == 400) + ? new ResourceModifiedException(e.getMessage(), e.getResponse(), e.getValue()) + : e; } /** @@ -954,11 +977,12 @@ static HttpResponseException mapRestoreSecretException(HttpResponseException ex) */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux listPropertiesOfSecrets() { - return new PagedFlux<>( - maxResults -> implClient.getSecretsSinglePageAsync(vaultUrl, maxResults) - .map(SecretAsyncClient::mapSecretItemPage), - (continuationToken, maxResults) -> implClient.getSecretsNextSinglePageAsync(continuationToken, vaultUrl) - .map(SecretAsyncClient::mapSecretItemPage)); + try { + return mapPages(implClient.getSecretsAsync(EMPTY_OPTIONS), + binaryData -> SecretsModelsUtils.createSecretProperties(binaryData.toObject(SecretItem.class))); + } catch (RuntimeException e) { + return pagedFluxError(LOGGER, e); + } } /** @@ -981,22 +1005,12 @@ public PagedFlux listPropertiesOfSecrets() { */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux listDeletedSecrets() { - return new PagedFlux<>( - maxResults -> implClient.getDeletedSecretsSinglePageAsync(vaultUrl, maxResults) - .map(SecretAsyncClient::mapDeletedSecretItemPage), - (continuationToken, maxResults) -> implClient - .getDeletedSecretsNextSinglePageAsync(continuationToken, vaultUrl) - .map(SecretAsyncClient::mapDeletedSecretItemPage)); - } - - static PagedResponse mapDeletedSecretItemPage(PagedResponse page) { - List converted = new ArrayList<>(page.getValue().size()); - for (DeletedSecretItem deletedSecretItem : page.getValue()) { - converted.add(createDeletedSecret(deletedSecretItem)); + try { + return mapPages(implClient.getDeletedSecretsAsync(EMPTY_OPTIONS), + binaryData -> SecretsModelsUtils.createDeletedSecret(binaryData.toObject(DeletedSecretItem.class))); + } catch (RuntimeException e) { + return pagedFluxError(LOGGER, e); } - - return new PagedResponseBase<>(page.getRequest(), page.getStatusCode(), page.getHeaders(), converted, - page.getContinuationToken(), null); } /** @@ -1028,21 +1042,27 @@ static PagedResponse mapDeletedSecretItemPage(PagedResponse listPropertiesOfSecretVersions(String name) { - return new PagedFlux<>( - maxResults -> implClient.getSecretVersionsSinglePageAsync(vaultUrl, name, maxResults) - .map(SecretAsyncClient::mapSecretItemPage), - (continuationToken, maxResults) -> implClient - .getSecretVersionsNextSinglePageAsync(continuationToken, vaultUrl) - .map(SecretAsyncClient::mapSecretItemPage)); + try { + return mapPages(implClient.getSecretVersionsAsync(name, EMPTY_OPTIONS), + binaryData -> SecretsModelsUtils.createSecretProperties(binaryData.toObject(SecretItem.class))); + } catch (RuntimeException e) { + return pagedFluxError(LOGGER, e); + } } - static PagedResponse mapSecretItemPage(PagedResponse page) { - List converted = new ArrayList<>(page.getValue().size()); - for (SecretItem secretItem : page.getValue()) { - converted.add(createSecretProperties(secretItem)); - } + private static PagedFlux mapPages(PagedFlux pagedFlux, Function mapper) { + final Function, PagedResponse> responseMapper + = inputResponse -> new PagedResponseBase(inputResponse.getRequest(), inputResponse.getStatusCode(), + inputResponse.getHeaders(), inputResponse.getValue().stream().map(mapper).collect(Collectors.toList()), + inputResponse.getContinuationToken(), null); + + final Supplier>> provider = () -> (continuationToken, pageSize) -> { + Flux> flux + = (continuationToken == null) ? pagedFlux.byPage() : pagedFlux.byPage(continuationToken); + + return flux.map(responseMapper); + }; - return new PagedResponseBase<>(page.getRequest(), page.getStatusCode(), page.getHeaders(), converted, - page.getContinuationToken(), null); + return PagedFlux.create(provider); } } diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretClient.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretClient.java index 8a66d7d4bccc..c735d1864ff4 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretClient.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretClient.java @@ -10,8 +10,10 @@ import com.azure.core.exception.ResourceModifiedException; import com.azure.core.exception.ResourceNotFoundException; import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.RequestOptions; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.BinaryData; import com.azure.core.util.Context; import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; @@ -22,8 +24,12 @@ import com.azure.security.keyvault.secrets.implementation.SecretClientImpl; import com.azure.security.keyvault.secrets.implementation.models.BackupSecretResult; import com.azure.security.keyvault.secrets.implementation.models.DeletedSecretBundle; -import com.azure.security.keyvault.secrets.implementation.models.KeyVaultErrorException; +import com.azure.security.keyvault.secrets.implementation.models.DeletedSecretItem; import com.azure.security.keyvault.secrets.implementation.models.SecretBundle; +import com.azure.security.keyvault.secrets.implementation.models.SecretItem; +import com.azure.security.keyvault.secrets.implementation.models.SecretRestoreParameters; +import com.azure.security.keyvault.secrets.implementation.models.SecretSetParameters; +import com.azure.security.keyvault.secrets.implementation.models.SecretUpdateParameters; import com.azure.security.keyvault.secrets.models.DeletedSecret; import com.azure.security.keyvault.secrets.models.KeyVaultSecret; import com.azure.security.keyvault.secrets.models.SecretProperties; @@ -32,8 +38,7 @@ import java.util.function.Function; import java.util.function.Supplier; -import static com.azure.security.keyvault.secrets.SecretAsyncClient.mapDeletedSecretItemPage; -import static com.azure.security.keyvault.secrets.SecretAsyncClient.mapSecretItemPage; +import static com.azure.security.keyvault.secrets.SecretAsyncClient.EMPTY_OPTIONS; import static com.azure.security.keyvault.secrets.implementation.models.SecretsModelsUtils.createDeletedSecret; import static com.azure.security.keyvault.secrets.implementation.models.SecretsModelsUtils.createKeyVaultSecret; import static com.azure.security.keyvault.secrets.implementation.models.SecretsModelsUtils.createSecretAttributes; @@ -163,8 +168,8 @@ public String getVaultUrl() { /** * Creates a SecretClient to service requests * - * @param implClient the implementation client. - * @param vaultUrl the vault url. + * @param implClient The implementation client. + * @param vaultUrl The vault url. */ SecretClient(SecretClientImpl implClient, String vaultUrl) { this.implClient = implClient; @@ -202,7 +207,13 @@ public String getVaultUrl() { */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret setSecret(KeyVaultSecret secret) { - return setSecretWithResponse(secret, Context.NONE).getValue(); + return callWithMappedException(() -> createKeyVaultSecret( + implClient + .setSecretWithResponse(secret.getName(), BinaryData.fromObject(prepareSecretSetParameters(secret)), + EMPTY_OPTIONS) + .getValue() + .toObject(SecretBundle.class)), + SecretAsyncClient::mapSetSecretException); } /** @@ -227,7 +238,11 @@ public KeyVaultSecret setSecret(KeyVaultSecret secret) { */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret setSecret(String name, String value) { - return setSecretWithResponse(new KeyVaultSecret(name, value), Context.NONE).getValue(); + return callWithMappedException(() -> createKeyVaultSecret( + implClient.setSecretWithResponse(name, BinaryData.fromObject(new SecretSetParameters(value)), EMPTY_OPTIONS) + .getValue() + .toObject(SecretBundle.class)), + SecretAsyncClient::mapSetSecretException); } /** @@ -257,20 +272,27 @@ public KeyVaultSecret setSecret(String name, String value) { @ServiceMethod(returns = ReturnType.SINGLE) public Response setSecretWithResponse(KeyVaultSecret secret, Context context) { return callWithMappedException(() -> { - SecretProperties secretProperties = secret.getProperties(); - if (secretProperties == null) { - Response response = implClient.setSecretWithResponse(vaultUrl, secret.getName(), - secret.getValue(), null, null, null, context); - return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); - } else { - Response response = implClient.setSecretWithResponse(vaultUrl, secret.getName(), - secret.getValue(), secretProperties.getTags(), secretProperties.getContentType(), - createSecretAttributes(secretProperties), context); - return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); - } + Response response = implClient.setSecretWithResponse(secret.getName(), + BinaryData.fromObject(prepareSecretSetParameters(secret)), new RequestOptions().setContext(context)); + + return new SimpleResponse<>(response, + createKeyVaultSecret(response.getValue().toObject(SecretBundle.class))); }, SecretAsyncClient::mapSetSecretException); } + static SecretSetParameters prepareSecretSetParameters(KeyVaultSecret secret) { + SecretSetParameters secretSetParameters = new SecretSetParameters(secret.getValue()); + SecretProperties secretProperties = secret.getProperties(); + + if (secretProperties != null) { + secretSetParameters.setTags(secretProperties.getTags()) + .setContentType(secretProperties.getContentType()) + .setSecretAttributes(createSecretAttributes(secretProperties)); + } + + return secretSetParameters; + } + /** * Gets the latest version of the specified secret from the key vault. * This operation requires the {@code secrets/get} permission. @@ -293,7 +315,14 @@ public Response setSecretWithResponse(KeyVaultSecret secret, Con */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret getSecret(String name) { - return getSecretWithResponse(name, null, Context.NONE).getValue(); + if (CoreUtils.isNullOrEmpty(name)) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException("'name' cannot be null or empty.")); + } + + return callWithMappedException( + () -> createKeyVaultSecret( + implClient.getSecretWithResponse(name, "", EMPTY_OPTIONS).getValue().toObject(SecretBundle.class)), + SecretAsyncClient::mapGetSecretException); } /** @@ -322,7 +351,14 @@ public KeyVaultSecret getSecret(String name) { */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret getSecret(String name, String version) { - return getSecretWithResponse(name, version, Context.NONE).getValue(); + if (CoreUtils.isNullOrEmpty(name)) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException("'name' cannot be null or empty.")); + } + + return callWithMappedException( + () -> createKeyVaultSecret( + implClient.getSecretWithResponse(name, version, EMPTY_OPTIONS).getValue().toObject(SecretBundle.class)), + SecretAsyncClient::mapGetSecretException); } /** @@ -357,8 +393,11 @@ public Response getSecretWithResponse(String name, String versio } return callWithMappedException(() -> { - Response response = implClient.getSecretWithResponse(vaultUrl, name, version, context); - return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); + Response response + = implClient.getSecretWithResponse(name, version, new RequestOptions().setContext(context)); + + return new SimpleResponse<>(response, + createKeyVaultSecret(response.getValue().toObject(SecretBundle.class))); }, SecretAsyncClient::mapGetSecretException); } @@ -394,7 +433,11 @@ public Response getSecretWithResponse(String name, String versio */ @ServiceMethod(returns = ReturnType.SINGLE) public SecretProperties updateSecretProperties(SecretProperties secretProperties) { - return updateSecretPropertiesWithResponse(secretProperties, Context.NONE).getValue(); + return createSecretProperties(implClient + .updateSecretWithResponse(secretProperties.getName(), secretProperties.getVersion(), + BinaryData.fromObject(prepareUpdateSecretParameters(secretProperties)), EMPTY_OPTIONS) + .getValue() + .toObject(SecretBundle.class)); } /** @@ -433,10 +476,24 @@ public SecretProperties updateSecretProperties(SecretProperties secretProperties @ServiceMethod(returns = ReturnType.SINGLE) public Response updateSecretPropertiesWithResponse(SecretProperties secretProperties, Context context) { - Response response = implClient.updateSecretWithResponse(vaultUrl, secretProperties.getName(), - secretProperties.getVersion(), secretProperties.getContentType(), createSecretAttributes(secretProperties), - secretProperties.getTags(), context); - return new SimpleResponse<>(response, createSecretProperties(response.getValue())); + + Response response = implClient.updateSecretWithResponse(secretProperties.getName(), + secretProperties.getVersion(), BinaryData.fromObject(prepareUpdateSecretParameters(secretProperties)), + new RequestOptions().setContext(context)); + + return new SimpleResponse<>(response, createSecretProperties(response.getValue().toObject(SecretBundle.class))); + } + + static SecretUpdateParameters prepareUpdateSecretParameters(SecretProperties secretProperties) { + SecretUpdateParameters secretUpdateParameters = new SecretUpdateParameters(); + + if (secretProperties != null) { + secretUpdateParameters.setTags(secretProperties.getTags()) + .setContentType(secretProperties.getContentType()) + .setSecretAttributes(createSecretAttributes(secretProperties)); + } + + return secretUpdateParameters; } /** @@ -479,19 +536,19 @@ public SyncPoller beginDeleteSecret(String name) { private Function, PollResponse> deleteActivationOperation(String name) { - return pollingContext -> callWithMappedException( - () -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, - createDeletedSecret(implClient.deleteSecret(vaultUrl, name))), - SecretAsyncClient::mapDeleteSecretException); + return pollingContext -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, createDeletedSecret( + implClient.deleteSecretWithResponse(name, EMPTY_OPTIONS).getValue().toObject(DeletedSecretBundle.class))); } private Function, PollResponse> deletePollOperation(String name) { return pollingContext -> { try { return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, - createDeletedSecret(implClient.getDeletedSecret(vaultUrl, name))); - } catch (HttpResponseException ex) { - if (ex.getResponse().getStatusCode() == 404) { + createDeletedSecret(implClient.getDeletedSecretWithResponse(name, EMPTY_OPTIONS) + .getValue() + .toObject(DeletedSecretBundle.class))); + } catch (HttpResponseException e) { + if (e.getResponse().getStatusCode() == 404) { return new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()); } else { @@ -501,7 +558,7 @@ private Function, PollResponse> del return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } - } catch (Exception ex) { + } catch (Exception e) { // This means either vault has soft-delete disabled or permission is not granted for the get deleted // key operation. In both cases deletion operation was successful when activation operation // succeeded before reaching here. @@ -532,7 +589,9 @@ private Function, PollResponse> del */ @ServiceMethod(returns = ReturnType.SINGLE) public DeletedSecret getDeletedSecret(String name) { - return getDeletedSecretWithResponse(name, Context.NONE).getValue(); + return createDeletedSecret(implClient.getDeletedSecretWithResponse(name, EMPTY_OPTIONS) + .getValue() + .toObject(DeletedSecretBundle.class)); } /** @@ -559,10 +618,11 @@ public DeletedSecret getDeletedSecret(String name) { */ @ServiceMethod(returns = ReturnType.SINGLE) public Response getDeletedSecretWithResponse(String name, Context context) { - return callWithMappedException(() -> { - Response response = implClient.getDeletedSecretWithResponse(vaultUrl, name, context); - return new SimpleResponse<>(response, createDeletedSecret(response.getValue())); - }, SecretAsyncClient::mapGetDeletedSecretException); + Response response + = implClient.getDeletedSecretWithResponse(name, new RequestOptions().setContext(context)); + + return new SimpleResponse<>(response, + createDeletedSecret(response.getValue().toObject(DeletedSecretBundle.class))); } /** @@ -585,7 +645,7 @@ public Response getDeletedSecretWithResponse(String name, Context */ @ServiceMethod(returns = ReturnType.SINGLE) public void purgeDeletedSecret(String name) { - purgeDeletedSecretWithResponse(name, Context.NONE); + implClient.purgeDeletedSecretWithResponse(name, EMPTY_OPTIONS).getValue(); } /** @@ -611,8 +671,7 @@ public void purgeDeletedSecret(String name) { */ @ServiceMethod(returns = ReturnType.SINGLE) public Response purgeDeletedSecretWithResponse(String name, Context context) { - return callWithMappedException(() -> implClient.purgeDeletedSecretWithResponse(vaultUrl, name, context), - SecretAsyncClient::mapPurgeDeletedSecretException); + return implClient.purgeDeletedSecretWithResponse(name, new RequestOptions().setContext(context)); } /** @@ -650,19 +709,18 @@ public SyncPoller beginRecoverDeletedSecret(String name) { private Function, PollResponse> recoverActivationOperation(String name) { - return pollingContext -> callWithMappedException( - () -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, - createKeyVaultSecret(implClient.recoverDeletedSecret(vaultUrl, name))), - SecretAsyncClient::mapRecoverDeletedSecretException); + + return pollingContext -> new PollResponse<>(LongRunningOperationStatus.NOT_STARTED, createKeyVaultSecret( + implClient.recoverDeletedSecretWithResponse(name, EMPTY_OPTIONS).getValue().toObject(SecretBundle.class))); } private Function, PollResponse> recoverPollOperation(String name) { return pollingContext -> { try { - return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, - createKeyVaultSecret(implClient.getSecret(vaultUrl, name, null))); - } catch (HttpResponseException ex) { - if (ex.getResponse().getStatusCode() == 404) { + return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, createKeyVaultSecret( + implClient.getSecretWithResponse(name, "", EMPTY_OPTIONS).getValue().toObject(SecretBundle.class))); + } catch (HttpResponseException e) { + if (e.getResponse().getStatusCode() == 404) { return new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, pollingContext.getLatestResponse().getValue()); } else { @@ -671,7 +729,7 @@ private Function, PollResponse> r return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollingContext.getLatestResponse().getValue()); } - } catch (Exception ex) { + } catch (Exception e) { // This means permission is not granted for the get deleted key operation. In both cases the // deletion operation was successful when activation operation succeeded before reaching here. return new PollResponse<>(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, @@ -701,7 +759,10 @@ private Function, PollResponse> r */ @ServiceMethod(returns = ReturnType.SINGLE) public byte[] backupSecret(String name) { - return backupSecretWithResponse(name, Context.NONE).getValue(); + return implClient.backupSecretWithResponse(name, EMPTY_OPTIONS) + .getValue() + .toObject(BackupSecretResult.class) + .getValue(); } /** @@ -728,10 +789,10 @@ public byte[] backupSecret(String name) { */ @ServiceMethod(returns = ReturnType.SINGLE) public Response backupSecretWithResponse(String name, Context context) { - return callWithMappedException(() -> { - Response response = implClient.backupSecretWithResponse(vaultUrl, name, context); - return new SimpleResponse<>(response, response.getValue().getValue()); - }, SecretAsyncClient::mapBackupSecretException); + Response response + = implClient.backupSecretWithResponse(name, new RequestOptions().setContext(context)); + + return new SimpleResponse<>(response, response.getValue().toBytes()); } /** @@ -759,7 +820,10 @@ public Response backupSecretWithResponse(String name, Context context) { */ @ServiceMethod(returns = ReturnType.SINGLE) public KeyVaultSecret restoreSecretBackup(byte[] backup) { - return restoreSecretBackupWithResponse(backup, Context.NONE).getValue(); + return callWithMappedException(() -> createKeyVaultSecret(implClient + .restoreSecretWithResponse(BinaryData.fromObject(new SecretRestoreParameters(backup)), EMPTY_OPTIONS) + .getValue() + .toObject(SecretBundle.class)), SecretAsyncClient::mapRestoreSecretException); } /** @@ -790,8 +854,11 @@ public KeyVaultSecret restoreSecretBackup(byte[] backup) { @ServiceMethod(returns = ReturnType.SINGLE) public Response restoreSecretBackupWithResponse(byte[] backup, Context context) { return callWithMappedException(() -> { - Response response = implClient.restoreSecretWithResponse(vaultUrl, backup, context); - return new SimpleResponse<>(response, createKeyVaultSecret(response.getValue())); + Response response = implClient.restoreSecretWithResponse( + BinaryData.fromObject(new SecretRestoreParameters(backup)), new RequestOptions().setContext(context)); + + return new SimpleResponse<>(response, + createKeyVaultSecret(response.getValue().toObject(SecretBundle.class))); }, SecretAsyncClient::mapRestoreSecretException); } @@ -839,7 +906,8 @@ public Response restoreSecretBackupWithResponse(byte[] backup, C */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable listPropertiesOfSecrets() { - return listPropertiesOfSecrets(Context.NONE); + return implClient.getSecrets(EMPTY_OPTIONS) + .mapPage(binaryData -> createSecretProperties(binaryData.toObject(SecretItem.class))); } /** @@ -867,10 +935,8 @@ public PagedIterable listPropertiesOfSecrets() { */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable listPropertiesOfSecrets(Context context) { - return new PagedIterable<>( - maxResults -> mapSecretItemPage(implClient.getSecretsSinglePage(vaultUrl, maxResults, context)), - (continuationToken, maxResults) -> mapSecretItemPage( - implClient.getSecretsNextSinglePage(continuationToken, vaultUrl, context))); + return implClient.getSecrets(new RequestOptions().setContext(context)) + .mapPage(binaryData -> createSecretProperties(binaryData.toObject(SecretItem.class))); } /** @@ -906,7 +972,8 @@ public PagedIterable listPropertiesOfSecrets(Context context) */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable listDeletedSecrets() { - return listDeletedSecrets(Context.NONE); + return implClient.getDeletedSecrets(EMPTY_OPTIONS) + .mapPage(binaryData -> createDeletedSecret(binaryData.toObject(DeletedSecretItem.class))); } /** @@ -928,11 +995,8 @@ public PagedIterable listDeletedSecrets() { */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable listDeletedSecrets(Context context) { - return new PagedIterable<>( - maxResults -> mapDeletedSecretItemPage( - implClient.getDeletedSecretsSinglePage(vaultUrl, maxResults, context)), - (continuationToken, maxResults) -> mapDeletedSecretItemPage( - implClient.getDeletedSecretsNextSinglePage(continuationToken, vaultUrl, context))); + return implClient.getDeletedSecrets(new RequestOptions().setContext(context)) + .mapPage(binaryData -> createDeletedSecret(binaryData.toObject(DeletedSecretItem.class))); } /** @@ -962,7 +1026,8 @@ public PagedIterable listDeletedSecrets(Context context) { */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable listPropertiesOfSecretVersions(String name) { - return listPropertiesOfSecretVersions(name, Context.NONE); + return implClient.getSecretVersions(name, EMPTY_OPTIONS) + .mapPage(binaryData -> createSecretProperties(binaryData.toObject(SecretItem.class))); } /** @@ -1014,19 +1079,17 @@ public PagedIterable listPropertiesOfSecretVersions(String nam */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable listPropertiesOfSecretVersions(String name, Context context) { - return new PagedIterable<>( - maxResults -> mapSecretItemPage( - implClient.getSecretVersionsSinglePage(vaultUrl, name, maxResults, context)), - (continuationToken, maxResults) -> mapSecretItemPage( - implClient.getSecretVersionsNextSinglePage(continuationToken, vaultUrl, context))); + return implClient.getSecretVersions(name, new RequestOptions().setContext(context)) + .mapPage(binaryData -> createSecretProperties(binaryData.toObject(SecretItem.class))); } private static T callWithMappedException(Supplier call, - Function exceptionMapper) { + Function exceptionMapper) { + try { return call.get(); - } catch (KeyVaultErrorException ex) { - throw exceptionMapper.apply(ex); + } catch (HttpResponseException e) { + throw exceptionMapper.apply(e); } } } diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretClientBuilder.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretClientBuilder.java index 5c163cb2819b..1f618c835548 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretClientBuilder.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretClientBuilder.java @@ -114,6 +114,7 @@ public final class SecretClientBuilder implements TokenCredentialTrait properties; private TokenCredential credential; private HttpPipeline pipeline; + private HttpPipeline builtPipeline; private String vaultUrl; private HttpClient httpClient; private HttpLogOptions httpLogOptions; @@ -153,7 +154,7 @@ public SecretClientBuilder() { * and {@link #retryPolicy(RetryPolicy)} have been set. */ public SecretClient buildClient() { - return new SecretClient(buildInnerClient(), vaultUrl); + return new SecretClient(getClientImpl(), vaultUrl); } /** @@ -175,10 +176,10 @@ public SecretClient buildClient() { * and {@link #retryPolicy(RetryPolicy)} have been set. */ public SecretAsyncClient buildAsyncClient() { - return new SecretAsyncClient(buildInnerClient(), vaultUrl); + return new SecretAsyncClient(getClientImpl(), vaultUrl); } - private SecretClientImpl buildInnerClient() { + private SecretClientImpl getClientImpl() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; String buildEndpoint = getBuildEndpoint(buildConfiguration); @@ -188,10 +189,12 @@ private SecretClientImpl buildInnerClient() { .logExceptionAsError(new IllegalStateException(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED)); } - SecretServiceVersion serviceVersion = version != null ? version : SecretServiceVersion.getLatest(); + if (version == null) { + version = SecretServiceVersion.getLatest(); + } if (pipeline != null) { - return new SecretClientImpl(pipeline, serviceVersion.getVersion()); + return new SecretClientImpl(pipeline, vaultUrl, version); } if (credential == null) { @@ -235,13 +238,13 @@ private SecretClientImpl buildInnerClient() { Tracer tracer = TracerProvider.getDefaultProvider() .createTracer(clientName, clientVersion, KEYVAULT_TRACING_NAMESPACE_VALUE, tracingOptions); - HttpPipeline pipeline = new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) + builtPipeline = new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .clientOptions(localClientOptions) .tracer(tracer) .build(); - return new SecretClientImpl(pipeline, serviceVersion.getVersion()); + return new SecretClientImpl(builtPipeline, vaultUrl, version); } /** @@ -514,4 +517,9 @@ private String getBuildEndpoint(Configuration configuration) { return null; } } + + // For testing purposes + HttpPipeline getPipelineForTest() { + return pipeline != null ? pipeline : builtPipeline; + } } diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/DeletedSecretHelper.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/DeletedSecretHelper.java index 85ddb89acc21..4bc086f7b104 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/DeletedSecretHelper.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/DeletedSecretHelper.java @@ -10,6 +10,24 @@ public final class DeletedSecretHelper { private static DeletedSecretAccessor accessor; public interface DeletedSecretAccessor { + void setId(DeletedSecret properties, String id); + + void setVersion(DeletedSecret properties, String version); + + void setCreatedOn(DeletedSecret properties, OffsetDateTime createdOn); + + void setUpdatedOn(DeletedSecret properties, OffsetDateTime updatedOn); + + void setName(DeletedSecret properties, String name); + + void setRecoveryLevel(DeletedSecret properties, String recoveryLevel); + + void setKeyId(DeletedSecret properties, String keyId); + + void setManaged(DeletedSecret properties, Boolean managed); + + void setRecoverableDays(DeletedSecret properties, Integer recoverableDays); + void setRecoveryId(DeletedSecret deletedSecret, String recoveryId); void setScheduledPurgeDate(DeletedSecret deletedSecret, OffsetDateTime scheduledPurgeDate); @@ -17,6 +35,87 @@ public interface DeletedSecretAccessor { void setDeletedOn(DeletedSecret deletedSecret, OffsetDateTime deletedOn); } + public static void setId(DeletedSecret deletedSecret, String id) { + if (accessor == null) { + new DeletedSecret(); + } + + assert accessor != null; + accessor.setId(deletedSecret, id); + } + + public static void setVersion(DeletedSecret deletedSecret, String version) { + if (accessor == null) { + new DeletedSecret(); + } + + assert accessor != null; + accessor.setVersion(deletedSecret, version); + } + + public static void setCreatedOn(DeletedSecret deletedSecret, OffsetDateTime createdOn) { + if (accessor == null) { + new DeletedSecret(); + } + + assert accessor != null; + accessor.setCreatedOn(deletedSecret, createdOn); + } + + public static void setUpdatedOn(DeletedSecret deletedSecret, OffsetDateTime updatedOn) { + if (accessor == null) { + new DeletedSecret(); + } + + assert accessor != null; + accessor.setUpdatedOn(deletedSecret, updatedOn); + } + + public static void setName(DeletedSecret deletedSecret, String name) { + if (accessor == null) { + new DeletedSecret(); + } + + assert accessor != null; + accessor.setName(deletedSecret, name); + } + + public static void setRecoveryLevel(DeletedSecret deletedSecret, String recoveryLevel) { + if (accessor == null) { + new DeletedSecret(); + } + + assert accessor != null; + accessor.setRecoveryLevel(deletedSecret, recoveryLevel); + } + + public static void setKeyId(DeletedSecret deletedSecret, String keyId) { + if (accessor == null) { + new DeletedSecret(); + } + + assert accessor != null; + accessor.setKeyId(deletedSecret, keyId); + } + + public static void setManaged(DeletedSecret deletedSecret, Boolean managed) { + if (accessor == null) { + new DeletedSecret(); + } + + assert accessor != null; + accessor.setManaged(deletedSecret, managed); + } + + public static void setRecoverableDays(DeletedSecret deletedSecret, Integer recoverableDays) { + if (accessor == null) { + new DeletedSecret(); + } + + assert accessor != null; + accessor.setRecoverableDays(deletedSecret, recoverableDays); + } + public static void setRecoveryId(DeletedSecret deletedSecret, String recoveryId) { if (accessor == null) { new DeletedSecret(); diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/SecretClientImpl.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/SecretClientImpl.java index aaeaf37c2278..1563bba24bb7 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/SecretClientImpl.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/SecretClientImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.secrets.implementation; @@ -20,6 +20,10 @@ import com.azure.core.annotation.ServiceInterface; import com.azure.core.annotation.ServiceMethod; import com.azure.core.annotation.UnexpectedResponseExceptionType; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; import com.azure.core.http.HttpPipeline; import com.azure.core.http.HttpPipelineBuilder; import com.azure.core.http.policy.RetryPolicy; @@ -28,25 +32,18 @@ import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.PagedResponse; import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.RequestOptions; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.RestProxy; +import com.azure.core.util.BinaryData; import com.azure.core.util.Context; import com.azure.core.util.FluxUtil; import com.azure.core.util.serializer.JacksonAdapter; import com.azure.core.util.serializer.SerializerAdapter; -import com.azure.security.keyvault.secrets.implementation.models.BackupSecretResult; -import com.azure.security.keyvault.secrets.implementation.models.DeletedSecretBundle; -import com.azure.security.keyvault.secrets.implementation.models.DeletedSecretItem; -import com.azure.security.keyvault.secrets.implementation.models.DeletedSecretListResult; -import com.azure.security.keyvault.secrets.implementation.models.KeyVaultErrorException; -import com.azure.security.keyvault.secrets.implementation.models.SecretAttributes; -import com.azure.security.keyvault.secrets.implementation.models.SecretBundle; -import com.azure.security.keyvault.secrets.implementation.models.SecretItem; -import com.azure.security.keyvault.secrets.implementation.models.SecretListResult; -import com.azure.security.keyvault.secrets.implementation.models.SecretRestoreParameters; -import com.azure.security.keyvault.secrets.implementation.models.SecretSetParameters; -import com.azure.security.keyvault.secrets.implementation.models.SecretUpdateParameters; +import com.azure.security.keyvault.secrets.SecretServiceVersion; +import java.util.List; import java.util.Map; +import java.util.stream.Collectors; import reactor.core.publisher.Mono; /** @@ -59,17 +56,30 @@ public final class SecretClientImpl { private final SecretClientService service; /** - * Api Version. */ - private final String apiVersion; + private final String vaultBaseUrl; /** - * Gets Api Version. + * Gets. * - * @return the apiVersion value. + * @return the vaultBaseUrl value. */ - public String getApiVersion() { - return this.apiVersion; + public String getVaultBaseUrl() { + return this.vaultBaseUrl; + } + + /** + * Service version. + */ + private final SecretServiceVersion serviceVersion; + + /** + * Gets Service version. + * + * @return the serviceVersion value. + */ + public SecretServiceVersion getServiceVersion() { + return this.serviceVersion; } /** @@ -103,21 +113,23 @@ public SerializerAdapter getSerializerAdapter() { /** * Initializes an instance of SecretClient client. * - * @param apiVersion Api Version. + * @param vaultBaseUrl + * @param serviceVersion Service version. */ - public SecretClientImpl(String apiVersion) { + public SecretClientImpl(String vaultBaseUrl, SecretServiceVersion serviceVersion) { this(new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build(), - JacksonAdapter.createDefaultSerializerAdapter(), apiVersion); + JacksonAdapter.createDefaultSerializerAdapter(), vaultBaseUrl, serviceVersion); } /** * Initializes an instance of SecretClient client. * * @param httpPipeline The HTTP pipeline to send requests through. - * @param apiVersion Api Version. + * @param vaultBaseUrl + * @param serviceVersion Service version. */ - public SecretClientImpl(HttpPipeline httpPipeline, String apiVersion) { - this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), apiVersion); + public SecretClientImpl(HttpPipeline httpPipeline, String vaultBaseUrl, SecretServiceVersion serviceVersion) { + this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), vaultBaseUrl, serviceVersion); } /** @@ -125,12 +137,15 @@ public SecretClientImpl(HttpPipeline httpPipeline, String apiVersion) { * * @param httpPipeline The HTTP pipeline to send requests through. * @param serializerAdapter The serializer to serialize an object into a string. - * @param apiVersion Api Version. + * @param vaultBaseUrl + * @param serviceVersion Service version. */ - public SecretClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String apiVersion) { + public SecretClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String vaultBaseUrl, + SecretServiceVersion serviceVersion) { this.httpPipeline = httpPipeline; this.serializerAdapter = serializerAdapter; - this.apiVersion = apiVersion; + this.vaultBaseUrl = vaultBaseUrl; + this.serviceVersion = serviceVersion; this.service = RestProxy.create(SecretClientService.class, this.httpPipeline, this.getSerializerAdapter()); } @@ -142,245 +157,313 @@ public SecretClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerA public interface SecretClientService { @Put("/secrets/{secret-name}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> setSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") SecretSetParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> setSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("secret-name") String secretName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData parameters, RequestOptions requestOptions, Context context); @Put("/secrets/{secret-name}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response setSecretSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") SecretSetParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response setSecretSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("secret-name") String secretName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData parameters, RequestOptions requestOptions, Context context); @Delete("/secrets/{secret-name}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> deleteSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> deleteSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("secret-name") String secretName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Delete("/secrets/{secret-name}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response deleteSecretSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response deleteSecretSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("secret-name") String secretName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Patch("/secrets/{secret-name}/{secret-version}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> updateSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @PathParam("secret-version") String secretVersion, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") SecretUpdateParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> updateSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("secret-name") String secretName, + @PathParam("secret-version") String secretVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Patch("/secrets/{secret-name}/{secret-version}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response updateSecretSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @PathParam("secret-version") String secretVersion, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") SecretUpdateParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response updateSecretSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("secret-name") String secretName, + @PathParam("secret-version") String secretVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Get("/secrets/{secret-name}/{secret-version}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @PathParam("secret-version") String secretVersion, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("secret-name") String secretName, + @PathParam("secret-version") String secretVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("/secrets/{secret-name}/{secret-version}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getSecretSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @PathParam("secret-version") String secretVersion, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getSecretSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("secret-name") String secretName, + @PathParam("secret-version") String secretVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("/secrets") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getSecrets(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("maxresults") Integer maxresults, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getSecrets(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("/secrets") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getSecretsSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("maxresults") Integer maxresults, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getSecretsSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("/secrets/{secret-name}/versions") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getSecretVersions(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("maxresults") Integer maxresults, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getSecretVersions(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("secret-name") String secretName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Get("/secrets/{secret-name}/versions") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getSecretVersionsSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("maxresults") Integer maxresults, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getSecretVersionsSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("secret-name") String secretName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Get("/deletedsecrets") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getDeletedSecrets(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("maxresults") Integer maxresults, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getDeletedSecrets(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("/deletedsecrets") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getDeletedSecretsSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("maxresults") Integer maxresults, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getDeletedSecretsSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("/deletedsecrets/{secret-name}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getDeletedSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getDeletedSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("secret-name") String secretName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Get("/deletedsecrets/{secret-name}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getDeletedSecretSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getDeletedSecretSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("secret-name") String secretName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Delete("/deletedsecrets/{secret-name}") @ExpectedResponses({ 204 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) Mono> purgeDeletedSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @QueryParam("api-version") String apiVersion, @PathParam("secret-name") String secretName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Delete("/deletedsecrets/{secret-name}") @ExpectedResponses({ 204 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) Response purgeDeletedSecretSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @QueryParam("api-version") String apiVersion, @PathParam("secret-name") String secretName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Post("/deletedsecrets/{secret-name}/recover") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> recoverDeletedSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> recoverDeletedSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("secret-name") String secretName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Post("/deletedsecrets/{secret-name}/recover") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response recoverDeletedSecretSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response recoverDeletedSecretSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("secret-name") String secretName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Post("/secrets/{secret-name}/backup") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> backupSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> backupSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("secret-name") String secretName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Post("/secrets/{secret-name}/backup") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response backupSecretSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @PathParam("secret-name") String secretName, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response backupSecretSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @PathParam("secret-name") String secretName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); @Post("/secrets/restore") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> restoreSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") SecretRestoreParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> restoreSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Post("/secrets/restore") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response restoreSecretSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") SecretRestoreParameters parameters, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response restoreSecretSync(@HostParam("vaultBaseUrl") String vaultBaseUrl, + @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData parameters, + RequestOptions requestOptions, Context context); @Get("{nextLink}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getSecretsNext(@PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getSecretsNext(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("{nextLink}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getSecretsNextSync(@PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getSecretsNextSync(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("{nextLink}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getSecretVersionsNext( - @PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getSecretVersionsNext(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("{nextLink}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getSecretVersionsNextSync( - @PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getSecretVersionsNextSync(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("{nextLink}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Mono> getDeletedSecretsNext( - @PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getDeletedSecretsNext(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); @Get("{nextLink}") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(KeyVaultErrorException.class) - Response getDeletedSecretsNextSync( - @PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, Context context); - } - - /** - * Sets a secret in a specified key vault. - * - * The SET operation adds a secret to the Azure Key Vault. If the named secret already exists, Azure Key Vault - * creates a new version of that secret. This operation requires the secrets/set permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. The value you provide may be copied globally for the purpose of running - * the service. The value provided should not include personally identifiable or sensitive information. - * @param value The value of the secret. - * @param tags Application specific metadata in the form of key-value pairs. - * @param secretContentType Type of the secret value such as a password. - * @param secretAttributes The secret management attributes. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> setSecretWithResponseAsync(String vaultBaseUrl, String secretName, String value, - Map tags, String secretContentType, SecretAttributes secretAttributes) { - return FluxUtil.withContext(context -> setSecretWithResponseAsync(vaultBaseUrl, secretName, value, tags, - secretContentType, secretAttributes, context)); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getDeletedSecretsNextSync(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("vaultBaseUrl") String vaultBaseUrl, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); } /** @@ -388,82 +471,74 @@ public Mono> setSecretWithResponseAsync(String vaultBaseU * * The SET operation adds a secret to the Azure Key Vault. If the named secret already exists, Azure Key Vault * creates a new version of that secret. This operation requires the secrets/set permission. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: String (Required)
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: String (Optional)
          +     *     id: String (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     kid: String (Optional)
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretName The name of the secret. The value you provide may be copied globally for the purpose of running * the service. The value provided should not include personally identifiable or sensitive information. - * @param value The value of the secret. - * @param tags Application specific metadata in the form of key-value pairs. - * @param secretContentType Type of the secret value such as a password. - * @param secretAttributes The secret management attributes. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param parameters The parameters for setting the secret. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a secret consisting of a value, id and its attributes along with {@link Response} on successful * completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> setSecretWithResponseAsync(String vaultBaseUrl, String secretName, String value, - Map tags, String secretContentType, SecretAttributes secretAttributes, Context context) { + public Mono> setSecretWithResponseAsync(String secretName, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - SecretSetParameters parameters = new SecretSetParameters(); - parameters.setValue(value); - parameters.setTags(tags); - parameters.setSecretContentType(secretContentType); - parameters.setSecretAttributes(secretAttributes); - return service.setSecret(vaultBaseUrl, secretName, this.getApiVersion(), parameters, accept, context); - } - - /** - * Sets a secret in a specified key vault. - * - * The SET operation adds a secret to the Azure Key Vault. If the named secret already exists, Azure Key Vault - * creates a new version of that secret. This operation requires the secrets/set permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. The value you provide may be copied globally for the purpose of running - * the service. The value provided should not include personally identifiable or sensitive information. - * @param value The value of the secret. - * @param tags Application specific metadata in the form of key-value pairs. - * @param secretContentType Type of the secret value such as a password. - * @param secretAttributes The secret management attributes. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono setSecretAsync(String vaultBaseUrl, String secretName, String value, - Map tags, String secretContentType, SecretAttributes secretAttributes) { - return setSecretWithResponseAsync(vaultBaseUrl, secretName, value, tags, secretContentType, secretAttributes) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Sets a secret in a specified key vault. - * - * The SET operation adds a secret to the Azure Key Vault. If the named secret already exists, Azure Key Vault - * creates a new version of that secret. This operation requires the secrets/set permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. The value you provide may be copied globally for the purpose of running - * the service. The value provided should not include personally identifiable or sensitive information. - * @param value The value of the secret. - * @param tags Application specific metadata in the form of key-value pairs. - * @param secretContentType Type of the secret value such as a password. - * @param secretAttributes The secret management attributes. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono setSecretAsync(String vaultBaseUrl, String secretName, String value, - Map tags, String secretContentType, SecretAttributes secretAttributes, Context context) { - return setSecretWithResponseAsync(vaultBaseUrl, secretName, value, tags, secretContentType, secretAttributes, - context).flatMap(res -> Mono.justOrEmpty(res.getValue())); + return FluxUtil + .withContext(context -> service.setSecret(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + secretName, contentType, accept, parameters, requestOptions, context)); } /** @@ -471,74 +546,72 @@ public Mono setSecretAsync(String vaultBaseUrl, String secretName, * * The SET operation adds a secret to the Azure Key Vault. If the named secret already exists, Azure Key Vault * creates a new version of that secret. This operation requires the secrets/set permission. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: String (Required)
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: String (Optional)
          +     *     id: String (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     kid: String (Optional)
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretName The name of the secret. The value you provide may be copied globally for the purpose of running * the service. The value provided should not include personally identifiable or sensitive information. - * @param value The value of the secret. - * @param tags Application specific metadata in the form of key-value pairs. - * @param secretContentType Type of the secret value such as a password. - * @param secretAttributes The secret management attributes. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param parameters The parameters for setting the secret. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a secret consisting of a value, id and its attributes along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response setSecretWithResponse(String vaultBaseUrl, String secretName, String value, - Map tags, String secretContentType, SecretAttributes secretAttributes, Context context) { + public Response setSecretWithResponse(String secretName, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - SecretSetParameters parameters = new SecretSetParameters(); - parameters.setValue(value); - parameters.setTags(tags); - parameters.setSecretContentType(secretContentType); - parameters.setSecretAttributes(secretAttributes); - return service.setSecretSync(vaultBaseUrl, secretName, this.getApiVersion(), parameters, accept, context); - } - - /** - * Sets a secret in a specified key vault. - * - * The SET operation adds a secret to the Azure Key Vault. If the named secret already exists, Azure Key Vault - * creates a new version of that secret. This operation requires the secrets/set permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. The value you provide may be copied globally for the purpose of running - * the service. The value provided should not include personally identifiable or sensitive information. - * @param value The value of the secret. - * @param tags Application specific metadata in the form of key-value pairs. - * @param secretContentType Type of the secret value such as a password. - * @param secretAttributes The secret management attributes. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SecretBundle setSecret(String vaultBaseUrl, String secretName, String value, Map tags, - String secretContentType, SecretAttributes secretAttributes) { - return setSecretWithResponse(vaultBaseUrl, secretName, value, tags, secretContentType, secretAttributes, - Context.NONE).getValue(); - } - - /** - * Deletes a secret from a specified key vault. - * - * The DELETE operation applies to any secret stored in Azure Key Vault. DELETE cannot be applied to an individual - * version of a secret. This operation requires the secrets/delete permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Secret consisting of its previous id, attributes and its tags, as well as information on when - * it will be purged along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteSecretWithResponseAsync(String vaultBaseUrl, String secretName) { - return FluxUtil.withContext(context -> deleteSecretWithResponseAsync(vaultBaseUrl, secretName, context)); + return service.setSecretSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), secretName, + contentType, accept, parameters, requestOptions, Context.NONE); } /** @@ -546,61 +619,49 @@ public Mono> deleteSecretWithResponseAsync(String * * The DELETE operation applies to any secret stored in Azure Key Vault. DELETE cannot be applied to an individual * version of a secret. This operation requires the secrets/delete permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: String (Optional)
          +     *     id: String (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     kid: String (Optional)
          +     *     managed: Boolean (Optional)
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretName The name of the secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a Deleted Secret consisting of its previous id, attributes and its tags, as well as information on when * it will be purged along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteSecretWithResponseAsync(String vaultBaseUrl, String secretName, - Context context) { + public Mono> deleteSecretWithResponseAsync(String secretName, RequestOptions requestOptions) { final String accept = "application/json"; - return service.deleteSecret(vaultBaseUrl, secretName, this.getApiVersion(), accept, context); - } - - /** - * Deletes a secret from a specified key vault. - * - * The DELETE operation applies to any secret stored in Azure Key Vault. DELETE cannot be applied to an individual - * version of a secret. This operation requires the secrets/delete permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Secret consisting of its previous id, attributes and its tags, as well as information on when - * it will be purged on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteSecretAsync(String vaultBaseUrl, String secretName) { - return deleteSecretWithResponseAsync(vaultBaseUrl, secretName).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Deletes a secret from a specified key vault. - * - * The DELETE operation applies to any secret stored in Azure Key Vault. DELETE cannot be applied to an individual - * version of a secret. This operation requires the secrets/delete permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Secret consisting of its previous id, attributes and its tags, as well as information on when - * it will be purged on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteSecretAsync(String vaultBaseUrl, String secretName, Context context) { - return deleteSecretWithResponseAsync(vaultBaseUrl, secretName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + return FluxUtil.withContext(context -> service.deleteSecret(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), secretName, accept, requestOptions, context)); } /** @@ -608,66 +669,49 @@ public Mono deleteSecretAsync(String vaultBaseUrl, String s * * The DELETE operation applies to any secret stored in Azure Key Vault. DELETE cannot be applied to an individual * version of a secret. This operation requires the secrets/delete permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: String (Optional)
          +     *     id: String (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     kid: String (Optional)
          +     *     managed: Boolean (Optional)
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretName The name of the secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a Deleted Secret consisting of its previous id, attributes and its tags, as well as information on when * it will be purged along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteSecretWithResponse(String vaultBaseUrl, String secretName, - Context context) { + public Response deleteSecretWithResponse(String secretName, RequestOptions requestOptions) { final String accept = "application/json"; - return service.deleteSecretSync(vaultBaseUrl, secretName, this.getApiVersion(), accept, context); - } - - /** - * Deletes a secret from a specified key vault. - * - * The DELETE operation applies to any secret stored in Azure Key Vault. DELETE cannot be applied to an individual - * version of a secret. This operation requires the secrets/delete permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Secret consisting of its previous id, attributes and its tags, as well as information on when - * it will be purged. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public DeletedSecretBundle deleteSecret(String vaultBaseUrl, String secretName) { - return deleteSecretWithResponse(vaultBaseUrl, secretName, Context.NONE).getValue(); - } - - /** - * Updates the attributes associated with a specified secret in a given key vault. - * - * The UPDATE operation changes specified attributes of an existing stored secret. Attributes that are not specified - * in the request are left unchanged. The value of a secret itself cannot be changed. This operation requires the - * secrets/set permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param secretVersion The version of the secret. - * @param secretContentType Type of the secret value such as a password. - * @param secretAttributes The secret management attributes. - * @param tags Application specific metadata in the form of key-value pairs. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> updateSecretWithResponseAsync(String vaultBaseUrl, String secretName, - String secretVersion, String secretContentType, SecretAttributes secretAttributes, Map tags) { - return FluxUtil.withContext(context -> updateSecretWithResponseAsync(vaultBaseUrl, secretName, secretVersion, - secretContentType, secretAttributes, tags, context)); + return service.deleteSecretSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), secretName, + accept, requestOptions, Context.NONE); } /** @@ -676,82 +720,73 @@ public Mono> updateSecretWithResponseAsync(String vaultBa * The UPDATE operation changes specified attributes of an existing stored secret. Attributes that are not specified * in the request are left unchanged. The value of a secret itself cannot be changed. This operation requires the * secrets/set permission. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: String (Optional)
          +     *     id: String (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     kid: String (Optional)
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretName The name of the secret. * @param secretVersion The version of the secret. - * @param secretContentType Type of the secret value such as a password. - * @param secretAttributes The secret management attributes. - * @param tags Application specific metadata in the form of key-value pairs. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param parameters The parameters for update secret operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a secret consisting of a value, id and its attributes along with {@link Response} on successful * completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> updateSecretWithResponseAsync(String vaultBaseUrl, String secretName, - String secretVersion, String secretContentType, SecretAttributes secretAttributes, Map tags, - Context context) { + public Mono> updateSecretWithResponseAsync(String secretName, String secretVersion, + BinaryData parameters, RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - SecretUpdateParameters parameters = new SecretUpdateParameters(); - parameters.setSecretContentType(secretContentType); - parameters.setSecretAttributes(secretAttributes); - parameters.setTags(tags); - return service.updateSecret(vaultBaseUrl, secretName, secretVersion, this.getApiVersion(), parameters, accept, - context); - } - - /** - * Updates the attributes associated with a specified secret in a given key vault. - * - * The UPDATE operation changes specified attributes of an existing stored secret. Attributes that are not specified - * in the request are left unchanged. The value of a secret itself cannot be changed. This operation requires the - * secrets/set permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param secretVersion The version of the secret. - * @param secretContentType Type of the secret value such as a password. - * @param secretAttributes The secret management attributes. - * @param tags Application specific metadata in the form of key-value pairs. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono updateSecretAsync(String vaultBaseUrl, String secretName, String secretVersion, - String secretContentType, SecretAttributes secretAttributes, Map tags) { - return updateSecretWithResponseAsync(vaultBaseUrl, secretName, secretVersion, secretContentType, - secretAttributes, tags).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Updates the attributes associated with a specified secret in a given key vault. - * - * The UPDATE operation changes specified attributes of an existing stored secret. Attributes that are not specified - * in the request are left unchanged. The value of a secret itself cannot be changed. This operation requires the - * secrets/set permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param secretVersion The version of the secret. - * @param secretContentType Type of the secret value such as a password. - * @param secretAttributes The secret management attributes. - * @param tags Application specific metadata in the form of key-value pairs. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono updateSecretAsync(String vaultBaseUrl, String secretName, String secretVersion, - String secretContentType, SecretAttributes secretAttributes, Map tags, Context context) { - return updateSecretWithResponseAsync(vaultBaseUrl, secretName, secretVersion, secretContentType, - secretAttributes, tags, context).flatMap(res -> Mono.justOrEmpty(res.getValue())); + return FluxUtil + .withContext(context -> service.updateSecret(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + secretName, secretVersion, contentType, accept, parameters, requestOptions, context)); } /** @@ -760,77 +795,71 @@ public Mono updateSecretAsync(String vaultBaseUrl, String secretNa * The UPDATE operation changes specified attributes of an existing stored secret. Attributes that are not specified * in the request are left unchanged. The value of a secret itself cannot be changed. This operation requires the * secrets/set permission. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: String (Optional)
          +     *     id: String (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     kid: String (Optional)
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretName The name of the secret. * @param secretVersion The version of the secret. - * @param secretContentType Type of the secret value such as a password. - * @param secretAttributes The secret management attributes. - * @param tags Application specific metadata in the form of key-value pairs. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param parameters The parameters for update secret operation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a secret consisting of a value, id and its attributes along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response updateSecretWithResponse(String vaultBaseUrl, String secretName, String secretVersion, - String secretContentType, SecretAttributes secretAttributes, Map tags, Context context) { + public Response updateSecretWithResponse(String secretName, String secretVersion, BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - SecretUpdateParameters parameters = new SecretUpdateParameters(); - parameters.setSecretContentType(secretContentType); - parameters.setSecretAttributes(secretAttributes); - parameters.setTags(tags); - return service.updateSecretSync(vaultBaseUrl, secretName, secretVersion, this.getApiVersion(), parameters, - accept, context); - } - - /** - * Updates the attributes associated with a specified secret in a given key vault. - * - * The UPDATE operation changes specified attributes of an existing stored secret. Attributes that are not specified - * in the request are left unchanged. The value of a secret itself cannot be changed. This operation requires the - * secrets/set permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param secretVersion The version of the secret. - * @param secretContentType Type of the secret value such as a password. - * @param secretAttributes The secret management attributes. - * @param tags Application specific metadata in the form of key-value pairs. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SecretBundle updateSecret(String vaultBaseUrl, String secretName, String secretVersion, - String secretContentType, SecretAttributes secretAttributes, Map tags) { - return updateSecretWithResponse(vaultBaseUrl, secretName, secretVersion, secretContentType, secretAttributes, - tags, Context.NONE).getValue(); - } - - /** - * Get a specified secret from a given key vault. - * - * The GET operation is applicable to any secret stored in Azure Key Vault. This operation requires the secrets/get - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param secretVersion The version of the secret. This URI fragment is optional. If not specified, the latest - * version of the secret is returned. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSecretWithResponseAsync(String vaultBaseUrl, String secretName, - String secretVersion) { - return FluxUtil - .withContext(context -> getSecretWithResponseAsync(vaultBaseUrl, secretName, secretVersion, context)); + return service.updateSecretSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), secretName, + secretVersion, contentType, accept, parameters, requestOptions, Context.NONE); } /** @@ -838,44 +867,51 @@ public Mono> getSecretWithResponseAsync(String vaultBaseU * * The GET operation is applicable to any secret stored in Azure Key Vault. This operation requires the secrets/get * permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: String (Optional)
          +     *     id: String (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     kid: String (Optional)
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretName The name of the secret. * @param secretVersion The version of the secret. This URI fragment is optional. If not specified, the latest * version of the secret is returned. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes along with {@link Response} on successful + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a specified secret from a given key vault. + * + * The GET operation is applicable to any secret stored in Azure Key Vault along with {@link Response} on successful * completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSecretWithResponseAsync(String vaultBaseUrl, String secretName, - String secretVersion, Context context) { + public Mono> getSecretWithResponseAsync(String secretName, String secretVersion, + RequestOptions requestOptions) { final String accept = "application/json"; - return service.getSecret(vaultBaseUrl, secretName, secretVersion, this.getApiVersion(), accept, context); - } - - /** - * Get a specified secret from a given key vault. - * - * The GET operation is applicable to any secret stored in Azure Key Vault. This operation requires the secrets/get - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param secretVersion The version of the secret. This URI fragment is optional. If not specified, the latest - * version of the secret is returned. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSecretAsync(String vaultBaseUrl, String secretName, String secretVersion) { - return getSecretWithResponseAsync(vaultBaseUrl, secretName, secretVersion) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + return FluxUtil.withContext(context -> service.getSecret(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), secretName, secretVersion, accept, requestOptions, context)); } /** @@ -883,65 +919,50 @@ public Mono getSecretAsync(String vaultBaseUrl, String secretName, * * The GET operation is applicable to any secret stored in Azure Key Vault. This operation requires the secrets/get * permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: String (Optional)
          +     *     id: String (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     kid: String (Optional)
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretName The name of the secret. * @param secretVersion The version of the secret. This URI fragment is optional. If not specified, the latest * version of the secret is returned. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSecretAsync(String vaultBaseUrl, String secretName, String secretVersion, - Context context) { - return getSecretWithResponseAsync(vaultBaseUrl, secretName, secretVersion, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Get a specified secret from a given key vault. - * - * The GET operation is applicable to any secret stored in Azure Key Vault. This operation requires the secrets/get - * permission. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a specified secret from a given key vault. * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param secretVersion The version of the secret. This URI fragment is optional. If not specified, the latest - * version of the secret is returned. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes along with {@link Response}. + * The GET operation is applicable to any secret stored in Azure Key Vault along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response getSecretWithResponse(String vaultBaseUrl, String secretName, String secretVersion, - Context context) { + public Response getSecretWithResponse(String secretName, String secretVersion, + RequestOptions requestOptions) { final String accept = "application/json"; - return service.getSecretSync(vaultBaseUrl, secretName, secretVersion, this.getApiVersion(), accept, context); - } - - /** - * Get a specified secret from a given key vault. - * - * The GET operation is applicable to any secret stored in Azure Key Vault. This operation requires the secrets/get - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param secretVersion The version of the secret. This URI fragment is optional. If not specified, the latest - * version of the secret is returned. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SecretBundle getSecret(String vaultBaseUrl, String secretName, String secretVersion) { - return getSecretWithResponse(vaultBaseUrl, secretName, secretVersion, Context.NONE).getValue(); + return service.getSecretSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), secretName, + secretVersion, accept, requestOptions, Context.NONE); } /** @@ -950,22 +971,53 @@ public SecretBundle getSecret(String vaultBaseUrl, String secretName, String sec * The Get Secrets operation is applicable to the entire vault. However, only the base secret identifier and its * attributes are provided in the response. Individual secret versions are not listed in the response. This * operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     contentType: String (Optional)
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the secret list result along with {@link PagedResponse} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSecretsSinglePageAsync(String vaultBaseUrl, Integer maxresults) { + private Mono> getSecretsSinglePageAsync(RequestOptions requestOptions) { final String accept = "application/json"; return FluxUtil - .withContext(context -> service.getSecrets(vaultBaseUrl, maxresults, this.getApiVersion(), accept, context)) + .withContext(context -> service.getSecrets(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + accept, requestOptions, context)) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } /** @@ -974,23 +1026,52 @@ public Mono> getSecretsSinglePageAsync(String vaultBas * The Get Secrets operation is applicable to the entire vault. However, only the base secret identifier and its * attributes are provided in the response. Individual secret versions are not listed in the response. This * operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result along with {@link PagedResponse} on successful completion of {@link Mono}. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     contentType: String (Optional)
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the secret list result as paginated response with {@link PagedFlux}. */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSecretsSinglePageAsync(String vaultBaseUrl, Integer maxresults, - Context context) { - final String accept = "application/json"; - return service.getSecrets(vaultBaseUrl, maxresults, this.getApiVersion(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux getSecretsAsync(RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedFlux<>(() -> getSecretsSinglePageAsync(requestOptions), + nextLink -> getSecretsNextSinglePageAsync(nextLink, requestOptionsForNextPage)); } /** @@ -999,19 +1080,52 @@ public Mono> getSecretsSinglePageAsync(String vaultBas * The Get Secrets operation is applicable to the entire vault. However, only the base secret identifier and its * attributes are provided in the response. Individual secret versions are not listed in the response. This * operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result as paginated response with {@link PagedFlux}. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     contentType: String (Optional)
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the secret list result along with {@link PagedResponse}. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getSecretsAsync(String vaultBaseUrl, Integer maxresults) { - return new PagedFlux<>(() -> getSecretsSinglePageAsync(vaultBaseUrl, maxresults), - nextLink -> getSecretsNextSinglePageAsync(nextLink, vaultBaseUrl)); + @ServiceMethod(returns = ReturnType.SINGLE) + private PagedResponse getSecretsSinglePage(RequestOptions requestOptions) { + final String accept = "application/json"; + Response res = service.getSecretsSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + accept, requestOptions, Context.NONE); + return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } /** @@ -1020,184 +1134,162 @@ public PagedFlux getSecretsAsync(String vaultBaseUrl, Integer maxres * The Get Secrets operation is applicable to the entire vault. However, only the base secret identifier and its * attributes are provided in the response. Individual secret versions are not listed in the response. This * operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result as paginated response with {@link PagedFlux}. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     contentType: String (Optional)
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the secret list result as paginated response with {@link PagedIterable}. */ @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getSecretsAsync(String vaultBaseUrl, Integer maxresults, Context context) { - return new PagedFlux<>(() -> getSecretsSinglePageAsync(vaultBaseUrl, maxresults, context), - nextLink -> getSecretsNextSinglePageAsync(nextLink, vaultBaseUrl, context)); + public PagedIterable getSecrets(RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedIterable<>(() -> getSecretsSinglePage(requestOptions), + nextLink -> getSecretsNextSinglePage(nextLink, requestOptionsForNextPage)); } /** - * List secrets in a specified key vault. + * List all versions of the specified secret. * - * The Get Secrets operation is applicable to the entire vault. However, only the base secret identifier and its - * attributes are provided in the response. Individual secret versions are not listed in the response. This - * operation requires the secrets/list permission. + * The full secret identifier and attributes are provided in the response. No values are returned for the secrets. + * This operations requires the secrets/list permission. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     contentType: String (Optional)
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result along with {@link PagedResponse}. + * @param secretName The name of the secret. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the secret list result along with {@link PagedResponse} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getSecretsSinglePage(String vaultBaseUrl, Integer maxresults) { + private Mono> getSecretVersionsSinglePageAsync(String secretName, + RequestOptions requestOptions) { final String accept = "application/json"; - Response res - = service.getSecretsSync(vaultBaseUrl, maxresults, this.getApiVersion(), accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); + return FluxUtil + .withContext(context -> service.getSecretVersions(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), secretName, accept, requestOptions, context)) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } /** - * List secrets in a specified key vault. - * - * The Get Secrets operation is applicable to the entire vault. However, only the base secret identifier and its - * attributes are provided in the response. Individual secret versions are not listed in the response. This - * operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getSecretsSinglePage(String vaultBaseUrl, Integer maxresults, Context context) { - final String accept = "application/json"; - Response res - = service.getSecretsSync(vaultBaseUrl, maxresults, this.getApiVersion(), accept, context); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * List secrets in a specified key vault. - * - * The Get Secrets operation is applicable to the entire vault. However, only the base secret identifier and its - * attributes are provided in the response. Individual secret versions are not listed in the response. This - * operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getSecrets(String vaultBaseUrl, Integer maxresults) { - return new PagedIterable<>(() -> getSecretsSinglePage(vaultBaseUrl, maxresults, Context.NONE), - nextLink -> getSecretsNextSinglePage(nextLink, vaultBaseUrl)); - } - - /** - * List secrets in a specified key vault. - * - * The Get Secrets operation is applicable to the entire vault. However, only the base secret identifier and its - * attributes are provided in the response. Individual secret versions are not listed in the response. This - * operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getSecrets(String vaultBaseUrl, Integer maxresults, Context context) { - return new PagedIterable<>(() -> getSecretsSinglePage(vaultBaseUrl, maxresults, context), - nextLink -> getSecretsNextSinglePage(nextLink, vaultBaseUrl, context)); - } - - /** - * List all versions of the specified secret. + * List all versions of the specified secret. * * The full secret identifier and attributes are provided in the response. No values are returned for the secrets. * This operations requires the secrets/list permission. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     contentType: String (Optional)
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretName The name of the secret. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSecretVersionsSinglePageAsync(String vaultBaseUrl, String secretName, - Integer maxresults) { - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.getSecretVersions(vaultBaseUrl, secretName, maxresults, - this.getApiVersion(), accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * List all versions of the specified secret. - * - * The full secret identifier and attributes are provided in the response. No values are returned for the secrets. - * This operations requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSecretVersionsSinglePageAsync(String vaultBaseUrl, String secretName, - Integer maxresults, Context context) { - final String accept = "application/json"; - return service.getSecretVersions(vaultBaseUrl, secretName, maxresults, this.getApiVersion(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * List all versions of the specified secret. - * - * The full secret identifier and attributes are provided in the response. No values are returned for the secrets. - * This operations requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the secret list result as paginated response with {@link PagedFlux}. */ @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getSecretVersionsAsync(String vaultBaseUrl, String secretName, Integer maxresults) { - return new PagedFlux<>(() -> getSecretVersionsSinglePageAsync(vaultBaseUrl, secretName, maxresults), - nextLink -> getSecretVersionsNextSinglePageAsync(nextLink, vaultBaseUrl)); + public PagedFlux getSecretVersionsAsync(String secretName, RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedFlux<>(() -> getSecretVersionsSinglePageAsync(secretName, requestOptions), + nextLink -> getSecretVersionsNextSinglePageAsync(nextLink, requestOptionsForNextPage)); } /** @@ -1205,47 +1297,53 @@ public PagedFlux getSecretVersionsAsync(String vaultBaseUrl, String * * The full secret identifier and attributes are provided in the response. No values are returned for the secrets. * This operations requires the secrets/list permission. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     contentType: String (Optional)
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretName The name of the secret. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getSecretVersionsAsync(String vaultBaseUrl, String secretName, Integer maxresults, - Context context) { - return new PagedFlux<>(() -> getSecretVersionsSinglePageAsync(vaultBaseUrl, secretName, maxresults, context), - nextLink -> getSecretVersionsNextSinglePageAsync(nextLink, vaultBaseUrl, context)); - } - - /** - * List all versions of the specified secret. - * - * The full secret identifier and attributes are provided in the response. No values are returned for the secrets. - * This operations requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the secret list result along with {@link PagedResponse}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getSecretVersionsSinglePage(String vaultBaseUrl, String secretName, - Integer maxresults) { + private PagedResponse getSecretVersionsSinglePage(String secretName, RequestOptions requestOptions) { final String accept = "application/json"; - Response res = service.getSecretVersionsSync(vaultBaseUrl, secretName, maxresults, - this.getApiVersion(), accept, Context.NONE); + Response res = service.getSecretVersionsSync(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), secretName, accept, requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } /** @@ -1253,70 +1351,53 @@ public PagedResponse getSecretVersionsSinglePage(String vaultBaseUrl * * The full secret identifier and attributes are provided in the response. No values are returned for the secrets. * This operations requires the secrets/list permission. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     contentType: String (Optional)
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretName The name of the secret. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getSecretVersionsSinglePage(String vaultBaseUrl, String secretName, - Integer maxresults, Context context) { - final String accept = "application/json"; - Response res = service.getSecretVersionsSync(vaultBaseUrl, secretName, maxresults, - this.getApiVersion(), accept, context); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * List all versions of the specified secret. - * - * The full secret identifier and attributes are provided in the response. No values are returned for the secrets. - * This operations requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getSecretVersions(String vaultBaseUrl, String secretName, Integer maxresults) { - return new PagedIterable<>( - () -> getSecretVersionsSinglePage(vaultBaseUrl, secretName, maxresults, Context.NONE), - nextLink -> getSecretVersionsNextSinglePage(nextLink, vaultBaseUrl)); - } - - /** - * List all versions of the specified secret. - * - * The full secret identifier and attributes are provided in the response. No values are returned for the secrets. - * This operations requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param maxresults Maximum number of results to return in a page. If not specified, the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the secret list result as paginated response with {@link PagedIterable}. */ @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getSecretVersions(String vaultBaseUrl, String secretName, Integer maxresults, - Context context) { - return new PagedIterable<>(() -> getSecretVersionsSinglePage(vaultBaseUrl, secretName, maxresults, context), - nextLink -> getSecretVersionsNextSinglePage(nextLink, vaultBaseUrl, context)); + public PagedIterable getSecretVersions(String secretName, RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedIterable<>(() -> getSecretVersionsSinglePage(secretName, requestOptions), + nextLink -> getSecretVersionsNextSinglePage(nextLink, requestOptionsForNextPage)); } /** @@ -1324,24 +1405,56 @@ public PagedIterable getSecretVersions(String vaultBaseUrl, String s * * The Get Deleted Secrets operation returns the secrets that have been deleted for a vault enabled for soft-delete. * This operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     contentType: String (Optional)
          +     *     managed: Boolean (Optional)
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the deleted secret list result along with {@link PagedResponse} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedSecretsSinglePageAsync(String vaultBaseUrl, - Integer maxresults) { + private Mono> getDeletedSecretsSinglePageAsync(RequestOptions requestOptions) { final String accept = "application/json"; return FluxUtil - .withContext( - context -> service.getDeletedSecrets(vaultBaseUrl, maxresults, this.getApiVersion(), accept, context)) + .withContext(context -> service.getDeletedSecrets(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), accept, requestOptions, context)) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } /** @@ -1349,43 +1462,55 @@ public Mono> getDeletedSecretsSinglePageAsync(S * * The Get Deleted Secrets operation returns the secrets that have been deleted for a vault enabled for soft-delete. * This operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the deleted secret list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedSecretsSinglePageAsync(String vaultBaseUrl, - Integer maxresults, Context context) { - final String accept = "application/json"; - return service.getDeletedSecrets(vaultBaseUrl, maxresults, this.getApiVersion(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** - * Lists deleted secrets for the specified vault. - * - * The Get Deleted Secrets operation returns the secrets that have been deleted for a vault enabled for soft-delete. - * This operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     contentType: String (Optional)
          +     *     managed: Boolean (Optional)
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the deleted secret list result as paginated response with {@link PagedFlux}. */ @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getDeletedSecretsAsync(String vaultBaseUrl, Integer maxresults) { - return new PagedFlux<>(() -> getDeletedSecretsSinglePageAsync(vaultBaseUrl, maxresults), - nextLink -> getDeletedSecretsNextSinglePageAsync(nextLink, vaultBaseUrl)); + public PagedFlux getDeletedSecretsAsync(RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedFlux<>(() -> getDeletedSecretsSinglePageAsync(requestOptions), + nextLink -> getDeletedSecretsNextSinglePageAsync(nextLink, requestOptionsForNextPage)); } /** @@ -1393,44 +1518,55 @@ public PagedFlux getDeletedSecretsAsync(String vaultBaseUrl, * * The Get Deleted Secrets operation returns the secrets that have been deleted for a vault enabled for soft-delete. * This operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the deleted secret list result as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getDeletedSecretsAsync(String vaultBaseUrl, Integer maxresults, - Context context) { - return new PagedFlux<>(() -> getDeletedSecretsSinglePageAsync(vaultBaseUrl, maxresults, context), - nextLink -> getDeletedSecretsNextSinglePageAsync(nextLink, vaultBaseUrl, context)); - } - - /** - * Lists deleted secrets for the specified vault. - * - * The Get Deleted Secrets operation returns the secrets that have been deleted for a vault enabled for soft-delete. - * This operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     contentType: String (Optional)
          +     *     managed: Boolean (Optional)
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the deleted secret list result along with {@link PagedResponse}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getDeletedSecretsSinglePage(String vaultBaseUrl, Integer maxresults) { + private PagedResponse getDeletedSecretsSinglePage(RequestOptions requestOptions) { final String accept = "application/json"; - Response res - = service.getDeletedSecretsSync(vaultBaseUrl, maxresults, this.getApiVersion(), accept, Context.NONE); + Response res = service.getDeletedSecretsSync(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), accept, requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } /** @@ -1438,66 +1574,55 @@ public PagedResponse getDeletedSecretsSinglePage(String vault * * The Get Deleted Secrets operation returns the secrets that have been deleted for a vault enabled for soft-delete. * This operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the deleted secret list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getDeletedSecretsSinglePage(String vaultBaseUrl, Integer maxresults, - Context context) { - final String accept = "application/json"; - Response res - = service.getDeletedSecretsSync(vaultBaseUrl, maxresults, this.getApiVersion(), accept, context); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** - * Lists deleted secrets for the specified vault. - * - * The Get Deleted Secrets operation returns the secrets that have been deleted for a vault enabled for soft-delete. - * This operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + *

          Query Parameters

          + * + * + * + * + *
          Query Parameters
          NameTypeRequiredDescription
          maxresultsIntegerNoMaximum number of results to return in a page. If not + * specified the service will return up to 25 results.
          + * You can add these to a request with {@link RequestOptions#addQueryParam} + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     contentType: String (Optional)
          +     *     managed: Boolean (Optional)
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the deleted secret list result as paginated response with {@link PagedIterable}. */ @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getDeletedSecrets(String vaultBaseUrl, Integer maxresults) { - return new PagedIterable<>(() -> getDeletedSecretsSinglePage(vaultBaseUrl, maxresults, Context.NONE), - nextLink -> getDeletedSecretsNextSinglePage(nextLink, vaultBaseUrl)); - } - - /** - * Lists deleted secrets for the specified vault. - * - * The Get Deleted Secrets operation returns the secrets that have been deleted for a vault enabled for soft-delete. - * This operation requires the secrets/list permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param maxresults Maximum number of results to return in a page. If not specified the service will return up to - * 25 results. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the deleted secret list result as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getDeletedSecrets(String vaultBaseUrl, Integer maxresults, - Context context) { - return new PagedIterable<>(() -> getDeletedSecretsSinglePage(vaultBaseUrl, maxresults, context), - nextLink -> getDeletedSecretsNextSinglePage(nextLink, vaultBaseUrl, context)); + public PagedIterable getDeletedSecrets(RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedIterable<>(() -> getDeletedSecretsSinglePage(requestOptions), + nextLink -> getDeletedSecretsNextSinglePage(nextLink, requestOptionsForNextPage)); } /** @@ -1505,61 +1630,52 @@ public PagedIterable getDeletedSecrets(String vaultBaseUrl, I * * The Get Deleted Secret operation returns the specified deleted secret along with its attributes. This operation * requires the secrets/get permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: String (Optional)
          +     *     id: String (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     kid: String (Optional)
          +     *     managed: Boolean (Optional)
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretName The name of the secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Secret consisting of its previous id, attributes and its tags, as well as information on when - * it will be purged along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedSecretWithResponseAsync(String vaultBaseUrl, - String secretName) { - return FluxUtil.withContext(context -> getDeletedSecretWithResponseAsync(vaultBaseUrl, secretName, context)); - } - - /** - * Gets the specified deleted secret. - * - * The Get Deleted Secret operation returns the specified deleted secret along with its attributes. This operation - * requires the secrets/get permission. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the specified deleted secret. * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Secret consisting of its previous id, attributes and its tags, as well as information on when - * it will be purged along with {@link Response} on successful completion of {@link Mono}. + * The Get Deleted Secret operation returns the specified deleted secret along with its attributes along with + * {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedSecretWithResponseAsync(String vaultBaseUrl, String secretName, - Context context) { + public Mono> getDeletedSecretWithResponseAsync(String secretName, + RequestOptions requestOptions) { final String accept = "application/json"; - return service.getDeletedSecret(vaultBaseUrl, secretName, this.getApiVersion(), accept, context); - } - - /** - * Gets the specified deleted secret. - * - * The Get Deleted Secret operation returns the specified deleted secret along with its attributes. This operation - * requires the secrets/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Secret consisting of its previous id, attributes and its tags, as well as information on when - * it will be purged on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getDeletedSecretAsync(String vaultBaseUrl, String secretName) { - return getDeletedSecretWithResponseAsync(vaultBaseUrl, secretName) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + return FluxUtil.withContext(context -> service.getDeletedSecret(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), secretName, accept, requestOptions, context)); } /** @@ -1567,80 +1683,51 @@ public Mono getDeletedSecretAsync(String vaultBaseUrl, Stri * * The Get Deleted Secret operation returns the specified deleted secret along with its attributes. This operation * requires the secrets/get permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: String (Optional)
          +     *     id: String (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     kid: String (Optional)
          +     *     managed: Boolean (Optional)
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretName The name of the secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Secret consisting of its previous id, attributes and its tags, as well as information on when - * it will be purged on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getDeletedSecretAsync(String vaultBaseUrl, String secretName, Context context) { - return getDeletedSecretWithResponseAsync(vaultBaseUrl, secretName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Gets the specified deleted secret. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the specified deleted secret. * - * The Get Deleted Secret operation returns the specified deleted secret along with its attributes. This operation - * requires the secrets/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Secret consisting of its previous id, attributes and its tags, as well as information on when - * it will be purged along with {@link Response}. + * The Get Deleted Secret operation returns the specified deleted secret along with its attributes along with + * {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response getDeletedSecretWithResponse(String vaultBaseUrl, String secretName, - Context context) { + public Response getDeletedSecretWithResponse(String secretName, RequestOptions requestOptions) { final String accept = "application/json"; - return service.getDeletedSecretSync(vaultBaseUrl, secretName, this.getApiVersion(), accept, context); - } - - /** - * Gets the specified deleted secret. - * - * The Get Deleted Secret operation returns the specified deleted secret along with its attributes. This operation - * requires the secrets/get permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Deleted Secret consisting of its previous id, attributes and its tags, as well as information on when - * it will be purged. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public DeletedSecretBundle getDeletedSecret(String vaultBaseUrl, String secretName) { - return getDeletedSecretWithResponse(vaultBaseUrl, secretName, Context.NONE).getValue(); - } - - /** - * Permanently deletes the specified secret. - * - * The purge deleted secret operation removes the secret permanently, without the possibility of recovery. This - * operation can only be enabled on a soft-delete enabled vault. This operation requires the secrets/purge - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> purgeDeletedSecretWithResponseAsync(String vaultBaseUrl, String secretName) { - return FluxUtil.withContext(context -> purgeDeletedSecretWithResponseAsync(vaultBaseUrl, secretName, context)); + return service.getDeletedSecretSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), secretName, + accept, requestOptions, Context.NONE); } /** @@ -1650,38 +1737,19 @@ public Mono> purgeDeletedSecretWithResponseAsync(String vaultBase * operation can only be enabled on a soft-delete enabled vault. This operation requires the secrets/purge * permission. * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretName The name of the secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> purgeDeletedSecretWithResponseAsync(String vaultBaseUrl, String secretName, - Context context) { + public Mono> purgeDeletedSecretWithResponseAsync(String secretName, RequestOptions requestOptions) { final String accept = "application/json"; - return service.purgeDeletedSecret(vaultBaseUrl, secretName, this.getApiVersion(), accept, context); - } - - /** - * Permanently deletes the specified secret. - * - * The purge deleted secret operation removes the secret permanently, without the possibility of recovery. This - * operation can only be enabled on a soft-delete enabled vault. This operation requires the secrets/purge - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono purgeDeletedSecretAsync(String vaultBaseUrl, String secretName) { - return purgeDeletedSecretWithResponseAsync(vaultBaseUrl, secretName).flatMap(ignored -> Mono.empty()); + return FluxUtil.withContext(context -> service.purgeDeletedSecret(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), secretName, accept, requestOptions, context)); } /** @@ -1691,76 +1759,19 @@ public Mono purgeDeletedSecretAsync(String vaultBaseUrl, String secretName * operation can only be enabled on a soft-delete enabled vault. This operation requires the secrets/purge * permission. * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretName The name of the secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono purgeDeletedSecretAsync(String vaultBaseUrl, String secretName, Context context) { - return purgeDeletedSecretWithResponseAsync(vaultBaseUrl, secretName, context).flatMap(ignored -> Mono.empty()); - } - - /** - * Permanently deletes the specified secret. - * - * The purge deleted secret operation removes the secret permanently, without the possibility of recovery. This - * operation can only be enabled on a soft-delete enabled vault. This operation requires the secrets/purge - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response purgeDeletedSecretWithResponse(String vaultBaseUrl, String secretName, Context context) { + public Response purgeDeletedSecretWithResponse(String secretName, RequestOptions requestOptions) { final String accept = "application/json"; - return service.purgeDeletedSecretSync(vaultBaseUrl, secretName, this.getApiVersion(), accept, context); - } - - /** - * Permanently deletes the specified secret. - * - * The purge deleted secret operation removes the secret permanently, without the possibility of recovery. This - * operation can only be enabled on a soft-delete enabled vault. This operation requires the secrets/purge - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void purgeDeletedSecret(String vaultBaseUrl, String secretName) { - purgeDeletedSecretWithResponse(vaultBaseUrl, secretName, Context.NONE); - } - - /** - * Recovers the deleted secret to the latest version. - * - * Recovers the deleted secret in the specified vault. This operation can only be performed on a soft-delete enabled - * vault. This operation requires the secrets/recover permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the deleted secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> recoverDeletedSecretWithResponseAsync(String vaultBaseUrl, String secretName) { - return FluxUtil - .withContext(context -> recoverDeletedSecretWithResponseAsync(vaultBaseUrl, secretName, context)); + return service.purgeDeletedSecretSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), secretName, + accept, requestOptions, Context.NONE); } /** @@ -1768,21 +1779,47 @@ public Mono> recoverDeletedSecretWithResponseAsync(String * * Recovers the deleted secret in the specified vault. This operation can only be performed on a soft-delete enabled * vault. This operation requires the secrets/recover permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: String (Optional)
          +     *     id: String (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     kid: String (Optional)
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretName The name of the deleted secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a secret consisting of a value, id and its attributes along with {@link Response} on successful * completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> recoverDeletedSecretWithResponseAsync(String vaultBaseUrl, String secretName, - Context context) { + public Mono> recoverDeletedSecretWithResponseAsync(String secretName, + RequestOptions requestOptions) { final String accept = "application/json"; - return service.recoverDeletedSecret(vaultBaseUrl, secretName, this.getApiVersion(), accept, context); + return FluxUtil.withContext(context -> service.recoverDeletedSecret(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), secretName, accept, requestOptions, context)); } /** @@ -1790,77 +1827,45 @@ public Mono> recoverDeletedSecretWithResponseAsync(String * * Recovers the deleted secret in the specified vault. This operation can only be performed on a soft-delete enabled * vault. This operation requires the secrets/recover permission. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: String (Optional)
          +     *     id: String (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     kid: String (Optional)
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretName The name of the deleted secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono recoverDeletedSecretAsync(String vaultBaseUrl, String secretName) { - return recoverDeletedSecretWithResponseAsync(vaultBaseUrl, secretName) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Recovers the deleted secret to the latest version. - * - * Recovers the deleted secret in the specified vault. This operation can only be performed on a soft-delete enabled - * vault. This operation requires the secrets/recover permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the deleted secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono recoverDeletedSecretAsync(String vaultBaseUrl, String secretName, Context context) { - return recoverDeletedSecretWithResponseAsync(vaultBaseUrl, secretName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Recovers the deleted secret to the latest version. - * - * Recovers the deleted secret in the specified vault. This operation can only be performed on a soft-delete enabled - * vault. This operation requires the secrets/recover permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the deleted secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a secret consisting of a value, id and its attributes along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response recoverDeletedSecretWithResponse(String vaultBaseUrl, String secretName, - Context context) { + public Response recoverDeletedSecretWithResponse(String secretName, RequestOptions requestOptions) { final String accept = "application/json"; - return service.recoverDeletedSecretSync(vaultBaseUrl, secretName, this.getApiVersion(), accept, context); - } - - /** - * Recovers the deleted secret to the latest version. - * - * Recovers the deleted secret in the specified vault. This operation can only be performed on a soft-delete enabled - * vault. This operation requires the secrets/recover permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the deleted secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SecretBundle recoverDeletedSecret(String vaultBaseUrl, String secretName) { - return recoverDeletedSecretWithResponse(vaultBaseUrl, secretName, Context.NONE).getValue(); + return service.recoverDeletedSecretSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), + secretName, accept, requestOptions, Context.NONE); } /** @@ -1868,40 +1873,30 @@ public SecretBundle recoverDeletedSecret(String vaultBaseUrl, String secretName) * * Requests that a backup of the specified secret be downloaded to the client. All versions of the secret will be * downloaded. This operation requires the secrets/backup permission. + *

          Response Body Schema

          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the backup secret result, containing the backup blob along with {@link Response} on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> backupSecretWithResponseAsync(String vaultBaseUrl, String secretName) { - return FluxUtil.withContext(context -> backupSecretWithResponseAsync(vaultBaseUrl, secretName, context)); - } - - /** - * Backs up the specified secret. - * - * Requests that a backup of the specified secret be downloaded to the client. All versions of the secret will be - * downloaded. This operation requires the secrets/backup permission. + *
          +     * {@code
          +     * {
          +     *     value: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretName The name of the secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the backup secret result, containing the backup blob along with {@link Response} on successful completion * of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> backupSecretWithResponseAsync(String vaultBaseUrl, String secretName, - Context context) { + public Mono> backupSecretWithResponseAsync(String secretName, RequestOptions requestOptions) { final String accept = "application/json"; - return service.backupSecret(vaultBaseUrl, secretName, this.getApiVersion(), accept, context); + return FluxUtil.withContext(context -> service.backupSecret(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), secretName, accept, requestOptions, context)); } /** @@ -1909,76 +1904,29 @@ public Mono> backupSecretWithResponseAsync(String v * * Requests that a backup of the specified secret be downloaded to the client. All versions of the secret will be * downloaded. This operation requires the secrets/backup permission. + *

          Response Body Schema

          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the backup secret result, containing the backup blob on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono backupSecretAsync(String vaultBaseUrl, String secretName) { - return backupSecretWithResponseAsync(vaultBaseUrl, secretName).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Backs up the specified secret. - * - * Requests that a backup of the specified secret be downloaded to the client. All versions of the secret will be - * downloaded. This operation requires the secrets/backup permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the backup secret result, containing the backup blob on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono backupSecretAsync(String vaultBaseUrl, String secretName, Context context) { - return backupSecretWithResponseAsync(vaultBaseUrl, secretName, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Backs up the specified secret. - * - * Requests that a backup of the specified secret be downloaded to the client. All versions of the secret will be - * downloaded. This operation requires the secrets/backup permission. + *
          +     * {@code
          +     * {
          +     *     value: Base64Url (Optional)
          +     * }
          +     * }
          +     * 
          * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretName The name of the secret. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the backup secret result, containing the backup blob along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response backupSecretWithResponse(String vaultBaseUrl, String secretName, - Context context) { + public Response backupSecretWithResponse(String secretName, RequestOptions requestOptions) { final String accept = "application/json"; - return service.backupSecretSync(vaultBaseUrl, secretName, this.getApiVersion(), accept, context); - } - - /** - * Backs up the specified secret. - * - * Requests that a backup of the specified secret be downloaded to the client. All versions of the secret will be - * downloaded. This operation requires the secrets/backup permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretName The name of the secret. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the backup secret result, containing the backup blob. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public BackupSecretResult backupSecret(String vaultBaseUrl, String secretName) { - return backupSecretWithResponse(vaultBaseUrl, secretName, Context.NONE).getValue(); + return service.backupSecretSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), secretName, + accept, requestOptions, Context.NONE); } /** @@ -1986,43 +1934,58 @@ public BackupSecretResult backupSecret(String vaultBaseUrl, String secretName) { * * Restores a backed up secret, and all its versions, to a vault. This operation requires the secrets/restore * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretBundleBackup The backup blob associated with a secret bundle. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> restoreSecretWithResponseAsync(String vaultBaseUrl, byte[] secretBundleBackup) { - return FluxUtil - .withContext(context -> restoreSecretWithResponseAsync(vaultBaseUrl, secretBundleBackup, context)); - } - - /** - * Restores a backed up secret to a vault. - * - * Restores a backed up secret, and all its versions, to a vault. This operation requires the secrets/restore - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretBundleBackup The backup blob associated with a secret bundle. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: Base64Url (Required)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: String (Optional)
          +     *     id: String (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     kid: String (Optional)
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param parameters The parameters to restore the secret. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a secret consisting of a value, id and its attributes along with {@link Response} on successful * completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> restoreSecretWithResponseAsync(String vaultBaseUrl, byte[] secretBundleBackup, - Context context) { + public Mono> restoreSecretWithResponseAsync(BinaryData parameters, + RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - SecretRestoreParameters parameters = new SecretRestoreParameters(); - parameters.setSecretBundleBackup(secretBundleBackup); - return service.restoreSecret(vaultBaseUrl, this.getApiVersion(), parameters, accept, context); + return FluxUtil.withContext(context -> service.restoreSecret(this.getVaultBaseUrl(), + this.getServiceVersion().getVersion(), contentType, accept, parameters, requestOptions, context)); } /** @@ -2030,309 +1993,354 @@ public Mono> restoreSecretWithResponseAsync(String vaultB * * Restores a backed up secret, and all its versions, to a vault. This operation requires the secrets/restore * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretBundleBackup The backup blob associated with a secret bundle. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono restoreSecretAsync(String vaultBaseUrl, byte[] secretBundleBackup) { - return restoreSecretWithResponseAsync(vaultBaseUrl, secretBundleBackup) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Restores a backed up secret to a vault. - * - * Restores a backed up secret, and all its versions, to a vault. This operation requires the secrets/restore - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretBundleBackup The backup blob associated with a secret bundle. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono restoreSecretAsync(String vaultBaseUrl, byte[] secretBundleBackup, Context context) { - return restoreSecretWithResponseAsync(vaultBaseUrl, secretBundleBackup, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Restores a backed up secret to a vault. - * - * Restores a backed up secret, and all its versions, to a vault. This operation requires the secrets/restore - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretBundleBackup The backup blob associated with a secret bundle. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + *

          Request Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: Base64Url (Required)
          +     * }
          +     * }
          +     * 
          + * + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     value: String (Optional)
          +     *     id: String (Optional)
          +     *     contentType: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     kid: String (Optional)
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          + * + * @param parameters The parameters to restore the secret. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a secret consisting of a value, id and its attributes along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response restoreSecretWithResponse(String vaultBaseUrl, byte[] secretBundleBackup, - Context context) { + public Response restoreSecretWithResponse(BinaryData parameters, RequestOptions requestOptions) { + final String contentType = "application/json"; final String accept = "application/json"; - SecretRestoreParameters parameters = new SecretRestoreParameters(); - parameters.setSecretBundleBackup(secretBundleBackup); - return service.restoreSecretSync(vaultBaseUrl, this.getApiVersion(), parameters, accept, context); - } - - /** - * Restores a backed up secret to a vault. - * - * Restores a backed up secret, and all its versions, to a vault. This operation requires the secrets/restore - * permission. - * - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param secretBundleBackup The backup blob associated with a secret bundle. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a secret consisting of a value, id and its attributes. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SecretBundle restoreSecret(String vaultBaseUrl, byte[] secretBundleBackup) { - return restoreSecretWithResponse(vaultBaseUrl, secretBundleBackup, Context.NONE).getValue(); + return service.restoreSecretSync(this.getVaultBaseUrl(), this.getServiceVersion().getVersion(), contentType, + accept, parameters, requestOptions, Context.NONE); } /** - * Get the next page of items. + * List secrets in a specified key vault. * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSecretsNextSinglePageAsync(String nextLink, String vaultBaseUrl) { - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.getSecretsNext(nextLink, vaultBaseUrl, accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** * Get the next page of items. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     contentType: String (Optional)
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          * * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the secret list result along with {@link PagedResponse} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSecretsNextSinglePageAsync(String nextLink, String vaultBaseUrl, - Context context) { + private Mono> getSecretsNextSinglePageAsync(String nextLink, + RequestOptions requestOptions) { final String accept = "application/json"; - return service.getSecretsNext(nextLink, vaultBaseUrl, accept, context) + return FluxUtil + .withContext( + context -> service.getSecretsNext(nextLink, this.getVaultBaseUrl(), accept, requestOptions, context)) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } /** - * Get the next page of items. + * List secrets in a specified key vault. * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getSecretsNextSinglePage(String nextLink, String vaultBaseUrl) { - final String accept = "application/json"; - Response res = service.getSecretsNextSync(nextLink, vaultBaseUrl, accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** * Get the next page of items. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     contentType: String (Optional)
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          * * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the secret list result along with {@link PagedResponse}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getSecretsNextSinglePage(String nextLink, String vaultBaseUrl, Context context) { + private PagedResponse getSecretsNextSinglePage(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; - Response res = service.getSecretsNextSync(nextLink, vaultBaseUrl, accept, context); + Response res + = service.getSecretsNextSync(nextLink, this.getVaultBaseUrl(), accept, requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } /** - * Get the next page of items. + * List all versions of the specified secret. * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSecretVersionsNextSinglePageAsync(String nextLink, String vaultBaseUrl) { - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.getSecretVersionsNext(nextLink, vaultBaseUrl, accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** * Get the next page of items. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     contentType: String (Optional)
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          * * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the secret list result along with {@link PagedResponse} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSecretVersionsNextSinglePageAsync(String nextLink, String vaultBaseUrl, - Context context) { + private Mono> getSecretVersionsNextSinglePageAsync(String nextLink, + RequestOptions requestOptions) { final String accept = "application/json"; - return service.getSecretVersionsNext(nextLink, vaultBaseUrl, accept, context) + return FluxUtil.withContext( + context -> service.getSecretVersionsNext(nextLink, this.getVaultBaseUrl(), accept, requestOptions, context)) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } /** - * Get the next page of items. + * List all versions of the specified secret. * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the secret list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getSecretVersionsNextSinglePage(String nextLink, String vaultBaseUrl) { - final String accept = "application/json"; - Response res - = service.getSecretVersionsNextSync(nextLink, vaultBaseUrl, accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** * Get the next page of items. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     contentType: String (Optional)
          +     *     managed: Boolean (Optional)
          +     * }
          +     * }
          +     * 
          * * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the secret list result along with {@link PagedResponse}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getSecretVersionsNextSinglePage(String nextLink, String vaultBaseUrl, - Context context) { + private PagedResponse getSecretVersionsNextSinglePage(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; - Response res = service.getSecretVersionsNextSync(nextLink, vaultBaseUrl, accept, context); + Response res + = service.getSecretVersionsNextSync(nextLink, this.getVaultBaseUrl(), accept, requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } /** - * Get the next page of items. + * Lists deleted secrets for the specified vault. * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the deleted secret list result along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedSecretsNextSinglePageAsync(String nextLink, - String vaultBaseUrl) { - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.getDeletedSecretsNext(nextLink, vaultBaseUrl, accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); - } - - /** * Get the next page of items. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     contentType: String (Optional)
          +     *     managed: Boolean (Optional)
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          * * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the deleted secret list result along with {@link PagedResponse} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDeletedSecretsNextSinglePageAsync(String nextLink, - String vaultBaseUrl, Context context) { + private Mono> getDeletedSecretsNextSinglePageAsync(String nextLink, + RequestOptions requestOptions) { final String accept = "application/json"; - return service.getDeletedSecretsNext(nextLink, vaultBaseUrl, accept, context) + return FluxUtil.withContext( + context -> service.getDeletedSecretsNext(nextLink, this.getVaultBaseUrl(), accept, requestOptions, context)) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null)); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } /** - * Get the next page of items. + * Lists deleted secrets for the specified vault. * - * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the deleted secret list result along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getDeletedSecretsNextSinglePage(String nextLink, String vaultBaseUrl) { - final String accept = "application/json"; - Response res - = service.getDeletedSecretsNextSync(nextLink, vaultBaseUrl, accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); - } - - /** * Get the next page of items. + *

          Response Body Schema

          + * + *
          +     * {@code
          +     * {
          +     *     id: String (Optional)
          +     *     attributes (Optional): {
          +     *         enabled: Boolean (Optional)
          +     *         nbf: Long (Optional)
          +     *         exp: Long (Optional)
          +     *         created: Long (Optional)
          +     *         updated: Long (Optional)
          +     *         recoverableDays: Integer (Optional)
          +     *         recoveryLevel: String(Purgeable/Recoverable+Purgeable/Recoverable/Recoverable+ProtectedSubscription/CustomizedRecoverable+Purgeable/CustomizedRecoverable/CustomizedRecoverable+ProtectedSubscription) (Optional)
          +     *     }
          +     *     tags (Optional): {
          +     *         String: String (Required)
          +     *     }
          +     *     contentType: String (Optional)
          +     *     managed: Boolean (Optional)
          +     *     recoveryId: String (Optional)
          +     *     scheduledPurgeDate: Long (Optional)
          +     *     deletedDate: Long (Optional)
          +     * }
          +     * }
          +     * 
          * * @param nextLink The URL to get the next list of items. - * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws KeyVaultErrorException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the deleted secret list result along with {@link PagedResponse}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getDeletedSecretsNextSinglePage(String nextLink, String vaultBaseUrl, - Context context) { + private PagedResponse getDeletedSecretsNextSinglePage(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; - Response res - = service.getDeletedSecretsNextSync(nextLink, vaultBaseUrl, accept, context); + Response res + = service.getDeletedSecretsNextSync(nextLink, this.getVaultBaseUrl(), accept, requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getValue(), res.getValue().getNextLink(), null); + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); + } + + private List getValues(BinaryData binaryData, String path) { + try { + Map obj = binaryData.toObject(Map.class); + List values = (List) obj.get(path); + return values.stream().map(BinaryData::fromObject).collect(Collectors.toList()); + } catch (RuntimeException e) { + return null; + } + } + + private String getNextLink(BinaryData binaryData, String path) { + try { + Map obj = binaryData.toObject(Map.class); + return (String) obj.get(path); + } catch (RuntimeException e) { + return null; + } } } diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/Attributes.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/Attributes.java deleted file mode 100644 index a409d75c7a23..000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/Attributes.java +++ /dev/null @@ -1,226 +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.security.keyvault.secrets.implementation.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.time.Instant; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; - -/** - * The object attributes managed by the KeyVault service. - */ -@Fluent -public class Attributes implements JsonSerializable { - /* - * Determines whether the object is enabled. - */ - private Boolean enabled; - - /* - * Not before date in UTC. - */ - private Long notBefore; - - /* - * Expiry date in UTC. - */ - private Long expires; - - /* - * Creation time in UTC. - */ - private Long created; - - /* - * Last updated time in UTC. - */ - private Long updated; - - /** - * Creates an instance of Attributes class. - */ - public Attributes() { - } - - /** - * Get the enabled property: Determines whether the object is enabled. - * - * @return the enabled value. - */ - public Boolean isEnabled() { - return this.enabled; - } - - /** - * Set the enabled property: Determines whether the object is enabled. - * - * @param enabled the enabled value to set. - * @return the Attributes object itself. - */ - public Attributes setEnabled(Boolean enabled) { - this.enabled = enabled; - return this; - } - - /** - * Get the notBefore property: Not before date in UTC. - * - * @return the notBefore value. - */ - public OffsetDateTime getNotBefore() { - if (this.notBefore == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.notBefore), ZoneOffset.UTC); - } - - /** - * Set the notBefore property: Not before date in UTC. - * - * @param notBefore the notBefore value to set. - * @return the Attributes object itself. - */ - public Attributes setNotBefore(OffsetDateTime notBefore) { - if (notBefore == null) { - this.notBefore = null; - } else { - this.notBefore = notBefore.toEpochSecond(); - } - return this; - } - - /** - * Get the expires property: Expiry date in UTC. - * - * @return the expires value. - */ - public OffsetDateTime getExpires() { - if (this.expires == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.expires), ZoneOffset.UTC); - } - - /** - * Set the expires property: Expiry date in UTC. - * - * @param expires the expires value to set. - * @return the Attributes object itself. - */ - public Attributes setExpires(OffsetDateTime expires) { - if (expires == null) { - this.expires = null; - } else { - this.expires = expires.toEpochSecond(); - } - return this; - } - - /** - * Get the created property: Creation time in UTC. - * - * @return the created value. - */ - public OffsetDateTime getCreated() { - if (this.created == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.created), ZoneOffset.UTC); - } - - /** - * Set the created property: Creation time in UTC. - * - * @param created the created value to set. - * @return the Attributes object itself. - */ - Attributes setCreated(OffsetDateTime created) { - if (created == null) { - this.created = null; - } else { - this.created = created.toEpochSecond(); - } - return this; - } - - /** - * Get the updated property: Last updated time in UTC. - * - * @return the updated value. - */ - public OffsetDateTime getUpdated() { - if (this.updated == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.updated), ZoneOffset.UTC); - } - - /** - * Set the updated property: Last updated time in UTC. - * - * @param updated the updated value to set. - * @return the Attributes object itself. - */ - Attributes setUpdated(OffsetDateTime updated) { - if (updated == null) { - this.updated = null; - } else { - this.updated = updated.toEpochSecond(); - } - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeBooleanField("enabled", this.enabled); - jsonWriter.writeNumberField("nbf", this.notBefore); - jsonWriter.writeNumberField("exp", this.expires); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of Attributes from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of Attributes 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 Attributes. - */ - public static Attributes fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - Attributes deserializedAttributes = new Attributes(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("enabled".equals(fieldName)) { - deserializedAttributes.enabled = reader.getNullable(JsonReader::getBoolean); - } else if ("nbf".equals(fieldName)) { - deserializedAttributes.notBefore = reader.getNullable(JsonReader::getLong); - } else if ("exp".equals(fieldName)) { - deserializedAttributes.expires = reader.getNullable(JsonReader::getLong); - } else if ("created".equals(fieldName)) { - deserializedAttributes.created = reader.getNullable(JsonReader::getLong); - } else if ("updated".equals(fieldName)) { - deserializedAttributes.updated = reader.getNullable(JsonReader::getLong); - } else { - reader.skipChildren(); - } - } - - return deserializedAttributes; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/BackupSecretResult.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/BackupSecretResult.java index b3d30d2bf45f..ed9cfc21194a 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/BackupSecretResult.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/BackupSecretResult.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.secrets.implementation.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.core.util.Base64Url; import com.azure.json.JsonReader; @@ -17,22 +17,26 @@ */ @Immutable public final class BackupSecretResult implements JsonSerializable { + /* * The backup blob containing the backed up secret. */ + @Generated private Base64Url value; /** * Creates an instance of BackupSecretResult class. */ - public BackupSecretResult() { + @Generated + private BackupSecretResult() { } /** * Get the value property: The backup blob containing the backed up secret. - * + * * @return the value value. */ + @Generated public byte[] getValue() { if (this.value == null) { return null; @@ -43,6 +47,7 @@ public byte[] getValue() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -51,19 +56,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of BackupSecretResult from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of BackupSecretResult 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 BackupSecretResult. */ + @Generated public static BackupSecretResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { BackupSecretResult deserializedBackupSecretResult = new BackupSecretResult(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("value".equals(fieldName)) { deserializedBackupSecretResult.value = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); @@ -71,7 +76,6 @@ public static BackupSecretResult fromJson(JsonReader jsonReader) throws IOExcept reader.skipChildren(); } } - return deserializedBackupSecretResult; }); } diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletedSecretBundle.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletedSecretBundle.java index 76027d396870..ed6261ddf7c6 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletedSecretBundle.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletedSecretBundle.java @@ -1,11 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.secrets.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +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; @@ -18,193 +19,228 @@ * A Deleted Secret consisting of its previous id, attributes and its tags, as well as information on when it will be * purged. */ -@Fluent -public final class DeletedSecretBundle extends SecretBundle { +@Immutable +public final class DeletedSecretBundle implements JsonSerializable { + /* - * The url of the recovery object, used to identify and recover the deleted secret. + * The secret value. */ - private String recoveryId; + @Generated + private String value; /* - * The time when the secret is scheduled to be purged, in UTC + * The secret id. */ - private Long scheduledPurgeDate; + @Generated + private String id; /* - * The time when the secret was deleted, in UTC + * The content type of the secret. */ - private Long deletedDate; + @Generated + private String contentType; /* - * True if the secret's lifetime is managed by key vault. If this is a secret backing a certificate, then managed - * will be true. + * The secret management attributes. */ - private Boolean managed; + @Generated + private SecretAttributes attributes; + + /* + * Application specific metadata in the form of key-value pairs. + */ + @Generated + private Map tags; /* * If this is a secret backing a KV certificate, then this field specifies the corresponding key backing the KV * certificate. */ + @Generated private String kid; + /* + * True if the secret's lifetime is managed by key vault. If this is a secret backing a certificate, then managed + * will be true. + */ + @Generated + private Boolean managed; + + /* + * The url of the recovery object, used to identify and recover the deleted secret. + */ + @Generated + private String recoveryId; + + /* + * The time when the secret is scheduled to be purged, in UTC + */ + @Generated + private Long scheduledPurgeDate; + + /* + * The time when the secret was deleted, in UTC + */ + @Generated + private Long deletedDate; + /** * Creates an instance of DeletedSecretBundle class. */ - public DeletedSecretBundle() { + @Generated + private DeletedSecretBundle() { } /** - * Get the recoveryId property: The url of the recovery object, used to identify and recover the deleted secret. - * - * @return the recoveryId value. + * Get the value property: The secret value. + * + * @return the value value. */ - public String getRecoveryId() { - return this.recoveryId; + @Generated + public String getValue() { + return this.value; } /** - * Set the recoveryId property: The url of the recovery object, used to identify and recover the deleted secret. - * - * @param recoveryId the recoveryId value to set. - * @return the DeletedSecretBundle object itself. - */ - public DeletedSecretBundle setRecoveryId(String recoveryId) { - this.recoveryId = recoveryId; - return this; + * Get the id property: The secret id. + * + * @return the id value. + */ + @Generated + public String getId() { + return this.id; } /** - * Get the scheduledPurgeDate property: The time when the secret is scheduled to be purged, in UTC. - * - * @return the scheduledPurgeDate value. + * Get the contentType property: The content type of the secret. + * + * @return the contentType value. */ - public OffsetDateTime getScheduledPurgeDate() { - if (this.scheduledPurgeDate == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.scheduledPurgeDate), ZoneOffset.UTC); + @Generated + public String getContentType() { + return this.contentType; } /** - * Get the deletedDate property: The time when the secret was deleted, in UTC. - * - * @return the deletedDate value. + * Get the attributes property: The secret management attributes. + * + * @return the attributes value. */ - public OffsetDateTime getDeletedDate() { - if (this.deletedDate == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.deletedDate), ZoneOffset.UTC); + @Generated + public SecretAttributes getAttributes() { + return this.attributes; } /** - * Get the managed property: True if the secret's lifetime is managed by key vault. If this is a secret backing a - * certificate, then managed will be true. - * - * @return the managed value. + * Get the tags property: Application specific metadata in the form of key-value pairs. + * + * @return the tags value. */ - @Override - public Boolean isManaged() { - return this.managed; + @Generated + public Map getTags() { + return this.tags; } /** * Get the kid property: If this is a secret backing a KV certificate, then this field specifies the corresponding * key backing the KV certificate. - * + * * @return the kid value. */ - @Override + @Generated public String getKid() { return this.kid; } /** - * {@inheritDoc} - */ - @Override - public DeletedSecretBundle setValue(String value) { - super.setValue(value); - return this; - } - - /** - * {@inheritDoc} + * Get the managed property: True if the secret's lifetime is managed by key vault. If this is a secret backing a + * certificate, then managed will be true. + * + * @return the managed value. */ - @Override - public DeletedSecretBundle setId(String id) { - super.setId(id); - return this; + @Generated + public Boolean isManaged() { + return this.managed; } /** - * {@inheritDoc} + * Get the recoveryId property: The url of the recovery object, used to identify and recover the deleted secret. + * + * @return the recoveryId value. */ - @Override - public DeletedSecretBundle setContentType(String contentType) { - super.setContentType(contentType); - return this; + @Generated + public String getRecoveryId() { + return this.recoveryId; } /** - * {@inheritDoc} + * Get the scheduledPurgeDate property: The time when the secret is scheduled to be purged, in UTC. + * + * @return the scheduledPurgeDate value. */ - @Override - public DeletedSecretBundle setAttributes(SecretAttributes attributes) { - super.setAttributes(attributes); - return this; + @Generated + public OffsetDateTime getScheduledPurgeDate() { + if (this.scheduledPurgeDate == null) { + return null; + } + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.scheduledPurgeDate), ZoneOffset.UTC); } /** - * {@inheritDoc} + * Get the deletedDate property: The time when the secret was deleted, in UTC. + * + * @return the deletedDate value. */ - @Override - public DeletedSecretBundle setTags(Map tags) { - super.setTags(tags); - return this; + @Generated + public OffsetDateTime getDeletedDate() { + if (this.deletedDate == null) { + return null; + } + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.deletedDate), ZoneOffset.UTC); } /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeStringField("value", getValue()); - jsonWriter.writeStringField("id", getId()); - jsonWriter.writeStringField("contentType", getContentType()); - jsonWriter.writeJsonField("attributes", getAttributes()); - jsonWriter.writeMapField("tags", getTags(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("value", this.value); + jsonWriter.writeStringField("id", this.id); + jsonWriter.writeStringField("contentType", this.contentType); + jsonWriter.writeJsonField("attributes", this.attributes); + jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); jsonWriter.writeStringField("recoveryId", this.recoveryId); return jsonWriter.writeEndObject(); } /** * Reads an instance of DeletedSecretBundle from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of DeletedSecretBundle 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 DeletedSecretBundle. */ + @Generated public static DeletedSecretBundle fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { DeletedSecretBundle deserializedDeletedSecretBundle = new DeletedSecretBundle(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("value".equals(fieldName)) { - deserializedDeletedSecretBundle.setValue(reader.getString()); + deserializedDeletedSecretBundle.value = reader.getString(); } else if ("id".equals(fieldName)) { - deserializedDeletedSecretBundle.setId(reader.getString()); + deserializedDeletedSecretBundle.id = reader.getString(); } else if ("contentType".equals(fieldName)) { - deserializedDeletedSecretBundle.setContentType(reader.getString()); + deserializedDeletedSecretBundle.contentType = reader.getString(); } else if ("attributes".equals(fieldName)) { - deserializedDeletedSecretBundle.setAttributes(SecretAttributes.fromJson(reader)); + deserializedDeletedSecretBundle.attributes = SecretAttributes.fromJson(reader); } else if ("tags".equals(fieldName)) { Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedDeletedSecretBundle.setTags(tags); + deserializedDeletedSecretBundle.tags = tags; } else if ("kid".equals(fieldName)) { deserializedDeletedSecretBundle.kid = reader.getString(); } else if ("managed".equals(fieldName)) { @@ -219,7 +255,6 @@ public static DeletedSecretBundle fromJson(JsonReader jsonReader) throws IOExcep reader.skipChildren(); } } - return deserializedDeletedSecretBundle; }); } diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletedSecretItem.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletedSecretItem.java index 7796427df1e5..1d1f7cc403c6 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletedSecretItem.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletedSecretItem.java @@ -1,11 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.secrets.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +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; @@ -17,164 +18,191 @@ /** * The deleted secret item containing metadata about the deleted secret. */ -@Fluent -public final class DeletedSecretItem extends SecretItem { +@Immutable +public final class DeletedSecretItem implements JsonSerializable { + /* - * The url of the recovery object, used to identify and recover the deleted secret. + * Secret identifier. */ - private String recoveryId; + @Generated + private String id; /* - * The time when the secret is scheduled to be purged, in UTC + * The secret management attributes. */ - private Long scheduledPurgeDate; + @Generated + private SecretAttributes attributes; /* - * The time when the secret was deleted, in UTC + * Application specific metadata in the form of key-value pairs. */ - private Long deletedDate; + @Generated + private Map tags; + + /* + * Type of the secret value such as a password. + */ + @Generated + private String contentType; /* * True if the secret's lifetime is managed by key vault. If this is a key backing a certificate, then managed will * be true. */ + @Generated private Boolean managed; + /* + * The url of the recovery object, used to identify and recover the deleted secret. + */ + @Generated + private String recoveryId; + + /* + * The time when the secret is scheduled to be purged, in UTC + */ + @Generated + private Long scheduledPurgeDate; + + /* + * The time when the secret was deleted, in UTC + */ + @Generated + private Long deletedDate; + /** * Creates an instance of DeletedSecretItem class. */ - public DeletedSecretItem() { + @Generated + private DeletedSecretItem() { } /** - * Get the recoveryId property: The url of the recovery object, used to identify and recover the deleted secret. - * - * @return the recoveryId value. + * Get the id property: Secret identifier. + * + * @return the id value. */ - public String getRecoveryId() { - return this.recoveryId; + @Generated + public String getId() { + return this.id; } /** - * Set the recoveryId property: The url of the recovery object, used to identify and recover the deleted secret. - * - * @param recoveryId the recoveryId value to set. - * @return the DeletedSecretItem object itself. - */ - public DeletedSecretItem setRecoveryId(String recoveryId) { - this.recoveryId = recoveryId; - return this; + * Get the attributes property: The secret management attributes. + * + * @return the attributes value. + */ + @Generated + public SecretAttributes getAttributes() { + return this.attributes; } /** - * Get the scheduledPurgeDate property: The time when the secret is scheduled to be purged, in UTC. - * - * @return the scheduledPurgeDate value. + * Get the tags property: Application specific metadata in the form of key-value pairs. + * + * @return the tags value. */ - public OffsetDateTime getScheduledPurgeDate() { - if (this.scheduledPurgeDate == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.scheduledPurgeDate), ZoneOffset.UTC); + @Generated + public Map getTags() { + return this.tags; } /** - * Get the deletedDate property: The time when the secret was deleted, in UTC. - * - * @return the deletedDate value. + * Get the contentType property: Type of the secret value such as a password. + * + * @return the contentType value. */ - public OffsetDateTime getDeletedDate() { - if (this.deletedDate == null) { - return null; - } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.deletedDate), ZoneOffset.UTC); + @Generated + public String getContentType() { + return this.contentType; } /** * Get the managed property: True if the secret's lifetime is managed by key vault. If this is a key backing a * certificate, then managed will be true. - * + * * @return the managed value. */ - @Override + @Generated public Boolean isManaged() { return this.managed; } /** - * {@inheritDoc} - */ - @Override - public DeletedSecretItem setId(String id) { - super.setId(id); - return this; - } - - /** - * {@inheritDoc} + * Get the recoveryId property: The url of the recovery object, used to identify and recover the deleted secret. + * + * @return the recoveryId value. */ - @Override - public DeletedSecretItem setAttributes(SecretAttributes attributes) { - super.setAttributes(attributes); - return this; + @Generated + public String getRecoveryId() { + return this.recoveryId; } /** - * {@inheritDoc} + * Get the scheduledPurgeDate property: The time when the secret is scheduled to be purged, in UTC. + * + * @return the scheduledPurgeDate value. */ - @Override - public DeletedSecretItem setTags(Map tags) { - super.setTags(tags); - return this; + @Generated + public OffsetDateTime getScheduledPurgeDate() { + if (this.scheduledPurgeDate == null) { + return null; + } + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.scheduledPurgeDate), ZoneOffset.UTC); } /** - * {@inheritDoc} + * Get the deletedDate property: The time when the secret was deleted, in UTC. + * + * @return the deletedDate value. */ - @Override - public DeletedSecretItem setContentType(String contentType) { - super.setContentType(contentType); - return this; + @Generated + public OffsetDateTime getDeletedDate() { + if (this.deletedDate == null) { + return null; + } + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.deletedDate), ZoneOffset.UTC); } /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeStringField("id", getId()); - jsonWriter.writeJsonField("attributes", getAttributes()); - jsonWriter.writeMapField("tags", getTags(), (writer, element) -> writer.writeString(element)); - jsonWriter.writeStringField("contentType", getContentType()); + jsonWriter.writeStringField("id", this.id); + jsonWriter.writeJsonField("attributes", this.attributes); + jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("contentType", this.contentType); jsonWriter.writeStringField("recoveryId", this.recoveryId); return jsonWriter.writeEndObject(); } /** * Reads an instance of DeletedSecretItem from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of DeletedSecretItem 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 DeletedSecretItem. */ + @Generated public static DeletedSecretItem fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { DeletedSecretItem deserializedDeletedSecretItem = new DeletedSecretItem(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("id".equals(fieldName)) { - deserializedDeletedSecretItem.setId(reader.getString()); + deserializedDeletedSecretItem.id = reader.getString(); } else if ("attributes".equals(fieldName)) { - deserializedDeletedSecretItem.setAttributes(SecretAttributes.fromJson(reader)); + deserializedDeletedSecretItem.attributes = SecretAttributes.fromJson(reader); } else if ("tags".equals(fieldName)) { Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedDeletedSecretItem.setTags(tags); + deserializedDeletedSecretItem.tags = tags; } else if ("contentType".equals(fieldName)) { - deserializedDeletedSecretItem.setContentType(reader.getString()); + deserializedDeletedSecretItem.contentType = reader.getString(); } else if ("managed".equals(fieldName)) { deserializedDeletedSecretItem.managed = reader.getNullable(JsonReader::getBoolean); } else if ("recoveryId".equals(fieldName)) { @@ -187,7 +215,6 @@ public static DeletedSecretItem fromJson(JsonReader jsonReader) throws IOExcepti reader.skipChildren(); } } - return deserializedDeletedSecretItem; }); } diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletedSecretListResult.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletedSecretListResult.java deleted file mode 100644 index 62d91307493d..000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletedSecretListResult.java +++ /dev/null @@ -1,93 +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.security.keyvault.secrets.implementation.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; -import java.util.List; - -/** - * The deleted secret list result. - */ -@Immutable -public final class DeletedSecretListResult implements JsonSerializable { - /* - * A response message containing a list of the deleted secrets in the vault along with a link to the next page of - * deleted secrets - */ - private List value; - - /* - * The URL to get the next set of deleted secrets. - */ - private String nextLink; - - /** - * Creates an instance of DeletedSecretListResult class. - */ - public DeletedSecretListResult() { - } - - /** - * Get the value property: A response message containing a list of the deleted secrets in the vault along with a - * link to the next page of deleted secrets. - * - * @return the value value. - */ - public List getValue() { - return this.value; - } - - /** - * Get the nextLink property: The URL to get the next set of deleted secrets. - * - * @return the nextLink value. - */ - public String getNextLink() { - return this.nextLink; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of DeletedSecretListResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of DeletedSecretListResult 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 DeletedSecretListResult. - */ - public static DeletedSecretListResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - DeletedSecretListResult deserializedDeletedSecretListResult = new DeletedSecretListResult(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - List value = reader.readArray(reader1 -> DeletedSecretItem.fromJson(reader1)); - deserializedDeletedSecretListResult.value = value; - } else if ("nextLink".equals(fieldName)) { - deserializedDeletedSecretListResult.nextLink = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedDeletedSecretListResult; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletionRecoveryLevel.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletionRecoveryLevel.java index 33351dbfc1ba..f82e7a167db8 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletionRecoveryLevel.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/DeletionRecoveryLevel.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.secrets.implementation.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -13,11 +13,13 @@ * secret, at the end of the retention interval. */ public final class DeletionRecoveryLevel extends ExpandableStringEnum { + /** * Denotes a vault state in which deletion is an irreversible operation, without the possibility for recovery. This * level corresponds to no protection being available against a Delete operation; the data is irretrievably lost * upon accepting a Delete operation at the entity level or higher (vault, resource group, subscription etc.). */ + @Generated public static final DeletionRecoveryLevel PURGEABLE = fromString("Purgeable"); /** @@ -26,14 +28,16 @@ public final class DeletionRecoveryLevel extends ExpandableStringEnum values() { return values(DeletionRecoveryLevel.class); } diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/Error.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/Error.java deleted file mode 100644 index ea1218e5c05f..000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/Error.java +++ /dev/null @@ -1,105 +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.security.keyvault.secrets.implementation.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 key vault server error. - */ -@Immutable -public final class Error implements JsonSerializable { - /* - * The error code. - */ - private String code; - - /* - * The error message. - */ - private String message; - - /* - * The key vault server error. - */ - private Error innerError; - - /** - * Creates an instance of Error class. - */ - public Error() { - } - - /** - * Get the code property: The error code. - * - * @return the code value. - */ - public String getCode() { - return this.code; - } - - /** - * Get the message property: The error message. - * - * @return the message value. - */ - public String getMessage() { - return this.message; - } - - /** - * Get the innerError property: The key vault server error. - * - * @return the innerError value. - */ - public Error getInnerError() { - return this.innerError; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of Error from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of Error 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 Error. - */ - public static Error fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - Error deserializedError = new Error(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("code".equals(fieldName)) { - deserializedError.code = reader.getString(); - } else if ("message".equals(fieldName)) { - deserializedError.message = reader.getString(); - } else if ("innererror".equals(fieldName)) { - deserializedError.innerError = Error.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedError; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/KeyVaultError.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/KeyVaultError.java deleted file mode 100644 index 67f004980d7f..000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/KeyVaultError.java +++ /dev/null @@ -1,73 +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.security.keyvault.secrets.implementation.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 key vault error exception. - */ -@Immutable -public final class KeyVaultError implements JsonSerializable { - /* - * The key vault server error. - */ - private Error error; - - /** - * Creates an instance of KeyVaultError class. - */ - public KeyVaultError() { - } - - /** - * Get the error property: The key vault server error. - * - * @return the error value. - */ - public Error getError() { - return this.error; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KeyVaultError from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KeyVaultError 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 KeyVaultError. - */ - public static KeyVaultError fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KeyVaultError deserializedKeyVaultError = new KeyVaultError(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("error".equals(fieldName)) { - deserializedKeyVaultError.error = Error.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedKeyVaultError; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/KeyVaultErrorException.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/KeyVaultErrorException.java deleted file mode 100644 index 50b18ba8ce65..000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/KeyVaultErrorException.java +++ /dev/null @@ -1,42 +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.security.keyvault.secrets.implementation.models; - -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpResponse; - -/** - * Exception thrown for an invalid response with KeyVaultError information. - */ -public final class KeyVaultErrorException extends HttpResponseException { - /** - * Initializes a new instance of the KeyVaultErrorException class. - * - * @param message the exception message or the response content if a message is not available. - * @param response the HTTP response. - */ - public KeyVaultErrorException(String message, HttpResponse response) { - super(message, response); - } - - /** - * Initializes a new instance of the KeyVaultErrorException 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 KeyVaultErrorException(String message, HttpResponse response, KeyVaultError value) { - super(message, response, value); - } - - /** - * {@inheritDoc} - */ - @Override - public KeyVaultError getValue() { - return (KeyVaultError) super.getValue(); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretAttributes.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretAttributes.java index 33a3b08b6122..5135d4640a1b 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretAttributes.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretAttributes.java @@ -1,11 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.secrets.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; @@ -17,75 +18,145 @@ * The secret management attributes. */ @Fluent -public final class SecretAttributes extends Attributes { +public final class SecretAttributes implements JsonSerializable { + /* - * softDelete data retention days. Value should be >=7 and <=90 when softDelete enabled, otherwise 0. + * Determines whether the object is enabled. */ - private Integer recoverableDays; + @Generated + private Boolean enabled; /* - * Reflects the deletion recovery level currently in effect for secrets in the current vault. If it contains - * 'Purgeable', the secret can be permanently deleted by a privileged user; otherwise, only the system can purge the - * secret, at the end of the retention interval. + * Not before date in UTC. */ - private DeletionRecoveryLevel recoveryLevel; + @Generated + private Long notBefore; /* - * Last updated time in UTC. + * Expiry date in UTC. */ - private Long updated; + @Generated + private Long expires; /* * Creation time in UTC. */ + @Generated private Long created; + /* + * Last updated time in UTC. + */ + @Generated + private Long updated; + + /* + * softDelete data retention days. Value should be >=7 and <=90 when softDelete enabled, otherwise 0. + */ + @Generated + private Integer recoverableDays; + + /* + * Reflects the deletion recovery level currently in effect for secrets in the current vault. If it contains + * 'Purgeable', the secret can be permanently deleted by a privileged user; otherwise, only the system can purge the + * secret, at the end of the retention interval. + */ + @Generated + private DeletionRecoveryLevel recoveryLevel; + /** * Creates an instance of SecretAttributes class. */ + @Generated public SecretAttributes() { } /** - * Get the recoverableDays property: softDelete data retention days. Value should be >=7 and <=90 when - * softDelete enabled, otherwise 0. - * - * @return the recoverableDays value. + * Get the enabled property: Determines whether the object is enabled. + * + * @return the enabled value. */ - public Integer getRecoverableDays() { - return this.recoverableDays; + @Generated + public Boolean isEnabled() { + return this.enabled; } /** - * Get the recoveryLevel property: Reflects the deletion recovery level currently in effect for secrets in the - * current vault. If it contains 'Purgeable', the secret can be permanently deleted by a privileged user; otherwise, - * only the system can purge the secret, at the end of the retention interval. - * - * @return the recoveryLevel value. + * Set the enabled property: Determines whether the object is enabled. + * + * @param enabled the enabled value to set. + * @return the SecretAttributes object itself. */ - public DeletionRecoveryLevel getRecoveryLevel() { - return this.recoveryLevel; + @Generated + public SecretAttributes setEnabled(Boolean enabled) { + this.enabled = enabled; + return this; } /** - * Get the updated property: Last updated time in UTC. - * - * @return the updated value. + * Get the notBefore property: Not before date in UTC. + * + * @return the notBefore value. */ - @Override - public OffsetDateTime getUpdated() { - if (this.updated == null) { + @Generated + public OffsetDateTime getNotBefore() { + if (this.notBefore == null) { return null; } - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.updated), ZoneOffset.UTC); + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.notBefore), ZoneOffset.UTC); + } + + /** + * Set the notBefore property: Not before date in UTC. + * + * @param notBefore the notBefore value to set. + * @return the SecretAttributes object itself. + */ + @Generated + public SecretAttributes setNotBefore(OffsetDateTime notBefore) { + if (notBefore == null) { + this.notBefore = null; + } else { + this.notBefore = notBefore.toEpochSecond(); + } + return this; + } + + /** + * Get the expires property: Expiry date in UTC. + * + * @return the expires value. + */ + @Generated + public OffsetDateTime getExpires() { + if (this.expires == null) { + return null; + } + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.expires), ZoneOffset.UTC); + } + + /** + * Set the expires property: Expiry date in UTC. + * + * @param expires the expires value to set. + * @return the SecretAttributes object itself. + */ + @Generated + public SecretAttributes setExpires(OffsetDateTime expires) { + if (expires == null) { + this.expires = null; + } else { + this.expires = expires.toEpochSecond(); + } + return this; } /** * Get the created property: Creation time in UTC. - * + * * @return the created value. */ - @Override + @Generated public OffsetDateTime getCreated() { if (this.created == null) { return null; @@ -94,77 +165,75 @@ public OffsetDateTime getCreated() { } /** - * {@inheritDoc} + * Get the updated property: Last updated time in UTC. + * + * @return the updated value. */ - @Override - public SecretAttributes setEnabled(Boolean enabled) { - super.setEnabled(enabled); - return this; + @Generated + public OffsetDateTime getUpdated() { + if (this.updated == null) { + return null; + } + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.updated), ZoneOffset.UTC); } /** - * {@inheritDoc} + * Get the recoverableDays property: softDelete data retention days. Value should be >=7 and <=90 when + * softDelete enabled, otherwise 0. + * + * @return the recoverableDays value. */ - @Override - public SecretAttributes setNotBefore(OffsetDateTime notBefore) { - super.setNotBefore(notBefore); - return this; + @Generated + public Integer getRecoverableDays() { + return this.recoverableDays; } /** - * {@inheritDoc} + * Get the recoveryLevel property: Reflects the deletion recovery level currently in effect for secrets in the + * current vault. If it contains 'Purgeable', the secret can be permanently deleted by a privileged user; otherwise, + * only the system can purge the secret, at the end of the retention interval. + * + * @return the recoveryLevel value. */ - @Override - public SecretAttributes setExpires(OffsetDateTime expires) { - super.setExpires(expires); - return this; + @Generated + public DeletionRecoveryLevel getRecoveryLevel() { + return this.recoveryLevel; } /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeBooleanField("enabled", isEnabled()); - if (getNotBefore() != null) { - jsonWriter.writeNumberField("nbf", getNotBefore().toEpochSecond()); - } - if (getExpires() != null) { - jsonWriter.writeNumberField("exp", getExpires().toEpochSecond()); - } + jsonWriter.writeBooleanField("enabled", this.enabled); + jsonWriter.writeNumberField("nbf", this.notBefore); + jsonWriter.writeNumberField("exp", this.expires); return jsonWriter.writeEndObject(); } /** * Reads an instance of SecretAttributes from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SecretAttributes 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 SecretAttributes. */ + @Generated public static SecretAttributes fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { SecretAttributes deserializedSecretAttributes = new SecretAttributes(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("enabled".equals(fieldName)) { - deserializedSecretAttributes.setEnabled(reader.getNullable(JsonReader::getBoolean)); + deserializedSecretAttributes.enabled = reader.getNullable(JsonReader::getBoolean); } else if ("nbf".equals(fieldName)) { - Long notBeforeHolder = reader.getNullable(JsonReader::getLong); - if (notBeforeHolder != null) { - deserializedSecretAttributes.setNotBefore( - OffsetDateTime.ofInstant(Instant.ofEpochSecond(notBeforeHolder), ZoneOffset.UTC)); - } + deserializedSecretAttributes.notBefore = reader.getNullable(JsonReader::getLong); } else if ("exp".equals(fieldName)) { - Long expiresHolder = reader.getNullable(JsonReader::getLong); - if (expiresHolder != null) { - deserializedSecretAttributes - .setExpires(OffsetDateTime.ofInstant(Instant.ofEpochSecond(expiresHolder), ZoneOffset.UTC)); - } + deserializedSecretAttributes.expires = reader.getNullable(JsonReader::getLong); } else if ("created".equals(fieldName)) { deserializedSecretAttributes.created = reader.getNullable(JsonReader::getLong); } else if ("updated".equals(fieldName)) { @@ -177,7 +246,6 @@ public static SecretAttributes fromJson(JsonReader jsonReader) throws IOExceptio reader.skipChildren(); } } - return deserializedSecretAttributes; }); } diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretBundle.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretBundle.java index 86f56a6754f4..0c14ca98b2a3 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretBundle.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretBundle.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.secrets.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -15,198 +15,136 @@ /** * A secret consisting of a value, id and its attributes. */ -@Fluent -public class SecretBundle implements JsonSerializable { +@Immutable +public final class SecretBundle implements JsonSerializable { + /* * The secret value. */ + @Generated private String value; /* * The secret id. */ + @Generated private String id; /* * The content type of the secret. */ + @Generated private String contentType; /* * The secret management attributes. */ + @Generated private SecretAttributes attributes; /* * Application specific metadata in the form of key-value pairs. */ + @Generated private Map tags; /* * If this is a secret backing a KV certificate, then this field specifies the corresponding key backing the KV * certificate. */ + @Generated private String kid; /* * True if the secret's lifetime is managed by key vault. If this is a secret backing a certificate, then managed * will be true. */ + @Generated private Boolean managed; /** * Creates an instance of SecretBundle class. */ - public SecretBundle() { + @Generated + private SecretBundle() { } /** * Get the value property: The secret value. - * + * * @return the value value. */ + @Generated public String getValue() { return this.value; } - /** - * Set the value property: The secret value. - * - * @param value the value value to set. - * @return the SecretBundle object itself. - */ - public SecretBundle setValue(String value) { - this.value = value; - return this; - } - /** * Get the id property: The secret id. - * + * * @return the id value. */ + @Generated public String getId() { return this.id; } - /** - * Set the id property: The secret id. - * - * @param id the id value to set. - * @return the SecretBundle object itself. - */ - public SecretBundle setId(String id) { - this.id = id; - return this; - } - /** * Get the contentType property: The content type of the secret. - * + * * @return the contentType value. */ + @Generated public String getContentType() { return this.contentType; } - /** - * Set the contentType property: The content type of the secret. - * - * @param contentType the contentType value to set. - * @return the SecretBundle object itself. - */ - public SecretBundle setContentType(String contentType) { - this.contentType = contentType; - return this; - } - /** * Get the attributes property: The secret management attributes. - * + * * @return the attributes value. */ + @Generated public SecretAttributes getAttributes() { return this.attributes; } - /** - * Set the attributes property: The secret management attributes. - * - * @param attributes the attributes value to set. - * @return the SecretBundle object itself. - */ - public SecretBundle setAttributes(SecretAttributes attributes) { - this.attributes = attributes; - return this; - } - /** * Get the tags property: Application specific metadata in the form of key-value pairs. - * + * * @return the tags value. */ + @Generated public Map getTags() { return this.tags; } - /** - * Set the tags property: Application specific metadata in the form of key-value pairs. - * - * @param tags the tags value to set. - * @return the SecretBundle object itself. - */ - public SecretBundle setTags(Map tags) { - this.tags = tags; - return this; - } - /** * Get the kid property: If this is a secret backing a KV certificate, then this field specifies the corresponding * key backing the KV certificate. - * + * * @return the kid value. */ + @Generated public String getKid() { return this.kid; } - /** - * Set the kid property: If this is a secret backing a KV certificate, then this field specifies the corresponding - * key backing the KV certificate. - * - * @param kid the kid value to set. - * @return the SecretBundle object itself. - */ - SecretBundle setKid(String kid) { - this.kid = kid; - return this; - } - /** * Get the managed property: True if the secret's lifetime is managed by key vault. If this is a secret backing a * certificate, then managed will be true. - * + * * @return the managed value. */ + @Generated public Boolean isManaged() { return this.managed; } - /** - * Set the managed property: True if the secret's lifetime is managed by key vault. If this is a secret backing a - * certificate, then managed will be true. - * - * @param managed the managed value to set. - * @return the SecretBundle object itself. - */ - SecretBundle setManaged(Boolean managed) { - this.managed = managed; - return this; - } - /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -220,19 +158,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SecretBundle from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SecretBundle 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 SecretBundle. */ + @Generated public static SecretBundle fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { SecretBundle deserializedSecretBundle = new SecretBundle(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("value".equals(fieldName)) { deserializedSecretBundle.value = reader.getString(); } else if ("id".equals(fieldName)) { @@ -252,7 +190,6 @@ public static SecretBundle fromJson(JsonReader jsonReader) throws IOException { reader.skipChildren(); } } - return deserializedSecretBundle; }); } diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretItem.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretItem.java index a999777b0f37..c5debaaaccc4 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretItem.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretItem.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.secrets.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -15,145 +15,102 @@ /** * The secret item containing secret metadata. */ -@Fluent -public class SecretItem implements JsonSerializable { +@Immutable +public final class SecretItem implements JsonSerializable { + /* * Secret identifier. */ + @Generated private String id; /* * The secret management attributes. */ + @Generated private SecretAttributes attributes; /* * Application specific metadata in the form of key-value pairs. */ + @Generated private Map tags; /* * Type of the secret value such as a password. */ + @Generated private String contentType; /* * True if the secret's lifetime is managed by key vault. If this is a key backing a certificate, then managed will * be true. */ + @Generated private Boolean managed; /** * Creates an instance of SecretItem class. */ - public SecretItem() { + @Generated + private SecretItem() { } /** * Get the id property: Secret identifier. - * + * * @return the id value. */ + @Generated public String getId() { return this.id; } - /** - * Set the id property: Secret identifier. - * - * @param id the id value to set. - * @return the SecretItem object itself. - */ - public SecretItem setId(String id) { - this.id = id; - return this; - } - /** * Get the attributes property: The secret management attributes. - * + * * @return the attributes value. */ + @Generated public SecretAttributes getAttributes() { return this.attributes; } - /** - * Set the attributes property: The secret management attributes. - * - * @param attributes the attributes value to set. - * @return the SecretItem object itself. - */ - public SecretItem setAttributes(SecretAttributes attributes) { - this.attributes = attributes; - return this; - } - /** * Get the tags property: Application specific metadata in the form of key-value pairs. - * + * * @return the tags value. */ + @Generated public Map getTags() { return this.tags; } - /** - * Set the tags property: Application specific metadata in the form of key-value pairs. - * - * @param tags the tags value to set. - * @return the SecretItem object itself. - */ - public SecretItem setTags(Map tags) { - this.tags = tags; - return this; - } - /** * Get the contentType property: Type of the secret value such as a password. - * + * * @return the contentType value. */ + @Generated public String getContentType() { return this.contentType; } - /** - * Set the contentType property: Type of the secret value such as a password. - * - * @param contentType the contentType value to set. - * @return the SecretItem object itself. - */ - public SecretItem setContentType(String contentType) { - this.contentType = contentType; - return this; - } - /** * Get the managed property: True if the secret's lifetime is managed by key vault. If this is a key backing a * certificate, then managed will be true. - * + * * @return the managed value. */ + @Generated public Boolean isManaged() { return this.managed; } - /** - * Set the managed property: True if the secret's lifetime is managed by key vault. If this is a key backing a - * certificate, then managed will be true. - * - * @param managed the managed value to set. - * @return the SecretItem object itself. - */ - SecretItem setManaged(Boolean managed) { - this.managed = managed; - return this; - } - /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -166,19 +123,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SecretItem from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SecretItem 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 SecretItem. */ + @Generated public static SecretItem fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { SecretItem deserializedSecretItem = new SecretItem(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("id".equals(fieldName)) { deserializedSecretItem.id = reader.getString(); } else if ("attributes".equals(fieldName)) { @@ -194,7 +151,6 @@ public static SecretItem fromJson(JsonReader jsonReader) throws IOException { reader.skipChildren(); } } - return deserializedSecretItem; }); } diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretListResult.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretListResult.java deleted file mode 100644 index 3b55cb272de6..000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretListResult.java +++ /dev/null @@ -1,92 +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.security.keyvault.secrets.implementation.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; -import java.util.List; - -/** - * The secret list result. - */ -@Immutable -public final class SecretListResult implements JsonSerializable { - /* - * A response message containing a list of secrets in the key vault along with a link to the next page of secrets. - */ - private List value; - - /* - * The URL to get the next set of secrets. - */ - private String nextLink; - - /** - * Creates an instance of SecretListResult class. - */ - public SecretListResult() { - } - - /** - * Get the value property: A response message containing a list of secrets in the key vault along with a link to the - * next page of secrets. - * - * @return the value value. - */ - public List getValue() { - return this.value; - } - - /** - * Get the nextLink property: The URL to get the next set of secrets. - * - * @return the nextLink value. - */ - public String getNextLink() { - return this.nextLink; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SecretListResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SecretListResult 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 SecretListResult. - */ - public static SecretListResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SecretListResult deserializedSecretListResult = new SecretListResult(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - List value = reader.readArray(reader1 -> SecretItem.fromJson(reader1)); - deserializedSecretListResult.value = value; - } else if ("nextLink".equals(fieldName)) { - deserializedSecretListResult.nextLink = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedSecretListResult; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretProperties.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretProperties.java deleted file mode 100644 index 12e7f9132c16..000000000000 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretProperties.java +++ /dev/null @@ -1,85 +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.security.keyvault.secrets.implementation.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; - -/** - * Properties of the key backing a certificate. - */ -@Fluent -public final class SecretProperties implements JsonSerializable { - /* - * The media type (MIME type). - */ - private String contentType; - - /** - * Creates an instance of SecretProperties class. - */ - public SecretProperties() { - } - - /** - * Get the contentType property: The media type (MIME type). - * - * @return the contentType value. - */ - public String getContentType() { - return this.contentType; - } - - /** - * Set the contentType property: The media type (MIME type). - * - * @param contentType the contentType value to set. - * @return the SecretProperties object itself. - */ - public SecretProperties setContentType(String contentType) { - this.contentType = contentType; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("contentType", this.contentType); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SecretProperties from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SecretProperties 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 SecretProperties. - */ - public static SecretProperties fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SecretProperties deserializedSecretProperties = new SecretProperties(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("contentType".equals(fieldName)) { - deserializedSecretProperties.contentType = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedSecretProperties; - }); - } -} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretRestoreParameters.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretRestoreParameters.java index b4bd7300816f..7c63a735d475 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretRestoreParameters.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretRestoreParameters.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.secrets.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; import com.azure.core.util.Base64Url; -import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -17,24 +16,35 @@ /** * The secret restore parameters. */ -@Fluent +@Immutable public final class SecretRestoreParameters implements JsonSerializable { + /* * The backup blob associated with a secret bundle. */ - private Base64Url secretBundleBackup; + @Generated + private final Base64Url secretBundleBackup; /** * Creates an instance of SecretRestoreParameters class. + * + * @param secretBundleBackup the secretBundleBackup value to set. */ - public SecretRestoreParameters() { + @Generated + public SecretRestoreParameters(byte[] secretBundleBackup) { + if (secretBundleBackup == null) { + this.secretBundleBackup = null; + } else { + this.secretBundleBackup = Base64Url.encode(secretBundleBackup); + } } /** * Get the secretBundleBackup property: The backup blob associated with a secret bundle. - * + * * @return the secretBundleBackup value. */ + @Generated public byte[] getSecretBundleBackup() { if (this.secretBundleBackup == null) { return null; @@ -42,24 +52,10 @@ public byte[] getSecretBundleBackup() { return this.secretBundleBackup.decodedBytes(); } - /** - * Set the secretBundleBackup property: The backup blob associated with a secret bundle. - * - * @param secretBundleBackup the secretBundleBackup value to set. - * @return the SecretRestoreParameters object itself. - */ - public SecretRestoreParameters setSecretBundleBackup(byte[] secretBundleBackup) { - if (secretBundleBackup == null) { - this.secretBundleBackup = null; - } else { - this.secretBundleBackup = Base64Url.encode(CoreUtils.clone(secretBundleBackup)); - } - return this; - } - /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -69,29 +65,31 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SecretRestoreParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SecretRestoreParameters 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 SecretRestoreParameters. */ + @Generated public static SecretRestoreParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - SecretRestoreParameters deserializedSecretRestoreParameters = new SecretRestoreParameters(); + byte[] secretBundleBackup = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("value".equals(fieldName)) { - deserializedSecretRestoreParameters.secretBundleBackup + Base64Url secretBundleBackupHolder = reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString())); + if (secretBundleBackupHolder != null) { + secretBundleBackup = secretBundleBackupHolder.decodedBytes(); + } } else { reader.skipChildren(); } } - - return deserializedSecretRestoreParameters; + return new SecretRestoreParameters(secretBundleBackup); }); } } diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretSetParameters.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretSetParameters.java index 2e968c4ee899..1b5f32334204 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretSetParameters.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretSetParameters.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.secrets.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -17,107 +17,112 @@ */ @Fluent public final class SecretSetParameters implements JsonSerializable { + /* * The value of the secret. */ - private String value; + @Generated + private final String value; /* * Application specific metadata in the form of key-value pairs. */ + @Generated private Map tags; /* * Type of the secret value such as a password. */ - private String secretContentType; + @Generated + private String contentType; /* * The secret management attributes. */ + @Generated private SecretAttributes secretAttributes; /** * Creates an instance of SecretSetParameters class. + * + * @param value the value value to set. */ - public SecretSetParameters() { + @Generated + public SecretSetParameters(String value) { + this.value = value; } /** * Get the value property: The value of the secret. - * + * * @return the value value. */ + @Generated public String getValue() { return this.value; } - /** - * Set the value property: The value of the secret. - * - * @param value the value value to set. - * @return the SecretSetParameters object itself. - */ - public SecretSetParameters setValue(String value) { - this.value = value; - return this; - } - /** * Get the tags property: Application specific metadata in the form of key-value pairs. - * + * * @return the tags value. */ + @Generated public Map getTags() { return this.tags; } /** * Set the tags property: Application specific metadata in the form of key-value pairs. - * + * * @param tags the tags value to set. * @return the SecretSetParameters object itself. */ + @Generated public SecretSetParameters setTags(Map tags) { this.tags = tags; return this; } /** - * Get the secretContentType property: Type of the secret value such as a password. - * - * @return the secretContentType value. + * Get the contentType property: Type of the secret value such as a password. + * + * @return the contentType value. */ - public String getSecretContentType() { - return this.secretContentType; + @Generated + public String getContentType() { + return this.contentType; } /** - * Set the secretContentType property: Type of the secret value such as a password. - * - * @param secretContentType the secretContentType value to set. + * Set the contentType property: Type of the secret value such as a password. + * + * @param contentType the contentType value to set. * @return the SecretSetParameters object itself. */ - public SecretSetParameters setSecretContentType(String secretContentType) { - this.secretContentType = secretContentType; + @Generated + public SecretSetParameters setContentType(String contentType) { + this.contentType = contentType; return this; } /** * Get the secretAttributes property: The secret management attributes. - * + * * @return the secretAttributes value. */ + @Generated public SecretAttributes getSecretAttributes() { return this.secretAttributes; } /** * Set the secretAttributes property: The secret management attributes. - * + * * @param secretAttributes the secretAttributes value to set. * @return the SecretSetParameters object itself. */ + @Generated public SecretSetParameters setSecretAttributes(SecretAttributes secretAttributes) { this.secretAttributes = secretAttributes; return this; @@ -126,46 +131,52 @@ public SecretSetParameters setSecretAttributes(SecretAttributes secretAttributes /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("value", this.value); jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); - jsonWriter.writeStringField("contentType", this.secretContentType); + jsonWriter.writeStringField("contentType", this.contentType); jsonWriter.writeJsonField("attributes", this.secretAttributes); return jsonWriter.writeEndObject(); } /** * Reads an instance of SecretSetParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SecretSetParameters 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 SecretSetParameters. */ + @Generated public static SecretSetParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - SecretSetParameters deserializedSecretSetParameters = new SecretSetParameters(); + String value = null; + Map tags = null; + String contentType = null; + SecretAttributes secretAttributes = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("value".equals(fieldName)) { - deserializedSecretSetParameters.value = reader.getString(); + value = reader.getString(); } else if ("tags".equals(fieldName)) { - Map tags = reader.readMap(reader1 -> reader1.getString()); - deserializedSecretSetParameters.tags = tags; + tags = reader.readMap(reader1 -> reader1.getString()); } else if ("contentType".equals(fieldName)) { - deserializedSecretSetParameters.secretContentType = reader.getString(); + contentType = reader.getString(); } else if ("attributes".equals(fieldName)) { - deserializedSecretSetParameters.secretAttributes = SecretAttributes.fromJson(reader); + secretAttributes = SecretAttributes.fromJson(reader); } else { reader.skipChildren(); } } - + SecretSetParameters deserializedSecretSetParameters = new SecretSetParameters(value); + deserializedSecretSetParameters.tags = tags; + deserializedSecretSetParameters.contentType = contentType; + deserializedSecretSetParameters.secretAttributes = secretAttributes; return deserializedSecretSetParameters; }); } diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretUpdateParameters.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretUpdateParameters.java index d0b2f5eed2f2..2822e51319ff 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretUpdateParameters.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretUpdateParameters.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.security.keyvault.secrets.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -17,62 +17,71 @@ */ @Fluent public final class SecretUpdateParameters implements JsonSerializable { + /* * Type of the secret value such as a password. */ - private String secretContentType; + @Generated + private String contentType; /* * The secret management attributes. */ + @Generated private SecretAttributes secretAttributes; /* * Application specific metadata in the form of key-value pairs. */ + @Generated private Map tags; /** * Creates an instance of SecretUpdateParameters class. */ + @Generated public SecretUpdateParameters() { } /** - * Get the secretContentType property: Type of the secret value such as a password. - * - * @return the secretContentType value. + * Get the contentType property: Type of the secret value such as a password. + * + * @return the contentType value. */ - public String getSecretContentType() { - return this.secretContentType; + @Generated + public String getContentType() { + return this.contentType; } /** - * Set the secretContentType property: Type of the secret value such as a password. - * - * @param secretContentType the secretContentType value to set. + * Set the contentType property: Type of the secret value such as a password. + * + * @param contentType the contentType value to set. * @return the SecretUpdateParameters object itself. */ - public SecretUpdateParameters setSecretContentType(String secretContentType) { - this.secretContentType = secretContentType; + @Generated + public SecretUpdateParameters setContentType(String contentType) { + this.contentType = contentType; return this; } /** * Get the secretAttributes property: The secret management attributes. - * + * * @return the secretAttributes value. */ + @Generated public SecretAttributes getSecretAttributes() { return this.secretAttributes; } /** * Set the secretAttributes property: The secret management attributes. - * + * * @param secretAttributes the secretAttributes value to set. * @return the SecretUpdateParameters object itself. */ + @Generated public SecretUpdateParameters setSecretAttributes(SecretAttributes secretAttributes) { this.secretAttributes = secretAttributes; return this; @@ -80,19 +89,21 @@ public SecretUpdateParameters setSecretAttributes(SecretAttributes secretAttribu /** * Get the tags property: Application specific metadata in the form of key-value pairs. - * + * * @return the tags value. */ + @Generated public Map getTags() { return this.tags; } /** * Set the tags property: Application specific metadata in the form of key-value pairs. - * + * * @param tags the tags value to set. * @return the SecretUpdateParameters object itself. */ + @Generated public SecretUpdateParameters setTags(Map tags) { this.tags = tags; return this; @@ -101,10 +112,11 @@ public SecretUpdateParameters setTags(Map tags) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeStringField("contentType", this.secretContentType); + jsonWriter.writeStringField("contentType", this.contentType); jsonWriter.writeJsonField("attributes", this.secretAttributes); jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); return jsonWriter.writeEndObject(); @@ -112,21 +124,21 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SecretUpdateParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SecretUpdateParameters 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 SecretUpdateParameters. */ + @Generated public static SecretUpdateParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { SecretUpdateParameters deserializedSecretUpdateParameters = new SecretUpdateParameters(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("contentType".equals(fieldName)) { - deserializedSecretUpdateParameters.secretContentType = reader.getString(); + deserializedSecretUpdateParameters.contentType = reader.getString(); } else if ("attributes".equals(fieldName)) { deserializedSecretUpdateParameters.secretAttributes = SecretAttributes.fromJson(reader); } else if ("tags".equals(fieldName)) { @@ -136,7 +148,6 @@ public static SecretUpdateParameters fromJson(JsonReader jsonReader) throws IOEx reader.skipChildren(); } } - return deserializedSecretUpdateParameters; }); } diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretsModelsUtils.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretsModelsUtils.java index daa9d2230aed..49f5c3bf8fd1 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretsModelsUtils.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/SecretsModelsUtils.java @@ -122,7 +122,31 @@ public static DeletedSecret createDeletedSecret(DeletedSecretBundle deletedSecre } DeletedSecret deletedSecret = new DeletedSecret(); - setSecretPropertiesValues(deletedSecretBundle, deletedSecret.getProperties()); + + deletedSecret.getProperties() + .setContentType(deletedSecretBundle.getContentType()) + .setTags(deletedSecretBundle.getTags()); + + DeletedSecretHelper.setId(deletedSecret, deletedSecretBundle.getId()); + DeletedSecretHelper.setKeyId(deletedSecret, deletedSecretBundle.getKid()); + DeletedSecretHelper.setManaged(deletedSecret, deletedSecretBundle.isManaged()); + + SecretAttributes secretAttributes = deletedSecretBundle.getAttributes(); + + if (secretAttributes != null) { + deletedSecret.getProperties() + .setEnabled(secretAttributes.isEnabled()) + .setExpiresOn(secretAttributes.getExpires()) + .setNotBefore(secretAttributes.getNotBefore()); + + DeletedSecretHelper.setCreatedOn(deletedSecret, secretAttributes.getCreated()); + DeletedSecretHelper.setUpdatedOn(deletedSecret, secretAttributes.getUpdated()); + DeletedSecretHelper.setRecoveryLevel(deletedSecret, secretAttributes.getRecoveryLevel().toString()); + DeletedSecretHelper.setRecoverableDays(deletedSecret, secretAttributes.getRecoverableDays()); + } + + unpackId(deletedSecretBundle.getId(), name -> DeletedSecretHelper.setName(deletedSecret, name), + version -> DeletedSecretHelper.setVersion(deletedSecret, version)); DeletedSecretHelper.setRecoveryId(deletedSecret, deletedSecretBundle.getRecoveryId()); DeletedSecretHelper.setScheduledPurgeDate(deletedSecret, deletedSecretBundle.getScheduledPurgeDate()); @@ -137,7 +161,30 @@ public static DeletedSecret createDeletedSecret(DeletedSecretItem deletedSecretI } DeletedSecret deletedSecret = new DeletedSecret(); - setSecretPropertiesValues(deletedSecretItem, deletedSecret.getProperties()); + + deletedSecret.getProperties() + .setContentType(deletedSecretItem.getContentType()) + .setTags(deletedSecretItem.getTags()); + + DeletedSecretHelper.setId(deletedSecret, deletedSecretItem.getId()); + DeletedSecretHelper.setManaged(deletedSecret, deletedSecretItem.isManaged()); + + SecretAttributes secretAttributes = deletedSecretItem.getAttributes(); + + if (secretAttributes != null) { + deletedSecret.getProperties() + .setEnabled(secretAttributes.isEnabled()) + .setExpiresOn(secretAttributes.getExpires()) + .setNotBefore(secretAttributes.getNotBefore()); + + DeletedSecretHelper.setCreatedOn(deletedSecret, secretAttributes.getCreated()); + DeletedSecretHelper.setUpdatedOn(deletedSecret, secretAttributes.getUpdated()); + DeletedSecretHelper.setRecoveryLevel(deletedSecret, secretAttributes.getRecoveryLevel().toString()); + DeletedSecretHelper.setRecoverableDays(deletedSecret, secretAttributes.getRecoverableDays()); + } + + unpackId(deletedSecretItem.getId(), name -> DeletedSecretHelper.setName(deletedSecret, name), + version -> DeletedSecretHelper.setVersion(deletedSecret, version)); DeletedSecretHelper.setRecoveryId(deletedSecret, deletedSecretItem.getRecoveryId()); DeletedSecretHelper.setScheduledPurgeDate(deletedSecret, deletedSecretItem.getScheduledPurgeDate()); diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/package-info.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/package-info.java index e43601b6a57b..a77fcb6e8653 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/package-info.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/models/package-info.java @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. /** * Package containing the data models for SecretClient. * The key vault client performs cryptographic key operations and vault operations against the Key Vault service. diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/package-info.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/package-info.java index e199af1c54cf..7edc4e75061f 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/package-info.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/package-info.java @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - +// Code generated by Microsoft (R) TypeSpec Code Generator. /** * Package containing the implementations for SecretClient. * The key vault client performs cryptographic key operations and vault operations against the Key Vault service. diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/DeletedSecret.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/DeletedSecret.java index 9b1359b1ca1d..b2db6174425d 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/DeletedSecret.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/DeletedSecret.java @@ -23,9 +23,53 @@ * @see SecretAsyncClient */ public final class DeletedSecret extends KeyVaultSecret { - static { DeletedSecretHelper.setAccessor(new DeletedSecretHelper.DeletedSecretAccessor() { + @Override + public void setId(DeletedSecret deletedSecret, String id) { + deletedSecret.properties.id = id; + } + + @Override + public void setVersion(DeletedSecret deletedSecret, String version) { + deletedSecret.properties.version = version; + } + + @Override + public void setCreatedOn(DeletedSecret deletedSecret, OffsetDateTime createdOn) { + deletedSecret.properties.createdOn = createdOn; + } + + @Override + public void setUpdatedOn(DeletedSecret deletedSecret, OffsetDateTime updatedOn) { + deletedSecret.properties.updatedOn = updatedOn; + } + + @Override + public void setName(DeletedSecret deletedSecret, String name) { + deletedSecret.properties.name = name; + } + + @Override + public void setRecoveryLevel(DeletedSecret deletedSecret, String recoveryLevel) { + deletedSecret.properties.recoveryLevel = recoveryLevel; + } + + @Override + public void setKeyId(DeletedSecret deletedSecret, String keyId) { + deletedSecret.properties.keyId = keyId; + } + + @Override + public void setManaged(DeletedSecret deletedSecret, Boolean managed) { + deletedSecret.properties.managed = managed; + } + + @Override + public void setRecoverableDays(DeletedSecret deletedSecret, Integer recoverableDays) { + deletedSecret.properties.recoverableDays = recoverableDays; + } + @Override public void setRecoveryId(DeletedSecret deletedSecret, String recoveryId) { deletedSecret.recoveryId = recoveryId; @@ -62,6 +106,7 @@ public void setDeletedOn(DeletedSecret deletedSecret, OffsetDateTime deletedOn) * Creates a new instance of {@link DeletedSecret}. */ public DeletedSecret() { + super(); } /** diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/KeyVaultSecret.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/KeyVaultSecret.java index a56a11ae0d52..18bd92974039 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/KeyVaultSecret.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/KeyVaultSecret.java @@ -36,7 +36,7 @@ public class KeyVaultSecret implements JsonSerializable { SecretProperties properties; /** - * Creates an empty instance of the Secret. + * Creates an empty instance of KeyVaultSecret. This constructor is used by the deserializer. */ KeyVaultSecret() { properties = new SecretProperties(); diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/SecretProperties.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/SecretProperties.java index 554043fbb5c7..0ebc323371d9 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/SecretProperties.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/models/SecretProperties.java @@ -151,7 +151,7 @@ public void setRecoverableDays(SecretProperties properties, Integer recoverableD /** * The number of days a secret is retained before being deleted for a soft delete-enabled Key Vault. */ - private Integer recoverableDays; + Integer recoverableDays; SecretProperties(String secretName) { this.name = secretName; diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/package-info.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/package-info.java index 94fd5bc936d0..05e210a7d6d5 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/package-info.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/package-info.java @@ -1,29 +1,30 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. - /** + * *

          Azure Key Vault is a cloud-based service * provided by Microsoft Azure that allows users to store, manage, and access secrets, such as passwords, certificates, * and other sensitive information, securely in the cloud. The service provides a centralized and secure location for * storing secrets, which can be accessed by authorized applications and users with appropriate permissions. * Azure Key Vault Secrets offers several key features, including:

          *
            - *
          • Secret management: It allows users to store, manage, and access secrets securely, and provides features such - * as versioning, backup, and restoration.
          • - *
          • Access control: It offers - * - * role-based access control (RBAC) and enables users to grant specific permissions to access secrets to - * other users, applications, or services.
          • - *
          • Integration with other Azure services: Azure Key Vault Secrets can be integrated with other Azure services, - * such as Azure App Service, Azure Functions, and Azure Virtual Machines, to simplify the process of securing - * sensitive information.
          • - *
          • High availability and scalability: The service is designed to provide high availability and scalability, - * with the ability to handle large volumes of secrets and requests.
          • + *
          • Secret management: It allows users to store, manage, and access secrets securely, and provides features such + * as versioning, backup, and restoration.
          • + *
          • Access control: It offers + * + * role-based access control (RBAC) and enables users to grant specific permissions to access secrets to + * other users, applications, or services.
          • + *
          • Integration with other Azure services: Azure Key Vault Secrets can be integrated with other Azure services, + * such as Azure App Service, Azure Functions, and Azure Virtual Machines, to simplify the process of securing + * sensitive information.
          • + *
          • High availability and scalability: The service is designed to provide high availability and scalability, + * with the ability to handle large volumes of secrets and requests.
          • *
          * *

          The Azure Key Vault Secrets client library allows developers to interact with the Azure Key Vault service * from their applications. The library provides a set of APIs that enable developers to securely store, manage, and - * retrieve secrets in a key vault, and supports operations such as creating, updating, deleting, and retrieving secrets.

          + * retrieve secrets in a key vault, and supports operations such as creating, updating, deleting, and retrieving + * secrets.

          * *

          Key Concepts:

          * @@ -39,17 +40,18 @@ * specified:

          * *
            - *
          1. enabled: Specifies whether the secret data can be retrieved.
          2. - *
          3. notBefore: Identifies the time after which the secret will be active.
          4. - *
          5. expires: Identifies the expiration time on or after which the secret data should not be retrieved.
          6. - *
          7. created: Indicates when this version of the secret was created.
          8. - *
          9. updated: Indicates when this version of the secret was updated.
          10. + *
          11. enabled: Specifies whether the secret data can be retrieved.
          12. + *
          13. notBefore: Identifies the time after which the secret will be active.
          14. + *
          15. expires: Identifies the expiration time on or after which the secret data should not be retrieved.
          16. + *
          17. created: Indicates when this version of the secret was created.
          18. + *
          19. updated: Indicates when this version of the secret was updated.
          20. *
          * *

          Getting Started

          * *

          In order to interact with the Azure Key Vault service, you will need to create an instance of the - * {@link com.azure.security.keyvault.secrets.SecretClient} or {@link com.azure.security.keyvault.secrets.SecretAsyncClient} class, a vault url and a credential object.

          + * {@link com.azure.security.keyvault.secrets.SecretClient} or + * {@link com.azure.security.keyvault.secrets.SecretAsyncClient} class, a vault url and a credential object.

          * *

          The examples shown in this document use a credential object named DefaultAzureCredential for authentication, * which is appropriate for most scenarios, including local development and production environments. Additionally, @@ -58,7 +60,7 @@ * managed identity for authentication in production environments. * You can find more information on different ways of authenticating and their corresponding credential types in the * - * Azure Identity documentation".

          + * Azure Identity documentation".

          * *

          Sample: Construct Synchronous Secret Client

          * @@ -145,7 +147,8 @@ * *

          Synchronous Code Sample:

          *

          The following code sample demonstrates how to synchronously delete a secret from the - * key vault, using the {@link com.azure.security.keyvault.secrets.SecretClient#beginDeleteSecret(java.lang.String)} API. + * key vault, using the {@link com.azure.security.keyvault.secrets.SecretClient#beginDeleteSecret(java.lang.String)} + * API. *

          * * diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/module-info.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/module-info.java index 2280fd863c41..08ce806cb870 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/module-info.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/module-info.java @@ -1,5 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. module com.azure.security.keyvault.secrets { requires transitive com.azure.core; @@ -8,8 +9,8 @@ exports com.azure.security.keyvault.secrets; exports com.azure.security.keyvault.secrets.models; + opens com.azure.security.keyvault.secrets.implementation.models to com.azure.core; opens com.azure.security.keyvault.secrets to com.azure.core; opens com.azure.security.keyvault.secrets.implementation to com.azure.core; - opens com.azure.security.keyvault.secrets.implementation.models to com.azure.core; opens com.azure.security.keyvault.secrets.models to com.azure.core; } diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-secrets/resource-config.json b/sdk/keyvault/azure-security-keyvault-secrets/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-secrets/resource-config.json index e190caaf40a9..ab85a7e70774 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-secrets/resource-config.json +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/resources/META-INF/native-image/com.azure/azure-security-keyvault-secrets/resource-config.json @@ -2,7 +2,7 @@ "resources": { "includes": [ { - "pattern": "azure-key-vault-secrets.properties" + "pattern": "azure-security-keyvault-secrets.properties" }, { "pattern": "kvErrorStrings.properties" diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/resources/azure-security-keyvault-secrets.properties b/sdk/keyvault/azure-security-keyvault-secrets/src/main/resources/azure-security-keyvault-secrets.properties new file mode 100644 index 000000000000..ca812989b4f2 --- /dev/null +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/resources/azure-security-keyvault-secrets.properties @@ -0,0 +1,2 @@ +name=${project.artifactId} +version=${project.version} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/samples/README.md b/sdk/keyvault/azure-security-keyvault-secrets/src/samples/README.md index c6add772b022..31302647c534 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/samples/README.md +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/samples/README.md @@ -84,4 +84,4 @@ This project welcomes contributions and suggestions. Find [more contributing][SD [sample_ManageDeleted]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/ManagingDeletedSecrets.java [sample_ManageDeletedAsync]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/ManagingDeletedSecretsAsync.java -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fkeyvault%2Fazure-security-keyvault-secrets%2Fsrc%2Fsamples%2FREADME.png) + diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/KeyVaultSecretsUserAgentPropertiesTest.java b/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/KeyVaultSecretsUserAgentPropertiesTest.java index 24d7e65649ae..6148bb86095c 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/KeyVaultSecretsUserAgentPropertiesTest.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/KeyVaultSecretsUserAgentPropertiesTest.java @@ -14,7 +14,7 @@ public class KeyVaultSecretsUserAgentPropertiesTest { @Test public void testAzureConfiguration() { - Map properties = CoreUtils.getProperties("azure-key-vault-secrets.properties"); + Map properties = CoreUtils.getProperties("azure-security-keyvault-secrets.properties"); assertTrue(properties.get("name").matches("azure-security-keyvault-secrets")); assertTrue(properties.get("version").matches("(\\d)+.(\\d)+.(\\d)+([-a-zA-Z0-9.])*")); } 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 3b73717bf38e..54ded6d8a1a2 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 @@ -3,6 +3,7 @@ package com.azure.security.keyvault.secrets; +import com.azure.core.exception.HttpResponseException; import com.azure.core.exception.ResourceModifiedException; import com.azure.core.exception.ResourceNotFoundException; import com.azure.core.http.HttpClient; @@ -12,7 +13,6 @@ import com.azure.core.util.polling.AsyncPollResponse; import com.azure.core.util.polling.PollerFlux; import com.azure.security.keyvault.secrets.implementation.KeyVaultCredentialPolicy; -import com.azure.security.keyvault.secrets.implementation.models.KeyVaultErrorException; import com.azure.security.keyvault.secrets.models.DeletedSecret; import com.azure.security.keyvault.secrets.models.KeyVaultSecret; import com.azure.security.keyvault.secrets.models.SecretProperties; @@ -103,7 +103,7 @@ public void setSecretEmptyName(HttpClient httpClient, SecretServiceVersion servi StepVerifier.create(secretAsyncClient.setSecret("", "A value")) .verifyErrorSatisfies( - e -> assertRestException(e, KeyVaultErrorException.class, HttpURLConnection.HTTP_BAD_METHOD)); + e -> assertRestException(e, HttpResponseException.class, HttpURLConnection.HTTP_BAD_METHOD)); } /** diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretClientBuilderTest.java b/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretClientBuilderTest.java index 142c45abbba3..7f0df112d3a3 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretClientBuilderTest.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretClientBuilderTest.java @@ -152,14 +152,14 @@ public void bothRetryOptionsAndRetryPolicySet() { // and auth would fail because we changed a signed header. @Test public void addPerCallPolicy() { - SecretAsyncClient secretAsyncClient = new SecretClientBuilder().vaultUrl(vaultUrl) + SecretClientBuilder secretClientBuilder = new SecretClientBuilder().vaultUrl(vaultUrl) .credential(new TestUtils.TestCredential()) .addPolicy(new TestUtils.PerCallPolicy()) - .addPolicy(new TestUtils.PerRetryPolicy()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildAsyncClient(); + .addPolicy(new TestUtils.PerRetryPolicy()); + + secretClientBuilder.buildClient(); - HttpPipeline pipeline = secretAsyncClient.getHttpPipeline(); + HttpPipeline pipeline = secretClientBuilder.getPipelineForTest(); int retryPolicyPosition = -1, perCallPolicyPosition = -1, perRetryPolicyPosition = -1; 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 68df398db87e..9629109b55f7 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 @@ -3,6 +3,7 @@ package com.azure.security.keyvault.secrets; +import com.azure.core.exception.HttpResponseException; import com.azure.core.exception.ResourceModifiedException; import com.azure.core.exception.ResourceNotFoundException; import com.azure.core.http.HttpClient; @@ -11,7 +12,6 @@ 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; import com.azure.security.keyvault.secrets.models.DeletedSecret; import com.azure.security.keyvault.secrets.models.KeyVaultSecret; import com.azure.security.keyvault.secrets.models.SecretProperties; @@ -93,7 +93,7 @@ public void setSecretWithMultipleTenants(HttpClient httpClient, SecretServiceVer public void setSecretEmptyName(HttpClient httpClient, SecretServiceVersion serviceVersion) { createClient(httpClient, serviceVersion); - assertRestException(() -> secretClient.setSecret("", "A value"), KeyVaultErrorException.class, + assertRestException(() -> secretClient.setSecret("", "A value"), HttpResponseException.class, HttpURLConnection.HTTP_BAD_METHOD); } diff --git a/sdk/keyvault/azure-security-keyvault-secrets/swagger/pom.xml b/sdk/keyvault/azure-security-keyvault-secrets/swagger/pom.xml new file mode 100644 index 000000000000..f7884b5fb240 --- /dev/null +++ b/sdk/keyvault/azure-security-keyvault-secrets/swagger/pom.xml @@ -0,0 +1,21 @@ + + + 4.0.0 + + + com.azure + azure-code-customization-parent + 1.0.0-beta.1 + ../../../parents/azure-code-customization-parent + + + Microsoft Azure Security Key Vault Secrets code generation customization + This package contains code generation customization for Microsoft Azure Security Key Vault Secrets + + com.azure.tools + azure-security-keyvault-secrets-autorest-customization + 1.0.0-beta.1 + jar + diff --git a/sdk/keyvault/azure-security-keyvault-secrets/swagger/src/main/java/SecretsCustomizations.java b/sdk/keyvault/azure-security-keyvault-secrets/swagger/src/main/java/SecretsCustomizations.java new file mode 100644 index 000000000000..7f7f7748ac92 --- /dev/null +++ b/sdk/keyvault/azure-security-keyvault-secrets/swagger/src/main/java/SecretsCustomizations.java @@ -0,0 +1,41 @@ +// 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.Editor; +import com.azure.autorest.customization.LibraryCustomization; +import org.slf4j.Logger; + +/** + * Contains customizations for Azure KeyVault's Secrets swagger code generation. + */ +public class SecretsCustomizations extends Customization { + @Override + public void customize(LibraryCustomization libraryCustomization, Logger logger) { + // Remove unnecessary files. + removeFiles(libraryCustomization.getRawEditor()); + // Customize the SecretClientImpl class. + customizeClientImpl(libraryCustomization); + } + + private static void removeFiles(Editor editor) { + // Remove the next line in favor of renaming to SecretServiceVersion once the TSP spec includes all service + // versions. + editor.removeFile("src/main/java/com/azure/security/keyvault/secrets/KeyVaultServiceVersion.java"); + editor.removeFile("src/main/java/com/azure/security/keyvault/secrets/SecretAsyncClient.java"); + editor.removeFile("src/main/java/com/azure/security/keyvault/secrets/SecretClient.java"); + editor.removeFile("src/main/java/com/azure/security/keyvault/secrets/SecretClientBuilder.java"); + } + + private static void customizeClientImpl(LibraryCustomization libraryCustomization) { + ClassCustomization classCustomization = libraryCustomization + .getPackage("com.azure.security.keyvault.secrets.implementation") + .getClass("SecretClientImpl"); + String classPath = "src/main/java/com/azure/security/keyvault/secrets/implementation/SecretClientImpl.java"; + Editor editor = classCustomization.getEditor(); + String newFileContent = editor.getFileContent(classPath).replace("KeyVault", "Secret"); + + editor.replaceFile(classPath, newFileContent); + } +} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/tsp-location.yaml b/sdk/keyvault/azure-security-keyvault-secrets/tsp-location.yaml new file mode 100644 index 000000000000..d612ad556ab6 --- /dev/null +++ b/sdk/keyvault/azure-security-keyvault-secrets/tsp-location.yaml @@ -0,0 +1,6 @@ +directory: specification/keyvault/Security.KeyVault.Secrets +commit: 23202def50f87680141866766c62158f2bc82a31 +repo: Azure/azure-rest-api-specs +cleanup: true +additionalDirectories: +- specification/keyvault/Security.KeyVault.Common/ diff --git a/sdk/keyvault/azure-security-test-keyvault-jca/pom.xml b/sdk/keyvault/azure-security-test-keyvault-jca/pom.xml index b4cd497bf149..e924103db53a 100644 --- a/sdk/keyvault/azure-security-test-keyvault-jca/pom.xml +++ b/sdk/keyvault/azure-security-test-keyvault-jca/pom.xml @@ -66,7 +66,7 @@ com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test diff --git a/sdk/keyvault/ci.yml b/sdk/keyvault/ci.yml index 18b2ee5f8366..8aa3060f9fa1 100644 --- a/sdk/keyvault/ci.yml +++ b/sdk/keyvault/ci.yml @@ -94,7 +94,6 @@ extends: groupId: com.azure safeName: azuresecuritykeyvaultjca releaseInBatch: ${{ parameters.release_azuresecuritykeyvaultjca }} - skipPublishDocMs: true - name: azure-security-keyvault-keys groupId: com.azure safeName: azuresecuritykeyvaultkeys diff --git a/sdk/kubernetesconfiguration/azure-resourcemanager-kubernetesconfiguration/README.md b/sdk/kubernetesconfiguration/azure-resourcemanager-kubernetesconfiguration/README.md index 3d2835e6b763..60919f1d9b32 100644 --- a/sdk/kubernetesconfiguration/azure-resourcemanager-kubernetesconfiguration/README.md +++ b/sdk/kubernetesconfiguration/azure-resourcemanager-kubernetesconfiguration/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-kubernetesconfiguration - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fkubernetesconfiguration%2Fazure-resourcemanager-kubernetesconfiguration%2FREADME.png) + diff --git a/sdk/kubernetesconfiguration/azure-resourcemanager-kubernetesconfiguration/pom.xml b/sdk/kubernetesconfiguration/azure-resourcemanager-kubernetesconfiguration/pom.xml index ca22e35b3ad1..c0a8bca3c5ca 100644 --- a/sdk/kubernetesconfiguration/azure-resourcemanager-kubernetesconfiguration/pom.xml +++ b/sdk/kubernetesconfiguration/azure-resourcemanager-kubernetesconfiguration/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/kusto/azure-resourcemanager-kusto/CHANGELOG.md b/sdk/kusto/azure-resourcemanager-kusto/CHANGELOG.md index 8dfc3fdce688..9f31d39bf1af 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/CHANGELOG.md +++ b/sdk/kusto/azure-resourcemanager-kusto/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.2.0-beta.1 (Unreleased) +## 1.3.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,95 @@ ### Other Changes +## 1.2.0 (2025-01-24) + +- Azure Resource Manager Kusto client library for Java. This package contains Microsoft Azure SDK for Kusto Management SDK. The Azure Kusto management API provides a RESTful set of web services that interact with Azure Kusto services to manage your clusters and databases. The API enables you to create, update, and delete clusters and databases. Package tag package-2024-04. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). + +### Features Added + +* `models.FollowerDatabaseDefinitionGet` was added + +* `models.FollowerDatabaseListResultGet` was added + +* `models.ScriptLevel` was added + +* `models.ZoneStatus` was added + +* `models.CalloutType` was added + +* `models.CalloutPolicyToRemove` was added + +* `models.PrincipalPermissionsAction` was added + +* `models.CalloutPoliciesList` was added + +* `models.OutboundAccess` was added + +* `models.CalloutPolicy` was added + +#### `models.Clusters` was modified + +* `listCalloutPolicies(java.lang.String,java.lang.String)` was added +* `listFollowerDatabasesGet(java.lang.String,java.lang.String)` was added +* `addCalloutPolicies(java.lang.String,java.lang.String,models.CalloutPoliciesList,com.azure.core.util.Context)` was added +* `addCalloutPolicies(java.lang.String,java.lang.String,models.CalloutPoliciesList)` was added +* `listFollowerDatabasesGet(java.lang.String,java.lang.String,com.azure.core.util.Context)` was added +* `removeCalloutPolicy(java.lang.String,java.lang.String,models.CalloutPolicyToRemove)` was added +* `removeCalloutPolicy(java.lang.String,java.lang.String,models.CalloutPolicyToRemove,com.azure.core.util.Context)` was added +* `listCalloutPolicies(java.lang.String,java.lang.String,com.azure.core.util.Context)` was added + +#### `models.Script$Definition` was modified + +* `withScriptLevel(models.ScriptLevel)` was added +* `withPrincipalPermissionsAction(models.PrincipalPermissionsAction)` was added + +#### `models.SandboxCustomImage$Definition` was modified + +* `withBaseImageName(java.lang.String)` was added + +#### `models.Cluster` was modified + +* `calloutPolicies()` was added +* `listCalloutPolicies()` was added +* `zoneStatus()` was added +* `removeCalloutPolicy(models.CalloutPolicyToRemove)` was added +* `addCalloutPolicies(models.CalloutPoliciesList,com.azure.core.util.Context)` was added +* `removeCalloutPolicy(models.CalloutPolicyToRemove,com.azure.core.util.Context)` was added +* `addCalloutPolicies(models.CalloutPoliciesList)` was added +* `listCalloutPolicies(com.azure.core.util.Context)` was added + +#### `models.SandboxCustomImage` was modified + +* `baseImageName()` was added + +#### `models.Cluster$Definition` was modified + +* `withCalloutPolicies(java.util.List)` was added + +#### `models.Script` was modified + +* `scriptLevel()` was added +* `principalPermissionsAction()` was added + +#### `models.ClusterUpdate` was modified + +* `withCalloutPolicies(java.util.List)` was added +* `zoneStatus()` was added +* `calloutPolicies()` was added + +#### `models.SandboxCustomImage$Update` was modified + +* `withBaseImageName(java.lang.String)` was added + +#### `models.Cluster$Update` was modified + +* `withCalloutPolicies(java.util.List)` was added + +#### `models.Script$Update` was modified + +* `withScriptLevel(models.ScriptLevel)` was added +* `withPrincipalPermissionsAction(models.PrincipalPermissionsAction)` was added + ## 1.1.0 (2024-12-11) - Azure Resource Manager Kusto client library for Java. This package contains Microsoft Azure SDK for Kusto Management SDK. The Azure Kusto management API provides a RESTful set of web services that interact with Azure Kusto services to manage your clusters and databases. The API enables you to create, update, and delete clusters and databases. Package tag package-2023-08. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). diff --git a/sdk/kusto/azure-resourcemanager-kusto/README.md b/sdk/kusto/azure-resourcemanager-kusto/README.md index 4a292e2206be..240570fb8d66 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/README.md +++ b/sdk/kusto/azure-resourcemanager-kusto/README.md @@ -2,7 +2,7 @@ Azure Resource Manager Kusto client library for Java. -This package contains Microsoft Azure SDK for Kusto Management SDK. The Azure Kusto management API provides a RESTful set of web services that interact with Azure Kusto services to manage your clusters and databases. The API enables you to create, update, and delete clusters and databases. Package tag package-2023-08. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). +This package contains Microsoft Azure SDK for Kusto Management SDK. The Azure Kusto management API provides a RESTful set of web services that interact with Azure Kusto services to manage your clusters and databases. The API enables you to create, update, and delete clusters and databases. Package tag package-2024-04. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). ## We'd love to hear your feedback @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-kusto - 1.1.0 + 1.3.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -111,4 +111,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fkusto%2Fazure-resourcemanager-kusto%2FREADME.png) + diff --git a/sdk/kusto/azure-resourcemanager-kusto/SAMPLE.md b/sdk/kusto/azure-resourcemanager-kusto/SAMPLE.md index fabab83c0505..f66944bbf90b 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/SAMPLE.md +++ b/sdk/kusto/azure-resourcemanager-kusto/SAMPLE.md @@ -19,6 +19,7 @@ ## Clusters +- [AddCalloutPolicies](#clusters_addcalloutpolicies) - [AddLanguageExtensions](#clusters_addlanguageextensions) - [CheckNameAvailability](#clusters_checknameavailability) - [CreateOrUpdate](#clusters_createorupdate) @@ -28,12 +29,15 @@ - [GetByResourceGroup](#clusters_getbyresourcegroup) - [List](#clusters_list) - [ListByResourceGroup](#clusters_listbyresourcegroup) +- [ListCalloutPolicies](#clusters_listcalloutpolicies) - [ListFollowerDatabases](#clusters_listfollowerdatabases) +- [ListFollowerDatabasesGet](#clusters_listfollowerdatabasesget) - [ListLanguageExtensions](#clusters_listlanguageextensions) - [ListOutboundNetworkDependenciesEndpoints](#clusters_listoutboundnetworkdependenciesendpoints) - [ListSkus](#clusters_listskus) - [ListSkusByResource](#clusters_listskusbyresource) - [Migrate](#clusters_migrate) +- [RemoveCalloutPolicy](#clusters_removecalloutpolicy) - [RemoveLanguageExtensions](#clusters_removelanguageextensions) - [Start](#clusters_start) - [Stop](#clusters_stop) @@ -137,7 +141,7 @@ import com.azure.resourcemanager.kusto.models.AttachedDatabaseConfigurationsChec */ public final class AttachedDatabaseConfigurationsCheckNameAvailabilitySamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoAttachedDatabaseConfigurationCheckNameAvailability.json */ /** @@ -167,7 +171,7 @@ import java.util.Arrays; */ public final class AttachedDatabaseConfigurationsCreateOrUpdateSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoAttachedDatabaseConfigurationsCreateOrUpdate.json */ /** @@ -206,7 +210,7 @@ public final class AttachedDatabaseConfigurationsCreateOrUpdateSamples { */ public final class AttachedDatabaseConfigurationsDeleteSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoAttachedDatabaseConfigurationsDelete.json */ /** @@ -230,7 +234,7 @@ public final class AttachedDatabaseConfigurationsDeleteSamples { */ public final class AttachedDatabaseConfigurationsGetSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoAttachedDatabaseConfigurationsGet.json */ /** @@ -254,7 +258,7 @@ public final class AttachedDatabaseConfigurationsGetSamples { */ public final class AttachedDatabaseConfigurationsListByClusterSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoAttachedDatabaseConfigurationsListByCluster.json */ /** @@ -280,7 +284,7 @@ import com.azure.resourcemanager.kusto.models.ClusterPrincipalAssignmentCheckNam */ public final class ClusterPrincipalAssignmentsCheckNameAvailabilitySamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoClusterPrincipalAssignmentsCheckNameAvailability.json */ /** @@ -309,7 +313,7 @@ import com.azure.resourcemanager.kusto.models.PrincipalType; */ public final class ClusterPrincipalAssignmentsCreateOrUpdateSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoClusterPrincipalAssignmentsCreateOrUpdate.json */ /** @@ -339,7 +343,7 @@ public final class ClusterPrincipalAssignmentsCreateOrUpdateSamples { */ public final class ClusterPrincipalAssignmentsDeleteSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoClusterPrincipalAssignmentsDelete.json */ /** @@ -362,7 +366,7 @@ public final class ClusterPrincipalAssignmentsDeleteSamples { */ public final class ClusterPrincipalAssignmentsGetSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoClusterPrincipalAssignmentsGet.json */ /** @@ -385,7 +389,7 @@ public final class ClusterPrincipalAssignmentsGetSamples { */ public final class ClusterPrincipalAssignmentsListSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoClusterPrincipalAssignmentsList.json */ /** @@ -399,6 +403,39 @@ public final class ClusterPrincipalAssignmentsListSamples { } ``` +### Clusters_AddCalloutPolicies + +```java +import com.azure.resourcemanager.kusto.fluent.models.CalloutPolicyInner; +import com.azure.resourcemanager.kusto.models.CalloutPoliciesList; +import com.azure.resourcemanager.kusto.models.CalloutType; +import com.azure.resourcemanager.kusto.models.OutboundAccess; +import java.util.Arrays; + +/** + * Samples for Clusters AddCalloutPolicies. + */ +public final class ClustersAddCalloutPoliciesSamples { + /* + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ + * KustoClusterAddCalloutPolicies.json + */ + /** + * Sample code: KustoClusterAddCalloutPolicy. + * + * @param manager Entry point to KustoManager. + */ + public static void kustoClusterAddCalloutPolicy(com.azure.resourcemanager.kusto.KustoManager manager) { + manager.clusters() + .addCalloutPolicies("kustorptest", "kustoCluster", + new CalloutPoliciesList().withValue(Arrays.asList(new CalloutPolicyInner().withCalloutUriRegex("*") + .withCalloutType(CalloutType.KUSTO) + .withOutboundAccess(OutboundAccess.ALLOW))), + com.azure.core.util.Context.NONE); + } +} +``` + ### Clusters_AddLanguageExtensions ```java @@ -412,7 +449,7 @@ import java.util.Arrays; */ public final class ClustersAddLanguageExtensionsSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoClusterAddLanguageExtensions.json */ /** @@ -441,7 +478,7 @@ import com.azure.resourcemanager.kusto.models.ClusterCheckNameRequest; */ public final class ClustersCheckNameAvailabilitySamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoClustersCheckNameAvailability.json */ /** @@ -479,7 +516,7 @@ import java.util.Arrays; public final class ClustersCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoClustersCreateOrUpdate + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoClustersCreateOrUpdate * .json */ /** @@ -521,7 +558,7 @@ public final class ClustersCreateOrUpdateSamples { public final class ClustersDeleteSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoClustersDelete.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoClustersDelete.json */ /** * Sample code: KustoClustersDelete. @@ -544,7 +581,7 @@ import com.azure.resourcemanager.kusto.fluent.models.FollowerDatabaseDefinitionI */ public final class ClustersDetachFollowerDatabasesSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoClusterDetachFollowerDatabases.json */ /** @@ -571,7 +608,7 @@ public final class ClustersDetachFollowerDatabasesSamples { */ public final class ClustersDiagnoseVirtualNetworkSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoClustersDiagnoseVirtualNetwork.json */ /** @@ -594,7 +631,7 @@ public final class ClustersDiagnoseVirtualNetworkSamples { public final class ClustersGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoClustersGet.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoClustersGet.json */ /** * Sample code: KustoClustersGet. @@ -617,7 +654,7 @@ public final class ClustersGetByResourceGroupSamples { public final class ClustersListSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoClustersList.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoClustersList.json */ /** * Sample code: KustoClustersList. @@ -638,7 +675,7 @@ public final class ClustersListSamples { */ public final class ClustersListByResourceGroupSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoClustersListByResourceGroup.json */ /** @@ -652,6 +689,28 @@ public final class ClustersListByResourceGroupSamples { } ``` +### Clusters_ListCalloutPolicies + +```java +/** + * Samples for Clusters ListCalloutPolicies. + */ +public final class ClustersListCalloutPoliciesSamples { + /* + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ + * KustoClustersListCalloutPolicies.json + */ + /** + * Sample code: KustoClusterListCalloutPolicies. + * + * @param manager Entry point to KustoManager. + */ + public static void kustoClusterListCalloutPolicies(com.azure.resourcemanager.kusto.KustoManager manager) { + manager.clusters().listCalloutPolicies("kustorptest", "kustoCluster", com.azure.core.util.Context.NONE); + } +} +``` + ### Clusters_ListFollowerDatabases ```java @@ -660,7 +719,7 @@ public final class ClustersListByResourceGroupSamples { */ public final class ClustersListFollowerDatabasesSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoClusterListFollowerDatabases.json */ /** @@ -674,6 +733,28 @@ public final class ClustersListFollowerDatabasesSamples { } ``` +### Clusters_ListFollowerDatabasesGet + +```java +/** + * Samples for Clusters ListFollowerDatabasesGet. + */ +public final class ClustersListFollowerDatabasesGetSamples { + /* + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ + * KustoClusterListFollowerDatabasesGet.json + */ + /** + * Sample code: KustoClusterListFollowerDatabasesGet. + * + * @param manager Entry point to KustoManager. + */ + public static void kustoClusterListFollowerDatabasesGet(com.azure.resourcemanager.kusto.KustoManager manager) { + manager.clusters().listFollowerDatabasesGet("kustorptest", "kustoCluster", com.azure.core.util.Context.NONE); + } +} +``` + ### Clusters_ListLanguageExtensions ```java @@ -682,7 +763,7 @@ public final class ClustersListFollowerDatabasesSamples { */ public final class ClustersListLanguageExtensionsSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoClusterListLanguageExtensions.json */ /** @@ -704,7 +785,7 @@ public final class ClustersListLanguageExtensionsSamples { */ public final class ClustersListOutboundNetworkDependenciesEndpointsSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoOutboundNetworkDependenciesList.json */ /** @@ -729,7 +810,7 @@ public final class ClustersListOutboundNetworkDependenciesEndpointsSamples { public final class ClustersListSkusSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoClustersListSkus.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoClustersListSkus.json */ /** * Sample code: KustoClustersListSkus. @@ -750,7 +831,7 @@ public final class ClustersListSkusSamples { */ public final class ClustersListSkusByResourceSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoClustersListResourceSkus.json */ /** @@ -775,7 +856,7 @@ import com.azure.resourcemanager.kusto.models.ClusterMigrateRequest; public final class ClustersMigrateSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoClusterMigrate.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoClusterMigrate.json */ /** * Sample code: KustoClusterMigrate. @@ -791,6 +872,32 @@ public final class ClustersMigrateSamples { } ``` +### Clusters_RemoveCalloutPolicy + +```java +import com.azure.resourcemanager.kusto.models.CalloutPolicyToRemove; + +/** + * Samples for Clusters RemoveCalloutPolicy. + */ +public final class ClustersRemoveCalloutPolicySamples { + /* + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ + * KustoClusterRemoveCalloutPolicy.json + */ + /** + * Sample code: KustoClusterDropCalloutPolicy. + * + * @param manager Entry point to KustoManager. + */ + public static void kustoClusterDropCalloutPolicy(com.azure.resourcemanager.kusto.KustoManager manager) { + manager.clusters() + .removeCalloutPolicy("kustorptest", "kustoCluster", new CalloutPolicyToRemove().withCalloutId("*_kusto"), + com.azure.core.util.Context.NONE); + } +} +``` + ### Clusters_RemoveLanguageExtensions ```java @@ -804,7 +911,7 @@ import java.util.Arrays; */ public final class ClustersRemoveLanguageExtensionsSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoClusterRemoveLanguageExtensions.json */ /** @@ -832,7 +939,7 @@ public final class ClustersRemoveLanguageExtensionsSamples { public final class ClustersStartSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoClustersStart.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoClustersStart.json */ /** * Sample code: KustoClustersStart. @@ -854,7 +961,7 @@ public final class ClustersStartSamples { public final class ClustersStopSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoClustersStop.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoClustersStop.json */ /** * Sample code: KustoClustersStop. @@ -878,7 +985,7 @@ import com.azure.resourcemanager.kusto.models.Cluster; public final class ClustersUpdateSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoClustersUpdate.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoClustersUpdate.json */ /** * Sample code: KustoClustersUpdate. @@ -904,7 +1011,7 @@ import com.azure.resourcemanager.kusto.models.DataConnectionCheckNameRequest; */ public final class DataConnectionsCheckNameAvailabilitySamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDataConnectionsCheckNameAvailability.json */ /** @@ -936,7 +1043,7 @@ import java.time.OffsetDateTime; */ public final class DataConnectionsCreateOrUpdateSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDataConnectionsEventGridCreateOrUpdate.json */ /** @@ -958,7 +1065,7 @@ public final class DataConnectionsCreateOrUpdateSamples { .withConsumerGroup("$Default") .withTableName("TestTable") .withMappingRuleName("TestMapping") - .withDataFormat(EventGridDataFormat.JSON) + .withDataFormat(EventGridDataFormat.MULTIJSON) .withIgnoreFirstRecord(false) .withBlobStorageEventType(BlobStorageEventType.MICROSOFT_STORAGE_BLOB_CREATED) .withManagedIdentityResourceId( @@ -968,7 +1075,7 @@ public final class DataConnectionsCreateOrUpdateSamples { } /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDataConnectionsCosmosDbCreateOrUpdate.json */ /** @@ -994,7 +1101,7 @@ public final class DataConnectionsCreateOrUpdateSamples { } /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDataConnectionsCreateOrUpdate.json */ /** @@ -1033,7 +1140,7 @@ import com.azure.resourcemanager.kusto.models.EventHubDataFormat; */ public final class DataConnectionsDataConnectionValidationSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDataConnectionValidationAsync.json */ /** @@ -1050,7 +1157,7 @@ public final class DataConnectionsDataConnectionValidationSamples { .withConsumerGroup("testConsumerGroup1") .withTableName("TestTable") .withMappingRuleName("TestMapping") - .withDataFormat(EventHubDataFormat.JSON) + .withDataFormat(EventHubDataFormat.MULTIJSON) .withCompression(Compression.NONE) .withManagedIdentityResourceId( "/subscriptions/12345678-1234-1234-1234-123456789098/resourceGroups/kustorptest/providers/Microsoft.ManagedIdentity/userAssignedIdentities/managedidentityTest1")), @@ -1058,7 +1165,7 @@ public final class DataConnectionsDataConnectionValidationSamples { } /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDataConnectionEventGridValidationAsync.json */ /** @@ -1079,7 +1186,7 @@ public final class DataConnectionsDataConnectionValidationSamples { .withConsumerGroup("$Default") .withTableName("TestTable") .withMappingRuleName("TestMapping") - .withDataFormat(EventGridDataFormat.JSON) + .withDataFormat(EventGridDataFormat.MULTIJSON) .withIgnoreFirstRecord(false) .withBlobStorageEventType(BlobStorageEventType.MICROSOFT_STORAGE_BLOB_CREATED) .withManagedIdentityResourceId( @@ -1099,7 +1206,7 @@ public final class DataConnectionsDataConnectionValidationSamples { public final class DataConnectionsDeleteSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoDataConnectionsDelete. + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoDataConnectionsDelete. * json */ /** @@ -1123,7 +1230,7 @@ public final class DataConnectionsDeleteSamples { */ public final class DataConnectionsGetSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDataConnectionsEventGridGet.json */ /** @@ -1138,7 +1245,7 @@ public final class DataConnectionsGetSamples { } /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDataConnectionsCosmosDbGet.json */ /** @@ -1154,7 +1261,7 @@ public final class DataConnectionsGetSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoDataConnectionsGet. + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoDataConnectionsGet. * json */ /** @@ -1178,7 +1285,7 @@ public final class DataConnectionsGetSamples { */ public final class DataConnectionsListByDatabaseSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDataConnectionsListByDatabase.json */ /** @@ -1209,7 +1316,7 @@ import java.time.OffsetDateTime; */ public final class DataConnectionsUpdateSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDataConnectionsCosmosDbUpdate.json */ /** @@ -1235,7 +1342,7 @@ public final class DataConnectionsUpdateSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoDataConnectionsUpdate. + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoDataConnectionsUpdate. * json */ /** @@ -1256,7 +1363,7 @@ public final class DataConnectionsUpdateSamples { } /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDataConnectionsEventGridUpdate.json */ /** @@ -1277,7 +1384,7 @@ public final class DataConnectionsUpdateSamples { .withConsumerGroup("$Default") .withTableName("TestTable") .withMappingRuleName("TestMapping") - .withDataFormat(EventGridDataFormat.JSON) + .withDataFormat(EventGridDataFormat.MULTIJSON) .withIgnoreFirstRecord(false) .withBlobStorageEventType(BlobStorageEventType.MICROSOFT_STORAGE_BLOB_CREATED) .withManagedIdentityResourceId( @@ -1300,7 +1407,7 @@ import java.util.Arrays; public final class DatabaseOperationInviteFollowerSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoDatabaseInviteFollower + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoDatabaseInviteFollower * .json */ /** @@ -1336,7 +1443,7 @@ import com.azure.resourcemanager.kusto.models.DatabasePrincipalAssignmentCheckNa */ public final class DatabasePrincipalAssignmentsCheckNameAvailabilitySamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDatabasePrincipalAssignmentsCheckNameAvailability.json */ /** @@ -1364,7 +1471,7 @@ import com.azure.resourcemanager.kusto.models.PrincipalType; */ public final class DatabasePrincipalAssignmentsCreateOrUpdateSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDatabasePrincipalAssignmentsCreateOrUpdate.json */ /** @@ -1394,7 +1501,7 @@ public final class DatabasePrincipalAssignmentsCreateOrUpdateSamples { */ public final class DatabasePrincipalAssignmentsDeleteSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDatabasePrincipalAssignmentsDelete.json */ /** @@ -1418,7 +1525,7 @@ public final class DatabasePrincipalAssignmentsDeleteSamples { */ public final class DatabasePrincipalAssignmentsGetSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDatabasePrincipalAssignmentsGet.json */ /** @@ -1442,7 +1549,7 @@ public final class DatabasePrincipalAssignmentsGetSamples { */ public final class DatabasePrincipalAssignmentsListSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDatabasePrincipalAssignmentsList.json */ /** @@ -1472,7 +1579,7 @@ import java.util.Arrays; public final class DatabasesAddPrincipalsSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoDatabaseAddPrincipals. + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoDatabaseAddPrincipals. * json */ /** @@ -1518,7 +1625,7 @@ import com.azure.resourcemanager.kusto.models.Type; */ public final class DatabasesCheckNameAvailabilitySamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDatabasesCheckNameAvailability.json */ /** @@ -1549,7 +1656,7 @@ import java.time.Duration; public final class DatabasesCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoDatabaseReadonlyUpdate + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoDatabaseReadonlyUpdate * .json */ /** @@ -1565,7 +1672,7 @@ public final class DatabasesCreateOrUpdateSamples { } /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDatabasesCreateOrUpdate.json */ /** @@ -1591,7 +1698,7 @@ public final class DatabasesCreateOrUpdateSamples { public final class DatabasesDeleteSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoDatabasesDelete.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoDatabasesDelete.json */ /** * Sample code: KustoDatabasesDelete. @@ -1613,7 +1720,7 @@ public final class DatabasesDeleteSamples { public final class DatabasesGetSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoSuspendedDatabasesGet. + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoSuspendedDatabasesGet. * json */ /** @@ -1628,7 +1735,7 @@ public final class DatabasesGetSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoDatabasesGet.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoDatabasesGet.json */ /** * Sample code: KustoDatabasesGet. @@ -1651,7 +1758,7 @@ public final class DatabasesGetSamples { public final class DatabasesListByClusterSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoDatabasesListByCluster + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoDatabasesListByCluster * .json */ /** @@ -1674,7 +1781,7 @@ public final class DatabasesListByClusterSamples { public final class DatabasesListPrincipalsSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoDatabaseListPrincipals + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoDatabaseListPrincipals * .json */ /** @@ -1703,7 +1810,7 @@ import java.util.Arrays; */ public final class DatabasesRemovePrincipalsSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDatabaseRemovePrincipals.json */ /** @@ -1750,7 +1857,7 @@ import java.time.Duration; public final class DatabasesUpdateSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoDatabasesUpdate.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoDatabasesUpdate.json */ /** * Sample code: KustoDatabasesUpdate. @@ -1776,7 +1883,7 @@ import com.azure.resourcemanager.kusto.models.ManagedPrivateEndpointsCheckNameRe */ public final class ManagedPrivateEndpointsCheckNameAvailabilitySamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoManagedPrivateEndpointsCheckNameAvailability.json */ /** @@ -1801,7 +1908,7 @@ public final class ManagedPrivateEndpointsCheckNameAvailabilitySamples { */ public final class ManagedPrivateEndpointsCreateOrUpdateSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoManagedPrivateEndpointsCreateOrUpdate.json */ /** @@ -1831,7 +1938,7 @@ public final class ManagedPrivateEndpointsCreateOrUpdateSamples { */ public final class ManagedPrivateEndpointsDeleteSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoManagedPrivateEndpointsDelete.json */ /** @@ -1854,7 +1961,7 @@ public final class ManagedPrivateEndpointsDeleteSamples { */ public final class ManagedPrivateEndpointsGetSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoManagedPrivateEndpointsGet.json */ /** @@ -1878,7 +1985,7 @@ public final class ManagedPrivateEndpointsGetSamples { */ public final class ManagedPrivateEndpointsListSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoManagedPrivateEndpointsList.json */ /** @@ -1902,7 +2009,7 @@ import com.azure.resourcemanager.kusto.models.ManagedPrivateEndpoint; */ public final class ManagedPrivateEndpointsUpdateSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoManagedPrivateEndpointsUpdate.json */ /** @@ -1934,7 +2041,7 @@ public final class ManagedPrivateEndpointsUpdateSamples { public final class OperationsListSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoOperationsList.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoOperationsList.json */ /** * Sample code: KustoOperationsList. @@ -1956,7 +2063,7 @@ public final class OperationsListSamples { public final class OperationsResultsGetSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoOperationResultsGet. + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoOperationResultsGet. * json */ /** @@ -1979,7 +2086,7 @@ public final class OperationsResultsGetSamples { */ public final class OperationsResultsLocationGetSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoOperationResultsOperationResultResponseTypeGet.json */ /** @@ -2004,7 +2111,7 @@ import com.azure.resourcemanager.kusto.models.PrivateLinkServiceConnectionStateP */ public final class PrivateEndpointConnectionsCreateOrUpdateSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoPrivateEndpointConnectionsCreateOrUpdate.json */ /** @@ -2033,7 +2140,7 @@ public final class PrivateEndpointConnectionsCreateOrUpdateSamples { */ public final class PrivateEndpointConnectionsDeleteSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoPrivateEndpointConnectionsDelete.json */ /** @@ -2057,7 +2164,7 @@ public final class PrivateEndpointConnectionsDeleteSamples { */ public final class PrivateEndpointConnectionsGetSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoPrivateEndpointConnectionsGet.json */ /** @@ -2080,7 +2187,7 @@ public final class PrivateEndpointConnectionsGetSamples { */ public final class PrivateEndpointConnectionsListSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoPrivateEndpointConnectionsList.json */ /** @@ -2102,7 +2209,7 @@ public final class PrivateEndpointConnectionsListSamples { */ public final class PrivateLinkResourcesGetSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoPrivateLinkResourcesGet.json */ /** @@ -2125,7 +2232,7 @@ public final class PrivateLinkResourcesGetSamples { */ public final class PrivateLinkResourcesListSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoPrivateLinkResourcesList.json */ /** @@ -2149,7 +2256,7 @@ import com.azure.resourcemanager.kusto.models.SandboxCustomImagesCheckNameReques */ public final class SandboxCustomImagesCheckNameAvailabilitySamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoSandboxCustomImagesCheckNameAvailability.json */ /** @@ -2177,7 +2284,7 @@ import com.azure.resourcemanager.kusto.models.Language; */ public final class SandboxCustomImagesCreateOrUpdateSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoSandboxCustomImagesCreateOrUpdate.json */ /** @@ -2194,6 +2301,46 @@ public final class SandboxCustomImagesCreateOrUpdateSamples { .withRequirementsFileContent("Requests") .create(); } + + /* + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ + * KustoSandboxCustomImagesCreateOrUpdateWithCustomBaseImage.json + */ + /** + * Sample code: KustoSandboxCustomImagesCreateOrUpdateWithCustomBaseImage. + * + * @param manager Entry point to KustoManager. + */ + public static void kustoSandboxCustomImagesCreateOrUpdateWithCustomBaseImage( + com.azure.resourcemanager.kusto.KustoManager manager) { + manager.sandboxCustomImages() + .define("customImage2") + .withExistingCluster("kustorptest", "kustoCluster") + .withLanguage(Language.PYTHON) + .withBaseImageName("customImage1") + .withRequirementsFileContent("Requests") + .create(); + } + + /* + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ + * KustoSandboxCustomImagesCreateOrUpdateWithManagedBaseImage.json + */ + /** + * Sample code: KustoSandboxCustomImagesCreateOrUpdateWithManagedBaseImage. + * + * @param manager Entry point to KustoManager. + */ + public static void kustoSandboxCustomImagesCreateOrUpdateWithManagedBaseImage( + com.azure.resourcemanager.kusto.KustoManager manager) { + manager.sandboxCustomImages() + .define("customImage2") + .withExistingCluster("kustorptest", "kustoCluster") + .withLanguage(Language.PYTHON) + .withBaseImageName("Python3_10_8") + .withRequirementsFileContent("Requests") + .create(); + } } ``` @@ -2205,7 +2352,7 @@ public final class SandboxCustomImagesCreateOrUpdateSamples { */ public final class SandboxCustomImagesDeleteSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoSandboxCustomImageDelete.json */ /** @@ -2229,7 +2376,7 @@ public final class SandboxCustomImagesDeleteSamples { public final class SandboxCustomImagesGetSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoSandboxCustomImagesGet + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoSandboxCustomImagesGet * .json */ /** @@ -2252,7 +2399,7 @@ public final class SandboxCustomImagesGetSamples { */ public final class SandboxCustomImagesListByClusterSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoSandboxCustomImagesList.json */ /** @@ -2277,7 +2424,7 @@ import com.azure.resourcemanager.kusto.models.SandboxCustomImage; */ public final class SandboxCustomImagesUpdateSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoSandboxCustomImageUpdate.json */ /** @@ -2308,7 +2455,7 @@ import com.azure.resourcemanager.kusto.models.ScriptCheckNameRequest; */ public final class ScriptsCheckNameAvailabilitySamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoScriptsCheckNameAvailability.json */ /** @@ -2327,13 +2474,16 @@ public final class ScriptsCheckNameAvailabilitySamples { ### Scripts_CreateOrUpdate ```java +import com.azure.resourcemanager.kusto.models.PrincipalPermissionsAction; +import com.azure.resourcemanager.kusto.models.ScriptLevel; + /** * Samples for Scripts CreateOrUpdate. */ public final class ScriptsCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoScriptsCreateOrUpdate. + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoScriptsCreateOrUpdate. * json */ /** @@ -2350,6 +2500,8 @@ public final class ScriptsCreateOrUpdateSamples { "?sv=2019-02-02&st=2019-04-29T22%3A18%3A26Z&se=2019-04-30T02%3A23%3A26Z&sr=b&sp=rw&sip=168.1.5.60-168.1.5.70&spr=https&sig=********************************") .withForceUpdateTag("2bcf3c21-ffd1-4444-b9dd-e52e00ee53fe") .withContinueOnErrors(true) + .withScriptLevel(ScriptLevel.DATABASE) + .withPrincipalPermissionsAction(PrincipalPermissionsAction.REMOVE_PERMISSION_ON_SCRIPT_COMPLETION) .create(); } } @@ -2364,7 +2516,7 @@ public final class ScriptsCreateOrUpdateSamples { public final class ScriptsDeleteSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoScriptsDelete.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoScriptsDelete.json */ /** * Sample code: KustoScriptsDelete. @@ -2387,7 +2539,7 @@ public final class ScriptsDeleteSamples { public final class ScriptsGetSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoScriptsGet.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoScriptsGet.json */ /** * Sample code: KustoScriptsGet. @@ -2411,7 +2563,7 @@ public final class ScriptsGetSamples { public final class ScriptsListByDatabaseSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoScriptsListByDatabase. + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoScriptsListByDatabase. * json */ /** @@ -2429,7 +2581,9 @@ public final class ScriptsListByDatabaseSamples { ### Scripts_Update ```java +import com.azure.resourcemanager.kusto.models.PrincipalPermissionsAction; import com.azure.resourcemanager.kusto.models.Script; +import com.azure.resourcemanager.kusto.models.ScriptLevel; /** * Samples for Scripts Update. @@ -2437,7 +2591,7 @@ import com.azure.resourcemanager.kusto.models.Script; public final class ScriptsUpdateSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoScriptsUpdate.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoScriptsUpdate.json */ /** * Sample code: KustoScriptsUpdate. @@ -2453,6 +2607,8 @@ public final class ScriptsUpdateSamples { .withScriptUrl("https://mysa.blob.core.windows.net/container/script.txt") .withForceUpdateTag("2bcf3c21-ffd1-4444-b9dd-e52e00ee53fe") .withContinueOnErrors(true) + .withScriptLevel(ScriptLevel.DATABASE) + .withPrincipalPermissionsAction(PrincipalPermissionsAction.REMOVE_PERMISSION_ON_SCRIPT_COMPLETION) .apply(); } } @@ -2467,7 +2623,7 @@ public final class ScriptsUpdateSamples { public final class SkusListSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoSkus.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoSkus.json */ /** * Sample code: KustoListRegionSkus. diff --git a/sdk/kusto/azure-resourcemanager-kusto/pom.xml b/sdk/kusto/azure-resourcemanager-kusto/pom.xml index 1ee89226fd4f..8ff3a0fd7ce9 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/pom.xml +++ b/sdk/kusto/azure-resourcemanager-kusto/pom.xml @@ -14,11 +14,11 @@ com.azure.resourcemanager azure-resourcemanager-kusto - 1.2.0-beta.1 + 1.3.0-beta.1 jar Microsoft Azure SDK for Kusto Management - This package contains Microsoft Azure SDK for Kusto Management SDK. For documentation on how to use this package, please see https://aka.ms/azsdk/java/mgmt. The Azure Kusto management API provides a RESTful set of web services that interact with Azure Kusto services to manage your clusters and databases. The API enables you to create, update, and delete clusters and databases. Package tag package-2023-08. + This package contains Microsoft Azure SDK for Kusto Management SDK. For documentation on how to use this package, please see https://aka.ms/azsdk/java/mgmt. The Azure Kusto management API provides a RESTful set of web services that interact with Azure Kusto services to manage your clusters and databases. The API enables you to create, update, and delete clusters and databases. Package tag package-2024-04. https://github.com/Azure/azure-sdk-for-java @@ -46,35 +46,34 @@ 0 0 false - true com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/KustoManager.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/KustoManager.java index c623df6878a6..ac3207cfe36f 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/KustoManager.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/KustoManager.java @@ -266,7 +266,7 @@ public KustoManager authenticate(TokenCredential credential, AzureProfile profil .append("-") .append("com.azure.resourcemanager.kusto") .append("/") - .append("1.1.0"); + .append("1.2.0"); if (!Configuration.getGlobalConfiguration().get("AZURE_TELEMETRY_DISABLED", false)) { userAgentBuilder.append(" (") .append(Configuration.getGlobalConfiguration().get("java.version")) diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/fluent/ClustersClient.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/fluent/ClustersClient.java index 30e47fb80f2a..626210ee9d14 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/fluent/ClustersClient.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/fluent/ClustersClient.java @@ -12,13 +12,17 @@ import com.azure.core.util.Context; import com.azure.core.util.polling.SyncPoller; import com.azure.resourcemanager.kusto.fluent.models.AzureResourceSkuInner; +import com.azure.resourcemanager.kusto.fluent.models.CalloutPolicyInner; import com.azure.resourcemanager.kusto.fluent.models.CheckNameResultInner; import com.azure.resourcemanager.kusto.fluent.models.ClusterInner; import com.azure.resourcemanager.kusto.fluent.models.DiagnoseVirtualNetworkResultInner; +import com.azure.resourcemanager.kusto.fluent.models.FollowerDatabaseDefinitionGetInner; import com.azure.resourcemanager.kusto.fluent.models.FollowerDatabaseDefinitionInner; import com.azure.resourcemanager.kusto.fluent.models.LanguageExtensionInner; import com.azure.resourcemanager.kusto.fluent.models.OutboundNetworkDependenciesEndpointInner; import com.azure.resourcemanager.kusto.fluent.models.SkuDescriptionInner; +import com.azure.resourcemanager.kusto.models.CalloutPoliciesList; +import com.azure.resourcemanager.kusto.models.CalloutPolicyToRemove; import com.azure.resourcemanager.kusto.models.ClusterCheckNameRequest; import com.azure.resourcemanager.kusto.models.ClusterMigrateRequest; import com.azure.resourcemanager.kusto.models.ClusterUpdate; @@ -405,6 +409,35 @@ SyncPoller, Void> beginMigrate(String resourceGroupName, String void migrate(String resourceGroupName, String clusterName, ClusterMigrateRequest clusterMigrateRequest, Context context); + /** + * Returns a list of databases that are owned by this cluster and were followed by another cluster. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the list Kusto database principals operation response as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listFollowerDatabasesGet(String resourceGroupName, + String clusterName); + + /** + * Returns a list of databases that are owned by this cluster and were followed by another cluster. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the list Kusto database principals operation response as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listFollowerDatabasesGet(String resourceGroupName, + String clusterName, Context context); + /** * Returns a list of databases that are owned by this cluster and were followed by another cluster. * @@ -706,6 +739,152 @@ PagedIterable listSkusByResource(String resourceGroupName PagedIterable listOutboundNetworkDependenciesEndpoints(String resourceGroupName, String clusterName, Context context); + /** + * Adds a list of callout policies for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicies The callout policies to add. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, Void> beginAddCalloutPolicies(String resourceGroupName, String clusterName, + CalloutPoliciesList calloutPolicies); + + /** + * Adds a list of callout policies for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicies The callout policies to add. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, Void> beginAddCalloutPolicies(String resourceGroupName, String clusterName, + CalloutPoliciesList calloutPolicies, Context context); + + /** + * Adds a list of callout policies for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicies The callout policies to add. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void addCalloutPolicies(String resourceGroupName, String clusterName, CalloutPoliciesList calloutPolicies); + + /** + * Adds a list of callout policies for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicies The callout policies to add. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void addCalloutPolicies(String resourceGroupName, String clusterName, CalloutPoliciesList calloutPolicies, + Context context); + + /** + * Removes callout policy for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicy The callout policies to remove. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, Void> beginRemoveCalloutPolicy(String resourceGroupName, String clusterName, + CalloutPolicyToRemove calloutPolicy); + + /** + * Removes callout policy for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicy The callout policies to remove. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, Void> beginRemoveCalloutPolicy(String resourceGroupName, String clusterName, + CalloutPolicyToRemove calloutPolicy, Context context); + + /** + * Removes callout policy for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicy The callout policies to remove. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void removeCalloutPolicy(String resourceGroupName, String clusterName, CalloutPolicyToRemove calloutPolicy); + + /** + * Removes callout policy for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicy The callout policies to remove. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void removeCalloutPolicy(String resourceGroupName, String clusterName, CalloutPolicyToRemove calloutPolicy, + Context context); + + /** + * Returns the allowed callout policies for the specified service. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of the service's callout policy objects as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listCalloutPolicies(String resourceGroupName, String clusterName); + + /** + * Returns the allowed callout policies for the specified service. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of the service's callout policy objects as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listCalloutPolicies(String resourceGroupName, String clusterName, + Context context); + /** * Returns a list of language extensions that can run within KQL queries. * diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/fluent/models/CalloutPolicyInner.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/fluent/models/CalloutPolicyInner.java new file mode 100644 index 000000000000..27a506bffcc6 --- /dev/null +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/fluent/models/CalloutPolicyInner.java @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.kusto.fluent.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.resourcemanager.kusto.models.CalloutType; +import com.azure.resourcemanager.kusto.models.OutboundAccess; +import java.io.IOException; + +/** + * Configuration for external callout policies, including URI patterns, access types, and service types. + */ +@Fluent +public final class CalloutPolicyInner implements JsonSerializable { + /* + * Regular expression or FQDN pattern for the callout URI. + */ + private String calloutUriRegex; + + /* + * Type of the callout service, specifying the kind of external resource or service being accessed. + */ + private CalloutType calloutType; + + /* + * Indicates whether outbound access is permitted for the specified URI pattern. + */ + private OutboundAccess outboundAccess; + + /* + * Unique identifier for the callout configuration. + */ + private String calloutId; + + /** + * Creates an instance of CalloutPolicyInner class. + */ + public CalloutPolicyInner() { + } + + /** + * Get the calloutUriRegex property: Regular expression or FQDN pattern for the callout URI. + * + * @return the calloutUriRegex value. + */ + public String calloutUriRegex() { + return this.calloutUriRegex; + } + + /** + * Set the calloutUriRegex property: Regular expression or FQDN pattern for the callout URI. + * + * @param calloutUriRegex the calloutUriRegex value to set. + * @return the CalloutPolicyInner object itself. + */ + public CalloutPolicyInner withCalloutUriRegex(String calloutUriRegex) { + this.calloutUriRegex = calloutUriRegex; + return this; + } + + /** + * Get the calloutType property: Type of the callout service, specifying the kind of external resource or service + * being accessed. + * + * @return the calloutType value. + */ + public CalloutType calloutType() { + return this.calloutType; + } + + /** + * Set the calloutType property: Type of the callout service, specifying the kind of external resource or service + * being accessed. + * + * @param calloutType the calloutType value to set. + * @return the CalloutPolicyInner object itself. + */ + public CalloutPolicyInner withCalloutType(CalloutType calloutType) { + this.calloutType = calloutType; + return this; + } + + /** + * Get the outboundAccess property: Indicates whether outbound access is permitted for the specified URI pattern. + * + * @return the outboundAccess value. + */ + public OutboundAccess outboundAccess() { + return this.outboundAccess; + } + + /** + * Set the outboundAccess property: Indicates whether outbound access is permitted for the specified URI pattern. + * + * @param outboundAccess the outboundAccess value to set. + * @return the CalloutPolicyInner object itself. + */ + public CalloutPolicyInner withOutboundAccess(OutboundAccess outboundAccess) { + this.outboundAccess = outboundAccess; + return this; + } + + /** + * Get the calloutId property: Unique identifier for the callout configuration. + * + * @return the calloutId value. + */ + public String calloutId() { + return this.calloutId; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("calloutUriRegex", this.calloutUriRegex); + jsonWriter.writeStringField("calloutType", this.calloutType == null ? null : this.calloutType.toString()); + jsonWriter.writeStringField("outboundAccess", + this.outboundAccess == null ? null : this.outboundAccess.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of CalloutPolicyInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of CalloutPolicyInner 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 CalloutPolicyInner. + */ + public static CalloutPolicyInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CalloutPolicyInner deserializedCalloutPolicyInner = new CalloutPolicyInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("calloutUriRegex".equals(fieldName)) { + deserializedCalloutPolicyInner.calloutUriRegex = reader.getString(); + } else if ("calloutType".equals(fieldName)) { + deserializedCalloutPolicyInner.calloutType = CalloutType.fromString(reader.getString()); + } else if ("outboundAccess".equals(fieldName)) { + deserializedCalloutPolicyInner.outboundAccess = OutboundAccess.fromString(reader.getString()); + } else if ("calloutId".equals(fieldName)) { + deserializedCalloutPolicyInner.calloutId = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedCalloutPolicyInner; + }); + } +} diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/fluent/models/ClusterInner.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/fluent/models/ClusterInner.java index b8207d2b3afc..29f38ca80ce6 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/fluent/models/ClusterInner.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/fluent/models/ClusterInner.java @@ -26,6 +26,7 @@ import com.azure.resourcemanager.kusto.models.State; import com.azure.resourcemanager.kusto.models.TrustedExternalTenant; import com.azure.resourcemanager.kusto.models.VirtualNetworkConfiguration; +import com.azure.resourcemanager.kusto.models.ZoneStatus; import java.io.IOException; import java.util.List; import java.util.Map; @@ -640,6 +641,29 @@ public ClusterInner withAllowedFqdnList(List allowedFqdnList) { return this; } + /** + * Get the calloutPolicies property: List of callout policies for egress from Cluster. + * + * @return the calloutPolicies value. + */ + public List calloutPolicies() { + return this.innerProperties() == null ? null : this.innerProperties().calloutPolicies(); + } + + /** + * Set the calloutPolicies property: List of callout policies for egress from Cluster. + * + * @param calloutPolicies the calloutPolicies value to set. + * @return the ClusterInner object itself. + */ + public ClusterInner withCalloutPolicies(List calloutPolicies) { + if (this.innerProperties() == null) { + this.innerProperties = new ClusterProperties(); + } + this.innerProperties().withCalloutPolicies(calloutPolicies); + return this; + } + /** * Get the publicIpType property: Indicates what public IP type to create - IPv4 (default), or DualStack (both IPv4 * and IPv6). @@ -706,6 +730,15 @@ public MigrationClusterProperties migrationCluster() { return this.innerProperties() == null ? null : this.innerProperties().migrationCluster(); } + /** + * Get the zoneStatus property: Indicates whether the cluster is zonal or non-zonal. + * + * @return the zoneStatus value. + */ + public ZoneStatus zoneStatus() { + return this.innerProperties() == null ? null : this.innerProperties().zoneStatus(); + } + /** * Validates the instance. * diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/fluent/models/ClusterProperties.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/fluent/models/ClusterProperties.java index c9f62706ceda..3bafba565b30 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/fluent/models/ClusterProperties.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/fluent/models/ClusterProperties.java @@ -22,6 +22,7 @@ import com.azure.resourcemanager.kusto.models.State; import com.azure.resourcemanager.kusto.models.TrustedExternalTenant; import com.azure.resourcemanager.kusto.models.VirtualNetworkConfiguration; +import com.azure.resourcemanager.kusto.models.ZoneStatus; import java.io.IOException; import java.util.List; @@ -138,6 +139,11 @@ public final class ClusterProperties implements JsonSerializable allowedFqdnList; + /* + * List of callout policies for egress from Cluster. + */ + private List calloutPolicies; + /* * Indicates what public IP type to create - IPv4 (default), or DualStack (both IPv4 and IPv6) */ @@ -158,6 +164,11 @@ public final class ClusterProperties implements JsonSerializable allowedFqdnList) { return this; } + /** + * Get the calloutPolicies property: List of callout policies for egress from Cluster. + * + * @return the calloutPolicies value. + */ + public List calloutPolicies() { + return this.calloutPolicies; + } + + /** + * Set the calloutPolicies property: List of callout policies for egress from Cluster. + * + * @param calloutPolicies the calloutPolicies value to set. + * @return the ClusterProperties object itself. + */ + public ClusterProperties withCalloutPolicies(List calloutPolicies) { + this.calloutPolicies = calloutPolicies; + return this; + } + /** * Get the publicIpType property: Indicates what public IP type to create - IPv4 (default), or DualStack (both IPv4 * and IPv6). @@ -595,6 +626,15 @@ public MigrationClusterProperties migrationCluster() { return this.migrationCluster; } + /** + * Get the zoneStatus property: Indicates whether the cluster is zonal or non-zonal. + * + * @return the zoneStatus value. + */ + public ZoneStatus zoneStatus() { + return this.zoneStatus; + } + /** * Validates the instance. * @@ -619,6 +659,9 @@ public void validate() { if (acceptedAudiences() != null) { acceptedAudiences().forEach(e -> e.validate()); } + if (calloutPolicies() != null) { + calloutPolicies().forEach(e -> e.validate()); + } if (privateEndpointConnections() != null) { privateEndpointConnections().forEach(e -> e.validate()); } @@ -655,6 +698,8 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { this.restrictOutboundNetworkAccess == null ? null : this.restrictOutboundNetworkAccess.toString()); jsonWriter.writeArrayField("allowedFqdnList", this.allowedFqdnList, (writer, element) -> writer.writeString(element)); + jsonWriter.writeArrayField("calloutPolicies", this.calloutPolicies, + (writer, element) -> writer.writeJson(element)); jsonWriter.writeStringField("publicIPType", this.publicIpType == null ? null : this.publicIpType.toString()); jsonWriter.writeStringField("virtualClusterGraduationProperties", this.virtualClusterGraduationProperties); return jsonWriter.writeEndObject(); @@ -726,6 +771,10 @@ public static ClusterProperties fromJson(JsonReader jsonReader) throws IOExcepti } else if ("allowedFqdnList".equals(fieldName)) { List allowedFqdnList = reader.readArray(reader1 -> reader1.getString()); deserializedClusterProperties.allowedFqdnList = allowedFqdnList; + } else if ("calloutPolicies".equals(fieldName)) { + List calloutPolicies + = reader.readArray(reader1 -> CalloutPolicyInner.fromJson(reader1)); + deserializedClusterProperties.calloutPolicies = calloutPolicies; } else if ("publicIPType".equals(fieldName)) { deserializedClusterProperties.publicIpType = PublicIpType.fromString(reader.getString()); } else if ("virtualClusterGraduationProperties".equals(fieldName)) { @@ -736,6 +785,8 @@ public static ClusterProperties fromJson(JsonReader jsonReader) throws IOExcepti deserializedClusterProperties.privateEndpointConnections = privateEndpointConnections; } else if ("migrationCluster".equals(fieldName)) { deserializedClusterProperties.migrationCluster = MigrationClusterProperties.fromJson(reader); + } else if ("zoneStatus".equals(fieldName)) { + deserializedClusterProperties.zoneStatus = ZoneStatus.fromString(reader.getString()); } else { reader.skipChildren(); } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/fluent/models/FollowerDatabaseDefinitionGetInner.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/fluent/models/FollowerDatabaseDefinitionGetInner.java new file mode 100644 index 000000000000..fd02d7453989 --- /dev/null +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/fluent/models/FollowerDatabaseDefinitionGetInner.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. + +package com.azure.resourcemanager.kusto.fluent.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.resourcemanager.kusto.models.DatabaseShareOrigin; +import com.azure.resourcemanager.kusto.models.TableLevelSharingProperties; +import java.io.IOException; + +/** + * A class representing follower database object. + */ +@Fluent +public final class FollowerDatabaseDefinitionGetInner implements JsonSerializable { + /* + * Follower database definition. + */ + private FollowerDatabaseProperties innerProperties; + + /** + * Creates an instance of FollowerDatabaseDefinitionGetInner class. + */ + public FollowerDatabaseDefinitionGetInner() { + } + + /** + * Get the innerProperties property: Follower database definition. + * + * @return the innerProperties value. + */ + private FollowerDatabaseProperties innerProperties() { + return this.innerProperties; + } + + /** + * Get the clusterResourceId property: Resource id of the cluster that follows a database owned by this cluster. + * + * @return the clusterResourceId value. + */ + public String clusterResourceId() { + return this.innerProperties() == null ? null : this.innerProperties().clusterResourceId(); + } + + /** + * Set the clusterResourceId property: Resource id of the cluster that follows a database owned by this cluster. + * + * @param clusterResourceId the clusterResourceId value to set. + * @return the FollowerDatabaseDefinitionGetInner object itself. + */ + public FollowerDatabaseDefinitionGetInner withClusterResourceId(String clusterResourceId) { + if (this.innerProperties() == null) { + this.innerProperties = new FollowerDatabaseProperties(); + } + this.innerProperties().withClusterResourceId(clusterResourceId); + return this; + } + + /** + * Get the attachedDatabaseConfigurationName property: Resource name of the attached database configuration in the + * follower cluster. + * + * @return the attachedDatabaseConfigurationName value. + */ + public String attachedDatabaseConfigurationName() { + return this.innerProperties() == null ? null : this.innerProperties().attachedDatabaseConfigurationName(); + } + + /** + * Set the attachedDatabaseConfigurationName property: Resource name of the attached database configuration in the + * follower cluster. + * + * @param attachedDatabaseConfigurationName the attachedDatabaseConfigurationName value to set. + * @return the FollowerDatabaseDefinitionGetInner object itself. + */ + public FollowerDatabaseDefinitionGetInner + withAttachedDatabaseConfigurationName(String attachedDatabaseConfigurationName) { + if (this.innerProperties() == null) { + this.innerProperties = new FollowerDatabaseProperties(); + } + this.innerProperties().withAttachedDatabaseConfigurationName(attachedDatabaseConfigurationName); + return this; + } + + /** + * Get the databaseName property: The database name owned by this cluster that was followed. * in case following all + * databases. + * + * @return the databaseName value. + */ + public String databaseName() { + return this.innerProperties() == null ? null : this.innerProperties().databaseName(); + } + + /** + * Get the tableLevelSharingProperties property: Table level sharing specifications. + * + * @return the tableLevelSharingProperties value. + */ + public TableLevelSharingProperties tableLevelSharingProperties() { + return this.innerProperties() == null ? null : this.innerProperties().tableLevelSharingProperties(); + } + + /** + * Get the databaseShareOrigin property: The origin of the following setup. + * + * @return the databaseShareOrigin value. + */ + public DatabaseShareOrigin databaseShareOrigin() { + return this.innerProperties() == null ? null : this.innerProperties().databaseShareOrigin(); + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (innerProperties() != null) { + innerProperties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.innerProperties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of FollowerDatabaseDefinitionGetInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of FollowerDatabaseDefinitionGetInner 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 FollowerDatabaseDefinitionGetInner. + */ + public static FollowerDatabaseDefinitionGetInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + FollowerDatabaseDefinitionGetInner deserializedFollowerDatabaseDefinitionGetInner + = new FollowerDatabaseDefinitionGetInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("properties".equals(fieldName)) { + deserializedFollowerDatabaseDefinitionGetInner.innerProperties + = FollowerDatabaseProperties.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedFollowerDatabaseDefinitionGetInner; + }); + } +} diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/fluent/models/FollowerDatabaseProperties.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/fluent/models/FollowerDatabaseProperties.java new file mode 100644 index 000000000000..1aa322b7c831 --- /dev/null +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/fluent/models/FollowerDatabaseProperties.java @@ -0,0 +1,193 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.kusto.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.kusto.models.DatabaseShareOrigin; +import com.azure.resourcemanager.kusto.models.TableLevelSharingProperties; +import java.io.IOException; + +/** + * A class representing the properties of a follower database object. + */ +@Fluent +public final class FollowerDatabaseProperties implements JsonSerializable { + /* + * Resource id of the cluster that follows a database owned by this cluster. + */ + private String clusterResourceId; + + /* + * Resource name of the attached database configuration in the follower cluster. + */ + private String attachedDatabaseConfigurationName; + + /* + * The database name owned by this cluster that was followed. * in case following all databases. + */ + private String databaseName; + + /* + * Table level sharing specifications + */ + private TableLevelSharingProperties tableLevelSharingProperties; + + /* + * The origin of the following setup. + */ + private DatabaseShareOrigin databaseShareOrigin; + + /** + * Creates an instance of FollowerDatabaseProperties class. + */ + public FollowerDatabaseProperties() { + } + + /** + * Get the clusterResourceId property: Resource id of the cluster that follows a database owned by this cluster. + * + * @return the clusterResourceId value. + */ + public String clusterResourceId() { + return this.clusterResourceId; + } + + /** + * Set the clusterResourceId property: Resource id of the cluster that follows a database owned by this cluster. + * + * @param clusterResourceId the clusterResourceId value to set. + * @return the FollowerDatabaseProperties object itself. + */ + public FollowerDatabaseProperties withClusterResourceId(String clusterResourceId) { + this.clusterResourceId = clusterResourceId; + return this; + } + + /** + * Get the attachedDatabaseConfigurationName property: Resource name of the attached database configuration in the + * follower cluster. + * + * @return the attachedDatabaseConfigurationName value. + */ + public String attachedDatabaseConfigurationName() { + return this.attachedDatabaseConfigurationName; + } + + /** + * Set the attachedDatabaseConfigurationName property: Resource name of the attached database configuration in the + * follower cluster. + * + * @param attachedDatabaseConfigurationName the attachedDatabaseConfigurationName value to set. + * @return the FollowerDatabaseProperties object itself. + */ + public FollowerDatabaseProperties withAttachedDatabaseConfigurationName(String attachedDatabaseConfigurationName) { + this.attachedDatabaseConfigurationName = attachedDatabaseConfigurationName; + return this; + } + + /** + * Get the databaseName property: The database name owned by this cluster that was followed. * in case following all + * databases. + * + * @return the databaseName value. + */ + public String databaseName() { + return this.databaseName; + } + + /** + * Get the tableLevelSharingProperties property: Table level sharing specifications. + * + * @return the tableLevelSharingProperties value. + */ + public TableLevelSharingProperties tableLevelSharingProperties() { + return this.tableLevelSharingProperties; + } + + /** + * Get the databaseShareOrigin property: The origin of the following setup. + * + * @return the databaseShareOrigin value. + */ + public DatabaseShareOrigin databaseShareOrigin() { + return this.databaseShareOrigin; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (clusterResourceId() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property clusterResourceId in model FollowerDatabaseProperties")); + } + if (attachedDatabaseConfigurationName() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property attachedDatabaseConfigurationName in model FollowerDatabaseProperties")); + } + if (tableLevelSharingProperties() != null) { + tableLevelSharingProperties().validate(); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(FollowerDatabaseProperties.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("clusterResourceId", this.clusterResourceId); + jsonWriter.writeStringField("attachedDatabaseConfigurationName", this.attachedDatabaseConfigurationName); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of FollowerDatabaseProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of FollowerDatabaseProperties 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 FollowerDatabaseProperties. + */ + public static FollowerDatabaseProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + FollowerDatabaseProperties deserializedFollowerDatabaseProperties = new FollowerDatabaseProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("clusterResourceId".equals(fieldName)) { + deserializedFollowerDatabaseProperties.clusterResourceId = reader.getString(); + } else if ("attachedDatabaseConfigurationName".equals(fieldName)) { + deserializedFollowerDatabaseProperties.attachedDatabaseConfigurationName = reader.getString(); + } else if ("databaseName".equals(fieldName)) { + deserializedFollowerDatabaseProperties.databaseName = reader.getString(); + } else if ("tableLevelSharingProperties".equals(fieldName)) { + deserializedFollowerDatabaseProperties.tableLevelSharingProperties + = TableLevelSharingProperties.fromJson(reader); + } else if ("databaseShareOrigin".equals(fieldName)) { + deserializedFollowerDatabaseProperties.databaseShareOrigin + = DatabaseShareOrigin.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedFollowerDatabaseProperties; + }); + } +} diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/fluent/models/SandboxCustomImageInner.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/fluent/models/SandboxCustomImageInner.java index 00d758ba4330..8b80a23f8ada 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/fluent/models/SandboxCustomImageInner.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/fluent/models/SandboxCustomImageInner.java @@ -107,7 +107,8 @@ public SandboxCustomImageInner withLanguage(Language language) { } /** - * Get the languageVersion property: The version of the language. + * Get the languageVersion property: The version of the language. Either this property or baseImageName should be + * specified. * * @return the languageVersion value. */ @@ -116,7 +117,8 @@ public String languageVersion() { } /** - * Set the languageVersion property: The version of the language. + * Set the languageVersion property: The version of the language. Either this property or baseImageName should be + * specified. * * @param languageVersion the languageVersion value to set. * @return the SandboxCustomImageInner object itself. @@ -129,6 +131,33 @@ public SandboxCustomImageInner withLanguageVersion(String languageVersion) { return this; } + /** + * Get the baseImageName property: The base image name on which the custom image is built on top of. It can be one + * of the LanguageExtensionImageName (e.g.: 'Python3_10_8', 'Python3_10_8_DL') or the name of an existing custom + * image. Either this property or languageVersion should be specified. + * + * @return the baseImageName value. + */ + public String baseImageName() { + return this.innerProperties() == null ? null : this.innerProperties().baseImageName(); + } + + /** + * Set the baseImageName property: The base image name on which the custom image is built on top of. It can be one + * of the LanguageExtensionImageName (e.g.: 'Python3_10_8', 'Python3_10_8_DL') or the name of an existing custom + * image. Either this property or languageVersion should be specified. + * + * @param baseImageName the baseImageName value to set. + * @return the SandboxCustomImageInner object itself. + */ + public SandboxCustomImageInner withBaseImageName(String baseImageName) { + if (this.innerProperties() == null) { + this.innerProperties = new SandboxCustomImageProperties(); + } + this.innerProperties().withBaseImageName(baseImageName); + return this; + } + /** * Get the requirementsFileContent property: The requirements file content. * diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/fluent/models/SandboxCustomImageProperties.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/fluent/models/SandboxCustomImageProperties.java index 1f1818436850..8b17a676cf7f 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/fluent/models/SandboxCustomImageProperties.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/fluent/models/SandboxCustomImageProperties.java @@ -25,10 +25,17 @@ public final class SandboxCustomImageProperties implements JsonSerializable allowedFqdnList() { } } + public List calloutPolicies() { + List inner = this.innerModel().calloutPolicies(); + if (inner != null) { + return Collections.unmodifiableList(inner.stream() + .map(inner1 -> new CalloutPolicyImpl(inner1, this.manager())) + .collect(Collectors.toList())); + } else { + return Collections.emptyList(); + } + } + public PublicIpType publicIpType() { return this.innerModel().publicIpType(); } @@ -220,6 +236,10 @@ public MigrationClusterProperties migrationCluster() { return this.innerModel().migrationCluster(); } + public ZoneStatus zoneStatus() { + return this.innerModel().zoneStatus(); + } + public Region region() { return Region.fromName(this.regionName()); } @@ -373,6 +393,30 @@ public DiagnoseVirtualNetworkResult diagnoseVirtualNetwork(Context context) { return serviceManager.clusters().diagnoseVirtualNetwork(resourceGroupName, clusterName, context); } + public void addCalloutPolicies(CalloutPoliciesList calloutPolicies) { + serviceManager.clusters().addCalloutPolicies(resourceGroupName, clusterName, calloutPolicies); + } + + public void addCalloutPolicies(CalloutPoliciesList calloutPolicies, Context context) { + serviceManager.clusters().addCalloutPolicies(resourceGroupName, clusterName, calloutPolicies, context); + } + + public void removeCalloutPolicy(CalloutPolicyToRemove calloutPolicy) { + serviceManager.clusters().removeCalloutPolicy(resourceGroupName, clusterName, calloutPolicy); + } + + public void removeCalloutPolicy(CalloutPolicyToRemove calloutPolicy, Context context) { + serviceManager.clusters().removeCalloutPolicy(resourceGroupName, clusterName, calloutPolicy, context); + } + + public PagedIterable listCalloutPolicies() { + return serviceManager.clusters().listCalloutPolicies(resourceGroupName, clusterName); + } + + public PagedIterable listCalloutPolicies(Context context) { + return serviceManager.clusters().listCalloutPolicies(resourceGroupName, clusterName, context); + } + public PagedIterable listLanguageExtensions() { return serviceManager.clusters().listLanguageExtensions(resourceGroupName, clusterName); } @@ -609,6 +653,16 @@ public ClusterImpl withAllowedFqdnList(List allowedFqdnList) { } } + public ClusterImpl withCalloutPolicies(List calloutPolicies) { + if (isInCreateMode()) { + this.innerModel().withCalloutPolicies(calloutPolicies); + return this; + } else { + this.updateParameters.withCalloutPolicies(calloutPolicies); + return this; + } + } + public ClusterImpl withPublicIpType(PublicIpType publicIpType) { if (isInCreateMode()) { this.innerModel().withPublicIpType(publicIpType); diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/implementation/ClustersClientImpl.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/implementation/ClustersClientImpl.java index 757f9194bd9a..eb27d1270d71 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/implementation/ClustersClientImpl.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/implementation/ClustersClientImpl.java @@ -35,18 +35,23 @@ import com.azure.core.util.polling.SyncPoller; import com.azure.resourcemanager.kusto.fluent.ClustersClient; import com.azure.resourcemanager.kusto.fluent.models.AzureResourceSkuInner; +import com.azure.resourcemanager.kusto.fluent.models.CalloutPolicyInner; import com.azure.resourcemanager.kusto.fluent.models.CheckNameResultInner; import com.azure.resourcemanager.kusto.fluent.models.ClusterInner; import com.azure.resourcemanager.kusto.fluent.models.DiagnoseVirtualNetworkResultInner; +import com.azure.resourcemanager.kusto.fluent.models.FollowerDatabaseDefinitionGetInner; import com.azure.resourcemanager.kusto.fluent.models.FollowerDatabaseDefinitionInner; import com.azure.resourcemanager.kusto.fluent.models.LanguageExtensionInner; import com.azure.resourcemanager.kusto.fluent.models.OutboundNetworkDependenciesEndpointInner; import com.azure.resourcemanager.kusto.fluent.models.SkuDescriptionInner; +import com.azure.resourcemanager.kusto.models.CalloutPoliciesList; +import com.azure.resourcemanager.kusto.models.CalloutPolicyToRemove; import com.azure.resourcemanager.kusto.models.ClusterCheckNameRequest; import com.azure.resourcemanager.kusto.models.ClusterListResult; import com.azure.resourcemanager.kusto.models.ClusterMigrateRequest; import com.azure.resourcemanager.kusto.models.ClusterUpdate; import com.azure.resourcemanager.kusto.models.FollowerDatabaseListResult; +import com.azure.resourcemanager.kusto.models.FollowerDatabaseListResultGet; import com.azure.resourcemanager.kusto.models.LanguageExtensionsList; import com.azure.resourcemanager.kusto.models.ListResourceSkusResult; import com.azure.resourcemanager.kusto.models.OutboundNetworkDependenciesEndpointListResult; @@ -153,6 +158,15 @@ Mono>> migrate(@HostParam("$host") String endpoint, @BodyParam("application/json") ClusterMigrateRequest clusterMigrateRequest, @HeaderParam("Accept") String accept, Context context); + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/listFollowerDatabases") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listFollowerDatabasesGet(@HostParam("$host") String endpoint, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("clusterName") String clusterName, + @PathParam("subscriptionId") String subscriptionId, @QueryParam("api-version") String apiVersion, + @HeaderParam("Accept") String accept, Context context); + @Headers({ "Content-Type: application/json" }) @Post("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/listFollowerDatabases") @ExpectedResponses({ 200 }) @@ -233,6 +247,37 @@ Mono> listOutboundNetwor @PathParam("resourceGroupName") String resourceGroupName, @PathParam("clusterName") String clusterName, @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + @Headers({ "Content-Type: application/json" }) + @Post("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/addCalloutPolicies") + @ExpectedResponses({ 200, 202 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> addCalloutPolicies(@HostParam("$host") String endpoint, + @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("clusterName") String clusterName, + @QueryParam("api-version") String apiVersion, + @BodyParam("application/json") CalloutPoliciesList calloutPolicies, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Post("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/removeCalloutPolicy") + @ExpectedResponses({ 200, 202 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> removeCalloutPolicy(@HostParam("$host") String endpoint, + @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("clusterName") String clusterName, + @QueryParam("api-version") String apiVersion, + @BodyParam("application/json") CalloutPolicyToRemove calloutPolicy, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Post("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/listCalloutPolicies") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listCalloutPolicies(@HostParam("$host") String endpoint, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("clusterName") String clusterName, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @HeaderParam("Accept") String accept, Context context); + @Headers({ "Content-Type: application/json" }) @Post("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/listLanguageExtensions") @ExpectedResponses({ 200 }) @@ -1816,6 +1861,149 @@ public void migrate(String resourceGroupName, String clusterName, ClusterMigrate migrateAsync(resourceGroupName, clusterName, clusterMigrateRequest, context).block(); } + /** + * Returns a list of databases that are owned by this cluster and were followed by another cluster. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the list Kusto database principals operation response along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> + listFollowerDatabasesGetSinglePageAsync(String resourceGroupName, String clusterName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (clusterName == null) { + return Mono.error(new IllegalArgumentException("Parameter clusterName is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listFollowerDatabasesGet(this.client.getEndpoint(), resourceGroupName, + clusterName, this.client.getSubscriptionId(), this.client.getApiVersion(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), null, null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Returns a list of databases that are owned by this cluster and were followed by another cluster. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the list Kusto database principals operation response along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> + listFollowerDatabasesGetSinglePageAsync(String resourceGroupName, String clusterName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (clusterName == null) { + return Mono.error(new IllegalArgumentException("Parameter clusterName is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listFollowerDatabasesGet(this.client.getEndpoint(), resourceGroupName, clusterName, + this.client.getSubscriptionId(), this.client.getApiVersion(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), null, null)); + } + + /** + * Returns a list of databases that are owned by this cluster and were followed by another cluster. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the list Kusto database principals operation response as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listFollowerDatabasesGetAsync(String resourceGroupName, + String clusterName) { + return new PagedFlux<>(() -> listFollowerDatabasesGetSinglePageAsync(resourceGroupName, clusterName)); + } + + /** + * Returns a list of databases that are owned by this cluster and were followed by another cluster. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the list Kusto database principals operation response as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listFollowerDatabasesGetAsync(String resourceGroupName, + String clusterName, Context context) { + return new PagedFlux<>(() -> listFollowerDatabasesGetSinglePageAsync(resourceGroupName, clusterName, context)); + } + + /** + * Returns a list of databases that are owned by this cluster and were followed by another cluster. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the list Kusto database principals operation response as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listFollowerDatabasesGet(String resourceGroupName, + String clusterName) { + return new PagedIterable<>(listFollowerDatabasesGetAsync(resourceGroupName, clusterName)); + } + + /** + * Returns a list of databases that are owned by this cluster and were followed by another cluster. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the list Kusto database principals operation response as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listFollowerDatabasesGet(String resourceGroupName, + String clusterName, Context context) { + return new PagedIterable<>(listFollowerDatabasesGetAsync(resourceGroupName, clusterName, context)); + } + /** * Returns a list of databases that are owned by this cluster and were followed by another cluster. * @@ -3166,6 +3354,609 @@ public PagedIterable listSkusByResource(String resourceGr listOutboundNetworkDependenciesEndpointsAsync(resourceGroupName, clusterName, context)); } + /** + * Adds a list of callout policies for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicies The callout policies to add. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> addCalloutPoliciesWithResponseAsync(String resourceGroupName, + String clusterName, CalloutPoliciesList calloutPolicies) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (clusterName == null) { + return Mono.error(new IllegalArgumentException("Parameter clusterName is required and cannot be null.")); + } + if (calloutPolicies == null) { + return Mono + .error(new IllegalArgumentException("Parameter calloutPolicies is required and cannot be null.")); + } else { + calloutPolicies.validate(); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.addCalloutPolicies(this.client.getEndpoint(), this.client.getSubscriptionId(), + resourceGroupName, clusterName, this.client.getApiVersion(), calloutPolicies, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Adds a list of callout policies for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicies The callout policies to add. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> addCalloutPoliciesWithResponseAsync(String resourceGroupName, + String clusterName, CalloutPoliciesList calloutPolicies, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (clusterName == null) { + return Mono.error(new IllegalArgumentException("Parameter clusterName is required and cannot be null.")); + } + if (calloutPolicies == null) { + return Mono + .error(new IllegalArgumentException("Parameter calloutPolicies is required and cannot be null.")); + } else { + calloutPolicies.validate(); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.addCalloutPolicies(this.client.getEndpoint(), this.client.getSubscriptionId(), resourceGroupName, + clusterName, this.client.getApiVersion(), calloutPolicies, accept, context); + } + + /** + * Adds a list of callout policies for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicies The callout policies to add. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, Void> beginAddCalloutPoliciesAsync(String resourceGroupName, + String clusterName, CalloutPoliciesList calloutPolicies) { + Mono>> mono + = addCalloutPoliciesWithResponseAsync(resourceGroupName, clusterName, calloutPolicies); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), Void.class, Void.class, + this.client.getContext()); + } + + /** + * Adds a list of callout policies for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicies The callout policies to add. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, Void> beginAddCalloutPoliciesAsync(String resourceGroupName, + String clusterName, CalloutPoliciesList calloutPolicies, Context context) { + context = this.client.mergeContext(context); + Mono>> mono + = addCalloutPoliciesWithResponseAsync(resourceGroupName, clusterName, calloutPolicies, context); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), Void.class, Void.class, + context); + } + + /** + * Adds a list of callout policies for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicies The callout policies to add. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, Void> beginAddCalloutPolicies(String resourceGroupName, String clusterName, + CalloutPoliciesList calloutPolicies) { + return this.beginAddCalloutPoliciesAsync(resourceGroupName, clusterName, calloutPolicies).getSyncPoller(); + } + + /** + * Adds a list of callout policies for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicies The callout policies to add. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, Void> beginAddCalloutPolicies(String resourceGroupName, String clusterName, + CalloutPoliciesList calloutPolicies, Context context) { + return this.beginAddCalloutPoliciesAsync(resourceGroupName, clusterName, calloutPolicies, context) + .getSyncPoller(); + } + + /** + * Adds a list of callout policies for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicies The callout policies to add. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono addCalloutPoliciesAsync(String resourceGroupName, String clusterName, + CalloutPoliciesList calloutPolicies) { + return beginAddCalloutPoliciesAsync(resourceGroupName, clusterName, calloutPolicies).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Adds a list of callout policies for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicies The callout policies to add. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono addCalloutPoliciesAsync(String resourceGroupName, String clusterName, + CalloutPoliciesList calloutPolicies, Context context) { + return beginAddCalloutPoliciesAsync(resourceGroupName, clusterName, calloutPolicies, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Adds a list of callout policies for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicies The callout policies to add. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void addCalloutPolicies(String resourceGroupName, String clusterName, CalloutPoliciesList calloutPolicies) { + addCalloutPoliciesAsync(resourceGroupName, clusterName, calloutPolicies).block(); + } + + /** + * Adds a list of callout policies for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicies The callout policies to add. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void addCalloutPolicies(String resourceGroupName, String clusterName, CalloutPoliciesList calloutPolicies, + Context context) { + addCalloutPoliciesAsync(resourceGroupName, clusterName, calloutPolicies, context).block(); + } + + /** + * Removes callout policy for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicy The callout policies to remove. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> removeCalloutPolicyWithResponseAsync(String resourceGroupName, + String clusterName, CalloutPolicyToRemove calloutPolicy) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (clusterName == null) { + return Mono.error(new IllegalArgumentException("Parameter clusterName is required and cannot be null.")); + } + if (calloutPolicy == null) { + return Mono.error(new IllegalArgumentException("Parameter calloutPolicy is required and cannot be null.")); + } else { + calloutPolicy.validate(); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.removeCalloutPolicy(this.client.getEndpoint(), this.client.getSubscriptionId(), + resourceGroupName, clusterName, this.client.getApiVersion(), calloutPolicy, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Removes callout policy for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicy The callout policies to remove. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> removeCalloutPolicyWithResponseAsync(String resourceGroupName, + String clusterName, CalloutPolicyToRemove calloutPolicy, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (clusterName == null) { + return Mono.error(new IllegalArgumentException("Parameter clusterName is required and cannot be null.")); + } + if (calloutPolicy == null) { + return Mono.error(new IllegalArgumentException("Parameter calloutPolicy is required and cannot be null.")); + } else { + calloutPolicy.validate(); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.removeCalloutPolicy(this.client.getEndpoint(), this.client.getSubscriptionId(), + resourceGroupName, clusterName, this.client.getApiVersion(), calloutPolicy, accept, context); + } + + /** + * Removes callout policy for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicy The callout policies to remove. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, Void> beginRemoveCalloutPolicyAsync(String resourceGroupName, + String clusterName, CalloutPolicyToRemove calloutPolicy) { + Mono>> mono + = removeCalloutPolicyWithResponseAsync(resourceGroupName, clusterName, calloutPolicy); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), Void.class, Void.class, + this.client.getContext()); + } + + /** + * Removes callout policy for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicy The callout policies to remove. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, Void> beginRemoveCalloutPolicyAsync(String resourceGroupName, + String clusterName, CalloutPolicyToRemove calloutPolicy, Context context) { + context = this.client.mergeContext(context); + Mono>> mono + = removeCalloutPolicyWithResponseAsync(resourceGroupName, clusterName, calloutPolicy, context); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), Void.class, Void.class, + context); + } + + /** + * Removes callout policy for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicy The callout policies to remove. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, Void> beginRemoveCalloutPolicy(String resourceGroupName, String clusterName, + CalloutPolicyToRemove calloutPolicy) { + return this.beginRemoveCalloutPolicyAsync(resourceGroupName, clusterName, calloutPolicy).getSyncPoller(); + } + + /** + * Removes callout policy for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicy The callout policies to remove. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, Void> beginRemoveCalloutPolicy(String resourceGroupName, String clusterName, + CalloutPolicyToRemove calloutPolicy, Context context) { + return this.beginRemoveCalloutPolicyAsync(resourceGroupName, clusterName, calloutPolicy, context) + .getSyncPoller(); + } + + /** + * Removes callout policy for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicy The callout policies to remove. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono removeCalloutPolicyAsync(String resourceGroupName, String clusterName, + CalloutPolicyToRemove calloutPolicy) { + return beginRemoveCalloutPolicyAsync(resourceGroupName, clusterName, calloutPolicy).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Removes callout policy for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicy The callout policies to remove. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono removeCalloutPolicyAsync(String resourceGroupName, String clusterName, + CalloutPolicyToRemove calloutPolicy, Context context) { + return beginRemoveCalloutPolicyAsync(resourceGroupName, clusterName, calloutPolicy, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Removes callout policy for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicy The callout policies to remove. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void removeCalloutPolicy(String resourceGroupName, String clusterName, CalloutPolicyToRemove calloutPolicy) { + removeCalloutPolicyAsync(resourceGroupName, clusterName, calloutPolicy).block(); + } + + /** + * Removes callout policy for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicy The callout policies to remove. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void removeCalloutPolicy(String resourceGroupName, String clusterName, CalloutPolicyToRemove calloutPolicy, + Context context) { + removeCalloutPolicyAsync(resourceGroupName, clusterName, calloutPolicy, context).block(); + } + + /** + * Returns the allowed callout policies for the specified service. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of the service's callout policy objects along with {@link PagedResponse} on successful completion + * of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listCalloutPoliciesSinglePageAsync(String resourceGroupName, + String clusterName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (clusterName == null) { + return Mono.error(new IllegalArgumentException("Parameter clusterName is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listCalloutPolicies(this.client.getEndpoint(), resourceGroupName, + clusterName, this.client.getApiVersion(), this.client.getSubscriptionId(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), null, null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Returns the allowed callout policies for the specified service. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of the service's callout policy objects along with {@link PagedResponse} on successful completion + * of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listCalloutPoliciesSinglePageAsync(String resourceGroupName, + String clusterName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (clusterName == null) { + return Mono.error(new IllegalArgumentException("Parameter clusterName is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listCalloutPolicies(this.client.getEndpoint(), resourceGroupName, clusterName, this.client.getApiVersion(), + this.client.getSubscriptionId(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), null, null)); + } + + /** + * Returns the allowed callout policies for the specified service. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of the service's callout policy objects as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listCalloutPoliciesAsync(String resourceGroupName, String clusterName) { + return new PagedFlux<>(() -> listCalloutPoliciesSinglePageAsync(resourceGroupName, clusterName)); + } + + /** + * Returns the allowed callout policies for the specified service. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of the service's callout policy objects as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listCalloutPoliciesAsync(String resourceGroupName, String clusterName, + Context context) { + return new PagedFlux<>(() -> listCalloutPoliciesSinglePageAsync(resourceGroupName, clusterName, context)); + } + + /** + * Returns the allowed callout policies for the specified service. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of the service's callout policy objects as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listCalloutPolicies(String resourceGroupName, String clusterName) { + return new PagedIterable<>(listCalloutPoliciesAsync(resourceGroupName, clusterName)); + } + + /** + * Returns the allowed callout policies for the specified service. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of the service's callout policy objects as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listCalloutPolicies(String resourceGroupName, String clusterName, + Context context) { + return new PagedIterable<>(listCalloutPoliciesAsync(resourceGroupName, clusterName, context)); + } + /** * Returns a list of language extensions that can run within KQL queries. * diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/implementation/ClustersImpl.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/implementation/ClustersImpl.java index 2b2a4bee6c02..842a5c2646b9 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/implementation/ClustersImpl.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/implementation/ClustersImpl.java @@ -11,14 +11,19 @@ import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.kusto.fluent.ClustersClient; import com.azure.resourcemanager.kusto.fluent.models.AzureResourceSkuInner; +import com.azure.resourcemanager.kusto.fluent.models.CalloutPolicyInner; import com.azure.resourcemanager.kusto.fluent.models.CheckNameResultInner; import com.azure.resourcemanager.kusto.fluent.models.ClusterInner; import com.azure.resourcemanager.kusto.fluent.models.DiagnoseVirtualNetworkResultInner; +import com.azure.resourcemanager.kusto.fluent.models.FollowerDatabaseDefinitionGetInner; import com.azure.resourcemanager.kusto.fluent.models.FollowerDatabaseDefinitionInner; import com.azure.resourcemanager.kusto.fluent.models.LanguageExtensionInner; import com.azure.resourcemanager.kusto.fluent.models.OutboundNetworkDependenciesEndpointInner; import com.azure.resourcemanager.kusto.fluent.models.SkuDescriptionInner; import com.azure.resourcemanager.kusto.models.AzureResourceSku; +import com.azure.resourcemanager.kusto.models.CalloutPoliciesList; +import com.azure.resourcemanager.kusto.models.CalloutPolicy; +import com.azure.resourcemanager.kusto.models.CalloutPolicyToRemove; import com.azure.resourcemanager.kusto.models.CheckNameResult; import com.azure.resourcemanager.kusto.models.Cluster; import com.azure.resourcemanager.kusto.models.ClusterCheckNameRequest; @@ -26,6 +31,7 @@ import com.azure.resourcemanager.kusto.models.Clusters; import com.azure.resourcemanager.kusto.models.DiagnoseVirtualNetworkResult; import com.azure.resourcemanager.kusto.models.FollowerDatabaseDefinition; +import com.azure.resourcemanager.kusto.models.FollowerDatabaseDefinitionGet; import com.azure.resourcemanager.kusto.models.LanguageExtension; import com.azure.resourcemanager.kusto.models.LanguageExtensionsList; import com.azure.resourcemanager.kusto.models.OutboundNetworkDependenciesEndpoint; @@ -97,6 +103,22 @@ public void migrate(String resourceGroupName, String clusterName, ClusterMigrate this.serviceClient().migrate(resourceGroupName, clusterName, clusterMigrateRequest, context); } + public PagedIterable listFollowerDatabasesGet(String resourceGroupName, + String clusterName) { + PagedIterable inner + = this.serviceClient().listFollowerDatabasesGet(resourceGroupName, clusterName); + return ResourceManagerUtils.mapPage(inner, + inner1 -> new FollowerDatabaseDefinitionGetImpl(inner1, this.manager())); + } + + public PagedIterable listFollowerDatabasesGet(String resourceGroupName, + String clusterName, Context context) { + PagedIterable inner + = this.serviceClient().listFollowerDatabasesGet(resourceGroupName, clusterName, context); + return ResourceManagerUtils.mapPage(inner, + inner1 -> new FollowerDatabaseDefinitionGetImpl(inner1, this.manager())); + } + public PagedIterable listFollowerDatabases(String resourceGroupName, String clusterName) { PagedIterable inner @@ -224,6 +246,37 @@ public PagedIterable listSkusByResource(String resourceGroupNa inner1 -> new OutboundNetworkDependenciesEndpointImpl(inner1, this.manager())); } + public void addCalloutPolicies(String resourceGroupName, String clusterName, CalloutPoliciesList calloutPolicies) { + this.serviceClient().addCalloutPolicies(resourceGroupName, clusterName, calloutPolicies); + } + + public void addCalloutPolicies(String resourceGroupName, String clusterName, CalloutPoliciesList calloutPolicies, + Context context) { + this.serviceClient().addCalloutPolicies(resourceGroupName, clusterName, calloutPolicies, context); + } + + public void removeCalloutPolicy(String resourceGroupName, String clusterName, CalloutPolicyToRemove calloutPolicy) { + this.serviceClient().removeCalloutPolicy(resourceGroupName, clusterName, calloutPolicy); + } + + public void removeCalloutPolicy(String resourceGroupName, String clusterName, CalloutPolicyToRemove calloutPolicy, + Context context) { + this.serviceClient().removeCalloutPolicy(resourceGroupName, clusterName, calloutPolicy, context); + } + + public PagedIterable listCalloutPolicies(String resourceGroupName, String clusterName) { + PagedIterable inner + = this.serviceClient().listCalloutPolicies(resourceGroupName, clusterName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new CalloutPolicyImpl(inner1, this.manager())); + } + + public PagedIterable listCalloutPolicies(String resourceGroupName, String clusterName, + Context context) { + PagedIterable inner + = this.serviceClient().listCalloutPolicies(resourceGroupName, clusterName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new CalloutPolicyImpl(inner1, this.manager())); + } + public PagedIterable listLanguageExtensions(String resourceGroupName, String clusterName) { PagedIterable inner = this.serviceClient().listLanguageExtensions(resourceGroupName, clusterName); diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/implementation/FollowerDatabaseDefinitionGetImpl.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/implementation/FollowerDatabaseDefinitionGetImpl.java new file mode 100644 index 000000000000..1f074a68f8fd --- /dev/null +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/implementation/FollowerDatabaseDefinitionGetImpl.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.kusto.implementation; + +import com.azure.resourcemanager.kusto.fluent.models.FollowerDatabaseDefinitionGetInner; +import com.azure.resourcemanager.kusto.models.DatabaseShareOrigin; +import com.azure.resourcemanager.kusto.models.FollowerDatabaseDefinitionGet; +import com.azure.resourcemanager.kusto.models.TableLevelSharingProperties; + +public final class FollowerDatabaseDefinitionGetImpl implements FollowerDatabaseDefinitionGet { + private FollowerDatabaseDefinitionGetInner innerObject; + + private final com.azure.resourcemanager.kusto.KustoManager serviceManager; + + FollowerDatabaseDefinitionGetImpl(FollowerDatabaseDefinitionGetInner innerObject, + com.azure.resourcemanager.kusto.KustoManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String clusterResourceId() { + return this.innerModel().clusterResourceId(); + } + + public String attachedDatabaseConfigurationName() { + return this.innerModel().attachedDatabaseConfigurationName(); + } + + public String databaseName() { + return this.innerModel().databaseName(); + } + + public TableLevelSharingProperties tableLevelSharingProperties() { + return this.innerModel().tableLevelSharingProperties(); + } + + public DatabaseShareOrigin databaseShareOrigin() { + return this.innerModel().databaseShareOrigin(); + } + + public FollowerDatabaseDefinitionGetInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.kusto.KustoManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/implementation/KustoManagementClientImpl.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/implementation/KustoManagementClientImpl.java index 50bca9bbd7f8..dbb11cbaa287 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/implementation/KustoManagementClientImpl.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/implementation/KustoManagementClientImpl.java @@ -379,7 +379,7 @@ public OperationsResultsLocationsClient getOperationsResultsLocations() { this.defaultPollInterval = defaultPollInterval; this.subscriptionId = subscriptionId; this.endpoint = endpoint; - this.apiVersion = "2023-08-15"; + this.apiVersion = "2024-04-13"; this.clusters = new ClustersClientImpl(this); this.clusterPrincipalAssignments = new ClusterPrincipalAssignmentsClientImpl(this); this.skus = new SkusClientImpl(this); diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/implementation/SandboxCustomImageImpl.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/implementation/SandboxCustomImageImpl.java index 273cb429d1e6..bede99f51e0a 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/implementation/SandboxCustomImageImpl.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/implementation/SandboxCustomImageImpl.java @@ -36,6 +36,10 @@ public String languageVersion() { return this.innerModel().languageVersion(); } + public String baseImageName() { + return this.innerModel().baseImageName(); + } + public String requirementsFileContent() { return this.innerModel().requirementsFileContent(); } @@ -142,6 +146,11 @@ public SandboxCustomImageImpl withLanguageVersion(String languageVersion) { return this; } + public SandboxCustomImageImpl withBaseImageName(String baseImageName) { + this.innerModel().withBaseImageName(baseImageName); + return this; + } + public SandboxCustomImageImpl withRequirementsFileContent(String requirementsFileContent) { this.innerModel().withRequirementsFileContent(requirementsFileContent); return this; diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/implementation/ScriptImpl.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/implementation/ScriptImpl.java index 0e7db2579d45..0681fc8d0e19 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/implementation/ScriptImpl.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/implementation/ScriptImpl.java @@ -7,8 +7,10 @@ import com.azure.core.management.SystemData; import com.azure.core.util.Context; import com.azure.resourcemanager.kusto.fluent.models.ScriptInner; +import com.azure.resourcemanager.kusto.models.PrincipalPermissionsAction; import com.azure.resourcemanager.kusto.models.ProvisioningState; import com.azure.resourcemanager.kusto.models.Script; +import com.azure.resourcemanager.kusto.models.ScriptLevel; public final class ScriptImpl implements Script, Script.Definition, Script.Update { private ScriptInner innerObject; @@ -55,6 +57,14 @@ public ProvisioningState provisioningState() { return this.innerModel().provisioningState(); } + public ScriptLevel scriptLevel() { + return this.innerModel().scriptLevel(); + } + + public PrincipalPermissionsAction principalPermissionsAction() { + return this.innerModel().principalPermissionsAction(); + } + public String resourceGroupName() { return resourceGroupName; } @@ -169,4 +179,14 @@ public ScriptImpl withContinueOnErrors(Boolean continueOnErrors) { this.innerModel().withContinueOnErrors(continueOnErrors); return this; } + + public ScriptImpl withScriptLevel(ScriptLevel scriptLevel) { + this.innerModel().withScriptLevel(scriptLevel); + return this; + } + + public ScriptImpl withPrincipalPermissionsAction(PrincipalPermissionsAction principalPermissionsAction) { + this.innerModel().withPrincipalPermissionsAction(principalPermissionsAction); + return this; + } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/CalloutPoliciesList.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/CalloutPoliciesList.java new file mode 100644 index 000000000000..9f825d4408d9 --- /dev/null +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/CalloutPoliciesList.java @@ -0,0 +1,127 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.kusto.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.resourcemanager.kusto.fluent.models.CalloutPolicyInner; +import java.io.IOException; +import java.util.List; + +/** + * A list of the service's callout policy objects. + */ +@Fluent +public final class CalloutPoliciesList implements JsonSerializable { + /* + * A list of the service's callout policies. + */ + private List value; + + /* + * The URL to get the next set of callout policies list results if there are any. + */ + private String nextLink; + + /** + * Creates an instance of CalloutPoliciesList class. + */ + public CalloutPoliciesList() { + } + + /** + * Get the value property: A list of the service's callout policies. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Set the value property: A list of the service's callout policies. + * + * @param value the value value to set. + * @return the CalloutPoliciesList object itself. + */ + public CalloutPoliciesList withValue(List value) { + this.value = value; + return this; + } + + /** + * Get the nextLink property: The URL to get the next set of callout policies list results if there are any. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The URL to get the next set of callout policies list results if there are any. + * + * @param nextLink the nextLink value to set. + * @return the CalloutPoliciesList object itself. + */ + public CalloutPoliciesList withNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() != null) { + value().forEach(e -> e.validate()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of CalloutPoliciesList from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of CalloutPoliciesList 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 CalloutPoliciesList. + */ + public static CalloutPoliciesList fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CalloutPoliciesList deserializedCalloutPoliciesList = new CalloutPoliciesList(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value = reader.readArray(reader1 -> CalloutPolicyInner.fromJson(reader1)); + deserializedCalloutPoliciesList.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedCalloutPoliciesList.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedCalloutPoliciesList; + }); + } +} diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/CalloutPolicy.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/CalloutPolicy.java new file mode 100644 index 000000000000..42f84121d88f --- /dev/null +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/CalloutPolicy.java @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.kusto.models; + +import com.azure.resourcemanager.kusto.fluent.models.CalloutPolicyInner; + +/** + * An immutable client-side representation of CalloutPolicy. + */ +public interface CalloutPolicy { + /** + * Gets the calloutUriRegex property: Regular expression or FQDN pattern for the callout URI. + * + * @return the calloutUriRegex value. + */ + String calloutUriRegex(); + + /** + * Gets the calloutType property: Type of the callout service, specifying the kind of external resource or service + * being accessed. + * + * @return the calloutType value. + */ + CalloutType calloutType(); + + /** + * Gets the outboundAccess property: Indicates whether outbound access is permitted for the specified URI pattern. + * + * @return the outboundAccess value. + */ + OutboundAccess outboundAccess(); + + /** + * Gets the calloutId property: Unique identifier for the callout configuration. + * + * @return the calloutId value. + */ + String calloutId(); + + /** + * Gets the inner com.azure.resourcemanager.kusto.fluent.models.CalloutPolicyInner object. + * + * @return the inner object. + */ + CalloutPolicyInner innerModel(); +} diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/CalloutPolicyToRemove.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/CalloutPolicyToRemove.java new file mode 100644 index 000000000000..f302850c7d11 --- /dev/null +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/CalloutPolicyToRemove.java @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.kusto.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; + +/** + * Configuration for an external callout policy to remove. + */ +@Fluent +public final class CalloutPolicyToRemove implements JsonSerializable { + /* + * Unique identifier for the callout configuration. + */ + private String calloutId; + + /** + * Creates an instance of CalloutPolicyToRemove class. + */ + public CalloutPolicyToRemove() { + } + + /** + * Get the calloutId property: Unique identifier for the callout configuration. + * + * @return the calloutId value. + */ + public String calloutId() { + return this.calloutId; + } + + /** + * Set the calloutId property: Unique identifier for the callout configuration. + * + * @param calloutId the calloutId value to set. + * @return the CalloutPolicyToRemove object itself. + */ + public CalloutPolicyToRemove withCalloutId(String calloutId) { + this.calloutId = calloutId; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("calloutId", this.calloutId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of CalloutPolicyToRemove from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of CalloutPolicyToRemove 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 CalloutPolicyToRemove. + */ + public static CalloutPolicyToRemove fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CalloutPolicyToRemove deserializedCalloutPolicyToRemove = new CalloutPolicyToRemove(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("calloutId".equals(fieldName)) { + deserializedCalloutPolicyToRemove.calloutId = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedCalloutPolicyToRemove; + }); + } +} diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/CalloutType.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/CalloutType.java new file mode 100644 index 000000000000..4a3dfd5105df --- /dev/null +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/CalloutType.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. + +package com.azure.resourcemanager.kusto.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Type of the callout service, specifying the kind of external resource or service being accessed. + */ +public final class CalloutType extends ExpandableStringEnum { + /** + * Static value kusto for CalloutType. + */ + public static final CalloutType KUSTO = fromString("kusto"); + + /** + * Static value sql for CalloutType. + */ + public static final CalloutType SQL = fromString("sql"); + + /** + * Static value cosmosdb for CalloutType. + */ + public static final CalloutType COSMOSDB = fromString("cosmosdb"); + + /** + * Static value external_data for CalloutType. + */ + public static final CalloutType EXTERNAL_DATA = fromString("external_data"); + + /** + * Static value azure_digital_twins for CalloutType. + */ + public static final CalloutType AZURE_DIGITAL_TWINS = fromString("azure_digital_twins"); + + /** + * Static value sandbox_artifacts for CalloutType. + */ + public static final CalloutType SANDBOX_ARTIFACTS = fromString("sandbox_artifacts"); + + /** + * Static value webapi for CalloutType. + */ + public static final CalloutType WEBAPI = fromString("webapi"); + + /** + * Static value mysql for CalloutType. + */ + public static final CalloutType MYSQL = fromString("mysql"); + + /** + * Static value postgresql for CalloutType. + */ + public static final CalloutType POSTGRESQL = fromString("postgresql"); + + /** + * Static value genevametrics for CalloutType. + */ + public static final CalloutType GENEVAMETRICS = fromString("genevametrics"); + + /** + * Static value azure_openai for CalloutType. + */ + public static final CalloutType AZURE_OPENAI = fromString("azure_openai"); + + /** + * Creates a new instance of CalloutType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public CalloutType() { + } + + /** + * Creates or finds a CalloutType from its string representation. + * + * @param name a name to look for. + * @return the corresponding CalloutType. + */ + public static CalloutType fromString(String name) { + return fromString(name, CalloutType.class); + } + + /** + * Gets known CalloutType values. + * + * @return known CalloutType values. + */ + public static Collection values() { + return values(CalloutType.class); + } +} diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/Cluster.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/Cluster.java index 61fa774e324d..2b978f36e62b 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/Cluster.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/Cluster.java @@ -8,6 +8,7 @@ import com.azure.core.management.Region; import com.azure.core.management.SystemData; import com.azure.core.util.Context; +import com.azure.resourcemanager.kusto.fluent.models.CalloutPolicyInner; import com.azure.resourcemanager.kusto.fluent.models.ClusterInner; import com.azure.resourcemanager.kusto.fluent.models.FollowerDatabaseDefinitionInner; import java.util.List; @@ -237,6 +238,13 @@ public interface Cluster { */ List allowedFqdnList(); + /** + * Gets the calloutPolicies property: List of callout policies for egress from Cluster. + * + * @return the calloutPolicies value. + */ + List calloutPolicies(); + /** * Gets the publicIpType property: Indicates what public IP type to create - IPv4 (default), or DualStack (both IPv4 * and IPv6). @@ -266,6 +274,13 @@ public interface Cluster { */ MigrationClusterProperties migrationCluster(); + /** + * Gets the zoneStatus property: Indicates whether the cluster is zonal or non-zonal. + * + * @return the zoneStatus value. + */ + ZoneStatus zoneStatus(); + /** * Gets the region of the resource. * @@ -362,16 +377,16 @@ interface WithSku { * The stage of the Cluster definition which contains all the minimum required properties for the resource to be * created, but also allows for any other optional properties to be specified. */ - interface WithCreate - extends DefinitionStages.WithTags, DefinitionStages.WithZones, DefinitionStages.WithIdentity, - DefinitionStages.WithTrustedExternalTenants, DefinitionStages.WithOptimizedAutoscale, - DefinitionStages.WithEnableDiskEncryption, DefinitionStages.WithEnableStreamingIngest, - DefinitionStages.WithVirtualNetworkConfiguration, DefinitionStages.WithKeyVaultProperties, - DefinitionStages.WithEnablePurge, DefinitionStages.WithLanguageExtensions, - DefinitionStages.WithEnableDoubleEncryption, DefinitionStages.WithPublicNetworkAccess, - DefinitionStages.WithAllowedIpRangeList, DefinitionStages.WithEngineType, - DefinitionStages.WithAcceptedAudiences, DefinitionStages.WithEnableAutoStop, - DefinitionStages.WithRestrictOutboundNetworkAccess, DefinitionStages.WithAllowedFqdnList, + interface WithCreate extends DefinitionStages.WithTags, DefinitionStages.WithZones, + DefinitionStages.WithIdentity, DefinitionStages.WithTrustedExternalTenants, + DefinitionStages.WithOptimizedAutoscale, DefinitionStages.WithEnableDiskEncryption, + DefinitionStages.WithEnableStreamingIngest, DefinitionStages.WithVirtualNetworkConfiguration, + DefinitionStages.WithKeyVaultProperties, DefinitionStages.WithEnablePurge, + DefinitionStages.WithLanguageExtensions, DefinitionStages.WithEnableDoubleEncryption, + DefinitionStages.WithPublicNetworkAccess, DefinitionStages.WithAllowedIpRangeList, + DefinitionStages.WithEngineType, DefinitionStages.WithAcceptedAudiences, + DefinitionStages.WithEnableAutoStop, DefinitionStages.WithRestrictOutboundNetworkAccess, + DefinitionStages.WithAllowedFqdnList, DefinitionStages.WithCalloutPolicies, DefinitionStages.WithPublicIpType, DefinitionStages.WithVirtualClusterGraduationProperties, DefinitionStages.WithIfMatch, DefinitionStages.WithIfNoneMatch { /** @@ -648,6 +663,19 @@ interface WithAllowedFqdnList { WithCreate withAllowedFqdnList(List allowedFqdnList); } + /** + * The stage of the Cluster definition allowing to specify calloutPolicies. + */ + interface WithCalloutPolicies { + /** + * Specifies the calloutPolicies property: List of callout policies for egress from Cluster.. + * + * @param calloutPolicies List of callout policies for egress from Cluster. + * @return the next definition stage. + */ + WithCreate withCalloutPolicies(List calloutPolicies); + } + /** * The stage of the Cluster definition allowing to specify publicIpType. */ @@ -724,8 +752,8 @@ interface Update extends UpdateStages.WithTags, UpdateStages.WithSku, UpdateStag UpdateStages.WithLanguageExtensions, UpdateStages.WithEnableDoubleEncryption, UpdateStages.WithPublicNetworkAccess, UpdateStages.WithAllowedIpRangeList, UpdateStages.WithEngineType, UpdateStages.WithAcceptedAudiences, UpdateStages.WithEnableAutoStop, - UpdateStages.WithRestrictOutboundNetworkAccess, UpdateStages.WithAllowedFqdnList, UpdateStages.WithPublicIpType, - UpdateStages.WithIfMatch { + UpdateStages.WithRestrictOutboundNetworkAccess, UpdateStages.WithAllowedFqdnList, + UpdateStages.WithCalloutPolicies, UpdateStages.WithPublicIpType, UpdateStages.WithIfMatch { /** * Executes the update request. * @@ -1017,6 +1045,19 @@ interface WithAllowedFqdnList { Update withAllowedFqdnList(List allowedFqdnList); } + /** + * The stage of the Cluster update allowing to specify calloutPolicies. + */ + interface WithCalloutPolicies { + /** + * Specifies the calloutPolicies property: List of callout policies for egress from Cluster.. + * + * @param calloutPolicies List of callout policies for egress from Cluster. + * @return the next definition stage. + */ + Update withCalloutPolicies(List calloutPolicies); + } + /** * The stage of the Cluster update allowing to specify publicIpType. */ @@ -1181,6 +1222,68 @@ interface WithIfMatch { */ DiagnoseVirtualNetworkResult diagnoseVirtualNetwork(Context context); + /** + * Adds a list of callout policies for engine services. + * + * @param calloutPolicies The callout policies to add. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void addCalloutPolicies(CalloutPoliciesList calloutPolicies); + + /** + * Adds a list of callout policies for engine services. + * + * @param calloutPolicies The callout policies to add. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void addCalloutPolicies(CalloutPoliciesList calloutPolicies, Context context); + + /** + * Removes callout policy for engine services. + * + * @param calloutPolicy The callout policies to remove. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void removeCalloutPolicy(CalloutPolicyToRemove calloutPolicy); + + /** + * Removes callout policy for engine services. + * + * @param calloutPolicy The callout policies to remove. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void removeCalloutPolicy(CalloutPolicyToRemove calloutPolicy, Context context); + + /** + * Returns the allowed callout policies for the specified service. + * + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of the service's callout policy objects as paginated response with {@link PagedIterable}. + */ + PagedIterable listCalloutPolicies(); + + /** + * Returns the allowed callout policies for the specified service. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of the service's callout policy objects as paginated response with {@link PagedIterable}. + */ + PagedIterable listCalloutPolicies(Context context); + /** * Returns a list of language extensions that can run within KQL queries. * diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/ClusterPrincipalRole.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/ClusterPrincipalRole.java index 3a9c332f3d1c..4aecaa2ad1c7 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/ClusterPrincipalRole.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/ClusterPrincipalRole.java @@ -21,6 +21,11 @@ public final class ClusterPrincipalRole extends ExpandableStringEnum allowedFqdnList) { return this; } + /** + * Get the calloutPolicies property: List of callout policies for egress from Cluster. + * + * @return the calloutPolicies value. + */ + public List calloutPolicies() { + return this.innerProperties() == null ? null : this.innerProperties().calloutPolicies(); + } + + /** + * Set the calloutPolicies property: List of callout policies for egress from Cluster. + * + * @param calloutPolicies the calloutPolicies value to set. + * @return the ClusterUpdate object itself. + */ + public ClusterUpdate withCalloutPolicies(List calloutPolicies) { + if (this.innerProperties() == null) { + this.innerProperties = new ClusterProperties(); + } + this.innerProperties().withCalloutPolicies(calloutPolicies); + return this; + } + /** * Get the publicIpType property: Indicates what public IP type to create - IPv4 (default), or DualStack (both IPv4 * and IPv6). @@ -695,6 +719,15 @@ public MigrationClusterProperties migrationCluster() { return this.innerProperties() == null ? null : this.innerProperties().migrationCluster(); } + /** + * Get the zoneStatus property: Indicates whether the cluster is zonal or non-zonal. + * + * @return the zoneStatus value. + */ + public ZoneStatus zoneStatus() { + return this.innerProperties() == null ? null : this.innerProperties().zoneStatus(); + } + /** * Validates the instance. * diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/Clusters.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/Clusters.java index c611cb845f3f..e907e8d427ba 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/Clusters.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/Clusters.java @@ -133,6 +133,32 @@ public interface Clusters { void migrate(String resourceGroupName, String clusterName, ClusterMigrateRequest clusterMigrateRequest, Context context); + /** + * Returns a list of databases that are owned by this cluster and were followed by another cluster. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the list Kusto database principals operation response as paginated response with {@link PagedIterable}. + */ + PagedIterable listFollowerDatabasesGet(String resourceGroupName, String clusterName); + + /** + * Returns a list of databases that are owned by this cluster and were followed by another cluster. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the list Kusto database principals operation response as paginated response with {@link PagedIterable}. + */ + PagedIterable listFollowerDatabasesGet(String resourceGroupName, String clusterName, + Context context); + /** * Returns a list of databases that are owned by this cluster and were followed by another cluster. * @@ -354,6 +380,83 @@ Response checkNameAvailabilityWithResponse(String location, Clu PagedIterable listOutboundNetworkDependenciesEndpoints(String resourceGroupName, String clusterName, Context context); + /** + * Adds a list of callout policies for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicies The callout policies to add. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void addCalloutPolicies(String resourceGroupName, String clusterName, CalloutPoliciesList calloutPolicies); + + /** + * Adds a list of callout policies for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicies The callout policies to add. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void addCalloutPolicies(String resourceGroupName, String clusterName, CalloutPoliciesList calloutPolicies, + Context context); + + /** + * Removes callout policy for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicy The callout policies to remove. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void removeCalloutPolicy(String resourceGroupName, String clusterName, CalloutPolicyToRemove calloutPolicy); + + /** + * Removes callout policy for engine services. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param calloutPolicy The callout policies to remove. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void removeCalloutPolicy(String resourceGroupName, String clusterName, CalloutPolicyToRemove calloutPolicy, + Context context); + + /** + * Returns the allowed callout policies for the specified service. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of the service's callout policy objects as paginated response with {@link PagedIterable}. + */ + PagedIterable listCalloutPolicies(String resourceGroupName, String clusterName); + + /** + * Returns the allowed callout policies for the specified service. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param clusterName The name of the Kusto cluster. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of the service's callout policy objects as paginated response with {@link PagedIterable}. + */ + PagedIterable listCalloutPolicies(String resourceGroupName, String clusterName, Context context); + /** * Returns a list of language extensions that can run within KQL queries. * diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/FollowerDatabaseDefinitionGet.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/FollowerDatabaseDefinitionGet.java new file mode 100644 index 000000000000..d5063c80e671 --- /dev/null +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/FollowerDatabaseDefinitionGet.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. + +package com.azure.resourcemanager.kusto.models; + +import com.azure.resourcemanager.kusto.fluent.models.FollowerDatabaseDefinitionGetInner; + +/** + * An immutable client-side representation of FollowerDatabaseDefinitionGet. + */ +public interface FollowerDatabaseDefinitionGet { + /** + * Gets the clusterResourceId property: Resource id of the cluster that follows a database owned by this cluster. + * + * @return the clusterResourceId value. + */ + String clusterResourceId(); + + /** + * Gets the attachedDatabaseConfigurationName property: Resource name of the attached database configuration in the + * follower cluster. + * + * @return the attachedDatabaseConfigurationName value. + */ + String attachedDatabaseConfigurationName(); + + /** + * Gets the databaseName property: The database name owned by this cluster that was followed. * in case following + * all databases. + * + * @return the databaseName value. + */ + String databaseName(); + + /** + * Gets the tableLevelSharingProperties property: Table level sharing specifications. + * + * @return the tableLevelSharingProperties value. + */ + TableLevelSharingProperties tableLevelSharingProperties(); + + /** + * Gets the databaseShareOrigin property: The origin of the following setup. + * + * @return the databaseShareOrigin value. + */ + DatabaseShareOrigin databaseShareOrigin(); + + /** + * Gets the inner com.azure.resourcemanager.kusto.fluent.models.FollowerDatabaseDefinitionGetInner object. + * + * @return the inner object. + */ + FollowerDatabaseDefinitionGetInner innerModel(); +} diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/FollowerDatabaseListResultGet.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/FollowerDatabaseListResultGet.java new file mode 100644 index 000000000000..6e10bcbedded --- /dev/null +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/FollowerDatabaseListResultGet.java @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.kusto.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.resourcemanager.kusto.fluent.models.FollowerDatabaseDefinitionGetInner; +import java.io.IOException; +import java.util.List; + +/** + * The list Kusto database principals operation response. + */ +@Fluent +public final class FollowerDatabaseListResultGet implements JsonSerializable { + /* + * The list of follower database result. + */ + private List value; + + /* + * The URL to get the next set of follower databases list results if there are any. + */ + private String nextLink; + + /** + * Creates an instance of FollowerDatabaseListResultGet class. + */ + public FollowerDatabaseListResultGet() { + } + + /** + * Get the value property: The list of follower database result. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Set the value property: The list of follower database result. + * + * @param value the value value to set. + * @return the FollowerDatabaseListResultGet object itself. + */ + public FollowerDatabaseListResultGet withValue(List value) { + this.value = value; + return this; + } + + /** + * Get the nextLink property: The URL to get the next set of follower databases list results if there are any. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The URL to get the next set of follower databases list results if there are any. + * + * @param nextLink the nextLink value to set. + * @return the FollowerDatabaseListResultGet object itself. + */ + public FollowerDatabaseListResultGet withNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() != null) { + value().forEach(e -> e.validate()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of FollowerDatabaseListResultGet from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of FollowerDatabaseListResultGet 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 FollowerDatabaseListResultGet. + */ + public static FollowerDatabaseListResultGet fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + FollowerDatabaseListResultGet deserializedFollowerDatabaseListResultGet + = new FollowerDatabaseListResultGet(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> FollowerDatabaseDefinitionGetInner.fromJson(reader1)); + deserializedFollowerDatabaseListResultGet.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedFollowerDatabaseListResultGet.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedFollowerDatabaseListResultGet; + }); + } +} diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/LanguageExtensionImageName.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/LanguageExtensionImageName.java index be8735b96787..4359fb1f5c86 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/LanguageExtensionImageName.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/LanguageExtensionImageName.java @@ -36,6 +36,16 @@ public final class LanguageExtensionImageName extends ExpandableStringEnum { + /** + * Static value Allow for OutboundAccess. + */ + public static final OutboundAccess ALLOW = fromString("Allow"); + + /** + * Static value Deny for OutboundAccess. + */ + public static final OutboundAccess DENY = fromString("Deny"); + + /** + * Creates a new instance of OutboundAccess value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public OutboundAccess() { + } + + /** + * Creates or finds a OutboundAccess from its string representation. + * + * @param name a name to look for. + * @return the corresponding OutboundAccess. + */ + public static OutboundAccess fromString(String name) { + return fromString(name, OutboundAccess.class); + } + + /** + * Gets known OutboundAccess values. + * + * @return known OutboundAccess values. + */ + public static Collection values() { + return values(OutboundAccess.class); + } +} diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/PrincipalPermissionsAction.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/PrincipalPermissionsAction.java new file mode 100644 index 000000000000..55582a103661 --- /dev/null +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/PrincipalPermissionsAction.java @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.kusto.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Indicates if the permissions for the script caller are kept following completion of the script. + */ +public final class PrincipalPermissionsAction extends ExpandableStringEnum { + /** + * Static value RetainPermissionOnScriptCompletion for PrincipalPermissionsAction. + */ + public static final PrincipalPermissionsAction RETAIN_PERMISSION_ON_SCRIPT_COMPLETION + = fromString("RetainPermissionOnScriptCompletion"); + + /** + * Static value RemovePermissionOnScriptCompletion for PrincipalPermissionsAction. + */ + public static final PrincipalPermissionsAction REMOVE_PERMISSION_ON_SCRIPT_COMPLETION + = fromString("RemovePermissionOnScriptCompletion"); + + /** + * Creates a new instance of PrincipalPermissionsAction value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public PrincipalPermissionsAction() { + } + + /** + * Creates or finds a PrincipalPermissionsAction from its string representation. + * + * @param name a name to look for. + * @return the corresponding PrincipalPermissionsAction. + */ + public static PrincipalPermissionsAction fromString(String name) { + return fromString(name, PrincipalPermissionsAction.class); + } + + /** + * Gets known PrincipalPermissionsAction values. + * + * @return known PrincipalPermissionsAction values. + */ + public static Collection values() { + return values(PrincipalPermissionsAction.class); + } +} diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/SandboxCustomImage.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/SandboxCustomImage.java index b664326edce0..3f7c4823abee 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/SandboxCustomImage.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/SandboxCustomImage.java @@ -40,12 +40,22 @@ public interface SandboxCustomImage { Language language(); /** - * Gets the languageVersion property: The version of the language. + * Gets the languageVersion property: The version of the language. Either this property or baseImageName should be + * specified. * * @return the languageVersion value. */ String languageVersion(); + /** + * Gets the baseImageName property: The base image name on which the custom image is built on top of. It can be one + * of the LanguageExtensionImageName (e.g.: 'Python3_10_8', 'Python3_10_8_DL') or the name of an existing custom + * image. Either this property or languageVersion should be specified. + * + * @return the baseImageName value. + */ + String baseImageName(); + /** * Gets the requirementsFileContent property: The requirements file content. * @@ -110,7 +120,7 @@ interface WithParentResource { * resource to be created, but also allows for any other optional properties to be specified. */ interface WithCreate extends DefinitionStages.WithLanguage, DefinitionStages.WithLanguageVersion, - DefinitionStages.WithRequirementsFileContent { + DefinitionStages.WithBaseImageName, DefinitionStages.WithRequirementsFileContent { /** * Executes the create request. * @@ -145,14 +155,33 @@ interface WithLanguage { */ interface WithLanguageVersion { /** - * Specifies the languageVersion property: The version of the language.. + * Specifies the languageVersion property: The version of the language. Either this property or + * baseImageName should be specified.. * - * @param languageVersion The version of the language. + * @param languageVersion The version of the language. Either this property or baseImageName should be + * specified. * @return the next definition stage. */ WithCreate withLanguageVersion(String languageVersion); } + /** + * The stage of the SandboxCustomImage definition allowing to specify baseImageName. + */ + interface WithBaseImageName { + /** + * Specifies the baseImageName property: The base image name on which the custom image is built on top of. + * It can be one of the LanguageExtensionImageName (e.g.: 'Python3_10_8', 'Python3_10_8_DL') or the name of + * an existing custom image. Either this property or languageVersion should be specified.. + * + * @param baseImageName The base image name on which the custom image is built on top of. It can be one of + * the LanguageExtensionImageName (e.g.: 'Python3_10_8', 'Python3_10_8_DL') or the name of an existing + * custom image. Either this property or languageVersion should be specified. + * @return the next definition stage. + */ + WithCreate withBaseImageName(String baseImageName); + } + /** * The stage of the SandboxCustomImage definition allowing to specify requirementsFileContent. */ @@ -177,8 +206,8 @@ interface WithRequirementsFileContent { /** * The template for SandboxCustomImage update. */ - interface Update - extends UpdateStages.WithLanguage, UpdateStages.WithLanguageVersion, UpdateStages.WithRequirementsFileContent { + interface Update extends UpdateStages.WithLanguage, UpdateStages.WithLanguageVersion, + UpdateStages.WithBaseImageName, UpdateStages.WithRequirementsFileContent { /** * Executes the update request. * @@ -217,14 +246,33 @@ interface WithLanguage { */ interface WithLanguageVersion { /** - * Specifies the languageVersion property: The version of the language.. + * Specifies the languageVersion property: The version of the language. Either this property or + * baseImageName should be specified.. * - * @param languageVersion The version of the language. + * @param languageVersion The version of the language. Either this property or baseImageName should be + * specified. * @return the next definition stage. */ Update withLanguageVersion(String languageVersion); } + /** + * The stage of the SandboxCustomImage update allowing to specify baseImageName. + */ + interface WithBaseImageName { + /** + * Specifies the baseImageName property: The base image name on which the custom image is built on top of. + * It can be one of the LanguageExtensionImageName (e.g.: 'Python3_10_8', 'Python3_10_8_DL') or the name of + * an existing custom image. Either this property or languageVersion should be specified.. + * + * @param baseImageName The base image name on which the custom image is built on top of. It can be one of + * the LanguageExtensionImageName (e.g.: 'Python3_10_8', 'Python3_10_8_DL') or the name of an existing + * custom image. Either this property or languageVersion should be specified. + * @return the next definition stage. + */ + Update withBaseImageName(String baseImageName); + } + /** * The stage of the SandboxCustomImage update allowing to specify requirementsFileContent. */ diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/Script.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/Script.java index a15859c2ddf2..8f0d3e4a47bf 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/Script.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/Script.java @@ -85,6 +85,22 @@ public interface Script { */ ProvisioningState provisioningState(); + /** + * Gets the scriptLevel property: Differentiates between the type of script commands included - Database or Cluster. + * The default is Database. + * + * @return the scriptLevel value. + */ + ScriptLevel scriptLevel(); + + /** + * Gets the principalPermissionsAction property: Indicates if the permissions for the script caller are kept + * following completion of the script. + * + * @return the principalPermissionsAction value. + */ + PrincipalPermissionsAction principalPermissionsAction(); + /** * Gets the name of the resource group. * @@ -137,7 +153,8 @@ interface WithParentResource { */ interface WithCreate extends DefinitionStages.WithScriptUrl, DefinitionStages.WithScriptUrlSasToken, DefinitionStages.WithScriptContent, DefinitionStages.WithForceUpdateTag, - DefinitionStages.WithContinueOnErrors { + DefinitionStages.WithContinueOnErrors, DefinitionStages.WithScriptLevel, + DefinitionStages.WithPrincipalPermissionsAction { /** * Executes the create request. * @@ -226,6 +243,36 @@ interface WithContinueOnErrors { */ WithCreate withContinueOnErrors(Boolean continueOnErrors); } + + /** + * The stage of the Script definition allowing to specify scriptLevel. + */ + interface WithScriptLevel { + /** + * Specifies the scriptLevel property: Differentiates between the type of script commands included - + * Database or Cluster. The default is Database.. + * + * @param scriptLevel Differentiates between the type of script commands included - Database or Cluster. The + * default is Database. + * @return the next definition stage. + */ + WithCreate withScriptLevel(ScriptLevel scriptLevel); + } + + /** + * The stage of the Script definition allowing to specify principalPermissionsAction. + */ + interface WithPrincipalPermissionsAction { + /** + * Specifies the principalPermissionsAction property: Indicates if the permissions for the script caller are + * kept following completion of the script.. + * + * @param principalPermissionsAction Indicates if the permissions for the script caller are kept following + * completion of the script. + * @return the next definition stage. + */ + WithCreate withPrincipalPermissionsAction(PrincipalPermissionsAction principalPermissionsAction); + } } /** @@ -238,8 +285,8 @@ interface WithContinueOnErrors { /** * The template for Script update. */ - interface Update - extends UpdateStages.WithScriptUrl, UpdateStages.WithForceUpdateTag, UpdateStages.WithContinueOnErrors { + interface Update extends UpdateStages.WithScriptUrl, UpdateStages.WithForceUpdateTag, + UpdateStages.WithContinueOnErrors, UpdateStages.WithScriptLevel, UpdateStages.WithPrincipalPermissionsAction { /** * Executes the update request. * @@ -301,6 +348,36 @@ interface WithContinueOnErrors { */ Update withContinueOnErrors(Boolean continueOnErrors); } + + /** + * The stage of the Script update allowing to specify scriptLevel. + */ + interface WithScriptLevel { + /** + * Specifies the scriptLevel property: Differentiates between the type of script commands included - + * Database or Cluster. The default is Database.. + * + * @param scriptLevel Differentiates between the type of script commands included - Database or Cluster. The + * default is Database. + * @return the next definition stage. + */ + Update withScriptLevel(ScriptLevel scriptLevel); + } + + /** + * The stage of the Script update allowing to specify principalPermissionsAction. + */ + interface WithPrincipalPermissionsAction { + /** + * Specifies the principalPermissionsAction property: Indicates if the permissions for the script caller are + * kept following completion of the script.. + * + * @param principalPermissionsAction Indicates if the permissions for the script caller are kept following + * completion of the script. + * @return the next definition stage. + */ + Update withPrincipalPermissionsAction(PrincipalPermissionsAction principalPermissionsAction); + } } /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/ScriptLevel.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/ScriptLevel.java new file mode 100644 index 000000000000..851de2598956 --- /dev/null +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/ScriptLevel.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.kusto.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Differentiates between the type of script commands included - Database or Cluster. The default is Database. + */ +public final class ScriptLevel extends ExpandableStringEnum { + /** + * Static value Database for ScriptLevel. + */ + public static final ScriptLevel DATABASE = fromString("Database"); + + /** + * Static value Cluster for ScriptLevel. + */ + public static final ScriptLevel CLUSTER = fromString("Cluster"); + + /** + * Creates a new instance of ScriptLevel value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public ScriptLevel() { + } + + /** + * Creates or finds a ScriptLevel from its string representation. + * + * @param name a name to look for. + * @return the corresponding ScriptLevel. + */ + public static ScriptLevel fromString(String name) { + return fromString(name, ScriptLevel.class); + } + + /** + * Gets known ScriptLevel values. + * + * @return known ScriptLevel values. + */ + public static Collection values() { + return values(ScriptLevel.class); + } +} diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/ZoneStatus.java b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/ZoneStatus.java new file mode 100644 index 000000000000..d87548b4e311 --- /dev/null +++ b/sdk/kusto/azure-resourcemanager-kusto/src/main/java/com/azure/resourcemanager/kusto/models/ZoneStatus.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. + +package com.azure.resourcemanager.kusto.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Indicates whether the cluster is zonal or non-zonal. + */ +public final class ZoneStatus extends ExpandableStringEnum { + /** + * Static value NonZonal for ZoneStatus. + */ + public static final ZoneStatus NON_ZONAL = fromString("NonZonal"); + + /** + * Static value ZonalInconsistency for ZoneStatus. + */ + public static final ZoneStatus ZONAL_INCONSISTENCY = fromString("ZonalInconsistency"); + + /** + * Static value Zonal for ZoneStatus. + */ + public static final ZoneStatus ZONAL = fromString("Zonal"); + + /** + * Creates a new instance of ZoneStatus value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public ZoneStatus() { + } + + /** + * Creates or finds a ZoneStatus from its string representation. + * + * @param name a name to look for. + * @return the corresponding ZoneStatus. + */ + public static ZoneStatus fromString(String name) { + return fromString(name, ZoneStatus.class); + } + + /** + * Gets known ZoneStatus values. + * + * @return known ZoneStatus values. + */ + public static Collection values() { + return values(ZoneStatus.class); + } +} diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsCheckNameAvailabilitySamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsCheckNameAvailabilitySamples.java index 920aa1c8551c..4ac6ad03e1d8 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsCheckNameAvailabilitySamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsCheckNameAvailabilitySamples.java @@ -11,7 +11,7 @@ */ public final class AttachedDatabaseConfigurationsCheckNameAvailabilitySamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoAttachedDatabaseConfigurationCheckNameAvailability.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsCreateOrUpdateSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsCreateOrUpdateSamples.java index 50b967b8b069..19a7a9e85ad9 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsCreateOrUpdateSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsCreateOrUpdateSamples.java @@ -13,7 +13,7 @@ */ public final class AttachedDatabaseConfigurationsCreateOrUpdateSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoAttachedDatabaseConfigurationsCreateOrUpdate.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsDeleteSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsDeleteSamples.java index 456f0a97e871..0a7a154e6fe6 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsDeleteSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsDeleteSamples.java @@ -9,7 +9,7 @@ */ public final class AttachedDatabaseConfigurationsDeleteSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoAttachedDatabaseConfigurationsDelete.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsGetSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsGetSamples.java index bbd23a3138ff..906e38b32db2 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsGetSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsGetSamples.java @@ -9,7 +9,7 @@ */ public final class AttachedDatabaseConfigurationsGetSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoAttachedDatabaseConfigurationsGet.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsListByClusterSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsListByClusterSamples.java index 4d213f2cd2ec..663cede4db2a 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsListByClusterSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsListByClusterSamples.java @@ -9,7 +9,7 @@ */ public final class AttachedDatabaseConfigurationsListByClusterSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoAttachedDatabaseConfigurationsListByCluster.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsCheckNameAvailabilitySamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsCheckNameAvailabilitySamples.java index 282e280c3c5f..3896f00655f5 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsCheckNameAvailabilitySamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsCheckNameAvailabilitySamples.java @@ -11,7 +11,7 @@ */ public final class ClusterPrincipalAssignmentsCheckNameAvailabilitySamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoClusterPrincipalAssignmentsCheckNameAvailability.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsCreateOrUpdateSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsCreateOrUpdateSamples.java index 0c1d9ec64687..490f06a3767e 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsCreateOrUpdateSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsCreateOrUpdateSamples.java @@ -12,7 +12,7 @@ */ public final class ClusterPrincipalAssignmentsCreateOrUpdateSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoClusterPrincipalAssignmentsCreateOrUpdate.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsDeleteSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsDeleteSamples.java index 63ba72f131b1..6145db794835 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsDeleteSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsDeleteSamples.java @@ -9,7 +9,7 @@ */ public final class ClusterPrincipalAssignmentsDeleteSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoClusterPrincipalAssignmentsDelete.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsGetSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsGetSamples.java index 2c272f74f9a1..3042fdcc69e2 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsGetSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsGetSamples.java @@ -9,7 +9,7 @@ */ public final class ClusterPrincipalAssignmentsGetSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoClusterPrincipalAssignmentsGet.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsListSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsListSamples.java index c68d4272c6d0..a82a70c5ab63 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsListSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsListSamples.java @@ -9,7 +9,7 @@ */ public final class ClusterPrincipalAssignmentsListSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoClusterPrincipalAssignmentsList.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersAddCalloutPoliciesSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersAddCalloutPoliciesSamples.java new file mode 100644 index 000000000000..78d5bc8523b4 --- /dev/null +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersAddCalloutPoliciesSamples.java @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.kusto.generated; + +import com.azure.resourcemanager.kusto.fluent.models.CalloutPolicyInner; +import com.azure.resourcemanager.kusto.models.CalloutPoliciesList; +import com.azure.resourcemanager.kusto.models.CalloutType; +import com.azure.resourcemanager.kusto.models.OutboundAccess; +import java.util.Arrays; + +/** + * Samples for Clusters AddCalloutPolicies. + */ +public final class ClustersAddCalloutPoliciesSamples { + /* + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ + * KustoClusterAddCalloutPolicies.json + */ + /** + * Sample code: KustoClusterAddCalloutPolicy. + * + * @param manager Entry point to KustoManager. + */ + public static void kustoClusterAddCalloutPolicy(com.azure.resourcemanager.kusto.KustoManager manager) { + manager.clusters() + .addCalloutPolicies("kustorptest", "kustoCluster", + new CalloutPoliciesList().withValue(Arrays.asList(new CalloutPolicyInner().withCalloutUriRegex("*") + .withCalloutType(CalloutType.KUSTO) + .withOutboundAccess(OutboundAccess.ALLOW))), + com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersAddLanguageExtensionsSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersAddLanguageExtensionsSamples.java index ccf7250ed209..64de6fe79368 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersAddLanguageExtensionsSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersAddLanguageExtensionsSamples.java @@ -14,7 +14,7 @@ */ public final class ClustersAddLanguageExtensionsSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoClusterAddLanguageExtensions.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersCheckNameAvailabilitySamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersCheckNameAvailabilitySamples.java index 5a5e38d3b774..5d9e4486379b 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersCheckNameAvailabilitySamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersCheckNameAvailabilitySamples.java @@ -11,7 +11,7 @@ */ public final class ClustersCheckNameAvailabilitySamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoClustersCheckNameAvailability.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersCreateOrUpdateSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersCreateOrUpdateSamples.java index 0e09f97537a8..bd9c17dbb3ec 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersCreateOrUpdateSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersCreateOrUpdateSamples.java @@ -23,7 +23,7 @@ public final class ClustersCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoClustersCreateOrUpdate + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoClustersCreateOrUpdate * .json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersDeleteSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersDeleteSamples.java index 45d556920dfd..ba46bfd96afb 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersDeleteSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersDeleteSamples.java @@ -10,7 +10,7 @@ public final class ClustersDeleteSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoClustersDelete.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoClustersDelete.json */ /** * Sample code: KustoClustersDelete. diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersDetachFollowerDatabasesSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersDetachFollowerDatabasesSamples.java index 6983878bf739..e00bcdedc7b3 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersDetachFollowerDatabasesSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersDetachFollowerDatabasesSamples.java @@ -11,7 +11,7 @@ */ public final class ClustersDetachFollowerDatabasesSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoClusterDetachFollowerDatabases.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersDiagnoseVirtualNetworkSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersDiagnoseVirtualNetworkSamples.java index dbc603158e0c..9d0178f6f8e5 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersDiagnoseVirtualNetworkSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersDiagnoseVirtualNetworkSamples.java @@ -9,7 +9,7 @@ */ public final class ClustersDiagnoseVirtualNetworkSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoClustersDiagnoseVirtualNetwork.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersGetByResourceGroupSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersGetByResourceGroupSamples.java index 1d18c7092ec2..62111d80d418 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersGetByResourceGroupSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersGetByResourceGroupSamples.java @@ -10,7 +10,7 @@ public final class ClustersGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoClustersGet.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoClustersGet.json */ /** * Sample code: KustoClustersGet. diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListByResourceGroupSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListByResourceGroupSamples.java index 55e131b44666..af7e2669dc8c 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListByResourceGroupSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListByResourceGroupSamples.java @@ -9,7 +9,7 @@ */ public final class ClustersListByResourceGroupSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoClustersListByResourceGroup.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListCalloutPoliciesSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListCalloutPoliciesSamples.java new file mode 100644 index 000000000000..eb3181242233 --- /dev/null +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListCalloutPoliciesSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.kusto.generated; + +/** + * Samples for Clusters ListCalloutPolicies. + */ +public final class ClustersListCalloutPoliciesSamples { + /* + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ + * KustoClustersListCalloutPolicies.json + */ + /** + * Sample code: KustoClusterListCalloutPolicies. + * + * @param manager Entry point to KustoManager. + */ + public static void kustoClusterListCalloutPolicies(com.azure.resourcemanager.kusto.KustoManager manager) { + manager.clusters().listCalloutPolicies("kustorptest", "kustoCluster", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListFollowerDatabasesGetSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListFollowerDatabasesGetSamples.java new file mode 100644 index 000000000000..a0e842fd7998 --- /dev/null +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListFollowerDatabasesGetSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.kusto.generated; + +/** + * Samples for Clusters ListFollowerDatabasesGet. + */ +public final class ClustersListFollowerDatabasesGetSamples { + /* + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ + * KustoClusterListFollowerDatabasesGet.json + */ + /** + * Sample code: KustoClusterListFollowerDatabasesGet. + * + * @param manager Entry point to KustoManager. + */ + public static void kustoClusterListFollowerDatabasesGet(com.azure.resourcemanager.kusto.KustoManager manager) { + manager.clusters().listFollowerDatabasesGet("kustorptest", "kustoCluster", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListFollowerDatabasesSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListFollowerDatabasesSamples.java index ab7aef9065af..786b42b45739 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListFollowerDatabasesSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListFollowerDatabasesSamples.java @@ -9,7 +9,7 @@ */ public final class ClustersListFollowerDatabasesSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoClusterListFollowerDatabases.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListLanguageExtensionsSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListLanguageExtensionsSamples.java index 4ac44a9baaec..b9e8d9da74a4 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListLanguageExtensionsSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListLanguageExtensionsSamples.java @@ -9,7 +9,7 @@ */ public final class ClustersListLanguageExtensionsSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoClusterListLanguageExtensions.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListOutboundNetworkDependenciesEndpointsSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListOutboundNetworkDependenciesEndpointsSamples.java index be09bd43e421..4a8a4a59c839 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListOutboundNetworkDependenciesEndpointsSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListOutboundNetworkDependenciesEndpointsSamples.java @@ -9,7 +9,7 @@ */ public final class ClustersListOutboundNetworkDependenciesEndpointsSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoOutboundNetworkDependenciesList.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListSamples.java index 069ed4bb1f8d..d9caa40daa55 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListSamples.java @@ -10,7 +10,7 @@ public final class ClustersListSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoClustersList.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoClustersList.json */ /** * Sample code: KustoClustersList. diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListSkusByResourceSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListSkusByResourceSamples.java index 0cc3f726ea87..93788cd54f82 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListSkusByResourceSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListSkusByResourceSamples.java @@ -9,7 +9,7 @@ */ public final class ClustersListSkusByResourceSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoClustersListResourceSkus.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListSkusSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListSkusSamples.java index f37ebcd4e36b..77b342190b67 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListSkusSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersListSkusSamples.java @@ -10,7 +10,7 @@ public final class ClustersListSkusSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoClustersListSkus.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoClustersListSkus.json */ /** * Sample code: KustoClustersListSkus. diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersMigrateSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersMigrateSamples.java index 73b45c03a3c3..cd2fae45913a 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersMigrateSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersMigrateSamples.java @@ -12,7 +12,7 @@ public final class ClustersMigrateSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoClusterMigrate.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoClusterMigrate.json */ /** * Sample code: KustoClusterMigrate. diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersRemoveCalloutPolicySamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersRemoveCalloutPolicySamples.java new file mode 100644 index 000000000000..dc89b88c5034 --- /dev/null +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersRemoveCalloutPolicySamples.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.kusto.generated; + +import com.azure.resourcemanager.kusto.models.CalloutPolicyToRemove; + +/** + * Samples for Clusters RemoveCalloutPolicy. + */ +public final class ClustersRemoveCalloutPolicySamples { + /* + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ + * KustoClusterRemoveCalloutPolicy.json + */ + /** + * Sample code: KustoClusterDropCalloutPolicy. + * + * @param manager Entry point to KustoManager. + */ + public static void kustoClusterDropCalloutPolicy(com.azure.resourcemanager.kusto.KustoManager manager) { + manager.clusters() + .removeCalloutPolicy("kustorptest", "kustoCluster", new CalloutPolicyToRemove().withCalloutId("*_kusto"), + com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersRemoveLanguageExtensionsSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersRemoveLanguageExtensionsSamples.java index aa4074c57fea..431029325d1c 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersRemoveLanguageExtensionsSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersRemoveLanguageExtensionsSamples.java @@ -14,7 +14,7 @@ */ public final class ClustersRemoveLanguageExtensionsSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoClusterRemoveLanguageExtensions.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersStartSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersStartSamples.java index af6069c550d2..43364e5bd97d 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersStartSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersStartSamples.java @@ -10,7 +10,7 @@ public final class ClustersStartSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoClustersStart.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoClustersStart.json */ /** * Sample code: KustoClustersStart. diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersStopSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersStopSamples.java index d0f74063c4e3..3ff521da8a6f 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersStopSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersStopSamples.java @@ -10,7 +10,7 @@ public final class ClustersStopSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoClustersStop.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoClustersStop.json */ /** * Sample code: KustoClustersStop. diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersUpdateSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersUpdateSamples.java index d1fae7a1793e..df210ad7658e 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersUpdateSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ClustersUpdateSamples.java @@ -12,7 +12,7 @@ public final class ClustersUpdateSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoClustersUpdate.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoClustersUpdate.json */ /** * Sample code: KustoClustersUpdate. diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DataConnectionsCheckNameAvailabilitySamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DataConnectionsCheckNameAvailabilitySamples.java index 608d5ae03614..7da718cfcc64 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DataConnectionsCheckNameAvailabilitySamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DataConnectionsCheckNameAvailabilitySamples.java @@ -11,7 +11,7 @@ */ public final class DataConnectionsCheckNameAvailabilitySamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDataConnectionsCheckNameAvailability.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DataConnectionsCreateOrUpdateSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DataConnectionsCreateOrUpdateSamples.java index faeadffe0362..34b85f0553f9 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DataConnectionsCreateOrUpdateSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DataConnectionsCreateOrUpdateSamples.java @@ -17,7 +17,7 @@ */ public final class DataConnectionsCreateOrUpdateSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDataConnectionsEventGridCreateOrUpdate.json */ /** @@ -39,7 +39,7 @@ public final class DataConnectionsCreateOrUpdateSamples { .withConsumerGroup("$Default") .withTableName("TestTable") .withMappingRuleName("TestMapping") - .withDataFormat(EventGridDataFormat.JSON) + .withDataFormat(EventGridDataFormat.MULTIJSON) .withIgnoreFirstRecord(false) .withBlobStorageEventType(BlobStorageEventType.MICROSOFT_STORAGE_BLOB_CREATED) .withManagedIdentityResourceId( @@ -49,7 +49,7 @@ public final class DataConnectionsCreateOrUpdateSamples { } /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDataConnectionsCosmosDbCreateOrUpdate.json */ /** @@ -75,7 +75,7 @@ public final class DataConnectionsCreateOrUpdateSamples { } /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDataConnectionsCreateOrUpdate.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DataConnectionsDataConnectionValidationSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DataConnectionsDataConnectionValidationSamples.java index 0e61f1eb2986..59192bc42a63 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DataConnectionsDataConnectionValidationSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DataConnectionsDataConnectionValidationSamples.java @@ -18,7 +18,7 @@ */ public final class DataConnectionsDataConnectionValidationSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDataConnectionValidationAsync.json */ /** @@ -35,7 +35,7 @@ public static void kustoDataConnectionValidation(com.azure.resourcemanager.kusto .withConsumerGroup("testConsumerGroup1") .withTableName("TestTable") .withMappingRuleName("TestMapping") - .withDataFormat(EventHubDataFormat.JSON) + .withDataFormat(EventHubDataFormat.MULTIJSON) .withCompression(Compression.NONE) .withManagedIdentityResourceId( "/subscriptions/12345678-1234-1234-1234-123456789098/resourceGroups/kustorptest/providers/Microsoft.ManagedIdentity/userAssignedIdentities/managedidentityTest1")), @@ -43,7 +43,7 @@ public static void kustoDataConnectionValidation(com.azure.resourcemanager.kusto } /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDataConnectionEventGridValidationAsync.json */ /** @@ -64,7 +64,7 @@ public static void kustoDataConnectionEventGridValidation(com.azure.resourcemana .withConsumerGroup("$Default") .withTableName("TestTable") .withMappingRuleName("TestMapping") - .withDataFormat(EventGridDataFormat.JSON) + .withDataFormat(EventGridDataFormat.MULTIJSON) .withIgnoreFirstRecord(false) .withBlobStorageEventType(BlobStorageEventType.MICROSOFT_STORAGE_BLOB_CREATED) .withManagedIdentityResourceId( diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DataConnectionsDeleteSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DataConnectionsDeleteSamples.java index 00557400d98d..996e0373eb2b 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DataConnectionsDeleteSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DataConnectionsDeleteSamples.java @@ -10,7 +10,7 @@ public final class DataConnectionsDeleteSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoDataConnectionsDelete. + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoDataConnectionsDelete. * json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DataConnectionsGetSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DataConnectionsGetSamples.java index 5fa91b47b6df..ebe23027a4e1 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DataConnectionsGetSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DataConnectionsGetSamples.java @@ -9,7 +9,7 @@ */ public final class DataConnectionsGetSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDataConnectionsEventGridGet.json */ /** @@ -24,7 +24,7 @@ public static void kustoDataConnectionsEventGridGet(com.azure.resourcemanager.ku } /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDataConnectionsCosmosDbGet.json */ /** @@ -40,7 +40,7 @@ public static void kustoDataConnectionsCosmosDbGet(com.azure.resourcemanager.kus /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoDataConnectionsGet. + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoDataConnectionsGet. * json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DataConnectionsListByDatabaseSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DataConnectionsListByDatabaseSamples.java index 07a1bc33d35f..b9145713a1a1 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DataConnectionsListByDatabaseSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DataConnectionsListByDatabaseSamples.java @@ -9,7 +9,7 @@ */ public final class DataConnectionsListByDatabaseSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDataConnectionsListByDatabase.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DataConnectionsUpdateSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DataConnectionsUpdateSamples.java index a86dfbc2c023..f64793be5c20 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DataConnectionsUpdateSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DataConnectionsUpdateSamples.java @@ -17,7 +17,7 @@ */ public final class DataConnectionsUpdateSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDataConnectionsCosmosDbUpdate.json */ /** @@ -43,7 +43,7 @@ public static void kustoDataConnectionsCosmosDbUpdate(com.azure.resourcemanager. /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoDataConnectionsUpdate. + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoDataConnectionsUpdate. * json */ /** @@ -64,7 +64,7 @@ public static void kustoDataConnectionsUpdate(com.azure.resourcemanager.kusto.Ku } /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDataConnectionsEventGridUpdate.json */ /** @@ -85,7 +85,7 @@ public static void kustoDataConnectionsEventGridUpdate(com.azure.resourcemanager .withConsumerGroup("$Default") .withTableName("TestTable") .withMappingRuleName("TestMapping") - .withDataFormat(EventGridDataFormat.JSON) + .withDataFormat(EventGridDataFormat.MULTIJSON) .withIgnoreFirstRecord(false) .withBlobStorageEventType(BlobStorageEventType.MICROSOFT_STORAGE_BLOB_CREATED) .withManagedIdentityResourceId( diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabaseOperationInviteFollowerSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabaseOperationInviteFollowerSamples.java index c3d638b32752..d03ff0fb34eb 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabaseOperationInviteFollowerSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabaseOperationInviteFollowerSamples.java @@ -14,7 +14,7 @@ public final class DatabaseOperationInviteFollowerSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoDatabaseInviteFollower + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoDatabaseInviteFollower * .json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsCheckNameAvailabilitySamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsCheckNameAvailabilitySamples.java index 9dfe6ba18031..467e67493cac 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsCheckNameAvailabilitySamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsCheckNameAvailabilitySamples.java @@ -11,7 +11,7 @@ */ public final class DatabasePrincipalAssignmentsCheckNameAvailabilitySamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDatabasePrincipalAssignmentsCheckNameAvailability.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsCreateOrUpdateSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsCreateOrUpdateSamples.java index 5e9c9e95032b..bbb27572e032 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsCreateOrUpdateSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsCreateOrUpdateSamples.java @@ -12,7 +12,7 @@ */ public final class DatabasePrincipalAssignmentsCreateOrUpdateSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDatabasePrincipalAssignmentsCreateOrUpdate.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsDeleteSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsDeleteSamples.java index e8762f8770bc..169c971f11b5 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsDeleteSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsDeleteSamples.java @@ -9,7 +9,7 @@ */ public final class DatabasePrincipalAssignmentsDeleteSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDatabasePrincipalAssignmentsDelete.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsGetSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsGetSamples.java index dc0df7c556d2..200722a7dca7 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsGetSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsGetSamples.java @@ -9,7 +9,7 @@ */ public final class DatabasePrincipalAssignmentsGetSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDatabasePrincipalAssignmentsGet.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsListSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsListSamples.java index 09d13f8131ba..334aec650dbe 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsListSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsListSamples.java @@ -9,7 +9,7 @@ */ public final class DatabasePrincipalAssignmentsListSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDatabasePrincipalAssignmentsList.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesAddPrincipalsSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesAddPrincipalsSamples.java index da19decf4182..a1e3965be850 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesAddPrincipalsSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesAddPrincipalsSamples.java @@ -16,7 +16,7 @@ public final class DatabasesAddPrincipalsSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoDatabaseAddPrincipals. + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoDatabaseAddPrincipals. * json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesCheckNameAvailabilitySamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesCheckNameAvailabilitySamples.java index 74b787cfbee6..a71c7064340c 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesCheckNameAvailabilitySamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesCheckNameAvailabilitySamples.java @@ -12,7 +12,7 @@ */ public final class DatabasesCheckNameAvailabilitySamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDatabasesCheckNameAvailability.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesCreateOrUpdateSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesCreateOrUpdateSamples.java index 0e901295d91d..feb0f87b6231 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesCreateOrUpdateSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesCreateOrUpdateSamples.java @@ -15,7 +15,7 @@ public final class DatabasesCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoDatabaseReadonlyUpdate + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoDatabaseReadonlyUpdate * .json */ /** @@ -31,7 +31,7 @@ public static void kustoReadOnlyDatabaseUpdate(com.azure.resourcemanager.kusto.K } /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDatabasesCreateOrUpdate.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesDeleteSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesDeleteSamples.java index 690b0c7e472f..2b6e4b5a4a4f 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesDeleteSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesDeleteSamples.java @@ -10,7 +10,7 @@ public final class DatabasesDeleteSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoDatabasesDelete.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoDatabasesDelete.json */ /** * Sample code: KustoDatabasesDelete. diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesGetSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesGetSamples.java index 8e0b12ebd51c..030fa9a64e9a 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesGetSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesGetSamples.java @@ -10,7 +10,7 @@ public final class DatabasesGetSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoSuspendedDatabasesGet. + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoSuspendedDatabasesGet. * json */ /** @@ -25,7 +25,7 @@ public static void kustoSuspendedDatabasesGet(com.azure.resourcemanager.kusto.Ku /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoDatabasesGet.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoDatabasesGet.json */ /** * Sample code: KustoDatabasesGet. diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesListByClusterSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesListByClusterSamples.java index ee079c6c96b4..aba6a5bfdc6a 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesListByClusterSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesListByClusterSamples.java @@ -10,7 +10,7 @@ public final class DatabasesListByClusterSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoDatabasesListByCluster + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoDatabasesListByCluster * .json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesListPrincipalsSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesListPrincipalsSamples.java index ee4df5e555e5..11fa11f49d04 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesListPrincipalsSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesListPrincipalsSamples.java @@ -10,7 +10,7 @@ public final class DatabasesListPrincipalsSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoDatabaseListPrincipals + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoDatabaseListPrincipals * .json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesRemovePrincipalsSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesRemovePrincipalsSamples.java index 014091451f61..004d64d1456d 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesRemovePrincipalsSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesRemovePrincipalsSamples.java @@ -15,7 +15,7 @@ */ public final class DatabasesRemovePrincipalsSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoDatabaseRemovePrincipals.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesUpdateSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesUpdateSamples.java index 4a18afab1620..221efa8bd426 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesUpdateSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/DatabasesUpdateSamples.java @@ -13,7 +13,7 @@ public final class DatabasesUpdateSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoDatabasesUpdate.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoDatabasesUpdate.json */ /** * Sample code: KustoDatabasesUpdate. diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsCheckNameAvailabilitySamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsCheckNameAvailabilitySamples.java index 599f0d7f36a1..f47700661ca3 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsCheckNameAvailabilitySamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsCheckNameAvailabilitySamples.java @@ -11,7 +11,7 @@ */ public final class ManagedPrivateEndpointsCheckNameAvailabilitySamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoManagedPrivateEndpointsCheckNameAvailability.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsCreateOrUpdateSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsCreateOrUpdateSamples.java index 5af128d6c732..cb81083d99d5 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsCreateOrUpdateSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsCreateOrUpdateSamples.java @@ -9,7 +9,7 @@ */ public final class ManagedPrivateEndpointsCreateOrUpdateSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoManagedPrivateEndpointsCreateOrUpdate.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsDeleteSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsDeleteSamples.java index 02fbcd440bfb..26672ed3115f 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsDeleteSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsDeleteSamples.java @@ -9,7 +9,7 @@ */ public final class ManagedPrivateEndpointsDeleteSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoManagedPrivateEndpointsDelete.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsGetSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsGetSamples.java index e400e43c3637..420824716ff6 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsGetSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsGetSamples.java @@ -9,7 +9,7 @@ */ public final class ManagedPrivateEndpointsGetSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoManagedPrivateEndpointsGet.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsListSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsListSamples.java index 53a169ba2278..5305d0f3d5c7 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsListSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsListSamples.java @@ -9,7 +9,7 @@ */ public final class ManagedPrivateEndpointsListSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoManagedPrivateEndpointsList.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsUpdateSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsUpdateSamples.java index ab6f333683a3..4f061f769139 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsUpdateSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsUpdateSamples.java @@ -11,7 +11,7 @@ */ public final class ManagedPrivateEndpointsUpdateSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoManagedPrivateEndpointsUpdate.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/OperationsListSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/OperationsListSamples.java index 2d9ce0ddb0e8..4f573bc340c2 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/OperationsListSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/OperationsListSamples.java @@ -10,7 +10,7 @@ public final class OperationsListSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoOperationsList.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoOperationsList.json */ /** * Sample code: KustoOperationsList. diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/OperationsResultsGetSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/OperationsResultsGetSamples.java index ed10e94d6dfd..1179cc96ccbb 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/OperationsResultsGetSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/OperationsResultsGetSamples.java @@ -10,7 +10,7 @@ public final class OperationsResultsGetSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoOperationResultsGet. + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoOperationResultsGet. * json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/OperationsResultsLocationGetSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/OperationsResultsLocationGetSamples.java index 4efd0f54d680..d4a249052b99 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/OperationsResultsLocationGetSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/OperationsResultsLocationGetSamples.java @@ -9,7 +9,7 @@ */ public final class OperationsResultsLocationGetSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoOperationResultsOperationResultResponseTypeGet.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsCreateOrUpdateSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsCreateOrUpdateSamples.java index 06d310913213..e60f6db32aec 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsCreateOrUpdateSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsCreateOrUpdateSamples.java @@ -11,7 +11,7 @@ */ public final class PrivateEndpointConnectionsCreateOrUpdateSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoPrivateEndpointConnectionsCreateOrUpdate.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsDeleteSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsDeleteSamples.java index 1addbab01770..1259cc616506 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsDeleteSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsDeleteSamples.java @@ -9,7 +9,7 @@ */ public final class PrivateEndpointConnectionsDeleteSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoPrivateEndpointConnectionsDelete.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsGetSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsGetSamples.java index 345bf78e1e4e..09ef29e069ad 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsGetSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsGetSamples.java @@ -9,7 +9,7 @@ */ public final class PrivateEndpointConnectionsGetSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoPrivateEndpointConnectionsGet.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsListSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsListSamples.java index ae54e1ce0cab..da20cb8b1806 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsListSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsListSamples.java @@ -9,7 +9,7 @@ */ public final class PrivateEndpointConnectionsListSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoPrivateEndpointConnectionsList.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/PrivateLinkResourcesGetSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/PrivateLinkResourcesGetSamples.java index 10c5fa0c78f0..c3215a149050 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/PrivateLinkResourcesGetSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/PrivateLinkResourcesGetSamples.java @@ -9,7 +9,7 @@ */ public final class PrivateLinkResourcesGetSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoPrivateLinkResourcesGet.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/PrivateLinkResourcesListSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/PrivateLinkResourcesListSamples.java index 38e6d92f1407..542a5944d7c7 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/PrivateLinkResourcesListSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/PrivateLinkResourcesListSamples.java @@ -9,7 +9,7 @@ */ public final class PrivateLinkResourcesListSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoPrivateLinkResourcesList.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesCheckNameAvailabilitySamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesCheckNameAvailabilitySamples.java index 8e29d5717bf2..a475e267309c 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesCheckNameAvailabilitySamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesCheckNameAvailabilitySamples.java @@ -11,7 +11,7 @@ */ public final class SandboxCustomImagesCheckNameAvailabilitySamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoSandboxCustomImagesCheckNameAvailability.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesCreateOrUpdateSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesCreateOrUpdateSamples.java index 3b83f59a28a2..b70a683d40b5 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesCreateOrUpdateSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesCreateOrUpdateSamples.java @@ -11,7 +11,7 @@ */ public final class SandboxCustomImagesCreateOrUpdateSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoSandboxCustomImagesCreateOrUpdate.json */ /** @@ -28,4 +28,44 @@ public static void kustoSandboxCustomImagesCreateOrUpdate(com.azure.resourcemana .withRequirementsFileContent("Requests") .create(); } + + /* + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ + * KustoSandboxCustomImagesCreateOrUpdateWithCustomBaseImage.json + */ + /** + * Sample code: KustoSandboxCustomImagesCreateOrUpdateWithCustomBaseImage. + * + * @param manager Entry point to KustoManager. + */ + public static void kustoSandboxCustomImagesCreateOrUpdateWithCustomBaseImage( + com.azure.resourcemanager.kusto.KustoManager manager) { + manager.sandboxCustomImages() + .define("customImage2") + .withExistingCluster("kustorptest", "kustoCluster") + .withLanguage(Language.PYTHON) + .withBaseImageName("customImage1") + .withRequirementsFileContent("Requests") + .create(); + } + + /* + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ + * KustoSandboxCustomImagesCreateOrUpdateWithManagedBaseImage.json + */ + /** + * Sample code: KustoSandboxCustomImagesCreateOrUpdateWithManagedBaseImage. + * + * @param manager Entry point to KustoManager. + */ + public static void kustoSandboxCustomImagesCreateOrUpdateWithManagedBaseImage( + com.azure.resourcemanager.kusto.KustoManager manager) { + manager.sandboxCustomImages() + .define("customImage2") + .withExistingCluster("kustorptest", "kustoCluster") + .withLanguage(Language.PYTHON) + .withBaseImageName("Python3_10_8") + .withRequirementsFileContent("Requests") + .create(); + } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesDeleteSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesDeleteSamples.java index e2448dd00911..51689ae558f8 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesDeleteSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesDeleteSamples.java @@ -9,7 +9,7 @@ */ public final class SandboxCustomImagesDeleteSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoSandboxCustomImageDelete.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesGetSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesGetSamples.java index afec39aabcd6..fac824b0fb51 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesGetSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesGetSamples.java @@ -10,7 +10,7 @@ public final class SandboxCustomImagesGetSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoSandboxCustomImagesGet + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoSandboxCustomImagesGet * .json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesListByClusterSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesListByClusterSamples.java index efd4f9239430..3a53389a4ddf 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesListByClusterSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesListByClusterSamples.java @@ -9,7 +9,7 @@ */ public final class SandboxCustomImagesListByClusterSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoSandboxCustomImagesList.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesUpdateSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesUpdateSamples.java index 1ae28841604c..c21013dc6f3b 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesUpdateSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesUpdateSamples.java @@ -12,7 +12,7 @@ */ public final class SandboxCustomImagesUpdateSamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoSandboxCustomImageUpdate.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ScriptsCheckNameAvailabilitySamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ScriptsCheckNameAvailabilitySamples.java index c7d74a84523b..496de298ccf8 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ScriptsCheckNameAvailabilitySamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ScriptsCheckNameAvailabilitySamples.java @@ -11,7 +11,7 @@ */ public final class ScriptsCheckNameAvailabilitySamples { /* - * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/ + * x-ms-original-file: specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/ * KustoScriptsCheckNameAvailability.json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ScriptsCreateOrUpdateSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ScriptsCreateOrUpdateSamples.java index bfb449968768..a0d82784e486 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ScriptsCreateOrUpdateSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ScriptsCreateOrUpdateSamples.java @@ -4,13 +4,16 @@ package com.azure.resourcemanager.kusto.generated; +import com.azure.resourcemanager.kusto.models.PrincipalPermissionsAction; +import com.azure.resourcemanager.kusto.models.ScriptLevel; + /** * Samples for Scripts CreateOrUpdate. */ public final class ScriptsCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoScriptsCreateOrUpdate. + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoScriptsCreateOrUpdate. * json */ /** @@ -27,6 +30,8 @@ public static void kustoScriptsCreateOrUpdate(com.azure.resourcemanager.kusto.Ku "?sv=2019-02-02&st=2019-04-29T22%3A18%3A26Z&se=2019-04-30T02%3A23%3A26Z&sr=b&sp=rw&sip=168.1.5.60-168.1.5.70&spr=https&sig=********************************") .withForceUpdateTag("2bcf3c21-ffd1-4444-b9dd-e52e00ee53fe") .withContinueOnErrors(true) + .withScriptLevel(ScriptLevel.DATABASE) + .withPrincipalPermissionsAction(PrincipalPermissionsAction.REMOVE_PERMISSION_ON_SCRIPT_COMPLETION) .create(); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ScriptsDeleteSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ScriptsDeleteSamples.java index 084953a29a04..0b17b1352d56 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ScriptsDeleteSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ScriptsDeleteSamples.java @@ -10,7 +10,7 @@ public final class ScriptsDeleteSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoScriptsDelete.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoScriptsDelete.json */ /** * Sample code: KustoScriptsDelete. diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ScriptsGetSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ScriptsGetSamples.java index f18f6f55c913..015252ee1876 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ScriptsGetSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ScriptsGetSamples.java @@ -10,7 +10,7 @@ public final class ScriptsGetSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoScriptsGet.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoScriptsGet.json */ /** * Sample code: KustoScriptsGet. diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ScriptsListByDatabaseSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ScriptsListByDatabaseSamples.java index 883147474b08..657fbfdd5f01 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ScriptsListByDatabaseSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ScriptsListByDatabaseSamples.java @@ -10,7 +10,7 @@ public final class ScriptsListByDatabaseSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoScriptsListByDatabase. + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoScriptsListByDatabase. * json */ /** diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ScriptsUpdateSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ScriptsUpdateSamples.java index 23f17e4acac2..60d7fe6f44ac 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ScriptsUpdateSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/ScriptsUpdateSamples.java @@ -4,7 +4,9 @@ package com.azure.resourcemanager.kusto.generated; +import com.azure.resourcemanager.kusto.models.PrincipalPermissionsAction; import com.azure.resourcemanager.kusto.models.Script; +import com.azure.resourcemanager.kusto.models.ScriptLevel; /** * Samples for Scripts Update. @@ -12,7 +14,7 @@ public final class ScriptsUpdateSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoScriptsUpdate.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoScriptsUpdate.json */ /** * Sample code: KustoScriptsUpdate. @@ -28,6 +30,8 @@ public static void kustoScriptsUpdate(com.azure.resourcemanager.kusto.KustoManag .withScriptUrl("https://mysa.blob.core.windows.net/container/script.txt") .withForceUpdateTag("2bcf3c21-ffd1-4444-b9dd-e52e00ee53fe") .withContinueOnErrors(true) + .withScriptLevel(ScriptLevel.DATABASE) + .withPrincipalPermissionsAction(PrincipalPermissionsAction.REMOVE_PERMISSION_ON_SCRIPT_COMPLETION) .apply(); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/SkusListSamples.java b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/SkusListSamples.java index 34daf8ee1ba7..e55e2d4e2b86 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/SkusListSamples.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/samples/java/com/azure/resourcemanager/kusto/generated/SkusListSamples.java @@ -10,7 +10,7 @@ public final class SkusListSamples { /* * x-ms-original-file: - * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2023-08-15/examples/KustoSkus.json + * specification/azure-kusto/resource-manager/Microsoft.Kusto/stable/2024-04-13/examples/KustoSkus.json */ /** * Sample code: KustoListRegionSkus. diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationInnerTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationInnerTests.java index c431ec5add80..810630f96998 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationInnerTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationInnerTests.java @@ -15,55 +15,55 @@ public final class AttachedDatabaseConfigurationInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { AttachedDatabaseConfigurationInner model = BinaryData.fromString( - "{\"location\":\"ronasxift\",\"properties\":{\"provisioningState\":\"Moving\",\"databaseName\":\"zh\",\"clusterResourceId\":\"tw\",\"attachedDatabaseNames\":[\"ogczhonnxkrlg\",\"yhmossxkkg\",\"h\",\"rghxjb\"],\"defaultPrincipalsModificationKind\":\"None\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"cx\",\"frpdsofbshrns\",\"buswdvzyy\",\"ycnunvjsrtk\"],\"tablesToExclude\":[\"nopqgikyzirtx\",\"yuxzejntpsewgi\",\"ilqu\",\"rydxtqm\"],\"externalTablesToInclude\":[\"xorgg\"],\"externalTablesToExclude\":[\"yaomtb\",\"hhavgrvkffovjz\",\"pjbi\",\"gjmfxumvfcl\"],\"materializedViewsToInclude\":[\"vwxnbkfe\",\"zxscyhwzdgirujb\",\"bomvzzbtdcqv\",\"niyujv\"],\"materializedViewsToExclude\":[\"wdsh\"],\"functionsToInclude\":[\"n\",\"bgye\",\"rymsgaojfmw\",\"cotmr\"],\"functionsToExclude\":[\"rctym\",\"xoftpipiwyczu\",\"xacpqjli\",\"hyus\"]},\"databaseNameOverride\":\"kasdvlm\",\"databaseNamePrefix\":\"dgzxulucvpamrsr\"},\"id\":\"uzvx\",\"name\":\"risjnhnytxifqjz\",\"type\":\"xmrhu\"}") + "{\"location\":\"vjzhpjbib\",\"properties\":{\"provisioningState\":\"Moving\",\"databaseName\":\"xumvfcluyovw\",\"clusterResourceId\":\"nbkfezzxscy\",\"attachedDatabaseNames\":[\"dgirujbzbom\",\"zzbtdcqvpniyujvi\"],\"defaultPrincipalsModificationKind\":\"None\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"hfssnrb\",\"ye\",\"rymsgaojfmw\"],\"tablesToExclude\":[\"tmr\",\"hirctymoxoftpipi\"],\"externalTablesToInclude\":[\"zuhx\",\"cpqjlihhyu\",\"pskasdvlmfwdg\",\"x\"],\"externalTablesToExclude\":[\"cvpa\",\"rsre\"],\"materializedViewsToInclude\":[\"xurisjnhnyt\",\"ifqjz\",\"xmrhu\",\"lw\"],\"materializedViewsToExclude\":[\"sutrgjup\",\"uutpwoqhih\",\"jqgwzp\",\"fqntcyp\"],\"functionsToInclude\":[\"vfoimwksli\"],\"functionsToExclude\":[\"zjxvydfcea\"]},\"databaseNameOverride\":\"lhvygdyftu\",\"databaseNamePrefix\":\"twnawjslbiwkojgc\"},\"id\":\"ztsfmznbaeqp\",\"name\":\"chqnrnrpxehuwry\",\"type\":\"qgaifmviklbydv\"}") .toObject(AttachedDatabaseConfigurationInner.class); - Assertions.assertEquals("ronasxift", model.location()); - Assertions.assertEquals("zh", model.databaseName()); - Assertions.assertEquals("tw", model.clusterResourceId()); + Assertions.assertEquals("vjzhpjbib", model.location()); + Assertions.assertEquals("xumvfcluyovw", model.databaseName()); + Assertions.assertEquals("nbkfezzxscy", model.clusterResourceId()); Assertions.assertEquals(DefaultPrincipalsModificationKind.NONE, model.defaultPrincipalsModificationKind()); - Assertions.assertEquals("cx", model.tableLevelSharingProperties().tablesToInclude().get(0)); - Assertions.assertEquals("nopqgikyzirtx", model.tableLevelSharingProperties().tablesToExclude().get(0)); - Assertions.assertEquals("xorgg", model.tableLevelSharingProperties().externalTablesToInclude().get(0)); - Assertions.assertEquals("yaomtb", model.tableLevelSharingProperties().externalTablesToExclude().get(0)); - Assertions.assertEquals("vwxnbkfe", model.tableLevelSharingProperties().materializedViewsToInclude().get(0)); - Assertions.assertEquals("wdsh", model.tableLevelSharingProperties().materializedViewsToExclude().get(0)); - Assertions.assertEquals("n", model.tableLevelSharingProperties().functionsToInclude().get(0)); - Assertions.assertEquals("rctym", model.tableLevelSharingProperties().functionsToExclude().get(0)); - Assertions.assertEquals("kasdvlm", model.databaseNameOverride()); - Assertions.assertEquals("dgzxulucvpamrsr", model.databaseNamePrefix()); + Assertions.assertEquals("hfssnrb", model.tableLevelSharingProperties().tablesToInclude().get(0)); + Assertions.assertEquals("tmr", model.tableLevelSharingProperties().tablesToExclude().get(0)); + Assertions.assertEquals("zuhx", model.tableLevelSharingProperties().externalTablesToInclude().get(0)); + Assertions.assertEquals("cvpa", model.tableLevelSharingProperties().externalTablesToExclude().get(0)); + Assertions.assertEquals("xurisjnhnyt", model.tableLevelSharingProperties().materializedViewsToInclude().get(0)); + Assertions.assertEquals("sutrgjup", model.tableLevelSharingProperties().materializedViewsToExclude().get(0)); + Assertions.assertEquals("vfoimwksli", model.tableLevelSharingProperties().functionsToInclude().get(0)); + Assertions.assertEquals("zjxvydfcea", model.tableLevelSharingProperties().functionsToExclude().get(0)); + Assertions.assertEquals("lhvygdyftu", model.databaseNameOverride()); + Assertions.assertEquals("twnawjslbiwkojgc", model.databaseNamePrefix()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - AttachedDatabaseConfigurationInner model = new AttachedDatabaseConfigurationInner().withLocation("ronasxift") - .withDatabaseName("zh") - .withClusterResourceId("tw") + AttachedDatabaseConfigurationInner model = new AttachedDatabaseConfigurationInner().withLocation("vjzhpjbib") + .withDatabaseName("xumvfcluyovw") + .withClusterResourceId("nbkfezzxscy") .withDefaultPrincipalsModificationKind(DefaultPrincipalsModificationKind.NONE) - .withTableLevelSharingProperties(new TableLevelSharingProperties() - .withTablesToInclude(Arrays.asList("cx", "frpdsofbshrns", "buswdvzyy", "ycnunvjsrtk")) - .withTablesToExclude(Arrays.asList("nopqgikyzirtx", "yuxzejntpsewgi", "ilqu", "rydxtqm")) - .withExternalTablesToInclude(Arrays.asList("xorgg")) - .withExternalTablesToExclude(Arrays.asList("yaomtb", "hhavgrvkffovjz", "pjbi", "gjmfxumvfcl")) - .withMaterializedViewsToInclude(Arrays.asList("vwxnbkfe", "zxscyhwzdgirujb", "bomvzzbtdcqv", "niyujv")) - .withMaterializedViewsToExclude(Arrays.asList("wdsh")) - .withFunctionsToInclude(Arrays.asList("n", "bgye", "rymsgaojfmw", "cotmr")) - .withFunctionsToExclude(Arrays.asList("rctym", "xoftpipiwyczu", "xacpqjli", "hyus"))) - .withDatabaseNameOverride("kasdvlm") - .withDatabaseNamePrefix("dgzxulucvpamrsr"); + .withTableLevelSharingProperties( + new TableLevelSharingProperties().withTablesToInclude(Arrays.asList("hfssnrb", "ye", "rymsgaojfmw")) + .withTablesToExclude(Arrays.asList("tmr", "hirctymoxoftpipi")) + .withExternalTablesToInclude(Arrays.asList("zuhx", "cpqjlihhyu", "pskasdvlmfwdg", "x")) + .withExternalTablesToExclude(Arrays.asList("cvpa", "rsre")) + .withMaterializedViewsToInclude(Arrays.asList("xurisjnhnyt", "ifqjz", "xmrhu", "lw")) + .withMaterializedViewsToExclude(Arrays.asList("sutrgjup", "uutpwoqhih", "jqgwzp", "fqntcyp")) + .withFunctionsToInclude(Arrays.asList("vfoimwksli")) + .withFunctionsToExclude(Arrays.asList("zjxvydfcea"))) + .withDatabaseNameOverride("lhvygdyftu") + .withDatabaseNamePrefix("twnawjslbiwkojgc"); model = BinaryData.fromObject(model).toObject(AttachedDatabaseConfigurationInner.class); - Assertions.assertEquals("ronasxift", model.location()); - Assertions.assertEquals("zh", model.databaseName()); - Assertions.assertEquals("tw", model.clusterResourceId()); + Assertions.assertEquals("vjzhpjbib", model.location()); + Assertions.assertEquals("xumvfcluyovw", model.databaseName()); + Assertions.assertEquals("nbkfezzxscy", model.clusterResourceId()); Assertions.assertEquals(DefaultPrincipalsModificationKind.NONE, model.defaultPrincipalsModificationKind()); - Assertions.assertEquals("cx", model.tableLevelSharingProperties().tablesToInclude().get(0)); - Assertions.assertEquals("nopqgikyzirtx", model.tableLevelSharingProperties().tablesToExclude().get(0)); - Assertions.assertEquals("xorgg", model.tableLevelSharingProperties().externalTablesToInclude().get(0)); - Assertions.assertEquals("yaomtb", model.tableLevelSharingProperties().externalTablesToExclude().get(0)); - Assertions.assertEquals("vwxnbkfe", model.tableLevelSharingProperties().materializedViewsToInclude().get(0)); - Assertions.assertEquals("wdsh", model.tableLevelSharingProperties().materializedViewsToExclude().get(0)); - Assertions.assertEquals("n", model.tableLevelSharingProperties().functionsToInclude().get(0)); - Assertions.assertEquals("rctym", model.tableLevelSharingProperties().functionsToExclude().get(0)); - Assertions.assertEquals("kasdvlm", model.databaseNameOverride()); - Assertions.assertEquals("dgzxulucvpamrsr", model.databaseNamePrefix()); + Assertions.assertEquals("hfssnrb", model.tableLevelSharingProperties().tablesToInclude().get(0)); + Assertions.assertEquals("tmr", model.tableLevelSharingProperties().tablesToExclude().get(0)); + Assertions.assertEquals("zuhx", model.tableLevelSharingProperties().externalTablesToInclude().get(0)); + Assertions.assertEquals("cvpa", model.tableLevelSharingProperties().externalTablesToExclude().get(0)); + Assertions.assertEquals("xurisjnhnyt", model.tableLevelSharingProperties().materializedViewsToInclude().get(0)); + Assertions.assertEquals("sutrgjup", model.tableLevelSharingProperties().materializedViewsToExclude().get(0)); + Assertions.assertEquals("vfoimwksli", model.tableLevelSharingProperties().functionsToInclude().get(0)); + Assertions.assertEquals("zjxvydfcea", model.tableLevelSharingProperties().functionsToExclude().get(0)); + Assertions.assertEquals("lhvygdyftu", model.databaseNameOverride()); + Assertions.assertEquals("twnawjslbiwkojgc", model.databaseNamePrefix()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationListResultTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationListResultTests.java index c1c9aa7e5b9b..305b0084c052 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationListResultTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationListResultTests.java @@ -16,109 +16,88 @@ public final class AttachedDatabaseConfigurationListResultTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { AttachedDatabaseConfigurationListResult model = BinaryData.fromString( - "{\"value\":[{\"location\":\"sexso\",\"properties\":{\"provisioningState\":\"Deleting\",\"databaseName\":\"uqhhahhxvrh\",\"clusterResourceId\":\"zkw\",\"attachedDatabaseNames\":[\"wws\"],\"defaultPrincipalsModificationKind\":\"None\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"tqs\",\"hqxujxukndxdi\",\"rjguufzdmsyqtf\",\"hwhbotzingamv\"],\"tablesToExclude\":[\"o\"],\"externalTablesToInclude\":[\"zudphqamvdkfw\",\"nwcvtbvkayhmtnv\"],\"externalTablesToExclude\":[\"atkzwpcnpw\",\"cjaesgvvs\",\"cyajguqf\"],\"materializedViewsToInclude\":[\"gzlvdnkfxu\"],\"materializedViewsToExclude\":[\"dwzrmuh\",\"pfcqdp\",\"qxqvpsvuoymgc\",\"elvezrypq\"],\"functionsToInclude\":[\"eokerqwkyhkobopg\"],\"functionsToExclude\":[\"k\"]},\"databaseNameOverride\":\"epbqpcrfkbw\",\"databaseNamePrefix\":\"snjvcdwxlpqekftn\"},\"id\":\"htjsying\",\"name\":\"fq\",\"type\":\"tmtdhtmdvypgik\"},{\"location\":\"szywkbirryu\",\"properties\":{\"provisioningState\":\"Creating\",\"databaseName\":\"kj\",\"clusterResourceId\":\"qrvqq\",\"attachedDatabaseNames\":[\"jinrvgoupmfiibfg\"],\"defaultPrincipalsModificationKind\":\"Union\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"lvrwxkvtkk\",\"llqwjygvjayvblmh\"],\"tablesToExclude\":[\"uhbxvvy\",\"gsopbyrqufegxu\",\"wz\",\"bnhlmc\"],\"externalTablesToInclude\":[\"dn\"],\"externalTablesToExclude\":[\"vgbmhr\",\"xkw\",\"yijejvegrhbpnaix\",\"xccbdreaxhcex\"],\"materializedViewsToInclude\":[\"vqahqkghtpwi\",\"nhyjsv\",\"ycxzbfvoo\",\"vrvmtgjqppyost\"],\"materializedViewsToExclude\":[\"zm\"],\"functionsToInclude\":[\"fipns\",\"kmcwaekrrjreafx\"],\"functionsToExclude\":[\"umh\",\"glikkxwslolb\",\"pvuzlmv\",\"elfk\"]},\"databaseNameOverride\":\"plcrpwjxeznoig\",\"databaseNamePrefix\":\"njwmwkpnbsazejj\"},\"id\":\"qkagfhsxt\",\"name\":\"augzxnfaazpxdtn\",\"type\":\"dm\"},{\"location\":\"j\",\"properties\":{\"provisioningState\":\"Deleting\",\"databaseName\":\"envrkpyouaibrebq\",\"clusterResourceId\":\"aysjkixqtnqttez\",\"attachedDatabaseNames\":[\"ffiakp\",\"pqqmted\"],\"defaultPrincipalsModificationKind\":\"None\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"ihyeozphvw\"],\"tablesToExclude\":[\"qncygupkvi\"],\"externalTablesToInclude\":[\"scw\",\"qupevzh\",\"stotxh\",\"jujbypelmcuvhixb\"],\"externalTablesToExclude\":[\"fw\",\"yl\"],\"materializedViewsToInclude\":[\"o\"],\"materializedViewsToExclude\":[\"tpkiwkkbnujry\",\"vtylbfpncu\",\"doiwi\",\"thtywub\"],\"functionsToInclude\":[\"ihwqknfdntwjchr\",\"goihx\",\"mwctondzjluudfd\"],\"functionsToExclude\":[\"gytsbwtovv\"]},\"databaseNameOverride\":\"seinqfiuf\",\"databaseNamePrefix\":\"knpirgnepttwq\"},\"id\":\"sniffc\",\"name\":\"mqnrojlpijnkr\",\"type\":\"frddhcrati\"}]}") + "{\"value\":[{\"location\":\"svfycxzbfv\",\"properties\":{\"provisioningState\":\"Moving\",\"databaseName\":\"rvmtgjq\",\"clusterResourceId\":\"pyostronzmyhgfi\",\"attachedDatabaseNames\":[\"xkmcwaekrrjre\"],\"defaultPrincipalsModificationKind\":\"Replace\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"gumhjglikkxws\",\"olbq\",\"vuzlm\",\"felfktg\"],\"tablesToExclude\":[\"rpw\"],\"externalTablesToInclude\":[\"znoigbrn\",\"w\"],\"externalTablesToExclude\":[\"pn\"],\"materializedViewsToInclude\":[\"zejjoqk\"],\"materializedViewsToExclude\":[\"hsxttaugzxnf\",\"azpxdtnkdmkqjjl\",\"uenvrkp\"],\"functionsToInclude\":[\"aibrebqaaysjkixq\",\"nqttezl\",\"fffiak\",\"jpqqmted\"],\"functionsToExclude\":[\"mjihyeozphv\"]},\"databaseNameOverride\":\"uyqncygupkvipmd\",\"databaseNamePrefix\":\"wx\"},\"id\":\"upev\",\"name\":\"hfstotxhojujbyp\",\"type\":\"lmcuvhixb\"},{\"location\":\"yfwnylr\",\"properties\":{\"provisioningState\":\"Running\",\"databaseName\":\"sttp\",\"clusterResourceId\":\"iwkkbn\",\"attachedDatabaseNames\":[\"ywvtylbfpnc\",\"rd\",\"iwii\"],\"defaultPrincipalsModificationKind\":\"Replace\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"ubxcbihw\",\"knfd\"],\"tablesToExclude\":[\"jchrdgoihxumw\",\"ton\"],\"externalTablesToInclude\":[\"luudfdlwggytsb\"],\"externalTablesToExclude\":[\"vvt\",\"seinqfiuf\",\"qknp\",\"rgnepttwqmsniffc\"],\"materializedViewsToInclude\":[\"nrojlpijnkr\",\"frddhcrati\",\"zronasxift\",\"zq\"],\"materializedViewsToExclude\":[\"f\",\"wesgogczh\",\"nnxk\"],\"functionsToInclude\":[\"nyhmossxkkgthr\",\"gh\",\"jbdhqxvc\"],\"functionsToExclude\":[\"rpdsof\",\"shrnsvbuswdvz\",\"ybycnunvj\",\"rtkfawnopq\"]},\"databaseNameOverride\":\"kyzirtxdyux\",\"databaseNamePrefix\":\"jntpsewgioilqu\"},\"id\":\"rydxtqm\",\"name\":\"eoxorggufhyao\",\"type\":\"tbghhavgrvkf\"}]}") .toObject(AttachedDatabaseConfigurationListResult.class); - Assertions.assertEquals("sexso", model.value().get(0).location()); - Assertions.assertEquals("uqhhahhxvrh", model.value().get(0).databaseName()); - Assertions.assertEquals("zkw", model.value().get(0).clusterResourceId()); - Assertions.assertEquals(DefaultPrincipalsModificationKind.NONE, + Assertions.assertEquals("svfycxzbfv", model.value().get(0).location()); + Assertions.assertEquals("rvmtgjq", model.value().get(0).databaseName()); + Assertions.assertEquals("pyostronzmyhgfi", model.value().get(0).clusterResourceId()); + Assertions.assertEquals(DefaultPrincipalsModificationKind.REPLACE, model.value().get(0).defaultPrincipalsModificationKind()); - Assertions.assertEquals("tqs", model.value().get(0).tableLevelSharingProperties().tablesToInclude().get(0)); - Assertions.assertEquals("o", model.value().get(0).tableLevelSharingProperties().tablesToExclude().get(0)); - Assertions.assertEquals("zudphqamvdkfw", + Assertions.assertEquals("gumhjglikkxws", + model.value().get(0).tableLevelSharingProperties().tablesToInclude().get(0)); + Assertions.assertEquals("rpw", model.value().get(0).tableLevelSharingProperties().tablesToExclude().get(0)); + Assertions.assertEquals("znoigbrn", model.value().get(0).tableLevelSharingProperties().externalTablesToInclude().get(0)); - Assertions.assertEquals("atkzwpcnpw", + Assertions.assertEquals("pn", model.value().get(0).tableLevelSharingProperties().externalTablesToExclude().get(0)); - Assertions.assertEquals("gzlvdnkfxu", + Assertions.assertEquals("zejjoqk", model.value().get(0).tableLevelSharingProperties().materializedViewsToInclude().get(0)); - Assertions.assertEquals("dwzrmuh", + Assertions.assertEquals("hsxttaugzxnf", model.value().get(0).tableLevelSharingProperties().materializedViewsToExclude().get(0)); - Assertions.assertEquals("eokerqwkyhkobopg", + Assertions.assertEquals("aibrebqaaysjkixq", model.value().get(0).tableLevelSharingProperties().functionsToInclude().get(0)); - Assertions.assertEquals("k", model.value().get(0).tableLevelSharingProperties().functionsToExclude().get(0)); - Assertions.assertEquals("epbqpcrfkbw", model.value().get(0).databaseNameOverride()); - Assertions.assertEquals("snjvcdwxlpqekftn", model.value().get(0).databaseNamePrefix()); + Assertions.assertEquals("mjihyeozphv", + model.value().get(0).tableLevelSharingProperties().functionsToExclude().get(0)); + Assertions.assertEquals("uyqncygupkvipmd", model.value().get(0).databaseNameOverride()); + Assertions.assertEquals("wx", model.value().get(0).databaseNamePrefix()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { AttachedDatabaseConfigurationListResult model - = new AttachedDatabaseConfigurationListResult() - .withValue( - Arrays - .asList( - new AttachedDatabaseConfigurationInner().withLocation("sexso") - .withDatabaseName("uqhhahhxvrh") - .withClusterResourceId("zkw") - .withDefaultPrincipalsModificationKind(DefaultPrincipalsModificationKind.NONE) - .withTableLevelSharingProperties(new TableLevelSharingProperties() - .withTablesToInclude( - Arrays.asList("tqs", "hqxujxukndxdi", "rjguufzdmsyqtf", "hwhbotzingamv")) - .withTablesToExclude(Arrays.asList("o")) - .withExternalTablesToInclude(Arrays.asList("zudphqamvdkfw", "nwcvtbvkayhmtnv")) - .withExternalTablesToExclude(Arrays.asList("atkzwpcnpw", "cjaesgvvs", "cyajguqf")) - .withMaterializedViewsToInclude(Arrays.asList("gzlvdnkfxu")) - .withMaterializedViewsToExclude( - Arrays.asList("dwzrmuh", "pfcqdp", "qxqvpsvuoymgc", "elvezrypq")) - .withFunctionsToInclude(Arrays.asList("eokerqwkyhkobopg")) - .withFunctionsToExclude(Arrays.asList("k"))) - .withDatabaseNameOverride("epbqpcrfkbw") - .withDatabaseNamePrefix("snjvcdwxlpqekftn"), - new AttachedDatabaseConfigurationInner().withLocation("szywkbirryu") - .withDatabaseName("kj") - .withClusterResourceId("qrvqq") - .withDefaultPrincipalsModificationKind(DefaultPrincipalsModificationKind.UNION) - .withTableLevelSharingProperties(new TableLevelSharingProperties() - .withTablesToInclude(Arrays.asList("lvrwxkvtkk", "llqwjygvjayvblmh")) - .withTablesToExclude(Arrays.asList("uhbxvvy", "gsopbyrqufegxu", "wz", "bnhlmc")) - .withExternalTablesToInclude(Arrays.asList("dn")) - .withExternalTablesToExclude( - Arrays.asList("vgbmhr", "xkw", "yijejvegrhbpnaix", "xccbdreaxhcex")) - .withMaterializedViewsToInclude( - Arrays.asList("vqahqkghtpwi", "nhyjsv", "ycxzbfvoo", "vrvmtgjqppyost")) - .withMaterializedViewsToExclude(Arrays.asList("zm")) - .withFunctionsToInclude(Arrays.asList("fipns", "kmcwaekrrjreafx")) - .withFunctionsToExclude(Arrays.asList("umh", "glikkxwslolb", "pvuzlmv", "elfk"))) - .withDatabaseNameOverride("plcrpwjxeznoig") - .withDatabaseNamePrefix("njwmwkpnbsazejj"), - new AttachedDatabaseConfigurationInner().withLocation("j") - .withDatabaseName("envrkpyouaibrebq") - .withClusterResourceId("aysjkixqtnqttez") - .withDefaultPrincipalsModificationKind(DefaultPrincipalsModificationKind.NONE) - .withTableLevelSharingProperties( - new TableLevelSharingProperties().withTablesToInclude(Arrays.asList("ihyeozphvw")) - .withTablesToExclude(Arrays.asList("qncygupkvi")) - .withExternalTablesToInclude( - Arrays.asList("scw", "qupevzh", "stotxh", "jujbypelmcuvhixb")) - .withExternalTablesToExclude(Arrays.asList("fw", "yl")) - .withMaterializedViewsToInclude(Arrays.asList("o")) - .withMaterializedViewsToExclude( - Arrays.asList("tpkiwkkbnujry", "vtylbfpncu", "doiwi", "thtywub")) - .withFunctionsToInclude( - Arrays.asList("ihwqknfdntwjchr", "goihx", "mwctondzjluudfd")) - .withFunctionsToExclude(Arrays.asList("gytsbwtovv"))) - .withDatabaseNameOverride("seinqfiuf") - .withDatabaseNamePrefix("knpirgnepttwq"))); + = new AttachedDatabaseConfigurationListResult().withValue(Arrays.asList( + new AttachedDatabaseConfigurationInner().withLocation("svfycxzbfv") + .withDatabaseName("rvmtgjq") + .withClusterResourceId("pyostronzmyhgfi") + .withDefaultPrincipalsModificationKind(DefaultPrincipalsModificationKind.REPLACE) + .withTableLevelSharingProperties(new TableLevelSharingProperties() + .withTablesToInclude(Arrays.asList("gumhjglikkxws", "olbq", "vuzlm", "felfktg")) + .withTablesToExclude(Arrays.asList("rpw")) + .withExternalTablesToInclude(Arrays.asList("znoigbrn", "w")) + .withExternalTablesToExclude(Arrays.asList("pn")) + .withMaterializedViewsToInclude(Arrays.asList("zejjoqk")) + .withMaterializedViewsToExclude(Arrays.asList("hsxttaugzxnf", "azpxdtnkdmkqjjl", "uenvrkp")) + .withFunctionsToInclude(Arrays.asList("aibrebqaaysjkixq", "nqttezl", "fffiak", "jpqqmted")) + .withFunctionsToExclude(Arrays.asList("mjihyeozphv"))) + .withDatabaseNameOverride("uyqncygupkvipmd") + .withDatabaseNamePrefix("wx"), + new AttachedDatabaseConfigurationInner().withLocation("yfwnylr") + .withDatabaseName("sttp") + .withClusterResourceId("iwkkbn") + .withDefaultPrincipalsModificationKind(DefaultPrincipalsModificationKind.REPLACE) + .withTableLevelSharingProperties(new TableLevelSharingProperties() + .withTablesToInclude(Arrays.asList("ubxcbihw", "knfd")) + .withTablesToExclude(Arrays.asList("jchrdgoihxumw", "ton")) + .withExternalTablesToInclude(Arrays.asList("luudfdlwggytsb")) + .withExternalTablesToExclude(Arrays.asList("vvt", "seinqfiuf", "qknp", "rgnepttwqmsniffc")) + .withMaterializedViewsToInclude(Arrays.asList("nrojlpijnkr", "frddhcrati", "zronasxift", "zq")) + .withMaterializedViewsToExclude(Arrays.asList("f", "wesgogczh", "nnxk")) + .withFunctionsToInclude(Arrays.asList("nyhmossxkkgthr", "gh", "jbdhqxvc")) + .withFunctionsToExclude(Arrays.asList("rpdsof", "shrnsvbuswdvz", "ybycnunvj", "rtkfawnopq"))) + .withDatabaseNameOverride("kyzirtxdyux") + .withDatabaseNamePrefix("jntpsewgioilqu"))); model = BinaryData.fromObject(model).toObject(AttachedDatabaseConfigurationListResult.class); - Assertions.assertEquals("sexso", model.value().get(0).location()); - Assertions.assertEquals("uqhhahhxvrh", model.value().get(0).databaseName()); - Assertions.assertEquals("zkw", model.value().get(0).clusterResourceId()); - Assertions.assertEquals(DefaultPrincipalsModificationKind.NONE, + Assertions.assertEquals("svfycxzbfv", model.value().get(0).location()); + Assertions.assertEquals("rvmtgjq", model.value().get(0).databaseName()); + Assertions.assertEquals("pyostronzmyhgfi", model.value().get(0).clusterResourceId()); + Assertions.assertEquals(DefaultPrincipalsModificationKind.REPLACE, model.value().get(0).defaultPrincipalsModificationKind()); - Assertions.assertEquals("tqs", model.value().get(0).tableLevelSharingProperties().tablesToInclude().get(0)); - Assertions.assertEquals("o", model.value().get(0).tableLevelSharingProperties().tablesToExclude().get(0)); - Assertions.assertEquals("zudphqamvdkfw", + Assertions.assertEquals("gumhjglikkxws", + model.value().get(0).tableLevelSharingProperties().tablesToInclude().get(0)); + Assertions.assertEquals("rpw", model.value().get(0).tableLevelSharingProperties().tablesToExclude().get(0)); + Assertions.assertEquals("znoigbrn", model.value().get(0).tableLevelSharingProperties().externalTablesToInclude().get(0)); - Assertions.assertEquals("atkzwpcnpw", + Assertions.assertEquals("pn", model.value().get(0).tableLevelSharingProperties().externalTablesToExclude().get(0)); - Assertions.assertEquals("gzlvdnkfxu", + Assertions.assertEquals("zejjoqk", model.value().get(0).tableLevelSharingProperties().materializedViewsToInclude().get(0)); - Assertions.assertEquals("dwzrmuh", + Assertions.assertEquals("hsxttaugzxnf", model.value().get(0).tableLevelSharingProperties().materializedViewsToExclude().get(0)); - Assertions.assertEquals("eokerqwkyhkobopg", + Assertions.assertEquals("aibrebqaaysjkixq", model.value().get(0).tableLevelSharingProperties().functionsToInclude().get(0)); - Assertions.assertEquals("k", model.value().get(0).tableLevelSharingProperties().functionsToExclude().get(0)); - Assertions.assertEquals("epbqpcrfkbw", model.value().get(0).databaseNameOverride()); - Assertions.assertEquals("snjvcdwxlpqekftn", model.value().get(0).databaseNamePrefix()); + Assertions.assertEquals("mjihyeozphv", + model.value().get(0).tableLevelSharingProperties().functionsToExclude().get(0)); + Assertions.assertEquals("uyqncygupkvipmd", model.value().get(0).databaseNameOverride()); + Assertions.assertEquals("wx", model.value().get(0).databaseNamePrefix()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationPropertiesTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationPropertiesTests.java index 73eced1aad22..ec23c44649cd 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationPropertiesTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationPropertiesTests.java @@ -15,55 +15,58 @@ public final class AttachedDatabaseConfigurationPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { AttachedDatabaseConfigurationProperties model = BinaryData.fromString( - "{\"provisioningState\":\"Creating\",\"databaseName\":\"pcesutrg\",\"clusterResourceId\":\"upauut\",\"attachedDatabaseNames\":[\"qhih\"],\"defaultPrincipalsModificationKind\":\"None\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"zpnfqntcypsxj\"],\"tablesToExclude\":[\"imwkslircizj\",\"vydfceacvlhvygdy\",\"t\"],\"externalTablesToInclude\":[\"twnawjslbiwkojgc\",\"ztsfmznbaeqp\",\"chqnrnrpxehuwry\"],\"externalTablesToExclude\":[\"aifmvikl\",\"ydv\"],\"materializedViewsToInclude\":[\"ejd\",\"nxcvds\",\"hnjivo\"],\"materializedViewsToExclude\":[\"novqfzge\",\"jdftuljltd\",\"ceamtm\",\"zuo\"],\"functionsToInclude\":[\"wcw\"],\"functionsToExclude\":[\"oknssxmojmsvpkjp\",\"vk\",\"cfzq\"]},\"databaseNameOverride\":\"yxgtczh\",\"databaseNamePrefix\":\"dbsdshm\"}") + "{\"provisioningState\":\"Canceled\",\"databaseName\":\"ejd\",\"clusterResourceId\":\"nxcvds\",\"attachedDatabaseNames\":[\"jivolvtnov\",\"fzg\",\"mjdftu\"],\"defaultPrincipalsModificationKind\":\"Union\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"ucea\",\"tmczuomejwcwwqi\",\"knssxmojm\"],\"tablesToExclude\":[\"kjprvk\"],\"externalTablesToInclude\":[\"zqljyxgtczh\"],\"externalTablesToExclude\":[\"bsdshmkxmaehvbbx\",\"ripltf\"],\"materializedViewsToInclude\":[\"baxk\",\"xywr\"],\"materializedViewsToExclude\":[\"yklyhpluodpvruud\",\"gzibthostgktstv\",\"xeclzedqbcvhzlhp\",\"odqkdlwwqfb\"],\"functionsToInclude\":[\"kxtrq\"],\"functionsToExclude\":[\"mlmbtxhwgfwsrta\",\"coezbrhubskh\",\"dyg\",\"ookk\"]},\"databaseNameOverride\":\"qjbvleorfmlu\",\"databaseNamePrefix\":\"tqzfavyv\"}") .toObject(AttachedDatabaseConfigurationProperties.class); - Assertions.assertEquals("pcesutrg", model.databaseName()); - Assertions.assertEquals("upauut", model.clusterResourceId()); - Assertions.assertEquals(DefaultPrincipalsModificationKind.NONE, model.defaultPrincipalsModificationKind()); - Assertions.assertEquals("zpnfqntcypsxj", model.tableLevelSharingProperties().tablesToInclude().get(0)); - Assertions.assertEquals("imwkslircizj", model.tableLevelSharingProperties().tablesToExclude().get(0)); - Assertions.assertEquals("twnawjslbiwkojgc", - model.tableLevelSharingProperties().externalTablesToInclude().get(0)); - Assertions.assertEquals("aifmvikl", model.tableLevelSharingProperties().externalTablesToExclude().get(0)); - Assertions.assertEquals("ejd", model.tableLevelSharingProperties().materializedViewsToInclude().get(0)); - Assertions.assertEquals("novqfzge", model.tableLevelSharingProperties().materializedViewsToExclude().get(0)); - Assertions.assertEquals("wcw", model.tableLevelSharingProperties().functionsToInclude().get(0)); - Assertions.assertEquals("oknssxmojmsvpkjp", model.tableLevelSharingProperties().functionsToExclude().get(0)); - Assertions.assertEquals("yxgtczh", model.databaseNameOverride()); - Assertions.assertEquals("dbsdshm", model.databaseNamePrefix()); + Assertions.assertEquals("ejd", model.databaseName()); + Assertions.assertEquals("nxcvds", model.clusterResourceId()); + Assertions.assertEquals(DefaultPrincipalsModificationKind.UNION, model.defaultPrincipalsModificationKind()); + Assertions.assertEquals("ucea", model.tableLevelSharingProperties().tablesToInclude().get(0)); + Assertions.assertEquals("kjprvk", model.tableLevelSharingProperties().tablesToExclude().get(0)); + Assertions.assertEquals("zqljyxgtczh", model.tableLevelSharingProperties().externalTablesToInclude().get(0)); + Assertions.assertEquals("bsdshmkxmaehvbbx", + model.tableLevelSharingProperties().externalTablesToExclude().get(0)); + Assertions.assertEquals("baxk", model.tableLevelSharingProperties().materializedViewsToInclude().get(0)); + Assertions.assertEquals("yklyhpluodpvruud", + model.tableLevelSharingProperties().materializedViewsToExclude().get(0)); + Assertions.assertEquals("kxtrq", model.tableLevelSharingProperties().functionsToInclude().get(0)); + Assertions.assertEquals("mlmbtxhwgfwsrta", model.tableLevelSharingProperties().functionsToExclude().get(0)); + Assertions.assertEquals("qjbvleorfmlu", model.databaseNameOverride()); + Assertions.assertEquals("tqzfavyv", model.databaseNamePrefix()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { AttachedDatabaseConfigurationProperties model - = new AttachedDatabaseConfigurationProperties().withDatabaseName("pcesutrg") - .withClusterResourceId("upauut") - .withDefaultPrincipalsModificationKind(DefaultPrincipalsModificationKind.NONE) + = new AttachedDatabaseConfigurationProperties().withDatabaseName("ejd") + .withClusterResourceId("nxcvds") + .withDefaultPrincipalsModificationKind(DefaultPrincipalsModificationKind.UNION) .withTableLevelSharingProperties(new TableLevelSharingProperties() - .withTablesToInclude(Arrays.asList("zpnfqntcypsxj")) - .withTablesToExclude(Arrays.asList("imwkslircizj", "vydfceacvlhvygdy", "t")) - .withExternalTablesToInclude(Arrays.asList("twnawjslbiwkojgc", "ztsfmznbaeqp", "chqnrnrpxehuwry")) - .withExternalTablesToExclude(Arrays.asList("aifmvikl", "ydv")) - .withMaterializedViewsToInclude(Arrays.asList("ejd", "nxcvds", "hnjivo")) - .withMaterializedViewsToExclude(Arrays.asList("novqfzge", "jdftuljltd", "ceamtm", "zuo")) - .withFunctionsToInclude(Arrays.asList("wcw")) - .withFunctionsToExclude(Arrays.asList("oknssxmojmsvpkjp", "vk", "cfzq"))) - .withDatabaseNameOverride("yxgtczh") - .withDatabaseNamePrefix("dbsdshm"); + .withTablesToInclude(Arrays.asList("ucea", "tmczuomejwcwwqi", "knssxmojm")) + .withTablesToExclude(Arrays.asList("kjprvk")) + .withExternalTablesToInclude(Arrays.asList("zqljyxgtczh")) + .withExternalTablesToExclude(Arrays.asList("bsdshmkxmaehvbbx", "ripltf")) + .withMaterializedViewsToInclude(Arrays.asList("baxk", "xywr")) + .withMaterializedViewsToExclude( + Arrays.asList("yklyhpluodpvruud", "gzibthostgktstv", "xeclzedqbcvhzlhp", "odqkdlwwqfb")) + .withFunctionsToInclude(Arrays.asList("kxtrq")) + .withFunctionsToExclude(Arrays.asList("mlmbtxhwgfwsrta", "coezbrhubskh", "dyg", "ookk"))) + .withDatabaseNameOverride("qjbvleorfmlu") + .withDatabaseNamePrefix("tqzfavyv"); model = BinaryData.fromObject(model).toObject(AttachedDatabaseConfigurationProperties.class); - Assertions.assertEquals("pcesutrg", model.databaseName()); - Assertions.assertEquals("upauut", model.clusterResourceId()); - Assertions.assertEquals(DefaultPrincipalsModificationKind.NONE, model.defaultPrincipalsModificationKind()); - Assertions.assertEquals("zpnfqntcypsxj", model.tableLevelSharingProperties().tablesToInclude().get(0)); - Assertions.assertEquals("imwkslircizj", model.tableLevelSharingProperties().tablesToExclude().get(0)); - Assertions.assertEquals("twnawjslbiwkojgc", - model.tableLevelSharingProperties().externalTablesToInclude().get(0)); - Assertions.assertEquals("aifmvikl", model.tableLevelSharingProperties().externalTablesToExclude().get(0)); - Assertions.assertEquals("ejd", model.tableLevelSharingProperties().materializedViewsToInclude().get(0)); - Assertions.assertEquals("novqfzge", model.tableLevelSharingProperties().materializedViewsToExclude().get(0)); - Assertions.assertEquals("wcw", model.tableLevelSharingProperties().functionsToInclude().get(0)); - Assertions.assertEquals("oknssxmojmsvpkjp", model.tableLevelSharingProperties().functionsToExclude().get(0)); - Assertions.assertEquals("yxgtczh", model.databaseNameOverride()); - Assertions.assertEquals("dbsdshm", model.databaseNamePrefix()); + Assertions.assertEquals("ejd", model.databaseName()); + Assertions.assertEquals("nxcvds", model.clusterResourceId()); + Assertions.assertEquals(DefaultPrincipalsModificationKind.UNION, model.defaultPrincipalsModificationKind()); + Assertions.assertEquals("ucea", model.tableLevelSharingProperties().tablesToInclude().get(0)); + Assertions.assertEquals("kjprvk", model.tableLevelSharingProperties().tablesToExclude().get(0)); + Assertions.assertEquals("zqljyxgtczh", model.tableLevelSharingProperties().externalTablesToInclude().get(0)); + Assertions.assertEquals("bsdshmkxmaehvbbx", + model.tableLevelSharingProperties().externalTablesToExclude().get(0)); + Assertions.assertEquals("baxk", model.tableLevelSharingProperties().materializedViewsToInclude().get(0)); + Assertions.assertEquals("yklyhpluodpvruud", + model.tableLevelSharingProperties().materializedViewsToExclude().get(0)); + Assertions.assertEquals("kxtrq", model.tableLevelSharingProperties().functionsToInclude().get(0)); + Assertions.assertEquals("mlmbtxhwgfwsrta", model.tableLevelSharingProperties().functionsToExclude().get(0)); + Assertions.assertEquals("qjbvleorfmlu", model.databaseNameOverride()); + Assertions.assertEquals("tqzfavyv", model.databaseNamePrefix()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsCheckNameAvailabilityWithResponseMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsCheckNameAvailabilityWithResponseMockTests.java index 8c1431ad066c..7a3fbfe435ff 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsCheckNameAvailabilityWithResponseMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsCheckNameAvailabilityWithResponseMockTests.java @@ -23,7 +23,7 @@ public final class AttachedDatabaseConfigurationsCheckNameAvailabilityWithRespon @Test public void testCheckNameAvailabilityWithResponse() throws Exception { String responseStr - = "{\"nameAvailable\":true,\"name\":\"xjbaqehgpdohzjq\",\"message\":\"ucoig\",\"reason\":\"Invalid\"}"; + = "{\"nameAvailable\":true,\"name\":\"qqekewvnqvcdlgu\",\"message\":\"cmfdjwnlax\",\"reason\":\"Invalid\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -33,14 +33,14 @@ public void testCheckNameAvailabilityWithResponse() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); CheckNameResult response = manager.attachedDatabaseConfigurations() - .checkNameAvailabilityWithResponse("ecjxe", "gtuhxuicbu", - new AttachedDatabaseConfigurationsCheckNameRequest().withName("wmrswnjlxuzrh"), + .checkNameAvailabilityWithResponse("nsharujtjiqxfzyj", "ttvwkpqh", + new AttachedDatabaseConfigurationsCheckNameRequest().withName("penuy"), com.azure.core.util.Context.NONE) .getValue(); Assertions.assertEquals(true, response.nameAvailable()); - Assertions.assertEquals("xjbaqehgpdohzjq", response.name()); - Assertions.assertEquals("ucoig", response.message()); + Assertions.assertEquals("qqekewvnqvcdlgu", response.name()); + Assertions.assertEquals("cmfdjwnlax", response.message()); Assertions.assertEquals(Reason.INVALID, response.reason()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsCheckNameRequestTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsCheckNameRequestTests.java index 8c22ba76a687..f894f16faa89 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsCheckNameRequestTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsCheckNameRequestTests.java @@ -11,16 +11,16 @@ public final class AttachedDatabaseConfigurationsCheckNameRequestTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - AttachedDatabaseConfigurationsCheckNameRequest model = BinaryData.fromString("{\"name\":\"wpmqt\"}") + AttachedDatabaseConfigurationsCheckNameRequest model = BinaryData.fromString("{\"name\":\"paxmodfvuefywsb\"}") .toObject(AttachedDatabaseConfigurationsCheckNameRequest.class); - Assertions.assertEquals("wpmqt", model.name()); + Assertions.assertEquals("paxmodfvuefywsb", model.name()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { AttachedDatabaseConfigurationsCheckNameRequest model - = new AttachedDatabaseConfigurationsCheckNameRequest().withName("wpmqt"); + = new AttachedDatabaseConfigurationsCheckNameRequest().withName("paxmodfvuefywsb"); model = BinaryData.fromObject(model).toObject(AttachedDatabaseConfigurationsCheckNameRequest.class); - Assertions.assertEquals("wpmqt", model.name()); + Assertions.assertEquals("paxmodfvuefywsb", model.name()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsCreateOrUpdateMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsCreateOrUpdateMockTests.java index 6542d7de6c37..66e1d5cb8b99 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsCreateOrUpdateMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsCreateOrUpdateMockTests.java @@ -24,7 +24,7 @@ public final class AttachedDatabaseConfigurationsCreateOrUpdateMockTests { @Test public void testCreateOrUpdate() throws Exception { String responseStr - = "{\"location\":\"cjimryvwgcwwpbmz\",\"properties\":{\"provisioningState\":\"Succeeded\",\"databaseName\":\"ydsx\",\"clusterResourceId\":\"efoh\",\"attachedDatabaseNames\":[\"vopwndyqleallk\",\"mtkhlowkxxpvbr\",\"fjmzsyzfho\"],\"defaultPrincipalsModificationKind\":\"Replace\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"cyychunsjlp\"],\"tablesToExclude\":[\"wszhvvuicphvtrr\",\"hwrbfdpyflubh\",\"jgl\"],\"externalTablesToInclude\":[\"uyzlw\",\"hmem\",\"ooclutnp\",\"memczjkmmyk\"],\"externalTablesToExclude\":[\"xsglh\",\"rr\"],\"materializedViewsToInclude\":[\"jylmbkzudnigr\",\"ihotjewlpxuzzjg\",\"refqy\"],\"materializedViewsToExclude\":[\"toihiqakydi\",\"fb\"],\"functionsToInclude\":[\"pzdqtvhcspod\",\"qaxsipietgbebjf\",\"lbmoichd\"],\"functionsToExclude\":[\"fpubntnbatz\",\"iqsowsaaelc\",\"ttcjuhplrvkmjc\"]},\"databaseNameOverride\":\"jvlgfggcvkyyliz\",\"databaseNamePrefix\":\"bjpsfxsfuztlvtm\"},\"id\":\"agb\",\"name\":\"idqlvhu\",\"type\":\"oveofizrvjfnmj\"}"; + = "{\"location\":\"gcvkyyli\",\"properties\":{\"provisioningState\":\"Succeeded\",\"databaseName\":\"jpsfxsfu\",\"clusterResourceId\":\"tl\",\"attachedDatabaseNames\":[\"vagbwidqlvhukove\",\"fizr\",\"jfnmjmvlwyz\",\"iblkujr\"],\"defaultPrincipalsModificationKind\":\"None\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"uidjpuuyjucej\"],\"tablesToExclude\":[\"oeo\",\"vtzejetjklnti\",\"yjuzkdb\"],\"externalTablesToInclude\":[\"lxrzvhqjwtr\"],\"externalTablesToExclude\":[\"vgzpcrrkolawj\"],\"materializedViewsToInclude\":[\"mwrokcdxfzzzwyja\"],\"materializedViewsToExclude\":[\"lhguyn\",\"chl\",\"mltx\"],\"functionsToInclude\":[\"mozusgzvlnsnnjz\"],\"functionsToExclude\":[\"folpymwamxqzra\",\"p\",\"dphtv\",\"ulajvlejchc\"]},\"databaseNameOverride\":\"lzk\",\"databaseNamePrefix\":\"zlanrupdwvnph\"},\"id\":\"nzqtpjhmqrhvt\",\"name\":\"laiwdcxsmlzzh\",\"type\":\"dtxetlgydlh\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -34,41 +34,40 @@ public void testCreateOrUpdate() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); AttachedDatabaseConfiguration response = manager.attachedDatabaseConfigurations() - .define("zqcyknap") - .withExistingCluster("d", "dtfgxqbawpcbb") - .withRegion("fyuicdh") - .withDatabaseName("bwwg") - .withClusterResourceId("d") + .define("ucsofldpuviyf") + .withExistingCluster("eaclgschorimk", "srrm") + .withRegion("abeolhbhlvbm") + .withDatabaseName("bsxtkcudfbsfarfs") + .withClusterResourceId("owlkjxnqpv") .withDefaultPrincipalsModificationKind(DefaultPrincipalsModificationKind.NONE) - .withTableLevelSharingProperties( - new TableLevelSharingProperties().withTablesToInclude(Arrays.asList("u", "apckccrrvw")) - .withTablesToExclude(Arrays.asList("xoy", "ukphaimmoiroq")) - .withExternalTablesToInclude(Arrays.asList("hbragapyyr", "fsv")) - .withExternalTablesToExclude(Arrays.asList("vbopfppdbwnu", "gahxkumasjcaa")) - .withMaterializedViewsToInclude(Arrays.asList("mmcpug", "ehqepvufhbzehe", "hoqhnl", "qnbldxe")) - .withMaterializedViewsToExclude(Arrays.asList("gschorimkrsrr")) - .withFunctionsToInclude(Arrays.asList("cso", "ldpuviy", "caab", "olhbhlvb")) - .withFunctionsToExclude(Arrays.asList("qi", "s", "tkcudfbsfarfsiow"))) - .withDatabaseNameOverride("jxnqp") - .withDatabaseNamePrefix("gf") + .withTableLevelSharingProperties(new TableLevelSharingProperties() + .withTablesToInclude(Arrays.asList("wefohecbvo", "wndyqleallk", "mtkhlowkxxpvbr", "fjmzsyzfho")) + .withTablesToExclude(Arrays.asList("ikcyyc")) + .withExternalTablesToInclude(Arrays.asList("sjlpjrtwszhv", "uic", "hvtrrmhwrbfdpyf")) + .withExternalTablesToExclude(Arrays.asList("hvj", "lrocuyzlwh")) + .withMaterializedViewsToInclude(Arrays.asList("mhoocl", "tnpqmemczjk", "mykyujxsglhs")) + .withMaterializedViewsToExclude(Arrays.asList("yejylmbkzudnigrf")) + .withFunctionsToInclude(Arrays.asList("tjewlpxuzzj", "nrefqyh", "otoihiqa", "ydiw")) + .withFunctionsToExclude(Arrays.asList("kwpzdqtvh", "spodaqax", "ipietgbe", "jfulbmoic"))) + .withDatabaseNameOverride("lpnfpubntnb") + .withDatabaseNamePrefix("zviqsowsaae") .create(); - Assertions.assertEquals("cjimryvwgcwwpbmz", response.location()); - Assertions.assertEquals("ydsx", response.databaseName()); - Assertions.assertEquals("efoh", response.clusterResourceId()); - Assertions.assertEquals(DefaultPrincipalsModificationKind.REPLACE, - response.defaultPrincipalsModificationKind()); - Assertions.assertEquals("cyychunsjlp", response.tableLevelSharingProperties().tablesToInclude().get(0)); - Assertions.assertEquals("wszhvvuicphvtrr", response.tableLevelSharingProperties().tablesToExclude().get(0)); - Assertions.assertEquals("uyzlw", response.tableLevelSharingProperties().externalTablesToInclude().get(0)); - Assertions.assertEquals("xsglh", response.tableLevelSharingProperties().externalTablesToExclude().get(0)); - Assertions.assertEquals("jylmbkzudnigr", + Assertions.assertEquals("gcvkyyli", response.location()); + Assertions.assertEquals("jpsfxsfu", response.databaseName()); + Assertions.assertEquals("tl", response.clusterResourceId()); + Assertions.assertEquals(DefaultPrincipalsModificationKind.NONE, response.defaultPrincipalsModificationKind()); + Assertions.assertEquals("uidjpuuyjucej", response.tableLevelSharingProperties().tablesToInclude().get(0)); + Assertions.assertEquals("oeo", response.tableLevelSharingProperties().tablesToExclude().get(0)); + Assertions.assertEquals("lxrzvhqjwtr", response.tableLevelSharingProperties().externalTablesToInclude().get(0)); + Assertions.assertEquals("vgzpcrrkolawj", + response.tableLevelSharingProperties().externalTablesToExclude().get(0)); + Assertions.assertEquals("mwrokcdxfzzzwyja", response.tableLevelSharingProperties().materializedViewsToInclude().get(0)); - Assertions.assertEquals("toihiqakydi", - response.tableLevelSharingProperties().materializedViewsToExclude().get(0)); - Assertions.assertEquals("pzdqtvhcspod", response.tableLevelSharingProperties().functionsToInclude().get(0)); - Assertions.assertEquals("fpubntnbatz", response.tableLevelSharingProperties().functionsToExclude().get(0)); - Assertions.assertEquals("jvlgfggcvkyyliz", response.databaseNameOverride()); - Assertions.assertEquals("bjpsfxsfuztlvtm", response.databaseNamePrefix()); + Assertions.assertEquals("lhguyn", response.tableLevelSharingProperties().materializedViewsToExclude().get(0)); + Assertions.assertEquals("mozusgzvlnsnnjz", response.tableLevelSharingProperties().functionsToInclude().get(0)); + Assertions.assertEquals("folpymwamxqzra", response.tableLevelSharingProperties().functionsToExclude().get(0)); + Assertions.assertEquals("lzk", response.databaseNameOverride()); + Assertions.assertEquals("zlanrupdwvnph", response.databaseNamePrefix()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsDeleteMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsDeleteMockTests.java index f2cb59bd7d88..a94e9be346e5 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsDeleteMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsDeleteMockTests.java @@ -27,7 +27,8 @@ public void testDelete() throws Exception { .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), new AzureProfile("", "", AzureEnvironment.AZURE)); - manager.attachedDatabaseConfigurations().delete("lmv", "vfxzopjh", "zxlioh", com.azure.core.util.Context.NONE); + manager.attachedDatabaseConfigurations() + .delete("jcaacfdmmcpugm", "hqepvufhbzehewh", "qhnlbqnbld", com.azure.core.util.Context.NONE); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsGetWithResponseMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsGetWithResponseMockTests.java index 02ab723fbbfe..d8341c7c7fe8 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsGetWithResponseMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsGetWithResponseMockTests.java @@ -22,7 +22,7 @@ public final class AttachedDatabaseConfigurationsGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"location\":\"zmkw\",\"properties\":{\"provisioningState\":\"Canceled\",\"databaseName\":\"oxaxm\",\"clusterResourceId\":\"e\",\"attachedDatabaseNames\":[\"h\",\"jnhgwydyyn\"],\"defaultPrincipalsModificationKind\":\"None\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"gbv\",\"ta\"],\"tablesToExclude\":[\"fdlpukhpyr\"],\"externalTablesToInclude\":[\"zjcpeogk\",\"nmg\"],\"externalTablesToExclude\":[\"uxddbhfh\",\"fpazjzoywjxhpd\",\"lontacnpq\",\"tehtuevrhrljyoog\"],\"materializedViewsToInclude\":[\"nsduugwbsre\",\"rfqkfuar\",\"nlvhhtklnvnafvv\",\"yfedevjbo\"],\"materializedViewsToExclude\":[\"qxypokkhminq\",\"ymc\",\"ngnbdxxew\",\"ninvudbchaqdt\"],\"functionsToInclude\":[\"crqctmxxdtddmflh\"],\"functionsToExclude\":[\"xzvtzna\"]},\"databaseNameOverride\":\"bannovvoxczytp\",\"databaseNamePrefix\":\"nwvroevytlyokrr\"},\"id\":\"o\",\"name\":\"uxvnsasbcrymodi\",\"type\":\"rxklobdxnazpmk\"}"; + = "{\"location\":\"dxxewuninv\",\"properties\":{\"provisioningState\":\"Canceled\",\"databaseName\":\"h\",\"clusterResourceId\":\"qdtvqecrqctmxx\",\"attachedDatabaseNames\":[\"dmflhuytx\"],\"defaultPrincipalsModificationKind\":\"Replace\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"apxbannovvoxczy\",\"prwnwvroevytlyo\",\"rrrouuxvnsa\"],\"tablesToExclude\":[\"rymo\",\"izrxklob\",\"xnazpmkml\",\"vevfxz\"],\"externalTablesToInclude\":[\"hbzxli\",\"hrdd\",\"tfgxqbawpcb\",\"nzqcy\"],\"externalTablesToExclude\":[\"p\",\"ofyuicd\",\"zb\"],\"materializedViewsToInclude\":[\"wwgbdv\"],\"materializedViewsToExclude\":[\"dmhm\",\"ffplfmuvapckcc\"],\"functionsToInclude\":[\"weyoxoy\"],\"functionsToExclude\":[\"phaimmoi\"]},\"databaseNameOverride\":\"qboshbra\",\"databaseNamePrefix\":\"pyyrmfs\"},\"id\":\"bpav\",\"name\":\"opfppdbwnupgah\",\"type\":\"kuma\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -32,24 +32,23 @@ public void testGetWithResponse() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); AttachedDatabaseConfiguration response = manager.attachedDatabaseConfigurations() - .getWithResponse("nlgmtrwahzjmu", "ftbyrplro", "kpigqfusu", com.azure.core.util.Context.NONE) + .getWithResponse("lcqxypokk", "minqcym", "zng", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("zmkw", response.location()); - Assertions.assertEquals("oxaxm", response.databaseName()); - Assertions.assertEquals("e", response.clusterResourceId()); - Assertions.assertEquals(DefaultPrincipalsModificationKind.NONE, response.defaultPrincipalsModificationKind()); - Assertions.assertEquals("gbv", response.tableLevelSharingProperties().tablesToInclude().get(0)); - Assertions.assertEquals("fdlpukhpyr", response.tableLevelSharingProperties().tablesToExclude().get(0)); - Assertions.assertEquals("zjcpeogk", response.tableLevelSharingProperties().externalTablesToInclude().get(0)); - Assertions.assertEquals("uxddbhfh", response.tableLevelSharingProperties().externalTablesToExclude().get(0)); - Assertions.assertEquals("nsduugwbsre", - response.tableLevelSharingProperties().materializedViewsToInclude().get(0)); - Assertions.assertEquals("qxypokkhminq", - response.tableLevelSharingProperties().materializedViewsToExclude().get(0)); - Assertions.assertEquals("crqctmxxdtddmflh", response.tableLevelSharingProperties().functionsToInclude().get(0)); - Assertions.assertEquals("xzvtzna", response.tableLevelSharingProperties().functionsToExclude().get(0)); - Assertions.assertEquals("bannovvoxczytp", response.databaseNameOverride()); - Assertions.assertEquals("nwvroevytlyokrr", response.databaseNamePrefix()); + Assertions.assertEquals("dxxewuninv", response.location()); + Assertions.assertEquals("h", response.databaseName()); + Assertions.assertEquals("qdtvqecrqctmxx", response.clusterResourceId()); + Assertions.assertEquals(DefaultPrincipalsModificationKind.REPLACE, + response.defaultPrincipalsModificationKind()); + Assertions.assertEquals("apxbannovvoxczy", response.tableLevelSharingProperties().tablesToInclude().get(0)); + Assertions.assertEquals("rymo", response.tableLevelSharingProperties().tablesToExclude().get(0)); + Assertions.assertEquals("hbzxli", response.tableLevelSharingProperties().externalTablesToInclude().get(0)); + Assertions.assertEquals("p", response.tableLevelSharingProperties().externalTablesToExclude().get(0)); + Assertions.assertEquals("wwgbdv", response.tableLevelSharingProperties().materializedViewsToInclude().get(0)); + Assertions.assertEquals("dmhm", response.tableLevelSharingProperties().materializedViewsToExclude().get(0)); + Assertions.assertEquals("weyoxoy", response.tableLevelSharingProperties().functionsToInclude().get(0)); + Assertions.assertEquals("phaimmoi", response.tableLevelSharingProperties().functionsToExclude().get(0)); + Assertions.assertEquals("qboshbra", response.databaseNameOverride()); + Assertions.assertEquals("pyyrmfs", response.databaseNamePrefix()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsListByClusterMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsListByClusterMockTests.java index de142278346b..92c6d1785110 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsListByClusterMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AttachedDatabaseConfigurationsListByClusterMockTests.java @@ -23,7 +23,7 @@ public final class AttachedDatabaseConfigurationsListByClusterMockTests { @Test public void testListByCluster() throws Exception { String responseStr - = "{\"value\":[{\"location\":\"bjb\",\"properties\":{\"provisioningState\":\"Canceled\",\"databaseName\":\"gtdysnaqu\",\"clusterResourceId\":\"lqbctqhamzjrw\",\"attachedDatabaseNames\":[\"zeqyjleziun\",\"xdfzantkw\",\"eg\",\"amlbnseqacjjvpil\"],\"defaultPrincipalsModificationKind\":\"None\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"jagmdi\",\"gueiookjbsahrtdt\",\"delqacslmoto\",\"bnfxofvc\"],\"tablesToExclude\":[\"dirazf\",\"xejw\"],\"externalTablesToInclude\":[\"dujtmvcope\",\"c\",\"jurbuhhlkyqltqsr\",\"gtuwkff\"],\"externalTablesToExclude\":[\"tsysi\",\"fvcl\",\"lxnfuijtkbusqogs\",\"ikayiansharuj\"],\"materializedViewsToInclude\":[\"qxfzyjqttvwk\"],\"materializedViewsToExclude\":[\"j\",\"enuygbq\",\"qqekewvnqvcdlgu\"],\"functionsToInclude\":[\"mfdjwn\",\"axpunjqikczvv\",\"tacgxmfc\"],\"functionsToExclude\":[\"rxhtvso\"]},\"databaseNameOverride\":\"lwntsjgqrs\",\"databaseNamePrefix\":\"p\"},\"id\":\"uuuybnchrsziz\",\"name\":\"yuel\",\"type\":\"etndnbfqyggagf\"}]}"; + = "{\"value\":[{\"location\":\"gx\",\"properties\":{\"provisioningState\":\"Running\",\"databaseName\":\"serxht\",\"clusterResourceId\":\"soxhlwntsjgqr\",\"attachedDatabaseNames\":[\"p\"],\"defaultPrincipalsModificationKind\":\"Union\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"bnchrsziz\"],\"tablesToExclude\":[\"elyetndnbf\",\"yggagflnlgmt\",\"wahzjmucftbyr\"],\"externalTablesToInclude\":[\"ohkpigqfu\",\"u\",\"kzmkwklsnoxaxmqe\"],\"externalTablesToExclude\":[\"h\",\"jnhgwydyyn\"],\"materializedViewsToInclude\":[\"khgb\"],\"materializedViewsToExclude\":[\"anarfdlpukhpyrne\"],\"functionsToInclude\":[\"cpeogkhnmgbrou\",\"ddbhf\",\"pfpazjzoywjxhpdu\"],\"functionsToExclude\":[\"tacnpqwtehtuev\",\"hrljy\"]},\"databaseNameOverride\":\"gwxhnsduugwbsreu\",\"databaseNamePrefix\":\"q\"},\"id\":\"fuarenlvhht\",\"name\":\"lnvnafvvkyfedev\",\"type\":\"bo\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -32,31 +32,31 @@ public void testListByCluster() throws Exception { .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), new AzureProfile("", "", AzureEnvironment.AZURE)); - PagedIterable response = manager.attachedDatabaseConfigurations() - .listByCluster("ncnwfepbnwgf", "xjg", com.azure.core.util.Context.NONE); + PagedIterable response + = manager.attachedDatabaseConfigurations().listByCluster("jqi", "czvvit", com.azure.core.util.Context.NONE); - Assertions.assertEquals("bjb", response.iterator().next().location()); - Assertions.assertEquals("gtdysnaqu", response.iterator().next().databaseName()); - Assertions.assertEquals("lqbctqhamzjrw", response.iterator().next().clusterResourceId()); - Assertions.assertEquals(DefaultPrincipalsModificationKind.NONE, + Assertions.assertEquals("gx", response.iterator().next().location()); + Assertions.assertEquals("serxht", response.iterator().next().databaseName()); + Assertions.assertEquals("soxhlwntsjgqr", response.iterator().next().clusterResourceId()); + Assertions.assertEquals(DefaultPrincipalsModificationKind.UNION, response.iterator().next().defaultPrincipalsModificationKind()); - Assertions.assertEquals("jagmdi", + Assertions.assertEquals("bnchrsziz", response.iterator().next().tableLevelSharingProperties().tablesToInclude().get(0)); - Assertions.assertEquals("dirazf", + Assertions.assertEquals("elyetndnbf", response.iterator().next().tableLevelSharingProperties().tablesToExclude().get(0)); - Assertions.assertEquals("dujtmvcope", + Assertions.assertEquals("ohkpigqfu", response.iterator().next().tableLevelSharingProperties().externalTablesToInclude().get(0)); - Assertions.assertEquals("tsysi", + Assertions.assertEquals("h", response.iterator().next().tableLevelSharingProperties().externalTablesToExclude().get(0)); - Assertions.assertEquals("qxfzyjqttvwk", + Assertions.assertEquals("khgb", response.iterator().next().tableLevelSharingProperties().materializedViewsToInclude().get(0)); - Assertions.assertEquals("j", + Assertions.assertEquals("anarfdlpukhpyrne", response.iterator().next().tableLevelSharingProperties().materializedViewsToExclude().get(0)); - Assertions.assertEquals("mfdjwn", + Assertions.assertEquals("cpeogkhnmgbrou", response.iterator().next().tableLevelSharingProperties().functionsToInclude().get(0)); - Assertions.assertEquals("rxhtvso", + Assertions.assertEquals("tacnpqwtehtuev", response.iterator().next().tableLevelSharingProperties().functionsToExclude().get(0)); - Assertions.assertEquals("lwntsjgqrs", response.iterator().next().databaseNameOverride()); - Assertions.assertEquals("p", response.iterator().next().databaseNamePrefix()); + Assertions.assertEquals("gwxhnsduugwbsreu", response.iterator().next().databaseNameOverride()); + Assertions.assertEquals("q", response.iterator().next().databaseNamePrefix()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AzureCapacityTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AzureCapacityTests.java index 11b63e47417e..233aa6afc14d 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AzureCapacityTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AzureCapacityTests.java @@ -13,25 +13,24 @@ public final class AzureCapacityTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { AzureCapacity model = BinaryData - .fromString( - "{\"scaleType\":\"manual\",\"minimum\":1953452133,\"maximum\":709486053,\"default\":1687454547}") + .fromString("{\"scaleType\":\"none\",\"minimum\":10985850,\"maximum\":107340083,\"default\":1397433575}") .toObject(AzureCapacity.class); - Assertions.assertEquals(AzureScaleType.MANUAL, model.scaleType()); - Assertions.assertEquals(1953452133, model.minimum()); - Assertions.assertEquals(709486053, model.maximum()); - Assertions.assertEquals(1687454547, model.defaultProperty()); + Assertions.assertEquals(AzureScaleType.NONE, model.scaleType()); + Assertions.assertEquals(10985850, model.minimum()); + Assertions.assertEquals(107340083, model.maximum()); + Assertions.assertEquals(1397433575, model.defaultProperty()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - AzureCapacity model = new AzureCapacity().withScaleType(AzureScaleType.MANUAL) - .withMinimum(1953452133) - .withMaximum(709486053) - .withDefaultProperty(1687454547); + AzureCapacity model = new AzureCapacity().withScaleType(AzureScaleType.NONE) + .withMinimum(10985850) + .withMaximum(107340083) + .withDefaultProperty(1397433575); model = BinaryData.fromObject(model).toObject(AzureCapacity.class); - Assertions.assertEquals(AzureScaleType.MANUAL, model.scaleType()); - Assertions.assertEquals(1953452133, model.minimum()); - Assertions.assertEquals(709486053, model.maximum()); - Assertions.assertEquals(1687454547, model.defaultProperty()); + Assertions.assertEquals(AzureScaleType.NONE, model.scaleType()); + Assertions.assertEquals(10985850, model.minimum()); + Assertions.assertEquals(107340083, model.maximum()); + Assertions.assertEquals(1397433575, model.defaultProperty()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AzureResourceSkuInnerTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AzureResourceSkuInnerTests.java index 0aa722afe3b2..fb7d49ed9993 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AzureResourceSkuInnerTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/AzureResourceSkuInnerTests.java @@ -17,36 +17,36 @@ public final class AzureResourceSkuInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { AzureResourceSkuInner model = BinaryData.fromString( - "{\"resourceType\":\"ndslgnayqigynduh\",\"sku\":{\"name\":\"Standard_EC8as_v5+1TB_PS\",\"capacity\":1238517729,\"tier\":\"Standard\"},\"capacity\":{\"scaleType\":\"manual\",\"minimum\":918393543,\"maximum\":1117250592,\"default\":1615397265}}") + "{\"resourceType\":\"xvy\",\"sku\":{\"name\":\"Standard_D13_v2\",\"capacity\":1838860649,\"tier\":\"Basic\"},\"capacity\":{\"scaleType\":\"none\",\"minimum\":1364703724,\"maximum\":2107852573,\"default\":1321769346}}") .toObject(AzureResourceSkuInner.class); - Assertions.assertEquals("ndslgnayqigynduh", model.resourceType()); - Assertions.assertEquals(AzureSkuName.STANDARD_EC8AS_V5_1TB_PS, model.sku().name()); - Assertions.assertEquals(1238517729, model.sku().capacity()); - Assertions.assertEquals(AzureSkuTier.STANDARD, model.sku().tier()); - Assertions.assertEquals(AzureScaleType.MANUAL, model.capacity().scaleType()); - Assertions.assertEquals(918393543, model.capacity().minimum()); - Assertions.assertEquals(1117250592, model.capacity().maximum()); - Assertions.assertEquals(1615397265, model.capacity().defaultProperty()); + Assertions.assertEquals("xvy", model.resourceType()); + Assertions.assertEquals(AzureSkuName.STANDARD_D13_V2, model.sku().name()); + Assertions.assertEquals(1838860649, model.sku().capacity()); + Assertions.assertEquals(AzureSkuTier.BASIC, model.sku().tier()); + Assertions.assertEquals(AzureScaleType.NONE, model.capacity().scaleType()); + Assertions.assertEquals(1364703724, model.capacity().minimum()); + Assertions.assertEquals(2107852573, model.capacity().maximum()); + Assertions.assertEquals(1321769346, model.capacity().defaultProperty()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - AzureResourceSkuInner model = new AzureResourceSkuInner().withResourceType("ndslgnayqigynduh") - .withSku(new AzureSku().withName(AzureSkuName.STANDARD_EC8AS_V5_1TB_PS) - .withCapacity(1238517729) - .withTier(AzureSkuTier.STANDARD)) - .withCapacity(new AzureCapacity().withScaleType(AzureScaleType.MANUAL) - .withMinimum(918393543) - .withMaximum(1117250592) - .withDefaultProperty(1615397265)); + AzureResourceSkuInner model = new AzureResourceSkuInner().withResourceType("xvy") + .withSku(new AzureSku().withName(AzureSkuName.STANDARD_D13_V2) + .withCapacity(1838860649) + .withTier(AzureSkuTier.BASIC)) + .withCapacity(new AzureCapacity().withScaleType(AzureScaleType.NONE) + .withMinimum(1364703724) + .withMaximum(2107852573) + .withDefaultProperty(1321769346)); model = BinaryData.fromObject(model).toObject(AzureResourceSkuInner.class); - Assertions.assertEquals("ndslgnayqigynduh", model.resourceType()); - Assertions.assertEquals(AzureSkuName.STANDARD_EC8AS_V5_1TB_PS, model.sku().name()); - Assertions.assertEquals(1238517729, model.sku().capacity()); - Assertions.assertEquals(AzureSkuTier.STANDARD, model.sku().tier()); - Assertions.assertEquals(AzureScaleType.MANUAL, model.capacity().scaleType()); - Assertions.assertEquals(918393543, model.capacity().minimum()); - Assertions.assertEquals(1117250592, model.capacity().maximum()); - Assertions.assertEquals(1615397265, model.capacity().defaultProperty()); + Assertions.assertEquals("xvy", model.resourceType()); + Assertions.assertEquals(AzureSkuName.STANDARD_D13_V2, model.sku().name()); + Assertions.assertEquals(1838860649, model.sku().capacity()); + Assertions.assertEquals(AzureSkuTier.BASIC, model.sku().tier()); + Assertions.assertEquals(AzureScaleType.NONE, model.capacity().scaleType()); + Assertions.assertEquals(1364703724, model.capacity().minimum()); + Assertions.assertEquals(2107852573, model.capacity().maximum()); + Assertions.assertEquals(1321769346, model.capacity().defaultProperty()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/CalloutPoliciesListTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/CalloutPoliciesListTests.java new file mode 100644 index 000000000000..43e9489f3bdb --- /dev/null +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/CalloutPoliciesListTests.java @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.kusto.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.kusto.fluent.models.CalloutPolicyInner; +import com.azure.resourcemanager.kusto.models.CalloutPoliciesList; +import com.azure.resourcemanager.kusto.models.CalloutType; +import com.azure.resourcemanager.kusto.models.OutboundAccess; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class CalloutPoliciesListTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + CalloutPoliciesList model = BinaryData.fromString( + "{\"value\":[{\"calloutUriRegex\":\"ybvpay\",\"calloutType\":\"sandbox_artifacts\",\"outboundAccess\":\"Deny\",\"calloutId\":\"px\"},{\"calloutUriRegex\":\"jplmagstcy\",\"calloutType\":\"cosmosdb\",\"outboundAccess\":\"Allow\",\"calloutId\":\"rkdbdgiogsjkmnwq\"}],\"nextLink\":\"obaiyhddviaceg\"}") + .toObject(CalloutPoliciesList.class); + Assertions.assertEquals("ybvpay", model.value().get(0).calloutUriRegex()); + Assertions.assertEquals(CalloutType.SANDBOX_ARTIFACTS, model.value().get(0).calloutType()); + Assertions.assertEquals(OutboundAccess.DENY, model.value().get(0).outboundAccess()); + Assertions.assertEquals("obaiyhddviaceg", model.nextLink()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + CalloutPoliciesList model = new CalloutPoliciesList().withValue(Arrays.asList( + new CalloutPolicyInner().withCalloutUriRegex("ybvpay") + .withCalloutType(CalloutType.SANDBOX_ARTIFACTS) + .withOutboundAccess(OutboundAccess.DENY), + new CalloutPolicyInner().withCalloutUriRegex("jplmagstcy") + .withCalloutType(CalloutType.COSMOSDB) + .withOutboundAccess(OutboundAccess.ALLOW))) + .withNextLink("obaiyhddviaceg"); + model = BinaryData.fromObject(model).toObject(CalloutPoliciesList.class); + Assertions.assertEquals("ybvpay", model.value().get(0).calloutUriRegex()); + Assertions.assertEquals(CalloutType.SANDBOX_ARTIFACTS, model.value().get(0).calloutType()); + Assertions.assertEquals(OutboundAccess.DENY, model.value().get(0).outboundAccess()); + Assertions.assertEquals("obaiyhddviaceg", model.nextLink()); + } +} diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/CalloutPolicyInnerTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/CalloutPolicyInnerTests.java new file mode 100644 index 000000000000..aa7eaed504e7 --- /dev/null +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/CalloutPolicyInnerTests.java @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.kusto.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.kusto.fluent.models.CalloutPolicyInner; +import com.azure.resourcemanager.kusto.models.CalloutType; +import com.azure.resourcemanager.kusto.models.OutboundAccess; +import org.junit.jupiter.api.Assertions; + +public final class CalloutPolicyInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + CalloutPolicyInner model = BinaryData.fromString( + "{\"calloutUriRegex\":\"nmayhuybb\",\"calloutType\":\"postgresql\",\"outboundAccess\":\"Allow\",\"calloutId\":\"ooginuvamih\"}") + .toObject(CalloutPolicyInner.class); + Assertions.assertEquals("nmayhuybb", model.calloutUriRegex()); + Assertions.assertEquals(CalloutType.POSTGRESQL, model.calloutType()); + Assertions.assertEquals(OutboundAccess.ALLOW, model.outboundAccess()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + CalloutPolicyInner model = new CalloutPolicyInner().withCalloutUriRegex("nmayhuybb") + .withCalloutType(CalloutType.POSTGRESQL) + .withOutboundAccess(OutboundAccess.ALLOW); + model = BinaryData.fromObject(model).toObject(CalloutPolicyInner.class); + Assertions.assertEquals("nmayhuybb", model.calloutUriRegex()); + Assertions.assertEquals(CalloutType.POSTGRESQL, model.calloutType()); + Assertions.assertEquals(OutboundAccess.ALLOW, model.outboundAccess()); + } +} diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/CalloutPolicyToRemoveTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/CalloutPolicyToRemoveTests.java new file mode 100644 index 000000000000..d00a6fad5b21 --- /dev/null +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/CalloutPolicyToRemoveTests.java @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.kusto.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.kusto.models.CalloutPolicyToRemove; +import org.junit.jupiter.api.Assertions; + +public final class CalloutPolicyToRemoveTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + CalloutPolicyToRemove model + = BinaryData.fromString("{\"calloutId\":\"m\"}").toObject(CalloutPolicyToRemove.class); + Assertions.assertEquals("m", model.calloutId()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + CalloutPolicyToRemove model = new CalloutPolicyToRemove().withCalloutId("m"); + model = BinaryData.fromObject(model).toObject(CalloutPolicyToRemove.class); + Assertions.assertEquals("m", model.calloutId()); + } +} diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/CheckNameRequestTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/CheckNameRequestTests.java index aa4646f536e0..95d32dd24303 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/CheckNameRequestTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/CheckNameRequestTests.java @@ -12,19 +12,20 @@ public final class CheckNameRequestTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - CheckNameRequest model - = BinaryData.fromString("{\"name\":\"tpvjzbexilzznfqq\",\"type\":\"Microsoft.Kusto/clusters/databases\"}") - .toObject(CheckNameRequest.class); - Assertions.assertEquals("tpvjzbexilzznfqq", model.name()); - Assertions.assertEquals(Type.MICROSOFT_KUSTO_CLUSTERS_DATABASES, model.type()); + CheckNameRequest model = BinaryData + .fromString( + "{\"name\":\"pdggkzzlvm\",\"type\":\"Microsoft.Kusto/clusters/attachedDatabaseConfigurations\"}") + .toObject(CheckNameRequest.class); + Assertions.assertEquals("pdggkzzlvm", model.name()); + Assertions.assertEquals(Type.MICROSOFT_KUSTO_CLUSTERS_ATTACHED_DATABASE_CONFIGURATIONS, model.type()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - CheckNameRequest model - = new CheckNameRequest().withName("tpvjzbexilzznfqq").withType(Type.MICROSOFT_KUSTO_CLUSTERS_DATABASES); + CheckNameRequest model = new CheckNameRequest().withName("pdggkzzlvm") + .withType(Type.MICROSOFT_KUSTO_CLUSTERS_ATTACHED_DATABASE_CONFIGURATIONS); model = BinaryData.fromObject(model).toObject(CheckNameRequest.class); - Assertions.assertEquals("tpvjzbexilzznfqq", model.name()); - Assertions.assertEquals(Type.MICROSOFT_KUSTO_CLUSTERS_DATABASES, model.type()); + Assertions.assertEquals("pdggkzzlvm", model.name()); + Assertions.assertEquals(Type.MICROSOFT_KUSTO_CLUSTERS_ATTACHED_DATABASE_CONFIGURATIONS, model.type()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/CheckNameResultInnerTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/CheckNameResultInnerTests.java index 74ee69fd4c77..839105cbd2ad 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/CheckNameResultInnerTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/CheckNameResultInnerTests.java @@ -13,25 +13,24 @@ public final class CheckNameResultInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { CheckNameResultInner model = BinaryData - .fromString( - "{\"nameAvailable\":false,\"name\":\"jq\",\"message\":\"hmuouqfprwzwbn\",\"reason\":\"AlreadyExists\"}") + .fromString("{\"nameAvailable\":false,\"name\":\"y\",\"message\":\"hr\",\"reason\":\"AlreadyExists\"}") .toObject(CheckNameResultInner.class); Assertions.assertEquals(false, model.nameAvailable()); - Assertions.assertEquals("jq", model.name()); - Assertions.assertEquals("hmuouqfprwzwbn", model.message()); + Assertions.assertEquals("y", model.name()); + Assertions.assertEquals("hr", model.message()); Assertions.assertEquals(Reason.ALREADY_EXISTS, model.reason()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { CheckNameResultInner model = new CheckNameResultInner().withNameAvailable(false) - .withName("jq") - .withMessage("hmuouqfprwzwbn") + .withName("y") + .withMessage("hr") .withReason(Reason.ALREADY_EXISTS); model = BinaryData.fromObject(model).toObject(CheckNameResultInner.class); Assertions.assertEquals(false, model.nameAvailable()); - Assertions.assertEquals("jq", model.name()); - Assertions.assertEquals("hmuouqfprwzwbn", model.message()); + Assertions.assertEquals("y", model.name()); + Assertions.assertEquals("hr", model.message()); Assertions.assertEquals(Reason.ALREADY_EXISTS, model.reason()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterCheckNameRequestTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterCheckNameRequestTests.java index 1a74cc3d9a64..90bb68518e17 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterCheckNameRequestTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterCheckNameRequestTests.java @@ -12,14 +12,14 @@ public final class ClusterCheckNameRequestTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ClusterCheckNameRequest model - = BinaryData.fromString("{\"name\":\"t\"}").toObject(ClusterCheckNameRequest.class); - Assertions.assertEquals("t", model.name()); + = BinaryData.fromString("{\"name\":\"niyqslui\"}").toObject(ClusterCheckNameRequest.class); + Assertions.assertEquals("niyqslui", model.name()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - ClusterCheckNameRequest model = new ClusterCheckNameRequest().withName("t"); + ClusterCheckNameRequest model = new ClusterCheckNameRequest().withName("niyqslui"); model = BinaryData.fromObject(model).toObject(ClusterCheckNameRequest.class); - Assertions.assertEquals("t", model.name()); + Assertions.assertEquals("niyqslui", model.name()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterMigrateRequestTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterMigrateRequestTests.java index 06aa9cb3fbfe..0f430b7281e6 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterMigrateRequestTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterMigrateRequestTests.java @@ -12,14 +12,14 @@ public final class ClusterMigrateRequestTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ClusterMigrateRequest model - = BinaryData.fromString("{\"clusterResourceId\":\"cpr\"}").toObject(ClusterMigrateRequest.class); - Assertions.assertEquals("cpr", model.clusterResourceId()); + = BinaryData.fromString("{\"clusterResourceId\":\"rwzwbng\"}").toObject(ClusterMigrateRequest.class); + Assertions.assertEquals("rwzwbng", model.clusterResourceId()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - ClusterMigrateRequest model = new ClusterMigrateRequest().withClusterResourceId("cpr"); + ClusterMigrateRequest model = new ClusterMigrateRequest().withClusterResourceId("rwzwbng"); model = BinaryData.fromObject(model).toObject(ClusterMigrateRequest.class); - Assertions.assertEquals("cpr", model.clusterResourceId()); + Assertions.assertEquals("rwzwbng", model.clusterResourceId()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentCheckNameRequestTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentCheckNameRequestTests.java index 52ae46c192a1..79517baefcfc 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentCheckNameRequestTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentCheckNameRequestTests.java @@ -11,16 +11,16 @@ public final class ClusterPrincipalAssignmentCheckNameRequestTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - ClusterPrincipalAssignmentCheckNameRequest model = BinaryData.fromString("{\"name\":\"nwbxgjvtbvpyssz\"}") + ClusterPrincipalAssignmentCheckNameRequest model = BinaryData.fromString("{\"name\":\"itnwuizgazxufi\"}") .toObject(ClusterPrincipalAssignmentCheckNameRequest.class); - Assertions.assertEquals("nwbxgjvtbvpyssz", model.name()); + Assertions.assertEquals("itnwuizgazxufi", model.name()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { ClusterPrincipalAssignmentCheckNameRequest model - = new ClusterPrincipalAssignmentCheckNameRequest().withName("nwbxgjvtbvpyssz"); + = new ClusterPrincipalAssignmentCheckNameRequest().withName("itnwuizgazxufi"); model = BinaryData.fromObject(model).toObject(ClusterPrincipalAssignmentCheckNameRequest.class); - Assertions.assertEquals("nwbxgjvtbvpyssz", model.name()); + Assertions.assertEquals("itnwuizgazxufi", model.name()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentInnerTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentInnerTests.java index a217aa1e29ca..e00419344d53 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentInnerTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentInnerTests.java @@ -14,24 +14,24 @@ public final class ClusterPrincipalAssignmentInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ClusterPrincipalAssignmentInner model = BinaryData.fromString( - "{\"properties\":{\"principalId\":\"nwui\",\"role\":\"AllDatabasesAdmin\",\"tenantId\":\"zxufiz\",\"principalType\":\"App\",\"tenantName\":\"y\",\"principalName\":\"hr\",\"provisioningState\":\"Moving\",\"aadObjectId\":\"vzwdzuhtymwis\"},\"id\":\"kfthwxmntei\",\"name\":\"aop\",\"type\":\"km\"}") + "{\"properties\":{\"principalId\":\"vzwdzuhtymwis\",\"role\":\"AllDatabasesViewer\",\"tenantId\":\"thwxmnteiwaopvkm\",\"principalType\":\"Group\",\"tenantName\":\"mmxdcu\",\"principalName\":\"fsrpymzidnse\",\"provisioningState\":\"Moving\",\"aadObjectId\":\"bzsgfyccsne\"},\"id\":\"mdwzjeiachboo\",\"name\":\"flnrosfqpteehzz\",\"type\":\"ypyqrimzinp\"}") .toObject(ClusterPrincipalAssignmentInner.class); - Assertions.assertEquals("nwui", model.principalId()); - Assertions.assertEquals(ClusterPrincipalRole.ALL_DATABASES_ADMIN, model.role()); - Assertions.assertEquals("zxufiz", model.tenantId()); - Assertions.assertEquals(PrincipalType.APP, model.principalType()); + Assertions.assertEquals("vzwdzuhtymwis", model.principalId()); + Assertions.assertEquals(ClusterPrincipalRole.ALL_DATABASES_VIEWER, model.role()); + Assertions.assertEquals("thwxmnteiwaopvkm", model.tenantId()); + Assertions.assertEquals(PrincipalType.GROUP, model.principalType()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - ClusterPrincipalAssignmentInner model = new ClusterPrincipalAssignmentInner().withPrincipalId("nwui") - .withRole(ClusterPrincipalRole.ALL_DATABASES_ADMIN) - .withTenantId("zxufiz") - .withPrincipalType(PrincipalType.APP); + ClusterPrincipalAssignmentInner model = new ClusterPrincipalAssignmentInner().withPrincipalId("vzwdzuhtymwis") + .withRole(ClusterPrincipalRole.ALL_DATABASES_VIEWER) + .withTenantId("thwxmnteiwaopvkm") + .withPrincipalType(PrincipalType.GROUP); model = BinaryData.fromObject(model).toObject(ClusterPrincipalAssignmentInner.class); - Assertions.assertEquals("nwui", model.principalId()); - Assertions.assertEquals(ClusterPrincipalRole.ALL_DATABASES_ADMIN, model.role()); - Assertions.assertEquals("zxufiz", model.tenantId()); - Assertions.assertEquals(PrincipalType.APP, model.principalType()); + Assertions.assertEquals("vzwdzuhtymwis", model.principalId()); + Assertions.assertEquals(ClusterPrincipalRole.ALL_DATABASES_VIEWER, model.role()); + Assertions.assertEquals("thwxmnteiwaopvkm", model.tenantId()); + Assertions.assertEquals(PrincipalType.GROUP, model.principalType()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentListResultTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentListResultTests.java index 77d01132ea2a..dae5d03ba758 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentListResultTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentListResultTests.java @@ -16,29 +16,25 @@ public final class ClusterPrincipalAssignmentListResultTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ClusterPrincipalAssignmentListResult model = BinaryData.fromString( - "{\"value\":[{\"properties\":{\"principalId\":\"sflnrosfqp\",\"role\":\"AllDatabasesAdmin\",\"tenantId\":\"hzzvypyq\",\"principalType\":\"User\",\"tenantName\":\"z\",\"principalName\":\"pvswjdkirso\",\"provisioningState\":\"Deleting\",\"aadObjectId\":\"hc\"},\"id\":\"mnoh\",\"name\":\"t\",\"type\":\"kwh\"},{\"properties\":{\"principalId\":\"oifiyipjxsqwpgr\",\"role\":\"AllDatabasesViewer\",\"tenantId\":\"norcjxvsnbyxqab\",\"principalType\":\"User\",\"tenantName\":\"cpc\",\"principalName\":\"hurzafblj\",\"provisioningState\":\"Creating\",\"aadObjectId\":\"toqcjmklja\"},\"id\":\"bqidtqaj\",\"name\":\"yulpkudjkr\",\"type\":\"khbzhfepgzg\"}]}") + "{\"value\":[{\"properties\":{\"principalId\":\"cyshurzafbljjgp\",\"role\":\"AllDatabasesMonitor\",\"tenantId\":\"qcjm\",\"principalType\":\"Group\",\"tenantName\":\"a\",\"principalName\":\"qidtqajzyu\",\"provisioningState\":\"Deleting\",\"aadObjectId\":\"dj\"},\"id\":\"rlkhbzhfepgzgq\",\"name\":\"xzlocxscp\",\"type\":\"ierhhbcsglummaj\"}]}") .toObject(ClusterPrincipalAssignmentListResult.class); - Assertions.assertEquals("sflnrosfqp", model.value().get(0).principalId()); - Assertions.assertEquals(ClusterPrincipalRole.ALL_DATABASES_ADMIN, model.value().get(0).role()); - Assertions.assertEquals("hzzvypyq", model.value().get(0).tenantId()); - Assertions.assertEquals(PrincipalType.USER, model.value().get(0).principalType()); + Assertions.assertEquals("cyshurzafbljjgp", model.value().get(0).principalId()); + Assertions.assertEquals(ClusterPrincipalRole.ALL_DATABASES_MONITOR, model.value().get(0).role()); + Assertions.assertEquals("qcjm", model.value().get(0).tenantId()); + Assertions.assertEquals(PrincipalType.GROUP, model.value().get(0).principalType()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - ClusterPrincipalAssignmentListResult model = new ClusterPrincipalAssignmentListResult().withValue(Arrays.asList( - new ClusterPrincipalAssignmentInner().withPrincipalId("sflnrosfqp") - .withRole(ClusterPrincipalRole.ALL_DATABASES_ADMIN) - .withTenantId("hzzvypyq") - .withPrincipalType(PrincipalType.USER), - new ClusterPrincipalAssignmentInner().withPrincipalId("oifiyipjxsqwpgr") - .withRole(ClusterPrincipalRole.ALL_DATABASES_VIEWER) - .withTenantId("norcjxvsnbyxqab") - .withPrincipalType(PrincipalType.USER))); + ClusterPrincipalAssignmentListResult model = new ClusterPrincipalAssignmentListResult() + .withValue(Arrays.asList(new ClusterPrincipalAssignmentInner().withPrincipalId("cyshurzafbljjgp") + .withRole(ClusterPrincipalRole.ALL_DATABASES_MONITOR) + .withTenantId("qcjm") + .withPrincipalType(PrincipalType.GROUP))); model = BinaryData.fromObject(model).toObject(ClusterPrincipalAssignmentListResult.class); - Assertions.assertEquals("sflnrosfqp", model.value().get(0).principalId()); - Assertions.assertEquals(ClusterPrincipalRole.ALL_DATABASES_ADMIN, model.value().get(0).role()); - Assertions.assertEquals("hzzvypyq", model.value().get(0).tenantId()); - Assertions.assertEquals(PrincipalType.USER, model.value().get(0).principalType()); + Assertions.assertEquals("cyshurzafbljjgp", model.value().get(0).principalId()); + Assertions.assertEquals(ClusterPrincipalRole.ALL_DATABASES_MONITOR, model.value().get(0).role()); + Assertions.assertEquals("qcjm", model.value().get(0).tenantId()); + Assertions.assertEquals(PrincipalType.GROUP, model.value().get(0).principalType()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsCheckNameAvailabilityWithResponseMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsCheckNameAvailabilityWithResponseMockTests.java index 16b6bc094cc1..6c52291ac20d 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsCheckNameAvailabilityWithResponseMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsCheckNameAvailabilityWithResponseMockTests.java @@ -23,7 +23,7 @@ public final class ClusterPrincipalAssignmentsCheckNameAvailabilityWithResponseM @Test public void testCheckNameAvailabilityWithResponse() throws Exception { String responseStr - = "{\"nameAvailable\":true,\"name\":\"v\",\"message\":\"yasflvgsgzwy\",\"reason\":\"Invalid\"}"; + = "{\"nameAvailable\":true,\"name\":\"kfkimrtixok\",\"message\":\"qyinl\",\"reason\":\"Invalid\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -33,13 +33,14 @@ public void testCheckNameAvailabilityWithResponse() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); CheckNameResult response = manager.clusterPrincipalAssignments() - .checkNameAvailabilityWithResponse("z", "puamwabzxr", - new ClusterPrincipalAssignmentCheckNameRequest().withName("xcushs"), com.azure.core.util.Context.NONE) + .checkNameAvailabilityWithResponse("gaao", "pttaqutd", + new ClusterPrincipalAssignmentCheckNameRequest().withName("wemxswvruunzz"), + com.azure.core.util.Context.NONE) .getValue(); Assertions.assertEquals(true, response.nameAvailable()); - Assertions.assertEquals("v", response.name()); - Assertions.assertEquals("yasflvgsgzwy", response.message()); + Assertions.assertEquals("kfkimrtixok", response.name()); + Assertions.assertEquals("qyinl", response.message()); Assertions.assertEquals(Reason.INVALID, response.reason()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsCreateOrUpdateMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsCreateOrUpdateMockTests.java index 3dfa269cec03..ad2cc35edb29 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsCreateOrUpdateMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsCreateOrUpdateMockTests.java @@ -23,7 +23,7 @@ public final class ClusterPrincipalAssignmentsCreateOrUpdateMockTests { @Test public void testCreateOrUpdate() throws Exception { String responseStr - = "{\"properties\":{\"principalId\":\"zjkjexfdeqv\",\"role\":\"AllDatabasesViewer\",\"tenantId\":\"ylkkshkbffmbm\",\"principalType\":\"Group\",\"tenantName\":\"rgywwp\",\"principalName\":\"xs\",\"provisioningState\":\"Succeeded\",\"aadObjectId\":\"ujgicgaaoe\"},\"id\":\"ttaqutdew\",\"name\":\"mxswvruunzz\",\"type\":\"gehkfkimrtixokff\"}"; + = "{\"properties\":{\"principalId\":\"syrq\",\"role\":\"AllDatabasesAdmin\",\"tenantId\":\"qhd\",\"principalType\":\"Group\",\"tenantName\":\"aulk\",\"principalName\":\"kdk\",\"provisioningState\":\"Succeeded\",\"aadObjectId\":\"nnawtqabpxuckpgg\"},\"id\":\"oweyirdhlis\",\"name\":\"gwflq\",\"type\":\"mpizru\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -33,17 +33,17 @@ public void testCreateOrUpdate() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); ClusterPrincipalAssignment response = manager.clusterPrincipalAssignments() - .define("fy") - .withExistingCluster("z", "kiwbuqnyoph") - .withPrincipalId("gcrpfbcun") - .withRole(ClusterPrincipalRole.ALL_DATABASES_VIEWER) - .withTenantId("cez") + .define("rltzkatbhjmz") + .withExistingCluster("smgbzahgxqdl", "rtltla") + .withPrincipalId("bsoqeqala") + .withRole(ClusterPrincipalRole.ALL_DATABASES_ADMIN) + .withTenantId("agunbtgfebw") .withPrincipalType(PrincipalType.GROUP) .create(); - Assertions.assertEquals("zjkjexfdeqv", response.principalId()); - Assertions.assertEquals(ClusterPrincipalRole.ALL_DATABASES_VIEWER, response.role()); - Assertions.assertEquals("ylkkshkbffmbm", response.tenantId()); + Assertions.assertEquals("syrq", response.principalId()); + Assertions.assertEquals(ClusterPrincipalRole.ALL_DATABASES_ADMIN, response.role()); + Assertions.assertEquals("qhd", response.tenantId()); Assertions.assertEquals(PrincipalType.GROUP, response.principalType()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsDeleteMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsDeleteMockTests.java index d56483fd64b7..edd4a57846b2 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsDeleteMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsDeleteMockTests.java @@ -28,7 +28,7 @@ public void testDelete() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); manager.clusterPrincipalAssignments() - .delete("blembnkbwvqvxkd", "vqihebwtswbzuwf", "duragegizvc", com.azure.core.util.Context.NONE); + .delete("vumwmxqh", "dvnoamldsehaohdj", "hflzokxco", com.azure.core.util.Context.NONE); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsGetWithResponseMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsGetWithResponseMockTests.java index f086cf7c0f63..0e16c623fc0a 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsGetWithResponseMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsGetWithResponseMockTests.java @@ -23,7 +23,7 @@ public final class ClusterPrincipalAssignmentsGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"principalId\":\"vwf\",\"role\":\"AllDatabasesAdmin\",\"tenantId\":\"yxonsupe\",\"principalType\":\"User\",\"tenantName\":\"zqn\",\"principalName\":\"vsqltnzoibgsxg\",\"provisioningState\":\"Moving\",\"aadObjectId\":\"qonmpqoxwdof\"},\"id\":\"bxiqxeiiqbimht\",\"name\":\"wwinhehf\",\"type\":\"pofvwb\"}"; + = "{\"properties\":{\"principalId\":\"ninwjizc\",\"role\":\"AllDatabasesMonitor\",\"tenantId\":\"ghgshejjtbxqmu\",\"principalType\":\"Group\",\"tenantName\":\"lxqzvn\",\"principalName\":\"sbycucrwnamikz\",\"provisioningState\":\"Failed\",\"aadObjectId\":\"bsmswziqgf\"},\"id\":\"hokzrusw\",\"name\":\"vhczznvfby\",\"type\":\"jsxjwwix\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -33,12 +33,12 @@ public void testGetWithResponse() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); ClusterPrincipalAssignment response = manager.clusterPrincipalAssignments() - .getWithResponse("oi", "knsmjblmljhlnymz", "tqyryuzcbmqqv", com.azure.core.util.Context.NONE) + .getWithResponse("pqwhixmonst", "hiyxgvelfclduc", "birdsvuwcobiegs", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("vwf", response.principalId()); - Assertions.assertEquals(ClusterPrincipalRole.ALL_DATABASES_ADMIN, response.role()); - Assertions.assertEquals("yxonsupe", response.tenantId()); - Assertions.assertEquals(PrincipalType.USER, response.principalType()); + Assertions.assertEquals("ninwjizc", response.principalId()); + Assertions.assertEquals(ClusterPrincipalRole.ALL_DATABASES_MONITOR, response.role()); + Assertions.assertEquals("ghgshejjtbxqmu", response.tenantId()); + Assertions.assertEquals(PrincipalType.GROUP, response.principalType()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsListMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsListMockTests.java index f1174f432d65..d47b5ae26f25 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsListMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalAssignmentsListMockTests.java @@ -24,7 +24,7 @@ public final class ClusterPrincipalAssignmentsListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"principalId\":\"xkbsazgakgac\",\"role\":\"AllDatabasesViewer\",\"tenantId\":\"m\",\"principalType\":\"Group\",\"tenantName\":\"spofapvuhry\",\"principalName\":\"iofrzgbzjedmstk\",\"provisioningState\":\"Moving\",\"aadObjectId\":\"xbcuiiznkt\"},\"id\":\"f\",\"name\":\"nsnvpd\",\"type\":\"bmikost\"}]}"; + = "{\"value\":[{\"properties\":{\"principalId\":\"pbswvefloccsrm\",\"role\":\"AllDatabasesAdmin\",\"tenantId\":\"hmipgawtxxpkyjc\",\"principalType\":\"Group\",\"tenantName\":\"xgrytfmp\",\"principalName\":\"cil\",\"provisioningState\":\"Succeeded\",\"aadObjectId\":\"ykggnoxuztrksx\"},\"id\":\"pndfcpfnznt\",\"name\":\"jtwkjaos\",\"type\":\"xuzvoamktcqi\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -34,11 +34,11 @@ public void testList() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); PagedIterable response - = manager.clusterPrincipalAssignments().list("felisdjub", "gbqi", com.azure.core.util.Context.NONE); + = manager.clusterPrincipalAssignments().list("pelnjetag", "tsxoatftgz", com.azure.core.util.Context.NONE); - Assertions.assertEquals("xkbsazgakgac", response.iterator().next().principalId()); - Assertions.assertEquals(ClusterPrincipalRole.ALL_DATABASES_VIEWER, response.iterator().next().role()); - Assertions.assertEquals("m", response.iterator().next().tenantId()); + Assertions.assertEquals("pbswvefloccsrm", response.iterator().next().principalId()); + Assertions.assertEquals(ClusterPrincipalRole.ALL_DATABASES_ADMIN, response.iterator().next().role()); + Assertions.assertEquals("hmipgawtxxpkyjc", response.iterator().next().tenantId()); Assertions.assertEquals(PrincipalType.GROUP, response.iterator().next().principalType()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalPropertiesTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalPropertiesTests.java index 07eb46ad90a4..cf30f9258923 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalPropertiesTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClusterPrincipalPropertiesTests.java @@ -14,24 +14,24 @@ public final class ClusterPrincipalPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ClusterPrincipalProperties model = BinaryData.fromString( - "{\"principalId\":\"jcmmxdcufufsrp\",\"role\":\"AllDatabasesViewer\",\"tenantId\":\"idnsezcxtb\",\"principalType\":\"Group\",\"tenantName\":\"fycc\",\"principalName\":\"ewmdw\",\"provisioningState\":\"Running\",\"aadObjectId\":\"ac\"}") + "{\"principalId\":\"swjdkirso\",\"role\":\"AllDatabasesAdmin\",\"tenantId\":\"xhcr\",\"principalType\":\"User\",\"tenantName\":\"hjtckwhd\",\"principalName\":\"ifiyipjxsqwpgrj\",\"provisioningState\":\"Moving\",\"aadObjectId\":\"rcjxvsnbyxqabn\"}") .toObject(ClusterPrincipalProperties.class); - Assertions.assertEquals("jcmmxdcufufsrp", model.principalId()); - Assertions.assertEquals(ClusterPrincipalRole.ALL_DATABASES_VIEWER, model.role()); - Assertions.assertEquals("idnsezcxtb", model.tenantId()); - Assertions.assertEquals(PrincipalType.GROUP, model.principalType()); + Assertions.assertEquals("swjdkirso", model.principalId()); + Assertions.assertEquals(ClusterPrincipalRole.ALL_DATABASES_ADMIN, model.role()); + Assertions.assertEquals("xhcr", model.tenantId()); + Assertions.assertEquals(PrincipalType.USER, model.principalType()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - ClusterPrincipalProperties model = new ClusterPrincipalProperties().withPrincipalId("jcmmxdcufufsrp") - .withRole(ClusterPrincipalRole.ALL_DATABASES_VIEWER) - .withTenantId("idnsezcxtb") - .withPrincipalType(PrincipalType.GROUP); + ClusterPrincipalProperties model = new ClusterPrincipalProperties().withPrincipalId("swjdkirso") + .withRole(ClusterPrincipalRole.ALL_DATABASES_ADMIN) + .withTenantId("xhcr") + .withPrincipalType(PrincipalType.USER); model = BinaryData.fromObject(model).toObject(ClusterPrincipalProperties.class); - Assertions.assertEquals("jcmmxdcufufsrp", model.principalId()); - Assertions.assertEquals(ClusterPrincipalRole.ALL_DATABASES_VIEWER, model.role()); - Assertions.assertEquals("idnsezcxtb", model.tenantId()); - Assertions.assertEquals(PrincipalType.GROUP, model.principalType()); + Assertions.assertEquals("swjdkirso", model.principalId()); + Assertions.assertEquals(ClusterPrincipalRole.ALL_DATABASES_ADMIN, model.role()); + Assertions.assertEquals("xhcr", model.tenantId()); + Assertions.assertEquals(PrincipalType.USER, model.principalType()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersAddCalloutPoliciesMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersAddCalloutPoliciesMockTests.java new file mode 100644 index 000000000000..2f5715f9cb11 --- /dev/null +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersAddCalloutPoliciesMockTests.java @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.kusto.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.kusto.KustoManager; +import com.azure.resourcemanager.kusto.fluent.models.CalloutPolicyInner; +import com.azure.resourcemanager.kusto.models.CalloutPoliciesList; +import com.azure.resourcemanager.kusto.models.CalloutType; +import com.azure.resourcemanager.kusto.models.OutboundAccess; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Arrays; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class ClustersAddCalloutPoliciesMockTests { + @Test + public void testAddCalloutPolicies() throws Exception { + String responseStr = "{}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + KustoManager manager = KustoManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureEnvironment.AZURE)); + + manager.clusters() + .addCalloutPolicies("gorqjbttzh", "aglkafhon", + new CalloutPoliciesList().withValue(Arrays.asList( + new CalloutPolicyInner().withCalloutUriRegex("eickpz") + .withCalloutType(CalloutType.SQL) + .withOutboundAccess(OutboundAccess.DENY), + new CalloutPolicyInner().withCalloutUriRegex("yjede") + .withCalloutType(CalloutType.MYSQL) + .withOutboundAccess(OutboundAccess.ALLOW))) + .withNextLink("amwabzxrvxcushsp"), + com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersAddLanguageExtensionsMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersAddLanguageExtensionsMockTests.java index 3f5e68efb65c..670e29a8ba83 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersAddLanguageExtensionsMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersAddLanguageExtensionsMockTests.java @@ -33,17 +33,11 @@ public void testAddLanguageExtensions() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); manager.clusters() - .addLanguageExtensions("pn", "qvcww", - new LanguageExtensionsList().withValue(Arrays.asList( - new LanguageExtensionInner().withLanguageExtensionName(LanguageExtensionName.R) - .withLanguageExtensionImageName(LanguageExtensionImageName.PYTHON_CUSTOM_IMAGE) - .withLanguageExtensionCustomImageName("ppr"), - new LanguageExtensionInner().withLanguageExtensionName(LanguageExtensionName.R) - .withLanguageExtensionImageName(LanguageExtensionImageName.R) - .withLanguageExtensionCustomImageName("k"), - new LanguageExtensionInner().withLanguageExtensionName(LanguageExtensionName.PYTHON) - .withLanguageExtensionImageName(LanguageExtensionImageName.PYTHON_CUSTOM_IMAGE) - .withLanguageExtensionCustomImageName("hlb"))), + .addLanguageExtensions("iiqbi", "htmwwinh", + new LanguageExtensionsList().withValue( + Arrays.asList(new LanguageExtensionInner().withLanguageExtensionName(LanguageExtensionName.PYTHON) + .withLanguageExtensionImageName(LanguageExtensionImageName.PYTHON3_10_8_DL) + .withLanguageExtensionCustomImageName("wbcb"))), com.azure.core.util.Context.NONE); } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersCheckNameAvailabilityWithResponseMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersCheckNameAvailabilityWithResponseMockTests.java index a0a95ffe333c..880a0c2344fc 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersCheckNameAvailabilityWithResponseMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersCheckNameAvailabilityWithResponseMockTests.java @@ -22,8 +22,7 @@ public final class ClustersCheckNameAvailabilityWithResponseMockTests { @Test public void testCheckNameAvailabilityWithResponse() throws Exception { - String responseStr - = "{\"nameAvailable\":false,\"name\":\"bxhugcmjkavlgorb\",\"message\":\"tp\",\"reason\":\"Invalid\"}"; + String responseStr = "{\"nameAvailable\":true,\"name\":\"mcjn\",\"message\":\"qdqx\",\"reason\":\"Invalid\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -33,13 +32,13 @@ public void testCheckNameAvailabilityWithResponse() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); CheckNameResult response = manager.clusters() - .checkNameAvailabilityWithResponse("xhcmavmqfoudo", new ClusterCheckNameRequest().withName("hcgyyprotwyp"), + .checkNameAvailabilityWithResponse("dsdaultxijjumf", new ClusterCheckNameRequest().withName("waz"), com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals(false, response.nameAvailable()); - Assertions.assertEquals("bxhugcmjkavlgorb", response.name()); - Assertions.assertEquals("tp", response.message()); + Assertions.assertEquals(true, response.nameAvailable()); + Assertions.assertEquals("mcjn", response.name()); + Assertions.assertEquals("qdqx", response.message()); Assertions.assertEquals(Reason.INVALID, response.reason()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersDeleteMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersDeleteMockTests.java index 59ce5e6d66ac..35fc8e9d131f 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersDeleteMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersDeleteMockTests.java @@ -27,7 +27,7 @@ public void testDelete() throws Exception { .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), new AzureProfile("", "", AzureEnvironment.AZURE)); - manager.clusters().delete("bkbxgomfa", "uwasqvd", com.azure.core.util.Context.NONE); + manager.clusters().delete("eesvecu", "jpxtxsuwprtuj", com.azure.core.util.Context.NONE); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersDetachFollowerDatabasesMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersDetachFollowerDatabasesMockTests.java index 11dcc66b09b0..3595414dba7a 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersDetachFollowerDatabasesMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersDetachFollowerDatabasesMockTests.java @@ -29,8 +29,10 @@ public void testDetachFollowerDatabases() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); manager.clusters() - .detachFollowerDatabases("lpagzrcx", "a", new FollowerDatabaseDefinitionInner().withClusterResourceId("lc") - .withAttachedDatabaseConfigurationName("xwmdboxd"), com.azure.core.util.Context.NONE); + .detachFollowerDatabases("rtffyaqitmh", "eioqaqhvse", + new FollowerDatabaseDefinitionInner().withClusterResourceId("fuqyrxpdlcgqlsi") + .withAttachedDatabaseConfigurationName("mjqfrddgamquhio"), + com.azure.core.util.Context.NONE); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersDiagnoseVirtualNetworkMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersDiagnoseVirtualNetworkMockTests.java index 8a7dd7281e66..a53e420d88d5 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersDiagnoseVirtualNetworkMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersDiagnoseVirtualNetworkMockTests.java @@ -20,7 +20,7 @@ public final class ClustersDiagnoseVirtualNetworkMockTests { @Test public void testDiagnoseVirtualNetwork() throws Exception { - String responseStr = "{\"findings\":[\"pwbralllibphbqz\"]}"; + String responseStr = "{\"findings\":[\"ywuhpsvfuur\",\"tlwexxwlalniexz\",\"rzpgep\"]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -29,9 +29,9 @@ public void testDiagnoseVirtualNetwork() throws Exception { .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), new AzureProfile("", "", AzureEnvironment.AZURE)); - DiagnoseVirtualNetworkResult response - = manager.clusters().diagnoseVirtualNetwork("gdqoh", "cwsldri", com.azure.core.util.Context.NONE); + DiagnoseVirtualNetworkResult response = manager.clusters() + .diagnoseVirtualNetwork("awumuaslzkwrrwo", "cqucwyhahnom", com.azure.core.util.Context.NONE); - Assertions.assertEquals("pwbralllibphbqz", response.findings().get(0)); + Assertions.assertEquals("ywuhpsvfuur", response.findings().get(0)); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersListCalloutPoliciesMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersListCalloutPoliciesMockTests.java new file mode 100644 index 000000000000..8f9d162b97fd --- /dev/null +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersListCalloutPoliciesMockTests.java @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.kusto.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.kusto.KustoManager; +import com.azure.resourcemanager.kusto.models.CalloutPolicy; +import com.azure.resourcemanager.kusto.models.CalloutType; +import com.azure.resourcemanager.kusto.models.OutboundAccess; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class ClustersListCalloutPoliciesMockTests { + @Test + public void testListCalloutPolicies() throws Exception { + String responseStr + = "{\"value\":[{\"calloutUriRegex\":\"gtayxonsupeujlz\",\"calloutType\":\"sql\",\"outboundAccess\":\"Deny\",\"calloutId\":\"ql\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + KustoManager manager = KustoManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureEnvironment.AZURE)); + + PagedIterable response + = manager.clusters().listCalloutPolicies("tqyryuzcbmqqv", "mv", com.azure.core.util.Context.NONE); + + Assertions.assertEquals("gtayxonsupeujlz", response.iterator().next().calloutUriRegex()); + Assertions.assertEquals(CalloutType.SQL, response.iterator().next().calloutType()); + Assertions.assertEquals(OutboundAccess.DENY, response.iterator().next().outboundAccess()); + } +} diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersListFollowerDatabasesGetMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersListFollowerDatabasesGetMockTests.java new file mode 100644 index 000000000000..751dea101a74 --- /dev/null +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersListFollowerDatabasesGetMockTests.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.resourcemanager.kusto.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.kusto.KustoManager; +import com.azure.resourcemanager.kusto.models.FollowerDatabaseDefinitionGet; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class ClustersListFollowerDatabasesGetMockTests { + @Test + public void testListFollowerDatabasesGet() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"clusterResourceId\":\"mes\",\"attachedDatabaseConfigurationName\":\"kdlpa\",\"databaseName\":\"rcxfailcfxwmdb\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"gsftufqobrjlnacg\",\"ckknhxkizvy\",\"nrzvuljraaer\"],\"tablesToExclude\":[\"kqg\",\"kkjqnvbroylaxxu\",\"cdisd\"],\"externalTablesToInclude\":[\"jbjsvgjrwh\"],\"externalTablesToExclude\":[\"ycy\"],\"materializedViewsToInclude\":[\"lxgccknfnwmbtm\"],\"materializedViewsToExclude\":[\"vjdhttzaefedxih\",\"hrphkmcrjdqn\",\"dfzpbgtgkylkdg\"],\"functionsToInclude\":[\"euutlwxezwzh\",\"kvbwnhhtqlgeh\"],\"functionsToExclude\":[\"ipifhpfeoajvg\",\"xtxj\"]},\"databaseShareOrigin\":\"Other\"}}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + KustoManager manager = KustoManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureEnvironment.AZURE)); + + PagedIterable response + = manager.clusters().listFollowerDatabasesGet("vodhtn", "irudh", com.azure.core.util.Context.NONE); + + Assertions.assertEquals("mes", response.iterator().next().clusterResourceId()); + Assertions.assertEquals("kdlpa", response.iterator().next().attachedDatabaseConfigurationName()); + } +} diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersListFollowerDatabasesMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersListFollowerDatabasesMockTests.java index 137af1ae9ccf..088117e11d0e 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersListFollowerDatabasesMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersListFollowerDatabasesMockTests.java @@ -22,7 +22,7 @@ public final class ClustersListFollowerDatabasesMockTests { @Test public void testListFollowerDatabases() throws Exception { String responseStr - = "{\"value\":[{\"clusterResourceId\":\"yxkyxvx\",\"attachedDatabaseConfigurationName\":\"vblbjednljlageua\",\"databaseName\":\"xuns\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"kppxynenlsvxeiz\",\"gwklnsr\",\"ffeycx\"],\"tablesToExclude\":[\"piymerteea\",\"mx\",\"iekkkzddrtkgdojb\"],\"externalTablesToInclude\":[\"a\",\"refdee\",\"vecuijpx\"],\"externalTablesToExclude\":[\"uwprtujwsawd\"],\"materializedViewsToInclude\":[\"babxvitit\",\"tzeexav\",\"xtfglecdmdqb\",\"pypqtgsfj\"],\"materializedViewsToExclude\":[\"slhhxudbxv\"],\"functionsToInclude\":[\"tnsi\",\"ud\"],\"functionsToExclude\":[\"mes\"]},\"databaseShareOrigin\":\"Other\"}]}"; + = "{\"value\":[{\"clusterResourceId\":\"egprhptil\",\"attachedDatabaseConfigurationName\":\"ucb\",\"databaseName\":\"tgdqohmcwsldriz\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"bra\",\"llibphbqzmizak\",\"kan\",\"jpdn\"],\"tablesToExclude\":[\"ajoylhjl\"],\"externalTablesToInclude\":[\"y\",\"primr\"],\"externalTablesToExclude\":[\"teecjmeislst\",\"asylwx\"],\"materializedViewsToInclude\":[\"umweoohguufuzboy\",\"athwt\",\"olbaemwmdx\",\"ebwjscjpahlxvea\"],\"materializedViewsToExclude\":[\"xnmwmqtibxyijddt\",\"qcttadijaeukmrsi\"],\"functionsToInclude\":[\"pndzaapmudqmeq\"],\"functionsToExclude\":[\"pibudqwyxebeybpm\"]},\"databaseShareOrigin\":\"Other\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -31,10 +31,10 @@ public void testListFollowerDatabases() throws Exception { .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), new AzureProfile("", "", AzureEnvironment.AZURE)); - PagedIterable response - = manager.clusters().listFollowerDatabases("kzyb", "jjidjk", com.azure.core.util.Context.NONE); + PagedIterable response = manager.clusters() + .listFollowerDatabases("eafidltugsresm", "ssjhoiftxfkf", com.azure.core.util.Context.NONE); - Assertions.assertEquals("yxkyxvx", response.iterator().next().clusterResourceId()); - Assertions.assertEquals("vblbjednljlageua", response.iterator().next().attachedDatabaseConfigurationName()); + Assertions.assertEquals("egprhptil", response.iterator().next().clusterResourceId()); + Assertions.assertEquals("ucb", response.iterator().next().attachedDatabaseConfigurationName()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersListLanguageExtensionsMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersListLanguageExtensionsMockTests.java index 2f8bbeb5df0c..d1600139368f 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersListLanguageExtensionsMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersListLanguageExtensionsMockTests.java @@ -24,7 +24,7 @@ public final class ClustersListLanguageExtensionsMockTests { @Test public void testListLanguageExtensions() throws Exception { String responseStr - = "{\"value\":[{\"languageExtensionName\":\"R\",\"languageExtensionImageName\":\"Python3_6_5\",\"languageExtensionCustomImageName\":\"iojlvfhrb\"}]}"; + = "{\"value\":[{\"languageExtensionName\":\"PYTHON\",\"languageExtensionImageName\":\"Python3_10_8_DL\",\"languageExtensionCustomImageName\":\"wdofdbxiqx\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -34,11 +34,11 @@ public void testListLanguageExtensions() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); PagedIterable response - = manager.clusters().listLanguageExtensions("sbostzel", "dlat", com.azure.core.util.Context.NONE); + = manager.clusters().listLanguageExtensions("nzoibgsxgnx", "yqo", com.azure.core.util.Context.NONE); - Assertions.assertEquals(LanguageExtensionName.R, response.iterator().next().languageExtensionName()); - Assertions.assertEquals(LanguageExtensionImageName.PYTHON3_6_5, + Assertions.assertEquals(LanguageExtensionName.PYTHON, response.iterator().next().languageExtensionName()); + Assertions.assertEquals(LanguageExtensionImageName.PYTHON3_10_8_DL, response.iterator().next().languageExtensionImageName()); - Assertions.assertEquals("iojlvfhrb", response.iterator().next().languageExtensionCustomImageName()); + Assertions.assertEquals("wdofdbxiqx", response.iterator().next().languageExtensionCustomImageName()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersListOutboundNetworkDependenciesEndpointsMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersListOutboundNetworkDependenciesEndpointsMockTests.java index 955da5ee01c0..10852da884db 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersListOutboundNetworkDependenciesEndpointsMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersListOutboundNetworkDependenciesEndpointsMockTests.java @@ -22,7 +22,7 @@ public final class ClustersListOutboundNetworkDependenciesEndpointsMockTests { @Test public void testListOutboundNetworkDependenciesEndpoints() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"category\":\"tmcdzsufcohd\",\"endpoints\":[{\"domainName\":\"mcmuapc\",\"endpointDetails\":[{},{},{},{}]},{\"domainName\":\"evwqqxeyskonq\",\"endpointDetails\":[{},{},{}]},{\"domainName\":\"fkbg\",\"endpointDetails\":[{},{}]},{\"domainName\":\"wxeqocljmygvkzqk\",\"endpointDetails\":[{},{}]}],\"provisioningState\":\"Canceled\"},\"etag\":\"zefezrxcczurtl\",\"id\":\"ipqxbkwvzgnzv\",\"name\":\"fbzdixzmqpnoda\",\"type\":\"opqhewjptmc\"}]}"; + = "{\"value\":[{\"properties\":{\"category\":\"jlrigjkskyrioovz\",\"endpoints\":[{\"domainName\":\"waabzmifrygzn\",\"endpointDetails\":[{}]},{\"domainName\":\"ri\",\"endpointDetails\":[{}]}],\"provisioningState\":\"Deleting\"},\"etag\":\"opxlhslnelxieixy\",\"id\":\"llxecwc\",\"name\":\"ojphslhc\",\"type\":\"wjutifdwfmv\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -32,9 +32,9 @@ public void testListOutboundNetworkDependenciesEndpoints() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); PagedIterable response = manager.clusters() - .listOutboundNetworkDependenciesEndpoints("ysi", "sgqcwdho", com.azure.core.util.Context.NONE); + .listOutboundNetworkDependenciesEndpoints("nptgoeiybba", "pfhvfslk", com.azure.core.util.Context.NONE); - Assertions.assertEquals("tmcdzsufcohd", response.iterator().next().category()); - Assertions.assertEquals("mcmuapc", response.iterator().next().endpoints().get(0).domainName()); + Assertions.assertEquals("jlrigjkskyrioovz", response.iterator().next().category()); + Assertions.assertEquals("waabzmifrygzn", response.iterator().next().endpoints().get(0).domainName()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersListSkusByResourceMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersListSkusByResourceMockTests.java index 781c659dd4d7..06a58ba5be70 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersListSkusByResourceMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersListSkusByResourceMockTests.java @@ -25,7 +25,7 @@ public final class ClustersListSkusByResourceMockTests { @Test public void testListSkusByResource() throws Exception { String responseStr - = "{\"value\":[{\"resourceType\":\"pvpbdbzqgqqiheds\",\"sku\":{\"name\":\"Standard_E8as_v4+1TB_PS\",\"capacity\":1770973346,\"tier\":\"Basic\"},\"capacity\":{\"scaleType\":\"manual\",\"minimum\":649222469,\"maximum\":1468707412,\"default\":1456487398}}]}"; + = "{\"value\":[{\"resourceType\":\"qglcfhmlrqryxynq\",\"sku\":{\"name\":\"Standard_D14_v2\",\"capacity\":69570650,\"tier\":\"Standard\"},\"capacity\":{\"scaleType\":\"automatic\",\"minimum\":347579095,\"maximum\":786397425,\"default\":432652683}}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -35,15 +35,15 @@ public void testListSkusByResource() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); PagedIterable response - = manager.clusters().listSkusByResource("zfjltfvnzcyjto", "p", com.azure.core.util.Context.NONE); + = manager.clusters().listSkusByResource("wgnyfusfzsvtui", "zh", com.azure.core.util.Context.NONE); - Assertions.assertEquals("pvpbdbzqgqqiheds", response.iterator().next().resourceType()); - Assertions.assertEquals(AzureSkuName.STANDARD_E8AS_V4_1TB_PS, response.iterator().next().sku().name()); - Assertions.assertEquals(1770973346, response.iterator().next().sku().capacity()); - Assertions.assertEquals(AzureSkuTier.BASIC, response.iterator().next().sku().tier()); - Assertions.assertEquals(AzureScaleType.MANUAL, response.iterator().next().capacity().scaleType()); - Assertions.assertEquals(649222469, response.iterator().next().capacity().minimum()); - Assertions.assertEquals(1468707412, response.iterator().next().capacity().maximum()); - Assertions.assertEquals(1456487398, response.iterator().next().capacity().defaultProperty()); + Assertions.assertEquals("qglcfhmlrqryxynq", response.iterator().next().resourceType()); + Assertions.assertEquals(AzureSkuName.STANDARD_D14_V2, response.iterator().next().sku().name()); + Assertions.assertEquals(69570650, response.iterator().next().sku().capacity()); + Assertions.assertEquals(AzureSkuTier.STANDARD, response.iterator().next().sku().tier()); + Assertions.assertEquals(AzureScaleType.AUTOMATIC, response.iterator().next().capacity().scaleType()); + Assertions.assertEquals(347579095, response.iterator().next().capacity().minimum()); + Assertions.assertEquals(786397425, response.iterator().next().capacity().maximum()); + Assertions.assertEquals(432652683, response.iterator().next().capacity().defaultProperty()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersListSkusMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersListSkusMockTests.java index 5466277f8ae9..2d75b5701cdb 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersListSkusMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersListSkusMockTests.java @@ -21,7 +21,7 @@ public final class ClustersListSkusMockTests { @Test public void testListSkus() throws Exception { String responseStr - = "{\"value\":[{\"resourceType\":\"unqndyfpchrqb\",\"name\":\"jrcg\",\"tier\":\"ydcwboxjumv\",\"locations\":[\"lihrraiouaubr\",\"tloqxfuojrn\"],\"locationInfo\":[{\"location\":\"l\",\"zones\":[\"asccbiui\",\"zdlyjdfqw\"],\"zoneDetails\":[{\"name\":[\"ufdvruz\",\"lzo\",\"hpc\",\"fnmdxotn\"],\"capabilities\":[{}]},{\"name\":[\"geyzihgrkyuiz\",\"bsnmfpph\",\"jee\",\"yhyhsgzfczb\"],\"capabilities\":[{}]},{\"name\":[\"beglqg\",\"eohibet\",\"luan\"],\"capabilities\":[{},{},{}]}]},{\"location\":\"fxeeebtijvacvbm\",\"zones\":[\"qqxlajr\",\"wxacevehj\"],\"zoneDetails\":[{\"name\":[\"afgaoqlt\",\"aeylinm\"],\"capabilities\":[{},{},{}]},{\"name\":[\"r\",\"gh\",\"iypoqeyhlqhykprl\",\"yznuciqd\"],\"capabilities\":[{}]}]}],\"restrictions\":[\"dataitdfuxtyasiib\",\"dataiybnnustgnljhnmg\"]}]}"; + = "{\"value\":[{\"resourceType\":\"lm\",\"name\":\"uapcvhdbevwqqxe\",\"tier\":\"ko\",\"locations\":[\"inkfkbgbz\",\"owxeqocljmy\",\"vkzqk\",\"jeokbzefezrxccz\"],\"locationInfo\":[{\"location\":\"leipqx\",\"zones\":[\"vz\"],\"zoneDetails\":[{\"name\":[\"fbzdixzmqpnoda\",\"opqhewjptmc\",\"sbostzel\"],\"capabilities\":[{}]}]},{\"location\":\"atutmzlbiojlvfhr\",\"zones\":[\"neqvcwwyyurmo\"],\"zoneDetails\":[{\"name\":[\"prsnmokayzejn\",\"lbkpb\"],\"capabilities\":[{},{}]}]},{\"location\":\"piljhahzvech\",\"zones\":[\"nwieholewjw\",\"uubw\",\"fqsfa\"],\"zoneDetails\":[{\"name\":[\"e\"],\"capabilities\":[{}]},{\"name\":[\"x\"],\"capabilities\":[{},{},{},{}]},{\"name\":[\"apjwogqqnobpudcd\"],\"capabilities\":[{},{}]},{\"name\":[\"pwyawbz\",\"sqbuc\"],\"capabilities\":[{},{},{}]}]}],\"restrictions\":[\"dataexaoguya\",\"datap\"]}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersMigrateMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersMigrateMockTests.java index a3d939f2682d..8be5b04f5b69 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersMigrateMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersMigrateMockTests.java @@ -29,7 +29,7 @@ public void testMigrate() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); manager.clusters() - .migrate("kgfmocwahpq", "atjeaahh", new ClusterMigrateRequest().withClusterResourceId("jhhn"), + .migrate("pypqtgsfj", "cbslhhx", new ClusterMigrateRequest().withClusterResourceId("db"), com.azure.core.util.Context.NONE); } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersRemoveCalloutPolicyMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersRemoveCalloutPolicyMockTests.java new file mode 100644 index 000000000000..c3a3433d6384 --- /dev/null +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersRemoveCalloutPolicyMockTests.java @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.kusto.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.kusto.KustoManager; +import com.azure.resourcemanager.kusto.models.CalloutPolicyToRemove; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class ClustersRemoveCalloutPolicyMockTests { + @Test + public void testRemoveCalloutPolicy() throws Exception { + String responseStr = "{}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + KustoManager manager = KustoManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureEnvironment.AZURE)); + + manager.clusters() + .removeCalloutPolicy("aivmxyasflvgs", "zwywako", + new CalloutPolicyToRemove().withCalloutId("knsmjblmljhlnymz"), com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersRemoveLanguageExtensionsMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersRemoveLanguageExtensionsMockTests.java index 0ad75e6c1e66..ac5304cb92cc 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersRemoveLanguageExtensionsMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersRemoveLanguageExtensionsMockTests.java @@ -33,17 +33,14 @@ public void testRemoveLanguageExtensions() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); manager.clusters() - .removeLanguageExtensions("pbzpcpiljhahz", "echndbnwieholew", + .removeLanguageExtensions("embnkbw", "qvxkd", new LanguageExtensionsList().withValue(Arrays.asList( new LanguageExtensionInner().withLanguageExtensionName(LanguageExtensionName.PYTHON) .withLanguageExtensionImageName(LanguageExtensionImageName.PYTHON3_10_8) - .withLanguageExtensionCustomImageName("fqsfa"), - new LanguageExtensionInner().withLanguageExtensionName(LanguageExtensionName.R) - .withLanguageExtensionImageName(LanguageExtensionImageName.PYTHON3_10_8_DL) - .withLanguageExtensionCustomImageName("rrqwexjk"), + .withLanguageExtensionCustomImageName("tswbzuwfmd"), new LanguageExtensionInner().withLanguageExtensionName(LanguageExtensionName.PYTHON) - .withLanguageExtensionImageName(LanguageExtensionImageName.PYTHON3_6_5) - .withLanguageExtensionCustomImageName("wogqqnobpudcdab"))), + .withLanguageExtensionImageName(LanguageExtensionImageName.PYTHON3_10_8_DL) + .withLanguageExtensionCustomImageName("izvcjfe"))), com.azure.core.util.Context.NONE); } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersStartMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersStartMockTests.java index 11fbea06a0ea..cc527f5f92bf 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersStartMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersStartMockTests.java @@ -27,7 +27,7 @@ public void testStart() throws Exception { .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), new AzureProfile("", "", AzureEnvironment.AZURE)); - manager.clusters().start("uxakjsqzhzbezk", "imsidxasicddyvvj", com.azure.core.util.Context.NONE); + manager.clusters().start("tfgle", "dmdqb", com.azure.core.util.Context.NONE); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersStopMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersStopMockTests.java index 29bfc44690fa..0f633dcb1c38 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersStopMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ClustersStopMockTests.java @@ -27,7 +27,7 @@ public void testStop() throws Exception { .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), new AzureProfile("", "", AzureEnvironment.AZURE)); - manager.clusters().stop("e", "y", com.azure.core.util.Context.NONE); + manager.clusters().stop("sawddjibabxvi", "itvtzeexavo", com.azure.core.util.Context.NONE); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/CosmosDbDataConnectionPropertiesTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/CosmosDbDataConnectionPropertiesTests.java index 021ae8224c86..6eeaecc841cd 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/CosmosDbDataConnectionPropertiesTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/CosmosDbDataConnectionPropertiesTests.java @@ -13,33 +13,33 @@ public final class CosmosDbDataConnectionPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { CosmosDbDataConnectionProperties model = BinaryData.fromString( - "{\"tableName\":\"nhdwdigumbnra\",\"mappingRuleName\":\"zzp\",\"managedIdentityResourceId\":\"jazysdzhezwwvaiq\",\"managedIdentityObjectId\":\"vv\",\"cosmosDbAccountResourceId\":\"onkp\",\"cosmosDbDatabase\":\"hqyikvy\",\"cosmosDbContainer\":\"auy\",\"retrievalStartDate\":\"2021-04-05T06:39:57Z\",\"provisioningState\":\"Succeeded\"}") + "{\"tableName\":\"xvd\",\"mappingRuleName\":\"fwafqrouda\",\"managedIdentityResourceId\":\"pavehhr\",\"managedIdentityObjectId\":\"bunzozudh\",\"cosmosDbAccountResourceId\":\"xg\",\"cosmosDbDatabase\":\"moy\",\"cosmosDbContainer\":\"cdyuibhmfdnbzyd\",\"retrievalStartDate\":\"2021-04-24T12:16:29Z\",\"provisioningState\":\"Creating\"}") .toObject(CosmosDbDataConnectionProperties.class); - Assertions.assertEquals("nhdwdigumbnra", model.tableName()); - Assertions.assertEquals("zzp", model.mappingRuleName()); - Assertions.assertEquals("jazysdzhezwwvaiq", model.managedIdentityResourceId()); - Assertions.assertEquals("onkp", model.cosmosDbAccountResourceId()); - Assertions.assertEquals("hqyikvy", model.cosmosDbDatabase()); - Assertions.assertEquals("auy", model.cosmosDbContainer()); - Assertions.assertEquals(OffsetDateTime.parse("2021-04-05T06:39:57Z"), model.retrievalStartDate()); + Assertions.assertEquals("xvd", model.tableName()); + Assertions.assertEquals("fwafqrouda", model.mappingRuleName()); + Assertions.assertEquals("pavehhr", model.managedIdentityResourceId()); + Assertions.assertEquals("xg", model.cosmosDbAccountResourceId()); + Assertions.assertEquals("moy", model.cosmosDbDatabase()); + Assertions.assertEquals("cdyuibhmfdnbzyd", model.cosmosDbContainer()); + Assertions.assertEquals(OffsetDateTime.parse("2021-04-24T12:16:29Z"), model.retrievalStartDate()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - CosmosDbDataConnectionProperties model = new CosmosDbDataConnectionProperties().withTableName("nhdwdigumbnra") - .withMappingRuleName("zzp") - .withManagedIdentityResourceId("jazysdzhezwwvaiq") - .withCosmosDbAccountResourceId("onkp") - .withCosmosDbDatabase("hqyikvy") - .withCosmosDbContainer("auy") - .withRetrievalStartDate(OffsetDateTime.parse("2021-04-05T06:39:57Z")); + CosmosDbDataConnectionProperties model = new CosmosDbDataConnectionProperties().withTableName("xvd") + .withMappingRuleName("fwafqrouda") + .withManagedIdentityResourceId("pavehhr") + .withCosmosDbAccountResourceId("xg") + .withCosmosDbDatabase("moy") + .withCosmosDbContainer("cdyuibhmfdnbzyd") + .withRetrievalStartDate(OffsetDateTime.parse("2021-04-24T12:16:29Z")); model = BinaryData.fromObject(model).toObject(CosmosDbDataConnectionProperties.class); - Assertions.assertEquals("nhdwdigumbnra", model.tableName()); - Assertions.assertEquals("zzp", model.mappingRuleName()); - Assertions.assertEquals("jazysdzhezwwvaiq", model.managedIdentityResourceId()); - Assertions.assertEquals("onkp", model.cosmosDbAccountResourceId()); - Assertions.assertEquals("hqyikvy", model.cosmosDbDatabase()); - Assertions.assertEquals("auy", model.cosmosDbContainer()); - Assertions.assertEquals(OffsetDateTime.parse("2021-04-05T06:39:57Z"), model.retrievalStartDate()); + Assertions.assertEquals("xvd", model.tableName()); + Assertions.assertEquals("fwafqrouda", model.mappingRuleName()); + Assertions.assertEquals("pavehhr", model.managedIdentityResourceId()); + Assertions.assertEquals("xg", model.cosmosDbAccountResourceId()); + Assertions.assertEquals("moy", model.cosmosDbDatabase()); + Assertions.assertEquals("cdyuibhmfdnbzyd", model.cosmosDbContainer()); + Assertions.assertEquals(OffsetDateTime.parse("2021-04-24T12:16:29Z"), model.retrievalStartDate()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/CosmosDbDataConnectionTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/CosmosDbDataConnectionTests.java index 54ee347e662a..02c7070019b9 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/CosmosDbDataConnectionTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/CosmosDbDataConnectionTests.java @@ -13,36 +13,36 @@ public final class CosmosDbDataConnectionTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { CosmosDbDataConnection model = BinaryData.fromString( - "{\"kind\":\"CosmosDb\",\"properties\":{\"tableName\":\"uhdqazk\",\"mappingRuleName\":\"gg\",\"managedIdentityResourceId\":\"wpijrajci\",\"managedIdentityObjectId\":\"mghfcfiwrxgkne\",\"cosmosDbAccountResourceId\":\"vyi\",\"cosmosDbDatabase\":\"zqodfvpgshox\",\"cosmosDbContainer\":\"sgbpfgzdjtx\",\"retrievalStartDate\":\"2020-12-23T06:59:29Z\",\"provisioningState\":\"Creating\"},\"location\":\"v\",\"id\":\"aqvlgafcqusr\",\"name\":\"vetnwsdtutn\",\"type\":\"lduycv\"}") + "{\"kind\":\"CosmosDb\",\"properties\":{\"tableName\":\"xgketwz\",\"mappingRuleName\":\"zjhfjmhvv\",\"managedIdentityResourceId\":\"uvgp\",\"managedIdentityObjectId\":\"neqsxvmh\",\"cosmosDbAccountResourceId\":\"buzjyih\",\"cosmosDbDatabase\":\"as\",\"cosmosDbContainer\":\"hudypohyuemsl\",\"retrievalStartDate\":\"2021-08-05T10:43:49Z\",\"provisioningState\":\"Running\"},\"location\":\"pfoobr\",\"id\":\"ttymsjny\",\"name\":\"qdnfwqzdz\",\"type\":\"tilaxh\"}") .toObject(CosmosDbDataConnection.class); - Assertions.assertEquals("v", model.location()); - Assertions.assertEquals("uhdqazk", model.tableName()); - Assertions.assertEquals("gg", model.mappingRuleName()); - Assertions.assertEquals("wpijrajci", model.managedIdentityResourceId()); - Assertions.assertEquals("vyi", model.cosmosDbAccountResourceId()); - Assertions.assertEquals("zqodfvpgshox", model.cosmosDbDatabase()); - Assertions.assertEquals("sgbpfgzdjtx", model.cosmosDbContainer()); - Assertions.assertEquals(OffsetDateTime.parse("2020-12-23T06:59:29Z"), model.retrievalStartDate()); + Assertions.assertEquals("pfoobr", model.location()); + Assertions.assertEquals("xgketwz", model.tableName()); + Assertions.assertEquals("zjhfjmhvv", model.mappingRuleName()); + Assertions.assertEquals("uvgp", model.managedIdentityResourceId()); + Assertions.assertEquals("buzjyih", model.cosmosDbAccountResourceId()); + Assertions.assertEquals("as", model.cosmosDbDatabase()); + Assertions.assertEquals("hudypohyuemsl", model.cosmosDbContainer()); + Assertions.assertEquals(OffsetDateTime.parse("2021-08-05T10:43:49Z"), model.retrievalStartDate()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - CosmosDbDataConnection model = new CosmosDbDataConnection().withLocation("v") - .withTableName("uhdqazk") - .withMappingRuleName("gg") - .withManagedIdentityResourceId("wpijrajci") - .withCosmosDbAccountResourceId("vyi") - .withCosmosDbDatabase("zqodfvpgshox") - .withCosmosDbContainer("sgbpfgzdjtx") - .withRetrievalStartDate(OffsetDateTime.parse("2020-12-23T06:59:29Z")); + CosmosDbDataConnection model = new CosmosDbDataConnection().withLocation("pfoobr") + .withTableName("xgketwz") + .withMappingRuleName("zjhfjmhvv") + .withManagedIdentityResourceId("uvgp") + .withCosmosDbAccountResourceId("buzjyih") + .withCosmosDbDatabase("as") + .withCosmosDbContainer("hudypohyuemsl") + .withRetrievalStartDate(OffsetDateTime.parse("2021-08-05T10:43:49Z")); model = BinaryData.fromObject(model).toObject(CosmosDbDataConnection.class); - Assertions.assertEquals("v", model.location()); - Assertions.assertEquals("uhdqazk", model.tableName()); - Assertions.assertEquals("gg", model.mappingRuleName()); - Assertions.assertEquals("wpijrajci", model.managedIdentityResourceId()); - Assertions.assertEquals("vyi", model.cosmosDbAccountResourceId()); - Assertions.assertEquals("zqodfvpgshox", model.cosmosDbDatabase()); - Assertions.assertEquals("sgbpfgzdjtx", model.cosmosDbContainer()); - Assertions.assertEquals(OffsetDateTime.parse("2020-12-23T06:59:29Z"), model.retrievalStartDate()); + Assertions.assertEquals("pfoobr", model.location()); + Assertions.assertEquals("xgketwz", model.tableName()); + Assertions.assertEquals("zjhfjmhvv", model.mappingRuleName()); + Assertions.assertEquals("uvgp", model.managedIdentityResourceId()); + Assertions.assertEquals("buzjyih", model.cosmosDbAccountResourceId()); + Assertions.assertEquals("as", model.cosmosDbDatabase()); + Assertions.assertEquals("hudypohyuemsl", model.cosmosDbContainer()); + Assertions.assertEquals(OffsetDateTime.parse("2021-08-05T10:43:49Z"), model.retrievalStartDate()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionCheckNameRequestTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionCheckNameRequestTests.java index 4f6ba4ccfb64..586a8d82129c 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionCheckNameRequestTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionCheckNameRequestTests.java @@ -12,14 +12,14 @@ public final class DataConnectionCheckNameRequestTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { DataConnectionCheckNameRequest model - = BinaryData.fromString("{\"name\":\"j\"}").toObject(DataConnectionCheckNameRequest.class); - Assertions.assertEquals("j", model.name()); + = BinaryData.fromString("{\"name\":\"fomiloxgg\"}").toObject(DataConnectionCheckNameRequest.class); + Assertions.assertEquals("fomiloxgg", model.name()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - DataConnectionCheckNameRequest model = new DataConnectionCheckNameRequest().withName("j"); + DataConnectionCheckNameRequest model = new DataConnectionCheckNameRequest().withName("fomiloxgg"); model = BinaryData.fromObject(model).toObject(DataConnectionCheckNameRequest.class); - Assertions.assertEquals("j", model.name()); + Assertions.assertEquals("fomiloxgg", model.name()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionInnerTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionInnerTests.java index 70c23b915196..3810b833f0e6 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionInnerTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionInnerTests.java @@ -12,15 +12,15 @@ public final class DataConnectionInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { DataConnectionInner model = BinaryData.fromString( - "{\"kind\":\"DataConnection\",\"location\":\"zbrhubskhudyg\",\"id\":\"ookk\",\"name\":\"fqjbvleo\",\"type\":\"fmluiqtqzfavyvn\"}") + "{\"kind\":\"DataConnection\",\"location\":\"sutujba\",\"id\":\"pjuohminyfl\",\"name\":\"orwmduvwpklv\",\"type\":\"w\"}") .toObject(DataConnectionInner.class); - Assertions.assertEquals("zbrhubskhudyg", model.location()); + Assertions.assertEquals("sutujba", model.location()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - DataConnectionInner model = new DataConnectionInner().withLocation("zbrhubskhudyg"); + DataConnectionInner model = new DataConnectionInner().withLocation("sutujba"); model = BinaryData.fromObject(model).toObject(DataConnectionInner.class); - Assertions.assertEquals("zbrhubskhudyg", model.location()); + Assertions.assertEquals("sutujba", model.location()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionListResultTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionListResultTests.java index b8d1ff22c436..cc3db3b024fe 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionListResultTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionListResultTests.java @@ -14,18 +14,18 @@ public final class DataConnectionListResultTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { DataConnectionListResult model = BinaryData.fromString( - "{\"value\":[{\"kind\":\"DataConnection\",\"location\":\"ehvbbxurip\",\"id\":\"tfnhtbaxkgxywr\",\"name\":\"kpyklyhp\",\"type\":\"uodpv\"},{\"kind\":\"DataConnection\",\"location\":\"udlgzibthostgkts\",\"id\":\"vdxec\",\"name\":\"zedqbcvhzlhplo\",\"type\":\"qkdlw\"},{\"kind\":\"DataConnection\",\"location\":\"fbumlkx\",\"id\":\"rqjfsmlm\",\"name\":\"txhwgfws\",\"type\":\"tawc\"}]}") + "{\"value\":[{\"kind\":\"DataConnection\",\"location\":\"bar\",\"id\":\"euayjkqabqgzsles\",\"name\":\"cbhernntiewdj\",\"type\":\"vbquwr\"},{\"kind\":\"DataConnection\",\"location\":\"hwagohbuffkmrqe\",\"id\":\"vvhmxtdrj\",\"name\":\"utacoe\",\"type\":\"jvewzcjznmwcp\"},{\"kind\":\"DataConnection\",\"location\":\"uaadraufactkahzo\",\"id\":\"ajjziuxxpshne\",\"name\":\"kulfg\",\"type\":\"lqubkwdlen\"}]}") .toObject(DataConnectionListResult.class); - Assertions.assertEquals("ehvbbxurip", model.value().get(0).location()); + Assertions.assertEquals("bar", model.value().get(0).location()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - DataConnectionListResult model = new DataConnectionListResult() - .withValue(Arrays.asList(new DataConnectionInner().withLocation("ehvbbxurip"), - new DataConnectionInner().withLocation("udlgzibthostgkts"), - new DataConnectionInner().withLocation("fbumlkx"))); + DataConnectionListResult model + = new DataConnectionListResult().withValue(Arrays.asList(new DataConnectionInner().withLocation("bar"), + new DataConnectionInner().withLocation("hwagohbuffkmrqe"), + new DataConnectionInner().withLocation("uaadraufactkahzo"))); model = BinaryData.fromObject(model).toObject(DataConnectionListResult.class); - Assertions.assertEquals("ehvbbxurip", model.value().get(0).location()); + Assertions.assertEquals("bar", model.value().get(0).location()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionValidationInnerTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionValidationInnerTests.java index c6fb77e7784f..3760240eb66c 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionValidationInnerTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionValidationInnerTests.java @@ -13,18 +13,18 @@ public final class DataConnectionValidationInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { DataConnectionValidationInner model = BinaryData.fromString( - "{\"dataConnectionName\":\"ybar\",\"properties\":{\"kind\":\"DataConnection\",\"location\":\"ayjkqa\",\"id\":\"qgzsles\",\"name\":\"cbhernntiewdj\",\"type\":\"vbquwr\"}}") + "{\"dataConnectionName\":\"gdxpg\",\"properties\":{\"kind\":\"DataConnection\",\"location\":\"hiszepnnbjcrxgib\",\"id\":\"daxconfozauorsuk\",\"name\":\"kwbqplhlvnuu\",\"type\":\"pzlrphw\"}}") .toObject(DataConnectionValidationInner.class); - Assertions.assertEquals("ybar", model.dataConnectionName()); - Assertions.assertEquals("ayjkqa", model.properties().location()); + Assertions.assertEquals("gdxpg", model.dataConnectionName()); + Assertions.assertEquals("hiszepnnbjcrxgib", model.properties().location()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - DataConnectionValidationInner model = new DataConnectionValidationInner().withDataConnectionName("ybar") - .withProperties(new DataConnectionInner().withLocation("ayjkqa")); + DataConnectionValidationInner model = new DataConnectionValidationInner().withDataConnectionName("gdxpg") + .withProperties(new DataConnectionInner().withLocation("hiszepnnbjcrxgib")); model = BinaryData.fromObject(model).toObject(DataConnectionValidationInner.class); - Assertions.assertEquals("ybar", model.dataConnectionName()); - Assertions.assertEquals("ayjkqa", model.properties().location()); + Assertions.assertEquals("gdxpg", model.dataConnectionName()); + Assertions.assertEquals("hiszepnnbjcrxgib", model.properties().location()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionValidationListResultInnerTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionValidationListResultInnerTests.java index 0dc668ccdbb8..b529f69e5aa1 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionValidationListResultInnerTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionValidationListResultInnerTests.java @@ -14,19 +14,18 @@ public final class DataConnectionValidationListResultInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { DataConnectionValidationListResultInner model = BinaryData.fromString( - "{\"value\":[{\"errorMessage\":\"agohbuff\"},{\"errorMessage\":\"rqemvvhmxt\"},{\"errorMessage\":\"jfutacoebj\"},{\"errorMessage\":\"wzcjznmwcpmgua\"}]}") + "{\"value\":[{\"errorMessage\":\"dweyuqdunv\"},{\"errorMessage\":\"nrwrbiork\"},{\"errorMessage\":\"lywjhh\"}]}") .toObject(DataConnectionValidationListResultInner.class); - Assertions.assertEquals("agohbuff", model.value().get(0).errorMessage()); + Assertions.assertEquals("dweyuqdunv", model.value().get(0).errorMessage()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { DataConnectionValidationListResultInner model = new DataConnectionValidationListResultInner() - .withValue(Arrays.asList(new DataConnectionValidationResult().withErrorMessage("agohbuff"), - new DataConnectionValidationResult().withErrorMessage("rqemvvhmxt"), - new DataConnectionValidationResult().withErrorMessage("jfutacoebj"), - new DataConnectionValidationResult().withErrorMessage("wzcjznmwcpmgua"))); + .withValue(Arrays.asList(new DataConnectionValidationResult().withErrorMessage("dweyuqdunv"), + new DataConnectionValidationResult().withErrorMessage("nrwrbiork"), + new DataConnectionValidationResult().withErrorMessage("lywjhh"))); model = BinaryData.fromObject(model).toObject(DataConnectionValidationListResultInner.class); - Assertions.assertEquals("agohbuff", model.value().get(0).errorMessage()); + Assertions.assertEquals("dweyuqdunv", model.value().get(0).errorMessage()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionValidationResultTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionValidationResultTests.java index 7eaec2aa5a6e..e22db89454d9 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionValidationResultTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionValidationResultTests.java @@ -11,15 +11,15 @@ public final class DataConnectionValidationResultTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - DataConnectionValidationResult model = BinaryData.fromString("{\"errorMessage\":\"raufactkahzova\"}") - .toObject(DataConnectionValidationResult.class); - Assertions.assertEquals("raufactkahzova", model.errorMessage()); + DataConnectionValidationResult model + = BinaryData.fromString("{\"errorMessage\":\"nhxmsi\"}").toObject(DataConnectionValidationResult.class); + Assertions.assertEquals("nhxmsi", model.errorMessage()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - DataConnectionValidationResult model = new DataConnectionValidationResult().withErrorMessage("raufactkahzova"); + DataConnectionValidationResult model = new DataConnectionValidationResult().withErrorMessage("nhxmsi"); model = BinaryData.fromObject(model).toObject(DataConnectionValidationResult.class); - Assertions.assertEquals("raufactkahzova", model.errorMessage()); + Assertions.assertEquals("nhxmsi", model.errorMessage()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionsCheckNameAvailabilityWithResponseMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionsCheckNameAvailabilityWithResponseMockTests.java index 7e6d19e112d5..05656428963e 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionsCheckNameAvailabilityWithResponseMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionsCheckNameAvailabilityWithResponseMockTests.java @@ -23,7 +23,7 @@ public final class DataConnectionsCheckNameAvailabilityWithResponseMockTests { @Test public void testCheckNameAvailabilityWithResponse() throws Exception { String responseStr - = "{\"nameAvailable\":false,\"name\":\"qinfszpyglqd\",\"message\":\"rjzralcx\",\"reason\":\"AlreadyExists\"}"; + = "{\"nameAvailable\":true,\"name\":\"xiwkgfbql\",\"message\":\"qkhychocok\",\"reason\":\"Invalid\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -33,13 +33,13 @@ public void testCheckNameAvailabilityWithResponse() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); CheckNameResult response = manager.dataConnections() - .checkNameAvailabilityWithResponse("czhcoeocnh", "qr", "ttjzcfyjzpt", - new DataConnectionCheckNameRequest().withName("rl"), com.azure.core.util.Context.NONE) + .checkNameAvailabilityWithResponse("awmo", "ia", "cz", + new DataConnectionCheckNameRequest().withName("vodrrslblxydkxr"), com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals(false, response.nameAvailable()); - Assertions.assertEquals("qinfszpyglqd", response.name()); - Assertions.assertEquals("rjzralcx", response.message()); - Assertions.assertEquals(Reason.ALREADY_EXISTS, response.reason()); + Assertions.assertEquals(true, response.nameAvailable()); + Assertions.assertEquals("xiwkgfbql", response.name()); + Assertions.assertEquals("qkhychocok", response.message()); + Assertions.assertEquals(Reason.INVALID, response.reason()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionsCreateOrUpdateMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionsCreateOrUpdateMockTests.java index c21273f683b4..4dac28acb343 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionsCreateOrUpdateMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionsCreateOrUpdateMockTests.java @@ -22,7 +22,7 @@ public final class DataConnectionsCreateOrUpdateMockTests { @Test public void testCreateOrUpdate() throws Exception { String responseStr - = "{\"kind\":\"DataConnection\",\"location\":\"ddwwnlzafwxudgnh\",\"id\":\"ookrtalvnbw\",\"name\":\"pbeme\",\"type\":\"uclvdjj\"}"; + = "{\"kind\":\"DataConnection\",\"location\":\"tnuwjtkschgc\",\"id\":\"qyhleseyq\",\"name\":\"hvyeldotj\",\"type\":\"dkwisw\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -32,9 +32,9 @@ public void testCreateOrUpdate() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); DataConnection response = manager.dataConnections() - .createOrUpdate("bscm", "lzijiufehgmvflnw", "v", "kxrerlniylylyfwx", - new DataConnectionInner().withLocation("tgqztwhghmup"), com.azure.core.util.Context.NONE); + .createOrUpdate("scgdu", "sioycblevpmcl", "jy", "kyxl", + new DataConnectionInner().withLocation("sjgkzzltafh"), com.azure.core.util.Context.NONE); - Assertions.assertEquals("ddwwnlzafwxudgnh", response.location()); + Assertions.assertEquals("tnuwjtkschgc", response.location()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionsDataConnectionValidationMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionsDataConnectionValidationMockTests.java index 6109410f4c45..d1ba3089c3e3 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionsDataConnectionValidationMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionsDataConnectionValidationMockTests.java @@ -23,7 +23,7 @@ public final class DataConnectionsDataConnectionValidationMockTests { @Test public void testDataConnectionValidation() throws Exception { String responseStr - = "{\"value\":[{\"errorMessage\":\"ewnf\"},{\"errorMessage\":\"hhhqosm\"},{\"errorMessage\":\"jkutycyarnr\"},{\"errorMessage\":\"hguabzoghktdp\"}]}"; + = "{\"value\":[{\"errorMessage\":\"tlghwzhomew\"},{\"errorMessage\":\"s\"},{\"errorMessage\":\"iuh\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -33,11 +33,11 @@ public void testDataConnectionValidation() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); DataConnectionValidationListResult response = manager.dataConnections() - .dataConnectionValidation("aan", "ggiycwkdtaawxwf", "ka", - new DataConnectionValidationInner().withDataConnectionName("rrqmbzmqk") - .withProperties(new DataConnectionInner().withLocation("bnxwbjsidbirkf")), + .dataConnectionValidation("nlzafwxudgnh", "ookrtalvnbw", "pbeme", + new DataConnectionValidationInner().withDataConnectionName("clvdjjukyrdnqod") + .withProperties(new DataConnectionInner().withLocation("h")), com.azure.core.util.Context.NONE); - Assertions.assertEquals("ewnf", response.value().get(0).errorMessage()); + Assertions.assertEquals("tlghwzhomew", response.value().get(0).errorMessage()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionsDeleteMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionsDeleteMockTests.java index 5cbf257b98c7..d25896cd229b 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionsDeleteMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionsDeleteMockTests.java @@ -27,9 +27,7 @@ public void testDelete() throws Exception { .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), new AzureProfile("", "", AzureEnvironment.AZURE)); - manager.dataConnections() - .delete("vodrrslblxydkxr", "vvbxiwkgfbqljnq", "hychocokuleh", "rqlrqffawe", - com.azure.core.util.Context.NONE); + manager.dataConnections().delete("djus", "br", "eqy", "kceysfaqegplw", com.azure.core.util.Context.NONE); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionsGetWithResponseMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionsGetWithResponseMockTests.java index 166f8fc2c8d1..66620588839e 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionsGetWithResponseMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionsGetWithResponseMockTests.java @@ -21,7 +21,7 @@ public final class DataConnectionsGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"kind\":\"DataConnection\",\"location\":\"hqxu\",\"id\":\"yvca\",\"name\":\"oyvivbsiz\",\"type\":\"sjsz\"}"; + = "{\"kind\":\"DataConnection\",\"location\":\"xk\",\"id\":\"y\",\"name\":\"jjk\",\"type\":\"ajb\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -31,9 +31,9 @@ public void testGetWithResponse() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); DataConnection response = manager.dataConnections() - .getWithResponse("yypsjoqc", "enky", "fq", "vsqxfxjelgcmpzqj", com.azure.core.util.Context.NONE) + .getWithResponse("hurql", "qffawey", "rkphyjdxr", "vjuqdbrxmrgchb", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("hqxu", response.location()); + Assertions.assertEquals("xk", response.location()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionsListByDatabaseMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionsListByDatabaseMockTests.java index 5becbc6418dc..aabbbe5dfe40 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionsListByDatabaseMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionsListByDatabaseMockTests.java @@ -22,7 +22,7 @@ public final class DataConnectionsListByDatabaseMockTests { @Test public void testListByDatabase() throws Exception { String responseStr - = "{\"value\":[{\"kind\":\"DataConnection\",\"location\":\"xyivpinbm\",\"id\":\"wbjijkgq\",\"name\":\"nhmbkez\",\"type\":\"jauj\"}]}"; + = "{\"value\":[{\"kind\":\"DataConnection\",\"location\":\"mupgxy\",\"id\":\"tcdxabbujftaben\",\"name\":\"bklqpxz\",\"type\":\"cafeddw\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -32,8 +32,8 @@ public void testListByDatabase() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); PagedIterable response = manager.dataConnections() - .listByDatabase("aolnjpnnbmjk", "ibjgsjjxxahm", "nadzyq", com.azure.core.util.Context.NONE); + .listByDatabase("v", "kxrerlniylylyfwx", "utgqztwh", com.azure.core.util.Context.NONE); - Assertions.assertEquals("xyivpinbm", response.iterator().next().location()); + Assertions.assertEquals("mupgxy", response.iterator().next().location()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionsUpdateMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionsUpdateMockTests.java index bb07ad01dcfe..b46edb5756af 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionsUpdateMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DataConnectionsUpdateMockTests.java @@ -22,7 +22,7 @@ public final class DataConnectionsUpdateMockTests { @Test public void testUpdate() throws Exception { String responseStr - = "{\"kind\":\"DataConnection\",\"location\":\"iuh\",\"id\":\"awmo\",\"name\":\"ia\",\"type\":\"cz\"}"; + = "{\"kind\":\"DataConnection\",\"location\":\"kfaoytehq\",\"id\":\"uvjmv\",\"name\":\"mtdwcky\",\"type\":\"roejnndl\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -32,9 +32,9 @@ public void testUpdate() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); DataConnection response = manager.dataConnections() - .update("kyrdnqodx", "hhxhq", "aqnvzoqgyipemchg", "v", new DataConnectionInner().withLocation("zuejd"), - com.azure.core.util.Context.NONE); + .update("kukjtasb", "wispkxk", "txfkndlqvt", "knvgmmbugtywat", + new DataConnectionInner().withLocation("aqkue"), com.azure.core.util.Context.NONE); - Assertions.assertEquals("iuh", response.location()); + Assertions.assertEquals("kfaoytehq", response.location()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabaseInnerTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabaseInnerTests.java index 5ce9116426d9..b84520e2d411 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabaseInnerTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabaseInnerTests.java @@ -12,15 +12,15 @@ public final class DatabaseInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { DatabaseInner model = BinaryData.fromString( - "{\"kind\":\"Database\",\"location\":\"nkww\",\"id\":\"pp\",\"name\":\"flcxoga\",\"type\":\"konzmnsik\"}") + "{\"kind\":\"Database\",\"location\":\"btkuwhh\",\"id\":\"hykojoxafnndlpic\",\"name\":\"koymkcd\",\"type\":\"h\"}") .toObject(DatabaseInner.class); - Assertions.assertEquals("nkww", model.location()); + Assertions.assertEquals("btkuwhh", model.location()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - DatabaseInner model = new DatabaseInner().withLocation("nkww"); + DatabaseInner model = new DatabaseInner().withLocation("btkuwhh"); model = BinaryData.fromObject(model).toObject(DatabaseInner.class); - Assertions.assertEquals("nkww", model.location()); + Assertions.assertEquals("btkuwhh", model.location()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabaseInviteFollowerRequestTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabaseInviteFollowerRequestTests.java index fac0abf79bcf..c497d2f57e5d 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabaseInviteFollowerRequestTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabaseInviteFollowerRequestTests.java @@ -14,42 +14,45 @@ public final class DatabaseInviteFollowerRequestTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { DatabaseInviteFollowerRequest model = BinaryData.fromString( - "{\"inviteeEmail\":\"mkqzeqqkdltfzxmh\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"ur\",\"odkwobd\",\"gxtibqdxbxw\",\"kbogqxndlkzgx\"],\"tablesToExclude\":[\"iplbpodxunkbebxm\"],\"externalTablesToInclude\":[\"yntwlrbq\",\"koievseo\"],\"externalTablesToExclude\":[\"rlltmuwlauwzizx\"],\"materializedViewsToInclude\":[\"gcj\",\"fuzmuvpbtt\",\"um\"],\"materializedViewsToExclude\":[\"pxebmnzbt\"],\"functionsToInclude\":[\"pglkf\",\"ohdneuel\",\"phsdyhto\"],\"functionsToExclude\":[\"kd\",\"wwquuvxzxclvithh\",\"zonosgg\"]}}") + "{\"inviteeEmail\":\"pkkpw\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"novvqfovljxy\"],\"tablesToExclude\":[\"w\",\"yrs\",\"dsytgadgvr\",\"ea\"],\"externalTablesToInclude\":[\"qnzarrwl\"],\"externalTablesToExclude\":[\"ijfqkacewiipfp\",\"bjibwwiftohq\"],\"materializedViewsToInclude\":[\"uvksgplsaknynfsy\",\"ljphuopxodl\"],\"materializedViewsToExclude\":[\"ntorzihleosjswsr\"],\"functionsToInclude\":[\"yzrpzbchckqqzq\",\"ox\",\"ysuiizynkedya\",\"rwyhqmibzyhwitsm\"],\"functionsToExclude\":[\"ynpcdpumnzgmwznm\",\"biknsorgjhxbld\",\"lwwrl\",\"dmtnc\"]}}") .toObject(DatabaseInviteFollowerRequest.class); - Assertions.assertEquals("mkqzeqqkdltfzxmh", model.inviteeEmail()); - Assertions.assertEquals("ur", model.tableLevelSharingProperties().tablesToInclude().get(0)); - Assertions.assertEquals("iplbpodxunkbebxm", model.tableLevelSharingProperties().tablesToExclude().get(0)); - Assertions.assertEquals("yntwlrbq", model.tableLevelSharingProperties().externalTablesToInclude().get(0)); - Assertions.assertEquals("rlltmuwlauwzizx", - model.tableLevelSharingProperties().externalTablesToExclude().get(0)); - Assertions.assertEquals("gcj", model.tableLevelSharingProperties().materializedViewsToInclude().get(0)); - Assertions.assertEquals("pxebmnzbt", model.tableLevelSharingProperties().materializedViewsToExclude().get(0)); - Assertions.assertEquals("pglkf", model.tableLevelSharingProperties().functionsToInclude().get(0)); - Assertions.assertEquals("kd", model.tableLevelSharingProperties().functionsToExclude().get(0)); + Assertions.assertEquals("pkkpw", model.inviteeEmail()); + Assertions.assertEquals("novvqfovljxy", model.tableLevelSharingProperties().tablesToInclude().get(0)); + Assertions.assertEquals("w", model.tableLevelSharingProperties().tablesToExclude().get(0)); + Assertions.assertEquals("qnzarrwl", model.tableLevelSharingProperties().externalTablesToInclude().get(0)); + Assertions.assertEquals("ijfqkacewiipfp", model.tableLevelSharingProperties().externalTablesToExclude().get(0)); + Assertions.assertEquals("uvksgplsaknynfsy", + model.tableLevelSharingProperties().materializedViewsToInclude().get(0)); + Assertions.assertEquals("ntorzihleosjswsr", + model.tableLevelSharingProperties().materializedViewsToExclude().get(0)); + Assertions.assertEquals("yzrpzbchckqqzq", model.tableLevelSharingProperties().functionsToInclude().get(0)); + Assertions.assertEquals("ynpcdpumnzgmwznm", model.tableLevelSharingProperties().functionsToExclude().get(0)); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - DatabaseInviteFollowerRequest model = new DatabaseInviteFollowerRequest().withInviteeEmail("mkqzeqqkdltfzxmh") - .withTableLevelSharingProperties(new TableLevelSharingProperties() - .withTablesToInclude(Arrays.asList("ur", "odkwobd", "gxtibqdxbxw", "kbogqxndlkzgx")) - .withTablesToExclude(Arrays.asList("iplbpodxunkbebxm")) - .withExternalTablesToInclude(Arrays.asList("yntwlrbq", "koievseo")) - .withExternalTablesToExclude(Arrays.asList("rlltmuwlauwzizx")) - .withMaterializedViewsToInclude(Arrays.asList("gcj", "fuzmuvpbtt", "um")) - .withMaterializedViewsToExclude(Arrays.asList("pxebmnzbt")) - .withFunctionsToInclude(Arrays.asList("pglkf", "ohdneuel", "phsdyhto")) - .withFunctionsToExclude(Arrays.asList("kd", "wwquuvxzxclvithh", "zonosgg"))); + DatabaseInviteFollowerRequest model + = new DatabaseInviteFollowerRequest().withInviteeEmail("pkkpw") + .withTableLevelSharingProperties(new TableLevelSharingProperties() + .withTablesToInclude(Arrays.asList("novvqfovljxy")) + .withTablesToExclude(Arrays.asList("w", "yrs", "dsytgadgvr", "ea")) + .withExternalTablesToInclude(Arrays.asList("qnzarrwl")) + .withExternalTablesToExclude(Arrays.asList("ijfqkacewiipfp", "bjibwwiftohq")) + .withMaterializedViewsToInclude(Arrays.asList("uvksgplsaknynfsy", "ljphuopxodl")) + .withMaterializedViewsToExclude(Arrays.asList("ntorzihleosjswsr")) + .withFunctionsToInclude(Arrays.asList("yzrpzbchckqqzq", "ox", "ysuiizynkedya", "rwyhqmibzyhwitsm")) + .withFunctionsToExclude(Arrays.asList("ynpcdpumnzgmwznm", "biknsorgjhxbld", "lwwrl", "dmtnc"))); model = BinaryData.fromObject(model).toObject(DatabaseInviteFollowerRequest.class); - Assertions.assertEquals("mkqzeqqkdltfzxmh", model.inviteeEmail()); - Assertions.assertEquals("ur", model.tableLevelSharingProperties().tablesToInclude().get(0)); - Assertions.assertEquals("iplbpodxunkbebxm", model.tableLevelSharingProperties().tablesToExclude().get(0)); - Assertions.assertEquals("yntwlrbq", model.tableLevelSharingProperties().externalTablesToInclude().get(0)); - Assertions.assertEquals("rlltmuwlauwzizx", - model.tableLevelSharingProperties().externalTablesToExclude().get(0)); - Assertions.assertEquals("gcj", model.tableLevelSharingProperties().materializedViewsToInclude().get(0)); - Assertions.assertEquals("pxebmnzbt", model.tableLevelSharingProperties().materializedViewsToExclude().get(0)); - Assertions.assertEquals("pglkf", model.tableLevelSharingProperties().functionsToInclude().get(0)); - Assertions.assertEquals("kd", model.tableLevelSharingProperties().functionsToExclude().get(0)); + Assertions.assertEquals("pkkpw", model.inviteeEmail()); + Assertions.assertEquals("novvqfovljxy", model.tableLevelSharingProperties().tablesToInclude().get(0)); + Assertions.assertEquals("w", model.tableLevelSharingProperties().tablesToExclude().get(0)); + Assertions.assertEquals("qnzarrwl", model.tableLevelSharingProperties().externalTablesToInclude().get(0)); + Assertions.assertEquals("ijfqkacewiipfp", model.tableLevelSharingProperties().externalTablesToExclude().get(0)); + Assertions.assertEquals("uvksgplsaknynfsy", + model.tableLevelSharingProperties().materializedViewsToInclude().get(0)); + Assertions.assertEquals("ntorzihleosjswsr", + model.tableLevelSharingProperties().materializedViewsToExclude().get(0)); + Assertions.assertEquals("yzrpzbchckqqzq", model.tableLevelSharingProperties().functionsToInclude().get(0)); + Assertions.assertEquals("ynpcdpumnzgmwznm", model.tableLevelSharingProperties().functionsToExclude().get(0)); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabaseInviteFollowerResultInnerTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabaseInviteFollowerResultInnerTests.java index 39eecf453048..66e9606ae10a 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabaseInviteFollowerResultInnerTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabaseInviteFollowerResultInnerTests.java @@ -11,15 +11,16 @@ public final class DatabaseInviteFollowerResultInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - DatabaseInviteFollowerResultInner model = BinaryData.fromString("{\"generatedInvitation\":\"c\"}") + DatabaseInviteFollowerResultInner model = BinaryData.fromString("{\"generatedInvitation\":\"kotl\"}") .toObject(DatabaseInviteFollowerResultInner.class); - Assertions.assertEquals("c", model.generatedInvitation()); + Assertions.assertEquals("kotl", model.generatedInvitation()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - DatabaseInviteFollowerResultInner model = new DatabaseInviteFollowerResultInner().withGeneratedInvitation("c"); + DatabaseInviteFollowerResultInner model + = new DatabaseInviteFollowerResultInner().withGeneratedInvitation("kotl"); model = BinaryData.fromObject(model).toObject(DatabaseInviteFollowerResultInner.class); - Assertions.assertEquals("c", model.generatedInvitation()); + Assertions.assertEquals("kotl", model.generatedInvitation()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabaseListResultTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabaseListResultTests.java index 5c5969ef38da..3b4c6d98ec3b 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabaseListResultTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabaseListResultTests.java @@ -14,20 +14,21 @@ public final class DatabaseListResultTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { DatabaseListResult model = BinaryData.fromString( - "{\"nextLink\":\"ycduier\",\"value\":[{\"kind\":\"Database\",\"location\":\"y\",\"id\":\"vaolpsslqlf\",\"name\":\"mdnbbglzpswiy\",\"type\":\"mcwyhzdxssadb\"},{\"kind\":\"Database\",\"location\":\"nvdfznuda\",\"id\":\"dvxzbncblylpst\",\"name\":\"bhhxsrzdzuc\",\"type\":\"rsc\"},{\"kind\":\"Database\",\"location\":\"t\",\"id\":\"evfiwjmygt\",\"name\":\"sslswtmweriof\",\"type\":\"pyqs\"},{\"kind\":\"Database\",\"location\":\"wab\",\"id\":\"ets\",\"name\":\"hszhedplvwiwu\",\"type\":\"mwmbes\"}]}") + "{\"nextLink\":\"qgxy\",\"value\":[{\"kind\":\"Database\",\"location\":\"mbqfqvmk\",\"id\":\"xozap\",\"name\":\"helxprglya\",\"type\":\"dd\"},{\"kind\":\"Database\",\"location\":\"cbcuejrjxgciqi\",\"id\":\"rhos\",\"name\":\"sdqrhzoymibmrq\",\"type\":\"ibahwflus\"},{\"kind\":\"Database\",\"location\":\"tmhrkwofyyvoqacp\",\"id\":\"expbtg\",\"name\":\"wbwo\",\"type\":\"nwashrtd\"},{\"kind\":\"Database\",\"location\":\"cnqxwbpokulpi\",\"id\":\"jwaa\",\"name\":\"ipqiiobyuqerpq\",\"type\":\"pqwcciuqgbdbutau\"}]}") .toObject(DatabaseListResult.class); - Assertions.assertEquals("ycduier", model.nextLink()); - Assertions.assertEquals("y", model.value().get(0).location()); + Assertions.assertEquals("qgxy", model.nextLink()); + Assertions.assertEquals("mbqfqvmk", model.value().get(0).location()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - DatabaseListResult model = new DatabaseListResult().withNextLink("ycduier") - .withValue( - Arrays.asList(new DatabaseInner().withLocation("y"), new DatabaseInner().withLocation("nvdfznuda"), - new DatabaseInner().withLocation("t"), new DatabaseInner().withLocation("wab"))); + DatabaseListResult model = new DatabaseListResult().withNextLink("qgxy") + .withValue(Arrays.asList(new DatabaseInner().withLocation("mbqfqvmk"), + new DatabaseInner().withLocation("cbcuejrjxgciqi"), + new DatabaseInner().withLocation("tmhrkwofyyvoqacp"), + new DatabaseInner().withLocation("cnqxwbpokulpi"))); model = BinaryData.fromObject(model).toObject(DatabaseListResult.class); - Assertions.assertEquals("ycduier", model.nextLink()); - Assertions.assertEquals("y", model.value().get(0).location()); + Assertions.assertEquals("qgxy", model.nextLink()); + Assertions.assertEquals("mbqfqvmk", model.value().get(0).location()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabaseOperationsInviteFollowerWithResponseMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabaseOperationsInviteFollowerWithResponseMockTests.java index 1f2da5e61c18..eb8448c63fe0 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabaseOperationsInviteFollowerWithResponseMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabaseOperationsInviteFollowerWithResponseMockTests.java @@ -23,7 +23,7 @@ public final class DatabaseOperationsInviteFollowerWithResponseMockTests { @Test public void testInviteFollowerWithResponse() throws Exception { - String responseStr = "{\"generatedInvitation\":\"ewbidyvteowxv\"}"; + String responseStr = "{\"generatedInvitation\":\"cxmjpbyephmg\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -33,20 +33,21 @@ public void testInviteFollowerWithResponse() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); DatabaseInviteFollowerResult response = manager.databaseOperations() - .inviteFollowerWithResponse("wjksghudgzhxo", "jggsvo", "jkxibda", - new DatabaseInviteFollowerRequest().withInviteeEmail("hrkmdyomkxfbvfbh") + .inviteFollowerWithResponse("sxze", "paxwkufyk", "vuhx", + new DatabaseInviteFollowerRequest().withInviteeEmail("pmru") .withTableLevelSharingProperties(new TableLevelSharingProperties() - .withTablesToInclude(Arrays.asList("hpwpgddeimawzovg")) - .withTablesToExclude(Arrays.asList("muikjcjcaztbws")) - .withExternalTablesToInclude(Arrays.asList("owxwcomli", "ytwvczcswkacve")) - .withExternalTablesToExclude(Arrays.asList("dvlvhbwrnfxtgdd")) - .withMaterializedViewsToInclude(Arrays.asList("hehnmnaoya")) - .withMaterializedViewsToExclude(Arrays.asList("oe", "swankltytmh", "roznnhdrlktgj", "sggux")) - .withFunctionsToInclude(Arrays.asList("lwywae", "czg", "bukklels")) - .withFunctionsToExclude(Arrays.asList("lycsxz", "jks", "lsmdesqplpvmjc"))), + .withTablesToInclude(Arrays.asList("baobn", "lujdjltymkmv", "uihywart", "pphkixkykxds")) + .withTablesToExclude(Arrays.asList("emmucfxh", "kkflrmymyincqlhr", "s")) + .withExternalTablesToInclude(Arrays.asList("miii", "v")) + .withExternalTablesToExclude(Arrays.asList("gxuugqkctotio", "l", "teqdptj", "wdtgukranblw")) + .withMaterializedViewsToInclude( + Arrays.asList("lkccuzgygqwa", "oiulwgniipr", "lvawuwzdufypivls", "bjpmcubk")) + .withMaterializedViewsToExclude(Arrays.asList("oxxkubvp")) + .withFunctionsToInclude(Arrays.asList("pmhbrbq")) + .withFunctionsToExclude(Arrays.asList("ovpbbttefjoknssq", "zqedikdfrdbi", "mrjgeihfqlggwfi"))), com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("ewbidyvteowxv", response.generatedInvitation()); + Assertions.assertEquals("cxmjpbyephmg", response.generatedInvitation()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentCheckNameRequestTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentCheckNameRequestTests.java index 4f5e8e8115ae..d46833ab6574 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentCheckNameRequestTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentCheckNameRequestTests.java @@ -11,16 +11,16 @@ public final class DatabasePrincipalAssignmentCheckNameRequestTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - DatabasePrincipalAssignmentCheckNameRequest model = BinaryData.fromString("{\"name\":\"hfwdsjnkaljutiis\"}") - .toObject(DatabasePrincipalAssignmentCheckNameRequest.class); - Assertions.assertEquals("hfwdsjnkaljutiis", model.name()); + DatabasePrincipalAssignmentCheckNameRequest model + = BinaryData.fromString("{\"name\":\"xdy\"}").toObject(DatabasePrincipalAssignmentCheckNameRequest.class); + Assertions.assertEquals("xdy", model.name()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { DatabasePrincipalAssignmentCheckNameRequest model - = new DatabasePrincipalAssignmentCheckNameRequest().withName("hfwdsjnkaljutiis"); + = new DatabasePrincipalAssignmentCheckNameRequest().withName("xdy"); model = BinaryData.fromObject(model).toObject(DatabasePrincipalAssignmentCheckNameRequest.class); - Assertions.assertEquals("hfwdsjnkaljutiis", model.name()); + Assertions.assertEquals("xdy", model.name()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentInnerTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentInnerTests.java index 16ddf1cad526..817d7bc28151 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentInnerTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentInnerTests.java @@ -14,24 +14,25 @@ public final class DatabasePrincipalAssignmentInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { DatabasePrincipalAssignmentInner model = BinaryData.fromString( - "{\"properties\":{\"principalId\":\"cffgdkzzewk\",\"role\":\"User\",\"tenantId\":\"qcrailvpnppfufl\",\"principalType\":\"Group\",\"tenantName\":\"mh\",\"principalName\":\"xyjrxsagafcnih\",\"provisioningState\":\"Deleting\",\"aadObjectId\":\"pnedgf\"},\"id\":\"cvkcvqvpkeqdcv\",\"name\":\"rhvoods\",\"type\":\"tbobz\"}") + "{\"properties\":{\"principalId\":\"syocogjltdtbnnha\",\"role\":\"User\",\"tenantId\":\"crkvcikhnv\",\"principalType\":\"App\",\"tenantName\":\"qgxqquezikyw\",\"principalName\":\"xkalla\",\"provisioningState\":\"Failed\",\"aadObjectId\":\"wuipiccjzkzivg\"},\"id\":\"vc\",\"name\":\"ayrhyrnx\",\"type\":\"mueedndrdvstk\"}") .toObject(DatabasePrincipalAssignmentInner.class); - Assertions.assertEquals("cffgdkzzewk", model.principalId()); + Assertions.assertEquals("syocogjltdtbnnha", model.principalId()); Assertions.assertEquals(DatabasePrincipalRole.USER, model.role()); - Assertions.assertEquals("qcrailvpnppfufl", model.tenantId()); - Assertions.assertEquals(PrincipalType.GROUP, model.principalType()); + Assertions.assertEquals("crkvcikhnv", model.tenantId()); + Assertions.assertEquals(PrincipalType.APP, model.principalType()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - DatabasePrincipalAssignmentInner model = new DatabasePrincipalAssignmentInner().withPrincipalId("cffgdkzzewk") - .withRole(DatabasePrincipalRole.USER) - .withTenantId("qcrailvpnppfufl") - .withPrincipalType(PrincipalType.GROUP); + DatabasePrincipalAssignmentInner model + = new DatabasePrincipalAssignmentInner().withPrincipalId("syocogjltdtbnnha") + .withRole(DatabasePrincipalRole.USER) + .withTenantId("crkvcikhnv") + .withPrincipalType(PrincipalType.APP); model = BinaryData.fromObject(model).toObject(DatabasePrincipalAssignmentInner.class); - Assertions.assertEquals("cffgdkzzewk", model.principalId()); + Assertions.assertEquals("syocogjltdtbnnha", model.principalId()); Assertions.assertEquals(DatabasePrincipalRole.USER, model.role()); - Assertions.assertEquals("qcrailvpnppfufl", model.tenantId()); - Assertions.assertEquals(PrincipalType.GROUP, model.principalType()); + Assertions.assertEquals("crkvcikhnv", model.tenantId()); + Assertions.assertEquals(PrincipalType.APP, model.principalType()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentListResultTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentListResultTests.java index d57b8251cb85..daadfda62947 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentListResultTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentListResultTests.java @@ -16,11 +16,11 @@ public final class DatabasePrincipalAssignmentListResultTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { DatabasePrincipalAssignmentListResult model = BinaryData.fromString( - "{\"value\":[{\"properties\":{\"principalId\":\"mbmpaxmodfvuefy\",\"role\":\"UnrestrictedViewer\",\"tenantId\":\"pfvmwyhrfou\",\"principalType\":\"User\",\"tenantName\":\"aakc\",\"principalName\":\"iyzvqtmnub\",\"provisioningState\":\"Deleting\",\"aadObjectId\":\"zksmondj\"},\"id\":\"quxvypomgkop\",\"name\":\"whojvp\",\"type\":\"jqg\"},{\"properties\":{\"principalId\":\"smocmbq\",\"role\":\"Viewer\",\"tenantId\":\"mkcxozapvh\",\"principalType\":\"App\",\"tenantName\":\"prglya\",\"principalName\":\"dckcbc\",\"provisioningState\":\"Failed\",\"aadObjectId\":\"jxgciqibrh\"},\"id\":\"sxsdqrhzoymibm\",\"name\":\"qyib\",\"type\":\"hwflu\"},{\"properties\":{\"principalId\":\"dtmhrkwofyyvoqa\",\"role\":\"Admin\",\"tenantId\":\"expbtg\",\"principalType\":\"App\",\"tenantName\":\"wo\",\"principalName\":\"washr\",\"provisioningState\":\"Moving\",\"aadObjectId\":\"cnqxwbpokulpi\"},\"id\":\"jwaa\",\"name\":\"ipqiiobyuqerpq\",\"type\":\"pqwcciuqgbdbutau\"},{\"properties\":{\"principalId\":\"btkuwhh\",\"role\":\"UnrestrictedViewer\",\"tenantId\":\"k\",\"principalType\":\"App\",\"tenantName\":\"xafnndlpichko\",\"principalName\":\"kcdyhbpk\",\"provisioningState\":\"Deleting\",\"aadObjectId\":\"reqnovvqfov\"},\"id\":\"jxywsuws\",\"name\":\"rsndsytgadgvra\",\"type\":\"aeneqnzarrwl\"}]}") + "{\"value\":[{\"properties\":{\"principalId\":\"fnjhfjxwmszkkfo\",\"role\":\"Monitor\",\"tenantId\":\"yfkzik\",\"principalType\":\"User\",\"tenantName\":\"wneaiv\",\"principalName\":\"czelpcirel\",\"provisioningState\":\"Failed\",\"aadObjectId\":\"enwabfatk\"},\"id\":\"ddxbjhwuaanoz\",\"name\":\"osphyoul\",\"type\":\"jrvxaglrv\"},{\"properties\":{\"principalId\":\"jwosytxitcskfck\",\"role\":\"Viewer\",\"tenantId\":\"miekkezzikhlyfjh\",\"principalType\":\"User\",\"tenantName\":\"gge\",\"principalName\":\"unygaeqid\",\"provisioningState\":\"Failed\",\"aadObjectId\":\"t\"},\"id\":\"xllrxcyjm\",\"name\":\"a\",\"type\":\"su\"},{\"properties\":{\"principalId\":\"r\",\"role\":\"Monitor\",\"tenantId\":\"dmjsjqb\",\"principalType\":\"App\",\"tenantName\":\"yxxrwlycoduh\",\"principalName\":\"xkgymareqnajxqu\",\"provisioningState\":\"Succeeded\",\"aadObjectId\":\"ycubeddgs\"},\"id\":\"ofwq\",\"name\":\"zqalkrmnjijpx\",\"type\":\"cqqudf\"}]}") .toObject(DatabasePrincipalAssignmentListResult.class); - Assertions.assertEquals("mbmpaxmodfvuefy", model.value().get(0).principalId()); - Assertions.assertEquals(DatabasePrincipalRole.UNRESTRICTED_VIEWER, model.value().get(0).role()); - Assertions.assertEquals("pfvmwyhrfou", model.value().get(0).tenantId()); + Assertions.assertEquals("fnjhfjxwmszkkfo", model.value().get(0).principalId()); + Assertions.assertEquals(DatabasePrincipalRole.MONITOR, model.value().get(0).role()); + Assertions.assertEquals("yfkzik", model.value().get(0).tenantId()); Assertions.assertEquals(PrincipalType.USER, model.value().get(0).principalType()); } @@ -28,26 +28,22 @@ public void testDeserialize() throws Exception { public void testSerialize() throws Exception { DatabasePrincipalAssignmentListResult model = new DatabasePrincipalAssignmentListResult().withValue(Arrays.asList( - new DatabasePrincipalAssignmentInner().withPrincipalId("mbmpaxmodfvuefy") - .withRole(DatabasePrincipalRole.UNRESTRICTED_VIEWER) - .withTenantId("pfvmwyhrfou") + new DatabasePrincipalAssignmentInner().withPrincipalId("fnjhfjxwmszkkfo") + .withRole(DatabasePrincipalRole.MONITOR) + .withTenantId("yfkzik") .withPrincipalType(PrincipalType.USER), - new DatabasePrincipalAssignmentInner().withPrincipalId("smocmbq") + new DatabasePrincipalAssignmentInner().withPrincipalId("jwosytxitcskfck") .withRole(DatabasePrincipalRole.VIEWER) - .withTenantId("mkcxozapvh") - .withPrincipalType(PrincipalType.APP), - new DatabasePrincipalAssignmentInner().withPrincipalId("dtmhrkwofyyvoqa") - .withRole(DatabasePrincipalRole.ADMIN) - .withTenantId("expbtg") - .withPrincipalType(PrincipalType.APP), - new DatabasePrincipalAssignmentInner().withPrincipalId("btkuwhh") - .withRole(DatabasePrincipalRole.UNRESTRICTED_VIEWER) - .withTenantId("k") + .withTenantId("miekkezzikhlyfjh") + .withPrincipalType(PrincipalType.USER), + new DatabasePrincipalAssignmentInner().withPrincipalId("r") + .withRole(DatabasePrincipalRole.MONITOR) + .withTenantId("dmjsjqb") .withPrincipalType(PrincipalType.APP))); model = BinaryData.fromObject(model).toObject(DatabasePrincipalAssignmentListResult.class); - Assertions.assertEquals("mbmpaxmodfvuefy", model.value().get(0).principalId()); - Assertions.assertEquals(DatabasePrincipalRole.UNRESTRICTED_VIEWER, model.value().get(0).role()); - Assertions.assertEquals("pfvmwyhrfou", model.value().get(0).tenantId()); + Assertions.assertEquals("fnjhfjxwmszkkfo", model.value().get(0).principalId()); + Assertions.assertEquals(DatabasePrincipalRole.MONITOR, model.value().get(0).role()); + Assertions.assertEquals("yfkzik", model.value().get(0).tenantId()); Assertions.assertEquals(PrincipalType.USER, model.value().get(0).principalType()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsCheckNameAvailabilityWithResponseMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsCheckNameAvailabilityWithResponseMockTests.java index 71e1c34b4a9a..bf149f20359c 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsCheckNameAvailabilityWithResponseMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsCheckNameAvailabilityWithResponseMockTests.java @@ -23,7 +23,7 @@ public final class DatabasePrincipalAssignmentsCheckNameAvailabilityWithResponse @Test public void testCheckNameAvailabilityWithResponse() throws Exception { String responseStr - = "{\"nameAvailable\":true,\"name\":\"wartspphkixkykxd\",\"message\":\"j\",\"reason\":\"Invalid\"}"; + = "{\"nameAvailable\":false,\"name\":\"aswlp\",\"message\":\"gm\",\"reason\":\"AlreadyExists\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -33,14 +33,13 @@ public void testCheckNameAvailabilityWithResponse() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); CheckNameResult response = manager.databasePrincipalAssignments() - .checkNameAvailabilityWithResponse("piudeugfsxzecpa", "wkufykhvuhxepm", "utznabaobns", - new DatabasePrincipalAssignmentCheckNameRequest().withName("ujdjltymkmvg"), - com.azure.core.util.Context.NONE) + .checkNameAvailabilityWithResponse("vljvrc", "yfqi", "gxhnpomyqwcabv", + new DatabasePrincipalAssignmentCheckNameRequest().withName("ui"), com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals(true, response.nameAvailable()); - Assertions.assertEquals("wartspphkixkykxd", response.name()); - Assertions.assertEquals("j", response.message()); - Assertions.assertEquals(Reason.INVALID, response.reason()); + Assertions.assertEquals(false, response.nameAvailable()); + Assertions.assertEquals("aswlp", response.name()); + Assertions.assertEquals("gm", response.message()); + Assertions.assertEquals(Reason.ALREADY_EXISTS, response.reason()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsCreateOrUpdateMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsCreateOrUpdateMockTests.java index 16ff43ef2936..ba056c79827f 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsCreateOrUpdateMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsCreateOrUpdateMockTests.java @@ -23,7 +23,7 @@ public final class DatabasePrincipalAssignmentsCreateOrUpdateMockTests { @Test public void testCreateOrUpdate() throws Exception { String responseStr - = "{\"properties\":{\"principalId\":\"mkoisqcssf\",\"role\":\"Ingestor\",\"tenantId\":\"ifmcsypobkdqzr\",\"principalType\":\"App\",\"tenantName\":\"ylollgtrczzydmxz\",\"principalName\":\"jpvuaurkihcirld\",\"provisioningState\":\"Succeeded\",\"aadObjectId\":\"dcoxnbk\"},\"id\":\"ja\",\"name\":\"urnnqbnqbpiz\",\"type\":\"qltgrd\"}"; + = "{\"properties\":{\"principalId\":\"mjel\",\"role\":\"UnrestrictedViewer\",\"tenantId\":\"cigeleohdbvqvw\",\"principalType\":\"Group\",\"tenantName\":\"opwbeonrlkwzd\",\"principalName\":\"bxcea\",\"provisioningState\":\"Succeeded\",\"aadObjectId\":\"tsoqfyiaseqchk\"},\"id\":\"ttzrazisgyki\",\"name\":\"emv\",\"type\":\"nbwzohmnrxxbso\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -33,17 +33,17 @@ public void testCreateOrUpdate() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); DatabasePrincipalAssignment response = manager.databasePrincipalAssignments() - .define("xtwbta") - .withExistingDatabase("dlrgms", "lzgaufcshhvnew", "nxkympqanxrjk") - .withPrincipalId("pnyghs") + .define("k") + .withExistingDatabase("spnxwqagnepzw", "klsbsbqqqagw", "rxaomzisglrrcze") + .withPrincipalId("ltn") .withRole(DatabasePrincipalRole.INGESTOR) - .withTenantId("ylhk") + .withTenantId("hqo") .withPrincipalType(PrincipalType.GROUP) .create(); - Assertions.assertEquals("mkoisqcssf", response.principalId()); - Assertions.assertEquals(DatabasePrincipalRole.INGESTOR, response.role()); - Assertions.assertEquals("ifmcsypobkdqzr", response.tenantId()); - Assertions.assertEquals(PrincipalType.APP, response.principalType()); + Assertions.assertEquals("mjel", response.principalId()); + Assertions.assertEquals(DatabasePrincipalRole.UNRESTRICTED_VIEWER, response.role()); + Assertions.assertEquals("cigeleohdbvqvw", response.tenantId()); + Assertions.assertEquals(PrincipalType.GROUP, response.principalType()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsDeleteMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsDeleteMockTests.java index b84d1d757c07..67a3aa764b72 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsDeleteMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsDeleteMockTests.java @@ -28,7 +28,7 @@ public void testDelete() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); manager.databasePrincipalAssignments() - .delete("gvgovpbbttefjo", "nssqyzqed", "kdfrdbiqmrjgeihf", "lg", com.azure.core.util.Context.NONE); + .delete("ac", "u", "vxnqmhrpqpd", "wmkoisq", com.azure.core.util.Context.NONE); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsGetWithResponseMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsGetWithResponseMockTests.java index a6d8ff3e7671..ce10f0747962 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsGetWithResponseMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsGetWithResponseMockTests.java @@ -23,7 +23,7 @@ public final class DatabasePrincipalAssignmentsGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"principalId\":\"iiovgqcgxu\",\"role\":\"Admin\",\"tenantId\":\"kctotiowlxteq\",\"principalType\":\"User\",\"tenantName\":\"jgwdtgukranbl\",\"principalName\":\"hqlkccuzgygqwaho\",\"provisioningState\":\"Running\",\"aadObjectId\":\"gniiprglvaw\"},\"id\":\"wzdufypivlsbb\",\"name\":\"pmcubkmifoxxkub\",\"type\":\"phavpmhbrb\"}"; + = "{\"properties\":{\"principalId\":\"guamlj\",\"role\":\"Ingestor\",\"tenantId\":\"gmsplzgaufcshhv\",\"principalType\":\"App\",\"tenantName\":\"gnxkympqan\",\"principalName\":\"jk\",\"provisioningState\":\"Succeeded\",\"aadObjectId\":\"bta\"},\"id\":\"ypnyghshxc\",\"name\":\"lhkgmnsghp\",\"type\":\"ycphdrwjjkhvyo\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -33,12 +33,13 @@ public void testGetWithResponse() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); DatabasePrincipalAssignment response = manager.databasePrincipalAssignments() - .getWithResponse("mucfxhikkf", "rmymyincqlhr", "s", "sl", com.azure.core.util.Context.NONE) + .getWithResponse("jlrxwtoaukhfk", "cisiz", "oaedsxjwuivedwcg", "eewxeiqbpsmg", + com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("iiovgqcgxu", response.principalId()); - Assertions.assertEquals(DatabasePrincipalRole.ADMIN, response.role()); - Assertions.assertEquals("kctotiowlxteq", response.tenantId()); - Assertions.assertEquals(PrincipalType.USER, response.principalType()); + Assertions.assertEquals("guamlj", response.principalId()); + Assertions.assertEquals(DatabasePrincipalRole.INGESTOR, response.role()); + Assertions.assertEquals("gmsplzgaufcshhv", response.tenantId()); + Assertions.assertEquals(PrincipalType.APP, response.principalType()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsListMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsListMockTests.java index 7d4c328da2d0..e893ffde13e1 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsListMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalAssignmentsListMockTests.java @@ -24,7 +24,7 @@ public final class DatabasePrincipalAssignmentsListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"principalId\":\"yqwcabvnuil\",\"role\":\"Monitor\",\"tenantId\":\"aswlp\",\"principalType\":\"Group\",\"tenantName\":\"mrmfjl\",\"principalName\":\"wtoaukhfk\",\"provisioningState\":\"Canceled\",\"aadObjectId\":\"izmoaeds\"},\"id\":\"jwuive\",\"name\":\"wcgyeewxeiqb\",\"type\":\"smgomguaml\"}]}"; + = "{\"value\":[{\"properties\":{\"principalId\":\"zzydmxzjijpvua\",\"role\":\"Monitor\",\"tenantId\":\"ihcirldef\",\"principalType\":\"User\",\"tenantName\":\"c\",\"principalName\":\"nbkkjanurnnq\",\"provisioningState\":\"Creating\",\"aadObjectId\":\"pizxqltgrdogyp\"},\"id\":\"rxvbfihwuh\",\"name\":\"ctafsrbxrblm\",\"type\":\"iowxi\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -34,11 +34,11 @@ public void testList() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); PagedIterable response = manager.databasePrincipalAssignments() - .list("wfiwzcxmj", "byephmgt", "ljvrcmyfqipgxhnp", com.azure.core.util.Context.NONE); + .list("ssffxuifmc", "ypobkdqzr", "zsylollgt", com.azure.core.util.Context.NONE); - Assertions.assertEquals("yqwcabvnuil", response.iterator().next().principalId()); + Assertions.assertEquals("zzydmxzjijpvua", response.iterator().next().principalId()); Assertions.assertEquals(DatabasePrincipalRole.MONITOR, response.iterator().next().role()); - Assertions.assertEquals("aswlp", response.iterator().next().tenantId()); - Assertions.assertEquals(PrincipalType.GROUP, response.iterator().next().principalType()); + Assertions.assertEquals("ihcirldef", response.iterator().next().tenantId()); + Assertions.assertEquals(PrincipalType.USER, response.iterator().next().principalType()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalInnerTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalInnerTests.java index d681f51cbbf6..8d0d46e3c469 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalInnerTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalInnerTests.java @@ -14,30 +14,30 @@ public final class DatabasePrincipalInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { DatabasePrincipalInner model = BinaryData.fromString( - "{\"role\":\"Admin\",\"name\":\"ynkedyatrwyhqmib\",\"type\":\"App\",\"fqn\":\"wit\",\"email\":\"ypyynpcdpumnzg\",\"appId\":\"z\",\"tenantName\":\"abikns\"}") + "{\"role\":\"Admin\",\"name\":\"pulpqblylsyxk\",\"type\":\"App\",\"fqn\":\"sjervti\",\"email\":\"xsdszuempsb\",\"appId\":\"f\",\"tenantName\":\"eyvpnqicvinvkj\"}") .toObject(DatabasePrincipalInner.class); Assertions.assertEquals(DatabasePrincipalRole.ADMIN, model.role()); - Assertions.assertEquals("ynkedyatrwyhqmib", model.name()); + Assertions.assertEquals("pulpqblylsyxk", model.name()); Assertions.assertEquals(DatabasePrincipalType.APP, model.type()); - Assertions.assertEquals("wit", model.fqn()); - Assertions.assertEquals("ypyynpcdpumnzg", model.email()); - Assertions.assertEquals("z", model.appId()); + Assertions.assertEquals("sjervti", model.fqn()); + Assertions.assertEquals("xsdszuempsb", model.email()); + Assertions.assertEquals("f", model.appId()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { DatabasePrincipalInner model = new DatabasePrincipalInner().withRole(DatabasePrincipalRole.ADMIN) - .withName("ynkedyatrwyhqmib") + .withName("pulpqblylsyxk") .withType(DatabasePrincipalType.APP) - .withFqn("wit") - .withEmail("ypyynpcdpumnzg") - .withAppId("z"); + .withFqn("sjervti") + .withEmail("xsdszuempsb") + .withAppId("f"); model = BinaryData.fromObject(model).toObject(DatabasePrincipalInner.class); Assertions.assertEquals(DatabasePrincipalRole.ADMIN, model.role()); - Assertions.assertEquals("ynkedyatrwyhqmib", model.name()); + Assertions.assertEquals("pulpqblylsyxk", model.name()); Assertions.assertEquals(DatabasePrincipalType.APP, model.type()); - Assertions.assertEquals("wit", model.fqn()); - Assertions.assertEquals("ypyynpcdpumnzg", model.email()); - Assertions.assertEquals("z", model.appId()); + Assertions.assertEquals("sjervti", model.fqn()); + Assertions.assertEquals("xsdszuempsb", model.email()); + Assertions.assertEquals("f", model.appId()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalListRequestTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalListRequestTests.java index 3ab187fd0baf..b8ed1185d090 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalListRequestTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalListRequestTests.java @@ -16,31 +16,43 @@ public final class DatabasePrincipalListRequestTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { DatabasePrincipalListRequest model = BinaryData.fromString( - "{\"value\":[{\"role\":\"UnrestrictedViewer\",\"name\":\"hxbld\",\"type\":\"App\",\"fqn\":\"wrlkdmtn\",\"email\":\"ok\",\"appId\":\"llxdyhgs\",\"tenantName\":\"cogjltdtbn\"}]}") + "{\"value\":[{\"role\":\"Viewer\",\"name\":\"rbuukzclewyhmlwp\",\"type\":\"User\",\"fqn\":\"zpof\",\"email\":\"ckw\",\"appId\":\"zqwhxxbuyqaxzfeq\",\"tenantName\":\"ppriol\"},{\"role\":\"Viewer\",\"name\":\"rjaltolmncw\",\"type\":\"User\",\"fqn\":\"qwcsdbnwdcfhuc\",\"email\":\"pfuvglsbjjca\",\"appId\":\"xbvtvudu\",\"tenantName\":\"cormr\"},{\"role\":\"Ingestor\",\"name\":\"qtvcofudflvkgj\",\"type\":\"Group\",\"fqn\":\"dknnqvsazn\",\"email\":\"tor\",\"appId\":\"sgsahmkycgr\",\"tenantName\":\"wjue\"}]}") .toObject(DatabasePrincipalListRequest.class); - Assertions.assertEquals(DatabasePrincipalRole.UNRESTRICTED_VIEWER, model.value().get(0).role()); - Assertions.assertEquals("hxbld", model.value().get(0).name()); - Assertions.assertEquals(DatabasePrincipalType.APP, model.value().get(0).type()); - Assertions.assertEquals("wrlkdmtn", model.value().get(0).fqn()); - Assertions.assertEquals("ok", model.value().get(0).email()); - Assertions.assertEquals("llxdyhgs", model.value().get(0).appId()); + Assertions.assertEquals(DatabasePrincipalRole.VIEWER, model.value().get(0).role()); + Assertions.assertEquals("rbuukzclewyhmlwp", model.value().get(0).name()); + Assertions.assertEquals(DatabasePrincipalType.USER, model.value().get(0).type()); + Assertions.assertEquals("zpof", model.value().get(0).fqn()); + Assertions.assertEquals("ckw", model.value().get(0).email()); + Assertions.assertEquals("zqwhxxbuyqaxzfeq", model.value().get(0).appId()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - DatabasePrincipalListRequest model = new DatabasePrincipalListRequest() - .withValue(Arrays.asList(new DatabasePrincipalInner().withRole(DatabasePrincipalRole.UNRESTRICTED_VIEWER) - .withName("hxbld") - .withType(DatabasePrincipalType.APP) - .withFqn("wrlkdmtn") - .withEmail("ok") - .withAppId("llxdyhgs"))); + DatabasePrincipalListRequest model = new DatabasePrincipalListRequest().withValue(Arrays.asList( + new DatabasePrincipalInner().withRole(DatabasePrincipalRole.VIEWER) + .withName("rbuukzclewyhmlwp") + .withType(DatabasePrincipalType.USER) + .withFqn("zpof") + .withEmail("ckw") + .withAppId("zqwhxxbuyqaxzfeq"), + new DatabasePrincipalInner().withRole(DatabasePrincipalRole.VIEWER) + .withName("rjaltolmncw") + .withType(DatabasePrincipalType.USER) + .withFqn("qwcsdbnwdcfhuc") + .withEmail("pfuvglsbjjca") + .withAppId("xbvtvudu"), + new DatabasePrincipalInner().withRole(DatabasePrincipalRole.INGESTOR) + .withName("qtvcofudflvkgj") + .withType(DatabasePrincipalType.GROUP) + .withFqn("dknnqvsazn") + .withEmail("tor") + .withAppId("sgsahmkycgr"))); model = BinaryData.fromObject(model).toObject(DatabasePrincipalListRequest.class); - Assertions.assertEquals(DatabasePrincipalRole.UNRESTRICTED_VIEWER, model.value().get(0).role()); - Assertions.assertEquals("hxbld", model.value().get(0).name()); - Assertions.assertEquals(DatabasePrincipalType.APP, model.value().get(0).type()); - Assertions.assertEquals("wrlkdmtn", model.value().get(0).fqn()); - Assertions.assertEquals("ok", model.value().get(0).email()); - Assertions.assertEquals("llxdyhgs", model.value().get(0).appId()); + Assertions.assertEquals(DatabasePrincipalRole.VIEWER, model.value().get(0).role()); + Assertions.assertEquals("rbuukzclewyhmlwp", model.value().get(0).name()); + Assertions.assertEquals(DatabasePrincipalType.USER, model.value().get(0).type()); + Assertions.assertEquals("zpof", model.value().get(0).fqn()); + Assertions.assertEquals("ckw", model.value().get(0).email()); + Assertions.assertEquals("zqwhxxbuyqaxzfeq", model.value().get(0).appId()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalListResultInnerTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalListResultInnerTests.java index 7ca2199ce2ae..7b63514d20f2 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalListResultInnerTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalListResultInnerTests.java @@ -16,37 +16,49 @@ public final class DatabasePrincipalListResultInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { DatabasePrincipalListResultInner model = BinaryData.fromString( - "{\"value\":[{\"role\":\"Admin\",\"name\":\"jfqka\",\"type\":\"Group\",\"fqn\":\"iipfpubj\",\"email\":\"wwiftohqkvpuv\",\"appId\":\"gplsaknynf\",\"tenantName\":\"n\"},{\"role\":\"Ingestor\",\"name\":\"ph\",\"type\":\"App\",\"fqn\":\"xodlqiyntorzih\",\"email\":\"osjswsr\",\"appId\":\"lyzrpzbchckqqzqi\",\"tenantName\":\"iysui\"}]}") + "{\"value\":[{\"role\":\"UnrestrictedViewer\",\"name\":\"baaa\",\"type\":\"User\",\"fqn\":\"vayffimrzrt\",\"email\":\"qogsexnevfd\",\"appId\":\"nw\",\"tenantName\":\"wzsyyceuzs\"},{\"role\":\"Monitor\",\"name\":\"bjudpfrxtrthzv\",\"type\":\"User\",\"fqn\":\"dwkqbrq\",\"email\":\"paxh\",\"appId\":\"iilivpdtiirqtd\",\"tenantName\":\"axoruzfgsquy\"},{\"role\":\"Ingestor\",\"name\":\"rxxle\",\"type\":\"App\",\"fqn\":\"amxjezwlw\",\"email\":\"xuqlcvydypat\",\"appId\":\"oa\",\"tenantName\":\"kniod\"},{\"role\":\"Admin\",\"name\":\"oebwnujhemms\",\"type\":\"User\",\"fqn\":\"kcrodtjinfw\",\"email\":\"fltkacjv\",\"appId\":\"kdlfoa\",\"tenantName\":\"gkfpaga\"}]}") .toObject(DatabasePrincipalListResultInner.class); - Assertions.assertEquals(DatabasePrincipalRole.ADMIN, model.value().get(0).role()); - Assertions.assertEquals("jfqka", model.value().get(0).name()); - Assertions.assertEquals(DatabasePrincipalType.GROUP, model.value().get(0).type()); - Assertions.assertEquals("iipfpubj", model.value().get(0).fqn()); - Assertions.assertEquals("wwiftohqkvpuv", model.value().get(0).email()); - Assertions.assertEquals("gplsaknynf", model.value().get(0).appId()); + Assertions.assertEquals(DatabasePrincipalRole.UNRESTRICTED_VIEWER, model.value().get(0).role()); + Assertions.assertEquals("baaa", model.value().get(0).name()); + Assertions.assertEquals(DatabasePrincipalType.USER, model.value().get(0).type()); + Assertions.assertEquals("vayffimrzrt", model.value().get(0).fqn()); + Assertions.assertEquals("qogsexnevfd", model.value().get(0).email()); + Assertions.assertEquals("nw", model.value().get(0).appId()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { DatabasePrincipalListResultInner model = new DatabasePrincipalListResultInner().withValue(Arrays.asList( - new DatabasePrincipalInner().withRole(DatabasePrincipalRole.ADMIN) - .withName("jfqka") - .withType(DatabasePrincipalType.GROUP) - .withFqn("iipfpubj") - .withEmail("wwiftohqkvpuv") - .withAppId("gplsaknynf"), + new DatabasePrincipalInner().withRole(DatabasePrincipalRole.UNRESTRICTED_VIEWER) + .withName("baaa") + .withType(DatabasePrincipalType.USER) + .withFqn("vayffimrzrt") + .withEmail("qogsexnevfd") + .withAppId("nw"), + new DatabasePrincipalInner().withRole(DatabasePrincipalRole.MONITOR) + .withName("bjudpfrxtrthzv") + .withType(DatabasePrincipalType.USER) + .withFqn("dwkqbrq") + .withEmail("paxh") + .withAppId("iilivpdtiirqtd"), new DatabasePrincipalInner().withRole(DatabasePrincipalRole.INGESTOR) - .withName("ph") + .withName("rxxle") .withType(DatabasePrincipalType.APP) - .withFqn("xodlqiyntorzih") - .withEmail("osjswsr") - .withAppId("lyzrpzbchckqqzqi"))); + .withFqn("amxjezwlw") + .withEmail("xuqlcvydypat") + .withAppId("oa"), + new DatabasePrincipalInner().withRole(DatabasePrincipalRole.ADMIN) + .withName("oebwnujhemms") + .withType(DatabasePrincipalType.USER) + .withFqn("kcrodtjinfw") + .withEmail("fltkacjv") + .withAppId("kdlfoa"))); model = BinaryData.fromObject(model).toObject(DatabasePrincipalListResultInner.class); - Assertions.assertEquals(DatabasePrincipalRole.ADMIN, model.value().get(0).role()); - Assertions.assertEquals("jfqka", model.value().get(0).name()); - Assertions.assertEquals(DatabasePrincipalType.GROUP, model.value().get(0).type()); - Assertions.assertEquals("iipfpubj", model.value().get(0).fqn()); - Assertions.assertEquals("wwiftohqkvpuv", model.value().get(0).email()); - Assertions.assertEquals("gplsaknynf", model.value().get(0).appId()); + Assertions.assertEquals(DatabasePrincipalRole.UNRESTRICTED_VIEWER, model.value().get(0).role()); + Assertions.assertEquals("baaa", model.value().get(0).name()); + Assertions.assertEquals(DatabasePrincipalType.USER, model.value().get(0).type()); + Assertions.assertEquals("vayffimrzrt", model.value().get(0).fqn()); + Assertions.assertEquals("qogsexnevfd", model.value().get(0).email()); + Assertions.assertEquals("nw", model.value().get(0).appId()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalPropertiesTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalPropertiesTests.java index 5a9d7dd8169a..b29a087b0e1d 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalPropertiesTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasePrincipalPropertiesTests.java @@ -14,24 +14,24 @@ public final class DatabasePrincipalPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { DatabasePrincipalProperties model = BinaryData.fromString( - "{\"principalId\":\"opcjwvnhd\",\"role\":\"Ingestor\",\"tenantId\":\"mgxcxrslpm\",\"principalType\":\"App\",\"tenantName\":\"uoegrpkhjwniyqs\",\"principalName\":\"i\",\"provisioningState\":\"Succeeded\",\"aadObjectId\":\"gk\"}") + "{\"principalId\":\"qqtch\",\"role\":\"UnrestrictedViewer\",\"tenantId\":\"mfmtdaaygdvw\",\"principalType\":\"User\",\"tenantName\":\"iohgwxrtfud\",\"principalName\":\"pxgy\",\"provisioningState\":\"Canceled\",\"aadObjectId\":\"rvmnpkukghimdblx\"}") .toObject(DatabasePrincipalProperties.class); - Assertions.assertEquals("opcjwvnhd", model.principalId()); - Assertions.assertEquals(DatabasePrincipalRole.INGESTOR, model.role()); - Assertions.assertEquals("mgxcxrslpm", model.tenantId()); - Assertions.assertEquals(PrincipalType.APP, model.principalType()); + Assertions.assertEquals("qqtch", model.principalId()); + Assertions.assertEquals(DatabasePrincipalRole.UNRESTRICTED_VIEWER, model.role()); + Assertions.assertEquals("mfmtdaaygdvw", model.tenantId()); + Assertions.assertEquals(PrincipalType.USER, model.principalType()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - DatabasePrincipalProperties model = new DatabasePrincipalProperties().withPrincipalId("opcjwvnhd") - .withRole(DatabasePrincipalRole.INGESTOR) - .withTenantId("mgxcxrslpm") - .withPrincipalType(PrincipalType.APP); + DatabasePrincipalProperties model = new DatabasePrincipalProperties().withPrincipalId("qqtch") + .withRole(DatabasePrincipalRole.UNRESTRICTED_VIEWER) + .withTenantId("mfmtdaaygdvw") + .withPrincipalType(PrincipalType.USER); model = BinaryData.fromObject(model).toObject(DatabasePrincipalProperties.class); - Assertions.assertEquals("opcjwvnhd", model.principalId()); - Assertions.assertEquals(DatabasePrincipalRole.INGESTOR, model.role()); - Assertions.assertEquals("mgxcxrslpm", model.tenantId()); - Assertions.assertEquals(PrincipalType.APP, model.principalType()); + Assertions.assertEquals("qqtch", model.principalId()); + Assertions.assertEquals(DatabasePrincipalRole.UNRESTRICTED_VIEWER, model.role()); + Assertions.assertEquals("mfmtdaaygdvw", model.tenantId()); + Assertions.assertEquals(PrincipalType.USER, model.principalType()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabaseStatisticsTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabaseStatisticsTests.java index 410e37cd780f..c51f1db647e2 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabaseStatisticsTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabaseStatisticsTests.java @@ -11,14 +11,14 @@ public final class DatabaseStatisticsTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - DatabaseStatistics model = BinaryData.fromString("{\"size\":48.312317}").toObject(DatabaseStatistics.class); - Assertions.assertEquals(48.312317F, model.size()); + DatabaseStatistics model = BinaryData.fromString("{\"size\":81.256256}").toObject(DatabaseStatistics.class); + Assertions.assertEquals(81.256256F, model.size()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - DatabaseStatistics model = new DatabaseStatistics().withSize(48.312317F); + DatabaseStatistics model = new DatabaseStatistics().withSize(81.256256F); model = BinaryData.fromObject(model).toObject(DatabaseStatistics.class); - Assertions.assertEquals(48.312317F, model.size()); + Assertions.assertEquals(81.256256F, model.size()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesAddPrincipalsWithResponseMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesAddPrincipalsWithResponseMockTests.java index a479443cf425..0cf8b6eba0e2 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesAddPrincipalsWithResponseMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesAddPrincipalsWithResponseMockTests.java @@ -26,7 +26,7 @@ public final class DatabasesAddPrincipalsWithResponseMockTests { @Test public void testAddPrincipalsWithResponse() throws Exception { String responseStr - = "{\"value\":[{\"role\":\"User\",\"name\":\"iibakcl\",\"type\":\"User\",\"fqn\":\"fr\",\"email\":\"ousxauzlwvsgmw\",\"appId\":\"qf\",\"tenantName\":\"zvuxm\"},{\"role\":\"Admin\",\"name\":\"jsvthnwpzteko\",\"type\":\"User\",\"fqn\":\"ibiattg\",\"email\":\"ucfotangcf\",\"appId\":\"ykzcugswvxwl\",\"tenantName\":\"qwm\"},{\"role\":\"User\",\"name\":\"xnjmxm\",\"type\":\"App\",\"fqn\":\"udtc\",\"email\":\"lxynpdkvgf\",\"appId\":\"uiyjib\",\"tenantName\":\"phdu\"},{\"role\":\"Admin\",\"name\":\"eiknpgo\",\"type\":\"User\",\"fqn\":\"iuqhibtozipqwj\",\"email\":\"mur\",\"appId\":\"x\",\"tenantName\":\"wpktvqylkmqpzoyh\"}]}"; + = "{\"value\":[{\"role\":\"Ingestor\",\"name\":\"tjxtxr\",\"type\":\"Group\",\"fqn\":\"tjvidt\",\"email\":\"epu\",\"appId\":\"vyjtcvu\",\"tenantName\":\"asiz\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -36,22 +36,22 @@ public void testAddPrincipalsWithResponse() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); DatabasePrincipalListResult response = manager.databases() - .addPrincipalsWithResponse("ao", "jrmzvupor", "zdfuydzvkfvxcnqm", + .addPrincipalsWithResponse("fypococtfjgti", "rjvzuyt", "rmlmuowo", new DatabasePrincipalListRequest() - .withValue(Arrays.asList(new DatabasePrincipalInner().withRole(DatabasePrincipalRole.INGESTOR) - .withName("wokmvkhlggd") + .withValue(Arrays.asList(new DatabasePrincipalInner().withRole(DatabasePrincipalRole.ADMIN) + .withName("iropionszon") .withType(DatabasePrincipalType.APP) - .withFqn("mzqkz") - .withEmail("uwiwtglxxhljfpg") - .withAppId("crmnzhrgmqgjs"))), + .withFqn("gajinnixjawrtmj") + .withEmail("myccx") + .withAppId("hcoxov"))), com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals(DatabasePrincipalRole.USER, response.value().get(0).role()); - Assertions.assertEquals("iibakcl", response.value().get(0).name()); - Assertions.assertEquals(DatabasePrincipalType.USER, response.value().get(0).type()); - Assertions.assertEquals("fr", response.value().get(0).fqn()); - Assertions.assertEquals("ousxauzlwvsgmw", response.value().get(0).email()); - Assertions.assertEquals("qf", response.value().get(0).appId()); + Assertions.assertEquals(DatabasePrincipalRole.INGESTOR, response.value().get(0).role()); + Assertions.assertEquals("tjxtxr", response.value().get(0).name()); + Assertions.assertEquals(DatabasePrincipalType.GROUP, response.value().get(0).type()); + Assertions.assertEquals("tjvidt", response.value().get(0).fqn()); + Assertions.assertEquals("epu", response.value().get(0).email()); + Assertions.assertEquals("vyjtcvu", response.value().get(0).appId()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesCheckNameAvailabilityWithResponseMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesCheckNameAvailabilityWithResponseMockTests.java index a1fabc60d1e5..a87b84458d6c 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesCheckNameAvailabilityWithResponseMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesCheckNameAvailabilityWithResponseMockTests.java @@ -24,7 +24,7 @@ public final class DatabasesCheckNameAvailabilityWithResponseMockTests { @Test public void testCheckNameAvailabilityWithResponse() throws Exception { String responseStr - = "{\"nameAvailable\":true,\"name\":\"jxlyyzglgouwtlm\",\"message\":\"yuojqtobaxk\",\"reason\":\"AlreadyExists\"}"; + = "{\"nameAvailable\":false,\"name\":\"haowj\",\"message\":\"zvuporqzdfuydz\",\"reason\":\"AlreadyExists\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -34,15 +34,15 @@ public void testCheckNameAvailabilityWithResponse() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); CheckNameResult response = manager.databases() - .checkNameAvailabilityWithResponse("tgfebwln", "mhyreeudz", - new CheckNameRequest().withName("av") + .checkNameAvailabilityWithResponse("bcpzgpxtivh", "knidib", + new CheckNameRequest().withName("qjxgpnrhgovfgp") .withType(Type.MICROSOFT_KUSTO_CLUSTERS_ATTACHED_DATABASE_CONFIGURATIONS), com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals(true, response.nameAvailable()); - Assertions.assertEquals("jxlyyzglgouwtlm", response.name()); - Assertions.assertEquals("yuojqtobaxk", response.message()); + Assertions.assertEquals(false, response.nameAvailable()); + Assertions.assertEquals("haowj", response.name()); + Assertions.assertEquals("zvuporqzdfuydz", response.message()); Assertions.assertEquals(Reason.ALREADY_EXISTS, response.reason()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesCreateOrUpdateMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesCreateOrUpdateMockTests.java index 135103281f3f..97aa7bb5a907 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesCreateOrUpdateMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesCreateOrUpdateMockTests.java @@ -23,7 +23,7 @@ public final class DatabasesCreateOrUpdateMockTests { @Test public void testCreateOrUpdate() throws Exception { String responseStr - = "{\"kind\":\"Database\",\"location\":\"cttuxuu\",\"id\":\"i\",\"name\":\"flqo\",\"type\":\"quvre\"}"; + = "{\"kind\":\"Database\",\"location\":\"phdu\",\"id\":\"neiknpg\",\"name\":\"xgjiuqh\",\"type\":\"btozipqwje\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -33,9 +33,9 @@ public void testCreateOrUpdate() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); Database response = manager.databases() - .createOrUpdate("zvzbglbyv", "ctctbrxkjz", "rgxffmshkw", new DatabaseInner().withLocation("kgozxwop"), - CallerRole.ADMIN, com.azure.core.util.Context.NONE); + .createOrUpdate("ribi", "ttgplucfotangcf", "nykzcugswvxwlm", new DatabaseInner().withLocation("wmvtxnjm"), + CallerRole.NONE, com.azure.core.util.Context.NONE); - Assertions.assertEquals("cttuxuu", response.location()); + Assertions.assertEquals("phdu", response.location()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesDeleteMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesDeleteMockTests.java index 89399d5a6394..0521f7ead770 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesDeleteMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesDeleteMockTests.java @@ -27,8 +27,7 @@ public void testDelete() throws Exception { .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), new AzureProfile("", "", AzureEnvironment.AZURE)); - manager.databases() - .delete("yjpmspbpssdfppyo", "tieyujtvczkcny", "rxmunjdxvgln", com.azure.core.util.Context.NONE); + manager.databases().delete("xffi", "hx", "rsnewmozqvbubqma", com.azure.core.util.Context.NONE); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesGetWithResponseMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesGetWithResponseMockTests.java index 8e406ec5ce54..35fcab15aa74 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesGetWithResponseMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesGetWithResponseMockTests.java @@ -21,7 +21,7 @@ public final class DatabasesGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"kind\":\"Database\",\"location\":\"aas\",\"id\":\"ixtmkzjvkviirhgf\",\"name\":\"rwsdp\",\"type\":\"ra\"}"; + = "{\"kind\":\"Database\",\"location\":\"mwohqfzizvuxmmkj\",\"id\":\"vthn\",\"name\":\"pz\",\"type\":\"ekov\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -31,9 +31,9 @@ public void testGetWithResponse() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); Database response = manager.databases() - .getWithResponse("hlisngw", "lqqmpiz", "uwnpqxpxiwfcng", com.azure.core.util.Context.NONE) + .getWithResponse("qcbfrmbodths", "qgvriibakcla", "jfrnxousxauzlwv", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("aas", response.location()); + Assertions.assertEquals("mwohqfzizvuxmmkj", response.location()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesListByClusterMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesListByClusterMockTests.java index 4749dd49565c..0ac6a261b868 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesListByClusterMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesListByClusterMockTests.java @@ -22,7 +22,7 @@ public final class DatabasesListByClusterMockTests { @Test public void testListByCluster() throws Exception { String responseStr - = "{\"value\":[{\"kind\":\"Database\",\"location\":\"jqhden\",\"id\":\"aulk\",\"name\":\"akdkifmjnnawtqab\",\"type\":\"xuckpggqoweyir\"}]}"; + = "{\"value\":[{\"kind\":\"Database\",\"location\":\"kzsz\",\"id\":\"wiwtglxxhl\",\"name\":\"fpgpicrmnzhrgm\",\"type\":\"gjsxv\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -32,8 +32,8 @@ public void testListByCluster() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); PagedIterable response = manager.databases() - .listByCluster("tu", "lbfjkwr", 1064304425, "nkqbhsyrq", com.azure.core.util.Context.NONE); + .listByCluster("vxcnqmxqps", "okmvkhlggd", 969740243, "em", com.azure.core.util.Context.NONE); - Assertions.assertEquals("jqhden", response.iterator().next().location()); + Assertions.assertEquals("kzsz", response.iterator().next().location()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesListPrincipalsMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesListPrincipalsMockTests.java index 1c63523ae1e0..0f05843e2cc6 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesListPrincipalsMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesListPrincipalsMockTests.java @@ -24,7 +24,7 @@ public final class DatabasesListPrincipalsMockTests { @Test public void testListPrincipals() throws Exception { String responseStr - = "{\"value\":[{\"role\":\"UnrestrictedViewer\",\"name\":\"pfpubcpzgpx\",\"type\":\"User\",\"fqn\":\"hjknidibg\",\"email\":\"xgpnr\",\"appId\":\"ov\",\"tenantName\":\"pikqmh\"}]}"; + = "{\"value\":[{\"role\":\"Ingestor\",\"name\":\"erngbtcjuahokqto\",\"type\":\"App\",\"fqn\":\"uxofshfphwpnulai\",\"email\":\"zejywhslw\",\"appId\":\"jpllndnpdwrpq\",\"tenantName\":\"gfugsnnfhyet\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -34,13 +34,13 @@ public void testListPrincipals() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); PagedIterable response = manager.databases() - .listPrincipals("vxlx", "aglqivbgkcvkh", "zvuqdflvon", com.azure.core.util.Context.NONE); + .listPrincipals("hsycxhxzgaz", "taboidvmf", "hppubowsepdfgkmt", com.azure.core.util.Context.NONE); - Assertions.assertEquals(DatabasePrincipalRole.UNRESTRICTED_VIEWER, response.iterator().next().role()); - Assertions.assertEquals("pfpubcpzgpx", response.iterator().next().name()); - Assertions.assertEquals(DatabasePrincipalType.USER, response.iterator().next().type()); - Assertions.assertEquals("hjknidibg", response.iterator().next().fqn()); - Assertions.assertEquals("xgpnr", response.iterator().next().email()); - Assertions.assertEquals("ov", response.iterator().next().appId()); + Assertions.assertEquals(DatabasePrincipalRole.INGESTOR, response.iterator().next().role()); + Assertions.assertEquals("erngbtcjuahokqto", response.iterator().next().name()); + Assertions.assertEquals(DatabasePrincipalType.APP, response.iterator().next().type()); + Assertions.assertEquals("uxofshfphwpnulai", response.iterator().next().fqn()); + Assertions.assertEquals("zejywhslw", response.iterator().next().email()); + Assertions.assertEquals("jpllndnpdwrpq", response.iterator().next().appId()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesRemovePrincipalsWithResponseMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesRemovePrincipalsWithResponseMockTests.java index 2e5b48b5d09d..4aff71cbdf41 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesRemovePrincipalsWithResponseMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesRemovePrincipalsWithResponseMockTests.java @@ -26,7 +26,7 @@ public final class DatabasesRemovePrincipalsWithResponseMockTests { @Test public void testRemovePrincipalsWithResponse() throws Exception { String responseStr - = "{\"value\":[{\"role\":\"Admin\",\"name\":\"dfgkmtdh\",\"type\":\"User\",\"fqn\":\"gb\",\"email\":\"juahokqto\",\"appId\":\"auxofshfph\",\"tenantName\":\"nulaiywzejywhsl\"},{\"role\":\"Monitor\",\"name\":\"ojpllndnpdwrpqaf\",\"type\":\"User\",\"fqn\":\"gsnnf\",\"email\":\"et\",\"appId\":\"ypococtfjgtixr\",\"tenantName\":\"zuyt\"},{\"role\":\"UnrestrictedViewer\",\"name\":\"mlmuowol\",\"type\":\"User\",\"fqn\":\"iropionszon\",\"email\":\"ngajinnixjawrtmj\",\"appId\":\"myccx\",\"tenantName\":\"hcoxov\"},{\"role\":\"Viewer\",\"name\":\"khenlus\",\"type\":\"App\",\"fqn\":\"dtjxtxrdcqt\",\"email\":\"idttgepus\",\"appId\":\"yjtcvuwk\",\"tenantName\":\"iziesfuughtuq\"}]}"; + = "{\"value\":[{\"role\":\"Admin\",\"name\":\"m\",\"type\":\"User\",\"fqn\":\"ebnfxofvc\",\"email\":\"gdirazf\",\"appId\":\"ejwabmdujtmvco\",\"tenantName\":\"xcmjurbu\"},{\"role\":\"Ingestor\",\"name\":\"lkyqltqsrog\",\"type\":\"App\",\"fqn\":\"kffdjktsys\",\"email\":\"fvcl\",\"appId\":\"xnfuijtkbusqogs\",\"tenantName\":\"kayi\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -36,28 +36,34 @@ public void testRemovePrincipalsWithResponse() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); DatabasePrincipalListResult response = manager.databases() - .removePrincipalsWithResponse("fbcgwgcloxoebqin", "ipnwj", "ujqlafcbahh", + .removePrincipalsWithResponse("esfuught", "qfecjxeygtuhx", "ic", new DatabasePrincipalListRequest().withValue(Arrays.asList( - new DatabasePrincipalInner().withRole(DatabasePrincipalRole.VIEWER) - .withName("foiyjwpfilk") + new DatabasePrincipalInner().withRole(DatabasePrincipalRole.MONITOR) + .withName("mr") + .withType(DatabasePrincipalType.APP) + .withFqn("jlxuz") + .withEmail("wpusxjbaqehg") + .withAppId("ohzjqatucoigeb"), + new DatabasePrincipalInner().withRole(DatabasePrincipalRole.ADMIN) + .withName("bjb") .withType(DatabasePrincipalType.GROUP) - .withFqn("holvdn") - .withEmail("iauogphuartv") - .withAppId("ukyefchnmnahmnxh"), - new DatabasePrincipalInner().withRole(DatabasePrincipalRole.UNRESTRICTED_VIEWER) - .withName("oxffif") - .withType(DatabasePrincipalType.USER) - .withFqn("rsnewmozqvbubqma") - .withEmail("sycxhxzgaz") - .withAppId("abo"))), + .withFqn("fgt") + .withEmail("snaquf") + .withAppId("bctqhamzjrwd"), + new DatabasePrincipalInner().withRole(DatabasePrincipalRole.INGESTOR) + .withName("dfzantkwcegy") + .withType(DatabasePrincipalType.GROUP) + .withFqn("bnseqacjjvpilg") + .withEmail("oq") + .withAppId("gmditgueiookjbs"))), com.azure.core.util.Context.NONE) .getValue(); Assertions.assertEquals(DatabasePrincipalRole.ADMIN, response.value().get(0).role()); - Assertions.assertEquals("dfgkmtdh", response.value().get(0).name()); + Assertions.assertEquals("m", response.value().get(0).name()); Assertions.assertEquals(DatabasePrincipalType.USER, response.value().get(0).type()); - Assertions.assertEquals("gb", response.value().get(0).fqn()); - Assertions.assertEquals("juahokqto", response.value().get(0).email()); - Assertions.assertEquals("auxofshfph", response.value().get(0).appId()); + Assertions.assertEquals("ebnfxofvc", response.value().get(0).fqn()); + Assertions.assertEquals("gdirazf", response.value().get(0).email()); + Assertions.assertEquals("ejwabmdujtmvco", response.value().get(0).appId()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesUpdateMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesUpdateMockTests.java index 473e2d371cfc..96fd32b90da3 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesUpdateMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DatabasesUpdateMockTests.java @@ -23,7 +23,7 @@ public final class DatabasesUpdateMockTests { @Test public void testUpdate() throws Exception { String responseStr - = "{\"kind\":\"Database\",\"location\":\"w\",\"id\":\"xqszdtmaajquh\",\"name\":\"xylrjvmtygjbmz\",\"type\":\"ospspshckf\"}"; + = "{\"kind\":\"Database\",\"location\":\"olvdnd\",\"id\":\"iauogphuartv\",\"name\":\"iukyefchnmna\",\"type\":\"mnxhkxjqirwrweo\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -33,9 +33,9 @@ public void testUpdate() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); Database response = manager.databases() - .update("mrnjh", "sujz", "czytqjtwhauunfpr", new DatabaseInner().withLocation("letlx"), CallerRole.ADMIN, - com.azure.core.util.Context.NONE); + .update("mur", "xxgewpk", "vqylkmqpzoyhl", new DatabaseInner().withLocation("cgwgcloxoebqinji"), + CallerRole.ADMIN, com.azure.core.util.Context.NONE); - Assertions.assertEquals("w", response.location()); + Assertions.assertEquals("olvdnd", response.location()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DiagnoseVirtualNetworkResultInnerTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DiagnoseVirtualNetworkResultInnerTests.java index 3108b0ebbefb..8eaddc168034 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DiagnoseVirtualNetworkResultInnerTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/DiagnoseVirtualNetworkResultInnerTests.java @@ -12,16 +12,16 @@ public final class DiagnoseVirtualNetworkResultInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - DiagnoseVirtualNetworkResultInner model - = BinaryData.fromString("{\"findings\":[\"pmr\"]}").toObject(DiagnoseVirtualNetworkResultInner.class); - Assertions.assertEquals("pmr", model.findings().get(0)); + DiagnoseVirtualNetworkResultInner model = BinaryData.fromString("{\"findings\":[\"ck\",\"rlhrxs\",\"kyv\"]}") + .toObject(DiagnoseVirtualNetworkResultInner.class); + Assertions.assertEquals("ck", model.findings().get(0)); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { DiagnoseVirtualNetworkResultInner model - = new DiagnoseVirtualNetworkResultInner().withFindings(Arrays.asList("pmr")); + = new DiagnoseVirtualNetworkResultInner().withFindings(Arrays.asList("ck", "rlhrxs", "kyv")); model = BinaryData.fromObject(model).toObject(DiagnoseVirtualNetworkResultInner.class); - Assertions.assertEquals("pmr", model.findings().get(0)); + Assertions.assertEquals("ck", model.findings().get(0)); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/EndpointDependencyTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/EndpointDependencyTests.java index bba3b3c04fb7..98faa20409e5 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/EndpointDependencyTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/EndpointDependencyTests.java @@ -14,21 +14,23 @@ public final class EndpointDependencyTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { EndpointDependency model = BinaryData.fromString( - "{\"domainName\":\"lhflsjcdhszfjvf\",\"endpointDetails\":[{\"port\":1130233947,\"ipAddress\":\"jagrqmqhldvr\"}]}") + "{\"domainName\":\"l\",\"endpointDetails\":[{\"port\":1262930280,\"ipAddress\":\"vgbmhr\"},{\"port\":283160638,\"ipAddress\":\"myijejvegr\"},{\"port\":662218702,\"ipAddress\":\"aixexccbdreaxh\"},{\"port\":1486564388,\"ipAddress\":\"rrvqa\"}]}") .toObject(EndpointDependency.class); - Assertions.assertEquals("lhflsjcdhszfjvf", model.domainName()); - Assertions.assertEquals(1130233947, model.endpointDetails().get(0).port()); - Assertions.assertEquals("jagrqmqhldvr", model.endpointDetails().get(0).ipAddress()); + Assertions.assertEquals("l", model.domainName()); + Assertions.assertEquals(1262930280, model.endpointDetails().get(0).port()); + Assertions.assertEquals("vgbmhr", model.endpointDetails().get(0).ipAddress()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - EndpointDependency model = new EndpointDependency().withDomainName("lhflsjcdhszfjvf") - .withEndpointDetails( - Arrays.asList(new EndpointDetail().withPort(1130233947).withIpAddress("jagrqmqhldvr"))); + EndpointDependency model = new EndpointDependency().withDomainName("l") + .withEndpointDetails(Arrays.asList(new EndpointDetail().withPort(1262930280).withIpAddress("vgbmhr"), + new EndpointDetail().withPort(283160638).withIpAddress("myijejvegr"), + new EndpointDetail().withPort(662218702).withIpAddress("aixexccbdreaxh"), + new EndpointDetail().withPort(1486564388).withIpAddress("rrvqa"))); model = BinaryData.fromObject(model).toObject(EndpointDependency.class); - Assertions.assertEquals("lhflsjcdhszfjvf", model.domainName()); - Assertions.assertEquals(1130233947, model.endpointDetails().get(0).port()); - Assertions.assertEquals("jagrqmqhldvr", model.endpointDetails().get(0).ipAddress()); + Assertions.assertEquals("l", model.domainName()); + Assertions.assertEquals(1262930280, model.endpointDetails().get(0).port()); + Assertions.assertEquals("vgbmhr", model.endpointDetails().get(0).ipAddress()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/EndpointDetailTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/EndpointDetailTests.java index 58f10b18973d..b95b403255e7 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/EndpointDetailTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/EndpointDetailTests.java @@ -12,16 +12,16 @@ public final class EndpointDetailTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { EndpointDetail model - = BinaryData.fromString("{\"port\":1300337109,\"ipAddress\":\"jnalghf\"}").toObject(EndpointDetail.class); - Assertions.assertEquals(1300337109, model.port()); - Assertions.assertEquals("jnalghf", model.ipAddress()); + = BinaryData.fromString("{\"port\":396764740,\"ipAddress\":\"htpwij\"}").toObject(EndpointDetail.class); + Assertions.assertEquals(396764740, model.port()); + Assertions.assertEquals("htpwij", model.ipAddress()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - EndpointDetail model = new EndpointDetail().withPort(1300337109).withIpAddress("jnalghf"); + EndpointDetail model = new EndpointDetail().withPort(396764740).withIpAddress("htpwij"); model = BinaryData.fromObject(model).toObject(EndpointDetail.class); - Assertions.assertEquals(1300337109, model.port()); - Assertions.assertEquals("jnalghf", model.ipAddress()); + Assertions.assertEquals(396764740, model.port()); + Assertions.assertEquals("htpwij", model.ipAddress()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/EventGridConnectionPropertiesTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/EventGridConnectionPropertiesTests.java index 4287b11bcf50..f44d61f1b259 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/EventGridConnectionPropertiesTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/EventGridConnectionPropertiesTests.java @@ -15,46 +15,46 @@ public final class EventGridConnectionPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { EventGridConnectionProperties model = BinaryData.fromString( - "{\"storageAccountResourceId\":\"zvfvaawz\",\"eventGridResourceId\":\"dflgzuri\",\"eventHubResourceId\":\"laecxndticok\",\"consumerGroup\":\"vzm\",\"tableName\":\"t\",\"mappingRuleName\":\"dgxobfircl\",\"dataFormat\":\"TXT\",\"ignoreFirstRecord\":false,\"blobStorageEventType\":\"Microsoft.Storage.BlobCreated\",\"managedIdentityResourceId\":\"riykhyawfvjlbox\",\"managedIdentityObjectId\":\"kjlmx\",\"databaseRouting\":\"Single\",\"provisioningState\":\"Succeeded\"}") + "{\"storageAccountResourceId\":\"gnjdgkynscliqhz\",\"eventGridResourceId\":\"xnkomtkubo\",\"eventHubResourceId\":\"ppnvdxz\",\"consumerGroup\":\"hihfrbbcevqagtlt\",\"tableName\":\"lfkqojpy\",\"mappingRuleName\":\"gtrd\",\"dataFormat\":\"PSV\",\"ignoreFirstRecord\":false,\"blobStorageEventType\":\"Microsoft.Storage.BlobRenamed\",\"managedIdentityResourceId\":\"dymbrny\",\"managedIdentityObjectId\":\"xmprafwg\",\"databaseRouting\":\"Multi\",\"provisioningState\":\"Creating\"}") .toObject(EventGridConnectionProperties.class); - Assertions.assertEquals("zvfvaawz", model.storageAccountResourceId()); - Assertions.assertEquals("dflgzuri", model.eventGridResourceId()); - Assertions.assertEquals("laecxndticok", model.eventHubResourceId()); - Assertions.assertEquals("vzm", model.consumerGroup()); - Assertions.assertEquals("t", model.tableName()); - Assertions.assertEquals("dgxobfircl", model.mappingRuleName()); - Assertions.assertEquals(EventGridDataFormat.TXT, model.dataFormat()); + Assertions.assertEquals("gnjdgkynscliqhz", model.storageAccountResourceId()); + Assertions.assertEquals("xnkomtkubo", model.eventGridResourceId()); + Assertions.assertEquals("ppnvdxz", model.eventHubResourceId()); + Assertions.assertEquals("hihfrbbcevqagtlt", model.consumerGroup()); + Assertions.assertEquals("lfkqojpy", model.tableName()); + Assertions.assertEquals("gtrd", model.mappingRuleName()); + Assertions.assertEquals(EventGridDataFormat.PSV, model.dataFormat()); Assertions.assertEquals(false, model.ignoreFirstRecord()); - Assertions.assertEquals(BlobStorageEventType.MICROSOFT_STORAGE_BLOB_CREATED, model.blobStorageEventType()); - Assertions.assertEquals("riykhyawfvjlbox", model.managedIdentityResourceId()); - Assertions.assertEquals(DatabaseRouting.SINGLE, model.databaseRouting()); + Assertions.assertEquals(BlobStorageEventType.MICROSOFT_STORAGE_BLOB_RENAMED, model.blobStorageEventType()); + Assertions.assertEquals("dymbrny", model.managedIdentityResourceId()); + Assertions.assertEquals(DatabaseRouting.MULTI, model.databaseRouting()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { EventGridConnectionProperties model - = new EventGridConnectionProperties().withStorageAccountResourceId("zvfvaawz") - .withEventGridResourceId("dflgzuri") - .withEventHubResourceId("laecxndticok") - .withConsumerGroup("vzm") - .withTableName("t") - .withMappingRuleName("dgxobfircl") - .withDataFormat(EventGridDataFormat.TXT) + = new EventGridConnectionProperties().withStorageAccountResourceId("gnjdgkynscliqhz") + .withEventGridResourceId("xnkomtkubo") + .withEventHubResourceId("ppnvdxz") + .withConsumerGroup("hihfrbbcevqagtlt") + .withTableName("lfkqojpy") + .withMappingRuleName("gtrd") + .withDataFormat(EventGridDataFormat.PSV) .withIgnoreFirstRecord(false) - .withBlobStorageEventType(BlobStorageEventType.MICROSOFT_STORAGE_BLOB_CREATED) - .withManagedIdentityResourceId("riykhyawfvjlbox") - .withDatabaseRouting(DatabaseRouting.SINGLE); + .withBlobStorageEventType(BlobStorageEventType.MICROSOFT_STORAGE_BLOB_RENAMED) + .withManagedIdentityResourceId("dymbrny") + .withDatabaseRouting(DatabaseRouting.MULTI); model = BinaryData.fromObject(model).toObject(EventGridConnectionProperties.class); - Assertions.assertEquals("zvfvaawz", model.storageAccountResourceId()); - Assertions.assertEquals("dflgzuri", model.eventGridResourceId()); - Assertions.assertEquals("laecxndticok", model.eventHubResourceId()); - Assertions.assertEquals("vzm", model.consumerGroup()); - Assertions.assertEquals("t", model.tableName()); - Assertions.assertEquals("dgxobfircl", model.mappingRuleName()); - Assertions.assertEquals(EventGridDataFormat.TXT, model.dataFormat()); + Assertions.assertEquals("gnjdgkynscliqhz", model.storageAccountResourceId()); + Assertions.assertEquals("xnkomtkubo", model.eventGridResourceId()); + Assertions.assertEquals("ppnvdxz", model.eventHubResourceId()); + Assertions.assertEquals("hihfrbbcevqagtlt", model.consumerGroup()); + Assertions.assertEquals("lfkqojpy", model.tableName()); + Assertions.assertEquals("gtrd", model.mappingRuleName()); + Assertions.assertEquals(EventGridDataFormat.PSV, model.dataFormat()); Assertions.assertEquals(false, model.ignoreFirstRecord()); - Assertions.assertEquals(BlobStorageEventType.MICROSOFT_STORAGE_BLOB_CREATED, model.blobStorageEventType()); - Assertions.assertEquals("riykhyawfvjlbox", model.managedIdentityResourceId()); - Assertions.assertEquals(DatabaseRouting.SINGLE, model.databaseRouting()); + Assertions.assertEquals(BlobStorageEventType.MICROSOFT_STORAGE_BLOB_RENAMED, model.blobStorageEventType()); + Assertions.assertEquals("dymbrny", model.managedIdentityResourceId()); + Assertions.assertEquals(DatabaseRouting.MULTI, model.databaseRouting()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/EventGridDataConnectionTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/EventGridDataConnectionTests.java index 805bf6ddf46b..65d810c37068 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/EventGridDataConnectionTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/EventGridDataConnectionTests.java @@ -15,48 +15,48 @@ public final class EventGridDataConnectionTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { EventGridDataConnection model = BinaryData.fromString( - "{\"kind\":\"EventGrid\",\"properties\":{\"storageAccountResourceId\":\"alhsnvkc\",\"eventGridResourceId\":\"xzrpo\",\"eventHubResourceId\":\"imlnwiaaomylw\",\"consumerGroup\":\"azul\",\"tableName\":\"ethwwnpjhlfz\",\"mappingRuleName\":\"pchwa\",\"dataFormat\":\"SCSV\",\"ignoreFirstRecord\":true,\"blobStorageEventType\":\"Microsoft.Storage.BlobCreated\",\"managedIdentityResourceId\":\"epgfew\",\"managedIdentityObjectId\":\"wlyxgncxyk\",\"databaseRouting\":\"Single\",\"provisioningState\":\"Deleting\"},\"location\":\"immbcx\",\"id\":\"h\",\"name\":\"cporxvxcjz\",\"type\":\"qizxfpxtgqscjavf\"}") + "{\"kind\":\"EventGrid\",\"properties\":{\"storageAccountResourceId\":\"tgguwpijrajcivmm\",\"eventGridResourceId\":\"f\",\"eventHubResourceId\":\"fiwrxgkn\",\"consumerGroup\":\"uvyinzqodfvpgs\",\"tableName\":\"xgsg\",\"mappingRuleName\":\"fgzdjtxvz\",\"dataFormat\":\"PSV\",\"ignoreFirstRecord\":false,\"blobStorageEventType\":\"Microsoft.Storage.BlobRenamed\",\"managedIdentityResourceId\":\"vl\",\"managedIdentityObjectId\":\"fcq\",\"databaseRouting\":\"Single\",\"provisioningState\":\"Moving\"},\"location\":\"t\",\"id\":\"wsdtutnwl\",\"name\":\"uycvuzhyrmewip\",\"type\":\"vekdxukuqgsjjxu\"}") .toObject(EventGridDataConnection.class); - Assertions.assertEquals("immbcx", model.location()); - Assertions.assertEquals("alhsnvkc", model.storageAccountResourceId()); - Assertions.assertEquals("xzrpo", model.eventGridResourceId()); - Assertions.assertEquals("imlnwiaaomylw", model.eventHubResourceId()); - Assertions.assertEquals("azul", model.consumerGroup()); - Assertions.assertEquals("ethwwnpjhlfz", model.tableName()); - Assertions.assertEquals("pchwa", model.mappingRuleName()); - Assertions.assertEquals(EventGridDataFormat.SCSV, model.dataFormat()); - Assertions.assertEquals(true, model.ignoreFirstRecord()); - Assertions.assertEquals(BlobStorageEventType.MICROSOFT_STORAGE_BLOB_CREATED, model.blobStorageEventType()); - Assertions.assertEquals("epgfew", model.managedIdentityResourceId()); + Assertions.assertEquals("t", model.location()); + Assertions.assertEquals("tgguwpijrajcivmm", model.storageAccountResourceId()); + Assertions.assertEquals("f", model.eventGridResourceId()); + Assertions.assertEquals("fiwrxgkn", model.eventHubResourceId()); + Assertions.assertEquals("uvyinzqodfvpgs", model.consumerGroup()); + Assertions.assertEquals("xgsg", model.tableName()); + Assertions.assertEquals("fgzdjtxvz", model.mappingRuleName()); + Assertions.assertEquals(EventGridDataFormat.PSV, model.dataFormat()); + Assertions.assertEquals(false, model.ignoreFirstRecord()); + Assertions.assertEquals(BlobStorageEventType.MICROSOFT_STORAGE_BLOB_RENAMED, model.blobStorageEventType()); + Assertions.assertEquals("vl", model.managedIdentityResourceId()); Assertions.assertEquals(DatabaseRouting.SINGLE, model.databaseRouting()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - EventGridDataConnection model = new EventGridDataConnection().withLocation("immbcx") - .withStorageAccountResourceId("alhsnvkc") - .withEventGridResourceId("xzrpo") - .withEventHubResourceId("imlnwiaaomylw") - .withConsumerGroup("azul") - .withTableName("ethwwnpjhlfz") - .withMappingRuleName("pchwa") - .withDataFormat(EventGridDataFormat.SCSV) - .withIgnoreFirstRecord(true) - .withBlobStorageEventType(BlobStorageEventType.MICROSOFT_STORAGE_BLOB_CREATED) - .withManagedIdentityResourceId("epgfew") + EventGridDataConnection model = new EventGridDataConnection().withLocation("t") + .withStorageAccountResourceId("tgguwpijrajcivmm") + .withEventGridResourceId("f") + .withEventHubResourceId("fiwrxgkn") + .withConsumerGroup("uvyinzqodfvpgs") + .withTableName("xgsg") + .withMappingRuleName("fgzdjtxvz") + .withDataFormat(EventGridDataFormat.PSV) + .withIgnoreFirstRecord(false) + .withBlobStorageEventType(BlobStorageEventType.MICROSOFT_STORAGE_BLOB_RENAMED) + .withManagedIdentityResourceId("vl") .withDatabaseRouting(DatabaseRouting.SINGLE); model = BinaryData.fromObject(model).toObject(EventGridDataConnection.class); - Assertions.assertEquals("immbcx", model.location()); - Assertions.assertEquals("alhsnvkc", model.storageAccountResourceId()); - Assertions.assertEquals("xzrpo", model.eventGridResourceId()); - Assertions.assertEquals("imlnwiaaomylw", model.eventHubResourceId()); - Assertions.assertEquals("azul", model.consumerGroup()); - Assertions.assertEquals("ethwwnpjhlfz", model.tableName()); - Assertions.assertEquals("pchwa", model.mappingRuleName()); - Assertions.assertEquals(EventGridDataFormat.SCSV, model.dataFormat()); - Assertions.assertEquals(true, model.ignoreFirstRecord()); - Assertions.assertEquals(BlobStorageEventType.MICROSOFT_STORAGE_BLOB_CREATED, model.blobStorageEventType()); - Assertions.assertEquals("epgfew", model.managedIdentityResourceId()); + Assertions.assertEquals("t", model.location()); + Assertions.assertEquals("tgguwpijrajcivmm", model.storageAccountResourceId()); + Assertions.assertEquals("f", model.eventGridResourceId()); + Assertions.assertEquals("fiwrxgkn", model.eventHubResourceId()); + Assertions.assertEquals("uvyinzqodfvpgs", model.consumerGroup()); + Assertions.assertEquals("xgsg", model.tableName()); + Assertions.assertEquals("fgzdjtxvz", model.mappingRuleName()); + Assertions.assertEquals(EventGridDataFormat.PSV, model.dataFormat()); + Assertions.assertEquals(false, model.ignoreFirstRecord()); + Assertions.assertEquals(BlobStorageEventType.MICROSOFT_STORAGE_BLOB_RENAMED, model.blobStorageEventType()); + Assertions.assertEquals("vl", model.managedIdentityResourceId()); Assertions.assertEquals(DatabaseRouting.SINGLE, model.databaseRouting()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/EventHubConnectionPropertiesTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/EventHubConnectionPropertiesTests.java index 9e052b4b7c47..4e7b381a4e2c 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/EventHubConnectionPropertiesTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/EventHubConnectionPropertiesTests.java @@ -17,42 +17,42 @@ public final class EventHubConnectionPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { EventHubConnectionProperties model = BinaryData.fromString( - "{\"eventHubResourceId\":\"jdxon\",\"consumerGroup\":\"zoggculapz\",\"tableName\":\"rpgogtqxep\",\"mappingRuleName\":\"lbfu\",\"dataFormat\":\"TSV\",\"eventSystemProperties\":[\"tlvofq\",\"hvfcibyfmow\",\"xrkjpvdw\",\"fzwiivwzjbhyz\"],\"compression\":\"GZip\",\"provisioningState\":\"Moving\",\"managedIdentityResourceId\":\"mbtrnegvmnvu\",\"managedIdentityObjectId\":\"qvldspastjbkkd\",\"databaseRouting\":\"Single\",\"retrievalStartDate\":\"2021-03-26T07:45:49Z\"}") + "{\"eventHubResourceId\":\"zqadf\",\"consumerGroup\":\"gzuriglaecxndt\",\"tableName\":\"okpvzm\",\"mappingRuleName\":\"t\",\"dataFormat\":\"SINGLEJSON\",\"eventSystemProperties\":[\"obfirclnpk\"],\"compression\":\"None\",\"provisioningState\":\"Canceled\",\"managedIdentityResourceId\":\"iykhy\",\"managedIdentityObjectId\":\"fvjlboxqvkjlmx\",\"databaseRouting\":\"Single\",\"retrievalStartDate\":\"2021-09-19T13:24:45Z\"}") .toObject(EventHubConnectionProperties.class); - Assertions.assertEquals("jdxon", model.eventHubResourceId()); - Assertions.assertEquals("zoggculapz", model.consumerGroup()); - Assertions.assertEquals("rpgogtqxep", model.tableName()); - Assertions.assertEquals("lbfu", model.mappingRuleName()); - Assertions.assertEquals(EventHubDataFormat.TSV, model.dataFormat()); - Assertions.assertEquals("tlvofq", model.eventSystemProperties().get(0)); - Assertions.assertEquals(Compression.GZIP, model.compression()); - Assertions.assertEquals("mbtrnegvmnvu", model.managedIdentityResourceId()); + Assertions.assertEquals("zqadf", model.eventHubResourceId()); + Assertions.assertEquals("gzuriglaecxndt", model.consumerGroup()); + Assertions.assertEquals("okpvzm", model.tableName()); + Assertions.assertEquals("t", model.mappingRuleName()); + Assertions.assertEquals(EventHubDataFormat.SINGLEJSON, model.dataFormat()); + Assertions.assertEquals("obfirclnpk", model.eventSystemProperties().get(0)); + Assertions.assertEquals(Compression.NONE, model.compression()); + Assertions.assertEquals("iykhy", model.managedIdentityResourceId()); Assertions.assertEquals(DatabaseRouting.SINGLE, model.databaseRouting()); - Assertions.assertEquals(OffsetDateTime.parse("2021-03-26T07:45:49Z"), model.retrievalStartDate()); + Assertions.assertEquals(OffsetDateTime.parse("2021-09-19T13:24:45Z"), model.retrievalStartDate()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - EventHubConnectionProperties model = new EventHubConnectionProperties().withEventHubResourceId("jdxon") - .withConsumerGroup("zoggculapz") - .withTableName("rpgogtqxep") - .withMappingRuleName("lbfu") - .withDataFormat(EventHubDataFormat.TSV) - .withEventSystemProperties(Arrays.asList("tlvofq", "hvfcibyfmow", "xrkjpvdw", "fzwiivwzjbhyz")) - .withCompression(Compression.GZIP) - .withManagedIdentityResourceId("mbtrnegvmnvu") + EventHubConnectionProperties model = new EventHubConnectionProperties().withEventHubResourceId("zqadf") + .withConsumerGroup("gzuriglaecxndt") + .withTableName("okpvzm") + .withMappingRuleName("t") + .withDataFormat(EventHubDataFormat.SINGLEJSON) + .withEventSystemProperties(Arrays.asList("obfirclnpk")) + .withCompression(Compression.NONE) + .withManagedIdentityResourceId("iykhy") .withDatabaseRouting(DatabaseRouting.SINGLE) - .withRetrievalStartDate(OffsetDateTime.parse("2021-03-26T07:45:49Z")); + .withRetrievalStartDate(OffsetDateTime.parse("2021-09-19T13:24:45Z")); model = BinaryData.fromObject(model).toObject(EventHubConnectionProperties.class); - Assertions.assertEquals("jdxon", model.eventHubResourceId()); - Assertions.assertEquals("zoggculapz", model.consumerGroup()); - Assertions.assertEquals("rpgogtqxep", model.tableName()); - Assertions.assertEquals("lbfu", model.mappingRuleName()); - Assertions.assertEquals(EventHubDataFormat.TSV, model.dataFormat()); - Assertions.assertEquals("tlvofq", model.eventSystemProperties().get(0)); - Assertions.assertEquals(Compression.GZIP, model.compression()); - Assertions.assertEquals("mbtrnegvmnvu", model.managedIdentityResourceId()); + Assertions.assertEquals("zqadf", model.eventHubResourceId()); + Assertions.assertEquals("gzuriglaecxndt", model.consumerGroup()); + Assertions.assertEquals("okpvzm", model.tableName()); + Assertions.assertEquals("t", model.mappingRuleName()); + Assertions.assertEquals(EventHubDataFormat.SINGLEJSON, model.dataFormat()); + Assertions.assertEquals("obfirclnpk", model.eventSystemProperties().get(0)); + Assertions.assertEquals(Compression.NONE, model.compression()); + Assertions.assertEquals("iykhy", model.managedIdentityResourceId()); Assertions.assertEquals(DatabaseRouting.SINGLE, model.databaseRouting()); - Assertions.assertEquals(OffsetDateTime.parse("2021-03-26T07:45:49Z"), model.retrievalStartDate()); + Assertions.assertEquals(OffsetDateTime.parse("2021-09-19T13:24:45Z"), model.retrievalStartDate()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/EventHubDataConnectionTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/EventHubDataConnectionTests.java index 78d9020b890e..243d1cfeceee 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/EventHubDataConnectionTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/EventHubDataConnectionTests.java @@ -17,45 +17,45 @@ public final class EventHubDataConnectionTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { EventHubDataConnection model = BinaryData.fromString( - "{\"kind\":\"EventHub\",\"properties\":{\"eventHubResourceId\":\"u\",\"consumerGroup\":\"lcplc\",\"tableName\":\"hihihlhzdsqtzbsr\",\"mappingRuleName\":\"o\",\"dataFormat\":\"CSV\",\"eventSystemProperties\":[\"gmvecactxmw\",\"teyowclu\",\"ovekqvgqouwi\",\"zmpjwyiv\"],\"compression\":\"GZip\",\"provisioningState\":\"Moving\",\"managedIdentityResourceId\":\"vhrfsphuagrt\",\"managedIdentityObjectId\":\"kteusqczk\",\"databaseRouting\":\"Single\",\"retrievalStartDate\":\"2021-06-04T23:13:27Z\"},\"location\":\"byjaffmmf\",\"id\":\"lcqcuubgqibrt\",\"name\":\"lmetttwgdslqxi\",\"type\":\"hrmooi\"}") + "{\"kind\":\"EventHub\",\"properties\":{\"eventHubResourceId\":\"seypxiutcxapz\",\"consumerGroup\":\"y\",\"tableName\":\"etoge\",\"mappingRuleName\":\"oxslh\",\"dataFormat\":\"SOHSV\",\"eventSystemProperties\":[\"brqnkkzjcjb\",\"rgaehvvibrxjj\",\"toqbeitpkxztmoob\"],\"compression\":\"None\",\"provisioningState\":\"Canceled\",\"managedIdentityResourceId\":\"gfcwqmpimaqxzhem\",\"managedIdentityObjectId\":\"h\",\"databaseRouting\":\"Single\",\"retrievalStartDate\":\"2021-02-04T05:09:41Z\"},\"location\":\"t\",\"id\":\"kozzwculkb\",\"name\":\"wpfaj\",\"type\":\"jwltlwtjjgu\"}") .toObject(EventHubDataConnection.class); - Assertions.assertEquals("byjaffmmf", model.location()); - Assertions.assertEquals("u", model.eventHubResourceId()); - Assertions.assertEquals("lcplc", model.consumerGroup()); - Assertions.assertEquals("hihihlhzdsqtzbsr", model.tableName()); - Assertions.assertEquals("o", model.mappingRuleName()); - Assertions.assertEquals(EventHubDataFormat.CSV, model.dataFormat()); - Assertions.assertEquals("gmvecactxmw", model.eventSystemProperties().get(0)); - Assertions.assertEquals(Compression.GZIP, model.compression()); - Assertions.assertEquals("vhrfsphuagrt", model.managedIdentityResourceId()); + Assertions.assertEquals("t", model.location()); + Assertions.assertEquals("seypxiutcxapz", model.eventHubResourceId()); + Assertions.assertEquals("y", model.consumerGroup()); + Assertions.assertEquals("etoge", model.tableName()); + Assertions.assertEquals("oxslh", model.mappingRuleName()); + Assertions.assertEquals(EventHubDataFormat.SOHSV, model.dataFormat()); + Assertions.assertEquals("brqnkkzjcjb", model.eventSystemProperties().get(0)); + Assertions.assertEquals(Compression.NONE, model.compression()); + Assertions.assertEquals("gfcwqmpimaqxzhem", model.managedIdentityResourceId()); Assertions.assertEquals(DatabaseRouting.SINGLE, model.databaseRouting()); - Assertions.assertEquals(OffsetDateTime.parse("2021-06-04T23:13:27Z"), model.retrievalStartDate()); + Assertions.assertEquals(OffsetDateTime.parse("2021-02-04T05:09:41Z"), model.retrievalStartDate()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - EventHubDataConnection model = new EventHubDataConnection().withLocation("byjaffmmf") - .withEventHubResourceId("u") - .withConsumerGroup("lcplc") - .withTableName("hihihlhzdsqtzbsr") - .withMappingRuleName("o") - .withDataFormat(EventHubDataFormat.CSV) - .withEventSystemProperties(Arrays.asList("gmvecactxmw", "teyowclu", "ovekqvgqouwi", "zmpjwyiv")) - .withCompression(Compression.GZIP) - .withManagedIdentityResourceId("vhrfsphuagrt") + EventHubDataConnection model = new EventHubDataConnection().withLocation("t") + .withEventHubResourceId("seypxiutcxapz") + .withConsumerGroup("y") + .withTableName("etoge") + .withMappingRuleName("oxslh") + .withDataFormat(EventHubDataFormat.SOHSV) + .withEventSystemProperties(Arrays.asList("brqnkkzjcjb", "rgaehvvibrxjj", "toqbeitpkxztmoob")) + .withCompression(Compression.NONE) + .withManagedIdentityResourceId("gfcwqmpimaqxzhem") .withDatabaseRouting(DatabaseRouting.SINGLE) - .withRetrievalStartDate(OffsetDateTime.parse("2021-06-04T23:13:27Z")); + .withRetrievalStartDate(OffsetDateTime.parse("2021-02-04T05:09:41Z")); model = BinaryData.fromObject(model).toObject(EventHubDataConnection.class); - Assertions.assertEquals("byjaffmmf", model.location()); - Assertions.assertEquals("u", model.eventHubResourceId()); - Assertions.assertEquals("lcplc", model.consumerGroup()); - Assertions.assertEquals("hihihlhzdsqtzbsr", model.tableName()); - Assertions.assertEquals("o", model.mappingRuleName()); - Assertions.assertEquals(EventHubDataFormat.CSV, model.dataFormat()); - Assertions.assertEquals("gmvecactxmw", model.eventSystemProperties().get(0)); - Assertions.assertEquals(Compression.GZIP, model.compression()); - Assertions.assertEquals("vhrfsphuagrt", model.managedIdentityResourceId()); + Assertions.assertEquals("t", model.location()); + Assertions.assertEquals("seypxiutcxapz", model.eventHubResourceId()); + Assertions.assertEquals("y", model.consumerGroup()); + Assertions.assertEquals("etoge", model.tableName()); + Assertions.assertEquals("oxslh", model.mappingRuleName()); + Assertions.assertEquals(EventHubDataFormat.SOHSV, model.dataFormat()); + Assertions.assertEquals("brqnkkzjcjb", model.eventSystemProperties().get(0)); + Assertions.assertEquals(Compression.NONE, model.compression()); + Assertions.assertEquals("gfcwqmpimaqxzhem", model.managedIdentityResourceId()); Assertions.assertEquals(DatabaseRouting.SINGLE, model.databaseRouting()); - Assertions.assertEquals(OffsetDateTime.parse("2021-06-04T23:13:27Z"), model.retrievalStartDate()); + Assertions.assertEquals(OffsetDateTime.parse("2021-02-04T05:09:41Z"), model.retrievalStartDate()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/FollowerDatabaseDefinitionGetInnerTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/FollowerDatabaseDefinitionGetInnerTests.java new file mode 100644 index 000000000000..99f22ead1b34 --- /dev/null +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/FollowerDatabaseDefinitionGetInnerTests.java @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.kusto.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.kusto.fluent.models.FollowerDatabaseDefinitionGetInner; +import org.junit.jupiter.api.Assertions; + +public final class FollowerDatabaseDefinitionGetInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + FollowerDatabaseDefinitionGetInner model = BinaryData.fromString( + "{\"properties\":{\"clusterResourceId\":\"gual\",\"attachedDatabaseConfigurationName\":\"b\",\"databaseName\":\"hejjz\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"dgwdslfhot\",\"mcy\",\"pwlbjnpg\"],\"tablesToExclude\":[\"tadehxnltyfsopp\",\"suesnzw\",\"ej\",\"avo\"],\"externalTablesToInclude\":[\"dmoh\",\"tbqvudw\",\"dndnvow\"],\"externalTablesToExclude\":[\"jugwdkcglhsl\",\"zj\",\"yggdtjixh\",\"kuofqweykhme\"],\"materializedViewsToInclude\":[\"fyexfwhy\",\"cibvyvdcsitynn\"],\"materializedViewsToExclude\":[\"dectehfiqsc\",\"eypvhezrkg\",\"hcjrefovgmk\",\"sle\"],\"functionsToInclude\":[\"xyqj\",\"k\",\"attpngjcrcczsq\",\"jh\"],\"functionsToExclude\":[\"ajvnysounqe\"]},\"databaseShareOrigin\":\"Other\"}}") + .toObject(FollowerDatabaseDefinitionGetInner.class); + Assertions.assertEquals("gual", model.clusterResourceId()); + Assertions.assertEquals("b", model.attachedDatabaseConfigurationName()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + FollowerDatabaseDefinitionGetInner model + = new FollowerDatabaseDefinitionGetInner().withClusterResourceId("gual") + .withAttachedDatabaseConfigurationName("b"); + model = BinaryData.fromObject(model).toObject(FollowerDatabaseDefinitionGetInner.class); + Assertions.assertEquals("gual", model.clusterResourceId()); + Assertions.assertEquals("b", model.attachedDatabaseConfigurationName()); + } +} diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/FollowerDatabaseDefinitionInnerTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/FollowerDatabaseDefinitionInnerTests.java index 8ff8b2c029d3..a2f2734fa899 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/FollowerDatabaseDefinitionInnerTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/FollowerDatabaseDefinitionInnerTests.java @@ -12,18 +12,19 @@ public final class FollowerDatabaseDefinitionInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { FollowerDatabaseDefinitionInner model = BinaryData.fromString( - "{\"clusterResourceId\":\"xyqj\",\"attachedDatabaseConfigurationName\":\"k\",\"databaseName\":\"t\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"jcrcczsqpjhvmda\",\"v\",\"ysou\",\"q\"],\"tablesToExclude\":[\"noae\"],\"externalTablesToInclude\":[\"hy\",\"ltrpmopj\",\"cma\",\"u\"],\"externalTablesToExclude\":[\"hfuiuaodsfc\",\"kvxod\",\"uozmyzydagfua\",\"bezy\"],\"materializedViewsToInclude\":[\"kktwhrdxw\",\"ywqsmbsurexim\",\"ryocfsfksymdd\"],\"materializedViewsToExclude\":[\"kiiuxhqyudxor\"],\"functionsToInclude\":[\"b\",\"oczvy\",\"fqrvkdvjsllrmvvd\",\"watkpnpulexxb\"],\"functionsToExclude\":[\"truwiqzb\",\"j\",\"sovmyokacspkwl\",\"zdobpxjmflbvvnch\"]},\"databaseShareOrigin\":\"Direct\"}") + "{\"clusterResourceId\":\"psiebtfhvpes\",\"attachedDatabaseConfigurationName\":\"pskrdqmh\",\"databaseName\":\"dhtldwkyz\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"kn\",\"ws\"],\"tablesToExclude\":[\"vlxotogtwrupqsx\",\"nmic\",\"kvceoveilovnotyf\",\"fcnj\"],\"externalTablesToInclude\":[\"nxdhbt\"],\"externalTablesToExclude\":[\"h\",\"wpn\"],\"materializedViewsToInclude\":[\"oqnermclfpl\"],\"materializedViewsToExclude\":[\"xus\",\"rpabg\",\"epsbjtazqu\",\"xywpmueefjzwfqkq\"],\"functionsToInclude\":[\"dsuyonobgla\"],\"functionsToExclude\":[\"xtccmg\",\"udxytlmoyrx\",\"wfudwpzntxhdzhl\"]},\"databaseShareOrigin\":\"DataShare\"}") .toObject(FollowerDatabaseDefinitionInner.class); - Assertions.assertEquals("xyqj", model.clusterResourceId()); - Assertions.assertEquals("k", model.attachedDatabaseConfigurationName()); + Assertions.assertEquals("psiebtfhvpes", model.clusterResourceId()); + Assertions.assertEquals("pskrdqmh", model.attachedDatabaseConfigurationName()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - FollowerDatabaseDefinitionInner model = new FollowerDatabaseDefinitionInner().withClusterResourceId("xyqj") - .withAttachedDatabaseConfigurationName("k"); + FollowerDatabaseDefinitionInner model + = new FollowerDatabaseDefinitionInner().withClusterResourceId("psiebtfhvpes") + .withAttachedDatabaseConfigurationName("pskrdqmh"); model = BinaryData.fromObject(model).toObject(FollowerDatabaseDefinitionInner.class); - Assertions.assertEquals("xyqj", model.clusterResourceId()); - Assertions.assertEquals("k", model.attachedDatabaseConfigurationName()); + Assertions.assertEquals("psiebtfhvpes", model.clusterResourceId()); + Assertions.assertEquals("pskrdqmh", model.attachedDatabaseConfigurationName()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/FollowerDatabaseListResultGetTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/FollowerDatabaseListResultGetTests.java new file mode 100644 index 000000000000..dc81b9700d1f --- /dev/null +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/FollowerDatabaseListResultGetTests.java @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.kusto.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.kusto.fluent.models.FollowerDatabaseDefinitionGetInner; +import com.azure.resourcemanager.kusto.models.FollowerDatabaseListResultGet; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class FollowerDatabaseListResultGetTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + FollowerDatabaseListResultGet model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"clusterResourceId\":\"dxob\",\"attachedDatabaseConfigurationName\":\"bdxkqpxokaj\",\"databaseName\":\"npime\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"xgcp\",\"dg\",\"aajrm\",\"djwzrlov\"],\"tablesToExclude\":[\"whijcoejctbza\",\"s\",\"sycbkbfk\",\"ukdkexxppofmxa\"],\"externalTablesToInclude\":[\"jpgd\",\"toc\",\"j\",\"hvpmoue\"],\"externalTablesToExclude\":[\"zxibqeoj\",\"xqbzvddntwnd\",\"icbtwnpzao\",\"vuhrhcffcyddgl\"],\"materializedViewsToInclude\":[\"hjq\"],\"materializedViewsToExclude\":[\"yeicxmqciwqvhk\",\"ixuigdtopbobj\"],\"functionsToInclude\":[\"m\"],\"functionsToExclude\":[\"a\"]},\"databaseShareOrigin\":\"DataShare\"}},{\"properties\":{\"clusterResourceId\":\"rzayv\",\"attachedDatabaseConfigurationName\":\"t\",\"databaseName\":\"vdfgiotk\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"qxlngx\",\"efgugnxk\"],\"tablesToExclude\":[\"qmi\",\"tthzrvqd\"],\"externalTablesToInclude\":[\"hjybigehoqfbo\"],\"externalTablesToExclude\":[\"anyktzlcuiywg\",\"ywgndrv\",\"nhzgpphrcgyn\",\"ocpecfvmmco\"],\"materializedViewsToInclude\":[\"xlzevgbmqjqabcy\",\"mivkwlzuvcc\",\"wnfnbacf\"],\"materializedViewsToExclude\":[\"l\",\"bxetqgtzxdpn\",\"bqqwxrj\",\"eallnwsubisnj\"],\"functionsToInclude\":[\"mngnzscxaqw\"],\"functionsToExclude\":[\"hcbonqvpkvlr\",\"njeaseipheofloke\",\"y\",\"enjbdlwtgrhp\"]},\"databaseShareOrigin\":\"Other\"}}],\"nextLink\":\"umasxazjpq\"}") + .toObject(FollowerDatabaseListResultGet.class); + Assertions.assertEquals("dxob", model.value().get(0).clusterResourceId()); + Assertions.assertEquals("bdxkqpxokaj", model.value().get(0).attachedDatabaseConfigurationName()); + Assertions.assertEquals("umasxazjpq", model.nextLink()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + FollowerDatabaseListResultGet model = new FollowerDatabaseListResultGet().withValue(Arrays.asList( + new FollowerDatabaseDefinitionGetInner().withClusterResourceId("dxob") + .withAttachedDatabaseConfigurationName("bdxkqpxokaj"), + new FollowerDatabaseDefinitionGetInner().withClusterResourceId("rzayv") + .withAttachedDatabaseConfigurationName("t"))) + .withNextLink("umasxazjpq"); + model = BinaryData.fromObject(model).toObject(FollowerDatabaseListResultGet.class); + Assertions.assertEquals("dxob", model.value().get(0).clusterResourceId()); + Assertions.assertEquals("bdxkqpxokaj", model.value().get(0).attachedDatabaseConfigurationName()); + Assertions.assertEquals("umasxazjpq", model.nextLink()); + } +} diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/FollowerDatabaseListResultTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/FollowerDatabaseListResultTests.java index ba9b6300f986..38fcee771a85 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/FollowerDatabaseListResultTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/FollowerDatabaseListResultTests.java @@ -14,23 +14,21 @@ public final class FollowerDatabaseListResultTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { FollowerDatabaseListResult model = BinaryData.fromString( - "{\"value\":[{\"clusterResourceId\":\"zloc\",\"attachedDatabaseConfigurationName\":\"scpai\",\"databaseName\":\"hhbcsglummajtjao\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"nbdxk\",\"pxokajionp\",\"mexgstxgcp\",\"dg\"],\"tablesToExclude\":[\"jrmvdjwzrlo\",\"mcl\",\"hijco\",\"jctbza\"],\"externalTablesToInclude\":[\"sycbkbfk\",\"ukdkexxppofmxa\",\"c\"],\"externalTablesToExclude\":[\"gddtocj\"],\"materializedViewsToInclude\":[\"vpmouexhdzxib\",\"eojnxqbzvddn\"],\"materializedViewsToExclude\":[\"deicbtwnpzao\"],\"functionsToInclude\":[\"hrhcffcyddglmjth\",\"qkwpyeicxmqc\",\"wqvhkhixuigdt\",\"pbobjo\"],\"functionsToExclude\":[\"e\"]},\"databaseShareOrigin\":\"Other\"},{\"clusterResourceId\":\"m\",\"attachedDatabaseConfigurationName\":\"uhrzayvvt\",\"databaseName\":\"vdfgiotk\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"qxlngx\",\"efgugnxk\"],\"tablesToExclude\":[\"qmi\",\"tthzrvqd\"],\"externalTablesToInclude\":[\"hjybigehoqfbo\"],\"externalTablesToExclude\":[\"anyktzlcuiywg\",\"ywgndrv\",\"nhzgpphrcgyn\",\"ocpecfvmmco\"],\"materializedViewsToInclude\":[\"xlzevgbmqjqabcy\",\"mivkwlzuvcc\",\"wnfnbacf\"],\"materializedViewsToExclude\":[\"l\",\"bxetqgtzxdpn\",\"bqqwxrj\",\"eallnwsubisnj\"],\"functionsToInclude\":[\"mngnzscxaqw\"],\"functionsToExclude\":[\"hcbonqvpkvlr\",\"njeaseipheofloke\",\"y\",\"enjbdlwtgrhp\"]},\"databaseShareOrigin\":\"Other\"},{\"clusterResourceId\":\"jumasx\",\"attachedDatabaseConfigurationName\":\"zj\",\"databaseName\":\"yegu\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"xxhejjzzvd\"],\"tablesToExclude\":[\"wdslfhotwmcy\",\"pwlbjnpg\",\"cftadeh\"],\"externalTablesToInclude\":[\"tyfsoppusuesn\",\"wd\"],\"externalTablesToExclude\":[\"avo\"],\"materializedViewsToInclude\":[\"dmoh\",\"tbqvudw\",\"dndnvow\"],\"materializedViewsToExclude\":[\"jugwdkcglhsl\",\"zj\",\"yggdtjixh\",\"kuofqweykhme\"],\"functionsToInclude\":[\"fyexfwhy\",\"cibvyvdcsitynn\"],\"functionsToExclude\":[\"dectehfiqsc\",\"eypvhezrkg\",\"hcjrefovgmk\",\"sle\"]},\"databaseShareOrigin\":\"Direct\"}]}") + "{\"value\":[{\"clusterResourceId\":\"njeputtmrywn\",\"attachedDatabaseConfigurationName\":\"zoqftiyqzrnkcqvy\",\"databaseName\":\"whzlsicohoq\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"lryav\",\"hheunmmqhgyx\",\"konocu\",\"oklyaxuconuq\"],\"tablesToExclude\":[\"kbeype\",\"rmjmwvvjektc\"],\"externalTablesToInclude\":[\"nhwlrsffrzpwvl\",\"dqgbiqylihkaetc\"],\"externalTablesToExclude\":[\"fcivfsnkym\",\"ctq\",\"jf\",\"ebrjcxe\"],\"materializedViewsToInclude\":[\"wutttxfvjrbi\",\"phxepcyvahf\",\"ljkyqxjvuuj\",\"gidokgjljyoxgvcl\"],\"materializedViewsToExclude\":[\"sncghkjeszz\",\"bijhtxfvgxbf\",\"mxnehmp\"],\"functionsToInclude\":[\"xgodebfqkkrbmp\",\"kgriwflzlfbx\"],\"functionsToExclude\":[\"zycispn\",\"zahmgkbrpyydhibn\",\"qqkpikadrg\"]},\"databaseShareOrigin\":\"Other\"},{\"clusterResourceId\":\"agnb\",\"attachedDatabaseConfigurationName\":\"ynhijggme\",\"databaseName\":\"siarbutrcvpn\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"hj\",\"unmpxttd\",\"hrbnlankxmyskpbh\",\"nbtkcxywnytnr\"],\"tablesToExclude\":[\"lqidyby\",\"czfc\",\"haaxdbabphl\"],\"externalTablesToInclude\":[\"lfktsths\",\"cocmnyyaztt\",\"twwrqp\"],\"externalTablesToExclude\":[\"ckzywbiexzfeyue\",\"xibxujwbhqwalm\",\"zyoxaepdkzjan\"],\"materializedViewsToInclude\":[\"rhdwbavxbniw\",\"jswztsdbpg\",\"xytxhpzxbz\",\"fzab\"],\"materializedViewsToExclude\":[\"uhxwtctyqiklbbov\"],\"functionsToInclude\":[\"zbhvgyuguosv\",\"kfssxqukkf\",\"l\"],\"functionsToExclude\":[\"sxnkjzkdeslpvlo\",\"wiyighxpkdw\",\"baiuebbaumny\",\"upedeojnabckhs\"]},\"databaseShareOrigin\":\"Direct\"}]}") .toObject(FollowerDatabaseListResult.class); - Assertions.assertEquals("zloc", model.value().get(0).clusterResourceId()); - Assertions.assertEquals("scpai", model.value().get(0).attachedDatabaseConfigurationName()); + Assertions.assertEquals("njeputtmrywn", model.value().get(0).clusterResourceId()); + Assertions.assertEquals("zoqftiyqzrnkcqvy", model.value().get(0).attachedDatabaseConfigurationName()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { FollowerDatabaseListResult model = new FollowerDatabaseListResult().withValue(Arrays.asList( - new FollowerDatabaseDefinitionInner().withClusterResourceId("zloc") - .withAttachedDatabaseConfigurationName("scpai"), - new FollowerDatabaseDefinitionInner().withClusterResourceId("m") - .withAttachedDatabaseConfigurationName("uhrzayvvt"), - new FollowerDatabaseDefinitionInner().withClusterResourceId("jumasx") - .withAttachedDatabaseConfigurationName("zj"))); + new FollowerDatabaseDefinitionInner().withClusterResourceId("njeputtmrywn") + .withAttachedDatabaseConfigurationName("zoqftiyqzrnkcqvy"), + new FollowerDatabaseDefinitionInner().withClusterResourceId("agnb") + .withAttachedDatabaseConfigurationName("ynhijggme"))); model = BinaryData.fromObject(model).toObject(FollowerDatabaseListResult.class); - Assertions.assertEquals("zloc", model.value().get(0).clusterResourceId()); - Assertions.assertEquals("scpai", model.value().get(0).attachedDatabaseConfigurationName()); + Assertions.assertEquals("njeputtmrywn", model.value().get(0).clusterResourceId()); + Assertions.assertEquals("zoqftiyqzrnkcqvy", model.value().get(0).attachedDatabaseConfigurationName()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/FollowerDatabasePropertiesTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/FollowerDatabasePropertiesTests.java new file mode 100644 index 000000000000..743b59964a30 --- /dev/null +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/FollowerDatabasePropertiesTests.java @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.kusto.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.kusto.fluent.models.FollowerDatabaseProperties; +import org.junit.jupiter.api.Assertions; + +public final class FollowerDatabasePropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + FollowerDatabaseProperties model = BinaryData.fromString( + "{\"clusterResourceId\":\"oaeupfhyhltrpmo\",\"attachedDatabaseConfigurationName\":\"jmcmatuokthfu\",\"databaseName\":\"aodsfcpkv\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"uozmyzydagfua\",\"bezy\",\"uokktwhrdxwz\"],\"tablesToExclude\":[\"sm\"],\"externalTablesToInclude\":[\"reximoryocfs\",\"ksymd\",\"ys\",\"kiiuxhqyudxor\"],\"externalTablesToExclude\":[\"b\",\"oczvy\",\"fqrvkdvjsllrmvvd\",\"watkpnpulexxb\"],\"materializedViewsToInclude\":[\"truwiqzb\",\"j\",\"sovmyokacspkwl\",\"zdobpxjmflbvvnch\"],\"materializedViewsToExclude\":[\"ciwwzjuqkhr\"],\"functionsToInclude\":[\"iwkuofos\",\"ghsauuimjmvxied\",\"ugidyjrr\",\"byao\"],\"functionsToExclude\":[\"xc\"]},\"databaseShareOrigin\":\"Direct\"}") + .toObject(FollowerDatabaseProperties.class); + Assertions.assertEquals("oaeupfhyhltrpmo", model.clusterResourceId()); + Assertions.assertEquals("jmcmatuokthfu", model.attachedDatabaseConfigurationName()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + FollowerDatabaseProperties model = new FollowerDatabaseProperties().withClusterResourceId("oaeupfhyhltrpmo") + .withAttachedDatabaseConfigurationName("jmcmatuokthfu"); + model = BinaryData.fromObject(model).toObject(FollowerDatabaseProperties.class); + Assertions.assertEquals("oaeupfhyhltrpmo", model.clusterResourceId()); + Assertions.assertEquals("jmcmatuokthfu", model.attachedDatabaseConfigurationName()); + } +} diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/IotHubConnectionPropertiesTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/IotHubConnectionPropertiesTests.java index 781bdf4c84e4..40b5a58facdd 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/IotHubConnectionPropertiesTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/IotHubConnectionPropertiesTests.java @@ -16,39 +16,39 @@ public final class IotHubConnectionPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { IotHubConnectionProperties model = BinaryData.fromString( - "{\"iotHubResourceId\":\"stmjlxrri\",\"consumerGroup\":\"ozapeew\",\"tableName\":\"pxlktwkuziycsl\",\"mappingRuleName\":\"ufuztcktyhjtq\",\"dataFormat\":\"PARQUET\",\"eventSystemProperties\":[\"ulwm\",\"rqzz\",\"rjvpglydzgkrvqee\",\"toepryu\"],\"sharedAccessPolicyName\":\"nwy\",\"databaseRouting\":\"Single\",\"retrievalStartDate\":\"2021-01-20T06:32:43Z\",\"provisioningState\":\"Failed\"}") + "{\"iotHubResourceId\":\"nhdwdigumbnra\",\"consumerGroup\":\"uzzptjazysdz\",\"tableName\":\"zwwva\",\"mappingRuleName\":\"yuvvfonkp\",\"dataFormat\":\"SOHSV\",\"eventSystemProperties\":[\"kvylauyavl\",\"wmn\",\"sttijfybvp\"],\"sharedAccessPolicyName\":\"ekrsgs\",\"databaseRouting\":\"Multi\",\"retrievalStartDate\":\"2021-08-14T00:34:57Z\",\"provisioningState\":\"Moving\"}") .toObject(IotHubConnectionProperties.class); - Assertions.assertEquals("stmjlxrri", model.iotHubResourceId()); - Assertions.assertEquals("ozapeew", model.consumerGroup()); - Assertions.assertEquals("pxlktwkuziycsl", model.tableName()); - Assertions.assertEquals("ufuztcktyhjtq", model.mappingRuleName()); - Assertions.assertEquals(IotHubDataFormat.PARQUET, model.dataFormat()); - Assertions.assertEquals("ulwm", model.eventSystemProperties().get(0)); - Assertions.assertEquals("nwy", model.sharedAccessPolicyName()); - Assertions.assertEquals(DatabaseRouting.SINGLE, model.databaseRouting()); - Assertions.assertEquals(OffsetDateTime.parse("2021-01-20T06:32:43Z"), model.retrievalStartDate()); + Assertions.assertEquals("nhdwdigumbnra", model.iotHubResourceId()); + Assertions.assertEquals("uzzptjazysdz", model.consumerGroup()); + Assertions.assertEquals("zwwva", model.tableName()); + Assertions.assertEquals("yuvvfonkp", model.mappingRuleName()); + Assertions.assertEquals(IotHubDataFormat.SOHSV, model.dataFormat()); + Assertions.assertEquals("kvylauyavl", model.eventSystemProperties().get(0)); + Assertions.assertEquals("ekrsgs", model.sharedAccessPolicyName()); + Assertions.assertEquals(DatabaseRouting.MULTI, model.databaseRouting()); + Assertions.assertEquals(OffsetDateTime.parse("2021-08-14T00:34:57Z"), model.retrievalStartDate()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - IotHubConnectionProperties model = new IotHubConnectionProperties().withIotHubResourceId("stmjlxrri") - .withConsumerGroup("ozapeew") - .withTableName("pxlktwkuziycsl") - .withMappingRuleName("ufuztcktyhjtq") - .withDataFormat(IotHubDataFormat.PARQUET) - .withEventSystemProperties(Arrays.asList("ulwm", "rqzz", "rjvpglydzgkrvqee", "toepryu")) - .withSharedAccessPolicyName("nwy") - .withDatabaseRouting(DatabaseRouting.SINGLE) - .withRetrievalStartDate(OffsetDateTime.parse("2021-01-20T06:32:43Z")); + IotHubConnectionProperties model = new IotHubConnectionProperties().withIotHubResourceId("nhdwdigumbnra") + .withConsumerGroup("uzzptjazysdz") + .withTableName("zwwva") + .withMappingRuleName("yuvvfonkp") + .withDataFormat(IotHubDataFormat.SOHSV) + .withEventSystemProperties(Arrays.asList("kvylauyavl", "wmn", "sttijfybvp")) + .withSharedAccessPolicyName("ekrsgs") + .withDatabaseRouting(DatabaseRouting.MULTI) + .withRetrievalStartDate(OffsetDateTime.parse("2021-08-14T00:34:57Z")); model = BinaryData.fromObject(model).toObject(IotHubConnectionProperties.class); - Assertions.assertEquals("stmjlxrri", model.iotHubResourceId()); - Assertions.assertEquals("ozapeew", model.consumerGroup()); - Assertions.assertEquals("pxlktwkuziycsl", model.tableName()); - Assertions.assertEquals("ufuztcktyhjtq", model.mappingRuleName()); - Assertions.assertEquals(IotHubDataFormat.PARQUET, model.dataFormat()); - Assertions.assertEquals("ulwm", model.eventSystemProperties().get(0)); - Assertions.assertEquals("nwy", model.sharedAccessPolicyName()); - Assertions.assertEquals(DatabaseRouting.SINGLE, model.databaseRouting()); - Assertions.assertEquals(OffsetDateTime.parse("2021-01-20T06:32:43Z"), model.retrievalStartDate()); + Assertions.assertEquals("nhdwdigumbnra", model.iotHubResourceId()); + Assertions.assertEquals("uzzptjazysdz", model.consumerGroup()); + Assertions.assertEquals("zwwva", model.tableName()); + Assertions.assertEquals("yuvvfonkp", model.mappingRuleName()); + Assertions.assertEquals(IotHubDataFormat.SOHSV, model.dataFormat()); + Assertions.assertEquals("kvylauyavl", model.eventSystemProperties().get(0)); + Assertions.assertEquals("ekrsgs", model.sharedAccessPolicyName()); + Assertions.assertEquals(DatabaseRouting.MULTI, model.databaseRouting()); + Assertions.assertEquals(OffsetDateTime.parse("2021-08-14T00:34:57Z"), model.retrievalStartDate()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/IotHubDataConnectionTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/IotHubDataConnectionTests.java index f3b00000b71a..e5c5991e7963 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/IotHubDataConnectionTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/IotHubDataConnectionTests.java @@ -16,42 +16,42 @@ public final class IotHubDataConnectionTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { IotHubDataConnection model = BinaryData.fromString( - "{\"kind\":\"IotHub\",\"properties\":{\"iotHubResourceId\":\"seypxiutcxapz\",\"consumerGroup\":\"y\",\"tableName\":\"etoge\",\"mappingRuleName\":\"oxslh\",\"dataFormat\":\"SOHSV\",\"eventSystemProperties\":[\"brqnkkzjcjb\",\"rgaehvvibrxjj\",\"toqbeitpkxztmoob\"],\"sharedAccessPolicyName\":\"lftidgfcwqmpim\",\"databaseRouting\":\"Single\",\"retrievalStartDate\":\"2021-12-01T05:05:15Z\",\"provisioningState\":\"Running\"},\"location\":\"yhohujswtwkozzwc\",\"id\":\"lkb\",\"name\":\"wpfaj\",\"type\":\"jwltlwtjjgu\"}") + "{\"kind\":\"IotHub\",\"properties\":{\"iotHubResourceId\":\"alhsnvkc\",\"consumerGroup\":\"mxzrpoa\",\"tableName\":\"lnwiaaomylwe\",\"mappingRuleName\":\"ulcsethwwnpj\",\"dataFormat\":\"JSON\",\"eventSystemProperties\":[\"wpchwahf\",\"ousnfepgfewe\",\"wlyxgncxyk\",\"hdjhlimmbcx\"],\"sharedAccessPolicyName\":\"h\",\"databaseRouting\":\"Single\",\"retrievalStartDate\":\"2021-08-24T02:48:56Z\",\"provisioningState\":\"Moving\"},\"location\":\"cjzhqi\",\"id\":\"xfpxtgqscja\",\"name\":\"ftjuh\",\"type\":\"qaz\"}") .toObject(IotHubDataConnection.class); - Assertions.assertEquals("yhohujswtwkozzwc", model.location()); - Assertions.assertEquals("seypxiutcxapz", model.iotHubResourceId()); - Assertions.assertEquals("y", model.consumerGroup()); - Assertions.assertEquals("etoge", model.tableName()); - Assertions.assertEquals("oxslh", model.mappingRuleName()); - Assertions.assertEquals(IotHubDataFormat.SOHSV, model.dataFormat()); - Assertions.assertEquals("brqnkkzjcjb", model.eventSystemProperties().get(0)); - Assertions.assertEquals("lftidgfcwqmpim", model.sharedAccessPolicyName()); + Assertions.assertEquals("cjzhqi", model.location()); + Assertions.assertEquals("alhsnvkc", model.iotHubResourceId()); + Assertions.assertEquals("mxzrpoa", model.consumerGroup()); + Assertions.assertEquals("lnwiaaomylwe", model.tableName()); + Assertions.assertEquals("ulcsethwwnpj", model.mappingRuleName()); + Assertions.assertEquals(IotHubDataFormat.JSON, model.dataFormat()); + Assertions.assertEquals("wpchwahf", model.eventSystemProperties().get(0)); + Assertions.assertEquals("h", model.sharedAccessPolicyName()); Assertions.assertEquals(DatabaseRouting.SINGLE, model.databaseRouting()); - Assertions.assertEquals(OffsetDateTime.parse("2021-12-01T05:05:15Z"), model.retrievalStartDate()); + Assertions.assertEquals(OffsetDateTime.parse("2021-08-24T02:48:56Z"), model.retrievalStartDate()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - IotHubDataConnection model = new IotHubDataConnection().withLocation("yhohujswtwkozzwc") - .withIotHubResourceId("seypxiutcxapz") - .withConsumerGroup("y") - .withTableName("etoge") - .withMappingRuleName("oxslh") - .withDataFormat(IotHubDataFormat.SOHSV) - .withEventSystemProperties(Arrays.asList("brqnkkzjcjb", "rgaehvvibrxjj", "toqbeitpkxztmoob")) - .withSharedAccessPolicyName("lftidgfcwqmpim") + IotHubDataConnection model = new IotHubDataConnection().withLocation("cjzhqi") + .withIotHubResourceId("alhsnvkc") + .withConsumerGroup("mxzrpoa") + .withTableName("lnwiaaomylwe") + .withMappingRuleName("ulcsethwwnpj") + .withDataFormat(IotHubDataFormat.JSON) + .withEventSystemProperties(Arrays.asList("wpchwahf", "ousnfepgfewe", "wlyxgncxyk", "hdjhlimmbcx")) + .withSharedAccessPolicyName("h") .withDatabaseRouting(DatabaseRouting.SINGLE) - .withRetrievalStartDate(OffsetDateTime.parse("2021-12-01T05:05:15Z")); + .withRetrievalStartDate(OffsetDateTime.parse("2021-08-24T02:48:56Z")); model = BinaryData.fromObject(model).toObject(IotHubDataConnection.class); - Assertions.assertEquals("yhohujswtwkozzwc", model.location()); - Assertions.assertEquals("seypxiutcxapz", model.iotHubResourceId()); - Assertions.assertEquals("y", model.consumerGroup()); - Assertions.assertEquals("etoge", model.tableName()); - Assertions.assertEquals("oxslh", model.mappingRuleName()); - Assertions.assertEquals(IotHubDataFormat.SOHSV, model.dataFormat()); - Assertions.assertEquals("brqnkkzjcjb", model.eventSystemProperties().get(0)); - Assertions.assertEquals("lftidgfcwqmpim", model.sharedAccessPolicyName()); + Assertions.assertEquals("cjzhqi", model.location()); + Assertions.assertEquals("alhsnvkc", model.iotHubResourceId()); + Assertions.assertEquals("mxzrpoa", model.consumerGroup()); + Assertions.assertEquals("lnwiaaomylwe", model.tableName()); + Assertions.assertEquals("ulcsethwwnpj", model.mappingRuleName()); + Assertions.assertEquals(IotHubDataFormat.JSON, model.dataFormat()); + Assertions.assertEquals("wpchwahf", model.eventSystemProperties().get(0)); + Assertions.assertEquals("h", model.sharedAccessPolicyName()); Assertions.assertEquals(DatabaseRouting.SINGLE, model.databaseRouting()); - Assertions.assertEquals(OffsetDateTime.parse("2021-12-01T05:05:15Z"), model.retrievalStartDate()); + Assertions.assertEquals(OffsetDateTime.parse("2021-08-24T02:48:56Z"), model.retrievalStartDate()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/LanguageExtensionsListTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/LanguageExtensionsListTests.java index 578abd76a399..a0fcab0c350e 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/LanguageExtensionsListTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/LanguageExtensionsListTests.java @@ -16,10 +16,10 @@ public final class LanguageExtensionsListTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { LanguageExtensionsList model = BinaryData.fromString( - "{\"value\":[{\"languageExtensionName\":\"R\",\"languageExtensionImageName\":\"Python3_10_8\",\"languageExtensionCustomImageName\":\"qtrgqjbpfzfsinzg\"},{\"languageExtensionName\":\"R\",\"languageExtensionImageName\":\"R\",\"languageExtensionCustomImageName\":\"zoxxjtf\"}]}") + "{\"value\":[{\"languageExtensionName\":\"R\",\"languageExtensionImageName\":\"Python3_11_7_DL\",\"languageExtensionCustomImageName\":\"qtrgqjbpfzfsinzg\"},{\"languageExtensionName\":\"R\",\"languageExtensionImageName\":\"Python3_11_7\",\"languageExtensionCustomImageName\":\"zoxxjtf\"}]}") .toObject(LanguageExtensionsList.class); Assertions.assertEquals(LanguageExtensionName.R, model.value().get(0).languageExtensionName()); - Assertions.assertEquals(LanguageExtensionImageName.PYTHON3_10_8, + Assertions.assertEquals(LanguageExtensionImageName.PYTHON3_11_7_DL, model.value().get(0).languageExtensionImageName()); Assertions.assertEquals("qtrgqjbpfzfsinzg", model.value().get(0).languageExtensionCustomImageName()); } @@ -28,14 +28,14 @@ public void testDeserialize() throws Exception { public void testSerialize() throws Exception { LanguageExtensionsList model = new LanguageExtensionsList().withValue(Arrays.asList( new LanguageExtensionInner().withLanguageExtensionName(LanguageExtensionName.R) - .withLanguageExtensionImageName(LanguageExtensionImageName.PYTHON3_10_8) + .withLanguageExtensionImageName(LanguageExtensionImageName.PYTHON3_11_7_DL) .withLanguageExtensionCustomImageName("qtrgqjbpfzfsinzg"), new LanguageExtensionInner().withLanguageExtensionName(LanguageExtensionName.R) - .withLanguageExtensionImageName(LanguageExtensionImageName.R) + .withLanguageExtensionImageName(LanguageExtensionImageName.PYTHON3_11_7) .withLanguageExtensionCustomImageName("zoxxjtf"))); model = BinaryData.fromObject(model).toObject(LanguageExtensionsList.class); Assertions.assertEquals(LanguageExtensionName.R, model.value().get(0).languageExtensionName()); - Assertions.assertEquals(LanguageExtensionImageName.PYTHON3_10_8, + Assertions.assertEquals(LanguageExtensionImageName.PYTHON3_11_7_DL, model.value().get(0).languageExtensionImageName()); Assertions.assertEquals("qtrgqjbpfzfsinzg", model.value().get(0).languageExtensionCustomImageName()); } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ListResourceSkusResultTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ListResourceSkusResultTests.java index e5c9e38d2578..4c88c8fa646f 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ListResourceSkusResultTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ListResourceSkusResultTests.java @@ -19,45 +19,45 @@ public final class ListResourceSkusResultTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ListResourceSkusResult model = BinaryData.fromString( - "{\"value\":[{\"resourceType\":\"qytjrybnwjewgd\",\"sku\":{\"name\":\"Standard_EC8ads_v5\",\"capacity\":1822878262,\"tier\":\"Standard\"},\"capacity\":{\"scaleType\":\"automatic\",\"minimum\":1214178064,\"maximum\":432099850,\"default\":282586156}},{\"resourceType\":\"hin\",\"sku\":{\"name\":\"Standard_L4s\",\"capacity\":412409909,\"tier\":\"Basic\"},\"capacity\":{\"scaleType\":\"automatic\",\"minimum\":1448466618,\"maximum\":372150678,\"default\":1092081926}}]}") + "{\"value\":[{\"resourceType\":\"uyfta\",\"sku\":{\"name\":\"Standard_L8s\",\"capacity\":1662588727,\"tier\":\"Standard\"},\"capacity\":{\"scaleType\":\"manual\",\"minimum\":1777343462,\"maximum\":842537299,\"default\":1814420357}},{\"resourceType\":\"nubexk\",\"sku\":{\"name\":\"Standard_L32as_v3\",\"capacity\":986433901,\"tier\":\"Basic\"},\"capacity\":{\"scaleType\":\"automatic\",\"minimum\":848558030,\"maximum\":1929847054,\"default\":1007666972}}]}") .toObject(ListResourceSkusResult.class); - Assertions.assertEquals("qytjrybnwjewgd", model.value().get(0).resourceType()); - Assertions.assertEquals(AzureSkuName.STANDARD_EC8ADS_V5, model.value().get(0).sku().name()); - Assertions.assertEquals(1822878262, model.value().get(0).sku().capacity()); + Assertions.assertEquals("uyfta", model.value().get(0).resourceType()); + Assertions.assertEquals(AzureSkuName.STANDARD_L8S, model.value().get(0).sku().name()); + Assertions.assertEquals(1662588727, model.value().get(0).sku().capacity()); Assertions.assertEquals(AzureSkuTier.STANDARD, model.value().get(0).sku().tier()); - Assertions.assertEquals(AzureScaleType.AUTOMATIC, model.value().get(0).capacity().scaleType()); - Assertions.assertEquals(1214178064, model.value().get(0).capacity().minimum()); - Assertions.assertEquals(432099850, model.value().get(0).capacity().maximum()); - Assertions.assertEquals(282586156, model.value().get(0).capacity().defaultProperty()); + Assertions.assertEquals(AzureScaleType.MANUAL, model.value().get(0).capacity().scaleType()); + Assertions.assertEquals(1777343462, model.value().get(0).capacity().minimum()); + Assertions.assertEquals(842537299, model.value().get(0).capacity().maximum()); + Assertions.assertEquals(1814420357, model.value().get(0).capacity().defaultProperty()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { ListResourceSkusResult model = new ListResourceSkusResult().withValue(Arrays.asList( - new AzureResourceSkuInner().withResourceType("qytjrybnwjewgd") - .withSku(new AzureSku().withName(AzureSkuName.STANDARD_EC8ADS_V5) - .withCapacity(1822878262) + new AzureResourceSkuInner().withResourceType("uyfta") + .withSku(new AzureSku().withName(AzureSkuName.STANDARD_L8S) + .withCapacity(1662588727) .withTier(AzureSkuTier.STANDARD)) - .withCapacity(new AzureCapacity().withScaleType(AzureScaleType.AUTOMATIC) - .withMinimum(1214178064) - .withMaximum(432099850) - .withDefaultProperty(282586156)), - new AzureResourceSkuInner().withResourceType("hin") - .withSku(new AzureSku().withName(AzureSkuName.STANDARD_L4S) - .withCapacity(412409909) + .withCapacity(new AzureCapacity().withScaleType(AzureScaleType.MANUAL) + .withMinimum(1777343462) + .withMaximum(842537299) + .withDefaultProperty(1814420357)), + new AzureResourceSkuInner().withResourceType("nubexk") + .withSku(new AzureSku().withName(AzureSkuName.STANDARD_L32AS_V3) + .withCapacity(986433901) .withTier(AzureSkuTier.BASIC)) .withCapacity(new AzureCapacity().withScaleType(AzureScaleType.AUTOMATIC) - .withMinimum(1448466618) - .withMaximum(372150678) - .withDefaultProperty(1092081926)))); + .withMinimum(848558030) + .withMaximum(1929847054) + .withDefaultProperty(1007666972)))); model = BinaryData.fromObject(model).toObject(ListResourceSkusResult.class); - Assertions.assertEquals("qytjrybnwjewgd", model.value().get(0).resourceType()); - Assertions.assertEquals(AzureSkuName.STANDARD_EC8ADS_V5, model.value().get(0).sku().name()); - Assertions.assertEquals(1822878262, model.value().get(0).sku().capacity()); + Assertions.assertEquals("uyfta", model.value().get(0).resourceType()); + Assertions.assertEquals(AzureSkuName.STANDARD_L8S, model.value().get(0).sku().name()); + Assertions.assertEquals(1662588727, model.value().get(0).sku().capacity()); Assertions.assertEquals(AzureSkuTier.STANDARD, model.value().get(0).sku().tier()); - Assertions.assertEquals(AzureScaleType.AUTOMATIC, model.value().get(0).capacity().scaleType()); - Assertions.assertEquals(1214178064, model.value().get(0).capacity().minimum()); - Assertions.assertEquals(432099850, model.value().get(0).capacity().maximum()); - Assertions.assertEquals(282586156, model.value().get(0).capacity().defaultProperty()); + Assertions.assertEquals(AzureScaleType.MANUAL, model.value().get(0).capacity().scaleType()); + Assertions.assertEquals(1777343462, model.value().get(0).capacity().minimum()); + Assertions.assertEquals(842537299, model.value().get(0).capacity().maximum()); + Assertions.assertEquals(1814420357, model.value().get(0).capacity().defaultProperty()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointInnerTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointInnerTests.java index 8a93113c27d4..97a618b8dc5c 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointInnerTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointInnerTests.java @@ -12,24 +12,25 @@ public final class ManagedPrivateEndpointInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ManagedPrivateEndpointInner model = BinaryData.fromString( - "{\"properties\":{\"privateLinkResourceId\":\"xbaaabjyv\",\"privateLinkResourceRegion\":\"ffimrzrtuzqogsex\",\"groupId\":\"evfdnwnwm\",\"requestMessage\":\"zsyyceuzso\",\"provisioningState\":\"Canceled\"},\"id\":\"dpfrxtrthzvaytdw\",\"name\":\"qbrqubpaxhexiili\",\"type\":\"pdtii\"}") + "{\"properties\":{\"privateLinkResourceId\":\"cslfaoqzpiyylha\",\"privateLinkResourceRegion\":\"swhccsphk\",\"groupId\":\"ivwitqscywugg\",\"requestMessage\":\"luhczbw\",\"provisioningState\":\"Deleting\"},\"id\":\"i\",\"name\":\"sbrgz\",\"type\":\"wmsweypqwd\"}") .toObject(ManagedPrivateEndpointInner.class); - Assertions.assertEquals("xbaaabjyv", model.privateLinkResourceId()); - Assertions.assertEquals("ffimrzrtuzqogsex", model.privateLinkResourceRegion()); - Assertions.assertEquals("evfdnwnwm", model.groupId()); - Assertions.assertEquals("zsyyceuzso", model.requestMessage()); + Assertions.assertEquals("cslfaoqzpiyylha", model.privateLinkResourceId()); + Assertions.assertEquals("swhccsphk", model.privateLinkResourceRegion()); + Assertions.assertEquals("ivwitqscywugg", model.groupId()); + Assertions.assertEquals("luhczbw", model.requestMessage()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - ManagedPrivateEndpointInner model = new ManagedPrivateEndpointInner().withPrivateLinkResourceId("xbaaabjyv") - .withPrivateLinkResourceRegion("ffimrzrtuzqogsex") - .withGroupId("evfdnwnwm") - .withRequestMessage("zsyyceuzso"); + ManagedPrivateEndpointInner model + = new ManagedPrivateEndpointInner().withPrivateLinkResourceId("cslfaoqzpiyylha") + .withPrivateLinkResourceRegion("swhccsphk") + .withGroupId("ivwitqscywugg") + .withRequestMessage("luhczbw"); model = BinaryData.fromObject(model).toObject(ManagedPrivateEndpointInner.class); - Assertions.assertEquals("xbaaabjyv", model.privateLinkResourceId()); - Assertions.assertEquals("ffimrzrtuzqogsex", model.privateLinkResourceRegion()); - Assertions.assertEquals("evfdnwnwm", model.groupId()); - Assertions.assertEquals("zsyyceuzso", model.requestMessage()); + Assertions.assertEquals("cslfaoqzpiyylha", model.privateLinkResourceId()); + Assertions.assertEquals("swhccsphk", model.privateLinkResourceRegion()); + Assertions.assertEquals("ivwitqscywugg", model.groupId()); + Assertions.assertEquals("luhczbw", model.requestMessage()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointListResultTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointListResultTests.java index 213060bdc3ab..d744c3b266a6 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointListResultTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointListResultTests.java @@ -14,25 +14,25 @@ public final class ManagedPrivateEndpointListResultTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ManagedPrivateEndpointListResult model = BinaryData.fromString( - "{\"value\":[{\"properties\":{\"privateLinkResourceId\":\"jhhyxxrwlycoduhp\",\"privateLinkResourceRegion\":\"kgymareqnajxqug\",\"groupId\":\"hky\",\"requestMessage\":\"beddgssofw\",\"provisioningState\":\"Running\"},\"id\":\"alkrmn\",\"name\":\"i\",\"type\":\"pxacqqudfn\"}]}") + "{\"value\":[{\"properties\":{\"privateLinkResourceId\":\"rdgrtw\",\"privateLinkResourceRegion\":\"nuuzkopbm\",\"groupId\":\"nrfdw\",\"requestMessage\":\"uhhziuiefozbhdm\",\"provisioningState\":\"Moving\"},\"id\":\"zqhof\",\"name\":\"rmaequ\",\"type\":\"ah\"}]}") .toObject(ManagedPrivateEndpointListResult.class); - Assertions.assertEquals("jhhyxxrwlycoduhp", model.value().get(0).privateLinkResourceId()); - Assertions.assertEquals("kgymareqnajxqug", model.value().get(0).privateLinkResourceRegion()); - Assertions.assertEquals("hky", model.value().get(0).groupId()); - Assertions.assertEquals("beddgssofw", model.value().get(0).requestMessage()); + Assertions.assertEquals("rdgrtw", model.value().get(0).privateLinkResourceId()); + Assertions.assertEquals("nuuzkopbm", model.value().get(0).privateLinkResourceRegion()); + Assertions.assertEquals("nrfdw", model.value().get(0).groupId()); + Assertions.assertEquals("uhhziuiefozbhdm", model.value().get(0).requestMessage()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { ManagedPrivateEndpointListResult model = new ManagedPrivateEndpointListResult() - .withValue(Arrays.asList(new ManagedPrivateEndpointInner().withPrivateLinkResourceId("jhhyxxrwlycoduhp") - .withPrivateLinkResourceRegion("kgymareqnajxqug") - .withGroupId("hky") - .withRequestMessage("beddgssofw"))); + .withValue(Arrays.asList(new ManagedPrivateEndpointInner().withPrivateLinkResourceId("rdgrtw") + .withPrivateLinkResourceRegion("nuuzkopbm") + .withGroupId("nrfdw") + .withRequestMessage("uhhziuiefozbhdm"))); model = BinaryData.fromObject(model).toObject(ManagedPrivateEndpointListResult.class); - Assertions.assertEquals("jhhyxxrwlycoduhp", model.value().get(0).privateLinkResourceId()); - Assertions.assertEquals("kgymareqnajxqug", model.value().get(0).privateLinkResourceRegion()); - Assertions.assertEquals("hky", model.value().get(0).groupId()); - Assertions.assertEquals("beddgssofw", model.value().get(0).requestMessage()); + Assertions.assertEquals("rdgrtw", model.value().get(0).privateLinkResourceId()); + Assertions.assertEquals("nuuzkopbm", model.value().get(0).privateLinkResourceRegion()); + Assertions.assertEquals("nrfdw", model.value().get(0).groupId()); + Assertions.assertEquals("uhhziuiefozbhdm", model.value().get(0).requestMessage()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointPropertiesTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointPropertiesTests.java index 7c9c70fc3022..e435e1360058 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointPropertiesTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointPropertiesTests.java @@ -12,24 +12,25 @@ public final class ManagedPrivateEndpointPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ManagedPrivateEndpointProperties model = BinaryData.fromString( - "{\"privateLinkResourceId\":\"q\",\"privateLinkResourceRegion\":\"qoaxoruzfgs\",\"groupId\":\"uyfxrxxleptramxj\",\"requestMessage\":\"wlwnwxuqlcv\",\"provisioningState\":\"Deleting\"}") + "{\"privateLinkResourceId\":\"ggicccnxqhue\",\"privateLinkResourceRegion\":\"ktt\",\"groupId\":\"stvlzywemhzrnc\",\"requestMessage\":\"tclusiypbsfgy\",\"provisioningState\":\"Succeeded\"}") .toObject(ManagedPrivateEndpointProperties.class); - Assertions.assertEquals("q", model.privateLinkResourceId()); - Assertions.assertEquals("qoaxoruzfgs", model.privateLinkResourceRegion()); - Assertions.assertEquals("uyfxrxxleptramxj", model.groupId()); - Assertions.assertEquals("wlwnwxuqlcv", model.requestMessage()); + Assertions.assertEquals("ggicccnxqhue", model.privateLinkResourceId()); + Assertions.assertEquals("ktt", model.privateLinkResourceRegion()); + Assertions.assertEquals("stvlzywemhzrnc", model.groupId()); + Assertions.assertEquals("tclusiypbsfgy", model.requestMessage()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - ManagedPrivateEndpointProperties model = new ManagedPrivateEndpointProperties().withPrivateLinkResourceId("q") - .withPrivateLinkResourceRegion("qoaxoruzfgs") - .withGroupId("uyfxrxxleptramxj") - .withRequestMessage("wlwnwxuqlcv"); + ManagedPrivateEndpointProperties model + = new ManagedPrivateEndpointProperties().withPrivateLinkResourceId("ggicccnxqhue") + .withPrivateLinkResourceRegion("ktt") + .withGroupId("stvlzywemhzrnc") + .withRequestMessage("tclusiypbsfgy"); model = BinaryData.fromObject(model).toObject(ManagedPrivateEndpointProperties.class); - Assertions.assertEquals("q", model.privateLinkResourceId()); - Assertions.assertEquals("qoaxoruzfgs", model.privateLinkResourceRegion()); - Assertions.assertEquals("uyfxrxxleptramxj", model.groupId()); - Assertions.assertEquals("wlwnwxuqlcv", model.requestMessage()); + Assertions.assertEquals("ggicccnxqhue", model.privateLinkResourceId()); + Assertions.assertEquals("ktt", model.privateLinkResourceRegion()); + Assertions.assertEquals("stvlzywemhzrnc", model.groupId()); + Assertions.assertEquals("tclusiypbsfgy", model.requestMessage()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsCheckNameAvailabilityWithResponseMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsCheckNameAvailabilityWithResponseMockTests.java index 634fc2d9d70e..bfa298cb6b85 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsCheckNameAvailabilityWithResponseMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsCheckNameAvailabilityWithResponseMockTests.java @@ -23,7 +23,7 @@ public final class ManagedPrivateEndpointsCheckNameAvailabilityWithResponseMockT @Test public void testCheckNameAvailabilityWithResponse() throws Exception { String responseStr - = "{\"nameAvailable\":true,\"name\":\"tzejetjklnt\",\"message\":\"yjuzkdb\",\"reason\":\"Invalid\"}"; + = "{\"nameAvailable\":true,\"name\":\"kglklbyulidwcw\",\"message\":\"zegjonfhjirwgdn\",\"reason\":\"Invalid\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -33,13 +33,13 @@ public void testCheckNameAvailabilityWithResponse() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); CheckNameResult response = manager.managedPrivateEndpoints() - .checkNameAvailabilityWithResponse("vlwyzg", "blkujrllfojuidjp", - new ManagedPrivateEndpointsCheckNameRequest().withName("uyjucejikzo"), com.azure.core.util.Context.NONE) + .checkNameAvailabilityWithResponse("vlnnpx", "b", + new ManagedPrivateEndpointsCheckNameRequest().withName("fiqgeaar"), com.azure.core.util.Context.NONE) .getValue(); Assertions.assertEquals(true, response.nameAvailable()); - Assertions.assertEquals("tzejetjklnt", response.name()); - Assertions.assertEquals("yjuzkdb", response.message()); + Assertions.assertEquals("kglklbyulidwcw", response.name()); + Assertions.assertEquals("zegjonfhjirwgdn", response.message()); Assertions.assertEquals(Reason.INVALID, response.reason()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsCheckNameRequestTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsCheckNameRequestTests.java index 1b75f136bb08..d58825039ac1 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsCheckNameRequestTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsCheckNameRequestTests.java @@ -12,15 +12,14 @@ public final class ManagedPrivateEndpointsCheckNameRequestTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ManagedPrivateEndpointsCheckNameRequest model - = BinaryData.fromString("{\"name\":\"ruoujmk\"}").toObject(ManagedPrivateEndpointsCheckNameRequest.class); - Assertions.assertEquals("ruoujmk", model.name()); + = BinaryData.fromString("{\"name\":\"fvmwy\"}").toObject(ManagedPrivateEndpointsCheckNameRequest.class); + Assertions.assertEquals("fvmwy", model.name()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - ManagedPrivateEndpointsCheckNameRequest model - = new ManagedPrivateEndpointsCheckNameRequest().withName("ruoujmk"); + ManagedPrivateEndpointsCheckNameRequest model = new ManagedPrivateEndpointsCheckNameRequest().withName("fvmwy"); model = BinaryData.fromObject(model).toObject(ManagedPrivateEndpointsCheckNameRequest.class); - Assertions.assertEquals("ruoujmk", model.name()); + Assertions.assertEquals("fvmwy", model.name()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsCreateOrUpdateMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsCreateOrUpdateMockTests.java index 8cd1c67107b2..13146aace051 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsCreateOrUpdateMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsCreateOrUpdateMockTests.java @@ -21,7 +21,7 @@ public final class ManagedPrivateEndpointsCreateOrUpdateMockTests { @Test public void testCreateOrUpdate() throws Exception { String responseStr - = "{\"properties\":{\"privateLinkResourceId\":\"wskondcbrwimuvqe\",\"privateLinkResourceRegion\":\"so\",\"groupId\":\"yrrleaesinuqt\",\"requestMessage\":\"qobbpihehcec\",\"provisioningState\":\"Succeeded\"},\"id\":\"qbr\",\"name\":\"bbmpxdlvykfre\",\"type\":\"crse\"}"; + = "{\"properties\":{\"privateLinkResourceId\":\"zgfbukklelssx\",\"privateLinkResourceRegion\":\"ycsxzu\",\"groupId\":\"ksrl\",\"requestMessage\":\"desqplpvmjcdo\",\"provisioningState\":\"Succeeded\"},\"id\":\"dyvt\",\"name\":\"owx\",\"type\":\"gpiudeug\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -31,17 +31,17 @@ public void testCreateOrUpdate() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); ManagedPrivateEndpoint response = manager.managedPrivateEndpoints() - .define("jcitdigsxcdglj") - .withExistingCluster("pzhz", "tk") - .withPrivateLinkResourceId("keuachtomf") - .withPrivateLinkResourceRegion("ytswfp") - .withGroupId("mdgycxn") - .withRequestMessage("kwhqj") + .define("ve") + .withExistingCluster("mlikytw", "czcswka") + .withPrivateLinkResourceId("fdv") + .withPrivateLinkResourceRegion("hbwrnfxtgddpqth") + .withGroupId("hn") + .withRequestMessage("aoyankcoeqswa") .create(); - Assertions.assertEquals("wskondcbrwimuvqe", response.privateLinkResourceId()); - Assertions.assertEquals("so", response.privateLinkResourceRegion()); - Assertions.assertEquals("yrrleaesinuqt", response.groupId()); - Assertions.assertEquals("qobbpihehcec", response.requestMessage()); + Assertions.assertEquals("zgfbukklelssx", response.privateLinkResourceId()); + Assertions.assertEquals("ycsxzu", response.privateLinkResourceRegion()); + Assertions.assertEquals("ksrl", response.groupId()); + Assertions.assertEquals("desqplpvmjcdo", response.requestMessage()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsDeleteMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsDeleteMockTests.java index c267b07e01a3..71aba3360d29 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsDeleteMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsDeleteMockTests.java @@ -27,7 +27,8 @@ public void testDelete() throws Exception { .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), new AzureProfile("", "", AzureEnvironment.AZURE)); - manager.managedPrivateEndpoints().delete("eg", "o", "fhjirwgdnqzbrfk", com.azure.core.util.Context.NONE); + manager.managedPrivateEndpoints() + .delete("awzovgkk", "muikjcjcaztbws", "sqowxwc", com.azure.core.util.Context.NONE); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsGetWithResponseMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsGetWithResponseMockTests.java index aa6dcca06775..0bacf58f09a1 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsGetWithResponseMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsGetWithResponseMockTests.java @@ -21,7 +21,7 @@ public final class ManagedPrivateEndpointsGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"privateLinkResourceId\":\"wvnph\",\"privateLinkResourceRegion\":\"zqtpjhmq\",\"groupId\":\"hvthlaiwdcxsm\",\"requestMessage\":\"zhzdtxetlgydlhqv\",\"provisioningState\":\"Running\"},\"id\":\"xybafiqgea\",\"name\":\"rbgjekglkl\",\"type\":\"yulidwcwvm\"}"; + = "{\"properties\":{\"privateLinkResourceId\":\"cecybmrqbrjbbmpx\",\"privateLinkResourceRegion\":\"vykfrexcrse\",\"groupId\":\"wjksghudgzhxo\",\"requestMessage\":\"ggsvoujkxibdaf\",\"provisioningState\":\"Creating\"},\"id\":\"dyomkxfbv\",\"name\":\"bhdyir\",\"type\":\"pwpgddei\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -31,12 +31,12 @@ public void testGetWithResponse() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); ManagedPrivateEndpoint response = manager.managedPrivateEndpoints() - .getWithResponse("vdulajv", "ejchcsrlz", "nmzlanru", com.azure.core.util.Context.NONE) + .getWithResponse("uvqejosovyrrle", "esi", "uqtljqobbpih", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("wvnph", response.privateLinkResourceId()); - Assertions.assertEquals("zqtpjhmq", response.privateLinkResourceRegion()); - Assertions.assertEquals("hvthlaiwdcxsm", response.groupId()); - Assertions.assertEquals("zhzdtxetlgydlhqv", response.requestMessage()); + Assertions.assertEquals("cecybmrqbrjbbmpx", response.privateLinkResourceId()); + Assertions.assertEquals("vykfrexcrse", response.privateLinkResourceRegion()); + Assertions.assertEquals("wjksghudgzhxo", response.groupId()); + Assertions.assertEquals("ggsvoujkxibdaf", response.requestMessage()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsListMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsListMockTests.java index 9bab26608d5b..db2614d1ec39 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsListMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ManagedPrivateEndpointsListMockTests.java @@ -22,7 +22,7 @@ public final class ManagedPrivateEndpointsListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"privateLinkResourceId\":\"rkolawjm\",\"privateLinkResourceRegion\":\"mwrokcdxfzzzwyja\",\"groupId\":\"itlhguyn\",\"requestMessage\":\"hlgmltxdwhmoz\",\"provisioningState\":\"Moving\"},\"id\":\"vlnsnnjz\",\"name\":\"pafolp\",\"type\":\"mwamxqzragpgdph\"}]}"; + = "{\"value\":[{\"properties\":{\"privateLinkResourceId\":\"cit\",\"privateLinkResourceRegion\":\"gsxcdgljplkeua\",\"groupId\":\"htomflrytswfp\",\"requestMessage\":\"dgycxnmskwhqjjy\",\"provisioningState\":\"Succeeded\"},\"id\":\"lpshhkvpedwqslsr\",\"name\":\"mpqvwwsk\",\"type\":\"ndcbrwi\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -32,11 +32,11 @@ public void testList() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); PagedIterable response - = manager.managedPrivateEndpoints().list("lxrzvhqjwtr", "tgvgzp", com.azure.core.util.Context.NONE); + = manager.managedPrivateEndpoints().list("rfkspzhz", "tk", com.azure.core.util.Context.NONE); - Assertions.assertEquals("rkolawjm", response.iterator().next().privateLinkResourceId()); - Assertions.assertEquals("mwrokcdxfzzzwyja", response.iterator().next().privateLinkResourceRegion()); - Assertions.assertEquals("itlhguyn", response.iterator().next().groupId()); - Assertions.assertEquals("hlgmltxdwhmoz", response.iterator().next().requestMessage()); + Assertions.assertEquals("cit", response.iterator().next().privateLinkResourceId()); + Assertions.assertEquals("gsxcdgljplkeua", response.iterator().next().privateLinkResourceRegion()); + Assertions.assertEquals("htomflrytswfp", response.iterator().next().groupId()); + Assertions.assertEquals("dgycxnmskwhqjjy", response.iterator().next().requestMessage()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/MigrationClusterPropertiesTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/MigrationClusterPropertiesTests.java index 5ae9999d7e32..aafcb8cf68ed 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/MigrationClusterPropertiesTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/MigrationClusterPropertiesTests.java @@ -12,7 +12,7 @@ public final class MigrationClusterPropertiesTests { public void testDeserialize() throws Exception { MigrationClusterProperties model = BinaryData .fromString( - "{\"id\":\"fmppe\",\"uri\":\"vmgxsab\",\"dataIngestionUri\":\"qduujitcjczdz\",\"role\":\"Source\"}") + "{\"id\":\"ltmrldh\",\"uri\":\"jzzd\",\"dataIngestionUri\":\"qxhocdgeablgphut\",\"role\":\"Source\"}") .toObject(MigrationClusterProperties.class); } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OperationDisplayTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OperationDisplayTests.java index ccef90eb8c23..a70a5eb08ace 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OperationDisplayTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OperationDisplayTests.java @@ -12,24 +12,24 @@ public final class OperationDisplayTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { OperationDisplay model = BinaryData.fromString( - "{\"provider\":\"oqytibyowbblgy\",\"operation\":\"utp\",\"resource\":\"joxoism\",\"description\":\"sbpimlq\"}") + "{\"provider\":\"dilmyww\",\"operation\":\"gkxnyedabg\",\"resource\":\"udtjuewbc\",\"description\":\"xuuwhcj\"}") .toObject(OperationDisplay.class); - Assertions.assertEquals("oqytibyowbblgy", model.provider()); - Assertions.assertEquals("utp", model.operation()); - Assertions.assertEquals("joxoism", model.resource()); - Assertions.assertEquals("sbpimlq", model.description()); + Assertions.assertEquals("dilmyww", model.provider()); + Assertions.assertEquals("gkxnyedabg", model.operation()); + Assertions.assertEquals("udtjuewbc", model.resource()); + Assertions.assertEquals("xuuwhcj", model.description()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - OperationDisplay model = new OperationDisplay().withProvider("oqytibyowbblgy") - .withOperation("utp") - .withResource("joxoism") - .withDescription("sbpimlq"); + OperationDisplay model = new OperationDisplay().withProvider("dilmyww") + .withOperation("gkxnyedabg") + .withResource("udtjuewbc") + .withDescription("xuuwhcj"); model = BinaryData.fromObject(model).toObject(OperationDisplay.class); - Assertions.assertEquals("oqytibyowbblgy", model.provider()); - Assertions.assertEquals("utp", model.operation()); - Assertions.assertEquals("joxoism", model.resource()); - Assertions.assertEquals("sbpimlq", model.description()); + Assertions.assertEquals("dilmyww", model.provider()); + Assertions.assertEquals("gkxnyedabg", model.operation()); + Assertions.assertEquals("udtjuewbc", model.resource()); + Assertions.assertEquals("xuuwhcj", model.description()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OperationInnerTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OperationInnerTests.java index a2a1d61fa4f9..2f3acd65ceb1 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OperationInnerTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OperationInnerTests.java @@ -13,31 +13,31 @@ public final class OperationInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { OperationInner model = BinaryData.fromString( - "{\"name\":\"vcyy\",\"display\":{\"provider\":\"gdotcubiipuipwo\",\"operation\":\"nmacj\",\"resource\":\"nizshqvcim\",\"description\":\"vfgmblrrilby\"},\"origin\":\"xsmiccwrwfscjf\",\"properties\":\"datanszqujiz\"}") + "{\"name\":\"katnwxyi\",\"display\":{\"provider\":\"dkqqfkuvscxkd\",\"operation\":\"igovi\",\"resource\":\"xk\",\"description\":\"loazuruocbgoo\"},\"origin\":\"te\",\"properties\":\"databfhjxakvvjgsl\"}") .toObject(OperationInner.class); - Assertions.assertEquals("vcyy", model.name()); - Assertions.assertEquals("gdotcubiipuipwo", model.display().provider()); - Assertions.assertEquals("nmacj", model.display().operation()); - Assertions.assertEquals("nizshqvcim", model.display().resource()); - Assertions.assertEquals("vfgmblrrilby", model.display().description()); - Assertions.assertEquals("xsmiccwrwfscjf", model.origin()); + Assertions.assertEquals("katnwxyi", model.name()); + Assertions.assertEquals("dkqqfkuvscxkd", model.display().provider()); + Assertions.assertEquals("igovi", model.display().operation()); + Assertions.assertEquals("xk", model.display().resource()); + Assertions.assertEquals("loazuruocbgoo", model.display().description()); + Assertions.assertEquals("te", model.origin()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - OperationInner model = new OperationInner().withName("vcyy") - .withDisplay(new OperationDisplay().withProvider("gdotcubiipuipwo") - .withOperation("nmacj") - .withResource("nizshqvcim") - .withDescription("vfgmblrrilby")) - .withOrigin("xsmiccwrwfscjf") - .withProperties("datanszqujiz"); + OperationInner model = new OperationInner().withName("katnwxyi") + .withDisplay(new OperationDisplay().withProvider("dkqqfkuvscxkd") + .withOperation("igovi") + .withResource("xk") + .withDescription("loazuruocbgoo")) + .withOrigin("te") + .withProperties("databfhjxakvvjgsl"); model = BinaryData.fromObject(model).toObject(OperationInner.class); - Assertions.assertEquals("vcyy", model.name()); - Assertions.assertEquals("gdotcubiipuipwo", model.display().provider()); - Assertions.assertEquals("nmacj", model.display().operation()); - Assertions.assertEquals("nizshqvcim", model.display().resource()); - Assertions.assertEquals("vfgmblrrilby", model.display().description()); - Assertions.assertEquals("xsmiccwrwfscjf", model.origin()); + Assertions.assertEquals("katnwxyi", model.name()); + Assertions.assertEquals("dkqqfkuvscxkd", model.display().provider()); + Assertions.assertEquals("igovi", model.display().operation()); + Assertions.assertEquals("xk", model.display().resource()); + Assertions.assertEquals("loazuruocbgoo", model.display().description()); + Assertions.assertEquals("te", model.origin()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OperationListResultTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OperationListResultTests.java index bf52d79dc5fb..371bc3b0acbd 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OperationListResultTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OperationListResultTests.java @@ -15,42 +15,49 @@ public final class OperationListResultTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { OperationListResult model = BinaryData.fromString( - "{\"value\":[{\"name\":\"bkwdlenrds\",\"display\":{\"provider\":\"jbazpjuohminy\",\"operation\":\"norwmduvwpklvx\",\"resource\":\"ygdxpgpqchis\",\"description\":\"pnnbjc\"},\"origin\":\"gibbdaxc\",\"properties\":\"datafozauorsuk\"},{\"name\":\"wbqpl\",\"display\":{\"provider\":\"nuuepzlrp\",\"operation\":\"zsoldwey\",\"resource\":\"dunvmnnrwrbiorkt\",\"description\":\"ywjhhgdnhx\"},\"origin\":\"ivfomiloxgg\",\"properties\":\"datafi\"}],\"nextLink\":\"dieuzaofj\"}") + "{\"value\":[{\"name\":\"cyyysfgdot\",\"display\":{\"provider\":\"iipuipwoqonm\",\"operation\":\"jeknizshq\",\"resource\":\"impevf\",\"description\":\"b\"},\"origin\":\"rilbywdx\",\"properties\":\"dataicc\"},{\"name\":\"wfscjfn\",\"display\":{\"provider\":\"zqujizdvoqytiby\",\"operation\":\"bblgyavut\",\"resource\":\"hjoxo\",\"description\":\"msksbp\"},\"origin\":\"lqol\",\"properties\":\"datakcgxxlxsffgcvi\"},{\"name\":\"zdwlvwlyoupfgfb\",\"display\":{\"provider\":\"bdyhgkfminsgowz\",\"operation\":\"tsttktlahbq\",\"resource\":\"tx\",\"description\":\"zukxitmmqtgqq\"},\"origin\":\"hrnxrxc\",\"properties\":\"datauisavokq\"}],\"nextLink\":\"fvazivjlfrqttba\"}") .toObject(OperationListResult.class); - Assertions.assertEquals("bkwdlenrds", model.value().get(0).name()); - Assertions.assertEquals("jbazpjuohminy", model.value().get(0).display().provider()); - Assertions.assertEquals("norwmduvwpklvx", model.value().get(0).display().operation()); - Assertions.assertEquals("ygdxpgpqchis", model.value().get(0).display().resource()); - Assertions.assertEquals("pnnbjc", model.value().get(0).display().description()); - Assertions.assertEquals("gibbdaxc", model.value().get(0).origin()); - Assertions.assertEquals("dieuzaofj", model.nextLink()); + Assertions.assertEquals("cyyysfgdot", model.value().get(0).name()); + Assertions.assertEquals("iipuipwoqonm", model.value().get(0).display().provider()); + Assertions.assertEquals("jeknizshq", model.value().get(0).display().operation()); + Assertions.assertEquals("impevf", model.value().get(0).display().resource()); + Assertions.assertEquals("b", model.value().get(0).display().description()); + Assertions.assertEquals("rilbywdx", model.value().get(0).origin()); + Assertions.assertEquals("fvazivjlfrqttba", model.nextLink()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { OperationListResult model = new OperationListResult().withValue(Arrays.asList( - new OperationInner().withName("bkwdlenrds") - .withDisplay(new OperationDisplay().withProvider("jbazpjuohminy") - .withOperation("norwmduvwpklvx") - .withResource("ygdxpgpqchis") - .withDescription("pnnbjc")) - .withOrigin("gibbdaxc") - .withProperties("datafozauorsuk"), - new OperationInner().withName("wbqpl") - .withDisplay(new OperationDisplay().withProvider("nuuepzlrp") - .withOperation("zsoldwey") - .withResource("dunvmnnrwrbiorkt") - .withDescription("ywjhhgdnhx")) - .withOrigin("ivfomiloxgg") - .withProperties("datafi"))) - .withNextLink("dieuzaofj"); + new OperationInner().withName("cyyysfgdot") + .withDisplay(new OperationDisplay().withProvider("iipuipwoqonm") + .withOperation("jeknizshq") + .withResource("impevf") + .withDescription("b")) + .withOrigin("rilbywdx") + .withProperties("dataicc"), + new OperationInner().withName("wfscjfn") + .withDisplay(new OperationDisplay().withProvider("zqujizdvoqytiby") + .withOperation("bblgyavut") + .withResource("hjoxo") + .withDescription("msksbp")) + .withOrigin("lqol") + .withProperties("datakcgxxlxsffgcvi"), + new OperationInner().withName("zdwlvwlyoupfgfb") + .withDisplay(new OperationDisplay().withProvider("bdyhgkfminsgowz") + .withOperation("tsttktlahbq") + .withResource("tx") + .withDescription("zukxitmmqtgqq")) + .withOrigin("hrnxrxc") + .withProperties("datauisavokq"))) + .withNextLink("fvazivjlfrqttba"); model = BinaryData.fromObject(model).toObject(OperationListResult.class); - Assertions.assertEquals("bkwdlenrds", model.value().get(0).name()); - Assertions.assertEquals("jbazpjuohminy", model.value().get(0).display().provider()); - Assertions.assertEquals("norwmduvwpklvx", model.value().get(0).display().operation()); - Assertions.assertEquals("ygdxpgpqchis", model.value().get(0).display().resource()); - Assertions.assertEquals("pnnbjc", model.value().get(0).display().description()); - Assertions.assertEquals("gibbdaxc", model.value().get(0).origin()); - Assertions.assertEquals("dieuzaofj", model.nextLink()); + Assertions.assertEquals("cyyysfgdot", model.value().get(0).name()); + Assertions.assertEquals("iipuipwoqonm", model.value().get(0).display().provider()); + Assertions.assertEquals("jeknizshq", model.value().get(0).display().operation()); + Assertions.assertEquals("impevf", model.value().get(0).display().resource()); + Assertions.assertEquals("b", model.value().get(0).display().description()); + Assertions.assertEquals("rilbywdx", model.value().get(0).origin()); + Assertions.assertEquals("fvazivjlfrqttba", model.nextLink()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OperationResultPropertiesTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OperationResultPropertiesTests.java index 61a6261b7be5..0b0243c7bf7a 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OperationResultPropertiesTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OperationResultPropertiesTests.java @@ -11,19 +11,20 @@ public final class OperationResultPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - OperationResultProperties model = BinaryData.fromString( - "{\"operationKind\":\"zfttsttktlahb\",\"provisioningState\":\"Creating\",\"operationState\":\"xtgzukxitmmqtgqq\"}") + OperationResultProperties model = BinaryData + .fromString( + "{\"operationKind\":\"abwidfcxsspuun\",\"provisioningState\":\"Failed\",\"operationState\":\"hkx\"}") .toObject(OperationResultProperties.class); - Assertions.assertEquals("zfttsttktlahb", model.operationKind()); - Assertions.assertEquals("xtgzukxitmmqtgqq", model.operationState()); + Assertions.assertEquals("abwidfcxsspuun", model.operationKind()); + Assertions.assertEquals("hkx", model.operationState()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { OperationResultProperties model - = new OperationResultProperties().withOperationKind("zfttsttktlahb").withOperationState("xtgzukxitmmqtgqq"); + = new OperationResultProperties().withOperationKind("abwidfcxsspuun").withOperationState("hkx"); model = BinaryData.fromObject(model).toObject(OperationResultProperties.class); - Assertions.assertEquals("zfttsttktlahb", model.operationKind()); - Assertions.assertEquals("xtgzukxitmmqtgqq", model.operationState()); + Assertions.assertEquals("abwidfcxsspuun", model.operationKind()); + Assertions.assertEquals("hkx", model.operationState()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OperationsListMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OperationsListMockTests.java index 01f4caa6d343..97aa831f8fba 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OperationsListMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OperationsListMockTests.java @@ -22,7 +22,7 @@ public final class OperationsListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"name\":\"rkphyjdxr\",\"display\":{\"provider\":\"uqd\",\"operation\":\"xmrgchbapxkiy\",\"resource\":\"j\",\"description\":\"ajb\"},\"origin\":\"cgduusio\",\"properties\":\"datablevpmcluj\"}]}"; + = "{\"value\":[{\"name\":\"shwddkvbxgk\",\"display\":{\"provider\":\"ybwptda\",\"operation\":\"rvv\",\"resource\":\"ntymtpoiwenazero\",\"description\":\"rs\"},\"origin\":\"lsxkd\",\"properties\":\"dataqapfgsdpc\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -33,11 +33,11 @@ public void testList() throws Exception { PagedIterable response = manager.operations().list(com.azure.core.util.Context.NONE); - Assertions.assertEquals("rkphyjdxr", response.iterator().next().name()); - Assertions.assertEquals("uqd", response.iterator().next().display().provider()); - Assertions.assertEquals("xmrgchbapxkiy", response.iterator().next().display().operation()); - Assertions.assertEquals("j", response.iterator().next().display().resource()); - Assertions.assertEquals("ajb", response.iterator().next().display().description()); - Assertions.assertEquals("cgduusio", response.iterator().next().origin()); + Assertions.assertEquals("shwddkvbxgk", response.iterator().next().name()); + Assertions.assertEquals("ybwptda", response.iterator().next().display().provider()); + Assertions.assertEquals("rvv", response.iterator().next().display().operation()); + Assertions.assertEquals("ntymtpoiwenazero", response.iterator().next().display().resource()); + Assertions.assertEquals("rs", response.iterator().next().display().description()); + Assertions.assertEquals("lsxkd", response.iterator().next().origin()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OperationsResultsLocationsGetWithResponseMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OperationsResultsLocationsGetWithResponseMockTests.java index a787272e3a04..df345ff23602 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OperationsResultsLocationsGetWithResponseMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OperationsResultsLocationsGetWithResponseMockTests.java @@ -27,7 +27,7 @@ public void testGetWithResponse() throws Exception { .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), new AzureProfile("", "", AzureEnvironment.AZURE)); - manager.operationsResultsLocations().getWithResponse("hvyeldotj", "dkwisw", com.azure.core.util.Context.NONE); + manager.operationsResultsLocations().getWithResponse("eimipskd", "zatvfuzka", com.azure.core.util.Context.NONE); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OutboundNetworkDependenciesEndpointInnerTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OutboundNetworkDependenciesEndpointInnerTests.java index 59727207ec26..85cfb4e1bbcf 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OutboundNetworkDependenciesEndpointInnerTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OutboundNetworkDependenciesEndpointInnerTests.java @@ -15,32 +15,36 @@ public final class OutboundNetworkDependenciesEndpointInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { OutboundNetworkDependenciesEndpointInner model = BinaryData.fromString( - "{\"properties\":{\"category\":\"o\",\"endpoints\":[{\"domainName\":\"jk\",\"endpointDetails\":[{\"port\":1604322971,\"ipAddress\":\"uwqlgzrfzeey\"},{\"port\":32622439,\"ipAddress\":\"ikayuhqlbjbsybb\"}]},{\"domainName\":\"r\",\"endpointDetails\":[{\"port\":1918019278,\"ipAddress\":\"fp\"},{\"port\":1408041355,\"ipAddress\":\"ipaslthaqfxssmwu\"},{\"port\":1363759065,\"ipAddress\":\"srezp\"}]}],\"provisioningState\":\"Creating\"},\"etag\":\"euyowqkd\",\"id\":\"ytisibir\",\"name\":\"gpikpzimejza\",\"type\":\"lfzxiavrmbzonoki\"}") + "{\"properties\":{\"category\":\"pcnp\",\"endpoints\":[{\"domainName\":\"a\",\"endpointDetails\":[{\"port\":171079627,\"ipAddress\":\"ccyajg\"}]},{\"domainName\":\"fhwygzlvdnkfxus\",\"endpointDetails\":[{\"port\":1095077901,\"ipAddress\":\"muhapfcqdpsqxqv\"},{\"port\":1014865004,\"ipAddress\":\"oymgccelvezr\"}]},{\"domainName\":\"qlmfeoker\",\"endpointDetails\":[{\"port\":553153301,\"ipAddress\":\"ob\"},{\"port\":1642208339,\"ipAddress\":\"edkowepbqpcrfk\"},{\"port\":1217910065,\"ipAddress\":\"snjvcdwxlpqekftn\"}]}],\"provisioningState\":\"Failed\"},\"etag\":\"syingwfqatmtdht\",\"id\":\"dvypgikdgsz\",\"name\":\"w\",\"type\":\"birryuzhl\"}") .toObject(OutboundNetworkDependenciesEndpointInner.class); - Assertions.assertEquals("o", model.category()); - Assertions.assertEquals("jk", model.endpoints().get(0).domainName()); - Assertions.assertEquals(1604322971, model.endpoints().get(0).endpointDetails().get(0).port()); - Assertions.assertEquals("uwqlgzrfzeey", model.endpoints().get(0).endpointDetails().get(0).ipAddress()); + Assertions.assertEquals("pcnp", model.category()); + Assertions.assertEquals("a", model.endpoints().get(0).domainName()); + Assertions.assertEquals(171079627, model.endpoints().get(0).endpointDetails().get(0).port()); + Assertions.assertEquals("ccyajg", model.endpoints().get(0).endpointDetails().get(0).ipAddress()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { OutboundNetworkDependenciesEndpointInner model - = new OutboundNetworkDependenciesEndpointInner().withCategory("o") - .withEndpoints(Arrays.asList( - new EndpointDependency().withDomainName("jk") - .withEndpointDetails(Arrays.asList( - new EndpointDetail().withPort(1604322971).withIpAddress("uwqlgzrfzeey"), - new EndpointDetail().withPort(32622439).withIpAddress("ikayuhqlbjbsybb"))), - new EndpointDependency().withDomainName("r") - .withEndpointDetails( - Arrays.asList(new EndpointDetail().withPort(1918019278).withIpAddress("fp"), - new EndpointDetail().withPort(1408041355).withIpAddress("ipaslthaqfxssmwu"), - new EndpointDetail().withPort(1363759065).withIpAddress("srezp"))))); + = new OutboundNetworkDependenciesEndpointInner().withCategory("pcnp") + .withEndpoints( + Arrays.asList( + new EndpointDependency().withDomainName("a") + .withEndpointDetails( + Arrays.asList(new EndpointDetail().withPort(171079627).withIpAddress("ccyajg"))), + new EndpointDependency().withDomainName("fhwygzlvdnkfxus") + .withEndpointDetails(Arrays.asList( + new EndpointDetail().withPort(1095077901).withIpAddress("muhapfcqdpsqxqv"), + new EndpointDetail().withPort(1014865004).withIpAddress("oymgccelvezr"))), + new EndpointDependency().withDomainName("qlmfeoker") + .withEndpointDetails( + Arrays.asList(new EndpointDetail().withPort(553153301).withIpAddress("ob"), + new EndpointDetail().withPort(1642208339).withIpAddress("edkowepbqpcrfk"), + new EndpointDetail().withPort(1217910065).withIpAddress("snjvcdwxlpqekftn"))))); model = BinaryData.fromObject(model).toObject(OutboundNetworkDependenciesEndpointInner.class); - Assertions.assertEquals("o", model.category()); - Assertions.assertEquals("jk", model.endpoints().get(0).domainName()); - Assertions.assertEquals(1604322971, model.endpoints().get(0).endpointDetails().get(0).port()); - Assertions.assertEquals("uwqlgzrfzeey", model.endpoints().get(0).endpointDetails().get(0).ipAddress()); + Assertions.assertEquals("pcnp", model.category()); + Assertions.assertEquals("a", model.endpoints().get(0).domainName()); + Assertions.assertEquals(171079627, model.endpoints().get(0).endpointDetails().get(0).port()); + Assertions.assertEquals("ccyajg", model.endpoints().get(0).endpointDetails().get(0).ipAddress()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OutboundNetworkDependenciesEndpointListResultTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OutboundNetworkDependenciesEndpointListResultTests.java index 57000a1f8620..6b74dd74c6b9 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OutboundNetworkDependenciesEndpointListResultTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OutboundNetworkDependenciesEndpointListResultTests.java @@ -16,28 +16,27 @@ public final class OutboundNetworkDependenciesEndpointListResultTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { OutboundNetworkDependenciesEndpointListResult model = BinaryData.fromString( - "{\"value\":[{\"properties\":{\"category\":\"fvpdbo\",\"endpoints\":[{\"domainName\":\"zsjqlh\",\"endpointDetails\":[{}]},{\"domainName\":\"bdeibqipqk\",\"endpointDetails\":[{},{}]},{\"domainName\":\"ndzwmkrefa\",\"endpointDetails\":[{},{},{},{}]},{\"domainName\":\"rwkq\",\"endpointDetails\":[{},{}]}],\"provisioningState\":\"Moving\"},\"etag\":\"j\",\"id\":\"jivfxzsjabib\",\"name\":\"ystawfsdjpvkvp\",\"type\":\"jxbkzbzkdvn\"}],\"nextLink\":\"abudurgk\"}") + "{\"value\":[{\"properties\":{\"category\":\"kwpjgwwspughftqs\",\"endpoints\":[{\"domainName\":\"ujxukndxd\",\"endpointDetails\":[{},{},{},{}]},{\"domainName\":\"guufzd\",\"endpointDetails\":[{},{}]},{\"domainName\":\"tfih\",\"endpointDetails\":[{},{},{},{}]}],\"provisioningState\":\"Canceled\"},\"etag\":\"ingamvp\",\"id\":\"ho\",\"name\":\"zqzudph\",\"type\":\"amvdkfwynwcvtbv\"}],\"nextLink\":\"yhmtnvyqiat\"}") .toObject(OutboundNetworkDependenciesEndpointListResult.class); - Assertions.assertEquals("fvpdbo", model.value().get(0).category()); - Assertions.assertEquals("zsjqlh", model.value().get(0).endpoints().get(0).domainName()); + Assertions.assertEquals("kwpjgwwspughftqs", model.value().get(0).category()); + Assertions.assertEquals("ujxukndxd", model.value().get(0).endpoints().get(0).domainName()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { OutboundNetworkDependenciesEndpointListResult model = new OutboundNetworkDependenciesEndpointListResult() - .withValue(Arrays.asList(new OutboundNetworkDependenciesEndpointInner().withCategory("fvpdbo") + .withValue(Arrays.asList(new OutboundNetworkDependenciesEndpointInner().withCategory("kwpjgwwspughftqs") .withEndpoints(Arrays.asList( - new EndpointDependency().withDomainName("zsjqlh") - .withEndpointDetails(Arrays.asList(new EndpointDetail())), - new EndpointDependency().withDomainName("bdeibqipqk") - .withEndpointDetails(Arrays.asList(new EndpointDetail(), new EndpointDetail())), - new EndpointDependency().withDomainName("ndzwmkrefa") + new EndpointDependency().withDomainName("ujxukndxd") .withEndpointDetails(Arrays.asList(new EndpointDetail(), new EndpointDetail(), new EndpointDetail(), new EndpointDetail())), - new EndpointDependency().withDomainName("rwkq") - .withEndpointDetails(Arrays.asList(new EndpointDetail(), new EndpointDetail())))))); + new EndpointDependency().withDomainName("guufzd") + .withEndpointDetails(Arrays.asList(new EndpointDetail(), new EndpointDetail())), + new EndpointDependency().withDomainName("tfih") + .withEndpointDetails(Arrays.asList(new EndpointDetail(), new EndpointDetail(), + new EndpointDetail(), new EndpointDetail())))))); model = BinaryData.fromObject(model).toObject(OutboundNetworkDependenciesEndpointListResult.class); - Assertions.assertEquals("fvpdbo", model.value().get(0).category()); - Assertions.assertEquals("zsjqlh", model.value().get(0).endpoints().get(0).domainName()); + Assertions.assertEquals("kwpjgwwspughftqs", model.value().get(0).category()); + Assertions.assertEquals("ujxukndxd", model.value().get(0).endpoints().get(0).domainName()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OutboundNetworkDependenciesEndpointPropertiesTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OutboundNetworkDependenciesEndpointPropertiesTests.java index 0589aa6e46d5..f2d4d48e5f1a 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OutboundNetworkDependenciesEndpointPropertiesTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/OutboundNetworkDependenciesEndpointPropertiesTests.java @@ -15,25 +15,27 @@ public final class OutboundNetworkDependenciesEndpointPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { OutboundNetworkDependenciesEndpointProperties model = BinaryData.fromString( - "{\"category\":\"jq\",\"endpoints\":[{\"domainName\":\"zpfrla\",\"endpointDetails\":[{\"port\":1822187571,\"ipAddress\":\"oiindfpwpjy\"}]}],\"provisioningState\":\"Moving\"}") + "{\"category\":\"joqrvqqaatj\",\"endpoints\":[{\"domainName\":\"goupmfiibfg\",\"endpointDetails\":[{\"port\":1249202476,\"ipAddress\":\"vrwxkv\"},{\"port\":46928565,\"ipAddress\":\"llqwjygvjayvblmh\"},{\"port\":1458242132,\"ipAddress\":\"hbxvvyhgsopbyrqu\"},{\"port\":175567556,\"ipAddress\":\"uvwzfbnh\"}]}],\"provisioningState\":\"Canceled\"}") .toObject(OutboundNetworkDependenciesEndpointProperties.class); - Assertions.assertEquals("jq", model.category()); - Assertions.assertEquals("zpfrla", model.endpoints().get(0).domainName()); - Assertions.assertEquals(1822187571, model.endpoints().get(0).endpointDetails().get(0).port()); - Assertions.assertEquals("oiindfpwpjy", model.endpoints().get(0).endpointDetails().get(0).ipAddress()); + Assertions.assertEquals("joqrvqqaatj", model.category()); + Assertions.assertEquals("goupmfiibfg", model.endpoints().get(0).domainName()); + Assertions.assertEquals(1249202476, model.endpoints().get(0).endpointDetails().get(0).port()); + Assertions.assertEquals("vrwxkv", model.endpoints().get(0).endpointDetails().get(0).ipAddress()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - OutboundNetworkDependenciesEndpointProperties model - = new OutboundNetworkDependenciesEndpointProperties().withCategory("jq") - .withEndpoints(Arrays.asList(new EndpointDependency().withDomainName("zpfrla") - .withEndpointDetails( - Arrays.asList(new EndpointDetail().withPort(1822187571).withIpAddress("oiindfpwpjy"))))); + OutboundNetworkDependenciesEndpointProperties model = new OutboundNetworkDependenciesEndpointProperties() + .withCategory("joqrvqqaatj") + .withEndpoints(Arrays.asList(new EndpointDependency().withDomainName("goupmfiibfg") + .withEndpointDetails(Arrays.asList(new EndpointDetail().withPort(1249202476).withIpAddress("vrwxkv"), + new EndpointDetail().withPort(46928565).withIpAddress("llqwjygvjayvblmh"), + new EndpointDetail().withPort(1458242132).withIpAddress("hbxvvyhgsopbyrqu"), + new EndpointDetail().withPort(175567556).withIpAddress("uvwzfbnh"))))); model = BinaryData.fromObject(model).toObject(OutboundNetworkDependenciesEndpointProperties.class); - Assertions.assertEquals("jq", model.category()); - Assertions.assertEquals("zpfrla", model.endpoints().get(0).domainName()); - Assertions.assertEquals(1822187571, model.endpoints().get(0).endpointDetails().get(0).port()); - Assertions.assertEquals("oiindfpwpjy", model.endpoints().get(0).endpointDetails().get(0).ipAddress()); + Assertions.assertEquals("joqrvqqaatj", model.category()); + Assertions.assertEquals("goupmfiibfg", model.endpoints().get(0).domainName()); + Assertions.assertEquals(1249202476, model.endpoints().get(0).endpointDetails().get(0).port()); + Assertions.assertEquals("vrwxkv", model.endpoints().get(0).endpointDetails().get(0).ipAddress()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionInnerTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionInnerTests.java index b549a5db1842..ae9823190aad 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionInnerTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionInnerTests.java @@ -13,19 +13,20 @@ public final class PrivateEndpointConnectionInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { PrivateEndpointConnectionInner model = BinaryData.fromString( - "{\"properties\":{\"privateEndpoint\":{\"id\":\"ayhuy\"},\"privateLinkServiceConnectionState\":{\"status\":\"kpode\",\"description\":\"oginuvamiheognar\",\"actionsRequired\":\"xth\"},\"groupId\":\"tusivyevcciqihn\",\"provisioningState\":\"ngbwjz\"},\"id\":\"fygxgispemvtzfk\",\"name\":\"fublj\",\"type\":\"fxqeof\"}") + "{\"properties\":{\"privateEndpoint\":{\"id\":\"arxzxtheot\"},\"privateLinkServiceConnectionState\":{\"status\":\"ivyevcciqihnhun\",\"description\":\"wjzrnfygxgisp\",\"actionsRequired\":\"vtz\"},\"groupId\":\"ufubl\",\"provisioningState\":\"fxqeof\"},\"id\":\"e\",\"name\":\"jhqjbasvmsmjqul\",\"type\":\"gsntnbybkzgcwr\"}") .toObject(PrivateEndpointConnectionInner.class); - Assertions.assertEquals("kpode", model.privateLinkServiceConnectionState().status()); - Assertions.assertEquals("oginuvamiheognar", model.privateLinkServiceConnectionState().description()); + Assertions.assertEquals("ivyevcciqihnhun", model.privateLinkServiceConnectionState().status()); + Assertions.assertEquals("wjzrnfygxgisp", model.privateLinkServiceConnectionState().description()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - PrivateEndpointConnectionInner model = new PrivateEndpointConnectionInner() - .withPrivateLinkServiceConnectionState(new PrivateLinkServiceConnectionStateProperty().withStatus("kpode") - .withDescription("oginuvamiheognar")); + PrivateEndpointConnectionInner model + = new PrivateEndpointConnectionInner().withPrivateLinkServiceConnectionState( + new PrivateLinkServiceConnectionStateProperty().withStatus("ivyevcciqihnhun") + .withDescription("wjzrnfygxgisp")); model = BinaryData.fromObject(model).toObject(PrivateEndpointConnectionInner.class); - Assertions.assertEquals("kpode", model.privateLinkServiceConnectionState().status()); - Assertions.assertEquals("oginuvamiheognar", model.privateLinkServiceConnectionState().description()); + Assertions.assertEquals("ivyevcciqihnhun", model.privateLinkServiceConnectionState().status()); + Assertions.assertEquals("wjzrnfygxgisp", model.privateLinkServiceConnectionState().description()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionListResultTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionListResultTests.java index f8f7cec5e3be..39e231454b30 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionListResultTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionListResultTests.java @@ -15,27 +15,25 @@ public final class PrivateEndpointConnectionListResultTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { PrivateEndpointConnectionListResult model = BinaryData.fromString( - "{\"value\":[{\"properties\":{\"privateEndpoint\":{\"id\":\"oa\"},\"privateLinkServiceConnectionState\":{\"status\":\"kniod\",\"description\":\"oebwnujhemms\",\"actionsRequired\":\"dkcrodt\"},\"groupId\":\"nfwjlfltkacjvefk\",\"provisioningState\":\"foakgg\"},\"id\":\"pagao\",\"name\":\"pulpqblylsyxk\",\"type\":\"jnsjervtiagxsd\"},{\"properties\":{\"privateEndpoint\":{\"id\":\"mpsbzkfzbeyv\"},\"privateLinkServiceConnectionState\":{\"status\":\"qi\",\"description\":\"invkjjxdxrbuu\",\"actionsRequired\":\"clewyhm\"},\"groupId\":\"paztzpofncck\",\"provisioningState\":\"fz\"},\"id\":\"hxx\",\"name\":\"uyqaxzfeqztppr\",\"type\":\"o\"},{\"properties\":{\"privateEndpoint\":{\"id\":\"jaltolmnc\"},\"privateLinkServiceConnectionState\":{\"status\":\"obqwcsdbnwdcfh\",\"description\":\"qdpfuvglsbjjca\",\"actionsRequired\":\"xbvtvudu\"},\"groupId\":\"cormr\",\"provisioningState\":\"qtvcofudflvkgj\"},\"id\":\"gdknnqv\",\"name\":\"aznqntoru\",\"type\":\"sgsahmkycgr\"},{\"properties\":{\"privateEndpoint\":{\"id\":\"uetae\"},\"privateLinkServiceConnectionState\":{\"status\":\"ruvdmov\",\"description\":\"zlxwabmqoefkifr\",\"actionsRequired\":\"puqujmqlgkfbtn\"},\"groupId\":\"aongbj\",\"provisioningState\":\"tujitcjedft\"},\"id\":\"ae\",\"name\":\"kojvd\",\"type\":\"pzfoqoui\"}]}") + "{\"value\":[{\"properties\":{\"privateEndpoint\":{\"id\":\"dcygqukyhejhz\"},\"privateLinkServiceConnectionState\":{\"status\":\"xgfpelolppv\",\"description\":\"r\",\"actionsRequired\":\"vu\"},\"groupId\":\"raehtwdwrft\",\"provisioningState\":\"iby\"},\"id\":\"dl\",\"name\":\"h\",\"type\":\"hfwpracstwit\"},{\"properties\":{\"privateEndpoint\":{\"id\":\"vxccedcp\"},\"privateLinkServiceConnectionState\":{\"status\":\"dyodnwzxltj\",\"description\":\"nhltiugcxn\",\"actionsRequired\":\"vwxqibyqunyo\"},\"groupId\":\"wlmdjrkv\",\"provisioningState\":\"bvfvpdbod\"},\"id\":\"izsjqlhkrr\",\"name\":\"bdeibqipqk\",\"type\":\"hvxndzwmkrefajpj\"},{\"properties\":{\"privateEndpoint\":{\"id\":\"qnyhgb\"},\"privateLinkServiceConnectionState\":{\"status\":\"tjivfxzsjabib\",\"description\":\"stawfsdjpvkv\",\"actionsRequired\":\"jxbkzbzkdvn\"},\"groupId\":\"abudurgk\",\"provisioningState\":\"mokzhjjklf\"},\"id\":\"mouwqlgzrfzeey\",\"name\":\"bizikayuhq\",\"type\":\"bjbsybb\"}]}") .toObject(PrivateEndpointConnectionListResult.class); - Assertions.assertEquals("kniod", model.value().get(0).privateLinkServiceConnectionState().status()); - Assertions.assertEquals("oebwnujhemms", model.value().get(0).privateLinkServiceConnectionState().description()); + Assertions.assertEquals("xgfpelolppv", model.value().get(0).privateLinkServiceConnectionState().status()); + Assertions.assertEquals("r", model.value().get(0).privateLinkServiceConnectionState().description()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { PrivateEndpointConnectionListResult model = new PrivateEndpointConnectionListResult().withValue(Arrays.asList( new PrivateEndpointConnectionInner().withPrivateLinkServiceConnectionState( - new PrivateLinkServiceConnectionStateProperty().withStatus("kniod").withDescription("oebwnujhemms")), + new PrivateLinkServiceConnectionStateProperty().withStatus("xgfpelolppv").withDescription("r")), new PrivateEndpointConnectionInner().withPrivateLinkServiceConnectionState( - new PrivateLinkServiceConnectionStateProperty().withStatus("qi").withDescription("invkjjxdxrbuu")), + new PrivateLinkServiceConnectionStateProperty().withStatus("dyodnwzxltj") + .withDescription("nhltiugcxn")), new PrivateEndpointConnectionInner().withPrivateLinkServiceConnectionState( - new PrivateLinkServiceConnectionStateProperty().withStatus("obqwcsdbnwdcfh") - .withDescription("qdpfuvglsbjjca")), - new PrivateEndpointConnectionInner().withPrivateLinkServiceConnectionState( - new PrivateLinkServiceConnectionStateProperty().withStatus("ruvdmov") - .withDescription("zlxwabmqoefkifr")))); + new PrivateLinkServiceConnectionStateProperty().withStatus("tjivfxzsjabib") + .withDescription("stawfsdjpvkv")))); model = BinaryData.fromObject(model).toObject(PrivateEndpointConnectionListResult.class); - Assertions.assertEquals("kniod", model.value().get(0).privateLinkServiceConnectionState().status()); - Assertions.assertEquals("oebwnujhemms", model.value().get(0).privateLinkServiceConnectionState().description()); + Assertions.assertEquals("xgfpelolppv", model.value().get(0).privateLinkServiceConnectionState().status()); + Assertions.assertEquals("r", model.value().get(0).privateLinkServiceConnectionState().description()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionPropertiesTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionPropertiesTests.java index fc936fb89ad9..dad5b025ab10 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionPropertiesTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionPropertiesTests.java @@ -13,19 +13,19 @@ public final class PrivateEndpointConnectionPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { PrivateEndpointConnectionProperties model = BinaryData.fromString( - "{\"privateEndpoint\":{\"id\":\"qjhqjbas\"},\"privateLinkServiceConnectionState\":{\"status\":\"smjqulngsntnbyb\",\"description\":\"gc\",\"actionsRequired\":\"wclxxwrl\"},\"groupId\":\"ouskcqvkocrc\",\"provisioningState\":\"kwt\"}") + "{\"privateEndpoint\":{\"id\":\"xxwr\"},\"privateLinkServiceConnectionState\":{\"status\":\"douskcqvkocrcjdk\",\"description\":\"nh\",\"actionsRequired\":\"njbiksqrglssain\"},\"groupId\":\"jwnzlljfmp\",\"provisioningState\":\"ebvmgxsabkyqd\"}") .toObject(PrivateEndpointConnectionProperties.class); - Assertions.assertEquals("smjqulngsntnbyb", model.privateLinkServiceConnectionState().status()); - Assertions.assertEquals("gc", model.privateLinkServiceConnectionState().description()); + Assertions.assertEquals("douskcqvkocrcjdk", model.privateLinkServiceConnectionState().status()); + Assertions.assertEquals("nh", model.privateLinkServiceConnectionState().description()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { PrivateEndpointConnectionProperties model = new PrivateEndpointConnectionProperties().withPrivateLinkServiceConnectionState( - new PrivateLinkServiceConnectionStateProperty().withStatus("smjqulngsntnbyb").withDescription("gc")); + new PrivateLinkServiceConnectionStateProperty().withStatus("douskcqvkocrcjdk").withDescription("nh")); model = BinaryData.fromObject(model).toObject(PrivateEndpointConnectionProperties.class); - Assertions.assertEquals("smjqulngsntnbyb", model.privateLinkServiceConnectionState().status()); - Assertions.assertEquals("gc", model.privateLinkServiceConnectionState().description()); + Assertions.assertEquals("douskcqvkocrcjdk", model.privateLinkServiceConnectionState().status()); + Assertions.assertEquals("nh", model.privateLinkServiceConnectionState().description()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsCreateOrUpdateMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsCreateOrUpdateMockTests.java index 713269fdc2f2..21f309c0c5e0 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsCreateOrUpdateMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsCreateOrUpdateMockTests.java @@ -22,7 +22,7 @@ public final class PrivateEndpointConnectionsCreateOrUpdateMockTests { @Test public void testCreateOrUpdate() throws Exception { String responseStr - = "{\"properties\":{\"privateEndpoint\":{\"id\":\"rweft\"},\"privateLinkServiceConnectionState\":{\"status\":\"qejpmvssehaepwa\",\"description\":\"xtczhupeuknijd\",\"actionsRequired\":\"yespydjfbocyv\"},\"groupId\":\"ulrtywikdmh\",\"provisioningState\":\"Succeeded\"},\"id\":\"uacdixmxuf\",\"name\":\"sryjqgdkfno\",\"type\":\"oeoq\"}"; + = "{\"properties\":{\"privateEndpoint\":{\"id\":\"gxyivpinbmh\"},\"privateLinkServiceConnectionState\":{\"status\":\"jijkgqxnhmbke\",\"description\":\"jauj\",\"actionsRequired\":\"annggiy\"},\"groupId\":\"kdtaaw\",\"provisioningState\":\"Succeeded\"},\"id\":\"umrrqmbzm\",\"name\":\"kratbnxwbj\",\"type\":\"idbirkfpkso\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -32,13 +32,13 @@ public void testCreateOrUpdate() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); PrivateEndpointConnection response = manager.privateEndpointConnections() - .define("ecmslclbl") - .withExistingCluster("uovmaonurjt", "mghihp") + .define("ukkutvl") + .withExistingCluster("yskbruff", "l") .withPrivateLinkServiceConnectionState( - new PrivateLinkServiceConnectionStateProperty().withStatus("gctmgxuupbezq").withDescription("ydrtc")) + new PrivateLinkServiceConnectionStateProperty().withStatus("hbcdsziry").withDescription("ndo")) .create(); - Assertions.assertEquals("qejpmvssehaepwa", response.privateLinkServiceConnectionState().status()); - Assertions.assertEquals("xtczhupeuknijd", response.privateLinkServiceConnectionState().description()); + Assertions.assertEquals("jijkgqxnhmbke", response.privateLinkServiceConnectionState().status()); + Assertions.assertEquals("jauj", response.privateLinkServiceConnectionState().description()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsDeleteMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsDeleteMockTests.java index c694ca56a828..6ae02f1816e4 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsDeleteMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsDeleteMockTests.java @@ -28,7 +28,7 @@ public void testDelete() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); manager.privateEndpointConnections() - .delete("etnjuhpsprkz", "aupia", "cxnafbwqrooh", com.azure.core.util.Context.NONE); + .delete("knyuxgvttxpn", "upzaamrdixtre", "ids", com.azure.core.util.Context.NONE); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsGetWithResponseMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsGetWithResponseMockTests.java index 5220465ba901..46340318efc8 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsGetWithResponseMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsGetWithResponseMockTests.java @@ -21,7 +21,7 @@ public final class PrivateEndpointConnectionsGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"privateEndpoint\":{\"id\":\"yctww\"},\"privateLinkServiceConnectionState\":{\"status\":\"wxjlmec\",\"description\":\"gygzyvn\",\"actionsRequired\":\"zaifghtmoqqtlff\"},\"groupId\":\"bkrkjj\",\"provisioningState\":\"vfqnvhnqoewdo\"},\"id\":\"yetesy\",\"name\":\"vidbztjhqtfb\",\"type\":\"vnynkb\"}"; + = "{\"properties\":{\"privateEndpoint\":{\"id\":\"mqkyojwyvfkmbts\"},\"privateLinkServiceConnectionState\":{\"status\":\"hxsgxj\",\"description\":\"mzrrscubiwsdrn\",\"actionsRequired\":\"qwodiffjx\"},\"groupId\":\"rmmuabwibvjo\",\"provisioningState\":\"onmcyefoyzb\"},\"id\":\"wine\",\"name\":\"fvfkak\",\"type\":\"oldtvevboclzhz\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -31,10 +31,10 @@ public void testGetWithResponse() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); PrivateEndpointConnection response = manager.privateEndpointConnections() - .getWithResponse("hiqfyuttdiy", "b", "vnwsw", com.azure.core.util.Context.NONE) + .getWithResponse("vjhvefgwbm", "jchnta", "faymxbulpz", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("wxjlmec", response.privateLinkServiceConnectionState().status()); - Assertions.assertEquals("gygzyvn", response.privateLinkServiceConnectionState().description()); + Assertions.assertEquals("hxsgxj", response.privateLinkServiceConnectionState().status()); + Assertions.assertEquals("mzrrscubiwsdrn", response.privateLinkServiceConnectionState().description()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsListMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsListMockTests.java index 703548f64110..c65f1a0b9703 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsListMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointConnectionsListMockTests.java @@ -22,7 +22,7 @@ public final class PrivateEndpointConnectionsListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"privateEndpoint\":{\"id\":\"wvqsgny\"},\"privateLinkServiceConnectionState\":{\"status\":\"uzivensrpmeyyvp\",\"description\":\"atlb\",\"actionsRequired\":\"pzgsk\"},\"groupId\":\"fhfv\",\"provisioningState\":\"mknbnxwcdommpv\"},\"id\":\"awz\",\"name\":\"gbrt\",\"type\":\"uiaclkiexhajlfn\"}]}"; + = "{\"value\":[{\"properties\":{\"privateEndpoint\":{\"id\":\"ehaepwamcxtc\"},\"privateLinkServiceConnectionState\":{\"status\":\"upeuknijduyye\",\"description\":\"ydjfb\",\"actionsRequired\":\"yv\"},\"groupId\":\"ulrtywikdmh\",\"provisioningState\":\"kuflgbh\"},\"id\":\"uacdixmxuf\",\"name\":\"sryjqgdkfno\",\"type\":\"oeoq\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -32,10 +32,10 @@ public void testList() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); PagedIterable response - = manager.privateEndpointConnections().list("ma", "lpdwwexymzvlazi", com.azure.core.util.Context.NONE); + = manager.privateEndpointConnections().list("stacsjvhrweftkwq", "jp", com.azure.core.util.Context.NONE); - Assertions.assertEquals("uzivensrpmeyyvp", + Assertions.assertEquals("upeuknijduyye", response.iterator().next().privateLinkServiceConnectionState().status()); - Assertions.assertEquals("atlb", response.iterator().next().privateLinkServiceConnectionState().description()); + Assertions.assertEquals("ydjfb", response.iterator().next().privateLinkServiceConnectionState().description()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointPropertyTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointPropertyTests.java index c7b4974a2a18..dcb095974c12 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointPropertyTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateEndpointPropertyTests.java @@ -11,7 +11,7 @@ public final class PrivateEndpointPropertyTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { PrivateEndpointProperty model - = BinaryData.fromString("{\"id\":\"xbnjbiksq\"}").toObject(PrivateEndpointProperty.class); + = BinaryData.fromString("{\"id\":\"jitcjczdzevn\"}").toObject(PrivateEndpointProperty.class); } @org.junit.jupiter.api.Test diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateLinkResourceInnerTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateLinkResourceInnerTests.java index f03241a51d5f..145356ecbbbd 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateLinkResourceInnerTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateLinkResourceInnerTests.java @@ -11,7 +11,7 @@ public final class PrivateLinkResourceInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { PrivateLinkResourceInner model = BinaryData.fromString( - "{\"properties\":{\"groupId\":\"xgfpelolppv\",\"requiredMembers\":[\"pqvujzraehtwdwrf\"],\"requiredZoneNames\":[\"iby\"]},\"id\":\"dl\",\"name\":\"h\",\"type\":\"hfwpracstwit\"}") + "{\"properties\":{\"groupId\":\"zimejzanlfzx\",\"requiredMembers\":[\"rmbzo\",\"okixrjqcir\"],\"requiredZoneNames\":[\"frl\",\"zszrnwoiindfpw\"]},\"id\":\"ylwbtlhflsjcdhsz\",\"name\":\"jvfbgofelja\",\"type\":\"rqmq\"}") .toObject(PrivateLinkResourceInner.class); } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateLinkResourceListResultTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateLinkResourceListResultTests.java index f8e7bd0aee0c..7d20eb7cf4ea 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateLinkResourceListResultTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateLinkResourceListResultTests.java @@ -13,15 +13,14 @@ public final class PrivateLinkResourceListResultTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { PrivateLinkResourceListResult model = BinaryData.fromString( - "{\"value\":[{\"properties\":{\"groupId\":\"rzgszufoxci\",\"requiredMembers\":[\"idoamciodhkha\"],\"requiredZoneNames\":[\"hnzbonl\",\"ntoe\",\"okdwb\"]},\"id\":\"kszzcmrvexztv\",\"name\":\"t\",\"type\":\"gsfraoyzkoow\"},{\"properties\":{\"groupId\":\"nguxawqaldsy\",\"requiredMembers\":[\"imerqfobwyznk\",\"ykutwpf\",\"pagmhrskdsnf\",\"sd\"],\"requiredZoneNames\":[\"gtdlmk\",\"zev\",\"l\"]},\"id\":\"wpusdsttwvogv\",\"name\":\"bejdcn\",\"type\":\"qqmoaku\"},{\"properties\":{\"groupId\":\"jzrwrdgrtw\",\"requiredMembers\":[\"u\",\"zkopb\",\"inrfdwoyu\"],\"requiredZoneNames\":[\"iuiefozbhdmsm\",\"mzqhoftrmaequi\",\"hxicslfaoqz\"]},\"id\":\"yylhalnswhccsp\",\"name\":\"kaivwit\",\"type\":\"scywuggwoluhc\"},{\"properties\":{\"groupId\":\"emh\",\"requiredMembers\":[\"sbrgz\",\"wmsweypqwd\",\"ggicccnxqhue\"],\"requiredZoneNames\":[\"ttlstvlzywemhz\"]},\"id\":\"csdtclusiypbs\",\"name\":\"gytguslfead\",\"type\":\"ygqukyhejh\"}]}") + "{\"value\":[{\"properties\":{\"groupId\":\"ldgmfpgvmpip\",\"requiredMembers\":[\"thaqfxssmwu\"],\"requiredZoneNames\":[\"dsrezpdrhneuyow\",\"kdw\"]},\"id\":\"i\",\"name\":\"ib\",\"type\":\"rcgp\"}]}") .toObject(PrivateLinkResourceListResult.class); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { PrivateLinkResourceListResult model - = new PrivateLinkResourceListResult().withValue(Arrays.asList(new PrivateLinkResourceInner(), - new PrivateLinkResourceInner(), new PrivateLinkResourceInner(), new PrivateLinkResourceInner())); + = new PrivateLinkResourceListResult().withValue(Arrays.asList(new PrivateLinkResourceInner())); model = BinaryData.fromObject(model).toObject(PrivateLinkResourceListResult.class); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateLinkResourcePropertiesTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateLinkResourcePropertiesTests.java index 9a5b11532788..3bcc9f236c69 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateLinkResourcePropertiesTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateLinkResourcePropertiesTests.java @@ -11,7 +11,7 @@ public final class PrivateLinkResourcePropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { PrivateLinkResourceProperties model = BinaryData.fromString( - "{\"groupId\":\"hevxcced\",\"requiredMembers\":[\"md\",\"odn\",\"zxltjcvn\"],\"requiredZoneNames\":[\"iugcxnavvwxq\",\"byqunyow\",\"wlmdjrkv\"]}") + "{\"groupId\":\"dvriiiojnal\",\"requiredMembers\":[\"kvtvsexso\"],\"requiredZoneNames\":[\"luqhhahhxv\"]}") .toObject(PrivateLinkResourceProperties.class); } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateLinkResourcesGetWithResponseMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateLinkResourcesGetWithResponseMockTests.java index c6462a44130a..9eac7ae354f3 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateLinkResourcesGetWithResponseMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateLinkResourcesGetWithResponseMockTests.java @@ -20,7 +20,7 @@ public final class PrivateLinkResourcesGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"groupId\":\"hzjkn\",\"requiredMembers\":[\"gvttx\",\"nrup\"],\"requiredZoneNames\":[\"mrdixtreki\",\"swyskbruffg\",\"lukkutvlxhrpqhvm\",\"lcouqehbhbcdszir\"]},\"id\":\"an\",\"name\":\"oypmbltoorm\",\"type\":\"fqlwxldykalsy\"}"; + = "{\"properties\":{\"groupId\":\"xj\",\"requiredMembers\":[\"cmpzqjhhhqx\"],\"requiredZoneNames\":[\"vcacoyv\"]},\"id\":\"bsizus\",\"name\":\"szlbscm\",\"type\":\"lzijiufehgmvflnw\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -30,7 +30,7 @@ public void testGetWithResponse() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); PrivateLinkResource response = manager.privateLinkResources() - .getWithResponse("e", "oyzbamwineofvf", "akpoldtvevbo", com.azure.core.util.Context.NONE) + .getWithResponse("ypsjoq", "jenkyh", "qzvs", com.azure.core.util.Context.NONE) .getValue(); } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateLinkResourcesListMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateLinkResourcesListMockTests.java index dfe67d707250..97c832a25d8a 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateLinkResourcesListMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateLinkResourcesListMockTests.java @@ -21,7 +21,7 @@ public final class PrivateLinkResourcesListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"groupId\":\"ymxbulpzealb\",\"requiredMembers\":[\"yojwyvfkmbtsu\",\"hxsgxj\",\"mmzrrscub\"],\"requiredZoneNames\":[\"drnpxqwodiff\"]},\"id\":\"cjrmmua\",\"name\":\"wibvjogj\",\"type\":\"nmc\"}]}"; + = "{\"value\":[{\"properties\":{\"groupId\":\"yewnfnzhhhqos\",\"requiredMembers\":[\"jkutycyarnr\",\"ohguabz\",\"ghktdpy\",\"z\"],\"requiredZoneNames\":[\"eocnhzqrottj\",\"cfyjzp\",\"wrlohapqinfszpyg\"]},\"id\":\"d\",\"name\":\"mrjzral\",\"type\":\"xpjb\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -31,7 +31,7 @@ public void testList() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); PagedIterable response - = manager.privateLinkResources().list("vjhvefgwbm", "jchnta", com.azure.core.util.Context.NONE); + = manager.privateLinkResources().list("dgo", "ewijymrhbguz", com.azure.core.util.Context.NONE); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateLinkServiceConnectionStatePropertyTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateLinkServiceConnectionStatePropertyTests.java index 3a943f68d8a3..5b90842d7da8 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateLinkServiceConnectionStatePropertyTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/PrivateLinkServiceConnectionStatePropertyTests.java @@ -11,19 +11,19 @@ public final class PrivateLinkServiceConnectionStatePropertyTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - PrivateLinkServiceConnectionStateProperty model - = BinaryData.fromString("{\"status\":\"lssai\",\"description\":\"p\",\"actionsRequired\":\"nzl\"}") - .toObject(PrivateLinkServiceConnectionStateProperty.class); - Assertions.assertEquals("lssai", model.status()); - Assertions.assertEquals("p", model.description()); + PrivateLinkServiceConnectionStateProperty model = BinaryData + .fromString("{\"status\":\"krwpdap\",\"description\":\"sbdkvwr\",\"actionsRequired\":\"feusnhut\"}") + .toObject(PrivateLinkServiceConnectionStateProperty.class); + Assertions.assertEquals("krwpdap", model.status()); + Assertions.assertEquals("sbdkvwr", model.description()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { PrivateLinkServiceConnectionStateProperty model - = new PrivateLinkServiceConnectionStateProperty().withStatus("lssai").withDescription("p"); + = new PrivateLinkServiceConnectionStateProperty().withStatus("krwpdap").withDescription("sbdkvwr"); model = BinaryData.fromObject(model).toObject(PrivateLinkServiceConnectionStateProperty.class); - Assertions.assertEquals("lssai", model.status()); - Assertions.assertEquals("p", model.description()); + Assertions.assertEquals("krwpdap", model.status()); + Assertions.assertEquals("sbdkvwr", model.description()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ReadOnlyFollowingDatabasePropertiesTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ReadOnlyFollowingDatabasePropertiesTests.java index cc065e5389f1..ec465dc58298 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ReadOnlyFollowingDatabasePropertiesTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ReadOnlyFollowingDatabasePropertiesTests.java @@ -13,16 +13,16 @@ public final class ReadOnlyFollowingDatabasePropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ReadOnlyFollowingDatabaseProperties model = BinaryData.fromString( - "{\"provisioningState\":\"Succeeded\",\"softDeletePeriod\":\"PT117H46M54S\",\"hotCachePeriod\":\"PT191H20M49S\",\"statistics\":{\"size\":33.585636},\"leaderClusterResourceId\":\"fku\",\"attachedDatabaseConfigurationName\":\"cxkdmligovi\",\"principalsModificationKind\":\"Replace\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"loazuruocbgoo\",\"bteoybf\"],\"tablesToExclude\":[\"akvvjgslordi\",\"mywwtkgkxnyed\",\"b\"],\"externalTablesToInclude\":[\"udtjuewbc\",\"hxuuwhcjyxccybvp\",\"yakk\",\"dzpxgwjpl\"],\"externalTablesToExclude\":[\"stcyohpfkyrkdbd\",\"iogsjkmnwq\",\"nobaiyhddviacegf\"],\"materializedViewsToInclude\":[\"tfpmvmemfnczdw\",\"vbalxlllc\",\"podbzevwrdnh\"],\"materializedViewsToExclude\":[\"uvsj\",\"swsmys\",\"uluqypfc\"],\"functionsToInclude\":[\"rchpqbmfpjbabwid\"],\"functionsToExclude\":[\"sspuunnoxyhkx\",\"qddrihpfhoqcaae\",\"dao\",\"djvlpj\"]},\"originalDatabaseName\":\"kzbrmsgeivsiy\",\"databaseShareOrigin\":\"DataShare\",\"suspensionDetails\":{\"suspensionStartDate\":\"2021-08-20T00:02:05Z\"}}") + "{\"provisioningState\":\"Canceled\",\"softDeletePeriod\":\"PT133H19M40S\",\"hotCachePeriod\":\"PT125H19M50S\",\"statistics\":{\"size\":27.006971},\"leaderClusterResourceId\":\"dncj\",\"attachedDatabaseConfigurationName\":\"onbzoggculapzwy\",\"principalsModificationKind\":\"None\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"qxepnylbfuaj\",\"yjt\"],\"tablesToExclude\":[\"fqzhv\"],\"externalTablesToInclude\":[\"byfmowuxr\",\"jpvd\"],\"externalTablesToExclude\":[\"zwiivwzjbhyzs\",\"jrkambtrnegvmnv\",\"q\",\"qvldspastjbkkd\"],\"materializedViewsToInclude\":[\"vestmjl\"],\"materializedViewsToExclude\":[\"ilozapeewchpxlk\"],\"functionsToInclude\":[\"uziycsl\",\"vu\",\"uztcktyhjtqed\"],\"functionsToExclude\":[\"ulwm\",\"rqzz\",\"rjvpglydzgkrvqee\",\"toepryu\"]},\"originalDatabaseName\":\"wytpzdmovz\",\"databaseShareOrigin\":\"Direct\",\"suspensionDetails\":{\"suspensionStartDate\":\"2021-06-08T04:09:14Z\"}}") .toObject(ReadOnlyFollowingDatabaseProperties.class); - Assertions.assertEquals(Duration.parse("PT191H20M49S"), model.hotCachePeriod()); + Assertions.assertEquals(Duration.parse("PT125H19M50S"), model.hotCachePeriod()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { ReadOnlyFollowingDatabaseProperties model - = new ReadOnlyFollowingDatabaseProperties().withHotCachePeriod(Duration.parse("PT191H20M49S")); + = new ReadOnlyFollowingDatabaseProperties().withHotCachePeriod(Duration.parse("PT125H19M50S")); model = BinaryData.fromObject(model).toObject(ReadOnlyFollowingDatabaseProperties.class); - Assertions.assertEquals(Duration.parse("PT191H20M49S"), model.hotCachePeriod()); + Assertions.assertEquals(Duration.parse("PT125H19M50S"), model.hotCachePeriod()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ReadOnlyFollowingDatabaseTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ReadOnlyFollowingDatabaseTests.java index de0cf1c49b17..65ce216d68ee 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ReadOnlyFollowingDatabaseTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ReadOnlyFollowingDatabaseTests.java @@ -13,18 +13,18 @@ public final class ReadOnlyFollowingDatabaseTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ReadOnlyFollowingDatabase model = BinaryData.fromString( - "{\"kind\":\"ReadOnlyFollowing\",\"properties\":{\"provisioningState\":\"Succeeded\",\"softDeletePeriod\":\"PT189H4M16S\",\"hotCachePeriod\":\"PT238H46M6S\",\"statistics\":{\"size\":94.85628},\"leaderClusterResourceId\":\"kynscliqhzv\",\"attachedDatabaseConfigurationName\":\"nk\",\"principalsModificationKind\":\"None\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"otppnv\"],\"tablesToExclude\":[\"xhihfrbbcevqagtl\"],\"externalTablesToInclude\":[\"lfkqojpy\",\"vgtrdcnifmzzs\",\"ymbrnysuxmpraf\"],\"externalTablesToExclude\":[\"khocxvdfffwaf\"],\"materializedViewsToInclude\":[\"udaspavehh\",\"vkbunzozudh\",\"xg\",\"moy\"],\"materializedViewsToExclude\":[\"yuibhm\",\"dnbzydvfvfcjn\"],\"functionsToInclude\":[\"isrvhm\",\"orffukiscv\",\"mzhwplefaxvxi\",\"cbtgnhnz\"],\"functionsToExclude\":[\"xtjjfzqlqhycav\",\"dggxdbeesmi\",\"knlrariaawiuagy\",\"wqfbylyrfgiagt\"]},\"originalDatabaseName\":\"jocqwogfnzjvusf\",\"databaseShareOrigin\":\"Direct\",\"suspensionDetails\":{\"suspensionStartDate\":\"2021-08-30T15:20:16Z\"}},\"location\":\"xylfsb\",\"id\":\"kadpysown\",\"name\":\"tgkbugrjqctojc\",\"type\":\"isofieypefojyqd\"}") + "{\"kind\":\"ReadOnlyFollowing\",\"properties\":{\"provisioningState\":\"Creating\",\"softDeletePeriod\":\"PT175H34M27S\",\"hotCachePeriod\":\"PT40H32M34S\",\"statistics\":{\"size\":39.45976},\"leaderClusterResourceId\":\"ilcbtgnhnzeyqxtj\",\"attachedDatabaseConfigurationName\":\"zqlqhyc\",\"principalsModificationKind\":\"Union\",\"tableLevelSharingProperties\":{\"tablesToInclude\":[\"xdbeesmieknl\",\"ariaawi\",\"agy\"],\"tablesToExclude\":[\"fbylyrfg\"],\"externalTablesToInclude\":[\"tcojocqwo\",\"fnzjvusfzldm\",\"zuxylfsbtkadpyso\"],\"externalTablesToExclude\":[\"tgkbugrjqctojc\",\"isofieypefojyqd\",\"cuplcplcwkhih\",\"hlhzdsqtzbsrgno\"],\"materializedViewsToInclude\":[\"hfgmvecactxm\"],\"materializedViewsToExclude\":[\"e\",\"owcluqo\"],\"functionsToInclude\":[\"qvgqouw\",\"fzmpjwyivq\"],\"functionsToExclude\":[\"xcvhrfs\"]},\"originalDatabaseName\":\"uagrttikteusqc\",\"databaseShareOrigin\":\"Direct\",\"suspensionDetails\":{\"suspensionStartDate\":\"2021-07-05T09:11:28Z\"}},\"location\":\"ubyjaffmmf\",\"id\":\"lcqcuubgqibrt\",\"name\":\"lmetttwgdslqxi\",\"type\":\"hrmooi\"}") .toObject(ReadOnlyFollowingDatabase.class); - Assertions.assertEquals("xylfsb", model.location()); - Assertions.assertEquals(Duration.parse("PT238H46M6S"), model.hotCachePeriod()); + Assertions.assertEquals("ubyjaffmmf", model.location()); + Assertions.assertEquals(Duration.parse("PT40H32M34S"), model.hotCachePeriod()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - ReadOnlyFollowingDatabase model - = new ReadOnlyFollowingDatabase().withLocation("xylfsb").withHotCachePeriod(Duration.parse("PT238H46M6S")); + ReadOnlyFollowingDatabase model = new ReadOnlyFollowingDatabase().withLocation("ubyjaffmmf") + .withHotCachePeriod(Duration.parse("PT40H32M34S")); model = BinaryData.fromObject(model).toObject(ReadOnlyFollowingDatabase.class); - Assertions.assertEquals("xylfsb", model.location()); - Assertions.assertEquals(Duration.parse("PT238H46M6S"), model.hotCachePeriod()); + Assertions.assertEquals("ubyjaffmmf", model.location()); + Assertions.assertEquals(Duration.parse("PT40H32M34S"), model.hotCachePeriod()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ResourceSkuCapabilitiesTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ResourceSkuCapabilitiesTests.java index 98b079f582c1..3e82afeaa9bc 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ResourceSkuCapabilitiesTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ResourceSkuCapabilitiesTests.java @@ -11,7 +11,8 @@ public final class ResourceSkuCapabilitiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ResourceSkuCapabilities model - = BinaryData.fromString("{\"name\":\"bsrfbj\",\"value\":\"twss\"}").toObject(ResourceSkuCapabilities.class); + = BinaryData.fromString("{\"name\":\"nhdldwmgxcx\",\"value\":\"lpmutwuoegrpkhj\"}") + .toObject(ResourceSkuCapabilities.class); } @org.junit.jupiter.api.Test diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ResourceSkuZoneDetailsTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ResourceSkuZoneDetailsTests.java index ba30b3903d04..afc42ab78d21 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ResourceSkuZoneDetailsTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ResourceSkuZoneDetailsTests.java @@ -11,7 +11,7 @@ public final class ResourceSkuZoneDetailsTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ResourceSkuZoneDetails model = BinaryData.fromString( - "{\"name\":[\"dxxiv\",\"tvtc\",\"aqtdoqmcbx\",\"wvxysl\"],\"capabilities\":[{\"name\":\"fxoblytkb\",\"value\":\"pe\"},{\"name\":\"wfbkrvrns\",\"value\":\"hqjohxcrsbfova\"},{\"name\":\"ruvw\",\"value\":\"sqfsubcgjbirxb\"}]}") + "{\"name\":[\"wqapnedgfbcvk\"],\"capabilities\":[{\"name\":\"pkeqdcvdrhvoo\",\"value\":\"otbobzdopcj\"}]}") .toObject(ResourceSkuZoneDetails.class); } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImageInnerTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImageInnerTests.java index 4091b3ca07a2..1432de6d8b01 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImageInnerTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImageInnerTests.java @@ -13,21 +13,24 @@ public final class SandboxCustomImageInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { SandboxCustomImageInner model = BinaryData.fromString( - "{\"properties\":{\"language\":\"Python\",\"languageVersion\":\"skfc\",\"requirementsFileContent\":\"qumiek\",\"provisioningState\":\"Failed\"},\"id\":\"zikhl\",\"name\":\"fjhdg\",\"type\":\"gge\"}") + "{\"properties\":{\"language\":\"Python\",\"languageVersion\":\"rvexztvb\",\"baseImageName\":\"gsfraoyzkoow\",\"requirementsFileContent\":\"mnguxawqaldsyu\",\"provisioningState\":\"Creating\"},\"id\":\"merqfobwyznkb\",\"name\":\"kutwpf\",\"type\":\"pagmhrskdsnf\"}") .toObject(SandboxCustomImageInner.class); Assertions.assertEquals(Language.PYTHON, model.language()); - Assertions.assertEquals("skfc", model.languageVersion()); - Assertions.assertEquals("qumiek", model.requirementsFileContent()); + Assertions.assertEquals("rvexztvb", model.languageVersion()); + Assertions.assertEquals("gsfraoyzkoow", model.baseImageName()); + Assertions.assertEquals("mnguxawqaldsyu", model.requirementsFileContent()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { SandboxCustomImageInner model = new SandboxCustomImageInner().withLanguage(Language.PYTHON) - .withLanguageVersion("skfc") - .withRequirementsFileContent("qumiek"); + .withLanguageVersion("rvexztvb") + .withBaseImageName("gsfraoyzkoow") + .withRequirementsFileContent("mnguxawqaldsyu"); model = BinaryData.fromObject(model).toObject(SandboxCustomImageInner.class); Assertions.assertEquals(Language.PYTHON, model.language()); - Assertions.assertEquals("skfc", model.languageVersion()); - Assertions.assertEquals("qumiek", model.requirementsFileContent()); + Assertions.assertEquals("rvexztvb", model.languageVersion()); + Assertions.assertEquals("gsfraoyzkoow", model.baseImageName()); + Assertions.assertEquals("mnguxawqaldsyu", model.requirementsFileContent()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagePropertiesTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagePropertiesTests.java index fbebbb5c4c61..b041f52ce4f4 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagePropertiesTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagePropertiesTests.java @@ -13,21 +13,24 @@ public final class SandboxCustomImagePropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { SandboxCustomImageProperties model = BinaryData.fromString( - "{\"language\":\"Python\",\"languageVersion\":\"unygaeqid\",\"requirementsFileContent\":\"fatpxllrxcyjmoa\",\"provisioningState\":\"Running\"}") + "{\"language\":\"Python\",\"languageVersion\":\"oakgtdlmkkzev\",\"baseImageName\":\"hewpusdsttwv\",\"requirementsFileContent\":\"vbbejdcng\",\"provisioningState\":\"Running\"}") .toObject(SandboxCustomImageProperties.class); Assertions.assertEquals(Language.PYTHON, model.language()); - Assertions.assertEquals("unygaeqid", model.languageVersion()); - Assertions.assertEquals("fatpxllrxcyjmoa", model.requirementsFileContent()); + Assertions.assertEquals("oakgtdlmkkzev", model.languageVersion()); + Assertions.assertEquals("hewpusdsttwv", model.baseImageName()); + Assertions.assertEquals("vbbejdcng", model.requirementsFileContent()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { SandboxCustomImageProperties model = new SandboxCustomImageProperties().withLanguage(Language.PYTHON) - .withLanguageVersion("unygaeqid") - .withRequirementsFileContent("fatpxllrxcyjmoa"); + .withLanguageVersion("oakgtdlmkkzev") + .withBaseImageName("hewpusdsttwv") + .withRequirementsFileContent("vbbejdcng"); model = BinaryData.fromObject(model).toObject(SandboxCustomImageProperties.class); Assertions.assertEquals(Language.PYTHON, model.language()); - Assertions.assertEquals("unygaeqid", model.languageVersion()); - Assertions.assertEquals("fatpxllrxcyjmoa", model.requirementsFileContent()); + Assertions.assertEquals("oakgtdlmkkzev", model.languageVersion()); + Assertions.assertEquals("hewpusdsttwv", model.baseImageName()); + Assertions.assertEquals("vbbejdcng", model.requirementsFileContent()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesCheckNameAvailabilityWithResponseMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesCheckNameAvailabilityWithResponseMockTests.java index 8937f9046d68..115eb391ae6d 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesCheckNameAvailabilityWithResponseMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesCheckNameAvailabilityWithResponseMockTests.java @@ -23,7 +23,7 @@ public final class SandboxCustomImagesCheckNameAvailabilityWithResponseMockTests @Test public void testCheckNameAvailabilityWithResponse() throws Exception { String responseStr - = "{\"nameAvailable\":true,\"name\":\"pucygvoavyunss\",\"message\":\"ghiee\",\"reason\":\"AlreadyExists\"}"; + = "{\"nameAvailable\":true,\"name\":\"ogiyetes\",\"message\":\"vidbztjhqtfb\",\"reason\":\"Invalid\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -33,13 +33,13 @@ public void testCheckNameAvailabilityWithResponse() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); CheckNameResult response = manager.sandboxCustomImages() - .checkNameAvailabilityWithResponse("kmrocxne", "v", - new SandboxCustomImagesCheckNameRequest().withName("mtodl"), com.azure.core.util.Context.NONE) + .checkNameAvailabilityWithResponse("oqqtl", "fhzbkr", + new SandboxCustomImagesCheckNameRequest().withName("jjjavfqnvhnq"), com.azure.core.util.Context.NONE) .getValue(); Assertions.assertEquals(true, response.nameAvailable()); - Assertions.assertEquals("pucygvoavyunss", response.name()); - Assertions.assertEquals("ghiee", response.message()); - Assertions.assertEquals(Reason.ALREADY_EXISTS, response.reason()); + Assertions.assertEquals("ogiyetes", response.name()); + Assertions.assertEquals("vidbztjhqtfb", response.message()); + Assertions.assertEquals(Reason.INVALID, response.reason()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesCheckNameRequestTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesCheckNameRequestTests.java index c9832983f7da..3992166f4bae 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesCheckNameRequestTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesCheckNameRequestTests.java @@ -12,14 +12,14 @@ public final class SandboxCustomImagesCheckNameRequestTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { SandboxCustomImagesCheckNameRequest model - = BinaryData.fromString("{\"name\":\"varmywdmj\"}").toObject(SandboxCustomImagesCheckNameRequest.class); - Assertions.assertEquals("varmywdmj", model.name()); + = BinaryData.fromString("{\"name\":\"oakufgm\"}").toObject(SandboxCustomImagesCheckNameRequest.class); + Assertions.assertEquals("oakufgm", model.name()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - SandboxCustomImagesCheckNameRequest model = new SandboxCustomImagesCheckNameRequest().withName("varmywdmj"); + SandboxCustomImagesCheckNameRequest model = new SandboxCustomImagesCheckNameRequest().withName("oakufgm"); model = BinaryData.fromObject(model).toObject(SandboxCustomImagesCheckNameRequest.class); - Assertions.assertEquals("varmywdmj", model.name()); + Assertions.assertEquals("oakufgm", model.name()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesCreateOrUpdateMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesCreateOrUpdateMockTests.java index 6e1235526ddc..b1e6b69b4e27 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesCreateOrUpdateMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesCreateOrUpdateMockTests.java @@ -22,7 +22,7 @@ public final class SandboxCustomImagesCreateOrUpdateMockTests { @Test public void testCreateOrUpdate() throws Exception { String responseStr - = "{\"properties\":{\"language\":\"Python\",\"languageVersion\":\"tqpbrlcy\",\"requirementsFileContent\":\"uczkgofxyfsruc\",\"provisioningState\":\"Succeeded\"},\"id\":\"rpcjttbstvjeaqnr\",\"name\":\"vvf\",\"type\":\"oxmlghktuidv\"}"; + = "{\"properties\":{\"language\":\"Python\",\"languageVersion\":\"ezq\",\"baseImageName\":\"ydrtc\",\"requirementsFileContent\":\"kdqkkyihzt\",\"provisioningState\":\"Succeeded\"},\"id\":\"mgqzgwldoyc\",\"name\":\"illcecfehu\",\"type\":\"aoaguhicqlli\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -32,15 +32,17 @@ public void testCreateOrUpdate() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); SandboxCustomImage response = manager.sandboxCustomImages() - .define("aq") - .withExistingCluster("gvvpasek", "gbuxantuygdh") + .define("prkzya") + .withExistingCluster("ynkbwetnju", "p") .withLanguage(Language.PYTHON) - .withLanguageVersion("rpiwrqofulo") - .withRequirementsFileContent("jnlex") + .withLanguageVersion("ccxnafbwqroohtuo") + .withBaseImageName("aonurjtumg") + .withRequirementsFileContent("hpv") .create(); Assertions.assertEquals(Language.PYTHON, response.language()); - Assertions.assertEquals("tqpbrlcy", response.languageVersion()); - Assertions.assertEquals("uczkgofxyfsruc", response.requirementsFileContent()); + Assertions.assertEquals("ezq", response.languageVersion()); + Assertions.assertEquals("ydrtc", response.baseImageName()); + Assertions.assertEquals("kdqkkyihzt", response.requirementsFileContent()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesDeleteMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesDeleteMockTests.java index 37269124a38f..9d3173c52fc4 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesDeleteMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesDeleteMockTests.java @@ -27,7 +27,7 @@ public void testDelete() throws Exception { .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), new AzureProfile("", "", AzureEnvironment.AZURE)); - manager.sandboxCustomImages().delete("r", "hmbpyryxamebly", "yvk", com.azure.core.util.Context.NONE); + manager.sandboxCustomImages().delete("l", "ecvo", "ygzyvneezaifght", com.azure.core.util.Context.NONE); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesGetWithResponseMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesGetWithResponseMockTests.java index c896e0925f38..d52682350578 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesGetWithResponseMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesGetWithResponseMockTests.java @@ -22,7 +22,7 @@ public final class SandboxCustomImagesGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"language\":\"Python\",\"languageVersion\":\"tzuuvb\",\"requirementsFileContent\":\"grebwggahttzlsw\",\"provisioningState\":\"Failed\"},\"id\":\"qfutlxjo\",\"name\":\"zasunwqrjzfrgq\",\"type\":\"aohcmbuocn\"}"; + = "{\"properties\":{\"language\":\"Python\",\"languageVersion\":\"lbijpzgsksrfhfvo\",\"baseImageName\":\"knbnxwcdommpvfq\",\"requirementsFileContent\":\"zfgbrttuiaclkie\",\"provisioningState\":\"Canceled\"},\"id\":\"jlfnthiq\",\"name\":\"yuttdiygbpvnwswm\",\"type\":\"xkyctwwgzwx\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -32,11 +32,12 @@ public void testGetWithResponse() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); SandboxCustomImage response = manager.sandboxCustomImages() - .getWithResponse("mzwcjjncqt", "z", "izvg", com.azure.core.util.Context.NONE) + .getWithResponse("wwexymzvlazipbh", "wvqsgny", "uuzivensrpmeyyvp", com.azure.core.util.Context.NONE) .getValue(); Assertions.assertEquals(Language.PYTHON, response.language()); - Assertions.assertEquals("tzuuvb", response.languageVersion()); - Assertions.assertEquals("grebwggahttzlsw", response.requirementsFileContent()); + Assertions.assertEquals("lbijpzgsksrfhfvo", response.languageVersion()); + Assertions.assertEquals("knbnxwcdommpvfq", response.baseImageName()); + Assertions.assertEquals("zfgbrttuiaclkie", response.requirementsFileContent()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesListByClusterMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesListByClusterMockTests.java index 532578d3a479..e77f693eaf7a 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesListByClusterMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesListByClusterMockTests.java @@ -23,7 +23,7 @@ public final class SandboxCustomImagesListByClusterMockTests { @Test public void testListByCluster() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"language\":\"Python\",\"languageVersion\":\"qwoyxqvapco\",\"requirementsFileContent\":\"oucqpqojx\",\"provisioningState\":\"Creating\"},\"id\":\"rzdcgdzbenribcaw\",\"name\":\"tzqdd\",\"type\":\"jwfljhznamtua\"}]}"; + = "{\"value\":[{\"properties\":{\"language\":\"Python\",\"languageVersion\":\"zkgofxyf\",\"baseImageName\":\"uc\",\"requirementsFileContent\":\"rrp\",\"provisioningState\":\"Deleting\"},\"id\":\"tbstvjeaqnrmv\",\"name\":\"fkoxmlghktuidvr\",\"type\":\"azlp\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -33,10 +33,11 @@ public void testListByCluster() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); PagedIterable response - = manager.sandboxCustomImages().listByCluster("gnzxojpslsvj", "pli", com.azure.core.util.Context.NONE); + = manager.sandboxCustomImages().listByCluster("uuerctatoyi", "tqpbrlcy", com.azure.core.util.Context.NONE); Assertions.assertEquals(Language.PYTHON, response.iterator().next().language()); - Assertions.assertEquals("qwoyxqvapco", response.iterator().next().languageVersion()); - Assertions.assertEquals("oucqpqojx", response.iterator().next().requirementsFileContent()); + Assertions.assertEquals("zkgofxyf", response.iterator().next().languageVersion()); + Assertions.assertEquals("uc", response.iterator().next().baseImageName()); + Assertions.assertEquals("rrp", response.iterator().next().requirementsFileContent()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesListResultTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesListResultTests.java index a368e229cb36..5834a945b794 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesListResultTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SandboxCustomImagesListResultTests.java @@ -15,31 +15,27 @@ public final class SandboxCustomImagesListResultTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { SandboxCustomImagesListResult model = BinaryData.fromString( - "{\"nextLink\":\"dndrdvstkwqqtche\",\"value\":[{\"properties\":{\"language\":\"Python\",\"languageVersion\":\"tdaaygdvwvg\",\"requirementsFileContent\":\"ohgwxrtfudxepxg\",\"provisioningState\":\"Succeeded\"},\"id\":\"gvr\",\"name\":\"mnpkukghimdblxg\",\"type\":\"imfnjhfjx\"},{\"properties\":{\"language\":\"Python\",\"languageVersion\":\"zk\",\"requirementsFileContent\":\"oqreyfkzikfjawn\",\"provisioningState\":\"Moving\"},\"id\":\"vxwc\",\"name\":\"elpcirelsfeaenwa\",\"type\":\"fatkld\"},{\"properties\":{\"language\":\"Python\",\"languageVersion\":\"jhwuaanozjos\",\"requirementsFileContent\":\"youlp\",\"provisioningState\":\"Moving\"},\"id\":\"xagl\",\"name\":\"vimjwos\",\"type\":\"tx\"}]}") + "{\"nextLink\":\"c\",\"value\":[{\"properties\":{\"language\":\"Python\",\"languageVersion\":\"waezkojvd\",\"baseImageName\":\"zfoqouicybxar\",\"requirementsFileContent\":\"szufoxciqopidoa\",\"provisioningState\":\"Canceled\"},\"id\":\"odhkha\",\"name\":\"xkhnzbonlwnto\",\"type\":\"gokdwbwhks\"}]}") .toObject(SandboxCustomImagesListResult.class); - Assertions.assertEquals("dndrdvstkwqqtche", model.nextLink()); + Assertions.assertEquals("c", model.nextLink()); Assertions.assertEquals(Language.PYTHON, model.value().get(0).language()); - Assertions.assertEquals("tdaaygdvwvg", model.value().get(0).languageVersion()); - Assertions.assertEquals("ohgwxrtfudxepxg", model.value().get(0).requirementsFileContent()); + Assertions.assertEquals("waezkojvd", model.value().get(0).languageVersion()); + Assertions.assertEquals("zfoqouicybxar", model.value().get(0).baseImageName()); + Assertions.assertEquals("szufoxciqopidoa", model.value().get(0).requirementsFileContent()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - SandboxCustomImagesListResult model = new SandboxCustomImagesListResult().withNextLink("dndrdvstkwqqtche") - .withValue(Arrays.asList( - new SandboxCustomImageInner().withLanguage(Language.PYTHON) - .withLanguageVersion("tdaaygdvwvg") - .withRequirementsFileContent("ohgwxrtfudxepxg"), - new SandboxCustomImageInner().withLanguage(Language.PYTHON) - .withLanguageVersion("zk") - .withRequirementsFileContent("oqreyfkzikfjawn"), - new SandboxCustomImageInner().withLanguage(Language.PYTHON) - .withLanguageVersion("jhwuaanozjos") - .withRequirementsFileContent("youlp"))); + SandboxCustomImagesListResult model = new SandboxCustomImagesListResult().withNextLink("c") + .withValue(Arrays.asList(new SandboxCustomImageInner().withLanguage(Language.PYTHON) + .withLanguageVersion("waezkojvd") + .withBaseImageName("zfoqouicybxar") + .withRequirementsFileContent("szufoxciqopidoa"))); model = BinaryData.fromObject(model).toObject(SandboxCustomImagesListResult.class); - Assertions.assertEquals("dndrdvstkwqqtche", model.nextLink()); + Assertions.assertEquals("c", model.nextLink()); Assertions.assertEquals(Language.PYTHON, model.value().get(0).language()); - Assertions.assertEquals("tdaaygdvwvg", model.value().get(0).languageVersion()); - Assertions.assertEquals("ohgwxrtfudxepxg", model.value().get(0).requirementsFileContent()); + Assertions.assertEquals("waezkojvd", model.value().get(0).languageVersion()); + Assertions.assertEquals("zfoqouicybxar", model.value().get(0).baseImageName()); + Assertions.assertEquals("szufoxciqopidoa", model.value().get(0).requirementsFileContent()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ScriptCheckNameRequestTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ScriptCheckNameRequestTests.java index 95ce8e7e8059..b78486231bc3 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ScriptCheckNameRequestTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ScriptCheckNameRequestTests.java @@ -12,14 +12,14 @@ public final class ScriptCheckNameRequestTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ScriptCheckNameRequest model - = BinaryData.fromString("{\"name\":\"iuxxpshneekulfg\"}").toObject(ScriptCheckNameRequest.class); - Assertions.assertEquals("iuxxpshneekulfg", model.name()); + = BinaryData.fromString("{\"name\":\"ufiqndieuzaof\"}").toObject(ScriptCheckNameRequest.class); + Assertions.assertEquals("ufiqndieuzaof", model.name()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - ScriptCheckNameRequest model = new ScriptCheckNameRequest().withName("iuxxpshneekulfg"); + ScriptCheckNameRequest model = new ScriptCheckNameRequest().withName("ufiqndieuzaof"); model = BinaryData.fromObject(model).toObject(ScriptCheckNameRequest.class); - Assertions.assertEquals("iuxxpshneekulfg", model.name()); + Assertions.assertEquals("ufiqndieuzaof", model.name()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ScriptsCheckNameAvailabilityWithResponseMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ScriptsCheckNameAvailabilityWithResponseMockTests.java index a58f73d673ad..764b79464b93 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ScriptsCheckNameAvailabilityWithResponseMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ScriptsCheckNameAvailabilityWithResponseMockTests.java @@ -23,7 +23,7 @@ public final class ScriptsCheckNameAvailabilityWithResponseMockTests { @Test public void testCheckNameAvailabilityWithResponse() throws Exception { String responseStr - = "{\"nameAvailable\":false,\"name\":\"vqvwzkjopwbe\",\"message\":\"r\",\"reason\":\"AlreadyExists\"}"; + = "{\"nameAvailable\":true,\"name\":\"pucygvoavyunss\",\"message\":\"ghiee\",\"reason\":\"AlreadyExists\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -33,13 +33,13 @@ public void testCheckNameAvailabilityWithResponse() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); CheckNameResult response = manager.scripts() - .checkNameAvailabilityWithResponse("d", "opedbwdpyqyybxub", "dnafcbqwre", - new ScriptCheckNameRequest().withName("jelaqacigele"), com.azure.core.util.Context.NONE) + .checkNameAvailabilityWithResponse("zfrgqhaohcm", "uocnjrohmbpyr", "xameblydyvkfkm", + new ScriptCheckNameRequest().withName("ocxnehvsmtodl"), com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals(false, response.nameAvailable()); - Assertions.assertEquals("vqvwzkjopwbe", response.name()); - Assertions.assertEquals("r", response.message()); + Assertions.assertEquals(true, response.nameAvailable()); + Assertions.assertEquals("pucygvoavyunss", response.name()); + Assertions.assertEquals("ghiee", response.message()); Assertions.assertEquals(Reason.ALREADY_EXISTS, response.reason()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ScriptsDeleteMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ScriptsDeleteMockTests.java index 45ad24f16ec5..0c3163b3c4f1 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ScriptsDeleteMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/ScriptsDeleteMockTests.java @@ -27,8 +27,7 @@ public void testDelete() throws Exception { .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), new AzureProfile("", "", AzureEnvironment.AZURE)); - manager.scripts() - .delete("qoyueayfbpcmsplb", "rrueqthwmg", "mbscbbx", "gdhxi", com.azure.core.util.Context.NONE); + manager.scripts().delete("grebwggahttzlsw", "ajqfutlx", "oqza", "unwqr", com.azure.core.util.Context.NONE); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SkuDescriptionInnerTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SkuDescriptionInnerTests.java index fdae377e1c4b..b6f441b50d64 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SkuDescriptionInnerTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SkuDescriptionInnerTests.java @@ -11,7 +11,7 @@ public final class SkuDescriptionInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { SkuDescriptionInner model = BinaryData.fromString( - "{\"resourceType\":\"fudwpznt\",\"name\":\"dzhlrq\",\"tier\":\"hckfrlhrx\",\"locations\":[\"yvpycanuzbpzk\"],\"locationInfo\":[{\"location\":\"uwbc\",\"zones\":[\"bmehh\"],\"zoneDetails\":[{\"name\":[\"us\",\"tslhspkdeem\",\"ofmxagkvtmelmqkr\"],\"capabilities\":[{},{},{}]},{\"name\":[\"juahaquhcdhmdual\",\"exq\",\"vfadmws\"],\"capabilities\":[{}]},{\"name\":[\"xpvgo\",\"zlfmisgwbnbbeld\"],\"capabilities\":[{}]}]},{\"location\":\"zbaliourqha\",\"zones\":[\"hashsfwxosow\",\"xcug\",\"cjooxdjebwpucwwf\"],\"zoneDetails\":[{\"name\":[\"meue\",\"ivyhzceuojgjrwju\"],\"capabilities\":[{},{}]},{\"name\":[\"mcdytdxwitxnrj\",\"wgqwgxhn\",\"skxfbk\"],\"capabilities\":[{}]}]},{\"location\":\"gklwn\",\"zones\":[\"jdauwhvy\",\"wzbtdhxu\",\"znbmpowuwprzq\"],\"zoneDetails\":[{\"name\":[\"lupj\",\"khfxobbcswsrt\"],\"capabilities\":[{},{},{},{}]},{\"name\":[\"rbpbewtghfgblcg\",\"xzvlvqhjkbegib\",\"nmxiebwwaloayqc\",\"wrtz\"],\"capabilities\":[{}]},{\"name\":[\"yzm\",\"txon\",\"mtsavjcbpwxqp\"],\"capabilities\":[{},{},{}]}]}],\"restrictions\":[\"datatguvriuhp\",\"datawmdyvxqtay\"]}") + "{\"resourceType\":\"fbjfdtwssotftpvj\",\"name\":\"exilzznfqqnvwpmq\",\"tier\":\"ruoujmk\",\"locations\":[\"wqytjrybnwjewgdr\",\"ervnaenqpehi\"],\"locationInfo\":[{\"location\":\"ygmi\",\"zones\":[\"nzdndslgna\",\"qig\",\"nduhavhqlkthum\",\"qolbgyc\"],\"zoneDetails\":[{\"name\":[\"tgccymvaolpss\"],\"capabilities\":[{},{},{},{}]},{\"name\":[\"mdnbbglzpswiy\",\"mcwyhzdxssadb\",\"mnvdfzn\"],\"capabilities\":[{}]},{\"name\":[\"vxzbncb\",\"ylpstdbhhxsrzdz\",\"cers\",\"dntnevf\"],\"capabilities\":[{},{},{},{}]},{\"name\":[\"gtdsslswt\",\"weriofzpyqsem\",\"abnetshh\"],\"capabilities\":[{}]}]},{\"location\":\"edplvwiwubmw\",\"zones\":[\"sldnkwwtppjflcxo\"],\"zoneDetails\":[{\"name\":[\"nzmnsikvm\"],\"capabilities\":[{}]},{\"name\":[\"qkdltfz\",\"mhhv\",\"gureodkwobdag\",\"tibqdxbxwakb\"],\"capabilities\":[{}]},{\"name\":[\"dlkzgxhuri\",\"lbpodxunk\",\"ebxmubyynt\"],\"capabilities\":[{},{}]},{\"name\":[\"tkoievseotgq\",\"l\"],\"capabilities\":[{},{},{},{}]}]}],\"restrictions\":[\"datalauwzizxbmpgcjef\",\"datazmuvpbttdumorppx\",\"databmnzbtbhjpgl\",\"datafgohdneuelfphs\"]}") .toObject(SkuDescriptionInner.class); } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SkuDescriptionListTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SkuDescriptionListTests.java index 37ccd19ac63b..5b41c3819707 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SkuDescriptionListTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SkuDescriptionListTests.java @@ -11,7 +11,7 @@ public final class SkuDescriptionListTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { SkuDescriptionList model = BinaryData.fromString( - "{\"value\":[{\"resourceType\":\"j\",\"name\":\"idokgjlj\",\"tier\":\"xgvcl\",\"locations\":[\"sncghkjeszz\",\"bijhtxfvgxbf\",\"mxnehmp\"],\"locationInfo\":[{\"location\":\"xgodebfqkkrbmp\",\"zones\":[\"riwflzlfb\"],\"zoneDetails\":[{}]},{\"location\":\"uzycispnqza\",\"zones\":[\"kbrpyydhibnuq\",\"kpikadrgvt\"],\"zoneDetails\":[{},{}]}],\"restrictions\":[\"datauynhijg\",\"datamebf\",\"dataiarbutrcvpna\"]},{\"resourceType\":\"mhjrunmpxttdbhr\",\"name\":\"l\",\"tier\":\"kx\",\"locations\":[\"k\",\"bhenbtkcxywnyt\",\"rsyn\",\"qidybyx\"],\"locationInfo\":[{\"location\":\"clha\",\"zones\":[\"babphlwrqlfk\",\"sthsu\"],\"zoneDetails\":[{},{},{}]},{\"location\":\"mnyyazt\",\"zones\":[\"wwrq\",\"uedck\"],\"zoneDetails\":[{},{},{}]},{\"location\":\"biexzfeyu\",\"zones\":[\"ibx\",\"jwbhqwalmuz\",\"oxaepd\",\"zjancuxr\"],\"zoneDetails\":[{},{},{}]},{\"location\":\"bavxbniwdjswzt\",\"zones\":[\"pgn\"],\"zoneDetails\":[{}]}],\"restrictions\":[\"datapzxbz\",\"datafzab\",\"datalcuhxwtctyqiklb\"]},{\"resourceType\":\"vplwzbhv\",\"name\":\"u\",\"tier\":\"osvmk\",\"locations\":[\"xquk\"],\"locationInfo\":[{\"location\":\"l\",\"zones\":[\"sxnkjzkdeslpvlo\",\"wiyighxpkdw\",\"baiuebbaumny\",\"upedeojnabckhs\"],\"zoneDetails\":[{},{},{},{}]},{\"location\":\"psiebtfhvpes\",\"zones\":[\"krdqmh\",\"jdhtldwkyzxu\",\"tkncwsc\"],\"zoneDetails\":[{},{},{},{}]},{\"location\":\"lxotogtwrupq\",\"zones\":[\"nmic\"],\"zoneDetails\":[{}]}],\"restrictions\":[\"datao\",\"dataeil\",\"datavnotyfjfcnj\",\"datak\"]},{\"resourceType\":\"x\",\"name\":\"bttk\",\"tier\":\"ywpnvjt\",\"locations\":[\"ermclfplphoxuscr\",\"abgy\"],\"locationInfo\":[{\"location\":\"bjtazqugxywpmu\",\"zones\":[\"jzwf\"],\"zoneDetails\":[{}]}],\"restrictions\":[\"dataids\",\"datayonobgl\",\"dataocqxtccmg\",\"dataudxytlmoyrx\"]}]}") + "{\"value\":[{\"resourceType\":\"bm\",\"name\":\"wuwprzqlv\",\"tier\":\"alupjm\",\"locations\":[\"xobbcswsrt\",\"riplrbpbewtg\",\"fgb\"],\"locationInfo\":[{\"location\":\"wxzvlvqhjkb\",\"zones\":[\"btn\",\"xiebwwaloayqcg\",\"rtzju\",\"gwyzm\"],\"zoneDetails\":[{},{},{},{}]}],\"restrictions\":[\"datagmtsavjcbpwxqpsr\",\"datanftguvriuhpr\",\"datamdyvxqtayriw\"]},{\"resourceType\":\"oyq\",\"name\":\"xrmcqibycnojvk\",\"tier\":\"e\",\"locations\":[\"gzva\",\"apj\",\"zhpvgqzcjrvxd\",\"zlmwlxkvugfhz\"],\"locationInfo\":[{\"location\":\"wjvzunluthnn\",\"zones\":[\"xipeilpjzuaejx\",\"ultskzbbtdz\"],\"zoneDetails\":[{},{},{},{}]},{\"location\":\"e\",\"zones\":[\"pwo\"],\"zoneDetails\":[{},{}]},{\"location\":\"kfpbs\",\"zones\":[\"f\"],\"zoneDetails\":[{}]},{\"location\":\"uusdttouwa\",\"zones\":[\"kqvkelnsmvbxwyjs\",\"lh\"],\"zoneDetails\":[{},{}]}],\"restrictions\":[\"datan\",\"dataixisxyawjoy\",\"dataqcslyjpkiid\"]},{\"resourceType\":\"exznelixhnr\",\"name\":\"folhbnxknal\",\"tier\":\"lp\",\"locations\":[\"dtpnapnyiropuhp\",\"gvpgy\",\"gqgitxmedjvcsl\"],\"locationInfo\":[{\"location\":\"wwncwzzhxgk\",\"zones\":[\"gucnapkte\",\"ellwptfdy\"],\"zoneDetails\":[{},{},{}]},{\"location\":\"qbuaceopzfqr\",\"zones\":[\"ao\",\"ppcqeqxolz\",\"ahzxctobgbk\"],\"zoneDetails\":[{},{},{},{}]}],\"restrictions\":[\"datapostmgrcfbunrm\",\"dataqjhhkxbpv\",\"dataymjhxxjyngudivkr\"]},{\"resourceType\":\"wbxqzvszjfau\",\"name\":\"fdxxivetvtcqaqtd\",\"tier\":\"mcbxvwvxysl\",\"locations\":[\"sfxobl\",\"tkblmpewww\",\"bkrvrnsvshqj\"],\"locationInfo\":[{\"location\":\"crsbfovasr\",\"zones\":[\"wbhsqfsub\"],\"zoneDetails\":[{}]}],\"restrictions\":[\"datarxbpyb\"]}]}") .toObject(SkuDescriptionList.class); } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SkuLocationInfoItemTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SkuLocationInfoItemTests.java index 6d71be7e1a82..fb95ed9ee2e8 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SkuLocationInfoItemTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SkuLocationInfoItemTests.java @@ -14,20 +14,19 @@ public final class SkuLocationInfoItemTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { SkuLocationInfoItem model = BinaryData.fromString( - "{\"location\":\"iwwroyqbexrmc\",\"zones\":[\"ycnojvknmefqsg\",\"vah\",\"pjyzhpv\"],\"zoneDetails\":[{\"name\":[\"rvxdjzlmw\"],\"capabilities\":[{\"name\":\"ug\",\"value\":\"zovawjvz\"},{\"name\":\"luthn\",\"value\":\"rnxipei\"},{\"name\":\"jzuaejxdultskzbb\",\"value\":\"zumveekgpwo\"},{\"name\":\"hkfpbs\",\"value\":\"ofd\"}]},{\"name\":[\"us\",\"ttouwaboekqvkel\",\"smv\"],\"capabilities\":[{\"name\":\"jsflhhcaalnjix\",\"value\":\"xyawj\"},{\"name\":\"aq\",\"value\":\"lyjpk\"},{\"name\":\"dzyexznelixh\",\"value\":\"ztfolhbnxk\"},{\"name\":\"laulppg\",\"value\":\"tpnapnyiropuhpig\"}]},{\"name\":[\"ylgqgitxmedjvcsl\",\"n\",\"wwncwzzhxgk\",\"rmgucnap\"],\"capabilities\":[{\"name\":\"ellwptfdy\",\"value\":\"fqbuaceopzf\"},{\"name\":\"hhuao\",\"value\":\"pcqeqx\"},{\"name\":\"z\",\"value\":\"hzxct\"},{\"name\":\"gbkdmoizpos\",\"value\":\"grcfb\"}]},{\"name\":[\"mfqjhhkxbp\",\"jy\",\"jhxxjyn\",\"u\"],\"capabilities\":[{\"name\":\"r\",\"value\":\"wbxqzvszjfau\"}]}]}") + "{\"location\":\"yhtozfikdowwqu\",\"zones\":[\"zx\",\"lvithhqzonosgg\"],\"zoneDetails\":[{\"name\":[\"fwdsj\",\"ka\",\"jutiiswacff\",\"dkzzewkfvhqcrail\"],\"capabilities\":[{\"name\":\"pfuflrw\",\"value\":\"hdlxyjrxsagafcn\"}]}]}") .toObject(SkuLocationInfoItem.class); - Assertions.assertEquals("iwwroyqbexrmc", model.location()); - Assertions.assertEquals("ycnojvknmefqsg", model.zones().get(0)); + Assertions.assertEquals("yhtozfikdowwqu", model.location()); + Assertions.assertEquals("zx", model.zones().get(0)); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - SkuLocationInfoItem model = new SkuLocationInfoItem().withLocation("iwwroyqbexrmc") - .withZones(Arrays.asList("ycnojvknmefqsg", "vah", "pjyzhpv")) - .withZoneDetails(Arrays.asList(new ResourceSkuZoneDetails(), new ResourceSkuZoneDetails(), - new ResourceSkuZoneDetails(), new ResourceSkuZoneDetails())); + SkuLocationInfoItem model = new SkuLocationInfoItem().withLocation("yhtozfikdowwqu") + .withZones(Arrays.asList("zx", "lvithhqzonosgg")) + .withZoneDetails(Arrays.asList(new ResourceSkuZoneDetails())); model = BinaryData.fromObject(model).toObject(SkuLocationInfoItem.class); - Assertions.assertEquals("iwwroyqbexrmc", model.location()); - Assertions.assertEquals("ycnojvknmefqsg", model.zones().get(0)); + Assertions.assertEquals("yhtozfikdowwqu", model.location()); + Assertions.assertEquals("zx", model.zones().get(0)); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SkusListMockTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SkusListMockTests.java index defb2c9b4cd3..91903f46dc20 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SkusListMockTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SkusListMockTests.java @@ -21,7 +21,7 @@ public final class SkusListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"resourceType\":\"whixmonstsh\",\"name\":\"xgvelfclduccbird\",\"tier\":\"uwc\",\"locations\":[\"egstmninwjizci\",\"nghgshej\"],\"locationInfo\":[{\"location\":\"xqmul\",\"zones\":[\"xqzv\",\"ers\"],\"zoneDetails\":[{\"name\":[\"rwnamikzeb\",\"qbsms\",\"ziqgfuh\"],\"capabilities\":[{},{}]},{\"name\":[\"swhvhczznvfbycj\",\"xjww\",\"xzv\",\"mwmxqhndvnoamld\"],\"capabilities\":[{},{},{},{}]},{\"name\":[\"hdjhhflz\",\"kxcoxpelnje\",\"agltsxoa\"],\"capabilities\":[{},{}]}]},{\"location\":\"g\",\"zones\":[\"pbswvefloccsrm\"],\"zoneDetails\":[{\"name\":[\"ipgawtxx\"],\"capabilities\":[{}]},{\"name\":[\"xcjxgrytfmpcy\",\"ilrmcaykggnox\"],\"capabilities\":[{}]},{\"name\":[\"sxwpndfcpfnznthj\",\"wkjaos\"],\"capabilities\":[{},{},{},{}]},{\"name\":[\"oamktcq\",\"os\",\"gbzahgxqdlyr\",\"ltlaprltzkatbhj\"],\"capabilities\":[{},{},{}]}]}],\"restrictions\":[\"datas\",\"dataqeqala\",\"datavlagun\"]}]}"; + = "{\"value\":[{\"resourceType\":\"xpxiwfcngjs\",\"name\":\"sii\",\"tier\":\"mkzjvkviir\",\"locations\":[\"grwsdp\",\"ra\",\"zvzbglbyv\",\"ctctbrxkjz\"],\"locationInfo\":[{\"location\":\"xff\",\"zones\":[\"kwfbkgo\",\"xwopdbydpizqa\",\"lnapxbiygn\",\"gjkn\"],\"zoneDetails\":[{\"name\":[\"ttuxuuyilflqoiqu\",\"rehmr\"],\"capabilities\":[{},{}]},{\"name\":[\"ujztcz\"],\"capabilities\":[{},{}]}]},{\"location\":\"jtwhauunf\",\"zones\":[\"jletlxsmrpddo\"],\"zoneDetails\":[{\"name\":[\"owa\",\"iynknlq\",\"zdvpiw\",\"xqszdtmaajquh\"],\"capabilities\":[{}]}]},{\"location\":\"lrjvmtyg\",\"zones\":[\"zyos\",\"spshckfkyjp\",\"sp\"],\"zoneDetails\":[{\"name\":[\"fppyogtieyujtvcz\"],\"capabilities\":[{}]},{\"name\":[\"rxmunjdxvgln\"],\"capabilities\":[{}]}]}],\"restrictions\":[\"datapaglqivbgk\",\"datavkhpzvuqdflvo\",\"dataiypfp\"]}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -30,7 +30,7 @@ public void testList() throws Exception { .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), new AzureProfile("", "", AzureEnvironment.AZURE)); - PagedIterable response = manager.skus().list("yinljqe", com.azure.core.util.Context.NONE); + PagedIterable response = manager.skus().list("n", com.azure.core.util.Context.NONE); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SuspensionDetailsTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SuspensionDetailsTests.java index efb86d70b2b2..2219b7e55e54 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SuspensionDetailsTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/SuspensionDetailsTests.java @@ -12,16 +12,16 @@ public final class SuspensionDetailsTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - SuspensionDetails model = BinaryData.fromString("{\"suspensionStartDate\":\"2021-04-16T08:57:57Z\"}") + SuspensionDetails model = BinaryData.fromString("{\"suspensionStartDate\":\"2021-07-29T14:30:38Z\"}") .toObject(SuspensionDetails.class); - Assertions.assertEquals(OffsetDateTime.parse("2021-04-16T08:57:57Z"), model.suspensionStartDate()); + Assertions.assertEquals(OffsetDateTime.parse("2021-07-29T14:30:38Z"), model.suspensionStartDate()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { SuspensionDetails model - = new SuspensionDetails().withSuspensionStartDate(OffsetDateTime.parse("2021-04-16T08:57:57Z")); + = new SuspensionDetails().withSuspensionStartDate(OffsetDateTime.parse("2021-07-29T14:30:38Z")); model = BinaryData.fromObject(model).toObject(SuspensionDetails.class); - Assertions.assertEquals(OffsetDateTime.parse("2021-04-16T08:57:57Z"), model.suspensionStartDate()); + Assertions.assertEquals(OffsetDateTime.parse("2021-07-29T14:30:38Z"), model.suspensionStartDate()); } } diff --git a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/TableLevelSharingPropertiesTests.java b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/TableLevelSharingPropertiesTests.java index 87a1f0b851ef..0b81c8fcad2a 100644 --- a/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/TableLevelSharingPropertiesTests.java +++ b/sdk/kusto/azure-resourcemanager-kusto/src/test/java/com/azure/resourcemanager/kusto/generated/TableLevelSharingPropertiesTests.java @@ -13,37 +13,37 @@ public final class TableLevelSharingPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { TableLevelSharingProperties model = BinaryData.fromString( - "{\"tablesToInclude\":[\"wwzjuqkhrsajiwku\",\"foskghsauuimj\"],\"tablesToExclude\":[\"ied\",\"ugidyjrr\",\"byao\",\"v\"],\"externalTablesToInclude\":[\"sonpclhocohs\",\"kevle\",\"gz\"],\"externalTablesToExclude\":[\"hfmvfaxkffe\"],\"materializedViewsToInclude\":[\"hl\"],\"materializedViewsToExclude\":[\"zy\"],\"functionsToInclude\":[\"xmzsbbzogg\",\"grxwbu\",\"vjxxjnsp\",\"dptkoenkouk\"],\"functionsToExclude\":[\"dwtiukbldngkp\",\"cipazyxoegukgjnp\",\"ucgygevqz\"]}") + "{\"tablesToInclude\":[\"lhocohslkev\",\"eggzfb\",\"hfmvfaxkffe\"],\"tablesToExclude\":[\"hl\"],\"externalTablesToInclude\":[\"zy\"],\"externalTablesToExclude\":[\"xmzsbbzogg\",\"grxwbu\",\"vjxxjnsp\",\"dptkoenkouk\"],\"materializedViewsToInclude\":[\"dwtiukbldngkp\",\"cipazyxoegukgjnp\",\"ucgygevqz\"],\"materializedViewsToExclude\":[\"pmr\"],\"functionsToInclude\":[\"zcdrqjsdpydnfyhx\",\"eoejzic\",\"ifsjttgzfbishcb\"],\"functionsToExclude\":[\"jdeyeamdpha\",\"alpbuxwgipwhon\",\"wkgshwa\",\"kix\"]}") .toObject(TableLevelSharingProperties.class); - Assertions.assertEquals("wwzjuqkhrsajiwku", model.tablesToInclude().get(0)); - Assertions.assertEquals("ied", model.tablesToExclude().get(0)); - Assertions.assertEquals("sonpclhocohs", model.externalTablesToInclude().get(0)); - Assertions.assertEquals("hfmvfaxkffe", model.externalTablesToExclude().get(0)); - Assertions.assertEquals("hl", model.materializedViewsToInclude().get(0)); - Assertions.assertEquals("zy", model.materializedViewsToExclude().get(0)); - Assertions.assertEquals("xmzsbbzogg", model.functionsToInclude().get(0)); - Assertions.assertEquals("dwtiukbldngkp", model.functionsToExclude().get(0)); + Assertions.assertEquals("lhocohslkev", model.tablesToInclude().get(0)); + Assertions.assertEquals("hl", model.tablesToExclude().get(0)); + Assertions.assertEquals("zy", model.externalTablesToInclude().get(0)); + Assertions.assertEquals("xmzsbbzogg", model.externalTablesToExclude().get(0)); + Assertions.assertEquals("dwtiukbldngkp", model.materializedViewsToInclude().get(0)); + Assertions.assertEquals("pmr", model.materializedViewsToExclude().get(0)); + Assertions.assertEquals("zcdrqjsdpydnfyhx", model.functionsToInclude().get(0)); + Assertions.assertEquals("jdeyeamdpha", model.functionsToExclude().get(0)); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - TableLevelSharingProperties model - = new TableLevelSharingProperties().withTablesToInclude(Arrays.asList("wwzjuqkhrsajiwku", "foskghsauuimj")) - .withTablesToExclude(Arrays.asList("ied", "ugidyjrr", "byao", "v")) - .withExternalTablesToInclude(Arrays.asList("sonpclhocohs", "kevle", "gz")) - .withExternalTablesToExclude(Arrays.asList("hfmvfaxkffe")) - .withMaterializedViewsToInclude(Arrays.asList("hl")) - .withMaterializedViewsToExclude(Arrays.asList("zy")) - .withFunctionsToInclude(Arrays.asList("xmzsbbzogg", "grxwbu", "vjxxjnsp", "dptkoenkouk")) - .withFunctionsToExclude(Arrays.asList("dwtiukbldngkp", "cipazyxoegukgjnp", "ucgygevqz")); + TableLevelSharingProperties model = new TableLevelSharingProperties() + .withTablesToInclude(Arrays.asList("lhocohslkev", "eggzfb", "hfmvfaxkffe")) + .withTablesToExclude(Arrays.asList("hl")) + .withExternalTablesToInclude(Arrays.asList("zy")) + .withExternalTablesToExclude(Arrays.asList("xmzsbbzogg", "grxwbu", "vjxxjnsp", "dptkoenkouk")) + .withMaterializedViewsToInclude(Arrays.asList("dwtiukbldngkp", "cipazyxoegukgjnp", "ucgygevqz")) + .withMaterializedViewsToExclude(Arrays.asList("pmr")) + .withFunctionsToInclude(Arrays.asList("zcdrqjsdpydnfyhx", "eoejzic", "ifsjttgzfbishcb")) + .withFunctionsToExclude(Arrays.asList("jdeyeamdpha", "alpbuxwgipwhon", "wkgshwa", "kix")); model = BinaryData.fromObject(model).toObject(TableLevelSharingProperties.class); - Assertions.assertEquals("wwzjuqkhrsajiwku", model.tablesToInclude().get(0)); - Assertions.assertEquals("ied", model.tablesToExclude().get(0)); - Assertions.assertEquals("sonpclhocohs", model.externalTablesToInclude().get(0)); - Assertions.assertEquals("hfmvfaxkffe", model.externalTablesToExclude().get(0)); - Assertions.assertEquals("hl", model.materializedViewsToInclude().get(0)); - Assertions.assertEquals("zy", model.materializedViewsToExclude().get(0)); - Assertions.assertEquals("xmzsbbzogg", model.functionsToInclude().get(0)); - Assertions.assertEquals("dwtiukbldngkp", model.functionsToExclude().get(0)); + Assertions.assertEquals("lhocohslkev", model.tablesToInclude().get(0)); + Assertions.assertEquals("hl", model.tablesToExclude().get(0)); + Assertions.assertEquals("zy", model.externalTablesToInclude().get(0)); + Assertions.assertEquals("xmzsbbzogg", model.externalTablesToExclude().get(0)); + Assertions.assertEquals("dwtiukbldngkp", model.materializedViewsToInclude().get(0)); + Assertions.assertEquals("pmr", model.materializedViewsToExclude().get(0)); + Assertions.assertEquals("zcdrqjsdpydnfyhx", model.functionsToInclude().get(0)); + Assertions.assertEquals("jdeyeamdpha", model.functionsToExclude().get(0)); } } diff --git a/sdk/labservices/azure-resourcemanager-labservices/README.md b/sdk/labservices/azure-resourcemanager-labservices/README.md index 10e48329a0da..df1033bda8ab 100644 --- a/sdk/labservices/azure-resourcemanager-labservices/README.md +++ b/sdk/labservices/azure-resourcemanager-labservices/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-labservices - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Flabservices%2Fazure-resourcemanager-labservices%2FREADME.png) + diff --git a/sdk/labservices/azure-resourcemanager-labservices/pom.xml b/sdk/labservices/azure-resourcemanager-labservices/pom.xml index 0283fcc5c434..10fc35963dc7 100644 --- a/sdk/labservices/azure-resourcemanager-labservices/pom.xml +++ b/sdk/labservices/azure-resourcemanager-labservices/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/largeinstance/azure-resourcemanager-largeinstance/README.md b/sdk/largeinstance/azure-resourcemanager-largeinstance/README.md index 348153596ae8..66e8df9b199e 100644 --- a/sdk/largeinstance/azure-resourcemanager-largeinstance/README.md +++ b/sdk/largeinstance/azure-resourcemanager-largeinstance/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-largeinstance - 1.0.0-beta.2 + 1.0.0-beta.3 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Flargeinstance%2Fazure-resourcemanager-largeinstance%2FREADME.png) + diff --git a/sdk/largeinstance/azure-resourcemanager-largeinstance/pom.xml b/sdk/largeinstance/azure-resourcemanager-largeinstance/pom.xml index 6447c0054453..b0b04521aeb0 100644 --- a/sdk/largeinstance/azure-resourcemanager-largeinstance/pom.xml +++ b/sdk/largeinstance/azure-resourcemanager-largeinstance/pom.xml @@ -52,23 +52,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/loadtesting/azure-developer-loadtesting/CHANGELOG.md b/sdk/loadtesting/azure-developer-loadtesting/CHANGELOG.md index feb0b626cf9e..0f94332cbc99 100644 --- a/sdk/loadtesting/azure-developer-loadtesting/CHANGELOG.md +++ b/sdk/loadtesting/azure-developer-loadtesting/CHANGELOG.md @@ -1,5 +1,24 @@ # Release History +## 1.1.0-beta.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + +## 1.0.21 (2025-02-25) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`. + ## 1.0.20 (2025-01-20) ### Other Changes diff --git a/sdk/loadtesting/azure-developer-loadtesting/README.md b/sdk/loadtesting/azure-developer-loadtesting/README.md index 376f58fa0f32..8db9930aba19 100644 --- a/sdk/loadtesting/azure-developer-loadtesting/README.md +++ b/sdk/loadtesting/azure-developer-loadtesting/README.md @@ -27,7 +27,7 @@ Various documentation is available to help you get started com.azure azure-developer-loadtesting - 1.0.20 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/loadtesting/azure-developer-loadtesting/pom.xml b/sdk/loadtesting/azure-developer-loadtesting/pom.xml index 3d44e3b97787..b5db2819e194 100644 --- a/sdk/loadtesting/azure-developer-loadtesting/pom.xml +++ b/sdk/loadtesting/azure-developer-loadtesting/pom.xml @@ -9,7 +9,7 @@ com.azure azure-developer-loadtesting - 1.0.20 + 1.1.0-beta.1 jar Microsoft Azure SDK for Load Testing @@ -47,23 +47,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/loadtesting/azure-resourcemanager-loadtesting/README.md b/sdk/loadtesting/azure-resourcemanager-loadtesting/README.md index 70ca30807c0c..9f7adaaee29b 100644 --- a/sdk/loadtesting/azure-resourcemanager-loadtesting/README.md +++ b/sdk/loadtesting/azure-resourcemanager-loadtesting/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-loadtesting - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Floadtesting%2Fazure-resourcemanager-loadtesting%2FREADME.png) + diff --git a/sdk/loadtesting/azure-resourcemanager-loadtesting/pom.xml b/sdk/loadtesting/azure-resourcemanager-loadtesting/pom.xml index 00c5165f3179..7d5033a0652b 100644 --- a/sdk/loadtesting/azure-resourcemanager-loadtesting/pom.xml +++ b/sdk/loadtesting/azure-resourcemanager-loadtesting/pom.xml @@ -52,29 +52,29 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/loganalytics/azure-resourcemanager-loganalytics/README.md b/sdk/loganalytics/azure-resourcemanager-loganalytics/README.md index 427ab12c3d28..0badc4533918 100644 --- a/sdk/loganalytics/azure-resourcemanager-loganalytics/README.md +++ b/sdk/loganalytics/azure-resourcemanager-loganalytics/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-loganalytics - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -108,4 +108,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Floganalytics%2Fazure-resourcemanager-loganalytics%2FREADME.png) + diff --git a/sdk/loganalytics/azure-resourcemanager-loganalytics/pom.xml b/sdk/loganalytics/azure-resourcemanager-loganalytics/pom.xml index 251aa3fad51f..fa97657db9e4 100644 --- a/sdk/loganalytics/azure-resourcemanager-loganalytics/pom.xml +++ b/sdk/loganalytics/azure-resourcemanager-loganalytics/pom.xml @@ -52,23 +52,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test @@ -92,7 +92,7 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/logic/azure-resourcemanager-logic/README.md b/sdk/logic/azure-resourcemanager-logic/README.md index 1f6fac2a5e5e..19a148d4baa1 100644 --- a/sdk/logic/azure-resourcemanager-logic/README.md +++ b/sdk/logic/azure-resourcemanager-logic/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-logic - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Flogic%2Fazure-resourcemanager-logic%2FREADME.png) + diff --git a/sdk/logic/azure-resourcemanager-logic/pom.xml b/sdk/logic/azure-resourcemanager-logic/pom.xml index f8e94d2e65f6..dd087e832487 100644 --- a/sdk/logic/azure-resourcemanager-logic/pom.xml +++ b/sdk/logic/azure-resourcemanager-logic/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/logz/azure-resourcemanager-logz/CHANGELOG.md b/sdk/logz/azure-resourcemanager-logz/CHANGELOG.md index 9060c84de45d..1818dc2c4c95 100644 --- a/sdk/logz/azure-resourcemanager-logz/CHANGELOG.md +++ b/sdk/logz/azure-resourcemanager-logz/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.0.0-beta.4 (Unreleased) +## 1.0.0-beta.5 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 1.0.0-beta.4 (2025-02-14) + +- Please note, this package has been deprecated and will no longer be maintained after 01/01/2025. Refer to our deprecation policy (https://aka.ms/azsdk/support-policies) for more details. + +### Other Changes + +- Please note, this package has been deprecated and will no longer be maintained after 01/01/2025. Refer to our deprecation policy (https://aka.ms/azsdk/support-policies) for more details. + ## 1.0.0-beta.3 (2024-10-17) - Azure Resource Manager logz client library for Java. This package contains Microsoft Azure SDK for logz Management SDK. Package tag package-2020-10-01. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). diff --git a/sdk/logz/azure-resourcemanager-logz/README.md b/sdk/logz/azure-resourcemanager-logz/README.md index cfdecafb1da3..e5c7ef2edaf1 100644 --- a/sdk/logz/azure-resourcemanager-logz/README.md +++ b/sdk/logz/azure-resourcemanager-logz/README.md @@ -1,5 +1,7 @@ # Azure Resource Manager logz client library for Java +Please note, this package has been deprecated and will no longer be maintained after 01/01/2025. Refer to our deprecation policy (https://aka.ms/azsdk/support-policies) for more details. + Azure Resource Manager logz client library for Java. This package contains Microsoft Azure SDK for logz Management SDK. Package tag package-2020-10-01. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). @@ -32,7 +34,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-logz - 1.0.0-beta.3 + 1.0.0-beta.5 ``` [//]: # ({x-version-update-end}) @@ -52,7 +54,7 @@ Azure subscription ID can be configured via `AZURE_SUBSCRIPTION_ID` environment Assuming the use of the `DefaultAzureCredential` credential class, the client can be authenticated using the following code: ```java -AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); +AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); @@ -60,7 +62,7 @@ LogzManager manager = LogzManager .authenticate(credential, profile); ``` -The sample code assumes global Azure. Please change `AzureEnvironment.AZURE` variable if otherwise. +The sample code assumes global Azure. Please change the `AzureCloud.AZURE_PUBLIC_CLOUD` variable if otherwise. See [Authentication][authenticate] for more options. @@ -100,5 +102,3 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [cg]: https://github.com/Azure/azure-sdk-for-java/blob/main/CONTRIBUTING.md [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ - -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Flogz%2Fazure-resourcemanager-logz%2FREADME.png) diff --git a/sdk/logz/azure-resourcemanager-logz/pom.xml b/sdk/logz/azure-resourcemanager-logz/pom.xml index fe322542a97d..a529a61a4914 100644 --- a/sdk/logz/azure-resourcemanager-logz/pom.xml +++ b/sdk/logz/azure-resourcemanager-logz/pom.xml @@ -14,11 +14,11 @@ com.azure.resourcemanager azure-resourcemanager-logz - 1.0.0-beta.4 + 1.0.0-beta.5 jar Microsoft Azure SDK for logz Management - This package contains Microsoft Azure SDK for logz Management SDK. For documentation on how to use this package, please see https://aka.ms/azsdk/java/mgmt. Package tag package-2020-10-01. + Please note, this package has been deprecated and will no longer be maintained after 01/01/2025. Refer to our deprecation policy (https://aka.ms/azsdk/support-policies) for more details. https://github.com/Azure/azure-sdk-for-java @@ -46,28 +46,29 @@ 0 0 true + false com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/logz/azure-resourcemanager-logz/src/main/java/com/azure/resourcemanager/logz/LogzManager.java b/sdk/logz/azure-resourcemanager-logz/src/main/java/com/azure/resourcemanager/logz/LogzManager.java index 90e586dcf8e7..8ad987d1c82d 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/main/java/com/azure/resourcemanager/logz/LogzManager.java +++ b/sdk/logz/azure-resourcemanager-logz/src/main/java/com/azure/resourcemanager/logz/LogzManager.java @@ -11,6 +11,7 @@ import com.azure.core.http.HttpPipelinePosition; import com.azure.core.http.policy.AddDatePolicy; import com.azure.core.http.policy.AddHeadersFromContextPolicy; +import com.azure.core.http.policy.BearerTokenAuthenticationPolicy; import com.azure.core.http.policy.HttpLogOptions; import com.azure.core.http.policy.HttpLoggingPolicy; import com.azure.core.http.policy.HttpPipelinePolicy; @@ -19,7 +20,6 @@ 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.management.http.policy.ArmChallengeAuthenticationPolicy; import com.azure.core.management.profile.AzureProfile; import com.azure.core.util.Configuration; import com.azure.core.util.logging.ClientLogger; @@ -228,7 +228,7 @@ public LogzManager authenticate(TokenCredential credential, AzureProfile profile .append("-") .append("com.azure.resourcemanager.logz") .append("/") - .append("1.0.0-beta.3"); + .append("1.0.0-beta.4"); if (!Configuration.getGlobalConfiguration().get("AZURE_TELEMETRY_DISABLED", false)) { userAgentBuilder.append(" (") .append(Configuration.getGlobalConfiguration().get("java.version")) @@ -261,7 +261,7 @@ public LogzManager authenticate(TokenCredential credential, AzureProfile profile HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy); policies.add(new AddDatePolicy()); - policies.add(new ArmChallengeAuthenticationPolicy(credential, scopes.toArray(new String[0]))); + policies.add(new BearerTokenAuthenticationPolicy(credential, scopes.toArray(new String[0]))); policies.addAll(this.policies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .collect(Collectors.toList())); diff --git a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorOperationsListVMHostsMockTests.java b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorOperationsListVMHostsMockTests.java index 934312abeb94..ceeb0b967c5b 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorOperationsListVMHostsMockTests.java +++ b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorOperationsListVMHostsMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.logz.LogzManager; import com.azure.resourcemanager.logz.models.VMResources; @@ -28,7 +28,7 @@ public void testListVMHosts() throws Exception { LogzManager manager = LogzManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.monitorOperations().listVMHosts("qhoftrmaequiah", "icslfaoq", com.azure.core.util.Context.NONE); diff --git a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorOperationsListVmHostUpdateMockTests.java b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorOperationsListVmHostUpdateMockTests.java index 1bf729cf7dd1..14d18d928f4d 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorOperationsListVmHostUpdateMockTests.java +++ b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorOperationsListVmHostUpdateMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.logz.LogzManager; import com.azure.resourcemanager.logz.fluent.models.VMResourcesInner; @@ -32,7 +32,7 @@ public void testListVmHostUpdate() throws Exception { LogzManager manager = LogzManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.monitorOperations() .listVmHostUpdate("qqmoaku", "gm", diff --git a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorsCreateMockTests.java b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorsCreateMockTests.java index 62577f7b9fc6..839ff102f4f7 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorsCreateMockTests.java +++ b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorsCreateMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.logz.LogzManager; import com.azure.resourcemanager.logz.models.IdentityProperties; @@ -38,7 +38,7 @@ public void testCreate() throws Exception { LogzManager manager = LogzManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); LogzMonitorResource response = manager.monitors() .define("lpvlopw") diff --git a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorsDeleteMockTests.java b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorsDeleteMockTests.java index f1bf1089ca5c..3e9a79711456 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorsDeleteMockTests.java +++ b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorsDeleteMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.logz.LogzManager; import java.nio.charset.StandardCharsets; @@ -25,7 +25,7 @@ public void testDelete() throws Exception { LogzManager manager = LogzManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); manager.monitors().delete("xbzpfzab", "lcuhxwtctyqiklb", com.azure.core.util.Context.NONE); diff --git a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorsGetByResourceGroupWithResponseMockTests.java b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorsGetByResourceGroupWithResponseMockTests.java index 14ca82c0a63d..1607cc2d987d 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorsGetByResourceGroupWithResponseMockTests.java +++ b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorsGetByResourceGroupWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.logz.LogzManager; import com.azure.resourcemanager.logz.models.LogzMonitorResource; @@ -31,7 +31,7 @@ public void testGetByResourceGroupWithResponse() throws Exception { LogzManager manager = LogzManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); LogzMonitorResource response = manager.monitors() .getByResourceGroupWithResponse("qzahmgkbrp", "y", com.azure.core.util.Context.NONE) diff --git a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorsListByResourceGroupMockTests.java b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorsListByResourceGroupMockTests.java index dddb346ed826..ef630fc2d278 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorsListByResourceGroupMockTests.java +++ b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorsListByResourceGroupMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.logz.LogzManager; import com.azure.resourcemanager.logz.models.LogzMonitorResource; @@ -32,7 +32,7 @@ public void testListByResourceGroup() throws Exception { LogzManager manager = LogzManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.monitors().listByResourceGroup("gyxzk", com.azure.core.util.Context.NONE); diff --git a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorsListMockTests.java b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorsListMockTests.java index d8b19e1613ac..58c1c33266e0 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorsListMockTests.java +++ b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorsListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.logz.LogzManager; import com.azure.resourcemanager.logz.models.LogzMonitorResource; @@ -32,7 +32,7 @@ public void testList() throws Exception { LogzManager manager = LogzManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.monitors().list(com.azure.core.util.Context.NONE); diff --git a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorsListMonitoredResourcesMockTests.java b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorsListMonitoredResourcesMockTests.java index 3a407990c040..5a46c6861b09 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorsListMonitoredResourcesMockTests.java +++ b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorsListMonitoredResourcesMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.logz.LogzManager; import com.azure.resourcemanager.logz.models.MonitoredResource; @@ -29,7 +29,7 @@ public void testListMonitoredResources() throws Exception { LogzManager manager = LogzManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.monitors().listMonitoredResources("ied", "ugidyjrr", com.azure.core.util.Context.NONE); diff --git a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorsListUserRolesMockTests.java b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorsListUserRolesMockTests.java index d228df68e821..8df0bb966ff2 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorsListUserRolesMockTests.java +++ b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/MonitorsListUserRolesMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.logz.LogzManager; import com.azure.resourcemanager.logz.models.UserRole; @@ -30,7 +30,7 @@ public void testListUserRoles() throws Exception { LogzManager manager = LogzManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.monitors() .listUserRoles("ovplw", "bhvgy", new UserRoleRequest().withEmailAddress("uosvmkfssxqukk"), diff --git a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/OperationsListMockTests.java b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/OperationsListMockTests.java index 9f618fc248ee..93e89e40d914 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/OperationsListMockTests.java +++ b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/OperationsListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.logz.LogzManager; import com.azure.resourcemanager.logz.models.OperationResult; @@ -29,7 +29,7 @@ public void testList() throws Exception { LogzManager manager = LogzManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.operations().list(com.azure.core.util.Context.NONE); diff --git a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SingleSignOnsCreateOrUpdateMockTests.java b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SingleSignOnsCreateOrUpdateMockTests.java index 8f13fdcabf88..9075559718f9 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SingleSignOnsCreateOrUpdateMockTests.java +++ b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SingleSignOnsCreateOrUpdateMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.logz.LogzManager; import com.azure.resourcemanager.logz.models.LogzSingleSignOnProperties; @@ -30,7 +30,7 @@ public void testCreateOrUpdate() throws Exception { LogzManager manager = LogzManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); LogzSingleSignOnResource response = manager.singleSignOns() .define("gjb") diff --git a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SingleSignOnsGetWithResponseMockTests.java b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SingleSignOnsGetWithResponseMockTests.java index d791856f9026..178246256a8b 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SingleSignOnsGetWithResponseMockTests.java +++ b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SingleSignOnsGetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.logz.LogzManager; import com.azure.resourcemanager.logz.models.LogzSingleSignOnResource; @@ -29,7 +29,7 @@ public void testGetWithResponse() throws Exception { LogzManager manager = LogzManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); LogzSingleSignOnResource response = manager.singleSignOns() .getWithResponse("szjfauvjfdxxivet", "t", "qaqtdoqmcbxvwvxy", com.azure.core.util.Context.NONE) diff --git a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SingleSignOnsListMockTests.java b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SingleSignOnsListMockTests.java index 218ae12e3392..d39a24d23609 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SingleSignOnsListMockTests.java +++ b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SingleSignOnsListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.logz.LogzManager; import com.azure.resourcemanager.logz.models.LogzSingleSignOnResource; @@ -30,7 +30,7 @@ public void testList() throws Exception { LogzManager manager = LogzManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.singleSignOns().list("z", "ahzxctobgbk", com.azure.core.util.Context.NONE); diff --git a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountTagRulesCreateOrUpdateWithResponseMockTests.java b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountTagRulesCreateOrUpdateWithResponseMockTests.java index 8c723ffea1e4..e0f8be6e36df 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountTagRulesCreateOrUpdateWithResponseMockTests.java +++ b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountTagRulesCreateOrUpdateWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.logz.LogzManager; import com.azure.resourcemanager.logz.fluent.models.MonitoringTagRulesInner; @@ -34,7 +34,7 @@ public void testCreateOrUpdateWithResponse() throws Exception { LogzManager manager = LogzManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); MonitoringTagRules response = manager.subAccountTagRules() .createOrUpdateWithResponse("whxxbuyqax", "feqztppriol", "or", "altol", new MonitoringTagRulesInner() diff --git a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountTagRulesDeleteWithResponseMockTests.java b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountTagRulesDeleteWithResponseMockTests.java index 875fb874c6ca..0ec5c2cbfd63 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountTagRulesDeleteWithResponseMockTests.java +++ b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountTagRulesDeleteWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.logz.LogzManager; import java.nio.charset.StandardCharsets; @@ -25,7 +25,7 @@ public void testDeleteWithResponse() throws Exception { LogzManager manager = LogzManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); manager.subAccountTagRules() .deleteWithResponse("znkbykutwpfhpagm", "r", "kdsnfdsdoakgtdl", "kkze", com.azure.core.util.Context.NONE); diff --git a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountTagRulesGetWithResponseMockTests.java b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountTagRulesGetWithResponseMockTests.java index 738afae156ab..6fcece859129 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountTagRulesGetWithResponseMockTests.java +++ b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountTagRulesGetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.logz.LogzManager; import com.azure.resourcemanager.logz.models.MonitoringTagRules; @@ -29,7 +29,7 @@ public void testGetWithResponse() throws Exception { LogzManager manager = LogzManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); MonitoringTagRules response = manager.subAccountTagRules() .getWithResponse("waezkojvd", "pzfoqoui", "ybxarzgszu", "oxciqopidoamcio", com.azure.core.util.Context.NONE) diff --git a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountTagRulesListMockTests.java b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountTagRulesListMockTests.java index a669f6c88618..57914de1a1d3 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountTagRulesListMockTests.java +++ b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountTagRulesListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.logz.LogzManager; import com.azure.resourcemanager.logz.models.MonitoringTagRules; @@ -30,7 +30,7 @@ public void testList() throws Exception { LogzManager manager = LogzManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.subAccountTagRules().list("lfoakg", "kfpagao", "pulpqblylsyxk", com.azure.core.util.Context.NONE); diff --git a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsCreateMockTests.java b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsCreateMockTests.java index b32d57ba49b7..40836b707a95 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsCreateMockTests.java +++ b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsCreateMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.logz.LogzManager; import com.azure.resourcemanager.logz.fluent.models.LogzMonitorResourceInner; @@ -39,7 +39,7 @@ public void testCreate() throws Exception { LogzManager manager = LogzManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); LogzMonitorResource response = manager.subAccounts() .create("okonzmnsikvmkqz", "qqkdltfzxmhhvhgu", "eodkwobda", new LogzMonitorResourceInner() diff --git a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsDeleteMockTests.java b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsDeleteMockTests.java index cf2a3401aeb8..37a3275d312b 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsDeleteMockTests.java +++ b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsDeleteMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.logz.LogzManager; import java.nio.charset.StandardCharsets; @@ -25,7 +25,7 @@ public void testDelete() throws Exception { LogzManager manager = LogzManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); manager.subAccounts().delete("mwzn", "abikns", "rgjhxb", com.azure.core.util.Context.NONE); diff --git a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsGetWithResponseMockTests.java b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsGetWithResponseMockTests.java index e4c9446c3de6..559ad4336062 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsGetWithResponseMockTests.java +++ b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsGetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.logz.LogzManager; import com.azure.resourcemanager.logz.models.LogzMonitorResource; @@ -31,7 +31,7 @@ public void testGetWithResponse() throws Exception { LogzManager manager = LogzManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); LogzMonitorResource response = manager.subAccounts() .getWithResponse("nwashrtd", "kcnqxwbpo", "ulpiuj", com.azure.core.util.Context.NONE) diff --git a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsListMockTests.java b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsListMockTests.java index 940a2f6589c9..61cc49369711 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsListMockTests.java +++ b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.logz.LogzManager; import com.azure.resourcemanager.logz.models.LogzMonitorResource; @@ -32,7 +32,7 @@ public void testList() throws Exception { LogzManager manager = LogzManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.subAccounts().list("nzdndslgna", "qig", com.azure.core.util.Context.NONE); diff --git a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsListMonitoredResourcesMockTests.java b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsListMonitoredResourcesMockTests.java index 7ee995190d24..d13372f01599 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsListMonitoredResourcesMockTests.java +++ b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsListMonitoredResourcesMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.logz.LogzManager; import com.azure.resourcemanager.logz.models.MonitoredResource; @@ -29,7 +29,7 @@ public void testListMonitoredResources() throws Exception { LogzManager manager = LogzManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.subAccounts() .listMonitoredResources("hlyfjhdgqgg", "bdunygaeqid", "qfatpxllrxcyjm", com.azure.core.util.Context.NONE); diff --git a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsListVMHostsMockTests.java b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsListVMHostsMockTests.java index b4c122186791..4f32bfb7248c 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsListVMHostsMockTests.java +++ b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsListVMHostsMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.logz.LogzManager; import com.azure.resourcemanager.logz.models.VMResources; @@ -28,7 +28,7 @@ public void testListVMHosts() throws Exception { LogzManager manager = LogzManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.subAccounts() .listVMHosts("nwxuqlcvydyp", "tdooaoj", "niodkooeb", com.azure.core.util.Context.NONE); diff --git a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsListVmHostUpdateMockTests.java b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsListVmHostUpdateMockTests.java index 65719684190a..c302375057f8 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsListVmHostUpdateMockTests.java +++ b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsListVmHostUpdateMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.logz.LogzManager; import com.azure.resourcemanager.logz.fluent.models.VMResourcesInner; @@ -32,7 +32,7 @@ public void testListVmHostUpdate() throws Exception { LogzManager manager = LogzManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.subAccounts() .listVmHostUpdate("mzqa", "krmnjijpxacqqud", "nbyxbaaabjyv", diff --git a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsUpdateWithResponseMockTests.java b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsUpdateWithResponseMockTests.java index 783ae037bb3a..3d65f8ccc6ea 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsUpdateWithResponseMockTests.java +++ b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/SubAccountsUpdateWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.logz.LogzManager; import com.azure.resourcemanager.logz.models.LogzMonitorResource; @@ -35,7 +35,7 @@ public void testUpdateWithResponse() throws Exception { LogzManager manager = LogzManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); LogzMonitorResource response = manager.subAccounts() .updateWithResponse("dtlwwrlkd", "tncvokot", "lxdy", diff --git a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/TagRulesCreateOrUpdateWithResponseMockTests.java b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/TagRulesCreateOrUpdateWithResponseMockTests.java index 8c0321cc4f14..927dfb31be05 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/TagRulesCreateOrUpdateWithResponseMockTests.java +++ b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/TagRulesCreateOrUpdateWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.logz.LogzManager; import com.azure.resourcemanager.logz.models.FilteringTag; @@ -33,7 +33,7 @@ public void testCreateOrUpdateWithResponse() throws Exception { LogzManager manager = LogzManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); MonitoringTagRules response = manager.tagRules() .define("oekqvk") diff --git a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/TagRulesDeleteWithResponseMockTests.java b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/TagRulesDeleteWithResponseMockTests.java index eb458623a413..7f47ff52aa9d 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/TagRulesDeleteWithResponseMockTests.java +++ b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/TagRulesDeleteWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.logz.LogzManager; import java.nio.charset.StandardCharsets; @@ -25,7 +25,7 @@ public void testDeleteWithResponse() throws Exception { LogzManager manager = LogzManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); manager.tagRules().deleteWithResponse("xdult", "kzbbtd", "umveekgpwozuhkf", com.azure.core.util.Context.NONE); diff --git a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/TagRulesGetWithResponseMockTests.java b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/TagRulesGetWithResponseMockTests.java index 986129c99ce8..2495e1610781 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/TagRulesGetWithResponseMockTests.java +++ b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/TagRulesGetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.logz.LogzManager; import com.azure.resourcemanager.logz.models.MonitoringTagRules; @@ -29,7 +29,7 @@ public void testGetWithResponse() throws Exception { LogzManager manager = LogzManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); MonitoringTagRules response = manager.tagRules() .getWithResponse("ro", "qbex", "mcqibycnojv", com.azure.core.util.Context.NONE) diff --git a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/TagRulesListMockTests.java b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/TagRulesListMockTests.java index bc55248f8bdb..c8bf101c1f6d 100644 --- a/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/TagRulesListMockTests.java +++ b/sdk/logz/azure-resourcemanager-logz/src/test/java/com/azure/resourcemanager/logz/generated/TagRulesListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.logz.LogzManager; import com.azure.resourcemanager.logz.models.MonitoringTagRules; @@ -30,7 +30,7 @@ public void testList() throws Exception { LogzManager manager = LogzManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.tagRules().list("kbegibt", "mxiebw", com.azure.core.util.Context.NONE); diff --git a/sdk/machinelearning/azure-resourcemanager-machinelearning/README.md b/sdk/machinelearning/azure-resourcemanager-machinelearning/README.md index 4184eaf56d90..d6e0a036eb7a 100644 --- a/sdk/machinelearning/azure-resourcemanager-machinelearning/README.md +++ b/sdk/machinelearning/azure-resourcemanager-machinelearning/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-machinelearning - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -144,4 +144,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fmachinelearning%2Fazure-resourcemanager-machinelearning%2FREADME.png) + diff --git a/sdk/machinelearning/azure-resourcemanager-machinelearning/pom.xml b/sdk/machinelearning/azure-resourcemanager-machinelearning/pom.xml index 37f3d22af960..55af068c0527 100644 --- a/sdk/machinelearning/azure-resourcemanager-machinelearning/pom.xml +++ b/sdk/machinelearning/azure-resourcemanager-machinelearning/pom.xml @@ -51,40 +51,40 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-storage - 2.46.0 + 2.48.0 test com.azure.resourcemanager azure-resourcemanager-keyvault - 2.46.0 + 2.48.0 test @@ -96,7 +96,7 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/maintenance/azure-resourcemanager-maintenance/README.md b/sdk/maintenance/azure-resourcemanager-maintenance/README.md index 5da409b3ea11..e95fad2f714e 100644 --- a/sdk/maintenance/azure-resourcemanager-maintenance/README.md +++ b/sdk/maintenance/azure-resourcemanager-maintenance/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-maintenance - 1.1.0-beta.2 + 1.1.0-beta.3 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fmaintenance%2Fazure-resourcemanager-maintenance%2FREADME.png) + diff --git a/sdk/maintenance/azure-resourcemanager-maintenance/pom.xml b/sdk/maintenance/azure-resourcemanager-maintenance/pom.xml index a3c2f873687e..5c367c40e2af 100644 --- a/sdk/maintenance/azure-resourcemanager-maintenance/pom.xml +++ b/sdk/maintenance/azure-resourcemanager-maintenance/pom.xml @@ -52,29 +52,29 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/managedapplications/azure-resourcemanager-managedapplications/README.md b/sdk/managedapplications/azure-resourcemanager-managedapplications/README.md index ab1b6d11c37e..371bfa45a132 100644 --- a/sdk/managedapplications/azure-resourcemanager-managedapplications/README.md +++ b/sdk/managedapplications/azure-resourcemanager-managedapplications/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-managedapplications - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fmanagedapplications%2Fazure-resourcemanager-managedapplications%2FREADME.png) + diff --git a/sdk/managedapplications/azure-resourcemanager-managedapplications/pom.xml b/sdk/managedapplications/azure-resourcemanager-managedapplications/pom.xml index da6b2c5e49eb..b5404d895954 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.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/managednetworkfabric/azure-resourcemanager-managednetworkfabric/README.md b/sdk/managednetworkfabric/azure-resourcemanager-managednetworkfabric/README.md index 1503d5fd9bc2..d08de63fef32 100644 --- a/sdk/managednetworkfabric/azure-resourcemanager-managednetworkfabric/README.md +++ b/sdk/managednetworkfabric/azure-resourcemanager-managednetworkfabric/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-managednetworkfabric - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -143,4 +143,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fmanagednetworkfabric%2Fazure-resourcemanager-managednetworkfabric%2FREADME.png) + diff --git a/sdk/managednetworkfabric/azure-resourcemanager-managednetworkfabric/pom.xml b/sdk/managednetworkfabric/azure-resourcemanager-managednetworkfabric/pom.xml index f28ecc121856..6997d4ac029f 100644 --- a/sdk/managednetworkfabric/azure-resourcemanager-managednetworkfabric/pom.xml +++ b/sdk/managednetworkfabric/azure-resourcemanager-managednetworkfabric/pom.xml @@ -52,23 +52,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test @@ -92,7 +92,7 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/managementgroups/azure-resourcemanager-managementgroups/README.md b/sdk/managementgroups/azure-resourcemanager-managementgroups/README.md index cb5bb2c4332d..af04640695ff 100644 --- a/sdk/managementgroups/azure-resourcemanager-managementgroups/README.md +++ b/sdk/managementgroups/azure-resourcemanager-managementgroups/README.md @@ -35,7 +35,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-managementgroups - 1.0.0-beta.2 + 1.0.0-beta.3 ``` [//]: # ({x-version-update-end}) @@ -104,4 +104,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fmanagementgroups%2Fazure-resourcemanager-managementgroups%2FREADME.png) + diff --git a/sdk/managementgroups/azure-resourcemanager-managementgroups/pom.xml b/sdk/managementgroups/azure-resourcemanager-managementgroups/pom.xml index d21021f0974f..c4fc34de26ab 100644 --- a/sdk/managementgroups/azure-resourcemanager-managementgroups/pom.xml +++ b/sdk/managementgroups/azure-resourcemanager-managementgroups/pom.xml @@ -54,23 +54,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/maps/azure-maps-geolocation/README.md b/sdk/maps/azure-maps-geolocation/README.md index c1d49c9980aa..6f8a56fa6295 100644 --- a/sdk/maps/azure-maps-geolocation/README.md +++ b/sdk/maps/azure-maps-geolocation/README.md @@ -26,7 +26,7 @@ Various documentation is available to help you get started com.azure azure-maps-geolocation - 1.0.0-beta.3 + 1.0.0-beta.4 ``` [//]: # ({x-version-update-end}) @@ -112,4 +112,4 @@ For details on contributing to this repository, see the [contributing guide](htt [authenticate]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/resourcemanager/docs/AUTH.md [design]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/resourcemanager/docs/DESIGN.md -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fmaps%2Fazure-maps-geolocation%2FREADME.png) + diff --git a/sdk/maps/azure-maps-geolocation/pom.xml b/sdk/maps/azure-maps-geolocation/pom.xml index 9be43c380167..f6a5cec0dbbc 100644 --- a/sdk/maps/azure-maps-geolocation/pom.xml +++ b/sdk/maps/azure-maps-geolocation/pom.xml @@ -59,23 +59,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test diff --git a/sdk/maps/azure-maps-render/README.md b/sdk/maps/azure-maps-render/README.md index d6068b9103de..3d85d4882848 100644 --- a/sdk/maps/azure-maps-render/README.md +++ b/sdk/maps/azure-maps-render/README.md @@ -26,7 +26,7 @@ Various documentation is available to help you get started com.azure azure-maps-render - 2.0.0-beta.2 + 2.0.0-beta.3 ``` [//]: # ({x-version-update-end}) @@ -167,4 +167,4 @@ For details on contributing to this repository, see the [contributing guide](htt [authenticate]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/resourcemanager/docs/AUTH.md [design]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/resourcemanager/docs/DESIGN.md -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fmaps%2Fazure-maps-render%2FREADME.png) + diff --git a/sdk/maps/azure-maps-render/pom.xml b/sdk/maps/azure-maps-render/pom.xml index 37b6ac5f5169..1c276cb00679 100644 --- a/sdk/maps/azure-maps-render/pom.xml +++ b/sdk/maps/azure-maps-render/pom.xml @@ -62,23 +62,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test diff --git a/sdk/maps/azure-maps-route/README.md b/sdk/maps/azure-maps-route/README.md index f23a0e2e8482..aaeb1e37b0a1 100644 --- a/sdk/maps/azure-maps-route/README.md +++ b/sdk/maps/azure-maps-route/README.md @@ -26,7 +26,7 @@ Various documentation is available to help you get started com.azure azure-maps-route - 1.0.0-beta.3 + 1.0.0-beta.4 ``` [//]: # ({x-version-update-end}) @@ -223,4 +223,4 @@ For details on contributing to this repository, see the [contributing guide](htt [authenticate]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/resourcemanager/docs/AUTH.md [design]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/resourcemanager/docs/DESIGN.md -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fmaps%2Fazure-maps-route%2FREADME.png) + diff --git a/sdk/maps/azure-maps-route/pom.xml b/sdk/maps/azure-maps-route/pom.xml index 6741e2935bb1..13cee83506df 100644 --- a/sdk/maps/azure-maps-route/pom.xml +++ b/sdk/maps/azure-maps-route/pom.xml @@ -60,23 +60,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test diff --git a/sdk/maps/azure-maps-search/README.md b/sdk/maps/azure-maps-search/README.md index fb9b000f05c4..250a1221d3e8 100644 --- a/sdk/maps/azure-maps-search/README.md +++ b/sdk/maps/azure-maps-search/README.md @@ -26,7 +26,7 @@ Various documentation is available to help you get started com.azure azure-maps-search - 2.0.0-beta.2 + 2.0.0-beta.3 ``` [//]: # ({x-version-update-end}) @@ -192,4 +192,4 @@ For details on contributing to this repository, see the [contributing guide](htt [authenticate]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/resourcemanager/docs/AUTH.md [design]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/resourcemanager/docs/DESIGN.md -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fmaps%2Fazure-maps-search%2FREADME.png) + diff --git a/sdk/maps/azure-maps-search/pom.xml b/sdk/maps/azure-maps-search/pom.xml index db764677cfe9..fbfd826c5bb5 100644 --- a/sdk/maps/azure-maps-search/pom.xml +++ b/sdk/maps/azure-maps-search/pom.xml @@ -65,28 +65,28 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test diff --git a/sdk/maps/azure-maps-timezone/README.md b/sdk/maps/azure-maps-timezone/README.md index 9874c188f8ba..9c62b73890b5 100644 --- a/sdk/maps/azure-maps-timezone/README.md +++ b/sdk/maps/azure-maps-timezone/README.md @@ -26,7 +26,7 @@ Various documentation is available to help you get started com.azure azure-maps-timezone - 1.0.0-beta.2 + 1.0.0-beta.3 ``` [//]: # ({x-version-update-end}) @@ -140,4 +140,4 @@ For details on contributing to this repository, see the [contributing guide](htt [authenticate]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/resourcemanager/docs/AUTH.md [design]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/resourcemanager/docs/DESIGN.md -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fmaps%2Fazure-maps-timezone%2FREADME.png) + diff --git a/sdk/maps/azure-maps-timezone/pom.xml b/sdk/maps/azure-maps-timezone/pom.xml index 8bcd677f086f..e712785ff53c 100644 --- a/sdk/maps/azure-maps-timezone/pom.xml +++ b/sdk/maps/azure-maps-timezone/pom.xml @@ -59,28 +59,28 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test diff --git a/sdk/maps/azure-maps-traffic/README.md b/sdk/maps/azure-maps-traffic/README.md index ff856728cc67..cca4c4fbea80 100644 --- a/sdk/maps/azure-maps-traffic/README.md +++ b/sdk/maps/azure-maps-traffic/README.md @@ -27,7 +27,7 @@ Various documentation is available to help you get started com.azure azure-maps-traffic - 1.0.0-beta.1 + 1.0.0-beta.2 ``` [//]: # ({x-version-update-end}) @@ -198,4 +198,4 @@ For details on contributing to this repository, see the [contributing guide](htt [authenticate]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/resourcemanager/docs/AUTH.md [design]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/resourcemanager/docs/DESIGN.md -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fmaps%2Fazure-maps-traffic%2FREADME.png) + diff --git a/sdk/maps/azure-maps-traffic/pom.xml b/sdk/maps/azure-maps-traffic/pom.xml index eadb1b47f8ee..f092788668eb 100644 --- a/sdk/maps/azure-maps-traffic/pom.xml +++ b/sdk/maps/azure-maps-traffic/pom.xml @@ -56,23 +56,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test diff --git a/sdk/maps/azure-maps-weather/CHANGELOG.md b/sdk/maps/azure-maps-weather/CHANGELOG.md index 74797b80d82e..2988d8466ebc 100644 --- a/sdk/maps/azure-maps-weather/CHANGELOG.md +++ b/sdk/maps/azure-maps-weather/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.0.0-beta.3 (Unreleased) +## 1.0.0-beta.4 (Unreleased) ### Features Added @@ -10,6 +10,23 @@ ### Other Changes +## 1.0.0-beta.3 (2025-02-19) + +### Breaking Changes + +- Update to latest API spec. `temperatureSummary` returns `past3Hours`, `past6Hours`, `past9Hours`, `past12Hours`, `past18Hours`, and `past24Hours`. +- Rename methods: + - `getAirQualityDailyForecasts` to `getDailyAirQualityForecasts` + - `getAirQualityHourlyForecasts` to `getHourlyAirQualityForecasts` + - `getGovId` to `getGovernmentId` in `ActiveStorm` class +- Update `getCurrentConditions` function signature +- Remove `getNextLink` in all classes +- Remove `isActive` method from `ActiveStorm` class + +### Other Changes + +- Upgrade `@autorest/java` version + ## 1.0.0-beta.2 (2024-12-27) ### Features Added diff --git a/sdk/maps/azure-maps-weather/README.md b/sdk/maps/azure-maps-weather/README.md index 3ceba5c15500..becb754c3ba8 100644 --- a/sdk/maps/azure-maps-weather/README.md +++ b/sdk/maps/azure-maps-weather/README.md @@ -26,7 +26,7 @@ Various documentation is available to help you get started com.azure azure-maps-weather - 1.0.0-beta.2 + 1.0.0-beta.4 ``` [//]: # ({x-version-update-end}) @@ -92,7 +92,7 @@ client.getQuarterDayForecast(new GeoPosition(-122.138874, 47.632346), null, 1, n Get Current Conditions ```java com.azure.maps.weather.sync.get_current_conditions client.getCurrentConditions(new GeoPosition(-122.125679, 47.641268), - null, null, null, null); + null, true, null, null); ``` Get Daily Forecast @@ -134,7 +134,7 @@ Get Tropical Storm Search ActiveStormResult result = client.getTropicalStormActive(); if (result.getActiveStorms().size() > 0) { ActiveStorm storm = result.getActiveStorms().get(0); - client.searchTropicalStorm(storm.getYear(), storm.getBasinId(), storm.getGovId()); + client.searchTropicalStorm(storm.getYear(), storm.getBasinId(), storm.getGovernmentId()); } ``` @@ -144,8 +144,8 @@ ActiveStormResult result = client.getTropicalStormActive(); if (result.getActiveStorms().size() > 0) { ActiveStorm storm = result.getActiveStorms().get(0); TropicalStormForecastOptions forecastOptions = new TropicalStormForecastOptions(storm.getYear(), - storm.getBasinId(), storm.getGovId()) - .setIncludeWindowGeometry(true); + storm.getBasinId(), storm.getGovernmentId()) + .setIncludeWindowGeometry(true); client.getTropicalStormForecast(forecastOptions); } ``` @@ -156,7 +156,7 @@ ActiveStormResult result = client.getTropicalStormActive(); if (result.getActiveStorms().size() > 0) { ActiveStorm storm = result.getActiveStorms().get(0); TropicalStormLocationOptions locationOptions = new TropicalStormLocationOptions(storm.getYear(), - storm.getBasinId(), storm.getGovId()); + storm.getBasinId(), storm.getGovernmentId()); client.getTropicalStormLocations(locationOptions); } ``` @@ -164,19 +164,19 @@ if (result.getActiveStorms().size() > 0) { Get Current Air Quality ```java com.azure.maps.weather.sync.get_current_air_quality client.getCurrentAirQuality( - new GeoPosition(-122.138874, 47.632346), "es", false); + new GeoPosition(-122.138874, 47.632346), "es", false); ``` Get Air Quality Daily Forecasts ```java com.azure.maps.weather.sync.get_air_quality_daily_forecasts -client.getAirQualityDailyForecasts( - new GeoPosition(-122.138874, 47.632346), "en", DailyDuration.TWO_DAYS); +client.getDailyAirQualityForecast( + new GeoPosition(-122.138874, 47.632346), "en", DailyDuration.TWO_DAYS); ``` Get Air Quality Hourly Forecasts ```java com.azure.maps.weather.sync.get_air_quality_daily_forecasts -client.getAirQualityDailyForecasts( - new GeoPosition(-122.138874, 47.632346), "en", DailyDuration.TWO_DAYS); +client.getDailyAirQualityForecast( + new GeoPosition(-122.138874, 47.632346), "en", DailyDuration.TWO_DAYS); ``` Get Daily Historical Actuals @@ -233,4 +233,4 @@ For details on contributing to this repository, see the [contributing guide](htt [authenticate]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/resourcemanager/docs/AUTH.md [design]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/resourcemanager/docs/DESIGN.md -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fmaps%2Fazure-maps-weather%2FREADME.png) + diff --git a/sdk/maps/azure-maps-weather/assets.json b/sdk/maps/azure-maps-weather/assets.json index e1cb3f423ca6..986bc7b34da3 100644 --- a/sdk/maps/azure-maps-weather/assets.json +++ b/sdk/maps/azure-maps-weather/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "java", "TagPrefix": "java/maps/azure-maps-weather", - "Tag": "java/maps/azure-maps-weather_4953d9fa59" -} + "Tag": "java/maps/azure-maps-weather_54ec2016fc" +} \ No newline at end of file diff --git a/sdk/maps/azure-maps-weather/pom.xml b/sdk/maps/azure-maps-weather/pom.xml index 083b7015c703..4046b0e19adf 100644 --- a/sdk/maps/azure-maps-weather/pom.xml +++ b/sdk/maps/azure-maps-weather/pom.xml @@ -11,7 +11,7 @@ com.azure azure-maps-weather - 1.0.0-beta.3 + 1.0.0-beta.4 jar Azure Maps SDK Weather client library @@ -56,28 +56,28 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/WeatherAsyncClient.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/WeatherAsyncClient.java index 39c466933876..6e731464b61f 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/WeatherAsyncClient.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/WeatherAsyncClient.java @@ -20,6 +20,7 @@ import com.azure.maps.weather.models.ActiveStormResult; import com.azure.maps.weather.models.AirQualityResult; import com.azure.maps.weather.models.BasinId; +import com.azure.maps.weather.models.CurrentConditionDuration; import com.azure.maps.weather.models.CurrentConditionsResult; import com.azure.maps.weather.models.DailyAirQualityForecastResult; import com.azure.maps.weather.models.DailyDuration; @@ -52,7 +53,8 @@ /** * Initializes a new instance of the asynchronous WeatherClient type. - * Creating an async client using a {@link com.azure.core.credential.AzureKeyCredential}: + * Creating an async client using a + * {@link com.azure.core.credential.AzureKeyCredential}: * *
            * // Authenticates using subscription key
          @@ -92,32 +94,52 @@ public final class WeatherAsyncClient {
                * 
          * * - *

          **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

          + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

          Request detailed weather forecast by the hour for the next 1, 12, 24 (1 day), 72 (3 days), 120 (5 days), and - * 240 hours (10 days) for the given coordinate location. The API returns details such as temperature, humidity, + *

          + * Request detailed weather forecast by the hour for the next 1, 12, 24 (1 day), + * 72 (3 days), 120 (5 days), and + * 240 hours (10 days) for the given coordinate location. The API returns + * details such as temperature, humidity, * wind, precipitation, and ultraviolet (UV) index. * - *

          In S0 you can request hourly forecast for the next 1, 12, 24 hours (1 day), and 72 hours (3 days). In S1 you - * can also request hourly forecast for the next 120 (5 days) and 240 hours (10 days). + *

          + * In S0 you can request hourly forecast for the next 1, 12, 24 hours (1 day), + * and 72 hours (3 days). In S1 you + * can also request hourly forecast for the next 120 (5 days) and 240 hours (10 + * days). * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. - * @param duration Time frame of the returned weather forecast. By default, the forecast data for next hour will be - * returned. Available values are * `1` - Return forecast data for the next hour. Default value. * `12` - Return - * hourly forecast for next 12 hours. * `24` - Return hourly forecast for next 24 hours. * `72` - Return hourly - * forecast for next 72 hours (3 days). * `120` - Return hourly forecast for next 120 hours (5 days). Only - * available in S1 SKU. * `240` - Return hourly forecast for next 240 hours (10 days). Only available in S1 SKU. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. + * @param duration Time frame of the returned weather forecast. By default, the + * forecast data for next hour will be + * returned. Available values are * `1` - Return forecast data + * for the next hour. Default value. * `12` - Return + * hourly forecast for next 12 hours. * `24` - Return hourly + * forecast for next 24 hours. * `72` - Return hourly + * forecast for next 72 hours (3 days). * `120` - Return hourly + * forecast for next 120 hours (5 days). Only + * available in S1 SKU. * `240` - Return hourly forecast for + * next 240 hours (10 days). Only available in S1 SKU. + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

          Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

          + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -135,32 +157,52 @@ public Mono getHourlyForecast(GeoPosition position, Weathe *

          * * - *

          **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

          + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

          Request detailed weather forecast by the hour for the next 1, 12, 24 (1 day), 72 (3 days), 120 (5 days), and - * 240 hours (10 days) for the given coordinate location. The API returns details such as temperature, + *

          + * Request detailed weather forecast by the hour for the next 1, 12, 24 (1 day), + * 72 (3 days), 120 (5 days), and + * 240 hours (10 days) for the given coordinate location. The API returns + * details such as temperature, * humidity, wind, precipitation, and ultraviolet (UV) index. * - *

          In S0 you can request hourly forecast for the next 1, 12, 24 hours (1 day), and 72 hours (3 days). In S1 you - * can also request hourly forecast for the next 120 (5 days) and 240 hours (10 days). + *

          + * In S0 you can request hourly forecast for the next 1, 12, 24 hours (1 day), + * and 72 hours (3 days). In S1 you + * can also request hourly forecast for the next 120 (5 days) and 240 hours (10 + * days). * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. - * @param duration Time frame of the returned weather forecast. By default, the forecast data for next hour will be - * returned. Available values are * `1` - Return forecast data for the next hour. Default value. * `12` - Return - * hourly forecast for next 12 hours. * `24` - Return hourly forecast for next 24 hours. * `72` - Return hourly - * forecast for next 72 hours (3 days). * `120` - Return hourly forecast for next 120 hours (5 days). Only - * available in S1 SKU. * `240` - Return hourly forecast for next 240 hours (10 days). Only available in S1 SKU. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. + * @param duration Time frame of the returned weather forecast. By default, the + * forecast data for next hour will be + * returned. Available values are * `1` - Return forecast data + * for the next hour. Default value. * `12` - Return + * hourly forecast for next 12 hours. * `24` - Return hourly + * forecast for next 24 hours. * `72` - Return hourly + * forecast for next 72 hours (3 days). * `120` - Return hourly + * forecast for next 120 hours (5 days). Only + * available in S1 SKU. * `240` - Return hourly forecast for + * next 240 hours (10 days). Only available in S1 SKU. + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

          Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

          + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -178,33 +220,53 @@ public Mono> getHourlyForecastWithResponse(GeoPos *

        * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Request detailed weather forecast by the hour for the next 1, 12, 24 (1 day), 72 (3 days), 120 (5 days), and - * 240 hours (10 days) for the given coordinate location. The API returns details such as temperature, humidity, + *

        + * Request detailed weather forecast by the hour for the next 1, 12, 24 (1 day), + * 72 (3 days), 120 (5 days), and + * 240 hours (10 days) for the given coordinate location. The API returns + * details such as temperature, humidity, * wind, precipitation, and ultraviolet (UV) index. * - *

        In S0 you can request hourly forecast for the next 1, 12, 24 hours (1 day), and 72 hours (3 days). In S1 you - * can also request hourly forecast for the next 120 (5 days) and 240 hours (10 days). + *

        + * In S0 you can request hourly forecast for the next 1, 12, 24 hours (1 day), + * and 72 hours (3 days). In S1 you + * can also request hourly forecast for the next 120 (5 days) and 240 hours (10 + * days). * * @param context The context to associate with this operation. - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. - * @param duration Time frame of the returned weather forecast. By default, the forecast data for next hour will be - * returned. Available values are * `1` - Return forecast data for the next hour. Default value. * `12` - Return - * hourly forecast for next 12 hours. * `24` - Return hourly forecast for next 24 hours. * `72` - Return hourly - * forecast for next 72 hours (3 days). * `120` - Return hourly forecast for next 120 hours (5 days). Only - * available in S1 SKU. * `240` - Return hourly forecast for next 240 hours (10 days). Only available in S1 SKU. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. + * @param duration Time frame of the returned weather forecast. By default, the + * forecast data for next hour will be + * returned. Available values are * `1` - Return forecast data + * for the next hour. Default value. * `12` - Return + * hourly forecast for next 12 hours. * `24` - Return hourly + * forecast for next 24 hours. * `72` - Return hourly + * forecast for next 72 hours (3 days). * `120` - Return hourly + * forecast for next 120 hours (5 days). Only + * available in S1 SKU. * `240` - Return hourly forecast for + * next 240 hours (10 days). Only available in S1 SKU. + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated Mono> getHourlyForecastWithResponse(GeoPosition position, WeatherDataUnit unit, @@ -224,27 +286,42 @@ Mono> getHourlyForecastWithResponse(GeoPosition p *

        * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get Minute Forecast service returns minute-by-minute forecasts for a given location for the next 120 minutes. - * Users can request weather forecasts in the interval of 1, 5 and 15 minutes. The response will include details - * such as the type of precipitation (including rain, snow, or a mixture of both), start time, and precipitation + *

        + * Get Minute Forecast service returns minute-by-minute forecasts for a given + * location for the next 120 minutes. + * Users can request weather forecasts in the interval of 1, 5 and 15 minutes. + * The response will include details + * such as the type of precipitation (including rain, snow, or a mixture of + * both), start time, and precipitation * intensity value (dBZ). * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param interval Specifies time interval in minutes for the returned weather forecast. Supported values are * `1` - * - Retrieve forecast for 1-minute intervals. Returned by default. * `5` - Retrieve forecasts for 5-minute - * intervals. * `15` - Retrieve forecasts for 15-minute intervals. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param interval Specifies time interval in minutes for the returned weather + * forecast. Supported values are * `1` + * - Retrieve forecast for 1-minute intervals. Returned by + * default. * `5` - Retrieve forecasts for 5-minute + * intervals. * `15` - Retrieve forecasts for 15-minute + * intervals. + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -261,27 +338,42 @@ public Mono getMinuteForecast(GeoPosition position, Intege *

        * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get Minute Forecast service returns minute-by-minute forecasts for a given location for the next 120 minutes. - * Users can request weather forecasts in the interval of 1, 5 and 15 minutes. The response will include details - * such as the type of precipitation (including rain, snow, or a mixture of both), start time, and precipitation + *

        + * Get Minute Forecast service returns minute-by-minute forecasts for a given + * location for the next 120 minutes. + * Users can request weather forecasts in the interval of 1, 5 and 15 minutes. + * The response will include details + * such as the type of precipitation (including rain, snow, or a mixture of + * both), start time, and precipitation * intensity value (dBZ). * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param interval Specifies time interval in minutes for the returned weather forecast. Supported values are * `1` - * - Retrieve forecast for 1-minute intervals. Returned by default. * `5` - Retrieve forecasts for 5-minute - * intervals. * `15` - Retrieve forecasts for 15-minute intervals. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param interval Specifies time interval in minutes for the returned weather + * forecast. Supported values are * `1` + * - Retrieve forecast for 1-minute intervals. Returned by + * default. * `5` - Retrieve forecasts for 5-minute + * intervals. * `15` - Retrieve forecasts for 15-minute + * intervals. + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -299,28 +391,43 @@ public Mono> getMinuteForecastWithResponse(GeoPos *

        * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get Minute Forecast service returns minute-by-minute forecasts for a given location for the next 120 minutes. - * Users can request weather forecasts in the interval of 1, 5 and 15 minutes. The response will include details - * such as the type of precipitation (including rain, snow, or a mixture of both), start time, and precipitation + *

        + * Get Minute Forecast service returns minute-by-minute forecasts for a given + * location for the next 120 minutes. + * Users can request weather forecasts in the interval of 1, 5 and 15 minutes. + * The response will include details + * such as the type of precipitation (including rain, snow, or a mixture of + * both), start time, and precipitation * intensity value (dBZ). * * @param context The context to associate with this operation. - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param interval Specifies time interval in minutes for the returned weather forecast. Supported values are * `1` - * - Retrieve forecast for 1-minute intervals. Returned by default. * `5` - Retrieve forecasts for 5-minute - * intervals. * `15` - Retrieve forecasts for 15-minute intervals. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param interval Specifies time interval in minutes for the returned weather + * forecast. Supported values are * `1` + * - Retrieve forecast for 1-minute intervals. Returned by + * default. * `5` - Retrieve forecasts for 5-minute + * intervals. * `15` - Retrieve forecasts for 15-minute + * intervals. + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated Mono> getMinuteForecastWithResponse(GeoPosition position, Integer interval, @@ -340,28 +447,44 @@ Mono> getMinuteForecastWithResponse(GeoPosition p * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Service returns detailed weather forecast by quarter-day for the next 1, 5, 10, or 15 days for a given - * location. Response data is presented by quarters of the day - morning, afternoon, evening, and overnight. Details - * such as temperature, humidity, wind, precipitation, and UV index are returned. + *

        + * Service returns detailed weather forecast by quarter-day for the next 1, 5, + * 10, or 15 days for a given + * location. Response data is presented by quarters of the day - morning, + * afternoon, evening, and overnight. Details + * such as temperature, humidity, wind, precipitation, and UV index are + * returned. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. - * @param duration Specifies for how many days the quester-day forecast responses are returned. Supported values - * are: * `1` - Return forecast data for the next day. Returned by default. * `5` - Return forecast data for the - * next 5 days. * `10` - Return forecast data for next 10 days. * `15` - Return forecast data for the next 15 + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. + * @param duration Specifies for how many days the quester-day forecast + * responses are returned. Supported values + * are: * `1` - Return forecast data for the next day. Returned + * by default. * `5` - Return forecast data for the + * next 5 days. * `10` - Return forecast data for next 10 days. + * * `15` - Return forecast data for the next 15 * days. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -379,28 +502,44 @@ public Mono getQuarterDayForecast(GeoPosition position * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Service returns detailed weather forecast by quarter-day for the next 1, 5, 10, or 15 days for a given - * location. Response data is presented by quarters of the day - morning, afternoon, evening, and overnight. Details - * such as temperature, humidity, wind, precipitation, and UV index are returned. + *

        + * Service returns detailed weather forecast by quarter-day for the next 1, 5, + * 10, or 15 days for a given + * location. Response data is presented by quarters of the day - morning, + * afternoon, evening, and overnight. Details + * such as temperature, humidity, wind, precipitation, and UV index are + * returned. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. - * @param duration Specifies for how many days the quester-day forecast responses are returned. Supported values - * are: * `1` - Return forecast data for the next day. Returned by default. * `5` - Return forecast data for the - * next 5 days. * `10` - Return forecast data for next 10 days. * `15` - Return forecast data for the next 15 + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. + * @param duration Specifies for how many days the quester-day forecast + * responses are returned. Supported values + * are: * `1` - Return forecast data for the next day. Returned + * by default. * `5` - Return forecast data for the + * next 5 days. * `10` - Return forecast data for next 10 days. + * * `15` - Return forecast data for the next 15 * days. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -418,29 +557,45 @@ public Mono> getQuarterDayForecastWithRespons * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Service returns detailed weather forecast by quarter-day for the next 1, 5, 10, or 15 days for a given - * location. Response data is presented by quarters of the day - morning, afternoon, evening, and overnight. Details - * such as temperature, humidity, wind, precipitation, and UV index are returned. + *

        + * Service returns detailed weather forecast by quarter-day for the next 1, 5, + * 10, or 15 days for a given + * location. Response data is presented by quarters of the day - morning, + * afternoon, evening, and overnight. Details + * such as temperature, humidity, wind, precipitation, and UV index are + * returned. * * @param context The context to associate with this operation. - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. - * @param duration Specifies for how many days the quester-day forecast responses are returned. Supported values - * are: * `1` - Return forecast data for the next day. Returned by default. * `5` - Return forecast data for the - * next 5 days. * `10` - Return forecast data for next 10 days. * `15` - Return forecast data for the next 15 + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. + * @param duration Specifies for how many days the quester-day forecast + * responses are returned. Supported values + * are: * `1` - Return forecast data for the next day. Returned + * by default. * `5` - Return forecast data for the + * next 5 days. * `10` - Return forecast data for next 10 days. + * * `15` - Return forecast data for the next 15 * days. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated Mono> getQuarterDayForecastWithResponse(GeoPosition position, @@ -457,44 +612,75 @@ Mono> getQuarterDayForecastWithResponse(GeoPo * *

              * asyncClient.getCurrentConditions(new GeoPosition(-122.125679, 47.641268),
        -     *     null, null, null, null);
        +     *     null, true, null, null);
              * 
        * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        Get Current Conditions service returns detailed current weather conditions such as precipitation, temperature - * and wind for a given coordinate location. Also, observations from the past 6 or 24 hours for a particular - * location can be retrieved. The basic information returned with the response include details such as observation - * date and time, brief description of the weather conditions, weather icon, precipitation indicator flags, and - * temperature. Additional details such as RealFeel™ Temperature and UV index are also returned. - * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * Get Current Conditions service returns detailed current weather conditions + * such as precipitation, temperature + * and wind for a given coordinate location. Also, observations from the past 6 + * or 24 hours for a particular + * location can be retrieved. The basic information returned with the response + * include details such as observation + * date and time, brief description of the weather conditions, weather icon, + * precipitation indicator flags, and + * temperature. Additional details such as RealFeel™ Temperature and UV index + * are also returned. + * + * @param position The applicable query specified as a comma separated + * string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. - * @param details Return full details for the current conditions. Available values are * `true` - Returns full - * details. By default, all details are returned. * `false` - Returns a truncated version of the current - * condition data, which includes observation date time, weather phrase, icon code, precipitation indicator + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. + * @param includeDetails Return full details for the current conditions. + * Available + * values are * `true` - Returns full + * details. By default, all details are returned. * + * `false` - + * Returns a truncated version of the current + * condition data, which includes observation date time, + * weather + * phrase, icon code, precipitation indicator * flag, and temperature. - * @param duration Time frame of the returned weather conditions. By default, the most current weather conditions - * will be returned. Default value is 0. Supported values are: * `0` - Return the most current weather - * conditions. * `6` - Return weather conditions from past 6 hours. * `24` - Return weather conditions from past + * @param duration Time frame of the returned weather conditions. By + * default, + * the most current weather conditions + * will be returned. Default value is 0. Supported values + * are: * + * `0` - Return the most current weather + * conditions. * `6` - Return weather conditions from past + * 6 + * hours. * `24` - Return weather conditions from past * 24 hours. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. + * Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language + * is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Mono getCurrentConditions(GeoPosition position, WeatherDataUnit unit, - String details, Integer duration, String language) { - return getCurrentConditionsWithResponse(position, unit, details, duration, language).flatMap(FluxUtil::toMono); + Boolean includeDetails, CurrentConditionDuration duration, String language) { + return getCurrentConditionsWithResponse(position, unit, includeDetails, duration, language) + .flatMap(FluxUtil::toMono); } /** @@ -503,45 +689,75 @@ public Mono getCurrentConditions(GeoPosition position, * *

              * asyncClient.getCurrentConditions(new GeoPosition(-122.125679, 47.641268),
        -     *     null, null, null, null);
        +     *     null, true, null, null);
              * 
        * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        Get Current Conditions service returns detailed current weather conditions such as precipitation, temperature - * and wind for a given coordinate location. Also, observations from the past 6 or 24 hours for a particular - * location can be retrieved. The basic information returned with the response include details such as observation - * date and time, brief description of the weather conditions, weather icon, precipitation indicator flags, and - * temperature. Additional details such as RealFeel™ Temperature and UV index are also returned. - * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * Get Current Conditions service returns detailed current weather conditions + * such as precipitation, temperature + * and wind for a given coordinate location. Also, observations from the past 6 + * or 24 hours for a particular + * location can be retrieved. The basic information returned with the response + * include details such as observation + * date and time, brief description of the weather conditions, weather icon, + * precipitation indicator flags, and + * temperature. Additional details such as RealFeel™ Temperature and UV index + * are also returned. + * + * @param position The applicable query specified as a comma separated + * string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. - * @param details Return full details for the current conditions. Available values are * `true` - Returns full - * details. By default, all details are returned. * `false` - Returns a truncated version of the current - * condition data, which includes observation date time, weather phrase, icon code, precipitation indicator + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. + * @param includeDetails Return full details for the current conditions. + * Available + * values are * `true` - Returns full + * details. By default, all details are returned. * + * `false` - + * Returns a truncated version of the current + * condition data, which includes observation date time, + * weather + * phrase, icon code, precipitation indicator * flag, and temperature. - * @param duration Time frame of the returned weather conditions. By default, the most current weather conditions - * will be returned. Default value is 0. Supported values are: * `0` - Return the most current weather - * conditions. * `6` - Return weather conditions from past 6 hours. * `24` - Return weather conditions from past + * @param duration Time frame of the returned weather conditions. By + * default, + * the most current weather conditions + * will be returned. Default value is 0. Supported values + * are: * + * `0` - Return the most current weather + * conditions. * `6` - Return weather conditions from past + * 6 + * hours. * `24` - Return weather conditions from past * 24 hours. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. + * Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language + * is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getCurrentConditionsWithResponse(GeoPosition position, - WeatherDataUnit unit, String details, Integer duration, String language) { + WeatherDataUnit unit, Boolean includeDetails, CurrentConditionDuration duration, String language) { return withContext( - context -> getCurrentConditionsWithResponse(position, unit, details, duration, language, context)); + context -> getCurrentConditionsWithResponse(position, unit, includeDetails, duration, language, context)); } /** @@ -550,47 +766,77 @@ public Mono> getCurrentConditionsWithResponse( * *

              * asyncClient.getCurrentConditions(new GeoPosition(-122.125679, 47.641268),
        -     *     null, null, null, null);
        +     *     null, true, null, null);
              * 
        * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        Get Current Conditions service returns detailed current weather conditions such as precipitation, temperature - * and wind for a given coordinate location. Also, observations from the past 6 or 24 hours for a particular - * location can be retrieved. The basic information returned with the response include details such as observation - * date and time, brief description of the weather conditions, weather icon, precipitation indicator flags, and - * temperature. Additional details such as RealFeel™ Temperature and UV index are also returned. + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * Get Current Conditions service returns detailed current weather conditions + * such as precipitation, temperature + * and wind for a given coordinate location. Also, observations from the past 6 + * or 24 hours for a particular + * location can be retrieved. The basic information returned with the response + * include details such as observation + * date and time, brief description of the weather conditions, weather icon, + * precipitation indicator flags, and + * temperature. Additional details such as RealFeel™ Temperature and UV index + * are also returned. * * @param context The context to associate with this operation. - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated + * string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. - * @param details Return full details for the current conditions. Available values are * `true` - Returns full - * details. By default, all details are returned. * `false` - Returns a truncated version of the current - * condition data, which includes observation date time, weather phrase, icon code, precipitation indicator + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. + * @param includeDetails Return full details for the current conditions. + * Available + * values are * `true` - Returns full + * details. By default, all details are returned. * + * `false` - + * Returns a truncated version of the current + * condition data, which includes observation date time, + * weather + * phrase, icon code, precipitation indicator * flag, and temperature. - * @param duration Time frame of the returned weather conditions. By default, the most current weather conditions - * will be returned. Default value is 0. Supported values are: * `0` - Return the most current weather - * conditions. * `6` - Return weather conditions from past 6 hours. * `24` - Return weather conditions from past + * @param duration Time frame of the returned weather conditions. By + * default, + * the most current weather conditions + * will be returned. Default value is 0. Supported values + * are: * + * `0` - Return the most current weather + * conditions. * `6` - Return weather conditions from past + * 6 + * hours. * `24` - Return weather conditions from past * 24 hours. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. + * Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language + * is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated Mono> getCurrentConditionsWithResponse(GeoPosition position, WeatherDataUnit unit, - String details, Integer duration, String language, Context context) { + Boolean includeDetails, CurrentConditionDuration duration, String language, Context context) { List coordinates = Arrays.asList(position.getLatitude(), position.getLongitude()); return this.serviceClient - .getCurrentConditionsWithResponseAsync(JsonFormat.JSON, coordinates, unit, details, duration, language, - context) + .getCurrentConditionsWithResponseAsync(JsonFormat.JSON, coordinates, unit, String.valueOf(includeDetails), + duration == null ? null : duration.getValue(), language, context) .onErrorMap(WeatherAsyncClient::mapThrowable); } @@ -603,31 +849,49 @@ Mono> getCurrentConditionsWithResponse(GeoPosi * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        The service returns detailed weather forecast such as temperature and wind by day for the next 1, 5, 10, 15, - * 25, or 45 days for a given coordinate location. The response include details such as temperature, wind, + *

        + * The service returns detailed weather forecast such as temperature and wind by + * day for the next 1, 5, 10, 15, + * 25, or 45 days for a given coordinate location. The response include details + * such as temperature, wind, * precipitation, air quality, and UV index. * - *

        In S0 you can request daily forecast for the next 1, 5, 10, and 15 days. In S1 you can also request daily + *

        + * In S0 you can request daily forecast for the next 1, 5, 10, and 15 days. In + * S1 you can also request daily * forecast for the next 25 days, and 45 days. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. - * @param duration Specifies for how many days the daily forecast responses are returned. Available values are * `1` - * - Return forecast data for the next day. Returned by default. * `5` - Return forecast data for the next 5 - * days. * `10` - Return forecast data for the next 10 days. * `25` - Return forecast data for the next 25 days. - * Only available in S1 SKU. * `45` - Return forecast data for the next 45 days. Only available in S1 SKU. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. + * @param duration Specifies for how many days the daily forecast responses are + * returned. Available values are * `1` + * - Return forecast data for the next day. Returned by default. + * * `5` - Return forecast data for the next 5 + * days. * `10` - Return forecast data for the next 10 days. * + * `25` - Return forecast data for the next 25 days. + * Only available in S1 SKU. * `45` - Return forecast data for + * the next 45 days. Only available in S1 SKU. + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -645,31 +909,49 @@ public Mono getDailyForecast(GeoPosition position, WeatherD * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        The service returns detailed weather forecast such as temperature and wind by day for the next 1, 5, 10, 15, - * 25, or 45 days for a given coordinate location. The response include details such as temperature, wind, + *

        + * The service returns detailed weather forecast such as temperature and wind by + * day for the next 1, 5, 10, 15, + * 25, or 45 days for a given coordinate location. The response include details + * such as temperature, wind, * precipitation, air quality, and UV index. * - *

        In S0 you can request daily forecast for the next 1, 5, 10, and 15 days. In S1 you can also request daily + *

        + * In S0 you can request daily forecast for the next 1, 5, 10, and 15 days. In + * S1 you can also request daily * forecast for the next 25 days, and 45 days. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. - * @param duration Specifies for how many days the daily forecast responses are returned. Available values are * `1` - * - Return forecast data for the next day. Returned by default. * `5` - Return forecast data for the next 5 - * days. * `10` - Return forecast data for the next 10 days. * `25` - Return forecast data for the next 25 days. - * Only available in S1 SKU. * `45` - Return forecast data for the next 45 days. Only available in S1 SKU. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. + * @param duration Specifies for how many days the daily forecast responses are + * returned. Available values are * `1` + * - Return forecast data for the next day. Returned by default. + * * `5` - Return forecast data for the next 5 + * days. * `10` - Return forecast data for the next 10 days. * + * `25` - Return forecast data for the next 25 days. + * Only available in S1 SKU. * `45` - Return forecast data for + * the next 45 days. Only available in S1 SKU. + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -687,32 +969,50 @@ public Mono> getDailyForecastWithResponse(GeoPosit * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        The service returns detailed weather forecast such as temperature and wind by day for the next 1, 5, 10, 15, - * 25, or 45 days for a given coordinate location. The response include details such as temperature, wind, + *

        + * The service returns detailed weather forecast such as temperature and wind by + * day for the next 1, 5, 10, 15, + * 25, or 45 days for a given coordinate location. The response include details + * such as temperature, wind, * precipitation, air quality, and UV index. * - *

        In S0 you can request daily forecast for the next 1, 5, 10, and 15 days. In S1 you can also request daily + *

        + * In S0 you can request daily forecast for the next 1, 5, 10, and 15 days. In + * S1 you can also request daily * forecast for the next 25 days, and 45 days. * * @param context The context to associate with this operation. - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. - * @param duration Specifies for how many days the daily forecast responses are returned. Available values are * `1` - * - Return forecast data for the next day. Returned by default. * `5` - Return forecast data for the next 5 - * days. * `10` - Return forecast data for the next 10 days. * `25` - Return forecast data for the next 25 days. - * Only available in S1 SKU. * `45` - Return forecast data for the next 45 days. Only available in S1 SKU. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. + * @param duration Specifies for how many days the daily forecast responses are + * returned. Available values are * `1` + * - Return forecast data for the next day. Returned by default. + * * `5` - Return forecast data for the next 5 + * days. * `10` - Return forecast data for the next 10 days. * + * `25` - Return forecast data for the next 25 days. + * Only available in S1 SKU. * `45` - Return forecast data for + * the next 45 days. Only available in S1 SKU. + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated Mono> getDailyForecastWithResponse(GeoPosition position, WeatherDataUnit unit, @@ -741,53 +1041,93 @@ Mono> getDailyForecastWithResponse(GeoPosition pos * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        Weather along a route API returns hyper local (one kilometer or less), up-to-the-minute weather nowcasts, - * weather hazard assessments, and notifications along a route described as a sequence of waypoints. This includes a - * list of weather hazards affecting the waypoint or route, and the aggregated hazard index for each waypoint might - * be used to paint each portion of a route according to how safe it is for the driver. When submitting the - * waypoints, it is recommended to stay within, or close to, the distance that can be traveled within 120-mins or + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * Weather along a route API returns hyper local (one kilometer or less), + * up-to-the-minute weather nowcasts, + * weather hazard assessments, and notifications along a route described as a + * sequence of waypoints. This includes a + * list of weather hazards affecting the waypoint or route, and the aggregated + * hazard index for each waypoint might + * be used to paint each portion of a route according to how safe it is for the + * driver. When submitting the + * waypoints, it is recommended to stay within, or close to, the distance that + * can be traveled within 120-mins or * shortly after. Data is updated every five minutes. * - *

        The service supplements Azure Maps [Route Service](https://docs.microsoft.com/rest/api/maps/route) that allows - * you to first request a route between an origin and a destination and use that as an input for Weather Along Route + *

        + * The service supplements Azure Maps [Route + * Service](https://docs.microsoft.com/rest/api/maps/route) that allows + * you to first request a route between an origin and a destination and use that + * as an input for Weather Along Route * endpoint. * - *

        In addition, the service supports scenarios to generate weather notifications for waypoints that experience an - * increase in intensity of a weather hazard. For example, if the vehicle is expected to begin experiencing heavy - * rain as it reaches a waypoint, a weather notification for heavy rain will be generated for that waypoint allowing - * the end product to display a heavy rain notification before the driver reaches that waypoint. The trigger for - * when to display the notification for a waypoint could be based, for example, on a - * [geofence](https://docs.microsoft.com/azure/azure-maps/tutorial-iot-hub-maps), or selectable distance to the + *

        + * In addition, the service supports scenarios to generate weather notifications + * for waypoints that experience an + * increase in intensity of a weather hazard. For example, if the vehicle is + * expected to begin experiencing heavy + * rain as it reaches a waypoint, a weather notification for heavy rain will be + * generated for that waypoint allowing + * the end product to display a heavy rain notification before the driver + * reaches that waypoint. The trigger for + * when to display the notification for a waypoint could be based, for example, + * on a + * [geofence](https://docs.microsoft.com/azure/azure-maps/tutorial-iot-hub-maps), + * or selectable distance to the * waypoint. * - *

        The API covers all regions of the planet except latitudes above Greenland and Antarctica. - * - * @param waypoints Coordinates through which the route is calculated, separated by colon (:) and entered in - * chronological order. A minimum of two waypoints is required. A single API call may contain up to 60 - * waypoints. A waypoint indicates location, ETA, and optional heading: latitude,longitude,ETA,heading, where * - * `Latitude` - Latitude coordinate in decimal degrees. * `Longitude` - Longitude coordinate in decimal degrees. - * * `ETA (estimated time of arrival)` - The number of minutes from the present time that it will take for the - * vehicle to reach the waypoint. Allowed range is from 0.0 to 120.0 minutes. * `Heading` - An optional value - * indicating the vehicle heading as it passes the waypoint. Expressed in clockwise degrees relative to true - * north. This is issued to calculate sun glare as a driving hazard. Allowed range is from 0.0 to 360.0 degrees. - * If not provided, a heading will automatically be derived based on the position of neighboring waypoints. - *

        It is recommended to stay within, or close to, the distance that can be traveled within 120-mins or - * shortly after. This way a more accurate assessment can be provided for the trip and prevent isolated events - * not being captured between waypoints. Information can and should be updated along the route (especially for - * trips greater than 2 hours) to continuously pull new waypoints moving forward, but also to ensure that - * forecast information for content such as precipitation type and intensity is accurate as storms develop and + *

        + * The API covers all regions of the planet except latitudes above Greenland and + * Antarctica. + * + * @param waypoints Coordinates through which the route is calculated, separated + * by colon (:) and entered in + * chronological order. A minimum of two waypoints is required. + * A single API call may contain up to 60 + * waypoints. A waypoint indicates location, ETA, and optional + * heading: latitude,longitude,ETA,heading, where * + * `Latitude` - Latitude coordinate in decimal degrees. * + * `Longitude` - Longitude coordinate in decimal degrees. + * * `ETA (estimated time of arrival)` - The number of minutes + * from the present time that it will take for the + * vehicle to reach the waypoint. Allowed range is from 0.0 to + * 120.0 minutes. * `Heading` - An optional value + * indicating the vehicle heading as it passes the waypoint. + * Expressed in clockwise degrees relative to true + * north. This is issued to calculate sun glare as a driving + * hazard. Allowed range is from 0.0 to 360.0 degrees. + * If not provided, a heading will automatically be derived + * based on the position of neighboring waypoints. + *

        + * It is recommended to stay within, or close to, the distance + * that can be traveled within 120-mins or + * shortly after. This way a more accurate assessment can be + * provided for the trip and prevent isolated events + * not being captured between waypoints. Information can and + * should be updated along the route (especially for + * trips greater than 2 hours) to continuously pull new + * waypoints moving forward, but also to ensure that + * forecast information for content such as precipitation type + * and intensity is accurate as storms develop and * dissipate over time. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @return this object is returned from a successful Weather Along Route. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -813,53 +1153,93 @@ public Mono getWeatherAlongRoute(List waypoin * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        Weather along a route API returns hyper local (one kilometer or less), up-to-the-minute weather nowcasts, - * weather hazard assessments, and notifications along a route described as a sequence of waypoints. This includes a - * list of weather hazards affecting the waypoint or route, and the aggregated hazard index for each waypoint might - * be used to paint each portion of a route according to how safe it is for the driver. When submitting the - * waypoints, it is recommended to stay within, or close to, the distance that can be traveled within 120-mins or + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * Weather along a route API returns hyper local (one kilometer or less), + * up-to-the-minute weather nowcasts, + * weather hazard assessments, and notifications along a route described as a + * sequence of waypoints. This includes a + * list of weather hazards affecting the waypoint or route, and the aggregated + * hazard index for each waypoint might + * be used to paint each portion of a route according to how safe it is for the + * driver. When submitting the + * waypoints, it is recommended to stay within, or close to, the distance that + * can be traveled within 120-mins or * shortly after. Data is updated every five minutes. * - *

        The service supplements Azure Maps [Route Service](https://docs.microsoft.com/rest/api/maps/route) that allows - * you to first request a route between an origin and a destination and use that as an input for Weather Along Route + *

        + * The service supplements Azure Maps [Route + * Service](https://docs.microsoft.com/rest/api/maps/route) that allows + * you to first request a route between an origin and a destination and use that + * as an input for Weather Along Route * endpoint. * - *

        In addition, the service supports scenarios to generate weather notifications for waypoints that experience an - * increase in intensity of a weather hazard. For example, if the vehicle is expected to begin experiencing heavy - * rain as it reaches a waypoint, a weather notification for heavy rain will be generated for that waypoint allowing - * the end product to display a heavy rain notification before the driver reaches that waypoint. The trigger for - * when to display the notification for a waypoint could be based, for example, on a - * [geofence](https://docs.microsoft.com/azure/azure-maps/tutorial-iot-hub-maps), or selectable distance to the + *

        + * In addition, the service supports scenarios to generate weather notifications + * for waypoints that experience an + * increase in intensity of a weather hazard. For example, if the vehicle is + * expected to begin experiencing heavy + * rain as it reaches a waypoint, a weather notification for heavy rain will be + * generated for that waypoint allowing + * the end product to display a heavy rain notification before the driver + * reaches that waypoint. The trigger for + * when to display the notification for a waypoint could be based, for example, + * on a + * [geofence](https://docs.microsoft.com/azure/azure-maps/tutorial-iot-hub-maps), + * or selectable distance to the * waypoint. * - *

        The API covers all regions of the planet except latitudes above Greenland and Antarctica. - * - * @param waypoints Coordinates through which the route is calculated, separated by colon (:) and entered in - * chronological order. A minimum of two waypoints is required. A single API call may contain up to 60 - * waypoints. A waypoint indicates location, ETA, and optional heading: latitude,longitude,ETA,heading, where * - * `Latitude` - Latitude coordinate in decimal degrees. * `Longitude` - Longitude coordinate in decimal degrees. - * * `ETA (estimated time of arrival)` - The number of minutes from the present time that it will take for the - * vehicle to reach the waypoint. Allowed range is from 0.0 to 120.0 minutes. * `Heading` - An optional value - * indicating the vehicle heading as it passes the waypoint. Expressed in clockwise degrees relative to true - * north. This is issued to calculate sun glare as a driving hazard. Allowed range is from 0.0 to 360.0 degrees. - * If not provided, a heading will automatically be derived based on the position of neighboring waypoints. - *

        It is recommended to stay within, or close to, the distance that can be traveled within 120-mins or - * shortly after. This way a more accurate assessment can be provided for the trip and prevent isolated events - * not being captured between waypoints. Information can and should be updated along the route (especially for - * trips greater than 2 hours) to continuously pull new waypoints moving forward, but also to ensure that - * forecast information for content such as precipitation type and intensity is accurate as storms develop and + *

        + * The API covers all regions of the planet except latitudes above Greenland and + * Antarctica. + * + * @param waypoints Coordinates through which the route is calculated, separated + * by colon (:) and entered in + * chronological order. A minimum of two waypoints is required. + * A single API call may contain up to 60 + * waypoints. A waypoint indicates location, ETA, and optional + * heading: latitude,longitude,ETA,heading, where * + * `Latitude` - Latitude coordinate in decimal degrees. * + * `Longitude` - Longitude coordinate in decimal degrees. + * * `ETA (estimated time of arrival)` - The number of minutes + * from the present time that it will take for the + * vehicle to reach the waypoint. Allowed range is from 0.0 to + * 120.0 minutes. * `Heading` - An optional value + * indicating the vehicle heading as it passes the waypoint. + * Expressed in clockwise degrees relative to true + * north. This is issued to calculate sun glare as a driving + * hazard. Allowed range is from 0.0 to 360.0 degrees. + * If not provided, a heading will automatically be derived + * based on the position of neighboring waypoints. + *

        + * It is recommended to stay within, or close to, the distance + * that can be traveled within 120-mins or + * shortly after. This way a more accurate assessment can be + * provided for the trip and prevent isolated events + * not being captured between waypoints. Information can and + * should be updated along the route (especially for + * trips greater than 2 hours) to continuously pull new + * waypoints moving forward, but also to ensure that + * forecast information for content such as precipitation type + * and intensity is accurate as storms develop and * dissipate over time. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @return this object is returned from a successful Weather Along Route. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -886,54 +1266,94 @@ public Mono> getWeatherAlongRouteWithResponse( * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        Weather along a route API returns hyper local (one kilometer or less), up-to-the-minute weather nowcasts, - * weather hazard assessments, and notifications along a route described as a sequence of waypoints. This includes a - * list of weather hazards affecting the waypoint or route, and the aggregated hazard index for each waypoint might - * be used to paint each portion of a route according to how safe it is for the driver. When submitting the - * waypoints, it is recommended to stay within, or close to, the distance that can be traveled within 120-mins or + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * Weather along a route API returns hyper local (one kilometer or less), + * up-to-the-minute weather nowcasts, + * weather hazard assessments, and notifications along a route described as a + * sequence of waypoints. This includes a + * list of weather hazards affecting the waypoint or route, and the aggregated + * hazard index for each waypoint might + * be used to paint each portion of a route according to how safe it is for the + * driver. When submitting the + * waypoints, it is recommended to stay within, or close to, the distance that + * can be traveled within 120-mins or * shortly after. Data is updated every five minutes. * - *

        The service supplements Azure Maps [Route Service](https://docs.microsoft.com/rest/api/maps/route) that allows - * you to first request a route between an origin and a destination and use that as an input for Weather Along Route + *

        + * The service supplements Azure Maps [Route + * Service](https://docs.microsoft.com/rest/api/maps/route) that allows + * you to first request a route between an origin and a destination and use that + * as an input for Weather Along Route * endpoint. * - *

        In addition, the service supports scenarios to generate weather notifications for waypoints that experience an - * increase in intensity of a weather hazard. For example, if the vehicle is expected to begin experiencing heavy - * rain as it reaches a waypoint, a weather notification for heavy rain will be generated for that waypoint allowing - * the end product to display a heavy rain notification before the driver reaches that waypoint. The trigger for - * when to display the notification for a waypoint could be based, for example, on a - * [geofence](https://docs.microsoft.com/azure/azure-maps/tutorial-iot-hub-maps), or selectable distance to the + *

        + * In addition, the service supports scenarios to generate weather notifications + * for waypoints that experience an + * increase in intensity of a weather hazard. For example, if the vehicle is + * expected to begin experiencing heavy + * rain as it reaches a waypoint, a weather notification for heavy rain will be + * generated for that waypoint allowing + * the end product to display a heavy rain notification before the driver + * reaches that waypoint. The trigger for + * when to display the notification for a waypoint could be based, for example, + * on a + * [geofence](https://docs.microsoft.com/azure/azure-maps/tutorial-iot-hub-maps), + * or selectable distance to the * waypoint. * - *

        The API covers all regions of the planet except latitudes above Greenland and Antarctica. + *

        + * The API covers all regions of the planet except latitudes above Greenland and + * Antarctica. * * @param context The context to associate with this operation. - * @param waypoints Coordinates through which the route is calculated, separated by colon (:) and entered in - * chronological order. A minimum of two waypoints is required. A single API call may contain up to 60 - * waypoints. A waypoint indicates location, ETA, and optional heading: latitude,longitude,ETA,heading, where * - * `Latitude` - Latitude coordinate in decimal degrees. * `Longitude` - Longitude coordinate in decimal degrees. - * * `ETA (estimated time of arrival)` - The number of minutes from the present time that it will take for the - * vehicle to reach the waypoint. Allowed range is from 0.0 to 120.0 minutes. * `Heading` - An optional value - * indicating the vehicle heading as it passes the waypoint. Expressed in clockwise degrees relative to true - * north. This is issued to calculate sun glare as a driving hazard. Allowed range is from 0.0 to 360.0 degrees. - * If not provided, a heading will automatically be derived based on the position of neighboring waypoints. - *

        It is recommended to stay within, or close to, the distance that can be traveled within 120-mins or - * shortly after. This way a more accurate assessment can be provided for the trip and prevent isolated events - * not being captured between waypoints. Information can and should be updated along the route (especially for - * trips greater than 2 hours) to continuously pull new waypoints moving forward, but also to ensure that - * forecast information for content such as precipitation type and intensity is accurate as storms develop and + * @param waypoints Coordinates through which the route is calculated, separated + * by colon (:) and entered in + * chronological order. A minimum of two waypoints is required. + * A single API call may contain up to 60 + * waypoints. A waypoint indicates location, ETA, and optional + * heading: latitude,longitude,ETA,heading, where * + * `Latitude` - Latitude coordinate in decimal degrees. * + * `Longitude` - Longitude coordinate in decimal degrees. + * * `ETA (estimated time of arrival)` - The number of minutes + * from the present time that it will take for the + * vehicle to reach the waypoint. Allowed range is from 0.0 to + * 120.0 minutes. * `Heading` - An optional value + * indicating the vehicle heading as it passes the waypoint. + * Expressed in clockwise degrees relative to true + * north. This is issued to calculate sun glare as a driving + * hazard. Allowed range is from 0.0 to 360.0 degrees. + * If not provided, a heading will automatically be derived + * based on the position of neighboring waypoints. + *

        + * It is recommended to stay within, or close to, the distance + * that can be traveled within 120-mins or + * shortly after. This way a more accurate assessment can be + * provided for the trip and prevent isolated events + * not being captured between waypoints. Information can and + * should be updated along the route (especially for + * trips greater than 2 hours) to continuously pull new + * waypoints moving forward, but also to ensure that + * forecast information for content such as precipitation type + * and intensity is accurate as storms develop and * dissipate over time. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @return this object is returned from a successful Weather Along Route. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated Mono> getWeatherAlongRouteWithResponse(List waypoints, String language, @@ -953,31 +1373,52 @@ Mono> getWeatherAlongRouteWithResponse(List * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        Severe weather phenomenon can significantly impact our everyday life and business operations. For example, - * severe weather conditions such as tropical storms, high winds or flooding can close roads and force logistics - * companies to reroute their fleet causing delays in reaching destinations and breaking the cold chain of - * refrigerated food products. Azure Maps Severe Weather Alerts API returns the severe weather alerts that are - * available worldwide from both official Government Meteorological Agencies and leading global to - * regional weather alert providers. The service can return details such as alert type, category, level and detailed - * description about the active severe alerts for the requested location, like hurricanes, thunderstorms, lightning, + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * Severe weather phenomenon can significantly impact our everyday life and + * business operations. For example, + * severe weather conditions such as tropical storms, high winds or flooding can + * close roads and force logistics + * companies to reroute their fleet causing delays in reaching destinations and + * breaking the cold chain of + * refrigerated food products. Azure Maps Severe Weather Alerts API returns the + * severe weather alerts that are + * available worldwide from both official Government Meteorological Agencies and + * leading global to + * regional weather alert providers. The service can return details such as + * alert type, category, level and detailed + * description about the active severe alerts for the requested location, like + * hurricanes, thunderstorms, lightning, * heat waves or forest fires. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated + * string composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. + * Should be one of supported IETF language + * tags, case-insensitive. When data in specified language + * is not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. - * @param includeDetails Return full details for the severe weather alerts. Available values are * `true` - Returns full - * details. By default, all details are returned. * `false` - Returns a truncated version of the alerts data, - * which excludes the area-specific full description of alert details (`alertDetails`). - * @return this object is returned from a successful Get Severe Weather Alerts call. + * @param includeDetails Return full details for the severe weather alerts. + * Available values are * `True` - Returns full + * details. By default, all details are returned. * + * `False` - Returns a truncated version of the alerts + * data, + * which excludes the area-specific full description of + * alert details (`alertDetails`). + * @return this object is returned from a successful Get Severe Weather Alerts + * call. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -995,31 +1436,52 @@ public Mono getSevereWeatherAlerts(GeoPosition positi * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        Severe weather phenomenon can significantly impact our everyday life and business operations. For example, - * severe weather conditions such as tropical storms, high winds or flooding can close roads and force logistics - * companies to reroute their fleet causing delays in reaching destinations and breaking the cold chain of - * refrigerated food products. Azure Maps Severe Weather Alerts API returns the severe weather alerts that are - * available worldwide from both official Government Meteorological Agencies and leading global to - * regional weather alert providers. The service can return details such as alert type, category, level and detailed - * description about the active severe alerts for the requested location, like hurricanes, thunderstorms, lightning, + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * Severe weather phenomenon can significantly impact our everyday life and + * business operations. For example, + * severe weather conditions such as tropical storms, high winds or flooding can + * close roads and force logistics + * companies to reroute their fleet causing delays in reaching destinations and + * breaking the cold chain of + * refrigerated food products. Azure Maps Severe Weather Alerts API returns the + * severe weather alerts that are + * available worldwide from both official Government Meteorological Agencies and + * leading global to + * regional weather alert providers. The service can return details such as + * alert type, category, level and detailed + * description about the active severe alerts for the requested location, like + * hurricanes, thunderstorms, lightning, * heat waves or forest fires. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated + * string composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. + * Should be one of supported IETF language + * tags, case-insensitive. When data in specified language + * is not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. - * @param includeDetails Return full details for the severe weather alerts. Available values are * `true` - Returns full - * details. By default, all details are returned. * `false` - Returns a truncated version of the alerts data, - * which excludes the area-specific full description of alert details (`alertDetails`). - * @return this object is returned from a successful Get Severe Weather Alerts call. + * @param includeDetails Return full details for the severe weather alerts. + * Available values are * `true` - Returns full + * details. By default, all details are returned. * + * `false` - Returns a truncated version of the alerts + * data, + * which excludes the area-specific full description of + * alert details (`alertDetails`). + * @return this object is returned from a successful Get Severe Weather Alerts + * call. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -1037,32 +1499,53 @@ public Mono> getSevereWeatherAlertsWithRespo * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        Severe weather phenomenon can significantly impact our everyday life and business operations. For example, - * severe weather conditions such as tropical storms, high winds or flooding can close roads and force logistics - * companies to reroute their fleet causing delays in reaching destinations and breaking the cold chain of - * refrigerated food products. Azure Maps Severe Weather Alerts API returns the severe weather alerts that are - * available worldwide from both official Government Meteorological Agencies and leading global to - * regional weather alert providers. The service can return details such as alert type, category, level and detailed - * description about the active severe alerts for the requested location, like hurricanes, thunderstorms, lightning, + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * Severe weather phenomenon can significantly impact our everyday life and + * business operations. For example, + * severe weather conditions such as tropical storms, high winds or flooding can + * close roads and force logistics + * companies to reroute their fleet causing delays in reaching destinations and + * breaking the cold chain of + * refrigerated food products. Azure Maps Severe Weather Alerts API returns the + * severe weather alerts that are + * available worldwide from both official Government Meteorological Agencies and + * leading global to + * regional weather alert providers. The service can return details such as + * alert type, category, level and detailed + * description about the active severe alerts for the requested location, like + * hurricanes, thunderstorms, lightning, * heat waves or forest fires. * * @param context The context to associate with this operation. - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated + * string composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. + * Should be one of supported IETF language + * tags, case-insensitive. When data in specified language + * is not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. - * @param includeDetails Return full details for the severe weather alerts. Available values are * `true` - Returns full - * details. By default, all details are returned. * `false` - Returns a truncated version of the alerts data, - * which excludes the area-specific full description of alert details (`alertDetails`). - * @return this object is returned from a successful Get Severe Weather Alerts call. + * @param includeDetails Return full details for the severe weather alerts. + * Available values are * `true` - Returns full + * details. By default, all details are returned. * + * `false` - Returns a truncated version of the alerts + * data, + * which excludes the area-specific full description of + * alert details (`alertDetails`). + * @return this object is returned from a successful Get Severe Weather Alerts + * call. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated Mono> getSevereWeatherAlertsWithResponse(GeoPosition position, String language, @@ -1083,39 +1566,66 @@ Mono> getSevereWeatherAlertsWithResponse(Geo * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        There may be times when you want to know if the weather conditions are optimal for a specific activity, for - * example, for outdoor construction, indoor activities, running or farming including soil moisture information. - * Azure Maps Indices API returns index values that will guide end users to plan future activities. For example, a - * health mobile application can notify users that today is good weather for running or for other outdoors - * activities like for playing golf, and retail stores can optimize their digital marketing campaigns based on - * predicted index values. The service returns in daily indices values for current and next 5, 10 and 15 days + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * There may be times when you want to know if the weather conditions are + * optimal for a specific activity, for + * example, for outdoor construction, indoor activities, running or farming + * including soil moisture information. + * Azure Maps Indices API returns index values that will guide end users to plan + * future activities. For example, a + * health mobile application can notify users that today is good weather for + * running or for other outdoors + * activities like for playing golf, and retail stores can optimize their + * digital marketing campaigns based on + * predicted index values. The service returns in daily indices values for + * current and next 5, 10 and 15 days * starting from current day. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated + * string composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. + * Should be one of supported IETF language + * tags, case insensitive. When data in specified language + * is not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. - * @param duration Specifies for how many days the daily indices are returned. By default, the indices data for the - * current day will be returned. When requesting future indices data, the current day is included in the - * response as day 1. Available values are * `1` - Return daily index data for the current day. Default value. * - * `5` - Return 5 days of daily index data starting from the current day. * `10` - Return 10 days of daily index - * data starting from the current day. * `15` - Return 15 days of daily index data starting from the current + * @param duration Specifies for how many days the daily indices are + * returned. By default, the indices data for the + * current day will be returned. When requesting future + * indices data, the current day is included in the + * response as day 1. Available values are * `1` - Return + * daily index data for the current day. Default value. * + * `5` - Return 5 days of daily index data starting from the + * current day. * `10` - Return 10 days of daily index + * data starting from the current day. * `15` - Return 15 + * days of daily index data starting from the current * day. - * @param indexId Numeric index identifier that can be used for restricting returned results to the corresponding - * index type. Cannot be paired with `indexGroupId`. Please refer to [Weather Service - * Concepts](https://aka.ms/AzureMapsWeatherConcepts) for details and to see the supported indices. - * @param indexGroupId Numeric index group identifier that can be used for restricting returned results to the - * corresponding subset of indices (index group). Cannot be paired with `indexId`. Please refer to [Weather - * Service Concepts](https://aka.ms/AzureMapsWeatherConcepts) for details and to see the supported index groups. + * @param indexId Numeric index identifier that can be used for restricting + * returned results to the corresponding + * index type. Cannot be paired with `indexGroupId`. Please + * refer to [Weather Service + * Concepts](https://aka.ms/AzureMapsWeatherConcepts) for + * details and to see the supported indices. + * @param indexGroupId Numeric index group identifier that can be used for + * restricting returned results to the + * corresponding subset of indices (index group). Cannot be + * paired with `indexId`. Please refer to [Weather + * Service + * Concepts](https://aka.ms/AzureMapsWeatherConcepts) for + * details and to see the supported index groups. * @return this object is returned from a successful Get Daily Indices call. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -1134,39 +1644,66 @@ public Mono getDailyIndices(GeoPosition position, String lan * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        There may be times when you want to know if the weather conditions are optimal for a specific activity, for - * example, for outdoor construction, indoor activities, running or farming including soil moisture information. - * Azure Maps Indices API returns index values that will guide end users to plan future activities. For example, a - * health mobile application can notify users that today is good weather for running or for other outdoors - * activities like for playing golf, and retail stores can optimize their digital marketing campaigns based on - * predicted index values. The service returns in daily indices values for current and next 5, 10 and 15 days + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * There may be times when you want to know if the weather conditions are + * optimal for a specific activity, for + * example, for outdoor construction, indoor activities, running or farming + * including soil moisture information. + * Azure Maps Indices API returns index values that will guide end users to plan + * future activities. For example, a + * health mobile application can notify users that today is good weather for + * running or for other outdoors + * activities like for playing golf, and retail stores can optimize their + * digital marketing campaigns based on + * predicted index values. The service returns in daily indices values for + * current and next 5, 10 and 15 days * starting from current day. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated + * string composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. + * Should be one of supported IETF language + * tags, case-insensitive. When data in specified language + * is not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. - * @param duration Specifies for how many days the daily indices are returned. By default, the indices data for the - * current day will be returned. When requesting future indices data, the current day is included in the - * response as day 1. Available values are * `1` - Return daily index data for the current day. Default value. * - * `5` - Return 5 days of daily index data starting from the current day. * `10` - Return 10 days of daily index - * data starting from the current day. * `15` - Return 15 days of daily index data starting from the current + * @param duration Specifies for how many days the daily indices are + * returned. By default, the indices data for the + * current day will be returned. When requesting future + * indices data, the current day is included in the + * response as day 1. Available values are * `1` - Return + * daily index data for the current day. Default value. * + * `5` - Return 5 days of daily index data starting from the + * current day. * `10` - Return 10 days of daily index + * data starting from the current day. * `15` - Return 15 + * days of daily index data starting from the current * day. - * @param indexId Numeric index identifier that can be used for restricting returned results to the corresponding - * index type. Cannot be paired with `indexGroupId`. Please refer to [Weather Service - * Concepts](https://aka.ms/AzureMapsWeatherConcepts) for details and to see the supported indices. - * @param indexGroupId Numeric index group identifier that can be used for restricting returned results to the - * corresponding subset of indices (index group). Cannot be paired with `indexId`. Please refer to [Weather - * Service Concepts](https://aka.ms/AzureMapsWeatherConcepts) for details and to see the supported index groups. + * @param indexId Numeric index identifier that can be used for restricting + * returned results to the corresponding + * index type. Cannot be paired with `indexGroupId`. Please + * refer to [Weather Service + * Concepts](https://aka.ms/AzureMapsWeatherConcepts) for + * details and to see the supported indices. + * @param indexGroupId Numeric index group identifier that can be used for + * restricting returned results to the + * corresponding subset of indices (index group). Cannot be + * paired with `indexId`. Please refer to [Weather + * Service + * Concepts](https://aka.ms/AzureMapsWeatherConcepts) for + * details and to see the supported index groups. * @return this object is returned from a successful Get Daily Indices call. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -1185,40 +1722,67 @@ public Mono> getDailyIndicesWithResponse(GeoPositio * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        There may be times when you want to know if the weather conditions are optimal for a specific activity, for - * example, for outdoor construction, indoor activities, running or farming including soil moisture information. - * Azure Maps Indices API returns index values that will guide end users to plan future activities. For example, a - * health mobile application can notify users that today is good weather for running or for other outdoors - * activities like for playing golf, and retail stores can optimize their digital marketing campaigns based on - * predicted index values. The service returns in daily indices values for current and next 5, 10 and 15 days + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * There may be times when you want to know if the weather conditions are + * optimal for a specific activity, for + * example, for outdoor construction, indoor activities, running or farming + * including soil moisture information. + * Azure Maps Indices API returns index values that will guide end users to plan + * future activities. For example, a + * health mobile application can notify users that today is good weather for + * running or for other outdoors + * activities like for playing golf, and retail stores can optimize their + * digital marketing campaigns based on + * predicted index values. The service returns in daily indices values for + * current and next 5, 10 and 15 days * starting from current day. * * @param context The context to associate with this operation. - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated + * string composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. + * Should be one of supported IETF language + * tags, case-insensitive. When data in specified language + * is not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. - * @param duration Specifies for how many days the daily indices are returned. By default, the indices data for the - * current day will be returned. When requesting future indices data, the current day is included in the - * response as day 1. Available values are * `1` - Return daily index data for the current day. Default value. * - * `5` - Return 5 days of daily index data starting from the current day. * `10` - Return 10 days of daily index - * data starting from the current day. * `15` - Return 15 days of daily index data starting from the current + * @param duration Specifies for how many days the daily indices are + * returned. By default, the indices data for the + * current day will be returned. When requesting future + * indices data, the current day is included in the + * response as day 1. Available values are * `1` - Return + * daily index data for the current day. Default value. * + * `5` - Return 5 days of daily index data starting from the + * current day. * `10` - Return 10 days of daily index + * data starting from the current day. * `15` - Return 15 + * days of daily index data starting from the current * day. - * @param indexId Numeric index identifier that can be used for restricting returned results to the corresponding - * index type. Cannot be paired with `indexGroupId`. Please refer to [Weather Service - * Concepts](https://aka.ms/AzureMapsWeatherConcepts) for details and to see the supported indices. - * @param indexGroupId Numeric index group identifier that can be used for restricting returned results to the - * corresponding subset of indices (index group). Cannot be paired with `indexId`. Please refer to [Weather - * Service Concepts](https://aka.ms/AzureMapsWeatherConcepts) for details and to see the supported index groups. + * @param indexId Numeric index identifier that can be used for restricting + * returned results to the corresponding + * index type. Cannot be paired with `indexGroupId`. Please + * refer to [Weather Service + * Concepts](https://aka.ms/AzureMapsWeatherConcepts) for + * details and to see the supported indices. + * @param indexGroupId Numeric index group identifier that can be used for + * restricting returned results to the + * corresponding subset of indices (index group). Cannot be + * paired with `indexId`. Please refer to [Weather + * Service + * Concepts](https://aka.ms/AzureMapsWeatherConcepts) for + * details and to see the supported index groups. * @return this object is returned from a successful Get Daily Indices call. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated Mono> getDailyIndicesWithResponse(GeoPosition position, String language, @@ -1239,15 +1803,19 @@ Mono> getDailyIndicesWithResponse(GeoPosition posit * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get all government-issued active tropical storms. Information about the tropical storms includes, government + *

        + * Get all government-issued active tropical storms. Information about the + * tropical storms includes, government * ID, basin ID, year of origin, name and if it is subtropical. * * @return all government-issued active storms. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -1264,15 +1832,19 @@ public Mono getTropicalStormActive() { * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get all government-issued active tropical storms. Information about the tropical storms includes, government + *

        + * Get all government-issued active tropical storms. Information about the + * tropical storms includes, government * ID, basin ID, year of origin, name and if it is subtropical. * * @return all government-issued active storms. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -1289,16 +1861,20 @@ public Mono> getTropicalStormActiveWithResponse() { * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get all government-issued active tropical storms. Information about the tropical storms includes, government + *

        + * Get all government-issued active tropical storms. Information about the + * tropical storms includes, government * ID, basin ID, year of origin, name and if it is subtropical. * * @param context The context to associate with this operation. * @return all government-issued active storms. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated Mono> getTropicalStormActiveWithResponse(Context context) { @@ -1312,10 +1888,14 @@ Mono> getTropicalStormActiveWithResponse(Context con * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Search government-issued tropical storms by year, basin ID, and government ID. Information about the tropical - * storms includes, government ID, basin ID, status, year, name and if it is subtropical. + *

        + * Search government-issued tropical storms by year, basin ID, and government + * ID. Information about the tropical + * storms includes, government ID, basin ID, status, year, name and if it is + * subtropical. * * @param year Year of the cyclone(s). * @param basinId Basin identifier. @@ -1323,7 +1903,8 @@ Mono> getTropicalStormActiveWithResponse(Context con * @return search government-issued storms. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -1337,10 +1918,14 @@ public Mono searchTropicalStorm(Integer year, BasinId basinId * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Search government-issued tropical storms by year, basin ID, and government ID. Information about the tropical - * storms includes, government ID, basin ID, status, year, name and if it is subtropical. + *

        + * Search government-issued tropical storms by year, basin ID, and government + * ID. Information about the tropical + * storms includes, government ID, basin ID, status, year, name and if it is + * subtropical. * * @param year Year of the cyclone(s). * @param basinId Basin identifier. @@ -1348,7 +1933,8 @@ public Mono searchTropicalStorm(Integer year, BasinId basinId * @return search government-issued storms. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -1363,10 +1949,14 @@ public Mono> searchTropicalStormWithResponse(Integer * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Search government-issued tropical storms by year, basin ID, and government ID. Information about the tropical - * storms includes, government ID, basin ID, status, year, name and if it is subtropical. + *

        + * Search government-issued tropical storms by year, basin ID, and government + * ID. Information about the tropical + * storms includes, government ID, basin ID, status, year, name and if it is + * subtropical. * * @param context The context to associate with this operation. * @param year Year of the cyclone(s). @@ -1375,7 +1965,8 @@ public Mono> searchTropicalStormWithResponse(Integer * @return search government-issued storms. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated Mono> searchTropicalStormWithResponse(Integer year, BasinId basinId, @@ -1394,23 +1985,28 @@ Mono> searchTropicalStormWithResponse(Integer year, * if (activeStormResult.getActiveStorms().size() > 0) { * ActiveStorm storm = activeStormResult.getActiveStorms().get(0); * TropicalStormForecastOptions forecastOptions = new TropicalStormForecastOptions(storm.getYear(), - * storm.getBasinId(), storm.getGovId()) - * .setIncludeWindowGeometry(true); + * storm.getBasinId(), storm.getGovernmentId()) + * .setIncludeWindowGeometry(true); * asyncClient.getTropicalStormForecast(forecastOptions); * } * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get individual government-issued tropical storm forecasts. Information about the forecasted tropical storms - * includes, location, status, date the forecast was created, window, wind speed and wind radii. + *

        + * Get individual government-issued tropical storm forecasts. Information about + * the forecasted tropical storms + * includes, location, status, date the forecast was created, window, wind speed + * and wind radii. * * @param options TropicalStormForecastOptions * @return the list of Government-issued forecasts. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -1427,23 +2023,28 @@ public Mono getTropicalStormForecast(TropicalStormForecastO * if (activeStormResult.getActiveStorms().size() > 0) { * ActiveStorm storm = activeStormResult.getActiveStorms().get(0); * TropicalStormForecastOptions forecastOptions = new TropicalStormForecastOptions(storm.getYear(), - * storm.getBasinId(), storm.getGovId()) - * .setIncludeWindowGeometry(true); + * storm.getBasinId(), storm.getGovernmentId()) + * .setIncludeWindowGeometry(true); * asyncClient.getTropicalStormForecast(forecastOptions); * } * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get individual government-issued tropical storm forecasts. Information about the forecasted tropical storms - * includes, location, status, date the forecast was created, window, wind speed and wind radii. + *

        + * Get individual government-issued tropical storm forecasts. Information about + * the forecasted tropical storms + * includes, location, status, date the forecast was created, window, wind speed + * and wind radii. * * @param options TropicalStormForecastOptions * @return the list of Government-issued forecasts. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -1461,23 +2062,28 @@ public Mono getTropicalStormForecast(TropicalStormForecastO * if (activeStormResult.getActiveStorms().size() > 0) { * ActiveStorm storm = activeStormResult.getActiveStorms().get(0); * TropicalStormForecastOptions forecastOptions = new TropicalStormForecastOptions(storm.getYear(), - * storm.getBasinId(), storm.getGovId()) - * .setIncludeWindowGeometry(true); + * storm.getBasinId(), storm.getGovernmentId()) + * .setIncludeWindowGeometry(true); * asyncClient.getTropicalStormForecast(forecastOptions); * } * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get individual government-issued tropical storm forecasts. Information about the forecasted tropical storms - * includes, location, status, date the forecast was created, window, wind speed and wind radii. + *

        + * Get individual government-issued tropical storm forecasts. Information about + * the forecasted tropical storms + * includes, location, status, date the forecast was created, window, wind speed + * and wind radii. * * @param options TropicalStormForecastOptions * @return the list of Government-issued forecasts. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated Mono> getTropicalStormForecastWithResponse(TropicalStormForecastOptions options, @@ -1498,22 +2104,26 @@ Mono> getTropicalStormForecastWithResponse(Tropica * if (activeStormResult.getActiveStorms().size() > 0) { * ActiveStorm storm = activeStormResult.getActiveStorms().get(0); * TropicalStormLocationOptions locationOptions = new TropicalStormLocationOptions(storm.getYear(), - * storm.getBasinId(), storm.getGovId()); + * storm.getBasinId(), storm.getGovernmentId()); * asyncClient.getTropicalStormLocations(locationOptions); * } * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get location of individual government-issued tropical storms. Information about the tropical storms includes, + *

        + * Get location of individual government-issued tropical storms. Information + * about the tropical storms includes, * location coordinates, geometry, basin ID, date, wind details and wind radii. * * @param options TropicalStormLocationOptions * @return locations for an individual government-issued storm. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -1530,22 +2140,26 @@ public Mono getTropicalStormLocations(TropicalStormLocatio * if (activeStormResult.getActiveStorms().size() > 0) { * ActiveStorm storm = activeStormResult.getActiveStorms().get(0); * TropicalStormLocationOptions locationOptions = new TropicalStormLocationOptions(storm.getYear(), - * storm.getBasinId(), storm.getGovId()); + * storm.getBasinId(), storm.getGovernmentId()); * asyncClient.getTropicalStormLocations(locationOptions); * } * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get location of individual government-issued tropical storms. Information about the tropical storms includes, + *

        + * Get location of individual government-issued tropical storms. Information + * about the tropical storms includes, * location coordinates, geometry, basin ID, date, wind details and wind radii. * * @param options TropicalStormLocationOptions * @return locations for an individual government-issued storm. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -1563,22 +2177,26 @@ public Mono getTropicalStormLocations(TropicalStormLocatio * if (activeStormResult.getActiveStorms().size() > 0) { * ActiveStorm storm = activeStormResult.getActiveStorms().get(0); * TropicalStormLocationOptions locationOptions = new TropicalStormLocationOptions(storm.getYear(), - * storm.getBasinId(), storm.getGovId()); + * storm.getBasinId(), storm.getGovernmentId()); * asyncClient.getTropicalStormLocations(locationOptions); * } * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get location of individual government-issued tropical storms. Information about the tropical storms includes, + *

        + * Get location of individual government-issued tropical storms. Information + * about the tropical storms includes, * location coordinates, geometry, basin ID, date, wind details and wind radii. * * @param options TropicalStormLocationOptions * @return locations for an individual government-issued storm. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated Mono> getTropicalStormLocationsWithResponse(TropicalStormLocationOptions options, @@ -1596,29 +2214,44 @@ Mono> getTropicalStormLocationsWithResponse(Tropi * *

              * asyncClient.getCurrentAirQuality(
        -     *     new GeoPosition(-122.138874, 47.632346), "es", false);
        +     *         new GeoPosition(-122.138874, 47.632346), "es", false);
              * 
        * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get detailed information about the concentration of pollutants and overall status for current air quality. - * Information includes, pollution levels, air quality index values, the dominant pollutant, and a brief statement + *

        + * Get detailed information about the concentration of pollutants and overall + * status for current air quality. + * Information includes, pollution levels, air quality index values, the + * dominant pollutant, and a brief statement * summarizing risk level and suggested precautions. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma + * separated string composed by longitude + * followed by * latitude e.g. "-122.125679,47.641268". - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be + * returned. Should be one of supported IETF + * language + * tags, case-insensitive. When data in specified + * language is not available for a specific + * field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. - * @param includePollutantDetails Boolean value that returns detailed information about each pollutant. By default + * @param includePollutantDetails Boolean value that returns detailed + * information about each pollutant. By default * is True. * @return this object is returned from a successful Get Air Quality call. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -1633,29 +2266,44 @@ public Mono getCurrentAirQuality(GeoPosition position, String * *

              * asyncClient.getCurrentAirQuality(
        -     *     new GeoPosition(-122.138874, 47.632346), "es", false);
        +     *         new GeoPosition(-122.138874, 47.632346), "es", false);
              * 
        * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get detailed information about the concentration of pollutants and overall status for current air quality. - * Information includes, pollution levels, air quality index values, the dominant pollutant, and a brief statement + *

        + * Get detailed information about the concentration of pollutants and overall + * status for current air quality. + * Information includes, pollution levels, air quality index values, the + * dominant pollutant, and a brief statement * summarizing risk level and suggested precautions. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma + * separated string composed by longitude + * followed by * latitude e.g. "-122.125679,47.641268". - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be + * returned. Should be one of supported IETF + * language + * tags, case-insensitive. When data in specified + * language is not available for a specific + * field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. - * @param includePollutantDetails Boolean value that returns detailed information about each pollutant. By default + * @param includePollutantDetails Boolean value that returns detailed + * information about each pollutant. By default * is True. * @return this object is returned from a successful Get Air Quality call. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -1671,30 +2319,45 @@ public Mono> getCurrentAirQualityWithResponse(GeoPosi * *

              * asyncClient.getCurrentAirQuality(
        -     *     new GeoPosition(-122.138874, 47.632346), "es", false);
        +     *         new GeoPosition(-122.138874, 47.632346), "es", false);
              * 
        * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get detailed information about the concentration of pollutants and overall status for current air quality. - * Information includes, pollution levels, air quality index values, the dominant pollutant, and a brief statement + *

        + * Get detailed information about the concentration of pollutants and overall + * status for current air quality. + * Information includes, pollution levels, air quality index values, the + * dominant pollutant, and a brief statement * summarizing risk level and suggested precautions. * * @param context The context to associate with this operation. - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma + * separated string composed by longitude + * followed by * latitude e.g. "-122.125679,47.641268". - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be + * returned. Should be one of supported IETF + * language + * tags, case-insensitive. When data in specified + * language is not available for a specific + * field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. - * @param includePollutantDetails Boolean value that returns detailed information about each pollutant. By default + * @param includePollutantDetails Boolean value that returns detailed + * information about each pollutant. By default * is True. * @return this object is returned from a successful Get Air Quality call. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated Mono> getCurrentAirQualityWithResponse(GeoPosition position, String language, @@ -1709,113 +2372,164 @@ Mono> getCurrentAirQualityWithResponse(GeoPosition po /** * **Get Air Quality Daily Forecasts** * - * + * + * *

        -     * asyncClient.getAirQualityDailyForecasts(
        -     *     new GeoPosition(-122.138874, 47.632346), "en", DailyDuration.TWO_DAYS);
        +     * asyncClient.getDailyAirQualityForecast(
        +     * new GeoPosition(-122.138874, 47.632346), "en", DailyDuration.TWO_DAYS);
              * 
        + * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get detailed information about the concentration of pollutants and overall status of forecasted daily air - * quality. The service can provide forecasted daily air quality information for the upcoming 1 to 7 days. - * Information includes, pollution levels, air quality index values, the dominant pollutant, and a brief statement + *

        + * Get detailed information about the concentration of pollutants and overall + * status of forecasted daily air + * quality. The service can provide forecasted daily air quality information for + * the upcoming 1 to 7 days. + * Information includes, pollution levels, air quality index values, the + * dominant pollutant, and a brief statement * summarizing risk level and suggested precautions. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. - * @param duration Specifies for how many days from now we would like to know about the air quality. Available + * @param duration Specifies for how many days from now we would like to know + * about the air quality. Available * values are 1, 2, 3, 4, 5, 6, and 7. Default value is 1. - * @return this object is returned from a successful Get Daily Air Quality Forecast call. + * @return this object is returned from a successful Get Daily Air Quality + * Forecast call. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getAirQualityDailyForecasts(GeoPosition position, String language, + public Mono getDailyAirQualityForecast(GeoPosition position, String language, DailyDuration duration) { - return getAirQualityDailyForecastsWithResponse(position, language, duration).flatMap(FluxUtil::toMono); + return getDailyAirQualityForecastWithResponse(position, language, duration).flatMap(FluxUtil::toMono); } /** * **Get Air Quality Daily Forecasts** * - * + * + * *

        -     * asyncClient.getAirQualityDailyForecasts(
        -     *     new GeoPosition(-122.138874, 47.632346), "en", DailyDuration.TWO_DAYS);
        +     * asyncClient.getDailyAirQualityForecast(
        +     * new GeoPosition(-122.138874, 47.632346), "en", DailyDuration.TWO_DAYS);
              * 
        + * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get detailed information about the concentration of pollutants and overall status of forecasted daily air - * quality. The service can provide forecasted daily air quality information for the upcoming 1 to 7 days. - * Information includes, pollution levels, air quality index values, the dominant pollutant, and a brief statement + *

        + * Get detailed information about the concentration of pollutants and overall + * status of forecasted daily air + * quality. The service can provide forecasted daily air quality information for + * the upcoming 1 to 7 days. + * Information includes, pollution levels, air quality index values, the + * dominant pollutant, and a brief statement * summarizing risk level and suggested precautions. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. - * @param duration Specifies for how many days from now we would like to know about the air quality. Available + * @param duration Specifies for how many days from now we would like to know + * about the air quality. Available * values are 1, 2, 3, 4, 5, 6, and 7. Default value is 1. - * @return this object is returned from a successful Get Daily Air Quality Forecast call. + * @return this object is returned from a successful Get Daily Air Quality + * Forecast call. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getAirQualityDailyForecastsWithResponse(GeoPosition position, + public Mono> getDailyAirQualityForecastWithResponse(GeoPosition position, String language, DailyDuration duration) { - return withContext(context -> getAirQualityDailyForecastsWithResponse(position, language, duration, context)); + return withContext(context -> getDailyAirQualityForecastWithResponse(position, language, duration, context)); } /** * **Get Air Quality Daily Forecasts** * - * + * + * *

        -     * asyncClient.getAirQualityDailyForecasts(
        -     *     new GeoPosition(-122.138874, 47.632346), "en", DailyDuration.TWO_DAYS);
        +     * asyncClient.getDailyAirQualityForecast(
        +     * new GeoPosition(-122.138874, 47.632346), "en", DailyDuration.TWO_DAYS);
              * 
        + * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get detailed information about the concentration of pollutants and overall status of forecasted daily air - * quality. The service can provide forecasted daily air quality information for the upcoming 1 to 7 days. - * Information includes, pollution levels, air quality index values, the dominant pollutant, and a brief statement + *

        + * Get detailed information about the concentration of pollutants and overall + * status of forecasted daily air + * quality. The service can provide forecasted daily air quality information for + * the upcoming 1 to 7 days. + * Information includes, pollution levels, air quality index values, the + * dominant pollutant, and a brief statement * summarizing risk level and suggested precautions. * * @param context The context to associate with this operation. - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. - * @param duration Specifies for how many days from now we would like to know about the air quality. Available + * @param duration Specifies for how many days from now we would like to know + * about the air quality. Available * values are 1, 2, 3, 4, 5, 6, and 7. Default value is 1. - * @return this object is returned from a successful Get Daily Air Quality Forecast call. + * @return this object is returned from a successful Get Daily Air Quality + * Forecast call. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated - Mono> getAirQualityDailyForecastsWithResponse(GeoPosition position, + Mono> getDailyAirQualityForecastWithResponse(GeoPosition position, String language, DailyDuration duration, Context context) { List coordinates = Arrays.asList(position.getLatitude(), position.getLongitude()); return this.serviceClient @@ -1826,121 +2540,187 @@ Mono> getAirQualityDailyForecastsWithRes /** * **Get Air Quality Hourly Forecasts** * - * + * + * *

        -     * asyncClient.getAirQualityHourlyForecasts(
        -     *     new GeoPosition(-122.138874, 47.632346), "fr", HourlyDuration.ONE_HOUR, false);
        +     * asyncClient.getHourlyAirQualityForecast(
        +     * new GeoPosition(-122.138874, 47.632346), "fr", HourlyDuration.ONE_HOUR, false);
              * 
        - * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        Get detailed information about the concentration of pollutants and overall status for forecasted upcoming - * hourly air quality. The service can provide forecasted hourly air quality information for the upcoming time spans - * of 1, 12, 24, 48, 72, and 96 hours. Information includes, pollution levels, air quality index values, the - * dominant pollutant, and a brief statement summarizing risk level and suggested precautions. + * * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * Get detailed information about the concentration of pollutants and overall + * status for forecasted upcoming + * hourly air quality. The service can provide forecasted hourly air quality + * information for the upcoming time spans + * of 1, 12, 24, 48, 72, and 96 hours. Information includes, pollution levels, + * air quality index values, the + * dominant pollutant, and a brief statement summarizing risk level and + * suggested precautions. + * + * @param position The applicable query specified as a comma + * separated string composed by longitude + * followed by * latitude e.g. "-122.125679,47.641268". - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be + * returned. Should be one of supported IETF + * language + * tags, case-insensitive. When data in specified + * language is not available for a specific + * field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. - * @param duration Specifies for how many hours from now we would like to know about the air quality. Available - * values are 1, 12, 24, 48, 72, 96. Default value is 1 hour. - * @param includePollutantDetails Boolean value that returns detailed information about each pollutant. By default + * @param duration Specifies for how many hours from now we would + * like to know about the air quality. Available + * values are 1, 12, 24, 48, 72, 96. Default + * value is 1 hour. + * @param includePollutantDetails Boolean value that returns detailed + * information about each pollutant. By default * is True. * @return this object is returned from a successful Get Air Quality call. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getAirQualityHourlyForecasts(GeoPosition position, String language, + public Mono getHourlyAirQualityForecast(GeoPosition position, String language, HourlyDuration duration, Boolean includePollutantDetails) { - return getAirQualityHourlyForecastsWithResponse(position, language, duration, includePollutantDetails) + return getHourlyAirQualityForecastWithResponse(position, language, duration, includePollutantDetails) .flatMap(FluxUtil::toMono); } /** * **Get Air Quality Hourly Forecasts** * - * + * + * *

        -     * asyncClient.getAirQualityHourlyForecasts(
        -     *     new GeoPosition(-122.138874, 47.632346), "fr", HourlyDuration.ONE_HOUR, false);
        +     * asyncClient.getHourlyAirQualityForecast(
        +     * new GeoPosition(-122.138874, 47.632346), "fr", HourlyDuration.ONE_HOUR, false);
              * 
        - * - * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get detailed information about the concentration of pollutants and overall status for forecasted upcoming - * hourly air quality. The service can provide forecasted hourly air quality information for the upcoming time spans - * of 1, 12, 24, 48, 72, and 96 hours. Information includes, pollution levels, air quality index values, the - * dominant pollutant, and a brief statement summarizing risk level and suggested precautions. + * * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * Get detailed information about the concentration of pollutants and overall + * status for forecasted upcoming + * hourly air quality. The service can provide forecasted hourly air quality + * information for the upcoming time spans + * of 1, 12, 24, 48, 72, and 96 hours. Information includes, pollution levels, + * air quality index values, the + * dominant pollutant, and a brief statement summarizing risk level and + * suggested precautions. + * + * @param position The applicable query specified as a comma + * separated string composed by longitude + * followed by * latitude e.g. "-122.125679,47.641268". - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be + * returned. Should be one of supported IETF + * language + * tags, case-insensitive. When data in specified + * language is not available for a specific + * field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. - * @param duration Specifies for how many hours from now we would like to know about the air quality. Available - * values are 1, 12, 24, 48, 72, 96. Default value is 1 hour. - * @param includePollutantDetails Boolean value that returns detailed information about each pollutant. By default + * @param duration Specifies for how many hours from now we would + * like to know about the air quality. Available + * values are 1, 12, 24, 48, 72, 96. Default + * value is 1 hour. + * @param includePollutantDetails Boolean value that returns detailed + * information about each pollutant. By default * is True. * @return this object is returned from a successful Get Air Quality call. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getAirQualityHourlyForecastsWithResponse(GeoPosition position, + public Mono> getHourlyAirQualityForecastWithResponse(GeoPosition position, String language, HourlyDuration duration, Boolean includePollutantDetails) { - return withContext(context -> getAirQualityHourlyForecastsWithResponse(position, language, duration, + return withContext(context -> getHourlyAirQualityForecastWithResponse(position, language, duration, includePollutantDetails, context)); } /** * **Get Air Quality Hourly Forecasts** * - * + * + * *

        -     * asyncClient.getAirQualityHourlyForecasts(
        -     *     new GeoPosition(-122.138874, 47.632346), "fr", HourlyDuration.ONE_HOUR, false);
        +     * asyncClient.getHourlyAirQualityForecast(
        +     * new GeoPosition(-122.138874, 47.632346), "fr", HourlyDuration.ONE_HOUR, false);
              * 
        + * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get detailed information about the concentration of pollutants and overall status for forecasted upcoming - * hourly air quality. The service can provide forecasted hourly air quality information for the upcoming time spans - * of 1, 12, 24, 48, 72, and 96 hours. Information includes, pollution levels, air quality index values, the - * dominant pollutant, and a brief statement summarizing risk level and suggested precautions. + *

        + * Get detailed information about the concentration of pollutants and overall + * status for forecasted upcoming + * hourly air quality. The service can provide forecasted hourly air quality + * information for the upcoming time spans + * of 1, 12, 24, 48, 72, and 96 hours. Information includes, pollution levels, + * air quality index values, the + * dominant pollutant, and a brief statement summarizing risk level and + * suggested precautions. * * @param context The context to associate with this operation. - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma + * separated string composed by longitude + * followed by * latitude e.g. "-122.125679,47.641268". - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be + * returned. Should be one of supported IETF + * language + * tags, case-insensitive. When data in specified + * language is not available for a specific + * field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. - * @param duration Specifies for how many hours from now we would like to know about the air quality. Available - * values are 1, 12, 24, 48, 72, 96. Default value is 1 hour. - * @param includePollutantDetails Boolean value that returns detailed information about each pollutant. By default + * @param duration Specifies for how many hours from now we would + * like to know about the air quality. Available + * values are 1, 12, 24, 48, 72, 96. Default + * value is 1 hour. + * @param includePollutantDetails Boolean value that returns detailed + * information about each pollutant. By default * is True. * @return this object is returned from a successful Get Air Quality call. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated - Mono> getAirQualityHourlyForecastsWithResponse(GeoPosition position, String language, + Mono> getHourlyAirQualityForecastWithResponse(GeoPosition position, String language, HourlyDuration duration, Boolean includePollutantDetails, Context context) { List coordinates = Arrays.asList(position.getLatitude(), position.getLongitude()); return this.serviceClient @@ -1960,26 +2740,39 @@ Mono> getAirQualityHourlyForecastsWithResponse(GeoPos * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        Get Daily Historical Actuals service returns climatology data such as past daily actual observed temperatures, - * precipitation, snowfall, snow depth and cooling/heating degree day information, for the day at a given coordinate - * location. The data is requested for a specified date range, up to 31 days in a single API request. Generally, - * historical data may be available as far back as the last 5 to 40+ years, depending on the location. + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * Get Daily Historical Actuals service returns climatology data such as past + * daily actual observed temperatures, + * precipitation, snowfall, snow depth and cooling/heating degree day + * information, for the day at a given coordinate + * location. The data is requested for a specified date range, up to 31 days in + * a single API request. Generally, + * historical data may be available as far back as the last 5 to 40+ years, + * depending on the location. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The date range supported is 1 to 31 - * calendar days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The + * date range supported is 1 to 31 + * calendar days, so be sure to specify a startDate and endDate + * that does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The date range supported is 1 to 31 calendar - * days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The + * date range supported is 1 to 31 calendar + * days, so be sure to specify a startDate and endDate that + * does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -1999,26 +2792,39 @@ public Mono getDailyHistoricalActuals(GeoPosition * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        Get Daily Historical Actuals service returns climatology data such as past daily actual observed temperatures, - * precipitation, snowfall, snow depth and cooling/heating degree day information, for the day at a given coordinate - * location. The data is requested for a specified date range, up to 31 days in a single API request. Generally, - * historical data may be available as far back as the last 5 to 40+ years, depending on the location. + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * Get Daily Historical Actuals service returns climatology data such as past + * daily actual observed temperatures, + * precipitation, snowfall, snow depth and cooling/heating degree day + * information, for the day at a given coordinate + * location. The data is requested for a specified date range, up to 31 days in + * a single API request. Generally, + * historical data may be available as far back as the last 5 to 40+ years, + * depending on the location. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The date range supported is 1 to 31 - * calendar days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The + * date range supported is 1 to 31 + * calendar days, so be sure to specify a startDate and endDate + * that does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The date range supported is 1 to 31 calendar - * days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The + * date range supported is 1 to 31 calendar + * days, so be sure to specify a startDate and endDate that + * does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -2039,27 +2845,40 @@ public Mono> getDailyHistoricalActualsWit * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        Get Daily Historical Actuals service returns climatology data such as past daily actual observed temperatures, - * precipitation, snowfall, snow depth and cooling/heating degree day information, for the day at a given coordinate - * location. The data is requested for a specified date range, up to 31 days in a single API request. Generally, - * historical data may be available as far back as the last 5 to 40+ years, depending on the location. + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * Get Daily Historical Actuals service returns climatology data such as past + * daily actual observed temperatures, + * precipitation, snowfall, snow depth and cooling/heating degree day + * information, for the day at a given coordinate + * location. The data is requested for a specified date range, up to 31 days in + * a single API request. Generally, + * historical data may be available as far back as the last 5 to 40+ years, + * depending on the location. * * @param context The context to associate with this operation. - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The date range supported is 1 to 31 - * calendar days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The + * date range supported is 1 to 31 + * calendar days, so be sure to specify a startDate and endDate + * that does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The date range supported is 1 to 31 calendar - * days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The + * date range supported is 1 to 31 calendar + * days, so be sure to specify a startDate and endDate that + * does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated Mono> getDailyHistoricalActualsWithResponse(GeoPosition position, @@ -2081,25 +2900,37 @@ Mono> getDailyHistoricalActualsWithRespon * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get Daily Historical Records service returns climatology data such as past daily record temperatures, - * precipitation and snowfall at a given coordinate location. Availability of records data will vary by location. - * Generally, historical data may be available as far back as the last 5 to 40+ years, depending on the location. + *

        + * Get Daily Historical Records service returns climatology data such as past + * daily record temperatures, + * precipitation and snowfall at a given coordinate location. Availability of + * records data will vary by location. + * Generally, historical data may be available as far back as the last 5 to 40+ + * years, depending on the location. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The date range supported is 1 to 31 - * calendar days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The + * date range supported is 1 to 31 + * calendar days, so be sure to specify a startDate and endDate + * that does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The date range supported is 1 to 31 calendar - * days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The + * date range supported is 1 to 31 calendar + * days, so be sure to specify a startDate and endDate that + * does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -2119,25 +2950,37 @@ public Mono getDailyHistoricalRecords(GeoPosition * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get Daily Historical Records service returns climatology data such as past daily record temperatures, - * precipitation and snowfall at a given coordinate location. Availability of records data will vary by location. - * Generally, historical data may be available as far back as the last 5 to 40+ years, depending on the location. + *

        + * Get Daily Historical Records service returns climatology data such as past + * daily record temperatures, + * precipitation and snowfall at a given coordinate location. Availability of + * records data will vary by location. + * Generally, historical data may be available as far back as the last 5 to 40+ + * years, depending on the location. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The date range supported is 1 to 31 - * calendar days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The + * date range supported is 1 to 31 + * calendar days, so be sure to specify a startDate and endDate + * that does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The date range supported is 1 to 31 calendar - * days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The + * date range supported is 1 to 31 calendar + * days, so be sure to specify a startDate and endDate that + * does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -2158,26 +3001,38 @@ public Mono> getDailyHistoricalRecordsWit * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get Daily Historical Records service returns climatology data such as past daily record temperatures, - * precipitation and snowfall at a given coordinate location. Availability of records data will vary by location. - * Generally, historical data may be available as far back as the last 5 to 40+ years, depending on the location. + *

        + * Get Daily Historical Records service returns climatology data such as past + * daily record temperatures, + * precipitation and snowfall at a given coordinate location. Availability of + * records data will vary by location. + * Generally, historical data may be available as far back as the last 5 to 40+ + * years, depending on the location. * * @param context The context to associate with this operation. - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The date range supported is 1 to 31 - * calendar days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The + * date range supported is 1 to 31 + * calendar days, so be sure to specify a startDate and endDate + * that does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The date range supported is 1 to 31 calendar - * days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The + * date range supported is 1 to 31 calendar + * days, so be sure to specify a startDate and endDate that + * does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated Mono> getDailyHistoricalRecordsWithResponse(GeoPosition position, @@ -2199,28 +3054,42 @@ Mono> getDailyHistoricalRecordsWithRespon * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        Get Daily Historical Normals service returns climatology data such as past daily normal temperatures, - * precipitation and cooling/heating degree day information for the day at a given coordinate location. Normals are - * a 30-year average for temperatures and precipitation for a specific location. As is standard practice in - * climatology, the 30-year average covers years 1991-2020, this data will be used for one decade and then will - * reset in the year 2030. Generally, historical data may be available as far back as the last 5 to 40+ years, + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * Get Daily Historical Normals service returns climatology data such as past + * daily normal temperatures, + * precipitation and cooling/heating degree day information for the day at a + * given coordinate location. Normals are + * a 30-year average for temperatures and precipitation for a specific location. + * As is standard practice in + * climatology, the 30-year average covers years 1991-2020, this data will be + * used for one decade and then will + * reset in the year 2030. Generally, historical data may be available as far + * back as the last 5 to 40+ years, * depending on the location. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The date range supported is 1 to 31 - * calendar days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The + * date range supported is 1 to 31 + * calendar days, so be sure to specify a startDate and endDate + * that does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The date range supported is 1 to 31 calendar - * days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The + * date range supported is 1 to 31 calendar + * days, so be sure to specify a startDate and endDate that + * does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -2240,28 +3109,42 @@ public Mono getDailyHistoricalNormals(GeoPosition * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        Get Daily Historical Normals service returns climatology data such as past daily normal temperatures, - * precipitation and cooling/heating degree day information for the day at a given coordinate location. Normals are - * a 30-year average for temperatures and precipitation for a specific location. As is standard practice in - * climatology, the 30-year average covers years 1991-2020, this data will be used for one decade and then will - * reset in the year 2030. Generally, historical data may be available as far back as the last 5 to 40+ years, + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * Get Daily Historical Normals service returns climatology data such as past + * daily normal temperatures, + * precipitation and cooling/heating degree day information for the day at a + * given coordinate location. Normals are + * a 30-year average for temperatures and precipitation for a specific location. + * As is standard practice in + * climatology, the 30-year average covers years 1991-2020, this data will be + * used for one decade and then will + * reset in the year 2030. Generally, historical data may be available as far + * back as the last 5 to 40+ years, * depending on the location. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The date range supported is 1 to 31 - * calendar days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The + * date range supported is 1 to 31 + * calendar days, so be sure to specify a startDate and endDate + * that does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The date range supported is 1 to 31 calendar - * days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The + * date range supported is 1 to 31 calendar + * days, so be sure to specify a startDate and endDate that + * does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -2282,29 +3165,43 @@ public Mono> getDailyHistoricalNormalsWit * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        Get Daily Historical Normals service returns climatology data such as past daily normal temperatures, - * precipitation and cooling/heating degree day information for the day at a given coordinate location. Normals are - * a 30-year average for temperatures and precipitation for a specific location. As is standard practice in - * climatology, the 30-year average covers years 1991-2020, this data will be used for one decade and then will - * reset in the year 2030. Generally, historical data may be available as far back as the last 5 to 40+ years, + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * Get Daily Historical Normals service returns climatology data such as past + * daily normal temperatures, + * precipitation and cooling/heating degree day information for the day at a + * given coordinate location. Normals are + * a 30-year average for temperatures and precipitation for a specific location. + * As is standard practice in + * climatology, the 30-year average covers years 1991-2020, this data will be + * used for one decade and then will + * reset in the year 2030. Generally, historical data may be available as far + * back as the last 5 to 40+ years, * depending on the location. * * @param context The context to associate with this operation. - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The date range supported is 1 to 31 - * calendar days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The + * date range supported is 1 to 31 + * calendar days, so be sure to specify a startDate and endDate + * that does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The date range supported is 1 to 31 calendar - * days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The + * date range supported is 1 to 31 calendar + * days, so be sure to specify a startDate and endDate that + * does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated Mono> getDailyHistoricalNormalsWithResponse(GeoPosition position, diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/WeatherClient.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/WeatherClient.java index f38ff8d28c84..353e0f072d91 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/WeatherClient.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/WeatherClient.java @@ -16,6 +16,7 @@ import com.azure.maps.weather.models.ActiveStormResult; import com.azure.maps.weather.models.AirQualityResult; import com.azure.maps.weather.models.BasinId; +import com.azure.maps.weather.models.CurrentConditionDuration; import com.azure.maps.weather.models.CurrentConditionsResult; import com.azure.maps.weather.models.DailyAirQualityForecastResult; import com.azure.maps.weather.models.DailyDuration; @@ -43,7 +44,8 @@ /** * Initializes a new instance of the synchronous WeatherClient type. - * {@link WeatherClient} instances are created via the {@link WeatherClientBuilder}, as shown below. + * {@link WeatherClient} instances are created via the + * {@link WeatherClientBuilder}, as shown below. * Creating a sync client using a {@link AzureKeyCredential}: * *

        @@ -81,32 +83,52 @@ public final class WeatherClient {
              * 
        * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Request detailed weather forecast by the hour for the next 1, 12, 24 (1 day), 72 (3 days), 120 (5 days), and - * 240 hours (10 days) for the given coordinate location. The API returns details such as temperature, + *

        + * Request detailed weather forecast by the hour for the next 1, 12, 24 (1 day), + * 72 (3 days), 120 (5 days), and + * 240 hours (10 days) for the given coordinate location. The API returns + * details such as temperature, * humidity, wind, precipitation, and ultraviolet (UV) index. * - *

        In S0 you can request hourly forecast for the next 1, 12, 24 hours (1 day), and 72 hours (3 days). In S1 you - * can also request hourly forecast for the next 120 (5 days) and 240 hours (10 days). + *

        + * In S0 you can request hourly forecast for the next 1, 12, 24 hours (1 day), + * and 72 hours (3 days). In S1 you + * can also request hourly forecast for the next 120 (5 days) and 240 hours (10 + * days). * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. - * @param duration Time frame of the returned weather forecast. By default, the forecast data for next hour will be - * returned. Available values are * `1` - Return forecast data for the next hour. Default value. * `12` - Return - * hourly forecast for next 12 hours. * `24` - Return hourly forecast for next 24 hours. * `72` - Return hourly - * forecast for next 72 hours (3 days). * `120` - Return hourly forecast for next 120 hours (5 days). Only - * available in S1 SKU. * `240` - Return hourly forecast for next 240 hours (10 days). Only available in S1 SKU. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. + * @param duration Time frame of the returned weather forecast. By default, the + * forecast data for next hour will be + * returned. Available values are * `1` - Return forecast data + * for the next hour. Default value. * `12` - Return + * hourly forecast for next 12 hours. * `24` - Return hourly + * forecast for next 24 hours. * `72` - Return hourly + * forecast for next 72 hours (3 days). * `120` - Return hourly + * forecast for next 120 hours (5 days). Only + * available in S1 SKU. * `240` - Return hourly forecast for + * next 240 hours (10 days). Only available in S1 SKU. + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -124,33 +146,53 @@ public HourlyForecastResult getHourlyForecast(GeoPosition position, WeatherDataU * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Request detailed weather forecast by the hour for the next 1, 12, 24 (1 day), 72 (3 days), 120 (5 days), and - * 240 hours (10 days) for the given coordinate location. The API returns details such as temperature, + *

        + * Request detailed weather forecast by the hour for the next 1, 12, 24 (1 day), + * 72 (3 days), 120 (5 days), and + * 240 hours (10 days) for the given coordinate location. The API returns + * details such as temperature, * humidity, wind, precipitation, and ultraviolet (UV) index. * - *

        In S0 you can request hourly forecast for the next 1, 12, 24 hours (1 day), and 72 hours (3 days). In S1 you - * can also request hourly forecast for the next 120 (5 days) and 240 hours (10 days). + *

        + * In S0 you can request hourly forecast for the next 1, 12, 24 hours (1 day), + * and 72 hours (3 days). In S1 you + * can also request hourly forecast for the next 120 (5 days) and 240 hours (10 + * days). * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. - * @param duration Time frame of the returned weather forecast. By default, the forecast data for next hour will be - * returned. Available values are * `1` - Return forecast data for the next hour. Default value. * `12` - Return - * hourly forecast for next 12 hours. * `24` - Return hourly forecast for next 24 hours. * `72` - Return hourly - * forecast for next 72 hours (3 days). * `120` - Return hourly forecast for next 120 hours (5 days). Only - * available in S1 SKU. * `240` - Return hourly forecast for next 240 hours (10 days). Only available in S1 SKU. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. + * @param duration Time frame of the returned weather forecast. By default, the + * forecast data for next hour will be + * returned. Available values are * `1` - Return forecast data + * for the next hour. Default value. * `12` - Return + * hourly forecast for next 12 hours. * `24` - Return hourly + * forecast for next 24 hours. * `72` - Return hourly + * forecast for next 72 hours (3 days). * `120` - Return hourly + * forecast for next 120 hours (5 days). Only + * available in S1 SKU. * `240` - Return hourly forecast for + * next 240 hours (10 days). Only available in S1 SKU. + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @param context The context to associate with this operation. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -168,27 +210,42 @@ public Response getHourlyForecastWithResponse(GeoPosition * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get Minute Forecast service returns minute-by-minute forecasts for a given location for the next 120 minutes. - * Users can request weather forecasts in the interval of 1, 5 and 15 minutes. The response will include details - * such as the type of precipitation (including rain, snow, or a mixture of both), start time, and precipitation + *

        + * Get Minute Forecast service returns minute-by-minute forecasts for a given + * location for the next 120 minutes. + * Users can request weather forecasts in the interval of 1, 5 and 15 minutes. + * The response will include details + * such as the type of precipitation (including rain, snow, or a mixture of + * both), start time, and precipitation * intensity value (dBZ). * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param interval Specifies time interval in minutes for the returned weather forecast. Supported values are * `1` - * - Retrieve forecast for 1-minute intervals. Returned by default. * `5` - Retrieve forecasts for 5-minute - * intervals. * `15` - Retrieve forecasts for 15-minute intervals. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param interval Specifies time interval in minutes for the returned weather + * forecast. Supported values are * `1` + * - Retrieve forecast for 1-minute intervals. Returned by + * default. * `5` - Retrieve forecasts for 5-minute + * intervals. * `15` - Retrieve forecasts for 15-minute + * intervals. + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -205,28 +262,43 @@ public MinuteForecastResult getMinuteForecast(GeoPosition position, Integer inte * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get Minute Forecast service returns minute-by-minute forecasts for a given location for the next 120 minutes. - * Users can request weather forecasts in the interval of 1, 5 and 15 minutes. The response will include details - * such as the type of precipitation (including rain, snow, or a mixture of both), start time, and precipitation + *

        + * Get Minute Forecast service returns minute-by-minute forecasts for a given + * location for the next 120 minutes. + * Users can request weather forecasts in the interval of 1, 5 and 15 minutes. + * The response will include details + * such as the type of precipitation (including rain, snow, or a mixture of + * both), start time, and precipitation * intensity value (dBZ). * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param interval Specifies time interval in minutes for the returned weather forecast. Supported values are * `1` - * - Retrieve forecast for 1-minute intervals. Returned by default. * `5` - Retrieve forecasts for 5-minute - * intervals. * `15` - Retrieve forecasts for 15-minute intervals. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param interval Specifies time interval in minutes for the returned weather + * forecast. Supported values are * `1` + * - Retrieve forecast for 1-minute intervals. Returned by + * default. * `5` - Retrieve forecasts for 5-minute + * intervals. * `15` - Retrieve forecasts for 15-minute + * intervals. + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @param context The context to associate with this operation. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -244,28 +316,44 @@ public Response getMinuteForecastWithResponse(GeoPosition * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Service returns detailed weather forecast by quarter-day for the next 1, 5, 10, or 15 days for a given - * location. Response data is presented by quarters of the day - morning, afternoon, evening, and overnight. Details - * such as temperature, humidity, wind, precipitation, and UV index are returned. + *

        + * Service returns detailed weather forecast by quarter-day for the next 1, 5, + * 10, or 15 days for a given + * location. Response data is presented by quarters of the day - morning, + * afternoon, evening, and overnight. Details + * such as temperature, humidity, wind, precipitation, and UV index are + * returned. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. - * @param duration Specifies for how many days the quester-day forecast responses are returned. Supported values - * are: * `1` - Return forecast data for the next day. Returned by default. * `5` - Return forecast data for the - * next 5 days. * `10` - Return forecast data for next 10 days. * `15` - Return forecast data for the next 15 + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. + * @param duration Specifies for how many days the quester-day forecast + * responses are returned. Supported values + * are: * `1` - Return forecast data for the next day. Returned + * by default. * `5` - Return forecast data for the + * next 5 days. * `10` - Return forecast data for next 10 days. + * * `15` - Return forecast data for the next 15 * days. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -283,29 +371,45 @@ public QuarterDayForecastResult getQuarterDayForecast(GeoPosition position, Weat * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Service returns detailed weather forecast by quarter-day for the next 1, 5, 10, or 15 days for a given - * location. Response data is presented by quarters of the day - morning, afternoon, evening, and overnight. Details - * such as temperature, humidity, wind, precipitation, and UV index are returned. + *

        + * Service returns detailed weather forecast by quarter-day for the next 1, 5, + * 10, or 15 days for a given + * location. Response data is presented by quarters of the day - morning, + * afternoon, evening, and overnight. Details + * such as temperature, humidity, wind, precipitation, and UV index are + * returned. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. - * @param duration Specifies for how many days the quester-day forecast responses are returned. Supported values - * are: * `1` - Return forecast data for the next day. Returned by default. * `5` - Return forecast data for the - * next 5 days. * `10` - Return forecast data for next 10 days. * `15` - Return forecast data for the next 15 + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. + * @param duration Specifies for how many days the quester-day forecast + * responses are returned. Supported values + * are: * `1` - Return forecast data for the next day. Returned + * by default. * `5` - Return forecast data for the + * next 5 days. * `10` - Return forecast data for next 10 days. + * * `15` - Return forecast data for the next 15 * days. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @param context The context to associate with this operation. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -320,44 +424,74 @@ public Response getQuarterDayForecastWithResponse(GeoP * *

              * client.getCurrentConditions(new GeoPosition(-122.125679, 47.641268),
        -     *     null, null, null, null);
        +     *     null, true, null, null);
              * 
        * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        Get Current Conditions service returns detailed current weather conditions such as precipitation, temperature - * and wind for a given coordinate location. Also, observations from the past 6 or 24 hours for a particular - * location can be retrieved. The basic information returned with the response include details such as observation - * date and time, brief description of the weather conditions, weather icon, precipitation indicator flags, and - * temperature. Additional details such as RealFeel™ Temperature and UV index are also returned. - * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * Get Current Conditions service returns detailed current weather conditions + * such as precipitation, temperature + * and wind for a given coordinate location. Also, observations from the past 6 + * or 24 hours for a particular + * location can be retrieved. The basic information returned with the response + * include details such as observation + * date and time, brief description of the weather conditions, weather icon, + * precipitation indicator flags, and + * temperature. Additional details such as RealFeel™ Temperature and UV index + * are also returned. + * + * @param position The applicable query specified as a comma separated + * string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. - * @param details Return full details for the current conditions. Available values are * `true` - Returns full - * details. By default, all details are returned. * `false` - Returns a truncated version of the current - * condition data, which includes observation date time, weather phrase, icon code, precipitation indicator + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. + * @param includeDetails Return full details for the current conditions. + * Available + * values are * `true` - Returns full + * details. By default, all details are returned. * + * `false` - + * Returns a truncated version of the current + * condition data, which includes observation date time, + * weather + * phrase, icon code, precipitation indicator * flag, and temperature. - * @param duration Time frame of the returned weather conditions. By default, the most current weather conditions - * will be returned. Default value is 0. Supported values are: * `0` - Return the most current weather - * conditions. * `6` - Return weather conditions from past 6 hours. * `24` - Return weather conditions from past + * @param duration Time frame of the returned weather conditions. By + * default, + * the most current weather conditions + * will be returned. Default value is 0. Supported values + * are: * + * `0` - Return the most current weather + * conditions. * `6` - Return weather conditions from past + * 6 + * hours. * `24` - Return weather conditions from past * 24 hours. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. + * Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language + * is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public CurrentConditionsResult getCurrentConditions(GeoPosition position, WeatherDataUnit unit, String details, - Integer duration, String language) { - return this.asyncClient.getCurrentConditions(position, unit, details, duration, language).block(); + public CurrentConditionsResult getCurrentConditions(GeoPosition position, WeatherDataUnit unit, + Boolean includeDetails, CurrentConditionDuration duration, String language) { + return this.asyncClient.getCurrentConditions(position, unit, includeDetails, duration, language).block(); } /** @@ -366,45 +500,77 @@ public CurrentConditionsResult getCurrentConditions(GeoPosition position, Weathe * *

              * client.getCurrentConditions(new GeoPosition(-122.125679, 47.641268),
        -     *     null, null, null, null);
        +     *     null, true, null, null);
              * 
        * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        Get Current Conditions service returns detailed current weather conditions such as precipitation, temperature - * and wind for a given coordinate location. Also, observations from the past 6 or 24 hours for a particular - * location can be retrieved. The basic information returned with the response include details such as observation - * date and time, brief description of the weather conditions, weather icon, precipitation indicator flags, and - * temperature. Additional details such as RealFeel™ Temperature and UV index are also returned. - * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * Get Current Conditions service returns detailed current weather conditions + * such as precipitation, temperature + * and wind for a given coordinate location. Also, observations from the past 6 + * or 24 hours for a particular + * location can be retrieved. The basic information returned with the response + * include details such as observation + * date and time, brief description of the weather conditions, weather icon, + * precipitation indicator flags, and + * temperature. Additional details such as RealFeel™ Temperature and UV index + * are also returned. + * + * @param position The applicable query specified as a comma separated + * string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. - * @param details Return full details for the current conditions. Available values are * `true` - Returns full - * details. By default, all details are returned. * `false` - Returns a truncated version of the current - * condition data, which includes observation date time, weather phrase, icon code, precipitation indicator + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. + * @param includeDetails Return full details for the current conditions. + * Available + * values are * `true` - Returns full + * details. By default, all details are returned. * + * `false` - + * Returns a truncated version of the current + * condition data, which includes observation date time, + * weather + * phrase, icon code, precipitation indicator * flag, and temperature. - * @param duration Time frame of the returned weather conditions. By default, the most current weather conditions - * will be returned. Default value is 0. Supported values are: * `0` - Return the most current weather - * conditions. * `6` - Return weather conditions from past 6 hours. * `24` - Return weather conditions from past + * @param duration Time frame of the returned weather conditions. By + * default, + * the most current weather conditions + * will be returned. Default value is 0. Supported values + * are: * + * `0` - Return the most current weather + * conditions. * `6` - Return weather conditions from past + * 6 + * hours. * `24` - Return weather conditions from past * 24 hours. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. + * Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language + * is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @param context The context to associate with this operation. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) public Response getCurrentConditionsWithResponse(GeoPosition position, - WeatherDataUnit unit, String details, Integer duration, String language, Context context) { - return this.asyncClient.getCurrentConditionsWithResponse(position, unit, details, duration, language, context) + WeatherDataUnit unit, Boolean includeDetails, CurrentConditionDuration duration, String language, + Context context) { + return this.asyncClient + .getCurrentConditionsWithResponse(position, unit, includeDetails, duration, language, context) .block(); } @@ -417,31 +583,49 @@ public Response getCurrentConditionsWithResponse(GeoPos * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        The service returns detailed weather forecast such as temperature and wind by day for the next 1, 5, 10, 15, - * 25, or 45 days for a given coordinate location. The response include details such as temperature, wind, + *

        + * The service returns detailed weather forecast such as temperature and wind by + * day for the next 1, 5, 10, 15, + * 25, or 45 days for a given coordinate location. The response include details + * such as temperature, wind, * precipitation, air quality, and UV index. * - *

        In S0 you can request daily forecast for the next 1, 5, 10, and 15 days. In S1 you can also request daily + *

        + * In S0 you can request daily forecast for the next 1, 5, 10, and 15 days. In + * S1 you can also request daily * forecast for the next 25 days, and 45 days. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. - * @param duration Specifies for how many days the daily forecast responses are returned. Available values are * `1` - * - Return forecast data for the next day. Returned by default. * `5` - Return forecast data for the next 5 - * days. * `10` - Return forecast data for the next 10 days. * `25` - Return forecast data for the next 25 days. - * Only available in S1 SKU. * `45` - Return forecast data for the next 45 days. Only available in S1 SKU. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. + * @param duration Specifies for how many days the daily forecast responses are + * returned. Available values are * `1` + * - Return forecast data for the next day. Returned by default. + * * `5` - Return forecast data for the next 5 + * days. * `10` - Return forecast data for the next 10 days. * + * `25` - Return forecast data for the next 25 days. + * Only available in S1 SKU. * `45` - Return forecast data for + * the next 45 days. Only available in S1 SKU. + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -459,32 +643,50 @@ public DailyForecastResult getDailyForecast(GeoPosition position, WeatherDataUni * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        The service returns detailed weather forecast such as temperature and wind by day for the next 1, 5, 10, 15, - * 25, or 45 days for a given coordinate location. The response include details such as temperature, wind, + *

        + * The service returns detailed weather forecast such as temperature and wind by + * day for the next 1, 5, 10, 15, + * 25, or 45 days for a given coordinate location. The response include details + * such as temperature, wind, * precipitation, air quality, and UV index. * - *

        In S0 you can request daily forecast for the next 1, 5, 10, and 15 days. In S1 you can also request daily + *

        + * In S0 you can request daily forecast for the next 1, 5, 10, and 15 days. In + * S1 you can also request daily * forecast for the next 25 days, and 45 days. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. - * @param duration Specifies for how many days the daily forecast responses are returned. Available values are * `1` - * - Return forecast data for the next day. Returned by default. * `5` - Return forecast data for the next 5 - * days. * `10` - Return forecast data for the next 10 days. * `25` - Return forecast data for the next 25 days. - * Only available in S1 SKU. * `45` - Return forecast data for the next 45 days. Only available in S1 SKU. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. + * @param duration Specifies for how many days the daily forecast responses are + * returned. Available values are * `1` + * - Return forecast data for the next day. Returned by default. + * * `5` - Return forecast data for the next 5 + * days. * `10` - Return forecast data for the next 10 days. * + * `25` - Return forecast data for the next 25 days. + * Only available in S1 SKU. * `45` - Return forecast data for + * the next 45 days. Only available in S1 SKU. + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @param context The context to associate with this operation. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -511,53 +713,93 @@ public Response getDailyForecastWithResponse(GeoPosition po * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        Weather along a route API returns hyper local (one kilometer or less), up-to-the-minute weather nowcasts, - * weather hazard assessments, and notifications along a route described as a sequence of waypoints. This includes a - * list of weather hazards affecting the waypoint or route, and the aggregated hazard index for each waypoint might - * be used to paint each portion of a route according to how safe it is for the driver. When submitting the - * waypoints, it is recommended to stay within, or close to, the distance that can be traveled within 120-mins or + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * Weather along a route API returns hyper local (one kilometer or less), + * up-to-the-minute weather nowcasts, + * weather hazard assessments, and notifications along a route described as a + * sequence of waypoints. This includes a + * list of weather hazards affecting the waypoint or route, and the aggregated + * hazard index for each waypoint might + * be used to paint each portion of a route according to how safe it is for the + * driver. When submitting the + * waypoints, it is recommended to stay within, or close to, the distance that + * can be traveled within 120-mins or * shortly after. Data is updated every five minutes. * - *

        The service supplements Azure Maps [Route Service](https://docs.microsoft.com/rest/api/maps/route) that allows - * you to first request a route between an origin and a destination and use that as an input for Weather Along Route + *

        + * The service supplements Azure Maps [Route + * Service](https://docs.microsoft.com/rest/api/maps/route) that allows + * you to first request a route between an origin and a destination and use that + * as an input for Weather Along Route * endpoint. * - *

        In addition, the service supports scenarios to generate weather notifications for waypoints that experience an - * increase in intensity of a weather hazard. For example, if the vehicle is expected to begin experiencing heavy - * rain as it reaches a waypoint, a weather notification for heavy rain will be generated for that waypoint allowing - * the end product to display a heavy rain notification before the driver reaches that waypoint. The trigger for - * when to display the notification for a waypoint could be based, for example, on a - * [geofence](https://docs.microsoft.com/azure/azure-maps/tutorial-iot-hub-maps), or selectable distance to the + *

        + * In addition, the service supports scenarios to generate weather notifications + * for waypoints that experience an + * increase in intensity of a weather hazard. For example, if the vehicle is + * expected to begin experiencing heavy + * rain as it reaches a waypoint, a weather notification for heavy rain will be + * generated for that waypoint allowing + * the end product to display a heavy rain notification before the driver + * reaches that waypoint. The trigger for + * when to display the notification for a waypoint could be based, for example, + * on a + * [geofence](https://docs.microsoft.com/azure/azure-maps/tutorial-iot-hub-maps), + * or selectable distance to the * waypoint. * - *

        The API covers all regions of the planet except latitudes above Greenland and Antarctica. - * - * @param waypoints Coordinates through which the route is calculated, separated by colon (:) and entered in - * chronological order. A minimum of two waypoints is required. A single API call may contain up to 60 - * waypoints. A waypoint indicates location, ETA, and optional heading: latitude,longitude,ETA,heading, where * - * `Latitude` - Latitude coordinate in decimal degrees. * `Longitude` - Longitude coordinate in decimal degrees. - * * `ETA (estimated time of arrival)` - The number of minutes from the present time that it will take for the - * vehicle to reach the waypoint. Allowed range is from 0.0 to 120.0 minutes. * `Heading` - An optional value - * indicating the vehicle heading as it passes the waypoint. Expressed in clockwise degrees relative to true - * north. This is issued to calculate sun glare as a driving hazard. Allowed range is from 0.0 to 360.0 degrees. - * If not provided, a heading will automatically be derived based on the position of neighboring waypoints. - *

        It is recommended to stay within, or close to, the distance that can be traveled within 120-mins or - * shortly after. This way a more accurate assessment can be provided for the trip and prevent isolated events - * not being captured between waypoints. Information can and should be updated along the route (especially for - * trips greater than 2 hours) to continuously pull new waypoints moving forward, but also to ensure that - * forecast information for content such as precipitation type and intensity is accurate as storms develop and + *

        + * The API covers all regions of the planet except latitudes above Greenland and + * Antarctica. + * + * @param waypoints Coordinates through which the route is calculated, separated + * by colon (:) and entered in + * chronological order. A minimum of two waypoints is required. + * A single API call may contain up to 60 + * waypoints. A waypoint indicates location, ETA, and optional + * heading: latitude,longitude,ETA,heading, where * + * `Latitude` - Latitude coordinate in decimal degrees. * + * `Longitude` - Longitude coordinate in decimal degrees. + * * `ETA (estimated time of arrival)` - The number of minutes + * from the present time that it will take for the + * vehicle to reach the waypoint. Allowed range is from 0.0 to + * 120.0 minutes. * `Heading` - An optional value + * indicating the vehicle heading as it passes the waypoint. + * Expressed in clockwise degrees relative to true + * north. This is issued to calculate sun glare as a driving + * hazard. Allowed range is from 0.0 to 360.0 degrees. + * If not provided, a heading will automatically be derived + * based on the position of neighboring waypoints. + *

        + * It is recommended to stay within, or close to, the distance + * that can be traveled within 120-mins or + * shortly after. This way a more accurate assessment can be + * provided for the trip and prevent isolated events + * not being captured between waypoints. Information can and + * should be updated along the route (especially for + * trips greater than 2 hours) to continuously pull new + * waypoints moving forward, but also to ensure that + * forecast information for content such as precipitation type + * and intensity is accurate as storms develop and * dissipate over time. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @return this object is returned from a successful Weather Along Route. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -583,54 +825,94 @@ public WeatherAlongRouteResult getWeatherAlongRoute(List waypoints, St * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        Weather along a route API returns hyper local (one kilometer or less), up-to-the-minute weather nowcasts, - * weather hazard assessments, and notifications along a route described as a sequence of waypoints. This includes a - * list of weather hazards affecting the waypoint or route, and the aggregated hazard index for each waypoint might - * be used to paint each portion of a route according to how safe it is for the driver. When submitting the - * waypoints, it is recommended to stay within, or close to, the distance that can be traveled within 120-mins or + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * Weather along a route API returns hyper local (one kilometer or less), + * up-to-the-minute weather nowcasts, + * weather hazard assessments, and notifications along a route described as a + * sequence of waypoints. This includes a + * list of weather hazards affecting the waypoint or route, and the aggregated + * hazard index for each waypoint might + * be used to paint each portion of a route according to how safe it is for the + * driver. When submitting the + * waypoints, it is recommended to stay within, or close to, the distance that + * can be traveled within 120-mins or * shortly after. Data is updated every five minutes. * - *

        The service supplements Azure Maps [Route Service](https://docs.microsoft.com/rest/api/maps/route) that allows - * you to first request a route between an origin and a destination and use that as an input for Weather Along Route + *

        + * The service supplements Azure Maps [Route + * Service](https://docs.microsoft.com/rest/api/maps/route) that allows + * you to first request a route between an origin and a destination and use that + * as an input for Weather Along Route * endpoint. * - *

        In addition, the service supports scenarios to generate weather notifications for waypoints that experience an - * increase in intensity of a weather hazard. For example, if the vehicle is expected to begin experiencing heavy - * rain as it reaches a waypoint, a weather notification for heavy rain will be generated for that waypoint allowing - * the end product to display a heavy rain notification before the driver reaches that waypoint. The trigger for - * when to display the notification for a waypoint could be based, for example, on a - * [geofence](https://docs.microsoft.com/azure/azure-maps/tutorial-iot-hub-maps), or selectable distance to the + *

        + * In addition, the service supports scenarios to generate weather notifications + * for waypoints that experience an + * increase in intensity of a weather hazard. For example, if the vehicle is + * expected to begin experiencing heavy + * rain as it reaches a waypoint, a weather notification for heavy rain will be + * generated for that waypoint allowing + * the end product to display a heavy rain notification before the driver + * reaches that waypoint. The trigger for + * when to display the notification for a waypoint could be based, for example, + * on a + * [geofence](https://docs.microsoft.com/azure/azure-maps/tutorial-iot-hub-maps), + * or selectable distance to the * waypoint. * - *

        The API covers all regions of the planet except latitudes above Greenland and Antarctica. - * - * @param waypoints Coordinates through which the route is calculated, separated by colon (:) and entered in - * chronological order. A minimum of two waypoints is required. A single API call may contain up to 60 - * waypoints. A waypoint indicates location, ETA, and optional heading: latitude,longitude,ETA,heading, where * - * `Latitude` - Latitude coordinate in decimal degrees. * `Longitude` - Longitude coordinate in decimal degrees. - * * `ETA (estimated time of arrival)` - The number of minutes from the present time that it will take for the - * vehicle to reach the waypoint. Allowed range is from 0.0 to 120.0 minutes. * `Heading` - An optional value - * indicating the vehicle heading as it passes the waypoint. Expressed in clockwise degrees relative to true - * north. This is issued to calculate sun glare as a driving hazard. Allowed range is from 0.0 to 360.0 degrees. - * If not provided, a heading will automatically be derived based on the position of neighboring waypoints. - *

        It is recommended to stay within, or close to, the distance that can be traveled within 120-mins or - * shortly after. This way a more accurate assessment can be provided for the trip and prevent isolated events - * not being captured between waypoints. Information can and should be updated along the route (especially for - * trips greater than 2 hours) to continuously pull new waypoints moving forward, but also to ensure that - * forecast information for content such as precipitation type and intensity is accurate as storms develop and + *

        + * The API covers all regions of the planet except latitudes above Greenland and + * Antarctica. + * + * @param waypoints Coordinates through which the route is calculated, separated + * by colon (:) and entered in + * chronological order. A minimum of two waypoints is required. + * A single API call may contain up to 60 + * waypoints. A waypoint indicates location, ETA, and optional + * heading: latitude,longitude,ETA,heading, where * + * `Latitude` - Latitude coordinate in decimal degrees. * + * `Longitude` - Longitude coordinate in decimal degrees. + * * `ETA (estimated time of arrival)` - The number of minutes + * from the present time that it will take for the + * vehicle to reach the waypoint. Allowed range is from 0.0 to + * 120.0 minutes. * `Heading` - An optional value + * indicating the vehicle heading as it passes the waypoint. + * Expressed in clockwise degrees relative to true + * north. This is issued to calculate sun glare as a driving + * hazard. Allowed range is from 0.0 to 360.0 degrees. + * If not provided, a heading will automatically be derived + * based on the position of neighboring waypoints. + *

        + * It is recommended to stay within, or close to, the distance + * that can be traveled within 120-mins or + * shortly after. This way a more accurate assessment can be + * provided for the trip and prevent isolated events + * not being captured between waypoints. Information can and + * should be updated along the route (especially for + * trips greater than 2 hours) to continuously pull new + * waypoints moving forward, but also to ensure that + * forecast information for content such as precipitation type + * and intensity is accurate as storms develop and * dissipate over time. - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. * @param context The context to associate with this operation. * @return this object is returned from a successful Weather Along Route. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -648,31 +930,52 @@ public Response getWeatherAlongRouteWithResponse(List * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        Severe weather phenomenon can significantly impact our everyday life and business operations. For example, - * severe weather conditions such as tropical storms, high winds or flooding can close roads and force logistics - * companies to reroute their fleet causing delays in reaching destinations and breaking the cold chain of - * refrigerated food products. Azure Maps Severe Weather Alerts API returns the severe weather alerts that are - * available worldwide from both official Government Meteorological Agencies and leading global to - * regional weather alert providers. The service can return details such as alert type, category, level and detailed - * description about the active severe alerts for the requested location, like hurricanes, thunderstorms, lightning, + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * Severe weather phenomenon can significantly impact our everyday life and + * business operations. For example, + * severe weather conditions such as tropical storms, high winds or flooding can + * close roads and force logistics + * companies to reroute their fleet causing delays in reaching destinations and + * breaking the cold chain of + * refrigerated food products. Azure Maps Severe Weather Alerts API returns the + * severe weather alerts that are + * available worldwide from both official Government Meteorological Agencies and + * leading global to + * regional weather alert providers. The service can return details such as + * alert type, category, level and detailed + * description about the active severe alerts for the requested location, like + * hurricanes, thunderstorms, lightning, * heat waves or forest fires. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated + * string composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. + * Should be one of supported IETF language + * tags, case-insensitive. When data in specified language + * is not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. - * @param includeDetails Return full details for the severe weather alerts. Available values are * `true` - Returns full - * details. By default, all details are returned. * `false` - Returns a truncated version of the alerts data, - * which excludes the area-specific full description of alert details (`alertDetails`). - * @return this object is returned from a successful Get Severe Weather Alerts call. + * @param includeDetails Return full details for the severe weather alerts. + * Available values are * `true` - Returns full + * details. By default, all details are returned. * + * `false` - Returns a truncated version of the alerts + * data, + * which excludes the area-specific full description of + * alert details (`alertDetails`). + * @return this object is returned from a successful Get Severe Weather Alerts + * call. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -690,32 +993,53 @@ public SevereWeatherAlertsResult getSevereWeatherAlerts(GeoPosition position, St * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        Severe weather phenomenon can significantly impact our everyday life and business operations. For example, - * severe weather conditions such as tropical storms, high winds or flooding can close roads and force logistics - * companies to reroute their fleet causing delays in reaching destinations and breaking the cold chain of - * refrigerated food products. Azure Maps Severe Weather Alerts API returns the severe weather alerts that are - * available worldwide from both official Government Meteorological Agencies and leading global to - * regional weather alert providers. The service can return details such as alert type, category, level and detailed - * description about the active severe alerts for the requested location, like hurricanes, thunderstorms, lightning, + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * Severe weather phenomenon can significantly impact our everyday life and + * business operations. For example, + * severe weather conditions such as tropical storms, high winds or flooding can + * close roads and force logistics + * companies to reroute their fleet causing delays in reaching destinations and + * breaking the cold chain of + * refrigerated food products. Azure Maps Severe Weather Alerts API returns the + * severe weather alerts that are + * available worldwide from both official Government Meteorological Agencies and + * leading global to + * regional weather alert providers. The service can return details such as + * alert type, category, level and detailed + * description about the active severe alerts for the requested location, like + * hurricanes, thunderstorms, lightning, * heat waves or forest fires. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated + * string composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. + * Should be one of supported IETF language + * tags, case-insensitive. When data in specified language + * is not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. - * @param includeDetails Return full details for the severe weather alerts. Available values are * `true` - Returns full - * details. By default, all details are returned. * `false` - Returns a truncated version of the alerts data, - * which excludes the area-specific full description of alert details (`alertDetails`). + * @param includeDetails Return full details for the severe weather alerts. + * Available values are * `true` - Returns full + * details. By default, all details are returned. * + * `false` - Returns a truncated version of the alerts + * data, + * which excludes the area-specific full description of + * alert details (`alertDetails`). * @param context The context to associate with this operation. - * @return this object is returned from a successful Get Severe Weather Alerts call. + * @return this object is returned from a successful Get Severe Weather Alerts + * call. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -733,39 +1057,66 @@ public Response getSevereWeatherAlertsWithResponse(Ge * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        There may be times when you want to know if the weather conditions are optimal for a specific activity, for - * example, for outdoor construction, indoor activities, running or farming including soil moisture information. - * Azure Maps Indices API returns index values that will guide end users to plan future activities. For example, a - * health mobile application can notify users that today is good weather for running or for other outdoors - * activities like for playing golf, and retail stores can optimize their digital marketing campaigns based on - * predicted index values. The service returns in daily indices values for current and next 5, 10 and 15 days + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * There may be times when you want to know if the weather conditions are + * optimal for a specific activity, for + * example, for outdoor construction, indoor activities, running or farming + * including soil moisture information. + * Azure Maps Indices API returns index values that will guide end users to plan + * future activities. For example, a + * health mobile application can notify users that today is good weather for + * running or for other outdoors + * activities like for playing golf, and retail stores can optimize their + * digital marketing campaigns based on + * predicted index values. The service returns in daily indices values for + * current and next 5, 10 and 15 days * starting from current day. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated + * string composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. + * Should be one of supported IETF language + * tags, case-insensitive. When data in specified language + * is not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. - * @param duration Specifies for how many days the daily indices are returned. By default, the indices data for the - * current day will be returned. When requesting future indices data, the current day is included in the - * response as day 1. Available values are * `1` - Return daily index data for the current day. Default value. * - * `5` - Return 5 days of daily index data starting from the current day. * `10` - Return 10 days of daily index - * data starting from the current day. * `15` - Return 15 days of daily index data starting from the current + * @param duration Specifies for how many days the daily indices are + * returned. By default, the indices data for the + * current day will be returned. When requesting future + * indices data, the current day is included in the + * response as day 1. Available values are * `1` - Return + * daily index data for the current day. Default value. * + * `5` - Return 5 days of daily index data starting from the + * current day. * `10` - Return 10 days of daily index + * data starting from the current day. * `15` - Return 15 + * days of daily index data starting from the current * day. - * @param indexId Numeric index identifier that can be used for restricting returned results to the corresponding - * index type. Cannot be paired with `indexGroupId`. Please refer to [Weather Service - * Concepts](https://aka.ms/AzureMapsWeatherConcepts) for details and to see the supported indices. - * @param indexGroupId Numeric index group identifier that can be used for restricting returned results to the - * corresponding subset of indices (index group). Cannot be paired with `indexId`. Please refer to [Weather - * Service Concepts](https://aka.ms/AzureMapsWeatherConcepts) for details and to see the supported index groups. + * @param indexId Numeric index identifier that can be used for restricting + * returned results to the corresponding + * index type. Cannot be paired with `indexGroupId`. Please + * refer to [Weather Service + * Concepts](https://aka.ms/AzureMapsWeatherConcepts) for + * details and to see the supported indices. + * @param indexGroupId Numeric index group identifier that can be used for + * restricting returned results to the + * corresponding subset of indices (index group). Cannot be + * paired with `indexId`. Please refer to [Weather + * Service + * Concepts](https://aka.ms/AzureMapsWeatherConcepts) for + * details and to see the supported index groups. * @return this object is returned from a successful Get Daily Indices call. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -783,40 +1134,67 @@ public DailyIndicesResult getDailyIndices(GeoPosition position, String language, * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        There may be times when you want to know if the weather conditions are optimal for a specific activity, for - * example, for outdoor construction, indoor activities, running or farming including soil moisture information. - * Azure Maps Indices API returns index values that will guide end users to plan future activities. For example, a - * health mobile application can notify users that today is good weather for running or for other outdoors - * activities like for playing golf, and retail stores can optimize their digital marketing campaigns based on - * predicted index values. The service returns in daily indices values for current and next 5, 10 and 15 days + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * There may be times when you want to know if the weather conditions are + * optimal for a specific activity, for + * example, for outdoor construction, indoor activities, running or farming + * including soil moisture information. + * Azure Maps Indices API returns index values that will guide end users to plan + * future activities. For example, a + * health mobile application can notify users that today is good weather for + * running or for other outdoors + * activities like for playing golf, and retail stores can optimize their + * digital marketing campaigns based on + * predicted index values. The service returns in daily indices values for + * current and next 5, 10 and 15 days * starting from current day. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated + * string composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. + * Should be one of supported IETF language + * tags, case-insensitive. When data in specified language + * is not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. - * @param duration Specifies for how many days the daily indices are returned. By default, the indices data for the - * current day will be returned. When requesting future indices data, the current day is included in the - * response as day 1. Available values are * `1` - Return daily index data for the current day. Default value. * - * `5` - Return 5 days of daily index data starting from the current day. * `10` - Return 10 days of daily index - * data starting from the current day. * `15` - Return 15 days of daily index data starting from the current + * @param duration Specifies for how many days the daily indices are + * returned. By default, the indices data for the + * current day will be returned. When requesting future + * indices data, the current day is included in the + * response as day 1. Available values are * `1` - Return + * daily index data for the current day. Default value. * + * `5` - Return 5 days of daily index data starting from the + * current day. * `10` - Return 10 days of daily index + * data starting from the current day. * `15` - Return 15 + * days of daily index data starting from the current * day. - * @param indexId Numeric index identifier that can be used for restricting returned results to the corresponding - * index type. Cannot be paired with `indexGroupId`. Please refer to [Weather Service - * Concepts](https://aka.ms/AzureMapsWeatherConcepts) for details and to see the supported indices. - * @param indexGroupId Numeric index group identifier that can be used for restricting returned results to the - * corresponding subset of indices (index group). Cannot be paired with `indexId`. Please refer to [Weather - * Service Concepts](https://aka.ms/AzureMapsWeatherConcepts) for details and to see the supported index groups. + * @param indexId Numeric index identifier that can be used for restricting + * returned results to the corresponding + * index type. Cannot be paired with `indexGroupId`. Please + * refer to [Weather Service + * Concepts](https://aka.ms/AzureMapsWeatherConcepts) for + * details and to see the supported indices. + * @param indexGroupId Numeric index group identifier that can be used for + * restricting returned results to the + * corresponding subset of indices (index group). Cannot be + * paired with `indexId`. Please refer to [Weather + * Service + * Concepts](https://aka.ms/AzureMapsWeatherConcepts) for + * details and to see the supported index groups. * @param context The context to associate with this operation. * @return this object is returned from a successful Get Daily Indices call. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -836,15 +1214,19 @@ public Response getDailyIndicesWithResponse(GeoPosition posi * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get all government-issued active tropical storms. Information about the tropical storms includes, government + *

        + * Get all government-issued active tropical storms. Information about the + * tropical storms includes, government * ID, basin ID, year of origin, name and if it is subtropical. * * @return all government-issued active storms. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -861,16 +1243,20 @@ public ActiveStormResult getTropicalStormActive() { * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get all government-issued active tropical storms. Information about the tropical storms includes, government + *

        + * Get all government-issued active tropical storms. Information about the + * tropical storms includes, government * ID, basin ID, year of origin, name and if it is subtropical. * * @param context The context to associate with this operation. * @return all government-issued active storms. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -886,15 +1272,19 @@ public Response getTropicalStormActiveWithResponse(Context co * ActiveStormResult result = client.getTropicalStormActive(); * if (result.getActiveStorms().size() > 0) { * ActiveStorm storm = result.getActiveStorms().get(0); - * client.searchTropicalStorm(storm.getYear(), storm.getBasinId(), storm.getGovId()); + * client.searchTropicalStorm(storm.getYear(), storm.getBasinId(), storm.getGovernmentId()); * } * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Search government-issued tropical storms by year, basin ID, and government ID. Information about the tropical - * storms includes, government ID, basin ID, status, year, name and if it is subtropical. + *

        + * Search government-issued tropical storms by year, basin ID, and government + * ID. Information about the tropical + * storms includes, government ID, basin ID, status, year, name and if it is + * subtropical. * * @param year Year of the cyclone(s). * @param basinId Basin identifier. @@ -902,7 +1292,8 @@ public Response getTropicalStormActiveWithResponse(Context co * @return search government-issued storms. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -918,15 +1309,19 @@ public StormSearchResult searchTropicalStorm(Integer year, BasinId basinId, Inte * ActiveStormResult result = client.getTropicalStormActive(); * if (result.getActiveStorms().size() > 0) { * ActiveStorm storm = result.getActiveStorms().get(0); - * client.searchTropicalStorm(storm.getYear(), storm.getBasinId(), storm.getGovId()); + * client.searchTropicalStorm(storm.getYear(), storm.getBasinId(), storm.getGovernmentId()); * } * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Search government-issued tropical storms by year, basin ID, and government ID. Information about the tropical - * storms includes, government ID, basin ID, status, year, name and if it is subtropical. + *

        + * Search government-issued tropical storms by year, basin ID, and government + * ID. Information about the tropical + * storms includes, government ID, basin ID, status, year, name and if it is + * subtropical. * * @param year Year of the cyclone(s). * @param basinId Basin identifier. @@ -935,7 +1330,8 @@ public StormSearchResult searchTropicalStorm(Integer year, BasinId basinId, Inte * @return search government-issued storms. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -953,23 +1349,28 @@ public Response searchTropicalStormWithResponse(Integer year, * if (result.getActiveStorms().size() > 0) { * ActiveStorm storm = result.getActiveStorms().get(0); * TropicalStormForecastOptions forecastOptions = new TropicalStormForecastOptions(storm.getYear(), - * storm.getBasinId(), storm.getGovId()) - * .setIncludeWindowGeometry(true); + * storm.getBasinId(), storm.getGovernmentId()) + * .setIncludeWindowGeometry(true); * client.getTropicalStormForecast(forecastOptions); * } * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get individual government-issued tropical storm forecasts. Information about the forecasted tropical storms - * includes, location, status, date the forecast was created, window, wind speed and wind radii. + *

        + * Get individual government-issued tropical storm forecasts. Information about + * the forecasted tropical storms + * includes, location, status, date the forecast was created, window, wind speed + * and wind radii. * * @param options TropicalStormForecastOptions * @return the list of Government-issued forecasts. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -986,24 +1387,29 @@ public StormForecastResult getTropicalStormForecast(TropicalStormForecastOptions * if (result.getActiveStorms().size() > 0) { * ActiveStorm storm = result.getActiveStorms().get(0); * TropicalStormForecastOptions forecastOptions = new TropicalStormForecastOptions(storm.getYear(), - * storm.getBasinId(), storm.getGovId()) - * .setIncludeWindowGeometry(true); + * storm.getBasinId(), storm.getGovernmentId()) + * .setIncludeWindowGeometry(true); * client.getTropicalStormForecast(forecastOptions); * } * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get individual government-issued tropical storm forecasts. Information about the forecasted tropical storms - * includes, location, status, date the forecast was created, window, wind speed and wind radii. + *

        + * Get individual government-issued tropical storm forecasts. Information about + * the forecasted tropical storms + * includes, location, status, date the forecast was created, window, wind speed + * and wind radii. * * @param options TropicalStormForecastOptions * @param context The context to associate with this operation. * @return the list of Government-issued forecasts. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -1021,22 +1427,26 @@ public Response getTropicalStormForecastWithResponse(Tropic * if (result.getActiveStorms().size() > 0) { * ActiveStorm storm = result.getActiveStorms().get(0); * TropicalStormLocationOptions locationOptions = new TropicalStormLocationOptions(storm.getYear(), - * storm.getBasinId(), storm.getGovId()); + * storm.getBasinId(), storm.getGovernmentId()); * client.getTropicalStormLocations(locationOptions); * } * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get location of individual government-issued tropical storms. Information about the tropical storms includes, + *

        + * Get location of individual government-issued tropical storms. Information + * about the tropical storms includes, * location coordinates, geometry, basin ID, date, wind details and wind radii. * * @param options TropicalStormLocationOptions * @return locations for an individual government-issued storm. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -1053,15 +1463,18 @@ public StormLocationsResult getTropicalStormLocations(TropicalStormLocationOptio * if (result.getActiveStorms().size() > 0) { * ActiveStorm storm = result.getActiveStorms().get(0); * TropicalStormLocationOptions locationOptions = new TropicalStormLocationOptions(storm.getYear(), - * storm.getBasinId(), storm.getGovId()); + * storm.getBasinId(), storm.getGovernmentId()); * client.getTropicalStormLocations(locationOptions); * } * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get location of individual government-issued tropical storms. Information about the tropical storms includes, + *

        + * Get location of individual government-issued tropical storms. Information + * about the tropical storms includes, * location coordinates, geometry, basin ID, date, wind details and wind radii. * * @param options TropicalStormLocationOptions @@ -1069,7 +1482,8 @@ public StormLocationsResult getTropicalStormLocations(TropicalStormLocationOptio * @return locations for an individual government-issued storm. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -1084,29 +1498,44 @@ public Response getTropicalStormLocationsWithResponse(Trop * *

              * client.getCurrentAirQuality(
        -     *     new GeoPosition(-122.138874, 47.632346), "es", false);
        +     *         new GeoPosition(-122.138874, 47.632346), "es", false);
              * 
        * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get detailed information about the concentration of pollutants and overall status for current air quality. - * Information includes, pollution levels, air quality index values, the dominant pollutant, and a brief statement + *

        + * Get detailed information about the concentration of pollutants and overall + * status for current air quality. + * Information includes, pollution levels, air quality index values, the + * dominant pollutant, and a brief statement * summarizing risk level and suggested precautions. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma + * separated string composed by longitude + * followed by * latitude e.g. "-122.125679,47.641268". - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be + * returned. Should be one of supported IETF + * language + * tags, case-insensitive. When data in specified + * language is not available for a specific + * field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. - * @param includePollutantDetails Boolean value that returns detailed information about each pollutant. By default + * @param includePollutantDetails Boolean value that returns detailed + * information about each pollutant. By default * is True. * @return this object is returned from a successful Get Air Quality call. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -1121,30 +1550,45 @@ public AirQualityResult getCurrentAirQuality(GeoPosition position, String langua * *

              * client.getCurrentAirQuality(
        -     *     new GeoPosition(-122.138874, 47.632346), "es", false);
        +     *         new GeoPosition(-122.138874, 47.632346), "es", false);
              * 
        * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get detailed information about the concentration of pollutants and overall status for current air quality. - * Information includes, pollution levels, air quality index values, the dominant pollutant, and a brief statement + *

        + * Get detailed information about the concentration of pollutants and overall + * status for current air quality. + * Information includes, pollution levels, air quality index values, the + * dominant pollutant, and a brief statement * summarizing risk level and suggested precautions. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma + * separated string composed by longitude + * followed by * latitude e.g. "-122.125679,47.641268". - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be + * returned. Should be one of supported IETF + * language + * tags, case-insensitive. When data in specified + * language is not available for a specific + * field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. - * @param includePollutantDetails Boolean value that returns detailed information about each pollutant. By default + * @param includePollutantDetails Boolean value that returns detailed + * information about each pollutant. By default * is True. * @param context The context to associate with this operation. * @return this object is returned from a successful Get Air Quality call. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -1157,161 +1601,239 @@ public Response getCurrentAirQualityWithResponse(GeoPosition p /** * **Get Air Quality Daily Forecasts** * - * + * + * *

        -     * client.getAirQualityDailyForecasts(
        -     *     new GeoPosition(-122.138874, 47.632346), "en", DailyDuration.TWO_DAYS);
        +     * client.getDailyAirQualityForecast(
        +     * new GeoPosition(-122.138874, 47.632346), "en", DailyDuration.TWO_DAYS);
              * 
        + * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get detailed information about the concentration of pollutants and overall status of forecasted daily air - * quality. The service can provide forecasted daily air quality information for the upcoming 1 to 7 days. - * Information includes, pollution levels, air quality index values, the dominant pollutant, and a brief statement + *

        + * Get detailed information about the concentration of pollutants and overall + * status of forecasted daily air + * quality. The service can provide forecasted daily air quality information for + * the upcoming 1 to 7 days. + * Information includes, pollution levels, air quality index values, the + * dominant pollutant, and a brief statement * summarizing risk level and suggested precautions. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. - * @param duration Specifies for how many days from now we would like to know about the air quality. Available + * @param duration Specifies for how many days from now we would like to know + * about the air quality. Available * values are 1, 2, 3, 4, 5, 6, and 7. Default value is 1. - * @return this object is returned from a successful Get Daily Air Quality Forecast call. + * @return this object is returned from a successful Get Daily Air Quality + * Forecast call. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public DailyAirQualityForecastResult getAirQualityDailyForecasts(GeoPosition position, String language, + public DailyAirQualityForecastResult getDailyAirQualityForecast(GeoPosition position, String language, DailyDuration duration) { - return this.asyncClient.getAirQualityDailyForecasts(position, language, duration).block(); + return this.asyncClient.getDailyAirQualityForecast(position, language, duration).block(); } /** * **Get Air Quality Daily Forecasts** * - * + * + * *

        -     * client.getAirQualityDailyForecasts(
        -     *     new GeoPosition(-122.138874, 47.632346), "en", DailyDuration.TWO_DAYS);
        +     * client.getDailyAirQualityForecast(
        +     * new GeoPosition(-122.138874, 47.632346), "en", DailyDuration.TWO_DAYS);
              * 
        + * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get detailed information about the concentration of pollutants and overall status of forecasted daily air - * quality. The service can provide forecasted daily air quality information for the upcoming 1 to 7 days. - * Information includes, pollution levels, air quality index values, the dominant pollutant, and a brief statement + *

        + * Get detailed information about the concentration of pollutants and overall + * status of forecasted daily air + * quality. The service can provide forecasted daily air quality information for + * the upcoming 1 to 7 days. + * Information includes, pollution levels, air quality index values, the + * dominant pollutant, and a brief statement * summarizing risk level and suggested precautions. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be returned. Should + * be one of supported IETF language + * tags, case-insensitive. When data in specified language is + * not available for a specific field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. - * @param duration Specifies for how many days from now we would like to know about the air quality. Available + * @param duration Specifies for how many days from now we would like to know + * about the air quality. Available * values are 1, 2, 3, 4, 5, 6, and 7. Default value is 1. * @param context The context to associate with this operation. - * @return this object is returned from a successful Get Daily Air Quality Forecast call. + * @return this object is returned from a successful Get Daily Air Quality + * Forecast call. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Response getAirQualityDailyForecastsWithResponse(GeoPosition position, + public Response getDailyAirQualityForecastWithResponse(GeoPosition position, String language, DailyDuration duration, Context context) { - return this.asyncClient.getAirQualityDailyForecastsWithResponse(position, language, duration, context).block(); + return this.asyncClient.getDailyAirQualityForecastWithResponse(position, language, duration, context).block(); } /** * **Get Air Quality Hourly Forecasts** * - * + * + * *

        -     * client.getAirQualityHourlyForecasts(
        -     *     new GeoPosition(-122.138874, 47.632346), "fr", HourlyDuration.ONE_HOUR, false);
        +     * client.getHourlyAirQualityForecast(
        +     * new GeoPosition(-122.138874, 47.632346), "fr", HourlyDuration.ONE_HOUR, false);
              * 
        - * - * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get detailed information about the concentration of pollutants and overall status for forecasted upcoming - * hourly air quality. The service can provide forecasted hourly air quality information for the upcoming time spans - * of 1, 12, 24, 48, 72, and 96 hours. Information includes, pollution levels, air quality index values, the - * dominant pollutant, and a brief statement summarizing risk level and suggested precautions. + * * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * Get detailed information about the concentration of pollutants and overall + * status for forecasted upcoming + * hourly air quality. The service can provide forecasted hourly air quality + * information for the upcoming time spans + * of 1, 12, 24, 48, 72, and 96 hours. Information includes, pollution levels, + * air quality index values, the + * dominant pollutant, and a brief statement summarizing risk level and + * suggested precautions. + * + * @param position The applicable query specified as a comma + * separated string composed by longitude + * followed by * latitude e.g. "-122.125679,47.641268". - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be + * returned. Should be one of supported IETF + * language + * tags, case-insensitive. When data in specified + * language is not available for a specific + * field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. - * @param duration Specifies for how many hours from now we would like to know about the air quality. Available - * values are 1, 12, 24, 48, 72, 96. Default value is 1 hour. - * @param includePollutantDetails Boolean value that returns detailed information about each pollutant. By default + * @param duration Specifies for how many hours from now we would + * like to know about the air quality. Available + * values are 1, 12, 24, 48, 72, 96. Default + * value is 1 hour. + * @param includePollutantDetails Boolean value that returns detailed + * information about each pollutant. By default * is True. * @return this object is returned from a successful Get Air Quality call. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public AirQualityResult getAirQualityHourlyForecasts(GeoPosition position, String language, HourlyDuration duration, + public AirQualityResult getHourlyAirQualityForecast(GeoPosition position, String language, HourlyDuration duration, Boolean includePollutantDetails) { - return this.asyncClient.getAirQualityHourlyForecasts(position, language, duration, includePollutantDetails) + return this.asyncClient.getHourlyAirQualityForecast(position, language, duration, includePollutantDetails) .block(); } /** * **Get Air Quality Hourly Forecasts** * - * + * + * *

        -     * client.getAirQualityHourlyForecasts(
        -     *     new GeoPosition(-122.138874, 47.632346), "fr", HourlyDuration.ONE_HOUR, false);
        +     * client.getHourlyAirQualityForecast(
        +     * new GeoPosition(-122.138874, 47.632346), "fr", HourlyDuration.ONE_HOUR, false);
              * 
        - * - * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get detailed information about the concentration of pollutants and overall status for forecasted upcoming - * hourly air quality. The service can provide forecasted hourly air quality information for the upcoming time spans - * of 1, 12, 24, 48, 72, and 96 hours. Information includes, pollution levels, air quality index values, the - * dominant pollutant, and a brief statement summarizing risk level and suggested precautions. + * * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * Get detailed information about the concentration of pollutants and overall + * status for forecasted upcoming + * hourly air quality. The service can provide forecasted hourly air quality + * information for the upcoming time spans + * of 1, 12, 24, 48, 72, and 96 hours. Information includes, pollution levels, + * air quality index values, the + * dominant pollutant, and a brief statement summarizing risk level and + * suggested precautions. + * + * @param position The applicable query specified as a comma + * separated string composed by longitude + * followed by * latitude e.g. "-122.125679,47.641268". - * @param language Language in which search results should be returned. Should be one of supported IETF language - * tags, case-insensitive. When data in specified language is not available for a specific field, default + * @param language Language in which search results should be + * returned. Should be one of supported IETF + * language + * tags, case-insensitive. When data in specified + * language is not available for a specific + * field, default * language is used. - *

        Please refer to [Supported Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) for + *

        + * Please refer to [Supported + * Languages](https://docs.microsoft.com/azure/azure-maps/supported-languages) + * for * details. - * @param duration Specifies for how many hours from now we would like to know about the air quality. Available - * values are 1, 12, 24, 48, 72, 96. Default value is 1 hour. - * @param includePollutantDetails Boolean value that returns detailed information about each pollutant. By default + * @param duration Specifies for how many hours from now we would + * like to know about the air quality. Available + * values are 1, 12, 24, 48, 72, 96. Default + * value is 1 hour. + * @param includePollutantDetails Boolean value that returns detailed + * information about each pollutant. By default * is True. * @param context The context to associate with this operation. * @return this object is returned from a successful Get Air Quality call. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Response getAirQualityHourlyForecastsWithResponse(GeoPosition position, String language, + public Response getHourlyAirQualityForecastWithResponse(GeoPosition position, String language, HourlyDuration duration, Boolean includePollutantDetails, Context context) { return this.asyncClient - .getAirQualityHourlyForecastsWithResponse(position, language, duration, includePollutantDetails, context) + .getHourlyAirQualityForecastWithResponse(position, language, duration, includePollutantDetails, context) .block(); } @@ -1326,26 +1848,39 @@ public Response getAirQualityHourlyForecastsWithResponse(GeoPo * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        Get Daily Historical Actuals service returns climatology data such as past daily actual observed temperatures, - * precipitation, snowfall, snow depth and cooling/heating degree day information, for the day at a given coordinate - * location. The data is requested for a specified date range, up to 31 days in a single API request. Generally, - * historical data may be available as far back as the last 5 to 40+ years, depending on the location. + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * Get Daily Historical Actuals service returns climatology data such as past + * daily actual observed temperatures, + * precipitation, snowfall, snow depth and cooling/heating degree day + * information, for the day at a given coordinate + * location. The data is requested for a specified date range, up to 31 days in + * a single API request. Generally, + * historical data may be available as far back as the last 5 to 40+ years, + * depending on the location. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The date range supported is 1 to 31 - * calendar days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The + * date range supported is 1 to 31 + * calendar days, so be sure to specify a startDate and endDate + * that does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The date range supported is 1 to 31 calendar - * days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The + * date range supported is 1 to 31 calendar + * days, so be sure to specify a startDate and endDate that + * does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -1365,27 +1900,40 @@ public DailyHistoricalActualsResult getDailyHistoricalActuals(GeoPosition positi * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        Get Daily Historical Actuals service returns climatology data such as past daily actual observed temperatures, - * precipitation, snowfall, snow depth and cooling/heating degree day information, for the day at a given coordinate - * location. The data is requested for a specified date range, up to 31 days in a single API request. Generally, - * historical data may be available as far back as the last 5 to 40+ years, depending on the location. + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * Get Daily Historical Actuals service returns climatology data such as past + * daily actual observed temperatures, + * precipitation, snowfall, snow depth and cooling/heating degree day + * information, for the day at a given coordinate + * location. The data is requested for a specified date range, up to 31 days in + * a single API request. Generally, + * historical data may be available as far back as the last 5 to 40+ years, + * depending on the location. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The date range supported is 1 to 31 - * calendar days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The + * date range supported is 1 to 31 + * calendar days, so be sure to specify a startDate and endDate + * that does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The date range supported is 1 to 31 calendar - * days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The + * date range supported is 1 to 31 calendar + * days, so be sure to specify a startDate and endDate that + * does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. * @param context The context to associate with this operation. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -1406,25 +1954,37 @@ public Response getDailyHistoricalActualsWithRespo * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get Daily Historical Records service returns climatology data such as past daily record temperatures, - * precipitation and snowfall at a given coordinate location. Availability of records data will vary by location. - * Generally, historical data may be available as far back as the last 5 to 40+ years, depending on the location. + *

        + * Get Daily Historical Records service returns climatology data such as past + * daily record temperatures, + * precipitation and snowfall at a given coordinate location. Availability of + * records data will vary by location. + * Generally, historical data may be available as far back as the last 5 to 40+ + * years, depending on the location. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The date range supported is 1 to 31 - * calendar days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The + * date range supported is 1 to 31 + * calendar days, so be sure to specify a startDate and endDate + * that does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The date range supported is 1 to 31 calendar - * days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The + * date range supported is 1 to 31 calendar + * days, so be sure to specify a startDate and endDate that + * does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -1444,26 +2004,38 @@ public DailyHistoricalRecordsResult getDailyHistoricalRecords(GeoPosition positi * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). * - *

        Get Daily Historical Records service returns climatology data such as past daily record temperatures, - * precipitation and snowfall at a given coordinate location. Availability of records data will vary by location. - * Generally, historical data may be available as far back as the last 5 to 40+ years, depending on the location. + *

        + * Get Daily Historical Records service returns climatology data such as past + * daily record temperatures, + * precipitation and snowfall at a given coordinate location. Availability of + * records data will vary by location. + * Generally, historical data may be available as far back as the last 5 to 40+ + * years, depending on the location. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The date range supported is 1 to 31 - * calendar days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The + * date range supported is 1 to 31 + * calendar days, so be sure to specify a startDate and endDate + * that does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The date range supported is 1 to 31 calendar - * days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The + * date range supported is 1 to 31 calendar + * days, so be sure to specify a startDate and endDate that + * does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. * @param context The context to associate with this operation. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -1484,28 +2056,42 @@ public Response getDailyHistoricalRecordsWithRespo * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        Get Daily Historical Normals service returns climatology data such as past daily normal temperatures, - * precipitation and cooling/heating degree day information for the day at a given coordinate location. Normals are - * a 30-year average for temperatures and precipitation for a specific location. As is standard practice in - * climatology, the 30-year average covers years 1991-2020, this data will be used for one decade and then will - * reset in the year 2030. Generally, historical data may be available as far back as the last 5 to 40+ years, + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * Get Daily Historical Normals service returns climatology data such as past + * daily normal temperatures, + * precipitation and cooling/heating degree day information for the day at a + * given coordinate location. Normals are + * a 30-year average for temperatures and precipitation for a specific location. + * As is standard practice in + * climatology, the 30-year average covers years 1991-2020, this data will be + * used for one decade and then will + * reset in the year 2030. Generally, historical data may be available as far + * back as the last 5 to 40+ years, * depending on the location. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The date range supported is 1 to 31 - * calendar days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The + * date range supported is 1 to 31 + * calendar days, so be sure to specify a startDate and endDate + * that does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The date range supported is 1 to 31 calendar - * days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The + * date range supported is 1 to 31 calendar + * days, so be sure to specify a startDate and endDate that + * does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) @@ -1525,29 +2111,43 @@ public DailyHistoricalNormalsResult getDailyHistoricalNormals(GeoPosition positi * * * - *

        **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). - * - *

        Get Daily Historical Normals service returns climatology data such as past daily normal temperatures, - * precipitation and cooling/heating degree day information for the day at a given coordinate location. Normals are - * a 30-year average for temperatures and precipitation for a specific location. As is standard practice in - * climatology, the 30-year average covers years 1991-2020, this data will be used for one decade and then will - * reset in the year 2030. Generally, historical data may be available as far back as the last 5 to 40+ years, + *

        + * **Applies to**: see pricing [tiers](https://aka.ms/AzureMapsPricingTier). + * + *

        + * Get Daily Historical Normals service returns climatology data such as past + * daily normal temperatures, + * precipitation and cooling/heating degree day information for the day at a + * given coordinate location. Normals are + * a 30-year average for temperatures and precipitation for a specific location. + * As is standard practice in + * climatology, the 30-year average covers years 1991-2020, this data will be + * used for one decade and then will + * reset in the year 2030. Generally, historical data may be available as far + * back as the last 5 to 40+ years, * depending on the location. * - * @param position The applicable query specified as a comma separated string composed by longitude followed by + * @param position The applicable query specified as a comma separated string + * composed by longitude followed by * latitude e.g. "-122.125679,47.641268". - * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The date range supported is 1 to 31 - * calendar days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param startDate Start date in ISO 8601 format, for example, 2019-10-27. The + * date range supported is 1 to 31 + * calendar days, so be sure to specify a startDate and endDate + * that does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The date range supported is 1 to 31 calendar - * days, so be sure to specify a startDate and endDate that does not exceed a maximum of 31 days (i.e.: + * @param endDate End date in ISO 8601 format, for example, 2019-10-28. The + * date range supported is 1 to 31 calendar + * days, so be sure to specify a startDate and endDate that + * does not exceed a maximum of 31 days (i.e.: * startDate=2012-01-01&endDate=2012-01-31). - * @param unit Specifies to return the data in either metric units or imperial units. Default value is metric. + * @param unit Specifies to return the data in either metric units or + * imperial units. Default value is metric. * @param context The context to associate with this operation. * @return the response. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @throws RuntimeException all other wrapped checked exceptions if the + * request fails to be sent. */ @Generated @ServiceMethod(returns = ReturnType.SINGLE) diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/WeatherClientBuilder.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/WeatherClientBuilder.java index dfb07c0501be..cbf63c3991e0 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/WeatherClientBuilder.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/WeatherClientBuilder.java @@ -44,7 +44,8 @@ import java.util.Objects; /** - * Builder class used to instantiate both synchronous and asynchronous {@link WeatherClient} clients. + * Builder class used to instantiate both synchronous and asynchronous + * {@link WeatherClient} clients. */ @ServiceClientBuilder(serviceClients = { WeatherClient.class, WeatherAsyncClient.class }) public final class WeatherClientBuilder implements AzureKeyCredentialTrait, @@ -89,10 +90,13 @@ public WeatherClientBuilder() { } /** - * Sets the Azure Maps client id for use with Azure AD Authentication. This client id + * Sets the Azure Maps client id for use with Azure AD Authentication. This + * client id * is the account-based GUID that appears on the Azure Maps Authentication page. *

        - * More details: Azure Maps AD Authentication + * More details: Azure + * Maps AD Authentication * * @param weatherClientId the clientId value. * @return the WeatherClientBuilder. @@ -117,13 +121,18 @@ public WeatherClientBuilder endpoint(String endpoint) { /** * Sets the {@link WeatherServiceVersion} 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. + * 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. + * Targeting a specific service version may also mean that the service will + * return an error for newer APIs. * - * @param version {@link WeatherServiceVersion} of the service to be used when making requests. + * @param version {@link WeatherServiceVersion} of the service to be used when + * making requests. * @return the updated WeatherClientBuilder object */ public WeatherClientBuilder serviceVersion(WeatherServiceVersion version) { @@ -162,7 +171,8 @@ public WeatherClientBuilder httpClient(HttpClient httpClient) { } /** - * Sets The configuration store that is used during construction of the service client. + * Sets The configuration store that is used during construction of the service + * client. * * @param configuration the configuration value. * @return the WeatherClientBuilder. @@ -179,13 +189,15 @@ public WeatherClientBuilder configuration(Configuration configuration) { * @param httpLogOptions the httpLogOptions value. * @return the WeatherClientBuilder. */ + @Override public WeatherClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = Objects.requireNonNull(httpLogOptions, "'logOptions' cannot be null."); return this; } /** - * Sets The retry policy that will attempt to retry failed requests, if applicable. + * Sets The retry policy that will attempt to retry failed requests, if + * applicable. * * @param retryPolicy the retryPolicy value. * @return the WeatherClientBuilder. @@ -196,11 +208,13 @@ public WeatherClientBuilder retryPolicy(RetryPolicy retryPolicy) { } /** - * Sets The client options such as application ID and custom headers to set on a request. + * Sets The client options such as application ID and custom headers to set on a + * request. * * @param clientOptions the clientOptions value. * @return the WeatherClientBuilder. */ + @Override public WeatherClientBuilder clientOptions(ClientOptions clientOptions) { this.clientOptions = Objects.requireNonNull(clientOptions, "'clientOptions' cannot be null."); return this; @@ -212,6 +226,7 @@ public WeatherClientBuilder clientOptions(ClientOptions clientOptions) { * @param customPolicy The custom Http pipeline policy to add. * @return the WeatherClientBuilder. */ + @Override public WeatherClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { pipelinePolicies.add(Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null.")); return this; @@ -220,10 +235,12 @@ public WeatherClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * - * @param tokenCredential {@link TokenCredential} used to authenticate HTTP requests. + * @param tokenCredential {@link TokenCredential} used to authenticate HTTP + * requests. * @return The updated {@link WeatherClientBuilder} object. * @throws NullPointerException If {@code tokenCredential} is null. */ + @Override public WeatherClientBuilder credential(TokenCredential tokenCredential) { this.tokenCredential = Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null."); return this; @@ -232,10 +249,12 @@ public WeatherClientBuilder credential(TokenCredential tokenCredential) { /** * Sets the {@link AzureKeyCredential} used to authenticate HTTP requests. * - * @param keyCredential The {@link AzureKeyCredential} used to authenticate HTTP requests. + * @param keyCredential The {@link AzureKeyCredential} used to authenticate HTTP + * requests. * @return The updated {@link WeatherClientBuilder} object. * @throws NullPointerException If {@code keyCredential} is null. */ + @Override public WeatherClientBuilder credential(AzureKeyCredential keyCredential) { this.keyCredential = Objects.requireNonNull(keyCredential, "'keyCredential' cannot be null."); return this; @@ -244,10 +263,12 @@ public WeatherClientBuilder credential(AzureKeyCredential keyCredential) { /** * Sets the {@link AzureSasCredential} used to authenticate HTTP requests. * - * @param sasCredential The {@link AzureSasCredential} used to authenticate HTTP requests. + * @param sasCredential The {@link AzureSasCredential} used to authenticate HTTP + * requests. * @return The updated {@link WeatherClientBuilder} object. * @throws NullPointerException If {@code sasCredential} is null. */ + @Override public WeatherClientBuilder credential(AzureSasCredential sasCredential) { this.sasCredential = Objects.requireNonNull(sasCredential, "'sasCredential' cannot be null."); return this; @@ -255,6 +276,7 @@ public WeatherClientBuilder credential(AzureSasCredential sasCredential) { /** * Sets retry options + * * @param retryOptions the retry options for the client * @return a reference to this {@code WeatherClientBuilder} */ diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/WeatherClientImplBuilder.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/WeatherClientImplBuilder.java index 2c17f80ddad9..dd09abdfc62b 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/WeatherClientImplBuilder.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/WeatherClientImplBuilder.java @@ -9,7 +9,6 @@ import com.azure.core.client.traits.ConfigurationTrait; import com.azure.core.client.traits.HttpTrait; import com.azure.core.http.HttpClient; -import com.azure.core.http.HttpHeaderName; import com.azure.core.http.HttpHeaders; import com.azure.core.http.HttpPipeline; import com.azure.core.http.HttpPipelineBuilder; @@ -17,8 +16,8 @@ import com.azure.core.http.policy.AddDatePolicy; import com.azure.core.http.policy.AddHeadersFromContextPolicy; import com.azure.core.http.policy.AddHeadersPolicy; -import com.azure.core.http.policy.HttpLoggingPolicy; 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.RequestIdPolicy; @@ -175,7 +174,10 @@ public WeatherClientImplBuilder configuration(Configuration configuration) { } /* - * Specifies which account is intended for usage in conjunction with the Microsoft Entra ID security model. It represents a unique ID for the Azure Maps account and can be retrieved from the Azure Maps management plane Account API. To use Microsoft Entra ID security in Azure Maps see the following [articles](https://aka.ms/amauthdetails) for guidance. + * Specifies which account is intended for usage in conjunction with the Microsoft Entra ID security model. It + * represents a unique ID for the Azure Maps account and can be retrieved from the Azure Maps management plane + * Account API. To use Microsoft Entra ID security in Azure Maps see the following + * [articles](https://aka.ms/amauthdetails) for guidance. */ @Generated private String clientId; @@ -274,6 +276,7 @@ public WeatherClientImplBuilder retryPolicy(RetryPolicy retryPolicy) { */ @Generated public WeatherClientImpl buildClient() { + this.validateClient(); HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); String localHost = (host != null) ? host : "https://atlas.microsoft.com"; String localApiVersion = (apiVersion != null) ? apiVersion : "1.1"; @@ -284,6 +287,12 @@ public WeatherClientImpl buildClient() { return client; } + @Generated + private void validateClient() { + // This method is invoked from 'buildInnerClient'/'buildClient' method. + // Developer can customize this method, to validate that the necessary conditions are met for the new client. + } + @Generated private HttpPipeline createHttpPipeline() { Configuration buildConfiguration @@ -297,10 +306,8 @@ private HttpPipeline createHttpPipeline() { policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersFromContextPolicy()); - HttpHeaders headers = new HttpHeaders(); - localClientOptions.getHeaders() - .forEach(header -> headers.set(HttpHeaderName.fromString(header.getName()), header.getValue())); - if (headers.getSize() > 0) { + HttpHeaders headers = CoreUtils.createHttpHeadersFromClientOptions(localClientOptions); + if (headers != null) { policies.add(new AddHeadersPolicy(headers)); } this.pipelinePolicies.stream() diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/WeathersImpl.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/WeathersImpl.java index 17813358d4da..4e10bc1939fb 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/WeathersImpl.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/WeathersImpl.java @@ -291,12 +291,8 @@ Mono> getDailyHistoricalNormals(@HostPara @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getHourlyForecastWithResponseAsync(JsonFormat format, List coordinates, WeatherDataUnit unit, Integer duration, String language) { - final String accept = "application/json"; - String coordinatesConverted - = JacksonAdapter.createDefaultSerializerAdapter().serializeIterable(coordinates, CollectionFormat.CSV); - return FluxUtil - .withContext(context -> service.getHourlyForecast(this.client.getHost(), this.client.getClientId(), - this.client.getApiVersion(), format, coordinatesConverted, unit, duration, language, accept, context)); + return FluxUtil.withContext( + context -> getHourlyForecastWithResponseAsync(format, coordinates, unit, duration, language, context)); } /** @@ -578,12 +574,8 @@ public HourlyForecastResult getHourlyForecast(JsonFormat format, List co @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getMinuteForecastWithResponseAsync(JsonFormat format, List coordinates, Integer interval, String language) { - final String accept = "application/json"; - String coordinatesConverted - = JacksonAdapter.createDefaultSerializerAdapter().serializeIterable(coordinates, CollectionFormat.CSV); - return FluxUtil - .withContext(context -> service.getMinuteForecast(this.client.getHost(), this.client.getClientId(), - this.client.getApiVersion(), format, coordinatesConverted, interval, language, accept, context)); + return FluxUtil.withContext( + context -> getMinuteForecastWithResponseAsync(format, coordinates, interval, language, context)); } /** @@ -822,12 +814,8 @@ public MinuteForecastResult getMinuteForecast(JsonFormat format, List co @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getQuarterDayForecastWithResponseAsync(JsonFormat format, List coordinates, WeatherDataUnit unit, Integer duration, String language) { - final String accept = "application/json"; - String coordinatesConverted - = JacksonAdapter.createDefaultSerializerAdapter().serializeIterable(coordinates, CollectionFormat.CSV); - return FluxUtil - .withContext(context -> service.getQuarterDayForecast(this.client.getHost(), this.client.getClientId(), - this.client.getApiVersion(), format, coordinatesConverted, unit, duration, language, accept, context)); + return FluxUtil.withContext( + context -> getQuarterDayForecastWithResponseAsync(format, coordinates, unit, duration, language, context)); } /** @@ -1083,12 +1071,8 @@ public QuarterDayForecastResult getQuarterDayForecast(JsonFormat format, List> getCurrentConditionsWithResponseAsync(JsonFormat format, List coordinates, WeatherDataUnit unit, String details, Integer duration, String language) { - final String accept = "application/json"; - String coordinatesConverted - = JacksonAdapter.createDefaultSerializerAdapter().serializeIterable(coordinates, CollectionFormat.CSV); - return FluxUtil.withContext(context -> service.getCurrentConditions(this.client.getHost(), - this.client.getClientId(), this.client.getApiVersion(), format, coordinatesConverted, unit, details, - duration, language, accept, context)); + return FluxUtil.withContext(context -> getCurrentConditionsWithResponseAsync(format, coordinates, unit, details, + duration, language, context)); } /** @@ -1376,12 +1360,8 @@ public CurrentConditionsResult getCurrentConditions(JsonFormat format, List> getDailyForecastWithResponseAsync(JsonFormat format, List coordinates, WeatherDataUnit unit, Integer duration, String language) { - final String accept = "application/json"; - String coordinatesConverted - = JacksonAdapter.createDefaultSerializerAdapter().serializeIterable(coordinates, CollectionFormat.CSV); - return FluxUtil - .withContext(context -> service.getDailyForecast(this.client.getHost(), this.client.getClientId(), - this.client.getApiVersion(), format, coordinatesConverted, unit, duration, language, accept, context)); + return FluxUtil.withContext( + context -> getDailyForecastWithResponseAsync(format, coordinates, unit, duration, language, context)); } /** @@ -1674,9 +1654,7 @@ public DailyForecastResult getDailyForecast(JsonFormat format, List coor @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getWeatherAlongRouteWithResponseAsync(JsonFormat format, String query, String language) { - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.getWeatherAlongRoute(this.client.getHost(), - this.client.getClientId(), this.client.getApiVersion(), format, query, language, accept, context)); + return FluxUtil.withContext(context -> getWeatherAlongRouteWithResponseAsync(format, query, language, context)); } /** @@ -2016,7 +1994,7 @@ public WeatherAlongRouteResult getWeatherAlongRoute(JsonFormat format, String qu * alert providers. The service can return details such as alert type, category, level and detailed description * about the active severe alerts for the requested location, like hurricanes, thunderstorms, lightning, heat waves * or forest fires. For more information, see [Request severe weather - * alerts](/azure-maps/how-to-request-weather-data#request-severe-weather-alerts). + * alerts](/azure/azure-maps/how-to-request-weather-data#request-severe-weather-alerts). * * @param format Desired format of the response. Only `json` format is supported. * @param coordinates The applicable query specified as a comma separated string composed by latitude followed by @@ -2043,12 +2021,8 @@ public WeatherAlongRouteResult getWeatherAlongRoute(JsonFormat format, String qu @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getSevereWeatherAlertsWithResponseAsync(JsonFormat format, List coordinates, String language, String details) { - final String accept = "application/json"; - String coordinatesConverted - = JacksonAdapter.createDefaultSerializerAdapter().serializeIterable(coordinates, CollectionFormat.CSV); - return FluxUtil - .withContext(context -> service.getSevereWeatherAlerts(this.client.getHost(), this.client.getClientId(), - this.client.getApiVersion(), format, coordinatesConverted, language, details, accept, context)); + return FluxUtil.withContext( + context -> getSevereWeatherAlertsWithResponseAsync(format, coordinates, language, details, context)); } /** @@ -2067,7 +2041,7 @@ public Mono> getSevereWeatherAlertsWithRespo * alert providers. The service can return details such as alert type, category, level and detailed description * about the active severe alerts for the requested location, like hurricanes, thunderstorms, lightning, heat waves * or forest fires. For more information, see [Request severe weather - * alerts](/azure-maps/how-to-request-weather-data#request-severe-weather-alerts). + * alerts](/azure/azure-maps/how-to-request-weather-data#request-severe-weather-alerts). * * @param format Desired format of the response. Only `json` format is supported. * @param coordinates The applicable query specified as a comma separated string composed by latitude followed by @@ -2118,7 +2092,7 @@ public Mono> getSevereWeatherAlertsWithRespo * alert providers. The service can return details such as alert type, category, level and detailed description * about the active severe alerts for the requested location, like hurricanes, thunderstorms, lightning, heat waves * or forest fires. For more information, see [Request severe weather - * alerts](/azure-maps/how-to-request-weather-data#request-severe-weather-alerts). + * alerts](/azure/azure-maps/how-to-request-weather-data#request-severe-weather-alerts). * * @param format Desired format of the response. Only `json` format is supported. * @param coordinates The applicable query specified as a comma separated string composed by latitude followed by @@ -2165,7 +2139,7 @@ public Mono getSevereWeatherAlertsAsync(JsonFormat fo * alert providers. The service can return details such as alert type, category, level and detailed description * about the active severe alerts for the requested location, like hurricanes, thunderstorms, lightning, heat waves * or forest fires. For more information, see [Request severe weather - * alerts](/azure-maps/how-to-request-weather-data#request-severe-weather-alerts). + * alerts](/azure/azure-maps/how-to-request-weather-data#request-severe-weather-alerts). * * @param format Desired format of the response. Only `json` format is supported. * @param coordinates The applicable query specified as a comma separated string composed by latitude followed by @@ -2213,7 +2187,7 @@ public Mono getSevereWeatherAlertsAsync(JsonFormat fo * alert providers. The service can return details such as alert type, category, level and detailed description * about the active severe alerts for the requested location, like hurricanes, thunderstorms, lightning, heat waves * or forest fires. For more information, see [Request severe weather - * alerts](/azure-maps/how-to-request-weather-data#request-severe-weather-alerts). + * alerts](/azure/azure-maps/how-to-request-weather-data#request-severe-weather-alerts). * * @param format Desired format of the response. Only `json` format is supported. * @param coordinates The applicable query specified as a comma separated string composed by latitude followed by @@ -2259,7 +2233,7 @@ public Response getSevereWeatherAlertsWithResponse(Js * alert providers. The service can return details such as alert type, category, level and detailed description * about the active severe alerts for the requested location, like hurricanes, thunderstorms, lightning, heat waves * or forest fires. For more information, see [Request severe weather - * alerts](/azure-maps/how-to-request-weather-data#request-severe-weather-alerts). + * alerts](/azure/azure-maps/how-to-request-weather-data#request-severe-weather-alerts). * * @param format Desired format of the response. Only `json` format is supported. * @param coordinates The applicable query specified as a comma separated string composed by latitude followed by @@ -2336,12 +2310,8 @@ public SevereWeatherAlertsResult getSevereWeatherAlerts(JsonFormat format, List< @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getDailyIndicesWithResponseAsync(JsonFormat format, List coordinates, String language, Integer duration, Integer indexId, Integer indexGroupId) { - final String accept = "application/json"; - String coordinatesConverted - = JacksonAdapter.createDefaultSerializerAdapter().serializeIterable(coordinates, CollectionFormat.CSV); - return FluxUtil.withContext(context -> service.getDailyIndices(this.client.getHost(), this.client.getClientId(), - this.client.getApiVersion(), format, coordinatesConverted, language, duration, indexId, indexGroupId, - accept, context)); + return FluxUtil.withContext(context -> getDailyIndicesWithResponseAsync(format, coordinates, language, duration, + indexId, indexGroupId, context)); } /** @@ -2626,9 +2596,7 @@ public DailyIndicesResult getDailyIndices(JsonFormat format, List coordi */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getTropicalStormActiveWithResponseAsync(JsonFormat format) { - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.getTropicalStormActive(this.client.getHost(), - this.client.getClientId(), this.client.getApiVersion(), format, accept, context)); + return FluxUtil.withContext(context -> getTropicalStormActiveWithResponseAsync(format, context)); } /** @@ -2759,10 +2727,8 @@ public ActiveStormResult getTropicalStormActive(JsonFormat format) { @ServiceMethod(returns = ReturnType.SINGLE) public Mono> searchTropicalStormWithResponseAsync(JsonFormat format, int year, BasinId basinId, Integer governmentStormId) { - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.searchTropicalStorm(this.client.getHost(), this.client.getClientId(), - this.client.getApiVersion(), format, year, basinId, governmentStormId, accept, context)); + return FluxUtil.withContext( + context -> searchTropicalStormWithResponseAsync(format, year, basinId, governmentStormId, context)); } /** @@ -2920,10 +2886,8 @@ public StormSearchResult searchTropicalStorm(JsonFormat format, int year, BasinI public Mono> getTropicalStormForecastWithResponseAsync(JsonFormat format, int year, BasinId basinId, int governmentStormId, WeatherDataUnit unit, Boolean includeDetails, Boolean includeGeometricDetails, Boolean includeWindowGeometry) { - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.getTropicalStormForecast(this.client.getHost(), - this.client.getClientId(), this.client.getApiVersion(), format, year, basinId, governmentStormId, unit, - includeDetails, includeGeometricDetails, includeWindowGeometry, accept, context)); + return FluxUtil.withContext(context -> getTropicalStormForecastWithResponseAsync(format, year, basinId, + governmentStormId, unit, includeDetails, includeGeometricDetails, includeWindowGeometry, context)); } /** @@ -3115,10 +3079,8 @@ public StormForecastResult getTropicalStormForecast(JsonFormat format, int year, public Mono> getTropicalStormLocationsWithResponseAsync(JsonFormat format, int year, BasinId basinId, int governmentStormId, Boolean includeDetails, Boolean includeGeometricDetails, WeatherDataUnit unit, Boolean includeCurrentStorm) { - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.getTropicalStormLocations(this.client.getHost(), - this.client.getClientId(), this.client.getApiVersion(), format, year, basinId, governmentStormId, - includeDetails, includeGeometricDetails, unit, includeCurrentStorm, accept, context)); + return FluxUtil.withContext(context -> getTropicalStormLocationsWithResponseAsync(format, year, basinId, + governmentStormId, includeDetails, includeGeometricDetails, unit, includeCurrentStorm, context)); } /** @@ -3315,12 +3277,8 @@ public StormLocationsResult getTropicalStormLocations(JsonFormat format, int yea @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getCurrentAirQualityWithResponseAsync(JsonFormat format, List coordinates, String language, Boolean includePollutantDetails) { - final String accept = "application/json"; - String coordinatesConverted - = JacksonAdapter.createDefaultSerializerAdapter().serializeIterable(coordinates, CollectionFormat.CSV); - return FluxUtil.withContext(context -> service.getCurrentAirQuality(this.client.getHost(), - this.client.getClientId(), this.client.getApiVersion(), format, language, coordinatesConverted, - includePollutantDetails, accept, context)); + return FluxUtil.withContext(context -> getCurrentAirQualityWithResponseAsync(format, coordinates, language, + includePollutantDetails, context)); } /** @@ -3540,12 +3498,8 @@ public AirQualityResult getCurrentAirQuality(JsonFormat format, List coo @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getAirQualityDailyForecastsWithResponseAsync(JsonFormat format, List coordinates, String language, DailyDuration duration) { - final String accept = "application/json"; - String coordinatesConverted - = JacksonAdapter.createDefaultSerializerAdapter().serializeIterable(coordinates, CollectionFormat.CSV); return FluxUtil.withContext( - context -> service.getAirQualityDailyForecasts(this.client.getHost(), this.client.getClientId(), - this.client.getApiVersion(), format, language, coordinatesConverted, duration, accept, context)); + context -> getAirQualityDailyForecastsWithResponseAsync(format, coordinates, language, duration, context)); } /** @@ -3779,12 +3733,8 @@ public DailyAirQualityForecastResult getAirQualityDailyForecasts(JsonFormat form @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getAirQualityHourlyForecastsWithResponseAsync(JsonFormat format, List coordinates, String language, HourlyDuration duration, Boolean includePollutantDetails) { - final String accept = "application/json"; - String coordinatesConverted - = JacksonAdapter.createDefaultSerializerAdapter().serializeIterable(coordinates, CollectionFormat.CSV); - return FluxUtil.withContext(context -> service.getAirQualityHourlyForecasts(this.client.getHost(), - this.client.getClientId(), this.client.getApiVersion(), format, language, coordinatesConverted, duration, - includePollutantDetails, accept, context)); + return FluxUtil.withContext(context -> getAirQualityHourlyForecastsWithResponseAsync(format, coordinates, + language, duration, includePollutantDetails, context)); } /** @@ -4030,12 +3980,8 @@ public AirQualityResult getAirQualityHourlyForecasts(JsonFormat format, List> getDailyHistoricalActualsWithResponseAsync(JsonFormat format, List coordinates, LocalDate startDate, LocalDate endDate, WeatherDataUnit unit) { - final String accept = "application/json"; - String coordinatesConverted - = JacksonAdapter.createDefaultSerializerAdapter().serializeIterable(coordinates, CollectionFormat.CSV); - return FluxUtil - .withContext(context -> service.getDailyHistoricalActuals(this.client.getHost(), this.client.getClientId(), - this.client.getApiVersion(), format, coordinatesConverted, startDate, endDate, unit, accept, context)); + return FluxUtil.withContext(context -> getDailyHistoricalActualsWithResponseAsync(format, coordinates, + startDate, endDate, unit, context)); } /** @@ -4261,12 +4207,8 @@ public DailyHistoricalActualsResult getDailyHistoricalActuals(JsonFormat format, @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getDailyHistoricalRecordsWithResponseAsync(JsonFormat format, List coordinates, LocalDate startDate, LocalDate endDate, WeatherDataUnit unit) { - final String accept = "application/json"; - String coordinatesConverted - = JacksonAdapter.createDefaultSerializerAdapter().serializeIterable(coordinates, CollectionFormat.CSV); - return FluxUtil - .withContext(context -> service.getDailyHistoricalRecords(this.client.getHost(), this.client.getClientId(), - this.client.getApiVersion(), format, coordinatesConverted, startDate, endDate, unit, accept, context)); + return FluxUtil.withContext(context -> getDailyHistoricalRecordsWithResponseAsync(format, coordinates, + startDate, endDate, unit, context)); } /** @@ -4489,12 +4431,8 @@ public DailyHistoricalRecordsResult getDailyHistoricalRecords(JsonFormat format, @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getDailyHistoricalNormalsWithResponseAsync(JsonFormat format, List coordinates, LocalDate startDate, LocalDate endDate, WeatherDataUnit unit) { - final String accept = "application/json"; - String coordinatesConverted - = JacksonAdapter.createDefaultSerializerAdapter().serializeIterable(coordinates, CollectionFormat.CSV); - return FluxUtil - .withContext(context -> service.getDailyHistoricalNormals(this.client.getHost(), this.client.getClientId(), - this.client.getApiVersion(), format, coordinatesConverted, startDate, endDate, unit, accept, context)); + return FluxUtil.withContext(context -> getDailyHistoricalNormalsWithResponseAsync(format, coordinates, + startDate, endDate, unit, context)); } /** diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonFeature.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonFeature.java index fda086788864..5d7a4a663683 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonFeature.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonFeature.java @@ -17,17 +17,21 @@ @Fluent public final class GeoJsonFeature extends GeoJsonObject { /* - * Specifies the `GeoJSON` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection. + * Specifies the `GeoJSON` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, + * MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection. */ private GeoJsonObjectType type = GeoJsonObjectType.GEO_JSON_FEATURE; /* - * A valid `GeoJSON` geometry object. The type must be one of the seven valid GeoJSON geometry types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon and GeometryCollection. Please refer to [RFC 7946](https://tools.ietf.org/html/rfc7946#section-3.1) for details. + * A valid `GeoJSON` geometry object. The type must be one of the seven valid GeoJSON geometry types - Point, + * MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon and GeometryCollection. Please refer to [RFC + * 7946](https://tools.ietf.org/html/rfc7946#section-3.1) for details. */ private GeoJsonGeometry geometry; /* - * Properties can contain any additional metadata about the `Feature`. Value can be any JSON object or a JSON null value + * Properties can contain any additional metadata about the `Feature`. Value can be any JSON object or a JSON null + * value */ private Object properties; @@ -37,7 +41,8 @@ public final class GeoJsonFeature extends GeoJsonObject { private String id; /* - * The type of the feature. The value depends on the data model the current feature is part of. Some data models may have an empty value. + * The type of the feature. The value depends on the data model the current feature is part of. Some data models may + * have an empty value. */ private String featureType; diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonFeatureCollection.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonFeatureCollection.java index b3f14c1a5fe3..ec4f1fbdb7a0 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonFeatureCollection.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonFeatureCollection.java @@ -18,7 +18,8 @@ @Fluent public final class GeoJsonFeatureCollection extends GeoJsonObject { /* - * Specifies the `GeoJSON` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection. + * Specifies the `GeoJSON` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, + * MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection. */ private GeoJsonObjectType type = GeoJsonObjectType.GEO_JSON_FEATURE_COLLECTION; diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonFeatureData.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonFeatureData.java index 77a50f291fd0..e977acb5723e 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonFeatureData.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonFeatureData.java @@ -17,12 +17,15 @@ @Fluent public class GeoJsonFeatureData implements JsonSerializable { /* - * A valid `GeoJSON` geometry object. The type must be one of the seven valid GeoJSON geometry types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon and GeometryCollection. Please refer to [RFC 7946](https://tools.ietf.org/html/rfc7946#section-3.1) for details. + * A valid `GeoJSON` geometry object. The type must be one of the seven valid GeoJSON geometry types - Point, + * MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon and GeometryCollection. Please refer to [RFC + * 7946](https://tools.ietf.org/html/rfc7946#section-3.1) for details. */ private GeoJsonGeometry geometry; /* - * Properties can contain any additional metadata about the `Feature`. Value can be any JSON object or a JSON null value + * Properties can contain any additional metadata about the `Feature`. Value can be any JSON object or a JSON null + * value */ private Object properties; @@ -32,7 +35,8 @@ public class GeoJsonFeatureData implements JsonSerializable private String id; /* - * The type of the feature. The value depends on the data model the current feature is part of. Some data models may have an empty value. + * The type of the feature. The value depends on the data model the current feature is part of. Some data models may + * have an empty value. */ private String featureType; diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonGeometry.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonGeometry.java index 127da6b1c129..4986eb7403fc 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonGeometry.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonGeometry.java @@ -18,9 +18,10 @@ @Immutable public class GeoJsonGeometry extends GeoJsonObject { /* - * Specifies the `GeoJSON` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection. + * Specifies the `GeoJSON` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, + * MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection. */ - private GeoJsonObjectType type = GeoJsonObjectType.fromString("GeoJsonGeometry"); + private GeoJsonObjectType type; /** * Creates an instance of GeoJsonGeometry class. diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonGeometryCollection.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonGeometryCollection.java index 5333e13d7de8..de3605cfb470 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonGeometryCollection.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonGeometryCollection.java @@ -18,12 +18,14 @@ @Fluent public final class GeoJsonGeometryCollection extends GeoJsonGeometry { /* - * Specifies the `GeoJSON` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection. + * Specifies the `GeoJSON` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, + * MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection. */ private GeoJsonObjectType type = GeoJsonObjectType.GEO_JSON_GEOMETRY_COLLECTION; /* - * Contains a list of valid `GeoJSON` geometry objects. **Note** that coordinates in GeoJSON are in x, y order (longitude, latitude). + * Contains a list of valid `GeoJSON` geometry objects. **Note** that coordinates in GeoJSON are in x, y order + * (longitude, latitude). */ private List geometries; diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonGeometryCollectionData.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonGeometryCollectionData.java index 85051dc59511..49f2022ad9b4 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonGeometryCollectionData.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonGeometryCollectionData.java @@ -18,7 +18,8 @@ @Fluent public class GeoJsonGeometryCollectionData implements JsonSerializable { /* - * Contains a list of valid `GeoJSON` geometry objects. **Note** that coordinates in GeoJSON are in x, y order (longitude, latitude). + * Contains a list of valid `GeoJSON` geometry objects. **Note** that coordinates in GeoJSON are in x, y order + * (longitude, latitude). */ private List geometries; diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonLineString.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonLineString.java index 474aa1ebf8a8..2a16d37cec79 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonLineString.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonLineString.java @@ -18,7 +18,8 @@ @Fluent public final class GeoJsonLineString extends GeoJsonGeometry { /* - * Specifies the `GeoJSON` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection. + * Specifies the `GeoJSON` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, + * MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection. */ private GeoJsonObjectType type = GeoJsonObjectType.GEO_JSON_LINE_STRING; diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonMultiLineString.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonMultiLineString.java index c7cc32ac8ccd..d73fa5172feb 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonMultiLineString.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonMultiLineString.java @@ -18,7 +18,8 @@ @Fluent public final class GeoJsonMultiLineString extends GeoJsonGeometry { /* - * Specifies the `GeoJSON` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection. + * Specifies the `GeoJSON` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, + * MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection. */ private GeoJsonObjectType type = GeoJsonObjectType.GEO_JSON_MULTI_LINE_STRING; diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonMultiPoint.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonMultiPoint.java index 03caaac2479c..99a3c9aa8cf8 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonMultiPoint.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonMultiPoint.java @@ -18,7 +18,8 @@ @Fluent public final class GeoJsonMultiPoint extends GeoJsonGeometry { /* - * Specifies the `GeoJSON` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection. + * Specifies the `GeoJSON` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, + * MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection. */ private GeoJsonObjectType type = GeoJsonObjectType.GEO_JSON_MULTI_POINT; diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonMultiPolygon.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonMultiPolygon.java index 22d1674ea2d2..b1650bea37fc 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonMultiPolygon.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonMultiPolygon.java @@ -18,12 +18,14 @@ @Fluent public final class GeoJsonMultiPolygon extends GeoJsonGeometry { /* - * Specifies the `GeoJSON` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection. + * Specifies the `GeoJSON` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, + * MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection. */ private GeoJsonObjectType type = GeoJsonObjectType.GEO_JSON_MULTI_POLYGON; /* - * Contains a list of valid `GeoJSON Polygon` objects. **Note** that coordinates in GeoJSON are in x, y order (longitude, latitude). + * Contains a list of valid `GeoJSON Polygon` objects. **Note** that coordinates in GeoJSON are in x, y order + * (longitude, latitude). */ private List>>> coordinates; diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonMultiPolygonData.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonMultiPolygonData.java index 817d983a2128..809e80e5009d 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonMultiPolygonData.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonMultiPolygonData.java @@ -18,7 +18,8 @@ @Fluent public class GeoJsonMultiPolygonData implements JsonSerializable { /* - * Contains a list of valid `GeoJSON Polygon` objects. **Note** that coordinates in GeoJSON are in x, y order (longitude, latitude). + * Contains a list of valid `GeoJSON Polygon` objects. **Note** that coordinates in GeoJSON are in x, y order + * (longitude, latitude). */ private List>>> coordinates; diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonObject.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonObject.java index 93b35a43ecdc..9c55ea3371f9 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonObject.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonObject.java @@ -17,7 +17,8 @@ @Immutable public class GeoJsonObject implements JsonSerializable { /* - * Specifies the `GeoJSON` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection. + * Specifies the `GeoJSON` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, + * MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection. */ private GeoJsonObjectType type; @@ -25,7 +26,6 @@ public class GeoJsonObject implements JsonSerializable { * Creates an instance of GeoJsonObject class. */ public GeoJsonObject() { - this.type = GeoJsonObjectType.fromString("GeoJsonObject"); } /** diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonPoint.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonPoint.java index 6e2d850a0059..dec8ba384b39 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonPoint.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonPoint.java @@ -18,12 +18,15 @@ @Fluent public final class GeoJsonPoint extends GeoJsonGeometry { /* - * Specifies the `GeoJSON` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection. + * Specifies the `GeoJSON` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, + * MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection. */ private GeoJsonObjectType type = GeoJsonObjectType.GEO_JSON_POINT; /* - * A `Position` is an array of numbers with two or more elements. The first two elements are _longitude_ and _latitude_, precisely in that order. _Altitude/Elevation_ is an optional third element. Please refer to [RFC 7946](https://tools.ietf.org/html/rfc7946#section-3.1.1) for details. + * A `Position` is an array of numbers with two or more elements. The first two elements are _longitude_ and + * _latitude_, precisely in that order. _Altitude/Elevation_ is an optional third element. Please refer to [RFC + * 7946](https://tools.ietf.org/html/rfc7946#section-3.1.1) for details. */ private List coordinates; diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonPointData.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonPointData.java index ced35b003eb7..8438056ff998 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonPointData.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonPointData.java @@ -18,7 +18,9 @@ @Fluent public class GeoJsonPointData implements JsonSerializable { /* - * A `Position` is an array of numbers with two or more elements. The first two elements are _longitude_ and _latitude_, precisely in that order. _Altitude/Elevation_ is an optional third element. Please refer to [RFC 7946](https://tools.ietf.org/html/rfc7946#section-3.1.1) for details. + * A `Position` is an array of numbers with two or more elements. The first two elements are _longitude_ and + * _latitude_, precisely in that order. _Altitude/Elevation_ is an optional third element. Please refer to [RFC + * 7946](https://tools.ietf.org/html/rfc7946#section-3.1.1) for details. */ private List coordinates; diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonPolygon.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonPolygon.java index 73ddab5ed949..2cb9c57e74fc 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonPolygon.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/implementation/models/GeoJsonPolygon.java @@ -18,7 +18,8 @@ @Fluent public final class GeoJsonPolygon extends GeoJsonGeometry { /* - * Specifies the `GeoJSON` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection. + * Specifies the `GeoJSON` type. Must be one of the nine valid GeoJSON object types - Point, MultiPoint, LineString, + * MultiLineString, Polygon, MultiPolygon, GeometryCollection, Feature and FeatureCollection. */ private GeoJsonObjectType type = GeoJsonObjectType.GEO_JSON_POLYGON; diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/ActiveStorm.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/ActiveStorm.java index 6558ae570355..48544c79e2b3 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/ActiveStorm.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/ActiveStorm.java @@ -79,15 +79,6 @@ public String getName() { return this.name; } - /** - * Get the isActive property: True if the depression has been updated recently. - * - * @return the isActive value. - */ - public Boolean isActive() { - return this.isActive; - } - /** * Get the isSubtropical property: True when the depression is classified as a subtropical cyclone. * @@ -102,7 +93,7 @@ public Boolean isSubtropical() { * * @return the govId value. */ - public Integer getGovId() { + public Integer getGovernmentId() { return this.govId; } diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/ActiveStormResult.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/ActiveStormResult.java index 4b0a30b54736..895b010cca21 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/ActiveStormResult.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/ActiveStormResult.java @@ -42,16 +42,6 @@ public List getActiveStorms() { return this.activeStorms; } - /** - * Get the nextLink property: The is the link to the next page of the features returned. If it's the last page, no - * this field. - * - * @return the nextLink value. - */ - public String getNextLink() { - return this.nextLink; - } - /** * {@inheritDoc} */ diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/AirAndPollen.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/AirAndPollen.java index 048b9a8e8f76..c725f5185577 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/AirAndPollen.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/AirAndPollen.java @@ -22,7 +22,8 @@ public final class AirAndPollen implements JsonSerializable { private String description; /* - * Value of the given type above. Values associated with mold, grass, weed and tree are in units of parts per cubic meter. Both air quality and UV are indices, so they are unitless. + * Value of the given type above. Values associated with mold, grass, weed and tree are in units of parts per cubic + * meter. Both air quality and UV are indices, so they are unitless. */ private Integer value; @@ -32,7 +33,8 @@ public final class AirAndPollen implements JsonSerializable { private String category; /* - * Value associated with the air quality or pollution category. These values range from 1 to 6. 1 implying good conditions, 6 implying hazardous conditions. + * Value associated with the air quality or pollution category. These values range from 1 to 6. 1 implying good + * conditions, 6 implying hazardous conditions. */ private Integer categoryValue; diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/AirQuality.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/AirQuality.java index 6b27eb393473..189887b8f0ed 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/AirQuality.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/AirQuality.java @@ -4,6 +4,7 @@ package com.azure.maps.weather.models; import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -25,12 +26,14 @@ public final class AirQuality implements JsonSerializable { private OffsetDateTime timestamp; /* - * Air quality rating on a scale set by local regulating bodies. Scales can vary widely based on location. See [Wikipedia](https://en.wikipedia.org/wiki/Air_quality_index) for more information. + * Air quality rating on a scale set by local regulating bodies. Scales can vary widely based on location. See + * [Wikipedia](https://en.wikipedia.org/wiki/Air_quality_index) for more information. */ private Float index; /* - * Internationally normalized air quality rating on a scale from 0 to 300 and up, with higher numbers representing worse air quality. + * Internationally normalized air quality rating on a scale from 0 to 300 and up, with higher numbers representing + * worse air quality. */ private Float globalIndex; @@ -175,8 +178,8 @@ public static AirQuality fromJson(JsonReader jsonReader) throws IOException { String fieldName = reader.getFieldName(); reader.nextToken(); if ("dateTime".equals(fieldName)) { - deserializedAirQuality.timestamp - = reader.getNullable(nonNullReader -> OffsetDateTime.parse(nonNullReader.getString())); + deserializedAirQuality.timestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); } else if ("index".equals(fieldName)) { deserializedAirQuality.index = reader.getNullable(JsonReader::getFloat); } else if ("globalIndex".equals(fieldName)) { diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/AirQualityResult.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/AirQualityResult.java index f4c18486057d..81e2a724099c 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/AirQualityResult.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/AirQualityResult.java @@ -42,16 +42,6 @@ public List getAirQualityResults() { return this.airQualityResults; } - /** - * Get the nextLink property: The is the link to the next page of the features returned. If it's the last page, no - * this field. - * - * @return the nextLink value. - */ - public String getNextLink() { - return this.nextLink; - } - /** * {@inheritDoc} */ diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/AlertDetails.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/AlertDetails.java index e6dba6a248a4..33b5c0c078cc 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/AlertDetails.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/AlertDetails.java @@ -4,6 +4,7 @@ package com.azure.maps.weather.models; import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -31,12 +32,16 @@ public final class AlertDetails implements JsonSerializable { private String description; /* - * The start date and time of the alert in ISO 8601 format, for example, 2019-10-27T19:39:57-08:00. If the alert crosses multiple time zones the returned time in the response is the local time to the requested coordinate location. + * The start date and time of the alert in ISO 8601 format, for example, 2019-10-27T19:39:57-08:00. If the alert + * crosses multiple time zones the returned time in the response is the local time to the requested coordinate + * location. */ private OffsetDateTime startTime; /* - * The end date and time of the alert in ISO 8601 format, for example, 2019-10-27T19:39:57-08:00. If the alert crosses multiple time zones the returned time in the response is the local time to the requested coordinate location. + * The end date and time of the alert in ISO 8601 format, for example, 2019-10-27T19:39:57-08:00. If the alert + * crosses multiple time zones the returned time in the response is the local time to the requested coordinate + * location. */ private OffsetDateTime endTime; @@ -46,12 +51,17 @@ public final class AlertDetails implements JsonSerializable { private LatestStatus latestStatus; /* - * Full details associated with the alert. Returned if `details`=True. This field is always returned in the language(s) of choice by the issuing provider and Azure Maps only returns what is created by the provider. Please note, some countries/regions may offer their native language and English. Language parameter won’t apply to this field. + * Full details associated with the alert. Returned if `details`=True. This field is always returned in the + * language(s) of choice by the issuing provider and Azure Maps only returns what is created by the provider. Please + * note, some countries/regions may offer their native language and English. Language parameter won’t apply to this + * field. */ private String details; /* - * Language of the `alertDetails`. This field helps to point out that the language of the `alertDetails` may differ from the requested language parameter. Returned if `details`=True. Language code has been derived from the ISO 639-1 Alpha-2 codes. + * Language of the `alertDetails`. This field helps to point out that the language of the `alertDetails` may differ + * from the requested language parameter. Returned if `details`=True. Language code has been derived from the ISO + * 639-1 Alpha-2 codes. */ private String language; @@ -171,11 +181,11 @@ public static AlertDetails fromJson(JsonReader jsonReader) throws IOException { } else if ("summary".equals(fieldName)) { deserializedAlertDetails.description = reader.getString(); } else if ("startTime".equals(fieldName)) { - deserializedAlertDetails.startTime - = reader.getNullable(nonNullReader -> OffsetDateTime.parse(nonNullReader.getString())); + deserializedAlertDetails.startTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); } else if ("endTime".equals(fieldName)) { - deserializedAlertDetails.endTime - = reader.getNullable(nonNullReader -> OffsetDateTime.parse(nonNullReader.getString())); + deserializedAlertDetails.endTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); } else if ("latestStatus".equals(fieldName)) { deserializedAlertDetails.latestStatus = LatestStatus.fromJson(reader); } else if ("alertDetails".equals(fieldName)) { diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/CurrentConditionDuration.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/CurrentConditionDuration.java new file mode 100644 index 000000000000..d9867b74b2d9 --- /dev/null +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/CurrentConditionDuration.java @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.maps.weather.models; + +import com.azure.core.util.ExpandableEnum; +import com.fasterxml.jackson.annotation.JsonValue; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Defines values for CurrentConditionDuration. + */ +public final class CurrentConditionDuration implements ExpandableEnum { + private static final Map VALUES = new ConcurrentHashMap<>(); + + /** + * The most current weather conditions. + */ + public static final CurrentConditionDuration MOST_RECENT = fromValue(0); + + /** + * Past 6 Hours. + */ + public static final CurrentConditionDuration PAST_SIX_HOURS = fromValue(6); + + /** + * Past 24 Hours. + */ + public static final CurrentConditionDuration PAST_TWENTY_FOUR_HOURS = fromValue(24); + + private final Integer value; + + private CurrentConditionDuration(Integer value) { + this.value = value; + } + + /** + * Creates or finds a CurrentConditionDuration. + * + * @param value a value to look for. + * @return the corresponding CurrentConditionDuration. + */ + public static CurrentConditionDuration fromValue(Integer value) { + return VALUES.computeIfAbsent(value, CurrentConditionDuration::new); + } + + /** + * Gets known CurrentConditionDuration values. + * + * @return known CurrentConditionDuration values. + */ + public static Collection values() { + return new ArrayList<>(VALUES.values()); + } + + /** + * Gets the value of the CurrentConditionDuration instance. + * + * @return the value of the CurrentConditionDuration instance. + */ + @Override + public Integer getValue() { + return this.value; + } + + @Override + @JsonValue + public String toString() { + return Objects.toString(this.value); + } + + @Override + public boolean equals(Object obj) { + return this == obj; + } + + @Override + public int hashCode() { + return Objects.hashCode(this.value); + } +} diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/CurrentConditions.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/CurrentConditions.java index 5c264f34d466..080228d4a671 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/CurrentConditions.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/CurrentConditions.java @@ -4,6 +4,7 @@ package com.azure.maps.weather.models; import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -24,17 +25,19 @@ public final class CurrentConditions implements JsonSerializable OffsetDateTime.parse(nonNullReader.getString())); + deserializedCurrentConditions.dateTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); } else if ("phrase".equals(fieldName)) { deserializedCurrentConditions.description = reader.getString(); } else if ("iconCode".equals(fieldName)) { - deserializedCurrentConditions.iconCode = IconCode.fromInt(reader.getInt()); + deserializedCurrentConditions.iconCode = IconCode.fromValue(reader.getInt()); } else if ("hasPrecipitation".equals(fieldName)) { deserializedCurrentConditions.hasPrecipitation = reader.getNullable(JsonReader::getBoolean); } else if ("isDayTime".equals(fieldName)) { diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyAirQuality.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyAirQuality.java index 99196f45624a..ccc39ecc42c8 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyAirQuality.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyAirQuality.java @@ -4,6 +4,7 @@ package com.azure.maps.weather.models; import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -24,12 +25,14 @@ public final class DailyAirQuality implements JsonSerializable private OffsetDateTime timestamp; /* - * Air quality rating on a scale set by local regulating bodies. Scales can vary widely based on location. See [Wikipedia](https://en.wikipedia.org/wiki/Air_quality_index) for more information. + * Air quality rating on a scale set by local regulating bodies. Scales can vary widely based on location. See + * [Wikipedia](https://en.wikipedia.org/wiki/Air_quality_index) for more information. */ private Float index; /* - * Internationally normalized air quality rating on a scale from 0 to 300 and up, with higher numbers representing worse air quality. + * Internationally normalized air quality rating on a scale from 0 to 300 and up, with higher numbers representing + * worse air quality. */ private Float globalIndex; @@ -159,8 +162,8 @@ public static DailyAirQuality fromJson(JsonReader jsonReader) throws IOException String fieldName = reader.getFieldName(); reader.nextToken(); if ("dateTime".equals(fieldName)) { - deserializedDailyAirQuality.timestamp - = reader.getNullable(nonNullReader -> OffsetDateTime.parse(nonNullReader.getString())); + deserializedDailyAirQuality.timestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); } else if ("index".equals(fieldName)) { deserializedDailyAirQuality.index = reader.getNullable(JsonReader::getFloat); } else if ("globalIndex".equals(fieldName)) { diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyAirQualityForecastResult.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyAirQualityForecastResult.java index 34baa988fefb..d65a68af8bed 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyAirQualityForecastResult.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyAirQualityForecastResult.java @@ -42,16 +42,6 @@ public List getAirQualityResults() { return this.airQualityResults; } - /** - * Get the nextLink property: The is the link to the next page of the features returned. If it's the last page, no - * this field. - * - * @return the nextLink value. - */ - public String getNextLink() { - return this.nextLink; - } - /** * {@inheritDoc} */ diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyDuration.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyDuration.java index 0aeb12a468ce..6d5aad350606 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyDuration.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyDuration.java @@ -4,73 +4,142 @@ package com.azure.maps.weather.models; -import com.azure.core.util.ExpandableStringEnum; +import com.azure.core.util.ExpandableEnum; +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.Collection; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; /** * Defines values for DailyDuration. */ -public final class DailyDuration extends ExpandableStringEnum { +public final class DailyDuration implements ExpandableEnum, JsonSerializable { + private static final Map VALUES = new ConcurrentHashMap<>(); + + private static final Function NEW_INSTANCE = DailyDuration::new; + /** * 1 day. */ - public static final DailyDuration ONE_DAY = fromInt(1); + public static final DailyDuration ONE_DAY = fromValue(1); /** * 2 days. */ - public static final DailyDuration TWO_DAYS = fromInt(2); + public static final DailyDuration TWO_DAYS = fromValue(2); /** * 3 days. */ - public static final DailyDuration THREE_DAYS = fromInt(3); + public static final DailyDuration THREE_DAYS = fromValue(3); /** * 4 days. */ - public static final DailyDuration FOUR_DAYS = fromInt(4); + public static final DailyDuration FOUR_DAYS = fromValue(4); /** * 5 days. */ - public static final DailyDuration FIVE_DAYS = fromInt(5); + public static final DailyDuration FIVE_DAYS = fromValue(5); /** * 6 days. */ - public static final DailyDuration SIX_DAYS = fromInt(6); + public static final DailyDuration SIX_DAYS = fromValue(6); /** * 7 days. */ - public static final DailyDuration SEVEN_DAYS = fromInt(7); + public static final DailyDuration SEVEN_DAYS = fromValue(7); - /** - * Creates a new instance of DailyDuration value. - * - * @deprecated Use the {@link #fromInt(int)} factory method. - */ - @Deprecated - public DailyDuration() { + private final Integer value; + + private DailyDuration(Integer value) { + this.value = value; } /** - * Creates or finds a DailyDuration from its string representation. + * Creates or finds a DailyDuration. * - * @param name a name to look for. + * @param value a value to look for. * @return the corresponding DailyDuration. + * @throws IllegalArgumentException if value is null. */ - public static DailyDuration fromInt(int name) { - return fromString(String.valueOf(name), DailyDuration.class); + public static DailyDuration fromValue(Integer value) { + if (value == null) { + throw new IllegalArgumentException("'value' cannot be null."); + } + return VALUES.computeIfAbsent(value, NEW_INSTANCE); } /** * Gets known DailyDuration values. * - * @return known DailyDuration values. + * @return Known DailyDuration values. */ public static Collection values() { - return values(DailyDuration.class); + return new ArrayList<>(VALUES.values()); + } + + /** + * Gets the value of the DailyDuration instance. + * + * @return the value of the DailyDuration instance. + */ + @Override + public Integer getValue() { + return this.value; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeInt(getValue()); + } + + /** + * Reads an instance of DailyDuration from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of DailyDuration if the JsonReader was pointing to an instance of it, or null if the + * JsonReader was pointing to JSON null. + * @throws IOException If an error occurs while reading the DailyDuration. + * @throws IllegalStateException If unexpected JSON token is found. + */ + public static DailyDuration fromJson(JsonReader jsonReader) throws IOException { + JsonToken nextToken = jsonReader.nextToken(); + if (nextToken == JsonToken.NULL) { + return null; + } + if (nextToken != JsonToken.NUMBER) { + throw new IllegalStateException( + String.format("Unexpected JSON token for %s deserialization: %s", JsonToken.NUMBER, nextToken)); + } + return DailyDuration.fromValue(jsonReader.getInt()); + } + + @Override + public String toString() { + return Objects.toString(this.value); + } + + @Override + public boolean equals(Object obj) { + return this == obj; + } + + @Override + public int hashCode() { + return Objects.hashCode(this.value); } } diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyForecast.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyForecast.java index 26a7b56a0c38..16c369c3f6af 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyForecast.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyForecast.java @@ -4,6 +4,7 @@ package com.azure.maps.weather.models; import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -203,8 +204,8 @@ public static DailyForecast fromJson(JsonReader jsonReader) throws IOException { String fieldName = reader.getFieldName(); reader.nextToken(); if ("date".equals(fieldName)) { - deserializedDailyForecast.dateTime - = reader.getNullable(nonNullReader -> OffsetDateTime.parse(nonNullReader.getString())); + deserializedDailyForecast.dateTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); } else if ("temperature".equals(fieldName)) { deserializedDailyForecast.temperature = WeatherValueRange.fromJson(reader); } else if ("realFeelTemperature".equals(fieldName)) { diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyForecastDetail.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyForecastDetail.java index 6dc7e2b363ed..ef8945a6c268 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyForecastDetail.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyForecastDetail.java @@ -17,7 +17,8 @@ public final class DailyForecastDetail implements JsonSerializable { /* - * Numeric value representing an image that displays the `iconPhrase`. Please refer to [Weather services in Azure Maps](/azure/azure-maps/weather-services-concepts#weather-icons) for details. + * Numeric value representing an image that displays the `iconPhrase`. Please refer to [Weather services in Azure + * Maps](/azure/azure-maps/weather-services-concepts#weather-icons) for details. */ private IconCode iconCode; @@ -32,12 +33,14 @@ public final class DailyForecastDetail implements JsonSerializable { /* - * Summary for the main conditions for the requested time period. Notice that summary can cover only part of the time period. + * Summary for the main conditions for the requested time period. Notice that summary can cover only part of the + * time period. */ private DailyForecastSummary summary; diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyForecastSummary.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyForecastSummary.java index daa738f35a3f..d77d87928254 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyForecastSummary.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyForecastSummary.java @@ -4,6 +4,7 @@ package com.azure.maps.weather.models; import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -20,7 +21,8 @@ public final class DailyForecastSummary implements JsonSerializable { /* - * Date and time that the summary is in effect, displayed in ISO 8601 format, for example, 2019-10-27T19:39:57-08:00. + * Date and time that the summary is in effect, displayed in ISO 8601 format, for example, + * 2019-10-27T19:39:57-08:00. */ private OffsetDateTime startDate; @@ -35,7 +37,7 @@ public final class DailyForecastSummary implements JsonSerializable OffsetDateTime.parse(nonNullReader.getString())); + deserializedDailyForecastSummary.startDate = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); } else if ("endDate".equals(fieldName)) { - deserializedDailyForecastSummary.endDate - = reader.getNullable(nonNullReader -> OffsetDateTime.parse(nonNullReader.getString())); + deserializedDailyForecastSummary.endDate = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); } else if ("severity".equals(fieldName)) { deserializedDailyForecastSummary.severity = reader.getNullable(JsonReader::getInt); } else if ("phrase".equals(fieldName)) { diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyHistoricalActuals.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyHistoricalActuals.java index 7850a3eb5243..3486bcb9f911 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyHistoricalActuals.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyHistoricalActuals.java @@ -4,6 +4,7 @@ package com.azure.maps.weather.models; import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -29,7 +30,9 @@ public final class DailyHistoricalActuals implements JsonSerializable OffsetDateTime.parse(nonNullReader.getString())); + deserializedDailyHistoricalActuals.timestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); } else if ("temperature".equals(fieldName)) { deserializedDailyHistoricalActuals.temperature = WeatherValueMaxMinAvg.fromJson(reader); } else if ("degreeDaySummary".equals(fieldName)) { diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyHistoricalActualsResult.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyHistoricalActualsResult.java index 412a8959d4b1..9d3bbdc87f00 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyHistoricalActualsResult.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyHistoricalActualsResult.java @@ -42,16 +42,6 @@ public List getHistoricalActuals() { return this.historicalActuals; } - /** - * Get the nextLink property: The is the link to the next page of the features returned. If it's the last page, no - * this field. - * - * @return the nextLink value. - */ - public String getNextLink() { - return this.nextLink; - } - /** * {@inheritDoc} */ diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyHistoricalNormals.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyHistoricalNormals.java index 7ef5734227cc..af6d3317851d 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyHistoricalNormals.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyHistoricalNormals.java @@ -4,6 +4,7 @@ package com.azure.maps.weather.models; import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -110,8 +111,8 @@ public static DailyHistoricalNormals fromJson(JsonReader jsonReader) throws IOEx String fieldName = reader.getFieldName(); reader.nextToken(); if ("date".equals(fieldName)) { - deserializedDailyHistoricalNormals.timestamp - = reader.getNullable(nonNullReader -> OffsetDateTime.parse(nonNullReader.getString())); + deserializedDailyHistoricalNormals.timestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); } else if ("temperature".equals(fieldName)) { deserializedDailyHistoricalNormals.temperature = WeatherValueMaxMinAvg.fromJson(reader); } else if ("degreeDaySummary".equals(fieldName)) { diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyHistoricalNormalsResult.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyHistoricalNormalsResult.java index cfa997148a6b..2502f8b2cd97 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyHistoricalNormalsResult.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyHistoricalNormalsResult.java @@ -42,16 +42,6 @@ public List getHistoricalNormals() { return this.historicalNormals; } - /** - * Get the nextLink property: The is the link to the next page of the features returned. If it's the last page, no - * this field. - * - * @return the nextLink value. - */ - public String getNextLink() { - return this.nextLink; - } - /** * {@inheritDoc} */ diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyHistoricalRecords.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyHistoricalRecords.java index b1bee89398b1..36d7c38180d2 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyHistoricalRecords.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyHistoricalRecords.java @@ -4,6 +4,7 @@ package com.azure.maps.weather.models; import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -110,8 +111,8 @@ public static DailyHistoricalRecords fromJson(JsonReader jsonReader) throws IOEx String fieldName = reader.getFieldName(); reader.nextToken(); if ("date".equals(fieldName)) { - deserializedDailyHistoricalRecords.timestamp - = reader.getNullable(nonNullReader -> OffsetDateTime.parse(nonNullReader.getString())); + deserializedDailyHistoricalRecords.timestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); } else if ("temperature".equals(fieldName)) { deserializedDailyHistoricalRecords.temperature = WeatherValueYearMaxMinAvg.fromJson(reader); } else if ("precipitation".equals(fieldName)) { diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyHistoricalRecordsResult.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyHistoricalRecordsResult.java index c4bd8b6edc83..ef24b78b1940 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyHistoricalRecordsResult.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyHistoricalRecordsResult.java @@ -42,16 +42,6 @@ public List getHistoricalRecords() { return this.historicalRecords; } - /** - * Get the nextLink property: The is the link to the next page of the features returned. If it's the last page, no - * this field. - * - * @return the nextLink value. - */ - public String getNextLink() { - return this.nextLink; - } - /** * {@inheritDoc} */ diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyIndex.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyIndex.java index f9a63f7334f6..290b81b7c83f 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyIndex.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DailyIndex.java @@ -4,6 +4,7 @@ package com.azure.maps.weather.models; import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -24,7 +25,9 @@ public final class DailyIndex implements JsonSerializable { private String indexName; /* - * Numeric ID used to identify the specific index. Please refer to [Weather services in Azure Maps](/azure/azure-maps/weather-services-concepts#daily-index-range-sets) for details and to see the supported index IDs. For example, the index ID can support UI visualization scenarios. + * Numeric ID used to identify the specific index. Please refer to [Weather services in Azure + * Maps](/azure/azure-maps/weather-services-concepts#daily-index-range-sets) for details and to see the supported + * index IDs. For example, the index ID can support UI visualization scenarios. */ private Integer indexId; @@ -34,27 +37,36 @@ public final class DailyIndex implements JsonSerializable { private OffsetDateTime dateTime; /* - * Index value. Ranges from 0.0 to 10.0. Please refer to [Weather services in Azure Maps](/azure/azure-maps/weather-services-concepts#daily-index-range-sets) for details and to see the supported ranges. + * Index value. Ranges from 0.0 to 10.0. Please refer to [Weather services in Azure + * Maps](/azure/azure-maps/weather-services-concepts#daily-index-range-sets) for details and to see the supported + * ranges. */ private Float value; /* - * Textual description for `categoryValue` corresponding to the level that the index value falls under, for example "Very Good". + * Textual description for `categoryValue` corresponding to the level that the index value falls under, for example + * "Very Good". */ private String categoryDescription; /* - * Level that the index value falls under, represented by an integer. This value can be 1 through 5 and should be used in combination with the `ascending` flag because it can differ among indices. For example, the following values apply for Mosquito Activity: Low=1, Moderate=2, High=3, Very High=4, and Extreme=5. + * Level that the index value falls under, represented by an integer. This value can be 1 through 5 and should be + * used in combination with the `ascending` flag because it can differ among indices. For example, the following + * values apply for Mosquito Activity: Low=1, Moderate=2, High=3, Very High=4, and Extreme=5. */ private Integer categoryValue; /* - * Describes the direction of the `value` and `categoryValue`. For example, when set to `true`, the poorest index value is 0 and the best index value is 10. When set to `true`, the poorest index value is 10 and the best index value is 0. + * Describes the direction of the `value` and `categoryValue`. For example, when set to `true`, the poorest index + * value is 0 and the best index value is 10. When set to `true`, the poorest index value is 10 and the best index + * value is 0. */ private Boolean isAscending; /* - * A textual explanation that can be used for display purposes to summarize the index value and category. For example, when the index value for Flight Delays is very good, the description will be "Conditions are excellent for flying!". + * A textual explanation that can be used for display purposes to summarize the index value and category. For + * example, when the index value for Flight Delays is very good, the description will be + * "Conditions are excellent for flying!". */ private String description; @@ -186,8 +198,8 @@ public static DailyIndex fromJson(JsonReader jsonReader) throws IOException { } else if ("indexId".equals(fieldName)) { deserializedDailyIndex.indexId = reader.getNullable(JsonReader::getInt); } else if ("dateTime".equals(fieldName)) { - deserializedDailyIndex.dateTime - = reader.getNullable(nonNullReader -> OffsetDateTime.parse(nonNullReader.getString())); + deserializedDailyIndex.dateTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); } else if ("value".equals(fieldName)) { deserializedDailyIndex.value = reader.getNullable(JsonReader::getFloat); } else if ("category".equals(fieldName)) { diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DayQuarter.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DayQuarter.java index a4ccf2de9736..ee5699d9e2b9 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DayQuarter.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/DayQuarter.java @@ -3,60 +3,129 @@ // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.maps.weather.models; -import com.azure.core.util.ExpandableStringEnum; +import com.azure.core.util.ExpandableEnum; +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.Collection; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; /** * Quarter of the day. */ -public final class DayQuarter extends ExpandableStringEnum { +public final class DayQuarter implements ExpandableEnum, JsonSerializable { + + private static final Map VALUES = new ConcurrentHashMap<>(); + + private static final Function NEW_INSTANCE = DayQuarter::new; /** * 7:00 am - 1:00 pm / 7:00- 13:00. */ - public static final DayQuarter FIRST_QUARTER = fromInt(0); + public static final DayQuarter FIRST_QUARTER = fromValue(0); /** * 1:00 pm - 7:00 pm/ 13:00- 19:00. */ - public static final DayQuarter SECOND_QUARTER = fromInt(1); + public static final DayQuarter SECOND_QUARTER = fromValue(1); /** * 7:00 pm - 1:00 am/ 19:00 - 01:00. */ - public static final DayQuarter THIRD_QUARTER = fromInt(2); + public static final DayQuarter THIRD_QUARTER = fromValue(2); /** * 1:00 am - 7:00 am/ 01:00 - 07:00. */ - public static final DayQuarter FORTH_QUARTER = fromInt(3); + public static final DayQuarter FORTH_QUARTER = fromValue(3); - /** - * Creates a new instance of DayQuarter value. - * - * @deprecated Use the {@link #fromInt(int)} factory method. - */ - @Deprecated - public DayQuarter() { + private final Integer value; + + private DayQuarter(Integer value) { + this.value = value; } /** - * Creates or finds a DayQuarter from its string representation. + * Creates or finds a DayQuarter. * - * @param name a name to look for. + * @param value a value to look for. * @return the corresponding DayQuarter. + * @throws IllegalArgumentException if value is null. */ - public static DayQuarter fromInt(int name) { - return fromString(String.valueOf(name), DayQuarter.class); + public static DayQuarter fromValue(Integer value) { + if (value == null) { + throw new IllegalArgumentException("'value' cannot be null."); + } + return VALUES.computeIfAbsent(value, NEW_INSTANCE); } /** * Gets known DayQuarter values. * - * @return known DayQuarter values. + * @return Known DayQuarter values. */ public static Collection values() { - return values(DayQuarter.class); + return new ArrayList<>(VALUES.values()); + } + + /** + * Gets the value of the DayQuarter instance. + * + * @return the value of the DayQuarter instance. + */ + @Override + public Integer getValue() { + return this.value; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeInt(getValue()); + } + + /** + * Reads an instance of DayQuarter from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of DayQuarter if the JsonReader was pointing to an instance of it, or null if the JsonReader + * was pointing to JSON null. + * @throws IOException If an error occurs while reading the DayQuarter. + * @throws IllegalStateException If unexpected JSON token is found. + */ + public static DayQuarter fromJson(JsonReader jsonReader) throws IOException { + JsonToken nextToken = jsonReader.nextToken(); + if (nextToken == JsonToken.NULL) { + return null; + } + if (nextToken != JsonToken.NUMBER) { + throw new IllegalStateException( + String.format("Unexpected JSON token for %s deserialization: %s", JsonToken.NUMBER, nextToken)); + } + return DayQuarter.fromValue(jsonReader.getInt()); + } + + @Override + public String toString() { + return Objects.toString(this.value); + } + + @Override + public boolean equals(Object obj) { + return this == obj; + } + + @Override + public int hashCode() { + return Objects.hashCode(this.value); } int toInt() { diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/ForecastInterval.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/ForecastInterval.java index 8a1aba4df4cf..182af17ec9b3 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/ForecastInterval.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/ForecastInterval.java @@ -4,6 +4,7 @@ package com.azure.maps.weather.models; import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -39,12 +40,14 @@ public final class ForecastInterval implements JsonSerializable OffsetDateTime.parse(nonNullReader.getString())); + deserializedForecastInterval.startTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); } else if ("minute".equals(fieldName)) { deserializedForecastInterval.minute = reader.getNullable(JsonReader::getInt); } else if ("dbz".equals(fieldName)) { @@ -235,7 +240,7 @@ public static ForecastInterval fromJson(JsonReader jsonReader) throws IOExceptio } else if ("precipitationType".equals(fieldName)) { deserializedForecastInterval.precipitationType = PrecipitationType.fromString(reader.getString()); } else if ("iconCode".equals(fieldName)) { - deserializedForecastInterval.iconCode = IconCode.fromInt(reader.getInt()); + deserializedForecastInterval.iconCode = IconCode.fromValue(reader.getInt()); } else if ("cloudCover".equals(fieldName)) { deserializedForecastInterval.cloudCover = reader.getNullable(JsonReader::getInt); } else { diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/HazardDetail.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/HazardDetail.java index 1da83fb1d02a..1b095056a552 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/HazardDetail.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/HazardDetail.java @@ -18,16 +18,19 @@ public final class HazardDetail implements JsonSerializable { /* * A severity/hazard index. - * * `0` - No hazard. - * * `1` - Be informed, be aware. - * * `2` - Pay attention, be prepared. - * * `3` - Take action. - * * `4` - Life threatening, emergency. + * * `0` - No hazard. + * * `1` - Be informed, be aware. + * * `2` - Pay attention, be prepared. + * * `3` - Take action. + * * `4` - Life threatening, emergency. */ private HazardIndex hazardIndex; /* - * A unique identifier (non-displayable) for each type of hazard: LightRain, ModerateRain, HeavyRain, LightMix, ModerateMix, HeavyMix, LightSnow, ModerateSnow, HeavySnow, LightIce, ModerateIce, HeavyIce, Hail, LargeHail, SunGlare, SunGlareHigh, Lightning, SevereLightning, WindModerate, WindHigh, WindExtreme, FloodWarning, FlashFloodWarning, TornadoWarning, TsunamiWarning, SevereThunderstormWarning. + * A unique identifier (non-displayable) for each type of hazard: LightRain, ModerateRain, HeavyRain, LightMix, + * ModerateMix, HeavyMix, LightSnow, ModerateSnow, HeavySnow, LightIce, ModerateIce, HeavyIce, Hail, LargeHail, + * SunGlare, SunGlareHigh, Lightning, SevereLightning, WindModerate, WindHigh, WindExtreme, FloodWarning, + * FlashFloodWarning, TornadoWarning, TsunamiWarning, SevereThunderstormWarning. */ private String hazardCode; @@ -85,7 +88,7 @@ public String getShortDescription() { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeNumberField("hazardIndex", this.hazardIndex == null ? null : this.hazardIndex.toInt()); + jsonWriter.writeNumberField("hazardIndex", this.hazardIndex == null ? null : this.hazardIndex.getValue()); jsonWriter.writeStringField("hazardCode", this.hazardCode); jsonWriter.writeStringField("shortPhrase", this.shortDescription); return jsonWriter.writeEndObject(); @@ -106,7 +109,7 @@ public static HazardDetail fromJson(JsonReader jsonReader) throws IOException { String fieldName = reader.getFieldName(); reader.nextToken(); if ("hazardIndex".equals(fieldName)) { - deserializedHazardDetail.hazardIndex = HazardIndex.fromInt(reader.getInt()); + deserializedHazardDetail.hazardIndex = HazardIndex.fromValue(reader.getInt()); } else if ("hazardCode".equals(fieldName)) { deserializedHazardDetail.hazardCode = reader.getString(); } else if ("shortPhrase".equals(fieldName)) { diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/HazardIndex.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/HazardIndex.java index d5e65a158e79..a69aad2882fb 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/HazardIndex.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/HazardIndex.java @@ -3,8 +3,18 @@ // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.maps.weather.models; -import com.azure.core.util.ExpandableStringEnum; +import com.azure.core.util.ExpandableEnum; +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.Collection; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; /** * A severity/hazard index. @@ -14,59 +24,118 @@ * * `3` - Take action. * * `4` - Life threatening, emergency. */ -public final class HazardIndex extends ExpandableStringEnum { +public final class HazardIndex implements ExpandableEnum, JsonSerializable { + + private static final Map VALUES = new ConcurrentHashMap<>(); + + private static final Function NEW_INSTANCE = HazardIndex::new; /** * No hazard. */ - public static final HazardIndex NO_HAZARD = fromInt(0); + public static final HazardIndex NO_HAZARD = fromValue(0); /** * Be informed. */ - public static final HazardIndex INFORMED = fromInt(1); + public static final HazardIndex INFORMED = fromValue(1); /** * Pay attention. */ - public static final HazardIndex PAY_ATTENTION = fromInt(2); + public static final HazardIndex PAY_ATTENTION = fromValue(2); /** * Take action. */ - public static final HazardIndex TAKE_ACTION = fromInt(3); + public static final HazardIndex TAKE_ACTION = fromValue(3); /** * Emergency. */ - public static final HazardIndex EMERGENCY = fromInt(4); + public static final HazardIndex EMERGENCY = fromValue(4); - /** - * Creates a new instance of HazardIndex value. - * - * @deprecated Use the {@link #fromInt(int)} factory method. - */ - @Deprecated - public HazardIndex() { + private final Integer value; + + private HazardIndex(Integer value) { + this.value = value; } /** - * Creates or finds a HazardIndex from its string representation. + * Creates or finds a HazardIndex. * - * @param name a name to look for. + * @param value a value to look for. * @return the corresponding HazardIndex. + * @throws IllegalArgumentException if value is null. */ - public static HazardIndex fromInt(int name) { - return fromString(String.valueOf(name), HazardIndex.class); + public static HazardIndex fromValue(Integer value) { + if (value == null) { + throw new IllegalArgumentException("'value' cannot be null."); + } + return VALUES.computeIfAbsent(value, NEW_INSTANCE); } /** * Gets known HazardIndex values. * - * @return known HazardIndex values. + * @return Known HazardIndex values. */ public static Collection values() { - return values(HazardIndex.class); + return new ArrayList<>(VALUES.values()); + } + + /** + * Gets the value of the HazardIndex instance. + * + * @return the value of the HazardIndex instance. + */ + @Override + public Integer getValue() { + return this.value; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeInt(getValue()); + } + + /** + * Reads an instance of HazardIndex from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of HazardIndex if the JsonReader was pointing to an instance of it, or null if the JsonReader + * was pointing to JSON null. + * @throws IOException If an error occurs while reading the HazardIndex. + * @throws IllegalStateException If unexpected JSON token is found. + */ + public static HazardIndex fromJson(JsonReader jsonReader) throws IOException { + JsonToken nextToken = jsonReader.nextToken(); + if (nextToken == JsonToken.NULL) { + return null; + } + if (nextToken != JsonToken.NUMBER) { + throw new IllegalStateException( + String.format("Unexpected JSON token for %s deserialization: %s", JsonToken.NUMBER, nextToken)); + } + return HazardIndex.fromValue(jsonReader.getInt()); + } + + @Override + public String toString() { + return Objects.toString(this.value); + } + + @Override + public boolean equals(Object obj) { + return this == obj; + } + + @Override + public int hashCode() { + return Objects.hashCode(this.value); } int toInt() { diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/HourlyDuration.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/HourlyDuration.java index e5fcfee27bce..ca995a0cff70 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/HourlyDuration.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/HourlyDuration.java @@ -4,68 +4,137 @@ package com.azure.maps.weather.models; -import com.azure.core.util.ExpandableStringEnum; +import com.azure.core.util.ExpandableEnum; +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.Collection; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; /** * Defines values for HourlyDuration. */ -public final class HourlyDuration extends ExpandableStringEnum { +public final class HourlyDuration implements ExpandableEnum, JsonSerializable { + private static final Map VALUES = new ConcurrentHashMap<>(); + + private static final Function NEW_INSTANCE = HourlyDuration::new; + /** * 1 Hours. */ - public static final HourlyDuration ONE_HOUR = fromInt(1); + public static final HourlyDuration ONE_HOUR = fromValue(1); /** * 12 Hours. */ - public static final HourlyDuration TWELVE_HOURS = fromInt(12); + public static final HourlyDuration TWELVE_HOURS = fromValue(12); /** * 24 Hours. */ - public static final HourlyDuration TWENTY_FOUR_HOURS = fromInt(24); + public static final HourlyDuration TWENTY_FOUR_HOURS = fromValue(24); /** * 48 Hours. */ - public static final HourlyDuration FORTY_EIGHT_HOURS = fromInt(48); + public static final HourlyDuration FORTY_EIGHT_HOURS = fromValue(48); /** * 72 Hours. */ - public static final HourlyDuration SEVENTY_TWO_HOURS = fromInt(72); + public static final HourlyDuration SEVENTY_TWO_HOURS = fromValue(72); /** * 96 Hours. */ - public static final HourlyDuration NINETY_SIX_HOURS = fromInt(96); + public static final HourlyDuration NINETY_SIX_HOURS = fromValue(96); - /** - * Creates a new instance of HourlyDuration value. - * - * @deprecated Use the {@link #fromInt(int)} factory method. - */ - @Deprecated - public HourlyDuration() { + private final Integer value; + + private HourlyDuration(Integer value) { + this.value = value; } /** - * Creates or finds a HourlyDuration from its string representation. + * Creates or finds a HourlyDuration. * - * @param name a name to look for. + * @param value a value to look for. * @return the corresponding HourlyDuration. + * @throws IllegalArgumentException if value is null. */ - public static HourlyDuration fromInt(int name) { - return fromString(String.valueOf(name), HourlyDuration.class); + public static HourlyDuration fromValue(Integer value) { + if (value == null) { + throw new IllegalArgumentException("'value' cannot be null."); + } + return VALUES.computeIfAbsent(value, NEW_INSTANCE); } /** * Gets known HourlyDuration values. * - * @return known HourlyDuration values. + * @return Known HourlyDuration values. */ public static Collection values() { - return values(HourlyDuration.class); + return new ArrayList<>(VALUES.values()); + } + + /** + * Gets the value of the HourlyDuration instance. + * + * @return the value of the HourlyDuration instance. + */ + @Override + public Integer getValue() { + return this.value; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeInt(getValue()); + } + + /** + * Reads an instance of HourlyDuration from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of HourlyDuration if the JsonReader was pointing to an instance of it, or null if the + * JsonReader was pointing to JSON null. + * @throws IOException If an error occurs while reading the HourlyDuration. + * @throws IllegalStateException If unexpected JSON token is found. + */ + public static HourlyDuration fromJson(JsonReader jsonReader) throws IOException { + JsonToken nextToken = jsonReader.nextToken(); + if (nextToken == JsonToken.NULL) { + return null; + } + if (nextToken != JsonToken.NUMBER) { + throw new IllegalStateException( + String.format("Unexpected JSON token for %s deserialization: %s", JsonToken.NUMBER, nextToken)); + } + return HourlyDuration.fromValue(jsonReader.getInt()); + } + + @Override + public String toString() { + return Objects.toString(this.value); + } + + @Override + public boolean equals(Object obj) { + return this == obj; + } + + @Override + public int hashCode() { + return Objects.hashCode(this.value); } } diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/HourlyForecast.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/HourlyForecast.java index 0a5703e79a56..123f2d34edc9 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/HourlyForecast.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/HourlyForecast.java @@ -4,6 +4,7 @@ package com.azure.maps.weather.models; import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -24,7 +25,8 @@ public final class HourlyForecast implements JsonSerializable { private OffsetDateTime timestamp; /* - * Numeric value representing an image that displays the `iconPhrase`. Please refer to [Weather services in Azure Maps](/azure/azure-maps/weather-services-concepts#weather-icons) for details. + * Numeric value representing an image that displays the `iconPhrase`. Please refer to [Weather services in Azure + * Maps](/azure/azure-maps/weather-services-concepts#weather-icons) for details. */ private IconCode iconCode; @@ -34,7 +36,8 @@ public final class HourlyForecast implements JsonSerializable { private String iconPhrase; /* - * Indicates the presence or absence of precipitation. True indicates the presence of precipitation, false indicates the absence of precipitation. + * Indicates the presence or absence of precipitation. True indicates the presence of precipitation, false indicates + * the absence of precipitation. */ private Boolean hasPrecipitation; @@ -54,12 +57,14 @@ public final class HourlyForecast implements JsonSerializable { private WeatherUnitDetails realFeelTemperature; /* - * The temperature to which air may be cooled by evaporating water into it at constant pressure until it reaches saturation. + * The temperature to which air may be cooled by evaporating water into it at constant pressure until it reaches + * saturation. */ private WeatherUnitDetails wetBulbTemperature; /* - * The dewpoint temperature in specified unit. The dewpoint temperature is the temperature that the air must be cooled to in order to reach saturation. + * The dewpoint temperature in specified unit. The dewpoint temperature is the temperature that the air must be + * cooled to in order to reach saturation. */ private WeatherUnitDetails dewPoint; @@ -74,7 +79,8 @@ public final class HourlyForecast implements JsonSerializable { private WindDetails windGust; /* - * Relative humidity is the amount of water vapor present in air expressed as a percentage of the amount needed for saturation at the same temperature. + * Relative humidity is the amount of water vapor present in air expressed as a percentage of the amount needed for + * saturation at the same temperature. */ private Integer relativeHumidity; @@ -90,11 +96,11 @@ public final class HourlyForecast implements JsonSerializable { /* * Measure of the strength of the ultraviolet radiation from the sun. Supported values are: - * * `0-2` - Low danger from the sun's UV rays or the average person. - * * `3-5` - Moderate risk of harm from unprotected sun exposure. - * * `6-7` - High risk of harm from unprotected sun exposure. - * * `8-10` - Very high risk of harm from unprotected sun exposure. - * * `11+` - Extreme risk of harm from unprotected sun exposure. + * * `0-2` - Low danger from the sun's UV rays or the average person. + * * `3-5` - Moderate risk of harm from unprotected sun exposure. + * * `6-7` - High risk of harm from unprotected sun exposure. + * * `8-10` - Very high risk of harm from unprotected sun exposure. + * * `11+` - Extreme risk of harm from unprotected sun exposure. */ private Integer uvIndex; @@ -212,8 +218,8 @@ public WeatherUnitDetails getTemperature() { } /** - * Get the realFeelTemperature property: RealFeel™ Temperature being returned. Describes what the temperature really - * feels like in the shade. + * Get the realFeelTemperature property: RealFeel™ Temperature being returned. Describes what the temperature + * really feels like in the shade. * * @return the realFeelTemperature value. */ @@ -403,7 +409,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("date", this.timestamp == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.timestamp)); - jsonWriter.writeNumberField("iconCode", this.iconCode == null ? null : this.iconCode.toInt()); + jsonWriter.writeNumberField("iconCode", this.iconCode == null ? null : this.iconCode.getValue()); jsonWriter.writeStringField("iconPhrase", this.iconPhrase); jsonWriter.writeBooleanField("hasPrecipitation", this.hasPrecipitation); jsonWriter.writeBooleanField("isDaylight", this.isDaylight); @@ -445,10 +451,10 @@ public static HourlyForecast fromJson(JsonReader jsonReader) throws IOException String fieldName = reader.getFieldName(); reader.nextToken(); if ("date".equals(fieldName)) { - deserializedHourlyForecast.timestamp - = reader.getNullable(nonNullReader -> OffsetDateTime.parse(nonNullReader.getString())); + deserializedHourlyForecast.timestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); } else if ("iconCode".equals(fieldName)) { - deserializedHourlyForecast.iconCode = IconCode.fromInt(reader.getInt()); + deserializedHourlyForecast.iconCode = IconCode.fromValue(reader.getInt()); } else if ("iconPhrase".equals(fieldName)) { deserializedHourlyForecast.iconPhrase = reader.getString(); } else if ("hasPrecipitation".equals(fieldName)) { diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/IconCode.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/IconCode.java index 69b3947d01d6..b96531a23662 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/IconCode.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/IconCode.java @@ -3,241 +3,310 @@ // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.maps.weather.models; -import com.azure.core.util.ExpandableStringEnum; +import com.azure.core.util.ExpandableEnum; +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.Collection; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; /** * Numeric value representing an image that displays the `iconPhrase`. Please refer to [Weather services in Azure * Maps](/azure/azure-maps/weather-services-concepts#weather-icons) for details. */ -public final class IconCode extends ExpandableStringEnum { +public final class IconCode implements ExpandableEnum, JsonSerializable { + + private static final Map VALUES = new ConcurrentHashMap<>(); + + private static final Function NEW_INSTANCE = IconCode::new; /** * Sunny. */ - public static final IconCode SUNNY = fromInt(1); + public static final IconCode SUNNY = fromValue(1); /** * Mostly Sunny. */ - public static final IconCode MOSTLY_SUNNY = fromInt(2); + public static final IconCode MOSTLY_SUNNY = fromValue(2); /** * Partly Sunny. */ - public static final IconCode PARTLY_SUNNY = fromInt(3); + public static final IconCode PARTLY_SUNNY = fromValue(3); /** * Intermittent Clouds. */ - public static final IconCode INTERMITTENT_CLOUDS = fromInt(4); + public static final IconCode INTERMITTENT_CLOUDS = fromValue(4); /** * Hazy Sunshine. */ - public static final IconCode HAZY_SUNSHINE = fromInt(5); + public static final IconCode HAZY_SUNSHINE = fromValue(5); /** * Mostly Cloudy. */ - public static final IconCode MOSTLY_CLOUDY = fromInt(6); + public static final IconCode MOSTLY_CLOUDY = fromValue(6); /** * Cloudy. */ - public static final IconCode CLOUDY = fromInt(7); + public static final IconCode CLOUDY = fromValue(7); /** * Dreary (Overcast). */ - public static final IconCode DREARY = fromInt(8); + public static final IconCode DREARY = fromValue(8); /** * Fog. */ - public static final IconCode FOG = fromInt(11); + public static final IconCode FOG = fromValue(11); /** * Showers. */ - public static final IconCode SHOWERS = fromInt(12); + public static final IconCode SHOWERS = fromValue(12); /** * Mostly Cloudy with Showers. */ - public static final IconCode MOSTLY_CLOUDY_WITH_SHOWERS = fromInt(13); + public static final IconCode MOSTLY_CLOUDY_WITH_SHOWERS = fromValue(13); /** * Partly Sunny with Showers. */ - public static final IconCode PARTLY_SUNNY_WITH_SHOWERS = fromInt(14); + public static final IconCode PARTLY_SUNNY_WITH_SHOWERS = fromValue(14); /** * Thunderstorms. */ - public static final IconCode THUNDERSTORMS = fromInt(15); + public static final IconCode THUNDERSTORMS = fromValue(15); /** * Mostly Cloudy with Thunderstorms. */ - public static final IconCode MOSTLY_CLOUDY_WITH_THUNDERSTORMS = fromInt(16); + public static final IconCode MOSTLY_CLOUDY_WITH_THUNDERSTORMS = fromValue(16); /** * Partly Sunny with Thunderstorms. */ - public static final IconCode PARTLY_SUNNY_WITH_THUNDERSTORMS = fromInt(17); + public static final IconCode PARTLY_SUNNY_WITH_THUNDERSTORMS = fromValue(17); /** * Rain. */ - public static final IconCode RAIN = fromInt(18); + public static final IconCode RAIN = fromValue(18); /** * Flurries. */ - public static final IconCode FLURRIES = fromInt(19); + public static final IconCode FLURRIES = fromValue(19); /** * Mostly Cloudy with Flurries. */ - public static final IconCode MOSTLY_CLOUDY_WITH_FLURRIES = fromInt(20); + public static final IconCode MOSTLY_CLOUDY_WITH_FLURRIES = fromValue(20); /** * Partly Sunny with Flurries. */ - public static final IconCode PARTLY_SUNNY_WITH_FLURRIES = fromInt(21); + public static final IconCode PARTLY_SUNNY_WITH_FLURRIES = fromValue(21); /** * Snow. */ - public static final IconCode SNOW = fromInt(22); + public static final IconCode SNOW = fromValue(22); /** * Mostly Cloudy with Snow. */ - public static final IconCode MOSTLY_CLOUDY_WITH_SNOW = fromInt(23); + public static final IconCode MOSTLY_CLOUDY_WITH_SNOW = fromValue(23); /** * Ice. */ - public static final IconCode ICE = fromInt(24); + public static final IconCode ICE = fromValue(24); /** * Sleet. */ - public static final IconCode SLEET = fromInt(25); + public static final IconCode SLEET = fromValue(25); /** * Freezing Rain. */ - public static final IconCode FREEZING_RAIN = fromInt(26); + public static final IconCode FREEZING_RAIN = fromValue(26); /** * Rain and Snow. */ - public static final IconCode RAIN_AND_SNOW = fromInt(29); + public static final IconCode RAIN_AND_SNOW = fromValue(29); /** * Hot. */ - public static final IconCode HOT = fromInt(30); + public static final IconCode HOT = fromValue(30); /** * Cold. */ - public static final IconCode COLD = fromInt(31); + public static final IconCode COLD = fromValue(31); /** * Windy. */ - public static final IconCode WINDY = fromInt(32); + public static final IconCode WINDY = fromValue(32); /** * Clear. */ - public static final IconCode CLEAR = fromInt(33); + public static final IconCode CLEAR = fromValue(33); /** * Mostly Clear. */ - public static final IconCode MOSTLY_CLEAR = fromInt(34); + public static final IconCode MOSTLY_CLEAR = fromValue(34); /** * Partly Cloudy. */ - public static final IconCode PARTLY_CLOUDY = fromInt(35); + public static final IconCode PARTLY_CLOUDY = fromValue(35); /** * Intermittent Clouds (Night). */ - public static final IconCode INTERMITTENT_CLOUDS_NIGHT = fromInt(36); + public static final IconCode INTERMITTENT_CLOUDS_NIGHT = fromValue(36); /** * Hazy Moonlight. */ - public static final IconCode HAZY_MOONLIGHT = fromInt(37); + public static final IconCode HAZY_MOONLIGHT = fromValue(37); /** * Mostly Cloudy (Night). */ - public static final IconCode MOSTLY_CLOUDY_NIGHT = fromInt(38); + public static final IconCode MOSTLY_CLOUDY_NIGHT = fromValue(38); /** * Partly Cloudy with Showers. */ - public static final IconCode PARTLY_CLOUDY_WITH_SHOWERS = fromInt(39); + public static final IconCode PARTLY_CLOUDY_WITH_SHOWERS = fromValue(39); /** * Mostly Cloudy with Showers (Night). */ - public static final IconCode MOSTLY_CLOUDY_WITH_SHOWERS_NIGHT = fromInt(40); + public static final IconCode MOSTLY_CLOUDY_WITH_SHOWERS_NIGHT = fromValue(40); /** * Partly Cloudy with Thunderstorms. */ - public static final IconCode PARTLY_CLOUDY_WITH_THUNDERSTORMS = fromInt(41); + public static final IconCode PARTLY_CLOUDY_WITH_THUNDERSTORMS = fromValue(41); /** * Mostly Cloudy with Thunderstorms (Night). */ - public static final IconCode MOSTLY_CLOUDY_WITH_THUNDERSTORMS_NIGHT = fromInt(42); + public static final IconCode MOSTLY_CLOUDY_WITH_THUNDERSTORMS_NIGHT = fromValue(42); /** * Mostly Cloudy with Flurries (Night). */ - public static final IconCode MOSTLY_CLOUDY_WITH_FLURRIES_NIGHT = fromInt(43); + public static final IconCode MOSTLY_CLOUDY_WITH_FLURRIES_NIGHT = fromValue(43); /** * Mostly Cloudy with Snow (Night). */ - public static final IconCode MOSTLY_CLOUDY_WITH_SNOW_NIGHT = fromInt(44); + public static final IconCode MOSTLY_CLOUDY_WITH_SNOW_NIGHT = fromValue(44); - /** - * Creates a new instance of IconCode value. - * - * @deprecated Use the {@link #fromInt(int)} factory method. - */ - @Deprecated - public IconCode() { + private final Integer value; + + private IconCode(Integer value) { + this.value = value; } /** - * Creates or finds a IconCode from its string representation. + * Creates or finds a IconCode. * - * @param name a name to look for. + * @param value a value to look for. * @return the corresponding IconCode. + * @throws IllegalArgumentException if value is null. */ - public static IconCode fromInt(int name) { - return fromString(String.valueOf(name), IconCode.class); + public static IconCode fromValue(Integer value) { + if (value == null) { + throw new IllegalArgumentException("'value' cannot be null."); + } + return VALUES.computeIfAbsent(value, NEW_INSTANCE); } /** * Gets known IconCode values. * - * @return known IconCode values. + * @return Known IconCode values. */ public static Collection values() { - return values(IconCode.class); + return new ArrayList<>(VALUES.values()); + } + + /** + * Gets the value of the IconCode instance. + * + * @return the value of the IconCode instance. + */ + @Override + public Integer getValue() { + return this.value; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeInt(getValue()); + } + + /** + * Reads an instance of IconCode from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of IconCode if the JsonReader was pointing to an instance of it, or null if the JsonReader + * was pointing to JSON null. + * @throws IOException If an error occurs while reading the IconCode. + * @throws IllegalStateException If unexpected JSON token is found. + */ + public static IconCode fromJson(JsonReader jsonReader) throws IOException { + JsonToken nextToken = jsonReader.nextToken(); + if (nextToken == JsonToken.NULL) { + return null; + } + if (nextToken != JsonToken.NUMBER) { + throw new IllegalStateException( + String.format("Unexpected JSON token for %s deserialization: %s", JsonToken.NUMBER, nextToken)); + } + return IconCode.fromValue(jsonReader.getInt()); + } + + @Override + public String toString() { + return Objects.toString(this.value); + } + + @Override + public boolean equals(Object obj) { + return this == obj; + } + + @Override + public int hashCode() { + return Objects.hashCode(this.value); } int toInt() { diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/IntervalSummary.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/IntervalSummary.java index 72bfd6e49839..56a7688baffe 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/IntervalSummary.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/IntervalSummary.java @@ -47,7 +47,8 @@ public final class IntervalSummary implements JsonSerializable private String longPhrase; /* - * Numeric value representing an image that displays the `iconPhrase`. Please refer to [Weather services in Azure Maps](/azure/azure-maps/weather-services-concepts#weather-icons) for details. + * Numeric value representing an image that displays the `iconPhrase`. Please refer to [Weather services in Azure + * Maps](/azure/azure-maps/weather-services-concepts#weather-icons) for details. */ private IconCode iconCode; @@ -133,7 +134,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStringField("shortPhrase", this.shortDescription); jsonWriter.writeStringField("briefPhrase", this.briefDescription); jsonWriter.writeStringField("longPhrase", this.longPhrase); - jsonWriter.writeNumberField("iconCode", this.iconCode == null ? null : this.iconCode.toInt()); + jsonWriter.writeNumberField("iconCode", this.iconCode == null ? null : this.iconCode.getValue()); return jsonWriter.writeEndObject(); } @@ -164,7 +165,7 @@ public static IntervalSummary fromJson(JsonReader jsonReader) throws IOException } else if ("longPhrase".equals(fieldName)) { deserializedIntervalSummary.longPhrase = reader.getString(); } else if ("iconCode".equals(fieldName)) { - deserializedIntervalSummary.iconCode = IconCode.fromInt(reader.getInt()); + deserializedIntervalSummary.iconCode = IconCode.fromValue(reader.getInt()); } else { reader.skipChildren(); } diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/LocalSource.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/LocalSource.java index ff44346802bc..e743cc439cb0 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/LocalSource.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/LocalSource.java @@ -22,12 +22,14 @@ public final class LocalSource implements JsonSerializable { private Integer id; /* - * Name of the local data provider. Name is displayed in the language specified by language code in URL, if available. Otherwise, Name is displayed in English or the language in which the name was provided. + * Name of the local data provider. Name is displayed in the language specified by language code in URL, if + * available. Otherwise, Name is displayed in English or the language in which the name was provided. */ private String name; /* - * Weather code provided by the local data provider. This weather code allows the forecast to be matched to icons provided by the local data provider instead of Azure Maps icons. + * Weather code provided by the local data provider. This weather code allows the forecast to be matched to icons + * provided by the local data provider instead of Azure Maps icons. */ private String weatherCode; diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/MinuteForecastResult.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/MinuteForecastResult.java index 75f61c75f355..3727468bf73c 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/MinuteForecastResult.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/MinuteForecastResult.java @@ -23,7 +23,8 @@ public final class MinuteForecastResult implements JsonSerializable intervalSummaries; diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/MinuteForecastSummary.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/MinuteForecastSummary.java index 26cc2380297b..28d4a6553449 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/MinuteForecastSummary.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/MinuteForecastSummary.java @@ -37,7 +37,8 @@ public final class MinuteForecastSummary implements JsonSerializable { private String name; /* - * Air quality rating on a scale set by local regulating bodies. Scales can vary widely based on location. See [Wikipedia](https://en.wikipedia.org/wiki/Air_quality_index) for more information. + * Air quality rating on a scale set by local regulating bodies. Scales can vary widely based on location. See + * [Wikipedia](https://en.wikipedia.org/wiki/Air_quality_index) for more information. */ private Float index; /* - * Internationally normalized air quality rating on a scale from 0 to 300 and up, with higher numbers representing worse air quality. + * Internationally normalized air quality rating on a scale from 0 to 300 and up, with higher numbers representing + * worse air quality. */ private Float globalIndex; diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/PrecipitationSummary.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/PrecipitationSummary.java index 37129ba9eba3..bc483b9a04de 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/PrecipitationSummary.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/PrecipitationSummary.java @@ -24,32 +24,33 @@ public final class PrecipitationSummary implements JsonSerializable OffsetDateTime.parse(nonNullReader.getString())); + deserializedQuarterDayForecast.dateTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); } else if ("effectiveDate".equals(fieldName)) { - deserializedQuarterDayForecast.effectiveDate - = reader.getNullable(nonNullReader -> OffsetDateTime.parse(nonNullReader.getString())); + deserializedQuarterDayForecast.effectiveDate = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); } else if ("quarter".equals(fieldName)) { - deserializedQuarterDayForecast.quarter = DayQuarter.fromInt(reader.getInt()); + deserializedQuarterDayForecast.quarter = DayQuarter.fromValue(reader.getInt()); } else if ("iconCode".equals(fieldName)) { - deserializedQuarterDayForecast.iconCode = IconCode.fromInt(reader.getInt()); + deserializedQuarterDayForecast.iconCode = IconCode.fromValue(reader.getInt()); } else if ("iconPhrase".equals(fieldName)) { deserializedQuarterDayForecast.iconPhrase = reader.getString(); } else if ("phrase".equals(fieldName)) { diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/SevereWeatherAlert.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/SevereWeatherAlert.java index ecae604eae3e..4369698edc3d 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/SevereWeatherAlert.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/SevereWeatherAlert.java @@ -38,7 +38,9 @@ public final class SevereWeatherAlert implements JsonSerializable { /* - * Description of the alert in the specified language. By default English (en-US) is returned if the language parameter is not specified in the request. + * Description of the alert in the specified language. By default English (en-US) is returned if the language + * parameter is not specified in the request. */ private String description; diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/StormForecast.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/StormForecast.java index 6c54175704c3..9dd6ea270075 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/StormForecast.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/StormForecast.java @@ -4,14 +4,16 @@ package com.azure.maps.weather.models; import com.azure.core.annotation.Fluent; +import com.azure.core.models.GeoPosition; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import com.azure.maps.weather.implementation.models.LatLongPair; import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; import java.util.List; -import com.azure.core.models.GeoPosition; /** * Government-issued storm forecast. @@ -22,7 +24,7 @@ public final class StormForecast implements JsonSerializable { /* * Datetime the forecast is valid, displayed in ISO8601 format. */ - private String timestamp; + private OffsetDateTime timestamp; /* * Datetime the forecast was created, displayed in ISO8601 format. @@ -45,12 +47,20 @@ public final class StormForecast implements JsonSerializable { private WeatherUnitDetails sustainedWind; /* - * Possible status values include:

        • Cyclonic storm
        • Deep depression
        • Depression
        • Extremely severe cyclonic storm
        • Hurricane category (1-5)
        • Intense tropical cyclone
        • Moderate tropical storm
        • Post-tropical cyclone
        • Potential tropical cyclone
        • Severe cyclonic storm
        • Severe tropical storm
        • Subtropical
        • Super cyclonic storm
        • Tropical cyclone
        • Tropical cyclone category (1-5)
        • Tropical depression
        • Tropical disturbance
        • Tropical storm
        • Typhoon
        • Very intense tropical cyclone
        • Very severe cyclonic storm
        • Very strong typhoon
        • Violent typhoon
        + * Possible status values include:
        • Cyclonic storm
        • Deep + * depression
        • Depression
        • Extremely severe cyclonic storm
        • Hurricane category + * (1-5)
        • Intense tropical cyclone
        • Moderate tropical storm
        • Post-tropical + * cyclone
        • Potential tropical cyclone
        • Severe cyclonic storm
        • Severe tropical + * storm
        • Subtropical
        • Super cyclonic storm
        • Tropical cyclone
        • Tropical cyclone category + * (1-5)
        • Tropical depression
        • Tropical disturbance
        • Tropical + * storm
        • Typhoon
        • Very intense tropical cyclone
        • Very severe cyclonic storm
        • Very + * strong typhoon
        • Violent typhoon
        */ private String status; /* - * Contains information about the forecast window for the storm during the specified time period (not the entire cone). If windowGeometry=true in the request, this object will include geoJSON details for window geometry. + * Contains information about the forecast window for the storm during the specified time period (not the entire + * cone). If windowGeometry=true in the request, this object will include geoJSON details for window geometry. */ private WeatherWindow weatherWindow; @@ -70,7 +80,7 @@ private StormForecast() { * * @return the timestamp value. */ - public String getTimestamp() { + public OffsetDateTime getTimestamp() { return this.timestamp; } @@ -155,7 +165,8 @@ public List getWindRadiiSummary() { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeStringField("dateTime", this.timestamp); + jsonWriter.writeStringField("dateTime", + this.timestamp == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.timestamp)); jsonWriter.writeStringField("initializedDateTime", this.initializedTimestamp); jsonWriter.writeJsonField("location", this.coordinates); jsonWriter.writeJsonField("maxWindGust", this.maxWindGust); @@ -182,7 +193,8 @@ public static StormForecast fromJson(JsonReader jsonReader) throws IOException { String fieldName = reader.getFieldName(); reader.nextToken(); if ("dateTime".equals(fieldName)) { - deserializedStormForecast.timestamp = reader.getString(); + deserializedStormForecast.timestamp + = reader.getNullable(nonNullReader -> OffsetDateTime.parse(nonNullReader.getString())); } else if ("initializedDateTime".equals(fieldName)) { deserializedStormForecast.initializedTimestamp = reader.getString(); } else if ("location".equals(fieldName)) { diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/StormForecastResult.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/StormForecastResult.java index c39507225621..8fafda454bf6 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/StormForecastResult.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/StormForecastResult.java @@ -42,16 +42,6 @@ public List getStormForecasts() { return this.stormForecasts; } - /** - * Get the nextLink property: The is the link to the next page of the features returned. If it's the last page, no - * this field. - * - * @return the nextLink value. - */ - public String getNextLink() { - return this.nextLink; - } - /** * {@inheritDoc} */ diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/StormLocation.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/StormLocation.java index a49213713f8f..9ed903f2f2f6 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/StormLocation.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/StormLocation.java @@ -4,14 +4,16 @@ package com.azure.maps.weather.models; import com.azure.core.annotation.Fluent; +import com.azure.core.models.GeoPosition; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import com.azure.maps.weather.implementation.models.LatLongPair; import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; import java.util.List; -import com.azure.core.models.GeoPosition; /** * Location for an individual Government-issued storm. @@ -22,7 +24,7 @@ public final class StormLocation implements JsonSerializable { /* * Datetime the forecast is valid, displayed in ISO8601 format. */ - private String timestamp; + private OffsetDateTime timestamp; /* * Coordinates of the storm @@ -85,7 +87,7 @@ private StormLocation() { * * @return the timestamp value. */ - public String getTimestamp() { + public OffsetDateTime getTimestamp() { return this.timestamp; } @@ -186,7 +188,8 @@ public List getWindRadiiSummary() { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeStringField("dateTime", this.timestamp); + jsonWriter.writeStringField("dateTime", + this.timestamp == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.timestamp)); jsonWriter.writeJsonField("location", this.coordinates); jsonWriter.writeJsonField("maxWindGust", this.maxWindGust); jsonWriter.writeJsonField("sustainedWind", this.sustainedWind); @@ -216,7 +219,8 @@ public static StormLocation fromJson(JsonReader jsonReader) throws IOException { String fieldName = reader.getFieldName(); reader.nextToken(); if ("dateTime".equals(fieldName)) { - deserializedStormLocation.timestamp = reader.getString(); + deserializedStormLocation.timestamp + = reader.getNullable(nonNullReader -> OffsetDateTime.parse(nonNullReader.getString())); } else if ("location".equals(fieldName)) { deserializedStormLocation.coordinates = LatLongPair.fromJson(reader); } else if ("maxWindGust".equals(fieldName)) { diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/StormLocationsResult.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/StormLocationsResult.java index 9b44ad545669..2dc7128efdeb 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/StormLocationsResult.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/StormLocationsResult.java @@ -42,16 +42,6 @@ public List getStormLocations() { return this.stormLocations; } - /** - * Get the nextLink property: The is the link to the next page of the features returned. If it's the last page, no - * this field. - * - * @return the nextLink value. - */ - public String getNextLink() { - return this.nextLink; - } - /** * {@inheritDoc} */ diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/StormSearchResult.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/StormSearchResult.java index e3cbc66a4af2..b364b708f66b 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/StormSearchResult.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/StormSearchResult.java @@ -42,16 +42,6 @@ public List getStorms() { return this.storms; } - /** - * Get the nextLink property: The is the link to the next page of the features returned. If it's the last page, no - * this field. - * - * @return the nextLink value. - */ - public String getNextLink() { - return this.nextLink; - } - /** * {@inheritDoc} */ diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/StormSearchResultItem.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/StormSearchResultItem.java index 2d3b517de40a..dc10b8582dae 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/StormSearchResultItem.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/StormSearchResultItem.java @@ -116,7 +116,7 @@ public Boolean isSubtropical() { * * @return the govId value. */ - public Integer getGovId() { + public Integer getGovernmentId() { return this.govId; } diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/StormWindRadiiSummary.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/StormWindRadiiSummary.java index eab0b94d6678..68dca698958d 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/StormWindRadiiSummary.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/StormWindRadiiSummary.java @@ -4,15 +4,17 @@ package com.azure.maps.weather.models; import com.azure.core.annotation.Fluent; +import com.azure.core.models.GeoPolygon; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; +import com.azure.maps.weather.implementation.helpers.Utility; import com.azure.maps.weather.implementation.models.GeoJsonGeometry; import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; import java.util.List; -import com.azure.core.models.GeoPolygon; -import com.azure.maps.weather.implementation.helpers.Utility; /** * Displayed when details=true or radiiGeometry=true in the request. @@ -23,7 +25,7 @@ public final class StormWindRadiiSummary implements JsonSerializable radiusSectorData; @@ -51,7 +54,7 @@ private StormWindRadiiSummary() { * * @return the timestamp value. */ - public String getTimestamp() { + public OffsetDateTime getTimestamp() { return this.timestamp; } @@ -65,8 +68,8 @@ public WeatherUnitDetails getWindSpeed() { } /** - * Get the radiusSectorData property: Contains the information needed to plot wind radius quadrants. Bearing 0–90 = - * NE quadrant; 90–180 = SE quadrant; 180–270 = SW quadrant; 270–360 = NW quadrant. + * Get the radiusSectorData property: Contains the information needed to plot wind radius quadrants. Bearing 0–90 + * = NE quadrant; 90–180 = SE quadrant; 180–270 = SW quadrant; 270–360 = NW quadrant. * * @return the radiusSectorData value. */ @@ -80,7 +83,8 @@ public List getRadiusSectorData() { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeStringField("dateTime", this.timestamp); + jsonWriter.writeStringField("dateTime", + this.timestamp == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.timestamp)); jsonWriter.writeJsonField("windSpeed", this.windSpeed); jsonWriter.writeArrayField("radiusSectorData", this.radiusSectorData, (writer, element) -> writer.writeJson(element)); @@ -103,7 +107,8 @@ public static StormWindRadiiSummary fromJson(JsonReader jsonReader) throws IOExc String fieldName = reader.getFieldName(); reader.nextToken(); if ("dateTime".equals(fieldName)) { - deserializedStormWindRadiiSummary.timestamp = reader.getString(); + deserializedStormWindRadiiSummary.timestamp + = reader.getNullable(nonNullReader -> OffsetDateTime.parse(nonNullReader.getString())); } else if ("windSpeed".equals(fieldName)) { deserializedStormWindRadiiSummary.windSpeed = WeatherUnitDetails.fromJson(reader); } else if ("radiusSectorData".equals(fieldName)) { diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/SunGlare.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/SunGlare.java index e7b7cd334d7b..cfbde2759e64 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/SunGlare.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/SunGlare.java @@ -17,12 +17,15 @@ public final class SunGlare implements JsonSerializable { /* - * If the vehicle heading value is not provided for a waypoint, then the service will calculate a heading based upon the location of neighboring waypoints if provided. + * If the vehicle heading value is not provided for a waypoint, then the service will calculate a heading based upon + * the location of neighboring waypoints if provided. */ private Integer calculatedVehicleHeading; /* - * An index from 0 to 100 indicating sun glare intensity for a driver. A value of 50 and above can be considered a hazard for some drivers and a value of 100 signifies the driver is driving straight into the sun and atmospheric conditions are clear allowing for the full intensity of the sun to blind the driver. + * An index from 0 to 100 indicating sun glare intensity for a driver. A value of 50 and above can be considered a + * hazard for some drivers and a value of 100 signifies the driver is driving straight into the sun and atmospheric + * conditions are clear allowing for the full intensity of the sun to blind the driver. */ private Integer glareIndex; diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/TemperatureSummary.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/TemperatureSummary.java index a10bacf37fcc..3a5681573009 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/TemperatureSummary.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/TemperatureSummary.java @@ -19,17 +19,17 @@ public final class TemperatureSummary implements JsonSerializable { +public final class UnitType implements ExpandableEnum, JsonSerializable { + + private static final Map VALUES = new ConcurrentHashMap<>(); + + private static final Function NEW_INSTANCE = UnitType::new; /** * feet. */ - public static final UnitType FEET = fromInt(0); + public static final UnitType FEET = fromValue(0); /** * inches. */ - public static final UnitType INCHES = fromInt(1); + public static final UnitType INCHES = fromValue(1); /** * miles. */ - public static final UnitType MILES = fromInt(2); + public static final UnitType MILES = fromValue(2); /** * millimeter. */ - public static final UnitType MILLIMETER = fromInt(3); + public static final UnitType MILLIMETER = fromValue(3); /** * centimeter. */ - public static final UnitType CENTIMETER = fromInt(4); + public static final UnitType CENTIMETER = fromValue(4); /** * meter. */ - public static final UnitType METER = fromInt(5); + public static final UnitType METER = fromValue(5); /** * kilometer. */ - public static final UnitType KILOMETER = fromInt(6); + public static final UnitType KILOMETER = fromValue(6); /** * kilometersPerHour. */ - public static final UnitType KILOMETERS_PER_HOUR = fromInt(7); + public static final UnitType KILOMETERS_PER_HOUR = fromValue(7); /** * knots. */ - public static final UnitType KNOTS = fromInt(8); + public static final UnitType KNOTS = fromValue(8); /** * milesPerHour. */ - public static final UnitType MILES_PER_HOUR = fromInt(9); + public static final UnitType MILES_PER_HOUR = fromValue(9); /** * metersPerSecond. */ - public static final UnitType METERS_PER_SECOND = fromInt(10); + public static final UnitType METERS_PER_SECOND = fromValue(10); /** * hectoPascals. */ - public static final UnitType HECTO_PASCALS = fromInt(11); + public static final UnitType HECTO_PASCALS = fromValue(11); /** * inchesOfMercury. */ - public static final UnitType INCHES_OF_MERCURY = fromInt(12); + public static final UnitType INCHES_OF_MERCURY = fromValue(12); /** * kiloPascals. */ - public static final UnitType KILO_PASCALS = fromInt(13); + public static final UnitType KILO_PASCALS = fromValue(13); /** * millibars. */ - public static final UnitType MILLIBARS = fromInt(14); + public static final UnitType MILLIBARS = fromValue(14); /** * millimetersOfMercury. */ - public static final UnitType MILLIMETERS_OF_MERCURY = fromInt(15); + public static final UnitType MILLIMETERS_OF_MERCURY = fromValue(15); /** * poundsPerSquareInch. */ - public static final UnitType POUNDS_PER_SQUARE_INCH = fromInt(16); + public static final UnitType POUNDS_PER_SQUARE_INCH = fromValue(16); /** * celsius. */ - public static final UnitType CELSIUS = fromInt(17); + public static final UnitType CELSIUS = fromValue(17); /** * fahrenheit. */ - public static final UnitType FAHRENHEIT = fromInt(18); + public static final UnitType FAHRENHEIT = fromValue(18); /** * kelvin. */ - public static final UnitType KELVIN = fromInt(19); + public static final UnitType KELVIN = fromValue(19); /** * percent. */ - public static final UnitType PERCENT = fromInt(20); + public static final UnitType PERCENT = fromValue(20); /** * float. */ - public static final UnitType FLOAT = fromInt(21); + public static final UnitType FLOAT = fromValue(21); /** * integer. */ - public static final UnitType INTEGER = fromInt(22); + public static final UnitType INTEGER = fromValue(22); /** * MicrogramsPerCubicMeterOfAir. */ - public static final UnitType MICROGRAMS_PER_CUBIC_METER_OF_AIR = fromInt(31); + public static final UnitType MICROGRAMS_PER_CUBIC_METER_OF_AIR = fromValue(31); - /** - * Creates a new instance of UnitType value. - * - * @deprecated Use the {@link #fromInt(int)} factory method. - */ - @Deprecated - public UnitType() { + private final Integer value; + + private UnitType(Integer value) { + this.value = value; } /** - * Creates or finds a UnitType from its string representation. + * Creates or finds a UnitType. * - * @param name a name to look for. + * @param value a value to look for. * @return the corresponding UnitType. + * @throws IllegalArgumentException if value is null. */ - public static UnitType fromInt(int name) { - return fromString(String.valueOf(name), UnitType.class); + public static UnitType fromValue(Integer value) { + if (value == null) { + throw new IllegalArgumentException("'value' cannot be null."); + } + return VALUES.computeIfAbsent(value, NEW_INSTANCE); } /** * Gets known UnitType values. * - * @return known UnitType values. + * @return Known UnitType values. */ public static Collection values() { - return values(UnitType.class); + return new ArrayList<>(VALUES.values()); + } + + /** + * Gets the value of the UnitType instance. + * + * @return the value of the UnitType instance. + */ + @Override + public Integer getValue() { + return this.value; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeInt(getValue()); + } + + /** + * Reads an instance of UnitType from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of UnitType if the JsonReader was pointing to an instance of it, or null if the JsonReader + * was pointing to JSON null. + * @throws IOException If an error occurs while reading the UnitType. + * @throws IllegalStateException If unexpected JSON token is found. + */ + public static UnitType fromJson(JsonReader jsonReader) throws IOException { + JsonToken nextToken = jsonReader.nextToken(); + if (nextToken == JsonToken.NULL) { + return null; + } + if (nextToken != JsonToken.NUMBER) { + throw new IllegalStateException( + String.format("Unexpected JSON token for %s deserialization: %s", JsonToken.NUMBER, nextToken)); + } + return UnitType.fromValue(jsonReader.getInt()); + } + + @Override + public String toString() { + return Objects.toString(this.value); + } + + @Override + public boolean equals(Object obj) { + return this == obj; + } + + @Override + public int hashCode() { + return Objects.hashCode(this.value); } int toInt() { diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/WaypointForecast.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/WaypointForecast.java index c3e144e74c13..3bba3e97ad1c 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/WaypointForecast.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/WaypointForecast.java @@ -18,7 +18,8 @@ public final class WaypointForecast implements JsonSerializable { /* - * Numeric value representing an image that displays the `iconPhrase`. Please refer to [Weather services in Azure Maps](/azure/azure-maps/weather-services-concepts#weather-icons) for details. + * Numeric value representing an image that displays the `iconPhrase`. Please refer to [Weather services in Azure + * Maps](/azure/azure-maps/weather-services-concepts#weather-icons) for details. */ private IconCode iconCode; @@ -58,7 +59,8 @@ public final class WaypointForecast implements JsonSerializable getNotifications() { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeNumberField("iconCode", this.iconCode == null ? null : this.iconCode.toInt()); + jsonWriter.writeNumberField("iconCode", this.iconCode == null ? null : this.iconCode.getValue()); jsonWriter.writeStringField("shortPhrase", this.shortDescription); jsonWriter.writeBooleanField("isDayTime", this.isDaytime); jsonWriter.writeNumberField("cloudCover", this.cloudCover); @@ -242,7 +244,7 @@ public static WaypointForecast fromJson(JsonReader jsonReader) throws IOExceptio String fieldName = reader.getFieldName(); reader.nextToken(); if ("iconCode".equals(fieldName)) { - deserializedWaypointForecast.iconCode = IconCode.fromInt(reader.getInt()); + deserializedWaypointForecast.iconCode = IconCode.fromValue(reader.getInt()); } else if ("shortPhrase".equals(fieldName)) { deserializedWaypointForecast.shortDescription = reader.getString(); } else if ("isDayTime".equals(fieldName)) { diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/WeatherAlongRoutePrecipitation.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/WeatherAlongRoutePrecipitation.java index 56d39c145ea6..a83c1025958d 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/WeatherAlongRoutePrecipitation.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/WeatherAlongRoutePrecipitation.java @@ -22,7 +22,8 @@ public final class WeatherAlongRoutePrecipitation implements JsonSerializable { /* - * Numeric value representing an image that displays the `iconPhrase`. Please refer to [Weather services in Azure Maps](/azure/azure-maps/weather-services-concepts#weather-icons) for details. + * Numeric value representing an image that displays the `iconPhrase`. Please refer to [Weather services in Azure + * Maps](/azure/azure-maps/weather-services-concepts#weather-icons) for details. */ private IconCode iconCode; @@ -80,7 +81,7 @@ public WeatherAlongRouteSummary setHazards(WeatherHazards hazards) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeNumberField("iconCode", this.iconCode == null ? null : this.iconCode.toInt()); + jsonWriter.writeNumberField("iconCode", this.iconCode == null ? null : this.iconCode.getValue()); jsonWriter.writeJsonField("hazards", this.hazards); return jsonWriter.writeEndObject(); } @@ -100,7 +101,7 @@ public static WeatherAlongRouteSummary fromJson(JsonReader jsonReader) throws IO String fieldName = reader.getFieldName(); reader.nextToken(); if ("iconCode".equals(fieldName)) { - deserializedWeatherAlongRouteSummary.iconCode = IconCode.fromInt(reader.getInt()); + deserializedWeatherAlongRouteSummary.iconCode = IconCode.fromValue(reader.getInt()); } else if ("hazards".equals(fieldName)) { deserializedWeatherAlongRouteSummary.hazards = WeatherHazards.fromJson(reader); } else { diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/WeatherHazards.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/WeatherHazards.java index 4ad39170dc41..30ca210cf632 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/WeatherHazards.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/WeatherHazards.java @@ -19,11 +19,11 @@ public final class WeatherHazards implements JsonSerializable { /* * A severity/hazard index. - * * `0` - No hazard. - * * `1` - Be informed, be aware. - * * `2` - Pay attention, be prepared. - * * `3` - Take action. - * * `4` - Life threatening, emergency. + * * `0` - No hazard. + * * `1` - Be informed, be aware. + * * `2` - Pay attention, be prepared. + * * `3` - Take action. + * * `4` - Life threatening, emergency. */ private HazardIndex maxHazardIndex; @@ -67,7 +67,8 @@ public List getDetails() { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeNumberField("maxHazardIndex", this.maxHazardIndex == null ? null : this.maxHazardIndex.toInt()); + jsonWriter.writeNumberField("maxHazardIndex", + this.maxHazardIndex == null ? null : this.maxHazardIndex.getValue()); jsonWriter.writeArrayField("hazardDetails", this.details, (writer, element) -> writer.writeJson(element)); return jsonWriter.writeEndObject(); } @@ -87,7 +88,7 @@ public static WeatherHazards fromJson(JsonReader jsonReader) throws IOException String fieldName = reader.getFieldName(); reader.nextToken(); if ("maxHazardIndex".equals(fieldName)) { - deserializedWeatherHazards.maxHazardIndex = HazardIndex.fromInt(reader.getInt()); + deserializedWeatherHazards.maxHazardIndex = HazardIndex.fromValue(reader.getInt()); } else if ("hazardDetails".equals(fieldName)) { List details = reader.readArray(reader1 -> HazardDetail.fromJson(reader1)); deserializedWeatherHazards.details = details; diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/WeatherNotification.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/WeatherNotification.java index 2cb1510fd077..5f9523f3d248 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/WeatherNotification.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/WeatherNotification.java @@ -23,16 +23,19 @@ public final class WeatherNotification implements JsonSerializable { private String endStatus; /* - * Displayed when windowGeometry=true in request. GeoJSON object containing coordinates describing the window of movement during the specified timeframe. + * Displayed when windowGeometry=true in request. GeoJSON object containing coordinates describing the window of + * movement during the specified timeframe. */ private GeoJsonGeometry geometry; @@ -156,11 +158,11 @@ public static WeatherWindow fromJson(JsonReader jsonReader) throws IOException { } else if ("right".equals(fieldName)) { deserializedWeatherWindow.bottomRight = LatLongPair.fromJson(reader); } else if ("beginDateTime".equals(fieldName)) { - deserializedWeatherWindow.beginTimestamp - = reader.getNullable(nonNullReader -> OffsetDateTime.parse(nonNullReader.getString())); + deserializedWeatherWindow.beginTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); } else if ("endDateTime".equals(fieldName)) { - deserializedWeatherWindow.endTimestamp - = reader.getNullable(nonNullReader -> OffsetDateTime.parse(nonNullReader.getString())); + deserializedWeatherWindow.endTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); } else if ("beginStatus".equals(fieldName)) { deserializedWeatherWindow.beginStatus = reader.getString(); } else if ("endStatus".equals(fieldName)) { diff --git a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/WindDirection.java b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/WindDirection.java index 574ff1a34862..6cbe2238abbd 100644 --- a/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/WindDirection.java +++ b/sdk/maps/azure-maps-weather/src/main/java/com/azure/maps/weather/models/WindDirection.java @@ -17,7 +17,8 @@ public final class WindDirection implements JsonSerializable { /* - * Wind direction in Azimuth degrees, starting at true North and continuing in clockwise direction. North is 0 degrees, east is 90 degrees, south is 180 degrees, west is 270 degrees. Possible values 0-359. + * Wind direction in Azimuth degrees, starting at true North and continuing in clockwise direction. North is 0 + * degrees, east is 90 degrees, south is 180 degrees, west is 270 degrees. Possible values 0-359. */ private Integer degrees; diff --git a/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/GetAirQualityDailyForecasts.java b/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/GetAirQualityDailyForecasts.java deleted file mode 100644 index dea47d281f0d..000000000000 --- a/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/GetAirQualityDailyForecasts.java +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.maps.weather.samples; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.models.GeoPosition; -import com.azure.maps.weather.WeatherAsyncClient; -import com.azure.maps.weather.WeatherClient; -import com.azure.maps.weather.WeatherClientBuilder; -import com.azure.maps.weather.models.DailyDuration; - -public class GetAirQualityDailyForecasts { - public static void main(String[] args) { - // Authenticates using subscription key - AzureKeyCredential keyCredential = new AzureKeyCredential(System.getenv("SUBSCRIPTION_KEY")); - // builder.credential(keyCredential); - - // Authenticates using Azure AD building a default credential - // This will look for AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_CLIENT_SECRET env variables - // DefaultAzureCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); - - WeatherClient client = new WeatherClientBuilder() - .credential(keyCredential) - .weatherClientId(System.getenv("MAPS_CLIENT_ID")) - .buildClient(); - - // Get Air Quality Daily Forecasts - - // https://docs.microsoft.com/en-us/rest/api/maps/weather/get-air-quality-daily-forecasts - // Get detailed information about the concentration of pollutants and overall status of forecasted daily air quality. - // The service can provide forecasted daily air quality information for the upcoming 1 to 7 days. - // Information includes, pollution levels, air quality index values, the dominant pollutant, and a brief statement summarizing risk level and suggested precautions. - System.out.println("Get Air Quality Daily Forecasts Sync Client"); - // BEGIN: com.azure.maps.weather.sync.get_air_quality_daily_forecasts - client.getAirQualityDailyForecasts( - new GeoPosition(-122.138874, 47.632346), "en", DailyDuration.TWO_DAYS); - // END: com.azure.maps.weather.sync.get_air_quality_daily_forecasts - - // Authenticates using subscription key - AzureKeyCredential asyncClientKeyCredential = new AzureKeyCredential(System.getenv("SUBSCRIPTION_KEY")); - // builder.credential(keyCredential); - - // Authenticates using Azure AD building a default credential - // This will look for AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_CLIENT_SECRET env variables - // DefaultAzureCredential asyncClientTokenCredential = new DefaultAzureCredentialBuilder().build(); - - WeatherAsyncClient asyncClient = new WeatherClientBuilder() - .credential(asyncClientKeyCredential) - .weatherClientId(System.getenv("MAPS_CLIENT_ID")) - .buildAsyncClient(); - - // Get Air Quality Daily Forecasts - - // https://docs.microsoft.com/en-us/rest/api/maps/weather/get-air-quality-daily-forecasts - // Get detailed information about the concentration of pollutants and overall status of forecasted daily air quality. - // The service can provide forecasted daily air quality information for the upcoming 1 to 7 days. - // Information includes, pollution levels, air quality index values, the dominant pollutant, and a brief statement summarizing risk level and suggested precautions. - System.out.println("Get Air Quality Daily Forecasts Async Client"); - // BEGIN: com.azure.maps.weather.async.get_air_quality_daily_forecasts - asyncClient.getAirQualityDailyForecasts( - new GeoPosition(-122.138874, 47.632346), "en", DailyDuration.TWO_DAYS); - // END: com.azure.maps.weather.async.get_air_quality_daily_forecasts - } -} diff --git a/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/GetAirQualityHourlyForecasts.java b/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/GetAirQualityHourlyForecasts.java deleted file mode 100644 index 4b5356390e70..000000000000 --- a/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/GetAirQualityHourlyForecasts.java +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.maps.weather.samples; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.models.GeoPosition; -import com.azure.maps.weather.WeatherAsyncClient; -import com.azure.maps.weather.WeatherClient; -import com.azure.maps.weather.WeatherClientBuilder; -import com.azure.maps.weather.models.HourlyDuration; - -public class GetAirQualityHourlyForecasts { - public static void main(String[] args) { - // Authenticates using subscription key - AzureKeyCredential keyCredential = new AzureKeyCredential(System.getenv("SUBSCRIPTION_KEY")); - // builder.credential(keyCredential); - - // Authenticates using Azure AD building a default credential - // This will look for AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_CLIENT_SECRET env variables - // DefaultAzureCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); - - WeatherClient client = new WeatherClientBuilder() - .credential(keyCredential) - .weatherClientId(System.getenv("MAPS_CLIENT_ID")) - .buildClient(); - - // Get Air Quality Hourly Forecasts - - // https://docs.microsoft.com/en-us/rest/api/maps/weather/get-air-quality-hourly-forecasts - // Get detailed information about the concentration of pollutants and overall status for current air quality. - // Information includes, pollution levels, air quality index values, the dominant pollutant, and a brief statement summarizing risk level and suggested precautions. - System.out.println("Get Air Quality Hourly Forecasts Sync Client"); - // BEGIN: com.azure.maps.weather.sync.get_air_quality_hourly_forecasts - client.getAirQualityHourlyForecasts( - new GeoPosition(-122.138874, 47.632346), "fr", HourlyDuration.ONE_HOUR, false); - // END: com.azure.maps.weather.sync.get_air_quality_hourly_forecasts - - // Authenticates using subscription key - AzureKeyCredential asyncClientKeyCredential = new AzureKeyCredential(System.getenv("SUBSCRIPTION_KEY")); - // builder.credential(keyCredential); - - // Authenticates using Azure AD building a default credential - // This will look for AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_CLIENT_SECRET env variables - // DefaultAzureCredential asyncClientTokenCredential = new DefaultAzureCredentialBuilder().build(); - - WeatherAsyncClient asyncClient = new WeatherClientBuilder() - .credential(asyncClientKeyCredential) - .weatherClientId(System.getenv("MAPS_CLIENT_ID")) - .buildAsyncClient(); - - // Get Air Quality Hourly Forecasts - - // https://docs.microsoft.com/en-us/rest/api/maps/weather/get-air-quality-hourly-forecasts - // Get detailed information about the concentration of pollutants and overall status for current air quality. - // Information includes, pollution levels, air quality index values, the dominant pollutant, and a brief statement summarizing risk level and suggested precautions. - System.out.println("Get Air Quality Hourly Forecasts Async Client"); - // BEGIN: com.azure.maps.weather.async.get_air_quality_hourly_forecasts - asyncClient.getAirQualityHourlyForecasts( - new GeoPosition(-122.138874, 47.632346), "fr", HourlyDuration.ONE_HOUR, false); - // END: com.azure.maps.weather.async.get_air_quality_hourly_forecasts - } -} diff --git a/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/GetCurrentAirQuality.java b/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/GetCurrentAirQuality.java index eb3f9002e092..6416a9c27482 100644 --- a/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/GetCurrentAirQuality.java +++ b/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/GetCurrentAirQuality.java @@ -16,22 +16,27 @@ public static void main(String[] args) { // builder.credential(keyCredential); // Authenticates using Azure AD building a default credential - // This will look for AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_CLIENT_SECRET env variables - // DefaultAzureCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); + // This will look for AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_CLIENT_SECRET + // env variables + // DefaultAzureCredential tokenCredential = new + // DefaultAzureCredentialBuilder().build(); WeatherClient client = new WeatherClientBuilder() - .credential(keyCredential) - .weatherClientId(System.getenv("MAPS_CLIENT_ID")) - .buildClient(); + .credential(keyCredential) + .weatherClientId(System.getenv("MAPS_CLIENT_ID")) + .buildClient(); // Get Current Air Quality - // https://docs.microsoft.com/en-us/rest/api/maps/weather/get-current-air-quality - // Get detailed information about the concentration of pollutants and overall status for current air quality. - // Information includes, pollution levels, air quality index values, the dominant pollutant, and a brief statement summarizing risk level and suggested precautions. + // Get detailed information about the concentration of pollutants and overall + // status for current air quality. + // Information includes, pollution levels, air quality index values, the + // dominant pollutant, and a brief statement summarizing risk level and + // suggested precautions. System.out.println("Get Current Air Quality Sync Client"); // BEGIN: com.azure.maps.weather.sync.get_current_air_quality client.getCurrentAirQuality( - new GeoPosition(-122.138874, 47.632346), "es", false); + new GeoPosition(-122.138874, 47.632346), "es", false); // END: com.azure.maps.weather.sync.get_current_air_quality // Authenticates using subscription key @@ -39,22 +44,27 @@ public static void main(String[] args) { // builder.credential(keyCredential); // Authenticates using Azure AD building a default credential - // This will look for AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_CLIENT_SECRET env variables - // DefaultAzureCredential asyncClientTokenCredential = new DefaultAzureCredentialBuilder().build(); + // This will look for AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_CLIENT_SECRET + // env variables + // DefaultAzureCredential asyncClientTokenCredential = new + // DefaultAzureCredentialBuilder().build(); WeatherAsyncClient asyncClient = new WeatherClientBuilder() - .credential(asyncClientKeyCredential) - .weatherClientId(System.getenv("MAPS_CLIENT_ID")) - .buildAsyncClient(); + .credential(asyncClientKeyCredential) + .weatherClientId(System.getenv("MAPS_CLIENT_ID")) + .buildAsyncClient(); // Get Current Air Quality - // https://docs.microsoft.com/en-us/rest/api/maps/weather/get-current-air-quality - // Get detailed information about the concentration of pollutants and overall status for current air quality. - // Information includes, pollution levels, air quality index values, the dominant pollutant, and a brief statement summarizing risk level and suggested precautions. + // Get detailed information about the concentration of pollutants and overall + // status for current air quality. + // Information includes, pollution levels, air quality index values, the + // dominant pollutant, and a brief statement summarizing risk level and + // suggested precautions. System.out.println("Get Current Air Quality Async Client"); // BEGIN: com.azure.maps.weather.async.get_current_air_quality asyncClient.getCurrentAirQuality( - new GeoPosition(-122.138874, 47.632346), "es", false); + new GeoPosition(-122.138874, 47.632346), "es", false); // END: com.azure.maps.weather.async.get_current_air_quality } } diff --git a/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/GetCurrentConditions.java b/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/GetCurrentConditions.java index b17e16f957eb..e3b70e3a06ba 100644 --- a/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/GetCurrentConditions.java +++ b/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/GetCurrentConditions.java @@ -31,7 +31,7 @@ public static void main(String[] args) { System.out.println("Get Current Conditions Sync Client"); // BEGIN: com.azure.maps.weather.sync.get_current_conditions client.getCurrentConditions(new GeoPosition(-122.125679, 47.641268), - null, null, null, null); + null, true, null, null); // END: com.azure.maps.weather.sync.get_current_conditions // Authenticates using subscription key @@ -54,7 +54,7 @@ public static void main(String[] args) { System.out.println("Get Current Conditions Async Client"); // BEGIN: com.azure.maps.weather.async.get_current_conditions asyncClient.getCurrentConditions(new GeoPosition(-122.125679, 47.641268), - null, null, null, null); + null, true, null, null); // END: com.azure.maps.weather.async.get_current_conditions } } diff --git a/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/GetDailyAirQualityForecast.java b/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/GetDailyAirQualityForecast.java new file mode 100644 index 000000000000..428debb22c56 --- /dev/null +++ b/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/GetDailyAirQualityForecast.java @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.maps.weather.samples; + +import com.azure.core.credential.AzureKeyCredential; +import com.azure.core.models.GeoPosition; +import com.azure.maps.weather.WeatherAsyncClient; +import com.azure.maps.weather.WeatherClient; +import com.azure.maps.weather.WeatherClientBuilder; +import com.azure.maps.weather.models.DailyDuration; + +public class GetDailyAirQualityForecast { + public static void main(String[] args) { + // Authenticates using subscription key + AzureKeyCredential keyCredential = new AzureKeyCredential(System.getenv("SUBSCRIPTION_KEY")); + // builder.credential(keyCredential); + + // Authenticates using Azure AD building a default credential + // This will look for AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_CLIENT_SECRET + // env variables + // DefaultAzureCredential tokenCredential = new + // DefaultAzureCredentialBuilder().build(); + + WeatherClient client = new WeatherClientBuilder() + .credential(keyCredential) + .weatherClientId(System.getenv("MAPS_CLIENT_ID")) + .buildClient(); + + // Get Air Quality Daily Forecasts - + // https://docs.microsoft.com/en-us/rest/api/maps/weather/get-air-quality-daily-forecasts + // Get detailed information about the concentration of pollutants and overall + // status of forecasted daily air quality. + // The service can provide forecasted daily air quality information for the + // upcoming 1 to 7 days. + // Information includes, pollution levels, air quality index values, the + // dominant pollutant, and a brief statement summarizing risk level and + // suggested precautions. + System.out.println("Get Air Quality Daily Forecasts Sync Client"); + // BEGIN: com.azure.maps.weather.sync.get_air_quality_daily_forecasts + client.getDailyAirQualityForecast( + new GeoPosition(-122.138874, 47.632346), "en", DailyDuration.TWO_DAYS); + // END: com.azure.maps.weather.sync.get_air_quality_daily_forecasts + + // Authenticates using subscription key + AzureKeyCredential asyncClientKeyCredential = new AzureKeyCredential(System.getenv("SUBSCRIPTION_KEY")); + // builder.credential(keyCredential); + + // Authenticates using Azure AD building a default credential + // This will look for AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_CLIENT_SECRET + // env variables + // DefaultAzureCredential asyncClientTokenCredential = new + // DefaultAzureCredentialBuilder().build(); + + WeatherAsyncClient asyncClient = new WeatherClientBuilder() + .credential(asyncClientKeyCredential) + .weatherClientId(System.getenv("MAPS_CLIENT_ID")) + .buildAsyncClient(); + + // Get Air Quality Daily Forecasts - + // https://docs.microsoft.com/en-us/rest/api/maps/weather/get-air-quality-daily-forecasts + // Get detailed information about the concentration of pollutants and overall + // status of forecasted daily air quality. + // The service can provide forecasted daily air quality information for the + // upcoming 1 to 7 days. + // Information includes, pollution levels, air quality index values, the + // dominant pollutant, and a brief statement summarizing risk level and + // suggested precautions. + System.out.println("Get Air Quality Daily Forecasts Async Client"); + // BEGIN: com.azure.maps.weather.async.get_air_quality_daily_forecasts + asyncClient.getDailyAirQualityForecast( + new GeoPosition(-122.138874, 47.632346), "en", DailyDuration.TWO_DAYS); + // END: com.azure.maps.weather.async.get_air_quality_daily_forecasts + } +} diff --git a/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/GetHourlyAirQualityForecast.java b/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/GetHourlyAirQualityForecast.java new file mode 100644 index 000000000000..6152b3ba9a55 --- /dev/null +++ b/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/GetHourlyAirQualityForecast.java @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.maps.weather.samples; + +import com.azure.core.credential.AzureKeyCredential; +import com.azure.core.models.GeoPosition; +import com.azure.maps.weather.WeatherAsyncClient; +import com.azure.maps.weather.WeatherClient; +import com.azure.maps.weather.WeatherClientBuilder; +import com.azure.maps.weather.models.HourlyDuration; + +public class GetHourlyAirQualityForecast { + public static void main(String[] args) { + // Authenticates using subscription key + AzureKeyCredential keyCredential = new AzureKeyCredential(System.getenv("SUBSCRIPTION_KEY")); + // builder.credential(keyCredential); + + // Authenticates using Azure AD building a default credential + // This will look for AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_CLIENT_SECRET + // env variables + // DefaultAzureCredential tokenCredential = new + // DefaultAzureCredentialBuilder().build(); + + WeatherClient client = new WeatherClientBuilder() + .credential(keyCredential) + .weatherClientId(System.getenv("MAPS_CLIENT_ID")) + .buildClient(); + + // Get Air Quality Hourly Forecasts - + // https://docs.microsoft.com/en-us/rest/api/maps/weather/get-air-quality-hourly-forecasts + // Get detailed information about the concentration of pollutants and overall + // status for current air quality. + // Information includes, pollution levels, air quality index values, the + // dominant pollutant, and a brief statement summarizing risk level and + // suggested precautions. + System.out.println("Get Air Quality Hourly Forecasts Sync Client"); + // BEGIN: com.azure.maps.weather.sync.get_air_quality_hourly_forecasts + client.getHourlyAirQualityForecast( + new GeoPosition(-122.138874, 47.632346), "fr", HourlyDuration.ONE_HOUR, false); + // END: com.azure.maps.weather.sync.get_air_quality_hourly_forecasts + + // Authenticates using subscription key + AzureKeyCredential asyncClientKeyCredential = new AzureKeyCredential(System.getenv("SUBSCRIPTION_KEY")); + // builder.credential(keyCredential); + + // Authenticates using Azure AD building a default credential + // This will look for AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_CLIENT_SECRET + // env variables + // DefaultAzureCredential asyncClientTokenCredential = new + // DefaultAzureCredentialBuilder().build(); + + WeatherAsyncClient asyncClient = new WeatherClientBuilder() + .credential(asyncClientKeyCredential) + .weatherClientId(System.getenv("MAPS_CLIENT_ID")) + .buildAsyncClient(); + + // Get Air Quality Hourly Forecasts - + // https://docs.microsoft.com/en-us/rest/api/maps/weather/get-air-quality-hourly-forecasts + // Get detailed information about the concentration of pollutants and overall + // status for current air quality. + // Information includes, pollution levels, air quality index values, the + // dominant pollutant, and a brief statement summarizing risk level and + // suggested precautions. + System.out.println("Get Air Quality Hourly Forecasts Async Client"); + // BEGIN: com.azure.maps.weather.async.get_air_quality_hourly_forecasts + asyncClient.getHourlyAirQualityForecast( + new GeoPosition(-122.138874, 47.632346), "fr", HourlyDuration.ONE_HOUR, false); + // END: com.azure.maps.weather.async.get_air_quality_hourly_forecasts + } +} diff --git a/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/GetTropicalStormForecast.java b/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/GetTropicalStormForecast.java index b6b066dcc3e1..244a2cbd270b 100644 --- a/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/GetTropicalStormForecast.java +++ b/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/GetTropicalStormForecast.java @@ -18,13 +18,15 @@ public static void main(String[] args) { // builder.credential(keyCredential); // Authenticates using Azure AD building a default credential - // This will look for AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_CLIENT_SECRET env variables - // DefaultAzureCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); + // This will look for AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_CLIENT_SECRET + // env variables + // DefaultAzureCredential tokenCredential = new + // DefaultAzureCredentialBuilder().build(); WeatherClient client = new WeatherClientBuilder() - .credential(keyCredential) - .weatherClientId(System.getenv("MAPS_CLIENT_ID")) - .buildClient(); + .credential(keyCredential) + .weatherClientId(System.getenv("MAPS_CLIENT_ID")) + .buildClient(); // Get Tropical Storm Forecast - // https://docs.microsoft.com/en-us/rest/api/maps/weather/get-tropical-storm-forecast @@ -37,8 +39,8 @@ public static void main(String[] args) { if (result.getActiveStorms().size() > 0) { ActiveStorm storm = result.getActiveStorms().get(0); TropicalStormForecastOptions forecastOptions = new TropicalStormForecastOptions(storm.getYear(), - storm.getBasinId(), storm.getGovId()) - .setIncludeWindowGeometry(true); + storm.getBasinId(), storm.getGovernmentId()) + .setIncludeWindowGeometry(true); client.getTropicalStormForecast(forecastOptions); } // END: com.azure.maps.weather.sync.get_tropical_storm_forecast @@ -48,13 +50,15 @@ public static void main(String[] args) { // builder.credential(keyCredential); // Authenticates using Azure AD building a default credential - // This will look for AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_CLIENT_SECRET env variables - // DefaultAzureCredential asyncClientTokenCredential = new DefaultAzureCredentialBuilder().build(); + // This will look for AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_CLIENT_SECRET + // env variables + // DefaultAzureCredential asyncClientTokenCredential = new + // DefaultAzureCredentialBuilder().build(); WeatherAsyncClient asyncClient = new WeatherClientBuilder() - .credential(asyncClientKeyCredential) - .weatherClientId(System.getenv("MAPS_CLIENT_ID")) - .buildAsyncClient(); + .credential(asyncClientKeyCredential) + .weatherClientId(System.getenv("MAPS_CLIENT_ID")) + .buildAsyncClient(); // Get Tropical Storm Forecast - // https://docs.microsoft.com/en-us/rest/api/maps/weather/get-tropical-storm-forecast @@ -67,8 +71,8 @@ public static void main(String[] args) { if (activeStormResult.getActiveStorms().size() > 0) { ActiveStorm storm = activeStormResult.getActiveStorms().get(0); TropicalStormForecastOptions forecastOptions = new TropicalStormForecastOptions(storm.getYear(), - storm.getBasinId(), storm.getGovId()) - .setIncludeWindowGeometry(true); + storm.getBasinId(), storm.getGovernmentId()) + .setIncludeWindowGeometry(true); asyncClient.getTropicalStormForecast(forecastOptions); } // END: com.azure.maps.weather.async.get_tropical_storm_forecast diff --git a/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/GetTropicalStormLocations.java b/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/GetTropicalStormLocations.java index 59dd8f31621d..220f0e5fb87f 100644 --- a/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/GetTropicalStormLocations.java +++ b/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/GetTropicalStormLocations.java @@ -18,25 +18,28 @@ public static void main(String[] args) { // builder.credential(keyCredential); // Authenticates using Azure AD building a default credential - // This will look for AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_CLIENT_SECRET env variables - // DefaultAzureCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); + // This will look for AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_CLIENT_SECRET + // env variables + // DefaultAzureCredential tokenCredential = new + // DefaultAzureCredentialBuilder().build(); WeatherClient client = new WeatherClientBuilder() - .credential(keyCredential) - .weatherClientId(System.getenv("MAPS_CLIENT_ID")) - .buildClient(); + .credential(keyCredential) + .weatherClientId(System.getenv("MAPS_CLIENT_ID")) + .buildClient(); // Get Tropical Storm Locations - // https://docs.microsoft.com/en-us/rest/api/maps/weather/get-tropical-storm-locations // Get location of individual government-issued tropical storms. - // Information about the tropical storms includes, location coordinates, geometry, basin ID, date, wind details and wind radii. + // Information about the tropical storms includes, location coordinates, + // geometry, basin ID, date, wind details and wind radii. System.out.println("Get Tropical Storm Locations Sync Client"); // BEGIN: com.azure.maps.weather.sync.get_tropical_storm_locations ActiveStormResult result = client.getTropicalStormActive(); if (result.getActiveStorms().size() > 0) { ActiveStorm storm = result.getActiveStorms().get(0); TropicalStormLocationOptions locationOptions = new TropicalStormLocationOptions(storm.getYear(), - storm.getBasinId(), storm.getGovId()); + storm.getBasinId(), storm.getGovernmentId()); client.getTropicalStormLocations(locationOptions); } // END: com.azure.maps.weather.sync.get_tropical_storm_locations @@ -46,25 +49,28 @@ public static void main(String[] args) { // builder.credential(keyCredential); // Authenticates using Azure AD building a default credential - // This will look for AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_CLIENT_SECRET env variables - // DefaultAzureCredential asyncClientTokenCredential = new DefaultAzureCredentialBuilder().build(); + // This will look for AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_CLIENT_SECRET + // env variables + // DefaultAzureCredential asyncClientTokenCredential = new + // DefaultAzureCredentialBuilder().build(); WeatherAsyncClient asyncClient = new WeatherClientBuilder() - .credential(asyncClientKeyCredential) - .weatherClientId(System.getenv("MAPS_CLIENT_ID")) - .buildAsyncClient(); + .credential(asyncClientKeyCredential) + .weatherClientId(System.getenv("MAPS_CLIENT_ID")) + .buildAsyncClient(); // Get Tropical Storm Locations - // https://docs.microsoft.com/en-us/rest/api/maps/weather/get-tropical-storm-locations // Get location of individual government-issued tropical storms. - // Information about the tropical storms includes, location coordinates, geometry, basin ID, date, wind details and wind radii. + // Information about the tropical storms includes, location coordinates, + // geometry, basin ID, date, wind details and wind radii. System.out.println("Get Tropical Storm Locations Async Client"); // BEGIN: com.azure.maps.weather.async.get_tropical_storm_locations ActiveStormResult activeStormResult = client.getTropicalStormActive(); if (activeStormResult.getActiveStorms().size() > 0) { ActiveStorm storm = activeStormResult.getActiveStorms().get(0); TropicalStormLocationOptions locationOptions = new TropicalStormLocationOptions(storm.getYear(), - storm.getBasinId(), storm.getGovId()); + storm.getBasinId(), storm.getGovernmentId()); asyncClient.getTropicalStormLocations(locationOptions); } // END: com.azure.maps.weather.async.get_tropical_storm_locations diff --git a/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/SearchTropicalStorm.java b/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/SearchTropicalStorm.java index 0233d79ad579..ff2610e33e08 100644 --- a/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/SearchTropicalStorm.java +++ b/sdk/maps/azure-maps-weather/src/samples/java/com/azure/maps/weather/samples/SearchTropicalStorm.java @@ -17,24 +17,28 @@ public static void main(String[] args) { // builder.credential(keyCredential); // Authenticates using Azure AD building a default credential - // This will look for AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_CLIENT_SECRET env variables - // DefaultAzureCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); + // This will look for AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_CLIENT_SECRET + // env variables + // DefaultAzureCredential tokenCredential = new + // DefaultAzureCredentialBuilder().build(); WeatherClient client = new WeatherClientBuilder() - .credential(keyCredential) - .weatherClientId(System.getenv("MAPS_CLIENT_ID")) - .buildClient(); + .credential(keyCredential) + .weatherClientId(System.getenv("MAPS_CLIENT_ID")) + .buildClient(); // Get Tropical Storm Search - // https://docs.microsoft.com/en-us/rest/api/maps/weather/get-tropical-storm-search - // Search government-issued tropical storms by year, basin ID, and government ID. - // Information about the tropical storms includes, government ID, basin ID, status, year, name and if it is subtropical. + // Search government-issued tropical storms by year, basin ID, and government + // ID. + // Information about the tropical storms includes, government ID, basin ID, + // status, year, name and if it is subtropical. System.out.println("Get Tropical Storm Search Sync Client"); // BEGIN: com.azure.maps.weather.sync.get_tropical_storm_search ActiveStormResult result = client.getTropicalStormActive(); if (result.getActiveStorms().size() > 0) { ActiveStorm storm = result.getActiveStorms().get(0); - client.searchTropicalStorm(storm.getYear(), storm.getBasinId(), storm.getGovId()); + client.searchTropicalStorm(storm.getYear(), storm.getBasinId(), storm.getGovernmentId()); } // END: com.azure.maps.weather.sync.get_tropical_storm_search @@ -43,24 +47,28 @@ public static void main(String[] args) { // builder.credential(keyCredential); // Authenticates using Azure AD building a default credential - // This will look for AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_CLIENT_SECRET env variables - // DefaultAzureCredential asyncClientTokenCredential = new DefaultAzureCredentialBuilder().build(); + // This will look for AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_CLIENT_SECRET + // env variables + // DefaultAzureCredential asyncClientTokenCredential = new + // DefaultAzureCredentialBuilder().build(); WeatherAsyncClient asyncClient = new WeatherClientBuilder() - .credential(asyncClientKeyCredential) - .weatherClientId(System.getenv("MAPS_CLIENT_ID")) - .buildAsyncClient(); + .credential(asyncClientKeyCredential) + .weatherClientId(System.getenv("MAPS_CLIENT_ID")) + .buildAsyncClient(); // Get Tropical Storm Search - // https://docs.microsoft.com/en-us/rest/api/maps/weather/get-tropical-storm-search - // Search government-issued tropical storms by year, basin ID, and government ID. - // Information about the tropical storms includes, government ID, basin ID, status, year, name and if it is subtropical. + // Search government-issued tropical storms by year, basin ID, and government + // ID. + // Information about the tropical storms includes, government ID, basin ID, + // status, year, name and if it is subtropical. System.out.println("Get Tropical Storm Search Async Client"); // BEGIN: com.azure.maps.weather.async.get_tropical_storm_search ActiveStormResult activeStormResult = asyncClient.getTropicalStormActive().block(); if (activeStormResult.getActiveStorms().size() > 0) { ActiveStorm storm = result.getActiveStorms().get(0); - asyncClient.searchTropicalStorm(storm.getYear(), storm.getBasinId(), storm.getGovId()); + asyncClient.searchTropicalStorm(storm.getYear(), storm.getBasinId(), storm.getGovernmentId()); } // END: com.azure.maps.weather.async.get_tropical_storm_search } diff --git a/sdk/maps/azure-maps-weather/src/test/java/com/azure/maps/weather/TestUtils.java b/sdk/maps/azure-maps-weather/src/test/java/com/azure/maps/weather/TestUtils.java index 1f3af853bc42..7e54ce0d21a6 100644 --- a/sdk/maps/azure-maps-weather/src/test/java/com/azure/maps/weather/TestUtils.java +++ b/sdk/maps/azure-maps-weather/src/test/java/com/azure/maps/weather/TestUtils.java @@ -37,7 +37,8 @@ public class TestUtils { public static final Duration DEFAULT_POLL_INTERVAL = Duration.ofSeconds(30); /** - * Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and + * Returns a stream of arguments that includes all combinations of eligible + * {@link HttpClient HttpClients} and * service versions that should be tested. * * @return A stream of HttpClient and service version combinations to test. @@ -100,12 +101,12 @@ static AirQualityResult getExpectedCurrentAirQuality() { return deserialize("getcurrentairquality.json", AirQualityResult::fromJson); } - static DailyAirQualityForecastResult getExpectedAirQualityDailyForecasts() { - return deserialize("getairqualitydailyforecasts.json", DailyAirQualityForecastResult::fromJson); + static DailyAirQualityForecastResult getExpectedDailyAirQualityForecast() { + return deserialize("getdailyairqualityforecast.json", DailyAirQualityForecastResult::fromJson); } - static AirQualityResult getExpectedAirQualityHourlyForecasts() { - return deserialize("getairqualityhourlyforecasts.json", AirQualityResult::fromJson); + static AirQualityResult getExpectedHourlyAirQualityForecast() { + return deserialize("gethourlyairqualityforecast.json", AirQualityResult::fromJson); } static DailyHistoricalRecordsResult getExpectedDailyHistoricalRecords() { diff --git a/sdk/maps/azure-maps-weather/src/test/java/com/azure/maps/weather/WeatherAsyncClientTest.java b/sdk/maps/azure-maps-weather/src/test/java/com/azure/maps/weather/WeatherAsyncClientTest.java index 056b1822d2b5..2f05cdeaba56 100644 --- a/sdk/maps/azure-maps-weather/src/test/java/com/azure/maps/weather/WeatherAsyncClientTest.java +++ b/sdk/maps/azure-maps-weather/src/test/java/com/azure/maps/weather/WeatherAsyncClientTest.java @@ -161,7 +161,7 @@ public void testAsyncInvalidGetQuarterDayForecastWithResponse(HttpClient httpCli public void testAsyncGetCurrentConditions(HttpClient httpClient, WeatherServiceVersion serviceVersion) { WeatherAsyncClient client = getWeatherAsyncClient(httpClient, serviceVersion); StepVerifier - .create(client.getCurrentConditions(new GeoPosition(-122.125679, 47.641268), null, null, null, null)) + .create(client.getCurrentConditions(new GeoPosition(-122.125679, 47.641268), null, true, null, null)) .assertNext( actualResults -> validateGetCurrentConditions(TestUtils.getExpectedCurrentConditions(), actualResults)) .expectComplete() @@ -175,7 +175,7 @@ public void testAsyncGetCurrentConditions(HttpClient httpClient, WeatherServiceV public void testAsyncGetCurrentConditionsWithResponse(HttpClient httpClient, WeatherServiceVersion serviceVersion) { WeatherAsyncClient client = getWeatherAsyncClient(httpClient, serviceVersion); StepVerifier - .create(client.getCurrentConditionsWithResponse(new GeoPosition(-122.125679, 47.641268), null, null, null, + .create(client.getCurrentConditionsWithResponse(new GeoPosition(-122.125679, 47.641268), null, true, null, null, null)) .assertNext(response -> validateGetCurrentConditionsWithResponse(TestUtils.getExpectedCurrentConditions(), response)) @@ -407,7 +407,8 @@ public void testAsyncSearchTropicalStorm(HttpClient httpClient, WeatherServiceVe ActiveStormResult result = client.getTropicalStormActive().block(); if (!result.getActiveStorms().isEmpty()) { ActiveStorm storm = result.getActiveStorms().get(0); - StepVerifier.create(client.searchTropicalStorm(storm.getYear(), storm.getBasinId(), storm.getGovId())) + StepVerifier + .create(client.searchTropicalStorm(storm.getYear(), storm.getBasinId(), storm.getGovernmentId())) .assertNext(actualResults -> validateGetSearchTropicalStorm(TestUtils.getExpectedSearchTropicalStorm(), actualResults)) .expectComplete() @@ -425,7 +426,8 @@ public void testAsyncSearchTropicalStormWithResponse(HttpClient httpClient, Weat if (!result.getActiveStorms().isEmpty()) { ActiveStorm storm = result.getActiveStorms().get(0); StepVerifier - .create(client.searchTropicalStormWithResponse(storm.getYear(), storm.getBasinId(), storm.getGovId())) + .create(client.searchTropicalStormWithResponse(storm.getYear(), storm.getBasinId(), + storm.getGovernmentId())) .assertNext(response -> validateGetSearchTropicalStormWithResponse( TestUtils.getExpectedSearchTropicalStorm(), response)) .expectComplete() @@ -442,7 +444,7 @@ public void testAsyncInvalidSearchTropicalStormWithResponse(HttpClient httpClien ActiveStormResult result = client.getTropicalStormActive().block(); if (!result.getActiveStorms().isEmpty()) { ActiveStorm storm = result.getActiveStorms().get(0); - StepVerifier.create(client.searchTropicalStormWithResponse(-1, storm.getBasinId(), storm.getGovId())) + StepVerifier.create(client.searchTropicalStormWithResponse(-1, storm.getBasinId(), storm.getGovernmentId())) .expectErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); @@ -460,7 +462,7 @@ public void testAsyncGetTropicalStormForecast(HttpClient httpClient, WeatherServ if (!result.getActiveStorms().isEmpty()) { ActiveStorm storm = result.getActiveStorms().get(0); TropicalStormForecastOptions forecastOptions - = new TropicalStormForecastOptions(storm.getYear(), storm.getBasinId(), storm.getGovId()) + = new TropicalStormForecastOptions(storm.getYear(), storm.getBasinId(), storm.getGovernmentId()) .setIncludeWindowGeometry(true); StepVerifier.create(client.getTropicalStormForecast(forecastOptions)) .assertNext(actualResults -> validateGetTropicalStormForecast( @@ -481,7 +483,7 @@ public void testAsyncGetTropicalStormForecastWithResponse(HttpClient httpClient, if (!result.getActiveStorms().isEmpty()) { ActiveStorm storm = result.getActiveStorms().get(0); TropicalStormForecastOptions forecastOptions - = new TropicalStormForecastOptions(storm.getYear(), storm.getBasinId(), storm.getGovId()) + = new TropicalStormForecastOptions(storm.getYear(), storm.getBasinId(), storm.getGovernmentId()) .setIncludeWindowGeometry(true); StepVerifier.create(client.getTropicalStormForecastWithResponse(forecastOptions, null)) .assertNext(response -> validateGetTropicalStormForecastWithResponse( @@ -501,7 +503,7 @@ public void testAsyncInvalidGetTropicalStormForecastWithResponse(HttpClient http if (!result.getActiveStorms().isEmpty()) { ActiveStorm storm = result.getActiveStorms().get(0); TropicalStormForecastOptions forecastOptions - = new TropicalStormForecastOptions(-1, storm.getBasinId(), storm.getGovId()) + = new TropicalStormForecastOptions(-1, storm.getBasinId(), storm.getGovernmentId()) .setIncludeWindowGeometry(true); StepVerifier.create(client.getTropicalStormForecastWithResponse(forecastOptions, null)) .expectErrorSatisfies(ex -> { @@ -521,7 +523,7 @@ public void testAsyncGetTropicalStormLocations(HttpClient httpClient, WeatherSer if (!result.getActiveStorms().isEmpty()) { ActiveStorm storm = result.getActiveStorms().get(0); TropicalStormLocationOptions locationOptions - = new TropicalStormLocationOptions(storm.getYear(), storm.getBasinId(), storm.getGovId()); + = new TropicalStormLocationOptions(storm.getYear(), storm.getBasinId(), storm.getGovernmentId()); StepVerifier.create(client.getTropicalStormLocations(locationOptions)) .assertNext(actualResults -> validateGetTropicalStormLocations( TestUtils.getExpectedTropicalStormLocations(), actualResults)) @@ -541,7 +543,7 @@ public void testAsyncGetTropicalStormLocationsWithResponse(HttpClient httpClient if (!result.getActiveStorms().isEmpty()) { ActiveStorm storm = result.getActiveStorms().get(0); TropicalStormLocationOptions locationOptions - = new TropicalStormLocationOptions(storm.getYear(), storm.getBasinId(), storm.getGovId()); + = new TropicalStormLocationOptions(storm.getYear(), storm.getBasinId(), storm.getGovernmentId()); StepVerifier.create(client.getTropicalStormLocationsWithResponse(locationOptions, null)) .assertNext(response -> validateGetTropicalStormLocationsWithResponse( TestUtils.getExpectedTropicalStormLocations(), response)) @@ -560,7 +562,7 @@ public void testAsyncInvalidGetTropicalStormLocationsWithResponse(HttpClient htt if (!result.getActiveStorms().isEmpty()) { ActiveStorm storm = result.getActiveStorms().get(0); TropicalStormLocationOptions locationOptions - = new TropicalStormLocationOptions(-1, storm.getBasinId(), storm.getGovId()); + = new TropicalStormLocationOptions(-1, storm.getBasinId(), storm.getGovernmentId()); StepVerifier.create(client.getTropicalStormLocationsWithResponse(locationOptions, null)) .expectErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; @@ -614,13 +616,13 @@ public void testAsyncInvalidGetCurrentAirQualityWithResponse(HttpClient httpClie // Test async get air quality daily forecasts @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.maps.weather.TestUtils#getTestParameters") - public void testAsyncGetAirQualityDailyForecasts(HttpClient httpClient, WeatherServiceVersion serviceVersion) { + public void testAsyncGetDailyAirQualityForecast(HttpClient httpClient, WeatherServiceVersion serviceVersion) { WeatherAsyncClient client = getWeatherAsyncClient(httpClient, serviceVersion); StepVerifier - .create(client.getAirQualityDailyForecasts(new GeoPosition(-122.138874, 47.632346), "en", + .create(client.getDailyAirQualityForecast(new GeoPosition(-122.138874, 47.632346), "en", DailyDuration.TWO_DAYS)) - .assertNext(actualResults -> validateGetAirQualityDailyForecasts( - TestUtils.getExpectedAirQualityDailyForecasts(), actualResults)) + .assertNext(actualResults -> validateGetDailyAirQualityForecast( + TestUtils.getExpectedDailyAirQualityForecast(), actualResults)) .expectComplete() .verify(DEFAULT_TIMEOUT); } @@ -629,14 +631,14 @@ public void testAsyncGetAirQualityDailyForecasts(HttpClient httpClient, WeatherS // Case 1: 200 @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.maps.weather.TestUtils#getTestParameters") - public void testAsyncGetAirQualityDailyForecastsWithResponse(HttpClient httpClient, + public void testAsyncGetDailyAirQualityForecastWithResponse(HttpClient httpClient, WeatherServiceVersion serviceVersion) { WeatherAsyncClient client = getWeatherAsyncClient(httpClient, serviceVersion); StepVerifier - .create(client.getAirQualityDailyForecastsWithResponse(new GeoPosition(-122.138874, 47.632346), "en", + .create(client.getDailyAirQualityForecastWithResponse(new GeoPosition(-122.138874, 47.632346), "en", DailyDuration.TWO_DAYS, null)) - .assertNext(response -> validateGetAirQualityDailyForecastsWithResponse( - TestUtils.getExpectedAirQualityDailyForecasts(), response)) + .assertNext(response -> validateGetDailyAirQualityForecastWithResponse( + TestUtils.getExpectedDailyAirQualityForecast(), response)) .expectComplete() .verify(DEFAULT_TIMEOUT); } @@ -644,10 +646,10 @@ public void testAsyncGetAirQualityDailyForecastsWithResponse(HttpClient httpClie // Case 2: 400 invalid input @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.maps.weather.TestUtils#getTestParameters") - public void testAsyncInvalidGetAirQualityDailyForecastsWithResponse(HttpClient httpClient, + public void testAsyncInvalidGetDailyAirQualityForecastWithResponse(HttpClient httpClient, WeatherServiceVersion serviceVersion) { WeatherAsyncClient client = getWeatherAsyncClient(httpClient, serviceVersion); - StepVerifier.create(client.getAirQualityDailyForecastsWithResponse(new GeoPosition(-100000, 47.632346), "en", + StepVerifier.create(client.getDailyAirQualityForecastWithResponse(new GeoPosition(-100000, 47.632346), "en", DailyDuration.TWO_DAYS, null)).expectErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); @@ -657,13 +659,13 @@ public void testAsyncInvalidGetAirQualityDailyForecastsWithResponse(HttpClient h // Test async get air quality hourly forecasts @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.maps.weather.TestUtils#getTestParameters") - public void testAsyncGetAirQualityHourlyForecasts(HttpClient httpClient, WeatherServiceVersion serviceVersion) { + public void testAsyncGetHourlyAirQualityForecast(HttpClient httpClient, WeatherServiceVersion serviceVersion) { WeatherAsyncClient client = getWeatherAsyncClient(httpClient, serviceVersion); StepVerifier - .create(client.getAirQualityHourlyForecasts(new GeoPosition(-122.138874, 47.632346), "fr", + .create(client.getHourlyAirQualityForecast(new GeoPosition(-122.138874, 47.632346), "fr", HourlyDuration.ONE_HOUR, false)) - .assertNext(actualResults -> validateGetAirQualityHourlyForecasts( - TestUtils.getExpectedAirQualityHourlyForecasts(), actualResults)) + .assertNext(actualResults -> validateGetHourlyAirQualityForecast( + TestUtils.getExpectedHourlyAirQualityForecast(), actualResults)) .expectComplete() .verify(DEFAULT_TIMEOUT); } @@ -672,14 +674,14 @@ public void testAsyncGetAirQualityHourlyForecasts(HttpClient httpClient, Weather // Case 1: 200 @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.maps.weather.TestUtils#getTestParameters") - public void testAsyncGetAirQualityHourlyForecastsWithResponse(HttpClient httpClient, + public void testAsyncGetHourlyAirQualityForecastWithResponse(HttpClient httpClient, WeatherServiceVersion serviceVersion) { WeatherAsyncClient client = getWeatherAsyncClient(httpClient, serviceVersion); StepVerifier - .create(client.getAirQualityHourlyForecastsWithResponse(new GeoPosition(-122.138874, 47.632346), "fr", + .create(client.getHourlyAirQualityForecastWithResponse(new GeoPosition(-122.138874, 47.632346), "fr", HourlyDuration.ONE_HOUR, false, null)) - .assertNext(response -> validateGetAirQualityHourlyForecastsWithResponse( - TestUtils.getExpectedAirQualityHourlyForecasts(), response)) + .assertNext(response -> validateGetHourlyAirQualityForecastWithResponse( + TestUtils.getExpectedHourlyAirQualityForecast(), response)) .expectComplete() .verify(DEFAULT_TIMEOUT); } @@ -687,10 +689,10 @@ public void testAsyncGetAirQualityHourlyForecastsWithResponse(HttpClient httpCli // Case 2: 400 invalid input @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.maps.weather.TestUtils#getTestParameters") - public void testAsyncInvalidGetAirQualityHourlyForecastsWithResponse(HttpClient httpClient, + public void testAsyncInvalidGetHourlyAirQualityForecastWithResponse(HttpClient httpClient, WeatherServiceVersion serviceVersion) { WeatherAsyncClient client = getWeatherAsyncClient(httpClient, serviceVersion); - StepVerifier.create(client.getAirQualityHourlyForecastsWithResponse(new GeoPosition(-100000, 47.632346), "fr", + StepVerifier.create(client.getHourlyAirQualityForecastWithResponse(new GeoPosition(-100000, 47.632346), "fr", HourlyDuration.ONE_HOUR, false, null)).expectErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); diff --git a/sdk/maps/azure-maps-weather/src/test/java/com/azure/maps/weather/WeatherClientTest.java b/sdk/maps/azure-maps-weather/src/test/java/com/azure/maps/weather/WeatherClientTest.java index 055ec2a5688f..de9ee7c6ae36 100644 --- a/sdk/maps/azure-maps-weather/src/test/java/com/azure/maps/weather/WeatherClientTest.java +++ b/sdk/maps/azure-maps-weather/src/test/java/com/azure/maps/weather/WeatherClientTest.java @@ -146,7 +146,7 @@ public void testInvalidGetQuarterDayForecastWithResponse(HttpClient httpClient, public void testGetCurrentConditions(HttpClient httpClient, WeatherServiceVersion serviceVersion) { client = getWeatherClient(httpClient, serviceVersion); CurrentConditionsResult actualResult - = client.getCurrentConditions(new GeoPosition(-122.125679, 47.641268), null, null, null, null); + = client.getCurrentConditions(new GeoPosition(-122.125679, 47.641268), null, true, null, null); CurrentConditionsResult expectedResult = TestUtils.getExpectedCurrentConditions(); validateGetCurrentConditions(expectedResult, actualResult); } @@ -158,7 +158,7 @@ public void testGetCurrentConditions(HttpClient httpClient, WeatherServiceVersio public void testGetCurrentConditionsWithResponse(HttpClient httpClient, WeatherServiceVersion serviceVersion) { client = getWeatherClient(httpClient, serviceVersion); validateGetCurrentConditionsWithResponse(TestUtils.getExpectedCurrentConditions(), client - .getCurrentConditionsWithResponse(new GeoPosition(-122.125679, 47.641268), null, null, null, null, null)); + .getCurrentConditionsWithResponse(new GeoPosition(-122.125679, 47.641268), null, true, null, null, null)); } // Case 2: Response 400, incorrect input @@ -339,7 +339,7 @@ public void testSearchTropicalStorm(HttpClient httpClient, WeatherServiceVersion if (!result.getActiveStorms().isEmpty()) { ActiveStorm storm = result.getActiveStorms().get(0); StormSearchResult actualResult - = client.searchTropicalStorm(storm.getYear(), storm.getBasinId(), storm.getGovId()); + = client.searchTropicalStorm(storm.getYear(), storm.getBasinId(), storm.getGovernmentId()); StormSearchResult expectedResult = TestUtils.getExpectedSearchTropicalStorm(); validateGetSearchTropicalStorm(expectedResult, actualResult); } @@ -354,8 +354,8 @@ public void testSearchTropicalStormWithResponse(HttpClient httpClient, WeatherSe ActiveStormResult result = client.getTropicalStormActive(); if (!result.getActiveStorms().isEmpty()) { ActiveStorm storm = result.getActiveStorms().get(0); - validateGetSearchTropicalStormWithResponse(TestUtils.getExpectedSearchTropicalStorm(), - client.searchTropicalStormWithResponse(storm.getYear(), storm.getBasinId(), storm.getGovId(), null)); + validateGetSearchTropicalStormWithResponse(TestUtils.getExpectedSearchTropicalStorm(), client + .searchTropicalStormWithResponse(storm.getYear(), storm.getBasinId(), storm.getGovernmentId(), null)); } } @@ -369,7 +369,7 @@ public void testInvalidSearchTropicalStormWithResponse(HttpClient httpClient, if (!result.getActiveStorms().isEmpty()) { ActiveStorm storm = result.getActiveStorms().get(0); final HttpResponseException httpResponseException = assertThrows(HttpResponseException.class, - () -> client.searchTropicalStormWithResponse(-100, storm.getBasinId(), storm.getGovId(), null)); + () -> client.searchTropicalStormWithResponse(-100, storm.getBasinId(), storm.getGovernmentId(), null)); assertEquals(400, httpResponseException.getResponse().getStatusCode()); } } @@ -383,7 +383,7 @@ public void testGetTropicalStormForecast(HttpClient httpClient, WeatherServiceVe if (!result.getActiveStorms().isEmpty()) { ActiveStorm storm = result.getActiveStorms().get(0); TropicalStormForecastOptions forecastOptions - = new TropicalStormForecastOptions(storm.getYear(), storm.getBasinId(), storm.getGovId()) + = new TropicalStormForecastOptions(storm.getYear(), storm.getBasinId(), storm.getGovernmentId()) .setIncludeWindowGeometry(true); StormForecastResult actualResult = client.getTropicalStormForecast(forecastOptions); StormForecastResult expectedResult = TestUtils.getExpectedTropicalStormForecast(); @@ -401,7 +401,7 @@ public void testGetTropicalStormForecastWithResponse(HttpClient httpClient, Weat if (!result.getActiveStorms().isEmpty()) { ActiveStorm storm = result.getActiveStorms().get(0); TropicalStormForecastOptions forecastOptions - = new TropicalStormForecastOptions(storm.getYear(), storm.getBasinId(), storm.getGovId()) + = new TropicalStormForecastOptions(storm.getYear(), storm.getBasinId(), storm.getGovernmentId()) .setIncludeWindowGeometry(true); validateGetTropicalStormForecastWithResponse(TestUtils.getExpectedTropicalStormForecast(), client.getTropicalStormForecastWithResponse(forecastOptions, null)); @@ -418,7 +418,7 @@ public void testInvalidGetTropicalStormForecastWithResponse(HttpClient httpClien if (!result.getActiveStorms().isEmpty()) { ActiveStorm storm = result.getActiveStorms().get(0); TropicalStormForecastOptions forecastOptions - = new TropicalStormForecastOptions(-100, storm.getBasinId(), storm.getGovId()) + = new TropicalStormForecastOptions(-100, storm.getBasinId(), storm.getGovernmentId()) .setIncludeWindowGeometry(true); final HttpResponseException httpResponseException = assertThrows(HttpResponseException.class, () -> client.getTropicalStormForecastWithResponse(forecastOptions, null)); @@ -435,7 +435,7 @@ public void testGetTropicalStormLocations(HttpClient httpClient, WeatherServiceV if (!result.getActiveStorms().isEmpty()) { ActiveStorm storm = result.getActiveStorms().get(0); TropicalStormLocationOptions locationOptions - = new TropicalStormLocationOptions(storm.getYear(), storm.getBasinId(), storm.getGovId()); + = new TropicalStormLocationOptions(storm.getYear(), storm.getBasinId(), storm.getGovernmentId()); StormLocationsResult actualResult = client.getTropicalStormLocations(locationOptions); StormLocationsResult expectedResult = TestUtils.getExpectedTropicalStormLocations(); validateGetTropicalStormLocations(expectedResult, actualResult); @@ -452,7 +452,7 @@ public void testGetTropicalStormLocationsWithResponse(HttpClient httpClient, Wea if (!result.getActiveStorms().isEmpty()) { ActiveStorm storm = result.getActiveStorms().get(0); TropicalStormLocationOptions locationOptions - = new TropicalStormLocationOptions(storm.getYear(), storm.getBasinId(), storm.getGovId()); + = new TropicalStormLocationOptions(storm.getYear(), storm.getBasinId(), storm.getGovernmentId()); validateGetTropicalStormLocationsWithResponse(TestUtils.getExpectedTropicalStormLocations(), client.getTropicalStormLocationsWithResponse(locationOptions, null)); } @@ -468,7 +468,7 @@ public void testInvalidGetTropicalStormLocationsWithResponse(HttpClient httpClie if (!result.getActiveStorms().isEmpty()) { ActiveStorm storm = result.getActiveStorms().get(0); TropicalStormLocationOptions locationOptions - = new TropicalStormLocationOptions(-100, storm.getBasinId(), storm.getGovId()); + = new TropicalStormLocationOptions(-100, storm.getBasinId(), storm.getGovernmentId()); final HttpResponseException httpResponseException = assertThrows(HttpResponseException.class, () -> client.getTropicalStormLocationsWithResponse(locationOptions, null)); assertEquals(400, httpResponseException.getResponse().getStatusCode()); @@ -510,34 +510,34 @@ public void testInvalidGetCurrentAirQualityWithResponse(HttpClient httpClient, // Test get air quality daily forecasts @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.maps.weather.TestUtils#getTestParameters") - public void testGetAirQualityDailyForecasts(HttpClient httpClient, WeatherServiceVersion serviceVersion) { + public void testGetDailyAirQualityForecast(HttpClient httpClient, WeatherServiceVersion serviceVersion) { client = getWeatherClient(httpClient, serviceVersion); DailyAirQualityForecastResult actualResult - = client.getAirQualityDailyForecasts(new GeoPosition(-122.138874, 47.632346), "en", DailyDuration.TWO_DAYS); - DailyAirQualityForecastResult expectedResult = TestUtils.getExpectedAirQualityDailyForecasts(); - validateGetAirQualityDailyForecasts(expectedResult, actualResult); + = client.getDailyAirQualityForecast(new GeoPosition(-122.138874, 47.632346), "en", DailyDuration.TWO_DAYS); + DailyAirQualityForecastResult expectedResult = TestUtils.getExpectedDailyAirQualityForecast(); + validateGetDailyAirQualityForecast(expectedResult, actualResult); } // Test get air quality daily forecasts with response // Case 1: 200 @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.maps.weather.TestUtils#getTestParameters") - public void testGetAirQualityDailyForecastsWithResponse(HttpClient httpClient, + public void testGetDailyAirQualityForecastWithResponse(HttpClient httpClient, WeatherServiceVersion serviceVersion) { client = getWeatherClient(httpClient, serviceVersion); - validateGetAirQualityDailyForecastsWithResponse(TestUtils.getExpectedAirQualityDailyForecasts(), - client.getAirQualityDailyForecastsWithResponse(new GeoPosition(-122.138874, 47.632346), "en", + validateGetDailyAirQualityForecastWithResponse(TestUtils.getExpectedDailyAirQualityForecast(), + client.getDailyAirQualityForecastWithResponse(new GeoPosition(-122.138874, 47.632346), "en", DailyDuration.TWO_DAYS, null)); } // Case 2: Response 400, incorrect input @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.maps.weather.TestUtils#getTestParameters") - public void testInvalidGetAirQualityDailyForecastsWithResponse(HttpClient httpClient, + public void testInvalidGetDailyAirQualityForecastWithResponse(HttpClient httpClient, WeatherServiceVersion serviceVersion) { client = getWeatherClient(httpClient, serviceVersion); final HttpResponseException httpResponseException = assertThrows(HttpResponseException.class, - () -> client.getAirQualityDailyForecastsWithResponse(new GeoPosition(-100000, 47.632346), "en", + () -> client.getDailyAirQualityForecastWithResponse(new GeoPosition(-100000, 47.632346), "en", DailyDuration.TWO_DAYS, null)); assertEquals(400, httpResponseException.getResponse().getStatusCode()); } @@ -545,34 +545,34 @@ public void testInvalidGetAirQualityDailyForecastsWithResponse(HttpClient httpCl // Test get air quality hourly forecasts @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.maps.weather.TestUtils#getTestParameters") - public void testGetAirQualityHourlyForecasts(HttpClient httpClient, WeatherServiceVersion serviceVersion) { + public void testGetHourlyAirQualityForecast(HttpClient httpClient, WeatherServiceVersion serviceVersion) { client = getWeatherClient(httpClient, serviceVersion); - AirQualityResult actualResult = client.getAirQualityHourlyForecasts(new GeoPosition(-122.138874, 47.632346), + AirQualityResult actualResult = client.getHourlyAirQualityForecast(new GeoPosition(-122.138874, 47.632346), "fr", HourlyDuration.ONE_HOUR, false); - AirQualityResult expectedResult = TestUtils.getExpectedAirQualityHourlyForecasts(); - validateGetAirQualityHourlyForecasts(expectedResult, actualResult); + AirQualityResult expectedResult = TestUtils.getExpectedHourlyAirQualityForecast(); + validateGetHourlyAirQualityForecast(expectedResult, actualResult); } // Test get air quality hourly forecasts with response // Case 1: 200 @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.maps.weather.TestUtils#getTestParameters") - public void testGetAirQualityHourlyForecastsWithResponse(HttpClient httpClient, + public void testGetHourlyAirQualityForecastWithResponse(HttpClient httpClient, WeatherServiceVersion serviceVersion) { client = getWeatherClient(httpClient, serviceVersion); - validateGetAirQualityHourlyForecastsWithResponse(TestUtils.getExpectedAirQualityHourlyForecasts(), - client.getAirQualityHourlyForecastsWithResponse(new GeoPosition(-122.138874, 47.632346), "fr", + validateGetHourlyAirQualityForecastWithResponse(TestUtils.getExpectedHourlyAirQualityForecast(), + client.getHourlyAirQualityForecastWithResponse(new GeoPosition(-122.138874, 47.632346), "fr", HourlyDuration.ONE_HOUR, false, null)); } // Case 2: Response 400, incorrect input @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.maps.weather.TestUtils#getTestParameters") - public void testInvalidGetAirQualityHourlyForecastsWithResponse(HttpClient httpClient, + public void testInvalidGetHourlyAirQualityForecastWithResponse(HttpClient httpClient, WeatherServiceVersion serviceVersion) { client = getWeatherClient(httpClient, serviceVersion); final HttpResponseException httpResponseException = assertThrows(HttpResponseException.class, - () -> client.getAirQualityHourlyForecastsWithResponse(new GeoPosition(-100000, 47.632346), "fr", + () -> client.getHourlyAirQualityForecastWithResponse(new GeoPosition(-100000, 47.632346), "fr", HourlyDuration.ONE_HOUR, false, null)); assertEquals(400, httpResponseException.getResponse().getStatusCode()); } diff --git a/sdk/maps/azure-maps-weather/src/test/java/com/azure/maps/weather/WeatherTestBase.java b/sdk/maps/azure-maps-weather/src/test/java/com/azure/maps/weather/WeatherTestBase.java index efbb3787a070..c5fd9584d5d3 100644 --- a/sdk/maps/azure-maps-weather/src/test/java/com/azure/maps/weather/WeatherTestBase.java +++ b/sdk/maps/azure-maps-weather/src/test/java/com/azure/maps/weather/WeatherTestBase.java @@ -16,7 +16,6 @@ import com.azure.core.test.models.TestProxySanitizerType; import com.azure.core.test.utils.MockTokenCredential; import com.azure.core.util.Configuration; -import com.azure.identity.AzurePowerShellCredentialBuilder; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.maps.weather.models.ActiveStormResult; import com.azure.maps.weather.models.AirQualityResult; @@ -80,7 +79,7 @@ WeatherClientBuilder modifyBuilder(HttpClient httpClient, WeatherClientBuilder b } else if (interceptorManager.isPlaybackMode()) { builder.credential(new MockTokenCredential()).weatherClientId("weatherClientId"); } else { - builder.credential(new AzurePowerShellCredentialBuilder().build()) + builder.credential(new DefaultAzureCredentialBuilder().build()) .weatherClientId(Configuration.getGlobalConfiguration().get("MAPS_CLIENT_ID")); } @@ -228,7 +227,6 @@ static void validateGetSearchTropicalStorm(StormSearchResult expected, StormSear assertNotNull(expected); assertEquals(expected.getClass().getName(), actual.getClass().getName()); assertEquals(expected.getClass().getSimpleName(), actual.getClass().getSimpleName()); - assertEquals(expected.getNextLink(), actual.getNextLink()); } static void validateGetSearchTropicalStormWithResponse(StormSearchResult expected, @@ -241,7 +239,6 @@ static void validateGetSearchTropicalStormWithResponse(StormSearchResult expecte static void validateGetTropicalStormForecast(StormForecastResult expected, StormForecastResult actual) { assertNotNull(actual); assertNotNull(expected); - assertEquals(expected.getNextLink(), actual.getNextLink()); assertEquals(expected.getClass().getName(), actual.getClass().getName()); assertEquals(expected.getClass().getSimpleName(), actual.getClass().getSimpleName()); } @@ -256,7 +253,6 @@ static void validateGetTropicalStormForecastWithResponse(StormForecastResult exp static void validateGetTropicalStormLocations(StormLocationsResult expected, StormLocationsResult actual) { assertNotNull(actual); assertNotNull(expected); - assertEquals(expected.getNextLink(), actual.getNextLink()); assertEquals(expected.getClass().getName(), actual.getClass().getName()); assertEquals(expected.getClass().getSimpleName(), actual.getClass().getSimpleName()); } @@ -272,7 +268,6 @@ static void validateGetCurrentAirQuality(AirQualityResult expected, AirQualityRe assertNotNull(actual); assertNotNull(expected); assertEquals(expected.getAirQualityResults().size(), actual.getAirQualityResults().size()); - assertEquals(expected.getNextLink(), actual.getNextLink()); assertEquals(expected.getClass().getName(), actual.getClass().getName()); assertEquals(expected.getClass().getSimpleName(), actual.getClass().getSimpleName()); } @@ -284,42 +279,39 @@ static void validateGetCurrentAirQualityWithResponse(AirQualityResult expected, validateGetCurrentAirQuality(expected, response.getValue()); } - static void validateGetAirQualityDailyForecasts(DailyAirQualityForecastResult expected, + static void validateGetDailyAirQualityForecast(DailyAirQualityForecastResult expected, DailyAirQualityForecastResult actual) { assertNotNull(actual); assertNotNull(expected); - assertEquals(expected.getNextLink(), actual.getNextLink()); assertEquals(expected.getClass().getName(), actual.getClass().getName()); assertEquals(expected.getClass().getSimpleName(), actual.getClass().getSimpleName()); } - static void validateGetAirQualityDailyForecastsWithResponse(DailyAirQualityForecastResult expected, + static void validateGetDailyAirQualityForecastWithResponse(DailyAirQualityForecastResult expected, Response response) { assertNotNull(response); assertEquals(200, response.getStatusCode()); - validateGetAirQualityDailyForecasts(expected, response.getValue()); + validateGetDailyAirQualityForecast(expected, response.getValue()); } - static void validateGetAirQualityHourlyForecasts(AirQualityResult expected, AirQualityResult actual) { + static void validateGetHourlyAirQualityForecast(AirQualityResult expected, AirQualityResult actual) { assertNotNull(actual); assertNotNull(expected); - assertEquals(expected.getNextLink(), actual.getNextLink()); assertEquals(expected.getClass().getName(), actual.getClass().getName()); assertEquals(expected.getClass().getSimpleName(), actual.getClass().getSimpleName()); } - static void validateGetAirQualityHourlyForecastsWithResponse(AirQualityResult expected, + static void validateGetHourlyAirQualityForecastWithResponse(AirQualityResult expected, Response response) { assertNotNull(response); assertEquals(200, response.getStatusCode()); - validateGetAirQualityHourlyForecasts(expected, response.getValue()); + validateGetHourlyAirQualityForecast(expected, response.getValue()); } static void validateGetDailyHistoricalRecords(DailyHistoricalRecordsResult expected, DailyHistoricalRecordsResult actual) { assertNotNull(actual); assertNotNull(expected); - assertEquals(expected.getNextLink(), actual.getNextLink()); assertEquals(expected.getClass().getName(), actual.getClass().getName()); assertEquals(expected.getClass().getSimpleName(), actual.getClass().getSimpleName()); } @@ -335,7 +327,6 @@ static void validateGetDailyHistoricalActuals(DailyHistoricalActualsResult expec DailyHistoricalActualsResult actual) { assertNotNull(actual); assertNotNull(expected); - assertEquals(expected.getNextLink(), actual.getNextLink()); assertEquals(expected.getClass().getName(), actual.getClass().getName()); assertEquals(expected.getClass().getSimpleName(), actual.getClass().getSimpleName()); } @@ -351,7 +342,6 @@ static void validateGetDailyHistoricalNormalsResult(DailyHistoricalNormalsResult DailyHistoricalNormalsResult actual) { assertNotNull(actual); assertNotNull(expected); - assertEquals(expected.getNextLink(), actual.getNextLink()); assertEquals(expected.getClass().getName(), actual.getClass().getName()); assertEquals(expected.getClass().getSimpleName(), actual.getClass().getSimpleName()); } diff --git a/sdk/maps/azure-maps-weather/src/test/resources/getairqualitydailyforecasts.json b/sdk/maps/azure-maps-weather/src/test/resources/getdailyairqualityforecast.json similarity index 100% rename from sdk/maps/azure-maps-weather/src/test/resources/getairqualitydailyforecasts.json rename to sdk/maps/azure-maps-weather/src/test/resources/getdailyairqualityforecast.json diff --git a/sdk/maps/azure-maps-weather/src/test/resources/getairqualityhourlyforecasts.json b/sdk/maps/azure-maps-weather/src/test/resources/gethourlyairqualityforecast.json similarity index 100% rename from sdk/maps/azure-maps-weather/src/test/resources/getairqualityhourlyforecasts.json rename to sdk/maps/azure-maps-weather/src/test/resources/gethourlyairqualityforecast.json diff --git a/sdk/maps/azure-maps-weather/swagger/README.md b/sdk/maps/azure-maps-weather/swagger/README.md index e660e938f98d..36d09ff1c4b5 100644 --- a/sdk/maps/azure-maps-weather/swagger/README.md +++ b/sdk/maps/azure-maps-weather/swagger/README.md @@ -39,10 +39,10 @@ directive: $["security"] = []; title: WeatherClient -input-file: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/maps/data-plane/Weather/stable/1.1/weather.json +input-file: https://github.com/Azure/azure-rest-api-specs/blob/b43042075540b8d67cce7d3d9f70b9b9f5a359da/specification/maps/data-plane/Weather/stable/1.1/weather.json namespace: com.azure.maps.weather java: true -use: '@autorest/java@4.1.29' +use: '@autorest/java@4.1.45' output-folder: ../ license-header: MICROSOFT_MIT_SMALL payload-flattening-threshold: 0 diff --git a/sdk/maps/azure-maps-weather/swagger/src/main/java/WeatherCustomization.java b/sdk/maps/azure-maps-weather/swagger/src/main/java/WeatherCustomization.java index b9ec8fac566a..88f0c418f7b5 100644 --- a/sdk/maps/azure-maps-weather/swagger/src/main/java/WeatherCustomization.java +++ b/sdk/maps/azure-maps-weather/swagger/src/main/java/WeatherCustomization.java @@ -85,8 +85,8 @@ public void customize(LibraryCustomization customization, Logger logger) { // customize to make default constructor private bulkPrivateConstructors(models, "WeatherUnitDetails", "WeatherAlongRouteSummary", "WeatherAlongRouteResult", - "SevereWeatherAlertsResult", "QuarterDayForecastResult", "MinuteForecastResult", "HourlyForecastResult", - "DailyIndicesResult", "DailyForecastResult", "CurrentConditionsResult"); + "SevereWeatherAlertsResult", "QuarterDayForecastResult", "MinuteForecastResult", "HourlyForecastResult", + "DailyIndicesResult", "DailyForecastResult", "CurrentConditionsResult"); addToIntMethod(models, "DayQuarter", "HazardIndex", "IconCode", "UnitType"); } @@ -94,22 +94,23 @@ public void customize(LibraryCustomization customization, Logger logger) { // Customizes the StormForecast class @SuppressWarnings("unchecked") private void customizeLatLongPairClasses(ClassOrInterfaceDeclaration clazz, String propertyName, String getter, - String setter) { + String setter) { clazz.findAncestor(CompilationUnit.class).ifPresent(p -> p.addImport("com.azure.core.models.GeoPosition")); clazz.getMethodsByName(getter) - .get(0) - .setType("GeoPosition") - .setBody(StaticJavaParser.parseBlock( - "{ return new GeoPosition(this." + propertyName + ".getLongitude(), this." + propertyName - + ".getLatitude()); }")); + .get(0) + .setType("GeoPosition") + .setBody(StaticJavaParser.parseBlock( + "{ return new GeoPosition(this." + propertyName + ".getLongitude(), this." + propertyName + + ".getLatitude()); }")); clazz.getMethodsByName(setter).forEach(Node::remove); } // Customizes the WeatherWindow and StormWindRadiiSummary classes - // Have to customize it this way because setting return type imports the wrong Utility package. + // Have to customize it this way because setting return type imports the wrong + // Utility package. @SuppressWarnings("unchecked") private void customizeGeoJsonGeometryProperty(ClassOrInterfaceDeclaration clazz, String getter, String setter, - String property) { + String property) { clazz.findAncestor(CompilationUnit.class).ifPresent(p -> { p.addImport("com.azure.core.models.GeoPolygon"); p.addImport("com.azure.maps.weather.implementation.helpers.Utility"); @@ -118,27 +119,27 @@ private void customizeGeoJsonGeometryProperty(ClassOrInterfaceDeclaration clazz, clazz.getMethodsByName(getter).forEach(Node::remove); clazz.getMethodsByName(setter).forEach(Node::remove); clazz.addMethod("getPolygon", Modifier.Keyword.PUBLIC) - .setType("GeoPolygon") - .setBody(StaticJavaParser.parseBlock("{ return Utility.toGeoPolygon(this." + property + "); }")) - .setJavadocComment(new Javadoc(JavadocDescription.parseText("Return GeoPolygon")).addBlockTag("return", - "Returns a {@link GeoPolygon} for this weather window")); + .setType("GeoPolygon") + .setBody(StaticJavaParser.parseBlock("{ return Utility.toGeoPolygon(this." + property + "); }")) + .setJavadocComment(new Javadoc(JavadocDescription.parseText("Return GeoPolygon")).addBlockTag("return", + "Returns a {@link GeoPolygon} for this weather window")); } // Customizes classes with getYear() as a String private void customizeClassesWithString(ClassOrInterfaceDeclaration clazz) { clazz.getMethodsByName("getYear") - .get(0) - .setType("Integer") - .setBody(StaticJavaParser.parseBlock("{ return Integer.valueOf(" + "year" + "); }")); + .get(0) + .setType("Integer") + .setBody(StaticJavaParser.parseBlock("{ return Integer.valueOf(" + "year" + "); }")); clazz.getMethodsByName("setYear").forEach(Node::remove); } // Customizes to private constructor class private void customizePrivateConstructor(ClassOrInterfaceDeclaration clazz) { clazz.getConstructors() - .get(0) - .setModifiers(Modifier.Keyword.PRIVATE) - .setJavadocComment("Set default " + clazz.getNameAsString() + " constructor to private"); + .get(0) + .setModifiers(Modifier.Keyword.PRIVATE) + .setJavadocComment("Set default " + clazz.getNameAsString() + " constructor to private"); } // Customizes to remove setter in ActiveStorm @@ -146,7 +147,9 @@ private void customizeActiveStorm(PackageCustomization models) { customizeClass(models, "ActiveStorm", clazz -> { customizePrivateConstructor(clazz); customizeClassesWithString(clazz); - bulkRemoveMethods(clazz, "setBasinId", "setName", "setIsActive", "setIsSubtropical", "setGovId"); + clazz.getMothod("getGovId").rename("getGovernmentId"); + bulkRemoveMethods(clazz, "setBasinId", "setName", "setIsActive", "setIsSubtropical", "setGovId", + "isActive"); }); } @@ -154,7 +157,7 @@ private void customizeActiveStorm(PackageCustomization models) { private void customizeActiveStormResult(PackageCustomization models) { customizeClass(models, "ActiveStormResult", clazz -> { customizePrivateConstructor(clazz); - bulkRemoveMethods(clazz, "setActiveStorms", "setNextLink"); + bulkRemoveMethods(clazz, "setActiveStorms", "setNextLink", "getNextLink"); }); } @@ -163,7 +166,7 @@ private void customizeAirAndPollen(PackageCustomization models) { customizeClass(models, "AirAndPollen", clazz -> { customizePrivateConstructor(clazz); bulkRemoveMethods(clazz, "setDescription", "setValue", "setCategory", "setCategoryValue", - "setAirQualityType"); + "setAirQualityType"); }); } @@ -172,7 +175,7 @@ private void customizeAirQuality(PackageCustomization models) { customizeClass(models, "AirQuality", clazz -> { customizePrivateConstructor(clazz); bulkRemoveMethods(clazz, "setTimestamp", "setIndex", "setGlobalIndex", "setDominantPollutant", - "setCategory", "setCategoryColor", "setDescription", "setPollutants"); + "setCategory", "setCategoryColor", "setDescription", "setPollutants"); }); } @@ -180,7 +183,7 @@ private void customizeAirQuality(PackageCustomization models) { private void customizeAirQualityResult(PackageCustomization models) { customizeClass(models, "AirQualityResult", clazz -> { customizePrivateConstructor(clazz); - bulkRemoveMethods(clazz, "setAirQualityResults", "setNextLink"); + bulkRemoveMethods(clazz, "setAirQualityResults", "setNextLink", "getNextLink"); }); } @@ -189,7 +192,7 @@ private void customizeAlertDetails(PackageCustomization models) { customizeClass(models, "AlertDetails", clazz -> { customizePrivateConstructor(clazz); bulkRemoveMethods(clazz, "setName", "setDescription", "setStartTime", "setEndTime", "setLatestStatus", - "setDetails", "setLanguage"); + "setDetails", "setLanguage"); }); } @@ -206,11 +209,13 @@ private void customizeCurrentConditions(PackageCustomization models) { customizeClass(models, "CurrentConditions", clazz -> { customizePrivateConstructor(clazz); bulkRemoveMethods(clazz, "setDateTime", "setDescription", "setIconCode", "setHasPrecipitation", - "setIsDaytime", "setTemperature", "setRealFeelTemperature", "setRealFeelTemperatureShade", - "setRelativeHumidity", "setDewPoint", "setWind", "setWindGust", "setUvIndex", "setUvIndexDescription", - "setVisibility", "setObstructionsToVisibility", "setCloudCover", "setCloudCeiling", "setPressure", - "setPressureTendency", "setPastTwentyFourHourTemperatureDeparture", "setApparentTemperature", - "setWindChillTemperature", "setWetBulbTemperature", "setPrecipitationSummary", "setTemperatureSummary"); + "setIsDaytime", "setTemperature", "setRealFeelTemperature", "setRealFeelTemperatureShade", + "setRelativeHumidity", "setDewPoint", "setWind", "setWindGust", "setUvIndex", + "setUvIndexDescription", + "setVisibility", "setObstructionsToVisibility", "setCloudCover", "setCloudCeiling", "setPressure", + "setPressureTendency", "setPastTwentyFourHourTemperatureDeparture", "setApparentTemperature", + "setWindChillTemperature", "setWetBulbTemperature", "setPrecipitationSummary", + "setTemperatureSummary"); }); } @@ -219,7 +224,7 @@ private void customizeDailyAirQuality(PackageCustomization models) { customizeClass(models, "DailyAirQuality", clazz -> { customizePrivateConstructor(clazz); bulkRemoveMethods(clazz, "setTimestamp", "setIndex", "setGlobalIndex", "setDominantPollutant", - "setCategory", "setCategoryColor", "setDescription"); + "setCategory", "setCategoryColor", "setDescription"); }); } @@ -227,7 +232,7 @@ private void customizeDailyAirQuality(PackageCustomization models) { private void customizeDailyAirQualityForecastResult(PackageCustomization models) { customizeClass(models, "DailyAirQualityForecastResult", clazz -> { customizePrivateConstructor(clazz); - bulkRemoveMethods(clazz, "setAirQualityResults", "setNextLink"); + bulkRemoveMethods(clazz, "setAirQualityResults", "setNextLink", "getNextLink"); }); } @@ -236,8 +241,8 @@ private void customizeDailyForecast(PackageCustomization models) { customizeClass(models, "DailyForecast", clazz -> { customizePrivateConstructor(clazz); bulkRemoveMethods(clazz, "setDateTime", "setTemperature", "setRealFeelTemperature", - "setRealFeelTemperatureShade", "setHoursOfSun", "setMeanTemperatureDeviation", "setAirQuality", - "setDaytimeForecast", "setNighttimeForecast", "setSources"); + "setRealFeelTemperatureShade", "setHoursOfSun", "setMeanTemperatureDeviation", "setAirQuality", + "setDaytimeForecast", "setNighttimeForecast", "setSources"); }); } @@ -246,10 +251,11 @@ private void customizeDailyForecastDetail(PackageCustomization models) { customizeClass(models, "DailyForecastDetail", clazz -> { customizePrivateConstructor(clazz); bulkRemoveMethods(clazz, "setIconCode", "setIconPhrase", "setLocalSource", "setHasPrecipitation", - "setPrecipitationType", "setPrecipitationIntensity", "setShortDescription", "setLongPhrase", - "setPrecipitationProbability", "setThunderstormProbability", "setRainProbability", "setSnowProbability", - "setIceProbability", "setWind", "setWindGust", "setTotalLiquid", "setRain", "setSnow", "setIce", - "setHoursOfPrecipitation", "setHoursOfRain", "setHoursOfSnow", "setHoursOfIce", "setCloudCover"); + "setPrecipitationType", "setPrecipitationIntensity", "setShortDescription", "setLongPhrase", + "setPrecipitationProbability", "setThunderstormProbability", "setRainProbability", + "setSnowProbability", + "setIceProbability", "setWind", "setWindGust", "setTotalLiquid", "setRain", "setSnow", "setIce", + "setHoursOfPrecipitation", "setHoursOfRain", "setHoursOfSnow", "setHoursOfIce", "setCloudCover"); clazz.getMethodsByName("isHasPrecipitation").get(0).setName("hasPrecipitation"); clazz.getMethodsByName("getRain").get(0).setName("getRainUnitDetails"); clazz.getMethodsByName("getSnow").get(0).setName("getSnowUnitDetails"); @@ -261,7 +267,7 @@ private void customizeDailyForecastDetail(PackageCustomization models) { // Customize WeatherValue private void customizeWeatherValue(PackageCustomization models) { customizeClass(models, "WeatherValue", - clazz -> bulkRemoveMethods(clazz, "setValue", "setUnitLabel", "setUnitType")); + clazz -> bulkRemoveMethods(clazz, "setValue", "setUnitLabel", "setUnitType")); models.getClass("WeatherValue").rename("WeatherUnitDetails"); } @@ -279,7 +285,7 @@ private void customizeDailyHistoricalActuals(PackageCustomization models) { customizeClass(models, "DailyHistoricalActuals", clazz -> { customizePrivateConstructor(clazz); bulkRemoveMethods(clazz, "setTimestamp", "setTemperature", "setDegreeDaySummary", "setPrecipitation", - "setSnowfall", "setSnowDepth"); + "setSnowfall", "setSnowDepth"); }); } @@ -287,7 +293,7 @@ private void customizeDailyHistoricalActuals(PackageCustomization models) { private void customizeDailyHistoricalActualsResult(PackageCustomization models) { customizeClass(models, "DailyHistoricalActualsResult", clazz -> { customizePrivateConstructor(clazz); - bulkRemoveMethods(clazz, "setHistoricalActuals", "setNextLink"); + bulkRemoveMethods(clazz, "setHistoricalActuals", "setNextLink", "getNextLink"); }); } @@ -303,7 +309,7 @@ private void customizeDailyHistoricalNormals(PackageCustomization models) { private void customizeDailyHistoricalNormalsResult(PackageCustomization models) { customizeClass(models, "DailyHistoricalNormalsResult", clazz -> { customizePrivateConstructor(clazz); - bulkRemoveMethods(clazz, "setHistoricalNormals", "setNextLink"); + bulkRemoveMethods(clazz, "setHistoricalNormals", "setNextLink", "getNextLink"); }); } @@ -319,7 +325,7 @@ private void customizeDailyHistoricalRecords(PackageCustomization models) { private void customizeDailyHistoricalRecordsResult(PackageCustomization models) { customizeClass(models, "DailyHistoricalRecordsResult", clazz -> { customizePrivateConstructor(clazz); - bulkRemoveMethods(clazz, "setHistoricalRecords", "setNextLink"); + bulkRemoveMethods(clazz, "setHistoricalRecords", "setNextLink", "getNextLink"); }); } @@ -328,7 +334,7 @@ private void customizeDailyIndex(PackageCustomization models) { customizeClass(models, "DailyIndex", clazz -> { customizePrivateConstructor(clazz); bulkRemoveMethods(clazz, "setIndexName", "setIndexId", "setDateTime", "setValue", "setCategoryDescription", - "setCategoryValue", "setIsAscending", "setDescription"); + "setCategoryValue", "setIsAscending", "setDescription"); }); } @@ -345,8 +351,8 @@ private void customizeForecastInterval(PackageCustomization models) { customizeClass(models, "ForecastInterval", clazz -> { customizePrivateConstructor(clazz); bulkRemoveMethods(clazz, "setStartMinute", "setMinute", "setDecibelRelativeToZ", "setShortDescription", - "setThreshold", "setColor", "setSimplifiedColor", "setPrecipitationType", "setIconCode", - "setCloudCover"); + "setThreshold", "setColor", "setSimplifiedColor", "setPrecipitationType", "setIconCode", + "setCloudCover"); }); } @@ -363,10 +369,10 @@ private void customizeHourlyForecast(PackageCustomization models) { customizeClass(models, "HourlyForecast", clazz -> { customizePrivateConstructor(clazz); bulkRemoveMethods(clazz, "setTimestamp", "setIconCode", "setIconPhrase", "setHasPrecipitation", - "setIsDaylight", "setTemperature", "setRealFeelTemperature", "setWetBulbTemperature", "setDewPoint", - "setWind", "setWindGust", "setRelativeHumidity", "setVisibility", "setCloudCeiling", "setUvIndex", - "setUvIndexDescription", "setPrecipitationProbability", "setRainProbability", "setSnowProbability", - "setIceProbability", "setTotalLiquid", "setRain", "setSnow", "setIce", "setCloudCover"); + "setIsDaylight", "setTemperature", "setRealFeelTemperature", "setWetBulbTemperature", "setDewPoint", + "setWind", "setWindGust", "setRelativeHumidity", "setVisibility", "setCloudCeiling", "setUvIndex", + "setUvIndexDescription", "setPrecipitationProbability", "setRainProbability", "setSnowProbability", + "setIceProbability", "setTotalLiquid", "setRain", "setSnow", "setIce", "setCloudCover"); }); } @@ -375,7 +381,7 @@ private void customizeIntervalSummary(PackageCustomization models) { customizeClass(models, "IntervalSummary", clazz -> { customizePrivateConstructor(clazz); bulkRemoveMethods(clazz, "setStartMinute", "setEndMinute", "setTotalMinutes", "setShortDescription", - "setBriefDescription", "setLongPhrase", "setIconCode"); + "setBriefDescription", "setLongPhrase", "setIconCode"); }); } @@ -400,7 +406,7 @@ private void customizeMinuteForecastSummary(PackageCustomization models) { customizeClass(models, "MinuteForecastSummary", clazz -> { customizePrivateConstructor(clazz); bulkRemoveMethods(clazz, "setBriefPhrase60", "setShortDescription", "setBriefDescription", "setLongPhrase", - "setIconCode"); + "setIconCode"); }); } @@ -416,8 +422,8 @@ private void customizePollutant(PackageCustomization models) { private void customizePrecipitationSummary(PackageCustomization models) { customizeClass(models, "PrecipitationSummary", clazz -> { customizePrivateConstructor(clazz); - bulkRemoveMethods(clazz, "setPastHour", "setPastThreeHours", "setPastSixHours", "setPastNineHours", - "setPastTwelveHours", "setPastEighteenHours", "setPastTwentyFourHours"); + bulkRemoveMethods(clazz, "setPastHour", "setPast3Hours", "setPast6Hours", "setPast9Hours", + "setPast12Hours", "setPast18Hours", "setPast24Hours"); }); } @@ -442,10 +448,10 @@ private void customizeQuarterDayForecast(PackageCustomization models) { customizeClass(models, "QuarterDayForecast", clazz -> { customizePrivateConstructor(clazz); bulkRemoveMethods(clazz, "setDateTime", "setEffectiveDate", "setQuarter", "setIconCode", "setIconPhrase", - "setPhrase", "setTemperature", "setRealFeelTemperature", "setDewPoint", "setRelativeHumidity", - "setWind", "setWindGust", "setVisibility", "setCloudCover", "setPrecipitationType", - "setHasPrecipitation", "setPrecipitationIntensity", "setPrecipitationProbability", - "setThunderstormProbability", "setTotalLiquid", "setRain", "setSnow", "setIce"); + "setPhrase", "setTemperature", "setRealFeelTemperature", "setDewPoint", "setRelativeHumidity", + "setWind", "setWindGust", "setVisibility", "setCloudCover", "setPrecipitationType", + "setHasPrecipitation", "setPrecipitationIntensity", "setPrecipitationProbability", + "setThunderstormProbability", "setTotalLiquid", "setRain", "setSnow", "setIce"); }); } @@ -462,7 +468,7 @@ private void customizeSevereWeatherAlert(PackageCustomization models) { customizeClass(models, "SevereWeatherAlert", clazz -> { customizePrivateConstructor(clazz); bulkRemoveMethods(clazz, "setCountryCode", "setAlertId", "setDescription", "setCategory", "setPriority", - "setClassification", "setLevel", "setSource", "setSourceId", "setDisclaimer", "setAlertDetails"); + "setClassification", "setLevel", "setSource", "setSourceId", "setDisclaimer", "setAlertDetails"); }); } @@ -480,7 +486,7 @@ private void customizeStormForecast(PackageCustomization models) { customizePrivateConstructor(clazz); customizeLatLongPairClasses(clazz, "coordinates", "getCoordinates", "setCoordinates"); bulkRemoveMethods(clazz, "setCoordinates", "setTimestamp", "setInitializedTimestamp", "setMaxWindGust", - "setSustainedWind", "setStatus", "setWeatherWindow", "setWindRadiiSummary"); + "setSustainedWind", "setStatus", "setWeatherWindow", "setWindRadiiSummary"); }); } @@ -488,7 +494,7 @@ private void customizeStormForecast(PackageCustomization models) { private void customizeStormForecastResult(PackageCustomization models) { customizeClass(models, "StormForecastResult", clazz -> { customizePrivateConstructor(clazz); - bulkRemoveMethods(clazz, "setStormForecasts", "setNextLink"); + bulkRemoveMethods(clazz, "setStormForecasts", "setNextLink", "getNextLink"); }); } @@ -498,8 +504,8 @@ private void customizeStormLocation(PackageCustomization models) { customizePrivateConstructor(clazz); customizeLatLongPairClasses(clazz, "coordinates", "getCoordinates", "setCoordinates"); bulkRemoveMethods(clazz, "setTimestamp", "setMaxWindGust", "setSustainedWind", "setMinimumPressure", - "setMovement", "setStatus", "setIsSubtropical", "setHasTropicalPotential", "setIsPostTropical", - "setWindRadiiSummary"); + "setMovement", "setStatus", "setIsSubtropical", "setHasTropicalPotential", "setIsPostTropical", + "setWindRadiiSummary"); }); } @@ -507,7 +513,7 @@ private void customizeStormLocation(PackageCustomization models) { private void customizeStormLocationsResult(PackageCustomization models) { customizeClass(models, "StormLocationsResult", clazz -> { customizePrivateConstructor(clazz); - bulkRemoveMethods(clazz, "setStormLocations", "setNextLink"); + bulkRemoveMethods(clazz, "setStormLocations", "setNextLink", "getNextLink"); }); } @@ -515,29 +521,30 @@ private void customizeStormLocationsResult(PackageCustomization models) { private void customizeStormSearchResult(PackageCustomization models) { customizeClass(models, "StormSearchResult", clazz -> { customizePrivateConstructor(clazz); - bulkRemoveMethods(clazz, "setStorms", "setNextLink"); + clazz.getMothod("getGovId").rename("getGovernmentId"); + bulkRemoveMethods(clazz, "setStorms", "setNextLink", "getNextLink"); }); } // Remove setters from StormSearchResultItem private void customizeStormSearchResultItem(PackageCustomization models) { models.getClass("StormSearchResultItem") - .customizeAst(ast -> ast.getClassByName("StormSearchResultItem").ifPresent(clazz -> { - customizePrivateConstructor(clazz); - customizeClassesWithString(clazz); - bulkRemoveMethods(clazz, "setBasinId", "setName", "setIsActive", "setIsRetired", "setIsSubtropical", - "setGovId"); - })); + .customizeAst(ast -> ast.getClassByName("StormSearchResultItem").ifPresent(clazz -> { + customizePrivateConstructor(clazz); + customizeClassesWithString(clazz); + bulkRemoveMethods(clazz, "setBasinId", "setName", "setIsActive", "setIsRetired", "setIsSubtropical", + "setGovId"); + })); } // Remove setters from StormWindRadiiSummary private void customizeStormWindRadiiSummary(PackageCustomization models) { models.getClass("StormWindRadiiSummary") - .customizeAst(ast -> ast.getClassByName("StormWindRadiiSummary").ifPresent(clazz -> { - customizePrivateConstructor(clazz); - customizeGeoJsonGeometryProperty(clazz, "getRadiiGeometry", "setRadiiGeometry", "radiiGeometry"); - bulkRemoveMethods(clazz, "setTimestamp", "setWindSpeed", "setRadiusSectorData"); - })); + .customizeAst(ast -> ast.getClassByName("StormWindRadiiSummary").ifPresent(clazz -> { + customizePrivateConstructor(clazz); + customizeGeoJsonGeometryProperty(clazz, "getRadiiGeometry", "setRadiiGeometry", "radiiGeometry"); + bulkRemoveMethods(clazz, "setTimestamp", "setWindSpeed", "setRadiusSectorData"); + })); } // Remove setters from SunGlare @@ -552,7 +559,7 @@ private void customizeSunGlare(PackageCustomization models) { private void customizeTemperatureSummary(PackageCustomization models) { customizeClass(models, "TemperatureSummary", clazz -> { customizePrivateConstructor(clazz); - bulkRemoveMethods(clazz, "setPastSixHours", "setPastTwelveHours", "setPastTwentyFourHours"); + bulkRemoveMethods(clazz, "setPast6Hours", "setPast12Hours", "setPast24Hours"); }); } @@ -568,7 +575,7 @@ private void customizeWeatherAlongRoutePrecipitation(PackageCustomization models // Remove setters from WeatherAlongRouteSummary private void customizeWeatherAlongRouteSummary(PackageCustomization models) { customizeClass(models, "WeatherAlongRouteSummary", - clazz -> bulkRemoveMethods(clazz, "setIconCode", "setHazards")); + clazz -> bulkRemoveMethods(clazz, "setIconCode", "setHazards")); } // Remove setters from WeatherHazards @@ -612,12 +619,12 @@ private void customizeWeatherValueYear(PackageCustomization models) { MethodDeclaration fromJson = clazz.getMethodsByName("fromJson").get(0); String body = fromJson.getBody().get().toString(); body = body.replace("deserializedWeatherValueYear.year = reader.getNullable(JsonReader::getInt);", - String.join("\n", - "if (reader.currentToken() == JsonToken.NUMBER) {", - " deserializedWeatherValueYear.year = reader.getNullable(JsonReader::getInt);", - "} else if (reader.currentToken() == JsonToken.STRING) {", - " deserializedWeatherValueYear.year = Integer.parseInt(reader.getString());", - "}")); + String.join("\n", + "if (reader.currentToken() == JsonToken.NUMBER) {", + " deserializedWeatherValueYear.year = reader.getNullable(JsonReader::getInt);", + "} else if (reader.currentToken() == JsonToken.STRING) {", + " deserializedWeatherValueYear.year = Integer.parseInt(reader.getString());", + "}")); fromJson.setBody(StaticJavaParser.parseBlock(body)); }); } @@ -671,15 +678,15 @@ private void customizeWaypointForecast(PackageCustomization models) { customizeClass(models, "WaypointForecast", clazz -> { customizePrivateConstructor(clazz); bulkRemoveMethods(clazz, "setIconCode", "setIsDaytime", "setCloudCover", "setTemperature", "setWind", - "setWindGust", "setPrecipitation", "setLightningCount", "setSunGlare", "setHazards", - "setNotifications"); + "setWindGust", "setPrecipitation", "setLightningCount", "setSunGlare", "setHazards", + "setNotifications"); }); } private static void customizeClass(PackageCustomization models, String className, - Consumer classOrInterfaceDeclarationConsumer) { + Consumer classOrInterfaceDeclarationConsumer) { models.getClass(className) - .customizeAst(ast -> ast.getClassByName(className).ifPresent(classOrInterfaceDeclarationConsumer)); + .customizeAst(ast -> ast.getClassByName(className).ifPresent(classOrInterfaceDeclarationConsumer)); } private static void bulkRemoveMethods(ClassOrInterfaceDeclaration clazz, String... methodsToRemove) { @@ -697,7 +704,7 @@ private void bulkPrivateConstructors(PackageCustomization models, String... clas private void addToIntMethod(PackageCustomization models, String... classNames) { for (String className : classNames) { customizeClass(models, className, clazz -> clazz.addMethod("toInt").setType("int") - .setBody(StaticJavaParser.parseBlock("{ return Integer.parseInt(toString()); }"))); + .setBody(StaticJavaParser.parseBlock("{ return Integer.parseInt(toString()); }"))); } } } diff --git a/sdk/maps/azure-resourcemanager-maps/README.md b/sdk/maps/azure-resourcemanager-maps/README.md index 25de5da35778..af31621c04f4 100644 --- a/sdk/maps/azure-resourcemanager-maps/README.md +++ b/sdk/maps/azure-resourcemanager-maps/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-maps - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fmaps%2Fazure-resourcemanager-maps%2FREADME.png) + diff --git a/sdk/maps/azure-resourcemanager-maps/pom.xml b/sdk/maps/azure-resourcemanager-maps/pom.xml index 70f68fb74114..f69b4c1267b0 100644 --- a/sdk/maps/azure-resourcemanager-maps/pom.xml +++ b/sdk/maps/azure-resourcemanager-maps/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test @@ -91,7 +91,7 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/mariadb/azure-resourcemanager-mariadb/README.md b/sdk/mariadb/azure-resourcemanager-mariadb/README.md index 352902ce1413..432c7861a8f8 100644 --- a/sdk/mariadb/azure-resourcemanager-mariadb/README.md +++ b/sdk/mariadb/azure-resourcemanager-mariadb/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-mariadb - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fmariadb%2Fazure-resourcemanager-mariadb%2FREADME.png) + diff --git a/sdk/mariadb/azure-resourcemanager-mariadb/pom.xml b/sdk/mariadb/azure-resourcemanager-mariadb/pom.xml index 677e558745d6..f7957b4a3985 100644 --- a/sdk/mariadb/azure-resourcemanager-mariadb/pom.xml +++ b/sdk/mariadb/azure-resourcemanager-mariadb/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/marketplaceordering/azure-resourcemanager-marketplaceordering/README.md b/sdk/marketplaceordering/azure-resourcemanager-marketplaceordering/README.md index 1764a3b4a2ef..b754c85c56ea 100644 --- a/sdk/marketplaceordering/azure-resourcemanager-marketplaceordering/README.md +++ b/sdk/marketplaceordering/azure-resourcemanager-marketplaceordering/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-marketplaceordering - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fmarketplaceordering%2Fazure-resourcemanager-marketplaceordering%2FREADME.png) + diff --git a/sdk/marketplaceordering/azure-resourcemanager-marketplaceordering/pom.xml b/sdk/marketplaceordering/azure-resourcemanager-marketplaceordering/pom.xml index 81364efbe01a..366348fd40b2 100644 --- a/sdk/marketplaceordering/azure-resourcemanager-marketplaceordering/pom.xml +++ b/sdk/marketplaceordering/azure-resourcemanager-marketplaceordering/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/mediaservices/azure-resourcemanager-mediaservices/README.md b/sdk/mediaservices/azure-resourcemanager-mediaservices/README.md index 9b734377d0b2..0772b1d5892d 100644 --- a/sdk/mediaservices/azure-resourcemanager-mediaservices/README.md +++ b/sdk/mediaservices/azure-resourcemanager-mediaservices/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-mediaservices - 2.4.0-beta.2 + 2.4.0-beta.3 ``` [//]: # ({x-version-update-end}) @@ -155,4 +155,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fmediaservices%2Fazure-resourcemanager-mediaservices%2FREADME.png) + diff --git a/sdk/mediaservices/azure-resourcemanager-mediaservices/pom.xml b/sdk/mediaservices/azure-resourcemanager-mediaservices/pom.xml index 70b2a0177866..6c7977ffb51e 100644 --- a/sdk/mediaservices/azure-resourcemanager-mediaservices/pom.xml +++ b/sdk/mediaservices/azure-resourcemanager-mediaservices/pom.xml @@ -52,23 +52,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test @@ -92,13 +92,13 @@ com.azure.resourcemanager azure-resourcemanager-storage - 2.46.0 + 2.48.0 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/metricsadvisor/azure-ai-metricsadvisor-perf/README.md b/sdk/metricsadvisor/azure-ai-metricsadvisor-perf/README.md index f11337600e2a..3a67431b4d8c 100644 --- a/sdk/metricsadvisor/azure-ai-metricsadvisor-perf/README.md +++ b/sdk/metricsadvisor/azure-ai-metricsadvisor-perf/README.md @@ -36,7 +36,7 @@ METRICS_ADVISOR_MAX_LIST_ELEMENTS= com.azure azure-ai-metricsadvisor - 1.1.11 + 1.3.0-beta.1 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/metricsadvisor/azure-ai-metricsadvisor-perf/pom.xml b/sdk/metricsadvisor/azure-ai-metricsadvisor-perf/pom.xml index a6b2b5ebd025..4e580eaf41e1 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.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 diff --git a/sdk/metricsadvisor/azure-ai-metricsadvisor/CHANGELOG.md b/sdk/metricsadvisor/azure-ai-metricsadvisor/CHANGELOG.md index 2c357ca680b8..7e646f6b9e89 100644 --- a/sdk/metricsadvisor/azure-ai-metricsadvisor/CHANGELOG.md +++ b/sdk/metricsadvisor/azure-ai-metricsadvisor/CHANGELOG.md @@ -10,6 +10,16 @@ ### Other Changes +## 1.2.5 (2025-02-25) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`. +- Upgraded `azure-json` from `1.3.0` to version `1.4.0`. +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. + ## 1.2.4 (2024-12-04) diff --git a/sdk/metricsadvisor/azure-ai-metricsadvisor/README.md b/sdk/metricsadvisor/azure-ai-metricsadvisor/README.md index 807b87962551..05b84f228e44 100644 --- a/sdk/metricsadvisor/azure-ai-metricsadvisor/README.md +++ b/sdk/metricsadvisor/azure-ai-metricsadvisor/README.md @@ -54,7 +54,7 @@ add the direct dependency to your project as follows. com.azure azure-ai-metricsadvisor - 1.2.0 + 1.3.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -113,7 +113,7 @@ Authentication with AAD requires some initial setup: com.azure azure-identity - 1.14.2 + 1.15.3 ``` [//]: # ({x-version-update-end}) @@ -445,4 +445,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [samples_readme]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/metricsadvisor/azure-ai-metricsadvisor/src/samples/README.md [wiki_identity]: https://learn.microsoft.com/azure/developer/java/sdk/identity -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%metricsadvisor%2Fazure-ai-metricsadvisor%2FREADME.png) + diff --git a/sdk/metricsadvisor/azure-ai-metricsadvisor/pom.xml b/sdk/metricsadvisor/azure-ai-metricsadvisor/pom.xml index 62f1b3e370f8..fbc1cbd398d3 100644 --- a/sdk/metricsadvisor/azure-ai-metricsadvisor/pom.xml +++ b/sdk/metricsadvisor/azure-ai-metricsadvisor/pom.xml @@ -49,30 +49,30 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/metricsadvisor/azure-ai-metricsadvisor/src/samples/README.md b/sdk/metricsadvisor/azure-ai-metricsadvisor/src/samples/README.md index d04c3ecc5b6c..1f9ce12916a6 100644 --- a/sdk/metricsadvisor/azure-ai-metricsadvisor/src/samples/README.md +++ b/sdk/metricsadvisor/azure-ai-metricsadvisor/src/samples/README.md @@ -118,4 +118,4 @@ Guidelines][SDK_README_CONTRIBUTING] for more information. [list_anomaly_alert_sample]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/metricsadvisor/azure-ai-metricsadvisor/src/samples/java/com/azure/ai/metricsadvisor/ListsAnomaliesForAlertsSample.java [list_anomaly_alert_async_sample]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/metricsadvisor/azure-ai-metricsadvisor/src/samples/java/com/azure/ai/metricsadvisor/ListsAnomaliesForAlertsAsyncSample.java -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fmetricsadvisor%2Fazure-ai-metricsadvisor%2FREADME.png) + diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/CHANGELOG.md b/sdk/migration/azure-resourcemanager-migration-assessment/CHANGELOG.md new file mode 100644 index 000000000000..e95e8853bae1 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/CHANGELOG.md @@ -0,0 +1,19 @@ +# Release History + +## 1.0.0-beta.2 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + +## 1.0.0-beta.1 (2025-02-26) + +- Azure Resource Manager Migration Assessment client library for Java. This package contains Microsoft Azure SDK for Migration Assessment Management SDK. Azure Migrate Resource Provider management API. Package tag package-2023-03. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). +### Features Added + +- Initial release for the azure-resourcemanager-migration-assessment Java SDK. + diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/README.md b/sdk/migration/azure-resourcemanager-migration-assessment/README.md new file mode 100644 index 000000000000..11f0f69c57f1 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/README.md @@ -0,0 +1,102 @@ +# Azure Resource Manager Migration Assessment client library for Java + +Azure Resource Manager Migration Assessment client library for Java. + +This package contains Microsoft Azure SDK for Migration Assessment Management SDK. Azure Migrate Resource Provider management API. Package tag package-2023-03. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). + +## We'd love to hear your feedback + +We're always working on improving our products and the way we communicate with our users. So we'd love to learn what's working and how we can do better. + +If you haven't already, please take a few minutes to [complete this short survey][survey] we have put together. + +Thank you in advance for your collaboration. We really appreciate your time! + +## Documentation + +Various documentation is available to help you get started + +- [API reference documentation][docs] + +## Getting started + +### Prerequisites + +- [Java Development Kit (JDK)][jdk] with version 8 or above +- [Azure Subscription][azure_subscription] + +### Adding the package to your product + +[//]: # ({x-version-update-start;com.azure.resourcemanager:azure-resourcemanager-migration-assessment;current}) +```xml + + com.azure.resourcemanager + azure-resourcemanager-migration-assessment + 1.0.0-beta.2 + +``` +[//]: # ({x-version-update-end}) + +### Include the recommended packages + +Azure Management Libraries require a `TokenCredential` implementation for authentication and an `HttpClient` implementation for HTTP client. + +[Azure Identity][azure_identity] and [Azure Core Netty HTTP][azure_core_http_netty] packages provide the default implementation. + +### Authentication + +Microsoft Entra ID token authentication relies on the [credential class][azure_identity_credentials] from [Azure Identity][azure_identity] package. + +Azure subscription ID can be configured via `AZURE_SUBSCRIPTION_ID` environment variable. + +Assuming the use of the `DefaultAzureCredential` credential class, the client can be authenticated using the following code: + +```java +AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); +TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); +MigrationAssessmentManager manager = MigrationAssessmentManager + .authenticate(credential, profile); +``` + +The sample code assumes global Azure. Please change the `AzureCloud.AZURE_PUBLIC_CLOUD` variable if otherwise. + +See [Authentication][authenticate] for more options. + +## Key concepts + +See [API design][design] for general introduction on design and key concepts on Azure Management Libraries. + +## Examples + +[Code snippets and samples](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/migration/azure-resourcemanager-migration-assessment/SAMPLE.md) + + +## Troubleshooting + +## Next steps + +## Contributing + +For details on contributing to this repository, see the [contributing guide][cg]. + +This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit . + +When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repositories using our CLA. + +This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For more information see the [Code of Conduct FAQ][coc_faq] or contact with any additional questions or comments. + + +[survey]: https://microsoft.qualtrics.com/jfe/form/SV_ehN0lIk2FKEBkwd?Q_CHL=DOCS +[docs]: https://azure.github.io/azure-sdk-for-java/ +[jdk]: https://learn.microsoft.com/azure/developer/java/fundamentals/ +[azure_subscription]: https://azure.microsoft.com/free/ +[azure_identity]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/identity/azure-identity +[azure_identity_credentials]: https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/identity/azure-identity#credentials +[azure_core_http_netty]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/core/azure-core-http-netty +[authenticate]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/resourcemanager/docs/AUTH.md +[design]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/resourcemanager/docs/DESIGN.md +[cg]: https://github.com/Azure/azure-sdk-for-java/blob/main/CONTRIBUTING.md +[coc]: https://opensource.microsoft.com/codeofconduct/ +[coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/SAMPLE.md b/sdk/migration/azure-resourcemanager-migration-assessment/SAMPLE.md new file mode 100644 index 000000000000..e3cbddb3ef31 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/SAMPLE.md @@ -0,0 +1,2425 @@ +# Code snippets and samples + + +## AssessedMachinesOperations + +- [Get](#assessedmachinesoperations_get) +- [ListByAssessment](#assessedmachinesoperations_listbyassessment) + +## AssessedSqlDatabaseV2Operations + +- [Get](#assessedsqldatabasev2operations_get) +- [ListBySqlAssessmentV2](#assessedsqldatabasev2operations_listbysqlassessmentv2) + +## AssessedSqlInstanceV2Operations + +- [Get](#assessedsqlinstancev2operations_get) +- [ListBySqlAssessmentV2](#assessedsqlinstancev2operations_listbysqlassessmentv2) + +## AssessedSqlMachinesOperations + +- [Get](#assessedsqlmachinesoperations_get) +- [ListBySqlAssessmentV2](#assessedsqlmachinesoperations_listbysqlassessmentv2) + +## AssessedSqlRecommendedEntityOperations + +- [Get](#assessedsqlrecommendedentityoperations_get) +- [ListBySqlAssessmentV2](#assessedsqlrecommendedentityoperations_listbysqlassessmentv2) + +## AssessmentOptionsOperations + +- [Get](#assessmentoptionsoperations_get) +- [ListByAssessmentProject](#assessmentoptionsoperations_listbyassessmentproject) + +## AssessmentProjectSummaryOperations + +- [Get](#assessmentprojectsummaryoperations_get) +- [ListByAssessmentProject](#assessmentprojectsummaryoperations_listbyassessmentproject) + +## AssessmentProjectsOperations + +- [Create](#assessmentprojectsoperations_create) +- [Delete](#assessmentprojectsoperations_delete) +- [GetByResourceGroup](#assessmentprojectsoperations_getbyresourcegroup) +- [List](#assessmentprojectsoperations_list) +- [ListByResourceGroup](#assessmentprojectsoperations_listbyresourcegroup) +- [Update](#assessmentprojectsoperations_update) + +## AssessmentsOperations + +- [Create](#assessmentsoperations_create) +- [Delete](#assessmentsoperations_delete) +- [DownloadUrl](#assessmentsoperations_downloadurl) +- [Get](#assessmentsoperations_get) +- [ListByGroup](#assessmentsoperations_listbygroup) + +## AvsAssessedMachinesOperations + +- [Get](#avsassessedmachinesoperations_get) +- [ListByAvsAssessment](#avsassessedmachinesoperations_listbyavsassessment) + +## AvsAssessmentOptionsOperations + +- [Get](#avsassessmentoptionsoperations_get) +- [ListByAssessmentProject](#avsassessmentoptionsoperations_listbyassessmentproject) + +## AvsAssessmentsOperations + +- [Create](#avsassessmentsoperations_create) +- [Delete](#avsassessmentsoperations_delete) +- [DownloadUrl](#avsassessmentsoperations_downloadurl) +- [Get](#avsassessmentsoperations_get) +- [ListByGroup](#avsassessmentsoperations_listbygroup) + +## GroupsOperations + +- [Create](#groupsoperations_create) +- [Delete](#groupsoperations_delete) +- [Get](#groupsoperations_get) +- [ListByAssessmentProject](#groupsoperations_listbyassessmentproject) +- [UpdateMachines](#groupsoperations_updatemachines) + +## HypervCollectorsOperations + +- [Create](#hypervcollectorsoperations_create) +- [Delete](#hypervcollectorsoperations_delete) +- [Get](#hypervcollectorsoperations_get) +- [ListByAssessmentProject](#hypervcollectorsoperations_listbyassessmentproject) + +## ImportCollectorsOperations + +- [Create](#importcollectorsoperations_create) +- [Delete](#importcollectorsoperations_delete) +- [Get](#importcollectorsoperations_get) +- [ListByAssessmentProject](#importcollectorsoperations_listbyassessmentproject) + +## MachinesOperations + +- [Get](#machinesoperations_get) +- [ListByAssessmentProject](#machinesoperations_listbyassessmentproject) + +## Operations + +- [List](#operations_list) + +## PrivateEndpointConnectionOperations + +- [Delete](#privateendpointconnectionoperations_delete) +- [Get](#privateendpointconnectionoperations_get) +- [ListByAssessmentProject](#privateendpointconnectionoperations_listbyassessmentproject) +- [Update](#privateendpointconnectionoperations_update) + +## PrivateLinkResourceOperations + +- [Get](#privatelinkresourceoperations_get) +- [ListByAssessmentProject](#privatelinkresourceoperations_listbyassessmentproject) + +## ServerCollectorsOperations + +- [Create](#servercollectorsoperations_create) +- [Delete](#servercollectorsoperations_delete) +- [Get](#servercollectorsoperations_get) +- [ListByAssessmentProject](#servercollectorsoperations_listbyassessmentproject) + +## SqlAssessmentOptionsOperations + +- [Get](#sqlassessmentoptionsoperations_get) +- [ListByAssessmentProject](#sqlassessmentoptionsoperations_listbyassessmentproject) + +## SqlAssessmentV2Operations + +- [Create](#sqlassessmentv2operations_create) +- [Delete](#sqlassessmentv2operations_delete) +- [DownloadUrl](#sqlassessmentv2operations_downloadurl) +- [Get](#sqlassessmentv2operations_get) +- [ListByGroup](#sqlassessmentv2operations_listbygroup) + +## SqlAssessmentV2SummaryOperations + +- [Get](#sqlassessmentv2summaryoperations_get) +- [ListBySqlAssessmentV2](#sqlassessmentv2summaryoperations_listbysqlassessmentv2) + +## SqlCollectorOperations + +- [Create](#sqlcollectoroperations_create) +- [Delete](#sqlcollectoroperations_delete) +- [Get](#sqlcollectoroperations_get) +- [ListByAssessmentProject](#sqlcollectoroperations_listbyassessmentproject) + +## VmwareCollectorsOperations + +- [Create](#vmwarecollectorsoperations_create) +- [Delete](#vmwarecollectorsoperations_delete) +- [Get](#vmwarecollectorsoperations_get) +- [ListByAssessmentProject](#vmwarecollectorsoperations_listbyassessmentproject) +### AssessedMachinesOperations_Get + +```java +/** + * Samples for AssessedMachinesOperations Get. + */ +public final class AssessedMachinesOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessedMachinesOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: AssessedMachinesOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessedMachinesOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessedMachinesOperations() + .getWithResponse("rgopenapi", "pavqtntysjn", "smawqdmhfngray", "qjlumxyqsitd", "oqxjeheiipjmuo", + com.azure.core.util.Context.NONE); + } +} +``` + +### AssessedMachinesOperations_ListByAssessment + +```java +/** + * Samples for AssessedMachinesOperations ListByAssessment. + */ +public final class AssessedMachinesOperationsListByAssessmentSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessedMachinesOperations_ListByAssessment_MaximumSet_Gen.json + */ + /** + * Sample code: AssessedMachinesOperations_ListByAssessment_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessedMachinesOperationsListByAssessmentMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessedMachinesOperations() + .listByAssessment("rgopenapi", "sloqixzfjk", "kjuepxerwseq", "rhzcmubwrrkhtocsibu", "sbkdovsfqldhdb", 10, + "hbyseetshbplfkjmpjhsiurqgt", 25, com.azure.core.util.Context.NONE); + } +} +``` + +### AssessedSqlDatabaseV2Operations_Get + +```java +/** + * Samples for AssessedSqlDatabaseV2Operations Get. + */ +public final class AssessedSqlDatabaseV2OperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessedSqlDatabaseV2Operations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: AssessedSqlDatabaseV2Operations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessedSqlDatabaseV2OperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessedSqlDatabaseV2Operations() + .getWithResponse("rgmigrate", "fci-test6904project", "test_fci_hadr", "test_swagger_1", + "858eb860-9e07-417c-91b6-bca1bffb3bf5", com.azure.core.util.Context.NONE); + } +} +``` + +### AssessedSqlDatabaseV2Operations_ListBySqlAssessmentV2 + +```java +/** + * Samples for AssessedSqlDatabaseV2Operations ListBySqlAssessmentV2. + */ +public final class AssessedSqlDatabaseV2OperationsListBySqlAssessmentV2Samples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessedSqlDatabaseV2Operations_ListBySqlAssessmentV2_MaximumSet_Gen.json + */ + /** + * Sample code: AssessedSqlDatabaseV2Operations_ListBySqlAssessmentV2_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessedSqlDatabaseV2OperationsListBySqlAssessmentV2MaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessedSqlDatabaseV2Operations() + .listBySqlAssessmentV2("rgmigrate", "fci-test6904project", "test_fci_hadr", "test_swagger_1", + "(contains(Properties/DatabaseName,'adv130'))", 23, null, 1, com.azure.core.util.Context.NONE); + } +} +``` + +### AssessedSqlInstanceV2Operations_Get + +```java +/** + * Samples for AssessedSqlInstanceV2Operations Get. + */ +public final class AssessedSqlInstanceV2OperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessedSqlInstanceV2Operations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: AssessedSqlInstanceV2Operations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessedSqlInstanceV2OperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessedSqlInstanceV2Operations() + .getWithResponse("rgmigrate", "fci-test6904project", "test_fci_hadr", "test_swagger_1", + "3c6574cf-b4e1-4fdc-93db-6bbcc570dda2", com.azure.core.util.Context.NONE); + } +} +``` + +### AssessedSqlInstanceV2Operations_ListBySqlAssessmentV2 + +```java +/** + * Samples for AssessedSqlInstanceV2Operations ListBySqlAssessmentV2. + */ +public final class AssessedSqlInstanceV2OperationsListBySqlAssessmentV2Samples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessedSqlInstanceV2Operations_ListBySqlAssessmentV2_MaximumSet_Gen.json + */ + /** + * Sample code: AssessedSqlInstanceV2Operations_ListBySqlAssessmentV2_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessedSqlInstanceV2OperationsListBySqlAssessmentV2MaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessedSqlInstanceV2Operations() + .listBySqlAssessmentV2("rgmigrate", "fci-test6904project", "test_fci_hadr", "test_swagger_1", + "(contains(Properties/InstanceName,'MSSQLSERVER'))", 23, null, 1, com.azure.core.util.Context.NONE); + } +} +``` + +### AssessedSqlMachinesOperations_Get + +```java +/** + * Samples for AssessedSqlMachinesOperations Get. + */ +public final class AssessedSqlMachinesOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessedSqlMachinesOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: AssessedSqlMachinesOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessedSqlMachinesOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessedSqlMachinesOperations() + .getWithResponse("rgmigrate", "fci-test6904project", "test_fci_hadr", "test_swagger_1", + "cc64c9dc-b38e-435d-85ad-d509df5d92c6", com.azure.core.util.Context.NONE); + } +} +``` + +### AssessedSqlMachinesOperations_ListBySqlAssessmentV2 + +```java +/** + * Samples for AssessedSqlMachinesOperations ListBySqlAssessmentV2. + */ +public final class AssessedSqlMachinesOperationsListBySqlAssessmentV2Samples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessedSqlMachinesOperations_ListBySqlAssessmentV2_MaximumSet_Gen.json + */ + /** + * Sample code: AssessedSqlMachinesOperations_ListBySqlAssessmentV2_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessedSqlMachinesOperationsListBySqlAssessmentV2MaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessedSqlMachinesOperations() + .listBySqlAssessmentV2("rgmigrate", "fci-test6904project", "test_fci_hadr", "test_swagger_1", + "(contains(Properties/DisplayName,'SQLHAVM17'))", 23, null, 1, com.azure.core.util.Context.NONE); + } +} +``` + +### AssessedSqlRecommendedEntityOperations_Get + +```java +/** + * Samples for AssessedSqlRecommendedEntityOperations Get. + */ +public final class AssessedSqlRecommendedEntityOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessedSqlRecommendedEntityOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: AssessedSqlRecommendedEntityOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessedSqlRecommendedEntityOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessedSqlRecommendedEntityOperations() + .getWithResponse("rgmigrate", "fci-test6904project", "test_fci_hadr", "test_swagger_1", + "cc64c9dc-b38e-435d-85ad-d509df5d92c6", com.azure.core.util.Context.NONE); + } +} +``` + +### AssessedSqlRecommendedEntityOperations_ListBySqlAssessmentV2 + +```java +/** + * Samples for AssessedSqlRecommendedEntityOperations ListBySqlAssessmentV2. + */ +public final class AssessedSqlRecommendedEntityOperationsListBySqlAssessmentV2Samples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessedSqlRecommendedEntityOperations_ListBySqlAssessmentV2_MaximumSet_Gen.json + */ + /** + * Sample code: AssessedSqlRecommendedEntityOperations_ListBySqlAssessmentV2_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessedSqlRecommendedEntityOperationsListBySqlAssessmentV2MaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessedSqlRecommendedEntityOperations() + .listBySqlAssessmentV2("rgmigrate", "fci-test6904project", "test_fci_hadr", "test_swagger_1", + "(contains(Properties/InstanceName,'MSSQLSERVER'))", 23, null, 1, com.azure.core.util.Context.NONE); + } +} +``` + +### AssessmentOptionsOperations_Get + +```java +/** + * Samples for AssessmentOptionsOperations Get. + */ +public final class AssessmentOptionsOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentOptionsOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentOptionsOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentOptionsOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessmentOptionsOperations() + .getWithResponse("ayagrawrg", "app18700project", "default", com.azure.core.util.Context.NONE); + } +} +``` + +### AssessmentOptionsOperations_ListByAssessmentProject + +```java +/** + * Samples for AssessmentOptionsOperations ListByAssessmentProject. + */ +public final class AssessmentOptionsOperationsListByAssessmentProjectSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentOptionsOperations_ListByAssessmentProject_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentOptionsOperations_ListByAssessmentProject_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentOptionsOperationsListByAssessmentProjectMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessmentOptionsOperations() + .listByAssessmentProject("rgmigrate", "fhodvffhuoqwbysrrqbizete", com.azure.core.util.Context.NONE); + } +} +``` + +### AssessmentProjectSummaryOperations_Get + +```java +/** + * Samples for AssessmentProjectSummaryOperations Get. + */ +public final class AssessmentProjectSummaryOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentProjectSummaryOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentProjectSummaryOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentProjectSummaryOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessmentProjectSummaryOperations() + .getWithResponse("piyushapp1", "PiyushApp15328project", "default", com.azure.core.util.Context.NONE); + } +} +``` + +### AssessmentProjectSummaryOperations_ListByAssessmentProject + +```java +/** + * Samples for AssessmentProjectSummaryOperations ListByAssessmentProject. + */ +public final class AssessmentProjectSummaryOperationsListByAssessmentProjectSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentProjectSummaryOperations_ListByAssessmentProject_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentProjectSummaryOperations_ListByAssessmentProject_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentProjectSummaryOperationsListByAssessmentProjectMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessmentProjectSummaryOperations() + .listByAssessmentProject("piyushapp1", "PiyushApp15328project", com.azure.core.util.Context.NONE); + } +} +``` + +### AssessmentProjectsOperations_Create + +```java +import com.azure.resourcemanager.migration.assessment.models.ProjectProperties; +import com.azure.resourcemanager.migration.assessment.models.ProjectStatus; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.util.HashMap; +import java.util.Map; + +/** + * Samples for AssessmentProjectsOperations Create. + */ +public final class AssessmentProjectsOperationsCreateSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentProjectsOperations_Create_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentProjectsOperations_Create_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentProjectsOperationsCreateMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessmentProjectsOperations() + .define("sakanwar1204project") + .withRegion("southeastasia") + .withExistingResourceGroup("sakanwar") + .withTags(mapOf("Migrate Project", "sakanwar-PE-SEA")) + .withProperties(new ProjectProperties().withProvisioningState(ProvisioningState.SUCCEEDED) + .withAssessmentSolutionId( + "/subscriptions/4bd2aa0f-2bd2-4d67-91a8-5a4533d58600/resourceGroups/sakanwar/providers/Microsoft.Storage/storageAccounts/sakanwar1204usa") + .withProjectStatus(ProjectStatus.ACTIVE) + .withPublicNetworkAccess("Disabled") + .withCustomerStorageAccountArmId( + "/subscriptions/4bd2aa0f-2bd2-4d67-91a8-5a4533d58600/resourceGroups/sakanwar/providers/Microsoft.Storage/storageAccounts/sakanwar1204usa")) + .create(); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} +``` + +### AssessmentProjectsOperations_Delete + +```java +/** + * Samples for AssessmentProjectsOperations Delete. + */ +public final class AssessmentProjectsOperationsDeleteSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentProjectsOperations_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentProjectsOperations_Delete_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentProjectsOperationsDeleteMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessmentProjectsOperations() + .deleteByResourceGroupWithResponse("rgmigrate", "zqrsyncwahgydqvwuchkfd", com.azure.core.util.Context.NONE); + } +} +``` + +### AssessmentProjectsOperations_GetByResourceGroup + +```java +/** + * Samples for AssessmentProjectsOperations GetByResourceGroup. + */ +public final class AssessmentProjectsOperationsGetByResourceGroupSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentProjectsOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentProjectsOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentProjectsOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessmentProjectsOperations() + .getByResourceGroupWithResponse("sakanwar", "sakanwar1204project", com.azure.core.util.Context.NONE); + } +} +``` + +### AssessmentProjectsOperations_List + +```java +/** + * Samples for AssessmentProjectsOperations List. + */ +public final class AssessmentProjectsOperationsListSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentProjectsOperations_ListBySubscription_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentProjectsOperations_ListBySubscription_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentProjectsOperationsListBySubscriptionMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessmentProjectsOperations().list(com.azure.core.util.Context.NONE); + } +} +``` + +### AssessmentProjectsOperations_ListByResourceGroup + +```java +/** + * Samples for AssessmentProjectsOperations ListByResourceGroup. + */ +public final class AssessmentProjectsOperationsListByResourceGroupSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentProjectsOperations_ListByResourceGroup_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentProjectsOperations_ListByResourceGroup_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentProjectsOperationsListByResourceGroupMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessmentProjectsOperations().listByResourceGroup("sakanwar", com.azure.core.util.Context.NONE); + } +} +``` + +### AssessmentProjectsOperations_Update + +```java +import com.azure.resourcemanager.migration.assessment.models.AssessmentProject; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProjectUpdateProperties; +import com.azure.resourcemanager.migration.assessment.models.ProjectStatus; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.util.HashMap; +import java.util.Map; + +/** + * Samples for AssessmentProjectsOperations Update. + */ +public final class AssessmentProjectsOperationsUpdateSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentProjectsOperations_Update_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentProjectsOperations_Update_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentProjectsOperationsUpdateMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + AssessmentProject resource = manager.assessmentProjectsOperations() + .getByResourceGroupWithResponse("sakanwar", "sakanwar1204project", com.azure.core.util.Context.NONE) + .getValue(); + resource.update() + .withTags(mapOf("Migrate Project", "sakanwar-PE-SEA")) + .withProperties(new AssessmentProjectUpdateProperties().withAssessmentSolutionId( + "/subscriptions/4bd2aa0f-2bd2-4d67-91a8-5a4533d58600/resourceGroups/sakanwar/providers/Microsoft.Storage/storageAccounts/sakanwar1204usa") + .withProjectStatus(ProjectStatus.ACTIVE) + .withPublicNetworkAccess("Disabled") + .withCustomerStorageAccountArmId( + "/subscriptions/4bd2aa0f-2bd2-4d67-91a8-5a4533d58600/resourceGroups/sakanwar/providers/Microsoft.Storage/storageAccounts/sakanwar1204usa") + .withProvisioningState(ProvisioningState.SUCCEEDED)) + .apply(); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} +``` + +### AssessmentsOperations_Create + +```java +import com.azure.resourcemanager.migration.assessment.models.AssessmentSizingCriterion; +import com.azure.resourcemanager.migration.assessment.models.AzureCurrency; +import com.azure.resourcemanager.migration.assessment.models.AzureDiskType; +import com.azure.resourcemanager.migration.assessment.models.AzureHybridUseBenefit; +import com.azure.resourcemanager.migration.assessment.models.AzureOfferCode; +import com.azure.resourcemanager.migration.assessment.models.AzurePricingTier; +import com.azure.resourcemanager.migration.assessment.models.AzureReservedInstance; +import com.azure.resourcemanager.migration.assessment.models.AzureStorageRedundancy; +import com.azure.resourcemanager.migration.assessment.models.AzureVmFamily; +import com.azure.resourcemanager.migration.assessment.models.MachineAssessmentProperties; +import com.azure.resourcemanager.migration.assessment.models.Percentile; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import com.azure.resourcemanager.migration.assessment.models.TimeRange; +import com.azure.resourcemanager.migration.assessment.models.VmUptime; +import java.time.OffsetDateTime; +import java.util.Arrays; + +/** + * Samples for AssessmentsOperations Create. + */ +public final class AssessmentsOperationsCreateSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentsOperations_Create_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentsOperations_Create_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentsOperationsCreateMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessmentsOperations() + .define("asm1") + .withExistingGroup("ayagrawrg", "app18700project", "kuchatur-test") + .withProperties(new MachineAssessmentProperties().withProvisioningState(ProvisioningState.SUCCEEDED) + .withEaSubscriptionId("kwsu") + .withAzurePricingTier(AzurePricingTier.STANDARD) + .withAzureStorageRedundancy(AzureStorageRedundancy.UNKNOWN) + .withReservedInstance(AzureReservedInstance.NONE) + .withAzureHybridUseBenefit(AzureHybridUseBenefit.UNKNOWN) + .withAzureDiskTypes(Arrays.asList(AzureDiskType.PREMIUM, AzureDiskType.STANDARD_SSD)) + .withAzureVmFamilies( + Arrays.asList(AzureVmFamily.D_SERIES, AzureVmFamily.LSV2_SERIES, AzureVmFamily.M_SERIES, + AzureVmFamily.MDSV2_SERIES, AzureVmFamily.MSV2_SERIES, AzureVmFamily.MV2_SERIES)) + .withVmUptime(new VmUptime().withDaysPerMonth(13).withHoursPerDay(26)) + .withAzureLocation("njxbwdtsxzhichsnk") + .withAzureOfferCode(AzureOfferCode.UNKNOWN) + .withCurrency(AzureCurrency.UNKNOWN) + .withScalingFactor(24.0F) + .withPercentile(Percentile.PERCENTILE50) + .withTimeRange(TimeRange.DAY) + .withPerfDataStartTime(OffsetDateTime.parse("2023-09-26T09:36:48.491Z")) + .withPerfDataEndTime(OffsetDateTime.parse("2023-09-26T09:36:48.491Z")) + .withDiscountPercentage(6.0F) + .withSizingCriterion(AssessmentSizingCriterion.PERFORMANCE_BASED)) + .create(); + } +} +``` + +### AssessmentsOperations_Delete + +```java +/** + * Samples for AssessmentsOperations Delete. + */ +public final class AssessmentsOperationsDeleteSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentsOperations_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentsOperations_Delete_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentsOperationsDeleteMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessmentsOperations() + .deleteWithResponse("ayagrawrg", "app18700project", "kuchatur-test", "asm1", + com.azure.core.util.Context.NONE); + } +} +``` + +### AssessmentsOperations_DownloadUrl + +```java +import com.azure.core.management.serializer.SerializerFactory; +import com.azure.core.util.serializer.SerializerEncoding; +import java.io.IOException; + +/** + * Samples for AssessmentsOperations DownloadUrl. + */ +public final class AssessmentsOperationsDownloadUrlSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentsOperations_DownloadUrl_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentsOperations_DownloadUrl_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentsOperationsDownloadUrlMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) throws IOException { + manager.assessmentsOperations() + .downloadUrl("ayagrawrg", "app18700project", "kuchatur-test", "asm1", + SerializerFactory.createDefaultManagementSerializerAdapter() + .deserialize("{}", Object.class, SerializerEncoding.JSON), + com.azure.core.util.Context.NONE); + } +} +``` + +### AssessmentsOperations_Get + +```java +/** + * Samples for AssessmentsOperations Get. + */ +public final class AssessmentsOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentsOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentsOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentsOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessmentsOperations() + .getWithResponse("ayagrawrg", "app18700project", "kuchatur-test", "asm1", com.azure.core.util.Context.NONE); + } +} +``` + +### AssessmentsOperations_ListByGroup + +```java +/** + * Samples for AssessmentsOperations ListByGroup. + */ +public final class AssessmentsOperationsListByGroupSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentsOperations_ListByGroup_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentsOperations_ListByGroup_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentsOperationsListByGroupMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessmentsOperations() + .listByGroup("ayagrawrg", "app18700project", "kuchatur-test", com.azure.core.util.Context.NONE); + } +} +``` + +### AvsAssessedMachinesOperations_Get + +```java +/** + * Samples for AvsAssessedMachinesOperations Get. + */ +public final class AvsAssessedMachinesOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AvsAssessedMachinesOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: AvsAssessedMachinesOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void avsAssessedMachinesOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.avsAssessedMachinesOperations() + .getWithResponse("ayagrawrg", "app18700project", "kuchatur-test", "asm2", + "b6d6fc6f-796f-4c16-96af-a6d22e0f12f7", com.azure.core.util.Context.NONE); + } +} +``` + +### AvsAssessedMachinesOperations_ListByAvsAssessment + +```java +/** + * Samples for AvsAssessedMachinesOperations ListByAvsAssessment. + */ +public final class AvsAssessedMachinesOperationsListByAvsAssessmentSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AvsAssessedMachinesOperations_ListByAvsAssessment_MaximumSet_Gen.json + */ + /** + * Sample code: AvsAssessedMachinesOperations_ListByAvsAssessment_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void avsAssessedMachinesOperationsListByAvsAssessmentMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.avsAssessedMachinesOperations() + .listByAvsAssessment("ayagrawrg", "app18700project", "kuchatur-test", "asm2", "ujmwhhuloficljxcjyc", 6, + "qwrjeiukbcicfrkqlqsfukfc", 19, com.azure.core.util.Context.NONE); + } +} +``` + +### AvsAssessmentOptionsOperations_Get + +```java +/** + * Samples for AvsAssessmentOptionsOperations Get. + */ +public final class AvsAssessmentOptionsOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AvsAssessmentOptionsOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: AvsAssessmentOptionsOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void avsAssessmentOptionsOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.avsAssessmentOptionsOperations() + .getWithResponse("ayagrawrg", "app18700project", "default", com.azure.core.util.Context.NONE); + } +} +``` + +### AvsAssessmentOptionsOperations_ListByAssessmentProject + +```java +/** + * Samples for AvsAssessmentOptionsOperations ListByAssessmentProject. + */ +public final class AvsAssessmentOptionsOperationsListByAssessmentProjectSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AvsAssessmentOptionsOperations_ListByAssessmentProject_MaximumSet_Gen.json + */ + /** + * Sample code: AvsAssessmentOptionsOperations_ListByAssessmentProject_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void avsAssessmentOptionsOperationsListByAssessmentProjectMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.avsAssessmentOptionsOperations() + .listByAssessmentProject("ayagrawrg", "app18700project", com.azure.core.util.Context.NONE); + } +} +``` + +### AvsAssessmentsOperations_Create + +```java +import com.azure.resourcemanager.migration.assessment.models.AssessmentSizingCriterion; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessmentProperties; +import com.azure.resourcemanager.migration.assessment.models.AzureAvsNodeType; +import com.azure.resourcemanager.migration.assessment.models.AzureCurrency; +import com.azure.resourcemanager.migration.assessment.models.AzureLocation; +import com.azure.resourcemanager.migration.assessment.models.AzureOfferCode; +import com.azure.resourcemanager.migration.assessment.models.AzureReservedInstance; +import com.azure.resourcemanager.migration.assessment.models.FttAndRaidLevel; +import com.azure.resourcemanager.migration.assessment.models.Percentile; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import com.azure.resourcemanager.migration.assessment.models.TimeRange; +import java.time.OffsetDateTime; + +/** + * Samples for AvsAssessmentsOperations Create. + */ +public final class AvsAssessmentsOperationsCreateSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AvsAssessmentsOperations_Create_MaximumSet_Gen.json + */ + /** + * Sample code: AvsAssessmentsOperations_Create_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void avsAssessmentsOperationsCreateMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.avsAssessmentsOperations() + .define("asm2") + .withExistingGroup("ayagrawrg", "app18700project", "kuchatur-test") + .withProperties(new AvsAssessmentProperties().withProvisioningState(ProvisioningState.SUCCEEDED) + .withFailuresToTolerateAndRaidLevel(FttAndRaidLevel.FTT1RAID1) + .withVcpuOversubscription(4.0F) + .withNodeType(AzureAvsNodeType.AV36) + .withReservedInstance(AzureReservedInstance.RI3YEAR) + .withMemOvercommit(1.0F) + .withDedupeCompression(1.5F) + .withIsStretchClusterEnabled(true) + .withAzureLocation(AzureLocation.EAST_US) + .withAzureOfferCode(AzureOfferCode.MSAZR0003P) + .withCurrency(AzureCurrency.USD) + .withScalingFactor(1.0F) + .withPercentile(Percentile.PERCENTILE95) + .withTimeRange(TimeRange.DAY) + .withPerfDataStartTime(OffsetDateTime.parse("2023-09-25T13:35:56.5671462Z")) + .withPerfDataEndTime(OffsetDateTime.parse("2023-09-26T13:35:56.5671462Z")) + .withDiscountPercentage(0.0F) + .withSizingCriterion(AssessmentSizingCriterion.AS_ON_PREMISES)) + .create(); + } +} +``` + +### AvsAssessmentsOperations_Delete + +```java +/** + * Samples for AvsAssessmentsOperations Delete. + */ +public final class AvsAssessmentsOperationsDeleteSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AvsAssessmentsOperations_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: AvsAssessmentsOperations_Delete_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void avsAssessmentsOperationsDeleteMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.avsAssessmentsOperations() + .deleteWithResponse("ayagrawrg", "app18700project", "kuchatur-test", "asm2", + com.azure.core.util.Context.NONE); + } +} +``` + +### AvsAssessmentsOperations_DownloadUrl + +```java +import com.azure.core.management.serializer.SerializerFactory; +import com.azure.core.util.serializer.SerializerEncoding; +import java.io.IOException; + +/** + * Samples for AvsAssessmentsOperations DownloadUrl. + */ +public final class AvsAssessmentsOperationsDownloadUrlSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AvsAssessmentsOperations_DownloadUrl_MaximumSet_Gen.json + */ + /** + * Sample code: AvsAssessmentsOperations_DownloadUrl_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void avsAssessmentsOperationsDownloadUrlMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) throws IOException { + manager.avsAssessmentsOperations() + .downloadUrl("ayagrawrg", "app18700project", "kuchatur-test", "asm2", + SerializerFactory.createDefaultManagementSerializerAdapter() + .deserialize("{}", Object.class, SerializerEncoding.JSON), + com.azure.core.util.Context.NONE); + } +} +``` + +### AvsAssessmentsOperations_Get + +```java +/** + * Samples for AvsAssessmentsOperations Get. + */ +public final class AvsAssessmentsOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AvsAssessmentsOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: AvsAssessmentsOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void avsAssessmentsOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.avsAssessmentsOperations() + .getWithResponse("ayagrawrg", "app18700project", "kuchatur-test", "asm2", com.azure.core.util.Context.NONE); + } +} +``` + +### AvsAssessmentsOperations_ListByGroup + +```java +/** + * Samples for AvsAssessmentsOperations ListByGroup. + */ +public final class AvsAssessmentsOperationsListByGroupSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AvsAssessmentsOperations_ListByGroup_MaximumSet_Gen.json + */ + /** + * Sample code: AvsAssessmentsOperations_ListByGroup_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void avsAssessmentsOperationsListByGroupMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.avsAssessmentsOperations() + .listByGroup("ayagrawrg", "app18700project", "kuchatur-test", com.azure.core.util.Context.NONE); + } +} +``` + +### GroupsOperations_Create + +```java +import com.azure.resourcemanager.migration.assessment.models.GroupProperties; +import com.azure.resourcemanager.migration.assessment.models.GroupType; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; + +/** + * Samples for GroupsOperations Create. + */ +public final class GroupsOperationsCreateSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * GroupsOperations_Create_MaximumSet_Gen.json + */ + /** + * Sample code: GroupsOperations_Create_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void groupsOperationsCreateMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.groupsOperations() + .define("kuchatur-test") + .withExistingAssessmentProject("ayagrawrg", "app18700project") + .withProperties(new GroupProperties().withProvisioningState(ProvisioningState.SUCCEEDED) + .withGroupType(GroupType.DEFAULT)) + .create(); + } +} +``` + +### GroupsOperations_Delete + +```java +/** + * Samples for GroupsOperations Delete. + */ +public final class GroupsOperationsDeleteSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * GroupsOperations_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: GroupsOperations_Delete_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void groupsOperationsDeleteMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.groupsOperations() + .deleteWithResponse("ayagrawrg", "app18700project", "kuchatur-test", com.azure.core.util.Context.NONE); + } +} +``` + +### GroupsOperations_Get + +```java +/** + * Samples for GroupsOperations Get. + */ +public final class GroupsOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * GroupsOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: GroupsOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void groupsOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.groupsOperations() + .getWithResponse("ayagrawrg", "app18700project", "kuchatur-test", com.azure.core.util.Context.NONE); + } +} +``` + +### GroupsOperations_ListByAssessmentProject + +```java +/** + * Samples for GroupsOperations ListByAssessmentProject. + */ +public final class GroupsOperationsListByAssessmentProjectSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * GroupsOperations_ListByAssessmentProject_MaximumSet_Gen.json + */ + /** + * Sample code: GroupsOperations_ListByAssessmentProject_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void groupsOperationsListByAssessmentProjectMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.groupsOperations() + .listByAssessmentProject("ayagrawrg", "app18700project", com.azure.core.util.Context.NONE); + } +} +``` + +### GroupsOperations_UpdateMachines + +```java +import com.azure.resourcemanager.migration.assessment.models.GroupBodyProperties; +import com.azure.resourcemanager.migration.assessment.models.GroupUpdateOperation; +import com.azure.resourcemanager.migration.assessment.models.UpdateGroupBody; +import java.util.Arrays; + +/** + * Samples for GroupsOperations UpdateMachines. + */ +public final class GroupsOperationsUpdateMachinesSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * GroupsOperations_UpdateMachines_MaximumSet_Gen.json + */ + /** + * Sample code: GroupsOperations_UpdateMachines_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void groupsOperationsUpdateMachinesMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.groupsOperations() + .updateMachines("ayagrawrg", "app18700project", "kuchatur-test", new UpdateGroupBody().withEtag("*") + .withProperties(new GroupBodyProperties().withOperationType(GroupUpdateOperation.ADD) + .withMachines(Arrays.asList( + "/subscriptions/4bd2aa0f-2bd2-4d67-91a8-5a4533d58600/resourceGroups/ayagrawrg/providers/Microsoft.Migrate/assessmentprojects/app18700project/machines/18895660-c5e5-4247-8cfc-cd24e1fe57f3"))), + com.azure.core.util.Context.NONE); + } +} +``` + +### HypervCollectorsOperations_Create + +```java +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentSpnPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBaseWithAgent; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.time.OffsetDateTime; + +/** + * Samples for HypervCollectorsOperations Create. + */ +public final class HypervCollectorsOperationsCreateSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * HypervCollectorsOperations_Create_MaximumSet_Gen.json + */ + /** + * Sample code: HypervCollectorsOperations_Create_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void hypervCollectorsOperationsCreateMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.hypervCollectorsOperations() + .define("test-697cecollector") + .withExistingAssessmentProject("ayagrawRG", "app18700project") + .withProperties(new CollectorPropertiesBaseWithAgent().withProvisioningState(ProvisioningState.SUCCEEDED) + .withAgentProperties(new CollectorAgentPropertiesBase().withId("12f1d90f-b3fa-4926-8893-e56803a09af0") + .withVersion("2.0.1993.19") + .withLastHeartbeatUtc(OffsetDateTime.parse("2022-07-07T14:25:35.708325Z")) + .withSpnDetails(new CollectorAgentSpnPropertiesBase() + .withAuthority("https://login.windows.net/72f988bf-86f1-41af-91ab-2d7cd011db47") + .withApplicationId("e3bd6eaa-980b-40ae-a30e-2a5069ba097c") + .withAudience("e3bd6eaa-980b-40ae-a30e-2a5069ba097c") + .withObjectId("01b9f9e2-2d82-414c-adaa-09ce259b6b44") + .withTenantId("72f988bf-86f1-41af-91ab-2d7cd011db47"))) + .withDiscoverySiteId( + "/subscriptions/4bd2aa0f-2bd2-4d67-91a8-5a4533d58600/resourceGroups/ayagrawRG/providers/Microsoft.OffAzure/HyperVSites/test-60527site")) + .create(); + } +} +``` + +### HypervCollectorsOperations_Delete + +```java +/** + * Samples for HypervCollectorsOperations Delete. + */ +public final class HypervCollectorsOperationsDeleteSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * HypervCollectorsOperations_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: HypervCollectorsOperations_Delete_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void hypervCollectorsOperationsDeleteMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.hypervCollectorsOperations() + .deleteWithResponse("ayagrawRG", "app18700project", "test-697cecollector", + com.azure.core.util.Context.NONE); + } +} +``` + +### HypervCollectorsOperations_Get + +```java +/** + * Samples for HypervCollectorsOperations Get. + */ +public final class HypervCollectorsOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * HypervCollectorsOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: HypervCollectorsOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void hypervCollectorsOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.hypervCollectorsOperations() + .getWithResponse("ayagrawRG", "app18700project", "test-697cecollector", com.azure.core.util.Context.NONE); + } +} +``` + +### HypervCollectorsOperations_ListByAssessmentProject + +```java +/** + * Samples for HypervCollectorsOperations ListByAssessmentProject. + */ +public final class HypervCollectorsOperationsListByAssessmentProjectSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * HypervCollectorsOperations_ListByAssessmentProject_MaximumSet_Gen.json + */ + /** + * Sample code: HypervCollectorsOperations_ListByAssessmentProject_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void hypervCollectorsOperationsListByAssessmentProjectMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.hypervCollectorsOperations() + .listByAssessmentProject("ayagrawRG", "app18700project", com.azure.core.util.Context.NONE); + } +} +``` + +### ImportCollectorsOperations_Create + +```java +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; + +/** + * Samples for ImportCollectorsOperations Create. + */ +public final class ImportCollectorsOperationsCreateSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * ImportCollectorsOperations_Create_MaximumSet_Gen.json + */ + /** + * Sample code: ImportCollectorsOperations_Create_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void importCollectorsOperationsCreateMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.importCollectorsOperations() + .define("importCollectore7d5") + .withExistingAssessmentProject("ayagrawRG", "app18700project") + .withProperties(new CollectorPropertiesBase().withProvisioningState(ProvisioningState.SUCCEEDED) + .withDiscoverySiteId( + "/subscriptions/4bd2aa0f-2bd2-4d67-91a8-5a4533d58600/resourcegroups/ayagrawRG/providers/microsoft.offazure/importsites/actualSEA37d4importSite")) + .create(); + } +} +``` + +### ImportCollectorsOperations_Delete + +```java +/** + * Samples for ImportCollectorsOperations Delete. + */ +public final class ImportCollectorsOperationsDeleteSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * ImportCollectorsOperations_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: ImportCollectorsOperations_Delete_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void importCollectorsOperationsDeleteMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.importCollectorsOperations() + .deleteWithResponse("ayagrawRG", "app18700project", "importCollectore7d5", + com.azure.core.util.Context.NONE); + } +} +``` + +### ImportCollectorsOperations_Get + +```java +/** + * Samples for ImportCollectorsOperations Get. + */ +public final class ImportCollectorsOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * ImportCollectorsOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: ImportCollectorsOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void importCollectorsOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.importCollectorsOperations() + .getWithResponse("ayagrawRG", "app18700project", "importCollectore7d5", com.azure.core.util.Context.NONE); + } +} +``` + +### ImportCollectorsOperations_ListByAssessmentProject + +```java +/** + * Samples for ImportCollectorsOperations ListByAssessmentProject. + */ +public final class ImportCollectorsOperationsListByAssessmentProjectSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * ImportCollectorsOperations_ListByAssessmentProject_MaximumSet_Gen.json + */ + /** + * Sample code: ImportCollectorsOperations_ListByAssessmentProject_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void importCollectorsOperationsListByAssessmentProjectMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.importCollectorsOperations() + .listByAssessmentProject("ayagrawRG", "app18700project", com.azure.core.util.Context.NONE); + } +} +``` + +### MachinesOperations_Get + +```java +/** + * Samples for MachinesOperations Get. + */ +public final class MachinesOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * MachinesOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: MachinesOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void machinesOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.machinesOperations() + .getWithResponse("ayagrawrg", "app18700project", "55082b89-99e2-4c40-b63f-d4f4d6ba961d", + com.azure.core.util.Context.NONE); + } +} +``` + +### MachinesOperations_ListByAssessmentProject + +```java +/** + * Samples for MachinesOperations ListByAssessmentProject. + */ +public final class MachinesOperationsListByAssessmentProjectSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * MachinesOperations_ListByAssessmentProject_MaximumSet_Gen.json + */ + /** + * Sample code: MachinesOperations_ListByAssessmentProject_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void machinesOperationsListByAssessmentProjectMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.machinesOperations() + .listByAssessmentProject("ayagrawrg", "app18700project", null, 1, null, 1, + com.azure.core.util.Context.NONE); + } +} +``` + +### Operations_List + +```java +/** + * Samples for Operations List. + */ +public final class OperationsListSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * Operations_List_MaximumSet_Gen.json + */ + /** + * Sample code: Operations_List_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void + operationsListMaximumSetGen(com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.operations().list(com.azure.core.util.Context.NONE); + } +} +``` + +### PrivateEndpointConnectionOperations_Delete + +```java +/** + * Samples for PrivateEndpointConnectionOperations Delete. + */ +public final class PrivateEndpointConnectionOperationsDeleteSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * PrivateEndpointConnectionOperations_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: PrivateEndpointConnectionOperations_Delete_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void privateEndpointConnectionOperationsDeleteMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.privateEndpointConnectionOperations() + .deleteWithResponse("sakanwar", "sakanwar1204project", + "sakanwar1204project1634pe.bf42f8a1-09f5-4ee4-aea6-a019cc60f9d7", com.azure.core.util.Context.NONE); + } +} +``` + +### PrivateEndpointConnectionOperations_Get + +```java +/** + * Samples for PrivateEndpointConnectionOperations Get. + */ +public final class PrivateEndpointConnectionOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * PrivateEndpointConnectionOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: PrivateEndpointConnectionOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void privateEndpointConnectionOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.privateEndpointConnectionOperations() + .getWithResponse("sakanwar", "sakanwar1204project", + "sakanwar1204project1634pe.bf42f8a1-09f5-4ee4-aea6-a019cc60f9d7", com.azure.core.util.Context.NONE); + } +} +``` + +### PrivateEndpointConnectionOperations_ListByAssessmentProject + +```java +/** + * Samples for PrivateEndpointConnectionOperations ListByAssessmentProject. + */ +public final class PrivateEndpointConnectionOperationsListByAssessmentProjectSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * PrivateEndpointConnectionOperations_ListByAssessmentProject_MaximumSet_Gen.json + */ + /** + * Sample code: PrivateEndpointConnectionOperations_ListByAssessmentProject_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void privateEndpointConnectionOperationsListByAssessmentProjectMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.privateEndpointConnectionOperations() + .listByAssessmentProject("sakanwar", "sakanwar1204project", com.azure.core.util.Context.NONE); + } +} +``` + +### PrivateEndpointConnectionOperations_Update + +```java +import com.azure.resourcemanager.migration.assessment.fluent.models.PrivateEndpointConnectionInner; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpoint; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpointConnectionProperties; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpointServiceConnectionStatus; +import com.azure.resourcemanager.migration.assessment.models.PrivateLinkServiceConnectionState; + +/** + * Samples for PrivateEndpointConnectionOperations Update. + */ +public final class PrivateEndpointConnectionOperationsUpdateSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * PrivateEndpointConnectionOperations_Update_MaximumSet_Gen.json + */ + /** + * Sample code: PrivateEndpointConnectionOperations_Update_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void privateEndpointConnectionOperationsUpdateMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.privateEndpointConnectionOperations() + .update("sakanwar", "sakanwar1204project", "sakanwar1204project1634pe.bf42f8a1-09f5-4ee4-aea6-a019cc60f9d7", + new PrivateEndpointConnectionInner() + .withProperties(new PrivateEndpointConnectionProperties().withPrivateEndpoint(new PrivateEndpoint()) + .withPrivateLinkServiceConnectionState(new PrivateLinkServiceConnectionState() + .withStatus(PrivateEndpointServiceConnectionStatus.APPROVED) + .withActionsRequired(""))), + com.azure.core.util.Context.NONE); + } +} +``` + +### PrivateLinkResourceOperations_Get + +```java +/** + * Samples for PrivateLinkResourceOperations Get. + */ +public final class PrivateLinkResourceOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * PrivateLinkResourceOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: PrivateLinkResourceOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void privateLinkResourceOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.privateLinkResourceOperations() + .getWithResponse("sakanwar", "sakanwar1204project", "Default", com.azure.core.util.Context.NONE); + } +} +``` + +### PrivateLinkResourceOperations_ListByAssessmentProject + +```java +/** + * Samples for PrivateLinkResourceOperations ListByAssessmentProject. + */ +public final class PrivateLinkResourceOperationsListByAssessmentProjectSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * PrivateLinkResourceOperations_ListByAssessmentProject_MaximumSet_Gen.json + */ + /** + * Sample code: PrivateLinkResourceOperations_ListByAssessmentProject_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void privateLinkResourceOperationsListByAssessmentProjectMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.privateLinkResourceOperations() + .listByAssessmentProject("sakanwar", "sakanwar1204project", com.azure.core.util.Context.NONE); + } +} +``` + +### ServerCollectorsOperations_Create + +```java +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentSpnPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBaseWithAgent; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; + +/** + * Samples for ServerCollectorsOperations Create. + */ +public final class ServerCollectorsOperationsCreateSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * ServerCollectorsOperations_Create_MaximumSet_Gen.json + */ + /** + * Sample code: ServerCollectorsOperations_Create_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void serverCollectorsOperationsCreateMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.serverCollectorsOperations() + .define("walter389fcollector") + .withExistingAssessmentProject("ayagrawRG", "app18700project") + .withProperties(new CollectorPropertiesBaseWithAgent().withProvisioningState(ProvisioningState.SUCCEEDED) + .withAgentProperties(new CollectorAgentPropertiesBase().withId("498e4965-bbb1-47c2-8613-345baff9c509") + .withSpnDetails(new CollectorAgentSpnPropertiesBase() + .withAuthority("https://login.windows.net/72f988bf-86f1-41af-91ab-2d7cd011db47") + .withApplicationId("65153d2f-9afb-44e8-b3ca-1369150b7354") + .withAudience("65153d2f-9afb-44e8-b3ca-1369150b7354") + .withObjectId("ddde6f96-87c8-420b-9d4d-f16a5090519e") + .withTenantId("72f988bf-86f1-41af-91ab-2d7cd011db47"))) + .withDiscoverySiteId( + "/subscriptions/4bd2aa0f-2bd2-4d67-91a8-5a4533d58600/resourceGroups/ayagrawRG/providers/Microsoft.OffAzure/ServerSites/walter7155site")) + .create(); + } +} +``` + +### ServerCollectorsOperations_Delete + +```java +/** + * Samples for ServerCollectorsOperations Delete. + */ +public final class ServerCollectorsOperationsDeleteSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * ServerCollectorsOperations_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: ServerCollectorsOperations_Delete_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void serverCollectorsOperationsDeleteMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.serverCollectorsOperations() + .deleteWithResponse("ayagrawRG", "app18700project", "walter389fcollector", + com.azure.core.util.Context.NONE); + } +} +``` + +### ServerCollectorsOperations_Get + +```java +/** + * Samples for ServerCollectorsOperations Get. + */ +public final class ServerCollectorsOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * ServerCollectorsOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: ServerCollectorsOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void serverCollectorsOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.serverCollectorsOperations() + .getWithResponse("ayagrawRG", "app18700project", "walter389fcollector", com.azure.core.util.Context.NONE); + } +} +``` + +### ServerCollectorsOperations_ListByAssessmentProject + +```java +/** + * Samples for ServerCollectorsOperations ListByAssessmentProject. + */ +public final class ServerCollectorsOperationsListByAssessmentProjectSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * ServerCollectorsOperations_ListByAssessmentProject_MaximumSet_Gen.json + */ + /** + * Sample code: ServerCollectorsOperations_ListByAssessmentProject_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void serverCollectorsOperationsListByAssessmentProjectMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.serverCollectorsOperations() + .listByAssessmentProject("ayagrawRG", "app18700project", com.azure.core.util.Context.NONE); + } +} +``` + +### SqlAssessmentOptionsOperations_Get + +```java +/** + * Samples for SqlAssessmentOptionsOperations Get. + */ +public final class SqlAssessmentOptionsOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * SqlAssessmentOptionsOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: SqlAssessmentOptionsOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void sqlAssessmentOptionsOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.sqlAssessmentOptionsOperations() + .getWithResponse("rgmigrate", "fci-test6904project", "default", com.azure.core.util.Context.NONE); + } +} +``` + +### SqlAssessmentOptionsOperations_ListByAssessmentProject + +```java +/** + * Samples for SqlAssessmentOptionsOperations ListByAssessmentProject. + */ +public final class SqlAssessmentOptionsOperationsListByAssessmentProjectSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * SqlAssessmentOptionsOperations_ListByAssessmentProject_MaximumSet_Gen.json + */ + /** + * Sample code: SqlAssessmentOptionsOperations_ListByAssessmentProject_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void sqlAssessmentOptionsOperationsListByAssessmentProjectMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.sqlAssessmentOptionsOperations() + .listByAssessmentProject("rgmigrate", "fci-test6904project", com.azure.core.util.Context.NONE); + } +} +``` + +### SqlAssessmentV2Operations_Create + +```java +import com.azure.resourcemanager.migration.assessment.models.AssessmentSizingCriterion; +import com.azure.resourcemanager.migration.assessment.models.AsyncCommitModeIntent; +import com.azure.resourcemanager.migration.assessment.models.AzureCurrency; +import com.azure.resourcemanager.migration.assessment.models.AzureLocation; +import com.azure.resourcemanager.migration.assessment.models.AzureOfferCode; +import com.azure.resourcemanager.migration.assessment.models.AzureReservedInstance; +import com.azure.resourcemanager.migration.assessment.models.AzureSqlDataBaseType; +import com.azure.resourcemanager.migration.assessment.models.AzureSqlInstanceType; +import com.azure.resourcemanager.migration.assessment.models.AzureSqlPurchaseModel; +import com.azure.resourcemanager.migration.assessment.models.AzureSqlServiceTier; +import com.azure.resourcemanager.migration.assessment.models.AzureVmFamily; +import com.azure.resourcemanager.migration.assessment.models.ComputeTier; +import com.azure.resourcemanager.migration.assessment.models.EntityUptime; +import com.azure.resourcemanager.migration.assessment.models.EnvironmentType; +import com.azure.resourcemanager.migration.assessment.models.MultiSubnetIntent; +import com.azure.resourcemanager.migration.assessment.models.OptimizationLogic; +import com.azure.resourcemanager.migration.assessment.models.OsLicense; +import com.azure.resourcemanager.migration.assessment.models.Percentile; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentV2Properties; +import com.azure.resourcemanager.migration.assessment.models.SqlDbSettings; +import com.azure.resourcemanager.migration.assessment.models.SqlMiSettings; +import com.azure.resourcemanager.migration.assessment.models.SqlServerLicense; +import com.azure.resourcemanager.migration.assessment.models.SqlVmSettings; +import com.azure.resourcemanager.migration.assessment.models.TimeRange; +import java.util.Arrays; + +/** + * Samples for SqlAssessmentV2Operations Create. + */ +public final class SqlAssessmentV2OperationsCreateSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * SqlAssessmentV2Operations_Create_MaximumSet_Gen.json + */ + /** + * Sample code: SqlAssessmentV2Operations_Create_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void sqlAssessmentV2OperationsCreateMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.sqlAssessmentV2Operations() + .define("test_swagger_1") + .withExistingGroup("rgmigrate", "fci-test6904project", "test_fci_hadr") + .withProperties(new SqlAssessmentV2Properties().withOsLicense(OsLicense.UNKNOWN) + .withEnvironmentType(EnvironmentType.PRODUCTION) + .withEntityUptime(new EntityUptime().withDaysPerMonth(30).withHoursPerDay(24)) + .withOptimizationLogic(OptimizationLogic.MINIMIZE_COST) + .withReservedInstanceForVm(AzureReservedInstance.NONE) + .withAzureOfferCodeForVm(AzureOfferCode.MSAZR0003P) + .withAzureSqlManagedInstanceSettings( + new SqlMiSettings().withAzureSqlServiceTier(AzureSqlServiceTier.AUTOMATIC) + .withAzureSqlInstanceType(AzureSqlInstanceType.SINGLE_INSTANCE)) + .withAzureSqlDatabaseSettings(new SqlDbSettings().withAzureSqlServiceTier(AzureSqlServiceTier.AUTOMATIC) + .withAzureSqlDataBaseType(AzureSqlDataBaseType.SINGLE_DATABASE) + .withAzureSqlComputeTier(ComputeTier.AUTOMATIC) + .withAzureSqlPurchaseModel(AzureSqlPurchaseModel.VCORE)) + .withAzureSqlVmSettings( + new SqlVmSettings().withInstanceSeries(Arrays.asList(AzureVmFamily.EADSV5_SERIES))) + .withMultiSubnetIntent(MultiSubnetIntent.DISASTER_RECOVERY) + .withAsyncCommitModeIntent(AsyncCommitModeIntent.DISASTER_RECOVERY) + .withDisasterRecoveryLocation(AzureLocation.EAST_ASIA) + .withEnableHadrAssessment(true) + .withReservedInstance(AzureReservedInstance.NONE) + .withSqlServerLicense(SqlServerLicense.UNKNOWN) + .withAzureLocation("SoutheastAsia") + .withAzureOfferCode(AzureOfferCode.MSAZR0003P) + .withCurrency(AzureCurrency.USD) + .withScalingFactor(1.0F) + .withPercentile(Percentile.PERCENTILE95) + .withTimeRange(TimeRange.DAY) + .withDiscountPercentage(0.0F) + .withSizingCriterion(AssessmentSizingCriterion.PERFORMANCE_BASED)) + .create(); + } +} +``` + +### SqlAssessmentV2Operations_Delete + +```java +/** + * Samples for SqlAssessmentV2Operations Delete. + */ +public final class SqlAssessmentV2OperationsDeleteSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * SqlAssessmentV2Operations_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: SqlAssessmentV2Operations_Delete_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void sqlAssessmentV2OperationsDeleteMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.sqlAssessmentV2Operations() + .deleteWithResponse("rgmigrate", "fci-test6904project", "test_fci_hadr", "test_swagger_1", + com.azure.core.util.Context.NONE); + } +} +``` + +### SqlAssessmentV2Operations_DownloadUrl + +```java +import com.azure.core.management.serializer.SerializerFactory; +import com.azure.core.util.serializer.SerializerEncoding; +import java.io.IOException; + +/** + * Samples for SqlAssessmentV2Operations DownloadUrl. + */ +public final class SqlAssessmentV2OperationsDownloadUrlSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * SqlAssessmentV2Operations_DownloadUrl_MaximumSet_Gen.json + */ + /** + * Sample code: SqlAssessmentV2Operations_DownloadUrl_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void sqlAssessmentV2OperationsDownloadUrlMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) throws IOException { + manager.sqlAssessmentV2Operations() + .downloadUrl("rgmigrate", "fci-test6904project", "test_fci_hadr", "test_swagger_1", + SerializerFactory.createDefaultManagementSerializerAdapter() + .deserialize("{}", Object.class, SerializerEncoding.JSON), + com.azure.core.util.Context.NONE); + } +} +``` + +### SqlAssessmentV2Operations_Get + +```java +/** + * Samples for SqlAssessmentV2Operations Get. + */ +public final class SqlAssessmentV2OperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * SqlAssessmentV2Operations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: SqlAssessmentV2Operations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void sqlAssessmentV2OperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.sqlAssessmentV2Operations() + .getWithResponse("rgmigrate", "fci-test6904project", "test_fci_hadr", "test_swagger_1", + com.azure.core.util.Context.NONE); + } +} +``` + +### SqlAssessmentV2Operations_ListByGroup + +```java +/** + * Samples for SqlAssessmentV2Operations ListByGroup. + */ +public final class SqlAssessmentV2OperationsListByGroupSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * SqlAssessmentV2Operations_ListByGroup_MaximumSet_Gen.json + */ + /** + * Sample code: SqlAssessmentV2Operations_ListByGroup_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void sqlAssessmentV2OperationsListByGroupMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.sqlAssessmentV2Operations() + .listByGroup("rgmigrate", "fci-test6904project", "test_fci_hadr", com.azure.core.util.Context.NONE); + } +} +``` + +### SqlAssessmentV2SummaryOperations_Get + +```java +/** + * Samples for SqlAssessmentV2SummaryOperations Get. + */ +public final class SqlAssessmentV2SummaryOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * SqlAssessmentV2SummaryOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: SqlAssessmentV2SummaryOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void sqlAssessmentV2SummaryOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.sqlAssessmentV2SummaryOperations() + .getWithResponse("rgmigrate", "fci-test6904project", "test_fci_hadr", "test_swagger_1", "default", + com.azure.core.util.Context.NONE); + } +} +``` + +### SqlAssessmentV2SummaryOperations_ListBySqlAssessmentV2 + +```java +/** + * Samples for SqlAssessmentV2SummaryOperations ListBySqlAssessmentV2. + */ +public final class SqlAssessmentV2SummaryOperationsListBySqlAssessmentV2Samples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * SqlAssessmentV2SummaryOperations_ListBySqlAssessmentV2_MaximumSet_Gen.json + */ + /** + * Sample code: SqlAssessmentV2SummaryOperations_ListBySqlAssessmentV2_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void sqlAssessmentV2SummaryOperationsListBySqlAssessmentV2MaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.sqlAssessmentV2SummaryOperations() + .listBySqlAssessmentV2("rgmigrate", "fci-test6904project", "test_fci_hadr", "test_swagger_1", + com.azure.core.util.Context.NONE); + } +} +``` + +### SqlCollectorOperations_Create + +```java +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentSpnPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBaseWithAgent; + +/** + * Samples for SqlCollectorOperations Create. + */ +public final class SqlCollectorOperationsCreateSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * SqlCollectorOperations_Create_MaximumSet_Gen.json + */ + /** + * Sample code: SqlCollectorOperations_Create_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void sqlCollectorOperationsCreateMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.sqlCollectorOperations() + .define("fci-test0c1esqlsitecollector") + .withExistingAssessmentProject("rgmigrate", "fci-test6904project") + .withProperties(new CollectorPropertiesBaseWithAgent() + .withAgentProperties( + new CollectorAgentPropertiesBase().withId("630da710-4d44-41f7-a189-72fe3db5502b-agent") + .withSpnDetails(new CollectorAgentSpnPropertiesBase() + .withAuthority("https://login.windows.net/72f988bf-86f1-41af-91ab-2d7cd011db47") + .withApplicationId("db9c4c3d-477c-4d5a-817b-318276713565") + .withAudience("db9c4c3d-477c-4d5a-817b-318276713565") + .withObjectId("e50236ad-ad07-47d4-af71-ed7b52d200d5") + .withTenantId("72f988bf-86f1-41af-91ab-2d7cd011db47"))) + .withDiscoverySiteId( + "/subscriptions/4bd2aa0f-2bd2-4d67-91a8-5a4533d58600/resourceGroups/bansalankit-rg/providers/Microsoft.OffAzure/MasterSites/fci-ankit-test6065mastersite/SqlSites/fci-ankit-test6065sqlsites")) + .create(); + } +} +``` + +### SqlCollectorOperations_Delete + +```java +/** + * Samples for SqlCollectorOperations Delete. + */ +public final class SqlCollectorOperationsDeleteSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * SqlCollectorOperations_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: SqlCollectorOperations_Delete_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void sqlCollectorOperationsDeleteMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.sqlCollectorOperations() + .deleteWithResponse("rgmigrate", "fci-test6904project", "fci-test0c1esqlsitecollector", + com.azure.core.util.Context.NONE); + } +} +``` + +### SqlCollectorOperations_Get + +```java +/** + * Samples for SqlCollectorOperations Get. + */ +public final class SqlCollectorOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * SqlCollectorOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: SqlCollectorOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void sqlCollectorOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.sqlCollectorOperations() + .getWithResponse("rgmigrate", "fci-test6904project", "fci-test0c1esqlsitecollector", + com.azure.core.util.Context.NONE); + } +} +``` + +### SqlCollectorOperations_ListByAssessmentProject + +```java +/** + * Samples for SqlCollectorOperations ListByAssessmentProject. + */ +public final class SqlCollectorOperationsListByAssessmentProjectSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * SqlCollectorOperations_ListByAssessmentProject_MaximumSet_Gen.json + */ + /** + * Sample code: SqlCollectorOperations_ListByAssessmentProject_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void sqlCollectorOperationsListByAssessmentProjectMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.sqlCollectorOperations() + .listByAssessmentProject("rgmigrate", "fci-test6904project", com.azure.core.util.Context.NONE); + } +} +``` + +### VmwareCollectorsOperations_Create + +```java +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentSpnPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBaseWithAgent; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.time.OffsetDateTime; + +/** + * Samples for VmwareCollectorsOperations Create. + */ +public final class VmwareCollectorsOperationsCreateSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * VmwareCollectorsOperations_Create_MaximumSet_Gen.json + */ + /** + * Sample code: VmwareCollectorsOperations_Create_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void vmwareCollectorsOperationsCreateMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.vmwareCollectorsOperations() + .define("Vmware2258collector") + .withExistingAssessmentProject("ayagrawRG", "app18700project") + .withProperties(new CollectorPropertiesBaseWithAgent().withProvisioningState(ProvisioningState.SUCCEEDED) + .withAgentProperties(new CollectorAgentPropertiesBase().withId("fe243486-3318-41fa-aaba-c48b5df75308") + .withVersion("1.0.8.383") + .withLastHeartbeatUtc(OffsetDateTime.parse("2022-03-29T12:10:08.9167289Z")) + .withSpnDetails(new CollectorAgentSpnPropertiesBase() + .withAuthority("https://login.windows.net/72f988bf-86f1-41af-91ab-2d7cd011db47") + .withApplicationId("82b3e452-c0e8-4662-8347-58282925ae84") + .withAudience("82b3e452-c0e8-4662-8347-58282925ae84") + .withObjectId("3fc89111-1405-4938-9214-37aa4739401d") + .withTenantId("72f988bf-86f1-41af-91ab-2d7cd011db47"))) + .withDiscoverySiteId( + "/subscriptions/4bd2aa0f-2bd2-4d67-91a8-5a4533d58600/resourceGroups/ayagrawRG/providers/Microsoft.OffAzure/VMwareSites/Vmware2744site")) + .create(); + } +} +``` + +### VmwareCollectorsOperations_Delete + +```java +/** + * Samples for VmwareCollectorsOperations Delete. + */ +public final class VmwareCollectorsOperationsDeleteSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * VmwareCollectorsOperations_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: VmwareCollectorsOperations_Delete_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void vmwareCollectorsOperationsDeleteMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.vmwareCollectorsOperations() + .deleteWithResponse("ayagrawRG", "app18700project", "Vmware2258collector", + com.azure.core.util.Context.NONE); + } +} +``` + +### VmwareCollectorsOperations_Get + +```java +/** + * Samples for VmwareCollectorsOperations Get. + */ +public final class VmwareCollectorsOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * VmwareCollectorsOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: VmwareCollectorsOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void vmwareCollectorsOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.vmwareCollectorsOperations() + .getWithResponse("ayagrawRG", "app18700project", "Vmware2258collector", com.azure.core.util.Context.NONE); + } +} +``` + +### VmwareCollectorsOperations_ListByAssessmentProject + +```java +/** + * Samples for VmwareCollectorsOperations ListByAssessmentProject. + */ +public final class VmwareCollectorsOperationsListByAssessmentProjectSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * VmwareCollectorsOperations_ListByAssessmentProject_MaximumSet_Gen.json + */ + /** + * Sample code: VmwareCollectorsOperations_ListByAssessmentProject_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void vmwareCollectorsOperationsListByAssessmentProjectMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.vmwareCollectorsOperations() + .listByAssessmentProject("ayagrawRG", "app18700project", com.azure.core.util.Context.NONE); + } +} +``` + diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/pom.xml b/sdk/migration/azure-resourcemanager-migration-assessment/pom.xml new file mode 100644 index 000000000000..45abcca993ff --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/pom.xml @@ -0,0 +1,75 @@ + + + 4.0.0 + + com.azure + azure-client-sdk-parent + 1.7.0 + ../../parents/azure-client-sdk-parent + + + com.azure.resourcemanager + azure-resourcemanager-migration-assessment + 1.0.0-beta.2 + jar + + Microsoft Azure SDK for Migration Assessment Management + This package contains Microsoft Azure SDK for Migration Assessment Management SDK. For documentation on how to use this package, please see https://aka.ms/azsdk/java/mgmt. Azure Migrate Resource Provider management API. Package tag package-2023-03. + https://github.com/Azure/azure-sdk-for-java + + + + The MIT License (MIT) + http://opensource.org/licenses/MIT + repo + + + + + https://github.com/Azure/azure-sdk-for-java + scm:git:git@github.com:Azure/azure-sdk-for-java.git + scm:git:git@github.com:Azure/azure-sdk-for-java.git + HEAD + + + + microsoft + Microsoft + + + + UTF-8 + 0 + 0 + true + false + + + + com.azure + azure-core + 1.55.3 + + + com.azure + azure-core-management + 1.17.0 + + + com.azure + azure-core-test + 1.27.0-beta.8 + test + + + com.azure + azure-identity + 1.15.4 + test + + + diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/MigrationAssessmentManager.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/MigrationAssessmentManager.java new file mode 100644 index 000000000000..7bc6082cdd20 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/MigrationAssessmentManager.java @@ -0,0 +1,687 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.HttpPipelinePosition; +import com.azure.core.http.policy.AddDatePolicy; +import com.azure.core.http.policy.AddHeadersFromContextPolicy; +import com.azure.core.http.policy.BearerTokenAuthenticationPolicy; +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.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.management.profile.AzureProfile; +import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.migration.assessment.fluent.MigrationAssessmentManagementClient; +import com.azure.resourcemanager.migration.assessment.implementation.AssessedMachinesOperationsImpl; +import com.azure.resourcemanager.migration.assessment.implementation.AssessedSqlDatabaseV2OperationsImpl; +import com.azure.resourcemanager.migration.assessment.implementation.AssessedSqlInstanceV2OperationsImpl; +import com.azure.resourcemanager.migration.assessment.implementation.AssessedSqlMachinesOperationsImpl; +import com.azure.resourcemanager.migration.assessment.implementation.AssessedSqlRecommendedEntityOperationsImpl; +import com.azure.resourcemanager.migration.assessment.implementation.AssessmentOptionsOperationsImpl; +import com.azure.resourcemanager.migration.assessment.implementation.AssessmentProjectSummaryOperationsImpl; +import com.azure.resourcemanager.migration.assessment.implementation.AssessmentProjectsOperationsImpl; +import com.azure.resourcemanager.migration.assessment.implementation.AssessmentsOperationsImpl; +import com.azure.resourcemanager.migration.assessment.implementation.AvsAssessedMachinesOperationsImpl; +import com.azure.resourcemanager.migration.assessment.implementation.AvsAssessmentOptionsOperationsImpl; +import com.azure.resourcemanager.migration.assessment.implementation.AvsAssessmentsOperationsImpl; +import com.azure.resourcemanager.migration.assessment.implementation.GroupsOperationsImpl; +import com.azure.resourcemanager.migration.assessment.implementation.HypervCollectorsOperationsImpl; +import com.azure.resourcemanager.migration.assessment.implementation.ImportCollectorsOperationsImpl; +import com.azure.resourcemanager.migration.assessment.implementation.MachinesOperationsImpl; +import com.azure.resourcemanager.migration.assessment.implementation.MigrationAssessmentManagementClientBuilder; +import com.azure.resourcemanager.migration.assessment.implementation.OperationsImpl; +import com.azure.resourcemanager.migration.assessment.implementation.PrivateEndpointConnectionOperationsImpl; +import com.azure.resourcemanager.migration.assessment.implementation.PrivateLinkResourceOperationsImpl; +import com.azure.resourcemanager.migration.assessment.implementation.ServerCollectorsOperationsImpl; +import com.azure.resourcemanager.migration.assessment.implementation.SqlAssessmentOptionsOperationsImpl; +import com.azure.resourcemanager.migration.assessment.implementation.SqlAssessmentV2OperationsImpl; +import com.azure.resourcemanager.migration.assessment.implementation.SqlAssessmentV2SummaryOperationsImpl; +import com.azure.resourcemanager.migration.assessment.implementation.SqlCollectorOperationsImpl; +import com.azure.resourcemanager.migration.assessment.implementation.VmwareCollectorsOperationsImpl; +import com.azure.resourcemanager.migration.assessment.models.AssessedMachinesOperations; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlDatabaseV2Operations; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlInstanceV2Operations; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlMachinesOperations; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlRecommendedEntityOperations; +import com.azure.resourcemanager.migration.assessment.models.AssessmentOptionsOperations; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProjectSummaryOperations; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProjectsOperations; +import com.azure.resourcemanager.migration.assessment.models.AssessmentsOperations; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessedMachinesOperations; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessmentOptionsOperations; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessmentsOperations; +import com.azure.resourcemanager.migration.assessment.models.GroupsOperations; +import com.azure.resourcemanager.migration.assessment.models.HypervCollectorsOperations; +import com.azure.resourcemanager.migration.assessment.models.ImportCollectorsOperations; +import com.azure.resourcemanager.migration.assessment.models.MachinesOperations; +import com.azure.resourcemanager.migration.assessment.models.Operations; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpointConnectionOperations; +import com.azure.resourcemanager.migration.assessment.models.PrivateLinkResourceOperations; +import com.azure.resourcemanager.migration.assessment.models.ServerCollectorsOperations; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentOptionsOperations; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentV2Operations; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentV2SummaryOperations; +import com.azure.resourcemanager.migration.assessment.models.SqlCollectorOperations; +import com.azure.resourcemanager.migration.assessment.models.VmwareCollectorsOperations; +import java.time.Duration; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +/** + * Entry point to MigrationAssessmentManager. + * Azure Migrate Resource Provider management API. + */ +public final class MigrationAssessmentManager { + private Operations operations; + + private AssessmentProjectsOperations assessmentProjectsOperations; + + private AssessmentOptionsOperations assessmentOptionsOperations; + + private AvsAssessmentOptionsOperations avsAssessmentOptionsOperations; + + private GroupsOperations groupsOperations; + + private AssessmentsOperations assessmentsOperations; + + private AssessedMachinesOperations assessedMachinesOperations; + + private AvsAssessmentsOperations avsAssessmentsOperations; + + private AvsAssessedMachinesOperations avsAssessedMachinesOperations; + + private SqlAssessmentV2Operations sqlAssessmentV2Operations; + + private AssessedSqlDatabaseV2Operations assessedSqlDatabaseV2Operations; + + private AssessedSqlInstanceV2Operations assessedSqlInstanceV2Operations; + + private AssessedSqlMachinesOperations assessedSqlMachinesOperations; + + private AssessedSqlRecommendedEntityOperations assessedSqlRecommendedEntityOperations; + + private SqlAssessmentV2SummaryOperations sqlAssessmentV2SummaryOperations; + + private HypervCollectorsOperations hypervCollectorsOperations; + + private ImportCollectorsOperations importCollectorsOperations; + + private MachinesOperations machinesOperations; + + private PrivateEndpointConnectionOperations privateEndpointConnectionOperations; + + private PrivateLinkResourceOperations privateLinkResourceOperations; + + private AssessmentProjectSummaryOperations assessmentProjectSummaryOperations; + + private ServerCollectorsOperations serverCollectorsOperations; + + private SqlAssessmentOptionsOperations sqlAssessmentOptionsOperations; + + private SqlCollectorOperations sqlCollectorOperations; + + private VmwareCollectorsOperations vmwareCollectorsOperations; + + private final MigrationAssessmentManagementClient clientObject; + + private MigrationAssessmentManager(HttpPipeline httpPipeline, AzureProfile profile, Duration defaultPollInterval) { + Objects.requireNonNull(httpPipeline, "'httpPipeline' cannot be null."); + Objects.requireNonNull(profile, "'profile' cannot be null."); + this.clientObject = new MigrationAssessmentManagementClientBuilder().pipeline(httpPipeline) + .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) + .subscriptionId(profile.getSubscriptionId()) + .defaultPollInterval(defaultPollInterval) + .buildClient(); + } + + /** + * Creates an instance of Migration Assessment service API entry point. + * + * @param credential the credential to use. + * @param profile the Azure profile for client. + * @return the Migration Assessment service API instance. + */ + public static MigrationAssessmentManager authenticate(TokenCredential credential, AzureProfile profile) { + Objects.requireNonNull(credential, "'credential' cannot be null."); + Objects.requireNonNull(profile, "'profile' cannot be null."); + return configure().authenticate(credential, profile); + } + + /** + * Creates an instance of Migration Assessment service API entry point. + * + * @param httpPipeline the {@link HttpPipeline} configured with Azure authentication credential. + * @param profile the Azure profile for client. + * @return the Migration Assessment service API instance. + */ + public static MigrationAssessmentManager authenticate(HttpPipeline httpPipeline, AzureProfile profile) { + Objects.requireNonNull(httpPipeline, "'httpPipeline' cannot be null."); + Objects.requireNonNull(profile, "'profile' cannot be null."); + return new MigrationAssessmentManager(httpPipeline, profile, null); + } + + /** + * Gets a Configurable instance that can be used to create MigrationAssessmentManager with optional configuration. + * + * @return the Configurable instance allowing configurations. + */ + public static Configurable configure() { + return new MigrationAssessmentManager.Configurable(); + } + + /** + * The Configurable allowing configurations to be set. + */ + public static final class Configurable { + private static final ClientLogger LOGGER = new ClientLogger(Configurable.class); + private static final String SDK_VERSION = "version"; + private static final Map PROPERTIES + = CoreUtils.getProperties("azure-resourcemanager-migration-assessment.properties"); + + private HttpClient httpClient; + private HttpLogOptions httpLogOptions; + private final List policies = new ArrayList<>(); + private final List scopes = new ArrayList<>(); + private RetryPolicy retryPolicy; + private RetryOptions retryOptions; + private Duration defaultPollInterval; + + private Configurable() { + } + + /** + * Sets the http client. + * + * @param httpClient the HTTP client. + * @return the configurable object itself. + */ + public Configurable withHttpClient(HttpClient httpClient) { + this.httpClient = Objects.requireNonNull(httpClient, "'httpClient' cannot be null."); + return this; + } + + /** + * Sets the logging options to the HTTP pipeline. + * + * @param httpLogOptions the HTTP log options. + * @return the configurable object itself. + */ + public Configurable withLogOptions(HttpLogOptions httpLogOptions) { + this.httpLogOptions = Objects.requireNonNull(httpLogOptions, "'httpLogOptions' cannot be null."); + return this; + } + + /** + * Adds the pipeline policy to the HTTP pipeline. + * + * @param policy the HTTP pipeline policy. + * @return the configurable object itself. + */ + public Configurable withPolicy(HttpPipelinePolicy policy) { + this.policies.add(Objects.requireNonNull(policy, "'policy' cannot be null.")); + return this; + } + + /** + * Adds the scope to permission sets. + * + * @param scope the scope. + * @return the configurable object itself. + */ + public Configurable withScope(String scope) { + this.scopes.add(Objects.requireNonNull(scope, "'scope' cannot be null.")); + return this; + } + + /** + * Sets the retry policy to the HTTP pipeline. + * + * @param retryPolicy the HTTP pipeline retry policy. + * @return the configurable object itself. + */ + public Configurable withRetryPolicy(RetryPolicy retryPolicy) { + this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null."); + return this; + } + + /** + * Sets the retry options for the HTTP pipeline retry policy. + *

        + * This setting has no effect, if retry policy is set via {@link #withRetryPolicy(RetryPolicy)}. + * + * @param retryOptions the retry options for the HTTP pipeline retry policy. + * @return the configurable object itself. + */ + public Configurable withRetryOptions(RetryOptions retryOptions) { + this.retryOptions = Objects.requireNonNull(retryOptions, "'retryOptions' cannot be null."); + return this; + } + + /** + * Sets the default poll interval, used when service does not provide "Retry-After" header. + * + * @param defaultPollInterval the default poll interval. + * @return the configurable object itself. + */ + public Configurable withDefaultPollInterval(Duration defaultPollInterval) { + this.defaultPollInterval + = Objects.requireNonNull(defaultPollInterval, "'defaultPollInterval' cannot be null."); + if (this.defaultPollInterval.isNegative()) { + throw LOGGER + .logExceptionAsError(new IllegalArgumentException("'defaultPollInterval' cannot be negative")); + } + return this; + } + + /** + * Creates an instance of Migration Assessment service API entry point. + * + * @param credential the credential to use. + * @param profile the Azure profile for client. + * @return the Migration Assessment service API instance. + */ + public MigrationAssessmentManager authenticate(TokenCredential credential, AzureProfile profile) { + Objects.requireNonNull(credential, "'credential' cannot be null."); + Objects.requireNonNull(profile, "'profile' cannot be null."); + + String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); + + StringBuilder userAgentBuilder = new StringBuilder(); + userAgentBuilder.append("azsdk-java") + .append("-") + .append("com.azure.resourcemanager.migration.assessment") + .append("/") + .append(clientVersion); + if (!Configuration.getGlobalConfiguration().get("AZURE_TELEMETRY_DISABLED", false)) { + userAgentBuilder.append(" (") + .append(Configuration.getGlobalConfiguration().get("java.version")) + .append("; ") + .append(Configuration.getGlobalConfiguration().get("os.name")) + .append("; ") + .append(Configuration.getGlobalConfiguration().get("os.version")) + .append("; auto-generated)"); + } else { + userAgentBuilder.append(" (auto-generated)"); + } + + if (scopes.isEmpty()) { + scopes.add(profile.getEnvironment().getManagementEndpoint() + "/.default"); + } + if (retryPolicy == null) { + if (retryOptions != null) { + retryPolicy = new RetryPolicy(retryOptions); + } else { + retryPolicy = new RetryPolicy("Retry-After", ChronoUnit.SECONDS); + } + } + List policies = new ArrayList<>(); + policies.add(new UserAgentPolicy(userAgentBuilder.toString())); + policies.add(new AddHeadersFromContextPolicy()); + policies.add(new RequestIdPolicy()); + policies.addAll(this.policies.stream() + .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) + .collect(Collectors.toList())); + HttpPolicyProviders.addBeforeRetryPolicies(policies); + policies.add(retryPolicy); + policies.add(new AddDatePolicy()); + policies.add(new BearerTokenAuthenticationPolicy(credential, scopes.toArray(new String[0]))); + policies.addAll(this.policies.stream() + .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) + .collect(Collectors.toList())); + HttpPolicyProviders.addAfterRetryPolicies(policies); + policies.add(new HttpLoggingPolicy(httpLogOptions)); + HttpPipeline httpPipeline = new HttpPipelineBuilder().httpClient(httpClient) + .policies(policies.toArray(new HttpPipelinePolicy[0])) + .build(); + return new MigrationAssessmentManager(httpPipeline, profile, defaultPollInterval); + } + } + + /** + * Gets the resource collection API of Operations. + * + * @return Resource collection API of Operations. + */ + public Operations operations() { + if (this.operations == null) { + this.operations = new OperationsImpl(clientObject.getOperations(), this); + } + return operations; + } + + /** + * Gets the resource collection API of AssessmentProjectsOperations. It manages AssessmentProject. + * + * @return Resource collection API of AssessmentProjectsOperations. + */ + public AssessmentProjectsOperations assessmentProjectsOperations() { + if (this.assessmentProjectsOperations == null) { + this.assessmentProjectsOperations + = new AssessmentProjectsOperationsImpl(clientObject.getAssessmentProjectsOperations(), this); + } + return assessmentProjectsOperations; + } + + /** + * Gets the resource collection API of AssessmentOptionsOperations. + * + * @return Resource collection API of AssessmentOptionsOperations. + */ + public AssessmentOptionsOperations assessmentOptionsOperations() { + if (this.assessmentOptionsOperations == null) { + this.assessmentOptionsOperations + = new AssessmentOptionsOperationsImpl(clientObject.getAssessmentOptionsOperations(), this); + } + return assessmentOptionsOperations; + } + + /** + * Gets the resource collection API of AvsAssessmentOptionsOperations. + * + * @return Resource collection API of AvsAssessmentOptionsOperations. + */ + public AvsAssessmentOptionsOperations avsAssessmentOptionsOperations() { + if (this.avsAssessmentOptionsOperations == null) { + this.avsAssessmentOptionsOperations + = new AvsAssessmentOptionsOperationsImpl(clientObject.getAvsAssessmentOptionsOperations(), this); + } + return avsAssessmentOptionsOperations; + } + + /** + * Gets the resource collection API of GroupsOperations. It manages Group. + * + * @return Resource collection API of GroupsOperations. + */ + public GroupsOperations groupsOperations() { + if (this.groupsOperations == null) { + this.groupsOperations = new GroupsOperationsImpl(clientObject.getGroupsOperations(), this); + } + return groupsOperations; + } + + /** + * Gets the resource collection API of AssessmentsOperations. It manages Assessment. + * + * @return Resource collection API of AssessmentsOperations. + */ + public AssessmentsOperations assessmentsOperations() { + if (this.assessmentsOperations == null) { + this.assessmentsOperations = new AssessmentsOperationsImpl(clientObject.getAssessmentsOperations(), this); + } + return assessmentsOperations; + } + + /** + * Gets the resource collection API of AssessedMachinesOperations. + * + * @return Resource collection API of AssessedMachinesOperations. + */ + public AssessedMachinesOperations assessedMachinesOperations() { + if (this.assessedMachinesOperations == null) { + this.assessedMachinesOperations + = new AssessedMachinesOperationsImpl(clientObject.getAssessedMachinesOperations(), this); + } + return assessedMachinesOperations; + } + + /** + * Gets the resource collection API of AvsAssessmentsOperations. It manages AvsAssessment. + * + * @return Resource collection API of AvsAssessmentsOperations. + */ + public AvsAssessmentsOperations avsAssessmentsOperations() { + if (this.avsAssessmentsOperations == null) { + this.avsAssessmentsOperations + = new AvsAssessmentsOperationsImpl(clientObject.getAvsAssessmentsOperations(), this); + } + return avsAssessmentsOperations; + } + + /** + * Gets the resource collection API of AvsAssessedMachinesOperations. + * + * @return Resource collection API of AvsAssessedMachinesOperations. + */ + public AvsAssessedMachinesOperations avsAssessedMachinesOperations() { + if (this.avsAssessedMachinesOperations == null) { + this.avsAssessedMachinesOperations + = new AvsAssessedMachinesOperationsImpl(clientObject.getAvsAssessedMachinesOperations(), this); + } + return avsAssessedMachinesOperations; + } + + /** + * Gets the resource collection API of SqlAssessmentV2Operations. It manages SqlAssessmentV2. + * + * @return Resource collection API of SqlAssessmentV2Operations. + */ + public SqlAssessmentV2Operations sqlAssessmentV2Operations() { + if (this.sqlAssessmentV2Operations == null) { + this.sqlAssessmentV2Operations + = new SqlAssessmentV2OperationsImpl(clientObject.getSqlAssessmentV2Operations(), this); + } + return sqlAssessmentV2Operations; + } + + /** + * Gets the resource collection API of AssessedSqlDatabaseV2Operations. + * + * @return Resource collection API of AssessedSqlDatabaseV2Operations. + */ + public AssessedSqlDatabaseV2Operations assessedSqlDatabaseV2Operations() { + if (this.assessedSqlDatabaseV2Operations == null) { + this.assessedSqlDatabaseV2Operations + = new AssessedSqlDatabaseV2OperationsImpl(clientObject.getAssessedSqlDatabaseV2Operations(), this); + } + return assessedSqlDatabaseV2Operations; + } + + /** + * Gets the resource collection API of AssessedSqlInstanceV2Operations. + * + * @return Resource collection API of AssessedSqlInstanceV2Operations. + */ + public AssessedSqlInstanceV2Operations assessedSqlInstanceV2Operations() { + if (this.assessedSqlInstanceV2Operations == null) { + this.assessedSqlInstanceV2Operations + = new AssessedSqlInstanceV2OperationsImpl(clientObject.getAssessedSqlInstanceV2Operations(), this); + } + return assessedSqlInstanceV2Operations; + } + + /** + * Gets the resource collection API of AssessedSqlMachinesOperations. + * + * @return Resource collection API of AssessedSqlMachinesOperations. + */ + public AssessedSqlMachinesOperations assessedSqlMachinesOperations() { + if (this.assessedSqlMachinesOperations == null) { + this.assessedSqlMachinesOperations + = new AssessedSqlMachinesOperationsImpl(clientObject.getAssessedSqlMachinesOperations(), this); + } + return assessedSqlMachinesOperations; + } + + /** + * Gets the resource collection API of AssessedSqlRecommendedEntityOperations. + * + * @return Resource collection API of AssessedSqlRecommendedEntityOperations. + */ + public AssessedSqlRecommendedEntityOperations assessedSqlRecommendedEntityOperations() { + if (this.assessedSqlRecommendedEntityOperations == null) { + this.assessedSqlRecommendedEntityOperations = new AssessedSqlRecommendedEntityOperationsImpl( + clientObject.getAssessedSqlRecommendedEntityOperations(), this); + } + return assessedSqlRecommendedEntityOperations; + } + + /** + * Gets the resource collection API of SqlAssessmentV2SummaryOperations. + * + * @return Resource collection API of SqlAssessmentV2SummaryOperations. + */ + public SqlAssessmentV2SummaryOperations sqlAssessmentV2SummaryOperations() { + if (this.sqlAssessmentV2SummaryOperations == null) { + this.sqlAssessmentV2SummaryOperations + = new SqlAssessmentV2SummaryOperationsImpl(clientObject.getSqlAssessmentV2SummaryOperations(), this); + } + return sqlAssessmentV2SummaryOperations; + } + + /** + * Gets the resource collection API of HypervCollectorsOperations. It manages HypervCollector. + * + * @return Resource collection API of HypervCollectorsOperations. + */ + public HypervCollectorsOperations hypervCollectorsOperations() { + if (this.hypervCollectorsOperations == null) { + this.hypervCollectorsOperations + = new HypervCollectorsOperationsImpl(clientObject.getHypervCollectorsOperations(), this); + } + return hypervCollectorsOperations; + } + + /** + * Gets the resource collection API of ImportCollectorsOperations. It manages ImportCollector. + * + * @return Resource collection API of ImportCollectorsOperations. + */ + public ImportCollectorsOperations importCollectorsOperations() { + if (this.importCollectorsOperations == null) { + this.importCollectorsOperations + = new ImportCollectorsOperationsImpl(clientObject.getImportCollectorsOperations(), this); + } + return importCollectorsOperations; + } + + /** + * Gets the resource collection API of MachinesOperations. + * + * @return Resource collection API of MachinesOperations. + */ + public MachinesOperations machinesOperations() { + if (this.machinesOperations == null) { + this.machinesOperations = new MachinesOperationsImpl(clientObject.getMachinesOperations(), this); + } + return machinesOperations; + } + + /** + * Gets the resource collection API of PrivateEndpointConnectionOperations. + * + * @return Resource collection API of PrivateEndpointConnectionOperations. + */ + public PrivateEndpointConnectionOperations privateEndpointConnectionOperations() { + if (this.privateEndpointConnectionOperations == null) { + this.privateEndpointConnectionOperations = new PrivateEndpointConnectionOperationsImpl( + clientObject.getPrivateEndpointConnectionOperations(), this); + } + return privateEndpointConnectionOperations; + } + + /** + * Gets the resource collection API of PrivateLinkResourceOperations. + * + * @return Resource collection API of PrivateLinkResourceOperations. + */ + public PrivateLinkResourceOperations privateLinkResourceOperations() { + if (this.privateLinkResourceOperations == null) { + this.privateLinkResourceOperations + = new PrivateLinkResourceOperationsImpl(clientObject.getPrivateLinkResourceOperations(), this); + } + return privateLinkResourceOperations; + } + + /** + * Gets the resource collection API of AssessmentProjectSummaryOperations. + * + * @return Resource collection API of AssessmentProjectSummaryOperations. + */ + public AssessmentProjectSummaryOperations assessmentProjectSummaryOperations() { + if (this.assessmentProjectSummaryOperations == null) { + this.assessmentProjectSummaryOperations = new AssessmentProjectSummaryOperationsImpl( + clientObject.getAssessmentProjectSummaryOperations(), this); + } + return assessmentProjectSummaryOperations; + } + + /** + * Gets the resource collection API of ServerCollectorsOperations. It manages ServerCollector. + * + * @return Resource collection API of ServerCollectorsOperations. + */ + public ServerCollectorsOperations serverCollectorsOperations() { + if (this.serverCollectorsOperations == null) { + this.serverCollectorsOperations + = new ServerCollectorsOperationsImpl(clientObject.getServerCollectorsOperations(), this); + } + return serverCollectorsOperations; + } + + /** + * Gets the resource collection API of SqlAssessmentOptionsOperations. + * + * @return Resource collection API of SqlAssessmentOptionsOperations. + */ + public SqlAssessmentOptionsOperations sqlAssessmentOptionsOperations() { + if (this.sqlAssessmentOptionsOperations == null) { + this.sqlAssessmentOptionsOperations + = new SqlAssessmentOptionsOperationsImpl(clientObject.getSqlAssessmentOptionsOperations(), this); + } + return sqlAssessmentOptionsOperations; + } + + /** + * Gets the resource collection API of SqlCollectorOperations. It manages SqlCollector. + * + * @return Resource collection API of SqlCollectorOperations. + */ + public SqlCollectorOperations sqlCollectorOperations() { + if (this.sqlCollectorOperations == null) { + this.sqlCollectorOperations + = new SqlCollectorOperationsImpl(clientObject.getSqlCollectorOperations(), this); + } + return sqlCollectorOperations; + } + + /** + * Gets the resource collection API of VmwareCollectorsOperations. It manages VmwareCollector. + * + * @return Resource collection API of VmwareCollectorsOperations. + */ + public VmwareCollectorsOperations vmwareCollectorsOperations() { + if (this.vmwareCollectorsOperations == null) { + this.vmwareCollectorsOperations + = new VmwareCollectorsOperationsImpl(clientObject.getVmwareCollectorsOperations(), this); + } + return vmwareCollectorsOperations; + } + + /** + * Gets wrapped service client MigrationAssessmentManagementClient providing direct access to the underlying + * auto-generated API implementation, based on Azure REST API. + * + * @return Wrapped service client MigrationAssessmentManagementClient. + */ + public MigrationAssessmentManagementClient serviceClient() { + return this.clientObject; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AssessedMachinesOperationsClient.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AssessedMachinesOperationsClient.java new file mode 100644 index 000000000000..2f35ff739cd0 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AssessedMachinesOperationsClient.java @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedMachineInner; + +/** + * An instance of this class provides access to all the operations defined in AssessedMachinesOperationsClient. + */ +public interface AssessedMachinesOperationsClient { + /** + * List AssessedMachine resources by Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedMachine list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAssessment(String resourceGroupName, String projectName, String groupName, + String assessmentName); + + /** + * List AssessedMachine resources by Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedMachine list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAssessment(String resourceGroupName, String projectName, String groupName, + String assessmentName, String filter, Integer pageSize, String continuationToken, Integer totalRecordCount, + Context context); + + /** + * Get a AssessedMachine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param assessedMachineName Machine assessment Assessed Machine ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedMachine along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, String assessedMachineName, Context context); + + /** + * Get a AssessedMachine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param assessedMachineName Machine assessment Assessed Machine ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedMachine. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + AssessedMachineInner get(String resourceGroupName, String projectName, String groupName, String assessmentName, + String assessedMachineName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AssessedSqlDatabaseV2OperationsClient.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AssessedSqlDatabaseV2OperationsClient.java new file mode 100644 index 000000000000..ad400e52b56e --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AssessedSqlDatabaseV2OperationsClient.java @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlDatabaseV2Inner; + +/** + * An instance of this class provides access to all the operations defined in AssessedSqlDatabaseV2OperationsClient. + */ +public interface AssessedSqlDatabaseV2OperationsClient { + /** + * List AssessedSqlDatabaseV2 resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlDatabaseV2 list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName); + + /** + * List AssessedSqlDatabaseV2 resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlDatabaseV2 list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName, String filter, Integer pageSize, String continuationToken, + Integer totalRecordCount, Context context); + + /** + * Get a AssessedSqlDatabaseV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param assessedSqlDatabaseName Sql assessment Assessed Databases ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlDatabaseV2 along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, String assessedSqlDatabaseName, Context context); + + /** + * Get a AssessedSqlDatabaseV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param assessedSqlDatabaseName Sql assessment Assessed Databases ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlDatabaseV2. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + AssessedSqlDatabaseV2Inner get(String resourceGroupName, String projectName, String groupName, + String assessmentName, String assessedSqlDatabaseName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AssessedSqlInstanceV2OperationsClient.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AssessedSqlInstanceV2OperationsClient.java new file mode 100644 index 000000000000..a0c4c1265285 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AssessedSqlInstanceV2OperationsClient.java @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlInstanceV2Inner; + +/** + * An instance of this class provides access to all the operations defined in AssessedSqlInstanceV2OperationsClient. + */ +public interface AssessedSqlInstanceV2OperationsClient { + /** + * List AssessedSqlInstanceV2 resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlInstanceV2 list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName); + + /** + * List AssessedSqlInstanceV2 resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlInstanceV2 list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName, String filter, Integer pageSize, String continuationToken, + Integer totalRecordCount, Context context); + + /** + * Get a AssessedSqlInstanceV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param assessedSqlInstanceName Sql assessment Assessed Instance ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlInstanceV2 along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, String assessedSqlInstanceName, Context context); + + /** + * Get a AssessedSqlInstanceV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param assessedSqlInstanceName Sql assessment Assessed Instance ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlInstanceV2. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + AssessedSqlInstanceV2Inner get(String resourceGroupName, String projectName, String groupName, + String assessmentName, String assessedSqlInstanceName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AssessedSqlMachinesOperationsClient.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AssessedSqlMachinesOperationsClient.java new file mode 100644 index 000000000000..f676d43a87b8 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AssessedSqlMachinesOperationsClient.java @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlMachineInner; + +/** + * An instance of this class provides access to all the operations defined in AssessedSqlMachinesOperationsClient. + */ +public interface AssessedSqlMachinesOperationsClient { + /** + * List AssessedSqlMachine resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlMachine list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName); + + /** + * List AssessedSqlMachine resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlMachine list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName, String filter, Integer pageSize, String continuationToken, + Integer totalRecordCount, Context context); + + /** + * Get a AssessedSqlMachine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param assessedSqlMachineName Sql assessment Assessed Machine ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlMachine along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, String assessedSqlMachineName, Context context); + + /** + * Get a AssessedSqlMachine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param assessedSqlMachineName Sql assessment Assessed Machine ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlMachine. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + AssessedSqlMachineInner get(String resourceGroupName, String projectName, String groupName, String assessmentName, + String assessedSqlMachineName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AssessedSqlRecommendedEntityOperationsClient.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AssessedSqlRecommendedEntityOperationsClient.java new file mode 100644 index 000000000000..22683f66c45f --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AssessedSqlRecommendedEntityOperationsClient.java @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlRecommendedEntityInner; + +/** + * An instance of this class provides access to all the operations defined in + * AssessedSqlRecommendedEntityOperationsClient. + */ +public interface AssessedSqlRecommendedEntityOperationsClient { + /** + * List AssessedSqlRecommendedEntity resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlRecommendedEntity list operation as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName); + + /** + * List AssessedSqlRecommendedEntity resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlRecommendedEntity list operation as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName, String filter, Integer pageSize, String continuationToken, + Integer totalRecordCount, Context context); + + /** + * Get a AssessedSqlRecommendedEntity. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param recommendedAssessedEntityName Sql assessment Assessed Recommended Entity ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlRecommendedEntity along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceGroupName, String projectName, + String groupName, String assessmentName, String recommendedAssessedEntityName, Context context); + + /** + * Get a AssessedSqlRecommendedEntity. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param recommendedAssessedEntityName Sql assessment Assessed Recommended Entity ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlRecommendedEntity. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + AssessedSqlRecommendedEntityInner get(String resourceGroupName, String projectName, String groupName, + String assessmentName, String recommendedAssessedEntityName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AssessmentOptionsOperationsClient.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AssessmentOptionsOperationsClient.java new file mode 100644 index 000000000000..a7b7acb8f35f --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AssessmentOptionsOperationsClient.java @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentOptionsInner; + +/** + * An instance of this class provides access to all the operations defined in AssessmentOptionsOperationsClient. + */ +public interface AssessmentOptionsOperationsClient { + /** + * List AssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentOptions list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName); + + /** + * List AssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentOptions list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context); + + /** + * Get a AssessmentOptions. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param assessmentOptionsName assessment options ARM name. Accepted value is 'default'. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessmentOptions along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceGroupName, String projectName, + String assessmentOptionsName, Context context); + + /** + * Get a AssessmentOptions. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param assessmentOptionsName assessment options ARM name. Accepted value is 'default'. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessmentOptions. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + AssessmentOptionsInner get(String resourceGroupName, String projectName, String assessmentOptionsName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AssessmentProjectSummaryOperationsClient.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AssessmentProjectSummaryOperationsClient.java new file mode 100644 index 000000000000..82d40c43bbba --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AssessmentProjectSummaryOperationsClient.java @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentProjectSummaryInner; + +/** + * An instance of this class provides access to all the operations defined in AssessmentProjectSummaryOperationsClient. + */ +public interface AssessmentProjectSummaryOperationsClient { + /** + * List AssessmentProjectSummary resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProjectSummary list operation as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName); + + /** + * List AssessmentProjectSummary resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProjectSummary list operation as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context); + + /** + * Get a AssessmentProjectSummary. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param projectSummaryName Group ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessmentProjectSummary along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceGroupName, String projectName, + String projectSummaryName, Context context); + + /** + * Get a AssessmentProjectSummary. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param projectSummaryName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessmentProjectSummary. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + AssessmentProjectSummaryInner get(String resourceGroupName, String projectName, String projectSummaryName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AssessmentProjectsOperationsClient.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AssessmentProjectsOperationsClient.java new file mode 100644 index 000000000000..7961ba27a66e --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AssessmentProjectsOperationsClient.java @@ -0,0 +1,243 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentProjectInner; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProjectUpdate; + +/** + * An instance of this class provides access to all the operations defined in AssessmentProjectsOperationsClient. + */ +public interface AssessmentProjectsOperationsClient { + /** + * List AssessmentProject resources by subscription ID. + * + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProject list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(); + + /** + * List AssessmentProject resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProject list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(Context context); + + /** + * List AssessmentProject resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProject list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByResourceGroup(String resourceGroupName); + + /** + * List AssessmentProject resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProject list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByResourceGroup(String resourceGroupName, Context context); + + /** + * Get a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessmentProject along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getByResourceGroupWithResponse(String resourceGroupName, String projectName, + Context context); + + /** + * Get a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessmentProject. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + AssessmentProjectInner getByResourceGroup(String resourceGroupName, String projectName); + + /** + * Create a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of an Assessment project site resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, AssessmentProjectInner> beginCreate(String resourceGroupName, + String projectName, AssessmentProjectInner resource); + + /** + * Create a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of an Assessment project site resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, AssessmentProjectInner> beginCreate(String resourceGroupName, + String projectName, AssessmentProjectInner resource, Context context); + + /** + * Create a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Assessment project site resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + AssessmentProjectInner create(String resourceGroupName, String projectName, AssessmentProjectInner resource); + + /** + * Create a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Assessment project site resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + AssessmentProjectInner create(String resourceGroupName, String projectName, AssessmentProjectInner resource, + Context context); + + /** + * Update a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of an Assessment project site resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, AssessmentProjectInner> beginUpdate(String resourceGroupName, + String projectName, AssessmentProjectUpdate properties); + + /** + * Update a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param properties The resource properties to be updated. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of an Assessment project site resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, AssessmentProjectInner> beginUpdate(String resourceGroupName, + String projectName, AssessmentProjectUpdate properties, Context context); + + /** + * Update a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Assessment project site resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + AssessmentProjectInner update(String resourceGroupName, String projectName, AssessmentProjectUpdate properties); + + /** + * Update a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param properties The resource properties to be updated. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Assessment project site resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + AssessmentProjectInner update(String resourceGroupName, String projectName, AssessmentProjectUpdate properties, + Context context); + + /** + * Delete a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response deleteWithResponse(String resourceGroupName, String projectName, Context context); + + /** + * Delete a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void delete(String resourceGroupName, String projectName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AssessmentsOperationsClient.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AssessmentsOperationsClient.java new file mode 100644 index 000000000000..8cc3299e80c7 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AssessmentsOperationsClient.java @@ -0,0 +1,261 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentInner; +import com.azure.resourcemanager.migration.assessment.fluent.models.DownloadUrlInner; + +/** + * An instance of this class provides access to all the operations defined in AssessmentsOperationsClient. + */ +public interface AssessmentsOperationsClient { + /** + * List Assessment resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Assessment list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByGroup(String resourceGroupName, String projectName, String groupName); + + /** + * List Assessment resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Assessment list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByGroup(String resourceGroupName, String projectName, String groupName, + Context context); + + /** + * Get a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Assessment along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, Context context); + + /** + * Get a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Assessment. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + AssessmentInner get(String resourceGroupName, String projectName, String groupName, String assessmentName); + + /** + * Create a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of machine assessment resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, AssessmentInner> beginCreate(String resourceGroupName, String projectName, + String groupName, String assessmentName, AssessmentInner resource); + + /** + * Create a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of machine assessment resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, AssessmentInner> beginCreate(String resourceGroupName, String projectName, + String groupName, String assessmentName, AssessmentInner resource, Context context); + + /** + * Create a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return machine assessment resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + AssessmentInner create(String resourceGroupName, String projectName, String groupName, String assessmentName, + AssessmentInner resource); + + /** + * Create a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return machine assessment resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + AssessmentInner create(String resourceGroupName, String projectName, String groupName, String assessmentName, + AssessmentInner resource, Context context); + + /** + * Delete a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response deleteWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, Context context); + + /** + * Delete a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void delete(String resourceGroupName, String projectName, String groupName, String assessmentName); + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, DownloadUrlInner> beginDownloadUrl(String resourceGroupName, + String projectName, String groupName, String assessmentName, Object body); + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, DownloadUrlInner> beginDownloadUrl(String resourceGroupName, + String projectName, String groupName, String assessmentName, Object body, Context context); + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + DownloadUrlInner downloadUrl(String resourceGroupName, String projectName, String groupName, String assessmentName, + Object body); + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + DownloadUrlInner downloadUrl(String resourceGroupName, String projectName, String groupName, String assessmentName, + Object body, Context context); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AvsAssessedMachinesOperationsClient.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AvsAssessedMachinesOperationsClient.java new file mode 100644 index 000000000000..1d9f199cbb64 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AvsAssessedMachinesOperationsClient.java @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.AvsAssessedMachineInner; + +/** + * An instance of this class provides access to all the operations defined in AvsAssessedMachinesOperationsClient. + */ +public interface AvsAssessedMachinesOperationsClient { + /** + * List AvsAssessedMachine resources by AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessedMachine list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAvsAssessment(String resourceGroupName, String projectName, + String groupName, String assessmentName); + + /** + * List AvsAssessedMachine resources by AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessedMachine list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAvsAssessment(String resourceGroupName, String projectName, + String groupName, String assessmentName, String filter, Integer pageSize, String continuationToken, + Integer totalRecordCount, Context context); + + /** + * Get a AvsAssessedMachine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param avsAssessedMachineName AVS assessment Assessed Machine ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AvsAssessedMachine along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, String avsAssessedMachineName, Context context); + + /** + * Get a AvsAssessedMachine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param avsAssessedMachineName AVS assessment Assessed Machine ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AvsAssessedMachine. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + AvsAssessedMachineInner get(String resourceGroupName, String projectName, String groupName, String assessmentName, + String avsAssessedMachineName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AvsAssessmentOptionsOperationsClient.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AvsAssessmentOptionsOperationsClient.java new file mode 100644 index 000000000000..8c660a9e6bbd --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AvsAssessmentOptionsOperationsClient.java @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.AvsAssessmentOptionsInner; + +/** + * An instance of this class provides access to all the operations defined in AvsAssessmentOptionsOperationsClient. + */ +public interface AvsAssessmentOptionsOperationsClient { + /** + * List AvsAssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessmentOptions list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName); + + /** + * List AvsAssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessmentOptions list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context); + + /** + * Get a AvsAssessmentOptions. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param avsAssessmentOptionsName AVS Assessment options ARM name. Accepted value is 'default'. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AvsAssessmentOptions along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceGroupName, String projectName, + String avsAssessmentOptionsName, Context context); + + /** + * Get a AvsAssessmentOptions. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param avsAssessmentOptionsName AVS Assessment options ARM name. Accepted value is 'default'. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AvsAssessmentOptions. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + AvsAssessmentOptionsInner get(String resourceGroupName, String projectName, String avsAssessmentOptionsName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AvsAssessmentsOperationsClient.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AvsAssessmentsOperationsClient.java new file mode 100644 index 000000000000..16d92ec87274 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/AvsAssessmentsOperationsClient.java @@ -0,0 +1,261 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.migration.assessment.fluent.models.AvsAssessmentInner; +import com.azure.resourcemanager.migration.assessment.fluent.models.DownloadUrlInner; + +/** + * An instance of this class provides access to all the operations defined in AvsAssessmentsOperationsClient. + */ +public interface AvsAssessmentsOperationsClient { + /** + * List AvsAssessment resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessment list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByGroup(String resourceGroupName, String projectName, String groupName); + + /** + * List AvsAssessment resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessment list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByGroup(String resourceGroupName, String projectName, String groupName, + Context context); + + /** + * Get a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AvsAssessment along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, Context context); + + /** + * Get a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AvsAssessment. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + AvsAssessmentInner get(String resourceGroupName, String projectName, String groupName, String assessmentName); + + /** + * Create a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of aVS assessment resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, AvsAssessmentInner> beginCreate(String resourceGroupName, + String projectName, String groupName, String assessmentName, AvsAssessmentInner resource); + + /** + * Create a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of aVS assessment resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, AvsAssessmentInner> beginCreate(String resourceGroupName, + String projectName, String groupName, String assessmentName, AvsAssessmentInner resource, Context context); + + /** + * Create a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return aVS assessment resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + AvsAssessmentInner create(String resourceGroupName, String projectName, String groupName, String assessmentName, + AvsAssessmentInner resource); + + /** + * Create a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return aVS assessment resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + AvsAssessmentInner create(String resourceGroupName, String projectName, String groupName, String assessmentName, + AvsAssessmentInner resource, Context context); + + /** + * Delete a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response deleteWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, Context context); + + /** + * Delete a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void delete(String resourceGroupName, String projectName, String groupName, String assessmentName); + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, DownloadUrlInner> beginDownloadUrl(String resourceGroupName, + String projectName, String groupName, String assessmentName, Object body); + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, DownloadUrlInner> beginDownloadUrl(String resourceGroupName, + String projectName, String groupName, String assessmentName, Object body, Context context); + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + DownloadUrlInner downloadUrl(String resourceGroupName, String projectName, String groupName, String assessmentName, + Object body); + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + DownloadUrlInner downloadUrl(String resourceGroupName, String projectName, String groupName, String assessmentName, + Object body, Context context); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/GroupsOperationsClient.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/GroupsOperationsClient.java new file mode 100644 index 000000000000..25b4362edabd --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/GroupsOperationsClient.java @@ -0,0 +1,243 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.migration.assessment.fluent.models.GroupInner; +import com.azure.resourcemanager.migration.assessment.models.UpdateGroupBody; + +/** + * An instance of this class provides access to all the operations defined in GroupsOperationsClient. + */ +public interface GroupsOperationsClient { + /** + * List Group resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Group list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName); + + /** + * List Group resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Group list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, Context context); + + /** + * Get a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Group along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceGroupName, String projectName, String groupName, + Context context); + + /** + * Get a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Group. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + GroupInner get(String resourceGroupName, String projectName, String groupName); + + /** + * Create a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of group resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, GroupInner> beginCreate(String resourceGroupName, String projectName, + String groupName, GroupInner resource); + + /** + * Create a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of group resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, GroupInner> beginCreate(String resourceGroupName, String projectName, + String groupName, GroupInner resource, Context context); + + /** + * Create a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return group resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + GroupInner create(String resourceGroupName, String projectName, String groupName, GroupInner resource); + + /** + * Create a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return group resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + GroupInner create(String resourceGroupName, String projectName, String groupName, GroupInner resource, + Context context); + + /** + * Delete a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response deleteWithResponse(String resourceGroupName, String projectName, String groupName, Context context); + + /** + * Delete a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void delete(String resourceGroupName, String projectName, String groupName); + + /** + * Update machines in group. + * + * Update machines in group by adding or removing machines. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of group resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, GroupInner> beginUpdateMachines(String resourceGroupName, String projectName, + String groupName, UpdateGroupBody body); + + /** + * Update machines in group. + * + * Update machines in group by adding or removing machines. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of group resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, GroupInner> beginUpdateMachines(String resourceGroupName, String projectName, + String groupName, UpdateGroupBody body, Context context); + + /** + * Update machines in group. + * + * Update machines in group by adding or removing machines. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return group resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + GroupInner updateMachines(String resourceGroupName, String projectName, String groupName, UpdateGroupBody body); + + /** + * Update machines in group. + * + * Update machines in group by adding or removing machines. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return group resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + GroupInner updateMachines(String resourceGroupName, String projectName, String groupName, UpdateGroupBody body, + Context context); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/HypervCollectorsOperationsClient.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/HypervCollectorsOperationsClient.java new file mode 100644 index 000000000000..101f8478dff4 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/HypervCollectorsOperationsClient.java @@ -0,0 +1,172 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.migration.assessment.fluent.models.HypervCollectorInner; + +/** + * An instance of this class provides access to all the operations defined in HypervCollectorsOperationsClient. + */ +public interface HypervCollectorsOperationsClient { + /** + * List HypervCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a HypervCollector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName); + + /** + * List HypervCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a HypervCollector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context); + + /** + * Get a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a HypervCollector along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceGroupName, String projectName, + String hypervCollectorName, Context context); + + /** + * Get a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a HypervCollector. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + HypervCollectorInner get(String resourceGroupName, String projectName, String hypervCollectorName); + + /** + * Create a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of hyper-V collector resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, HypervCollectorInner> beginCreate(String resourceGroupName, + String projectName, String hypervCollectorName, HypervCollectorInner resource); + + /** + * Create a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of hyper-V collector resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, HypervCollectorInner> beginCreate(String resourceGroupName, + String projectName, String hypervCollectorName, HypervCollectorInner resource, Context context); + + /** + * Create a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return hyper-V collector resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + HypervCollectorInner create(String resourceGroupName, String projectName, String hypervCollectorName, + HypervCollectorInner resource); + + /** + * Create a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return hyper-V collector resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + HypervCollectorInner create(String resourceGroupName, String projectName, String hypervCollectorName, + HypervCollectorInner resource, Context context); + + /** + * Delete a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response deleteWithResponse(String resourceGroupName, String projectName, String hypervCollectorName, + Context context); + + /** + * Delete a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void delete(String resourceGroupName, String projectName, String hypervCollectorName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/ImportCollectorsOperationsClient.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/ImportCollectorsOperationsClient.java new file mode 100644 index 000000000000..4273a751dc52 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/ImportCollectorsOperationsClient.java @@ -0,0 +1,172 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.migration.assessment.fluent.models.ImportCollectorInner; + +/** + * An instance of this class provides access to all the operations defined in ImportCollectorsOperationsClient. + */ +public interface ImportCollectorsOperationsClient { + /** + * List ImportCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ImportCollector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName); + + /** + * List ImportCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ImportCollector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context); + + /** + * Get a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ImportCollector along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceGroupName, String projectName, + String importCollectorName, Context context); + + /** + * Get a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ImportCollector. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + ImportCollectorInner get(String resourceGroupName, String projectName, String importCollectorName); + + /** + * Create a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of import collector resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, ImportCollectorInner> beginCreate(String resourceGroupName, + String projectName, String importCollectorName, ImportCollectorInner resource); + + /** + * Create a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of import collector resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, ImportCollectorInner> beginCreate(String resourceGroupName, + String projectName, String importCollectorName, ImportCollectorInner resource, Context context); + + /** + * Create a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return import collector resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + ImportCollectorInner create(String resourceGroupName, String projectName, String importCollectorName, + ImportCollectorInner resource); + + /** + * Create a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return import collector resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + ImportCollectorInner create(String resourceGroupName, String projectName, String importCollectorName, + ImportCollectorInner resource, Context context); + + /** + * Delete a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response deleteWithResponse(String resourceGroupName, String projectName, String importCollectorName, + Context context); + + /** + * Delete a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void delete(String resourceGroupName, String projectName, String importCollectorName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/MachinesOperationsClient.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/MachinesOperationsClient.java new file mode 100644 index 000000000000..8c7db2769da6 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/MachinesOperationsClient.java @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.MachineInner; + +/** + * An instance of this class provides access to all the operations defined in MachinesOperationsClient. + */ +public interface MachinesOperationsClient { + /** + * List Machine resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Machine list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName); + + /** + * List Machine resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Machine list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, String filter, + Integer pageSize, String continuationToken, Integer totalRecordCount, Context context); + + /** + * Get a Machine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param machineName Assessible Machine ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Machine along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceGroupName, String projectName, String machineName, + Context context); + + /** + * Get a Machine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param machineName Assessible Machine ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Machine. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + MachineInner get(String resourceGroupName, String projectName, String machineName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/MigrationAssessmentManagementClient.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/MigrationAssessmentManagementClient.java new file mode 100644 index 000000000000..51c1e938e946 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/MigrationAssessmentManagementClient.java @@ -0,0 +1,223 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent; + +import com.azure.core.http.HttpPipeline; +import java.time.Duration; + +/** + * The interface for MigrationAssessmentManagementClient class. + */ +public interface MigrationAssessmentManagementClient { + /** + * Gets The ID of the target subscription. + * + * @return the subscriptionId value. + */ + String getSubscriptionId(); + + /** + * Gets server parameter. + * + * @return the endpoint value. + */ + String getEndpoint(); + + /** + * Gets Api Version. + * + * @return the apiVersion value. + */ + String getApiVersion(); + + /** + * Gets The HTTP pipeline to send requests through. + * + * @return the httpPipeline value. + */ + HttpPipeline getHttpPipeline(); + + /** + * Gets The default poll interval for long-running operation. + * + * @return the defaultPollInterval value. + */ + Duration getDefaultPollInterval(); + + /** + * Gets the OperationsClient object to access its operations. + * + * @return the OperationsClient object. + */ + OperationsClient getOperations(); + + /** + * Gets the AssessmentProjectsOperationsClient object to access its operations. + * + * @return the AssessmentProjectsOperationsClient object. + */ + AssessmentProjectsOperationsClient getAssessmentProjectsOperations(); + + /** + * Gets the AssessmentOptionsOperationsClient object to access its operations. + * + * @return the AssessmentOptionsOperationsClient object. + */ + AssessmentOptionsOperationsClient getAssessmentOptionsOperations(); + + /** + * Gets the AvsAssessmentOptionsOperationsClient object to access its operations. + * + * @return the AvsAssessmentOptionsOperationsClient object. + */ + AvsAssessmentOptionsOperationsClient getAvsAssessmentOptionsOperations(); + + /** + * Gets the GroupsOperationsClient object to access its operations. + * + * @return the GroupsOperationsClient object. + */ + GroupsOperationsClient getGroupsOperations(); + + /** + * Gets the AssessmentsOperationsClient object to access its operations. + * + * @return the AssessmentsOperationsClient object. + */ + AssessmentsOperationsClient getAssessmentsOperations(); + + /** + * Gets the AssessedMachinesOperationsClient object to access its operations. + * + * @return the AssessedMachinesOperationsClient object. + */ + AssessedMachinesOperationsClient getAssessedMachinesOperations(); + + /** + * Gets the AvsAssessmentsOperationsClient object to access its operations. + * + * @return the AvsAssessmentsOperationsClient object. + */ + AvsAssessmentsOperationsClient getAvsAssessmentsOperations(); + + /** + * Gets the AvsAssessedMachinesOperationsClient object to access its operations. + * + * @return the AvsAssessedMachinesOperationsClient object. + */ + AvsAssessedMachinesOperationsClient getAvsAssessedMachinesOperations(); + + /** + * Gets the SqlAssessmentV2OperationsClient object to access its operations. + * + * @return the SqlAssessmentV2OperationsClient object. + */ + SqlAssessmentV2OperationsClient getSqlAssessmentV2Operations(); + + /** + * Gets the AssessedSqlDatabaseV2OperationsClient object to access its operations. + * + * @return the AssessedSqlDatabaseV2OperationsClient object. + */ + AssessedSqlDatabaseV2OperationsClient getAssessedSqlDatabaseV2Operations(); + + /** + * Gets the AssessedSqlInstanceV2OperationsClient object to access its operations. + * + * @return the AssessedSqlInstanceV2OperationsClient object. + */ + AssessedSqlInstanceV2OperationsClient getAssessedSqlInstanceV2Operations(); + + /** + * Gets the AssessedSqlMachinesOperationsClient object to access its operations. + * + * @return the AssessedSqlMachinesOperationsClient object. + */ + AssessedSqlMachinesOperationsClient getAssessedSqlMachinesOperations(); + + /** + * Gets the AssessedSqlRecommendedEntityOperationsClient object to access its operations. + * + * @return the AssessedSqlRecommendedEntityOperationsClient object. + */ + AssessedSqlRecommendedEntityOperationsClient getAssessedSqlRecommendedEntityOperations(); + + /** + * Gets the SqlAssessmentV2SummaryOperationsClient object to access its operations. + * + * @return the SqlAssessmentV2SummaryOperationsClient object. + */ + SqlAssessmentV2SummaryOperationsClient getSqlAssessmentV2SummaryOperations(); + + /** + * Gets the HypervCollectorsOperationsClient object to access its operations. + * + * @return the HypervCollectorsOperationsClient object. + */ + HypervCollectorsOperationsClient getHypervCollectorsOperations(); + + /** + * Gets the ImportCollectorsOperationsClient object to access its operations. + * + * @return the ImportCollectorsOperationsClient object. + */ + ImportCollectorsOperationsClient getImportCollectorsOperations(); + + /** + * Gets the MachinesOperationsClient object to access its operations. + * + * @return the MachinesOperationsClient object. + */ + MachinesOperationsClient getMachinesOperations(); + + /** + * Gets the PrivateEndpointConnectionOperationsClient object to access its operations. + * + * @return the PrivateEndpointConnectionOperationsClient object. + */ + PrivateEndpointConnectionOperationsClient getPrivateEndpointConnectionOperations(); + + /** + * Gets the PrivateLinkResourceOperationsClient object to access its operations. + * + * @return the PrivateLinkResourceOperationsClient object. + */ + PrivateLinkResourceOperationsClient getPrivateLinkResourceOperations(); + + /** + * Gets the AssessmentProjectSummaryOperationsClient object to access its operations. + * + * @return the AssessmentProjectSummaryOperationsClient object. + */ + AssessmentProjectSummaryOperationsClient getAssessmentProjectSummaryOperations(); + + /** + * Gets the ServerCollectorsOperationsClient object to access its operations. + * + * @return the ServerCollectorsOperationsClient object. + */ + ServerCollectorsOperationsClient getServerCollectorsOperations(); + + /** + * Gets the SqlAssessmentOptionsOperationsClient object to access its operations. + * + * @return the SqlAssessmentOptionsOperationsClient object. + */ + SqlAssessmentOptionsOperationsClient getSqlAssessmentOptionsOperations(); + + /** + * Gets the SqlCollectorOperationsClient object to access its operations. + * + * @return the SqlCollectorOperationsClient object. + */ + SqlCollectorOperationsClient getSqlCollectorOperations(); + + /** + * Gets the VmwareCollectorsOperationsClient object to access its operations. + * + * @return the VmwareCollectorsOperationsClient object. + */ + VmwareCollectorsOperationsClient getVmwareCollectorsOperations(); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/OperationsClient.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/OperationsClient.java new file mode 100644 index 000000000000..6b4e842aba53 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/OperationsClient.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.resourcemanager.migration.assessment.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.OperationInner; + +/** + * An instance of this class provides access to all the operations defined in OperationsClient. + */ +public interface OperationsClient { + /** + * List the operations for the provider. + * + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(); + + /** + * List the operations for the provider. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(Context context); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/PrivateEndpointConnectionOperationsClient.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/PrivateEndpointConnectionOperationsClient.java new file mode 100644 index 000000000000..cf56d4399537 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/PrivateEndpointConnectionOperationsClient.java @@ -0,0 +1,177 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.migration.assessment.fluent.models.PrivateEndpointConnectionInner; + +/** + * An instance of this class provides access to all the operations defined in PrivateEndpointConnectionOperationsClient. + */ +public interface PrivateEndpointConnectionOperationsClient { + /** + * List PrivateEndpointConnection resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PrivateEndpointConnection list operation as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName); + + /** + * List PrivateEndpointConnection resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PrivateEndpointConnection list operation as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context); + + /** + * Get a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a PrivateEndpointConnection along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceGroupName, String projectName, + String privateEndpointConnectionName, Context context); + + /** + * Get a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a PrivateEndpointConnection. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + PrivateEndpointConnectionInner get(String resourceGroupName, String projectName, + String privateEndpointConnectionName); + + /** + * Create a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of private endpoint connection resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, PrivateEndpointConnectionInner> beginUpdate( + String resourceGroupName, String projectName, String privateEndpointConnectionName, + PrivateEndpointConnectionInner resource); + + /** + * Create a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of private endpoint connection resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, PrivateEndpointConnectionInner> beginUpdate( + String resourceGroupName, String projectName, String privateEndpointConnectionName, + PrivateEndpointConnectionInner resource, Context context); + + /** + * Create a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return private endpoint connection resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + PrivateEndpointConnectionInner update(String resourceGroupName, String projectName, + String privateEndpointConnectionName, PrivateEndpointConnectionInner resource); + + /** + * Create a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return private endpoint connection resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + PrivateEndpointConnectionInner update(String resourceGroupName, String projectName, + String privateEndpointConnectionName, PrivateEndpointConnectionInner resource, Context context); + + /** + * Delete a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response deleteWithResponse(String resourceGroupName, String projectName, + String privateEndpointConnectionName, Context context); + + /** + * Delete a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void delete(String resourceGroupName, String projectName, String privateEndpointConnectionName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/PrivateLinkResourceOperationsClient.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/PrivateLinkResourceOperationsClient.java new file mode 100644 index 000000000000..5b9aca756a73 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/PrivateLinkResourceOperationsClient.java @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.PrivateLinkResourceInner; + +/** + * An instance of this class provides access to all the operations defined in PrivateLinkResourceOperationsClient. + */ +public interface PrivateLinkResourceOperationsClient { + /** + * List PrivateLinkResource resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PrivateLinkResource list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName); + + /** + * List PrivateLinkResource resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PrivateLinkResource list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context); + + /** + * Get a PrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateLinkResourceName Private link resource ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a PrivateLinkResource along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceGroupName, String projectName, + String privateLinkResourceName, Context context); + + /** + * Get a PrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateLinkResourceName Private link resource ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a PrivateLinkResource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + PrivateLinkResourceInner get(String resourceGroupName, String projectName, String privateLinkResourceName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/ServerCollectorsOperationsClient.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/ServerCollectorsOperationsClient.java new file mode 100644 index 000000000000..8289d03cf7e6 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/ServerCollectorsOperationsClient.java @@ -0,0 +1,172 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.migration.assessment.fluent.models.ServerCollectorInner; + +/** + * An instance of this class provides access to all the operations defined in ServerCollectorsOperationsClient. + */ +public interface ServerCollectorsOperationsClient { + /** + * List ServerCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ServerCollector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName); + + /** + * List ServerCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ServerCollector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context); + + /** + * Get a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ServerCollector along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceGroupName, String projectName, + String serverCollectorName, Context context); + + /** + * Get a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ServerCollector. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + ServerCollectorInner get(String resourceGroupName, String projectName, String serverCollectorName); + + /** + * Create a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of physical server collector resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, ServerCollectorInner> beginCreate(String resourceGroupName, + String projectName, String serverCollectorName, ServerCollectorInner resource); + + /** + * Create a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of physical server collector resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, ServerCollectorInner> beginCreate(String resourceGroupName, + String projectName, String serverCollectorName, ServerCollectorInner resource, Context context); + + /** + * Create a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return physical server collector resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + ServerCollectorInner create(String resourceGroupName, String projectName, String serverCollectorName, + ServerCollectorInner resource); + + /** + * Create a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return physical server collector resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + ServerCollectorInner create(String resourceGroupName, String projectName, String serverCollectorName, + ServerCollectorInner resource, Context context); + + /** + * Delete a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response deleteWithResponse(String resourceGroupName, String projectName, String serverCollectorName, + Context context); + + /** + * Delete a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void delete(String resourceGroupName, String projectName, String serverCollectorName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/SqlAssessmentOptionsOperationsClient.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/SqlAssessmentOptionsOperationsClient.java new file mode 100644 index 000000000000..0c0fd604c4bf --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/SqlAssessmentOptionsOperationsClient.java @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlAssessmentOptionsInner; + +/** + * An instance of this class provides access to all the operations defined in SqlAssessmentOptionsOperationsClient. + */ +public interface SqlAssessmentOptionsOperationsClient { + /** + * List SqlAssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentOptions list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName); + + /** + * List SqlAssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentOptions list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context); + + /** + * Get a SqlAssessmentOptions. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param assessmentOptionsName Sql assessment options ARM name. Accepted values is 'default'. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlAssessmentOptions along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceGroupName, String projectName, + String assessmentOptionsName, Context context); + + /** + * Get a SqlAssessmentOptions. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param assessmentOptionsName Sql assessment options ARM name. Accepted values is 'default'. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlAssessmentOptions. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + SqlAssessmentOptionsInner get(String resourceGroupName, String projectName, String assessmentOptionsName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/SqlAssessmentV2OperationsClient.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/SqlAssessmentV2OperationsClient.java new file mode 100644 index 000000000000..2aa35203f534 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/SqlAssessmentV2OperationsClient.java @@ -0,0 +1,261 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.migration.assessment.fluent.models.DownloadUrlInner; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlAssessmentV2Inner; + +/** + * An instance of this class provides access to all the operations defined in SqlAssessmentV2OperationsClient. + */ +public interface SqlAssessmentV2OperationsClient { + /** + * List SqlAssessmentV2 resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentV2 list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByGroup(String resourceGroupName, String projectName, String groupName); + + /** + * List SqlAssessmentV2 resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentV2 list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByGroup(String resourceGroupName, String projectName, String groupName, + Context context); + + /** + * Get a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlAssessmentV2 along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, Context context); + + /** + * Get a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlAssessmentV2. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + SqlAssessmentV2Inner get(String resourceGroupName, String projectName, String groupName, String assessmentName); + + /** + * Create a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of sQL Assessment REST resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, SqlAssessmentV2Inner> beginCreate(String resourceGroupName, + String projectName, String groupName, String assessmentName, SqlAssessmentV2Inner resource); + + /** + * Create a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of sQL Assessment REST resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, SqlAssessmentV2Inner> beginCreate(String resourceGroupName, + String projectName, String groupName, String assessmentName, SqlAssessmentV2Inner resource, Context context); + + /** + * Create a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return sQL Assessment REST resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + SqlAssessmentV2Inner create(String resourceGroupName, String projectName, String groupName, String assessmentName, + SqlAssessmentV2Inner resource); + + /** + * Create a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return sQL Assessment REST resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + SqlAssessmentV2Inner create(String resourceGroupName, String projectName, String groupName, String assessmentName, + SqlAssessmentV2Inner resource, Context context); + + /** + * Delete a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response deleteWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, Context context); + + /** + * Delete a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void delete(String resourceGroupName, String projectName, String groupName, String assessmentName); + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, DownloadUrlInner> beginDownloadUrl(String resourceGroupName, + String projectName, String groupName, String assessmentName, Object body); + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, DownloadUrlInner> beginDownloadUrl(String resourceGroupName, + String projectName, String groupName, String assessmentName, Object body, Context context); + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + DownloadUrlInner downloadUrl(String resourceGroupName, String projectName, String groupName, String assessmentName, + Object body); + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + DownloadUrlInner downloadUrl(String resourceGroupName, String projectName, String groupName, String assessmentName, + Object body, Context context); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/SqlAssessmentV2SummaryOperationsClient.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/SqlAssessmentV2SummaryOperationsClient.java new file mode 100644 index 000000000000..5ed8dd3c7c5b --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/SqlAssessmentV2SummaryOperationsClient.java @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlAssessmentV2SummaryInner; + +/** + * An instance of this class provides access to all the operations defined in SqlAssessmentV2SummaryOperationsClient. + */ +public interface SqlAssessmentV2SummaryOperationsClient { + /** + * List SqlAssessmentV2Summary resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentV2Summary list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName); + + /** + * List SqlAssessmentV2Summary resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentV2Summary list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName, Context context); + + /** + * Get a SqlAssessmentV2Summary. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param summaryName Gets the Name of the SQL Summary. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlAssessmentV2Summary along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceGroupName, String projectName, + String groupName, String assessmentName, String summaryName, Context context); + + /** + * Get a SqlAssessmentV2Summary. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param summaryName Gets the Name of the SQL Summary. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlAssessmentV2Summary. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + SqlAssessmentV2SummaryInner get(String resourceGroupName, String projectName, String groupName, + String assessmentName, String summaryName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/SqlCollectorOperationsClient.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/SqlCollectorOperationsClient.java new file mode 100644 index 000000000000..22ae5a0c1df5 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/SqlCollectorOperationsClient.java @@ -0,0 +1,172 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlCollectorInner; + +/** + * An instance of this class provides access to all the operations defined in SqlCollectorOperationsClient. + */ +public interface SqlCollectorOperationsClient { + /** + * List SqlCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlCollector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName); + + /** + * List SqlCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlCollector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context); + + /** + * Get a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlCollector along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceGroupName, String projectName, String collectorName, + Context context); + + /** + * Get a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlCollector. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + SqlCollectorInner get(String resourceGroupName, String projectName, String collectorName); + + /** + * Create a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of the SQL collector REST object. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, SqlCollectorInner> beginCreate(String resourceGroupName, + String projectName, String collectorName, SqlCollectorInner resource); + + /** + * Create a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of the SQL collector REST object. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, SqlCollectorInner> beginCreate(String resourceGroupName, + String projectName, String collectorName, SqlCollectorInner resource, Context context); + + /** + * Create a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the SQL collector REST object. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + SqlCollectorInner create(String resourceGroupName, String projectName, String collectorName, + SqlCollectorInner resource); + + /** + * Create a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the SQL collector REST object. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + SqlCollectorInner create(String resourceGroupName, String projectName, String collectorName, + SqlCollectorInner resource, Context context); + + /** + * Delete a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response deleteWithResponse(String resourceGroupName, String projectName, String collectorName, + Context context); + + /** + * Delete a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void delete(String resourceGroupName, String projectName, String collectorName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/VmwareCollectorsOperationsClient.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/VmwareCollectorsOperationsClient.java new file mode 100644 index 000000000000..b74e2ff07ddb --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/VmwareCollectorsOperationsClient.java @@ -0,0 +1,172 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.migration.assessment.fluent.models.VmwareCollectorInner; + +/** + * An instance of this class provides access to all the operations defined in VmwareCollectorsOperationsClient. + */ +public interface VmwareCollectorsOperationsClient { + /** + * List VmwareCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a VmwareCollector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName); + + /** + * List VmwareCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a VmwareCollector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context); + + /** + * Get a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a VmwareCollector along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceGroupName, String projectName, + String vmWareCollectorName, Context context); + + /** + * Get a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a VmwareCollector. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + VmwareCollectorInner get(String resourceGroupName, String projectName, String vmWareCollectorName); + + /** + * Create a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of vMware collector resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, VmwareCollectorInner> beginCreate(String resourceGroupName, + String projectName, String vmWareCollectorName, VmwareCollectorInner resource); + + /** + * Create a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of vMware collector resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, VmwareCollectorInner> beginCreate(String resourceGroupName, + String projectName, String vmWareCollectorName, VmwareCollectorInner resource, Context context); + + /** + * Create a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return vMware collector resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + VmwareCollectorInner create(String resourceGroupName, String projectName, String vmWareCollectorName, + VmwareCollectorInner resource); + + /** + * Create a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return vMware collector resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + VmwareCollectorInner create(String resourceGroupName, String projectName, String vmWareCollectorName, + VmwareCollectorInner resource, Context context); + + /** + * Delete a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response deleteWithResponse(String resourceGroupName, String projectName, String vmWareCollectorName, + Context context); + + /** + * Delete a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void delete(String resourceGroupName, String projectName, String vmWareCollectorName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AssessedMachineInner.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AssessedMachineInner.java new file mode 100644 index 000000000000..54b7bc81f0a3 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AssessedMachineInner.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. + +package com.azure.resourcemanager.migration.assessment.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.models.AssessedMachineProperties; +import java.io.IOException; + +/** + * Machine assessment Assessed Machine resource. + */ +@Fluent +public final class AssessedMachineInner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private AssessedMachineProperties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of AssessedMachineInner class. + */ + public AssessedMachineInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public AssessedMachineProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the AssessedMachineInner object itself. + */ + public AssessedMachineInner withProperties(AssessedMachineProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessedMachineInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessedMachineInner 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 AssessedMachineInner. + */ + public static AssessedMachineInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessedMachineInner deserializedAssessedMachineInner = new AssessedMachineInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedAssessedMachineInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedAssessedMachineInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedAssessedMachineInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedAssessedMachineInner.properties = AssessedMachineProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedAssessedMachineInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessedMachineInner; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AssessedSqlDatabaseV2Inner.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AssessedSqlDatabaseV2Inner.java new file mode 100644 index 000000000000..c9517a74c948 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AssessedSqlDatabaseV2Inner.java @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlDatabaseV2Properties; +import java.io.IOException; + +/** + * Assessed SQL database web model class. + */ +@Fluent +public final class AssessedSqlDatabaseV2Inner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private AssessedSqlDatabaseV2Properties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of AssessedSqlDatabaseV2Inner class. + */ + public AssessedSqlDatabaseV2Inner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public AssessedSqlDatabaseV2Properties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the AssessedSqlDatabaseV2Inner object itself. + */ + public AssessedSqlDatabaseV2Inner withProperties(AssessedSqlDatabaseV2Properties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessedSqlDatabaseV2Inner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessedSqlDatabaseV2Inner 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 AssessedSqlDatabaseV2Inner. + */ + public static AssessedSqlDatabaseV2Inner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessedSqlDatabaseV2Inner deserializedAssessedSqlDatabaseV2Inner = new AssessedSqlDatabaseV2Inner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Inner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Inner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Inner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Inner.properties + = AssessedSqlDatabaseV2Properties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Inner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessedSqlDatabaseV2Inner; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AssessedSqlInstanceV2Inner.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AssessedSqlInstanceV2Inner.java new file mode 100644 index 000000000000..b73f608e07c7 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AssessedSqlInstanceV2Inner.java @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlInstanceV2Properties; +import java.io.IOException; + +/** + * Assessed SQL instance web model class. + */ +@Fluent +public final class AssessedSqlInstanceV2Inner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private AssessedSqlInstanceV2Properties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of AssessedSqlInstanceV2Inner class. + */ + public AssessedSqlInstanceV2Inner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public AssessedSqlInstanceV2Properties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the AssessedSqlInstanceV2Inner object itself. + */ + public AssessedSqlInstanceV2Inner withProperties(AssessedSqlInstanceV2Properties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessedSqlInstanceV2Inner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessedSqlInstanceV2Inner 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 AssessedSqlInstanceV2Inner. + */ + public static AssessedSqlInstanceV2Inner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessedSqlInstanceV2Inner deserializedAssessedSqlInstanceV2Inner = new AssessedSqlInstanceV2Inner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Inner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Inner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Inner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Inner.properties + = AssessedSqlInstanceV2Properties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Inner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessedSqlInstanceV2Inner; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AssessedSqlMachineInner.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AssessedSqlMachineInner.java new file mode 100644 index 000000000000..5488db54d19e --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AssessedSqlMachineInner.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. + +package com.azure.resourcemanager.migration.assessment.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlMachineProperties; +import java.io.IOException; + +/** + * SQL Assessment REST resource. + */ +@Fluent +public final class AssessedSqlMachineInner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private AssessedSqlMachineProperties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of AssessedSqlMachineInner class. + */ + public AssessedSqlMachineInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public AssessedSqlMachineProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the AssessedSqlMachineInner object itself. + */ + public AssessedSqlMachineInner withProperties(AssessedSqlMachineProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessedSqlMachineInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessedSqlMachineInner 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 AssessedSqlMachineInner. + */ + public static AssessedSqlMachineInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessedSqlMachineInner deserializedAssessedSqlMachineInner = new AssessedSqlMachineInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedAssessedSqlMachineInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedAssessedSqlMachineInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedAssessedSqlMachineInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedAssessedSqlMachineInner.properties = AssessedSqlMachineProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedAssessedSqlMachineInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessedSqlMachineInner; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AssessedSqlRecommendedEntityInner.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AssessedSqlRecommendedEntityInner.java new file mode 100644 index 000000000000..a71e8547dba5 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AssessedSqlRecommendedEntityInner.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. + +package com.azure.resourcemanager.migration.assessment.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlRecommendedEntityProperties; +import java.io.IOException; + +/** + * SQL Assessment REST resource. + */ +@Fluent +public final class AssessedSqlRecommendedEntityInner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private AssessedSqlRecommendedEntityProperties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of AssessedSqlRecommendedEntityInner class. + */ + public AssessedSqlRecommendedEntityInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public AssessedSqlRecommendedEntityProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the AssessedSqlRecommendedEntityInner object itself. + */ + public AssessedSqlRecommendedEntityInner withProperties(AssessedSqlRecommendedEntityProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessedSqlRecommendedEntityInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessedSqlRecommendedEntityInner 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 AssessedSqlRecommendedEntityInner. + */ + public static AssessedSqlRecommendedEntityInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessedSqlRecommendedEntityInner deserializedAssessedSqlRecommendedEntityInner + = new AssessedSqlRecommendedEntityInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedAssessedSqlRecommendedEntityInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedAssessedSqlRecommendedEntityInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedAssessedSqlRecommendedEntityInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedAssessedSqlRecommendedEntityInner.properties + = AssessedSqlRecommendedEntityProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedAssessedSqlRecommendedEntityInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessedSqlRecommendedEntityInner; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AssessmentInner.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AssessmentInner.java new file mode 100644 index 000000000000..18d43f0acdc5 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AssessmentInner.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. + +package com.azure.resourcemanager.migration.assessment.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.models.MachineAssessmentProperties; +import java.io.IOException; + +/** + * Machine assessment resource. + */ +@Fluent +public final class AssessmentInner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private MachineAssessmentProperties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of AssessmentInner class. + */ + public AssessmentInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public MachineAssessmentProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the AssessmentInner object itself. + */ + public AssessmentInner withProperties(MachineAssessmentProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessmentInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessmentInner 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 AssessmentInner. + */ + public static AssessmentInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessmentInner deserializedAssessmentInner = new AssessmentInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedAssessmentInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedAssessmentInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedAssessmentInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedAssessmentInner.properties = MachineAssessmentProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedAssessmentInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessmentInner; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AssessmentOptionsInner.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AssessmentOptionsInner.java new file mode 100644 index 000000000000..2f9cd6facb61 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AssessmentOptionsInner.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. + +package com.azure.resourcemanager.migration.assessment.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.models.AssessmentOptionsProperties; +import java.io.IOException; + +/** + * Assessment options resource. + */ +@Fluent +public final class AssessmentOptionsInner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private AssessmentOptionsProperties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of AssessmentOptionsInner class. + */ + public AssessmentOptionsInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public AssessmentOptionsProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the AssessmentOptionsInner object itself. + */ + public AssessmentOptionsInner withProperties(AssessmentOptionsProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessmentOptionsInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessmentOptionsInner 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 AssessmentOptionsInner. + */ + public static AssessmentOptionsInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessmentOptionsInner deserializedAssessmentOptionsInner = new AssessmentOptionsInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedAssessmentOptionsInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedAssessmentOptionsInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedAssessmentOptionsInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedAssessmentOptionsInner.properties = AssessmentOptionsProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedAssessmentOptionsInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessmentOptionsInner; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AssessmentProjectInner.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AssessmentProjectInner.java new file mode 100644 index 000000000000..362688a76b25 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AssessmentProjectInner.java @@ -0,0 +1,192 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.Resource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.models.ProjectProperties; +import java.io.IOException; +import java.util.Map; + +/** + * An Assessment project site resource. + */ +@Fluent +public final class AssessmentProjectInner extends Resource { + /* + * The resource-specific properties for this resource. + */ + private ProjectProperties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of AssessmentProjectInner class. + */ + public AssessmentProjectInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public ProjectProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the AssessmentProjectInner object itself. + */ + public AssessmentProjectInner withProperties(ProjectProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * {@inheritDoc} + */ + @Override + public AssessmentProjectInner withLocation(String location) { + super.withLocation(location); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AssessmentProjectInner withTags(Map tags) { + super.withTags(tags); + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("location", location()); + jsonWriter.writeMapField("tags", tags(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessmentProjectInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessmentProjectInner 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 AssessmentProjectInner. + */ + public static AssessmentProjectInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessmentProjectInner deserializedAssessmentProjectInner = new AssessmentProjectInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedAssessmentProjectInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedAssessmentProjectInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedAssessmentProjectInner.type = reader.getString(); + } else if ("location".equals(fieldName)) { + deserializedAssessmentProjectInner.withLocation(reader.getString()); + } else if ("tags".equals(fieldName)) { + Map tags = reader.readMap(reader1 -> reader1.getString()); + deserializedAssessmentProjectInner.withTags(tags); + } else if ("properties".equals(fieldName)) { + deserializedAssessmentProjectInner.properties = ProjectProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedAssessmentProjectInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessmentProjectInner; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AssessmentProjectSummaryInner.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AssessmentProjectSummaryInner.java new file mode 100644 index 000000000000..1401c5de0e7a --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AssessmentProjectSummaryInner.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. + +package com.azure.resourcemanager.migration.assessment.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProjectSummaryProperties; +import java.io.IOException; + +/** + * Assessment project summary resource. + */ +@Fluent +public final class AssessmentProjectSummaryInner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private AssessmentProjectSummaryProperties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of AssessmentProjectSummaryInner class. + */ + public AssessmentProjectSummaryInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public AssessmentProjectSummaryProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the AssessmentProjectSummaryInner object itself. + */ + public AssessmentProjectSummaryInner withProperties(AssessmentProjectSummaryProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessmentProjectSummaryInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessmentProjectSummaryInner 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 AssessmentProjectSummaryInner. + */ + public static AssessmentProjectSummaryInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessmentProjectSummaryInner deserializedAssessmentProjectSummaryInner + = new AssessmentProjectSummaryInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedAssessmentProjectSummaryInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedAssessmentProjectSummaryInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedAssessmentProjectSummaryInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedAssessmentProjectSummaryInner.properties + = AssessmentProjectSummaryProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedAssessmentProjectSummaryInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessmentProjectSummaryInner; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AvsAssessedMachineInner.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AvsAssessedMachineInner.java new file mode 100644 index 000000000000..355b90d6e5d7 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AvsAssessedMachineInner.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. + +package com.azure.resourcemanager.migration.assessment.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessedMachineProperties; +import java.io.IOException; + +/** + * AVS assessment Assessed Machine resource. + */ +@Fluent +public final class AvsAssessedMachineInner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private AvsAssessedMachineProperties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of AvsAssessedMachineInner class. + */ + public AvsAssessedMachineInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public AvsAssessedMachineProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the AvsAssessedMachineInner object itself. + */ + public AvsAssessedMachineInner withProperties(AvsAssessedMachineProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AvsAssessedMachineInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AvsAssessedMachineInner 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 AvsAssessedMachineInner. + */ + public static AvsAssessedMachineInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AvsAssessedMachineInner deserializedAvsAssessedMachineInner = new AvsAssessedMachineInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedAvsAssessedMachineInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedAvsAssessedMachineInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedAvsAssessedMachineInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedAvsAssessedMachineInner.properties = AvsAssessedMachineProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedAvsAssessedMachineInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedAvsAssessedMachineInner; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AvsAssessmentInner.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AvsAssessmentInner.java new file mode 100644 index 000000000000..8424d9087c12 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AvsAssessmentInner.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. + +package com.azure.resourcemanager.migration.assessment.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessmentProperties; +import java.io.IOException; + +/** + * AVS assessment resource. + */ +@Fluent +public final class AvsAssessmentInner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private AvsAssessmentProperties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of AvsAssessmentInner class. + */ + public AvsAssessmentInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public AvsAssessmentProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the AvsAssessmentInner object itself. + */ + public AvsAssessmentInner withProperties(AvsAssessmentProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AvsAssessmentInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AvsAssessmentInner 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 AvsAssessmentInner. + */ + public static AvsAssessmentInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AvsAssessmentInner deserializedAvsAssessmentInner = new AvsAssessmentInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedAvsAssessmentInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedAvsAssessmentInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedAvsAssessmentInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedAvsAssessmentInner.properties = AvsAssessmentProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedAvsAssessmentInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedAvsAssessmentInner; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AvsAssessmentOptionsInner.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AvsAssessmentOptionsInner.java new file mode 100644 index 000000000000..2f0b94bb8bbf --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/AvsAssessmentOptionsInner.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. + +package com.azure.resourcemanager.migration.assessment.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessmentOptionsProperties; +import java.io.IOException; + +/** + * AVS Assessment options resource. + */ +@Fluent +public final class AvsAssessmentOptionsInner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private AvsAssessmentOptionsProperties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of AvsAssessmentOptionsInner class. + */ + public AvsAssessmentOptionsInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public AvsAssessmentOptionsProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the AvsAssessmentOptionsInner object itself. + */ + public AvsAssessmentOptionsInner withProperties(AvsAssessmentOptionsProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AvsAssessmentOptionsInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AvsAssessmentOptionsInner 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 AvsAssessmentOptionsInner. + */ + public static AvsAssessmentOptionsInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AvsAssessmentOptionsInner deserializedAvsAssessmentOptionsInner = new AvsAssessmentOptionsInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedAvsAssessmentOptionsInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedAvsAssessmentOptionsInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedAvsAssessmentOptionsInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedAvsAssessmentOptionsInner.properties = AvsAssessmentOptionsProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedAvsAssessmentOptionsInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedAvsAssessmentOptionsInner; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/DownloadUrlInner.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/DownloadUrlInner.java new file mode 100644 index 000000000000..873fd5ede278 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/DownloadUrlInner.java @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; + +/** + * Data model of Download URL for assessment report. + */ +@Immutable +public final class DownloadUrlInner implements JsonSerializable { + /* + * Hyperlink to download report. + */ + private String assessmentReportUrl; + + /* + * Expiry date of download url. + */ + private OffsetDateTime expirationTime; + + /** + * Creates an instance of DownloadUrlInner class. + */ + public DownloadUrlInner() { + } + + /** + * Get the assessmentReportUrl property: Hyperlink to download report. + * + * @return the assessmentReportUrl value. + */ + public String assessmentReportUrl() { + return this.assessmentReportUrl; + } + + /** + * Get the expirationTime property: Expiry date of download url. + * + * @return the expirationTime value. + */ + public OffsetDateTime expirationTime() { + return this.expirationTime; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of DownloadUrlInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of DownloadUrlInner 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 DownloadUrlInner. + */ + public static DownloadUrlInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + DownloadUrlInner deserializedDownloadUrlInner = new DownloadUrlInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("assessmentReportUrl".equals(fieldName)) { + deserializedDownloadUrlInner.assessmentReportUrl = reader.getString(); + } else if ("expirationTime".equals(fieldName)) { + deserializedDownloadUrlInner.expirationTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else { + reader.skipChildren(); + } + } + + return deserializedDownloadUrlInner; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/GroupInner.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/GroupInner.java new file mode 100644 index 000000000000..1e81fb016105 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/GroupInner.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. + +package com.azure.resourcemanager.migration.assessment.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.models.GroupProperties; +import java.io.IOException; + +/** + * Group resource. + */ +@Fluent +public final class GroupInner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private GroupProperties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of GroupInner class. + */ + public GroupInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public GroupProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the GroupInner object itself. + */ + public GroupInner withProperties(GroupProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of GroupInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of GroupInner 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 GroupInner. + */ + public static GroupInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + GroupInner deserializedGroupInner = new GroupInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedGroupInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedGroupInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedGroupInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedGroupInner.properties = GroupProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedGroupInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedGroupInner; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/HypervCollectorInner.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/HypervCollectorInner.java new file mode 100644 index 000000000000..4f64a7d596fa --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/HypervCollectorInner.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. + +package com.azure.resourcemanager.migration.assessment.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBaseWithAgent; +import java.io.IOException; + +/** + * Hyper-V collector resource. + */ +@Fluent +public final class HypervCollectorInner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private CollectorPropertiesBaseWithAgent properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of HypervCollectorInner class. + */ + public HypervCollectorInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public CollectorPropertiesBaseWithAgent properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the HypervCollectorInner object itself. + */ + public HypervCollectorInner withProperties(CollectorPropertiesBaseWithAgent properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of HypervCollectorInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of HypervCollectorInner 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 HypervCollectorInner. + */ + public static HypervCollectorInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + HypervCollectorInner deserializedHypervCollectorInner = new HypervCollectorInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedHypervCollectorInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedHypervCollectorInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedHypervCollectorInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedHypervCollectorInner.properties = CollectorPropertiesBaseWithAgent.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedHypervCollectorInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedHypervCollectorInner; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/ImportCollectorInner.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/ImportCollectorInner.java new file mode 100644 index 000000000000..4cc8c1f82628 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/ImportCollectorInner.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. + +package com.azure.resourcemanager.migration.assessment.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBase; +import java.io.IOException; + +/** + * Import collector resource. + */ +@Fluent +public final class ImportCollectorInner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private CollectorPropertiesBase properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of ImportCollectorInner class. + */ + public ImportCollectorInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public CollectorPropertiesBase properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the ImportCollectorInner object itself. + */ + public ImportCollectorInner withProperties(CollectorPropertiesBase properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ImportCollectorInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ImportCollectorInner 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 ImportCollectorInner. + */ + public static ImportCollectorInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ImportCollectorInner deserializedImportCollectorInner = new ImportCollectorInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedImportCollectorInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedImportCollectorInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedImportCollectorInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedImportCollectorInner.properties = CollectorPropertiesBase.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedImportCollectorInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedImportCollectorInner; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/MachineInner.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/MachineInner.java new file mode 100644 index 000000000000..c707dd93181b --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/MachineInner.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. + +package com.azure.resourcemanager.migration.assessment.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.models.MachineProperties; +import java.io.IOException; + +/** + * Machine resource. + */ +@Fluent +public final class MachineInner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private MachineProperties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of MachineInner class. + */ + public MachineInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public MachineProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the MachineInner object itself. + */ + public MachineInner withProperties(MachineProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of MachineInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of MachineInner 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 MachineInner. + */ + public static MachineInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + MachineInner deserializedMachineInner = new MachineInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedMachineInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedMachineInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedMachineInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedMachineInner.properties = MachineProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedMachineInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedMachineInner; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/OperationInner.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/OperationInner.java new file mode 100644 index 000000000000..6be3227cc5f3 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/OperationInner.java @@ -0,0 +1,172 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent.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.resourcemanager.migration.assessment.models.ActionType; +import com.azure.resourcemanager.migration.assessment.models.OperationDisplay; +import com.azure.resourcemanager.migration.assessment.models.Origin; +import java.io.IOException; + +/** + * REST API Operation + * + * Details of a REST API operation, returned from the Resource Provider Operations API. + */ +@Fluent +public final class OperationInner implements JsonSerializable { + /* + * The name of the operation, as per Resource-Based Access Control (RBAC). Examples: + * "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action" + */ + private String name; + + /* + * Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for + * ARM/control-plane operations. + */ + private Boolean isDataAction; + + /* + * Localized display information for this particular operation. + */ + private OperationDisplay display; + + /* + * The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default + * value is "user,system" + */ + private Origin origin; + + /* + * Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + */ + private ActionType actionType; + + /** + * Creates an instance of OperationInner class. + */ + public OperationInner() { + } + + /** + * Get the name property: The name of the operation, as per Resource-Based Access Control (RBAC). Examples: + * "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action". + * + * @return the name value. + */ + public String name() { + return this.name; + } + + /** + * Get the isDataAction property: Whether the operation applies to data-plane. This is "true" for data-plane + * operations and "false" for ARM/control-plane operations. + * + * @return the isDataAction value. + */ + public Boolean isDataAction() { + return this.isDataAction; + } + + /** + * Get the display property: Localized display information for this particular operation. + * + * @return the display value. + */ + public OperationDisplay display() { + return this.display; + } + + /** + * Set the display property: Localized display information for this particular operation. + * + * @param display the display value to set. + * @return the OperationInner object itself. + */ + public OperationInner withDisplay(OperationDisplay display) { + this.display = display; + return this; + } + + /** + * Get the origin property: The intended executor of the operation; as in Resource Based Access Control (RBAC) and + * audit logs UX. Default value is "user,system". + * + * @return the origin value. + */ + public Origin origin() { + return this.origin; + } + + /** + * Get the actionType property: Enum. Indicates the action type. "Internal" refers to actions that are for internal + * only APIs. + * + * @return the actionType value. + */ + public ActionType actionType() { + return this.actionType; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (display() != null) { + display().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("display", this.display); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OperationInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OperationInner 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 OperationInner. + */ + public static OperationInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OperationInner deserializedOperationInner = new OperationInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("name".equals(fieldName)) { + deserializedOperationInner.name = reader.getString(); + } else if ("isDataAction".equals(fieldName)) { + deserializedOperationInner.isDataAction = reader.getNullable(JsonReader::getBoolean); + } else if ("display".equals(fieldName)) { + deserializedOperationInner.display = OperationDisplay.fromJson(reader); + } else if ("origin".equals(fieldName)) { + deserializedOperationInner.origin = Origin.fromString(reader.getString()); + } else if ("actionType".equals(fieldName)) { + deserializedOperationInner.actionType = ActionType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedOperationInner; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/PrivateEndpointConnectionInner.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/PrivateEndpointConnectionInner.java new file mode 100644 index 000000000000..67a6198b1726 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/PrivateEndpointConnectionInner.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. + +package com.azure.resourcemanager.migration.assessment.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpointConnectionProperties; +import java.io.IOException; + +/** + * Private endpoint connection resource. + */ +@Fluent +public final class PrivateEndpointConnectionInner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private PrivateEndpointConnectionProperties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of PrivateEndpointConnectionInner class. + */ + public PrivateEndpointConnectionInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public PrivateEndpointConnectionProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the PrivateEndpointConnectionInner object itself. + */ + public PrivateEndpointConnectionInner withProperties(PrivateEndpointConnectionProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of PrivateEndpointConnectionInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of PrivateEndpointConnectionInner 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 PrivateEndpointConnectionInner. + */ + public static PrivateEndpointConnectionInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + PrivateEndpointConnectionInner deserializedPrivateEndpointConnectionInner + = new PrivateEndpointConnectionInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedPrivateEndpointConnectionInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedPrivateEndpointConnectionInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedPrivateEndpointConnectionInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedPrivateEndpointConnectionInner.properties + = PrivateEndpointConnectionProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedPrivateEndpointConnectionInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedPrivateEndpointConnectionInner; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/PrivateLinkResourceInner.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/PrivateLinkResourceInner.java new file mode 100644 index 000000000000..6df1276555ab --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/PrivateLinkResourceInner.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. + +package com.azure.resourcemanager.migration.assessment.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.models.PrivateLinkResourceProperties; +import java.io.IOException; + +/** + * Private link resource. + */ +@Fluent +public final class PrivateLinkResourceInner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private PrivateLinkResourceProperties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of PrivateLinkResourceInner class. + */ + public PrivateLinkResourceInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public PrivateLinkResourceProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the PrivateLinkResourceInner object itself. + */ + public PrivateLinkResourceInner withProperties(PrivateLinkResourceProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of PrivateLinkResourceInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of PrivateLinkResourceInner 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 PrivateLinkResourceInner. + */ + public static PrivateLinkResourceInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + PrivateLinkResourceInner deserializedPrivateLinkResourceInner = new PrivateLinkResourceInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedPrivateLinkResourceInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedPrivateLinkResourceInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedPrivateLinkResourceInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedPrivateLinkResourceInner.properties = PrivateLinkResourceProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedPrivateLinkResourceInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedPrivateLinkResourceInner; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/ServerCollectorInner.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/ServerCollectorInner.java new file mode 100644 index 000000000000..fdadcbd45dc4 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/ServerCollectorInner.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. + +package com.azure.resourcemanager.migration.assessment.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBaseWithAgent; +import java.io.IOException; + +/** + * Physical server collector resource. + */ +@Fluent +public final class ServerCollectorInner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private CollectorPropertiesBaseWithAgent properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of ServerCollectorInner class. + */ + public ServerCollectorInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public CollectorPropertiesBaseWithAgent properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the ServerCollectorInner object itself. + */ + public ServerCollectorInner withProperties(CollectorPropertiesBaseWithAgent properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ServerCollectorInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ServerCollectorInner 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 ServerCollectorInner. + */ + public static ServerCollectorInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ServerCollectorInner deserializedServerCollectorInner = new ServerCollectorInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedServerCollectorInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedServerCollectorInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedServerCollectorInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedServerCollectorInner.properties = CollectorPropertiesBaseWithAgent.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedServerCollectorInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedServerCollectorInner; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/SqlAssessmentOptionsInner.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/SqlAssessmentOptionsInner.java new file mode 100644 index 000000000000..b6d3ff5fcec0 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/SqlAssessmentOptionsInner.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. + +package com.azure.resourcemanager.migration.assessment.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentOptionsProperties; +import java.io.IOException; + +/** + * SQL Assessment options web model object. + */ +@Fluent +public final class SqlAssessmentOptionsInner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private SqlAssessmentOptionsProperties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of SqlAssessmentOptionsInner class. + */ + public SqlAssessmentOptionsInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public SqlAssessmentOptionsProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the SqlAssessmentOptionsInner object itself. + */ + public SqlAssessmentOptionsInner withProperties(SqlAssessmentOptionsProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlAssessmentOptionsInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlAssessmentOptionsInner 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 SqlAssessmentOptionsInner. + */ + public static SqlAssessmentOptionsInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlAssessmentOptionsInner deserializedSqlAssessmentOptionsInner = new SqlAssessmentOptionsInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedSqlAssessmentOptionsInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedSqlAssessmentOptionsInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedSqlAssessmentOptionsInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedSqlAssessmentOptionsInner.properties = SqlAssessmentOptionsProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedSqlAssessmentOptionsInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedSqlAssessmentOptionsInner; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/SqlAssessmentV2Inner.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/SqlAssessmentV2Inner.java new file mode 100644 index 000000000000..697451af3298 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/SqlAssessmentV2Inner.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. + +package com.azure.resourcemanager.migration.assessment.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentV2Properties; +import java.io.IOException; + +/** + * SQL Assessment REST resource. + */ +@Fluent +public final class SqlAssessmentV2Inner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private SqlAssessmentV2Properties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of SqlAssessmentV2Inner class. + */ + public SqlAssessmentV2Inner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public SqlAssessmentV2Properties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the SqlAssessmentV2Inner object itself. + */ + public SqlAssessmentV2Inner withProperties(SqlAssessmentV2Properties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlAssessmentV2Inner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlAssessmentV2Inner 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 SqlAssessmentV2Inner. + */ + public static SqlAssessmentV2Inner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlAssessmentV2Inner deserializedSqlAssessmentV2Inner = new SqlAssessmentV2Inner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedSqlAssessmentV2Inner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedSqlAssessmentV2Inner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedSqlAssessmentV2Inner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedSqlAssessmentV2Inner.properties = SqlAssessmentV2Properties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedSqlAssessmentV2Inner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedSqlAssessmentV2Inner; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/SqlAssessmentV2SummaryInner.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/SqlAssessmentV2SummaryInner.java new file mode 100644 index 000000000000..7acc05c96500 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/SqlAssessmentV2SummaryInner.java @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentV2SummaryProperties; +import java.io.IOException; + +/** + * SQL Assessment REST resource. + */ +@Fluent +public final class SqlAssessmentV2SummaryInner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private SqlAssessmentV2SummaryProperties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of SqlAssessmentV2SummaryInner class. + */ + public SqlAssessmentV2SummaryInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public SqlAssessmentV2SummaryProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the SqlAssessmentV2SummaryInner object itself. + */ + public SqlAssessmentV2SummaryInner withProperties(SqlAssessmentV2SummaryProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlAssessmentV2SummaryInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlAssessmentV2SummaryInner 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 SqlAssessmentV2SummaryInner. + */ + public static SqlAssessmentV2SummaryInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlAssessmentV2SummaryInner deserializedSqlAssessmentV2SummaryInner = new SqlAssessmentV2SummaryInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedSqlAssessmentV2SummaryInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedSqlAssessmentV2SummaryInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedSqlAssessmentV2SummaryInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedSqlAssessmentV2SummaryInner.properties + = SqlAssessmentV2SummaryProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedSqlAssessmentV2SummaryInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedSqlAssessmentV2SummaryInner; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/SqlCollectorInner.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/SqlCollectorInner.java new file mode 100644 index 000000000000..afcf1c44955c --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/SqlCollectorInner.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. + +package com.azure.resourcemanager.migration.assessment.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBaseWithAgent; +import java.io.IOException; + +/** + * The SQL collector REST object. + */ +@Fluent +public final class SqlCollectorInner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private CollectorPropertiesBaseWithAgent properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of SqlCollectorInner class. + */ + public SqlCollectorInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public CollectorPropertiesBaseWithAgent properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the SqlCollectorInner object itself. + */ + public SqlCollectorInner withProperties(CollectorPropertiesBaseWithAgent properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlCollectorInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlCollectorInner 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 SqlCollectorInner. + */ + public static SqlCollectorInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlCollectorInner deserializedSqlCollectorInner = new SqlCollectorInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedSqlCollectorInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedSqlCollectorInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedSqlCollectorInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedSqlCollectorInner.properties = CollectorPropertiesBaseWithAgent.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedSqlCollectorInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedSqlCollectorInner; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/VmwareCollectorInner.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/VmwareCollectorInner.java new file mode 100644 index 000000000000..bda94f348b60 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/VmwareCollectorInner.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. + +package com.azure.resourcemanager.migration.assessment.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBaseWithAgent; +import java.io.IOException; + +/** + * VMware collector resource. + */ +@Fluent +public final class VmwareCollectorInner extends ProxyResource { + /* + * The resource-specific properties for this resource. + */ + private CollectorPropertiesBaseWithAgent properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of VmwareCollectorInner class. + */ + public VmwareCollectorInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public CollectorPropertiesBaseWithAgent properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the VmwareCollectorInner object itself. + */ + public VmwareCollectorInner withProperties(CollectorPropertiesBaseWithAgent properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of VmwareCollectorInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of VmwareCollectorInner 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 VmwareCollectorInner. + */ + public static VmwareCollectorInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + VmwareCollectorInner deserializedVmwareCollectorInner = new VmwareCollectorInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedVmwareCollectorInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedVmwareCollectorInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedVmwareCollectorInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedVmwareCollectorInner.properties = CollectorPropertiesBaseWithAgent.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedVmwareCollectorInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedVmwareCollectorInner; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/package-info.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/package-info.java new file mode 100644 index 000000000000..3f7b2edfa8a1 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/models/package-info.java @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +/** + * Package containing the inner data models for MigrationAssessmentManagementClient. + * Azure Migrate Resource Provider management API. + */ +package com.azure.resourcemanager.migration.assessment.fluent.models; diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/package-info.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/package-info.java new file mode 100644 index 000000000000..63269d0fcc3c --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/fluent/package-info.java @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +/** + * Package containing the service clients for MigrationAssessmentManagementClient. + * Azure Migrate Resource Provider management API. + */ +package com.azure.resourcemanager.migration.assessment.fluent; diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedMachineImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedMachineImpl.java new file mode 100644 index 000000000000..48337823a02a --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedMachineImpl.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedMachineInner; +import com.azure.resourcemanager.migration.assessment.models.AssessedMachine; +import com.azure.resourcemanager.migration.assessment.models.AssessedMachineProperties; + +public final class AssessedMachineImpl implements AssessedMachine { + private AssessedMachineInner innerObject; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + AssessedMachineImpl(AssessedMachineInner innerObject, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public AssessedMachineProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public AssessedMachineInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedMachinesOperationsClientImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedMachinesOperationsClientImpl.java new file mode 100644 index 000000000000..93b313bd3f88 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedMachinesOperationsClientImpl.java @@ -0,0 +1,540 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.resourcemanager.migration.assessment.fluent.AssessedMachinesOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedMachineInner; +import com.azure.resourcemanager.migration.assessment.models.AssessedMachineListResult; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in AssessedMachinesOperationsClient. + */ +public final class AssessedMachinesOperationsClientImpl implements AssessedMachinesOperationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final AssessedMachinesOperationsService service; + + /** + * The service client containing this operation class. + */ + private final MigrationAssessmentManagementClientImpl client; + + /** + * Initializes an instance of AssessedMachinesOperationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + AssessedMachinesOperationsClientImpl(MigrationAssessmentManagementClientImpl client) { + this.service = RestProxy.create(AssessedMachinesOperationsService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for MigrationAssessmentManagementClientAssessedMachinesOperations to be + * used by the proxy service to perform REST calls. + */ + @Host("{$host}") + @ServiceInterface(name = "MigrationAssessmentM") + public interface AssessedMachinesOperationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/assessments/{assessmentName}/assessedMachines") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAssessment(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @QueryParam("$filter") String filter, + @QueryParam("pageSize") Integer pageSize, @QueryParam("continuationToken") String continuationToken, + @QueryParam("totalRecordCount") Integer totalRecordCount, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @PathParam("assessmentName") String assessmentName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/assessments/{assessmentName}/assessedMachines/{assessedMachineName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @PathParam("assessmentName") String assessmentName, + @PathParam("assessedMachineName") String assessedMachineName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAssessmentNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * List AssessedMachine resources by Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedMachine list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentSinglePageAsync(String resourceGroupName, + String projectName, String groupName, String assessmentName, String filter, Integer pageSize, + String continuationToken, Integer totalRecordCount) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listByAssessment(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, filter, pageSize, continuationToken, + totalRecordCount, projectName, groupName, assessmentName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List AssessedMachine resources by Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedMachine list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentSinglePageAsync(String resourceGroupName, + String projectName, String groupName, String assessmentName, String filter, Integer pageSize, + String continuationToken, Integer totalRecordCount, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByAssessment(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, filter, pageSize, continuationToken, totalRecordCount, projectName, groupName, + assessmentName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List AssessedMachine resources by Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedMachine list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName, String filter, Integer pageSize, String continuationToken, + Integer totalRecordCount) { + return new PagedFlux<>( + () -> listByAssessmentSinglePageAsync(resourceGroupName, projectName, groupName, assessmentName, filter, + pageSize, continuationToken, totalRecordCount), + nextLink -> listByAssessmentNextSinglePageAsync(nextLink)); + } + + /** + * List AssessedMachine resources by Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedMachine list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName) { + final String filter = null; + final Integer pageSize = null; + final String continuationToken = null; + final Integer totalRecordCount = null; + return new PagedFlux<>( + () -> listByAssessmentSinglePageAsync(resourceGroupName, projectName, groupName, assessmentName, filter, + pageSize, continuationToken, totalRecordCount), + nextLink -> listByAssessmentNextSinglePageAsync(nextLink)); + } + + /** + * List AssessedMachine resources by Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedMachine list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName, String filter, Integer pageSize, String continuationToken, + Integer totalRecordCount, Context context) { + return new PagedFlux<>( + () -> listByAssessmentSinglePageAsync(resourceGroupName, projectName, groupName, assessmentName, filter, + pageSize, continuationToken, totalRecordCount, context), + nextLink -> listByAssessmentNextSinglePageAsync(nextLink, context)); + } + + /** + * List AssessedMachine resources by Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedMachine list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAssessment(String resourceGroupName, String projectName, + String groupName, String assessmentName) { + final String filter = null; + final Integer pageSize = null; + final String continuationToken = null; + final Integer totalRecordCount = null; + return new PagedIterable<>(listByAssessmentAsync(resourceGroupName, projectName, groupName, assessmentName, + filter, pageSize, continuationToken, totalRecordCount)); + } + + /** + * List AssessedMachine resources by Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedMachine list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAssessment(String resourceGroupName, String projectName, + String groupName, String assessmentName, String filter, Integer pageSize, String continuationToken, + Integer totalRecordCount, Context context) { + return new PagedIterable<>(listByAssessmentAsync(resourceGroupName, projectName, groupName, assessmentName, + filter, pageSize, continuationToken, totalRecordCount, context)); + } + + /** + * Get a AssessedMachine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param assessedMachineName Machine assessment Assessed Machine ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedMachine along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName, String assessedMachineName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + if (assessedMachineName == null) { + return Mono + .error(new IllegalArgumentException("Parameter assessedMachineName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, assessmentName, + assessedMachineName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a AssessedMachine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param assessedMachineName Machine assessment Assessed Machine ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedMachine along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName, String assessedMachineName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + if (assessedMachineName == null) { + return Mono + .error(new IllegalArgumentException("Parameter assessedMachineName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, groupName, assessmentName, assessedMachineName, accept, context); + } + + /** + * Get a AssessedMachine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param assessedMachineName Machine assessment Assessed Machine ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedMachine on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName, String assessedMachineName) { + return getWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, assessedMachineName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a AssessedMachine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param assessedMachineName Machine assessment Assessed Machine ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedMachine along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceGroupName, String projectName, + String groupName, String assessmentName, String assessedMachineName, Context context) { + return getWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, assessedMachineName, + context).block(); + } + + /** + * Get a AssessedMachine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param assessedMachineName Machine assessment Assessed Machine ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedMachine. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public AssessedMachineInner get(String resourceGroupName, String projectName, String groupName, + String assessmentName, String assessedMachineName) { + return getWithResponse(resourceGroupName, projectName, groupName, assessmentName, assessedMachineName, + Context.NONE).getValue(); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedMachine list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listByAssessmentNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedMachine list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listByAssessmentNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedMachinesOperationsImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedMachinesOperationsImpl.java new file mode 100644 index 000000000000..4704bf357b0d --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedMachinesOperationsImpl.java @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.migration.assessment.fluent.AssessedMachinesOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedMachineInner; +import com.azure.resourcemanager.migration.assessment.models.AssessedMachine; +import com.azure.resourcemanager.migration.assessment.models.AssessedMachinesOperations; + +public final class AssessedMachinesOperationsImpl implements AssessedMachinesOperations { + private static final ClientLogger LOGGER = new ClientLogger(AssessedMachinesOperationsImpl.class); + + private final AssessedMachinesOperationsClient innerClient; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + public AssessedMachinesOperationsImpl(AssessedMachinesOperationsClient innerClient, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public PagedIterable listByAssessment(String resourceGroupName, String projectName, + String groupName, String assessmentName) { + PagedIterable inner + = this.serviceClient().listByAssessment(resourceGroupName, projectName, groupName, assessmentName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new AssessedMachineImpl(inner1, this.manager())); + } + + public PagedIterable listByAssessment(String resourceGroupName, String projectName, + String groupName, String assessmentName, String filter, Integer pageSize, String continuationToken, + Integer totalRecordCount, Context context) { + PagedIterable inner = this.serviceClient() + .listByAssessment(resourceGroupName, projectName, groupName, assessmentName, filter, pageSize, + continuationToken, totalRecordCount, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new AssessedMachineImpl(inner1, this.manager())); + } + + public Response getWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, String assessedMachineName, Context context) { + Response inner = this.serviceClient() + .getWithResponse(resourceGroupName, projectName, groupName, assessmentName, assessedMachineName, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new AssessedMachineImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public AssessedMachine get(String resourceGroupName, String projectName, String groupName, String assessmentName, + String assessedMachineName) { + AssessedMachineInner inner + = this.serviceClient().get(resourceGroupName, projectName, groupName, assessmentName, assessedMachineName); + if (inner != null) { + return new AssessedMachineImpl(inner, this.manager()); + } else { + return null; + } + } + + private AssessedMachinesOperationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlDatabaseV2Impl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlDatabaseV2Impl.java new file mode 100644 index 000000000000..07cbc5686efe --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlDatabaseV2Impl.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlDatabaseV2Inner; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlDatabaseV2; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlDatabaseV2Properties; + +public final class AssessedSqlDatabaseV2Impl implements AssessedSqlDatabaseV2 { + private AssessedSqlDatabaseV2Inner innerObject; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + AssessedSqlDatabaseV2Impl(AssessedSqlDatabaseV2Inner innerObject, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public AssessedSqlDatabaseV2Properties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public AssessedSqlDatabaseV2Inner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlDatabaseV2OperationsClientImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlDatabaseV2OperationsClientImpl.java new file mode 100644 index 000000000000..b942cccf11e8 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlDatabaseV2OperationsClientImpl.java @@ -0,0 +1,541 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.resourcemanager.migration.assessment.fluent.AssessedSqlDatabaseV2OperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlDatabaseV2Inner; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlDatabaseV2ListResult; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in AssessedSqlDatabaseV2OperationsClient. + */ +public final class AssessedSqlDatabaseV2OperationsClientImpl implements AssessedSqlDatabaseV2OperationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final AssessedSqlDatabaseV2OperationsService service; + + /** + * The service client containing this operation class. + */ + private final MigrationAssessmentManagementClientImpl client; + + /** + * Initializes an instance of AssessedSqlDatabaseV2OperationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + AssessedSqlDatabaseV2OperationsClientImpl(MigrationAssessmentManagementClientImpl client) { + this.service = RestProxy.create(AssessedSqlDatabaseV2OperationsService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for MigrationAssessmentManagementClientAssessedSqlDatabaseV2Operations to + * be used by the proxy service to perform REST calls. + */ + @Host("{$host}") + @ServiceInterface(name = "MigrationAssessmentM") + public interface AssessedSqlDatabaseV2OperationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/sqlAssessments/{assessmentName}/assessedSqlDatabases") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listBySqlAssessmentV2(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @QueryParam("$filter") String filter, + @QueryParam("pageSize") Integer pageSize, @QueryParam("continuationToken") String continuationToken, + @QueryParam("totalRecordCount") Integer totalRecordCount, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @PathParam("assessmentName") String assessmentName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/sqlAssessments/{assessmentName}/assessedSqlDatabases/{assessedSqlDatabaseName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @PathParam("assessmentName") String assessmentName, + @PathParam("assessedSqlDatabaseName") String assessedSqlDatabaseName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listBySqlAssessmentV2Next( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * List AssessedSqlDatabaseV2 resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlDatabaseV2 list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySqlAssessmentV2SinglePageAsync( + String resourceGroupName, String projectName, String groupName, String assessmentName, String filter, + Integer pageSize, String continuationToken, Integer totalRecordCount) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listBySqlAssessmentV2(this.client.getEndpoint(), + this.client.getApiVersion(), this.client.getSubscriptionId(), resourceGroupName, filter, pageSize, + continuationToken, totalRecordCount, projectName, groupName, assessmentName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List AssessedSqlDatabaseV2 resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlDatabaseV2 list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySqlAssessmentV2SinglePageAsync( + String resourceGroupName, String projectName, String groupName, String assessmentName, String filter, + Integer pageSize, String continuationToken, Integer totalRecordCount, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listBySqlAssessmentV2(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, filter, pageSize, continuationToken, + totalRecordCount, projectName, groupName, assessmentName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List AssessedSqlDatabaseV2 resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlDatabaseV2 list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listBySqlAssessmentV2Async(String resourceGroupName, + String projectName, String groupName, String assessmentName, String filter, Integer pageSize, + String continuationToken, Integer totalRecordCount) { + return new PagedFlux<>( + () -> listBySqlAssessmentV2SinglePageAsync(resourceGroupName, projectName, groupName, assessmentName, + filter, pageSize, continuationToken, totalRecordCount), + nextLink -> listBySqlAssessmentV2NextSinglePageAsync(nextLink)); + } + + /** + * List AssessedSqlDatabaseV2 resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlDatabaseV2 list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listBySqlAssessmentV2Async(String resourceGroupName, + String projectName, String groupName, String assessmentName) { + final String filter = null; + final Integer pageSize = null; + final String continuationToken = null; + final Integer totalRecordCount = null; + return new PagedFlux<>( + () -> listBySqlAssessmentV2SinglePageAsync(resourceGroupName, projectName, groupName, assessmentName, + filter, pageSize, continuationToken, totalRecordCount), + nextLink -> listBySqlAssessmentV2NextSinglePageAsync(nextLink)); + } + + /** + * List AssessedSqlDatabaseV2 resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlDatabaseV2 list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listBySqlAssessmentV2Async(String resourceGroupName, + String projectName, String groupName, String assessmentName, String filter, Integer pageSize, + String continuationToken, Integer totalRecordCount, Context context) { + return new PagedFlux<>( + () -> listBySqlAssessmentV2SinglePageAsync(resourceGroupName, projectName, groupName, assessmentName, + filter, pageSize, continuationToken, totalRecordCount, context), + nextLink -> listBySqlAssessmentV2NextSinglePageAsync(nextLink, context)); + } + + /** + * List AssessedSqlDatabaseV2 resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlDatabaseV2 list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName) { + final String filter = null; + final Integer pageSize = null; + final String continuationToken = null; + final Integer totalRecordCount = null; + return new PagedIterable<>(listBySqlAssessmentV2Async(resourceGroupName, projectName, groupName, assessmentName, + filter, pageSize, continuationToken, totalRecordCount)); + } + + /** + * List AssessedSqlDatabaseV2 resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlDatabaseV2 list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName, String filter, Integer pageSize, String continuationToken, + Integer totalRecordCount, Context context) { + return new PagedIterable<>(listBySqlAssessmentV2Async(resourceGroupName, projectName, groupName, assessmentName, + filter, pageSize, continuationToken, totalRecordCount, context)); + } + + /** + * Get a AssessedSqlDatabaseV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param assessedSqlDatabaseName Sql assessment Assessed Databases ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlDatabaseV2 along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, + String projectName, String groupName, String assessmentName, String assessedSqlDatabaseName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + if (assessedSqlDatabaseName == null) { + return Mono.error( + new IllegalArgumentException("Parameter assessedSqlDatabaseName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, assessmentName, + assessedSqlDatabaseName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a AssessedSqlDatabaseV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param assessedSqlDatabaseName Sql assessment Assessed Databases ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlDatabaseV2 along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, + String projectName, String groupName, String assessmentName, String assessedSqlDatabaseName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + if (assessedSqlDatabaseName == null) { + return Mono.error( + new IllegalArgumentException("Parameter assessedSqlDatabaseName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, groupName, assessmentName, assessedSqlDatabaseName, accept, context); + } + + /** + * Get a AssessedSqlDatabaseV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param assessedSqlDatabaseName Sql assessment Assessed Databases ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlDatabaseV2 on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName, String assessedSqlDatabaseName) { + return getWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, assessedSqlDatabaseName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a AssessedSqlDatabaseV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param assessedSqlDatabaseName Sql assessment Assessed Databases ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlDatabaseV2 along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceGroupName, String projectName, + String groupName, String assessmentName, String assessedSqlDatabaseName, Context context) { + return getWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, assessedSqlDatabaseName, + context).block(); + } + + /** + * Get a AssessedSqlDatabaseV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param assessedSqlDatabaseName Sql assessment Assessed Databases ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlDatabaseV2. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public AssessedSqlDatabaseV2Inner get(String resourceGroupName, String projectName, String groupName, + String assessmentName, String assessedSqlDatabaseName) { + return getWithResponse(resourceGroupName, projectName, groupName, assessmentName, assessedSqlDatabaseName, + Context.NONE).getValue(); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlDatabaseV2 list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySqlAssessmentV2NextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listBySqlAssessmentV2Next(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlDatabaseV2 list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySqlAssessmentV2NextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listBySqlAssessmentV2Next(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlDatabaseV2OperationsImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlDatabaseV2OperationsImpl.java new file mode 100644 index 000000000000..2157f7c23413 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlDatabaseV2OperationsImpl.java @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.migration.assessment.fluent.AssessedSqlDatabaseV2OperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlDatabaseV2Inner; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlDatabaseV2; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlDatabaseV2Operations; + +public final class AssessedSqlDatabaseV2OperationsImpl implements AssessedSqlDatabaseV2Operations { + private static final ClientLogger LOGGER = new ClientLogger(AssessedSqlDatabaseV2OperationsImpl.class); + + private final AssessedSqlDatabaseV2OperationsClient innerClient; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + public AssessedSqlDatabaseV2OperationsImpl(AssessedSqlDatabaseV2OperationsClient innerClient, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName) { + PagedIterable inner + = this.serviceClient().listBySqlAssessmentV2(resourceGroupName, projectName, groupName, assessmentName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new AssessedSqlDatabaseV2Impl(inner1, this.manager())); + } + + public PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName, String filter, Integer pageSize, String continuationToken, + Integer totalRecordCount, Context context) { + PagedIterable inner = this.serviceClient() + .listBySqlAssessmentV2(resourceGroupName, projectName, groupName, assessmentName, filter, pageSize, + continuationToken, totalRecordCount, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new AssessedSqlDatabaseV2Impl(inner1, this.manager())); + } + + public Response getWithResponse(String resourceGroupName, String projectName, + String groupName, String assessmentName, String assessedSqlDatabaseName, Context context) { + Response inner = this.serviceClient() + .getWithResponse(resourceGroupName, projectName, groupName, assessmentName, assessedSqlDatabaseName, + context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new AssessedSqlDatabaseV2Impl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public AssessedSqlDatabaseV2 get(String resourceGroupName, String projectName, String groupName, + String assessmentName, String assessedSqlDatabaseName) { + AssessedSqlDatabaseV2Inner inner = this.serviceClient() + .get(resourceGroupName, projectName, groupName, assessmentName, assessedSqlDatabaseName); + if (inner != null) { + return new AssessedSqlDatabaseV2Impl(inner, this.manager()); + } else { + return null; + } + } + + private AssessedSqlDatabaseV2OperationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlInstanceV2Impl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlInstanceV2Impl.java new file mode 100644 index 000000000000..b7ab2e3249ca --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlInstanceV2Impl.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlInstanceV2Inner; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlInstanceV2; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlInstanceV2Properties; + +public final class AssessedSqlInstanceV2Impl implements AssessedSqlInstanceV2 { + private AssessedSqlInstanceV2Inner innerObject; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + AssessedSqlInstanceV2Impl(AssessedSqlInstanceV2Inner innerObject, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public AssessedSqlInstanceV2Properties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public AssessedSqlInstanceV2Inner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlInstanceV2OperationsClientImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlInstanceV2OperationsClientImpl.java new file mode 100644 index 000000000000..b2f8bba31883 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlInstanceV2OperationsClientImpl.java @@ -0,0 +1,541 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.resourcemanager.migration.assessment.fluent.AssessedSqlInstanceV2OperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlInstanceV2Inner; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlInstanceV2ListResult; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in AssessedSqlInstanceV2OperationsClient. + */ +public final class AssessedSqlInstanceV2OperationsClientImpl implements AssessedSqlInstanceV2OperationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final AssessedSqlInstanceV2OperationsService service; + + /** + * The service client containing this operation class. + */ + private final MigrationAssessmentManagementClientImpl client; + + /** + * Initializes an instance of AssessedSqlInstanceV2OperationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + AssessedSqlInstanceV2OperationsClientImpl(MigrationAssessmentManagementClientImpl client) { + this.service = RestProxy.create(AssessedSqlInstanceV2OperationsService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for MigrationAssessmentManagementClientAssessedSqlInstanceV2Operations to + * be used by the proxy service to perform REST calls. + */ + @Host("{$host}") + @ServiceInterface(name = "MigrationAssessmentM") + public interface AssessedSqlInstanceV2OperationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/sqlAssessments/{assessmentName}/assessedSqlInstances") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listBySqlAssessmentV2(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @QueryParam("$filter") String filter, + @QueryParam("pageSize") Integer pageSize, @QueryParam("continuationToken") String continuationToken, + @QueryParam("totalRecordCount") Integer totalRecordCount, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @PathParam("assessmentName") String assessmentName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/sqlAssessments/{assessmentName}/assessedSqlInstances/{assessedSqlInstanceName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @PathParam("assessmentName") String assessmentName, + @PathParam("assessedSqlInstanceName") String assessedSqlInstanceName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listBySqlAssessmentV2Next( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * List AssessedSqlInstanceV2 resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlInstanceV2 list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySqlAssessmentV2SinglePageAsync( + String resourceGroupName, String projectName, String groupName, String assessmentName, String filter, + Integer pageSize, String continuationToken, Integer totalRecordCount) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listBySqlAssessmentV2(this.client.getEndpoint(), + this.client.getApiVersion(), this.client.getSubscriptionId(), resourceGroupName, filter, pageSize, + continuationToken, totalRecordCount, projectName, groupName, assessmentName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List AssessedSqlInstanceV2 resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlInstanceV2 list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySqlAssessmentV2SinglePageAsync( + String resourceGroupName, String projectName, String groupName, String assessmentName, String filter, + Integer pageSize, String continuationToken, Integer totalRecordCount, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listBySqlAssessmentV2(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, filter, pageSize, continuationToken, + totalRecordCount, projectName, groupName, assessmentName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List AssessedSqlInstanceV2 resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlInstanceV2 list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listBySqlAssessmentV2Async(String resourceGroupName, + String projectName, String groupName, String assessmentName, String filter, Integer pageSize, + String continuationToken, Integer totalRecordCount) { + return new PagedFlux<>( + () -> listBySqlAssessmentV2SinglePageAsync(resourceGroupName, projectName, groupName, assessmentName, + filter, pageSize, continuationToken, totalRecordCount), + nextLink -> listBySqlAssessmentV2NextSinglePageAsync(nextLink)); + } + + /** + * List AssessedSqlInstanceV2 resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlInstanceV2 list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listBySqlAssessmentV2Async(String resourceGroupName, + String projectName, String groupName, String assessmentName) { + final String filter = null; + final Integer pageSize = null; + final String continuationToken = null; + final Integer totalRecordCount = null; + return new PagedFlux<>( + () -> listBySqlAssessmentV2SinglePageAsync(resourceGroupName, projectName, groupName, assessmentName, + filter, pageSize, continuationToken, totalRecordCount), + nextLink -> listBySqlAssessmentV2NextSinglePageAsync(nextLink)); + } + + /** + * List AssessedSqlInstanceV2 resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlInstanceV2 list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listBySqlAssessmentV2Async(String resourceGroupName, + String projectName, String groupName, String assessmentName, String filter, Integer pageSize, + String continuationToken, Integer totalRecordCount, Context context) { + return new PagedFlux<>( + () -> listBySqlAssessmentV2SinglePageAsync(resourceGroupName, projectName, groupName, assessmentName, + filter, pageSize, continuationToken, totalRecordCount, context), + nextLink -> listBySqlAssessmentV2NextSinglePageAsync(nextLink, context)); + } + + /** + * List AssessedSqlInstanceV2 resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlInstanceV2 list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName) { + final String filter = null; + final Integer pageSize = null; + final String continuationToken = null; + final Integer totalRecordCount = null; + return new PagedIterable<>(listBySqlAssessmentV2Async(resourceGroupName, projectName, groupName, assessmentName, + filter, pageSize, continuationToken, totalRecordCount)); + } + + /** + * List AssessedSqlInstanceV2 resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlInstanceV2 list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName, String filter, Integer pageSize, String continuationToken, + Integer totalRecordCount, Context context) { + return new PagedIterable<>(listBySqlAssessmentV2Async(resourceGroupName, projectName, groupName, assessmentName, + filter, pageSize, continuationToken, totalRecordCount, context)); + } + + /** + * Get a AssessedSqlInstanceV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param assessedSqlInstanceName Sql assessment Assessed Instance ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlInstanceV2 along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, + String projectName, String groupName, String assessmentName, String assessedSqlInstanceName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + if (assessedSqlInstanceName == null) { + return Mono.error( + new IllegalArgumentException("Parameter assessedSqlInstanceName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, assessmentName, + assessedSqlInstanceName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a AssessedSqlInstanceV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param assessedSqlInstanceName Sql assessment Assessed Instance ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlInstanceV2 along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, + String projectName, String groupName, String assessmentName, String assessedSqlInstanceName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + if (assessedSqlInstanceName == null) { + return Mono.error( + new IllegalArgumentException("Parameter assessedSqlInstanceName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, groupName, assessmentName, assessedSqlInstanceName, accept, context); + } + + /** + * Get a AssessedSqlInstanceV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param assessedSqlInstanceName Sql assessment Assessed Instance ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlInstanceV2 on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName, String assessedSqlInstanceName) { + return getWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, assessedSqlInstanceName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a AssessedSqlInstanceV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param assessedSqlInstanceName Sql assessment Assessed Instance ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlInstanceV2 along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceGroupName, String projectName, + String groupName, String assessmentName, String assessedSqlInstanceName, Context context) { + return getWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, assessedSqlInstanceName, + context).block(); + } + + /** + * Get a AssessedSqlInstanceV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param assessedSqlInstanceName Sql assessment Assessed Instance ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlInstanceV2. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public AssessedSqlInstanceV2Inner get(String resourceGroupName, String projectName, String groupName, + String assessmentName, String assessedSqlInstanceName) { + return getWithResponse(resourceGroupName, projectName, groupName, assessmentName, assessedSqlInstanceName, + Context.NONE).getValue(); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlInstanceV2 list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySqlAssessmentV2NextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listBySqlAssessmentV2Next(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlInstanceV2 list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySqlAssessmentV2NextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listBySqlAssessmentV2Next(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlInstanceV2OperationsImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlInstanceV2OperationsImpl.java new file mode 100644 index 000000000000..eee210892584 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlInstanceV2OperationsImpl.java @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.migration.assessment.fluent.AssessedSqlInstanceV2OperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlInstanceV2Inner; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlInstanceV2; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlInstanceV2Operations; + +public final class AssessedSqlInstanceV2OperationsImpl implements AssessedSqlInstanceV2Operations { + private static final ClientLogger LOGGER = new ClientLogger(AssessedSqlInstanceV2OperationsImpl.class); + + private final AssessedSqlInstanceV2OperationsClient innerClient; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + public AssessedSqlInstanceV2OperationsImpl(AssessedSqlInstanceV2OperationsClient innerClient, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName) { + PagedIterable inner + = this.serviceClient().listBySqlAssessmentV2(resourceGroupName, projectName, groupName, assessmentName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new AssessedSqlInstanceV2Impl(inner1, this.manager())); + } + + public PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName, String filter, Integer pageSize, String continuationToken, + Integer totalRecordCount, Context context) { + PagedIterable inner = this.serviceClient() + .listBySqlAssessmentV2(resourceGroupName, projectName, groupName, assessmentName, filter, pageSize, + continuationToken, totalRecordCount, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new AssessedSqlInstanceV2Impl(inner1, this.manager())); + } + + public Response getWithResponse(String resourceGroupName, String projectName, + String groupName, String assessmentName, String assessedSqlInstanceName, Context context) { + Response inner = this.serviceClient() + .getWithResponse(resourceGroupName, projectName, groupName, assessmentName, assessedSqlInstanceName, + context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new AssessedSqlInstanceV2Impl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public AssessedSqlInstanceV2 get(String resourceGroupName, String projectName, String groupName, + String assessmentName, String assessedSqlInstanceName) { + AssessedSqlInstanceV2Inner inner = this.serviceClient() + .get(resourceGroupName, projectName, groupName, assessmentName, assessedSqlInstanceName); + if (inner != null) { + return new AssessedSqlInstanceV2Impl(inner, this.manager()); + } else { + return null; + } + } + + private AssessedSqlInstanceV2OperationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlMachineImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlMachineImpl.java new file mode 100644 index 000000000000..6e997f26e1f2 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlMachineImpl.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlMachineInner; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlMachine; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlMachineProperties; + +public final class AssessedSqlMachineImpl implements AssessedSqlMachine { + private AssessedSqlMachineInner innerObject; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + AssessedSqlMachineImpl(AssessedSqlMachineInner innerObject, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public AssessedSqlMachineProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public AssessedSqlMachineInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlMachinesOperationsClientImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlMachinesOperationsClientImpl.java new file mode 100644 index 000000000000..c00904dbe115 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlMachinesOperationsClientImpl.java @@ -0,0 +1,541 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.resourcemanager.migration.assessment.fluent.AssessedSqlMachinesOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlMachineInner; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlMachineListResult; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in AssessedSqlMachinesOperationsClient. + */ +public final class AssessedSqlMachinesOperationsClientImpl implements AssessedSqlMachinesOperationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final AssessedSqlMachinesOperationsService service; + + /** + * The service client containing this operation class. + */ + private final MigrationAssessmentManagementClientImpl client; + + /** + * Initializes an instance of AssessedSqlMachinesOperationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + AssessedSqlMachinesOperationsClientImpl(MigrationAssessmentManagementClientImpl client) { + this.service = RestProxy.create(AssessedSqlMachinesOperationsService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for MigrationAssessmentManagementClientAssessedSqlMachinesOperations to + * be used by the proxy service to perform REST calls. + */ + @Host("{$host}") + @ServiceInterface(name = "MigrationAssessmentM") + public interface AssessedSqlMachinesOperationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/sqlAssessments/{assessmentName}/assessedSqlMachines") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listBySqlAssessmentV2(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @QueryParam("$filter") String filter, + @QueryParam("pageSize") Integer pageSize, @QueryParam("continuationToken") String continuationToken, + @QueryParam("totalRecordCount") Integer totalRecordCount, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @PathParam("assessmentName") String assessmentName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/sqlAssessments/{assessmentName}/assessedSqlMachines/{assessedSqlMachineName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @PathParam("assessmentName") String assessmentName, + @PathParam("assessedSqlMachineName") String assessedSqlMachineName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listBySqlAssessmentV2Next( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * List AssessedSqlMachine resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlMachine list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySqlAssessmentV2SinglePageAsync(String resourceGroupName, + String projectName, String groupName, String assessmentName, String filter, Integer pageSize, + String continuationToken, Integer totalRecordCount) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listBySqlAssessmentV2(this.client.getEndpoint(), + this.client.getApiVersion(), this.client.getSubscriptionId(), resourceGroupName, filter, pageSize, + continuationToken, totalRecordCount, projectName, groupName, assessmentName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List AssessedSqlMachine resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlMachine list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySqlAssessmentV2SinglePageAsync(String resourceGroupName, + String projectName, String groupName, String assessmentName, String filter, Integer pageSize, + String continuationToken, Integer totalRecordCount, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listBySqlAssessmentV2(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, filter, pageSize, continuationToken, + totalRecordCount, projectName, groupName, assessmentName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List AssessedSqlMachine resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlMachine list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listBySqlAssessmentV2Async(String resourceGroupName, String projectName, + String groupName, String assessmentName, String filter, Integer pageSize, String continuationToken, + Integer totalRecordCount) { + return new PagedFlux<>( + () -> listBySqlAssessmentV2SinglePageAsync(resourceGroupName, projectName, groupName, assessmentName, + filter, pageSize, continuationToken, totalRecordCount), + nextLink -> listBySqlAssessmentV2NextSinglePageAsync(nextLink)); + } + + /** + * List AssessedSqlMachine resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlMachine list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listBySqlAssessmentV2Async(String resourceGroupName, String projectName, + String groupName, String assessmentName) { + final String filter = null; + final Integer pageSize = null; + final String continuationToken = null; + final Integer totalRecordCount = null; + return new PagedFlux<>( + () -> listBySqlAssessmentV2SinglePageAsync(resourceGroupName, projectName, groupName, assessmentName, + filter, pageSize, continuationToken, totalRecordCount), + nextLink -> listBySqlAssessmentV2NextSinglePageAsync(nextLink)); + } + + /** + * List AssessedSqlMachine resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlMachine list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listBySqlAssessmentV2Async(String resourceGroupName, String projectName, + String groupName, String assessmentName, String filter, Integer pageSize, String continuationToken, + Integer totalRecordCount, Context context) { + return new PagedFlux<>( + () -> listBySqlAssessmentV2SinglePageAsync(resourceGroupName, projectName, groupName, assessmentName, + filter, pageSize, continuationToken, totalRecordCount, context), + nextLink -> listBySqlAssessmentV2NextSinglePageAsync(nextLink, context)); + } + + /** + * List AssessedSqlMachine resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlMachine list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName) { + final String filter = null; + final Integer pageSize = null; + final String continuationToken = null; + final Integer totalRecordCount = null; + return new PagedIterable<>(listBySqlAssessmentV2Async(resourceGroupName, projectName, groupName, assessmentName, + filter, pageSize, continuationToken, totalRecordCount)); + } + + /** + * List AssessedSqlMachine resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlMachine list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName, String filter, Integer pageSize, String continuationToken, + Integer totalRecordCount, Context context) { + return new PagedIterable<>(listBySqlAssessmentV2Async(resourceGroupName, projectName, groupName, assessmentName, + filter, pageSize, continuationToken, totalRecordCount, context)); + } + + /** + * Get a AssessedSqlMachine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param assessedSqlMachineName Sql assessment Assessed Machine ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlMachine along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName, String assessedSqlMachineName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + if (assessedSqlMachineName == null) { + return Mono.error( + new IllegalArgumentException("Parameter assessedSqlMachineName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, assessmentName, + assessedSqlMachineName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a AssessedSqlMachine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param assessedSqlMachineName Sql assessment Assessed Machine ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlMachine along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName, String assessedSqlMachineName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + if (assessedSqlMachineName == null) { + return Mono.error( + new IllegalArgumentException("Parameter assessedSqlMachineName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, groupName, assessmentName, assessedSqlMachineName, accept, context); + } + + /** + * Get a AssessedSqlMachine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param assessedSqlMachineName Sql assessment Assessed Machine ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlMachine on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName, String assessedSqlMachineName) { + return getWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, assessedSqlMachineName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a AssessedSqlMachine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param assessedSqlMachineName Sql assessment Assessed Machine ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlMachine along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceGroupName, String projectName, + String groupName, String assessmentName, String assessedSqlMachineName, Context context) { + return getWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, assessedSqlMachineName, + context).block(); + } + + /** + * Get a AssessedSqlMachine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param assessedSqlMachineName Sql assessment Assessed Machine ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlMachine. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public AssessedSqlMachineInner get(String resourceGroupName, String projectName, String groupName, + String assessmentName, String assessedSqlMachineName) { + return getWithResponse(resourceGroupName, projectName, groupName, assessmentName, assessedSqlMachineName, + Context.NONE).getValue(); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlMachine list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySqlAssessmentV2NextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listBySqlAssessmentV2Next(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlMachine list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySqlAssessmentV2NextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listBySqlAssessmentV2Next(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlMachinesOperationsImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlMachinesOperationsImpl.java new file mode 100644 index 000000000000..8d46a78e8c17 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlMachinesOperationsImpl.java @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.migration.assessment.fluent.AssessedSqlMachinesOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlMachineInner; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlMachine; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlMachinesOperations; + +public final class AssessedSqlMachinesOperationsImpl implements AssessedSqlMachinesOperations { + private static final ClientLogger LOGGER = new ClientLogger(AssessedSqlMachinesOperationsImpl.class); + + private final AssessedSqlMachinesOperationsClient innerClient; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + public AssessedSqlMachinesOperationsImpl(AssessedSqlMachinesOperationsClient innerClient, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName) { + PagedIterable inner + = this.serviceClient().listBySqlAssessmentV2(resourceGroupName, projectName, groupName, assessmentName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new AssessedSqlMachineImpl(inner1, this.manager())); + } + + public PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName, String filter, Integer pageSize, String continuationToken, + Integer totalRecordCount, Context context) { + PagedIterable inner = this.serviceClient() + .listBySqlAssessmentV2(resourceGroupName, projectName, groupName, assessmentName, filter, pageSize, + continuationToken, totalRecordCount, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new AssessedSqlMachineImpl(inner1, this.manager())); + } + + public Response getWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, String assessedSqlMachineName, Context context) { + Response inner = this.serviceClient() + .getWithResponse(resourceGroupName, projectName, groupName, assessmentName, assessedSqlMachineName, + context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new AssessedSqlMachineImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public AssessedSqlMachine get(String resourceGroupName, String projectName, String groupName, String assessmentName, + String assessedSqlMachineName) { + AssessedSqlMachineInner inner = this.serviceClient() + .get(resourceGroupName, projectName, groupName, assessmentName, assessedSqlMachineName); + if (inner != null) { + return new AssessedSqlMachineImpl(inner, this.manager()); + } else { + return null; + } + } + + private AssessedSqlMachinesOperationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlRecommendedEntityImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlRecommendedEntityImpl.java new file mode 100644 index 000000000000..fd9a2821c92c --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlRecommendedEntityImpl.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlRecommendedEntityInner; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlRecommendedEntity; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlRecommendedEntityProperties; + +public final class AssessedSqlRecommendedEntityImpl implements AssessedSqlRecommendedEntity { + private AssessedSqlRecommendedEntityInner innerObject; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + AssessedSqlRecommendedEntityImpl(AssessedSqlRecommendedEntityInner innerObject, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public AssessedSqlRecommendedEntityProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public AssessedSqlRecommendedEntityInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlRecommendedEntityOperationsClientImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlRecommendedEntityOperationsClientImpl.java new file mode 100644 index 000000000000..8b3126eaf54f --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlRecommendedEntityOperationsClientImpl.java @@ -0,0 +1,552 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.resourcemanager.migration.assessment.fluent.AssessedSqlRecommendedEntityOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlRecommendedEntityInner; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlRecommendedEntityListResult; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in + * AssessedSqlRecommendedEntityOperationsClient. + */ +public final class AssessedSqlRecommendedEntityOperationsClientImpl + implements AssessedSqlRecommendedEntityOperationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final AssessedSqlRecommendedEntityOperationsService service; + + /** + * The service client containing this operation class. + */ + private final MigrationAssessmentManagementClientImpl client; + + /** + * Initializes an instance of AssessedSqlRecommendedEntityOperationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + AssessedSqlRecommendedEntityOperationsClientImpl(MigrationAssessmentManagementClientImpl client) { + this.service = RestProxy.create(AssessedSqlRecommendedEntityOperationsService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for + * MigrationAssessmentManagementClientAssessedSqlRecommendedEntityOperations to be used by the proxy service to + * perform REST calls. + */ + @Host("{$host}") + @ServiceInterface(name = "MigrationAssessmentM") + public interface AssessedSqlRecommendedEntityOperationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/sqlAssessments/{assessmentName}/recommendedAssessedEntities") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listBySqlAssessmentV2( + @HostParam("$host") String endpoint, @QueryParam("api-version") String apiVersion, + @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @QueryParam("$filter") String filter, + @QueryParam("pageSize") Integer pageSize, @QueryParam("continuationToken") String continuationToken, + @QueryParam("totalRecordCount") Integer totalRecordCount, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @PathParam("assessmentName") String assessmentName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/sqlAssessments/{assessmentName}/recommendedAssessedEntities/{recommendedAssessedEntityName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @PathParam("assessmentName") String assessmentName, + @PathParam("recommendedAssessedEntityName") String recommendedAssessedEntityName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listBySqlAssessmentV2Next( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * List AssessedSqlRecommendedEntity resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlRecommendedEntity list operation along with {@link PagedResponse} on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySqlAssessmentV2SinglePageAsync( + String resourceGroupName, String projectName, String groupName, String assessmentName, String filter, + Integer pageSize, String continuationToken, Integer totalRecordCount) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listBySqlAssessmentV2(this.client.getEndpoint(), + this.client.getApiVersion(), this.client.getSubscriptionId(), resourceGroupName, filter, pageSize, + continuationToken, totalRecordCount, projectName, groupName, assessmentName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List AssessedSqlRecommendedEntity resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlRecommendedEntity list operation along with {@link PagedResponse} on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySqlAssessmentV2SinglePageAsync( + String resourceGroupName, String projectName, String groupName, String assessmentName, String filter, + Integer pageSize, String continuationToken, Integer totalRecordCount, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listBySqlAssessmentV2(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, filter, pageSize, continuationToken, + totalRecordCount, projectName, groupName, assessmentName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List AssessedSqlRecommendedEntity resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlRecommendedEntity list operation as paginated response with + * {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listBySqlAssessmentV2Async(String resourceGroupName, + String projectName, String groupName, String assessmentName, String filter, Integer pageSize, + String continuationToken, Integer totalRecordCount) { + return new PagedFlux<>( + () -> listBySqlAssessmentV2SinglePageAsync(resourceGroupName, projectName, groupName, assessmentName, + filter, pageSize, continuationToken, totalRecordCount), + nextLink -> listBySqlAssessmentV2NextSinglePageAsync(nextLink)); + } + + /** + * List AssessedSqlRecommendedEntity resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlRecommendedEntity list operation as paginated response with + * {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listBySqlAssessmentV2Async(String resourceGroupName, + String projectName, String groupName, String assessmentName) { + final String filter = null; + final Integer pageSize = null; + final String continuationToken = null; + final Integer totalRecordCount = null; + return new PagedFlux<>( + () -> listBySqlAssessmentV2SinglePageAsync(resourceGroupName, projectName, groupName, assessmentName, + filter, pageSize, continuationToken, totalRecordCount), + nextLink -> listBySqlAssessmentV2NextSinglePageAsync(nextLink)); + } + + /** + * List AssessedSqlRecommendedEntity resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlRecommendedEntity list operation as paginated response with + * {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listBySqlAssessmentV2Async(String resourceGroupName, + String projectName, String groupName, String assessmentName, String filter, Integer pageSize, + String continuationToken, Integer totalRecordCount, Context context) { + return new PagedFlux<>( + () -> listBySqlAssessmentV2SinglePageAsync(resourceGroupName, projectName, groupName, assessmentName, + filter, pageSize, continuationToken, totalRecordCount, context), + nextLink -> listBySqlAssessmentV2NextSinglePageAsync(nextLink, context)); + } + + /** + * List AssessedSqlRecommendedEntity resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlRecommendedEntity list operation as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listBySqlAssessmentV2(String resourceGroupName, + String projectName, String groupName, String assessmentName) { + final String filter = null; + final Integer pageSize = null; + final String continuationToken = null; + final Integer totalRecordCount = null; + return new PagedIterable<>(listBySqlAssessmentV2Async(resourceGroupName, projectName, groupName, assessmentName, + filter, pageSize, continuationToken, totalRecordCount)); + } + + /** + * List AssessedSqlRecommendedEntity resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlRecommendedEntity list operation as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listBySqlAssessmentV2(String resourceGroupName, + String projectName, String groupName, String assessmentName, String filter, Integer pageSize, + String continuationToken, Integer totalRecordCount, Context context) { + return new PagedIterable<>(listBySqlAssessmentV2Async(resourceGroupName, projectName, groupName, assessmentName, + filter, pageSize, continuationToken, totalRecordCount, context)); + } + + /** + * Get a AssessedSqlRecommendedEntity. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param recommendedAssessedEntityName Sql assessment Assessed Recommended Entity ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlRecommendedEntity along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, + String projectName, String groupName, String assessmentName, String recommendedAssessedEntityName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + if (recommendedAssessedEntityName == null) { + return Mono.error(new IllegalArgumentException( + "Parameter recommendedAssessedEntityName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, assessmentName, + recommendedAssessedEntityName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a AssessedSqlRecommendedEntity. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param recommendedAssessedEntityName Sql assessment Assessed Recommended Entity ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlRecommendedEntity along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, + String projectName, String groupName, String assessmentName, String recommendedAssessedEntityName, + Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + if (recommendedAssessedEntityName == null) { + return Mono.error(new IllegalArgumentException( + "Parameter recommendedAssessedEntityName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, groupName, assessmentName, recommendedAssessedEntityName, accept, context); + } + + /** + * Get a AssessedSqlRecommendedEntity. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param recommendedAssessedEntityName Sql assessment Assessed Recommended Entity ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlRecommendedEntity on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName, String recommendedAssessedEntityName) { + return getWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, + recommendedAssessedEntityName).flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a AssessedSqlRecommendedEntity. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param recommendedAssessedEntityName Sql assessment Assessed Recommended Entity ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlRecommendedEntity along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceGroupName, String projectName, + String groupName, String assessmentName, String recommendedAssessedEntityName, Context context) { + return getWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, + recommendedAssessedEntityName, context).block(); + } + + /** + * Get a AssessedSqlRecommendedEntity. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param recommendedAssessedEntityName Sql assessment Assessed Recommended Entity ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlRecommendedEntity. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public AssessedSqlRecommendedEntityInner get(String resourceGroupName, String projectName, String groupName, + String assessmentName, String recommendedAssessedEntityName) { + return getWithResponse(resourceGroupName, projectName, groupName, assessmentName, recommendedAssessedEntityName, + Context.NONE).getValue(); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlRecommendedEntity list operation along with {@link PagedResponse} on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> + listBySqlAssessmentV2NextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listBySqlAssessmentV2Next(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlRecommendedEntity list operation along with {@link PagedResponse} on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> + listBySqlAssessmentV2NextSinglePageAsync(String nextLink, Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listBySqlAssessmentV2Next(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlRecommendedEntityOperationsImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlRecommendedEntityOperationsImpl.java new file mode 100644 index 000000000000..e29602665240 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessedSqlRecommendedEntityOperationsImpl.java @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.migration.assessment.fluent.AssessedSqlRecommendedEntityOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlRecommendedEntityInner; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlRecommendedEntity; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlRecommendedEntityOperations; + +public final class AssessedSqlRecommendedEntityOperationsImpl implements AssessedSqlRecommendedEntityOperations { + private static final ClientLogger LOGGER = new ClientLogger(AssessedSqlRecommendedEntityOperationsImpl.class); + + private final AssessedSqlRecommendedEntityOperationsClient innerClient; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + public AssessedSqlRecommendedEntityOperationsImpl(AssessedSqlRecommendedEntityOperationsClient innerClient, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public PagedIterable listBySqlAssessmentV2(String resourceGroupName, + String projectName, String groupName, String assessmentName) { + PagedIterable inner + = this.serviceClient().listBySqlAssessmentV2(resourceGroupName, projectName, groupName, assessmentName); + return ResourceManagerUtils.mapPage(inner, + inner1 -> new AssessedSqlRecommendedEntityImpl(inner1, this.manager())); + } + + public PagedIterable listBySqlAssessmentV2(String resourceGroupName, + String projectName, String groupName, String assessmentName, String filter, Integer pageSize, + String continuationToken, Integer totalRecordCount, Context context) { + PagedIterable inner = this.serviceClient() + .listBySqlAssessmentV2(resourceGroupName, projectName, groupName, assessmentName, filter, pageSize, + continuationToken, totalRecordCount, context); + return ResourceManagerUtils.mapPage(inner, + inner1 -> new AssessedSqlRecommendedEntityImpl(inner1, this.manager())); + } + + public Response getWithResponse(String resourceGroupName, String projectName, + String groupName, String assessmentName, String recommendedAssessedEntityName, Context context) { + Response inner = this.serviceClient() + .getWithResponse(resourceGroupName, projectName, groupName, assessmentName, recommendedAssessedEntityName, + context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new AssessedSqlRecommendedEntityImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public AssessedSqlRecommendedEntity get(String resourceGroupName, String projectName, String groupName, + String assessmentName, String recommendedAssessedEntityName) { + AssessedSqlRecommendedEntityInner inner = this.serviceClient() + .get(resourceGroupName, projectName, groupName, assessmentName, recommendedAssessedEntityName); + if (inner != null) { + return new AssessedSqlRecommendedEntityImpl(inner, this.manager()); + } else { + return null; + } + } + + private AssessedSqlRecommendedEntityOperationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentImpl.java new file mode 100644 index 000000000000..defecb496ac0 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentImpl.java @@ -0,0 +1,119 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentInner; +import com.azure.resourcemanager.migration.assessment.models.Assessment; +import com.azure.resourcemanager.migration.assessment.models.DownloadUrl; +import com.azure.resourcemanager.migration.assessment.models.MachineAssessmentProperties; + +public final class AssessmentImpl implements Assessment, Assessment.Definition { + private AssessmentInner innerObject; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + AssessmentImpl(AssessmentInner innerObject, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public MachineAssessmentProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public AssessmentInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } + + private String resourceGroupName; + + private String projectName; + + private String groupName; + + private String assessmentName; + + public AssessmentImpl withExistingGroup(String resourceGroupName, String projectName, String groupName) { + this.resourceGroupName = resourceGroupName; + this.projectName = projectName; + this.groupName = groupName; + return this; + } + + public Assessment create() { + this.innerObject = serviceManager.serviceClient() + .getAssessmentsOperations() + .create(resourceGroupName, projectName, groupName, assessmentName, this.innerModel(), Context.NONE); + return this; + } + + public Assessment create(Context context) { + this.innerObject = serviceManager.serviceClient() + .getAssessmentsOperations() + .create(resourceGroupName, projectName, groupName, assessmentName, this.innerModel(), context); + return this; + } + + AssessmentImpl(String name, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = new AssessmentInner(); + this.serviceManager = serviceManager; + this.assessmentName = name; + } + + public Assessment refresh() { + this.innerObject = serviceManager.serviceClient() + .getAssessmentsOperations() + .getWithResponse(resourceGroupName, projectName, groupName, assessmentName, Context.NONE) + .getValue(); + return this; + } + + public Assessment refresh(Context context) { + this.innerObject = serviceManager.serviceClient() + .getAssessmentsOperations() + .getWithResponse(resourceGroupName, projectName, groupName, assessmentName, context) + .getValue(); + return this; + } + + public DownloadUrl downloadUrl(Object body) { + return serviceManager.assessmentsOperations() + .downloadUrl(resourceGroupName, projectName, groupName, assessmentName, body); + } + + public DownloadUrl downloadUrl(Object body, Context context) { + return serviceManager.assessmentsOperations() + .downloadUrl(resourceGroupName, projectName, groupName, assessmentName, body, context); + } + + public AssessmentImpl withProperties(MachineAssessmentProperties properties) { + this.innerModel().withProperties(properties); + return this; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentOptionsImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentOptionsImpl.java new file mode 100644 index 000000000000..26bf0205990a --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentOptionsImpl.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentOptionsInner; +import com.azure.resourcemanager.migration.assessment.models.AssessmentOptions; +import com.azure.resourcemanager.migration.assessment.models.AssessmentOptionsProperties; + +public final class AssessmentOptionsImpl implements AssessmentOptions { + private AssessmentOptionsInner innerObject; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + AssessmentOptionsImpl(AssessmentOptionsInner innerObject, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public AssessmentOptionsProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public AssessmentOptionsInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentOptionsOperationsClientImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentOptionsOperationsClientImpl.java new file mode 100644 index 000000000000..215d34b565d1 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentOptionsOperationsClientImpl.java @@ -0,0 +1,424 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.resourcemanager.migration.assessment.fluent.AssessmentOptionsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentOptionsInner; +import com.azure.resourcemanager.migration.assessment.models.AssessmentOptionsListResult; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in AssessmentOptionsOperationsClient. + */ +public final class AssessmentOptionsOperationsClientImpl implements AssessmentOptionsOperationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final AssessmentOptionsOperationsService service; + + /** + * The service client containing this operation class. + */ + private final MigrationAssessmentManagementClientImpl client; + + /** + * Initializes an instance of AssessmentOptionsOperationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + AssessmentOptionsOperationsClientImpl(MigrationAssessmentManagementClientImpl client) { + this.service = RestProxy.create(AssessmentOptionsOperationsService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for MigrationAssessmentManagementClientAssessmentOptionsOperations to be + * used by the proxy service to perform REST calls. + */ + @Host("{$host}") + @ServiceInterface(name = "MigrationAssessmentM") + public interface AssessmentOptionsOperationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/assessmentOptions") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAssessmentProject(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/assessmentOptions/{assessmentOptionsName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("assessmentOptionsName") String assessmentOptionsName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAssessmentProjectNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * List AssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentOptions list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectSinglePageAsync(String resourceGroupName, + String projectName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByAssessmentProject(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List AssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentOptions list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectSinglePageAsync(String resourceGroupName, + String projectName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByAssessmentProject(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List AssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentOptions list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentProjectAsync(String resourceGroupName, + String projectName) { + return new PagedFlux<>(() -> listByAssessmentProjectSinglePageAsync(resourceGroupName, projectName), + nextLink -> listByAssessmentProjectNextSinglePageAsync(nextLink)); + } + + /** + * List AssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentOptions list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentProjectAsync(String resourceGroupName, String projectName, + Context context) { + return new PagedFlux<>(() -> listByAssessmentProjectSinglePageAsync(resourceGroupName, projectName, context), + nextLink -> listByAssessmentProjectNextSinglePageAsync(nextLink, context)); + } + + /** + * List AssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentOptions list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName) { + return new PagedIterable<>(listByAssessmentProjectAsync(resourceGroupName, projectName)); + } + + /** + * List AssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentOptions list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context) { + return new PagedIterable<>(listByAssessmentProjectAsync(resourceGroupName, projectName, context)); + } + + /** + * Get a AssessmentOptions. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param assessmentOptionsName assessment options ARM name. Accepted value is 'default'. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessmentOptions along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String assessmentOptionsName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (assessmentOptionsName == null) { + return Mono + .error(new IllegalArgumentException("Parameter assessmentOptionsName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, assessmentOptionsName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a AssessmentOptions. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param assessmentOptionsName assessment options ARM name. Accepted value is 'default'. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessmentOptions along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String assessmentOptionsName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (assessmentOptionsName == null) { + return Mono + .error(new IllegalArgumentException("Parameter assessmentOptionsName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, assessmentOptionsName, accept, context); + } + + /** + * Get a AssessmentOptions. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param assessmentOptionsName assessment options ARM name. Accepted value is 'default'. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessmentOptions on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceGroupName, String projectName, + String assessmentOptionsName) { + return getWithResponseAsync(resourceGroupName, projectName, assessmentOptionsName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a AssessmentOptions. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param assessmentOptionsName assessment options ARM name. Accepted value is 'default'. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessmentOptions along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceGroupName, String projectName, + String assessmentOptionsName, Context context) { + return getWithResponseAsync(resourceGroupName, projectName, assessmentOptionsName, context).block(); + } + + /** + * Get a AssessmentOptions. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param assessmentOptionsName assessment options ARM name. Accepted value is 'default'. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessmentOptions. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public AssessmentOptionsInner get(String resourceGroupName, String projectName, String assessmentOptionsName) { + return getWithResponse(resourceGroupName, projectName, assessmentOptionsName, Context.NONE).getValue(); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentOptions list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByAssessmentProjectNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentOptions list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listByAssessmentProjectNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentOptionsOperationsImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentOptionsOperationsImpl.java new file mode 100644 index 000000000000..65b062939663 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentOptionsOperationsImpl.java @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.migration.assessment.fluent.AssessmentOptionsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentOptionsInner; +import com.azure.resourcemanager.migration.assessment.models.AssessmentOptions; +import com.azure.resourcemanager.migration.assessment.models.AssessmentOptionsOperations; + +public final class AssessmentOptionsOperationsImpl implements AssessmentOptionsOperations { + private static final ClientLogger LOGGER = new ClientLogger(AssessmentOptionsOperationsImpl.class); + + private final AssessmentOptionsOperationsClient innerClient; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + public AssessmentOptionsOperationsImpl(AssessmentOptionsOperationsClient innerClient, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName) { + PagedIterable inner + = this.serviceClient().listByAssessmentProject(resourceGroupName, projectName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new AssessmentOptionsImpl(inner1, this.manager())); + } + + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context) { + PagedIterable inner + = this.serviceClient().listByAssessmentProject(resourceGroupName, projectName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new AssessmentOptionsImpl(inner1, this.manager())); + } + + public Response getWithResponse(String resourceGroupName, String projectName, + String assessmentOptionsName, Context context) { + Response inner + = this.serviceClient().getWithResponse(resourceGroupName, projectName, assessmentOptionsName, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new AssessmentOptionsImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public AssessmentOptions get(String resourceGroupName, String projectName, String assessmentOptionsName) { + AssessmentOptionsInner inner = this.serviceClient().get(resourceGroupName, projectName, assessmentOptionsName); + if (inner != null) { + return new AssessmentOptionsImpl(inner, this.manager()); + } else { + return null; + } + } + + private AssessmentOptionsOperationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentProjectImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentProjectImpl.java new file mode 100644 index 000000000000..a799360049d1 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentProjectImpl.java @@ -0,0 +1,185 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.management.Region; +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentProjectInner; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProject; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProjectUpdate; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProjectUpdateProperties; +import com.azure.resourcemanager.migration.assessment.models.ProjectProperties; +import java.util.Collections; +import java.util.Map; + +public final class AssessmentProjectImpl + implements AssessmentProject, AssessmentProject.Definition, AssessmentProject.Update { + private AssessmentProjectInner innerObject; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public String location() { + return this.innerModel().location(); + } + + public Map tags() { + Map inner = this.innerModel().tags(); + if (inner != null) { + return Collections.unmodifiableMap(inner); + } else { + return Collections.emptyMap(); + } + } + + public ProjectProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public Region region() { + return Region.fromName(this.regionName()); + } + + public String regionName() { + return this.location(); + } + + public String resourceGroupName() { + return resourceGroupName; + } + + public AssessmentProjectInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } + + private String resourceGroupName; + + private String projectName; + + private AssessmentProjectUpdate updateProperties; + + public AssessmentProjectImpl withExistingResourceGroup(String resourceGroupName) { + this.resourceGroupName = resourceGroupName; + return this; + } + + public AssessmentProject create() { + this.innerObject = serviceManager.serviceClient() + .getAssessmentProjectsOperations() + .create(resourceGroupName, projectName, this.innerModel(), Context.NONE); + return this; + } + + public AssessmentProject create(Context context) { + this.innerObject = serviceManager.serviceClient() + .getAssessmentProjectsOperations() + .create(resourceGroupName, projectName, this.innerModel(), context); + return this; + } + + AssessmentProjectImpl(String name, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = new AssessmentProjectInner(); + this.serviceManager = serviceManager; + this.projectName = name; + } + + public AssessmentProjectImpl update() { + this.updateProperties = new AssessmentProjectUpdate(); + return this; + } + + public AssessmentProject apply() { + this.innerObject = serviceManager.serviceClient() + .getAssessmentProjectsOperations() + .update(resourceGroupName, projectName, updateProperties, Context.NONE); + return this; + } + + public AssessmentProject apply(Context context) { + this.innerObject = serviceManager.serviceClient() + .getAssessmentProjectsOperations() + .update(resourceGroupName, projectName, updateProperties, context); + return this; + } + + AssessmentProjectImpl(AssessmentProjectInner innerObject, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + this.resourceGroupName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "resourceGroups"); + this.projectName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "assessmentProjects"); + } + + public AssessmentProject refresh() { + this.innerObject = serviceManager.serviceClient() + .getAssessmentProjectsOperations() + .getByResourceGroupWithResponse(resourceGroupName, projectName, Context.NONE) + .getValue(); + return this; + } + + public AssessmentProject refresh(Context context) { + this.innerObject = serviceManager.serviceClient() + .getAssessmentProjectsOperations() + .getByResourceGroupWithResponse(resourceGroupName, projectName, context) + .getValue(); + return this; + } + + public AssessmentProjectImpl withRegion(Region location) { + this.innerModel().withLocation(location.toString()); + return this; + } + + public AssessmentProjectImpl withRegion(String location) { + this.innerModel().withLocation(location); + return this; + } + + public AssessmentProjectImpl withTags(Map tags) { + if (isInCreateMode()) { + this.innerModel().withTags(tags); + return this; + } else { + this.updateProperties.withTags(tags); + return this; + } + } + + public AssessmentProjectImpl withProperties(ProjectProperties properties) { + this.innerModel().withProperties(properties); + return this; + } + + public AssessmentProjectImpl withProperties(AssessmentProjectUpdateProperties properties) { + this.updateProperties.withProperties(properties); + return this; + } + + private boolean isInCreateMode() { + return this.innerModel().id() == null; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentProjectSummaryImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentProjectSummaryImpl.java new file mode 100644 index 000000000000..951d3f471aa9 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentProjectSummaryImpl.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentProjectSummaryInner; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProjectSummary; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProjectSummaryProperties; + +public final class AssessmentProjectSummaryImpl implements AssessmentProjectSummary { + private AssessmentProjectSummaryInner innerObject; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + AssessmentProjectSummaryImpl(AssessmentProjectSummaryInner innerObject, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public AssessmentProjectSummaryProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public AssessmentProjectSummaryInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentProjectSummaryOperationsClientImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentProjectSummaryOperationsClientImpl.java new file mode 100644 index 000000000000..f3ede7a19730 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentProjectSummaryOperationsClientImpl.java @@ -0,0 +1,429 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.resourcemanager.migration.assessment.fluent.AssessmentProjectSummaryOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentProjectSummaryInner; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProjectSummaryListResult; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in AssessmentProjectSummaryOperationsClient. + */ +public final class AssessmentProjectSummaryOperationsClientImpl implements AssessmentProjectSummaryOperationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final AssessmentProjectSummaryOperationsService service; + + /** + * The service client containing this operation class. + */ + private final MigrationAssessmentManagementClientImpl client; + + /** + * Initializes an instance of AssessmentProjectSummaryOperationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + AssessmentProjectSummaryOperationsClientImpl(MigrationAssessmentManagementClientImpl client) { + this.service = RestProxy.create(AssessmentProjectSummaryOperationsService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for MigrationAssessmentManagementClientAssessmentProjectSummaryOperations + * to be used by the proxy service to perform REST calls. + */ + @Host("{$host}") + @ServiceInterface(name = "MigrationAssessmentM") + public interface AssessmentProjectSummaryOperationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/projectSummary") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAssessmentProject(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/projectSummary/{projectSummaryName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("projectSummaryName") String projectSummaryName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAssessmentProjectNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * List AssessmentProjectSummary resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProjectSummary list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> + listByAssessmentProjectSinglePageAsync(String resourceGroupName, String projectName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByAssessmentProject(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List AssessmentProjectSummary resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProjectSummary list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> + listByAssessmentProjectSinglePageAsync(String resourceGroupName, String projectName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByAssessmentProject(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List AssessmentProjectSummary resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProjectSummary list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentProjectAsync(String resourceGroupName, + String projectName) { + return new PagedFlux<>(() -> listByAssessmentProjectSinglePageAsync(resourceGroupName, projectName), + nextLink -> listByAssessmentProjectNextSinglePageAsync(nextLink)); + } + + /** + * List AssessmentProjectSummary resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProjectSummary list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentProjectAsync(String resourceGroupName, + String projectName, Context context) { + return new PagedFlux<>(() -> listByAssessmentProjectSinglePageAsync(resourceGroupName, projectName, context), + nextLink -> listByAssessmentProjectNextSinglePageAsync(nextLink, context)); + } + + /** + * List AssessmentProjectSummary resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProjectSummary list operation as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAssessmentProject(String resourceGroupName, + String projectName) { + return new PagedIterable<>(listByAssessmentProjectAsync(resourceGroupName, projectName)); + } + + /** + * List AssessmentProjectSummary resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProjectSummary list operation as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAssessmentProject(String resourceGroupName, + String projectName, Context context) { + return new PagedIterable<>(listByAssessmentProjectAsync(resourceGroupName, projectName, context)); + } + + /** + * Get a AssessmentProjectSummary. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param projectSummaryName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessmentProjectSummary along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, + String projectName, String projectSummaryName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (projectSummaryName == null) { + return Mono + .error(new IllegalArgumentException("Parameter projectSummaryName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, projectSummaryName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a AssessmentProjectSummary. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param projectSummaryName Group ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessmentProjectSummary along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, + String projectName, String projectSummaryName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (projectSummaryName == null) { + return Mono + .error(new IllegalArgumentException("Parameter projectSummaryName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, projectSummaryName, accept, context); + } + + /** + * Get a AssessmentProjectSummary. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param projectSummaryName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessmentProjectSummary on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceGroupName, String projectName, + String projectSummaryName) { + return getWithResponseAsync(resourceGroupName, projectName, projectSummaryName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a AssessmentProjectSummary. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param projectSummaryName Group ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessmentProjectSummary along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceGroupName, String projectName, + String projectSummaryName, Context context) { + return getWithResponseAsync(resourceGroupName, projectName, projectSummaryName, context).block(); + } + + /** + * Get a AssessmentProjectSummary. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param projectSummaryName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessmentProjectSummary. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public AssessmentProjectSummaryInner get(String resourceGroupName, String projectName, String projectSummaryName) { + return getWithResponse(resourceGroupName, projectName, projectSummaryName, Context.NONE).getValue(); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProjectSummary list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> + listByAssessmentProjectNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByAssessmentProjectNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProjectSummary list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> + listByAssessmentProjectNextSinglePageAsync(String nextLink, Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listByAssessmentProjectNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentProjectSummaryOperationsImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentProjectSummaryOperationsImpl.java new file mode 100644 index 000000000000..9580bbc7f81b --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentProjectSummaryOperationsImpl.java @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.migration.assessment.fluent.AssessmentProjectSummaryOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentProjectSummaryInner; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProjectSummary; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProjectSummaryOperations; + +public final class AssessmentProjectSummaryOperationsImpl implements AssessmentProjectSummaryOperations { + private static final ClientLogger LOGGER = new ClientLogger(AssessmentProjectSummaryOperationsImpl.class); + + private final AssessmentProjectSummaryOperationsClient innerClient; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + public AssessmentProjectSummaryOperationsImpl(AssessmentProjectSummaryOperationsClient innerClient, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public PagedIterable listByAssessmentProject(String resourceGroupName, + String projectName) { + PagedIterable inner + = this.serviceClient().listByAssessmentProject(resourceGroupName, projectName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new AssessmentProjectSummaryImpl(inner1, this.manager())); + } + + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context) { + PagedIterable inner + = this.serviceClient().listByAssessmentProject(resourceGroupName, projectName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new AssessmentProjectSummaryImpl(inner1, this.manager())); + } + + public Response getWithResponse(String resourceGroupName, String projectName, + String projectSummaryName, Context context) { + Response inner + = this.serviceClient().getWithResponse(resourceGroupName, projectName, projectSummaryName, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new AssessmentProjectSummaryImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public AssessmentProjectSummary get(String resourceGroupName, String projectName, String projectSummaryName) { + AssessmentProjectSummaryInner inner + = this.serviceClient().get(resourceGroupName, projectName, projectSummaryName); + if (inner != null) { + return new AssessmentProjectSummaryImpl(inner, this.manager()); + } else { + return null; + } + } + + private AssessmentProjectSummaryOperationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentProjectsOperationsClientImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentProjectsOperationsClientImpl.java new file mode 100644 index 000000000000..43664812a74d --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentProjectsOperationsClientImpl.java @@ -0,0 +1,1190 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.Patch; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Put; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.core.util.polling.PollerFlux; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.migration.assessment.fluent.AssessmentProjectsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentProjectInner; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProjectListResult; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProjectUpdate; +import java.nio.ByteBuffer; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in AssessmentProjectsOperationsClient. + */ +public final class AssessmentProjectsOperationsClientImpl implements AssessmentProjectsOperationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final AssessmentProjectsOperationsService service; + + /** + * The service client containing this operation class. + */ + private final MigrationAssessmentManagementClientImpl client; + + /** + * Initializes an instance of AssessmentProjectsOperationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + AssessmentProjectsOperationsClientImpl(MigrationAssessmentManagementClientImpl client) { + this.service = RestProxy.create(AssessmentProjectsOperationsService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for MigrationAssessmentManagementClientAssessmentProjectsOperations to be + * used by the proxy service to perform REST calls. + */ + @Host("{$host}") + @ServiceInterface(name = "MigrationAssessmentM") + public interface AssessmentProjectsOperationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/providers/Microsoft.Migrate/assessmentProjects") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> list(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByResourceGroup(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> getByResourceGroup(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Put("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> create(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @BodyParam("application/json") AssessmentProjectInner resource, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Patch("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}") + @ExpectedResponses({ 200, 202 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> update(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @BodyParam("application/json") AssessmentProjectUpdate properties, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Delete("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}") + @ExpectedResponses({ 200, 204 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> delete(@HostParam("$host") String endpoint, @QueryParam("api-version") String apiVersion, + @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listBySubscriptionNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByResourceGroupNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * List AssessmentProject resources by subscription ID. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProject list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync() { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.list(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List AssessmentProject resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProject list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync(Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .list(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), accept, + context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List AssessmentProject resources by subscription ID. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProject list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync() { + return new PagedFlux<>(() -> listSinglePageAsync(), + nextLink -> listBySubscriptionNextSinglePageAsync(nextLink)); + } + + /** + * List AssessmentProject resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProject list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync(Context context) { + return new PagedFlux<>(() -> listSinglePageAsync(context), + nextLink -> listBySubscriptionNextSinglePageAsync(nextLink, context)); + } + + /** + * List AssessmentProject resources by subscription ID. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProject list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list() { + return new PagedIterable<>(listAsync()); + } + + /** + * List AssessmentProject resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProject list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(Context context) { + return new PagedIterable<>(listAsync(context)); + } + + /** + * List AssessmentProject resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProject list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByResourceGroupSinglePageAsync(String resourceGroupName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List AssessmentProject resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProject list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByResourceGroupSinglePageAsync(String resourceGroupName, + Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List AssessmentProject resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProject list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByResourceGroupAsync(String resourceGroupName) { + return new PagedFlux<>(() -> listByResourceGroupSinglePageAsync(resourceGroupName), + nextLink -> listByResourceGroupNextSinglePageAsync(nextLink)); + } + + /** + * List AssessmentProject resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProject list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByResourceGroupAsync(String resourceGroupName, Context context) { + return new PagedFlux<>(() -> listByResourceGroupSinglePageAsync(resourceGroupName, context), + nextLink -> listByResourceGroupNextSinglePageAsync(nextLink, context)); + } + + /** + * List AssessmentProject resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProject list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByResourceGroup(String resourceGroupName) { + return new PagedIterable<>(listByResourceGroupAsync(resourceGroupName)); + } + + /** + * List AssessmentProject resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProject list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByResourceGroup(String resourceGroupName, Context context) { + return new PagedIterable<>(listByResourceGroupAsync(resourceGroupName, context)); + } + + /** + * Get a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessmentProject along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getByResourceGroupWithResponseAsync(String resourceGroupName, + String projectName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.getByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessmentProject along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getByResourceGroupWithResponseAsync(String resourceGroupName, + String projectName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.getByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, accept, context); + } + + /** + * Get a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessmentProject on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getByResourceGroupAsync(String resourceGroupName, String projectName) { + return getByResourceGroupWithResponseAsync(resourceGroupName, projectName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessmentProject along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getByResourceGroupWithResponse(String resourceGroupName, String projectName, + Context context) { + return getByResourceGroupWithResponseAsync(resourceGroupName, projectName, context).block(); + } + + /** + * Get a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessmentProject. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public AssessmentProjectInner getByResourceGroup(String resourceGroupName, String projectName) { + return getByResourceGroupWithResponse(resourceGroupName, projectName, Context.NONE).getValue(); + } + + /** + * Create a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Assessment project site resource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createWithResponseAsync(String resourceGroupName, String projectName, + AssessmentProjectInner resource) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.create(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, resource, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Create a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Assessment project site resource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createWithResponseAsync(String resourceGroupName, String projectName, + AssessmentProjectInner resource, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.create(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, resource, accept, context); + } + + /** + * Create a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of an Assessment project site resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, AssessmentProjectInner> + beginCreateAsync(String resourceGroupName, String projectName, AssessmentProjectInner resource) { + Mono>> mono = createWithResponseAsync(resourceGroupName, projectName, resource); + return this.client.getLroResult(mono, + this.client.getHttpPipeline(), AssessmentProjectInner.class, AssessmentProjectInner.class, + this.client.getContext()); + } + + /** + * Create a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of an Assessment project site resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, AssessmentProjectInner> beginCreateAsync( + String resourceGroupName, String projectName, AssessmentProjectInner resource, Context context) { + context = this.client.mergeContext(context); + Mono>> mono + = createWithResponseAsync(resourceGroupName, projectName, resource, context); + return this.client.getLroResult(mono, + this.client.getHttpPipeline(), AssessmentProjectInner.class, AssessmentProjectInner.class, context); + } + + /** + * Create a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of an Assessment project site resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, AssessmentProjectInner> beginCreate(String resourceGroupName, + String projectName, AssessmentProjectInner resource) { + return this.beginCreateAsync(resourceGroupName, projectName, resource).getSyncPoller(); + } + + /** + * Create a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of an Assessment project site resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, AssessmentProjectInner> beginCreate(String resourceGroupName, + String projectName, AssessmentProjectInner resource, Context context) { + return this.beginCreateAsync(resourceGroupName, projectName, resource, context).getSyncPoller(); + } + + /** + * Create a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Assessment project site resource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createAsync(String resourceGroupName, String projectName, + AssessmentProjectInner resource) { + return beginCreateAsync(resourceGroupName, projectName, resource).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Assessment project site resource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createAsync(String resourceGroupName, String projectName, + AssessmentProjectInner resource, Context context) { + return beginCreateAsync(resourceGroupName, projectName, resource, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Assessment project site resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public AssessmentProjectInner create(String resourceGroupName, String projectName, + AssessmentProjectInner resource) { + return createAsync(resourceGroupName, projectName, resource).block(); + } + + /** + * Create a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Assessment project site resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public AssessmentProjectInner create(String resourceGroupName, String projectName, AssessmentProjectInner resource, + Context context) { + return createAsync(resourceGroupName, projectName, resource, context).block(); + } + + /** + * Update a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Assessment project site resource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> updateWithResponseAsync(String resourceGroupName, String projectName, + AssessmentProjectUpdate properties) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (properties == null) { + return Mono.error(new IllegalArgumentException("Parameter properties is required and cannot be null.")); + } else { + properties.validate(); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.update(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, properties, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Update a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param properties The resource properties to be updated. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Assessment project site resource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> updateWithResponseAsync(String resourceGroupName, String projectName, + AssessmentProjectUpdate properties, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (properties == null) { + return Mono.error(new IllegalArgumentException("Parameter properties is required and cannot be null.")); + } else { + properties.validate(); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.update(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, properties, accept, context); + } + + /** + * Update a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of an Assessment project site resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, AssessmentProjectInner> + beginUpdateAsync(String resourceGroupName, String projectName, AssessmentProjectUpdate properties) { + Mono>> mono = updateWithResponseAsync(resourceGroupName, projectName, properties); + return this.client.getLroResult(mono, + this.client.getHttpPipeline(), AssessmentProjectInner.class, AssessmentProjectInner.class, + this.client.getContext()); + } + + /** + * Update a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param properties The resource properties to be updated. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of an Assessment project site resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, AssessmentProjectInner> beginUpdateAsync( + String resourceGroupName, String projectName, AssessmentProjectUpdate properties, Context context) { + context = this.client.mergeContext(context); + Mono>> mono + = updateWithResponseAsync(resourceGroupName, projectName, properties, context); + return this.client.getLroResult(mono, + this.client.getHttpPipeline(), AssessmentProjectInner.class, AssessmentProjectInner.class, context); + } + + /** + * Update a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of an Assessment project site resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, AssessmentProjectInner> beginUpdate(String resourceGroupName, + String projectName, AssessmentProjectUpdate properties) { + return this.beginUpdateAsync(resourceGroupName, projectName, properties).getSyncPoller(); + } + + /** + * Update a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param properties The resource properties to be updated. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of an Assessment project site resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, AssessmentProjectInner> beginUpdate(String resourceGroupName, + String projectName, AssessmentProjectUpdate properties, Context context) { + return this.beginUpdateAsync(resourceGroupName, projectName, properties, context).getSyncPoller(); + } + + /** + * Update a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Assessment project site resource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono updateAsync(String resourceGroupName, String projectName, + AssessmentProjectUpdate properties) { + return beginUpdateAsync(resourceGroupName, projectName, properties).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Update a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param properties The resource properties to be updated. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Assessment project site resource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono updateAsync(String resourceGroupName, String projectName, + AssessmentProjectUpdate properties, Context context) { + return beginUpdateAsync(resourceGroupName, projectName, properties, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Update a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Assessment project site resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public AssessmentProjectInner update(String resourceGroupName, String projectName, + AssessmentProjectUpdate properties) { + return updateAsync(resourceGroupName, projectName, properties).block(); + } + + /** + * Update a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param properties The resource properties to be updated. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an Assessment project site resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public AssessmentProjectInner update(String resourceGroupName, String projectName, + AssessmentProjectUpdate properties, Context context) { + return updateAsync(resourceGroupName, projectName, properties, context).block(); + } + + /** + * Delete a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String projectName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.delete(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Delete a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String projectName, + Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.delete(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, accept, context); + } + + /** + * Delete a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono deleteAsync(String resourceGroupName, String projectName) { + return deleteWithResponseAsync(resourceGroupName, projectName).flatMap(ignored -> Mono.empty()); + } + + /** + * Delete a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String resourceGroupName, String projectName, Context context) { + return deleteWithResponseAsync(resourceGroupName, projectName, context).block(); + } + + /** + * Delete a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String resourceGroupName, String projectName) { + deleteWithResponse(resourceGroupName, projectName, Context.NONE); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProject list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySubscriptionNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProject list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySubscriptionNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProject list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByResourceGroupNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByResourceGroupNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProject list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByResourceGroupNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listByResourceGroupNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentProjectsOperationsImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentProjectsOperationsImpl.java new file mode 100644 index 000000000000..cef3525453f9 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentProjectsOperationsImpl.java @@ -0,0 +1,148 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.migration.assessment.fluent.AssessmentProjectsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentProjectInner; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProject; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProjectsOperations; + +public final class AssessmentProjectsOperationsImpl implements AssessmentProjectsOperations { + private static final ClientLogger LOGGER = new ClientLogger(AssessmentProjectsOperationsImpl.class); + + private final AssessmentProjectsOperationsClient innerClient; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + public AssessmentProjectsOperationsImpl(AssessmentProjectsOperationsClient innerClient, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public PagedIterable list() { + PagedIterable inner = this.serviceClient().list(); + return ResourceManagerUtils.mapPage(inner, inner1 -> new AssessmentProjectImpl(inner1, this.manager())); + } + + public PagedIterable list(Context context) { + PagedIterable inner = this.serviceClient().list(context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new AssessmentProjectImpl(inner1, this.manager())); + } + + public PagedIterable listByResourceGroup(String resourceGroupName) { + PagedIterable inner = this.serviceClient().listByResourceGroup(resourceGroupName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new AssessmentProjectImpl(inner1, this.manager())); + } + + public PagedIterable listByResourceGroup(String resourceGroupName, Context context) { + PagedIterable inner + = this.serviceClient().listByResourceGroup(resourceGroupName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new AssessmentProjectImpl(inner1, this.manager())); + } + + public Response getByResourceGroupWithResponse(String resourceGroupName, String projectName, + Context context) { + Response inner + = this.serviceClient().getByResourceGroupWithResponse(resourceGroupName, projectName, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new AssessmentProjectImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public AssessmentProject getByResourceGroup(String resourceGroupName, String projectName) { + AssessmentProjectInner inner = this.serviceClient().getByResourceGroup(resourceGroupName, projectName); + if (inner != null) { + return new AssessmentProjectImpl(inner, this.manager()); + } else { + return null; + } + } + + public Response deleteByResourceGroupWithResponse(String resourceGroupName, String projectName, + Context context) { + return this.serviceClient().deleteWithResponse(resourceGroupName, projectName, context); + } + + public void deleteByResourceGroup(String resourceGroupName, String projectName) { + this.serviceClient().delete(resourceGroupName, projectName); + } + + public AssessmentProject getById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + return this.getByResourceGroupWithResponse(resourceGroupName, projectName, Context.NONE).getValue(); + } + + public Response getByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + return this.getByResourceGroupWithResponse(resourceGroupName, projectName, context); + } + + public void deleteById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + this.deleteByResourceGroupWithResponse(resourceGroupName, projectName, Context.NONE); + } + + public Response deleteByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + return this.deleteByResourceGroupWithResponse(resourceGroupName, projectName, context); + } + + private AssessmentProjectsOperationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } + + public AssessmentProjectImpl define(String name) { + return new AssessmentProjectImpl(name, this.manager()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentsOperationsClientImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentsOperationsClientImpl.java new file mode 100644 index 000000000000..2c3a04d9f5cf --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentsOperationsClientImpl.java @@ -0,0 +1,1177 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Post; +import com.azure.core.annotation.Put; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.core.util.polling.PollerFlux; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.migration.assessment.fluent.AssessmentsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentInner; +import com.azure.resourcemanager.migration.assessment.fluent.models.DownloadUrlInner; +import com.azure.resourcemanager.migration.assessment.models.AssessmentListResult; +import java.nio.ByteBuffer; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in AssessmentsOperationsClient. + */ +public final class AssessmentsOperationsClientImpl implements AssessmentsOperationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final AssessmentsOperationsService service; + + /** + * The service client containing this operation class. + */ + private final MigrationAssessmentManagementClientImpl client; + + /** + * Initializes an instance of AssessmentsOperationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + AssessmentsOperationsClientImpl(MigrationAssessmentManagementClientImpl client) { + this.service = RestProxy.create(AssessmentsOperationsService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for MigrationAssessmentManagementClientAssessmentsOperations to be used + * by the proxy service to perform REST calls. + */ + @Host("{$host}") + @ServiceInterface(name = "MigrationAssessmentM") + public interface AssessmentsOperationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/assessments") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByGroup(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/assessments/{assessmentName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @PathParam("assessmentName") String assessmentName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Put("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/assessments/{assessmentName}") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> create(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @PathParam("assessmentName") String assessmentName, + @BodyParam("application/json") AssessmentInner resource, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Delete("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/assessments/{assessmentName}") + @ExpectedResponses({ 200, 204 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> delete(@HostParam("$host") String endpoint, @QueryParam("api-version") String apiVersion, + @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @PathParam("assessmentName") String assessmentName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Post("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/assessments/{assessmentName}/downloadUrl") + @ExpectedResponses({ 200, 202 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> downloadUrl(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @PathParam("assessmentName") String assessmentName, + @BodyParam("application/json") Object body, @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByGroupNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * List Assessment resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Assessment list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByGroupSinglePageAsync(String resourceGroupName, + String projectName, String groupName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listByGroup(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), + res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List Assessment resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Assessment list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByGroupSinglePageAsync(String resourceGroupName, + String projectName, String groupName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByGroup(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, groupName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List Assessment resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Assessment list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByGroupAsync(String resourceGroupName, String projectName, + String groupName) { + return new PagedFlux<>(() -> listByGroupSinglePageAsync(resourceGroupName, projectName, groupName), + nextLink -> listByGroupNextSinglePageAsync(nextLink)); + } + + /** + * List Assessment resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Assessment list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByGroupAsync(String resourceGroupName, String projectName, String groupName, + Context context) { + return new PagedFlux<>(() -> listByGroupSinglePageAsync(resourceGroupName, projectName, groupName, context), + nextLink -> listByGroupNextSinglePageAsync(nextLink, context)); + } + + /** + * List Assessment resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Assessment list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByGroup(String resourceGroupName, String projectName, String groupName) { + return new PagedIterable<>(listByGroupAsync(resourceGroupName, projectName, groupName)); + } + + /** + * List Assessment resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Assessment list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByGroup(String resourceGroupName, String projectName, String groupName, + Context context) { + return new PagedIterable<>(listByGroupAsync(resourceGroupName, projectName, groupName, context)); + } + + /** + * Get a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Assessment along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, assessmentName, accept, + context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Assessment along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, groupName, assessmentName, accept, context); + } + + /** + * Get a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Assessment on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName) { + return getWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Assessment along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, Context context) { + return getWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, context).block(); + } + + /** + * Get a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Assessment. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public AssessmentInner get(String resourceGroupName, String projectName, String groupName, String assessmentName) { + return getWithResponse(resourceGroupName, projectName, groupName, assessmentName, Context.NONE).getValue(); + } + + /** + * Create a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return machine assessment resource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createWithResponseAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName, AssessmentInner resource) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.create(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, assessmentName, resource, + accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Create a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return machine assessment resource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createWithResponseAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName, AssessmentInner resource, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.create(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, groupName, assessmentName, resource, accept, context); + } + + /** + * Create a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of machine assessment resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, AssessmentInner> beginCreateAsync(String resourceGroupName, + String projectName, String groupName, String assessmentName, AssessmentInner resource) { + Mono>> mono + = createWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, resource); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + AssessmentInner.class, AssessmentInner.class, this.client.getContext()); + } + + /** + * Create a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of machine assessment resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, AssessmentInner> beginCreateAsync(String resourceGroupName, + String projectName, String groupName, String assessmentName, AssessmentInner resource, Context context) { + context = this.client.mergeContext(context); + Mono>> mono + = createWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, resource, context); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + AssessmentInner.class, AssessmentInner.class, context); + } + + /** + * Create a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of machine assessment resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, AssessmentInner> beginCreate(String resourceGroupName, + String projectName, String groupName, String assessmentName, AssessmentInner resource) { + return this.beginCreateAsync(resourceGroupName, projectName, groupName, assessmentName, resource) + .getSyncPoller(); + } + + /** + * Create a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of machine assessment resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, AssessmentInner> beginCreate(String resourceGroupName, + String projectName, String groupName, String assessmentName, AssessmentInner resource, Context context) { + return this.beginCreateAsync(resourceGroupName, projectName, groupName, assessmentName, resource, context) + .getSyncPoller(); + } + + /** + * Create a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return machine assessment resource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName, AssessmentInner resource) { + return beginCreateAsync(resourceGroupName, projectName, groupName, assessmentName, resource).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return machine assessment resource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName, AssessmentInner resource, Context context) { + return beginCreateAsync(resourceGroupName, projectName, groupName, assessmentName, resource, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return machine assessment resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public AssessmentInner create(String resourceGroupName, String projectName, String groupName, String assessmentName, + AssessmentInner resource) { + return createAsync(resourceGroupName, projectName, groupName, assessmentName, resource).block(); + } + + /** + * Create a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return machine assessment resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public AssessmentInner create(String resourceGroupName, String projectName, String groupName, String assessmentName, + AssessmentInner resource, Context context) { + return createAsync(resourceGroupName, projectName, groupName, assessmentName, resource, context).block(); + } + + /** + * Delete a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.delete(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, assessmentName, accept, + context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Delete a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.delete(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, groupName, assessmentName, accept, context); + } + + /** + * Delete a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono deleteAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName) { + return deleteWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName) + .flatMap(ignored -> Mono.empty()); + } + + /** + * Delete a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, Context context) { + return deleteWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, context).block(); + } + + /** + * Delete a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String resourceGroupName, String projectName, String groupName, String assessmentName) { + deleteWithResponse(resourceGroupName, projectName, groupName, assessmentName, Context.NONE); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format along with {@link Response} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> downloadUrlWithResponseAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName, Object body) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + if (body == null) { + return Mono.error(new IllegalArgumentException("Parameter body is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.downloadUrl(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, assessmentName, body, + accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format along with {@link Response} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> downloadUrlWithResponseAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName, Object body, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + if (body == null) { + return Mono.error(new IllegalArgumentException("Parameter body is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.downloadUrl(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, assessmentName, body, accept, + context); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, DownloadUrlInner> beginDownloadUrlAsync(String resourceGroupName, + String projectName, String groupName, String assessmentName, Object body) { + Mono>> mono + = downloadUrlWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, body); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + DownloadUrlInner.class, DownloadUrlInner.class, this.client.getContext()); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, DownloadUrlInner> beginDownloadUrlAsync(String resourceGroupName, + String projectName, String groupName, String assessmentName, Object body, Context context) { + context = this.client.mergeContext(context); + Mono>> mono + = downloadUrlWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, body, context); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + DownloadUrlInner.class, DownloadUrlInner.class, context); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, DownloadUrlInner> beginDownloadUrl(String resourceGroupName, + String projectName, String groupName, String assessmentName, Object body) { + return this.beginDownloadUrlAsync(resourceGroupName, projectName, groupName, assessmentName, body) + .getSyncPoller(); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, DownloadUrlInner> beginDownloadUrl(String resourceGroupName, + String projectName, String groupName, String assessmentName, Object body, Context context) { + return this.beginDownloadUrlAsync(resourceGroupName, projectName, groupName, assessmentName, body, context) + .getSyncPoller(); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono downloadUrlAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName, Object body) { + return beginDownloadUrlAsync(resourceGroupName, projectName, groupName, assessmentName, body).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono downloadUrlAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName, Object body, Context context) { + return beginDownloadUrlAsync(resourceGroupName, projectName, groupName, assessmentName, body, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public DownloadUrlInner downloadUrl(String resourceGroupName, String projectName, String groupName, + String assessmentName, Object body) { + return downloadUrlAsync(resourceGroupName, projectName, groupName, assessmentName, body).block(); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public DownloadUrlInner downloadUrl(String resourceGroupName, String projectName, String groupName, + String assessmentName, Object body, Context context) { + return downloadUrlAsync(resourceGroupName, projectName, groupName, assessmentName, body, context).block(); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Assessment list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByGroupNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listByGroupNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), + res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Assessment list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByGroupNextSinglePageAsync(String nextLink, Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listByGroupNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentsOperationsImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentsOperationsImpl.java new file mode 100644 index 000000000000..0cd9f8d900a6 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AssessmentsOperationsImpl.java @@ -0,0 +1,205 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.migration.assessment.fluent.AssessmentsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentInner; +import com.azure.resourcemanager.migration.assessment.fluent.models.DownloadUrlInner; +import com.azure.resourcemanager.migration.assessment.models.Assessment; +import com.azure.resourcemanager.migration.assessment.models.AssessmentsOperations; +import com.azure.resourcemanager.migration.assessment.models.DownloadUrl; + +public final class AssessmentsOperationsImpl implements AssessmentsOperations { + private static final ClientLogger LOGGER = new ClientLogger(AssessmentsOperationsImpl.class); + + private final AssessmentsOperationsClient innerClient; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + public AssessmentsOperationsImpl(AssessmentsOperationsClient innerClient, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public PagedIterable listByGroup(String resourceGroupName, String projectName, String groupName) { + PagedIterable inner + = this.serviceClient().listByGroup(resourceGroupName, projectName, groupName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new AssessmentImpl(inner1, this.manager())); + } + + public PagedIterable listByGroup(String resourceGroupName, String projectName, String groupName, + Context context) { + PagedIterable inner + = this.serviceClient().listByGroup(resourceGroupName, projectName, groupName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new AssessmentImpl(inner1, this.manager())); + } + + public Response getWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, Context context) { + Response inner + = this.serviceClient().getWithResponse(resourceGroupName, projectName, groupName, assessmentName, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new AssessmentImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public Assessment get(String resourceGroupName, String projectName, String groupName, String assessmentName) { + AssessmentInner inner = this.serviceClient().get(resourceGroupName, projectName, groupName, assessmentName); + if (inner != null) { + return new AssessmentImpl(inner, this.manager()); + } else { + return null; + } + } + + public Response deleteWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, Context context) { + return this.serviceClient() + .deleteWithResponse(resourceGroupName, projectName, groupName, assessmentName, context); + } + + public void delete(String resourceGroupName, String projectName, String groupName, String assessmentName) { + this.serviceClient().delete(resourceGroupName, projectName, groupName, assessmentName); + } + + public DownloadUrl downloadUrl(String resourceGroupName, String projectName, String groupName, + String assessmentName, Object body) { + DownloadUrlInner inner + = this.serviceClient().downloadUrl(resourceGroupName, projectName, groupName, assessmentName, body); + if (inner != null) { + return new DownloadUrlImpl(inner, this.manager()); + } else { + return null; + } + } + + public DownloadUrl downloadUrl(String resourceGroupName, String projectName, String groupName, + String assessmentName, Object body, Context context) { + DownloadUrlInner inner = this.serviceClient() + .downloadUrl(resourceGroupName, projectName, groupName, assessmentName, body, context); + if (inner != null) { + return new DownloadUrlImpl(inner, this.manager()); + } else { + return null; + } + } + + public Assessment getById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String groupName = ResourceManagerUtils.getValueFromIdByName(id, "groups"); + if (groupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'groups'.", id))); + } + String assessmentName = ResourceManagerUtils.getValueFromIdByName(id, "assessments"); + if (assessmentName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessments'.", id))); + } + return this.getWithResponse(resourceGroupName, projectName, groupName, assessmentName, Context.NONE).getValue(); + } + + public Response getByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String groupName = ResourceManagerUtils.getValueFromIdByName(id, "groups"); + if (groupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'groups'.", id))); + } + String assessmentName = ResourceManagerUtils.getValueFromIdByName(id, "assessments"); + if (assessmentName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessments'.", id))); + } + return this.getWithResponse(resourceGroupName, projectName, groupName, assessmentName, context); + } + + public void deleteById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String groupName = ResourceManagerUtils.getValueFromIdByName(id, "groups"); + if (groupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'groups'.", id))); + } + String assessmentName = ResourceManagerUtils.getValueFromIdByName(id, "assessments"); + if (assessmentName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessments'.", id))); + } + this.deleteWithResponse(resourceGroupName, projectName, groupName, assessmentName, Context.NONE); + } + + public Response deleteByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String groupName = ResourceManagerUtils.getValueFromIdByName(id, "groups"); + if (groupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'groups'.", id))); + } + String assessmentName = ResourceManagerUtils.getValueFromIdByName(id, "assessments"); + if (assessmentName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessments'.", id))); + } + return this.deleteWithResponse(resourceGroupName, projectName, groupName, assessmentName, context); + } + + private AssessmentsOperationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } + + public AssessmentImpl define(String name) { + return new AssessmentImpl(name, this.manager()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AvsAssessedMachineImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AvsAssessedMachineImpl.java new file mode 100644 index 000000000000..2b08ddca045f --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AvsAssessedMachineImpl.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AvsAssessedMachineInner; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessedMachine; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessedMachineProperties; + +public final class AvsAssessedMachineImpl implements AvsAssessedMachine { + private AvsAssessedMachineInner innerObject; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + AvsAssessedMachineImpl(AvsAssessedMachineInner innerObject, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public AvsAssessedMachineProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public AvsAssessedMachineInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AvsAssessedMachinesOperationsClientImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AvsAssessedMachinesOperationsClientImpl.java new file mode 100644 index 000000000000..0d1198782cc6 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AvsAssessedMachinesOperationsClientImpl.java @@ -0,0 +1,541 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.resourcemanager.migration.assessment.fluent.AvsAssessedMachinesOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.AvsAssessedMachineInner; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessedMachineListResult; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in AvsAssessedMachinesOperationsClient. + */ +public final class AvsAssessedMachinesOperationsClientImpl implements AvsAssessedMachinesOperationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final AvsAssessedMachinesOperationsService service; + + /** + * The service client containing this operation class. + */ + private final MigrationAssessmentManagementClientImpl client; + + /** + * Initializes an instance of AvsAssessedMachinesOperationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + AvsAssessedMachinesOperationsClientImpl(MigrationAssessmentManagementClientImpl client) { + this.service = RestProxy.create(AvsAssessedMachinesOperationsService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for MigrationAssessmentManagementClientAvsAssessedMachinesOperations to + * be used by the proxy service to perform REST calls. + */ + @Host("{$host}") + @ServiceInterface(name = "MigrationAssessmentM") + public interface AvsAssessedMachinesOperationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/avsAssessments/{assessmentName}/avsAssessedMachines") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAvsAssessment(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @QueryParam("$filter") String filter, + @QueryParam("pageSize") Integer pageSize, @QueryParam("continuationToken") String continuationToken, + @QueryParam("totalRecordCount") Integer totalRecordCount, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @PathParam("assessmentName") String assessmentName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/avsAssessments/{assessmentName}/avsAssessedMachines/{avsAssessedMachineName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @PathParam("assessmentName") String assessmentName, + @PathParam("avsAssessedMachineName") String avsAssessedMachineName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAvsAssessmentNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * List AvsAssessedMachine resources by AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessedMachine list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAvsAssessmentSinglePageAsync(String resourceGroupName, + String projectName, String groupName, String assessmentName, String filter, Integer pageSize, + String continuationToken, Integer totalRecordCount) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listByAvsAssessment(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, filter, pageSize, continuationToken, + totalRecordCount, projectName, groupName, assessmentName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List AvsAssessedMachine resources by AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessedMachine list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAvsAssessmentSinglePageAsync(String resourceGroupName, + String projectName, String groupName, String assessmentName, String filter, Integer pageSize, + String continuationToken, Integer totalRecordCount, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByAvsAssessment(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, filter, pageSize, continuationToken, + totalRecordCount, projectName, groupName, assessmentName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List AvsAssessedMachine resources by AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessedMachine list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAvsAssessmentAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName, String filter, Integer pageSize, String continuationToken, + Integer totalRecordCount) { + return new PagedFlux<>( + () -> listByAvsAssessmentSinglePageAsync(resourceGroupName, projectName, groupName, assessmentName, filter, + pageSize, continuationToken, totalRecordCount), + nextLink -> listByAvsAssessmentNextSinglePageAsync(nextLink)); + } + + /** + * List AvsAssessedMachine resources by AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessedMachine list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAvsAssessmentAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName) { + final String filter = null; + final Integer pageSize = null; + final String continuationToken = null; + final Integer totalRecordCount = null; + return new PagedFlux<>( + () -> listByAvsAssessmentSinglePageAsync(resourceGroupName, projectName, groupName, assessmentName, filter, + pageSize, continuationToken, totalRecordCount), + nextLink -> listByAvsAssessmentNextSinglePageAsync(nextLink)); + } + + /** + * List AvsAssessedMachine resources by AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessedMachine list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAvsAssessmentAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName, String filter, Integer pageSize, String continuationToken, + Integer totalRecordCount, Context context) { + return new PagedFlux<>( + () -> listByAvsAssessmentSinglePageAsync(resourceGroupName, projectName, groupName, assessmentName, filter, + pageSize, continuationToken, totalRecordCount, context), + nextLink -> listByAvsAssessmentNextSinglePageAsync(nextLink, context)); + } + + /** + * List AvsAssessedMachine resources by AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessedMachine list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAvsAssessment(String resourceGroupName, String projectName, + String groupName, String assessmentName) { + final String filter = null; + final Integer pageSize = null; + final String continuationToken = null; + final Integer totalRecordCount = null; + return new PagedIterable<>(listByAvsAssessmentAsync(resourceGroupName, projectName, groupName, assessmentName, + filter, pageSize, continuationToken, totalRecordCount)); + } + + /** + * List AvsAssessedMachine resources by AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessedMachine list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAvsAssessment(String resourceGroupName, String projectName, + String groupName, String assessmentName, String filter, Integer pageSize, String continuationToken, + Integer totalRecordCount, Context context) { + return new PagedIterable<>(listByAvsAssessmentAsync(resourceGroupName, projectName, groupName, assessmentName, + filter, pageSize, continuationToken, totalRecordCount, context)); + } + + /** + * Get a AvsAssessedMachine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param avsAssessedMachineName AVS assessment Assessed Machine ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AvsAssessedMachine along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName, String avsAssessedMachineName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + if (avsAssessedMachineName == null) { + return Mono.error( + new IllegalArgumentException("Parameter avsAssessedMachineName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, assessmentName, + avsAssessedMachineName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a AvsAssessedMachine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param avsAssessedMachineName AVS assessment Assessed Machine ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AvsAssessedMachine along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName, String avsAssessedMachineName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + if (avsAssessedMachineName == null) { + return Mono.error( + new IllegalArgumentException("Parameter avsAssessedMachineName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, groupName, assessmentName, avsAssessedMachineName, accept, context); + } + + /** + * Get a AvsAssessedMachine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param avsAssessedMachineName AVS assessment Assessed Machine ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AvsAssessedMachine on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName, String avsAssessedMachineName) { + return getWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, avsAssessedMachineName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a AvsAssessedMachine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param avsAssessedMachineName AVS assessment Assessed Machine ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AvsAssessedMachine along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceGroupName, String projectName, + String groupName, String assessmentName, String avsAssessedMachineName, Context context) { + return getWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, avsAssessedMachineName, + context).block(); + } + + /** + * Get a AvsAssessedMachine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param avsAssessedMachineName AVS assessment Assessed Machine ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AvsAssessedMachine. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public AvsAssessedMachineInner get(String resourceGroupName, String projectName, String groupName, + String assessmentName, String avsAssessedMachineName) { + return getWithResponse(resourceGroupName, projectName, groupName, assessmentName, avsAssessedMachineName, + Context.NONE).getValue(); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessedMachine list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAvsAssessmentNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByAvsAssessmentNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessedMachine list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAvsAssessmentNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listByAvsAssessmentNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AvsAssessedMachinesOperationsImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AvsAssessedMachinesOperationsImpl.java new file mode 100644 index 000000000000..4132ced59d4a --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AvsAssessedMachinesOperationsImpl.java @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.migration.assessment.fluent.AvsAssessedMachinesOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.AvsAssessedMachineInner; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessedMachine; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessedMachinesOperations; + +public final class AvsAssessedMachinesOperationsImpl implements AvsAssessedMachinesOperations { + private static final ClientLogger LOGGER = new ClientLogger(AvsAssessedMachinesOperationsImpl.class); + + private final AvsAssessedMachinesOperationsClient innerClient; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + public AvsAssessedMachinesOperationsImpl(AvsAssessedMachinesOperationsClient innerClient, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public PagedIterable listByAvsAssessment(String resourceGroupName, String projectName, + String groupName, String assessmentName) { + PagedIterable inner + = this.serviceClient().listByAvsAssessment(resourceGroupName, projectName, groupName, assessmentName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new AvsAssessedMachineImpl(inner1, this.manager())); + } + + public PagedIterable listByAvsAssessment(String resourceGroupName, String projectName, + String groupName, String assessmentName, String filter, Integer pageSize, String continuationToken, + Integer totalRecordCount, Context context) { + PagedIterable inner = this.serviceClient() + .listByAvsAssessment(resourceGroupName, projectName, groupName, assessmentName, filter, pageSize, + continuationToken, totalRecordCount, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new AvsAssessedMachineImpl(inner1, this.manager())); + } + + public Response getWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, String avsAssessedMachineName, Context context) { + Response inner = this.serviceClient() + .getWithResponse(resourceGroupName, projectName, groupName, assessmentName, avsAssessedMachineName, + context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new AvsAssessedMachineImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public AvsAssessedMachine get(String resourceGroupName, String projectName, String groupName, String assessmentName, + String avsAssessedMachineName) { + AvsAssessedMachineInner inner = this.serviceClient() + .get(resourceGroupName, projectName, groupName, assessmentName, avsAssessedMachineName); + if (inner != null) { + return new AvsAssessedMachineImpl(inner, this.manager()); + } else { + return null; + } + } + + private AvsAssessedMachinesOperationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AvsAssessmentImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AvsAssessmentImpl.java new file mode 100644 index 000000000000..e8ab52e4f9ad --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AvsAssessmentImpl.java @@ -0,0 +1,119 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.AvsAssessmentInner; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessment; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessmentProperties; +import com.azure.resourcemanager.migration.assessment.models.DownloadUrl; + +public final class AvsAssessmentImpl implements AvsAssessment, AvsAssessment.Definition { + private AvsAssessmentInner innerObject; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + AvsAssessmentImpl(AvsAssessmentInner innerObject, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public AvsAssessmentProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public AvsAssessmentInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } + + private String resourceGroupName; + + private String projectName; + + private String groupName; + + private String assessmentName; + + public AvsAssessmentImpl withExistingGroup(String resourceGroupName, String projectName, String groupName) { + this.resourceGroupName = resourceGroupName; + this.projectName = projectName; + this.groupName = groupName; + return this; + } + + public AvsAssessment create() { + this.innerObject = serviceManager.serviceClient() + .getAvsAssessmentsOperations() + .create(resourceGroupName, projectName, groupName, assessmentName, this.innerModel(), Context.NONE); + return this; + } + + public AvsAssessment create(Context context) { + this.innerObject = serviceManager.serviceClient() + .getAvsAssessmentsOperations() + .create(resourceGroupName, projectName, groupName, assessmentName, this.innerModel(), context); + return this; + } + + AvsAssessmentImpl(String name, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = new AvsAssessmentInner(); + this.serviceManager = serviceManager; + this.assessmentName = name; + } + + public AvsAssessment refresh() { + this.innerObject = serviceManager.serviceClient() + .getAvsAssessmentsOperations() + .getWithResponse(resourceGroupName, projectName, groupName, assessmentName, Context.NONE) + .getValue(); + return this; + } + + public AvsAssessment refresh(Context context) { + this.innerObject = serviceManager.serviceClient() + .getAvsAssessmentsOperations() + .getWithResponse(resourceGroupName, projectName, groupName, assessmentName, context) + .getValue(); + return this; + } + + public DownloadUrl downloadUrl(Object body) { + return serviceManager.avsAssessmentsOperations() + .downloadUrl(resourceGroupName, projectName, groupName, assessmentName, body); + } + + public DownloadUrl downloadUrl(Object body, Context context) { + return serviceManager.avsAssessmentsOperations() + .downloadUrl(resourceGroupName, projectName, groupName, assessmentName, body, context); + } + + public AvsAssessmentImpl withProperties(AvsAssessmentProperties properties) { + this.innerModel().withProperties(properties); + return this; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AvsAssessmentOptionsImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AvsAssessmentOptionsImpl.java new file mode 100644 index 000000000000..5e49b4d51a43 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AvsAssessmentOptionsImpl.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AvsAssessmentOptionsInner; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessmentOptions; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessmentOptionsProperties; + +public final class AvsAssessmentOptionsImpl implements AvsAssessmentOptions { + private AvsAssessmentOptionsInner innerObject; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + AvsAssessmentOptionsImpl(AvsAssessmentOptionsInner innerObject, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public AvsAssessmentOptionsProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public AvsAssessmentOptionsInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AvsAssessmentOptionsOperationsClientImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AvsAssessmentOptionsOperationsClientImpl.java new file mode 100644 index 000000000000..d2669de8699a --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AvsAssessmentOptionsOperationsClientImpl.java @@ -0,0 +1,426 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.resourcemanager.migration.assessment.fluent.AvsAssessmentOptionsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.AvsAssessmentOptionsInner; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessmentOptionsListResult; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in AvsAssessmentOptionsOperationsClient. + */ +public final class AvsAssessmentOptionsOperationsClientImpl implements AvsAssessmentOptionsOperationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final AvsAssessmentOptionsOperationsService service; + + /** + * The service client containing this operation class. + */ + private final MigrationAssessmentManagementClientImpl client; + + /** + * Initializes an instance of AvsAssessmentOptionsOperationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + AvsAssessmentOptionsOperationsClientImpl(MigrationAssessmentManagementClientImpl client) { + this.service = RestProxy.create(AvsAssessmentOptionsOperationsService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for MigrationAssessmentManagementClientAvsAssessmentOptionsOperations to + * be used by the proxy service to perform REST calls. + */ + @Host("{$host}") + @ServiceInterface(name = "MigrationAssessmentM") + public interface AvsAssessmentOptionsOperationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/avsAssessmentOptions") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAssessmentProject(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/avsAssessmentOptions/{avsAssessmentOptionsName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("avsAssessmentOptionsName") String avsAssessmentOptionsName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAssessmentProjectNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * List AvsAssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessmentOptions list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> + listByAssessmentProjectSinglePageAsync(String resourceGroupName, String projectName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByAssessmentProject(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List AvsAssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessmentOptions list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> + listByAssessmentProjectSinglePageAsync(String resourceGroupName, String projectName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByAssessmentProject(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List AvsAssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessmentOptions list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentProjectAsync(String resourceGroupName, + String projectName) { + return new PagedFlux<>(() -> listByAssessmentProjectSinglePageAsync(resourceGroupName, projectName), + nextLink -> listByAssessmentProjectNextSinglePageAsync(nextLink)); + } + + /** + * List AvsAssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessmentOptions list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentProjectAsync(String resourceGroupName, + String projectName, Context context) { + return new PagedFlux<>(() -> listByAssessmentProjectSinglePageAsync(resourceGroupName, projectName, context), + nextLink -> listByAssessmentProjectNextSinglePageAsync(nextLink, context)); + } + + /** + * List AvsAssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessmentOptions list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAssessmentProject(String resourceGroupName, + String projectName) { + return new PagedIterable<>(listByAssessmentProjectAsync(resourceGroupName, projectName)); + } + + /** + * List AvsAssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessmentOptions list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAssessmentProject(String resourceGroupName, + String projectName, Context context) { + return new PagedIterable<>(listByAssessmentProjectAsync(resourceGroupName, projectName, context)); + } + + /** + * Get a AvsAssessmentOptions. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param avsAssessmentOptionsName AVS Assessment options ARM name. Accepted value is 'default'. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AvsAssessmentOptions along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String avsAssessmentOptionsName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (avsAssessmentOptionsName == null) { + return Mono.error( + new IllegalArgumentException("Parameter avsAssessmentOptionsName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, avsAssessmentOptionsName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a AvsAssessmentOptions. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param avsAssessmentOptionsName AVS Assessment options ARM name. Accepted value is 'default'. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AvsAssessmentOptions along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String avsAssessmentOptionsName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (avsAssessmentOptionsName == null) { + return Mono.error( + new IllegalArgumentException("Parameter avsAssessmentOptionsName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, avsAssessmentOptionsName, accept, context); + } + + /** + * Get a AvsAssessmentOptions. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param avsAssessmentOptionsName AVS Assessment options ARM name. Accepted value is 'default'. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AvsAssessmentOptions on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceGroupName, String projectName, + String avsAssessmentOptionsName) { + return getWithResponseAsync(resourceGroupName, projectName, avsAssessmentOptionsName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a AvsAssessmentOptions. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param avsAssessmentOptionsName AVS Assessment options ARM name. Accepted value is 'default'. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AvsAssessmentOptions along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceGroupName, String projectName, + String avsAssessmentOptionsName, Context context) { + return getWithResponseAsync(resourceGroupName, projectName, avsAssessmentOptionsName, context).block(); + } + + /** + * Get a AvsAssessmentOptions. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param avsAssessmentOptionsName AVS Assessment options ARM name. Accepted value is 'default'. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AvsAssessmentOptions. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public AvsAssessmentOptionsInner get(String resourceGroupName, String projectName, + String avsAssessmentOptionsName) { + return getWithResponse(resourceGroupName, projectName, avsAssessmentOptionsName, Context.NONE).getValue(); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessmentOptions list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByAssessmentProjectNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessmentOptions list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listByAssessmentProjectNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AvsAssessmentOptionsOperationsImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AvsAssessmentOptionsOperationsImpl.java new file mode 100644 index 000000000000..e055c8b717e7 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AvsAssessmentOptionsOperationsImpl.java @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.migration.assessment.fluent.AvsAssessmentOptionsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.AvsAssessmentOptionsInner; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessmentOptions; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessmentOptionsOperations; + +public final class AvsAssessmentOptionsOperationsImpl implements AvsAssessmentOptionsOperations { + private static final ClientLogger LOGGER = new ClientLogger(AvsAssessmentOptionsOperationsImpl.class); + + private final AvsAssessmentOptionsOperationsClient innerClient; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + public AvsAssessmentOptionsOperationsImpl(AvsAssessmentOptionsOperationsClient innerClient, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName) { + PagedIterable inner + = this.serviceClient().listByAssessmentProject(resourceGroupName, projectName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new AvsAssessmentOptionsImpl(inner1, this.manager())); + } + + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context) { + PagedIterable inner + = this.serviceClient().listByAssessmentProject(resourceGroupName, projectName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new AvsAssessmentOptionsImpl(inner1, this.manager())); + } + + public Response getWithResponse(String resourceGroupName, String projectName, + String avsAssessmentOptionsName, Context context) { + Response inner + = this.serviceClient().getWithResponse(resourceGroupName, projectName, avsAssessmentOptionsName, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new AvsAssessmentOptionsImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public AvsAssessmentOptions get(String resourceGroupName, String projectName, String avsAssessmentOptionsName) { + AvsAssessmentOptionsInner inner + = this.serviceClient().get(resourceGroupName, projectName, avsAssessmentOptionsName); + if (inner != null) { + return new AvsAssessmentOptionsImpl(inner, this.manager()); + } else { + return null; + } + } + + private AvsAssessmentOptionsOperationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AvsAssessmentsOperationsClientImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AvsAssessmentsOperationsClientImpl.java new file mode 100644 index 000000000000..f0246ce5ab3d --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AvsAssessmentsOperationsClientImpl.java @@ -0,0 +1,1179 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Post; +import com.azure.core.annotation.Put; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.core.util.polling.PollerFlux; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.migration.assessment.fluent.AvsAssessmentsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.AvsAssessmentInner; +import com.azure.resourcemanager.migration.assessment.fluent.models.DownloadUrlInner; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessmentListResult; +import java.nio.ByteBuffer; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in AvsAssessmentsOperationsClient. + */ +public final class AvsAssessmentsOperationsClientImpl implements AvsAssessmentsOperationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final AvsAssessmentsOperationsService service; + + /** + * The service client containing this operation class. + */ + private final MigrationAssessmentManagementClientImpl client; + + /** + * Initializes an instance of AvsAssessmentsOperationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + AvsAssessmentsOperationsClientImpl(MigrationAssessmentManagementClientImpl client) { + this.service = RestProxy.create(AvsAssessmentsOperationsService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for MigrationAssessmentManagementClientAvsAssessmentsOperations to be + * used by the proxy service to perform REST calls. + */ + @Host("{$host}") + @ServiceInterface(name = "MigrationAssessmentM") + public interface AvsAssessmentsOperationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/avsAssessments") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByGroup(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/avsAssessments/{assessmentName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @PathParam("assessmentName") String assessmentName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Put("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/avsAssessments/{assessmentName}") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> create(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @PathParam("assessmentName") String assessmentName, + @BodyParam("application/json") AvsAssessmentInner resource, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Delete("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/avsAssessments/{assessmentName}") + @ExpectedResponses({ 200, 204 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> delete(@HostParam("$host") String endpoint, @QueryParam("api-version") String apiVersion, + @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @PathParam("assessmentName") String assessmentName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Post("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/avsAssessments/{assessmentName}/downloadUrl") + @ExpectedResponses({ 200, 202 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> downloadUrl(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @PathParam("assessmentName") String assessmentName, + @BodyParam("application/json") Object body, @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByGroupNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * List AvsAssessment resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessment list operation along with {@link PagedResponse} on successful completion + * of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByGroupSinglePageAsync(String resourceGroupName, + String projectName, String groupName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listByGroup(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List AvsAssessment resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessment list operation along with {@link PagedResponse} on successful completion + * of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByGroupSinglePageAsync(String resourceGroupName, + String projectName, String groupName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByGroup(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, groupName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List AvsAssessment resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessment list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByGroupAsync(String resourceGroupName, String projectName, + String groupName) { + return new PagedFlux<>(() -> listByGroupSinglePageAsync(resourceGroupName, projectName, groupName), + nextLink -> listByGroupNextSinglePageAsync(nextLink)); + } + + /** + * List AvsAssessment resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessment list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByGroupAsync(String resourceGroupName, String projectName, + String groupName, Context context) { + return new PagedFlux<>(() -> listByGroupSinglePageAsync(resourceGroupName, projectName, groupName, context), + nextLink -> listByGroupNextSinglePageAsync(nextLink, context)); + } + + /** + * List AvsAssessment resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessment list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByGroup(String resourceGroupName, String projectName, + String groupName) { + return new PagedIterable<>(listByGroupAsync(resourceGroupName, projectName, groupName)); + } + + /** + * List AvsAssessment resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessment list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByGroup(String resourceGroupName, String projectName, String groupName, + Context context) { + return new PagedIterable<>(listByGroupAsync(resourceGroupName, projectName, groupName, context)); + } + + /** + * Get a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AvsAssessment along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, assessmentName, accept, + context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AvsAssessment along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, groupName, assessmentName, accept, context); + } + + /** + * Get a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AvsAssessment on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName) { + return getWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AvsAssessment along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, Context context) { + return getWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, context).block(); + } + + /** + * Get a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AvsAssessment. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public AvsAssessmentInner get(String resourceGroupName, String projectName, String groupName, + String assessmentName) { + return getWithResponse(resourceGroupName, projectName, groupName, assessmentName, Context.NONE).getValue(); + } + + /** + * Create a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return aVS assessment resource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createWithResponseAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName, AvsAssessmentInner resource) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.create(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, assessmentName, resource, + accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Create a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return aVS assessment resource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createWithResponseAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName, AvsAssessmentInner resource, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.create(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, groupName, assessmentName, resource, accept, context); + } + + /** + * Create a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of aVS assessment resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, AvsAssessmentInner> beginCreateAsync(String resourceGroupName, + String projectName, String groupName, String assessmentName, AvsAssessmentInner resource) { + Mono>> mono + = createWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, resource); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + AvsAssessmentInner.class, AvsAssessmentInner.class, this.client.getContext()); + } + + /** + * Create a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of aVS assessment resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, AvsAssessmentInner> beginCreateAsync(String resourceGroupName, + String projectName, String groupName, String assessmentName, AvsAssessmentInner resource, Context context) { + context = this.client.mergeContext(context); + Mono>> mono + = createWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, resource, context); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + AvsAssessmentInner.class, AvsAssessmentInner.class, context); + } + + /** + * Create a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of aVS assessment resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, AvsAssessmentInner> beginCreate(String resourceGroupName, + String projectName, String groupName, String assessmentName, AvsAssessmentInner resource) { + return this.beginCreateAsync(resourceGroupName, projectName, groupName, assessmentName, resource) + .getSyncPoller(); + } + + /** + * Create a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of aVS assessment resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, AvsAssessmentInner> beginCreate(String resourceGroupName, + String projectName, String groupName, String assessmentName, AvsAssessmentInner resource, Context context) { + return this.beginCreateAsync(resourceGroupName, projectName, groupName, assessmentName, resource, context) + .getSyncPoller(); + } + + /** + * Create a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return aVS assessment resource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName, AvsAssessmentInner resource) { + return beginCreateAsync(resourceGroupName, projectName, groupName, assessmentName, resource).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return aVS assessment resource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName, AvsAssessmentInner resource, Context context) { + return beginCreateAsync(resourceGroupName, projectName, groupName, assessmentName, resource, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return aVS assessment resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public AvsAssessmentInner create(String resourceGroupName, String projectName, String groupName, + String assessmentName, AvsAssessmentInner resource) { + return createAsync(resourceGroupName, projectName, groupName, assessmentName, resource).block(); + } + + /** + * Create a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return aVS assessment resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public AvsAssessmentInner create(String resourceGroupName, String projectName, String groupName, + String assessmentName, AvsAssessmentInner resource, Context context) { + return createAsync(resourceGroupName, projectName, groupName, assessmentName, resource, context).block(); + } + + /** + * Delete a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.delete(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, assessmentName, accept, + context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Delete a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.delete(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, groupName, assessmentName, accept, context); + } + + /** + * Delete a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono deleteAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName) { + return deleteWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName) + .flatMap(ignored -> Mono.empty()); + } + + /** + * Delete a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, Context context) { + return deleteWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, context).block(); + } + + /** + * Delete a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String resourceGroupName, String projectName, String groupName, String assessmentName) { + deleteWithResponse(resourceGroupName, projectName, groupName, assessmentName, Context.NONE); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format along with {@link Response} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> downloadUrlWithResponseAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName, Object body) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + if (body == null) { + return Mono.error(new IllegalArgumentException("Parameter body is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.downloadUrl(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, assessmentName, body, + accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format along with {@link Response} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> downloadUrlWithResponseAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName, Object body, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + if (body == null) { + return Mono.error(new IllegalArgumentException("Parameter body is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.downloadUrl(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, assessmentName, body, accept, + context); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, DownloadUrlInner> beginDownloadUrlAsync(String resourceGroupName, + String projectName, String groupName, String assessmentName, Object body) { + Mono>> mono + = downloadUrlWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, body); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + DownloadUrlInner.class, DownloadUrlInner.class, this.client.getContext()); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, DownloadUrlInner> beginDownloadUrlAsync(String resourceGroupName, + String projectName, String groupName, String assessmentName, Object body, Context context) { + context = this.client.mergeContext(context); + Mono>> mono + = downloadUrlWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, body, context); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + DownloadUrlInner.class, DownloadUrlInner.class, context); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, DownloadUrlInner> beginDownloadUrl(String resourceGroupName, + String projectName, String groupName, String assessmentName, Object body) { + return this.beginDownloadUrlAsync(resourceGroupName, projectName, groupName, assessmentName, body) + .getSyncPoller(); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, DownloadUrlInner> beginDownloadUrl(String resourceGroupName, + String projectName, String groupName, String assessmentName, Object body, Context context) { + return this.beginDownloadUrlAsync(resourceGroupName, projectName, groupName, assessmentName, body, context) + .getSyncPoller(); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono downloadUrlAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName, Object body) { + return beginDownloadUrlAsync(resourceGroupName, projectName, groupName, assessmentName, body).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono downloadUrlAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName, Object body, Context context) { + return beginDownloadUrlAsync(resourceGroupName, projectName, groupName, assessmentName, body, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public DownloadUrlInner downloadUrl(String resourceGroupName, String projectName, String groupName, + String assessmentName, Object body) { + return downloadUrlAsync(resourceGroupName, projectName, groupName, assessmentName, body).block(); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public DownloadUrlInner downloadUrl(String resourceGroupName, String projectName, String groupName, + String assessmentName, Object body, Context context) { + return downloadUrlAsync(resourceGroupName, projectName, groupName, assessmentName, body, context).block(); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessment list operation along with {@link PagedResponse} on successful completion + * of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByGroupNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listByGroupNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessment list operation along with {@link PagedResponse} on successful completion + * of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByGroupNextSinglePageAsync(String nextLink, Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listByGroupNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AvsAssessmentsOperationsImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AvsAssessmentsOperationsImpl.java new file mode 100644 index 000000000000..6b94e0766eea --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/AvsAssessmentsOperationsImpl.java @@ -0,0 +1,205 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.migration.assessment.fluent.AvsAssessmentsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.AvsAssessmentInner; +import com.azure.resourcemanager.migration.assessment.fluent.models.DownloadUrlInner; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessment; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessmentsOperations; +import com.azure.resourcemanager.migration.assessment.models.DownloadUrl; + +public final class AvsAssessmentsOperationsImpl implements AvsAssessmentsOperations { + private static final ClientLogger LOGGER = new ClientLogger(AvsAssessmentsOperationsImpl.class); + + private final AvsAssessmentsOperationsClient innerClient; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + public AvsAssessmentsOperationsImpl(AvsAssessmentsOperationsClient innerClient, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public PagedIterable listByGroup(String resourceGroupName, String projectName, String groupName) { + PagedIterable inner + = this.serviceClient().listByGroup(resourceGroupName, projectName, groupName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new AvsAssessmentImpl(inner1, this.manager())); + } + + public PagedIterable listByGroup(String resourceGroupName, String projectName, String groupName, + Context context) { + PagedIterable inner + = this.serviceClient().listByGroup(resourceGroupName, projectName, groupName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new AvsAssessmentImpl(inner1, this.manager())); + } + + public Response getWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, Context context) { + Response inner + = this.serviceClient().getWithResponse(resourceGroupName, projectName, groupName, assessmentName, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new AvsAssessmentImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public AvsAssessment get(String resourceGroupName, String projectName, String groupName, String assessmentName) { + AvsAssessmentInner inner = this.serviceClient().get(resourceGroupName, projectName, groupName, assessmentName); + if (inner != null) { + return new AvsAssessmentImpl(inner, this.manager()); + } else { + return null; + } + } + + public Response deleteWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, Context context) { + return this.serviceClient() + .deleteWithResponse(resourceGroupName, projectName, groupName, assessmentName, context); + } + + public void delete(String resourceGroupName, String projectName, String groupName, String assessmentName) { + this.serviceClient().delete(resourceGroupName, projectName, groupName, assessmentName); + } + + public DownloadUrl downloadUrl(String resourceGroupName, String projectName, String groupName, + String assessmentName, Object body) { + DownloadUrlInner inner + = this.serviceClient().downloadUrl(resourceGroupName, projectName, groupName, assessmentName, body); + if (inner != null) { + return new DownloadUrlImpl(inner, this.manager()); + } else { + return null; + } + } + + public DownloadUrl downloadUrl(String resourceGroupName, String projectName, String groupName, + String assessmentName, Object body, Context context) { + DownloadUrlInner inner = this.serviceClient() + .downloadUrl(resourceGroupName, projectName, groupName, assessmentName, body, context); + if (inner != null) { + return new DownloadUrlImpl(inner, this.manager()); + } else { + return null; + } + } + + public AvsAssessment getById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String groupName = ResourceManagerUtils.getValueFromIdByName(id, "groups"); + if (groupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'groups'.", id))); + } + String assessmentName = ResourceManagerUtils.getValueFromIdByName(id, "avsAssessments"); + if (assessmentName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'avsAssessments'.", id))); + } + return this.getWithResponse(resourceGroupName, projectName, groupName, assessmentName, Context.NONE).getValue(); + } + + public Response getByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String groupName = ResourceManagerUtils.getValueFromIdByName(id, "groups"); + if (groupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'groups'.", id))); + } + String assessmentName = ResourceManagerUtils.getValueFromIdByName(id, "avsAssessments"); + if (assessmentName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'avsAssessments'.", id))); + } + return this.getWithResponse(resourceGroupName, projectName, groupName, assessmentName, context); + } + + public void deleteById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String groupName = ResourceManagerUtils.getValueFromIdByName(id, "groups"); + if (groupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'groups'.", id))); + } + String assessmentName = ResourceManagerUtils.getValueFromIdByName(id, "avsAssessments"); + if (assessmentName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'avsAssessments'.", id))); + } + this.deleteWithResponse(resourceGroupName, projectName, groupName, assessmentName, Context.NONE); + } + + public Response deleteByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String groupName = ResourceManagerUtils.getValueFromIdByName(id, "groups"); + if (groupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'groups'.", id))); + } + String assessmentName = ResourceManagerUtils.getValueFromIdByName(id, "avsAssessments"); + if (assessmentName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'avsAssessments'.", id))); + } + return this.deleteWithResponse(resourceGroupName, projectName, groupName, assessmentName, context); + } + + private AvsAssessmentsOperationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } + + public AvsAssessmentImpl define(String name) { + return new AvsAssessmentImpl(name, this.manager()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/DownloadUrlImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/DownloadUrlImpl.java new file mode 100644 index 000000000000..d979aba64f6f --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/DownloadUrlImpl.java @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.resourcemanager.migration.assessment.fluent.models.DownloadUrlInner; +import com.azure.resourcemanager.migration.assessment.models.DownloadUrl; +import java.time.OffsetDateTime; + +public final class DownloadUrlImpl implements DownloadUrl { + private DownloadUrlInner innerObject; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + DownloadUrlImpl(DownloadUrlInner innerObject, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String assessmentReportUrl() { + return this.innerModel().assessmentReportUrl(); + } + + public OffsetDateTime expirationTime() { + return this.innerModel().expirationTime(); + } + + public DownloadUrlInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/GroupImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/GroupImpl.java new file mode 100644 index 000000000000..3a65a90de1a6 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/GroupImpl.java @@ -0,0 +1,114 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.GroupInner; +import com.azure.resourcemanager.migration.assessment.models.Group; +import com.azure.resourcemanager.migration.assessment.models.GroupProperties; +import com.azure.resourcemanager.migration.assessment.models.UpdateGroupBody; + +public final class GroupImpl implements Group, Group.Definition { + private GroupInner innerObject; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + GroupImpl(GroupInner innerObject, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public GroupProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public GroupInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } + + private String resourceGroupName; + + private String projectName; + + private String groupName; + + public GroupImpl withExistingAssessmentProject(String resourceGroupName, String projectName) { + this.resourceGroupName = resourceGroupName; + this.projectName = projectName; + return this; + } + + public Group create() { + this.innerObject = serviceManager.serviceClient() + .getGroupsOperations() + .create(resourceGroupName, projectName, groupName, this.innerModel(), Context.NONE); + return this; + } + + public Group create(Context context) { + this.innerObject = serviceManager.serviceClient() + .getGroupsOperations() + .create(resourceGroupName, projectName, groupName, this.innerModel(), context); + return this; + } + + GroupImpl(String name, com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = new GroupInner(); + this.serviceManager = serviceManager; + this.groupName = name; + } + + public Group refresh() { + this.innerObject = serviceManager.serviceClient() + .getGroupsOperations() + .getWithResponse(resourceGroupName, projectName, groupName, Context.NONE) + .getValue(); + return this; + } + + public Group refresh(Context context) { + this.innerObject = serviceManager.serviceClient() + .getGroupsOperations() + .getWithResponse(resourceGroupName, projectName, groupName, context) + .getValue(); + return this; + } + + public Group updateMachines(UpdateGroupBody body) { + return serviceManager.groupsOperations().updateMachines(resourceGroupName, projectName, groupName, body); + } + + public Group updateMachines(UpdateGroupBody body, Context context) { + return serviceManager.groupsOperations() + .updateMachines(resourceGroupName, projectName, groupName, body, context); + } + + public GroupImpl withProperties(GroupProperties properties) { + this.innerModel().withProperties(properties); + return this; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/GroupsOperationsClientImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/GroupsOperationsClientImpl.java new file mode 100644 index 000000000000..cbf5d2413046 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/GroupsOperationsClientImpl.java @@ -0,0 +1,1099 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Post; +import com.azure.core.annotation.Put; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.core.util.polling.PollerFlux; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.migration.assessment.fluent.GroupsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.GroupInner; +import com.azure.resourcemanager.migration.assessment.models.GroupListResult; +import com.azure.resourcemanager.migration.assessment.models.UpdateGroupBody; +import java.nio.ByteBuffer; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in GroupsOperationsClient. + */ +public final class GroupsOperationsClientImpl implements GroupsOperationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final GroupsOperationsService service; + + /** + * The service client containing this operation class. + */ + private final MigrationAssessmentManagementClientImpl client; + + /** + * Initializes an instance of GroupsOperationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + GroupsOperationsClientImpl(MigrationAssessmentManagementClientImpl client) { + this.service + = RestProxy.create(GroupsOperationsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for MigrationAssessmentManagementClientGroupsOperations to be used by the + * proxy service to perform REST calls. + */ + @Host("{$host}") + @ServiceInterface(name = "MigrationAssessmentM") + public interface GroupsOperationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAssessmentProject(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Put("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> create(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @BodyParam("application/json") GroupInner resource, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Delete("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}") + @ExpectedResponses({ 200, 204 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> delete(@HostParam("$host") String endpoint, @QueryParam("api-version") String apiVersion, + @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Post("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/updateMachines") + @ExpectedResponses({ 200, 202 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> updateMachines(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @BodyParam("application/json") UpdateGroupBody body, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAssessmentProjectNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * List Group resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Group list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectSinglePageAsync(String resourceGroupName, + String projectName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByAssessmentProject(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), + res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List Group resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Group list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectSinglePageAsync(String resourceGroupName, + String projectName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByAssessmentProject(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List Group resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Group list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentProjectAsync(String resourceGroupName, String projectName) { + return new PagedFlux<>(() -> listByAssessmentProjectSinglePageAsync(resourceGroupName, projectName), + nextLink -> listByAssessmentProjectNextSinglePageAsync(nextLink)); + } + + /** + * List Group resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Group list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentProjectAsync(String resourceGroupName, String projectName, + Context context) { + return new PagedFlux<>(() -> listByAssessmentProjectSinglePageAsync(resourceGroupName, projectName, context), + nextLink -> listByAssessmentProjectNextSinglePageAsync(nextLink, context)); + } + + /** + * List Group resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Group list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName) { + return new PagedIterable<>(listByAssessmentProjectAsync(resourceGroupName, projectName)); + } + + /** + * List Group resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Group list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context) { + return new PagedIterable<>(listByAssessmentProjectAsync(resourceGroupName, projectName, context)); + } + + /** + * Get a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Group along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String groupName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Group along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String groupName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, groupName, accept, context); + } + + /** + * Get a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Group on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceGroupName, String projectName, String groupName) { + return getWithResponseAsync(resourceGroupName, projectName, groupName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Group along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceGroupName, String projectName, String groupName, + Context context) { + return getWithResponseAsync(resourceGroupName, projectName, groupName, context).block(); + } + + /** + * Get a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Group. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public GroupInner get(String resourceGroupName, String projectName, String groupName) { + return getWithResponse(resourceGroupName, projectName, groupName, Context.NONE).getValue(); + } + + /** + * Create a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return group resource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createWithResponseAsync(String resourceGroupName, String projectName, + String groupName, GroupInner resource) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.create(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, resource, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Create a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return group resource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createWithResponseAsync(String resourceGroupName, String projectName, + String groupName, GroupInner resource, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.create(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, groupName, resource, accept, context); + } + + /** + * Create a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of group resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, GroupInner> beginCreateAsync(String resourceGroupName, + String projectName, String groupName, GroupInner resource) { + Mono>> mono + = createWithResponseAsync(resourceGroupName, projectName, groupName, resource); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), GroupInner.class, + GroupInner.class, this.client.getContext()); + } + + /** + * Create a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of group resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, GroupInner> beginCreateAsync(String resourceGroupName, + String projectName, String groupName, GroupInner resource, Context context) { + context = this.client.mergeContext(context); + Mono>> mono + = createWithResponseAsync(resourceGroupName, projectName, groupName, resource, context); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), GroupInner.class, + GroupInner.class, context); + } + + /** + * Create a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of group resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, GroupInner> beginCreate(String resourceGroupName, String projectName, + String groupName, GroupInner resource) { + return this.beginCreateAsync(resourceGroupName, projectName, groupName, resource).getSyncPoller(); + } + + /** + * Create a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of group resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, GroupInner> beginCreate(String resourceGroupName, String projectName, + String groupName, GroupInner resource, Context context) { + return this.beginCreateAsync(resourceGroupName, projectName, groupName, resource, context).getSyncPoller(); + } + + /** + * Create a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return group resource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createAsync(String resourceGroupName, String projectName, String groupName, + GroupInner resource) { + return beginCreateAsync(resourceGroupName, projectName, groupName, resource).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return group resource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createAsync(String resourceGroupName, String projectName, String groupName, + GroupInner resource, Context context) { + return beginCreateAsync(resourceGroupName, projectName, groupName, resource, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return group resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public GroupInner create(String resourceGroupName, String projectName, String groupName, GroupInner resource) { + return createAsync(resourceGroupName, projectName, groupName, resource).block(); + } + + /** + * Create a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return group resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public GroupInner create(String resourceGroupName, String projectName, String groupName, GroupInner resource, + Context context) { + return createAsync(resourceGroupName, projectName, groupName, resource, context).block(); + } + + /** + * Delete a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String projectName, + String groupName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.delete(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Delete a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String projectName, String groupName, + Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.delete(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, groupName, accept, context); + } + + /** + * Delete a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono deleteAsync(String resourceGroupName, String projectName, String groupName) { + return deleteWithResponseAsync(resourceGroupName, projectName, groupName).flatMap(ignored -> Mono.empty()); + } + + /** + * Delete a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String resourceGroupName, String projectName, String groupName, + Context context) { + return deleteWithResponseAsync(resourceGroupName, projectName, groupName, context).block(); + } + + /** + * Delete a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String resourceGroupName, String projectName, String groupName) { + deleteWithResponse(resourceGroupName, projectName, groupName, Context.NONE); + } + + /** + * Update machines in group. + * + * Update machines in group by adding or removing machines. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return group resource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> updateMachinesWithResponseAsync(String resourceGroupName, + String projectName, String groupName, UpdateGroupBody body) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (body == null) { + return Mono.error(new IllegalArgumentException("Parameter body is required and cannot be null.")); + } else { + body.validate(); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.updateMachines(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, body, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Update machines in group. + * + * Update machines in group by adding or removing machines. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return group resource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> updateMachinesWithResponseAsync(String resourceGroupName, + String projectName, String groupName, UpdateGroupBody body, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (body == null) { + return Mono.error(new IllegalArgumentException("Parameter body is required and cannot be null.")); + } else { + body.validate(); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.updateMachines(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, body, accept, context); + } + + /** + * Update machines in group. + * + * Update machines in group by adding or removing machines. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of group resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, GroupInner> beginUpdateMachinesAsync(String resourceGroupName, + String projectName, String groupName, UpdateGroupBody body) { + Mono>> mono + = updateMachinesWithResponseAsync(resourceGroupName, projectName, groupName, body); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), GroupInner.class, + GroupInner.class, this.client.getContext()); + } + + /** + * Update machines in group. + * + * Update machines in group by adding or removing machines. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of group resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, GroupInner> beginUpdateMachinesAsync(String resourceGroupName, + String projectName, String groupName, UpdateGroupBody body, Context context) { + context = this.client.mergeContext(context); + Mono>> mono + = updateMachinesWithResponseAsync(resourceGroupName, projectName, groupName, body, context); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), GroupInner.class, + GroupInner.class, context); + } + + /** + * Update machines in group. + * + * Update machines in group by adding or removing machines. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of group resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, GroupInner> beginUpdateMachines(String resourceGroupName, + String projectName, String groupName, UpdateGroupBody body) { + return this.beginUpdateMachinesAsync(resourceGroupName, projectName, groupName, body).getSyncPoller(); + } + + /** + * Update machines in group. + * + * Update machines in group by adding or removing machines. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of group resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, GroupInner> beginUpdateMachines(String resourceGroupName, + String projectName, String groupName, UpdateGroupBody body, Context context) { + return this.beginUpdateMachinesAsync(resourceGroupName, projectName, groupName, body, context).getSyncPoller(); + } + + /** + * Update machines in group. + * + * Update machines in group by adding or removing machines. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return group resource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono updateMachinesAsync(String resourceGroupName, String projectName, String groupName, + UpdateGroupBody body) { + return beginUpdateMachinesAsync(resourceGroupName, projectName, groupName, body).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Update machines in group. + * + * Update machines in group by adding or removing machines. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return group resource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono updateMachinesAsync(String resourceGroupName, String projectName, String groupName, + UpdateGroupBody body, Context context) { + return beginUpdateMachinesAsync(resourceGroupName, projectName, groupName, body, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Update machines in group. + * + * Update machines in group by adding or removing machines. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return group resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public GroupInner updateMachines(String resourceGroupName, String projectName, String groupName, + UpdateGroupBody body) { + return updateMachinesAsync(resourceGroupName, projectName, groupName, body).block(); + } + + /** + * Update machines in group. + * + * Update machines in group by adding or removing machines. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return group resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public GroupInner updateMachines(String resourceGroupName, String projectName, String groupName, + UpdateGroupBody body, Context context) { + return updateMachinesAsync(resourceGroupName, projectName, groupName, body, context).block(); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Group list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByAssessmentProjectNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), + res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Group list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listByAssessmentProjectNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/GroupsOperationsImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/GroupsOperationsImpl.java new file mode 100644 index 000000000000..f477e02f26bd --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/GroupsOperationsImpl.java @@ -0,0 +1,179 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.migration.assessment.fluent.GroupsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.GroupInner; +import com.azure.resourcemanager.migration.assessment.models.Group; +import com.azure.resourcemanager.migration.assessment.models.GroupsOperations; +import com.azure.resourcemanager.migration.assessment.models.UpdateGroupBody; + +public final class GroupsOperationsImpl implements GroupsOperations { + private static final ClientLogger LOGGER = new ClientLogger(GroupsOperationsImpl.class); + + private final GroupsOperationsClient innerClient; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + public GroupsOperationsImpl(GroupsOperationsClient innerClient, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName) { + PagedIterable inner = this.serviceClient().listByAssessmentProject(resourceGroupName, projectName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new GroupImpl(inner1, this.manager())); + } + + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, Context context) { + PagedIterable inner + = this.serviceClient().listByAssessmentProject(resourceGroupName, projectName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new GroupImpl(inner1, this.manager())); + } + + public Response getWithResponse(String resourceGroupName, String projectName, String groupName, + Context context) { + Response inner + = this.serviceClient().getWithResponse(resourceGroupName, projectName, groupName, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new GroupImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public Group get(String resourceGroupName, String projectName, String groupName) { + GroupInner inner = this.serviceClient().get(resourceGroupName, projectName, groupName); + if (inner != null) { + return new GroupImpl(inner, this.manager()); + } else { + return null; + } + } + + public Response deleteWithResponse(String resourceGroupName, String projectName, String groupName, + Context context) { + return this.serviceClient().deleteWithResponse(resourceGroupName, projectName, groupName, context); + } + + public void delete(String resourceGroupName, String projectName, String groupName) { + this.serviceClient().delete(resourceGroupName, projectName, groupName); + } + + public Group updateMachines(String resourceGroupName, String projectName, String groupName, UpdateGroupBody body) { + GroupInner inner = this.serviceClient().updateMachines(resourceGroupName, projectName, groupName, body); + if (inner != null) { + return new GroupImpl(inner, this.manager()); + } else { + return null; + } + } + + public Group updateMachines(String resourceGroupName, String projectName, String groupName, UpdateGroupBody body, + Context context) { + GroupInner inner + = this.serviceClient().updateMachines(resourceGroupName, projectName, groupName, body, context); + if (inner != null) { + return new GroupImpl(inner, this.manager()); + } else { + return null; + } + } + + public Group getById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String groupName = ResourceManagerUtils.getValueFromIdByName(id, "groups"); + if (groupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'groups'.", id))); + } + return this.getWithResponse(resourceGroupName, projectName, groupName, Context.NONE).getValue(); + } + + public Response getByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String groupName = ResourceManagerUtils.getValueFromIdByName(id, "groups"); + if (groupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'groups'.", id))); + } + return this.getWithResponse(resourceGroupName, projectName, groupName, context); + } + + public void deleteById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String groupName = ResourceManagerUtils.getValueFromIdByName(id, "groups"); + if (groupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'groups'.", id))); + } + this.deleteWithResponse(resourceGroupName, projectName, groupName, Context.NONE); + } + + public Response deleteByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String groupName = ResourceManagerUtils.getValueFromIdByName(id, "groups"); + if (groupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'groups'.", id))); + } + return this.deleteWithResponse(resourceGroupName, projectName, groupName, context); + } + + private GroupsOperationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } + + public GroupImpl define(String name) { + return new GroupImpl(name, this.manager()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/HypervCollectorImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/HypervCollectorImpl.java new file mode 100644 index 000000000000..235059c62c28 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/HypervCollectorImpl.java @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.HypervCollectorInner; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBaseWithAgent; +import com.azure.resourcemanager.migration.assessment.models.HypervCollector; + +public final class HypervCollectorImpl implements HypervCollector, HypervCollector.Definition { + private HypervCollectorInner innerObject; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + HypervCollectorImpl(HypervCollectorInner innerObject, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public CollectorPropertiesBaseWithAgent properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public HypervCollectorInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } + + private String resourceGroupName; + + private String projectName; + + private String hypervCollectorName; + + public HypervCollectorImpl withExistingAssessmentProject(String resourceGroupName, String projectName) { + this.resourceGroupName = resourceGroupName; + this.projectName = projectName; + return this; + } + + public HypervCollector create() { + this.innerObject = serviceManager.serviceClient() + .getHypervCollectorsOperations() + .create(resourceGroupName, projectName, hypervCollectorName, this.innerModel(), Context.NONE); + return this; + } + + public HypervCollector create(Context context) { + this.innerObject = serviceManager.serviceClient() + .getHypervCollectorsOperations() + .create(resourceGroupName, projectName, hypervCollectorName, this.innerModel(), context); + return this; + } + + HypervCollectorImpl(String name, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = new HypervCollectorInner(); + this.serviceManager = serviceManager; + this.hypervCollectorName = name; + } + + public HypervCollector refresh() { + this.innerObject = serviceManager.serviceClient() + .getHypervCollectorsOperations() + .getWithResponse(resourceGroupName, projectName, hypervCollectorName, Context.NONE) + .getValue(); + return this; + } + + public HypervCollector refresh(Context context) { + this.innerObject = serviceManager.serviceClient() + .getHypervCollectorsOperations() + .getWithResponse(resourceGroupName, projectName, hypervCollectorName, context) + .getValue(); + return this; + } + + public HypervCollectorImpl withProperties(CollectorPropertiesBaseWithAgent properties) { + this.innerModel().withProperties(properties); + return this; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/HypervCollectorsOperationsClientImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/HypervCollectorsOperationsClientImpl.java new file mode 100644 index 000000000000..5ac2a18ca05f --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/HypervCollectorsOperationsClientImpl.java @@ -0,0 +1,835 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Put; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.core.util.polling.PollerFlux; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.migration.assessment.fluent.HypervCollectorsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.HypervCollectorInner; +import com.azure.resourcemanager.migration.assessment.models.HypervCollectorListResult; +import java.nio.ByteBuffer; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in HypervCollectorsOperationsClient. + */ +public final class HypervCollectorsOperationsClientImpl implements HypervCollectorsOperationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final HypervCollectorsOperationsService service; + + /** + * The service client containing this operation class. + */ + private final MigrationAssessmentManagementClientImpl client; + + /** + * Initializes an instance of HypervCollectorsOperationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + HypervCollectorsOperationsClientImpl(MigrationAssessmentManagementClientImpl client) { + this.service = RestProxy.create(HypervCollectorsOperationsService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for MigrationAssessmentManagementClientHypervCollectorsOperations to be + * used by the proxy service to perform REST calls. + */ + @Host("{$host}") + @ServiceInterface(name = "MigrationAssessmentM") + public interface HypervCollectorsOperationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/hypervcollectors") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAssessmentProject(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/hypervcollectors/{hypervCollectorName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("hypervCollectorName") String hypervCollectorName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Put("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/hypervcollectors/{hypervCollectorName}") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> create(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("hypervCollectorName") String hypervCollectorName, + @BodyParam("application/json") HypervCollectorInner resource, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Delete("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/hypervcollectors/{hypervCollectorName}") + @ExpectedResponses({ 200, 204 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> delete(@HostParam("$host") String endpoint, @QueryParam("api-version") String apiVersion, + @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("hypervCollectorName") String hypervCollectorName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAssessmentProjectNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * List HypervCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a HypervCollector list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectSinglePageAsync(String resourceGroupName, + String projectName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByAssessmentProject(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List HypervCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a HypervCollector list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectSinglePageAsync(String resourceGroupName, + String projectName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByAssessmentProject(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List HypervCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a HypervCollector list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentProjectAsync(String resourceGroupName, String projectName) { + return new PagedFlux<>(() -> listByAssessmentProjectSinglePageAsync(resourceGroupName, projectName), + nextLink -> listByAssessmentProjectNextSinglePageAsync(nextLink)); + } + + /** + * List HypervCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a HypervCollector list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentProjectAsync(String resourceGroupName, String projectName, + Context context) { + return new PagedFlux<>(() -> listByAssessmentProjectSinglePageAsync(resourceGroupName, projectName, context), + nextLink -> listByAssessmentProjectNextSinglePageAsync(nextLink, context)); + } + + /** + * List HypervCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a HypervCollector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName) { + return new PagedIterable<>(listByAssessmentProjectAsync(resourceGroupName, projectName)); + } + + /** + * List HypervCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a HypervCollector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context) { + return new PagedIterable<>(listByAssessmentProjectAsync(resourceGroupName, projectName, context)); + } + + /** + * Get a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a HypervCollector along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String hypervCollectorName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (hypervCollectorName == null) { + return Mono + .error(new IllegalArgumentException("Parameter hypervCollectorName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, hypervCollectorName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a HypervCollector along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String hypervCollectorName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (hypervCollectorName == null) { + return Mono + .error(new IllegalArgumentException("Parameter hypervCollectorName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, hypervCollectorName, accept, context); + } + + /** + * Get a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a HypervCollector on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceGroupName, String projectName, + String hypervCollectorName) { + return getWithResponseAsync(resourceGroupName, projectName, hypervCollectorName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a HypervCollector along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceGroupName, String projectName, + String hypervCollectorName, Context context) { + return getWithResponseAsync(resourceGroupName, projectName, hypervCollectorName, context).block(); + } + + /** + * Get a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a HypervCollector. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public HypervCollectorInner get(String resourceGroupName, String projectName, String hypervCollectorName) { + return getWithResponse(resourceGroupName, projectName, hypervCollectorName, Context.NONE).getValue(); + } + + /** + * Create a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return hyper-V collector resource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createWithResponseAsync(String resourceGroupName, String projectName, + String hypervCollectorName, HypervCollectorInner resource) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (hypervCollectorName == null) { + return Mono + .error(new IllegalArgumentException("Parameter hypervCollectorName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.create(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, hypervCollectorName, resource, accept, + context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Create a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return hyper-V collector resource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createWithResponseAsync(String resourceGroupName, String projectName, + String hypervCollectorName, HypervCollectorInner resource, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (hypervCollectorName == null) { + return Mono + .error(new IllegalArgumentException("Parameter hypervCollectorName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.create(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, hypervCollectorName, resource, accept, context); + } + + /** + * Create a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of hyper-V collector resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, HypervCollectorInner> beginCreateAsync( + String resourceGroupName, String projectName, String hypervCollectorName, HypervCollectorInner resource) { + Mono>> mono + = createWithResponseAsync(resourceGroupName, projectName, hypervCollectorName, resource); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + HypervCollectorInner.class, HypervCollectorInner.class, this.client.getContext()); + } + + /** + * Create a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of hyper-V collector resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, HypervCollectorInner> beginCreateAsync( + String resourceGroupName, String projectName, String hypervCollectorName, HypervCollectorInner resource, + Context context) { + context = this.client.mergeContext(context); + Mono>> mono + = createWithResponseAsync(resourceGroupName, projectName, hypervCollectorName, resource, context); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + HypervCollectorInner.class, HypervCollectorInner.class, context); + } + + /** + * Create a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of hyper-V collector resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, HypervCollectorInner> beginCreate(String resourceGroupName, + String projectName, String hypervCollectorName, HypervCollectorInner resource) { + return this.beginCreateAsync(resourceGroupName, projectName, hypervCollectorName, resource).getSyncPoller(); + } + + /** + * Create a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of hyper-V collector resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, HypervCollectorInner> beginCreate(String resourceGroupName, + String projectName, String hypervCollectorName, HypervCollectorInner resource, Context context) { + return this.beginCreateAsync(resourceGroupName, projectName, hypervCollectorName, resource, context) + .getSyncPoller(); + } + + /** + * Create a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return hyper-V collector resource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createAsync(String resourceGroupName, String projectName, + String hypervCollectorName, HypervCollectorInner resource) { + return beginCreateAsync(resourceGroupName, projectName, hypervCollectorName, resource).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return hyper-V collector resource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createAsync(String resourceGroupName, String projectName, + String hypervCollectorName, HypervCollectorInner resource, Context context) { + return beginCreateAsync(resourceGroupName, projectName, hypervCollectorName, resource, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return hyper-V collector resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public HypervCollectorInner create(String resourceGroupName, String projectName, String hypervCollectorName, + HypervCollectorInner resource) { + return createAsync(resourceGroupName, projectName, hypervCollectorName, resource).block(); + } + + /** + * Create a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return hyper-V collector resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public HypervCollectorInner create(String resourceGroupName, String projectName, String hypervCollectorName, + HypervCollectorInner resource, Context context) { + return createAsync(resourceGroupName, projectName, hypervCollectorName, resource, context).block(); + } + + /** + * Delete a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String projectName, + String hypervCollectorName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (hypervCollectorName == null) { + return Mono + .error(new IllegalArgumentException("Parameter hypervCollectorName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.delete(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, hypervCollectorName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Delete a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String projectName, + String hypervCollectorName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (hypervCollectorName == null) { + return Mono + .error(new IllegalArgumentException("Parameter hypervCollectorName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.delete(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, hypervCollectorName, accept, context); + } + + /** + * Delete a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono deleteAsync(String resourceGroupName, String projectName, String hypervCollectorName) { + return deleteWithResponseAsync(resourceGroupName, projectName, hypervCollectorName) + .flatMap(ignored -> Mono.empty()); + } + + /** + * Delete a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String resourceGroupName, String projectName, String hypervCollectorName, + Context context) { + return deleteWithResponseAsync(resourceGroupName, projectName, hypervCollectorName, context).block(); + } + + /** + * Delete a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String resourceGroupName, String projectName, String hypervCollectorName) { + deleteWithResponse(resourceGroupName, projectName, hypervCollectorName, Context.NONE); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a HypervCollector list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByAssessmentProjectNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a HypervCollector list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listByAssessmentProjectNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/HypervCollectorsOperationsImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/HypervCollectorsOperationsImpl.java new file mode 100644 index 000000000000..76e15b76e4a0 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/HypervCollectorsOperationsImpl.java @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.migration.assessment.fluent.HypervCollectorsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.HypervCollectorInner; +import com.azure.resourcemanager.migration.assessment.models.HypervCollector; +import com.azure.resourcemanager.migration.assessment.models.HypervCollectorsOperations; + +public final class HypervCollectorsOperationsImpl implements HypervCollectorsOperations { + private static final ClientLogger LOGGER = new ClientLogger(HypervCollectorsOperationsImpl.class); + + private final HypervCollectorsOperationsClient innerClient; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + public HypervCollectorsOperationsImpl(HypervCollectorsOperationsClient innerClient, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName) { + PagedIterable inner + = this.serviceClient().listByAssessmentProject(resourceGroupName, projectName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new HypervCollectorImpl(inner1, this.manager())); + } + + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context) { + PagedIterable inner + = this.serviceClient().listByAssessmentProject(resourceGroupName, projectName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new HypervCollectorImpl(inner1, this.manager())); + } + + public Response getWithResponse(String resourceGroupName, String projectName, + String hypervCollectorName, Context context) { + Response inner + = this.serviceClient().getWithResponse(resourceGroupName, projectName, hypervCollectorName, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new HypervCollectorImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public HypervCollector get(String resourceGroupName, String projectName, String hypervCollectorName) { + HypervCollectorInner inner = this.serviceClient().get(resourceGroupName, projectName, hypervCollectorName); + if (inner != null) { + return new HypervCollectorImpl(inner, this.manager()); + } else { + return null; + } + } + + public Response deleteWithResponse(String resourceGroupName, String projectName, String hypervCollectorName, + Context context) { + return this.serviceClient().deleteWithResponse(resourceGroupName, projectName, hypervCollectorName, context); + } + + public void delete(String resourceGroupName, String projectName, String hypervCollectorName) { + this.serviceClient().delete(resourceGroupName, projectName, hypervCollectorName); + } + + public HypervCollector getById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String hypervCollectorName = ResourceManagerUtils.getValueFromIdByName(id, "hypervcollectors"); + if (hypervCollectorName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'hypervcollectors'.", id))); + } + return this.getWithResponse(resourceGroupName, projectName, hypervCollectorName, Context.NONE).getValue(); + } + + public Response getByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String hypervCollectorName = ResourceManagerUtils.getValueFromIdByName(id, "hypervcollectors"); + if (hypervCollectorName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'hypervcollectors'.", id))); + } + return this.getWithResponse(resourceGroupName, projectName, hypervCollectorName, context); + } + + public void deleteById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String hypervCollectorName = ResourceManagerUtils.getValueFromIdByName(id, "hypervcollectors"); + if (hypervCollectorName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'hypervcollectors'.", id))); + } + this.deleteWithResponse(resourceGroupName, projectName, hypervCollectorName, Context.NONE); + } + + public Response deleteByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String hypervCollectorName = ResourceManagerUtils.getValueFromIdByName(id, "hypervcollectors"); + if (hypervCollectorName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'hypervcollectors'.", id))); + } + return this.deleteWithResponse(resourceGroupName, projectName, hypervCollectorName, context); + } + + private HypervCollectorsOperationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } + + public HypervCollectorImpl define(String name) { + return new HypervCollectorImpl(name, this.manager()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/ImportCollectorImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/ImportCollectorImpl.java new file mode 100644 index 000000000000..f702093bf336 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/ImportCollectorImpl.java @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.ImportCollectorInner; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.ImportCollector; + +public final class ImportCollectorImpl implements ImportCollector, ImportCollector.Definition { + private ImportCollectorInner innerObject; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + ImportCollectorImpl(ImportCollectorInner innerObject, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public CollectorPropertiesBase properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public ImportCollectorInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } + + private String resourceGroupName; + + private String projectName; + + private String importCollectorName; + + public ImportCollectorImpl withExistingAssessmentProject(String resourceGroupName, String projectName) { + this.resourceGroupName = resourceGroupName; + this.projectName = projectName; + return this; + } + + public ImportCollector create() { + this.innerObject = serviceManager.serviceClient() + .getImportCollectorsOperations() + .create(resourceGroupName, projectName, importCollectorName, this.innerModel(), Context.NONE); + return this; + } + + public ImportCollector create(Context context) { + this.innerObject = serviceManager.serviceClient() + .getImportCollectorsOperations() + .create(resourceGroupName, projectName, importCollectorName, this.innerModel(), context); + return this; + } + + ImportCollectorImpl(String name, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = new ImportCollectorInner(); + this.serviceManager = serviceManager; + this.importCollectorName = name; + } + + public ImportCollector refresh() { + this.innerObject = serviceManager.serviceClient() + .getImportCollectorsOperations() + .getWithResponse(resourceGroupName, projectName, importCollectorName, Context.NONE) + .getValue(); + return this; + } + + public ImportCollector refresh(Context context) { + this.innerObject = serviceManager.serviceClient() + .getImportCollectorsOperations() + .getWithResponse(resourceGroupName, projectName, importCollectorName, context) + .getValue(); + return this; + } + + public ImportCollectorImpl withProperties(CollectorPropertiesBase properties) { + this.innerModel().withProperties(properties); + return this; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/ImportCollectorsOperationsClientImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/ImportCollectorsOperationsClientImpl.java new file mode 100644 index 000000000000..9069f656ad8a --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/ImportCollectorsOperationsClientImpl.java @@ -0,0 +1,835 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Put; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.core.util.polling.PollerFlux; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.migration.assessment.fluent.ImportCollectorsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.ImportCollectorInner; +import com.azure.resourcemanager.migration.assessment.models.ImportCollectorListResult; +import java.nio.ByteBuffer; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in ImportCollectorsOperationsClient. + */ +public final class ImportCollectorsOperationsClientImpl implements ImportCollectorsOperationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final ImportCollectorsOperationsService service; + + /** + * The service client containing this operation class. + */ + private final MigrationAssessmentManagementClientImpl client; + + /** + * Initializes an instance of ImportCollectorsOperationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + ImportCollectorsOperationsClientImpl(MigrationAssessmentManagementClientImpl client) { + this.service = RestProxy.create(ImportCollectorsOperationsService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for MigrationAssessmentManagementClientImportCollectorsOperations to be + * used by the proxy service to perform REST calls. + */ + @Host("{$host}") + @ServiceInterface(name = "MigrationAssessmentM") + public interface ImportCollectorsOperationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/importcollectors") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAssessmentProject(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/importcollectors/{importCollectorName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("importCollectorName") String importCollectorName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Put("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/importcollectors/{importCollectorName}") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> create(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("importCollectorName") String importCollectorName, + @BodyParam("application/json") ImportCollectorInner resource, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Delete("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/importcollectors/{importCollectorName}") + @ExpectedResponses({ 200, 204 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> delete(@HostParam("$host") String endpoint, @QueryParam("api-version") String apiVersion, + @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("importCollectorName") String importCollectorName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAssessmentProjectNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * List ImportCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ImportCollector list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectSinglePageAsync(String resourceGroupName, + String projectName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByAssessmentProject(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List ImportCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ImportCollector list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectSinglePageAsync(String resourceGroupName, + String projectName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByAssessmentProject(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List ImportCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ImportCollector list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentProjectAsync(String resourceGroupName, String projectName) { + return new PagedFlux<>(() -> listByAssessmentProjectSinglePageAsync(resourceGroupName, projectName), + nextLink -> listByAssessmentProjectNextSinglePageAsync(nextLink)); + } + + /** + * List ImportCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ImportCollector list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentProjectAsync(String resourceGroupName, String projectName, + Context context) { + return new PagedFlux<>(() -> listByAssessmentProjectSinglePageAsync(resourceGroupName, projectName, context), + nextLink -> listByAssessmentProjectNextSinglePageAsync(nextLink, context)); + } + + /** + * List ImportCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ImportCollector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName) { + return new PagedIterable<>(listByAssessmentProjectAsync(resourceGroupName, projectName)); + } + + /** + * List ImportCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ImportCollector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context) { + return new PagedIterable<>(listByAssessmentProjectAsync(resourceGroupName, projectName, context)); + } + + /** + * Get a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ImportCollector along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String importCollectorName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (importCollectorName == null) { + return Mono + .error(new IllegalArgumentException("Parameter importCollectorName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, importCollectorName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ImportCollector along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String importCollectorName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (importCollectorName == null) { + return Mono + .error(new IllegalArgumentException("Parameter importCollectorName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, importCollectorName, accept, context); + } + + /** + * Get a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ImportCollector on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceGroupName, String projectName, + String importCollectorName) { + return getWithResponseAsync(resourceGroupName, projectName, importCollectorName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ImportCollector along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceGroupName, String projectName, + String importCollectorName, Context context) { + return getWithResponseAsync(resourceGroupName, projectName, importCollectorName, context).block(); + } + + /** + * Get a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ImportCollector. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public ImportCollectorInner get(String resourceGroupName, String projectName, String importCollectorName) { + return getWithResponse(resourceGroupName, projectName, importCollectorName, Context.NONE).getValue(); + } + + /** + * Create a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return import collector resource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createWithResponseAsync(String resourceGroupName, String projectName, + String importCollectorName, ImportCollectorInner resource) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (importCollectorName == null) { + return Mono + .error(new IllegalArgumentException("Parameter importCollectorName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.create(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, importCollectorName, resource, accept, + context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Create a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return import collector resource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createWithResponseAsync(String resourceGroupName, String projectName, + String importCollectorName, ImportCollectorInner resource, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (importCollectorName == null) { + return Mono + .error(new IllegalArgumentException("Parameter importCollectorName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.create(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, importCollectorName, resource, accept, context); + } + + /** + * Create a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of import collector resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, ImportCollectorInner> beginCreateAsync( + String resourceGroupName, String projectName, String importCollectorName, ImportCollectorInner resource) { + Mono>> mono + = createWithResponseAsync(resourceGroupName, projectName, importCollectorName, resource); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + ImportCollectorInner.class, ImportCollectorInner.class, this.client.getContext()); + } + + /** + * Create a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of import collector resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, ImportCollectorInner> beginCreateAsync( + String resourceGroupName, String projectName, String importCollectorName, ImportCollectorInner resource, + Context context) { + context = this.client.mergeContext(context); + Mono>> mono + = createWithResponseAsync(resourceGroupName, projectName, importCollectorName, resource, context); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + ImportCollectorInner.class, ImportCollectorInner.class, context); + } + + /** + * Create a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of import collector resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, ImportCollectorInner> beginCreate(String resourceGroupName, + String projectName, String importCollectorName, ImportCollectorInner resource) { + return this.beginCreateAsync(resourceGroupName, projectName, importCollectorName, resource).getSyncPoller(); + } + + /** + * Create a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of import collector resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, ImportCollectorInner> beginCreate(String resourceGroupName, + String projectName, String importCollectorName, ImportCollectorInner resource, Context context) { + return this.beginCreateAsync(resourceGroupName, projectName, importCollectorName, resource, context) + .getSyncPoller(); + } + + /** + * Create a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return import collector resource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createAsync(String resourceGroupName, String projectName, + String importCollectorName, ImportCollectorInner resource) { + return beginCreateAsync(resourceGroupName, projectName, importCollectorName, resource).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return import collector resource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createAsync(String resourceGroupName, String projectName, + String importCollectorName, ImportCollectorInner resource, Context context) { + return beginCreateAsync(resourceGroupName, projectName, importCollectorName, resource, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return import collector resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public ImportCollectorInner create(String resourceGroupName, String projectName, String importCollectorName, + ImportCollectorInner resource) { + return createAsync(resourceGroupName, projectName, importCollectorName, resource).block(); + } + + /** + * Create a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return import collector resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public ImportCollectorInner create(String resourceGroupName, String projectName, String importCollectorName, + ImportCollectorInner resource, Context context) { + return createAsync(resourceGroupName, projectName, importCollectorName, resource, context).block(); + } + + /** + * Delete a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String projectName, + String importCollectorName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (importCollectorName == null) { + return Mono + .error(new IllegalArgumentException("Parameter importCollectorName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.delete(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, importCollectorName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Delete a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String projectName, + String importCollectorName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (importCollectorName == null) { + return Mono + .error(new IllegalArgumentException("Parameter importCollectorName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.delete(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, importCollectorName, accept, context); + } + + /** + * Delete a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono deleteAsync(String resourceGroupName, String projectName, String importCollectorName) { + return deleteWithResponseAsync(resourceGroupName, projectName, importCollectorName) + .flatMap(ignored -> Mono.empty()); + } + + /** + * Delete a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String resourceGroupName, String projectName, String importCollectorName, + Context context) { + return deleteWithResponseAsync(resourceGroupName, projectName, importCollectorName, context).block(); + } + + /** + * Delete a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String resourceGroupName, String projectName, String importCollectorName) { + deleteWithResponse(resourceGroupName, projectName, importCollectorName, Context.NONE); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ImportCollector list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByAssessmentProjectNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ImportCollector list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listByAssessmentProjectNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/ImportCollectorsOperationsImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/ImportCollectorsOperationsImpl.java new file mode 100644 index 000000000000..a758a099b217 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/ImportCollectorsOperationsImpl.java @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.migration.assessment.fluent.ImportCollectorsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.ImportCollectorInner; +import com.azure.resourcemanager.migration.assessment.models.ImportCollector; +import com.azure.resourcemanager.migration.assessment.models.ImportCollectorsOperations; + +public final class ImportCollectorsOperationsImpl implements ImportCollectorsOperations { + private static final ClientLogger LOGGER = new ClientLogger(ImportCollectorsOperationsImpl.class); + + private final ImportCollectorsOperationsClient innerClient; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + public ImportCollectorsOperationsImpl(ImportCollectorsOperationsClient innerClient, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName) { + PagedIterable inner + = this.serviceClient().listByAssessmentProject(resourceGroupName, projectName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new ImportCollectorImpl(inner1, this.manager())); + } + + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context) { + PagedIterable inner + = this.serviceClient().listByAssessmentProject(resourceGroupName, projectName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new ImportCollectorImpl(inner1, this.manager())); + } + + public Response getWithResponse(String resourceGroupName, String projectName, + String importCollectorName, Context context) { + Response inner + = this.serviceClient().getWithResponse(resourceGroupName, projectName, importCollectorName, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new ImportCollectorImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public ImportCollector get(String resourceGroupName, String projectName, String importCollectorName) { + ImportCollectorInner inner = this.serviceClient().get(resourceGroupName, projectName, importCollectorName); + if (inner != null) { + return new ImportCollectorImpl(inner, this.manager()); + } else { + return null; + } + } + + public Response deleteWithResponse(String resourceGroupName, String projectName, String importCollectorName, + Context context) { + return this.serviceClient().deleteWithResponse(resourceGroupName, projectName, importCollectorName, context); + } + + public void delete(String resourceGroupName, String projectName, String importCollectorName) { + this.serviceClient().delete(resourceGroupName, projectName, importCollectorName); + } + + public ImportCollector getById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String importCollectorName = ResourceManagerUtils.getValueFromIdByName(id, "importcollectors"); + if (importCollectorName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'importcollectors'.", id))); + } + return this.getWithResponse(resourceGroupName, projectName, importCollectorName, Context.NONE).getValue(); + } + + public Response getByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String importCollectorName = ResourceManagerUtils.getValueFromIdByName(id, "importcollectors"); + if (importCollectorName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'importcollectors'.", id))); + } + return this.getWithResponse(resourceGroupName, projectName, importCollectorName, context); + } + + public void deleteById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String importCollectorName = ResourceManagerUtils.getValueFromIdByName(id, "importcollectors"); + if (importCollectorName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'importcollectors'.", id))); + } + this.deleteWithResponse(resourceGroupName, projectName, importCollectorName, Context.NONE); + } + + public Response deleteByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String importCollectorName = ResourceManagerUtils.getValueFromIdByName(id, "importcollectors"); + if (importCollectorName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'importcollectors'.", id))); + } + return this.deleteWithResponse(resourceGroupName, projectName, importCollectorName, context); + } + + private ImportCollectorsOperationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } + + public ImportCollectorImpl define(String name) { + return new ImportCollectorImpl(name, this.manager()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/MachineImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/MachineImpl.java new file mode 100644 index 000000000000..85d4282e45d1 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/MachineImpl.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.migration.assessment.fluent.models.MachineInner; +import com.azure.resourcemanager.migration.assessment.models.Machine; +import com.azure.resourcemanager.migration.assessment.models.MachineProperties; + +public final class MachineImpl implements Machine { + private MachineInner innerObject; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + MachineImpl(MachineInner innerObject, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public MachineProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public MachineInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/MachinesOperationsClientImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/MachinesOperationsClientImpl.java new file mode 100644 index 000000000000..1c9dddfad45f --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/MachinesOperationsClientImpl.java @@ -0,0 +1,475 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.resourcemanager.migration.assessment.fluent.MachinesOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.MachineInner; +import com.azure.resourcemanager.migration.assessment.models.MachineListResult; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in MachinesOperationsClient. + */ +public final class MachinesOperationsClientImpl implements MachinesOperationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final MachinesOperationsService service; + + /** + * The service client containing this operation class. + */ + private final MigrationAssessmentManagementClientImpl client; + + /** + * Initializes an instance of MachinesOperationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + MachinesOperationsClientImpl(MigrationAssessmentManagementClientImpl client) { + this.service = RestProxy.create(MachinesOperationsService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for MigrationAssessmentManagementClientMachinesOperations to be used by + * the proxy service to perform REST calls. + */ + @Host("{$host}") + @ServiceInterface(name = "MigrationAssessmentM") + public interface MachinesOperationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/machines") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAssessmentProject(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @QueryParam("$filter") String filter, + @QueryParam("pageSize") Integer pageSize, @QueryParam("continuationToken") String continuationToken, + @QueryParam("totalRecordCount") Integer totalRecordCount, @PathParam("projectName") String projectName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/machines/{machineName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("machineName") String machineName, @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAssessmentProjectNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * List Machine resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Machine list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectSinglePageAsync(String resourceGroupName, + String projectName, String filter, Integer pageSize, String continuationToken, Integer totalRecordCount) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listByAssessmentProject(this.client.getEndpoint(), + this.client.getApiVersion(), this.client.getSubscriptionId(), resourceGroupName, filter, pageSize, + continuationToken, totalRecordCount, projectName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), + res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List Machine resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Machine list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectSinglePageAsync(String resourceGroupName, + String projectName, String filter, Integer pageSize, String continuationToken, Integer totalRecordCount, + Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByAssessmentProject(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, filter, pageSize, continuationToken, + totalRecordCount, projectName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List Machine resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Machine list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentProjectAsync(String resourceGroupName, String projectName, + String filter, Integer pageSize, String continuationToken, Integer totalRecordCount) { + return new PagedFlux<>(() -> listByAssessmentProjectSinglePageAsync(resourceGroupName, projectName, filter, + pageSize, continuationToken, totalRecordCount), + nextLink -> listByAssessmentProjectNextSinglePageAsync(nextLink)); + } + + /** + * List Machine resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Machine list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentProjectAsync(String resourceGroupName, String projectName) { + final String filter = null; + final Integer pageSize = null; + final String continuationToken = null; + final Integer totalRecordCount = null; + return new PagedFlux<>(() -> listByAssessmentProjectSinglePageAsync(resourceGroupName, projectName, filter, + pageSize, continuationToken, totalRecordCount), + nextLink -> listByAssessmentProjectNextSinglePageAsync(nextLink)); + } + + /** + * List Machine resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Machine list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentProjectAsync(String resourceGroupName, String projectName, + String filter, Integer pageSize, String continuationToken, Integer totalRecordCount, Context context) { + return new PagedFlux<>( + () -> listByAssessmentProjectSinglePageAsync(resourceGroupName, projectName, filter, pageSize, + continuationToken, totalRecordCount, context), + nextLink -> listByAssessmentProjectNextSinglePageAsync(nextLink, context)); + } + + /** + * List Machine resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Machine list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName) { + final String filter = null; + final Integer pageSize = null; + final String continuationToken = null; + final Integer totalRecordCount = null; + return new PagedIterable<>(listByAssessmentProjectAsync(resourceGroupName, projectName, filter, pageSize, + continuationToken, totalRecordCount)); + } + + /** + * List Machine resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Machine list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + String filter, Integer pageSize, String continuationToken, Integer totalRecordCount, Context context) { + return new PagedIterable<>(listByAssessmentProjectAsync(resourceGroupName, projectName, filter, pageSize, + continuationToken, totalRecordCount, context)); + } + + /** + * Get a Machine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param machineName Assessible Machine ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Machine along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String machineName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (machineName == null) { + return Mono.error(new IllegalArgumentException("Parameter machineName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, machineName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a Machine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param machineName Assessible Machine ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Machine along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String machineName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (machineName == null) { + return Mono.error(new IllegalArgumentException("Parameter machineName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, machineName, accept, context); + } + + /** + * Get a Machine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param machineName Assessible Machine ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Machine on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceGroupName, String projectName, String machineName) { + return getWithResponseAsync(resourceGroupName, projectName, machineName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a Machine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param machineName Assessible Machine ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Machine along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceGroupName, String projectName, String machineName, + Context context) { + return getWithResponseAsync(resourceGroupName, projectName, machineName, context).block(); + } + + /** + * Get a Machine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param machineName Assessible Machine ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Machine. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public MachineInner get(String resourceGroupName, String projectName, String machineName) { + return getWithResponse(resourceGroupName, projectName, machineName, Context.NONE).getValue(); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Machine list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByAssessmentProjectNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), + res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Machine list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listByAssessmentProjectNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/MachinesOperationsImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/MachinesOperationsImpl.java new file mode 100644 index 000000000000..8e8152c07fce --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/MachinesOperationsImpl.java @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.migration.assessment.fluent.MachinesOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.MachineInner; +import com.azure.resourcemanager.migration.assessment.models.Machine; +import com.azure.resourcemanager.migration.assessment.models.MachinesOperations; + +public final class MachinesOperationsImpl implements MachinesOperations { + private static final ClientLogger LOGGER = new ClientLogger(MachinesOperationsImpl.class); + + private final MachinesOperationsClient innerClient; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + public MachinesOperationsImpl(MachinesOperationsClient innerClient, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName) { + PagedIterable inner + = this.serviceClient().listByAssessmentProject(resourceGroupName, projectName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new MachineImpl(inner1, this.manager())); + } + + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, String filter, + Integer pageSize, String continuationToken, Integer totalRecordCount, Context context) { + PagedIterable inner = this.serviceClient() + .listByAssessmentProject(resourceGroupName, projectName, filter, pageSize, continuationToken, + totalRecordCount, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new MachineImpl(inner1, this.manager())); + } + + public Response getWithResponse(String resourceGroupName, String projectName, String machineName, + Context context) { + Response inner + = this.serviceClient().getWithResponse(resourceGroupName, projectName, machineName, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new MachineImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public Machine get(String resourceGroupName, String projectName, String machineName) { + MachineInner inner = this.serviceClient().get(resourceGroupName, projectName, machineName); + if (inner != null) { + return new MachineImpl(inner, this.manager()); + } else { + return null; + } + } + + private MachinesOperationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/MigrationAssessmentManagementClientBuilder.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/MigrationAssessmentManagementClientBuilder.java new file mode 100644 index 000000000000..cbb4b4a28039 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/MigrationAssessmentManagementClientBuilder.java @@ -0,0 +1,138 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.annotation.ServiceClientBuilder; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.policy.RetryPolicy; +import com.azure.core.http.policy.UserAgentPolicy; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.serializer.SerializerFactory; +import com.azure.core.util.serializer.SerializerAdapter; +import java.time.Duration; + +/** + * A builder for creating a new instance of the MigrationAssessmentManagementClientImpl type. + */ +@ServiceClientBuilder(serviceClients = { MigrationAssessmentManagementClientImpl.class }) +public final class MigrationAssessmentManagementClientBuilder { + /* + * The ID of the target subscription. + */ + private String subscriptionId; + + /** + * Sets The ID of the target subscription. + * + * @param subscriptionId the subscriptionId value. + * @return the MigrationAssessmentManagementClientBuilder. + */ + public MigrationAssessmentManagementClientBuilder subscriptionId(String subscriptionId) { + this.subscriptionId = subscriptionId; + return this; + } + + /* + * server parameter + */ + private String endpoint; + + /** + * Sets server parameter. + * + * @param endpoint the endpoint value. + * @return the MigrationAssessmentManagementClientBuilder. + */ + public MigrationAssessmentManagementClientBuilder endpoint(String endpoint) { + this.endpoint = endpoint; + return this; + } + + /* + * The environment to connect to + */ + private AzureEnvironment environment; + + /** + * Sets The environment to connect to. + * + * @param environment the environment value. + * @return the MigrationAssessmentManagementClientBuilder. + */ + public MigrationAssessmentManagementClientBuilder environment(AzureEnvironment environment) { + this.environment = environment; + 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 MigrationAssessmentManagementClientBuilder. + */ + public MigrationAssessmentManagementClientBuilder pipeline(HttpPipeline pipeline) { + this.pipeline = pipeline; + return this; + } + + /* + * The default poll interval for long-running operation + */ + private Duration defaultPollInterval; + + /** + * Sets The default poll interval for long-running operation. + * + * @param defaultPollInterval the defaultPollInterval value. + * @return the MigrationAssessmentManagementClientBuilder. + */ + public MigrationAssessmentManagementClientBuilder defaultPollInterval(Duration defaultPollInterval) { + this.defaultPollInterval = defaultPollInterval; + 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 MigrationAssessmentManagementClientBuilder. + */ + public MigrationAssessmentManagementClientBuilder serializerAdapter(SerializerAdapter serializerAdapter) { + this.serializerAdapter = serializerAdapter; + return this; + } + + /** + * Builds an instance of MigrationAssessmentManagementClientImpl with the provided parameters. + * + * @return an instance of MigrationAssessmentManagementClientImpl. + */ + public MigrationAssessmentManagementClientImpl buildClient() { + String localEndpoint = (endpoint != null) ? endpoint : "https://management.azure.com"; + AzureEnvironment localEnvironment = (environment != null) ? environment : AzureEnvironment.AZURE; + HttpPipeline localPipeline = (pipeline != null) + ? pipeline + : new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build(); + Duration localDefaultPollInterval + = (defaultPollInterval != null) ? defaultPollInterval : Duration.ofSeconds(30); + SerializerAdapter localSerializerAdapter = (serializerAdapter != null) + ? serializerAdapter + : SerializerFactory.createDefaultManagementSerializerAdapter(); + MigrationAssessmentManagementClientImpl client = new MigrationAssessmentManagementClientImpl(localPipeline, + localSerializerAdapter, localDefaultPollInterval, localEnvironment, this.subscriptionId, localEndpoint); + return client; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/MigrationAssessmentManagementClientImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/MigrationAssessmentManagementClientImpl.java new file mode 100644 index 000000000000..66c1cd731f96 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/MigrationAssessmentManagementClientImpl.java @@ -0,0 +1,672 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.annotation.ServiceClient; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.HttpHeaders; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpResponse; +import com.azure.core.http.rest.Response; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.exception.ManagementError; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.management.polling.PollResult; +import com.azure.core.management.polling.PollerFactory; +import com.azure.core.util.Context; +import com.azure.core.util.CoreUtils; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.polling.AsyncPollResponse; +import com.azure.core.util.polling.LongRunningOperationStatus; +import com.azure.core.util.polling.PollerFlux; +import com.azure.core.util.serializer.SerializerAdapter; +import com.azure.core.util.serializer.SerializerEncoding; +import com.azure.resourcemanager.migration.assessment.fluent.AssessedMachinesOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.AssessedSqlDatabaseV2OperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.AssessedSqlInstanceV2OperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.AssessedSqlMachinesOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.AssessedSqlRecommendedEntityOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.AssessmentOptionsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.AssessmentProjectSummaryOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.AssessmentProjectsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.AssessmentsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.AvsAssessedMachinesOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.AvsAssessmentOptionsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.AvsAssessmentsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.GroupsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.HypervCollectorsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.ImportCollectorsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.MachinesOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.MigrationAssessmentManagementClient; +import com.azure.resourcemanager.migration.assessment.fluent.OperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.PrivateEndpointConnectionOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.PrivateLinkResourceOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.ServerCollectorsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.SqlAssessmentOptionsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.SqlAssessmentV2OperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.SqlAssessmentV2SummaryOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.SqlCollectorOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.VmwareCollectorsOperationsClient; +import java.io.IOException; +import java.lang.reflect.Type; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * Initializes a new instance of the MigrationAssessmentManagementClientImpl type. + */ +@ServiceClient(builder = MigrationAssessmentManagementClientBuilder.class) +public final class MigrationAssessmentManagementClientImpl implements MigrationAssessmentManagementClient { + /** + * The ID of the target subscription. + */ + private final String subscriptionId; + + /** + * Gets The ID of the target subscription. + * + * @return the subscriptionId value. + */ + public String getSubscriptionId() { + return this.subscriptionId; + } + + /** + * server parameter. + */ + private final String endpoint; + + /** + * Gets server parameter. + * + * @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. + */ + SerializerAdapter getSerializerAdapter() { + return this.serializerAdapter; + } + + /** + * The default poll interval for long-running operation. + */ + private final Duration defaultPollInterval; + + /** + * Gets The default poll interval for long-running operation. + * + * @return the defaultPollInterval value. + */ + public Duration getDefaultPollInterval() { + return this.defaultPollInterval; + } + + /** + * The OperationsClient object to access its operations. + */ + private final OperationsClient operations; + + /** + * Gets the OperationsClient object to access its operations. + * + * @return the OperationsClient object. + */ + public OperationsClient getOperations() { + return this.operations; + } + + /** + * The AssessmentProjectsOperationsClient object to access its operations. + */ + private final AssessmentProjectsOperationsClient assessmentProjectsOperations; + + /** + * Gets the AssessmentProjectsOperationsClient object to access its operations. + * + * @return the AssessmentProjectsOperationsClient object. + */ + public AssessmentProjectsOperationsClient getAssessmentProjectsOperations() { + return this.assessmentProjectsOperations; + } + + /** + * The AssessmentOptionsOperationsClient object to access its operations. + */ + private final AssessmentOptionsOperationsClient assessmentOptionsOperations; + + /** + * Gets the AssessmentOptionsOperationsClient object to access its operations. + * + * @return the AssessmentOptionsOperationsClient object. + */ + public AssessmentOptionsOperationsClient getAssessmentOptionsOperations() { + return this.assessmentOptionsOperations; + } + + /** + * The AvsAssessmentOptionsOperationsClient object to access its operations. + */ + private final AvsAssessmentOptionsOperationsClient avsAssessmentOptionsOperations; + + /** + * Gets the AvsAssessmentOptionsOperationsClient object to access its operations. + * + * @return the AvsAssessmentOptionsOperationsClient object. + */ + public AvsAssessmentOptionsOperationsClient getAvsAssessmentOptionsOperations() { + return this.avsAssessmentOptionsOperations; + } + + /** + * The GroupsOperationsClient object to access its operations. + */ + private final GroupsOperationsClient groupsOperations; + + /** + * Gets the GroupsOperationsClient object to access its operations. + * + * @return the GroupsOperationsClient object. + */ + public GroupsOperationsClient getGroupsOperations() { + return this.groupsOperations; + } + + /** + * The AssessmentsOperationsClient object to access its operations. + */ + private final AssessmentsOperationsClient assessmentsOperations; + + /** + * Gets the AssessmentsOperationsClient object to access its operations. + * + * @return the AssessmentsOperationsClient object. + */ + public AssessmentsOperationsClient getAssessmentsOperations() { + return this.assessmentsOperations; + } + + /** + * The AssessedMachinesOperationsClient object to access its operations. + */ + private final AssessedMachinesOperationsClient assessedMachinesOperations; + + /** + * Gets the AssessedMachinesOperationsClient object to access its operations. + * + * @return the AssessedMachinesOperationsClient object. + */ + public AssessedMachinesOperationsClient getAssessedMachinesOperations() { + return this.assessedMachinesOperations; + } + + /** + * The AvsAssessmentsOperationsClient object to access its operations. + */ + private final AvsAssessmentsOperationsClient avsAssessmentsOperations; + + /** + * Gets the AvsAssessmentsOperationsClient object to access its operations. + * + * @return the AvsAssessmentsOperationsClient object. + */ + public AvsAssessmentsOperationsClient getAvsAssessmentsOperations() { + return this.avsAssessmentsOperations; + } + + /** + * The AvsAssessedMachinesOperationsClient object to access its operations. + */ + private final AvsAssessedMachinesOperationsClient avsAssessedMachinesOperations; + + /** + * Gets the AvsAssessedMachinesOperationsClient object to access its operations. + * + * @return the AvsAssessedMachinesOperationsClient object. + */ + public AvsAssessedMachinesOperationsClient getAvsAssessedMachinesOperations() { + return this.avsAssessedMachinesOperations; + } + + /** + * The SqlAssessmentV2OperationsClient object to access its operations. + */ + private final SqlAssessmentV2OperationsClient sqlAssessmentV2Operations; + + /** + * Gets the SqlAssessmentV2OperationsClient object to access its operations. + * + * @return the SqlAssessmentV2OperationsClient object. + */ + public SqlAssessmentV2OperationsClient getSqlAssessmentV2Operations() { + return this.sqlAssessmentV2Operations; + } + + /** + * The AssessedSqlDatabaseV2OperationsClient object to access its operations. + */ + private final AssessedSqlDatabaseV2OperationsClient assessedSqlDatabaseV2Operations; + + /** + * Gets the AssessedSqlDatabaseV2OperationsClient object to access its operations. + * + * @return the AssessedSqlDatabaseV2OperationsClient object. + */ + public AssessedSqlDatabaseV2OperationsClient getAssessedSqlDatabaseV2Operations() { + return this.assessedSqlDatabaseV2Operations; + } + + /** + * The AssessedSqlInstanceV2OperationsClient object to access its operations. + */ + private final AssessedSqlInstanceV2OperationsClient assessedSqlInstanceV2Operations; + + /** + * Gets the AssessedSqlInstanceV2OperationsClient object to access its operations. + * + * @return the AssessedSqlInstanceV2OperationsClient object. + */ + public AssessedSqlInstanceV2OperationsClient getAssessedSqlInstanceV2Operations() { + return this.assessedSqlInstanceV2Operations; + } + + /** + * The AssessedSqlMachinesOperationsClient object to access its operations. + */ + private final AssessedSqlMachinesOperationsClient assessedSqlMachinesOperations; + + /** + * Gets the AssessedSqlMachinesOperationsClient object to access its operations. + * + * @return the AssessedSqlMachinesOperationsClient object. + */ + public AssessedSqlMachinesOperationsClient getAssessedSqlMachinesOperations() { + return this.assessedSqlMachinesOperations; + } + + /** + * The AssessedSqlRecommendedEntityOperationsClient object to access its operations. + */ + private final AssessedSqlRecommendedEntityOperationsClient assessedSqlRecommendedEntityOperations; + + /** + * Gets the AssessedSqlRecommendedEntityOperationsClient object to access its operations. + * + * @return the AssessedSqlRecommendedEntityOperationsClient object. + */ + public AssessedSqlRecommendedEntityOperationsClient getAssessedSqlRecommendedEntityOperations() { + return this.assessedSqlRecommendedEntityOperations; + } + + /** + * The SqlAssessmentV2SummaryOperationsClient object to access its operations. + */ + private final SqlAssessmentV2SummaryOperationsClient sqlAssessmentV2SummaryOperations; + + /** + * Gets the SqlAssessmentV2SummaryOperationsClient object to access its operations. + * + * @return the SqlAssessmentV2SummaryOperationsClient object. + */ + public SqlAssessmentV2SummaryOperationsClient getSqlAssessmentV2SummaryOperations() { + return this.sqlAssessmentV2SummaryOperations; + } + + /** + * The HypervCollectorsOperationsClient object to access its operations. + */ + private final HypervCollectorsOperationsClient hypervCollectorsOperations; + + /** + * Gets the HypervCollectorsOperationsClient object to access its operations. + * + * @return the HypervCollectorsOperationsClient object. + */ + public HypervCollectorsOperationsClient getHypervCollectorsOperations() { + return this.hypervCollectorsOperations; + } + + /** + * The ImportCollectorsOperationsClient object to access its operations. + */ + private final ImportCollectorsOperationsClient importCollectorsOperations; + + /** + * Gets the ImportCollectorsOperationsClient object to access its operations. + * + * @return the ImportCollectorsOperationsClient object. + */ + public ImportCollectorsOperationsClient getImportCollectorsOperations() { + return this.importCollectorsOperations; + } + + /** + * The MachinesOperationsClient object to access its operations. + */ + private final MachinesOperationsClient machinesOperations; + + /** + * Gets the MachinesOperationsClient object to access its operations. + * + * @return the MachinesOperationsClient object. + */ + public MachinesOperationsClient getMachinesOperations() { + return this.machinesOperations; + } + + /** + * The PrivateEndpointConnectionOperationsClient object to access its operations. + */ + private final PrivateEndpointConnectionOperationsClient privateEndpointConnectionOperations; + + /** + * Gets the PrivateEndpointConnectionOperationsClient object to access its operations. + * + * @return the PrivateEndpointConnectionOperationsClient object. + */ + public PrivateEndpointConnectionOperationsClient getPrivateEndpointConnectionOperations() { + return this.privateEndpointConnectionOperations; + } + + /** + * The PrivateLinkResourceOperationsClient object to access its operations. + */ + private final PrivateLinkResourceOperationsClient privateLinkResourceOperations; + + /** + * Gets the PrivateLinkResourceOperationsClient object to access its operations. + * + * @return the PrivateLinkResourceOperationsClient object. + */ + public PrivateLinkResourceOperationsClient getPrivateLinkResourceOperations() { + return this.privateLinkResourceOperations; + } + + /** + * The AssessmentProjectSummaryOperationsClient object to access its operations. + */ + private final AssessmentProjectSummaryOperationsClient assessmentProjectSummaryOperations; + + /** + * Gets the AssessmentProjectSummaryOperationsClient object to access its operations. + * + * @return the AssessmentProjectSummaryOperationsClient object. + */ + public AssessmentProjectSummaryOperationsClient getAssessmentProjectSummaryOperations() { + return this.assessmentProjectSummaryOperations; + } + + /** + * The ServerCollectorsOperationsClient object to access its operations. + */ + private final ServerCollectorsOperationsClient serverCollectorsOperations; + + /** + * Gets the ServerCollectorsOperationsClient object to access its operations. + * + * @return the ServerCollectorsOperationsClient object. + */ + public ServerCollectorsOperationsClient getServerCollectorsOperations() { + return this.serverCollectorsOperations; + } + + /** + * The SqlAssessmentOptionsOperationsClient object to access its operations. + */ + private final SqlAssessmentOptionsOperationsClient sqlAssessmentOptionsOperations; + + /** + * Gets the SqlAssessmentOptionsOperationsClient object to access its operations. + * + * @return the SqlAssessmentOptionsOperationsClient object. + */ + public SqlAssessmentOptionsOperationsClient getSqlAssessmentOptionsOperations() { + return this.sqlAssessmentOptionsOperations; + } + + /** + * The SqlCollectorOperationsClient object to access its operations. + */ + private final SqlCollectorOperationsClient sqlCollectorOperations; + + /** + * Gets the SqlCollectorOperationsClient object to access its operations. + * + * @return the SqlCollectorOperationsClient object. + */ + public SqlCollectorOperationsClient getSqlCollectorOperations() { + return this.sqlCollectorOperations; + } + + /** + * The VmwareCollectorsOperationsClient object to access its operations. + */ + private final VmwareCollectorsOperationsClient vmwareCollectorsOperations; + + /** + * Gets the VmwareCollectorsOperationsClient object to access its operations. + * + * @return the VmwareCollectorsOperationsClient object. + */ + public VmwareCollectorsOperationsClient getVmwareCollectorsOperations() { + return this.vmwareCollectorsOperations; + } + + /** + * Initializes an instance of MigrationAssessmentManagementClient client. + * + * @param httpPipeline The HTTP pipeline to send requests through. + * @param serializerAdapter The serializer to serialize an object into a string. + * @param defaultPollInterval The default poll interval for long-running operation. + * @param environment The Azure environment. + * @param subscriptionId The ID of the target subscription. + * @param endpoint server parameter. + */ + MigrationAssessmentManagementClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, + Duration defaultPollInterval, AzureEnvironment environment, String subscriptionId, String endpoint) { + this.httpPipeline = httpPipeline; + this.serializerAdapter = serializerAdapter; + this.defaultPollInterval = defaultPollInterval; + this.subscriptionId = subscriptionId; + this.endpoint = endpoint; + this.apiVersion = "2023-03-15"; + this.operations = new OperationsClientImpl(this); + this.assessmentProjectsOperations = new AssessmentProjectsOperationsClientImpl(this); + this.assessmentOptionsOperations = new AssessmentOptionsOperationsClientImpl(this); + this.avsAssessmentOptionsOperations = new AvsAssessmentOptionsOperationsClientImpl(this); + this.groupsOperations = new GroupsOperationsClientImpl(this); + this.assessmentsOperations = new AssessmentsOperationsClientImpl(this); + this.assessedMachinesOperations = new AssessedMachinesOperationsClientImpl(this); + this.avsAssessmentsOperations = new AvsAssessmentsOperationsClientImpl(this); + this.avsAssessedMachinesOperations = new AvsAssessedMachinesOperationsClientImpl(this); + this.sqlAssessmentV2Operations = new SqlAssessmentV2OperationsClientImpl(this); + this.assessedSqlDatabaseV2Operations = new AssessedSqlDatabaseV2OperationsClientImpl(this); + this.assessedSqlInstanceV2Operations = new AssessedSqlInstanceV2OperationsClientImpl(this); + this.assessedSqlMachinesOperations = new AssessedSqlMachinesOperationsClientImpl(this); + this.assessedSqlRecommendedEntityOperations = new AssessedSqlRecommendedEntityOperationsClientImpl(this); + this.sqlAssessmentV2SummaryOperations = new SqlAssessmentV2SummaryOperationsClientImpl(this); + this.hypervCollectorsOperations = new HypervCollectorsOperationsClientImpl(this); + this.importCollectorsOperations = new ImportCollectorsOperationsClientImpl(this); + this.machinesOperations = new MachinesOperationsClientImpl(this); + this.privateEndpointConnectionOperations = new PrivateEndpointConnectionOperationsClientImpl(this); + this.privateLinkResourceOperations = new PrivateLinkResourceOperationsClientImpl(this); + this.assessmentProjectSummaryOperations = new AssessmentProjectSummaryOperationsClientImpl(this); + this.serverCollectorsOperations = new ServerCollectorsOperationsClientImpl(this); + this.sqlAssessmentOptionsOperations = new SqlAssessmentOptionsOperationsClientImpl(this); + this.sqlCollectorOperations = new SqlCollectorOperationsClientImpl(this); + this.vmwareCollectorsOperations = new VmwareCollectorsOperationsClientImpl(this); + } + + /** + * Gets default client context. + * + * @return the default client context. + */ + public Context getContext() { + return Context.NONE; + } + + /** + * Merges default client context with provided context. + * + * @param context the context to be merged with default client context. + * @return the merged context. + */ + public Context mergeContext(Context context) { + return CoreUtils.mergeContexts(this.getContext(), context); + } + + /** + * Gets long running operation result. + * + * @param activationResponse the response of activation operation. + * @param httpPipeline the http pipeline. + * @param pollResultType type of poll result. + * @param finalResultType type of final result. + * @param context the context shared by all requests. + * @param type of poll result. + * @param type of final result. + * @return poller flux for poll result and final result. + */ + public PollerFlux, U> getLroResult(Mono>> activationResponse, + HttpPipeline httpPipeline, Type pollResultType, Type finalResultType, Context context) { + return PollerFactory.create(serializerAdapter, httpPipeline, pollResultType, finalResultType, + defaultPollInterval, activationResponse, context); + } + + /** + * Gets the final result, or an error, based on last async poll response. + * + * @param response the last async poll response. + * @param type of poll result. + * @param type of final result. + * @return the final result, or an error. + */ + public Mono getLroFinalResultOrError(AsyncPollResponse, U> response) { + if (response.getStatus() != LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { + String errorMessage; + ManagementError managementError = null; + HttpResponse errorResponse = null; + PollResult.Error lroError = response.getValue().getError(); + if (lroError != null) { + errorResponse = new HttpResponseImpl(lroError.getResponseStatusCode(), lroError.getResponseHeaders(), + lroError.getResponseBody()); + + errorMessage = response.getValue().getError().getMessage(); + String errorBody = response.getValue().getError().getResponseBody(); + if (errorBody != null) { + // try to deserialize error body to ManagementError + try { + managementError = this.getSerializerAdapter() + .deserialize(errorBody, ManagementError.class, SerializerEncoding.JSON); + if (managementError.getCode() == null || managementError.getMessage() == null) { + managementError = null; + } + } catch (IOException | RuntimeException ioe) { + LOGGER.logThrowableAsWarning(ioe); + } + } + } else { + // fallback to default error message + errorMessage = "Long running operation failed."; + } + if (managementError == null) { + // fallback to default ManagementError + managementError = new ManagementError(response.getStatus().toString(), errorMessage); + } + return Mono.error(new ManagementException(errorMessage, errorResponse, managementError)); + } else { + return response.getFinalResult(); + } + } + + private static final class HttpResponseImpl extends HttpResponse { + private final int statusCode; + + private final byte[] responseBody; + + private final HttpHeaders httpHeaders; + + HttpResponseImpl(int statusCode, HttpHeaders httpHeaders, String responseBody) { + super(null); + this.statusCode = statusCode; + this.httpHeaders = httpHeaders; + this.responseBody = responseBody == null ? null : responseBody.getBytes(StandardCharsets.UTF_8); + } + + public int getStatusCode() { + return statusCode; + } + + public String getHeaderValue(String s) { + return httpHeaders.getValue(HttpHeaderName.fromString(s)); + } + + public HttpHeaders getHeaders() { + return httpHeaders; + } + + public Flux getBody() { + return Flux.just(ByteBuffer.wrap(responseBody)); + } + + public Mono getBodyAsByteArray() { + return Mono.just(responseBody); + } + + public Mono getBodyAsString() { + return Mono.just(new String(responseBody, StandardCharsets.UTF_8)); + } + + public Mono getBodyAsString(Charset charset) { + return Mono.just(new String(responseBody, charset)); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(MigrationAssessmentManagementClientImpl.class); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/OperationImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/OperationImpl.java new file mode 100644 index 000000000000..ef17bde16642 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/OperationImpl.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.resourcemanager.migration.assessment.fluent.models.OperationInner; +import com.azure.resourcemanager.migration.assessment.models.ActionType; +import com.azure.resourcemanager.migration.assessment.models.Operation; +import com.azure.resourcemanager.migration.assessment.models.OperationDisplay; +import com.azure.resourcemanager.migration.assessment.models.Origin; + +public final class OperationImpl implements Operation { + private OperationInner innerObject; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + OperationImpl(OperationInner innerObject, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String name() { + return this.innerModel().name(); + } + + public Boolean isDataAction() { + return this.innerModel().isDataAction(); + } + + public OperationDisplay display() { + return this.innerModel().display(); + } + + public Origin origin() { + return this.innerModel().origin(); + } + + public ActionType actionType() { + return this.innerModel().actionType(); + } + + public OperationInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/OperationsClientImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/OperationsClientImpl.java new file mode 100644 index 000000000000..d4a9917f5fb2 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/OperationsClientImpl.java @@ -0,0 +1,235 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.resourcemanager.migration.assessment.fluent.OperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.OperationInner; +import com.azure.resourcemanager.migration.assessment.models.OperationListResult; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in OperationsClient. + */ +public final class OperationsClientImpl implements OperationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final OperationsService service; + + /** + * The service client containing this operation class. + */ + private final MigrationAssessmentManagementClientImpl client; + + /** + * Initializes an instance of OperationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + OperationsClientImpl(MigrationAssessmentManagementClientImpl client) { + this.service + = RestProxy.create(OperationsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for MigrationAssessmentManagementClientOperations to be used by the proxy + * service to perform REST calls. + */ + @Host("{$host}") + @ServiceInterface(name = "MigrationAssessmentM") + public interface OperationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/providers/Microsoft.Migrate/operations") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> list(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listNext(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("$host") String endpoint, @HeaderParam("Accept") String accept, Context context); + } + + /** + * List the operations for the provider. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider along with {@link PagedResponse} on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync() { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.list(this.client.getEndpoint(), this.client.getApiVersion(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), + res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List the operations for the provider. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider along with {@link PagedResponse} on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync(Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.list(this.client.getEndpoint(), this.client.getApiVersion(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List the operations for the provider. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync() { + return new PagedFlux<>(() -> listSinglePageAsync(), nextLink -> listNextSinglePageAsync(nextLink)); + } + + /** + * List the operations for the provider. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync(Context context) { + return new PagedFlux<>(() -> listSinglePageAsync(context), + nextLink -> listNextSinglePageAsync(nextLink, context)); + } + + /** + * List the operations for the provider. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list() { + return new PagedIterable<>(listAsync()); + } + + /** + * List the operations for the provider. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(Context context) { + return new PagedIterable<>(listAsync(context)); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider along with {@link PagedResponse} on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.listNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), + res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider along with {@link PagedResponse} on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listNextSinglePageAsync(String nextLink, Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/OperationsImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/OperationsImpl.java new file mode 100644 index 000000000000..16f493ba0b45 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/OperationsImpl.java @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.migration.assessment.fluent.OperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.OperationInner; +import com.azure.resourcemanager.migration.assessment.models.Operation; +import com.azure.resourcemanager.migration.assessment.models.Operations; + +public final class OperationsImpl implements Operations { + private static final ClientLogger LOGGER = new ClientLogger(OperationsImpl.class); + + private final OperationsClient innerClient; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + public OperationsImpl(OperationsClient innerClient, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public PagedIterable list() { + PagedIterable inner = this.serviceClient().list(); + return ResourceManagerUtils.mapPage(inner, inner1 -> new OperationImpl(inner1, this.manager())); + } + + public PagedIterable list(Context context) { + PagedIterable inner = this.serviceClient().list(context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new OperationImpl(inner1, this.manager())); + } + + private OperationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/PrivateEndpointConnectionImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/PrivateEndpointConnectionImpl.java new file mode 100644 index 000000000000..3871f9178080 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/PrivateEndpointConnectionImpl.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.migration.assessment.fluent.models.PrivateEndpointConnectionInner; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpointConnection; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpointConnectionProperties; + +public final class PrivateEndpointConnectionImpl implements PrivateEndpointConnection { + private PrivateEndpointConnectionInner innerObject; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + PrivateEndpointConnectionImpl(PrivateEndpointConnectionInner innerObject, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public PrivateEndpointConnectionProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public PrivateEndpointConnectionInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/PrivateEndpointConnectionOperationsClientImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/PrivateEndpointConnectionOperationsClientImpl.java new file mode 100644 index 000000000000..6a89a2404baf --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/PrivateEndpointConnectionOperationsClientImpl.java @@ -0,0 +1,852 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Put; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.core.util.polling.PollerFlux; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.migration.assessment.fluent.PrivateEndpointConnectionOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.PrivateEndpointConnectionInner; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpointConnectionListResult; +import java.nio.ByteBuffer; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in PrivateEndpointConnectionOperationsClient. + */ +public final class PrivateEndpointConnectionOperationsClientImpl implements PrivateEndpointConnectionOperationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final PrivateEndpointConnectionOperationsService service; + + /** + * The service client containing this operation class. + */ + private final MigrationAssessmentManagementClientImpl client; + + /** + * Initializes an instance of PrivateEndpointConnectionOperationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + PrivateEndpointConnectionOperationsClientImpl(MigrationAssessmentManagementClientImpl client) { + this.service = RestProxy.create(PrivateEndpointConnectionOperationsService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for + * MigrationAssessmentManagementClientPrivateEndpointConnectionOperations to be used by the proxy service to perform + * REST calls. + */ + @Host("{$host}") + @ServiceInterface(name = "MigrationAssessmentM") + public interface PrivateEndpointConnectionOperationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/privateEndpointConnections") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAssessmentProject(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/privateEndpointConnections/{privateEndpointConnectionName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("privateEndpointConnectionName") String privateEndpointConnectionName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Put("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/privateEndpointConnections/{privateEndpointConnectionName}") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> update(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("privateEndpointConnectionName") String privateEndpointConnectionName, + @BodyParam("application/json") PrivateEndpointConnectionInner resource, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Delete("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/privateEndpointConnections/{privateEndpointConnectionName}") + @ExpectedResponses({ 200, 204 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> delete(@HostParam("$host") String endpoint, @QueryParam("api-version") String apiVersion, + @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("privateEndpointConnectionName") String privateEndpointConnectionName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAssessmentProjectNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * List PrivateEndpointConnection resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PrivateEndpointConnection list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> + listByAssessmentProjectSinglePageAsync(String resourceGroupName, String projectName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByAssessmentProject(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List PrivateEndpointConnection resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PrivateEndpointConnection list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> + listByAssessmentProjectSinglePageAsync(String resourceGroupName, String projectName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByAssessmentProject(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List PrivateEndpointConnection resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PrivateEndpointConnection list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentProjectAsync(String resourceGroupName, + String projectName) { + return new PagedFlux<>(() -> listByAssessmentProjectSinglePageAsync(resourceGroupName, projectName), + nextLink -> listByAssessmentProjectNextSinglePageAsync(nextLink)); + } + + /** + * List PrivateEndpointConnection resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PrivateEndpointConnection list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentProjectAsync(String resourceGroupName, + String projectName, Context context) { + return new PagedFlux<>(() -> listByAssessmentProjectSinglePageAsync(resourceGroupName, projectName, context), + nextLink -> listByAssessmentProjectNextSinglePageAsync(nextLink, context)); + } + + /** + * List PrivateEndpointConnection resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PrivateEndpointConnection list operation as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAssessmentProject(String resourceGroupName, + String projectName) { + return new PagedIterable<>(listByAssessmentProjectAsync(resourceGroupName, projectName)); + } + + /** + * List PrivateEndpointConnection resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PrivateEndpointConnection list operation as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAssessmentProject(String resourceGroupName, + String projectName, Context context) { + return new PagedIterable<>(listByAssessmentProjectAsync(resourceGroupName, projectName, context)); + } + + /** + * Get a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a PrivateEndpointConnection along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, + String projectName, String privateEndpointConnectionName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (privateEndpointConnectionName == null) { + return Mono.error(new IllegalArgumentException( + "Parameter privateEndpointConnectionName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, privateEndpointConnectionName, accept, + context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a PrivateEndpointConnection along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, + String projectName, String privateEndpointConnectionName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (privateEndpointConnectionName == null) { + return Mono.error(new IllegalArgumentException( + "Parameter privateEndpointConnectionName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, privateEndpointConnectionName, accept, context); + } + + /** + * Get a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a PrivateEndpointConnection on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceGroupName, String projectName, + String privateEndpointConnectionName) { + return getWithResponseAsync(resourceGroupName, projectName, privateEndpointConnectionName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a PrivateEndpointConnection along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceGroupName, String projectName, + String privateEndpointConnectionName, Context context) { + return getWithResponseAsync(resourceGroupName, projectName, privateEndpointConnectionName, context).block(); + } + + /** + * Get a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a PrivateEndpointConnection. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public PrivateEndpointConnectionInner get(String resourceGroupName, String projectName, + String privateEndpointConnectionName) { + return getWithResponse(resourceGroupName, projectName, privateEndpointConnectionName, Context.NONE).getValue(); + } + + /** + * Create a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return private endpoint connection resource along with {@link Response} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> updateWithResponseAsync(String resourceGroupName, String projectName, + String privateEndpointConnectionName, PrivateEndpointConnectionInner resource) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (privateEndpointConnectionName == null) { + return Mono.error(new IllegalArgumentException( + "Parameter privateEndpointConnectionName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.update(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, privateEndpointConnectionName, + resource, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Create a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return private endpoint connection resource along with {@link Response} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> updateWithResponseAsync(String resourceGroupName, String projectName, + String privateEndpointConnectionName, PrivateEndpointConnectionInner resource, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (privateEndpointConnectionName == null) { + return Mono.error(new IllegalArgumentException( + "Parameter privateEndpointConnectionName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.update(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, privateEndpointConnectionName, resource, accept, context); + } + + /** + * Create a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of private endpoint connection resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, PrivateEndpointConnectionInner> beginUpdateAsync( + String resourceGroupName, String projectName, String privateEndpointConnectionName, + PrivateEndpointConnectionInner resource) { + Mono>> mono + = updateWithResponseAsync(resourceGroupName, projectName, privateEndpointConnectionName, resource); + return this.client.getLroResult(mono, + this.client.getHttpPipeline(), PrivateEndpointConnectionInner.class, PrivateEndpointConnectionInner.class, + this.client.getContext()); + } + + /** + * Create a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of private endpoint connection resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, PrivateEndpointConnectionInner> beginUpdateAsync( + String resourceGroupName, String projectName, String privateEndpointConnectionName, + PrivateEndpointConnectionInner resource, Context context) { + context = this.client.mergeContext(context); + Mono>> mono + = updateWithResponseAsync(resourceGroupName, projectName, privateEndpointConnectionName, resource, context); + return this.client.getLroResult(mono, + this.client.getHttpPipeline(), PrivateEndpointConnectionInner.class, PrivateEndpointConnectionInner.class, + context); + } + + /** + * Create a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of private endpoint connection resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, PrivateEndpointConnectionInner> beginUpdate( + String resourceGroupName, String projectName, String privateEndpointConnectionName, + PrivateEndpointConnectionInner resource) { + return this.beginUpdateAsync(resourceGroupName, projectName, privateEndpointConnectionName, resource) + .getSyncPoller(); + } + + /** + * Create a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of private endpoint connection resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, PrivateEndpointConnectionInner> beginUpdate( + String resourceGroupName, String projectName, String privateEndpointConnectionName, + PrivateEndpointConnectionInner resource, Context context) { + return this.beginUpdateAsync(resourceGroupName, projectName, privateEndpointConnectionName, resource, context) + .getSyncPoller(); + } + + /** + * Create a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return private endpoint connection resource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono updateAsync(String resourceGroupName, String projectName, + String privateEndpointConnectionName, PrivateEndpointConnectionInner resource) { + return beginUpdateAsync(resourceGroupName, projectName, privateEndpointConnectionName, resource).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return private endpoint connection resource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono updateAsync(String resourceGroupName, String projectName, + String privateEndpointConnectionName, PrivateEndpointConnectionInner resource, Context context) { + return beginUpdateAsync(resourceGroupName, projectName, privateEndpointConnectionName, resource, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return private endpoint connection resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public PrivateEndpointConnectionInner update(String resourceGroupName, String projectName, + String privateEndpointConnectionName, PrivateEndpointConnectionInner resource) { + return updateAsync(resourceGroupName, projectName, privateEndpointConnectionName, resource).block(); + } + + /** + * Create a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return private endpoint connection resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public PrivateEndpointConnectionInner update(String resourceGroupName, String projectName, + String privateEndpointConnectionName, PrivateEndpointConnectionInner resource, Context context) { + return updateAsync(resourceGroupName, projectName, privateEndpointConnectionName, resource, context).block(); + } + + /** + * Delete a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String projectName, + String privateEndpointConnectionName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (privateEndpointConnectionName == null) { + return Mono.error(new IllegalArgumentException( + "Parameter privateEndpointConnectionName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.delete(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, privateEndpointConnectionName, accept, + context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Delete a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String projectName, + String privateEndpointConnectionName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (privateEndpointConnectionName == null) { + return Mono.error(new IllegalArgumentException( + "Parameter privateEndpointConnectionName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.delete(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, privateEndpointConnectionName, accept, context); + } + + /** + * Delete a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono deleteAsync(String resourceGroupName, String projectName, String privateEndpointConnectionName) { + return deleteWithResponseAsync(resourceGroupName, projectName, privateEndpointConnectionName) + .flatMap(ignored -> Mono.empty()); + } + + /** + * Delete a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String resourceGroupName, String projectName, + String privateEndpointConnectionName, Context context) { + return deleteWithResponseAsync(resourceGroupName, projectName, privateEndpointConnectionName, context).block(); + } + + /** + * Delete a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String resourceGroupName, String projectName, String privateEndpointConnectionName) { + deleteWithResponse(resourceGroupName, projectName, privateEndpointConnectionName, Context.NONE); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PrivateEndpointConnection list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> + listByAssessmentProjectNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByAssessmentProjectNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PrivateEndpointConnection list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> + listByAssessmentProjectNextSinglePageAsync(String nextLink, Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listByAssessmentProjectNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/PrivateEndpointConnectionOperationsImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/PrivateEndpointConnectionOperationsImpl.java new file mode 100644 index 000000000000..d88a01e865d5 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/PrivateEndpointConnectionOperationsImpl.java @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.migration.assessment.fluent.PrivateEndpointConnectionOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.PrivateEndpointConnectionInner; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpointConnection; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpointConnectionOperations; + +public final class PrivateEndpointConnectionOperationsImpl implements PrivateEndpointConnectionOperations { + private static final ClientLogger LOGGER = new ClientLogger(PrivateEndpointConnectionOperationsImpl.class); + + private final PrivateEndpointConnectionOperationsClient innerClient; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + public PrivateEndpointConnectionOperationsImpl(PrivateEndpointConnectionOperationsClient innerClient, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public PagedIterable listByAssessmentProject(String resourceGroupName, + String projectName) { + PagedIterable inner + = this.serviceClient().listByAssessmentProject(resourceGroupName, projectName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new PrivateEndpointConnectionImpl(inner1, this.manager())); + } + + public PagedIterable listByAssessmentProject(String resourceGroupName, + String projectName, Context context) { + PagedIterable inner + = this.serviceClient().listByAssessmentProject(resourceGroupName, projectName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new PrivateEndpointConnectionImpl(inner1, this.manager())); + } + + public Response getWithResponse(String resourceGroupName, String projectName, + String privateEndpointConnectionName, Context context) { + Response inner = this.serviceClient() + .getWithResponse(resourceGroupName, projectName, privateEndpointConnectionName, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new PrivateEndpointConnectionImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public PrivateEndpointConnection get(String resourceGroupName, String projectName, + String privateEndpointConnectionName) { + PrivateEndpointConnectionInner inner + = this.serviceClient().get(resourceGroupName, projectName, privateEndpointConnectionName); + if (inner != null) { + return new PrivateEndpointConnectionImpl(inner, this.manager()); + } else { + return null; + } + } + + public PrivateEndpointConnection update(String resourceGroupName, String projectName, + String privateEndpointConnectionName, PrivateEndpointConnectionInner resource) { + PrivateEndpointConnectionInner inner + = this.serviceClient().update(resourceGroupName, projectName, privateEndpointConnectionName, resource); + if (inner != null) { + return new PrivateEndpointConnectionImpl(inner, this.manager()); + } else { + return null; + } + } + + public PrivateEndpointConnection update(String resourceGroupName, String projectName, + String privateEndpointConnectionName, PrivateEndpointConnectionInner resource, Context context) { + PrivateEndpointConnectionInner inner = this.serviceClient() + .update(resourceGroupName, projectName, privateEndpointConnectionName, resource, context); + if (inner != null) { + return new PrivateEndpointConnectionImpl(inner, this.manager()); + } else { + return null; + } + } + + public Response deleteWithResponse(String resourceGroupName, String projectName, + String privateEndpointConnectionName, Context context) { + return this.serviceClient() + .deleteWithResponse(resourceGroupName, projectName, privateEndpointConnectionName, context); + } + + public void delete(String resourceGroupName, String projectName, String privateEndpointConnectionName) { + this.serviceClient().delete(resourceGroupName, projectName, privateEndpointConnectionName); + } + + private PrivateEndpointConnectionOperationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/PrivateLinkResourceImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/PrivateLinkResourceImpl.java new file mode 100644 index 000000000000..60f26695ecc0 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/PrivateLinkResourceImpl.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.migration.assessment.fluent.models.PrivateLinkResourceInner; +import com.azure.resourcemanager.migration.assessment.models.PrivateLinkResource; +import com.azure.resourcemanager.migration.assessment.models.PrivateLinkResourceProperties; + +public final class PrivateLinkResourceImpl implements PrivateLinkResource { + private PrivateLinkResourceInner innerObject; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + PrivateLinkResourceImpl(PrivateLinkResourceInner innerObject, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public PrivateLinkResourceProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public PrivateLinkResourceInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/PrivateLinkResourceOperationsClientImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/PrivateLinkResourceOperationsClientImpl.java new file mode 100644 index 000000000000..d1861115619f --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/PrivateLinkResourceOperationsClientImpl.java @@ -0,0 +1,425 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.resourcemanager.migration.assessment.fluent.PrivateLinkResourceOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.PrivateLinkResourceInner; +import com.azure.resourcemanager.migration.assessment.models.PrivateLinkResourceListResult; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in PrivateLinkResourceOperationsClient. + */ +public final class PrivateLinkResourceOperationsClientImpl implements PrivateLinkResourceOperationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final PrivateLinkResourceOperationsService service; + + /** + * The service client containing this operation class. + */ + private final MigrationAssessmentManagementClientImpl client; + + /** + * Initializes an instance of PrivateLinkResourceOperationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + PrivateLinkResourceOperationsClientImpl(MigrationAssessmentManagementClientImpl client) { + this.service = RestProxy.create(PrivateLinkResourceOperationsService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for MigrationAssessmentManagementClientPrivateLinkResourceOperations to + * be used by the proxy service to perform REST calls. + */ + @Host("{$host}") + @ServiceInterface(name = "MigrationAssessmentM") + public interface PrivateLinkResourceOperationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/privateLinkResources") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAssessmentProject(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/privateLinkResources/{privateLinkResourceName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("privateLinkResourceName") String privateLinkResourceName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAssessmentProjectNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * List PrivateLinkResource resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PrivateLinkResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> + listByAssessmentProjectSinglePageAsync(String resourceGroupName, String projectName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByAssessmentProject(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List PrivateLinkResource resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PrivateLinkResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> + listByAssessmentProjectSinglePageAsync(String resourceGroupName, String projectName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByAssessmentProject(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List PrivateLinkResource resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PrivateLinkResource list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentProjectAsync(String resourceGroupName, + String projectName) { + return new PagedFlux<>(() -> listByAssessmentProjectSinglePageAsync(resourceGroupName, projectName), + nextLink -> listByAssessmentProjectNextSinglePageAsync(nextLink)); + } + + /** + * List PrivateLinkResource resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PrivateLinkResource list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentProjectAsync(String resourceGroupName, + String projectName, Context context) { + return new PagedFlux<>(() -> listByAssessmentProjectSinglePageAsync(resourceGroupName, projectName, context), + nextLink -> listByAssessmentProjectNextSinglePageAsync(nextLink, context)); + } + + /** + * List PrivateLinkResource resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PrivateLinkResource list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAssessmentProject(String resourceGroupName, + String projectName) { + return new PagedIterable<>(listByAssessmentProjectAsync(resourceGroupName, projectName)); + } + + /** + * List PrivateLinkResource resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PrivateLinkResource list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context) { + return new PagedIterable<>(listByAssessmentProjectAsync(resourceGroupName, projectName, context)); + } + + /** + * Get a PrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateLinkResourceName Private link resource ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a PrivateLinkResource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String privateLinkResourceName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (privateLinkResourceName == null) { + return Mono.error( + new IllegalArgumentException("Parameter privateLinkResourceName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, privateLinkResourceName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a PrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateLinkResourceName Private link resource ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a PrivateLinkResource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String privateLinkResourceName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (privateLinkResourceName == null) { + return Mono.error( + new IllegalArgumentException("Parameter privateLinkResourceName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, privateLinkResourceName, accept, context); + } + + /** + * Get a PrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateLinkResourceName Private link resource ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a PrivateLinkResource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceGroupName, String projectName, + String privateLinkResourceName) { + return getWithResponseAsync(resourceGroupName, projectName, privateLinkResourceName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a PrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateLinkResourceName Private link resource ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a PrivateLinkResource along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceGroupName, String projectName, + String privateLinkResourceName, Context context) { + return getWithResponseAsync(resourceGroupName, projectName, privateLinkResourceName, context).block(); + } + + /** + * Get a PrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateLinkResourceName Private link resource ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a PrivateLinkResource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public PrivateLinkResourceInner get(String resourceGroupName, String projectName, String privateLinkResourceName) { + return getWithResponse(resourceGroupName, projectName, privateLinkResourceName, Context.NONE).getValue(); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PrivateLinkResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByAssessmentProjectNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PrivateLinkResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listByAssessmentProjectNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/PrivateLinkResourceOperationsImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/PrivateLinkResourceOperationsImpl.java new file mode 100644 index 000000000000..60f6f4ba500f --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/PrivateLinkResourceOperationsImpl.java @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.migration.assessment.fluent.PrivateLinkResourceOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.PrivateLinkResourceInner; +import com.azure.resourcemanager.migration.assessment.models.PrivateLinkResource; +import com.azure.resourcemanager.migration.assessment.models.PrivateLinkResourceOperations; + +public final class PrivateLinkResourceOperationsImpl implements PrivateLinkResourceOperations { + private static final ClientLogger LOGGER = new ClientLogger(PrivateLinkResourceOperationsImpl.class); + + private final PrivateLinkResourceOperationsClient innerClient; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + public PrivateLinkResourceOperationsImpl(PrivateLinkResourceOperationsClient innerClient, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName) { + PagedIterable inner + = this.serviceClient().listByAssessmentProject(resourceGroupName, projectName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new PrivateLinkResourceImpl(inner1, this.manager())); + } + + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context) { + PagedIterable inner + = this.serviceClient().listByAssessmentProject(resourceGroupName, projectName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new PrivateLinkResourceImpl(inner1, this.manager())); + } + + public Response getWithResponse(String resourceGroupName, String projectName, + String privateLinkResourceName, Context context) { + Response inner + = this.serviceClient().getWithResponse(resourceGroupName, projectName, privateLinkResourceName, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new PrivateLinkResourceImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public PrivateLinkResource get(String resourceGroupName, String projectName, String privateLinkResourceName) { + PrivateLinkResourceInner inner + = this.serviceClient().get(resourceGroupName, projectName, privateLinkResourceName); + if (inner != null) { + return new PrivateLinkResourceImpl(inner, this.manager()); + } else { + return null; + } + } + + private PrivateLinkResourceOperationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/ResourceManagerUtils.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/ResourceManagerUtils.java new file mode 100644 index 000000000000..805434819488 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/ResourceManagerUtils.java @@ -0,0 +1,195 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.util.CoreUtils; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import reactor.core.publisher.Flux; + +final class ResourceManagerUtils { + private ResourceManagerUtils() { + } + + static String getValueFromIdByName(String id, String name) { + if (id == null) { + return null; + } + Iterator itr = Arrays.stream(id.split("/")).iterator(); + while (itr.hasNext()) { + String part = itr.next(); + if (part != null && !part.trim().isEmpty()) { + if (part.equalsIgnoreCase(name)) { + if (itr.hasNext()) { + return itr.next(); + } else { + return null; + } + } + } + } + return null; + } + + static String getValueFromIdByParameterName(String id, String pathTemplate, String parameterName) { + if (id == null || pathTemplate == null) { + return null; + } + String parameterNameParentheses = "{" + parameterName + "}"; + List idSegmentsReverted = Arrays.asList(id.split("/")); + List pathSegments = Arrays.asList(pathTemplate.split("/")); + Collections.reverse(idSegmentsReverted); + Iterator idItrReverted = idSegmentsReverted.iterator(); + int pathIndex = pathSegments.size(); + while (idItrReverted.hasNext() && pathIndex > 0) { + String idSegment = idItrReverted.next(); + String pathSegment = pathSegments.get(--pathIndex); + if (!CoreUtils.isNullOrEmpty(idSegment) && !CoreUtils.isNullOrEmpty(pathSegment)) { + if (pathSegment.equalsIgnoreCase(parameterNameParentheses)) { + if (pathIndex == 0 || (pathIndex == 1 && pathSegments.get(0).isEmpty())) { + List segments = new ArrayList<>(); + segments.add(idSegment); + idItrReverted.forEachRemaining(segments::add); + Collections.reverse(segments); + if (!segments.isEmpty() && segments.get(0).isEmpty()) { + segments.remove(0); + } + return String.join("/", segments); + } else { + return idSegment; + } + } + } + } + return null; + } + + static PagedIterable mapPage(PagedIterable pageIterable, Function mapper) { + return new PagedIterableImpl<>(pageIterable, mapper); + } + + private static final class PagedIterableImpl extends PagedIterable { + + private final PagedIterable pagedIterable; + private final Function mapper; + private final Function, PagedResponse> pageMapper; + + private PagedIterableImpl(PagedIterable pagedIterable, Function mapper) { + super(PagedFlux.create(() -> (continuationToken, pageSize) -> Flux + .fromStream(pagedIterable.streamByPage().map(getPageMapper(mapper))))); + this.pagedIterable = pagedIterable; + this.mapper = mapper; + this.pageMapper = getPageMapper(mapper); + } + + private static Function, PagedResponse> getPageMapper(Function mapper) { + return page -> new PagedResponseBase(page.getRequest(), page.getStatusCode(), page.getHeaders(), + page.getElements().stream().map(mapper).collect(Collectors.toList()), page.getContinuationToken(), + null); + } + + @Override + public Stream stream() { + return pagedIterable.stream().map(mapper); + } + + @Override + public Stream> streamByPage() { + return pagedIterable.streamByPage().map(pageMapper); + } + + @Override + public Stream> streamByPage(String continuationToken) { + return pagedIterable.streamByPage(continuationToken).map(pageMapper); + } + + @Override + public Stream> streamByPage(int preferredPageSize) { + return pagedIterable.streamByPage(preferredPageSize).map(pageMapper); + } + + @Override + public Stream> streamByPage(String continuationToken, int preferredPageSize) { + return pagedIterable.streamByPage(continuationToken, preferredPageSize).map(pageMapper); + } + + @Override + public Iterator iterator() { + return new IteratorImpl<>(pagedIterable.iterator(), mapper); + } + + @Override + public Iterable> iterableByPage() { + return new IterableImpl<>(pagedIterable.iterableByPage(), pageMapper); + } + + @Override + public Iterable> iterableByPage(String continuationToken) { + return new IterableImpl<>(pagedIterable.iterableByPage(continuationToken), pageMapper); + } + + @Override + public Iterable> iterableByPage(int preferredPageSize) { + return new IterableImpl<>(pagedIterable.iterableByPage(preferredPageSize), pageMapper); + } + + @Override + public Iterable> iterableByPage(String continuationToken, int preferredPageSize) { + return new IterableImpl<>(pagedIterable.iterableByPage(continuationToken, preferredPageSize), pageMapper); + } + } + + private static final class IteratorImpl implements Iterator { + + private final Iterator iterator; + private final Function mapper; + + private IteratorImpl(Iterator iterator, Function mapper) { + this.iterator = iterator; + this.mapper = mapper; + } + + @Override + public boolean hasNext() { + return iterator.hasNext(); + } + + @Override + public S next() { + return mapper.apply(iterator.next()); + } + + @Override + public void remove() { + iterator.remove(); + } + } + + private static final class IterableImpl implements Iterable { + + private final Iterable iterable; + private final Function mapper; + + private IterableImpl(Iterable iterable, Function mapper) { + this.iterable = iterable; + this.mapper = mapper; + } + + @Override + public Iterator iterator() { + return new IteratorImpl<>(iterable.iterator(), mapper); + } + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/ServerCollectorImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/ServerCollectorImpl.java new file mode 100644 index 000000000000..5fee005575ae --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/ServerCollectorImpl.java @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.ServerCollectorInner; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBaseWithAgent; +import com.azure.resourcemanager.migration.assessment.models.ServerCollector; + +public final class ServerCollectorImpl implements ServerCollector, ServerCollector.Definition { + private ServerCollectorInner innerObject; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + ServerCollectorImpl(ServerCollectorInner innerObject, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public CollectorPropertiesBaseWithAgent properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public ServerCollectorInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } + + private String resourceGroupName; + + private String projectName; + + private String serverCollectorName; + + public ServerCollectorImpl withExistingAssessmentProject(String resourceGroupName, String projectName) { + this.resourceGroupName = resourceGroupName; + this.projectName = projectName; + return this; + } + + public ServerCollector create() { + this.innerObject = serviceManager.serviceClient() + .getServerCollectorsOperations() + .create(resourceGroupName, projectName, serverCollectorName, this.innerModel(), Context.NONE); + return this; + } + + public ServerCollector create(Context context) { + this.innerObject = serviceManager.serviceClient() + .getServerCollectorsOperations() + .create(resourceGroupName, projectName, serverCollectorName, this.innerModel(), context); + return this; + } + + ServerCollectorImpl(String name, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = new ServerCollectorInner(); + this.serviceManager = serviceManager; + this.serverCollectorName = name; + } + + public ServerCollector refresh() { + this.innerObject = serviceManager.serviceClient() + .getServerCollectorsOperations() + .getWithResponse(resourceGroupName, projectName, serverCollectorName, Context.NONE) + .getValue(); + return this; + } + + public ServerCollector refresh(Context context) { + this.innerObject = serviceManager.serviceClient() + .getServerCollectorsOperations() + .getWithResponse(resourceGroupName, projectName, serverCollectorName, context) + .getValue(); + return this; + } + + public ServerCollectorImpl withProperties(CollectorPropertiesBaseWithAgent properties) { + this.innerModel().withProperties(properties); + return this; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/ServerCollectorsOperationsClientImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/ServerCollectorsOperationsClientImpl.java new file mode 100644 index 000000000000..124d30ad2fa9 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/ServerCollectorsOperationsClientImpl.java @@ -0,0 +1,835 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Put; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.core.util.polling.PollerFlux; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.migration.assessment.fluent.ServerCollectorsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.ServerCollectorInner; +import com.azure.resourcemanager.migration.assessment.models.ServerCollectorListResult; +import java.nio.ByteBuffer; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in ServerCollectorsOperationsClient. + */ +public final class ServerCollectorsOperationsClientImpl implements ServerCollectorsOperationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final ServerCollectorsOperationsService service; + + /** + * The service client containing this operation class. + */ + private final MigrationAssessmentManagementClientImpl client; + + /** + * Initializes an instance of ServerCollectorsOperationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + ServerCollectorsOperationsClientImpl(MigrationAssessmentManagementClientImpl client) { + this.service = RestProxy.create(ServerCollectorsOperationsService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for MigrationAssessmentManagementClientServerCollectorsOperations to be + * used by the proxy service to perform REST calls. + */ + @Host("{$host}") + @ServiceInterface(name = "MigrationAssessmentM") + public interface ServerCollectorsOperationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/servercollectors") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAssessmentProject(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/servercollectors/{serverCollectorName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("serverCollectorName") String serverCollectorName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Put("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/servercollectors/{serverCollectorName}") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> create(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("serverCollectorName") String serverCollectorName, + @BodyParam("application/json") ServerCollectorInner resource, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Delete("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/servercollectors/{serverCollectorName}") + @ExpectedResponses({ 200, 204 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> delete(@HostParam("$host") String endpoint, @QueryParam("api-version") String apiVersion, + @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("serverCollectorName") String serverCollectorName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAssessmentProjectNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * List ServerCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ServerCollector list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectSinglePageAsync(String resourceGroupName, + String projectName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByAssessmentProject(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List ServerCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ServerCollector list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectSinglePageAsync(String resourceGroupName, + String projectName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByAssessmentProject(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List ServerCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ServerCollector list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentProjectAsync(String resourceGroupName, String projectName) { + return new PagedFlux<>(() -> listByAssessmentProjectSinglePageAsync(resourceGroupName, projectName), + nextLink -> listByAssessmentProjectNextSinglePageAsync(nextLink)); + } + + /** + * List ServerCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ServerCollector list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentProjectAsync(String resourceGroupName, String projectName, + Context context) { + return new PagedFlux<>(() -> listByAssessmentProjectSinglePageAsync(resourceGroupName, projectName, context), + nextLink -> listByAssessmentProjectNextSinglePageAsync(nextLink, context)); + } + + /** + * List ServerCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ServerCollector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName) { + return new PagedIterable<>(listByAssessmentProjectAsync(resourceGroupName, projectName)); + } + + /** + * List ServerCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ServerCollector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context) { + return new PagedIterable<>(listByAssessmentProjectAsync(resourceGroupName, projectName, context)); + } + + /** + * Get a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ServerCollector along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String serverCollectorName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (serverCollectorName == null) { + return Mono + .error(new IllegalArgumentException("Parameter serverCollectorName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, serverCollectorName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ServerCollector along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String serverCollectorName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (serverCollectorName == null) { + return Mono + .error(new IllegalArgumentException("Parameter serverCollectorName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, serverCollectorName, accept, context); + } + + /** + * Get a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ServerCollector on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceGroupName, String projectName, + String serverCollectorName) { + return getWithResponseAsync(resourceGroupName, projectName, serverCollectorName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ServerCollector along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceGroupName, String projectName, + String serverCollectorName, Context context) { + return getWithResponseAsync(resourceGroupName, projectName, serverCollectorName, context).block(); + } + + /** + * Get a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ServerCollector. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public ServerCollectorInner get(String resourceGroupName, String projectName, String serverCollectorName) { + return getWithResponse(resourceGroupName, projectName, serverCollectorName, Context.NONE).getValue(); + } + + /** + * Create a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return physical server collector resource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createWithResponseAsync(String resourceGroupName, String projectName, + String serverCollectorName, ServerCollectorInner resource) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (serverCollectorName == null) { + return Mono + .error(new IllegalArgumentException("Parameter serverCollectorName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.create(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, serverCollectorName, resource, accept, + context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Create a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return physical server collector resource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createWithResponseAsync(String resourceGroupName, String projectName, + String serverCollectorName, ServerCollectorInner resource, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (serverCollectorName == null) { + return Mono + .error(new IllegalArgumentException("Parameter serverCollectorName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.create(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, serverCollectorName, resource, accept, context); + } + + /** + * Create a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of physical server collector resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, ServerCollectorInner> beginCreateAsync( + String resourceGroupName, String projectName, String serverCollectorName, ServerCollectorInner resource) { + Mono>> mono + = createWithResponseAsync(resourceGroupName, projectName, serverCollectorName, resource); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + ServerCollectorInner.class, ServerCollectorInner.class, this.client.getContext()); + } + + /** + * Create a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of physical server collector resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, ServerCollectorInner> beginCreateAsync( + String resourceGroupName, String projectName, String serverCollectorName, ServerCollectorInner resource, + Context context) { + context = this.client.mergeContext(context); + Mono>> mono + = createWithResponseAsync(resourceGroupName, projectName, serverCollectorName, resource, context); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + ServerCollectorInner.class, ServerCollectorInner.class, context); + } + + /** + * Create a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of physical server collector resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, ServerCollectorInner> beginCreate(String resourceGroupName, + String projectName, String serverCollectorName, ServerCollectorInner resource) { + return this.beginCreateAsync(resourceGroupName, projectName, serverCollectorName, resource).getSyncPoller(); + } + + /** + * Create a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of physical server collector resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, ServerCollectorInner> beginCreate(String resourceGroupName, + String projectName, String serverCollectorName, ServerCollectorInner resource, Context context) { + return this.beginCreateAsync(resourceGroupName, projectName, serverCollectorName, resource, context) + .getSyncPoller(); + } + + /** + * Create a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return physical server collector resource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createAsync(String resourceGroupName, String projectName, + String serverCollectorName, ServerCollectorInner resource) { + return beginCreateAsync(resourceGroupName, projectName, serverCollectorName, resource).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return physical server collector resource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createAsync(String resourceGroupName, String projectName, + String serverCollectorName, ServerCollectorInner resource, Context context) { + return beginCreateAsync(resourceGroupName, projectName, serverCollectorName, resource, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return physical server collector resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public ServerCollectorInner create(String resourceGroupName, String projectName, String serverCollectorName, + ServerCollectorInner resource) { + return createAsync(resourceGroupName, projectName, serverCollectorName, resource).block(); + } + + /** + * Create a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return physical server collector resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public ServerCollectorInner create(String resourceGroupName, String projectName, String serverCollectorName, + ServerCollectorInner resource, Context context) { + return createAsync(resourceGroupName, projectName, serverCollectorName, resource, context).block(); + } + + /** + * Delete a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String projectName, + String serverCollectorName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (serverCollectorName == null) { + return Mono + .error(new IllegalArgumentException("Parameter serverCollectorName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.delete(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, serverCollectorName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Delete a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String projectName, + String serverCollectorName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (serverCollectorName == null) { + return Mono + .error(new IllegalArgumentException("Parameter serverCollectorName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.delete(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, serverCollectorName, accept, context); + } + + /** + * Delete a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono deleteAsync(String resourceGroupName, String projectName, String serverCollectorName) { + return deleteWithResponseAsync(resourceGroupName, projectName, serverCollectorName) + .flatMap(ignored -> Mono.empty()); + } + + /** + * Delete a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String resourceGroupName, String projectName, String serverCollectorName, + Context context) { + return deleteWithResponseAsync(resourceGroupName, projectName, serverCollectorName, context).block(); + } + + /** + * Delete a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String resourceGroupName, String projectName, String serverCollectorName) { + deleteWithResponse(resourceGroupName, projectName, serverCollectorName, Context.NONE); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ServerCollector list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByAssessmentProjectNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ServerCollector list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listByAssessmentProjectNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/ServerCollectorsOperationsImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/ServerCollectorsOperationsImpl.java new file mode 100644 index 000000000000..33410176828a --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/ServerCollectorsOperationsImpl.java @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.migration.assessment.fluent.ServerCollectorsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.ServerCollectorInner; +import com.azure.resourcemanager.migration.assessment.models.ServerCollector; +import com.azure.resourcemanager.migration.assessment.models.ServerCollectorsOperations; + +public final class ServerCollectorsOperationsImpl implements ServerCollectorsOperations { + private static final ClientLogger LOGGER = new ClientLogger(ServerCollectorsOperationsImpl.class); + + private final ServerCollectorsOperationsClient innerClient; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + public ServerCollectorsOperationsImpl(ServerCollectorsOperationsClient innerClient, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName) { + PagedIterable inner + = this.serviceClient().listByAssessmentProject(resourceGroupName, projectName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new ServerCollectorImpl(inner1, this.manager())); + } + + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context) { + PagedIterable inner + = this.serviceClient().listByAssessmentProject(resourceGroupName, projectName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new ServerCollectorImpl(inner1, this.manager())); + } + + public Response getWithResponse(String resourceGroupName, String projectName, + String serverCollectorName, Context context) { + Response inner + = this.serviceClient().getWithResponse(resourceGroupName, projectName, serverCollectorName, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new ServerCollectorImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public ServerCollector get(String resourceGroupName, String projectName, String serverCollectorName) { + ServerCollectorInner inner = this.serviceClient().get(resourceGroupName, projectName, serverCollectorName); + if (inner != null) { + return new ServerCollectorImpl(inner, this.manager()); + } else { + return null; + } + } + + public Response deleteWithResponse(String resourceGroupName, String projectName, String serverCollectorName, + Context context) { + return this.serviceClient().deleteWithResponse(resourceGroupName, projectName, serverCollectorName, context); + } + + public void delete(String resourceGroupName, String projectName, String serverCollectorName) { + this.serviceClient().delete(resourceGroupName, projectName, serverCollectorName); + } + + public ServerCollector getById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String serverCollectorName = ResourceManagerUtils.getValueFromIdByName(id, "servercollectors"); + if (serverCollectorName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'servercollectors'.", id))); + } + return this.getWithResponse(resourceGroupName, projectName, serverCollectorName, Context.NONE).getValue(); + } + + public Response getByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String serverCollectorName = ResourceManagerUtils.getValueFromIdByName(id, "servercollectors"); + if (serverCollectorName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'servercollectors'.", id))); + } + return this.getWithResponse(resourceGroupName, projectName, serverCollectorName, context); + } + + public void deleteById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String serverCollectorName = ResourceManagerUtils.getValueFromIdByName(id, "servercollectors"); + if (serverCollectorName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'servercollectors'.", id))); + } + this.deleteWithResponse(resourceGroupName, projectName, serverCollectorName, Context.NONE); + } + + public Response deleteByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String serverCollectorName = ResourceManagerUtils.getValueFromIdByName(id, "servercollectors"); + if (serverCollectorName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'servercollectors'.", id))); + } + return this.deleteWithResponse(resourceGroupName, projectName, serverCollectorName, context); + } + + private ServerCollectorsOperationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } + + public ServerCollectorImpl define(String name) { + return new ServerCollectorImpl(name, this.manager()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlAssessmentOptionsImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlAssessmentOptionsImpl.java new file mode 100644 index 000000000000..36897088f726 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlAssessmentOptionsImpl.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlAssessmentOptionsInner; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentOptions; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentOptionsProperties; + +public final class SqlAssessmentOptionsImpl implements SqlAssessmentOptions { + private SqlAssessmentOptionsInner innerObject; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + SqlAssessmentOptionsImpl(SqlAssessmentOptionsInner innerObject, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public SqlAssessmentOptionsProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public SqlAssessmentOptionsInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlAssessmentOptionsOperationsClientImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlAssessmentOptionsOperationsClientImpl.java new file mode 100644 index 000000000000..dad284cf7564 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlAssessmentOptionsOperationsClientImpl.java @@ -0,0 +1,425 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.resourcemanager.migration.assessment.fluent.SqlAssessmentOptionsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlAssessmentOptionsInner; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentOptionsListResult; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in SqlAssessmentOptionsOperationsClient. + */ +public final class SqlAssessmentOptionsOperationsClientImpl implements SqlAssessmentOptionsOperationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final SqlAssessmentOptionsOperationsService service; + + /** + * The service client containing this operation class. + */ + private final MigrationAssessmentManagementClientImpl client; + + /** + * Initializes an instance of SqlAssessmentOptionsOperationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + SqlAssessmentOptionsOperationsClientImpl(MigrationAssessmentManagementClientImpl client) { + this.service = RestProxy.create(SqlAssessmentOptionsOperationsService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for MigrationAssessmentManagementClientSqlAssessmentOptionsOperations to + * be used by the proxy service to perform REST calls. + */ + @Host("{$host}") + @ServiceInterface(name = "MigrationAssessmentM") + public interface SqlAssessmentOptionsOperationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/sqlAssessmentOptions") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAssessmentProject(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/sqlAssessmentOptions/{assessmentOptionsName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("assessmentOptionsName") String assessmentOptionsName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAssessmentProjectNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * List SqlAssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentOptions list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> + listByAssessmentProjectSinglePageAsync(String resourceGroupName, String projectName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByAssessmentProject(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List SqlAssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentOptions list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> + listByAssessmentProjectSinglePageAsync(String resourceGroupName, String projectName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByAssessmentProject(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List SqlAssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentOptions list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentProjectAsync(String resourceGroupName, + String projectName) { + return new PagedFlux<>(() -> listByAssessmentProjectSinglePageAsync(resourceGroupName, projectName), + nextLink -> listByAssessmentProjectNextSinglePageAsync(nextLink)); + } + + /** + * List SqlAssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentOptions list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentProjectAsync(String resourceGroupName, + String projectName, Context context) { + return new PagedFlux<>(() -> listByAssessmentProjectSinglePageAsync(resourceGroupName, projectName, context), + nextLink -> listByAssessmentProjectNextSinglePageAsync(nextLink, context)); + } + + /** + * List SqlAssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentOptions list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAssessmentProject(String resourceGroupName, + String projectName) { + return new PagedIterable<>(listByAssessmentProjectAsync(resourceGroupName, projectName)); + } + + /** + * List SqlAssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentOptions list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAssessmentProject(String resourceGroupName, + String projectName, Context context) { + return new PagedIterable<>(listByAssessmentProjectAsync(resourceGroupName, projectName, context)); + } + + /** + * Get a SqlAssessmentOptions. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param assessmentOptionsName Sql assessment options ARM name. Accepted values is 'default'. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlAssessmentOptions along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String assessmentOptionsName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (assessmentOptionsName == null) { + return Mono + .error(new IllegalArgumentException("Parameter assessmentOptionsName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, assessmentOptionsName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a SqlAssessmentOptions. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param assessmentOptionsName Sql assessment options ARM name. Accepted values is 'default'. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlAssessmentOptions along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String assessmentOptionsName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (assessmentOptionsName == null) { + return Mono + .error(new IllegalArgumentException("Parameter assessmentOptionsName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, assessmentOptionsName, accept, context); + } + + /** + * Get a SqlAssessmentOptions. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param assessmentOptionsName Sql assessment options ARM name. Accepted values is 'default'. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlAssessmentOptions on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceGroupName, String projectName, + String assessmentOptionsName) { + return getWithResponseAsync(resourceGroupName, projectName, assessmentOptionsName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a SqlAssessmentOptions. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param assessmentOptionsName Sql assessment options ARM name. Accepted values is 'default'. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlAssessmentOptions along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceGroupName, String projectName, + String assessmentOptionsName, Context context) { + return getWithResponseAsync(resourceGroupName, projectName, assessmentOptionsName, context).block(); + } + + /** + * Get a SqlAssessmentOptions. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param assessmentOptionsName Sql assessment options ARM name. Accepted values is 'default'. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlAssessmentOptions. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public SqlAssessmentOptionsInner get(String resourceGroupName, String projectName, String assessmentOptionsName) { + return getWithResponse(resourceGroupName, projectName, assessmentOptionsName, Context.NONE).getValue(); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentOptions list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByAssessmentProjectNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentOptions list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listByAssessmentProjectNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlAssessmentOptionsOperationsImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlAssessmentOptionsOperationsImpl.java new file mode 100644 index 000000000000..00c0dd2a829e --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlAssessmentOptionsOperationsImpl.java @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.migration.assessment.fluent.SqlAssessmentOptionsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlAssessmentOptionsInner; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentOptions; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentOptionsOperations; + +public final class SqlAssessmentOptionsOperationsImpl implements SqlAssessmentOptionsOperations { + private static final ClientLogger LOGGER = new ClientLogger(SqlAssessmentOptionsOperationsImpl.class); + + private final SqlAssessmentOptionsOperationsClient innerClient; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + public SqlAssessmentOptionsOperationsImpl(SqlAssessmentOptionsOperationsClient innerClient, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName) { + PagedIterable inner + = this.serviceClient().listByAssessmentProject(resourceGroupName, projectName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new SqlAssessmentOptionsImpl(inner1, this.manager())); + } + + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context) { + PagedIterable inner + = this.serviceClient().listByAssessmentProject(resourceGroupName, projectName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new SqlAssessmentOptionsImpl(inner1, this.manager())); + } + + public Response getWithResponse(String resourceGroupName, String projectName, + String assessmentOptionsName, Context context) { + Response inner + = this.serviceClient().getWithResponse(resourceGroupName, projectName, assessmentOptionsName, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new SqlAssessmentOptionsImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public SqlAssessmentOptions get(String resourceGroupName, String projectName, String assessmentOptionsName) { + SqlAssessmentOptionsInner inner + = this.serviceClient().get(resourceGroupName, projectName, assessmentOptionsName); + if (inner != null) { + return new SqlAssessmentOptionsImpl(inner, this.manager()); + } else { + return null; + } + } + + private SqlAssessmentOptionsOperationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlAssessmentV2Impl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlAssessmentV2Impl.java new file mode 100644 index 000000000000..fb43e197c6d2 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlAssessmentV2Impl.java @@ -0,0 +1,119 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlAssessmentV2Inner; +import com.azure.resourcemanager.migration.assessment.models.DownloadUrl; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentV2; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentV2Properties; + +public final class SqlAssessmentV2Impl implements SqlAssessmentV2, SqlAssessmentV2.Definition { + private SqlAssessmentV2Inner innerObject; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + SqlAssessmentV2Impl(SqlAssessmentV2Inner innerObject, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public SqlAssessmentV2Properties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public SqlAssessmentV2Inner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } + + private String resourceGroupName; + + private String projectName; + + private String groupName; + + private String assessmentName; + + public SqlAssessmentV2Impl withExistingGroup(String resourceGroupName, String projectName, String groupName) { + this.resourceGroupName = resourceGroupName; + this.projectName = projectName; + this.groupName = groupName; + return this; + } + + public SqlAssessmentV2 create() { + this.innerObject = serviceManager.serviceClient() + .getSqlAssessmentV2Operations() + .create(resourceGroupName, projectName, groupName, assessmentName, this.innerModel(), Context.NONE); + return this; + } + + public SqlAssessmentV2 create(Context context) { + this.innerObject = serviceManager.serviceClient() + .getSqlAssessmentV2Operations() + .create(resourceGroupName, projectName, groupName, assessmentName, this.innerModel(), context); + return this; + } + + SqlAssessmentV2Impl(String name, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = new SqlAssessmentV2Inner(); + this.serviceManager = serviceManager; + this.assessmentName = name; + } + + public SqlAssessmentV2 refresh() { + this.innerObject = serviceManager.serviceClient() + .getSqlAssessmentV2Operations() + .getWithResponse(resourceGroupName, projectName, groupName, assessmentName, Context.NONE) + .getValue(); + return this; + } + + public SqlAssessmentV2 refresh(Context context) { + this.innerObject = serviceManager.serviceClient() + .getSqlAssessmentV2Operations() + .getWithResponse(resourceGroupName, projectName, groupName, assessmentName, context) + .getValue(); + return this; + } + + public DownloadUrl downloadUrl(Object body) { + return serviceManager.sqlAssessmentV2Operations() + .downloadUrl(resourceGroupName, projectName, groupName, assessmentName, body); + } + + public DownloadUrl downloadUrl(Object body, Context context) { + return serviceManager.sqlAssessmentV2Operations() + .downloadUrl(resourceGroupName, projectName, groupName, assessmentName, body, context); + } + + public SqlAssessmentV2Impl withProperties(SqlAssessmentV2Properties properties) { + this.innerModel().withProperties(properties); + return this; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlAssessmentV2OperationsClientImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlAssessmentV2OperationsClientImpl.java new file mode 100644 index 000000000000..ffb46ab80a25 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlAssessmentV2OperationsClientImpl.java @@ -0,0 +1,1181 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Post; +import com.azure.core.annotation.Put; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.core.util.polling.PollerFlux; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.migration.assessment.fluent.SqlAssessmentV2OperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.DownloadUrlInner; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlAssessmentV2Inner; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentV2ListResult; +import java.nio.ByteBuffer; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in SqlAssessmentV2OperationsClient. + */ +public final class SqlAssessmentV2OperationsClientImpl implements SqlAssessmentV2OperationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final SqlAssessmentV2OperationsService service; + + /** + * The service client containing this operation class. + */ + private final MigrationAssessmentManagementClientImpl client; + + /** + * Initializes an instance of SqlAssessmentV2OperationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + SqlAssessmentV2OperationsClientImpl(MigrationAssessmentManagementClientImpl client) { + this.service = RestProxy.create(SqlAssessmentV2OperationsService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for MigrationAssessmentManagementClientSqlAssessmentV2Operations to be + * used by the proxy service to perform REST calls. + */ + @Host("{$host}") + @ServiceInterface(name = "MigrationAssessmentM") + public interface SqlAssessmentV2OperationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/sqlAssessments") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByGroup(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/sqlAssessments/{assessmentName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @PathParam("assessmentName") String assessmentName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Put("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/sqlAssessments/{assessmentName}") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> create(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @PathParam("assessmentName") String assessmentName, + @BodyParam("application/json") SqlAssessmentV2Inner resource, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Delete("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/sqlAssessments/{assessmentName}") + @ExpectedResponses({ 200, 204 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> delete(@HostParam("$host") String endpoint, @QueryParam("api-version") String apiVersion, + @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @PathParam("assessmentName") String assessmentName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Post("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/sqlAssessments/{assessmentName}/downloadUrl") + @ExpectedResponses({ 200, 202 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> downloadUrl(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @PathParam("assessmentName") String assessmentName, + @BodyParam("application/json") Object body, @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByGroupNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * List SqlAssessmentV2 resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentV2 list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByGroupSinglePageAsync(String resourceGroupName, + String projectName, String groupName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listByGroup(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List SqlAssessmentV2 resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentV2 list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByGroupSinglePageAsync(String resourceGroupName, + String projectName, String groupName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByGroup(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, groupName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List SqlAssessmentV2 resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentV2 list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByGroupAsync(String resourceGroupName, String projectName, + String groupName) { + return new PagedFlux<>(() -> listByGroupSinglePageAsync(resourceGroupName, projectName, groupName), + nextLink -> listByGroupNextSinglePageAsync(nextLink)); + } + + /** + * List SqlAssessmentV2 resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentV2 list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByGroupAsync(String resourceGroupName, String projectName, + String groupName, Context context) { + return new PagedFlux<>(() -> listByGroupSinglePageAsync(resourceGroupName, projectName, groupName, context), + nextLink -> listByGroupNextSinglePageAsync(nextLink, context)); + } + + /** + * List SqlAssessmentV2 resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentV2 list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByGroup(String resourceGroupName, String projectName, + String groupName) { + return new PagedIterable<>(listByGroupAsync(resourceGroupName, projectName, groupName)); + } + + /** + * List SqlAssessmentV2 resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentV2 list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByGroup(String resourceGroupName, String projectName, + String groupName, Context context) { + return new PagedIterable<>(listByGroupAsync(resourceGroupName, projectName, groupName, context)); + } + + /** + * Get a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlAssessmentV2 along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, assessmentName, accept, + context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlAssessmentV2 along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, groupName, assessmentName, accept, context); + } + + /** + * Get a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlAssessmentV2 on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName) { + return getWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlAssessmentV2 along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceGroupName, String projectName, + String groupName, String assessmentName, Context context) { + return getWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, context).block(); + } + + /** + * Get a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlAssessmentV2. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public SqlAssessmentV2Inner get(String resourceGroupName, String projectName, String groupName, + String assessmentName) { + return getWithResponse(resourceGroupName, projectName, groupName, assessmentName, Context.NONE).getValue(); + } + + /** + * Create a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return sQL Assessment REST resource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createWithResponseAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName, SqlAssessmentV2Inner resource) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.create(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, assessmentName, resource, + accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Create a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return sQL Assessment REST resource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createWithResponseAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName, SqlAssessmentV2Inner resource, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.create(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, groupName, assessmentName, resource, accept, context); + } + + /** + * Create a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of sQL Assessment REST resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, SqlAssessmentV2Inner> beginCreateAsync( + String resourceGroupName, String projectName, String groupName, String assessmentName, + SqlAssessmentV2Inner resource) { + Mono>> mono + = createWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, resource); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + SqlAssessmentV2Inner.class, SqlAssessmentV2Inner.class, this.client.getContext()); + } + + /** + * Create a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of sQL Assessment REST resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, SqlAssessmentV2Inner> beginCreateAsync( + String resourceGroupName, String projectName, String groupName, String assessmentName, + SqlAssessmentV2Inner resource, Context context) { + context = this.client.mergeContext(context); + Mono>> mono + = createWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, resource, context); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + SqlAssessmentV2Inner.class, SqlAssessmentV2Inner.class, context); + } + + /** + * Create a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of sQL Assessment REST resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, SqlAssessmentV2Inner> beginCreate(String resourceGroupName, + String projectName, String groupName, String assessmentName, SqlAssessmentV2Inner resource) { + return this.beginCreateAsync(resourceGroupName, projectName, groupName, assessmentName, resource) + .getSyncPoller(); + } + + /** + * Create a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of sQL Assessment REST resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, SqlAssessmentV2Inner> beginCreate(String resourceGroupName, + String projectName, String groupName, String assessmentName, SqlAssessmentV2Inner resource, Context context) { + return this.beginCreateAsync(resourceGroupName, projectName, groupName, assessmentName, resource, context) + .getSyncPoller(); + } + + /** + * Create a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return sQL Assessment REST resource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName, SqlAssessmentV2Inner resource) { + return beginCreateAsync(resourceGroupName, projectName, groupName, assessmentName, resource).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return sQL Assessment REST resource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName, SqlAssessmentV2Inner resource, Context context) { + return beginCreateAsync(resourceGroupName, projectName, groupName, assessmentName, resource, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return sQL Assessment REST resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public SqlAssessmentV2Inner create(String resourceGroupName, String projectName, String groupName, + String assessmentName, SqlAssessmentV2Inner resource) { + return createAsync(resourceGroupName, projectName, groupName, assessmentName, resource).block(); + } + + /** + * Create a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return sQL Assessment REST resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public SqlAssessmentV2Inner create(String resourceGroupName, String projectName, String groupName, + String assessmentName, SqlAssessmentV2Inner resource, Context context) { + return createAsync(resourceGroupName, projectName, groupName, assessmentName, resource, context).block(); + } + + /** + * Delete a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.delete(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, assessmentName, accept, + context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Delete a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.delete(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, groupName, assessmentName, accept, context); + } + + /** + * Delete a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono deleteAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName) { + return deleteWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName) + .flatMap(ignored -> Mono.empty()); + } + + /** + * Delete a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, Context context) { + return deleteWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, context).block(); + } + + /** + * Delete a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String resourceGroupName, String projectName, String groupName, String assessmentName) { + deleteWithResponse(resourceGroupName, projectName, groupName, assessmentName, Context.NONE); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format along with {@link Response} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> downloadUrlWithResponseAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName, Object body) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + if (body == null) { + return Mono.error(new IllegalArgumentException("Parameter body is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.downloadUrl(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, assessmentName, body, + accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format along with {@link Response} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> downloadUrlWithResponseAsync(String resourceGroupName, String projectName, + String groupName, String assessmentName, Object body, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + if (body == null) { + return Mono.error(new IllegalArgumentException("Parameter body is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.downloadUrl(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, assessmentName, body, accept, + context); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, DownloadUrlInner> beginDownloadUrlAsync(String resourceGroupName, + String projectName, String groupName, String assessmentName, Object body) { + Mono>> mono + = downloadUrlWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, body); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + DownloadUrlInner.class, DownloadUrlInner.class, this.client.getContext()); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, DownloadUrlInner> beginDownloadUrlAsync(String resourceGroupName, + String projectName, String groupName, String assessmentName, Object body, Context context) { + context = this.client.mergeContext(context); + Mono>> mono + = downloadUrlWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, body, context); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + DownloadUrlInner.class, DownloadUrlInner.class, context); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, DownloadUrlInner> beginDownloadUrl(String resourceGroupName, + String projectName, String groupName, String assessmentName, Object body) { + return this.beginDownloadUrlAsync(resourceGroupName, projectName, groupName, assessmentName, body) + .getSyncPoller(); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, DownloadUrlInner> beginDownloadUrl(String resourceGroupName, + String projectName, String groupName, String assessmentName, Object body, Context context) { + return this.beginDownloadUrlAsync(resourceGroupName, projectName, groupName, assessmentName, body, context) + .getSyncPoller(); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono downloadUrlAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName, Object body) { + return beginDownloadUrlAsync(resourceGroupName, projectName, groupName, assessmentName, body).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono downloadUrlAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName, Object body, Context context) { + return beginDownloadUrlAsync(resourceGroupName, projectName, groupName, assessmentName, body, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public DownloadUrlInner downloadUrl(String resourceGroupName, String projectName, String groupName, + String assessmentName, Object body) { + return downloadUrlAsync(resourceGroupName, projectName, groupName, assessmentName, body).block(); + } + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public DownloadUrlInner downloadUrl(String resourceGroupName, String projectName, String groupName, + String assessmentName, Object body, Context context) { + return downloadUrlAsync(resourceGroupName, projectName, groupName, assessmentName, body, context).block(); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentV2 list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByGroupNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listByGroupNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentV2 list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByGroupNextSinglePageAsync(String nextLink, Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listByGroupNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlAssessmentV2OperationsImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlAssessmentV2OperationsImpl.java new file mode 100644 index 000000000000..c86a37981839 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlAssessmentV2OperationsImpl.java @@ -0,0 +1,206 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.migration.assessment.fluent.SqlAssessmentV2OperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.DownloadUrlInner; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlAssessmentV2Inner; +import com.azure.resourcemanager.migration.assessment.models.DownloadUrl; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentV2; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentV2Operations; + +public final class SqlAssessmentV2OperationsImpl implements SqlAssessmentV2Operations { + private static final ClientLogger LOGGER = new ClientLogger(SqlAssessmentV2OperationsImpl.class); + + private final SqlAssessmentV2OperationsClient innerClient; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + public SqlAssessmentV2OperationsImpl(SqlAssessmentV2OperationsClient innerClient, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public PagedIterable listByGroup(String resourceGroupName, String projectName, String groupName) { + PagedIterable inner + = this.serviceClient().listByGroup(resourceGroupName, projectName, groupName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new SqlAssessmentV2Impl(inner1, this.manager())); + } + + public PagedIterable listByGroup(String resourceGroupName, String projectName, String groupName, + Context context) { + PagedIterable inner + = this.serviceClient().listByGroup(resourceGroupName, projectName, groupName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new SqlAssessmentV2Impl(inner1, this.manager())); + } + + public Response getWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, Context context) { + Response inner + = this.serviceClient().getWithResponse(resourceGroupName, projectName, groupName, assessmentName, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new SqlAssessmentV2Impl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public SqlAssessmentV2 get(String resourceGroupName, String projectName, String groupName, String assessmentName) { + SqlAssessmentV2Inner inner + = this.serviceClient().get(resourceGroupName, projectName, groupName, assessmentName); + if (inner != null) { + return new SqlAssessmentV2Impl(inner, this.manager()); + } else { + return null; + } + } + + public Response deleteWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, Context context) { + return this.serviceClient() + .deleteWithResponse(resourceGroupName, projectName, groupName, assessmentName, context); + } + + public void delete(String resourceGroupName, String projectName, String groupName, String assessmentName) { + this.serviceClient().delete(resourceGroupName, projectName, groupName, assessmentName); + } + + public DownloadUrl downloadUrl(String resourceGroupName, String projectName, String groupName, + String assessmentName, Object body) { + DownloadUrlInner inner + = this.serviceClient().downloadUrl(resourceGroupName, projectName, groupName, assessmentName, body); + if (inner != null) { + return new DownloadUrlImpl(inner, this.manager()); + } else { + return null; + } + } + + public DownloadUrl downloadUrl(String resourceGroupName, String projectName, String groupName, + String assessmentName, Object body, Context context) { + DownloadUrlInner inner = this.serviceClient() + .downloadUrl(resourceGroupName, projectName, groupName, assessmentName, body, context); + if (inner != null) { + return new DownloadUrlImpl(inner, this.manager()); + } else { + return null; + } + } + + public SqlAssessmentV2 getById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String groupName = ResourceManagerUtils.getValueFromIdByName(id, "groups"); + if (groupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'groups'.", id))); + } + String assessmentName = ResourceManagerUtils.getValueFromIdByName(id, "sqlAssessments"); + if (assessmentName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'sqlAssessments'.", id))); + } + return this.getWithResponse(resourceGroupName, projectName, groupName, assessmentName, Context.NONE).getValue(); + } + + public Response getByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String groupName = ResourceManagerUtils.getValueFromIdByName(id, "groups"); + if (groupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'groups'.", id))); + } + String assessmentName = ResourceManagerUtils.getValueFromIdByName(id, "sqlAssessments"); + if (assessmentName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'sqlAssessments'.", id))); + } + return this.getWithResponse(resourceGroupName, projectName, groupName, assessmentName, context); + } + + public void deleteById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String groupName = ResourceManagerUtils.getValueFromIdByName(id, "groups"); + if (groupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'groups'.", id))); + } + String assessmentName = ResourceManagerUtils.getValueFromIdByName(id, "sqlAssessments"); + if (assessmentName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'sqlAssessments'.", id))); + } + this.deleteWithResponse(resourceGroupName, projectName, groupName, assessmentName, Context.NONE); + } + + public Response deleteByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String groupName = ResourceManagerUtils.getValueFromIdByName(id, "groups"); + if (groupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'groups'.", id))); + } + String assessmentName = ResourceManagerUtils.getValueFromIdByName(id, "sqlAssessments"); + if (assessmentName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'sqlAssessments'.", id))); + } + return this.deleteWithResponse(resourceGroupName, projectName, groupName, assessmentName, context); + } + + private SqlAssessmentV2OperationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } + + public SqlAssessmentV2Impl define(String name) { + return new SqlAssessmentV2Impl(name, this.manager()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlAssessmentV2SummaryImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlAssessmentV2SummaryImpl.java new file mode 100644 index 000000000000..4328b3fd8a7f --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlAssessmentV2SummaryImpl.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlAssessmentV2SummaryInner; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentV2Summary; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentV2SummaryProperties; + +public final class SqlAssessmentV2SummaryImpl implements SqlAssessmentV2Summary { + private SqlAssessmentV2SummaryInner innerObject; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + SqlAssessmentV2SummaryImpl(SqlAssessmentV2SummaryInner innerObject, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public SqlAssessmentV2SummaryProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public SqlAssessmentV2SummaryInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlAssessmentV2SummaryOperationsClientImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlAssessmentV2SummaryOperationsClientImpl.java new file mode 100644 index 000000000000..119b638a0fb3 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlAssessmentV2SummaryOperationsClientImpl.java @@ -0,0 +1,477 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.resourcemanager.migration.assessment.fluent.SqlAssessmentV2SummaryOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlAssessmentV2SummaryInner; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentV2SummaryListResult; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in SqlAssessmentV2SummaryOperationsClient. + */ +public final class SqlAssessmentV2SummaryOperationsClientImpl implements SqlAssessmentV2SummaryOperationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final SqlAssessmentV2SummaryOperationsService service; + + /** + * The service client containing this operation class. + */ + private final MigrationAssessmentManagementClientImpl client; + + /** + * Initializes an instance of SqlAssessmentV2SummaryOperationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + SqlAssessmentV2SummaryOperationsClientImpl(MigrationAssessmentManagementClientImpl client) { + this.service = RestProxy.create(SqlAssessmentV2SummaryOperationsService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for MigrationAssessmentManagementClientSqlAssessmentV2SummaryOperations + * to be used by the proxy service to perform REST calls. + */ + @Host("{$host}") + @ServiceInterface(name = "MigrationAssessmentM") + public interface SqlAssessmentV2SummaryOperationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/sqlAssessments/{assessmentName}/summaries") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listBySqlAssessmentV2(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @PathParam("assessmentName") String assessmentName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/groups/{groupName}/sqlAssessments/{assessmentName}/summaries/{summaryName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("groupName") String groupName, @PathParam("assessmentName") String assessmentName, + @PathParam("summaryName") String summaryName, @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listBySqlAssessmentV2Next( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * List SqlAssessmentV2Summary resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentV2Summary list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySqlAssessmentV2SinglePageAsync( + String resourceGroupName, String projectName, String groupName, String assessmentName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listBySqlAssessmentV2(this.client.getEndpoint(), + this.client.getApiVersion(), this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, + assessmentName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List SqlAssessmentV2Summary resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentV2Summary list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySqlAssessmentV2SinglePageAsync( + String resourceGroupName, String projectName, String groupName, String assessmentName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listBySqlAssessmentV2(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, assessmentName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List SqlAssessmentV2Summary resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentV2Summary list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listBySqlAssessmentV2Async(String resourceGroupName, + String projectName, String groupName, String assessmentName) { + return new PagedFlux<>( + () -> listBySqlAssessmentV2SinglePageAsync(resourceGroupName, projectName, groupName, assessmentName), + nextLink -> listBySqlAssessmentV2NextSinglePageAsync(nextLink)); + } + + /** + * List SqlAssessmentV2Summary resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentV2Summary list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listBySqlAssessmentV2Async(String resourceGroupName, + String projectName, String groupName, String assessmentName, Context context) { + return new PagedFlux<>(() -> listBySqlAssessmentV2SinglePageAsync(resourceGroupName, projectName, groupName, + assessmentName, context), nextLink -> listBySqlAssessmentV2NextSinglePageAsync(nextLink, context)); + } + + /** + * List SqlAssessmentV2Summary resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentV2Summary list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listBySqlAssessmentV2(String resourceGroupName, + String projectName, String groupName, String assessmentName) { + return new PagedIterable<>( + listBySqlAssessmentV2Async(resourceGroupName, projectName, groupName, assessmentName)); + } + + /** + * List SqlAssessmentV2Summary resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentV2Summary list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listBySqlAssessmentV2(String resourceGroupName, + String projectName, String groupName, String assessmentName, Context context) { + return new PagedIterable<>( + listBySqlAssessmentV2Async(resourceGroupName, projectName, groupName, assessmentName, context)); + } + + /** + * Get a SqlAssessmentV2Summary. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param summaryName Gets the Name of the SQL Summary. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlAssessmentV2Summary along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, + String projectName, String groupName, String assessmentName, String summaryName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + if (summaryName == null) { + return Mono.error(new IllegalArgumentException("Parameter summaryName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, groupName, assessmentName, summaryName, + accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a SqlAssessmentV2Summary. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param summaryName Gets the Name of the SQL Summary. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlAssessmentV2Summary along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, + String projectName, String groupName, String assessmentName, String summaryName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (assessmentName == null) { + return Mono.error(new IllegalArgumentException("Parameter assessmentName is required and cannot be null.")); + } + if (summaryName == null) { + return Mono.error(new IllegalArgumentException("Parameter summaryName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, groupName, assessmentName, summaryName, accept, context); + } + + /** + * Get a SqlAssessmentV2Summary. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param summaryName Gets the Name of the SQL Summary. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlAssessmentV2Summary on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceGroupName, String projectName, String groupName, + String assessmentName, String summaryName) { + return getWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, summaryName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a SqlAssessmentV2Summary. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param summaryName Gets the Name of the SQL Summary. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlAssessmentV2Summary along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceGroupName, String projectName, + String groupName, String assessmentName, String summaryName, Context context) { + return getWithResponseAsync(resourceGroupName, projectName, groupName, assessmentName, summaryName, context) + .block(); + } + + /** + * Get a SqlAssessmentV2Summary. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param summaryName Gets the Name of the SQL Summary. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlAssessmentV2Summary. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public SqlAssessmentV2SummaryInner get(String resourceGroupName, String projectName, String groupName, + String assessmentName, String summaryName) { + return getWithResponse(resourceGroupName, projectName, groupName, assessmentName, summaryName, Context.NONE) + .getValue(); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentV2Summary list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySqlAssessmentV2NextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listBySqlAssessmentV2Next(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentV2Summary list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySqlAssessmentV2NextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listBySqlAssessmentV2Next(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlAssessmentV2SummaryOperationsImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlAssessmentV2SummaryOperationsImpl.java new file mode 100644 index 000000000000..0289781a1f00 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlAssessmentV2SummaryOperationsImpl.java @@ -0,0 +1,74 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.migration.assessment.fluent.SqlAssessmentV2SummaryOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlAssessmentV2SummaryInner; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentV2Summary; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentV2SummaryOperations; + +public final class SqlAssessmentV2SummaryOperationsImpl implements SqlAssessmentV2SummaryOperations { + private static final ClientLogger LOGGER = new ClientLogger(SqlAssessmentV2SummaryOperationsImpl.class); + + private final SqlAssessmentV2SummaryOperationsClient innerClient; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + public SqlAssessmentV2SummaryOperationsImpl(SqlAssessmentV2SummaryOperationsClient innerClient, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName) { + PagedIterable inner + = this.serviceClient().listBySqlAssessmentV2(resourceGroupName, projectName, groupName, assessmentName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new SqlAssessmentV2SummaryImpl(inner1, this.manager())); + } + + public PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName, Context context) { + PagedIterable inner = this.serviceClient() + .listBySqlAssessmentV2(resourceGroupName, projectName, groupName, assessmentName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new SqlAssessmentV2SummaryImpl(inner1, this.manager())); + } + + public Response getWithResponse(String resourceGroupName, String projectName, + String groupName, String assessmentName, String summaryName, Context context) { + Response inner = this.serviceClient() + .getWithResponse(resourceGroupName, projectName, groupName, assessmentName, summaryName, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new SqlAssessmentV2SummaryImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public SqlAssessmentV2Summary get(String resourceGroupName, String projectName, String groupName, + String assessmentName, String summaryName) { + SqlAssessmentV2SummaryInner inner + = this.serviceClient().get(resourceGroupName, projectName, groupName, assessmentName, summaryName); + if (inner != null) { + return new SqlAssessmentV2SummaryImpl(inner, this.manager()); + } else { + return null; + } + } + + private SqlAssessmentV2SummaryOperationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlCollectorImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlCollectorImpl.java new file mode 100644 index 000000000000..6ab50f932d18 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlCollectorImpl.java @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlCollectorInner; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBaseWithAgent; +import com.azure.resourcemanager.migration.assessment.models.SqlCollector; + +public final class SqlCollectorImpl implements SqlCollector, SqlCollector.Definition { + private SqlCollectorInner innerObject; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + SqlCollectorImpl(SqlCollectorInner innerObject, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public CollectorPropertiesBaseWithAgent properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public SqlCollectorInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } + + private String resourceGroupName; + + private String projectName; + + private String collectorName; + + public SqlCollectorImpl withExistingAssessmentProject(String resourceGroupName, String projectName) { + this.resourceGroupName = resourceGroupName; + this.projectName = projectName; + return this; + } + + public SqlCollector create() { + this.innerObject = serviceManager.serviceClient() + .getSqlCollectorOperations() + .create(resourceGroupName, projectName, collectorName, this.innerModel(), Context.NONE); + return this; + } + + public SqlCollector create(Context context) { + this.innerObject = serviceManager.serviceClient() + .getSqlCollectorOperations() + .create(resourceGroupName, projectName, collectorName, this.innerModel(), context); + return this; + } + + SqlCollectorImpl(String name, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = new SqlCollectorInner(); + this.serviceManager = serviceManager; + this.collectorName = name; + } + + public SqlCollector refresh() { + this.innerObject = serviceManager.serviceClient() + .getSqlCollectorOperations() + .getWithResponse(resourceGroupName, projectName, collectorName, Context.NONE) + .getValue(); + return this; + } + + public SqlCollector refresh(Context context) { + this.innerObject = serviceManager.serviceClient() + .getSqlCollectorOperations() + .getWithResponse(resourceGroupName, projectName, collectorName, context) + .getValue(); + return this; + } + + public SqlCollectorImpl withProperties(CollectorPropertiesBaseWithAgent properties) { + this.innerModel().withProperties(properties); + return this; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlCollectorOperationsClientImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlCollectorOperationsClientImpl.java new file mode 100644 index 000000000000..a05026e5c9cb --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlCollectorOperationsClientImpl.java @@ -0,0 +1,820 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Put; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.core.util.polling.PollerFlux; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.migration.assessment.fluent.SqlCollectorOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlCollectorInner; +import com.azure.resourcemanager.migration.assessment.models.SqlCollectorListResult; +import java.nio.ByteBuffer; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in SqlCollectorOperationsClient. + */ +public final class SqlCollectorOperationsClientImpl implements SqlCollectorOperationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final SqlCollectorOperationsService service; + + /** + * The service client containing this operation class. + */ + private final MigrationAssessmentManagementClientImpl client; + + /** + * Initializes an instance of SqlCollectorOperationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + SqlCollectorOperationsClientImpl(MigrationAssessmentManagementClientImpl client) { + this.service = RestProxy.create(SqlCollectorOperationsService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for MigrationAssessmentManagementClientSqlCollectorOperations to be used + * by the proxy service to perform REST calls. + */ + @Host("{$host}") + @ServiceInterface(name = "MigrationAssessmentM") + public interface SqlCollectorOperationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/sqlcollectors") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAssessmentProject(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/sqlcollectors/{collectorName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("collectorName") String collectorName, @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Put("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/sqlcollectors/{collectorName}") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> create(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("collectorName") String collectorName, @BodyParam("application/json") SqlCollectorInner resource, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Delete("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/sqlcollectors/{collectorName}") + @ExpectedResponses({ 200, 204 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> delete(@HostParam("$host") String endpoint, @QueryParam("api-version") String apiVersion, + @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("collectorName") String collectorName, @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAssessmentProjectNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * List SqlCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlCollector list operation along with {@link PagedResponse} on successful completion + * of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectSinglePageAsync(String resourceGroupName, + String projectName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByAssessmentProject(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), + res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List SqlCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlCollector list operation along with {@link PagedResponse} on successful completion + * of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectSinglePageAsync(String resourceGroupName, + String projectName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByAssessmentProject(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List SqlCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlCollector list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentProjectAsync(String resourceGroupName, String projectName) { + return new PagedFlux<>(() -> listByAssessmentProjectSinglePageAsync(resourceGroupName, projectName), + nextLink -> listByAssessmentProjectNextSinglePageAsync(nextLink)); + } + + /** + * List SqlCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlCollector list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentProjectAsync(String resourceGroupName, String projectName, + Context context) { + return new PagedFlux<>(() -> listByAssessmentProjectSinglePageAsync(resourceGroupName, projectName, context), + nextLink -> listByAssessmentProjectNextSinglePageAsync(nextLink, context)); + } + + /** + * List SqlCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlCollector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName) { + return new PagedIterable<>(listByAssessmentProjectAsync(resourceGroupName, projectName)); + } + + /** + * List SqlCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlCollector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context) { + return new PagedIterable<>(listByAssessmentProjectAsync(resourceGroupName, projectName, context)); + } + + /** + * Get a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlCollector along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String collectorName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (collectorName == null) { + return Mono.error(new IllegalArgumentException("Parameter collectorName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, collectorName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlCollector along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String collectorName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (collectorName == null) { + return Mono.error(new IllegalArgumentException("Parameter collectorName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, collectorName, accept, context); + } + + /** + * Get a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlCollector on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceGroupName, String projectName, String collectorName) { + return getWithResponseAsync(resourceGroupName, projectName, collectorName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlCollector along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceGroupName, String projectName, + String collectorName, Context context) { + return getWithResponseAsync(resourceGroupName, projectName, collectorName, context).block(); + } + + /** + * Get a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlCollector. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public SqlCollectorInner get(String resourceGroupName, String projectName, String collectorName) { + return getWithResponse(resourceGroupName, projectName, collectorName, Context.NONE).getValue(); + } + + /** + * Create a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the SQL collector REST object along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createWithResponseAsync(String resourceGroupName, String projectName, + String collectorName, SqlCollectorInner resource) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (collectorName == null) { + return Mono.error(new IllegalArgumentException("Parameter collectorName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.create(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, collectorName, resource, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Create a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the SQL collector REST object along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createWithResponseAsync(String resourceGroupName, String projectName, + String collectorName, SqlCollectorInner resource, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (collectorName == null) { + return Mono.error(new IllegalArgumentException("Parameter collectorName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.create(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, collectorName, resource, accept, context); + } + + /** + * Create a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of the SQL collector REST object. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, SqlCollectorInner> beginCreateAsync(String resourceGroupName, + String projectName, String collectorName, SqlCollectorInner resource) { + Mono>> mono + = createWithResponseAsync(resourceGroupName, projectName, collectorName, resource); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + SqlCollectorInner.class, SqlCollectorInner.class, this.client.getContext()); + } + + /** + * Create a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of the SQL collector REST object. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, SqlCollectorInner> beginCreateAsync(String resourceGroupName, + String projectName, String collectorName, SqlCollectorInner resource, Context context) { + context = this.client.mergeContext(context); + Mono>> mono + = createWithResponseAsync(resourceGroupName, projectName, collectorName, resource, context); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + SqlCollectorInner.class, SqlCollectorInner.class, context); + } + + /** + * Create a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of the SQL collector REST object. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, SqlCollectorInner> beginCreate(String resourceGroupName, + String projectName, String collectorName, SqlCollectorInner resource) { + return this.beginCreateAsync(resourceGroupName, projectName, collectorName, resource).getSyncPoller(); + } + + /** + * Create a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of the SQL collector REST object. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, SqlCollectorInner> beginCreate(String resourceGroupName, + String projectName, String collectorName, SqlCollectorInner resource, Context context) { + return this.beginCreateAsync(resourceGroupName, projectName, collectorName, resource, context).getSyncPoller(); + } + + /** + * Create a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the SQL collector REST object on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createAsync(String resourceGroupName, String projectName, String collectorName, + SqlCollectorInner resource) { + return beginCreateAsync(resourceGroupName, projectName, collectorName, resource).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the SQL collector REST object on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createAsync(String resourceGroupName, String projectName, String collectorName, + SqlCollectorInner resource, Context context) { + return beginCreateAsync(resourceGroupName, projectName, collectorName, resource, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the SQL collector REST object. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public SqlCollectorInner create(String resourceGroupName, String projectName, String collectorName, + SqlCollectorInner resource) { + return createAsync(resourceGroupName, projectName, collectorName, resource).block(); + } + + /** + * Create a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the SQL collector REST object. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public SqlCollectorInner create(String resourceGroupName, String projectName, String collectorName, + SqlCollectorInner resource, Context context) { + return createAsync(resourceGroupName, projectName, collectorName, resource, context).block(); + } + + /** + * Delete a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String projectName, + String collectorName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (collectorName == null) { + return Mono.error(new IllegalArgumentException("Parameter collectorName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.delete(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, collectorName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Delete a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String projectName, + String collectorName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (collectorName == null) { + return Mono.error(new IllegalArgumentException("Parameter collectorName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.delete(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, collectorName, accept, context); + } + + /** + * Delete a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono deleteAsync(String resourceGroupName, String projectName, String collectorName) { + return deleteWithResponseAsync(resourceGroupName, projectName, collectorName).flatMap(ignored -> Mono.empty()); + } + + /** + * Delete a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String resourceGroupName, String projectName, String collectorName, + Context context) { + return deleteWithResponseAsync(resourceGroupName, projectName, collectorName, context).block(); + } + + /** + * Delete a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String resourceGroupName, String projectName, String collectorName) { + deleteWithResponse(resourceGroupName, projectName, collectorName, Context.NONE); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlCollector list operation along with {@link PagedResponse} on successful completion + * of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByAssessmentProjectNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), + res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlCollector list operation along with {@link PagedResponse} on successful completion + * of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listByAssessmentProjectNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlCollectorOperationsImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlCollectorOperationsImpl.java new file mode 100644 index 000000000000..3c8e9f305574 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/SqlCollectorOperationsImpl.java @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.migration.assessment.fluent.SqlCollectorOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlCollectorInner; +import com.azure.resourcemanager.migration.assessment.models.SqlCollector; +import com.azure.resourcemanager.migration.assessment.models.SqlCollectorOperations; + +public final class SqlCollectorOperationsImpl implements SqlCollectorOperations { + private static final ClientLogger LOGGER = new ClientLogger(SqlCollectorOperationsImpl.class); + + private final SqlCollectorOperationsClient innerClient; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + public SqlCollectorOperationsImpl(SqlCollectorOperationsClient innerClient, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName) { + PagedIterable inner + = this.serviceClient().listByAssessmentProject(resourceGroupName, projectName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new SqlCollectorImpl(inner1, this.manager())); + } + + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context) { + PagedIterable inner + = this.serviceClient().listByAssessmentProject(resourceGroupName, projectName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new SqlCollectorImpl(inner1, this.manager())); + } + + public Response getWithResponse(String resourceGroupName, String projectName, String collectorName, + Context context) { + Response inner + = this.serviceClient().getWithResponse(resourceGroupName, projectName, collectorName, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new SqlCollectorImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public SqlCollector get(String resourceGroupName, String projectName, String collectorName) { + SqlCollectorInner inner = this.serviceClient().get(resourceGroupName, projectName, collectorName); + if (inner != null) { + return new SqlCollectorImpl(inner, this.manager()); + } else { + return null; + } + } + + public Response deleteWithResponse(String resourceGroupName, String projectName, String collectorName, + Context context) { + return this.serviceClient().deleteWithResponse(resourceGroupName, projectName, collectorName, context); + } + + public void delete(String resourceGroupName, String projectName, String collectorName) { + this.serviceClient().delete(resourceGroupName, projectName, collectorName); + } + + public SqlCollector getById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String collectorName = ResourceManagerUtils.getValueFromIdByName(id, "sqlcollectors"); + if (collectorName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'sqlcollectors'.", id))); + } + return this.getWithResponse(resourceGroupName, projectName, collectorName, Context.NONE).getValue(); + } + + public Response getByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String collectorName = ResourceManagerUtils.getValueFromIdByName(id, "sqlcollectors"); + if (collectorName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'sqlcollectors'.", id))); + } + return this.getWithResponse(resourceGroupName, projectName, collectorName, context); + } + + public void deleteById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String collectorName = ResourceManagerUtils.getValueFromIdByName(id, "sqlcollectors"); + if (collectorName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'sqlcollectors'.", id))); + } + this.deleteWithResponse(resourceGroupName, projectName, collectorName, Context.NONE); + } + + public Response deleteByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String collectorName = ResourceManagerUtils.getValueFromIdByName(id, "sqlcollectors"); + if (collectorName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'sqlcollectors'.", id))); + } + return this.deleteWithResponse(resourceGroupName, projectName, collectorName, context); + } + + private SqlCollectorOperationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } + + public SqlCollectorImpl define(String name) { + return new SqlCollectorImpl(name, this.manager()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/VmwareCollectorImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/VmwareCollectorImpl.java new file mode 100644 index 000000000000..40b90bbb98ba --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/VmwareCollectorImpl.java @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.VmwareCollectorInner; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBaseWithAgent; +import com.azure.resourcemanager.migration.assessment.models.VmwareCollector; + +public final class VmwareCollectorImpl implements VmwareCollector, VmwareCollector.Definition { + private VmwareCollectorInner innerObject; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + VmwareCollectorImpl(VmwareCollectorInner innerObject, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public CollectorPropertiesBaseWithAgent properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public VmwareCollectorInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } + + private String resourceGroupName; + + private String projectName; + + private String vmWareCollectorName; + + public VmwareCollectorImpl withExistingAssessmentProject(String resourceGroupName, String projectName) { + this.resourceGroupName = resourceGroupName; + this.projectName = projectName; + return this; + } + + public VmwareCollector create() { + this.innerObject = serviceManager.serviceClient() + .getVmwareCollectorsOperations() + .create(resourceGroupName, projectName, vmWareCollectorName, this.innerModel(), Context.NONE); + return this; + } + + public VmwareCollector create(Context context) { + this.innerObject = serviceManager.serviceClient() + .getVmwareCollectorsOperations() + .create(resourceGroupName, projectName, vmWareCollectorName, this.innerModel(), context); + return this; + } + + VmwareCollectorImpl(String name, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerObject = new VmwareCollectorInner(); + this.serviceManager = serviceManager; + this.vmWareCollectorName = name; + } + + public VmwareCollector refresh() { + this.innerObject = serviceManager.serviceClient() + .getVmwareCollectorsOperations() + .getWithResponse(resourceGroupName, projectName, vmWareCollectorName, Context.NONE) + .getValue(); + return this; + } + + public VmwareCollector refresh(Context context) { + this.innerObject = serviceManager.serviceClient() + .getVmwareCollectorsOperations() + .getWithResponse(resourceGroupName, projectName, vmWareCollectorName, context) + .getValue(); + return this; + } + + public VmwareCollectorImpl withProperties(CollectorPropertiesBaseWithAgent properties) { + this.innerModel().withProperties(properties); + return this; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/VmwareCollectorsOperationsClientImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/VmwareCollectorsOperationsClientImpl.java new file mode 100644 index 000000000000..8ec2e0aae49f --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/VmwareCollectorsOperationsClientImpl.java @@ -0,0 +1,835 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Put; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.core.util.polling.PollerFlux; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.migration.assessment.fluent.VmwareCollectorsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.VmwareCollectorInner; +import com.azure.resourcemanager.migration.assessment.models.VmwareCollectorListResult; +import java.nio.ByteBuffer; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in VmwareCollectorsOperationsClient. + */ +public final class VmwareCollectorsOperationsClientImpl implements VmwareCollectorsOperationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final VmwareCollectorsOperationsService service; + + /** + * The service client containing this operation class. + */ + private final MigrationAssessmentManagementClientImpl client; + + /** + * Initializes an instance of VmwareCollectorsOperationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + VmwareCollectorsOperationsClientImpl(MigrationAssessmentManagementClientImpl client) { + this.service = RestProxy.create(VmwareCollectorsOperationsService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for MigrationAssessmentManagementClientVmwareCollectorsOperations to be + * used by the proxy service to perform REST calls. + */ + @Host("{$host}") + @ServiceInterface(name = "MigrationAssessmentM") + public interface VmwareCollectorsOperationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/vmwarecollectors") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAssessmentProject(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/vmwarecollectors/{vmWareCollectorName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("vmWareCollectorName") String vmWareCollectorName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Put("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/vmwarecollectors/{vmWareCollectorName}") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> create(@HostParam("$host") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("vmWareCollectorName") String vmWareCollectorName, + @BodyParam("application/json") VmwareCollectorInner resource, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Delete("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/assessmentProjects/{projectName}/vmwarecollectors/{vmWareCollectorName}") + @ExpectedResponses({ 200, 204 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> delete(@HostParam("$host") String endpoint, @QueryParam("api-version") String apiVersion, + @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("projectName") String projectName, + @PathParam("vmWareCollectorName") String vmWareCollectorName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByAssessmentProjectNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * List VmwareCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a VmwareCollector list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectSinglePageAsync(String resourceGroupName, + String projectName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByAssessmentProject(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List VmwareCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a VmwareCollector list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectSinglePageAsync(String resourceGroupName, + String projectName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByAssessmentProject(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List VmwareCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a VmwareCollector list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentProjectAsync(String resourceGroupName, String projectName) { + return new PagedFlux<>(() -> listByAssessmentProjectSinglePageAsync(resourceGroupName, projectName), + nextLink -> listByAssessmentProjectNextSinglePageAsync(nextLink)); + } + + /** + * List VmwareCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a VmwareCollector list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByAssessmentProjectAsync(String resourceGroupName, String projectName, + Context context) { + return new PagedFlux<>(() -> listByAssessmentProjectSinglePageAsync(resourceGroupName, projectName, context), + nextLink -> listByAssessmentProjectNextSinglePageAsync(nextLink, context)); + } + + /** + * List VmwareCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a VmwareCollector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName) { + return new PagedIterable<>(listByAssessmentProjectAsync(resourceGroupName, projectName)); + } + + /** + * List VmwareCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a VmwareCollector list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context) { + return new PagedIterable<>(listByAssessmentProjectAsync(resourceGroupName, projectName, context)); + } + + /** + * Get a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a VmwareCollector along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String vmWareCollectorName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (vmWareCollectorName == null) { + return Mono + .error(new IllegalArgumentException("Parameter vmWareCollectorName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, vmWareCollectorName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a VmwareCollector along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, String projectName, + String vmWareCollectorName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (vmWareCollectorName == null) { + return Mono + .error(new IllegalArgumentException("Parameter vmWareCollectorName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, vmWareCollectorName, accept, context); + } + + /** + * Get a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a VmwareCollector on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceGroupName, String projectName, + String vmWareCollectorName) { + return getWithResponseAsync(resourceGroupName, projectName, vmWareCollectorName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a VmwareCollector along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceGroupName, String projectName, + String vmWareCollectorName, Context context) { + return getWithResponseAsync(resourceGroupName, projectName, vmWareCollectorName, context).block(); + } + + /** + * Get a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a VmwareCollector. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public VmwareCollectorInner get(String resourceGroupName, String projectName, String vmWareCollectorName) { + return getWithResponse(resourceGroupName, projectName, vmWareCollectorName, Context.NONE).getValue(); + } + + /** + * Create a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return vMware collector resource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createWithResponseAsync(String resourceGroupName, String projectName, + String vmWareCollectorName, VmwareCollectorInner resource) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (vmWareCollectorName == null) { + return Mono + .error(new IllegalArgumentException("Parameter vmWareCollectorName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.create(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, vmWareCollectorName, resource, accept, + context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Create a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return vMware collector resource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createWithResponseAsync(String resourceGroupName, String projectName, + String vmWareCollectorName, VmwareCollectorInner resource, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (vmWareCollectorName == null) { + return Mono + .error(new IllegalArgumentException("Parameter vmWareCollectorName is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.create(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, vmWareCollectorName, resource, accept, context); + } + + /** + * Create a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of vMware collector resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, VmwareCollectorInner> beginCreateAsync( + String resourceGroupName, String projectName, String vmWareCollectorName, VmwareCollectorInner resource) { + Mono>> mono + = createWithResponseAsync(resourceGroupName, projectName, vmWareCollectorName, resource); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + VmwareCollectorInner.class, VmwareCollectorInner.class, this.client.getContext()); + } + + /** + * Create a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of vMware collector resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, VmwareCollectorInner> beginCreateAsync( + String resourceGroupName, String projectName, String vmWareCollectorName, VmwareCollectorInner resource, + Context context) { + context = this.client.mergeContext(context); + Mono>> mono + = createWithResponseAsync(resourceGroupName, projectName, vmWareCollectorName, resource, context); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), + VmwareCollectorInner.class, VmwareCollectorInner.class, context); + } + + /** + * Create a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of vMware collector resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, VmwareCollectorInner> beginCreate(String resourceGroupName, + String projectName, String vmWareCollectorName, VmwareCollectorInner resource) { + return this.beginCreateAsync(resourceGroupName, projectName, vmWareCollectorName, resource).getSyncPoller(); + } + + /** + * Create a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of vMware collector resource. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, VmwareCollectorInner> beginCreate(String resourceGroupName, + String projectName, String vmWareCollectorName, VmwareCollectorInner resource, Context context) { + return this.beginCreateAsync(resourceGroupName, projectName, vmWareCollectorName, resource, context) + .getSyncPoller(); + } + + /** + * Create a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return vMware collector resource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createAsync(String resourceGroupName, String projectName, + String vmWareCollectorName, VmwareCollectorInner resource) { + return beginCreateAsync(resourceGroupName, projectName, vmWareCollectorName, resource).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return vMware collector resource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createAsync(String resourceGroupName, String projectName, + String vmWareCollectorName, VmwareCollectorInner resource, Context context) { + return beginCreateAsync(resourceGroupName, projectName, vmWareCollectorName, resource, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return vMware collector resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public VmwareCollectorInner create(String resourceGroupName, String projectName, String vmWareCollectorName, + VmwareCollectorInner resource) { + return createAsync(resourceGroupName, projectName, vmWareCollectorName, resource).block(); + } + + /** + * Create a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return vMware collector resource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public VmwareCollectorInner create(String resourceGroupName, String projectName, String vmWareCollectorName, + VmwareCollectorInner resource, Context context) { + return createAsync(resourceGroupName, projectName, vmWareCollectorName, resource, context).block(); + } + + /** + * Delete a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String projectName, + String vmWareCollectorName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (vmWareCollectorName == null) { + return Mono + .error(new IllegalArgumentException("Parameter vmWareCollectorName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.delete(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, projectName, vmWareCollectorName, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Delete a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String projectName, + String vmWareCollectorName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (projectName == null) { + return Mono.error(new IllegalArgumentException("Parameter projectName is required and cannot be null.")); + } + if (vmWareCollectorName == null) { + return Mono + .error(new IllegalArgumentException("Parameter vmWareCollectorName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.delete(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, projectName, vmWareCollectorName, accept, context); + } + + /** + * Delete a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono deleteAsync(String resourceGroupName, String projectName, String vmWareCollectorName) { + return deleteWithResponseAsync(resourceGroupName, projectName, vmWareCollectorName) + .flatMap(ignored -> Mono.empty()); + } + + /** + * Delete a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String resourceGroupName, String projectName, String vmWareCollectorName, + Context context) { + return deleteWithResponseAsync(resourceGroupName, projectName, vmWareCollectorName, context).block(); + } + + /** + * Delete a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String resourceGroupName, String projectName, String vmWareCollectorName) { + deleteWithResponse(resourceGroupName, projectName, vmWareCollectorName, Context.NONE); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a VmwareCollector list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByAssessmentProjectNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a VmwareCollector list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByAssessmentProjectNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listByAssessmentProjectNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/VmwareCollectorsOperationsImpl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/VmwareCollectorsOperationsImpl.java new file mode 100644 index 000000000000..6d8f228f2e32 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/VmwareCollectorsOperationsImpl.java @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.migration.assessment.fluent.VmwareCollectorsOperationsClient; +import com.azure.resourcemanager.migration.assessment.fluent.models.VmwareCollectorInner; +import com.azure.resourcemanager.migration.assessment.models.VmwareCollector; +import com.azure.resourcemanager.migration.assessment.models.VmwareCollectorsOperations; + +public final class VmwareCollectorsOperationsImpl implements VmwareCollectorsOperations { + private static final ClientLogger LOGGER = new ClientLogger(VmwareCollectorsOperationsImpl.class); + + private final VmwareCollectorsOperationsClient innerClient; + + private final com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager; + + public VmwareCollectorsOperationsImpl(VmwareCollectorsOperationsClient innerClient, + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName) { + PagedIterable inner + = this.serviceClient().listByAssessmentProject(resourceGroupName, projectName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new VmwareCollectorImpl(inner1, this.manager())); + } + + public PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context) { + PagedIterable inner + = this.serviceClient().listByAssessmentProject(resourceGroupName, projectName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new VmwareCollectorImpl(inner1, this.manager())); + } + + public Response getWithResponse(String resourceGroupName, String projectName, + String vmWareCollectorName, Context context) { + Response inner + = this.serviceClient().getWithResponse(resourceGroupName, projectName, vmWareCollectorName, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new VmwareCollectorImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public VmwareCollector get(String resourceGroupName, String projectName, String vmWareCollectorName) { + VmwareCollectorInner inner = this.serviceClient().get(resourceGroupName, projectName, vmWareCollectorName); + if (inner != null) { + return new VmwareCollectorImpl(inner, this.manager()); + } else { + return null; + } + } + + public Response deleteWithResponse(String resourceGroupName, String projectName, String vmWareCollectorName, + Context context) { + return this.serviceClient().deleteWithResponse(resourceGroupName, projectName, vmWareCollectorName, context); + } + + public void delete(String resourceGroupName, String projectName, String vmWareCollectorName) { + this.serviceClient().delete(resourceGroupName, projectName, vmWareCollectorName); + } + + public VmwareCollector getById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String vmWareCollectorName = ResourceManagerUtils.getValueFromIdByName(id, "vmwarecollectors"); + if (vmWareCollectorName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'vmwarecollectors'.", id))); + } + return this.getWithResponse(resourceGroupName, projectName, vmWareCollectorName, Context.NONE).getValue(); + } + + public Response getByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String vmWareCollectorName = ResourceManagerUtils.getValueFromIdByName(id, "vmwarecollectors"); + if (vmWareCollectorName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'vmwarecollectors'.", id))); + } + return this.getWithResponse(resourceGroupName, projectName, vmWareCollectorName, context); + } + + public void deleteById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String vmWareCollectorName = ResourceManagerUtils.getValueFromIdByName(id, "vmwarecollectors"); + if (vmWareCollectorName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'vmwarecollectors'.", id))); + } + this.deleteWithResponse(resourceGroupName, projectName, vmWareCollectorName, Context.NONE); + } + + public Response deleteByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String projectName = ResourceManagerUtils.getValueFromIdByName(id, "assessmentProjects"); + if (projectName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'assessmentProjects'.", id))); + } + String vmWareCollectorName = ResourceManagerUtils.getValueFromIdByName(id, "vmwarecollectors"); + if (vmWareCollectorName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'vmwarecollectors'.", id))); + } + return this.deleteWithResponse(resourceGroupName, projectName, vmWareCollectorName, context); + } + + private VmwareCollectorsOperationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager() { + return this.serviceManager; + } + + public VmwareCollectorImpl define(String name) { + return new VmwareCollectorImpl(name, this.manager()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/package-info.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/package-info.java new file mode 100644 index 000000000000..4e90b6a4e17c --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/implementation/package-info.java @@ -0,0 +1,9 @@ +// 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 MigrationAssessmentManagementClient. + * Azure Migrate Resource Provider management API. + */ +package com.azure.resourcemanager.migration.assessment.implementation; diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ActionType.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ActionType.java new file mode 100644 index 000000000000..8b9f9be7dabd --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ActionType.java @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + */ +public final class ActionType extends ExpandableStringEnum { + /** + * Static value Internal for ActionType. + */ + public static final ActionType INTERNAL = fromString("Internal"); + + /** + * Creates a new instance of ActionType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public ActionType() { + } + + /** + * Creates or finds a ActionType from its string representation. + * + * @param name a name to look for. + * @return the corresponding ActionType. + */ + public static ActionType fromString(String name) { + return fromString(name, ActionType.class); + } + + /** + * Gets known ActionType values. + * + * @return known ActionType values. + */ + public static Collection values() { + return values(ActionType.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedDisk.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedDisk.java new file mode 100644 index 000000000000..3002c537d50a --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedDisk.java @@ -0,0 +1,520 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * The AssessedDisk model. + */ +@Fluent +public final class AssessedDisk implements JsonSerializable { + /* + * Gets the suitability. + */ + private CloudSuitability suitability; + + /* + * Gets the suitability explanation. + */ + private AzureDiskSuitabilityExplanation suitabilityExplanation; + + /* + * Gets the suitability detail. + */ + private AzureDiskSuitabilityDetail suitabilityDetail; + + /* + * Gets the recommended disk size. + */ + private AzureDiskSize recommendedDiskSize; + + /* + * Gets the recommended disk type. + */ + private AzureDiskType recommendedDiskType; + + /* + * Gets the recommended disk size. + */ + private Integer gigabytesForRecommendedDiskSize; + + /* + * Gets the recommended disk throughput. + */ + private Float recommendDiskThroughputInMbps; + + /* + * Gets the recommended disk iops. + */ + private Float recommendedDiskIops; + + /* + * Gets the monthly storage cost. + */ + private Float monthlyStorageCost; + + /* + * Gets the name. + */ + private String name; + + /* + * Gets the machine display name. + */ + private String displayName; + + /* + * Gets the gigabytes provisioned. + */ + private Float gigabytesProvisioned; + + /* + * Gets the megabytes per second of read. + */ + private Float megabytesPerSecondOfRead; + + /* + * Gets the megabytes per second of write. + */ + private Float megabytesPerSecondOfWrite; + + /* + * Gets the number of read operations per second. + */ + private Float numberOfReadOperationsPerSecond; + + /* + * Gets the number of write operations per second. + */ + private Float numberOfWriteOperationsPerSecond; + + /** + * Creates an instance of AssessedDisk class. + */ + public AssessedDisk() { + } + + /** + * Get the suitability property: Gets the suitability. + * + * @return the suitability value. + */ + public CloudSuitability suitability() { + return this.suitability; + } + + /** + * Set the suitability property: Gets the suitability. + * + * @param suitability the suitability value to set. + * @return the AssessedDisk object itself. + */ + public AssessedDisk withSuitability(CloudSuitability suitability) { + this.suitability = suitability; + return this; + } + + /** + * Get the suitabilityExplanation property: Gets the suitability explanation. + * + * @return the suitabilityExplanation value. + */ + public AzureDiskSuitabilityExplanation suitabilityExplanation() { + return this.suitabilityExplanation; + } + + /** + * Set the suitabilityExplanation property: Gets the suitability explanation. + * + * @param suitabilityExplanation the suitabilityExplanation value to set. + * @return the AssessedDisk object itself. + */ + public AssessedDisk withSuitabilityExplanation(AzureDiskSuitabilityExplanation suitabilityExplanation) { + this.suitabilityExplanation = suitabilityExplanation; + return this; + } + + /** + * Get the suitabilityDetail property: Gets the suitability detail. + * + * @return the suitabilityDetail value. + */ + public AzureDiskSuitabilityDetail suitabilityDetail() { + return this.suitabilityDetail; + } + + /** + * Set the suitabilityDetail property: Gets the suitability detail. + * + * @param suitabilityDetail the suitabilityDetail value to set. + * @return the AssessedDisk object itself. + */ + public AssessedDisk withSuitabilityDetail(AzureDiskSuitabilityDetail suitabilityDetail) { + this.suitabilityDetail = suitabilityDetail; + return this; + } + + /** + * Get the recommendedDiskSize property: Gets the recommended disk size. + * + * @return the recommendedDiskSize value. + */ + public AzureDiskSize recommendedDiskSize() { + return this.recommendedDiskSize; + } + + /** + * Set the recommendedDiskSize property: Gets the recommended disk size. + * + * @param recommendedDiskSize the recommendedDiskSize value to set. + * @return the AssessedDisk object itself. + */ + public AssessedDisk withRecommendedDiskSize(AzureDiskSize recommendedDiskSize) { + this.recommendedDiskSize = recommendedDiskSize; + return this; + } + + /** + * Get the recommendedDiskType property: Gets the recommended disk type. + * + * @return the recommendedDiskType value. + */ + public AzureDiskType recommendedDiskType() { + return this.recommendedDiskType; + } + + /** + * Set the recommendedDiskType property: Gets the recommended disk type. + * + * @param recommendedDiskType the recommendedDiskType value to set. + * @return the AssessedDisk object itself. + */ + public AssessedDisk withRecommendedDiskType(AzureDiskType recommendedDiskType) { + this.recommendedDiskType = recommendedDiskType; + return this; + } + + /** + * Get the gigabytesForRecommendedDiskSize property: Gets the recommended disk size. + * + * @return the gigabytesForRecommendedDiskSize value. + */ + public Integer gigabytesForRecommendedDiskSize() { + return this.gigabytesForRecommendedDiskSize; + } + + /** + * Set the gigabytesForRecommendedDiskSize property: Gets the recommended disk size. + * + * @param gigabytesForRecommendedDiskSize the gigabytesForRecommendedDiskSize value to set. + * @return the AssessedDisk object itself. + */ + public AssessedDisk withGigabytesForRecommendedDiskSize(Integer gigabytesForRecommendedDiskSize) { + this.gigabytesForRecommendedDiskSize = gigabytesForRecommendedDiskSize; + return this; + } + + /** + * Get the recommendDiskThroughputInMbps property: Gets the recommended disk throughput. + * + * @return the recommendDiskThroughputInMbps value. + */ + public Float recommendDiskThroughputInMbps() { + return this.recommendDiskThroughputInMbps; + } + + /** + * Set the recommendDiskThroughputInMbps property: Gets the recommended disk throughput. + * + * @param recommendDiskThroughputInMbps the recommendDiskThroughputInMbps value to set. + * @return the AssessedDisk object itself. + */ + public AssessedDisk withRecommendDiskThroughputInMbps(Float recommendDiskThroughputInMbps) { + this.recommendDiskThroughputInMbps = recommendDiskThroughputInMbps; + return this; + } + + /** + * Get the recommendedDiskIops property: Gets the recommended disk iops. + * + * @return the recommendedDiskIops value. + */ + public Float recommendedDiskIops() { + return this.recommendedDiskIops; + } + + /** + * Set the recommendedDiskIops property: Gets the recommended disk iops. + * + * @param recommendedDiskIops the recommendedDiskIops value to set. + * @return the AssessedDisk object itself. + */ + public AssessedDisk withRecommendedDiskIops(Float recommendedDiskIops) { + this.recommendedDiskIops = recommendedDiskIops; + return this; + } + + /** + * Get the monthlyStorageCost property: Gets the monthly storage cost. + * + * @return the monthlyStorageCost value. + */ + public Float monthlyStorageCost() { + return this.monthlyStorageCost; + } + + /** + * Set the monthlyStorageCost property: Gets the monthly storage cost. + * + * @param monthlyStorageCost the monthlyStorageCost value to set. + * @return the AssessedDisk object itself. + */ + public AssessedDisk withMonthlyStorageCost(Float monthlyStorageCost) { + this.monthlyStorageCost = monthlyStorageCost; + return this; + } + + /** + * Get the name property: Gets the name. + * + * @return the name value. + */ + public String name() { + return this.name; + } + + /** + * Set the name property: Gets the name. + * + * @param name the name value to set. + * @return the AssessedDisk object itself. + */ + public AssessedDisk withName(String name) { + this.name = name; + return this; + } + + /** + * Get the displayName property: Gets the machine display name. + * + * @return the displayName value. + */ + public String displayName() { + return this.displayName; + } + + /** + * Set the displayName property: Gets the machine display name. + * + * @param displayName the displayName value to set. + * @return the AssessedDisk object itself. + */ + public AssessedDisk withDisplayName(String displayName) { + this.displayName = displayName; + return this; + } + + /** + * Get the gigabytesProvisioned property: Gets the gigabytes provisioned. + * + * @return the gigabytesProvisioned value. + */ + public Float gigabytesProvisioned() { + return this.gigabytesProvisioned; + } + + /** + * Set the gigabytesProvisioned property: Gets the gigabytes provisioned. + * + * @param gigabytesProvisioned the gigabytesProvisioned value to set. + * @return the AssessedDisk object itself. + */ + public AssessedDisk withGigabytesProvisioned(Float gigabytesProvisioned) { + this.gigabytesProvisioned = gigabytesProvisioned; + return this; + } + + /** + * Get the megabytesPerSecondOfRead property: Gets the megabytes per second of read. + * + * @return the megabytesPerSecondOfRead value. + */ + public Float megabytesPerSecondOfRead() { + return this.megabytesPerSecondOfRead; + } + + /** + * Set the megabytesPerSecondOfRead property: Gets the megabytes per second of read. + * + * @param megabytesPerSecondOfRead the megabytesPerSecondOfRead value to set. + * @return the AssessedDisk object itself. + */ + public AssessedDisk withMegabytesPerSecondOfRead(Float megabytesPerSecondOfRead) { + this.megabytesPerSecondOfRead = megabytesPerSecondOfRead; + return this; + } + + /** + * Get the megabytesPerSecondOfWrite property: Gets the megabytes per second of write. + * + * @return the megabytesPerSecondOfWrite value. + */ + public Float megabytesPerSecondOfWrite() { + return this.megabytesPerSecondOfWrite; + } + + /** + * Set the megabytesPerSecondOfWrite property: Gets the megabytes per second of write. + * + * @param megabytesPerSecondOfWrite the megabytesPerSecondOfWrite value to set. + * @return the AssessedDisk object itself. + */ + public AssessedDisk withMegabytesPerSecondOfWrite(Float megabytesPerSecondOfWrite) { + this.megabytesPerSecondOfWrite = megabytesPerSecondOfWrite; + return this; + } + + /** + * Get the numberOfReadOperationsPerSecond property: Gets the number of read operations per second. + * + * @return the numberOfReadOperationsPerSecond value. + */ + public Float numberOfReadOperationsPerSecond() { + return this.numberOfReadOperationsPerSecond; + } + + /** + * Set the numberOfReadOperationsPerSecond property: Gets the number of read operations per second. + * + * @param numberOfReadOperationsPerSecond the numberOfReadOperationsPerSecond value to set. + * @return the AssessedDisk object itself. + */ + public AssessedDisk withNumberOfReadOperationsPerSecond(Float numberOfReadOperationsPerSecond) { + this.numberOfReadOperationsPerSecond = numberOfReadOperationsPerSecond; + return this; + } + + /** + * Get the numberOfWriteOperationsPerSecond property: Gets the number of write operations per second. + * + * @return the numberOfWriteOperationsPerSecond value. + */ + public Float numberOfWriteOperationsPerSecond() { + return this.numberOfWriteOperationsPerSecond; + } + + /** + * Set the numberOfWriteOperationsPerSecond property: Gets the number of write operations per second. + * + * @param numberOfWriteOperationsPerSecond the numberOfWriteOperationsPerSecond value to set. + * @return the AssessedDisk object itself. + */ + public AssessedDisk withNumberOfWriteOperationsPerSecond(Float numberOfWriteOperationsPerSecond) { + this.numberOfWriteOperationsPerSecond = numberOfWriteOperationsPerSecond; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("suitability", this.suitability == null ? null : this.suitability.toString()); + jsonWriter.writeStringField("suitabilityExplanation", + this.suitabilityExplanation == null ? null : this.suitabilityExplanation.toString()); + jsonWriter.writeStringField("suitabilityDetail", + this.suitabilityDetail == null ? null : this.suitabilityDetail.toString()); + jsonWriter.writeStringField("recommendedDiskSize", + this.recommendedDiskSize == null ? null : this.recommendedDiskSize.toString()); + jsonWriter.writeStringField("recommendedDiskType", + this.recommendedDiskType == null ? null : this.recommendedDiskType.toString()); + jsonWriter.writeNumberField("gigabytesForRecommendedDiskSize", this.gigabytesForRecommendedDiskSize); + jsonWriter.writeNumberField("recommendDiskThroughputInMbps", this.recommendDiskThroughputInMbps); + jsonWriter.writeNumberField("recommendedDiskIops", this.recommendedDiskIops); + jsonWriter.writeNumberField("monthlyStorageCost", this.monthlyStorageCost); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("displayName", this.displayName); + jsonWriter.writeNumberField("gigabytesProvisioned", this.gigabytesProvisioned); + jsonWriter.writeNumberField("megabytesPerSecondOfRead", this.megabytesPerSecondOfRead); + jsonWriter.writeNumberField("megabytesPerSecondOfWrite", this.megabytesPerSecondOfWrite); + jsonWriter.writeNumberField("numberOfReadOperationsPerSecond", this.numberOfReadOperationsPerSecond); + jsonWriter.writeNumberField("numberOfWriteOperationsPerSecond", this.numberOfWriteOperationsPerSecond); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessedDisk from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessedDisk 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 AssessedDisk. + */ + public static AssessedDisk fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessedDisk deserializedAssessedDisk = new AssessedDisk(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("suitability".equals(fieldName)) { + deserializedAssessedDisk.suitability = CloudSuitability.fromString(reader.getString()); + } else if ("suitabilityExplanation".equals(fieldName)) { + deserializedAssessedDisk.suitabilityExplanation + = AzureDiskSuitabilityExplanation.fromString(reader.getString()); + } else if ("suitabilityDetail".equals(fieldName)) { + deserializedAssessedDisk.suitabilityDetail + = AzureDiskSuitabilityDetail.fromString(reader.getString()); + } else if ("recommendedDiskSize".equals(fieldName)) { + deserializedAssessedDisk.recommendedDiskSize = AzureDiskSize.fromString(reader.getString()); + } else if ("recommendedDiskType".equals(fieldName)) { + deserializedAssessedDisk.recommendedDiskType = AzureDiskType.fromString(reader.getString()); + } else if ("gigabytesForRecommendedDiskSize".equals(fieldName)) { + deserializedAssessedDisk.gigabytesForRecommendedDiskSize = reader.getNullable(JsonReader::getInt); + } else if ("recommendDiskThroughputInMbps".equals(fieldName)) { + deserializedAssessedDisk.recommendDiskThroughputInMbps = reader.getNullable(JsonReader::getFloat); + } else if ("recommendedDiskIops".equals(fieldName)) { + deserializedAssessedDisk.recommendedDiskIops = reader.getNullable(JsonReader::getFloat); + } else if ("monthlyStorageCost".equals(fieldName)) { + deserializedAssessedDisk.monthlyStorageCost = reader.getNullable(JsonReader::getFloat); + } else if ("name".equals(fieldName)) { + deserializedAssessedDisk.name = reader.getString(); + } else if ("displayName".equals(fieldName)) { + deserializedAssessedDisk.displayName = reader.getString(); + } else if ("gigabytesProvisioned".equals(fieldName)) { + deserializedAssessedDisk.gigabytesProvisioned = reader.getNullable(JsonReader::getFloat); + } else if ("megabytesPerSecondOfRead".equals(fieldName)) { + deserializedAssessedDisk.megabytesPerSecondOfRead = reader.getNullable(JsonReader::getFloat); + } else if ("megabytesPerSecondOfWrite".equals(fieldName)) { + deserializedAssessedDisk.megabytesPerSecondOfWrite = reader.getNullable(JsonReader::getFloat); + } else if ("numberOfReadOperationsPerSecond".equals(fieldName)) { + deserializedAssessedDisk.numberOfReadOperationsPerSecond = reader.getNullable(JsonReader::getFloat); + } else if ("numberOfWriteOperationsPerSecond".equals(fieldName)) { + deserializedAssessedDisk.numberOfWriteOperationsPerSecond + = reader.getNullable(JsonReader::getFloat); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessedDisk; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedDiskData.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedDiskData.java new file mode 100644 index 000000000000..b2c91080695c --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedDiskData.java @@ -0,0 +1,522 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * Assessed Disk data. Used in Assessed SQL machine DTO. + */ +@Fluent +public final class AssessedDiskData implements JsonSerializable { + /* + * Gets the suitability. + */ + private CloudSuitability suitability; + + /* + * Gets the suitability explanation. + */ + private AzureDiskSuitabilityExplanation suitabilityExplanation; + + /* + * Gets the suitability detail. + */ + private AzureDiskSuitabilityDetail suitabilityDetail; + + /* + * Gets the recommended disk size. + */ + private AzureDiskSize recommendedDiskSize; + + /* + * Gets the recommended disk type. + */ + private AzureDiskType recommendedDiskType; + + /* + * Gets the recommended disk size. + */ + private Integer recommendedDiskSizeGigabytes; + + /* + * Gets the recommended disk throughput. + */ + private Float recommendDiskThroughputInMbps; + + /* + * Gets the recommended disk iops. + */ + private Float recommendedDiskIops; + + /* + * Gets the monthly storage cost. + */ + private Float monthlyStorageCost; + + /* + * Gets the name. + */ + private String name; + + /* + * Gets the machine display name. + */ + private String displayName; + + /* + * Gets the gigabytes provisioned. + */ + private Float gigabytesProvisioned; + + /* + * Gets the megabytes per second of read. + */ + private Float megabytesPerSecondOfRead; + + /* + * Gets the megabytes per second of write. + */ + private Float megabytesPerSecondOfWrite; + + /* + * Gets the number of read operations per second. + */ + private Float numberOfReadOperationsPerSecond; + + /* + * Gets the number of write operations per second. + */ + private Float numberOfWriteOperationsPerSecond; + + /** + * Creates an instance of AssessedDiskData class. + */ + public AssessedDiskData() { + } + + /** + * Get the suitability property: Gets the suitability. + * + * @return the suitability value. + */ + public CloudSuitability suitability() { + return this.suitability; + } + + /** + * Set the suitability property: Gets the suitability. + * + * @param suitability the suitability value to set. + * @return the AssessedDiskData object itself. + */ + public AssessedDiskData withSuitability(CloudSuitability suitability) { + this.suitability = suitability; + return this; + } + + /** + * Get the suitabilityExplanation property: Gets the suitability explanation. + * + * @return the suitabilityExplanation value. + */ + public AzureDiskSuitabilityExplanation suitabilityExplanation() { + return this.suitabilityExplanation; + } + + /** + * Set the suitabilityExplanation property: Gets the suitability explanation. + * + * @param suitabilityExplanation the suitabilityExplanation value to set. + * @return the AssessedDiskData object itself. + */ + public AssessedDiskData withSuitabilityExplanation(AzureDiskSuitabilityExplanation suitabilityExplanation) { + this.suitabilityExplanation = suitabilityExplanation; + return this; + } + + /** + * Get the suitabilityDetail property: Gets the suitability detail. + * + * @return the suitabilityDetail value. + */ + public AzureDiskSuitabilityDetail suitabilityDetail() { + return this.suitabilityDetail; + } + + /** + * Set the suitabilityDetail property: Gets the suitability detail. + * + * @param suitabilityDetail the suitabilityDetail value to set. + * @return the AssessedDiskData object itself. + */ + public AssessedDiskData withSuitabilityDetail(AzureDiskSuitabilityDetail suitabilityDetail) { + this.suitabilityDetail = suitabilityDetail; + return this; + } + + /** + * Get the recommendedDiskSize property: Gets the recommended disk size. + * + * @return the recommendedDiskSize value. + */ + public AzureDiskSize recommendedDiskSize() { + return this.recommendedDiskSize; + } + + /** + * Set the recommendedDiskSize property: Gets the recommended disk size. + * + * @param recommendedDiskSize the recommendedDiskSize value to set. + * @return the AssessedDiskData object itself. + */ + public AssessedDiskData withRecommendedDiskSize(AzureDiskSize recommendedDiskSize) { + this.recommendedDiskSize = recommendedDiskSize; + return this; + } + + /** + * Get the recommendedDiskType property: Gets the recommended disk type. + * + * @return the recommendedDiskType value. + */ + public AzureDiskType recommendedDiskType() { + return this.recommendedDiskType; + } + + /** + * Set the recommendedDiskType property: Gets the recommended disk type. + * + * @param recommendedDiskType the recommendedDiskType value to set. + * @return the AssessedDiskData object itself. + */ + public AssessedDiskData withRecommendedDiskType(AzureDiskType recommendedDiskType) { + this.recommendedDiskType = recommendedDiskType; + return this; + } + + /** + * Get the recommendedDiskSizeGigabytes property: Gets the recommended disk size. + * + * @return the recommendedDiskSizeGigabytes value. + */ + public Integer recommendedDiskSizeGigabytes() { + return this.recommendedDiskSizeGigabytes; + } + + /** + * Set the recommendedDiskSizeGigabytes property: Gets the recommended disk size. + * + * @param recommendedDiskSizeGigabytes the recommendedDiskSizeGigabytes value to set. + * @return the AssessedDiskData object itself. + */ + public AssessedDiskData withRecommendedDiskSizeGigabytes(Integer recommendedDiskSizeGigabytes) { + this.recommendedDiskSizeGigabytes = recommendedDiskSizeGigabytes; + return this; + } + + /** + * Get the recommendDiskThroughputInMbps property: Gets the recommended disk throughput. + * + * @return the recommendDiskThroughputInMbps value. + */ + public Float recommendDiskThroughputInMbps() { + return this.recommendDiskThroughputInMbps; + } + + /** + * Set the recommendDiskThroughputInMbps property: Gets the recommended disk throughput. + * + * @param recommendDiskThroughputInMbps the recommendDiskThroughputInMbps value to set. + * @return the AssessedDiskData object itself. + */ + public AssessedDiskData withRecommendDiskThroughputInMbps(Float recommendDiskThroughputInMbps) { + this.recommendDiskThroughputInMbps = recommendDiskThroughputInMbps; + return this; + } + + /** + * Get the recommendedDiskIops property: Gets the recommended disk iops. + * + * @return the recommendedDiskIops value. + */ + public Float recommendedDiskIops() { + return this.recommendedDiskIops; + } + + /** + * Set the recommendedDiskIops property: Gets the recommended disk iops. + * + * @param recommendedDiskIops the recommendedDiskIops value to set. + * @return the AssessedDiskData object itself. + */ + public AssessedDiskData withRecommendedDiskIops(Float recommendedDiskIops) { + this.recommendedDiskIops = recommendedDiskIops; + return this; + } + + /** + * Get the monthlyStorageCost property: Gets the monthly storage cost. + * + * @return the monthlyStorageCost value. + */ + public Float monthlyStorageCost() { + return this.monthlyStorageCost; + } + + /** + * Set the monthlyStorageCost property: Gets the monthly storage cost. + * + * @param monthlyStorageCost the monthlyStorageCost value to set. + * @return the AssessedDiskData object itself. + */ + public AssessedDiskData withMonthlyStorageCost(Float monthlyStorageCost) { + this.monthlyStorageCost = monthlyStorageCost; + return this; + } + + /** + * Get the name property: Gets the name. + * + * @return the name value. + */ + public String name() { + return this.name; + } + + /** + * Set the name property: Gets the name. + * + * @param name the name value to set. + * @return the AssessedDiskData object itself. + */ + public AssessedDiskData withName(String name) { + this.name = name; + return this; + } + + /** + * Get the displayName property: Gets the machine display name. + * + * @return the displayName value. + */ + public String displayName() { + return this.displayName; + } + + /** + * Set the displayName property: Gets the machine display name. + * + * @param displayName the displayName value to set. + * @return the AssessedDiskData object itself. + */ + public AssessedDiskData withDisplayName(String displayName) { + this.displayName = displayName; + return this; + } + + /** + * Get the gigabytesProvisioned property: Gets the gigabytes provisioned. + * + * @return the gigabytesProvisioned value. + */ + public Float gigabytesProvisioned() { + return this.gigabytesProvisioned; + } + + /** + * Set the gigabytesProvisioned property: Gets the gigabytes provisioned. + * + * @param gigabytesProvisioned the gigabytesProvisioned value to set. + * @return the AssessedDiskData object itself. + */ + public AssessedDiskData withGigabytesProvisioned(Float gigabytesProvisioned) { + this.gigabytesProvisioned = gigabytesProvisioned; + return this; + } + + /** + * Get the megabytesPerSecondOfRead property: Gets the megabytes per second of read. + * + * @return the megabytesPerSecondOfRead value. + */ + public Float megabytesPerSecondOfRead() { + return this.megabytesPerSecondOfRead; + } + + /** + * Set the megabytesPerSecondOfRead property: Gets the megabytes per second of read. + * + * @param megabytesPerSecondOfRead the megabytesPerSecondOfRead value to set. + * @return the AssessedDiskData object itself. + */ + public AssessedDiskData withMegabytesPerSecondOfRead(Float megabytesPerSecondOfRead) { + this.megabytesPerSecondOfRead = megabytesPerSecondOfRead; + return this; + } + + /** + * Get the megabytesPerSecondOfWrite property: Gets the megabytes per second of write. + * + * @return the megabytesPerSecondOfWrite value. + */ + public Float megabytesPerSecondOfWrite() { + return this.megabytesPerSecondOfWrite; + } + + /** + * Set the megabytesPerSecondOfWrite property: Gets the megabytes per second of write. + * + * @param megabytesPerSecondOfWrite the megabytesPerSecondOfWrite value to set. + * @return the AssessedDiskData object itself. + */ + public AssessedDiskData withMegabytesPerSecondOfWrite(Float megabytesPerSecondOfWrite) { + this.megabytesPerSecondOfWrite = megabytesPerSecondOfWrite; + return this; + } + + /** + * Get the numberOfReadOperationsPerSecond property: Gets the number of read operations per second. + * + * @return the numberOfReadOperationsPerSecond value. + */ + public Float numberOfReadOperationsPerSecond() { + return this.numberOfReadOperationsPerSecond; + } + + /** + * Set the numberOfReadOperationsPerSecond property: Gets the number of read operations per second. + * + * @param numberOfReadOperationsPerSecond the numberOfReadOperationsPerSecond value to set. + * @return the AssessedDiskData object itself. + */ + public AssessedDiskData withNumberOfReadOperationsPerSecond(Float numberOfReadOperationsPerSecond) { + this.numberOfReadOperationsPerSecond = numberOfReadOperationsPerSecond; + return this; + } + + /** + * Get the numberOfWriteOperationsPerSecond property: Gets the number of write operations per second. + * + * @return the numberOfWriteOperationsPerSecond value. + */ + public Float numberOfWriteOperationsPerSecond() { + return this.numberOfWriteOperationsPerSecond; + } + + /** + * Set the numberOfWriteOperationsPerSecond property: Gets the number of write operations per second. + * + * @param numberOfWriteOperationsPerSecond the numberOfWriteOperationsPerSecond value to set. + * @return the AssessedDiskData object itself. + */ + public AssessedDiskData withNumberOfWriteOperationsPerSecond(Float numberOfWriteOperationsPerSecond) { + this.numberOfWriteOperationsPerSecond = numberOfWriteOperationsPerSecond; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("suitability", this.suitability == null ? null : this.suitability.toString()); + jsonWriter.writeStringField("suitabilityExplanation", + this.suitabilityExplanation == null ? null : this.suitabilityExplanation.toString()); + jsonWriter.writeStringField("suitabilityDetail", + this.suitabilityDetail == null ? null : this.suitabilityDetail.toString()); + jsonWriter.writeStringField("recommendedDiskSize", + this.recommendedDiskSize == null ? null : this.recommendedDiskSize.toString()); + jsonWriter.writeStringField("recommendedDiskType", + this.recommendedDiskType == null ? null : this.recommendedDiskType.toString()); + jsonWriter.writeNumberField("recommendedDiskSizeGigabytes", this.recommendedDiskSizeGigabytes); + jsonWriter.writeNumberField("recommendDiskThroughputInMbps", this.recommendDiskThroughputInMbps); + jsonWriter.writeNumberField("recommendedDiskIops", this.recommendedDiskIops); + jsonWriter.writeNumberField("monthlyStorageCost", this.monthlyStorageCost); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("displayName", this.displayName); + jsonWriter.writeNumberField("gigabytesProvisioned", this.gigabytesProvisioned); + jsonWriter.writeNumberField("megabytesPerSecondOfRead", this.megabytesPerSecondOfRead); + jsonWriter.writeNumberField("megabytesPerSecondOfWrite", this.megabytesPerSecondOfWrite); + jsonWriter.writeNumberField("numberOfReadOperationsPerSecond", this.numberOfReadOperationsPerSecond); + jsonWriter.writeNumberField("numberOfWriteOperationsPerSecond", this.numberOfWriteOperationsPerSecond); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessedDiskData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessedDiskData 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 AssessedDiskData. + */ + public static AssessedDiskData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessedDiskData deserializedAssessedDiskData = new AssessedDiskData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("suitability".equals(fieldName)) { + deserializedAssessedDiskData.suitability = CloudSuitability.fromString(reader.getString()); + } else if ("suitabilityExplanation".equals(fieldName)) { + deserializedAssessedDiskData.suitabilityExplanation + = AzureDiskSuitabilityExplanation.fromString(reader.getString()); + } else if ("suitabilityDetail".equals(fieldName)) { + deserializedAssessedDiskData.suitabilityDetail + = AzureDiskSuitabilityDetail.fromString(reader.getString()); + } else if ("recommendedDiskSize".equals(fieldName)) { + deserializedAssessedDiskData.recommendedDiskSize = AzureDiskSize.fromString(reader.getString()); + } else if ("recommendedDiskType".equals(fieldName)) { + deserializedAssessedDiskData.recommendedDiskType = AzureDiskType.fromString(reader.getString()); + } else if ("recommendedDiskSizeGigabytes".equals(fieldName)) { + deserializedAssessedDiskData.recommendedDiskSizeGigabytes = reader.getNullable(JsonReader::getInt); + } else if ("recommendDiskThroughputInMbps".equals(fieldName)) { + deserializedAssessedDiskData.recommendDiskThroughputInMbps + = reader.getNullable(JsonReader::getFloat); + } else if ("recommendedDiskIops".equals(fieldName)) { + deserializedAssessedDiskData.recommendedDiskIops = reader.getNullable(JsonReader::getFloat); + } else if ("monthlyStorageCost".equals(fieldName)) { + deserializedAssessedDiskData.monthlyStorageCost = reader.getNullable(JsonReader::getFloat); + } else if ("name".equals(fieldName)) { + deserializedAssessedDiskData.name = reader.getString(); + } else if ("displayName".equals(fieldName)) { + deserializedAssessedDiskData.displayName = reader.getString(); + } else if ("gigabytesProvisioned".equals(fieldName)) { + deserializedAssessedDiskData.gigabytesProvisioned = reader.getNullable(JsonReader::getFloat); + } else if ("megabytesPerSecondOfRead".equals(fieldName)) { + deserializedAssessedDiskData.megabytesPerSecondOfRead = reader.getNullable(JsonReader::getFloat); + } else if ("megabytesPerSecondOfWrite".equals(fieldName)) { + deserializedAssessedDiskData.megabytesPerSecondOfWrite = reader.getNullable(JsonReader::getFloat); + } else if ("numberOfReadOperationsPerSecond".equals(fieldName)) { + deserializedAssessedDiskData.numberOfReadOperationsPerSecond + = reader.getNullable(JsonReader::getFloat); + } else if ("numberOfWriteOperationsPerSecond".equals(fieldName)) { + deserializedAssessedDiskData.numberOfWriteOperationsPerSecond + = reader.getNullable(JsonReader::getFloat); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessedDiskData; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedMachine.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedMachine.java new file mode 100644 index 000000000000..a42331165aba --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedMachine.java @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedMachineInner; + +/** + * An immutable client-side representation of AssessedMachine. + */ +public interface AssessedMachine { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + AssessedMachineProperties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.migration.assessment.fluent.models.AssessedMachineInner object. + * + * @return the inner object. + */ + AssessedMachineInner innerModel(); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedMachineListResult.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedMachineListResult.java new file mode 100644 index 000000000000..ccc0c8153038 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedMachineListResult.java @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedMachineInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a AssessedMachine list operation. + */ +@Fluent +public final class AssessedMachineListResult implements JsonSerializable { + /* + * The AssessedMachine items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of AssessedMachineListResult class. + */ + public AssessedMachineListResult() { + } + + /** + * Get the value property: The AssessedMachine items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Set the value property: The AssessedMachine items on this page. + * + * @param value the value value to set. + * @return the AssessedMachineListResult object itself. + */ + public AssessedMachineListResult withValue(List value) { + this.value = value; + return this; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The link to the next page of items. + * + * @param nextLink the nextLink value to set. + * @return the AssessedMachineListResult object itself. + */ + public AssessedMachineListResult withNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log( + new IllegalArgumentException("Missing required property value in model AssessedMachineListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(AssessedMachineListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessedMachineListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessedMachineListResult 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 AssessedMachineListResult. + */ + public static AssessedMachineListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessedMachineListResult deserializedAssessedMachineListResult = new AssessedMachineListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> AssessedMachineInner.fromJson(reader1)); + deserializedAssessedMachineListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedAssessedMachineListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessedMachineListResult; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedMachineProperties.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedMachineProperties.java new file mode 100644 index 000000000000..f3b4284d471a --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedMachineProperties.java @@ -0,0 +1,732 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.util.List; +import java.util.Map; + +/** + * Assessed machine properties class. + */ +@Fluent +public final class AssessedMachineProperties implements JsonSerializable { + /* + * List of errors for this machine. + */ + private List errors; + + /* + * Dictionary of disks attached to the machine. Key is ID of disk. Value is a disk object. + */ + private Map disks; + + /* + * Monthly ultra storage cost. + */ + private Float monthlyUltraStorageCost; + + /* + * Gets or sets the processor details of the host. + */ + private ProcessorInfo hostProcessor; + + /* + * Gets or sets the collection of cost components. + */ + private List costComponents; + + /* + * Gets the product support status related details. + */ + private ProductSupportStatus productSupportStatus; + + /* + * Monthly networking cost. + */ + private Float monthlyBandwidthCost; + + /* + * Monthly storage cost. + */ + private Float monthlyStorageCost; + + /* + * Monthly premium storage cost. + */ + private Float monthlyPremiumStorageCost; + + /* + * Monthly standard SSD storage cost. + */ + private Float monthlyStandardSsdStorageCost; + + /* + * List of Network Adapters that were assessed as part of this machine's + * assessment. + */ + private Map networkAdapters; + + /* + * Recommended Azure Size for the machine. + */ + private AzureVmSize recommendedSize; + + /* + * Number of cores for recommended size. Read Only. + */ + private Integer numberOfCoresForRecommendedSize; + + /* + * Megabytes of memory for recommended size. Read Only. + */ + private Float megabytesOfMemoryForRecommendedSize; + + /* + * Monthly Compute cost calculated for Recommended size, for a 31-day month. + */ + private Float monthlyComputeCostForRecommendedSize; + + /* + * Gets the explanation if machine is not suitable for cloud. + */ + private AzureVmSuitabilityExplanation suitabilityExplanation; + + /* + * Gets the details if machine is not suitable for cloud. + */ + private AzureVmSuitabilityDetail suitabilityDetail; + + /* + * Assessed machine type. + */ + private AssessedMachineType type; + + /* + * Boot type of machine discovered in private data center. + */ + private MachineBootType bootType; + + /* + * Operating system as reported by datacenter management solution. + */ + private String operatingSystemType; + + /* + * Operating system as reported by datacenter management solution. + */ + private String operatingSystemName; + + /* + * Operating system version as reported by datacenter management solution. + */ + private String operatingSystemVersion; + + /* + * Operating system architecture as reported by datacenter management solution. + */ + private GuestOperatingSystemArchitecture operatingSystemArchitecture; + + /* + * When was machine first created. + */ + private OffsetDateTime createdTimestamp; + + /* + * When was machine last updated. + */ + private OffsetDateTime updatedTimestamp; + + /* + * Display Name of the Machine. + */ + private String displayName; + + /* + * Description for the machine. + */ + private String description; + + /* + * Data center machine ARM id. + */ + private String datacenterMachineArmId; + + /* + * Data center management server ARM id. + */ + private String datacenterManagementServerArmId; + + /* + * Data center management server name. + */ + private String datacenterManagementServerName; + + /* + * Megabytes of memory found allocated for the machine in private data center. + */ + private Float megabytesOfMemory; + + /* + * Number of CPU cores found on the machine. + */ + private Integer numberOfCores; + + /* + * Confidence Rating in Percentage. + */ + private Float confidenceRatingInPercentage; + + /* + * Percentile of Percentage of Cores Utilized noted during time period T. + * + * Here N and T are settings on Assessment. + */ + private Float percentageCoresUtilization; + + /* + * Percentile of Percentage of Memory Utilized noted during time period T. + * + * Here N and T are settings on Assessment. + */ + private Float percentageMemoryUtilization; + + /* + * Gets a value indicating whether machine is suitable for the cloud platform + * selected. + */ + private CloudSuitability suitability; + + /** + * Creates an instance of AssessedMachineProperties class. + */ + public AssessedMachineProperties() { + } + + /** + * Get the errors property: List of errors for this machine. + * + * @return the errors value. + */ + public List errors() { + return this.errors; + } + + /** + * Get the disks property: Dictionary of disks attached to the machine. Key is ID of disk. Value is a disk object. + * + * @return the disks value. + */ + public Map disks() { + return this.disks; + } + + /** + * Get the monthlyUltraStorageCost property: Monthly ultra storage cost. + * + * @return the monthlyUltraStorageCost value. + */ + public Float monthlyUltraStorageCost() { + return this.monthlyUltraStorageCost; + } + + /** + * Get the hostProcessor property: Gets or sets the processor details of the host. + * + * @return the hostProcessor value. + */ + public ProcessorInfo hostProcessor() { + return this.hostProcessor; + } + + /** + * Set the hostProcessor property: Gets or sets the processor details of the host. + * + * @param hostProcessor the hostProcessor value to set. + * @return the AssessedMachineProperties object itself. + */ + public AssessedMachineProperties withHostProcessor(ProcessorInfo hostProcessor) { + this.hostProcessor = hostProcessor; + return this; + } + + /** + * Get the costComponents property: Gets or sets the collection of cost components. + * + * @return the costComponents value. + */ + public List costComponents() { + return this.costComponents; + } + + /** + * Set the costComponents property: Gets or sets the collection of cost components. + * + * @param costComponents the costComponents value to set. + * @return the AssessedMachineProperties object itself. + */ + public AssessedMachineProperties withCostComponents(List costComponents) { + this.costComponents = costComponents; + return this; + } + + /** + * Get the productSupportStatus property: Gets the product support status related details. + * + * @return the productSupportStatus value. + */ + public ProductSupportStatus productSupportStatus() { + return this.productSupportStatus; + } + + /** + * Get the monthlyBandwidthCost property: Monthly networking cost. + * + * @return the monthlyBandwidthCost value. + */ + public Float monthlyBandwidthCost() { + return this.monthlyBandwidthCost; + } + + /** + * Get the monthlyStorageCost property: Monthly storage cost. + * + * @return the monthlyStorageCost value. + */ + public Float monthlyStorageCost() { + return this.monthlyStorageCost; + } + + /** + * Get the monthlyPremiumStorageCost property: Monthly premium storage cost. + * + * @return the monthlyPremiumStorageCost value. + */ + public Float monthlyPremiumStorageCost() { + return this.monthlyPremiumStorageCost; + } + + /** + * Get the monthlyStandardSsdStorageCost property: Monthly standard SSD storage cost. + * + * @return the monthlyStandardSsdStorageCost value. + */ + public Float monthlyStandardSsdStorageCost() { + return this.monthlyStandardSsdStorageCost; + } + + /** + * Get the networkAdapters property: List of Network Adapters that were assessed as part of this machine's + * assessment. + * + * @return the networkAdapters value. + */ + public Map networkAdapters() { + return this.networkAdapters; + } + + /** + * Get the recommendedSize property: Recommended Azure Size for the machine. + * + * @return the recommendedSize value. + */ + public AzureVmSize recommendedSize() { + return this.recommendedSize; + } + + /** + * Get the numberOfCoresForRecommendedSize property: Number of cores for recommended size. Read Only. + * + * @return the numberOfCoresForRecommendedSize value. + */ + public Integer numberOfCoresForRecommendedSize() { + return this.numberOfCoresForRecommendedSize; + } + + /** + * Get the megabytesOfMemoryForRecommendedSize property: Megabytes of memory for recommended size. Read Only. + * + * @return the megabytesOfMemoryForRecommendedSize value. + */ + public Float megabytesOfMemoryForRecommendedSize() { + return this.megabytesOfMemoryForRecommendedSize; + } + + /** + * Get the monthlyComputeCostForRecommendedSize property: Monthly Compute cost calculated for Recommended size, for + * a 31-day month. + * + * @return the monthlyComputeCostForRecommendedSize value. + */ + public Float monthlyComputeCostForRecommendedSize() { + return this.monthlyComputeCostForRecommendedSize; + } + + /** + * Get the suitabilityExplanation property: Gets the explanation if machine is not suitable for cloud. + * + * @return the suitabilityExplanation value. + */ + public AzureVmSuitabilityExplanation suitabilityExplanation() { + return this.suitabilityExplanation; + } + + /** + * Get the suitabilityDetail property: Gets the details if machine is not suitable for cloud. + * + * @return the suitabilityDetail value. + */ + public AzureVmSuitabilityDetail suitabilityDetail() { + return this.suitabilityDetail; + } + + /** + * Get the type property: Assessed machine type. + * + * @return the type value. + */ + public AssessedMachineType type() { + return this.type; + } + + /** + * Get the bootType property: Boot type of machine discovered in private data center. + * + * @return the bootType value. + */ + public MachineBootType bootType() { + return this.bootType; + } + + /** + * Get the operatingSystemType property: Operating system as reported by datacenter management solution. + * + * @return the operatingSystemType value. + */ + public String operatingSystemType() { + return this.operatingSystemType; + } + + /** + * Get the operatingSystemName property: Operating system as reported by datacenter management solution. + * + * @return the operatingSystemName value. + */ + public String operatingSystemName() { + return this.operatingSystemName; + } + + /** + * Get the operatingSystemVersion property: Operating system version as reported by datacenter management solution. + * + * @return the operatingSystemVersion value. + */ + public String operatingSystemVersion() { + return this.operatingSystemVersion; + } + + /** + * Get the operatingSystemArchitecture property: Operating system architecture as reported by datacenter management + * solution. + * + * @return the operatingSystemArchitecture value. + */ + public GuestOperatingSystemArchitecture operatingSystemArchitecture() { + return this.operatingSystemArchitecture; + } + + /** + * Get the createdTimestamp property: When was machine first created. + * + * @return the createdTimestamp value. + */ + public OffsetDateTime createdTimestamp() { + return this.createdTimestamp; + } + + /** + * Get the updatedTimestamp property: When was machine last updated. + * + * @return the updatedTimestamp value. + */ + public OffsetDateTime updatedTimestamp() { + return this.updatedTimestamp; + } + + /** + * Get the displayName property: Display Name of the Machine. + * + * @return the displayName value. + */ + public String displayName() { + return this.displayName; + } + + /** + * Get the description property: Description for the machine. + * + * @return the description value. + */ + public String description() { + return this.description; + } + + /** + * Get the datacenterMachineArmId property: Data center machine ARM id. + * + * @return the datacenterMachineArmId value. + */ + public String datacenterMachineArmId() { + return this.datacenterMachineArmId; + } + + /** + * Get the datacenterManagementServerArmId property: Data center management server ARM id. + * + * @return the datacenterManagementServerArmId value. + */ + public String datacenterManagementServerArmId() { + return this.datacenterManagementServerArmId; + } + + /** + * Get the datacenterManagementServerName property: Data center management server name. + * + * @return the datacenterManagementServerName value. + */ + public String datacenterManagementServerName() { + return this.datacenterManagementServerName; + } + + /** + * Get the megabytesOfMemory property: Megabytes of memory found allocated for the machine in private data center. + * + * @return the megabytesOfMemory value. + */ + public Float megabytesOfMemory() { + return this.megabytesOfMemory; + } + + /** + * Get the numberOfCores property: Number of CPU cores found on the machine. + * + * @return the numberOfCores value. + */ + public Integer numberOfCores() { + return this.numberOfCores; + } + + /** + * Get the confidenceRatingInPercentage property: Confidence Rating in Percentage. + * + * @return the confidenceRatingInPercentage value. + */ + public Float confidenceRatingInPercentage() { + return this.confidenceRatingInPercentage; + } + + /** + * Get the percentageCoresUtilization property: Percentile of Percentage of Cores Utilized noted during time period + * T. + * + * Here N and T are settings on Assessment. + * + * @return the percentageCoresUtilization value. + */ + public Float percentageCoresUtilization() { + return this.percentageCoresUtilization; + } + + /** + * Get the percentageMemoryUtilization property: Percentile of Percentage of Memory Utilized noted during time + * period T. + * + * Here N and T are settings on Assessment. + * + * @return the percentageMemoryUtilization value. + */ + public Float percentageMemoryUtilization() { + return this.percentageMemoryUtilization; + } + + /** + * Get the suitability property: Gets a value indicating whether machine is suitable for the cloud platform + * selected. + * + * @return the suitability value. + */ + public CloudSuitability suitability() { + return this.suitability; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (errors() != null) { + errors().forEach(e -> e.validate()); + } + if (disks() != null) { + disks().values().forEach(e -> { + if (e != null) { + e.validate(); + } + }); + } + if (hostProcessor() != null) { + hostProcessor().validate(); + } + if (costComponents() != null) { + costComponents().forEach(e -> e.validate()); + } + if (productSupportStatus() != null) { + productSupportStatus().validate(); + } + if (networkAdapters() != null) { + networkAdapters().values().forEach(e -> { + if (e != null) { + e.validate(); + } + }); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("hostProcessor", this.hostProcessor); + jsonWriter.writeArrayField("costComponents", this.costComponents, + (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessedMachineProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessedMachineProperties 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 AssessedMachineProperties. + */ + public static AssessedMachineProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessedMachineProperties deserializedAssessedMachineProperties = new AssessedMachineProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("errors".equals(fieldName)) { + List errors = reader.readArray(reader1 -> Error.fromJson(reader1)); + deserializedAssessedMachineProperties.errors = errors; + } else if ("disks".equals(fieldName)) { + Map disks = reader.readMap(reader1 -> AssessedDisk.fromJson(reader1)); + deserializedAssessedMachineProperties.disks = disks; + } else if ("monthlyUltraStorageCost".equals(fieldName)) { + deserializedAssessedMachineProperties.monthlyUltraStorageCost + = reader.getNullable(JsonReader::getFloat); + } else if ("hostProcessor".equals(fieldName)) { + deserializedAssessedMachineProperties.hostProcessor = ProcessorInfo.fromJson(reader); + } else if ("costComponents".equals(fieldName)) { + List costComponents = reader.readArray(reader1 -> CostComponent.fromJson(reader1)); + deserializedAssessedMachineProperties.costComponents = costComponents; + } else if ("productSupportStatus".equals(fieldName)) { + deserializedAssessedMachineProperties.productSupportStatus = ProductSupportStatus.fromJson(reader); + } else if ("monthlyBandwidthCost".equals(fieldName)) { + deserializedAssessedMachineProperties.monthlyBandwidthCost + = reader.getNullable(JsonReader::getFloat); + } else if ("monthlyStorageCost".equals(fieldName)) { + deserializedAssessedMachineProperties.monthlyStorageCost = reader.getNullable(JsonReader::getFloat); + } else if ("monthlyPremiumStorageCost".equals(fieldName)) { + deserializedAssessedMachineProperties.monthlyPremiumStorageCost + = reader.getNullable(JsonReader::getFloat); + } else if ("monthlyStandardSsdStorageCost".equals(fieldName)) { + deserializedAssessedMachineProperties.monthlyStandardSsdStorageCost + = reader.getNullable(JsonReader::getFloat); + } else if ("networkAdapters".equals(fieldName)) { + Map networkAdapters + = reader.readMap(reader1 -> AssessedNetworkAdapter.fromJson(reader1)); + deserializedAssessedMachineProperties.networkAdapters = networkAdapters; + } else if ("recommendedSize".equals(fieldName)) { + deserializedAssessedMachineProperties.recommendedSize = AzureVmSize.fromString(reader.getString()); + } else if ("numberOfCoresForRecommendedSize".equals(fieldName)) { + deserializedAssessedMachineProperties.numberOfCoresForRecommendedSize + = reader.getNullable(JsonReader::getInt); + } else if ("megabytesOfMemoryForRecommendedSize".equals(fieldName)) { + deserializedAssessedMachineProperties.megabytesOfMemoryForRecommendedSize + = reader.getNullable(JsonReader::getFloat); + } else if ("monthlyComputeCostForRecommendedSize".equals(fieldName)) { + deserializedAssessedMachineProperties.monthlyComputeCostForRecommendedSize + = reader.getNullable(JsonReader::getFloat); + } else if ("suitabilityExplanation".equals(fieldName)) { + deserializedAssessedMachineProperties.suitabilityExplanation + = AzureVmSuitabilityExplanation.fromString(reader.getString()); + } else if ("suitabilityDetail".equals(fieldName)) { + deserializedAssessedMachineProperties.suitabilityDetail + = AzureVmSuitabilityDetail.fromString(reader.getString()); + } else if ("type".equals(fieldName)) { + deserializedAssessedMachineProperties.type = AssessedMachineType.fromString(reader.getString()); + } else if ("bootType".equals(fieldName)) { + deserializedAssessedMachineProperties.bootType = MachineBootType.fromString(reader.getString()); + } else if ("operatingSystemType".equals(fieldName)) { + deserializedAssessedMachineProperties.operatingSystemType = reader.getString(); + } else if ("operatingSystemName".equals(fieldName)) { + deserializedAssessedMachineProperties.operatingSystemName = reader.getString(); + } else if ("operatingSystemVersion".equals(fieldName)) { + deserializedAssessedMachineProperties.operatingSystemVersion = reader.getString(); + } else if ("operatingSystemArchitecture".equals(fieldName)) { + deserializedAssessedMachineProperties.operatingSystemArchitecture + = GuestOperatingSystemArchitecture.fromString(reader.getString()); + } else if ("createdTimestamp".equals(fieldName)) { + deserializedAssessedMachineProperties.createdTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("updatedTimestamp".equals(fieldName)) { + deserializedAssessedMachineProperties.updatedTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("displayName".equals(fieldName)) { + deserializedAssessedMachineProperties.displayName = reader.getString(); + } else if ("description".equals(fieldName)) { + deserializedAssessedMachineProperties.description = reader.getString(); + } else if ("datacenterMachineArmId".equals(fieldName)) { + deserializedAssessedMachineProperties.datacenterMachineArmId = reader.getString(); + } else if ("datacenterManagementServerArmId".equals(fieldName)) { + deserializedAssessedMachineProperties.datacenterManagementServerArmId = reader.getString(); + } else if ("datacenterManagementServerName".equals(fieldName)) { + deserializedAssessedMachineProperties.datacenterManagementServerName = reader.getString(); + } else if ("megabytesOfMemory".equals(fieldName)) { + deserializedAssessedMachineProperties.megabytesOfMemory = reader.getNullable(JsonReader::getFloat); + } else if ("numberOfCores".equals(fieldName)) { + deserializedAssessedMachineProperties.numberOfCores = reader.getNullable(JsonReader::getInt); + } else if ("confidenceRatingInPercentage".equals(fieldName)) { + deserializedAssessedMachineProperties.confidenceRatingInPercentage + = reader.getNullable(JsonReader::getFloat); + } else if ("percentageCoresUtilization".equals(fieldName)) { + deserializedAssessedMachineProperties.percentageCoresUtilization + = reader.getNullable(JsonReader::getFloat); + } else if ("percentageMemoryUtilization".equals(fieldName)) { + deserializedAssessedMachineProperties.percentageMemoryUtilization + = reader.getNullable(JsonReader::getFloat); + } else if ("suitability".equals(fieldName)) { + deserializedAssessedMachineProperties.suitability = CloudSuitability.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessedMachineProperties; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedMachineType.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedMachineType.java new file mode 100644 index 000000000000..82dcda84675d --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedMachineType.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AssessedMachineType. + */ +public final class AssessedMachineType extends ExpandableStringEnum { + /** + * Static value Unknown for AssessedMachineType. + */ + public static final AssessedMachineType UNKNOWN = fromString("Unknown"); + + /** + * Static value AssessedMachine for AssessedMachineType. + */ + public static final AssessedMachineType ASSESSED_MACHINE = fromString("AssessedMachine"); + + /** + * Static value AvsAssessedMachine for AssessedMachineType. + */ + public static final AssessedMachineType AVS_ASSESSED_MACHINE = fromString("AvsAssessedMachine"); + + /** + * Static value SqlAssessedMachine for AssessedMachineType. + */ + public static final AssessedMachineType SQL_ASSESSED_MACHINE = fromString("SqlAssessedMachine"); + + /** + * Creates a new instance of AssessedMachineType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AssessedMachineType() { + } + + /** + * Creates or finds a AssessedMachineType from its string representation. + * + * @param name a name to look for. + * @return the corresponding AssessedMachineType. + */ + public static AssessedMachineType fromString(String name) { + return fromString(name, AssessedMachineType.class); + } + + /** + * Gets known AssessedMachineType values. + * + * @return known AssessedMachineType values. + */ + public static Collection values() { + return values(AssessedMachineType.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedMachinesOperations.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedMachinesOperations.java new file mode 100644 index 000000000000..a2b2a4cf6e6d --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedMachinesOperations.java @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of AssessedMachinesOperations. + */ +public interface AssessedMachinesOperations { + /** + * List AssessedMachine resources by Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedMachine list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByAssessment(String resourceGroupName, String projectName, String groupName, + String assessmentName); + + /** + * List AssessedMachine resources by Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedMachine list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByAssessment(String resourceGroupName, String projectName, String groupName, + String assessmentName, String filter, Integer pageSize, String continuationToken, Integer totalRecordCount, + Context context); + + /** + * Get a AssessedMachine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param assessedMachineName Machine assessment Assessed Machine ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedMachine along with {@link Response}. + */ + Response getWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, String assessedMachineName, Context context); + + /** + * Get a AssessedMachine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param assessedMachineName Machine assessment Assessed Machine ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedMachine. + */ + AssessedMachine get(String resourceGroupName, String projectName, String groupName, String assessmentName, + String assessedMachineName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedNetworkAdapter.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedNetworkAdapter.java new file mode 100644 index 000000000000..c0a2718b6fa1 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedNetworkAdapter.java @@ -0,0 +1,343 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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.List; + +/** + * Assessed Network Adapter. + */ +@Fluent +public final class AssessedNetworkAdapter implements JsonSerializable { + /* + * Gets the suitability. + */ + private CloudSuitability suitability; + + /* + * Gets the suitability detail. + */ + private AzureNetworkAdapterSuitabilityDetail suitabilityDetail; + + /* + * Gets the suitability explanation. + */ + private AzureNetworkAdapterSuitabilityExplanation suitabilityExplanation; + + /* + * Gets the monthly bandwidth costs. + */ + private Float monthlyBandwidthCosts; + + /* + * Gets the net gigabytes transmitted per month. + */ + private Float netGigabytesTransmittedPerMonth; + + /* + * Gets the display name. + */ + private String displayName; + + /* + * Gets the mac address. + */ + private String macAddress; + + /* + * Gets the ip addresses. + */ + private List ipAddresses; + + /* + * Gets the megabytes per second received. + */ + private Float megabytesPerSecondReceived; + + /* + * Gets the megabytes per second transmitted. + */ + private Float megabytesPerSecondTransmitted; + + /** + * Creates an instance of AssessedNetworkAdapter class. + */ + public AssessedNetworkAdapter() { + } + + /** + * Get the suitability property: Gets the suitability. + * + * @return the suitability value. + */ + public CloudSuitability suitability() { + return this.suitability; + } + + /** + * Set the suitability property: Gets the suitability. + * + * @param suitability the suitability value to set. + * @return the AssessedNetworkAdapter object itself. + */ + public AssessedNetworkAdapter withSuitability(CloudSuitability suitability) { + this.suitability = suitability; + return this; + } + + /** + * Get the suitabilityDetail property: Gets the suitability detail. + * + * @return the suitabilityDetail value. + */ + public AzureNetworkAdapterSuitabilityDetail suitabilityDetail() { + return this.suitabilityDetail; + } + + /** + * Set the suitabilityDetail property: Gets the suitability detail. + * + * @param suitabilityDetail the suitabilityDetail value to set. + * @return the AssessedNetworkAdapter object itself. + */ + public AssessedNetworkAdapter withSuitabilityDetail(AzureNetworkAdapterSuitabilityDetail suitabilityDetail) { + this.suitabilityDetail = suitabilityDetail; + return this; + } + + /** + * Get the suitabilityExplanation property: Gets the suitability explanation. + * + * @return the suitabilityExplanation value. + */ + public AzureNetworkAdapterSuitabilityExplanation suitabilityExplanation() { + return this.suitabilityExplanation; + } + + /** + * Set the suitabilityExplanation property: Gets the suitability explanation. + * + * @param suitabilityExplanation the suitabilityExplanation value to set. + * @return the AssessedNetworkAdapter object itself. + */ + public AssessedNetworkAdapter + withSuitabilityExplanation(AzureNetworkAdapterSuitabilityExplanation suitabilityExplanation) { + this.suitabilityExplanation = suitabilityExplanation; + return this; + } + + /** + * Get the monthlyBandwidthCosts property: Gets the monthly bandwidth costs. + * + * @return the monthlyBandwidthCosts value. + */ + public Float monthlyBandwidthCosts() { + return this.monthlyBandwidthCosts; + } + + /** + * Set the monthlyBandwidthCosts property: Gets the monthly bandwidth costs. + * + * @param monthlyBandwidthCosts the monthlyBandwidthCosts value to set. + * @return the AssessedNetworkAdapter object itself. + */ + public AssessedNetworkAdapter withMonthlyBandwidthCosts(Float monthlyBandwidthCosts) { + this.monthlyBandwidthCosts = monthlyBandwidthCosts; + return this; + } + + /** + * Get the netGigabytesTransmittedPerMonth property: Gets the net gigabytes transmitted per month. + * + * @return the netGigabytesTransmittedPerMonth value. + */ + public Float netGigabytesTransmittedPerMonth() { + return this.netGigabytesTransmittedPerMonth; + } + + /** + * Set the netGigabytesTransmittedPerMonth property: Gets the net gigabytes transmitted per month. + * + * @param netGigabytesTransmittedPerMonth the netGigabytesTransmittedPerMonth value to set. + * @return the AssessedNetworkAdapter object itself. + */ + public AssessedNetworkAdapter withNetGigabytesTransmittedPerMonth(Float netGigabytesTransmittedPerMonth) { + this.netGigabytesTransmittedPerMonth = netGigabytesTransmittedPerMonth; + return this; + } + + /** + * Get the displayName property: Gets the display name. + * + * @return the displayName value. + */ + public String displayName() { + return this.displayName; + } + + /** + * Set the displayName property: Gets the display name. + * + * @param displayName the displayName value to set. + * @return the AssessedNetworkAdapter object itself. + */ + public AssessedNetworkAdapter withDisplayName(String displayName) { + this.displayName = displayName; + return this; + } + + /** + * Get the macAddress property: Gets the mac address. + * + * @return the macAddress value. + */ + public String macAddress() { + return this.macAddress; + } + + /** + * Set the macAddress property: Gets the mac address. + * + * @param macAddress the macAddress value to set. + * @return the AssessedNetworkAdapter object itself. + */ + public AssessedNetworkAdapter withMacAddress(String macAddress) { + this.macAddress = macAddress; + return this; + } + + /** + * Get the ipAddresses property: Gets the ip addresses. + * + * @return the ipAddresses value. + */ + public List ipAddresses() { + return this.ipAddresses; + } + + /** + * Get the megabytesPerSecondReceived property: Gets the megabytes per second received. + * + * @return the megabytesPerSecondReceived value. + */ + public Float megabytesPerSecondReceived() { + return this.megabytesPerSecondReceived; + } + + /** + * Set the megabytesPerSecondReceived property: Gets the megabytes per second received. + * + * @param megabytesPerSecondReceived the megabytesPerSecondReceived value to set. + * @return the AssessedNetworkAdapter object itself. + */ + public AssessedNetworkAdapter withMegabytesPerSecondReceived(Float megabytesPerSecondReceived) { + this.megabytesPerSecondReceived = megabytesPerSecondReceived; + return this; + } + + /** + * Get the megabytesPerSecondTransmitted property: Gets the megabytes per second transmitted. + * + * @return the megabytesPerSecondTransmitted value. + */ + public Float megabytesPerSecondTransmitted() { + return this.megabytesPerSecondTransmitted; + } + + /** + * Set the megabytesPerSecondTransmitted property: Gets the megabytes per second transmitted. + * + * @param megabytesPerSecondTransmitted the megabytesPerSecondTransmitted value to set. + * @return the AssessedNetworkAdapter object itself. + */ + public AssessedNetworkAdapter withMegabytesPerSecondTransmitted(Float megabytesPerSecondTransmitted) { + this.megabytesPerSecondTransmitted = megabytesPerSecondTransmitted; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("suitability", this.suitability == null ? null : this.suitability.toString()); + jsonWriter.writeStringField("suitabilityDetail", + this.suitabilityDetail == null ? null : this.suitabilityDetail.toString()); + jsonWriter.writeStringField("suitabilityExplanation", + this.suitabilityExplanation == null ? null : this.suitabilityExplanation.toString()); + jsonWriter.writeNumberField("monthlyBandwidthCosts", this.monthlyBandwidthCosts); + jsonWriter.writeNumberField("netGigabytesTransmittedPerMonth", this.netGigabytesTransmittedPerMonth); + jsonWriter.writeStringField("displayName", this.displayName); + jsonWriter.writeStringField("macAddress", this.macAddress); + jsonWriter.writeNumberField("megabytesPerSecondReceived", this.megabytesPerSecondReceived); + jsonWriter.writeNumberField("megabytesPerSecondTransmitted", this.megabytesPerSecondTransmitted); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessedNetworkAdapter from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessedNetworkAdapter 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 AssessedNetworkAdapter. + */ + public static AssessedNetworkAdapter fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessedNetworkAdapter deserializedAssessedNetworkAdapter = new AssessedNetworkAdapter(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("suitability".equals(fieldName)) { + deserializedAssessedNetworkAdapter.suitability = CloudSuitability.fromString(reader.getString()); + } else if ("suitabilityDetail".equals(fieldName)) { + deserializedAssessedNetworkAdapter.suitabilityDetail + = AzureNetworkAdapterSuitabilityDetail.fromString(reader.getString()); + } else if ("suitabilityExplanation".equals(fieldName)) { + deserializedAssessedNetworkAdapter.suitabilityExplanation + = AzureNetworkAdapterSuitabilityExplanation.fromString(reader.getString()); + } else if ("monthlyBandwidthCosts".equals(fieldName)) { + deserializedAssessedNetworkAdapter.monthlyBandwidthCosts = reader.getNullable(JsonReader::getFloat); + } else if ("netGigabytesTransmittedPerMonth".equals(fieldName)) { + deserializedAssessedNetworkAdapter.netGigabytesTransmittedPerMonth + = reader.getNullable(JsonReader::getFloat); + } else if ("displayName".equals(fieldName)) { + deserializedAssessedNetworkAdapter.displayName = reader.getString(); + } else if ("macAddress".equals(fieldName)) { + deserializedAssessedNetworkAdapter.macAddress = reader.getString(); + } else if ("ipAddresses".equals(fieldName)) { + List ipAddresses = reader.readArray(reader1 -> reader1.getString()); + deserializedAssessedNetworkAdapter.ipAddresses = ipAddresses; + } else if ("megabytesPerSecondReceived".equals(fieldName)) { + deserializedAssessedNetworkAdapter.megabytesPerSecondReceived + = reader.getNullable(JsonReader::getFloat); + } else if ("megabytesPerSecondTransmitted".equals(fieldName)) { + deserializedAssessedNetworkAdapter.megabytesPerSecondTransmitted + = reader.getNullable(JsonReader::getFloat); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessedNetworkAdapter; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlDatabaseV2.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlDatabaseV2.java new file mode 100644 index 000000000000..ec3b7682f491 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlDatabaseV2.java @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlDatabaseV2Inner; + +/** + * An immutable client-side representation of AssessedSqlDatabaseV2. + */ +public interface AssessedSqlDatabaseV2 { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + AssessedSqlDatabaseV2Properties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlDatabaseV2Inner object. + * + * @return the inner object. + */ + AssessedSqlDatabaseV2Inner innerModel(); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlDatabaseV2ListResult.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlDatabaseV2ListResult.java new file mode 100644 index 000000000000..23db29c30e22 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlDatabaseV2ListResult.java @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlDatabaseV2Inner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a AssessedSqlDatabaseV2 list operation. + */ +@Fluent +public final class AssessedSqlDatabaseV2ListResult implements JsonSerializable { + /* + * The AssessedSqlDatabaseV2 items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of AssessedSqlDatabaseV2ListResult class. + */ + public AssessedSqlDatabaseV2ListResult() { + } + + /** + * Get the value property: The AssessedSqlDatabaseV2 items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Set the value property: The AssessedSqlDatabaseV2 items on this page. + * + * @param value the value value to set. + * @return the AssessedSqlDatabaseV2ListResult object itself. + */ + public AssessedSqlDatabaseV2ListResult withValue(List value) { + this.value = value; + return this; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The link to the next page of items. + * + * @param nextLink the nextLink value to set. + * @return the AssessedSqlDatabaseV2ListResult object itself. + */ + public AssessedSqlDatabaseV2ListResult withNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property value in model AssessedSqlDatabaseV2ListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(AssessedSqlDatabaseV2ListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessedSqlDatabaseV2ListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessedSqlDatabaseV2ListResult 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 AssessedSqlDatabaseV2ListResult. + */ + public static AssessedSqlDatabaseV2ListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessedSqlDatabaseV2ListResult deserializedAssessedSqlDatabaseV2ListResult + = new AssessedSqlDatabaseV2ListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> AssessedSqlDatabaseV2Inner.fromJson(reader1)); + deserializedAssessedSqlDatabaseV2ListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2ListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessedSqlDatabaseV2ListResult; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlDatabaseV2Operations.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlDatabaseV2Operations.java new file mode 100644 index 000000000000..534519b8401c --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlDatabaseV2Operations.java @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of AssessedSqlDatabaseV2Operations. + */ +public interface AssessedSqlDatabaseV2Operations { + /** + * List AssessedSqlDatabaseV2 resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlDatabaseV2 list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName); + + /** + * List AssessedSqlDatabaseV2 resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlDatabaseV2 list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName, String filter, Integer pageSize, String continuationToken, + Integer totalRecordCount, Context context); + + /** + * Get a AssessedSqlDatabaseV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param assessedSqlDatabaseName Sql assessment Assessed Databases ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlDatabaseV2 along with {@link Response}. + */ + Response getWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, String assessedSqlDatabaseName, Context context); + + /** + * Get a AssessedSqlDatabaseV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param assessedSqlDatabaseName Sql assessment Assessed Databases ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlDatabaseV2. + */ + AssessedSqlDatabaseV2 get(String resourceGroupName, String projectName, String groupName, String assessmentName, + String assessedSqlDatabaseName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlDatabaseV2Properties.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlDatabaseV2Properties.java new file mode 100644 index 000000000000..ad935a45c06e --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlDatabaseV2Properties.java @@ -0,0 +1,509 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; + +/** + * Assessed SQL database properties web model. + */ +@Immutable +public final class AssessedSqlDatabaseV2Properties implements JsonSerializable { + /* + * Gets or sets the recommended azure SQL target type. + */ + private TargetType recommendedAzureSqlTargetType; + + /* + * Gets or sets the recommended azure SQL suitability. + */ + private RecommendedSuitability recommendedSuitability; + + /* + * Gets or sets the aggregated cache size of this database. This is a performance + * data metric for this DB. + */ + private Float bufferCacheSizeInMB; + + /* + * Gets the product support status related details. + */ + private ProductSupportStatus productSupportStatus; + + /* + * Gets or sets the azure SQL MI suitability details. + */ + private SqlAssessmentV2PaasSuitabilityData azureSqlMISuitabilityDetails; + + /* + * Gets or sets the azure SQL DB suitability details. + */ + private SqlAssessmentV2PaasSuitabilityData azureSqlDBSuitabilityDetails; + + /* + * Gets a value indicating whether the assessed SQL database is highly available + * or not. + */ + private Boolean isDatabaseHighlyAvailable; + + /* + * Gets the linked availability group overview if the database being assessed is + * highly available. + */ + private SqlAvailabilityGroupDataOverview linkedAvailabilityGroupOverview; + + /* + * Machine arm id. + */ + private String machineArmId; + + /* + * Assessed SQL instance arm id. + */ + private String assessedSqlInstanceArmId; + + /* + * Machine display name. + */ + private String machineName; + + /* + * SQL instance name. + */ + private String instanceName; + + /* + * SQL database name. + */ + private String databaseName; + + /* + * SQL database size in megabytes. + */ + private Float databaseSizeInMB; + + /* + * Database compatibility level. + */ + private CompatibilityLevel compatibilityLevel; + + /* + * SQL database SDS arm id. + */ + private String sqlDatabaseSdsArmId; + + /* + * The percentage of the total number of cores being utilized by the SQL database. + */ + private Float percentageCoresUtilization; + + /* + * The read throughput of the SQL database. + */ + private Float megabytesPerSecondOfRead; + + /* + * The write throughput of the SQL database. + */ + private Float megabytesPerSecondOfWrite; + + /* + * The read operations per second of the SQL database. + */ + private Float numberOfReadOperationsPerSecond; + + /* + * The write operations per second of the SQL database. + */ + private Float numberOfWriteOperationsPerSecond; + + /* + * Confidence Rating in Percentage. + */ + private Float confidenceRatingInPercentage; + + /* + * Assessment sizing criterion. + */ + private AssessmentSizingCriterion sizingCriterion; + + /* + * When was assessed SQL database first created. + */ + private OffsetDateTime createdTimestamp; + + /* + * When was assessed SQL database last updated. + */ + private OffsetDateTime updatedTimestamp; + + /** + * Creates an instance of AssessedSqlDatabaseV2Properties class. + */ + public AssessedSqlDatabaseV2Properties() { + } + + /** + * Get the recommendedAzureSqlTargetType property: Gets or sets the recommended azure SQL target type. + * + * @return the recommendedAzureSqlTargetType value. + */ + public TargetType recommendedAzureSqlTargetType() { + return this.recommendedAzureSqlTargetType; + } + + /** + * Get the recommendedSuitability property: Gets or sets the recommended azure SQL suitability. + * + * @return the recommendedSuitability value. + */ + public RecommendedSuitability recommendedSuitability() { + return this.recommendedSuitability; + } + + /** + * Get the bufferCacheSizeInMB property: Gets or sets the aggregated cache size of this database. This is a + * performance + * data metric for this DB. + * + * @return the bufferCacheSizeInMB value. + */ + public Float bufferCacheSizeInMB() { + return this.bufferCacheSizeInMB; + } + + /** + * Get the productSupportStatus property: Gets the product support status related details. + * + * @return the productSupportStatus value. + */ + public ProductSupportStatus productSupportStatus() { + return this.productSupportStatus; + } + + /** + * Get the azureSqlMISuitabilityDetails property: Gets or sets the azure SQL MI suitability details. + * + * @return the azureSqlMISuitabilityDetails value. + */ + public SqlAssessmentV2PaasSuitabilityData azureSqlMISuitabilityDetails() { + return this.azureSqlMISuitabilityDetails; + } + + /** + * Get the azureSqlDBSuitabilityDetails property: Gets or sets the azure SQL DB suitability details. + * + * @return the azureSqlDBSuitabilityDetails value. + */ + public SqlAssessmentV2PaasSuitabilityData azureSqlDBSuitabilityDetails() { + return this.azureSqlDBSuitabilityDetails; + } + + /** + * Get the isDatabaseHighlyAvailable property: Gets a value indicating whether the assessed SQL database is highly + * available + * or not. + * + * @return the isDatabaseHighlyAvailable value. + */ + public Boolean isDatabaseHighlyAvailable() { + return this.isDatabaseHighlyAvailable; + } + + /** + * Get the linkedAvailabilityGroupOverview property: Gets the linked availability group overview if the database + * being assessed is + * highly available. + * + * @return the linkedAvailabilityGroupOverview value. + */ + public SqlAvailabilityGroupDataOverview linkedAvailabilityGroupOverview() { + return this.linkedAvailabilityGroupOverview; + } + + /** + * Get the machineArmId property: Machine arm id. + * + * @return the machineArmId value. + */ + public String machineArmId() { + return this.machineArmId; + } + + /** + * Get the assessedSqlInstanceArmId property: Assessed SQL instance arm id. + * + * @return the assessedSqlInstanceArmId value. + */ + public String assessedSqlInstanceArmId() { + return this.assessedSqlInstanceArmId; + } + + /** + * Get the machineName property: Machine display name. + * + * @return the machineName value. + */ + public String machineName() { + return this.machineName; + } + + /** + * Get the instanceName property: SQL instance name. + * + * @return the instanceName value. + */ + public String instanceName() { + return this.instanceName; + } + + /** + * Get the databaseName property: SQL database name. + * + * @return the databaseName value. + */ + public String databaseName() { + return this.databaseName; + } + + /** + * Get the databaseSizeInMB property: SQL database size in megabytes. + * + * @return the databaseSizeInMB value. + */ + public Float databaseSizeInMB() { + return this.databaseSizeInMB; + } + + /** + * Get the compatibilityLevel property: Database compatibility level. + * + * @return the compatibilityLevel value. + */ + public CompatibilityLevel compatibilityLevel() { + return this.compatibilityLevel; + } + + /** + * Get the sqlDatabaseSdsArmId property: SQL database SDS arm id. + * + * @return the sqlDatabaseSdsArmId value. + */ + public String sqlDatabaseSdsArmId() { + return this.sqlDatabaseSdsArmId; + } + + /** + * Get the percentageCoresUtilization property: The percentage of the total number of cores being utilized by the + * SQL database. + * + * @return the percentageCoresUtilization value. + */ + public Float percentageCoresUtilization() { + return this.percentageCoresUtilization; + } + + /** + * Get the megabytesPerSecondOfRead property: The read throughput of the SQL database. + * + * @return the megabytesPerSecondOfRead value. + */ + public Float megabytesPerSecondOfRead() { + return this.megabytesPerSecondOfRead; + } + + /** + * Get the megabytesPerSecondOfWrite property: The write throughput of the SQL database. + * + * @return the megabytesPerSecondOfWrite value. + */ + public Float megabytesPerSecondOfWrite() { + return this.megabytesPerSecondOfWrite; + } + + /** + * Get the numberOfReadOperationsPerSecond property: The read operations per second of the SQL database. + * + * @return the numberOfReadOperationsPerSecond value. + */ + public Float numberOfReadOperationsPerSecond() { + return this.numberOfReadOperationsPerSecond; + } + + /** + * Get the numberOfWriteOperationsPerSecond property: The write operations per second of the SQL database. + * + * @return the numberOfWriteOperationsPerSecond value. + */ + public Float numberOfWriteOperationsPerSecond() { + return this.numberOfWriteOperationsPerSecond; + } + + /** + * Get the confidenceRatingInPercentage property: Confidence Rating in Percentage. + * + * @return the confidenceRatingInPercentage value. + */ + public Float confidenceRatingInPercentage() { + return this.confidenceRatingInPercentage; + } + + /** + * Get the sizingCriterion property: Assessment sizing criterion. + * + * @return the sizingCriterion value. + */ + public AssessmentSizingCriterion sizingCriterion() { + return this.sizingCriterion; + } + + /** + * Get the createdTimestamp property: When was assessed SQL database first created. + * + * @return the createdTimestamp value. + */ + public OffsetDateTime createdTimestamp() { + return this.createdTimestamp; + } + + /** + * Get the updatedTimestamp property: When was assessed SQL database last updated. + * + * @return the updatedTimestamp value. + */ + public OffsetDateTime updatedTimestamp() { + return this.updatedTimestamp; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (productSupportStatus() != null) { + productSupportStatus().validate(); + } + if (azureSqlMISuitabilityDetails() != null) { + azureSqlMISuitabilityDetails().validate(); + } + if (azureSqlDBSuitabilityDetails() != null) { + azureSqlDBSuitabilityDetails().validate(); + } + if (linkedAvailabilityGroupOverview() != null) { + linkedAvailabilityGroupOverview().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessedSqlDatabaseV2Properties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessedSqlDatabaseV2Properties 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 AssessedSqlDatabaseV2Properties. + */ + public static AssessedSqlDatabaseV2Properties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessedSqlDatabaseV2Properties deserializedAssessedSqlDatabaseV2Properties + = new AssessedSqlDatabaseV2Properties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("recommendedAzureSqlTargetType".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Properties.recommendedAzureSqlTargetType + = TargetType.fromString(reader.getString()); + } else if ("recommendedSuitability".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Properties.recommendedSuitability + = RecommendedSuitability.fromString(reader.getString()); + } else if ("bufferCacheSizeInMB".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Properties.bufferCacheSizeInMB + = reader.getNullable(JsonReader::getFloat); + } else if ("productSupportStatus".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Properties.productSupportStatus + = ProductSupportStatus.fromJson(reader); + } else if ("azureSqlMISuitabilityDetails".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Properties.azureSqlMISuitabilityDetails + = SqlAssessmentV2PaasSuitabilityData.fromJson(reader); + } else if ("azureSqlDBSuitabilityDetails".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Properties.azureSqlDBSuitabilityDetails + = SqlAssessmentV2PaasSuitabilityData.fromJson(reader); + } else if ("isDatabaseHighlyAvailable".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Properties.isDatabaseHighlyAvailable + = reader.getNullable(JsonReader::getBoolean); + } else if ("linkedAvailabilityGroupOverview".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Properties.linkedAvailabilityGroupOverview + = SqlAvailabilityGroupDataOverview.fromJson(reader); + } else if ("machineArmId".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Properties.machineArmId = reader.getString(); + } else if ("assessedSqlInstanceArmId".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Properties.assessedSqlInstanceArmId = reader.getString(); + } else if ("machineName".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Properties.machineName = reader.getString(); + } else if ("instanceName".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Properties.instanceName = reader.getString(); + } else if ("databaseName".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Properties.databaseName = reader.getString(); + } else if ("databaseSizeInMB".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Properties.databaseSizeInMB + = reader.getNullable(JsonReader::getFloat); + } else if ("compatibilityLevel".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Properties.compatibilityLevel + = CompatibilityLevel.fromString(reader.getString()); + } else if ("sqlDatabaseSdsArmId".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Properties.sqlDatabaseSdsArmId = reader.getString(); + } else if ("percentageCoresUtilization".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Properties.percentageCoresUtilization + = reader.getNullable(JsonReader::getFloat); + } else if ("megabytesPerSecondOfRead".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Properties.megabytesPerSecondOfRead + = reader.getNullable(JsonReader::getFloat); + } else if ("megabytesPerSecondOfWrite".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Properties.megabytesPerSecondOfWrite + = reader.getNullable(JsonReader::getFloat); + } else if ("numberOfReadOperationsPerSecond".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Properties.numberOfReadOperationsPerSecond + = reader.getNullable(JsonReader::getFloat); + } else if ("numberOfWriteOperationsPerSecond".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Properties.numberOfWriteOperationsPerSecond + = reader.getNullable(JsonReader::getFloat); + } else if ("confidenceRatingInPercentage".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Properties.confidenceRatingInPercentage + = reader.getNullable(JsonReader::getFloat); + } else if ("sizingCriterion".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Properties.sizingCriterion + = AssessmentSizingCriterion.fromString(reader.getString()); + } else if ("createdTimestamp".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Properties.createdTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("updatedTimestamp".equals(fieldName)) { + deserializedAssessedSqlDatabaseV2Properties.updatedTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessedSqlDatabaseV2Properties; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlInstanceDatabaseSummary.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlInstanceDatabaseSummary.java new file mode 100644 index 000000000000..350fb25346aa --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlInstanceDatabaseSummary.java @@ -0,0 +1,182 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * Assessed Sql Instance Database Summary. + */ +@Fluent +public final class AssessedSqlInstanceDatabaseSummary implements JsonSerializable { + /* + * Gets the number of user databases. + */ + private Integer numberOfUserDatabases; + + /* + * Gets the total database size in MB. + */ + private Float totalDatabaseSizeInMB; + + /* + * Gets the largest database size in MB. + */ + private Float largestDatabaseSizeInMB; + + /* + * Gets the total discovered user databases. + */ + private Integer totalDiscoveredUserDatabases; + + /** + * Creates an instance of AssessedSqlInstanceDatabaseSummary class. + */ + public AssessedSqlInstanceDatabaseSummary() { + } + + /** + * Get the numberOfUserDatabases property: Gets the number of user databases. + * + * @return the numberOfUserDatabases value. + */ + public Integer numberOfUserDatabases() { + return this.numberOfUserDatabases; + } + + /** + * Set the numberOfUserDatabases property: Gets the number of user databases. + * + * @param numberOfUserDatabases the numberOfUserDatabases value to set. + * @return the AssessedSqlInstanceDatabaseSummary object itself. + */ + public AssessedSqlInstanceDatabaseSummary withNumberOfUserDatabases(Integer numberOfUserDatabases) { + this.numberOfUserDatabases = numberOfUserDatabases; + return this; + } + + /** + * Get the totalDatabaseSizeInMB property: Gets the total database size in MB. + * + * @return the totalDatabaseSizeInMB value. + */ + public Float totalDatabaseSizeInMB() { + return this.totalDatabaseSizeInMB; + } + + /** + * Set the totalDatabaseSizeInMB property: Gets the total database size in MB. + * + * @param totalDatabaseSizeInMB the totalDatabaseSizeInMB value to set. + * @return the AssessedSqlInstanceDatabaseSummary object itself. + */ + public AssessedSqlInstanceDatabaseSummary withTotalDatabaseSizeInMB(Float totalDatabaseSizeInMB) { + this.totalDatabaseSizeInMB = totalDatabaseSizeInMB; + return this; + } + + /** + * Get the largestDatabaseSizeInMB property: Gets the largest database size in MB. + * + * @return the largestDatabaseSizeInMB value. + */ + public Float largestDatabaseSizeInMB() { + return this.largestDatabaseSizeInMB; + } + + /** + * Set the largestDatabaseSizeInMB property: Gets the largest database size in MB. + * + * @param largestDatabaseSizeInMB the largestDatabaseSizeInMB value to set. + * @return the AssessedSqlInstanceDatabaseSummary object itself. + */ + public AssessedSqlInstanceDatabaseSummary withLargestDatabaseSizeInMB(Float largestDatabaseSizeInMB) { + this.largestDatabaseSizeInMB = largestDatabaseSizeInMB; + return this; + } + + /** + * Get the totalDiscoveredUserDatabases property: Gets the total discovered user databases. + * + * @return the totalDiscoveredUserDatabases value. + */ + public Integer totalDiscoveredUserDatabases() { + return this.totalDiscoveredUserDatabases; + } + + /** + * Set the totalDiscoveredUserDatabases property: Gets the total discovered user databases. + * + * @param totalDiscoveredUserDatabases the totalDiscoveredUserDatabases value to set. + * @return the AssessedSqlInstanceDatabaseSummary object itself. + */ + public AssessedSqlInstanceDatabaseSummary withTotalDiscoveredUserDatabases(Integer totalDiscoveredUserDatabases) { + this.totalDiscoveredUserDatabases = totalDiscoveredUserDatabases; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeNumberField("numberOfUserDatabases", this.numberOfUserDatabases); + jsonWriter.writeNumberField("totalDatabaseSizeInMB", this.totalDatabaseSizeInMB); + jsonWriter.writeNumberField("largestDatabaseSizeInMB", this.largestDatabaseSizeInMB); + jsonWriter.writeNumberField("totalDiscoveredUserDatabases", this.totalDiscoveredUserDatabases); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessedSqlInstanceDatabaseSummary from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessedSqlInstanceDatabaseSummary 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 AssessedSqlInstanceDatabaseSummary. + */ + public static AssessedSqlInstanceDatabaseSummary fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessedSqlInstanceDatabaseSummary deserializedAssessedSqlInstanceDatabaseSummary + = new AssessedSqlInstanceDatabaseSummary(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("numberOfUserDatabases".equals(fieldName)) { + deserializedAssessedSqlInstanceDatabaseSummary.numberOfUserDatabases + = reader.getNullable(JsonReader::getInt); + } else if ("totalDatabaseSizeInMB".equals(fieldName)) { + deserializedAssessedSqlInstanceDatabaseSummary.totalDatabaseSizeInMB + = reader.getNullable(JsonReader::getFloat); + } else if ("largestDatabaseSizeInMB".equals(fieldName)) { + deserializedAssessedSqlInstanceDatabaseSummary.largestDatabaseSizeInMB + = reader.getNullable(JsonReader::getFloat); + } else if ("totalDiscoveredUserDatabases".equals(fieldName)) { + deserializedAssessedSqlInstanceDatabaseSummary.totalDiscoveredUserDatabases + = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessedSqlInstanceDatabaseSummary; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlInstanceDiskDetails.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlInstanceDiskDetails.java new file mode 100644 index 000000000000..fb8a0bd9838f --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlInstanceDiskDetails.java @@ -0,0 +1,238 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * Assessed Sql Instance Disk Details. + */ +@Fluent +public final class AssessedSqlInstanceDiskDetails implements JsonSerializable { + /* + * Gets the disk id. + */ + private String diskId; + + /* + * Gets the disk size in mb. + */ + private Float diskSizeInMB; + + /* + * Gets the megabytes per second of read. + */ + private Float megabytesPerSecondOfRead; + + /* + * Gets the megabytes per second of write. + */ + private Float megabytesPerSecondOfWrite; + + /* + * Gets the number of read operations per second. + */ + private Float numberOfReadOperationsPerSecond; + + /* + * Gets the number of write operations per second. + */ + private Float numberOfWriteOperationsPerSecond; + + /** + * Creates an instance of AssessedSqlInstanceDiskDetails class. + */ + public AssessedSqlInstanceDiskDetails() { + } + + /** + * Get the diskId property: Gets the disk id. + * + * @return the diskId value. + */ + public String diskId() { + return this.diskId; + } + + /** + * Set the diskId property: Gets the disk id. + * + * @param diskId the diskId value to set. + * @return the AssessedSqlInstanceDiskDetails object itself. + */ + public AssessedSqlInstanceDiskDetails withDiskId(String diskId) { + this.diskId = diskId; + return this; + } + + /** + * Get the diskSizeInMB property: Gets the disk size in mb. + * + * @return the diskSizeInMB value. + */ + public Float diskSizeInMB() { + return this.diskSizeInMB; + } + + /** + * Set the diskSizeInMB property: Gets the disk size in mb. + * + * @param diskSizeInMB the diskSizeInMB value to set. + * @return the AssessedSqlInstanceDiskDetails object itself. + */ + public AssessedSqlInstanceDiskDetails withDiskSizeInMB(Float diskSizeInMB) { + this.diskSizeInMB = diskSizeInMB; + return this; + } + + /** + * Get the megabytesPerSecondOfRead property: Gets the megabytes per second of read. + * + * @return the megabytesPerSecondOfRead value. + */ + public Float megabytesPerSecondOfRead() { + return this.megabytesPerSecondOfRead; + } + + /** + * Set the megabytesPerSecondOfRead property: Gets the megabytes per second of read. + * + * @param megabytesPerSecondOfRead the megabytesPerSecondOfRead value to set. + * @return the AssessedSqlInstanceDiskDetails object itself. + */ + public AssessedSqlInstanceDiskDetails withMegabytesPerSecondOfRead(Float megabytesPerSecondOfRead) { + this.megabytesPerSecondOfRead = megabytesPerSecondOfRead; + return this; + } + + /** + * Get the megabytesPerSecondOfWrite property: Gets the megabytes per second of write. + * + * @return the megabytesPerSecondOfWrite value. + */ + public Float megabytesPerSecondOfWrite() { + return this.megabytesPerSecondOfWrite; + } + + /** + * Set the megabytesPerSecondOfWrite property: Gets the megabytes per second of write. + * + * @param megabytesPerSecondOfWrite the megabytesPerSecondOfWrite value to set. + * @return the AssessedSqlInstanceDiskDetails object itself. + */ + public AssessedSqlInstanceDiskDetails withMegabytesPerSecondOfWrite(Float megabytesPerSecondOfWrite) { + this.megabytesPerSecondOfWrite = megabytesPerSecondOfWrite; + return this; + } + + /** + * Get the numberOfReadOperationsPerSecond property: Gets the number of read operations per second. + * + * @return the numberOfReadOperationsPerSecond value. + */ + public Float numberOfReadOperationsPerSecond() { + return this.numberOfReadOperationsPerSecond; + } + + /** + * Set the numberOfReadOperationsPerSecond property: Gets the number of read operations per second. + * + * @param numberOfReadOperationsPerSecond the numberOfReadOperationsPerSecond value to set. + * @return the AssessedSqlInstanceDiskDetails object itself. + */ + public AssessedSqlInstanceDiskDetails withNumberOfReadOperationsPerSecond(Float numberOfReadOperationsPerSecond) { + this.numberOfReadOperationsPerSecond = numberOfReadOperationsPerSecond; + return this; + } + + /** + * Get the numberOfWriteOperationsPerSecond property: Gets the number of write operations per second. + * + * @return the numberOfWriteOperationsPerSecond value. + */ + public Float numberOfWriteOperationsPerSecond() { + return this.numberOfWriteOperationsPerSecond; + } + + /** + * Set the numberOfWriteOperationsPerSecond property: Gets the number of write operations per second. + * + * @param numberOfWriteOperationsPerSecond the numberOfWriteOperationsPerSecond value to set. + * @return the AssessedSqlInstanceDiskDetails object itself. + */ + public AssessedSqlInstanceDiskDetails withNumberOfWriteOperationsPerSecond(Float numberOfWriteOperationsPerSecond) { + this.numberOfWriteOperationsPerSecond = numberOfWriteOperationsPerSecond; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("diskId", this.diskId); + jsonWriter.writeNumberField("diskSizeInMB", this.diskSizeInMB); + jsonWriter.writeNumberField("megabytesPerSecondOfRead", this.megabytesPerSecondOfRead); + jsonWriter.writeNumberField("megabytesPerSecondOfWrite", this.megabytesPerSecondOfWrite); + jsonWriter.writeNumberField("numberOfReadOperationsPerSecond", this.numberOfReadOperationsPerSecond); + jsonWriter.writeNumberField("numberOfWriteOperationsPerSecond", this.numberOfWriteOperationsPerSecond); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessedSqlInstanceDiskDetails from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessedSqlInstanceDiskDetails 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 AssessedSqlInstanceDiskDetails. + */ + public static AssessedSqlInstanceDiskDetails fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessedSqlInstanceDiskDetails deserializedAssessedSqlInstanceDiskDetails + = new AssessedSqlInstanceDiskDetails(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("diskId".equals(fieldName)) { + deserializedAssessedSqlInstanceDiskDetails.diskId = reader.getString(); + } else if ("diskSizeInMB".equals(fieldName)) { + deserializedAssessedSqlInstanceDiskDetails.diskSizeInMB = reader.getNullable(JsonReader::getFloat); + } else if ("megabytesPerSecondOfRead".equals(fieldName)) { + deserializedAssessedSqlInstanceDiskDetails.megabytesPerSecondOfRead + = reader.getNullable(JsonReader::getFloat); + } else if ("megabytesPerSecondOfWrite".equals(fieldName)) { + deserializedAssessedSqlInstanceDiskDetails.megabytesPerSecondOfWrite + = reader.getNullable(JsonReader::getFloat); + } else if ("numberOfReadOperationsPerSecond".equals(fieldName)) { + deserializedAssessedSqlInstanceDiskDetails.numberOfReadOperationsPerSecond + = reader.getNullable(JsonReader::getFloat); + } else if ("numberOfWriteOperationsPerSecond".equals(fieldName)) { + deserializedAssessedSqlInstanceDiskDetails.numberOfWriteOperationsPerSecond + = reader.getNullable(JsonReader::getFloat); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessedSqlInstanceDiskDetails; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlInstanceStorageDetails.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlInstanceStorageDetails.java new file mode 100644 index 000000000000..4a37a4913f62 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlInstanceStorageDetails.java @@ -0,0 +1,241 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * Assessed Sql Instance Storage Details. + */ +@Fluent +public final class AssessedSqlInstanceStorageDetails implements JsonSerializable { + /* + * Gets the storage type. + */ + private String storageType; + + /* + * Gets the disk size in mb. + */ + private Float diskSizeInMB; + + /* + * Gets the megabytes per second of read. + */ + private Float megabytesPerSecondOfRead; + + /* + * Gets the megabytes per second of read. + */ + private Float megabytesPerSecondOfWrite; + + /* + * Gets the number of read operations per second. + */ + private Float numberOfReadOperationsPerSecond; + + /* + * Gets the number of write operations per second. + */ + private Float numberOfWriteOperationsPerSecond; + + /** + * Creates an instance of AssessedSqlInstanceStorageDetails class. + */ + public AssessedSqlInstanceStorageDetails() { + } + + /** + * Get the storageType property: Gets the storage type. + * + * @return the storageType value. + */ + public String storageType() { + return this.storageType; + } + + /** + * Set the storageType property: Gets the storage type. + * + * @param storageType the storageType value to set. + * @return the AssessedSqlInstanceStorageDetails object itself. + */ + public AssessedSqlInstanceStorageDetails withStorageType(String storageType) { + this.storageType = storageType; + return this; + } + + /** + * Get the diskSizeInMB property: Gets the disk size in mb. + * + * @return the diskSizeInMB value. + */ + public Float diskSizeInMB() { + return this.diskSizeInMB; + } + + /** + * Set the diskSizeInMB property: Gets the disk size in mb. + * + * @param diskSizeInMB the diskSizeInMB value to set. + * @return the AssessedSqlInstanceStorageDetails object itself. + */ + public AssessedSqlInstanceStorageDetails withDiskSizeInMB(Float diskSizeInMB) { + this.diskSizeInMB = diskSizeInMB; + return this; + } + + /** + * Get the megabytesPerSecondOfRead property: Gets the megabytes per second of read. + * + * @return the megabytesPerSecondOfRead value. + */ + public Float megabytesPerSecondOfRead() { + return this.megabytesPerSecondOfRead; + } + + /** + * Set the megabytesPerSecondOfRead property: Gets the megabytes per second of read. + * + * @param megabytesPerSecondOfRead the megabytesPerSecondOfRead value to set. + * @return the AssessedSqlInstanceStorageDetails object itself. + */ + public AssessedSqlInstanceStorageDetails withMegabytesPerSecondOfRead(Float megabytesPerSecondOfRead) { + this.megabytesPerSecondOfRead = megabytesPerSecondOfRead; + return this; + } + + /** + * Get the megabytesPerSecondOfWrite property: Gets the megabytes per second of read. + * + * @return the megabytesPerSecondOfWrite value. + */ + public Float megabytesPerSecondOfWrite() { + return this.megabytesPerSecondOfWrite; + } + + /** + * Set the megabytesPerSecondOfWrite property: Gets the megabytes per second of read. + * + * @param megabytesPerSecondOfWrite the megabytesPerSecondOfWrite value to set. + * @return the AssessedSqlInstanceStorageDetails object itself. + */ + public AssessedSqlInstanceStorageDetails withMegabytesPerSecondOfWrite(Float megabytesPerSecondOfWrite) { + this.megabytesPerSecondOfWrite = megabytesPerSecondOfWrite; + return this; + } + + /** + * Get the numberOfReadOperationsPerSecond property: Gets the number of read operations per second. + * + * @return the numberOfReadOperationsPerSecond value. + */ + public Float numberOfReadOperationsPerSecond() { + return this.numberOfReadOperationsPerSecond; + } + + /** + * Set the numberOfReadOperationsPerSecond property: Gets the number of read operations per second. + * + * @param numberOfReadOperationsPerSecond the numberOfReadOperationsPerSecond value to set. + * @return the AssessedSqlInstanceStorageDetails object itself. + */ + public AssessedSqlInstanceStorageDetails + withNumberOfReadOperationsPerSecond(Float numberOfReadOperationsPerSecond) { + this.numberOfReadOperationsPerSecond = numberOfReadOperationsPerSecond; + return this; + } + + /** + * Get the numberOfWriteOperationsPerSecond property: Gets the number of write operations per second. + * + * @return the numberOfWriteOperationsPerSecond value. + */ + public Float numberOfWriteOperationsPerSecond() { + return this.numberOfWriteOperationsPerSecond; + } + + /** + * Set the numberOfWriteOperationsPerSecond property: Gets the number of write operations per second. + * + * @param numberOfWriteOperationsPerSecond the numberOfWriteOperationsPerSecond value to set. + * @return the AssessedSqlInstanceStorageDetails object itself. + */ + public AssessedSqlInstanceStorageDetails + withNumberOfWriteOperationsPerSecond(Float numberOfWriteOperationsPerSecond) { + this.numberOfWriteOperationsPerSecond = numberOfWriteOperationsPerSecond; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("storageType", this.storageType); + jsonWriter.writeNumberField("diskSizeInMB", this.diskSizeInMB); + jsonWriter.writeNumberField("megabytesPerSecondOfRead", this.megabytesPerSecondOfRead); + jsonWriter.writeNumberField("megabytesPerSecondOfWrite", this.megabytesPerSecondOfWrite); + jsonWriter.writeNumberField("numberOfReadOperationsPerSecond", this.numberOfReadOperationsPerSecond); + jsonWriter.writeNumberField("numberOfWriteOperationsPerSecond", this.numberOfWriteOperationsPerSecond); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessedSqlInstanceStorageDetails from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessedSqlInstanceStorageDetails 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 AssessedSqlInstanceStorageDetails. + */ + public static AssessedSqlInstanceStorageDetails fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessedSqlInstanceStorageDetails deserializedAssessedSqlInstanceStorageDetails + = new AssessedSqlInstanceStorageDetails(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("storageType".equals(fieldName)) { + deserializedAssessedSqlInstanceStorageDetails.storageType = reader.getString(); + } else if ("diskSizeInMB".equals(fieldName)) { + deserializedAssessedSqlInstanceStorageDetails.diskSizeInMB + = reader.getNullable(JsonReader::getFloat); + } else if ("megabytesPerSecondOfRead".equals(fieldName)) { + deserializedAssessedSqlInstanceStorageDetails.megabytesPerSecondOfRead + = reader.getNullable(JsonReader::getFloat); + } else if ("megabytesPerSecondOfWrite".equals(fieldName)) { + deserializedAssessedSqlInstanceStorageDetails.megabytesPerSecondOfWrite + = reader.getNullable(JsonReader::getFloat); + } else if ("numberOfReadOperationsPerSecond".equals(fieldName)) { + deserializedAssessedSqlInstanceStorageDetails.numberOfReadOperationsPerSecond + = reader.getNullable(JsonReader::getFloat); + } else if ("numberOfWriteOperationsPerSecond".equals(fieldName)) { + deserializedAssessedSqlInstanceStorageDetails.numberOfWriteOperationsPerSecond + = reader.getNullable(JsonReader::getFloat); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessedSqlInstanceStorageDetails; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlInstanceSummary.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlInstanceSummary.java new file mode 100644 index 000000000000..a636bfd526c9 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlInstanceSummary.java @@ -0,0 +1,318 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * Assessed Sql Instance Summary. + */ +@Fluent +public final class AssessedSqlInstanceSummary implements JsonSerializable { + /* + * Gets the instance id. + */ + private String instanceId; + + /* + * Gets the instance name. + */ + private String instanceName; + + /* + * Gets the instance arm id. + */ + private String sqlInstanceSdsArmId; + + /* + * Gets the instance entity id. + */ + private String sqlInstanceEntityId; + + /* + * Gets the Sql edition. + */ + private String sqlEdition; + + /* + * Gets the Sql version. + */ + private String sqlVersion; + + /* + * Gets whether Sql is clustered. + */ + private Boolean isClustered; + + /* + * Gets whether Sql is highly available. + */ + private Boolean isHighAvailabilityEnabled; + + /* + * Gets the Sql Fci state. + */ + private SqlFciState sqlFciState; + + /** + * Creates an instance of AssessedSqlInstanceSummary class. + */ + public AssessedSqlInstanceSummary() { + } + + /** + * Get the instanceId property: Gets the instance id. + * + * @return the instanceId value. + */ + public String instanceId() { + return this.instanceId; + } + + /** + * Set the instanceId property: Gets the instance id. + * + * @param instanceId the instanceId value to set. + * @return the AssessedSqlInstanceSummary object itself. + */ + public AssessedSqlInstanceSummary withInstanceId(String instanceId) { + this.instanceId = instanceId; + return this; + } + + /** + * Get the instanceName property: Gets the instance name. + * + * @return the instanceName value. + */ + public String instanceName() { + return this.instanceName; + } + + /** + * Set the instanceName property: Gets the instance name. + * + * @param instanceName the instanceName value to set. + * @return the AssessedSqlInstanceSummary object itself. + */ + public AssessedSqlInstanceSummary withInstanceName(String instanceName) { + this.instanceName = instanceName; + return this; + } + + /** + * Get the sqlInstanceSdsArmId property: Gets the instance arm id. + * + * @return the sqlInstanceSdsArmId value. + */ + public String sqlInstanceSdsArmId() { + return this.sqlInstanceSdsArmId; + } + + /** + * Set the sqlInstanceSdsArmId property: Gets the instance arm id. + * + * @param sqlInstanceSdsArmId the sqlInstanceSdsArmId value to set. + * @return the AssessedSqlInstanceSummary object itself. + */ + public AssessedSqlInstanceSummary withSqlInstanceSdsArmId(String sqlInstanceSdsArmId) { + this.sqlInstanceSdsArmId = sqlInstanceSdsArmId; + return this; + } + + /** + * Get the sqlInstanceEntityId property: Gets the instance entity id. + * + * @return the sqlInstanceEntityId value. + */ + public String sqlInstanceEntityId() { + return this.sqlInstanceEntityId; + } + + /** + * Set the sqlInstanceEntityId property: Gets the instance entity id. + * + * @param sqlInstanceEntityId the sqlInstanceEntityId value to set. + * @return the AssessedSqlInstanceSummary object itself. + */ + public AssessedSqlInstanceSummary withSqlInstanceEntityId(String sqlInstanceEntityId) { + this.sqlInstanceEntityId = sqlInstanceEntityId; + return this; + } + + /** + * Get the sqlEdition property: Gets the Sql edition. + * + * @return the sqlEdition value. + */ + public String sqlEdition() { + return this.sqlEdition; + } + + /** + * Set the sqlEdition property: Gets the Sql edition. + * + * @param sqlEdition the sqlEdition value to set. + * @return the AssessedSqlInstanceSummary object itself. + */ + public AssessedSqlInstanceSummary withSqlEdition(String sqlEdition) { + this.sqlEdition = sqlEdition; + return this; + } + + /** + * Get the sqlVersion property: Gets the Sql version. + * + * @return the sqlVersion value. + */ + public String sqlVersion() { + return this.sqlVersion; + } + + /** + * Set the sqlVersion property: Gets the Sql version. + * + * @param sqlVersion the sqlVersion value to set. + * @return the AssessedSqlInstanceSummary object itself. + */ + public AssessedSqlInstanceSummary withSqlVersion(String sqlVersion) { + this.sqlVersion = sqlVersion; + return this; + } + + /** + * Get the isClustered property: Gets whether Sql is clustered. + * + * @return the isClustered value. + */ + public Boolean isClustered() { + return this.isClustered; + } + + /** + * Set the isClustered property: Gets whether Sql is clustered. + * + * @param isClustered the isClustered value to set. + * @return the AssessedSqlInstanceSummary object itself. + */ + public AssessedSqlInstanceSummary withIsClustered(Boolean isClustered) { + this.isClustered = isClustered; + return this; + } + + /** + * Get the isHighAvailabilityEnabled property: Gets whether Sql is highly available. + * + * @return the isHighAvailabilityEnabled value. + */ + public Boolean isHighAvailabilityEnabled() { + return this.isHighAvailabilityEnabled; + } + + /** + * Set the isHighAvailabilityEnabled property: Gets whether Sql is highly available. + * + * @param isHighAvailabilityEnabled the isHighAvailabilityEnabled value to set. + * @return the AssessedSqlInstanceSummary object itself. + */ + public AssessedSqlInstanceSummary withIsHighAvailabilityEnabled(Boolean isHighAvailabilityEnabled) { + this.isHighAvailabilityEnabled = isHighAvailabilityEnabled; + return this; + } + + /** + * Get the sqlFciState property: Gets the Sql Fci state. + * + * @return the sqlFciState value. + */ + public SqlFciState sqlFciState() { + return this.sqlFciState; + } + + /** + * Set the sqlFciState property: Gets the Sql Fci state. + * + * @param sqlFciState the sqlFciState value to set. + * @return the AssessedSqlInstanceSummary object itself. + */ + public AssessedSqlInstanceSummary withSqlFciState(SqlFciState sqlFciState) { + this.sqlFciState = sqlFciState; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("instanceId", this.instanceId); + jsonWriter.writeStringField("instanceName", this.instanceName); + jsonWriter.writeStringField("sqlInstanceSdsArmId", this.sqlInstanceSdsArmId); + jsonWriter.writeStringField("sqlInstanceEntityId", this.sqlInstanceEntityId); + jsonWriter.writeStringField("sqlEdition", this.sqlEdition); + jsonWriter.writeStringField("sqlVersion", this.sqlVersion); + jsonWriter.writeBooleanField("isClustered", this.isClustered); + jsonWriter.writeBooleanField("isHighAvailabilityEnabled", this.isHighAvailabilityEnabled); + jsonWriter.writeStringField("sqlFciState", this.sqlFciState == null ? null : this.sqlFciState.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessedSqlInstanceSummary from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessedSqlInstanceSummary 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 AssessedSqlInstanceSummary. + */ + public static AssessedSqlInstanceSummary fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessedSqlInstanceSummary deserializedAssessedSqlInstanceSummary = new AssessedSqlInstanceSummary(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("instanceId".equals(fieldName)) { + deserializedAssessedSqlInstanceSummary.instanceId = reader.getString(); + } else if ("instanceName".equals(fieldName)) { + deserializedAssessedSqlInstanceSummary.instanceName = reader.getString(); + } else if ("sqlInstanceSdsArmId".equals(fieldName)) { + deserializedAssessedSqlInstanceSummary.sqlInstanceSdsArmId = reader.getString(); + } else if ("sqlInstanceEntityId".equals(fieldName)) { + deserializedAssessedSqlInstanceSummary.sqlInstanceEntityId = reader.getString(); + } else if ("sqlEdition".equals(fieldName)) { + deserializedAssessedSqlInstanceSummary.sqlEdition = reader.getString(); + } else if ("sqlVersion".equals(fieldName)) { + deserializedAssessedSqlInstanceSummary.sqlVersion = reader.getString(); + } else if ("isClustered".equals(fieldName)) { + deserializedAssessedSqlInstanceSummary.isClustered = reader.getNullable(JsonReader::getBoolean); + } else if ("isHighAvailabilityEnabled".equals(fieldName)) { + deserializedAssessedSqlInstanceSummary.isHighAvailabilityEnabled + = reader.getNullable(JsonReader::getBoolean); + } else if ("sqlFciState".equals(fieldName)) { + deserializedAssessedSqlInstanceSummary.sqlFciState = SqlFciState.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessedSqlInstanceSummary; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlInstanceV2.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlInstanceV2.java new file mode 100644 index 000000000000..68fea8ce41fa --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlInstanceV2.java @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlInstanceV2Inner; + +/** + * An immutable client-side representation of AssessedSqlInstanceV2. + */ +public interface AssessedSqlInstanceV2 { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + AssessedSqlInstanceV2Properties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlInstanceV2Inner object. + * + * @return the inner object. + */ + AssessedSqlInstanceV2Inner innerModel(); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlInstanceV2ListResult.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlInstanceV2ListResult.java new file mode 100644 index 000000000000..50e91ac9c776 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlInstanceV2ListResult.java @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlInstanceV2Inner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a AssessedSqlInstanceV2 list operation. + */ +@Fluent +public final class AssessedSqlInstanceV2ListResult implements JsonSerializable { + /* + * The AssessedSqlInstanceV2 items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of AssessedSqlInstanceV2ListResult class. + */ + public AssessedSqlInstanceV2ListResult() { + } + + /** + * Get the value property: The AssessedSqlInstanceV2 items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Set the value property: The AssessedSqlInstanceV2 items on this page. + * + * @param value the value value to set. + * @return the AssessedSqlInstanceV2ListResult object itself. + */ + public AssessedSqlInstanceV2ListResult withValue(List value) { + this.value = value; + return this; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The link to the next page of items. + * + * @param nextLink the nextLink value to set. + * @return the AssessedSqlInstanceV2ListResult object itself. + */ + public AssessedSqlInstanceV2ListResult withNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property value in model AssessedSqlInstanceV2ListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(AssessedSqlInstanceV2ListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessedSqlInstanceV2ListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessedSqlInstanceV2ListResult 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 AssessedSqlInstanceV2ListResult. + */ + public static AssessedSqlInstanceV2ListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessedSqlInstanceV2ListResult deserializedAssessedSqlInstanceV2ListResult + = new AssessedSqlInstanceV2ListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> AssessedSqlInstanceV2Inner.fromJson(reader1)); + deserializedAssessedSqlInstanceV2ListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedAssessedSqlInstanceV2ListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessedSqlInstanceV2ListResult; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlInstanceV2Operations.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlInstanceV2Operations.java new file mode 100644 index 000000000000..5709c7d05bc8 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlInstanceV2Operations.java @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of AssessedSqlInstanceV2Operations. + */ +public interface AssessedSqlInstanceV2Operations { + /** + * List AssessedSqlInstanceV2 resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlInstanceV2 list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName); + + /** + * List AssessedSqlInstanceV2 resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlInstanceV2 list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName, String filter, Integer pageSize, String continuationToken, + Integer totalRecordCount, Context context); + + /** + * Get a AssessedSqlInstanceV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param assessedSqlInstanceName Sql assessment Assessed Instance ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlInstanceV2 along with {@link Response}. + */ + Response getWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, String assessedSqlInstanceName, Context context); + + /** + * Get a AssessedSqlInstanceV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param assessedSqlInstanceName Sql assessment Assessed Instance ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlInstanceV2. + */ + AssessedSqlInstanceV2 get(String resourceGroupName, String projectName, String groupName, String assessmentName, + String assessedSqlInstanceName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlInstanceV2Properties.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlInstanceV2Properties.java new file mode 100644 index 000000000000..f9c08c111c2a --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlInstanceV2Properties.java @@ -0,0 +1,577 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.util.List; + +/** + * Assessed SQL instance properties web model. + */ +@Immutable +public final class AssessedSqlInstanceV2Properties implements JsonSerializable { + /* + * Gets or sets the memory used by SQL instance in megabytes. + */ + private Float memoryInUseInMB; + + /* + * Gets or sets a value indicating whether SQL instance has been deep discovered. + */ + private Boolean hasScanOccurred; + + /* + * Gets or sets the recommended azure SQL target type. + */ + private TargetType recommendedAzureSqlTargetType; + + /* + * Gets or sets the recommended azure SQL suitability. + */ + private RecommendedSuitability recommendedSuitability; + + /* + * SQL instance azure SQL MI suitability details. + */ + private SqlAssessmentV2PaasSuitabilityData azureSqlMISuitabilityDetails; + + /* + * SQL instance azure SQL DB suitability details. + */ + private SqlAssessmentV2PaasSuitabilityData azureSqlDBSuitabilityDetails; + + /* + * SQL instance azure SQL VM suitability details. + */ + private SqlAssessmentV2IaasSuitabilityData azureSqlVMSuitabilityDetails; + + /* + * Gets the storage details. + */ + private List storageTypeBasedDetails; + + /* + * Gets the product support status related details. + */ + private ProductSupportStatus productSupportStatus; + + /* + * Gets the FCI metadata if this instance represents an FCI instance. + */ + private SqlFciMetadata fciMetadata; + + /* + * Gets the overview counts of availability replicas in the assessed instance, by + * commit mode and read type. + */ + private SqlAvailabilityReplicaSummary availabilityReplicaSummary; + + /* + * Gets a value indicating whether the SQL instance is clustered or not. + */ + private Boolean isClustered; + + /* + * Gets a value indicating whether the high availability is enabled or not. + */ + private Boolean isHighAvailabilityEnabled; + + /* + * Gets the list of recommended target reasoning. + */ + private List recommendedTargetReasonings; + + /* + * Machine arm id. + */ + private String machineArmId; + + /* + * Machine display name. + */ + private String machineName; + + /* + * SQL instance name. + */ + private String instanceName; + + /* + * SQL instance SDS arm id. + */ + private String sqlInstanceSdsArmId; + + /* + * SQL instance edition. + */ + private String sqlEdition; + + /* + * SQL instance version. + */ + private String sqlVersion; + + /* + * Number of CPU cores assigned to the SQL instance. + */ + private Integer numberOfCoresAllocated; + + /* + * The percentage of the total number of cores being utilized by the SQL instance. + */ + private Float percentageCoresUtilization; + + /* + * The logical disk details. + */ + private List logicalDisks; + + /* + * The databases summary. + */ + private AssessedSqlInstanceDatabaseSummary databaseSummary; + + /* + * Confidence Rating in Percentage. + */ + private Float confidenceRatingInPercentage; + + /* + * Assessment sizing criterion. + */ + private AssessmentSizingCriterion sizingCriterion; + + /* + * When was assessed SQL instance first created. + */ + private OffsetDateTime createdTimestamp; + + /* + * When was assessed SQL instance last updated. + */ + private OffsetDateTime updatedTimestamp; + + /** + * Creates an instance of AssessedSqlInstanceV2Properties class. + */ + public AssessedSqlInstanceV2Properties() { + } + + /** + * Get the memoryInUseInMB property: Gets or sets the memory used by SQL instance in megabytes. + * + * @return the memoryInUseInMB value. + */ + public Float memoryInUseInMB() { + return this.memoryInUseInMB; + } + + /** + * Get the hasScanOccurred property: Gets or sets a value indicating whether SQL instance has been deep discovered. + * + * @return the hasScanOccurred value. + */ + public Boolean hasScanOccurred() { + return this.hasScanOccurred; + } + + /** + * Get the recommendedAzureSqlTargetType property: Gets or sets the recommended azure SQL target type. + * + * @return the recommendedAzureSqlTargetType value. + */ + public TargetType recommendedAzureSqlTargetType() { + return this.recommendedAzureSqlTargetType; + } + + /** + * Get the recommendedSuitability property: Gets or sets the recommended azure SQL suitability. + * + * @return the recommendedSuitability value. + */ + public RecommendedSuitability recommendedSuitability() { + return this.recommendedSuitability; + } + + /** + * Get the azureSqlMISuitabilityDetails property: SQL instance azure SQL MI suitability details. + * + * @return the azureSqlMISuitabilityDetails value. + */ + public SqlAssessmentV2PaasSuitabilityData azureSqlMISuitabilityDetails() { + return this.azureSqlMISuitabilityDetails; + } + + /** + * Get the azureSqlDBSuitabilityDetails property: SQL instance azure SQL DB suitability details. + * + * @return the azureSqlDBSuitabilityDetails value. + */ + public SqlAssessmentV2PaasSuitabilityData azureSqlDBSuitabilityDetails() { + return this.azureSqlDBSuitabilityDetails; + } + + /** + * Get the azureSqlVMSuitabilityDetails property: SQL instance azure SQL VM suitability details. + * + * @return the azureSqlVMSuitabilityDetails value. + */ + public SqlAssessmentV2IaasSuitabilityData azureSqlVMSuitabilityDetails() { + return this.azureSqlVMSuitabilityDetails; + } + + /** + * Get the storageTypeBasedDetails property: Gets the storage details. + * + * @return the storageTypeBasedDetails value. + */ + public List storageTypeBasedDetails() { + return this.storageTypeBasedDetails; + } + + /** + * Get the productSupportStatus property: Gets the product support status related details. + * + * @return the productSupportStatus value. + */ + public ProductSupportStatus productSupportStatus() { + return this.productSupportStatus; + } + + /** + * Get the fciMetadata property: Gets the FCI metadata if this instance represents an FCI instance. + * + * @return the fciMetadata value. + */ + public SqlFciMetadata fciMetadata() { + return this.fciMetadata; + } + + /** + * Get the availabilityReplicaSummary property: Gets the overview counts of availability replicas in the assessed + * instance, by + * commit mode and read type. + * + * @return the availabilityReplicaSummary value. + */ + public SqlAvailabilityReplicaSummary availabilityReplicaSummary() { + return this.availabilityReplicaSummary; + } + + /** + * Get the isClustered property: Gets a value indicating whether the SQL instance is clustered or not. + * + * @return the isClustered value. + */ + public Boolean isClustered() { + return this.isClustered; + } + + /** + * Get the isHighAvailabilityEnabled property: Gets a value indicating whether the high availability is enabled or + * not. + * + * @return the isHighAvailabilityEnabled value. + */ + public Boolean isHighAvailabilityEnabled() { + return this.isHighAvailabilityEnabled; + } + + /** + * Get the recommendedTargetReasonings property: Gets the list of recommended target reasoning. + * + * @return the recommendedTargetReasonings value. + */ + public List recommendedTargetReasonings() { + return this.recommendedTargetReasonings; + } + + /** + * Get the machineArmId property: Machine arm id. + * + * @return the machineArmId value. + */ + public String machineArmId() { + return this.machineArmId; + } + + /** + * Get the machineName property: Machine display name. + * + * @return the machineName value. + */ + public String machineName() { + return this.machineName; + } + + /** + * Get the instanceName property: SQL instance name. + * + * @return the instanceName value. + */ + public String instanceName() { + return this.instanceName; + } + + /** + * Get the sqlInstanceSdsArmId property: SQL instance SDS arm id. + * + * @return the sqlInstanceSdsArmId value. + */ + public String sqlInstanceSdsArmId() { + return this.sqlInstanceSdsArmId; + } + + /** + * Get the sqlEdition property: SQL instance edition. + * + * @return the sqlEdition value. + */ + public String sqlEdition() { + return this.sqlEdition; + } + + /** + * Get the sqlVersion property: SQL instance version. + * + * @return the sqlVersion value. + */ + public String sqlVersion() { + return this.sqlVersion; + } + + /** + * Get the numberOfCoresAllocated property: Number of CPU cores assigned to the SQL instance. + * + * @return the numberOfCoresAllocated value. + */ + public Integer numberOfCoresAllocated() { + return this.numberOfCoresAllocated; + } + + /** + * Get the percentageCoresUtilization property: The percentage of the total number of cores being utilized by the + * SQL instance. + * + * @return the percentageCoresUtilization value. + */ + public Float percentageCoresUtilization() { + return this.percentageCoresUtilization; + } + + /** + * Get the logicalDisks property: The logical disk details. + * + * @return the logicalDisks value. + */ + public List logicalDisks() { + return this.logicalDisks; + } + + /** + * Get the databaseSummary property: The databases summary. + * + * @return the databaseSummary value. + */ + public AssessedSqlInstanceDatabaseSummary databaseSummary() { + return this.databaseSummary; + } + + /** + * Get the confidenceRatingInPercentage property: Confidence Rating in Percentage. + * + * @return the confidenceRatingInPercentage value. + */ + public Float confidenceRatingInPercentage() { + return this.confidenceRatingInPercentage; + } + + /** + * Get the sizingCriterion property: Assessment sizing criterion. + * + * @return the sizingCriterion value. + */ + public AssessmentSizingCriterion sizingCriterion() { + return this.sizingCriterion; + } + + /** + * Get the createdTimestamp property: When was assessed SQL instance first created. + * + * @return the createdTimestamp value. + */ + public OffsetDateTime createdTimestamp() { + return this.createdTimestamp; + } + + /** + * Get the updatedTimestamp property: When was assessed SQL instance last updated. + * + * @return the updatedTimestamp value. + */ + public OffsetDateTime updatedTimestamp() { + return this.updatedTimestamp; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (azureSqlMISuitabilityDetails() != null) { + azureSqlMISuitabilityDetails().validate(); + } + if (azureSqlDBSuitabilityDetails() != null) { + azureSqlDBSuitabilityDetails().validate(); + } + if (azureSqlVMSuitabilityDetails() != null) { + azureSqlVMSuitabilityDetails().validate(); + } + if (storageTypeBasedDetails() != null) { + storageTypeBasedDetails().forEach(e -> e.validate()); + } + if (productSupportStatus() != null) { + productSupportStatus().validate(); + } + if (fciMetadata() != null) { + fciMetadata().validate(); + } + if (availabilityReplicaSummary() != null) { + availabilityReplicaSummary().validate(); + } + if (recommendedTargetReasonings() != null) { + recommendedTargetReasonings().forEach(e -> e.validate()); + } + if (logicalDisks() != null) { + logicalDisks().forEach(e -> e.validate()); + } + if (databaseSummary() != null) { + databaseSummary().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessedSqlInstanceV2Properties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessedSqlInstanceV2Properties 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 AssessedSqlInstanceV2Properties. + */ + public static AssessedSqlInstanceV2Properties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessedSqlInstanceV2Properties deserializedAssessedSqlInstanceV2Properties + = new AssessedSqlInstanceV2Properties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("memoryInUseInMB".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Properties.memoryInUseInMB + = reader.getNullable(JsonReader::getFloat); + } else if ("hasScanOccurred".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Properties.hasScanOccurred + = reader.getNullable(JsonReader::getBoolean); + } else if ("recommendedAzureSqlTargetType".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Properties.recommendedAzureSqlTargetType + = TargetType.fromString(reader.getString()); + } else if ("recommendedSuitability".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Properties.recommendedSuitability + = RecommendedSuitability.fromString(reader.getString()); + } else if ("azureSqlMISuitabilityDetails".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Properties.azureSqlMISuitabilityDetails + = SqlAssessmentV2PaasSuitabilityData.fromJson(reader); + } else if ("azureSqlDBSuitabilityDetails".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Properties.azureSqlDBSuitabilityDetails + = SqlAssessmentV2PaasSuitabilityData.fromJson(reader); + } else if ("azureSqlVMSuitabilityDetails".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Properties.azureSqlVMSuitabilityDetails + = SqlAssessmentV2IaasSuitabilityData.fromJson(reader); + } else if ("storageTypeBasedDetails".equals(fieldName)) { + List storageTypeBasedDetails + = reader.readArray(reader1 -> AssessedSqlInstanceStorageDetails.fromJson(reader1)); + deserializedAssessedSqlInstanceV2Properties.storageTypeBasedDetails = storageTypeBasedDetails; + } else if ("productSupportStatus".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Properties.productSupportStatus + = ProductSupportStatus.fromJson(reader); + } else if ("fciMetadata".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Properties.fciMetadata = SqlFciMetadata.fromJson(reader); + } else if ("availabilityReplicaSummary".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Properties.availabilityReplicaSummary + = SqlAvailabilityReplicaSummary.fromJson(reader); + } else if ("isClustered".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Properties.isClustered + = reader.getNullable(JsonReader::getBoolean); + } else if ("isHighAvailabilityEnabled".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Properties.isHighAvailabilityEnabled + = reader.getNullable(JsonReader::getBoolean); + } else if ("recommendedTargetReasonings".equals(fieldName)) { + List recommendedTargetReasonings + = reader.readArray(reader1 -> SqlRecommendationReasoning.fromJson(reader1)); + deserializedAssessedSqlInstanceV2Properties.recommendedTargetReasonings + = recommendedTargetReasonings; + } else if ("machineArmId".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Properties.machineArmId = reader.getString(); + } else if ("machineName".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Properties.machineName = reader.getString(); + } else if ("instanceName".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Properties.instanceName = reader.getString(); + } else if ("sqlInstanceSdsArmId".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Properties.sqlInstanceSdsArmId = reader.getString(); + } else if ("sqlEdition".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Properties.sqlEdition = reader.getString(); + } else if ("sqlVersion".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Properties.sqlVersion = reader.getString(); + } else if ("numberOfCoresAllocated".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Properties.numberOfCoresAllocated + = reader.getNullable(JsonReader::getInt); + } else if ("percentageCoresUtilization".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Properties.percentageCoresUtilization + = reader.getNullable(JsonReader::getFloat); + } else if ("logicalDisks".equals(fieldName)) { + List logicalDisks + = reader.readArray(reader1 -> AssessedSqlInstanceDiskDetails.fromJson(reader1)); + deserializedAssessedSqlInstanceV2Properties.logicalDisks = logicalDisks; + } else if ("databaseSummary".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Properties.databaseSummary + = AssessedSqlInstanceDatabaseSummary.fromJson(reader); + } else if ("confidenceRatingInPercentage".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Properties.confidenceRatingInPercentage + = reader.getNullable(JsonReader::getFloat); + } else if ("sizingCriterion".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Properties.sizingCriterion + = AssessmentSizingCriterion.fromString(reader.getString()); + } else if ("createdTimestamp".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Properties.createdTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("updatedTimestamp".equals(fieldName)) { + deserializedAssessedSqlInstanceV2Properties.updatedTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessedSqlInstanceV2Properties; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlMachine.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlMachine.java new file mode 100644 index 000000000000..d51e0cced912 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlMachine.java @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlMachineInner; + +/** + * An immutable client-side representation of AssessedSqlMachine. + */ +public interface AssessedSqlMachine { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + AssessedSqlMachineProperties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlMachineInner object. + * + * @return the inner object. + */ + AssessedSqlMachineInner innerModel(); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlMachineListResult.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlMachineListResult.java new file mode 100644 index 000000000000..fa6d5734dbf6 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlMachineListResult.java @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlMachineInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a AssessedSqlMachine list operation. + */ +@Fluent +public final class AssessedSqlMachineListResult implements JsonSerializable { + /* + * The AssessedSqlMachine items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of AssessedSqlMachineListResult class. + */ + public AssessedSqlMachineListResult() { + } + + /** + * Get the value property: The AssessedSqlMachine items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Set the value property: The AssessedSqlMachine items on this page. + * + * @param value the value value to set. + * @return the AssessedSqlMachineListResult object itself. + */ + public AssessedSqlMachineListResult withValue(List value) { + this.value = value; + return this; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The link to the next page of items. + * + * @param nextLink the nextLink value to set. + * @return the AssessedSqlMachineListResult object itself. + */ + public AssessedSqlMachineListResult withNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property value in model AssessedSqlMachineListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(AssessedSqlMachineListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessedSqlMachineListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessedSqlMachineListResult 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 AssessedSqlMachineListResult. + */ + public static AssessedSqlMachineListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessedSqlMachineListResult deserializedAssessedSqlMachineListResult = new AssessedSqlMachineListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> AssessedSqlMachineInner.fromJson(reader1)); + deserializedAssessedSqlMachineListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedAssessedSqlMachineListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessedSqlMachineListResult; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlMachineProperties.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlMachineProperties.java new file mode 100644 index 000000000000..2861eb6fb9d0 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlMachineProperties.java @@ -0,0 +1,760 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.util.List; +import java.util.Map; + +/** + * Assessed SQL machine properties. + */ +@Fluent +public final class AssessedSqlMachineProperties implements JsonSerializable { + /* + * Gets or sets the BIOS GUID for the machine. + */ + private String biosGuid; + + /* + * Gets or sets the FQDN for the machine. + */ + private String fqdn; + + /* + * Gets the list of SQL instances discovered on the machine. + */ + private List sqlInstances; + + /* + * Gets or sets the detailed messages that were set on the machine during + * evaluation. + */ + private AzureVmSuitabilityDetail suitabilityDetail; + + /* + * Gets or sets the explanation if machine is not suitable for cloud. + */ + private AzureVmSuitabilityExplanation suitabilityExplanation; + + /* + * Gets or sets the Recommended Azure Size for the machine. + */ + private AzureVmSize recommendedVmSize; + + /* + * Gets or sets the Recommended Azure VM Family for the machine. + */ + private AzureVmFamily recommendedVmFamily; + + /* + * Gets the product support status related details. + */ + private ProductSupportStatus productSupportStatus; + + /* + * Gets or sets the Number of cores for recommended size. + */ + private Integer recommendedVmSizeNumberOfCores; + + /* + * Gets or sets the Megabytes of memory for recommended size. + */ + private Float recommendedVmSizeMegabytesOfMemory; + + /* + * Gets or sets the monthly compute cost calculated for recommended size. + */ + private Float monthlyComputeCost; + + /* + * Gets the list of data disks that were assessed as part of this assessment. + */ + private Map disks; + + /* + * Gets the list of network adapters that were assessed as part of this assessment. + */ + private Map networkAdapters; + + /* + * Gets or sets the monthly networking cost. + */ + private Float monthlyBandwidthCost; + + /* + * Gets or sets the monthly total storage cost. + */ + private Float monthlyStorageCost; + + /* + * Gets the collection of cost components. + */ + private List costComponents; + + /* + * Gets the suitability for Microsoft cloud defender. + */ + private CloudSuitability securitySuitability; + + /* + * Gets the list of migration guidelines applicable. + */ + private List migrationGuidelines; + + /* + * Boot type of machine discovered in private data center. + */ + private MachineBootType bootType; + + /* + * Operating system as reported by datacenter management solution. + */ + private String operatingSystemType; + + /* + * Operating system as reported by datacenter management solution. + */ + private String operatingSystemName; + + /* + * Operating system version as reported by datacenter management solution. + */ + private String operatingSystemVersion; + + /* + * Operating system architecture as reported by datacenter management solution. + */ + private GuestOperatingSystemArchitecture operatingSystemArchitecture; + + /* + * When was machine first created. + */ + private OffsetDateTime createdTimestamp; + + /* + * When was machine last updated. + */ + private OffsetDateTime updatedTimestamp; + + /* + * Display Name of the Machine. + */ + private String displayName; + + /* + * Assessed machine type. + */ + private AssessedMachineType type; + + /* + * Description for the machine. + */ + private String description; + + /* + * Data center machine ARM id. + */ + private String datacenterMachineArmId; + + /* + * Data center management server ARM id. + */ + private String datacenterManagementServerArmId; + + /* + * Data center management server name. + */ + private String datacenterManagementServerName; + + /* + * Megabytes of memory found allocated for the machine in private data center. + */ + private Float megabytesOfMemory; + + /* + * Number of CPU cores found on the machine. + */ + private Integer numberOfCores; + + /* + * Confidence Rating in Percentage. + */ + private Float confidenceRatingInPercentage; + + /* + * Percentile of Percentage of Cores Utilized noted during time period T. + * + * Here N and T are settings on Assessment. + */ + private Float percentageCoresUtilization; + + /* + * Percentile of Percentage of Memory Utilized noted during time period T. + * + * Here N and T are settings on Assessment. + */ + private Float percentageMemoryUtilization; + + /* + * Gets a value indicating whether machine is suitable for the cloud platform + * selected. + */ + private CloudSuitability suitability; + + /* + * Assessment sizing criterion. + */ + private AssessmentSizingCriterion sizingCriterion; + + /** + * Creates an instance of AssessedSqlMachineProperties class. + */ + public AssessedSqlMachineProperties() { + } + + /** + * Get the biosGuid property: Gets or sets the BIOS GUID for the machine. + * + * @return the biosGuid value. + */ + public String biosGuid() { + return this.biosGuid; + } + + /** + * Get the fqdn property: Gets or sets the FQDN for the machine. + * + * @return the fqdn value. + */ + public String fqdn() { + return this.fqdn; + } + + /** + * Get the sqlInstances property: Gets the list of SQL instances discovered on the machine. + * + * @return the sqlInstances value. + */ + public List sqlInstances() { + return this.sqlInstances; + } + + /** + * Get the suitabilityDetail property: Gets or sets the detailed messages that were set on the machine during + * evaluation. + * + * @return the suitabilityDetail value. + */ + public AzureVmSuitabilityDetail suitabilityDetail() { + return this.suitabilityDetail; + } + + /** + * Get the suitabilityExplanation property: Gets or sets the explanation if machine is not suitable for cloud. + * + * @return the suitabilityExplanation value. + */ + public AzureVmSuitabilityExplanation suitabilityExplanation() { + return this.suitabilityExplanation; + } + + /** + * Get the recommendedVmSize property: Gets or sets the Recommended Azure Size for the machine. + * + * @return the recommendedVmSize value. + */ + public AzureVmSize recommendedVmSize() { + return this.recommendedVmSize; + } + + /** + * Get the recommendedVmFamily property: Gets or sets the Recommended Azure VM Family for the machine. + * + * @return the recommendedVmFamily value. + */ + public AzureVmFamily recommendedVmFamily() { + return this.recommendedVmFamily; + } + + /** + * Get the productSupportStatus property: Gets the product support status related details. + * + * @return the productSupportStatus value. + */ + public ProductSupportStatus productSupportStatus() { + return this.productSupportStatus; + } + + /** + * Get the recommendedVmSizeNumberOfCores property: Gets or sets the Number of cores for recommended size. + * + * @return the recommendedVmSizeNumberOfCores value. + */ + public Integer recommendedVmSizeNumberOfCores() { + return this.recommendedVmSizeNumberOfCores; + } + + /** + * Get the recommendedVmSizeMegabytesOfMemory property: Gets or sets the Megabytes of memory for recommended size. + * + * @return the recommendedVmSizeMegabytesOfMemory value. + */ + public Float recommendedVmSizeMegabytesOfMemory() { + return this.recommendedVmSizeMegabytesOfMemory; + } + + /** + * Get the monthlyComputeCost property: Gets or sets the monthly compute cost calculated for recommended size. + * + * @return the monthlyComputeCost value. + */ + public Float monthlyComputeCost() { + return this.monthlyComputeCost; + } + + /** + * Get the disks property: Gets the list of data disks that were assessed as part of this assessment. + * + * @return the disks value. + */ + public Map disks() { + return this.disks; + } + + /** + * Get the networkAdapters property: Gets the list of network adapters that were assessed as part of this + * assessment. + * + * @return the networkAdapters value. + */ + public Map networkAdapters() { + return this.networkAdapters; + } + + /** + * Get the monthlyBandwidthCost property: Gets or sets the monthly networking cost. + * + * @return the monthlyBandwidthCost value. + */ + public Float monthlyBandwidthCost() { + return this.monthlyBandwidthCost; + } + + /** + * Get the monthlyStorageCost property: Gets or sets the monthly total storage cost. + * + * @return the monthlyStorageCost value. + */ + public Float monthlyStorageCost() { + return this.monthlyStorageCost; + } + + /** + * Get the costComponents property: Gets the collection of cost components. + * + * @return the costComponents value. + */ + public List costComponents() { + return this.costComponents; + } + + /** + * Set the costComponents property: Gets the collection of cost components. + * + * @param costComponents the costComponents value to set. + * @return the AssessedSqlMachineProperties object itself. + */ + public AssessedSqlMachineProperties withCostComponents(List costComponents) { + this.costComponents = costComponents; + return this; + } + + /** + * Get the securitySuitability property: Gets the suitability for Microsoft cloud defender. + * + * @return the securitySuitability value. + */ + public CloudSuitability securitySuitability() { + return this.securitySuitability; + } + + /** + * Get the migrationGuidelines property: Gets the list of migration guidelines applicable. + * + * @return the migrationGuidelines value. + */ + public List migrationGuidelines() { + return this.migrationGuidelines; + } + + /** + * Get the bootType property: Boot type of machine discovered in private data center. + * + * @return the bootType value. + */ + public MachineBootType bootType() { + return this.bootType; + } + + /** + * Get the operatingSystemType property: Operating system as reported by datacenter management solution. + * + * @return the operatingSystemType value. + */ + public String operatingSystemType() { + return this.operatingSystemType; + } + + /** + * Get the operatingSystemName property: Operating system as reported by datacenter management solution. + * + * @return the operatingSystemName value. + */ + public String operatingSystemName() { + return this.operatingSystemName; + } + + /** + * Get the operatingSystemVersion property: Operating system version as reported by datacenter management solution. + * + * @return the operatingSystemVersion value. + */ + public String operatingSystemVersion() { + return this.operatingSystemVersion; + } + + /** + * Get the operatingSystemArchitecture property: Operating system architecture as reported by datacenter management + * solution. + * + * @return the operatingSystemArchitecture value. + */ + public GuestOperatingSystemArchitecture operatingSystemArchitecture() { + return this.operatingSystemArchitecture; + } + + /** + * Get the createdTimestamp property: When was machine first created. + * + * @return the createdTimestamp value. + */ + public OffsetDateTime createdTimestamp() { + return this.createdTimestamp; + } + + /** + * Get the updatedTimestamp property: When was machine last updated. + * + * @return the updatedTimestamp value. + */ + public OffsetDateTime updatedTimestamp() { + return this.updatedTimestamp; + } + + /** + * Get the displayName property: Display Name of the Machine. + * + * @return the displayName value. + */ + public String displayName() { + return this.displayName; + } + + /** + * Get the type property: Assessed machine type. + * + * @return the type value. + */ + public AssessedMachineType type() { + return this.type; + } + + /** + * Get the description property: Description for the machine. + * + * @return the description value. + */ + public String description() { + return this.description; + } + + /** + * Get the datacenterMachineArmId property: Data center machine ARM id. + * + * @return the datacenterMachineArmId value. + */ + public String datacenterMachineArmId() { + return this.datacenterMachineArmId; + } + + /** + * Get the datacenterManagementServerArmId property: Data center management server ARM id. + * + * @return the datacenterManagementServerArmId value. + */ + public String datacenterManagementServerArmId() { + return this.datacenterManagementServerArmId; + } + + /** + * Get the datacenterManagementServerName property: Data center management server name. + * + * @return the datacenterManagementServerName value. + */ + public String datacenterManagementServerName() { + return this.datacenterManagementServerName; + } + + /** + * Get the megabytesOfMemory property: Megabytes of memory found allocated for the machine in private data center. + * + * @return the megabytesOfMemory value. + */ + public Float megabytesOfMemory() { + return this.megabytesOfMemory; + } + + /** + * Get the numberOfCores property: Number of CPU cores found on the machine. + * + * @return the numberOfCores value. + */ + public Integer numberOfCores() { + return this.numberOfCores; + } + + /** + * Get the confidenceRatingInPercentage property: Confidence Rating in Percentage. + * + * @return the confidenceRatingInPercentage value. + */ + public Float confidenceRatingInPercentage() { + return this.confidenceRatingInPercentage; + } + + /** + * Get the percentageCoresUtilization property: Percentile of Percentage of Cores Utilized noted during time period + * T. + * + * Here N and T are settings on Assessment. + * + * @return the percentageCoresUtilization value. + */ + public Float percentageCoresUtilization() { + return this.percentageCoresUtilization; + } + + /** + * Get the percentageMemoryUtilization property: Percentile of Percentage of Memory Utilized noted during time + * period T. + * + * Here N and T are settings on Assessment. + * + * @return the percentageMemoryUtilization value. + */ + public Float percentageMemoryUtilization() { + return this.percentageMemoryUtilization; + } + + /** + * Get the suitability property: Gets a value indicating whether machine is suitable for the cloud platform + * selected. + * + * @return the suitability value. + */ + public CloudSuitability suitability() { + return this.suitability; + } + + /** + * Get the sizingCriterion property: Assessment sizing criterion. + * + * @return the sizingCriterion value. + */ + public AssessmentSizingCriterion sizingCriterion() { + return this.sizingCriterion; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (sqlInstances() != null) { + sqlInstances().forEach(e -> e.validate()); + } + if (productSupportStatus() != null) { + productSupportStatus().validate(); + } + if (disks() != null) { + disks().values().forEach(e -> { + if (e != null) { + e.validate(); + } + }); + } + if (networkAdapters() != null) { + networkAdapters().values().forEach(e -> { + if (e != null) { + e.validate(); + } + }); + } + if (costComponents() != null) { + costComponents().forEach(e -> e.validate()); + } + if (migrationGuidelines() != null) { + migrationGuidelines().forEach(e -> e.validate()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("costComponents", this.costComponents, + (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessedSqlMachineProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessedSqlMachineProperties 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 AssessedSqlMachineProperties. + */ + public static AssessedSqlMachineProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessedSqlMachineProperties deserializedAssessedSqlMachineProperties = new AssessedSqlMachineProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("biosGuid".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.biosGuid = reader.getString(); + } else if ("fqdn".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.fqdn = reader.getString(); + } else if ("sqlInstances".equals(fieldName)) { + List sqlInstances + = reader.readArray(reader1 -> AssessedSqlInstanceSummary.fromJson(reader1)); + deserializedAssessedSqlMachineProperties.sqlInstances = sqlInstances; + } else if ("suitabilityDetail".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.suitabilityDetail + = AzureVmSuitabilityDetail.fromString(reader.getString()); + } else if ("suitabilityExplanation".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.suitabilityExplanation + = AzureVmSuitabilityExplanation.fromString(reader.getString()); + } else if ("recommendedVmSize".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.recommendedVmSize + = AzureVmSize.fromString(reader.getString()); + } else if ("recommendedVmFamily".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.recommendedVmFamily + = AzureVmFamily.fromString(reader.getString()); + } else if ("productSupportStatus".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.productSupportStatus + = ProductSupportStatus.fromJson(reader); + } else if ("recommendedVmSizeNumberOfCores".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.recommendedVmSizeNumberOfCores + = reader.getNullable(JsonReader::getInt); + } else if ("recommendedVmSizeMegabytesOfMemory".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.recommendedVmSizeMegabytesOfMemory + = reader.getNullable(JsonReader::getFloat); + } else if ("monthlyComputeCost".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.monthlyComputeCost + = reader.getNullable(JsonReader::getFloat); + } else if ("disks".equals(fieldName)) { + Map disks = reader.readMap(reader1 -> AssessedDiskData.fromJson(reader1)); + deserializedAssessedSqlMachineProperties.disks = disks; + } else if ("networkAdapters".equals(fieldName)) { + Map networkAdapters + = reader.readMap(reader1 -> SqlAssessedNetworkAdapter.fromJson(reader1)); + deserializedAssessedSqlMachineProperties.networkAdapters = networkAdapters; + } else if ("monthlyBandwidthCost".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.monthlyBandwidthCost + = reader.getNullable(JsonReader::getFloat); + } else if ("monthlyStorageCost".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.monthlyStorageCost + = reader.getNullable(JsonReader::getFloat); + } else if ("costComponents".equals(fieldName)) { + List costComponents = reader.readArray(reader1 -> CostComponent.fromJson(reader1)); + deserializedAssessedSqlMachineProperties.costComponents = costComponents; + } else if ("securitySuitability".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.securitySuitability + = CloudSuitability.fromString(reader.getString()); + } else if ("migrationGuidelines".equals(fieldName)) { + List migrationGuidelines + = reader.readArray(reader1 -> SqlMigrationGuideline.fromJson(reader1)); + deserializedAssessedSqlMachineProperties.migrationGuidelines = migrationGuidelines; + } else if ("bootType".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.bootType = MachineBootType.fromString(reader.getString()); + } else if ("operatingSystemType".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.operatingSystemType = reader.getString(); + } else if ("operatingSystemName".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.operatingSystemName = reader.getString(); + } else if ("operatingSystemVersion".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.operatingSystemVersion = reader.getString(); + } else if ("operatingSystemArchitecture".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.operatingSystemArchitecture + = GuestOperatingSystemArchitecture.fromString(reader.getString()); + } else if ("createdTimestamp".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.createdTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("updatedTimestamp".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.updatedTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("displayName".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.displayName = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.type = AssessedMachineType.fromString(reader.getString()); + } else if ("description".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.description = reader.getString(); + } else if ("datacenterMachineArmId".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.datacenterMachineArmId = reader.getString(); + } else if ("datacenterManagementServerArmId".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.datacenterManagementServerArmId = reader.getString(); + } else if ("datacenterManagementServerName".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.datacenterManagementServerName = reader.getString(); + } else if ("megabytesOfMemory".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.megabytesOfMemory + = reader.getNullable(JsonReader::getFloat); + } else if ("numberOfCores".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.numberOfCores = reader.getNullable(JsonReader::getInt); + } else if ("confidenceRatingInPercentage".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.confidenceRatingInPercentage + = reader.getNullable(JsonReader::getFloat); + } else if ("percentageCoresUtilization".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.percentageCoresUtilization + = reader.getNullable(JsonReader::getFloat); + } else if ("percentageMemoryUtilization".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.percentageMemoryUtilization + = reader.getNullable(JsonReader::getFloat); + } else if ("suitability".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.suitability + = CloudSuitability.fromString(reader.getString()); + } else if ("sizingCriterion".equals(fieldName)) { + deserializedAssessedSqlMachineProperties.sizingCriterion + = AssessmentSizingCriterion.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessedSqlMachineProperties; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlMachinesOperations.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlMachinesOperations.java new file mode 100644 index 000000000000..aaaa76d270bc --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlMachinesOperations.java @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of AssessedSqlMachinesOperations. + */ +public interface AssessedSqlMachinesOperations { + /** + * List AssessedSqlMachine resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlMachine list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName); + + /** + * List AssessedSqlMachine resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlMachine list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName, String filter, Integer pageSize, String continuationToken, + Integer totalRecordCount, Context context); + + /** + * Get a AssessedSqlMachine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param assessedSqlMachineName Sql assessment Assessed Machine ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlMachine along with {@link Response}. + */ + Response getWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, String assessedSqlMachineName, Context context); + + /** + * Get a AssessedSqlMachine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param assessedSqlMachineName Sql assessment Assessed Machine ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlMachine. + */ + AssessedSqlMachine get(String resourceGroupName, String projectName, String groupName, String assessmentName, + String assessedSqlMachineName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlRecommendedEntity.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlRecommendedEntity.java new file mode 100644 index 000000000000..bf61fbe4a318 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlRecommendedEntity.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. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlRecommendedEntityInner; + +/** + * An immutable client-side representation of AssessedSqlRecommendedEntity. + */ +public interface AssessedSqlRecommendedEntity { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + AssessedSqlRecommendedEntityProperties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlRecommendedEntityInner + * object. + * + * @return the inner object. + */ + AssessedSqlRecommendedEntityInner innerModel(); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlRecommendedEntityListResult.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlRecommendedEntityListResult.java new file mode 100644 index 000000000000..878fcd3a1a29 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlRecommendedEntityListResult.java @@ -0,0 +1,138 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlRecommendedEntityInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a AssessedSqlRecommendedEntity list operation. + */ +@Fluent +public final class AssessedSqlRecommendedEntityListResult + implements JsonSerializable { + /* + * The AssessedSqlRecommendedEntity items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of AssessedSqlRecommendedEntityListResult class. + */ + public AssessedSqlRecommendedEntityListResult() { + } + + /** + * Get the value property: The AssessedSqlRecommendedEntity items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Set the value property: The AssessedSqlRecommendedEntity items on this page. + * + * @param value the value value to set. + * @return the AssessedSqlRecommendedEntityListResult object itself. + */ + public AssessedSqlRecommendedEntityListResult withValue(List value) { + this.value = value; + return this; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The link to the next page of items. + * + * @param nextLink the nextLink value to set. + * @return the AssessedSqlRecommendedEntityListResult object itself. + */ + public AssessedSqlRecommendedEntityListResult withNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property value in model AssessedSqlRecommendedEntityListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(AssessedSqlRecommendedEntityListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessedSqlRecommendedEntityListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessedSqlRecommendedEntityListResult 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 AssessedSqlRecommendedEntityListResult. + */ + public static AssessedSqlRecommendedEntityListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessedSqlRecommendedEntityListResult deserializedAssessedSqlRecommendedEntityListResult + = new AssessedSqlRecommendedEntityListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> AssessedSqlRecommendedEntityInner.fromJson(reader1)); + deserializedAssessedSqlRecommendedEntityListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedAssessedSqlRecommendedEntityListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessedSqlRecommendedEntityListResult; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlRecommendedEntityOperations.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlRecommendedEntityOperations.java new file mode 100644 index 000000000000..48ae81944f08 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlRecommendedEntityOperations.java @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of AssessedSqlRecommendedEntityOperations. + */ +public interface AssessedSqlRecommendedEntityOperations { + /** + * List AssessedSqlRecommendedEntity resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlRecommendedEntity list operation as paginated response with + * {@link PagedIterable}. + */ + PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName); + + /** + * List AssessedSqlRecommendedEntity resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessedSqlRecommendedEntity list operation as paginated response with + * {@link PagedIterable}. + */ + PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName, String filter, Integer pageSize, String continuationToken, + Integer totalRecordCount, Context context); + + /** + * Get a AssessedSqlRecommendedEntity. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param recommendedAssessedEntityName Sql assessment Assessed Recommended Entity ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlRecommendedEntity along with {@link Response}. + */ + Response getWithResponse(String resourceGroupName, String projectName, + String groupName, String assessmentName, String recommendedAssessedEntityName, Context context); + + /** + * Get a AssessedSqlRecommendedEntity. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param recommendedAssessedEntityName Sql assessment Assessed Recommended Entity ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessedSqlRecommendedEntity. + */ + AssessedSqlRecommendedEntity get(String resourceGroupName, String projectName, String groupName, + String assessmentName, String recommendedAssessedEntityName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlRecommendedEntityProperties.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlRecommendedEntityProperties.java new file mode 100644 index 000000000000..c669f7ba2233 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessedSqlRecommendedEntityProperties.java @@ -0,0 +1,377 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * Assessed SQL recommended entity properties. + */ +@Fluent +public final class AssessedSqlRecommendedEntityProperties + implements JsonSerializable { + /* + * Gets or sets machine name. + */ + private String machineName; + + /* + * Gets or sets SQL instance name. + */ + private String instanceName; + + /* + * Gets the product support status related details. + */ + private ProductSupportStatus productSupportStatus; + + /* + * Gets or sets assessed database count. + */ + private Integer dbCount; + + /* + * Gets or sets the total discovered database count. + */ + private Integer discoveredDBCount; + + /* + * Gets or sets a value indicating whether instance deep discovery has occurred or + * not. + */ + private Boolean hasScanOccurred; + + /* + * Gets or sets the recommended azure SQL target type. + */ + private TargetType recommendedAzureSqlTargetType; + + /* + * Gets or sets the recommended azure SQL suitability. + */ + private RecommendedSuitability recommendedSuitability; + + /* + * SQL instance azure SQL MI suitability details. + */ + private SqlAssessmentV2PaasSuitabilityData azureSqlMISuitabilityDetails; + + /* + * SQL instance azure SQL DB suitability details. + */ + private SqlAssessmentV2PaasSuitabilityData azureSqlDBSuitabilityDetails; + + /* + * SQL instance azure SQL VM suitability details. + */ + private SqlAssessmentV2IaasSuitabilityData azureSqlVMSuitabilityDetails; + + /* + * Gets or sets Arm id of assessed entity. + */ + private String assessedSqlEntityArmId; + + /* + * Gets or sets a value indicating whether the SQL instance is clustered or not. + */ + private Boolean isClustered; + + /* + * Gets or sets a value indicating whether the high availability is enabled or not. + */ + private Boolean isHighAvailabilityEnabled; + + /* + * Gets the SQL edition from the recommended entity if applicable. + */ + private String sqlEdition; + + /* + * Gets the SQL version from the recommended entity if applicable. + */ + private String sqlVersion; + + /* + * Assessment sizing criterion. + */ + private AssessmentSizingCriterion sizingCriterion; + + /** + * Creates an instance of AssessedSqlRecommendedEntityProperties class. + */ + public AssessedSqlRecommendedEntityProperties() { + } + + /** + * Get the machineName property: Gets or sets machine name. + * + * @return the machineName value. + */ + public String machineName() { + return this.machineName; + } + + /** + * Get the instanceName property: Gets or sets SQL instance name. + * + * @return the instanceName value. + */ + public String instanceName() { + return this.instanceName; + } + + /** + * Get the productSupportStatus property: Gets the product support status related details. + * + * @return the productSupportStatus value. + */ + public ProductSupportStatus productSupportStatus() { + return this.productSupportStatus; + } + + /** + * Get the dbCount property: Gets or sets assessed database count. + * + * @return the dbCount value. + */ + public Integer dbCount() { + return this.dbCount; + } + + /** + * Get the discoveredDBCount property: Gets or sets the total discovered database count. + * + * @return the discoveredDBCount value. + */ + public Integer discoveredDBCount() { + return this.discoveredDBCount; + } + + /** + * Get the hasScanOccurred property: Gets or sets a value indicating whether instance deep discovery has occurred or + * not. + * + * @return the hasScanOccurred value. + */ + public Boolean hasScanOccurred() { + return this.hasScanOccurred; + } + + /** + * Get the recommendedAzureSqlTargetType property: Gets or sets the recommended azure SQL target type. + * + * @return the recommendedAzureSqlTargetType value. + */ + public TargetType recommendedAzureSqlTargetType() { + return this.recommendedAzureSqlTargetType; + } + + /** + * Get the recommendedSuitability property: Gets or sets the recommended azure SQL suitability. + * + * @return the recommendedSuitability value. + */ + public RecommendedSuitability recommendedSuitability() { + return this.recommendedSuitability; + } + + /** + * Get the azureSqlMISuitabilityDetails property: SQL instance azure SQL MI suitability details. + * + * @return the azureSqlMISuitabilityDetails value. + */ + public SqlAssessmentV2PaasSuitabilityData azureSqlMISuitabilityDetails() { + return this.azureSqlMISuitabilityDetails; + } + + /** + * Get the azureSqlDBSuitabilityDetails property: SQL instance azure SQL DB suitability details. + * + * @return the azureSqlDBSuitabilityDetails value. + */ + public SqlAssessmentV2PaasSuitabilityData azureSqlDBSuitabilityDetails() { + return this.azureSqlDBSuitabilityDetails; + } + + /** + * Get the azureSqlVMSuitabilityDetails property: SQL instance azure SQL VM suitability details. + * + * @return the azureSqlVMSuitabilityDetails value. + */ + public SqlAssessmentV2IaasSuitabilityData azureSqlVMSuitabilityDetails() { + return this.azureSqlVMSuitabilityDetails; + } + + /** + * Get the assessedSqlEntityArmId property: Gets or sets Arm id of assessed entity. + * + * @return the assessedSqlEntityArmId value. + */ + public String assessedSqlEntityArmId() { + return this.assessedSqlEntityArmId; + } + + /** + * Set the assessedSqlEntityArmId property: Gets or sets Arm id of assessed entity. + * + * @param assessedSqlEntityArmId the assessedSqlEntityArmId value to set. + * @return the AssessedSqlRecommendedEntityProperties object itself. + */ + public AssessedSqlRecommendedEntityProperties withAssessedSqlEntityArmId(String assessedSqlEntityArmId) { + this.assessedSqlEntityArmId = assessedSqlEntityArmId; + return this; + } + + /** + * Get the isClustered property: Gets or sets a value indicating whether the SQL instance is clustered or not. + * + * @return the isClustered value. + */ + public Boolean isClustered() { + return this.isClustered; + } + + /** + * Get the isHighAvailabilityEnabled property: Gets or sets a value indicating whether the high availability is + * enabled or not. + * + * @return the isHighAvailabilityEnabled value. + */ + public Boolean isHighAvailabilityEnabled() { + return this.isHighAvailabilityEnabled; + } + + /** + * Get the sqlEdition property: Gets the SQL edition from the recommended entity if applicable. + * + * @return the sqlEdition value. + */ + public String sqlEdition() { + return this.sqlEdition; + } + + /** + * Get the sqlVersion property: Gets the SQL version from the recommended entity if applicable. + * + * @return the sqlVersion value. + */ + public String sqlVersion() { + return this.sqlVersion; + } + + /** + * Get the sizingCriterion property: Assessment sizing criterion. + * + * @return the sizingCriterion value. + */ + public AssessmentSizingCriterion sizingCriterion() { + return this.sizingCriterion; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (productSupportStatus() != null) { + productSupportStatus().validate(); + } + if (azureSqlMISuitabilityDetails() != null) { + azureSqlMISuitabilityDetails().validate(); + } + if (azureSqlDBSuitabilityDetails() != null) { + azureSqlDBSuitabilityDetails().validate(); + } + if (azureSqlVMSuitabilityDetails() != null) { + azureSqlVMSuitabilityDetails().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("assessedSqlEntityArmId", this.assessedSqlEntityArmId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessedSqlRecommendedEntityProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessedSqlRecommendedEntityProperties 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 AssessedSqlRecommendedEntityProperties. + */ + public static AssessedSqlRecommendedEntityProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessedSqlRecommendedEntityProperties deserializedAssessedSqlRecommendedEntityProperties + = new AssessedSqlRecommendedEntityProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("machineName".equals(fieldName)) { + deserializedAssessedSqlRecommendedEntityProperties.machineName = reader.getString(); + } else if ("instanceName".equals(fieldName)) { + deserializedAssessedSqlRecommendedEntityProperties.instanceName = reader.getString(); + } else if ("productSupportStatus".equals(fieldName)) { + deserializedAssessedSqlRecommendedEntityProperties.productSupportStatus + = ProductSupportStatus.fromJson(reader); + } else if ("dbCount".equals(fieldName)) { + deserializedAssessedSqlRecommendedEntityProperties.dbCount = reader.getNullable(JsonReader::getInt); + } else if ("discoveredDBCount".equals(fieldName)) { + deserializedAssessedSqlRecommendedEntityProperties.discoveredDBCount + = reader.getNullable(JsonReader::getInt); + } else if ("hasScanOccurred".equals(fieldName)) { + deserializedAssessedSqlRecommendedEntityProperties.hasScanOccurred + = reader.getNullable(JsonReader::getBoolean); + } else if ("recommendedAzureSqlTargetType".equals(fieldName)) { + deserializedAssessedSqlRecommendedEntityProperties.recommendedAzureSqlTargetType + = TargetType.fromString(reader.getString()); + } else if ("recommendedSuitability".equals(fieldName)) { + deserializedAssessedSqlRecommendedEntityProperties.recommendedSuitability + = RecommendedSuitability.fromString(reader.getString()); + } else if ("azureSqlMISuitabilityDetails".equals(fieldName)) { + deserializedAssessedSqlRecommendedEntityProperties.azureSqlMISuitabilityDetails + = SqlAssessmentV2PaasSuitabilityData.fromJson(reader); + } else if ("azureSqlDBSuitabilityDetails".equals(fieldName)) { + deserializedAssessedSqlRecommendedEntityProperties.azureSqlDBSuitabilityDetails + = SqlAssessmentV2PaasSuitabilityData.fromJson(reader); + } else if ("azureSqlVMSuitabilityDetails".equals(fieldName)) { + deserializedAssessedSqlRecommendedEntityProperties.azureSqlVMSuitabilityDetails + = SqlAssessmentV2IaasSuitabilityData.fromJson(reader); + } else if ("assessedSqlEntityArmId".equals(fieldName)) { + deserializedAssessedSqlRecommendedEntityProperties.assessedSqlEntityArmId = reader.getString(); + } else if ("isClustered".equals(fieldName)) { + deserializedAssessedSqlRecommendedEntityProperties.isClustered + = reader.getNullable(JsonReader::getBoolean); + } else if ("isHighAvailabilityEnabled".equals(fieldName)) { + deserializedAssessedSqlRecommendedEntityProperties.isHighAvailabilityEnabled + = reader.getNullable(JsonReader::getBoolean); + } else if ("sqlEdition".equals(fieldName)) { + deserializedAssessedSqlRecommendedEntityProperties.sqlEdition = reader.getString(); + } else if ("sqlVersion".equals(fieldName)) { + deserializedAssessedSqlRecommendedEntityProperties.sqlVersion = reader.getString(); + } else if ("sizingCriterion".equals(fieldName)) { + deserializedAssessedSqlRecommendedEntityProperties.sizingCriterion + = AssessmentSizingCriterion.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessedSqlRecommendedEntityProperties; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/Assessment.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/Assessment.java new file mode 100644 index 000000000000..502b29af8fca --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/Assessment.java @@ -0,0 +1,165 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentInner; + +/** + * An immutable client-side representation of Assessment. + */ +public interface Assessment { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + MachineAssessmentProperties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentInner object. + * + * @return the inner object. + */ + AssessmentInner innerModel(); + + /** + * The entirety of the Assessment definition. + */ + interface Definition + extends DefinitionStages.Blank, DefinitionStages.WithParentResource, DefinitionStages.WithCreate { + } + + /** + * The Assessment definition stages. + */ + interface DefinitionStages { + /** + * The first stage of the Assessment definition. + */ + interface Blank extends WithParentResource { + } + + /** + * The stage of the Assessment definition allowing to specify parent resource. + */ + interface WithParentResource { + /** + * Specifies resourceGroupName, projectName, groupName. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @return the next definition stage. + */ + WithCreate withExistingGroup(String resourceGroupName, String projectName, String groupName); + } + + /** + * The stage of the Assessment definition which contains all the minimum required properties for the resource to + * be created, but also allows for any other optional properties to be specified. + */ + interface WithCreate extends DefinitionStages.WithProperties { + /** + * Executes the create request. + * + * @return the created resource. + */ + Assessment create(); + + /** + * Executes the create request. + * + * @param context The context to associate with this operation. + * @return the created resource. + */ + Assessment create(Context context); + } + + /** + * The stage of the Assessment definition allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The resource-specific properties for this resource.. + * + * @param properties The resource-specific properties for this resource. + * @return the next definition stage. + */ + WithCreate withProperties(MachineAssessmentProperties properties); + } + } + + /** + * Refreshes the resource to sync with Azure. + * + * @return the refreshed resource. + */ + Assessment refresh(); + + /** + * Refreshes the resource to sync with Azure. + * + * @param context The context to associate with this operation. + * @return the refreshed resource. + */ + Assessment refresh(Context context); + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format. + */ + DownloadUrl downloadUrl(Object body); + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format. + */ + DownloadUrl downloadUrl(Object body, Context context); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentListResult.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentListResult.java new file mode 100644 index 000000000000..83479de963f4 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentListResult.java @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a Assessment list operation. + */ +@Fluent +public final class AssessmentListResult implements JsonSerializable { + /* + * The Assessment items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of AssessmentListResult class. + */ + public AssessmentListResult() { + } + + /** + * Get the value property: The Assessment items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Set the value property: The Assessment items on this page. + * + * @param value the value value to set. + * @return the AssessmentListResult object itself. + */ + public AssessmentListResult withValue(List value) { + this.value = value; + return this; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The link to the next page of items. + * + * @param nextLink the nextLink value to set. + * @return the AssessmentListResult object itself. + */ + public AssessmentListResult withNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property value in model AssessmentListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(AssessmentListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessmentListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessmentListResult 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 AssessmentListResult. + */ + public static AssessmentListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessmentListResult deserializedAssessmentListResult = new AssessmentListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value = reader.readArray(reader1 -> AssessmentInner.fromJson(reader1)); + deserializedAssessmentListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedAssessmentListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessmentListResult; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentOptions.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentOptions.java new file mode 100644 index 000000000000..8bc9950a698e --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentOptions.java @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentOptionsInner; + +/** + * An immutable client-side representation of AssessmentOptions. + */ +public interface AssessmentOptions { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + AssessmentOptionsProperties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentOptionsInner object. + * + * @return the inner object. + */ + AssessmentOptionsInner innerModel(); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentOptionsListResult.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentOptionsListResult.java new file mode 100644 index 000000000000..8d206d8caf33 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentOptionsListResult.java @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentOptionsInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a AssessmentOptions list operation. + */ +@Fluent +public final class AssessmentOptionsListResult implements JsonSerializable { + /* + * The AssessmentOptions items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of AssessmentOptionsListResult class. + */ + public AssessmentOptionsListResult() { + } + + /** + * Get the value property: The AssessmentOptions items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Set the value property: The AssessmentOptions items on this page. + * + * @param value the value value to set. + * @return the AssessmentOptionsListResult object itself. + */ + public AssessmentOptionsListResult withValue(List value) { + this.value = value; + return this; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The link to the next page of items. + * + * @param nextLink the nextLink value to set. + * @return the AssessmentOptionsListResult object itself. + */ + public AssessmentOptionsListResult withNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property value in model AssessmentOptionsListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(AssessmentOptionsListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessmentOptionsListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessmentOptionsListResult 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 AssessmentOptionsListResult. + */ + public static AssessmentOptionsListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessmentOptionsListResult deserializedAssessmentOptionsListResult = new AssessmentOptionsListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> AssessmentOptionsInner.fromJson(reader1)); + deserializedAssessmentOptionsListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedAssessmentOptionsListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessmentOptionsListResult; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentOptionsOperations.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentOptionsOperations.java new file mode 100644 index 000000000000..0fc2d30010d3 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentOptionsOperations.java @@ -0,0 +1,68 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of AssessmentOptionsOperations. + */ +public interface AssessmentOptionsOperations { + /** + * List AssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentOptions list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName); + + /** + * List AssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentOptions list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context); + + /** + * Get a AssessmentOptions. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param assessmentOptionsName assessment options ARM name. Accepted value is 'default'. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessmentOptions along with {@link Response}. + */ + Response getWithResponse(String resourceGroupName, String projectName, + String assessmentOptionsName, Context context); + + /** + * Get a AssessmentOptions. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param assessmentOptionsName assessment options ARM name. Accepted value is 'default'. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessmentOptions. + */ + AssessmentOptions get(String resourceGroupName, String projectName, String assessmentOptionsName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentOptionsProperties.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentOptionsProperties.java new file mode 100644 index 000000000000..04271f5820f6 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentOptionsProperties.java @@ -0,0 +1,233 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; +import java.util.List; + +/** + * Assessment options properties. + */ +@Immutable +public final class AssessmentOptionsProperties implements JsonSerializable { + /* + * Dictionary of VM families grouped by vm family name describing the targeted + * azure locations of VM family and the category of the family. + */ + private List vmFamilies; + + /* + * List of supported VM Families. + */ + private List reservedInstanceVmFamilies; + + /* + * List of supported Azure regions for reserved instances. + */ + private List reservedInstanceSupportedLocations; + + /* + * List of supported currencies for reserved instances. + */ + private List reservedInstanceSupportedCurrencies; + + /* + * List of supported Azure offer codes for reserved instances. + */ + private List reservedInstanceSupportedOffers; + + /* + * Ultra disk related assessment options. + */ + private List ultraDiskVmFamilies; + + /* + * List of VM Families that support premium disks for assessments. + */ + private List premiumDiskVmFamilies; + + /* + * List of VM Families that support Savings plan offer for assessments. + */ + private List savingsPlanVmFamilies; + + /* + * List of Azure locations that support Savings plan offer for assessments. + */ + private List savingsPlanSupportedLocations; + + /** + * Creates an instance of AssessmentOptionsProperties class. + */ + public AssessmentOptionsProperties() { + } + + /** + * Get the vmFamilies property: Dictionary of VM families grouped by vm family name describing the targeted + * azure locations of VM family and the category of the family. + * + * @return the vmFamilies value. + */ + public List vmFamilies() { + return this.vmFamilies; + } + + /** + * Get the reservedInstanceVmFamilies property: List of supported VM Families. + * + * @return the reservedInstanceVmFamilies value. + */ + public List reservedInstanceVmFamilies() { + return this.reservedInstanceVmFamilies; + } + + /** + * Get the reservedInstanceSupportedLocations property: List of supported Azure regions for reserved instances. + * + * @return the reservedInstanceSupportedLocations value. + */ + public List reservedInstanceSupportedLocations() { + return this.reservedInstanceSupportedLocations; + } + + /** + * Get the reservedInstanceSupportedCurrencies property: List of supported currencies for reserved instances. + * + * @return the reservedInstanceSupportedCurrencies value. + */ + public List reservedInstanceSupportedCurrencies() { + return this.reservedInstanceSupportedCurrencies; + } + + /** + * Get the reservedInstanceSupportedOffers property: List of supported Azure offer codes for reserved instances. + * + * @return the reservedInstanceSupportedOffers value. + */ + public List reservedInstanceSupportedOffers() { + return this.reservedInstanceSupportedOffers; + } + + /** + * Get the ultraDiskVmFamilies property: Ultra disk related assessment options. + * + * @return the ultraDiskVmFamilies value. + */ + public List ultraDiskVmFamilies() { + return this.ultraDiskVmFamilies; + } + + /** + * Get the premiumDiskVmFamilies property: List of VM Families that support premium disks for assessments. + * + * @return the premiumDiskVmFamilies value. + */ + public List premiumDiskVmFamilies() { + return this.premiumDiskVmFamilies; + } + + /** + * Get the savingsPlanVmFamilies property: List of VM Families that support Savings plan offer for assessments. + * + * @return the savingsPlanVmFamilies value. + */ + public List savingsPlanVmFamilies() { + return this.savingsPlanVmFamilies; + } + + /** + * Get the savingsPlanSupportedLocations property: List of Azure locations that support Savings plan offer for + * assessments. + * + * @return the savingsPlanSupportedLocations value. + */ + public List savingsPlanSupportedLocations() { + return this.savingsPlanSupportedLocations; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (vmFamilies() != null) { + vmFamilies().forEach(e -> e.validate()); + } + if (ultraDiskVmFamilies() != null) { + ultraDiskVmFamilies().forEach(e -> e.validate()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessmentOptionsProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessmentOptionsProperties 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 AssessmentOptionsProperties. + */ + public static AssessmentOptionsProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessmentOptionsProperties deserializedAssessmentOptionsProperties = new AssessmentOptionsProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("vmFamilies".equals(fieldName)) { + List vmFamilies = reader.readArray(reader1 -> VmFamilyOptions.fromJson(reader1)); + deserializedAssessmentOptionsProperties.vmFamilies = vmFamilies; + } else if ("reservedInstanceVmFamilies".equals(fieldName)) { + List reservedInstanceVmFamilies = reader.readArray(reader1 -> reader1.getString()); + deserializedAssessmentOptionsProperties.reservedInstanceVmFamilies = reservedInstanceVmFamilies; + } else if ("reservedInstanceSupportedLocations".equals(fieldName)) { + List reservedInstanceSupportedLocations = reader.readArray(reader1 -> reader1.getString()); + deserializedAssessmentOptionsProperties.reservedInstanceSupportedLocations + = reservedInstanceSupportedLocations; + } else if ("reservedInstanceSupportedCurrencies".equals(fieldName)) { + List reservedInstanceSupportedCurrencies = reader.readArray(reader1 -> reader1.getString()); + deserializedAssessmentOptionsProperties.reservedInstanceSupportedCurrencies + = reservedInstanceSupportedCurrencies; + } else if ("reservedInstanceSupportedOffers".equals(fieldName)) { + List reservedInstanceSupportedOffers = reader.readArray(reader1 -> reader1.getString()); + deserializedAssessmentOptionsProperties.reservedInstanceSupportedOffers + = reservedInstanceSupportedOffers; + } else if ("ultraDiskVmFamilies".equals(fieldName)) { + List ultraDiskVmFamilies + = reader.readArray(reader1 -> UltraDiskAssessmentOptions.fromJson(reader1)); + deserializedAssessmentOptionsProperties.ultraDiskVmFamilies = ultraDiskVmFamilies; + } else if ("premiumDiskVmFamilies".equals(fieldName)) { + List premiumDiskVmFamilies = reader.readArray(reader1 -> reader1.getString()); + deserializedAssessmentOptionsProperties.premiumDiskVmFamilies = premiumDiskVmFamilies; + } else if ("savingsPlanVmFamilies".equals(fieldName)) { + List savingsPlanVmFamilies = reader.readArray(reader1 -> reader1.getString()); + deserializedAssessmentOptionsProperties.savingsPlanVmFamilies = savingsPlanVmFamilies; + } else if ("savingsPlanSupportedLocations".equals(fieldName)) { + List savingsPlanSupportedLocations = reader.readArray(reader1 -> reader1.getString()); + deserializedAssessmentOptionsProperties.savingsPlanSupportedLocations + = savingsPlanSupportedLocations; + } else { + reader.skipChildren(); + } + } + + return deserializedAssessmentOptionsProperties; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentProject.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentProject.java new file mode 100644 index 000000000000..e0a698589d8b --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentProject.java @@ -0,0 +1,265 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.management.Region; +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentProjectInner; +import java.util.Map; + +/** + * An immutable client-side representation of AssessmentProject. + */ +public interface AssessmentProject { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the location property: The geo-location where the resource lives. + * + * @return the location value. + */ + String location(); + + /** + * Gets the tags property: Resource tags. + * + * @return the tags value. + */ + Map tags(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + ProjectProperties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the region of the resource. + * + * @return the region of the resource. + */ + Region region(); + + /** + * Gets the name of the resource region. + * + * @return the name of the resource region. + */ + String regionName(); + + /** + * Gets the name of the resource group. + * + * @return the name of the resource group. + */ + String resourceGroupName(); + + /** + * Gets the inner com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentProjectInner object. + * + * @return the inner object. + */ + AssessmentProjectInner innerModel(); + + /** + * The entirety of the AssessmentProject definition. + */ + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithLocation, + DefinitionStages.WithResourceGroup, DefinitionStages.WithCreate { + } + + /** + * The AssessmentProject definition stages. + */ + interface DefinitionStages { + /** + * The first stage of the AssessmentProject definition. + */ + interface Blank extends WithLocation { + } + + /** + * The stage of the AssessmentProject definition allowing to specify location. + */ + interface WithLocation { + /** + * Specifies the region for the resource. + * + * @param location The geo-location where the resource lives. + * @return the next definition stage. + */ + WithResourceGroup withRegion(Region location); + + /** + * Specifies the region for the resource. + * + * @param location The geo-location where the resource lives. + * @return the next definition stage. + */ + WithResourceGroup withRegion(String location); + } + + /** + * The stage of the AssessmentProject definition allowing to specify parent resource. + */ + interface WithResourceGroup { + /** + * Specifies resourceGroupName. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @return the next definition stage. + */ + WithCreate withExistingResourceGroup(String resourceGroupName); + } + + /** + * The stage of the AssessmentProject definition which contains all the minimum required properties for the + * resource to be created, but also allows for any other optional properties to be specified. + */ + interface WithCreate extends DefinitionStages.WithTags, DefinitionStages.WithProperties { + /** + * Executes the create request. + * + * @return the created resource. + */ + AssessmentProject create(); + + /** + * Executes the create request. + * + * @param context The context to associate with this operation. + * @return the created resource. + */ + AssessmentProject create(Context context); + } + + /** + * The stage of the AssessmentProject definition allowing to specify tags. + */ + interface WithTags { + /** + * Specifies the tags property: Resource tags.. + * + * @param tags Resource tags. + * @return the next definition stage. + */ + WithCreate withTags(Map tags); + } + + /** + * The stage of the AssessmentProject definition allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The resource-specific properties for this resource.. + * + * @param properties The resource-specific properties for this resource. + * @return the next definition stage. + */ + WithCreate withProperties(ProjectProperties properties); + } + } + + /** + * Begins update for the AssessmentProject resource. + * + * @return the stage of resource update. + */ + AssessmentProject.Update update(); + + /** + * The template for AssessmentProject update. + */ + interface Update extends UpdateStages.WithTags, UpdateStages.WithProperties { + /** + * Executes the update request. + * + * @return the updated resource. + */ + AssessmentProject apply(); + + /** + * Executes the update request. + * + * @param context The context to associate with this operation. + * @return the updated resource. + */ + AssessmentProject apply(Context context); + } + + /** + * The AssessmentProject update stages. + */ + interface UpdateStages { + /** + * The stage of the AssessmentProject update allowing to specify tags. + */ + interface WithTags { + /** + * Specifies the tags property: Resource tags.. + * + * @param tags Resource tags. + * @return the next definition stage. + */ + Update withTags(Map tags); + } + + /** + * The stage of the AssessmentProject update allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The updatable properties of the AssessmentProject.. + * + * @param properties The updatable properties of the AssessmentProject. + * @return the next definition stage. + */ + Update withProperties(AssessmentProjectUpdateProperties properties); + } + } + + /** + * Refreshes the resource to sync with Azure. + * + * @return the refreshed resource. + */ + AssessmentProject refresh(); + + /** + * Refreshes the resource to sync with Azure. + * + * @param context The context to associate with this operation. + * @return the refreshed resource. + */ + AssessmentProject refresh(Context context); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentProjectListResult.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentProjectListResult.java new file mode 100644 index 000000000000..10a5e3f68bc7 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentProjectListResult.java @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentProjectInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a AssessmentProject list operation. + */ +@Fluent +public final class AssessmentProjectListResult implements JsonSerializable { + /* + * The AssessmentProject items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of AssessmentProjectListResult class. + */ + public AssessmentProjectListResult() { + } + + /** + * Get the value property: The AssessmentProject items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Set the value property: The AssessmentProject items on this page. + * + * @param value the value value to set. + * @return the AssessmentProjectListResult object itself. + */ + public AssessmentProjectListResult withValue(List value) { + this.value = value; + return this; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The link to the next page of items. + * + * @param nextLink the nextLink value to set. + * @return the AssessmentProjectListResult object itself. + */ + public AssessmentProjectListResult withNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property value in model AssessmentProjectListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(AssessmentProjectListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessmentProjectListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessmentProjectListResult 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 AssessmentProjectListResult. + */ + public static AssessmentProjectListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessmentProjectListResult deserializedAssessmentProjectListResult = new AssessmentProjectListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> AssessmentProjectInner.fromJson(reader1)); + deserializedAssessmentProjectListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedAssessmentProjectListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessmentProjectListResult; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentProjectSummary.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentProjectSummary.java new file mode 100644 index 000000000000..8fa5cf67258b --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentProjectSummary.java @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentProjectSummaryInner; + +/** + * An immutable client-side representation of AssessmentProjectSummary. + */ +public interface AssessmentProjectSummary { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + AssessmentProjectSummaryProperties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentProjectSummaryInner object. + * + * @return the inner object. + */ + AssessmentProjectSummaryInner innerModel(); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentProjectSummaryListResult.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentProjectSummaryListResult.java new file mode 100644 index 000000000000..95131b8dd390 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentProjectSummaryListResult.java @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentProjectSummaryInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a AssessmentProjectSummary list operation. + */ +@Fluent +public final class AssessmentProjectSummaryListResult implements JsonSerializable { + /* + * The AssessmentProjectSummary items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of AssessmentProjectSummaryListResult class. + */ + public AssessmentProjectSummaryListResult() { + } + + /** + * Get the value property: The AssessmentProjectSummary items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Set the value property: The AssessmentProjectSummary items on this page. + * + * @param value the value value to set. + * @return the AssessmentProjectSummaryListResult object itself. + */ + public AssessmentProjectSummaryListResult withValue(List value) { + this.value = value; + return this; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The link to the next page of items. + * + * @param nextLink the nextLink value to set. + * @return the AssessmentProjectSummaryListResult object itself. + */ + public AssessmentProjectSummaryListResult withNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property value in model AssessmentProjectSummaryListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(AssessmentProjectSummaryListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessmentProjectSummaryListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessmentProjectSummaryListResult 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 AssessmentProjectSummaryListResult. + */ + public static AssessmentProjectSummaryListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessmentProjectSummaryListResult deserializedAssessmentProjectSummaryListResult + = new AssessmentProjectSummaryListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> AssessmentProjectSummaryInner.fromJson(reader1)); + deserializedAssessmentProjectSummaryListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedAssessmentProjectSummaryListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessmentProjectSummaryListResult; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentProjectSummaryOperations.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentProjectSummaryOperations.java new file mode 100644 index 000000000000..ec9c3338b8ec --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentProjectSummaryOperations.java @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of AssessmentProjectSummaryOperations. + */ +public interface AssessmentProjectSummaryOperations { + /** + * List AssessmentProjectSummary resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProjectSummary list operation as paginated response with + * {@link PagedIterable}. + */ + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName); + + /** + * List AssessmentProjectSummary resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProjectSummary list operation as paginated response with + * {@link PagedIterable}. + */ + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context); + + /** + * Get a AssessmentProjectSummary. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param projectSummaryName Group ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessmentProjectSummary along with {@link Response}. + */ + Response getWithResponse(String resourceGroupName, String projectName, + String projectSummaryName, Context context); + + /** + * Get a AssessmentProjectSummary. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param projectSummaryName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessmentProjectSummary. + */ + AssessmentProjectSummary get(String resourceGroupName, String projectName, String projectSummaryName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentProjectSummaryProperties.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentProjectSummaryProperties.java new file mode 100644 index 000000000000..0ed1c1f5a156 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentProjectSummaryProperties.java @@ -0,0 +1,196 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.util.List; + +/** + * Assessment project summary properties class. + */ +@Immutable +public final class AssessmentProjectSummaryProperties implements JsonSerializable { + /* + * Gets the Error summary by feature. Contains number of affected Entities per + * feature. + */ + private List errorSummaryAffectedEntities; + + /* + * Gets the number of private endpoint connections. + */ + private Integer numberOfPrivateEndpointConnections; + + /* + * Gets the number of groups created in this project. + */ + private Integer numberOfGroups; + + /* + * Gets the number of machines part of this project. + */ + private Integer numberOfMachines; + + /* + * Gets the number of import machines part of this project. + */ + private Integer numberOfImportMachines; + + /* + * Gets the number of assessments created in this project. + */ + private Integer numberOfAssessments; + + /* + * Gets the last assessment timestamp. + */ + private OffsetDateTime lastAssessmentTimestamp; + + /** + * Creates an instance of AssessmentProjectSummaryProperties class. + */ + public AssessmentProjectSummaryProperties() { + } + + /** + * Get the errorSummaryAffectedEntities property: Gets the Error summary by feature. Contains number of affected + * Entities per + * feature. + * + * @return the errorSummaryAffectedEntities value. + */ + public List errorSummaryAffectedEntities() { + return this.errorSummaryAffectedEntities; + } + + /** + * Get the numberOfPrivateEndpointConnections property: Gets the number of private endpoint connections. + * + * @return the numberOfPrivateEndpointConnections value. + */ + public Integer numberOfPrivateEndpointConnections() { + return this.numberOfPrivateEndpointConnections; + } + + /** + * Get the numberOfGroups property: Gets the number of groups created in this project. + * + * @return the numberOfGroups value. + */ + public Integer numberOfGroups() { + return this.numberOfGroups; + } + + /** + * Get the numberOfMachines property: Gets the number of machines part of this project. + * + * @return the numberOfMachines value. + */ + public Integer numberOfMachines() { + return this.numberOfMachines; + } + + /** + * Get the numberOfImportMachines property: Gets the number of import machines part of this project. + * + * @return the numberOfImportMachines value. + */ + public Integer numberOfImportMachines() { + return this.numberOfImportMachines; + } + + /** + * Get the numberOfAssessments property: Gets the number of assessments created in this project. + * + * @return the numberOfAssessments value. + */ + public Integer numberOfAssessments() { + return this.numberOfAssessments; + } + + /** + * Get the lastAssessmentTimestamp property: Gets the last assessment timestamp. + * + * @return the lastAssessmentTimestamp value. + */ + public OffsetDateTime lastAssessmentTimestamp() { + return this.lastAssessmentTimestamp; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (errorSummaryAffectedEntities() != null) { + errorSummaryAffectedEntities().forEach(e -> e.validate()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessmentProjectSummaryProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessmentProjectSummaryProperties 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 AssessmentProjectSummaryProperties. + */ + public static AssessmentProjectSummaryProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessmentProjectSummaryProperties deserializedAssessmentProjectSummaryProperties + = new AssessmentProjectSummaryProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("errorSummaryAffectedEntities".equals(fieldName)) { + List errorSummaryAffectedEntities + = reader.readArray(reader1 -> ErrorSummary.fromJson(reader1)); + deserializedAssessmentProjectSummaryProperties.errorSummaryAffectedEntities + = errorSummaryAffectedEntities; + } else if ("numberOfPrivateEndpointConnections".equals(fieldName)) { + deserializedAssessmentProjectSummaryProperties.numberOfPrivateEndpointConnections + = reader.getNullable(JsonReader::getInt); + } else if ("numberOfGroups".equals(fieldName)) { + deserializedAssessmentProjectSummaryProperties.numberOfGroups + = reader.getNullable(JsonReader::getInt); + } else if ("numberOfMachines".equals(fieldName)) { + deserializedAssessmentProjectSummaryProperties.numberOfMachines + = reader.getNullable(JsonReader::getInt); + } else if ("numberOfImportMachines".equals(fieldName)) { + deserializedAssessmentProjectSummaryProperties.numberOfImportMachines + = reader.getNullable(JsonReader::getInt); + } else if ("numberOfAssessments".equals(fieldName)) { + deserializedAssessmentProjectSummaryProperties.numberOfAssessments + = reader.getNullable(JsonReader::getInt); + } else if ("lastAssessmentTimestamp".equals(fieldName)) { + deserializedAssessmentProjectSummaryProperties.lastAssessmentTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessmentProjectSummaryProperties; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentProjectUpdate.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentProjectUpdate.java new file mode 100644 index 000000000000..bec1baa28805 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentProjectUpdate.java @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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.Map; + +/** + * The type used for update operations of the AssessmentProject. + */ +@Fluent +public final class AssessmentProjectUpdate implements JsonSerializable { + /* + * Resource tags. + */ + private Map tags; + + /* + * The updatable properties of the AssessmentProject. + */ + private AssessmentProjectUpdateProperties properties; + + /** + * Creates an instance of AssessmentProjectUpdate class. + */ + public AssessmentProjectUpdate() { + } + + /** + * Get the tags property: Resource tags. + * + * @return the tags value. + */ + public Map tags() { + return this.tags; + } + + /** + * Set the tags property: Resource tags. + * + * @param tags the tags value to set. + * @return the AssessmentProjectUpdate object itself. + */ + public AssessmentProjectUpdate withTags(Map tags) { + this.tags = tags; + return this; + } + + /** + * Get the properties property: The updatable properties of the AssessmentProject. + * + * @return the properties value. + */ + public AssessmentProjectUpdateProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The updatable properties of the AssessmentProject. + * + * @param properties the properties value to set. + * @return the AssessmentProjectUpdate object itself. + */ + public AssessmentProjectUpdate withProperties(AssessmentProjectUpdateProperties properties) { + this.properties = properties; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessmentProjectUpdate from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessmentProjectUpdate 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 AssessmentProjectUpdate. + */ + public static AssessmentProjectUpdate fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessmentProjectUpdate deserializedAssessmentProjectUpdate = new AssessmentProjectUpdate(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("tags".equals(fieldName)) { + Map tags = reader.readMap(reader1 -> reader1.getString()); + deserializedAssessmentProjectUpdate.tags = tags; + } else if ("properties".equals(fieldName)) { + deserializedAssessmentProjectUpdate.properties = AssessmentProjectUpdateProperties.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessmentProjectUpdate; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentProjectUpdateProperties.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentProjectUpdateProperties.java new file mode 100644 index 000000000000..1c78f2b826f0 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentProjectUpdateProperties.java @@ -0,0 +1,279 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * The updatable properties of the AssessmentProject. + */ +@Fluent +public final class AssessmentProjectUpdateProperties implements JsonSerializable { + /* + * Assessment solution ARM id tracked by Microsoft.Migrate/migrateProjects. + */ + private String assessmentSolutionId; + + /* + * Assessment project status. + */ + private ProjectStatus projectStatus; + + /* + * The ARM id of service map workspace created by customer. + */ + private String customerWorkspaceId; + + /* + * Location of service map workspace created by customer. + */ + private String customerWorkspaceLocation; + + /* + * This value can be set to 'enabled' to avoid breaking changes on existing + * customer resources and templates. If set to 'disabled', traffic over public + * interface is not allowed, and private endpoint connections would be the + * exclusive access method. + */ + private String publicNetworkAccess; + + /* + * The ARM id of the storage account used for interactions when public access is + * disabled. + */ + private String customerStorageAccountArmId; + + /* + * The status of the last operation. + */ + private ProvisioningState provisioningState; + + /** + * Creates an instance of AssessmentProjectUpdateProperties class. + */ + public AssessmentProjectUpdateProperties() { + } + + /** + * Get the assessmentSolutionId property: Assessment solution ARM id tracked by Microsoft.Migrate/migrateProjects. + * + * @return the assessmentSolutionId value. + */ + public String assessmentSolutionId() { + return this.assessmentSolutionId; + } + + /** + * Set the assessmentSolutionId property: Assessment solution ARM id tracked by Microsoft.Migrate/migrateProjects. + * + * @param assessmentSolutionId the assessmentSolutionId value to set. + * @return the AssessmentProjectUpdateProperties object itself. + */ + public AssessmentProjectUpdateProperties withAssessmentSolutionId(String assessmentSolutionId) { + this.assessmentSolutionId = assessmentSolutionId; + return this; + } + + /** + * Get the projectStatus property: Assessment project status. + * + * @return the projectStatus value. + */ + public ProjectStatus projectStatus() { + return this.projectStatus; + } + + /** + * Set the projectStatus property: Assessment project status. + * + * @param projectStatus the projectStatus value to set. + * @return the AssessmentProjectUpdateProperties object itself. + */ + public AssessmentProjectUpdateProperties withProjectStatus(ProjectStatus projectStatus) { + this.projectStatus = projectStatus; + return this; + } + + /** + * Get the customerWorkspaceId property: The ARM id of service map workspace created by customer. + * + * @return the customerWorkspaceId value. + */ + public String customerWorkspaceId() { + return this.customerWorkspaceId; + } + + /** + * Set the customerWorkspaceId property: The ARM id of service map workspace created by customer. + * + * @param customerWorkspaceId the customerWorkspaceId value to set. + * @return the AssessmentProjectUpdateProperties object itself. + */ + public AssessmentProjectUpdateProperties withCustomerWorkspaceId(String customerWorkspaceId) { + this.customerWorkspaceId = customerWorkspaceId; + return this; + } + + /** + * Get the customerWorkspaceLocation property: Location of service map workspace created by customer. + * + * @return the customerWorkspaceLocation value. + */ + public String customerWorkspaceLocation() { + return this.customerWorkspaceLocation; + } + + /** + * Set the customerWorkspaceLocation property: Location of service map workspace created by customer. + * + * @param customerWorkspaceLocation the customerWorkspaceLocation value to set. + * @return the AssessmentProjectUpdateProperties object itself. + */ + public AssessmentProjectUpdateProperties withCustomerWorkspaceLocation(String customerWorkspaceLocation) { + this.customerWorkspaceLocation = customerWorkspaceLocation; + return this; + } + + /** + * Get the publicNetworkAccess property: This value can be set to 'enabled' to avoid breaking changes on existing + * customer resources and templates. If set to 'disabled', traffic over public + * interface is not allowed, and private endpoint connections would be the + * exclusive access method. + * + * @return the publicNetworkAccess value. + */ + public String publicNetworkAccess() { + return this.publicNetworkAccess; + } + + /** + * Set the publicNetworkAccess property: This value can be set to 'enabled' to avoid breaking changes on existing + * customer resources and templates. If set to 'disabled', traffic over public + * interface is not allowed, and private endpoint connections would be the + * exclusive access method. + * + * @param publicNetworkAccess the publicNetworkAccess value to set. + * @return the AssessmentProjectUpdateProperties object itself. + */ + public AssessmentProjectUpdateProperties withPublicNetworkAccess(String publicNetworkAccess) { + this.publicNetworkAccess = publicNetworkAccess; + return this; + } + + /** + * Get the customerStorageAccountArmId property: The ARM id of the storage account used for interactions when public + * access is + * disabled. + * + * @return the customerStorageAccountArmId value. + */ + public String customerStorageAccountArmId() { + return this.customerStorageAccountArmId; + } + + /** + * Set the customerStorageAccountArmId property: The ARM id of the storage account used for interactions when public + * access is + * disabled. + * + * @param customerStorageAccountArmId the customerStorageAccountArmId value to set. + * @return the AssessmentProjectUpdateProperties object itself. + */ + public AssessmentProjectUpdateProperties withCustomerStorageAccountArmId(String customerStorageAccountArmId) { + this.customerStorageAccountArmId = customerStorageAccountArmId; + return this; + } + + /** + * Get the provisioningState property: The status of the last operation. + * + * @return the provisioningState value. + */ + public ProvisioningState provisioningState() { + return this.provisioningState; + } + + /** + * Set the provisioningState property: The status of the last operation. + * + * @param provisioningState the provisioningState value to set. + * @return the AssessmentProjectUpdateProperties object itself. + */ + public AssessmentProjectUpdateProperties withProvisioningState(ProvisioningState provisioningState) { + this.provisioningState = provisioningState; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("assessmentSolutionId", this.assessmentSolutionId); + jsonWriter.writeStringField("projectStatus", this.projectStatus == null ? null : this.projectStatus.toString()); + jsonWriter.writeStringField("customerWorkspaceId", this.customerWorkspaceId); + jsonWriter.writeStringField("customerWorkspaceLocation", this.customerWorkspaceLocation); + jsonWriter.writeStringField("publicNetworkAccess", this.publicNetworkAccess); + jsonWriter.writeStringField("customerStorageAccountArmId", this.customerStorageAccountArmId); + jsonWriter.writeStringField("provisioningState", + this.provisioningState == null ? null : this.provisioningState.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssessmentProjectUpdateProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssessmentProjectUpdateProperties 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 AssessmentProjectUpdateProperties. + */ + public static AssessmentProjectUpdateProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssessmentProjectUpdateProperties deserializedAssessmentProjectUpdateProperties + = new AssessmentProjectUpdateProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("assessmentSolutionId".equals(fieldName)) { + deserializedAssessmentProjectUpdateProperties.assessmentSolutionId = reader.getString(); + } else if ("projectStatus".equals(fieldName)) { + deserializedAssessmentProjectUpdateProperties.projectStatus + = ProjectStatus.fromString(reader.getString()); + } else if ("customerWorkspaceId".equals(fieldName)) { + deserializedAssessmentProjectUpdateProperties.customerWorkspaceId = reader.getString(); + } else if ("customerWorkspaceLocation".equals(fieldName)) { + deserializedAssessmentProjectUpdateProperties.customerWorkspaceLocation = reader.getString(); + } else if ("publicNetworkAccess".equals(fieldName)) { + deserializedAssessmentProjectUpdateProperties.publicNetworkAccess = reader.getString(); + } else if ("customerStorageAccountArmId".equals(fieldName)) { + deserializedAssessmentProjectUpdateProperties.customerStorageAccountArmId = reader.getString(); + } else if ("provisioningState".equals(fieldName)) { + deserializedAssessmentProjectUpdateProperties.provisioningState + = ProvisioningState.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedAssessmentProjectUpdateProperties; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentProjectsOperations.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentProjectsOperations.java new file mode 100644 index 000000000000..4c03e2524797 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentProjectsOperations.java @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of AssessmentProjectsOperations. + */ +public interface AssessmentProjectsOperations { + /** + * List AssessmentProject resources by subscription ID. + * + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProject list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable list(); + + /** + * List AssessmentProject resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProject list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable list(Context context); + + /** + * List AssessmentProject resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProject list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByResourceGroup(String resourceGroupName); + + /** + * List AssessmentProject resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AssessmentProject list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByResourceGroup(String resourceGroupName, Context context); + + /** + * Get a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessmentProject along with {@link Response}. + */ + Response getByResourceGroupWithResponse(String resourceGroupName, String projectName, + Context context); + + /** + * Get a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessmentProject. + */ + AssessmentProject getByResourceGroup(String resourceGroupName, String projectName); + + /** + * Delete a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteByResourceGroupWithResponse(String resourceGroupName, String projectName, Context context); + + /** + * Delete a AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteByResourceGroup(String resourceGroupName, String projectName); + + /** + * Get a AssessmentProject. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessmentProject along with {@link Response}. + */ + AssessmentProject getById(String id); + + /** + * Get a AssessmentProject. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AssessmentProject along with {@link Response}. + */ + Response getByIdWithResponse(String id, Context context); + + /** + * Delete a AssessmentProject. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteById(String id); + + /** + * Delete a AssessmentProject. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteByIdWithResponse(String id, Context context); + + /** + * Begins definition for a new AssessmentProject resource. + * + * @param name resource name. + * @return the first stage of the new AssessmentProject definition. + */ + AssessmentProject.DefinitionStages.Blank define(String name); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentSizingCriterion.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentSizingCriterion.java new file mode 100644 index 000000000000..1fc06a2ec9bd --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentSizingCriterion.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Assessment Sizing Criteria. + */ +public final class AssessmentSizingCriterion extends ExpandableStringEnum { + /** + * Static value PerformanceBased for AssessmentSizingCriterion. + */ + public static final AssessmentSizingCriterion PERFORMANCE_BASED = fromString("PerformanceBased"); + + /** + * Static value AsOnPremises for AssessmentSizingCriterion. + */ + public static final AssessmentSizingCriterion AS_ON_PREMISES = fromString("AsOnPremises"); + + /** + * Creates a new instance of AssessmentSizingCriterion value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AssessmentSizingCriterion() { + } + + /** + * Creates or finds a AssessmentSizingCriterion from its string representation. + * + * @param name a name to look for. + * @return the corresponding AssessmentSizingCriterion. + */ + public static AssessmentSizingCriterion fromString(String name) { + return fromString(name, AssessmentSizingCriterion.class); + } + + /** + * Gets known AssessmentSizingCriterion values. + * + * @return known AssessmentSizingCriterion values. + */ + public static Collection values() { + return values(AssessmentSizingCriterion.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentStage.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentStage.java new file mode 100644 index 000000000000..862757c89f72 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentStage.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. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AssessmentStage. + */ +public final class AssessmentStage extends ExpandableStringEnum { + /** + * Static value InProgress for AssessmentStage. + */ + public static final AssessmentStage IN_PROGRESS = fromString("InProgress"); + + /** + * Static value UnderReview for AssessmentStage. + */ + public static final AssessmentStage UNDER_REVIEW = fromString("UnderReview"); + + /** + * Static value Approved for AssessmentStage. + */ + public static final AssessmentStage APPROVED = fromString("Approved"); + + /** + * Creates a new instance of AssessmentStage value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AssessmentStage() { + } + + /** + * Creates or finds a AssessmentStage from its string representation. + * + * @param name a name to look for. + * @return the corresponding AssessmentStage. + */ + public static AssessmentStage fromString(String name) { + return fromString(name, AssessmentStage.class); + } + + /** + * Gets known AssessmentStage values. + * + * @return known AssessmentStage values. + */ + public static Collection values() { + return values(AssessmentStage.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentStatus.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentStatus.java new file mode 100644 index 000000000000..090934c77182 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentStatus.java @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Assessment Status. + */ +public final class AssessmentStatus extends ExpandableStringEnum { + /** + * Static value Created for AssessmentStatus. + */ + public static final AssessmentStatus CREATED = fromString("Created"); + + /** + * Static value Updated for AssessmentStatus. + */ + public static final AssessmentStatus UPDATED = fromString("Updated"); + + /** + * Static value Running for AssessmentStatus. + */ + public static final AssessmentStatus RUNNING = fromString("Running"); + + /** + * Static value Completed for AssessmentStatus. + */ + public static final AssessmentStatus COMPLETED = fromString("Completed"); + + /** + * Static value Invalid for AssessmentStatus. + */ + public static final AssessmentStatus INVALID = fromString("Invalid"); + + /** + * Static value OutOfSync for AssessmentStatus. + */ + public static final AssessmentStatus OUT_OF_SYNC = fromString("OutOfSync"); + + /** + * Static value OutDated for AssessmentStatus. + */ + public static final AssessmentStatus OUT_DATED = fromString("OutDated"); + + /** + * Static value Deleted for AssessmentStatus. + */ + public static final AssessmentStatus DELETED = fromString("Deleted"); + + /** + * Creates a new instance of AssessmentStatus value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AssessmentStatus() { + } + + /** + * Creates or finds a AssessmentStatus from its string representation. + * + * @param name a name to look for. + * @return the corresponding AssessmentStatus. + */ + public static AssessmentStatus fromString(String name) { + return fromString(name, AssessmentStatus.class); + } + + /** + * Gets known AssessmentStatus values. + * + * @return known AssessmentStatus values. + */ + public static Collection values() { + return values(AssessmentStatus.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentType.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentType.java new file mode 100644 index 000000000000..3c8c61549312 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentType.java @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AssessmentType. + */ +public final class AssessmentType extends ExpandableStringEnum { + /** + * Static value Unknown for AssessmentType. + */ + public static final AssessmentType UNKNOWN = fromString("Unknown"); + + /** + * Static value MachineAssessment for AssessmentType. + */ + public static final AssessmentType MACHINE_ASSESSMENT = fromString("MachineAssessment"); + + /** + * Static value AvsAssessment for AssessmentType. + */ + public static final AssessmentType AVS_ASSESSMENT = fromString("AvsAssessment"); + + /** + * Static value SqlAssessment for AssessmentType. + */ + public static final AssessmentType SQL_ASSESSMENT = fromString("SqlAssessment"); + + /** + * Static value WebAppAssessment for AssessmentType. + */ + public static final AssessmentType WEB_APP_ASSESSMENT = fromString("WebAppAssessment"); + + /** + * Creates a new instance of AssessmentType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AssessmentType() { + } + + /** + * Creates or finds a AssessmentType from its string representation. + * + * @param name a name to look for. + * @return the corresponding AssessmentType. + */ + public static AssessmentType fromString(String name) { + return fromString(name, AssessmentType.class); + } + + /** + * Gets known AssessmentType values. + * + * @return known AssessmentType values. + */ + public static Collection values() { + return values(AssessmentType.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentsOperations.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentsOperations.java new file mode 100644 index 000000000000..a0a13ba605c2 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AssessmentsOperations.java @@ -0,0 +1,191 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of AssessmentsOperations. + */ +public interface AssessmentsOperations { + /** + * List Assessment resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Assessment list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByGroup(String resourceGroupName, String projectName, String groupName); + + /** + * List Assessment resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Assessment list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByGroup(String resourceGroupName, String projectName, String groupName, + Context context); + + /** + * Get a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Assessment along with {@link Response}. + */ + Response getWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, Context context); + + /** + * Get a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Assessment. + */ + Assessment get(String resourceGroupName, String projectName, String groupName, String assessmentName); + + /** + * Delete a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, Context context); + + /** + * Delete a Assessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void delete(String resourceGroupName, String projectName, String groupName, String assessmentName); + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format. + */ + DownloadUrl downloadUrl(String resourceGroupName, String projectName, String groupName, String assessmentName, + Object body); + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName Machine Assessment ARM name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format. + */ + DownloadUrl downloadUrl(String resourceGroupName, String projectName, String groupName, String assessmentName, + Object body, Context context); + + /** + * Get a Assessment. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Assessment along with {@link Response}. + */ + Assessment getById(String id); + + /** + * Get a Assessment. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Assessment along with {@link Response}. + */ + Response getByIdWithResponse(String id, Context context); + + /** + * Delete a Assessment. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteById(String id); + + /** + * Delete a Assessment. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteByIdWithResponse(String id, Context context); + + /** + * Begins definition for a new Assessment resource. + * + * @param name resource name. + * @return the first stage of the new Assessment definition. + */ + Assessment.DefinitionStages.Blank define(String name); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AsyncCommitModeIntent.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AsyncCommitModeIntent.java new file mode 100644 index 000000000000..e85e5652e36d --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AsyncCommitModeIntent.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. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AsyncCommitModeIntent. + */ +public final class AsyncCommitModeIntent extends ExpandableStringEnum { + /** + * Static value None for AsyncCommitModeIntent. + */ + public static final AsyncCommitModeIntent NONE = fromString("None"); + + /** + * Static value HighAvailability for AsyncCommitModeIntent. + */ + public static final AsyncCommitModeIntent HIGH_AVAILABILITY = fromString("HighAvailability"); + + /** + * Static value DisasterRecovery for AsyncCommitModeIntent. + */ + public static final AsyncCommitModeIntent DISASTER_RECOVERY = fromString("DisasterRecovery"); + + /** + * Creates a new instance of AsyncCommitModeIntent value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AsyncCommitModeIntent() { + } + + /** + * Creates or finds a AsyncCommitModeIntent from its string representation. + * + * @param name a name to look for. + * @return the corresponding AsyncCommitModeIntent. + */ + public static AsyncCommitModeIntent fromString(String name) { + return fromString(name, AsyncCommitModeIntent.class); + } + + /** + * Gets known AsyncCommitModeIntent values. + * + * @return known AsyncCommitModeIntent values. + */ + public static Collection values() { + return values(AsyncCommitModeIntent.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessedDisk.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessedDisk.java new file mode 100644 index 000000000000..9ffdeb72f89c --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessedDisk.java @@ -0,0 +1,179 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * AVS assessed disk web model class. + */ +@Immutable +public final class AvsAssessedDisk implements JsonSerializable { + /* + * Gets the ID of the disk. + */ + private String name; + + /* + * Gets the display name of the disk. + */ + private String displayName; + + /* + * Gigabytes Provisioned for a disk in private data center. + */ + private Float gigabytesProvisioned; + + /* + * Disk Read Throughput in MB/s. + */ + private Float megabytesPerSecondOfRead; + + /* + * Disk Write Throughput in MB/s. + */ + private Float megabytesPerSecondOfWrite; + + /* + * Read Operations per second. + */ + private Float numberOfReadOperationsPerSecond; + + /* + * Write Operations per second. + */ + private Float numberOfWriteOperationsPerSecond; + + /** + * Creates an instance of AvsAssessedDisk class. + */ + public AvsAssessedDisk() { + } + + /** + * Get the name property: Gets the ID of the disk. + * + * @return the name value. + */ + public String name() { + return this.name; + } + + /** + * Get the displayName property: Gets the display name of the disk. + * + * @return the displayName value. + */ + public String displayName() { + return this.displayName; + } + + /** + * Get the gigabytesProvisioned property: Gigabytes Provisioned for a disk in private data center. + * + * @return the gigabytesProvisioned value. + */ + public Float gigabytesProvisioned() { + return this.gigabytesProvisioned; + } + + /** + * Get the megabytesPerSecondOfRead property: Disk Read Throughput in MB/s. + * + * @return the megabytesPerSecondOfRead value. + */ + public Float megabytesPerSecondOfRead() { + return this.megabytesPerSecondOfRead; + } + + /** + * Get the megabytesPerSecondOfWrite property: Disk Write Throughput in MB/s. + * + * @return the megabytesPerSecondOfWrite value. + */ + public Float megabytesPerSecondOfWrite() { + return this.megabytesPerSecondOfWrite; + } + + /** + * Get the numberOfReadOperationsPerSecond property: Read Operations per second. + * + * @return the numberOfReadOperationsPerSecond value. + */ + public Float numberOfReadOperationsPerSecond() { + return this.numberOfReadOperationsPerSecond; + } + + /** + * Get the numberOfWriteOperationsPerSecond property: Write Operations per second. + * + * @return the numberOfWriteOperationsPerSecond value. + */ + public Float numberOfWriteOperationsPerSecond() { + return this.numberOfWriteOperationsPerSecond; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AvsAssessedDisk from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AvsAssessedDisk 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 AvsAssessedDisk. + */ + public static AvsAssessedDisk fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AvsAssessedDisk deserializedAvsAssessedDisk = new AvsAssessedDisk(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("name".equals(fieldName)) { + deserializedAvsAssessedDisk.name = reader.getString(); + } else if ("displayName".equals(fieldName)) { + deserializedAvsAssessedDisk.displayName = reader.getString(); + } else if ("gigabytesProvisioned".equals(fieldName)) { + deserializedAvsAssessedDisk.gigabytesProvisioned = reader.getNullable(JsonReader::getFloat); + } else if ("megabytesPerSecondOfRead".equals(fieldName)) { + deserializedAvsAssessedDisk.megabytesPerSecondOfRead = reader.getNullable(JsonReader::getFloat); + } else if ("megabytesPerSecondOfWrite".equals(fieldName)) { + deserializedAvsAssessedDisk.megabytesPerSecondOfWrite = reader.getNullable(JsonReader::getFloat); + } else if ("numberOfReadOperationsPerSecond".equals(fieldName)) { + deserializedAvsAssessedDisk.numberOfReadOperationsPerSecond + = reader.getNullable(JsonReader::getFloat); + } else if ("numberOfWriteOperationsPerSecond".equals(fieldName)) { + deserializedAvsAssessedDisk.numberOfWriteOperationsPerSecond + = reader.getNullable(JsonReader::getFloat); + } else { + reader.skipChildren(); + } + } + + return deserializedAvsAssessedDisk; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessedMachine.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessedMachine.java new file mode 100644 index 000000000000..3d1507001f14 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessedMachine.java @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AvsAssessedMachineInner; + +/** + * An immutable client-side representation of AvsAssessedMachine. + */ +public interface AvsAssessedMachine { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + AvsAssessedMachineProperties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.migration.assessment.fluent.models.AvsAssessedMachineInner object. + * + * @return the inner object. + */ + AvsAssessedMachineInner innerModel(); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessedMachineListResult.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessedMachineListResult.java new file mode 100644 index 000000000000..f1a418ea5c51 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessedMachineListResult.java @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.fluent.models.AvsAssessedMachineInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a AvsAssessedMachine list operation. + */ +@Fluent +public final class AvsAssessedMachineListResult implements JsonSerializable { + /* + * The AvsAssessedMachine items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of AvsAssessedMachineListResult class. + */ + public AvsAssessedMachineListResult() { + } + + /** + * Get the value property: The AvsAssessedMachine items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Set the value property: The AvsAssessedMachine items on this page. + * + * @param value the value value to set. + * @return the AvsAssessedMachineListResult object itself. + */ + public AvsAssessedMachineListResult withValue(List value) { + this.value = value; + return this; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The link to the next page of items. + * + * @param nextLink the nextLink value to set. + * @return the AvsAssessedMachineListResult object itself. + */ + public AvsAssessedMachineListResult withNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property value in model AvsAssessedMachineListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(AvsAssessedMachineListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AvsAssessedMachineListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AvsAssessedMachineListResult 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 AvsAssessedMachineListResult. + */ + public static AvsAssessedMachineListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AvsAssessedMachineListResult deserializedAvsAssessedMachineListResult = new AvsAssessedMachineListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> AvsAssessedMachineInner.fromJson(reader1)); + deserializedAvsAssessedMachineListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedAvsAssessedMachineListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAvsAssessedMachineListResult; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessedMachineProperties.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessedMachineProperties.java new file mode 100644 index 000000000000..fc978a354155 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessedMachineProperties.java @@ -0,0 +1,515 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.util.List; +import java.util.Map; + +/** + * AVS assessed machine properties web model. + */ +@Immutable +public final class AvsAssessedMachineProperties implements JsonSerializable { + /* + * List of errors for this machine. + */ + private List errors; + + /* + * List of Disks that were assessed as part of this machine's assessment. + */ + private Map disks; + + /* + * List of Network Adapters that were assessed as part of this machine's + * assessment. + */ + private Map networkAdapters; + + /* + * Gets the storage in use. + */ + private Float storageInUseGB; + + /* + * Gets the explanation if machine is not suitable for cloud. + */ + private AzureAvsVmSuitabilityExplanation suitabilityExplanation; + + /* + * Gets the details if machine is not suitable for cloud. + */ + private AzureAvsVmSuitabilityDetail suitabilityDetail; + + /* + * Assessed machine type. + */ + private AssessedMachineType type; + + /* + * Boot type of machine discovered in private data center. + */ + private MachineBootType bootType; + + /* + * Operating system as reported by datacenter management solution. + */ + private String operatingSystemType; + + /* + * Operating system as reported by datacenter management solution. + */ + private String operatingSystemName; + + /* + * Operating system version as reported by datacenter management solution. + */ + private String operatingSystemVersion; + + /* + * Operating system architecture as reported by datacenter management solution. + */ + private GuestOperatingSystemArchitecture operatingSystemArchitecture; + + /* + * When was machine first created. + */ + private OffsetDateTime createdTimestamp; + + /* + * When was machine last updated. + */ + private OffsetDateTime updatedTimestamp; + + /* + * Display Name of the Machine. + */ + private String displayName; + + /* + * Description for the machine. + */ + private String description; + + /* + * Data center machine ARM id. + */ + private String datacenterMachineArmId; + + /* + * Data center management server ARM id. + */ + private String datacenterManagementServerArmId; + + /* + * Data center management server name. + */ + private String datacenterManagementServerName; + + /* + * Megabytes of memory found allocated for the machine in private data center. + */ + private Float megabytesOfMemory; + + /* + * Number of CPU cores found on the machine. + */ + private Integer numberOfCores; + + /* + * Confidence Rating in Percentage. + */ + private Float confidenceRatingInPercentage; + + /* + * Percentile of Percentage of Cores Utilized noted during time period T. + * + * Here N and T are settings on Assessment. + */ + private Float percentageCoresUtilization; + + /* + * Percentile of Percentage of Memory Utilized noted during time period T. + * + * Here N and T are settings on Assessment. + */ + private Float percentageMemoryUtilization; + + /* + * Gets a value indicating whether machine is suitable for the cloud platform + * selected. + */ + private CloudSuitability suitability; + + /** + * Creates an instance of AvsAssessedMachineProperties class. + */ + public AvsAssessedMachineProperties() { + } + + /** + * Get the errors property: List of errors for this machine. + * + * @return the errors value. + */ + public List errors() { + return this.errors; + } + + /** + * Get the disks property: List of Disks that were assessed as part of this machine's assessment. + * + * @return the disks value. + */ + public Map disks() { + return this.disks; + } + + /** + * Get the networkAdapters property: List of Network Adapters that were assessed as part of this machine's + * assessment. + * + * @return the networkAdapters value. + */ + public Map networkAdapters() { + return this.networkAdapters; + } + + /** + * Get the storageInUseGB property: Gets the storage in use. + * + * @return the storageInUseGB value. + */ + public Float storageInUseGB() { + return this.storageInUseGB; + } + + /** + * Get the suitabilityExplanation property: Gets the explanation if machine is not suitable for cloud. + * + * @return the suitabilityExplanation value. + */ + public AzureAvsVmSuitabilityExplanation suitabilityExplanation() { + return this.suitabilityExplanation; + } + + /** + * Get the suitabilityDetail property: Gets the details if machine is not suitable for cloud. + * + * @return the suitabilityDetail value. + */ + public AzureAvsVmSuitabilityDetail suitabilityDetail() { + return this.suitabilityDetail; + } + + /** + * Get the type property: Assessed machine type. + * + * @return the type value. + */ + public AssessedMachineType type() { + return this.type; + } + + /** + * Get the bootType property: Boot type of machine discovered in private data center. + * + * @return the bootType value. + */ + public MachineBootType bootType() { + return this.bootType; + } + + /** + * Get the operatingSystemType property: Operating system as reported by datacenter management solution. + * + * @return the operatingSystemType value. + */ + public String operatingSystemType() { + return this.operatingSystemType; + } + + /** + * Get the operatingSystemName property: Operating system as reported by datacenter management solution. + * + * @return the operatingSystemName value. + */ + public String operatingSystemName() { + return this.operatingSystemName; + } + + /** + * Get the operatingSystemVersion property: Operating system version as reported by datacenter management solution. + * + * @return the operatingSystemVersion value. + */ + public String operatingSystemVersion() { + return this.operatingSystemVersion; + } + + /** + * Get the operatingSystemArchitecture property: Operating system architecture as reported by datacenter management + * solution. + * + * @return the operatingSystemArchitecture value. + */ + public GuestOperatingSystemArchitecture operatingSystemArchitecture() { + return this.operatingSystemArchitecture; + } + + /** + * Get the createdTimestamp property: When was machine first created. + * + * @return the createdTimestamp value. + */ + public OffsetDateTime createdTimestamp() { + return this.createdTimestamp; + } + + /** + * Get the updatedTimestamp property: When was machine last updated. + * + * @return the updatedTimestamp value. + */ + public OffsetDateTime updatedTimestamp() { + return this.updatedTimestamp; + } + + /** + * Get the displayName property: Display Name of the Machine. + * + * @return the displayName value. + */ + public String displayName() { + return this.displayName; + } + + /** + * Get the description property: Description for the machine. + * + * @return the description value. + */ + public String description() { + return this.description; + } + + /** + * Get the datacenterMachineArmId property: Data center machine ARM id. + * + * @return the datacenterMachineArmId value. + */ + public String datacenterMachineArmId() { + return this.datacenterMachineArmId; + } + + /** + * Get the datacenterManagementServerArmId property: Data center management server ARM id. + * + * @return the datacenterManagementServerArmId value. + */ + public String datacenterManagementServerArmId() { + return this.datacenterManagementServerArmId; + } + + /** + * Get the datacenterManagementServerName property: Data center management server name. + * + * @return the datacenterManagementServerName value. + */ + public String datacenterManagementServerName() { + return this.datacenterManagementServerName; + } + + /** + * Get the megabytesOfMemory property: Megabytes of memory found allocated for the machine in private data center. + * + * @return the megabytesOfMemory value. + */ + public Float megabytesOfMemory() { + return this.megabytesOfMemory; + } + + /** + * Get the numberOfCores property: Number of CPU cores found on the machine. + * + * @return the numberOfCores value. + */ + public Integer numberOfCores() { + return this.numberOfCores; + } + + /** + * Get the confidenceRatingInPercentage property: Confidence Rating in Percentage. + * + * @return the confidenceRatingInPercentage value. + */ + public Float confidenceRatingInPercentage() { + return this.confidenceRatingInPercentage; + } + + /** + * Get the percentageCoresUtilization property: Percentile of Percentage of Cores Utilized noted during time period + * T. + * + * Here N and T are settings on Assessment. + * + * @return the percentageCoresUtilization value. + */ + public Float percentageCoresUtilization() { + return this.percentageCoresUtilization; + } + + /** + * Get the percentageMemoryUtilization property: Percentile of Percentage of Memory Utilized noted during time + * period T. + * + * Here N and T are settings on Assessment. + * + * @return the percentageMemoryUtilization value. + */ + public Float percentageMemoryUtilization() { + return this.percentageMemoryUtilization; + } + + /** + * Get the suitability property: Gets a value indicating whether machine is suitable for the cloud platform + * selected. + * + * @return the suitability value. + */ + public CloudSuitability suitability() { + return this.suitability; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (errors() != null) { + errors().forEach(e -> e.validate()); + } + if (disks() != null) { + disks().values().forEach(e -> { + if (e != null) { + e.validate(); + } + }); + } + if (networkAdapters() != null) { + networkAdapters().values().forEach(e -> { + if (e != null) { + e.validate(); + } + }); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AvsAssessedMachineProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AvsAssessedMachineProperties 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 AvsAssessedMachineProperties. + */ + public static AvsAssessedMachineProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AvsAssessedMachineProperties deserializedAvsAssessedMachineProperties = new AvsAssessedMachineProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("errors".equals(fieldName)) { + List errors = reader.readArray(reader1 -> Error.fromJson(reader1)); + deserializedAvsAssessedMachineProperties.errors = errors; + } else if ("disks".equals(fieldName)) { + Map disks = reader.readMap(reader1 -> AvsAssessedDisk.fromJson(reader1)); + deserializedAvsAssessedMachineProperties.disks = disks; + } else if ("networkAdapters".equals(fieldName)) { + Map networkAdapters + = reader.readMap(reader1 -> AvsAssessedNetworkAdapter.fromJson(reader1)); + deserializedAvsAssessedMachineProperties.networkAdapters = networkAdapters; + } else if ("storageInUseGB".equals(fieldName)) { + deserializedAvsAssessedMachineProperties.storageInUseGB = reader.getNullable(JsonReader::getFloat); + } else if ("suitabilityExplanation".equals(fieldName)) { + deserializedAvsAssessedMachineProperties.suitabilityExplanation + = AzureAvsVmSuitabilityExplanation.fromString(reader.getString()); + } else if ("suitabilityDetail".equals(fieldName)) { + deserializedAvsAssessedMachineProperties.suitabilityDetail + = AzureAvsVmSuitabilityDetail.fromString(reader.getString()); + } else if ("type".equals(fieldName)) { + deserializedAvsAssessedMachineProperties.type = AssessedMachineType.fromString(reader.getString()); + } else if ("bootType".equals(fieldName)) { + deserializedAvsAssessedMachineProperties.bootType = MachineBootType.fromString(reader.getString()); + } else if ("operatingSystemType".equals(fieldName)) { + deserializedAvsAssessedMachineProperties.operatingSystemType = reader.getString(); + } else if ("operatingSystemName".equals(fieldName)) { + deserializedAvsAssessedMachineProperties.operatingSystemName = reader.getString(); + } else if ("operatingSystemVersion".equals(fieldName)) { + deserializedAvsAssessedMachineProperties.operatingSystemVersion = reader.getString(); + } else if ("operatingSystemArchitecture".equals(fieldName)) { + deserializedAvsAssessedMachineProperties.operatingSystemArchitecture + = GuestOperatingSystemArchitecture.fromString(reader.getString()); + } else if ("createdTimestamp".equals(fieldName)) { + deserializedAvsAssessedMachineProperties.createdTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("updatedTimestamp".equals(fieldName)) { + deserializedAvsAssessedMachineProperties.updatedTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("displayName".equals(fieldName)) { + deserializedAvsAssessedMachineProperties.displayName = reader.getString(); + } else if ("description".equals(fieldName)) { + deserializedAvsAssessedMachineProperties.description = reader.getString(); + } else if ("datacenterMachineArmId".equals(fieldName)) { + deserializedAvsAssessedMachineProperties.datacenterMachineArmId = reader.getString(); + } else if ("datacenterManagementServerArmId".equals(fieldName)) { + deserializedAvsAssessedMachineProperties.datacenterManagementServerArmId = reader.getString(); + } else if ("datacenterManagementServerName".equals(fieldName)) { + deserializedAvsAssessedMachineProperties.datacenterManagementServerName = reader.getString(); + } else if ("megabytesOfMemory".equals(fieldName)) { + deserializedAvsAssessedMachineProperties.megabytesOfMemory + = reader.getNullable(JsonReader::getFloat); + } else if ("numberOfCores".equals(fieldName)) { + deserializedAvsAssessedMachineProperties.numberOfCores = reader.getNullable(JsonReader::getInt); + } else if ("confidenceRatingInPercentage".equals(fieldName)) { + deserializedAvsAssessedMachineProperties.confidenceRatingInPercentage + = reader.getNullable(JsonReader::getFloat); + } else if ("percentageCoresUtilization".equals(fieldName)) { + deserializedAvsAssessedMachineProperties.percentageCoresUtilization + = reader.getNullable(JsonReader::getFloat); + } else if ("percentageMemoryUtilization".equals(fieldName)) { + deserializedAvsAssessedMachineProperties.percentageMemoryUtilization + = reader.getNullable(JsonReader::getFloat); + } else if ("suitability".equals(fieldName)) { + deserializedAvsAssessedMachineProperties.suitability + = CloudSuitability.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedAvsAssessedMachineProperties; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessedMachinesOperations.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessedMachinesOperations.java new file mode 100644 index 000000000000..bd3c851a9e5b --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessedMachinesOperations.java @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of AvsAssessedMachinesOperations. + */ +public interface AvsAssessedMachinesOperations { + /** + * List AvsAssessedMachine resources by AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessedMachine list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByAvsAssessment(String resourceGroupName, String projectName, + String groupName, String assessmentName); + + /** + * List AvsAssessedMachine resources by AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessedMachine list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByAvsAssessment(String resourceGroupName, String projectName, + String groupName, String assessmentName, String filter, Integer pageSize, String continuationToken, + Integer totalRecordCount, Context context); + + /** + * Get a AvsAssessedMachine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param avsAssessedMachineName AVS assessment Assessed Machine ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AvsAssessedMachine along with {@link Response}. + */ + Response getWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, String avsAssessedMachineName, Context context); + + /** + * Get a AvsAssessedMachine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param avsAssessedMachineName AVS assessment Assessed Machine ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AvsAssessedMachine. + */ + AvsAssessedMachine get(String resourceGroupName, String projectName, String groupName, String assessmentName, + String avsAssessedMachineName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessedNetworkAdapter.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessedNetworkAdapter.java new file mode 100644 index 000000000000..943ba7143a6d --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessedNetworkAdapter.java @@ -0,0 +1,157 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; +import java.util.List; + +/** + * Second level object returned as part of AVS AssessedMachine REST resource. + */ +@Immutable +public final class AvsAssessedNetworkAdapter implements JsonSerializable { + /* + * Mac address of the NIC. + */ + private String macAddress; + + /* + * IP V4 addresses for the machine. + */ + private List ipAddresses; + + /* + * Gets the display name of the network adapter. + */ + private String displayName; + + /* + * Gets the Received data for Network Adapter in MB/s. + * This value is + * the percentile of historical data based on options selected in Assessment. + */ + private Float megabytesPerSecondReceived; + + /* + * Gets the Transmitted data for Network Adapter in MB/s. + * This value + * is the percentile of historical data based on options selected in Assessment. + */ + private Float megabytesPerSecondTransmitted; + + /** + * Creates an instance of AvsAssessedNetworkAdapter class. + */ + public AvsAssessedNetworkAdapter() { + } + + /** + * Get the macAddress property: Mac address of the NIC. + * + * @return the macAddress value. + */ + public String macAddress() { + return this.macAddress; + } + + /** + * Get the ipAddresses property: IP V4 addresses for the machine. + * + * @return the ipAddresses value. + */ + public List ipAddresses() { + return this.ipAddresses; + } + + /** + * Get the displayName property: Gets the display name of the network adapter. + * + * @return the displayName value. + */ + public String displayName() { + return this.displayName; + } + + /** + * Get the megabytesPerSecondReceived property: Gets the Received data for Network Adapter in MB/s. + * This value is + * the percentile of historical data based on options selected in Assessment. + * + * @return the megabytesPerSecondReceived value. + */ + public Float megabytesPerSecondReceived() { + return this.megabytesPerSecondReceived; + } + + /** + * Get the megabytesPerSecondTransmitted property: Gets the Transmitted data for Network Adapter in MB/s. + * This value + * is the percentile of historical data based on options selected in Assessment. + * + * @return the megabytesPerSecondTransmitted value. + */ + public Float megabytesPerSecondTransmitted() { + return this.megabytesPerSecondTransmitted; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AvsAssessedNetworkAdapter from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AvsAssessedNetworkAdapter 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 AvsAssessedNetworkAdapter. + */ + public static AvsAssessedNetworkAdapter fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AvsAssessedNetworkAdapter deserializedAvsAssessedNetworkAdapter = new AvsAssessedNetworkAdapter(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("macAddress".equals(fieldName)) { + deserializedAvsAssessedNetworkAdapter.macAddress = reader.getString(); + } else if ("ipAddresses".equals(fieldName)) { + List ipAddresses = reader.readArray(reader1 -> reader1.getString()); + deserializedAvsAssessedNetworkAdapter.ipAddresses = ipAddresses; + } else if ("displayName".equals(fieldName)) { + deserializedAvsAssessedNetworkAdapter.displayName = reader.getString(); + } else if ("megabytesPerSecondReceived".equals(fieldName)) { + deserializedAvsAssessedNetworkAdapter.megabytesPerSecondReceived + = reader.getNullable(JsonReader::getFloat); + } else if ("megabytesPerSecondTransmitted".equals(fieldName)) { + deserializedAvsAssessedNetworkAdapter.megabytesPerSecondTransmitted + = reader.getNullable(JsonReader::getFloat); + } else { + reader.skipChildren(); + } + } + + return deserializedAvsAssessedNetworkAdapter; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessment.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessment.java new file mode 100644 index 000000000000..bdb23b54d28e --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessment.java @@ -0,0 +1,165 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.AvsAssessmentInner; + +/** + * An immutable client-side representation of AvsAssessment. + */ +public interface AvsAssessment { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + AvsAssessmentProperties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.migration.assessment.fluent.models.AvsAssessmentInner object. + * + * @return the inner object. + */ + AvsAssessmentInner innerModel(); + + /** + * The entirety of the AvsAssessment definition. + */ + interface Definition + extends DefinitionStages.Blank, DefinitionStages.WithParentResource, DefinitionStages.WithCreate { + } + + /** + * The AvsAssessment definition stages. + */ + interface DefinitionStages { + /** + * The first stage of the AvsAssessment definition. + */ + interface Blank extends WithParentResource { + } + + /** + * The stage of the AvsAssessment definition allowing to specify parent resource. + */ + interface WithParentResource { + /** + * Specifies resourceGroupName, projectName, groupName. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @return the next definition stage. + */ + WithCreate withExistingGroup(String resourceGroupName, String projectName, String groupName); + } + + /** + * The stage of the AvsAssessment definition which contains all the minimum required properties for the resource + * to be created, but also allows for any other optional properties to be specified. + */ + interface WithCreate extends DefinitionStages.WithProperties { + /** + * Executes the create request. + * + * @return the created resource. + */ + AvsAssessment create(); + + /** + * Executes the create request. + * + * @param context The context to associate with this operation. + * @return the created resource. + */ + AvsAssessment create(Context context); + } + + /** + * The stage of the AvsAssessment definition allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The resource-specific properties for this resource.. + * + * @param properties The resource-specific properties for this resource. + * @return the next definition stage. + */ + WithCreate withProperties(AvsAssessmentProperties properties); + } + } + + /** + * Refreshes the resource to sync with Azure. + * + * @return the refreshed resource. + */ + AvsAssessment refresh(); + + /** + * Refreshes the resource to sync with Azure. + * + * @param context The context to associate with this operation. + * @return the refreshed resource. + */ + AvsAssessment refresh(Context context); + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format. + */ + DownloadUrl downloadUrl(Object body); + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format. + */ + DownloadUrl downloadUrl(Object body, Context context); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessmentListResult.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessmentListResult.java new file mode 100644 index 000000000000..a9914ff9b730 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessmentListResult.java @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.fluent.models.AvsAssessmentInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a AvsAssessment list operation. + */ +@Fluent +public final class AvsAssessmentListResult implements JsonSerializable { + /* + * The AvsAssessment items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of AvsAssessmentListResult class. + */ + public AvsAssessmentListResult() { + } + + /** + * Get the value property: The AvsAssessment items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Set the value property: The AvsAssessment items on this page. + * + * @param value the value value to set. + * @return the AvsAssessmentListResult object itself. + */ + public AvsAssessmentListResult withValue(List value) { + this.value = value; + return this; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The link to the next page of items. + * + * @param nextLink the nextLink value to set. + * @return the AvsAssessmentListResult object itself. + */ + public AvsAssessmentListResult withNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property value in model AvsAssessmentListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(AvsAssessmentListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AvsAssessmentListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AvsAssessmentListResult 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 AvsAssessmentListResult. + */ + public static AvsAssessmentListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AvsAssessmentListResult deserializedAvsAssessmentListResult = new AvsAssessmentListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value = reader.readArray(reader1 -> AvsAssessmentInner.fromJson(reader1)); + deserializedAvsAssessmentListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedAvsAssessmentListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAvsAssessmentListResult; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessmentOptions.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessmentOptions.java new file mode 100644 index 000000000000..fb95db57bb8e --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessmentOptions.java @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AvsAssessmentOptionsInner; + +/** + * An immutable client-side representation of AvsAssessmentOptions. + */ +public interface AvsAssessmentOptions { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + AvsAssessmentOptionsProperties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.migration.assessment.fluent.models.AvsAssessmentOptionsInner object. + * + * @return the inner object. + */ + AvsAssessmentOptionsInner innerModel(); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessmentOptionsListResult.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessmentOptionsListResult.java new file mode 100644 index 000000000000..507d5b352d57 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessmentOptionsListResult.java @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.fluent.models.AvsAssessmentOptionsInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a AvsAssessmentOptions list operation. + */ +@Fluent +public final class AvsAssessmentOptionsListResult implements JsonSerializable { + /* + * The AvsAssessmentOptions items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of AvsAssessmentOptionsListResult class. + */ + public AvsAssessmentOptionsListResult() { + } + + /** + * Get the value property: The AvsAssessmentOptions items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Set the value property: The AvsAssessmentOptions items on this page. + * + * @param value the value value to set. + * @return the AvsAssessmentOptionsListResult object itself. + */ + public AvsAssessmentOptionsListResult withValue(List value) { + this.value = value; + return this; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The link to the next page of items. + * + * @param nextLink the nextLink value to set. + * @return the AvsAssessmentOptionsListResult object itself. + */ + public AvsAssessmentOptionsListResult withNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property value in model AvsAssessmentOptionsListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(AvsAssessmentOptionsListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AvsAssessmentOptionsListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AvsAssessmentOptionsListResult 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 AvsAssessmentOptionsListResult. + */ + public static AvsAssessmentOptionsListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AvsAssessmentOptionsListResult deserializedAvsAssessmentOptionsListResult + = new AvsAssessmentOptionsListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> AvsAssessmentOptionsInner.fromJson(reader1)); + deserializedAvsAssessmentOptionsListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedAvsAssessmentOptionsListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAvsAssessmentOptionsListResult; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessmentOptionsOperations.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessmentOptionsOperations.java new file mode 100644 index 000000000000..4b32288da733 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessmentOptionsOperations.java @@ -0,0 +1,68 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of AvsAssessmentOptionsOperations. + */ +public interface AvsAssessmentOptionsOperations { + /** + * List AvsAssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessmentOptions list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName); + + /** + * List AvsAssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessmentOptions list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context); + + /** + * Get a AvsAssessmentOptions. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param avsAssessmentOptionsName AVS Assessment options ARM name. Accepted value is 'default'. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AvsAssessmentOptions along with {@link Response}. + */ + Response getWithResponse(String resourceGroupName, String projectName, + String avsAssessmentOptionsName, Context context); + + /** + * Get a AvsAssessmentOptions. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param avsAssessmentOptionsName AVS Assessment options ARM name. Accepted value is 'default'. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AvsAssessmentOptions. + */ + AvsAssessmentOptions get(String resourceGroupName, String projectName, String avsAssessmentOptionsName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessmentOptionsProperties.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessmentOptionsProperties.java new file mode 100644 index 000000000000..86f8015a0bdd --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessmentOptionsProperties.java @@ -0,0 +1,263 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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.List; + +/** + * AVS Assessment options properties. + */ +@Fluent +public final class AvsAssessmentOptionsProperties implements JsonSerializable { + /* + * AVS SKU Nodes. + */ + private List avsNodes; + + /* + * FTT and Raid level values. + */ + private List failuresToTolerateAndRaidLevelValues; + + /* + * List of AVS nodes for RI. + */ + private List reservedInstanceAvsNodes; + + /* + * List of supported Azure regions for reserved instances. + */ + private List reservedInstanceSupportedLocations; + + /* + * List of supported currencies for reserved instances. + */ + private List reservedInstanceSupportedCurrencies; + + /* + * List of supported Azure offer codes for reserved instances. + */ + private List reservedInstanceSupportedOffers; + + /** + * Creates an instance of AvsAssessmentOptionsProperties class. + */ + public AvsAssessmentOptionsProperties() { + } + + /** + * Get the avsNodes property: AVS SKU Nodes. + * + * @return the avsNodes value. + */ + public List avsNodes() { + return this.avsNodes; + } + + /** + * Set the avsNodes property: AVS SKU Nodes. + * + * @param avsNodes the avsNodes value to set. + * @return the AvsAssessmentOptionsProperties object itself. + */ + public AvsAssessmentOptionsProperties withAvsNodes(List avsNodes) { + this.avsNodes = avsNodes; + return this; + } + + /** + * Get the failuresToTolerateAndRaidLevelValues property: FTT and Raid level values. + * + * @return the failuresToTolerateAndRaidLevelValues value. + */ + public List failuresToTolerateAndRaidLevelValues() { + return this.failuresToTolerateAndRaidLevelValues; + } + + /** + * Set the failuresToTolerateAndRaidLevelValues property: FTT and Raid level values. + * + * @param failuresToTolerateAndRaidLevelValues the failuresToTolerateAndRaidLevelValues value to set. + * @return the AvsAssessmentOptionsProperties object itself. + */ + public AvsAssessmentOptionsProperties + withFailuresToTolerateAndRaidLevelValues(List failuresToTolerateAndRaidLevelValues) { + this.failuresToTolerateAndRaidLevelValues = failuresToTolerateAndRaidLevelValues; + return this; + } + + /** + * Get the reservedInstanceAvsNodes property: List of AVS nodes for RI. + * + * @return the reservedInstanceAvsNodes value. + */ + public List reservedInstanceAvsNodes() { + return this.reservedInstanceAvsNodes; + } + + /** + * Set the reservedInstanceAvsNodes property: List of AVS nodes for RI. + * + * @param reservedInstanceAvsNodes the reservedInstanceAvsNodes value to set. + * @return the AvsAssessmentOptionsProperties object itself. + */ + public AvsAssessmentOptionsProperties + withReservedInstanceAvsNodes(List reservedInstanceAvsNodes) { + this.reservedInstanceAvsNodes = reservedInstanceAvsNodes; + return this; + } + + /** + * Get the reservedInstanceSupportedLocations property: List of supported Azure regions for reserved instances. + * + * @return the reservedInstanceSupportedLocations value. + */ + public List reservedInstanceSupportedLocations() { + return this.reservedInstanceSupportedLocations; + } + + /** + * Set the reservedInstanceSupportedLocations property: List of supported Azure regions for reserved instances. + * + * @param reservedInstanceSupportedLocations the reservedInstanceSupportedLocations value to set. + * @return the AvsAssessmentOptionsProperties object itself. + */ + public AvsAssessmentOptionsProperties + withReservedInstanceSupportedLocations(List reservedInstanceSupportedLocations) { + this.reservedInstanceSupportedLocations = reservedInstanceSupportedLocations; + return this; + } + + /** + * Get the reservedInstanceSupportedCurrencies property: List of supported currencies for reserved instances. + * + * @return the reservedInstanceSupportedCurrencies value. + */ + public List reservedInstanceSupportedCurrencies() { + return this.reservedInstanceSupportedCurrencies; + } + + /** + * Set the reservedInstanceSupportedCurrencies property: List of supported currencies for reserved instances. + * + * @param reservedInstanceSupportedCurrencies the reservedInstanceSupportedCurrencies value to set. + * @return the AvsAssessmentOptionsProperties object itself. + */ + public AvsAssessmentOptionsProperties + withReservedInstanceSupportedCurrencies(List reservedInstanceSupportedCurrencies) { + this.reservedInstanceSupportedCurrencies = reservedInstanceSupportedCurrencies; + return this; + } + + /** + * Get the reservedInstanceSupportedOffers property: List of supported Azure offer codes for reserved instances. + * + * @return the reservedInstanceSupportedOffers value. + */ + public List reservedInstanceSupportedOffers() { + return this.reservedInstanceSupportedOffers; + } + + /** + * Set the reservedInstanceSupportedOffers property: List of supported Azure offer codes for reserved instances. + * + * @param reservedInstanceSupportedOffers the reservedInstanceSupportedOffers value to set. + * @return the AvsAssessmentOptionsProperties object itself. + */ + public AvsAssessmentOptionsProperties + withReservedInstanceSupportedOffers(List reservedInstanceSupportedOffers) { + this.reservedInstanceSupportedOffers = reservedInstanceSupportedOffers; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (avsNodes() != null) { + avsNodes().forEach(e -> e.validate()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("avsNodes", this.avsNodes, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeArrayField("failuresToTolerateAndRaidLevelValues", this.failuresToTolerateAndRaidLevelValues, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); + jsonWriter.writeArrayField("reservedInstanceAvsNodes", this.reservedInstanceAvsNodes, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); + jsonWriter.writeArrayField("reservedInstanceSupportedLocations", this.reservedInstanceSupportedLocations, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); + jsonWriter.writeArrayField("reservedInstanceSupportedCurrencies", this.reservedInstanceSupportedCurrencies, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); + jsonWriter.writeArrayField("reservedInstanceSupportedOffers", this.reservedInstanceSupportedOffers, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AvsAssessmentOptionsProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AvsAssessmentOptionsProperties 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 AvsAssessmentOptionsProperties. + */ + public static AvsAssessmentOptionsProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AvsAssessmentOptionsProperties deserializedAvsAssessmentOptionsProperties + = new AvsAssessmentOptionsProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("avsNodes".equals(fieldName)) { + List avsNodes = reader.readArray(reader1 -> AvsSkuOptions.fromJson(reader1)); + deserializedAvsAssessmentOptionsProperties.avsNodes = avsNodes; + } else if ("failuresToTolerateAndRaidLevelValues".equals(fieldName)) { + List failuresToTolerateAndRaidLevelValues + = reader.readArray(reader1 -> FttAndRaidLevel.fromString(reader1.getString())); + deserializedAvsAssessmentOptionsProperties.failuresToTolerateAndRaidLevelValues + = failuresToTolerateAndRaidLevelValues; + } else if ("reservedInstanceAvsNodes".equals(fieldName)) { + List reservedInstanceAvsNodes + = reader.readArray(reader1 -> AzureAvsNodeType.fromString(reader1.getString())); + deserializedAvsAssessmentOptionsProperties.reservedInstanceAvsNodes = reservedInstanceAvsNodes; + } else if ("reservedInstanceSupportedLocations".equals(fieldName)) { + List reservedInstanceSupportedLocations + = reader.readArray(reader1 -> AzureLocation.fromString(reader1.getString())); + deserializedAvsAssessmentOptionsProperties.reservedInstanceSupportedLocations + = reservedInstanceSupportedLocations; + } else if ("reservedInstanceSupportedCurrencies".equals(fieldName)) { + List reservedInstanceSupportedCurrencies + = reader.readArray(reader1 -> AzureCurrency.fromString(reader1.getString())); + deserializedAvsAssessmentOptionsProperties.reservedInstanceSupportedCurrencies + = reservedInstanceSupportedCurrencies; + } else if ("reservedInstanceSupportedOffers".equals(fieldName)) { + List reservedInstanceSupportedOffers + = reader.readArray(reader1 -> AzureOfferCode.fromString(reader1.getString())); + deserializedAvsAssessmentOptionsProperties.reservedInstanceSupportedOffers + = reservedInstanceSupportedOffers; + } else { + reader.skipChildren(); + } + } + + return deserializedAvsAssessmentOptionsProperties; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessmentProperties.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessmentProperties.java new file mode 100644 index 000000000000..bf7d377e37e2 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessmentProperties.java @@ -0,0 +1,963 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Map; + +/** + * Properties of the AVS assessment. + */ +@Fluent +public final class AvsAssessmentProperties extends AzureResourceProperties { + /* + * Gets the assessment error summary. + * This is the number of machines + * affected by each type of error in this assessment. + */ + private Map assessmentErrorSummary; + + /* + * Failures to tolerate and RAID level in a common property. + */ + private FttAndRaidLevel failuresToTolerateAndRaidLevel; + + /* + * VCPU over subscription. + */ + private Float vcpuOversubscription; + + /* + * AVS node type. + */ + private AzureAvsNodeType nodeType; + + /* + * Reserved instance. + */ + private AzureReservedInstance reservedInstance; + + /* + * Total monthly cost. + */ + private Float totalMonthlyCost; + + /* + * Gets or sets the Assessment cloud suitability. + */ + private CloudSuitability suitability; + + /* + * Gets or sets the Assessment suitability explanation. + */ + private AzureAvsSuitabilityExplanation suitabilityExplanation; + + /* + * Recommended number of nodes. + */ + private Integer numberOfNodes; + + /* + * Predicted CPU utilization. + */ + private Float cpuUtilization; + + /* + * Predicted RAM utilization. + */ + private Float ramUtilization; + + /* + * Predicted storage utilization. + */ + private Float storageUtilization; + + /* + * Predicted total CPU cores used. + */ + private Float totalCpuCores; + + /* + * Predicted total RAM used in GB. + */ + private Float totalRamInGB; + + /* + * Predicted total Storage used in GB. + */ + private Float totalStorageInGB; + + /* + * Number of machines part of the assessment. + */ + private Integer numberOfMachines; + + /* + * Cloud suitability summary for all the machines in the assessment. + */ + private Map suitabilitySummary; + + /* + * Memory overcommit. + */ + private Float memOvercommit; + + /* + * De-duplication compression. + */ + private Float dedupeCompression; + + /* + * Limiting factor. + */ + private String limitingFactor; + + /* + * Is Stretch Cluster Enabled. + */ + private Boolean isStretchClusterEnabled; + + /* + * Gets the group type for the assessment. + */ + private GroupType groupType; + + /* + * Assessment type of the assessment. + */ + private AssessmentType assessmentType; + + /* + * Azure Location or Azure region where to which the machines will be migrated. + */ + private AzureLocation azureLocation; + + /* + * Azure Offer code according to which cost estimation is done. + */ + private AzureOfferCode azureOfferCode; + + /* + * Currency in which prices should be reported. + */ + private AzureCurrency currency; + + /* + * Percentage of buffer that user wants on performance metrics when recommending + * Azure sizes. + */ + private Float scalingFactor; + + /* + * Percentile of the utilization data values to be considered while assessing + * machines. + */ + private Percentile percentile; + + /* + * Time Range for which the historic utilization data should be considered for + * assessment. + */ + private TimeRange timeRange; + + /* + * Gets or sets the start time to consider performance data for assessment. + */ + private OffsetDateTime perfDataStartTime; + + /* + * Gets or sets the end time to consider performance data for assessment. + */ + private OffsetDateTime perfDataEndTime; + + /* + * User configurable setting to display the Stage of Assessment. + */ + private AssessmentStage stage; + + /* + * Custom discount percentage. + */ + private Float discountPercentage; + + /* + * Assessment sizing criterion. + */ + private AssessmentSizingCriterion sizingCriterion; + + /* + * Confidence Rating in Percentage. + */ + private Float confidenceRatingInPercentage; + + /* + * Time when the Azure Prices were queried. Date-Time represented in ISO-8601 + * format. + */ + private OffsetDateTime pricesTimestamp; + + /* + * Date and Time when assessment was created. + */ + private OffsetDateTime createdTimestamp; + + /* + * Date and Time when assessment was last updated. + */ + private OffsetDateTime updatedTimestamp; + + /* + * Whether assessment is in valid state and all machines have been assessed. + */ + private AssessmentStatus status; + + /* + * Schema version. + */ + private String schemaVersion; + + /** + * Creates an instance of AvsAssessmentProperties class. + */ + public AvsAssessmentProperties() { + } + + /** + * Get the assessmentErrorSummary property: Gets the assessment error summary. + * This is the number of machines + * affected by each type of error in this assessment. + * + * @return the assessmentErrorSummary value. + */ + public Map assessmentErrorSummary() { + return this.assessmentErrorSummary; + } + + /** + * Get the failuresToTolerateAndRaidLevel property: Failures to tolerate and RAID level in a common property. + * + * @return the failuresToTolerateAndRaidLevel value. + */ + public FttAndRaidLevel failuresToTolerateAndRaidLevel() { + return this.failuresToTolerateAndRaidLevel; + } + + /** + * Set the failuresToTolerateAndRaidLevel property: Failures to tolerate and RAID level in a common property. + * + * @param failuresToTolerateAndRaidLevel the failuresToTolerateAndRaidLevel value to set. + * @return the AvsAssessmentProperties object itself. + */ + public AvsAssessmentProperties withFailuresToTolerateAndRaidLevel(FttAndRaidLevel failuresToTolerateAndRaidLevel) { + this.failuresToTolerateAndRaidLevel = failuresToTolerateAndRaidLevel; + return this; + } + + /** + * Get the vcpuOversubscription property: VCPU over subscription. + * + * @return the vcpuOversubscription value. + */ + public Float vcpuOversubscription() { + return this.vcpuOversubscription; + } + + /** + * Set the vcpuOversubscription property: VCPU over subscription. + * + * @param vcpuOversubscription the vcpuOversubscription value to set. + * @return the AvsAssessmentProperties object itself. + */ + public AvsAssessmentProperties withVcpuOversubscription(Float vcpuOversubscription) { + this.vcpuOversubscription = vcpuOversubscription; + return this; + } + + /** + * Get the nodeType property: AVS node type. + * + * @return the nodeType value. + */ + public AzureAvsNodeType nodeType() { + return this.nodeType; + } + + /** + * Set the nodeType property: AVS node type. + * + * @param nodeType the nodeType value to set. + * @return the AvsAssessmentProperties object itself. + */ + public AvsAssessmentProperties withNodeType(AzureAvsNodeType nodeType) { + this.nodeType = nodeType; + return this; + } + + /** + * Get the reservedInstance property: Reserved instance. + * + * @return the reservedInstance value. + */ + public AzureReservedInstance reservedInstance() { + return this.reservedInstance; + } + + /** + * Set the reservedInstance property: Reserved instance. + * + * @param reservedInstance the reservedInstance value to set. + * @return the AvsAssessmentProperties object itself. + */ + public AvsAssessmentProperties withReservedInstance(AzureReservedInstance reservedInstance) { + this.reservedInstance = reservedInstance; + return this; + } + + /** + * Get the totalMonthlyCost property: Total monthly cost. + * + * @return the totalMonthlyCost value. + */ + public Float totalMonthlyCost() { + return this.totalMonthlyCost; + } + + /** + * Get the suitability property: Gets or sets the Assessment cloud suitability. + * + * @return the suitability value. + */ + public CloudSuitability suitability() { + return this.suitability; + } + + /** + * Get the suitabilityExplanation property: Gets or sets the Assessment suitability explanation. + * + * @return the suitabilityExplanation value. + */ + public AzureAvsSuitabilityExplanation suitabilityExplanation() { + return this.suitabilityExplanation; + } + + /** + * Get the numberOfNodes property: Recommended number of nodes. + * + * @return the numberOfNodes value. + */ + public Integer numberOfNodes() { + return this.numberOfNodes; + } + + /** + * Get the cpuUtilization property: Predicted CPU utilization. + * + * @return the cpuUtilization value. + */ + public Float cpuUtilization() { + return this.cpuUtilization; + } + + /** + * Get the ramUtilization property: Predicted RAM utilization. + * + * @return the ramUtilization value. + */ + public Float ramUtilization() { + return this.ramUtilization; + } + + /** + * Get the storageUtilization property: Predicted storage utilization. + * + * @return the storageUtilization value. + */ + public Float storageUtilization() { + return this.storageUtilization; + } + + /** + * Get the totalCpuCores property: Predicted total CPU cores used. + * + * @return the totalCpuCores value. + */ + public Float totalCpuCores() { + return this.totalCpuCores; + } + + /** + * Get the totalRamInGB property: Predicted total RAM used in GB. + * + * @return the totalRamInGB value. + */ + public Float totalRamInGB() { + return this.totalRamInGB; + } + + /** + * Get the totalStorageInGB property: Predicted total Storage used in GB. + * + * @return the totalStorageInGB value. + */ + public Float totalStorageInGB() { + return this.totalStorageInGB; + } + + /** + * Get the numberOfMachines property: Number of machines part of the assessment. + * + * @return the numberOfMachines value. + */ + public Integer numberOfMachines() { + return this.numberOfMachines; + } + + /** + * Get the suitabilitySummary property: Cloud suitability summary for all the machines in the assessment. + * + * @return the suitabilitySummary value. + */ + public Map suitabilitySummary() { + return this.suitabilitySummary; + } + + /** + * Get the memOvercommit property: Memory overcommit. + * + * @return the memOvercommit value. + */ + public Float memOvercommit() { + return this.memOvercommit; + } + + /** + * Set the memOvercommit property: Memory overcommit. + * + * @param memOvercommit the memOvercommit value to set. + * @return the AvsAssessmentProperties object itself. + */ + public AvsAssessmentProperties withMemOvercommit(Float memOvercommit) { + this.memOvercommit = memOvercommit; + return this; + } + + /** + * Get the dedupeCompression property: De-duplication compression. + * + * @return the dedupeCompression value. + */ + public Float dedupeCompression() { + return this.dedupeCompression; + } + + /** + * Set the dedupeCompression property: De-duplication compression. + * + * @param dedupeCompression the dedupeCompression value to set. + * @return the AvsAssessmentProperties object itself. + */ + public AvsAssessmentProperties withDedupeCompression(Float dedupeCompression) { + this.dedupeCompression = dedupeCompression; + return this; + } + + /** + * Get the limitingFactor property: Limiting factor. + * + * @return the limitingFactor value. + */ + public String limitingFactor() { + return this.limitingFactor; + } + + /** + * Get the isStretchClusterEnabled property: Is Stretch Cluster Enabled. + * + * @return the isStretchClusterEnabled value. + */ + public Boolean isStretchClusterEnabled() { + return this.isStretchClusterEnabled; + } + + /** + * Set the isStretchClusterEnabled property: Is Stretch Cluster Enabled. + * + * @param isStretchClusterEnabled the isStretchClusterEnabled value to set. + * @return the AvsAssessmentProperties object itself. + */ + public AvsAssessmentProperties withIsStretchClusterEnabled(Boolean isStretchClusterEnabled) { + this.isStretchClusterEnabled = isStretchClusterEnabled; + return this; + } + + /** + * Get the groupType property: Gets the group type for the assessment. + * + * @return the groupType value. + */ + public GroupType groupType() { + return this.groupType; + } + + /** + * Get the assessmentType property: Assessment type of the assessment. + * + * @return the assessmentType value. + */ + public AssessmentType assessmentType() { + return this.assessmentType; + } + + /** + * Get the azureLocation property: Azure Location or Azure region where to which the machines will be migrated. + * + * @return the azureLocation value. + */ + public AzureLocation azureLocation() { + return this.azureLocation; + } + + /** + * Set the azureLocation property: Azure Location or Azure region where to which the machines will be migrated. + * + * @param azureLocation the azureLocation value to set. + * @return the AvsAssessmentProperties object itself. + */ + public AvsAssessmentProperties withAzureLocation(AzureLocation azureLocation) { + this.azureLocation = azureLocation; + return this; + } + + /** + * Get the azureOfferCode property: Azure Offer code according to which cost estimation is done. + * + * @return the azureOfferCode value. + */ + public AzureOfferCode azureOfferCode() { + return this.azureOfferCode; + } + + /** + * Set the azureOfferCode property: Azure Offer code according to which cost estimation is done. + * + * @param azureOfferCode the azureOfferCode value to set. + * @return the AvsAssessmentProperties object itself. + */ + public AvsAssessmentProperties withAzureOfferCode(AzureOfferCode azureOfferCode) { + this.azureOfferCode = azureOfferCode; + return this; + } + + /** + * Get the currency property: Currency in which prices should be reported. + * + * @return the currency value. + */ + public AzureCurrency currency() { + return this.currency; + } + + /** + * Set the currency property: Currency in which prices should be reported. + * + * @param currency the currency value to set. + * @return the AvsAssessmentProperties object itself. + */ + public AvsAssessmentProperties withCurrency(AzureCurrency currency) { + this.currency = currency; + return this; + } + + /** + * Get the scalingFactor property: Percentage of buffer that user wants on performance metrics when recommending + * Azure sizes. + * + * @return the scalingFactor value. + */ + public Float scalingFactor() { + return this.scalingFactor; + } + + /** + * Set the scalingFactor property: Percentage of buffer that user wants on performance metrics when recommending + * Azure sizes. + * + * @param scalingFactor the scalingFactor value to set. + * @return the AvsAssessmentProperties object itself. + */ + public AvsAssessmentProperties withScalingFactor(Float scalingFactor) { + this.scalingFactor = scalingFactor; + return this; + } + + /** + * Get the percentile property: Percentile of the utilization data values to be considered while assessing + * machines. + * + * @return the percentile value. + */ + public Percentile percentile() { + return this.percentile; + } + + /** + * Set the percentile property: Percentile of the utilization data values to be considered while assessing + * machines. + * + * @param percentile the percentile value to set. + * @return the AvsAssessmentProperties object itself. + */ + public AvsAssessmentProperties withPercentile(Percentile percentile) { + this.percentile = percentile; + return this; + } + + /** + * Get the timeRange property: Time Range for which the historic utilization data should be considered for + * assessment. + * + * @return the timeRange value. + */ + public TimeRange timeRange() { + return this.timeRange; + } + + /** + * Set the timeRange property: Time Range for which the historic utilization data should be considered for + * assessment. + * + * @param timeRange the timeRange value to set. + * @return the AvsAssessmentProperties object itself. + */ + public AvsAssessmentProperties withTimeRange(TimeRange timeRange) { + this.timeRange = timeRange; + return this; + } + + /** + * Get the perfDataStartTime property: Gets or sets the start time to consider performance data for assessment. + * + * @return the perfDataStartTime value. + */ + public OffsetDateTime perfDataStartTime() { + return this.perfDataStartTime; + } + + /** + * Set the perfDataStartTime property: Gets or sets the start time to consider performance data for assessment. + * + * @param perfDataStartTime the perfDataStartTime value to set. + * @return the AvsAssessmentProperties object itself. + */ + public AvsAssessmentProperties withPerfDataStartTime(OffsetDateTime perfDataStartTime) { + this.perfDataStartTime = perfDataStartTime; + return this; + } + + /** + * Get the perfDataEndTime property: Gets or sets the end time to consider performance data for assessment. + * + * @return the perfDataEndTime value. + */ + public OffsetDateTime perfDataEndTime() { + return this.perfDataEndTime; + } + + /** + * Set the perfDataEndTime property: Gets or sets the end time to consider performance data for assessment. + * + * @param perfDataEndTime the perfDataEndTime value to set. + * @return the AvsAssessmentProperties object itself. + */ + public AvsAssessmentProperties withPerfDataEndTime(OffsetDateTime perfDataEndTime) { + this.perfDataEndTime = perfDataEndTime; + return this; + } + + /** + * Get the stage property: User configurable setting to display the Stage of Assessment. + * + * @return the stage value. + */ + public AssessmentStage stage() { + return this.stage; + } + + /** + * Get the discountPercentage property: Custom discount percentage. + * + * @return the discountPercentage value. + */ + public Float discountPercentage() { + return this.discountPercentage; + } + + /** + * Set the discountPercentage property: Custom discount percentage. + * + * @param discountPercentage the discountPercentage value to set. + * @return the AvsAssessmentProperties object itself. + */ + public AvsAssessmentProperties withDiscountPercentage(Float discountPercentage) { + this.discountPercentage = discountPercentage; + return this; + } + + /** + * Get the sizingCriterion property: Assessment sizing criterion. + * + * @return the sizingCriterion value. + */ + public AssessmentSizingCriterion sizingCriterion() { + return this.sizingCriterion; + } + + /** + * Set the sizingCriterion property: Assessment sizing criterion. + * + * @param sizingCriterion the sizingCriterion value to set. + * @return the AvsAssessmentProperties object itself. + */ + public AvsAssessmentProperties withSizingCriterion(AssessmentSizingCriterion sizingCriterion) { + this.sizingCriterion = sizingCriterion; + return this; + } + + /** + * Get the confidenceRatingInPercentage property: Confidence Rating in Percentage. + * + * @return the confidenceRatingInPercentage value. + */ + public Float confidenceRatingInPercentage() { + return this.confidenceRatingInPercentage; + } + + /** + * Get the pricesTimestamp property: Time when the Azure Prices were queried. Date-Time represented in ISO-8601 + * format. + * + * @return the pricesTimestamp value. + */ + public OffsetDateTime pricesTimestamp() { + return this.pricesTimestamp; + } + + /** + * Get the createdTimestamp property: Date and Time when assessment was created. + * + * @return the createdTimestamp value. + */ + public OffsetDateTime createdTimestamp() { + return this.createdTimestamp; + } + + /** + * Get the updatedTimestamp property: Date and Time when assessment was last updated. + * + * @return the updatedTimestamp value. + */ + public OffsetDateTime updatedTimestamp() { + return this.updatedTimestamp; + } + + /** + * Get the status property: Whether assessment is in valid state and all machines have been assessed. + * + * @return the status value. + */ + public AssessmentStatus status() { + return this.status; + } + + /** + * Get the schemaVersion property: Schema version. + * + * @return the schemaVersion value. + */ + public String schemaVersion() { + return this.schemaVersion; + } + + /** + * {@inheritDoc} + */ + @Override + public AvsAssessmentProperties withProvisioningState(ProvisioningState provisioningState) { + super.withProvisioningState(provisioningState); + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + @Override + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("provisioningState", + provisioningState() == null ? null : provisioningState().toString()); + jsonWriter.writeStringField("failuresToTolerateAndRaidLevel", + this.failuresToTolerateAndRaidLevel == null ? null : this.failuresToTolerateAndRaidLevel.toString()); + jsonWriter.writeNumberField("vcpuOversubscription", this.vcpuOversubscription); + jsonWriter.writeStringField("nodeType", this.nodeType == null ? null : this.nodeType.toString()); + jsonWriter.writeStringField("reservedInstance", + this.reservedInstance == null ? null : this.reservedInstance.toString()); + jsonWriter.writeNumberField("memOvercommit", this.memOvercommit); + jsonWriter.writeNumberField("dedupeCompression", this.dedupeCompression); + jsonWriter.writeBooleanField("isStretchClusterEnabled", this.isStretchClusterEnabled); + jsonWriter.writeStringField("azureLocation", this.azureLocation == null ? null : this.azureLocation.toString()); + jsonWriter.writeStringField("azureOfferCode", + this.azureOfferCode == null ? null : this.azureOfferCode.toString()); + jsonWriter.writeStringField("currency", this.currency == null ? null : this.currency.toString()); + jsonWriter.writeNumberField("scalingFactor", this.scalingFactor); + jsonWriter.writeStringField("percentile", this.percentile == null ? null : this.percentile.toString()); + jsonWriter.writeStringField("timeRange", this.timeRange == null ? null : this.timeRange.toString()); + jsonWriter.writeStringField("perfDataStartTime", + this.perfDataStartTime == null + ? null + : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.perfDataStartTime)); + jsonWriter.writeStringField("perfDataEndTime", + this.perfDataEndTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.perfDataEndTime)); + jsonWriter.writeNumberField("discountPercentage", this.discountPercentage); + jsonWriter.writeStringField("sizingCriterion", + this.sizingCriterion == null ? null : this.sizingCriterion.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AvsAssessmentProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AvsAssessmentProperties 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 AvsAssessmentProperties. + */ + public static AvsAssessmentProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AvsAssessmentProperties deserializedAvsAssessmentProperties = new AvsAssessmentProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("provisioningState".equals(fieldName)) { + deserializedAvsAssessmentProperties + .withProvisioningState(ProvisioningState.fromString(reader.getString())); + } else if ("assessmentErrorSummary".equals(fieldName)) { + Map assessmentErrorSummary = reader.readMap(reader1 -> reader1.getInt()); + deserializedAvsAssessmentProperties.assessmentErrorSummary = assessmentErrorSummary; + } else if ("failuresToTolerateAndRaidLevel".equals(fieldName)) { + deserializedAvsAssessmentProperties.failuresToTolerateAndRaidLevel + = FttAndRaidLevel.fromString(reader.getString()); + } else if ("vcpuOversubscription".equals(fieldName)) { + deserializedAvsAssessmentProperties.vcpuOversubscription = reader.getNullable(JsonReader::getFloat); + } else if ("nodeType".equals(fieldName)) { + deserializedAvsAssessmentProperties.nodeType = AzureAvsNodeType.fromString(reader.getString()); + } else if ("reservedInstance".equals(fieldName)) { + deserializedAvsAssessmentProperties.reservedInstance + = AzureReservedInstance.fromString(reader.getString()); + } else if ("totalMonthlyCost".equals(fieldName)) { + deserializedAvsAssessmentProperties.totalMonthlyCost = reader.getNullable(JsonReader::getFloat); + } else if ("suitability".equals(fieldName)) { + deserializedAvsAssessmentProperties.suitability = CloudSuitability.fromString(reader.getString()); + } else if ("suitabilityExplanation".equals(fieldName)) { + deserializedAvsAssessmentProperties.suitabilityExplanation + = AzureAvsSuitabilityExplanation.fromString(reader.getString()); + } else if ("numberOfNodes".equals(fieldName)) { + deserializedAvsAssessmentProperties.numberOfNodes = reader.getNullable(JsonReader::getInt); + } else if ("cpuUtilization".equals(fieldName)) { + deserializedAvsAssessmentProperties.cpuUtilization = reader.getNullable(JsonReader::getFloat); + } else if ("ramUtilization".equals(fieldName)) { + deserializedAvsAssessmentProperties.ramUtilization = reader.getNullable(JsonReader::getFloat); + } else if ("storageUtilization".equals(fieldName)) { + deserializedAvsAssessmentProperties.storageUtilization = reader.getNullable(JsonReader::getFloat); + } else if ("totalCpuCores".equals(fieldName)) { + deserializedAvsAssessmentProperties.totalCpuCores = reader.getNullable(JsonReader::getFloat); + } else if ("totalRamInGB".equals(fieldName)) { + deserializedAvsAssessmentProperties.totalRamInGB = reader.getNullable(JsonReader::getFloat); + } else if ("totalStorageInGB".equals(fieldName)) { + deserializedAvsAssessmentProperties.totalStorageInGB = reader.getNullable(JsonReader::getFloat); + } else if ("numberOfMachines".equals(fieldName)) { + deserializedAvsAssessmentProperties.numberOfMachines = reader.getNullable(JsonReader::getInt); + } else if ("suitabilitySummary".equals(fieldName)) { + Map suitabilitySummary = reader.readMap(reader1 -> reader1.getInt()); + deserializedAvsAssessmentProperties.suitabilitySummary = suitabilitySummary; + } else if ("memOvercommit".equals(fieldName)) { + deserializedAvsAssessmentProperties.memOvercommit = reader.getNullable(JsonReader::getFloat); + } else if ("dedupeCompression".equals(fieldName)) { + deserializedAvsAssessmentProperties.dedupeCompression = reader.getNullable(JsonReader::getFloat); + } else if ("limitingFactor".equals(fieldName)) { + deserializedAvsAssessmentProperties.limitingFactor = reader.getString(); + } else if ("isStretchClusterEnabled".equals(fieldName)) { + deserializedAvsAssessmentProperties.isStretchClusterEnabled + = reader.getNullable(JsonReader::getBoolean); + } else if ("groupType".equals(fieldName)) { + deserializedAvsAssessmentProperties.groupType = GroupType.fromString(reader.getString()); + } else if ("assessmentType".equals(fieldName)) { + deserializedAvsAssessmentProperties.assessmentType = AssessmentType.fromString(reader.getString()); + } else if ("azureLocation".equals(fieldName)) { + deserializedAvsAssessmentProperties.azureLocation = AzureLocation.fromString(reader.getString()); + } else if ("azureOfferCode".equals(fieldName)) { + deserializedAvsAssessmentProperties.azureOfferCode = AzureOfferCode.fromString(reader.getString()); + } else if ("currency".equals(fieldName)) { + deserializedAvsAssessmentProperties.currency = AzureCurrency.fromString(reader.getString()); + } else if ("scalingFactor".equals(fieldName)) { + deserializedAvsAssessmentProperties.scalingFactor = reader.getNullable(JsonReader::getFloat); + } else if ("percentile".equals(fieldName)) { + deserializedAvsAssessmentProperties.percentile = Percentile.fromString(reader.getString()); + } else if ("timeRange".equals(fieldName)) { + deserializedAvsAssessmentProperties.timeRange = TimeRange.fromString(reader.getString()); + } else if ("perfDataStartTime".equals(fieldName)) { + deserializedAvsAssessmentProperties.perfDataStartTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("perfDataEndTime".equals(fieldName)) { + deserializedAvsAssessmentProperties.perfDataEndTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("stage".equals(fieldName)) { + deserializedAvsAssessmentProperties.stage = AssessmentStage.fromString(reader.getString()); + } else if ("discountPercentage".equals(fieldName)) { + deserializedAvsAssessmentProperties.discountPercentage = reader.getNullable(JsonReader::getFloat); + } else if ("sizingCriterion".equals(fieldName)) { + deserializedAvsAssessmentProperties.sizingCriterion + = AssessmentSizingCriterion.fromString(reader.getString()); + } else if ("confidenceRatingInPercentage".equals(fieldName)) { + deserializedAvsAssessmentProperties.confidenceRatingInPercentage + = reader.getNullable(JsonReader::getFloat); + } else if ("pricesTimestamp".equals(fieldName)) { + deserializedAvsAssessmentProperties.pricesTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("createdTimestamp".equals(fieldName)) { + deserializedAvsAssessmentProperties.createdTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("updatedTimestamp".equals(fieldName)) { + deserializedAvsAssessmentProperties.updatedTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("status".equals(fieldName)) { + deserializedAvsAssessmentProperties.status = AssessmentStatus.fromString(reader.getString()); + } else if ("schemaVersion".equals(fieldName)) { + deserializedAvsAssessmentProperties.schemaVersion = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAvsAssessmentProperties; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessmentsOperations.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessmentsOperations.java new file mode 100644 index 000000000000..5f023d43b38f --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsAssessmentsOperations.java @@ -0,0 +1,191 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of AvsAssessmentsOperations. + */ +public interface AvsAssessmentsOperations { + /** + * List AvsAssessment resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessment list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByGroup(String resourceGroupName, String projectName, String groupName); + + /** + * List AvsAssessment resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a AvsAssessment list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByGroup(String resourceGroupName, String projectName, String groupName, + Context context); + + /** + * Get a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AvsAssessment along with {@link Response}. + */ + Response getWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, Context context); + + /** + * Get a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AvsAssessment. + */ + AvsAssessment get(String resourceGroupName, String projectName, String groupName, String assessmentName); + + /** + * Delete a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, Context context); + + /** + * Delete a AvsAssessment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void delete(String resourceGroupName, String projectName, String groupName, String assessmentName); + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format. + */ + DownloadUrl downloadUrl(String resourceGroupName, String projectName, String groupName, String assessmentName, + Object body); + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName AVS Assessment ARM name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format. + */ + DownloadUrl downloadUrl(String resourceGroupName, String projectName, String groupName, String assessmentName, + Object body, Context context); + + /** + * Get a AvsAssessment. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AvsAssessment along with {@link Response}. + */ + AvsAssessment getById(String id); + + /** + * Get a AvsAssessment. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a AvsAssessment along with {@link Response}. + */ + Response getByIdWithResponse(String id, Context context); + + /** + * Delete a AvsAssessment. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteById(String id); + + /** + * Delete a AvsAssessment. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteByIdWithResponse(String id, Context context); + + /** + * Begins definition for a new AvsAssessment resource. + * + * @param name resource name. + * @return the first stage of the new AvsAssessment definition. + */ + AvsAssessment.DefinitionStages.Blank define(String name); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsSkuOptions.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsSkuOptions.java new file mode 100644 index 000000000000..926490834aaf --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AvsSkuOptions.java @@ -0,0 +1,125 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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.List; + +/** + * AVS SKU specific options. + */ +@Fluent +public final class AvsSkuOptions implements JsonSerializable { + /* + * AVS Node type. + */ + private AzureAvsNodeType nodeType; + + /* + * List of locations where this node type is available. + */ + private List targetLocations; + + /** + * Creates an instance of AvsSkuOptions class. + */ + public AvsSkuOptions() { + } + + /** + * Get the nodeType property: AVS Node type. + * + * @return the nodeType value. + */ + public AzureAvsNodeType nodeType() { + return this.nodeType; + } + + /** + * Set the nodeType property: AVS Node type. + * + * @param nodeType the nodeType value to set. + * @return the AvsSkuOptions object itself. + */ + public AvsSkuOptions withNodeType(AzureAvsNodeType nodeType) { + this.nodeType = nodeType; + return this; + } + + /** + * Get the targetLocations property: List of locations where this node type is available. + * + * @return the targetLocations value. + */ + public List targetLocations() { + return this.targetLocations; + } + + /** + * Set the targetLocations property: List of locations where this node type is available. + * + * @param targetLocations the targetLocations value to set. + * @return the AvsSkuOptions object itself. + */ + public AvsSkuOptions withTargetLocations(List targetLocations) { + this.targetLocations = targetLocations; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("nodeType", this.nodeType == null ? null : this.nodeType.toString()); + jsonWriter.writeArrayField("targetLocations", this.targetLocations, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AvsSkuOptions from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AvsSkuOptions 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 AvsSkuOptions. + */ + public static AvsSkuOptions fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AvsSkuOptions deserializedAvsSkuOptions = new AvsSkuOptions(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("nodeType".equals(fieldName)) { + deserializedAvsSkuOptions.nodeType = AzureAvsNodeType.fromString(reader.getString()); + } else if ("targetLocations".equals(fieldName)) { + List targetLocations + = reader.readArray(reader1 -> AzureLocation.fromString(reader1.getString())); + deserializedAvsSkuOptions.targetLocations = targetLocations; + } else { + reader.skipChildren(); + } + } + + return deserializedAvsSkuOptions; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureAvsNodeType.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureAvsNodeType.java new file mode 100644 index 000000000000..2e2c7b58a5da --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureAvsNodeType.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AzureAvsNodeType. + */ +public final class AzureAvsNodeType extends ExpandableStringEnum { + /** + * Static value Unknown for AzureAvsNodeType. + */ + public static final AzureAvsNodeType UNKNOWN = fromString("Unknown"); + + /** + * Static value AV36 for AzureAvsNodeType. + */ + public static final AzureAvsNodeType AV36 = fromString("AV36"); + + /** + * Creates a new instance of AzureAvsNodeType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureAvsNodeType() { + } + + /** + * Creates or finds a AzureAvsNodeType from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureAvsNodeType. + */ + public static AzureAvsNodeType fromString(String name) { + return fromString(name, AzureAvsNodeType.class); + } + + /** + * Gets known AzureAvsNodeType values. + * + * @return known AzureAvsNodeType values. + */ + public static Collection values() { + return values(AzureAvsNodeType.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureAvsSuitabilityExplanation.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureAvsSuitabilityExplanation.java new file mode 100644 index 000000000000..95528b61326d --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureAvsSuitabilityExplanation.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AzureAvsSuitabilityExplanation. + */ +public final class AzureAvsSuitabilityExplanation extends ExpandableStringEnum { + /** + * Static value Unknown for AzureAvsSuitabilityExplanation. + */ + public static final AzureAvsSuitabilityExplanation UNKNOWN = fromString("Unknown"); + + /** + * Static value NotApplicable for AzureAvsSuitabilityExplanation. + */ + public static final AzureAvsSuitabilityExplanation NOT_APPLICABLE = fromString("NotApplicable"); + + /** + * Static value UnsupportedLocationForSelectedNode for AzureAvsSuitabilityExplanation. + */ + public static final AzureAvsSuitabilityExplanation UNSUPPORTED_LOCATION_FOR_SELECTED_NODE + = fromString("UnsupportedLocationForSelectedNode"); + + /** + * Creates a new instance of AzureAvsSuitabilityExplanation value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureAvsSuitabilityExplanation() { + } + + /** + * Creates or finds a AzureAvsSuitabilityExplanation from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureAvsSuitabilityExplanation. + */ + public static AzureAvsSuitabilityExplanation fromString(String name) { + return fromString(name, AzureAvsSuitabilityExplanation.class); + } + + /** + * Gets known AzureAvsSuitabilityExplanation values. + * + * @return known AzureAvsSuitabilityExplanation values. + */ + public static Collection values() { + return values(AzureAvsSuitabilityExplanation.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureAvsVmSuitabilityDetail.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureAvsVmSuitabilityDetail.java new file mode 100644 index 000000000000..7fb4f058cead --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureAvsVmSuitabilityDetail.java @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AzureAvsVmSuitabilityDetail. + */ +public final class AzureAvsVmSuitabilityDetail extends ExpandableStringEnum { + /** + * Static value None for AzureAvsVmSuitabilityDetail. + */ + public static final AzureAvsVmSuitabilityDetail NONE = fromString("None"); + + /** + * Static value PercentageOfCoresUtilizedMissing for AzureAvsVmSuitabilityDetail. + */ + public static final AzureAvsVmSuitabilityDetail PERCENTAGE_OF_CORES_UTILIZED_MISSING + = fromString("PercentageOfCoresUtilizedMissing"); + + /** + * Static value PercentageOfMemoryUtilizedMissing for AzureAvsVmSuitabilityDetail. + */ + public static final AzureAvsVmSuitabilityDetail PERCENTAGE_OF_MEMORY_UTILIZED_MISSING + = fromString("PercentageOfMemoryUtilizedMissing"); + + /** + * Static value PercentageOfCoresUtilizedOutOfRange for AzureAvsVmSuitabilityDetail. + */ + public static final AzureAvsVmSuitabilityDetail PERCENTAGE_OF_CORES_UTILIZED_OUT_OF_RANGE + = fromString("PercentageOfCoresUtilizedOutOfRange"); + + /** + * Static value PercentageOfMemoryUtilizedOutOfRange for AzureAvsVmSuitabilityDetail. + */ + public static final AzureAvsVmSuitabilityDetail PERCENTAGE_OF_MEMORY_UTILIZED_OUT_OF_RANGE + = fromString("PercentageOfMemoryUtilizedOutOfRange"); + + /** + * Static value PercentageOfStorageUtilizedOutOfRange for AzureAvsVmSuitabilityDetail. + */ + public static final AzureAvsVmSuitabilityDetail PERCENTAGE_OF_STORAGE_UTILIZED_OUT_OF_RANGE + = fromString("PercentageOfStorageUtilizedOutOfRange"); + + /** + * Creates a new instance of AzureAvsVmSuitabilityDetail value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureAvsVmSuitabilityDetail() { + } + + /** + * Creates or finds a AzureAvsVmSuitabilityDetail from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureAvsVmSuitabilityDetail. + */ + public static AzureAvsVmSuitabilityDetail fromString(String name) { + return fromString(name, AzureAvsVmSuitabilityDetail.class); + } + + /** + * Gets known AzureAvsVmSuitabilityDetail values. + * + * @return known AzureAvsVmSuitabilityDetail values. + */ + public static Collection values() { + return values(AzureAvsVmSuitabilityDetail.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureAvsVmSuitabilityExplanation.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureAvsVmSuitabilityExplanation.java new file mode 100644 index 000000000000..49725c4a825e --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureAvsVmSuitabilityExplanation.java @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AzureAvsVmSuitabilityExplanation. + */ +public final class AzureAvsVmSuitabilityExplanation extends ExpandableStringEnum { + /** + * Static value Unknown for AzureAvsVmSuitabilityExplanation. + */ + public static final AzureAvsVmSuitabilityExplanation UNKNOWN = fromString("Unknown"); + + /** + * Static value NotApplicable for AzureAvsVmSuitabilityExplanation. + */ + public static final AzureAvsVmSuitabilityExplanation NOT_APPLICABLE = fromString("NotApplicable"); + + /** + * Static value IpV6NotSupported for AzureAvsVmSuitabilityExplanation. + */ + public static final AzureAvsVmSuitabilityExplanation IP_V6NOT_SUPPORTED = fromString("IpV6NotSupported"); + + /** + * Static value UnsupportedOperatingSystem for AzureAvsVmSuitabilityExplanation. + */ + public static final AzureAvsVmSuitabilityExplanation UNSUPPORTED_OPERATING_SYSTEM + = fromString("UnsupportedOperatingSystem"); + + /** + * Creates a new instance of AzureAvsVmSuitabilityExplanation value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureAvsVmSuitabilityExplanation() { + } + + /** + * Creates or finds a AzureAvsVmSuitabilityExplanation from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureAvsVmSuitabilityExplanation. + */ + public static AzureAvsVmSuitabilityExplanation fromString(String name) { + return fromString(name, AzureAvsVmSuitabilityExplanation.class); + } + + /** + * Gets known AzureAvsVmSuitabilityExplanation values. + * + * @return known AzureAvsVmSuitabilityExplanation values. + */ + public static Collection values() { + return values(AzureAvsVmSuitabilityExplanation.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureCurrency.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureCurrency.java new file mode 100644 index 000000000000..f258ecb2092c --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureCurrency.java @@ -0,0 +1,171 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Currency for Azure. + */ +public final class AzureCurrency extends ExpandableStringEnum { + /** + * Static value Unknown for AzureCurrency. + */ + public static final AzureCurrency UNKNOWN = fromString("Unknown"); + + /** + * Static value USD for AzureCurrency. + */ + public static final AzureCurrency USD = fromString("USD"); + + /** + * Static value DKK for AzureCurrency. + */ + public static final AzureCurrency DKK = fromString("DKK"); + + /** + * Static value CAD for AzureCurrency. + */ + public static final AzureCurrency CAD = fromString("CAD"); + + /** + * Static value IDR for AzureCurrency. + */ + public static final AzureCurrency IDR = fromString("IDR"); + + /** + * Static value JPY for AzureCurrency. + */ + public static final AzureCurrency JPY = fromString("JPY"); + + /** + * Static value KRW for AzureCurrency. + */ + public static final AzureCurrency KRW = fromString("KRW"); + + /** + * Static value NZD for AzureCurrency. + */ + public static final AzureCurrency NZD = fromString("NZD"); + + /** + * Static value NOK for AzureCurrency. + */ + public static final AzureCurrency NOK = fromString("NOK"); + + /** + * Static value RUB for AzureCurrency. + */ + public static final AzureCurrency RUB = fromString("RUB"); + + /** + * Static value SAR for AzureCurrency. + */ + public static final AzureCurrency SAR = fromString("SAR"); + + /** + * Static value ZAR for AzureCurrency. + */ + public static final AzureCurrency ZAR = fromString("ZAR"); + + /** + * Static value SEK for AzureCurrency. + */ + public static final AzureCurrency SEK = fromString("SEK"); + + /** + * Static value TRY for AzureCurrency. + */ + public static final AzureCurrency TRY = fromString("TRY"); + + /** + * Static value GBP for AzureCurrency. + */ + public static final AzureCurrency GBP = fromString("GBP"); + + /** + * Static value MXN for AzureCurrency. + */ + public static final AzureCurrency MXN = fromString("MXN"); + + /** + * Static value MYR for AzureCurrency. + */ + public static final AzureCurrency MYR = fromString("MYR"); + + /** + * Static value INR for AzureCurrency. + */ + public static final AzureCurrency INR = fromString("INR"); + + /** + * Static value HKD for AzureCurrency. + */ + public static final AzureCurrency HKD = fromString("HKD"); + + /** + * Static value BRL for AzureCurrency. + */ + public static final AzureCurrency BRL = fromString("BRL"); + + /** + * Static value TWD for AzureCurrency. + */ + public static final AzureCurrency TWD = fromString("TWD"); + + /** + * Static value EUR for AzureCurrency. + */ + public static final AzureCurrency EUR = fromString("EUR"); + + /** + * Static value CHF for AzureCurrency. + */ + public static final AzureCurrency CHF = fromString("CHF"); + + /** + * Static value ARS for AzureCurrency. + */ + public static final AzureCurrency ARS = fromString("ARS"); + + /** + * Static value AUD for AzureCurrency. + */ + public static final AzureCurrency AUD = fromString("AUD"); + + /** + * Static value CNY for AzureCurrency. + */ + public static final AzureCurrency CNY = fromString("CNY"); + + /** + * Creates a new instance of AzureCurrency value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureCurrency() { + } + + /** + * Creates or finds a AzureCurrency from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureCurrency. + */ + public static AzureCurrency fromString(String name) { + return fromString(name, AzureCurrency.class); + } + + /** + * Gets known AzureCurrency values. + * + * @return known AzureCurrency values. + */ + public static Collection values() { + return values(AzureCurrency.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureDiskSize.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureDiskSize.java new file mode 100644 index 000000000000..63e37894d6c8 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureDiskSize.java @@ -0,0 +1,251 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AzureDiskSize. + */ +public final class AzureDiskSize extends ExpandableStringEnum { + /** + * Static value Unknown for AzureDiskSize. + */ + public static final AzureDiskSize UNKNOWN = fromString("Unknown"); + + /** + * Static value Standard_S4 for AzureDiskSize. + */ + public static final AzureDiskSize STANDARD_S4 = fromString("Standard_S4"); + + /** + * Static value Standard_S6 for AzureDiskSize. + */ + public static final AzureDiskSize STANDARD_S6 = fromString("Standard_S6"); + + /** + * Static value Standard_S10 for AzureDiskSize. + */ + public static final AzureDiskSize STANDARD_S10 = fromString("Standard_S10"); + + /** + * Static value Standard_S15 for AzureDiskSize. + */ + public static final AzureDiskSize STANDARD_S15 = fromString("Standard_S15"); + + /** + * Static value Standard_S20 for AzureDiskSize. + */ + public static final AzureDiskSize STANDARD_S20 = fromString("Standard_S20"); + + /** + * Static value Standard_S30 for AzureDiskSize. + */ + public static final AzureDiskSize STANDARD_S30 = fromString("Standard_S30"); + + /** + * Static value Standard_S40 for AzureDiskSize. + */ + public static final AzureDiskSize STANDARD_S40 = fromString("Standard_S40"); + + /** + * Static value Standard_S50 for AzureDiskSize. + */ + public static final AzureDiskSize STANDARD_S50 = fromString("Standard_S50"); + + /** + * Static value Standard_S60 for AzureDiskSize. + */ + public static final AzureDiskSize STANDARD_S60 = fromString("Standard_S60"); + + /** + * Static value Standard_S70 for AzureDiskSize. + */ + public static final AzureDiskSize STANDARD_S70 = fromString("Standard_S70"); + + /** + * Static value Standard_S80 for AzureDiskSize. + */ + public static final AzureDiskSize STANDARD_S80 = fromString("Standard_S80"); + + /** + * Static value Premium_P4 for AzureDiskSize. + */ + public static final AzureDiskSize PREMIUM_P4 = fromString("Premium_P4"); + + /** + * Static value Premium_P6 for AzureDiskSize. + */ + public static final AzureDiskSize PREMIUM_P6 = fromString("Premium_P6"); + + /** + * Static value Premium_P10 for AzureDiskSize. + */ + public static final AzureDiskSize PREMIUM_P10 = fromString("Premium_P10"); + + /** + * Static value Premium_P15 for AzureDiskSize. + */ + public static final AzureDiskSize PREMIUM_P15 = fromString("Premium_P15"); + + /** + * Static value Premium_P20 for AzureDiskSize. + */ + public static final AzureDiskSize PREMIUM_P20 = fromString("Premium_P20"); + + /** + * Static value Premium_P30 for AzureDiskSize. + */ + public static final AzureDiskSize PREMIUM_P30 = fromString("Premium_P30"); + + /** + * Static value Premium_P40 for AzureDiskSize. + */ + public static final AzureDiskSize PREMIUM_P40 = fromString("Premium_P40"); + + /** + * Static value Premium_P50 for AzureDiskSize. + */ + public static final AzureDiskSize PREMIUM_P50 = fromString("Premium_P50"); + + /** + * Static value Premium_P60 for AzureDiskSize. + */ + public static final AzureDiskSize PREMIUM_P60 = fromString("Premium_P60"); + + /** + * Static value Premium_P70 for AzureDiskSize. + */ + public static final AzureDiskSize PREMIUM_P70 = fromString("Premium_P70"); + + /** + * Static value Premium_P80 for AzureDiskSize. + */ + public static final AzureDiskSize PREMIUM_P80 = fromString("Premium_P80"); + + /** + * Static value StandardSSD_E10 for AzureDiskSize. + */ + public static final AzureDiskSize STANDARD_SSD_E10 = fromString("StandardSSD_E10"); + + /** + * Static value StandardSSD_E15 for AzureDiskSize. + */ + public static final AzureDiskSize STANDARD_SSD_E15 = fromString("StandardSSD_E15"); + + /** + * Static value StandardSSD_E20 for AzureDiskSize. + */ + public static final AzureDiskSize STANDARD_SSD_E20 = fromString("StandardSSD_E20"); + + /** + * Static value StandardSSD_E30 for AzureDiskSize. + */ + public static final AzureDiskSize STANDARD_SSD_E30 = fromString("StandardSSD_E30"); + + /** + * Static value StandardSSD_E40 for AzureDiskSize. + */ + public static final AzureDiskSize STANDARD_SSD_E40 = fromString("StandardSSD_E40"); + + /** + * Static value StandardSSD_E50 for AzureDiskSize. + */ + public static final AzureDiskSize STANDARD_SSD_E50 = fromString("StandardSSD_E50"); + + /** + * Static value StandardSSD_E60 for AzureDiskSize. + */ + public static final AzureDiskSize STANDARD_SSD_E60 = fromString("StandardSSD_E60"); + + /** + * Static value StandardSSD_E70 for AzureDiskSize. + */ + public static final AzureDiskSize STANDARD_SSD_E70 = fromString("StandardSSD_E70"); + + /** + * Static value StandardSSD_E80 for AzureDiskSize. + */ + public static final AzureDiskSize STANDARD_SSD_E80 = fromString("StandardSSD_E80"); + + /** + * Static value StandardSSD_E4 for AzureDiskSize. + */ + public static final AzureDiskSize STANDARD_SSD_E4 = fromString("StandardSSD_E4"); + + /** + * Static value StandardSSD_E6 for AzureDiskSize. + */ + public static final AzureDiskSize STANDARD_SSD_E6 = fromString("StandardSSD_E6"); + + /** + * Static value StandardSSD_E1 for AzureDiskSize. + */ + public static final AzureDiskSize STANDARD_SSD_E1 = fromString("StandardSSD_E1"); + + /** + * Static value StandardSSD_E2 for AzureDiskSize. + */ + public static final AzureDiskSize STANDARD_SSD_E2 = fromString("StandardSSD_E2"); + + /** + * Static value StandardSSD_E3 for AzureDiskSize. + */ + public static final AzureDiskSize STANDARD_SSD_E3 = fromString("StandardSSD_E3"); + + /** + * Static value Premium_P1 for AzureDiskSize. + */ + public static final AzureDiskSize PREMIUM_P1 = fromString("Premium_P1"); + + /** + * Static value Premium_P2 for AzureDiskSize. + */ + public static final AzureDiskSize PREMIUM_P2 = fromString("Premium_P2"); + + /** + * Static value Premium_P3 for AzureDiskSize. + */ + public static final AzureDiskSize PREMIUM_P3 = fromString("Premium_P3"); + + /** + * Static value Ultra for AzureDiskSize. + */ + public static final AzureDiskSize ULTRA = fromString("Ultra"); + + /** + * Static value PremiumV2 for AzureDiskSize. + */ + public static final AzureDiskSize PREMIUM_V2 = fromString("PremiumV2"); + + /** + * Creates a new instance of AzureDiskSize value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureDiskSize() { + } + + /** + * Creates or finds a AzureDiskSize from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureDiskSize. + */ + public static AzureDiskSize fromString(String name) { + return fromString(name, AzureDiskSize.class); + } + + /** + * Gets known AzureDiskSize values. + * + * @return known AzureDiskSize values. + */ + public static Collection values() { + return values(AzureDiskSize.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureDiskSuitabilityDetail.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureDiskSuitabilityDetail.java new file mode 100644 index 000000000000..50455f760acb --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureDiskSuitabilityDetail.java @@ -0,0 +1,118 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AzureDiskSuitabilityDetail. + */ +public final class AzureDiskSuitabilityDetail extends ExpandableStringEnum { + /** + * Static value None for AzureDiskSuitabilityDetail. + */ + public static final AzureDiskSuitabilityDetail NONE = fromString("None"); + + /** + * Static value NumberOfReadOperationsPerSecondMissing for AzureDiskSuitabilityDetail. + */ + public static final AzureDiskSuitabilityDetail NUMBER_OF_READ_OPERATIONS_PER_SECOND_MISSING + = fromString("NumberOfReadOperationsPerSecondMissing"); + + /** + * Static value NumberOfWriteOperationsPerSecondMissing for AzureDiskSuitabilityDetail. + */ + public static final AzureDiskSuitabilityDetail NUMBER_OF_WRITE_OPERATIONS_PER_SECOND_MISSING + = fromString("NumberOfWriteOperationsPerSecondMissing"); + + /** + * Static value MegabytesPerSecondOfReadMissing for AzureDiskSuitabilityDetail. + */ + public static final AzureDiskSuitabilityDetail MEGABYTES_PER_SECOND_OF_READ_MISSING + = fromString("MegabytesPerSecondOfReadMissing"); + + /** + * Static value MegabytesPerSecondOfWriteMissing for AzureDiskSuitabilityDetail. + */ + public static final AzureDiskSuitabilityDetail MEGABYTES_PER_SECOND_OF_WRITE_MISSING + = fromString("MegabytesPerSecondOfWriteMissing"); + + /** + * Static value DiskGigabytesConsumedMissing for AzureDiskSuitabilityDetail. + */ + public static final AzureDiskSuitabilityDetail DISK_GIGABYTES_CONSUMED_MISSING + = fromString("DiskGigabytesConsumedMissing"); + + /** + * Static value DiskGigabytesProvisionedMissing for AzureDiskSuitabilityDetail. + */ + public static final AzureDiskSuitabilityDetail DISK_GIGABYTES_PROVISIONED_MISSING + = fromString("DiskGigabytesProvisionedMissing"); + + /** + * Static value NumberOfReadOperationsPerSecondOutOfRange for AzureDiskSuitabilityDetail. + */ + public static final AzureDiskSuitabilityDetail NUMBER_OF_READ_OPERATIONS_PER_SECOND_OUT_OF_RANGE + = fromString("NumberOfReadOperationsPerSecondOutOfRange"); + + /** + * Static value NumberOfWriteOperationsPerSecondOutOfRange for AzureDiskSuitabilityDetail. + */ + public static final AzureDiskSuitabilityDetail NUMBER_OF_WRITE_OPERATIONS_PER_SECOND_OUT_OF_RANGE + = fromString("NumberOfWriteOperationsPerSecondOutOfRange"); + + /** + * Static value MegabytesPerSecondOfReadOutOfRange for AzureDiskSuitabilityDetail. + */ + public static final AzureDiskSuitabilityDetail MEGABYTES_PER_SECOND_OF_READ_OUT_OF_RANGE + = fromString("MegabytesPerSecondOfReadOutOfRange"); + + /** + * Static value MegabytesPerSecondOfWriteOutOfRange for AzureDiskSuitabilityDetail. + */ + public static final AzureDiskSuitabilityDetail MEGABYTES_PER_SECOND_OF_WRITE_OUT_OF_RANGE + = fromString("MegabytesPerSecondOfWriteOutOfRange"); + + /** + * Static value DiskGigabytesConsumedOutOfRange for AzureDiskSuitabilityDetail. + */ + public static final AzureDiskSuitabilityDetail DISK_GIGABYTES_CONSUMED_OUT_OF_RANGE + = fromString("DiskGigabytesConsumedOutOfRange"); + + /** + * Static value DiskGigabytesProvisionedOutOfRange for AzureDiskSuitabilityDetail. + */ + public static final AzureDiskSuitabilityDetail DISK_GIGABYTES_PROVISIONED_OUT_OF_RANGE + = fromString("DiskGigabytesProvisionedOutOfRange"); + + /** + * Creates a new instance of AzureDiskSuitabilityDetail value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureDiskSuitabilityDetail() { + } + + /** + * Creates or finds a AzureDiskSuitabilityDetail from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureDiskSuitabilityDetail. + */ + public static AzureDiskSuitabilityDetail fromString(String name) { + return fromString(name, AzureDiskSuitabilityDetail.class); + } + + /** + * Gets known AzureDiskSuitabilityDetail values. + * + * @return known AzureDiskSuitabilityDetail values. + */ + public static Collection values() { + return values(AzureDiskSuitabilityDetail.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureDiskSuitabilityExplanation.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureDiskSuitabilityExplanation.java new file mode 100644 index 000000000000..f551ecb0c842 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureDiskSuitabilityExplanation.java @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AzureDiskSuitabilityExplanation. + */ +public final class AzureDiskSuitabilityExplanation extends ExpandableStringEnum { + /** + * Static value Unknown for AzureDiskSuitabilityExplanation. + */ + public static final AzureDiskSuitabilityExplanation UNKNOWN = fromString("Unknown"); + + /** + * Static value NotApplicable for AzureDiskSuitabilityExplanation. + */ + public static final AzureDiskSuitabilityExplanation NOT_APPLICABLE = fromString("NotApplicable"); + + /** + * Static value DiskSizeGreaterThanSupported for AzureDiskSuitabilityExplanation. + */ + public static final AzureDiskSuitabilityExplanation DISK_SIZE_GREATER_THAN_SUPPORTED + = fromString("DiskSizeGreaterThanSupported"); + + /** + * Static value NoSuitableDiskSizeForIops for AzureDiskSuitabilityExplanation. + */ + public static final AzureDiskSuitabilityExplanation NO_SUITABLE_DISK_SIZE_FOR_IOPS + = fromString("NoSuitableDiskSizeForIops"); + + /** + * Static value NoSuitableDiskSizeForThroughput for AzureDiskSuitabilityExplanation. + */ + public static final AzureDiskSuitabilityExplanation NO_SUITABLE_DISK_SIZE_FOR_THROUGHPUT + = fromString("NoSuitableDiskSizeForThroughput"); + + /** + * Static value NoDiskSizeFoundInSelectedLocation for AzureDiskSuitabilityExplanation. + */ + public static final AzureDiskSuitabilityExplanation NO_DISK_SIZE_FOUND_IN_SELECTED_LOCATION + = fromString("NoDiskSizeFoundInSelectedLocation"); + + /** + * Static value NoDiskSizeFoundForSelectedRedundancy for AzureDiskSuitabilityExplanation. + */ + public static final AzureDiskSuitabilityExplanation NO_DISK_SIZE_FOUND_FOR_SELECTED_REDUNDANCY + = fromString("NoDiskSizeFoundForSelectedRedundancy"); + + /** + * Static value InternalErrorOccurredForDiskEvaluation for AzureDiskSuitabilityExplanation. + */ + public static final AzureDiskSuitabilityExplanation INTERNAL_ERROR_OCCURRED_FOR_DISK_EVALUATION + = fromString("InternalErrorOccurredForDiskEvaluation"); + + /** + * Static value NoEaPriceFoundForDiskSize for AzureDiskSuitabilityExplanation. + */ + public static final AzureDiskSuitabilityExplanation NO_EA_PRICE_FOUND_FOR_DISK_SIZE + = fromString("NoEaPriceFoundForDiskSize"); + + /** + * Creates a new instance of AzureDiskSuitabilityExplanation value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureDiskSuitabilityExplanation() { + } + + /** + * Creates or finds a AzureDiskSuitabilityExplanation from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureDiskSuitabilityExplanation. + */ + public static AzureDiskSuitabilityExplanation fromString(String name) { + return fromString(name, AzureDiskSuitabilityExplanation.class); + } + + /** + * Gets known AzureDiskSuitabilityExplanation values. + * + * @return known AzureDiskSuitabilityExplanation values. + */ + public static Collection values() { + return values(AzureDiskSuitabilityExplanation.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureDiskType.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureDiskType.java new file mode 100644 index 000000000000..847ab83d9d52 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureDiskType.java @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AzureDiskType. + */ +public final class AzureDiskType extends ExpandableStringEnum { + /** + * Static value Unknown for AzureDiskType. + */ + public static final AzureDiskType UNKNOWN = fromString("Unknown"); + + /** + * Static value Standard for AzureDiskType. + */ + public static final AzureDiskType STANDARD = fromString("Standard"); + + /** + * Static value StandardSSD for AzureDiskType. + */ + public static final AzureDiskType STANDARD_SSD = fromString("StandardSSD"); + + /** + * Static value Premium for AzureDiskType. + */ + public static final AzureDiskType PREMIUM = fromString("Premium"); + + /** + * Static value StandardOrPremium for AzureDiskType. + */ + public static final AzureDiskType STANDARD_OR_PREMIUM = fromString("StandardOrPremium"); + + /** + * Static value Ultra for AzureDiskType. + */ + public static final AzureDiskType ULTRA = fromString("Ultra"); + + /** + * Static value PremiumV2 for AzureDiskType. + */ + public static final AzureDiskType PREMIUM_V2 = fromString("PremiumV2"); + + /** + * Creates a new instance of AzureDiskType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureDiskType() { + } + + /** + * Creates or finds a AzureDiskType from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureDiskType. + */ + public static AzureDiskType fromString(String name) { + return fromString(name, AzureDiskType.class); + } + + /** + * Gets known AzureDiskType values. + * + * @return known AzureDiskType values. + */ + public static Collection values() { + return values(AzureDiskType.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureHybridUseBenefit.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureHybridUseBenefit.java new file mode 100644 index 000000000000..4b20e08874ca --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureHybridUseBenefit.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. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AzureHybridUseBenefit. + */ +public final class AzureHybridUseBenefit extends ExpandableStringEnum { + /** + * Static value Unknown for AzureHybridUseBenefit. + */ + public static final AzureHybridUseBenefit UNKNOWN = fromString("Unknown"); + + /** + * Static value Yes for AzureHybridUseBenefit. + */ + public static final AzureHybridUseBenefit YES = fromString("Yes"); + + /** + * Static value No for AzureHybridUseBenefit. + */ + public static final AzureHybridUseBenefit NO = fromString("No"); + + /** + * Creates a new instance of AzureHybridUseBenefit value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureHybridUseBenefit() { + } + + /** + * Creates or finds a AzureHybridUseBenefit from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureHybridUseBenefit. + */ + public static AzureHybridUseBenefit fromString(String name) { + return fromString(name, AzureHybridUseBenefit.class); + } + + /** + * Gets known AzureHybridUseBenefit values. + * + * @return known AzureHybridUseBenefit values. + */ + public static Collection values() { + return values(AzureHybridUseBenefit.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureLocation.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureLocation.java new file mode 100644 index 000000000000..e80f2739b2de --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureLocation.java @@ -0,0 +1,341 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Location for Azure. + */ +public final class AzureLocation extends ExpandableStringEnum { + /** + * Static value Unknown for AzureLocation. + */ + public static final AzureLocation UNKNOWN = fromString("Unknown"); + + /** + * Static value EastAsia for AzureLocation. + */ + public static final AzureLocation EAST_ASIA = fromString("EastAsia"); + + /** + * Static value SoutheastAsia for AzureLocation. + */ + public static final AzureLocation SOUTHEAST_ASIA = fromString("SoutheastAsia"); + + /** + * Static value AustraliaEast for AzureLocation. + */ + public static final AzureLocation AUSTRALIA_EAST = fromString("AustraliaEast"); + + /** + * Static value AustraliaSoutheast for AzureLocation. + */ + public static final AzureLocation AUSTRALIA_SOUTHEAST = fromString("AustraliaSoutheast"); + + /** + * Static value BrazilSouth for AzureLocation. + */ + public static final AzureLocation BRAZIL_SOUTH = fromString("BrazilSouth"); + + /** + * Static value CanadaCentral for AzureLocation. + */ + public static final AzureLocation CANADA_CENTRAL = fromString("CanadaCentral"); + + /** + * Static value CanadaEast for AzureLocation. + */ + public static final AzureLocation CANADA_EAST = fromString("CanadaEast"); + + /** + * Static value WestEurope for AzureLocation. + */ + public static final AzureLocation WEST_EUROPE = fromString("WestEurope"); + + /** + * Static value NorthEurope for AzureLocation. + */ + public static final AzureLocation NORTH_EUROPE = fromString("NorthEurope"); + + /** + * Static value CentralIndia for AzureLocation. + */ + public static final AzureLocation CENTRAL_INDIA = fromString("CentralIndia"); + + /** + * Static value SouthIndia for AzureLocation. + */ + public static final AzureLocation SOUTH_INDIA = fromString("SouthIndia"); + + /** + * Static value WestIndia for AzureLocation. + */ + public static final AzureLocation WEST_INDIA = fromString("WestIndia"); + + /** + * Static value JapanEast for AzureLocation. + */ + public static final AzureLocation JAPAN_EAST = fromString("JapanEast"); + + /** + * Static value JapanWest for AzureLocation. + */ + public static final AzureLocation JAPAN_WEST = fromString("JapanWest"); + + /** + * Static value KoreaCentral for AzureLocation. + */ + public static final AzureLocation KOREA_CENTRAL = fromString("KoreaCentral"); + + /** + * Static value KoreaSouth for AzureLocation. + */ + public static final AzureLocation KOREA_SOUTH = fromString("KoreaSouth"); + + /** + * Static value UkWest for AzureLocation. + */ + public static final AzureLocation UK_WEST = fromString("UkWest"); + + /** + * Static value UkSouth for AzureLocation. + */ + public static final AzureLocation UK_SOUTH = fromString("UkSouth"); + + /** + * Static value NorthCentralUs for AzureLocation. + */ + public static final AzureLocation NORTH_CENTRAL_US = fromString("NorthCentralUs"); + + /** + * Static value EastUs for AzureLocation. + */ + public static final AzureLocation EAST_US = fromString("EastUs"); + + /** + * Static value WestUs2 for AzureLocation. + */ + public static final AzureLocation WEST_US2 = fromString("WestUs2"); + + /** + * Static value SouthCentralUs for AzureLocation. + */ + public static final AzureLocation SOUTH_CENTRAL_US = fromString("SouthCentralUs"); + + /** + * Static value CentralUs for AzureLocation. + */ + public static final AzureLocation CENTRAL_US = fromString("CentralUs"); + + /** + * Static value EastUs2 for AzureLocation. + */ + public static final AzureLocation EAST_US2 = fromString("EastUs2"); + + /** + * Static value WestUs for AzureLocation. + */ + public static final AzureLocation WEST_US = fromString("WestUs"); + + /** + * Static value WestCentralUs for AzureLocation. + */ + public static final AzureLocation WEST_CENTRAL_US = fromString("WestCentralUs"); + + /** + * Static value GermanyCentral for AzureLocation. + */ + public static final AzureLocation GERMANY_CENTRAL = fromString("GermanyCentral"); + + /** + * Static value GermanyNortheast for AzureLocation. + */ + public static final AzureLocation GERMANY_NORTHEAST = fromString("GermanyNortheast"); + + /** + * Static value ChinaNorth for AzureLocation. + */ + public static final AzureLocation CHINA_NORTH = fromString("ChinaNorth"); + + /** + * Static value ChinaEast for AzureLocation. + */ + public static final AzureLocation CHINA_EAST = fromString("ChinaEast"); + + /** + * Static value USGovArizona for AzureLocation. + */ + public static final AzureLocation USGOV_ARIZONA = fromString("USGovArizona"); + + /** + * Static value USGovTexas for AzureLocation. + */ + public static final AzureLocation USGOV_TEXAS = fromString("USGovTexas"); + + /** + * Static value USGovIowa for AzureLocation. + */ + public static final AzureLocation USGOV_IOWA = fromString("USGovIowa"); + + /** + * Static value USGovVirginia for AzureLocation. + */ + public static final AzureLocation USGOV_VIRGINIA = fromString("USGovVirginia"); + + /** + * Static value USDoDCentral for AzureLocation. + */ + public static final AzureLocation USDO_DCENTRAL = fromString("USDoDCentral"); + + /** + * Static value USDoDEast for AzureLocation. + */ + public static final AzureLocation USDO_DEAST = fromString("USDoDEast"); + + /** + * Static value FranceCentral for AzureLocation. + */ + public static final AzureLocation FRANCE_CENTRAL = fromString("FranceCentral"); + + /** + * Static value AustraliaCentral for AzureLocation. + */ + public static final AzureLocation AUSTRALIA_CENTRAL = fromString("AustraliaCentral"); + + /** + * Static value SouthAfricaNorth for AzureLocation. + */ + public static final AzureLocation SOUTH_AFRICA_NORTH = fromString("SouthAfricaNorth"); + + /** + * Static value FranceSouth for AzureLocation. + */ + public static final AzureLocation FRANCE_SOUTH = fromString("FranceSouth"); + + /** + * Static value AustraliaCentral2 for AzureLocation. + */ + public static final AzureLocation AUSTRALIA_CENTRAL2 = fromString("AustraliaCentral2"); + + /** + * Static value SouthAfricaWest for AzureLocation. + */ + public static final AzureLocation SOUTH_AFRICA_WEST = fromString("SouthAfricaWest"); + + /** + * Static value GermanyNorth for AzureLocation. + */ + public static final AzureLocation GERMANY_NORTH = fromString("GermanyNorth"); + + /** + * Static value GermanyWestCentral for AzureLocation. + */ + public static final AzureLocation GERMANY_WEST_CENTRAL = fromString("GermanyWestCentral"); + + /** + * Static value NorwayEast for AzureLocation. + */ + public static final AzureLocation NORWAY_EAST = fromString("NorwayEast"); + + /** + * Static value NorwayWest for AzureLocation. + */ + public static final AzureLocation NORWAY_WEST = fromString("NorwayWest"); + + /** + * Static value ChinaEast2 for AzureLocation. + */ + public static final AzureLocation CHINA_EAST2 = fromString("ChinaEast2"); + + /** + * Static value ChinaNorth2 for AzureLocation. + */ + public static final AzureLocation CHINA_NORTH2 = fromString("ChinaNorth2"); + + /** + * Static value SwitzerlandNorth for AzureLocation. + */ + public static final AzureLocation SWITZERLAND_NORTH = fromString("SwitzerlandNorth"); + + /** + * Static value SwitzerlandWest for AzureLocation. + */ + public static final AzureLocation SWITZERLAND_WEST = fromString("SwitzerlandWest"); + + /** + * Static value UAENorth for AzureLocation. + */ + public static final AzureLocation UAENORTH = fromString("UAENorth"); + + /** + * Static value UAECentral for AzureLocation. + */ + public static final AzureLocation UAECENTRAL = fromString("UAECentral"); + + /** + * Static value UsNatEast for AzureLocation. + */ + public static final AzureLocation US_NAT_EAST = fromString("UsNatEast"); + + /** + * Static value UsNatWest for AzureLocation. + */ + public static final AzureLocation US_NAT_WEST = fromString("UsNatWest"); + + /** + * Static value UsSecEast for AzureLocation. + */ + public static final AzureLocation US_SEC_EAST = fromString("UsSecEast"); + + /** + * Static value UsSecCentral for AzureLocation. + */ + public static final AzureLocation US_SEC_CENTRAL = fromString("UsSecCentral"); + + /** + * Static value UsSecWest for AzureLocation. + */ + public static final AzureLocation US_SEC_WEST = fromString("UsSecWest"); + + /** + * Static value SwedenCentral for AzureLocation. + */ + public static final AzureLocation SWEDEN_CENTRAL = fromString("SwedenCentral"); + + /** + * Static value QatarCentral for AzureLocation. + */ + public static final AzureLocation QATAR_CENTRAL = fromString("QatarCentral"); + + /** + * Creates a new instance of AzureLocation value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureLocation() { + } + + /** + * Creates or finds a AzureLocation from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureLocation. + */ + public static AzureLocation fromString(String name) { + return fromString(name, AzureLocation.class); + } + + /** + * Gets known AzureLocation values. + * + * @return known AzureLocation values. + */ + public static Collection values() { + return values(AzureLocation.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureManagedDiskSkuDto.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureManagedDiskSkuDto.java new file mode 100644 index 000000000000..ca65e3b8dc80 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureManagedDiskSkuDto.java @@ -0,0 +1,180 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * Class representing an Azure Managed Disk SKU. + */ +@Immutable +public final class AzureManagedDiskSkuDto implements JsonSerializable { + /* + * Gets the Type ("tier") of disk - e.g. standard, premium, ultra. + */ + private AzureManagedDiskSkuDtoDiskType diskType; + + /* + * Gets the Size of the managed disk - e.g. P30, P40. + */ + private AzureDiskSize diskSize; + + /* + * Gets disk redundancy - e.g. LRS, ZRS. + */ + private AzureManagedDiskSkuDtoDiskRedundancy diskRedundancy; + + /* + * Gets the managed disk storage cost. + */ + private Float storageCost; + + /* + * Gets the recommended in GB of the managed disk. + */ + private Float recommendedSizeInGib; + + /* + * Gets the recommended throughput in MBPS of the managed disk. + */ + private Float recommendedThroughputInMbps; + + /* + * Gets the recommended IOPS of the managed disk. + */ + private Float recommendedIops; + + /** + * Creates an instance of AzureManagedDiskSkuDto class. + */ + public AzureManagedDiskSkuDto() { + } + + /** + * Get the diskType property: Gets the Type ("tier") of disk - e.g. standard, premium, ultra. + * + * @return the diskType value. + */ + public AzureManagedDiskSkuDtoDiskType diskType() { + return this.diskType; + } + + /** + * Get the diskSize property: Gets the Size of the managed disk - e.g. P30, P40. + * + * @return the diskSize value. + */ + public AzureDiskSize diskSize() { + return this.diskSize; + } + + /** + * Get the diskRedundancy property: Gets disk redundancy - e.g. LRS, ZRS. + * + * @return the diskRedundancy value. + */ + public AzureManagedDiskSkuDtoDiskRedundancy diskRedundancy() { + return this.diskRedundancy; + } + + /** + * Get the storageCost property: Gets the managed disk storage cost. + * + * @return the storageCost value. + */ + public Float storageCost() { + return this.storageCost; + } + + /** + * Get the recommendedSizeInGib property: Gets the recommended in GB of the managed disk. + * + * @return the recommendedSizeInGib value. + */ + public Float recommendedSizeInGib() { + return this.recommendedSizeInGib; + } + + /** + * Get the recommendedThroughputInMbps property: Gets the recommended throughput in MBPS of the managed disk. + * + * @return the recommendedThroughputInMbps value. + */ + public Float recommendedThroughputInMbps() { + return this.recommendedThroughputInMbps; + } + + /** + * Get the recommendedIops property: Gets the recommended IOPS of the managed disk. + * + * @return the recommendedIops value. + */ + public Float recommendedIops() { + return this.recommendedIops; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureManagedDiskSkuDto from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureManagedDiskSkuDto 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 AzureManagedDiskSkuDto. + */ + public static AzureManagedDiskSkuDto fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AzureManagedDiskSkuDto deserializedAzureManagedDiskSkuDto = new AzureManagedDiskSkuDto(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("diskType".equals(fieldName)) { + deserializedAzureManagedDiskSkuDto.diskType + = AzureManagedDiskSkuDtoDiskType.fromString(reader.getString()); + } else if ("diskSize".equals(fieldName)) { + deserializedAzureManagedDiskSkuDto.diskSize = AzureDiskSize.fromString(reader.getString()); + } else if ("diskRedundancy".equals(fieldName)) { + deserializedAzureManagedDiskSkuDto.diskRedundancy + = AzureManagedDiskSkuDtoDiskRedundancy.fromString(reader.getString()); + } else if ("storageCost".equals(fieldName)) { + deserializedAzureManagedDiskSkuDto.storageCost = reader.getNullable(JsonReader::getFloat); + } else if ("recommendedSizeInGib".equals(fieldName)) { + deserializedAzureManagedDiskSkuDto.recommendedSizeInGib = reader.getNullable(JsonReader::getFloat); + } else if ("recommendedThroughputInMbps".equals(fieldName)) { + deserializedAzureManagedDiskSkuDto.recommendedThroughputInMbps + = reader.getNullable(JsonReader::getFloat); + } else if ("recommendedIops".equals(fieldName)) { + deserializedAzureManagedDiskSkuDto.recommendedIops = reader.getNullable(JsonReader::getFloat); + } else { + reader.skipChildren(); + } + } + + return deserializedAzureManagedDiskSkuDto; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureManagedDiskSkuDtoDiskRedundancy.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureManagedDiskSkuDtoDiskRedundancy.java new file mode 100644 index 000000000000..495606d3b98c --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureManagedDiskSkuDtoDiskRedundancy.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AzureManagedDiskSkuDtoDiskRedundancy. + */ +public final class AzureManagedDiskSkuDtoDiskRedundancy + extends ExpandableStringEnum { + /** + * Static value Unknown for AzureManagedDiskSkuDtoDiskRedundancy. + */ + public static final AzureManagedDiskSkuDtoDiskRedundancy UNKNOWN = fromString("Unknown"); + + /** + * Static value LRS for AzureManagedDiskSkuDtoDiskRedundancy. + */ + public static final AzureManagedDiskSkuDtoDiskRedundancy LRS = fromString("LRS"); + + /** + * Static value ZRS for AzureManagedDiskSkuDtoDiskRedundancy. + */ + public static final AzureManagedDiskSkuDtoDiskRedundancy ZRS = fromString("ZRS"); + + /** + * Creates a new instance of AzureManagedDiskSkuDtoDiskRedundancy value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureManagedDiskSkuDtoDiskRedundancy() { + } + + /** + * Creates or finds a AzureManagedDiskSkuDtoDiskRedundancy from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureManagedDiskSkuDtoDiskRedundancy. + */ + public static AzureManagedDiskSkuDtoDiskRedundancy fromString(String name) { + return fromString(name, AzureManagedDiskSkuDtoDiskRedundancy.class); + } + + /** + * Gets known AzureManagedDiskSkuDtoDiskRedundancy values. + * + * @return known AzureManagedDiskSkuDtoDiskRedundancy values. + */ + public static Collection values() { + return values(AzureManagedDiskSkuDtoDiskRedundancy.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureManagedDiskSkuDtoDiskType.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureManagedDiskSkuDtoDiskType.java new file mode 100644 index 000000000000..20137048b6d1 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureManagedDiskSkuDtoDiskType.java @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AzureManagedDiskSkuDtoDiskType. + */ +public final class AzureManagedDiskSkuDtoDiskType extends ExpandableStringEnum { + /** + * Static value Unknown for AzureManagedDiskSkuDtoDiskType. + */ + public static final AzureManagedDiskSkuDtoDiskType UNKNOWN = fromString("Unknown"); + + /** + * Static value Standard for AzureManagedDiskSkuDtoDiskType. + */ + public static final AzureManagedDiskSkuDtoDiskType STANDARD = fromString("Standard"); + + /** + * Static value StandardSSD for AzureManagedDiskSkuDtoDiskType. + */ + public static final AzureManagedDiskSkuDtoDiskType STANDARD_SSD = fromString("StandardSSD"); + + /** + * Static value Premium for AzureManagedDiskSkuDtoDiskType. + */ + public static final AzureManagedDiskSkuDtoDiskType PREMIUM = fromString("Premium"); + + /** + * Static value StandardOrPremium for AzureManagedDiskSkuDtoDiskType. + */ + public static final AzureManagedDiskSkuDtoDiskType STANDARD_OR_PREMIUM = fromString("StandardOrPremium"); + + /** + * Static value Ultra for AzureManagedDiskSkuDtoDiskType. + */ + public static final AzureManagedDiskSkuDtoDiskType ULTRA = fromString("Ultra"); + + /** + * Static value PremiumV2 for AzureManagedDiskSkuDtoDiskType. + */ + public static final AzureManagedDiskSkuDtoDiskType PREMIUM_V2 = fromString("PremiumV2"); + + /** + * Creates a new instance of AzureManagedDiskSkuDtoDiskType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureManagedDiskSkuDtoDiskType() { + } + + /** + * Creates or finds a AzureManagedDiskSkuDtoDiskType from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureManagedDiskSkuDtoDiskType. + */ + public static AzureManagedDiskSkuDtoDiskType fromString(String name) { + return fromString(name, AzureManagedDiskSkuDtoDiskType.class); + } + + /** + * Gets known AzureManagedDiskSkuDtoDiskType values. + * + * @return known AzureManagedDiskSkuDtoDiskType values. + */ + public static Collection values() { + return values(AzureManagedDiskSkuDtoDiskType.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureNetworkAdapterSuitabilityDetail.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureNetworkAdapterSuitabilityDetail.java new file mode 100644 index 000000000000..28c0470ea0a4 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureNetworkAdapterSuitabilityDetail.java @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AzureNetworkAdapterSuitabilityDetail. + */ +public final class AzureNetworkAdapterSuitabilityDetail + extends ExpandableStringEnum { + /** + * Static value None for AzureNetworkAdapterSuitabilityDetail. + */ + public static final AzureNetworkAdapterSuitabilityDetail NONE = fromString("None"); + + /** + * Static value MegabytesOfDataTransmittedMissing for AzureNetworkAdapterSuitabilityDetail. + */ + public static final AzureNetworkAdapterSuitabilityDetail MEGABYTES_OF_DATA_TRANSMITTED_MISSING + = fromString("MegabytesOfDataTransmittedMissing"); + + /** + * Static value MegabytesOfDataTransmittedOutOfRange for AzureNetworkAdapterSuitabilityDetail. + */ + public static final AzureNetworkAdapterSuitabilityDetail MEGABYTES_OF_DATA_TRANSMITTED_OUT_OF_RANGE + = fromString("MegabytesOfDataTransmittedOutOfRange"); + + /** + * Static value MegabytesOfDataRecievedMissing for AzureNetworkAdapterSuitabilityDetail. + */ + public static final AzureNetworkAdapterSuitabilityDetail MEGABYTES_OF_DATA_RECIEVED_MISSING + = fromString("MegabytesOfDataRecievedMissing"); + + /** + * Static value MegabytesOfDataRecievedOutOfRange for AzureNetworkAdapterSuitabilityDetail. + */ + public static final AzureNetworkAdapterSuitabilityDetail MEGABYTES_OF_DATA_RECIEVED_OUT_OF_RANGE + = fromString("MegabytesOfDataRecievedOutOfRange"); + + /** + * Creates a new instance of AzureNetworkAdapterSuitabilityDetail value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureNetworkAdapterSuitabilityDetail() { + } + + /** + * Creates or finds a AzureNetworkAdapterSuitabilityDetail from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureNetworkAdapterSuitabilityDetail. + */ + public static AzureNetworkAdapterSuitabilityDetail fromString(String name) { + return fromString(name, AzureNetworkAdapterSuitabilityDetail.class); + } + + /** + * Gets known AzureNetworkAdapterSuitabilityDetail values. + * + * @return known AzureNetworkAdapterSuitabilityDetail values. + */ + public static Collection values() { + return values(AzureNetworkAdapterSuitabilityDetail.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureNetworkAdapterSuitabilityExplanation.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureNetworkAdapterSuitabilityExplanation.java new file mode 100644 index 000000000000..6d53e8221056 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureNetworkAdapterSuitabilityExplanation.java @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AzureNetworkAdapterSuitabilityExplanation. + */ +public final class AzureNetworkAdapterSuitabilityExplanation + extends ExpandableStringEnum { + /** + * Static value Unknown for AzureNetworkAdapterSuitabilityExplanation. + */ + public static final AzureNetworkAdapterSuitabilityExplanation UNKNOWN = fromString("Unknown"); + + /** + * Static value NotApplicable for AzureNetworkAdapterSuitabilityExplanation. + */ + public static final AzureNetworkAdapterSuitabilityExplanation NOT_APPLICABLE = fromString("NotApplicable"); + + /** + * Static value InternalErrorOccurred for AzureNetworkAdapterSuitabilityExplanation. + */ + public static final AzureNetworkAdapterSuitabilityExplanation INTERNAL_ERROR_OCCURRED + = fromString("InternalErrorOccurred"); + + /** + * Creates a new instance of AzureNetworkAdapterSuitabilityExplanation value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureNetworkAdapterSuitabilityExplanation() { + } + + /** + * Creates or finds a AzureNetworkAdapterSuitabilityExplanation from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureNetworkAdapterSuitabilityExplanation. + */ + public static AzureNetworkAdapterSuitabilityExplanation fromString(String name) { + return fromString(name, AzureNetworkAdapterSuitabilityExplanation.class); + } + + /** + * Gets known AzureNetworkAdapterSuitabilityExplanation values. + * + * @return known AzureNetworkAdapterSuitabilityExplanation values. + */ + public static Collection values() { + return values(AzureNetworkAdapterSuitabilityExplanation.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureOfferCode.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureOfferCode.java new file mode 100644 index 000000000000..58f8cd71a833 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureOfferCode.java @@ -0,0 +1,256 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AzureOfferCode. + */ +public final class AzureOfferCode extends ExpandableStringEnum { + /** + * Static value Unknown for AzureOfferCode. + */ + public static final AzureOfferCode UNKNOWN = fromString("Unknown"); + + /** + * Static value MSAZR0003P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZR0003P = fromString("MSAZR0003P"); + + /** + * Static value MSAZR0044P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZR0044P = fromString("MSAZR0044P"); + + /** + * Static value MSAZR0059P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZR0059P = fromString("MSAZR0059P"); + + /** + * Static value MSAZR0060P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZR0060P = fromString("MSAZR0060P"); + + /** + * Static value MSAZR0062P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZR0062P = fromString("MSAZR0062P"); + + /** + * Static value MSAZR0063P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZR0063P = fromString("MSAZR0063P"); + + /** + * Static value MSAZR0064P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZR0064P = fromString("MSAZR0064P"); + + /** + * Static value MSAZR0029P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZR0029P = fromString("MSAZR0029P"); + + /** + * Static value MSAZR0022P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZR0022P = fromString("MSAZR0022P"); + + /** + * Static value MSAZR0023P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZR0023P = fromString("MSAZR0023P"); + + /** + * Static value MSAZR0148P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZR0148P = fromString("MSAZR0148P"); + + /** + * Static value MSAZR0025P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZR0025P = fromString("MSAZR0025P"); + + /** + * Static value MSAZR0036P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZR0036P = fromString("MSAZR0036P"); + + /** + * Static value MSAZR0120P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZR0120P = fromString("MSAZR0120P"); + + /** + * Static value MSAZR0121P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZR0121P = fromString("MSAZR0121P"); + + /** + * Static value MSAZR0122P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZR0122P = fromString("MSAZR0122P"); + + /** + * Static value MSAZR0123P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZR0123P = fromString("MSAZR0123P"); + + /** + * Static value MSAZR0124P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZR0124P = fromString("MSAZR0124P"); + + /** + * Static value MSAZR0125P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZR0125P = fromString("MSAZR0125P"); + + /** + * Static value MSAZR0126P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZR0126P = fromString("MSAZR0126P"); + + /** + * Static value MSAZR0127P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZR0127P = fromString("MSAZR0127P"); + + /** + * Static value MSAZR0128P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZR0128P = fromString("MSAZR0128P"); + + /** + * Static value MSAZR0129P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZR0129P = fromString("MSAZR0129P"); + + /** + * Static value MSAZR0130P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZR0130P = fromString("MSAZR0130P"); + + /** + * Static value MSAZR0111P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZR0111P = fromString("MSAZR0111P"); + + /** + * Static value MSAZR0144P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZR0144P = fromString("MSAZR0144P"); + + /** + * Static value MSAZR0149P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZR0149P = fromString("MSAZR0149P"); + + /** + * Static value MSMCAZR0044P for AzureOfferCode. + */ + public static final AzureOfferCode MSMCAZR0044P = fromString("MSMCAZR0044P"); + + /** + * Static value MSMCAZR0059P for AzureOfferCode. + */ + public static final AzureOfferCode MSMCAZR0059P = fromString("MSMCAZR0059P"); + + /** + * Static value MSMCAZR0060P for AzureOfferCode. + */ + public static final AzureOfferCode MSMCAZR0060P = fromString("MSMCAZR0060P"); + + /** + * Static value MSMCAZR0063P for AzureOfferCode. + */ + public static final AzureOfferCode MSMCAZR0063P = fromString("MSMCAZR0063P"); + + /** + * Static value MSMCAZR0120P for AzureOfferCode. + */ + public static final AzureOfferCode MSMCAZR0120P = fromString("MSMCAZR0120P"); + + /** + * Static value MSMCAZR0121P for AzureOfferCode. + */ + public static final AzureOfferCode MSMCAZR0121P = fromString("MSMCAZR0121P"); + + /** + * Static value MSMCAZR0125P for AzureOfferCode. + */ + public static final AzureOfferCode MSMCAZR0125P = fromString("MSMCAZR0125P"); + + /** + * Static value MSMCAZR0128P for AzureOfferCode. + */ + public static final AzureOfferCode MSMCAZR0128P = fromString("MSMCAZR0128P"); + + /** + * Static value MSAZRDE0003P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZRDE0003P = fromString("MSAZRDE0003P"); + + /** + * Static value MSAZRDE0044P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZRDE0044P = fromString("MSAZRDE0044P"); + + /** + * Static value MSAZRUSGOV0003P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZRUSGOV0003P = fromString("MSAZRUSGOV0003P"); + + /** + * Static value EA for AzureOfferCode. + */ + public static final AzureOfferCode EA = fromString("EA"); + + /** + * Static value MSAZR0243P for AzureOfferCode. + */ + public static final AzureOfferCode MSAZR0243P = fromString("MSAZR0243P"); + + /** + * Static value SavingsPlan1Year for AzureOfferCode. + */ + public static final AzureOfferCode SAVINGS_PLAN1YEAR = fromString("SavingsPlan1Year"); + + /** + * Static value SavingsPlan3Year for AzureOfferCode. + */ + public static final AzureOfferCode SAVINGS_PLAN3YEAR = fromString("SavingsPlan3Year"); + + /** + * Creates a new instance of AzureOfferCode value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureOfferCode() { + } + + /** + * Creates or finds a AzureOfferCode from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureOfferCode. + */ + public static AzureOfferCode fromString(String name) { + return fromString(name, AzureOfferCode.class); + } + + /** + * Gets known AzureOfferCode values. + * + * @return known AzureOfferCode values. + */ + public static Collection values() { + return values(AzureOfferCode.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzurePricingTier.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzurePricingTier.java new file mode 100644 index 000000000000..661b847399e8 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzurePricingTier.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AzurePricingTier. + */ +public final class AzurePricingTier extends ExpandableStringEnum { + /** + * Static value Standard for AzurePricingTier. + */ + public static final AzurePricingTier STANDARD = fromString("Standard"); + + /** + * Static value Basic for AzurePricingTier. + */ + public static final AzurePricingTier BASIC = fromString("Basic"); + + /** + * Creates a new instance of AzurePricingTier value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzurePricingTier() { + } + + /** + * Creates or finds a AzurePricingTier from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzurePricingTier. + */ + public static AzurePricingTier fromString(String name) { + return fromString(name, AzurePricingTier.class); + } + + /** + * Gets known AzurePricingTier values. + * + * @return known AzurePricingTier values. + */ + public static Collection values() { + return values(AzurePricingTier.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureQuorumWitnessDto.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureQuorumWitnessDto.java new file mode 100644 index 000000000000..1a67b71f2c06 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureQuorumWitnessDto.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. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * Quorum Witness. + */ +@Immutable +public final class AzureQuorumWitnessDto implements JsonSerializable { + /* + * Gets quorum witness type. + */ + private AzureQuorumWitnessDtoQuorumWitnessType quorumWitnessType; + + /** + * Creates an instance of AzureQuorumWitnessDto class. + */ + public AzureQuorumWitnessDto() { + } + + /** + * Get the quorumWitnessType property: Gets quorum witness type. + * + * @return the quorumWitnessType value. + */ + public AzureQuorumWitnessDtoQuorumWitnessType quorumWitnessType() { + return this.quorumWitnessType; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureQuorumWitnessDto from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureQuorumWitnessDto 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 AzureQuorumWitnessDto. + */ + public static AzureQuorumWitnessDto fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AzureQuorumWitnessDto deserializedAzureQuorumWitnessDto = new AzureQuorumWitnessDto(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("quorumWitnessType".equals(fieldName)) { + deserializedAzureQuorumWitnessDto.quorumWitnessType + = AzureQuorumWitnessDtoQuorumWitnessType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedAzureQuorumWitnessDto; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureQuorumWitnessDtoQuorumWitnessType.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureQuorumWitnessDtoQuorumWitnessType.java new file mode 100644 index 000000000000..df0b6b0c2543 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureQuorumWitnessDtoQuorumWitnessType.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AzureQuorumWitnessDtoQuorumWitnessType. + */ +public final class AzureQuorumWitnessDtoQuorumWitnessType + extends ExpandableStringEnum { + /** + * Static value Unknown for AzureQuorumWitnessDtoQuorumWitnessType. + */ + public static final AzureQuorumWitnessDtoQuorumWitnessType UNKNOWN = fromString("Unknown"); + + /** + * Static value Cloud for AzureQuorumWitnessDtoQuorumWitnessType. + */ + public static final AzureQuorumWitnessDtoQuorumWitnessType CLOUD = fromString("Cloud"); + + /** + * Static value Disk for AzureQuorumWitnessDtoQuorumWitnessType. + */ + public static final AzureQuorumWitnessDtoQuorumWitnessType DISK = fromString("Disk"); + + /** + * Creates a new instance of AzureQuorumWitnessDtoQuorumWitnessType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureQuorumWitnessDtoQuorumWitnessType() { + } + + /** + * Creates or finds a AzureQuorumWitnessDtoQuorumWitnessType from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureQuorumWitnessDtoQuorumWitnessType. + */ + public static AzureQuorumWitnessDtoQuorumWitnessType fromString(String name) { + return fromString(name, AzureQuorumWitnessDtoQuorumWitnessType.class); + } + + /** + * Gets known AzureQuorumWitnessDtoQuorumWitnessType values. + * + * @return known AzureQuorumWitnessDtoQuorumWitnessType values. + */ + public static Collection values() { + return values(AzureQuorumWitnessDtoQuorumWitnessType.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureReservedInstance.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureReservedInstance.java new file mode 100644 index 000000000000..d771988466af --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureReservedInstance.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. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AzureReservedInstance. + */ +public final class AzureReservedInstance extends ExpandableStringEnum { + /** + * Static value None for AzureReservedInstance. + */ + public static final AzureReservedInstance NONE = fromString("None"); + + /** + * Static value RI1Year for AzureReservedInstance. + */ + public static final AzureReservedInstance RI1YEAR = fromString("RI1Year"); + + /** + * Static value RI3Year for AzureReservedInstance. + */ + public static final AzureReservedInstance RI3YEAR = fromString("RI3Year"); + + /** + * Creates a new instance of AzureReservedInstance value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureReservedInstance() { + } + + /** + * Creates or finds a AzureReservedInstance from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureReservedInstance. + */ + public static AzureReservedInstance fromString(String name) { + return fromString(name, AzureReservedInstance.class); + } + + /** + * Gets known AzureReservedInstance values. + * + * @return known AzureReservedInstance values. + */ + public static Collection values() { + return values(AzureReservedInstance.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureResourceProperties.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureResourceProperties.java new file mode 100644 index 000000000000..57e7e76d4abb --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureResourceProperties.java @@ -0,0 +1,95 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * Common properties for all azure tracked and proxy resources. + */ +@Fluent +public class AzureResourceProperties implements JsonSerializable { + /* + * The status of the last operation. + */ + private ProvisioningState provisioningState; + + /** + * Creates an instance of AzureResourceProperties class. + */ + public AzureResourceProperties() { + } + + /** + * Get the provisioningState property: The status of the last operation. + * + * @return the provisioningState value. + */ + public ProvisioningState provisioningState() { + return this.provisioningState; + } + + /** + * Set the provisioningState property: The status of the last operation. + * + * @param provisioningState the provisioningState value to set. + * @return the AzureResourceProperties object itself. + */ + public AzureResourceProperties withProvisioningState(ProvisioningState provisioningState) { + this.provisioningState = provisioningState; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("provisioningState", + this.provisioningState == null ? null : this.provisioningState.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureResourceProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureResourceProperties 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 AzureResourceProperties. + */ + public static AzureResourceProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AzureResourceProperties deserializedAzureResourceProperties = new AzureResourceProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("provisioningState".equals(fieldName)) { + deserializedAzureResourceProperties.provisioningState + = ProvisioningState.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedAzureResourceProperties; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureSecurityOfferingType.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureSecurityOfferingType.java new file mode 100644 index 000000000000..76c5aea4de2b --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureSecurityOfferingType.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AzureSecurityOfferingType. + */ +public final class AzureSecurityOfferingType extends ExpandableStringEnum { + /** + * Static value NO for AzureSecurityOfferingType. + */ + public static final AzureSecurityOfferingType NO = fromString("NO"); + + /** + * Static value MDC for AzureSecurityOfferingType. + */ + public static final AzureSecurityOfferingType MDC = fromString("MDC"); + + /** + * Creates a new instance of AzureSecurityOfferingType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureSecurityOfferingType() { + } + + /** + * Creates or finds a AzureSecurityOfferingType from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureSecurityOfferingType. + */ + public static AzureSecurityOfferingType fromString(String name) { + return fromString(name, AzureSecurityOfferingType.class); + } + + /** + * Gets known AzureSecurityOfferingType values. + * + * @return known AzureSecurityOfferingType values. + */ + public static Collection values() { + return values(AzureSecurityOfferingType.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureSqlDataBaseType.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureSqlDataBaseType.java new file mode 100644 index 000000000000..940b4f054dee --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureSqlDataBaseType.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AzureSqlDataBaseType. + */ +public final class AzureSqlDataBaseType extends ExpandableStringEnum { + /** + * Static value Unknown for AzureSqlDataBaseType. + */ + public static final AzureSqlDataBaseType UNKNOWN = fromString("Unknown"); + + /** + * Static value Automatic for AzureSqlDataBaseType. + */ + public static final AzureSqlDataBaseType AUTOMATIC = fromString("Automatic"); + + /** + * Static value SingleDatabase for AzureSqlDataBaseType. + */ + public static final AzureSqlDataBaseType SINGLE_DATABASE = fromString("SingleDatabase"); + + /** + * Static value ElasticPool for AzureSqlDataBaseType. + */ + public static final AzureSqlDataBaseType ELASTIC_POOL = fromString("ElasticPool"); + + /** + * Creates a new instance of AzureSqlDataBaseType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureSqlDataBaseType() { + } + + /** + * Creates or finds a AzureSqlDataBaseType from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureSqlDataBaseType. + */ + public static AzureSqlDataBaseType fromString(String name) { + return fromString(name, AzureSqlDataBaseType.class); + } + + /** + * Gets known AzureSqlDataBaseType values. + * + * @return known AzureSqlDataBaseType values. + */ + public static Collection values() { + return values(AzureSqlDataBaseType.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureSqlIaasSkuDto.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureSqlIaasSkuDto.java new file mode 100644 index 000000000000..8ab6628fea29 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureSqlIaasSkuDto.java @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; +import java.util.List; + +/** + * Class representing Azure SQL IAAS SKU. + */ +@Immutable +public final class AzureSqlIaasSkuDto implements JsonSerializable { + /* + * Gets the The Azure Compute Virtual Machine. + */ + private AzureVirtualMachineSkuDto virtualMachineSize; + + /* + * Gets the The list of data disk sizes. + */ + private List dataDiskSizes; + + /* + * Gets the The list of log disk sizes. + */ + private List logDiskSizes; + + /* + * Gets the target type. + */ + private TargetType azureSqlTargetType; + + /** + * Creates an instance of AzureSqlIaasSkuDto class. + */ + public AzureSqlIaasSkuDto() { + } + + /** + * Get the virtualMachineSize property: Gets the The Azure Compute Virtual Machine. + * + * @return the virtualMachineSize value. + */ + public AzureVirtualMachineSkuDto virtualMachineSize() { + return this.virtualMachineSize; + } + + /** + * Get the dataDiskSizes property: Gets the The list of data disk sizes. + * + * @return the dataDiskSizes value. + */ + public List dataDiskSizes() { + return this.dataDiskSizes; + } + + /** + * Get the logDiskSizes property: Gets the The list of log disk sizes. + * + * @return the logDiskSizes value. + */ + public List logDiskSizes() { + return this.logDiskSizes; + } + + /** + * Get the azureSqlTargetType property: Gets the target type. + * + * @return the azureSqlTargetType value. + */ + public TargetType azureSqlTargetType() { + return this.azureSqlTargetType; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (virtualMachineSize() != null) { + virtualMachineSize().validate(); + } + if (dataDiskSizes() != null) { + dataDiskSizes().forEach(e -> e.validate()); + } + if (logDiskSizes() != null) { + logDiskSizes().forEach(e -> e.validate()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureSqlIaasSkuDto from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureSqlIaasSkuDto 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 AzureSqlIaasSkuDto. + */ + public static AzureSqlIaasSkuDto fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AzureSqlIaasSkuDto deserializedAzureSqlIaasSkuDto = new AzureSqlIaasSkuDto(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("virtualMachineSize".equals(fieldName)) { + deserializedAzureSqlIaasSkuDto.virtualMachineSize = AzureVirtualMachineSkuDto.fromJson(reader); + } else if ("dataDiskSizes".equals(fieldName)) { + List dataDiskSizes + = reader.readArray(reader1 -> AzureManagedDiskSkuDto.fromJson(reader1)); + deserializedAzureSqlIaasSkuDto.dataDiskSizes = dataDiskSizes; + } else if ("logDiskSizes".equals(fieldName)) { + List logDiskSizes + = reader.readArray(reader1 -> AzureManagedDiskSkuDto.fromJson(reader1)); + deserializedAzureSqlIaasSkuDto.logDiskSizes = logDiskSizes; + } else if ("azureSqlTargetType".equals(fieldName)) { + deserializedAzureSqlIaasSkuDto.azureSqlTargetType = TargetType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedAzureSqlIaasSkuDto; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureSqlInstanceType.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureSqlInstanceType.java new file mode 100644 index 000000000000..e6fe8cc14a11 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureSqlInstanceType.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AzureSqlInstanceType. + */ +public final class AzureSqlInstanceType extends ExpandableStringEnum { + /** + * Static value Unknown for AzureSqlInstanceType. + */ + public static final AzureSqlInstanceType UNKNOWN = fromString("Unknown"); + + /** + * Static value Automatic for AzureSqlInstanceType. + */ + public static final AzureSqlInstanceType AUTOMATIC = fromString("Automatic"); + + /** + * Static value SingleInstance for AzureSqlInstanceType. + */ + public static final AzureSqlInstanceType SINGLE_INSTANCE = fromString("SingleInstance"); + + /** + * Static value InstancePools for AzureSqlInstanceType. + */ + public static final AzureSqlInstanceType INSTANCE_POOLS = fromString("InstancePools"); + + /** + * Creates a new instance of AzureSqlInstanceType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureSqlInstanceType() { + } + + /** + * Creates or finds a AzureSqlInstanceType from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureSqlInstanceType. + */ + public static AzureSqlInstanceType fromString(String name) { + return fromString(name, AzureSqlInstanceType.class); + } + + /** + * Gets known AzureSqlInstanceType values. + * + * @return known AzureSqlInstanceType values. + */ + public static Collection values() { + return values(AzureSqlInstanceType.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureSqlPaasSkuDto.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureSqlPaasSkuDto.java new file mode 100644 index 000000000000..f041c6a3ef67 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureSqlPaasSkuDto.java @@ -0,0 +1,200 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * Class representing Azure SQL PAAS SKU. + */ +@Immutable +public final class AzureSqlPaasSkuDto implements JsonSerializable { + /* + * Gets the service tier. + */ + private AzureSqlServiceTier azureSqlServiceTier; + + /* + * Gets the compute tier. + */ + private ComputeTier azureSqlComputeTier; + + /* + * Gets the hardware generation. + */ + private HardwareGeneration azureSqlHardwareGeneration; + + /* + * Gets the storage maximum size in megabytes. + */ + private Float storageMaxSizeInMB; + + /* + * Gets the predicted data size in megabytes in the Azure SQL, will impact the + * billing cost. + */ + private Float predictedDataSizeInMB; + + /* + * Gets the predicted log size in megabytes in the Azure SQL, will impact the + * billing cost. + */ + private Float predictedLogSizeInMB; + + /* + * Gets the number of cores. + */ + private Integer cores; + + /* + * Gets the target type. + */ + private TargetType azureSqlTargetType; + + /** + * Creates an instance of AzureSqlPaasSkuDto class. + */ + public AzureSqlPaasSkuDto() { + } + + /** + * Get the azureSqlServiceTier property: Gets the service tier. + * + * @return the azureSqlServiceTier value. + */ + public AzureSqlServiceTier azureSqlServiceTier() { + return this.azureSqlServiceTier; + } + + /** + * Get the azureSqlComputeTier property: Gets the compute tier. + * + * @return the azureSqlComputeTier value. + */ + public ComputeTier azureSqlComputeTier() { + return this.azureSqlComputeTier; + } + + /** + * Get the azureSqlHardwareGeneration property: Gets the hardware generation. + * + * @return the azureSqlHardwareGeneration value. + */ + public HardwareGeneration azureSqlHardwareGeneration() { + return this.azureSqlHardwareGeneration; + } + + /** + * Get the storageMaxSizeInMB property: Gets the storage maximum size in megabytes. + * + * @return the storageMaxSizeInMB value. + */ + public Float storageMaxSizeInMB() { + return this.storageMaxSizeInMB; + } + + /** + * Get the predictedDataSizeInMB property: Gets the predicted data size in megabytes in the Azure SQL, will impact + * the + * billing cost. + * + * @return the predictedDataSizeInMB value. + */ + public Float predictedDataSizeInMB() { + return this.predictedDataSizeInMB; + } + + /** + * Get the predictedLogSizeInMB property: Gets the predicted log size in megabytes in the Azure SQL, will impact the + * billing cost. + * + * @return the predictedLogSizeInMB value. + */ + public Float predictedLogSizeInMB() { + return this.predictedLogSizeInMB; + } + + /** + * Get the cores property: Gets the number of cores. + * + * @return the cores value. + */ + public Integer cores() { + return this.cores; + } + + /** + * Get the azureSqlTargetType property: Gets the target type. + * + * @return the azureSqlTargetType value. + */ + public TargetType azureSqlTargetType() { + return this.azureSqlTargetType; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureSqlPaasSkuDto from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureSqlPaasSkuDto 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 AzureSqlPaasSkuDto. + */ + public static AzureSqlPaasSkuDto fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AzureSqlPaasSkuDto deserializedAzureSqlPaasSkuDto = new AzureSqlPaasSkuDto(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("azureSqlServiceTier".equals(fieldName)) { + deserializedAzureSqlPaasSkuDto.azureSqlServiceTier + = AzureSqlServiceTier.fromString(reader.getString()); + } else if ("azureSqlComputeTier".equals(fieldName)) { + deserializedAzureSqlPaasSkuDto.azureSqlComputeTier = ComputeTier.fromString(reader.getString()); + } else if ("azureSqlHardwareGeneration".equals(fieldName)) { + deserializedAzureSqlPaasSkuDto.azureSqlHardwareGeneration + = HardwareGeneration.fromString(reader.getString()); + } else if ("storageMaxSizeInMB".equals(fieldName)) { + deserializedAzureSqlPaasSkuDto.storageMaxSizeInMB = reader.getNullable(JsonReader::getFloat); + } else if ("predictedDataSizeInMB".equals(fieldName)) { + deserializedAzureSqlPaasSkuDto.predictedDataSizeInMB = reader.getNullable(JsonReader::getFloat); + } else if ("predictedLogSizeInMB".equals(fieldName)) { + deserializedAzureSqlPaasSkuDto.predictedLogSizeInMB = reader.getNullable(JsonReader::getFloat); + } else if ("cores".equals(fieldName)) { + deserializedAzureSqlPaasSkuDto.cores = reader.getNullable(JsonReader::getInt); + } else if ("azureSqlTargetType".equals(fieldName)) { + deserializedAzureSqlPaasSkuDto.azureSqlTargetType = TargetType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedAzureSqlPaasSkuDto; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureSqlPurchaseModel.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureSqlPurchaseModel.java new file mode 100644 index 000000000000..724c7be29e48 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureSqlPurchaseModel.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. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AzureSqlPurchaseModel. + */ +public final class AzureSqlPurchaseModel extends ExpandableStringEnum { + /** + * Static value Unknown for AzureSqlPurchaseModel. + */ + public static final AzureSqlPurchaseModel UNKNOWN = fromString("Unknown"); + + /** + * Static value VCore for AzureSqlPurchaseModel. + */ + public static final AzureSqlPurchaseModel VCORE = fromString("VCore"); + + /** + * Static value DTU for AzureSqlPurchaseModel. + */ + public static final AzureSqlPurchaseModel DTU = fromString("DTU"); + + /** + * Creates a new instance of AzureSqlPurchaseModel value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureSqlPurchaseModel() { + } + + /** + * Creates or finds a AzureSqlPurchaseModel from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureSqlPurchaseModel. + */ + public static AzureSqlPurchaseModel fromString(String name) { + return fromString(name, AzureSqlPurchaseModel.class); + } + + /** + * Gets known AzureSqlPurchaseModel values. + * + * @return known AzureSqlPurchaseModel values. + */ + public static Collection values() { + return values(AzureSqlPurchaseModel.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureSqlServiceTier.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureSqlServiceTier.java new file mode 100644 index 000000000000..75d52a4733b1 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureSqlServiceTier.java @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AzureSqlServiceTier. + */ +public final class AzureSqlServiceTier extends ExpandableStringEnum { + /** + * Static value Unknown for AzureSqlServiceTier. + */ + public static final AzureSqlServiceTier UNKNOWN = fromString("Unknown"); + + /** + * Static value Automatic for AzureSqlServiceTier. + */ + public static final AzureSqlServiceTier AUTOMATIC = fromString("Automatic"); + + /** + * Static value GeneralPurpose for AzureSqlServiceTier. + */ + public static final AzureSqlServiceTier GENERAL_PURPOSE = fromString("GeneralPurpose"); + + /** + * Static value BusinessCritical for AzureSqlServiceTier. + */ + public static final AzureSqlServiceTier BUSINESS_CRITICAL = fromString("BusinessCritical"); + + /** + * Static value HyperScale for AzureSqlServiceTier. + */ + public static final AzureSqlServiceTier HYPER_SCALE = fromString("HyperScale"); + + /** + * Creates a new instance of AzureSqlServiceTier value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureSqlServiceTier() { + } + + /** + * Creates or finds a AzureSqlServiceTier from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureSqlServiceTier. + */ + public static AzureSqlServiceTier fromString(String name) { + return fromString(name, AzureSqlServiceTier.class); + } + + /** + * Gets known AzureSqlServiceTier values. + * + * @return known AzureSqlServiceTier values. + */ + public static Collection values() { + return values(AzureSqlServiceTier.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureStorageRedundancy.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureStorageRedundancy.java new file mode 100644 index 000000000000..2b01195310cb --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureStorageRedundancy.java @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AzureStorageRedundancy. + */ +public final class AzureStorageRedundancy extends ExpandableStringEnum { + /** + * Static value Unknown for AzureStorageRedundancy. + */ + public static final AzureStorageRedundancy UNKNOWN = fromString("Unknown"); + + /** + * Static value LocallyRedundant for AzureStorageRedundancy. + */ + public static final AzureStorageRedundancy LOCALLY_REDUNDANT = fromString("LocallyRedundant"); + + /** + * Static value ZoneRedundant for AzureStorageRedundancy. + */ + public static final AzureStorageRedundancy ZONE_REDUNDANT = fromString("ZoneRedundant"); + + /** + * Static value GeoRedundant for AzureStorageRedundancy. + */ + public static final AzureStorageRedundancy GEO_REDUNDANT = fromString("GeoRedundant"); + + /** + * Static value ReadAccessGeoRedundant for AzureStorageRedundancy. + */ + public static final AzureStorageRedundancy READ_ACCESS_GEO_REDUNDANT = fromString("ReadAccessGeoRedundant"); + + /** + * Creates a new instance of AzureStorageRedundancy value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureStorageRedundancy() { + } + + /** + * Creates or finds a AzureStorageRedundancy from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureStorageRedundancy. + */ + public static AzureStorageRedundancy fromString(String name) { + return fromString(name, AzureStorageRedundancy.class); + } + + /** + * Gets known AzureStorageRedundancy values. + * + * @return known AzureStorageRedundancy values. + */ + public static Collection values() { + return values(AzureStorageRedundancy.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureVirtualMachineSkuDto.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureVirtualMachineSkuDto.java new file mode 100644 index 000000000000..ec95ec03a490 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureVirtualMachineSkuDto.java @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * Azure Virtual Machine SKU. + */ +@Immutable +public final class AzureVirtualMachineSkuDto implements JsonSerializable { + /* + * Gets the Virtual Machine Family, for example : standardMSFamily. + */ + private AzureVmFamily azureVmFamily; + + /* + * Gets the Compute Size in vCores. + */ + private Integer cores; + + /* + * Gets the Virtual Machine SKU name,: E.g. : Standard_F16s. + */ + private AzureVmSize azureSkuName; + + /* + * Gets the Available vCores. This can be less than the vCores in the Constrained + * vCPU VM Sizes. + */ + private Integer availableCores; + + /* + * Gets the Max network interfaces. + */ + private Integer maxNetworkInterfaces; + + /** + * Creates an instance of AzureVirtualMachineSkuDto class. + */ + public AzureVirtualMachineSkuDto() { + } + + /** + * Get the azureVmFamily property: Gets the Virtual Machine Family, for example : standardMSFamily. + * + * @return the azureVmFamily value. + */ + public AzureVmFamily azureVmFamily() { + return this.azureVmFamily; + } + + /** + * Get the cores property: Gets the Compute Size in vCores. + * + * @return the cores value. + */ + public Integer cores() { + return this.cores; + } + + /** + * Get the azureSkuName property: Gets the Virtual Machine SKU name,: E.g. : Standard_F16s. + * + * @return the azureSkuName value. + */ + public AzureVmSize azureSkuName() { + return this.azureSkuName; + } + + /** + * Get the availableCores property: Gets the Available vCores. This can be less than the vCores in the Constrained + * vCPU VM Sizes. + * + * @return the availableCores value. + */ + public Integer availableCores() { + return this.availableCores; + } + + /** + * Get the maxNetworkInterfaces property: Gets the Max network interfaces. + * + * @return the maxNetworkInterfaces value. + */ + public Integer maxNetworkInterfaces() { + return this.maxNetworkInterfaces; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureVirtualMachineSkuDto from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureVirtualMachineSkuDto 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 AzureVirtualMachineSkuDto. + */ + public static AzureVirtualMachineSkuDto fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AzureVirtualMachineSkuDto deserializedAzureVirtualMachineSkuDto = new AzureVirtualMachineSkuDto(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("azureVmFamily".equals(fieldName)) { + deserializedAzureVirtualMachineSkuDto.azureVmFamily = AzureVmFamily.fromString(reader.getString()); + } else if ("cores".equals(fieldName)) { + deserializedAzureVirtualMachineSkuDto.cores = reader.getNullable(JsonReader::getInt); + } else if ("azureSkuName".equals(fieldName)) { + deserializedAzureVirtualMachineSkuDto.azureSkuName = AzureVmSize.fromString(reader.getString()); + } else if ("availableCores".equals(fieldName)) { + deserializedAzureVirtualMachineSkuDto.availableCores = reader.getNullable(JsonReader::getInt); + } else if ("maxNetworkInterfaces".equals(fieldName)) { + deserializedAzureVirtualMachineSkuDto.maxNetworkInterfaces = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + + return deserializedAzureVirtualMachineSkuDto; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureVmFamily.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureVmFamily.java new file mode 100644 index 000000000000..3b59bb72087a --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureVmFamily.java @@ -0,0 +1,301 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AzureVmFamily. + */ +public final class AzureVmFamily extends ExpandableStringEnum { + /** + * Static value Unknown for AzureVmFamily. + */ + public static final AzureVmFamily UNKNOWN = fromString("Unknown"); + + /** + * Static value Basic_A0_A4 for AzureVmFamily. + */ + public static final AzureVmFamily BASIC_A0_A4 = fromString("Basic_A0_A4"); + + /** + * Static value Standard_A0_A7 for AzureVmFamily. + */ + public static final AzureVmFamily STANDARD_A0_A7 = fromString("Standard_A0_A7"); + + /** + * Static value Standard_A8_A11 for AzureVmFamily. + */ + public static final AzureVmFamily STANDARD_A8_A11 = fromString("Standard_A8_A11"); + + /** + * Static value Av2_series for AzureVmFamily. + */ + public static final AzureVmFamily AV2_SERIES = fromString("Av2_series"); + + /** + * Static value D_series for AzureVmFamily. + */ + public static final AzureVmFamily D_SERIES = fromString("D_series"); + + /** + * Static value Dv2_series for AzureVmFamily. + */ + public static final AzureVmFamily DV2_SERIES = fromString("Dv2_series"); + + /** + * Static value DS_series for AzureVmFamily. + */ + public static final AzureVmFamily DS_SERIES = fromString("DS_series"); + + /** + * Static value DSv2_series for AzureVmFamily. + */ + public static final AzureVmFamily DSV2_SERIES = fromString("DSv2_series"); + + /** + * Static value F_series for AzureVmFamily. + */ + public static final AzureVmFamily F_SERIES = fromString("F_series"); + + /** + * Static value Fs_series for AzureVmFamily. + */ + public static final AzureVmFamily FS_SERIES = fromString("Fs_series"); + + /** + * Static value G_series for AzureVmFamily. + */ + public static final AzureVmFamily G_SERIES = fromString("G_series"); + + /** + * Static value GS_series for AzureVmFamily. + */ + public static final AzureVmFamily GS_SERIES = fromString("GS_series"); + + /** + * Static value H_series for AzureVmFamily. + */ + public static final AzureVmFamily H_SERIES = fromString("H_series"); + + /** + * Static value Ls_series for AzureVmFamily. + */ + public static final AzureVmFamily LS_SERIES = fromString("Ls_series"); + + /** + * Static value Dsv3_series for AzureVmFamily. + */ + public static final AzureVmFamily DSV3_SERIES = fromString("Dsv3_series"); + + /** + * Static value Dv3_series for AzureVmFamily. + */ + public static final AzureVmFamily DV3_SERIES = fromString("Dv3_series"); + + /** + * Static value Fsv2_series for AzureVmFamily. + */ + public static final AzureVmFamily FSV2_SERIES = fromString("Fsv2_series"); + + /** + * Static value Ev3_series for AzureVmFamily. + */ + public static final AzureVmFamily EV3_SERIES = fromString("Ev3_series"); + + /** + * Static value Esv3_series for AzureVmFamily. + */ + public static final AzureVmFamily ESV3_SERIES = fromString("Esv3_series"); + + /** + * Static value M_series for AzureVmFamily. + */ + public static final AzureVmFamily M_SERIES = fromString("M_series"); + + /** + * Static value DC_Series for AzureVmFamily. + */ + public static final AzureVmFamily DC_SERIES = fromString("DC_Series"); + + /** + * Static value Lsv2_series for AzureVmFamily. + */ + public static final AzureVmFamily LSV2_SERIES = fromString("Lsv2_series"); + + /** + * Static value Ev4_series for AzureVmFamily. + */ + public static final AzureVmFamily EV4_SERIES = fromString("Ev4_series"); + + /** + * Static value Esv4_series for AzureVmFamily. + */ + public static final AzureVmFamily ESV4_SERIES = fromString("Esv4_series"); + + /** + * Static value Edv4_series for AzureVmFamily. + */ + public static final AzureVmFamily EDV4_SERIES = fromString("Edv4_series"); + + /** + * Static value Edsv4_series for AzureVmFamily. + */ + public static final AzureVmFamily EDSV4_SERIES = fromString("Edsv4_series"); + + /** + * Static value Dv4_series for AzureVmFamily. + */ + public static final AzureVmFamily DV4_SERIES = fromString("Dv4_series"); + + /** + * Static value Dsv4_series for AzureVmFamily. + */ + public static final AzureVmFamily DSV4_SERIES = fromString("Dsv4_series"); + + /** + * Static value Ddv4_series for AzureVmFamily. + */ + public static final AzureVmFamily DDV4_SERIES = fromString("Ddv4_series"); + + /** + * Static value Ddsv4_series for AzureVmFamily. + */ + public static final AzureVmFamily DDSV4_SERIES = fromString("Ddsv4_series"); + + /** + * Static value Easv4_series for AzureVmFamily. + */ + public static final AzureVmFamily EASV4_SERIES = fromString("Easv4_series"); + + /** + * Static value Dasv4_series for AzureVmFamily. + */ + public static final AzureVmFamily DASV4_SERIES = fromString("Dasv4_series"); + + /** + * Static value Mv2_series for AzureVmFamily. + */ + public static final AzureVmFamily MV2_SERIES = fromString("Mv2_series"); + + /** + * Static value Eav4_series for AzureVmFamily. + */ + public static final AzureVmFamily EAV4_SERIES = fromString("Eav4_series"); + + /** + * Static value Dav4_series for AzureVmFamily. + */ + public static final AzureVmFamily DAV4_SERIES = fromString("Dav4_series"); + + /** + * Static value Msv2_series for AzureVmFamily. + */ + public static final AzureVmFamily MSV2_SERIES = fromString("Msv2_series"); + + /** + * Static value Mdsv2_series for AzureVmFamily. + */ + public static final AzureVmFamily MDSV2_SERIES = fromString("Mdsv2_series"); + + /** + * Static value Dv5_series for AzureVmFamily. + */ + public static final AzureVmFamily DV5_SERIES = fromString("Dv5_series"); + + /** + * Static value Dsv5_series for AzureVmFamily. + */ + public static final AzureVmFamily DSV5_SERIES = fromString("Dsv5_series"); + + /** + * Static value Ddv5_series for AzureVmFamily. + */ + public static final AzureVmFamily DDV5_SERIES = fromString("Ddv5_series"); + + /** + * Static value Ddsv5_series for AzureVmFamily. + */ + public static final AzureVmFamily DDSV5_SERIES = fromString("Ddsv5_series"); + + /** + * Static value Dasv5_series for AzureVmFamily. + */ + public static final AzureVmFamily DASV5_SERIES = fromString("Dasv5_series"); + + /** + * Static value Dadsv5_series for AzureVmFamily. + */ + public static final AzureVmFamily DADSV5_SERIES = fromString("Dadsv5_series"); + + /** + * Static value Ev5_series for AzureVmFamily. + */ + public static final AzureVmFamily EV5_SERIES = fromString("Ev5_series"); + + /** + * Static value Esv5_series for AzureVmFamily. + */ + public static final AzureVmFamily ESV5_SERIES = fromString("Esv5_series"); + + /** + * Static value Edv5_series for AzureVmFamily. + */ + public static final AzureVmFamily EDV5_SERIES = fromString("Edv5_series"); + + /** + * Static value Edsv5_series for AzureVmFamily. + */ + public static final AzureVmFamily EDSV5_SERIES = fromString("Edsv5_series"); + + /** + * Static value Easv5_series for AzureVmFamily. + */ + public static final AzureVmFamily EASV5_SERIES = fromString("Easv5_series"); + + /** + * Static value Eadsv5_series for AzureVmFamily. + */ + public static final AzureVmFamily EADSV5_SERIES = fromString("Eadsv5_series"); + + /** + * Static value Ebsv5_series for AzureVmFamily. + */ + public static final AzureVmFamily EBSV5_SERIES = fromString("Ebsv5_series"); + + /** + * Static value Ebdsv5_series for AzureVmFamily. + */ + public static final AzureVmFamily EBDSV5_SERIES = fromString("Ebdsv5_series"); + + /** + * Creates a new instance of AzureVmFamily value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureVmFamily() { + } + + /** + * Creates or finds a AzureVmFamily from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureVmFamily. + */ + public static AzureVmFamily fromString(String name) { + return fromString(name, AzureVmFamily.class); + } + + /** + * Gets known AzureVmFamily values. + * + * @return known AzureVmFamily values. + */ + public static Collection values() { + return values(AzureVmFamily.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureVmSize.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureVmSize.java new file mode 100644 index 000000000000..e44f7552dcc7 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureVmSize.java @@ -0,0 +1,2491 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AzureVmSize. + */ +public final class AzureVmSize extends ExpandableStringEnum { + /** + * Static value Unknown for AzureVmSize. + */ + public static final AzureVmSize UNKNOWN = fromString("Unknown"); + + /** + * Static value Basic_A0 for AzureVmSize. + */ + public static final AzureVmSize BASIC_A0 = fromString("Basic_A0"); + + /** + * Static value Basic_A1 for AzureVmSize. + */ + public static final AzureVmSize BASIC_A1 = fromString("Basic_A1"); + + /** + * Static value Basic_A2 for AzureVmSize. + */ + public static final AzureVmSize BASIC_A2 = fromString("Basic_A2"); + + /** + * Static value Basic_A3 for AzureVmSize. + */ + public static final AzureVmSize BASIC_A3 = fromString("Basic_A3"); + + /** + * Static value Basic_A4 for AzureVmSize. + */ + public static final AzureVmSize BASIC_A4 = fromString("Basic_A4"); + + /** + * Static value Standard_A0 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_A0 = fromString("Standard_A0"); + + /** + * Static value Standard_A1 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_A1 = fromString("Standard_A1"); + + /** + * Static value Standard_A2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_A2 = fromString("Standard_A2"); + + /** + * Static value Standard_A3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_A3 = fromString("Standard_A3"); + + /** + * Static value Standard_A4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_A4 = fromString("Standard_A4"); + + /** + * Static value Standard_A5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_A5 = fromString("Standard_A5"); + + /** + * Static value Standard_A6 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_A6 = fromString("Standard_A6"); + + /** + * Static value Standard_A7 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_A7 = fromString("Standard_A7"); + + /** + * Static value Standard_A8 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_A8 = fromString("Standard_A8"); + + /** + * Static value Standard_A9 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_A9 = fromString("Standard_A9"); + + /** + * Static value Standard_A10 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_A10 = fromString("Standard_A10"); + + /** + * Static value Standard_A11 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_A11 = fromString("Standard_A11"); + + /** + * Static value Standard_A1_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_A1_V2 = fromString("Standard_A1_v2"); + + /** + * Static value Standard_A2_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_A2_V2 = fromString("Standard_A2_v2"); + + /** + * Static value Standard_A4_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_A4_V2 = fromString("Standard_A4_v2"); + + /** + * Static value Standard_A8_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_A8_V2 = fromString("Standard_A8_v2"); + + /** + * Static value Standard_A2m_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_A2M_V2 = fromString("Standard_A2m_v2"); + + /** + * Static value Standard_A4m_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_A4M_V2 = fromString("Standard_A4m_v2"); + + /** + * Static value Standard_A8m_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_A8M_V2 = fromString("Standard_A8m_v2"); + + /** + * Static value Standard_D1 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D1 = fromString("Standard_D1"); + + /** + * Static value Standard_D2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D2 = fromString("Standard_D2"); + + /** + * Static value Standard_D3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D3 = fromString("Standard_D3"); + + /** + * Static value Standard_D4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D4 = fromString("Standard_D4"); + + /** + * Static value Standard_D11 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D11 = fromString("Standard_D11"); + + /** + * Static value Standard_D12 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D12 = fromString("Standard_D12"); + + /** + * Static value Standard_D13 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D13 = fromString("Standard_D13"); + + /** + * Static value Standard_D14 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D14 = fromString("Standard_D14"); + + /** + * Static value Standard_D1_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D1_V2 = fromString("Standard_D1_v2"); + + /** + * Static value Standard_D2_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D2_V2 = fromString("Standard_D2_v2"); + + /** + * Static value Standard_D3_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D3_V2 = fromString("Standard_D3_v2"); + + /** + * Static value Standard_D4_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D4_V2 = fromString("Standard_D4_v2"); + + /** + * Static value Standard_D5_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D5_V2 = fromString("Standard_D5_v2"); + + /** + * Static value Standard_D11_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D11_V2 = fromString("Standard_D11_v2"); + + /** + * Static value Standard_D12_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D12_V2 = fromString("Standard_D12_v2"); + + /** + * Static value Standard_D13_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D13_V2 = fromString("Standard_D13_v2"); + + /** + * Static value Standard_D14_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D14_V2 = fromString("Standard_D14_v2"); + + /** + * Static value Standard_D15_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D15_V2 = fromString("Standard_D15_v2"); + + /** + * Static value Standard_DS1 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_DS1 = fromString("Standard_DS1"); + + /** + * Static value Standard_DS2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_DS2 = fromString("Standard_DS2"); + + /** + * Static value Standard_DS3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_DS3 = fromString("Standard_DS3"); + + /** + * Static value Standard_DS4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_DS4 = fromString("Standard_DS4"); + + /** + * Static value Standard_DS11 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_DS11 = fromString("Standard_DS11"); + + /** + * Static value Standard_DS12 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_DS12 = fromString("Standard_DS12"); + + /** + * Static value Standard_DS13 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_DS13 = fromString("Standard_DS13"); + + /** + * Static value Standard_DS14 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_DS14 = fromString("Standard_DS14"); + + /** + * Static value Standard_DS1_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_DS1_V2 = fromString("Standard_DS1_v2"); + + /** + * Static value Standard_DS2_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_DS2_V2 = fromString("Standard_DS2_v2"); + + /** + * Static value Standard_DS3_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_DS3_V2 = fromString("Standard_DS3_v2"); + + /** + * Static value Standard_DS4_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_DS4_V2 = fromString("Standard_DS4_v2"); + + /** + * Static value Standard_DS5_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_DS5_V2 = fromString("Standard_DS5_v2"); + + /** + * Static value Standard_DS11_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_DS11_V2 = fromString("Standard_DS11_v2"); + + /** + * Static value Standard_DS12_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_DS12_V2 = fromString("Standard_DS12_v2"); + + /** + * Static value Standard_DS13_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_DS13_V2 = fromString("Standard_DS13_v2"); + + /** + * Static value Standard_DS14_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_DS14_V2 = fromString("Standard_DS14_v2"); + + /** + * Static value Standard_DS15_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_DS15_V2 = fromString("Standard_DS15_v2"); + + /** + * Static value Standard_F1 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_F1 = fromString("Standard_F1"); + + /** + * Static value Standard_F2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_F2 = fromString("Standard_F2"); + + /** + * Static value Standard_F4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_F4 = fromString("Standard_F4"); + + /** + * Static value Standard_F8 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_F8 = fromString("Standard_F8"); + + /** + * Static value Standard_F16 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_F16 = fromString("Standard_F16"); + + /** + * Static value Standard_F1s for AzureVmSize. + */ + public static final AzureVmSize STANDARD_F1S = fromString("Standard_F1s"); + + /** + * Static value Standard_F2s for AzureVmSize. + */ + public static final AzureVmSize STANDARD_F2S = fromString("Standard_F2s"); + + /** + * Static value Standard_F4s for AzureVmSize. + */ + public static final AzureVmSize STANDARD_F4S = fromString("Standard_F4s"); + + /** + * Static value Standard_F8s for AzureVmSize. + */ + public static final AzureVmSize STANDARD_F8S = fromString("Standard_F8s"); + + /** + * Static value Standard_F16s for AzureVmSize. + */ + public static final AzureVmSize STANDARD_F16S = fromString("Standard_F16s"); + + /** + * Static value Standard_G1 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_G1 = fromString("Standard_G1"); + + /** + * Static value Standard_G2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_G2 = fromString("Standard_G2"); + + /** + * Static value Standard_G3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_G3 = fromString("Standard_G3"); + + /** + * Static value Standard_G4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_G4 = fromString("Standard_G4"); + + /** + * Static value Standard_G5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_G5 = fromString("Standard_G5"); + + /** + * Static value Standard_GS1 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_GS1 = fromString("Standard_GS1"); + + /** + * Static value Standard_GS2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_GS2 = fromString("Standard_GS2"); + + /** + * Static value Standard_GS3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_GS3 = fromString("Standard_GS3"); + + /** + * Static value Standard_GS4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_GS4 = fromString("Standard_GS4"); + + /** + * Static value Standard_GS5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_GS5 = fromString("Standard_GS5"); + + /** + * Static value Standard_H8 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_H8 = fromString("Standard_H8"); + + /** + * Static value Standard_H16 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_H16 = fromString("Standard_H16"); + + /** + * Static value Standard_H8m for AzureVmSize. + */ + public static final AzureVmSize STANDARD_H8M = fromString("Standard_H8m"); + + /** + * Static value Standard_H16m for AzureVmSize. + */ + public static final AzureVmSize STANDARD_H16M = fromString("Standard_H16m"); + + /** + * Static value Standard_H16r for AzureVmSize. + */ + public static final AzureVmSize STANDARD_H16R = fromString("Standard_H16r"); + + /** + * Static value Standard_H16mr for AzureVmSize. + */ + public static final AzureVmSize STANDARD_H16MR = fromString("Standard_H16mr"); + + /** + * Static value Standard_L4s for AzureVmSize. + */ + public static final AzureVmSize STANDARD_L4S = fromString("Standard_L4s"); + + /** + * Static value Standard_L8s for AzureVmSize. + */ + public static final AzureVmSize STANDARD_L8S = fromString("Standard_L8s"); + + /** + * Static value Standard_L16s for AzureVmSize. + */ + public static final AzureVmSize STANDARD_L16S = fromString("Standard_L16s"); + + /** + * Static value Standard_L32s for AzureVmSize. + */ + public static final AzureVmSize STANDARD_L32S = fromString("Standard_L32s"); + + /** + * Static value Standard_D2s_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D2S_V3 = fromString("Standard_D2s_v3"); + + /** + * Static value Standard_D4s_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D4S_V3 = fromString("Standard_D4s_v3"); + + /** + * Static value Standard_D8s_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D8S_V3 = fromString("Standard_D8s_v3"); + + /** + * Static value Standard_D16s_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D16S_V3 = fromString("Standard_D16s_v3"); + + /** + * Static value Standard_D32s_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D32S_V3 = fromString("Standard_D32s_v3"); + + /** + * Static value Standard_D64s_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D64S_V3 = fromString("Standard_D64s_v3"); + + /** + * Static value Standard_D2_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D2_V3 = fromString("Standard_D2_v3"); + + /** + * Static value Standard_D4_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D4_V3 = fromString("Standard_D4_v3"); + + /** + * Static value Standard_D8_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D8_V3 = fromString("Standard_D8_v3"); + + /** + * Static value Standard_D16_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D16_V3 = fromString("Standard_D16_v3"); + + /** + * Static value Standard_D32_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D32_V3 = fromString("Standard_D32_v3"); + + /** + * Static value Standard_D64_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D64_V3 = fromString("Standard_D64_v3"); + + /** + * Static value Standard_F2s_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_F2S_V2 = fromString("Standard_F2s_v2"); + + /** + * Static value Standard_F4s_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_F4S_V2 = fromString("Standard_F4s_v2"); + + /** + * Static value Standard_F8s_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_F8S_V2 = fromString("Standard_F8s_v2"); + + /** + * Static value Standard_F16s_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_F16S_V2 = fromString("Standard_F16s_v2"); + + /** + * Static value Standard_F32s_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_F32S_V2 = fromString("Standard_F32s_v2"); + + /** + * Static value Standard_F64s_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_F64S_V2 = fromString("Standard_F64s_v2"); + + /** + * Static value Standard_F72s_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_F72S_V2 = fromString("Standard_F72s_v2"); + + /** + * Static value Standard_E2_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E2_V3 = fromString("Standard_E2_v3"); + + /** + * Static value Standard_E4_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E4_V3 = fromString("Standard_E4_v3"); + + /** + * Static value Standard_E8_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8_V3 = fromString("Standard_E8_v3"); + + /** + * Static value Standard_E16_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16_V3 = fromString("Standard_E16_v3"); + + /** + * Static value Standard_E32_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32_V3 = fromString("Standard_E32_v3"); + + /** + * Static value Standard_E64_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64_V3 = fromString("Standard_E64_v3"); + + /** + * Static value Standard_E2s_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E2S_V3 = fromString("Standard_E2s_v3"); + + /** + * Static value Standard_E4s_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E4S_V3 = fromString("Standard_E4s_v3"); + + /** + * Static value Standard_E8s_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8S_V3 = fromString("Standard_E8s_v3"); + + /** + * Static value Standard_E16s_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16S_V3 = fromString("Standard_E16s_v3"); + + /** + * Static value Standard_E32s_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32S_V3 = fromString("Standard_E32s_v3"); + + /** + * Static value Standard_E64s_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64S_V3 = fromString("Standard_E64s_v3"); + + /** + * Static value Standard_M64s for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M64S = fromString("Standard_M64s"); + + /** + * Static value Standard_M64ms for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M64MS = fromString("Standard_M64ms"); + + /** + * Static value Standard_M128s for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M128S = fromString("Standard_M128s"); + + /** + * Static value Standard_M128ms for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M128MS = fromString("Standard_M128ms"); + + /** + * Static value Standard_DC2s for AzureVmSize. + */ + public static final AzureVmSize STANDARD_DC2S = fromString("Standard_DC2s"); + + /** + * Static value Standard_DC4s for AzureVmSize. + */ + public static final AzureVmSize STANDARD_DC4S = fromString("Standard_DC4s"); + + /** + * Static value Standard_E20_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E20_V3 = fromString("Standard_E20_v3"); + + /** + * Static value Standard_E20s_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E20S_V3 = fromString("Standard_E20s_v3"); + + /** + * Static value Standard_E64i_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64I_V3 = fromString("Standard_E64i_v3"); + + /** + * Static value Standard_E64is_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64IS_V3 = fromString("Standard_E64is_v3"); + + /** + * Static value Standard_M8ms for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M8MS = fromString("Standard_M8ms"); + + /** + * Static value Standard_M16ms for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M16MS = fromString("Standard_M16ms"); + + /** + * Static value Standard_M32ls for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M32LS = fromString("Standard_M32ls"); + + /** + * Static value Standard_M32ms for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M32MS = fromString("Standard_M32ms"); + + /** + * Static value Standard_M32ts for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M32TS = fromString("Standard_M32ts"); + + /** + * Static value Standard_M64 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M64 = fromString("Standard_M64"); + + /** + * Static value Standard_M64ls for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M64LS = fromString("Standard_M64ls"); + + /** + * Static value Standard_M64m for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M64M = fromString("Standard_M64m"); + + /** + * Static value Standard_M128 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M128 = fromString("Standard_M128"); + + /** + * Static value Standard_M128m for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M128M = fromString("Standard_M128m"); + + /** + * Static value Standard_L8s_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_L8S_V2 = fromString("Standard_L8s_v2"); + + /** + * Static value Standard_L16s_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_L16S_V2 = fromString("Standard_L16s_v2"); + + /** + * Static value Standard_L32s_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_L32S_V2 = fromString("Standard_L32s_v2"); + + /** + * Static value Standard_L48s_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_L48S_V2 = fromString("Standard_L48s_v2"); + + /** + * Static value Standard_L64s_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_L64S_V2 = fromString("Standard_L64s_v2"); + + /** + * Static value Standard_L80s_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_L80S_V2 = fromString("Standard_L80s_v2"); + + /** + * Static value Standard_D2_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D2_V4 = fromString("Standard_D2_v4"); + + /** + * Static value Standard_D4_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D4_V4 = fromString("Standard_D4_v4"); + + /** + * Static value Standard_D8_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D8_V4 = fromString("Standard_D8_v4"); + + /** + * Static value Standard_D16_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D16_V4 = fromString("Standard_D16_v4"); + + /** + * Static value Standard_D32_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D32_V4 = fromString("Standard_D32_v4"); + + /** + * Static value Standard_D48_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D48_V4 = fromString("Standard_D48_v4"); + + /** + * Static value Standard_D64_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D64_V4 = fromString("Standard_D64_v4"); + + /** + * Static value Standard_D2s_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D2S_V4 = fromString("Standard_D2s_v4"); + + /** + * Static value Standard_D4s_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D4S_V4 = fromString("Standard_D4s_v4"); + + /** + * Static value Standard_D8s_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D8S_V4 = fromString("Standard_D8s_v4"); + + /** + * Static value Standard_D16s_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D16S_V4 = fromString("Standard_D16s_v4"); + + /** + * Static value Standard_D32s_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D32S_V4 = fromString("Standard_D32s_v4"); + + /** + * Static value Standard_D48s_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D48S_V4 = fromString("Standard_D48s_v4"); + + /** + * Static value Standard_D64s_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D64S_V4 = fromString("Standard_D64s_v4"); + + /** + * Static value Standard_D2d_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D2D_V4 = fromString("Standard_D2d_v4"); + + /** + * Static value Standard_D4d_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D4D_V4 = fromString("Standard_D4d_v4"); + + /** + * Static value Standard_D8d_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D8D_V4 = fromString("Standard_D8d_v4"); + + /** + * Static value Standard_D16d_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D16D_V4 = fromString("Standard_D16d_v4"); + + /** + * Static value Standard_D32d_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D32D_V4 = fromString("Standard_D32d_v4"); + + /** + * Static value Standard_D48d_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D48D_V4 = fromString("Standard_D48d_v4"); + + /** + * Static value Standard_D64d_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D64D_V4 = fromString("Standard_D64d_v4"); + + /** + * Static value Standard_D2ds_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D2DS_V4 = fromString("Standard_D2ds_v4"); + + /** + * Static value Standard_D4ds_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D4DS_V4 = fromString("Standard_D4ds_v4"); + + /** + * Static value Standard_D8ds_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D8DS_V4 = fromString("Standard_D8ds_v4"); + + /** + * Static value Standard_D16ds_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D16DS_V4 = fromString("Standard_D16ds_v4"); + + /** + * Static value Standard_D32ds_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D32DS_V4 = fromString("Standard_D32ds_v4"); + + /** + * Static value Standard_D48ds_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D48DS_V4 = fromString("Standard_D48ds_v4"); + + /** + * Static value Standard_D64ds_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D64DS_V4 = fromString("Standard_D64ds_v4"); + + /** + * Static value Standard_E2_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E2_V4 = fromString("Standard_E2_v4"); + + /** + * Static value Standard_E4_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E4_V4 = fromString("Standard_E4_v4"); + + /** + * Static value Standard_E8_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8_V4 = fromString("Standard_E8_v4"); + + /** + * Static value Standard_E16_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16_V4 = fromString("Standard_E16_v4"); + + /** + * Static value Standard_E20_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E20_V4 = fromString("Standard_E20_v4"); + + /** + * Static value Standard_E32_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32_V4 = fromString("Standard_E32_v4"); + + /** + * Static value Standard_E48_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E48_V4 = fromString("Standard_E48_v4"); + + /** + * Static value Standard_E64_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64_V4 = fromString("Standard_E64_v4"); + + /** + * Static value Standard_E2s_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E2S_V4 = fromString("Standard_E2s_v4"); + + /** + * Static value Standard_E4s_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E4S_V4 = fromString("Standard_E4s_v4"); + + /** + * Static value Standard_E8s_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8S_V4 = fromString("Standard_E8s_v4"); + + /** + * Static value Standard_E16s_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16S_V4 = fromString("Standard_E16s_v4"); + + /** + * Static value Standard_E20s_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E20S_V4 = fromString("Standard_E20s_v4"); + + /** + * Static value Standard_E32s_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32S_V4 = fromString("Standard_E32s_v4"); + + /** + * Static value Standard_E48s_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E48S_V4 = fromString("Standard_E48s_v4"); + + /** + * Static value Standard_E64s_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64S_V4 = fromString("Standard_E64s_v4"); + + /** + * Static value Standard_E2d_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E2D_V4 = fromString("Standard_E2d_v4"); + + /** + * Static value Standard_E4d_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E4D_V4 = fromString("Standard_E4d_v4"); + + /** + * Static value Standard_E8d_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8D_V4 = fromString("Standard_E8d_v4"); + + /** + * Static value Standard_E16d_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16D_V4 = fromString("Standard_E16d_v4"); + + /** + * Static value Standard_E20d_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E20D_V4 = fromString("Standard_E20d_v4"); + + /** + * Static value Standard_E32d_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32D_V4 = fromString("Standard_E32d_v4"); + + /** + * Static value Standard_E48d_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E48D_V4 = fromString("Standard_E48d_v4"); + + /** + * Static value Standard_E64d_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64D_V4 = fromString("Standard_E64d_v4"); + + /** + * Static value Standard_E2ds_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E2DS_V4 = fromString("Standard_E2ds_v4"); + + /** + * Static value Standard_E4ds_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E4DS_V4 = fromString("Standard_E4ds_v4"); + + /** + * Static value Standard_E8ds_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8DS_V4 = fromString("Standard_E8ds_v4"); + + /** + * Static value Standard_E16ds_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16DS_V4 = fromString("Standard_E16ds_v4"); + + /** + * Static value Standard_E20ds_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E20DS_V4 = fromString("Standard_E20ds_v4"); + + /** + * Static value Standard_E32ds_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32DS_V4 = fromString("Standard_E32ds_v4"); + + /** + * Static value Standard_E48ds_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E48DS_V4 = fromString("Standard_E48ds_v4"); + + /** + * Static value Standard_E64ds_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64DS_V4 = fromString("Standard_E64ds_v4"); + + /** + * Static value Standard_E2as_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E2AS_V4 = fromString("Standard_E2as_v4"); + + /** + * Static value Standard_E4as_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E4AS_V4 = fromString("Standard_E4as_v4"); + + /** + * Static value Standard_E8as_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8AS_V4 = fromString("Standard_E8as_v4"); + + /** + * Static value Standard_E16as_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16AS_V4 = fromString("Standard_E16as_v4"); + + /** + * Static value Standard_E20as_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E20AS_V4 = fromString("Standard_E20as_v4"); + + /** + * Static value Standard_E32as_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32AS_V4 = fromString("Standard_E32as_v4"); + + /** + * Static value Standard_E48as_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E48AS_V4 = fromString("Standard_E48as_v4"); + + /** + * Static value Standard_E64as_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64AS_V4 = fromString("Standard_E64as_v4"); + + /** + * Static value Standard_E96as_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E96AS_V4 = fromString("Standard_E96as_v4"); + + /** + * Static value Standard_D2as_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D2AS_V4 = fromString("Standard_D2as_v4"); + + /** + * Static value Standard_D4as_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D4AS_V4 = fromString("Standard_D4as_v4"); + + /** + * Static value Standard_D8as_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D8AS_V4 = fromString("Standard_D8as_v4"); + + /** + * Static value Standard_D16as_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D16AS_V4 = fromString("Standard_D16as_v4"); + + /** + * Static value Standard_D32as_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D32AS_V4 = fromString("Standard_D32as_v4"); + + /** + * Static value Standard_D48as_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D48AS_V4 = fromString("Standard_D48as_v4"); + + /** + * Static value Standard_D64as_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D64AS_V4 = fromString("Standard_D64as_v4"); + + /** + * Static value Standard_D96as_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D96AS_V4 = fromString("Standard_D96as_v4"); + + /** + * Static value Standard_M208ms_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M208MS_V2 = fromString("Standard_M208ms_v2"); + + /** + * Static value Standard_M208s_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M208S_V2 = fromString("Standard_M208s_v2"); + + /** + * Static value Standard_M416ms_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M416MS_V2 = fromString("Standard_M416ms_v2"); + + /** + * Static value Standard_M416s_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M416S_V2 = fromString("Standard_M416s_v2"); + + /** + * Static value Standard_F48s_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_F48S_V2 = fromString("Standard_F48s_v2"); + + /** + * Static value Standard_E48_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E48_V3 = fromString("Standard_E48_v3"); + + /** + * Static value Standard_E48s_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E48S_V3 = fromString("Standard_E48s_v3"); + + /** + * Static value Standard_E80is_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E80IS_V4 = fromString("Standard_E80is_v4"); + + /** + * Static value Standard_E80ids_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E80IDS_V4 = fromString("Standard_E80ids_v4"); + + /** + * Static value Standard_E2a_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E2A_V4 = fromString("Standard_E2a_v4"); + + /** + * Static value Standard_E4a_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E4A_V4 = fromString("Standard_E4a_v4"); + + /** + * Static value Standard_E8a_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8A_V4 = fromString("Standard_E8a_v4"); + + /** + * Static value Standard_E16a_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16A_V4 = fromString("Standard_E16a_v4"); + + /** + * Static value Standard_E20a_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E20A_V4 = fromString("Standard_E20a_v4"); + + /** + * Static value Standard_E32a_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32A_V4 = fromString("Standard_E32a_v4"); + + /** + * Static value Standard_E48a_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E48A_V4 = fromString("Standard_E48a_v4"); + + /** + * Static value Standard_E64a_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64A_V4 = fromString("Standard_E64a_v4"); + + /** + * Static value Standard_E96a_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E96A_V4 = fromString("Standard_E96a_v4"); + + /** + * Static value Standard_D2a_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D2A_V4 = fromString("Standard_D2a_v4"); + + /** + * Static value Standard_D4a_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D4A_V4 = fromString("Standard_D4a_v4"); + + /** + * Static value Standard_D8a_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D8A_V4 = fromString("Standard_D8a_v4"); + + /** + * Static value Standard_D16a_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D16A_V4 = fromString("Standard_D16a_v4"); + + /** + * Static value Standard_D32a_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D32A_V4 = fromString("Standard_D32a_v4"); + + /** + * Static value Standard_D48a_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D48A_V4 = fromString("Standard_D48a_v4"); + + /** + * Static value Standard_D64a_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D64A_V4 = fromString("Standard_D64a_v4"); + + /** + * Static value Standard_D96a_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D96A_V4 = fromString("Standard_D96a_v4"); + + /** + * Static value Standard_M32ms_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M32MS_V2 = fromString("Standard_M32ms_v2"); + + /** + * Static value Standard_M64s_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M64S_V2 = fromString("Standard_M64s_v2"); + + /** + * Static value Standard_M64ms_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M64MS_V2 = fromString("Standard_M64ms_v2"); + + /** + * Static value Standard_M128s_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M128S_V2 = fromString("Standard_M128s_v2"); + + /** + * Static value Standard_M128ms_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M128MS_V2 = fromString("Standard_M128ms_v2"); + + /** + * Static value Standard_M192is_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M192IS_V2 = fromString("Standard_M192is_v2"); + + /** + * Static value Standard_M192ims_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M192IMS_V2 = fromString("Standard_M192ims_v2"); + + /** + * Static value Standard_M32dms_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M32DMS_V2 = fromString("Standard_M32dms_v2"); + + /** + * Static value Standard_M64ds_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M64DS_V2 = fromString("Standard_M64ds_v2"); + + /** + * Static value Standard_M64dms_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M64DMS_V2 = fromString("Standard_M64dms_v2"); + + /** + * Static value Standard_M128ds_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M128DS_V2 = fromString("Standard_M128ds_v2"); + + /** + * Static value Standard_M128dms_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M128DMS_V2 = fromString("Standard_M128dms_v2"); + + /** + * Static value Standard_M192ids_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M192IDS_V2 = fromString("Standard_M192ids_v2"); + + /** + * Static value Standard_M192idms_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M192IDMS_V2 = fromString("Standard_M192idms_v2"); + + /** + * Static value Standard_D2_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D2_V5 = fromString("Standard_D2_v5"); + + /** + * Static value Standard_D4_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D4_V5 = fromString("Standard_D4_v5"); + + /** + * Static value Standard_D8_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D8_V5 = fromString("Standard_D8_v5"); + + /** + * Static value Standard_D16_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D16_V5 = fromString("Standard_D16_v5"); + + /** + * Static value Standard_D32_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D32_V5 = fromString("Standard_D32_v5"); + + /** + * Static value Standard_D48_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D48_V5 = fromString("Standard_D48_v5"); + + /** + * Static value Standard_D64_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D64_V5 = fromString("Standard_D64_v5"); + + /** + * Static value Standard_D96_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D96_V5 = fromString("Standard_D96_v5"); + + /** + * Static value Standard_D2s_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D2S_V5 = fromString("Standard_D2s_v5"); + + /** + * Static value Standard_D4s_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D4S_V5 = fromString("Standard_D4s_v5"); + + /** + * Static value Standard_D8s_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D8S_V5 = fromString("Standard_D8s_v5"); + + /** + * Static value Standard_D16s_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D16S_V5 = fromString("Standard_D16s_v5"); + + /** + * Static value Standard_D32s_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D32S_V5 = fromString("Standard_D32s_v5"); + + /** + * Static value Standard_D48s_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D48S_V5 = fromString("Standard_D48s_v5"); + + /** + * Static value Standard_D64s_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D64S_V5 = fromString("Standard_D64s_v5"); + + /** + * Static value Standard_D96s_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D96S_V5 = fromString("Standard_D96s_v5"); + + /** + * Static value Standard_D2d_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D2D_V5 = fromString("Standard_D2d_v5"); + + /** + * Static value Standard_D4d_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D4D_V5 = fromString("Standard_D4d_v5"); + + /** + * Static value Standard_D8d_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D8D_V5 = fromString("Standard_D8d_v5"); + + /** + * Static value Standard_D16d_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D16D_V5 = fromString("Standard_D16d_v5"); + + /** + * Static value Standard_D32d_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D32D_V5 = fromString("Standard_D32d_v5"); + + /** + * Static value Standard_D48d_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D48D_V5 = fromString("Standard_D48d_v5"); + + /** + * Static value Standard_D64d_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D64D_V5 = fromString("Standard_D64d_v5"); + + /** + * Static value Standard_D96d_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D96D_V5 = fromString("Standard_D96d_v5"); + + /** + * Static value Standard_D2ds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D2DS_V5 = fromString("Standard_D2ds_v5"); + + /** + * Static value Standard_D4ds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D4DS_V5 = fromString("Standard_D4ds_v5"); + + /** + * Static value Standard_D8ds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D8DS_V5 = fromString("Standard_D8ds_v5"); + + /** + * Static value Standard_D16ds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D16DS_V5 = fromString("Standard_D16ds_v5"); + + /** + * Static value Standard_D32ds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D32DS_V5 = fromString("Standard_D32ds_v5"); + + /** + * Static value Standard_D48ds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D48DS_V5 = fromString("Standard_D48ds_v5"); + + /** + * Static value Standard_D64ds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D64DS_V5 = fromString("Standard_D64ds_v5"); + + /** + * Static value Standard_D96ds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D96DS_V5 = fromString("Standard_D96ds_v5"); + + /** + * Static value Standard_D2as_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D2AS_V5 = fromString("Standard_D2as_v5"); + + /** + * Static value Standard_D4as_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D4AS_V5 = fromString("Standard_D4as_v5"); + + /** + * Static value Standard_D8as_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D8AS_V5 = fromString("Standard_D8as_v5"); + + /** + * Static value Standard_D16as_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D16AS_V5 = fromString("Standard_D16as_v5"); + + /** + * Static value Standard_D32as_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D32AS_V5 = fromString("Standard_D32as_v5"); + + /** + * Static value Standard_D48as_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D48AS_V5 = fromString("Standard_D48as_v5"); + + /** + * Static value Standard_D64as_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D64AS_V5 = fromString("Standard_D64as_v5"); + + /** + * Static value Standard_D96as_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D96AS_V5 = fromString("Standard_D96as_v5"); + + /** + * Static value Standard_D2ads_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D2ADS_V5 = fromString("Standard_D2ads_v5"); + + /** + * Static value Standard_D4ads_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D4ADS_V5 = fromString("Standard_D4ads_v5"); + + /** + * Static value Standard_D8ads_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D8ADS_V5 = fromString("Standard_D8ads_v5"); + + /** + * Static value Standard_D16ads_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D16ADS_V5 = fromString("Standard_D16ads_v5"); + + /** + * Static value Standard_D32ads_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D32ADS_V5 = fromString("Standard_D32ads_v5"); + + /** + * Static value Standard_D48ads_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D48ADS_V5 = fromString("Standard_D48ads_v5"); + + /** + * Static value Standard_D64ads_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D64ADS_V5 = fromString("Standard_D64ads_v5"); + + /** + * Static value Standard_D96ads_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_D96ADS_V5 = fromString("Standard_D96ads_v5"); + + /** + * Static value Standard_E2_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E2_V5 = fromString("Standard_E2_v5"); + + /** + * Static value Standard_E4_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E4_V5 = fromString("Standard_E4_v5"); + + /** + * Static value Standard_E8_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8_V5 = fromString("Standard_E8_v5"); + + /** + * Static value Standard_E16_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16_V5 = fromString("Standard_E16_v5"); + + /** + * Static value Standard_E20_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E20_V5 = fromString("Standard_E20_v5"); + + /** + * Static value Standard_E32_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32_V5 = fromString("Standard_E32_v5"); + + /** + * Static value Standard_E48_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E48_V5 = fromString("Standard_E48_v5"); + + /** + * Static value Standard_E64_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64_V5 = fromString("Standard_E64_v5"); + + /** + * Static value Standard_E96_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E96_V5 = fromString("Standard_E96_v5"); + + /** + * Static value Standard_E104i_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E104I_V5 = fromString("Standard_E104i_v5"); + + /** + * Static value Standard_E2s_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E2S_V5 = fromString("Standard_E2s_v5"); + + /** + * Static value Standard_E4s_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E4S_V5 = fromString("Standard_E4s_v5"); + + /** + * Static value Standard_E8s_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8S_V5 = fromString("Standard_E8s_v5"); + + /** + * Static value Standard_E16s_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16S_V5 = fromString("Standard_E16s_v5"); + + /** + * Static value Standard_E20s_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E20S_V5 = fromString("Standard_E20s_v5"); + + /** + * Static value Standard_E32s_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32S_V5 = fromString("Standard_E32s_v5"); + + /** + * Static value Standard_E48s_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E48S_V5 = fromString("Standard_E48s_v5"); + + /** + * Static value Standard_E64s_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64S_V5 = fromString("Standard_E64s_v5"); + + /** + * Static value Standard_E96s_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E96S_V5 = fromString("Standard_E96s_v5"); + + /** + * Static value Standard_E104is_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E104IS_V5 = fromString("Standard_E104is_v5"); + + /** + * Static value Standard_E2d_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E2D_V5 = fromString("Standard_E2d_v5"); + + /** + * Static value Standard_E4d_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E4D_V5 = fromString("Standard_E4d_v5"); + + /** + * Static value Standard_E8d_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8D_V5 = fromString("Standard_E8d_v5"); + + /** + * Static value Standard_E16d_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16D_V5 = fromString("Standard_E16d_v5"); + + /** + * Static value Standard_E20d_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E20D_V5 = fromString("Standard_E20d_v5"); + + /** + * Static value Standard_E32d_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32D_V5 = fromString("Standard_E32d_v5"); + + /** + * Static value Standard_E48d_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E48D_V5 = fromString("Standard_E48d_v5"); + + /** + * Static value Standard_E64d_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64D_V5 = fromString("Standard_E64d_v5"); + + /** + * Static value Standard_E96d_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E96D_V5 = fromString("Standard_E96d_v5"); + + /** + * Static value Standard_E104id_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E104ID_V5 = fromString("Standard_E104id_v5"); + + /** + * Static value Standard_E2ds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E2DS_V5 = fromString("Standard_E2ds_v5"); + + /** + * Static value Standard_E4ds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E4DS_V5 = fromString("Standard_E4ds_v5"); + + /** + * Static value Standard_E8ds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8DS_V5 = fromString("Standard_E8ds_v5"); + + /** + * Static value Standard_E16ds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16DS_V5 = fromString("Standard_E16ds_v5"); + + /** + * Static value Standard_E20ds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E20DS_V5 = fromString("Standard_E20ds_v5"); + + /** + * Static value Standard_E32ds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32DS_V5 = fromString("Standard_E32ds_v5"); + + /** + * Static value Standard_E48ds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E48DS_V5 = fromString("Standard_E48ds_v5"); + + /** + * Static value Standard_E64ds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64DS_V5 = fromString("Standard_E64ds_v5"); + + /** + * Static value Standard_E96ds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E96DS_V5 = fromString("Standard_E96ds_v5"); + + /** + * Static value Standard_E104ids_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E104IDS_V5 = fromString("Standard_E104ids_v5"); + + /** + * Static value Standard_E2as_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E2AS_V5 = fromString("Standard_E2as_v5"); + + /** + * Static value Standard_E4as_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E4AS_V5 = fromString("Standard_E4as_v5"); + + /** + * Static value Standard_E8as_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8AS_V5 = fromString("Standard_E8as_v5"); + + /** + * Static value Standard_E16as_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16AS_V5 = fromString("Standard_E16as_v5"); + + /** + * Static value Standard_E20as_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E20AS_V5 = fromString("Standard_E20as_v5"); + + /** + * Static value Standard_E32as_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32AS_V5 = fromString("Standard_E32as_v5"); + + /** + * Static value Standard_E48as_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E48AS_V5 = fromString("Standard_E48as_v5"); + + /** + * Static value Standard_E64as_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64AS_V5 = fromString("Standard_E64as_v5"); + + /** + * Static value Standard_E96as_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E96AS_V5 = fromString("Standard_E96as_v5"); + + /** + * Static value Standard_E2ads_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E2ADS_V5 = fromString("Standard_E2ads_v5"); + + /** + * Static value Standard_E4ads_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E4ADS_V5 = fromString("Standard_E4ads_v5"); + + /** + * Static value Standard_E8ads_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8ADS_V5 = fromString("Standard_E8ads_v5"); + + /** + * Static value Standard_E16ads_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16ADS_V5 = fromString("Standard_E16ads_v5"); + + /** + * Static value Standard_E20ads_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E20ADS_V5 = fromString("Standard_E20ads_v5"); + + /** + * Static value Standard_E32ads_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32ADS_V5 = fromString("Standard_E32ads_v5"); + + /** + * Static value Standard_E48ads_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E48ADS_V5 = fromString("Standard_E48ads_v5"); + + /** + * Static value Standard_E64ads_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64ADS_V5 = fromString("Standard_E64ads_v5"); + + /** + * Static value Standard_E96ads_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E96ADS_V5 = fromString("Standard_E96ads_v5"); + + /** + * Static value Standard_M8_2ms for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M8_2MS = fromString("Standard_M8_2ms"); + + /** + * Static value Standard_M8_4ms for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M8_4MS = fromString("Standard_M8_4ms"); + + /** + * Static value Standard_M16_4ms for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M16_4MS = fromString("Standard_M16_4ms"); + + /** + * Static value Standard_M16_8ms for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M16_8MS = fromString("Standard_M16_8ms"); + + /** + * Static value Standard_M32_8ms for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M32_8MS = fromString("Standard_M32_8ms"); + + /** + * Static value Standard_M32_16ms for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M32_16MS = fromString("Standard_M32_16ms"); + + /** + * Static value Standard_M64_32ms for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M64_32MS = fromString("Standard_M64_32ms"); + + /** + * Static value Standard_M64_16ms for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M64_16MS = fromString("Standard_M64_16ms"); + + /** + * Static value Standard_M128_64ms for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M128_64MS = fromString("Standard_M128_64ms"); + + /** + * Static value Standard_M128_32ms for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M128_32MS = fromString("Standard_M128_32ms"); + + /** + * Static value Standard_E4_2s_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E4_2S_V3 = fromString("Standard_E4_2s_v3"); + + /** + * Static value Standard_E8_4s_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8_4S_V3 = fromString("Standard_E8_4s_v3"); + + /** + * Static value Standard_E8_2s_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8_2S_V3 = fromString("Standard_E8_2s_v3"); + + /** + * Static value Standard_E16_8s_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16_8S_V3 = fromString("Standard_E16_8s_v3"); + + /** + * Static value Standard_E16_4s_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16_4S_V3 = fromString("Standard_E16_4s_v3"); + + /** + * Static value Standard_E32_16s_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32_16S_V3 = fromString("Standard_E32_16s_v3"); + + /** + * Static value Standard_E32_8s_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32_8S_V3 = fromString("Standard_E32_8s_v3"); + + /** + * Static value Standard_E64_32s_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64_32S_V3 = fromString("Standard_E64_32s_v3"); + + /** + * Static value Standard_E64_16s_v3 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64_16S_V3 = fromString("Standard_E64_16s_v3"); + + /** + * Static value Standard_E4_2s_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E4_2S_V4 = fromString("Standard_E4_2s_v4"); + + /** + * Static value Standard_E8_4s_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8_4S_V4 = fromString("Standard_E8_4s_v4"); + + /** + * Static value Standard_E8_2s_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8_2S_V4 = fromString("Standard_E8_2s_v4"); + + /** + * Static value Standard_E16_8s_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16_8S_V4 = fromString("Standard_E16_8s_v4"); + + /** + * Static value Standard_E16_4s_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16_4S_V4 = fromString("Standard_E16_4s_v4"); + + /** + * Static value Standard_E32_16s_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32_16S_V4 = fromString("Standard_E32_16s_v4"); + + /** + * Static value Standard_E32_8s_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32_8S_V4 = fromString("Standard_E32_8s_v4"); + + /** + * Static value Standard_E64_32s_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64_32S_V4 = fromString("Standard_E64_32s_v4"); + + /** + * Static value Standard_E64_16s_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64_16S_V4 = fromString("Standard_E64_16s_v4"); + + /** + * Static value Standard_E4_2ds_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E4_2DS_V4 = fromString("Standard_E4_2ds_v4"); + + /** + * Static value Standard_E8_4ds_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8_4DS_V4 = fromString("Standard_E8_4ds_v4"); + + /** + * Static value Standard_E8_2ds_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8_2DS_V4 = fromString("Standard_E8_2ds_v4"); + + /** + * Static value Standard_E16_8ds_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16_8DS_V4 = fromString("Standard_E16_8ds_v4"); + + /** + * Static value Standard_E16_4ds_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16_4DS_V4 = fromString("Standard_E16_4ds_v4"); + + /** + * Static value Standard_E32_16ds_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32_16DS_V4 = fromString("Standard_E32_16ds_v4"); + + /** + * Static value Standard_E32_8ds_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32_8DS_V4 = fromString("Standard_E32_8ds_v4"); + + /** + * Static value Standard_E64_32ds_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64_32DS_V4 = fromString("Standard_E64_32ds_v4"); + + /** + * Static value Standard_E64_16ds_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64_16DS_V4 = fromString("Standard_E64_16ds_v4"); + + /** + * Static value Standard_E4_2as_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E4_2AS_V4 = fromString("Standard_E4_2as_v4"); + + /** + * Static value Standard_E8_4as_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8_4AS_V4 = fromString("Standard_E8_4as_v4"); + + /** + * Static value Standard_E8_2as_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8_2AS_V4 = fromString("Standard_E8_2as_v4"); + + /** + * Static value Standard_E16_8as_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16_8AS_V4 = fromString("Standard_E16_8as_v4"); + + /** + * Static value Standard_E16_4as_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16_4AS_V4 = fromString("Standard_E16_4as_v4"); + + /** + * Static value Standard_E32_16as_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32_16AS_V4 = fromString("Standard_E32_16as_v4"); + + /** + * Static value Standard_E32_8as_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32_8AS_V4 = fromString("Standard_E32_8as_v4"); + + /** + * Static value Standard_E64_32as_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64_32AS_V4 = fromString("Standard_E64_32as_v4"); + + /** + * Static value Standard_E64_16as_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64_16AS_V4 = fromString("Standard_E64_16as_v4"); + + /** + * Static value Standard_E96_48as_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E96_48AS_V4 = fromString("Standard_E96_48as_v4"); + + /** + * Static value Standard_E96_24as_v4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E96_24AS_V4 = fromString("Standard_E96_24as_v4"); + + /** + * Static value Standard_E4_2ads_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E4_2ADS_V5 = fromString("Standard_E4_2ads_v5"); + + /** + * Static value Standard_E8_4ads_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8_4ADS_V5 = fromString("Standard_E8_4ads_v5"); + + /** + * Static value Standard_E8_2ads_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8_2ADS_V5 = fromString("Standard_E8_2ads_v5"); + + /** + * Static value Standard_E16_8ads_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16_8ADS_V5 = fromString("Standard_E16_8ads_v5"); + + /** + * Static value Standard_E16_4ads_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16_4ADS_V5 = fromString("Standard_E16_4ads_v5"); + + /** + * Static value Standard_E32_16ads_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32_16ADS_V5 = fromString("Standard_E32_16ads_v5"); + + /** + * Static value Standard_E32_8ads_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32_8ADS_V5 = fromString("Standard_E32_8ads_v5"); + + /** + * Static value Standard_E64_32ads_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64_32ADS_V5 = fromString("Standard_E64_32ads_v5"); + + /** + * Static value Standard_E64_16ads_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64_16ADS_V5 = fromString("Standard_E64_16ads_v5"); + + /** + * Static value Standard_E96_48ads_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E96_48ADS_V5 = fromString("Standard_E96_48ads_v5"); + + /** + * Static value Standard_E96_24ads_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E96_24ADS_V5 = fromString("Standard_E96_24ads_v5"); + + /** + * Static value Standard_E4_2s_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E4_2S_V5 = fromString("Standard_E4_2s_v5"); + + /** + * Static value Standard_E8_4s_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8_4S_V5 = fromString("Standard_E8_4s_v5"); + + /** + * Static value Standard_E8_2s_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8_2S_V5 = fromString("Standard_E8_2s_v5"); + + /** + * Static value Standard_E16_8s_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16_8S_V5 = fromString("Standard_E16_8s_v5"); + + /** + * Static value Standard_E16_4s_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16_4S_V5 = fromString("Standard_E16_4s_v5"); + + /** + * Static value Standard_E32_16s_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32_16S_V5 = fromString("Standard_E32_16s_v5"); + + /** + * Static value Standard_E32_8s_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32_8S_V5 = fromString("Standard_E32_8s_v5"); + + /** + * Static value Standard_E64_32s_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64_32S_V5 = fromString("Standard_E64_32s_v5"); + + /** + * Static value Standard_E64_16s_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64_16S_V5 = fromString("Standard_E64_16s_v5"); + + /** + * Static value Standard_E96_48s_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E96_48S_V5 = fromString("Standard_E96_48s_v5"); + + /** + * Static value Standard_E96_24s_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E96_24S_V5 = fromString("Standard_E96_24s_v5"); + + /** + * Static value Standard_E4_2ds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E4_2DS_V5 = fromString("Standard_E4_2ds_v5"); + + /** + * Static value Standard_E8_4ds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8_4DS_V5 = fromString("Standard_E8_4ds_v5"); + + /** + * Static value Standard_E8_2ds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8_2DS_V5 = fromString("Standard_E8_2ds_v5"); + + /** + * Static value Standard_E16_8ds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16_8DS_V5 = fromString("Standard_E16_8ds_v5"); + + /** + * Static value Standard_E16_4ds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16_4DS_V5 = fromString("Standard_E16_4ds_v5"); + + /** + * Static value Standard_E32_16ds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32_16DS_V5 = fromString("Standard_E32_16ds_v5"); + + /** + * Static value Standard_E32_8ds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32_8DS_V5 = fromString("Standard_E32_8ds_v5"); + + /** + * Static value Standard_E64_32ds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64_32DS_V5 = fromString("Standard_E64_32ds_v5"); + + /** + * Static value Standard_E64_16ds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64_16DS_V5 = fromString("Standard_E64_16ds_v5"); + + /** + * Static value Standard_E96_48ds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E96_48DS_V5 = fromString("Standard_E96_48ds_v5"); + + /** + * Static value Standard_E96_24ds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E96_24DS_V5 = fromString("Standard_E96_24ds_v5"); + + /** + * Static value Standard_E4_2as_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E4_2AS_V5 = fromString("Standard_E4_2as_v5"); + + /** + * Static value Standard_E8_4as_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8_4AS_V5 = fromString("Standard_E8_4as_v5"); + + /** + * Static value Standard_E8_2as_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8_2AS_V5 = fromString("Standard_E8_2as_v5"); + + /** + * Static value Standard_E16_8as_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16_8AS_V5 = fromString("Standard_E16_8as_v5"); + + /** + * Static value Standard_E16_4as_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16_4AS_V5 = fromString("Standard_E16_4as_v5"); + + /** + * Static value Standard_E32_16as_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32_16AS_V5 = fromString("Standard_E32_16as_v5"); + + /** + * Static value Standard_E32_8as_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32_8AS_V5 = fromString("Standard_E32_8as_v5"); + + /** + * Static value Standard_E64_32as_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64_32AS_V5 = fromString("Standard_E64_32as_v5"); + + /** + * Static value Standard_E64_16as_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64_16AS_V5 = fromString("Standard_E64_16as_v5"); + + /** + * Static value Standard_E96_48as_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E96_48AS_V5 = fromString("Standard_E96_48as_v5"); + + /** + * Static value Standard_E96_24as_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E96_24AS_V5 = fromString("Standard_E96_24as_v5"); + + /** + * Static value Standard_GS4_8 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_GS4_8 = fromString("Standard_GS4_8"); + + /** + * Static value Standard_GS4_4 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_GS4_4 = fromString("Standard_GS4_4"); + + /** + * Static value Standard_GS5_16 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_GS5_16 = fromString("Standard_GS5_16"); + + /** + * Static value Standard_GS5_8 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_GS5_8 = fromString("Standard_GS5_8"); + + /** + * Static value Standard_DS11_1_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_DS11_1_V2 = fromString("Standard_DS11_1_v2"); + + /** + * Static value Standard_DS12_2_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_DS12_2_V2 = fromString("Standard_DS12_2_v2"); + + /** + * Static value Standard_DS12_1_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_DS12_1_V2 = fromString("Standard_DS12_1_v2"); + + /** + * Static value Standard_DS13_4_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_DS13_4_V2 = fromString("Standard_DS13_4_v2"); + + /** + * Static value Standard_DS13_2_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_DS13_2_V2 = fromString("Standard_DS13_2_v2"); + + /** + * Static value Standard_DS14_8_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_DS14_8_V2 = fromString("Standard_DS14_8_v2"); + + /** + * Static value Standard_DS14_4_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_DS14_4_V2 = fromString("Standard_DS14_4_v2"); + + /** + * Static value Standard_M416_208s_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M416_208S_V2 = fromString("Standard_M416_208s_v2"); + + /** + * Static value Standard_M416_208ms_v2 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_M416_208MS_V2 = fromString("Standard_M416_208ms_v2"); + + /** + * Static value Standard_E2bs_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E2BS_V5 = fromString("Standard_E2bs_v5"); + + /** + * Static value Standard_E4bs_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E4BS_V5 = fromString("Standard_E4bs_v5"); + + /** + * Static value Standard_E8bs_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8BS_V5 = fromString("Standard_E8bs_v5"); + + /** + * Static value Standard_E16bs_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16BS_V5 = fromString("Standard_E16bs_v5"); + + /** + * Static value Standard_E32bs_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32BS_V5 = fromString("Standard_E32bs_v5"); + + /** + * Static value Standard_E48bs_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E48BS_V5 = fromString("Standard_E48bs_v5"); + + /** + * Static value Standard_E64bs_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64BS_V5 = fromString("Standard_E64bs_v5"); + + /** + * Static value Standard_E2bds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E2BDS_V5 = fromString("Standard_E2bds_v5"); + + /** + * Static value Standard_E4bds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E4BDS_V5 = fromString("Standard_E4bds_v5"); + + /** + * Static value Standard_E8bds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E8BDS_V5 = fromString("Standard_E8bds_v5"); + + /** + * Static value Standard_E16bds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E16BDS_V5 = fromString("Standard_E16bds_v5"); + + /** + * Static value Standard_E32bds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E32BDS_V5 = fromString("Standard_E32bds_v5"); + + /** + * Static value Standard_E48bds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E48BDS_V5 = fromString("Standard_E48bds_v5"); + + /** + * Static value Standard_E64bds_v5 for AzureVmSize. + */ + public static final AzureVmSize STANDARD_E64BDS_V5 = fromString("Standard_E64bds_v5"); + + /** + * Creates a new instance of AzureVmSize value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureVmSize() { + } + + /** + * Creates or finds a AzureVmSize from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureVmSize. + */ + public static AzureVmSize fromString(String name) { + return fromString(name, AzureVmSize.class); + } + + /** + * Gets known AzureVmSize values. + * + * @return known AzureVmSize values. + */ + public static Collection values() { + return values(AzureVmSize.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureVmSuitabilityDetail.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureVmSuitabilityDetail.java new file mode 100644 index 000000000000..1df1bcf544b2 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureVmSuitabilityDetail.java @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AzureVmSuitabilityDetail. + */ +public final class AzureVmSuitabilityDetail extends ExpandableStringEnum { + /** + * Static value None for AzureVmSuitabilityDetail. + */ + public static final AzureVmSuitabilityDetail NONE = fromString("None"); + + /** + * Static value RecommendedSizeHasLessNetworkAdapters for AzureVmSuitabilityDetail. + */ + public static final AzureVmSuitabilityDetail RECOMMENDED_SIZE_HAS_LESS_NETWORK_ADAPTERS + = fromString("RecommendedSizeHasLessNetworkAdapters"); + + /** + * Static value CannotReportComputeCost for AzureVmSuitabilityDetail. + */ + public static final AzureVmSuitabilityDetail CANNOT_REPORT_COMPUTE_COST = fromString("CannotReportComputeCost"); + + /** + * Static value CannotReportStorageCost for AzureVmSuitabilityDetail. + */ + public static final AzureVmSuitabilityDetail CANNOT_REPORT_STORAGE_COST = fromString("CannotReportStorageCost"); + + /** + * Static value CannotReportBandwidthCosts for AzureVmSuitabilityDetail. + */ + public static final AzureVmSuitabilityDetail CANNOT_REPORT_BANDWIDTH_COSTS + = fromString("CannotReportBandwidthCosts"); + + /** + * Static value PercentageOfCoresUtilizedMissing for AzureVmSuitabilityDetail. + */ + public static final AzureVmSuitabilityDetail PERCENTAGE_OF_CORES_UTILIZED_MISSING + = fromString("PercentageOfCoresUtilizedMissing"); + + /** + * Static value PercentageOfMemoryUtilizedMissing for AzureVmSuitabilityDetail. + */ + public static final AzureVmSuitabilityDetail PERCENTAGE_OF_MEMORY_UTILIZED_MISSING + = fromString("PercentageOfMemoryUtilizedMissing"); + + /** + * Static value PercentageOfCoresUtilizedOutOfRange for AzureVmSuitabilityDetail. + */ + public static final AzureVmSuitabilityDetail PERCENTAGE_OF_CORES_UTILIZED_OUT_OF_RANGE + = fromString("PercentageOfCoresUtilizedOutOfRange"); + + /** + * Static value PercentageOfMemoryUtilizedOutOfRange for AzureVmSuitabilityDetail. + */ + public static final AzureVmSuitabilityDetail PERCENTAGE_OF_MEMORY_UTILIZED_OUT_OF_RANGE + = fromString("PercentageOfMemoryUtilizedOutOfRange"); + + /** + * Creates a new instance of AzureVmSuitabilityDetail value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureVmSuitabilityDetail() { + } + + /** + * Creates or finds a AzureVmSuitabilityDetail from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureVmSuitabilityDetail. + */ + public static AzureVmSuitabilityDetail fromString(String name) { + return fromString(name, AzureVmSuitabilityDetail.class); + } + + /** + * Gets known AzureVmSuitabilityDetail values. + * + * @return known AzureVmSuitabilityDetail values. + */ + public static Collection values() { + return values(AzureVmSuitabilityDetail.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureVmSuitabilityExplanation.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureVmSuitabilityExplanation.java new file mode 100644 index 000000000000..1b778db3f7e4 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/AzureVmSuitabilityExplanation.java @@ -0,0 +1,267 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for AzureVmSuitabilityExplanation. + */ +public final class AzureVmSuitabilityExplanation extends ExpandableStringEnum { + /** + * Static value Unknown for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation UNKNOWN = fromString("Unknown"); + + /** + * Static value NotApplicable for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation NOT_APPLICABLE = fromString("NotApplicable"); + + /** + * Static value GuestOperatingSystemArchitectureNotSupported for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation GUEST_OPERATING_SYSTEM_ARCHITECTURE_NOT_SUPPORTED + = fromString("GuestOperatingSystemArchitectureNotSupported"); + + /** + * Static value GuestOperatingSystemNotSupported for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation GUEST_OPERATING_SYSTEM_NOT_SUPPORTED + = fromString("GuestOperatingSystemNotSupported"); + + /** + * Static value BootTypeNotSupported for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation BOOT_TYPE_NOT_SUPPORTED = fromString("BootTypeNotSupported"); + + /** + * Static value MoreDisksThanSupported for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation MORE_DISKS_THAN_SUPPORTED = fromString("MoreDisksThanSupported"); + + /** + * Static value NoSuitableVmSizeFound for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation NO_SUITABLE_VM_SIZE_FOUND = fromString("NoSuitableVmSizeFound"); + + /** + * Static value OneOrMoreDisksNotSuitable for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation ONE_OR_MORE_DISKS_NOT_SUITABLE + = fromString("OneOrMoreDisksNotSuitable"); + + /** + * Static value OneOrMoreAdaptersNotSuitable for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation ONE_OR_MORE_ADAPTERS_NOT_SUITABLE + = fromString("OneOrMoreAdaptersNotSuitable"); + + /** + * Static value InternalErrorOccurredDuringComputeEvaluation for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation INTERNAL_ERROR_OCCURRED_DURING_COMPUTE_EVALUATION + = fromString("InternalErrorOccurredDuringComputeEvaluation"); + + /** + * Static value InternalErrorOccurredDuringStorageEvaluation for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation INTERNAL_ERROR_OCCURRED_DURING_STORAGE_EVALUATION + = fromString("InternalErrorOccurredDuringStorageEvaluation"); + + /** + * Static value InternalErrorOccurredDuringNetworkEvaluation for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation INTERNAL_ERROR_OCCURRED_DURING_NETWORK_EVALUATION + = fromString("InternalErrorOccurredDuringNetworkEvaluation"); + + /** + * Static value NoVmSizeSupportsStoragePerformance for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation NO_VM_SIZE_SUPPORTS_STORAGE_PERFORMANCE + = fromString("NoVmSizeSupportsStoragePerformance"); + + /** + * Static value NoVmSizeSupportsNetworkPerformance for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation NO_VM_SIZE_SUPPORTS_NETWORK_PERFORMANCE + = fromString("NoVmSizeSupportsNetworkPerformance"); + + /** + * Static value NoVmSizeForSelectedPricingTier for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation NO_VM_SIZE_FOR_SELECTED_PRICING_TIER + = fromString("NoVmSizeForSelectedPricingTier"); + + /** + * Static value NoVmSizeForSelectedAzureLocation for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation NO_VM_SIZE_FOR_SELECTED_AZURE_LOCATION + = fromString("NoVmSizeForSelectedAzureLocation"); + + /** + * Static value CheckRedHatLinuxVersion for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation CHECK_RED_HAT_LINUX_VERSION + = fromString("CheckRedHatLinuxVersion"); + + /** + * Static value CheckOpenSuseLinuxVersion for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation CHECK_OPEN_SUSE_LINUX_VERSION + = fromString("CheckOpenSuseLinuxVersion"); + + /** + * Static value CheckWindowsServer2008R2Version for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation CHECK_WINDOWS_SERVER2008R2VERSION + = fromString("CheckWindowsServer2008R2Version"); + + /** + * Static value CheckCentOsVersion for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation CHECK_CENT_OS_VERSION = fromString("CheckCentOsVersion"); + + /** + * Static value CheckDebianLinuxVersion for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation CHECK_DEBIAN_LINUX_VERSION + = fromString("CheckDebianLinuxVersion"); + + /** + * Static value CheckSuseLinuxVersion for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation CHECK_SUSE_LINUX_VERSION = fromString("CheckSuseLinuxVersion"); + + /** + * Static value CheckOracleLinuxVersion for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation CHECK_ORACLE_LINUX_VERSION + = fromString("CheckOracleLinuxVersion"); + + /** + * Static value CheckUbuntuLinuxVersion for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation CHECK_UBUNTU_LINUX_VERSION + = fromString("CheckUbuntuLinuxVersion"); + + /** + * Static value CheckCoreOsLinuxVersion for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation CHECK_CORE_OS_LINUX_VERSION + = fromString("CheckCoreOsLinuxVersion"); + + /** + * Static value WindowsServerVersionConditionallySupported for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation WINDOWS_SERVER_VERSION_CONDITIONALLY_SUPPORTED + = fromString("WindowsServerVersionConditionallySupported"); + + /** + * Static value NoGuestOperatingSystemConditionallySupported for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation NO_GUEST_OPERATING_SYSTEM_CONDITIONALLY_SUPPORTED + = fromString("NoGuestOperatingSystemConditionallySupported"); + + /** + * Static value WindowsClientVersionsConditionallySupported for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation WINDOWS_CLIENT_VERSIONS_CONDITIONALLY_SUPPORTED + = fromString("WindowsClientVersionsConditionallySupported"); + + /** + * Static value BootTypeUnknown for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation BOOT_TYPE_UNKNOWN = fromString("BootTypeUnknown"); + + /** + * Static value GuestOperatingSystemUnknown for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation GUEST_OPERATING_SYSTEM_UNKNOWN + = fromString("GuestOperatingSystemUnknown"); + + /** + * Static value WindowsServerVersionsSupportedWithCaveat for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation WINDOWS_SERVER_VERSIONS_SUPPORTED_WITH_CAVEAT + = fromString("WindowsServerVersionsSupportedWithCaveat"); + + /** + * Static value WindowsOSNoLongerUnderMSSupport for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation WINDOWS_OSNO_LONGER_UNDER_MSSUPPORT + = fromString("WindowsOSNoLongerUnderMSSupport"); + + /** + * Static value EndorsedWithConditionsLinuxDistributions for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation ENDORSED_WITH_CONDITIONS_LINUX_DISTRIBUTIONS + = fromString("EndorsedWithConditionsLinuxDistributions"); + + /** + * Static value UnendorsedLinuxDistributions for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation UNENDORSED_LINUX_DISTRIBUTIONS + = fromString("UnendorsedLinuxDistributions"); + + /** + * Static value NoVmSizeForStandardPricingTier for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation NO_VM_SIZE_FOR_STANDARD_PRICING_TIER + = fromString("NoVmSizeForStandardPricingTier"); + + /** + * Static value NoVmSizeForBasicPricingTier for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation NO_VM_SIZE_FOR_BASIC_PRICING_TIER + = fromString("NoVmSizeForBasicPricingTier"); + + /** + * Static value NoVmSizeInSelectedFamilyFound for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation NO_VM_SIZE_IN_SELECTED_FAMILY_FOUND + = fromString("NoVmSizeInSelectedFamilyFound"); + + /** + * Static value NoEaPriceFoundForVmSize for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation NO_EA_PRICE_FOUND_FOR_VM_SIZE + = fromString("NoEaPriceFoundForVmSize"); + + /** + * Static value NoVmSizeFoundForOfferCurrencyReservedInstance for AzureVmSuitabilityExplanation. + */ + public static final AzureVmSuitabilityExplanation NO_VM_SIZE_FOUND_FOR_OFFER_CURRENCY_RESERVED_INSTANCE + = fromString("NoVmSizeFoundForOfferCurrencyReservedInstance"); + + /** + * Creates a new instance of AzureVmSuitabilityExplanation value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureVmSuitabilityExplanation() { + } + + /** + * Creates or finds a AzureVmSuitabilityExplanation from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureVmSuitabilityExplanation. + */ + public static AzureVmSuitabilityExplanation fromString(String name) { + return fromString(name, AzureVmSuitabilityExplanation.class); + } + + /** + * Gets known AzureVmSuitabilityExplanation values. + * + * @return known AzureVmSuitabilityExplanation values. + */ + public static Collection values() { + return values(AzureVmSuitabilityExplanation.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/CloudSuitability.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/CloudSuitability.java new file mode 100644 index 000000000000..0c9ff40db87b --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/CloudSuitability.java @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Cloud Suitability for Azure. + */ +public final class CloudSuitability extends ExpandableStringEnum { + /** + * Static value Unknown for CloudSuitability. + */ + public static final CloudSuitability UNKNOWN = fromString("Unknown"); + + /** + * Static value NotSuitable for CloudSuitability. + */ + public static final CloudSuitability NOT_SUITABLE = fromString("NotSuitable"); + + /** + * Static value Suitable for CloudSuitability. + */ + public static final CloudSuitability SUITABLE = fromString("Suitable"); + + /** + * Static value ConditionallySuitable for CloudSuitability. + */ + public static final CloudSuitability CONDITIONALLY_SUITABLE = fromString("ConditionallySuitable"); + + /** + * Static value ReadinessUnknown for CloudSuitability. + */ + public static final CloudSuitability READINESS_UNKNOWN = fromString("ReadinessUnknown"); + + /** + * Creates a new instance of CloudSuitability value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public CloudSuitability() { + } + + /** + * Creates or finds a CloudSuitability from its string representation. + * + * @param name a name to look for. + * @return the corresponding CloudSuitability. + */ + public static CloudSuitability fromString(String name) { + return fromString(name, CloudSuitability.class); + } + + /** + * Gets known CloudSuitability values. + * + * @return known CloudSuitability values. + */ + public static Collection values() { + return values(CloudSuitability.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/CollectorAgentPropertiesBase.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/CollectorAgentPropertiesBase.java new file mode 100644 index 000000000000..cba35a6a2d9e --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/CollectorAgentPropertiesBase.java @@ -0,0 +1,188 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Collector agent property class. + */ +@Fluent +public final class CollectorAgentPropertiesBase implements JsonSerializable { + /* + * Gets the collector agent id. + */ + private String id; + + /* + * Gets the collector agent version. + */ + private String version; + + /* + * Gets the collector last heartbeat time. + */ + private OffsetDateTime lastHeartbeatUtc; + + /* + * Gets or sets the SPN details. + */ + private CollectorAgentSpnPropertiesBase spnDetails; + + /** + * Creates an instance of CollectorAgentPropertiesBase class. + */ + public CollectorAgentPropertiesBase() { + } + + /** + * Get the id property: Gets the collector agent id. + * + * @return the id value. + */ + public String id() { + return this.id; + } + + /** + * Set the id property: Gets the collector agent id. + * + * @param id the id value to set. + * @return the CollectorAgentPropertiesBase object itself. + */ + public CollectorAgentPropertiesBase withId(String id) { + this.id = id; + return this; + } + + /** + * Get the version property: Gets the collector agent version. + * + * @return the version value. + */ + public String version() { + return this.version; + } + + /** + * Set the version property: Gets the collector agent version. + * + * @param version the version value to set. + * @return the CollectorAgentPropertiesBase object itself. + */ + public CollectorAgentPropertiesBase withVersion(String version) { + this.version = version; + return this; + } + + /** + * Get the lastHeartbeatUtc property: Gets the collector last heartbeat time. + * + * @return the lastHeartbeatUtc value. + */ + public OffsetDateTime lastHeartbeatUtc() { + return this.lastHeartbeatUtc; + } + + /** + * Set the lastHeartbeatUtc property: Gets the collector last heartbeat time. + * + * @param lastHeartbeatUtc the lastHeartbeatUtc value to set. + * @return the CollectorAgentPropertiesBase object itself. + */ + public CollectorAgentPropertiesBase withLastHeartbeatUtc(OffsetDateTime lastHeartbeatUtc) { + this.lastHeartbeatUtc = lastHeartbeatUtc; + return this; + } + + /** + * Get the spnDetails property: Gets or sets the SPN details. + * + * @return the spnDetails value. + */ + public CollectorAgentSpnPropertiesBase spnDetails() { + return this.spnDetails; + } + + /** + * Set the spnDetails property: Gets or sets the SPN details. + * + * @param spnDetails the spnDetails value to set. + * @return the CollectorAgentPropertiesBase object itself. + */ + public CollectorAgentPropertiesBase withSpnDetails(CollectorAgentSpnPropertiesBase spnDetails) { + this.spnDetails = spnDetails; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (spnDetails() != null) { + spnDetails().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("id", this.id); + jsonWriter.writeStringField("version", this.version); + jsonWriter.writeStringField("lastHeartbeatUtc", + this.lastHeartbeatUtc == null + ? null + : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.lastHeartbeatUtc)); + jsonWriter.writeJsonField("spnDetails", this.spnDetails); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of CollectorAgentPropertiesBase from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of CollectorAgentPropertiesBase 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 CollectorAgentPropertiesBase. + */ + public static CollectorAgentPropertiesBase fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CollectorAgentPropertiesBase deserializedCollectorAgentPropertiesBase = new CollectorAgentPropertiesBase(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedCollectorAgentPropertiesBase.id = reader.getString(); + } else if ("version".equals(fieldName)) { + deserializedCollectorAgentPropertiesBase.version = reader.getString(); + } else if ("lastHeartbeatUtc".equals(fieldName)) { + deserializedCollectorAgentPropertiesBase.lastHeartbeatUtc = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("spnDetails".equals(fieldName)) { + deserializedCollectorAgentPropertiesBase.spnDetails + = CollectorAgentSpnPropertiesBase.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedCollectorAgentPropertiesBase; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/CollectorAgentSpnPropertiesBase.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/CollectorAgentSpnPropertiesBase.java new file mode 100644 index 000000000000..266f7be9cfd2 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/CollectorAgentSpnPropertiesBase.java @@ -0,0 +1,206 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * Collector agent SPN details class. + */ +@Fluent +public final class CollectorAgentSpnPropertiesBase implements JsonSerializable { + /* + * Gets the AAD authority endpoint. + */ + private String authority; + + /* + * Gets the AAD application id. + */ + private String applicationId; + + /* + * Gets the AAD audience url. + */ + private String audience; + + /* + * Gets the object id of the AAD application. + */ + private String objectId; + + /* + * Gets the tenant id of the AAD application. + */ + private String tenantId; + + /** + * Creates an instance of CollectorAgentSpnPropertiesBase class. + */ + public CollectorAgentSpnPropertiesBase() { + } + + /** + * Get the authority property: Gets the AAD authority endpoint. + * + * @return the authority value. + */ + public String authority() { + return this.authority; + } + + /** + * Set the authority property: Gets the AAD authority endpoint. + * + * @param authority the authority value to set. + * @return the CollectorAgentSpnPropertiesBase object itself. + */ + public CollectorAgentSpnPropertiesBase withAuthority(String authority) { + this.authority = authority; + return this; + } + + /** + * Get the applicationId property: Gets the AAD application id. + * + * @return the applicationId value. + */ + public String applicationId() { + return this.applicationId; + } + + /** + * Set the applicationId property: Gets the AAD application id. + * + * @param applicationId the applicationId value to set. + * @return the CollectorAgentSpnPropertiesBase object itself. + */ + public CollectorAgentSpnPropertiesBase withApplicationId(String applicationId) { + this.applicationId = applicationId; + return this; + } + + /** + * Get the audience property: Gets the AAD audience url. + * + * @return the audience value. + */ + public String audience() { + return this.audience; + } + + /** + * Set the audience property: Gets the AAD audience url. + * + * @param audience the audience value to set. + * @return the CollectorAgentSpnPropertiesBase object itself. + */ + public CollectorAgentSpnPropertiesBase withAudience(String audience) { + this.audience = audience; + return this; + } + + /** + * Get the objectId property: Gets the object id of the AAD application. + * + * @return the objectId value. + */ + public String objectId() { + return this.objectId; + } + + /** + * Set the objectId property: Gets the object id of the AAD application. + * + * @param objectId the objectId value to set. + * @return the CollectorAgentSpnPropertiesBase object itself. + */ + public CollectorAgentSpnPropertiesBase withObjectId(String objectId) { + this.objectId = objectId; + return this; + } + + /** + * Get the tenantId property: Gets the tenant id of the AAD application. + * + * @return the tenantId value. + */ + public String tenantId() { + return this.tenantId; + } + + /** + * Set the tenantId property: Gets the tenant id of the AAD application. + * + * @param tenantId the tenantId value to set. + * @return the CollectorAgentSpnPropertiesBase object itself. + */ + public CollectorAgentSpnPropertiesBase withTenantId(String tenantId) { + this.tenantId = tenantId; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("authority", this.authority); + jsonWriter.writeStringField("applicationId", this.applicationId); + jsonWriter.writeStringField("audience", this.audience); + jsonWriter.writeStringField("objectId", this.objectId); + jsonWriter.writeStringField("tenantId", this.tenantId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of CollectorAgentSpnPropertiesBase from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of CollectorAgentSpnPropertiesBase 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 CollectorAgentSpnPropertiesBase. + */ + public static CollectorAgentSpnPropertiesBase fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CollectorAgentSpnPropertiesBase deserializedCollectorAgentSpnPropertiesBase + = new CollectorAgentSpnPropertiesBase(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("authority".equals(fieldName)) { + deserializedCollectorAgentSpnPropertiesBase.authority = reader.getString(); + } else if ("applicationId".equals(fieldName)) { + deserializedCollectorAgentSpnPropertiesBase.applicationId = reader.getString(); + } else if ("audience".equals(fieldName)) { + deserializedCollectorAgentSpnPropertiesBase.audience = reader.getString(); + } else if ("objectId".equals(fieldName)) { + deserializedCollectorAgentSpnPropertiesBase.objectId = reader.getString(); + } else if ("tenantId".equals(fieldName)) { + deserializedCollectorAgentSpnPropertiesBase.tenantId = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedCollectorAgentSpnPropertiesBase; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/CollectorPropertiesBase.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/CollectorPropertiesBase.java new file mode 100644 index 000000000000..f02a9c4a7a78 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/CollectorPropertiesBase.java @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; + +/** + * Collector properties class. + */ +@Fluent +public final class CollectorPropertiesBase extends AzureResourceProperties { + /* + * Gets the discovery site id. + */ + private String discoverySiteId; + + /* + * Gets the Timestamp when collector was created. + */ + private OffsetDateTime createdTimestamp; + + /* + * Timestamp when collector was last updated. + */ + private OffsetDateTime updatedTimestamp; + + /** + * Creates an instance of CollectorPropertiesBase class. + */ + public CollectorPropertiesBase() { + } + + /** + * Get the discoverySiteId property: Gets the discovery site id. + * + * @return the discoverySiteId value. + */ + public String discoverySiteId() { + return this.discoverySiteId; + } + + /** + * Set the discoverySiteId property: Gets the discovery site id. + * + * @param discoverySiteId the discoverySiteId value to set. + * @return the CollectorPropertiesBase object itself. + */ + public CollectorPropertiesBase withDiscoverySiteId(String discoverySiteId) { + this.discoverySiteId = discoverySiteId; + return this; + } + + /** + * Get the createdTimestamp property: Gets the Timestamp when collector was created. + * + * @return the createdTimestamp value. + */ + public OffsetDateTime createdTimestamp() { + return this.createdTimestamp; + } + + /** + * Get the updatedTimestamp property: Timestamp when collector was last updated. + * + * @return the updatedTimestamp value. + */ + public OffsetDateTime updatedTimestamp() { + return this.updatedTimestamp; + } + + /** + * {@inheritDoc} + */ + @Override + public CollectorPropertiesBase withProvisioningState(ProvisioningState provisioningState) { + super.withProvisioningState(provisioningState); + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + @Override + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("provisioningState", + provisioningState() == null ? null : provisioningState().toString()); + jsonWriter.writeStringField("discoverySiteId", this.discoverySiteId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of CollectorPropertiesBase from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of CollectorPropertiesBase 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 CollectorPropertiesBase. + */ + public static CollectorPropertiesBase fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CollectorPropertiesBase deserializedCollectorPropertiesBase = new CollectorPropertiesBase(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("provisioningState".equals(fieldName)) { + deserializedCollectorPropertiesBase + .withProvisioningState(ProvisioningState.fromString(reader.getString())); + } else if ("discoverySiteId".equals(fieldName)) { + deserializedCollectorPropertiesBase.discoverySiteId = reader.getString(); + } else if ("createdTimestamp".equals(fieldName)) { + deserializedCollectorPropertiesBase.createdTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("updatedTimestamp".equals(fieldName)) { + deserializedCollectorPropertiesBase.updatedTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else { + reader.skipChildren(); + } + } + + return deserializedCollectorPropertiesBase; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/CollectorPropertiesBaseWithAgent.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/CollectorPropertiesBaseWithAgent.java new file mode 100644 index 000000000000..9b7bb06026c7 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/CollectorPropertiesBaseWithAgent.java @@ -0,0 +1,176 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; + +/** + * Collector properties class. + */ +@Fluent +public final class CollectorPropertiesBaseWithAgent extends AzureResourceProperties { + /* + * Gets or sets the collector agent properties. + */ + private CollectorAgentPropertiesBase agentProperties; + + /* + * Gets the discovery site id. + */ + private String discoverySiteId; + + /* + * Gets the Timestamp when collector was created. + */ + private OffsetDateTime createdTimestamp; + + /* + * Timestamp when collector was last updated. + */ + private OffsetDateTime updatedTimestamp; + + /** + * Creates an instance of CollectorPropertiesBaseWithAgent class. + */ + public CollectorPropertiesBaseWithAgent() { + } + + /** + * Get the agentProperties property: Gets or sets the collector agent properties. + * + * @return the agentProperties value. + */ + public CollectorAgentPropertiesBase agentProperties() { + return this.agentProperties; + } + + /** + * Set the agentProperties property: Gets or sets the collector agent properties. + * + * @param agentProperties the agentProperties value to set. + * @return the CollectorPropertiesBaseWithAgent object itself. + */ + public CollectorPropertiesBaseWithAgent withAgentProperties(CollectorAgentPropertiesBase agentProperties) { + this.agentProperties = agentProperties; + return this; + } + + /** + * Get the discoverySiteId property: Gets the discovery site id. + * + * @return the discoverySiteId value. + */ + public String discoverySiteId() { + return this.discoverySiteId; + } + + /** + * Set the discoverySiteId property: Gets the discovery site id. + * + * @param discoverySiteId the discoverySiteId value to set. + * @return the CollectorPropertiesBaseWithAgent object itself. + */ + public CollectorPropertiesBaseWithAgent withDiscoverySiteId(String discoverySiteId) { + this.discoverySiteId = discoverySiteId; + return this; + } + + /** + * Get the createdTimestamp property: Gets the Timestamp when collector was created. + * + * @return the createdTimestamp value. + */ + public OffsetDateTime createdTimestamp() { + return this.createdTimestamp; + } + + /** + * Get the updatedTimestamp property: Timestamp when collector was last updated. + * + * @return the updatedTimestamp value. + */ + public OffsetDateTime updatedTimestamp() { + return this.updatedTimestamp; + } + + /** + * {@inheritDoc} + */ + @Override + public CollectorPropertiesBaseWithAgent withProvisioningState(ProvisioningState provisioningState) { + super.withProvisioningState(provisioningState); + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + @Override + public void validate() { + if (agentProperties() != null) { + agentProperties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("provisioningState", + provisioningState() == null ? null : provisioningState().toString()); + jsonWriter.writeJsonField("agentProperties", this.agentProperties); + jsonWriter.writeStringField("discoverySiteId", this.discoverySiteId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of CollectorPropertiesBaseWithAgent from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of CollectorPropertiesBaseWithAgent 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 CollectorPropertiesBaseWithAgent. + */ + public static CollectorPropertiesBaseWithAgent fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CollectorPropertiesBaseWithAgent deserializedCollectorPropertiesBaseWithAgent + = new CollectorPropertiesBaseWithAgent(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("provisioningState".equals(fieldName)) { + deserializedCollectorPropertiesBaseWithAgent + .withProvisioningState(ProvisioningState.fromString(reader.getString())); + } else if ("agentProperties".equals(fieldName)) { + deserializedCollectorPropertiesBaseWithAgent.agentProperties + = CollectorAgentPropertiesBase.fromJson(reader); + } else if ("discoverySiteId".equals(fieldName)) { + deserializedCollectorPropertiesBaseWithAgent.discoverySiteId = reader.getString(); + } else if ("createdTimestamp".equals(fieldName)) { + deserializedCollectorPropertiesBaseWithAgent.createdTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("updatedTimestamp".equals(fieldName)) { + deserializedCollectorPropertiesBaseWithAgent.updatedTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else { + reader.skipChildren(); + } + } + + return deserializedCollectorPropertiesBaseWithAgent; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/CompatibilityLevel.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/CompatibilityLevel.java new file mode 100644 index 000000000000..e97b6f2b703a --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/CompatibilityLevel.java @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for CompatibilityLevel. + */ +public final class CompatibilityLevel extends ExpandableStringEnum { + /** + * Static value Unknown for CompatibilityLevel. + */ + public static final CompatibilityLevel UNKNOWN = fromString("Unknown"); + + /** + * Static value CompatLevel80 for CompatibilityLevel. + */ + public static final CompatibilityLevel COMPAT_LEVEL80 = fromString("CompatLevel80"); + + /** + * Static value CompatLevel90 for CompatibilityLevel. + */ + public static final CompatibilityLevel COMPAT_LEVEL90 = fromString("CompatLevel90"); + + /** + * Static value CompatLevel100 for CompatibilityLevel. + */ + public static final CompatibilityLevel COMPAT_LEVEL100 = fromString("CompatLevel100"); + + /** + * Static value CompatLevel110 for CompatibilityLevel. + */ + public static final CompatibilityLevel COMPAT_LEVEL110 = fromString("CompatLevel110"); + + /** + * Static value CompatLevel120 for CompatibilityLevel. + */ + public static final CompatibilityLevel COMPAT_LEVEL120 = fromString("CompatLevel120"); + + /** + * Static value CompatLevel130 for CompatibilityLevel. + */ + public static final CompatibilityLevel COMPAT_LEVEL130 = fromString("CompatLevel130"); + + /** + * Static value CompatLevel140 for CompatibilityLevel. + */ + public static final CompatibilityLevel COMPAT_LEVEL140 = fromString("CompatLevel140"); + + /** + * Static value CompatLevel150 for CompatibilityLevel. + */ + public static final CompatibilityLevel COMPAT_LEVEL150 = fromString("CompatLevel150"); + + /** + * Creates a new instance of CompatibilityLevel value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public CompatibilityLevel() { + } + + /** + * Creates or finds a CompatibilityLevel from its string representation. + * + * @param name a name to look for. + * @return the corresponding CompatibilityLevel. + */ + public static CompatibilityLevel fromString(String name) { + return fromString(name, CompatibilityLevel.class); + } + + /** + * Gets known CompatibilityLevel values. + * + * @return known CompatibilityLevel values. + */ + public static Collection values() { + return values(CompatibilityLevel.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ComputeTier.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ComputeTier.java new file mode 100644 index 000000000000..cbd82f4f8827 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ComputeTier.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for ComputeTier. + */ +public final class ComputeTier extends ExpandableStringEnum { + /** + * Static value Unknown for ComputeTier. + */ + public static final ComputeTier UNKNOWN = fromString("Unknown"); + + /** + * Static value Automatic for ComputeTier. + */ + public static final ComputeTier AUTOMATIC = fromString("Automatic"); + + /** + * Static value Provisioned for ComputeTier. + */ + public static final ComputeTier PROVISIONED = fromString("Provisioned"); + + /** + * Static value Serverless for ComputeTier. + */ + public static final ComputeTier SERVERLESS = fromString("Serverless"); + + /** + * Creates a new instance of ComputeTier value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public ComputeTier() { + } + + /** + * Creates or finds a ComputeTier from its string representation. + * + * @param name a name to look for. + * @return the corresponding ComputeTier. + */ + public static ComputeTier fromString(String name) { + return fromString(name, ComputeTier.class); + } + + /** + * Gets known ComputeTier values. + * + * @return known ComputeTier values. + */ + public static Collection values() { + return values(ComputeTier.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/CostComponent.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/CostComponent.java new file mode 100644 index 000000000000..3f08e0cd70c1 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/CostComponent.java @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * Class to represent the component of the cost. + */ +@Fluent +public final class CostComponent implements JsonSerializable { + /* + * Gets the name of the component. + */ + private CostComponentName name; + + /* + * The value of the component. + */ + private Float value; + + /* + * The textual description of the component. + */ + private String description; + + /** + * Creates an instance of CostComponent class. + */ + public CostComponent() { + } + + /** + * Get the name property: Gets the name of the component. + * + * @return the name value. + */ + public CostComponentName name() { + return this.name; + } + + /** + * Get the value property: The value of the component. + * + * @return the value value. + */ + public Float value() { + return this.value; + } + + /** + * Set the value property: The value of the component. + * + * @param value the value value to set. + * @return the CostComponent object itself. + */ + public CostComponent withValue(Float value) { + this.value = value; + return this; + } + + /** + * Get the description property: The textual description of the component. + * + * @return the description value. + */ + public String description() { + return this.description; + } + + /** + * Set the description property: The textual description of the component. + * + * @param description the description value to set. + * @return the CostComponent object itself. + */ + public CostComponent withDescription(String description) { + this.description = description; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeNumberField("value", this.value); + jsonWriter.writeStringField("description", this.description); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of CostComponent from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of CostComponent 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 CostComponent. + */ + public static CostComponent fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CostComponent deserializedCostComponent = new CostComponent(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("name".equals(fieldName)) { + deserializedCostComponent.name = CostComponentName.fromString(reader.getString()); + } else if ("value".equals(fieldName)) { + deserializedCostComponent.value = reader.getNullable(JsonReader::getFloat); + } else if ("description".equals(fieldName)) { + deserializedCostComponent.description = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedCostComponent; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/CostComponentName.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/CostComponentName.java new file mode 100644 index 000000000000..9e0c4454c89d --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/CostComponentName.java @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Enum to represent component name. + */ +public final class CostComponentName extends ExpandableStringEnum { + /** + * Static value Unknown for CostComponentName. + */ + public static final CostComponentName UNKNOWN = fromString("Unknown"); + + /** + * Static value MonthlyAzureHybridCostSavings for CostComponentName. + */ + public static final CostComponentName MONTHLY_AZURE_HYBRID_COST_SAVINGS + = fromString("MonthlyAzureHybridCostSavings"); + + /** + * Static value MonthlySecurityCost for CostComponentName. + */ + public static final CostComponentName MONTHLY_SECURITY_COST = fromString("MonthlySecurityCost"); + + /** + * Static value MonthlyPremiumV2StorageCost for CostComponentName. + */ + public static final CostComponentName MONTHLY_PREMIUM_V2STORAGE_COST = fromString("MonthlyPremiumV2StorageCost"); + + /** + * Creates a new instance of CostComponentName value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public CostComponentName() { + } + + /** + * Creates or finds a CostComponentName from its string representation. + * + * @param name a name to look for. + * @return the corresponding CostComponentName. + */ + public static CostComponentName fromString(String name) { + return fromString(name, CostComponentName.class); + } + + /** + * Gets known CostComponentName values. + * + * @return known CostComponentName values. + */ + public static Collection values() { + return values(CostComponentName.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/Disk.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/Disk.java new file mode 100644 index 000000000000..c84fb6546112 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/Disk.java @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * A disk discovered on a machine. + */ +@Immutable +public final class Disk implements JsonSerializable { + /* + * Gigabytes of storage provisioned for this disk. + */ + private Float gigabytesAllocated; + + /* + * User friendly name of the disk. + */ + private String displayName; + + /** + * Creates an instance of Disk class. + */ + public Disk() { + } + + /** + * Get the gigabytesAllocated property: Gigabytes of storage provisioned for this disk. + * + * @return the gigabytesAllocated value. + */ + public Float gigabytesAllocated() { + return this.gigabytesAllocated; + } + + /** + * Get the displayName property: User friendly name of the disk. + * + * @return the displayName value. + */ + public String displayName() { + return this.displayName; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of Disk from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of Disk 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 Disk. + */ + public static Disk fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Disk deserializedDisk = new Disk(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("gigabytesAllocated".equals(fieldName)) { + deserializedDisk.gigabytesAllocated = reader.getNullable(JsonReader::getFloat); + } else if ("displayName".equals(fieldName)) { + deserializedDisk.displayName = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedDisk; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/DownloadUrl.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/DownloadUrl.java new file mode 100644 index 000000000000..ac5499241b7a --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/DownloadUrl.java @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.resourcemanager.migration.assessment.fluent.models.DownloadUrlInner; +import java.time.OffsetDateTime; + +/** + * An immutable client-side representation of DownloadUrl. + */ +public interface DownloadUrl { + /** + * Gets the assessmentReportUrl property: Hyperlink to download report. + * + * @return the assessmentReportUrl value. + */ + String assessmentReportUrl(); + + /** + * Gets the expirationTime property: Expiry date of download url. + * + * @return the expirationTime value. + */ + OffsetDateTime expirationTime(); + + /** + * Gets the inner com.azure.resourcemanager.migration.assessment.fluent.models.DownloadUrlInner object. + * + * @return the inner object. + */ + DownloadUrlInner innerModel(); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/EntityUptime.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/EntityUptime.java new file mode 100644 index 000000000000..65558a425b65 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/EntityUptime.java @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * Entity Uptime. + */ +@Fluent +public final class EntityUptime implements JsonSerializable { + /* + * Gets the days per month. + */ + private Integer daysPerMonth; + + /* + * Gets the hours per day. + */ + private Integer hoursPerDay; + + /** + * Creates an instance of EntityUptime class. + */ + public EntityUptime() { + } + + /** + * Get the daysPerMonth property: Gets the days per month. + * + * @return the daysPerMonth value. + */ + public Integer daysPerMonth() { + return this.daysPerMonth; + } + + /** + * Set the daysPerMonth property: Gets the days per month. + * + * @param daysPerMonth the daysPerMonth value to set. + * @return the EntityUptime object itself. + */ + public EntityUptime withDaysPerMonth(Integer daysPerMonth) { + this.daysPerMonth = daysPerMonth; + return this; + } + + /** + * Get the hoursPerDay property: Gets the hours per day. + * + * @return the hoursPerDay value. + */ + public Integer hoursPerDay() { + return this.hoursPerDay; + } + + /** + * Set the hoursPerDay property: Gets the hours per day. + * + * @param hoursPerDay the hoursPerDay value to set. + * @return the EntityUptime object itself. + */ + public EntityUptime withHoursPerDay(Integer hoursPerDay) { + this.hoursPerDay = hoursPerDay; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeNumberField("daysPerMonth", this.daysPerMonth); + jsonWriter.writeNumberField("hoursPerDay", this.hoursPerDay); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of EntityUptime from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of EntityUptime 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 EntityUptime. + */ + public static EntityUptime fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + EntityUptime deserializedEntityUptime = new EntityUptime(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("daysPerMonth".equals(fieldName)) { + deserializedEntityUptime.daysPerMonth = reader.getNullable(JsonReader::getInt); + } else if ("hoursPerDay".equals(fieldName)) { + deserializedEntityUptime.hoursPerDay = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + + return deserializedEntityUptime; + }); + } +} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/EnvironmentType.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/EnvironmentType.java similarity index 85% rename from sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/EnvironmentType.java rename to sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/EnvironmentType.java index 65cee331e265..32c644f524d9 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/EnvironmentType.java +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/EnvironmentType.java @@ -2,24 +2,24 @@ // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. -package com.azure.resourcemanager.quota.models; +package com.azure.resourcemanager.migration.assessment.models; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; /** - * Environment name. + * Defines values for EnvironmentType. */ public final class EnvironmentType extends ExpandableStringEnum { /** - * Static value NonProduction for EnvironmentType. + * Static value Production for EnvironmentType. */ - public static final EnvironmentType NON_PRODUCTION = fromString("NonProduction"); + public static final EnvironmentType PRODUCTION = fromString("Production"); /** - * Static value Production for EnvironmentType. + * Static value Test for EnvironmentType. */ - public static final EnvironmentType PRODUCTION = fromString("Production"); + public static final EnvironmentType TEST = fromString("Test"); /** * Creates a new instance of EnvironmentType value. diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/Error.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/Error.java new file mode 100644 index 000000000000..7525130526ea --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/Error.java @@ -0,0 +1,278 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.util.Map; + +/** + * Error web model class. + */ +@Immutable +public final class Error implements JsonSerializable { + /* + * Gets the error ID. + */ + private Integer id; + + /* + * Gets the error code. + */ + private String code; + + /* + * Gets the Run as account ID. + */ + private String runAsAccountId; + + /* + * Gets the Appliance name. + */ + private String applianceName; + + /* + * Gets the error message. + */ + private String message; + + /* + * Gets the error summary message. + */ + private String summaryMessage; + + /* + * Gets the agent scenario where this error occurred. + */ + private String agentScenario; + + /* + * Gets the error possible causes. + */ + private String possibleCauses; + + /* + * Gets the recommended action for the error. + */ + private String recommendedAction; + + /* + * Gets the error severity. + */ + private String severity; + + /* + * Gets the error message parameters. + */ + private Map messageParameters; + + /* + * Gets the time stamp when the error was updated. + */ + private OffsetDateTime updatedTimestamp; + + /* + * Gets the type of assessment impacted by this error. + */ + private String impactedAssessmentType; + + /** + * Creates an instance of Error class. + */ + public Error() { + } + + /** + * Get the id property: Gets the error ID. + * + * @return the id value. + */ + public Integer id() { + return this.id; + } + + /** + * Get the code property: Gets the error code. + * + * @return the code value. + */ + public String code() { + return this.code; + } + + /** + * Get the runAsAccountId property: Gets the Run as account ID. + * + * @return the runAsAccountId value. + */ + public String runAsAccountId() { + return this.runAsAccountId; + } + + /** + * Get the applianceName property: Gets the Appliance name. + * + * @return the applianceName value. + */ + public String applianceName() { + return this.applianceName; + } + + /** + * Get the message property: Gets the error message. + * + * @return the message value. + */ + public String message() { + return this.message; + } + + /** + * Get the summaryMessage property: Gets the error summary message. + * + * @return the summaryMessage value. + */ + public String summaryMessage() { + return this.summaryMessage; + } + + /** + * Get the agentScenario property: Gets the agent scenario where this error occurred. + * + * @return the agentScenario value. + */ + public String agentScenario() { + return this.agentScenario; + } + + /** + * Get the possibleCauses property: Gets the error possible causes. + * + * @return the possibleCauses value. + */ + public String possibleCauses() { + return this.possibleCauses; + } + + /** + * Get the recommendedAction property: Gets the recommended action for the error. + * + * @return the recommendedAction value. + */ + public String recommendedAction() { + return this.recommendedAction; + } + + /** + * Get the severity property: Gets the error severity. + * + * @return the severity value. + */ + public String severity() { + return this.severity; + } + + /** + * Get the messageParameters property: Gets the error message parameters. + * + * @return the messageParameters value. + */ + public Map messageParameters() { + return this.messageParameters; + } + + /** + * Get the updatedTimestamp property: Gets the time stamp when the error was updated. + * + * @return the updatedTimestamp value. + */ + public OffsetDateTime updatedTimestamp() { + return this.updatedTimestamp; + } + + /** + * Get the impactedAssessmentType property: Gets the type of assessment impacted by this error. + * + * @return the impactedAssessmentType value. + */ + public String impactedAssessmentType() { + return this.impactedAssessmentType; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of Error from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of Error 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 Error. + */ + public static Error fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Error deserializedError = new Error(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedError.id = reader.getNullable(JsonReader::getInt); + } else if ("code".equals(fieldName)) { + deserializedError.code = reader.getString(); + } else if ("runAsAccountId".equals(fieldName)) { + deserializedError.runAsAccountId = reader.getString(); + } else if ("applianceName".equals(fieldName)) { + deserializedError.applianceName = reader.getString(); + } else if ("message".equals(fieldName)) { + deserializedError.message = reader.getString(); + } else if ("summaryMessage".equals(fieldName)) { + deserializedError.summaryMessage = reader.getString(); + } else if ("agentScenario".equals(fieldName)) { + deserializedError.agentScenario = reader.getString(); + } else if ("possibleCauses".equals(fieldName)) { + deserializedError.possibleCauses = reader.getString(); + } else if ("recommendedAction".equals(fieldName)) { + deserializedError.recommendedAction = reader.getString(); + } else if ("severity".equals(fieldName)) { + deserializedError.severity = reader.getString(); + } else if ("messageParameters".equals(fieldName)) { + Map messageParameters = reader.readMap(reader1 -> reader1.getString()); + deserializedError.messageParameters = messageParameters; + } else if ("updatedTimeStamp".equals(fieldName)) { + deserializedError.updatedTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("impactedAssessmentType".equals(fieldName)) { + deserializedError.impactedAssessmentType = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedError; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ErrorSummary.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ErrorSummary.java new file mode 100644 index 000000000000..42260482d270 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ErrorSummary.java @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * Error summary containing affected entities for each type of assessment. + */ +@Immutable +public final class ErrorSummary implements JsonSerializable { + /* + * Gets the assessment type. + */ + private AssessmentType assessmentType; + + /* + * Gets the affected entity count. + */ + private Integer count; + + /** + * Creates an instance of ErrorSummary class. + */ + public ErrorSummary() { + } + + /** + * Get the assessmentType property: Gets the assessment type. + * + * @return the assessmentType value. + */ + public AssessmentType assessmentType() { + return this.assessmentType; + } + + /** + * Get the count property: Gets the affected entity count. + * + * @return the count value. + */ + public Integer count() { + return this.count; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ErrorSummary from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ErrorSummary 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 ErrorSummary. + */ + public static ErrorSummary fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ErrorSummary deserializedErrorSummary = new ErrorSummary(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("assessmentType".equals(fieldName)) { + deserializedErrorSummary.assessmentType = AssessmentType.fromString(reader.getString()); + } else if ("count".equals(fieldName)) { + deserializedErrorSummary.count = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + + return deserializedErrorSummary; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/FttAndRaidLevel.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/FttAndRaidLevel.java new file mode 100644 index 000000000000..575fec6374ee --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/FttAndRaidLevel.java @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for FttAndRaidLevel. + */ +public final class FttAndRaidLevel extends ExpandableStringEnum { + /** + * Static value Unknown for FttAndRaidLevel. + */ + public static final FttAndRaidLevel UNKNOWN = fromString("Unknown"); + + /** + * Static value Ftt1Raid1 for FttAndRaidLevel. + */ + public static final FttAndRaidLevel FTT1RAID1 = fromString("Ftt1Raid1"); + + /** + * Static value Ftt1Raid5 for FttAndRaidLevel. + */ + public static final FttAndRaidLevel FTT1RAID5 = fromString("Ftt1Raid5"); + + /** + * Static value Ftt2Raid1 for FttAndRaidLevel. + */ + public static final FttAndRaidLevel FTT2RAID1 = fromString("Ftt2Raid1"); + + /** + * Static value Ftt2Raid6 for FttAndRaidLevel. + */ + public static final FttAndRaidLevel FTT2RAID6 = fromString("Ftt2Raid6"); + + /** + * Static value Ftt3Raid1 for FttAndRaidLevel. + */ + public static final FttAndRaidLevel FTT3RAID1 = fromString("Ftt3Raid1"); + + /** + * Creates a new instance of FttAndRaidLevel value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public FttAndRaidLevel() { + } + + /** + * Creates or finds a FttAndRaidLevel from its string representation. + * + * @param name a name to look for. + * @return the corresponding FttAndRaidLevel. + */ + public static FttAndRaidLevel fromString(String name) { + return fromString(name, FttAndRaidLevel.class); + } + + /** + * Gets known FttAndRaidLevel values. + * + * @return known FttAndRaidLevel values. + */ + public static Collection values() { + return values(FttAndRaidLevel.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/Group.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/Group.java new file mode 100644 index 000000000000..6f7581156ae1 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/Group.java @@ -0,0 +1,164 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.GroupInner; + +/** + * An immutable client-side representation of Group. + */ +public interface Group { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + GroupProperties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.migration.assessment.fluent.models.GroupInner object. + * + * @return the inner object. + */ + GroupInner innerModel(); + + /** + * The entirety of the Group definition. + */ + interface Definition + extends DefinitionStages.Blank, DefinitionStages.WithParentResource, DefinitionStages.WithCreate { + } + + /** + * The Group definition stages. + */ + interface DefinitionStages { + /** + * The first stage of the Group definition. + */ + interface Blank extends WithParentResource { + } + + /** + * The stage of the Group definition allowing to specify parent resource. + */ + interface WithParentResource { + /** + * Specifies resourceGroupName, projectName. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @return the next definition stage. + */ + WithCreate withExistingAssessmentProject(String resourceGroupName, String projectName); + } + + /** + * The stage of the Group definition which contains all the minimum required properties for the resource to be + * created, but also allows for any other optional properties to be specified. + */ + interface WithCreate extends DefinitionStages.WithProperties { + /** + * Executes the create request. + * + * @return the created resource. + */ + Group create(); + + /** + * Executes the create request. + * + * @param context The context to associate with this operation. + * @return the created resource. + */ + Group create(Context context); + } + + /** + * The stage of the Group definition allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The resource-specific properties for this resource.. + * + * @param properties The resource-specific properties for this resource. + * @return the next definition stage. + */ + WithCreate withProperties(GroupProperties properties); + } + } + + /** + * Refreshes the resource to sync with Azure. + * + * @return the refreshed resource. + */ + Group refresh(); + + /** + * Refreshes the resource to sync with Azure. + * + * @param context The context to associate with this operation. + * @return the refreshed resource. + */ + Group refresh(Context context); + + /** + * Update machines in group. + * + * Update machines in group by adding or removing machines. + * + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return group resource. + */ + Group updateMachines(UpdateGroupBody body); + + /** + * Update machines in group. + * + * Update machines in group by adding or removing machines. + * + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return group resource. + */ + Group updateMachines(UpdateGroupBody body, Context context); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/GroupBodyProperties.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/GroupBodyProperties.java new file mode 100644 index 000000000000..cf74a4db56b1 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/GroupBodyProperties.java @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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.List; + +/** + * Body properties of group update. + */ +@Fluent +public final class GroupBodyProperties implements JsonSerializable { + /* + * Whether to add or remove the machines. + */ + private GroupUpdateOperation operationType; + + /* + * List of machine names that are part of this group. + */ + private List machines; + + /** + * Creates an instance of GroupBodyProperties class. + */ + public GroupBodyProperties() { + } + + /** + * Get the operationType property: Whether to add or remove the machines. + * + * @return the operationType value. + */ + public GroupUpdateOperation operationType() { + return this.operationType; + } + + /** + * Set the operationType property: Whether to add or remove the machines. + * + * @param operationType the operationType value to set. + * @return the GroupBodyProperties object itself. + */ + public GroupBodyProperties withOperationType(GroupUpdateOperation operationType) { + this.operationType = operationType; + return this; + } + + /** + * Get the machines property: List of machine names that are part of this group. + * + * @return the machines value. + */ + public List machines() { + return this.machines; + } + + /** + * Set the machines property: List of machine names that are part of this group. + * + * @param machines the machines value to set. + * @return the GroupBodyProperties object itself. + */ + public GroupBodyProperties withMachines(List machines) { + this.machines = machines; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("operationType", this.operationType == null ? null : this.operationType.toString()); + jsonWriter.writeArrayField("machines", this.machines, (writer, element) -> writer.writeString(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of GroupBodyProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of GroupBodyProperties 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 GroupBodyProperties. + */ + public static GroupBodyProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + GroupBodyProperties deserializedGroupBodyProperties = new GroupBodyProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("operationType".equals(fieldName)) { + deserializedGroupBodyProperties.operationType = GroupUpdateOperation.fromString(reader.getString()); + } else if ("machines".equals(fieldName)) { + List machines = reader.readArray(reader1 -> reader1.getString()); + deserializedGroupBodyProperties.machines = machines; + } else { + reader.skipChildren(); + } + } + + return deserializedGroupBodyProperties; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/GroupListResult.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/GroupListResult.java new file mode 100644 index 000000000000..5348f33b8dca --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/GroupListResult.java @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.fluent.models.GroupInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a Group list operation. + */ +@Fluent +public final class GroupListResult implements JsonSerializable { + /* + * The Group items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of GroupListResult class. + */ + public GroupListResult() { + } + + /** + * Get the value property: The Group items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Set the value property: The Group items on this page. + * + * @param value the value value to set. + * @return the GroupListResult object itself. + */ + public GroupListResult withValue(List value) { + this.value = value; + return this; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The link to the next page of items. + * + * @param nextLink the nextLink value to set. + * @return the GroupListResult object itself. + */ + public GroupListResult withNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property value in model GroupListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(GroupListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of GroupListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of GroupListResult 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 GroupListResult. + */ + public static GroupListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + GroupListResult deserializedGroupListResult = new GroupListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value = reader.readArray(reader1 -> GroupInner.fromJson(reader1)); + deserializedGroupListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedGroupListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedGroupListResult; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/GroupProperties.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/GroupProperties.java new file mode 100644 index 000000000000..d2ef0b7782bb --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/GroupProperties.java @@ -0,0 +1,240 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.util.List; + +/** + * Properties of group resource. + */ +@Fluent +public final class GroupProperties extends AzureResourceProperties { + /* + * Whether the group has been created and is valid. + */ + private GroupStatus groupStatus; + + /* + * Number of machines part of this group. + */ + private Integer machineCount; + + /* + * List of References to Assessments created on this group. + */ + private List assessments; + + /* + * List of assessment types supported on this group. + */ + private List supportedAssessmentTypes; + + /* + * If the assessments are in running state. + */ + private Boolean areAssessmentsRunning; + + /* + * Time when this group was created. Date-Time represented in ISO-8601 format. + */ + private OffsetDateTime createdTimestamp; + + /* + * Time when this group was last updated. Date-Time represented in ISO-8601 format. + */ + private OffsetDateTime updatedTimestamp; + + /* + * The type of group. + */ + private GroupType groupType; + + /** + * Creates an instance of GroupProperties class. + */ + public GroupProperties() { + } + + /** + * Get the groupStatus property: Whether the group has been created and is valid. + * + * @return the groupStatus value. + */ + public GroupStatus groupStatus() { + return this.groupStatus; + } + + /** + * Get the machineCount property: Number of machines part of this group. + * + * @return the machineCount value. + */ + public Integer machineCount() { + return this.machineCount; + } + + /** + * Get the assessments property: List of References to Assessments created on this group. + * + * @return the assessments value. + */ + public List assessments() { + return this.assessments; + } + + /** + * Get the supportedAssessmentTypes property: List of assessment types supported on this group. + * + * @return the supportedAssessmentTypes value. + */ + public List supportedAssessmentTypes() { + return this.supportedAssessmentTypes; + } + + /** + * Set the supportedAssessmentTypes property: List of assessment types supported on this group. + * + * @param supportedAssessmentTypes the supportedAssessmentTypes value to set. + * @return the GroupProperties object itself. + */ + public GroupProperties withSupportedAssessmentTypes(List supportedAssessmentTypes) { + this.supportedAssessmentTypes = supportedAssessmentTypes; + return this; + } + + /** + * Get the areAssessmentsRunning property: If the assessments are in running state. + * + * @return the areAssessmentsRunning value. + */ + public Boolean areAssessmentsRunning() { + return this.areAssessmentsRunning; + } + + /** + * Get the createdTimestamp property: Time when this group was created. Date-Time represented in ISO-8601 format. + * + * @return the createdTimestamp value. + */ + public OffsetDateTime createdTimestamp() { + return this.createdTimestamp; + } + + /** + * Get the updatedTimestamp property: Time when this group was last updated. Date-Time represented in ISO-8601 + * format. + * + * @return the updatedTimestamp value. + */ + public OffsetDateTime updatedTimestamp() { + return this.updatedTimestamp; + } + + /** + * Get the groupType property: The type of group. + * + * @return the groupType value. + */ + public GroupType groupType() { + return this.groupType; + } + + /** + * Set the groupType property: The type of group. + * + * @param groupType the groupType value to set. + * @return the GroupProperties object itself. + */ + public GroupProperties withGroupType(GroupType groupType) { + this.groupType = groupType; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public GroupProperties withProvisioningState(ProvisioningState provisioningState) { + super.withProvisioningState(provisioningState); + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + @Override + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("provisioningState", + provisioningState() == null ? null : provisioningState().toString()); + jsonWriter.writeArrayField("supportedAssessmentTypes", this.supportedAssessmentTypes, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); + jsonWriter.writeStringField("groupType", this.groupType == null ? null : this.groupType.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of GroupProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of GroupProperties 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 GroupProperties. + */ + public static GroupProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + GroupProperties deserializedGroupProperties = new GroupProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("provisioningState".equals(fieldName)) { + deserializedGroupProperties.withProvisioningState(ProvisioningState.fromString(reader.getString())); + } else if ("groupStatus".equals(fieldName)) { + deserializedGroupProperties.groupStatus = GroupStatus.fromString(reader.getString()); + } else if ("machineCount".equals(fieldName)) { + deserializedGroupProperties.machineCount = reader.getNullable(JsonReader::getInt); + } else if ("assessments".equals(fieldName)) { + List assessments = reader.readArray(reader1 -> reader1.getString()); + deserializedGroupProperties.assessments = assessments; + } else if ("supportedAssessmentTypes".equals(fieldName)) { + List supportedAssessmentTypes + = reader.readArray(reader1 -> AssessmentType.fromString(reader1.getString())); + deserializedGroupProperties.supportedAssessmentTypes = supportedAssessmentTypes; + } else if ("areAssessmentsRunning".equals(fieldName)) { + deserializedGroupProperties.areAssessmentsRunning = reader.getNullable(JsonReader::getBoolean); + } else if ("createdTimestamp".equals(fieldName)) { + deserializedGroupProperties.createdTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("updatedTimestamp".equals(fieldName)) { + deserializedGroupProperties.updatedTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("groupType".equals(fieldName)) { + deserializedGroupProperties.groupType = GroupType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedGroupProperties; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/GroupStatus.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/GroupStatus.java new file mode 100644 index 000000000000..0b7b4d8fab41 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/GroupStatus.java @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for GroupStatus. + */ +public final class GroupStatus extends ExpandableStringEnum { + /** + * Static value Created for GroupStatus. + */ + public static final GroupStatus CREATED = fromString("Created"); + + /** + * Static value Updated for GroupStatus. + */ + public static final GroupStatus UPDATED = fromString("Updated"); + + /** + * Static value Running for GroupStatus. + */ + public static final GroupStatus RUNNING = fromString("Running"); + + /** + * Static value Completed for GroupStatus. + */ + public static final GroupStatus COMPLETED = fromString("Completed"); + + /** + * Static value Invalid for GroupStatus. + */ + public static final GroupStatus INVALID = fromString("Invalid"); + + /** + * Creates a new instance of GroupStatus value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public GroupStatus() { + } + + /** + * Creates or finds a GroupStatus from its string representation. + * + * @param name a name to look for. + * @return the corresponding GroupStatus. + */ + public static GroupStatus fromString(String name) { + return fromString(name, GroupStatus.class); + } + + /** + * Gets known GroupStatus values. + * + * @return known GroupStatus values. + */ + public static Collection values() { + return values(GroupStatus.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/GroupType.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/GroupType.java new file mode 100644 index 000000000000..fb10c9fdc7a1 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/GroupType.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for GroupType. + */ +public final class GroupType extends ExpandableStringEnum { + /** + * Static value Default for GroupType. + */ + public static final GroupType DEFAULT = fromString("Default"); + + /** + * Static value Import for GroupType. + */ + public static final GroupType IMPORT = fromString("Import"); + + /** + * Creates a new instance of GroupType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public GroupType() { + } + + /** + * Creates or finds a GroupType from its string representation. + * + * @param name a name to look for. + * @return the corresponding GroupType. + */ + public static GroupType fromString(String name) { + return fromString(name, GroupType.class); + } + + /** + * Gets known GroupType values. + * + * @return known GroupType values. + */ + public static Collection values() { + return values(GroupType.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/GroupUpdateOperation.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/GroupUpdateOperation.java new file mode 100644 index 000000000000..4d5a70a50b1e --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/GroupUpdateOperation.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for GroupUpdateOperation. + */ +public final class GroupUpdateOperation extends ExpandableStringEnum { + /** + * Static value Add for GroupUpdateOperation. + */ + public static final GroupUpdateOperation ADD = fromString("Add"); + + /** + * Static value Remove for GroupUpdateOperation. + */ + public static final GroupUpdateOperation REMOVE = fromString("Remove"); + + /** + * Creates a new instance of GroupUpdateOperation value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public GroupUpdateOperation() { + } + + /** + * Creates or finds a GroupUpdateOperation from its string representation. + * + * @param name a name to look for. + * @return the corresponding GroupUpdateOperation. + */ + public static GroupUpdateOperation fromString(String name) { + return fromString(name, GroupUpdateOperation.class); + } + + /** + * Gets known GroupUpdateOperation values. + * + * @return known GroupUpdateOperation values. + */ + public static Collection values() { + return values(GroupUpdateOperation.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/GroupsOperations.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/GroupsOperations.java new file mode 100644 index 000000000000..e7c8489a48b2 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/GroupsOperations.java @@ -0,0 +1,179 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of GroupsOperations. + */ +public interface GroupsOperations { + /** + * List Group resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Group list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName); + + /** + * List Group resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Group list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, Context context); + + /** + * Get a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Group along with {@link Response}. + */ + Response getWithResponse(String resourceGroupName, String projectName, String groupName, Context context); + + /** + * Get a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Group. + */ + Group get(String resourceGroupName, String projectName, String groupName); + + /** + * Delete a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteWithResponse(String resourceGroupName, String projectName, String groupName, Context context); + + /** + * Delete a Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void delete(String resourceGroupName, String projectName, String groupName); + + /** + * Update machines in group. + * + * Update machines in group by adding or removing machines. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return group resource. + */ + Group updateMachines(String resourceGroupName, String projectName, String groupName, UpdateGroupBody body); + + /** + * Update machines in group. + * + * Update machines in group by adding or removing machines. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return group resource. + */ + Group updateMachines(String resourceGroupName, String projectName, String groupName, UpdateGroupBody body, + Context context); + + /** + * Get a Group. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Group along with {@link Response}. + */ + Group getById(String id); + + /** + * Get a Group. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Group along with {@link Response}. + */ + Response getByIdWithResponse(String id, Context context); + + /** + * Delete a Group. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteById(String id); + + /** + * Delete a Group. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteByIdWithResponse(String id, Context context); + + /** + * Begins definition for a new Group resource. + * + * @param name resource name. + * @return the first stage of the new Group definition. + */ + Group.DefinitionStages.Blank define(String name); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/GuestOperatingSystemArchitecture.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/GuestOperatingSystemArchitecture.java new file mode 100644 index 000000000000..d064b15557ab --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/GuestOperatingSystemArchitecture.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. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for GuestOperatingSystemArchitecture. + */ +public final class GuestOperatingSystemArchitecture extends ExpandableStringEnum { + /** + * Static value Unknown for GuestOperatingSystemArchitecture. + */ + public static final GuestOperatingSystemArchitecture UNKNOWN = fromString("Unknown"); + + /** + * Static value X86 for GuestOperatingSystemArchitecture. + */ + public static final GuestOperatingSystemArchitecture X86 = fromString("X86"); + + /** + * Static value X64 for GuestOperatingSystemArchitecture. + */ + public static final GuestOperatingSystemArchitecture X64 = fromString("X64"); + + /** + * Creates a new instance of GuestOperatingSystemArchitecture value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public GuestOperatingSystemArchitecture() { + } + + /** + * Creates or finds a GuestOperatingSystemArchitecture from its string representation. + * + * @param name a name to look for. + * @return the corresponding GuestOperatingSystemArchitecture. + */ + public static GuestOperatingSystemArchitecture fromString(String name) { + return fromString(name, GuestOperatingSystemArchitecture.class); + } + + /** + * Gets known GuestOperatingSystemArchitecture values. + * + * @return known GuestOperatingSystemArchitecture values. + */ + public static Collection values() { + return values(GuestOperatingSystemArchitecture.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/HardwareGeneration.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/HardwareGeneration.java new file mode 100644 index 000000000000..0ba1bbe84285 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/HardwareGeneration.java @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for HardwareGeneration. + */ +public final class HardwareGeneration extends ExpandableStringEnum { + /** + * Static value Unknown for HardwareGeneration. + */ + public static final HardwareGeneration UNKNOWN = fromString("Unknown"); + + /** + * Static value Automatic for HardwareGeneration. + */ + public static final HardwareGeneration AUTOMATIC = fromString("Automatic"); + + /** + * Static value Gen5 for HardwareGeneration. + */ + public static final HardwareGeneration GEN5 = fromString("Gen5"); + + /** + * Static value Fsv2_series for HardwareGeneration. + */ + public static final HardwareGeneration FSV2_SERIES = fromString("Fsv2_series"); + + /** + * Static value M_series for HardwareGeneration. + */ + public static final HardwareGeneration M_SERIES = fromString("M_series"); + + /** + * Static value DC_series for HardwareGeneration. + */ + public static final HardwareGeneration DC_SERIES = fromString("DC_series"); + + /** + * Creates a new instance of HardwareGeneration value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public HardwareGeneration() { + } + + /** + * Creates or finds a HardwareGeneration from its string representation. + * + * @param name a name to look for. + * @return the corresponding HardwareGeneration. + */ + public static HardwareGeneration fromString(String name) { + return fromString(name, HardwareGeneration.class); + } + + /** + * Gets known HardwareGeneration values. + * + * @return known HardwareGeneration values. + */ + public static Collection values() { + return values(HardwareGeneration.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/HypervCollector.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/HypervCollector.java new file mode 100644 index 000000000000..7383755eb7e7 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/HypervCollector.java @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.HypervCollectorInner; + +/** + * An immutable client-side representation of HypervCollector. + */ +public interface HypervCollector { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + CollectorPropertiesBaseWithAgent properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.migration.assessment.fluent.models.HypervCollectorInner object. + * + * @return the inner object. + */ + HypervCollectorInner innerModel(); + + /** + * The entirety of the HypervCollector definition. + */ + interface Definition + extends DefinitionStages.Blank, DefinitionStages.WithParentResource, DefinitionStages.WithCreate { + } + + /** + * The HypervCollector definition stages. + */ + interface DefinitionStages { + /** + * The first stage of the HypervCollector definition. + */ + interface Blank extends WithParentResource { + } + + /** + * The stage of the HypervCollector definition allowing to specify parent resource. + */ + interface WithParentResource { + /** + * Specifies resourceGroupName, projectName. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @return the next definition stage. + */ + WithCreate withExistingAssessmentProject(String resourceGroupName, String projectName); + } + + /** + * The stage of the HypervCollector definition which contains all the minimum required properties for the + * resource to be created, but also allows for any other optional properties to be specified. + */ + interface WithCreate extends DefinitionStages.WithProperties { + /** + * Executes the create request. + * + * @return the created resource. + */ + HypervCollector create(); + + /** + * Executes the create request. + * + * @param context The context to associate with this operation. + * @return the created resource. + */ + HypervCollector create(Context context); + } + + /** + * The stage of the HypervCollector definition allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The resource-specific properties for this resource.. + * + * @param properties The resource-specific properties for this resource. + * @return the next definition stage. + */ + WithCreate withProperties(CollectorPropertiesBaseWithAgent properties); + } + } + + /** + * Refreshes the resource to sync with Azure. + * + * @return the refreshed resource. + */ + HypervCollector refresh(); + + /** + * Refreshes the resource to sync with Azure. + * + * @param context The context to associate with this operation. + * @return the refreshed resource. + */ + HypervCollector refresh(Context context); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/HypervCollectorListResult.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/HypervCollectorListResult.java new file mode 100644 index 000000000000..fe538f61cf97 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/HypervCollectorListResult.java @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.fluent.models.HypervCollectorInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a HypervCollector list operation. + */ +@Fluent +public final class HypervCollectorListResult implements JsonSerializable { + /* + * The HypervCollector items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of HypervCollectorListResult class. + */ + public HypervCollectorListResult() { + } + + /** + * Get the value property: The HypervCollector items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Set the value property: The HypervCollector items on this page. + * + * @param value the value value to set. + * @return the HypervCollectorListResult object itself. + */ + public HypervCollectorListResult withValue(List value) { + this.value = value; + return this; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The link to the next page of items. + * + * @param nextLink the nextLink value to set. + * @return the HypervCollectorListResult object itself. + */ + public HypervCollectorListResult withNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log( + new IllegalArgumentException("Missing required property value in model HypervCollectorListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(HypervCollectorListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of HypervCollectorListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of HypervCollectorListResult 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 HypervCollectorListResult. + */ + public static HypervCollectorListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + HypervCollectorListResult deserializedHypervCollectorListResult = new HypervCollectorListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> HypervCollectorInner.fromJson(reader1)); + deserializedHypervCollectorListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedHypervCollectorListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedHypervCollectorListResult; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/HypervCollectorsOperations.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/HypervCollectorsOperations.java new file mode 100644 index 000000000000..125d1224d1dd --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/HypervCollectorsOperations.java @@ -0,0 +1,148 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of HypervCollectorsOperations. + */ +public interface HypervCollectorsOperations { + /** + * List HypervCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a HypervCollector list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName); + + /** + * List HypervCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a HypervCollector list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context); + + /** + * Get a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a HypervCollector along with {@link Response}. + */ + Response getWithResponse(String resourceGroupName, String projectName, String hypervCollectorName, + Context context); + + /** + * Get a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a HypervCollector. + */ + HypervCollector get(String resourceGroupName, String projectName, String hypervCollectorName); + + /** + * Delete a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteWithResponse(String resourceGroupName, String projectName, String hypervCollectorName, + Context context); + + /** + * Delete a HypervCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param hypervCollectorName Hyper-V collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void delete(String resourceGroupName, String projectName, String hypervCollectorName); + + /** + * Get a HypervCollector. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a HypervCollector along with {@link Response}. + */ + HypervCollector getById(String id); + + /** + * Get a HypervCollector. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a HypervCollector along with {@link Response}. + */ + Response getByIdWithResponse(String id, Context context); + + /** + * Delete a HypervCollector. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteById(String id); + + /** + * Delete a HypervCollector. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteByIdWithResponse(String id, Context context); + + /** + * Begins definition for a new HypervCollector resource. + * + * @param name resource name. + * @return the first stage of the new HypervCollector definition. + */ + HypervCollector.DefinitionStages.Blank define(String name); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ImpactedAssessmentObject.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ImpactedAssessmentObject.java new file mode 100644 index 000000000000..239cbfaf2c75 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ImpactedAssessmentObject.java @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * Class representing the impacted objects. + */ +@Immutable +public final class ImpactedAssessmentObject implements JsonSerializable { + /* + * Gets the object name. + */ + private String objectName; + + /* + * Gets the object type. + */ + private String objectType; + + /** + * Creates an instance of ImpactedAssessmentObject class. + */ + public ImpactedAssessmentObject() { + } + + /** + * Get the objectName property: Gets the object name. + * + * @return the objectName value. + */ + public String objectName() { + return this.objectName; + } + + /** + * Get the objectType property: Gets the object type. + * + * @return the objectType value. + */ + public String objectType() { + return this.objectType; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ImpactedAssessmentObject from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ImpactedAssessmentObject 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 ImpactedAssessmentObject. + */ + public static ImpactedAssessmentObject fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ImpactedAssessmentObject deserializedImpactedAssessmentObject = new ImpactedAssessmentObject(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("objectName".equals(fieldName)) { + deserializedImpactedAssessmentObject.objectName = reader.getString(); + } else if ("objectType".equals(fieldName)) { + deserializedImpactedAssessmentObject.objectType = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedImpactedAssessmentObject; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ImportCollector.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ImportCollector.java new file mode 100644 index 000000000000..320d5c6ef518 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ImportCollector.java @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.ImportCollectorInner; + +/** + * An immutable client-side representation of ImportCollector. + */ +public interface ImportCollector { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + CollectorPropertiesBase properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.migration.assessment.fluent.models.ImportCollectorInner object. + * + * @return the inner object. + */ + ImportCollectorInner innerModel(); + + /** + * The entirety of the ImportCollector definition. + */ + interface Definition + extends DefinitionStages.Blank, DefinitionStages.WithParentResource, DefinitionStages.WithCreate { + } + + /** + * The ImportCollector definition stages. + */ + interface DefinitionStages { + /** + * The first stage of the ImportCollector definition. + */ + interface Blank extends WithParentResource { + } + + /** + * The stage of the ImportCollector definition allowing to specify parent resource. + */ + interface WithParentResource { + /** + * Specifies resourceGroupName, projectName. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @return the next definition stage. + */ + WithCreate withExistingAssessmentProject(String resourceGroupName, String projectName); + } + + /** + * The stage of the ImportCollector definition which contains all the minimum required properties for the + * resource to be created, but also allows for any other optional properties to be specified. + */ + interface WithCreate extends DefinitionStages.WithProperties { + /** + * Executes the create request. + * + * @return the created resource. + */ + ImportCollector create(); + + /** + * Executes the create request. + * + * @param context The context to associate with this operation. + * @return the created resource. + */ + ImportCollector create(Context context); + } + + /** + * The stage of the ImportCollector definition allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The resource-specific properties for this resource.. + * + * @param properties The resource-specific properties for this resource. + * @return the next definition stage. + */ + WithCreate withProperties(CollectorPropertiesBase properties); + } + } + + /** + * Refreshes the resource to sync with Azure. + * + * @return the refreshed resource. + */ + ImportCollector refresh(); + + /** + * Refreshes the resource to sync with Azure. + * + * @param context The context to associate with this operation. + * @return the refreshed resource. + */ + ImportCollector refresh(Context context); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ImportCollectorListResult.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ImportCollectorListResult.java new file mode 100644 index 000000000000..9218711c7eb3 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ImportCollectorListResult.java @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.fluent.models.ImportCollectorInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a ImportCollector list operation. + */ +@Fluent +public final class ImportCollectorListResult implements JsonSerializable { + /* + * The ImportCollector items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of ImportCollectorListResult class. + */ + public ImportCollectorListResult() { + } + + /** + * Get the value property: The ImportCollector items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Set the value property: The ImportCollector items on this page. + * + * @param value the value value to set. + * @return the ImportCollectorListResult object itself. + */ + public ImportCollectorListResult withValue(List value) { + this.value = value; + return this; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The link to the next page of items. + * + * @param nextLink the nextLink value to set. + * @return the ImportCollectorListResult object itself. + */ + public ImportCollectorListResult withNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log( + new IllegalArgumentException("Missing required property value in model ImportCollectorListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(ImportCollectorListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ImportCollectorListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ImportCollectorListResult 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 ImportCollectorListResult. + */ + public static ImportCollectorListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ImportCollectorListResult deserializedImportCollectorListResult = new ImportCollectorListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> ImportCollectorInner.fromJson(reader1)); + deserializedImportCollectorListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedImportCollectorListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedImportCollectorListResult; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ImportCollectorsOperations.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ImportCollectorsOperations.java new file mode 100644 index 000000000000..24a59f7f6f74 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ImportCollectorsOperations.java @@ -0,0 +1,148 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of ImportCollectorsOperations. + */ +public interface ImportCollectorsOperations { + /** + * List ImportCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ImportCollector list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName); + + /** + * List ImportCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ImportCollector list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context); + + /** + * Get a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ImportCollector along with {@link Response}. + */ + Response getWithResponse(String resourceGroupName, String projectName, String importCollectorName, + Context context); + + /** + * Get a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ImportCollector. + */ + ImportCollector get(String resourceGroupName, String projectName, String importCollectorName); + + /** + * Delete a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteWithResponse(String resourceGroupName, String projectName, String importCollectorName, + Context context); + + /** + * Delete a ImportCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param importCollectorName Import collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void delete(String resourceGroupName, String projectName, String importCollectorName); + + /** + * Get a ImportCollector. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ImportCollector along with {@link Response}. + */ + ImportCollector getById(String id); + + /** + * Get a ImportCollector. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ImportCollector along with {@link Response}. + */ + Response getByIdWithResponse(String id, Context context); + + /** + * Delete a ImportCollector. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteById(String id); + + /** + * Delete a ImportCollector. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteByIdWithResponse(String id, Context context); + + /** + * Begins definition for a new ImportCollector resource. + * + * @param name resource name. + * @return the first stage of the new ImportCollector definition. + */ + ImportCollector.DefinitionStages.Blank define(String name); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/Machine.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/Machine.java new file mode 100644 index 000000000000..d9b72f7de8e4 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/Machine.java @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.migration.assessment.fluent.models.MachineInner; + +/** + * An immutable client-side representation of Machine. + */ +public interface Machine { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + MachineProperties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.migration.assessment.fluent.models.MachineInner object. + * + * @return the inner object. + */ + MachineInner innerModel(); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/MachineAssessmentProperties.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/MachineAssessmentProperties.java new file mode 100644 index 000000000000..b9fc70d23eb4 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/MachineAssessmentProperties.java @@ -0,0 +1,1024 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.List; +import java.util.Map; + +/** + * Properties of an assessment. + */ +@Fluent +public final class MachineAssessmentProperties extends AzureResourceProperties { + /* + * Gets or sets the assessment error summary. + * This is the number of + * machines affected by each type of error in this assessment. + */ + private Map assessmentErrorSummary; + + /* + * Gets or sets the aggregate ultra storage cost for all machines in the + * assessment. + */ + private Float monthlyUltraStorageCost; + + /* + * Gets the collection of cost components. + */ + private List costComponents; + + /* + * Gets or sets enterprise agreement subscription id. + */ + private String eaSubscriptionId; + + /* + * Gets or sets Azure Pricing Tier - Free, Basic, etc. + */ + private AzurePricingTier azurePricingTier; + + /* + * Gets or sets the Azure Storage Redundancy. Example: Locally Redundant Storage. + */ + private AzureStorageRedundancy azureStorageRedundancy; + + /* + * Gets or sets the Azure Reserved Instance - 1-Year, 3-Year. + */ + private AzureReservedInstance reservedInstance; + + /* + * Gets or sets the user configurable setting to display the azure hybrid use + * benefit. + */ + private AzureHybridUseBenefit azureHybridUseBenefit; + + /* + * Gets or sets the azure storage type. Premium, Standard etc. + */ + private List azureDiskTypes; + + /* + * Gets or sets the Azure VM families. + */ + private List azureVmFamilies; + + /* + * Gets the distribution of sqlInstances by support status. + */ + private Map distributionBySupportStatus; + + /* + * Gets the distribution distribution of sqlInstances by service pack insight. + */ + private Map distributionByServicePackInsight; + + /* + * Gets the distribution by os name. + */ + private Map distributionByOsName; + + /* + * Gets or sets the aggregate Compute Cost for all machines in the assessment. + */ + private Float monthlyComputeCost; + + /* + * Gets or sets the aggregate Bandwidth Cost for all machines in the assessment. + */ + private Float monthlyBandwidthCost; + + /* + * Gets or sets the aggregate Storage Cost for all machines in the assessment. + */ + private Float monthlyStorageCost; + + /* + * Gets or sets the aggregate premium storage cost for all machines in the + * assessment. + */ + private Float monthlyPremiumStorageCost; + + /* + * Gets or sets the aggregate standard SSD storage cost for all the machines in + * the assessment. + */ + private Float monthlyStandardSsdStorageCost; + + /* + * Gets or sets the Cloud suitability summary for all the machines in the + * assessment. + */ + private Map suitabilitySummary; + + /* + * Gets or sets the Number of machines part of the assessment. + */ + private Integer numberOfMachines; + + /* + * Gets or sets the duration for which the VMs are up in the on-premises + * environment. + */ + private VmUptime vmUptime; + + /* + * Gets the group type for the assessment. + */ + private GroupType groupType; + + /* + * Assessment type of the assessment. + */ + private AssessmentType assessmentType; + + /* + * Azure Location or Azure region where to which the machines will be migrated. + */ + private String azureLocation; + + /* + * Azure Offer Code. + */ + private AzureOfferCode azureOfferCode; + + /* + * Currency in which prices should be reported. + */ + private AzureCurrency currency; + + /* + * Percentage of buffer that user wants on performance metrics when recommending + * Azure sizes. + */ + private Float scalingFactor; + + /* + * Percentile of the utilization data values to be considered while assessing + * machines. + */ + private Percentile percentile; + + /* + * Time Range for which the historic utilization data should be considered for + * assessment. + */ + private TimeRange timeRange; + + /* + * Gets or sets the start time to consider performance data for assessment. + */ + private OffsetDateTime perfDataStartTime; + + /* + * Gets or sets the end time to consider performance data for assessment. + */ + private OffsetDateTime perfDataEndTime; + + /* + * User configurable setting to display the Stage of Assessment. + */ + private AssessmentStage stage; + + /* + * Custom discount percentage. + */ + private Float discountPercentage; + + /* + * Assessment sizing criterion. + */ + private AssessmentSizingCriterion sizingCriterion; + + /* + * Confidence Rating in Percentage. + */ + private Float confidenceRatingInPercentage; + + /* + * Last time when rates were queried. + */ + private OffsetDateTime pricesTimestamp; + + /* + * Date and Time when assessment was created. + */ + private OffsetDateTime createdTimestamp; + + /* + * Date and Time when assessment was last updated. + */ + private OffsetDateTime updatedTimestamp; + + /* + * Whether assessment is in valid state and all machines have been assessed. + */ + private AssessmentStatus status; + + /* + * Schema version. + */ + private String schemaVersion; + + /** + * Creates an instance of MachineAssessmentProperties class. + */ + public MachineAssessmentProperties() { + } + + /** + * Get the assessmentErrorSummary property: Gets or sets the assessment error summary. + * This is the number of + * machines affected by each type of error in this assessment. + * + * @return the assessmentErrorSummary value. + */ + public Map assessmentErrorSummary() { + return this.assessmentErrorSummary; + } + + /** + * Get the monthlyUltraStorageCost property: Gets or sets the aggregate ultra storage cost for all machines in the + * assessment. + * + * @return the monthlyUltraStorageCost value. + */ + public Float monthlyUltraStorageCost() { + return this.monthlyUltraStorageCost; + } + + /** + * Get the costComponents property: Gets the collection of cost components. + * + * @return the costComponents value. + */ + public List costComponents() { + return this.costComponents; + } + + /** + * Get the eaSubscriptionId property: Gets or sets enterprise agreement subscription id. + * + * @return the eaSubscriptionId value. + */ + public String eaSubscriptionId() { + return this.eaSubscriptionId; + } + + /** + * Set the eaSubscriptionId property: Gets or sets enterprise agreement subscription id. + * + * @param eaSubscriptionId the eaSubscriptionId value to set. + * @return the MachineAssessmentProperties object itself. + */ + public MachineAssessmentProperties withEaSubscriptionId(String eaSubscriptionId) { + this.eaSubscriptionId = eaSubscriptionId; + return this; + } + + /** + * Get the azurePricingTier property: Gets or sets Azure Pricing Tier - Free, Basic, etc. + * + * @return the azurePricingTier value. + */ + public AzurePricingTier azurePricingTier() { + return this.azurePricingTier; + } + + /** + * Set the azurePricingTier property: Gets or sets Azure Pricing Tier - Free, Basic, etc. + * + * @param azurePricingTier the azurePricingTier value to set. + * @return the MachineAssessmentProperties object itself. + */ + public MachineAssessmentProperties withAzurePricingTier(AzurePricingTier azurePricingTier) { + this.azurePricingTier = azurePricingTier; + return this; + } + + /** + * Get the azureStorageRedundancy property: Gets or sets the Azure Storage Redundancy. Example: Locally Redundant + * Storage. + * + * @return the azureStorageRedundancy value. + */ + public AzureStorageRedundancy azureStorageRedundancy() { + return this.azureStorageRedundancy; + } + + /** + * Set the azureStorageRedundancy property: Gets or sets the Azure Storage Redundancy. Example: Locally Redundant + * Storage. + * + * @param azureStorageRedundancy the azureStorageRedundancy value to set. + * @return the MachineAssessmentProperties object itself. + */ + public MachineAssessmentProperties withAzureStorageRedundancy(AzureStorageRedundancy azureStorageRedundancy) { + this.azureStorageRedundancy = azureStorageRedundancy; + return this; + } + + /** + * Get the reservedInstance property: Gets or sets the Azure Reserved Instance - 1-Year, 3-Year. + * + * @return the reservedInstance value. + */ + public AzureReservedInstance reservedInstance() { + return this.reservedInstance; + } + + /** + * Set the reservedInstance property: Gets or sets the Azure Reserved Instance - 1-Year, 3-Year. + * + * @param reservedInstance the reservedInstance value to set. + * @return the MachineAssessmentProperties object itself. + */ + public MachineAssessmentProperties withReservedInstance(AzureReservedInstance reservedInstance) { + this.reservedInstance = reservedInstance; + return this; + } + + /** + * Get the azureHybridUseBenefit property: Gets or sets the user configurable setting to display the azure hybrid + * use + * benefit. + * + * @return the azureHybridUseBenefit value. + */ + public AzureHybridUseBenefit azureHybridUseBenefit() { + return this.azureHybridUseBenefit; + } + + /** + * Set the azureHybridUseBenefit property: Gets or sets the user configurable setting to display the azure hybrid + * use + * benefit. + * + * @param azureHybridUseBenefit the azureHybridUseBenefit value to set. + * @return the MachineAssessmentProperties object itself. + */ + public MachineAssessmentProperties withAzureHybridUseBenefit(AzureHybridUseBenefit azureHybridUseBenefit) { + this.azureHybridUseBenefit = azureHybridUseBenefit; + return this; + } + + /** + * Get the azureDiskTypes property: Gets or sets the azure storage type. Premium, Standard etc. + * + * @return the azureDiskTypes value. + */ + public List azureDiskTypes() { + return this.azureDiskTypes; + } + + /** + * Set the azureDiskTypes property: Gets or sets the azure storage type. Premium, Standard etc. + * + * @param azureDiskTypes the azureDiskTypes value to set. + * @return the MachineAssessmentProperties object itself. + */ + public MachineAssessmentProperties withAzureDiskTypes(List azureDiskTypes) { + this.azureDiskTypes = azureDiskTypes; + return this; + } + + /** + * Get the azureVmFamilies property: Gets or sets the Azure VM families. + * + * @return the azureVmFamilies value. + */ + public List azureVmFamilies() { + return this.azureVmFamilies; + } + + /** + * Set the azureVmFamilies property: Gets or sets the Azure VM families. + * + * @param azureVmFamilies the azureVmFamilies value to set. + * @return the MachineAssessmentProperties object itself. + */ + public MachineAssessmentProperties withAzureVmFamilies(List azureVmFamilies) { + this.azureVmFamilies = azureVmFamilies; + return this; + } + + /** + * Get the distributionBySupportStatus property: Gets the distribution of sqlInstances by support status. + * + * @return the distributionBySupportStatus value. + */ + public Map distributionBySupportStatus() { + return this.distributionBySupportStatus; + } + + /** + * Get the distributionByServicePackInsight property: Gets the distribution distribution of sqlInstances by service + * pack insight. + * + * @return the distributionByServicePackInsight value. + */ + public Map distributionByServicePackInsight() { + return this.distributionByServicePackInsight; + } + + /** + * Get the distributionByOsName property: Gets the distribution by os name. + * + * @return the distributionByOsName value. + */ + public Map distributionByOsName() { + return this.distributionByOsName; + } + + /** + * Get the monthlyComputeCost property: Gets or sets the aggregate Compute Cost for all machines in the assessment. + * + * @return the monthlyComputeCost value. + */ + public Float monthlyComputeCost() { + return this.monthlyComputeCost; + } + + /** + * Get the monthlyBandwidthCost property: Gets or sets the aggregate Bandwidth Cost for all machines in the + * assessment. + * + * @return the monthlyBandwidthCost value. + */ + public Float monthlyBandwidthCost() { + return this.monthlyBandwidthCost; + } + + /** + * Get the monthlyStorageCost property: Gets or sets the aggregate Storage Cost for all machines in the assessment. + * + * @return the monthlyStorageCost value. + */ + public Float monthlyStorageCost() { + return this.monthlyStorageCost; + } + + /** + * Get the monthlyPremiumStorageCost property: Gets or sets the aggregate premium storage cost for all machines in + * the + * assessment. + * + * @return the monthlyPremiumStorageCost value. + */ + public Float monthlyPremiumStorageCost() { + return this.monthlyPremiumStorageCost; + } + + /** + * Get the monthlyStandardSsdStorageCost property: Gets or sets the aggregate standard SSD storage cost for all the + * machines in + * the assessment. + * + * @return the monthlyStandardSsdStorageCost value. + */ + public Float monthlyStandardSsdStorageCost() { + return this.monthlyStandardSsdStorageCost; + } + + /** + * Get the suitabilitySummary property: Gets or sets the Cloud suitability summary for all the machines in the + * assessment. + * + * @return the suitabilitySummary value. + */ + public Map suitabilitySummary() { + return this.suitabilitySummary; + } + + /** + * Get the numberOfMachines property: Gets or sets the Number of machines part of the assessment. + * + * @return the numberOfMachines value. + */ + public Integer numberOfMachines() { + return this.numberOfMachines; + } + + /** + * Get the vmUptime property: Gets or sets the duration for which the VMs are up in the on-premises + * environment. + * + * @return the vmUptime value. + */ + public VmUptime vmUptime() { + return this.vmUptime; + } + + /** + * Set the vmUptime property: Gets or sets the duration for which the VMs are up in the on-premises + * environment. + * + * @param vmUptime the vmUptime value to set. + * @return the MachineAssessmentProperties object itself. + */ + public MachineAssessmentProperties withVmUptime(VmUptime vmUptime) { + this.vmUptime = vmUptime; + return this; + } + + /** + * Get the groupType property: Gets the group type for the assessment. + * + * @return the groupType value. + */ + public GroupType groupType() { + return this.groupType; + } + + /** + * Get the assessmentType property: Assessment type of the assessment. + * + * @return the assessmentType value. + */ + public AssessmentType assessmentType() { + return this.assessmentType; + } + + /** + * Get the azureLocation property: Azure Location or Azure region where to which the machines will be migrated. + * + * @return the azureLocation value. + */ + public String azureLocation() { + return this.azureLocation; + } + + /** + * Set the azureLocation property: Azure Location or Azure region where to which the machines will be migrated. + * + * @param azureLocation the azureLocation value to set. + * @return the MachineAssessmentProperties object itself. + */ + public MachineAssessmentProperties withAzureLocation(String azureLocation) { + this.azureLocation = azureLocation; + return this; + } + + /** + * Get the azureOfferCode property: Azure Offer Code. + * + * @return the azureOfferCode value. + */ + public AzureOfferCode azureOfferCode() { + return this.azureOfferCode; + } + + /** + * Set the azureOfferCode property: Azure Offer Code. + * + * @param azureOfferCode the azureOfferCode value to set. + * @return the MachineAssessmentProperties object itself. + */ + public MachineAssessmentProperties withAzureOfferCode(AzureOfferCode azureOfferCode) { + this.azureOfferCode = azureOfferCode; + return this; + } + + /** + * Get the currency property: Currency in which prices should be reported. + * + * @return the currency value. + */ + public AzureCurrency currency() { + return this.currency; + } + + /** + * Set the currency property: Currency in which prices should be reported. + * + * @param currency the currency value to set. + * @return the MachineAssessmentProperties object itself. + */ + public MachineAssessmentProperties withCurrency(AzureCurrency currency) { + this.currency = currency; + return this; + } + + /** + * Get the scalingFactor property: Percentage of buffer that user wants on performance metrics when recommending + * Azure sizes. + * + * @return the scalingFactor value. + */ + public Float scalingFactor() { + return this.scalingFactor; + } + + /** + * Set the scalingFactor property: Percentage of buffer that user wants on performance metrics when recommending + * Azure sizes. + * + * @param scalingFactor the scalingFactor value to set. + * @return the MachineAssessmentProperties object itself. + */ + public MachineAssessmentProperties withScalingFactor(Float scalingFactor) { + this.scalingFactor = scalingFactor; + return this; + } + + /** + * Get the percentile property: Percentile of the utilization data values to be considered while assessing + * machines. + * + * @return the percentile value. + */ + public Percentile percentile() { + return this.percentile; + } + + /** + * Set the percentile property: Percentile of the utilization data values to be considered while assessing + * machines. + * + * @param percentile the percentile value to set. + * @return the MachineAssessmentProperties object itself. + */ + public MachineAssessmentProperties withPercentile(Percentile percentile) { + this.percentile = percentile; + return this; + } + + /** + * Get the timeRange property: Time Range for which the historic utilization data should be considered for + * assessment. + * + * @return the timeRange value. + */ + public TimeRange timeRange() { + return this.timeRange; + } + + /** + * Set the timeRange property: Time Range for which the historic utilization data should be considered for + * assessment. + * + * @param timeRange the timeRange value to set. + * @return the MachineAssessmentProperties object itself. + */ + public MachineAssessmentProperties withTimeRange(TimeRange timeRange) { + this.timeRange = timeRange; + return this; + } + + /** + * Get the perfDataStartTime property: Gets or sets the start time to consider performance data for assessment. + * + * @return the perfDataStartTime value. + */ + public OffsetDateTime perfDataStartTime() { + return this.perfDataStartTime; + } + + /** + * Set the perfDataStartTime property: Gets or sets the start time to consider performance data for assessment. + * + * @param perfDataStartTime the perfDataStartTime value to set. + * @return the MachineAssessmentProperties object itself. + */ + public MachineAssessmentProperties withPerfDataStartTime(OffsetDateTime perfDataStartTime) { + this.perfDataStartTime = perfDataStartTime; + return this; + } + + /** + * Get the perfDataEndTime property: Gets or sets the end time to consider performance data for assessment. + * + * @return the perfDataEndTime value. + */ + public OffsetDateTime perfDataEndTime() { + return this.perfDataEndTime; + } + + /** + * Set the perfDataEndTime property: Gets or sets the end time to consider performance data for assessment. + * + * @param perfDataEndTime the perfDataEndTime value to set. + * @return the MachineAssessmentProperties object itself. + */ + public MachineAssessmentProperties withPerfDataEndTime(OffsetDateTime perfDataEndTime) { + this.perfDataEndTime = perfDataEndTime; + return this; + } + + /** + * Get the stage property: User configurable setting to display the Stage of Assessment. + * + * @return the stage value. + */ + public AssessmentStage stage() { + return this.stage; + } + + /** + * Get the discountPercentage property: Custom discount percentage. + * + * @return the discountPercentage value. + */ + public Float discountPercentage() { + return this.discountPercentage; + } + + /** + * Set the discountPercentage property: Custom discount percentage. + * + * @param discountPercentage the discountPercentage value to set. + * @return the MachineAssessmentProperties object itself. + */ + public MachineAssessmentProperties withDiscountPercentage(Float discountPercentage) { + this.discountPercentage = discountPercentage; + return this; + } + + /** + * Get the sizingCriterion property: Assessment sizing criterion. + * + * @return the sizingCriterion value. + */ + public AssessmentSizingCriterion sizingCriterion() { + return this.sizingCriterion; + } + + /** + * Set the sizingCriterion property: Assessment sizing criterion. + * + * @param sizingCriterion the sizingCriterion value to set. + * @return the MachineAssessmentProperties object itself. + */ + public MachineAssessmentProperties withSizingCriterion(AssessmentSizingCriterion sizingCriterion) { + this.sizingCriterion = sizingCriterion; + return this; + } + + /** + * Get the confidenceRatingInPercentage property: Confidence Rating in Percentage. + * + * @return the confidenceRatingInPercentage value. + */ + public Float confidenceRatingInPercentage() { + return this.confidenceRatingInPercentage; + } + + /** + * Get the pricesTimestamp property: Last time when rates were queried. + * + * @return the pricesTimestamp value. + */ + public OffsetDateTime pricesTimestamp() { + return this.pricesTimestamp; + } + + /** + * Get the createdTimestamp property: Date and Time when assessment was created. + * + * @return the createdTimestamp value. + */ + public OffsetDateTime createdTimestamp() { + return this.createdTimestamp; + } + + /** + * Get the updatedTimestamp property: Date and Time when assessment was last updated. + * + * @return the updatedTimestamp value. + */ + public OffsetDateTime updatedTimestamp() { + return this.updatedTimestamp; + } + + /** + * Get the status property: Whether assessment is in valid state and all machines have been assessed. + * + * @return the status value. + */ + public AssessmentStatus status() { + return this.status; + } + + /** + * Get the schemaVersion property: Schema version. + * + * @return the schemaVersion value. + */ + public String schemaVersion() { + return this.schemaVersion; + } + + /** + * {@inheritDoc} + */ + @Override + public MachineAssessmentProperties withProvisioningState(ProvisioningState provisioningState) { + super.withProvisioningState(provisioningState); + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + @Override + public void validate() { + if (costComponents() != null) { + costComponents().forEach(e -> e.validate()); + } + if (vmUptime() != null) { + vmUptime().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("provisioningState", + provisioningState() == null ? null : provisioningState().toString()); + jsonWriter.writeStringField("eaSubscriptionId", this.eaSubscriptionId); + jsonWriter.writeStringField("azurePricingTier", + this.azurePricingTier == null ? null : this.azurePricingTier.toString()); + jsonWriter.writeStringField("azureStorageRedundancy", + this.azureStorageRedundancy == null ? null : this.azureStorageRedundancy.toString()); + jsonWriter.writeStringField("reservedInstance", + this.reservedInstance == null ? null : this.reservedInstance.toString()); + jsonWriter.writeStringField("azureHybridUseBenefit", + this.azureHybridUseBenefit == null ? null : this.azureHybridUseBenefit.toString()); + jsonWriter.writeArrayField("azureDiskTypes", this.azureDiskTypes, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); + jsonWriter.writeArrayField("azureVmFamilies", this.azureVmFamilies, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); + jsonWriter.writeJsonField("vmUptime", this.vmUptime); + jsonWriter.writeStringField("azureLocation", this.azureLocation); + jsonWriter.writeStringField("azureOfferCode", + this.azureOfferCode == null ? null : this.azureOfferCode.toString()); + jsonWriter.writeStringField("currency", this.currency == null ? null : this.currency.toString()); + jsonWriter.writeNumberField("scalingFactor", this.scalingFactor); + jsonWriter.writeStringField("percentile", this.percentile == null ? null : this.percentile.toString()); + jsonWriter.writeStringField("timeRange", this.timeRange == null ? null : this.timeRange.toString()); + jsonWriter.writeStringField("perfDataStartTime", + this.perfDataStartTime == null + ? null + : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.perfDataStartTime)); + jsonWriter.writeStringField("perfDataEndTime", + this.perfDataEndTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.perfDataEndTime)); + jsonWriter.writeNumberField("discountPercentage", this.discountPercentage); + jsonWriter.writeStringField("sizingCriterion", + this.sizingCriterion == null ? null : this.sizingCriterion.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of MachineAssessmentProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of MachineAssessmentProperties 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 MachineAssessmentProperties. + */ + public static MachineAssessmentProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + MachineAssessmentProperties deserializedMachineAssessmentProperties = new MachineAssessmentProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("provisioningState".equals(fieldName)) { + deserializedMachineAssessmentProperties + .withProvisioningState(ProvisioningState.fromString(reader.getString())); + } else if ("assessmentErrorSummary".equals(fieldName)) { + Map assessmentErrorSummary = reader.readMap(reader1 -> reader1.getInt()); + deserializedMachineAssessmentProperties.assessmentErrorSummary = assessmentErrorSummary; + } else if ("monthlyUltraStorageCost".equals(fieldName)) { + deserializedMachineAssessmentProperties.monthlyUltraStorageCost + = reader.getNullable(JsonReader::getFloat); + } else if ("costComponents".equals(fieldName)) { + List costComponents = reader.readArray(reader1 -> CostComponent.fromJson(reader1)); + deserializedMachineAssessmentProperties.costComponents = costComponents; + } else if ("eaSubscriptionId".equals(fieldName)) { + deserializedMachineAssessmentProperties.eaSubscriptionId = reader.getString(); + } else if ("azurePricingTier".equals(fieldName)) { + deserializedMachineAssessmentProperties.azurePricingTier + = AzurePricingTier.fromString(reader.getString()); + } else if ("azureStorageRedundancy".equals(fieldName)) { + deserializedMachineAssessmentProperties.azureStorageRedundancy + = AzureStorageRedundancy.fromString(reader.getString()); + } else if ("reservedInstance".equals(fieldName)) { + deserializedMachineAssessmentProperties.reservedInstance + = AzureReservedInstance.fromString(reader.getString()); + } else if ("azureHybridUseBenefit".equals(fieldName)) { + deserializedMachineAssessmentProperties.azureHybridUseBenefit + = AzureHybridUseBenefit.fromString(reader.getString()); + } else if ("azureDiskTypes".equals(fieldName)) { + List azureDiskTypes + = reader.readArray(reader1 -> AzureDiskType.fromString(reader1.getString())); + deserializedMachineAssessmentProperties.azureDiskTypes = azureDiskTypes; + } else if ("azureVmFamilies".equals(fieldName)) { + List azureVmFamilies + = reader.readArray(reader1 -> AzureVmFamily.fromString(reader1.getString())); + deserializedMachineAssessmentProperties.azureVmFamilies = azureVmFamilies; + } else if ("distributionBySupportStatus".equals(fieldName)) { + Map distributionBySupportStatus = reader.readMap(reader1 -> reader1.getInt()); + deserializedMachineAssessmentProperties.distributionBySupportStatus = distributionBySupportStatus; + } else if ("distributionByServicePackInsight".equals(fieldName)) { + Map distributionByServicePackInsight = reader.readMap(reader1 -> reader1.getInt()); + deserializedMachineAssessmentProperties.distributionByServicePackInsight + = distributionByServicePackInsight; + } else if ("distributionByOsName".equals(fieldName)) { + Map distributionByOsName = reader.readMap(reader1 -> reader1.getInt()); + deserializedMachineAssessmentProperties.distributionByOsName = distributionByOsName; + } else if ("monthlyComputeCost".equals(fieldName)) { + deserializedMachineAssessmentProperties.monthlyComputeCost + = reader.getNullable(JsonReader::getFloat); + } else if ("monthlyBandwidthCost".equals(fieldName)) { + deserializedMachineAssessmentProperties.monthlyBandwidthCost + = reader.getNullable(JsonReader::getFloat); + } else if ("monthlyStorageCost".equals(fieldName)) { + deserializedMachineAssessmentProperties.monthlyStorageCost + = reader.getNullable(JsonReader::getFloat); + } else if ("monthlyPremiumStorageCost".equals(fieldName)) { + deserializedMachineAssessmentProperties.monthlyPremiumStorageCost + = reader.getNullable(JsonReader::getFloat); + } else if ("monthlyStandardSsdStorageCost".equals(fieldName)) { + deserializedMachineAssessmentProperties.monthlyStandardSsdStorageCost + = reader.getNullable(JsonReader::getFloat); + } else if ("suitabilitySummary".equals(fieldName)) { + Map suitabilitySummary = reader.readMap(reader1 -> reader1.getInt()); + deserializedMachineAssessmentProperties.suitabilitySummary = suitabilitySummary; + } else if ("numberOfMachines".equals(fieldName)) { + deserializedMachineAssessmentProperties.numberOfMachines = reader.getNullable(JsonReader::getInt); + } else if ("vmUptime".equals(fieldName)) { + deserializedMachineAssessmentProperties.vmUptime = VmUptime.fromJson(reader); + } else if ("groupType".equals(fieldName)) { + deserializedMachineAssessmentProperties.groupType = GroupType.fromString(reader.getString()); + } else if ("assessmentType".equals(fieldName)) { + deserializedMachineAssessmentProperties.assessmentType + = AssessmentType.fromString(reader.getString()); + } else if ("azureLocation".equals(fieldName)) { + deserializedMachineAssessmentProperties.azureLocation = reader.getString(); + } else if ("azureOfferCode".equals(fieldName)) { + deserializedMachineAssessmentProperties.azureOfferCode + = AzureOfferCode.fromString(reader.getString()); + } else if ("currency".equals(fieldName)) { + deserializedMachineAssessmentProperties.currency = AzureCurrency.fromString(reader.getString()); + } else if ("scalingFactor".equals(fieldName)) { + deserializedMachineAssessmentProperties.scalingFactor = reader.getNullable(JsonReader::getFloat); + } else if ("percentile".equals(fieldName)) { + deserializedMachineAssessmentProperties.percentile = Percentile.fromString(reader.getString()); + } else if ("timeRange".equals(fieldName)) { + deserializedMachineAssessmentProperties.timeRange = TimeRange.fromString(reader.getString()); + } else if ("perfDataStartTime".equals(fieldName)) { + deserializedMachineAssessmentProperties.perfDataStartTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("perfDataEndTime".equals(fieldName)) { + deserializedMachineAssessmentProperties.perfDataEndTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("stage".equals(fieldName)) { + deserializedMachineAssessmentProperties.stage = AssessmentStage.fromString(reader.getString()); + } else if ("discountPercentage".equals(fieldName)) { + deserializedMachineAssessmentProperties.discountPercentage + = reader.getNullable(JsonReader::getFloat); + } else if ("sizingCriterion".equals(fieldName)) { + deserializedMachineAssessmentProperties.sizingCriterion + = AssessmentSizingCriterion.fromString(reader.getString()); + } else if ("confidenceRatingInPercentage".equals(fieldName)) { + deserializedMachineAssessmentProperties.confidenceRatingInPercentage + = reader.getNullable(JsonReader::getFloat); + } else if ("pricesTimestamp".equals(fieldName)) { + deserializedMachineAssessmentProperties.pricesTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("createdTimestamp".equals(fieldName)) { + deserializedMachineAssessmentProperties.createdTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("updatedTimestamp".equals(fieldName)) { + deserializedMachineAssessmentProperties.updatedTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("status".equals(fieldName)) { + deserializedMachineAssessmentProperties.status = AssessmentStatus.fromString(reader.getString()); + } else if ("schemaVersion".equals(fieldName)) { + deserializedMachineAssessmentProperties.schemaVersion = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedMachineAssessmentProperties; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/MachineBootType.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/MachineBootType.java new file mode 100644 index 000000000000..53c1015b57d7 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/MachineBootType.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for MachineBootType. + */ +public final class MachineBootType extends ExpandableStringEnum { + /** + * Static value Unknown for MachineBootType. + */ + public static final MachineBootType UNKNOWN = fromString("Unknown"); + + /** + * Static value EFI for MachineBootType. + */ + public static final MachineBootType EFI = fromString("EFI"); + + /** + * Static value BIOS for MachineBootType. + */ + public static final MachineBootType BIOS = fromString("BIOS"); + + /** + * Static value NotSpecified for MachineBootType. + */ + public static final MachineBootType NOT_SPECIFIED = fromString("NotSpecified"); + + /** + * Creates a new instance of MachineBootType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public MachineBootType() { + } + + /** + * Creates or finds a MachineBootType from its string representation. + * + * @param name a name to look for. + * @return the corresponding MachineBootType. + */ + public static MachineBootType fromString(String name) { + return fromString(name, MachineBootType.class); + } + + /** + * Gets known MachineBootType values. + * + * @return known MachineBootType values. + */ + public static Collection values() { + return values(MachineBootType.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/MachineListResult.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/MachineListResult.java new file mode 100644 index 000000000000..b4b0e840a30f --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/MachineListResult.java @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.fluent.models.MachineInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a Machine list operation. + */ +@Fluent +public final class MachineListResult implements JsonSerializable { + /* + * The Machine items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of MachineListResult class. + */ + public MachineListResult() { + } + + /** + * Get the value property: The Machine items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Set the value property: The Machine items on this page. + * + * @param value the value value to set. + * @return the MachineListResult object itself. + */ + public MachineListResult withValue(List value) { + this.value = value; + return this; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The link to the next page of items. + * + * @param nextLink the nextLink value to set. + * @return the MachineListResult object itself. + */ + public MachineListResult withNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property value in model MachineListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(MachineListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of MachineListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of MachineListResult 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 MachineListResult. + */ + public static MachineListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + MachineListResult deserializedMachineListResult = new MachineListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value = reader.readArray(reader1 -> MachineInner.fromJson(reader1)); + deserializedMachineListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedMachineListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedMachineListResult; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/MachineProperties.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/MachineProperties.java new file mode 100644 index 000000000000..c42cfabd2852 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/MachineProperties.java @@ -0,0 +1,456 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.util.List; +import java.util.Map; + +/** + * Properties of a machine. + */ +@Immutable +public final class MachineProperties implements JsonSerializable { + /* + * Gets or sets workload summary. + */ + private WorkloadSummary workloadSummary; + + /* + * List of errors for this machine. + */ + private List errors; + + /* + * Gets Processor details of the host. + */ + private ProcessorInfo hostProcessor; + + /* + * Gets the product support status related details. + */ + private ProductSupportStatus productSupportStatus; + + /* + * Site id of machine discovered in private data center. + */ + private String discoveryMachineArmId; + + /* + * The data center management server ARM Id for the machine. + */ + private String datacenterManagementServerArmId; + + /* + * The data center management server name for the machine. + */ + private String datacenterManagementServerName; + + /* + * Boot type of machine discovered in private data center. + */ + private MachineBootType bootType; + + /* + * Display Name of the Machine. + */ + private String displayName; + + /* + * Megabytes of memory found allocated for the machine in private data center. + */ + private Float megabytesOfMemory; + + /* + * Number of CPU cores found on the machine. + */ + private Integer numberOfCores; + + /* + * Operating system as reported by datacenter management solution. + */ + private String operatingSystemType; + + /* + * Operating system as reported by datacenter management solution. + */ + private String operatingSystemName; + + /* + * Operating system version as reported by datacenter management solution. + */ + private String operatingSystemVersion; + + /* + * Description for the machine. + */ + private String description; + + /* + * When was machine first created. + */ + private OffsetDateTime createdTimestamp; + + /* + * Disks attached to the machine discovered in private data center. + */ + private Map disks; + + /* + * Gets the References to the groups that this machine is member of. + */ + private List groups; + + /* + * Network adapters attached to the machine discovered in private data center. + */ + private Map networkAdapters; + + /* + * SQL instances discovered on the machine. + */ + private List sqlInstances; + + /* + * Web applications discovered on the machine. + */ + private List webApplications; + + /* + * When was machine last updated. + */ + private OffsetDateTime updatedTimestamp; + + /** + * Creates an instance of MachineProperties class. + */ + public MachineProperties() { + } + + /** + * Get the workloadSummary property: Gets or sets workload summary. + * + * @return the workloadSummary value. + */ + public WorkloadSummary workloadSummary() { + return this.workloadSummary; + } + + /** + * Get the errors property: List of errors for this machine. + * + * @return the errors value. + */ + public List errors() { + return this.errors; + } + + /** + * Get the hostProcessor property: Gets Processor details of the host. + * + * @return the hostProcessor value. + */ + public ProcessorInfo hostProcessor() { + return this.hostProcessor; + } + + /** + * Get the productSupportStatus property: Gets the product support status related details. + * + * @return the productSupportStatus value. + */ + public ProductSupportStatus productSupportStatus() { + return this.productSupportStatus; + } + + /** + * Get the discoveryMachineArmId property: Site id of machine discovered in private data center. + * + * @return the discoveryMachineArmId value. + */ + public String discoveryMachineArmId() { + return this.discoveryMachineArmId; + } + + /** + * Get the datacenterManagementServerArmId property: The data center management server ARM Id for the machine. + * + * @return the datacenterManagementServerArmId value. + */ + public String datacenterManagementServerArmId() { + return this.datacenterManagementServerArmId; + } + + /** + * Get the datacenterManagementServerName property: The data center management server name for the machine. + * + * @return the datacenterManagementServerName value. + */ + public String datacenterManagementServerName() { + return this.datacenterManagementServerName; + } + + /** + * Get the bootType property: Boot type of machine discovered in private data center. + * + * @return the bootType value. + */ + public MachineBootType bootType() { + return this.bootType; + } + + /** + * Get the displayName property: Display Name of the Machine. + * + * @return the displayName value. + */ + public String displayName() { + return this.displayName; + } + + /** + * Get the megabytesOfMemory property: Megabytes of memory found allocated for the machine in private data center. + * + * @return the megabytesOfMemory value. + */ + public Float megabytesOfMemory() { + return this.megabytesOfMemory; + } + + /** + * Get the numberOfCores property: Number of CPU cores found on the machine. + * + * @return the numberOfCores value. + */ + public Integer numberOfCores() { + return this.numberOfCores; + } + + /** + * Get the operatingSystemType property: Operating system as reported by datacenter management solution. + * + * @return the operatingSystemType value. + */ + public String operatingSystemType() { + return this.operatingSystemType; + } + + /** + * Get the operatingSystemName property: Operating system as reported by datacenter management solution. + * + * @return the operatingSystemName value. + */ + public String operatingSystemName() { + return this.operatingSystemName; + } + + /** + * Get the operatingSystemVersion property: Operating system version as reported by datacenter management solution. + * + * @return the operatingSystemVersion value. + */ + public String operatingSystemVersion() { + return this.operatingSystemVersion; + } + + /** + * Get the description property: Description for the machine. + * + * @return the description value. + */ + public String description() { + return this.description; + } + + /** + * Get the createdTimestamp property: When was machine first created. + * + * @return the createdTimestamp value. + */ + public OffsetDateTime createdTimestamp() { + return this.createdTimestamp; + } + + /** + * Get the disks property: Disks attached to the machine discovered in private data center. + * + * @return the disks value. + */ + public Map disks() { + return this.disks; + } + + /** + * Get the groups property: Gets the References to the groups that this machine is member of. + * + * @return the groups value. + */ + public List groups() { + return this.groups; + } + + /** + * Get the networkAdapters property: Network adapters attached to the machine discovered in private data center. + * + * @return the networkAdapters value. + */ + public Map networkAdapters() { + return this.networkAdapters; + } + + /** + * Get the sqlInstances property: SQL instances discovered on the machine. + * + * @return the sqlInstances value. + */ + public List sqlInstances() { + return this.sqlInstances; + } + + /** + * Get the webApplications property: Web applications discovered on the machine. + * + * @return the webApplications value. + */ + public List webApplications() { + return this.webApplications; + } + + /** + * Get the updatedTimestamp property: When was machine last updated. + * + * @return the updatedTimestamp value. + */ + public OffsetDateTime updatedTimestamp() { + return this.updatedTimestamp; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (workloadSummary() != null) { + workloadSummary().validate(); + } + if (errors() != null) { + errors().forEach(e -> e.validate()); + } + if (hostProcessor() != null) { + hostProcessor().validate(); + } + if (productSupportStatus() != null) { + productSupportStatus().validate(); + } + if (disks() != null) { + disks().values().forEach(e -> { + if (e != null) { + e.validate(); + } + }); + } + if (networkAdapters() != null) { + networkAdapters().values().forEach(e -> { + if (e != null) { + e.validate(); + } + }); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of MachineProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of MachineProperties 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 MachineProperties. + */ + public static MachineProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + MachineProperties deserializedMachineProperties = new MachineProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("workloadSummary".equals(fieldName)) { + deserializedMachineProperties.workloadSummary = WorkloadSummary.fromJson(reader); + } else if ("errors".equals(fieldName)) { + List errors = reader.readArray(reader1 -> Error.fromJson(reader1)); + deserializedMachineProperties.errors = errors; + } else if ("hostProcessor".equals(fieldName)) { + deserializedMachineProperties.hostProcessor = ProcessorInfo.fromJson(reader); + } else if ("productSupportStatus".equals(fieldName)) { + deserializedMachineProperties.productSupportStatus = ProductSupportStatus.fromJson(reader); + } else if ("discoveryMachineArmId".equals(fieldName)) { + deserializedMachineProperties.discoveryMachineArmId = reader.getString(); + } else if ("datacenterManagementServerArmId".equals(fieldName)) { + deserializedMachineProperties.datacenterManagementServerArmId = reader.getString(); + } else if ("datacenterManagementServerName".equals(fieldName)) { + deserializedMachineProperties.datacenterManagementServerName = reader.getString(); + } else if ("bootType".equals(fieldName)) { + deserializedMachineProperties.bootType = MachineBootType.fromString(reader.getString()); + } else if ("displayName".equals(fieldName)) { + deserializedMachineProperties.displayName = reader.getString(); + } else if ("megabytesOfMemory".equals(fieldName)) { + deserializedMachineProperties.megabytesOfMemory = reader.getNullable(JsonReader::getFloat); + } else if ("numberOfCores".equals(fieldName)) { + deserializedMachineProperties.numberOfCores = reader.getNullable(JsonReader::getInt); + } else if ("operatingSystemType".equals(fieldName)) { + deserializedMachineProperties.operatingSystemType = reader.getString(); + } else if ("operatingSystemName".equals(fieldName)) { + deserializedMachineProperties.operatingSystemName = reader.getString(); + } else if ("operatingSystemVersion".equals(fieldName)) { + deserializedMachineProperties.operatingSystemVersion = reader.getString(); + } else if ("description".equals(fieldName)) { + deserializedMachineProperties.description = reader.getString(); + } else if ("createdTimestamp".equals(fieldName)) { + deserializedMachineProperties.createdTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("disks".equals(fieldName)) { + Map disks = reader.readMap(reader1 -> Disk.fromJson(reader1)); + deserializedMachineProperties.disks = disks; + } else if ("groups".equals(fieldName)) { + List groups = reader.readArray(reader1 -> reader1.getString()); + deserializedMachineProperties.groups = groups; + } else if ("networkAdapters".equals(fieldName)) { + Map networkAdapters + = reader.readMap(reader1 -> NetworkAdapter.fromJson(reader1)); + deserializedMachineProperties.networkAdapters = networkAdapters; + } else if ("sqlInstances".equals(fieldName)) { + List sqlInstances = reader.readArray(reader1 -> reader1.getString()); + deserializedMachineProperties.sqlInstances = sqlInstances; + } else if ("webApplications".equals(fieldName)) { + List webApplications = reader.readArray(reader1 -> reader1.getString()); + deserializedMachineProperties.webApplications = webApplications; + } else if ("updatedTimestamp".equals(fieldName)) { + deserializedMachineProperties.updatedTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else { + reader.skipChildren(); + } + } + + return deserializedMachineProperties; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/MachinesOperations.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/MachinesOperations.java new file mode 100644 index 000000000000..9df82549ae98 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/MachinesOperations.java @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of MachinesOperations. + */ +public interface MachinesOperations { + /** + * List Machine resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Machine list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName); + + /** + * List Machine resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param filter Filter query. + * @param pageSize Optional parameter for page size. + * @param continuationToken Optional parameter for continuation token. + * @param totalRecordCount Total record count. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Machine list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, String filter, + Integer pageSize, String continuationToken, Integer totalRecordCount, Context context); + + /** + * Get a Machine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param machineName Assessible Machine ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Machine along with {@link Response}. + */ + Response getWithResponse(String resourceGroupName, String projectName, String machineName, + Context context); + + /** + * Get a Machine. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param machineName Assessible Machine ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a Machine. + */ + Machine get(String resourceGroupName, String projectName, String machineName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/MigrationGuidelineContext.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/MigrationGuidelineContext.java new file mode 100644 index 000000000000..291a558b8afc --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/MigrationGuidelineContext.java @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * Migration Guideline Context. + */ +@Fluent +public final class MigrationGuidelineContext implements JsonSerializable { + /* + * Gets the reasoning context key. + */ + private String contextKey; + + /* + * Gets the reasoning context value. + */ + private String contextValue; + + /** + * Creates an instance of MigrationGuidelineContext class. + */ + public MigrationGuidelineContext() { + } + + /** + * Get the contextKey property: Gets the reasoning context key. + * + * @return the contextKey value. + */ + public String contextKey() { + return this.contextKey; + } + + /** + * Set the contextKey property: Gets the reasoning context key. + * + * @param contextKey the contextKey value to set. + * @return the MigrationGuidelineContext object itself. + */ + public MigrationGuidelineContext withContextKey(String contextKey) { + this.contextKey = contextKey; + return this; + } + + /** + * Get the contextValue property: Gets the reasoning context value. + * + * @return the contextValue value. + */ + public String contextValue() { + return this.contextValue; + } + + /** + * Set the contextValue property: Gets the reasoning context value. + * + * @param contextValue the contextValue value to set. + * @return the MigrationGuidelineContext object itself. + */ + public MigrationGuidelineContext withContextValue(String contextValue) { + this.contextValue = contextValue; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("contextKey", this.contextKey); + jsonWriter.writeStringField("contextValue", this.contextValue); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of MigrationGuidelineContext from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of MigrationGuidelineContext 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 MigrationGuidelineContext. + */ + public static MigrationGuidelineContext fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + MigrationGuidelineContext deserializedMigrationGuidelineContext = new MigrationGuidelineContext(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("contextKey".equals(fieldName)) { + deserializedMigrationGuidelineContext.contextKey = reader.getString(); + } else if ("contextValue".equals(fieldName)) { + deserializedMigrationGuidelineContext.contextValue = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedMigrationGuidelineContext; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/MultiSubnetIntent.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/MultiSubnetIntent.java new file mode 100644 index 000000000000..cc091ef618fc --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/MultiSubnetIntent.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. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for MultiSubnetIntent. + */ +public final class MultiSubnetIntent extends ExpandableStringEnum { + /** + * Static value None for MultiSubnetIntent. + */ + public static final MultiSubnetIntent NONE = fromString("None"); + + /** + * Static value HighAvailability for MultiSubnetIntent. + */ + public static final MultiSubnetIntent HIGH_AVAILABILITY = fromString("HighAvailability"); + + /** + * Static value DisasterRecovery for MultiSubnetIntent. + */ + public static final MultiSubnetIntent DISASTER_RECOVERY = fromString("DisasterRecovery"); + + /** + * Creates a new instance of MultiSubnetIntent value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public MultiSubnetIntent() { + } + + /** + * Creates or finds a MultiSubnetIntent from its string representation. + * + * @param name a name to look for. + * @return the corresponding MultiSubnetIntent. + */ + public static MultiSubnetIntent fromString(String name) { + return fromString(name, MultiSubnetIntent.class); + } + + /** + * Gets known MultiSubnetIntent values. + * + * @return known MultiSubnetIntent values. + */ + public static Collection values() { + return values(MultiSubnetIntent.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/NetworkAdapter.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/NetworkAdapter.java new file mode 100644 index 000000000000..b4976325579e --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/NetworkAdapter.java @@ -0,0 +1,115 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; +import java.util.List; + +/** + * A network adapter discovered on a machine. + */ +@Immutable +public final class NetworkAdapter implements JsonSerializable { + /* + * MAC Address of the network adapter. + */ + private String macAddress; + + /* + * List of IP Addresses on the network adapter. + */ + private List ipAddresses; + + /* + * User friendly name of the network adapter. + */ + private String displayName; + + /** + * Creates an instance of NetworkAdapter class. + */ + public NetworkAdapter() { + } + + /** + * Get the macAddress property: MAC Address of the network adapter. + * + * @return the macAddress value. + */ + public String macAddress() { + return this.macAddress; + } + + /** + * Get the ipAddresses property: List of IP Addresses on the network adapter. + * + * @return the ipAddresses value. + */ + public List ipAddresses() { + return this.ipAddresses; + } + + /** + * Get the displayName property: User friendly name of the network adapter. + * + * @return the displayName value. + */ + public String displayName() { + return this.displayName; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of NetworkAdapter from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of NetworkAdapter 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 NetworkAdapter. + */ + public static NetworkAdapter fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + NetworkAdapter deserializedNetworkAdapter = new NetworkAdapter(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("macAddress".equals(fieldName)) { + deserializedNetworkAdapter.macAddress = reader.getString(); + } else if ("ipAddresses".equals(fieldName)) { + List ipAddresses = reader.readArray(reader1 -> reader1.getString()); + deserializedNetworkAdapter.ipAddresses = ipAddresses; + } else if ("displayName".equals(fieldName)) { + deserializedNetworkAdapter.displayName = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedNetworkAdapter; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/Operation.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/Operation.java new file mode 100644 index 000000000000..2d07e4100208 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/Operation.java @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.resourcemanager.migration.assessment.fluent.models.OperationInner; + +/** + * An immutable client-side representation of Operation. + */ +public interface Operation { + /** + * Gets the name property: The name of the operation, as per Resource-Based Access Control (RBAC). Examples: + * "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action". + * + * @return the name value. + */ + String name(); + + /** + * Gets the isDataAction property: Whether the operation applies to data-plane. This is "true" for data-plane + * operations and "false" for ARM/control-plane operations. + * + * @return the isDataAction value. + */ + Boolean isDataAction(); + + /** + * Gets the display property: Localized display information for this particular operation. + * + * @return the display value. + */ + OperationDisplay display(); + + /** + * Gets the origin property: The intended executor of the operation; as in Resource Based Access Control (RBAC) and + * audit logs UX. Default value is "user,system". + * + * @return the origin value. + */ + Origin origin(); + + /** + * Gets the actionType property: Enum. Indicates the action type. "Internal" refers to actions that are for internal + * only APIs. + * + * @return the actionType value. + */ + ActionType actionType(); + + /** + * Gets the inner com.azure.resourcemanager.migration.assessment.fluent.models.OperationInner object. + * + * @return the inner object. + */ + OperationInner innerModel(); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/OperationDisplay.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/OperationDisplay.java new file mode 100644 index 000000000000..6e73b7aae51b --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/OperationDisplay.java @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * Localized display information for this particular operation. + */ +@Immutable +public final class OperationDisplay implements JsonSerializable { + /* + * The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or + * "Microsoft Compute". + */ + private String provider; + + /* + * The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or + * "Job Schedule Collections". + */ + private String resource; + + /* + * The concise, localized friendly name for the operation; suitable for dropdowns. E.g. + * "Create or Update Virtual Machine", "Restart Virtual Machine". + */ + private String operation; + + /* + * The short, localized friendly description of the operation; suitable for tool tips and detailed views. + */ + private String description; + + /** + * Creates an instance of OperationDisplay class. + */ + public OperationDisplay() { + } + + /** + * Get the provider property: The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring + * Insights" or "Microsoft Compute". + * + * @return the provider value. + */ + public String provider() { + return this.provider; + } + + /** + * Get the resource property: The localized friendly name of the resource type related to this operation. E.g. + * "Virtual Machines" or "Job Schedule Collections". + * + * @return the resource value. + */ + public String resource() { + return this.resource; + } + + /** + * Get the operation property: The concise, localized friendly name for the operation; suitable for dropdowns. E.g. + * "Create or Update Virtual Machine", "Restart Virtual Machine". + * + * @return the operation value. + */ + public String operation() { + return this.operation; + } + + /** + * Get the description property: The short, localized friendly description of the operation; suitable for tool tips + * and detailed views. + * + * @return the description value. + */ + public String description() { + return this.description; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OperationDisplay from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OperationDisplay 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 OperationDisplay. + */ + public static OperationDisplay fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OperationDisplay deserializedOperationDisplay = new OperationDisplay(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("provider".equals(fieldName)) { + deserializedOperationDisplay.provider = reader.getString(); + } else if ("resource".equals(fieldName)) { + deserializedOperationDisplay.resource = reader.getString(); + } else if ("operation".equals(fieldName)) { + deserializedOperationDisplay.operation = reader.getString(); + } else if ("description".equals(fieldName)) { + deserializedOperationDisplay.description = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedOperationDisplay; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/OperationListResult.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/OperationListResult.java new file mode 100644 index 000000000000..37909f7f4751 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/OperationListResult.java @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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 com.azure.resourcemanager.migration.assessment.fluent.models.OperationInner; +import java.io.IOException; +import java.util.List; + +/** + * A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + * results. + */ +@Immutable +public final class OperationListResult implements JsonSerializable { + /* + * List of operations supported by the resource provider + */ + private List value; + + /* + * URL to get the next set of operation list results (if there are any). + */ + private String nextLink; + + /** + * Creates an instance of OperationListResult class. + */ + public OperationListResult() { + } + + /** + * Get the value property: List of operations supported by the resource provider. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Get the nextLink property: URL to get the next set of operation list results (if there are any). + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() != null) { + value().forEach(e -> e.validate()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OperationListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OperationListResult 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 OperationListResult. + */ + public static OperationListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OperationListResult deserializedOperationListResult = new OperationListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value = reader.readArray(reader1 -> OperationInner.fromJson(reader1)); + deserializedOperationListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedOperationListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedOperationListResult; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/Operations.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/Operations.java new file mode 100644 index 000000000000..407f2c93a10f --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/Operations.java @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.Context; + +/** + * Resource collection API of Operations. + */ +public interface Operations { + /** + * List the operations for the provider. + * + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedIterable}. + */ + PagedIterable list(); + + /** + * List the operations for the provider. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedIterable}. + */ + PagedIterable list(Context context); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/OptimizationLogic.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/OptimizationLogic.java new file mode 100644 index 000000000000..64fb19c3fff2 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/OptimizationLogic.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for OptimizationLogic. + */ +public final class OptimizationLogic extends ExpandableStringEnum { + /** + * Static value MinimizeCost for OptimizationLogic. + */ + public static final OptimizationLogic MINIMIZE_COST = fromString("MinimizeCost"); + + /** + * Static value ModernizeToPaaS for OptimizationLogic. + */ + public static final OptimizationLogic MODERNIZE_TO_PAAS = fromString("ModernizeToPaaS"); + + /** + * Static value ModernizeToAzureSqlMi for OptimizationLogic. + */ + public static final OptimizationLogic MODERNIZE_TO_AZURE_SQL_MI = fromString("ModernizeToAzureSqlMi"); + + /** + * Static value ModernizeToAzureSqlDb for OptimizationLogic. + */ + public static final OptimizationLogic MODERNIZE_TO_AZURE_SQL_DB = fromString("ModernizeToAzureSqlDb"); + + /** + * Creates a new instance of OptimizationLogic value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public OptimizationLogic() { + } + + /** + * Creates or finds a OptimizationLogic from its string representation. + * + * @param name a name to look for. + * @return the corresponding OptimizationLogic. + */ + public static OptimizationLogic fromString(String name) { + return fromString(name, OptimizationLogic.class); + } + + /** + * Gets known OptimizationLogic values. + * + * @return known OptimizationLogic values. + */ + public static Collection values() { + return values(OptimizationLogic.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/Origin.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/Origin.java new file mode 100644 index 000000000000..76fdb0886e94 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/Origin.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value + * is "user,system". + */ +public final class Origin extends ExpandableStringEnum { + /** + * Static value user for Origin. + */ + public static final Origin USER = fromString("user"); + + /** + * Static value system for Origin. + */ + public static final Origin SYSTEM = fromString("system"); + + /** + * Static value user,system for Origin. + */ + public static final Origin USER_SYSTEM = fromString("user,system"); + + /** + * Creates a new instance of Origin value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public Origin() { + } + + /** + * Creates or finds a Origin from its string representation. + * + * @param name a name to look for. + * @return the corresponding Origin. + */ + public static Origin fromString(String name) { + return fromString(name, Origin.class); + } + + /** + * Gets known Origin values. + * + * @return known Origin values. + */ + public static Collection values() { + return values(Origin.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/OsLicense.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/OsLicense.java new file mode 100644 index 000000000000..e2b45e2cb16f --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/OsLicense.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. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for OsLicense. + */ +public final class OsLicense extends ExpandableStringEnum { + /** + * Static value Unknown for OsLicense. + */ + public static final OsLicense UNKNOWN = fromString("Unknown"); + + /** + * Static value Yes for OsLicense. + */ + public static final OsLicense YES = fromString("Yes"); + + /** + * Static value No for OsLicense. + */ + public static final OsLicense NO = fromString("No"); + + /** + * Creates a new instance of OsLicense value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public OsLicense() { + } + + /** + * Creates or finds a OsLicense from its string representation. + * + * @param name a name to look for. + * @return the corresponding OsLicense. + */ + public static OsLicense fromString(String name) { + return fromString(name, OsLicense.class); + } + + /** + * Gets known OsLicense values. + * + * @return known OsLicense values. + */ + public static Collection values() { + return values(OsLicense.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/Percentile.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/Percentile.java new file mode 100644 index 000000000000..90a049f1381c --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/Percentile.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for Percentile. + */ +public final class Percentile extends ExpandableStringEnum { + /** + * Static value Percentile50 for Percentile. + */ + public static final Percentile PERCENTILE50 = fromString("Percentile50"); + + /** + * Static value Percentile90 for Percentile. + */ + public static final Percentile PERCENTILE90 = fromString("Percentile90"); + + /** + * Static value Percentile95 for Percentile. + */ + public static final Percentile PERCENTILE95 = fromString("Percentile95"); + + /** + * Static value Percentile99 for Percentile. + */ + public static final Percentile PERCENTILE99 = fromString("Percentile99"); + + /** + * Creates a new instance of Percentile value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public Percentile() { + } + + /** + * Creates or finds a Percentile from its string representation. + * + * @param name a name to look for. + * @return the corresponding Percentile. + */ + public static Percentile fromString(String name) { + return fromString(name, Percentile.class); + } + + /** + * Gets known Percentile values. + * + * @return known Percentile values. + */ + public static Collection values() { + return values(Percentile.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateEndpoint.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateEndpoint.java new file mode 100644 index 000000000000..fd82d1083c6f --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateEndpoint.java @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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 private endpoint resource. + */ +@Immutable +public final class PrivateEndpoint implements JsonSerializable { + /* + * The ARM identifier for private endpoint. + */ + private String id; + + /** + * Creates an instance of PrivateEndpoint class. + */ + public PrivateEndpoint() { + } + + /** + * Get the id property: The ARM identifier for private endpoint. + * + * @return the id value. + */ + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of PrivateEndpoint from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of PrivateEndpoint 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 PrivateEndpoint. + */ + public static PrivateEndpoint fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + PrivateEndpoint deserializedPrivateEndpoint = new PrivateEndpoint(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedPrivateEndpoint.id = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedPrivateEndpoint; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateEndpointConnection.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateEndpointConnection.java new file mode 100644 index 000000000000..1af539976af0 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateEndpointConnection.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. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.migration.assessment.fluent.models.PrivateEndpointConnectionInner; + +/** + * An immutable client-side representation of PrivateEndpointConnection. + */ +public interface PrivateEndpointConnection { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + PrivateEndpointConnectionProperties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.migration.assessment.fluent.models.PrivateEndpointConnectionInner + * object. + * + * @return the inner object. + */ + PrivateEndpointConnectionInner innerModel(); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateEndpointConnectionListResult.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateEndpointConnectionListResult.java new file mode 100644 index 000000000000..f4b53f865723 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateEndpointConnectionListResult.java @@ -0,0 +1,138 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.fluent.models.PrivateEndpointConnectionInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a PrivateEndpointConnection list operation. + */ +@Fluent +public final class PrivateEndpointConnectionListResult + implements JsonSerializable { + /* + * The PrivateEndpointConnection items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of PrivateEndpointConnectionListResult class. + */ + public PrivateEndpointConnectionListResult() { + } + + /** + * Get the value property: The PrivateEndpointConnection items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Set the value property: The PrivateEndpointConnection items on this page. + * + * @param value the value value to set. + * @return the PrivateEndpointConnectionListResult object itself. + */ + public PrivateEndpointConnectionListResult withValue(List value) { + this.value = value; + return this; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The link to the next page of items. + * + * @param nextLink the nextLink value to set. + * @return the PrivateEndpointConnectionListResult object itself. + */ + public PrivateEndpointConnectionListResult withNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property value in model PrivateEndpointConnectionListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(PrivateEndpointConnectionListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of PrivateEndpointConnectionListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of PrivateEndpointConnectionListResult 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 PrivateEndpointConnectionListResult. + */ + public static PrivateEndpointConnectionListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + PrivateEndpointConnectionListResult deserializedPrivateEndpointConnectionListResult + = new PrivateEndpointConnectionListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> PrivateEndpointConnectionInner.fromJson(reader1)); + deserializedPrivateEndpointConnectionListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedPrivateEndpointConnectionListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedPrivateEndpointConnectionListResult; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateEndpointConnectionOperations.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateEndpointConnectionOperations.java new file mode 100644 index 000000000000..b06928bf5c7b --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateEndpointConnectionOperations.java @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.PrivateEndpointConnectionInner; + +/** + * Resource collection API of PrivateEndpointConnectionOperations. + */ +public interface PrivateEndpointConnectionOperations { + /** + * List PrivateEndpointConnection resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PrivateEndpointConnection list operation as paginated response with + * {@link PagedIterable}. + */ + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName); + + /** + * List PrivateEndpointConnection resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PrivateEndpointConnection list operation as paginated response with + * {@link PagedIterable}. + */ + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context); + + /** + * Get a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a PrivateEndpointConnection along with {@link Response}. + */ + Response getWithResponse(String resourceGroupName, String projectName, + String privateEndpointConnectionName, Context context); + + /** + * Get a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a PrivateEndpointConnection. + */ + PrivateEndpointConnection get(String resourceGroupName, String projectName, String privateEndpointConnectionName); + + /** + * Create a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return private endpoint connection resource. + */ + PrivateEndpointConnection update(String resourceGroupName, String projectName, String privateEndpointConnectionName, + PrivateEndpointConnectionInner resource); + + /** + * Create a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return private endpoint connection resource. + */ + PrivateEndpointConnection update(String resourceGroupName, String projectName, String privateEndpointConnectionName, + PrivateEndpointConnectionInner resource, Context context); + + /** + * Delete a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteWithResponse(String resourceGroupName, String projectName, + String privateEndpointConnectionName, Context context); + + /** + * Delete a PrivateEndpointConnection. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateEndpointConnectionName Private endpoint connection ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void delete(String resourceGroupName, String projectName, String privateEndpointConnectionName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateEndpointConnectionProperties.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateEndpointConnectionProperties.java new file mode 100644 index 000000000000..cf9b6d3b7287 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateEndpointConnectionProperties.java @@ -0,0 +1,176 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +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; + +/** + * Properties of the private endpoint connection. + */ +@Fluent +public final class PrivateEndpointConnectionProperties + implements JsonSerializable { + /* + * The group ids for the private endpoint resource. + */ + private List groupIds; + + /* + * The private endpoint resource. + */ + private PrivateEndpoint privateEndpoint; + + /* + * A collection of information about the state of the connection between service consumer and provider. + */ + private PrivateLinkServiceConnectionState privateLinkServiceConnectionState; + + /* + * The provisioning state of the private endpoint connection resource. + */ + private PrivateEndpointConnectionProvisioningState provisioningState; + + /** + * Creates an instance of PrivateEndpointConnectionProperties class. + */ + public PrivateEndpointConnectionProperties() { + } + + /** + * Get the groupIds property: The group ids for the private endpoint resource. + * + * @return the groupIds value. + */ + public List groupIds() { + return this.groupIds; + } + + /** + * Get the privateEndpoint property: The private endpoint resource. + * + * @return the privateEndpoint value. + */ + public PrivateEndpoint privateEndpoint() { + return this.privateEndpoint; + } + + /** + * Set the privateEndpoint property: The private endpoint resource. + * + * @param privateEndpoint the privateEndpoint value to set. + * @return the PrivateEndpointConnectionProperties object itself. + */ + public PrivateEndpointConnectionProperties withPrivateEndpoint(PrivateEndpoint privateEndpoint) { + this.privateEndpoint = privateEndpoint; + return this; + } + + /** + * Get the privateLinkServiceConnectionState property: A collection of information about the state of the connection + * between service consumer and provider. + * + * @return the privateLinkServiceConnectionState value. + */ + public PrivateLinkServiceConnectionState privateLinkServiceConnectionState() { + return this.privateLinkServiceConnectionState; + } + + /** + * Set the privateLinkServiceConnectionState property: A collection of information about the state of the connection + * between service consumer and provider. + * + * @param privateLinkServiceConnectionState the privateLinkServiceConnectionState value to set. + * @return the PrivateEndpointConnectionProperties object itself. + */ + public PrivateEndpointConnectionProperties + withPrivateLinkServiceConnectionState(PrivateLinkServiceConnectionState privateLinkServiceConnectionState) { + this.privateLinkServiceConnectionState = privateLinkServiceConnectionState; + return this; + } + + /** + * Get the provisioningState property: The provisioning state of the private endpoint connection resource. + * + * @return the provisioningState value. + */ + public PrivateEndpointConnectionProvisioningState provisioningState() { + return this.provisioningState; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (privateEndpoint() != null) { + privateEndpoint().validate(); + } + if (privateLinkServiceConnectionState() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property privateLinkServiceConnectionState in model PrivateEndpointConnectionProperties")); + } else { + privateLinkServiceConnectionState().validate(); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(PrivateEndpointConnectionProperties.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("privateLinkServiceConnectionState", this.privateLinkServiceConnectionState); + jsonWriter.writeJsonField("privateEndpoint", this.privateEndpoint); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of PrivateEndpointConnectionProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of PrivateEndpointConnectionProperties 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 PrivateEndpointConnectionProperties. + */ + public static PrivateEndpointConnectionProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + PrivateEndpointConnectionProperties deserializedPrivateEndpointConnectionProperties + = new PrivateEndpointConnectionProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("privateLinkServiceConnectionState".equals(fieldName)) { + deserializedPrivateEndpointConnectionProperties.privateLinkServiceConnectionState + = PrivateLinkServiceConnectionState.fromJson(reader); + } else if ("groupIds".equals(fieldName)) { + List groupIds = reader.readArray(reader1 -> reader1.getString()); + deserializedPrivateEndpointConnectionProperties.groupIds = groupIds; + } else if ("privateEndpoint".equals(fieldName)) { + deserializedPrivateEndpointConnectionProperties.privateEndpoint = PrivateEndpoint.fromJson(reader); + } else if ("provisioningState".equals(fieldName)) { + deserializedPrivateEndpointConnectionProperties.provisioningState + = PrivateEndpointConnectionProvisioningState.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedPrivateEndpointConnectionProperties; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateEndpointConnectionProvisioningState.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateEndpointConnectionProvisioningState.java new file mode 100644 index 000000000000..a95bc5c8b2e8 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateEndpointConnectionProvisioningState.java @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The current provisioning state. + */ +public final class PrivateEndpointConnectionProvisioningState + extends ExpandableStringEnum { + /** + * Static value Succeeded for PrivateEndpointConnectionProvisioningState. + */ + public static final PrivateEndpointConnectionProvisioningState SUCCEEDED = fromString("Succeeded"); + + /** + * Static value Creating for PrivateEndpointConnectionProvisioningState. + */ + public static final PrivateEndpointConnectionProvisioningState CREATING = fromString("Creating"); + + /** + * Static value Deleting for PrivateEndpointConnectionProvisioningState. + */ + public static final PrivateEndpointConnectionProvisioningState DELETING = fromString("Deleting"); + + /** + * Static value Failed for PrivateEndpointConnectionProvisioningState. + */ + public static final PrivateEndpointConnectionProvisioningState FAILED = fromString("Failed"); + + /** + * Creates a new instance of PrivateEndpointConnectionProvisioningState value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public PrivateEndpointConnectionProvisioningState() { + } + + /** + * Creates or finds a PrivateEndpointConnectionProvisioningState from its string representation. + * + * @param name a name to look for. + * @return the corresponding PrivateEndpointConnectionProvisioningState. + */ + public static PrivateEndpointConnectionProvisioningState fromString(String name) { + return fromString(name, PrivateEndpointConnectionProvisioningState.class); + } + + /** + * Gets known PrivateEndpointConnectionProvisioningState values. + * + * @return known PrivateEndpointConnectionProvisioningState values. + */ + public static Collection values() { + return values(PrivateEndpointConnectionProvisioningState.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateEndpointServiceConnectionStatus.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateEndpointServiceConnectionStatus.java new file mode 100644 index 000000000000..876285b768a1 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateEndpointServiceConnectionStatus.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The private endpoint connection status. + */ +public final class PrivateEndpointServiceConnectionStatus + extends ExpandableStringEnum { + /** + * Static value Pending for PrivateEndpointServiceConnectionStatus. + */ + public static final PrivateEndpointServiceConnectionStatus PENDING = fromString("Pending"); + + /** + * Static value Approved for PrivateEndpointServiceConnectionStatus. + */ + public static final PrivateEndpointServiceConnectionStatus APPROVED = fromString("Approved"); + + /** + * Static value Rejected for PrivateEndpointServiceConnectionStatus. + */ + public static final PrivateEndpointServiceConnectionStatus REJECTED = fromString("Rejected"); + + /** + * Creates a new instance of PrivateEndpointServiceConnectionStatus value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public PrivateEndpointServiceConnectionStatus() { + } + + /** + * Creates or finds a PrivateEndpointServiceConnectionStatus from its string representation. + * + * @param name a name to look for. + * @return the corresponding PrivateEndpointServiceConnectionStatus. + */ + public static PrivateEndpointServiceConnectionStatus fromString(String name) { + return fromString(name, PrivateEndpointServiceConnectionStatus.class); + } + + /** + * Gets known PrivateEndpointServiceConnectionStatus values. + * + * @return known PrivateEndpointServiceConnectionStatus values. + */ + public static Collection values() { + return values(PrivateEndpointServiceConnectionStatus.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateLinkResource.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateLinkResource.java new file mode 100644 index 000000000000..aedf06b3b412 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateLinkResource.java @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.migration.assessment.fluent.models.PrivateLinkResourceInner; + +/** + * An immutable client-side representation of PrivateLinkResource. + */ +public interface PrivateLinkResource { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + PrivateLinkResourceProperties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.migration.assessment.fluent.models.PrivateLinkResourceInner object. + * + * @return the inner object. + */ + PrivateLinkResourceInner innerModel(); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateLinkResourceListResult.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateLinkResourceListResult.java new file mode 100644 index 000000000000..3cf4101936ba --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateLinkResourceListResult.java @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.fluent.models.PrivateLinkResourceInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a PrivateLinkResource list operation. + */ +@Fluent +public final class PrivateLinkResourceListResult implements JsonSerializable { + /* + * The PrivateLinkResource items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of PrivateLinkResourceListResult class. + */ + public PrivateLinkResourceListResult() { + } + + /** + * Get the value property: The PrivateLinkResource items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Set the value property: The PrivateLinkResource items on this page. + * + * @param value the value value to set. + * @return the PrivateLinkResourceListResult object itself. + */ + public PrivateLinkResourceListResult withValue(List value) { + this.value = value; + return this; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The link to the next page of items. + * + * @param nextLink the nextLink value to set. + * @return the PrivateLinkResourceListResult object itself. + */ + public PrivateLinkResourceListResult withNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property value in model PrivateLinkResourceListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(PrivateLinkResourceListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of PrivateLinkResourceListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of PrivateLinkResourceListResult 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 PrivateLinkResourceListResult. + */ + public static PrivateLinkResourceListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + PrivateLinkResourceListResult deserializedPrivateLinkResourceListResult + = new PrivateLinkResourceListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> PrivateLinkResourceInner.fromJson(reader1)); + deserializedPrivateLinkResourceListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedPrivateLinkResourceListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedPrivateLinkResourceListResult; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateLinkResourceOperations.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateLinkResourceOperations.java new file mode 100644 index 000000000000..adee3d9569f2 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateLinkResourceOperations.java @@ -0,0 +1,68 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of PrivateLinkResourceOperations. + */ +public interface PrivateLinkResourceOperations { + /** + * List PrivateLinkResource resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PrivateLinkResource list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName); + + /** + * List PrivateLinkResource resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a PrivateLinkResource list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context); + + /** + * Get a PrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateLinkResourceName Private link resource ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a PrivateLinkResource along with {@link Response}. + */ + Response getWithResponse(String resourceGroupName, String projectName, + String privateLinkResourceName, Context context); + + /** + * Get a PrivateLinkResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param privateLinkResourceName Private link resource ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a PrivateLinkResource. + */ + PrivateLinkResource get(String resourceGroupName, String projectName, String privateLinkResourceName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateLinkResourceProperties.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateLinkResourceProperties.java new file mode 100644 index 000000000000..48186039887e --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateLinkResourceProperties.java @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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.List; + +/** + * Properties of a private link resource. + */ +@Fluent +public final class PrivateLinkResourceProperties implements JsonSerializable { + /* + * The private link resource group id. + */ + private String groupId; + + /* + * The private link resource required member names. + */ + private List requiredMembers; + + /* + * The private link resource private link DNS zone name. + */ + private List requiredZoneNames; + + /** + * Creates an instance of PrivateLinkResourceProperties class. + */ + public PrivateLinkResourceProperties() { + } + + /** + * Get the groupId property: The private link resource group id. + * + * @return the groupId value. + */ + public String groupId() { + return this.groupId; + } + + /** + * Get the requiredMembers property: The private link resource required member names. + * + * @return the requiredMembers value. + */ + public List requiredMembers() { + return this.requiredMembers; + } + + /** + * Get the requiredZoneNames property: The private link resource private link DNS zone name. + * + * @return the requiredZoneNames value. + */ + public List requiredZoneNames() { + return this.requiredZoneNames; + } + + /** + * Set the requiredZoneNames property: The private link resource private link DNS zone name. + * + * @param requiredZoneNames the requiredZoneNames value to set. + * @return the PrivateLinkResourceProperties object itself. + */ + public PrivateLinkResourceProperties withRequiredZoneNames(List requiredZoneNames) { + this.requiredZoneNames = requiredZoneNames; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("requiredZoneNames", this.requiredZoneNames, + (writer, element) -> writer.writeString(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of PrivateLinkResourceProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of PrivateLinkResourceProperties 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 PrivateLinkResourceProperties. + */ + public static PrivateLinkResourceProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + PrivateLinkResourceProperties deserializedPrivateLinkResourceProperties + = new PrivateLinkResourceProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("groupId".equals(fieldName)) { + deserializedPrivateLinkResourceProperties.groupId = reader.getString(); + } else if ("requiredMembers".equals(fieldName)) { + List requiredMembers = reader.readArray(reader1 -> reader1.getString()); + deserializedPrivateLinkResourceProperties.requiredMembers = requiredMembers; + } else if ("requiredZoneNames".equals(fieldName)) { + List requiredZoneNames = reader.readArray(reader1 -> reader1.getString()); + deserializedPrivateLinkResourceProperties.requiredZoneNames = requiredZoneNames; + } else { + reader.skipChildren(); + } + } + + return deserializedPrivateLinkResourceProperties; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateLinkServiceConnectionState.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateLinkServiceConnectionState.java new file mode 100644 index 000000000000..6bd87141580b --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/PrivateLinkServiceConnectionState.java @@ -0,0 +1,155 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * A collection of information about the state of the connection between service consumer and provider. + */ +@Fluent +public final class PrivateLinkServiceConnectionState implements JsonSerializable { + /* + * Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. + */ + private PrivateEndpointServiceConnectionStatus status; + + /* + * The reason for approval/rejection of the connection. + */ + private String description; + + /* + * A message indicating if changes on the service provider require any updates on the consumer. + */ + private String actionsRequired; + + /** + * Creates an instance of PrivateLinkServiceConnectionState class. + */ + public PrivateLinkServiceConnectionState() { + } + + /** + * Get the status property: Indicates whether the connection has been Approved/Rejected/Removed by the owner of the + * service. + * + * @return the status value. + */ + public PrivateEndpointServiceConnectionStatus status() { + return this.status; + } + + /** + * Set the status property: Indicates whether the connection has been Approved/Rejected/Removed by the owner of the + * service. + * + * @param status the status value to set. + * @return the PrivateLinkServiceConnectionState object itself. + */ + public PrivateLinkServiceConnectionState withStatus(PrivateEndpointServiceConnectionStatus status) { + this.status = status; + return this; + } + + /** + * Get the description property: The reason for approval/rejection of the connection. + * + * @return the description value. + */ + public String description() { + return this.description; + } + + /** + * Set the description property: The reason for approval/rejection of the connection. + * + * @param description the description value to set. + * @return the PrivateLinkServiceConnectionState object itself. + */ + public PrivateLinkServiceConnectionState withDescription(String description) { + this.description = description; + return this; + } + + /** + * Get the actionsRequired property: A message indicating if changes on the service provider require any updates on + * the consumer. + * + * @return the actionsRequired value. + */ + public String actionsRequired() { + return this.actionsRequired; + } + + /** + * Set the actionsRequired property: A message indicating if changes on the service provider require any updates on + * the consumer. + * + * @param actionsRequired the actionsRequired value to set. + * @return the PrivateLinkServiceConnectionState object itself. + */ + public PrivateLinkServiceConnectionState withActionsRequired(String actionsRequired) { + this.actionsRequired = actionsRequired; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("status", this.status == null ? null : this.status.toString()); + jsonWriter.writeStringField("description", this.description); + jsonWriter.writeStringField("actionsRequired", this.actionsRequired); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of PrivateLinkServiceConnectionState from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of PrivateLinkServiceConnectionState 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 PrivateLinkServiceConnectionState. + */ + public static PrivateLinkServiceConnectionState fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + PrivateLinkServiceConnectionState deserializedPrivateLinkServiceConnectionState + = new PrivateLinkServiceConnectionState(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("status".equals(fieldName)) { + deserializedPrivateLinkServiceConnectionState.status + = PrivateEndpointServiceConnectionStatus.fromString(reader.getString()); + } else if ("description".equals(fieldName)) { + deserializedPrivateLinkServiceConnectionState.description = reader.getString(); + } else if ("actionsRequired".equals(fieldName)) { + deserializedPrivateLinkServiceConnectionState.actionsRequired = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedPrivateLinkServiceConnectionState; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ProcessorInfo.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ProcessorInfo.java new file mode 100644 index 000000000000..3785663e5cbf --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ProcessorInfo.java @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * Represents a information \ details of a processor. + */ +@Fluent +public final class ProcessorInfo implements JsonSerializable { + /* + * Gets or sets the name \ model of a processor. + */ + private String name; + + /* + * Gets or sets the number of sockets. + */ + private Integer numberOfSockets; + + /* + * Gets or sets the number of cores in a socket. + */ + private Integer numberOfCoresPerSocket; + + /** + * Creates an instance of ProcessorInfo class. + */ + public ProcessorInfo() { + } + + /** + * Get the name property: Gets or sets the name \ model of a processor. + * + * @return the name value. + */ + public String name() { + return this.name; + } + + /** + * Set the name property: Gets or sets the name \ model of a processor. + * + * @param name the name value to set. + * @return the ProcessorInfo object itself. + */ + public ProcessorInfo withName(String name) { + this.name = name; + return this; + } + + /** + * Get the numberOfSockets property: Gets or sets the number of sockets. + * + * @return the numberOfSockets value. + */ + public Integer numberOfSockets() { + return this.numberOfSockets; + } + + /** + * Set the numberOfSockets property: Gets or sets the number of sockets. + * + * @param numberOfSockets the numberOfSockets value to set. + * @return the ProcessorInfo object itself. + */ + public ProcessorInfo withNumberOfSockets(Integer numberOfSockets) { + this.numberOfSockets = numberOfSockets; + return this; + } + + /** + * Get the numberOfCoresPerSocket property: Gets or sets the number of cores in a socket. + * + * @return the numberOfCoresPerSocket value. + */ + public Integer numberOfCoresPerSocket() { + return this.numberOfCoresPerSocket; + } + + /** + * Set the numberOfCoresPerSocket property: Gets or sets the number of cores in a socket. + * + * @param numberOfCoresPerSocket the numberOfCoresPerSocket value to set. + * @return the ProcessorInfo object itself. + */ + public ProcessorInfo withNumberOfCoresPerSocket(Integer numberOfCoresPerSocket) { + this.numberOfCoresPerSocket = numberOfCoresPerSocket; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeNumberField("numberOfSockets", this.numberOfSockets); + jsonWriter.writeNumberField("numberOfCoresPerSocket", this.numberOfCoresPerSocket); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ProcessorInfo from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ProcessorInfo 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 ProcessorInfo. + */ + public static ProcessorInfo fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ProcessorInfo deserializedProcessorInfo = new ProcessorInfo(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("name".equals(fieldName)) { + deserializedProcessorInfo.name = reader.getString(); + } else if ("numberOfSockets".equals(fieldName)) { + deserializedProcessorInfo.numberOfSockets = reader.getNullable(JsonReader::getInt); + } else if ("numberOfCoresPerSocket".equals(fieldName)) { + deserializedProcessorInfo.numberOfCoresPerSocket = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + + return deserializedProcessorInfo; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ProductSupportStatus.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ProductSupportStatus.java new file mode 100644 index 000000000000..1e80df4a92d9 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ProductSupportStatus.java @@ -0,0 +1,251 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; + +/** + * Class to represent the Product Support Status. + */ +@Immutable +public final class ProductSupportStatus implements JsonSerializable { + /* + * Gets or sets current version of ServicePack. + */ + private String currentVersion; + + /* + * Gets or sets ServicePack of the product. + */ + private String servicePackStatus; + + /* + * Gets or sets the Extended Security Update ESU status. + */ + private String esuStatus; + + /* + * Gets or sets the support status of the product. + */ + private String supportStatus; + + /* + * Gets or sets the ETA. + */ + private Integer eta; + + /* + * Gets or sets the current ESU support year. + */ + private String currentEsuYear; + + /* + * Gets or sets the main stream end date of the product. + */ + private OffsetDateTime mainstreamEndDate; + + /* + * Gets or sets the extended support end date of the product. + */ + private OffsetDateTime extendedSupportEndDate; + + /* + * Gets or sets the extended security update year 1 end date of the product. + */ + private OffsetDateTime extendedSecurityUpdateYear1EndDate; + + /* + * Gets or sets the extended security update year 2 end date of the product. + */ + private OffsetDateTime extendedSecurityUpdateYear2EndDate; + + /* + * Gets or sets the extended security update year 3 end date of the product. + */ + private OffsetDateTime extendedSecurityUpdateYear3EndDate; + + /** + * Creates an instance of ProductSupportStatus class. + */ + public ProductSupportStatus() { + } + + /** + * Get the currentVersion property: Gets or sets current version of ServicePack. + * + * @return the currentVersion value. + */ + public String currentVersion() { + return this.currentVersion; + } + + /** + * Get the servicePackStatus property: Gets or sets ServicePack of the product. + * + * @return the servicePackStatus value. + */ + public String servicePackStatus() { + return this.servicePackStatus; + } + + /** + * Get the esuStatus property: Gets or sets the Extended Security Update ESU status. + * + * @return the esuStatus value. + */ + public String esuStatus() { + return this.esuStatus; + } + + /** + * Get the supportStatus property: Gets or sets the support status of the product. + * + * @return the supportStatus value. + */ + public String supportStatus() { + return this.supportStatus; + } + + /** + * Get the eta property: Gets or sets the ETA. + * + * @return the eta value. + */ + public Integer eta() { + return this.eta; + } + + /** + * Get the currentEsuYear property: Gets or sets the current ESU support year. + * + * @return the currentEsuYear value. + */ + public String currentEsuYear() { + return this.currentEsuYear; + } + + /** + * Get the mainstreamEndDate property: Gets or sets the main stream end date of the product. + * + * @return the mainstreamEndDate value. + */ + public OffsetDateTime mainstreamEndDate() { + return this.mainstreamEndDate; + } + + /** + * Get the extendedSupportEndDate property: Gets or sets the extended support end date of the product. + * + * @return the extendedSupportEndDate value. + */ + public OffsetDateTime extendedSupportEndDate() { + return this.extendedSupportEndDate; + } + + /** + * Get the extendedSecurityUpdateYear1EndDate property: Gets or sets the extended security update year 1 end date of + * the product. + * + * @return the extendedSecurityUpdateYear1EndDate value. + */ + public OffsetDateTime extendedSecurityUpdateYear1EndDate() { + return this.extendedSecurityUpdateYear1EndDate; + } + + /** + * Get the extendedSecurityUpdateYear2EndDate property: Gets or sets the extended security update year 2 end date of + * the product. + * + * @return the extendedSecurityUpdateYear2EndDate value. + */ + public OffsetDateTime extendedSecurityUpdateYear2EndDate() { + return this.extendedSecurityUpdateYear2EndDate; + } + + /** + * Get the extendedSecurityUpdateYear3EndDate property: Gets or sets the extended security update year 3 end date of + * the product. + * + * @return the extendedSecurityUpdateYear3EndDate value. + */ + public OffsetDateTime extendedSecurityUpdateYear3EndDate() { + return this.extendedSecurityUpdateYear3EndDate; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ProductSupportStatus from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ProductSupportStatus 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 ProductSupportStatus. + */ + public static ProductSupportStatus fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ProductSupportStatus deserializedProductSupportStatus = new ProductSupportStatus(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("currentVersion".equals(fieldName)) { + deserializedProductSupportStatus.currentVersion = reader.getString(); + } else if ("servicePackStatus".equals(fieldName)) { + deserializedProductSupportStatus.servicePackStatus = reader.getString(); + } else if ("esuStatus".equals(fieldName)) { + deserializedProductSupportStatus.esuStatus = reader.getString(); + } else if ("supportStatus".equals(fieldName)) { + deserializedProductSupportStatus.supportStatus = reader.getString(); + } else if ("eta".equals(fieldName)) { + deserializedProductSupportStatus.eta = reader.getNullable(JsonReader::getInt); + } else if ("currentEsuYear".equals(fieldName)) { + deserializedProductSupportStatus.currentEsuYear = reader.getString(); + } else if ("mainstreamEndDate".equals(fieldName)) { + deserializedProductSupportStatus.mainstreamEndDate = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("extendedSupportEndDate".equals(fieldName)) { + deserializedProductSupportStatus.extendedSupportEndDate = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("extendedSecurityUpdateYear1EndDate".equals(fieldName)) { + deserializedProductSupportStatus.extendedSecurityUpdateYear1EndDate = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("extendedSecurityUpdateYear2EndDate".equals(fieldName)) { + deserializedProductSupportStatus.extendedSecurityUpdateYear2EndDate = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("extendedSecurityUpdateYear3EndDate".equals(fieldName)) { + deserializedProductSupportStatus.extendedSecurityUpdateYear3EndDate = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else { + reader.skipChildren(); + } + } + + return deserializedProductSupportStatus; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ProjectProperties.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ProjectProperties.java new file mode 100644 index 000000000000..2914f1aadee0 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ProjectProperties.java @@ -0,0 +1,338 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.fluent.models.PrivateEndpointConnectionInner; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.util.List; + +/** + * Properties of a project. + */ +@Fluent +public final class ProjectProperties extends AzureResourceProperties { + /* + * Time when this project was created. Date-Time represented in ISO-8601 format. + */ + private OffsetDateTime createdTimestamp; + + /* + * Time when this project was last updated. Date-Time represented in ISO-8601 + * format. + */ + private OffsetDateTime updatedTimestamp; + + /* + * Endpoint at which the collector agent can call agent REST API. + */ + private String serviceEndpoint; + + /* + * Assessment solution ARM id tracked by Microsoft.Migrate/migrateProjects. + */ + private String assessmentSolutionId; + + /* + * Assessment project status. + */ + private ProjectStatus projectStatus; + + /* + * The ARM id of service map workspace created by customer. + */ + private String customerWorkspaceId; + + /* + * Location of service map workspace created by customer. + */ + private String customerWorkspaceLocation; + + /* + * This value can be set to 'enabled' to avoid breaking changes on existing + * customer resources and templates. If set to 'disabled', traffic over public + * interface is not allowed, and private endpoint connections would be the + * exclusive access method. + */ + private String publicNetworkAccess; + + /* + * The list of private endpoint connections to the project. + */ + private List privateEndpointConnections; + + /* + * The ARM id of the storage account used for interactions when public access is + * disabled. + */ + private String customerStorageAccountArmId; + + /** + * Creates an instance of ProjectProperties class. + */ + public ProjectProperties() { + } + + /** + * Get the createdTimestamp property: Time when this project was created. Date-Time represented in ISO-8601 format. + * + * @return the createdTimestamp value. + */ + public OffsetDateTime createdTimestamp() { + return this.createdTimestamp; + } + + /** + * Get the updatedTimestamp property: Time when this project was last updated. Date-Time represented in ISO-8601 + * format. + * + * @return the updatedTimestamp value. + */ + public OffsetDateTime updatedTimestamp() { + return this.updatedTimestamp; + } + + /** + * Get the serviceEndpoint property: Endpoint at which the collector agent can call agent REST API. + * + * @return the serviceEndpoint value. + */ + public String serviceEndpoint() { + return this.serviceEndpoint; + } + + /** + * Get the assessmentSolutionId property: Assessment solution ARM id tracked by Microsoft.Migrate/migrateProjects. + * + * @return the assessmentSolutionId value. + */ + public String assessmentSolutionId() { + return this.assessmentSolutionId; + } + + /** + * Set the assessmentSolutionId property: Assessment solution ARM id tracked by Microsoft.Migrate/migrateProjects. + * + * @param assessmentSolutionId the assessmentSolutionId value to set. + * @return the ProjectProperties object itself. + */ + public ProjectProperties withAssessmentSolutionId(String assessmentSolutionId) { + this.assessmentSolutionId = assessmentSolutionId; + return this; + } + + /** + * Get the projectStatus property: Assessment project status. + * + * @return the projectStatus value. + */ + public ProjectStatus projectStatus() { + return this.projectStatus; + } + + /** + * Set the projectStatus property: Assessment project status. + * + * @param projectStatus the projectStatus value to set. + * @return the ProjectProperties object itself. + */ + public ProjectProperties withProjectStatus(ProjectStatus projectStatus) { + this.projectStatus = projectStatus; + return this; + } + + /** + * Get the customerWorkspaceId property: The ARM id of service map workspace created by customer. + * + * @return the customerWorkspaceId value. + */ + public String customerWorkspaceId() { + return this.customerWorkspaceId; + } + + /** + * Set the customerWorkspaceId property: The ARM id of service map workspace created by customer. + * + * @param customerWorkspaceId the customerWorkspaceId value to set. + * @return the ProjectProperties object itself. + */ + public ProjectProperties withCustomerWorkspaceId(String customerWorkspaceId) { + this.customerWorkspaceId = customerWorkspaceId; + return this; + } + + /** + * Get the customerWorkspaceLocation property: Location of service map workspace created by customer. + * + * @return the customerWorkspaceLocation value. + */ + public String customerWorkspaceLocation() { + return this.customerWorkspaceLocation; + } + + /** + * Set the customerWorkspaceLocation property: Location of service map workspace created by customer. + * + * @param customerWorkspaceLocation the customerWorkspaceLocation value to set. + * @return the ProjectProperties object itself. + */ + public ProjectProperties withCustomerWorkspaceLocation(String customerWorkspaceLocation) { + this.customerWorkspaceLocation = customerWorkspaceLocation; + return this; + } + + /** + * Get the publicNetworkAccess property: This value can be set to 'enabled' to avoid breaking changes on existing + * customer resources and templates. If set to 'disabled', traffic over public + * interface is not allowed, and private endpoint connections would be the + * exclusive access method. + * + * @return the publicNetworkAccess value. + */ + public String publicNetworkAccess() { + return this.publicNetworkAccess; + } + + /** + * Set the publicNetworkAccess property: This value can be set to 'enabled' to avoid breaking changes on existing + * customer resources and templates. If set to 'disabled', traffic over public + * interface is not allowed, and private endpoint connections would be the + * exclusive access method. + * + * @param publicNetworkAccess the publicNetworkAccess value to set. + * @return the ProjectProperties object itself. + */ + public ProjectProperties withPublicNetworkAccess(String publicNetworkAccess) { + this.publicNetworkAccess = publicNetworkAccess; + return this; + } + + /** + * Get the privateEndpointConnections property: The list of private endpoint connections to the project. + * + * @return the privateEndpointConnections value. + */ + public List privateEndpointConnections() { + return this.privateEndpointConnections; + } + + /** + * Get the customerStorageAccountArmId property: The ARM id of the storage account used for interactions when public + * access is + * disabled. + * + * @return the customerStorageAccountArmId value. + */ + public String customerStorageAccountArmId() { + return this.customerStorageAccountArmId; + } + + /** + * Set the customerStorageAccountArmId property: The ARM id of the storage account used for interactions when public + * access is + * disabled. + * + * @param customerStorageAccountArmId the customerStorageAccountArmId value to set. + * @return the ProjectProperties object itself. + */ + public ProjectProperties withCustomerStorageAccountArmId(String customerStorageAccountArmId) { + this.customerStorageAccountArmId = customerStorageAccountArmId; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public ProjectProperties withProvisioningState(ProvisioningState provisioningState) { + super.withProvisioningState(provisioningState); + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + @Override + public void validate() { + if (privateEndpointConnections() != null) { + privateEndpointConnections().forEach(e -> e.validate()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("provisioningState", + provisioningState() == null ? null : provisioningState().toString()); + jsonWriter.writeStringField("assessmentSolutionId", this.assessmentSolutionId); + jsonWriter.writeStringField("projectStatus", this.projectStatus == null ? null : this.projectStatus.toString()); + jsonWriter.writeStringField("customerWorkspaceId", this.customerWorkspaceId); + jsonWriter.writeStringField("customerWorkspaceLocation", this.customerWorkspaceLocation); + jsonWriter.writeStringField("publicNetworkAccess", this.publicNetworkAccess); + jsonWriter.writeStringField("customerStorageAccountArmId", this.customerStorageAccountArmId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ProjectProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ProjectProperties 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 ProjectProperties. + */ + public static ProjectProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ProjectProperties deserializedProjectProperties = new ProjectProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("provisioningState".equals(fieldName)) { + deserializedProjectProperties + .withProvisioningState(ProvisioningState.fromString(reader.getString())); + } else if ("createdTimestamp".equals(fieldName)) { + deserializedProjectProperties.createdTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("updatedTimestamp".equals(fieldName)) { + deserializedProjectProperties.updatedTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("serviceEndpoint".equals(fieldName)) { + deserializedProjectProperties.serviceEndpoint = reader.getString(); + } else if ("assessmentSolutionId".equals(fieldName)) { + deserializedProjectProperties.assessmentSolutionId = reader.getString(); + } else if ("projectStatus".equals(fieldName)) { + deserializedProjectProperties.projectStatus = ProjectStatus.fromString(reader.getString()); + } else if ("customerWorkspaceId".equals(fieldName)) { + deserializedProjectProperties.customerWorkspaceId = reader.getString(); + } else if ("customerWorkspaceLocation".equals(fieldName)) { + deserializedProjectProperties.customerWorkspaceLocation = reader.getString(); + } else if ("publicNetworkAccess".equals(fieldName)) { + deserializedProjectProperties.publicNetworkAccess = reader.getString(); + } else if ("privateEndpointConnections".equals(fieldName)) { + List privateEndpointConnections + = reader.readArray(reader1 -> PrivateEndpointConnectionInner.fromJson(reader1)); + deserializedProjectProperties.privateEndpointConnections = privateEndpointConnections; + } else if ("customerStorageAccountArmId".equals(fieldName)) { + deserializedProjectProperties.customerStorageAccountArmId = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedProjectProperties; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ProjectStatus.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ProjectStatus.java new file mode 100644 index 000000000000..3ca081da7d74 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ProjectStatus.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Project Status. + */ +public final class ProjectStatus extends ExpandableStringEnum { + /** + * Static value Active for ProjectStatus. + */ + public static final ProjectStatus ACTIVE = fromString("Active"); + + /** + * Static value Inactive for ProjectStatus. + */ + public static final ProjectStatus INACTIVE = fromString("Inactive"); + + /** + * Creates a new instance of ProjectStatus value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public ProjectStatus() { + } + + /** + * Creates or finds a ProjectStatus from its string representation. + * + * @param name a name to look for. + * @return the corresponding ProjectStatus. + */ + public static ProjectStatus fromString(String name) { + return fromString(name, ProjectStatus.class); + } + + /** + * Gets known ProjectStatus values. + * + * @return known ProjectStatus values. + */ + public static Collection values() { + return values(ProjectStatus.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ProvisioningState.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ProvisioningState.java new file mode 100644 index 000000000000..2095dc93048c --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ProvisioningState.java @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The status of the current operation. + */ +public final class ProvisioningState extends ExpandableStringEnum { + /** + * Static value Succeeded for ProvisioningState. + */ + public static final ProvisioningState SUCCEEDED = fromString("Succeeded"); + + /** + * Static value Failed for ProvisioningState. + */ + public static final ProvisioningState FAILED = fromString("Failed"); + + /** + * Static value Canceled for ProvisioningState. + */ + public static final ProvisioningState CANCELED = fromString("Canceled"); + + /** + * Static value Provisioning for ProvisioningState. + */ + public static final ProvisioningState PROVISIONING = fromString("Provisioning"); + + /** + * Static value Updating for ProvisioningState. + */ + public static final ProvisioningState UPDATING = fromString("Updating"); + + /** + * Static value Deleting for ProvisioningState. + */ + public static final ProvisioningState DELETING = fromString("Deleting"); + + /** + * Static value Accepted for ProvisioningState. + */ + public static final ProvisioningState ACCEPTED = fromString("Accepted"); + + /** + * Creates a new instance of ProvisioningState value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public ProvisioningState() { + } + + /** + * Creates or finds a ProvisioningState from its string representation. + * + * @param name a name to look for. + * @return the corresponding ProvisioningState. + */ + public static ProvisioningState fromString(String name) { + return fromString(name, ProvisioningState.class); + } + + /** + * Gets known ProvisioningState values. + * + * @return known ProvisioningState values. + */ + public static Collection values() { + return values(ProvisioningState.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/RecommendedSuitability.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/RecommendedSuitability.java new file mode 100644 index 000000000000..7292b910a294 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/RecommendedSuitability.java @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for RecommendedSuitability. + */ +public final class RecommendedSuitability extends ExpandableStringEnum { + /** + * Static value Unknown for RecommendedSuitability. + */ + public static final RecommendedSuitability UNKNOWN = fromString("Unknown"); + + /** + * Static value SuitableForSqlDB for RecommendedSuitability. + */ + public static final RecommendedSuitability SUITABLE_FOR_SQL_DB = fromString("SuitableForSqlDB"); + + /** + * Static value SuitableForSqlMI for RecommendedSuitability. + */ + public static final RecommendedSuitability SUITABLE_FOR_SQL_MI = fromString("SuitableForSqlMI"); + + /** + * Static value SuitableForVM for RecommendedSuitability. + */ + public static final RecommendedSuitability SUITABLE_FOR_VM = fromString("SuitableForVM"); + + /** + * Static value PotentiallySuitableForVM for RecommendedSuitability. + */ + public static final RecommendedSuitability POTENTIALLY_SUITABLE_FOR_VM = fromString("PotentiallySuitableForVM"); + + /** + * Static value ReadinessUnknown for RecommendedSuitability. + */ + public static final RecommendedSuitability READINESS_UNKNOWN = fromString("ReadinessUnknown"); + + /** + * Static value NotSuitable for RecommendedSuitability. + */ + public static final RecommendedSuitability NOT_SUITABLE = fromString("NotSuitable"); + + /** + * Static value SuitableForSqlVM for RecommendedSuitability. + */ + public static final RecommendedSuitability SUITABLE_FOR_SQL_VM = fromString("SuitableForSqlVM"); + + /** + * Static value ConditionallySuitableForSqlDB for RecommendedSuitability. + */ + public static final RecommendedSuitability CONDITIONALLY_SUITABLE_FOR_SQL_DB + = fromString("ConditionallySuitableForSqlDB"); + + /** + * Static value ConditionallySuitableForSqlMI for RecommendedSuitability. + */ + public static final RecommendedSuitability CONDITIONALLY_SUITABLE_FOR_SQL_MI + = fromString("ConditionallySuitableForSqlMI"); + + /** + * Static value ConditionallySuitableForVM for RecommendedSuitability. + */ + public static final RecommendedSuitability CONDITIONALLY_SUITABLE_FOR_VM = fromString("ConditionallySuitableForVM"); + + /** + * Static value ConditionallySuitableForSqlVM for RecommendedSuitability. + */ + public static final RecommendedSuitability CONDITIONALLY_SUITABLE_FOR_SQL_VM + = fromString("ConditionallySuitableForSqlVM"); + + /** + * Creates a new instance of RecommendedSuitability value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public RecommendedSuitability() { + } + + /** + * Creates or finds a RecommendedSuitability from its string representation. + * + * @param name a name to look for. + * @return the corresponding RecommendedSuitability. + */ + public static RecommendedSuitability fromString(String name) { + return fromString(name, RecommendedSuitability.class); + } + + /** + * Gets known RecommendedSuitability values. + * + * @return known RecommendedSuitability values. + */ + public static Collection values() { + return values(RecommendedSuitability.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ServerCollector.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ServerCollector.java new file mode 100644 index 000000000000..63632f7c5c5d --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ServerCollector.java @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.ServerCollectorInner; + +/** + * An immutable client-side representation of ServerCollector. + */ +public interface ServerCollector { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + CollectorPropertiesBaseWithAgent properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.migration.assessment.fluent.models.ServerCollectorInner object. + * + * @return the inner object. + */ + ServerCollectorInner innerModel(); + + /** + * The entirety of the ServerCollector definition. + */ + interface Definition + extends DefinitionStages.Blank, DefinitionStages.WithParentResource, DefinitionStages.WithCreate { + } + + /** + * The ServerCollector definition stages. + */ + interface DefinitionStages { + /** + * The first stage of the ServerCollector definition. + */ + interface Blank extends WithParentResource { + } + + /** + * The stage of the ServerCollector definition allowing to specify parent resource. + */ + interface WithParentResource { + /** + * Specifies resourceGroupName, projectName. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @return the next definition stage. + */ + WithCreate withExistingAssessmentProject(String resourceGroupName, String projectName); + } + + /** + * The stage of the ServerCollector definition which contains all the minimum required properties for the + * resource to be created, but also allows for any other optional properties to be specified. + */ + interface WithCreate extends DefinitionStages.WithProperties { + /** + * Executes the create request. + * + * @return the created resource. + */ + ServerCollector create(); + + /** + * Executes the create request. + * + * @param context The context to associate with this operation. + * @return the created resource. + */ + ServerCollector create(Context context); + } + + /** + * The stage of the ServerCollector definition allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The resource-specific properties for this resource.. + * + * @param properties The resource-specific properties for this resource. + * @return the next definition stage. + */ + WithCreate withProperties(CollectorPropertiesBaseWithAgent properties); + } + } + + /** + * Refreshes the resource to sync with Azure. + * + * @return the refreshed resource. + */ + ServerCollector refresh(); + + /** + * Refreshes the resource to sync with Azure. + * + * @param context The context to associate with this operation. + * @return the refreshed resource. + */ + ServerCollector refresh(Context context); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ServerCollectorListResult.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ServerCollectorListResult.java new file mode 100644 index 000000000000..d4f252fb8edf --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ServerCollectorListResult.java @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.fluent.models.ServerCollectorInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a ServerCollector list operation. + */ +@Fluent +public final class ServerCollectorListResult implements JsonSerializable { + /* + * The ServerCollector items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of ServerCollectorListResult class. + */ + public ServerCollectorListResult() { + } + + /** + * Get the value property: The ServerCollector items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Set the value property: The ServerCollector items on this page. + * + * @param value the value value to set. + * @return the ServerCollectorListResult object itself. + */ + public ServerCollectorListResult withValue(List value) { + this.value = value; + return this; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The link to the next page of items. + * + * @param nextLink the nextLink value to set. + * @return the ServerCollectorListResult object itself. + */ + public ServerCollectorListResult withNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log( + new IllegalArgumentException("Missing required property value in model ServerCollectorListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(ServerCollectorListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ServerCollectorListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ServerCollectorListResult 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 ServerCollectorListResult. + */ + public static ServerCollectorListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ServerCollectorListResult deserializedServerCollectorListResult = new ServerCollectorListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> ServerCollectorInner.fromJson(reader1)); + deserializedServerCollectorListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedServerCollectorListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedServerCollectorListResult; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ServerCollectorsOperations.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ServerCollectorsOperations.java new file mode 100644 index 000000000000..2ab5fa88ed9d --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/ServerCollectorsOperations.java @@ -0,0 +1,148 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of ServerCollectorsOperations. + */ +public interface ServerCollectorsOperations { + /** + * List ServerCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ServerCollector list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName); + + /** + * List ServerCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a ServerCollector list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context); + + /** + * Get a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ServerCollector along with {@link Response}. + */ + Response getWithResponse(String resourceGroupName, String projectName, String serverCollectorName, + Context context); + + /** + * Get a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ServerCollector. + */ + ServerCollector get(String resourceGroupName, String projectName, String serverCollectorName); + + /** + * Delete a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteWithResponse(String resourceGroupName, String projectName, String serverCollectorName, + Context context); + + /** + * Delete a ServerCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param serverCollectorName Physical server collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void delete(String resourceGroupName, String projectName, String serverCollectorName); + + /** + * Get a ServerCollector. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ServerCollector along with {@link Response}. + */ + ServerCollector getById(String id); + + /** + * Get a ServerCollector. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a ServerCollector along with {@link Response}. + */ + Response getByIdWithResponse(String id, Context context); + + /** + * Delete a ServerCollector. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteById(String id); + + /** + * Delete a ServerCollector. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteByIdWithResponse(String id, Context context); + + /** + * Begins definition for a new ServerCollector resource. + * + * @param name resource name. + * @return the first stage of the new ServerCollector definition. + */ + ServerCollector.DefinitionStages.Blank define(String name); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SharedResourcesDto.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SharedResourcesDto.java new file mode 100644 index 000000000000..9e0948cf6143 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SharedResourcesDto.java @@ -0,0 +1,164 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; +import java.util.List; + +/** + * Shared Resources. + */ +@Immutable +public final class SharedResourcesDto implements JsonSerializable { + /* + * Gets the list of shared data disks. + */ + private List sharedDataDisks; + + /* + * Gets the list of shared log disks. + */ + private List sharedLogDisks; + + /* + * Gets the list of shared Temporary database disks. + */ + private List sharedTempDbDisks; + + /* + * Gets number of mounts of shared disks. + */ + private Integer numberOfMounts; + + /* + * Gets quorum witness. + */ + private AzureQuorumWitnessDto quorumWitness; + + /** + * Creates an instance of SharedResourcesDto class. + */ + public SharedResourcesDto() { + } + + /** + * Get the sharedDataDisks property: Gets the list of shared data disks. + * + * @return the sharedDataDisks value. + */ + public List sharedDataDisks() { + return this.sharedDataDisks; + } + + /** + * Get the sharedLogDisks property: Gets the list of shared log disks. + * + * @return the sharedLogDisks value. + */ + public List sharedLogDisks() { + return this.sharedLogDisks; + } + + /** + * Get the sharedTempDbDisks property: Gets the list of shared Temporary database disks. + * + * @return the sharedTempDbDisks value. + */ + public List sharedTempDbDisks() { + return this.sharedTempDbDisks; + } + + /** + * Get the numberOfMounts property: Gets number of mounts of shared disks. + * + * @return the numberOfMounts value. + */ + public Integer numberOfMounts() { + return this.numberOfMounts; + } + + /** + * Get the quorumWitness property: Gets quorum witness. + * + * @return the quorumWitness value. + */ + public AzureQuorumWitnessDto quorumWitness() { + return this.quorumWitness; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (sharedDataDisks() != null) { + sharedDataDisks().forEach(e -> e.validate()); + } + if (sharedLogDisks() != null) { + sharedLogDisks().forEach(e -> e.validate()); + } + if (sharedTempDbDisks() != null) { + sharedTempDbDisks().forEach(e -> e.validate()); + } + if (quorumWitness() != null) { + quorumWitness().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SharedResourcesDto from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SharedResourcesDto 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 SharedResourcesDto. + */ + public static SharedResourcesDto fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SharedResourcesDto deserializedSharedResourcesDto = new SharedResourcesDto(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("sharedDataDisks".equals(fieldName)) { + List sharedDataDisks + = reader.readArray(reader1 -> AzureManagedDiskSkuDto.fromJson(reader1)); + deserializedSharedResourcesDto.sharedDataDisks = sharedDataDisks; + } else if ("sharedLogDisks".equals(fieldName)) { + List sharedLogDisks + = reader.readArray(reader1 -> AzureManagedDiskSkuDto.fromJson(reader1)); + deserializedSharedResourcesDto.sharedLogDisks = sharedLogDisks; + } else if ("sharedTempDbDisks".equals(fieldName)) { + List sharedTempDbDisks + = reader.readArray(reader1 -> AzureManagedDiskSkuDto.fromJson(reader1)); + deserializedSharedResourcesDto.sharedTempDbDisks = sharedTempDbDisks; + } else if ("numberOfMounts".equals(fieldName)) { + deserializedSharedResourcesDto.numberOfMounts = reader.getNullable(JsonReader::getInt); + } else if ("quorumWitness".equals(fieldName)) { + deserializedSharedResourcesDto.quorumWitness = AzureQuorumWitnessDto.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedSharedResourcesDto; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SkuReplicationMode.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SkuReplicationMode.java new file mode 100644 index 000000000000..b88a07962eb8 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SkuReplicationMode.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. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for SkuReplicationMode. + */ +public final class SkuReplicationMode extends ExpandableStringEnum { + /** + * Static value NotApplicable for SkuReplicationMode. + */ + public static final SkuReplicationMode NOT_APPLICABLE = fromString("NotApplicable"); + + /** + * Static value ActiveGeoReplication for SkuReplicationMode. + */ + public static final SkuReplicationMode ACTIVE_GEO_REPLICATION = fromString("ActiveGeoReplication"); + + /** + * Static value FailoverGroupInstance for SkuReplicationMode. + */ + public static final SkuReplicationMode FAILOVER_GROUP_INSTANCE = fromString("FailoverGroupInstance"); + + /** + * Creates a new instance of SkuReplicationMode value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public SkuReplicationMode() { + } + + /** + * Creates or finds a SkuReplicationMode from its string representation. + * + * @param name a name to look for. + * @return the corresponding SkuReplicationMode. + */ + public static SkuReplicationMode fromString(String name) { + return fromString(name, SkuReplicationMode.class); + } + + /** + * Gets known SkuReplicationMode values. + * + * @return known SkuReplicationMode values. + */ + public static Collection values() { + return values(SkuReplicationMode.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessedNetworkAdapter.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessedNetworkAdapter.java new file mode 100644 index 000000000000..91c090ff3c94 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessedNetworkAdapter.java @@ -0,0 +1,372 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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.List; + +/** + * SQL Assessed Network Adapter. + */ +@Fluent +public final class SqlAssessedNetworkAdapter implements JsonSerializable { + /* + * Gets the suitability. + */ + private CloudSuitability suitability; + + /* + * Gets the suitability detail. + */ + private AzureNetworkAdapterSuitabilityDetail suitabilityDetail; + + /* + * Gets the suitability explanation. + */ + private AzureNetworkAdapterSuitabilityExplanation suitabilityExplanation; + + /* + * Gets the monthly bandwidth costs. + */ + private Float monthlyBandwidthCosts; + + /* + * Gets the net gigabytes transmitted per month. + */ + private Float netGigabytesTransmittedPerMonth; + + /* + * Gets the name. + */ + private String name; + + /* + * Gets the display name. + */ + private String displayName; + + /* + * Gets the mac address. + */ + private String macAddress; + + /* + * Gets the ip addresses. + */ + private List ipAddresses; + + /* + * Gets the megabytes per second received. + */ + private Float megabytesPerSecondReceived; + + /* + * Gets the megabytes per second transmitted. + */ + private Float megabytesPerSecondTransmitted; + + /** + * Creates an instance of SqlAssessedNetworkAdapter class. + */ + public SqlAssessedNetworkAdapter() { + } + + /** + * Get the suitability property: Gets the suitability. + * + * @return the suitability value. + */ + public CloudSuitability suitability() { + return this.suitability; + } + + /** + * Set the suitability property: Gets the suitability. + * + * @param suitability the suitability value to set. + * @return the SqlAssessedNetworkAdapter object itself. + */ + public SqlAssessedNetworkAdapter withSuitability(CloudSuitability suitability) { + this.suitability = suitability; + return this; + } + + /** + * Get the suitabilityDetail property: Gets the suitability detail. + * + * @return the suitabilityDetail value. + */ + public AzureNetworkAdapterSuitabilityDetail suitabilityDetail() { + return this.suitabilityDetail; + } + + /** + * Set the suitabilityDetail property: Gets the suitability detail. + * + * @param suitabilityDetail the suitabilityDetail value to set. + * @return the SqlAssessedNetworkAdapter object itself. + */ + public SqlAssessedNetworkAdapter withSuitabilityDetail(AzureNetworkAdapterSuitabilityDetail suitabilityDetail) { + this.suitabilityDetail = suitabilityDetail; + return this; + } + + /** + * Get the suitabilityExplanation property: Gets the suitability explanation. + * + * @return the suitabilityExplanation value. + */ + public AzureNetworkAdapterSuitabilityExplanation suitabilityExplanation() { + return this.suitabilityExplanation; + } + + /** + * Set the suitabilityExplanation property: Gets the suitability explanation. + * + * @param suitabilityExplanation the suitabilityExplanation value to set. + * @return the SqlAssessedNetworkAdapter object itself. + */ + public SqlAssessedNetworkAdapter + withSuitabilityExplanation(AzureNetworkAdapterSuitabilityExplanation suitabilityExplanation) { + this.suitabilityExplanation = suitabilityExplanation; + return this; + } + + /** + * Get the monthlyBandwidthCosts property: Gets the monthly bandwidth costs. + * + * @return the monthlyBandwidthCosts value. + */ + public Float monthlyBandwidthCosts() { + return this.monthlyBandwidthCosts; + } + + /** + * Set the monthlyBandwidthCosts property: Gets the monthly bandwidth costs. + * + * @param monthlyBandwidthCosts the monthlyBandwidthCosts value to set. + * @return the SqlAssessedNetworkAdapter object itself. + */ + public SqlAssessedNetworkAdapter withMonthlyBandwidthCosts(Float monthlyBandwidthCosts) { + this.monthlyBandwidthCosts = monthlyBandwidthCosts; + return this; + } + + /** + * Get the netGigabytesTransmittedPerMonth property: Gets the net gigabytes transmitted per month. + * + * @return the netGigabytesTransmittedPerMonth value. + */ + public Float netGigabytesTransmittedPerMonth() { + return this.netGigabytesTransmittedPerMonth; + } + + /** + * Set the netGigabytesTransmittedPerMonth property: Gets the net gigabytes transmitted per month. + * + * @param netGigabytesTransmittedPerMonth the netGigabytesTransmittedPerMonth value to set. + * @return the SqlAssessedNetworkAdapter object itself. + */ + public SqlAssessedNetworkAdapter withNetGigabytesTransmittedPerMonth(Float netGigabytesTransmittedPerMonth) { + this.netGigabytesTransmittedPerMonth = netGigabytesTransmittedPerMonth; + return this; + } + + /** + * Get the name property: Gets the name. + * + * @return the name value. + */ + public String name() { + return this.name; + } + + /** + * Set the name property: Gets the name. + * + * @param name the name value to set. + * @return the SqlAssessedNetworkAdapter object itself. + */ + public SqlAssessedNetworkAdapter withName(String name) { + this.name = name; + return this; + } + + /** + * Get the displayName property: Gets the display name. + * + * @return the displayName value. + */ + public String displayName() { + return this.displayName; + } + + /** + * Set the displayName property: Gets the display name. + * + * @param displayName the displayName value to set. + * @return the SqlAssessedNetworkAdapter object itself. + */ + public SqlAssessedNetworkAdapter withDisplayName(String displayName) { + this.displayName = displayName; + return this; + } + + /** + * Get the macAddress property: Gets the mac address. + * + * @return the macAddress value. + */ + public String macAddress() { + return this.macAddress; + } + + /** + * Set the macAddress property: Gets the mac address. + * + * @param macAddress the macAddress value to set. + * @return the SqlAssessedNetworkAdapter object itself. + */ + public SqlAssessedNetworkAdapter withMacAddress(String macAddress) { + this.macAddress = macAddress; + return this; + } + + /** + * Get the ipAddresses property: Gets the ip addresses. + * + * @return the ipAddresses value. + */ + public List ipAddresses() { + return this.ipAddresses; + } + + /** + * Get the megabytesPerSecondReceived property: Gets the megabytes per second received. + * + * @return the megabytesPerSecondReceived value. + */ + public Float megabytesPerSecondReceived() { + return this.megabytesPerSecondReceived; + } + + /** + * Set the megabytesPerSecondReceived property: Gets the megabytes per second received. + * + * @param megabytesPerSecondReceived the megabytesPerSecondReceived value to set. + * @return the SqlAssessedNetworkAdapter object itself. + */ + public SqlAssessedNetworkAdapter withMegabytesPerSecondReceived(Float megabytesPerSecondReceived) { + this.megabytesPerSecondReceived = megabytesPerSecondReceived; + return this; + } + + /** + * Get the megabytesPerSecondTransmitted property: Gets the megabytes per second transmitted. + * + * @return the megabytesPerSecondTransmitted value. + */ + public Float megabytesPerSecondTransmitted() { + return this.megabytesPerSecondTransmitted; + } + + /** + * Set the megabytesPerSecondTransmitted property: Gets the megabytes per second transmitted. + * + * @param megabytesPerSecondTransmitted the megabytesPerSecondTransmitted value to set. + * @return the SqlAssessedNetworkAdapter object itself. + */ + public SqlAssessedNetworkAdapter withMegabytesPerSecondTransmitted(Float megabytesPerSecondTransmitted) { + this.megabytesPerSecondTransmitted = megabytesPerSecondTransmitted; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("suitability", this.suitability == null ? null : this.suitability.toString()); + jsonWriter.writeStringField("suitabilityDetail", + this.suitabilityDetail == null ? null : this.suitabilityDetail.toString()); + jsonWriter.writeStringField("suitabilityExplanation", + this.suitabilityExplanation == null ? null : this.suitabilityExplanation.toString()); + jsonWriter.writeNumberField("monthlyBandwidthCosts", this.monthlyBandwidthCosts); + jsonWriter.writeNumberField("netGigabytesTransmittedPerMonth", this.netGigabytesTransmittedPerMonth); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("displayName", this.displayName); + jsonWriter.writeStringField("macAddress", this.macAddress); + jsonWriter.writeNumberField("megabytesPerSecondReceived", this.megabytesPerSecondReceived); + jsonWriter.writeNumberField("megabytesPerSecondTransmitted", this.megabytesPerSecondTransmitted); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlAssessedNetworkAdapter from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlAssessedNetworkAdapter 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 SqlAssessedNetworkAdapter. + */ + public static SqlAssessedNetworkAdapter fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlAssessedNetworkAdapter deserializedSqlAssessedNetworkAdapter = new SqlAssessedNetworkAdapter(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("suitability".equals(fieldName)) { + deserializedSqlAssessedNetworkAdapter.suitability = CloudSuitability.fromString(reader.getString()); + } else if ("suitabilityDetail".equals(fieldName)) { + deserializedSqlAssessedNetworkAdapter.suitabilityDetail + = AzureNetworkAdapterSuitabilityDetail.fromString(reader.getString()); + } else if ("suitabilityExplanation".equals(fieldName)) { + deserializedSqlAssessedNetworkAdapter.suitabilityExplanation + = AzureNetworkAdapterSuitabilityExplanation.fromString(reader.getString()); + } else if ("monthlyBandwidthCosts".equals(fieldName)) { + deserializedSqlAssessedNetworkAdapter.monthlyBandwidthCosts + = reader.getNullable(JsonReader::getFloat); + } else if ("netGigabytesTransmittedPerMonth".equals(fieldName)) { + deserializedSqlAssessedNetworkAdapter.netGigabytesTransmittedPerMonth + = reader.getNullable(JsonReader::getFloat); + } else if ("name".equals(fieldName)) { + deserializedSqlAssessedNetworkAdapter.name = reader.getString(); + } else if ("displayName".equals(fieldName)) { + deserializedSqlAssessedNetworkAdapter.displayName = reader.getString(); + } else if ("macAddress".equals(fieldName)) { + deserializedSqlAssessedNetworkAdapter.macAddress = reader.getString(); + } else if ("ipAddresses".equals(fieldName)) { + List ipAddresses = reader.readArray(reader1 -> reader1.getString()); + deserializedSqlAssessedNetworkAdapter.ipAddresses = ipAddresses; + } else if ("megabytesPerSecondReceived".equals(fieldName)) { + deserializedSqlAssessedNetworkAdapter.megabytesPerSecondReceived + = reader.getNullable(JsonReader::getFloat); + } else if ("megabytesPerSecondTransmitted".equals(fieldName)) { + deserializedSqlAssessedNetworkAdapter.megabytesPerSecondTransmitted + = reader.getNullable(JsonReader::getFloat); + } else { + reader.skipChildren(); + } + } + + return deserializedSqlAssessedNetworkAdapter; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentMigrationIssue.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentMigrationIssue.java new file mode 100644 index 000000000000..223689a8287c --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentMigrationIssue.java @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; +import java.util.List; + +/** + * Class representing the SQL migration issues. + */ +@Immutable +public final class SqlAssessmentMigrationIssue implements JsonSerializable { + /* + * Gets the issue id. + */ + private String issueId; + + /* + * Gets the issue category. + */ + private SqlAssessmentMigrationIssueCategory issueCategory; + + /* + * Gets the list of impacted objects. + */ + private List impactedObjects; + + /** + * Creates an instance of SqlAssessmentMigrationIssue class. + */ + public SqlAssessmentMigrationIssue() { + } + + /** + * Get the issueId property: Gets the issue id. + * + * @return the issueId value. + */ + public String issueId() { + return this.issueId; + } + + /** + * Get the issueCategory property: Gets the issue category. + * + * @return the issueCategory value. + */ + public SqlAssessmentMigrationIssueCategory issueCategory() { + return this.issueCategory; + } + + /** + * Get the impactedObjects property: Gets the list of impacted objects. + * + * @return the impactedObjects value. + */ + public List impactedObjects() { + return this.impactedObjects; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (impactedObjects() != null) { + impactedObjects().forEach(e -> e.validate()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlAssessmentMigrationIssue from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlAssessmentMigrationIssue 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 SqlAssessmentMigrationIssue. + */ + public static SqlAssessmentMigrationIssue fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlAssessmentMigrationIssue deserializedSqlAssessmentMigrationIssue = new SqlAssessmentMigrationIssue(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("issueId".equals(fieldName)) { + deserializedSqlAssessmentMigrationIssue.issueId = reader.getString(); + } else if ("issueCategory".equals(fieldName)) { + deserializedSqlAssessmentMigrationIssue.issueCategory + = SqlAssessmentMigrationIssueCategory.fromString(reader.getString()); + } else if ("impactedObjects".equals(fieldName)) { + List impactedObjects + = reader.readArray(reader1 -> ImpactedAssessmentObject.fromJson(reader1)); + deserializedSqlAssessmentMigrationIssue.impactedObjects = impactedObjects; + } else { + reader.skipChildren(); + } + } + + return deserializedSqlAssessmentMigrationIssue; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentMigrationIssueCategory.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentMigrationIssueCategory.java new file mode 100644 index 000000000000..3bf4079b0039 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentMigrationIssueCategory.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for SqlAssessmentMigrationIssueCategory. + */ +public final class SqlAssessmentMigrationIssueCategory + extends ExpandableStringEnum { + /** + * Static value Issue for SqlAssessmentMigrationIssueCategory. + */ + public static final SqlAssessmentMigrationIssueCategory ISSUE = fromString("Issue"); + + /** + * Static value Warning for SqlAssessmentMigrationIssueCategory. + */ + public static final SqlAssessmentMigrationIssueCategory WARNING = fromString("Warning"); + + /** + * Static value Internal for SqlAssessmentMigrationIssueCategory. + */ + public static final SqlAssessmentMigrationIssueCategory INTERNAL = fromString("Internal"); + + /** + * Creates a new instance of SqlAssessmentMigrationIssueCategory value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public SqlAssessmentMigrationIssueCategory() { + } + + /** + * Creates or finds a SqlAssessmentMigrationIssueCategory from its string representation. + * + * @param name a name to look for. + * @return the corresponding SqlAssessmentMigrationIssueCategory. + */ + public static SqlAssessmentMigrationIssueCategory fromString(String name) { + return fromString(name, SqlAssessmentMigrationIssueCategory.class); + } + + /** + * Gets known SqlAssessmentMigrationIssueCategory values. + * + * @return known SqlAssessmentMigrationIssueCategory values. + */ + public static Collection values() { + return values(SqlAssessmentMigrationIssueCategory.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentOptions.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentOptions.java new file mode 100644 index 000000000000..5a18b1eab84c --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentOptions.java @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlAssessmentOptionsInner; + +/** + * An immutable client-side representation of SqlAssessmentOptions. + */ +public interface SqlAssessmentOptions { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + SqlAssessmentOptionsProperties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.migration.assessment.fluent.models.SqlAssessmentOptionsInner object. + * + * @return the inner object. + */ + SqlAssessmentOptionsInner innerModel(); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentOptionsListResult.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentOptionsListResult.java new file mode 100644 index 000000000000..6ef8f88b32e1 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentOptionsListResult.java @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlAssessmentOptionsInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a SqlAssessmentOptions list operation. + */ +@Fluent +public final class SqlAssessmentOptionsListResult implements JsonSerializable { + /* + * The SqlAssessmentOptions items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of SqlAssessmentOptionsListResult class. + */ + public SqlAssessmentOptionsListResult() { + } + + /** + * Get the value property: The SqlAssessmentOptions items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Set the value property: The SqlAssessmentOptions items on this page. + * + * @param value the value value to set. + * @return the SqlAssessmentOptionsListResult object itself. + */ + public SqlAssessmentOptionsListResult withValue(List value) { + this.value = value; + return this; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The link to the next page of items. + * + * @param nextLink the nextLink value to set. + * @return the SqlAssessmentOptionsListResult object itself. + */ + public SqlAssessmentOptionsListResult withNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property value in model SqlAssessmentOptionsListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(SqlAssessmentOptionsListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlAssessmentOptionsListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlAssessmentOptionsListResult 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 SqlAssessmentOptionsListResult. + */ + public static SqlAssessmentOptionsListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlAssessmentOptionsListResult deserializedSqlAssessmentOptionsListResult + = new SqlAssessmentOptionsListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> SqlAssessmentOptionsInner.fromJson(reader1)); + deserializedSqlAssessmentOptionsListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedSqlAssessmentOptionsListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedSqlAssessmentOptionsListResult; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentOptionsOperations.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentOptionsOperations.java new file mode 100644 index 000000000000..f4ef05007e92 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentOptionsOperations.java @@ -0,0 +1,68 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of SqlAssessmentOptionsOperations. + */ +public interface SqlAssessmentOptionsOperations { + /** + * List SqlAssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentOptions list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName); + + /** + * List SqlAssessmentOptions resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentOptions list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context); + + /** + * Get a SqlAssessmentOptions. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param assessmentOptionsName Sql assessment options ARM name. Accepted values is 'default'. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlAssessmentOptions along with {@link Response}. + */ + Response getWithResponse(String resourceGroupName, String projectName, + String assessmentOptionsName, Context context); + + /** + * Get a SqlAssessmentOptions. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param assessmentOptionsName Sql assessment options ARM name. Accepted values is 'default'. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlAssessmentOptions. + */ + SqlAssessmentOptions get(String resourceGroupName, String projectName, String assessmentOptionsName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentOptionsProperties.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentOptionsProperties.java new file mode 100644 index 000000000000..ae29471bafc0 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentOptionsProperties.java @@ -0,0 +1,492 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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.List; + +/** + * SQL Assessment options properties Web model object. + */ +@Fluent +public final class SqlAssessmentOptionsProperties implements JsonSerializable { + /* + * Gets the list of VM families. + */ + private List vmFamilies; + + /* + * Gets the Reserved Instance VM Families list. + */ + private List reservedInstanceVmFamilies; + + /* + * Gets the Premium disk VM Families list. + */ + private List premiumDiskVmFamilies; + + /* + * Gets or sets the Premium disk VM Families list. + */ + private List savingsPlanVmFamilies; + + /* + * Gets or sets the list of Azure locations supporting Saving Plans for IAAS. + */ + private List savingsPlanSupportedLocations; + + /* + * Gets or sets the list of Azure locations supporting Saving Plans for PAAS. + */ + private List savingsPlanSupportedLocationsForPaas; + + /* + * Gets or sets the list of Azure locations supporting Reserved Instances for IAAS. + */ + private List reservedInstanceSupportedLocationsForIaas; + + /* + * Gets or sets the list of Azure Offers supporting Saving Plans. + */ + private List savingsPlanSupportedOffers; + + /* + * Gets or sets the list of SQL target SKU properties for dropdowns. + */ + private List sqlSkus; + + /* + * Gets or sets the Reserved Instance SQL target types. + */ + private List reservedInstanceSqlTargets; + + /* + * Gets or sets the list of Azure locations supporting Reserved Instances. + */ + private List reservedInstanceSupportedLocations; + + /* + * Gets or sets the list of currencies supported for Reserved Instances. + */ + private List reservedInstanceSupportedCurrencies; + + /* + * Gets or sets the list of offers supported for Reserved Instances. + */ + private List reservedInstanceSupportedOffers; + + /* + * Gets or sets the list of offers supported for SQL assessments. + */ + private List supportedOffers; + + /** + * Creates an instance of SqlAssessmentOptionsProperties class. + */ + public SqlAssessmentOptionsProperties() { + } + + /** + * Get the vmFamilies property: Gets the list of VM families. + * + * @return the vmFamilies value. + */ + public List vmFamilies() { + return this.vmFamilies; + } + + /** + * Get the reservedInstanceVmFamilies property: Gets the Reserved Instance VM Families list. + * + * @return the reservedInstanceVmFamilies value. + */ + public List reservedInstanceVmFamilies() { + return this.reservedInstanceVmFamilies; + } + + /** + * Get the premiumDiskVmFamilies property: Gets the Premium disk VM Families list. + * + * @return the premiumDiskVmFamilies value. + */ + public List premiumDiskVmFamilies() { + return this.premiumDiskVmFamilies; + } + + /** + * Get the savingsPlanVmFamilies property: Gets or sets the Premium disk VM Families list. + * + * @return the savingsPlanVmFamilies value. + */ + public List savingsPlanVmFamilies() { + return this.savingsPlanVmFamilies; + } + + /** + * Set the savingsPlanVmFamilies property: Gets or sets the Premium disk VM Families list. + * + * @param savingsPlanVmFamilies the savingsPlanVmFamilies value to set. + * @return the SqlAssessmentOptionsProperties object itself. + */ + public SqlAssessmentOptionsProperties withSavingsPlanVmFamilies(List savingsPlanVmFamilies) { + this.savingsPlanVmFamilies = savingsPlanVmFamilies; + return this; + } + + /** + * Get the savingsPlanSupportedLocations property: Gets or sets the list of Azure locations supporting Saving Plans + * for IAAS. + * + * @return the savingsPlanSupportedLocations value. + */ + public List savingsPlanSupportedLocations() { + return this.savingsPlanSupportedLocations; + } + + /** + * Set the savingsPlanSupportedLocations property: Gets or sets the list of Azure locations supporting Saving Plans + * for IAAS. + * + * @param savingsPlanSupportedLocations the savingsPlanSupportedLocations value to set. + * @return the SqlAssessmentOptionsProperties object itself. + */ + public SqlAssessmentOptionsProperties + withSavingsPlanSupportedLocations(List savingsPlanSupportedLocations) { + this.savingsPlanSupportedLocations = savingsPlanSupportedLocations; + return this; + } + + /** + * Get the savingsPlanSupportedLocationsForPaas property: Gets or sets the list of Azure locations supporting Saving + * Plans for PAAS. + * + * @return the savingsPlanSupportedLocationsForPaas value. + */ + public List savingsPlanSupportedLocationsForPaas() { + return this.savingsPlanSupportedLocationsForPaas; + } + + /** + * Set the savingsPlanSupportedLocationsForPaas property: Gets or sets the list of Azure locations supporting Saving + * Plans for PAAS. + * + * @param savingsPlanSupportedLocationsForPaas the savingsPlanSupportedLocationsForPaas value to set. + * @return the SqlAssessmentOptionsProperties object itself. + */ + public SqlAssessmentOptionsProperties + withSavingsPlanSupportedLocationsForPaas(List savingsPlanSupportedLocationsForPaas) { + this.savingsPlanSupportedLocationsForPaas = savingsPlanSupportedLocationsForPaas; + return this; + } + + /** + * Get the reservedInstanceSupportedLocationsForIaas property: Gets or sets the list of Azure locations supporting + * Reserved Instances for IAAS. + * + * @return the reservedInstanceSupportedLocationsForIaas value. + */ + public List reservedInstanceSupportedLocationsForIaas() { + return this.reservedInstanceSupportedLocationsForIaas; + } + + /** + * Set the reservedInstanceSupportedLocationsForIaas property: Gets or sets the list of Azure locations supporting + * Reserved Instances for IAAS. + * + * @param reservedInstanceSupportedLocationsForIaas the reservedInstanceSupportedLocationsForIaas value to set. + * @return the SqlAssessmentOptionsProperties object itself. + */ + public SqlAssessmentOptionsProperties + withReservedInstanceSupportedLocationsForIaas(List reservedInstanceSupportedLocationsForIaas) { + this.reservedInstanceSupportedLocationsForIaas = reservedInstanceSupportedLocationsForIaas; + return this; + } + + /** + * Get the savingsPlanSupportedOffers property: Gets or sets the list of Azure Offers supporting Saving Plans. + * + * @return the savingsPlanSupportedOffers value. + */ + public List savingsPlanSupportedOffers() { + return this.savingsPlanSupportedOffers; + } + + /** + * Set the savingsPlanSupportedOffers property: Gets or sets the list of Azure Offers supporting Saving Plans. + * + * @param savingsPlanSupportedOffers the savingsPlanSupportedOffers value to set. + * @return the SqlAssessmentOptionsProperties object itself. + */ + public SqlAssessmentOptionsProperties + withSavingsPlanSupportedOffers(List savingsPlanSupportedOffers) { + this.savingsPlanSupportedOffers = savingsPlanSupportedOffers; + return this; + } + + /** + * Get the sqlSkus property: Gets or sets the list of SQL target SKU properties for dropdowns. + * + * @return the sqlSkus value. + */ + public List sqlSkus() { + return this.sqlSkus; + } + + /** + * Set the sqlSkus property: Gets or sets the list of SQL target SKU properties for dropdowns. + * + * @param sqlSkus the sqlSkus value to set. + * @return the SqlAssessmentOptionsProperties object itself. + */ + public SqlAssessmentOptionsProperties withSqlSkus(List sqlSkus) { + this.sqlSkus = sqlSkus; + return this; + } + + /** + * Get the reservedInstanceSqlTargets property: Gets or sets the Reserved Instance SQL target types. + * + * @return the reservedInstanceSqlTargets value. + */ + public List reservedInstanceSqlTargets() { + return this.reservedInstanceSqlTargets; + } + + /** + * Set the reservedInstanceSqlTargets property: Gets or sets the Reserved Instance SQL target types. + * + * @param reservedInstanceSqlTargets the reservedInstanceSqlTargets value to set. + * @return the SqlAssessmentOptionsProperties object itself. + */ + public SqlAssessmentOptionsProperties withReservedInstanceSqlTargets(List reservedInstanceSqlTargets) { + this.reservedInstanceSqlTargets = reservedInstanceSqlTargets; + return this; + } + + /** + * Get the reservedInstanceSupportedLocations property: Gets or sets the list of Azure locations supporting Reserved + * Instances. + * + * @return the reservedInstanceSupportedLocations value. + */ + public List reservedInstanceSupportedLocations() { + return this.reservedInstanceSupportedLocations; + } + + /** + * Set the reservedInstanceSupportedLocations property: Gets or sets the list of Azure locations supporting Reserved + * Instances. + * + * @param reservedInstanceSupportedLocations the reservedInstanceSupportedLocations value to set. + * @return the SqlAssessmentOptionsProperties object itself. + */ + public SqlAssessmentOptionsProperties + withReservedInstanceSupportedLocations(List reservedInstanceSupportedLocations) { + this.reservedInstanceSupportedLocations = reservedInstanceSupportedLocations; + return this; + } + + /** + * Get the reservedInstanceSupportedCurrencies property: Gets or sets the list of currencies supported for Reserved + * Instances. + * + * @return the reservedInstanceSupportedCurrencies value. + */ + public List reservedInstanceSupportedCurrencies() { + return this.reservedInstanceSupportedCurrencies; + } + + /** + * Set the reservedInstanceSupportedCurrencies property: Gets or sets the list of currencies supported for Reserved + * Instances. + * + * @param reservedInstanceSupportedCurrencies the reservedInstanceSupportedCurrencies value to set. + * @return the SqlAssessmentOptionsProperties object itself. + */ + public SqlAssessmentOptionsProperties + withReservedInstanceSupportedCurrencies(List reservedInstanceSupportedCurrencies) { + this.reservedInstanceSupportedCurrencies = reservedInstanceSupportedCurrencies; + return this; + } + + /** + * Get the reservedInstanceSupportedOffers property: Gets or sets the list of offers supported for Reserved + * Instances. + * + * @return the reservedInstanceSupportedOffers value. + */ + public List reservedInstanceSupportedOffers() { + return this.reservedInstanceSupportedOffers; + } + + /** + * Set the reservedInstanceSupportedOffers property: Gets or sets the list of offers supported for Reserved + * Instances. + * + * @param reservedInstanceSupportedOffers the reservedInstanceSupportedOffers value to set. + * @return the SqlAssessmentOptionsProperties object itself. + */ + public SqlAssessmentOptionsProperties + withReservedInstanceSupportedOffers(List reservedInstanceSupportedOffers) { + this.reservedInstanceSupportedOffers = reservedInstanceSupportedOffers; + return this; + } + + /** + * Get the supportedOffers property: Gets or sets the list of offers supported for SQL assessments. + * + * @return the supportedOffers value. + */ + public List supportedOffers() { + return this.supportedOffers; + } + + /** + * Set the supportedOffers property: Gets or sets the list of offers supported for SQL assessments. + * + * @param supportedOffers the supportedOffers value to set. + * @return the SqlAssessmentOptionsProperties object itself. + */ + public SqlAssessmentOptionsProperties withSupportedOffers(List supportedOffers) { + this.supportedOffers = supportedOffers; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (vmFamilies() != null) { + vmFamilies().forEach(e -> e.validate()); + } + if (sqlSkus() != null) { + sqlSkus().forEach(e -> e.validate()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("savingsPlanVmFamilies", this.savingsPlanVmFamilies, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); + jsonWriter.writeArrayField("savingsPlanSupportedLocations", this.savingsPlanSupportedLocations, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); + jsonWriter.writeArrayField("savingsPlanSupportedLocationsForPaas", this.savingsPlanSupportedLocationsForPaas, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); + jsonWriter.writeArrayField("reservedInstanceSupportedLocationsForIaas", + this.reservedInstanceSupportedLocationsForIaas, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); + jsonWriter.writeArrayField("savingsPlanSupportedOffers", this.savingsPlanSupportedOffers, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); + jsonWriter.writeArrayField("sqlSkus", this.sqlSkus, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeArrayField("reservedInstanceSqlTargets", this.reservedInstanceSqlTargets, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); + jsonWriter.writeArrayField("reservedInstanceSupportedLocations", this.reservedInstanceSupportedLocations, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); + jsonWriter.writeArrayField("reservedInstanceSupportedCurrencies", this.reservedInstanceSupportedCurrencies, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); + jsonWriter.writeArrayField("reservedInstanceSupportedOffers", this.reservedInstanceSupportedOffers, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); + jsonWriter.writeArrayField("supportedOffers", this.supportedOffers, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlAssessmentOptionsProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlAssessmentOptionsProperties 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 SqlAssessmentOptionsProperties. + */ + public static SqlAssessmentOptionsProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlAssessmentOptionsProperties deserializedSqlAssessmentOptionsProperties + = new SqlAssessmentOptionsProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("vmFamilies".equals(fieldName)) { + List vmFamilies = reader.readArray(reader1 -> VmFamilyOptions.fromJson(reader1)); + deserializedSqlAssessmentOptionsProperties.vmFamilies = vmFamilies; + } else if ("reservedInstanceVmFamilies".equals(fieldName)) { + List reservedInstanceVmFamilies + = reader.readArray(reader1 -> AzureVmFamily.fromString(reader1.getString())); + deserializedSqlAssessmentOptionsProperties.reservedInstanceVmFamilies = reservedInstanceVmFamilies; + } else if ("premiumDiskVmFamilies".equals(fieldName)) { + List premiumDiskVmFamilies + = reader.readArray(reader1 -> AzureVmFamily.fromString(reader1.getString())); + deserializedSqlAssessmentOptionsProperties.premiumDiskVmFamilies = premiumDiskVmFamilies; + } else if ("savingsPlanVmFamilies".equals(fieldName)) { + List savingsPlanVmFamilies + = reader.readArray(reader1 -> AzureVmFamily.fromString(reader1.getString())); + deserializedSqlAssessmentOptionsProperties.savingsPlanVmFamilies = savingsPlanVmFamilies; + } else if ("savingsPlanSupportedLocations".equals(fieldName)) { + List savingsPlanSupportedLocations + = reader.readArray(reader1 -> AzureLocation.fromString(reader1.getString())); + deserializedSqlAssessmentOptionsProperties.savingsPlanSupportedLocations + = savingsPlanSupportedLocations; + } else if ("savingsPlanSupportedLocationsForPaas".equals(fieldName)) { + List savingsPlanSupportedLocationsForPaas + = reader.readArray(reader1 -> AzureLocation.fromString(reader1.getString())); + deserializedSqlAssessmentOptionsProperties.savingsPlanSupportedLocationsForPaas + = savingsPlanSupportedLocationsForPaas; + } else if ("reservedInstanceSupportedLocationsForIaas".equals(fieldName)) { + List reservedInstanceSupportedLocationsForIaas + = reader.readArray(reader1 -> AzureLocation.fromString(reader1.getString())); + deserializedSqlAssessmentOptionsProperties.reservedInstanceSupportedLocationsForIaas + = reservedInstanceSupportedLocationsForIaas; + } else if ("savingsPlanSupportedOffers".equals(fieldName)) { + List savingsPlanSupportedOffers + = reader.readArray(reader1 -> AzureOfferCode.fromString(reader1.getString())); + deserializedSqlAssessmentOptionsProperties.savingsPlanSupportedOffers = savingsPlanSupportedOffers; + } else if ("sqlSkus".equals(fieldName)) { + List sqlSkus + = reader.readArray(reader1 -> SqlPaaSTargetOptions.fromJson(reader1)); + deserializedSqlAssessmentOptionsProperties.sqlSkus = sqlSkus; + } else if ("reservedInstanceSqlTargets".equals(fieldName)) { + List reservedInstanceSqlTargets + = reader.readArray(reader1 -> TargetType.fromString(reader1.getString())); + deserializedSqlAssessmentOptionsProperties.reservedInstanceSqlTargets = reservedInstanceSqlTargets; + } else if ("reservedInstanceSupportedLocations".equals(fieldName)) { + List reservedInstanceSupportedLocations + = reader.readArray(reader1 -> AzureLocation.fromString(reader1.getString())); + deserializedSqlAssessmentOptionsProperties.reservedInstanceSupportedLocations + = reservedInstanceSupportedLocations; + } else if ("reservedInstanceSupportedCurrencies".equals(fieldName)) { + List reservedInstanceSupportedCurrencies + = reader.readArray(reader1 -> AzureCurrency.fromString(reader1.getString())); + deserializedSqlAssessmentOptionsProperties.reservedInstanceSupportedCurrencies + = reservedInstanceSupportedCurrencies; + } else if ("reservedInstanceSupportedOffers".equals(fieldName)) { + List reservedInstanceSupportedOffers + = reader.readArray(reader1 -> AzureOfferCode.fromString(reader1.getString())); + deserializedSqlAssessmentOptionsProperties.reservedInstanceSupportedOffers + = reservedInstanceSupportedOffers; + } else if ("supportedOffers".equals(fieldName)) { + List supportedOffers + = reader.readArray(reader1 -> AzureOfferCode.fromString(reader1.getString())); + deserializedSqlAssessmentOptionsProperties.supportedOffers = supportedOffers; + } else { + reader.skipChildren(); + } + } + + return deserializedSqlAssessmentOptionsProperties; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2.java new file mode 100644 index 000000000000..bf21ac020ef7 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2.java @@ -0,0 +1,165 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlAssessmentV2Inner; + +/** + * An immutable client-side representation of SqlAssessmentV2. + */ +public interface SqlAssessmentV2 { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + SqlAssessmentV2Properties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.migration.assessment.fluent.models.SqlAssessmentV2Inner object. + * + * @return the inner object. + */ + SqlAssessmentV2Inner innerModel(); + + /** + * The entirety of the SqlAssessmentV2 definition. + */ + interface Definition + extends DefinitionStages.Blank, DefinitionStages.WithParentResource, DefinitionStages.WithCreate { + } + + /** + * The SqlAssessmentV2 definition stages. + */ + interface DefinitionStages { + /** + * The first stage of the SqlAssessmentV2 definition. + */ + interface Blank extends WithParentResource { + } + + /** + * The stage of the SqlAssessmentV2 definition allowing to specify parent resource. + */ + interface WithParentResource { + /** + * Specifies resourceGroupName, projectName, groupName. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @return the next definition stage. + */ + WithCreate withExistingGroup(String resourceGroupName, String projectName, String groupName); + } + + /** + * The stage of the SqlAssessmentV2 definition which contains all the minimum required properties for the + * resource to be created, but also allows for any other optional properties to be specified. + */ + interface WithCreate extends DefinitionStages.WithProperties { + /** + * Executes the create request. + * + * @return the created resource. + */ + SqlAssessmentV2 create(); + + /** + * Executes the create request. + * + * @param context The context to associate with this operation. + * @return the created resource. + */ + SqlAssessmentV2 create(Context context); + } + + /** + * The stage of the SqlAssessmentV2 definition allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The resource-specific properties for this resource.. + * + * @param properties The resource-specific properties for this resource. + * @return the next definition stage. + */ + WithCreate withProperties(SqlAssessmentV2Properties properties); + } + } + + /** + * Refreshes the resource to sync with Azure. + * + * @return the refreshed resource. + */ + SqlAssessmentV2 refresh(); + + /** + * Refreshes the resource to sync with Azure. + * + * @param context The context to associate with this operation. + * @return the refreshed resource. + */ + SqlAssessmentV2 refresh(Context context); + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format. + */ + DownloadUrl downloadUrl(Object body); + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format. + */ + DownloadUrl downloadUrl(Object body, Context context); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2IaasSuitabilityData.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2IaasSuitabilityData.java new file mode 100644 index 000000000000..a98bd91184f9 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2IaasSuitabilityData.java @@ -0,0 +1,342 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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.List; + +/** + * Class representing Azure SQL IAAS suitability details. + */ +@Fluent +public final class SqlAssessmentV2IaasSuitabilityData implements JsonSerializable { + /* + * Gets the azure SQL IAAS SKU. + */ + private AzureSqlIaasSkuDto azureSqlSku; + + /* + * Gets the replica azure SQL IAAS SKU. + */ + private List replicaAzureSqlSku; + + /* + * Gets the shared resources. + */ + private SharedResourcesDto sharedResources; + + /* + * Gets the monthly compute cost. + */ + private Float monthlyComputeCost; + + /* + * Gets the monthly storage cost. + */ + private Float monthlyStorageCost; + + /* + * Gets the collection of cost components. + */ + private List costComponents; + + /* + * Gets the suitability for Microsoft cloud defender. + */ + private CloudSuitability securitySuitability; + + /* + * Gets a value indicating whether replicas should be provisioned. + */ + private Boolean shouldProvisionReplicas; + + /* + * Gets the replication mode. + */ + private SkuReplicationMode skuReplicationMode; + + /* + * Gets the list of migration guidelines applicable to this target. + */ + private List migrationGuidelines; + + /* + * Gets the list of SQL recommendation Reasoning. + */ + private List recommendationReasonings; + + /* + * Gets the migration target platform. + */ + private TargetType migrationTargetPlatform; + + /* + * Gets the azure suitability. + */ + private CloudSuitability suitability; + + /* + * Gets the list of migrations issues. + */ + private List migrationIssues; + + /** + * Creates an instance of SqlAssessmentV2IaasSuitabilityData class. + */ + public SqlAssessmentV2IaasSuitabilityData() { + } + + /** + * Get the azureSqlSku property: Gets the azure SQL IAAS SKU. + * + * @return the azureSqlSku value. + */ + public AzureSqlIaasSkuDto azureSqlSku() { + return this.azureSqlSku; + } + + /** + * Get the replicaAzureSqlSku property: Gets the replica azure SQL IAAS SKU. + * + * @return the replicaAzureSqlSku value. + */ + public List replicaAzureSqlSku() { + return this.replicaAzureSqlSku; + } + + /** + * Get the sharedResources property: Gets the shared resources. + * + * @return the sharedResources value. + */ + public SharedResourcesDto sharedResources() { + return this.sharedResources; + } + + /** + * Get the monthlyComputeCost property: Gets the monthly compute cost. + * + * @return the monthlyComputeCost value. + */ + public Float monthlyComputeCost() { + return this.monthlyComputeCost; + } + + /** + * Get the monthlyStorageCost property: Gets the monthly storage cost. + * + * @return the monthlyStorageCost value. + */ + public Float monthlyStorageCost() { + return this.monthlyStorageCost; + } + + /** + * Get the costComponents property: Gets the collection of cost components. + * + * @return the costComponents value. + */ + public List costComponents() { + return this.costComponents; + } + + /** + * Set the costComponents property: Gets the collection of cost components. + * + * @param costComponents the costComponents value to set. + * @return the SqlAssessmentV2IaasSuitabilityData object itself. + */ + public SqlAssessmentV2IaasSuitabilityData withCostComponents(List costComponents) { + this.costComponents = costComponents; + return this; + } + + /** + * Get the securitySuitability property: Gets the suitability for Microsoft cloud defender. + * + * @return the securitySuitability value. + */ + public CloudSuitability securitySuitability() { + return this.securitySuitability; + } + + /** + * Get the shouldProvisionReplicas property: Gets a value indicating whether replicas should be provisioned. + * + * @return the shouldProvisionReplicas value. + */ + public Boolean shouldProvisionReplicas() { + return this.shouldProvisionReplicas; + } + + /** + * Get the skuReplicationMode property: Gets the replication mode. + * + * @return the skuReplicationMode value. + */ + public SkuReplicationMode skuReplicationMode() { + return this.skuReplicationMode; + } + + /** + * Get the migrationGuidelines property: Gets the list of migration guidelines applicable to this target. + * + * @return the migrationGuidelines value. + */ + public List migrationGuidelines() { + return this.migrationGuidelines; + } + + /** + * Get the recommendationReasonings property: Gets the list of SQL recommendation Reasoning. + * + * @return the recommendationReasonings value. + */ + public List recommendationReasonings() { + return this.recommendationReasonings; + } + + /** + * Get the migrationTargetPlatform property: Gets the migration target platform. + * + * @return the migrationTargetPlatform value. + */ + public TargetType migrationTargetPlatform() { + return this.migrationTargetPlatform; + } + + /** + * Get the suitability property: Gets the azure suitability. + * + * @return the suitability value. + */ + public CloudSuitability suitability() { + return this.suitability; + } + + /** + * Get the migrationIssues property: Gets the list of migrations issues. + * + * @return the migrationIssues value. + */ + public List migrationIssues() { + return this.migrationIssues; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (azureSqlSku() != null) { + azureSqlSku().validate(); + } + if (replicaAzureSqlSku() != null) { + replicaAzureSqlSku().forEach(e -> e.validate()); + } + if (sharedResources() != null) { + sharedResources().validate(); + } + if (costComponents() != null) { + costComponents().forEach(e -> e.validate()); + } + if (migrationGuidelines() != null) { + migrationGuidelines().forEach(e -> e.validate()); + } + if (recommendationReasonings() != null) { + recommendationReasonings().forEach(e -> e.validate()); + } + if (migrationIssues() != null) { + migrationIssues().forEach(e -> e.validate()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("costComponents", this.costComponents, + (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlAssessmentV2IaasSuitabilityData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlAssessmentV2IaasSuitabilityData 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 SqlAssessmentV2IaasSuitabilityData. + */ + public static SqlAssessmentV2IaasSuitabilityData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlAssessmentV2IaasSuitabilityData deserializedSqlAssessmentV2IaasSuitabilityData + = new SqlAssessmentV2IaasSuitabilityData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("azureSqlSku".equals(fieldName)) { + deserializedSqlAssessmentV2IaasSuitabilityData.azureSqlSku = AzureSqlIaasSkuDto.fromJson(reader); + } else if ("replicaAzureSqlSku".equals(fieldName)) { + List replicaAzureSqlSku + = reader.readArray(reader1 -> AzureSqlIaasSkuDto.fromJson(reader1)); + deserializedSqlAssessmentV2IaasSuitabilityData.replicaAzureSqlSku = replicaAzureSqlSku; + } else if ("sharedResources".equals(fieldName)) { + deserializedSqlAssessmentV2IaasSuitabilityData.sharedResources + = SharedResourcesDto.fromJson(reader); + } else if ("monthlyComputeCost".equals(fieldName)) { + deserializedSqlAssessmentV2IaasSuitabilityData.monthlyComputeCost + = reader.getNullable(JsonReader::getFloat); + } else if ("monthlyStorageCost".equals(fieldName)) { + deserializedSqlAssessmentV2IaasSuitabilityData.monthlyStorageCost + = reader.getNullable(JsonReader::getFloat); + } else if ("costComponents".equals(fieldName)) { + List costComponents = reader.readArray(reader1 -> CostComponent.fromJson(reader1)); + deserializedSqlAssessmentV2IaasSuitabilityData.costComponents = costComponents; + } else if ("securitySuitability".equals(fieldName)) { + deserializedSqlAssessmentV2IaasSuitabilityData.securitySuitability + = CloudSuitability.fromString(reader.getString()); + } else if ("shouldProvisionReplicas".equals(fieldName)) { + deserializedSqlAssessmentV2IaasSuitabilityData.shouldProvisionReplicas + = reader.getNullable(JsonReader::getBoolean); + } else if ("skuReplicationMode".equals(fieldName)) { + deserializedSqlAssessmentV2IaasSuitabilityData.skuReplicationMode + = SkuReplicationMode.fromString(reader.getString()); + } else if ("migrationGuidelines".equals(fieldName)) { + List migrationGuidelines + = reader.readArray(reader1 -> SqlMigrationGuideline.fromJson(reader1)); + deserializedSqlAssessmentV2IaasSuitabilityData.migrationGuidelines = migrationGuidelines; + } else if ("recommendationReasonings".equals(fieldName)) { + List recommendationReasonings + = reader.readArray(reader1 -> SqlRecommendationReasoning.fromJson(reader1)); + deserializedSqlAssessmentV2IaasSuitabilityData.recommendationReasonings = recommendationReasonings; + } else if ("migrationTargetPlatform".equals(fieldName)) { + deserializedSqlAssessmentV2IaasSuitabilityData.migrationTargetPlatform + = TargetType.fromString(reader.getString()); + } else if ("suitability".equals(fieldName)) { + deserializedSqlAssessmentV2IaasSuitabilityData.suitability + = CloudSuitability.fromString(reader.getString()); + } else if ("migrationIssues".equals(fieldName)) { + List migrationIssues + = reader.readArray(reader1 -> SqlAssessmentMigrationIssue.fromJson(reader1)); + deserializedSqlAssessmentV2IaasSuitabilityData.migrationIssues = migrationIssues; + } else { + reader.skipChildren(); + } + } + + return deserializedSqlAssessmentV2IaasSuitabilityData; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2ListResult.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2ListResult.java new file mode 100644 index 000000000000..13ed56d5ae1c --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2ListResult.java @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlAssessmentV2Inner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a SqlAssessmentV2 list operation. + */ +@Fluent +public final class SqlAssessmentV2ListResult implements JsonSerializable { + /* + * The SqlAssessmentV2 items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of SqlAssessmentV2ListResult class. + */ + public SqlAssessmentV2ListResult() { + } + + /** + * Get the value property: The SqlAssessmentV2 items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Set the value property: The SqlAssessmentV2 items on this page. + * + * @param value the value value to set. + * @return the SqlAssessmentV2ListResult object itself. + */ + public SqlAssessmentV2ListResult withValue(List value) { + this.value = value; + return this; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The link to the next page of items. + * + * @param nextLink the nextLink value to set. + * @return the SqlAssessmentV2ListResult object itself. + */ + public SqlAssessmentV2ListResult withNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log( + new IllegalArgumentException("Missing required property value in model SqlAssessmentV2ListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(SqlAssessmentV2ListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlAssessmentV2ListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlAssessmentV2ListResult 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 SqlAssessmentV2ListResult. + */ + public static SqlAssessmentV2ListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlAssessmentV2ListResult deserializedSqlAssessmentV2ListResult = new SqlAssessmentV2ListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> SqlAssessmentV2Inner.fromJson(reader1)); + deserializedSqlAssessmentV2ListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedSqlAssessmentV2ListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedSqlAssessmentV2ListResult; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2Operations.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2Operations.java new file mode 100644 index 000000000000..1ee0d9e46378 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2Operations.java @@ -0,0 +1,191 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of SqlAssessmentV2Operations. + */ +public interface SqlAssessmentV2Operations { + /** + * List SqlAssessmentV2 resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentV2 list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByGroup(String resourceGroupName, String projectName, String groupName); + + /** + * List SqlAssessmentV2 resources by Group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentV2 list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByGroup(String resourceGroupName, String projectName, String groupName, + Context context); + + /** + * Get a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlAssessmentV2 along with {@link Response}. + */ + Response getWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, Context context); + + /** + * Get a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlAssessmentV2. + */ + SqlAssessmentV2 get(String resourceGroupName, String projectName, String groupName, String assessmentName); + + /** + * Delete a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, Context context); + + /** + * Delete a SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void delete(String resourceGroupName, String projectName, String groupName, String assessmentName); + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param body The content of the action request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format. + */ + DownloadUrl downloadUrl(String resourceGroupName, String projectName, String groupName, String assessmentName, + Object body); + + /** + * Get download URL for the assessment report. + * + * Get the URL for downloading the assessment in a report format. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param body The content of the action request. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the URL for downloading the assessment in a report format. + */ + DownloadUrl downloadUrl(String resourceGroupName, String projectName, String groupName, String assessmentName, + Object body, Context context); + + /** + * Get a SqlAssessmentV2. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlAssessmentV2 along with {@link Response}. + */ + SqlAssessmentV2 getById(String id); + + /** + * Get a SqlAssessmentV2. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlAssessmentV2 along with {@link Response}. + */ + Response getByIdWithResponse(String id, Context context); + + /** + * Delete a SqlAssessmentV2. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteById(String id); + + /** + * Delete a SqlAssessmentV2. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteByIdWithResponse(String id, Context context); + + /** + * Begins definition for a new SqlAssessmentV2 resource. + * + * @param name resource name. + * @return the first stage of the new SqlAssessmentV2 definition. + */ + SqlAssessmentV2.DefinitionStages.Blank define(String name); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2PaasSuitabilityData.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2PaasSuitabilityData.java new file mode 100644 index 000000000000..25867747057a --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2PaasSuitabilityData.java @@ -0,0 +1,342 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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.List; + +/** + * Class representing Azure SQL PAAS suitability details. + */ +@Fluent +public final class SqlAssessmentV2PaasSuitabilityData implements JsonSerializable { + /* + * Gets the azure SQL PAAS SKU. + */ + private AzureSqlPaasSkuDto azureSqlSku; + + /* + * Gets the replica azure SQL PAAS SKU. + */ + private List replicaAzureSqlSku; + + /* + * Gets the shared resources. + */ + private SharedResourcesDto sharedResources; + + /* + * Gets the monthly compute cost. + */ + private Float monthlyComputeCost; + + /* + * Gets the monthly storage cost. + */ + private Float monthlyStorageCost; + + /* + * Gets the collection of cost components. + */ + private List costComponents; + + /* + * Gets the suitability for Microsoft cloud defender. + */ + private CloudSuitability securitySuitability; + + /* + * Gets a value indicating whether replicas should be provisioned. + */ + private Boolean shouldProvisionReplicas; + + /* + * Gets the replication mode. + */ + private SkuReplicationMode skuReplicationMode; + + /* + * Gets the list of migration guidelines applicable to this target. + */ + private List migrationGuidelines; + + /* + * Gets the list of SQL recommendation Reasoning. + */ + private List recommendationReasonings; + + /* + * Gets the migration target platform. + */ + private TargetType migrationTargetPlatform; + + /* + * Gets the azure suitability. + */ + private CloudSuitability suitability; + + /* + * Gets the list of migrations issues. + */ + private List migrationIssues; + + /** + * Creates an instance of SqlAssessmentV2PaasSuitabilityData class. + */ + public SqlAssessmentV2PaasSuitabilityData() { + } + + /** + * Get the azureSqlSku property: Gets the azure SQL PAAS SKU. + * + * @return the azureSqlSku value. + */ + public AzureSqlPaasSkuDto azureSqlSku() { + return this.azureSqlSku; + } + + /** + * Get the replicaAzureSqlSku property: Gets the replica azure SQL PAAS SKU. + * + * @return the replicaAzureSqlSku value. + */ + public List replicaAzureSqlSku() { + return this.replicaAzureSqlSku; + } + + /** + * Get the sharedResources property: Gets the shared resources. + * + * @return the sharedResources value. + */ + public SharedResourcesDto sharedResources() { + return this.sharedResources; + } + + /** + * Get the monthlyComputeCost property: Gets the monthly compute cost. + * + * @return the monthlyComputeCost value. + */ + public Float monthlyComputeCost() { + return this.monthlyComputeCost; + } + + /** + * Get the monthlyStorageCost property: Gets the monthly storage cost. + * + * @return the monthlyStorageCost value. + */ + public Float monthlyStorageCost() { + return this.monthlyStorageCost; + } + + /** + * Get the costComponents property: Gets the collection of cost components. + * + * @return the costComponents value. + */ + public List costComponents() { + return this.costComponents; + } + + /** + * Set the costComponents property: Gets the collection of cost components. + * + * @param costComponents the costComponents value to set. + * @return the SqlAssessmentV2PaasSuitabilityData object itself. + */ + public SqlAssessmentV2PaasSuitabilityData withCostComponents(List costComponents) { + this.costComponents = costComponents; + return this; + } + + /** + * Get the securitySuitability property: Gets the suitability for Microsoft cloud defender. + * + * @return the securitySuitability value. + */ + public CloudSuitability securitySuitability() { + return this.securitySuitability; + } + + /** + * Get the shouldProvisionReplicas property: Gets a value indicating whether replicas should be provisioned. + * + * @return the shouldProvisionReplicas value. + */ + public Boolean shouldProvisionReplicas() { + return this.shouldProvisionReplicas; + } + + /** + * Get the skuReplicationMode property: Gets the replication mode. + * + * @return the skuReplicationMode value. + */ + public SkuReplicationMode skuReplicationMode() { + return this.skuReplicationMode; + } + + /** + * Get the migrationGuidelines property: Gets the list of migration guidelines applicable to this target. + * + * @return the migrationGuidelines value. + */ + public List migrationGuidelines() { + return this.migrationGuidelines; + } + + /** + * Get the recommendationReasonings property: Gets the list of SQL recommendation Reasoning. + * + * @return the recommendationReasonings value. + */ + public List recommendationReasonings() { + return this.recommendationReasonings; + } + + /** + * Get the migrationTargetPlatform property: Gets the migration target platform. + * + * @return the migrationTargetPlatform value. + */ + public TargetType migrationTargetPlatform() { + return this.migrationTargetPlatform; + } + + /** + * Get the suitability property: Gets the azure suitability. + * + * @return the suitability value. + */ + public CloudSuitability suitability() { + return this.suitability; + } + + /** + * Get the migrationIssues property: Gets the list of migrations issues. + * + * @return the migrationIssues value. + */ + public List migrationIssues() { + return this.migrationIssues; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (azureSqlSku() != null) { + azureSqlSku().validate(); + } + if (replicaAzureSqlSku() != null) { + replicaAzureSqlSku().forEach(e -> e.validate()); + } + if (sharedResources() != null) { + sharedResources().validate(); + } + if (costComponents() != null) { + costComponents().forEach(e -> e.validate()); + } + if (migrationGuidelines() != null) { + migrationGuidelines().forEach(e -> e.validate()); + } + if (recommendationReasonings() != null) { + recommendationReasonings().forEach(e -> e.validate()); + } + if (migrationIssues() != null) { + migrationIssues().forEach(e -> e.validate()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("costComponents", this.costComponents, + (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlAssessmentV2PaasSuitabilityData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlAssessmentV2PaasSuitabilityData 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 SqlAssessmentV2PaasSuitabilityData. + */ + public static SqlAssessmentV2PaasSuitabilityData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlAssessmentV2PaasSuitabilityData deserializedSqlAssessmentV2PaasSuitabilityData + = new SqlAssessmentV2PaasSuitabilityData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("azureSqlSku".equals(fieldName)) { + deserializedSqlAssessmentV2PaasSuitabilityData.azureSqlSku = AzureSqlPaasSkuDto.fromJson(reader); + } else if ("replicaAzureSqlSku".equals(fieldName)) { + List replicaAzureSqlSku + = reader.readArray(reader1 -> AzureSqlPaasSkuDto.fromJson(reader1)); + deserializedSqlAssessmentV2PaasSuitabilityData.replicaAzureSqlSku = replicaAzureSqlSku; + } else if ("sharedResources".equals(fieldName)) { + deserializedSqlAssessmentV2PaasSuitabilityData.sharedResources + = SharedResourcesDto.fromJson(reader); + } else if ("monthlyComputeCost".equals(fieldName)) { + deserializedSqlAssessmentV2PaasSuitabilityData.monthlyComputeCost + = reader.getNullable(JsonReader::getFloat); + } else if ("monthlyStorageCost".equals(fieldName)) { + deserializedSqlAssessmentV2PaasSuitabilityData.monthlyStorageCost + = reader.getNullable(JsonReader::getFloat); + } else if ("costComponents".equals(fieldName)) { + List costComponents = reader.readArray(reader1 -> CostComponent.fromJson(reader1)); + deserializedSqlAssessmentV2PaasSuitabilityData.costComponents = costComponents; + } else if ("securitySuitability".equals(fieldName)) { + deserializedSqlAssessmentV2PaasSuitabilityData.securitySuitability + = CloudSuitability.fromString(reader.getString()); + } else if ("shouldProvisionReplicas".equals(fieldName)) { + deserializedSqlAssessmentV2PaasSuitabilityData.shouldProvisionReplicas + = reader.getNullable(JsonReader::getBoolean); + } else if ("skuReplicationMode".equals(fieldName)) { + deserializedSqlAssessmentV2PaasSuitabilityData.skuReplicationMode + = SkuReplicationMode.fromString(reader.getString()); + } else if ("migrationGuidelines".equals(fieldName)) { + List migrationGuidelines + = reader.readArray(reader1 -> SqlMigrationGuideline.fromJson(reader1)); + deserializedSqlAssessmentV2PaasSuitabilityData.migrationGuidelines = migrationGuidelines; + } else if ("recommendationReasonings".equals(fieldName)) { + List recommendationReasonings + = reader.readArray(reader1 -> SqlRecommendationReasoning.fromJson(reader1)); + deserializedSqlAssessmentV2PaasSuitabilityData.recommendationReasonings = recommendationReasonings; + } else if ("migrationTargetPlatform".equals(fieldName)) { + deserializedSqlAssessmentV2PaasSuitabilityData.migrationTargetPlatform + = TargetType.fromString(reader.getString()); + } else if ("suitability".equals(fieldName)) { + deserializedSqlAssessmentV2PaasSuitabilityData.suitability + = CloudSuitability.fromString(reader.getString()); + } else if ("migrationIssues".equals(fieldName)) { + List migrationIssues + = reader.readArray(reader1 -> SqlAssessmentMigrationIssue.fromJson(reader1)); + deserializedSqlAssessmentV2PaasSuitabilityData.migrationIssues = migrationIssues; + } else { + reader.skipChildren(); + } + } + + return deserializedSqlAssessmentV2PaasSuitabilityData; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2Properties.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2Properties.java new file mode 100644 index 000000000000..ed691a18bb28 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2Properties.java @@ -0,0 +1,1118 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * SQL assessment properties class. + */ +@Fluent +public final class SqlAssessmentV2Properties extends AzureResourceProperties { + /* + * Gets or sets user configurable setting to display the azure hybrid use benefit. + */ + private OsLicense osLicense; + + /* + * Gets or sets user configurable setting to display the environment type. + */ + private EnvironmentType environmentType; + + /* + * Gets or sets the duration for which the entity (SQL, VMs) are up in the + * on-premises environment. + */ + private EntityUptime entityUptime; + + /* + * Gets or sets SQL optimization logic. + */ + private OptimizationLogic optimizationLogic; + + /* + * Gets or sets azure reserved instance for VM. + */ + private AzureReservedInstance reservedInstanceForVm; + + /* + * Gets or sets Azure Offer Code for VM. + */ + private AzureOfferCode azureOfferCodeForVm; + + /* + * Gets or sets the Enterprise agreement subscription id. + */ + private String eaSubscriptionId; + + /* + * Gets or sets user configurable SQL managed instance settings. + */ + private SqlMiSettings azureSqlManagedInstanceSettings; + + /* + * Gets or sets user configurable SQL database settings. + */ + private SqlDbSettings azureSqlDatabaseSettings; + + /* + * Gets or sets user configurable SQL VM settings. + */ + private SqlVmSettings azureSqlVmSettings; + + /* + * Gets or sets user preference indicating intent of multi-subnet configuration. + */ + private MultiSubnetIntent multiSubnetIntent; + + /* + * Gets or sets user preference indicating intent of async commit mode. + */ + private AsyncCommitModeIntent asyncCommitModeIntent; + + /* + * Gets or sets a value indicating whether internet access is available. + */ + private Boolean isInternetAccessAvailable; + + /* + * Gets or sets the Azure Location or Azure region where to which the machines + * will be migrated. + */ + private AzureLocation disasterRecoveryLocation; + + /* + * Gets or sets a value indicating whether HADR assessments needs to be created. + */ + private Boolean enableHadrAssessment; + + /* + * Gets or sets a value indicating azure security offering type. + */ + private AzureSecurityOfferingType azureSecurityOfferingType; + + /* + * Reserved instance. + */ + private AzureReservedInstance reservedInstance; + + /* + * SQL server license. + */ + private SqlServerLicense sqlServerLicense; + + /* + * Gets the group type for the assessment. + */ + private GroupType groupType; + + /* + * Assessment type of the assessment. + */ + private AssessmentType assessmentType; + + /* + * Azure Location or Azure region where to which the machines will be migrated. + */ + private String azureLocation; + + /* + * Azure Offer Code. + */ + private AzureOfferCode azureOfferCode; + + /* + * Currency in which prices should be reported. + */ + private AzureCurrency currency; + + /* + * Percentage of buffer that user wants on performance metrics when recommending + * Azure sizes. + */ + private Float scalingFactor; + + /* + * Percentile of the utilization data values to be considered while assessing + * machines. + */ + private Percentile percentile; + + /* + * Time Range for which the historic utilization data should be considered for + * assessment. + */ + private TimeRange timeRange; + + /* + * Gets or sets the start time to consider performance data for assessment. + */ + private OffsetDateTime perfDataStartTime; + + /* + * Gets or sets the end time to consider performance data for assessment. + */ + private OffsetDateTime perfDataEndTime; + + /* + * User configurable setting to display the Stage of Assessment. + */ + private AssessmentStage stage; + + /* + * Custom discount percentage. + */ + private Float discountPercentage; + + /* + * Assessment sizing criterion. + */ + private AssessmentSizingCriterion sizingCriterion; + + /* + * Confidence Rating in Percentage. + */ + private Float confidenceRatingInPercentage; + + /* + * Last time when rates were queried. + */ + private OffsetDateTime pricesTimestamp; + + /* + * Date and Time when assessment was created. + */ + private OffsetDateTime createdTimestamp; + + /* + * Date and Time when assessment was last updated. + */ + private OffsetDateTime updatedTimestamp; + + /* + * Whether assessment is in valid state and all machines have been assessed. + */ + private AssessmentStatus status; + + /* + * Schema version. + */ + private String schemaVersion; + + /** + * Creates an instance of SqlAssessmentV2Properties class. + */ + public SqlAssessmentV2Properties() { + } + + /** + * Get the osLicense property: Gets or sets user configurable setting to display the azure hybrid use benefit. + * + * @return the osLicense value. + */ + public OsLicense osLicense() { + return this.osLicense; + } + + /** + * Set the osLicense property: Gets or sets user configurable setting to display the azure hybrid use benefit. + * + * @param osLicense the osLicense value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties withOsLicense(OsLicense osLicense) { + this.osLicense = osLicense; + return this; + } + + /** + * Get the environmentType property: Gets or sets user configurable setting to display the environment type. + * + * @return the environmentType value. + */ + public EnvironmentType environmentType() { + return this.environmentType; + } + + /** + * Set the environmentType property: Gets or sets user configurable setting to display the environment type. + * + * @param environmentType the environmentType value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties withEnvironmentType(EnvironmentType environmentType) { + this.environmentType = environmentType; + return this; + } + + /** + * Get the entityUptime property: Gets or sets the duration for which the entity (SQL, VMs) are up in the + * on-premises environment. + * + * @return the entityUptime value. + */ + public EntityUptime entityUptime() { + return this.entityUptime; + } + + /** + * Set the entityUptime property: Gets or sets the duration for which the entity (SQL, VMs) are up in the + * on-premises environment. + * + * @param entityUptime the entityUptime value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties withEntityUptime(EntityUptime entityUptime) { + this.entityUptime = entityUptime; + return this; + } + + /** + * Get the optimizationLogic property: Gets or sets SQL optimization logic. + * + * @return the optimizationLogic value. + */ + public OptimizationLogic optimizationLogic() { + return this.optimizationLogic; + } + + /** + * Set the optimizationLogic property: Gets or sets SQL optimization logic. + * + * @param optimizationLogic the optimizationLogic value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties withOptimizationLogic(OptimizationLogic optimizationLogic) { + this.optimizationLogic = optimizationLogic; + return this; + } + + /** + * Get the reservedInstanceForVm property: Gets or sets azure reserved instance for VM. + * + * @return the reservedInstanceForVm value. + */ + public AzureReservedInstance reservedInstanceForVm() { + return this.reservedInstanceForVm; + } + + /** + * Set the reservedInstanceForVm property: Gets or sets azure reserved instance for VM. + * + * @param reservedInstanceForVm the reservedInstanceForVm value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties withReservedInstanceForVm(AzureReservedInstance reservedInstanceForVm) { + this.reservedInstanceForVm = reservedInstanceForVm; + return this; + } + + /** + * Get the azureOfferCodeForVm property: Gets or sets Azure Offer Code for VM. + * + * @return the azureOfferCodeForVm value. + */ + public AzureOfferCode azureOfferCodeForVm() { + return this.azureOfferCodeForVm; + } + + /** + * Set the azureOfferCodeForVm property: Gets or sets Azure Offer Code for VM. + * + * @param azureOfferCodeForVm the azureOfferCodeForVm value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties withAzureOfferCodeForVm(AzureOfferCode azureOfferCodeForVm) { + this.azureOfferCodeForVm = azureOfferCodeForVm; + return this; + } + + /** + * Get the eaSubscriptionId property: Gets or sets the Enterprise agreement subscription id. + * + * @return the eaSubscriptionId value. + */ + public String eaSubscriptionId() { + return this.eaSubscriptionId; + } + + /** + * Set the eaSubscriptionId property: Gets or sets the Enterprise agreement subscription id. + * + * @param eaSubscriptionId the eaSubscriptionId value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties withEaSubscriptionId(String eaSubscriptionId) { + this.eaSubscriptionId = eaSubscriptionId; + return this; + } + + /** + * Get the azureSqlManagedInstanceSettings property: Gets or sets user configurable SQL managed instance settings. + * + * @return the azureSqlManagedInstanceSettings value. + */ + public SqlMiSettings azureSqlManagedInstanceSettings() { + return this.azureSqlManagedInstanceSettings; + } + + /** + * Set the azureSqlManagedInstanceSettings property: Gets or sets user configurable SQL managed instance settings. + * + * @param azureSqlManagedInstanceSettings the azureSqlManagedInstanceSettings value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties + withAzureSqlManagedInstanceSettings(SqlMiSettings azureSqlManagedInstanceSettings) { + this.azureSqlManagedInstanceSettings = azureSqlManagedInstanceSettings; + return this; + } + + /** + * Get the azureSqlDatabaseSettings property: Gets or sets user configurable SQL database settings. + * + * @return the azureSqlDatabaseSettings value. + */ + public SqlDbSettings azureSqlDatabaseSettings() { + return this.azureSqlDatabaseSettings; + } + + /** + * Set the azureSqlDatabaseSettings property: Gets or sets user configurable SQL database settings. + * + * @param azureSqlDatabaseSettings the azureSqlDatabaseSettings value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties withAzureSqlDatabaseSettings(SqlDbSettings azureSqlDatabaseSettings) { + this.azureSqlDatabaseSettings = azureSqlDatabaseSettings; + return this; + } + + /** + * Get the azureSqlVmSettings property: Gets or sets user configurable SQL VM settings. + * + * @return the azureSqlVmSettings value. + */ + public SqlVmSettings azureSqlVmSettings() { + return this.azureSqlVmSettings; + } + + /** + * Set the azureSqlVmSettings property: Gets or sets user configurable SQL VM settings. + * + * @param azureSqlVmSettings the azureSqlVmSettings value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties withAzureSqlVmSettings(SqlVmSettings azureSqlVmSettings) { + this.azureSqlVmSettings = azureSqlVmSettings; + return this; + } + + /** + * Get the multiSubnetIntent property: Gets or sets user preference indicating intent of multi-subnet configuration. + * + * @return the multiSubnetIntent value. + */ + public MultiSubnetIntent multiSubnetIntent() { + return this.multiSubnetIntent; + } + + /** + * Set the multiSubnetIntent property: Gets or sets user preference indicating intent of multi-subnet configuration. + * + * @param multiSubnetIntent the multiSubnetIntent value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties withMultiSubnetIntent(MultiSubnetIntent multiSubnetIntent) { + this.multiSubnetIntent = multiSubnetIntent; + return this; + } + + /** + * Get the asyncCommitModeIntent property: Gets or sets user preference indicating intent of async commit mode. + * + * @return the asyncCommitModeIntent value. + */ + public AsyncCommitModeIntent asyncCommitModeIntent() { + return this.asyncCommitModeIntent; + } + + /** + * Set the asyncCommitModeIntent property: Gets or sets user preference indicating intent of async commit mode. + * + * @param asyncCommitModeIntent the asyncCommitModeIntent value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties withAsyncCommitModeIntent(AsyncCommitModeIntent asyncCommitModeIntent) { + this.asyncCommitModeIntent = asyncCommitModeIntent; + return this; + } + + /** + * Get the isInternetAccessAvailable property: Gets or sets a value indicating whether internet access is available. + * + * @return the isInternetAccessAvailable value. + */ + public Boolean isInternetAccessAvailable() { + return this.isInternetAccessAvailable; + } + + /** + * Set the isInternetAccessAvailable property: Gets or sets a value indicating whether internet access is available. + * + * @param isInternetAccessAvailable the isInternetAccessAvailable value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties withIsInternetAccessAvailable(Boolean isInternetAccessAvailable) { + this.isInternetAccessAvailable = isInternetAccessAvailable; + return this; + } + + /** + * Get the disasterRecoveryLocation property: Gets or sets the Azure Location or Azure region where to which the + * machines + * will be migrated. + * + * @return the disasterRecoveryLocation value. + */ + public AzureLocation disasterRecoveryLocation() { + return this.disasterRecoveryLocation; + } + + /** + * Set the disasterRecoveryLocation property: Gets or sets the Azure Location or Azure region where to which the + * machines + * will be migrated. + * + * @param disasterRecoveryLocation the disasterRecoveryLocation value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties withDisasterRecoveryLocation(AzureLocation disasterRecoveryLocation) { + this.disasterRecoveryLocation = disasterRecoveryLocation; + return this; + } + + /** + * Get the enableHadrAssessment property: Gets or sets a value indicating whether HADR assessments needs to be + * created. + * + * @return the enableHadrAssessment value. + */ + public Boolean enableHadrAssessment() { + return this.enableHadrAssessment; + } + + /** + * Set the enableHadrAssessment property: Gets or sets a value indicating whether HADR assessments needs to be + * created. + * + * @param enableHadrAssessment the enableHadrAssessment value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties withEnableHadrAssessment(Boolean enableHadrAssessment) { + this.enableHadrAssessment = enableHadrAssessment; + return this; + } + + /** + * Get the azureSecurityOfferingType property: Gets or sets a value indicating azure security offering type. + * + * @return the azureSecurityOfferingType value. + */ + public AzureSecurityOfferingType azureSecurityOfferingType() { + return this.azureSecurityOfferingType; + } + + /** + * Set the azureSecurityOfferingType property: Gets or sets a value indicating azure security offering type. + * + * @param azureSecurityOfferingType the azureSecurityOfferingType value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties + withAzureSecurityOfferingType(AzureSecurityOfferingType azureSecurityOfferingType) { + this.azureSecurityOfferingType = azureSecurityOfferingType; + return this; + } + + /** + * Get the reservedInstance property: Reserved instance. + * + * @return the reservedInstance value. + */ + public AzureReservedInstance reservedInstance() { + return this.reservedInstance; + } + + /** + * Set the reservedInstance property: Reserved instance. + * + * @param reservedInstance the reservedInstance value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties withReservedInstance(AzureReservedInstance reservedInstance) { + this.reservedInstance = reservedInstance; + return this; + } + + /** + * Get the sqlServerLicense property: SQL server license. + * + * @return the sqlServerLicense value. + */ + public SqlServerLicense sqlServerLicense() { + return this.sqlServerLicense; + } + + /** + * Set the sqlServerLicense property: SQL server license. + * + * @param sqlServerLicense the sqlServerLicense value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties withSqlServerLicense(SqlServerLicense sqlServerLicense) { + this.sqlServerLicense = sqlServerLicense; + return this; + } + + /** + * Get the groupType property: Gets the group type for the assessment. + * + * @return the groupType value. + */ + public GroupType groupType() { + return this.groupType; + } + + /** + * Set the groupType property: Gets the group type for the assessment. + * + * @param groupType the groupType value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties withGroupType(GroupType groupType) { + this.groupType = groupType; + return this; + } + + /** + * Get the assessmentType property: Assessment type of the assessment. + * + * @return the assessmentType value. + */ + public AssessmentType assessmentType() { + return this.assessmentType; + } + + /** + * Set the assessmentType property: Assessment type of the assessment. + * + * @param assessmentType the assessmentType value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties withAssessmentType(AssessmentType assessmentType) { + this.assessmentType = assessmentType; + return this; + } + + /** + * Get the azureLocation property: Azure Location or Azure region where to which the machines will be migrated. + * + * @return the azureLocation value. + */ + public String azureLocation() { + return this.azureLocation; + } + + /** + * Set the azureLocation property: Azure Location or Azure region where to which the machines will be migrated. + * + * @param azureLocation the azureLocation value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties withAzureLocation(String azureLocation) { + this.azureLocation = azureLocation; + return this; + } + + /** + * Get the azureOfferCode property: Azure Offer Code. + * + * @return the azureOfferCode value. + */ + public AzureOfferCode azureOfferCode() { + return this.azureOfferCode; + } + + /** + * Set the azureOfferCode property: Azure Offer Code. + * + * @param azureOfferCode the azureOfferCode value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties withAzureOfferCode(AzureOfferCode azureOfferCode) { + this.azureOfferCode = azureOfferCode; + return this; + } + + /** + * Get the currency property: Currency in which prices should be reported. + * + * @return the currency value. + */ + public AzureCurrency currency() { + return this.currency; + } + + /** + * Set the currency property: Currency in which prices should be reported. + * + * @param currency the currency value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties withCurrency(AzureCurrency currency) { + this.currency = currency; + return this; + } + + /** + * Get the scalingFactor property: Percentage of buffer that user wants on performance metrics when recommending + * Azure sizes. + * + * @return the scalingFactor value. + */ + public Float scalingFactor() { + return this.scalingFactor; + } + + /** + * Set the scalingFactor property: Percentage of buffer that user wants on performance metrics when recommending + * Azure sizes. + * + * @param scalingFactor the scalingFactor value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties withScalingFactor(Float scalingFactor) { + this.scalingFactor = scalingFactor; + return this; + } + + /** + * Get the percentile property: Percentile of the utilization data values to be considered while assessing + * machines. + * + * @return the percentile value. + */ + public Percentile percentile() { + return this.percentile; + } + + /** + * Set the percentile property: Percentile of the utilization data values to be considered while assessing + * machines. + * + * @param percentile the percentile value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties withPercentile(Percentile percentile) { + this.percentile = percentile; + return this; + } + + /** + * Get the timeRange property: Time Range for which the historic utilization data should be considered for + * assessment. + * + * @return the timeRange value. + */ + public TimeRange timeRange() { + return this.timeRange; + } + + /** + * Set the timeRange property: Time Range for which the historic utilization data should be considered for + * assessment. + * + * @param timeRange the timeRange value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties withTimeRange(TimeRange timeRange) { + this.timeRange = timeRange; + return this; + } + + /** + * Get the perfDataStartTime property: Gets or sets the start time to consider performance data for assessment. + * + * @return the perfDataStartTime value. + */ + public OffsetDateTime perfDataStartTime() { + return this.perfDataStartTime; + } + + /** + * Set the perfDataStartTime property: Gets or sets the start time to consider performance data for assessment. + * + * @param perfDataStartTime the perfDataStartTime value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties withPerfDataStartTime(OffsetDateTime perfDataStartTime) { + this.perfDataStartTime = perfDataStartTime; + return this; + } + + /** + * Get the perfDataEndTime property: Gets or sets the end time to consider performance data for assessment. + * + * @return the perfDataEndTime value. + */ + public OffsetDateTime perfDataEndTime() { + return this.perfDataEndTime; + } + + /** + * Set the perfDataEndTime property: Gets or sets the end time to consider performance data for assessment. + * + * @param perfDataEndTime the perfDataEndTime value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties withPerfDataEndTime(OffsetDateTime perfDataEndTime) { + this.perfDataEndTime = perfDataEndTime; + return this; + } + + /** + * Get the stage property: User configurable setting to display the Stage of Assessment. + * + * @return the stage value. + */ + public AssessmentStage stage() { + return this.stage; + } + + /** + * Get the discountPercentage property: Custom discount percentage. + * + * @return the discountPercentage value. + */ + public Float discountPercentage() { + return this.discountPercentage; + } + + /** + * Set the discountPercentage property: Custom discount percentage. + * + * @param discountPercentage the discountPercentage value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties withDiscountPercentage(Float discountPercentage) { + this.discountPercentage = discountPercentage; + return this; + } + + /** + * Get the sizingCriterion property: Assessment sizing criterion. + * + * @return the sizingCriterion value. + */ + public AssessmentSizingCriterion sizingCriterion() { + return this.sizingCriterion; + } + + /** + * Set the sizingCriterion property: Assessment sizing criterion. + * + * @param sizingCriterion the sizingCriterion value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties withSizingCriterion(AssessmentSizingCriterion sizingCriterion) { + this.sizingCriterion = sizingCriterion; + return this; + } + + /** + * Get the confidenceRatingInPercentage property: Confidence Rating in Percentage. + * + * @return the confidenceRatingInPercentage value. + */ + public Float confidenceRatingInPercentage() { + return this.confidenceRatingInPercentage; + } + + /** + * Set the confidenceRatingInPercentage property: Confidence Rating in Percentage. + * + * @param confidenceRatingInPercentage the confidenceRatingInPercentage value to set. + * @return the SqlAssessmentV2Properties object itself. + */ + public SqlAssessmentV2Properties withConfidenceRatingInPercentage(Float confidenceRatingInPercentage) { + this.confidenceRatingInPercentage = confidenceRatingInPercentage; + return this; + } + + /** + * Get the pricesTimestamp property: Last time when rates were queried. + * + * @return the pricesTimestamp value. + */ + public OffsetDateTime pricesTimestamp() { + return this.pricesTimestamp; + } + + /** + * Get the createdTimestamp property: Date and Time when assessment was created. + * + * @return the createdTimestamp value. + */ + public OffsetDateTime createdTimestamp() { + return this.createdTimestamp; + } + + /** + * Get the updatedTimestamp property: Date and Time when assessment was last updated. + * + * @return the updatedTimestamp value. + */ + public OffsetDateTime updatedTimestamp() { + return this.updatedTimestamp; + } + + /** + * Get the status property: Whether assessment is in valid state and all machines have been assessed. + * + * @return the status value. + */ + public AssessmentStatus status() { + return this.status; + } + + /** + * Get the schemaVersion property: Schema version. + * + * @return the schemaVersion value. + */ + public String schemaVersion() { + return this.schemaVersion; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlAssessmentV2Properties withProvisioningState(ProvisioningState provisioningState) { + super.withProvisioningState(provisioningState); + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + @Override + public void validate() { + if (entityUptime() != null) { + entityUptime().validate(); + } + if (azureSqlManagedInstanceSettings() != null) { + azureSqlManagedInstanceSettings().validate(); + } + if (azureSqlDatabaseSettings() != null) { + azureSqlDatabaseSettings().validate(); + } + if (azureSqlVmSettings() != null) { + azureSqlVmSettings().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("provisioningState", + provisioningState() == null ? null : provisioningState().toString()); + jsonWriter.writeStringField("osLicense", this.osLicense == null ? null : this.osLicense.toString()); + jsonWriter.writeStringField("environmentType", + this.environmentType == null ? null : this.environmentType.toString()); + jsonWriter.writeJsonField("entityUptime", this.entityUptime); + jsonWriter.writeStringField("optimizationLogic", + this.optimizationLogic == null ? null : this.optimizationLogic.toString()); + jsonWriter.writeStringField("reservedInstanceForVm", + this.reservedInstanceForVm == null ? null : this.reservedInstanceForVm.toString()); + jsonWriter.writeStringField("azureOfferCodeForVm", + this.azureOfferCodeForVm == null ? null : this.azureOfferCodeForVm.toString()); + jsonWriter.writeStringField("eaSubscriptionId", this.eaSubscriptionId); + jsonWriter.writeJsonField("azureSqlManagedInstanceSettings", this.azureSqlManagedInstanceSettings); + jsonWriter.writeJsonField("azureSqlDatabaseSettings", this.azureSqlDatabaseSettings); + jsonWriter.writeJsonField("azureSqlVmSettings", this.azureSqlVmSettings); + jsonWriter.writeStringField("multiSubnetIntent", + this.multiSubnetIntent == null ? null : this.multiSubnetIntent.toString()); + jsonWriter.writeStringField("asyncCommitModeIntent", + this.asyncCommitModeIntent == null ? null : this.asyncCommitModeIntent.toString()); + jsonWriter.writeBooleanField("isInternetAccessAvailable", this.isInternetAccessAvailable); + jsonWriter.writeStringField("disasterRecoveryLocation", + this.disasterRecoveryLocation == null ? null : this.disasterRecoveryLocation.toString()); + jsonWriter.writeBooleanField("enableHadrAssessment", this.enableHadrAssessment); + jsonWriter.writeStringField("azureSecurityOfferingType", + this.azureSecurityOfferingType == null ? null : this.azureSecurityOfferingType.toString()); + jsonWriter.writeStringField("reservedInstance", + this.reservedInstance == null ? null : this.reservedInstance.toString()); + jsonWriter.writeStringField("sqlServerLicense", + this.sqlServerLicense == null ? null : this.sqlServerLicense.toString()); + jsonWriter.writeStringField("groupType", this.groupType == null ? null : this.groupType.toString()); + jsonWriter.writeStringField("assessmentType", + this.assessmentType == null ? null : this.assessmentType.toString()); + jsonWriter.writeStringField("azureLocation", this.azureLocation); + jsonWriter.writeStringField("azureOfferCode", + this.azureOfferCode == null ? null : this.azureOfferCode.toString()); + jsonWriter.writeStringField("currency", this.currency == null ? null : this.currency.toString()); + jsonWriter.writeNumberField("scalingFactor", this.scalingFactor); + jsonWriter.writeStringField("percentile", this.percentile == null ? null : this.percentile.toString()); + jsonWriter.writeStringField("timeRange", this.timeRange == null ? null : this.timeRange.toString()); + jsonWriter.writeStringField("perfDataStartTime", + this.perfDataStartTime == null + ? null + : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.perfDataStartTime)); + jsonWriter.writeStringField("perfDataEndTime", + this.perfDataEndTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.perfDataEndTime)); + jsonWriter.writeNumberField("discountPercentage", this.discountPercentage); + jsonWriter.writeStringField("sizingCriterion", + this.sizingCriterion == null ? null : this.sizingCriterion.toString()); + jsonWriter.writeNumberField("confidenceRatingInPercentage", this.confidenceRatingInPercentage); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlAssessmentV2Properties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlAssessmentV2Properties 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 SqlAssessmentV2Properties. + */ + public static SqlAssessmentV2Properties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlAssessmentV2Properties deserializedSqlAssessmentV2Properties = new SqlAssessmentV2Properties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("provisioningState".equals(fieldName)) { + deserializedSqlAssessmentV2Properties + .withProvisioningState(ProvisioningState.fromString(reader.getString())); + } else if ("osLicense".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.osLicense = OsLicense.fromString(reader.getString()); + } else if ("environmentType".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.environmentType + = EnvironmentType.fromString(reader.getString()); + } else if ("entityUptime".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.entityUptime = EntityUptime.fromJson(reader); + } else if ("optimizationLogic".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.optimizationLogic + = OptimizationLogic.fromString(reader.getString()); + } else if ("reservedInstanceForVm".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.reservedInstanceForVm + = AzureReservedInstance.fromString(reader.getString()); + } else if ("azureOfferCodeForVm".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.azureOfferCodeForVm + = AzureOfferCode.fromString(reader.getString()); + } else if ("eaSubscriptionId".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.eaSubscriptionId = reader.getString(); + } else if ("azureSqlManagedInstanceSettings".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.azureSqlManagedInstanceSettings + = SqlMiSettings.fromJson(reader); + } else if ("azureSqlDatabaseSettings".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.azureSqlDatabaseSettings = SqlDbSettings.fromJson(reader); + } else if ("azureSqlVmSettings".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.azureSqlVmSettings = SqlVmSettings.fromJson(reader); + } else if ("multiSubnetIntent".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.multiSubnetIntent + = MultiSubnetIntent.fromString(reader.getString()); + } else if ("asyncCommitModeIntent".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.asyncCommitModeIntent + = AsyncCommitModeIntent.fromString(reader.getString()); + } else if ("isInternetAccessAvailable".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.isInternetAccessAvailable + = reader.getNullable(JsonReader::getBoolean); + } else if ("disasterRecoveryLocation".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.disasterRecoveryLocation + = AzureLocation.fromString(reader.getString()); + } else if ("enableHadrAssessment".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.enableHadrAssessment + = reader.getNullable(JsonReader::getBoolean); + } else if ("azureSecurityOfferingType".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.azureSecurityOfferingType + = AzureSecurityOfferingType.fromString(reader.getString()); + } else if ("reservedInstance".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.reservedInstance + = AzureReservedInstance.fromString(reader.getString()); + } else if ("sqlServerLicense".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.sqlServerLicense + = SqlServerLicense.fromString(reader.getString()); + } else if ("groupType".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.groupType = GroupType.fromString(reader.getString()); + } else if ("assessmentType".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.assessmentType + = AssessmentType.fromString(reader.getString()); + } else if ("azureLocation".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.azureLocation = reader.getString(); + } else if ("azureOfferCode".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.azureOfferCode + = AzureOfferCode.fromString(reader.getString()); + } else if ("currency".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.currency = AzureCurrency.fromString(reader.getString()); + } else if ("scalingFactor".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.scalingFactor = reader.getNullable(JsonReader::getFloat); + } else if ("percentile".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.percentile = Percentile.fromString(reader.getString()); + } else if ("timeRange".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.timeRange = TimeRange.fromString(reader.getString()); + } else if ("perfDataStartTime".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.perfDataStartTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("perfDataEndTime".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.perfDataEndTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("stage".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.stage = AssessmentStage.fromString(reader.getString()); + } else if ("discountPercentage".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.discountPercentage = reader.getNullable(JsonReader::getFloat); + } else if ("sizingCriterion".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.sizingCriterion + = AssessmentSizingCriterion.fromString(reader.getString()); + } else if ("confidenceRatingInPercentage".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.confidenceRatingInPercentage + = reader.getNullable(JsonReader::getFloat); + } else if ("pricesTimestamp".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.pricesTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("createdTimestamp".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.createdTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("updatedTimestamp".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.updatedTimestamp = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("status".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.status = AssessmentStatus.fromString(reader.getString()); + } else if ("schemaVersion".equals(fieldName)) { + deserializedSqlAssessmentV2Properties.schemaVersion = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedSqlAssessmentV2Properties; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2Summary.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2Summary.java new file mode 100644 index 000000000000..428f9cb21320 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2Summary.java @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlAssessmentV2SummaryInner; + +/** + * An immutable client-side representation of SqlAssessmentV2Summary. + */ +public interface SqlAssessmentV2Summary { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + SqlAssessmentV2SummaryProperties properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.migration.assessment.fluent.models.SqlAssessmentV2SummaryInner object. + * + * @return the inner object. + */ + SqlAssessmentV2SummaryInner innerModel(); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2SummaryData.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2SummaryData.java new file mode 100644 index 000000000000..d41170b4aa65 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2SummaryData.java @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; +import java.util.Map; + +/** + * SQL Assessment V2 summary data. + */ +@Immutable +public final class SqlAssessmentV2SummaryData implements JsonSerializable { + /* + * Sql assessment summary data + */ + private Map suitabilitySummary; + + /* + * Monthly compute cost + */ + private Float monthlyComputeCost; + + /* + * Monthly storage cost + */ + private Float monthlyStorageCost; + + /* + * Monthly license cost + */ + private Float monthlyLicenseCost; + + /* + * Confidence Rating + */ + private Float confidenceScore; + + /* + * Monthly security cost + */ + private Float monthlySecurityCost; + + /** + * Creates an instance of SqlAssessmentV2SummaryData class. + */ + public SqlAssessmentV2SummaryData() { + } + + /** + * Get the suitabilitySummary property: Sql assessment summary data. + * + * @return the suitabilitySummary value. + */ + public Map suitabilitySummary() { + return this.suitabilitySummary; + } + + /** + * Get the monthlyComputeCost property: Monthly compute cost. + * + * @return the monthlyComputeCost value. + */ + public Float monthlyComputeCost() { + return this.monthlyComputeCost; + } + + /** + * Get the monthlyStorageCost property: Monthly storage cost. + * + * @return the monthlyStorageCost value. + */ + public Float monthlyStorageCost() { + return this.monthlyStorageCost; + } + + /** + * Get the monthlyLicenseCost property: Monthly license cost. + * + * @return the monthlyLicenseCost value. + */ + public Float monthlyLicenseCost() { + return this.monthlyLicenseCost; + } + + /** + * Get the confidenceScore property: Confidence Rating. + * + * @return the confidenceScore value. + */ + public Float confidenceScore() { + return this.confidenceScore; + } + + /** + * Get the monthlySecurityCost property: Monthly security cost. + * + * @return the monthlySecurityCost value. + */ + public Float monthlySecurityCost() { + return this.monthlySecurityCost; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlAssessmentV2SummaryData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlAssessmentV2SummaryData 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 SqlAssessmentV2SummaryData. + */ + public static SqlAssessmentV2SummaryData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlAssessmentV2SummaryData deserializedSqlAssessmentV2SummaryData = new SqlAssessmentV2SummaryData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("suitabilitySummary".equals(fieldName)) { + Map suitabilitySummary = reader.readMap(reader1 -> reader1.getInt()); + deserializedSqlAssessmentV2SummaryData.suitabilitySummary = suitabilitySummary; + } else if ("monthlyComputeCost".equals(fieldName)) { + deserializedSqlAssessmentV2SummaryData.monthlyComputeCost + = reader.getNullable(JsonReader::getFloat); + } else if ("monthlyStorageCost".equals(fieldName)) { + deserializedSqlAssessmentV2SummaryData.monthlyStorageCost + = reader.getNullable(JsonReader::getFloat); + } else if ("monthlyLicenseCost".equals(fieldName)) { + deserializedSqlAssessmentV2SummaryData.monthlyLicenseCost + = reader.getNullable(JsonReader::getFloat); + } else if ("confidenceScore".equals(fieldName)) { + deserializedSqlAssessmentV2SummaryData.confidenceScore = reader.getNullable(JsonReader::getFloat); + } else if ("monthlySecurityCost".equals(fieldName)) { + deserializedSqlAssessmentV2SummaryData.monthlySecurityCost + = reader.getNullable(JsonReader::getFloat); + } else { + reader.skipChildren(); + } + } + + return deserializedSqlAssessmentV2SummaryData; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2SummaryListResult.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2SummaryListResult.java new file mode 100644 index 000000000000..9cce76728e23 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2SummaryListResult.java @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlAssessmentV2SummaryInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a SqlAssessmentV2Summary list operation. + */ +@Fluent +public final class SqlAssessmentV2SummaryListResult implements JsonSerializable { + /* + * The SqlAssessmentV2Summary items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of SqlAssessmentV2SummaryListResult class. + */ + public SqlAssessmentV2SummaryListResult() { + } + + /** + * Get the value property: The SqlAssessmentV2Summary items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Set the value property: The SqlAssessmentV2Summary items on this page. + * + * @param value the value value to set. + * @return the SqlAssessmentV2SummaryListResult object itself. + */ + public SqlAssessmentV2SummaryListResult withValue(List value) { + this.value = value; + return this; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The link to the next page of items. + * + * @param nextLink the nextLink value to set. + * @return the SqlAssessmentV2SummaryListResult object itself. + */ + public SqlAssessmentV2SummaryListResult withNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property value in model SqlAssessmentV2SummaryListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(SqlAssessmentV2SummaryListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlAssessmentV2SummaryListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlAssessmentV2SummaryListResult 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 SqlAssessmentV2SummaryListResult. + */ + public static SqlAssessmentV2SummaryListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlAssessmentV2SummaryListResult deserializedSqlAssessmentV2SummaryListResult + = new SqlAssessmentV2SummaryListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> SqlAssessmentV2SummaryInner.fromJson(reader1)); + deserializedSqlAssessmentV2SummaryListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedSqlAssessmentV2SummaryListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedSqlAssessmentV2SummaryListResult; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2SummaryOperations.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2SummaryOperations.java new file mode 100644 index 000000000000..62a8b832ae7a --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2SummaryOperations.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.resourcemanager.migration.assessment.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of SqlAssessmentV2SummaryOperations. + */ +public interface SqlAssessmentV2SummaryOperations { + /** + * List SqlAssessmentV2Summary resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentV2Summary list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName); + + /** + * List SqlAssessmentV2Summary resources by SqlAssessmentV2. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlAssessmentV2Summary list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listBySqlAssessmentV2(String resourceGroupName, String projectName, + String groupName, String assessmentName, Context context); + + /** + * Get a SqlAssessmentV2Summary. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param summaryName Gets the Name of the SQL Summary. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlAssessmentV2Summary along with {@link Response}. + */ + Response getWithResponse(String resourceGroupName, String projectName, String groupName, + String assessmentName, String summaryName, Context context); + + /** + * Get a SqlAssessmentV2Summary. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param groupName Group ARM name. + * @param assessmentName SQL Assessment arm name. + * @param summaryName Gets the Name of the SQL Summary. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlAssessmentV2Summary. + */ + SqlAssessmentV2Summary get(String resourceGroupName, String projectName, String groupName, String assessmentName, + String summaryName); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2SummaryProperties.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2SummaryProperties.java new file mode 100644 index 000000000000..d2a57d86e4ac --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAssessmentV2SummaryProperties.java @@ -0,0 +1,304 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; +import java.util.Map; + +/** + * SQL Assessment V2 summary properties. + */ +@Immutable +public final class SqlAssessmentV2SummaryProperties implements JsonSerializable { + /* + * Gets or sets the Assessment summary. + */ + private Map assessmentSummary; + + /* + * Gets the distribution of sqlInstances by support status. + */ + private Map distributionBySupportStatus; + + /* + * Gets the distribution distribution of sqlInstances by service pack insight. + */ + private Map distributionByServicePackInsight; + + /* + * Gets the distribution of sqlInstances by sql version. + */ + private Map distributionBySqlVersion; + + /* + * Gets the distribution of sqlInstances by sql edition. + */ + private Map distributionBySqlEdition; + + /* + * Gets the instance distribution by sizing criterion. + */ + private Map instanceDistributionBySizingCriterion; + + /* + * Gets the database distribution by sizing criterion. + */ + private Map databaseDistributionBySizingCriterion; + + /* + * Number of machines part of the assessment. + */ + private Integer numberOfMachines; + + /* + * Number of sql instances part of the assessment. + */ + private Integer numberOfSqlInstances; + + /* + * Number of successfully discovered sql instances part of the assessment. + */ + private Integer numberOfSuccessfullyDiscoveredSqlInstances; + + /* + * Number of sql databases part of the assessment. + */ + private Integer numberOfSqlDatabases; + + /* + * Number of sql failover cluster instances part of the assessment. + */ + private Integer numberOfFciInstances; + + /* + * Number of sql availability groups part of the assessment. + */ + private Integer numberOfSqlAvailabilityGroups; + + /** + * Creates an instance of SqlAssessmentV2SummaryProperties class. + */ + public SqlAssessmentV2SummaryProperties() { + } + + /** + * Get the assessmentSummary property: Gets or sets the Assessment summary. + * + * @return the assessmentSummary value. + */ + public Map assessmentSummary() { + return this.assessmentSummary; + } + + /** + * Get the distributionBySupportStatus property: Gets the distribution of sqlInstances by support status. + * + * @return the distributionBySupportStatus value. + */ + public Map distributionBySupportStatus() { + return this.distributionBySupportStatus; + } + + /** + * Get the distributionByServicePackInsight property: Gets the distribution distribution of sqlInstances by service + * pack insight. + * + * @return the distributionByServicePackInsight value. + */ + public Map distributionByServicePackInsight() { + return this.distributionByServicePackInsight; + } + + /** + * Get the distributionBySqlVersion property: Gets the distribution of sqlInstances by sql version. + * + * @return the distributionBySqlVersion value. + */ + public Map distributionBySqlVersion() { + return this.distributionBySqlVersion; + } + + /** + * Get the distributionBySqlEdition property: Gets the distribution of sqlInstances by sql edition. + * + * @return the distributionBySqlEdition value. + */ + public Map distributionBySqlEdition() { + return this.distributionBySqlEdition; + } + + /** + * Get the instanceDistributionBySizingCriterion property: Gets the instance distribution by sizing criterion. + * + * @return the instanceDistributionBySizingCriterion value. + */ + public Map instanceDistributionBySizingCriterion() { + return this.instanceDistributionBySizingCriterion; + } + + /** + * Get the databaseDistributionBySizingCriterion property: Gets the database distribution by sizing criterion. + * + * @return the databaseDistributionBySizingCriterion value. + */ + public Map databaseDistributionBySizingCriterion() { + return this.databaseDistributionBySizingCriterion; + } + + /** + * Get the numberOfMachines property: Number of machines part of the assessment. + * + * @return the numberOfMachines value. + */ + public Integer numberOfMachines() { + return this.numberOfMachines; + } + + /** + * Get the numberOfSqlInstances property: Number of sql instances part of the assessment. + * + * @return the numberOfSqlInstances value. + */ + public Integer numberOfSqlInstances() { + return this.numberOfSqlInstances; + } + + /** + * Get the numberOfSuccessfullyDiscoveredSqlInstances property: Number of successfully discovered sql instances part + * of the assessment. + * + * @return the numberOfSuccessfullyDiscoveredSqlInstances value. + */ + public Integer numberOfSuccessfullyDiscoveredSqlInstances() { + return this.numberOfSuccessfullyDiscoveredSqlInstances; + } + + /** + * Get the numberOfSqlDatabases property: Number of sql databases part of the assessment. + * + * @return the numberOfSqlDatabases value. + */ + public Integer numberOfSqlDatabases() { + return this.numberOfSqlDatabases; + } + + /** + * Get the numberOfFciInstances property: Number of sql failover cluster instances part of the assessment. + * + * @return the numberOfFciInstances value. + */ + public Integer numberOfFciInstances() { + return this.numberOfFciInstances; + } + + /** + * Get the numberOfSqlAvailabilityGroups property: Number of sql availability groups part of the assessment. + * + * @return the numberOfSqlAvailabilityGroups value. + */ + public Integer numberOfSqlAvailabilityGroups() { + return this.numberOfSqlAvailabilityGroups; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (assessmentSummary() != null) { + assessmentSummary().values().forEach(e -> { + if (e != null) { + e.validate(); + } + }); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlAssessmentV2SummaryProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlAssessmentV2SummaryProperties 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 SqlAssessmentV2SummaryProperties. + */ + public static SqlAssessmentV2SummaryProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlAssessmentV2SummaryProperties deserializedSqlAssessmentV2SummaryProperties + = new SqlAssessmentV2SummaryProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("assessmentSummary".equals(fieldName)) { + Map assessmentSummary + = reader.readMap(reader1 -> SqlAssessmentV2SummaryData.fromJson(reader1)); + deserializedSqlAssessmentV2SummaryProperties.assessmentSummary = assessmentSummary; + } else if ("distributionBySupportStatus".equals(fieldName)) { + Map distributionBySupportStatus = reader.readMap(reader1 -> reader1.getInt()); + deserializedSqlAssessmentV2SummaryProperties.distributionBySupportStatus + = distributionBySupportStatus; + } else if ("distributionByServicePackInsight".equals(fieldName)) { + Map distributionByServicePackInsight = reader.readMap(reader1 -> reader1.getInt()); + deserializedSqlAssessmentV2SummaryProperties.distributionByServicePackInsight + = distributionByServicePackInsight; + } else if ("distributionBySqlVersion".equals(fieldName)) { + Map distributionBySqlVersion = reader.readMap(reader1 -> reader1.getInt()); + deserializedSqlAssessmentV2SummaryProperties.distributionBySqlVersion = distributionBySqlVersion; + } else if ("distributionBySqlEdition".equals(fieldName)) { + Map distributionBySqlEdition = reader.readMap(reader1 -> reader1.getInt()); + deserializedSqlAssessmentV2SummaryProperties.distributionBySqlEdition = distributionBySqlEdition; + } else if ("instanceDistributionBySizingCriterion".equals(fieldName)) { + Map instanceDistributionBySizingCriterion + = reader.readMap(reader1 -> reader1.getInt()); + deserializedSqlAssessmentV2SummaryProperties.instanceDistributionBySizingCriterion + = instanceDistributionBySizingCriterion; + } else if ("databaseDistributionBySizingCriterion".equals(fieldName)) { + Map databaseDistributionBySizingCriterion + = reader.readMap(reader1 -> reader1.getInt()); + deserializedSqlAssessmentV2SummaryProperties.databaseDistributionBySizingCriterion + = databaseDistributionBySizingCriterion; + } else if ("numberOfMachines".equals(fieldName)) { + deserializedSqlAssessmentV2SummaryProperties.numberOfMachines + = reader.getNullable(JsonReader::getInt); + } else if ("numberOfSqlInstances".equals(fieldName)) { + deserializedSqlAssessmentV2SummaryProperties.numberOfSqlInstances + = reader.getNullable(JsonReader::getInt); + } else if ("numberOfSuccessfullyDiscoveredSqlInstances".equals(fieldName)) { + deserializedSqlAssessmentV2SummaryProperties.numberOfSuccessfullyDiscoveredSqlInstances + = reader.getNullable(JsonReader::getInt); + } else if ("numberOfSqlDatabases".equals(fieldName)) { + deserializedSqlAssessmentV2SummaryProperties.numberOfSqlDatabases + = reader.getNullable(JsonReader::getInt); + } else if ("numberOfFciInstances".equals(fieldName)) { + deserializedSqlAssessmentV2SummaryProperties.numberOfFciInstances + = reader.getNullable(JsonReader::getInt); + } else if ("numberOfSqlAvailabilityGroups".equals(fieldName)) { + deserializedSqlAssessmentV2SummaryProperties.numberOfSqlAvailabilityGroups + = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + + return deserializedSqlAssessmentV2SummaryProperties; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAvailabilityGroupDataOverview.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAvailabilityGroupDataOverview.java new file mode 100644 index 000000000000..321579925594 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAvailabilityGroupDataOverview.java @@ -0,0 +1,206 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * Assessed Sql Availability Group Data Overview. + */ +@Fluent +public final class SqlAvailabilityGroupDataOverview implements JsonSerializable { + /* + * Gets the availability group id. + */ + private String availabilityGroupId; + + /* + * Gets the availability group name. + */ + private String availabilityGroupName; + + /* + * Gets the availability group arm id. + */ + private String sqlAvailabilityGroupSdsArmId; + + /* + * Gets the availability group entity id. + */ + private String sqlAvailabilityGroupEntityId; + + /* + * Gets the availability replica id. + */ + private String sqlAvailabilityReplicaId; + + /** + * Creates an instance of SqlAvailabilityGroupDataOverview class. + */ + public SqlAvailabilityGroupDataOverview() { + } + + /** + * Get the availabilityGroupId property: Gets the availability group id. + * + * @return the availabilityGroupId value. + */ + public String availabilityGroupId() { + return this.availabilityGroupId; + } + + /** + * Set the availabilityGroupId property: Gets the availability group id. + * + * @param availabilityGroupId the availabilityGroupId value to set. + * @return the SqlAvailabilityGroupDataOverview object itself. + */ + public SqlAvailabilityGroupDataOverview withAvailabilityGroupId(String availabilityGroupId) { + this.availabilityGroupId = availabilityGroupId; + return this; + } + + /** + * Get the availabilityGroupName property: Gets the availability group name. + * + * @return the availabilityGroupName value. + */ + public String availabilityGroupName() { + return this.availabilityGroupName; + } + + /** + * Set the availabilityGroupName property: Gets the availability group name. + * + * @param availabilityGroupName the availabilityGroupName value to set. + * @return the SqlAvailabilityGroupDataOverview object itself. + */ + public SqlAvailabilityGroupDataOverview withAvailabilityGroupName(String availabilityGroupName) { + this.availabilityGroupName = availabilityGroupName; + return this; + } + + /** + * Get the sqlAvailabilityGroupSdsArmId property: Gets the availability group arm id. + * + * @return the sqlAvailabilityGroupSdsArmId value. + */ + public String sqlAvailabilityGroupSdsArmId() { + return this.sqlAvailabilityGroupSdsArmId; + } + + /** + * Set the sqlAvailabilityGroupSdsArmId property: Gets the availability group arm id. + * + * @param sqlAvailabilityGroupSdsArmId the sqlAvailabilityGroupSdsArmId value to set. + * @return the SqlAvailabilityGroupDataOverview object itself. + */ + public SqlAvailabilityGroupDataOverview withSqlAvailabilityGroupSdsArmId(String sqlAvailabilityGroupSdsArmId) { + this.sqlAvailabilityGroupSdsArmId = sqlAvailabilityGroupSdsArmId; + return this; + } + + /** + * Get the sqlAvailabilityGroupEntityId property: Gets the availability group entity id. + * + * @return the sqlAvailabilityGroupEntityId value. + */ + public String sqlAvailabilityGroupEntityId() { + return this.sqlAvailabilityGroupEntityId; + } + + /** + * Set the sqlAvailabilityGroupEntityId property: Gets the availability group entity id. + * + * @param sqlAvailabilityGroupEntityId the sqlAvailabilityGroupEntityId value to set. + * @return the SqlAvailabilityGroupDataOverview object itself. + */ + public SqlAvailabilityGroupDataOverview withSqlAvailabilityGroupEntityId(String sqlAvailabilityGroupEntityId) { + this.sqlAvailabilityGroupEntityId = sqlAvailabilityGroupEntityId; + return this; + } + + /** + * Get the sqlAvailabilityReplicaId property: Gets the availability replica id. + * + * @return the sqlAvailabilityReplicaId value. + */ + public String sqlAvailabilityReplicaId() { + return this.sqlAvailabilityReplicaId; + } + + /** + * Set the sqlAvailabilityReplicaId property: Gets the availability replica id. + * + * @param sqlAvailabilityReplicaId the sqlAvailabilityReplicaId value to set. + * @return the SqlAvailabilityGroupDataOverview object itself. + */ + public SqlAvailabilityGroupDataOverview withSqlAvailabilityReplicaId(String sqlAvailabilityReplicaId) { + this.sqlAvailabilityReplicaId = sqlAvailabilityReplicaId; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("availabilityGroupId", this.availabilityGroupId); + jsonWriter.writeStringField("availabilityGroupName", this.availabilityGroupName); + jsonWriter.writeStringField("sqlAvailabilityGroupSdsArmId", this.sqlAvailabilityGroupSdsArmId); + jsonWriter.writeStringField("sqlAvailabilityGroupEntityId", this.sqlAvailabilityGroupEntityId); + jsonWriter.writeStringField("sqlAvailabilityReplicaId", this.sqlAvailabilityReplicaId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlAvailabilityGroupDataOverview from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlAvailabilityGroupDataOverview 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 SqlAvailabilityGroupDataOverview. + */ + public static SqlAvailabilityGroupDataOverview fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlAvailabilityGroupDataOverview deserializedSqlAvailabilityGroupDataOverview + = new SqlAvailabilityGroupDataOverview(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("availabilityGroupId".equals(fieldName)) { + deserializedSqlAvailabilityGroupDataOverview.availabilityGroupId = reader.getString(); + } else if ("availabilityGroupName".equals(fieldName)) { + deserializedSqlAvailabilityGroupDataOverview.availabilityGroupName = reader.getString(); + } else if ("sqlAvailabilityGroupSdsArmId".equals(fieldName)) { + deserializedSqlAvailabilityGroupDataOverview.sqlAvailabilityGroupSdsArmId = reader.getString(); + } else if ("sqlAvailabilityGroupEntityId".equals(fieldName)) { + deserializedSqlAvailabilityGroupDataOverview.sqlAvailabilityGroupEntityId = reader.getString(); + } else if ("sqlAvailabilityReplicaId".equals(fieldName)) { + deserializedSqlAvailabilityGroupDataOverview.sqlAvailabilityReplicaId = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedSqlAvailabilityGroupDataOverview; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAvailabilityReplicaSummary.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAvailabilityReplicaSummary.java new file mode 100644 index 000000000000..6e85a5b1e13b --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlAvailabilityReplicaSummary.java @@ -0,0 +1,214 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * Assessed Sql Availability Replica Summary. + */ +@Fluent +public final class SqlAvailabilityReplicaSummary implements JsonSerializable { + /* + * Gets the number Of synchronous read replicas. + */ + private Integer numberOfSynchronousReadReplicas; + + /* + * Gets the number Of synchronous non read replicas. + */ + private Integer numberOfSynchronousNonReadReplicas; + + /* + * Gets the number Of asynchronous read replicas. + */ + private Integer numberOfAsynchronousReadReplicas; + + /* + * Gets the number Of asynchronous non read replicas. + */ + private Integer numberOfAsynchronousNonReadReplicas; + + /* + * Gets the number Of primary replicas. + */ + private Integer numberOfPrimaryReplicas; + + /** + * Creates an instance of SqlAvailabilityReplicaSummary class. + */ + public SqlAvailabilityReplicaSummary() { + } + + /** + * Get the numberOfSynchronousReadReplicas property: Gets the number Of synchronous read replicas. + * + * @return the numberOfSynchronousReadReplicas value. + */ + public Integer numberOfSynchronousReadReplicas() { + return this.numberOfSynchronousReadReplicas; + } + + /** + * Set the numberOfSynchronousReadReplicas property: Gets the number Of synchronous read replicas. + * + * @param numberOfSynchronousReadReplicas the numberOfSynchronousReadReplicas value to set. + * @return the SqlAvailabilityReplicaSummary object itself. + */ + public SqlAvailabilityReplicaSummary withNumberOfSynchronousReadReplicas(Integer numberOfSynchronousReadReplicas) { + this.numberOfSynchronousReadReplicas = numberOfSynchronousReadReplicas; + return this; + } + + /** + * Get the numberOfSynchronousNonReadReplicas property: Gets the number Of synchronous non read replicas. + * + * @return the numberOfSynchronousNonReadReplicas value. + */ + public Integer numberOfSynchronousNonReadReplicas() { + return this.numberOfSynchronousNonReadReplicas; + } + + /** + * Set the numberOfSynchronousNonReadReplicas property: Gets the number Of synchronous non read replicas. + * + * @param numberOfSynchronousNonReadReplicas the numberOfSynchronousNonReadReplicas value to set. + * @return the SqlAvailabilityReplicaSummary object itself. + */ + public SqlAvailabilityReplicaSummary + withNumberOfSynchronousNonReadReplicas(Integer numberOfSynchronousNonReadReplicas) { + this.numberOfSynchronousNonReadReplicas = numberOfSynchronousNonReadReplicas; + return this; + } + + /** + * Get the numberOfAsynchronousReadReplicas property: Gets the number Of asynchronous read replicas. + * + * @return the numberOfAsynchronousReadReplicas value. + */ + public Integer numberOfAsynchronousReadReplicas() { + return this.numberOfAsynchronousReadReplicas; + } + + /** + * Set the numberOfAsynchronousReadReplicas property: Gets the number Of asynchronous read replicas. + * + * @param numberOfAsynchronousReadReplicas the numberOfAsynchronousReadReplicas value to set. + * @return the SqlAvailabilityReplicaSummary object itself. + */ + public SqlAvailabilityReplicaSummary + withNumberOfAsynchronousReadReplicas(Integer numberOfAsynchronousReadReplicas) { + this.numberOfAsynchronousReadReplicas = numberOfAsynchronousReadReplicas; + return this; + } + + /** + * Get the numberOfAsynchronousNonReadReplicas property: Gets the number Of asynchronous non read replicas. + * + * @return the numberOfAsynchronousNonReadReplicas value. + */ + public Integer numberOfAsynchronousNonReadReplicas() { + return this.numberOfAsynchronousNonReadReplicas; + } + + /** + * Set the numberOfAsynchronousNonReadReplicas property: Gets the number Of asynchronous non read replicas. + * + * @param numberOfAsynchronousNonReadReplicas the numberOfAsynchronousNonReadReplicas value to set. + * @return the SqlAvailabilityReplicaSummary object itself. + */ + public SqlAvailabilityReplicaSummary + withNumberOfAsynchronousNonReadReplicas(Integer numberOfAsynchronousNonReadReplicas) { + this.numberOfAsynchronousNonReadReplicas = numberOfAsynchronousNonReadReplicas; + return this; + } + + /** + * Get the numberOfPrimaryReplicas property: Gets the number Of primary replicas. + * + * @return the numberOfPrimaryReplicas value. + */ + public Integer numberOfPrimaryReplicas() { + return this.numberOfPrimaryReplicas; + } + + /** + * Set the numberOfPrimaryReplicas property: Gets the number Of primary replicas. + * + * @param numberOfPrimaryReplicas the numberOfPrimaryReplicas value to set. + * @return the SqlAvailabilityReplicaSummary object itself. + */ + public SqlAvailabilityReplicaSummary withNumberOfPrimaryReplicas(Integer numberOfPrimaryReplicas) { + this.numberOfPrimaryReplicas = numberOfPrimaryReplicas; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeNumberField("numberOfSynchronousReadReplicas", this.numberOfSynchronousReadReplicas); + jsonWriter.writeNumberField("numberOfSynchronousNonReadReplicas", this.numberOfSynchronousNonReadReplicas); + jsonWriter.writeNumberField("numberOfAsynchronousReadReplicas", this.numberOfAsynchronousReadReplicas); + jsonWriter.writeNumberField("numberOfAsynchronousNonReadReplicas", this.numberOfAsynchronousNonReadReplicas); + jsonWriter.writeNumberField("numberOfPrimaryReplicas", this.numberOfPrimaryReplicas); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlAvailabilityReplicaSummary from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlAvailabilityReplicaSummary 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 SqlAvailabilityReplicaSummary. + */ + public static SqlAvailabilityReplicaSummary fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlAvailabilityReplicaSummary deserializedSqlAvailabilityReplicaSummary + = new SqlAvailabilityReplicaSummary(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("numberOfSynchronousReadReplicas".equals(fieldName)) { + deserializedSqlAvailabilityReplicaSummary.numberOfSynchronousReadReplicas + = reader.getNullable(JsonReader::getInt); + } else if ("numberOfSynchronousNonReadReplicas".equals(fieldName)) { + deserializedSqlAvailabilityReplicaSummary.numberOfSynchronousNonReadReplicas + = reader.getNullable(JsonReader::getInt); + } else if ("numberOfAsynchronousReadReplicas".equals(fieldName)) { + deserializedSqlAvailabilityReplicaSummary.numberOfAsynchronousReadReplicas + = reader.getNullable(JsonReader::getInt); + } else if ("numberOfAsynchronousNonReadReplicas".equals(fieldName)) { + deserializedSqlAvailabilityReplicaSummary.numberOfAsynchronousNonReadReplicas + = reader.getNullable(JsonReader::getInt); + } else if ("numberOfPrimaryReplicas".equals(fieldName)) { + deserializedSqlAvailabilityReplicaSummary.numberOfPrimaryReplicas + = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + + return deserializedSqlAvailabilityReplicaSummary; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlCollector.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlCollector.java new file mode 100644 index 000000000000..e3aa149ec17e --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlCollector.java @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlCollectorInner; + +/** + * An immutable client-side representation of SqlCollector. + */ +public interface SqlCollector { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + CollectorPropertiesBaseWithAgent properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.migration.assessment.fluent.models.SqlCollectorInner object. + * + * @return the inner object. + */ + SqlCollectorInner innerModel(); + + /** + * The entirety of the SqlCollector definition. + */ + interface Definition + extends DefinitionStages.Blank, DefinitionStages.WithParentResource, DefinitionStages.WithCreate { + } + + /** + * The SqlCollector definition stages. + */ + interface DefinitionStages { + /** + * The first stage of the SqlCollector definition. + */ + interface Blank extends WithParentResource { + } + + /** + * The stage of the SqlCollector definition allowing to specify parent resource. + */ + interface WithParentResource { + /** + * Specifies resourceGroupName, projectName. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @return the next definition stage. + */ + WithCreate withExistingAssessmentProject(String resourceGroupName, String projectName); + } + + /** + * The stage of the SqlCollector definition which contains all the minimum required properties for the resource + * to be created, but also allows for any other optional properties to be specified. + */ + interface WithCreate extends DefinitionStages.WithProperties { + /** + * Executes the create request. + * + * @return the created resource. + */ + SqlCollector create(); + + /** + * Executes the create request. + * + * @param context The context to associate with this operation. + * @return the created resource. + */ + SqlCollector create(Context context); + } + + /** + * The stage of the SqlCollector definition allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The resource-specific properties for this resource.. + * + * @param properties The resource-specific properties for this resource. + * @return the next definition stage. + */ + WithCreate withProperties(CollectorPropertiesBaseWithAgent properties); + } + } + + /** + * Refreshes the resource to sync with Azure. + * + * @return the refreshed resource. + */ + SqlCollector refresh(); + + /** + * Refreshes the resource to sync with Azure. + * + * @param context The context to associate with this operation. + * @return the refreshed resource. + */ + SqlCollector refresh(Context context); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlCollectorListResult.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlCollectorListResult.java new file mode 100644 index 000000000000..5cfdae16acc3 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlCollectorListResult.java @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlCollectorInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a SqlCollector list operation. + */ +@Fluent +public final class SqlCollectorListResult implements JsonSerializable { + /* + * The SqlCollector items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of SqlCollectorListResult class. + */ + public SqlCollectorListResult() { + } + + /** + * Get the value property: The SqlCollector items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Set the value property: The SqlCollector items on this page. + * + * @param value the value value to set. + * @return the SqlCollectorListResult object itself. + */ + public SqlCollectorListResult withValue(List value) { + this.value = value; + return this; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The link to the next page of items. + * + * @param nextLink the nextLink value to set. + * @return the SqlCollectorListResult object itself. + */ + public SqlCollectorListResult withNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property value in model SqlCollectorListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(SqlCollectorListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlCollectorListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlCollectorListResult 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 SqlCollectorListResult. + */ + public static SqlCollectorListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlCollectorListResult deserializedSqlCollectorListResult = new SqlCollectorListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value = reader.readArray(reader1 -> SqlCollectorInner.fromJson(reader1)); + deserializedSqlCollectorListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedSqlCollectorListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedSqlCollectorListResult; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlCollectorOperations.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlCollectorOperations.java new file mode 100644 index 000000000000..475cb46ff246 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlCollectorOperations.java @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of SqlCollectorOperations. + */ +public interface SqlCollectorOperations { + /** + * List SqlCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlCollector list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName); + + /** + * List SqlCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SqlCollector list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, Context context); + + /** + * Get a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlCollector along with {@link Response}. + */ + Response getWithResponse(String resourceGroupName, String projectName, String collectorName, + Context context); + + /** + * Get a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlCollector. + */ + SqlCollector get(String resourceGroupName, String projectName, String collectorName); + + /** + * Delete a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteWithResponse(String resourceGroupName, String projectName, String collectorName, + Context context); + + /** + * Delete a SqlCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param collectorName Sql collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void delete(String resourceGroupName, String projectName, String collectorName); + + /** + * Get a SqlCollector. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlCollector along with {@link Response}. + */ + SqlCollector getById(String id); + + /** + * Get a SqlCollector. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a SqlCollector along with {@link Response}. + */ + Response getByIdWithResponse(String id, Context context); + + /** + * Delete a SqlCollector. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteById(String id); + + /** + * Delete a SqlCollector. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteByIdWithResponse(String id, Context context); + + /** + * Begins definition for a new SqlCollector resource. + * + * @param name resource name. + * @return the first stage of the new SqlCollector definition. + */ + SqlCollector.DefinitionStages.Blank define(String name); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlDbSettings.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlDbSettings.java new file mode 100644 index 000000000000..880cfb045ba4 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlDbSettings.java @@ -0,0 +1,183 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * SQL database assessment settings. + */ +@Fluent +public final class SqlDbSettings implements JsonSerializable { + /* + * Gets or sets the azure SQL service tier. + */ + private AzureSqlServiceTier azureSqlServiceTier; + + /* + * Gets or sets the azure PAAS SQL instance type. + */ + private AzureSqlDataBaseType azureSqlDataBaseType; + + /* + * Gets or sets the azure SQL compute tier. + */ + private ComputeTier azureSqlComputeTier; + + /* + * Gets or sets the azure SQL purchase model. + */ + private AzureSqlPurchaseModel azureSqlPurchaseModel; + + /** + * Creates an instance of SqlDbSettings class. + */ + public SqlDbSettings() { + } + + /** + * Get the azureSqlServiceTier property: Gets or sets the azure SQL service tier. + * + * @return the azureSqlServiceTier value. + */ + public AzureSqlServiceTier azureSqlServiceTier() { + return this.azureSqlServiceTier; + } + + /** + * Set the azureSqlServiceTier property: Gets or sets the azure SQL service tier. + * + * @param azureSqlServiceTier the azureSqlServiceTier value to set. + * @return the SqlDbSettings object itself. + */ + public SqlDbSettings withAzureSqlServiceTier(AzureSqlServiceTier azureSqlServiceTier) { + this.azureSqlServiceTier = azureSqlServiceTier; + return this; + } + + /** + * Get the azureSqlDataBaseType property: Gets or sets the azure PAAS SQL instance type. + * + * @return the azureSqlDataBaseType value. + */ + public AzureSqlDataBaseType azureSqlDataBaseType() { + return this.azureSqlDataBaseType; + } + + /** + * Set the azureSqlDataBaseType property: Gets or sets the azure PAAS SQL instance type. + * + * @param azureSqlDataBaseType the azureSqlDataBaseType value to set. + * @return the SqlDbSettings object itself. + */ + public SqlDbSettings withAzureSqlDataBaseType(AzureSqlDataBaseType azureSqlDataBaseType) { + this.azureSqlDataBaseType = azureSqlDataBaseType; + return this; + } + + /** + * Get the azureSqlComputeTier property: Gets or sets the azure SQL compute tier. + * + * @return the azureSqlComputeTier value. + */ + public ComputeTier azureSqlComputeTier() { + return this.azureSqlComputeTier; + } + + /** + * Set the azureSqlComputeTier property: Gets or sets the azure SQL compute tier. + * + * @param azureSqlComputeTier the azureSqlComputeTier value to set. + * @return the SqlDbSettings object itself. + */ + public SqlDbSettings withAzureSqlComputeTier(ComputeTier azureSqlComputeTier) { + this.azureSqlComputeTier = azureSqlComputeTier; + return this; + } + + /** + * Get the azureSqlPurchaseModel property: Gets or sets the azure SQL purchase model. + * + * @return the azureSqlPurchaseModel value. + */ + public AzureSqlPurchaseModel azureSqlPurchaseModel() { + return this.azureSqlPurchaseModel; + } + + /** + * Set the azureSqlPurchaseModel property: Gets or sets the azure SQL purchase model. + * + * @param azureSqlPurchaseModel the azureSqlPurchaseModel value to set. + * @return the SqlDbSettings object itself. + */ + public SqlDbSettings withAzureSqlPurchaseModel(AzureSqlPurchaseModel azureSqlPurchaseModel) { + this.azureSqlPurchaseModel = azureSqlPurchaseModel; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("azureSqlServiceTier", + this.azureSqlServiceTier == null ? null : this.azureSqlServiceTier.toString()); + jsonWriter.writeStringField("azureSqlDataBaseType", + this.azureSqlDataBaseType == null ? null : this.azureSqlDataBaseType.toString()); + jsonWriter.writeStringField("azureSqlComputeTier", + this.azureSqlComputeTier == null ? null : this.azureSqlComputeTier.toString()); + jsonWriter.writeStringField("azureSqlPurchaseModel", + this.azureSqlPurchaseModel == null ? null : this.azureSqlPurchaseModel.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlDbSettings from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlDbSettings 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 SqlDbSettings. + */ + public static SqlDbSettings fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlDbSettings deserializedSqlDbSettings = new SqlDbSettings(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("azureSqlServiceTier".equals(fieldName)) { + deserializedSqlDbSettings.azureSqlServiceTier = AzureSqlServiceTier.fromString(reader.getString()); + } else if ("azureSqlDataBaseType".equals(fieldName)) { + deserializedSqlDbSettings.azureSqlDataBaseType + = AzureSqlDataBaseType.fromString(reader.getString()); + } else if ("azureSqlComputeTier".equals(fieldName)) { + deserializedSqlDbSettings.azureSqlComputeTier = ComputeTier.fromString(reader.getString()); + } else if ("azureSqlPurchaseModel".equals(fieldName)) { + deserializedSqlDbSettings.azureSqlPurchaseModel + = AzureSqlPurchaseModel.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedSqlDbSettings; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlFciMetadata.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlFciMetadata.java new file mode 100644 index 000000000000..ca669846b868 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlFciMetadata.java @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * Sql fci meta data. + */ +@Fluent +public final class SqlFciMetadata implements JsonSerializable { + /* + * Gets the Sql fci meta data state. + */ + private SqlFciMetadataState state; + + /* + * Gets whether fci is multi subnet. + */ + private Boolean isMultiSubnet; + + /* + * Gets the fci shared disk count. + */ + private Integer fciSharedDiskCount; + + /** + * Creates an instance of SqlFciMetadata class. + */ + public SqlFciMetadata() { + } + + /** + * Get the state property: Gets the Sql fci meta data state. + * + * @return the state value. + */ + public SqlFciMetadataState state() { + return this.state; + } + + /** + * Set the state property: Gets the Sql fci meta data state. + * + * @param state the state value to set. + * @return the SqlFciMetadata object itself. + */ + public SqlFciMetadata withState(SqlFciMetadataState state) { + this.state = state; + return this; + } + + /** + * Get the isMultiSubnet property: Gets whether fci is multi subnet. + * + * @return the isMultiSubnet value. + */ + public Boolean isMultiSubnet() { + return this.isMultiSubnet; + } + + /** + * Set the isMultiSubnet property: Gets whether fci is multi subnet. + * + * @param isMultiSubnet the isMultiSubnet value to set. + * @return the SqlFciMetadata object itself. + */ + public SqlFciMetadata withIsMultiSubnet(Boolean isMultiSubnet) { + this.isMultiSubnet = isMultiSubnet; + return this; + } + + /** + * Get the fciSharedDiskCount property: Gets the fci shared disk count. + * + * @return the fciSharedDiskCount value. + */ + public Integer fciSharedDiskCount() { + return this.fciSharedDiskCount; + } + + /** + * Set the fciSharedDiskCount property: Gets the fci shared disk count. + * + * @param fciSharedDiskCount the fciSharedDiskCount value to set. + * @return the SqlFciMetadata object itself. + */ + public SqlFciMetadata withFciSharedDiskCount(Integer fciSharedDiskCount) { + this.fciSharedDiskCount = fciSharedDiskCount; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("state", this.state == null ? null : this.state.toString()); + jsonWriter.writeBooleanField("isMultiSubnet", this.isMultiSubnet); + jsonWriter.writeNumberField("fciSharedDiskCount", this.fciSharedDiskCount); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlFciMetadata from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlFciMetadata 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 SqlFciMetadata. + */ + public static SqlFciMetadata fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlFciMetadata deserializedSqlFciMetadata = new SqlFciMetadata(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("state".equals(fieldName)) { + deserializedSqlFciMetadata.state = SqlFciMetadataState.fromString(reader.getString()); + } else if ("isMultiSubnet".equals(fieldName)) { + deserializedSqlFciMetadata.isMultiSubnet = reader.getNullable(JsonReader::getBoolean); + } else if ("fciSharedDiskCount".equals(fieldName)) { + deserializedSqlFciMetadata.fciSharedDiskCount = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + + return deserializedSqlFciMetadata; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlFciMetadataState.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlFciMetadataState.java new file mode 100644 index 000000000000..df85ce59a963 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlFciMetadataState.java @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for SqlFciMetadataState. + */ +public final class SqlFciMetadataState extends ExpandableStringEnum { + /** + * Static value Unknown for SqlFciMetadataState. + */ + public static final SqlFciMetadataState UNKNOWN = fromString("Unknown"); + + /** + * Static value Inherited for SqlFciMetadataState. + */ + public static final SqlFciMetadataState INHERITED = fromString("Inherited"); + + /** + * Static value Initializing for SqlFciMetadataState. + */ + public static final SqlFciMetadataState INITIALIZING = fromString("Initializing"); + + /** + * Static value Online for SqlFciMetadataState. + */ + public static final SqlFciMetadataState ONLINE = fromString("Online"); + + /** + * Static value Offline for SqlFciMetadataState. + */ + public static final SqlFciMetadataState OFFLINE = fromString("Offline"); + + /** + * Static value Failed for SqlFciMetadataState. + */ + public static final SqlFciMetadataState FAILED = fromString("Failed"); + + /** + * Static value Pending for SqlFciMetadataState. + */ + public static final SqlFciMetadataState PENDING = fromString("Pending"); + + /** + * Static value OnlinePending for SqlFciMetadataState. + */ + public static final SqlFciMetadataState ONLINE_PENDING = fromString("OnlinePending"); + + /** + * Static value OfflinePending for SqlFciMetadataState. + */ + public static final SqlFciMetadataState OFFLINE_PENDING = fromString("OfflinePending"); + + /** + * Creates a new instance of SqlFciMetadataState value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public SqlFciMetadataState() { + } + + /** + * Creates or finds a SqlFciMetadataState from its string representation. + * + * @param name a name to look for. + * @return the corresponding SqlFciMetadataState. + */ + public static SqlFciMetadataState fromString(String name) { + return fromString(name, SqlFciMetadataState.class); + } + + /** + * Gets known SqlFciMetadataState values. + * + * @return known SqlFciMetadataState values. + */ + public static Collection values() { + return values(SqlFciMetadataState.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlFciState.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlFciState.java new file mode 100644 index 000000000000..15b0bb59825a --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlFciState.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for SqlFciState. + */ +public final class SqlFciState extends ExpandableStringEnum { + /** + * Static value Unknown for SqlFciState. + */ + public static final SqlFciState UNKNOWN = fromString("Unknown"); + + /** + * Static value Active for SqlFciState. + */ + public static final SqlFciState ACTIVE = fromString("Active"); + + /** + * Static value Passive for SqlFciState. + */ + public static final SqlFciState PASSIVE = fromString("Passive"); + + /** + * Static value NotApplicable for SqlFciState. + */ + public static final SqlFciState NOT_APPLICABLE = fromString("NotApplicable"); + + /** + * Creates a new instance of SqlFciState value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public SqlFciState() { + } + + /** + * Creates or finds a SqlFciState from its string representation. + * + * @param name a name to look for. + * @return the corresponding SqlFciState. + */ + public static SqlFciState fromString(String name) { + return fromString(name, SqlFciState.class); + } + + /** + * Gets known SqlFciState values. + * + * @return known SqlFciState values. + */ + public static Collection values() { + return values(SqlFciState.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlMiSettings.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlMiSettings.java new file mode 100644 index 000000000000..6f47f1e4464a --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlMiSettings.java @@ -0,0 +1,124 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * SQL managed instance assessment settings. + */ +@Fluent +public final class SqlMiSettings implements JsonSerializable { + /* + * Gets or sets the azure SQL service tier. + */ + private AzureSqlServiceTier azureSqlServiceTier; + + /* + * Gets or sets the azure PAAS SQL instance type. + */ + private AzureSqlInstanceType azureSqlInstanceType; + + /** + * Creates an instance of SqlMiSettings class. + */ + public SqlMiSettings() { + } + + /** + * Get the azureSqlServiceTier property: Gets or sets the azure SQL service tier. + * + * @return the azureSqlServiceTier value. + */ + public AzureSqlServiceTier azureSqlServiceTier() { + return this.azureSqlServiceTier; + } + + /** + * Set the azureSqlServiceTier property: Gets or sets the azure SQL service tier. + * + * @param azureSqlServiceTier the azureSqlServiceTier value to set. + * @return the SqlMiSettings object itself. + */ + public SqlMiSettings withAzureSqlServiceTier(AzureSqlServiceTier azureSqlServiceTier) { + this.azureSqlServiceTier = azureSqlServiceTier; + return this; + } + + /** + * Get the azureSqlInstanceType property: Gets or sets the azure PAAS SQL instance type. + * + * @return the azureSqlInstanceType value. + */ + public AzureSqlInstanceType azureSqlInstanceType() { + return this.azureSqlInstanceType; + } + + /** + * Set the azureSqlInstanceType property: Gets or sets the azure PAAS SQL instance type. + * + * @param azureSqlInstanceType the azureSqlInstanceType value to set. + * @return the SqlMiSettings object itself. + */ + public SqlMiSettings withAzureSqlInstanceType(AzureSqlInstanceType azureSqlInstanceType) { + this.azureSqlInstanceType = azureSqlInstanceType; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("azureSqlServiceTier", + this.azureSqlServiceTier == null ? null : this.azureSqlServiceTier.toString()); + jsonWriter.writeStringField("azureSqlInstanceType", + this.azureSqlInstanceType == null ? null : this.azureSqlInstanceType.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlMiSettings from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlMiSettings 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 SqlMiSettings. + */ + public static SqlMiSettings fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlMiSettings deserializedSqlMiSettings = new SqlMiSettings(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("azureSqlServiceTier".equals(fieldName)) { + deserializedSqlMiSettings.azureSqlServiceTier = AzureSqlServiceTier.fromString(reader.getString()); + } else if ("azureSqlInstanceType".equals(fieldName)) { + deserializedSqlMiSettings.azureSqlInstanceType + = AzureSqlInstanceType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedSqlMiSettings; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlMigrationGuideline.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlMigrationGuideline.java new file mode 100644 index 000000000000..f0bb6e24391c --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlMigrationGuideline.java @@ -0,0 +1,146 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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.List; + +/** + * Sql Migration Guideline. + */ +@Fluent +public final class SqlMigrationGuideline implements JsonSerializable { + /* + * Gets the guideline id. + */ + private String guidelineId; + + /* + * Gets the migration guideline category. + */ + private SqlMigrationGuidelineCategory migrationGuidelineCategory; + + /* + * Gets the migration guideline context. + */ + private List migrationGuidelineContext; + + /** + * Creates an instance of SqlMigrationGuideline class. + */ + public SqlMigrationGuideline() { + } + + /** + * Get the guidelineId property: Gets the guideline id. + * + * @return the guidelineId value. + */ + public String guidelineId() { + return this.guidelineId; + } + + /** + * Set the guidelineId property: Gets the guideline id. + * + * @param guidelineId the guidelineId value to set. + * @return the SqlMigrationGuideline object itself. + */ + public SqlMigrationGuideline withGuidelineId(String guidelineId) { + this.guidelineId = guidelineId; + return this; + } + + /** + * Get the migrationGuidelineCategory property: Gets the migration guideline category. + * + * @return the migrationGuidelineCategory value. + */ + public SqlMigrationGuidelineCategory migrationGuidelineCategory() { + return this.migrationGuidelineCategory; + } + + /** + * Set the migrationGuidelineCategory property: Gets the migration guideline category. + * + * @param migrationGuidelineCategory the migrationGuidelineCategory value to set. + * @return the SqlMigrationGuideline object itself. + */ + public SqlMigrationGuideline + withMigrationGuidelineCategory(SqlMigrationGuidelineCategory migrationGuidelineCategory) { + this.migrationGuidelineCategory = migrationGuidelineCategory; + return this; + } + + /** + * Get the migrationGuidelineContext property: Gets the migration guideline context. + * + * @return the migrationGuidelineContext value. + */ + public List migrationGuidelineContext() { + return this.migrationGuidelineContext; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (migrationGuidelineContext() != null) { + migrationGuidelineContext().forEach(e -> e.validate()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("guidelineId", this.guidelineId); + jsonWriter.writeStringField("migrationGuidelineCategory", + this.migrationGuidelineCategory == null ? null : this.migrationGuidelineCategory.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlMigrationGuideline from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlMigrationGuideline 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 SqlMigrationGuideline. + */ + public static SqlMigrationGuideline fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlMigrationGuideline deserializedSqlMigrationGuideline = new SqlMigrationGuideline(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("guidelineId".equals(fieldName)) { + deserializedSqlMigrationGuideline.guidelineId = reader.getString(); + } else if ("migrationGuidelineCategory".equals(fieldName)) { + deserializedSqlMigrationGuideline.migrationGuidelineCategory + = SqlMigrationGuidelineCategory.fromString(reader.getString()); + } else if ("migrationGuidelineContext".equals(fieldName)) { + List migrationGuidelineContext + = reader.readArray(reader1 -> MigrationGuidelineContext.fromJson(reader1)); + deserializedSqlMigrationGuideline.migrationGuidelineContext = migrationGuidelineContext; + } else { + reader.skipChildren(); + } + } + + return deserializedSqlMigrationGuideline; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlMigrationGuidelineCategory.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlMigrationGuidelineCategory.java new file mode 100644 index 000000000000..cb83e88e4c93 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlMigrationGuidelineCategory.java @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for SqlMigrationGuidelineCategory. + */ +public final class SqlMigrationGuidelineCategory extends ExpandableStringEnum { + /** + * Static value Unknown for SqlMigrationGuidelineCategory. + */ + public static final SqlMigrationGuidelineCategory UNKNOWN = fromString("Unknown"); + + /** + * Static value General for SqlMigrationGuidelineCategory. + */ + public static final SqlMigrationGuidelineCategory GENERAL = fromString("General"); + + /** + * Static value FailoverCluterInstanceGuideLine for SqlMigrationGuidelineCategory. + */ + public static final SqlMigrationGuidelineCategory FAILOVER_CLUTER_INSTANCE_GUIDE_LINE + = fromString("FailoverCluterInstanceGuideLine"); + + /** + * Static value AvailabilityGroupGuideline for SqlMigrationGuidelineCategory. + */ + public static final SqlMigrationGuidelineCategory AVAILABILITY_GROUP_GUIDELINE + = fromString("AvailabilityGroupGuideline"); + + /** + * Creates a new instance of SqlMigrationGuidelineCategory value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public SqlMigrationGuidelineCategory() { + } + + /** + * Creates or finds a SqlMigrationGuidelineCategory from its string representation. + * + * @param name a name to look for. + * @return the corresponding SqlMigrationGuidelineCategory. + */ + public static SqlMigrationGuidelineCategory fromString(String name) { + return fromString(name, SqlMigrationGuidelineCategory.class); + } + + /** + * Gets known SqlMigrationGuidelineCategory values. + * + * @return known SqlMigrationGuidelineCategory values. + */ + public static Collection values() { + return values(SqlMigrationGuidelineCategory.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlPaaSTargetOptions.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlPaaSTargetOptions.java new file mode 100644 index 000000000000..92d6ffb5b067 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlPaaSTargetOptions.java @@ -0,0 +1,211 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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.List; + +/** + * SQL target options. + */ +@Fluent +public final class SqlPaaSTargetOptions implements JsonSerializable { + /* + * Gets or sets the Azure SQL compute tier. + */ + private ComputeTier computeTier; + + /* + * Gets or sets the Azure SQL hardware generation. + */ + private HardwareGeneration hardwareGeneration; + + /* + * Gets or sets the Azure SQL target type. + */ + private TargetType targetType; + + /* + * Gets or sets the Azure SQL service tier. + */ + private AzureSqlServiceTier serviceTier; + + /* + * Gets or sets the target location. + */ + private List targetLocations; + + /** + * Creates an instance of SqlPaaSTargetOptions class. + */ + public SqlPaaSTargetOptions() { + } + + /** + * Get the computeTier property: Gets or sets the Azure SQL compute tier. + * + * @return the computeTier value. + */ + public ComputeTier computeTier() { + return this.computeTier; + } + + /** + * Set the computeTier property: Gets or sets the Azure SQL compute tier. + * + * @param computeTier the computeTier value to set. + * @return the SqlPaaSTargetOptions object itself. + */ + public SqlPaaSTargetOptions withComputeTier(ComputeTier computeTier) { + this.computeTier = computeTier; + return this; + } + + /** + * Get the hardwareGeneration property: Gets or sets the Azure SQL hardware generation. + * + * @return the hardwareGeneration value. + */ + public HardwareGeneration hardwareGeneration() { + return this.hardwareGeneration; + } + + /** + * Set the hardwareGeneration property: Gets or sets the Azure SQL hardware generation. + * + * @param hardwareGeneration the hardwareGeneration value to set. + * @return the SqlPaaSTargetOptions object itself. + */ + public SqlPaaSTargetOptions withHardwareGeneration(HardwareGeneration hardwareGeneration) { + this.hardwareGeneration = hardwareGeneration; + return this; + } + + /** + * Get the targetType property: Gets or sets the Azure SQL target type. + * + * @return the targetType value. + */ + public TargetType targetType() { + return this.targetType; + } + + /** + * Set the targetType property: Gets or sets the Azure SQL target type. + * + * @param targetType the targetType value to set. + * @return the SqlPaaSTargetOptions object itself. + */ + public SqlPaaSTargetOptions withTargetType(TargetType targetType) { + this.targetType = targetType; + return this; + } + + /** + * Get the serviceTier property: Gets or sets the Azure SQL service tier. + * + * @return the serviceTier value. + */ + public AzureSqlServiceTier serviceTier() { + return this.serviceTier; + } + + /** + * Set the serviceTier property: Gets or sets the Azure SQL service tier. + * + * @param serviceTier the serviceTier value to set. + * @return the SqlPaaSTargetOptions object itself. + */ + public SqlPaaSTargetOptions withServiceTier(AzureSqlServiceTier serviceTier) { + this.serviceTier = serviceTier; + return this; + } + + /** + * Get the targetLocations property: Gets or sets the target location. + * + * @return the targetLocations value. + */ + public List targetLocations() { + return this.targetLocations; + } + + /** + * Set the targetLocations property: Gets or sets the target location. + * + * @param targetLocations the targetLocations value to set. + * @return the SqlPaaSTargetOptions object itself. + */ + public SqlPaaSTargetOptions withTargetLocations(List targetLocations) { + this.targetLocations = targetLocations; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("computeTier", this.computeTier == null ? null : this.computeTier.toString()); + jsonWriter.writeStringField("hardwareGeneration", + this.hardwareGeneration == null ? null : this.hardwareGeneration.toString()); + jsonWriter.writeStringField("targetType", this.targetType == null ? null : this.targetType.toString()); + jsonWriter.writeStringField("serviceTier", this.serviceTier == null ? null : this.serviceTier.toString()); + jsonWriter.writeArrayField("targetLocations", this.targetLocations, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlPaaSTargetOptions from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlPaaSTargetOptions 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 SqlPaaSTargetOptions. + */ + public static SqlPaaSTargetOptions fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlPaaSTargetOptions deserializedSqlPaaSTargetOptions = new SqlPaaSTargetOptions(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("computeTier".equals(fieldName)) { + deserializedSqlPaaSTargetOptions.computeTier = ComputeTier.fromString(reader.getString()); + } else if ("hardwareGeneration".equals(fieldName)) { + deserializedSqlPaaSTargetOptions.hardwareGeneration + = HardwareGeneration.fromString(reader.getString()); + } else if ("targetType".equals(fieldName)) { + deserializedSqlPaaSTargetOptions.targetType = TargetType.fromString(reader.getString()); + } else if ("serviceTier".equals(fieldName)) { + deserializedSqlPaaSTargetOptions.serviceTier = AzureSqlServiceTier.fromString(reader.getString()); + } else if ("targetLocations".equals(fieldName)) { + List targetLocations + = reader.readArray(reader1 -> AzureLocation.fromString(reader1.getString())); + deserializedSqlPaaSTargetOptions.targetLocations = targetLocations; + } else { + reader.skipChildren(); + } + } + + return deserializedSqlPaaSTargetOptions; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlRecommendationReasoning.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlRecommendationReasoning.java new file mode 100644 index 000000000000..53464be65cc6 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlRecommendationReasoning.java @@ -0,0 +1,171 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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.List; + +/** + * Class representing Azure SQL Recommendation Reasoning. + */ +@Fluent +public final class SqlRecommendationReasoning implements JsonSerializable { + /* + * Gets the reasoning id. + */ + private String reasoningId; + + /* + * Gets the reasoning status. + */ + private String reasoningString; + + /* + * Gets the reasoning category. + */ + private String reasoningCategory; + + /* + * Gets the Sql recommended reasoning parameters. + */ + private List contextParameters; + + /** + * Creates an instance of SqlRecommendationReasoning class. + */ + public SqlRecommendationReasoning() { + } + + /** + * Get the reasoningId property: Gets the reasoning id. + * + * @return the reasoningId value. + */ + public String reasoningId() { + return this.reasoningId; + } + + /** + * Set the reasoningId property: Gets the reasoning id. + * + * @param reasoningId the reasoningId value to set. + * @return the SqlRecommendationReasoning object itself. + */ + public SqlRecommendationReasoning withReasoningId(String reasoningId) { + this.reasoningId = reasoningId; + return this; + } + + /** + * Get the reasoningString property: Gets the reasoning status. + * + * @return the reasoningString value. + */ + public String reasoningString() { + return this.reasoningString; + } + + /** + * Set the reasoningString property: Gets the reasoning status. + * + * @param reasoningString the reasoningString value to set. + * @return the SqlRecommendationReasoning object itself. + */ + public SqlRecommendationReasoning withReasoningString(String reasoningString) { + this.reasoningString = reasoningString; + return this; + } + + /** + * Get the reasoningCategory property: Gets the reasoning category. + * + * @return the reasoningCategory value. + */ + public String reasoningCategory() { + return this.reasoningCategory; + } + + /** + * Set the reasoningCategory property: Gets the reasoning category. + * + * @param reasoningCategory the reasoningCategory value to set. + * @return the SqlRecommendationReasoning object itself. + */ + public SqlRecommendationReasoning withReasoningCategory(String reasoningCategory) { + this.reasoningCategory = reasoningCategory; + return this; + } + + /** + * Get the contextParameters property: Gets the Sql recommended reasoning parameters. + * + * @return the contextParameters value. + */ + public List contextParameters() { + return this.contextParameters; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (contextParameters() != null) { + contextParameters().forEach(e -> e.validate()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("reasoningId", this.reasoningId); + jsonWriter.writeStringField("reasoningString", this.reasoningString); + jsonWriter.writeStringField("reasoningCategory", this.reasoningCategory); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlRecommendationReasoning from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlRecommendationReasoning 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 SqlRecommendationReasoning. + */ + public static SqlRecommendationReasoning fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlRecommendationReasoning deserializedSqlRecommendationReasoning = new SqlRecommendationReasoning(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("reasoningId".equals(fieldName)) { + deserializedSqlRecommendationReasoning.reasoningId = reader.getString(); + } else if ("reasoningString".equals(fieldName)) { + deserializedSqlRecommendationReasoning.reasoningString = reader.getString(); + } else if ("reasoningCategory".equals(fieldName)) { + deserializedSqlRecommendationReasoning.reasoningCategory = reader.getString(); + } else if ("contextParameters".equals(fieldName)) { + List contextParameters + = reader.readArray(reader1 -> SqlRecommendationReasoningContext.fromJson(reader1)); + deserializedSqlRecommendationReasoning.contextParameters = contextParameters; + } else { + reader.skipChildren(); + } + } + + return deserializedSqlRecommendationReasoning; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlRecommendationReasoningContext.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlRecommendationReasoningContext.java new file mode 100644 index 000000000000..18bab5696b83 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlRecommendationReasoningContext.java @@ -0,0 +1,122 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * Class representing Azure SQL Recommendation Reasoning Context. + */ +@Fluent +public final class SqlRecommendationReasoningContext implements JsonSerializable { + /* + * Gets the reasoning context key. + */ + private String contextKey; + + /* + * Gets the reasoning context value. + */ + private String contextValue; + + /** + * Creates an instance of SqlRecommendationReasoningContext class. + */ + public SqlRecommendationReasoningContext() { + } + + /** + * Get the contextKey property: Gets the reasoning context key. + * + * @return the contextKey value. + */ + public String contextKey() { + return this.contextKey; + } + + /** + * Set the contextKey property: Gets the reasoning context key. + * + * @param contextKey the contextKey value to set. + * @return the SqlRecommendationReasoningContext object itself. + */ + public SqlRecommendationReasoningContext withContextKey(String contextKey) { + this.contextKey = contextKey; + return this; + } + + /** + * Get the contextValue property: Gets the reasoning context value. + * + * @return the contextValue value. + */ + public String contextValue() { + return this.contextValue; + } + + /** + * Set the contextValue property: Gets the reasoning context value. + * + * @param contextValue the contextValue value to set. + * @return the SqlRecommendationReasoningContext object itself. + */ + public SqlRecommendationReasoningContext withContextValue(String contextValue) { + this.contextValue = contextValue; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("contextKey", this.contextKey); + jsonWriter.writeStringField("contextValue", this.contextValue); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlRecommendationReasoningContext from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlRecommendationReasoningContext 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 SqlRecommendationReasoningContext. + */ + public static SqlRecommendationReasoningContext fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlRecommendationReasoningContext deserializedSqlRecommendationReasoningContext + = new SqlRecommendationReasoningContext(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("contextKey".equals(fieldName)) { + deserializedSqlRecommendationReasoningContext.contextKey = reader.getString(); + } else if ("contextValue".equals(fieldName)) { + deserializedSqlRecommendationReasoningContext.contextValue = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedSqlRecommendationReasoningContext; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlServerLicense.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlServerLicense.java new file mode 100644 index 000000000000..013dca5143dd --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlServerLicense.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. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for SqlServerLicense. + */ +public final class SqlServerLicense extends ExpandableStringEnum { + /** + * Static value Unknown for SqlServerLicense. + */ + public static final SqlServerLicense UNKNOWN = fromString("Unknown"); + + /** + * Static value Yes for SqlServerLicense. + */ + public static final SqlServerLicense YES = fromString("Yes"); + + /** + * Static value No for SqlServerLicense. + */ + public static final SqlServerLicense NO = fromString("No"); + + /** + * Creates a new instance of SqlServerLicense value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public SqlServerLicense() { + } + + /** + * Creates or finds a SqlServerLicense from its string representation. + * + * @param name a name to look for. + * @return the corresponding SqlServerLicense. + */ + public static SqlServerLicense fromString(String name) { + return fromString(name, SqlServerLicense.class); + } + + /** + * Gets known SqlServerLicense values. + * + * @return known SqlServerLicense values. + */ + public static Collection values() { + return values(SqlServerLicense.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlVmSettings.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlVmSettings.java new file mode 100644 index 000000000000..411e7fb2afdb --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/SqlVmSettings.java @@ -0,0 +1,100 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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.List; + +/** + * SQL VM assessment settings. + */ +@Fluent +public final class SqlVmSettings implements JsonSerializable { + /* + * Gets or sets the Azure VM families (calling instance series to keep it + * consistent with other targets). + */ + private List instanceSeries; + + /** + * Creates an instance of SqlVmSettings class. + */ + public SqlVmSettings() { + } + + /** + * Get the instanceSeries property: Gets or sets the Azure VM families (calling instance series to keep it + * consistent with other targets). + * + * @return the instanceSeries value. + */ + public List instanceSeries() { + return this.instanceSeries; + } + + /** + * Set the instanceSeries property: Gets or sets the Azure VM families (calling instance series to keep it + * consistent with other targets). + * + * @param instanceSeries the instanceSeries value to set. + * @return the SqlVmSettings object itself. + */ + public SqlVmSettings withInstanceSeries(List instanceSeries) { + this.instanceSeries = instanceSeries; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("instanceSeries", this.instanceSeries, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlVmSettings from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlVmSettings 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 SqlVmSettings. + */ + public static SqlVmSettings fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlVmSettings deserializedSqlVmSettings = new SqlVmSettings(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("instanceSeries".equals(fieldName)) { + List instanceSeries + = reader.readArray(reader1 -> AzureVmFamily.fromString(reader1.getString())); + deserializedSqlVmSettings.instanceSeries = instanceSeries; + } else { + reader.skipChildren(); + } + } + + return deserializedSqlVmSettings; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/TargetType.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/TargetType.java new file mode 100644 index 000000000000..2ce49e07e271 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/TargetType.java @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for TargetType. + */ +public final class TargetType extends ExpandableStringEnum { + /** + * Static value Unknown for TargetType. + */ + public static final TargetType UNKNOWN = fromString("Unknown"); + + /** + * Static value Recommended for TargetType. + */ + public static final TargetType RECOMMENDED = fromString("Recommended"); + + /** + * Static value AzureSqlDatabase for TargetType. + */ + public static final TargetType AZURE_SQL_DATABASE = fromString("AzureSqlDatabase"); + + /** + * Static value AzureSqlManagedInstance for TargetType. + */ + public static final TargetType AZURE_SQL_MANAGED_INSTANCE = fromString("AzureSqlManagedInstance"); + + /** + * Static value AzureSqlVirtualMachine for TargetType. + */ + public static final TargetType AZURE_SQL_VIRTUAL_MACHINE = fromString("AzureSqlVirtualMachine"); + + /** + * Static value AzureVirtualMachine for TargetType. + */ + public static final TargetType AZURE_VIRTUAL_MACHINE = fromString("AzureVirtualMachine"); + + /** + * Creates a new instance of TargetType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public TargetType() { + } + + /** + * Creates or finds a TargetType from its string representation. + * + * @param name a name to look for. + * @return the corresponding TargetType. + */ + public static TargetType fromString(String name) { + return fromString(name, TargetType.class); + } + + /** + * Gets known TargetType values. + * + * @return known TargetType values. + */ + public static Collection values() { + return values(TargetType.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/TimeRange.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/TimeRange.java new file mode 100644 index 000000000000..92be582b80a0 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/TimeRange.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for TimeRange. + */ +public final class TimeRange extends ExpandableStringEnum { + /** + * Static value Day for TimeRange. + */ + public static final TimeRange DAY = fromString("Day"); + + /** + * Static value Week for TimeRange. + */ + public static final TimeRange WEEK = fromString("Week"); + + /** + * Static value Month for TimeRange. + */ + public static final TimeRange MONTH = fromString("Month"); + + /** + * Static value Custom for TimeRange. + */ + public static final TimeRange CUSTOM = fromString("Custom"); + + /** + * Creates a new instance of TimeRange value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public TimeRange() { + } + + /** + * Creates or finds a TimeRange from its string representation. + * + * @param name a name to look for. + * @return the corresponding TimeRange. + */ + public static TimeRange fromString(String name) { + return fromString(name, TimeRange.class); + } + + /** + * Gets known TimeRange values. + * + * @return known TimeRange values. + */ + public static Collection values() { + return values(TimeRange.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/UltraDiskAssessmentOptions.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/UltraDiskAssessmentOptions.java new file mode 100644 index 000000000000..587443557fd3 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/UltraDiskAssessmentOptions.java @@ -0,0 +1,124 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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.List; + +/** + * Assessment options for Ultra disk type. + */ +@Fluent +public final class UltraDiskAssessmentOptions implements JsonSerializable { + /* + * Family name. + */ + private String familyName; + + /* + * List of locations where ultra disk is supported for this VMfamily. + */ + private List targetLocations; + + /** + * Creates an instance of UltraDiskAssessmentOptions class. + */ + public UltraDiskAssessmentOptions() { + } + + /** + * Get the familyName property: Family name. + * + * @return the familyName value. + */ + public String familyName() { + return this.familyName; + } + + /** + * Set the familyName property: Family name. + * + * @param familyName the familyName value to set. + * @return the UltraDiskAssessmentOptions object itself. + */ + public UltraDiskAssessmentOptions withFamilyName(String familyName) { + this.familyName = familyName; + return this; + } + + /** + * Get the targetLocations property: List of locations where ultra disk is supported for this VMfamily. + * + * @return the targetLocations value. + */ + public List targetLocations() { + return this.targetLocations; + } + + /** + * Set the targetLocations property: List of locations where ultra disk is supported for this VMfamily. + * + * @param targetLocations the targetLocations value to set. + * @return the UltraDiskAssessmentOptions object itself. + */ + public UltraDiskAssessmentOptions withTargetLocations(List targetLocations) { + this.targetLocations = targetLocations; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("familyName", this.familyName); + jsonWriter.writeArrayField("targetLocations", this.targetLocations, + (writer, element) -> writer.writeString(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of UltraDiskAssessmentOptions from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of UltraDiskAssessmentOptions 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 UltraDiskAssessmentOptions. + */ + public static UltraDiskAssessmentOptions fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + UltraDiskAssessmentOptions deserializedUltraDiskAssessmentOptions = new UltraDiskAssessmentOptions(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("familyName".equals(fieldName)) { + deserializedUltraDiskAssessmentOptions.familyName = reader.getString(); + } else if ("targetLocations".equals(fieldName)) { + List targetLocations = reader.readArray(reader1 -> reader1.getString()); + deserializedUltraDiskAssessmentOptions.targetLocations = targetLocations; + } else { + reader.skipChildren(); + } + } + + return deserializedUltraDiskAssessmentOptions; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/UpdateGroupBody.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/UpdateGroupBody.java new file mode 100644 index 000000000000..83f8027ee956 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/UpdateGroupBody.java @@ -0,0 +1,124 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * Properties of group update. + */ +@Fluent +public final class UpdateGroupBody implements JsonSerializable { + /* + * For optimistic concurrency control. + */ + private String etag; + + /* + * Properties of the group. + */ + private GroupBodyProperties properties; + + /** + * Creates an instance of UpdateGroupBody class. + */ + public UpdateGroupBody() { + } + + /** + * Get the etag property: For optimistic concurrency control. + * + * @return the etag value. + */ + public String etag() { + return this.etag; + } + + /** + * Set the etag property: For optimistic concurrency control. + * + * @param etag the etag value to set. + * @return the UpdateGroupBody object itself. + */ + public UpdateGroupBody withEtag(String etag) { + this.etag = etag; + return this; + } + + /** + * Get the properties property: Properties of the group. + * + * @return the properties value. + */ + public GroupBodyProperties properties() { + return this.properties; + } + + /** + * Set the properties property: Properties of the group. + * + * @param properties the properties value to set. + * @return the UpdateGroupBody object itself. + */ + public UpdateGroupBody withProperties(GroupBodyProperties properties) { + this.properties = properties; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("eTag", this.etag); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of UpdateGroupBody from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of UpdateGroupBody 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 UpdateGroupBody. + */ + public static UpdateGroupBody fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + UpdateGroupBody deserializedUpdateGroupBody = new UpdateGroupBody(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("eTag".equals(fieldName)) { + deserializedUpdateGroupBody.etag = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedUpdateGroupBody.properties = GroupBodyProperties.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedUpdateGroupBody; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/VmFamilyOptions.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/VmFamilyOptions.java new file mode 100644 index 000000000000..669fcdde8739 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/VmFamilyOptions.java @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; +import java.util.List; + +/** + * VM family name, the list of targeted azure locations and the category of the + * family. + */ +@Immutable +public final class VmFamilyOptions implements JsonSerializable { + /* + * Name of the VM family. + */ + private String familyName; + + /* + * List of Azure regions. + */ + private List targetLocations; + + /* + * Category of the VM family. + */ + private List category; + + /** + * Creates an instance of VmFamilyOptions class. + */ + public VmFamilyOptions() { + } + + /** + * Get the familyName property: Name of the VM family. + * + * @return the familyName value. + */ + public String familyName() { + return this.familyName; + } + + /** + * Get the targetLocations property: List of Azure regions. + * + * @return the targetLocations value. + */ + public List targetLocations() { + return this.targetLocations; + } + + /** + * Get the category property: Category of the VM family. + * + * @return the category value. + */ + public List category() { + return this.category; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of VmFamilyOptions from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of VmFamilyOptions 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 VmFamilyOptions. + */ + public static VmFamilyOptions fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + VmFamilyOptions deserializedVmFamilyOptions = new VmFamilyOptions(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("familyName".equals(fieldName)) { + deserializedVmFamilyOptions.familyName = reader.getString(); + } else if ("targetLocations".equals(fieldName)) { + List targetLocations = reader.readArray(reader1 -> reader1.getString()); + deserializedVmFamilyOptions.targetLocations = targetLocations; + } else if ("category".equals(fieldName)) { + List category = reader.readArray(reader1 -> reader1.getString()); + deserializedVmFamilyOptions.category = category; + } else { + reader.skipChildren(); + } + } + + return deserializedVmFamilyOptions; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/VmUptime.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/VmUptime.java new file mode 100644 index 000000000000..61bf356fd402 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/VmUptime.java @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * Details on the total up-time for the VM. + */ +@Fluent +public final class VmUptime implements JsonSerializable { + /* + * Number of days in a month for VM uptime. + */ + private Integer daysPerMonth; + + /* + * Number of hours per day for VM uptime. + */ + private Integer hoursPerDay; + + /** + * Creates an instance of VmUptime class. + */ + public VmUptime() { + } + + /** + * Get the daysPerMonth property: Number of days in a month for VM uptime. + * + * @return the daysPerMonth value. + */ + public Integer daysPerMonth() { + return this.daysPerMonth; + } + + /** + * Set the daysPerMonth property: Number of days in a month for VM uptime. + * + * @param daysPerMonth the daysPerMonth value to set. + * @return the VmUptime object itself. + */ + public VmUptime withDaysPerMonth(Integer daysPerMonth) { + this.daysPerMonth = daysPerMonth; + return this; + } + + /** + * Get the hoursPerDay property: Number of hours per day for VM uptime. + * + * @return the hoursPerDay value. + */ + public Integer hoursPerDay() { + return this.hoursPerDay; + } + + /** + * Set the hoursPerDay property: Number of hours per day for VM uptime. + * + * @param hoursPerDay the hoursPerDay value to set. + * @return the VmUptime object itself. + */ + public VmUptime withHoursPerDay(Integer hoursPerDay) { + this.hoursPerDay = hoursPerDay; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeNumberField("daysPerMonth", this.daysPerMonth); + jsonWriter.writeNumberField("hoursPerDay", this.hoursPerDay); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of VmUptime from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of VmUptime 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 VmUptime. + */ + public static VmUptime fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + VmUptime deserializedVmUptime = new VmUptime(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("daysPerMonth".equals(fieldName)) { + deserializedVmUptime.daysPerMonth = reader.getNullable(JsonReader::getInt); + } else if ("hoursPerDay".equals(fieldName)) { + deserializedVmUptime.hoursPerDay = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + + return deserializedVmUptime; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/VmwareCollector.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/VmwareCollector.java new file mode 100644 index 000000000000..dcb6eb283e7c --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/VmwareCollector.java @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.migration.assessment.fluent.models.VmwareCollectorInner; + +/** + * An immutable client-side representation of VmwareCollector. + */ +public interface VmwareCollector { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + CollectorPropertiesBaseWithAgent properties(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the inner com.azure.resourcemanager.migration.assessment.fluent.models.VmwareCollectorInner object. + * + * @return the inner object. + */ + VmwareCollectorInner innerModel(); + + /** + * The entirety of the VmwareCollector definition. + */ + interface Definition + extends DefinitionStages.Blank, DefinitionStages.WithParentResource, DefinitionStages.WithCreate { + } + + /** + * The VmwareCollector definition stages. + */ + interface DefinitionStages { + /** + * The first stage of the VmwareCollector definition. + */ + interface Blank extends WithParentResource { + } + + /** + * The stage of the VmwareCollector definition allowing to specify parent resource. + */ + interface WithParentResource { + /** + * Specifies resourceGroupName, projectName. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @return the next definition stage. + */ + WithCreate withExistingAssessmentProject(String resourceGroupName, String projectName); + } + + /** + * The stage of the VmwareCollector definition which contains all the minimum required properties for the + * resource to be created, but also allows for any other optional properties to be specified. + */ + interface WithCreate extends DefinitionStages.WithProperties { + /** + * Executes the create request. + * + * @return the created resource. + */ + VmwareCollector create(); + + /** + * Executes the create request. + * + * @param context The context to associate with this operation. + * @return the created resource. + */ + VmwareCollector create(Context context); + } + + /** + * The stage of the VmwareCollector definition allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The resource-specific properties for this resource.. + * + * @param properties The resource-specific properties for this resource. + * @return the next definition stage. + */ + WithCreate withProperties(CollectorPropertiesBaseWithAgent properties); + } + } + + /** + * Refreshes the resource to sync with Azure. + * + * @return the refreshed resource. + */ + VmwareCollector refresh(); + + /** + * Refreshes the resource to sync with Azure. + * + * @param context The context to associate with this operation. + * @return the refreshed resource. + */ + VmwareCollector refresh(Context context); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/VmwareCollectorListResult.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/VmwareCollectorListResult.java new file mode 100644 index 000000000000..d8afb4f06d26 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/VmwareCollectorListResult.java @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.migration.assessment.fluent.models.VmwareCollectorInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a VmwareCollector list operation. + */ +@Fluent +public final class VmwareCollectorListResult implements JsonSerializable { + /* + * The VmwareCollector items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of VmwareCollectorListResult class. + */ + public VmwareCollectorListResult() { + } + + /** + * Get the value property: The VmwareCollector items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Set the value property: The VmwareCollector items on this page. + * + * @param value the value value to set. + * @return the VmwareCollectorListResult object itself. + */ + public VmwareCollectorListResult withValue(List value) { + this.value = value; + return this; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The link to the next page of items. + * + * @param nextLink the nextLink value to set. + * @return the VmwareCollectorListResult object itself. + */ + public VmwareCollectorListResult withNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log( + new IllegalArgumentException("Missing required property value in model VmwareCollectorListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(VmwareCollectorListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of VmwareCollectorListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of VmwareCollectorListResult 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 VmwareCollectorListResult. + */ + public static VmwareCollectorListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + VmwareCollectorListResult deserializedVmwareCollectorListResult = new VmwareCollectorListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> VmwareCollectorInner.fromJson(reader1)); + deserializedVmwareCollectorListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedVmwareCollectorListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedVmwareCollectorListResult; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/VmwareCollectorsOperations.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/VmwareCollectorsOperations.java new file mode 100644 index 000000000000..1452f2c3f131 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/VmwareCollectorsOperations.java @@ -0,0 +1,148 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of VmwareCollectorsOperations. + */ +public interface VmwareCollectorsOperations { + /** + * List VmwareCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a VmwareCollector list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName); + + /** + * List VmwareCollector resources by AssessmentProject. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a VmwareCollector list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByAssessmentProject(String resourceGroupName, String projectName, + Context context); + + /** + * Get a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a VmwareCollector along with {@link Response}. + */ + Response getWithResponse(String resourceGroupName, String projectName, String vmWareCollectorName, + Context context); + + /** + * Get a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a VmwareCollector. + */ + VmwareCollector get(String resourceGroupName, String projectName, String vmWareCollectorName); + + /** + * Delete a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteWithResponse(String resourceGroupName, String projectName, String vmWareCollectorName, + Context context); + + /** + * Delete a VmwareCollector. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param projectName Assessment Project Name. + * @param vmWareCollectorName VMware collector ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void delete(String resourceGroupName, String projectName, String vmWareCollectorName); + + /** + * Get a VmwareCollector. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a VmwareCollector along with {@link Response}. + */ + VmwareCollector getById(String id); + + /** + * Get a VmwareCollector. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a VmwareCollector along with {@link Response}. + */ + Response getByIdWithResponse(String id, Context context); + + /** + * Delete a VmwareCollector. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteById(String id); + + /** + * Delete a VmwareCollector. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteByIdWithResponse(String id, Context context); + + /** + * Begins definition for a new VmwareCollector resource. + * + * @param name resource name. + * @return the first stage of the new VmwareCollector definition. + */ + VmwareCollector.DefinitionStages.Blank define(String name); +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/WorkloadSummary.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/WorkloadSummary.java new file mode 100644 index 000000000000..62d1d1ab0e07 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/WorkloadSummary.java @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.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; + +/** + * Workload summary. + */ +@Fluent +public final class WorkloadSummary implements JsonSerializable { + /* + * Gets or sets oracle databases. + */ + private Integer oracleInstances; + + /* + * Gets or sets oracle databases. + */ + private Integer springApps; + + /** + * Creates an instance of WorkloadSummary class. + */ + public WorkloadSummary() { + } + + /** + * Get the oracleInstances property: Gets or sets oracle databases. + * + * @return the oracleInstances value. + */ + public Integer oracleInstances() { + return this.oracleInstances; + } + + /** + * Set the oracleInstances property: Gets or sets oracle databases. + * + * @param oracleInstances the oracleInstances value to set. + * @return the WorkloadSummary object itself. + */ + public WorkloadSummary withOracleInstances(Integer oracleInstances) { + this.oracleInstances = oracleInstances; + return this; + } + + /** + * Get the springApps property: Gets or sets oracle databases. + * + * @return the springApps value. + */ + public Integer springApps() { + return this.springApps; + } + + /** + * Set the springApps property: Gets or sets oracle databases. + * + * @param springApps the springApps value to set. + * @return the WorkloadSummary object itself. + */ + public WorkloadSummary withSpringApps(Integer springApps) { + this.springApps = springApps; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeNumberField("oracleInstances", this.oracleInstances); + jsonWriter.writeNumberField("springApps", this.springApps); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of WorkloadSummary from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of WorkloadSummary 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 WorkloadSummary. + */ + public static WorkloadSummary fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + WorkloadSummary deserializedWorkloadSummary = new WorkloadSummary(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("oracleInstances".equals(fieldName)) { + deserializedWorkloadSummary.oracleInstances = reader.getNullable(JsonReader::getInt); + } else if ("springApps".equals(fieldName)) { + deserializedWorkloadSummary.springApps = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + + return deserializedWorkloadSummary; + }); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/package-info.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/package-info.java new file mode 100644 index 000000000000..ff7b3ee53742 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/models/package-info.java @@ -0,0 +1,9 @@ +// 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 MigrationAssessmentManagementClient. + * Azure Migrate Resource Provider management API. + */ +package com.azure.resourcemanager.migration.assessment.models; diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/package-info.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/package-info.java new file mode 100644 index 000000000000..86585f11daf8 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/com/azure/resourcemanager/migration/assessment/package-info.java @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +/** + * Package containing the classes for MigrationAssessmentManagementClient. + * Azure Migrate Resource Provider management API. + */ +package com.azure.resourcemanager.migration.assessment; diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/module-info.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/module-info.java new file mode 100644 index 000000000000..ad2ec5f94e21 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/java/module-info.java @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +module com.azure.resourcemanager.migration.assessment { + requires transitive com.azure.core.management; + + exports com.azure.resourcemanager.migration.assessment; + exports com.azure.resourcemanager.migration.assessment.fluent; + exports com.azure.resourcemanager.migration.assessment.fluent.models; + exports com.azure.resourcemanager.migration.assessment.models; + + opens com.azure.resourcemanager.migration.assessment.fluent.models to com.azure.core; + opens com.azure.resourcemanager.migration.assessment.models to com.azure.core; +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-migration-assessment/proxy-config.json b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-migration-assessment/proxy-config.json new file mode 100644 index 000000000000..abc36389852e --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-migration-assessment/proxy-config.json @@ -0,0 +1 @@ +[["com.azure.resourcemanager.migration.assessment.implementation.AssessedMachinesOperationsClientImpl$AssessedMachinesOperationsService"],["com.azure.resourcemanager.migration.assessment.implementation.AssessedSqlDatabaseV2OperationsClientImpl$AssessedSqlDatabaseV2OperationsService"],["com.azure.resourcemanager.migration.assessment.implementation.AssessedSqlInstanceV2OperationsClientImpl$AssessedSqlInstanceV2OperationsService"],["com.azure.resourcemanager.migration.assessment.implementation.AssessedSqlMachinesOperationsClientImpl$AssessedSqlMachinesOperationsService"],["com.azure.resourcemanager.migration.assessment.implementation.AssessedSqlRecommendedEntityOperationsClientImpl$AssessedSqlRecommendedEntityOperationsService"],["com.azure.resourcemanager.migration.assessment.implementation.AssessmentOptionsOperationsClientImpl$AssessmentOptionsOperationsService"],["com.azure.resourcemanager.migration.assessment.implementation.AssessmentProjectSummaryOperationsClientImpl$AssessmentProjectSummaryOperationsService"],["com.azure.resourcemanager.migration.assessment.implementation.AssessmentProjectsOperationsClientImpl$AssessmentProjectsOperationsService"],["com.azure.resourcemanager.migration.assessment.implementation.AssessmentsOperationsClientImpl$AssessmentsOperationsService"],["com.azure.resourcemanager.migration.assessment.implementation.AvsAssessedMachinesOperationsClientImpl$AvsAssessedMachinesOperationsService"],["com.azure.resourcemanager.migration.assessment.implementation.AvsAssessmentOptionsOperationsClientImpl$AvsAssessmentOptionsOperationsService"],["com.azure.resourcemanager.migration.assessment.implementation.AvsAssessmentsOperationsClientImpl$AvsAssessmentsOperationsService"],["com.azure.resourcemanager.migration.assessment.implementation.GroupsOperationsClientImpl$GroupsOperationsService"],["com.azure.resourcemanager.migration.assessment.implementation.HypervCollectorsOperationsClientImpl$HypervCollectorsOperationsService"],["com.azure.resourcemanager.migration.assessment.implementation.ImportCollectorsOperationsClientImpl$ImportCollectorsOperationsService"],["com.azure.resourcemanager.migration.assessment.implementation.MachinesOperationsClientImpl$MachinesOperationsService"],["com.azure.resourcemanager.migration.assessment.implementation.OperationsClientImpl$OperationsService"],["com.azure.resourcemanager.migration.assessment.implementation.PrivateEndpointConnectionOperationsClientImpl$PrivateEndpointConnectionOperationsService"],["com.azure.resourcemanager.migration.assessment.implementation.PrivateLinkResourceOperationsClientImpl$PrivateLinkResourceOperationsService"],["com.azure.resourcemanager.migration.assessment.implementation.ServerCollectorsOperationsClientImpl$ServerCollectorsOperationsService"],["com.azure.resourcemanager.migration.assessment.implementation.SqlAssessmentOptionsOperationsClientImpl$SqlAssessmentOptionsOperationsService"],["com.azure.resourcemanager.migration.assessment.implementation.SqlAssessmentV2OperationsClientImpl$SqlAssessmentV2OperationsService"],["com.azure.resourcemanager.migration.assessment.implementation.SqlAssessmentV2SummaryOperationsClientImpl$SqlAssessmentV2SummaryOperationsService"],["com.azure.resourcemanager.migration.assessment.implementation.SqlCollectorOperationsClientImpl$SqlCollectorOperationsService"],["com.azure.resourcemanager.migration.assessment.implementation.VmwareCollectorsOperationsClientImpl$VmwareCollectorsOperationsService"]] \ No newline at end of file diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-migration-assessment/reflect-config.json b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-migration-assessment/reflect-config.json new file mode 100644 index 000000000000..0637a088a01e --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-migration-assessment/reflect-config.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/main/resources/azure-resourcemanager-migration-assessment.properties b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/resources/azure-resourcemanager-migration-assessment.properties new file mode 100644 index 000000000000..defbd48204e4 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/main/resources/azure-resourcemanager-migration-assessment.properties @@ -0,0 +1 @@ +version=${project.version} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedMachinesOperationsGetSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedMachinesOperationsGetSamples.java new file mode 100644 index 000000000000..accdb6ebadec --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedMachinesOperationsGetSamples.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for AssessedMachinesOperations Get. + */ +public final class AssessedMachinesOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessedMachinesOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: AssessedMachinesOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessedMachinesOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessedMachinesOperations() + .getWithResponse("rgopenapi", "pavqtntysjn", "smawqdmhfngray", "qjlumxyqsitd", "oqxjeheiipjmuo", + com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedMachinesOperationsListByAssessmentSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedMachinesOperationsListByAssessmentSamples.java new file mode 100644 index 000000000000..e6be6e870bf2 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedMachinesOperationsListByAssessmentSamples.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for AssessedMachinesOperations ListByAssessment. + */ +public final class AssessedMachinesOperationsListByAssessmentSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessedMachinesOperations_ListByAssessment_MaximumSet_Gen.json + */ + /** + * Sample code: AssessedMachinesOperations_ListByAssessment_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessedMachinesOperationsListByAssessmentMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessedMachinesOperations() + .listByAssessment("rgopenapi", "sloqixzfjk", "kjuepxerwseq", "rhzcmubwrrkhtocsibu", "sbkdovsfqldhdb", 10, + "hbyseetshbplfkjmpjhsiurqgt", 25, com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlDatabaseV2OperationsGetSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlDatabaseV2OperationsGetSamples.java new file mode 100644 index 000000000000..85f410cfa537 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlDatabaseV2OperationsGetSamples.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for AssessedSqlDatabaseV2Operations Get. + */ +public final class AssessedSqlDatabaseV2OperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessedSqlDatabaseV2Operations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: AssessedSqlDatabaseV2Operations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessedSqlDatabaseV2OperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessedSqlDatabaseV2Operations() + .getWithResponse("rgmigrate", "fci-test6904project", "test_fci_hadr", "test_swagger_1", + "858eb860-9e07-417c-91b6-bca1bffb3bf5", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlDatabaseV2OperationsListBySqlAssessmentV2Samples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlDatabaseV2OperationsListBySqlAssessmentV2Samples.java new file mode 100644 index 000000000000..f9add54d0304 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlDatabaseV2OperationsListBySqlAssessmentV2Samples.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for AssessedSqlDatabaseV2Operations ListBySqlAssessmentV2. + */ +public final class AssessedSqlDatabaseV2OperationsListBySqlAssessmentV2Samples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessedSqlDatabaseV2Operations_ListBySqlAssessmentV2_MaximumSet_Gen.json + */ + /** + * Sample code: AssessedSqlDatabaseV2Operations_ListBySqlAssessmentV2_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessedSqlDatabaseV2OperationsListBySqlAssessmentV2MaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessedSqlDatabaseV2Operations() + .listBySqlAssessmentV2("rgmigrate", "fci-test6904project", "test_fci_hadr", "test_swagger_1", + "(contains(Properties/DatabaseName,'adv130'))", 23, null, 1, com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlInstanceV2OperationsGetSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlInstanceV2OperationsGetSamples.java new file mode 100644 index 000000000000..c8c0842ea66a --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlInstanceV2OperationsGetSamples.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for AssessedSqlInstanceV2Operations Get. + */ +public final class AssessedSqlInstanceV2OperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessedSqlInstanceV2Operations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: AssessedSqlInstanceV2Operations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessedSqlInstanceV2OperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessedSqlInstanceV2Operations() + .getWithResponse("rgmigrate", "fci-test6904project", "test_fci_hadr", "test_swagger_1", + "3c6574cf-b4e1-4fdc-93db-6bbcc570dda2", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlInstanceV2OperationsListBySqlAssessmentV2Samples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlInstanceV2OperationsListBySqlAssessmentV2Samples.java new file mode 100644 index 000000000000..b6fd88e00f8e --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlInstanceV2OperationsListBySqlAssessmentV2Samples.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for AssessedSqlInstanceV2Operations ListBySqlAssessmentV2. + */ +public final class AssessedSqlInstanceV2OperationsListBySqlAssessmentV2Samples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessedSqlInstanceV2Operations_ListBySqlAssessmentV2_MaximumSet_Gen.json + */ + /** + * Sample code: AssessedSqlInstanceV2Operations_ListBySqlAssessmentV2_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessedSqlInstanceV2OperationsListBySqlAssessmentV2MaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessedSqlInstanceV2Operations() + .listBySqlAssessmentV2("rgmigrate", "fci-test6904project", "test_fci_hadr", "test_swagger_1", + "(contains(Properties/InstanceName,'MSSQLSERVER'))", 23, null, 1, com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlMachinesOperationsGetSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlMachinesOperationsGetSamples.java new file mode 100644 index 000000000000..462ef4f2b3cb --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlMachinesOperationsGetSamples.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for AssessedSqlMachinesOperations Get. + */ +public final class AssessedSqlMachinesOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessedSqlMachinesOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: AssessedSqlMachinesOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessedSqlMachinesOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessedSqlMachinesOperations() + .getWithResponse("rgmigrate", "fci-test6904project", "test_fci_hadr", "test_swagger_1", + "cc64c9dc-b38e-435d-85ad-d509df5d92c6", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlMachinesOperationsListBySqlAssessmentV2Samples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlMachinesOperationsListBySqlAssessmentV2Samples.java new file mode 100644 index 000000000000..8b6dca420d5e --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlMachinesOperationsListBySqlAssessmentV2Samples.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for AssessedSqlMachinesOperations ListBySqlAssessmentV2. + */ +public final class AssessedSqlMachinesOperationsListBySqlAssessmentV2Samples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessedSqlMachinesOperations_ListBySqlAssessmentV2_MaximumSet_Gen.json + */ + /** + * Sample code: AssessedSqlMachinesOperations_ListBySqlAssessmentV2_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessedSqlMachinesOperationsListBySqlAssessmentV2MaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessedSqlMachinesOperations() + .listBySqlAssessmentV2("rgmigrate", "fci-test6904project", "test_fci_hadr", "test_swagger_1", + "(contains(Properties/DisplayName,'SQLHAVM17'))", 23, null, 1, com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlRecommendedEntityOperationsGetSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlRecommendedEntityOperationsGetSamples.java new file mode 100644 index 000000000000..7dc9719c1ff6 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlRecommendedEntityOperationsGetSamples.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for AssessedSqlRecommendedEntityOperations Get. + */ +public final class AssessedSqlRecommendedEntityOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessedSqlRecommendedEntityOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: AssessedSqlRecommendedEntityOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessedSqlRecommendedEntityOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessedSqlRecommendedEntityOperations() + .getWithResponse("rgmigrate", "fci-test6904project", "test_fci_hadr", "test_swagger_1", + "cc64c9dc-b38e-435d-85ad-d509df5d92c6", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlRecommendedEntityOperationsListBySqlAssessmentV2Samples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlRecommendedEntityOperationsListBySqlAssessmentV2Samples.java new file mode 100644 index 000000000000..1fd81e8fa19d --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlRecommendedEntityOperationsListBySqlAssessmentV2Samples.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for AssessedSqlRecommendedEntityOperations ListBySqlAssessmentV2. + */ +public final class AssessedSqlRecommendedEntityOperationsListBySqlAssessmentV2Samples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessedSqlRecommendedEntityOperations_ListBySqlAssessmentV2_MaximumSet_Gen.json + */ + /** + * Sample code: AssessedSqlRecommendedEntityOperations_ListBySqlAssessmentV2_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessedSqlRecommendedEntityOperationsListBySqlAssessmentV2MaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessedSqlRecommendedEntityOperations() + .listBySqlAssessmentV2("rgmigrate", "fci-test6904project", "test_fci_hadr", "test_swagger_1", + "(contains(Properties/InstanceName,'MSSQLSERVER'))", 23, null, 1, com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentOptionsOperationsGetSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentOptionsOperationsGetSamples.java new file mode 100644 index 000000000000..61647144788a --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentOptionsOperationsGetSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for AssessmentOptionsOperations Get. + */ +public final class AssessmentOptionsOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentOptionsOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentOptionsOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentOptionsOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessmentOptionsOperations() + .getWithResponse("ayagrawrg", "app18700project", "default", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentOptionsOperationsListByAssessmentProjectSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentOptionsOperationsListByAssessmentProjectSamples.java new file mode 100644 index 000000000000..29de193eacd7 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentOptionsOperationsListByAssessmentProjectSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for AssessmentOptionsOperations ListByAssessmentProject. + */ +public final class AssessmentOptionsOperationsListByAssessmentProjectSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentOptionsOperations_ListByAssessmentProject_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentOptionsOperations_ListByAssessmentProject_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentOptionsOperationsListByAssessmentProjectMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessmentOptionsOperations() + .listByAssessmentProject("rgmigrate", "fhodvffhuoqwbysrrqbizete", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectSummaryOperationsGetSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectSummaryOperationsGetSamples.java new file mode 100644 index 000000000000..4a2528a260bd --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectSummaryOperationsGetSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for AssessmentProjectSummaryOperations Get. + */ +public final class AssessmentProjectSummaryOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentProjectSummaryOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentProjectSummaryOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentProjectSummaryOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessmentProjectSummaryOperations() + .getWithResponse("piyushapp1", "PiyushApp15328project", "default", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectSummaryOperationsListByAssessmentProjectSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectSummaryOperationsListByAssessmentProjectSamples.java new file mode 100644 index 000000000000..433b783b57de --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectSummaryOperationsListByAssessmentProjectSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for AssessmentProjectSummaryOperations ListByAssessmentProject. + */ +public final class AssessmentProjectSummaryOperationsListByAssessmentProjectSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentProjectSummaryOperations_ListByAssessmentProject_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentProjectSummaryOperations_ListByAssessmentProject_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentProjectSummaryOperationsListByAssessmentProjectMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessmentProjectSummaryOperations() + .listByAssessmentProject("piyushapp1", "PiyushApp15328project", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsCreateSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsCreateSamples.java new file mode 100644 index 000000000000..402f89e5dcdc --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsCreateSamples.java @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.resourcemanager.migration.assessment.models.ProjectProperties; +import com.azure.resourcemanager.migration.assessment.models.ProjectStatus; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.util.HashMap; +import java.util.Map; + +/** + * Samples for AssessmentProjectsOperations Create. + */ +public final class AssessmentProjectsOperationsCreateSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentProjectsOperations_Create_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentProjectsOperations_Create_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentProjectsOperationsCreateMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessmentProjectsOperations() + .define("sakanwar1204project") + .withRegion("southeastasia") + .withExistingResourceGroup("sakanwar") + .withTags(mapOf("Migrate Project", "sakanwar-PE-SEA")) + .withProperties(new ProjectProperties().withProvisioningState(ProvisioningState.SUCCEEDED) + .withAssessmentSolutionId( + "/subscriptions/4bd2aa0f-2bd2-4d67-91a8-5a4533d58600/resourceGroups/sakanwar/providers/Microsoft.Storage/storageAccounts/sakanwar1204usa") + .withProjectStatus(ProjectStatus.ACTIVE) + .withPublicNetworkAccess("Disabled") + .withCustomerStorageAccountArmId( + "/subscriptions/4bd2aa0f-2bd2-4d67-91a8-5a4533d58600/resourceGroups/sakanwar/providers/Microsoft.Storage/storageAccounts/sakanwar1204usa")) + .create(); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsDeleteSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsDeleteSamples.java new file mode 100644 index 000000000000..20fd879ba5aa --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsDeleteSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for AssessmentProjectsOperations Delete. + */ +public final class AssessmentProjectsOperationsDeleteSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentProjectsOperations_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentProjectsOperations_Delete_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentProjectsOperationsDeleteMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessmentProjectsOperations() + .deleteByResourceGroupWithResponse("rgmigrate", "zqrsyncwahgydqvwuchkfd", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsGetByResourceGroupSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsGetByResourceGroupSamples.java new file mode 100644 index 000000000000..c79cc729bed8 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsGetByResourceGroupSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for AssessmentProjectsOperations GetByResourceGroup. + */ +public final class AssessmentProjectsOperationsGetByResourceGroupSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentProjectsOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentProjectsOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentProjectsOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessmentProjectsOperations() + .getByResourceGroupWithResponse("sakanwar", "sakanwar1204project", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsListByResourceGroupSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsListByResourceGroupSamples.java new file mode 100644 index 000000000000..4bdec57e0e44 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsListByResourceGroupSamples.java @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for AssessmentProjectsOperations ListByResourceGroup. + */ +public final class AssessmentProjectsOperationsListByResourceGroupSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentProjectsOperations_ListByResourceGroup_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentProjectsOperations_ListByResourceGroup_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentProjectsOperationsListByResourceGroupMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessmentProjectsOperations().listByResourceGroup("sakanwar", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsListSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsListSamples.java new file mode 100644 index 000000000000..65dacec8fc24 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsListSamples.java @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for AssessmentProjectsOperations List. + */ +public final class AssessmentProjectsOperationsListSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentProjectsOperations_ListBySubscription_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentProjectsOperations_ListBySubscription_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentProjectsOperationsListBySubscriptionMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessmentProjectsOperations().list(com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsUpdateSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsUpdateSamples.java new file mode 100644 index 000000000000..186a92d476b9 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsUpdateSamples.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. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.resourcemanager.migration.assessment.models.AssessmentProject; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProjectUpdateProperties; +import com.azure.resourcemanager.migration.assessment.models.ProjectStatus; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.util.HashMap; +import java.util.Map; + +/** + * Samples for AssessmentProjectsOperations Update. + */ +public final class AssessmentProjectsOperationsUpdateSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentProjectsOperations_Update_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentProjectsOperations_Update_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentProjectsOperationsUpdateMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + AssessmentProject resource = manager.assessmentProjectsOperations() + .getByResourceGroupWithResponse("sakanwar", "sakanwar1204project", com.azure.core.util.Context.NONE) + .getValue(); + resource.update() + .withTags(mapOf("Migrate Project", "sakanwar-PE-SEA")) + .withProperties(new AssessmentProjectUpdateProperties().withAssessmentSolutionId( + "/subscriptions/4bd2aa0f-2bd2-4d67-91a8-5a4533d58600/resourceGroups/sakanwar/providers/Microsoft.Storage/storageAccounts/sakanwar1204usa") + .withProjectStatus(ProjectStatus.ACTIVE) + .withPublicNetworkAccess("Disabled") + .withCustomerStorageAccountArmId( + "/subscriptions/4bd2aa0f-2bd2-4d67-91a8-5a4533d58600/resourceGroups/sakanwar/providers/Microsoft.Storage/storageAccounts/sakanwar1204usa") + .withProvisioningState(ProvisioningState.SUCCEEDED)) + .apply(); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentsOperationsCreateSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentsOperationsCreateSamples.java new file mode 100644 index 000000000000..950967fb5760 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentsOperationsCreateSamples.java @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.resourcemanager.migration.assessment.models.AssessmentSizingCriterion; +import com.azure.resourcemanager.migration.assessment.models.AzureCurrency; +import com.azure.resourcemanager.migration.assessment.models.AzureDiskType; +import com.azure.resourcemanager.migration.assessment.models.AzureHybridUseBenefit; +import com.azure.resourcemanager.migration.assessment.models.AzureOfferCode; +import com.azure.resourcemanager.migration.assessment.models.AzurePricingTier; +import com.azure.resourcemanager.migration.assessment.models.AzureReservedInstance; +import com.azure.resourcemanager.migration.assessment.models.AzureStorageRedundancy; +import com.azure.resourcemanager.migration.assessment.models.AzureVmFamily; +import com.azure.resourcemanager.migration.assessment.models.MachineAssessmentProperties; +import com.azure.resourcemanager.migration.assessment.models.Percentile; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import com.azure.resourcemanager.migration.assessment.models.TimeRange; +import com.azure.resourcemanager.migration.assessment.models.VmUptime; +import java.time.OffsetDateTime; +import java.util.Arrays; + +/** + * Samples for AssessmentsOperations Create. + */ +public final class AssessmentsOperationsCreateSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentsOperations_Create_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentsOperations_Create_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentsOperationsCreateMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessmentsOperations() + .define("asm1") + .withExistingGroup("ayagrawrg", "app18700project", "kuchatur-test") + .withProperties(new MachineAssessmentProperties().withProvisioningState(ProvisioningState.SUCCEEDED) + .withEaSubscriptionId("kwsu") + .withAzurePricingTier(AzurePricingTier.STANDARD) + .withAzureStorageRedundancy(AzureStorageRedundancy.UNKNOWN) + .withReservedInstance(AzureReservedInstance.NONE) + .withAzureHybridUseBenefit(AzureHybridUseBenefit.UNKNOWN) + .withAzureDiskTypes(Arrays.asList(AzureDiskType.PREMIUM, AzureDiskType.STANDARD_SSD)) + .withAzureVmFamilies( + Arrays.asList(AzureVmFamily.D_SERIES, AzureVmFamily.LSV2_SERIES, AzureVmFamily.M_SERIES, + AzureVmFamily.MDSV2_SERIES, AzureVmFamily.MSV2_SERIES, AzureVmFamily.MV2_SERIES)) + .withVmUptime(new VmUptime().withDaysPerMonth(13).withHoursPerDay(26)) + .withAzureLocation("njxbwdtsxzhichsnk") + .withAzureOfferCode(AzureOfferCode.UNKNOWN) + .withCurrency(AzureCurrency.UNKNOWN) + .withScalingFactor(24.0F) + .withPercentile(Percentile.PERCENTILE50) + .withTimeRange(TimeRange.DAY) + .withPerfDataStartTime(OffsetDateTime.parse("2023-09-26T09:36:48.491Z")) + .withPerfDataEndTime(OffsetDateTime.parse("2023-09-26T09:36:48.491Z")) + .withDiscountPercentage(6.0F) + .withSizingCriterion(AssessmentSizingCriterion.PERFORMANCE_BASED)) + .create(); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentsOperationsDeleteSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentsOperationsDeleteSamples.java new file mode 100644 index 000000000000..bbf96fea4a1c --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentsOperationsDeleteSamples.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for AssessmentsOperations Delete. + */ +public final class AssessmentsOperationsDeleteSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentsOperations_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentsOperations_Delete_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentsOperationsDeleteMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessmentsOperations() + .deleteWithResponse("ayagrawrg", "app18700project", "kuchatur-test", "asm1", + com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentsOperationsDownloadUrlSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentsOperationsDownloadUrlSamples.java new file mode 100644 index 000000000000..646f7f290ea0 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentsOperationsDownloadUrlSamples.java @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.management.serializer.SerializerFactory; +import com.azure.core.util.serializer.SerializerEncoding; +import java.io.IOException; + +/** + * Samples for AssessmentsOperations DownloadUrl. + */ +public final class AssessmentsOperationsDownloadUrlSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentsOperations_DownloadUrl_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentsOperations_DownloadUrl_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentsOperationsDownloadUrlMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) throws IOException { + manager.assessmentsOperations() + .downloadUrl("ayagrawrg", "app18700project", "kuchatur-test", "asm1", + SerializerFactory.createDefaultManagementSerializerAdapter() + .deserialize("{}", Object.class, SerializerEncoding.JSON), + com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentsOperationsGetSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentsOperationsGetSamples.java new file mode 100644 index 000000000000..8f226261f0db --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentsOperationsGetSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for AssessmentsOperations Get. + */ +public final class AssessmentsOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentsOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentsOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentsOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessmentsOperations() + .getWithResponse("ayagrawrg", "app18700project", "kuchatur-test", "asm1", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentsOperationsListByGroupSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentsOperationsListByGroupSamples.java new file mode 100644 index 000000000000..24468b13434b --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentsOperationsListByGroupSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for AssessmentsOperations ListByGroup. + */ +public final class AssessmentsOperationsListByGroupSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AssessmentsOperations_ListByGroup_MaximumSet_Gen.json + */ + /** + * Sample code: AssessmentsOperations_ListByGroup_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void assessmentsOperationsListByGroupMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.assessmentsOperations() + .listByGroup("ayagrawrg", "app18700project", "kuchatur-test", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessedMachinesOperationsGetSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessedMachinesOperationsGetSamples.java new file mode 100644 index 000000000000..ed8c57e350c0 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessedMachinesOperationsGetSamples.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for AvsAssessedMachinesOperations Get. + */ +public final class AvsAssessedMachinesOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AvsAssessedMachinesOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: AvsAssessedMachinesOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void avsAssessedMachinesOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.avsAssessedMachinesOperations() + .getWithResponse("ayagrawrg", "app18700project", "kuchatur-test", "asm2", + "b6d6fc6f-796f-4c16-96af-a6d22e0f12f7", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessedMachinesOperationsListByAvsAssessmentSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessedMachinesOperationsListByAvsAssessmentSamples.java new file mode 100644 index 000000000000..8432cc6130f2 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessedMachinesOperationsListByAvsAssessmentSamples.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for AvsAssessedMachinesOperations ListByAvsAssessment. + */ +public final class AvsAssessedMachinesOperationsListByAvsAssessmentSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AvsAssessedMachinesOperations_ListByAvsAssessment_MaximumSet_Gen.json + */ + /** + * Sample code: AvsAssessedMachinesOperations_ListByAvsAssessment_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void avsAssessedMachinesOperationsListByAvsAssessmentMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.avsAssessedMachinesOperations() + .listByAvsAssessment("ayagrawrg", "app18700project", "kuchatur-test", "asm2", "ujmwhhuloficljxcjyc", 6, + "qwrjeiukbcicfrkqlqsfukfc", 19, com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentOptionsOperationsGetSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentOptionsOperationsGetSamples.java new file mode 100644 index 000000000000..1b95a32adae2 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentOptionsOperationsGetSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for AvsAssessmentOptionsOperations Get. + */ +public final class AvsAssessmentOptionsOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AvsAssessmentOptionsOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: AvsAssessmentOptionsOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void avsAssessmentOptionsOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.avsAssessmentOptionsOperations() + .getWithResponse("ayagrawrg", "app18700project", "default", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentOptionsOperationsListByAssessmentProjectSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentOptionsOperationsListByAssessmentProjectSamples.java new file mode 100644 index 000000000000..1273d8d4b80d --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentOptionsOperationsListByAssessmentProjectSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for AvsAssessmentOptionsOperations ListByAssessmentProject. + */ +public final class AvsAssessmentOptionsOperationsListByAssessmentProjectSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AvsAssessmentOptionsOperations_ListByAssessmentProject_MaximumSet_Gen.json + */ + /** + * Sample code: AvsAssessmentOptionsOperations_ListByAssessmentProject_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void avsAssessmentOptionsOperationsListByAssessmentProjectMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.avsAssessmentOptionsOperations() + .listByAssessmentProject("ayagrawrg", "app18700project", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentsOperationsCreateSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentsOperationsCreateSamples.java new file mode 100644 index 000000000000..836828ff1265 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentsOperationsCreateSamples.java @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.resourcemanager.migration.assessment.models.AssessmentSizingCriterion; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessmentProperties; +import com.azure.resourcemanager.migration.assessment.models.AzureAvsNodeType; +import com.azure.resourcemanager.migration.assessment.models.AzureCurrency; +import com.azure.resourcemanager.migration.assessment.models.AzureLocation; +import com.azure.resourcemanager.migration.assessment.models.AzureOfferCode; +import com.azure.resourcemanager.migration.assessment.models.AzureReservedInstance; +import com.azure.resourcemanager.migration.assessment.models.FttAndRaidLevel; +import com.azure.resourcemanager.migration.assessment.models.Percentile; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import com.azure.resourcemanager.migration.assessment.models.TimeRange; +import java.time.OffsetDateTime; + +/** + * Samples for AvsAssessmentsOperations Create. + */ +public final class AvsAssessmentsOperationsCreateSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AvsAssessmentsOperations_Create_MaximumSet_Gen.json + */ + /** + * Sample code: AvsAssessmentsOperations_Create_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void avsAssessmentsOperationsCreateMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.avsAssessmentsOperations() + .define("asm2") + .withExistingGroup("ayagrawrg", "app18700project", "kuchatur-test") + .withProperties(new AvsAssessmentProperties().withProvisioningState(ProvisioningState.SUCCEEDED) + .withFailuresToTolerateAndRaidLevel(FttAndRaidLevel.FTT1RAID1) + .withVcpuOversubscription(4.0F) + .withNodeType(AzureAvsNodeType.AV36) + .withReservedInstance(AzureReservedInstance.RI3YEAR) + .withMemOvercommit(1.0F) + .withDedupeCompression(1.5F) + .withIsStretchClusterEnabled(true) + .withAzureLocation(AzureLocation.EAST_US) + .withAzureOfferCode(AzureOfferCode.MSAZR0003P) + .withCurrency(AzureCurrency.USD) + .withScalingFactor(1.0F) + .withPercentile(Percentile.PERCENTILE95) + .withTimeRange(TimeRange.DAY) + .withPerfDataStartTime(OffsetDateTime.parse("2023-09-25T13:35:56.5671462Z")) + .withPerfDataEndTime(OffsetDateTime.parse("2023-09-26T13:35:56.5671462Z")) + .withDiscountPercentage(0.0F) + .withSizingCriterion(AssessmentSizingCriterion.AS_ON_PREMISES)) + .create(); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentsOperationsDeleteSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentsOperationsDeleteSamples.java new file mode 100644 index 000000000000..5086915dae9b --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentsOperationsDeleteSamples.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for AvsAssessmentsOperations Delete. + */ +public final class AvsAssessmentsOperationsDeleteSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AvsAssessmentsOperations_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: AvsAssessmentsOperations_Delete_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void avsAssessmentsOperationsDeleteMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.avsAssessmentsOperations() + .deleteWithResponse("ayagrawrg", "app18700project", "kuchatur-test", "asm2", + com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentsOperationsDownloadUrlSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentsOperationsDownloadUrlSamples.java new file mode 100644 index 000000000000..1f4d00c1c771 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentsOperationsDownloadUrlSamples.java @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.management.serializer.SerializerFactory; +import com.azure.core.util.serializer.SerializerEncoding; +import java.io.IOException; + +/** + * Samples for AvsAssessmentsOperations DownloadUrl. + */ +public final class AvsAssessmentsOperationsDownloadUrlSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AvsAssessmentsOperations_DownloadUrl_MaximumSet_Gen.json + */ + /** + * Sample code: AvsAssessmentsOperations_DownloadUrl_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void avsAssessmentsOperationsDownloadUrlMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) throws IOException { + manager.avsAssessmentsOperations() + .downloadUrl("ayagrawrg", "app18700project", "kuchatur-test", "asm2", + SerializerFactory.createDefaultManagementSerializerAdapter() + .deserialize("{}", Object.class, SerializerEncoding.JSON), + com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentsOperationsGetSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentsOperationsGetSamples.java new file mode 100644 index 000000000000..0499a4dd114d --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentsOperationsGetSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for AvsAssessmentsOperations Get. + */ +public final class AvsAssessmentsOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AvsAssessmentsOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: AvsAssessmentsOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void avsAssessmentsOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.avsAssessmentsOperations() + .getWithResponse("ayagrawrg", "app18700project", "kuchatur-test", "asm2", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentsOperationsListByGroupSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentsOperationsListByGroupSamples.java new file mode 100644 index 000000000000..9a39573d851e --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentsOperationsListByGroupSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for AvsAssessmentsOperations ListByGroup. + */ +public final class AvsAssessmentsOperationsListByGroupSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * AvsAssessmentsOperations_ListByGroup_MaximumSet_Gen.json + */ + /** + * Sample code: AvsAssessmentsOperations_ListByGroup_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void avsAssessmentsOperationsListByGroupMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.avsAssessmentsOperations() + .listByGroup("ayagrawrg", "app18700project", "kuchatur-test", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsCreateSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsCreateSamples.java new file mode 100644 index 000000000000..2988295133a6 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsCreateSamples.java @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.resourcemanager.migration.assessment.models.GroupProperties; +import com.azure.resourcemanager.migration.assessment.models.GroupType; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; + +/** + * Samples for GroupsOperations Create. + */ +public final class GroupsOperationsCreateSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * GroupsOperations_Create_MaximumSet_Gen.json + */ + /** + * Sample code: GroupsOperations_Create_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void groupsOperationsCreateMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.groupsOperations() + .define("kuchatur-test") + .withExistingAssessmentProject("ayagrawrg", "app18700project") + .withProperties(new GroupProperties().withProvisioningState(ProvisioningState.SUCCEEDED) + .withGroupType(GroupType.DEFAULT)) + .create(); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsDeleteSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsDeleteSamples.java new file mode 100644 index 000000000000..690de780135a --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsDeleteSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for GroupsOperations Delete. + */ +public final class GroupsOperationsDeleteSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * GroupsOperations_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: GroupsOperations_Delete_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void groupsOperationsDeleteMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.groupsOperations() + .deleteWithResponse("ayagrawrg", "app18700project", "kuchatur-test", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsGetSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsGetSamples.java new file mode 100644 index 000000000000..ade21ccc0f9b --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsGetSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for GroupsOperations Get. + */ +public final class GroupsOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * GroupsOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: GroupsOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void groupsOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.groupsOperations() + .getWithResponse("ayagrawrg", "app18700project", "kuchatur-test", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsListByAssessmentProjectSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsListByAssessmentProjectSamples.java new file mode 100644 index 000000000000..f77f185fdce3 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsListByAssessmentProjectSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for GroupsOperations ListByAssessmentProject. + */ +public final class GroupsOperationsListByAssessmentProjectSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * GroupsOperations_ListByAssessmentProject_MaximumSet_Gen.json + */ + /** + * Sample code: GroupsOperations_ListByAssessmentProject_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void groupsOperationsListByAssessmentProjectMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.groupsOperations() + .listByAssessmentProject("ayagrawrg", "app18700project", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsUpdateMachinesSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsUpdateMachinesSamples.java new file mode 100644 index 000000000000..cc0fd90b85ea --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsUpdateMachinesSamples.java @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.resourcemanager.migration.assessment.models.GroupBodyProperties; +import com.azure.resourcemanager.migration.assessment.models.GroupUpdateOperation; +import com.azure.resourcemanager.migration.assessment.models.UpdateGroupBody; +import java.util.Arrays; + +/** + * Samples for GroupsOperations UpdateMachines. + */ +public final class GroupsOperationsUpdateMachinesSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * GroupsOperations_UpdateMachines_MaximumSet_Gen.json + */ + /** + * Sample code: GroupsOperations_UpdateMachines_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void groupsOperationsUpdateMachinesMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.groupsOperations() + .updateMachines("ayagrawrg", "app18700project", "kuchatur-test", new UpdateGroupBody().withEtag("*") + .withProperties(new GroupBodyProperties().withOperationType(GroupUpdateOperation.ADD) + .withMachines(Arrays.asList( + "/subscriptions/4bd2aa0f-2bd2-4d67-91a8-5a4533d58600/resourceGroups/ayagrawrg/providers/Microsoft.Migrate/assessmentprojects/app18700project/machines/18895660-c5e5-4247-8cfc-cd24e1fe57f3"))), + com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorsOperationsCreateSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorsOperationsCreateSamples.java new file mode 100644 index 000000000000..6398834156ef --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorsOperationsCreateSamples.java @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentSpnPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBaseWithAgent; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.time.OffsetDateTime; + +/** + * Samples for HypervCollectorsOperations Create. + */ +public final class HypervCollectorsOperationsCreateSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * HypervCollectorsOperations_Create_MaximumSet_Gen.json + */ + /** + * Sample code: HypervCollectorsOperations_Create_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void hypervCollectorsOperationsCreateMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.hypervCollectorsOperations() + .define("test-697cecollector") + .withExistingAssessmentProject("ayagrawRG", "app18700project") + .withProperties(new CollectorPropertiesBaseWithAgent().withProvisioningState(ProvisioningState.SUCCEEDED) + .withAgentProperties(new CollectorAgentPropertiesBase().withId("12f1d90f-b3fa-4926-8893-e56803a09af0") + .withVersion("2.0.1993.19") + .withLastHeartbeatUtc(OffsetDateTime.parse("2022-07-07T14:25:35.708325Z")) + .withSpnDetails(new CollectorAgentSpnPropertiesBase() + .withAuthority("https://login.windows.net/72f988bf-86f1-41af-91ab-2d7cd011db47") + .withApplicationId("e3bd6eaa-980b-40ae-a30e-2a5069ba097c") + .withAudience("e3bd6eaa-980b-40ae-a30e-2a5069ba097c") + .withObjectId("01b9f9e2-2d82-414c-adaa-09ce259b6b44") + .withTenantId("72f988bf-86f1-41af-91ab-2d7cd011db47"))) + .withDiscoverySiteId( + "/subscriptions/4bd2aa0f-2bd2-4d67-91a8-5a4533d58600/resourceGroups/ayagrawRG/providers/Microsoft.OffAzure/HyperVSites/test-60527site")) + .create(); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorsOperationsDeleteSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorsOperationsDeleteSamples.java new file mode 100644 index 000000000000..3fcfead6b763 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorsOperationsDeleteSamples.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for HypervCollectorsOperations Delete. + */ +public final class HypervCollectorsOperationsDeleteSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * HypervCollectorsOperations_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: HypervCollectorsOperations_Delete_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void hypervCollectorsOperationsDeleteMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.hypervCollectorsOperations() + .deleteWithResponse("ayagrawRG", "app18700project", "test-697cecollector", + com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorsOperationsGetSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorsOperationsGetSamples.java new file mode 100644 index 000000000000..e0c9507885db --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorsOperationsGetSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for HypervCollectorsOperations Get. + */ +public final class HypervCollectorsOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * HypervCollectorsOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: HypervCollectorsOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void hypervCollectorsOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.hypervCollectorsOperations() + .getWithResponse("ayagrawRG", "app18700project", "test-697cecollector", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorsOperationsListByAssessmentProjectSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorsOperationsListByAssessmentProjectSamples.java new file mode 100644 index 000000000000..92b1f2b0f21b --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorsOperationsListByAssessmentProjectSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for HypervCollectorsOperations ListByAssessmentProject. + */ +public final class HypervCollectorsOperationsListByAssessmentProjectSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * HypervCollectorsOperations_ListByAssessmentProject_MaximumSet_Gen.json + */ + /** + * Sample code: HypervCollectorsOperations_ListByAssessmentProject_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void hypervCollectorsOperationsListByAssessmentProjectMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.hypervCollectorsOperations() + .listByAssessmentProject("ayagrawRG", "app18700project", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorsOperationsCreateSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorsOperationsCreateSamples.java new file mode 100644 index 000000000000..6d242286869f --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorsOperationsCreateSamples.java @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; + +/** + * Samples for ImportCollectorsOperations Create. + */ +public final class ImportCollectorsOperationsCreateSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * ImportCollectorsOperations_Create_MaximumSet_Gen.json + */ + /** + * Sample code: ImportCollectorsOperations_Create_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void importCollectorsOperationsCreateMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.importCollectorsOperations() + .define("importCollectore7d5") + .withExistingAssessmentProject("ayagrawRG", "app18700project") + .withProperties(new CollectorPropertiesBase().withProvisioningState(ProvisioningState.SUCCEEDED) + .withDiscoverySiteId( + "/subscriptions/4bd2aa0f-2bd2-4d67-91a8-5a4533d58600/resourcegroups/ayagrawRG/providers/microsoft.offazure/importsites/actualSEA37d4importSite")) + .create(); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorsOperationsDeleteSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorsOperationsDeleteSamples.java new file mode 100644 index 000000000000..f61e11dddef7 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorsOperationsDeleteSamples.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for ImportCollectorsOperations Delete. + */ +public final class ImportCollectorsOperationsDeleteSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * ImportCollectorsOperations_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: ImportCollectorsOperations_Delete_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void importCollectorsOperationsDeleteMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.importCollectorsOperations() + .deleteWithResponse("ayagrawRG", "app18700project", "importCollectore7d5", + com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorsOperationsGetSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorsOperationsGetSamples.java new file mode 100644 index 000000000000..24a69622b3a0 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorsOperationsGetSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for ImportCollectorsOperations Get. + */ +public final class ImportCollectorsOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * ImportCollectorsOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: ImportCollectorsOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void importCollectorsOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.importCollectorsOperations() + .getWithResponse("ayagrawRG", "app18700project", "importCollectore7d5", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorsOperationsListByAssessmentProjectSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorsOperationsListByAssessmentProjectSamples.java new file mode 100644 index 000000000000..ead0b7b930e0 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorsOperationsListByAssessmentProjectSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for ImportCollectorsOperations ListByAssessmentProject. + */ +public final class ImportCollectorsOperationsListByAssessmentProjectSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * ImportCollectorsOperations_ListByAssessmentProject_MaximumSet_Gen.json + */ + /** + * Sample code: ImportCollectorsOperations_ListByAssessmentProject_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void importCollectorsOperationsListByAssessmentProjectMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.importCollectorsOperations() + .listByAssessmentProject("ayagrawRG", "app18700project", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/MachinesOperationsGetSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/MachinesOperationsGetSamples.java new file mode 100644 index 000000000000..d5a0ddc37a32 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/MachinesOperationsGetSamples.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for MachinesOperations Get. + */ +public final class MachinesOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * MachinesOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: MachinesOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void machinesOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.machinesOperations() + .getWithResponse("ayagrawrg", "app18700project", "55082b89-99e2-4c40-b63f-d4f4d6ba961d", + com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/MachinesOperationsListByAssessmentProjectSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/MachinesOperationsListByAssessmentProjectSamples.java new file mode 100644 index 000000000000..de7cbf436315 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/MachinesOperationsListByAssessmentProjectSamples.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for MachinesOperations ListByAssessmentProject. + */ +public final class MachinesOperationsListByAssessmentProjectSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * MachinesOperations_ListByAssessmentProject_MaximumSet_Gen.json + */ + /** + * Sample code: MachinesOperations_ListByAssessmentProject_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void machinesOperationsListByAssessmentProjectMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.machinesOperations() + .listByAssessmentProject("ayagrawrg", "app18700project", null, 1, null, 1, + com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/OperationsListSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/OperationsListSamples.java new file mode 100644 index 000000000000..c9c22aaa438e --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/OperationsListSamples.java @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for Operations List. + */ +public final class OperationsListSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * Operations_List_MaximumSet_Gen.json + */ + /** + * Sample code: Operations_List_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void + operationsListMaximumSetGen(com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.operations().list(com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionOperationsDeleteSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionOperationsDeleteSamples.java new file mode 100644 index 000000000000..f6c7190cf92b --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionOperationsDeleteSamples.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for PrivateEndpointConnectionOperations Delete. + */ +public final class PrivateEndpointConnectionOperationsDeleteSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * PrivateEndpointConnectionOperations_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: PrivateEndpointConnectionOperations_Delete_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void privateEndpointConnectionOperationsDeleteMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.privateEndpointConnectionOperations() + .deleteWithResponse("sakanwar", "sakanwar1204project", + "sakanwar1204project1634pe.bf42f8a1-09f5-4ee4-aea6-a019cc60f9d7", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionOperationsGetSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionOperationsGetSamples.java new file mode 100644 index 000000000000..4571ff08dc0a --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionOperationsGetSamples.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for PrivateEndpointConnectionOperations Get. + */ +public final class PrivateEndpointConnectionOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * PrivateEndpointConnectionOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: PrivateEndpointConnectionOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void privateEndpointConnectionOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.privateEndpointConnectionOperations() + .getWithResponse("sakanwar", "sakanwar1204project", + "sakanwar1204project1634pe.bf42f8a1-09f5-4ee4-aea6-a019cc60f9d7", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionOperationsListByAssessmentProjectSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionOperationsListByAssessmentProjectSamples.java new file mode 100644 index 000000000000..9458745f3cab --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionOperationsListByAssessmentProjectSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for PrivateEndpointConnectionOperations ListByAssessmentProject. + */ +public final class PrivateEndpointConnectionOperationsListByAssessmentProjectSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * PrivateEndpointConnectionOperations_ListByAssessmentProject_MaximumSet_Gen.json + */ + /** + * Sample code: PrivateEndpointConnectionOperations_ListByAssessmentProject_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void privateEndpointConnectionOperationsListByAssessmentProjectMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.privateEndpointConnectionOperations() + .listByAssessmentProject("sakanwar", "sakanwar1204project", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionOperationsUpdateSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionOperationsUpdateSamples.java new file mode 100644 index 000000000000..b952d723ddb6 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionOperationsUpdateSamples.java @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.resourcemanager.migration.assessment.fluent.models.PrivateEndpointConnectionInner; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpoint; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpointConnectionProperties; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpointServiceConnectionStatus; +import com.azure.resourcemanager.migration.assessment.models.PrivateLinkServiceConnectionState; + +/** + * Samples for PrivateEndpointConnectionOperations Update. + */ +public final class PrivateEndpointConnectionOperationsUpdateSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * PrivateEndpointConnectionOperations_Update_MaximumSet_Gen.json + */ + /** + * Sample code: PrivateEndpointConnectionOperations_Update_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void privateEndpointConnectionOperationsUpdateMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.privateEndpointConnectionOperations() + .update("sakanwar", "sakanwar1204project", "sakanwar1204project1634pe.bf42f8a1-09f5-4ee4-aea6-a019cc60f9d7", + new PrivateEndpointConnectionInner() + .withProperties(new PrivateEndpointConnectionProperties().withPrivateEndpoint(new PrivateEndpoint()) + .withPrivateLinkServiceConnectionState(new PrivateLinkServiceConnectionState() + .withStatus(PrivateEndpointServiceConnectionStatus.APPROVED) + .withActionsRequired(""))), + com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/PrivateLinkResourceOperationsGetSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/PrivateLinkResourceOperationsGetSamples.java new file mode 100644 index 000000000000..acb01104b0f5 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/PrivateLinkResourceOperationsGetSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for PrivateLinkResourceOperations Get. + */ +public final class PrivateLinkResourceOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * PrivateLinkResourceOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: PrivateLinkResourceOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void privateLinkResourceOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.privateLinkResourceOperations() + .getWithResponse("sakanwar", "sakanwar1204project", "Default", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/PrivateLinkResourceOperationsListByAssessmentProjectSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/PrivateLinkResourceOperationsListByAssessmentProjectSamples.java new file mode 100644 index 000000000000..fcb6702c8313 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/PrivateLinkResourceOperationsListByAssessmentProjectSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for PrivateLinkResourceOperations ListByAssessmentProject. + */ +public final class PrivateLinkResourceOperationsListByAssessmentProjectSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * PrivateLinkResourceOperations_ListByAssessmentProject_MaximumSet_Gen.json + */ + /** + * Sample code: PrivateLinkResourceOperations_ListByAssessmentProject_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void privateLinkResourceOperationsListByAssessmentProjectMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.privateLinkResourceOperations() + .listByAssessmentProject("sakanwar", "sakanwar1204project", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorsOperationsCreateSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorsOperationsCreateSamples.java new file mode 100644 index 000000000000..6b14563ef370 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorsOperationsCreateSamples.java @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentSpnPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBaseWithAgent; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; + +/** + * Samples for ServerCollectorsOperations Create. + */ +public final class ServerCollectorsOperationsCreateSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * ServerCollectorsOperations_Create_MaximumSet_Gen.json + */ + /** + * Sample code: ServerCollectorsOperations_Create_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void serverCollectorsOperationsCreateMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.serverCollectorsOperations() + .define("walter389fcollector") + .withExistingAssessmentProject("ayagrawRG", "app18700project") + .withProperties(new CollectorPropertiesBaseWithAgent().withProvisioningState(ProvisioningState.SUCCEEDED) + .withAgentProperties(new CollectorAgentPropertiesBase().withId("498e4965-bbb1-47c2-8613-345baff9c509") + .withSpnDetails(new CollectorAgentSpnPropertiesBase() + .withAuthority("https://login.windows.net/72f988bf-86f1-41af-91ab-2d7cd011db47") + .withApplicationId("65153d2f-9afb-44e8-b3ca-1369150b7354") + .withAudience("65153d2f-9afb-44e8-b3ca-1369150b7354") + .withObjectId("ddde6f96-87c8-420b-9d4d-f16a5090519e") + .withTenantId("72f988bf-86f1-41af-91ab-2d7cd011db47"))) + .withDiscoverySiteId( + "/subscriptions/4bd2aa0f-2bd2-4d67-91a8-5a4533d58600/resourceGroups/ayagrawRG/providers/Microsoft.OffAzure/ServerSites/walter7155site")) + .create(); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorsOperationsDeleteSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorsOperationsDeleteSamples.java new file mode 100644 index 000000000000..414735ef6d1a --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorsOperationsDeleteSamples.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for ServerCollectorsOperations Delete. + */ +public final class ServerCollectorsOperationsDeleteSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * ServerCollectorsOperations_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: ServerCollectorsOperations_Delete_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void serverCollectorsOperationsDeleteMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.serverCollectorsOperations() + .deleteWithResponse("ayagrawRG", "app18700project", "walter389fcollector", + com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorsOperationsGetSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorsOperationsGetSamples.java new file mode 100644 index 000000000000..9efd3cb257c4 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorsOperationsGetSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for ServerCollectorsOperations Get. + */ +public final class ServerCollectorsOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * ServerCollectorsOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: ServerCollectorsOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void serverCollectorsOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.serverCollectorsOperations() + .getWithResponse("ayagrawRG", "app18700project", "walter389fcollector", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorsOperationsListByAssessmentProjectSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorsOperationsListByAssessmentProjectSamples.java new file mode 100644 index 000000000000..8bb8449e9607 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorsOperationsListByAssessmentProjectSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for ServerCollectorsOperations ListByAssessmentProject. + */ +public final class ServerCollectorsOperationsListByAssessmentProjectSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * ServerCollectorsOperations_ListByAssessmentProject_MaximumSet_Gen.json + */ + /** + * Sample code: ServerCollectorsOperations_ListByAssessmentProject_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void serverCollectorsOperationsListByAssessmentProjectMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.serverCollectorsOperations() + .listByAssessmentProject("ayagrawRG", "app18700project", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentOptionsOperationsGetSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentOptionsOperationsGetSamples.java new file mode 100644 index 000000000000..99714088827b --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentOptionsOperationsGetSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for SqlAssessmentOptionsOperations Get. + */ +public final class SqlAssessmentOptionsOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * SqlAssessmentOptionsOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: SqlAssessmentOptionsOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void sqlAssessmentOptionsOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.sqlAssessmentOptionsOperations() + .getWithResponse("rgmigrate", "fci-test6904project", "default", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentOptionsOperationsListByAssessmentProjectSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentOptionsOperationsListByAssessmentProjectSamples.java new file mode 100644 index 000000000000..9a7c648ac483 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentOptionsOperationsListByAssessmentProjectSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for SqlAssessmentOptionsOperations ListByAssessmentProject. + */ +public final class SqlAssessmentOptionsOperationsListByAssessmentProjectSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * SqlAssessmentOptionsOperations_ListByAssessmentProject_MaximumSet_Gen.json + */ + /** + * Sample code: SqlAssessmentOptionsOperations_ListByAssessmentProject_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void sqlAssessmentOptionsOperationsListByAssessmentProjectMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.sqlAssessmentOptionsOperations() + .listByAssessmentProject("rgmigrate", "fci-test6904project", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2OperationsCreateSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2OperationsCreateSamples.java new file mode 100644 index 000000000000..11c9a19412ef --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2OperationsCreateSamples.java @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.resourcemanager.migration.assessment.models.AssessmentSizingCriterion; +import com.azure.resourcemanager.migration.assessment.models.AsyncCommitModeIntent; +import com.azure.resourcemanager.migration.assessment.models.AzureCurrency; +import com.azure.resourcemanager.migration.assessment.models.AzureLocation; +import com.azure.resourcemanager.migration.assessment.models.AzureOfferCode; +import com.azure.resourcemanager.migration.assessment.models.AzureReservedInstance; +import com.azure.resourcemanager.migration.assessment.models.AzureSqlDataBaseType; +import com.azure.resourcemanager.migration.assessment.models.AzureSqlInstanceType; +import com.azure.resourcemanager.migration.assessment.models.AzureSqlPurchaseModel; +import com.azure.resourcemanager.migration.assessment.models.AzureSqlServiceTier; +import com.azure.resourcemanager.migration.assessment.models.AzureVmFamily; +import com.azure.resourcemanager.migration.assessment.models.ComputeTier; +import com.azure.resourcemanager.migration.assessment.models.EntityUptime; +import com.azure.resourcemanager.migration.assessment.models.EnvironmentType; +import com.azure.resourcemanager.migration.assessment.models.MultiSubnetIntent; +import com.azure.resourcemanager.migration.assessment.models.OptimizationLogic; +import com.azure.resourcemanager.migration.assessment.models.OsLicense; +import com.azure.resourcemanager.migration.assessment.models.Percentile; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentV2Properties; +import com.azure.resourcemanager.migration.assessment.models.SqlDbSettings; +import com.azure.resourcemanager.migration.assessment.models.SqlMiSettings; +import com.azure.resourcemanager.migration.assessment.models.SqlServerLicense; +import com.azure.resourcemanager.migration.assessment.models.SqlVmSettings; +import com.azure.resourcemanager.migration.assessment.models.TimeRange; +import java.util.Arrays; + +/** + * Samples for SqlAssessmentV2Operations Create. + */ +public final class SqlAssessmentV2OperationsCreateSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * SqlAssessmentV2Operations_Create_MaximumSet_Gen.json + */ + /** + * Sample code: SqlAssessmentV2Operations_Create_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void sqlAssessmentV2OperationsCreateMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.sqlAssessmentV2Operations() + .define("test_swagger_1") + .withExistingGroup("rgmigrate", "fci-test6904project", "test_fci_hadr") + .withProperties(new SqlAssessmentV2Properties().withOsLicense(OsLicense.UNKNOWN) + .withEnvironmentType(EnvironmentType.PRODUCTION) + .withEntityUptime(new EntityUptime().withDaysPerMonth(30).withHoursPerDay(24)) + .withOptimizationLogic(OptimizationLogic.MINIMIZE_COST) + .withReservedInstanceForVm(AzureReservedInstance.NONE) + .withAzureOfferCodeForVm(AzureOfferCode.MSAZR0003P) + .withAzureSqlManagedInstanceSettings( + new SqlMiSettings().withAzureSqlServiceTier(AzureSqlServiceTier.AUTOMATIC) + .withAzureSqlInstanceType(AzureSqlInstanceType.SINGLE_INSTANCE)) + .withAzureSqlDatabaseSettings(new SqlDbSettings().withAzureSqlServiceTier(AzureSqlServiceTier.AUTOMATIC) + .withAzureSqlDataBaseType(AzureSqlDataBaseType.SINGLE_DATABASE) + .withAzureSqlComputeTier(ComputeTier.AUTOMATIC) + .withAzureSqlPurchaseModel(AzureSqlPurchaseModel.VCORE)) + .withAzureSqlVmSettings( + new SqlVmSettings().withInstanceSeries(Arrays.asList(AzureVmFamily.EADSV5_SERIES))) + .withMultiSubnetIntent(MultiSubnetIntent.DISASTER_RECOVERY) + .withAsyncCommitModeIntent(AsyncCommitModeIntent.DISASTER_RECOVERY) + .withDisasterRecoveryLocation(AzureLocation.EAST_ASIA) + .withEnableHadrAssessment(true) + .withReservedInstance(AzureReservedInstance.NONE) + .withSqlServerLicense(SqlServerLicense.UNKNOWN) + .withAzureLocation("SoutheastAsia") + .withAzureOfferCode(AzureOfferCode.MSAZR0003P) + .withCurrency(AzureCurrency.USD) + .withScalingFactor(1.0F) + .withPercentile(Percentile.PERCENTILE95) + .withTimeRange(TimeRange.DAY) + .withDiscountPercentage(0.0F) + .withSizingCriterion(AssessmentSizingCriterion.PERFORMANCE_BASED)) + .create(); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2OperationsDeleteSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2OperationsDeleteSamples.java new file mode 100644 index 000000000000..66bee781f104 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2OperationsDeleteSamples.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for SqlAssessmentV2Operations Delete. + */ +public final class SqlAssessmentV2OperationsDeleteSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * SqlAssessmentV2Operations_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: SqlAssessmentV2Operations_Delete_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void sqlAssessmentV2OperationsDeleteMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.sqlAssessmentV2Operations() + .deleteWithResponse("rgmigrate", "fci-test6904project", "test_fci_hadr", "test_swagger_1", + com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2OperationsDownloadUrlSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2OperationsDownloadUrlSamples.java new file mode 100644 index 000000000000..24bd2fd8d879 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2OperationsDownloadUrlSamples.java @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.management.serializer.SerializerFactory; +import com.azure.core.util.serializer.SerializerEncoding; +import java.io.IOException; + +/** + * Samples for SqlAssessmentV2Operations DownloadUrl. + */ +public final class SqlAssessmentV2OperationsDownloadUrlSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * SqlAssessmentV2Operations_DownloadUrl_MaximumSet_Gen.json + */ + /** + * Sample code: SqlAssessmentV2Operations_DownloadUrl_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void sqlAssessmentV2OperationsDownloadUrlMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) throws IOException { + manager.sqlAssessmentV2Operations() + .downloadUrl("rgmigrate", "fci-test6904project", "test_fci_hadr", "test_swagger_1", + SerializerFactory.createDefaultManagementSerializerAdapter() + .deserialize("{}", Object.class, SerializerEncoding.JSON), + com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2OperationsGetSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2OperationsGetSamples.java new file mode 100644 index 000000000000..5673e9232691 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2OperationsGetSamples.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for SqlAssessmentV2Operations Get. + */ +public final class SqlAssessmentV2OperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * SqlAssessmentV2Operations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: SqlAssessmentV2Operations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void sqlAssessmentV2OperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.sqlAssessmentV2Operations() + .getWithResponse("rgmigrate", "fci-test6904project", "test_fci_hadr", "test_swagger_1", + com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2OperationsListByGroupSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2OperationsListByGroupSamples.java new file mode 100644 index 000000000000..d7a998cc6f12 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2OperationsListByGroupSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for SqlAssessmentV2Operations ListByGroup. + */ +public final class SqlAssessmentV2OperationsListByGroupSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * SqlAssessmentV2Operations_ListByGroup_MaximumSet_Gen.json + */ + /** + * Sample code: SqlAssessmentV2Operations_ListByGroup_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void sqlAssessmentV2OperationsListByGroupMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.sqlAssessmentV2Operations() + .listByGroup("rgmigrate", "fci-test6904project", "test_fci_hadr", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2SummaryOperationsGetSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2SummaryOperationsGetSamples.java new file mode 100644 index 000000000000..b8d604d61b2f --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2SummaryOperationsGetSamples.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for SqlAssessmentV2SummaryOperations Get. + */ +public final class SqlAssessmentV2SummaryOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * SqlAssessmentV2SummaryOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: SqlAssessmentV2SummaryOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void sqlAssessmentV2SummaryOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.sqlAssessmentV2SummaryOperations() + .getWithResponse("rgmigrate", "fci-test6904project", "test_fci_hadr", "test_swagger_1", "default", + com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2SummaryOperationsListBySqlAssessmentV2Samples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2SummaryOperationsListBySqlAssessmentV2Samples.java new file mode 100644 index 000000000000..187efbd26f86 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2SummaryOperationsListBySqlAssessmentV2Samples.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for SqlAssessmentV2SummaryOperations ListBySqlAssessmentV2. + */ +public final class SqlAssessmentV2SummaryOperationsListBySqlAssessmentV2Samples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * SqlAssessmentV2SummaryOperations_ListBySqlAssessmentV2_MaximumSet_Gen.json + */ + /** + * Sample code: SqlAssessmentV2SummaryOperations_ListBySqlAssessmentV2_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void sqlAssessmentV2SummaryOperationsListBySqlAssessmentV2MaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.sqlAssessmentV2SummaryOperations() + .listBySqlAssessmentV2("rgmigrate", "fci-test6904project", "test_fci_hadr", "test_swagger_1", + com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorOperationsCreateSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorOperationsCreateSamples.java new file mode 100644 index 000000000000..c226a9dabbdc --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorOperationsCreateSamples.java @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentSpnPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBaseWithAgent; + +/** + * Samples for SqlCollectorOperations Create. + */ +public final class SqlCollectorOperationsCreateSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * SqlCollectorOperations_Create_MaximumSet_Gen.json + */ + /** + * Sample code: SqlCollectorOperations_Create_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void sqlCollectorOperationsCreateMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.sqlCollectorOperations() + .define("fci-test0c1esqlsitecollector") + .withExistingAssessmentProject("rgmigrate", "fci-test6904project") + .withProperties(new CollectorPropertiesBaseWithAgent() + .withAgentProperties( + new CollectorAgentPropertiesBase().withId("630da710-4d44-41f7-a189-72fe3db5502b-agent") + .withSpnDetails(new CollectorAgentSpnPropertiesBase() + .withAuthority("https://login.windows.net/72f988bf-86f1-41af-91ab-2d7cd011db47") + .withApplicationId("db9c4c3d-477c-4d5a-817b-318276713565") + .withAudience("db9c4c3d-477c-4d5a-817b-318276713565") + .withObjectId("e50236ad-ad07-47d4-af71-ed7b52d200d5") + .withTenantId("72f988bf-86f1-41af-91ab-2d7cd011db47"))) + .withDiscoverySiteId( + "/subscriptions/4bd2aa0f-2bd2-4d67-91a8-5a4533d58600/resourceGroups/bansalankit-rg/providers/Microsoft.OffAzure/MasterSites/fci-ankit-test6065mastersite/SqlSites/fci-ankit-test6065sqlsites")) + .create(); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorOperationsDeleteSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorOperationsDeleteSamples.java new file mode 100644 index 000000000000..1a7627fbbb63 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorOperationsDeleteSamples.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for SqlCollectorOperations Delete. + */ +public final class SqlCollectorOperationsDeleteSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * SqlCollectorOperations_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: SqlCollectorOperations_Delete_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void sqlCollectorOperationsDeleteMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.sqlCollectorOperations() + .deleteWithResponse("rgmigrate", "fci-test6904project", "fci-test0c1esqlsitecollector", + com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorOperationsGetSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorOperationsGetSamples.java new file mode 100644 index 000000000000..b86ea4aa872f --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorOperationsGetSamples.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for SqlCollectorOperations Get. + */ +public final class SqlCollectorOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * SqlCollectorOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: SqlCollectorOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void sqlCollectorOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.sqlCollectorOperations() + .getWithResponse("rgmigrate", "fci-test6904project", "fci-test0c1esqlsitecollector", + com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorOperationsListByAssessmentProjectSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorOperationsListByAssessmentProjectSamples.java new file mode 100644 index 000000000000..862991feb6df --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorOperationsListByAssessmentProjectSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for SqlCollectorOperations ListByAssessmentProject. + */ +public final class SqlCollectorOperationsListByAssessmentProjectSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * SqlCollectorOperations_ListByAssessmentProject_MaximumSet_Gen.json + */ + /** + * Sample code: SqlCollectorOperations_ListByAssessmentProject_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void sqlCollectorOperationsListByAssessmentProjectMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.sqlCollectorOperations() + .listByAssessmentProject("rgmigrate", "fci-test6904project", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorsOperationsCreateSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorsOperationsCreateSamples.java new file mode 100644 index 000000000000..dfea5c739234 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorsOperationsCreateSamples.java @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentSpnPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBaseWithAgent; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.time.OffsetDateTime; + +/** + * Samples for VmwareCollectorsOperations Create. + */ +public final class VmwareCollectorsOperationsCreateSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * VmwareCollectorsOperations_Create_MaximumSet_Gen.json + */ + /** + * Sample code: VmwareCollectorsOperations_Create_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void vmwareCollectorsOperationsCreateMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.vmwareCollectorsOperations() + .define("Vmware2258collector") + .withExistingAssessmentProject("ayagrawRG", "app18700project") + .withProperties(new CollectorPropertiesBaseWithAgent().withProvisioningState(ProvisioningState.SUCCEEDED) + .withAgentProperties(new CollectorAgentPropertiesBase().withId("fe243486-3318-41fa-aaba-c48b5df75308") + .withVersion("1.0.8.383") + .withLastHeartbeatUtc(OffsetDateTime.parse("2022-03-29T12:10:08.9167289Z")) + .withSpnDetails(new CollectorAgentSpnPropertiesBase() + .withAuthority("https://login.windows.net/72f988bf-86f1-41af-91ab-2d7cd011db47") + .withApplicationId("82b3e452-c0e8-4662-8347-58282925ae84") + .withAudience("82b3e452-c0e8-4662-8347-58282925ae84") + .withObjectId("3fc89111-1405-4938-9214-37aa4739401d") + .withTenantId("72f988bf-86f1-41af-91ab-2d7cd011db47"))) + .withDiscoverySiteId( + "/subscriptions/4bd2aa0f-2bd2-4d67-91a8-5a4533d58600/resourceGroups/ayagrawRG/providers/Microsoft.OffAzure/VMwareSites/Vmware2744site")) + .create(); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorsOperationsDeleteSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorsOperationsDeleteSamples.java new file mode 100644 index 000000000000..6899e3f9c5ac --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorsOperationsDeleteSamples.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for VmwareCollectorsOperations Delete. + */ +public final class VmwareCollectorsOperationsDeleteSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * VmwareCollectorsOperations_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: VmwareCollectorsOperations_Delete_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void vmwareCollectorsOperationsDeleteMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.vmwareCollectorsOperations() + .deleteWithResponse("ayagrawRG", "app18700project", "Vmware2258collector", + com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorsOperationsGetSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorsOperationsGetSamples.java new file mode 100644 index 000000000000..2adc71019f10 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorsOperationsGetSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for VmwareCollectorsOperations Get. + */ +public final class VmwareCollectorsOperationsGetSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * VmwareCollectorsOperations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: VmwareCollectorsOperations_Get_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void vmwareCollectorsOperationsGetMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.vmwareCollectorsOperations() + .getWithResponse("ayagrawRG", "app18700project", "Vmware2258collector", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorsOperationsListByAssessmentProjectSamples.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorsOperationsListByAssessmentProjectSamples.java new file mode 100644 index 000000000000..4d34357d7b49 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/samples/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorsOperationsListByAssessmentProjectSamples.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +/** + * Samples for VmwareCollectorsOperations ListByAssessmentProject. + */ +public final class VmwareCollectorsOperationsListByAssessmentProjectSamples { + /* + * x-ms-original-file: + * specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects/stable/2023-03-15/examples/ + * VmwareCollectorsOperations_ListByAssessmentProject_MaximumSet_Gen.json + */ + /** + * Sample code: VmwareCollectorsOperations_ListByAssessmentProject_MaximumSet_Gen. + * + * @param manager Entry point to MigrationAssessmentManager. + */ + public static void vmwareCollectorsOperationsListByAssessmentProjectMaximumSetGen( + com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager manager) { + manager.vmwareCollectorsOperations() + .listByAssessmentProject("ayagrawRG", "app18700project", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedDiskDataTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedDiskDataTests.java new file mode 100644 index 000000000000..e1ab33884bfc --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedDiskDataTests.java @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.AssessedDiskData; +import com.azure.resourcemanager.migration.assessment.models.AzureDiskSize; +import com.azure.resourcemanager.migration.assessment.models.AzureDiskSuitabilityDetail; +import com.azure.resourcemanager.migration.assessment.models.AzureDiskSuitabilityExplanation; +import com.azure.resourcemanager.migration.assessment.models.AzureDiskType; +import com.azure.resourcemanager.migration.assessment.models.CloudSuitability; +import org.junit.jupiter.api.Assertions; + +public final class AssessedDiskDataTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AssessedDiskData model = BinaryData.fromString( + "{\"suitability\":\"NotSuitable\",\"suitabilityExplanation\":\"NoEaPriceFoundForDiskSize\",\"suitabilityDetail\":\"MegabytesPerSecondOfWriteOutOfRange\",\"recommendedDiskSize\":\"StandardSSD_E1\",\"recommendedDiskType\":\"PremiumV2\",\"recommendedDiskSizeGigabytes\":1924185709,\"recommendDiskThroughputInMbps\":77.596115,\"recommendedDiskIops\":28.821247,\"monthlyStorageCost\":46.197742,\"name\":\"cgx\",\"displayName\":\"csserxht\",\"gigabytesProvisioned\":27.112644,\"megabytesPerSecondOfRead\":51.11168,\"megabytesPerSecondOfWrite\":64.434204,\"numberOfReadOperationsPerSecond\":45.264824,\"numberOfWriteOperationsPerSecond\":3.874898}") + .toObject(AssessedDiskData.class); + Assertions.assertEquals(CloudSuitability.NOT_SUITABLE, model.suitability()); + Assertions.assertEquals(AzureDiskSuitabilityExplanation.NO_EA_PRICE_FOUND_FOR_DISK_SIZE, + model.suitabilityExplanation()); + Assertions.assertEquals(AzureDiskSuitabilityDetail.MEGABYTES_PER_SECOND_OF_WRITE_OUT_OF_RANGE, + model.suitabilityDetail()); + Assertions.assertEquals(AzureDiskSize.STANDARD_SSD_E1, model.recommendedDiskSize()); + Assertions.assertEquals(AzureDiskType.PREMIUM_V2, model.recommendedDiskType()); + Assertions.assertEquals(1924185709, model.recommendedDiskSizeGigabytes()); + Assertions.assertEquals(77.596115F, model.recommendDiskThroughputInMbps()); + Assertions.assertEquals(28.821247F, model.recommendedDiskIops()); + Assertions.assertEquals(46.197742F, model.monthlyStorageCost()); + Assertions.assertEquals("cgx", model.name()); + Assertions.assertEquals("csserxht", model.displayName()); + Assertions.assertEquals(27.112644F, model.gigabytesProvisioned()); + Assertions.assertEquals(51.11168F, model.megabytesPerSecondOfRead()); + Assertions.assertEquals(64.434204F, model.megabytesPerSecondOfWrite()); + Assertions.assertEquals(45.264824F, model.numberOfReadOperationsPerSecond()); + Assertions.assertEquals(3.874898F, model.numberOfWriteOperationsPerSecond()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AssessedDiskData model = new AssessedDiskData().withSuitability(CloudSuitability.NOT_SUITABLE) + .withSuitabilityExplanation(AzureDiskSuitabilityExplanation.NO_EA_PRICE_FOUND_FOR_DISK_SIZE) + .withSuitabilityDetail(AzureDiskSuitabilityDetail.MEGABYTES_PER_SECOND_OF_WRITE_OUT_OF_RANGE) + .withRecommendedDiskSize(AzureDiskSize.STANDARD_SSD_E1) + .withRecommendedDiskType(AzureDiskType.PREMIUM_V2) + .withRecommendedDiskSizeGigabytes(1924185709) + .withRecommendDiskThroughputInMbps(77.596115F) + .withRecommendedDiskIops(28.821247F) + .withMonthlyStorageCost(46.197742F) + .withName("cgx") + .withDisplayName("csserxht") + .withGigabytesProvisioned(27.112644F) + .withMegabytesPerSecondOfRead(51.11168F) + .withMegabytesPerSecondOfWrite(64.434204F) + .withNumberOfReadOperationsPerSecond(45.264824F) + .withNumberOfWriteOperationsPerSecond(3.874898F); + model = BinaryData.fromObject(model).toObject(AssessedDiskData.class); + Assertions.assertEquals(CloudSuitability.NOT_SUITABLE, model.suitability()); + Assertions.assertEquals(AzureDiskSuitabilityExplanation.NO_EA_PRICE_FOUND_FOR_DISK_SIZE, + model.suitabilityExplanation()); + Assertions.assertEquals(AzureDiskSuitabilityDetail.MEGABYTES_PER_SECOND_OF_WRITE_OUT_OF_RANGE, + model.suitabilityDetail()); + Assertions.assertEquals(AzureDiskSize.STANDARD_SSD_E1, model.recommendedDiskSize()); + Assertions.assertEquals(AzureDiskType.PREMIUM_V2, model.recommendedDiskType()); + Assertions.assertEquals(1924185709, model.recommendedDiskSizeGigabytes()); + Assertions.assertEquals(77.596115F, model.recommendDiskThroughputInMbps()); + Assertions.assertEquals(28.821247F, model.recommendedDiskIops()); + Assertions.assertEquals(46.197742F, model.monthlyStorageCost()); + Assertions.assertEquals("cgx", model.name()); + Assertions.assertEquals("csserxht", model.displayName()); + Assertions.assertEquals(27.112644F, model.gigabytesProvisioned()); + Assertions.assertEquals(51.11168F, model.megabytesPerSecondOfRead()); + Assertions.assertEquals(64.434204F, model.megabytesPerSecondOfWrite()); + Assertions.assertEquals(45.264824F, model.numberOfReadOperationsPerSecond()); + Assertions.assertEquals(3.874898F, model.numberOfWriteOperationsPerSecond()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedDiskTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedDiskTests.java new file mode 100644 index 000000000000..206206e931f7 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedDiskTests.java @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.AssessedDisk; +import com.azure.resourcemanager.migration.assessment.models.AzureDiskSize; +import com.azure.resourcemanager.migration.assessment.models.AzureDiskSuitabilityDetail; +import com.azure.resourcemanager.migration.assessment.models.AzureDiskSuitabilityExplanation; +import com.azure.resourcemanager.migration.assessment.models.AzureDiskType; +import com.azure.resourcemanager.migration.assessment.models.CloudSuitability; +import org.junit.jupiter.api.Assertions; + +public final class AssessedDiskTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AssessedDisk model = BinaryData.fromString( + "{\"suitability\":\"Unknown\",\"suitabilityExplanation\":\"NoDiskSizeFoundForSelectedRedundancy\",\"suitabilityDetail\":\"MegabytesPerSecondOfWriteMissing\",\"recommendedDiskSize\":\"Premium_P1\",\"recommendedDiskType\":\"StandardOrPremium\",\"gigabytesForRecommendedDiskSize\":1182920658,\"recommendDiskThroughputInMbps\":6.1038675,\"recommendedDiskIops\":32.54612,\"monthlyStorageCost\":30.48998,\"name\":\"qkacewii\",\"displayName\":\"pubjibw\",\"gigabytesProvisioned\":5.9326353,\"megabytesPerSecondOfRead\":86.60929,\"megabytesPerSecondOfWrite\":90.61733,\"numberOfReadOperationsPerSecond\":31.865799,\"numberOfWriteOperationsPerSecond\":99.55644}") + .toObject(AssessedDisk.class); + Assertions.assertEquals(CloudSuitability.UNKNOWN, model.suitability()); + Assertions.assertEquals(AzureDiskSuitabilityExplanation.NO_DISK_SIZE_FOUND_FOR_SELECTED_REDUNDANCY, + model.suitabilityExplanation()); + Assertions.assertEquals(AzureDiskSuitabilityDetail.MEGABYTES_PER_SECOND_OF_WRITE_MISSING, + model.suitabilityDetail()); + Assertions.assertEquals(AzureDiskSize.PREMIUM_P1, model.recommendedDiskSize()); + Assertions.assertEquals(AzureDiskType.STANDARD_OR_PREMIUM, model.recommendedDiskType()); + Assertions.assertEquals(1182920658, model.gigabytesForRecommendedDiskSize()); + Assertions.assertEquals(6.1038675F, model.recommendDiskThroughputInMbps()); + Assertions.assertEquals(32.54612F, model.recommendedDiskIops()); + Assertions.assertEquals(30.48998F, model.monthlyStorageCost()); + Assertions.assertEquals("qkacewii", model.name()); + Assertions.assertEquals("pubjibw", model.displayName()); + Assertions.assertEquals(5.9326353F, model.gigabytesProvisioned()); + Assertions.assertEquals(86.60929F, model.megabytesPerSecondOfRead()); + Assertions.assertEquals(90.61733F, model.megabytesPerSecondOfWrite()); + Assertions.assertEquals(31.865799F, model.numberOfReadOperationsPerSecond()); + Assertions.assertEquals(99.55644F, model.numberOfWriteOperationsPerSecond()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AssessedDisk model = new AssessedDisk().withSuitability(CloudSuitability.UNKNOWN) + .withSuitabilityExplanation(AzureDiskSuitabilityExplanation.NO_DISK_SIZE_FOUND_FOR_SELECTED_REDUNDANCY) + .withSuitabilityDetail(AzureDiskSuitabilityDetail.MEGABYTES_PER_SECOND_OF_WRITE_MISSING) + .withRecommendedDiskSize(AzureDiskSize.PREMIUM_P1) + .withRecommendedDiskType(AzureDiskType.STANDARD_OR_PREMIUM) + .withGigabytesForRecommendedDiskSize(1182920658) + .withRecommendDiskThroughputInMbps(6.1038675F) + .withRecommendedDiskIops(32.54612F) + .withMonthlyStorageCost(30.48998F) + .withName("qkacewii") + .withDisplayName("pubjibw") + .withGigabytesProvisioned(5.9326353F) + .withMegabytesPerSecondOfRead(86.60929F) + .withMegabytesPerSecondOfWrite(90.61733F) + .withNumberOfReadOperationsPerSecond(31.865799F) + .withNumberOfWriteOperationsPerSecond(99.55644F); + model = BinaryData.fromObject(model).toObject(AssessedDisk.class); + Assertions.assertEquals(CloudSuitability.UNKNOWN, model.suitability()); + Assertions.assertEquals(AzureDiskSuitabilityExplanation.NO_DISK_SIZE_FOUND_FOR_SELECTED_REDUNDANCY, + model.suitabilityExplanation()); + Assertions.assertEquals(AzureDiskSuitabilityDetail.MEGABYTES_PER_SECOND_OF_WRITE_MISSING, + model.suitabilityDetail()); + Assertions.assertEquals(AzureDiskSize.PREMIUM_P1, model.recommendedDiskSize()); + Assertions.assertEquals(AzureDiskType.STANDARD_OR_PREMIUM, model.recommendedDiskType()); + Assertions.assertEquals(1182920658, model.gigabytesForRecommendedDiskSize()); + Assertions.assertEquals(6.1038675F, model.recommendDiskThroughputInMbps()); + Assertions.assertEquals(32.54612F, model.recommendedDiskIops()); + Assertions.assertEquals(30.48998F, model.monthlyStorageCost()); + Assertions.assertEquals("qkacewii", model.name()); + Assertions.assertEquals("pubjibw", model.displayName()); + Assertions.assertEquals(5.9326353F, model.gigabytesProvisioned()); + Assertions.assertEquals(86.60929F, model.megabytesPerSecondOfRead()); + Assertions.assertEquals(90.61733F, model.megabytesPerSecondOfWrite()); + Assertions.assertEquals(31.865799F, model.numberOfReadOperationsPerSecond()); + Assertions.assertEquals(99.55644F, model.numberOfWriteOperationsPerSecond()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedNetworkAdapterTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedNetworkAdapterTests.java new file mode 100644 index 000000000000..ed1764fcbbec --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedNetworkAdapterTests.java @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.AssessedNetworkAdapter; +import com.azure.resourcemanager.migration.assessment.models.AzureNetworkAdapterSuitabilityDetail; +import com.azure.resourcemanager.migration.assessment.models.AzureNetworkAdapterSuitabilityExplanation; +import com.azure.resourcemanager.migration.assessment.models.CloudSuitability; +import org.junit.jupiter.api.Assertions; + +public final class AssessedNetworkAdapterTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AssessedNetworkAdapter model = BinaryData.fromString( + "{\"suitability\":\"Unknown\",\"suitabilityDetail\":\"MegabytesOfDataRecievedOutOfRange\",\"suitabilityExplanation\":\"Unknown\",\"monthlyBandwidthCosts\":82.95103,\"netGigabytesTransmittedPerMonth\":64.28258,\"displayName\":\"mibzyhwitsmypyyn\",\"macAddress\":\"dpumnzgmw\",\"ipAddresses\":[\"abikns\",\"rgjhxb\",\"dtlwwrlkd\",\"tncvokot\"],\"megabytesPerSecondReceived\":14.993447,\"megabytesPerSecondTransmitted\":25.275595}") + .toObject(AssessedNetworkAdapter.class); + Assertions.assertEquals(CloudSuitability.UNKNOWN, model.suitability()); + Assertions.assertEquals(AzureNetworkAdapterSuitabilityDetail.MEGABYTES_OF_DATA_RECIEVED_OUT_OF_RANGE, + model.suitabilityDetail()); + Assertions.assertEquals(AzureNetworkAdapterSuitabilityExplanation.UNKNOWN, model.suitabilityExplanation()); + Assertions.assertEquals(82.95103F, model.monthlyBandwidthCosts()); + Assertions.assertEquals(64.28258F, model.netGigabytesTransmittedPerMonth()); + Assertions.assertEquals("mibzyhwitsmypyyn", model.displayName()); + Assertions.assertEquals("dpumnzgmw", model.macAddress()); + Assertions.assertEquals(14.993447F, model.megabytesPerSecondReceived()); + Assertions.assertEquals(25.275595F, model.megabytesPerSecondTransmitted()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AssessedNetworkAdapter model = new AssessedNetworkAdapter().withSuitability(CloudSuitability.UNKNOWN) + .withSuitabilityDetail(AzureNetworkAdapterSuitabilityDetail.MEGABYTES_OF_DATA_RECIEVED_OUT_OF_RANGE) + .withSuitabilityExplanation(AzureNetworkAdapterSuitabilityExplanation.UNKNOWN) + .withMonthlyBandwidthCosts(82.95103F) + .withNetGigabytesTransmittedPerMonth(64.28258F) + .withDisplayName("mibzyhwitsmypyyn") + .withMacAddress("dpumnzgmw") + .withMegabytesPerSecondReceived(14.993447F) + .withMegabytesPerSecondTransmitted(25.275595F); + model = BinaryData.fromObject(model).toObject(AssessedNetworkAdapter.class); + Assertions.assertEquals(CloudSuitability.UNKNOWN, model.suitability()); + Assertions.assertEquals(AzureNetworkAdapterSuitabilityDetail.MEGABYTES_OF_DATA_RECIEVED_OUT_OF_RANGE, + model.suitabilityDetail()); + Assertions.assertEquals(AzureNetworkAdapterSuitabilityExplanation.UNKNOWN, model.suitabilityExplanation()); + Assertions.assertEquals(82.95103F, model.monthlyBandwidthCosts()); + Assertions.assertEquals(64.28258F, model.netGigabytesTransmittedPerMonth()); + Assertions.assertEquals("mibzyhwitsmypyyn", model.displayName()); + Assertions.assertEquals("dpumnzgmw", model.macAddress()); + Assertions.assertEquals(14.993447F, model.megabytesPerSecondReceived()); + Assertions.assertEquals(25.275595F, model.megabytesPerSecondTransmitted()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlDatabaseV2InnerTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlDatabaseV2InnerTests.java new file mode 100644 index 000000000000..081767b87ce8 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlDatabaseV2InnerTests.java @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlDatabaseV2Inner; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlDatabaseV2Properties; + +public final class AssessedSqlDatabaseV2InnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AssessedSqlDatabaseV2Inner model = BinaryData.fromString( + "{\"properties\":{\"recommendedAzureSqlTargetType\":\"AzureSqlManagedInstance\",\"recommendedSuitability\":\"ConditionallySuitableForSqlMI\",\"bufferCacheSizeInMB\":95.6737,\"productSupportStatus\":{\"currentVersion\":\"emhzrncsdtc\",\"servicePackStatus\":\"siypbs\",\"esuStatus\":\"ytguslf\",\"supportStatus\":\"dcygqukyhejhz\",\"eta\":581237500,\"currentEsuYear\":\"fpel\",\"mainstreamEndDate\":\"2021-01-25T06:01:21Z\",\"extendedSupportEndDate\":\"2021-12-10T20:32:17Z\",\"extendedSecurityUpdateYear1EndDate\":\"2021-01-11T13:41:06Z\",\"extendedSecurityUpdateYear2EndDate\":\"2021-08-16T07:12:35Z\",\"extendedSecurityUpdateYear3EndDate\":\"2021-02-05T20:48:24Z\"},\"azureSqlMISuitabilityDetails\":{\"azureSqlSku\":{\"azureSqlServiceTier\":\"Automatic\",\"azureSqlComputeTier\":\"Provisioned\",\"azureSqlHardwareGeneration\":\"Fsv2_series\",\"storageMaxSizeInMB\":12.180108,\"predictedDataSizeInMB\":5.453616,\"predictedLogSizeInMB\":36.356728,\"cores\":575939452,\"azureSqlTargetType\":\"AzureSqlDatabase\"},\"replicaAzureSqlSku\":[{\"azureSqlServiceTier\":\"Unknown\",\"azureSqlComputeTier\":\"Serverless\",\"azureSqlHardwareGeneration\":\"Fsv2_series\",\"storageMaxSizeInMB\":62.17856,\"predictedDataSizeInMB\":4.802215,\"predictedLogSizeInMB\":53.193123,\"cores\":1289831716,\"azureSqlTargetType\":\"AzureSqlManagedInstance\"},{\"azureSqlServiceTier\":\"BusinessCritical\",\"azureSqlComputeTier\":\"Provisioned\",\"azureSqlHardwareGeneration\":\"DC_series\",\"storageMaxSizeInMB\":81.58153,\"predictedDataSizeInMB\":52.03357,\"predictedLogSizeInMB\":65.96141,\"cores\":1900639449,\"azureSqlTargetType\":\"AzureVirtualMachine\"},{\"azureSqlServiceTier\":\"Unknown\",\"azureSqlComputeTier\":\"Serverless\",\"azureSqlHardwareGeneration\":\"Automatic\",\"storageMaxSizeInMB\":72.981895,\"predictedDataSizeInMB\":15.099293,\"predictedLogSizeInMB\":58.360874,\"cores\":424916927,\"azureSqlTargetType\":\"Recommended\"}],\"sharedResources\":{\"sharedDataDisks\":[{\"diskType\":\"StandardSSD\",\"diskSize\":\"StandardSSD_E80\",\"diskRedundancy\":\"LRS\",\"storageCost\":37.895233,\"recommendedSizeInGib\":19.479061,\"recommendedThroughputInMbps\":44.50355,\"recommendedIops\":75.07999},{\"diskType\":\"Standard\",\"diskSize\":\"StandardSSD_E3\",\"diskRedundancy\":\"Unknown\",\"storageCost\":94.36649,\"recommendedSizeInGib\":75.4705,\"recommendedThroughputInMbps\":77.55793,\"recommendedIops\":75.26911},{\"diskType\":\"Unknown\",\"diskSize\":\"Standard_S20\",\"diskRedundancy\":\"ZRS\",\"storageCost\":97.41935,\"recommendedSizeInGib\":40.128662,\"recommendedThroughputInMbps\":71.87891,\"recommendedIops\":60.886276}],\"sharedLogDisks\":[{\"diskType\":\"Standard\",\"diskSize\":\"Standard_S10\",\"diskRedundancy\":\"ZRS\",\"storageCost\":39.502205,\"recommendedSizeInGib\":43.626587,\"recommendedThroughputInMbps\":44.605457,\"recommendedIops\":72.386024}],\"sharedTempDbDisks\":[{\"diskType\":\"StandardSSD\",\"diskSize\":\"Standard_S50\",\"diskRedundancy\":\"LRS\",\"storageCost\":74.9261,\"recommendedSizeInGib\":11.313396,\"recommendedThroughputInMbps\":51.734554,\"recommendedIops\":34.290314}],\"numberOfMounts\":1155749150,\"quorumWitness\":{\"quorumWitnessType\":\"Disk\"}},\"monthlyComputeCost\":22.147728,\"monthlyStorageCost\":30.854982,\"costComponents\":[{\"name\":\"MonthlyAzureHybridCostSavings\",\"value\":5.4647923,\"description\":\"j\"},{\"name\":\"MonthlyPremiumV2StorageCost\",\"value\":76.01796,\"description\":\"zs\"},{\"name\":\"MonthlyPremiumV2StorageCost\",\"value\":85.62009,\"description\":\"ystawfsdjpvkvp\"}],\"securitySuitability\":\"Suitable\",\"shouldProvisionReplicas\":true,\"skuReplicationMode\":\"NotApplicable\",\"migrationGuidelines\":[{\"guidelineId\":\"vncjabudurgk\",\"migrationGuidelineCategory\":\"FailoverCluterInstanceGuideLine\",\"migrationGuidelineContext\":[{},{}]}],\"recommendationReasonings\":[{\"reasoningId\":\"jk\",\"reasoningString\":\"fhmouwq\",\"reasoningCategory\":\"zrfze\",\"contextParameters\":[{},{},{}]},{\"reasoningId\":\"izikayuhq\",\"reasoningString\":\"jbsybbqw\",\"reasoningCategory\":\"t\",\"contextParameters\":[{},{}]}],\"migrationTargetPlatform\":\"AzureSqlVirtualMachine\",\"suitability\":\"NotSuitable\",\"migrationIssues\":[{\"issueId\":\"ipaslthaqfxssmwu\",\"issueCategory\":\"Warning\",\"impactedObjects\":[{},{}]},{\"issueId\":\"ezpdrhneu\",\"issueCategory\":\"Warning\",\"impactedObjects\":[{}]},{\"issueId\":\"wyt\",\"issueCategory\":\"Issue\",\"impactedObjects\":[{},{},{}]},{\"issueId\":\"cgpik\",\"issueCategory\":\"Warning\",\"impactedObjects\":[{},{}]}]},\"azureSqlDBSuitabilityDetails\":{\"azureSqlSku\":{\"azureSqlServiceTier\":\"Automatic\",\"azureSqlComputeTier\":\"Provisioned\",\"azureSqlHardwareGeneration\":\"Fsv2_series\",\"storageMaxSizeInMB\":9.00774,\"predictedDataSizeInMB\":30.19936,\"predictedLogSizeInMB\":35.2318,\"cores\":944928815,\"azureSqlTargetType\":\"Recommended\"},\"replicaAzureSqlSku\":[{\"azureSqlServiceTier\":\"Unknown\",\"azureSqlComputeTier\":\"Unknown\",\"azureSqlHardwareGeneration\":\"Gen5\",\"storageMaxSizeInMB\":39.849525,\"predictedDataSizeInMB\":48.917915,\"predictedLogSizeInMB\":56.03118,\"cores\":1689158951,\"azureSqlTargetType\":\"AzureSqlManagedInstance\"}],\"sharedResources\":{\"sharedDataDisks\":[{\"diskType\":\"StandardOrPremium\",\"diskSize\":\"Premium_P10\",\"diskRedundancy\":\"Unknown\",\"storageCost\":14.39516,\"recommendedSizeInGib\":11.801916,\"recommendedThroughputInMbps\":96.64042,\"recommendedIops\":73.455444},{\"diskType\":\"PremiumV2\",\"diskSize\":\"StandardSSD_E80\",\"diskRedundancy\":\"LRS\",\"storageCost\":20.986683,\"recommendedSizeInGib\":37.539448,\"recommendedThroughputInMbps\":83.09367,\"recommendedIops\":85.45392}],\"sharedLogDisks\":[{\"diskType\":\"PremiumV2\",\"diskSize\":\"Premium_P60\",\"diskRedundancy\":\"LRS\",\"storageCost\":71.96245,\"recommendedSizeInGib\":71.89114,\"recommendedThroughputInMbps\":66.963486,\"recommendedIops\":16.782505},{\"diskType\":\"Standard\",\"diskSize\":\"Premium_P1\",\"diskRedundancy\":\"LRS\",\"storageCost\":80.275826,\"recommendedSizeInGib\":38.60216,\"recommendedThroughputInMbps\":11.96838,\"recommendedIops\":65.46099},{\"diskType\":\"Standard\",\"diskSize\":\"StandardSSD_E15\",\"diskRedundancy\":\"Unknown\",\"storageCost\":11.107027,\"recommendedSizeInGib\":82.047585,\"recommendedThroughputInMbps\":79.98476,\"recommendedIops\":10.109133},{\"diskType\":\"Premium\",\"diskSize\":\"Premium_P4\",\"diskRedundancy\":\"Unknown\",\"storageCost\":72.32076,\"recommendedSizeInGib\":31.32779,\"recommendedThroughputInMbps\":24.433767,\"recommendedIops\":16.203457}],\"sharedTempDbDisks\":[{\"diskType\":\"Unknown\",\"diskSize\":\"StandardSSD_E70\",\"diskRedundancy\":\"LRS\",\"storageCost\":47.469883,\"recommendedSizeInGib\":92.05685,\"recommendedThroughputInMbps\":15.483612,\"recommendedIops\":44.862534},{\"diskType\":\"PremiumV2\",\"diskSize\":\"Premium_P60\",\"diskRedundancy\":\"ZRS\",\"storageCost\":74.29807,\"recommendedSizeInGib\":89.42535,\"recommendedThroughputInMbps\":37.61905,\"recommendedIops\":66.83891}],\"numberOfMounts\":1490533084,\"quorumWitness\":{\"quorumWitnessType\":\"Disk\"}},\"monthlyComputeCost\":24.22722,\"monthlyStorageCost\":76.98546,\"costComponents\":[{\"name\":\"MonthlyPremiumV2StorageCost\",\"value\":12.315064,\"description\":\"hwhbotzingamv\"},{\"name\":\"Unknown\",\"value\":70.89071,\"description\":\"qzudphq\"}],\"securitySuitability\":\"ConditionallySuitable\",\"shouldProvisionReplicas\":false,\"skuReplicationMode\":\"NotApplicable\",\"migrationGuidelines\":[{\"guidelineId\":\"cvtbv\",\"migrationGuidelineCategory\":\"FailoverCluterInstanceGuideLine\",\"migrationGuidelineContext\":[{},{}]},{\"guidelineId\":\"nvyq\",\"migrationGuidelineCategory\":\"FailoverCluterInstanceGuideLine\",\"migrationGuidelineContext\":[{},{},{},{}]},{\"guidelineId\":\"pcnp\",\"migrationGuidelineCategory\":\"FailoverCluterInstanceGuideLine\",\"migrationGuidelineContext\":[{}]},{\"guidelineId\":\"sgvvsccyajguq\",\"migrationGuidelineCategory\":\"AvailabilityGroupGuideline\",\"migrationGuidelineContext\":[{},{},{}]}],\"recommendationReasonings\":[{\"reasoningId\":\"dnkfx\",\"reasoningString\":\"emdwzrmuhapfc\",\"reasoningCategory\":\"psqxq\",\"contextParameters\":[{}]},{\"reasoningId\":\"uoymgccelvezry\",\"reasoningString\":\"lmfeokerq\",\"reasoningCategory\":\"yhko\",\"contextParameters\":[{}]}],\"migrationTargetPlatform\":\"AzureSqlVirtualMachine\",\"suitability\":\"Suitable\",\"migrationIssues\":[{\"issueId\":\"epbqpcrfkbw\",\"issueCategory\":\"Internal\",\"impactedObjects\":[{},{},{}]},{\"issueId\":\"cdwxlpq\",\"issueCategory\":\"Warning\",\"impactedObjects\":[{},{},{}]},{\"issueId\":\"htjsying\",\"issueCategory\":\"Internal\",\"impactedObjects\":[{},{},{},{}]}]},\"isDatabaseHighlyAvailable\":true,\"linkedAvailabilityGroupOverview\":{\"availabilityGroupId\":\"tmdvypgikdgs\",\"availabilityGroupName\":\"w\",\"sqlAvailabilityGroupSdsArmId\":\"irryuzhlh\",\"sqlAvailabilityGroupEntityId\":\"oqrvqqaatjin\",\"sqlAvailabilityReplicaId\":\"goupmfiibfg\"},\"machineArmId\":\"ioolvrwxkvtkkgll\",\"assessedSqlInstanceArmId\":\"jygvjayvbl\",\"machineName\":\"vkzuhbxvvyhgso\",\"instanceName\":\"yrqufegxuvwz\",\"databaseName\":\"nhlmctlpdng\",\"databaseSizeInMB\":31.674772,\"compatibilityLevel\":\"CompatLevel120\",\"sqlDatabaseSdsArmId\":\"hrixkwmy\",\"percentageCoresUtilization\":87.95895,\"megabytesPerSecondOfRead\":13.23821,\"megabytesPerSecondOfWrite\":32.000755,\"numberOfReadOperationsPerSecond\":77.848915,\"numberOfWriteOperationsPerSecond\":15.418476,\"confidenceRatingInPercentage\":82.512985,\"sizingCriterion\":\"AsOnPremises\",\"createdTimestamp\":\"2021-09-08T02:56:48Z\",\"updatedTimestamp\":\"2021-07-11T23:25:50Z\"},\"id\":\"dreaxh\",\"name\":\"exdrrvqahqkg\",\"type\":\"tpwijnh\"}") + .toObject(AssessedSqlDatabaseV2Inner.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AssessedSqlDatabaseV2Inner model + = new AssessedSqlDatabaseV2Inner().withProperties(new AssessedSqlDatabaseV2Properties()); + model = BinaryData.fromObject(model).toObject(AssessedSqlDatabaseV2Inner.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlDatabaseV2ListResultTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlDatabaseV2ListResultTests.java new file mode 100644 index 000000000000..44f53190b295 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlDatabaseV2ListResultTests.java @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlDatabaseV2Inner; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlDatabaseV2ListResult; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlDatabaseV2Properties; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class AssessedSqlDatabaseV2ListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AssessedSqlDatabaseV2ListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"recommendedAzureSqlTargetType\":\"AzureVirtualMachine\",\"recommendedSuitability\":\"PotentiallySuitableForVM\",\"bufferCacheSizeInMB\":6.7974987,\"productSupportStatus\":{\"currentVersion\":\"fltkacjv\",\"servicePackStatus\":\"kdlfoa\",\"esuStatus\":\"gkfpaga\",\"supportStatus\":\"pulpqblylsyxk\",\"eta\":648285682,\"currentEsuYear\":\"jervtia\",\"mainstreamEndDate\":\"2020-12-21T17:25:21Z\",\"extendedSupportEndDate\":\"2021-11-07T14:14:59Z\",\"extendedSecurityUpdateYear1EndDate\":\"2021-01-31T00:39:07Z\",\"extendedSecurityUpdateYear2EndDate\":\"2021-01-08T11:48:06Z\",\"extendedSecurityUpdateYear3EndDate\":\"2021-01-27T10:36:07Z\"},\"azureSqlMISuitabilityDetails\":{\"azureSqlSku\":{\"azureSqlServiceTier\":\"HyperScale\",\"azureSqlComputeTier\":\"Serverless\",\"azureSqlHardwareGeneration\":\"Unknown\",\"storageMaxSizeInMB\":22.02875,\"predictedDataSizeInMB\":8.355331,\"predictedLogSizeInMB\":98.671165,\"cores\":1110186498,\"azureSqlTargetType\":\"Recommended\"},\"replicaAzureSqlSku\":[{}],\"sharedResources\":{\"sharedDataDisks\":[{},{},{}],\"sharedLogDisks\":[{},{},{},{}],\"sharedTempDbDisks\":[{},{},{},{}],\"numberOfMounts\":2049841705,\"quorumWitness\":{}},\"monthlyComputeCost\":67.076294,\"monthlyStorageCost\":32.550335,\"costComponents\":[{},{},{}],\"securitySuitability\":\"NotSuitable\",\"shouldProvisionReplicas\":true,\"skuReplicationMode\":\"FailoverGroupInstance\",\"migrationGuidelines\":[{}],\"recommendationReasonings\":[{},{},{},{}],\"migrationTargetPlatform\":\"Recommended\",\"suitability\":\"ReadinessUnknown\",\"migrationIssues\":[{},{},{},{}]},\"azureSqlDBSuitabilityDetails\":{\"azureSqlSku\":{\"azureSqlServiceTier\":\"Unknown\",\"azureSqlComputeTier\":\"Unknown\",\"azureSqlHardwareGeneration\":\"Fsv2_series\",\"storageMaxSizeInMB\":85.23259,\"predictedDataSizeInMB\":9.257221,\"predictedLogSizeInMB\":21.030748,\"cores\":804013471,\"azureSqlTargetType\":\"Unknown\"},\"replicaAzureSqlSku\":[{}],\"sharedResources\":{\"sharedDataDisks\":[{},{},{}],\"sharedLogDisks\":[{}],\"sharedTempDbDisks\":[{},{},{},{}],\"numberOfMounts\":621148688,\"quorumWitness\":{}},\"monthlyComputeCost\":6.8819046,\"monthlyStorageCost\":79.41099,\"costComponents\":[{},{},{},{}],\"securitySuitability\":\"Suitable\",\"shouldProvisionReplicas\":false,\"skuReplicationMode\":\"FailoverGroupInstance\",\"migrationGuidelines\":[{},{},{},{}],\"recommendationReasonings\":[{},{},{},{}],\"migrationTargetPlatform\":\"Recommended\",\"suitability\":\"Unknown\",\"migrationIssues\":[{}]},\"isDatabaseHighlyAvailable\":true,\"linkedAvailabilityGroupOverview\":{\"availabilityGroupId\":\"qdpfuvglsbjjca\",\"availabilityGroupName\":\"xbvtvudu\",\"sqlAvailabilityGroupSdsArmId\":\"cormr\",\"sqlAvailabilityGroupEntityId\":\"qtvcofudflvkgj\",\"sqlAvailabilityReplicaId\":\"gdknnqv\"},\"machineArmId\":\"znqntoru\",\"assessedSqlInstanceArmId\":\"gsahmkycgrauw\",\"machineName\":\"etaebu\",\"instanceName\":\"vdmovsmzlxwabm\",\"databaseName\":\"efkifr\",\"databaseSizeInMB\":87.23322,\"compatibilityLevel\":\"CompatLevel100\",\"sqlDatabaseSdsArmId\":\"jmqlgkfb\",\"percentageCoresUtilization\":29.160828,\"megabytesPerSecondOfRead\":37.295277,\"megabytesPerSecondOfWrite\":3.405124,\"numberOfReadOperationsPerSecond\":59.237026,\"numberOfWriteOperationsPerSecond\":6.8924847,\"confidenceRatingInPercentage\":64.58055,\"sizingCriterion\":\"AsOnPremises\",\"createdTimestamp\":\"2021-03-27T19:20:10Z\",\"updatedTimestamp\":\"2021-04-17T23:49:38Z\"},\"id\":\"df\",\"name\":\"wwa\",\"type\":\"zkoj\"},{\"properties\":{\"recommendedAzureSqlTargetType\":\"AzureSqlVirtualMachine\",\"recommendedSuitability\":\"SuitableForSqlDB\",\"bufferCacheSizeInMB\":85.01792,\"productSupportStatus\":{\"currentVersion\":\"i\",\"servicePackStatus\":\"bxarzgszufoxci\",\"esuStatus\":\"p\",\"supportStatus\":\"oamciodh\",\"eta\":1741139859,\"currentEsuYear\":\"xkhnzbonlwnto\",\"mainstreamEndDate\":\"2021-08-27T05:30:46Z\",\"extendedSupportEndDate\":\"2021-08-27T04:05:42Z\",\"extendedSecurityUpdateYear1EndDate\":\"2021-10-07T23:12:54Z\",\"extendedSecurityUpdateYear2EndDate\":\"2021-09-24T01:53:24Z\",\"extendedSecurityUpdateYear3EndDate\":\"2021-11-17T17:14:48Z\"},\"azureSqlMISuitabilityDetails\":{\"azureSqlSku\":{\"azureSqlServiceTier\":\"Automatic\",\"azureSqlComputeTier\":\"Provisioned\",\"azureSqlHardwareGeneration\":\"Gen5\",\"storageMaxSizeInMB\":15.110135,\"predictedDataSizeInMB\":10.827255,\"predictedLogSizeInMB\":77.007065,\"cores\":125773376,\"azureSqlTargetType\":\"Recommended\"},\"replicaAzureSqlSku\":[{},{}],\"sharedResources\":{\"sharedDataDisks\":[{},{}],\"sharedLogDisks\":[{},{},{},{}],\"sharedTempDbDisks\":[{},{}],\"numberOfMounts\":1422593899,\"quorumWitness\":{}},\"monthlyComputeCost\":7.1297703,\"monthlyStorageCost\":10.837847,\"costComponents\":[{}],\"securitySuitability\":\"ConditionallySuitable\",\"shouldProvisionReplicas\":true,\"skuReplicationMode\":\"NotApplicable\",\"migrationGuidelines\":[{},{},{},{}],\"recommendationReasonings\":[{},{},{},{}],\"migrationTargetPlatform\":\"Unknown\",\"suitability\":\"Unknown\",\"migrationIssues\":[{}]},\"azureSqlDBSuitabilityDetails\":{\"azureSqlSku\":{\"azureSqlServiceTier\":\"Automatic\",\"azureSqlComputeTier\":\"Automatic\",\"azureSqlHardwareGeneration\":\"Unknown\",\"storageMaxSizeInMB\":4.411727,\"predictedDataSizeInMB\":98.1842,\"predictedLogSizeInMB\":28.616787,\"cores\":237488555,\"azureSqlTargetType\":\"Unknown\"},\"replicaAzureSqlSku\":[{}],\"sharedResources\":{\"sharedDataDisks\":[{},{},{},{}],\"sharedLogDisks\":[{}],\"sharedTempDbDisks\":[{},{},{},{}],\"numberOfMounts\":2086518628,\"quorumWitness\":{}},\"monthlyComputeCost\":58.32351,\"monthlyStorageCost\":61.956436,\"costComponents\":[{}],\"securitySuitability\":\"NotSuitable\",\"shouldProvisionReplicas\":false,\"skuReplicationMode\":\"ActiveGeoReplication\",\"migrationGuidelines\":[{}],\"recommendationReasonings\":[{},{},{},{}],\"migrationTargetPlatform\":\"Unknown\",\"suitability\":\"Unknown\",\"migrationIssues\":[{},{},{}]},\"isDatabaseHighlyAvailable\":true,\"linkedAvailabilityGroupOverview\":{\"availabilityGroupId\":\"ogvbbejdcngq\",\"availabilityGroupName\":\"oakufgm\",\"sqlAvailabilityGroupSdsArmId\":\"rwr\",\"sqlAvailabilityGroupEntityId\":\"rtwaenuuzko\",\"sqlAvailabilityReplicaId\":\"minrfdw\"},\"machineArmId\":\"uhhziuiefozbhdm\",\"assessedSqlInstanceArmId\":\"l\",\"machineName\":\"qhoftrmaequiah\",\"instanceName\":\"cslfaoqzpiyylha\",\"databaseName\":\"swhccsphk\",\"databaseSizeInMB\":54.328762,\"compatibilityLevel\":\"CompatLevel80\",\"sqlDatabaseSdsArmId\":\"qscywu\",\"percentageCoresUtilization\":92.82295,\"megabytesPerSecondOfRead\":40.162403,\"megabytesPerSecondOfWrite\":2.1984339,\"numberOfReadOperationsPerSecond\":36.04179,\"numberOfWriteOperationsPerSecond\":13.990349,\"confidenceRatingInPercentage\":92.50669,\"sizingCriterion\":\"PerformanceBased\",\"createdTimestamp\":\"2021-02-18T08:40:02Z\",\"updatedTimestamp\":\"2021-03-17T16:24:18Z\"},\"id\":\"gzd\",\"name\":\"msweypqwdxggicc\",\"type\":\"n\"}],\"nextLink\":\"huexmk\"}") + .toObject(AssessedSqlDatabaseV2ListResult.class); + Assertions.assertEquals("huexmk", model.nextLink()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AssessedSqlDatabaseV2ListResult model = new AssessedSqlDatabaseV2ListResult() + .withValue( + Arrays.asList(new AssessedSqlDatabaseV2Inner().withProperties(new AssessedSqlDatabaseV2Properties()), + new AssessedSqlDatabaseV2Inner().withProperties(new AssessedSqlDatabaseV2Properties()))) + .withNextLink("huexmk"); + model = BinaryData.fromObject(model).toObject(AssessedSqlDatabaseV2ListResult.class); + Assertions.assertEquals("huexmk", model.nextLink()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlDatabaseV2OperationsGetWithResponseMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlDatabaseV2OperationsGetWithResponseMockTests.java new file mode 100644 index 000000000000..9719bd15959d --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlDatabaseV2OperationsGetWithResponseMockTests.java @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlDatabaseV2; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class AssessedSqlDatabaseV2OperationsGetWithResponseMockTests { + @Test + public void testGetWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"recommendedAzureSqlTargetType\":\"AzureSqlVirtualMachine\",\"recommendedSuitability\":\"ReadinessUnknown\",\"bufferCacheSizeInMB\":0.8788943,\"productSupportStatus\":{\"currentVersion\":\"iegftc\",\"servicePackStatus\":\"iiftksd\",\"esuStatus\":\"dnkefgm\",\"supportStatus\":\"hcebuvczldbglzo\",\"eta\":1037630035,\"currentEsuYear\":\"aqgzekajclyzgs\",\"mainstreamEndDate\":\"2021-04-21T17:36:16Z\",\"extendedSupportEndDate\":\"2021-04-23T22:59:57Z\",\"extendedSecurityUpdateYear1EndDate\":\"2021-11-11T22:10:46Z\",\"extendedSecurityUpdateYear2EndDate\":\"2021-04-21T21:06:45Z\",\"extendedSecurityUpdateYear3EndDate\":\"2021-05-23T21:13:43Z\"},\"azureSqlMISuitabilityDetails\":{\"azureSqlSku\":{\"azureSqlServiceTier\":\"BusinessCritical\",\"azureSqlComputeTier\":\"Serverless\",\"azureSqlHardwareGeneration\":\"Automatic\",\"storageMaxSizeInMB\":68.34222,\"predictedDataSizeInMB\":16.33374,\"predictedLogSizeInMB\":52.67709,\"cores\":903159206,\"azureSqlTargetType\":\"Recommended\"},\"replicaAzureSqlSku\":[{\"azureSqlServiceTier\":\"BusinessCritical\",\"azureSqlComputeTier\":\"Serverless\",\"azureSqlHardwareGeneration\":\"Gen5\",\"storageMaxSizeInMB\":38.71055,\"predictedDataSizeInMB\":87.59537,\"predictedLogSizeInMB\":43.163795,\"cores\":1578463604,\"azureSqlTargetType\":\"AzureVirtualMachine\"},{\"azureSqlServiceTier\":\"Unknown\",\"azureSqlComputeTier\":\"Serverless\",\"azureSqlHardwareGeneration\":\"Gen5\",\"storageMaxSizeInMB\":74.55601,\"predictedDataSizeInMB\":70.11732,\"predictedLogSizeInMB\":36.583263,\"cores\":516680467,\"azureSqlTargetType\":\"AzureSqlVirtualMachine\"}],\"sharedResources\":{\"sharedDataDisks\":[{}],\"sharedLogDisks\":[{},{}],\"sharedTempDbDisks\":[{},{}],\"numberOfMounts\":421959246,\"quorumWitness\":{\"quorumWitnessType\":\"Unknown\"}},\"monthlyComputeCost\":49.53341,\"monthlyStorageCost\":60.52063,\"costComponents\":[{\"name\":\"MonthlyAzureHybridCostSavings\",\"value\":35.289574,\"description\":\"j\"},{\"name\":\"Unknown\",\"value\":64.1754,\"description\":\"fyvrtpqpemhzcgk\"},{\"name\":\"MonthlyPremiumV2StorageCost\",\"value\":71.210846,\"description\":\"qyhwqwem\"}],\"securitySuitability\":\"ConditionallySuitable\",\"shouldProvisionReplicas\":true,\"skuReplicationMode\":\"ActiveGeoReplication\",\"migrationGuidelines\":[{\"guidelineId\":\"oxinh\",\"migrationGuidelineCategory\":\"Unknown\",\"migrationGuidelineContext\":[{}]},{\"guidelineId\":\"whlpuzjpceezn\",\"migrationGuidelineCategory\":\"Unknown\",\"migrationGuidelineContext\":[{},{},{},{}]}],\"recommendationReasonings\":[{\"reasoningId\":\"axyxzlbciphm\",\"reasoningString\":\"x\",\"reasoningCategory\":\"qrndktxfvon\",\"contextParameters\":[{}]},{\"reasoningId\":\"gpkrie\",\"reasoningString\":\"gnixxowwzkyfwnw\",\"reasoningCategory\":\"wxeiicrmpepk\",\"contextParameters\":[{},{},{},{}]},{\"reasoningId\":\"xxij\",\"reasoningString\":\"kwsdgkj\",\"reasoningCategory\":\"acwras\",\"contextParameters\":[{},{},{}]}],\"migrationTargetPlatform\":\"Unknown\",\"suitability\":\"NotSuitable\",\"migrationIssues\":[{\"issueId\":\"woqartwy\",\"issueCategory\":\"Warning\",\"impactedObjects\":[{}]},{\"issueId\":\"dvatdavuqm\",\"issueCategory\":\"Internal\",\"impactedObjects\":[{},{}]},{\"issueId\":\"ob\",\"issueCategory\":\"Issue\",\"impactedObjects\":[{},{},{},{}]}]},\"azureSqlDBSuitabilityDetails\":{\"azureSqlSku\":{\"azureSqlServiceTier\":\"GeneralPurpose\",\"azureSqlComputeTier\":\"Serverless\",\"azureSqlHardwareGeneration\":\"Gen5\",\"storageMaxSizeInMB\":23.274738,\"predictedDataSizeInMB\":26.043839,\"predictedLogSizeInMB\":67.29231,\"cores\":1199715241,\"azureSqlTargetType\":\"AzureSqlVirtualMachine\"},\"replicaAzureSqlSku\":[{\"azureSqlServiceTier\":\"HyperScale\",\"azureSqlComputeTier\":\"Automatic\",\"azureSqlHardwareGeneration\":\"Fsv2_series\",\"storageMaxSizeInMB\":30.55802,\"predictedDataSizeInMB\":26.492733,\"predictedLogSizeInMB\":71.933975,\"cores\":589477595,\"azureSqlTargetType\":\"Unknown\"}],\"sharedResources\":{\"sharedDataDisks\":[{},{}],\"sharedLogDisks\":[{},{}],\"sharedTempDbDisks\":[{},{}],\"numberOfMounts\":1948229122,\"quorumWitness\":{\"quorumWitnessType\":\"Unknown\"}},\"monthlyComputeCost\":36.676968,\"monthlyStorageCost\":45.845135,\"costComponents\":[{\"name\":\"MonthlyAzureHybridCostSavings\",\"value\":10.844618,\"description\":\"nmabed\"},{\"name\":\"MonthlyPremiumV2StorageCost\",\"value\":10.511869,\"description\":\"d\"},{\"name\":\"Unknown\",\"value\":99.390724,\"description\":\"cvstclgqrvwerf\"},{\"name\":\"MonthlySecurityCost\",\"value\":44.495235,\"description\":\"bljjehh\"}],\"securitySuitability\":\"ReadinessUnknown\",\"shouldProvisionReplicas\":false,\"skuReplicationMode\":\"NotApplicable\",\"migrationGuidelines\":[{\"guidelineId\":\"rek\",\"migrationGuidelineCategory\":\"General\",\"migrationGuidelineContext\":[{},{}]},{\"guidelineId\":\"fpwpqbyejuwyqwd\",\"migrationGuidelineCategory\":\"AvailabilityGroupGuideline\",\"migrationGuidelineContext\":[{}]},{\"guidelineId\":\"ginz\",\"migrationGuidelineCategory\":\"General\",\"migrationGuidelineContext\":[{},{}]}],\"recommendationReasonings\":[{\"reasoningId\":\"jcmrnkfm\",\"reasoningString\":\"cqtwmlmhjnqtq\",\"reasoningCategory\":\"hj\",\"contextParameters\":[{},{},{}]},{\"reasoningId\":\"agpokddxe\",\"reasoningString\":\"h\",\"reasoningCategory\":\"guavtptb\",\"contextParameters\":[{},{}]},{\"reasoningId\":\"qynspgbvoffb\",\"reasoningString\":\"w\",\"reasoningCategory\":\"xaexqokmyrljial\",\"contextParameters\":[{},{}]}],\"migrationTargetPlatform\":\"Unknown\",\"suitability\":\"NotSuitable\",\"migrationIssues\":[{\"issueId\":\"cjtrpzu\",\"issueCategory\":\"Issue\",\"impactedObjects\":[{},{},{},{}]},{\"issueId\":\"xnhsqeaeo\",\"issueCategory\":\"Issue\",\"impactedObjects\":[{},{}]},{\"issueId\":\"dhuruzytzarog\",\"issueCategory\":\"Issue\",\"impactedObjects\":[{}]},{\"issueId\":\"iywmpinmzvfkn\",\"issueCategory\":\"Issue\",\"impactedObjects\":[{},{}]}]},\"isDatabaseHighlyAvailable\":true,\"linkedAvailabilityGroupOverview\":{\"availabilityGroupId\":\"sj\",\"availabilityGroupName\":\"ugdybnhrxlel\",\"sqlAvailabilityGroupSdsArmId\":\"hkeizcp\",\"sqlAvailabilityGroupEntityId\":\"tdmiwjekptyca\",\"sqlAvailabilityReplicaId\":\"bjzcqymlcfnzhm\"},\"machineArmId\":\"urlgwqkpmmzps\",\"assessedSqlInstanceArmId\":\"u\",\"machineName\":\"awi\",\"instanceName\":\"momsgvvj\",\"databaseName\":\"vlrlohewjjmajn\",\"databaseSizeInMB\":26.176012,\"compatibilityLevel\":\"CompatLevel100\",\"sqlDatabaseSdsArmId\":\"onswae\",\"percentageCoresUtilization\":12.957537,\"megabytesPerSecondOfRead\":45.745068,\"megabytesPerSecondOfWrite\":96.45278,\"numberOfReadOperationsPerSecond\":65.69365,\"numberOfWriteOperationsPerSecond\":9.40125,\"confidenceRatingInPercentage\":0.98002553,\"sizingCriterion\":\"PerformanceBased\",\"createdTimestamp\":\"2021-08-07T15:49:55Z\",\"updatedTimestamp\":\"2021-05-14T04:39:56Z\"},\"id\":\"pkhx\",\"name\":\"mexznlwkb\",\"type\":\"okxkhupzer\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + AssessedSqlDatabaseV2 response = manager.assessedSqlDatabaseV2Operations() + .getWithResponse("kqv", "qepdx", "ltuubw", "vpjbowcpjqduq", "ixexkydfbwljavhu", + com.azure.core.util.Context.NONE) + .getValue(); + + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlDatabaseV2OperationsListBySqlAssessmentV2MockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlDatabaseV2OperationsListBySqlAssessmentV2MockTests.java new file mode 100644 index 000000000000..f6caf590ccf1 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlDatabaseV2OperationsListBySqlAssessmentV2MockTests.java @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlDatabaseV2; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class AssessedSqlDatabaseV2OperationsListBySqlAssessmentV2MockTests { + @Test + public void testListBySqlAssessmentV2() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"recommendedAzureSqlTargetType\":\"Recommended\",\"recommendedSuitability\":\"SuitableForSqlDB\",\"bufferCacheSizeInMB\":6.9218874,\"productSupportStatus\":{\"currentVersion\":\"lr\",\"servicePackStatus\":\"gtzjcv\",\"esuStatus\":\"qlapsnsso\",\"supportStatus\":\"xpavid\",\"eta\":435647020,\"currentEsuYear\":\"wffcvvye\",\"mainstreamEndDate\":\"2021-06-23T09:55:10Z\",\"extendedSupportEndDate\":\"2021-09-10T04:22:49Z\",\"extendedSecurityUpdateYear1EndDate\":\"2021-09-04T00:09:45Z\",\"extendedSecurityUpdateYear2EndDate\":\"2021-08-25T16:18:38Z\",\"extendedSecurityUpdateYear3EndDate\":\"2021-03-26T15:54:37Z\"},\"azureSqlMISuitabilityDetails\":{\"azureSqlSku\":{\"azureSqlServiceTier\":\"Unknown\",\"azureSqlComputeTier\":\"Serverless\",\"azureSqlHardwareGeneration\":\"DC_series\",\"storageMaxSizeInMB\":95.14251,\"predictedDataSizeInMB\":74.27462,\"predictedLogSizeInMB\":34.092625,\"cores\":1838467829,\"azureSqlTargetType\":\"Unknown\"},\"replicaAzureSqlSku\":[{\"azureSqlServiceTier\":\"HyperScale\",\"azureSqlComputeTier\":\"Provisioned\",\"azureSqlHardwareGeneration\":\"Automatic\",\"storageMaxSizeInMB\":87.86046,\"predictedDataSizeInMB\":22.210157,\"predictedLogSizeInMB\":67.66576,\"cores\":782520891,\"azureSqlTargetType\":\"AzureSqlVirtualMachine\"}],\"sharedResources\":{\"sharedDataDisks\":[{},{},{}],\"sharedLogDisks\":[{},{},{},{}],\"sharedTempDbDisks\":[{},{},{},{}],\"numberOfMounts\":1625697424,\"quorumWitness\":{\"quorumWitnessType\":\"Cloud\"}},\"monthlyComputeCost\":51.853474,\"monthlyStorageCost\":94.16587,\"costComponents\":[{\"name\":\"MonthlySecurityCost\",\"value\":83.56569,\"description\":\"qhnmhk\"}],\"securitySuitability\":\"ReadinessUnknown\",\"shouldProvisionReplicas\":true,\"skuReplicationMode\":\"NotApplicable\",\"migrationGuidelines\":[{\"guidelineId\":\"qdgcrux\",\"migrationGuidelineCategory\":\"AvailabilityGroupGuideline\",\"migrationGuidelineContext\":[{},{},{}]},{\"guidelineId\":\"m\",\"migrationGuidelineCategory\":\"General\",\"migrationGuidelineContext\":[{},{}]}],\"recommendationReasonings\":[{\"reasoningId\":\"pazf\",\"reasoningString\":\"jxuvj\",\"reasoningCategory\":\"fdvhaxdvwzae\",\"contextParameters\":[{}]},{\"reasoningId\":\"thd\",\"reasoningString\":\"mvetatlakfq\",\"reasoningCategory\":\"xwgiks\",\"contextParameters\":[{},{}]}],\"migrationTargetPlatform\":\"AzureSqlManagedInstance\",\"suitability\":\"NotSuitable\",\"migrationIssues\":[{\"issueId\":\"gwphchgjtnht\",\"issueCategory\":\"Internal\",\"impactedObjects\":[{},{},{},{}]}]},\"azureSqlDBSuitabilityDetails\":{\"azureSqlSku\":{\"azureSqlServiceTier\":\"BusinessCritical\",\"azureSqlComputeTier\":\"Provisioned\",\"azureSqlHardwareGeneration\":\"Automatic\",\"storageMaxSizeInMB\":28.095364,\"predictedDataSizeInMB\":67.82644,\"predictedLogSizeInMB\":87.82683,\"cores\":353154350,\"azureSqlTargetType\":\"Recommended\"},\"replicaAzureSqlSku\":[{\"azureSqlServiceTier\":\"Unknown\",\"azureSqlComputeTier\":\"Provisioned\",\"azureSqlHardwareGeneration\":\"M_series\",\"storageMaxSizeInMB\":79.7553,\"predictedDataSizeInMB\":2.1850169,\"predictedLogSizeInMB\":92.61337,\"cores\":968770502,\"azureSqlTargetType\":\"AzureSqlManagedInstance\"}],\"sharedResources\":{\"sharedDataDisks\":[{},{}],\"sharedLogDisks\":[{},{},{},{}],\"sharedTempDbDisks\":[{},{},{},{}],\"numberOfMounts\":1876924185,\"quorumWitness\":{\"quorumWitnessType\":\"Unknown\"}},\"monthlyComputeCost\":71.73476,\"monthlyStorageCost\":94.903854,\"costComponents\":[{\"name\":\"Unknown\",\"value\":26.463287,\"description\":\"mlscgrllccn\"},{\"name\":\"MonthlySecurityCost\",\"value\":74.24044,\"description\":\"azhpabacoml\"},{\"name\":\"Unknown\",\"value\":21.50871,\"description\":\"sxnsrqorcge\"},{\"name\":\"MonthlyPremiumV2StorageCost\",\"value\":17.64496,\"description\":\"xeetq\"}],\"securitySuitability\":\"ReadinessUnknown\",\"shouldProvisionReplicas\":false,\"skuReplicationMode\":\"ActiveGeoReplication\",\"migrationGuidelines\":[{\"guidelineId\":\"qjkedwqurc\",\"migrationGuidelineCategory\":\"FailoverCluterInstanceGuideLine\",\"migrationGuidelineContext\":[{},{},{},{}]},{\"guidelineId\":\"v\",\"migrationGuidelineCategory\":\"FailoverCluterInstanceGuideLine\",\"migrationGuidelineContext\":[{}]},{\"guidelineId\":\"zsehqqrsilcchskx\",\"migrationGuidelineCategory\":\"FailoverCluterInstanceGuideLine\",\"migrationGuidelineContext\":[{}]}],\"recommendationReasonings\":[{\"reasoningId\":\"ia\",\"reasoningString\":\"vtojrulfuctejr\",\"reasoningCategory\":\"cfjzhxl\",\"contextParameters\":[{}]}],\"migrationTargetPlatform\":\"AzureSqlDatabase\",\"suitability\":\"Unknown\",\"migrationIssues\":[{\"issueId\":\"rjeqmtzzbeqrztr\",\"issueCategory\":\"Issue\",\"impactedObjects\":[{},{}]},{\"issueId\":\"habsrwrsnrh\",\"issueCategory\":\"Issue\",\"impactedObjects\":[{},{}]},{\"issueId\":\"kkvyanxk\",\"issueCategory\":\"Issue\",\"impactedObjects\":[{}]}]},\"isDatabaseHighlyAvailable\":false,\"linkedAvailabilityGroupOverview\":{\"availabilityGroupId\":\"v\",\"availabilityGroupName\":\"kqxetqmmliv\",\"sqlAvailabilityGroupSdsArmId\":\"jxnw\",\"sqlAvailabilityGroupEntityId\":\"chp\",\"sqlAvailabilityReplicaId\":\"xlehzlxpgfquwzp\"},\"machineArmId\":\"ibelwcerwkw\",\"assessedSqlInstanceArmId\":\"jxljtxbusq\",\"machineName\":\"xxniuisdzhgbd\",\"instanceName\":\"pagsecnad\",\"databaseName\":\"wqrgxfllmqi\",\"databaseSizeInMB\":31.991226,\"compatibilityLevel\":\"Unknown\",\"sqlDatabaseSdsArmId\":\"lln\",\"percentageCoresUtilization\":20.776356,\"megabytesPerSecondOfRead\":4.9613,\"megabytesPerSecondOfWrite\":24.190844,\"numberOfReadOperationsPerSecond\":48.35083,\"numberOfWriteOperationsPerSecond\":74.788025,\"confidenceRatingInPercentage\":38.305767,\"sizingCriterion\":\"PerformanceBased\",\"createdTimestamp\":\"2021-02-13T02:19:45Z\",\"updatedTimestamp\":\"2021-02-26T07:03:36Z\"},\"id\":\"roqvqpilrgu\",\"name\":\"canlduwzorxs\",\"type\":\"mxaqklxym\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response = manager.assessedSqlDatabaseV2Operations() + .listBySqlAssessmentV2("ghsrleinkfscjfn", "jwvuag", "qwtltngvmreupt", "klzmijajw", "l", 1419456371, "s", + 922297419, com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlInstanceDatabaseSummaryTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlInstanceDatabaseSummaryTests.java new file mode 100644 index 000000000000..c6d184a5a134 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlInstanceDatabaseSummaryTests.java @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlInstanceDatabaseSummary; +import org.junit.jupiter.api.Assertions; + +public final class AssessedSqlInstanceDatabaseSummaryTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AssessedSqlInstanceDatabaseSummary model = BinaryData.fromString( + "{\"numberOfUserDatabases\":967532883,\"totalDatabaseSizeInMB\":17.572004,\"largestDatabaseSizeInMB\":72.82245,\"totalDiscoveredUserDatabases\":1096953417}") + .toObject(AssessedSqlInstanceDatabaseSummary.class); + Assertions.assertEquals(967532883, model.numberOfUserDatabases()); + Assertions.assertEquals(17.572004F, model.totalDatabaseSizeInMB()); + Assertions.assertEquals(72.82245F, model.largestDatabaseSizeInMB()); + Assertions.assertEquals(1096953417, model.totalDiscoveredUserDatabases()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AssessedSqlInstanceDatabaseSummary model + = new AssessedSqlInstanceDatabaseSummary().withNumberOfUserDatabases(967532883) + .withTotalDatabaseSizeInMB(17.572004F) + .withLargestDatabaseSizeInMB(72.82245F) + .withTotalDiscoveredUserDatabases(1096953417); + model = BinaryData.fromObject(model).toObject(AssessedSqlInstanceDatabaseSummary.class); + Assertions.assertEquals(967532883, model.numberOfUserDatabases()); + Assertions.assertEquals(17.572004F, model.totalDatabaseSizeInMB()); + Assertions.assertEquals(72.82245F, model.largestDatabaseSizeInMB()); + Assertions.assertEquals(1096953417, model.totalDiscoveredUserDatabases()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlInstanceDiskDetailsTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlInstanceDiskDetailsTests.java new file mode 100644 index 000000000000..fa7936850a0a --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlInstanceDiskDetailsTests.java @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlInstanceDiskDetails; +import org.junit.jupiter.api.Assertions; + +public final class AssessedSqlInstanceDiskDetailsTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AssessedSqlInstanceDiskDetails model = BinaryData.fromString( + "{\"diskId\":\"mfg\",\"diskSizeInMB\":46.877174,\"megabytesPerSecondOfRead\":99.32945,\"megabytesPerSecondOfWrite\":90.87945,\"numberOfReadOperationsPerSecond\":1.9399703,\"numberOfWriteOperationsPerSecond\":3.898108}") + .toObject(AssessedSqlInstanceDiskDetails.class); + Assertions.assertEquals("mfg", model.diskId()); + Assertions.assertEquals(46.877174F, model.diskSizeInMB()); + Assertions.assertEquals(99.32945F, model.megabytesPerSecondOfRead()); + Assertions.assertEquals(90.87945F, model.megabytesPerSecondOfWrite()); + Assertions.assertEquals(1.9399703F, model.numberOfReadOperationsPerSecond()); + Assertions.assertEquals(3.898108F, model.numberOfWriteOperationsPerSecond()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AssessedSqlInstanceDiskDetails model = new AssessedSqlInstanceDiskDetails().withDiskId("mfg") + .withDiskSizeInMB(46.877174F) + .withMegabytesPerSecondOfRead(99.32945F) + .withMegabytesPerSecondOfWrite(90.87945F) + .withNumberOfReadOperationsPerSecond(1.9399703F) + .withNumberOfWriteOperationsPerSecond(3.898108F); + model = BinaryData.fromObject(model).toObject(AssessedSqlInstanceDiskDetails.class); + Assertions.assertEquals("mfg", model.diskId()); + Assertions.assertEquals(46.877174F, model.diskSizeInMB()); + Assertions.assertEquals(99.32945F, model.megabytesPerSecondOfRead()); + Assertions.assertEquals(90.87945F, model.megabytesPerSecondOfWrite()); + Assertions.assertEquals(1.9399703F, model.numberOfReadOperationsPerSecond()); + Assertions.assertEquals(3.898108F, model.numberOfWriteOperationsPerSecond()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlInstanceStorageDetailsTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlInstanceStorageDetailsTests.java new file mode 100644 index 000000000000..a0ea005602fd --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlInstanceStorageDetailsTests.java @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlInstanceStorageDetails; +import org.junit.jupiter.api.Assertions; + +public final class AssessedSqlInstanceStorageDetailsTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AssessedSqlInstanceStorageDetails model = BinaryData.fromString( + "{\"storageType\":\"rkyui\",\"diskSizeInMB\":46.088665,\"megabytesPerSecondOfRead\":27.76271,\"megabytesPerSecondOfWrite\":36.77259,\"numberOfReadOperationsPerSecond\":60.807236,\"numberOfWriteOperationsPerSecond\":35.29606}") + .toObject(AssessedSqlInstanceStorageDetails.class); + Assertions.assertEquals("rkyui", model.storageType()); + Assertions.assertEquals(46.088665F, model.diskSizeInMB()); + Assertions.assertEquals(27.76271F, model.megabytesPerSecondOfRead()); + Assertions.assertEquals(36.77259F, model.megabytesPerSecondOfWrite()); + Assertions.assertEquals(60.807236F, model.numberOfReadOperationsPerSecond()); + Assertions.assertEquals(35.29606F, model.numberOfWriteOperationsPerSecond()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AssessedSqlInstanceStorageDetails model = new AssessedSqlInstanceStorageDetails().withStorageType("rkyui") + .withDiskSizeInMB(46.088665F) + .withMegabytesPerSecondOfRead(27.76271F) + .withMegabytesPerSecondOfWrite(36.77259F) + .withNumberOfReadOperationsPerSecond(60.807236F) + .withNumberOfWriteOperationsPerSecond(35.29606F); + model = BinaryData.fromObject(model).toObject(AssessedSqlInstanceStorageDetails.class); + Assertions.assertEquals("rkyui", model.storageType()); + Assertions.assertEquals(46.088665F, model.diskSizeInMB()); + Assertions.assertEquals(27.76271F, model.megabytesPerSecondOfRead()); + Assertions.assertEquals(36.77259F, model.megabytesPerSecondOfWrite()); + Assertions.assertEquals(60.807236F, model.numberOfReadOperationsPerSecond()); + Assertions.assertEquals(35.29606F, model.numberOfWriteOperationsPerSecond()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlInstanceSummaryTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlInstanceSummaryTests.java new file mode 100644 index 000000000000..ada957052855 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlInstanceSummaryTests.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlInstanceSummary; +import com.azure.resourcemanager.migration.assessment.models.SqlFciState; +import org.junit.jupiter.api.Assertions; + +public final class AssessedSqlInstanceSummaryTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AssessedSqlInstanceSummary model = BinaryData.fromString( + "{\"instanceId\":\"yi\",\"instanceName\":\"sharujtj\",\"sqlInstanceSdsArmId\":\"xfz\",\"sqlInstanceEntityId\":\"qttv\",\"sqlEdition\":\"pqhjpenuygbqeqq\",\"sqlVersion\":\"ewvnqvcdlgu\",\"isClustered\":true,\"isHighAvailabilityEnabled\":false,\"sqlFciState\":\"Active\"}") + .toObject(AssessedSqlInstanceSummary.class); + Assertions.assertEquals("yi", model.instanceId()); + Assertions.assertEquals("sharujtj", model.instanceName()); + Assertions.assertEquals("xfz", model.sqlInstanceSdsArmId()); + Assertions.assertEquals("qttv", model.sqlInstanceEntityId()); + Assertions.assertEquals("pqhjpenuygbqeqq", model.sqlEdition()); + Assertions.assertEquals("ewvnqvcdlgu", model.sqlVersion()); + Assertions.assertEquals(true, model.isClustered()); + Assertions.assertEquals(false, model.isHighAvailabilityEnabled()); + Assertions.assertEquals(SqlFciState.ACTIVE, model.sqlFciState()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AssessedSqlInstanceSummary model = new AssessedSqlInstanceSummary().withInstanceId("yi") + .withInstanceName("sharujtj") + .withSqlInstanceSdsArmId("xfz") + .withSqlInstanceEntityId("qttv") + .withSqlEdition("pqhjpenuygbqeqq") + .withSqlVersion("ewvnqvcdlgu") + .withIsClustered(true) + .withIsHighAvailabilityEnabled(false) + .withSqlFciState(SqlFciState.ACTIVE); + model = BinaryData.fromObject(model).toObject(AssessedSqlInstanceSummary.class); + Assertions.assertEquals("yi", model.instanceId()); + Assertions.assertEquals("sharujtj", model.instanceName()); + Assertions.assertEquals("xfz", model.sqlInstanceSdsArmId()); + Assertions.assertEquals("qttv", model.sqlInstanceEntityId()); + Assertions.assertEquals("pqhjpenuygbqeqq", model.sqlEdition()); + Assertions.assertEquals("ewvnqvcdlgu", model.sqlVersion()); + Assertions.assertEquals(true, model.isClustered()); + Assertions.assertEquals(false, model.isHighAvailabilityEnabled()); + Assertions.assertEquals(SqlFciState.ACTIVE, model.sqlFciState()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlInstanceV2ListResultTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlInstanceV2ListResultTests.java new file mode 100644 index 000000000000..e09214317189 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlInstanceV2ListResultTests.java @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlInstanceV2Inner; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlInstanceV2ListResult; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlInstanceV2Properties; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class AssessedSqlInstanceV2ListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AssessedSqlInstanceV2ListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"memoryInUseInMB\":9.758597,\"hasScanOccurred\":true,\"recommendedAzureSqlTargetType\":\"AzureVirtualMachine\",\"recommendedSuitability\":\"SuitableForVM\",\"azureSqlMISuitabilityDetails\":{\"azureSqlSku\":{\"azureSqlServiceTier\":\"Automatic\",\"azureSqlComputeTier\":\"Provisioned\",\"azureSqlHardwareGeneration\":\"Unknown\",\"storageMaxSizeInMB\":62.814766,\"predictedDataSizeInMB\":84.55681,\"predictedLogSizeInMB\":43.927773,\"cores\":2100674644,\"azureSqlTargetType\":\"AzureSqlDatabase\"},\"replicaAzureSqlSku\":[{},{}],\"sharedResources\":{\"sharedDataDisks\":[{}],\"sharedLogDisks\":[{},{},{}],\"sharedTempDbDisks\":[{},{},{},{}],\"numberOfMounts\":741141390,\"quorumWitness\":{}},\"monthlyComputeCost\":37.95228,\"monthlyStorageCost\":17.054766,\"costComponents\":[{},{},{}],\"securitySuitability\":\"Unknown\",\"shouldProvisionReplicas\":false,\"skuReplicationMode\":\"NotApplicable\",\"migrationGuidelines\":[{},{}],\"recommendationReasonings\":[{},{}],\"migrationTargetPlatform\":\"AzureSqlManagedInstance\",\"suitability\":\"ReadinessUnknown\",\"migrationIssues\":[{},{},{}]},\"azureSqlDBSuitabilityDetails\":{\"azureSqlSku\":{\"azureSqlServiceTier\":\"BusinessCritical\",\"azureSqlComputeTier\":\"Provisioned\",\"azureSqlHardwareGeneration\":\"DC_series\",\"storageMaxSizeInMB\":91.03727,\"predictedDataSizeInMB\":55.587914,\"predictedLogSizeInMB\":49.596615,\"cores\":997568890,\"azureSqlTargetType\":\"Unknown\"},\"replicaAzureSqlSku\":[{},{},{}],\"sharedResources\":{\"sharedDataDisks\":[{}],\"sharedLogDisks\":[{}],\"sharedTempDbDisks\":[{}],\"numberOfMounts\":418634069,\"quorumWitness\":{}},\"monthlyComputeCost\":3.8403451,\"monthlyStorageCost\":70.124275,\"costComponents\":[{},{},{},{}],\"securitySuitability\":\"NotSuitable\",\"shouldProvisionReplicas\":false,\"skuReplicationMode\":\"ActiveGeoReplication\",\"migrationGuidelines\":[{},{}],\"recommendationReasonings\":[{}],\"migrationTargetPlatform\":\"AzureVirtualMachine\",\"suitability\":\"Suitable\",\"migrationIssues\":[{},{}]},\"azureSqlVMSuitabilityDetails\":{\"azureSqlSku\":{\"virtualMachineSize\":{},\"dataDiskSizes\":[{}],\"logDiskSizes\":[{}],\"azureSqlTargetType\":\"AzureSqlManagedInstance\"},\"replicaAzureSqlSku\":[{}],\"sharedResources\":{\"sharedDataDisks\":[{},{}],\"sharedLogDisks\":[{}],\"sharedTempDbDisks\":[{},{}],\"numberOfMounts\":1894572195,\"quorumWitness\":{}},\"monthlyComputeCost\":92.74596,\"monthlyStorageCost\":0.8468509,\"costComponents\":[{},{},{}],\"securitySuitability\":\"Unknown\",\"shouldProvisionReplicas\":true,\"skuReplicationMode\":\"FailoverGroupInstance\",\"migrationGuidelines\":[{}],\"recommendationReasonings\":[{},{}],\"migrationTargetPlatform\":\"AzureSqlDatabase\",\"suitability\":\"Unknown\",\"migrationIssues\":[{}]},\"storageTypeBasedDetails\":[{\"storageType\":\"axkgx\",\"diskSizeInMB\":7.87431,\"megabytesPerSecondOfRead\":45.988117,\"megabytesPerSecondOfWrite\":99.56378,\"numberOfReadOperationsPerSecond\":87.37095,\"numberOfWriteOperationsPerSecond\":81.29393},{\"storageType\":\"lu\",\"diskSizeInMB\":43.955265,\"megabytesPerSecondOfRead\":21.977615,\"megabytesPerSecondOfWrite\":95.55131,\"numberOfReadOperationsPerSecond\":23.560375,\"numberOfWriteOperationsPerSecond\":23.65641}],\"productSupportStatus\":{\"currentVersion\":\"thost\",\"servicePackStatus\":\"tstvdxeclzedq\",\"esuStatus\":\"vh\",\"supportStatus\":\"h\",\"eta\":693304246,\"currentEsuYear\":\"qkdlw\",\"mainstreamEndDate\":\"2021-06-02T22:55:20Z\",\"extendedSupportEndDate\":\"2021-04-24T09:11:55Z\",\"extendedSecurityUpdateYear1EndDate\":\"2021-11-14T02:43:26Z\",\"extendedSecurityUpdateYear2EndDate\":\"2021-01-09T13:22:40Z\",\"extendedSecurityUpdateYear3EndDate\":\"2021-05-26T02:30:15Z\"},\"fciMetadata\":{\"state\":\"Inherited\",\"isMultiSubnet\":true,\"fciSharedDiskCount\":2109905275},\"availabilityReplicaSummary\":{\"numberOfSynchronousReadReplicas\":765522642,\"numberOfSynchronousNonReadReplicas\":16168895,\"numberOfAsynchronousReadReplicas\":1857777885,\"numberOfAsynchronousNonReadReplicas\":804071808,\"numberOfPrimaryReplicas\":836535007},\"isClustered\":true,\"isHighAvailabilityEnabled\":true,\"recommendedTargetReasonings\":[{\"reasoningId\":\"rhubskhud\",\"reasoningString\":\"oookkqfq\",\"reasoningCategory\":\"vleo\",\"contextParameters\":[{}]},{\"reasoningId\":\"uiqtqzfavy\",\"reasoningString\":\"qqybarye\",\"reasoningCategory\":\"yjkqabqgzslesjcb\",\"contextParameters\":[{},{},{}]},{\"reasoningId\":\"ntiew\",\"reasoningString\":\"cv\",\"reasoningCategory\":\"uwrbehwagoh\",\"contextParameters\":[{}]},{\"reasoningId\":\"kmr\",\"reasoningString\":\"mvvhmxtdrjfuta\",\"reasoningCategory\":\"ebjvewzcjzn\",\"contextParameters\":[{},{},{},{}]}],\"machineArmId\":\"mguaadraufa\",\"machineName\":\"kahzo\",\"instanceName\":\"jjziuxxpsh\",\"sqlInstanceSdsArmId\":\"e\",\"sqlEdition\":\"lfg\",\"sqlVersion\":\"qubkw\",\"numberOfCoresAllocated\":702643575,\"percentageCoresUtilization\":17.831444,\"logicalDisks\":[{\"diskId\":\"tujbazpju\",\"diskSizeInMB\":65.31831,\"megabytesPerSecondOfRead\":25.543505,\"megabytesPerSecondOfWrite\":69.86077,\"numberOfReadOperationsPerSecond\":86.60149,\"numberOfWriteOperationsPerSecond\":18.283283},{\"diskId\":\"mduvw\",\"diskSizeInMB\":39.49926,\"megabytesPerSecondOfRead\":71.83409,\"megabytesPerSecondOfWrite\":66.04359,\"numberOfReadOperationsPerSecond\":27.807796,\"numberOfWriteOperationsPerSecond\":26.512533}],\"databaseSummary\":{\"numberOfUserDatabases\":181907688,\"totalDatabaseSizeInMB\":34.69194,\"largestDatabaseSizeInMB\":23.62407,\"totalDiscoveredUserDatabases\":1044665061},\"confidenceRatingInPercentage\":36.441113,\"sizingCriterion\":\"PerformanceBased\",\"createdTimestamp\":\"2021-05-29T06:21:05Z\",\"updatedTimestamp\":\"2021-05-09T12:03:02Z\"},\"id\":\"gibbdaxc\",\"name\":\"nfo\",\"type\":\"auorsukokw\"},{\"properties\":{\"memoryInUseInMB\":19.009077,\"hasScanOccurred\":true,\"recommendedAzureSqlTargetType\":\"Recommended\",\"recommendedSuitability\":\"ConditionallySuitableForSqlDB\",\"azureSqlMISuitabilityDetails\":{\"azureSqlSku\":{\"azureSqlServiceTier\":\"BusinessCritical\",\"azureSqlComputeTier\":\"Serverless\",\"azureSqlHardwareGeneration\":\"Automatic\",\"storageMaxSizeInMB\":75.409386,\"predictedDataSizeInMB\":1.0991573,\"predictedLogSizeInMB\":16.2947,\"cores\":1290354736,\"azureSqlTargetType\":\"AzureSqlVirtualMachine\"},\"replicaAzureSqlSku\":[{},{}],\"sharedResources\":{\"sharedDataDisks\":[{},{}],\"sharedLogDisks\":[{},{},{}],\"sharedTempDbDisks\":[{},{}],\"numberOfMounts\":2013507582,\"quorumWitness\":{}},\"monthlyComputeCost\":11.9415045,\"monthlyStorageCost\":90.519005,\"costComponents\":[{},{}],\"securitySuitability\":\"Unknown\",\"shouldProvisionReplicas\":false,\"skuReplicationMode\":\"FailoverGroupInstance\",\"migrationGuidelines\":[{},{}],\"recommendationReasonings\":[{},{},{},{}],\"migrationTargetPlatform\":\"Unknown\",\"suitability\":\"ReadinessUnknown\",\"migrationIssues\":[{}]},\"azureSqlDBSuitabilityDetails\":{\"azureSqlSku\":{\"azureSqlServiceTier\":\"Unknown\",\"azureSqlComputeTier\":\"Provisioned\",\"azureSqlHardwareGeneration\":\"Gen5\",\"storageMaxSizeInMB\":12.222469,\"predictedDataSizeInMB\":1.7481148,\"predictedLogSizeInMB\":53.11064,\"cores\":1357028156,\"azureSqlTargetType\":\"AzureSqlDatabase\"},\"replicaAzureSqlSku\":[{},{},{}],\"sharedResources\":{\"sharedDataDisks\":[{},{},{}],\"sharedLogDisks\":[{}],\"sharedTempDbDisks\":[{},{},{},{}],\"numberOfMounts\":315622888,\"quorumWitness\":{}},\"monthlyComputeCost\":92.20822,\"monthlyStorageCost\":32.07748,\"costComponents\":[{},{},{}],\"securitySuitability\":\"Suitable\",\"shouldProvisionReplicas\":false,\"skuReplicationMode\":\"ActiveGeoReplication\",\"migrationGuidelines\":[{},{}],\"recommendationReasonings\":[{},{}],\"migrationTargetPlatform\":\"Unknown\",\"suitability\":\"Suitable\",\"migrationIssues\":[{}]},\"azureSqlVMSuitabilityDetails\":{\"azureSqlSku\":{\"virtualMachineSize\":{},\"dataDiskSizes\":[{}],\"logDiskSizes\":[{},{},{}],\"azureSqlTargetType\":\"Recommended\"},\"replicaAzureSqlSku\":[{},{}],\"sharedResources\":{\"sharedDataDisks\":[{}],\"sharedLogDisks\":[{},{},{}],\"sharedTempDbDisks\":[{},{}],\"numberOfMounts\":64895608,\"quorumWitness\":{}},\"monthlyComputeCost\":45.34594,\"monthlyStorageCost\":46.00898,\"costComponents\":[{},{}],\"securitySuitability\":\"ReadinessUnknown\",\"shouldProvisionReplicas\":true,\"skuReplicationMode\":\"FailoverGroupInstance\",\"migrationGuidelines\":[{},{}],\"recommendationReasonings\":[{},{},{},{}],\"migrationTargetPlatform\":\"AzureSqlDatabase\",\"suitability\":\"Unknown\",\"migrationIssues\":[{},{},{},{}]},\"storageTypeBasedDetails\":[{\"storageType\":\"szqujizdvoq\",\"diskSizeInMB\":88.05086,\"megabytesPerSecondOfRead\":9.872651,\"megabytesPerSecondOfWrite\":7.6423407,\"numberOfReadOperationsPerSecond\":69.872574,\"numberOfWriteOperationsPerSecond\":30.12582},{\"storageType\":\"avu\",\"diskSizeInMB\":54.3682,\"megabytesPerSecondOfRead\":38.259933,\"megabytesPerSecondOfWrite\":12.625467,\"numberOfReadOperationsPerSecond\":90.963974,\"numberOfWriteOperationsPerSecond\":33.112614}],\"productSupportStatus\":{\"currentVersion\":\"sbpimlq\",\"servicePackStatus\":\"jxkcgxxlxsff\",\"esuStatus\":\"vizqzdwl\",\"supportStatus\":\"lyoupfgfbkju\",\"eta\":1006951199,\"currentEsuYear\":\"gkfmins\",\"mainstreamEndDate\":\"2021-04-25T05:32:28Z\",\"extendedSupportEndDate\":\"2021-04-01T08:47:57Z\",\"extendedSecurityUpdateYear1EndDate\":\"2021-05-24T09:09:21Z\",\"extendedSecurityUpdateYear2EndDate\":\"2020-12-29T13:16:58Z\",\"extendedSecurityUpdateYear3EndDate\":\"2021-03-02T23:21:27Z\"},\"fciMetadata\":{\"state\":\"Online\",\"isMultiSubnet\":true,\"fciSharedDiskCount\":1086150789},\"availabilityReplicaSummary\":{\"numberOfSynchronousReadReplicas\":2006118206,\"numberOfSynchronousNonReadReplicas\":118535522,\"numberOfAsynchronousReadReplicas\":1217445631,\"numberOfAsynchronousNonReadReplicas\":563035925,\"numberOfPrimaryReplicas\":1089045976},\"isClustered\":false,\"isHighAvailabilityEnabled\":false,\"recommendedTargetReasonings\":[{\"reasoningId\":\"q\",\"reasoningString\":\"rnxrxcpj\",\"reasoningCategory\":\"savokqdzf\",\"contextParameters\":[{}]},{\"reasoningId\":\"vjlfrqtt\",\"reasoningString\":\"jlkatnwxy\",\"reasoningCategory\":\"pidkqqfkuvscxkdm\",\"contextParameters\":[{},{},{},{}]},{\"reasoningId\":\"vibrxkpmloazuruo\",\"reasoningString\":\"goorbteo\",\"reasoningCategory\":\"fhjxakvvjgs\",\"contextParameters\":[{}]}],\"machineArmId\":\"il\",\"machineName\":\"wwtkg\",\"instanceName\":\"nye\",\"sqlInstanceSdsArmId\":\"b\",\"sqlEdition\":\"vudtjuewbcihx\",\"sqlVersion\":\"whcjyxcc\",\"numberOfCoresAllocated\":970870399,\"percentageCoresUtilization\":60.170685,\"logicalDisks\":[{\"diskId\":\"kudzpxgwj\",\"diskSizeInMB\":16.411697,\"megabytesPerSecondOfRead\":53.891308,\"megabytesPerSecondOfWrite\":64.56741,\"numberOfReadOperationsPerSecond\":98.82529,\"numberOfWriteOperationsPerSecond\":73.92511},{\"diskId\":\"fkyrk\",\"diskSizeInMB\":6.8435373,\"megabytesPerSecondOfRead\":56.479233,\"megabytesPerSecondOfWrite\":15.116018,\"numberOfReadOperationsPerSecond\":37.10237,\"numberOfWriteOperationsPerSecond\":26.578474}],\"databaseSummary\":{\"numberOfUserDatabases\":1662791957,\"totalDatabaseSizeInMB\":94.966415,\"largestDatabaseSizeInMB\":80.58958,\"totalDiscoveredUserDatabases\":1666235741},\"confidenceRatingInPercentage\":14.321136,\"sizingCriterion\":\"PerformanceBased\",\"createdTimestamp\":\"2021-08-25T16:30:07Z\",\"updatedTimestamp\":\"2021-02-08T23:25:54Z\"},\"id\":\"gfnmntfpmvmemfnc\",\"name\":\"dwvvba\",\"type\":\"xlllchp\"},{\"properties\":{\"memoryInUseInMB\":77.99745,\"hasScanOccurred\":true,\"recommendedAzureSqlTargetType\":\"AzureSqlVirtualMachine\",\"recommendedSuitability\":\"SuitableForSqlDB\",\"azureSqlMISuitabilityDetails\":{\"azureSqlSku\":{\"azureSqlServiceTier\":\"HyperScale\",\"azureSqlComputeTier\":\"Serverless\",\"azureSqlHardwareGeneration\":\"M_series\",\"storageMaxSizeInMB\":34.633957,\"predictedDataSizeInMB\":78.143,\"predictedLogSizeInMB\":54.562737,\"cores\":1165309637,\"azureSqlTargetType\":\"AzureSqlVirtualMachine\"},\"replicaAzureSqlSku\":[{},{}],\"sharedResources\":{\"sharedDataDisks\":[{},{}],\"sharedLogDisks\":[{},{},{},{}],\"sharedTempDbDisks\":[{}],\"numberOfMounts\":631107682,\"quorumWitness\":{}},\"monthlyComputeCost\":77.97097,\"monthlyStorageCost\":48.8412,\"costComponents\":[{},{},{}],\"securitySuitability\":\"Unknown\",\"shouldProvisionReplicas\":true,\"skuReplicationMode\":\"ActiveGeoReplication\",\"migrationGuidelines\":[{},{},{},{}],\"recommendationReasonings\":[{},{},{},{}],\"migrationTargetPlatform\":\"AzureSqlDatabase\",\"suitability\":\"ReadinessUnknown\",\"migrationIssues\":[{},{}]},\"azureSqlDBSuitabilityDetails\":{\"azureSqlSku\":{\"azureSqlServiceTier\":\"Automatic\",\"azureSqlComputeTier\":\"Provisioned\",\"azureSqlHardwareGeneration\":\"Fsv2_series\",\"storageMaxSizeInMB\":43.476677,\"predictedDataSizeInMB\":48.135914,\"predictedLogSizeInMB\":7.1958246,\"cores\":1351999302,\"azureSqlTargetType\":\"AzureVirtualMachine\"},\"replicaAzureSqlSku\":[{},{}],\"sharedResources\":{\"sharedDataDisks\":[{}],\"sharedLogDisks\":[{}],\"sharedTempDbDisks\":[{},{},{},{}],\"numberOfMounts\":1360898265,\"quorumWitness\":{}},\"monthlyComputeCost\":1.5846968,\"monthlyStorageCost\":72.977165,\"costComponents\":[{}],\"securitySuitability\":\"Unknown\",\"shouldProvisionReplicas\":true,\"skuReplicationMode\":\"FailoverGroupInstance\",\"migrationGuidelines\":[{},{},{}],\"recommendationReasonings\":[{},{},{},{}],\"migrationTargetPlatform\":\"AzureSqlDatabase\",\"suitability\":\"ConditionallySuitable\",\"migrationIssues\":[{},{}]},\"azureSqlVMSuitabilityDetails\":{\"azureSqlSku\":{\"virtualMachineSize\":{},\"dataDiskSizes\":[{},{},{},{}],\"logDiskSizes\":[{},{},{},{}],\"azureSqlTargetType\":\"AzureVirtualMachine\"},\"replicaAzureSqlSku\":[{},{},{}],\"sharedResources\":{\"sharedDataDisks\":[{},{},{},{}],\"sharedLogDisks\":[{},{}],\"sharedTempDbDisks\":[{}],\"numberOfMounts\":1622388222,\"quorumWitness\":{}},\"monthlyComputeCost\":65.579056,\"monthlyStorageCost\":74.3787,\"costComponents\":[{},{}],\"securitySuitability\":\"ReadinessUnknown\",\"shouldProvisionReplicas\":false,\"skuReplicationMode\":\"NotApplicable\",\"migrationGuidelines\":[{}],\"recommendationReasonings\":[{},{}],\"migrationTargetPlatform\":\"AzureSqlVirtualMachine\",\"suitability\":\"Unknown\",\"migrationIssues\":[{},{}]},\"storageTypeBasedDetails\":[{\"storageType\":\"fqzhv\",\"diskSizeInMB\":36.793434,\"megabytesPerSecondOfRead\":13.861406,\"megabytesPerSecondOfWrite\":42.81506,\"numberOfReadOperationsPerSecond\":93.550156,\"numberOfWriteOperationsPerSecond\":43.901634},{\"storageType\":\"kjpvdwxf\",\"diskSizeInMB\":99.00972,\"megabytesPerSecondOfRead\":48.665874,\"megabytesPerSecondOfWrite\":14.327431,\"numberOfReadOperationsPerSecond\":45.895924,\"numberOfWriteOperationsPerSecond\":83.45672},{\"storageType\":\"sxjrk\",\"diskSizeInMB\":49.111115,\"megabytesPerSecondOfRead\":40.838493,\"megabytesPerSecondOfWrite\":17.515266,\"numberOfReadOperationsPerSecond\":28.952526,\"numberOfWriteOperationsPerSecond\":72.90136}],\"productSupportStatus\":{\"currentVersion\":\"q\",\"servicePackStatus\":\"vldspa\",\"esuStatus\":\"jbkkdmflvestmjl\",\"supportStatus\":\"ril\",\"eta\":1058689711,\"currentEsuYear\":\"eewchpxlktw\",\"mainstreamEndDate\":\"2021-12-02T10:26:58Z\",\"extendedSupportEndDate\":\"2021-02-16T10:40:04Z\",\"extendedSecurityUpdateYear1EndDate\":\"2021-05-28T01:28:42Z\",\"extendedSecurityUpdateYear2EndDate\":\"2021-01-26T13:39:55Z\",\"extendedSecurityUpdateYear3EndDate\":\"2021-06-28T05:31:47Z\"},\"fciMetadata\":{\"state\":\"Online\",\"isMultiSubnet\":false,\"fciSharedDiskCount\":743111845},\"availabilityReplicaSummary\":{\"numberOfSynchronousReadReplicas\":1077847462,\"numberOfSynchronousNonReadReplicas\":400720959,\"numberOfAsynchronousReadReplicas\":1558169297,\"numberOfAsynchronousNonReadReplicas\":1002446412,\"numberOfPrimaryReplicas\":950056847},\"isClustered\":false,\"isHighAvailabilityEnabled\":true,\"recommendedTargetReasonings\":[{\"reasoningId\":\"zrrjvpgly\",\"reasoningString\":\"gkrvqeevto\",\"reasoningCategory\":\"r\",\"contextParameters\":[{}]}],\"machineArmId\":\"wytpzdmovz\",\"machineName\":\"va\",\"instanceName\":\"zqadf\",\"sqlInstanceSdsArmId\":\"z\",\"sqlEdition\":\"iglaecx\",\"sqlVersion\":\"t\",\"numberOfCoresAllocated\":1510056241,\"percentageCoresUtilization\":16.003609,\"logicalDisks\":[{\"diskId\":\"lqtmldgxob\",\"diskSizeInMB\":38.34113,\"megabytesPerSecondOfRead\":47.5388,\"megabytesPerSecondOfWrite\":13.118106,\"numberOfReadOperationsPerSecond\":74.10391,\"numberOfWriteOperationsPerSecond\":25.982613},{\"diskId\":\"zriykhy\",\"diskSizeInMB\":85.29825,\"megabytesPerSecondOfRead\":14.867121,\"megabytesPerSecondOfWrite\":3.6425412,\"numberOfReadOperationsPerSecond\":85.78786,\"numberOfWriteOperationsPerSecond\":50.352837},{\"diskId\":\"jlmxhomdynhd\",\"diskSizeInMB\":14.867181,\"megabytesPerSecondOfRead\":65.220894,\"megabytesPerSecondOfWrite\":96.30957,\"numberOfReadOperationsPerSecond\":44.797707,\"numberOfWriteOperationsPerSecond\":71.97788}],\"databaseSummary\":{\"numberOfUserDatabases\":171373878,\"totalDatabaseSizeInMB\":9.2906,\"largestDatabaseSizeInMB\":4.538435,\"totalDiscoveredUserDatabases\":1799745167},\"confidenceRatingInPercentage\":10.202331,\"sizingCriterion\":\"AsOnPremises\",\"createdTimestamp\":\"2021-05-07T02:49:48Z\",\"updatedTimestamp\":\"2021-01-19T00:29:52Z\"},\"id\":\"aiqyuvvfo\",\"name\":\"kphhq\",\"type\":\"ikvylauya\"}],\"nextLink\":\"uwmncs\"}") + .toObject(AssessedSqlInstanceV2ListResult.class); + Assertions.assertEquals("uwmncs", model.nextLink()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AssessedSqlInstanceV2ListResult model = new AssessedSqlInstanceV2ListResult() + .withValue( + Arrays.asList(new AssessedSqlInstanceV2Inner().withProperties(new AssessedSqlInstanceV2Properties()), + new AssessedSqlInstanceV2Inner().withProperties(new AssessedSqlInstanceV2Properties()), + new AssessedSqlInstanceV2Inner().withProperties(new AssessedSqlInstanceV2Properties()))) + .withNextLink("uwmncs"); + model = BinaryData.fromObject(model).toObject(AssessedSqlInstanceV2ListResult.class); + Assertions.assertEquals("uwmncs", model.nextLink()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlInstanceV2OperationsGetWithResponseMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlInstanceV2OperationsGetWithResponseMockTests.java new file mode 100644 index 000000000000..2e03de8967ec --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlInstanceV2OperationsGetWithResponseMockTests.java @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlInstanceV2; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class AssessedSqlInstanceV2OperationsGetWithResponseMockTests { + @Test + public void testGetWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"memoryInUseInMB\":19.453466,\"hasScanOccurred\":false,\"recommendedAzureSqlTargetType\":\"AzureSqlVirtualMachine\",\"recommendedSuitability\":\"NotSuitable\",\"azureSqlMISuitabilityDetails\":{\"azureSqlSku\":{\"azureSqlServiceTier\":\"Automatic\",\"azureSqlComputeTier\":\"Automatic\",\"azureSqlHardwareGeneration\":\"Unknown\",\"storageMaxSizeInMB\":45.947193,\"predictedDataSizeInMB\":52.061802,\"predictedLogSizeInMB\":64.5819,\"cores\":1310159626,\"azureSqlTargetType\":\"AzureSqlVirtualMachine\"},\"replicaAzureSqlSku\":[{\"azureSqlServiceTier\":\"BusinessCritical\",\"azureSqlComputeTier\":\"Automatic\",\"azureSqlHardwareGeneration\":\"M_series\",\"storageMaxSizeInMB\":67.216576,\"predictedDataSizeInMB\":4.7587276,\"predictedLogSizeInMB\":65.09306,\"cores\":237480750,\"azureSqlTargetType\":\"Unknown\"},{\"azureSqlServiceTier\":\"GeneralPurpose\",\"azureSqlComputeTier\":\"Provisioned\",\"azureSqlHardwareGeneration\":\"Unknown\",\"storageMaxSizeInMB\":97.77749,\"predictedDataSizeInMB\":2.8196573,\"predictedLogSizeInMB\":65.7672,\"cores\":213893896,\"azureSqlTargetType\":\"AzureSqlVirtualMachine\"},{\"azureSqlServiceTier\":\"BusinessCritical\",\"azureSqlComputeTier\":\"Serverless\",\"azureSqlHardwareGeneration\":\"Gen5\",\"storageMaxSizeInMB\":94.609795,\"predictedDataSizeInMB\":18.32378,\"predictedLogSizeInMB\":17.042362,\"cores\":479855612,\"azureSqlTargetType\":\"AzureSqlVirtualMachine\"},{\"azureSqlServiceTier\":\"Unknown\",\"azureSqlComputeTier\":\"Serverless\",\"azureSqlHardwareGeneration\":\"Unknown\",\"storageMaxSizeInMB\":43.615593,\"predictedDataSizeInMB\":93.414345,\"predictedLogSizeInMB\":74.58498,\"cores\":397490106,\"azureSqlTargetType\":\"AzureVirtualMachine\"}],\"sharedResources\":{\"sharedDataDisks\":[{},{},{}],\"sharedLogDisks\":[{}],\"sharedTempDbDisks\":[{},{},{}],\"numberOfMounts\":1331477699,\"quorumWitness\":{\"quorumWitnessType\":\"Cloud\"}},\"monthlyComputeCost\":6.4360976,\"monthlyStorageCost\":23.65986,\"costComponents\":[{\"name\":\"MonthlyAzureHybridCostSavings\",\"value\":12.912739,\"description\":\"pu\"},{\"name\":\"MonthlyPremiumV2StorageCost\",\"value\":34.745342,\"description\":\"jljmphfkyezol\"}],\"securitySuitability\":\"NotSuitable\",\"shouldProvisionReplicas\":true,\"skuReplicationMode\":\"ActiveGeoReplication\",\"migrationGuidelines\":[{\"guidelineId\":\"ccn\",\"migrationGuidelineCategory\":\"FailoverCluterInstanceGuideLine\",\"migrationGuidelineContext\":[{},{}]},{\"guidelineId\":\"bui\",\"migrationGuidelineCategory\":\"AvailabilityGroupGuideline\",\"migrationGuidelineContext\":[{},{}]},{\"guidelineId\":\"ecaatsdohzniuc\",\"migrationGuidelineCategory\":\"FailoverCluterInstanceGuideLine\",\"migrationGuidelineContext\":[{},{},{},{}]}],\"recommendationReasonings\":[{\"reasoningId\":\"injdllwktlepo\",\"reasoningString\":\"vvqxua\",\"reasoningCategory\":\"cqwulynkgfcfd\",\"contextParameters\":[{},{},{},{}]},{\"reasoningId\":\"i\",\"reasoningString\":\"xtclhuulriqbyok\",\"reasoningCategory\":\"gbzsxebrslt\",\"contextParameters\":[{},{},{},{}]},{\"reasoningId\":\"cdjwsu\",\"reasoningString\":\"r\",\"reasoningCategory\":\"agttpufpb\",\"contextParameters\":[{},{},{}]}],\"migrationTargetPlatform\":\"AzureVirtualMachine\",\"suitability\":\"ConditionallySuitable\",\"migrationIssues\":[{\"issueId\":\"bfwxiplkys\",\"issueCategory\":\"Internal\",\"impactedObjects\":[{}]},{\"issueId\":\"rxslwhdmcv\",\"issueCategory\":\"Warning\",\"impactedObjects\":[{},{},{},{}]},{\"issueId\":\"hfvhuwzbxpcqz\",\"issueCategory\":\"Issue\",\"impactedObjects\":[{},{}]}]},\"azureSqlDBSuitabilityDetails\":{\"azureSqlSku\":{\"azureSqlServiceTier\":\"BusinessCritical\",\"azureSqlComputeTier\":\"Unknown\",\"azureSqlHardwareGeneration\":\"DC_series\",\"storageMaxSizeInMB\":42.872566,\"predictedDataSizeInMB\":79.52465,\"predictedLogSizeInMB\":8.235895,\"cores\":1723467853,\"azureSqlTargetType\":\"AzureVirtualMachine\"},\"replicaAzureSqlSku\":[{\"azureSqlServiceTier\":\"BusinessCritical\",\"azureSqlComputeTier\":\"Automatic\",\"azureSqlHardwareGeneration\":\"Gen5\",\"storageMaxSizeInMB\":50.997044,\"predictedDataSizeInMB\":65.91321,\"predictedLogSizeInMB\":34.034336,\"cores\":271586436,\"azureSqlTargetType\":\"AzureSqlVirtualMachine\"}],\"sharedResources\":{\"sharedDataDisks\":[{}],\"sharedLogDisks\":[{}],\"sharedTempDbDisks\":[{},{},{},{}],\"numberOfMounts\":101688613,\"quorumWitness\":{\"quorumWitnessType\":\"Cloud\"}},\"monthlyComputeCost\":39.085915,\"monthlyStorageCost\":56.776505,\"costComponents\":[{\"name\":\"Unknown\",\"value\":61.30045,\"description\":\"ejeg\"},{\"name\":\"MonthlyPremiumV2StorageCost\",\"value\":35.092632,\"description\":\"wrjmwv\"}],\"securitySuitability\":\"Suitable\",\"shouldProvisionReplicas\":true,\"skuReplicationMode\":\"FailoverGroupInstance\",\"migrationGuidelines\":[{\"guidelineId\":\"wgxql\",\"migrationGuidelineCategory\":\"Unknown\",\"migrationGuidelineContext\":[{},{},{}]},{\"guidelineId\":\"gxieqfkyfhi\",\"migrationGuidelineCategory\":\"AvailabilityGroupGuideline\",\"migrationGuidelineContext\":[{}]},{\"guidelineId\":\"pbyynvskpajbm\",\"migrationGuidelineCategory\":\"General\",\"migrationGuidelineContext\":[{}]},{\"guidelineId\":\"mj\",\"migrationGuidelineCategory\":\"FailoverCluterInstanceGuideLine\",\"migrationGuidelineContext\":[{},{}]}],\"recommendationReasonings\":[{\"reasoningId\":\"qmtxapeqiscrp\",\"reasoningString\":\"gftrqrejdaahuqim\",\"reasoningCategory\":\"ahlfxlmuifmuadj\",\"contextParameters\":[{}]}],\"migrationTargetPlatform\":\"AzureSqlManagedInstance\",\"suitability\":\"ConditionallySuitable\",\"migrationIssues\":[{\"issueId\":\"shjgczetybnxg\",\"issueCategory\":\"Issue\",\"impactedObjects\":[{},{}]},{\"issueId\":\"tjchfjvmy\",\"issueCategory\":\"Warning\",\"impactedObjects\":[{},{},{},{}]},{\"issueId\":\"cu\",\"issueCategory\":\"Issue\",\"impactedObjects\":[{},{}]},{\"issueId\":\"wc\",\"issueCategory\":\"Internal\",\"impactedObjects\":[{},{},{},{}]}]},\"azureSqlVMSuitabilityDetails\":{\"azureSqlSku\":{\"virtualMachineSize\":{\"azureVmFamily\":\"Lsv2_series\",\"cores\":104057558,\"azureSkuName\":\"Standard_M8ms\",\"availableCores\":123145419,\"maxNetworkInterfaces\":711165961},\"dataDiskSizes\":[{},{},{},{}],\"logDiskSizes\":[{},{}],\"azureSqlTargetType\":\"AzureSqlVirtualMachine\"},\"replicaAzureSqlSku\":[{\"virtualMachineSize\":{},\"dataDiskSizes\":[{},{},{},{}],\"logDiskSizes\":[{},{}],\"azureSqlTargetType\":\"Recommended\"},{\"virtualMachineSize\":{},\"dataDiskSizes\":[{}],\"logDiskSizes\":[{},{}],\"azureSqlTargetType\":\"AzureSqlDatabase\"},{\"virtualMachineSize\":{},\"dataDiskSizes\":[{},{}],\"logDiskSizes\":[{},{}],\"azureSqlTargetType\":\"AzureSqlManagedInstance\"},{\"virtualMachineSize\":{},\"dataDiskSizes\":[{},{}],\"logDiskSizes\":[{},{},{}],\"azureSqlTargetType\":\"Unknown\"}],\"sharedResources\":{\"sharedDataDisks\":[{}],\"sharedLogDisks\":[{}],\"sharedTempDbDisks\":[{}],\"numberOfMounts\":214582888,\"quorumWitness\":{\"quorumWitnessType\":\"Cloud\"}},\"monthlyComputeCost\":56.19525,\"monthlyStorageCost\":79.92231,\"costComponents\":[{\"name\":\"MonthlySecurityCost\",\"value\":86.46576,\"description\":\"ntwhymxymulwiv\"},{\"name\":\"Unknown\",\"value\":17.481882,\"description\":\"lsycoyb\"}],\"securitySuitability\":\"Unknown\",\"shouldProvisionReplicas\":true,\"skuReplicationMode\":\"FailoverGroupInstance\",\"migrationGuidelines\":[{\"guidelineId\":\"cywhj\",\"migrationGuidelineCategory\":\"General\",\"migrationGuidelineContext\":[{},{},{}]},{\"guidelineId\":\"oh\",\"migrationGuidelineCategory\":\"General\",\"migrationGuidelineContext\":[{},{},{}]},{\"guidelineId\":\"pukiymjzpwdlvwt\",\"migrationGuidelineCategory\":\"FailoverCluterInstanceGuideLine\",\"migrationGuidelineContext\":[{},{},{},{}]}],\"recommendationReasonings\":[{\"reasoningId\":\"nhqnampp\",\"reasoningString\":\"tassaekewna\",\"reasoningCategory\":\"ajbk\",\"contextParameters\":[{},{},{}]},{\"reasoningId\":\"yizyddcvxodk\",\"reasoningString\":\"fsxxby\",\"reasoningCategory\":\"sqlv\",\"contextParameters\":[{},{},{},{}]},{\"reasoningId\":\"wgoljtzx\",\"reasoningString\":\"xsdobygoogxqapjx\",\"reasoningCategory\":\"zyjfuc\",\"contextParameters\":[{},{}]}],\"migrationTargetPlatform\":\"AzureVirtualMachine\",\"suitability\":\"NotSuitable\",\"migrationIssues\":[{\"issueId\":\"vibfasgmatrnzpd\",\"issueCategory\":\"Internal\",\"impactedObjects\":[{}]}]},\"storageTypeBasedDetails\":[{\"storageType\":\"jktzboimyfpq\",\"diskSizeInMB\":73.76388,\"megabytesPerSecondOfRead\":88.76066,\"megabytesPerSecondOfWrite\":40.329243,\"numberOfReadOperationsPerSecond\":46.28459,\"numberOfWriteOperationsPerSecond\":71.138016}],\"productSupportStatus\":{\"currentVersion\":\"pctf\",\"servicePackStatus\":\"kffffgkuh\",\"esuStatus\":\"whvuldbkk\",\"supportStatus\":\"jkjigawgaz\",\"eta\":1272427334,\"currentEsuYear\":\"ifhujjsbcm\",\"mainstreamEndDate\":\"2021-08-31T07:34:01Z\",\"extendedSupportEndDate\":\"2021-11-05T17:50:30Z\",\"extendedSecurityUpdateYear1EndDate\":\"2021-01-17T05:07:29Z\",\"extendedSecurityUpdateYear2EndDate\":\"2021-04-15T18:23:21Z\",\"extendedSecurityUpdateYear3EndDate\":\"2021-05-31T02:30:19Z\"},\"fciMetadata\":{\"state\":\"Unknown\",\"isMultiSubnet\":false,\"fciSharedDiskCount\":22789876},\"availabilityReplicaSummary\":{\"numberOfSynchronousReadReplicas\":1841605546,\"numberOfSynchronousNonReadReplicas\":521127313,\"numberOfAsynchronousReadReplicas\":356055012,\"numberOfAsynchronousNonReadReplicas\":1899652732,\"numberOfPrimaryReplicas\":825740305},\"isClustered\":true,\"isHighAvailabilityEnabled\":true,\"recommendedTargetReasonings\":[{\"reasoningId\":\"oialahfxwccokdx\",\"reasoningString\":\"kmkcz\",\"reasoningCategory\":\"uhhoqeqshavlj\",\"contextParameters\":[{},{}]},{\"reasoningId\":\"rqolnthbb\",\"reasoningString\":\"gzukw\",\"reasoningCategory\":\"nzkjthfceyjn\",\"contextParameters\":[{},{},{}]},{\"reasoningId\":\"fuyf\",\"reasoningString\":\"pfiddhl\",\"reasoningCategory\":\"fz\",\"contextParameters\":[{},{}]},{\"reasoningId\":\"mq\",\"reasoningString\":\"uiocuselqkrsazr\",\"reasoningCategory\":\"uddq\",\"contextParameters\":[{},{}]}],\"machineArmId\":\"fisjmrkk\",\"machineName\":\"wdmdlgyqixokwt\",\"instanceName\":\"whvagnqfq\",\"sqlInstanceSdsArmId\":\"lcvmyolcaymjch\",\"sqlEdition\":\"snvlaqd\",\"sqlVersion\":\"yzawatu\",\"numberOfCoresAllocated\":805735300,\"percentageCoresUtilization\":56.507713,\"logicalDisks\":[{\"diskId\":\"othymgobl\",\"diskSizeInMB\":51.443768,\"megabytesPerSecondOfRead\":35.20525,\"megabytesPerSecondOfWrite\":78.35538,\"numberOfReadOperationsPerSecond\":32.124214,\"numberOfWriteOperationsPerSecond\":10.101181},{\"diskId\":\"eakhtmhobcya\",\"diskSizeInMB\":65.80291,\"megabytesPerSecondOfRead\":27.580101,\"megabytesPerSecondOfWrite\":29.441761,\"numberOfReadOperationsPerSecond\":99.774185,\"numberOfWriteOperationsPerSecond\":50.755436},{\"diskId\":\"ogxkfnaoa\",\"diskSizeInMB\":64.4314,\"megabytesPerSecondOfRead\":95.15503,\"megabytesPerSecondOfWrite\":52.549206,\"numberOfReadOperationsPerSecond\":52.02517,\"numberOfWriteOperationsPerSecond\":2.8191447}],\"databaseSummary\":{\"numberOfUserDatabases\":1466940432,\"totalDatabaseSizeInMB\":79.28132,\"largestDatabaseSizeInMB\":82.22219,\"totalDiscoveredUserDatabases\":1456079584},\"confidenceRatingInPercentage\":25.972563,\"sizingCriterion\":\"PerformanceBased\",\"createdTimestamp\":\"2021-06-09T18:25:31Z\",\"updatedTimestamp\":\"2021-02-17T03:07:14Z\"},\"id\":\"hajpxecxqnwhsc\",\"name\":\"zawmvgxsmp\",\"type\":\"npwirfljf\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + AssessedSqlInstanceV2 response = manager.assessedSqlInstanceV2Operations() + .getWithResponse("hazyntacihnco", "mip", "mliqmvlb", "i", "eaqgrvgpomxpupd", + com.azure.core.util.Context.NONE) + .getValue(); + + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlInstanceV2OperationsListBySqlAssessmentV2MockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlInstanceV2OperationsListBySqlAssessmentV2MockTests.java new file mode 100644 index 000000000000..3e2d1cf88664 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlInstanceV2OperationsListBySqlAssessmentV2MockTests.java @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlInstanceV2; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class AssessedSqlInstanceV2OperationsListBySqlAssessmentV2MockTests { + @Test + public void testListBySqlAssessmentV2() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"memoryInUseInMB\":33.808918,\"hasScanOccurred\":false,\"recommendedAzureSqlTargetType\":\"AzureVirtualMachine\",\"recommendedSuitability\":\"SuitableForSqlMI\",\"azureSqlMISuitabilityDetails\":{\"azureSqlSku\":{\"azureSqlServiceTier\":\"GeneralPurpose\",\"azureSqlComputeTier\":\"Automatic\",\"azureSqlHardwareGeneration\":\"Fsv2_series\",\"storageMaxSizeInMB\":13.264579,\"predictedDataSizeInMB\":63.21829,\"predictedLogSizeInMB\":6.2892556,\"cores\":997777760,\"azureSqlTargetType\":\"AzureVirtualMachine\"},\"replicaAzureSqlSku\":[{\"azureSqlServiceTier\":\"Unknown\",\"azureSqlComputeTier\":\"Unknown\",\"azureSqlHardwareGeneration\":\"Gen5\",\"storageMaxSizeInMB\":94.98802,\"predictedDataSizeInMB\":7.5854063,\"predictedLogSizeInMB\":31.403267,\"cores\":1914755995,\"azureSqlTargetType\":\"AzureSqlDatabase\"},{\"azureSqlServiceTier\":\"Automatic\",\"azureSqlComputeTier\":\"Unknown\",\"azureSqlHardwareGeneration\":\"Unknown\",\"storageMaxSizeInMB\":74.13537,\"predictedDataSizeInMB\":83.00802,\"predictedLogSizeInMB\":10.367346,\"cores\":281693558,\"azureSqlTargetType\":\"Unknown\"}],\"sharedResources\":{\"sharedDataDisks\":[{}],\"sharedLogDisks\":[{},{},{}],\"sharedTempDbDisks\":[{},{},{},{}],\"numberOfMounts\":631913462,\"quorumWitness\":{\"quorumWitnessType\":\"Cloud\"}},\"monthlyComputeCost\":60.338818,\"monthlyStorageCost\":78.85587,\"costComponents\":[{\"name\":\"Unknown\",\"value\":74.62461,\"description\":\"frjeizikgqaboohx\"},{\"name\":\"Unknown\",\"value\":35.841705,\"description\":\"qsxrmdvewu\"}],\"securitySuitability\":\"ReadinessUnknown\",\"shouldProvisionReplicas\":true,\"skuReplicationMode\":\"FailoverGroupInstance\",\"migrationGuidelines\":[{\"guidelineId\":\"ejkbvhhdaurgho\",\"migrationGuidelineCategory\":\"FailoverCluterInstanceGuideLine\",\"migrationGuidelineContext\":[{}]},{\"guidelineId\":\"k\",\"migrationGuidelineCategory\":\"General\",\"migrationGuidelineContext\":[{},{},{},{}]},{\"guidelineId\":\"ezlqxrkdknkobek\",\"migrationGuidelineCategory\":\"Unknown\",\"migrationGuidelineContext\":[{}]},{\"guidelineId\":\"m\",\"migrationGuidelineCategory\":\"FailoverCluterInstanceGuideLine\",\"migrationGuidelineContext\":[{},{},{}]}],\"recommendationReasonings\":[{\"reasoningId\":\"gwcd\",\"reasoningString\":\"sez\",\"reasoningCategory\":\"xke\",\"contextParameters\":[{},{},{},{}]},{\"reasoningId\":\"aabmdlqjb\",\"reasoningString\":\"pfixlhupmo\",\"reasoningCategory\":\"hzbdnpxpkcd\",\"contextParameters\":[{},{}]},{\"reasoningId\":\"xelyicghflr\",\"reasoningString\":\"ssjyghsfx\",\"reasoningCategory\":\"bh\",\"contextParameters\":[{},{}]},{\"reasoningId\":\"mqfmefgvqcpd\",\"reasoningString\":\"gquxweysland\",\"reasoningCategory\":\"cdjhunhg\",\"contextParameters\":[{},{},{}]}],\"migrationTargetPlatform\":\"AzureSqlDatabase\",\"suitability\":\"ConditionallySuitable\",\"migrationIssues\":[{\"issueId\":\"uoxsot\",\"issueCategory\":\"Internal\",\"impactedObjects\":[{},{},{},{}]},{\"issueId\":\"eobfsxstcyilbvzm\",\"issueCategory\":\"Issue\",\"impactedObjects\":[{},{}]},{\"issueId\":\"quzexokjxebjvbz\",\"issueCategory\":\"Internal\",\"impactedObjects\":[{},{},{}]},{\"issueId\":\"mvoglj\",\"issueCategory\":\"Issue\",\"impactedObjects\":[{}]}]},\"azureSqlDBSuitabilityDetails\":{\"azureSqlSku\":{\"azureSqlServiceTier\":\"GeneralPurpose\",\"azureSqlComputeTier\":\"Serverless\",\"azureSqlHardwareGeneration\":\"Fsv2_series\",\"storageMaxSizeInMB\":33.00345,\"predictedDataSizeInMB\":30.276209,\"predictedLogSizeInMB\":21.576887,\"cores\":1389972866,\"azureSqlTargetType\":\"AzureSqlVirtualMachine\"},\"replicaAzureSqlSku\":[{\"azureSqlServiceTier\":\"Unknown\",\"azureSqlComputeTier\":\"Provisioned\",\"azureSqlHardwareGeneration\":\"Unknown\",\"storageMaxSizeInMB\":57.369076,\"predictedDataSizeInMB\":81.87431,\"predictedLogSizeInMB\":83.95499,\"cores\":566172372,\"azureSqlTargetType\":\"Recommended\"},{\"azureSqlServiceTier\":\"BusinessCritical\",\"azureSqlComputeTier\":\"Unknown\",\"azureSqlHardwareGeneration\":\"Gen5\",\"storageMaxSizeInMB\":78.953186,\"predictedDataSizeInMB\":87.84802,\"predictedLogSizeInMB\":19.716978,\"cores\":206631041,\"azureSqlTargetType\":\"Recommended\"},{\"azureSqlServiceTier\":\"Unknown\",\"azureSqlComputeTier\":\"Serverless\",\"azureSqlHardwareGeneration\":\"Gen5\",\"storageMaxSizeInMB\":30.602943,\"predictedDataSizeInMB\":16.692627,\"predictedLogSizeInMB\":39.051582,\"cores\":1674868569,\"azureSqlTargetType\":\"AzureSqlDatabase\"},{\"azureSqlServiceTier\":\"Unknown\",\"azureSqlComputeTier\":\"Automatic\",\"azureSqlHardwareGeneration\":\"Gen5\",\"storageMaxSizeInMB\":27.860897,\"predictedDataSizeInMB\":7.6609254,\"predictedLogSizeInMB\":48.291744,\"cores\":724295825,\"azureSqlTargetType\":\"AzureVirtualMachine\"}],\"sharedResources\":{\"sharedDataDisks\":[{}],\"sharedLogDisks\":[{}],\"sharedTempDbDisks\":[{},{},{},{}],\"numberOfMounts\":1257889233,\"quorumWitness\":{\"quorumWitnessType\":\"Unknown\"}},\"monthlyComputeCost\":55.536007,\"monthlyStorageCost\":55.264236,\"costComponents\":[{\"name\":\"MonthlySecurityCost\",\"value\":22.828722,\"description\":\"pywyjlnld\"},{\"name\":\"MonthlyPremiumV2StorageCost\",\"value\":9.84984,\"description\":\"iiaocqib\"},{\"name\":\"MonthlyAzureHybridCostSavings\",\"value\":62.204887,\"description\":\"ebiphryvcjwqwoq\"},{\"name\":\"MonthlyPremiumV2StorageCost\",\"value\":29.57796,\"description\":\"dhzybsp\"}],\"securitySuitability\":\"Unknown\",\"shouldProvisionReplicas\":true,\"skuReplicationMode\":\"ActiveGeoReplication\",\"migrationGuidelines\":[{\"guidelineId\":\"agvwukhs\",\"migrationGuidelineCategory\":\"Unknown\",\"migrationGuidelineContext\":[{},{},{}]},{\"guidelineId\":\"fmz\",\"migrationGuidelineCategory\":\"Unknown\",\"migrationGuidelineContext\":[{},{},{},{}]},{\"guidelineId\":\"hnijmriprlkdneyt\",\"migrationGuidelineCategory\":\"FailoverCluterInstanceGuideLine\",\"migrationGuidelineContext\":[{},{},{},{}]},{\"guidelineId\":\"v\",\"migrationGuidelineCategory\":\"General\",\"migrationGuidelineContext\":[{},{},{},{}]}],\"recommendationReasonings\":[{\"reasoningId\":\"ltw\",\"reasoningString\":\"lu\",\"reasoningCategory\":\"nbpvzlq\",\"contextParameters\":[{},{}]},{\"reasoningId\":\"y\",\"reasoningString\":\"jckhmocgj\",\"reasoningCategory\":\"gouarhwvixqq\",\"contextParameters\":[{}]},{\"reasoningId\":\"kybsj\",\"reasoningString\":\"lrvtz\",\"reasoningCategory\":\"rbctbhpjhxpcvrd\",\"contextParameters\":[{},{},{},{}]}],\"migrationTargetPlatform\":\"Unknown\",\"suitability\":\"Suitable\",\"migrationIssues\":[{\"issueId\":\"dynzjahwr\",\"issueCategory\":\"Issue\",\"impactedObjects\":[{},{},{}]}]},\"azureSqlVMSuitabilityDetails\":{\"azureSqlSku\":{\"virtualMachineSize\":{\"azureVmFamily\":\"Fs_series\",\"cores\":1279251745,\"azureSkuName\":\"Standard_E2s_v4\",\"availableCores\":111361676,\"maxNetworkInterfaces\":1303757705},\"dataDiskSizes\":[{},{}],\"logDiskSizes\":[{},{},{},{}],\"azureSqlTargetType\":\"Unknown\"},\"replicaAzureSqlSku\":[{\"virtualMachineSize\":{},\"dataDiskSizes\":[{}],\"logDiskSizes\":[{},{},{},{}],\"azureSqlTargetType\":\"AzureVirtualMachine\"},{\"virtualMachineSize\":{},\"dataDiskSizes\":[{},{},{}],\"logDiskSizes\":[{},{}],\"azureSqlTargetType\":\"AzureSqlVirtualMachine\"},{\"virtualMachineSize\":{},\"dataDiskSizes\":[{}],\"logDiskSizes\":[{},{}],\"azureSqlTargetType\":\"AzureSqlDatabase\"},{\"virtualMachineSize\":{},\"dataDiskSizes\":[{}],\"logDiskSizes\":[{}],\"azureSqlTargetType\":\"AzureSqlVirtualMachine\"}],\"sharedResources\":{\"sharedDataDisks\":[{},{}],\"sharedLogDisks\":[{},{},{}],\"sharedTempDbDisks\":[{},{}],\"numberOfMounts\":251648854,\"quorumWitness\":{\"quorumWitnessType\":\"Cloud\"}},\"monthlyComputeCost\":82.192,\"monthlyStorageCost\":92.815796,\"costComponents\":[{\"name\":\"MonthlySecurityCost\",\"value\":69.84208,\"description\":\"cko\"},{\"name\":\"MonthlyPremiumV2StorageCost\",\"value\":27.702517,\"description\":\"spftesubzpv\"},{\"name\":\"MonthlySecurityCost\",\"value\":16.102236,\"description\":\"tcovqseusrfjb\"}],\"securitySuitability\":\"NotSuitable\",\"shouldProvisionReplicas\":true,\"skuReplicationMode\":\"NotApplicable\",\"migrationGuidelines\":[{\"guidelineId\":\"muoswkjmdih\",\"migrationGuidelineCategory\":\"FailoverCluterInstanceGuideLine\",\"migrationGuidelineContext\":[{},{},{},{}]},{\"guidelineId\":\"lwhbwzjnu\",\"migrationGuidelineCategory\":\"AvailabilityGroupGuideline\",\"migrationGuidelineContext\":[{}]}],\"recommendationReasonings\":[{\"reasoningId\":\"gnnbzrtf\",\"reasoningString\":\"dzuubjtvgjsxm\",\"reasoningCategory\":\"jjvavdpww\",\"contextParameters\":[{}]}],\"migrationTargetPlatform\":\"AzureVirtualMachine\",\"suitability\":\"ConditionallySuitable\",\"migrationIssues\":[{\"issueId\":\"ffofwan\",\"issueCategory\":\"Issue\",\"impactedObjects\":[{},{},{},{}]},{\"issueId\":\"uwazcgwdfriwg\",\"issueCategory\":\"Internal\",\"impactedObjects\":[{},{},{}]}]},\"storageTypeBasedDetails\":[{\"storageType\":\"scvgl\",\"diskSizeInMB\":4.1600227,\"megabytesPerSecondOfRead\":40.736492,\"megabytesPerSecondOfWrite\":56.071045,\"numberOfReadOperationsPerSecond\":94.1541,\"numberOfWriteOperationsPerSecond\":81.04214}],\"productSupportStatus\":{\"currentVersion\":\"k\",\"servicePackStatus\":\"xprwpxs\",\"esuStatus\":\"hu\",\"supportStatus\":\"lcsklt\",\"eta\":964103530,\"currentEsuYear\":\"ggg\",\"mainstreamEndDate\":\"2021-01-18T11:27:05Z\",\"extendedSupportEndDate\":\"2021-03-14T03:41:27Z\",\"extendedSecurityUpdateYear1EndDate\":\"2021-05-28T15:32:03Z\",\"extendedSecurityUpdateYear2EndDate\":\"2021-03-27T21:52:24Z\",\"extendedSecurityUpdateYear3EndDate\":\"2021-08-12T22:14Z\"},\"fciMetadata\":{\"state\":\"Pending\",\"isMultiSubnet\":true,\"fciSharedDiskCount\":1216756136},\"availabilityReplicaSummary\":{\"numberOfSynchronousReadReplicas\":1106035745,\"numberOfSynchronousNonReadReplicas\":2114805426,\"numberOfAsynchronousReadReplicas\":1200969454,\"numberOfAsynchronousNonReadReplicas\":866635783,\"numberOfPrimaryReplicas\":1139207418},\"isClustered\":false,\"isHighAvailabilityEnabled\":true,\"recommendedTargetReasonings\":[{\"reasoningId\":\"fbodetresrgvts\",\"reasoningString\":\"vftwaiv\",\"reasoningCategory\":\"qkevzgj\",\"contextParameters\":[{}]},{\"reasoningId\":\"hxmpdxxz\",\"reasoningString\":\"wwzjwotnxlkfhglh\",\"reasoningCategory\":\"oxqwecrsnhpcse\",\"contextParameters\":[{},{},{},{}]},{\"reasoningId\":\"vppqi\",\"reasoningString\":\"kklvzrlrmlccmet\",\"reasoningCategory\":\"czivfqbqna\",\"contextParameters\":[{}]}],\"machineArmId\":\"enz\",\"machineName\":\"euscplhyv\",\"instanceName\":\"xlyzkxit\",\"sqlInstanceSdsArmId\":\"hezsvkolrupjovm\",\"sqlEdition\":\"sayebra\",\"sqlVersion\":\"zlpzbtzuyky\",\"numberOfCoresAllocated\":770520105,\"percentageCoresUtilization\":45.060116,\"logicalDisks\":[{\"diskId\":\"pfnocm\",\"diskSizeInMB\":68.22835,\"megabytesPerSecondOfRead\":7.444686,\"megabytesPerSecondOfWrite\":94.60865,\"numberOfReadOperationsPerSecond\":17.045683,\"numberOfWriteOperationsPerSecond\":98.33398},{\"diskId\":\"wyqejgaao\",\"diskSizeInMB\":94.436035,\"megabytesPerSecondOfRead\":71.84324,\"megabytesPerSecondOfWrite\":94.4489,\"numberOfReadOperationsPerSecond\":60.43468,\"numberOfWriteOperationsPerSecond\":92.890724}],\"databaseSummary\":{\"numberOfUserDatabases\":2076485508,\"totalDatabaseSizeInMB\":71.95924,\"largestDatabaseSizeInMB\":57.79177,\"totalDiscoveredUserDatabases\":2115508099},\"confidenceRatingInPercentage\":6.8730474,\"sizingCriterion\":\"AsOnPremises\",\"createdTimestamp\":\"2021-06-13T17:39:06Z\",\"updatedTimestamp\":\"2021-07-12T06:05:15Z\"},\"id\":\"cqvhoejgoiutgwrm\",\"name\":\"a\",\"type\":\"p\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response = manager.assessedSqlInstanceV2Operations() + .listBySqlAssessmentV2("fgjblcd", "myfc", "mftzgyy", "y", "lugekdfqnhtt", 500622504, "owrczfjjnnuxxr", + 1309033644, com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlMachineListResultTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlMachineListResultTests.java new file mode 100644 index 000000000000..d9957b7f9efa --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlMachineListResultTests.java @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlMachineInner; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlMachineListResult; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlMachineProperties; +import com.azure.resourcemanager.migration.assessment.models.CostComponent; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class AssessedSqlMachineListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AssessedSqlMachineListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"biosGuid\":\"fxeeebtijvacvbm\",\"fqdn\":\"bqqxlaj\",\"sqlInstances\":[{\"instanceId\":\"acevehjkuyx\",\"instanceName\":\"fgaoq\",\"sqlInstanceSdsArmId\":\"faey\",\"sqlInstanceEntityId\":\"nm\",\"sqlEdition\":\"vxirpghriypo\",\"sqlVersion\":\"yhlqhykprlpyznu\",\"isClustered\":true,\"isHighAvailabilityEnabled\":true,\"sqlFciState\":\"Unknown\"},{\"instanceId\":\"iitdfuxt\",\"instanceName\":\"siibmiybnnustgn\",\"sqlInstanceSdsArmId\":\"hnmgixhcm\",\"sqlInstanceEntityId\":\"mqfoudorh\",\"sqlEdition\":\"yyprotwyp\",\"sqlVersion\":\"d\",\"isClustered\":false,\"isHighAvailabilityEnabled\":true,\"sqlFciState\":\"NotApplicable\"},{\"instanceId\":\"jkavl\",\"instanceName\":\"rb\",\"sqlInstanceSdsArmId\":\"tp\",\"sqlInstanceEntityId\":\"tzfjltf\",\"sqlEdition\":\"zcyjtot\",\"sqlVersion\":\"opv\",\"isClustered\":true,\"isHighAvailabilityEnabled\":false,\"sqlFciState\":\"Passive\"}],\"suitabilityDetail\":\"RecommendedSizeHasLessNetworkAdapters\",\"suitabilityExplanation\":\"NoVmSizeForStandardPricingTier\",\"recommendedVmSize\":\"Standard_D4a_v4\",\"recommendedVmFamily\":\"Ev3_series\",\"productSupportStatus\":{\"currentVersion\":\"thmkyib\",\"servicePackStatus\":\"sihsgqcwdhohsd\",\"esuStatus\":\"cdzsu\",\"supportStatus\":\"ohdxbzlmcmu\",\"eta\":879403543,\"currentEsuYear\":\"hdbevwqqxeyskon\",\"mainstreamEndDate\":\"2021-02-12T17:13:55Z\",\"extendedSupportEndDate\":\"2021-07-17T19:35:55Z\",\"extendedSecurityUpdateYear1EndDate\":\"2021-04-21T10:40:59Z\",\"extendedSecurityUpdateYear2EndDate\":\"2021-05-07T03:06:31Z\",\"extendedSecurityUpdateYear3EndDate\":\"2021-05-29T05:06:31Z\"},\"recommendedVmSizeNumberOfCores\":579813186,\"recommendedVmSizeMegabytesOfMemory\":30.244493,\"monthlyComputeCost\":18.97896,\"disks\":{\"zmqpnodawopqhewj\":{\"suitability\":\"NotSuitable\",\"suitabilityExplanation\":\"Unknown\",\"suitabilityDetail\":\"DiskGigabytesProvisionedMissing\",\"recommendedDiskSize\":\"StandardSSD_E70\",\"recommendedDiskType\":\"StandardOrPremium\",\"recommendedDiskSizeGigabytes\":1858033886,\"recommendDiskThroughputInMbps\":33.499878,\"recommendedDiskIops\":39.537643,\"monthlyStorageCost\":90.73885,\"name\":\"ezrxcczurtleipqx\",\"displayName\":\"wvz\",\"gigabytesProvisioned\":17.816608,\"megabytesPerSecondOfRead\":60.011448,\"megabytesPerSecondOfWrite\":48.05835,\"numberOfReadOperationsPerSecond\":4.7126713,\"numberOfWriteOperationsPerSecond\":70.94812}},\"networkAdapters\":{\"lbkpb\":{\"suitability\":\"ConditionallySuitable\",\"suitabilityDetail\":\"MegabytesOfDataTransmittedOutOfRange\",\"suitabilityExplanation\":\"Unknown\",\"monthlyBandwidthCosts\":88.63707,\"netGigabytesTransmittedPerMonth\":16.294712,\"name\":\"dlat\",\"displayName\":\"mzlbiojlvfhrb\",\"macAddress\":\"neqvcwwyyurmo\",\"ipAddresses\":[\"prprsnmokay\"],\"megabytesPerSecondReceived\":95.21919,\"megabytesPerSecondTransmitted\":12.67882},\"apjwogqqnobpudcd\":{\"suitability\":\"NotSuitable\",\"suitabilityDetail\":\"None\",\"suitabilityExplanation\":\"NotApplicable\",\"monthlyBandwidthCosts\":1.7720342,\"netGigabytesTransmittedPerMonth\":9.317743,\"name\":\"echndbnwieholew\",\"displayName\":\"iuubwefqsf\",\"macAddress\":\"aqtferr\",\"ipAddresses\":[\"x\"],\"megabytesPerSecondReceived\":78.82658,\"megabytesPerSecondTransmitted\":16.184013},\"yfu\":{\"suitability\":\"Suitable\",\"suitabilityDetail\":\"None\",\"suitabilityExplanation\":\"NotApplicable\",\"monthlyBandwidthCosts\":46.80928,\"netGigabytesTransmittedPerMonth\":95.067,\"name\":\"asqbucljgkyex\",\"displayName\":\"guyaip\",\"macAddress\":\"sdaultxij\",\"ipAddresses\":[\"fqwazlnqnmcjn\",\"zqdqxt\"],\"megabytesPerSecondReceived\":84.08586,\"megabytesPerSecondTransmitted\":91.10522},\"bp\":{\"suitability\":\"Unknown\",\"suitabilityDetail\":\"MegabytesOfDataRecievedMissing\",\"suitabilityExplanation\":\"NotApplicable\",\"monthlyBandwidthCosts\":72.10318,\"netGigabytesTransmittedPerMonth\":51.849754,\"name\":\"jqg\",\"displayName\":\"fh\",\"macAddress\":\"rqryxynqn\",\"ipAddresses\":[\"p\",\"ovw\",\"zn\",\"tgoe\"],\"megabytesPerSecondReceived\":26.714617,\"megabytesPerSecondTransmitted\":46.57859}},\"monthlyBandwidthCost\":11.20854,\"monthlyStorageCost\":47.728634,\"costComponents\":[{\"name\":\"MonthlyAzureHybridCostSavings\",\"value\":94.41636,\"description\":\"rigjkskyrioov\"},{\"name\":\"MonthlyAzureHybridCostSavings\",\"value\":95.8368,\"description\":\"aabzmif\"},{\"name\":\"MonthlyPremiumV2StorageCost\",\"value\":73.946815,\"description\":\"maxriz\"},{\"name\":\"MonthlyAzureHybridCostSavings\",\"value\":86.51203,\"description\":\"pxl\"}],\"securitySuitability\":\"NotSuitable\",\"migrationGuidelines\":[{\"guidelineId\":\"xieixynllxec\",\"migrationGuidelineCategory\":\"AvailabilityGroupGuideline\",\"migrationGuidelineContext\":[{},{},{}]},{\"guidelineId\":\"hslhca\",\"migrationGuidelineCategory\":\"Unknown\",\"migrationGuidelineContext\":[{}]},{\"guidelineId\":\"dwfmvigorqjb\",\"migrationGuidelineCategory\":\"FailoverCluterInstanceGuideLine\",\"migrationGuidelineContext\":[{},{}]},{\"guidelineId\":\"glka\",\"migrationGuidelineCategory\":\"AvailabilityGroupGuideline\",\"migrationGuidelineContext\":[{},{},{},{}]}],\"bootType\":\"EFI\",\"operatingSystemType\":\"eickpz\",\"operatingSystemName\":\"p\",\"operatingSystemVersion\":\"mxelnwcltyjed\",\"operatingSystemArchitecture\":\"X64\",\"createdTimestamp\":\"2021-11-12T19:58:50Z\",\"updatedTimestamp\":\"2021-02-24T02:10:51Z\",\"displayName\":\"qscazuawxtz\",\"type\":\"AvsAssessedMachine\",\"description\":\"mwabzxrvxc\",\"datacenterMachineArmId\":\"hsphaivmxyas\",\"datacenterManagementServerArmId\":\"vgsgzwywakoihkn\",\"datacenterManagementServerName\":\"jblmljhlnymz\",\"megabytesOfMemory\":85.03406,\"numberOfCores\":494637597,\"confidenceRatingInPercentage\":40.960278,\"percentageCoresUtilization\":18.226921,\"percentageMemoryUtilization\":81.135086,\"suitability\":\"ReadinessUnknown\",\"sizingCriterion\":\"PerformanceBased\"},\"id\":\"vwf\",\"name\":\"tayx\",\"type\":\"nsup\"},{\"properties\":{\"biosGuid\":\"lzqnhcvs\",\"fqdn\":\"tnzoibgsxgnxfy\",\"sqlInstances\":[{\"instanceId\":\"p\",\"instanceName\":\"xwdofdb\",\"sqlInstanceSdsArmId\":\"qxeiiqbimhtmwwi\",\"sqlInstanceEntityId\":\"ehfqpofvwbc\",\"sqlEdition\":\"embnkbw\",\"sqlVersion\":\"vxkdivqihebwtswb\",\"isClustered\":true,\"isHighAvailabilityEnabled\":false,\"sqlFciState\":\"Active\"},{\"instanceId\":\"agegiz\",\"instanceName\":\"jfelisdjubggbqig\",\"sqlInstanceSdsArmId\":\"kbsazgak\",\"sqlInstanceEntityId\":\"cyrcmjdmspo\",\"sqlEdition\":\"pv\",\"sqlVersion\":\"rylniofrzg\",\"isClustered\":false,\"isHighAvailabilityEnabled\":false,\"sqlFciState\":\"Unknown\"},{\"instanceId\":\"kvnlvxbcuiiznkt\",\"instanceName\":\"ansnvp\",\"sqlInstanceSdsArmId\":\"bmikost\",\"sqlInstanceEntityId\":\"bkiw\",\"sqlEdition\":\"qnyophzfyls\",\"sqlVersion\":\"rpfbcunezz\",\"isClustered\":true,\"isHighAvailabilityEnabled\":true,\"sqlFciState\":\"Unknown\"}],\"suitabilityDetail\":\"CannotReportStorageCost\",\"suitabilityExplanation\":\"NoVmSizeForBasicPricingTier\",\"recommendedVmSize\":\"Standard_M416s_v2\",\"recommendedVmFamily\":\"F_series\",\"productSupportStatus\":{\"currentVersion\":\"npsihclaf\",\"servicePackStatus\":\"aylp\",\"esuStatus\":\"sqqw\",\"supportStatus\":\"cmwqkchcxwa\",\"eta\":307394034,\"currentEsuYear\":\"zjkjexfdeqv\",\"mainstreamEndDate\":\"2021-10-11T15:41:07Z\",\"extendedSupportEndDate\":\"2020-12-20T15:35:44Z\",\"extendedSecurityUpdateYear1EndDate\":\"2021-09-09T16:59:46Z\",\"extendedSecurityUpdateYear2EndDate\":\"2021-10-24T00:31:56Z\",\"extendedSecurityUpdateYear3EndDate\":\"2021-05-08T15:06:42Z\"},\"recommendedVmSizeNumberOfCores\":127913719,\"recommendedVmSizeMegabytesOfMemory\":71.40286,\"monthlyComputeCost\":36.90302,\"disks\":{\"zjgehkfkim\":{\"suitability\":\"ReadinessUnknown\",\"suitabilityExplanation\":\"NoSuitableDiskSizeForThroughput\",\"suitabilityDetail\":\"MegabytesPerSecondOfReadOutOfRange\",\"recommendedDiskSize\":\"Premium_P20\",\"recommendedDiskType\":\"StandardOrPremium\",\"recommendedDiskSizeGigabytes\":1849178398,\"recommendDiskThroughputInMbps\":19.441557,\"recommendedDiskIops\":45.75102,\"monthlyStorageCost\":37.261547,\"name\":\"gaao\",\"displayName\":\"ttaqutdew\",\"gigabytesProvisioned\":33.730103,\"megabytesPerSecondOfRead\":51.00159,\"megabytesPerSecondOfWrite\":69.260704,\"numberOfReadOperationsPerSecond\":53.282524,\"numberOfWriteOperationsPerSecond\":60.865467},\"o\":{\"suitability\":\"Suitable\",\"suitabilityExplanation\":\"NoEaPriceFoundForDiskSize\",\"suitabilityDetail\":\"MegabytesPerSecondOfWriteOutOfRange\",\"recommendedDiskSize\":\"Standard_S4\",\"recommendedDiskType\":\"Standard\",\"recommendedDiskSizeGigabytes\":1426347910,\"recommendDiskThroughputInMbps\":67.66341,\"recommendedDiskIops\":65.54477,\"monthlyStorageCost\":68.6272,\"name\":\"ixmonstshiyxg\",\"displayName\":\"lfcldu\",\"gigabytesProvisioned\":92.06999,\"megabytesPerSecondOfRead\":15.541893,\"megabytesPerSecondOfWrite\":18.709505,\"numberOfReadOperationsPerSecond\":17.68028,\"numberOfWriteOperationsPerSecond\":95.38093},\"bsmswziqgf\":{\"suitability\":\"ConditionallySuitable\",\"suitabilityExplanation\":\"DiskSizeGreaterThanSupported\",\"suitabilityDetail\":\"DiskGigabytesProvisionedMissing\",\"recommendedDiskSize\":\"StandardSSD_E10\",\"recommendedDiskType\":\"Ultra\",\"recommendedDiskSizeGigabytes\":1117030946,\"recommendDiskThroughputInMbps\":80.3862,\"recommendedDiskIops\":94.08675,\"monthlyStorageCost\":83.48194,\"name\":\"gshejjtbxqmulux\",\"displayName\":\"qzvnersbycucr\",\"gigabytesProvisioned\":73.3862,\"megabytesPerSecondOfRead\":31.644154,\"megabytesPerSecondOfWrite\":9.675158,\"numberOfReadOperationsPerSecond\":59.315407,\"numberOfWriteOperationsPerSecond\":30.78078}},\"networkAdapters\":{\"wvefloccsrmoz\":{\"suitability\":\"ConditionallySuitable\",\"suitabilityDetail\":\"MegabytesOfDataTransmittedOutOfRange\",\"suitabilityExplanation\":\"Unknown\",\"monthlyBandwidthCosts\":57.039474,\"netGigabytesTransmittedPerMonth\":79.71306,\"name\":\"znvfbycjsxjww\",\"displayName\":\"z\",\"macAddress\":\"mwmxqhndvnoamld\",\"ipAddresses\":[\"aohdjh\",\"flzokxco\",\"pelnjetag\",\"tsxoatftgz\"],\"megabytesPerSecondReceived\":83.193085,\"megabytesPerSecondTransmitted\":86.567474},\"znth\":{\"suitability\":\"NotSuitable\",\"suitabilityDetail\":\"None\",\"suitabilityExplanation\":\"Unknown\",\"monthlyBandwidthCosts\":14.893383,\"netGigabytesTransmittedPerMonth\":7.6503515,\"name\":\"ky\",\"displayName\":\"xcjxgrytfmpcy\",\"macAddress\":\"lrmcaykg\",\"ipAddresses\":[\"xu\",\"t\",\"ksxwpnd\"],\"megabytesPerSecondReceived\":71.74752,\"megabytesPerSecondTransmitted\":49.58568}},\"monthlyBandwidthCost\":33.53333,\"monthlyStorageCost\":55.912632,\"costComponents\":[{\"name\":\"MonthlyAzureHybridCostSavings\",\"value\":84.35982,\"description\":\"voamktcqiosmg\"},{\"name\":\"Unknown\",\"value\":18.612463,\"description\":\"qdlyrtl\"},{\"name\":\"Unknown\",\"value\":69.58039,\"description\":\"tz\"}],\"securitySuitability\":\"Unknown\",\"migrationGuidelines\":[{\"guidelineId\":\"mznnbsoqeqalarvl\",\"migrationGuidelineCategory\":\"Unknown\",\"migrationGuidelineContext\":[{},{}]}],\"bootType\":\"EFI\",\"operatingSystemType\":\"ebwlnbmhyreeudzq\",\"operatingSystemName\":\"bpdqmjxlyy\",\"operatingSystemVersion\":\"lgouwtlmjj\",\"operatingSystemArchitecture\":\"X64\",\"createdTimestamp\":\"2021-10-10T19:20:29Z\",\"updatedTimestamp\":\"2021-02-11T22:31:47Z\",\"displayName\":\"axkjeytunlbfjk\",\"type\":\"Unknown\",\"description\":\"nkqbhsyrq\",\"datacenterMachineArmId\":\"jqhden\",\"datacenterManagementServerArmId\":\"ulkpakd\",\"datacenterManagementServerName\":\"fmjnnawtqa\",\"megabytesOfMemory\":82.25649,\"numberOfCores\":1193273500,\"confidenceRatingInPercentage\":5.6159616,\"percentageCoresUtilization\":83.88325,\"percentageMemoryUtilization\":64.996155,\"suitability\":\"NotSuitable\",\"sizingCriterion\":\"PerformanceBased\"},\"id\":\"dhlisngwflqqmpi\",\"name\":\"ruwnpqxpx\",\"type\":\"wfcngjsaas\"}],\"nextLink\":\"xtmkzjvkviir\"}") + .toObject(AssessedSqlMachineListResult.class); + Assertions.assertEquals(94.41636F, model.value().get(0).properties().costComponents().get(0).value()); + Assertions.assertEquals("rigjkskyrioov", + model.value().get(0).properties().costComponents().get(0).description()); + Assertions.assertEquals("xtmkzjvkviir", model.nextLink()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AssessedSqlMachineListResult model + = new AssessedSqlMachineListResult() + .withValue(Arrays.asList( + new AssessedSqlMachineInner().withProperties(new AssessedSqlMachineProperties().withCostComponents( + Arrays.asList(new CostComponent().withValue(94.41636F).withDescription("rigjkskyrioov"), + new CostComponent().withValue(95.8368F).withDescription("aabzmif"), + new CostComponent().withValue(73.946815F).withDescription("maxriz"), + new CostComponent().withValue(86.51203F).withDescription("pxl")))), + new AssessedSqlMachineInner().withProperties(new AssessedSqlMachineProperties().withCostComponents( + Arrays.asList(new CostComponent().withValue(84.35982F).withDescription("voamktcqiosmg"), + new CostComponent().withValue(18.612463F).withDescription("qdlyrtl"), + new CostComponent().withValue(69.58039F).withDescription("tz")))))) + .withNextLink("xtmkzjvkviir"); + model = BinaryData.fromObject(model).toObject(AssessedSqlMachineListResult.class); + Assertions.assertEquals(94.41636F, model.value().get(0).properties().costComponents().get(0).value()); + Assertions.assertEquals("rigjkskyrioov", + model.value().get(0).properties().costComponents().get(0).description()); + Assertions.assertEquals("xtmkzjvkviir", model.nextLink()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlMachinesOperationsGetWithResponseMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlMachinesOperationsGetWithResponseMockTests.java new file mode 100644 index 000000000000..bbdfed93f089 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlMachinesOperationsGetWithResponseMockTests.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.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlMachine; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class AssessedSqlMachinesOperationsGetWithResponseMockTests { + @Test + public void testGetWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"biosGuid\":\"impkjblorns\",\"fqdn\":\"qhudsmusuaawj\",\"sqlInstances\":[{\"instanceId\":\"jnfczmnniixy\",\"instanceName\":\"qban\",\"sqlInstanceSdsArmId\":\"jtgirnb\",\"sqlInstanceEntityId\":\"gm\",\"sqlEdition\":\"orgmynltwmpftm\",\"sqlVersion\":\"e\",\"isClustered\":false,\"isHighAvailabilityEnabled\":true,\"sqlFciState\":\"Unknown\"},{\"instanceId\":\"etamfddrvlkpzwb\",\"instanceName\":\"recchdidrmu\",\"sqlInstanceSdsArmId\":\"ahmjedbiu\",\"sqlInstanceEntityId\":\"khhwmj\",\"sqlEdition\":\"bweunxc\",\"sqlVersion\":\"rihufoihppiybxv\",\"isClustered\":true,\"isHighAvailabilityEnabled\":false,\"sqlFciState\":\"Unknown\"}],\"suitabilityDetail\":\"CannotReportBandwidthCosts\",\"suitabilityExplanation\":\"WindowsServerVersionConditionallySupported\",\"recommendedVmSize\":\"Standard_M8_4ms\",\"recommendedVmFamily\":\"Ddsv5_series\",\"productSupportStatus\":{\"currentVersion\":\"vkunhdim\",\"servicePackStatus\":\"ktirzka\",\"esuStatus\":\"pucdocf\",\"supportStatus\":\"lwgofm\",\"eta\":1996838839,\"currentEsuYear\":\"jlvzklk\",\"mainstreamEndDate\":\"2021-05-28T13:53:53Z\",\"extendedSupportEndDate\":\"2021-01-21T09:29:50Z\",\"extendedSecurityUpdateYear1EndDate\":\"2021-09-07T03:18:30Z\",\"extendedSecurityUpdateYear2EndDate\":\"2021-08-04T05:52:07Z\",\"extendedSecurityUpdateYear3EndDate\":\"2021-04-25T02:02Z\"},\"recommendedVmSizeNumberOfCores\":1054083047,\"recommendedVmSizeMegabytesOfMemory\":21.55339,\"monthlyComputeCost\":51.470005,\"disks\":{\"raxq\":{\"suitability\":\"ReadinessUnknown\",\"suitabilityExplanation\":\"DiskSizeGreaterThanSupported\",\"suitabilityDetail\":\"DiskGigabytesProvisionedMissing\",\"recommendedDiskSize\":\"Ultra\",\"recommendedDiskType\":\"Ultra\",\"recommendedDiskSizeGigabytes\":425882032,\"recommendDiskThroughputInMbps\":39.469727,\"recommendedDiskIops\":74.69294,\"monthlyStorageCost\":63.4106,\"name\":\"cdiykkc\",\"displayName\":\"nujvqynvavi\",\"gigabytesProvisioned\":44.86011,\"megabytesPerSecondOfRead\":33.159374,\"megabytesPerSecondOfWrite\":66.49689,\"numberOfReadOperationsPerSecond\":82.77711,\"numberOfWriteOperationsPerSecond\":79.22218}},\"networkAdapters\":{\"stsinvag\":{\"suitability\":\"NotSuitable\",\"suitabilityDetail\":\"None\",\"suitabilityExplanation\":\"NotApplicable\",\"monthlyBandwidthCosts\":87.74508,\"netGigabytesTransmittedPerMonth\":22.928202,\"name\":\"pv\",\"displayName\":\"dbwen\",\"macAddress\":\"nafhxrzfr\",\"ipAddresses\":[\"tiucwv\",\"qllukhkrcqxg\",\"bvzarmq\"],\"megabytesPerSecondReceived\":11.978602,\"megabytesPerSecondTransmitted\":17.930443},\"kheubanlx\":{\"suitability\":\"ConditionallySuitable\",\"suitabilityDetail\":\"MegabytesOfDataRecievedOutOfRange\",\"suitabilityExplanation\":\"Unknown\",\"monthlyBandwidthCosts\":35.926144,\"netGigabytesTransmittedPerMonth\":37.834274,\"name\":\"cehqw\",\"displayName\":\"txnmxgnmguz\",\"macAddress\":\"wvor\",\"ipAddresses\":[\"kjnbkbdhlltqstq\",\"qsygxiynec\"],\"megabytesPerSecondReceived\":12.935913,\"megabytesPerSecondTransmitted\":99.16029},\"e\":{\"suitability\":\"ReadinessUnknown\",\"suitabilityDetail\":\"MegabytesOfDataTransmittedMissing\",\"suitabilityExplanation\":\"NotApplicable\",\"monthlyBandwidthCosts\":86.49183,\"netGigabytesTransmittedPerMonth\":50.56507,\"name\":\"lzklaslgacizux\",\"displayName\":\"arwp\",\"macAddress\":\"saudoejtighsx\",\"ipAddresses\":[\"tnkqbala\",\"ovu\"],\"megabytesPerSecondReceived\":85.89372,\"megabytesPerSecondTransmitted\":68.44179}},\"monthlyBandwidthCost\":58.254917,\"monthlyStorageCost\":35.27037,\"costComponents\":[{\"name\":\"MonthlyAzureHybridCostSavings\",\"value\":99.090454,\"description\":\"bcngkegxc\"}],\"securitySuitability\":\"NotSuitable\",\"migrationGuidelines\":[{\"guidelineId\":\"etwilyrzoxpd\",\"migrationGuidelineCategory\":\"Unknown\",\"migrationGuidelineContext\":[{}]},{\"guidelineId\":\"lqownkiua\",\"migrationGuidelineCategory\":\"Unknown\",\"migrationGuidelineContext\":[{},{}]}],\"bootType\":\"Unknown\",\"operatingSystemType\":\"xjjmztnlmsoodtm\",\"operatingSystemName\":\"cdhdyswcrpt\",\"operatingSystemVersion\":\"ajczxvl\",\"operatingSystemArchitecture\":\"Unknown\",\"createdTimestamp\":\"2021-02-10T22:21:42Z\",\"updatedTimestamp\":\"2021-05-07T20:09:53Z\",\"displayName\":\"zrpywlptyuqh\",\"type\":\"Unknown\",\"description\":\"skykpfuofix\",\"datacenterMachineArmId\":\"pcfykkpy\",\"datacenterManagementServerArmId\":\"pawmpjprdp\",\"datacenterManagementServerName\":\"pcfpcfj\",\"megabytesOfMemory\":75.83426,\"numberOfCores\":1335357423,\"confidenceRatingInPercentage\":28.798502,\"percentageCoresUtilization\":32.203842,\"percentageMemoryUtilization\":15.144819,\"suitability\":\"ReadinessUnknown\",\"sizingCriterion\":\"AsOnPremises\"},\"id\":\"mnnidmdia\",\"name\":\"pzxkzrntmkct\",\"type\":\"huosgwqpsqaz\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + AssessedSqlMachine response = manager.assessedSqlMachinesOperations() + .getWithResponse("njhx", "h", "hmgpczqulpt", "bvcpxtzhi", "q", com.azure.core.util.Context.NONE) + .getValue(); + + Assertions.assertEquals(99.090454F, response.properties().costComponents().get(0).value()); + Assertions.assertEquals("bcngkegxc", response.properties().costComponents().get(0).description()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlMachinesOperationsListBySqlAssessmentV2MockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlMachinesOperationsListBySqlAssessmentV2MockTests.java new file mode 100644 index 000000000000..17f614552585 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlMachinesOperationsListBySqlAssessmentV2MockTests.java @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlMachine; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class AssessedSqlMachinesOperationsListBySqlAssessmentV2MockTests { + @Test + public void testListBySqlAssessmentV2() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"biosGuid\":\"yotnplfacqo\",\"fqdn\":\"qrqxwetjt\",\"sqlInstances\":[{\"instanceId\":\"tfdoadtx\",\"instanceName\":\"ge\",\"sqlInstanceSdsArmId\":\"adkm\",\"sqlInstanceEntityId\":\"gssz\",\"sqlEdition\":\"ctkbbxuha\",\"sqlVersion\":\"sirncclabvoy\",\"isClustered\":false,\"isHighAvailabilityEnabled\":false,\"sqlFciState\":\"Active\"},{\"instanceId\":\"bmyqjog\",\"instanceName\":\"saidjan\",\"sqlInstanceSdsArmId\":\"movdxxurn\",\"sqlInstanceEntityId\":\"jmoilunwe\",\"sqlEdition\":\"deel\",\"sqlVersion\":\"lkyozdsfzj\",\"isClustered\":false,\"isHighAvailabilityEnabled\":false,\"sqlFciState\":\"Passive\"},{\"instanceId\":\"slejtvxj\",\"instanceName\":\"vgjbfio\",\"sqlInstanceSdsArmId\":\"njodfcbjqqwmtq\",\"sqlInstanceEntityId\":\"oxsazuxejgwe\",\"sqlEdition\":\"wnf\",\"sqlVersion\":\"zzaczsinqbdn\",\"isClustered\":false,\"isHighAvailabilityEnabled\":false,\"sqlFciState\":\"Passive\"},{\"instanceId\":\"vrmkjmyitrchwu\",\"instanceName\":\"xeeihtpmno\",\"sqlInstanceSdsArmId\":\"hqlfmsib\",\"sqlInstanceEntityId\":\"yrfgxkyd\",\"sqlEdition\":\"yp\",\"sqlVersion\":\"qvmtywhlakx\",\"isClustered\":true,\"isHighAvailabilityEnabled\":false,\"sqlFciState\":\"Passive\"}],\"suitabilityDetail\":\"CannotReportBandwidthCosts\",\"suitabilityExplanation\":\"InternalErrorOccurredDuringNetworkEvaluation\",\"recommendedVmSize\":\"Standard_E20_v5\",\"recommendedVmFamily\":\"GS_series\",\"productSupportStatus\":{\"currentVersion\":\"rzgeuqxbpiatw\",\"servicePackStatus\":\"ujegqdtadra\",\"esuStatus\":\"ddhjkr\",\"supportStatus\":\"izyh\",\"eta\":562700229,\"currentEsuYear\":\"nqskt\",\"mainstreamEndDate\":\"2021-08-10T15:27:16Z\",\"extendedSupportEndDate\":\"2021-09-08T02:54:35Z\",\"extendedSecurityUpdateYear1EndDate\":\"2021-04-24T12:20:45Z\",\"extendedSecurityUpdateYear2EndDate\":\"2021-09-18T07:56:18Z\",\"extendedSecurityUpdateYear3EndDate\":\"2021-05-03T05:55:58Z\"},\"recommendedVmSizeNumberOfCores\":1205167221,\"recommendedVmSizeMegabytesOfMemory\":15.604812,\"monthlyComputeCost\":40.004826,\"disks\":{\"uvbdujgcwxvec\":{\"suitability\":\"NotSuitable\",\"suitabilityExplanation\":\"NoDiskSizeFoundInSelectedLocation\",\"suitabilityDetail\":\"DiskGigabytesProvisionedOutOfRange\",\"recommendedDiskSize\":\"StandardSSD_E3\",\"recommendedDiskType\":\"Unknown\",\"recommendedDiskSizeGigabytes\":2134981177,\"recommendDiskThroughputInMbps\":19.407808,\"recommendedDiskIops\":75.00775,\"monthlyStorageCost\":97.72125,\"name\":\"klciichgjsysm\",\"displayName\":\"o\",\"gigabytesProvisioned\":99.37963,\"megabytesPerSecondOfRead\":1.3408244,\"megabytesPerSecondOfWrite\":87.72186,\"numberOfReadOperationsPerSecond\":17.827404,\"numberOfWriteOperationsPerSecond\":83.63925}},\"networkAdapters\":{\"wuntobuiz\":{\"suitability\":\"Suitable\",\"suitabilityDetail\":\"MegabytesOfDataRecievedOutOfRange\",\"suitabilityExplanation\":\"Unknown\",\"monthlyBandwidthCosts\":85.95127,\"netGigabytesTransmittedPerMonth\":72.71101,\"name\":\"bgiark\",\"displayName\":\"kpgdqxwabzrwiq\",\"macAddress\":\"ha\",\"ipAddresses\":[\"dosqkptjqg\",\"ifmmainwh\",\"d\"],\"megabytesPerSecondReceived\":56.87188,\"megabytesPerSecondTransmitted\":41.46951},\"ikyypz\":{\"suitability\":\"ConditionallySuitable\",\"suitabilityDetail\":\"MegabytesOfDataRecievedOutOfRange\",\"suitabilityExplanation\":\"InternalErrorOccurred\",\"monthlyBandwidthCosts\":63.58878,\"netGigabytesTransmittedPerMonth\":38.958977,\"name\":\"f\",\"displayName\":\"klblaxp\",\"macAddress\":\"jwdabalfd\",\"ipAddresses\":[\"lz\",\"ytlbtlqhopxouvm\"],\"megabytesPerSecondReceived\":82.69837,\"megabytesPerSecondTransmitted\":98.499886},\"cq\":{\"suitability\":\"ConditionallySuitable\",\"suitabilityDetail\":\"MegabytesOfDataTransmittedOutOfRange\",\"suitabilityExplanation\":\"Unknown\",\"monthlyBandwidthCosts\":87.71719,\"netGigabytesTransmittedPerMonth\":74.619354,\"name\":\"bpoks\",\"displayName\":\"nm\",\"macAddress\":\"gpterdiu\",\"ipAddresses\":[\"rkskwztsdetjy\"],\"megabytesPerSecondReceived\":86.00711,\"megabytesPerSecondTransmitted\":35.51214}},\"monthlyBandwidthCost\":86.84527,\"monthlyStorageCost\":12.033564,\"costComponents\":[{\"name\":\"MonthlyPremiumV2StorageCost\",\"value\":37.48664,\"description\":\"ybz\"},{\"name\":\"Unknown\",\"value\":55.582367,\"description\":\"ptvdxxheigm\"}],\"securitySuitability\":\"Unknown\",\"migrationGuidelines\":[{\"guidelineId\":\"hjhjvm\",\"migrationGuidelineCategory\":\"FailoverCluterInstanceGuideLine\",\"migrationGuidelineContext\":[{},{}]}],\"bootType\":\"Unknown\",\"operatingSystemType\":\"b\",\"operatingSystemName\":\"d\",\"operatingSystemVersion\":\"bgymqt\",\"operatingSystemArchitecture\":\"X64\",\"createdTimestamp\":\"2021-11-09T12:10:09Z\",\"updatedTimestamp\":\"2021-08-04T15:49:36Z\",\"displayName\":\"rjnbsconxavipne\",\"type\":\"SqlAssessedMachine\",\"description\":\"jizqfsg\",\"datacenterMachineArmId\":\"dxze\",\"datacenterManagementServerArmId\":\"q\",\"datacenterManagementServerName\":\"fb\",\"megabytesOfMemory\":12.2989235,\"numberOfCores\":206526961,\"confidenceRatingInPercentage\":41.858093,\"percentageCoresUtilization\":84.57474,\"percentageMemoryUtilization\":48.314285,\"suitability\":\"Unknown\",\"sizingCriterion\":\"PerformanceBased\"},\"id\":\"ypi\",\"name\":\"dbkp\",\"type\":\"jtaqhsmqazpdg\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response = manager.assessedSqlMachinesOperations() + .listBySqlAssessmentV2("wxqouoxudnmc", "aprhknqiijgencdg", "oqueqihkkyowltj", "uwhldxwhieproqks", + "fxmcvprstvk", 1258845736, "b", 540536815, com.azure.core.util.Context.NONE); + + Assertions.assertEquals(37.48664F, response.iterator().next().properties().costComponents().get(0).value()); + Assertions.assertEquals("ybz", response.iterator().next().properties().costComponents().get(0).description()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlRecommendedEntityInnerTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlRecommendedEntityInnerTests.java new file mode 100644 index 000000000000..1fafa7b1e58a --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlRecommendedEntityInnerTests.java @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlRecommendedEntityInner; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlRecommendedEntityProperties; +import org.junit.jupiter.api.Assertions; + +public final class AssessedSqlRecommendedEntityInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AssessedSqlRecommendedEntityInner model = BinaryData.fromString( + "{\"properties\":{\"machineName\":\"xv\",\"instanceName\":\"asbcrymodizrx\",\"productSupportStatus\":{\"currentVersion\":\"bdxnaz\",\"servicePackStatus\":\"kml\",\"esuStatus\":\"evfxzopjhbzxlioh\",\"supportStatus\":\"dd\",\"eta\":255752990,\"currentEsuYear\":\"qbawpcbbnzqcykn\",\"mainstreamEndDate\":\"2021-11-02T01:12:01Z\",\"extendedSupportEndDate\":\"2021-03-06T20:54:18Z\",\"extendedSecurityUpdateYear1EndDate\":\"2021-07-22T15:12:48Z\",\"extendedSecurityUpdateYear2EndDate\":\"2021-04-01T15:17:48Z\",\"extendedSecurityUpdateYear3EndDate\":\"2021-01-01T11:04:25Z\"},\"dbCount\":513283107,\"discoveredDBCount\":902972363,\"hasScanOccurred\":false,\"recommendedAzureSqlTargetType\":\"Unknown\",\"recommendedSuitability\":\"SuitableForVM\",\"azureSqlMISuitabilityDetails\":{\"azureSqlSku\":{\"azureSqlServiceTier\":\"GeneralPurpose\",\"azureSqlComputeTier\":\"Automatic\",\"azureSqlHardwareGeneration\":\"Automatic\",\"storageMaxSizeInMB\":84.29777,\"predictedDataSizeInMB\":99.771095,\"predictedLogSizeInMB\":68.32871,\"cores\":150860449,\"azureSqlTargetType\":\"Recommended\"},\"replicaAzureSqlSku\":[{\"azureSqlServiceTier\":\"Unknown\",\"azureSqlComputeTier\":\"Automatic\",\"azureSqlHardwareGeneration\":\"Fsv2_series\",\"storageMaxSizeInMB\":79.18247,\"predictedDataSizeInMB\":46.459866,\"predictedLogSizeInMB\":10.004192,\"cores\":1601507048,\"azureSqlTargetType\":\"AzureSqlDatabase\"}],\"sharedResources\":{\"sharedDataDisks\":[{\"diskType\":\"PremiumV2\",\"diskSize\":\"Premium_P4\",\"diskRedundancy\":\"ZRS\",\"storageCost\":48.45098,\"recommendedSizeInGib\":62.555546,\"recommendedThroughputInMbps\":60.62409,\"recommendedIops\":86.50556},{\"diskType\":\"StandardSSD\",\"diskSize\":\"StandardSSD_E70\",\"diskRedundancy\":\"ZRS\",\"storageCost\":45.55057,\"recommendedSizeInGib\":98.22722,\"recommendedThroughputInMbps\":21.468824,\"recommendedIops\":37.586384},{\"diskType\":\"Ultra\",\"diskSize\":\"StandardSSD_E15\",\"diskRedundancy\":\"ZRS\",\"storageCost\":29.759396,\"recommendedSizeInGib\":61.058266,\"recommendedThroughputInMbps\":50.74714,\"recommendedIops\":78.82254}],\"sharedLogDisks\":[{\"diskType\":\"Standard\",\"diskSize\":\"StandardSSD_E50\",\"diskRedundancy\":\"ZRS\",\"storageCost\":24.992699,\"recommendedSizeInGib\":72.44504,\"recommendedThroughputInMbps\":45.95412,\"recommendedIops\":33.126175},{\"diskType\":\"Standard\",\"diskSize\":\"Premium_P50\",\"diskRedundancy\":\"LRS\",\"storageCost\":92.74943,\"recommendedSizeInGib\":71.27231,\"recommendedThroughputInMbps\":78.67329,\"recommendedIops\":77.75007},{\"diskType\":\"StandardOrPremium\",\"diskSize\":\"Standard_S40\",\"diskRedundancy\":\"LRS\",\"storageCost\":31.623632,\"recommendedSizeInGib\":57.0972,\"recommendedThroughputInMbps\":85.50122,\"recommendedIops\":29.51042},{\"diskType\":\"Standard\",\"diskSize\":\"Premium_P6\",\"diskRedundancy\":\"Unknown\",\"storageCost\":70.73475,\"recommendedSizeInGib\":24.424625,\"recommendedThroughputInMbps\":32.324684,\"recommendedIops\":41.786087}],\"sharedTempDbDisks\":[{\"diskType\":\"Standard\",\"diskSize\":\"Unknown\",\"diskRedundancy\":\"Unknown\",\"storageCost\":98.77709,\"recommendedSizeInGib\":75.847404,\"recommendedThroughputInMbps\":1.5102804,\"recommendedIops\":60.186977}],\"numberOfMounts\":1831822639,\"quorumWitness\":{\"quorumWitnessType\":\"Unknown\"}},\"monthlyComputeCost\":93.88989,\"monthlyStorageCost\":19.872547,\"costComponents\":[{\"name\":\"MonthlySecurityCost\",\"value\":27.317005,\"description\":\"bh\"},{\"name\":\"MonthlyAzureHybridCostSavings\",\"value\":76.805244,\"description\":\"qi\"},{\"name\":\"MonthlySecurityCost\",\"value\":97.28748,\"description\":\"udfbsfarf\"}],\"securitySuitability\":\"Unknown\",\"shouldProvisionReplicas\":true,\"skuReplicationMode\":\"FailoverGroupInstance\",\"migrationGuidelines\":[{\"guidelineId\":\"pvwgfstmhqykizmd\",\"migrationGuidelineCategory\":\"Unknown\",\"migrationGuidelineContext\":[{},{}]},{\"guidelineId\":\"cluqvo\",\"migrationGuidelineCategory\":\"AvailabilityGroupGuideline\",\"migrationGuidelineContext\":[{},{},{},{}]},{\"guidelineId\":\"mr\",\"migrationGuidelineCategory\":\"AvailabilityGroupGuideline\",\"migrationGuidelineContext\":[{}]},{\"guidelineId\":\"wpbmzgwesydsxwef\",\"migrationGuidelineCategory\":\"Unknown\",\"migrationGuidelineContext\":[{},{},{}]}],\"recommendationReasonings\":[{\"reasoningId\":\"wndyqleallk\",\"reasoningString\":\"tkhlowkxxpvbr\",\"reasoningCategory\":\"jmzsyzfh\",\"contextParameters\":[{},{},{},{}]},{\"reasoningId\":\"ikcyyc\",\"reasoningString\":\"nsjlpjrtws\",\"reasoningCategory\":\"vv\",\"contextParameters\":[{}]},{\"reasoningId\":\"hvtrrmhwrbfdpyf\",\"reasoningString\":\"bhvjglr\",\"reasoningCategory\":\"uyzlw\",\"contextParameters\":[{},{},{},{}]},{\"reasoningId\":\"mhoocl\",\"reasoningString\":\"n\",\"reasoningCategory\":\"memczjkmmyk\",\"contextParameters\":[{},{}]}],\"migrationTargetPlatform\":\"AzureSqlManagedInstance\",\"suitability\":\"ReadinessUnknown\",\"migrationIssues\":[{\"issueId\":\"rryejylmbkzudnig\",\"issueCategory\":\"Internal\",\"impactedObjects\":[{},{},{},{}]},{\"issueId\":\"jewlpxuzzjg\",\"issueCategory\":\"Issue\",\"impactedObjects\":[{},{}]},{\"issueId\":\"hqo\",\"issueCategory\":\"Warning\",\"impactedObjects\":[{},{},{}]},{\"issueId\":\"akydiwfbrkwpz\",\"issueCategory\":\"Issue\",\"impactedObjects\":[{},{}]}]},\"azureSqlDBSuitabilityDetails\":{\"azureSqlSku\":{\"azureSqlServiceTier\":\"Automatic\",\"azureSqlComputeTier\":\"Unknown\",\"azureSqlHardwareGeneration\":\"Gen5\",\"storageMaxSizeInMB\":22.325277,\"predictedDataSizeInMB\":14.166528,\"predictedLogSizeInMB\":67.56118,\"cores\":1379010451,\"azureSqlTargetType\":\"AzureVirtualMachine\"},\"replicaAzureSqlSku\":[{\"azureSqlServiceTier\":\"GeneralPurpose\",\"azureSqlComputeTier\":\"Automatic\",\"azureSqlHardwareGeneration\":\"Unknown\",\"storageMaxSizeInMB\":65.314285,\"predictedDataSizeInMB\":51.28268,\"predictedLogSizeInMB\":74.63233,\"cores\":540172830,\"azureSqlTargetType\":\"AzureVirtualMachine\"},{\"azureSqlServiceTier\":\"GeneralPurpose\",\"azureSqlComputeTier\":\"Automatic\",\"azureSqlHardwareGeneration\":\"Automatic\",\"storageMaxSizeInMB\":67.47476,\"predictedDataSizeInMB\":67.87149,\"predictedLogSizeInMB\":49.267586,\"cores\":1074910228,\"azureSqlTargetType\":\"AzureSqlVirtualMachine\"},{\"azureSqlServiceTier\":\"Unknown\",\"azureSqlComputeTier\":\"Unknown\",\"azureSqlHardwareGeneration\":\"Gen5\",\"storageMaxSizeInMB\":59.47985,\"predictedDataSizeInMB\":84.183266,\"predictedLogSizeInMB\":83.88658,\"cores\":1967896838,\"azureSqlTargetType\":\"AzureSqlManagedInstance\"}],\"sharedResources\":{\"sharedDataDisks\":[{\"diskType\":\"StandardSSD\",\"diskSize\":\"Premium_P6\",\"diskRedundancy\":\"Unknown\",\"storageCost\":29.923105,\"recommendedSizeInGib\":68.79162,\"recommendedThroughputInMbps\":42.975296,\"recommendedIops\":5.588526},{\"diskType\":\"Standard\",\"diskSize\":\"Standard_S80\",\"diskRedundancy\":\"ZRS\",\"storageCost\":34.000515,\"recommendedSizeInGib\":73.243675,\"recommendedThroughputInMbps\":62.01772,\"recommendedIops\":50.97294}],\"sharedLogDisks\":[{\"diskType\":\"PremiumV2\",\"diskSize\":\"Premium_P30\",\"diskRedundancy\":\"Unknown\",\"storageCost\":34.706463,\"recommendedSizeInGib\":37.694584,\"recommendedThroughputInMbps\":22.453255,\"recommendedIops\":18.89614}],\"sharedTempDbDisks\":[{\"diskType\":\"Standard\",\"diskSize\":\"Premium_P15\",\"diskRedundancy\":\"ZRS\",\"storageCost\":99.97765,\"recommendedSizeInGib\":21.16068,\"recommendedThroughputInMbps\":0.6466925,\"recommendedIops\":15.830064},{\"diskType\":\"StandardSSD\",\"diskSize\":\"Premium_P1\",\"diskRedundancy\":\"LRS\",\"storageCost\":64.1839,\"recommendedSizeInGib\":94.96739,\"recommendedThroughputInMbps\":68.434845,\"recommendedIops\":28.949053}],\"numberOfMounts\":491651275,\"quorumWitness\":{\"quorumWitnessType\":\"Cloud\"}},\"monthlyComputeCost\":80.78199,\"monthlyStorageCost\":63.010185,\"costComponents\":[{\"name\":\"MonthlySecurityCost\",\"value\":88.73604,\"description\":\"c\"},{\"name\":\"MonthlyPremiumV2StorageCost\",\"value\":72.14276,\"description\":\"eovvtzej\"},{\"name\":\"MonthlySecurityCost\",\"value\":7.799661,\"description\":\"tikyj\"}],\"securitySuitability\":\"Suitable\",\"shouldProvisionReplicas\":false,\"skuReplicationMode\":\"ActiveGeoReplication\",\"migrationGuidelines\":[{\"guidelineId\":\"rzvh\",\"migrationGuidelineCategory\":\"General\",\"migrationGuidelineContext\":[{},{},{},{}]},{\"guidelineId\":\"tgvgzp\",\"migrationGuidelineCategory\":\"General\",\"migrationGuidelineContext\":[{},{},{},{}]},{\"guidelineId\":\"awjmjsmw\",\"migrationGuidelineCategory\":\"FailoverCluterInstanceGuideLine\",\"migrationGuidelineContext\":[{},{},{}]}],\"recommendationReasonings\":[{\"reasoningId\":\"zz\",\"reasoningString\":\"jafi\",\"reasoningCategory\":\"hguynuchlgmltxdw\",\"contextParameters\":[{},{}]},{\"reasoningId\":\"us\",\"reasoningString\":\"vlnsnnjz\",\"reasoningCategory\":\"afolpymwamxqzrag\",\"contextParameters\":[{},{}]},{\"reasoningId\":\"htvdula\",\"reasoningString\":\"lejchcsr\",\"reasoningCategory\":\"knmzlanrupdwvnp\",\"contextParameters\":[{},{},{},{}]},{\"reasoningId\":\"q\",\"reasoningString\":\"jhmqrhvthla\",\"reasoningCategory\":\"dcxsmlz\",\"contextParameters\":[{},{},{}]}],\"migrationTargetPlatform\":\"Recommended\",\"suitability\":\"ReadinessUnknown\",\"migrationIssues\":[{\"issueId\":\"ydlhqvln\",\"issueCategory\":\"Issue\",\"impactedObjects\":[{}]}]},\"azureSqlVMSuitabilityDetails\":{\"azureSqlSku\":{\"virtualMachineSize\":{\"azureVmFamily\":\"Dv3_series\",\"cores\":224237712,\"azureSkuName\":\"Standard_A2\",\"availableCores\":339285731,\"maxNetworkInterfaces\":1799844298},\"dataDiskSizes\":[{\"diskType\":\"StandardSSD\",\"diskSize\":\"Premium_P30\",\"diskRedundancy\":\"LRS\",\"storageCost\":76.17075,\"recommendedSizeInGib\":49.107258,\"recommendedThroughputInMbps\":84.63951,\"recommendedIops\":39.722282},{\"diskType\":\"PremiumV2\",\"diskSize\":\"Premium_P40\",\"diskRedundancy\":\"Unknown\",\"storageCost\":9.709257,\"recommendedSizeInGib\":62.74608,\"recommendedThroughputInMbps\":44.4742,\"recommendedIops\":88.8744}],\"logDiskSizes\":[{\"diskType\":\"Ultra\",\"diskSize\":\"Premium_P1\",\"diskRedundancy\":\"Unknown\",\"storageCost\":60.33164,\"recommendedSizeInGib\":44.452847,\"recommendedThroughputInMbps\":8.862007,\"recommendedIops\":68.489395},{\"diskType\":\"Ultra\",\"diskSize\":\"Premium_P2\",\"diskRedundancy\":\"ZRS\",\"storageCost\":92.985374,\"recommendedSizeInGib\":74.32026,\"recommendedThroughputInMbps\":98.59011,\"recommendedIops\":31.529743}],\"azureSqlTargetType\":\"AzureSqlManagedInstance\"},\"replicaAzureSqlSku\":[{\"virtualMachineSize\":{\"azureVmFamily\":\"Unknown\",\"cores\":1312612071,\"azureSkuName\":\"Standard_E8ads_v5\",\"availableCores\":1256156886,\"maxNetworkInterfaces\":1553395151},\"dataDiskSizes\":[{},{}],\"logDiskSizes\":[{},{},{},{}],\"azureSqlTargetType\":\"AzureSqlManagedInstance\"},{\"virtualMachineSize\":{\"azureVmFamily\":\"Ddv4_series\",\"cores\":1822893044,\"azureSkuName\":\"Standard_DS1\",\"availableCores\":581418473,\"maxNetworkInterfaces\":2063610896},\"dataDiskSizes\":[{},{},{}],\"logDiskSizes\":[{},{}],\"azureSqlTargetType\":\"Unknown\"},{\"virtualMachineSize\":{\"azureVmFamily\":\"M_series\",\"cores\":1686230726,\"azureSkuName\":\"Standard_M64ls\",\"availableCores\":667658590,\"maxNetworkInterfaces\":1657438735},\"dataDiskSizes\":[{},{},{},{}],\"logDiskSizes\":[{}],\"azureSqlTargetType\":\"AzureSqlVirtualMachine\"}],\"sharedResources\":{\"sharedDataDisks\":[{\"diskType\":\"Standard\",\"diskSize\":\"Standard_S50\",\"diskRedundancy\":\"Unknown\",\"storageCost\":37.06757,\"recommendedSizeInGib\":37.920105,\"recommendedThroughputInMbps\":30.722845,\"recommendedIops\":12.901717},{\"diskType\":\"Unknown\",\"diskSize\":\"StandardSSD_E1\",\"diskRedundancy\":\"ZRS\",\"storageCost\":54.761898,\"recommendedSizeInGib\":9.566725,\"recommendedThroughputInMbps\":80.95274,\"recommendedIops\":73.064575}],\"sharedLogDisks\":[{\"diskType\":\"PremiumV2\",\"diskSize\":\"Premium_P40\",\"diskRedundancy\":\"LRS\",\"storageCost\":83.58084,\"recommendedSizeInGib\":98.88538,\"recommendedThroughputInMbps\":71.063446,\"recommendedIops\":67.13245},{\"diskType\":\"Premium\",\"diskSize\":\"Premium_P4\",\"diskRedundancy\":\"ZRS\",\"storageCost\":59.358376,\"recommendedSizeInGib\":72.6253,\"recommendedThroughputInMbps\":81.42051,\"recommendedIops\":17.64272}],\"sharedTempDbDisks\":[{\"diskType\":\"PremiumV2\",\"diskSize\":\"Premium_P30\",\"diskRedundancy\":\"ZRS\",\"storageCost\":46.628986,\"recommendedSizeInGib\":9.73481,\"recommendedThroughputInMbps\":61.396862,\"recommendedIops\":0.5134404}],\"numberOfMounts\":824374091,\"quorumWitness\":{\"quorumWitnessType\":\"Unknown\"}},\"monthlyComputeCost\":79.17579,\"monthlyStorageCost\":87.84745,\"costComponents\":[{\"name\":\"MonthlySecurityCost\",\"value\":35.51975,\"description\":\"hxogjggsvoujkxi\"},{\"name\":\"MonthlySecurityCost\",\"value\":94.60625,\"description\":\"kmdyomkxfbvfbh\"}],\"securitySuitability\":\"ConditionallySuitable\",\"shouldProvisionReplicas\":true,\"skuReplicationMode\":\"NotApplicable\",\"migrationGuidelines\":[{\"guidelineId\":\"deimawzov\",\"migrationGuidelineCategory\":\"FailoverCluterInstanceGuideLine\",\"migrationGuidelineContext\":[{},{},{},{}]},{\"guidelineId\":\"ikjcjcazt\",\"migrationGuidelineCategory\":\"FailoverCluterInstanceGuideLine\",\"migrationGuidelineContext\":[{},{}]}],\"recommendationReasonings\":[{\"reasoningId\":\"xwc\",\"reasoningString\":\"likytwvczcswka\",\"reasoningCategory\":\"ejyfdvlvhbwrnfx\",\"contextParameters\":[{},{}]},{\"reasoningId\":\"pqthehnmnaoya\",\"reasoningString\":\"coeqswankltytm\",\"reasoningCategory\":\"roznnhdrlktgj\",\"contextParameters\":[{},{},{}]},{\"reasoningId\":\"uxhemlwywaeeczg\",\"reasoningString\":\"ukklelss\",\"reasoningCategory\":\"lycsxz\",\"contextParameters\":[{}]}],\"migrationTargetPlatform\":\"AzureSqlDatabase\",\"suitability\":\"ConditionallySuitable\",\"migrationIssues\":[{\"issueId\":\"sqplpvmjcd\",\"issueCategory\":\"Internal\",\"impactedObjects\":[{},{}]},{\"issueId\":\"yvteowxvgpiudeu\",\"issueCategory\":\"Issue\",\"impactedObjects\":[{}]},{\"issueId\":\"c\",\"issueCategory\":\"Warning\",\"impactedObjects\":[{},{}]},{\"issueId\":\"fykhvuhxepmru\",\"issueCategory\":\"Internal\",\"impactedObjects\":[{},{}]}]},\"assessedSqlEntityArmId\":\"obns\",\"isClustered\":true,\"isHighAvailabilityEnabled\":true,\"sqlEdition\":\"tymkmvguihywart\",\"sqlVersion\":\"phkixkykxdssjpe\",\"sizingCriterion\":\"PerformanceBased\"},\"id\":\"fxhikkflrmymyi\",\"name\":\"cqlh\",\"type\":\"isws\"}") + .toObject(AssessedSqlRecommendedEntityInner.class); + Assertions.assertEquals("obns", model.properties().assessedSqlEntityArmId()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AssessedSqlRecommendedEntityInner model = new AssessedSqlRecommendedEntityInner() + .withProperties(new AssessedSqlRecommendedEntityProperties().withAssessedSqlEntityArmId("obns")); + model = BinaryData.fromObject(model).toObject(AssessedSqlRecommendedEntityInner.class); + Assertions.assertEquals("obns", model.properties().assessedSqlEntityArmId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlRecommendedEntityListResultTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlRecommendedEntityListResultTests.java new file mode 100644 index 000000000000..df2c1ee77f1b --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlRecommendedEntityListResultTests.java @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessedSqlRecommendedEntityInner; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlRecommendedEntityListResult; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlRecommendedEntityProperties; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class AssessedSqlRecommendedEntityListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AssessedSqlRecommendedEntityListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"machineName\":\"gm\",\"instanceName\":\"wahzjmucftbyr\",\"productSupportStatus\":{\"currentVersion\":\"ohkpigqfu\",\"servicePackStatus\":\"ckzmkwklsnox\",\"esuStatus\":\"mqeq\",\"supportStatus\":\"h\",\"eta\":652323587,\"currentEsuYear\":\"gwydyy\",\"mainstreamEndDate\":\"2021-07-30T21:21:05Z\",\"extendedSupportEndDate\":\"2021-07-27T13:55:01Z\",\"extendedSecurityUpdateYear1EndDate\":\"2021-06-04T03:09:29Z\",\"extendedSecurityUpdateYear2EndDate\":\"2021-03-04T03:34:09Z\",\"extendedSecurityUpdateYear3EndDate\":\"2021-02-24T07:07:12Z\"},\"dbCount\":1465661889,\"discoveredDBCount\":935843013,\"hasScanOccurred\":true,\"recommendedAzureSqlTargetType\":\"AzureVirtualMachine\",\"recommendedSuitability\":\"PotentiallySuitableForVM\",\"azureSqlMISuitabilityDetails\":{\"azureSqlSku\":{\"azureSqlServiceTier\":\"Unknown\",\"azureSqlComputeTier\":\"Serverless\",\"azureSqlHardwareGeneration\":\"M_series\",\"storageMaxSizeInMB\":85.834076,\"predictedDataSizeInMB\":65.096924,\"predictedLogSizeInMB\":89.39814,\"cores\":45100221,\"azureSqlTargetType\":\"AzureVirtualMachine\"},\"replicaAzureSqlSku\":[{},{}],\"sharedResources\":{\"sharedDataDisks\":[{},{}],\"sharedLogDisks\":[{},{}],\"sharedTempDbDisks\":[{},{},{},{}],\"numberOfMounts\":783631695,\"quorumWitness\":{}},\"monthlyComputeCost\":81.85477,\"monthlyStorageCost\":29.225004,\"costComponents\":[{},{},{}],\"securitySuitability\":\"NotSuitable\",\"shouldProvisionReplicas\":true,\"skuReplicationMode\":\"NotApplicable\",\"migrationGuidelines\":[{},{}],\"recommendationReasonings\":[{},{},{},{}],\"migrationTargetPlatform\":\"Recommended\",\"suitability\":\"ReadinessUnknown\",\"migrationIssues\":[{},{},{}]},\"azureSqlDBSuitabilityDetails\":{\"azureSqlSku\":{\"azureSqlServiceTier\":\"BusinessCritical\",\"azureSqlComputeTier\":\"Provisioned\",\"azureSqlHardwareGeneration\":\"Fsv2_series\",\"storageMaxSizeInMB\":20.945662,\"predictedDataSizeInMB\":75.05848,\"predictedLogSizeInMB\":85.42869,\"cores\":2123752302,\"azureSqlTargetType\":\"Unknown\"},\"replicaAzureSqlSku\":[{},{},{},{}],\"sharedResources\":{\"sharedDataDisks\":[{},{},{},{}],\"sharedLogDisks\":[{}],\"sharedTempDbDisks\":[{}],\"numberOfMounts\":188519413,\"quorumWitness\":{}},\"monthlyComputeCost\":77.997154,\"monthlyStorageCost\":3.6737323,\"costComponents\":[{},{}],\"securitySuitability\":\"ReadinessUnknown\",\"shouldProvisionReplicas\":true,\"skuReplicationMode\":\"FailoverGroupInstance\",\"migrationGuidelines\":[{}],\"recommendationReasonings\":[{},{},{}],\"migrationTargetPlatform\":\"Recommended\",\"suitability\":\"Suitable\",\"migrationIssues\":[{},{},{},{}]},\"azureSqlVMSuitabilityDetails\":{\"azureSqlSku\":{\"virtualMachineSize\":{},\"dataDiskSizes\":[{}],\"logDiskSizes\":[{},{},{},{}],\"azureSqlTargetType\":\"Unknown\"},\"replicaAzureSqlSku\":[{}],\"sharedResources\":{\"sharedDataDisks\":[{}],\"sharedLogDisks\":[{}],\"sharedTempDbDisks\":[{},{},{}],\"numberOfMounts\":1265182150,\"quorumWitness\":{}},\"monthlyComputeCost\":5.7943583,\"monthlyStorageCost\":45.729744,\"costComponents\":[{},{},{}],\"securitySuitability\":\"ConditionallySuitable\",\"shouldProvisionReplicas\":true,\"skuReplicationMode\":\"ActiveGeoReplication\",\"migrationGuidelines\":[{},{}],\"recommendationReasonings\":[{}],\"migrationTargetPlatform\":\"AzureVirtualMachine\",\"suitability\":\"NotSuitable\",\"migrationIssues\":[{},{}]},\"assessedSqlEntityArmId\":\"ewuninvud\",\"isClustered\":false,\"isHighAvailabilityEnabled\":true,\"sqlEdition\":\"tvq\",\"sqlVersion\":\"rqctmxxdtdd\",\"sizingCriterion\":\"AsOnPremises\"},\"id\":\"uytxzvtznapxban\",\"name\":\"o\",\"type\":\"voxczytpr\"}],\"nextLink\":\"wvroevytlyokrrr\"}") + .toObject(AssessedSqlRecommendedEntityListResult.class); + Assertions.assertEquals("ewuninvud", model.value().get(0).properties().assessedSqlEntityArmId()); + Assertions.assertEquals("wvroevytlyokrrr", model.nextLink()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AssessedSqlRecommendedEntityListResult model = new AssessedSqlRecommendedEntityListResult() + .withValue(Arrays.asList(new AssessedSqlRecommendedEntityInner() + .withProperties(new AssessedSqlRecommendedEntityProperties().withAssessedSqlEntityArmId("ewuninvud")))) + .withNextLink("wvroevytlyokrrr"); + model = BinaryData.fromObject(model).toObject(AssessedSqlRecommendedEntityListResult.class); + Assertions.assertEquals("ewuninvud", model.value().get(0).properties().assessedSqlEntityArmId()); + Assertions.assertEquals("wvroevytlyokrrr", model.nextLink()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlRecommendedEntityOperationsGetWithResponseMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlRecommendedEntityOperationsGetWithResponseMockTests.java new file mode 100644 index 000000000000..7d4194913062 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlRecommendedEntityOperationsGetWithResponseMockTests.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.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlRecommendedEntity; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class AssessedSqlRecommendedEntityOperationsGetWithResponseMockTests { + @Test + public void testGetWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"machineName\":\"d\",\"instanceName\":\"fhtwmmkfqb\",\"productSupportStatus\":{\"currentVersion\":\"ulwwtrjmeqkvyhz\",\"servicePackStatus\":\"poyu\",\"esuStatus\":\"uensn\",\"supportStatus\":\"jphmpoejnglpws\",\"eta\":709381303,\"currentEsuYear\":\"jsumxpezcoio\",\"mainstreamEndDate\":\"2021-02-11T21:12:39Z\",\"extendedSupportEndDate\":\"2021-04-29T14:56:08Z\",\"extendedSecurityUpdateYear1EndDate\":\"2021-09-14T09:51:16Z\",\"extendedSecurityUpdateYear2EndDate\":\"2021-09-05T21:06:38Z\",\"extendedSecurityUpdateYear3EndDate\":\"2021-11-22T22:48:31Z\"},\"dbCount\":1676856163,\"discoveredDBCount\":222653921,\"hasScanOccurred\":false,\"recommendedAzureSqlTargetType\":\"AzureSqlManagedInstance\",\"recommendedSuitability\":\"Unknown\",\"azureSqlMISuitabilityDetails\":{\"azureSqlSku\":{\"azureSqlServiceTier\":\"BusinessCritical\",\"azureSqlComputeTier\":\"Serverless\",\"azureSqlHardwareGeneration\":\"Fsv2_series\",\"storageMaxSizeInMB\":9.771246,\"predictedDataSizeInMB\":62.806965,\"predictedLogSizeInMB\":76.82925,\"cores\":266458582,\"azureSqlTargetType\":\"AzureSqlVirtualMachine\"},\"replicaAzureSqlSku\":[{\"azureSqlServiceTier\":\"Unknown\",\"azureSqlComputeTier\":\"Unknown\",\"azureSqlHardwareGeneration\":\"DC_series\",\"storageMaxSizeInMB\":50.425297,\"predictedDataSizeInMB\":56.37652,\"predictedLogSizeInMB\":48.299534,\"cores\":1638013744,\"azureSqlTargetType\":\"AzureSqlVirtualMachine\"},{\"azureSqlServiceTier\":\"Unknown\",\"azureSqlComputeTier\":\"Unknown\",\"azureSqlHardwareGeneration\":\"Automatic\",\"storageMaxSizeInMB\":82.06618,\"predictedDataSizeInMB\":0.20298958,\"predictedLogSizeInMB\":99.19687,\"cores\":1518729432,\"azureSqlTargetType\":\"AzureVirtualMachine\"},{\"azureSqlServiceTier\":\"Unknown\",\"azureSqlComputeTier\":\"Provisioned\",\"azureSqlHardwareGeneration\":\"DC_series\",\"storageMaxSizeInMB\":89.95035,\"predictedDataSizeInMB\":27.503252,\"predictedLogSizeInMB\":84.888824,\"cores\":1476415299,\"azureSqlTargetType\":\"AzureVirtualMachine\"}],\"sharedResources\":{\"sharedDataDisks\":[{},{},{},{}],\"sharedLogDisks\":[{},{},{}],\"sharedTempDbDisks\":[{},{},{}],\"numberOfMounts\":1276332701,\"quorumWitness\":{\"quorumWitnessType\":\"Cloud\"}},\"monthlyComputeCost\":67.98498,\"monthlyStorageCost\":89.08338,\"costComponents\":[{\"name\":\"MonthlyAzureHybridCostSavings\",\"value\":43.12796,\"description\":\"tikesl\"},{\"name\":\"MonthlyAzureHybridCostSavings\",\"value\":71.988,\"description\":\"ixyqhfnkvy\"}],\"securitySuitability\":\"Suitable\",\"shouldProvisionReplicas\":true,\"skuReplicationMode\":\"FailoverGroupInstance\",\"migrationGuidelines\":[{\"guidelineId\":\"quwzxhrptyodl\",\"migrationGuidelineCategory\":\"General\",\"migrationGuidelineContext\":[{},{}]}],\"recommendationReasonings\":[{\"reasoningId\":\"dsobjopnouhbq\",\"reasoningString\":\"kqxs\",\"reasoningCategory\":\"uzyigfcvcewbwqhd\",\"contextParameters\":[{},{}]}],\"migrationTargetPlatform\":\"Unknown\",\"suitability\":\"Unknown\",\"migrationIssues\":[{\"issueId\":\"mazdfsqxh\",\"issueCategory\":\"Issue\",\"impactedObjects\":[{},{}]},{\"issueId\":\"parn\",\"issueCategory\":\"Internal\",\"impactedObjects\":[{},{},{}]}]},\"azureSqlDBSuitabilityDetails\":{\"azureSqlSku\":{\"azureSqlServiceTier\":\"Automatic\",\"azureSqlComputeTier\":\"Provisioned\",\"azureSqlHardwareGeneration\":\"Automatic\",\"storageMaxSizeInMB\":7.691741,\"predictedDataSizeInMB\":3.1134665,\"predictedLogSizeInMB\":0.019079447,\"cores\":1650141631,\"azureSqlTargetType\":\"AzureSqlManagedInstance\"},\"replicaAzureSqlSku\":[{\"azureSqlServiceTier\":\"HyperScale\",\"azureSqlComputeTier\":\"Automatic\",\"azureSqlHardwareGeneration\":\"DC_series\",\"storageMaxSizeInMB\":52.820633,\"predictedDataSizeInMB\":95.00618,\"predictedLogSizeInMB\":49.1711,\"cores\":1244357050,\"azureSqlTargetType\":\"Recommended\"}],\"sharedResources\":{\"sharedDataDisks\":[{},{},{}],\"sharedLogDisks\":[{}],\"sharedTempDbDisks\":[{},{},{},{}],\"numberOfMounts\":1707361059,\"quorumWitness\":{\"quorumWitnessType\":\"Disk\"}},\"monthlyComputeCost\":8.474427,\"monthlyStorageCost\":51.78052,\"costComponents\":[{\"name\":\"MonthlySecurityCost\",\"value\":2.1707296,\"description\":\"rocqsxy\"}],\"securitySuitability\":\"NotSuitable\",\"shouldProvisionReplicas\":false,\"skuReplicationMode\":\"NotApplicable\",\"migrationGuidelines\":[{\"guidelineId\":\"is\",\"migrationGuidelineCategory\":\"Unknown\",\"migrationGuidelineContext\":[{},{}]},{\"guidelineId\":\"ajamc\",\"migrationGuidelineCategory\":\"Unknown\",\"migrationGuidelineContext\":[{},{},{},{}]},{\"guidelineId\":\"p\",\"migrationGuidelineCategory\":\"FailoverCluterInstanceGuideLine\",\"migrationGuidelineContext\":[{},{},{},{}]}],\"recommendationReasonings\":[{\"reasoningId\":\"eynq\",\"reasoningString\":\"hkigglclwalhvub\",\"reasoningCategory\":\"zphetxdqcm\",\"contextParameters\":[{},{}]},{\"reasoningId\":\"jq\",\"reasoningString\":\"vale\",\"reasoningCategory\":\"bibiwks\",\"contextParameters\":[{}]},{\"reasoningId\":\"x\",\"reasoningString\":\"fpzvoikvntwczf\",\"reasoningCategory\":\"ushlcxpblalh\",\"contextParameters\":[{},{}]}],\"migrationTargetPlatform\":\"Recommended\",\"suitability\":\"ConditionallySuitable\",\"migrationIssues\":[{\"issueId\":\"idqzsaaoqdsgpto\",\"issueCategory\":\"Warning\",\"impactedObjects\":[{},{}]}]},\"azureSqlVMSuitabilityDetails\":{\"azureSqlSku\":{\"virtualMachineSize\":{\"azureVmFamily\":\"Standard_A0_A7\",\"cores\":43506706,\"azureSkuName\":\"Basic_A2\",\"availableCores\":2052552411,\"maxNetworkInterfaces\":1525228635},\"dataDiskSizes\":[{}],\"logDiskSizes\":[{}],\"azureSqlTargetType\":\"Unknown\"},\"replicaAzureSqlSku\":[{\"virtualMachineSize\":{},\"dataDiskSizes\":[{}],\"logDiskSizes\":[{},{}],\"azureSqlTargetType\":\"AzureSqlManagedInstance\"},{\"virtualMachineSize\":{},\"dataDiskSizes\":[{},{},{}],\"logDiskSizes\":[{},{},{}],\"azureSqlTargetType\":\"Recommended\"}],\"sharedResources\":{\"sharedDataDisks\":[{}],\"sharedLogDisks\":[{},{},{}],\"sharedTempDbDisks\":[{},{},{},{}],\"numberOfMounts\":707800072,\"quorumWitness\":{\"quorumWitnessType\":\"Disk\"}},\"monthlyComputeCost\":59.643085,\"monthlyStorageCost\":67.26635,\"costComponents\":[{\"name\":\"MonthlyAzureHybridCostSavings\",\"value\":69.455376,\"description\":\"xre\"},{\"name\":\"Unknown\",\"value\":99.84853,\"description\":\"n\"}],\"securitySuitability\":\"ConditionallySuitable\",\"shouldProvisionReplicas\":false,\"skuReplicationMode\":\"ActiveGeoReplication\",\"migrationGuidelines\":[{\"guidelineId\":\"qycmmoxf\",\"migrationGuidelineCategory\":\"AvailabilityGroupGuideline\",\"migrationGuidelineContext\":[{}]}],\"recommendationReasonings\":[{\"reasoningId\":\"mwh\",\"reasoningString\":\"ali\",\"reasoningCategory\":\"ycgnwplrrbphc\",\"contextParameters\":[{}]},{\"reasoningId\":\"ibticuhqv\",\"reasoningString\":\"spbfsfeqbbewfc\",\"reasoningCategory\":\"fpyyxmzrmtm\",\"contextParameters\":[{},{}]},{\"reasoningId\":\"uweyyjshcyb\",\"reasoningString\":\"upp\",\"reasoningCategory\":\"prcmvouujxdiik\",\"contextParameters\":[{},{},{}]}],\"migrationTargetPlatform\":\"Recommended\",\"suitability\":\"ReadinessUnknown\",\"migrationIssues\":[{\"issueId\":\"lrxikj\",\"issueCategory\":\"Issue\",\"impactedObjects\":[{}]}]},\"assessedSqlEntityArmId\":\"npipcwybszfncn\",\"isClustered\":false,\"isHighAvailabilityEnabled\":true,\"sqlEdition\":\"saebwfwhxorpwal\",\"sqlVersion\":\"wugexojfccyl\",\"sizingCriterion\":\"PerformanceBased\"},\"id\":\"thvazjpw\",\"name\":\"xcdrzprobzzxezm\",\"type\":\"rkjg\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + AssessedSqlRecommendedEntity response = manager.assessedSqlRecommendedEntityOperations() + .getWithResponse("wz", "drpizfulgyctsdb", "qgkujds", "oxrqw", "eurbtigapdyarik", + com.azure.core.util.Context.NONE) + .getValue(); + + Assertions.assertEquals("npipcwybszfncn", response.properties().assessedSqlEntityArmId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlRecommendedEntityOperationsListBySqlAssessmentV2MockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlRecommendedEntityOperationsListBySqlAssessmentV2MockTests.java new file mode 100644 index 000000000000..40979d495ea4 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessedSqlRecommendedEntityOperationsListBySqlAssessmentV2MockTests.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.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.AssessedSqlRecommendedEntity; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class AssessedSqlRecommendedEntityOperationsListBySqlAssessmentV2MockTests { + @Test + public void testListBySqlAssessmentV2() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"machineName\":\"skbwgm\",\"instanceName\":\"rulcfogx\",\"productSupportStatus\":{\"currentVersion\":\"nwjtpf\",\"servicePackStatus\":\"xcouzfwofwak\",\"esuStatus\":\"zkdtzxsoed\",\"supportStatus\":\"wglihezomu\",\"eta\":1614778568,\"currentEsuYear\":\"isnionetbzdrdpue\",\"mainstreamEndDate\":\"2021-07-27T09:18:03Z\",\"extendedSupportEndDate\":\"2021-05-10T00:45:18Z\",\"extendedSecurityUpdateYear1EndDate\":\"2021-02-16T02:41:21Z\",\"extendedSecurityUpdateYear2EndDate\":\"2021-10-08T03:35:33Z\",\"extendedSecurityUpdateYear3EndDate\":\"2021-05-02T19:22:45Z\"},\"dbCount\":212272318,\"discoveredDBCount\":118271276,\"hasScanOccurred\":false,\"recommendedAzureSqlTargetType\":\"AzureVirtualMachine\",\"recommendedSuitability\":\"PotentiallySuitableForVM\",\"azureSqlMISuitabilityDetails\":{\"azureSqlSku\":{\"azureSqlServiceTier\":\"BusinessCritical\",\"azureSqlComputeTier\":\"Provisioned\",\"azureSqlHardwareGeneration\":\"Unknown\",\"storageMaxSizeInMB\":56.445385,\"predictedDataSizeInMB\":82.74375,\"predictedLogSizeInMB\":68.94291,\"cores\":926783353,\"azureSqlTargetType\":\"AzureSqlVirtualMachine\"},\"replicaAzureSqlSku\":[{\"azureSqlServiceTier\":\"GeneralPurpose\",\"azureSqlComputeTier\":\"Serverless\",\"azureSqlHardwareGeneration\":\"Gen5\",\"storageMaxSizeInMB\":96.515785,\"predictedDataSizeInMB\":95.57669,\"predictedLogSizeInMB\":2.9654562,\"cores\":1015199416,\"azureSqlTargetType\":\"Recommended\"},{\"azureSqlServiceTier\":\"Unknown\",\"azureSqlComputeTier\":\"Serverless\",\"azureSqlHardwareGeneration\":\"DC_series\",\"storageMaxSizeInMB\":28.742128,\"predictedDataSizeInMB\":89.02015,\"predictedLogSizeInMB\":35.792778,\"cores\":1889348759,\"azureSqlTargetType\":\"AzureSqlManagedInstance\"},{\"azureSqlServiceTier\":\"Automatic\",\"azureSqlComputeTier\":\"Provisioned\",\"azureSqlHardwareGeneration\":\"Unknown\",\"storageMaxSizeInMB\":36.13075,\"predictedDataSizeInMB\":58.18631,\"predictedLogSizeInMB\":76.93034,\"cores\":161019045,\"azureSqlTargetType\":\"Unknown\"},{\"azureSqlServiceTier\":\"GeneralPurpose\",\"azureSqlComputeTier\":\"Automatic\",\"azureSqlHardwareGeneration\":\"Fsv2_series\",\"storageMaxSizeInMB\":31.641466,\"predictedDataSizeInMB\":57.541405,\"predictedLogSizeInMB\":91.92485,\"cores\":1236323053,\"azureSqlTargetType\":\"AzureVirtualMachine\"}],\"sharedResources\":{\"sharedDataDisks\":[{}],\"sharedLogDisks\":[{},{}],\"sharedTempDbDisks\":[{},{}],\"numberOfMounts\":873252711,\"quorumWitness\":{\"quorumWitnessType\":\"Disk\"}},\"monthlyComputeCost\":54.43496,\"monthlyStorageCost\":95.73449,\"costComponents\":[{\"name\":\"MonthlyPremiumV2StorageCost\",\"value\":97.70187,\"description\":\"paydhfn\"}],\"securitySuitability\":\"ReadinessUnknown\",\"shouldProvisionReplicas\":true,\"skuReplicationMode\":\"NotApplicable\",\"migrationGuidelines\":[{\"guidelineId\":\"snyzmspam\",\"migrationGuidelineCategory\":\"General\",\"migrationGuidelineContext\":[{}]},{\"guidelineId\":\"lslcefiqdktwtkvi\",\"migrationGuidelineCategory\":\"General\",\"migrationGuidelineContext\":[{},{}]},{\"guidelineId\":\"woynguu\",\"migrationGuidelineCategory\":\"FailoverCluterInstanceGuideLine\",\"migrationGuidelineContext\":[{},{},{}]},{\"guidelineId\":\"dpcmhjh\",\"migrationGuidelineCategory\":\"FailoverCluterInstanceGuideLine\",\"migrationGuidelineContext\":[{}]}],\"recommendationReasonings\":[{\"reasoningId\":\"ym\",\"reasoningString\":\"ztsilscvq\",\"reasoningCategory\":\"eiihfymko\",\"contextParameters\":[{}]},{\"reasoningId\":\"eseuugci\",\"reasoningString\":\"hogsmgbvmtd\",\"reasoningCategory\":\"qbe\",\"contextParameters\":[{},{}]},{\"reasoningId\":\"veglabtvkbiwzn\",\"reasoningString\":\"fg\",\"reasoningCategory\":\"cud\",\"contextParameters\":[{},{}]},{\"reasoningId\":\"paczmuh\",\"reasoningString\":\"akznhokhoitwhr\",\"reasoningCategory\":\"dmmazdnc\",\"contextParameters\":[{}]}],\"migrationTargetPlatform\":\"AzureSqlManagedInstance\",\"suitability\":\"Unknown\",\"migrationIssues\":[{\"issueId\":\"qpx\",\"issueCategory\":\"Internal\",\"impactedObjects\":[{}]},{\"issueId\":\"kcdgfhbssd\",\"issueCategory\":\"Issue\",\"impactedObjects\":[{}]},{\"issueId\":\"xdede\",\"issueCategory\":\"Internal\",\"impactedObjects\":[{},{}]},{\"issueId\":\"gxsur\",\"issueCategory\":\"Issue\",\"impactedObjects\":[{}]}]},\"azureSqlDBSuitabilityDetails\":{\"azureSqlSku\":{\"azureSqlServiceTier\":\"HyperScale\",\"azureSqlComputeTier\":\"Unknown\",\"azureSqlHardwareGeneration\":\"Automatic\",\"storageMaxSizeInMB\":82.34454,\"predictedDataSizeInMB\":54.51052,\"predictedLogSizeInMB\":18.703657,\"cores\":753616806,\"azureSqlTargetType\":\"AzureSqlVirtualMachine\"},\"replicaAzureSqlSku\":[{\"azureSqlServiceTier\":\"Unknown\",\"azureSqlComputeTier\":\"Provisioned\",\"azureSqlHardwareGeneration\":\"Unknown\",\"storageMaxSizeInMB\":77.19659,\"predictedDataSizeInMB\":0.005275011,\"predictedLogSizeInMB\":1.6721785,\"cores\":1844678161,\"azureSqlTargetType\":\"AzureSqlVirtualMachine\"},{\"azureSqlServiceTier\":\"Automatic\",\"azureSqlComputeTier\":\"Automatic\",\"azureSqlHardwareGeneration\":\"Fsv2_series\",\"storageMaxSizeInMB\":80.447624,\"predictedDataSizeInMB\":10.910189,\"predictedLogSizeInMB\":37.55529,\"cores\":1473902358,\"azureSqlTargetType\":\"Unknown\"},{\"azureSqlServiceTier\":\"HyperScale\",\"azureSqlComputeTier\":\"Serverless\",\"azureSqlHardwareGeneration\":\"M_series\",\"storageMaxSizeInMB\":57.48646,\"predictedDataSizeInMB\":81.59941,\"predictedLogSizeInMB\":75.11977,\"cores\":1325876132,\"azureSqlTargetType\":\"AzureVirtualMachine\"}],\"sharedResources\":{\"sharedDataDisks\":[{},{},{}],\"sharedLogDisks\":[{}],\"sharedTempDbDisks\":[{},{},{}],\"numberOfMounts\":421840772,\"quorumWitness\":{\"quorumWitnessType\":\"Unknown\"}},\"monthlyComputeCost\":20.23537,\"monthlyStorageCost\":62.92355,\"costComponents\":[{\"name\":\"MonthlyAzureHybridCostSavings\",\"value\":96.248505,\"description\":\"kqlujqgira\"},{\"name\":\"MonthlyAzureHybridCostSavings\",\"value\":51.221985,\"description\":\"chpqvctsfaeuhww\"}],\"securitySuitability\":\"ConditionallySuitable\",\"shouldProvisionReplicas\":true,\"skuReplicationMode\":\"ActiveGeoReplication\",\"migrationGuidelines\":[{\"guidelineId\":\"asupmlppdpg\",\"migrationGuidelineCategory\":\"General\",\"migrationGuidelineContext\":[{},{}]},{\"guidelineId\":\"vbkarkptgon\",\"migrationGuidelineCategory\":\"AvailabilityGroupGuideline\",\"migrationGuidelineContext\":[{},{}]},{\"guidelineId\":\"yiysjqheni\",\"migrationGuidelineCategory\":\"Unknown\",\"migrationGuidelineContext\":[{}]},{\"guidelineId\":\"uba\",\"migrationGuidelineCategory\":\"FailoverCluterInstanceGuideLine\",\"migrationGuidelineContext\":[{},{}]}],\"recommendationReasonings\":[{\"reasoningId\":\"cseydz\",\"reasoningString\":\"mexmnvk\",\"reasoningCategory\":\"uwrxl\",\"contextParameters\":[{},{},{},{}]}],\"migrationTargetPlatform\":\"AzureSqlVirtualMachine\",\"suitability\":\"ReadinessUnknown\",\"migrationIssues\":[{\"issueId\":\"lhvdvmiphbeaeqj\",\"issueCategory\":\"Warning\",\"impactedObjects\":[{},{},{},{}]},{\"issueId\":\"lacro\",\"issueCategory\":\"Internal\",\"impactedObjects\":[{},{}]},{\"issueId\":\"erkeluxzsh\",\"issueCategory\":\"Warning\",\"impactedObjects\":[{},{}]},{\"issueId\":\"uzudlevzskejcg\",\"issueCategory\":\"Internal\",\"impactedObjects\":[{},{},{}]}]},\"azureSqlVMSuitabilityDetails\":{\"azureSqlSku\":{\"virtualMachineSize\":{\"azureVmFamily\":\"Ebsv5_series\",\"cores\":1663628881,\"azureSkuName\":\"Standard_M64ms_v2\",\"availableCores\":977354992,\"maxNetworkInterfaces\":30369579},\"dataDiskSizes\":[{},{},{},{}],\"logDiskSizes\":[{},{},{},{}],\"azureSqlTargetType\":\"Recommended\"},\"replicaAzureSqlSku\":[{\"virtualMachineSize\":{},\"dataDiskSizes\":[{},{},{}],\"logDiskSizes\":[{},{}],\"azureSqlTargetType\":\"AzureVirtualMachine\"}],\"sharedResources\":{\"sharedDataDisks\":[{},{}],\"sharedLogDisks\":[{}],\"sharedTempDbDisks\":[{},{},{}],\"numberOfMounts\":1723389232,\"quorumWitness\":{\"quorumWitnessType\":\"Disk\"}},\"monthlyComputeCost\":66.83869,\"monthlyStorageCost\":1.153487,\"costComponents\":[{\"name\":\"MonthlySecurityCost\",\"value\":36.31253,\"description\":\"aonzvaj\"},{\"name\":\"MonthlyPremiumV2StorageCost\",\"value\":39.682243,\"description\":\"demdidackzi\"},{\"name\":\"MonthlyPremiumV2StorageCost\",\"value\":92.795334,\"description\":\"damisvpztdi\"}],\"securitySuitability\":\"NotSuitable\",\"shouldProvisionReplicas\":true,\"skuReplicationMode\":\"FailoverGroupInstance\",\"migrationGuidelines\":[{\"guidelineId\":\"pjfojiunrls\",\"migrationGuidelineCategory\":\"FailoverCluterInstanceGuideLine\",\"migrationGuidelineContext\":[{}]}],\"recommendationReasonings\":[{\"reasoningId\":\"dtoiboancdrcoanv\",\"reasoningString\":\"ldxonckb\",\"reasoningCategory\":\"blfxlupibaqzi\",\"contextParameters\":[{},{}]}],\"migrationTargetPlatform\":\"AzureVirtualMachine\",\"suitability\":\"ConditionallySuitable\",\"migrationIssues\":[{\"issueId\":\"wwbogvgfklqiy\",\"issueCategory\":\"Internal\",\"impactedObjects\":[{}]},{\"issueId\":\"lsb\",\"issueCategory\":\"Internal\",\"impactedObjects\":[{},{},{},{}]}]},\"assessedSqlEntityArmId\":\"kzx\",\"isClustered\":false,\"isHighAvailabilityEnabled\":false,\"sqlEdition\":\"vlrdsmovpi\",\"sqlVersion\":\"ndnoxaxnrqaq\",\"sizingCriterion\":\"PerformanceBased\"},\"id\":\"dxolousdv\",\"name\":\"g\",\"type\":\"tqm\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response = manager.assessedSqlRecommendedEntityOperations() + .listBySqlAssessmentV2("hqodv", "gcnbhcbmjk", "ti", "n", "ynts", 695243142, "mfmeftvhkmoo", 1369210689, + com.azure.core.util.Context.NONE); + + Assertions.assertEquals("kzx", response.iterator().next().properties().assessedSqlEntityArmId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentOptionsInnerTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentOptionsInnerTests.java new file mode 100644 index 000000000000..e2347e4e8d7e --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentOptionsInnerTests.java @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentOptionsInner; +import com.azure.resourcemanager.migration.assessment.models.AssessmentOptionsProperties; + +public final class AssessmentOptionsInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AssessmentOptionsInner model = BinaryData.fromString( + "{\"properties\":{\"vmFamilies\":[{\"familyName\":\"mpxttdbhrbnlankx\",\"targetLocations\":[\"k\",\"bhenbtkcxywnyt\",\"rsyn\",\"qidybyx\"],\"category\":[\"clha\",\"xdbabphlwr\",\"lfktsths\",\"cocmnyyaztt\"]},{\"familyName\":\"wwrq\",\"targetLocations\":[\"dckzywbiexz\",\"eyueaxibxujwb\",\"qwalmuzyoxaepd\",\"zjancuxr\"],\"category\":[\"bavxbniwdjswzt\",\"dbpgnxytxhp\",\"xbzpfzab\"]}],\"reservedInstanceVmFamilies\":[\"uhxwtctyqiklbbov\"],\"reservedInstanceSupportedLocations\":[\"zbhvgyuguosv\",\"kfssxqukkf\",\"l\"],\"reservedInstanceSupportedCurrencies\":[\"sxnkjzkdeslpvlo\",\"wiyighxpkdw\",\"baiuebbaumny\",\"upedeojnabckhs\"],\"reservedInstanceSupportedOffers\":[\"psiebtfhvpes\",\"pskrdqmh\",\"jdhtldwkyzxu\",\"tkncwsc\"],\"ultraDiskVmFamilies\":[{\"familyName\":\"xotogtwrupqsxv\",\"targetLocations\":[\"cykvceo\"]},{\"familyName\":\"ilovnot\",\"targetLocations\":[\"fcnj\"]},{\"familyName\":\"cn\",\"targetLocations\":[\"bttk\",\"h\",\"wpn\"]},{\"familyName\":\"t\",\"targetLocations\":[\"ermclfplphoxuscr\",\"abgy\"]}],\"premiumDiskVmFamilies\":[\"bjtazqugxywpmu\"],\"savingsPlanVmFamilies\":[\"jzwf\"],\"savingsPlanSupportedLocations\":[\"ujidsuyono\"]},\"id\":\"laocqxtccmg\",\"name\":\"udxytlmoyrx\",\"type\":\"wfudwpzntxhdzhl\"}") + .toObject(AssessmentOptionsInner.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AssessmentOptionsInner model = new AssessmentOptionsInner().withProperties(new AssessmentOptionsProperties()); + model = BinaryData.fromObject(model).toObject(AssessmentOptionsInner.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentOptionsListResultTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentOptionsListResultTests.java new file mode 100644 index 000000000000..7482e1ef9178 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentOptionsListResultTests.java @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentOptionsInner; +import com.azure.resourcemanager.migration.assessment.models.AssessmentOptionsListResult; +import com.azure.resourcemanager.migration.assessment.models.AssessmentOptionsProperties; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class AssessmentOptionsListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AssessmentOptionsListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"vmFamilies\":[{\"familyName\":\"ljjgpbtoqcjmkl\",\"targetLocations\":[\"bqidtqaj\",\"yulpkudjkr\"],\"category\":[\"bzhfepgzgqexz\",\"ocxscpaierhhbcs\"]}],\"reservedInstanceVmFamilies\":[\"mmajtjaodx\",\"bnbdxkqpxokajion\",\"imexgstxgcpodgma\"],\"reservedInstanceSupportedLocations\":[\"mvdjwzrlovmc\"],\"reservedInstanceSupportedCurrencies\":[\"ijcoejctb\",\"aqsqsycbkbfk\"],\"reservedInstanceSupportedOffers\":[\"dkexxppofm\",\"axcfjpgddtocjjx\"],\"ultraDiskVmFamilies\":[{\"familyName\":\"o\",\"targetLocations\":[\"hd\",\"xibqeojnx\",\"bzv\",\"dntwndeicbtw\"]},{\"familyName\":\"zao\",\"targetLocations\":[\"hrhcffcyddglmjth\",\"qkwpyeicxmqc\",\"wqvhkhixuigdt\",\"pbobjo\"]},{\"familyName\":\"m\",\"targetLocations\":[\"a\"]}],\"premiumDiskVmFamilies\":[\"hrzayvvtpgvdf\",\"iotkftutqxl\",\"gxlefgugnxkrxd\"],\"savingsPlanVmFamilies\":[\"dt\"],\"savingsPlanSupportedLocations\":[\"rvqdra\",\"hjybigehoqfbo\"]},\"id\":\"kanyktzlcuiywg\",\"name\":\"ywgndrv\",\"type\":\"nhzgpphrcgyn\"},{\"properties\":{\"vmFamilies\":[{\"familyName\":\"cfvmmco\",\"targetLocations\":[\"xlzevgbmqjqabcy\",\"mivkwlzuvcc\",\"wnfnbacf\"],\"category\":[\"l\",\"bxetqgtzxdpn\",\"bqqwxrj\",\"eallnwsubisnj\"]}],\"reservedInstanceVmFamilies\":[\"mngnzscxaqw\"],\"reservedInstanceSupportedLocations\":[\"hcbonqvpkvlr\",\"njeaseipheofloke\",\"y\",\"enjbdlwtgrhp\"],\"reservedInstanceSupportedCurrencies\":[\"jumasx\"],\"reservedInstanceSupportedOffers\":[\"pqyegualhbxxh\",\"jj\"],\"ultraDiskVmFamilies\":[{\"familyName\":\"udgwdslfho\",\"targetLocations\":[\"cynpwlbjnp\"]}],\"premiumDiskVmFamilies\":[\"ftadehxnltyfs\",\"ppusuesnzwdejba\"],\"savingsPlanVmFamilies\":[\"xzdmohctb\",\"vudwx\",\"ndnvo\",\"gujjugwdkcglh\"],\"savingsPlanSupportedLocations\":[\"zj\",\"yggdtjixh\"]},\"id\":\"uofqwe\",\"name\":\"kh\",\"type\":\"enevfyexfwhybci\"},{\"properties\":{\"vmFamilies\":[{\"familyName\":\"c\",\"targetLocations\":[\"ynnaam\",\"ectehf\",\"qsc\",\"eypvhezrkg\"],\"category\":[\"jrefovgmkqsle\"]},{\"familyName\":\"vxyqjpkcattpngjc\",\"targetLocations\":[\"zsqpjhvmdajvny\",\"ounqecano\",\"eupfhyhltrpm\"],\"category\":[\"mcmatuokthfuiu\",\"odsfcpkvxodpuozm\",\"zydagfuaxbezyiuo\",\"ktwh\"]},{\"familyName\":\"xw\",\"targetLocations\":[\"q\",\"mbsureximo\"],\"category\":[\"cfsf\"]}],\"reservedInstanceVmFamilies\":[\"mddystkiiux\",\"qyud\"],\"reservedInstanceSupportedLocations\":[\"rq\",\"b\",\"oczvy\",\"fqrvkdvjsllrmvvd\"],\"reservedInstanceSupportedCurrencies\":[\"t\",\"pnpulexxbczwtru\"],\"reservedInstanceSupportedOffers\":[\"zb\",\"j\",\"sovmyokacspkwl\"],\"ultraDiskVmFamilies\":[{\"familyName\":\"bpxjmfl\",\"targetLocations\":[\"nchrkcciww\",\"juqk\",\"rsa\"]},{\"familyName\":\"wkuofoskghsauu\",\"targetLocations\":[\"mvxi\",\"duugidyjr\"]},{\"familyName\":\"byao\",\"targetLocations\":[\"xc\"]},{\"familyName\":\"npc\",\"targetLocations\":[\"cohslkev\",\"eggzfb\",\"hfmvfaxkffe\"]}],\"premiumDiskVmFamilies\":[\"hl\"],\"savingsPlanVmFamilies\":[\"zy\"],\"savingsPlanSupportedLocations\":[\"xmzsbbzogg\",\"grxwbu\",\"vjxxjnsp\",\"dptkoenkouk\"]},\"id\":\"udwtiukbl\",\"name\":\"ngkpocipazy\",\"type\":\"o\"},{\"properties\":{\"vmFamilies\":[{\"familyName\":\"jnpiucgyg\",\"targetLocations\":[\"zntypmrb\",\"izcdrqjsd\"],\"category\":[\"nfyhx\",\"eoejzic\",\"ifsjttgzfbishcb\",\"hajdeyeamdpha\"]}],\"reservedInstanceVmFamilies\":[\"pbuxwgipwhon\",\"wkgshwa\",\"kix\",\"bin\"],\"reservedInstanceSupportedLocations\":[\"uttmrywnuzoqft\"],\"reservedInstanceSupportedCurrencies\":[\"zrnkcqvyxlwh\",\"lsicohoqqnwv\",\"ryavwhheunmmqh\",\"yxzk\"],\"reservedInstanceSupportedOffers\":[\"cukoklyaxuconu\",\"szfkbe\",\"pewr\"],\"ultraDiskVmFamilies\":[{\"familyName\":\"vvjektcxsenhwlrs\",\"targetLocations\":[\"zpwv\",\"qdqgbi\",\"ylihkaetckt\",\"fcivfsnkym\"]},{\"familyName\":\"tqhjfbebrjcx\",\"targetLocations\":[\"uwutttxfvjrbi\",\"phxepcyvahf\",\"ljkyqxjvuuj\"]},{\"familyName\":\"idokgjlj\",\"targetLocations\":[\"gvcl\",\"bgsncghkjeszzhb\"]},{\"familyName\":\"htxfvgxbfsmxnehm\",\"targetLocations\":[\"cxgod\"]}],\"premiumDiskVmFamilies\":[\"qkkrb\",\"pukgriwflzlfb\"],\"savingsPlanVmFamilies\":[\"uzycispnqza\"],\"savingsPlanSupportedLocations\":[\"kbrpyydhibnuq\",\"kpikadrgvt\"]},\"id\":\"gnbuy\",\"name\":\"hijggme\",\"type\":\"fsiarbutr\"}],\"nextLink\":\"pnazzm\"}") + .toObject(AssessmentOptionsListResult.class); + Assertions.assertEquals("pnazzm", model.nextLink()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AssessmentOptionsListResult model + = new AssessmentOptionsListResult() + .withValue(Arrays.asList(new AssessmentOptionsInner().withProperties(new AssessmentOptionsProperties()), + new AssessmentOptionsInner().withProperties(new AssessmentOptionsProperties()), + new AssessmentOptionsInner().withProperties(new AssessmentOptionsProperties()), + new AssessmentOptionsInner().withProperties(new AssessmentOptionsProperties()))) + .withNextLink("pnazzm"); + model = BinaryData.fromObject(model).toObject(AssessmentOptionsListResult.class); + Assertions.assertEquals("pnazzm", model.nextLink()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentOptionsOperationsGetWithResponseMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentOptionsOperationsGetWithResponseMockTests.java new file mode 100644 index 000000000000..23bb52e33793 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentOptionsOperationsGetWithResponseMockTests.java @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.AssessmentOptions; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class AssessmentOptionsOperationsGetWithResponseMockTests { + @Test + public void testGetWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"vmFamilies\":[{\"familyName\":\"haokgkskjiv\",\"targetLocations\":[\"hajqfuk\",\"eexpgeumi\"],\"category\":[\"uitrdexyiono\"]},{\"familyName\":\"inbd\",\"targetLocations\":[\"xcwqqrsmpc\"],\"category\":[\"rtugavbzbcyks\",\"vm\"]},{\"familyName\":\"gd\",\"targetLocations\":[\"fcmkr\",\"tsjcwjjxs\",\"mb\"],\"category\":[\"ifdxkecifhocjxw\",\"loozrvt\",\"vcmuf\",\"nlcpxxviry\"]}],\"reservedInstanceVmFamilies\":[\"gjgvr\",\"uvp\",\"gglpmcrdcuelj\"],\"reservedInstanceSupportedLocations\":[\"hxmfqryarvsxzqb\"],\"reservedInstanceSupportedCurrencies\":[\"jkayspthzo\",\"ubtlmjtg\"],\"reservedInstanceSupportedOffers\":[\"oskkfmk\",\"fdjxyxg\",\"kkqvjcteoedl\",\"slskkz\"],\"ultraDiskVmFamilies\":[{\"familyName\":\"nzdpvoco\",\"targetLocations\":[\"cnabxzf\",\"nggy\"]},{\"familyName\":\"xv\",\"targetLocations\":[\"mhi\",\"zkwwwn\",\"knrzdajlskzpt\"]},{\"familyName\":\"ulweucyrth\",\"targetLocations\":[\"ehmcgcje\",\"n\",\"ehokamvfej\",\"qnttmbq\"]},{\"familyName\":\"bzfivfok\",\"targetLocations\":[\"thhzagjfw\",\"yrl\",\"g\"]}],\"premiumDiskVmFamilies\":[\"zejgvkv\",\"baqszllrzlsmmd\",\"gmihzpimcqr\",\"nxtminklog\"],\"savingsPlanVmFamilies\":[\"tzarhzvqnsqktc\"],\"savingsPlanSupportedLocations\":[\"wzzoslpk\",\"btglwkzpgajsqj\",\"emqbmfuvqarwzxuq\"]},\"id\":\"bluimmbw\",\"name\":\"sfgtdmbvxekra\",\"type\":\"k\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + AssessmentOptions response = manager.assessmentOptionsOperations() + .getWithResponse("ypefcpczshnuqnda", "zupfkhuytuszxhm", "vtvegwqiukvzw", com.azure.core.util.Context.NONE) + .getValue(); + + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentOptionsOperationsListByAssessmentProjectMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentOptionsOperationsListByAssessmentProjectMockTests.java new file mode 100644 index 000000000000..832cff36f2a5 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentOptionsOperationsListByAssessmentProjectMockTests.java @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.AssessmentOptions; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class AssessmentOptionsOperationsListByAssessmentProjectMockTests { + @Test + public void testListByAssessmentProject() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"vmFamilies\":[{\"familyName\":\"pjptn\",\"targetLocations\":[\"hrsidq\",\"xlbtp\",\"kft\"],\"category\":[\"twmykyut\"]},{\"familyName\":\"mdwmf\",\"targetLocations\":[\"y\",\"vjqdvdwkq\",\"ldrlefgnaavua\",\"n\"],\"category\":[\"aou\",\"n\",\"dc\"]},{\"familyName\":\"hspfefyihd\",\"targetLocations\":[\"uyld\",\"hmtybkcgsuthhll\",\"mwynefxexlfciatx\"],\"category\":[\"rl\",\"mdskjhhxdlajfoxc\",\"scv\"]}],\"reservedInstanceVmFamilies\":[\"lh\",\"a\",\"krmukmyjmkxett\"],\"reservedInstanceSupportedLocations\":[\"ojfkq\",\"dnqtoqxjhqx\",\"s\"],\"reservedInstanceSupportedCurrencies\":[\"kbtn\",\"l\",\"ngldmbiipsn\"],\"reservedInstanceSupportedOffers\":[\"lqkznxhhllxricct\"],\"ultraDiskVmFamilies\":[{\"familyName\":\"qqoajxeiyglesrw\",\"targetLocations\":[\"xhdctrceqnk\"]},{\"familyName\":\"upobehdmljz\",\"targetLocations\":[\"umepjpbibn\"]},{\"familyName\":\"phepifexleqirc\",\"targetLocations\":[\"ly\"]}],\"premiumDiskVmFamilies\":[\"x\",\"rpjl\"],\"savingsPlanVmFamilies\":[\"uod\",\"cpunettepdjx\",\"eskoy\"],\"savingsPlanSupportedLocations\":[\"ylpckaewsedv\",\"skwxe\"]},\"id\":\"phrgfnzhctm\",\"name\":\"tsghpbcbcp\",\"type\":\"arpzeqacdldtzm\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response = manager.assessmentOptionsOperations() + .listByAssessmentProject("fv", "n", com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentOptionsPropertiesTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentOptionsPropertiesTests.java new file mode 100644 index 000000000000..ccdd5df6c36c --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentOptionsPropertiesTests.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.AssessmentOptionsProperties; + +public final class AssessmentOptionsPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AssessmentOptionsProperties model = BinaryData.fromString( + "{\"vmFamilies\":[{\"familyName\":\"hckfrlhrx\",\"targetLocations\":[\"yvpycanuzbpzk\"],\"category\":[\"uwbc\",\"nwbmeh\",\"seyvj\"]},{\"familyName\":\"rts\",\"targetLocations\":[\"pkdeemaofmxagkvt\",\"elmqk\"],\"category\":[\"hvljuahaquh\",\"dhmdua\",\"aex\"]},{\"familyName\":\"vfadmws\",\"targetLocations\":[\"gvxp\"],\"category\":[\"mzlfmisgwb\",\"b\"]}],\"reservedInstanceVmFamilies\":[\"dawkzbali\",\"urqhaka\",\"hashsfwxosow\",\"xcug\"],\"reservedInstanceSupportedLocations\":[\"ooxdjebwpuc\",\"wfvovbv\",\"euecivyhzceuoj\"],\"reservedInstanceSupportedCurrencies\":[\"wjue\"],\"reservedInstanceSupportedOffers\":[\"wmcdytdxwi\"],\"ultraDiskVmFamilies\":[{\"familyName\":\"jawgqwg\",\"targetLocations\":[\"isk\"]},{\"familyName\":\"bkpyc\",\"targetLocations\":[\"wndnhj\"]},{\"familyName\":\"uwhvylwzbtdhxujz\",\"targetLocations\":[\"pow\",\"wpr\"]}],\"premiumDiskVmFamilies\":[\"veual\"],\"savingsPlanVmFamilies\":[\"mkh\"],\"savingsPlanSupportedLocations\":[\"bbcswsrtjri\"]}") + .toObject(AssessmentOptionsProperties.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AssessmentOptionsProperties model = new AssessmentOptionsProperties(); + model = BinaryData.fromObject(model).toObject(AssessmentOptionsProperties.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectInnerTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectInnerTests.java new file mode 100644 index 000000000000..71446b938ad8 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectInnerTests.java @@ -0,0 +1,67 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentProjectInner; +import com.azure.resourcemanager.migration.assessment.models.ProjectProperties; +import com.azure.resourcemanager.migration.assessment.models.ProjectStatus; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Assertions; + +public final class AssessmentProjectInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AssessmentProjectInner model = BinaryData.fromString( + "{\"properties\":{\"createdTimestamp\":\"2021-11-09T02:37:57Z\",\"updatedTimestamp\":\"2021-01-31T22:20:23Z\",\"serviceEndpoint\":\"aolthqtrg\",\"assessmentSolutionId\":\"bpf\",\"projectStatus\":\"Active\",\"customerWorkspaceId\":\"n\",\"customerWorkspaceLocation\":\"v\",\"publicNetworkAccess\":\"jrwzox\",\"privateEndpointConnections\":[{\"properties\":{\"groupIds\":[\"luwfzitonpeqfpjk\",\"lxofpdvhpfxxypin\",\"nmayhuybb\",\"podepoo\"],\"privateEndpoint\":{\"id\":\"uvamiheognarxzxt\"},\"privateLinkServiceConnectionState\":{\"status\":\"Rejected\",\"description\":\"usivye\",\"actionsRequired\":\"ciqihnhung\"},\"provisioningState\":\"Creating\"},\"id\":\"rnfygxgispem\",\"name\":\"tzfkufubl\",\"type\":\"ofx\"},{\"properties\":{\"groupIds\":[\"jaeq\",\"hqjbasvmsmj\"],\"privateEndpoint\":{\"id\":\"ngsntnbybk\"},\"privateLinkServiceConnectionState\":{\"status\":\"Rejected\",\"description\":\"rwclxxwrljdo\",\"actionsRequired\":\"kcqvkocrc\"},\"provisioningState\":\"Succeeded\"},\"id\":\"tnhxbn\",\"name\":\"biksq\",\"type\":\"gls\"}],\"customerStorageAccountArmId\":\"inqpjwnzll\",\"provisioningState\":\"Updating\"},\"location\":\"pee\",\"tags\":{\"uujitcjc\":\"gxsabkyq\",\"d\":\"dzevndhkrw\"},\"id\":\"ppdsbdkvwrwj\",\"name\":\"eusnhutj\",\"type\":\"ltmrldh\"}") + .toObject(AssessmentProjectInner.class); + Assertions.assertEquals("pee", model.location()); + Assertions.assertEquals("gxsabkyq", model.tags().get("uujitcjc")); + Assertions.assertEquals(ProvisioningState.UPDATING, model.properties().provisioningState()); + Assertions.assertEquals("bpf", model.properties().assessmentSolutionId()); + Assertions.assertEquals(ProjectStatus.ACTIVE, model.properties().projectStatus()); + Assertions.assertEquals("n", model.properties().customerWorkspaceId()); + Assertions.assertEquals("v", model.properties().customerWorkspaceLocation()); + Assertions.assertEquals("jrwzox", model.properties().publicNetworkAccess()); + Assertions.assertEquals("inqpjwnzll", model.properties().customerStorageAccountArmId()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AssessmentProjectInner model = new AssessmentProjectInner().withLocation("pee") + .withTags(mapOf("uujitcjc", "gxsabkyq", "d", "dzevndhkrw")) + .withProperties(new ProjectProperties().withProvisioningState(ProvisioningState.UPDATING) + .withAssessmentSolutionId("bpf") + .withProjectStatus(ProjectStatus.ACTIVE) + .withCustomerWorkspaceId("n") + .withCustomerWorkspaceLocation("v") + .withPublicNetworkAccess("jrwzox") + .withCustomerStorageAccountArmId("inqpjwnzll")); + model = BinaryData.fromObject(model).toObject(AssessmentProjectInner.class); + Assertions.assertEquals("pee", model.location()); + Assertions.assertEquals("gxsabkyq", model.tags().get("uujitcjc")); + Assertions.assertEquals(ProvisioningState.UPDATING, model.properties().provisioningState()); + Assertions.assertEquals("bpf", model.properties().assessmentSolutionId()); + Assertions.assertEquals(ProjectStatus.ACTIVE, model.properties().projectStatus()); + Assertions.assertEquals("n", model.properties().customerWorkspaceId()); + Assertions.assertEquals("v", model.properties().customerWorkspaceLocation()); + Assertions.assertEquals("jrwzox", model.properties().publicNetworkAccess()); + Assertions.assertEquals("inqpjwnzll", model.properties().customerStorageAccountArmId()); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectListResultTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectListResultTests.java new file mode 100644 index 000000000000..fee52fa8e190 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectListResultTests.java @@ -0,0 +1,74 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentProjectInner; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProjectListResult; +import com.azure.resourcemanager.migration.assessment.models.ProjectProperties; +import com.azure.resourcemanager.migration.assessment.models.ProjectStatus; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Assertions; + +public final class AssessmentProjectListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AssessmentProjectListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"createdTimestamp\":\"2021-11-25T18:32:18Z\",\"updatedTimestamp\":\"2021-08-11T05:57:13Z\",\"serviceEndpoint\":\"qhabifpikxwcz\",\"assessmentSolutionId\":\"scnpqxuhivy\",\"projectStatus\":\"Inactive\",\"customerWorkspaceId\":\"b\",\"customerWorkspaceLocation\":\"rkxvdum\",\"publicNetworkAccess\":\"rtfw\",\"privateEndpointConnections\":[{\"properties\":{\"privateLinkServiceConnectionState\":{}},\"id\":\"audccsnhs\",\"name\":\"cnyejhkryhtnapcz\",\"type\":\"lokjyemkk\"}],\"customerStorageAccountArmId\":\"ipjoxzjnchgejs\",\"provisioningState\":\"Failed\"},\"location\":\"ailzydehojwyahu\",\"tags\":{\"wixjsprozvcp\":\"pmqnja\",\"atscmd\":\"tegjvwmf\",\"zkrwfn\":\"pjhulsuuvmkj\",\"lwejdpv\":\"iodjp\"},\"id\":\"ryo\",\"name\":\"psoacctazakljl\",\"type\":\"hbcryffdfdosyge\"}],\"nextLink\":\"aojakhmsbzjhcrz\"}") + .toObject(AssessmentProjectListResult.class); + Assertions.assertEquals("ailzydehojwyahu", model.value().get(0).location()); + Assertions.assertEquals("pmqnja", model.value().get(0).tags().get("wixjsprozvcp")); + Assertions.assertEquals(ProvisioningState.FAILED, model.value().get(0).properties().provisioningState()); + Assertions.assertEquals("scnpqxuhivy", model.value().get(0).properties().assessmentSolutionId()); + Assertions.assertEquals(ProjectStatus.INACTIVE, model.value().get(0).properties().projectStatus()); + Assertions.assertEquals("b", model.value().get(0).properties().customerWorkspaceId()); + Assertions.assertEquals("rkxvdum", model.value().get(0).properties().customerWorkspaceLocation()); + Assertions.assertEquals("rtfw", model.value().get(0).properties().publicNetworkAccess()); + Assertions.assertEquals("ipjoxzjnchgejs", model.value().get(0).properties().customerStorageAccountArmId()); + Assertions.assertEquals("aojakhmsbzjhcrz", model.nextLink()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AssessmentProjectListResult model = new AssessmentProjectListResult() + .withValue(Arrays.asList(new AssessmentProjectInner().withLocation("ailzydehojwyahu") + .withTags( + mapOf("wixjsprozvcp", "pmqnja", "atscmd", "tegjvwmf", "zkrwfn", "pjhulsuuvmkj", "lwejdpv", "iodjp")) + .withProperties(new ProjectProperties().withProvisioningState(ProvisioningState.FAILED) + .withAssessmentSolutionId("scnpqxuhivy") + .withProjectStatus(ProjectStatus.INACTIVE) + .withCustomerWorkspaceId("b") + .withCustomerWorkspaceLocation("rkxvdum") + .withPublicNetworkAccess("rtfw") + .withCustomerStorageAccountArmId("ipjoxzjnchgejs")))) + .withNextLink("aojakhmsbzjhcrz"); + model = BinaryData.fromObject(model).toObject(AssessmentProjectListResult.class); + Assertions.assertEquals("ailzydehojwyahu", model.value().get(0).location()); + Assertions.assertEquals("pmqnja", model.value().get(0).tags().get("wixjsprozvcp")); + Assertions.assertEquals(ProvisioningState.FAILED, model.value().get(0).properties().provisioningState()); + Assertions.assertEquals("scnpqxuhivy", model.value().get(0).properties().assessmentSolutionId()); + Assertions.assertEquals(ProjectStatus.INACTIVE, model.value().get(0).properties().projectStatus()); + Assertions.assertEquals("b", model.value().get(0).properties().customerWorkspaceId()); + Assertions.assertEquals("rkxvdum", model.value().get(0).properties().customerWorkspaceLocation()); + Assertions.assertEquals("rtfw", model.value().get(0).properties().publicNetworkAccess()); + Assertions.assertEquals("ipjoxzjnchgejs", model.value().get(0).properties().customerStorageAccountArmId()); + Assertions.assertEquals("aojakhmsbzjhcrz", model.nextLink()); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectSummaryInnerTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectSummaryInnerTests.java new file mode 100644 index 000000000000..a66571246931 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectSummaryInnerTests.java @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentProjectSummaryInner; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProjectSummaryProperties; + +public final class AssessmentProjectSummaryInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AssessmentProjectSummaryInner model = BinaryData.fromString( + "{\"properties\":{\"errorSummaryAffectedEntities\":[{\"assessmentType\":\"Unknown\",\"count\":561767008},{\"assessmentType\":\"WebAppAssessment\",\"count\":1999784595},{\"assessmentType\":\"MachineAssessment\",\"count\":1630921405},{\"assessmentType\":\"Unknown\",\"count\":1509139368}],\"numberOfPrivateEndpointConnections\":1650902966,\"numberOfGroups\":512176401,\"numberOfMachines\":562062198,\"numberOfImportMachines\":2048897127,\"numberOfAssessments\":1477121585,\"lastAssessmentTimestamp\":\"2021-07-10T00:46:33Z\"},\"id\":\"oqmavnwqjwgo\",\"name\":\"nlejjjkxybwf\",\"type\":\"bkjbz\"}") + .toObject(AssessmentProjectSummaryInner.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AssessmentProjectSummaryInner model + = new AssessmentProjectSummaryInner().withProperties(new AssessmentProjectSummaryProperties()); + model = BinaryData.fromObject(model).toObject(AssessmentProjectSummaryInner.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectSummaryListResultTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectSummaryListResultTests.java new file mode 100644 index 000000000000..762c6b535cc0 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectSummaryListResultTests.java @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AssessmentProjectSummaryInner; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProjectSummaryListResult; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProjectSummaryProperties; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class AssessmentProjectSummaryListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AssessmentProjectSummaryListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"errorSummaryAffectedEntities\":[{\"assessmentType\":\"WebAppAssessment\",\"count\":1760515250},{\"assessmentType\":\"MachineAssessment\",\"count\":855475519},{\"assessmentType\":\"AvsAssessment\",\"count\":44359984},{\"assessmentType\":\"SqlAssessment\",\"count\":1790320918}],\"numberOfPrivateEndpointConnections\":1654088054,\"numberOfGroups\":43115717,\"numberOfMachines\":1661164676,\"numberOfImportMachines\":1777294883,\"numberOfAssessments\":1206039468,\"lastAssessmentTimestamp\":\"2021-08-24T15:13:37Z\"},\"id\":\"essmzhhku\",\"name\":\"ip\",\"type\":\"dqq\"},{\"properties\":{\"errorSummaryAffectedEntities\":[{\"assessmentType\":\"WebAppAssessment\",\"count\":1539234550}],\"numberOfPrivateEndpointConnections\":205688026,\"numberOfGroups\":863397586,\"numberOfMachines\":1828874744,\"numberOfImportMachines\":759827804,\"numberOfAssessments\":218702918,\"lastAssessmentTimestamp\":\"2021-01-24T19:13:48Z\"},\"id\":\"a\",\"name\":\"mxhzzysevus\",\"type\":\"ivzrrryveimipsk\"},{\"properties\":{\"errorSummaryAffectedEntities\":[{\"assessmentType\":\"Unknown\",\"count\":1556384271},{\"assessmentType\":\"WebAppAssessment\",\"count\":1460525745},{\"assessmentType\":\"SqlAssessment\",\"count\":754737870}],\"numberOfPrivateEndpointConnections\":1587694223,\"numberOfGroups\":1055282303,\"numberOfMachines\":1296722433,\"numberOfImportMachines\":1064338012,\"numberOfAssessments\":422626057,\"lastAssessmentTimestamp\":\"2021-05-14T23:41:37Z\"},\"id\":\"smjtgrqgdg\",\"name\":\"kileplkcsmknhwtb\",\"type\":\"aedorvvmqf\"},{\"properties\":{\"errorSummaryAffectedEntities\":[{\"assessmentType\":\"WebAppAssessment\",\"count\":1086162181}],\"numberOfPrivateEndpointConnections\":943881137,\"numberOfGroups\":833434328,\"numberOfMachines\":1369032842,\"numberOfImportMachines\":1457349123,\"numberOfAssessments\":1726761587,\"lastAssessmentTimestamp\":\"2021-08-22T08:57:03Z\"},\"id\":\"exjddvjsaqwot\",\"name\":\"mwllcolsrsxapt\",\"type\":\"f\"}],\"nextLink\":\"xcgjokjljnhvlq\"}") + .toObject(AssessmentProjectSummaryListResult.class); + Assertions.assertEquals("xcgjokjljnhvlq", model.nextLink()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AssessmentProjectSummaryListResult model = new AssessmentProjectSummaryListResult() + .withValue(Arrays.asList( + new AssessmentProjectSummaryInner().withProperties(new AssessmentProjectSummaryProperties()), + new AssessmentProjectSummaryInner().withProperties(new AssessmentProjectSummaryProperties()), + new AssessmentProjectSummaryInner().withProperties(new AssessmentProjectSummaryProperties()), + new AssessmentProjectSummaryInner().withProperties(new AssessmentProjectSummaryProperties()))) + .withNextLink("xcgjokjljnhvlq"); + model = BinaryData.fromObject(model).toObject(AssessmentProjectSummaryListResult.class); + Assertions.assertEquals("xcgjokjljnhvlq", model.nextLink()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectSummaryOperationsGetWithResponseMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectSummaryOperationsGetWithResponseMockTests.java new file mode 100644 index 000000000000..13a58db43faa --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectSummaryOperationsGetWithResponseMockTests.java @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProjectSummary; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class AssessmentProjectSummaryOperationsGetWithResponseMockTests { + @Test + public void testGetWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"errorSummaryAffectedEntities\":[{\"assessmentType\":\"WebAppAssessment\",\"count\":895776301},{\"assessmentType\":\"WebAppAssessment\",\"count\":1257209908}],\"numberOfPrivateEndpointConnections\":1819948805,\"numberOfGroups\":678358747,\"numberOfMachines\":1768698237,\"numberOfImportMachines\":817823208,\"numberOfAssessments\":161346417,\"lastAssessmentTimestamp\":\"2021-02-06T01:10:03Z\"},\"id\":\"ddwvmqxiyooky\",\"name\":\"ozkbnzxbypfq\",\"type\":\"gaixwrgrkkd\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + AssessmentProjectSummary response = manager.assessmentProjectSummaryOperations() + .getWithResponse("zxpxhn", "lslekcttgzkj", "yqpdwadeghztld", com.azure.core.util.Context.NONE) + .getValue(); + + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectSummaryOperationsListByAssessmentProjectMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectSummaryOperationsListByAssessmentProjectMockTests.java new file mode 100644 index 000000000000..e8642cd87c41 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectSummaryOperationsListByAssessmentProjectMockTests.java @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProjectSummary; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class AssessmentProjectSummaryOperationsListByAssessmentProjectMockTests { + @Test + public void testListByAssessmentProject() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"errorSummaryAffectedEntities\":[{\"assessmentType\":\"AvsAssessment\",\"count\":584772284}],\"numberOfPrivateEndpointConnections\":1957416812,\"numberOfGroups\":1553900618,\"numberOfMachines\":1951216053,\"numberOfImportMachines\":986123391,\"numberOfAssessments\":1439738026,\"lastAssessmentTimestamp\":\"2021-07-21T20:09:12Z\"},\"id\":\"qizjv\",\"name\":\"pwooajeyyj\",\"type\":\"jjx\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response = manager.assessmentProjectSummaryOperations() + .listByAssessmentProject("luqrojadhfztlray", "rkgzkyhudbkuw", com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectSummaryPropertiesTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectSummaryPropertiesTests.java new file mode 100644 index 000000000000..b209527c8040 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectSummaryPropertiesTests.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProjectSummaryProperties; + +public final class AssessmentProjectSummaryPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AssessmentProjectSummaryProperties model = BinaryData.fromString( + "{\"errorSummaryAffectedEntities\":[{\"assessmentType\":\"WebAppAssessment\",\"count\":880729716}],\"numberOfPrivateEndpointConnections\":1891353200,\"numberOfGroups\":1541050102,\"numberOfMachines\":605317874,\"numberOfImportMachines\":491994414,\"numberOfAssessments\":811449935,\"lastAssessmentTimestamp\":\"2021-03-02T20:18:48Z\"}") + .toObject(AssessmentProjectSummaryProperties.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AssessmentProjectSummaryProperties model = new AssessmentProjectSummaryProperties(); + model = BinaryData.fromObject(model).toObject(AssessmentProjectSummaryProperties.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectUpdatePropertiesTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectUpdatePropertiesTests.java new file mode 100644 index 000000000000..d231bb5b7aa1 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectUpdatePropertiesTests.java @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProjectUpdateProperties; +import com.azure.resourcemanager.migration.assessment.models.ProjectStatus; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import org.junit.jupiter.api.Assertions; + +public final class AssessmentProjectUpdatePropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AssessmentProjectUpdateProperties model = BinaryData.fromString( + "{\"assessmentSolutionId\":\"hc\",\"projectStatus\":\"Active\",\"customerWorkspaceId\":\"hjtckwhd\",\"customerWorkspaceLocation\":\"ifiyipjxsqwpgrj\",\"publicNetworkAccess\":\"norcjxvsnbyxqab\",\"customerStorageAccountArmId\":\"ocpcy\",\"provisioningState\":\"Accepted\"}") + .toObject(AssessmentProjectUpdateProperties.class); + Assertions.assertEquals("hc", model.assessmentSolutionId()); + Assertions.assertEquals(ProjectStatus.ACTIVE, model.projectStatus()); + Assertions.assertEquals("hjtckwhd", model.customerWorkspaceId()); + Assertions.assertEquals("ifiyipjxsqwpgrj", model.customerWorkspaceLocation()); + Assertions.assertEquals("norcjxvsnbyxqab", model.publicNetworkAccess()); + Assertions.assertEquals("ocpcy", model.customerStorageAccountArmId()); + Assertions.assertEquals(ProvisioningState.ACCEPTED, model.provisioningState()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AssessmentProjectUpdateProperties model = new AssessmentProjectUpdateProperties().withAssessmentSolutionId("hc") + .withProjectStatus(ProjectStatus.ACTIVE) + .withCustomerWorkspaceId("hjtckwhd") + .withCustomerWorkspaceLocation("ifiyipjxsqwpgrj") + .withPublicNetworkAccess("norcjxvsnbyxqab") + .withCustomerStorageAccountArmId("ocpcy") + .withProvisioningState(ProvisioningState.ACCEPTED); + model = BinaryData.fromObject(model).toObject(AssessmentProjectUpdateProperties.class); + Assertions.assertEquals("hc", model.assessmentSolutionId()); + Assertions.assertEquals(ProjectStatus.ACTIVE, model.projectStatus()); + Assertions.assertEquals("hjtckwhd", model.customerWorkspaceId()); + Assertions.assertEquals("ifiyipjxsqwpgrj", model.customerWorkspaceLocation()); + Assertions.assertEquals("norcjxvsnbyxqab", model.publicNetworkAccess()); + Assertions.assertEquals("ocpcy", model.customerStorageAccountArmId()); + Assertions.assertEquals(ProvisioningState.ACCEPTED, model.provisioningState()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectUpdateTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectUpdateTests.java new file mode 100644 index 000000000000..6a00d5733adb --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectUpdateTests.java @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProjectUpdate; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProjectUpdateProperties; +import com.azure.resourcemanager.migration.assessment.models.ProjectStatus; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Assertions; + +public final class AssessmentProjectUpdateTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AssessmentProjectUpdate model = BinaryData.fromString( + "{\"tags\":{\"ymwisdkft\":\"zwdzuh\",\"vkmijcmmxdcuf\":\"wxmnteiwao\",\"cxtbzsg\":\"fsrpymzidnse\",\"sne\":\"yc\"},\"properties\":{\"assessmentSolutionId\":\"wzjeiach\",\"projectStatus\":\"Active\",\"customerWorkspaceId\":\"flnrosfqpteehzz\",\"customerWorkspaceLocation\":\"pyqr\",\"publicNetworkAccess\":\"z\",\"customerStorageAccountArmId\":\"pvswjdkirso\",\"provisioningState\":\"Canceled\"}}") + .toObject(AssessmentProjectUpdate.class); + Assertions.assertEquals("zwdzuh", model.tags().get("ymwisdkft")); + Assertions.assertEquals("wzjeiach", model.properties().assessmentSolutionId()); + Assertions.assertEquals(ProjectStatus.ACTIVE, model.properties().projectStatus()); + Assertions.assertEquals("flnrosfqpteehzz", model.properties().customerWorkspaceId()); + Assertions.assertEquals("pyqr", model.properties().customerWorkspaceLocation()); + Assertions.assertEquals("z", model.properties().publicNetworkAccess()); + Assertions.assertEquals("pvswjdkirso", model.properties().customerStorageAccountArmId()); + Assertions.assertEquals(ProvisioningState.CANCELED, model.properties().provisioningState()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AssessmentProjectUpdate model = new AssessmentProjectUpdate() + .withTags( + mapOf("ymwisdkft", "zwdzuh", "vkmijcmmxdcuf", "wxmnteiwao", "cxtbzsg", "fsrpymzidnse", "sne", "yc")) + .withProperties(new AssessmentProjectUpdateProperties().withAssessmentSolutionId("wzjeiach") + .withProjectStatus(ProjectStatus.ACTIVE) + .withCustomerWorkspaceId("flnrosfqpteehzz") + .withCustomerWorkspaceLocation("pyqr") + .withPublicNetworkAccess("z") + .withCustomerStorageAccountArmId("pvswjdkirso") + .withProvisioningState(ProvisioningState.CANCELED)); + model = BinaryData.fromObject(model).toObject(AssessmentProjectUpdate.class); + Assertions.assertEquals("zwdzuh", model.tags().get("ymwisdkft")); + Assertions.assertEquals("wzjeiach", model.properties().assessmentSolutionId()); + Assertions.assertEquals(ProjectStatus.ACTIVE, model.properties().projectStatus()); + Assertions.assertEquals("flnrosfqpteehzz", model.properties().customerWorkspaceId()); + Assertions.assertEquals("pyqr", model.properties().customerWorkspaceLocation()); + Assertions.assertEquals("z", model.properties().publicNetworkAccess()); + Assertions.assertEquals("pvswjdkirso", model.properties().customerStorageAccountArmId()); + Assertions.assertEquals(ProvisioningState.CANCELED, model.properties().provisioningState()); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsCreateMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsCreateMockTests.java new file mode 100644 index 000000000000..26d3413daee3 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsCreateMockTests.java @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProject; +import com.azure.resourcemanager.migration.assessment.models.ProjectProperties; +import com.azure.resourcemanager.migration.assessment.models.ProjectStatus; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class AssessmentProjectsOperationsCreateMockTests { + @Test + public void testCreate() throws Exception { + String responseStr + = "{\"properties\":{\"createdTimestamp\":\"2021-12-08T22:47:10Z\",\"updatedTimestamp\":\"2021-05-04T10:08:41Z\",\"serviceEndpoint\":\"e\",\"assessmentSolutionId\":\"exkxbhx\",\"projectStatus\":\"Inactive\",\"customerWorkspaceId\":\"ulgm\",\"customerWorkspaceLocation\":\"jevdyznf\",\"publicNetworkAccess\":\"svkskmqoz\",\"privateEndpointConnections\":[{\"properties\":{\"groupIds\":[\"jrliiz\",\"ixlqfhefkwabsolr\",\"nqqlmgnl\",\"xsjxtelexhvuqboz\"],\"privateEndpoint\":{},\"privateLinkServiceConnectionState\":{},\"provisioningState\":\"Creating\"},\"id\":\"ocarkuzlbcnndt\",\"name\":\"nx\",\"type\":\"wqy\"},{\"properties\":{\"groupIds\":[\"dyz\"],\"privateEndpoint\":{},\"privateLinkServiceConnectionState\":{},\"provisioningState\":\"Creating\"},\"id\":\"exn\",\"name\":\"akckywym\",\"type\":\"gaabjkdtf\"},{\"properties\":{\"groupIds\":[\"ogzvk\",\"wrsiwdyjqurykc\"],\"privateEndpoint\":{},\"privateLinkServiceConnectionState\":{},\"provisioningState\":\"Creating\"},\"id\":\"ekcsueh\",\"name\":\"gdda\",\"type\":\"bcbgydlqidywmhm\"},{\"properties\":{\"groupIds\":[\"ilkfbnrqqxv\"],\"privateEndpoint\":{},\"privateLinkServiceConnectionState\":{},\"provisioningState\":\"Deleting\"},\"id\":\"fnqt\",\"name\":\"jtoma\",\"type\":\"swbnfddepldwqjns\"}],\"customerStorageAccountArmId\":\"ygleexa\",\"provisioningState\":\"Succeeded\"},\"location\":\"whsbrcary\",\"tags\":{\"yvoaqajuvehzp\":\"j\",\"mpfu\":\"dmkrrb\",\"mpzkrvfyifkd\":\"ubefgybpmfbfunu\",\"tnkjjwgcwnphb\":\"chlzvfi\"},\"id\":\"gfyrtogmhmjpjsc\",\"name\":\"fp\",\"type\":\"qwtygevgwmseharx\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + AssessmentProject response = manager.assessmentProjectsOperations() + .define("bjqvls") + .withRegion("sbzxl") + .withExistingResourceGroup("vxisimjcea") + .withTags(mapOf("zacn", "omeikjcl", "qbxyxoyfpuqqi", "wpfsuqtaaz", "wvpsoz", "ezxlhdjzqdca", "pnx", + "iihjriybmrzo")) + .withProperties(new ProjectProperties().withProvisioningState(ProvisioningState.ACCEPTED) + .withAssessmentSolutionId("puby") + .withProjectStatus(ProjectStatus.ACTIVE) + .withCustomerWorkspaceId("k") + .withCustomerWorkspaceLocation("eebgvopemtuoqu") + .withPublicNetworkAccess("yegq") + .withCustomerStorageAccountArmId("xuwwkp")) + .create(); + + Assertions.assertEquals("whsbrcary", response.location()); + Assertions.assertEquals("j", response.tags().get("yvoaqajuvehzp")); + Assertions.assertEquals(ProvisioningState.SUCCEEDED, response.properties().provisioningState()); + Assertions.assertEquals("exkxbhx", response.properties().assessmentSolutionId()); + Assertions.assertEquals(ProjectStatus.INACTIVE, response.properties().projectStatus()); + Assertions.assertEquals("ulgm", response.properties().customerWorkspaceId()); + Assertions.assertEquals("jevdyznf", response.properties().customerWorkspaceLocation()); + Assertions.assertEquals("svkskmqoz", response.properties().publicNetworkAccess()); + Assertions.assertEquals("ygleexa", response.properties().customerStorageAccountArmId()); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsDeleteByResourceGroupWithResponseMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsDeleteByResourceGroupWithResponseMockTests.java new file mode 100644 index 000000000000..3b0eb0771821 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsDeleteByResourceGroupWithResponseMockTests.java @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class AssessmentProjectsOperationsDeleteByResourceGroupWithResponseMockTests { + @Test + public void testDeleteWithResponse() throws Exception { + String responseStr = "{}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + manager.assessmentProjectsOperations() + .deleteByResourceGroupWithResponse("jcx", "yqgxhlus", com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsGetByResourceGroupWithResponseMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsGetByResourceGroupWithResponseMockTests.java new file mode 100644 index 000000000000..f315f8abb08d --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsGetByResourceGroupWithResponseMockTests.java @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProject; +import com.azure.resourcemanager.migration.assessment.models.ProjectStatus; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class AssessmentProjectsOperationsGetByResourceGroupWithResponseMockTests { + @Test + public void testGetByResourceGroupWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"createdTimestamp\":\"2021-09-12T18:54:27Z\",\"updatedTimestamp\":\"2021-07-23T12:28:28Z\",\"serviceEndpoint\":\"dsiwdfmmp\",\"assessmentSolutionId\":\"zzwvywrgyng\",\"projectStatus\":\"Inactive\",\"customerWorkspaceId\":\"pxncakiqao\",\"customerWorkspaceLocation\":\"jrkc\",\"publicNetworkAccess\":\"mgglvlmfe\",\"privateEndpointConnections\":[{\"properties\":{\"groupIds\":[\"kgltyg\",\"hqfgqkayejsx\"],\"privateEndpoint\":{},\"privateLinkServiceConnectionState\":{},\"provisioningState\":\"Deleting\"},\"id\":\"wf\",\"name\":\"ziiucij\",\"type\":\"ceatlijjjrtvamca\"},{\"properties\":{\"groupIds\":[\"xk\",\"ccxetyvkun\",\"ignohi\",\"kgqogjw\"],\"privateEndpoint\":{},\"privateLinkServiceConnectionState\":{},\"provisioningState\":\"Deleting\"},\"id\":\"dvabbxbhmedeilb\",\"name\":\"ywfcfxzi\",\"type\":\"zzihvwy\"}],\"customerStorageAccountArmId\":\"suvjslcz\",\"provisioningState\":\"Updating\"},\"location\":\"djsllfr\",\"tags\":{\"acfrgna\":\"mvxad\",\"fbktyjmfczlf\":\"bab\"},\"id\":\"yq\",\"name\":\"frbzgowo\",\"type\":\"qmje\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + AssessmentProject response = manager.assessmentProjectsOperations() + .getByResourceGroupWithResponse("dmkxwxdcvjwcy", "iakeciqc", com.azure.core.util.Context.NONE) + .getValue(); + + Assertions.assertEquals("djsllfr", response.location()); + Assertions.assertEquals("mvxad", response.tags().get("acfrgna")); + Assertions.assertEquals(ProvisioningState.UPDATING, response.properties().provisioningState()); + Assertions.assertEquals("zzwvywrgyng", response.properties().assessmentSolutionId()); + Assertions.assertEquals(ProjectStatus.INACTIVE, response.properties().projectStatus()); + Assertions.assertEquals("pxncakiqao", response.properties().customerWorkspaceId()); + Assertions.assertEquals("jrkc", response.properties().customerWorkspaceLocation()); + Assertions.assertEquals("mgglvlmfe", response.properties().publicNetworkAccess()); + Assertions.assertEquals("suvjslcz", response.properties().customerStorageAccountArmId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsListByResourceGroupMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsListByResourceGroupMockTests.java new file mode 100644 index 000000000000..d9919f59ad07 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsListByResourceGroupMockTests.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProject; +import com.azure.resourcemanager.migration.assessment.models.ProjectStatus; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class AssessmentProjectsOperationsListByResourceGroupMockTests { + @Test + public void testListByResourceGroup() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"createdTimestamp\":\"2021-09-08T11:13:10Z\",\"updatedTimestamp\":\"2021-11-06T14:05:16Z\",\"serviceEndpoint\":\"ljomevt\",\"assessmentSolutionId\":\"cnlbv\",\"projectStatus\":\"Active\",\"customerWorkspaceId\":\"dkkgjiiytssikizb\",\"customerWorkspaceLocation\":\"fqb\",\"publicNetworkAccess\":\"tnrgmqsorhce\",\"privateEndpointConnections\":[{\"properties\":{\"groupIds\":[\"km\",\"cpwzv\",\"doksqdtiwlwxlbon\"],\"privateEndpoint\":{},\"privateLinkServiceConnectionState\":{},\"provisioningState\":\"Deleting\"},\"id\":\"qicqchygt\",\"name\":\"xbyja\",\"type\":\"epubdp\"},{\"properties\":{\"groupIds\":[\"vgxiaodetvo\"],\"privateEndpoint\":{},\"privateLinkServiceConnectionState\":{},\"provisioningState\":\"Deleting\"},\"id\":\"uwsaifmcwn\",\"name\":\"s\",\"type\":\"zlehgcvkbcknjolg\"}],\"customerStorageAccountArmId\":\"yxpvelszerqze\",\"provisioningState\":\"Provisioning\"},\"location\":\"eintxwaljglzobl\",\"tags\":{\"yqbhd\":\"afrqulhm\",\"xwmzwdfkbnrz\":\"afjrqpjiyrqjcrg\",\"tqjfgxxsaet\":\"rpdltbq\",\"cduwjoedx\":\"zdgvpyigdaqqilz\"},\"id\":\"gucaif\",\"name\":\"aurwwgilfjq\",\"type\":\"a\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response + = manager.assessmentProjectsOperations().listByResourceGroup("cgqtag", com.azure.core.util.Context.NONE); + + Assertions.assertEquals("eintxwaljglzobl", response.iterator().next().location()); + Assertions.assertEquals("afrqulhm", response.iterator().next().tags().get("yqbhd")); + Assertions.assertEquals(ProvisioningState.PROVISIONING, + response.iterator().next().properties().provisioningState()); + Assertions.assertEquals("cnlbv", response.iterator().next().properties().assessmentSolutionId()); + Assertions.assertEquals(ProjectStatus.ACTIVE, response.iterator().next().properties().projectStatus()); + Assertions.assertEquals("dkkgjiiytssikizb", response.iterator().next().properties().customerWorkspaceId()); + Assertions.assertEquals("fqb", response.iterator().next().properties().customerWorkspaceLocation()); + Assertions.assertEquals("tnrgmqsorhce", response.iterator().next().properties().publicNetworkAccess()); + Assertions.assertEquals("yxpvelszerqze", response.iterator().next().properties().customerStorageAccountArmId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsListMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsListMockTests.java new file mode 100644 index 000000000000..745a981436c2 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentProjectsOperationsListMockTests.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.AssessmentProject; +import com.azure.resourcemanager.migration.assessment.models.ProjectStatus; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class AssessmentProjectsOperationsListMockTests { + @Test + public void testList() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"createdTimestamp\":\"2021-09-21T03:29:13Z\",\"updatedTimestamp\":\"2021-03-30T18:39:54Z\",\"serviceEndpoint\":\"adrmmwiuawvcmjzk\",\"assessmentSolutionId\":\"idisczskosw\",\"projectStatus\":\"Inactive\",\"customerWorkspaceId\":\"azugamxzkrrcoi\",\"customerWorkspaceLocation\":\"bamnppcc\",\"publicNetworkAccess\":\"u\",\"privateEndpointConnections\":[{\"properties\":{\"groupIds\":[\"zaxy\"],\"privateEndpoint\":{},\"privateLinkServiceConnectionState\":{},\"provisioningState\":\"Failed\"},\"id\":\"uizh\",\"name\":\"hnepkpeti\",\"type\":\"rx\"},{\"properties\":{\"groupIds\":[\"xdukecpxd\",\"zvdhctmmkosz\",\"dblnsntrp\",\"aqkiofkb\"],\"privateEndpoint\":{},\"privateLinkServiceConnectionState\":{},\"provisioningState\":\"Deleting\"},\"id\":\"lbnld\",\"name\":\"vcb\",\"type\":\"hez\"},{\"properties\":{\"groupIds\":[\"usqxutrpbrr\",\"yuuatvlmbjwcolbm\"],\"privateEndpoint\":{},\"privateLinkServiceConnectionState\":{},\"provisioningState\":\"Deleting\"},\"id\":\"tpc\",\"name\":\"ahprzrvxhmtfhocn\",\"type\":\"zcmjhngxnoqrxt\"}],\"customerStorageAccountArmId\":\"sn\",\"provisioningState\":\"Deleting\"},\"location\":\"d\",\"tags\":{\"hepfwwtjfdoes\":\"did\",\"dbckyo\":\"xhmw\",\"jzrbhtmeplv\":\"kxkxhnegk\",\"pgsn\":\"kaobrl\"},\"id\":\"agnchjhgemuowaky\",\"name\":\"a\",\"type\":\"hjym\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response + = manager.assessmentProjectsOperations().list(com.azure.core.util.Context.NONE); + + Assertions.assertEquals("d", response.iterator().next().location()); + Assertions.assertEquals("did", response.iterator().next().tags().get("hepfwwtjfdoes")); + Assertions.assertEquals(ProvisioningState.DELETING, + response.iterator().next().properties().provisioningState()); + Assertions.assertEquals("idisczskosw", response.iterator().next().properties().assessmentSolutionId()); + Assertions.assertEquals(ProjectStatus.INACTIVE, response.iterator().next().properties().projectStatus()); + Assertions.assertEquals("azugamxzkrrcoi", response.iterator().next().properties().customerWorkspaceId()); + Assertions.assertEquals("bamnppcc", response.iterator().next().properties().customerWorkspaceLocation()); + Assertions.assertEquals("u", response.iterator().next().properties().publicNetworkAccess()); + Assertions.assertEquals("sn", response.iterator().next().properties().customerStorageAccountArmId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentsOperationsDeleteWithResponseMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentsOperationsDeleteWithResponseMockTests.java new file mode 100644 index 000000000000..046319f3604d --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentsOperationsDeleteWithResponseMockTests.java @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class AssessmentsOperationsDeleteWithResponseMockTests { + @Test + public void testDeleteWithResponse() throws Exception { + String responseStr = "{}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + manager.assessmentsOperations() + .deleteWithResponse("dqqjwkrhwzdano", "isgglmvokat", "ztjctibpvbkae", "xsmzygdf", + com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentsOperationsDownloadUrlMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentsOperationsDownloadUrlMockTests.java new file mode 100644 index 000000000000..3b50d7d9eefe --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AssessmentsOperationsDownloadUrlMockTests.java @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.DownloadUrl; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class AssessmentsOperationsDownloadUrlMockTests { + @Test + public void testDownloadUrl() throws Exception { + String responseStr = "{\"assessmentReportUrl\":\"vgmfalkzazmgok\",\"expirationTime\":\"2021-09-06T15:08:44Z\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + DownloadUrl response = manager.assessmentsOperations() + .downloadUrl("akw", "eivmak", "hysowljuxlkbect", "tfjmskdchmaiub", "datavlzw", + com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessedDiskTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessedDiskTests.java new file mode 100644 index 000000000000..82966f8b7340 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessedDiskTests.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessedDisk; + +public final class AvsAssessedDiskTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AvsAssessedDisk model = BinaryData.fromString( + "{\"name\":\"uzqogsexnevf\",\"displayName\":\"wnwmewzs\",\"gigabytesProvisioned\":87.22587,\"megabytesPerSecondOfRead\":25.413382,\"megabytesPerSecondOfWrite\":66.84359,\"numberOfReadOperationsPerSecond\":4.8421144,\"numberOfWriteOperationsPerSecond\":47.16871}") + .toObject(AvsAssessedDisk.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AvsAssessedDisk model = new AvsAssessedDisk(); + model = BinaryData.fromObject(model).toObject(AvsAssessedDisk.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessedNetworkAdapterTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessedNetworkAdapterTests.java new file mode 100644 index 000000000000..3c3a0ffe591e --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessedNetworkAdapterTests.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessedNetworkAdapter; + +public final class AvsAssessedNetworkAdapterTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AvsAssessedNetworkAdapter model = BinaryData.fromString( + "{\"macAddress\":\"dpfrxtrthzvaytdw\",\"ipAddresses\":[\"rqubpaxhexiil\",\"vpdtiirqtdqoa\"],\"displayName\":\"r\",\"megabytesPerSecondReceived\":27.96995,\"megabytesPerSecondTransmitted\":74.71945}") + .toObject(AvsAssessedNetworkAdapter.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AvsAssessedNetworkAdapter model = new AvsAssessedNetworkAdapter(); + model = BinaryData.fromObject(model).toObject(AvsAssessedNetworkAdapter.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentOptionsInnerTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentOptionsInnerTests.java new file mode 100644 index 000000000000..c78d0f9f3885 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentOptionsInnerTests.java @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AvsAssessmentOptionsInner; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessmentOptionsProperties; +import com.azure.resourcemanager.migration.assessment.models.AvsSkuOptions; +import com.azure.resourcemanager.migration.assessment.models.AzureAvsNodeType; +import com.azure.resourcemanager.migration.assessment.models.AzureCurrency; +import com.azure.resourcemanager.migration.assessment.models.AzureLocation; +import com.azure.resourcemanager.migration.assessment.models.AzureOfferCode; +import com.azure.resourcemanager.migration.assessment.models.FttAndRaidLevel; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class AvsAssessmentOptionsInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AvsAssessmentOptionsInner model = BinaryData.fromString( + "{\"properties\":{\"avsNodes\":[{\"nodeType\":\"AV36\",\"targetLocations\":[\"USGovIowa\",\"SouthAfricaWest\"]},{\"nodeType\":\"Unknown\",\"targetLocations\":[\"CanadaCentral\",\"EastUs2\",\"NorthEurope\",\"KoreaCentral\"]},{\"nodeType\":\"AV36\",\"targetLocations\":[\"USDoDCentral\",\"USGovVirginia\",\"GermanyNortheast\"]}],\"failuresToTolerateAndRaidLevelValues\":[\"Ftt3Raid1\"],\"reservedInstanceAvsNodes\":[\"Unknown\",\"Unknown\",\"AV36\",\"Unknown\"],\"reservedInstanceSupportedLocations\":[\"JapanWest\",\"ChinaNorth\",\"EastUs2\",\"UAECentral\"],\"reservedInstanceSupportedCurrencies\":[\"BRL\",\"ARS\"],\"reservedInstanceSupportedOffers\":[\"MSAZR0149P\",\"Unknown\"]},\"id\":\"slynqwwnc\",\"name\":\"zzhxgktrm\",\"type\":\"ucnapkteoellwp\"}") + .toObject(AvsAssessmentOptionsInner.class); + Assertions.assertEquals(AzureAvsNodeType.AV36, model.properties().avsNodes().get(0).nodeType()); + Assertions.assertEquals(AzureLocation.USGOV_IOWA, + model.properties().avsNodes().get(0).targetLocations().get(0)); + Assertions.assertEquals(FttAndRaidLevel.FTT3RAID1, + model.properties().failuresToTolerateAndRaidLevelValues().get(0)); + Assertions.assertEquals(AzureAvsNodeType.UNKNOWN, model.properties().reservedInstanceAvsNodes().get(0)); + Assertions.assertEquals(AzureLocation.JAPAN_WEST, + model.properties().reservedInstanceSupportedLocations().get(0)); + Assertions.assertEquals(AzureCurrency.BRL, model.properties().reservedInstanceSupportedCurrencies().get(0)); + Assertions.assertEquals(AzureOfferCode.MSAZR0149P, model.properties().reservedInstanceSupportedOffers().get(0)); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AvsAssessmentOptionsInner model + = new AvsAssessmentOptionsInner().withProperties(new AvsAssessmentOptionsProperties() + .withAvsNodes(Arrays.asList( + new AvsSkuOptions().withNodeType(AzureAvsNodeType.AV36) + .withTargetLocations(Arrays.asList(AzureLocation.USGOV_IOWA, AzureLocation.SOUTH_AFRICA_WEST)), + new AvsSkuOptions().withNodeType(AzureAvsNodeType.UNKNOWN) + .withTargetLocations(Arrays.asList(AzureLocation.CANADA_CENTRAL, AzureLocation.EAST_US2, + AzureLocation.NORTH_EUROPE, AzureLocation.KOREA_CENTRAL)), + new AvsSkuOptions().withNodeType(AzureAvsNodeType.AV36) + .withTargetLocations(Arrays.asList(AzureLocation.USDO_DCENTRAL, AzureLocation.USGOV_VIRGINIA, + AzureLocation.GERMANY_NORTHEAST)))) + .withFailuresToTolerateAndRaidLevelValues(Arrays.asList(FttAndRaidLevel.FTT3RAID1)) + .withReservedInstanceAvsNodes(Arrays.asList(AzureAvsNodeType.UNKNOWN, AzureAvsNodeType.UNKNOWN, + AzureAvsNodeType.AV36, AzureAvsNodeType.UNKNOWN)) + .withReservedInstanceSupportedLocations(Arrays.asList(AzureLocation.JAPAN_WEST, + AzureLocation.CHINA_NORTH, AzureLocation.EAST_US2, AzureLocation.UAECENTRAL)) + .withReservedInstanceSupportedCurrencies(Arrays.asList(AzureCurrency.BRL, AzureCurrency.ARS)) + .withReservedInstanceSupportedOffers(Arrays.asList(AzureOfferCode.MSAZR0149P, AzureOfferCode.UNKNOWN))); + model = BinaryData.fromObject(model).toObject(AvsAssessmentOptionsInner.class); + Assertions.assertEquals(AzureAvsNodeType.AV36, model.properties().avsNodes().get(0).nodeType()); + Assertions.assertEquals(AzureLocation.USGOV_IOWA, + model.properties().avsNodes().get(0).targetLocations().get(0)); + Assertions.assertEquals(FttAndRaidLevel.FTT3RAID1, + model.properties().failuresToTolerateAndRaidLevelValues().get(0)); + Assertions.assertEquals(AzureAvsNodeType.UNKNOWN, model.properties().reservedInstanceAvsNodes().get(0)); + Assertions.assertEquals(AzureLocation.JAPAN_WEST, + model.properties().reservedInstanceSupportedLocations().get(0)); + Assertions.assertEquals(AzureCurrency.BRL, model.properties().reservedInstanceSupportedCurrencies().get(0)); + Assertions.assertEquals(AzureOfferCode.MSAZR0149P, model.properties().reservedInstanceSupportedOffers().get(0)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentOptionsListResultTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentOptionsListResultTests.java new file mode 100644 index 000000000000..d2172db1a834 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentOptionsListResultTests.java @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.AvsAssessmentOptionsInner; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessmentOptionsListResult; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessmentOptionsProperties; +import com.azure.resourcemanager.migration.assessment.models.AvsSkuOptions; +import com.azure.resourcemanager.migration.assessment.models.AzureAvsNodeType; +import com.azure.resourcemanager.migration.assessment.models.AzureCurrency; +import com.azure.resourcemanager.migration.assessment.models.AzureLocation; +import com.azure.resourcemanager.migration.assessment.models.AzureOfferCode; +import com.azure.resourcemanager.migration.assessment.models.FttAndRaidLevel; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class AvsAssessmentOptionsListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AvsAssessmentOptionsListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"avsNodes\":[{\"nodeType\":\"AV36\",\"targetLocations\":[\"CanadaEast\",\"USGovTexas\",\"USGovArizona\"]},{\"nodeType\":\"AV36\",\"targetLocations\":[\"ChinaEast\"]}],\"failuresToTolerateAndRaidLevelValues\":[\"Ftt1Raid5\",\"Unknown\",\"Ftt1Raid1\",\"Ftt2Raid1\"],\"reservedInstanceAvsNodes\":[\"Unknown\"],\"reservedInstanceSupportedLocations\":[\"NorwayWest\"],\"reservedInstanceSupportedCurrencies\":[\"MXN\",\"EUR\",\"KRW\",\"MYR\"],\"reservedInstanceSupportedOffers\":[\"Unknown\"]},\"id\":\"xdjzlmwlxk\",\"name\":\"ug\",\"type\":\"hzovawjvzunlut\"},{\"properties\":{\"avsNodes\":[{\"nodeType\":\"Unknown\",\"targetLocations\":[\"USGovVirginia\"]},{\"nodeType\":\"AV36\",\"targetLocations\":[\"AustraliaEast\"]},{\"nodeType\":\"AV36\",\"targetLocations\":[\"USGovTexas\"]}],\"failuresToTolerateAndRaidLevelValues\":[\"Ftt1Raid1\",\"Ftt2Raid6\"],\"reservedInstanceAvsNodes\":[\"Unknown\",\"AV36\"],\"reservedInstanceSupportedLocations\":[\"JapanEast\",\"AustraliaEast\",\"NorthCentralUs\"],\"reservedInstanceSupportedCurrencies\":[\"SEK\"],\"reservedInstanceSupportedOffers\":[\"MSMCAZR0060P\"]},\"id\":\"pwo\",\"name\":\"uh\",\"type\":\"fpbsjyofdxl\"},{\"properties\":{\"avsNodes\":[{\"nodeType\":\"AV36\",\"targetLocations\":[\"USDoDEast\",\"SwitzerlandWest\",\"SwedenCentral\"]},{\"nodeType\":\"Unknown\",\"targetLocations\":[\"USDoDEast\",\"KoreaCentral\"]},{\"nodeType\":\"Unknown\",\"targetLocations\":[\"EastUs2\"]},{\"nodeType\":\"AV36\",\"targetLocations\":[\"JapanWest\",\"SouthAfricaWest\",\"NorthCentralUs\",\"Unknown\"]}],\"failuresToTolerateAndRaidLevelValues\":[\"Ftt3Raid1\",\"Ftt2Raid1\"],\"reservedInstanceAvsNodes\":[\"AV36\"],\"reservedInstanceSupportedLocations\":[\"USGovArizona\",\"UsSecCentral\",\"NorthEurope\",\"NorwayWest\"],\"reservedInstanceSupportedCurrencies\":[\"AUD\"],\"reservedInstanceSupportedOffers\":[\"MSAZR0022P\"]},\"id\":\"aq\",\"name\":\"slyjpkiid\",\"type\":\"yexz\"}],\"nextLink\":\"lixhnrztfol\"}") + .toObject(AvsAssessmentOptionsListResult.class); + Assertions.assertEquals(AzureAvsNodeType.AV36, model.value().get(0).properties().avsNodes().get(0).nodeType()); + Assertions.assertEquals(AzureLocation.CANADA_EAST, + model.value().get(0).properties().avsNodes().get(0).targetLocations().get(0)); + Assertions.assertEquals(FttAndRaidLevel.FTT1RAID5, + model.value().get(0).properties().failuresToTolerateAndRaidLevelValues().get(0)); + Assertions.assertEquals(AzureAvsNodeType.UNKNOWN, + model.value().get(0).properties().reservedInstanceAvsNodes().get(0)); + Assertions.assertEquals(AzureLocation.NORWAY_WEST, + model.value().get(0).properties().reservedInstanceSupportedLocations().get(0)); + Assertions.assertEquals(AzureCurrency.MXN, + model.value().get(0).properties().reservedInstanceSupportedCurrencies().get(0)); + Assertions.assertEquals(AzureOfferCode.UNKNOWN, + model.value().get(0).properties().reservedInstanceSupportedOffers().get(0)); + Assertions.assertEquals("lixhnrztfol", model.nextLink()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AvsAssessmentOptionsListResult model = new AvsAssessmentOptionsListResult() + .withValue(Arrays.asList( + new AvsAssessmentOptionsInner().withProperties(new AvsAssessmentOptionsProperties() + .withAvsNodes(Arrays.asList( + new AvsSkuOptions().withNodeType(AzureAvsNodeType.AV36) + .withTargetLocations(Arrays.asList(AzureLocation.CANADA_EAST, AzureLocation.USGOV_TEXAS, + AzureLocation.USGOV_ARIZONA)), + new AvsSkuOptions().withNodeType(AzureAvsNodeType.AV36) + .withTargetLocations(Arrays.asList(AzureLocation.CHINA_EAST)))) + .withFailuresToTolerateAndRaidLevelValues(Arrays.asList(FttAndRaidLevel.FTT1RAID5, + FttAndRaidLevel.UNKNOWN, FttAndRaidLevel.FTT1RAID1, FttAndRaidLevel.FTT2RAID1)) + .withReservedInstanceAvsNodes(Arrays.asList(AzureAvsNodeType.UNKNOWN)) + .withReservedInstanceSupportedLocations(Arrays.asList(AzureLocation.NORWAY_WEST)) + .withReservedInstanceSupportedCurrencies( + Arrays.asList(AzureCurrency.MXN, AzureCurrency.EUR, AzureCurrency.KRW, AzureCurrency.MYR)) + .withReservedInstanceSupportedOffers(Arrays.asList(AzureOfferCode.UNKNOWN))), + new AvsAssessmentOptionsInner().withProperties(new AvsAssessmentOptionsProperties() + .withAvsNodes(Arrays.asList( + new AvsSkuOptions().withNodeType(AzureAvsNodeType.UNKNOWN) + .withTargetLocations(Arrays.asList(AzureLocation.USGOV_VIRGINIA)), + new AvsSkuOptions().withNodeType(AzureAvsNodeType.AV36) + .withTargetLocations(Arrays.asList(AzureLocation.AUSTRALIA_EAST)), + new AvsSkuOptions().withNodeType(AzureAvsNodeType.AV36) + .withTargetLocations(Arrays.asList(AzureLocation.USGOV_TEXAS)))) + .withFailuresToTolerateAndRaidLevelValues( + Arrays.asList(FttAndRaidLevel.FTT1RAID1, FttAndRaidLevel.FTT2RAID6)) + .withReservedInstanceAvsNodes(Arrays.asList(AzureAvsNodeType.UNKNOWN, AzureAvsNodeType.AV36)) + .withReservedInstanceSupportedLocations(Arrays + .asList(AzureLocation.JAPAN_EAST, AzureLocation.AUSTRALIA_EAST, AzureLocation.NORTH_CENTRAL_US)) + .withReservedInstanceSupportedCurrencies(Arrays.asList(AzureCurrency.SEK)) + .withReservedInstanceSupportedOffers(Arrays.asList(AzureOfferCode.MSMCAZR0060P))), + new AvsAssessmentOptionsInner().withProperties(new AvsAssessmentOptionsProperties() + .withAvsNodes(Arrays.asList( + new AvsSkuOptions().withNodeType(AzureAvsNodeType.AV36) + .withTargetLocations(Arrays.asList(AzureLocation.USDO_DEAST, AzureLocation.SWITZERLAND_WEST, + AzureLocation.SWEDEN_CENTRAL)), + new AvsSkuOptions() + .withNodeType(AzureAvsNodeType.UNKNOWN) + .withTargetLocations(Arrays.asList(AzureLocation.USDO_DEAST, AzureLocation.KOREA_CENTRAL)), + new AvsSkuOptions().withNodeType(AzureAvsNodeType.UNKNOWN) + .withTargetLocations(Arrays.asList(AzureLocation.EAST_US2)), + new AvsSkuOptions().withNodeType(AzureAvsNodeType.AV36) + .withTargetLocations( + Arrays.asList(AzureLocation.JAPAN_WEST, AzureLocation.SOUTH_AFRICA_WEST, + AzureLocation.NORTH_CENTRAL_US, AzureLocation.UNKNOWN)))) + .withFailuresToTolerateAndRaidLevelValues( + Arrays.asList(FttAndRaidLevel.FTT3RAID1, FttAndRaidLevel.FTT2RAID1)) + .withReservedInstanceAvsNodes(Arrays.asList(AzureAvsNodeType.AV36)) + .withReservedInstanceSupportedLocations(Arrays.asList(AzureLocation.USGOV_ARIZONA, + AzureLocation.US_SEC_CENTRAL, AzureLocation.NORTH_EUROPE, AzureLocation.NORWAY_WEST)) + .withReservedInstanceSupportedCurrencies(Arrays.asList(AzureCurrency.AUD)) + .withReservedInstanceSupportedOffers(Arrays.asList(AzureOfferCode.MSAZR0022P))))) + .withNextLink("lixhnrztfol"); + model = BinaryData.fromObject(model).toObject(AvsAssessmentOptionsListResult.class); + Assertions.assertEquals(AzureAvsNodeType.AV36, model.value().get(0).properties().avsNodes().get(0).nodeType()); + Assertions.assertEquals(AzureLocation.CANADA_EAST, + model.value().get(0).properties().avsNodes().get(0).targetLocations().get(0)); + Assertions.assertEquals(FttAndRaidLevel.FTT1RAID5, + model.value().get(0).properties().failuresToTolerateAndRaidLevelValues().get(0)); + Assertions.assertEquals(AzureAvsNodeType.UNKNOWN, + model.value().get(0).properties().reservedInstanceAvsNodes().get(0)); + Assertions.assertEquals(AzureLocation.NORWAY_WEST, + model.value().get(0).properties().reservedInstanceSupportedLocations().get(0)); + Assertions.assertEquals(AzureCurrency.MXN, + model.value().get(0).properties().reservedInstanceSupportedCurrencies().get(0)); + Assertions.assertEquals(AzureOfferCode.UNKNOWN, + model.value().get(0).properties().reservedInstanceSupportedOffers().get(0)); + Assertions.assertEquals("lixhnrztfol", model.nextLink()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentOptionsOperationsGetWithResponseMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentOptionsOperationsGetWithResponseMockTests.java new file mode 100644 index 000000000000..e216c9ce1b11 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentOptionsOperationsGetWithResponseMockTests.java @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessmentOptions; +import com.azure.resourcemanager.migration.assessment.models.AzureAvsNodeType; +import com.azure.resourcemanager.migration.assessment.models.AzureCurrency; +import com.azure.resourcemanager.migration.assessment.models.AzureLocation; +import com.azure.resourcemanager.migration.assessment.models.AzureOfferCode; +import com.azure.resourcemanager.migration.assessment.models.FttAndRaidLevel; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class AvsAssessmentOptionsOperationsGetWithResponseMockTests { + @Test + public void testGetWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"avsNodes\":[{\"nodeType\":\"AV36\",\"targetLocations\":[\"USGovVirginia\",\"SouthCentralUs\",\"EastUs2\"]}],\"failuresToTolerateAndRaidLevelValues\":[\"Ftt3Raid1\"],\"reservedInstanceAvsNodes\":[\"Unknown\",\"AV36\"],\"reservedInstanceSupportedLocations\":[\"SouthAfricaWest\",\"CanadaEast\"],\"reservedInstanceSupportedCurrencies\":[\"JPY\",\"SAR\"],\"reservedInstanceSupportedOffers\":[\"MSMCAZR0044P\",\"SavingsPlan3Year\",\"MSAZR0120P\"]},\"id\":\"ko\",\"name\":\"r\",\"type\":\"awn\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + AvsAssessmentOptions response = manager.avsAssessmentOptionsOperations() + .getWithResponse("fwbivqvo", "fuy", "wvbhlimbyq", com.azure.core.util.Context.NONE) + .getValue(); + + Assertions.assertEquals(AzureAvsNodeType.AV36, response.properties().avsNodes().get(0).nodeType()); + Assertions.assertEquals(AzureLocation.USGOV_VIRGINIA, + response.properties().avsNodes().get(0).targetLocations().get(0)); + Assertions.assertEquals(FttAndRaidLevel.FTT3RAID1, + response.properties().failuresToTolerateAndRaidLevelValues().get(0)); + Assertions.assertEquals(AzureAvsNodeType.UNKNOWN, response.properties().reservedInstanceAvsNodes().get(0)); + Assertions.assertEquals(AzureLocation.SOUTH_AFRICA_WEST, + response.properties().reservedInstanceSupportedLocations().get(0)); + Assertions.assertEquals(AzureCurrency.JPY, response.properties().reservedInstanceSupportedCurrencies().get(0)); + Assertions.assertEquals(AzureOfferCode.MSMCAZR0044P, + response.properties().reservedInstanceSupportedOffers().get(0)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentOptionsOperationsListByAssessmentProjectMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentOptionsOperationsListByAssessmentProjectMockTests.java new file mode 100644 index 000000000000..e52b5091b431 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentOptionsOperationsListByAssessmentProjectMockTests.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessmentOptions; +import com.azure.resourcemanager.migration.assessment.models.AzureAvsNodeType; +import com.azure.resourcemanager.migration.assessment.models.AzureCurrency; +import com.azure.resourcemanager.migration.assessment.models.AzureLocation; +import com.azure.resourcemanager.migration.assessment.models.AzureOfferCode; +import com.azure.resourcemanager.migration.assessment.models.FttAndRaidLevel; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class AvsAssessmentOptionsOperationsListByAssessmentProjectMockTests { + @Test + public void testListByAssessmentProject() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"avsNodes\":[{\"nodeType\":\"AV36\",\"targetLocations\":[\"SouthAfricaNorth\",\"ChinaNorth\",\"Unknown\"]},{\"nodeType\":\"Unknown\",\"targetLocations\":[\"UsSecWest\",\"JapanWest\",\"USGovTexas\",\"UAECentral\"]},{\"nodeType\":\"AV36\",\"targetLocations\":[\"CanadaEast\",\"ChinaNorth2\",\"JapanEast\",\"EastUs2\"]},{\"nodeType\":\"AV36\",\"targetLocations\":[\"SwitzerlandNorth\",\"NorthEurope\",\"NorwayEast\",\"CanadaEast\"]}],\"failuresToTolerateAndRaidLevelValues\":[\"Ftt2Raid1\",\"Ftt2Raid1\",\"Unknown\"],\"reservedInstanceAvsNodes\":[\"AV36\"],\"reservedInstanceSupportedLocations\":[\"NorwayEast\",\"SwitzerlandWest\",\"USGovVirginia\"],\"reservedInstanceSupportedCurrencies\":[\"TWD\"],\"reservedInstanceSupportedOffers\":[\"MSMCAZR0060P\",\"MSAZR0025P\",\"MSAZR0129P\",\"MSAZR0127P\"]},\"id\":\"mfcoibic\",\"name\":\"iuswswj\",\"type\":\"kbqsjhbtqqvyfscy\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response = manager.avsAssessmentOptionsOperations() + .listByAssessmentProject("kbudbtwaokb", "vlyttaaknwfrke", com.azure.core.util.Context.NONE); + + Assertions.assertEquals(AzureAvsNodeType.AV36, + response.iterator().next().properties().avsNodes().get(0).nodeType()); + Assertions.assertEquals(AzureLocation.SOUTH_AFRICA_NORTH, + response.iterator().next().properties().avsNodes().get(0).targetLocations().get(0)); + Assertions.assertEquals(FttAndRaidLevel.FTT2RAID1, + response.iterator().next().properties().failuresToTolerateAndRaidLevelValues().get(0)); + Assertions.assertEquals(AzureAvsNodeType.AV36, + response.iterator().next().properties().reservedInstanceAvsNodes().get(0)); + Assertions.assertEquals(AzureLocation.NORWAY_EAST, + response.iterator().next().properties().reservedInstanceSupportedLocations().get(0)); + Assertions.assertEquals(AzureCurrency.TWD, + response.iterator().next().properties().reservedInstanceSupportedCurrencies().get(0)); + Assertions.assertEquals(AzureOfferCode.MSMCAZR0060P, + response.iterator().next().properties().reservedInstanceSupportedOffers().get(0)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentOptionsPropertiesTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentOptionsPropertiesTests.java new file mode 100644 index 000000000000..ad00800e8f9f --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentOptionsPropertiesTests.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. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.AvsAssessmentOptionsProperties; +import com.azure.resourcemanager.migration.assessment.models.AvsSkuOptions; +import com.azure.resourcemanager.migration.assessment.models.AzureAvsNodeType; +import com.azure.resourcemanager.migration.assessment.models.AzureCurrency; +import com.azure.resourcemanager.migration.assessment.models.AzureLocation; +import com.azure.resourcemanager.migration.assessment.models.AzureOfferCode; +import com.azure.resourcemanager.migration.assessment.models.FttAndRaidLevel; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class AvsAssessmentOptionsPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AvsAssessmentOptionsProperties model = BinaryData.fromString( + "{\"avsNodes\":[{\"nodeType\":\"AV36\",\"targetLocations\":[\"SwitzerlandNorth\",\"CanadaCentral\",\"AustraliaCentral2\"]}],\"failuresToTolerateAndRaidLevelValues\":[\"Ftt2Raid6\",\"Ftt1Raid5\",\"Unknown\",\"Ftt1Raid1\"],\"reservedInstanceAvsNodes\":[\"AV36\",\"Unknown\"],\"reservedInstanceSupportedLocations\":[\"FranceSouth\",\"UsNatWest\",\"USGovVirginia\"],\"reservedInstanceSupportedCurrencies\":[\"MXN\",\"DKK\"],\"reservedInstanceSupportedOffers\":[\"Unknown\",\"MSMCAZR0059P\",\"MSAZR0125P\"]}") + .toObject(AvsAssessmentOptionsProperties.class); + Assertions.assertEquals(AzureAvsNodeType.AV36, model.avsNodes().get(0).nodeType()); + Assertions.assertEquals(AzureLocation.SWITZERLAND_NORTH, model.avsNodes().get(0).targetLocations().get(0)); + Assertions.assertEquals(FttAndRaidLevel.FTT2RAID6, model.failuresToTolerateAndRaidLevelValues().get(0)); + Assertions.assertEquals(AzureAvsNodeType.AV36, model.reservedInstanceAvsNodes().get(0)); + Assertions.assertEquals(AzureLocation.FRANCE_SOUTH, model.reservedInstanceSupportedLocations().get(0)); + Assertions.assertEquals(AzureCurrency.MXN, model.reservedInstanceSupportedCurrencies().get(0)); + Assertions.assertEquals(AzureOfferCode.UNKNOWN, model.reservedInstanceSupportedOffers().get(0)); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AvsAssessmentOptionsProperties model = new AvsAssessmentOptionsProperties() + .withAvsNodes(Arrays.asList(new AvsSkuOptions().withNodeType(AzureAvsNodeType.AV36) + .withTargetLocations(Arrays.asList(AzureLocation.SWITZERLAND_NORTH, AzureLocation.CANADA_CENTRAL, + AzureLocation.AUSTRALIA_CENTRAL2)))) + .withFailuresToTolerateAndRaidLevelValues(Arrays.asList(FttAndRaidLevel.FTT2RAID6, + FttAndRaidLevel.FTT1RAID5, FttAndRaidLevel.UNKNOWN, FttAndRaidLevel.FTT1RAID1)) + .withReservedInstanceAvsNodes(Arrays.asList(AzureAvsNodeType.AV36, AzureAvsNodeType.UNKNOWN)) + .withReservedInstanceSupportedLocations( + Arrays.asList(AzureLocation.FRANCE_SOUTH, AzureLocation.US_NAT_WEST, AzureLocation.USGOV_VIRGINIA)) + .withReservedInstanceSupportedCurrencies(Arrays.asList(AzureCurrency.MXN, AzureCurrency.DKK)) + .withReservedInstanceSupportedOffers( + Arrays.asList(AzureOfferCode.UNKNOWN, AzureOfferCode.MSMCAZR0059P, AzureOfferCode.MSAZR0125P)); + model = BinaryData.fromObject(model).toObject(AvsAssessmentOptionsProperties.class); + Assertions.assertEquals(AzureAvsNodeType.AV36, model.avsNodes().get(0).nodeType()); + Assertions.assertEquals(AzureLocation.SWITZERLAND_NORTH, model.avsNodes().get(0).targetLocations().get(0)); + Assertions.assertEquals(FttAndRaidLevel.FTT2RAID6, model.failuresToTolerateAndRaidLevelValues().get(0)); + Assertions.assertEquals(AzureAvsNodeType.AV36, model.reservedInstanceAvsNodes().get(0)); + Assertions.assertEquals(AzureLocation.FRANCE_SOUTH, model.reservedInstanceSupportedLocations().get(0)); + Assertions.assertEquals(AzureCurrency.MXN, model.reservedInstanceSupportedCurrencies().get(0)); + Assertions.assertEquals(AzureOfferCode.UNKNOWN, model.reservedInstanceSupportedOffers().get(0)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentsOperationsDeleteWithResponseMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentsOperationsDeleteWithResponseMockTests.java new file mode 100644 index 000000000000..f530b058f80d --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentsOperationsDeleteWithResponseMockTests.java @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class AvsAssessmentsOperationsDeleteWithResponseMockTests { + @Test + public void testDeleteWithResponse() throws Exception { + String responseStr = "{}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + manager.avsAssessmentsOperations() + .deleteWithResponse("g", "wdjuxdbdljzgdy", "cvuq", "sgzlrqhb", com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentsOperationsDownloadUrlMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentsOperationsDownloadUrlMockTests.java new file mode 100644 index 000000000000..3b2b298ded9b --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsAssessmentsOperationsDownloadUrlMockTests.java @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.DownloadUrl; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class AvsAssessmentsOperationsDownloadUrlMockTests { + @Test + public void testDownloadUrl() throws Exception { + String responseStr = "{\"assessmentReportUrl\":\"dzzqjmu\",\"expirationTime\":\"2021-11-30T17:24:02Z\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + DownloadUrl response = manager.avsAssessmentsOperations() + .downloadUrl("nq", "gdxwbsfpyxx", "jlf", "ecominxojjluxxd", "datailz", com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsSkuOptionsTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsSkuOptionsTests.java new file mode 100644 index 000000000000..85b8c369d5a4 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AvsSkuOptionsTests.java @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.AvsSkuOptions; +import com.azure.resourcemanager.migration.assessment.models.AzureAvsNodeType; +import com.azure.resourcemanager.migration.assessment.models.AzureLocation; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class AvsSkuOptionsTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AvsSkuOptions model + = BinaryData.fromString("{\"nodeType\":\"AV36\",\"targetLocations\":[\"SouthAfricaNorth\",\"WestUs2\"]}") + .toObject(AvsSkuOptions.class); + Assertions.assertEquals(AzureAvsNodeType.AV36, model.nodeType()); + Assertions.assertEquals(AzureLocation.SOUTH_AFRICA_NORTH, model.targetLocations().get(0)); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AvsSkuOptions model = new AvsSkuOptions().withNodeType(AzureAvsNodeType.AV36) + .withTargetLocations(Arrays.asList(AzureLocation.SOUTH_AFRICA_NORTH, AzureLocation.WEST_US2)); + model = BinaryData.fromObject(model).toObject(AvsSkuOptions.class); + Assertions.assertEquals(AzureAvsNodeType.AV36, model.nodeType()); + Assertions.assertEquals(AzureLocation.SOUTH_AFRICA_NORTH, model.targetLocations().get(0)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AzureManagedDiskSkuDtoTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AzureManagedDiskSkuDtoTests.java new file mode 100644 index 000000000000..9d559381de0c --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AzureManagedDiskSkuDtoTests.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.AzureManagedDiskSkuDto; + +public final class AzureManagedDiskSkuDtoTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AzureManagedDiskSkuDto model = BinaryData.fromString( + "{\"diskType\":\"PremiumV2\",\"diskSize\":\"StandardSSD_E80\",\"diskRedundancy\":\"ZRS\",\"storageCost\":45.557858,\"recommendedSizeInGib\":27.858305,\"recommendedThroughputInMbps\":40.938957,\"recommendedIops\":92.67548}") + .toObject(AzureManagedDiskSkuDto.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AzureManagedDiskSkuDto model = new AzureManagedDiskSkuDto(); + model = BinaryData.fromObject(model).toObject(AzureManagedDiskSkuDto.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AzureQuorumWitnessDtoTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AzureQuorumWitnessDtoTests.java new file mode 100644 index 000000000000..30c2b8332448 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AzureQuorumWitnessDtoTests.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.AzureQuorumWitnessDto; + +public final class AzureQuorumWitnessDtoTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AzureQuorumWitnessDto model + = BinaryData.fromString("{\"quorumWitnessType\":\"Unknown\"}").toObject(AzureQuorumWitnessDto.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AzureQuorumWitnessDto model = new AzureQuorumWitnessDto(); + model = BinaryData.fromObject(model).toObject(AzureQuorumWitnessDto.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AzureResourcePropertiesTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AzureResourcePropertiesTests.java new file mode 100644 index 000000000000..f51071f159ab --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AzureResourcePropertiesTests.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.AzureResourceProperties; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import org.junit.jupiter.api.Assertions; + +public final class AzureResourcePropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AzureResourceProperties model + = BinaryData.fromString("{\"provisioningState\":\"Deleting\"}").toObject(AzureResourceProperties.class); + Assertions.assertEquals(ProvisioningState.DELETING, model.provisioningState()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AzureResourceProperties model = new AzureResourceProperties().withProvisioningState(ProvisioningState.DELETING); + model = BinaryData.fromObject(model).toObject(AzureResourceProperties.class); + Assertions.assertEquals(ProvisioningState.DELETING, model.provisioningState()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AzureSqlIaasSkuDtoTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AzureSqlIaasSkuDtoTests.java new file mode 100644 index 000000000000..d24602d30ac2 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AzureSqlIaasSkuDtoTests.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.AzureSqlIaasSkuDto; + +public final class AzureSqlIaasSkuDtoTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AzureSqlIaasSkuDto model = BinaryData.fromString( + "{\"virtualMachineSize\":{\"azureVmFamily\":\"Edv5_series\",\"cores\":1029083448,\"azureSkuName\":\"Standard_D2as_v5\",\"availableCores\":1218728383,\"maxNetworkInterfaces\":617532608},\"dataDiskSizes\":[{\"diskType\":\"Premium\",\"diskSize\":\"Premium_P30\",\"diskRedundancy\":\"LRS\",\"storageCost\":37.59306,\"recommendedSizeInGib\":99.90342,\"recommendedThroughputInMbps\":43.10251,\"recommendedIops\":58.430733},{\"diskType\":\"Premium\",\"diskSize\":\"StandardSSD_E6\",\"diskRedundancy\":\"Unknown\",\"storageCost\":52.928745,\"recommendedSizeInGib\":44.91767,\"recommendedThroughputInMbps\":91.69271,\"recommendedIops\":61.968582},{\"diskType\":\"Standard\",\"diskSize\":\"StandardSSD_E70\",\"diskRedundancy\":\"ZRS\",\"storageCost\":40.48493,\"recommendedSizeInGib\":90.719376,\"recommendedThroughputInMbps\":48.726143,\"recommendedIops\":45.43301}],\"logDiskSizes\":[{\"diskType\":\"PremiumV2\",\"diskSize\":\"Premium_P1\",\"diskRedundancy\":\"LRS\",\"storageCost\":47.28567,\"recommendedSizeInGib\":64.00328,\"recommendedThroughputInMbps\":63.62545,\"recommendedIops\":91.40803}],\"azureSqlTargetType\":\"AzureVirtualMachine\"}") + .toObject(AzureSqlIaasSkuDto.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AzureSqlIaasSkuDto model = new AzureSqlIaasSkuDto(); + model = BinaryData.fromObject(model).toObject(AzureSqlIaasSkuDto.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AzureSqlPaasSkuDtoTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AzureSqlPaasSkuDtoTests.java new file mode 100644 index 000000000000..26466d9aa1d2 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AzureSqlPaasSkuDtoTests.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.AzureSqlPaasSkuDto; + +public final class AzureSqlPaasSkuDtoTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AzureSqlPaasSkuDto model = BinaryData.fromString( + "{\"azureSqlServiceTier\":\"Unknown\",\"azureSqlComputeTier\":\"Provisioned\",\"azureSqlHardwareGeneration\":\"Unknown\",\"storageMaxSizeInMB\":73.21512,\"predictedDataSizeInMB\":43.510838,\"predictedLogSizeInMB\":53.732086,\"cores\":1586436941,\"azureSqlTargetType\":\"Recommended\"}") + .toObject(AzureSqlPaasSkuDto.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AzureSqlPaasSkuDto model = new AzureSqlPaasSkuDto(); + model = BinaryData.fromObject(model).toObject(AzureSqlPaasSkuDto.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AzureVirtualMachineSkuDtoTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AzureVirtualMachineSkuDtoTests.java new file mode 100644 index 000000000000..b32b50b99bca --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/AzureVirtualMachineSkuDtoTests.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.AzureVirtualMachineSkuDto; + +public final class AzureVirtualMachineSkuDtoTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + AzureVirtualMachineSkuDto model = BinaryData.fromString( + "{\"azureVmFamily\":\"D_series\",\"cores\":1814498181,\"azureSkuName\":\"Standard_M64s_v2\",\"availableCores\":2136201648,\"maxNetworkInterfaces\":1242659668}") + .toObject(AzureVirtualMachineSkuDto.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + AzureVirtualMachineSkuDto model = new AzureVirtualMachineSkuDto(); + model = BinaryData.fromObject(model).toObject(AzureVirtualMachineSkuDto.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/CollectorAgentPropertiesBaseTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/CollectorAgentPropertiesBaseTests.java new file mode 100644 index 000000000000..55cd39987506 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/CollectorAgentPropertiesBaseTests.java @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentSpnPropertiesBase; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; + +public final class CollectorAgentPropertiesBaseTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + CollectorAgentPropertiesBase model = BinaryData.fromString( + "{\"id\":\"mbzmqk\",\"version\":\"tbnxwbjsid\",\"lastHeartbeatUtc\":\"2021-01-03T19:24:54Z\",\"spnDetails\":{\"authority\":\"pksokdgogew\",\"applicationId\":\"ym\",\"audience\":\"bguzozky\",\"objectId\":\"nfnzhhh\",\"tenantId\":\"smffjkutycyarnr\"}}") + .toObject(CollectorAgentPropertiesBase.class); + Assertions.assertEquals("mbzmqk", model.id()); + Assertions.assertEquals("tbnxwbjsid", model.version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-01-03T19:24:54Z"), model.lastHeartbeatUtc()); + Assertions.assertEquals("pksokdgogew", model.spnDetails().authority()); + Assertions.assertEquals("ym", model.spnDetails().applicationId()); + Assertions.assertEquals("bguzozky", model.spnDetails().audience()); + Assertions.assertEquals("nfnzhhh", model.spnDetails().objectId()); + Assertions.assertEquals("smffjkutycyarnr", model.spnDetails().tenantId()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + CollectorAgentPropertiesBase model = new CollectorAgentPropertiesBase().withId("mbzmqk") + .withVersion("tbnxwbjsid") + .withLastHeartbeatUtc(OffsetDateTime.parse("2021-01-03T19:24:54Z")) + .withSpnDetails(new CollectorAgentSpnPropertiesBase().withAuthority("pksokdgogew") + .withApplicationId("ym") + .withAudience("bguzozky") + .withObjectId("nfnzhhh") + .withTenantId("smffjkutycyarnr")); + model = BinaryData.fromObject(model).toObject(CollectorAgentPropertiesBase.class); + Assertions.assertEquals("mbzmqk", model.id()); + Assertions.assertEquals("tbnxwbjsid", model.version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-01-03T19:24:54Z"), model.lastHeartbeatUtc()); + Assertions.assertEquals("pksokdgogew", model.spnDetails().authority()); + Assertions.assertEquals("ym", model.spnDetails().applicationId()); + Assertions.assertEquals("bguzozky", model.spnDetails().audience()); + Assertions.assertEquals("nfnzhhh", model.spnDetails().objectId()); + Assertions.assertEquals("smffjkutycyarnr", model.spnDetails().tenantId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/CollectorAgentSpnPropertiesBaseTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/CollectorAgentSpnPropertiesBaseTests.java new file mode 100644 index 000000000000..43a2518f3343 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/CollectorAgentSpnPropertiesBaseTests.java @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentSpnPropertiesBase; +import org.junit.jupiter.api.Assertions; + +public final class CollectorAgentSpnPropertiesBaseTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + CollectorAgentSpnPropertiesBase model = BinaryData.fromString( + "{\"authority\":\"hguabzoghktdp\",\"applicationId\":\"z\",\"audience\":\"oeocnhzqrott\",\"objectId\":\"cfyjzp\",\"tenantId\":\"rl\"}") + .toObject(CollectorAgentSpnPropertiesBase.class); + Assertions.assertEquals("hguabzoghktdp", model.authority()); + Assertions.assertEquals("z", model.applicationId()); + Assertions.assertEquals("oeocnhzqrott", model.audience()); + Assertions.assertEquals("cfyjzp", model.objectId()); + Assertions.assertEquals("rl", model.tenantId()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + CollectorAgentSpnPropertiesBase model = new CollectorAgentSpnPropertiesBase().withAuthority("hguabzoghktdp") + .withApplicationId("z") + .withAudience("oeocnhzqrott") + .withObjectId("cfyjzp") + .withTenantId("rl"); + model = BinaryData.fromObject(model).toObject(CollectorAgentSpnPropertiesBase.class); + Assertions.assertEquals("hguabzoghktdp", model.authority()); + Assertions.assertEquals("z", model.applicationId()); + Assertions.assertEquals("oeocnhzqrott", model.audience()); + Assertions.assertEquals("cfyjzp", model.objectId()); + Assertions.assertEquals("rl", model.tenantId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/CollectorPropertiesBaseTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/CollectorPropertiesBaseTests.java new file mode 100644 index 000000000000..6fdd8792a3e1 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/CollectorPropertiesBaseTests.java @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import org.junit.jupiter.api.Assertions; + +public final class CollectorPropertiesBaseTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + CollectorPropertiesBase model = BinaryData.fromString( + "{\"discoverySiteId\":\"qkxrerl\",\"createdTimestamp\":\"2021-05-08T13:28:22Z\",\"updatedTimestamp\":\"2020-12-28T09:57:47Z\",\"provisioningState\":\"Failed\"}") + .toObject(CollectorPropertiesBase.class); + Assertions.assertEquals(ProvisioningState.FAILED, model.provisioningState()); + Assertions.assertEquals("qkxrerl", model.discoverySiteId()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + CollectorPropertiesBase model = new CollectorPropertiesBase().withProvisioningState(ProvisioningState.FAILED) + .withDiscoverySiteId("qkxrerl"); + model = BinaryData.fromObject(model).toObject(CollectorPropertiesBase.class); + Assertions.assertEquals(ProvisioningState.FAILED, model.provisioningState()); + Assertions.assertEquals("qkxrerl", model.discoverySiteId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/CollectorPropertiesBaseWithAgentTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/CollectorPropertiesBaseWithAgentTests.java new file mode 100644 index 000000000000..0de32d3202d4 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/CollectorPropertiesBaseWithAgentTests.java @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentSpnPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBaseWithAgent; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; + +public final class CollectorPropertiesBaseWithAgentTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + CollectorPropertiesBaseWithAgent model = BinaryData.fromString( + "{\"agentProperties\":{\"id\":\"ormkfqlwxldyk\",\"version\":\"sy\",\"lastHeartbeatUtc\":\"2021-08-24T12:28:36Z\",\"spnDetails\":{\"authority\":\"jpnnbmjksibjgsj\",\"applicationId\":\"xahmrnadzyqegxy\",\"audience\":\"pinbmhwbjijkgqxn\",\"objectId\":\"bkezn\",\"tenantId\":\"ujvaannggi\"}},\"discoverySiteId\":\"wkdtaawxwf\",\"createdTimestamp\":\"2021-05-27T21:19:02Z\",\"updatedTimestamp\":\"2021-08-31T11:37:22Z\",\"provisioningState\":\"Succeeded\"}") + .toObject(CollectorPropertiesBaseWithAgent.class); + Assertions.assertEquals(ProvisioningState.SUCCEEDED, model.provisioningState()); + Assertions.assertEquals("ormkfqlwxldyk", model.agentProperties().id()); + Assertions.assertEquals("sy", model.agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-08-24T12:28:36Z"), + model.agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("jpnnbmjksibjgsj", model.agentProperties().spnDetails().authority()); + Assertions.assertEquals("xahmrnadzyqegxy", model.agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("pinbmhwbjijkgqxn", model.agentProperties().spnDetails().audience()); + Assertions.assertEquals("bkezn", model.agentProperties().spnDetails().objectId()); + Assertions.assertEquals("ujvaannggi", model.agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("wkdtaawxwf", model.discoverySiteId()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + CollectorPropertiesBaseWithAgent model + = new CollectorPropertiesBaseWithAgent().withProvisioningState(ProvisioningState.SUCCEEDED) + .withAgentProperties(new CollectorAgentPropertiesBase().withId("ormkfqlwxldyk") + .withVersion("sy") + .withLastHeartbeatUtc(OffsetDateTime.parse("2021-08-24T12:28:36Z")) + .withSpnDetails(new CollectorAgentSpnPropertiesBase().withAuthority("jpnnbmjksibjgsj") + .withApplicationId("xahmrnadzyqegxy") + .withAudience("pinbmhwbjijkgqxn") + .withObjectId("bkezn") + .withTenantId("ujvaannggi"))) + .withDiscoverySiteId("wkdtaawxwf"); + model = BinaryData.fromObject(model).toObject(CollectorPropertiesBaseWithAgent.class); + Assertions.assertEquals(ProvisioningState.SUCCEEDED, model.provisioningState()); + Assertions.assertEquals("ormkfqlwxldyk", model.agentProperties().id()); + Assertions.assertEquals("sy", model.agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-08-24T12:28:36Z"), + model.agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("jpnnbmjksibjgsj", model.agentProperties().spnDetails().authority()); + Assertions.assertEquals("xahmrnadzyqegxy", model.agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("pinbmhwbjijkgqxn", model.agentProperties().spnDetails().audience()); + Assertions.assertEquals("bkezn", model.agentProperties().spnDetails().objectId()); + Assertions.assertEquals("ujvaannggi", model.agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("wkdtaawxwf", model.discoverySiteId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/CostComponentTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/CostComponentTests.java new file mode 100644 index 000000000000..4a6f1a0b1cb5 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/CostComponentTests.java @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.CostComponent; +import org.junit.jupiter.api.Assertions; + +public final class CostComponentTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + CostComponent model = BinaryData + .fromString("{\"name\":\"MonthlySecurityCost\",\"value\":2.368176,\"description\":\"hykojoxafnndlpic\"}") + .toObject(CostComponent.class); + Assertions.assertEquals(2.368176F, model.value()); + Assertions.assertEquals("hykojoxafnndlpic", model.description()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + CostComponent model = new CostComponent().withValue(2.368176F).withDescription("hykojoxafnndlpic"); + model = BinaryData.fromObject(model).toObject(CostComponent.class); + Assertions.assertEquals(2.368176F, model.value()); + Assertions.assertEquals("hykojoxafnndlpic", model.description()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/DiskTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/DiskTests.java new file mode 100644 index 000000000000..f23e8a763854 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/DiskTests.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.Disk; + +public final class DiskTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + Disk model = BinaryData.fromString("{\"gigabytesAllocated\":99.23195,\"displayName\":\"wwnlzafwxudgnh\"}") + .toObject(Disk.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + Disk model = new Disk(); + model = BinaryData.fromObject(model).toObject(Disk.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/DownloadUrlInnerTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/DownloadUrlInnerTests.java new file mode 100644 index 000000000000..51497a393fd9 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/DownloadUrlInnerTests.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.DownloadUrlInner; + +public final class DownloadUrlInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + DownloadUrlInner model + = BinaryData.fromString("{\"assessmentReportUrl\":\"h\",\"expirationTime\":\"2021-07-08T09:31:36Z\"}") + .toObject(DownloadUrlInner.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + DownloadUrlInner model = new DownloadUrlInner(); + model = BinaryData.fromObject(model).toObject(DownloadUrlInner.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/EntityUptimeTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/EntityUptimeTests.java new file mode 100644 index 000000000000..a3adde0bbcdd --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/EntityUptimeTests.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.EntityUptime; +import org.junit.jupiter.api.Assertions; + +public final class EntityUptimeTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + EntityUptime model = BinaryData.fromString("{\"daysPerMonth\":887664704,\"hoursPerDay\":354248500}") + .toObject(EntityUptime.class); + Assertions.assertEquals(887664704, model.daysPerMonth()); + Assertions.assertEquals(354248500, model.hoursPerDay()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + EntityUptime model = new EntityUptime().withDaysPerMonth(887664704).withHoursPerDay(354248500); + model = BinaryData.fromObject(model).toObject(EntityUptime.class); + Assertions.assertEquals(887664704, model.daysPerMonth()); + Assertions.assertEquals(354248500, model.hoursPerDay()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ErrorSummaryTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ErrorSummaryTests.java new file mode 100644 index 000000000000..fed7c01815cb --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ErrorSummaryTests.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.ErrorSummary; + +public final class ErrorSummaryTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + ErrorSummary model = BinaryData.fromString("{\"assessmentType\":\"MachineAssessment\",\"count\":877780052}") + .toObject(ErrorSummary.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + ErrorSummary model = new ErrorSummary(); + model = BinaryData.fromObject(model).toObject(ErrorSummary.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/GroupBodyPropertiesTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/GroupBodyPropertiesTests.java new file mode 100644 index 000000000000..da1314138147 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/GroupBodyPropertiesTests.java @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.GroupBodyProperties; +import com.azure.resourcemanager.migration.assessment.models.GroupUpdateOperation; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class GroupBodyPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + GroupBodyProperties model + = BinaryData.fromString("{\"operationType\":\"Remove\",\"machines\":[\"pmvssehaep\"]}") + .toObject(GroupBodyProperties.class); + Assertions.assertEquals(GroupUpdateOperation.REMOVE, model.operationType()); + Assertions.assertEquals("pmvssehaep", model.machines().get(0)); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + GroupBodyProperties model = new GroupBodyProperties().withOperationType(GroupUpdateOperation.REMOVE) + .withMachines(Arrays.asList("pmvssehaep")); + model = BinaryData.fromObject(model).toObject(GroupBodyProperties.class); + Assertions.assertEquals(GroupUpdateOperation.REMOVE, model.operationType()); + Assertions.assertEquals("pmvssehaep", model.machines().get(0)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/GroupInnerTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/GroupInnerTests.java new file mode 100644 index 000000000000..88b701755dfc --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/GroupInnerTests.java @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.GroupInner; +import com.azure.resourcemanager.migration.assessment.models.AssessmentType; +import com.azure.resourcemanager.migration.assessment.models.GroupProperties; +import com.azure.resourcemanager.migration.assessment.models.GroupType; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class GroupInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + GroupInner model = BinaryData.fromString( + "{\"properties\":{\"groupStatus\":\"Updated\",\"machineCount\":655886827,\"assessments\":[\"cgjbirxbp\",\"bsrfbj\",\"dtws\"],\"supportedAssessmentTypes\":[\"Unknown\"],\"areAssessmentsRunning\":false,\"createdTimestamp\":\"2021-01-31T07:10:37Z\",\"updatedTimestamp\":\"2021-12-05T15:12:17Z\",\"groupType\":\"Default\",\"provisioningState\":\"Failed\"},\"id\":\"znfqqnvwpmqtar\",\"name\":\"oujmkcjhwqytj\",\"type\":\"ybn\"}") + .toObject(GroupInner.class); + Assertions.assertEquals(ProvisioningState.FAILED, model.properties().provisioningState()); + Assertions.assertEquals(AssessmentType.UNKNOWN, model.properties().supportedAssessmentTypes().get(0)); + Assertions.assertEquals(GroupType.DEFAULT, model.properties().groupType()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + GroupInner model + = new GroupInner().withProperties(new GroupProperties().withProvisioningState(ProvisioningState.FAILED) + .withSupportedAssessmentTypes(Arrays.asList(AssessmentType.UNKNOWN)) + .withGroupType(GroupType.DEFAULT)); + model = BinaryData.fromObject(model).toObject(GroupInner.class); + Assertions.assertEquals(ProvisioningState.FAILED, model.properties().provisioningState()); + Assertions.assertEquals(AssessmentType.UNKNOWN, model.properties().supportedAssessmentTypes().get(0)); + Assertions.assertEquals(GroupType.DEFAULT, model.properties().groupType()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/GroupListResultTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/GroupListResultTests.java new file mode 100644 index 000000000000..7bd0dc1766a2 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/GroupListResultTests.java @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.GroupInner; +import com.azure.resourcemanager.migration.assessment.models.AssessmentType; +import com.azure.resourcemanager.migration.assessment.models.GroupListResult; +import com.azure.resourcemanager.migration.assessment.models.GroupProperties; +import com.azure.resourcemanager.migration.assessment.models.GroupType; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class GroupListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + GroupListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"groupStatus\":\"Invalid\",\"machineCount\":1172989545,\"assessments\":[\"moizpos\",\"mgrcfbu\",\"rmfqjhhkxbpvj\"],\"supportedAssessmentTypes\":[\"MachineAssessment\",\"AvsAssessment\"],\"areAssessmentsRunning\":false,\"createdTimestamp\":\"2021-02-21T04:56:22Z\",\"updatedTimestamp\":\"2021-02-07T09:11:24Z\",\"groupType\":\"Default\",\"provisioningState\":\"Succeeded\"},\"id\":\"tswb\",\"name\":\"qzvszjf\",\"type\":\"uvjfdxxive\"},{\"properties\":{\"groupStatus\":\"Running\",\"machineCount\":393815457,\"assessments\":[\"doqmcbxvwvxys\"],\"supportedAssessmentTypes\":[\"SqlAssessment\",\"MachineAssessment\"],\"areAssessmentsRunning\":true,\"createdTimestamp\":\"2021-01-17T13:22:14Z\",\"updatedTimestamp\":\"2021-08-05T08:56:45Z\",\"groupType\":\"Default\",\"provisioningState\":\"Canceled\"},\"id\":\"pe\",\"name\":\"wwfbkrvrnsvshq\",\"type\":\"ohxcrsbfova\"}],\"nextLink\":\"ruvw\"}") + .toObject(GroupListResult.class); + Assertions.assertEquals(ProvisioningState.SUCCEEDED, model.value().get(0).properties().provisioningState()); + Assertions.assertEquals(AssessmentType.MACHINE_ASSESSMENT, + model.value().get(0).properties().supportedAssessmentTypes().get(0)); + Assertions.assertEquals(GroupType.DEFAULT, model.value().get(0).properties().groupType()); + Assertions.assertEquals("ruvw", model.nextLink()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + GroupListResult model = new GroupListResult().withValue(Arrays.asList( + new GroupInner().withProperties(new GroupProperties().withProvisioningState(ProvisioningState.SUCCEEDED) + .withSupportedAssessmentTypes( + Arrays.asList(AssessmentType.MACHINE_ASSESSMENT, AssessmentType.AVS_ASSESSMENT)) + .withGroupType(GroupType.DEFAULT)), + new GroupInner().withProperties(new GroupProperties().withProvisioningState(ProvisioningState.CANCELED) + .withSupportedAssessmentTypes( + Arrays.asList(AssessmentType.SQL_ASSESSMENT, AssessmentType.MACHINE_ASSESSMENT)) + .withGroupType(GroupType.DEFAULT)))) + .withNextLink("ruvw"); + model = BinaryData.fromObject(model).toObject(GroupListResult.class); + Assertions.assertEquals(ProvisioningState.SUCCEEDED, model.value().get(0).properties().provisioningState()); + Assertions.assertEquals(AssessmentType.MACHINE_ASSESSMENT, + model.value().get(0).properties().supportedAssessmentTypes().get(0)); + Assertions.assertEquals(GroupType.DEFAULT, model.value().get(0).properties().groupType()); + Assertions.assertEquals("ruvw", model.nextLink()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/GroupPropertiesTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/GroupPropertiesTests.java new file mode 100644 index 000000000000..694622f851fd --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/GroupPropertiesTests.java @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.AssessmentType; +import com.azure.resourcemanager.migration.assessment.models.GroupProperties; +import com.azure.resourcemanager.migration.assessment.models.GroupType; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class GroupPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + GroupProperties model = BinaryData.fromString( + "{\"groupStatus\":\"Created\",\"machineCount\":1598094804,\"assessments\":[\"jervnaenqpehi\",\"doy\"],\"supportedAssessmentTypes\":[\"Unknown\",\"MachineAssessment\"],\"areAssessmentsRunning\":true,\"createdTimestamp\":\"2021-02-11T01:14:35Z\",\"updatedTimestamp\":\"2021-02-21T18:42:47Z\",\"groupType\":\"Default\",\"provisioningState\":\"Accepted\"}") + .toObject(GroupProperties.class); + Assertions.assertEquals(ProvisioningState.ACCEPTED, model.provisioningState()); + Assertions.assertEquals(AssessmentType.UNKNOWN, model.supportedAssessmentTypes().get(0)); + Assertions.assertEquals(GroupType.DEFAULT, model.groupType()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + GroupProperties model = new GroupProperties().withProvisioningState(ProvisioningState.ACCEPTED) + .withSupportedAssessmentTypes(Arrays.asList(AssessmentType.UNKNOWN, AssessmentType.MACHINE_ASSESSMENT)) + .withGroupType(GroupType.DEFAULT); + model = BinaryData.fromObject(model).toObject(GroupProperties.class); + Assertions.assertEquals(ProvisioningState.ACCEPTED, model.provisioningState()); + Assertions.assertEquals(AssessmentType.UNKNOWN, model.supportedAssessmentTypes().get(0)); + Assertions.assertEquals(GroupType.DEFAULT, model.groupType()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsCreateMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsCreateMockTests.java new file mode 100644 index 000000000000..f2d05b0f95de --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsCreateMockTests.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.AssessmentType; +import com.azure.resourcemanager.migration.assessment.models.Group; +import com.azure.resourcemanager.migration.assessment.models.GroupProperties; +import com.azure.resourcemanager.migration.assessment.models.GroupType; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class GroupsOperationsCreateMockTests { + @Test + public void testCreate() throws Exception { + String responseStr + = "{\"properties\":{\"groupStatus\":\"Running\",\"machineCount\":1655801360,\"assessments\":[\"lbvgwzsf\",\"tedousnktjtgrava\",\"ogfkbebauzlqb\",\"xxw\"],\"supportedAssessmentTypes\":[\"AvsAssessment\"],\"areAssessmentsRunning\":false,\"createdTimestamp\":\"2021-04-25T18:33:04Z\",\"updatedTimestamp\":\"2021-07-31T04:59:21Z\",\"groupType\":\"Default\",\"provisioningState\":\"Succeeded\"},\"id\":\"eboywhczzqrhm\",\"name\":\"gqbedygi\",\"type\":\"rzwnyk\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + Group response = manager.groupsOperations() + .define("gazlsvbz") + .withExistingAssessmentProject("csklhsidsjt", "lpbnin") + .withProperties(new GroupProperties().withProvisioningState(ProvisioningState.SUCCEEDED) + .withSupportedAssessmentTypes( + Arrays.asList(AssessmentType.WEB_APP_ASSESSMENT, AssessmentType.WEB_APP_ASSESSMENT)) + .withGroupType(GroupType.DEFAULT)) + .create(); + + Assertions.assertEquals(ProvisioningState.SUCCEEDED, response.properties().provisioningState()); + Assertions.assertEquals(AssessmentType.AVS_ASSESSMENT, response.properties().supportedAssessmentTypes().get(0)); + Assertions.assertEquals(GroupType.DEFAULT, response.properties().groupType()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsDeleteWithResponseMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsDeleteWithResponseMockTests.java new file mode 100644 index 000000000000..f33e47dc5054 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsDeleteWithResponseMockTests.java @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class GroupsOperationsDeleteWithResponseMockTests { + @Test + public void testDeleteWithResponse() throws Exception { + String responseStr = "{}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + manager.groupsOperations() + .deleteWithResponse("chlutixmqru", "jizcbfzmcrunfhiu", "nmfbc", com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsGetWithResponseMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsGetWithResponseMockTests.java new file mode 100644 index 000000000000..36028fc516fb --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsGetWithResponseMockTests.java @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.AssessmentType; +import com.azure.resourcemanager.migration.assessment.models.Group; +import com.azure.resourcemanager.migration.assessment.models.GroupType; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class GroupsOperationsGetWithResponseMockTests { + @Test + public void testGetWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"groupStatus\":\"Completed\",\"machineCount\":102893037,\"assessments\":[\"iprnzcalincry\",\"xzxaqzibmqimiym\",\"ruqg\"],\"supportedAssessmentTypes\":[\"SqlAssessment\",\"WebAppAssessment\",\"MachineAssessment\"],\"areAssessmentsRunning\":true,\"createdTimestamp\":\"2021-09-25T07:34:08Z\",\"updatedTimestamp\":\"2021-01-30T09:52:55Z\",\"groupType\":\"Default\",\"provisioningState\":\"Deleting\"},\"id\":\"flanfkgxsyao\",\"name\":\"uzowpuohdkcpr\",\"type\":\"ukxrzti\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + Group response = manager.groupsOperations() + .getWithResponse("fcmfcn", "jajqmatxjt", "elnzqgxxgfbbmt", com.azure.core.util.Context.NONE) + .getValue(); + + Assertions.assertEquals(ProvisioningState.DELETING, response.properties().provisioningState()); + Assertions.assertEquals(AssessmentType.SQL_ASSESSMENT, response.properties().supportedAssessmentTypes().get(0)); + Assertions.assertEquals(GroupType.DEFAULT, response.properties().groupType()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsListByAssessmentProjectMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsListByAssessmentProjectMockTests.java new file mode 100644 index 000000000000..3e48d64884fd --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsListByAssessmentProjectMockTests.java @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.AssessmentType; +import com.azure.resourcemanager.migration.assessment.models.Group; +import com.azure.resourcemanager.migration.assessment.models.GroupType; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class GroupsOperationsListByAssessmentProjectMockTests { + @Test + public void testListByAssessmentProject() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"groupStatus\":\"Completed\",\"machineCount\":1660222132,\"assessments\":[\"abjqqaxuyvymcnud\",\"doabhj\"],\"supportedAssessmentTypes\":[\"MachineAssessment\",\"Unknown\"],\"areAssessmentsRunning\":false,\"createdTimestamp\":\"2021-05-22T15:15:36Z\",\"updatedTimestamp\":\"2021-05-10T02:13:14Z\",\"groupType\":\"Import\",\"provisioningState\":\"Canceled\"},\"id\":\"tnsqxtlt\",\"name\":\"lkrdpqgfhy\",\"type\":\"frakkldgrc\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response + = manager.groupsOperations().listByAssessmentProject("zm", "n", com.azure.core.util.Context.NONE); + + Assertions.assertEquals(ProvisioningState.CANCELED, + response.iterator().next().properties().provisioningState()); + Assertions.assertEquals(AssessmentType.MACHINE_ASSESSMENT, + response.iterator().next().properties().supportedAssessmentTypes().get(0)); + Assertions.assertEquals(GroupType.IMPORT, response.iterator().next().properties().groupType()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsUpdateMachinesMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsUpdateMachinesMockTests.java new file mode 100644 index 000000000000..eab4ea734d25 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/GroupsOperationsUpdateMachinesMockTests.java @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.AssessmentType; +import com.azure.resourcemanager.migration.assessment.models.Group; +import com.azure.resourcemanager.migration.assessment.models.GroupBodyProperties; +import com.azure.resourcemanager.migration.assessment.models.GroupType; +import com.azure.resourcemanager.migration.assessment.models.GroupUpdateOperation; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import com.azure.resourcemanager.migration.assessment.models.UpdateGroupBody; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class GroupsOperationsUpdateMachinesMockTests { + @Test + public void testUpdateMachines() throws Exception { + String responseStr + = "{\"properties\":{\"groupStatus\":\"Invalid\",\"machineCount\":2066098356,\"assessments\":[\"ulndhzyoeo\",\"ht\",\"llhsvidmyt\",\"l\"],\"supportedAssessmentTypes\":[\"MachineAssessment\",\"Unknown\",\"WebAppAssessment\"],\"areAssessmentsRunning\":true,\"createdTimestamp\":\"2021-03-05T10:18:22Z\",\"updatedTimestamp\":\"2020-12-23T04:34:54Z\",\"groupType\":\"Import\",\"provisioningState\":\"Succeeded\"},\"id\":\"qagywvtxig\",\"name\":\"jrktpgaeukya\",\"type\":\"ohpmwhqn\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + Group response = manager.groupsOperations() + .updateMachines("aqktkrumzu", "dkyzbfvxov", "kxiuxqggvqr", + new UpdateGroupBody().withEtag("yhlwcjsqg") + .withProperties(new GroupBodyProperties().withOperationType(GroupUpdateOperation.REMOVE) + .withMachines(Arrays.asList("xrqrkijpeuqlsd", "eqztvxwmwwm", "swenawwa"))), + com.azure.core.util.Context.NONE); + + Assertions.assertEquals(ProvisioningState.SUCCEEDED, response.properties().provisioningState()); + Assertions.assertEquals(AssessmentType.MACHINE_ASSESSMENT, + response.properties().supportedAssessmentTypes().get(0)); + Assertions.assertEquals(GroupType.IMPORT, response.properties().groupType()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorInnerTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorInnerTests.java new file mode 100644 index 000000000000..fda66d24d6c5 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorInnerTests.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.HypervCollectorInner; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentSpnPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBaseWithAgent; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; + +public final class HypervCollectorInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + HypervCollectorInner model = BinaryData.fromString( + "{\"properties\":{\"agentProperties\":{\"id\":\"qwodiffjx\",\"version\":\"rmmuabwibvjo\",\"lastHeartbeatUtc\":\"2021-01-05T12:54:17Z\",\"spnDetails\":{\"authority\":\"cyefoyzbamwine\",\"applicationId\":\"vfkakpold\",\"audience\":\"evboclzhzjknyuxg\",\"objectId\":\"txpnrupza\",\"tenantId\":\"rdixt\"}},\"discoverySiteId\":\"kidswys\",\"createdTimestamp\":\"2021-08-12T20:46:57Z\",\"updatedTimestamp\":\"2021-04-18T19:34:30Z\",\"provisioningState\":\"Accepted\"},\"id\":\"lukkutvlxhrpqhvm\",\"name\":\"lcouqehbhbcdszir\",\"type\":\"randoypmb\"}") + .toObject(HypervCollectorInner.class); + Assertions.assertEquals(ProvisioningState.ACCEPTED, model.properties().provisioningState()); + Assertions.assertEquals("qwodiffjx", model.properties().agentProperties().id()); + Assertions.assertEquals("rmmuabwibvjo", model.properties().agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-01-05T12:54:17Z"), + model.properties().agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("cyefoyzbamwine", model.properties().agentProperties().spnDetails().authority()); + Assertions.assertEquals("vfkakpold", model.properties().agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("evboclzhzjknyuxg", model.properties().agentProperties().spnDetails().audience()); + Assertions.assertEquals("txpnrupza", model.properties().agentProperties().spnDetails().objectId()); + Assertions.assertEquals("rdixt", model.properties().agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("kidswys", model.properties().discoverySiteId()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + HypervCollectorInner model = new HypervCollectorInner() + .withProperties(new CollectorPropertiesBaseWithAgent().withProvisioningState(ProvisioningState.ACCEPTED) + .withAgentProperties(new CollectorAgentPropertiesBase().withId("qwodiffjx") + .withVersion("rmmuabwibvjo") + .withLastHeartbeatUtc(OffsetDateTime.parse("2021-01-05T12:54:17Z")) + .withSpnDetails(new CollectorAgentSpnPropertiesBase().withAuthority("cyefoyzbamwine") + .withApplicationId("vfkakpold") + .withAudience("evboclzhzjknyuxg") + .withObjectId("txpnrupza") + .withTenantId("rdixt"))) + .withDiscoverySiteId("kidswys")); + model = BinaryData.fromObject(model).toObject(HypervCollectorInner.class); + Assertions.assertEquals(ProvisioningState.ACCEPTED, model.properties().provisioningState()); + Assertions.assertEquals("qwodiffjx", model.properties().agentProperties().id()); + Assertions.assertEquals("rmmuabwibvjo", model.properties().agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-01-05T12:54:17Z"), + model.properties().agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("cyefoyzbamwine", model.properties().agentProperties().spnDetails().authority()); + Assertions.assertEquals("vfkakpold", model.properties().agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("evboclzhzjknyuxg", model.properties().agentProperties().spnDetails().audience()); + Assertions.assertEquals("txpnrupza", model.properties().agentProperties().spnDetails().objectId()); + Assertions.assertEquals("rdixt", model.properties().agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("kidswys", model.properties().discoverySiteId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorListResultTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorListResultTests.java new file mode 100644 index 000000000000..54bb91b2c625 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorListResultTests.java @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.HypervCollectorInner; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentSpnPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBaseWithAgent; +import com.azure.resourcemanager.migration.assessment.models.HypervCollectorListResult; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.time.OffsetDateTime; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class HypervCollectorListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + HypervCollectorListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"agentProperties\":{\"id\":\"tczhupeuknijd\",\"version\":\"yespydjfbocyv\",\"lastHeartbeatUtc\":\"2021-02-09T06:15:43Z\",\"spnDetails\":{\"authority\":\"tywikd\",\"applicationId\":\"lakuflgbhgauacd\",\"audience\":\"mxu\",\"objectId\":\"sryjqgdkfno\",\"tenantId\":\"eoqbvjhvefgwbmqj\"}},\"discoverySiteId\":\"ntasfaymxbu\",\"createdTimestamp\":\"2021-06-23T05:18:51Z\",\"updatedTimestamp\":\"2021-04-19T02:13:28Z\",\"provisioningState\":\"Accepted\"},\"id\":\"qkyojwyvf\",\"name\":\"mbtsuahxsg\",\"type\":\"jcmmzrrscub\"}],\"nextLink\":\"sd\"}") + .toObject(HypervCollectorListResult.class); + Assertions.assertEquals(ProvisioningState.ACCEPTED, model.value().get(0).properties().provisioningState()); + Assertions.assertEquals("tczhupeuknijd", model.value().get(0).properties().agentProperties().id()); + Assertions.assertEquals("yespydjfbocyv", model.value().get(0).properties().agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-02-09T06:15:43Z"), + model.value().get(0).properties().agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("tywikd", model.value().get(0).properties().agentProperties().spnDetails().authority()); + Assertions.assertEquals("lakuflgbhgauacd", + model.value().get(0).properties().agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("mxu", model.value().get(0).properties().agentProperties().spnDetails().audience()); + Assertions.assertEquals("sryjqgdkfno", + model.value().get(0).properties().agentProperties().spnDetails().objectId()); + Assertions.assertEquals("eoqbvjhvefgwbmqj", + model.value().get(0).properties().agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("ntasfaymxbu", model.value().get(0).properties().discoverySiteId()); + Assertions.assertEquals("sd", model.nextLink()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + HypervCollectorListResult model + = new HypervCollectorListResult().withValue(Arrays.asList(new HypervCollectorInner() + .withProperties(new CollectorPropertiesBaseWithAgent().withProvisioningState(ProvisioningState.ACCEPTED) + .withAgentProperties(new CollectorAgentPropertiesBase().withId("tczhupeuknijd") + .withVersion("yespydjfbocyv") + .withLastHeartbeatUtc(OffsetDateTime.parse("2021-02-09T06:15:43Z")) + .withSpnDetails(new CollectorAgentSpnPropertiesBase().withAuthority("tywikd") + .withApplicationId("lakuflgbhgauacd") + .withAudience("mxu") + .withObjectId("sryjqgdkfno") + .withTenantId("eoqbvjhvefgwbmqj"))) + .withDiscoverySiteId("ntasfaymxbu")))) + .withNextLink("sd"); + model = BinaryData.fromObject(model).toObject(HypervCollectorListResult.class); + Assertions.assertEquals(ProvisioningState.ACCEPTED, model.value().get(0).properties().provisioningState()); + Assertions.assertEquals("tczhupeuknijd", model.value().get(0).properties().agentProperties().id()); + Assertions.assertEquals("yespydjfbocyv", model.value().get(0).properties().agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-02-09T06:15:43Z"), + model.value().get(0).properties().agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("tywikd", model.value().get(0).properties().agentProperties().spnDetails().authority()); + Assertions.assertEquals("lakuflgbhgauacd", + model.value().get(0).properties().agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("mxu", model.value().get(0).properties().agentProperties().spnDetails().audience()); + Assertions.assertEquals("sryjqgdkfno", + model.value().get(0).properties().agentProperties().spnDetails().objectId()); + Assertions.assertEquals("eoqbvjhvefgwbmqj", + model.value().get(0).properties().agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("ntasfaymxbu", model.value().get(0).properties().discoverySiteId()); + Assertions.assertEquals("sd", model.nextLink()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorsOperationsCreateMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorsOperationsCreateMockTests.java new file mode 100644 index 000000000000..56d4773fd6d7 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorsOperationsCreateMockTests.java @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentSpnPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBaseWithAgent; +import com.azure.resourcemanager.migration.assessment.models.HypervCollector; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class HypervCollectorsOperationsCreateMockTests { + @Test + public void testCreate() throws Exception { + String responseStr + = "{\"properties\":{\"agentProperties\":{\"id\":\"mnoiicsudy\",\"version\":\"rjjtalxrdsjrho\",\"lastHeartbeatUtc\":\"2021-12-05T02:21:08Z\",\"spnDetails\":{\"authority\":\"usxxhdodpjwybl\",\"applicationId\":\"bdmvsby\",\"audience\":\"aelqpvekmkwjf\",\"objectId\":\"tlo\",\"tenantId\":\"dusxurs\"}},\"discoverySiteId\":\"v\",\"createdTimestamp\":\"2021-08-13T13:47:43Z\",\"updatedTimestamp\":\"2021-06-18T04:59:27Z\",\"provisioningState\":\"Succeeded\"},\"id\":\"w\",\"name\":\"z\",\"type\":\"yiqrizf\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + HypervCollector response = manager.hypervCollectorsOperations() + .define("mbtple") + .withExistingAssessmentProject("vrdmvxyrxdh", "vqojbxaotcgbz") + .withProperties(new CollectorPropertiesBaseWithAgent().withProvisioningState(ProvisioningState.SUCCEEDED) + .withAgentProperties(new CollectorAgentPropertiesBase().withId("yidoxznvg") + .withVersion("tmuuvdawsx") + .withLastHeartbeatUtc(OffsetDateTime.parse("2021-02-17T03:12:37Z")) + .withSpnDetails(new CollectorAgentSpnPropertiesBase().withAuthority("knimxlp") + .withApplicationId("rxrzutylcur") + .withAudience("q") + .withObjectId("b") + .withTenantId("aehtd"))) + .withDiscoverySiteId("mbnvynfaooeacted")) + .create(); + + Assertions.assertEquals(ProvisioningState.SUCCEEDED, response.properties().provisioningState()); + Assertions.assertEquals("mnoiicsudy", response.properties().agentProperties().id()); + Assertions.assertEquals("rjjtalxrdsjrho", response.properties().agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-12-05T02:21:08Z"), + response.properties().agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("usxxhdodpjwybl", response.properties().agentProperties().spnDetails().authority()); + Assertions.assertEquals("bdmvsby", response.properties().agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("aelqpvekmkwjf", response.properties().agentProperties().spnDetails().audience()); + Assertions.assertEquals("tlo", response.properties().agentProperties().spnDetails().objectId()); + Assertions.assertEquals("dusxurs", response.properties().agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("v", response.properties().discoverySiteId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorsOperationsDeleteWithResponseMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorsOperationsDeleteWithResponseMockTests.java new file mode 100644 index 000000000000..4debaa0a3177 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorsOperationsDeleteWithResponseMockTests.java @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class HypervCollectorsOperationsDeleteWithResponseMockTests { + @Test + public void testDeleteWithResponse() throws Exception { + String responseStr = "{}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + manager.hypervCollectorsOperations() + .deleteWithResponse("y", "pnml", "iqcpszpmcvq", com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorsOperationsGetWithResponseMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorsOperationsGetWithResponseMockTests.java new file mode 100644 index 000000000000..93300230835a --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorsOperationsGetWithResponseMockTests.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.HypervCollector; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class HypervCollectorsOperationsGetWithResponseMockTests { + @Test + public void testGetWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"agentProperties\":{\"id\":\"piilhvtozy\",\"version\":\"jjnxkby\",\"lastHeartbeatUtc\":\"2021-08-02T23:43:07Z\",\"spnDetails\":{\"authority\":\"gffklvqzr\",\"applicationId\":\"rdgscnvqeonsgn\",\"audience\":\"lwmezyohxpthceop\",\"objectId\":\"vtwfvesobpbokhm\",\"tenantId\":\"cdyarnggcjfwblqh\"}},\"discoverySiteId\":\"asmcolmugpyvaos\",\"createdTimestamp\":\"2021-10-04T02:15:18Z\",\"updatedTimestamp\":\"2021-09-24T23:31:20Z\",\"provisioningState\":\"Provisioning\"},\"id\":\"ygz\",\"name\":\"tyevjhu\",\"type\":\"nobguqisqsqkpdmi\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + HypervCollector response = manager.hypervCollectorsOperations() + .getWithResponse("ermhzicsbfdjhyaa", "nyukibx", "glhphzwx", com.azure.core.util.Context.NONE) + .getValue(); + + Assertions.assertEquals(ProvisioningState.PROVISIONING, response.properties().provisioningState()); + Assertions.assertEquals("piilhvtozy", response.properties().agentProperties().id()); + Assertions.assertEquals("jjnxkby", response.properties().agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-08-02T23:43:07Z"), + response.properties().agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("gffklvqzr", response.properties().agentProperties().spnDetails().authority()); + Assertions.assertEquals("rdgscnvqeonsgn", response.properties().agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("lwmezyohxpthceop", response.properties().agentProperties().spnDetails().audience()); + Assertions.assertEquals("vtwfvesobpbokhm", response.properties().agentProperties().spnDetails().objectId()); + Assertions.assertEquals("cdyarnggcjfwblqh", response.properties().agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("asmcolmugpyvaos", response.properties().discoverySiteId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorsOperationsListByAssessmentProjectMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorsOperationsListByAssessmentProjectMockTests.java new file mode 100644 index 000000000000..4772b5745225 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/HypervCollectorsOperationsListByAssessmentProjectMockTests.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. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.HypervCollector; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class HypervCollectorsOperationsListByAssessmentProjectMockTests { + @Test + public void testListByAssessmentProject() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"agentProperties\":{\"id\":\"tiklsm\",\"version\":\"hql\",\"lastHeartbeatUtc\":\"2021-11-24T07:26Z\",\"spnDetails\":{\"authority\":\"yiibh\",\"applicationId\":\"wbgbudav\",\"audience\":\"orbccqcdhth\",\"objectId\":\"vlirknuc\",\"tenantId\":\"awrdt\"}},\"discoverySiteId\":\"gzlgpyaixihz\",\"createdTimestamp\":\"2021-01-21T19:40:51Z\",\"updatedTimestamp\":\"2021-04-15T12:59:29Z\",\"provisioningState\":\"Provisioning\"},\"id\":\"dqftt\",\"name\":\"acybdueurgmcdcpk\",\"type\":\"hlo\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response = manager.hypervCollectorsOperations() + .listByAssessmentProject("x", "tzo", com.azure.core.util.Context.NONE); + + Assertions.assertEquals(ProvisioningState.PROVISIONING, + response.iterator().next().properties().provisioningState()); + Assertions.assertEquals("tiklsm", response.iterator().next().properties().agentProperties().id()); + Assertions.assertEquals("hql", response.iterator().next().properties().agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-11-24T07:26Z"), + response.iterator().next().properties().agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("yiibh", + response.iterator().next().properties().agentProperties().spnDetails().authority()); + Assertions.assertEquals("wbgbudav", + response.iterator().next().properties().agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("orbccqcdhth", + response.iterator().next().properties().agentProperties().spnDetails().audience()); + Assertions.assertEquals("vlirknuc", + response.iterator().next().properties().agentProperties().spnDetails().objectId()); + Assertions.assertEquals("awrdt", + response.iterator().next().properties().agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("gzlgpyaixihz", response.iterator().next().properties().discoverySiteId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ImpactedAssessmentObjectTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ImpactedAssessmentObjectTests.java new file mode 100644 index 000000000000..90b49dbcffdf --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ImpactedAssessmentObjectTests.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.ImpactedAssessmentObject; + +public final class ImpactedAssessmentObjectTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + ImpactedAssessmentObject model + = BinaryData.fromString("{\"objectName\":\"utpwoqhihejqgw\",\"objectType\":\"nfqn\"}") + .toObject(ImpactedAssessmentObject.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + ImpactedAssessmentObject model = new ImpactedAssessmentObject(); + model = BinaryData.fromObject(model).toObject(ImpactedAssessmentObject.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorInnerTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorInnerTests.java new file mode 100644 index 000000000000..3c012800a936 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorInnerTests.java @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.ImportCollectorInner; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import org.junit.jupiter.api.Assertions; + +public final class ImportCollectorInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + ImportCollectorInner model = BinaryData.fromString( + "{\"properties\":{\"discoverySiteId\":\"qxuwyvca\",\"createdTimestamp\":\"2021-10-26T05:34:42Z\",\"updatedTimestamp\":\"2021-06-20T08:40:01Z\",\"provisioningState\":\"Failed\"},\"id\":\"izus\",\"name\":\"szlbscm\",\"type\":\"lzijiufehgmvflnw\"}") + .toObject(ImportCollectorInner.class); + Assertions.assertEquals(ProvisioningState.FAILED, model.properties().provisioningState()); + Assertions.assertEquals("qxuwyvca", model.properties().discoverySiteId()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + ImportCollectorInner model = new ImportCollectorInner() + .withProperties(new CollectorPropertiesBase().withProvisioningState(ProvisioningState.FAILED) + .withDiscoverySiteId("qxuwyvca")); + model = BinaryData.fromObject(model).toObject(ImportCollectorInner.class); + Assertions.assertEquals(ProvisioningState.FAILED, model.properties().provisioningState()); + Assertions.assertEquals("qxuwyvca", model.properties().discoverySiteId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorListResultTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorListResultTests.java new file mode 100644 index 000000000000..5d587c8f1f78 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorListResultTests.java @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.ImportCollectorInner; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.ImportCollectorListResult; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class ImportCollectorListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + ImportCollectorListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"discoverySiteId\":\"qinfszpyglqd\",\"createdTimestamp\":\"2021-05-07T12:56:20Z\",\"updatedTimestamp\":\"2021-02-04T21:16:01Z\",\"provisioningState\":\"Canceled\"},\"id\":\"cxpjbyypsj\",\"name\":\"qcjenkyhf\",\"type\":\"zv\"}],\"nextLink\":\"xfxjelgcmpzqj\"}") + .toObject(ImportCollectorListResult.class); + Assertions.assertEquals(ProvisioningState.CANCELED, model.value().get(0).properties().provisioningState()); + Assertions.assertEquals("qinfszpyglqd", model.value().get(0).properties().discoverySiteId()); + Assertions.assertEquals("xfxjelgcmpzqj", model.nextLink()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + ImportCollectorListResult model + = new ImportCollectorListResult().withValue(Arrays.asList(new ImportCollectorInner() + .withProperties(new CollectorPropertiesBase().withProvisioningState(ProvisioningState.CANCELED) + .withDiscoverySiteId("qinfszpyglqd")))) + .withNextLink("xfxjelgcmpzqj"); + model = BinaryData.fromObject(model).toObject(ImportCollectorListResult.class); + Assertions.assertEquals(ProvisioningState.CANCELED, model.value().get(0).properties().provisioningState()); + Assertions.assertEquals("qinfszpyglqd", model.value().get(0).properties().discoverySiteId()); + Assertions.assertEquals("xfxjelgcmpzqj", model.nextLink()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorsOperationsCreateMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorsOperationsCreateMockTests.java new file mode 100644 index 000000000000..2ae61e13c6d7 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorsOperationsCreateMockTests.java @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.ImportCollector; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class ImportCollectorsOperationsCreateMockTests { + @Test + public void testCreate() throws Exception { + String responseStr + = "{\"properties\":{\"discoverySiteId\":\"nhrkmjqncfvdsc\",\"createdTimestamp\":\"2021-05-03T16:49:37Z\",\"updatedTimestamp\":\"2021-03-27T04:54:32Z\",\"provisioningState\":\"Succeeded\"},\"id\":\"qqwypvn\",\"name\":\"r\",\"type\":\"b\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + ImportCollector response = manager.importCollectorsOperations() + .define("fvezefk") + .withExistingAssessmentProject("aqjmkgxqwque", "uylztpziizevjyk") + .withProperties(new CollectorPropertiesBase().withProvisioningState(ProvisioningState.UPDATING) + .withDiscoverySiteId("twql")) + .create(); + + Assertions.assertEquals(ProvisioningState.SUCCEEDED, response.properties().provisioningState()); + Assertions.assertEquals("nhrkmjqncfvdsc", response.properties().discoverySiteId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorsOperationsDeleteWithResponseMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorsOperationsDeleteWithResponseMockTests.java new file mode 100644 index 000000000000..63984003381c --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorsOperationsDeleteWithResponseMockTests.java @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class ImportCollectorsOperationsDeleteWithResponseMockTests { + @Test + public void testDeleteWithResponse() throws Exception { + String responseStr = "{}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + manager.importCollectorsOperations() + .deleteWithResponse("yslb", "lglmnnkkwayqsh", "yqxridttb", com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorsOperationsGetWithResponseMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorsOperationsGetWithResponseMockTests.java new file mode 100644 index 000000000000..b8b1ab1e4e4a --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorsOperationsGetWithResponseMockTests.java @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.ImportCollector; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class ImportCollectorsOperationsGetWithResponseMockTests { + @Test + public void testGetWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"discoverySiteId\":\"jqy\",\"createdTimestamp\":\"2021-12-06T04:50:10Z\",\"updatedTimestamp\":\"2021-05-15T07:47:43Z\",\"provisioningState\":\"Failed\"},\"id\":\"tulcrcjdklo\",\"name\":\"csubmzoonsvobc\",\"type\":\"kxfpwh\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + ImportCollector response = manager.importCollectorsOperations() + .getWithResponse("yelsyasvfnk", "myg", "jekrknfd", com.azure.core.util.Context.NONE) + .getValue(); + + Assertions.assertEquals(ProvisioningState.FAILED, response.properties().provisioningState()); + Assertions.assertEquals("jqy", response.properties().discoverySiteId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorsOperationsListByAssessmentProjectMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorsOperationsListByAssessmentProjectMockTests.java new file mode 100644 index 000000000000..9a95bbf0862c --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ImportCollectorsOperationsListByAssessmentProjectMockTests.java @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.ImportCollector; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class ImportCollectorsOperationsListByAssessmentProjectMockTests { + @Test + public void testListByAssessmentProject() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"discoverySiteId\":\"aexxjfwtgdfkka\",\"createdTimestamp\":\"2021-09-28T18:01:42Z\",\"updatedTimestamp\":\"2021-06-30T22:22:51Z\",\"provisioningState\":\"Deleting\"},\"id\":\"mczfedyuepsvplt\",\"name\":\"dajjvywe\",\"type\":\"cfkumcfjxo\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response = manager.importCollectorsOperations() + .listByAssessmentProject("ihvaang", "tnhjrfdmfd", com.azure.core.util.Context.NONE); + + Assertions.assertEquals(ProvisioningState.DELETING, + response.iterator().next().properties().provisioningState()); + Assertions.assertEquals("aexxjfwtgdfkka", response.iterator().next().properties().discoverySiteId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/NetworkAdapterTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/NetworkAdapterTests.java new file mode 100644 index 000000000000..ac4aa629b441 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/NetworkAdapterTests.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.NetworkAdapter; + +public final class NetworkAdapterTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + NetworkAdapter model = BinaryData.fromString( + "{\"macAddress\":\"okrtalvnb\",\"ipAddresses\":[\"bemeluclvd\",\"jukyrdn\"],\"displayName\":\"dxahhxhqfaqnvzo\"}") + .toObject(NetworkAdapter.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + NetworkAdapter model = new NetworkAdapter(); + model = BinaryData.fromObject(model).toObject(NetworkAdapter.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/OperationDisplayTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/OperationDisplayTests.java new file mode 100644 index 000000000000..ab8cd3000305 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/OperationDisplayTests.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.OperationDisplay; + +public final class OperationDisplayTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + OperationDisplay model = BinaryData.fromString( + "{\"provider\":\"yrtih\",\"resource\":\"tijbpzvgnwzsymgl\",\"operation\":\"fcyzkohdbihanufh\",\"description\":\"bj\"}") + .toObject(OperationDisplay.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + OperationDisplay model = new OperationDisplay(); + model = BinaryData.fromObject(model).toObject(OperationDisplay.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/OperationInnerTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/OperationInnerTests.java new file mode 100644 index 000000000000..2a8316ecb86b --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/OperationInnerTests.java @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.OperationInner; +import com.azure.resourcemanager.migration.assessment.models.OperationDisplay; + +public final class OperationInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + OperationInner model = BinaryData.fromString( + "{\"name\":\"usarhmofc\",\"isDataAction\":false,\"display\":{\"provider\":\"urkdtmlx\",\"resource\":\"kuksjtxukcdm\",\"operation\":\"rcryuanzwuxzdxta\",\"description\":\"lhmwhfpmrqobm\"},\"origin\":\"user,system\",\"actionType\":\"Internal\"}") + .toObject(OperationInner.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + OperationInner model = new OperationInner().withDisplay(new OperationDisplay()); + model = BinaryData.fromObject(model).toObject(OperationInner.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/OperationListResultTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/OperationListResultTests.java new file mode 100644 index 000000000000..c1a2fa5d5691 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/OperationListResultTests.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.OperationListResult; + +public final class OperationListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + OperationListResult model = BinaryData.fromString( + "{\"value\":[{\"name\":\"quvgjxpybczme\",\"isDataAction\":true,\"display\":{\"provider\":\"pbsphrupidgs\",\"resource\":\"bejhphoycmsxa\",\"operation\":\"hdxbmtqio\",\"description\":\"zehtbmu\"},\"origin\":\"user,system\",\"actionType\":\"Internal\"},{\"name\":\"izhwlrxy\",\"isDataAction\":false,\"display\":{\"provider\":\"ijgkdm\",\"resource\":\"azlobcufpdznrbt\",\"operation\":\"qjnqglhqgnufoooj\",\"description\":\"ifsqesaagdfmg\"},\"origin\":\"user,system\",\"actionType\":\"Internal\"},{\"name\":\"rifkwm\",\"isDataAction\":true,\"display\":{\"provider\":\"izntocipao\",\"resource\":\"jpsq\",\"operation\":\"mpoyfd\",\"description\":\"ogknygjofjdd\"},\"origin\":\"user,system\",\"actionType\":\"Internal\"}],\"nextLink\":\"upewnwreitjzy\"}") + .toObject(OperationListResult.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + OperationListResult model = new OperationListResult(); + model = BinaryData.fromObject(model).toObject(OperationListResult.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/OperationsListMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/OperationsListMockTests.java new file mode 100644 index 000000000000..62cc620d2680 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/OperationsListMockTests.java @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.Operation; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class OperationsListMockTests { + @Test + public void testList() throws Exception { + String responseStr + = "{\"value\":[{\"name\":\"rhuzgfxonjtpu\",\"isDataAction\":false,\"display\":{\"provider\":\"pvti\",\"resource\":\"zbpdbo\",\"operation\":\"gryfqiuasig\",\"description\":\"wsocnequygdjbo\"},\"origin\":\"system\",\"actionType\":\"Internal\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response = manager.operations().list(com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionInnerTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionInnerTests.java new file mode 100644 index 000000000000..56b8f7663cdb --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionInnerTests.java @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.PrivateEndpointConnectionInner; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpoint; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpointConnectionProperties; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpointServiceConnectionStatus; +import com.azure.resourcemanager.migration.assessment.models.PrivateLinkServiceConnectionState; +import org.junit.jupiter.api.Assertions; + +public final class PrivateEndpointConnectionInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + PrivateEndpointConnectionInner model = BinaryData.fromString( + "{\"properties\":{\"groupIds\":[\"ddgmb\"],\"privateEndpoint\":{\"id\":\"xppbhtqqro\"},\"privateLinkServiceConnectionState\":{\"status\":\"Pending\",\"description\":\"psalgbqux\",\"actionsRequired\":\"jyj\"},\"provisioningState\":\"Deleting\"},\"id\":\"o\",\"name\":\"fhrtxilnerkujysv\",\"type\":\"eju\"}") + .toObject(PrivateEndpointConnectionInner.class); + Assertions.assertEquals(PrivateEndpointServiceConnectionStatus.PENDING, + model.properties().privateLinkServiceConnectionState().status()); + Assertions.assertEquals("psalgbqux", model.properties().privateLinkServiceConnectionState().description()); + Assertions.assertEquals("jyj", model.properties().privateLinkServiceConnectionState().actionsRequired()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + PrivateEndpointConnectionInner model + = new PrivateEndpointConnectionInner() + .withProperties(new PrivateEndpointConnectionProperties().withPrivateEndpoint(new PrivateEndpoint()) + .withPrivateLinkServiceConnectionState(new PrivateLinkServiceConnectionState() + .withStatus(PrivateEndpointServiceConnectionStatus.PENDING) + .withDescription("psalgbqux") + .withActionsRequired("jyj"))); + model = BinaryData.fromObject(model).toObject(PrivateEndpointConnectionInner.class); + Assertions.assertEquals(PrivateEndpointServiceConnectionStatus.PENDING, + model.properties().privateLinkServiceConnectionState().status()); + Assertions.assertEquals("psalgbqux", model.properties().privateLinkServiceConnectionState().description()); + Assertions.assertEquals("jyj", model.properties().privateLinkServiceConnectionState().actionsRequired()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionListResultTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionListResultTests.java new file mode 100644 index 000000000000..1ba9f0b2f1f0 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionListResultTests.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.PrivateEndpointConnectionInner; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpoint; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpointConnectionListResult; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpointConnectionProperties; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpointServiceConnectionStatus; +import com.azure.resourcemanager.migration.assessment.models.PrivateLinkServiceConnectionState; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class PrivateEndpointConnectionListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + PrivateEndpointConnectionListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"groupIds\":[\"emchgavsczuej\"],\"privateEndpoint\":{\"id\":\"ptlghwzhomewjjst\"},\"privateLinkServiceConnectionState\":{\"status\":\"Pending\",\"description\":\"qawmoaianc\",\"actionsRequired\":\"vodrrslblxydkxr\"},\"provisioningState\":\"Deleting\"},\"id\":\"xiwkgfbql\",\"name\":\"nqkhych\",\"type\":\"c\"},{\"properties\":{\"groupIds\":[\"ehurqlr\"],\"privateEndpoint\":{\"id\":\"aweyur\"},\"privateLinkServiceConnectionState\":{\"status\":\"Rejected\",\"description\":\"jdxravjuqdbrx\",\"actionsRequired\":\"gchbapxkiy\"},\"provisioningState\":\"Succeeded\"},\"id\":\"bajbuscgduusi\",\"name\":\"ycblevpmcl\",\"type\":\"jy\"}],\"nextLink\":\"yxlzgs\"}") + .toObject(PrivateEndpointConnectionListResult.class); + Assertions.assertEquals(PrivateEndpointServiceConnectionStatus.PENDING, + model.value().get(0).properties().privateLinkServiceConnectionState().status()); + Assertions.assertEquals("qawmoaianc", + model.value().get(0).properties().privateLinkServiceConnectionState().description()); + Assertions.assertEquals("vodrrslblxydkxr", + model.value().get(0).properties().privateLinkServiceConnectionState().actionsRequired()); + Assertions.assertEquals("yxlzgs", model.nextLink()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + PrivateEndpointConnectionListResult model = new PrivateEndpointConnectionListResult().withValue(Arrays.asList( + new PrivateEndpointConnectionInner() + .withProperties(new PrivateEndpointConnectionProperties().withPrivateEndpoint(new PrivateEndpoint()) + .withPrivateLinkServiceConnectionState(new PrivateLinkServiceConnectionState() + .withStatus(PrivateEndpointServiceConnectionStatus.PENDING) + .withDescription("qawmoaianc") + .withActionsRequired("vodrrslblxydkxr"))), + new PrivateEndpointConnectionInner() + .withProperties(new PrivateEndpointConnectionProperties().withPrivateEndpoint(new PrivateEndpoint()) + .withPrivateLinkServiceConnectionState(new PrivateLinkServiceConnectionState() + .withStatus(PrivateEndpointServiceConnectionStatus.REJECTED) + .withDescription("jdxravjuqdbrx") + .withActionsRequired("gchbapxkiy"))))) + .withNextLink("yxlzgs"); + model = BinaryData.fromObject(model).toObject(PrivateEndpointConnectionListResult.class); + Assertions.assertEquals(PrivateEndpointServiceConnectionStatus.PENDING, + model.value().get(0).properties().privateLinkServiceConnectionState().status()); + Assertions.assertEquals("qawmoaianc", + model.value().get(0).properties().privateLinkServiceConnectionState().description()); + Assertions.assertEquals("vodrrslblxydkxr", + model.value().get(0).properties().privateLinkServiceConnectionState().actionsRequired()); + Assertions.assertEquals("yxlzgs", model.nextLink()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionOperationsDeleteWithResponseMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionOperationsDeleteWithResponseMockTests.java new file mode 100644 index 000000000000..d6d1fece2b35 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionOperationsDeleteWithResponseMockTests.java @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class PrivateEndpointConnectionOperationsDeleteWithResponseMockTests { + @Test + public void testDeleteWithResponse() throws Exception { + String responseStr = "{}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + manager.privateEndpointConnectionOperations() + .deleteWithResponse("lduyehiiittugyuq", "rldaxurfqa", "csozjv", com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionOperationsGetWithResponseMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionOperationsGetWithResponseMockTests.java new file mode 100644 index 000000000000..09dc2f8936eb --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionOperationsGetWithResponseMockTests.java @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpointConnection; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpointServiceConnectionStatus; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class PrivateEndpointConnectionOperationsGetWithResponseMockTests { + @Test + public void testGetWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"groupIds\":[\"m\",\"yakmlwktf\"],\"privateEndpoint\":{\"id\":\"kroyrdurxflzqji\"},\"privateLinkServiceConnectionState\":{\"status\":\"Rejected\",\"description\":\"gzjxxlf\",\"actionsRequired\":\"lzuqloiwyayyzivr\"},\"provisioningState\":\"Creating\"},\"id\":\"dql\",\"name\":\"chwhrktj\",\"type\":\"eifibfiplhx\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PrivateEndpointConnection response = manager.privateEndpointConnectionOperations() + .getWithResponse("xjgvh", "ccbmkakm", "ookbpu", com.azure.core.util.Context.NONE) + .getValue(); + + Assertions.assertEquals(PrivateEndpointServiceConnectionStatus.REJECTED, + response.properties().privateLinkServiceConnectionState().status()); + Assertions.assertEquals("gzjxxlf", response.properties().privateLinkServiceConnectionState().description()); + Assertions.assertEquals("lzuqloiwyayyzivr", + response.properties().privateLinkServiceConnectionState().actionsRequired()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionOperationsListByAssessmentProjectMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionOperationsListByAssessmentProjectMockTests.java new file mode 100644 index 000000000000..9216242858cf --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionOperationsListByAssessmentProjectMockTests.java @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpointConnection; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpointServiceConnectionStatus; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class PrivateEndpointConnectionOperationsListByAssessmentProjectMockTests { + @Test + public void testListByAssessmentProject() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"groupIds\":[\"gbaduve\",\"ovsdqhzrtdbakrli\"],\"privateEndpoint\":{\"id\":\"vppkeqsi\"},\"privateLinkServiceConnectionState\":{\"status\":\"Approved\",\"description\":\"lng\",\"actionsRequired\":\"nhr\"},\"provisioningState\":\"Failed\"},\"id\":\"cdtajdopggorw\",\"name\":\"oqtrotpvclpo\",\"type\":\"yrlmwkptsk\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response = manager.privateEndpointConnectionOperations() + .listByAssessmentProject("yjxvc", "asormrexzvdube", com.azure.core.util.Context.NONE); + + Assertions.assertEquals(PrivateEndpointServiceConnectionStatus.APPROVED, + response.iterator().next().properties().privateLinkServiceConnectionState().status()); + Assertions.assertEquals("lng", + response.iterator().next().properties().privateLinkServiceConnectionState().description()); + Assertions.assertEquals("nhr", + response.iterator().next().properties().privateLinkServiceConnectionState().actionsRequired()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionOperationsUpdateMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionOperationsUpdateMockTests.java new file mode 100644 index 000000000000..9d6252e0e657 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionOperationsUpdateMockTests.java @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.fluent.models.PrivateEndpointConnectionInner; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpoint; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpointConnection; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpointConnectionProperties; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpointServiceConnectionStatus; +import com.azure.resourcemanager.migration.assessment.models.PrivateLinkServiceConnectionState; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class PrivateEndpointConnectionOperationsUpdateMockTests { + @Test + public void testUpdate() throws Exception { + String responseStr + = "{\"properties\":{\"groupIds\":[\"audgjtfbclakkucd\",\"wnhczbutou\",\"gjtirjwayhic\",\"qwwvgwkslvl\"],\"privateEndpoint\":{\"id\":\"dvbiabvnsrg\"},\"privateLinkServiceConnectionState\":{\"status\":\"Approved\",\"description\":\"qx\",\"actionsRequired\":\"yfhbmwkh\"},\"provisioningState\":\"Succeeded\"},\"id\":\"tbspvkhglaqjs\",\"name\":\"yzstujrzxrkns\",\"type\":\"d\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PrivateEndpointConnection response = manager.privateEndpointConnectionOperations() + .update("nsmy", "jow", "yeyzm", + new PrivateEndpointConnectionInner() + .withProperties(new PrivateEndpointConnectionProperties().withPrivateEndpoint(new PrivateEndpoint()) + .withPrivateLinkServiceConnectionState(new PrivateLinkServiceConnectionState() + .withStatus(PrivateEndpointServiceConnectionStatus.PENDING) + .withDescription("stcivrak") + .withActionsRequired("ry"))), + com.azure.core.util.Context.NONE); + + Assertions.assertEquals(PrivateEndpointServiceConnectionStatus.APPROVED, + response.properties().privateLinkServiceConnectionState().status()); + Assertions.assertEquals("qx", response.properties().privateLinkServiceConnectionState().description()); + Assertions.assertEquals("yfhbmwkh", + response.properties().privateLinkServiceConnectionState().actionsRequired()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionPropertiesTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionPropertiesTests.java new file mode 100644 index 000000000000..7e0380ffc48c --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointConnectionPropertiesTests.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.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpoint; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpointConnectionProperties; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpointServiceConnectionStatus; +import com.azure.resourcemanager.migration.assessment.models.PrivateLinkServiceConnectionState; +import org.junit.jupiter.api.Assertions; + +public final class PrivateEndpointConnectionPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + PrivateEndpointConnectionProperties model = BinaryData.fromString( + "{\"groupIds\":[\"awrlyx\",\"jkcpr\",\"nwbxgjvtbvpyssz\"],\"privateEndpoint\":{\"id\":\"uj\"},\"privateLinkServiceConnectionState\":{\"status\":\"Rejected\",\"description\":\"muouqfp\",\"actionsRequired\":\"zw\"},\"provisioningState\":\"Succeeded\"}") + .toObject(PrivateEndpointConnectionProperties.class); + Assertions.assertEquals(PrivateEndpointServiceConnectionStatus.REJECTED, + model.privateLinkServiceConnectionState().status()); + Assertions.assertEquals("muouqfp", model.privateLinkServiceConnectionState().description()); + Assertions.assertEquals("zw", model.privateLinkServiceConnectionState().actionsRequired()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + PrivateEndpointConnectionProperties model + = new PrivateEndpointConnectionProperties().withPrivateEndpoint(new PrivateEndpoint()) + .withPrivateLinkServiceConnectionState( + new PrivateLinkServiceConnectionState().withStatus(PrivateEndpointServiceConnectionStatus.REJECTED) + .withDescription("muouqfp") + .withActionsRequired("zw")); + model = BinaryData.fromObject(model).toObject(PrivateEndpointConnectionProperties.class); + Assertions.assertEquals(PrivateEndpointServiceConnectionStatus.REJECTED, + model.privateLinkServiceConnectionState().status()); + Assertions.assertEquals("muouqfp", model.privateLinkServiceConnectionState().description()); + Assertions.assertEquals("zw", model.privateLinkServiceConnectionState().actionsRequired()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointTests.java new file mode 100644 index 000000000000..5dd0fe7d7e80 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateEndpointTests.java @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpoint; + +public final class PrivateEndpointTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + PrivateEndpoint model = BinaryData.fromString("{\"id\":\"itnwuizgazxufi\"}").toObject(PrivateEndpoint.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + PrivateEndpoint model = new PrivateEndpoint(); + model = BinaryData.fromObject(model).toObject(PrivateEndpoint.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateLinkResourceInnerTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateLinkResourceInnerTests.java new file mode 100644 index 000000000000..90eb375373dc --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateLinkResourceInnerTests.java @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.PrivateLinkResourceInner; +import com.azure.resourcemanager.migration.assessment.models.PrivateLinkResourceProperties; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class PrivateLinkResourceInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + PrivateLinkResourceInner model = BinaryData.fromString( + "{\"properties\":{\"groupId\":\"fkndl\",\"requiredMembers\":[\"w\",\"nvgmmbugtywa\"],\"requiredZoneNames\":[\"aqkue\",\"tgroesh\"]},\"id\":\"gzcbyf\",\"name\":\"x\",\"type\":\"faoytehqpuv\"}") + .toObject(PrivateLinkResourceInner.class); + Assertions.assertEquals("aqkue", model.properties().requiredZoneNames().get(0)); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + PrivateLinkResourceInner model = new PrivateLinkResourceInner().withProperties( + new PrivateLinkResourceProperties().withRequiredZoneNames(Arrays.asList("aqkue", "tgroesh"))); + model = BinaryData.fromObject(model).toObject(PrivateLinkResourceInner.class); + Assertions.assertEquals("aqkue", model.properties().requiredZoneNames().get(0)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateLinkResourceListResultTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateLinkResourceListResultTests.java new file mode 100644 index 000000000000..bda4a5fd6d28 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateLinkResourceListResultTests.java @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.PrivateLinkResourceInner; +import com.azure.resourcemanager.migration.assessment.models.PrivateLinkResourceListResult; +import com.azure.resourcemanager.migration.assessment.models.PrivateLinkResourceProperties; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class PrivateLinkResourceListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + PrivateLinkResourceListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"groupId\":\"zltafhbzffovwm\",\"requiredMembers\":[\"zqs\"],\"requiredZoneNames\":[\"gvdwnapf\",\"qwowftptnuw\",\"tkschgcgqyhl\"]},\"id\":\"eyqrhv\",\"name\":\"eldotjv\",\"type\":\"kwiswskukjtas\"}],\"nextLink\":\"wispkxk\"}") + .toObject(PrivateLinkResourceListResult.class); + Assertions.assertEquals("gvdwnapf", model.value().get(0).properties().requiredZoneNames().get(0)); + Assertions.assertEquals("wispkxk", model.nextLink()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + PrivateLinkResourceListResult model = new PrivateLinkResourceListResult() + .withValue(Arrays.asList(new PrivateLinkResourceInner().withProperties(new PrivateLinkResourceProperties() + .withRequiredZoneNames(Arrays.asList("gvdwnapf", "qwowftptnuw", "tkschgcgqyhl"))))) + .withNextLink("wispkxk"); + model = BinaryData.fromObject(model).toObject(PrivateLinkResourceListResult.class); + Assertions.assertEquals("gvdwnapf", model.value().get(0).properties().requiredZoneNames().get(0)); + Assertions.assertEquals("wispkxk", model.nextLink()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateLinkResourceOperationsGetWithResponseMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateLinkResourceOperationsGetWithResponseMockTests.java new file mode 100644 index 000000000000..5fe0f09250b1 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateLinkResourceOperationsGetWithResponseMockTests.java @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.PrivateLinkResource; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class PrivateLinkResourceOperationsGetWithResponseMockTests { + @Test + public void testGetWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"groupId\":\"fnzzryizwbxg\",\"requiredMembers\":[\"xlayunomir\",\"p\",\"abenqlamwmg\",\"way\"],\"requiredZoneNames\":[\"nbcpjstbhemhcucs\",\"snxfbxu\",\"eapdrbzyv\"]},\"id\":\"uadulpodkaxpfo\",\"name\":\"kzhmhj\",\"type\":\"qltd\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PrivateLinkResource response = manager.privateLinkResourceOperations() + .getWithResponse("dqumqvfm", "caddtgc", "xegtvgwyur", com.azure.core.util.Context.NONE) + .getValue(); + + Assertions.assertEquals("nbcpjstbhemhcucs", response.properties().requiredZoneNames().get(0)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateLinkResourceOperationsListByAssessmentProjectMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateLinkResourceOperationsListByAssessmentProjectMockTests.java new file mode 100644 index 000000000000..494b45709161 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateLinkResourceOperationsListByAssessmentProjectMockTests.java @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.PrivateLinkResource; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class PrivateLinkResourceOperationsListByAssessmentProjectMockTests { + @Test + public void testListByAssessmentProject() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"groupId\":\"walzyxwhoeamoeo\",\"requiredMembers\":[\"eysf\",\"nimtwuuhaueg\"],\"requiredZoneNames\":[\"mnfeub\",\"zjy\",\"kwfugiphrrkuu\",\"nqd\"]},\"id\":\"hz\",\"name\":\"fopueoqusvwluj\",\"type\":\"pwnibittozt\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response = manager.privateLinkResourceOperations() + .listByAssessmentProject("dzciggb", "vt", com.azure.core.util.Context.NONE); + + Assertions.assertEquals("mnfeub", response.iterator().next().properties().requiredZoneNames().get(0)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateLinkResourcePropertiesTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateLinkResourcePropertiesTests.java new file mode 100644 index 000000000000..544417635730 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateLinkResourcePropertiesTests.java @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.PrivateLinkResourceProperties; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class PrivateLinkResourcePropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + PrivateLinkResourceProperties model = BinaryData.fromString( + "{\"groupId\":\"vqmtdwckygroejn\",\"requiredMembers\":[\"jdjusk\",\"rreqynkceysfaqe\",\"pl\",\"ryshwddkvbxgk\"],\"requiredZoneNames\":[\"ybwptda\",\"arvvlfnt\",\"mt\"]}") + .toObject(PrivateLinkResourceProperties.class); + Assertions.assertEquals("ybwptda", model.requiredZoneNames().get(0)); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + PrivateLinkResourceProperties model + = new PrivateLinkResourceProperties().withRequiredZoneNames(Arrays.asList("ybwptda", "arvvlfnt", "mt")); + model = BinaryData.fromObject(model).toObject(PrivateLinkResourceProperties.class); + Assertions.assertEquals("ybwptda", model.requiredZoneNames().get(0)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateLinkServiceConnectionStateTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateLinkServiceConnectionStateTests.java new file mode 100644 index 000000000000..4e6c0cb6d896 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/PrivateLinkServiceConnectionStateTests.java @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.PrivateEndpointServiceConnectionStatus; +import com.azure.resourcemanager.migration.assessment.models.PrivateLinkServiceConnectionState; +import org.junit.jupiter.api.Assertions; + +public final class PrivateLinkServiceConnectionStateTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + PrivateLinkServiceConnectionState model + = BinaryData.fromString("{\"status\":\"Pending\",\"description\":\"y\",\"actionsRequired\":\"hr\"}") + .toObject(PrivateLinkServiceConnectionState.class); + Assertions.assertEquals(PrivateEndpointServiceConnectionStatus.PENDING, model.status()); + Assertions.assertEquals("y", model.description()); + Assertions.assertEquals("hr", model.actionsRequired()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + PrivateLinkServiceConnectionState model + = new PrivateLinkServiceConnectionState().withStatus(PrivateEndpointServiceConnectionStatus.PENDING) + .withDescription("y") + .withActionsRequired("hr"); + model = BinaryData.fromObject(model).toObject(PrivateLinkServiceConnectionState.class); + Assertions.assertEquals(PrivateEndpointServiceConnectionStatus.PENDING, model.status()); + Assertions.assertEquals("y", model.description()); + Assertions.assertEquals("hr", model.actionsRequired()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ProcessorInfoTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ProcessorInfoTests.java new file mode 100644 index 000000000000..a32ba5ebceba --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ProcessorInfoTests.java @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.ProcessorInfo; +import org.junit.jupiter.api.Assertions; + +public final class ProcessorInfoTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + ProcessorInfo model = BinaryData + .fromString("{\"name\":\"ksgplsa\",\"numberOfSockets\":931393503,\"numberOfCoresPerSocket\":792282663}") + .toObject(ProcessorInfo.class); + Assertions.assertEquals("ksgplsa", model.name()); + Assertions.assertEquals(931393503, model.numberOfSockets()); + Assertions.assertEquals(792282663, model.numberOfCoresPerSocket()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + ProcessorInfo model = new ProcessorInfo().withName("ksgplsa") + .withNumberOfSockets(931393503) + .withNumberOfCoresPerSocket(792282663); + model = BinaryData.fromObject(model).toObject(ProcessorInfo.class); + Assertions.assertEquals("ksgplsa", model.name()); + Assertions.assertEquals(931393503, model.numberOfSockets()); + Assertions.assertEquals(792282663, model.numberOfCoresPerSocket()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ProductSupportStatusTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ProductSupportStatusTests.java new file mode 100644 index 000000000000..19f09edaf439 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ProductSupportStatusTests.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.ProductSupportStatus; + +public final class ProductSupportStatusTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + ProductSupportStatus model = BinaryData.fromString( + "{\"currentVersion\":\"ynl\",\"servicePackStatus\":\"huopxodlqiynto\",\"esuStatus\":\"ihleos\",\"supportStatus\":\"w\",\"eta\":1899163147,\"currentEsuYear\":\"lyzrpzbchckqqzqi\",\"mainstreamEndDate\":\"2021-05-24T05:08:39Z\",\"extendedSupportEndDate\":\"2021-11-07T11:18:56Z\",\"extendedSecurityUpdateYear1EndDate\":\"2021-10-31T06:14:16Z\",\"extendedSecurityUpdateYear2EndDate\":\"2021-10-09T00:37:48Z\",\"extendedSecurityUpdateYear3EndDate\":\"2021-06-27T05:18:24Z\"}") + .toObject(ProductSupportStatus.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + ProductSupportStatus model = new ProductSupportStatus(); + model = BinaryData.fromObject(model).toObject(ProductSupportStatus.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ProjectPropertiesTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ProjectPropertiesTests.java new file mode 100644 index 000000000000..88117538527e --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ProjectPropertiesTests.java @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.ProjectProperties; +import com.azure.resourcemanager.migration.assessment.models.ProjectStatus; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import org.junit.jupiter.api.Assertions; + +public final class ProjectPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + ProjectProperties model = BinaryData.fromString( + "{\"createdTimestamp\":\"2021-05-11T01:45:16Z\",\"updatedTimestamp\":\"2021-04-06T09:15:33Z\",\"serviceEndpoint\":\"atqxho\",\"assessmentSolutionId\":\"geablgphuticndvk\",\"projectStatus\":\"Inactive\",\"customerWorkspaceId\":\"yiftyhxhuro\",\"customerWorkspaceLocation\":\"tyxolniwpwc\",\"publicNetworkAccess\":\"jfkgiawxk\",\"privateEndpointConnections\":[{\"properties\":{\"groupIds\":[\"ckbasyypndd\",\"sgcbac\",\"hejkotynqgou\"],\"privateEndpoint\":{\"id\":\"dlikwyqkgfgibma\"},\"privateLinkServiceConnectionState\":{\"status\":\"Approved\",\"description\":\"eqsrxybzqqedqyt\",\"actionsRequired\":\"iqfouflmmnkz\"},\"provisioningState\":\"Creating\"},\"id\":\"mglougpbkw\",\"name\":\"mutduqktaps\",\"type\":\"wgcu\"}],\"customerStorageAccountArmId\":\"tumkdosvqwhbm\",\"provisioningState\":\"Provisioning\"}") + .toObject(ProjectProperties.class); + Assertions.assertEquals(ProvisioningState.PROVISIONING, model.provisioningState()); + Assertions.assertEquals("geablgphuticndvk", model.assessmentSolutionId()); + Assertions.assertEquals(ProjectStatus.INACTIVE, model.projectStatus()); + Assertions.assertEquals("yiftyhxhuro", model.customerWorkspaceId()); + Assertions.assertEquals("tyxolniwpwc", model.customerWorkspaceLocation()); + Assertions.assertEquals("jfkgiawxk", model.publicNetworkAccess()); + Assertions.assertEquals("tumkdosvqwhbm", model.customerStorageAccountArmId()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + ProjectProperties model = new ProjectProperties().withProvisioningState(ProvisioningState.PROVISIONING) + .withAssessmentSolutionId("geablgphuticndvk") + .withProjectStatus(ProjectStatus.INACTIVE) + .withCustomerWorkspaceId("yiftyhxhuro") + .withCustomerWorkspaceLocation("tyxolniwpwc") + .withPublicNetworkAccess("jfkgiawxk") + .withCustomerStorageAccountArmId("tumkdosvqwhbm"); + model = BinaryData.fromObject(model).toObject(ProjectProperties.class); + Assertions.assertEquals(ProvisioningState.PROVISIONING, model.provisioningState()); + Assertions.assertEquals("geablgphuticndvk", model.assessmentSolutionId()); + Assertions.assertEquals(ProjectStatus.INACTIVE, model.projectStatus()); + Assertions.assertEquals("yiftyhxhuro", model.customerWorkspaceId()); + Assertions.assertEquals("tyxolniwpwc", model.customerWorkspaceLocation()); + Assertions.assertEquals("jfkgiawxk", model.publicNetworkAccess()); + Assertions.assertEquals("tumkdosvqwhbm", model.customerStorageAccountArmId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorInnerTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorInnerTests.java new file mode 100644 index 000000000000..d6222cabf881 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorInnerTests.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.ServerCollectorInner; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentSpnPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBaseWithAgent; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; + +public final class ServerCollectorInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + ServerCollectorInner model = BinaryData.fromString( + "{\"properties\":{\"agentProperties\":{\"id\":\"ozfnkfexlvx\",\"version\":\"akizvoaikna\",\"lastHeartbeatUtc\":\"2021-04-06T13:12:15Z\",\"spnDetails\":{\"authority\":\"iguyxlykwphv\",\"applicationId\":\"cwxhmpej\",\"audience\":\"ke\",\"objectId\":\"onwivkcqhrxhxkn\",\"tenantId\":\"crmmkyupijuby\"}},\"discoverySiteId\":\"fkak\",\"createdTimestamp\":\"2021-11-11T13:29:18Z\",\"updatedTimestamp\":\"2021-07-21T09:43:27Z\",\"provisioningState\":\"Canceled\"},\"id\":\"il\",\"name\":\"udxjascowv\",\"type\":\"djkpdxph\"}") + .toObject(ServerCollectorInner.class); + Assertions.assertEquals(ProvisioningState.CANCELED, model.properties().provisioningState()); + Assertions.assertEquals("ozfnkfexlvx", model.properties().agentProperties().id()); + Assertions.assertEquals("akizvoaikna", model.properties().agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-04-06T13:12:15Z"), + model.properties().agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("iguyxlykwphv", model.properties().agentProperties().spnDetails().authority()); + Assertions.assertEquals("cwxhmpej", model.properties().agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("ke", model.properties().agentProperties().spnDetails().audience()); + Assertions.assertEquals("onwivkcqhrxhxkn", model.properties().agentProperties().spnDetails().objectId()); + Assertions.assertEquals("crmmkyupijuby", model.properties().agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("fkak", model.properties().discoverySiteId()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + ServerCollectorInner model = new ServerCollectorInner() + .withProperties(new CollectorPropertiesBaseWithAgent().withProvisioningState(ProvisioningState.CANCELED) + .withAgentProperties(new CollectorAgentPropertiesBase().withId("ozfnkfexlvx") + .withVersion("akizvoaikna") + .withLastHeartbeatUtc(OffsetDateTime.parse("2021-04-06T13:12:15Z")) + .withSpnDetails(new CollectorAgentSpnPropertiesBase().withAuthority("iguyxlykwphv") + .withApplicationId("cwxhmpej") + .withAudience("ke") + .withObjectId("onwivkcqhrxhxkn") + .withTenantId("crmmkyupijuby"))) + .withDiscoverySiteId("fkak")); + model = BinaryData.fromObject(model).toObject(ServerCollectorInner.class); + Assertions.assertEquals(ProvisioningState.CANCELED, model.properties().provisioningState()); + Assertions.assertEquals("ozfnkfexlvx", model.properties().agentProperties().id()); + Assertions.assertEquals("akizvoaikna", model.properties().agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-04-06T13:12:15Z"), + model.properties().agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("iguyxlykwphv", model.properties().agentProperties().spnDetails().authority()); + Assertions.assertEquals("cwxhmpej", model.properties().agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("ke", model.properties().agentProperties().spnDetails().audience()); + Assertions.assertEquals("onwivkcqhrxhxkn", model.properties().agentProperties().spnDetails().objectId()); + Assertions.assertEquals("crmmkyupijuby", model.properties().agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("fkak", model.properties().discoverySiteId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorListResultTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorListResultTests.java new file mode 100644 index 000000000000..f78f36f66a69 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorListResultTests.java @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.ServerCollectorInner; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentSpnPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBaseWithAgent; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import com.azure.resourcemanager.migration.assessment.models.ServerCollectorListResult; +import java.time.OffsetDateTime; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class ServerCollectorListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + ServerCollectorListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"agentProperties\":{\"id\":\"nq\",\"version\":\"gjfbpkuwxeoi\",\"lastHeartbeatUtc\":\"2021-05-31T08:53:37Z\",\"spnDetails\":{\"authority\":\"fa\",\"applicationId\":\"jzwfb\",\"audience\":\"aykmmf\",\"objectId\":\"bfw\",\"tenantId\":\"zxmdew\"}},\"discoverySiteId\":\"sxkrpl\",\"createdTimestamp\":\"2021-10-04T01:54:23Z\",\"updatedTimestamp\":\"2021-08-18T20:19:59Z\",\"provisioningState\":\"Failed\"},\"id\":\"viyoypsuhbrnnhjx\",\"name\":\"qwjhqkbiwetpozyc\",\"type\":\"qiqyhgfsetzlexbs\"},{\"properties\":{\"agentProperties\":{\"id\":\"ynojpziuw\",\"version\":\"zkkdtnhqs\",\"lastHeartbeatUtc\":\"2021-06-07T11:46:36Z\",\"spnDetails\":{\"authority\":\"elpkpbafvafhlbyl\",\"applicationId\":\"bevxrhyzd\",\"audience\":\"rsofpltdbmairrh\",\"objectId\":\"fnrac\",\"tenantId\":\"pqigtuujwouhd\"}},\"discoverySiteId\":\"s\",\"createdTimestamp\":\"2021-09-12T08:30:14Z\",\"updatedTimestamp\":\"2021-03-06T17:38:31Z\",\"provisioningState\":\"Updating\"},\"id\":\"jybvit\",\"name\":\"qkj\",\"type\":\"az\"}],\"nextLink\":\"mtggmu\"}") + .toObject(ServerCollectorListResult.class); + Assertions.assertEquals(ProvisioningState.FAILED, model.value().get(0).properties().provisioningState()); + Assertions.assertEquals("nq", model.value().get(0).properties().agentProperties().id()); + Assertions.assertEquals("gjfbpkuwxeoi", model.value().get(0).properties().agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-05-31T08:53:37Z"), + model.value().get(0).properties().agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("fa", model.value().get(0).properties().agentProperties().spnDetails().authority()); + Assertions.assertEquals("jzwfb", + model.value().get(0).properties().agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("aykmmf", model.value().get(0).properties().agentProperties().spnDetails().audience()); + Assertions.assertEquals("bfw", model.value().get(0).properties().agentProperties().spnDetails().objectId()); + Assertions.assertEquals("zxmdew", model.value().get(0).properties().agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("sxkrpl", model.value().get(0).properties().discoverySiteId()); + Assertions.assertEquals("mtggmu", model.nextLink()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + ServerCollectorListResult model = new ServerCollectorListResult().withValue(Arrays.asList( + new ServerCollectorInner() + .withProperties(new CollectorPropertiesBaseWithAgent().withProvisioningState(ProvisioningState.FAILED) + .withAgentProperties(new CollectorAgentPropertiesBase().withId("nq") + .withVersion("gjfbpkuwxeoi") + .withLastHeartbeatUtc(OffsetDateTime.parse("2021-05-31T08:53:37Z")) + .withSpnDetails(new CollectorAgentSpnPropertiesBase().withAuthority("fa") + .withApplicationId("jzwfb") + .withAudience("aykmmf") + .withObjectId("bfw") + .withTenantId("zxmdew"))) + .withDiscoverySiteId("sxkrpl")), + new ServerCollectorInner() + .withProperties(new CollectorPropertiesBaseWithAgent().withProvisioningState(ProvisioningState.UPDATING) + .withAgentProperties(new CollectorAgentPropertiesBase().withId("ynojpziuw") + .withVersion("zkkdtnhqs") + .withLastHeartbeatUtc(OffsetDateTime.parse("2021-06-07T11:46:36Z")) + .withSpnDetails(new CollectorAgentSpnPropertiesBase().withAuthority("elpkpbafvafhlbyl") + .withApplicationId("bevxrhyzd") + .withAudience("rsofpltdbmairrh") + .withObjectId("fnrac") + .withTenantId("pqigtuujwouhd"))) + .withDiscoverySiteId("s")))) + .withNextLink("mtggmu"); + model = BinaryData.fromObject(model).toObject(ServerCollectorListResult.class); + Assertions.assertEquals(ProvisioningState.FAILED, model.value().get(0).properties().provisioningState()); + Assertions.assertEquals("nq", model.value().get(0).properties().agentProperties().id()); + Assertions.assertEquals("gjfbpkuwxeoi", model.value().get(0).properties().agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-05-31T08:53:37Z"), + model.value().get(0).properties().agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("fa", model.value().get(0).properties().agentProperties().spnDetails().authority()); + Assertions.assertEquals("jzwfb", + model.value().get(0).properties().agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("aykmmf", model.value().get(0).properties().agentProperties().spnDetails().audience()); + Assertions.assertEquals("bfw", model.value().get(0).properties().agentProperties().spnDetails().objectId()); + Assertions.assertEquals("zxmdew", model.value().get(0).properties().agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("sxkrpl", model.value().get(0).properties().discoverySiteId()); + Assertions.assertEquals("mtggmu", model.nextLink()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorsOperationsCreateMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorsOperationsCreateMockTests.java new file mode 100644 index 000000000000..82e00b9ce175 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorsOperationsCreateMockTests.java @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentSpnPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBaseWithAgent; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import com.azure.resourcemanager.migration.assessment.models.ServerCollector; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class ServerCollectorsOperationsCreateMockTests { + @Test + public void testCreate() throws Exception { + String responseStr + = "{\"properties\":{\"agentProperties\":{\"id\":\"ekivycpzcvdizulr\",\"version\":\"bhtrezpzlpryfm\",\"lastHeartbeatUtc\":\"2021-03-29T10:22:50Z\",\"spnDetails\":{\"authority\":\"zf\",\"applicationId\":\"il\",\"audience\":\"udccgndjgdprig\",\"objectId\":\"qyeqfcbuulpyuflq\",\"tenantId\":\"shtujcyoh\"}},\"discoverySiteId\":\"imwdcsklkqnqvki\",\"createdTimestamp\":\"2021-01-31T20:14:53Z\",\"updatedTimestamp\":\"2021-09-14T00:51:35Z\",\"provisioningState\":\"Succeeded\"},\"id\":\"uyrzw\",\"name\":\"mbzayspzvrietv\",\"type\":\"phmdzxplgtp\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + ServerCollector response = manager.serverCollectorsOperations() + .define("woykdnonaaxwm") + .withExistingAssessmentProject("zbkuckgkdsksw", "iiqqcqikclsmalns") + .withProperties(new CollectorPropertiesBaseWithAgent().withProvisioningState(ProvisioningState.FAILED) + .withAgentProperties(new CollectorAgentPropertiesBase().withId("jlqcwny") + .withVersion("lei") + .withLastHeartbeatUtc(OffsetDateTime.parse("2021-10-19T04:53:11Z")) + .withSpnDetails(new CollectorAgentSpnPropertiesBase().withAuthority("vs") + .withApplicationId("sertoxadhxuvjh") + .withAudience("nrqstjcmetwmlg") + .withObjectId("vnpvvd") + .withTenantId("jnaqyq"))) + .withDiscoverySiteId("slz")) + .create(); + + Assertions.assertEquals(ProvisioningState.SUCCEEDED, response.properties().provisioningState()); + Assertions.assertEquals("ekivycpzcvdizulr", response.properties().agentProperties().id()); + Assertions.assertEquals("bhtrezpzlpryfm", response.properties().agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-03-29T10:22:50Z"), + response.properties().agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("zf", response.properties().agentProperties().spnDetails().authority()); + Assertions.assertEquals("il", response.properties().agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("udccgndjgdprig", response.properties().agentProperties().spnDetails().audience()); + Assertions.assertEquals("qyeqfcbuulpyuflq", response.properties().agentProperties().spnDetails().objectId()); + Assertions.assertEquals("shtujcyoh", response.properties().agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("imwdcsklkqnqvki", response.properties().discoverySiteId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorsOperationsDeleteWithResponseMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorsOperationsDeleteWithResponseMockTests.java new file mode 100644 index 000000000000..a12a9e6d9f5c --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorsOperationsDeleteWithResponseMockTests.java @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class ServerCollectorsOperationsDeleteWithResponseMockTests { + @Test + public void testDeleteWithResponse() throws Exception { + String responseStr = "{}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + manager.serverCollectorsOperations() + .deleteWithResponse("mtznpaxwfqtyyqi", "rcltungbsoljckm", "i", com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorsOperationsGetWithResponseMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorsOperationsGetWithResponseMockTests.java new file mode 100644 index 000000000000..b86ee5295256 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorsOperationsGetWithResponseMockTests.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import com.azure.resourcemanager.migration.assessment.models.ServerCollector; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class ServerCollectorsOperationsGetWithResponseMockTests { + @Test + public void testGetWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"agentProperties\":{\"id\":\"rfijhggabq\",\"version\":\"amklilirwdv\",\"lastHeartbeatUtc\":\"2021-02-25T01:02:51Z\",\"spnDetails\":{\"authority\":\"pzou\",\"applicationId\":\"tqrxqwqnjxrdf\",\"audience\":\"t\",\"objectId\":\"lygtavczcxdfweap\",\"tenantId\":\"mlx\"}},\"discoverySiteId\":\"jphrasp\",\"createdTimestamp\":\"2021-10-13T05:12:25Z\",\"updatedTimestamp\":\"2021-04-07T06:21:32Z\",\"provisioningState\":\"Provisioning\"},\"id\":\"mdbgi\",\"name\":\"ehfgsm\",\"type\":\"rjuqbpxtokl\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + ServerCollector response = manager.serverCollectorsOperations() + .getWithResponse("rmimrljdpoqfxyem", "kftbaewhte", "loamfmxtllfltym", com.azure.core.util.Context.NONE) + .getValue(); + + Assertions.assertEquals(ProvisioningState.PROVISIONING, response.properties().provisioningState()); + Assertions.assertEquals("rfijhggabq", response.properties().agentProperties().id()); + Assertions.assertEquals("amklilirwdv", response.properties().agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-02-25T01:02:51Z"), + response.properties().agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("pzou", response.properties().agentProperties().spnDetails().authority()); + Assertions.assertEquals("tqrxqwqnjxrdf", response.properties().agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("t", response.properties().agentProperties().spnDetails().audience()); + Assertions.assertEquals("lygtavczcxdfweap", response.properties().agentProperties().spnDetails().objectId()); + Assertions.assertEquals("mlx", response.properties().agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("jphrasp", response.properties().discoverySiteId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorsOperationsListByAssessmentProjectMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorsOperationsListByAssessmentProjectMockTests.java new file mode 100644 index 000000000000..7e7c444cdb99 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/ServerCollectorsOperationsListByAssessmentProjectMockTests.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. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import com.azure.resourcemanager.migration.assessment.models.ServerCollector; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class ServerCollectorsOperationsListByAssessmentProjectMockTests { + @Test + public void testListByAssessmentProject() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"agentProperties\":{\"id\":\"udzpgchz\",\"version\":\"fqum\",\"lastHeartbeatUtc\":\"2021-08-09T12:08:51Z\",\"spnDetails\":{\"authority\":\"zg\",\"applicationId\":\"odkynrc\",\"audience\":\"avf\",\"objectId\":\"dfmmxjdnajuopjy\",\"tenantId\":\"mk\"}},\"discoverySiteId\":\"hvcw\",\"createdTimestamp\":\"2020-12-27T08:55:26Z\",\"updatedTimestamp\":\"2021-07-26T14:54:57Z\",\"provisioningState\":\"Accepted\"},\"id\":\"uxxrwzobuzms\",\"name\":\"g\",\"type\":\"mtdtkwppthuzd\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response = manager.serverCollectorsOperations() + .listByAssessmentProject("rfrswqikwep", "ogggicwnxhtfm", com.azure.core.util.Context.NONE); + + Assertions.assertEquals(ProvisioningState.ACCEPTED, + response.iterator().next().properties().provisioningState()); + Assertions.assertEquals("udzpgchz", response.iterator().next().properties().agentProperties().id()); + Assertions.assertEquals("fqum", response.iterator().next().properties().agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-08-09T12:08:51Z"), + response.iterator().next().properties().agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("zg", + response.iterator().next().properties().agentProperties().spnDetails().authority()); + Assertions.assertEquals("odkynrc", + response.iterator().next().properties().agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("avf", + response.iterator().next().properties().agentProperties().spnDetails().audience()); + Assertions.assertEquals("dfmmxjdnajuopjy", + response.iterator().next().properties().agentProperties().spnDetails().objectId()); + Assertions.assertEquals("mk", + response.iterator().next().properties().agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("hvcw", response.iterator().next().properties().discoverySiteId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SharedResourcesDtoTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SharedResourcesDtoTests.java new file mode 100644 index 000000000000..f64bce531b40 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SharedResourcesDtoTests.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.SharedResourcesDto; + +public final class SharedResourcesDtoTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SharedResourcesDto model = BinaryData.fromString( + "{\"sharedDataDisks\":[{\"diskType\":\"PremiumV2\",\"diskSize\":\"StandardSSD_E6\",\"diskRedundancy\":\"LRS\",\"storageCost\":49.056522,\"recommendedSizeInGib\":91.00812,\"recommendedThroughputInMbps\":9.602481,\"recommendedIops\":34.19709},{\"diskType\":\"StandardSSD\",\"diskSize\":\"StandardSSD_E70\",\"diskRedundancy\":\"LRS\",\"storageCost\":95.53731,\"recommendedSizeInGib\":9.462631,\"recommendedThroughputInMbps\":56.672623,\"recommendedIops\":85.27624}],\"sharedLogDisks\":[{\"diskType\":\"StandardSSD\",\"diskSize\":\"Premium_P70\",\"diskRedundancy\":\"LRS\",\"storageCost\":37.982494,\"recommendedSizeInGib\":83.62443,\"recommendedThroughputInMbps\":27.694584,\"recommendedIops\":71.01518}],\"sharedTempDbDisks\":[{\"diskType\":\"StandardSSD\",\"diskSize\":\"Standard_S70\",\"diskRedundancy\":\"ZRS\",\"storageCost\":7.3985996,\"recommendedSizeInGib\":33.910362,\"recommendedThroughputInMbps\":58.884544,\"recommendedIops\":18.486155},{\"diskType\":\"StandardOrPremium\",\"diskSize\":\"StandardSSD_E30\",\"diskRedundancy\":\"ZRS\",\"storageCost\":68.46939,\"recommendedSizeInGib\":64.62172,\"recommendedThroughputInMbps\":86.46677,\"recommendedIops\":95.01893},{\"diskType\":\"Premium\",\"diskSize\":\"Premium_P50\",\"diskRedundancy\":\"LRS\",\"storageCost\":72.11864,\"recommendedSizeInGib\":19.875591,\"recommendedThroughputInMbps\":72.86604,\"recommendedIops\":52.05117}],\"numberOfMounts\":1786221046,\"quorumWitness\":{\"quorumWitnessType\":\"Unknown\"}}") + .toObject(SharedResourcesDto.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SharedResourcesDto model = new SharedResourcesDto(); + model = BinaryData.fromObject(model).toObject(SharedResourcesDto.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessedNetworkAdapterTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessedNetworkAdapterTests.java new file mode 100644 index 000000000000..655c868e599b --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessedNetworkAdapterTests.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.AzureNetworkAdapterSuitabilityDetail; +import com.azure.resourcemanager.migration.assessment.models.AzureNetworkAdapterSuitabilityExplanation; +import com.azure.resourcemanager.migration.assessment.models.CloudSuitability; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessedNetworkAdapter; +import org.junit.jupiter.api.Assertions; + +public final class SqlAssessedNetworkAdapterTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SqlAssessedNetworkAdapter model = BinaryData.fromString( + "{\"suitability\":\"ConditionallySuitable\",\"suitabilityDetail\":\"MegabytesOfDataTransmittedOutOfRange\",\"suitabilityExplanation\":\"InternalErrorOccurred\",\"monthlyBandwidthCosts\":55.11159,\"netGigabytesTransmittedPerMonth\":58.90187,\"name\":\"y\",\"displayName\":\"chrszi\",\"macAddress\":\"yuel\",\"ipAddresses\":[\"ndnbfqy\"],\"megabytesPerSecondReceived\":24.793839,\"megabytesPerSecondTransmitted\":46.289616}") + .toObject(SqlAssessedNetworkAdapter.class); + Assertions.assertEquals(CloudSuitability.CONDITIONALLY_SUITABLE, model.suitability()); + Assertions.assertEquals(AzureNetworkAdapterSuitabilityDetail.MEGABYTES_OF_DATA_TRANSMITTED_OUT_OF_RANGE, + model.suitabilityDetail()); + Assertions.assertEquals(AzureNetworkAdapterSuitabilityExplanation.INTERNAL_ERROR_OCCURRED, + model.suitabilityExplanation()); + Assertions.assertEquals(55.11159F, model.monthlyBandwidthCosts()); + Assertions.assertEquals(58.90187F, model.netGigabytesTransmittedPerMonth()); + Assertions.assertEquals("y", model.name()); + Assertions.assertEquals("chrszi", model.displayName()); + Assertions.assertEquals("yuel", model.macAddress()); + Assertions.assertEquals(24.793839F, model.megabytesPerSecondReceived()); + Assertions.assertEquals(46.289616F, model.megabytesPerSecondTransmitted()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SqlAssessedNetworkAdapter model + = new SqlAssessedNetworkAdapter().withSuitability(CloudSuitability.CONDITIONALLY_SUITABLE) + .withSuitabilityDetail(AzureNetworkAdapterSuitabilityDetail.MEGABYTES_OF_DATA_TRANSMITTED_OUT_OF_RANGE) + .withSuitabilityExplanation(AzureNetworkAdapterSuitabilityExplanation.INTERNAL_ERROR_OCCURRED) + .withMonthlyBandwidthCosts(55.11159F) + .withNetGigabytesTransmittedPerMonth(58.90187F) + .withName("y") + .withDisplayName("chrszi") + .withMacAddress("yuel") + .withMegabytesPerSecondReceived(24.793839F) + .withMegabytesPerSecondTransmitted(46.289616F); + model = BinaryData.fromObject(model).toObject(SqlAssessedNetworkAdapter.class); + Assertions.assertEquals(CloudSuitability.CONDITIONALLY_SUITABLE, model.suitability()); + Assertions.assertEquals(AzureNetworkAdapterSuitabilityDetail.MEGABYTES_OF_DATA_TRANSMITTED_OUT_OF_RANGE, + model.suitabilityDetail()); + Assertions.assertEquals(AzureNetworkAdapterSuitabilityExplanation.INTERNAL_ERROR_OCCURRED, + model.suitabilityExplanation()); + Assertions.assertEquals(55.11159F, model.monthlyBandwidthCosts()); + Assertions.assertEquals(58.90187F, model.netGigabytesTransmittedPerMonth()); + Assertions.assertEquals("y", model.name()); + Assertions.assertEquals("chrszi", model.displayName()); + Assertions.assertEquals("yuel", model.macAddress()); + Assertions.assertEquals(24.793839F, model.megabytesPerSecondReceived()); + Assertions.assertEquals(46.289616F, model.megabytesPerSecondTransmitted()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentMigrationIssueTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentMigrationIssueTests.java new file mode 100644 index 000000000000..1ec37f07be5f --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentMigrationIssueTests.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentMigrationIssue; + +public final class SqlAssessmentMigrationIssueTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SqlAssessmentMigrationIssue model = BinaryData.fromString( + "{\"issueId\":\"a\",\"issueCategory\":\"Issue\",\"impactedObjects\":[{\"objectName\":\"h\",\"objectType\":\"usps\"},{\"objectName\":\"sdvlmfwdgzxulucv\",\"objectType\":\"mrsreuzvxurisjnh\"},{\"objectName\":\"txifqj\",\"objectType\":\"xmrhu\"},{\"objectName\":\"wp\",\"objectType\":\"sutrgjup\"}]}") + .toObject(SqlAssessmentMigrationIssue.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SqlAssessmentMigrationIssue model = new SqlAssessmentMigrationIssue(); + model = BinaryData.fromObject(model).toObject(SqlAssessmentMigrationIssue.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentOptionsInnerTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentOptionsInnerTests.java new file mode 100644 index 000000000000..a5a23c6188ee --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentOptionsInnerTests.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. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlAssessmentOptionsInner; +import com.azure.resourcemanager.migration.assessment.models.AzureCurrency; +import com.azure.resourcemanager.migration.assessment.models.AzureLocation; +import com.azure.resourcemanager.migration.assessment.models.AzureOfferCode; +import com.azure.resourcemanager.migration.assessment.models.AzureSqlServiceTier; +import com.azure.resourcemanager.migration.assessment.models.AzureVmFamily; +import com.azure.resourcemanager.migration.assessment.models.ComputeTier; +import com.azure.resourcemanager.migration.assessment.models.HardwareGeneration; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentOptionsProperties; +import com.azure.resourcemanager.migration.assessment.models.SqlPaaSTargetOptions; +import com.azure.resourcemanager.migration.assessment.models.TargetType; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class SqlAssessmentOptionsInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SqlAssessmentOptionsInner model = BinaryData.fromString( + "{\"properties\":{\"vmFamilies\":[{\"familyName\":\"nuhzafccnuh\",\"targetLocations\":[\"byl\",\"ui\"],\"category\":[\"vatvcrkd\",\"b\"]},{\"familyName\":\"qxvhcsyhzlwxa\",\"targetLocations\":[\"vurex\"],\"category\":[\"sbdweaderzmwnt\"]},{\"familyName\":\"agttm\",\"targetLocations\":[\"agoaqylkjztji\",\"azjcgmxitpfin\",\"cpdltkrlg\"],\"category\":[\"bd\",\"vcqguefzh\",\"mpheqdur\"]},{\"familyName\":\"yujlfyoumpckyecl\",\"targetLocations\":[\"gptaj\",\"rzmq\",\"ucycijo\",\"lxiutgjcyzyzjdnr\"],\"category\":[\"txjeaoqaqbzgy\",\"fwwvuatbwbqam\",\"e\",\"liys\"]}],\"reservedInstanceVmFamilies\":[\"Msv2_series\",\"Dsv4_series\",\"Edsv5_series\",\"GS_series\"],\"premiumDiskVmFamilies\":[\"Edsv4_series\",\"Edv5_series\",\"Eadsv5_series\"],\"savingsPlanVmFamilies\":[\"Dsv3_series\",\"GS_series\",\"Esv4_series\"],\"savingsPlanSupportedLocations\":[\"AustraliaSoutheast\",\"USDoDCentral\"],\"savingsPlanSupportedLocationsForPaas\":[\"SouthAfricaWest\",\"GermanyNortheast\",\"UsSecCentral\"],\"reservedInstanceSupportedLocationsForIaas\":[\"WestEurope\",\"GermanyNorth\",\"USGovVirginia\",\"USGovIowa\"],\"savingsPlanSupportedOffers\":[\"MSAZRUSGOV0003P\",\"MSAZR0036P\",\"MSAZR0121P\",\"MSAZR0063P\"],\"sqlSkus\":[{\"computeTier\":\"Serverless\",\"hardwareGeneration\":\"Unknown\",\"targetType\":\"AzureSqlVirtualMachine\",\"serviceTier\":\"GeneralPurpose\",\"targetLocations\":[\"SwitzerlandWest\"]},{\"computeTier\":\"Provisioned\",\"hardwareGeneration\":\"Gen5\",\"targetType\":\"AzureSqlDatabase\",\"serviceTier\":\"Unknown\",\"targetLocations\":[\"SwitzerlandNorth\",\"WestCentralUs\",\"JapanEast\",\"JapanWest\"]},{\"computeTier\":\"Automatic\",\"hardwareGeneration\":\"Unknown\",\"targetType\":\"AzureSqlVirtualMachine\",\"serviceTier\":\"BusinessCritical\",\"targetLocations\":[\"USGovArizona\"]}],\"reservedInstanceSqlTargets\":[\"AzureSqlVirtualMachine\",\"Unknown\",\"AzureSqlManagedInstance\",\"Recommended\"],\"reservedInstanceSupportedLocations\":[\"WestUs\",\"SoutheastAsia\",\"CanadaCentral\",\"AustraliaCentral2\"],\"reservedInstanceSupportedCurrencies\":[\"USD\",\"DKK\",\"JPY\"],\"reservedInstanceSupportedOffers\":[\"Unknown\",\"SavingsPlan3Year\",\"MSMCAZR0063P\",\"MSMCAZR0060P\"],\"supportedOffers\":[\"MSAZR0243P\",\"MSAZR0127P\"]},\"id\":\"imwrzregzgyufu\",\"name\":\"rw\",\"type\":\"weryekzk\"}") + .toObject(SqlAssessmentOptionsInner.class); + Assertions.assertEquals(AzureVmFamily.DSV3_SERIES, model.properties().savingsPlanVmFamilies().get(0)); + Assertions.assertEquals(AzureLocation.AUSTRALIA_SOUTHEAST, + model.properties().savingsPlanSupportedLocations().get(0)); + Assertions.assertEquals(AzureLocation.SOUTH_AFRICA_WEST, + model.properties().savingsPlanSupportedLocationsForPaas().get(0)); + Assertions.assertEquals(AzureLocation.WEST_EUROPE, + model.properties().reservedInstanceSupportedLocationsForIaas().get(0)); + Assertions.assertEquals(AzureOfferCode.MSAZRUSGOV0003P, model.properties().savingsPlanSupportedOffers().get(0)); + Assertions.assertEquals(ComputeTier.SERVERLESS, model.properties().sqlSkus().get(0).computeTier()); + Assertions.assertEquals(HardwareGeneration.UNKNOWN, model.properties().sqlSkus().get(0).hardwareGeneration()); + Assertions.assertEquals(TargetType.AZURE_SQL_VIRTUAL_MACHINE, model.properties().sqlSkus().get(0).targetType()); + Assertions.assertEquals(AzureSqlServiceTier.GENERAL_PURPOSE, model.properties().sqlSkus().get(0).serviceTier()); + Assertions.assertEquals(AzureLocation.SWITZERLAND_WEST, + model.properties().sqlSkus().get(0).targetLocations().get(0)); + Assertions.assertEquals(TargetType.AZURE_SQL_VIRTUAL_MACHINE, + model.properties().reservedInstanceSqlTargets().get(0)); + Assertions.assertEquals(AzureLocation.WEST_US, model.properties().reservedInstanceSupportedLocations().get(0)); + Assertions.assertEquals(AzureCurrency.USD, model.properties().reservedInstanceSupportedCurrencies().get(0)); + Assertions.assertEquals(AzureOfferCode.UNKNOWN, model.properties().reservedInstanceSupportedOffers().get(0)); + Assertions.assertEquals(AzureOfferCode.MSAZR0243P, model.properties().supportedOffers().get(0)); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SqlAssessmentOptionsInner model + = new SqlAssessmentOptionsInner().withProperties(new SqlAssessmentOptionsProperties() + .withSavingsPlanVmFamilies( + Arrays.asList(AzureVmFamily.DSV3_SERIES, AzureVmFamily.GS_SERIES, AzureVmFamily.ESV4_SERIES)) + .withSavingsPlanSupportedLocations( + Arrays.asList(AzureLocation.AUSTRALIA_SOUTHEAST, AzureLocation.USDO_DCENTRAL)) + .withSavingsPlanSupportedLocationsForPaas(Arrays.asList(AzureLocation.SOUTH_AFRICA_WEST, + AzureLocation.GERMANY_NORTHEAST, AzureLocation.US_SEC_CENTRAL)) + .withReservedInstanceSupportedLocationsForIaas(Arrays.asList(AzureLocation.WEST_EUROPE, + AzureLocation.GERMANY_NORTH, AzureLocation.USGOV_VIRGINIA, AzureLocation.USGOV_IOWA)) + .withSavingsPlanSupportedOffers(Arrays.asList(AzureOfferCode.MSAZRUSGOV0003P, AzureOfferCode.MSAZR0036P, + AzureOfferCode.MSAZR0121P, AzureOfferCode.MSAZR0063P)) + .withSqlSkus(Arrays.asList( + new SqlPaaSTargetOptions().withComputeTier(ComputeTier.SERVERLESS) + .withHardwareGeneration(HardwareGeneration.UNKNOWN) + .withTargetType(TargetType.AZURE_SQL_VIRTUAL_MACHINE) + .withServiceTier(AzureSqlServiceTier.GENERAL_PURPOSE) + .withTargetLocations(Arrays.asList(AzureLocation.SWITZERLAND_WEST)), + new SqlPaaSTargetOptions().withComputeTier(ComputeTier.PROVISIONED) + .withHardwareGeneration(HardwareGeneration.GEN5) + .withTargetType(TargetType.AZURE_SQL_DATABASE) + .withServiceTier(AzureSqlServiceTier.UNKNOWN) + .withTargetLocations(Arrays.asList(AzureLocation.SWITZERLAND_NORTH, + AzureLocation.WEST_CENTRAL_US, AzureLocation.JAPAN_EAST, AzureLocation.JAPAN_WEST)), + new SqlPaaSTargetOptions().withComputeTier(ComputeTier.AUTOMATIC) + .withHardwareGeneration(HardwareGeneration.UNKNOWN) + .withTargetType(TargetType.AZURE_SQL_VIRTUAL_MACHINE) + .withServiceTier(AzureSqlServiceTier.BUSINESS_CRITICAL) + .withTargetLocations(Arrays.asList(AzureLocation.USGOV_ARIZONA)))) + .withReservedInstanceSqlTargets(Arrays.asList(TargetType.AZURE_SQL_VIRTUAL_MACHINE, TargetType.UNKNOWN, + TargetType.AZURE_SQL_MANAGED_INSTANCE, TargetType.RECOMMENDED)) + .withReservedInstanceSupportedLocations(Arrays.asList(AzureLocation.WEST_US, + AzureLocation.SOUTHEAST_ASIA, AzureLocation.CANADA_CENTRAL, AzureLocation.AUSTRALIA_CENTRAL2)) + .withReservedInstanceSupportedCurrencies( + Arrays.asList(AzureCurrency.USD, AzureCurrency.DKK, AzureCurrency.JPY)) + .withReservedInstanceSupportedOffers(Arrays.asList(AzureOfferCode.UNKNOWN, + AzureOfferCode.SAVINGS_PLAN3YEAR, AzureOfferCode.MSMCAZR0063P, AzureOfferCode.MSMCAZR0060P)) + .withSupportedOffers(Arrays.asList(AzureOfferCode.MSAZR0243P, AzureOfferCode.MSAZR0127P))); + model = BinaryData.fromObject(model).toObject(SqlAssessmentOptionsInner.class); + Assertions.assertEquals(AzureVmFamily.DSV3_SERIES, model.properties().savingsPlanVmFamilies().get(0)); + Assertions.assertEquals(AzureLocation.AUSTRALIA_SOUTHEAST, + model.properties().savingsPlanSupportedLocations().get(0)); + Assertions.assertEquals(AzureLocation.SOUTH_AFRICA_WEST, + model.properties().savingsPlanSupportedLocationsForPaas().get(0)); + Assertions.assertEquals(AzureLocation.WEST_EUROPE, + model.properties().reservedInstanceSupportedLocationsForIaas().get(0)); + Assertions.assertEquals(AzureOfferCode.MSAZRUSGOV0003P, model.properties().savingsPlanSupportedOffers().get(0)); + Assertions.assertEquals(ComputeTier.SERVERLESS, model.properties().sqlSkus().get(0).computeTier()); + Assertions.assertEquals(HardwareGeneration.UNKNOWN, model.properties().sqlSkus().get(0).hardwareGeneration()); + Assertions.assertEquals(TargetType.AZURE_SQL_VIRTUAL_MACHINE, model.properties().sqlSkus().get(0).targetType()); + Assertions.assertEquals(AzureSqlServiceTier.GENERAL_PURPOSE, model.properties().sqlSkus().get(0).serviceTier()); + Assertions.assertEquals(AzureLocation.SWITZERLAND_WEST, + model.properties().sqlSkus().get(0).targetLocations().get(0)); + Assertions.assertEquals(TargetType.AZURE_SQL_VIRTUAL_MACHINE, + model.properties().reservedInstanceSqlTargets().get(0)); + Assertions.assertEquals(AzureLocation.WEST_US, model.properties().reservedInstanceSupportedLocations().get(0)); + Assertions.assertEquals(AzureCurrency.USD, model.properties().reservedInstanceSupportedCurrencies().get(0)); + Assertions.assertEquals(AzureOfferCode.UNKNOWN, model.properties().reservedInstanceSupportedOffers().get(0)); + Assertions.assertEquals(AzureOfferCode.MSAZR0243P, model.properties().supportedOffers().get(0)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentOptionsListResultTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentOptionsListResultTests.java new file mode 100644 index 000000000000..c9aa4c0e5a03 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentOptionsListResultTests.java @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlAssessmentOptionsInner; +import com.azure.resourcemanager.migration.assessment.models.AzureCurrency; +import com.azure.resourcemanager.migration.assessment.models.AzureLocation; +import com.azure.resourcemanager.migration.assessment.models.AzureOfferCode; +import com.azure.resourcemanager.migration.assessment.models.AzureSqlServiceTier; +import com.azure.resourcemanager.migration.assessment.models.AzureVmFamily; +import com.azure.resourcemanager.migration.assessment.models.ComputeTier; +import com.azure.resourcemanager.migration.assessment.models.HardwareGeneration; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentOptionsListResult; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentOptionsProperties; +import com.azure.resourcemanager.migration.assessment.models.SqlPaaSTargetOptions; +import com.azure.resourcemanager.migration.assessment.models.TargetType; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class SqlAssessmentOptionsListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SqlAssessmentOptionsListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"vmFamilies\":[{\"familyName\":\"gzv\",\"targetLocations\":[\"jd\"],\"category\":[\"qnwsithuqolyah\",\"uqwqulsutrjbhxyk\",\"hyqezvqq\"]},{\"familyName\":\"drftbcvexreuquo\",\"targetLocations\":[\"jv\",\"whreagkhyxvrq\",\"vbczsulmdg\"],\"category\":[\"epjpfs\",\"ykgsangpszng\"]},{\"familyName\":\"p\",\"targetLocations\":[\"kvec\",\"ujcngo\"],\"category\":[\"edmzrgjfoknub\",\"oitpkpztrgdgx\"]},{\"familyName\":\"oqraswugyxpqi\",\"targetLocations\":[\"ialwv\",\"kbuhzaca\",\"ty\"],\"category\":[\"oqc\"]}],\"reservedInstanceVmFamilies\":[\"Dsv3_series\",\"Standard_A8_A11\",\"Ev5_series\"],\"premiumDiskVmFamilies\":[\"Unknown\",\"Fs_series\"],\"savingsPlanVmFamilies\":[\"Dav4_series\",\"Fs_series\"],\"savingsPlanSupportedLocations\":[\"GermanyNorth\"],\"savingsPlanSupportedLocationsForPaas\":[\"JapanEast\"],\"reservedInstanceSupportedLocationsForIaas\":[\"AustraliaCentral2\",\"CentralIndia\"],\"savingsPlanSupportedOffers\":[\"MSMCAZR0059P\",\"MSMCAZR0063P\",\"MSAZR0121P\",\"MSAZR0149P\"],\"sqlSkus\":[{\"computeTier\":\"Serverless\",\"hardwareGeneration\":\"Unknown\",\"targetType\":\"Recommended\",\"serviceTier\":\"Automatic\",\"targetLocations\":[\"UsSecWest\",\"GermanyNortheast\"]},{\"computeTier\":\"Serverless\",\"hardwareGeneration\":\"Automatic\",\"targetType\":\"AzureSqlVirtualMachine\",\"serviceTier\":\"GeneralPurpose\",\"targetLocations\":[\"WestUs\",\"ChinaNorth2\"]}],\"reservedInstanceSqlTargets\":[\"Unknown\",\"Recommended\",\"AzureSqlManagedInstance\",\"AzureVirtualMachine\"],\"reservedInstanceSupportedLocations\":[\"NorthEurope\",\"KoreaSouth\",\"WestIndia\",\"AustraliaCentral2\"],\"reservedInstanceSupportedCurrencies\":[\"BRL\",\"DKK\"],\"reservedInstanceSupportedOffers\":[\"MSAZRDE0044P\",\"MSMCAZR0044P\",\"MSMCAZR0128P\"],\"supportedOffers\":[\"MSMCAZR0044P\"]},\"id\":\"lialwcjgckbbcccg\",\"name\":\"praoxn\",\"type\":\"uffatsgftipwc\"}],\"nextLink\":\"yubhiqdx\"}") + .toObject(SqlAssessmentOptionsListResult.class); + Assertions.assertEquals(AzureVmFamily.DAV4_SERIES, + model.value().get(0).properties().savingsPlanVmFamilies().get(0)); + Assertions.assertEquals(AzureLocation.GERMANY_NORTH, + model.value().get(0).properties().savingsPlanSupportedLocations().get(0)); + Assertions.assertEquals(AzureLocation.JAPAN_EAST, + model.value().get(0).properties().savingsPlanSupportedLocationsForPaas().get(0)); + Assertions.assertEquals(AzureLocation.AUSTRALIA_CENTRAL2, + model.value().get(0).properties().reservedInstanceSupportedLocationsForIaas().get(0)); + Assertions.assertEquals(AzureOfferCode.MSMCAZR0059P, + model.value().get(0).properties().savingsPlanSupportedOffers().get(0)); + Assertions.assertEquals(ComputeTier.SERVERLESS, + model.value().get(0).properties().sqlSkus().get(0).computeTier()); + Assertions.assertEquals(HardwareGeneration.UNKNOWN, + model.value().get(0).properties().sqlSkus().get(0).hardwareGeneration()); + Assertions.assertEquals(TargetType.RECOMMENDED, + model.value().get(0).properties().sqlSkus().get(0).targetType()); + Assertions.assertEquals(AzureSqlServiceTier.AUTOMATIC, + model.value().get(0).properties().sqlSkus().get(0).serviceTier()); + Assertions.assertEquals(AzureLocation.US_SEC_WEST, + model.value().get(0).properties().sqlSkus().get(0).targetLocations().get(0)); + Assertions.assertEquals(TargetType.UNKNOWN, + model.value().get(0).properties().reservedInstanceSqlTargets().get(0)); + Assertions.assertEquals(AzureLocation.NORTH_EUROPE, + model.value().get(0).properties().reservedInstanceSupportedLocations().get(0)); + Assertions.assertEquals(AzureCurrency.BRL, + model.value().get(0).properties().reservedInstanceSupportedCurrencies().get(0)); + Assertions.assertEquals(AzureOfferCode.MSAZRDE0044P, + model.value().get(0).properties().reservedInstanceSupportedOffers().get(0)); + Assertions.assertEquals(AzureOfferCode.MSMCAZR0044P, + model.value().get(0).properties().supportedOffers().get(0)); + Assertions.assertEquals("yubhiqdx", model.nextLink()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SqlAssessmentOptionsListResult model = new SqlAssessmentOptionsListResult() + .withValue(Arrays.asList(new SqlAssessmentOptionsInner().withProperties(new SqlAssessmentOptionsProperties() + .withSavingsPlanVmFamilies(Arrays.asList(AzureVmFamily.DAV4_SERIES, AzureVmFamily.FS_SERIES)) + .withSavingsPlanSupportedLocations(Arrays.asList(AzureLocation.GERMANY_NORTH)) + .withSavingsPlanSupportedLocationsForPaas(Arrays.asList(AzureLocation.JAPAN_EAST)) + .withReservedInstanceSupportedLocationsForIaas( + Arrays.asList(AzureLocation.AUSTRALIA_CENTRAL2, AzureLocation.CENTRAL_INDIA)) + .withSavingsPlanSupportedOffers(Arrays.asList(AzureOfferCode.MSMCAZR0059P, AzureOfferCode.MSMCAZR0063P, + AzureOfferCode.MSAZR0121P, AzureOfferCode.MSAZR0149P)) + .withSqlSkus(Arrays.asList( + new SqlPaaSTargetOptions().withComputeTier(ComputeTier.SERVERLESS) + .withHardwareGeneration(HardwareGeneration.UNKNOWN) + .withTargetType(TargetType.RECOMMENDED) + .withServiceTier(AzureSqlServiceTier.AUTOMATIC) + .withTargetLocations(Arrays.asList(AzureLocation.US_SEC_WEST, AzureLocation.GERMANY_NORTHEAST)), + new SqlPaaSTargetOptions().withComputeTier(ComputeTier.SERVERLESS) + .withHardwareGeneration(HardwareGeneration.AUTOMATIC) + .withTargetType(TargetType.AZURE_SQL_VIRTUAL_MACHINE) + .withServiceTier(AzureSqlServiceTier.GENERAL_PURPOSE) + .withTargetLocations(Arrays.asList(AzureLocation.WEST_US, AzureLocation.CHINA_NORTH2)))) + .withReservedInstanceSqlTargets(Arrays.asList(TargetType.UNKNOWN, TargetType.RECOMMENDED, + TargetType.AZURE_SQL_MANAGED_INSTANCE, TargetType.AZURE_VIRTUAL_MACHINE)) + .withReservedInstanceSupportedLocations(Arrays.asList(AzureLocation.NORTH_EUROPE, + AzureLocation.KOREA_SOUTH, AzureLocation.WEST_INDIA, AzureLocation.AUSTRALIA_CENTRAL2)) + .withReservedInstanceSupportedCurrencies(Arrays.asList(AzureCurrency.BRL, AzureCurrency.DKK)) + .withReservedInstanceSupportedOffers(Arrays.asList(AzureOfferCode.MSAZRDE0044P, + AzureOfferCode.MSMCAZR0044P, AzureOfferCode.MSMCAZR0128P)) + .withSupportedOffers(Arrays.asList(AzureOfferCode.MSMCAZR0044P))))) + .withNextLink("yubhiqdx"); + model = BinaryData.fromObject(model).toObject(SqlAssessmentOptionsListResult.class); + Assertions.assertEquals(AzureVmFamily.DAV4_SERIES, + model.value().get(0).properties().savingsPlanVmFamilies().get(0)); + Assertions.assertEquals(AzureLocation.GERMANY_NORTH, + model.value().get(0).properties().savingsPlanSupportedLocations().get(0)); + Assertions.assertEquals(AzureLocation.JAPAN_EAST, + model.value().get(0).properties().savingsPlanSupportedLocationsForPaas().get(0)); + Assertions.assertEquals(AzureLocation.AUSTRALIA_CENTRAL2, + model.value().get(0).properties().reservedInstanceSupportedLocationsForIaas().get(0)); + Assertions.assertEquals(AzureOfferCode.MSMCAZR0059P, + model.value().get(0).properties().savingsPlanSupportedOffers().get(0)); + Assertions.assertEquals(ComputeTier.SERVERLESS, + model.value().get(0).properties().sqlSkus().get(0).computeTier()); + Assertions.assertEquals(HardwareGeneration.UNKNOWN, + model.value().get(0).properties().sqlSkus().get(0).hardwareGeneration()); + Assertions.assertEquals(TargetType.RECOMMENDED, + model.value().get(0).properties().sqlSkus().get(0).targetType()); + Assertions.assertEquals(AzureSqlServiceTier.AUTOMATIC, + model.value().get(0).properties().sqlSkus().get(0).serviceTier()); + Assertions.assertEquals(AzureLocation.US_SEC_WEST, + model.value().get(0).properties().sqlSkus().get(0).targetLocations().get(0)); + Assertions.assertEquals(TargetType.UNKNOWN, + model.value().get(0).properties().reservedInstanceSqlTargets().get(0)); + Assertions.assertEquals(AzureLocation.NORTH_EUROPE, + model.value().get(0).properties().reservedInstanceSupportedLocations().get(0)); + Assertions.assertEquals(AzureCurrency.BRL, + model.value().get(0).properties().reservedInstanceSupportedCurrencies().get(0)); + Assertions.assertEquals(AzureOfferCode.MSAZRDE0044P, + model.value().get(0).properties().reservedInstanceSupportedOffers().get(0)); + Assertions.assertEquals(AzureOfferCode.MSMCAZR0044P, + model.value().get(0).properties().supportedOffers().get(0)); + Assertions.assertEquals("yubhiqdx", model.nextLink()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentOptionsOperationsGetWithResponseMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentOptionsOperationsGetWithResponseMockTests.java new file mode 100644 index 000000000000..2db413e8b7fc --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentOptionsOperationsGetWithResponseMockTests.java @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.AzureCurrency; +import com.azure.resourcemanager.migration.assessment.models.AzureLocation; +import com.azure.resourcemanager.migration.assessment.models.AzureOfferCode; +import com.azure.resourcemanager.migration.assessment.models.AzureSqlServiceTier; +import com.azure.resourcemanager.migration.assessment.models.AzureVmFamily; +import com.azure.resourcemanager.migration.assessment.models.ComputeTier; +import com.azure.resourcemanager.migration.assessment.models.HardwareGeneration; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentOptions; +import com.azure.resourcemanager.migration.assessment.models.TargetType; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class SqlAssessmentOptionsOperationsGetWithResponseMockTests { + @Test + public void testGetWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"vmFamilies\":[{\"familyName\":\"fooy\",\"targetLocations\":[\"xdtzcqipsdudgco\",\"zomehxlantolam\"],\"category\":[\"juxkqll\"]},{\"familyName\":\"i\",\"targetLocations\":[\"dtgckzdqiqdlra\",\"rkwxo\",\"uwxsuykznhrfgsl\",\"lhpryjfzihuio\"],\"category\":[\"cpajtfe\",\"vkbdgddkrhdccxbe\"]}],\"reservedInstanceVmFamilies\":[\"Dasv5_series\",\"M_series\",\"Esv3_series\",\"Fs_series\"],\"premiumDiskVmFamilies\":[\"Esv5_series\",\"F_series\"],\"savingsPlanVmFamilies\":[\"Dasv4_series\",\"M_series\"],\"savingsPlanSupportedLocations\":[\"SouthIndia\",\"AustraliaCentral\",\"WestUs\",\"UsNatWest\"],\"savingsPlanSupportedLocationsForPaas\":[\"ChinaEast2\",\"UAECentral\",\"AustraliaEast\"],\"reservedInstanceSupportedLocationsForIaas\":[\"SwitzerlandWest\",\"UsSecWest\",\"KoreaCentral\"],\"savingsPlanSupportedOffers\":[\"MSMCAZR0060P\",\"MSAZR0060P\",\"MSAZR0025P\"],\"sqlSkus\":[{\"computeTier\":\"Serverless\",\"hardwareGeneration\":\"Unknown\",\"targetType\":\"AzureSqlVirtualMachine\",\"serviceTier\":\"Unknown\",\"targetLocations\":[\"QatarCentral\",\"AustraliaCentral2\",\"UkWest\",\"FranceSouth\"]},{\"computeTier\":\"Unknown\",\"hardwareGeneration\":\"Fsv2_series\",\"targetType\":\"Recommended\",\"serviceTier\":\"GeneralPurpose\",\"targetLocations\":[\"WestCentralUs\",\"USGovVirginia\",\"CentralIndia\"]}],\"reservedInstanceSqlTargets\":[\"AzureSqlDatabase\"],\"reservedInstanceSupportedLocations\":[\"KoreaSouth\",\"JapanEast\",\"USGovArizona\"],\"reservedInstanceSupportedCurrencies\":[\"BRL\",\"KRW\"],\"reservedInstanceSupportedOffers\":[\"MSMCAZR0060P\",\"MSAZR0111P\",\"MSAZRUSGOV0003P\",\"MSAZR0243P\"],\"supportedOffers\":[\"MSAZR0243P\"]},\"id\":\"rptvcshtkutzcttb\",\"name\":\"gdirda\",\"type\":\"m\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + SqlAssessmentOptions response = manager.sqlAssessmentOptionsOperations() + .getWithResponse("eiwtczkdd", "vovbooqbmdqrx", "glaetscflwtjd", com.azure.core.util.Context.NONE) + .getValue(); + + Assertions.assertEquals(AzureVmFamily.DASV4_SERIES, response.properties().savingsPlanVmFamilies().get(0)); + Assertions.assertEquals(AzureLocation.SOUTH_INDIA, + response.properties().savingsPlanSupportedLocations().get(0)); + Assertions.assertEquals(AzureLocation.CHINA_EAST2, + response.properties().savingsPlanSupportedLocationsForPaas().get(0)); + Assertions.assertEquals(AzureLocation.SWITZERLAND_WEST, + response.properties().reservedInstanceSupportedLocationsForIaas().get(0)); + Assertions.assertEquals(AzureOfferCode.MSMCAZR0060P, response.properties().savingsPlanSupportedOffers().get(0)); + Assertions.assertEquals(ComputeTier.SERVERLESS, response.properties().sqlSkus().get(0).computeTier()); + Assertions.assertEquals(HardwareGeneration.UNKNOWN, + response.properties().sqlSkus().get(0).hardwareGeneration()); + Assertions.assertEquals(TargetType.AZURE_SQL_VIRTUAL_MACHINE, + response.properties().sqlSkus().get(0).targetType()); + Assertions.assertEquals(AzureSqlServiceTier.UNKNOWN, response.properties().sqlSkus().get(0).serviceTier()); + Assertions.assertEquals(AzureLocation.QATAR_CENTRAL, + response.properties().sqlSkus().get(0).targetLocations().get(0)); + Assertions.assertEquals(TargetType.AZURE_SQL_DATABASE, + response.properties().reservedInstanceSqlTargets().get(0)); + Assertions.assertEquals(AzureLocation.KOREA_SOUTH, + response.properties().reservedInstanceSupportedLocations().get(0)); + Assertions.assertEquals(AzureCurrency.BRL, response.properties().reservedInstanceSupportedCurrencies().get(0)); + Assertions.assertEquals(AzureOfferCode.MSMCAZR0060P, + response.properties().reservedInstanceSupportedOffers().get(0)); + Assertions.assertEquals(AzureOfferCode.MSAZR0243P, response.properties().supportedOffers().get(0)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentOptionsOperationsListByAssessmentProjectMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentOptionsOperationsListByAssessmentProjectMockTests.java new file mode 100644 index 000000000000..c7b55fb034d4 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentOptionsOperationsListByAssessmentProjectMockTests.java @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.AzureCurrency; +import com.azure.resourcemanager.migration.assessment.models.AzureLocation; +import com.azure.resourcemanager.migration.assessment.models.AzureOfferCode; +import com.azure.resourcemanager.migration.assessment.models.AzureSqlServiceTier; +import com.azure.resourcemanager.migration.assessment.models.AzureVmFamily; +import com.azure.resourcemanager.migration.assessment.models.ComputeTier; +import com.azure.resourcemanager.migration.assessment.models.HardwareGeneration; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentOptions; +import com.azure.resourcemanager.migration.assessment.models.TargetType; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class SqlAssessmentOptionsOperationsListByAssessmentProjectMockTests { + @Test + public void testListByAssessmentProject() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"vmFamilies\":[{\"familyName\":\"ofuworimmovzwde\",\"targetLocations\":[\"mvhzfovanyrvaprt\",\"elgwewi\"],\"category\":[\"aq\",\"ndmymnqoqjumov\",\"fbpbvzopaxmfmvsm\",\"woxfaxdtnqifbsa\"]},{\"familyName\":\"oiauesugmocpcj\",\"targetLocations\":[\"oelrgttwfl\"],\"category\":[\"uorinikcedpk\",\"riwmmtmqrxrzqv\",\"yczyayubtgm\"]}],\"reservedInstanceVmFamilies\":[\"Eav4_series\",\"Dv3_series\",\"Unknown\"],\"premiumDiskVmFamilies\":[\"Unknown\"],\"savingsPlanVmFamilies\":[\"Ev4_series\",\"Dv5_series\"],\"savingsPlanSupportedLocations\":[\"BrazilSouth\",\"UsSecEast\",\"ChinaNorth\"],\"savingsPlanSupportedLocationsForPaas\":[\"NorwayWest\"],\"reservedInstanceSupportedLocationsForIaas\":[\"WestCentralUs\",\"SwitzerlandWest\",\"ChinaNorth\"],\"savingsPlanSupportedOffers\":[\"MSAZR0122P\"],\"sqlSkus\":[{\"computeTier\":\"Unknown\",\"hardwareGeneration\":\"DC_series\",\"targetType\":\"AzureVirtualMachine\",\"serviceTier\":\"Unknown\",\"targetLocations\":[\"USGovIowa\",\"QatarCentral\"]},{\"computeTier\":\"Serverless\",\"hardwareGeneration\":\"Gen5\",\"targetType\":\"AzureSqlVirtualMachine\",\"serviceTier\":\"BusinessCritical\",\"targetLocations\":[\"USGovVirginia\",\"AustraliaSoutheast\",\"WestUs2\",\"SwitzerlandNorth\"]}],\"reservedInstanceSqlTargets\":[\"AzureVirtualMachine\",\"AzureVirtualMachine\"],\"reservedInstanceSupportedLocations\":[\"FranceSouth\",\"UsSecEast\",\"EastUs\"],\"reservedInstanceSupportedCurrencies\":[\"NZD\",\"BRL\"],\"reservedInstanceSupportedOffers\":[\"MSAZR0063P\",\"MSAZR0149P\",\"MSAZR0063P\"],\"supportedOffers\":[\"MSAZR0124P\",\"MSAZR0127P\"]},\"id\":\"faryrvjlg\",\"name\":\"ezvjq\",\"type\":\"ahoyiyaxqvj\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response = manager.sqlAssessmentOptionsOperations() + .listByAssessmentProject("dvatlzmgschn", "rsbkkzovlzdmnfmf", com.azure.core.util.Context.NONE); + + Assertions.assertEquals(AzureVmFamily.EV4_SERIES, + response.iterator().next().properties().savingsPlanVmFamilies().get(0)); + Assertions.assertEquals(AzureLocation.BRAZIL_SOUTH, + response.iterator().next().properties().savingsPlanSupportedLocations().get(0)); + Assertions.assertEquals(AzureLocation.NORWAY_WEST, + response.iterator().next().properties().savingsPlanSupportedLocationsForPaas().get(0)); + Assertions.assertEquals(AzureLocation.WEST_CENTRAL_US, + response.iterator().next().properties().reservedInstanceSupportedLocationsForIaas().get(0)); + Assertions.assertEquals(AzureOfferCode.MSAZR0122P, + response.iterator().next().properties().savingsPlanSupportedOffers().get(0)); + Assertions.assertEquals(ComputeTier.UNKNOWN, + response.iterator().next().properties().sqlSkus().get(0).computeTier()); + Assertions.assertEquals(HardwareGeneration.DC_SERIES, + response.iterator().next().properties().sqlSkus().get(0).hardwareGeneration()); + Assertions.assertEquals(TargetType.AZURE_VIRTUAL_MACHINE, + response.iterator().next().properties().sqlSkus().get(0).targetType()); + Assertions.assertEquals(AzureSqlServiceTier.UNKNOWN, + response.iterator().next().properties().sqlSkus().get(0).serviceTier()); + Assertions.assertEquals(AzureLocation.USGOV_IOWA, + response.iterator().next().properties().sqlSkus().get(0).targetLocations().get(0)); + Assertions.assertEquals(TargetType.AZURE_VIRTUAL_MACHINE, + response.iterator().next().properties().reservedInstanceSqlTargets().get(0)); + Assertions.assertEquals(AzureLocation.FRANCE_SOUTH, + response.iterator().next().properties().reservedInstanceSupportedLocations().get(0)); + Assertions.assertEquals(AzureCurrency.NZD, + response.iterator().next().properties().reservedInstanceSupportedCurrencies().get(0)); + Assertions.assertEquals(AzureOfferCode.MSAZR0063P, + response.iterator().next().properties().reservedInstanceSupportedOffers().get(0)); + Assertions.assertEquals(AzureOfferCode.MSAZR0124P, + response.iterator().next().properties().supportedOffers().get(0)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentOptionsPropertiesTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentOptionsPropertiesTests.java new file mode 100644 index 000000000000..21bef70e7578 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentOptionsPropertiesTests.java @@ -0,0 +1,103 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.AzureCurrency; +import com.azure.resourcemanager.migration.assessment.models.AzureLocation; +import com.azure.resourcemanager.migration.assessment.models.AzureOfferCode; +import com.azure.resourcemanager.migration.assessment.models.AzureSqlServiceTier; +import com.azure.resourcemanager.migration.assessment.models.AzureVmFamily; +import com.azure.resourcemanager.migration.assessment.models.ComputeTier; +import com.azure.resourcemanager.migration.assessment.models.HardwareGeneration; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentOptionsProperties; +import com.azure.resourcemanager.migration.assessment.models.SqlPaaSTargetOptions; +import com.azure.resourcemanager.migration.assessment.models.TargetType; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class SqlAssessmentOptionsPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SqlAssessmentOptionsProperties model = BinaryData.fromString( + "{\"vmFamilies\":[{\"familyName\":\"ottaw\",\"targetLocations\":[\"sxwwhnhjtf\"],\"category\":[\"dpmiljpn\"]},{\"familyName\":\"nudqllz\",\"targetLocations\":[\"zp\",\"lxeehuxiq\",\"zlrayme\"],\"category\":[\"skihmxrfd\",\"ajrednwyyshtuw\",\"mevuafpwzy\",\"frkgwltxeq\"]}],\"reservedInstanceVmFamilies\":[\"Eadsv5_series\",\"Dasv4_series\",\"Ebdsv5_series\",\"Standard_A8_A11\"],\"premiumDiskVmFamilies\":[\"GS_series\",\"Ev3_series\",\"Easv4_series\"],\"savingsPlanVmFamilies\":[\"Ls_series\",\"Dadsv5_series\",\"Ddsv5_series\"],\"savingsPlanSupportedLocations\":[\"CentralUs\"],\"savingsPlanSupportedLocationsForPaas\":[\"GermanyWestCentral\"],\"reservedInstanceSupportedLocationsForIaas\":[\"KoreaSouth\"],\"savingsPlanSupportedOffers\":[\"MSMCAZR0120P\",\"MSAZRUSGOV0003P\",\"MSAZR0036P\",\"MSAZR0122P\"],\"sqlSkus\":[{\"computeTier\":\"Provisioned\",\"hardwareGeneration\":\"Unknown\",\"targetType\":\"AzureSqlVirtualMachine\",\"serviceTier\":\"BusinessCritical\",\"targetLocations\":[\"JapanWest\",\"AustraliaCentral\",\"SwitzerlandNorth\",\"FranceSouth\"]},{\"computeTier\":\"Provisioned\",\"hardwareGeneration\":\"Fsv2_series\",\"targetType\":\"Unknown\",\"serviceTier\":\"Unknown\",\"targetLocations\":[\"ChinaEast2\",\"CanadaEast\",\"SouthCentralUs\",\"AustraliaCentral2\"]},{\"computeTier\":\"Serverless\",\"hardwareGeneration\":\"Unknown\",\"targetType\":\"Unknown\",\"serviceTier\":\"BusinessCritical\",\"targetLocations\":[\"UAENorth\"]},{\"computeTier\":\"Serverless\",\"hardwareGeneration\":\"DC_series\",\"targetType\":\"AzureVirtualMachine\",\"serviceTier\":\"BusinessCritical\",\"targetLocations\":[\"ChinaEast2\",\"GermanyWestCentral\"]}],\"reservedInstanceSqlTargets\":[\"AzureSqlDatabase\",\"AzureSqlManagedInstance\"],\"reservedInstanceSupportedLocations\":[\"SouthIndia\",\"JapanEast\"],\"reservedInstanceSupportedCurrencies\":[\"MYR\"],\"reservedInstanceSupportedOffers\":[\"MSAZR0128P\",\"MSAZR0025P\"],\"supportedOffers\":[\"MSMCAZR0044P\",\"MSMCAZR0059P\",\"MSMCAZR0044P\",\"MSAZR0148P\"]}") + .toObject(SqlAssessmentOptionsProperties.class); + Assertions.assertEquals(AzureVmFamily.LS_SERIES, model.savingsPlanVmFamilies().get(0)); + Assertions.assertEquals(AzureLocation.CENTRAL_US, model.savingsPlanSupportedLocations().get(0)); + Assertions.assertEquals(AzureLocation.GERMANY_WEST_CENTRAL, + model.savingsPlanSupportedLocationsForPaas().get(0)); + Assertions.assertEquals(AzureLocation.KOREA_SOUTH, model.reservedInstanceSupportedLocationsForIaas().get(0)); + Assertions.assertEquals(AzureOfferCode.MSMCAZR0120P, model.savingsPlanSupportedOffers().get(0)); + Assertions.assertEquals(ComputeTier.PROVISIONED, model.sqlSkus().get(0).computeTier()); + Assertions.assertEquals(HardwareGeneration.UNKNOWN, model.sqlSkus().get(0).hardwareGeneration()); + Assertions.assertEquals(TargetType.AZURE_SQL_VIRTUAL_MACHINE, model.sqlSkus().get(0).targetType()); + Assertions.assertEquals(AzureSqlServiceTier.BUSINESS_CRITICAL, model.sqlSkus().get(0).serviceTier()); + Assertions.assertEquals(AzureLocation.JAPAN_WEST, model.sqlSkus().get(0).targetLocations().get(0)); + Assertions.assertEquals(TargetType.AZURE_SQL_DATABASE, model.reservedInstanceSqlTargets().get(0)); + Assertions.assertEquals(AzureLocation.SOUTH_INDIA, model.reservedInstanceSupportedLocations().get(0)); + Assertions.assertEquals(AzureCurrency.MYR, model.reservedInstanceSupportedCurrencies().get(0)); + Assertions.assertEquals(AzureOfferCode.MSAZR0128P, model.reservedInstanceSupportedOffers().get(0)); + Assertions.assertEquals(AzureOfferCode.MSMCAZR0044P, model.supportedOffers().get(0)); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SqlAssessmentOptionsProperties model = new SqlAssessmentOptionsProperties() + .withSavingsPlanVmFamilies( + Arrays.asList(AzureVmFamily.LS_SERIES, AzureVmFamily.DADSV5_SERIES, AzureVmFamily.DDSV5_SERIES)) + .withSavingsPlanSupportedLocations(Arrays.asList(AzureLocation.CENTRAL_US)) + .withSavingsPlanSupportedLocationsForPaas(Arrays.asList(AzureLocation.GERMANY_WEST_CENTRAL)) + .withReservedInstanceSupportedLocationsForIaas(Arrays.asList(AzureLocation.KOREA_SOUTH)) + .withSavingsPlanSupportedOffers(Arrays.asList(AzureOfferCode.MSMCAZR0120P, AzureOfferCode.MSAZRUSGOV0003P, + AzureOfferCode.MSAZR0036P, AzureOfferCode.MSAZR0122P)) + .withSqlSkus(Arrays.asList( + new SqlPaaSTargetOptions().withComputeTier(ComputeTier.PROVISIONED) + .withHardwareGeneration(HardwareGeneration.UNKNOWN) + .withTargetType(TargetType.AZURE_SQL_VIRTUAL_MACHINE) + .withServiceTier(AzureSqlServiceTier.BUSINESS_CRITICAL) + .withTargetLocations(Arrays.asList(AzureLocation.JAPAN_WEST, AzureLocation.AUSTRALIA_CENTRAL, + AzureLocation.SWITZERLAND_NORTH, AzureLocation.FRANCE_SOUTH)), + new SqlPaaSTargetOptions().withComputeTier(ComputeTier.PROVISIONED) + .withHardwareGeneration(HardwareGeneration.FSV2_SERIES) + .withTargetType(TargetType.UNKNOWN) + .withServiceTier(AzureSqlServiceTier.UNKNOWN) + .withTargetLocations(Arrays.asList(AzureLocation.CHINA_EAST2, AzureLocation.CANADA_EAST, + AzureLocation.SOUTH_CENTRAL_US, AzureLocation.AUSTRALIA_CENTRAL2)), + new SqlPaaSTargetOptions().withComputeTier(ComputeTier.SERVERLESS) + .withHardwareGeneration(HardwareGeneration.UNKNOWN) + .withTargetType(TargetType.UNKNOWN) + .withServiceTier(AzureSqlServiceTier.BUSINESS_CRITICAL) + .withTargetLocations(Arrays.asList(AzureLocation.UAENORTH)), + new SqlPaaSTargetOptions().withComputeTier(ComputeTier.SERVERLESS) + .withHardwareGeneration(HardwareGeneration.DC_SERIES) + .withTargetType(TargetType.AZURE_VIRTUAL_MACHINE) + .withServiceTier(AzureSqlServiceTier.BUSINESS_CRITICAL) + .withTargetLocations(Arrays.asList(AzureLocation.CHINA_EAST2, AzureLocation.GERMANY_WEST_CENTRAL)))) + .withReservedInstanceSqlTargets( + Arrays.asList(TargetType.AZURE_SQL_DATABASE, TargetType.AZURE_SQL_MANAGED_INSTANCE)) + .withReservedInstanceSupportedLocations(Arrays.asList(AzureLocation.SOUTH_INDIA, AzureLocation.JAPAN_EAST)) + .withReservedInstanceSupportedCurrencies(Arrays.asList(AzureCurrency.MYR)) + .withReservedInstanceSupportedOffers(Arrays.asList(AzureOfferCode.MSAZR0128P, AzureOfferCode.MSAZR0025P)) + .withSupportedOffers(Arrays.asList(AzureOfferCode.MSMCAZR0044P, AzureOfferCode.MSMCAZR0059P, + AzureOfferCode.MSMCAZR0044P, AzureOfferCode.MSAZR0148P)); + model = BinaryData.fromObject(model).toObject(SqlAssessmentOptionsProperties.class); + Assertions.assertEquals(AzureVmFamily.LS_SERIES, model.savingsPlanVmFamilies().get(0)); + Assertions.assertEquals(AzureLocation.CENTRAL_US, model.savingsPlanSupportedLocations().get(0)); + Assertions.assertEquals(AzureLocation.GERMANY_WEST_CENTRAL, + model.savingsPlanSupportedLocationsForPaas().get(0)); + Assertions.assertEquals(AzureLocation.KOREA_SOUTH, model.reservedInstanceSupportedLocationsForIaas().get(0)); + Assertions.assertEquals(AzureOfferCode.MSMCAZR0120P, model.savingsPlanSupportedOffers().get(0)); + Assertions.assertEquals(ComputeTier.PROVISIONED, model.sqlSkus().get(0).computeTier()); + Assertions.assertEquals(HardwareGeneration.UNKNOWN, model.sqlSkus().get(0).hardwareGeneration()); + Assertions.assertEquals(TargetType.AZURE_SQL_VIRTUAL_MACHINE, model.sqlSkus().get(0).targetType()); + Assertions.assertEquals(AzureSqlServiceTier.BUSINESS_CRITICAL, model.sqlSkus().get(0).serviceTier()); + Assertions.assertEquals(AzureLocation.JAPAN_WEST, model.sqlSkus().get(0).targetLocations().get(0)); + Assertions.assertEquals(TargetType.AZURE_SQL_DATABASE, model.reservedInstanceSqlTargets().get(0)); + Assertions.assertEquals(AzureLocation.SOUTH_INDIA, model.reservedInstanceSupportedLocations().get(0)); + Assertions.assertEquals(AzureCurrency.MYR, model.reservedInstanceSupportedCurrencies().get(0)); + Assertions.assertEquals(AzureOfferCode.MSAZR0128P, model.reservedInstanceSupportedOffers().get(0)); + Assertions.assertEquals(AzureOfferCode.MSMCAZR0044P, model.supportedOffers().get(0)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2OperationsDeleteWithResponseMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2OperationsDeleteWithResponseMockTests.java new file mode 100644 index 000000000000..8b6431fba894 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2OperationsDeleteWithResponseMockTests.java @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class SqlAssessmentV2OperationsDeleteWithResponseMockTests { + @Test + public void testDeleteWithResponse() throws Exception { + String responseStr = "{}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + manager.sqlAssessmentV2Operations() + .deleteWithResponse("cirtn", "emmjauwcg", "efnoh", "itranizerwguda", com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2OperationsDownloadUrlMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2OperationsDownloadUrlMockTests.java new file mode 100644 index 000000000000..65551c5234c9 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2OperationsDownloadUrlMockTests.java @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.DownloadUrl; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class SqlAssessmentV2OperationsDownloadUrlMockTests { + @Test + public void testDownloadUrl() throws Exception { + String responseStr + = "{\"assessmentReportUrl\":\"tmojhvrztnvgyshq\",\"expirationTime\":\"2021-01-12T06:13:47Z\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + DownloadUrl response = manager.sqlAssessmentV2Operations() + .downloadUrl("mxubvfbngfcoce", "hpriylfm", "ztraud", "vhl", "datadculregp", + com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2SummaryDataTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2SummaryDataTests.java new file mode 100644 index 000000000000..518ec9dfe196 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2SummaryDataTests.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentV2SummaryData; + +public final class SqlAssessmentV2SummaryDataTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SqlAssessmentV2SummaryData model = BinaryData.fromString( + "{\"suitabilitySummary\":{\"ydrtc\":1327503976},\"monthlyComputeCost\":58.1101,\"monthlyStorageCost\":80.28519,\"monthlyLicenseCost\":8.106685,\"confidenceScore\":93.98728,\"monthlySecurityCost\":78.215355}") + .toObject(SqlAssessmentV2SummaryData.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SqlAssessmentV2SummaryData model = new SqlAssessmentV2SummaryData(); + model = BinaryData.fromObject(model).toObject(SqlAssessmentV2SummaryData.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2SummaryInnerTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2SummaryInnerTests.java new file mode 100644 index 000000000000..55c6b0510a91 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2SummaryInnerTests.java @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlAssessmentV2SummaryInner; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentV2SummaryProperties; + +public final class SqlAssessmentV2SummaryInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SqlAssessmentV2SummaryInner model = BinaryData.fromString( + "{\"properties\":{\"assessmentSummary\":{\"gbgatzuuvbxn\":{\"suitabilitySummary\":{\"zqddtjwfljhzn\":1142415725,\"tuatmzwcj\":1931902052},\"monthlyComputeCost\":38.441837,\"monthlyStorageCost\":26.924026,\"monthlyLicenseCost\":2.3001134,\"confidenceScore\":18.954992,\"monthlySecurityCost\":84.98299},\"buocnjr\":{\"suitabilitySummary\":{\"wggahttzlswvaj\":2004295081,\"utlxjoqzasunwqrj\":505799405},\"monthlyComputeCost\":10.120636,\"monthlyStorageCost\":9.708929,\"monthlyLicenseCost\":59.0353,\"confidenceScore\":93.65819,\"monthlySecurityCost\":76.53575}},\"distributionBySupportStatus\":{\"py\":947492752,\"xameblydyvkfkm\":345056538,\"cxneh\":1201286902,\"mtodl\":400790615},\"distributionByServicePackInsight\":{\"pucygvoavyunss\":1892666564,\"ghiee\":2011344942,\"lgvvpaseksgbu\":230828821},\"distributionBySqlVersion\":{\"uygdhgaqipirp\":435496231,\"rqofulopmjnlexwh\":779964189,\"jpib\":811615068,\"phuuuerctato\":151309152},\"distributionBySqlEdition\":{\"qpbrlc\":1997384455,\"duczkgof\":1276551040},\"instanceDistributionBySizingCriterion\":{\"rucvcrrpcjttbs\":1320256014,\"jeaq\":2056089114},\"databaseDistributionBySizingCriterion\":{\"vfkoxml\":719536452,\"ktuidvrm\":508390105},\"numberOfMachines\":1771864251,\"numberOfSqlInstances\":1980965874,\"numberOfSuccessfullyDiscoveredSqlInstances\":621685940,\"numberOfSqlDatabases\":1574301649,\"numberOfFciInstances\":475011080,\"numberOfSqlAvailabilityGroups\":2021473351},\"id\":\"azipbhpwvqsg\",\"name\":\"yy\",\"type\":\"uzivensrpmeyyvp\"}") + .toObject(SqlAssessmentV2SummaryInner.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SqlAssessmentV2SummaryInner model + = new SqlAssessmentV2SummaryInner().withProperties(new SqlAssessmentV2SummaryProperties()); + model = BinaryData.fromObject(model).toObject(SqlAssessmentV2SummaryInner.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2SummaryListResultTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2SummaryListResultTests.java new file mode 100644 index 000000000000..8c065a0b298a --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2SummaryListResultTests.java @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlAssessmentV2SummaryInner; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentV2SummaryListResult; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentV2SummaryProperties; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class SqlAssessmentV2SummaryListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SqlAssessmentV2SummaryListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"assessmentSummary\":{\"nbkkjanurnnq\":{\"suitabilitySummary\":{\"xzji\":360585194,\"vuaurk\":179847946,\"ci\":781335273},\"monthlyComputeCost\":42.100155,\"monthlyStorageCost\":6.386435,\"monthlyLicenseCost\":59.72503,\"confidenceScore\":4.9952865,\"monthlySecurityCost\":36.149452},\"vctafsrb\":{\"suitabilitySummary\":{\"pizxqltgrdogyp\":535354048},\"monthlyComputeCost\":4.0882587,\"monthlyStorageCost\":25.938343,\"monthlyLicenseCost\":96.1939,\"confidenceScore\":15.696883,\"monthlySecurityCost\":30.422241},\"wqagnepzwa\":{\"suitabilitySummary\":{\"m\":1897800975},\"monthlyComputeCost\":26.815706,\"monthlyStorageCost\":52.668564,\"monthlyLicenseCost\":76.475235,\"confidenceScore\":3.0665696,\"monthlySecurityCost\":61.442966},\"zisglrrczezkhh\":{\"suitabilitySummary\":{\"sbq\":2052489280},\"monthlyComputeCost\":53.993744,\"monthlyStorageCost\":74.66148,\"monthlyLicenseCost\":91.80716,\"confidenceScore\":9.611225,\"monthlySecurityCost\":10.501474}},\"distributionBySupportStatus\":{\"adhqoa\":244052018},\"distributionByServicePackInsight\":{\"yueayfbpcmsp\":1275493501,\"yrrueqth\":152044099,\"gnmbscbbxigdhx\":479605196,\"d\":909175637},\"distributionBySqlVersion\":{\"dbwdpyqyybxubmdn\":904820675,\"cbq\":935812516,\"e\":949316725},\"distributionBySqlEdition\":{\"aqacigeleohd\":434183344},\"instanceDistributionBySizingCriterion\":{\"wzkjopwbeonrlkw\":1335444948,\"qybxceakxcp\":1224778046,\"oqfyiaseqch\":1877879239,\"ttzrazisgyki\":1352449329},\"databaseDistributionBySizingCriterion\":{\"anbwzohmnrxxbso\":1663489412,\"linhmdptysprqs\":1529419314},\"numberOfMachines\":205223358,\"numberOfSqlInstances\":1772909914,\"numberOfSuccessfullyDiscoveredSqlInstances\":1747064559,\"numberOfSqlDatabases\":70597241,\"numberOfFciInstances\":990938401,\"numberOfSqlAvailabilityGroups\":252558767},\"id\":\"liufiqwoyxq\",\"name\":\"apcohhouc\",\"type\":\"pqojxcx\"}],\"nextLink\":\"zdcgdzbenr\"}") + .toObject(SqlAssessmentV2SummaryListResult.class); + Assertions.assertEquals("zdcgdzbenr", model.nextLink()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SqlAssessmentV2SummaryListResult model = new SqlAssessmentV2SummaryListResult() + .withValue( + Arrays.asList(new SqlAssessmentV2SummaryInner().withProperties(new SqlAssessmentV2SummaryProperties()))) + .withNextLink("zdcgdzbenr"); + model = BinaryData.fromObject(model).toObject(SqlAssessmentV2SummaryListResult.class); + Assertions.assertEquals("zdcgdzbenr", model.nextLink()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2SummaryOperationsGetWithResponseMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2SummaryOperationsGetWithResponseMockTests.java new file mode 100644 index 000000000000..575575c28379 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2SummaryOperationsGetWithResponseMockTests.java @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentV2Summary; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class SqlAssessmentV2SummaryOperationsGetWithResponseMockTests { + @Test + public void testGetWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"assessmentSummary\":{\"uoorssatfybipufd\":{\"suitabilitySummary\":{\"jobzrfp\":1468320932,\"zdcqhyftcvb\":478729922},\"monthlyComputeCost\":56.466736,\"monthlyStorageCost\":1.3600409,\"monthlyLicenseCost\":11.365062,\"confidenceScore\":87.35244,\"monthlySecurityCost\":36.231476},\"pbtsixhgvbhxmnd\":{\"suitabilitySummary\":{\"bd\":1239120549,\"as\":1806172168},\"monthlyComputeCost\":81.84618,\"monthlyStorageCost\":4.6119747,\"monthlyLicenseCost\":68.0381,\"confidenceScore\":87.68802,\"monthlySecurityCost\":58.643806},\"ynosugkfhaxt\":{\"suitabilitySummary\":{\"q\":1653739504,\"yqmarxneib\":2044971910,\"brhbjdqknhqn\":1864849199,\"tpuwnnohmmzngocf\":1072575893},\"monthlyComputeCost\":79.477905,\"monthlyStorageCost\":60.40357,\"monthlyLicenseCost\":48.387802,\"confidenceScore\":97.191414,\"monthlySecurityCost\":22.06496}},\"distributionBySupportStatus\":{\"mwgsghq\":1634063639},\"distributionByServicePackInsight\":{\"lddauqmllfe\":982301337,\"hxuarig\":1031526761,\"dlj\":973089478,\"q\":2017658706},\"distributionBySqlVersion\":{\"bzkuastaxklpr\":618485084,\"l\":73703412},\"distributionBySqlEdition\":{\"oizwxvs\":208213223},\"instanceDistributionBySizingCriterion\":{\"fyy\":1134538169},\"databaseDistributionBySizingCriterion\":{\"kgaf\":1229970273,\"z\":1442778266},\"numberOfMachines\":241765250,\"numberOfSqlInstances\":1019734668,\"numberOfSuccessfullyDiscoveredSqlInstances\":327817901,\"numberOfSqlDatabases\":1900107834,\"numberOfFciInstances\":699440843,\"numberOfSqlAvailabilityGroups\":1580992750},\"id\":\"eszr\",\"name\":\"lhpdhwynctaczcnj\",\"type\":\"mbbfnv\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + SqlAssessmentV2Summary response = manager.sqlAssessmentV2SummaryOperations() + .getWithResponse("abdxfkuzb", "jecooyvhtu", "bpelniibncgagd", "cdqhftz", "pyfaofdfp", + com.azure.core.util.Context.NONE) + .getValue(); + + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2SummaryOperationsListBySqlAssessmentV2MockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2SummaryOperationsListBySqlAssessmentV2MockTests.java new file mode 100644 index 000000000000..c9f8bf867427 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2SummaryOperationsListBySqlAssessmentV2MockTests.java @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentV2Summary; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class SqlAssessmentV2SummaryOperationsListBySqlAssessmentV2MockTests { + @Test + public void testListBySqlAssessmentV2() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"assessmentSummary\":{\"ghnysvlpyeuu\":{\"suitabilitySummary\":{\"fk\":375029538,\"utibhlen\":1683631682,\"rvrk\":41830882},\"monthlyComputeCost\":21.447247,\"monthlyStorageCost\":1.8556774,\"monthlyLicenseCost\":51.31923,\"confidenceScore\":38.36888,\"monthlySecurityCost\":54.251736}},\"distributionBySupportStatus\":{\"ixqbolxvhhyqqeg\":1357963026,\"xgrzn\":1380260544,\"inmtsdixchwkibm\":540272069},\"distributionByServicePackInsight\":{\"ncjcag\":844595957,\"rwcqzo\":1766031205},\"distributionBySqlVersion\":{\"qjsvep\":1973070159,\"htleberpyljek\":303598295},\"distributionBySqlEdition\":{\"wjjqxowkdnjrx\":84522132,\"rhw\":1710147308},\"instanceDistributionBySizingCriterion\":{\"cpnowaw\":1916974086,\"oehrguqlhfwafbj\":1220851428,\"pyrgu\":377008762,\"azbkocbygvthrmxk\":1867492168},\"databaseDistributionBySizingCriterion\":{\"wdxomrawp\":349878823},\"numberOfMachines\":1860244201,\"numberOfSqlInstances\":691230543,\"numberOfSuccessfullyDiscoveredSqlInstances\":371950285,\"numberOfSqlDatabases\":53530423,\"numberOfFciInstances\":1435608560,\"numberOfSqlAvailabilityGroups\":1885342737},\"id\":\"aeda\",\"name\":\"i\",\"type\":\"clmgdtw\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response = manager.sqlAssessmentV2SummaryOperations() + .listBySqlAssessmentV2("jeuxsphlo", "fpmijpdvzvfbhwbd", "ufvcgnrgl", "qrwyambh", + com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2SummaryPropertiesTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2SummaryPropertiesTests.java new file mode 100644 index 000000000000..45bd156e8fab --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAssessmentV2SummaryPropertiesTests.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.SqlAssessmentV2SummaryProperties; + +public final class SqlAssessmentV2SummaryPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SqlAssessmentV2SummaryProperties model = BinaryData.fromString( + "{\"assessmentSummary\":{\"ajlfnthiqfyu\":{\"suitabilitySummary\":{\"ijp\":806090947,\"sksrfhfvolmknbn\":1945803494,\"cdommpvfqaw\":1021190323,\"gbrt\":1577393635},\"monthlyComputeCost\":13.88855,\"monthlyStorageCost\":62.33673,\"monthlyLicenseCost\":82.40468,\"confidenceScore\":49.691647,\"monthlySecurityCost\":31.652159}},\"distributionBySupportStatus\":{\"ygbpvnwswmt\":1631679355,\"yctww\":187719631,\"wxjlmec\":1491153884,\"gygzyvn\":510904775},\"distributionByServicePackInsight\":{\"ifgh\":772641091,\"oqqtl\":1019718195,\"hzbkrkjj\":1376045590,\"vfqnvhnqoewdo\":2022925418},\"distributionBySqlVersion\":{\"tesypvidbztjh\":2090110021,\"fbov\":74741921},\"distributionBySqlEdition\":{\"bwetnjuhpsp\":1612160914},\"instanceDistributionBySizingCriterion\":{\"aupia\":1546479219,\"xnafbw\":1005928957},\"databaseDistributionBySizingCriterion\":{\"htuov\":979206753,\"onurjtumghihpv\":339434421,\"mslclblyjxlt\":1685318113,\"juscvsfx\":1682487538},\"numberOfMachines\":1616664129,\"numberOfSqlInstances\":1008970730,\"numberOfSuccessfullyDiscoveredSqlInstances\":495815281,\"numberOfSqlDatabases\":1067127377,\"numberOfFciInstances\":45764322,\"numberOfSqlAvailabilityGroups\":272878773}") + .toObject(SqlAssessmentV2SummaryProperties.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SqlAssessmentV2SummaryProperties model = new SqlAssessmentV2SummaryProperties(); + model = BinaryData.fromObject(model).toObject(SqlAssessmentV2SummaryProperties.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAvailabilityGroupDataOverviewTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAvailabilityGroupDataOverviewTests.java new file mode 100644 index 000000000000..92a206994d68 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAvailabilityGroupDataOverviewTests.java @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.SqlAvailabilityGroupDataOverview; +import org.junit.jupiter.api.Assertions; + +public final class SqlAvailabilityGroupDataOverviewTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SqlAvailabilityGroupDataOverview model = BinaryData.fromString( + "{\"availabilityGroupId\":\"ypsxjvfoim\",\"availabilityGroupName\":\"slirciz\",\"sqlAvailabilityGroupSdsArmId\":\"vydfceacvlhvygdy\",\"sqlAvailabilityGroupEntityId\":\"umrtwnawjsl\",\"sqlAvailabilityReplicaId\":\"wkojgcyztsfmzn\"}") + .toObject(SqlAvailabilityGroupDataOverview.class); + Assertions.assertEquals("ypsxjvfoim", model.availabilityGroupId()); + Assertions.assertEquals("slirciz", model.availabilityGroupName()); + Assertions.assertEquals("vydfceacvlhvygdy", model.sqlAvailabilityGroupSdsArmId()); + Assertions.assertEquals("umrtwnawjsl", model.sqlAvailabilityGroupEntityId()); + Assertions.assertEquals("wkojgcyztsfmzn", model.sqlAvailabilityReplicaId()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SqlAvailabilityGroupDataOverview model + = new SqlAvailabilityGroupDataOverview().withAvailabilityGroupId("ypsxjvfoim") + .withAvailabilityGroupName("slirciz") + .withSqlAvailabilityGroupSdsArmId("vydfceacvlhvygdy") + .withSqlAvailabilityGroupEntityId("umrtwnawjsl") + .withSqlAvailabilityReplicaId("wkojgcyztsfmzn"); + model = BinaryData.fromObject(model).toObject(SqlAvailabilityGroupDataOverview.class); + Assertions.assertEquals("ypsxjvfoim", model.availabilityGroupId()); + Assertions.assertEquals("slirciz", model.availabilityGroupName()); + Assertions.assertEquals("vydfceacvlhvygdy", model.sqlAvailabilityGroupSdsArmId()); + Assertions.assertEquals("umrtwnawjsl", model.sqlAvailabilityGroupEntityId()); + Assertions.assertEquals("wkojgcyztsfmzn", model.sqlAvailabilityReplicaId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAvailabilityReplicaSummaryTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAvailabilityReplicaSummaryTests.java new file mode 100644 index 000000000000..0a514cd02963 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlAvailabilityReplicaSummaryTests.java @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.SqlAvailabilityReplicaSummary; +import org.junit.jupiter.api.Assertions; + +public final class SqlAvailabilityReplicaSummaryTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SqlAvailabilityReplicaSummary model = BinaryData.fromString( + "{\"numberOfSynchronousReadReplicas\":1052982888,\"numberOfSynchronousNonReadReplicas\":837668712,\"numberOfAsynchronousReadReplicas\":1792442027,\"numberOfAsynchronousNonReadReplicas\":296401749,\"numberOfPrimaryReplicas\":396816762}") + .toObject(SqlAvailabilityReplicaSummary.class); + Assertions.assertEquals(1052982888, model.numberOfSynchronousReadReplicas()); + Assertions.assertEquals(837668712, model.numberOfSynchronousNonReadReplicas()); + Assertions.assertEquals(1792442027, model.numberOfAsynchronousReadReplicas()); + Assertions.assertEquals(296401749, model.numberOfAsynchronousNonReadReplicas()); + Assertions.assertEquals(396816762, model.numberOfPrimaryReplicas()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SqlAvailabilityReplicaSummary model + = new SqlAvailabilityReplicaSummary().withNumberOfSynchronousReadReplicas(1052982888) + .withNumberOfSynchronousNonReadReplicas(837668712) + .withNumberOfAsynchronousReadReplicas(1792442027) + .withNumberOfAsynchronousNonReadReplicas(296401749) + .withNumberOfPrimaryReplicas(396816762); + model = BinaryData.fromObject(model).toObject(SqlAvailabilityReplicaSummary.class); + Assertions.assertEquals(1052982888, model.numberOfSynchronousReadReplicas()); + Assertions.assertEquals(837668712, model.numberOfSynchronousNonReadReplicas()); + Assertions.assertEquals(1792442027, model.numberOfAsynchronousReadReplicas()); + Assertions.assertEquals(296401749, model.numberOfAsynchronousNonReadReplicas()); + Assertions.assertEquals(396816762, model.numberOfPrimaryReplicas()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorInnerTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorInnerTests.java new file mode 100644 index 000000000000..40e81302ac8b --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorInnerTests.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlCollectorInner; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentSpnPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBaseWithAgent; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; + +public final class SqlCollectorInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SqlCollectorInner model = BinaryData.fromString( + "{\"properties\":{\"agentProperties\":{\"id\":\"nfwmyymvqdbpb\",\"version\":\"ckdvez\",\"lastHeartbeatUtc\":\"2021-09-07T23:55:15Z\",\"spnDetails\":{\"authority\":\"bzhdd\",\"applicationId\":\"bnqfblhk\",\"audience\":\"ehpavawugiqjtiog\",\"objectId\":\"dminic\",\"tenantId\":\"eajohiyg\"}},\"discoverySiteId\":\"n\",\"createdTimestamp\":\"2021-01-10T08:24:54Z\",\"updatedTimestamp\":\"2021-06-30T15:37:59Z\",\"provisioningState\":\"Accepted\"},\"id\":\"kmktpvwxqcseh\",\"name\":\"hkhufm\",\"type\":\"qumq\"}") + .toObject(SqlCollectorInner.class); + Assertions.assertEquals(ProvisioningState.ACCEPTED, model.properties().provisioningState()); + Assertions.assertEquals("nfwmyymvqdbpb", model.properties().agentProperties().id()); + Assertions.assertEquals("ckdvez", model.properties().agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-09-07T23:55:15Z"), + model.properties().agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("bzhdd", model.properties().agentProperties().spnDetails().authority()); + Assertions.assertEquals("bnqfblhk", model.properties().agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("ehpavawugiqjtiog", model.properties().agentProperties().spnDetails().audience()); + Assertions.assertEquals("dminic", model.properties().agentProperties().spnDetails().objectId()); + Assertions.assertEquals("eajohiyg", model.properties().agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("n", model.properties().discoverySiteId()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SqlCollectorInner model = new SqlCollectorInner() + .withProperties(new CollectorPropertiesBaseWithAgent().withProvisioningState(ProvisioningState.ACCEPTED) + .withAgentProperties(new CollectorAgentPropertiesBase().withId("nfwmyymvqdbpb") + .withVersion("ckdvez") + .withLastHeartbeatUtc(OffsetDateTime.parse("2021-09-07T23:55:15Z")) + .withSpnDetails(new CollectorAgentSpnPropertiesBase().withAuthority("bzhdd") + .withApplicationId("bnqfblhk") + .withAudience("ehpavawugiqjtiog") + .withObjectId("dminic") + .withTenantId("eajohiyg"))) + .withDiscoverySiteId("n")); + model = BinaryData.fromObject(model).toObject(SqlCollectorInner.class); + Assertions.assertEquals(ProvisioningState.ACCEPTED, model.properties().provisioningState()); + Assertions.assertEquals("nfwmyymvqdbpb", model.properties().agentProperties().id()); + Assertions.assertEquals("ckdvez", model.properties().agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-09-07T23:55:15Z"), + model.properties().agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("bzhdd", model.properties().agentProperties().spnDetails().authority()); + Assertions.assertEquals("bnqfblhk", model.properties().agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("ehpavawugiqjtiog", model.properties().agentProperties().spnDetails().audience()); + Assertions.assertEquals("dminic", model.properties().agentProperties().spnDetails().objectId()); + Assertions.assertEquals("eajohiyg", model.properties().agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("n", model.properties().discoverySiteId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorListResultTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorListResultTests.java new file mode 100644 index 000000000000..876647e0bfcf --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorListResultTests.java @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.SqlCollectorInner; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentSpnPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBaseWithAgent; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import com.azure.resourcemanager.migration.assessment.models.SqlCollectorListResult; +import java.time.OffsetDateTime; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class SqlCollectorListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SqlCollectorListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"agentProperties\":{\"id\":\"zlfytoit\",\"version\":\"ygvfltgvdihoyn\",\"lastHeartbeatUtc\":\"2021-07-12T20:14:31Z\",\"spnDetails\":{\"authority\":\"twk\",\"applicationId\":\"cy\",\"audience\":\"cpcunnuzdqum\",\"objectId\":\"nod\",\"tenantId\":\"ienhqhskndnelq\"}},\"discoverySiteId\":\"adlknwfoanni\",\"createdTimestamp\":\"2021-11-08T07:08:24Z\",\"updatedTimestamp\":\"2020-12-23T05:37:02Z\",\"provisioningState\":\"Provisioning\"},\"id\":\"cnrly\",\"name\":\"nucaephblkwqpat\",\"type\":\"bqsdtcjbctvi\"},{\"properties\":{\"agentProperties\":{\"id\":\"y\",\"version\":\"uo\",\"lastHeartbeatUtc\":\"2021-06-01T02:15:38Z\",\"spnDetails\":{\"authority\":\"it\",\"applicationId\":\"hzvb\",\"audience\":\"cdb\",\"objectId\":\"fzndscxmxeatkd\",\"tenantId\":\"wnrdjyibqbnaom\"}},\"discoverySiteId\":\"rmkuh\",\"createdTimestamp\":\"2021-02-02T00:53:22Z\",\"updatedTimestamp\":\"2021-01-24T19:55:15Z\",\"provisioningState\":\"Failed\"},\"id\":\"i\",\"name\":\"cjmobcanc\",\"type\":\"exxqcwg\"},{\"properties\":{\"agentProperties\":{\"id\":\"vaknokzwjj\",\"version\":\"ltixldzyyfytpq\",\"lastHeartbeatUtc\":\"2021-04-28T14:44Z\",\"spnDetails\":{\"authority\":\"m\",\"applicationId\":\"jivyqlkjuv\",\"audience\":\"bmslzoyov\",\"objectId\":\"dbpqvybefgvm\",\"tenantId\":\"okcvtlubses\"}},\"discoverySiteId\":\"cua\",\"createdTimestamp\":\"2021-11-09T04:41:13Z\",\"updatedTimestamp\":\"2021-06-28T06:17:55Z\",\"provisioningState\":\"Succeeded\"},\"id\":\"iryky\",\"name\":\"ndzfqivjreuyk\",\"type\":\"bmnwa\"}],\"nextLink\":\"tbxoee\"}") + .toObject(SqlCollectorListResult.class); + Assertions.assertEquals(ProvisioningState.PROVISIONING, model.value().get(0).properties().provisioningState()); + Assertions.assertEquals("zlfytoit", model.value().get(0).properties().agentProperties().id()); + Assertions.assertEquals("ygvfltgvdihoyn", model.value().get(0).properties().agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-07-12T20:14:31Z"), + model.value().get(0).properties().agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("twk", model.value().get(0).properties().agentProperties().spnDetails().authority()); + Assertions.assertEquals("cy", model.value().get(0).properties().agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("cpcunnuzdqum", + model.value().get(0).properties().agentProperties().spnDetails().audience()); + Assertions.assertEquals("nod", model.value().get(0).properties().agentProperties().spnDetails().objectId()); + Assertions.assertEquals("ienhqhskndnelq", + model.value().get(0).properties().agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("adlknwfoanni", model.value().get(0).properties().discoverySiteId()); + Assertions.assertEquals("tbxoee", model.nextLink()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SqlCollectorListResult model = new SqlCollectorListResult().withValue(Arrays.asList( + new SqlCollectorInner().withProperties( + new CollectorPropertiesBaseWithAgent().withProvisioningState(ProvisioningState.PROVISIONING) + .withAgentProperties(new CollectorAgentPropertiesBase().withId("zlfytoit") + .withVersion("ygvfltgvdihoyn") + .withLastHeartbeatUtc(OffsetDateTime.parse("2021-07-12T20:14:31Z")) + .withSpnDetails(new CollectorAgentSpnPropertiesBase().withAuthority("twk") + .withApplicationId("cy") + .withAudience("cpcunnuzdqum") + .withObjectId("nod") + .withTenantId("ienhqhskndnelq"))) + .withDiscoverySiteId("adlknwfoanni")), + new SqlCollectorInner() + .withProperties(new CollectorPropertiesBaseWithAgent().withProvisioningState(ProvisioningState.FAILED) + .withAgentProperties(new CollectorAgentPropertiesBase().withId("y") + .withVersion("uo") + .withLastHeartbeatUtc(OffsetDateTime.parse("2021-06-01T02:15:38Z")) + .withSpnDetails(new CollectorAgentSpnPropertiesBase().withAuthority("it") + .withApplicationId("hzvb") + .withAudience("cdb") + .withObjectId("fzndscxmxeatkd") + .withTenantId("wnrdjyibqbnaom"))) + .withDiscoverySiteId("rmkuh")), + new SqlCollectorInner().withProperties( + new CollectorPropertiesBaseWithAgent().withProvisioningState(ProvisioningState.SUCCEEDED) + .withAgentProperties(new CollectorAgentPropertiesBase().withId("vaknokzwjj") + .withVersion("ltixldzyyfytpq") + .withLastHeartbeatUtc(OffsetDateTime.parse("2021-04-28T14:44Z")) + .withSpnDetails(new CollectorAgentSpnPropertiesBase().withAuthority("m") + .withApplicationId("jivyqlkjuv") + .withAudience("bmslzoyov") + .withObjectId("dbpqvybefgvm") + .withTenantId("okcvtlubses"))) + .withDiscoverySiteId("cua")))) + .withNextLink("tbxoee"); + model = BinaryData.fromObject(model).toObject(SqlCollectorListResult.class); + Assertions.assertEquals(ProvisioningState.PROVISIONING, model.value().get(0).properties().provisioningState()); + Assertions.assertEquals("zlfytoit", model.value().get(0).properties().agentProperties().id()); + Assertions.assertEquals("ygvfltgvdihoyn", model.value().get(0).properties().agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-07-12T20:14:31Z"), + model.value().get(0).properties().agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("twk", model.value().get(0).properties().agentProperties().spnDetails().authority()); + Assertions.assertEquals("cy", model.value().get(0).properties().agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("cpcunnuzdqum", + model.value().get(0).properties().agentProperties().spnDetails().audience()); + Assertions.assertEquals("nod", model.value().get(0).properties().agentProperties().spnDetails().objectId()); + Assertions.assertEquals("ienhqhskndnelq", + model.value().get(0).properties().agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("adlknwfoanni", model.value().get(0).properties().discoverySiteId()); + Assertions.assertEquals("tbxoee", model.nextLink()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorOperationsCreateMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorOperationsCreateMockTests.java new file mode 100644 index 000000000000..be0e486c7d40 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorOperationsCreateMockTests.java @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentSpnPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBaseWithAgent; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import com.azure.resourcemanager.migration.assessment.models.SqlCollector; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class SqlCollectorOperationsCreateMockTests { + @Test + public void testCreate() throws Exception { + String responseStr + = "{\"properties\":{\"agentProperties\":{\"id\":\"oanpohrvm\",\"version\":\"qr\",\"lastHeartbeatUtc\":\"2021-07-03T12:21:15Z\",\"spnDetails\":{\"authority\":\"vznllaslkskhjqj\",\"applicationId\":\"baihxjtgzg\",\"audience\":\"iywbqgro\",\"objectId\":\"bsfsgsae\",\"tenantId\":\"ldfmhljq\"}},\"discoverySiteId\":\"spmrjct\",\"createdTimestamp\":\"2021-11-03T18:45:02Z\",\"updatedTimestamp\":\"2021-11-06T12:27:19Z\",\"provisioningState\":\"Succeeded\"},\"id\":\"uhsx\",\"name\":\"znmgsdaluyckhefr\",\"type\":\"hs\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + SqlCollector response = manager.sqlCollectorOperations() + .define("glqjoxtdahneaoov") + .withExistingAssessmentProject("vxcgdhyhgoqgs", "yqyxyjrcbqpbis") + .withProperties(new CollectorPropertiesBaseWithAgent().withProvisioningState(ProvisioningState.UPDATING) + .withAgentProperties(new CollectorAgentPropertiesBase().withId("tivfwjlo") + .withVersion("ekfsrm") + .withLastHeartbeatUtc(OffsetDateTime.parse("2021-10-04T04:38:24Z")) + .withSpnDetails(new CollectorAgentSpnPropertiesBase().withAuthority("jvcfoczh") + .withApplicationId("ejov") + .withAudience("wxn") + .withObjectId("hhnoyrzaaoee") + .withTenantId("mjenvjeatea"))) + .withDiscoverySiteId("crxoxdj")) + .create(); + + Assertions.assertEquals(ProvisioningState.SUCCEEDED, response.properties().provisioningState()); + Assertions.assertEquals("oanpohrvm", response.properties().agentProperties().id()); + Assertions.assertEquals("qr", response.properties().agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-07-03T12:21:15Z"), + response.properties().agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("vznllaslkskhjqj", response.properties().agentProperties().spnDetails().authority()); + Assertions.assertEquals("baihxjtgzg", response.properties().agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("iywbqgro", response.properties().agentProperties().spnDetails().audience()); + Assertions.assertEquals("bsfsgsae", response.properties().agentProperties().spnDetails().objectId()); + Assertions.assertEquals("ldfmhljq", response.properties().agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("spmrjct", response.properties().discoverySiteId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorOperationsDeleteWithResponseMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorOperationsDeleteWithResponseMockTests.java new file mode 100644 index 000000000000..f51223eaefc8 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorOperationsDeleteWithResponseMockTests.java @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class SqlCollectorOperationsDeleteWithResponseMockTests { + @Test + public void testDeleteWithResponse() throws Exception { + String responseStr = "{}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + manager.sqlCollectorOperations().deleteWithResponse("ses", "fga", "qiy", com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorOperationsGetWithResponseMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorOperationsGetWithResponseMockTests.java new file mode 100644 index 000000000000..bd137b53de38 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorOperationsGetWithResponseMockTests.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import com.azure.resourcemanager.migration.assessment.models.SqlCollector; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class SqlCollectorOperationsGetWithResponseMockTests { + @Test + public void testGetWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"agentProperties\":{\"id\":\"u\",\"version\":\"vcp\",\"lastHeartbeatUtc\":\"2021-02-02T04:48:03Z\",\"spnDetails\":{\"authority\":\"uckclbtxluevsolz\",\"applicationId\":\"lfngojfsqebuuxj\",\"audience\":\"fxfjwp\",\"objectId\":\"ktpmbmxb\",\"tenantId\":\"rwgzzxl\"}},\"discoverySiteId\":\"khxsdplaumy\",\"createdTimestamp\":\"2021-05-01T04:57:26Z\",\"updatedTimestamp\":\"2021-11-22T20:04:20Z\",\"provisioningState\":\"Deleting\"},\"id\":\"yxyd\",\"name\":\"tokvqbvwglgwz\",\"type\":\"vxakglh\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + SqlCollector response = manager.sqlCollectorOperations() + .getWithResponse("squnycwztlv", "wsnmrkkyjt", "epwpwfk", com.azure.core.util.Context.NONE) + .getValue(); + + Assertions.assertEquals(ProvisioningState.DELETING, response.properties().provisioningState()); + Assertions.assertEquals("u", response.properties().agentProperties().id()); + Assertions.assertEquals("vcp", response.properties().agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-02-02T04:48:03Z"), + response.properties().agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("uckclbtxluevsolz", response.properties().agentProperties().spnDetails().authority()); + Assertions.assertEquals("lfngojfsqebuuxj", + response.properties().agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("fxfjwp", response.properties().agentProperties().spnDetails().audience()); + Assertions.assertEquals("ktpmbmxb", response.properties().agentProperties().spnDetails().objectId()); + Assertions.assertEquals("rwgzzxl", response.properties().agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("khxsdplaumy", response.properties().discoverySiteId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorOperationsListByAssessmentProjectMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorOperationsListByAssessmentProjectMockTests.java new file mode 100644 index 000000000000..5da7c680cfa5 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlCollectorOperationsListByAssessmentProjectMockTests.java @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import com.azure.resourcemanager.migration.assessment.models.SqlCollector; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class SqlCollectorOperationsListByAssessmentProjectMockTests { + @Test + public void testListByAssessmentProject() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"agentProperties\":{\"id\":\"ofgeoagf\",\"version\":\"ftnxodwxmdajwiy\",\"lastHeartbeatUtc\":\"2021-06-10T16:01:40Z\",\"spnDetails\":{\"authority\":\"vmdmzenlr\",\"applicationId\":\"gfc\",\"audience\":\"j\",\"objectId\":\"cidt\",\"tenantId\":\"amyyznmrgcdogcv\"}},\"discoverySiteId\":\"gytoxuwhtt\",\"createdTimestamp\":\"2021-04-20T14:48:23Z\",\"updatedTimestamp\":\"2021-05-03T18:57:50Z\",\"provisioningState\":\"Provisioning\"},\"id\":\"bgszplusdek\",\"name\":\"dzzmssgpgv\",\"type\":\"kyejidbdq\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response = manager.sqlCollectorOperations() + .listByAssessmentProject("zjgcfjfx", "bwjjirmuydgf", com.azure.core.util.Context.NONE); + + Assertions.assertEquals(ProvisioningState.PROVISIONING, + response.iterator().next().properties().provisioningState()); + Assertions.assertEquals("ofgeoagf", response.iterator().next().properties().agentProperties().id()); + Assertions.assertEquals("ftnxodwxmdajwiy", response.iterator().next().properties().agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-06-10T16:01:40Z"), + response.iterator().next().properties().agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("vmdmzenlr", + response.iterator().next().properties().agentProperties().spnDetails().authority()); + Assertions.assertEquals("gfc", + response.iterator().next().properties().agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("j", response.iterator().next().properties().agentProperties().spnDetails().audience()); + Assertions.assertEquals("cidt", + response.iterator().next().properties().agentProperties().spnDetails().objectId()); + Assertions.assertEquals("amyyznmrgcdogcv", + response.iterator().next().properties().agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("gytoxuwhtt", response.iterator().next().properties().discoverySiteId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlDbSettingsTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlDbSettingsTests.java new file mode 100644 index 000000000000..caeb67b7f0c1 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlDbSettingsTests.java @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.AzureSqlDataBaseType; +import com.azure.resourcemanager.migration.assessment.models.AzureSqlPurchaseModel; +import com.azure.resourcemanager.migration.assessment.models.AzureSqlServiceTier; +import com.azure.resourcemanager.migration.assessment.models.ComputeTier; +import com.azure.resourcemanager.migration.assessment.models.SqlDbSettings; +import org.junit.jupiter.api.Assertions; + +public final class SqlDbSettingsTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SqlDbSettings model = BinaryData.fromString( + "{\"azureSqlServiceTier\":\"Unknown\",\"azureSqlDataBaseType\":\"ElasticPool\",\"azureSqlComputeTier\":\"Provisioned\",\"azureSqlPurchaseModel\":\"Unknown\"}") + .toObject(SqlDbSettings.class); + Assertions.assertEquals(AzureSqlServiceTier.UNKNOWN, model.azureSqlServiceTier()); + Assertions.assertEquals(AzureSqlDataBaseType.ELASTIC_POOL, model.azureSqlDataBaseType()); + Assertions.assertEquals(ComputeTier.PROVISIONED, model.azureSqlComputeTier()); + Assertions.assertEquals(AzureSqlPurchaseModel.UNKNOWN, model.azureSqlPurchaseModel()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SqlDbSettings model = new SqlDbSettings().withAzureSqlServiceTier(AzureSqlServiceTier.UNKNOWN) + .withAzureSqlDataBaseType(AzureSqlDataBaseType.ELASTIC_POOL) + .withAzureSqlComputeTier(ComputeTier.PROVISIONED) + .withAzureSqlPurchaseModel(AzureSqlPurchaseModel.UNKNOWN); + model = BinaryData.fromObject(model).toObject(SqlDbSettings.class); + Assertions.assertEquals(AzureSqlServiceTier.UNKNOWN, model.azureSqlServiceTier()); + Assertions.assertEquals(AzureSqlDataBaseType.ELASTIC_POOL, model.azureSqlDataBaseType()); + Assertions.assertEquals(ComputeTier.PROVISIONED, model.azureSqlComputeTier()); + Assertions.assertEquals(AzureSqlPurchaseModel.UNKNOWN, model.azureSqlPurchaseModel()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlFciMetadataTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlFciMetadataTests.java new file mode 100644 index 000000000000..0b68c47753a5 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlFciMetadataTests.java @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.SqlFciMetadata; +import com.azure.resourcemanager.migration.assessment.models.SqlFciMetadataState; +import org.junit.jupiter.api.Assertions; + +public final class SqlFciMetadataTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SqlFciMetadata model = BinaryData + .fromString("{\"state\":\"OnlinePending\",\"isMultiSubnet\":true,\"fciSharedDiskCount\":763875657}") + .toObject(SqlFciMetadata.class); + Assertions.assertEquals(SqlFciMetadataState.ONLINE_PENDING, model.state()); + Assertions.assertEquals(true, model.isMultiSubnet()); + Assertions.assertEquals(763875657, model.fciSharedDiskCount()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SqlFciMetadata model = new SqlFciMetadata().withState(SqlFciMetadataState.ONLINE_PENDING) + .withIsMultiSubnet(true) + .withFciSharedDiskCount(763875657); + model = BinaryData.fromObject(model).toObject(SqlFciMetadata.class); + Assertions.assertEquals(SqlFciMetadataState.ONLINE_PENDING, model.state()); + Assertions.assertEquals(true, model.isMultiSubnet()); + Assertions.assertEquals(763875657, model.fciSharedDiskCount()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlMiSettingsTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlMiSettingsTests.java new file mode 100644 index 000000000000..122cae18f3b3 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlMiSettingsTests.java @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.AzureSqlInstanceType; +import com.azure.resourcemanager.migration.assessment.models.AzureSqlServiceTier; +import com.azure.resourcemanager.migration.assessment.models.SqlMiSettings; +import org.junit.jupiter.api.Assertions; + +public final class SqlMiSettingsTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SqlMiSettings model + = BinaryData.fromString("{\"azureSqlServiceTier\":\"Automatic\",\"azureSqlInstanceType\":\"Automatic\"}") + .toObject(SqlMiSettings.class); + Assertions.assertEquals(AzureSqlServiceTier.AUTOMATIC, model.azureSqlServiceTier()); + Assertions.assertEquals(AzureSqlInstanceType.AUTOMATIC, model.azureSqlInstanceType()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SqlMiSettings model = new SqlMiSettings().withAzureSqlServiceTier(AzureSqlServiceTier.AUTOMATIC) + .withAzureSqlInstanceType(AzureSqlInstanceType.AUTOMATIC); + model = BinaryData.fromObject(model).toObject(SqlMiSettings.class); + Assertions.assertEquals(AzureSqlServiceTier.AUTOMATIC, model.azureSqlServiceTier()); + Assertions.assertEquals(AzureSqlInstanceType.AUTOMATIC, model.azureSqlInstanceType()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlPaaSTargetOptionsTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlPaaSTargetOptionsTests.java new file mode 100644 index 000000000000..57ac208eb89d --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlPaaSTargetOptionsTests.java @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.AzureLocation; +import com.azure.resourcemanager.migration.assessment.models.AzureSqlServiceTier; +import com.azure.resourcemanager.migration.assessment.models.ComputeTier; +import com.azure.resourcemanager.migration.assessment.models.HardwareGeneration; +import com.azure.resourcemanager.migration.assessment.models.SqlPaaSTargetOptions; +import com.azure.resourcemanager.migration.assessment.models.TargetType; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class SqlPaaSTargetOptionsTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SqlPaaSTargetOptions model = BinaryData.fromString( + "{\"computeTier\":\"Unknown\",\"hardwareGeneration\":\"Automatic\",\"targetType\":\"AzureVirtualMachine\",\"serviceTier\":\"HyperScale\",\"targetLocations\":[\"USDoDEast\",\"SouthCentralUs\"]}") + .toObject(SqlPaaSTargetOptions.class); + Assertions.assertEquals(ComputeTier.UNKNOWN, model.computeTier()); + Assertions.assertEquals(HardwareGeneration.AUTOMATIC, model.hardwareGeneration()); + Assertions.assertEquals(TargetType.AZURE_VIRTUAL_MACHINE, model.targetType()); + Assertions.assertEquals(AzureSqlServiceTier.HYPER_SCALE, model.serviceTier()); + Assertions.assertEquals(AzureLocation.USDO_DEAST, model.targetLocations().get(0)); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SqlPaaSTargetOptions model = new SqlPaaSTargetOptions().withComputeTier(ComputeTier.UNKNOWN) + .withHardwareGeneration(HardwareGeneration.AUTOMATIC) + .withTargetType(TargetType.AZURE_VIRTUAL_MACHINE) + .withServiceTier(AzureSqlServiceTier.HYPER_SCALE) + .withTargetLocations(Arrays.asList(AzureLocation.USDO_DEAST, AzureLocation.SOUTH_CENTRAL_US)); + model = BinaryData.fromObject(model).toObject(SqlPaaSTargetOptions.class); + Assertions.assertEquals(ComputeTier.UNKNOWN, model.computeTier()); + Assertions.assertEquals(HardwareGeneration.AUTOMATIC, model.hardwareGeneration()); + Assertions.assertEquals(TargetType.AZURE_VIRTUAL_MACHINE, model.targetType()); + Assertions.assertEquals(AzureSqlServiceTier.HYPER_SCALE, model.serviceTier()); + Assertions.assertEquals(AzureLocation.USDO_DEAST, model.targetLocations().get(0)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlVmSettingsTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlVmSettingsTests.java new file mode 100644 index 000000000000..97c6d5b6c0da --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/SqlVmSettingsTests.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.AzureVmFamily; +import com.azure.resourcemanager.migration.assessment.models.SqlVmSettings; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class SqlVmSettingsTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SqlVmSettings model + = BinaryData.fromString("{\"instanceSeries\":[\"Dsv4_series\"]}").toObject(SqlVmSettings.class); + Assertions.assertEquals(AzureVmFamily.DSV4_SERIES, model.instanceSeries().get(0)); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SqlVmSettings model = new SqlVmSettings().withInstanceSeries(Arrays.asList(AzureVmFamily.DSV4_SERIES)); + model = BinaryData.fromObject(model).toObject(SqlVmSettings.class); + Assertions.assertEquals(AzureVmFamily.DSV4_SERIES, model.instanceSeries().get(0)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/UltraDiskAssessmentOptionsTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/UltraDiskAssessmentOptionsTests.java new file mode 100644 index 000000000000..17275d48942a --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/UltraDiskAssessmentOptionsTests.java @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.UltraDiskAssessmentOptions; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class UltraDiskAssessmentOptionsTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + UltraDiskAssessmentOptions model = BinaryData + .fromString("{\"familyName\":\"knftguvriuh\",\"targetLocations\":[\"mdyvxqtayriw\",\"ro\",\"qbex\"]}") + .toObject(UltraDiskAssessmentOptions.class); + Assertions.assertEquals("knftguvriuh", model.familyName()); + Assertions.assertEquals("mdyvxqtayriw", model.targetLocations().get(0)); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + UltraDiskAssessmentOptions model = new UltraDiskAssessmentOptions().withFamilyName("knftguvriuh") + .withTargetLocations(Arrays.asList("mdyvxqtayriw", "ro", "qbex")); + model = BinaryData.fromObject(model).toObject(UltraDiskAssessmentOptions.class); + Assertions.assertEquals("knftguvriuh", model.familyName()); + Assertions.assertEquals("mdyvxqtayriw", model.targetLocations().get(0)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/UpdateGroupBodyTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/UpdateGroupBodyTests.java new file mode 100644 index 000000000000..e2ede4b2efa9 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/UpdateGroupBodyTests.java @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.GroupBodyProperties; +import com.azure.resourcemanager.migration.assessment.models.GroupUpdateOperation; +import com.azure.resourcemanager.migration.assessment.models.UpdateGroupBody; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class UpdateGroupBodyTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + UpdateGroupBody model = BinaryData.fromString( + "{\"eTag\":\"geqmgqzgwldoych\",\"properties\":{\"operationType\":\"Remove\",\"machines\":[\"fehuwaoaguhi\",\"qllizstac\",\"jvhrweft\"]}}") + .toObject(UpdateGroupBody.class); + Assertions.assertEquals("geqmgqzgwldoych", model.etag()); + Assertions.assertEquals(GroupUpdateOperation.REMOVE, model.properties().operationType()); + Assertions.assertEquals("fehuwaoaguhi", model.properties().machines().get(0)); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + UpdateGroupBody model = new UpdateGroupBody().withEtag("geqmgqzgwldoych") + .withProperties(new GroupBodyProperties().withOperationType(GroupUpdateOperation.REMOVE) + .withMachines(Arrays.asList("fehuwaoaguhi", "qllizstac", "jvhrweft"))); + model = BinaryData.fromObject(model).toObject(UpdateGroupBody.class); + Assertions.assertEquals("geqmgqzgwldoych", model.etag()); + Assertions.assertEquals(GroupUpdateOperation.REMOVE, model.properties().operationType()); + Assertions.assertEquals("fehuwaoaguhi", model.properties().machines().get(0)); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/VmFamilyOptionsTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/VmFamilyOptionsTests.java new file mode 100644 index 000000000000..73825396cfb3 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/VmFamilyOptionsTests.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.VmFamilyOptions; + +public final class VmFamilyOptionsTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + VmFamilyOptions model = BinaryData.fromString( + "{\"familyName\":\"rbpbewtghfgblcg\",\"targetLocations\":[\"vlvqhjkbegi\",\"t\",\"mxiebw\",\"aloayqcgwrtzju\"],\"category\":[\"yzm\",\"txon\",\"mtsavjcbpwxqp\"]}") + .toObject(VmFamilyOptions.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + VmFamilyOptions model = new VmFamilyOptions(); + model = BinaryData.fromObject(model).toObject(VmFamilyOptions.class); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/VmUptimeTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/VmUptimeTests.java new file mode 100644 index 000000000000..e2015cd210cd --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/VmUptimeTests.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.VmUptime; +import org.junit.jupiter.api.Assertions; + +public final class VmUptimeTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + VmUptime model + = BinaryData.fromString("{\"daysPerMonth\":171305753,\"hoursPerDay\":1847154217}").toObject(VmUptime.class); + Assertions.assertEquals(171305753, model.daysPerMonth()); + Assertions.assertEquals(1847154217, model.hoursPerDay()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + VmUptime model = new VmUptime().withDaysPerMonth(171305753).withHoursPerDay(1847154217); + model = BinaryData.fromObject(model).toObject(VmUptime.class); + Assertions.assertEquals(171305753, model.daysPerMonth()); + Assertions.assertEquals(1847154217, model.hoursPerDay()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorInnerTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorInnerTests.java new file mode 100644 index 000000000000..0466e4edd191 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorInnerTests.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.VmwareCollectorInner; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentSpnPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBaseWithAgent; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; + +public final class VmwareCollectorInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + VmwareCollectorInner model = BinaryData.fromString( + "{\"properties\":{\"agentProperties\":{\"id\":\"yd\",\"version\":\"uvvadswzsnu\",\"lastHeartbeatUtc\":\"2021-08-23T01:32:44Z\",\"spnDetails\":{\"authority\":\"wuowhlxlnwy\",\"applicationId\":\"ouvblgmo\",\"audience\":\"kltrfow\",\"objectId\":\"vrfmvlihcvjd\",\"tenantId\":\"crjidhftukv\"}},\"discoverySiteId\":\"xlwyoj\",\"createdTimestamp\":\"2021-02-13T08:09:39Z\",\"updatedTimestamp\":\"2021-03-15T14:07:07Z\",\"provisioningState\":\"Succeeded\"},\"id\":\"jyixhaf\",\"name\":\"atqxmbjroumzzn\",\"type\":\"al\"}") + .toObject(VmwareCollectorInner.class); + Assertions.assertEquals(ProvisioningState.SUCCEEDED, model.properties().provisioningState()); + Assertions.assertEquals("yd", model.properties().agentProperties().id()); + Assertions.assertEquals("uvvadswzsnu", model.properties().agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-08-23T01:32:44Z"), + model.properties().agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("wuowhlxlnwy", model.properties().agentProperties().spnDetails().authority()); + Assertions.assertEquals("ouvblgmo", model.properties().agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("kltrfow", model.properties().agentProperties().spnDetails().audience()); + Assertions.assertEquals("vrfmvlihcvjd", model.properties().agentProperties().spnDetails().objectId()); + Assertions.assertEquals("crjidhftukv", model.properties().agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("xlwyoj", model.properties().discoverySiteId()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + VmwareCollectorInner model = new VmwareCollectorInner() + .withProperties(new CollectorPropertiesBaseWithAgent().withProvisioningState(ProvisioningState.SUCCEEDED) + .withAgentProperties(new CollectorAgentPropertiesBase().withId("yd") + .withVersion("uvvadswzsnu") + .withLastHeartbeatUtc(OffsetDateTime.parse("2021-08-23T01:32:44Z")) + .withSpnDetails(new CollectorAgentSpnPropertiesBase().withAuthority("wuowhlxlnwy") + .withApplicationId("ouvblgmo") + .withAudience("kltrfow") + .withObjectId("vrfmvlihcvjd") + .withTenantId("crjidhftukv"))) + .withDiscoverySiteId("xlwyoj")); + model = BinaryData.fromObject(model).toObject(VmwareCollectorInner.class); + Assertions.assertEquals(ProvisioningState.SUCCEEDED, model.properties().provisioningState()); + Assertions.assertEquals("yd", model.properties().agentProperties().id()); + Assertions.assertEquals("uvvadswzsnu", model.properties().agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-08-23T01:32:44Z"), + model.properties().agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("wuowhlxlnwy", model.properties().agentProperties().spnDetails().authority()); + Assertions.assertEquals("ouvblgmo", model.properties().agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("kltrfow", model.properties().agentProperties().spnDetails().audience()); + Assertions.assertEquals("vrfmvlihcvjd", model.properties().agentProperties().spnDetails().objectId()); + Assertions.assertEquals("crjidhftukv", model.properties().agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("xlwyoj", model.properties().discoverySiteId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorListResultTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorListResultTests.java new file mode 100644 index 000000000000..e18177e018e7 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorListResultTests.java @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.fluent.models.VmwareCollectorInner; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentSpnPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBaseWithAgent; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import com.azure.resourcemanager.migration.assessment.models.VmwareCollectorListResult; +import java.time.OffsetDateTime; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class VmwareCollectorListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + VmwareCollectorListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"agentProperties\":{\"id\":\"zulo\",\"version\":\"aeuzanh\",\"lastHeartbeatUtc\":\"2021-11-19T22:08:29Z\",\"spnDetails\":{\"authority\":\"enwphpzfngq\",\"applicationId\":\"lidftujwjj\",\"audience\":\"wbeqrkuor\",\"objectId\":\"ssruqnmdvhazcvj\",\"tenantId\":\"iqswbqer\"}},\"discoverySiteId\":\"xiytxtdgukvl\",\"createdTimestamp\":\"2021-11-18T11:20:29Z\",\"updatedTimestamp\":\"2021-02-21T00:04:27Z\",\"provisioningState\":\"Deleting\"},\"id\":\"youambewr\",\"name\":\"swmowegmmuteyxe\",\"type\":\"guqigijiitns\"},{\"properties\":{\"agentProperties\":{\"id\":\"desygrijwa\",\"version\":\"fanraybfu\",\"lastHeartbeatUtc\":\"2021-02-09T08:33:36Z\",\"spnDetails\":{\"authority\":\"jsydgrhydkygywez\",\"applicationId\":\"iecafygzmxi\",\"audience\":\"vdsmaklixq\",\"objectId\":\"hyhxa\",\"tenantId\":\"bx\"}},\"discoverySiteId\":\"oij\",\"createdTimestamp\":\"2021-04-20T04:08:14Z\",\"updatedTimestamp\":\"2021-07-15T09:06:11Z\",\"provisioningState\":\"Updating\"},\"id\":\"kkwjdjodq\",\"name\":\"ykincnremehl\",\"type\":\"izhceumoqodkadp\"}],\"nextLink\":\"ibngqladyw\"}") + .toObject(VmwareCollectorListResult.class); + Assertions.assertEquals(ProvisioningState.DELETING, model.value().get(0).properties().provisioningState()); + Assertions.assertEquals("zulo", model.value().get(0).properties().agentProperties().id()); + Assertions.assertEquals("aeuzanh", model.value().get(0).properties().agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-11-19T22:08:29Z"), + model.value().get(0).properties().agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("enwphpzfngq", + model.value().get(0).properties().agentProperties().spnDetails().authority()); + Assertions.assertEquals("lidftujwjj", + model.value().get(0).properties().agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("wbeqrkuor", + model.value().get(0).properties().agentProperties().spnDetails().audience()); + Assertions.assertEquals("ssruqnmdvhazcvj", + model.value().get(0).properties().agentProperties().spnDetails().objectId()); + Assertions.assertEquals("iqswbqer", + model.value().get(0).properties().agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("xiytxtdgukvl", model.value().get(0).properties().discoverySiteId()); + Assertions.assertEquals("ibngqladyw", model.nextLink()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + VmwareCollectorListResult model = new VmwareCollectorListResult().withValue(Arrays.asList( + new VmwareCollectorInner() + .withProperties(new CollectorPropertiesBaseWithAgent().withProvisioningState(ProvisioningState.DELETING) + .withAgentProperties(new CollectorAgentPropertiesBase().withId("zulo") + .withVersion("aeuzanh") + .withLastHeartbeatUtc(OffsetDateTime.parse("2021-11-19T22:08:29Z")) + .withSpnDetails(new CollectorAgentSpnPropertiesBase().withAuthority("enwphpzfngq") + .withApplicationId("lidftujwjj") + .withAudience("wbeqrkuor") + .withObjectId("ssruqnmdvhazcvj") + .withTenantId("iqswbqer"))) + .withDiscoverySiteId("xiytxtdgukvl")), + new VmwareCollectorInner() + .withProperties(new CollectorPropertiesBaseWithAgent().withProvisioningState(ProvisioningState.UPDATING) + .withAgentProperties(new CollectorAgentPropertiesBase().withId("desygrijwa") + .withVersion("fanraybfu") + .withLastHeartbeatUtc(OffsetDateTime.parse("2021-02-09T08:33:36Z")) + .withSpnDetails(new CollectorAgentSpnPropertiesBase().withAuthority("jsydgrhydkygywez") + .withApplicationId("iecafygzmxi") + .withAudience("vdsmaklixq") + .withObjectId("hyhxa") + .withTenantId("bx"))) + .withDiscoverySiteId("oij")))) + .withNextLink("ibngqladyw"); + model = BinaryData.fromObject(model).toObject(VmwareCollectorListResult.class); + Assertions.assertEquals(ProvisioningState.DELETING, model.value().get(0).properties().provisioningState()); + Assertions.assertEquals("zulo", model.value().get(0).properties().agentProperties().id()); + Assertions.assertEquals("aeuzanh", model.value().get(0).properties().agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-11-19T22:08:29Z"), + model.value().get(0).properties().agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("enwphpzfngq", + model.value().get(0).properties().agentProperties().spnDetails().authority()); + Assertions.assertEquals("lidftujwjj", + model.value().get(0).properties().agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("wbeqrkuor", + model.value().get(0).properties().agentProperties().spnDetails().audience()); + Assertions.assertEquals("ssruqnmdvhazcvj", + model.value().get(0).properties().agentProperties().spnDetails().objectId()); + Assertions.assertEquals("iqswbqer", + model.value().get(0).properties().agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("xiytxtdgukvl", model.value().get(0).properties().discoverySiteId()); + Assertions.assertEquals("ibngqladyw", model.nextLink()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorsOperationsCreateMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorsOperationsCreateMockTests.java new file mode 100644 index 000000000000..2b36babced50 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorsOperationsCreateMockTests.java @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorAgentSpnPropertiesBase; +import com.azure.resourcemanager.migration.assessment.models.CollectorPropertiesBaseWithAgent; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import com.azure.resourcemanager.migration.assessment.models.VmwareCollector; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class VmwareCollectorsOperationsCreateMockTests { + @Test + public void testCreate() throws Exception { + String responseStr + = "{\"properties\":{\"agentProperties\":{\"id\":\"mcofn\",\"version\":\"lbsnosnqliw\",\"lastHeartbeatUtc\":\"2020-12-31T14:56:04Z\",\"spnDetails\":{\"authority\":\"fetya\",\"applicationId\":\"tg\",\"audience\":\"nazgbjbhrpgiq\",\"objectId\":\"tcucrcmmai\",\"tenantId\":\"qjiwifhbksldttoh\"}},\"discoverySiteId\":\"lna\",\"createdTimestamp\":\"2021-01-30T09:04:29Z\",\"updatedTimestamp\":\"2021-10-03T11:41:04Z\",\"provisioningState\":\"Succeeded\"},\"id\":\"kvllrhtpmglxkoi\",\"name\":\"mtrawrqkza\",\"type\":\"bun\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + VmwareCollector response = manager.vmwareCollectorsOperations() + .define("ekwuyckyvn") + .withExistingAssessmentProject("z", "canzb") + .withProperties(new CollectorPropertiesBaseWithAgent().withProvisioningState(ProvisioningState.UPDATING) + .withAgentProperties(new CollectorAgentPropertiesBase().withId("uffiwjbctvbpzu") + .withVersion("jtotdxposcs") + .withLastHeartbeatUtc(OffsetDateTime.parse("2021-06-08T17:25:47Z")) + .withSpnDetails(new CollectorAgentSpnPropertiesBase().withAuthority("siecktybhj") + .withApplicationId("idhhxomild") + .withAudience("jxdugxwj") + .withObjectId("l") + .withTenantId("rslaatep"))) + .withDiscoverySiteId("ujjzgxq")) + .create(); + + Assertions.assertEquals(ProvisioningState.SUCCEEDED, response.properties().provisioningState()); + Assertions.assertEquals("mcofn", response.properties().agentProperties().id()); + Assertions.assertEquals("lbsnosnqliw", response.properties().agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2020-12-31T14:56:04Z"), + response.properties().agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("fetya", response.properties().agentProperties().spnDetails().authority()); + Assertions.assertEquals("tg", response.properties().agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("nazgbjbhrpgiq", response.properties().agentProperties().spnDetails().audience()); + Assertions.assertEquals("tcucrcmmai", response.properties().agentProperties().spnDetails().objectId()); + Assertions.assertEquals("qjiwifhbksldttoh", response.properties().agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("lna", response.properties().discoverySiteId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorsOperationsDeleteWithResponseMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorsOperationsDeleteWithResponseMockTests.java new file mode 100644 index 000000000000..42e309a02c73 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorsOperationsDeleteWithResponseMockTests.java @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class VmwareCollectorsOperationsDeleteWithResponseMockTests { + @Test + public void testDeleteWithResponse() throws Exception { + String responseStr = "{}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + manager.vmwareCollectorsOperations() + .deleteWithResponse("hjmbji", "egmxdbsohc", "hpyvdkgdet", com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorsOperationsGetWithResponseMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorsOperationsGetWithResponseMockTests.java new file mode 100644 index 000000000000..409baa8cd0e8 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorsOperationsGetWithResponseMockTests.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import com.azure.resourcemanager.migration.assessment.models.VmwareCollector; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class VmwareCollectorsOperationsGetWithResponseMockTests { + @Test + public void testGetWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"agentProperties\":{\"id\":\"gsoriobij\",\"version\":\"ydyeuy\",\"lastHeartbeatUtc\":\"2021-08-02T19:21:07Z\",\"spnDetails\":{\"authority\":\"ayrgwy\",\"applicationId\":\"io\",\"audience\":\"weoftnorw\",\"objectId\":\"gsioc\",\"tenantId\":\"kmv\"}},\"discoverySiteId\":\"nx\",\"createdTimestamp\":\"2021-04-14T08:01:15Z\",\"updatedTimestamp\":\"2021-05-30T09:27:09Z\",\"provisioningState\":\"Failed\"},\"id\":\"nwosstfj\",\"name\":\"tvlxxzqfcwr\",\"type\":\"iomxeezw\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + VmwareCollector response = manager.vmwareCollectorsOperations() + .getWithResponse("sqywjopacky", "ydv", "kmfngpmillxgjs", com.azure.core.util.Context.NONE) + .getValue(); + + Assertions.assertEquals(ProvisioningState.FAILED, response.properties().provisioningState()); + Assertions.assertEquals("gsoriobij", response.properties().agentProperties().id()); + Assertions.assertEquals("ydyeuy", response.properties().agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-08-02T19:21:07Z"), + response.properties().agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("ayrgwy", response.properties().agentProperties().spnDetails().authority()); + Assertions.assertEquals("io", response.properties().agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("weoftnorw", response.properties().agentProperties().spnDetails().audience()); + Assertions.assertEquals("gsioc", response.properties().agentProperties().spnDetails().objectId()); + Assertions.assertEquals("kmv", response.properties().agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("nx", response.properties().discoverySiteId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorsOperationsListByAssessmentProjectMockTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorsOperationsListByAssessmentProjectMockTests.java new file mode 100644 index 000000000000..1fbf30eb268a --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/VmwareCollectorsOperationsListByAssessmentProjectMockTests.java @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.migration.assessment.MigrationAssessmentManager; +import com.azure.resourcemanager.migration.assessment.models.ProvisioningState; +import com.azure.resourcemanager.migration.assessment.models.VmwareCollector; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class VmwareCollectorsOperationsListByAssessmentProjectMockTests { + @Test + public void testListByAssessmentProject() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"agentProperties\":{\"id\":\"jmgtnsew\",\"version\":\"x\",\"lastHeartbeatUtc\":\"2021-06-07T17:36:48Z\",\"spnDetails\":{\"authority\":\"vyljurkeposehqq\",\"applicationId\":\"mpctwjwdsdlzmk\",\"audience\":\"rxxxoteehkhowgom\",\"objectId\":\"hxow\",\"tenantId\":\"bap\"}},\"discoverySiteId\":\"x\",\"createdTimestamp\":\"2021-10-05T11:42:42Z\",\"updatedTimestamp\":\"2021-06-23T08:30:24Z\",\"provisioningState\":\"Failed\"},\"id\":\"spfeylqlocvvuje\",\"name\":\"ayglxrkgjnmzpasl\",\"type\":\"vxjfiuofpieidzlv\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + MigrationAssessmentManager manager = MigrationAssessmentManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response = manager.vmwareCollectorsOperations() + .listByAssessmentProject("uerbgpxebjl", "dcaytujraxd", com.azure.core.util.Context.NONE); + + Assertions.assertEquals(ProvisioningState.FAILED, response.iterator().next().properties().provisioningState()); + Assertions.assertEquals("jmgtnsew", response.iterator().next().properties().agentProperties().id()); + Assertions.assertEquals("x", response.iterator().next().properties().agentProperties().version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-06-07T17:36:48Z"), + response.iterator().next().properties().agentProperties().lastHeartbeatUtc()); + Assertions.assertEquals("vyljurkeposehqq", + response.iterator().next().properties().agentProperties().spnDetails().authority()); + Assertions.assertEquals("mpctwjwdsdlzmk", + response.iterator().next().properties().agentProperties().spnDetails().applicationId()); + Assertions.assertEquals("rxxxoteehkhowgom", + response.iterator().next().properties().agentProperties().spnDetails().audience()); + Assertions.assertEquals("hxow", + response.iterator().next().properties().agentProperties().spnDetails().objectId()); + Assertions.assertEquals("bap", + response.iterator().next().properties().agentProperties().spnDetails().tenantId()); + Assertions.assertEquals("x", response.iterator().next().properties().discoverySiteId()); + } +} diff --git a/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/WorkloadSummaryTests.java b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/WorkloadSummaryTests.java new file mode 100644 index 000000000000..c77df94108f6 --- /dev/null +++ b/sdk/migration/azure-resourcemanager-migration-assessment/src/test/java/com/azure/resourcemanager/migration/assessment/generated/WorkloadSummaryTests.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.migration.assessment.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.migration.assessment.models.WorkloadSummary; +import org.junit.jupiter.api.Assertions; + +public final class WorkloadSummaryTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + WorkloadSummary model = BinaryData.fromString("{\"oracleInstances\":1849562249,\"springApps\":364097944}") + .toObject(WorkloadSummary.class); + Assertions.assertEquals(1849562249, model.oracleInstances()); + Assertions.assertEquals(364097944, model.springApps()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + WorkloadSummary model = new WorkloadSummary().withOracleInstances(1849562249).withSpringApps(364097944); + model = BinaryData.fromObject(model).toObject(WorkloadSummary.class); + Assertions.assertEquals(1849562249, model.oracleInstances()); + Assertions.assertEquals(364097944, model.springApps()); + } +} diff --git a/sdk/migration/ci.yml b/sdk/migration/ci.yml new file mode 100644 index 000000000000..a96ec0f3b96e --- /dev/null +++ b/sdk/migration/ci.yml @@ -0,0 +1,46 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. + +trigger: + branches: + include: + - main + - hotfix/* + - release/* + paths: + include: + - sdk/migration/ci.yml + - sdk/migration/azure-resourcemanager-migration-assessment/ + exclude: + - sdk/migration/pom.xml + - sdk/migration/azure-resourcemanager-migration-assessment/pom.xml + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/migration/ci.yml + - sdk/migration/azure-resourcemanager-migration-assessment/ + exclude: + - sdk/migration/pom.xml + - sdk/migration/azure-resourcemanager-migration-assessment/pom.xml + +parameters: + - name: release_azureresourcemanagermigrationassessment + displayName: azure-resourcemanager-migration-assessment + type: boolean + default: false + +extends: + template: ../../eng/pipelines/templates/stages/archetype-sdk-client.yml + parameters: + ServiceDirectory: migration + Artifacts: + - name: azure-resourcemanager-migration-assessment + groupId: com.azure.resourcemanager + safeName: azureresourcemanagermigrationassessment + releaseInBatch: ${{ parameters.release_azureresourcemanagermigrationassessment }} diff --git a/sdk/migration/pom.xml b/sdk/migration/pom.xml new file mode 100644 index 000000000000..f4a057f4a539 --- /dev/null +++ b/sdk/migration/pom.xml @@ -0,0 +1,15 @@ + + + 4.0.0 + com.azure + azure-migration-service + pom + 1.0.0 + + + azure-resourcemanager-migration-assessment + + diff --git a/sdk/migrationdiscoverysap/azure-resourcemanager-migrationdiscoverysap/README.md b/sdk/migrationdiscoverysap/azure-resourcemanager-migrationdiscoverysap/README.md index f60ab66a1d93..dff2670f8c99 100644 --- a/sdk/migrationdiscoverysap/azure-resourcemanager-migrationdiscoverysap/README.md +++ b/sdk/migrationdiscoverysap/azure-resourcemanager-migrationdiscoverysap/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-migrationdiscoverysap - 1.0.0-beta.2 + 1.0.0-beta.3 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fmigrationdiscoverysap%2Fazure-resourcemanager-migrationdiscoverysap%2FREADME.png) + diff --git a/sdk/migrationdiscoverysap/azure-resourcemanager-migrationdiscoverysap/pom.xml b/sdk/migrationdiscoverysap/azure-resourcemanager-migrationdiscoverysap/pom.xml index 1b52feb3a877..5b3aa3e1fd9d 100644 --- a/sdk/migrationdiscoverysap/azure-resourcemanager-migrationdiscoverysap/pom.xml +++ b/sdk/migrationdiscoverysap/azure-resourcemanager-migrationdiscoverysap/pom.xml @@ -52,23 +52,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/mixedreality/azure-mixedreality-authentication/CHANGELOG.md b/sdk/mixedreality/azure-mixedreality-authentication/CHANGELOG.md index ff33c38b90a6..102e5b044b9e 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/CHANGELOG.md +++ b/sdk/mixedreality/azure-mixedreality-authentication/CHANGELOG.md @@ -10,6 +10,16 @@ ### Other Changes +## 1.2.31 (2025-02-25) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`. +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. + + ## 1.2.30 (2024-12-04) ### Other Changes @@ -19,6 +29,7 @@ - Upgraded `azure-core` from `1.53.0` to version `1.54.1`. - Upgraded `azure-core-http-netty` from `1.15.5` to version `1.15.7`. + ## 1.2.29 (2024-10-27) ### Other Changes diff --git a/sdk/mixedreality/azure-mixedreality-authentication/README.md b/sdk/mixedreality/azure-mixedreality-authentication/README.md index c9d1701f3bf3..d6e2af579efe 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/README.md +++ b/sdk/mixedreality/azure-mixedreality-authentication/README.md @@ -61,7 +61,7 @@ add the direct dependency to your project as follows. com.azure azure-mixedreality-authentication - 1.2.15 + 1.3.0-beta.1 ``` @@ -187,4 +187,4 @@ For more information see the [Code of Conduct FAQ](https://opensource.microsoft. [api_documentation]: https://aka.ms/java-docs [source]: https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/mixedreality/azure-mixedreality-authentication -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fmixedreality%2Fazure-mixedreality-authentication%2FREADME.png) + diff --git a/sdk/mixedreality/azure-mixedreality-authentication/pom.xml b/sdk/mixedreality/azure-mixedreality-authentication/pom.xml index 88837d2e4e1b..327e2f405cc2 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/pom.xml +++ b/sdk/mixedreality/azure-mixedreality-authentication/pom.xml @@ -40,25 +40,25 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/mixedreality/azure-resourcemanager-mixedreality/README.md b/sdk/mixedreality/azure-resourcemanager-mixedreality/README.md index ba90d4ac6e2d..8d00a8ae23bb 100644 --- a/sdk/mixedreality/azure-resourcemanager-mixedreality/README.md +++ b/sdk/mixedreality/azure-resourcemanager-mixedreality/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-mixedreality - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fmixedreality%2Fazure-resourcemanager-mixedreality%2FREADME.png) + diff --git a/sdk/mixedreality/azure-resourcemanager-mixedreality/pom.xml b/sdk/mixedreality/azure-resourcemanager-mixedreality/pom.xml index c4f867a52f65..3d1353559061 100644 --- a/sdk/mixedreality/azure-resourcemanager-mixedreality/pom.xml +++ b/sdk/mixedreality/azure-resourcemanager-mixedreality/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/mobilenetwork/azure-resourcemanager-mobilenetwork/README.md b/sdk/mobilenetwork/azure-resourcemanager-mobilenetwork/README.md index 06eba299d9b5..f74dfd75bac5 100644 --- a/sdk/mobilenetwork/azure-resourcemanager-mobilenetwork/README.md +++ b/sdk/mobilenetwork/azure-resourcemanager-mobilenetwork/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-mobilenetwork - 1.3.0 + 1.4.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fmobilenetwork%2Fazure-resourcemanager-mobilenetwork%2FREADME.png) + diff --git a/sdk/mobilenetwork/azure-resourcemanager-mobilenetwork/pom.xml b/sdk/mobilenetwork/azure-resourcemanager-mobilenetwork/pom.xml index bf84ebeef41b..2874b7c9517a 100644 --- a/sdk/mobilenetwork/azure-resourcemanager-mobilenetwork/pom.xml +++ b/sdk/mobilenetwork/azure-resourcemanager-mobilenetwork/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/modelsrepository/azure-iot-modelsrepository/README.md b/sdk/modelsrepository/azure-iot-modelsrepository/README.md index 5a1772a1dbec..1d24ef85231a 100644 --- a/sdk/modelsrepository/azure-iot-modelsrepository/README.md +++ b/sdk/modelsrepository/azure-iot-modelsrepository/README.md @@ -18,7 +18,7 @@ For the best development experience, developers should use the official Microsof com.azure azure-iot-modelsrepository - 1.0.0-beta.1 + 1.0.0-beta.2 ``` diff --git a/sdk/modelsrepository/azure-iot-modelsrepository/pom.xml b/sdk/modelsrepository/azure-iot-modelsrepository/pom.xml index 9a08dcb90483..f6220dabb228 100644 --- a/sdk/modelsrepository/azure-iot-modelsrepository/pom.xml +++ b/sdk/modelsrepository/azure-iot-modelsrepository/pom.xml @@ -50,30 +50,30 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/mongocluster/azure-resourcemanager-mongocluster/README.md b/sdk/mongocluster/azure-resourcemanager-mongocluster/README.md index 1190015dc837..9b879937b908 100644 --- a/sdk/mongocluster/azure-resourcemanager-mongocluster/README.md +++ b/sdk/mongocluster/azure-resourcemanager-mongocluster/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-mongocluster - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -118,4 +118,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fmongocluster%2Fazure-resourcemanager-mongocluster%2FREADME.png) + diff --git a/sdk/mongocluster/azure-resourcemanager-mongocluster/pom.xml b/sdk/mongocluster/azure-resourcemanager-mongocluster/pom.xml index 558d0b69e2fa..9cd834795c1d 100644 --- a/sdk/mongocluster/azure-resourcemanager-mongocluster/pom.xml +++ b/sdk/mongocluster/azure-resourcemanager-mongocluster/pom.xml @@ -51,29 +51,29 @@ Code generated by Microsoft (R) TypeSpec Code Generator. com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/mongocluster/azure-resourcemanager-mongocluster/src/main/java/com/azure/resourcemanager/mongocluster/MongoClusterManager.java b/sdk/mongocluster/azure-resourcemanager-mongocluster/src/main/java/com/azure/resourcemanager/mongocluster/MongoClusterManager.java index d8294f1fbe8d..580d7a99faf9 100644 --- a/sdk/mongocluster/azure-resourcemanager-mongocluster/src/main/java/com/azure/resourcemanager/mongocluster/MongoClusterManager.java +++ b/sdk/mongocluster/azure-resourcemanager-mongocluster/src/main/java/com/azure/resourcemanager/mongocluster/MongoClusterManager.java @@ -22,6 +22,7 @@ import com.azure.core.http.policy.UserAgentPolicy; import com.azure.core.management.profile.AzureProfile; import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.mongocluster.fluent.MongoClusterManagementClient; import com.azure.resourcemanager.mongocluster.implementation.FirewallRulesImpl; @@ -41,6 +42,7 @@ import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; @@ -114,6 +116,9 @@ public static Configurable configure() { */ public static final class Configurable { private static final ClientLogger LOGGER = new ClientLogger(Configurable.class); + private static final String SDK_VERSION = "version"; + private static final Map PROPERTIES + = CoreUtils.getProperties("azure-resourcemanager-mongocluster.properties"); private HttpClient httpClient; private HttpLogOptions httpLogOptions; @@ -221,12 +226,14 @@ public MongoClusterManager authenticate(TokenCredential credential, AzureProfile Objects.requireNonNull(credential, "'credential' cannot be null."); Objects.requireNonNull(profile, "'profile' cannot be null."); + String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); + StringBuilder userAgentBuilder = new StringBuilder(); userAgentBuilder.append("azsdk-java") .append("-") .append("com.azure.resourcemanager.mongocluster") .append("/") - .append("1.0.0-beta.1"); + .append(clientVersion); if (!Configuration.getGlobalConfiguration().get("AZURE_TELEMETRY_DISABLED", false)) { userAgentBuilder.append(" (") .append(Configuration.getGlobalConfiguration().get("java.version")) diff --git a/sdk/mongocluster/azure-resourcemanager-mongocluster/src/main/resources/azure-resourcemanager-mongocluster.properties b/sdk/mongocluster/azure-resourcemanager-mongocluster/src/main/resources/azure-resourcemanager-mongocluster.properties new file mode 100644 index 000000000000..defbd48204e4 --- /dev/null +++ b/sdk/mongocluster/azure-resourcemanager-mongocluster/src/main/resources/azure-resourcemanager-mongocluster.properties @@ -0,0 +1 @@ +version=${project.version} diff --git a/sdk/monitor/azure-monitor-ingestion-perf/pom.xml b/sdk/monitor/azure-monitor-ingestion-perf/pom.xml index bdd2471b599c..dfb62c42bfa1 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.15.0 + 1.15.4 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 diff --git a/sdk/monitor/azure-monitor-ingestion/CHANGELOG.md b/sdk/monitor/azure-monitor-ingestion/CHANGELOG.md index 11e7c2981b30..b6323dd3ae05 100644 --- a/sdk/monitor/azure-monitor-ingestion/CHANGELOG.md +++ b/sdk/monitor/azure-monitor-ingestion/CHANGELOG.md @@ -10,6 +10,17 @@ ### Other Changes +## 1.2.8 (2025-02-25) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`. +- Upgraded `azure-json` from `1.3.0` to version `1.4.0`. +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. + + ## 1.2.7 (2024-12-04) ### Other Changes diff --git a/sdk/monitor/azure-monitor-ingestion/README.md b/sdk/monitor/azure-monitor-ingestion/README.md index 6da6e5f4d24e..134f46cbe3f1 100644 --- a/sdk/monitor/azure-monitor-ingestion/README.md +++ b/sdk/monitor/azure-monitor-ingestion/README.md @@ -58,7 +58,7 @@ add the direct dependency to your project as follows. com.azure azure-monitor-ingestion - 1.2.3 + 1.3.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -77,7 +77,7 @@ To use the [DefaultAzureCredential][DefaultAzureCredential] provider shown below com.azure azure-identity - 1.14.2 + 1.15.3 ``` [//]: # ({x-version-update-end}) @@ -250,4 +250,4 @@ For more information see the [Code of Conduct FAQ](https://opensource.microsoft. [log_analytics_workspace]: https://learn.microsoft.com//azure/azure-monitor/logs/log-analytics-workspace-overview [logging]: https://learn.microsoft.com//azure/developer/java/sdk/logging-overview [samples]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/monitor/azure-monitor-ingestion/src/samples/java/com/azure/monitor/ingestion -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fmonitor%2Fazure-monitor-ingestion%2FREADME.png) + diff --git a/sdk/monitor/azure-monitor-ingestion/pom.xml b/sdk/monitor/azure-monitor-ingestion/pom.xml index d590fe3200bb..04ed6f6c47d6 100644 --- a/sdk/monitor/azure-monitor-ingestion/pom.xml +++ b/sdk/monitor/azure-monitor-ingestion/pom.xml @@ -70,30 +70,30 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/monitor/azure-monitor-ingestion/src/samples/README.md b/sdk/monitor/azure-monitor-ingestion/src/samples/README.md index 7aa8f84e3585..7c19a54787a1 100644 --- a/sdk/monitor/azure-monitor-ingestion/src/samples/README.md +++ b/sdk/monitor/azure-monitor-ingestion/src/samples/README.md @@ -25,4 +25,4 @@ This project welcomes contributions and suggestions. Find [more contributing][SD [SDK_README_KEY_CONCEPTS]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/monitor/azure-monitor-ingestion/README.md#key-concepts [SDK_README_NEXT_STEPS]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/monitor/azure-monitor-ingestion/README.md#next-steps -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fmonitor%2Fazure-monitor-ingestion%2FREADME.png) + diff --git a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/CHANGELOG.md b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/CHANGELOG.md index 0c7b81f4c34e..187e21bdc932 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/CHANGELOG.md +++ b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/CHANGELOG.md @@ -1,5 +1,30 @@ # Release History +## 1.1.0-beta.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + +## 1.0.0 (2025-03-07) + +### Other Changes +- General availability release. + +## 1.0.0-beta.3 (2025-02-24) + +### Bugs Fixed +- Fixed redirection logic for QuickPulse service calls when only the instrumentation key is provided in the connection string. ([#44211](https://github.com/Azure/azure-sdk-for-net/pull/44211)) + +## 1.0.0-beta.2 (2025-01-31) + +### Other Changes +- [Update OpenTelemetry SDK to 1.46.0](https://github.com/Azure/azure-sdk-for-java/pull/43974) + ## 1.0.0-beta.1 (2025-01-16) ### Features Added diff --git a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/README.md b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/README.md index a77c4ef96bbf..22782f1da5a6 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/README.md +++ b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/README.md @@ -202,4 +202,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ [coc_contact]: mailto:opencode@microsoft.com -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%monitor%2Fazure-monitor-opentelemetry-autoconfigure%2FREADME.png) + diff --git a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/assets.json b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/assets.json deleted file mode 100644 index 387ae22c8548..000000000000 --- a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/assets.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "AssetsRepo": "Azure/azure-sdk-assets", - "AssetsRepoPrefixPath": "java", - "TagPrefix": "java/monitor/azure-monitor-opentelemetry-exporter", - "Tag": "java/monitor/azure-monitor-opentelemetry-exporter_558a81e425" -} diff --git a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/checkstyle-suppressions.xml b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/checkstyle-suppressions.xml index dcce54a16b2b..48b0ee4d0f7d 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/checkstyle-suppressions.xml +++ b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/checkstyle-suppressions.xml @@ -271,6 +271,8 @@ + + diff --git a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/pom.xml b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/pom.xml index 4e2dfda79b3a..0166acdd4fc1 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/pom.xml +++ b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/pom.xml @@ -14,7 +14,7 @@ com.azure azure-monitor-opentelemetry-autoconfigure - 1.0.0-beta.1 + 1.1.0-beta.1 Azure Monitor OpenTelemetry SDK Autoconfigure Distro This package contains Azure Monitor OpenTelemetry SDK Autoconfigure Distro. @@ -36,6 +36,8 @@ --add-opens com.azure.monitor.opentelemetry.autoconfigure/com.azure.monitor.opentelemetry.autoconfigure=ALL-UNNAMED + --add-exports com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED + --add-reads com.azure.monitor.opentelemetry.autoconfigure=com.azure.core.tracing.opentelemetry checkstyle-suppressions.xml @@ -47,47 +49,47 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 io.opentelemetry opentelemetry-api - 1.43.0 + 1.46.0 io.opentelemetry opentelemetry-sdk - 1.43.0 + 1.46.0 io.opentelemetry opentelemetry-sdk-metrics - 1.43.0 + 1.46.0 io.opentelemetry opentelemetry-sdk-logs - 1.43.0 + 1.46.0 io.opentelemetry opentelemetry-sdk-extension-autoconfigure-spi - 1.43.0 + 1.46.0 io.opentelemetry opentelemetry-sdk-extension-autoconfigure - 1.43.0 + 1.46.0 io.opentelemetry.semconv @@ -135,43 +137,43 @@ io.opentelemetry opentelemetry-sdk-testing - 1.43.0 + 1.46.0 test com.azure azure-data-appconfiguration - 1.7.3 + 1.7.4 test com.azure azure-messaging-eventhubs - 5.19.2 + 5.20.1 test com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.52 + 1.0.0-beta.56 test com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-messaging-eventhubs-checkpointstore-blob - 1.20.2 + 1.20.5 test com.azure azure-identity - 1.15.0 + 1.15.4 test @@ -192,12 +194,12 @@ - io.opentelemetry:opentelemetry-api:[1.43.0] - io.opentelemetry:opentelemetry-sdk:[1.43.0] - io.opentelemetry:opentelemetry-sdk-metrics:[1.43.0] - io.opentelemetry:opentelemetry-sdk-logs:[1.43.0] - io.opentelemetry:opentelemetry-sdk-extension-autoconfigure-spi:[1.43.0] - io.opentelemetry:opentelemetry-sdk-extension-autoconfigure:[1.43.0] + io.opentelemetry:opentelemetry-api:[1.46.0] + io.opentelemetry:opentelemetry-sdk:[1.46.0] + io.opentelemetry:opentelemetry-sdk-metrics:[1.46.0] + io.opentelemetry:opentelemetry-sdk-logs:[1.46.0] + io.opentelemetry:opentelemetry-sdk-extension-autoconfigure-spi:[1.46.0] + io.opentelemetry:opentelemetry-sdk-extension-autoconfigure:[1.46.0] io.opentelemetry.semconv:opentelemetry-semconv-incubating:[1.26.0-alpha] com.squareup.okio:okio:[3.9.1] diff --git a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/main/java/com/azure/monitor/opentelemetry/autoconfigure/AzureMonitorAutoConfigure.java b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/main/java/com/azure/monitor/opentelemetry/autoconfigure/AzureMonitorAutoConfigure.java index adbd2b971b59..1a45e4b90e53 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/main/java/com/azure/monitor/opentelemetry/autoconfigure/AzureMonitorAutoConfigure.java +++ b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/main/java/com/azure/monitor/opentelemetry/autoconfigure/AzureMonitorAutoConfigure.java @@ -47,10 +47,10 @@ public static void customize(AutoConfigurationCustomizer autoConfigurationCustom /** * Customizes an {@link AutoConfigurationCustomizer} for Azure Monitor. * @param autoConfigurationCustomizer the {@link AutoConfigurationCustomizer} object. - * @param exporterOptions Advanced configuration to send the data to Azure Monitor. + * @param autoConfigureOptions Advanced configuration to send the data to Azure Monitor. */ public static void customize(AutoConfigurationCustomizer autoConfigurationCustomizer, - AzureMonitorAutoConfigureOptions exporterOptions) { + AzureMonitorAutoConfigureOptions autoConfigureOptions) { autoConfigurationCustomizer.addPropertiesSupplier(() -> { Map props = new HashMap<>(); props.put("otel.traces.exporter", AzureMonitorExporterProviderKeys.EXPORTER_NAME); @@ -62,21 +62,21 @@ public static void customize(AutoConfigurationCustomizer autoConfigurationCustom AzureMonitorExporterBuilder azureMonitorExporterBuilder = new AzureMonitorExporterBuilder(); autoConfigurationCustomizer.addSpanExporterCustomizer((spanExporter, configProperties) -> { if (spanExporter instanceof AzureMonitorSpanExporterProvider.MarkerSpanExporter) { - azureMonitorExporterBuilder.initializeIfNot(exporterOptions, configProperties); + azureMonitorExporterBuilder.initializeIfNot(autoConfigureOptions, configProperties); spanExporter = azureMonitorExporterBuilder.buildSpanExporter(); } return spanExporter; }); autoConfigurationCustomizer.addMetricExporterCustomizer((metricExporter, configProperties) -> { if (metricExporter instanceof AzureMonitorMetricExporterProvider.MarkerMetricExporter) { - azureMonitorExporterBuilder.initializeIfNot(exporterOptions, configProperties); + azureMonitorExporterBuilder.initializeIfNot(autoConfigureOptions, configProperties); metricExporter = azureMonitorExporterBuilder.buildMetricExporter(); } return metricExporter; }); autoConfigurationCustomizer.addLogRecordExporterCustomizer((logRecordExporter, configProperties) -> { if (logRecordExporter instanceof AzureMonitorLogRecordExporterProvider.MarkerLogRecordExporter) { - azureMonitorExporterBuilder.initializeIfNot(exporterOptions, configProperties); + azureMonitorExporterBuilder.initializeIfNot(autoConfigureOptions, configProperties); logRecordExporter = azureMonitorExporterBuilder.buildLogRecordExporter(); } return logRecordExporter; diff --git a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/main/java/com/azure/monitor/opentelemetry/autoconfigure/implementation/pipeline/TelemetryItemExporter.java b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/main/java/com/azure/monitor/opentelemetry/autoconfigure/implementation/pipeline/TelemetryItemExporter.java index 4ff48fb7b8af..2902a6d4a69c 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/main/java/com/azure/monitor/opentelemetry/autoconfigure/implementation/pipeline/TelemetryItemExporter.java +++ b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/main/java/com/azure/monitor/opentelemetry/autoconfigure/implementation/pipeline/TelemetryItemExporter.java @@ -12,6 +12,7 @@ import com.azure.monitor.opentelemetry.autoconfigure.implementation.models.ContextTagKeys; import com.azure.monitor.opentelemetry.autoconfigure.implementation.models.TelemetryItem; import com.azure.monitor.opentelemetry.autoconfigure.implementation.utils.AksResourceAttributes; +import com.azure.monitor.opentelemetry.autoconfigure.implementation.utils.IKeyMasker; import io.opentelemetry.sdk.common.CompletableResultCode; import io.opentelemetry.sdk.resources.Resource; import io.opentelemetry.semconv.ServiceAttributes; @@ -168,8 +169,7 @@ private static String maskIKeys(List telemetryItems, String json) Set iKeys = telemetryItems.stream().map(TelemetryItem::getInstrumentationKey).collect(Collectors.toSet()); for (String instrumentationKey : iKeys) { - String maskedIKey = "*" + instrumentationKey.substring(instrumentationKey.length() - 13); - json = json.replace(instrumentationKey, maskedIKey); + json = json.replace(instrumentationKey, IKeyMasker.mask(instrumentationKey)); } return json; } diff --git a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/main/java/com/azure/monitor/opentelemetry/autoconfigure/implementation/quickpulse/QuickPulse.java b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/main/java/com/azure/monitor/opentelemetry/autoconfigure/implementation/quickpulse/QuickPulse.java index 9e5262dcb5cf..caef81a29274 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/main/java/com/azure/monitor/opentelemetry/autoconfigure/implementation/quickpulse/QuickPulse.java +++ b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/main/java/com/azure/monitor/opentelemetry/autoconfigure/implementation/quickpulse/QuickPulse.java @@ -4,12 +4,15 @@ package com.azure.monitor.opentelemetry.autoconfigure.implementation.quickpulse; import com.azure.core.http.HttpPipeline; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.azure.monitor.opentelemetry.autoconfigure.implementation.models.TelemetryItem; import com.azure.monitor.opentelemetry.autoconfigure.implementation.quickpulse.filtering.FilteringConfiguration; import com.azure.monitor.opentelemetry.autoconfigure.implementation.quickpulse.swagger.LiveMetricsRestAPIsForClientSDKs; import com.azure.monitor.opentelemetry.autoconfigure.implementation.quickpulse.swagger.LiveMetricsRestAPIsForClientSDKsBuilder; import com.azure.monitor.opentelemetry.autoconfigure.implementation.quickpulse.swagger.models.MonitoringDataPoint; import com.azure.monitor.opentelemetry.autoconfigure.implementation.utils.HostName; +import com.azure.monitor.opentelemetry.autoconfigure.implementation.utils.IKeyMasker; import com.azure.monitor.opentelemetry.autoconfigure.implementation.utils.Strings; import com.azure.monitor.opentelemetry.autoconfigure.implementation.utils.ThreadPoolUtils; import reactor.util.annotation.Nullable; @@ -28,6 +31,8 @@ public class QuickPulse { private volatile QuickPulseDataCollector collector; + private static final ClientLogger LOGGER = new ClientLogger(QuickPulse.class); + public static QuickPulse create(HttpPipeline httpPipeline, Supplier endpointUrl, Supplier instrumentationKey, @Nullable String roleName, @Nullable String roleInstance, String sdkVersion) { @@ -69,6 +74,12 @@ public void add(TelemetryItem telemetryItem) { private void initialize(HttpPipeline httpPipeline, Supplier endpointUrl, Supplier instrumentationKey, @Nullable String roleName, @Nullable String roleInstance, String sdkVersion) { + if (LOGGER.canLogAtLevel(LogLevel.VERBOSE)) { + LOGGER.verbose( + "Initializing QuickPulse with instrumentation key: {} , URL {}, rolename {}, role instance {}, sdk version {}", + IKeyMasker.mask(instrumentationKey.get()), endpointUrl.get().toString(), roleName, roleInstance, + sdkVersion); + } String quickPulseId = UUID.randomUUID().toString().replace("-", ""); ArrayBlockingQueue sendQueue = new ArrayBlockingQueue<>(256, true); @@ -121,4 +132,5 @@ private void initialize(HttpPipeline httpPipeline, Supplier endpointUrl, Su this.collector = collector; } + } diff --git a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/main/java/com/azure/monitor/opentelemetry/autoconfigure/implementation/quickpulse/QuickPulseCoordinator.java b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/main/java/com/azure/monitor/opentelemetry/autoconfigure/implementation/quickpulse/QuickPulseCoordinator.java index a2be60112d2d..2c45364b1c34 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/main/java/com/azure/monitor/opentelemetry/autoconfigure/implementation/quickpulse/QuickPulseCoordinator.java +++ b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/main/java/com/azure/monitor/opentelemetry/autoconfigure/implementation/quickpulse/QuickPulseCoordinator.java @@ -9,6 +9,8 @@ import org.slf4j.MDC; import reactor.util.annotation.Nullable; +import java.net.MalformedURLException; +import java.net.URL; import java.util.concurrent.TimeUnit; import static com.azure.monitor.opentelemetry.autoconfigure.implementation.utils.AzureMonitorMsgId.QUICK_PULSE_PING_ERROR; @@ -70,7 +72,6 @@ public void run() { @SuppressWarnings("try") private long sendData() { - dataSender.setRedirectEndpointPrefix(qpsServiceRedirectedEndpoint); dataFetcher.prepareQuickPulseDataForSend(); QuickPulseStatus qpStatus = dataSender.getQuickPulseStatus(); @@ -152,7 +153,16 @@ private long ping() { private QuickPulseStatus handleReceivedPingHeaders(IsSubscribedHeaders pingHeaders) { String redirectLink = pingHeaders.getXMsQpsServiceEndpointRedirectV2(); if (!Strings.isNullOrEmpty(redirectLink)) { - qpsServiceRedirectedEndpoint = redirectLink; + try { + URL redirectUrl = new URL(redirectLink); + // Taking the QuickPulseService.svc part out if present because the swagger will add that on. + qpsServiceRedirectedEndpoint = redirectUrl.getProtocol() + "://" + redirectUrl.getHost() + "/"; + logger.verbose("Handling ping header to redirect to {}", qpsServiceRedirectedEndpoint); + dataSender.setRedirectEndpointPrefix(qpsServiceRedirectedEndpoint); + } catch (MalformedURLException e) { + logger.error("The service returned a malformed URL in the redirect header: {}. Exception message: {}", + redirectLink, e.getMessage()); + } } String pollingIntervalHeader = pingHeaders.getXMsQpsServicePollingIntervalHint(); diff --git a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/main/java/com/azure/monitor/opentelemetry/autoconfigure/implementation/quickpulse/QuickPulseDataSender.java b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/main/java/com/azure/monitor/opentelemetry/autoconfigure/implementation/quickpulse/QuickPulseDataSender.java index 40a666923aea..0f4edd0518ab 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/main/java/com/azure/monitor/opentelemetry/autoconfigure/implementation/quickpulse/QuickPulseDataSender.java +++ b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/main/java/com/azure/monitor/opentelemetry/autoconfigure/implementation/quickpulse/QuickPulseDataSender.java @@ -54,6 +54,8 @@ class QuickPulseDataSender implements Runnable { this.qpStatus = QuickPulseStatus.QP_IS_OFF; this.instrumentationKey = instrumentationKey; this.configuration = configuration; + logger.verbose("QuickPulseDataSender initialized with endpointUrl: {}, instrumentationKey: {}", + endpointUrl.get().toString(), instrumentationKey.get()); } @Override @@ -73,6 +75,7 @@ public void run() { } long sendTime = System.nanoTime(); + // should not include "QuickPulseService.svc/" String endpointPrefix = Strings.isNullOrEmpty(redirectEndpointPrefix) ? getQuickPulseEndpoint() : redirectEndpointPrefix; // TODO (harskaur): for a future PR revisit caching & retry mechanism for failed post requests (shouldn't retry), send "cached" data points in the next post @@ -88,6 +91,8 @@ public void run() { } try { + // the swagger will add on the QuickPulseService.svc/ when creating the request. + logger.verbose("About to publish to quickpulse with the endpoint prefix: {}", endpointPrefix); Response responseMono = liveMetricsRestAPIsForClientSDKs .publishNoCustomHeadersWithResponseAsync(endpointPrefix, instrumentationKey.get(), etag, transmissionTimeInTicks, dataPointList) @@ -122,8 +127,7 @@ public void run() { } catch (RuntimeException e) { // this includes ServiceErrorException & RuntimeException thrown from quickpulse post api onPostError(sendTime); - logger.error( - "QuickPulseDataSender received a service error while attempting to send data to quickpulse {}", + logger.error("QuickPulseDataSender received an error while attempting to send data to quickpulse {}", e.getMessage()); } diff --git a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/main/java/com/azure/monitor/opentelemetry/autoconfigure/implementation/quickpulse/QuickPulsePingSender.java b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/main/java/com/azure/monitor/opentelemetry/autoconfigure/implementation/quickpulse/QuickPulsePingSender.java index 92c4afe5ff4b..f8da3592f530 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/main/java/com/azure/monitor/opentelemetry/autoconfigure/implementation/quickpulse/QuickPulsePingSender.java +++ b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/main/java/com/azure/monitor/opentelemetry/autoconfigure/implementation/quickpulse/QuickPulsePingSender.java @@ -78,12 +78,15 @@ IsSubscribedHeaders ping(String redirectedEndpoint) { Date currentDate = new Date(); long transmissionTimeInTicks = currentDate.getTime() * 10000 + TICKS_AT_EPOCH; + // should not include "QuickPulseService.svc/" String endpointPrefix = Strings.isNullOrEmpty(redirectedEndpoint) ? getQuickPulseEndpoint() : redirectedEndpoint; + logger.verbose("About to ping quickpulse with the endpoint prefix: {}", endpointPrefix); long sendTime = System.nanoTime(); try { + // The swagger api appends QuickPulseService.svc/ when creating the request. Response responseMono = liveMetricsRestAPIsForClientSDKs .isSubscribedNoCustomHeadersWithResponseAsync(endpointPrefix, instrumentationKey, @@ -118,9 +121,9 @@ IsSubscribedHeaders ping(String redirectedEndpoint) { } catch (RuntimeException e) { // 404 landed here Throwable t = e.getCause(); - if (!NetworkFriendlyExceptions.logSpecialOneTimeFriendlyException(t, getQuickPulseEndpoint(), + if (!NetworkFriendlyExceptions.logSpecialOneTimeFriendlyException(t, endpointPrefix, friendlyExceptionThrown, logger)) { - operationLogger.recordFailure(t.getMessage() + " (" + endpointPrefix + ")", t, QUICK_PULSE_PING_ERROR); + operationLogger.recordFailure(t.getMessage(), t, QUICK_PULSE_PING_ERROR); } } return onPingError(sendTime); diff --git a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/main/java/com/azure/monitor/opentelemetry/autoconfigure/implementation/utils/IKeyMasker.java b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/main/java/com/azure/monitor/opentelemetry/autoconfigure/implementation/utils/IKeyMasker.java new file mode 100644 index 000000000000..dc702fcd782c --- /dev/null +++ b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/main/java/com/azure/monitor/opentelemetry/autoconfigure/implementation/utils/IKeyMasker.java @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.monitor.opentelemetry.autoconfigure.implementation.utils; + +public final class IKeyMasker { + + private static final int CHARACTERS_TO_KEEP_AT_END = 13; + + private IKeyMasker() { + } + + public static String mask(String instrumentationKey) { + // Tests could set the connection string with a short one + if (instrumentationKey.length() > CHARACTERS_TO_KEEP_AT_END) { + return "*" + instrumentationKey.substring(instrumentationKey.length() - CHARACTERS_TO_KEEP_AT_END); + } + return instrumentationKey; + } +} diff --git a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/test/java/com/azure/monitor/opentelemetry/autoconfigure/AppConfigurationExporterIntegrationTest.java b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/test/java/com/azure/monitor/opentelemetry/autoconfigure/AppConfigurationExporterIntegrationTest.java index 6c6988726bc2..8777993699c9 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/test/java/com/azure/monitor/opentelemetry/autoconfigure/AppConfigurationExporterIntegrationTest.java +++ b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/test/java/com/azure/monitor/opentelemetry/autoconfigure/AppConfigurationExporterIntegrationTest.java @@ -3,6 +3,7 @@ package com.azure.monitor.opentelemetry.autoconfigure; +import com.azure.core.credential.TokenCredential; import com.azure.core.http.HttpPipelineCallContext; import com.azure.core.http.HttpPipelineNextPolicy; import com.azure.core.http.HttpResponse; @@ -10,6 +11,7 @@ import com.azure.core.http.policy.HttpLogOptions; import com.azure.core.http.policy.HttpPipelinePolicy; import com.azure.core.test.annotation.LiveOnly; +import com.azure.core.util.Configuration; import com.azure.core.util.Context; import com.azure.core.util.FluxUtil; import com.azure.data.appconfiguration.ConfigurationClient; @@ -37,6 +39,15 @@ @LiveOnly public class AppConfigurationExporterIntegrationTest extends MonitorExporterClientTestBase { + + private TokenCredential credential; + + @Override + public void beforeTest() { + super.beforeTest(); + credential = TokenCredentialUtil.getTestTokenCredential(interceptorManager); + } + @Test public void setConfigurationTest() throws InterruptedException { CountDownLatch exporterCountDown = new CountDownLatch(1); @@ -87,8 +98,10 @@ public void testDisableTracing() throws InterruptedException { assertTrue(exporterCountDown.await(60, TimeUnit.SECONDS)); } - private static ConfigurationClient getConfigurationClient() { - return new ConfigurationClientBuilder().connectionString(System.getenv("AZURE_APPCONFIG_CONNECTION_STRING")) + private ConfigurationClient getConfigurationClient() { + String endPoint = Configuration.getGlobalConfiguration().get("AZURE_APPCONFIG_ENDPOINT"); + return new ConfigurationClientBuilder().credential(credential) + .endpoint(endPoint) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .buildClient(); } diff --git a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/test/java/com/azure/monitor/opentelemetry/autoconfigure/AzureMonitorExportersEndToEndTest.java b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/test/java/com/azure/monitor/opentelemetry/autoconfigure/AzureMonitorExportersEndToEndTest.java index 9dbfe162c133..9790a55163db 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/test/java/com/azure/monitor/opentelemetry/autoconfigure/AzureMonitorExportersEndToEndTest.java +++ b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/test/java/com/azure/monitor/opentelemetry/autoconfigure/AzureMonitorExportersEndToEndTest.java @@ -3,7 +3,11 @@ package com.azure.monitor.opentelemetry.autoconfigure; +import com.azure.core.http.HttpClient; import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.policy.HttpPipelinePolicy; +import com.azure.monitor.opentelemetry.autoconfigure.implementation.NoopTracer; import com.azure.monitor.opentelemetry.autoconfigure.implementation.models.MessageData; import com.azure.monitor.opentelemetry.autoconfigure.implementation.models.MetricsData; import com.azure.monitor.opentelemetry.autoconfigure.implementation.models.RemoteDependencyData; @@ -19,11 +23,13 @@ import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.context.Scope; import io.opentelemetry.sdk.OpenTelemetrySdk; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import reactor.util.annotation.Nullable; import java.net.URL; +import java.util.ArrayList; import java.util.Collections; +import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; @@ -31,8 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; -@Disabled -public class AzureMonitorExportersEndToEndTest extends MonitorExporterClientTestBase { +public class AzureMonitorExportersEndToEndTest { private static final String CONNECTION_STRING_ENV = "InstrumentationKey=00000000-0000-0000-0000-0FEEDDADBEEF;" + "IngestionEndpoint=https://test.in.applicationinsights.azure.com/;" @@ -70,6 +75,21 @@ public void testBuildTraceExporter() throws Exception { validateSpan(spanTelemetryItem); } + HttpPipeline getHttpPipeline(@Nullable HttpPipelinePolicy policy, HttpClient httpClient) { + List policies = new ArrayList<>(); + if (policy != null) { + policies.add(policy); + } + return new HttpPipelineBuilder().httpClient(httpClient) + .policies(policies.toArray(new HttpPipelinePolicy[0])) + .tracer(new NoopTracer()) + .build(); + } + + HttpPipeline getHttpPipeline(@Nullable HttpPipelinePolicy policy) { + return getHttpPipeline(policy, HttpClient.createDefault()); + } + @Test public void testBuildMetricExporter() throws Exception { // create the OpenTelemetry SDK diff --git a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/test/java/com/azure/monitor/opentelemetry/autoconfigure/EventHubsExporterIntegrationTest.java b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/test/java/com/azure/monitor/opentelemetry/autoconfigure/EventHubsExporterIntegrationTest.java index 45591a00a6ca..0a8dc551f418 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/test/java/com/azure/monitor/opentelemetry/autoconfigure/EventHubsExporterIntegrationTest.java +++ b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/test/java/com/azure/monitor/opentelemetry/autoconfigure/EventHubsExporterIntegrationTest.java @@ -3,9 +3,18 @@ package com.azure.monitor.opentelemetry.autoconfigure; +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.HttpPipelineCallContext; +import com.azure.core.http.HttpPipelineNextPolicy; +import com.azure.core.http.HttpPipelineNextSyncPolicy; +import com.azure.core.http.HttpResponse; import com.azure.core.http.policy.HttpPipelinePolicy; import com.azure.core.test.annotation.LiveOnly; +import com.azure.core.tracing.opentelemetry.OpenTelemetryTracingOptions; +import com.azure.core.util.ClientOptions; import com.azure.core.util.FluxUtil; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.Configuration; import com.azure.messaging.eventhubs.EventData; import com.azure.messaging.eventhubs.EventHubClientBuilder; import com.azure.messaging.eventhubs.EventHubProducerAsyncClient; @@ -14,17 +23,25 @@ import com.azure.messaging.eventhubs.LoadBalancingStrategy; import com.azure.messaging.eventhubs.checkpointstore.blob.BlobCheckpointStore; import com.azure.messaging.eventhubs.models.CreateBatchOptions; +import com.azure.monitor.opentelemetry.autoconfigure.implementation.localstorage.LocalStorageTelemetryPipelineListener; +import com.azure.monitor.opentelemetry.autoconfigure.implementation.models.MonitorDomain; +import com.azure.monitor.opentelemetry.autoconfigure.implementation.models.RemoteDependencyData; +import com.azure.monitor.opentelemetry.autoconfigure.implementation.models.TelemetryItem; import com.azure.monitor.opentelemetry.autoconfigure.implementation.utils.TestUtils; import com.azure.storage.blob.BlobContainerAsyncClient; import com.azure.storage.blob.BlobContainerClientBuilder; +import io.opentelemetry.api.OpenTelemetry; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.context.Scope; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -37,38 +54,80 @@ public class EventHubsExporterIntegrationTest extends MonitorExporterClientTestB private static final String STORAGE_CONNECTION_STRING = System.getenv("STORAGE_CONNECTION_STRING"); private static final String CONTAINER_NAME = System.getenv("STORAGE_CONTAINER_NAME"); + private static final ClientLogger LOGGER = new ClientLogger(EventHubsExporterIntegrationTest.class); + + private TokenCredential credential; + + @Override + public void beforeTest() { + super.beforeTest(); + credential = TokenCredentialUtil.getTestTokenCredential(interceptorManager); + } + @Test + @SuppressWarnings("try") public void producerTest() throws InterruptedException { + String ehNamespace = Configuration.getGlobalConfiguration().get("AZURE_EVENTHUBS_FULLY_QUALIFIED_DOMAIN_NAME"); + String ehName = Configuration.getGlobalConfiguration().get("AZURE_EVENTHUBS_EVENT_HUB_NAME"); + CountDownLatch exporterCountDown = new CountDownLatch(2); String spanName = "event-hubs-producer-testing"; - HttpPipelinePolicy validationPolicy = (context, next) -> { - Mono asyncString = FluxUtil.collectBytesInByteBufferStream(context.getHttpRequest().getBody()) - .map(bytes -> new String(bytes, StandardCharsets.UTF_8)); - asyncString.subscribe(value -> { - if (value.contains(spanName)) { - exporterCountDown.countDown(); - } - if (value.contains("EventHubs.send")) { - exporterCountDown.countDown(); + HttpPipelinePolicy validationPolicy = new HttpPipelinePolicy() { + @Override + public Mono process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { + checkTelemetry(context); + return next.process(); + } + + @Override + public HttpResponse processSync(HttpPipelineCallContext context, HttpPipelineNextSyncPolicy next) { + checkTelemetry(context); + return next.processSync(); + } + + private void checkTelemetry(HttpPipelineCallContext context) { + byte[] asyncBytes = LocalStorageTelemetryPipelineListener + .ungzip(context.getHttpRequest().getBodyAsBinaryData().toBytes()); + List telemetryItems = TestUtils.deserialize(asyncBytes); + + for (TelemetryItem telemetryItem : telemetryItems) { + MonitorDomain monitorDomain = telemetryItem.getData().getBaseData(); + RemoteDependencyData remoteDependencyData = TestUtils.toRemoteDependencyData(monitorDomain); + String remoteDependencyName = remoteDependencyData.getName(); + if (remoteDependencyName.contains(spanName)) { + exporterCountDown.countDown(); + LOGGER.info("Count down " + spanName); + } else if (("send " + ehName).equals(remoteDependencyName)) { + exporterCountDown.countDown(); + LOGGER.info("Count down eventHubs send"); + } else { + LOGGER.info("remoteDependencyName = " + remoteDependencyName); + } } - }); - return next.process(); + } }; - Tracer tracer = TestUtils.createOpenTelemetrySdk(getHttpPipeline(validationPolicy)).getTracer("Sample"); - EventHubProducerAsyncClient producer - = new EventHubClientBuilder().connectionString(CONNECTION_STRING).buildAsyncProducerClient(); - Span span = tracer.spanBuilder(spanName).startSpan(); - Scope scope = span.makeCurrent(); - try { - producer.createBatch().flatMap(batch -> { - batch.tryAdd(new EventData("test event")); - return producer.send(batch); - }).subscribe(); - } finally { - span.end(); - scope.close(); + + OpenTelemetry otel = TestUtils.createOpenTelemetrySdk(getHttpPipeline(validationPolicy)); + Tracer tracer = otel.getTracer("Sample"); + + try (EventHubProducerAsyncClient producer = new EventHubClientBuilder().credential(credential) + .fullyQualifiedNamespace(ehNamespace) + .eventHubName(ehName) + .clientOptions( + new ClientOptions().setTracingOptions(new OpenTelemetryTracingOptions().setOpenTelemetry(otel))) + .buildAsyncProducerClient()) { + + Span span = tracer.spanBuilder(spanName).startSpan(); + try (Scope scope = span.makeCurrent()) { + StepVerifier.create(producer.createBatch().flatMap(batch -> { + batch.tryAdd(new EventData("test event")); + return producer.send(batch); + })).expectComplete().verify(Duration.ofSeconds(60)); + } finally { + span.end(); + } } - assertTrue(exporterCountDown.await(5, TimeUnit.SECONDS)); + assertTrue(exporterCountDown.await(20, TimeUnit.SECONDS)); } @Disabled("Processor integration tests require separate consumer group to not have partition contention in CI - https://github.com/Azure/azure-sdk-for-java/issues/23567") diff --git a/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/test/java/com/azure/monitor/opentelemetry/autoconfigure/TokenCredentialUtil.java b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/test/java/com/azure/monitor/opentelemetry/autoconfigure/TokenCredentialUtil.java new file mode 100644 index 000000000000..f62e3c63854d --- /dev/null +++ b/sdk/monitor/azure-monitor-opentelemetry-autoconfigure/src/test/java/com/azure/monitor/opentelemetry/autoconfigure/TokenCredentialUtil.java @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.monitor.opentelemetry.autoconfigure; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.test.InterceptorManager; +import com.azure.core.test.utils.MockTokenCredential; +import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; +import com.azure.identity.AzurePipelinesCredentialBuilder; +import com.azure.identity.DefaultAzureCredentialBuilder; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; + +class TokenCredentialUtil { + + /** + * Gets a token credential for use in tests. + * @param interceptorManager the interceptor manager + * @return the TokenCredential + */ + static TokenCredential getTestTokenCredential(InterceptorManager interceptorManager) { + if (interceptorManager.isLiveMode()) { + return getPipelineCredential(); + } else if (interceptorManager.isRecordMode()) { + return new DefaultAzureCredentialBuilder().build(); + } else { + return new MockTokenCredential(); + } + } + + private static TokenCredential getPipelineCredential() { + final String serviceConnectionId = getPropertyValue("AZURESUBSCRIPTION_SERVICE_CONNECTION_ID"); + final String clientId = getPropertyValue("AZURESUBSCRIPTION_CLIENT_ID"); + final String tenantId = getPropertyValue("AZURESUBSCRIPTION_TENANT_ID"); + final String systemAccessToken = getPropertyValue("SYSTEM_ACCESSTOKEN"); + + if (CoreUtils.isNullOrEmpty(serviceConnectionId) + || CoreUtils.isNullOrEmpty(clientId) + || CoreUtils.isNullOrEmpty(tenantId) + || CoreUtils.isNullOrEmpty(systemAccessToken)) { + return null; + } + + TokenCredential cred = new AzurePipelinesCredentialBuilder().systemAccessToken(systemAccessToken) + .clientId(clientId) + .tenantId(tenantId) + .serviceConnectionId(serviceConnectionId) + .build(); + + return request -> Mono.defer(() -> cred.getToken(request)).subscribeOn(Schedulers.boundedElastic()); + } + + private static String getPropertyValue(String propertyName) { + return Configuration.getGlobalConfiguration().get(propertyName, System.getenv(propertyName)); + } +} diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md b/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md index 8e6801c48f7f..a3767c4c545e 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.0.0-beta.32 (Unreleased) +## 1.0.0-beta.33 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 1.0.0-beta.32 (2025-02-04) + +### Other Changes + +This package has been deprecated and will no longer be maintained. We encourage you to upgrade to the replacement package, `azure-monitor-opentelemetry-autoconfigure`, to continue receiving updates. +Refer to our deprecation policy (https://aka.ms/azsdk/support-policies) for more details. +Checkout the [Migration Guide](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/monitor/azure-monitor-opentelemetry-exporter/MIGRATION.md) for detailed instructions on how to update your application code from version 1.0.0-beta.x to the `azure-monitor-opentelemetry-autoconfigure` library. + ## 1.0.0-beta.31 (2024-10-23) ### Bugs Fixed diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/MIGRATION.md b/sdk/monitor/azure-monitor-opentelemetry-exporter/MIGRATION.md new file mode 100644 index 000000000000..177cc0e88232 --- /dev/null +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/MIGRATION.md @@ -0,0 +1,19 @@ +# Migrating to Azure Monitor OpenTelemetry SDK Autoconfigure Distro + +## Replace dependency + +Replace the `azure-monitor-opentelemetry-exporter` dependency by the following one + +```xml + + com.azure + azure-monitor-opentelemetry-autoconfigure + +``` + +## Update the Java code + +Replace: +* the `com.azure.monitor.opentelemetry.exporter.AzureMonitorExporter` class by `com.azure.monitor.opentelemetry.autoconfigure.AzureMonitorAutoConfigure` +* the `com.azure.monitor.opentelemetry.exporter.AzureMonitorExporterOptions` class by `com.azure.monitor.opentelemetry.autoconfigure.AzureMonitorAutoConfigureOptions` + diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/README.md b/sdk/monitor/azure-monitor-opentelemetry-exporter/README.md index 8471987c60c2..28d02d2c25be 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/README.md +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/README.md @@ -1,5 +1,12 @@ # Azure Monitor OpenTelemetry Exporter client library for Java +## Deprecation Notice + +> Please note, this package has been deprecated and will no longer be maintained. We encourage you to +> upgrade to the replacement package, `azure-monitor-opentelemetry-autoconfigure`, to continue receiving updates. +> Refer to our deprecation policy (https://aka.ms/azsdk/support-policies) for more details. +> Checkout the [Migration Guide](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/monitor/azure-monitor-opentelemetry-exporter/MIGRATION.md) for detailed instructions on how to update your application code from version 1.0.0-beta.x to the `azure-monitor-opentelemetry-autoconfigure` library. + This client library provides support for exporting OpenTelemetry data to Azure Monitor. This package assumes your application is already instrumented with the [OpenTelemetry SDK][opentelemetry_sdk] following the [OpenTelemetry Specification][opentelemetry_specification]. @@ -196,4 +203,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ [coc_contact]: mailto:opencode@microsoft.com -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%monitor%2Fazure-monitor-opentelemetry-exporter%2FREADME.png) + diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/pom.xml b/sdk/monitor/azure-monitor-opentelemetry-exporter/pom.xml index 102c2fc6a79d..6133396568d3 100644 --- a/sdk/monitor/azure-monitor-opentelemetry-exporter/pom.xml +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/pom.xml @@ -14,16 +14,22 @@ com.azure azure-monitor-opentelemetry-exporter - 1.0.0-beta.32 + 1.0.0-beta.33 Microsoft Azure SDK for OpenTelemetry Azure Monitor Exporter - This package contains Microsoft Azure SDK for OpenTelemetry Azure Monitor Exporter. + Please note, this package has been deprecated and will no longer be maintained. + We encourage you to upgrade to the replacement package, `azure-monitor-opentelemetry-autoconfigure`, to continue receiving updates. + Refer to our deprecation policy (https://aka.ms/azsdk/support-policies) for more details. azure-java-build-docs ${site.url}/site/${project.artifactId} + + com.azure + azure-monitor-opentelemetry-autoconfigure + @@ -36,6 +42,8 @@ --add-opens com.azure.monitor.opentelemetry.exporter/com.azure.monitor.opentelemetry.exporter=ALL-UNNAMED + --add-exports com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED + --add-reads com.azure.monitor.opentelemetry.autoconfigure=com.azure.core.tracing.opentelemetry checkstyle-suppressions.xml @@ -47,52 +55,52 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 io.opentelemetry opentelemetry-api - 1.43.0 + 1.43.0 io.opentelemetry opentelemetry-sdk - 1.43.0 + 1.43.0 io.opentelemetry opentelemetry-sdk-metrics - 1.43.0 + 1.43.0 io.opentelemetry opentelemetry-sdk-logs - 1.43.0 + 1.43.0 io.opentelemetry opentelemetry-sdk-extension-autoconfigure-spi - 1.43.0 + 1.43.0 io.opentelemetry opentelemetry-sdk-extension-autoconfigure - 1.43.0 + 1.43.0 io.opentelemetry.semconv opentelemetry-semconv-incubating - 1.26.0-alpha + 1.26.0-alpha + 1.43.0 test com.azure azure-data-appconfiguration - 1.7.3 + 1.7.4 test com.azure azure-messaging-eventhubs - 5.19.2 + 5.20.1 test com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.52 + 1.0.0-beta.56 test com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-messaging-eventhubs-checkpointstore-blob - 1.20.2 + 1.20.5 test com.azure azure-identity - 1.15.0 + 1.15.4 test @@ -198,13 +206,13 @@ - io.opentelemetry:opentelemetry-api:[1.43.0] - io.opentelemetry:opentelemetry-sdk:[1.43.0] - io.opentelemetry:opentelemetry-sdk-metrics:[1.43.0] - io.opentelemetry:opentelemetry-sdk-logs:[1.43.0] - io.opentelemetry:opentelemetry-sdk-extension-autoconfigure-spi:[1.43.0] - io.opentelemetry:opentelemetry-sdk-extension-autoconfigure:[1.43.0] - io.opentelemetry.semconv:opentelemetry-semconv-incubating:[1.26.0-alpha] + io.opentelemetry:opentelemetry-api:[1.43.0] + io.opentelemetry:opentelemetry-sdk:[1.43.0] + io.opentelemetry:opentelemetry-sdk-metrics:[1.43.0] + io.opentelemetry:opentelemetry-sdk-logs:[1.43.0] + io.opentelemetry:opentelemetry-sdk-extension-autoconfigure-spi:[1.43.0] + io.opentelemetry:opentelemetry-sdk-extension-autoconfigure:[1.43.0] + io.opentelemetry.semconv:opentelemetry-semconv-incubating:[1.26.0-alpha] com.squareup.okio:okio:[3.9.1] 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 34fe59104d31..c2a9eedc0779 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 @@ -3,6 +3,7 @@ package com.azure.monitor.opentelemetry.exporter; +import com.azure.core.credential.TokenCredential; import com.azure.core.http.HttpPipelineCallContext; import com.azure.core.http.HttpPipelineNextPolicy; import com.azure.core.http.HttpResponse; @@ -10,6 +11,7 @@ import com.azure.core.http.policy.HttpLogOptions; import com.azure.core.http.policy.HttpPipelinePolicy; import com.azure.core.test.annotation.LiveOnly; +import com.azure.core.util.Configuration; import com.azure.core.util.Context; import com.azure.core.util.FluxUtil; import com.azure.data.appconfiguration.ConfigurationClient; @@ -37,6 +39,15 @@ @LiveOnly public class AppConfigurationExporterIntegrationTest extends MonitorExporterClientTestBase { + + private TokenCredential credential; + + @Override + public void beforeTest() { + super.beforeTest(); + credential = TokenCredentialUtil.getTestTokenCredential(interceptorManager); + } + @Test public void setConfigurationTest() throws InterruptedException { CountDownLatch exporterCountDown = new CountDownLatch(1); @@ -87,8 +98,10 @@ public void testDisableTracing() throws InterruptedException { assertTrue(exporterCountDown.await(60, TimeUnit.SECONDS)); } - private static ConfigurationClient getConfigurationClient() { - return new ConfigurationClientBuilder().connectionString(System.getenv("AZURE_APPCONFIG_CONNECTION_STRING")) + private ConfigurationClient getConfigurationClient() { + String endPoint = Configuration.getGlobalConfiguration().get("AZURE_APPCONFIG_ENDPOINT"); + return new ConfigurationClientBuilder().credential(credential) + .endpoint(endPoint) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .buildClient(); } 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 bdb5f0381033..4cf3ffef7f1c 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 @@ -3,9 +3,18 @@ package com.azure.monitor.opentelemetry.exporter; +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.HttpPipelineCallContext; +import com.azure.core.http.HttpPipelineNextPolicy; +import com.azure.core.http.HttpPipelineNextSyncPolicy; +import com.azure.core.http.HttpResponse; import com.azure.core.http.policy.HttpPipelinePolicy; import com.azure.core.test.annotation.LiveOnly; +import com.azure.core.tracing.opentelemetry.OpenTelemetryTracingOptions; +import com.azure.core.util.ClientOptions; import com.azure.core.util.FluxUtil; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.Configuration; import com.azure.messaging.eventhubs.EventData; import com.azure.messaging.eventhubs.EventHubClientBuilder; import com.azure.messaging.eventhubs.EventHubProducerAsyncClient; @@ -14,17 +23,25 @@ import com.azure.messaging.eventhubs.LoadBalancingStrategy; import com.azure.messaging.eventhubs.checkpointstore.blob.BlobCheckpointStore; import com.azure.messaging.eventhubs.models.CreateBatchOptions; +import com.azure.monitor.opentelemetry.exporter.implementation.localstorage.LocalStorageTelemetryPipelineListener; +import com.azure.monitor.opentelemetry.exporter.implementation.models.MonitorDomain; +import com.azure.monitor.opentelemetry.exporter.implementation.models.RemoteDependencyData; +import com.azure.monitor.opentelemetry.exporter.implementation.models.TelemetryItem; import com.azure.monitor.opentelemetry.exporter.implementation.utils.TestUtils; import com.azure.storage.blob.BlobContainerAsyncClient; import com.azure.storage.blob.BlobContainerClientBuilder; +import io.opentelemetry.api.OpenTelemetry; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.context.Scope; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -37,38 +54,80 @@ public class EventHubsExporterIntegrationTest extends MonitorExporterClientTestB private static final String STORAGE_CONNECTION_STRING = System.getenv("STORAGE_CONNECTION_STRING"); private static final String CONTAINER_NAME = System.getenv("STORAGE_CONTAINER_NAME"); + private static final ClientLogger LOGGER = new ClientLogger(EventHubsExporterIntegrationTest.class); + + private TokenCredential credential; + + @Override + public void beforeTest() { + super.beforeTest(); + credential = TokenCredentialUtil.getTestTokenCredential(interceptorManager); + } + @Test + @SuppressWarnings("try") public void producerTest() throws InterruptedException { + String ehNamespace = Configuration.getGlobalConfiguration().get("AZURE_EVENTHUBS_FULLY_QUALIFIED_DOMAIN_NAME"); + String ehName = Configuration.getGlobalConfiguration().get("AZURE_EVENTHUBS_EVENT_HUB_NAME"); + CountDownLatch exporterCountDown = new CountDownLatch(2); String spanName = "event-hubs-producer-testing"; - HttpPipelinePolicy validationPolicy = (context, next) -> { - Mono asyncString = FluxUtil.collectBytesInByteBufferStream(context.getHttpRequest().getBody()) - .map(bytes -> new String(bytes, StandardCharsets.UTF_8)); - asyncString.subscribe(value -> { - if (value.contains(spanName)) { - exporterCountDown.countDown(); - } - if (value.contains("EventHubs.send")) { - exporterCountDown.countDown(); + HttpPipelinePolicy validationPolicy = new HttpPipelinePolicy() { + @Override + public Mono process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { + checkTelemetry(context); + return next.process(); + } + + @Override + public HttpResponse processSync(HttpPipelineCallContext context, HttpPipelineNextSyncPolicy next) { + checkTelemetry(context); + return next.processSync(); + } + + private void checkTelemetry(HttpPipelineCallContext context) { + byte[] asyncBytes = LocalStorageTelemetryPipelineListener + .ungzip(context.getHttpRequest().getBodyAsBinaryData().toBytes()); + List telemetryItems = TestUtils.deserialize(asyncBytes); + + for (TelemetryItem telemetryItem : telemetryItems) { + MonitorDomain monitorDomain = telemetryItem.getData().getBaseData(); + RemoteDependencyData remoteDependencyData = TestUtils.toRemoteDependencyData(monitorDomain); + String remoteDependencyName = remoteDependencyData.getName(); + if (remoteDependencyName.contains(spanName)) { + exporterCountDown.countDown(); + LOGGER.info("Count down " + spanName); + } else if (("send " + ehName).equals(remoteDependencyName)) { + exporterCountDown.countDown(); + LOGGER.info("Count down eventHubs send"); + } else { + LOGGER.info("remoteDependencyName = " + remoteDependencyName); + } } - }); - return next.process(); + } }; - Tracer tracer = TestUtils.createOpenTelemetrySdk(getHttpPipeline(validationPolicy)).getTracer("Sample"); - EventHubProducerAsyncClient producer - = new EventHubClientBuilder().connectionString(CONNECTION_STRING).buildAsyncProducerClient(); - Span span = tracer.spanBuilder(spanName).startSpan(); - Scope scope = span.makeCurrent(); - try { - producer.createBatch().flatMap(batch -> { - batch.tryAdd(new EventData("test event")); - return producer.send(batch); - }).subscribe(); - } finally { - span.end(); - scope.close(); + + OpenTelemetry otel = TestUtils.createOpenTelemetrySdk(getHttpPipeline(validationPolicy)); + Tracer tracer = otel.getTracer("Sample"); + + try (EventHubProducerAsyncClient producer = new EventHubClientBuilder().credential(credential) + .fullyQualifiedNamespace(ehNamespace) + .eventHubName(ehName) + .clientOptions( + new ClientOptions().setTracingOptions(new OpenTelemetryTracingOptions().setOpenTelemetry(otel))) + .buildAsyncProducerClient()) { + + Span span = tracer.spanBuilder(spanName).startSpan(); + try (Scope scope = span.makeCurrent()) { + StepVerifier.create(producer.createBatch().flatMap(batch -> { + batch.tryAdd(new EventData("test event")); + return producer.send(batch); + })).expectComplete().verify(Duration.ofSeconds(60)); + } finally { + span.end(); + } } - assertTrue(exporterCountDown.await(5, TimeUnit.SECONDS)); + assertTrue(exporterCountDown.await(20, TimeUnit.SECONDS)); } @Disabled("Processor integration tests require separate consumer group to not have partition contention in CI - https://github.com/Azure/azure-sdk-for-java/issues/23567") diff --git a/sdk/monitor/azure-monitor-opentelemetry-exporter/src/test/java/com/azure/monitor/opentelemetry/exporter/TokenCredentialUtil.java b/sdk/monitor/azure-monitor-opentelemetry-exporter/src/test/java/com/azure/monitor/opentelemetry/exporter/TokenCredentialUtil.java new file mode 100644 index 000000000000..c9a4c3c6450a --- /dev/null +++ b/sdk/monitor/azure-monitor-opentelemetry-exporter/src/test/java/com/azure/monitor/opentelemetry/exporter/TokenCredentialUtil.java @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.monitor.opentelemetry.exporter; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.test.InterceptorManager; +import com.azure.core.test.utils.MockTokenCredential; +import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; +import com.azure.identity.AzurePipelinesCredentialBuilder; +import com.azure.identity.DefaultAzureCredentialBuilder; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; + +class TokenCredentialUtil { + + /** + * Gets a token credential for use in tests. + * @param interceptorManager the interceptor manager + * @return the TokenCredential + */ + static TokenCredential getTestTokenCredential(InterceptorManager interceptorManager) { + if (interceptorManager.isLiveMode()) { + return getPipelineCredential(); + } else if (interceptorManager.isRecordMode()) { + return new DefaultAzureCredentialBuilder().build(); + } else { + return new MockTokenCredential(); + } + } + + private static TokenCredential getPipelineCredential() { + final String serviceConnectionId = getPropertyValue("AZURESUBSCRIPTION_SERVICE_CONNECTION_ID"); + final String clientId = getPropertyValue("AZURESUBSCRIPTION_CLIENT_ID"); + final String tenantId = getPropertyValue("AZURESUBSCRIPTION_TENANT_ID"); + final String systemAccessToken = getPropertyValue("SYSTEM_ACCESSTOKEN"); + + if (CoreUtils.isNullOrEmpty(serviceConnectionId) + || CoreUtils.isNullOrEmpty(clientId) + || CoreUtils.isNullOrEmpty(tenantId) + || CoreUtils.isNullOrEmpty(systemAccessToken)) { + return null; + } + + TokenCredential cred = new AzurePipelinesCredentialBuilder().systemAccessToken(systemAccessToken) + .clientId(clientId) + .tenantId(tenantId) + .serviceConnectionId(serviceConnectionId) + .build(); + + return request -> Mono.defer(() -> cred.getToken(request)).subscribeOn(Schedulers.boundedElastic()); + } + + private static String getPropertyValue(String propertyName) { + return Configuration.getGlobalConfiguration().get(propertyName, System.getenv(propertyName)); + } +} diff --git a/sdk/monitor/azure-monitor-query-perf/pom.xml b/sdk/monitor/azure-monitor-query-perf/pom.xml index 174b9251a4a3..cbc60928ff6a 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.15.0 + 1.15.4 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 diff --git a/sdk/monitor/azure-monitor-query/CHANGELOG.md b/sdk/monitor/azure-monitor-query/CHANGELOG.md index a756b9bf5f87..0a809f851db6 100644 --- a/sdk/monitor/azure-monitor-query/CHANGELOG.md +++ b/sdk/monitor/azure-monitor-query/CHANGELOG.md @@ -10,6 +10,29 @@ ### Other Changes +## 1.5.6 (2025-02-25) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core-http-netty` from `1.15.9` to version `1.15.10`. +- Upgraded `azure-core` from `1.55.1` to version `1.55.2`. + + +## 1.5.5 (2025-02-18) + +### Bugs Fixed + +- [Fixed an issue](https://github.com/Azure/azure-sdk-for-java/issues/43841) where `MetricsClient` and `MetricsAsyncClient` would return a null `resourceId` when querying resources. + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.54.1` to version `1.55.1`. +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.9`. + ## 1.5.4 (2024-12-04) diff --git a/sdk/monitor/azure-monitor-query/README.md b/sdk/monitor/azure-monitor-query/README.md index e3fc8e062177..a3caecb07899 100644 --- a/sdk/monitor/azure-monitor-query/README.md +++ b/sdk/monitor/azure-monitor-query/README.md @@ -66,7 +66,7 @@ If you want to take dependency on a particular version of the library that isn't com.azure azure-monitor-query - 1.5.0 + 1.6.0-beta.1 ``` @@ -87,7 +87,7 @@ To use the [DefaultAzureCredential][DefaultAzureCredential] provider shown below com.azure azure-identity - 1.14.2 + 1.15.3 ``` [//]: # ({x-version-update-end}) @@ -622,4 +622,4 @@ comments. [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ [coc_contact]: mailto:opencode@microsoft.com -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fmonitor%2Fazure-monitor-query%2FREADME.png) + diff --git a/sdk/monitor/azure-monitor-query/assets.json b/sdk/monitor/azure-monitor-query/assets.json index 2ce94e92a389..20d798b600b9 100644 --- a/sdk/monitor/azure-monitor-query/assets.json +++ b/sdk/monitor/azure-monitor-query/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "java", "TagPrefix": "java/monitor/azure-monitor-query", - "Tag": "java/monitor/azure-monitor-query_5a906fd788" + "Tag": "java/monitor/azure-monitor-query_dba737553b" } diff --git a/sdk/monitor/azure-monitor-query/migration-guide.md b/sdk/monitor/azure-monitor-query/migration-guide.md index 3ba79d57dac8..21d2811fd400 100644 --- a/sdk/monitor/azure-monitor-query/migration-guide.md +++ b/sdk/monitor/azure-monitor-query/migration-guide.md @@ -176,9 +176,9 @@ queryResultsMono.subscribe(queryResult -> { More examples can be found at [Azure Monitor Query samples][README-Samples]. -[LogsQueryClientBuilder]: https://azuresdkdocs.blob.core.windows.net/$web/java/azure-monitor-query/latest/com/azure/monitor/query/LogsQueryClientBuilder.html -[LogsQueryClient]: https://azuresdkdocs.blob.core.windows.net/$web/java/azure-monitor-query/latest/com/azure/monitor/query/LogsQueryClient.html -[LogsQueryAsyncClient]: https://azuresdkdocs.blob.core.windows.net/$web/java/azure-monitor-query/latest/com/azure/monitor/query/LogsQueryAsyncClient.html +[LogsQueryClientBuilder]: https://learn.microsoft.com/java/api/com.azure.monitor.query.logsqueryclientbuilder?view=azure-java-stable +[LogsQueryClient]: https://learn.microsoft.com/java/api/com.azure.monitor.query.logsqueryclient?view=azure-java-stable +[LogsQueryAsyncClient]: https://learn.microsoft.com/java/api/com.azure.monitor.query.logsqueryasyncclient?view=azure-java-stable [Guidelines]: https://azure.github.io/azure-sdk/general_introduction.html [GuidelinesJava]: https://azure.github.io/azure-sdk/java_introduction.html [GuidelinesJavaDesign]: https://azure.github.io/azure-sdk/java_introduction.html#namespaces @@ -187,4 +187,4 @@ More examples can be found at [Azure Monitor Query samples][README-Samples]. [README]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/monitor/azure-monitor-query/README.md [azure-identity-readme]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/identity/azure-identity/README.md -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fmonitor%2Fazure-monitor-query%2Fmigration-guide.png) + diff --git a/sdk/monitor/azure-monitor-query/pom.xml b/sdk/monitor/azure-monitor-query/pom.xml index 05755a859410..d31e6046100c 100644 --- a/sdk/monitor/azure-monitor-query/pom.xml +++ b/sdk/monitor/azure-monitor-query/pom.xml @@ -45,40 +45,40 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-core-serializer-json-jackson - 1.5.4 + 1.5.8 test com.azure azure-data-appconfiguration - 1.7.3 + 1.7.4 test diff --git a/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metrics/models/MetricsHelper.java b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metrics/models/MetricsHelper.java index 284f37fbe8f5..e4f4660db4ca 100644 --- a/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metrics/models/MetricsHelper.java +++ b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metrics/models/MetricsHelper.java @@ -34,6 +34,7 @@ public final class MetricsHelper { private static MetricDefinitionAccessor metricDefinitionAccessor; private static MetricAvailabilityAccessor metricAvailabilityAccessor; private static MetricNamespaceAccessor metricNamespaceAccessor; + private static MetricsQueryResultResourceIdAccessor metricsQueryResultResourceIdAccessor; /** * Accessor interface @@ -62,6 +63,13 @@ void setMetricNamespaceProperties(MetricNamespace metricNamespace, NamespaceClas String id, String name, String fullyQualifiedName, String type); } + /** + * Accessor interface + */ + public interface MetricsQueryResultResourceIdAccessor { + void setMetricsQueryResultResourceIdProperty(MetricsQueryResult metricsQueryResult, String resourceId); + } + /** * Sets the accessor instance. * @param metricDefinitionAccessor the accessor instance @@ -78,6 +86,15 @@ public static void setMetricNamespaceAccessor(MetricNamespaceAccessor metricName MetricsHelper.metricNamespaceAccessor = metricNamespaceAccessor; } + public static void setMetricsQueryResultAccessor(final MetricsQueryResultResourceIdAccessor accessor) { + MetricsHelper.metricsQueryResultResourceIdAccessor = accessor; + } + + public static void setMetricsQueryResultResourceIdProperty(MetricsQueryResult metricsQueryResult, + String resourceId) { + metricsQueryResultResourceIdAccessor.setMetricsQueryResultResourceIdProperty(metricsQueryResult, resourceId); + } + public static void setMetricDefinitionProperties(MetricDefinition metricDefinition, Boolean dimensionRequired, String resourceId, String namespace, String name, String displayDescription, String category, MetricClass metricClass, MetricUnit unit, AggregationType primaryAggregationType, @@ -213,6 +230,7 @@ public static MetricsQueryResult mapToMetricsQueryResult(MetricResultsResponseVa MetricsQueryResult metricsQueryResult = new MetricsQueryResult(null, QueryTimeInterval.parse(item.getStarttime() + "/" + item.getEndtime()), Duration.parse(item.getInterval()), item.getNamespace(), item.getResourceregion(), metrics); + setMetricsQueryResultResourceIdProperty(metricsQueryResult, item.getResourceid()); return metricsQueryResult; } diff --git a/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/models/MetricsQueryResult.java b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/models/MetricsQueryResult.java index 6902d74fd142..e8330351352c 100644 --- a/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/models/MetricsQueryResult.java +++ b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/models/MetricsQueryResult.java @@ -5,6 +5,7 @@ import com.azure.core.annotation.Immutable; import com.azure.core.util.CoreUtils; +import com.azure.monitor.query.implementation.metrics.models.MetricsHelper; import java.time.Duration; import java.util.List; @@ -25,6 +26,10 @@ public final class MetricsQueryResult { private String resourceId; + static { + MetricsHelper.setMetricsQueryResultAccessor(MetricsQueryResult::setResourceId); + } + /** * Creates an instance of the response to a metrics query. * @param cost the integer value representing the cost of the query, for data case. @@ -100,6 +105,10 @@ public String getResourceId() { return resourceId; } + private void setResourceId(String resourceId) { + this.resourceId = resourceId; + } + /** * Returns the metric result for the {@code metricName}. * diff --git a/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/LogsQueryAsyncClientTest.java b/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/LogsQueryAsyncClientTest.java index 9ff27eb3a309..b5c5beba76e9 100644 --- a/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/LogsQueryAsyncClientTest.java +++ b/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/LogsQueryAsyncClientTest.java @@ -6,9 +6,12 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.HttpClient; import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.policy.HttpLogOptions; import com.azure.core.test.TestMode; import com.azure.core.test.TestProxyTestBase; import com.azure.core.test.annotation.DoNotRecord; +import com.azure.core.test.annotation.LiveOnly; import com.azure.core.test.http.AssertingHttpClientBuilder; import com.azure.core.util.Context; import com.azure.core.util.serializer.TypeReference; @@ -38,6 +41,7 @@ import static com.azure.monitor.query.MonitorQueryTestUtils.getAdditionalLogWorkspaceId; import static com.azure.monitor.query.MonitorQueryTestUtils.getLogResourceId; import static com.azure.monitor.query.MonitorQueryTestUtils.getLogWorkspaceId; +import static com.azure.monitor.query.TestUtil.addTestProxySanitizersAndMatchers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; @@ -65,11 +69,14 @@ public void setup() { resourceId = getLogResourceId(interceptorManager.isPlaybackMode()); credential = TestUtil.getTestTokenCredential(interceptorManager); - LogsQueryClientBuilder clientBuilder = new LogsQueryClientBuilder().credential(credential); + LogsQueryClientBuilder clientBuilder = new LogsQueryClientBuilder().credential(credential) + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)); if (getTestMode() == TestMode.PLAYBACK) { + addTestProxySanitizersAndMatchers(interceptorManager); clientBuilder.httpClient(getAssertingHttpClient(interceptorManager.getPlaybackClient())); } else if (getTestMode() == TestMode.RECORD) { + addTestProxySanitizersAndMatchers(interceptorManager); clientBuilder.addPolicy(interceptorManager.getRecordPolicy()); } else if (getTestMode() == TestMode.LIVE) { clientBuilder.endpoint(MonitorQueryTestUtils.getLogEndpoint()); @@ -116,6 +123,7 @@ public void testLogsResourceQuery() { @Test @DoNotRecord(skipInPlayback = true) + @LiveOnly public void testLogsQueryAllowPartialSuccess() { // Arrange final String query = "let dt = datatable (DateTime: datetime, Bool:bool, Guid: guid, Int: " diff --git a/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/LogsQueryClientTest.java b/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/LogsQueryClientTest.java index 1f9a7462b09c..949b7de7b2e3 100644 --- a/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/LogsQueryClientTest.java +++ b/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/LogsQueryClientTest.java @@ -11,6 +11,7 @@ import com.azure.core.test.TestMode; import com.azure.core.test.TestProxyTestBase; import com.azure.core.test.annotation.DoNotRecord; +import com.azure.core.test.annotation.LiveOnly; import com.azure.core.test.http.AssertingHttpClientBuilder; import com.azure.core.util.BinaryData; import com.azure.core.util.Context; @@ -45,6 +46,7 @@ import static com.azure.monitor.query.MonitorQueryTestUtils.getAdditionalLogWorkspaceId; import static com.azure.monitor.query.MonitorQueryTestUtils.getLogResourceId; import static com.azure.monitor.query.MonitorQueryTestUtils.getLogWorkspaceId; +import static com.azure.monitor.query.TestUtil.addTestProxySanitizersAndMatchers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; @@ -73,10 +75,12 @@ public void setup() { credential = TestUtil.getTestTokenCredential(interceptorManager); LogsQueryClientBuilder clientBuilder = new LogsQueryClientBuilder().credential(credential); if (getTestMode() == TestMode.PLAYBACK) { + addTestProxySanitizersAndMatchers(interceptorManager); clientBuilder.httpClient(getAssertingHttpClient(interceptorManager.getPlaybackClient())); } else if (getTestMode() == TestMode.RECORD) { clientBuilder.addPolicy(interceptorManager.getRecordPolicy()); } else if (getTestMode() == TestMode.LIVE) { + addTestProxySanitizersAndMatchers(interceptorManager); clientBuilder.endpoint(MonitorQueryTestUtils.getLogEndpoint()); } @@ -114,6 +118,7 @@ public void testLogsQueryResource() { @Test @DoNotRecord(skipInPlayback = true) + @LiveOnly public void testLogsQueryAllowPartialSuccess() { // Arrange final String query = "let dt = datatable (DateTime: datetime, Bool:bool, Guid: guid, Int: " diff --git a/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/MetricsAsyncCientTest.java b/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/MetricsAsyncCientTest.java new file mode 100644 index 000000000000..b6b2b56cfffd --- /dev/null +++ b/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/MetricsAsyncCientTest.java @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.monitor.query; + +import com.azure.core.exception.HttpResponseException; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.policy.HttpLogOptions; +import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; +import com.azure.monitor.query.models.MetricResult; +import com.azure.monitor.query.models.MetricsQueryResourcesOptions; +import com.azure.monitor.query.models.QueryTimeInterval; +import org.junit.jupiter.api.Test; +import reactor.test.StepVerifier; + +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Arrays; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +public class MetricsAsyncCientTest extends MetricsClientTestBase { + + @Test + public void testMetricsAsyncBatchQuery() { + MetricsAsyncClient metricsClient + = clientBuilder.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) + .buildAsyncClient(); + String resourceId + = Configuration.getGlobalConfiguration().get("AZURE_MONITOR_METRICS_RESOURCE_URI_2", FAKE_RESOURCE_ID); + resourceId = resourceId.substring(resourceId.indexOf("/subscriptions")); + + try { + configClient.getConfigurationSetting("foo", "bar"); + } catch (HttpResponseException exception) { + // ignore as this is only to generate some metrics + } + + MetricsQueryResourcesOptions options = new MetricsQueryResourcesOptions().setGranularity(Duration.ofMinutes(15)) + .setTop(10) + .setTimeInterval(new QueryTimeInterval(OffsetDateTime.now().minusDays(1), OffsetDateTime.now())); + + String finalResourceId = resourceId; + StepVerifier.create(metricsClient + .queryResourcesWithResponse(Arrays.asList(resourceId), Arrays.asList("HttpIncomingRequestCount"), + "microsoft.appconfiguration/configurationstores", options) + .flatMapMany(metricsQueryResourcesResultResponse -> { + assertEquals(1, metricsQueryResourcesResultResponse.getValue().getMetricsQueryResults().size()); + assertEquals(1, metricsQueryResourcesResultResponse.getValue().getMetricsQueryResults().size()); + assertEquals(1, + metricsQueryResourcesResultResponse.getValue().getMetricsQueryResults().get(0).getMetrics().size()); + MetricResult metricResult = metricsQueryResourcesResultResponse.getValue() + .getMetricsQueryResults() + .get(0) + .getMetrics() + .get(0); + assertEquals("HttpIncomingRequestCount", metricResult.getMetricName()); + assertFalse(CoreUtils.isNullOrEmpty(metricResult.getTimeSeries())); + return metricsClient.queryResourcesWithResponse(Arrays.asList(finalResourceId), + Arrays.asList("HttpIncomingRequestCount"), "microsoft.appconfiguration/configurationstores", + options); + })).expectNextCount(1).verifyComplete(); + } + +} diff --git a/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/MetricsClientTest.java b/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/MetricsClientTest.java index 1c2e19d157b8..d34e7e7d9b81 100644 --- a/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/MetricsClientTest.java +++ b/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/MetricsClientTest.java @@ -52,6 +52,7 @@ public void testMetricsBatchQuery() { .getValue(); assertEquals(1, metricsQueryResults.getMetricsQueryResults().size()); assertEquals(1, metricsQueryResults.getMetricsQueryResults().get(0).getMetrics().size()); + assertNotNull(metricsQueryResults.getMetricsQueryResults().get(0).getResourceId()); MetricResult metricResult = metricsQueryResults.getMetricsQueryResults().get(0).getMetrics().get(0); assertEquals("HttpIncomingRequestCount", metricResult.getMetricName()); assertFalse(CoreUtils.isNullOrEmpty(metricResult.getTimeSeries())); diff --git a/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/MetricsClientTestBase.java b/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/MetricsClientTestBase.java index f8687a2c8717..a701354c6a44 100644 --- a/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/MetricsClientTestBase.java +++ b/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/MetricsClientTestBase.java @@ -6,12 +6,11 @@ import com.azure.core.credential.TokenCredential; 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; import com.azure.data.appconfiguration.ConfigurationClient; import com.azure.data.appconfiguration.ConfigurationClientBuilder; -import java.util.Arrays; +import static com.azure.monitor.query.TestUtil.addTestProxySanitizersAndMatchers; public class MetricsClientTestBase extends TestProxyTestBase { @@ -36,18 +35,12 @@ public void beforeTest() { = new ConfigurationClientBuilder().endpoint(appConfigEndpoint).credential(credential); if (getTestMode() == TestMode.PLAYBACK) { - interceptorManager.addMatchers( - new CustomMatcher().setIgnoredQueryParameters(Arrays.asList("starttime", "endtime", "api-version")) - .setComparingBodies(false) - .setExcludedHeaders(Arrays.asList("x-ms-content-sha256"))); + addTestProxySanitizersAndMatchers(interceptorManager); clientBuilder.httpClient(interceptorManager.getPlaybackClient()); configClientBuilder.httpClient(interceptorManager.getPlaybackClient()); } else if (getTestMode() == TestMode.RECORD) { - interceptorManager.addMatchers( - new CustomMatcher().setIgnoredQueryParameters(Arrays.asList("starttime", "endtime", "api-version")) - .setComparingBodies(false) - .setExcludedHeaders(Arrays.asList("x-ms-content-sha256"))); + addTestProxySanitizersAndMatchers(interceptorManager); clientBuilder.addPolicy(interceptorManager.getRecordPolicy()); configClientBuilder.addPolicy(interceptorManager.getRecordPolicy()); diff --git a/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/MetricsQueryAsyncClientTest.java b/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/MetricsQueryAsyncClientTest.java index 31b769711ade..5f6381fd9b6d 100644 --- a/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/MetricsQueryAsyncClientTest.java +++ b/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/MetricsQueryAsyncClientTest.java @@ -32,6 +32,7 @@ import java.util.stream.Stream; import static com.azure.monitor.query.MonitorQueryTestUtils.getMetricResourceUri; +import static com.azure.monitor.query.TestUtil.addTestProxySanitizersAndMatchers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -86,8 +87,10 @@ public void setup() { MetricsQueryClientBuilder clientBuilder = new MetricsQueryClientBuilder().credential(credential); if (getTestMode() == TestMode.PLAYBACK) { + addTestProxySanitizersAndMatchers(interceptorManager); clientBuilder.httpClient(getAssertingHttpClient(interceptorManager.getPlaybackClient())); } else if (getTestMode() == TestMode.RECORD) { + addTestProxySanitizersAndMatchers(interceptorManager); clientBuilder.addPolicy(interceptorManager.getRecordPolicy()); } else if (getTestMode() == TestMode.LIVE) { clientBuilder.endpoint(MonitorQueryTestUtils.getMetricEndpoint()); diff --git a/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/MetricsQueryClientTest.java b/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/MetricsQueryClientTest.java index 49f68ec59581..9edcd42611c0 100644 --- a/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/MetricsQueryClientTest.java +++ b/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/MetricsQueryClientTest.java @@ -34,6 +34,7 @@ import java.util.stream.Stream; import static com.azure.monitor.query.MonitorQueryTestUtils.getMetricResourceUri; +import static com.azure.monitor.query.TestUtil.addTestProxySanitizersAndMatchers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -87,8 +88,10 @@ public void setup() { MetricsQueryClientBuilder clientBuilder = new MetricsQueryClientBuilder().credential(credential); if (getTestMode() == TestMode.PLAYBACK) { + addTestProxySanitizersAndMatchers(interceptorManager); clientBuilder.httpClient(getAssertingHttpClient(interceptorManager.getPlaybackClient())); } else if (getTestMode() == TestMode.RECORD) { + addTestProxySanitizersAndMatchers(interceptorManager); clientBuilder.addPolicy(interceptorManager.getRecordPolicy()); } else if (getTestMode() == TestMode.LIVE) { clientBuilder.endpoint(MonitorQueryTestUtils.getMetricEndpoint()); diff --git a/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/MonitorQueryTestUtils.java b/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/MonitorQueryTestUtils.java index 07e1395ea8e9..08d69e21ee42 100644 --- a/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/MonitorQueryTestUtils.java +++ b/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/MonitorQueryTestUtils.java @@ -57,7 +57,7 @@ public static String getAdditionalLogWorkspaceId(boolean isPlaybackMode) { public static String getLogResourceId(boolean isPlaybackMode) { if (isPlaybackMode) { - return "/subscriptions/faa080af-c1d8-40ad-9cce-e1a450ca5b57/resourceGroups/rg-april1/providers/Microsoft.OperationalInsights/workspaces/april1-azmonitorlogsws"; + return "/subscriptions/faa080af-c1d8-40ad-9cce-e1a450ca5b57/resourceGroups/rg/providers/Microsoft.OperationalInsights/workspaces/azmonitorlogsws"; } else { return LOG_RESOURCE_ID.substring(LOG_RESOURCE_ID.indexOf("/subscriptions")); } @@ -65,7 +65,7 @@ public static String getLogResourceId(boolean isPlaybackMode) { public static String getMetricResourceUri(boolean isPlaybackMode) { if (isPlaybackMode) { - return "/subscriptions/faa080af-c1d8-40ad-9cce-e1a450ca5b57/resourceGroups/rg-april1/providers/Microsoft.Eventhub/Namespaces/eventhubapril1"; + return "/subscriptions/faa080af-c1d8-40ad-9cce-e1a450ca5b57/resourceGroups/rg/providers/Microsoft.Eventhub/Namespaces/eventhub"; } else { return METRIC_RESOURCE_URI.substring(METRIC_RESOURCE_URI.indexOf("/subscriptions")); } diff --git a/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/TestUtil.java b/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/TestUtil.java index 50ec12324fdc..d4e1cbe756fc 100644 --- a/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/TestUtil.java +++ b/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/TestUtil.java @@ -5,11 +5,16 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.test.InterceptorManager; +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.identity.AzurePipelinesCredentialBuilder; import com.azure.identity.DefaultAzureCredentialBuilder; +import java.util.Arrays; + /** * Utility class for tests. */ @@ -40,4 +45,16 @@ public static TokenCredential getTestTokenCredential(InterceptorManager intercep return new MockTokenCredential(); } } + + public static void addTestProxySanitizersAndMatchers(InterceptorManager interceptorManager) { + interceptorManager.addSanitizers( + new TestProxySanitizer("resourceGroups\\/.*?\\/", "resourceGroups/REDACTED/", TestProxySanitizerType.URL), + new TestProxySanitizer("Namespaces\\/.*\\/providers", "Namespaces/REDACTED/providers", + TestProxySanitizerType.URL), + new TestProxySanitizer("workspaces\\/.*?\\/", "workspaces/REDACTED/", TestProxySanitizerType.URL)); + interceptorManager.addMatchers( + new CustomMatcher().setIgnoredQueryParameters(Arrays.asList("starttime", "endtime", "api-version")) + .setComparingBodies(false) + .setExcludedHeaders(Arrays.asList("x-ms-content-sha256"))); + } } diff --git a/sdk/monitor/test-resources.json b/sdk/monitor/test-resources.json index 7fb466a88efe..17a96a4f04c3 100644 --- a/sdk/monitor/test-resources.json +++ b/sdk/monitor/test-resources.json @@ -41,9 +41,12 @@ "type": "string", "defaultValue": "javaeventhub" }, - "eventHubNamespaceHostNameSuffix": { + "serviceBusEndpointSuffix": { "type": "string", - "defaultValue": "servicebus.windows.net" + "defaultValue": ".servicebus.windows.net", + "metadata": { + "description": "The url suffix to use when creating eventhubs connection strings." + } }, "location": { "type": "string", @@ -334,7 +337,7 @@ }, "AZURE_EVENTHUBS_FULLY_QUALIFIED_DOMAIN_NAME": { "type": "string", - "value": "[concat(variables('eventHubsNamespaceName'), '.', parameters('eventHubNamespaceHostNameSuffix'))]" + "value": "[concat(variables('eventHubsNamespaceName'), parameters('serviceBusEndpointSuffix'))]" }, "AZURE_MONITOR_DCE": { "type": "string", diff --git a/sdk/mysql/azure-resourcemanager-mysql/README.md b/sdk/mysql/azure-resourcemanager-mysql/README.md index 2a2d8d4e022f..6d06bb4df2c8 100644 --- a/sdk/mysql/azure-resourcemanager-mysql/README.md +++ b/sdk/mysql/azure-resourcemanager-mysql/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-mysql - 1.0.2 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/mysql/azure-resourcemanager-mysql/pom.xml b/sdk/mysql/azure-resourcemanager-mysql/pom.xml index 90d708a0ec65..15bd95786cd9 100644 --- a/sdk/mysql/azure-resourcemanager-mysql/pom.xml +++ b/sdk/mysql/azure-resourcemanager-mysql/pom.xml @@ -46,29 +46,29 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/mysqlflexibleserver/azure-resourcemanager-mysqlflexibleserver/README.md b/sdk/mysqlflexibleserver/azure-resourcemanager-mysqlflexibleserver/README.md index f1443068026f..7a84c8f37c98 100644 --- a/sdk/mysqlflexibleserver/azure-resourcemanager-mysqlflexibleserver/README.md +++ b/sdk/mysqlflexibleserver/azure-resourcemanager-mysqlflexibleserver/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-mysqlflexibleserver - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -110,4 +110,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fmysqlflexibleserver%2Fazure-resourcemanager-mysqlflexibleserver%2FREADME.png) + diff --git a/sdk/mysqlflexibleserver/azure-resourcemanager-mysqlflexibleserver/pom.xml b/sdk/mysqlflexibleserver/azure-resourcemanager-mysqlflexibleserver/pom.xml index 1f8f72515938..8dabaa9eefdf 100644 --- a/sdk/mysqlflexibleserver/azure-resourcemanager-mysqlflexibleserver/pom.xml +++ b/sdk/mysqlflexibleserver/azure-resourcemanager-mysqlflexibleserver/pom.xml @@ -51,29 +51,29 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/neonpostgres/azure-resourcemanager-neonpostgres/README.md b/sdk/neonpostgres/azure-resourcemanager-neonpostgres/README.md index 5554c2920801..ac4ccf6ce4e4 100644 --- a/sdk/neonpostgres/azure-resourcemanager-neonpostgres/README.md +++ b/sdk/neonpostgres/azure-resourcemanager-neonpostgres/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-neonpostgres - 1.0.0-beta.1 + 1.0.0-beta.2 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fneonpostgres%2Fazure-resourcemanager-neonpostgres%2FREADME.png) + diff --git a/sdk/neonpostgres/azure-resourcemanager-neonpostgres/pom.xml b/sdk/neonpostgres/azure-resourcemanager-neonpostgres/pom.xml index 98561019ce54..13745497a046 100644 --- a/sdk/neonpostgres/azure-resourcemanager-neonpostgres/pom.xml +++ b/sdk/neonpostgres/azure-resourcemanager-neonpostgres/pom.xml @@ -52,23 +52,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/neonpostgres/azure-resourcemanager-neonpostgres/src/main/java/com/azure/resourcemanager/neonpostgres/NeonPostgresManager.java b/sdk/neonpostgres/azure-resourcemanager-neonpostgres/src/main/java/com/azure/resourcemanager/neonpostgres/NeonPostgresManager.java index 5e28a6879755..4a4752f2f209 100644 --- a/sdk/neonpostgres/azure-resourcemanager-neonpostgres/src/main/java/com/azure/resourcemanager/neonpostgres/NeonPostgresManager.java +++ b/sdk/neonpostgres/azure-resourcemanager-neonpostgres/src/main/java/com/azure/resourcemanager/neonpostgres/NeonPostgresManager.java @@ -22,6 +22,7 @@ import com.azure.core.http.policy.UserAgentPolicy; import com.azure.core.management.profile.AzureProfile; import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.neonpostgres.fluent.NeonPostgresManagementClient; import com.azure.resourcemanager.neonpostgres.implementation.NeonPostgresManagementClientBuilder; @@ -33,6 +34,7 @@ import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; @@ -96,6 +98,9 @@ public static Configurable configure() { */ public static final class Configurable { private static final ClientLogger LOGGER = new ClientLogger(Configurable.class); + private static final String SDK_VERSION = "version"; + private static final Map PROPERTIES + = CoreUtils.getProperties("azure-resourcemanager-neonpostgres.properties"); private HttpClient httpClient; private HttpLogOptions httpLogOptions; @@ -203,12 +208,14 @@ public NeonPostgresManager authenticate(TokenCredential credential, AzureProfile Objects.requireNonNull(credential, "'credential' cannot be null."); Objects.requireNonNull(profile, "'profile' cannot be null."); + String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); + StringBuilder userAgentBuilder = new StringBuilder(); userAgentBuilder.append("azsdk-java") .append("-") .append("com.azure.resourcemanager.neonpostgres") .append("/") - .append("1.0.0-beta.1"); + .append(clientVersion); if (!Configuration.getGlobalConfiguration().get("AZURE_TELEMETRY_DISABLED", false)) { userAgentBuilder.append(" (") .append(Configuration.getGlobalConfiguration().get("java.version")) diff --git a/sdk/neonpostgres/azure-resourcemanager-neonpostgres/src/main/resources/azure-resourcemanager-neonpostgres.properties b/sdk/neonpostgres/azure-resourcemanager-neonpostgres/src/main/resources/azure-resourcemanager-neonpostgres.properties new file mode 100644 index 000000000000..defbd48204e4 --- /dev/null +++ b/sdk/neonpostgres/azure-resourcemanager-neonpostgres/src/main/resources/azure-resourcemanager-neonpostgres.properties @@ -0,0 +1 @@ +version=${project.version} diff --git a/sdk/netapp/azure-resourcemanager-netapp/CHANGELOG.md b/sdk/netapp/azure-resourcemanager-netapp/CHANGELOG.md index b5d5fee2e0e8..a72e1781e60f 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/CHANGELOG.md +++ b/sdk/netapp/azure-resourcemanager-netapp/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.6.0-beta.2 (Unreleased) +## 1.7.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,62 @@ ### Other Changes +## 1.6.0 (2025-02-21) + +- Azure Resource Manager NetAppFiles client library for Java. This package contains Microsoft Azure SDK for NetAppFiles Management SDK. Microsoft NetApp Files Azure Resource Provider specification. Package tag package-2024-09-01. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). + +### Features Added + +* `models.CoolAccessTieringPolicy` was added + +* `models.EncryptionTransitionRequest` was added + +* `models.KeyVaultPrivateEndpoint` was added + +* `models.GetKeyVaultStatusResponse` was added + +* `models.ChangeKeyVault` was added + +#### `models.Volume` was modified + +* `coolAccessTieringPolicy()` was added + +#### `models.Volume$Update` was modified + +* `withCoolAccessTieringPolicy(models.CoolAccessTieringPolicy)` was added + +#### `models.VolumePatch` was modified + +* `withCoolAccessTieringPolicy(models.CoolAccessTieringPolicy)` was added +* `coolAccessTieringPolicy()` was added + +#### `models.Volume$Definition` was modified + +* `withCoolAccessTieringPolicy(models.CoolAccessTieringPolicy)` was added + +#### `models.VolumeGroupVolumeProperties` was modified + +* `coolAccessTieringPolicy()` was added +* `withCoolAccessTieringPolicy(models.CoolAccessTieringPolicy)` was added + +#### `models.Accounts` was modified + +* `transitionToCmk(java.lang.String,java.lang.String,models.EncryptionTransitionRequest,com.azure.core.util.Context)` was added +* `transitionToCmk(java.lang.String,java.lang.String)` was added +* `getChangeKeyVaultInformation(java.lang.String,java.lang.String)` was added +* `changeKeyVault(java.lang.String,java.lang.String,models.ChangeKeyVault,com.azure.core.util.Context)` was added +* `changeKeyVault(java.lang.String,java.lang.String)` was added +* `getChangeKeyVaultInformation(java.lang.String,java.lang.String,com.azure.core.util.Context)` was added + +#### `models.NetAppAccount` was modified + +* `changeKeyVault(models.ChangeKeyVault,com.azure.core.util.Context)` was added +* `transitionToCmk()` was added +* `changeKeyVault()` was added +* `getChangeKeyVaultInformation(com.azure.core.util.Context)` was added +* `transitionToCmk(models.EncryptionTransitionRequest,com.azure.core.util.Context)` was added +* `getChangeKeyVaultInformation()` was added + ## 1.6.0-beta.1 (2024-11-18) - Azure Resource Manager NetAppFiles client library for Java. This package contains Microsoft Azure SDK for NetAppFiles Management SDK. Microsoft NetApp Files Azure Resource Provider specification. Package tag package-preview-2024-07-01-preview. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). diff --git a/sdk/netapp/azure-resourcemanager-netapp/README.md b/sdk/netapp/azure-resourcemanager-netapp/README.md index b7e8c1e15b95..6c2d493a72b2 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/README.md +++ b/sdk/netapp/azure-resourcemanager-netapp/README.md @@ -2,7 +2,7 @@ Azure Resource Manager NetAppFiles client library for Java. -This package contains Microsoft Azure SDK for NetAppFiles Management SDK. Microsoft NetApp Files Azure Resource Provider specification. Package tag package-preview-2024-07-01-preview. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). +This package contains Microsoft Azure SDK for NetAppFiles Management SDK. Microsoft NetApp Files Azure Resource Provider specification. Package tag package-2024-09-01. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). ## We'd love to hear your feedback @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-netapp - 1.6.0-beta.1 + 1.7.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -52,7 +52,7 @@ Azure subscription ID can be configured via `AZURE_SUBSCRIPTION_ID` environment Assuming the use of the `DefaultAzureCredential` credential class, the client can be authenticated using the following code: ```java -AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); +AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); @@ -60,7 +60,7 @@ NetAppFilesManager manager = NetAppFilesManager .authenticate(credential, profile); ``` -The sample code assumes global Azure. Please change `AzureEnvironment.AZURE` variable if otherwise. +The sample code assumes global Azure. Please change the `AzureCloud.AZURE_PUBLIC_CLOUD` variable if otherwise. See [Authentication][authenticate] for more options. @@ -107,5 +107,3 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [cg]: https://github.com/Azure/azure-sdk-for-java/blob/main/CONTRIBUTING.md [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ - -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fnetapp%2Fazure-resourcemanager-netapp%2FREADME.png) diff --git a/sdk/netapp/azure-resourcemanager-netapp/SAMPLE.md b/sdk/netapp/azure-resourcemanager-netapp/SAMPLE.md index 5a482ead1452..f1fb41340c0a 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/SAMPLE.md +++ b/sdk/netapp/azure-resourcemanager-netapp/SAMPLE.md @@ -139,7 +139,6 @@ - [Get](#volumes_get) - [List](#volumes_list) - [ListGetGroupIdListForLdapUser](#volumes_listgetgroupidlistforldapuser) -- [ListQuotaReport](#volumes_listquotareport) - [ListReplications](#volumes_listreplications) - [PeerExternalCluster](#volumes_peerexternalcluster) - [PerformReplicationTransfer](#volumes_performreplicationtransfer) @@ -153,7 +152,6 @@ - [ResyncReplication](#volumes_resyncreplication) - [Revert](#volumes_revert) - [RevertRelocation](#volumes_revertrelocation) -- [SplitCloneFromParent](#volumes_splitclonefromparent) - [Update](#volumes_update) ### Accounts_ChangeKeyVault @@ -167,8 +165,8 @@ import java.util.Arrays; */ public final class AccountsChangeKeyVaultSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Accounts_ChangeKeyVault.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Accounts_ChangeKeyVault.json */ /** * Sample code: Accounts_ChangeKeyVault. @@ -200,8 +198,8 @@ import java.util.Arrays; */ public final class AccountsCreateOrUpdateSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Accounts_CreateOrUpdate.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Accounts_CreateOrUpdate.json */ /** * Sample code: Accounts_CreateOrUpdate. @@ -213,8 +211,8 @@ public final class AccountsCreateOrUpdateSamples { } /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Accounts_CreateOrUpdateAD.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Accounts_CreateOrUpdateAD.json */ /** * Sample code: Accounts_CreateOrUpdateWithActiveDirectory. @@ -251,7 +249,7 @@ public final class AccountsCreateOrUpdateSamples { public final class AccountsDeleteSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Accounts_Delete.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Accounts_Delete.json */ /** * Sample code: Accounts_Delete. @@ -273,7 +271,7 @@ public final class AccountsDeleteSamples { public final class AccountsGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Accounts_Get.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Accounts_Get.json */ /** * Sample code: Accounts_Get. @@ -294,7 +292,7 @@ public final class AccountsGetByResourceGroupSamples { */ public final class AccountsGetChangeKeyVaultInformationSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ + * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/ * Accounts_GetChangeKeyVaultInformation.json */ /** @@ -318,7 +316,7 @@ public final class AccountsGetChangeKeyVaultInformationSamples { public final class AccountsListSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Accounts_List.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Accounts_List.json */ /** * Sample code: Accounts_List. @@ -340,7 +338,7 @@ public final class AccountsListSamples { public final class AccountsListByResourceGroupSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Accounts_List.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Accounts_List.json */ /** * Sample code: Accounts_List. @@ -361,8 +359,8 @@ public final class AccountsListByResourceGroupSamples { */ public final class AccountsRenewCredentialsSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Accounts_RenewCredentials.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Accounts_RenewCredentials.json */ /** * Sample code: Accounts_RenewCredentials. @@ -385,7 +383,7 @@ import com.azure.resourcemanager.netapp.models.EncryptionTransitionRequest; */ public final class AccountsTransitionToCmkSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ + * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/ * Accounts_TransitionEncryptionKey.json */ /** @@ -417,7 +415,7 @@ import java.util.Map; public final class AccountsUpdateSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Accounts_Update.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Accounts_Update.json */ /** * Sample code: Accounts_Update. @@ -454,8 +452,7 @@ public final class AccountsUpdateSamples { public final class BackupPoliciesCreateSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/BackupPolicies_Create. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupPolicies_Create.json */ /** * Sample code: BackupPolicies_Create. @@ -485,8 +482,7 @@ public final class BackupPoliciesCreateSamples { public final class BackupPoliciesDeleteSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/BackupPolicies_Delete. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupPolicies_Delete.json */ /** * Sample code: BackupPolicies_Delete. @@ -509,8 +505,7 @@ public final class BackupPoliciesDeleteSamples { public final class BackupPoliciesGetSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/BackupPolicies_Get. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupPolicies_Get.json */ /** * Sample code: Backups_Get. @@ -533,8 +528,7 @@ public final class BackupPoliciesGetSamples { public final class BackupPoliciesListSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/BackupPolicies_List. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupPolicies_List.json */ /** * Sample code: BackupPolicies_List. @@ -558,8 +552,7 @@ import com.azure.resourcemanager.netapp.models.BackupPolicy; public final class BackupPoliciesUpdateSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/BackupPolicies_Update. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupPolicies_Update.json */ /** * Sample code: BackupPolicies_Update. @@ -589,8 +582,7 @@ public final class BackupPoliciesUpdateSamples { public final class BackupVaultsCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/BackupVaults_Create. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupVaults_Create.json */ /** * Sample code: BackupVault_CreateOrUpdate. @@ -616,8 +608,7 @@ public final class BackupVaultsCreateOrUpdateSamples { public final class BackupVaultsDeleteSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/BackupVaults_Delete. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupVaults_Delete.json */ /** * Sample code: BackupVaults_Delete. @@ -639,7 +630,7 @@ public final class BackupVaultsDeleteSamples { public final class BackupVaultsGetSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/BackupVaults_Get.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupVaults_Get.json */ /** * Sample code: BackupVaults_Get. @@ -661,7 +652,7 @@ public final class BackupVaultsGetSamples { public final class BackupVaultsListByNetAppAccountSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/BackupVaults_List.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupVaults_List.json */ /** * Sample code: BackupVaults_List. @@ -687,8 +678,7 @@ import java.util.Map; public final class BackupVaultsUpdateSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/BackupVaults_Update. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupVaults_Update.json */ /** * Sample code: BackupVaults_Update. @@ -724,8 +714,9 @@ public final class BackupVaultsUpdateSamples { */ public final class BackupsCreateSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * BackupsUnderBackupVault_Create.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupsUnderBackupVault_Create. + * json */ /** * Sample code: BackupsUnderBackupVault_Create. @@ -752,8 +743,9 @@ public final class BackupsCreateSamples { */ public final class BackupsDeleteSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * BackupsUnderBackupVault_Delete.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupsUnderBackupVault_Delete. + * json */ /** * Sample code: BackupsUnderBackupVault_Delete. @@ -775,8 +767,9 @@ public final class BackupsDeleteSamples { */ public final class BackupsGetSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * BackupsUnderBackupVault_Get.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupsUnderBackupVault_Get. + * json */ /** * Sample code: BackupsUnderBackupVault_Get. @@ -798,8 +791,8 @@ public final class BackupsGetSamples { */ public final class BackupsGetLatestStatusSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_LatestBackupStatus.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_LatestBackupStatus.json */ /** * Sample code: Volumes_BackupStatus. @@ -821,8 +814,9 @@ public final class BackupsGetLatestStatusSamples { */ public final class BackupsGetVolumeLatestRestoreStatusSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_LatestRestoreStatus.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_LatestRestoreStatus. + * json */ /** * Sample code: Volumes_RestoreStatus. @@ -845,8 +839,9 @@ public final class BackupsGetVolumeLatestRestoreStatusSamples { */ public final class BackupsListByVaultSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * BackupsUnderBackupVault_List.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupsUnderBackupVault_List. + * json */ /** * Sample code: Backups_List. @@ -869,8 +864,9 @@ import com.azure.resourcemanager.netapp.models.Backup; */ public final class BackupsUpdateSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * BackupsUnderBackupVault_Update.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupsUnderBackupVault_Update. + * json */ /** * Sample code: BackupsUnderBackupVault_Update. @@ -896,8 +892,9 @@ import com.azure.resourcemanager.netapp.models.BackupsMigrationRequest; */ public final class BackupsUnderAccountMigrateBackupsSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * BackupsUnderAccount_Migrate.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupsUnderAccount_Migrate. + * json */ /** * Sample code: BackupsUnderAccount_Migrate. @@ -924,7 +921,7 @@ import java.util.Arrays; */ public final class BackupsUnderBackupVaultRestoreFilesSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ + * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/ * BackupsUnderBackupVault_SingleFileRestore.json */ /** @@ -953,8 +950,8 @@ import com.azure.resourcemanager.netapp.models.BackupsMigrationRequest; */ public final class BackupsUnderVolumeMigrateBackupsSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * BackupsUnderVolume_Migrate.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupsUnderVolume_Migrate.json */ /** * Sample code: BackupsUnderVolume_Migrate. @@ -980,8 +977,8 @@ import com.azure.resourcemanager.netapp.models.FilePathAvailabilityRequest; */ public final class NetAppResourceCheckFilePathAvailabilitySamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * CheckFilePathAvailability.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/CheckFilePathAvailability.json */ /** * Sample code: CheckFilePathAvailability. @@ -1011,8 +1008,7 @@ import com.azure.resourcemanager.netapp.models.ResourceNameAvailabilityRequest; public final class NetAppResourceCheckNameAvailabilitySamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/CheckNameAvailability. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/CheckNameAvailability.json */ /** * Sample code: CheckNameAvailability. @@ -1042,8 +1038,7 @@ import com.azure.resourcemanager.netapp.models.QuotaAvailabilityRequest; public final class NetAppResourceCheckQuotaAvailabilitySamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/CheckQuotaAvailability - * .json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/CheckQuotaAvailability.json */ /** * Sample code: CheckQuotaAvailability. @@ -1071,8 +1066,8 @@ import com.azure.resourcemanager.netapp.models.QueryNetworkSiblingSetRequest; */ public final class NetAppResourceQueryNetworkSiblingSetSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * NetworkSiblingSet_Query.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/NetworkSiblingSet_Query.json */ /** * Sample code: NetworkSiblingSet_Query. @@ -1099,7 +1094,7 @@ public final class NetAppResourceQueryNetworkSiblingSetSamples { public final class NetAppResourceQueryRegionInfoSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/RegionInfo.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/RegionInfo.json */ /** * Sample code: RegionInfo_Query. @@ -1123,8 +1118,8 @@ import com.azure.resourcemanager.netapp.models.UpdateNetworkSiblingSetRequest; */ public final class NetAppResourceUpdateNetworkSiblingSetSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * NetworkSiblingSet_Update.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/NetworkSiblingSet_Update.json */ /** * Sample code: NetworkFeatures_Update. @@ -1152,7 +1147,7 @@ public final class NetAppResourceUpdateNetworkSiblingSetSamples { public final class NetAppResourceQuotaLimitsGetSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/QuotaLimits_Get.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/QuotaLimits_Get.json */ /** * Sample code: QuotaLimits. @@ -1175,7 +1170,7 @@ public final class NetAppResourceQuotaLimitsGetSamples { public final class NetAppResourceQuotaLimitsListSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/QuotaLimits_List.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/QuotaLimits_List.json */ /** * Sample code: QuotaLimits. @@ -1197,7 +1192,7 @@ public final class NetAppResourceQuotaLimitsListSamples { public final class NetAppResourceRegionInfosGetSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/RegionInfos_Get.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/RegionInfos_Get.json */ /** * Sample code: RegionInfos_Get. @@ -1219,7 +1214,7 @@ public final class NetAppResourceRegionInfosGetSamples { public final class NetAppResourceRegionInfosListSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/RegionInfos_List.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/RegionInfos_List.json */ /** * Sample code: RegionInfos_List. @@ -1241,7 +1236,7 @@ public final class NetAppResourceRegionInfosListSamples { public final class OperationsListSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/OperationList.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/OperationList.json */ /** * Sample code: OperationList. @@ -1266,8 +1261,7 @@ import com.azure.resourcemanager.netapp.models.ServiceLevel; public final class PoolsCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Pools_CreateOrUpdate. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Pools_CreateOrUpdate.json */ /** * Sample code: Pools_CreateOrUpdate. @@ -1284,28 +1278,6 @@ public final class PoolsCreateOrUpdateSamples { .withQosType(QosType.AUTO) .create(); } - - /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Pools_CreateOrUpdate_CustomThroughput.json - */ - /** - * Sample code: Pools_CreateOrUpdate_CustomThroughput. - * - * @param manager Entry point to NetAppFilesManager. - */ - public static void - poolsCreateOrUpdateCustomThroughput(com.azure.resourcemanager.netapp.NetAppFilesManager manager) { - manager.pools() - .define("customPool1") - .withRegion("eastus") - .withExistingNetAppAccount("myRG", "account1") - .withSize(4398046511104L) - .withServiceLevel(ServiceLevel.FLEXIBLE) - .withCustomThroughputMibps(128.0F) - .withQosType(QosType.MANUAL) - .create(); - } } ``` @@ -1318,7 +1290,7 @@ public final class PoolsCreateOrUpdateSamples { public final class PoolsDeleteSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Pools_Delete.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Pools_Delete.json */ /** * Sample code: Pools_Delete. @@ -1338,22 +1310,9 @@ public final class PoolsDeleteSamples { * Samples for Pools Get. */ public final class PoolsGetSamples { - /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Pools_Get_CustomThroughput.json - */ - /** - * Sample code: Pools_Get_CustomThroughput. - * - * @param manager Entry point to NetAppFilesManager. - */ - public static void poolsGetCustomThroughput(com.azure.resourcemanager.netapp.NetAppFilesManager manager) { - manager.pools().getWithResponse("myRG", "account1", "customPool1", com.azure.core.util.Context.NONE); - } - /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Pools_Get.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Pools_Get.json */ /** * Sample code: Pools_Get. @@ -1375,7 +1334,7 @@ public final class PoolsGetSamples { public final class PoolsListSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Pools_List.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Pools_List.json */ /** * Sample code: Pools_List. @@ -1399,7 +1358,7 @@ import com.azure.resourcemanager.netapp.models.CapacityPool; public final class PoolsUpdateSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Pools_Update.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Pools_Update.json */ /** * Sample code: Pools_Update. @@ -1411,22 +1370,6 @@ public final class PoolsUpdateSamples { = manager.pools().getWithResponse("myRG", "account1", "pool1", com.azure.core.util.Context.NONE).getValue(); resource.update().apply(); } - - /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Pools_Update_CustomThroughput.json - */ - /** - * Sample code: Pools_Update_CustomThroughput. - * - * @param manager Entry point to NetAppFilesManager. - */ - public static void poolsUpdateCustomThroughput(com.azure.resourcemanager.netapp.NetAppFilesManager manager) { - CapacityPool resource = manager.pools() - .getWithResponse("myRG", "account1", "customPool1", com.azure.core.util.Context.NONE) - .getValue(); - resource.update().apply(); - } } ``` @@ -1443,8 +1386,8 @@ import com.azure.resourcemanager.netapp.models.WeeklySchedule; */ public final class SnapshotPoliciesCreateSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * SnapshotPolicies_Create.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/SnapshotPolicies_Create.json */ /** * Sample code: SnapshotPolicies_Create. @@ -1476,8 +1419,8 @@ public final class SnapshotPoliciesCreateSamples { */ public final class SnapshotPoliciesDeleteSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * SnapshotPolicies_Delete.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/SnapshotPolicies_Delete.json */ /** * Sample code: SnapshotPolicies_Delete. @@ -1500,8 +1443,7 @@ public final class SnapshotPoliciesDeleteSamples { public final class SnapshotPoliciesGetSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/SnapshotPolicies_Get. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/SnapshotPolicies_Get.json */ /** * Sample code: SnapshotPolicies_Get. @@ -1524,8 +1466,7 @@ public final class SnapshotPoliciesGetSamples { public final class SnapshotPoliciesListSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/SnapshotPolicies_List. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/SnapshotPolicies_List.json */ /** * Sample code: SnapshotPolicies_List. @@ -1546,8 +1487,9 @@ public final class SnapshotPoliciesListSamples { */ public final class SnapshotPoliciesListVolumesSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * SnapshotPolicies_ListVolumes.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/SnapshotPolicies_ListVolumes. + * json */ /** * Sample code: SnapshotPolicies_ListVolumes. @@ -1575,8 +1517,8 @@ import com.azure.resourcemanager.netapp.models.WeeklySchedule; */ public final class SnapshotPoliciesUpdateSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * SnapshotPolicies_Update.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/SnapshotPolicies_Update.json */ /** * Sample code: SnapshotPolicies_Update. @@ -1609,7 +1551,7 @@ public final class SnapshotPoliciesUpdateSamples { public final class SnapshotsCreateSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Snapshots_Create.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Snapshots_Create.json */ /** * Sample code: Snapshots_Create. @@ -1635,7 +1577,7 @@ public final class SnapshotsCreateSamples { public final class SnapshotsDeleteSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Snapshots_Delete.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Snapshots_Delete.json */ /** * Sample code: Snapshots_Delete. @@ -1658,7 +1600,7 @@ public final class SnapshotsDeleteSamples { public final class SnapshotsGetSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Snapshots_Get.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Snapshots_Get.json */ /** * Sample code: Snapshots_Get. @@ -1681,7 +1623,7 @@ public final class SnapshotsGetSamples { public final class SnapshotsListSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Snapshots_List.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Snapshots_List.json */ /** * Sample code: Snapshots_List. @@ -1705,8 +1647,9 @@ import java.util.Arrays; */ public final class SnapshotsRestoreFilesSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Snapshots_SingleFileRestore.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Snapshots_SingleFileRestore. + * json */ /** * Sample code: Snapshots_SingleFileRestore. @@ -1735,7 +1678,7 @@ import java.io.IOException; public final class SnapshotsUpdateSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Snapshots_Update.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Snapshots_Update.json */ /** * Sample code: Snapshots_Update. @@ -1761,7 +1704,7 @@ public final class SnapshotsUpdateSamples { public final class SubvolumesCreateSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Subvolumes_Create.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Subvolumes_Create.json */ /** * Sample code: Subvolumes_Create. @@ -1787,7 +1730,7 @@ public final class SubvolumesCreateSamples { public final class SubvolumesDeleteSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Subvolumes_Delete.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Subvolumes_Delete.json */ /** * Sample code: Subvolumes_Delete. @@ -1810,7 +1753,7 @@ public final class SubvolumesDeleteSamples { public final class SubvolumesGetSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Subvolumes_Get.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Subvolumes_Get.json */ /** * Sample code: Subvolumes_Get. @@ -1833,8 +1776,7 @@ public final class SubvolumesGetSamples { public final class SubvolumesGetMetadataSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Subvolumes_Metadata. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Subvolumes_Metadata.json */ /** * Sample code: Subvolumes_Metadata. @@ -1857,7 +1799,7 @@ public final class SubvolumesGetMetadataSamples { public final class SubvolumesListByVolumeSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Subvolumes_List.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Subvolumes_List.json */ /** * Sample code: Subvolumes_List. @@ -1881,7 +1823,7 @@ import com.azure.resourcemanager.netapp.models.SubvolumeInfo; public final class SubvolumesUpdateSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Subvolumes_Update.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Subvolumes_Update.json */ /** * Sample code: Subvolumes_Update. @@ -1913,8 +1855,9 @@ import java.util.Arrays; */ public final class VolumeGroupsCreateSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * VolumeGroups_Create_SapHana.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/VolumeGroups_Create_SapHana. + * json */ /** * Sample code: VolumeGroups_Create_SapHana. @@ -2074,8 +2017,8 @@ public final class VolumeGroupsCreateSamples { } /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * VolumeGroups_Create_Oracle.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/VolumeGroups_Create_Oracle.json */ /** * Sample code: VolumeGroups_Create_Oracle. @@ -2429,8 +2372,7 @@ public final class VolumeGroupsCreateSamples { public final class VolumeGroupsDeleteSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/VolumeGroups_Delete. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/VolumeGroups_Delete.json */ /** * Sample code: VolumeGroups_Delete. @@ -2451,8 +2393,8 @@ public final class VolumeGroupsDeleteSamples { */ public final class VolumeGroupsGetSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * VolumeGroups_Get_SapHana.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/VolumeGroups_Get_SapHana.json */ /** * Sample code: VolumeGroups_Get_SapHana. @@ -2464,8 +2406,8 @@ public final class VolumeGroupsGetSamples { } /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * VolumeGroups_Get_Oracle.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/VolumeGroups_Get_Oracle.json */ /** * Sample code: VolumeGroups_Get_Oracle. @@ -2486,8 +2428,8 @@ public final class VolumeGroupsGetSamples { */ public final class VolumeGroupsListByNetAppAccountSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * VolumeGroups_List_Oracle.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/VolumeGroups_List_Oracle.json */ /** * Sample code: VolumeGroups_List_Oracle. @@ -2499,8 +2441,8 @@ public final class VolumeGroupsListByNetAppAccountSamples { } /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * VolumeGroups_List_SapHana.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/VolumeGroups_List_SapHana.json */ /** * Sample code: VolumeGroups_List_SapHana. @@ -2523,8 +2465,8 @@ import com.azure.resourcemanager.netapp.models.Type; */ public final class VolumeQuotaRulesCreateSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * VolumeQuotaRules_Create.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/VolumeQuotaRules_Create.json */ /** * Sample code: VolumeQuotaRules_Create. @@ -2552,8 +2494,8 @@ public final class VolumeQuotaRulesCreateSamples { */ public final class VolumeQuotaRulesDeleteSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * VolumeQuotaRules_Delete.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/VolumeQuotaRules_Delete.json */ /** * Sample code: VolumeQuotaRules_Delete. @@ -2576,8 +2518,7 @@ public final class VolumeQuotaRulesDeleteSamples { public final class VolumeQuotaRulesGetSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/VolumeQuotaRules_Get. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/VolumeQuotaRules_Get.json */ /** * Sample code: VolumeQuotaRules_Get. @@ -2601,8 +2542,7 @@ public final class VolumeQuotaRulesGetSamples { public final class VolumeQuotaRulesListByVolumeSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/VolumeQuotaRules_List. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/VolumeQuotaRules_List.json */ /** * Sample code: VolumeQuotaRules_List. @@ -2626,8 +2566,8 @@ import com.azure.resourcemanager.netapp.models.VolumeQuotaRule; */ public final class VolumeQuotaRulesUpdateSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * VolumeQuotaRules_Update.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/VolumeQuotaRules_Update.json */ /** * Sample code: VolumeQuotaRules_Update. @@ -2652,7 +2592,7 @@ public final class VolumeQuotaRulesUpdateSamples { */ public final class VolumesAuthorizeExternalReplicationSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ + * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/ * Volumes_AuthorizeExternalReplication.json */ /** @@ -2678,8 +2618,9 @@ import com.azure.resourcemanager.netapp.models.AuthorizeRequest; */ public final class VolumesAuthorizeReplicationSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_AuthorizeReplication.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_AuthorizeReplication. + * json */ /** * Sample code: Volumes_AuthorizeReplication. @@ -2707,8 +2648,7 @@ import com.azure.resourcemanager.netapp.models.BreakFileLocksRequest; public final class VolumesBreakFileLocksSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Volumes_BreakFileLocks - * .json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_BreakFileLocks.json */ /** * Sample code: Volumes_BreakFileLocks. @@ -2734,8 +2674,8 @@ import com.azure.resourcemanager.netapp.models.BreakReplicationRequest; */ public final class VolumesBreakReplicationSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_BreakReplication.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_BreakReplication.json */ /** * Sample code: Volumes_BreakReplication. @@ -2761,8 +2701,7 @@ import com.azure.resourcemanager.netapp.models.ServiceLevel; public final class VolumesCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Volumes_CreateOrUpdate - * .json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_CreateOrUpdate.json */ /** * Sample code: Volumes_CreateOrUpdate. @@ -2793,7 +2732,7 @@ public final class VolumesCreateOrUpdateSamples { public final class VolumesDeleteSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Volumes_Delete.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_Delete.json */ /** * Sample code: Volumes_Delete. @@ -2814,8 +2753,8 @@ public final class VolumesDeleteSamples { */ public final class VolumesDeleteReplicationSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_DeleteReplication.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_DeleteReplication.json */ /** * Sample code: Volumes_DeleteReplication. @@ -2836,7 +2775,7 @@ public final class VolumesDeleteReplicationSamples { */ public final class VolumesFinalizeExternalReplicationSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ + * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/ * Volumes_FinalizeExternalReplication.json */ /** @@ -2859,8 +2798,8 @@ public final class VolumesFinalizeExternalReplicationSamples { */ public final class VolumesFinalizeRelocationSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_FinalizeRelocation.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_FinalizeRelocation.json */ /** * Sample code: Volumes_FinalizeRelocation. @@ -2882,7 +2821,7 @@ public final class VolumesFinalizeRelocationSamples { public final class VolumesGetSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Volumes_Get.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_Get.json */ /** * Sample code: Volumes_Get. @@ -2904,7 +2843,7 @@ public final class VolumesGetSamples { public final class VolumesListSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Volumes_List.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_List.json */ /** * Sample code: Volumes_List. @@ -2928,8 +2867,7 @@ import com.azure.resourcemanager.netapp.models.GetGroupIdListForLdapUserRequest; public final class VolumesListGetGroupIdListForLdapUserSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/GroupIdListForLDAPUser - * .json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/GroupIdListForLDAPUser.json */ /** * Sample code: GetGroupIdListForUser. @@ -2944,28 +2882,6 @@ public final class VolumesListGetGroupIdListForLdapUserSamples { } ``` -### Volumes_ListQuotaReport - -```java -/** - * Samples for Volumes ListQuotaReport. - */ -public final class VolumesListQuotaReportSamples { - /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_ListQuotaReport.json - */ - /** - * Sample code: ListQuotaReport. - * - * @param manager Entry point to NetAppFilesManager. - */ - public static void listQuotaReport(com.azure.resourcemanager.netapp.NetAppFilesManager manager) { - manager.volumes().listQuotaReport("myRG", "account1", "pool1", "volume1", com.azure.core.util.Context.NONE); - } -} -``` - ### Volumes_ListReplications ```java @@ -2974,8 +2890,8 @@ public final class VolumesListQuotaReportSamples { */ public final class VolumesListReplicationsSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_ListReplications.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_ListReplications.json */ /** * Sample code: Volumes_ListReplications. @@ -2999,8 +2915,9 @@ import java.util.Arrays; */ public final class VolumesPeerExternalClusterSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_PeerExternalCluster.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_PeerExternalCluster. + * json */ /** * Sample code: Volumes_PeerExternalCluster. @@ -3025,7 +2942,7 @@ public final class VolumesPeerExternalClusterSamples { */ public final class VolumesPerformReplicationTransferSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ + * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/ * Volumes_PerformReplicationTransfer.json */ /** @@ -3051,8 +2968,7 @@ import com.azure.resourcemanager.netapp.models.PoolChangeRequest; public final class VolumesPoolChangeSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Volumes_PoolChange. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_PoolChange.json */ /** * Sample code: Volumes_AuthorizeReplication. @@ -3076,7 +2992,7 @@ public final class VolumesPoolChangeSamples { */ public final class VolumesPopulateAvailabilityZoneSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ + * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/ * Volumes_PopulateAvailabilityZones.json */ /** @@ -3099,8 +3015,9 @@ public final class VolumesPopulateAvailabilityZoneSamples { */ public final class VolumesReInitializeReplicationSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_ReInitializeReplication.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_ReInitializeReplication + * .json */ /** * Sample code: Volumes_ReInitializeReplication. @@ -3124,8 +3041,9 @@ import com.azure.resourcemanager.netapp.models.ReestablishReplicationRequest; */ public final class VolumesReestablishReplicationSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_ReestablishReplication.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_ReestablishReplication. + * json */ /** * Sample code: Volumes_ReestablishReplication. @@ -3153,7 +3071,7 @@ import com.azure.resourcemanager.netapp.models.RelocateVolumeRequest; public final class VolumesRelocateSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Volumes_Relocate.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_Relocate.json */ /** * Sample code: Volumes_Relocate. @@ -3176,8 +3094,8 @@ public final class VolumesRelocateSamples { */ public final class VolumesReplicationStatusSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_ReplicationStatus.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_ReplicationStatus.json */ /** * Sample code: Volumes_ReplicationStatus. @@ -3199,8 +3117,8 @@ public final class VolumesReplicationStatusSamples { */ public final class VolumesResetCifsPasswordSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_ResetCifsPassword.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_ResetCifsPassword.json */ /** * Sample code: Volumes_ResetCifsPassword. @@ -3221,8 +3139,8 @@ public final class VolumesResetCifsPasswordSamples { */ public final class VolumesResyncReplicationSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_ResyncReplication.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_ResyncReplication.json */ /** * Sample code: Volumes_ResyncReplication. @@ -3246,7 +3164,7 @@ import com.azure.resourcemanager.netapp.models.VolumeRevert; public final class VolumesRevertSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Volumes_Revert.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_Revert.json */ /** * Sample code: Volumes_Revert. @@ -3270,8 +3188,8 @@ public final class VolumesRevertSamples { */ public final class VolumesRevertRelocationSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_RevertRelocation.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_RevertRelocation.json */ /** * Sample code: Volumes_RevertRelocation. @@ -3284,30 +3202,6 @@ public final class VolumesRevertRelocationSamples { } ``` -### Volumes_SplitCloneFromParent - -```java -/** - * Samples for Volumes SplitCloneFromParent. - */ -public final class VolumesSplitCloneFromParentSamples { - /* - * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Volumes_SplitClone. - * json - */ - /** - * Sample code: Volumes_SplitClone. - * - * @param manager Entry point to NetAppFilesManager. - */ - public static void volumesSplitClone(com.azure.resourcemanager.netapp.NetAppFilesManager manager) { - manager.volumes() - .splitCloneFromParent("myRG", "account1", "pool1", "volume1", com.azure.core.util.Context.NONE); - } -} -``` - ### Volumes_Update ```java @@ -3319,7 +3213,7 @@ import com.azure.resourcemanager.netapp.models.Volume; public final class VolumesUpdateSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Volumes_Update.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_Update.json */ /** * Sample code: Volumes_Update. diff --git a/sdk/netapp/azure-resourcemanager-netapp/pom.xml b/sdk/netapp/azure-resourcemanager-netapp/pom.xml index 373d887bec88..ee1c538778ad 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/pom.xml +++ b/sdk/netapp/azure-resourcemanager-netapp/pom.xml @@ -14,11 +14,11 @@ com.azure.resourcemanager azure-resourcemanager-netapp - 1.6.0-beta.2 + 1.7.0-beta.1 jar Microsoft Azure SDK for NetAppFiles Management - This package contains Microsoft Azure SDK for NetAppFiles Management SDK. For documentation on how to use this package, please see https://aka.ms/azsdk/java/mgmt. Microsoft NetApp Files Azure Resource Provider specification. Package tag package-preview-2024-07-01-preview. + This package contains Microsoft Azure SDK for NetAppFiles Management SDK. For documentation on how to use this package, please see https://aka.ms/azsdk/java/mgmt. Microsoft NetApp Files Azure Resource Provider specification. Package tag package-2024-09-01. https://github.com/Azure/azure-sdk-for-java @@ -45,36 +45,35 @@ UTF-8 0 0 - true false com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/NetAppFilesManager.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/NetAppFilesManager.java index d6bd14d786a0..f42fbd365df2 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/NetAppFilesManager.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/NetAppFilesManager.java @@ -22,6 +22,7 @@ import com.azure.core.http.policy.UserAgentPolicy; import com.azure.core.management.profile.AzureProfile; import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.netapp.fluent.NetAppManagementClient; import com.azure.resourcemanager.netapp.implementation.AccountsImpl; @@ -65,6 +66,7 @@ import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; @@ -161,6 +163,9 @@ public static Configurable configure() { */ public static final class Configurable { private static final ClientLogger LOGGER = new ClientLogger(Configurable.class); + private static final String SDK_VERSION = "version"; + private static final Map PROPERTIES + = CoreUtils.getProperties("azure-resourcemanager-netapp.properties"); private HttpClient httpClient; private HttpLogOptions httpLogOptions; @@ -268,12 +273,14 @@ public NetAppFilesManager authenticate(TokenCredential credential, AzureProfile Objects.requireNonNull(credential, "'credential' cannot be null."); Objects.requireNonNull(profile, "'profile' cannot be null."); + String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); + StringBuilder userAgentBuilder = new StringBuilder(); userAgentBuilder.append("azsdk-java") .append("-") .append("com.azure.resourcemanager.netapp") .append("/") - .append("1.6.0-beta.1"); + .append(clientVersion); if (!Configuration.getGlobalConfiguration().get("AZURE_TELEMETRY_DISABLED", false)) { userAgentBuilder.append(" (") .append(Configuration.getGlobalConfiguration().get("java.version")) diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/AccountsClient.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/AccountsClient.java index 6816b77b1250..442bcdf9d465 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/AccountsClient.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/AccountsClient.java @@ -11,6 +11,7 @@ import com.azure.core.management.polling.PollResult; import com.azure.core.util.Context; import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.netapp.fluent.models.GetKeyVaultStatusResponseInner; import com.azure.resourcemanager.netapp.fluent.models.NetAppAccountInner; import com.azure.resourcemanager.netapp.models.ChangeKeyVault; import com.azure.resourcemanager.netapp.models.EncryptionTransitionRequest; @@ -449,10 +450,12 @@ void transitionToCmk(String resourceGroupName, String accountName, EncryptionTra * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of long-running operation. + * @return the {@link SyncPoller} for polling of result of getKeyVaultStatus with information about how volumes + * under NetApp account are encrypted. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, Void> beginGetChangeKeyVaultInformation(String resourceGroupName, String accountName); + SyncPoller, GetKeyVaultStatusResponseInner> + beginGetChangeKeyVaultInformation(String resourceGroupName, String accountName); /** * Get information about how volumes under NetApp account are encrypted. @@ -467,11 +470,12 @@ void transitionToCmk(String resourceGroupName, String accountName, EncryptionTra * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of long-running operation. + * @return the {@link SyncPoller} for polling of result of getKeyVaultStatus with information about how volumes + * under NetApp account are encrypted. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, Void> beginGetChangeKeyVaultInformation(String resourceGroupName, String accountName, - Context context); + SyncPoller, GetKeyVaultStatusResponseInner> + beginGetChangeKeyVaultInformation(String resourceGroupName, String accountName, Context context); /** * Get information about how volumes under NetApp account are encrypted. @@ -485,9 +489,10 @@ SyncPoller, Void> beginGetChangeKeyVaultInformation(String reso * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return result of getKeyVaultStatus with information about how volumes under NetApp account are encrypted. */ @ServiceMethod(returns = ReturnType.SINGLE) - void getChangeKeyVaultInformation(String resourceGroupName, String accountName); + GetKeyVaultStatusResponseInner getChangeKeyVaultInformation(String resourceGroupName, String accountName); /** * Get information about how volumes under NetApp account are encrypted. @@ -502,9 +507,11 @@ SyncPoller, Void> beginGetChangeKeyVaultInformation(String reso * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return result of getKeyVaultStatus with information about how volumes under NetApp account are encrypted. */ @ServiceMethod(returns = ReturnType.SINGLE) - void getChangeKeyVaultInformation(String resourceGroupName, String accountName, Context context); + GetKeyVaultStatusResponseInner getChangeKeyVaultInformation(String resourceGroupName, String accountName, + Context context); /** * Change Key Vault/Managed HSM that is used for encryption of volumes under NetApp account. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/VolumesClient.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/VolumesClient.java index 5f4c25b6c0ce..76a8f005aeb6 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/VolumesClient.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/VolumesClient.java @@ -13,7 +13,6 @@ import com.azure.core.util.polling.SyncPoller; import com.azure.resourcemanager.netapp.fluent.models.ClusterPeerCommandResponseInner; import com.azure.resourcemanager.netapp.fluent.models.GetGroupIdListForLdapUserResponseInner; -import com.azure.resourcemanager.netapp.fluent.models.ListQuotaReportResponseInner; import com.azure.resourcemanager.netapp.fluent.models.ReplicationInner; import com.azure.resourcemanager.netapp.fluent.models.ReplicationStatusInner; import com.azure.resourcemanager.netapp.fluent.models.SvmPeerCommandResponseInner; @@ -553,77 +552,6 @@ SyncPoller, Void> beginResetCifsPassword(String resourceGroupNa void resetCifsPassword(String resourceGroupName, String accountName, String poolName, String volumeName, Context context); - /** - * Split clone from parent volume - * - * Split operation to convert clone volume to an independent volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of long-running operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, Void> beginSplitCloneFromParent(String resourceGroupName, String accountName, - String poolName, String volumeName); - - /** - * Split clone from parent volume - * - * Split operation to convert clone volume to an independent volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of long-running operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, Void> beginSplitCloneFromParent(String resourceGroupName, String accountName, - String poolName, String volumeName, Context context); - - /** - * Split clone from parent volume - * - * Split operation to convert clone volume to an independent volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - void splitCloneFromParent(String resourceGroupName, String accountName, String poolName, String volumeName); - - /** - * Split clone from parent volume - * - * Split operation to convert clone volume to an independent volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - void splitCloneFromParent(String resourceGroupName, String accountName, String poolName, String volumeName, - Context context); - /** * Break file locks * @@ -777,80 +705,6 @@ GetGroupIdListForLdapUserResponseInner listGetGroupIdListForLdapUser(String reso GetGroupIdListForLdapUserResponseInner listGetGroupIdListForLdapUser(String resourceGroupName, String accountName, String poolName, String volumeName, GetGroupIdListForLdapUserRequest body, Context context); - /** - * Lists Quota Report for the volume - * - * Returns report of quotas for the volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of quota Report for volume. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, ListQuotaReportResponseInner> - beginListQuotaReport(String resourceGroupName, String accountName, String poolName, String volumeName); - - /** - * Lists Quota Report for the volume - * - * Returns report of quotas for the volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of quota Report for volume. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, ListQuotaReportResponseInner> beginListQuotaReport( - String resourceGroupName, String accountName, String poolName, String volumeName, Context context); - - /** - * Lists Quota Report for the volume - * - * Returns report of quotas for the volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return quota Report for volume. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - ListQuotaReportResponseInner listQuotaReport(String resourceGroupName, String accountName, String poolName, - String volumeName); - - /** - * Lists Quota Report for the volume - * - * Returns report of quotas for the volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return quota Report for volume. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - ListQuotaReportResponseInner listQuotaReport(String resourceGroupName, String accountName, String poolName, - String volumeName, Context context); - /** * Break volume replication * diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/AccountProperties.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/AccountProperties.java index cb35f5ea1210..a0a0deb442f1 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/AccountProperties.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/AccountProperties.java @@ -39,17 +39,6 @@ public final class AccountProperties implements JsonSerializable writer.writeJson(element)); jsonWriter.writeJsonField("encryption", this.encryption); - jsonWriter.writeStringField("nfsV4IDDomain", this.nfsV4IdDomain); return jsonWriter.writeEndObject(); } @@ -198,10 +155,6 @@ public static AccountProperties fromJson(JsonReader jsonReader) throws IOExcepti deserializedAccountProperties.encryption = AccountEncryption.fromJson(reader); } else if ("disableShowmount".equals(fieldName)) { deserializedAccountProperties.disableShowmount = reader.getNullable(JsonReader::getBoolean); - } else if ("nfsV4IDDomain".equals(fieldName)) { - deserializedAccountProperties.nfsV4IdDomain = reader.getString(); - } else if ("isMultiAdEnabled".equals(fieldName)) { - deserializedAccountProperties.isMultiAdEnabled = reader.getNullable(JsonReader::getBoolean); } else { reader.skipChildren(); } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/BackupInner.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/BackupInner.java index a0902acb5275..bdb627ced090 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/BackupInner.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/BackupInner.java @@ -256,15 +256,6 @@ public String backupPolicyResourceId() { return this.innerProperties() == null ? null : this.innerProperties().backupPolicyResourceId(); } - /** - * Get the isLargeVolume property: Specifies if the backup is for a large volume. - * - * @return the isLargeVolume value. - */ - public Boolean isLargeVolume() { - return this.innerProperties() == null ? null : this.innerProperties().isLargeVolume(); - } - /** * Validates the instance. * diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/BackupPolicyInner.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/BackupPolicyInner.java index 6c9fd6905a68..8b40e7c539ec 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/BackupPolicyInner.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/BackupPolicyInner.java @@ -133,7 +133,7 @@ public BackupPolicyInner withTags(Map tags) { } /** - * Get the backupPolicyId property: Backup Policy Resource ID. + * Get the backupPolicyId property: Backup Policy GUID ID. * * @return the backupPolicyId value. */ diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/BackupPolicyProperties.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/BackupPolicyProperties.java index 9decde0bd19b..b69917e76822 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/BackupPolicyProperties.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/BackupPolicyProperties.java @@ -19,7 +19,7 @@ @Fluent public final class BackupPolicyProperties implements JsonSerializable { /* - * Backup Policy Resource ID + * Backup Policy GUID ID */ private String backupPolicyId; @@ -65,7 +65,7 @@ public BackupPolicyProperties() { } /** - * Get the backupPolicyId property: Backup Policy Resource ID. + * Get the backupPolicyId property: Backup Policy GUID ID. * * @return the backupPolicyId value. */ diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/BackupProperties.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/BackupProperties.java index 0e8373efcacb..38ff6c3df221 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/BackupProperties.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/BackupProperties.java @@ -76,11 +76,6 @@ public final class BackupProperties implements JsonSerializable { + /* + * Represents the properties of the getKeyVaultStatus. + */ + private GetKeyVaultStatusResponseProperties innerProperties; + + /** + * Creates an instance of GetKeyVaultStatusResponseInner class. + */ + public GetKeyVaultStatusResponseInner() { + } + + /** + * Get the innerProperties property: Represents the properties of the getKeyVaultStatus. + * + * @return the innerProperties value. + */ + private GetKeyVaultStatusResponseProperties innerProperties() { + return this.innerProperties; + } + + /** + * Get the keyVaultUri property: The URI of the key vault/managed HSM that should be used for encryption. + * + * @return the keyVaultUri value. + */ + public String keyVaultUri() { + return this.innerProperties() == null ? null : this.innerProperties().keyVaultUri(); + } + + /** + * Set the keyVaultUri property: The URI of the key vault/managed HSM that should be used for encryption. + * + * @param keyVaultUri the keyVaultUri value to set. + * @return the GetKeyVaultStatusResponseInner object itself. + */ + public GetKeyVaultStatusResponseInner withKeyVaultUri(String keyVaultUri) { + if (this.innerProperties() == null) { + this.innerProperties = new GetKeyVaultStatusResponseProperties(); + } + this.innerProperties().withKeyVaultUri(keyVaultUri); + return this; + } + + /** + * Get the keyName property: The name of the key that should be used for encryption. + * + * @return the keyName value. + */ + public String keyName() { + return this.innerProperties() == null ? null : this.innerProperties().keyName(); + } + + /** + * Set the keyName property: The name of the key that should be used for encryption. + * + * @param keyName the keyName value to set. + * @return the GetKeyVaultStatusResponseInner object itself. + */ + public GetKeyVaultStatusResponseInner withKeyName(String keyName) { + if (this.innerProperties() == null) { + this.innerProperties = new GetKeyVaultStatusResponseProperties(); + } + this.innerProperties().withKeyName(keyName); + return this; + } + + /** + * Get the keyVaultResourceId property: Azure resource ID of the key vault/managed HSM that should be used for + * encryption. + * + * @return the keyVaultResourceId value. + */ + public String keyVaultResourceId() { + return this.innerProperties() == null ? null : this.innerProperties().keyVaultResourceId(); + } + + /** + * Set the keyVaultResourceId property: Azure resource ID of the key vault/managed HSM that should be used for + * encryption. + * + * @param keyVaultResourceId the keyVaultResourceId value to set. + * @return the GetKeyVaultStatusResponseInner object itself. + */ + public GetKeyVaultStatusResponseInner withKeyVaultResourceId(String keyVaultResourceId) { + if (this.innerProperties() == null) { + this.innerProperties = new GetKeyVaultStatusResponseProperties(); + } + this.innerProperties().withKeyVaultResourceId(keyVaultResourceId); + return this; + } + + /** + * Get the keyVaultPrivateEndpoints property: Pairs of virtual network ID and private endpoint ID. Every virtual + * network that has volumes encrypted with customer-managed keys needs its own key vault private endpoint. + * + * @return the keyVaultPrivateEndpoints value. + */ + public List keyVaultPrivateEndpoints() { + return this.innerProperties() == null ? null : this.innerProperties().keyVaultPrivateEndpoints(); + } + + /** + * Set the keyVaultPrivateEndpoints property: Pairs of virtual network ID and private endpoint ID. Every virtual + * network that has volumes encrypted with customer-managed keys needs its own key vault private endpoint. + * + * @param keyVaultPrivateEndpoints the keyVaultPrivateEndpoints value to set. + * @return the GetKeyVaultStatusResponseInner object itself. + */ + public GetKeyVaultStatusResponseInner + withKeyVaultPrivateEndpoints(List keyVaultPrivateEndpoints) { + if (this.innerProperties() == null) { + this.innerProperties = new GetKeyVaultStatusResponseProperties(); + } + this.innerProperties().withKeyVaultPrivateEndpoints(keyVaultPrivateEndpoints); + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (innerProperties() != null) { + innerProperties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.innerProperties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of GetKeyVaultStatusResponseInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of GetKeyVaultStatusResponseInner 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 GetKeyVaultStatusResponseInner. + */ + public static GetKeyVaultStatusResponseInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + GetKeyVaultStatusResponseInner deserializedGetKeyVaultStatusResponseInner + = new GetKeyVaultStatusResponseInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("properties".equals(fieldName)) { + deserializedGetKeyVaultStatusResponseInner.innerProperties + = GetKeyVaultStatusResponseProperties.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedGetKeyVaultStatusResponseInner; + }); + } +} diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/GetKeyVaultStatusResponseProperties.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/GetKeyVaultStatusResponseProperties.java new file mode 100644 index 000000000000..ecda151f84a1 --- /dev/null +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/GetKeyVaultStatusResponseProperties.java @@ -0,0 +1,193 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.netapp.fluent.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.resourcemanager.netapp.models.KeyVaultPrivateEndpoint; +import java.io.IOException; +import java.util.List; + +/** + * Properties which represents Change key vault status. + */ +@Fluent +public final class GetKeyVaultStatusResponseProperties + implements JsonSerializable { + /* + * The URI of the key vault/managed HSM that should be used for encryption. + */ + private String keyVaultUri; + + /* + * The name of the key that should be used for encryption. + */ + private String keyName; + + /* + * Azure resource ID of the key vault/managed HSM that should be used for encryption. + */ + private String keyVaultResourceId; + + /* + * Pairs of virtual network ID and private endpoint ID. Every virtual network that has volumes encrypted with + * customer-managed keys needs its own key vault private endpoint. + */ + private List keyVaultPrivateEndpoints; + + /** + * Creates an instance of GetKeyVaultStatusResponseProperties class. + */ + public GetKeyVaultStatusResponseProperties() { + } + + /** + * Get the keyVaultUri property: The URI of the key vault/managed HSM that should be used for encryption. + * + * @return the keyVaultUri value. + */ + public String keyVaultUri() { + return this.keyVaultUri; + } + + /** + * Set the keyVaultUri property: The URI of the key vault/managed HSM that should be used for encryption. + * + * @param keyVaultUri the keyVaultUri value to set. + * @return the GetKeyVaultStatusResponseProperties object itself. + */ + public GetKeyVaultStatusResponseProperties withKeyVaultUri(String keyVaultUri) { + this.keyVaultUri = keyVaultUri; + return this; + } + + /** + * Get the keyName property: The name of the key that should be used for encryption. + * + * @return the keyName value. + */ + public String keyName() { + return this.keyName; + } + + /** + * Set the keyName property: The name of the key that should be used for encryption. + * + * @param keyName the keyName value to set. + * @return the GetKeyVaultStatusResponseProperties object itself. + */ + public GetKeyVaultStatusResponseProperties withKeyName(String keyName) { + this.keyName = keyName; + return this; + } + + /** + * Get the keyVaultResourceId property: Azure resource ID of the key vault/managed HSM that should be used for + * encryption. + * + * @return the keyVaultResourceId value. + */ + public String keyVaultResourceId() { + return this.keyVaultResourceId; + } + + /** + * Set the keyVaultResourceId property: Azure resource ID of the key vault/managed HSM that should be used for + * encryption. + * + * @param keyVaultResourceId the keyVaultResourceId value to set. + * @return the GetKeyVaultStatusResponseProperties object itself. + */ + public GetKeyVaultStatusResponseProperties withKeyVaultResourceId(String keyVaultResourceId) { + this.keyVaultResourceId = keyVaultResourceId; + return this; + } + + /** + * Get the keyVaultPrivateEndpoints property: Pairs of virtual network ID and private endpoint ID. Every virtual + * network that has volumes encrypted with customer-managed keys needs its own key vault private endpoint. + * + * @return the keyVaultPrivateEndpoints value. + */ + public List keyVaultPrivateEndpoints() { + return this.keyVaultPrivateEndpoints; + } + + /** + * Set the keyVaultPrivateEndpoints property: Pairs of virtual network ID and private endpoint ID. Every virtual + * network that has volumes encrypted with customer-managed keys needs its own key vault private endpoint. + * + * @param keyVaultPrivateEndpoints the keyVaultPrivateEndpoints value to set. + * @return the GetKeyVaultStatusResponseProperties object itself. + */ + public GetKeyVaultStatusResponseProperties + withKeyVaultPrivateEndpoints(List keyVaultPrivateEndpoints) { + this.keyVaultPrivateEndpoints = keyVaultPrivateEndpoints; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (keyVaultPrivateEndpoints() != null) { + keyVaultPrivateEndpoints().forEach(e -> e.validate()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("keyVaultUri", this.keyVaultUri); + jsonWriter.writeStringField("keyName", this.keyName); + jsonWriter.writeStringField("keyVaultResourceId", this.keyVaultResourceId); + jsonWriter.writeArrayField("keyVaultPrivateEndpoints", this.keyVaultPrivateEndpoints, + (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of GetKeyVaultStatusResponseProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of GetKeyVaultStatusResponseProperties 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 GetKeyVaultStatusResponseProperties. + */ + public static GetKeyVaultStatusResponseProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + GetKeyVaultStatusResponseProperties deserializedGetKeyVaultStatusResponseProperties + = new GetKeyVaultStatusResponseProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("keyVaultUri".equals(fieldName)) { + deserializedGetKeyVaultStatusResponseProperties.keyVaultUri = reader.getString(); + } else if ("keyName".equals(fieldName)) { + deserializedGetKeyVaultStatusResponseProperties.keyName = reader.getString(); + } else if ("keyVaultResourceId".equals(fieldName)) { + deserializedGetKeyVaultStatusResponseProperties.keyVaultResourceId = reader.getString(); + } else if ("keyVaultPrivateEndpoints".equals(fieldName)) { + List keyVaultPrivateEndpoints + = reader.readArray(reader1 -> KeyVaultPrivateEndpoint.fromJson(reader1)); + deserializedGetKeyVaultStatusResponseProperties.keyVaultPrivateEndpoints = keyVaultPrivateEndpoints; + } else { + reader.skipChildren(); + } + } + + return deserializedGetKeyVaultStatusResponseProperties; + }); + } +} diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/ListQuotaReportResponseInner.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/ListQuotaReportResponseInner.java deleted file mode 100644 index 0fc97a6a1a4d..000000000000 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/ListQuotaReportResponseInner.java +++ /dev/null @@ -1,127 +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.resourcemanager.netapp.fluent.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.resourcemanager.netapp.models.QuotaReport; -import java.io.IOException; -import java.util.List; - -/** - * Quota Report for volume. - */ -@Fluent -public final class ListQuotaReportResponseInner implements JsonSerializable { - /* - * List of volume quota report records - */ - private List value; - - /* - * URL to get the next set of results. - */ - private String nextLink; - - /** - * Creates an instance of ListQuotaReportResponseInner class. - */ - public ListQuotaReportResponseInner() { - } - - /** - * Get the value property: List of volume quota report records. - * - * @return the value value. - */ - public List value() { - return this.value; - } - - /** - * Set the value property: List of volume quota report records. - * - * @param value the value value to set. - * @return the ListQuotaReportResponseInner object itself. - */ - public ListQuotaReportResponseInner withValue(List value) { - this.value = value; - return this; - } - - /** - * Get the nextLink property: URL to get the next set of results. - * - * @return the nextLink value. - */ - public String nextLink() { - return this.nextLink; - } - - /** - * Set the nextLink property: URL to get the next set of results. - * - * @param nextLink the nextLink value to set. - * @return the ListQuotaReportResponseInner object itself. - */ - public ListQuotaReportResponseInner withNextLink(String nextLink) { - this.nextLink = nextLink; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (value() != null) { - value().forEach(e -> e.validate()); - } - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); - jsonWriter.writeStringField("nextLink", this.nextLink); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of ListQuotaReportResponseInner from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of ListQuotaReportResponseInner 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 ListQuotaReportResponseInner. - */ - public static ListQuotaReportResponseInner fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - ListQuotaReportResponseInner deserializedListQuotaReportResponseInner = new ListQuotaReportResponseInner(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - List value = reader.readArray(reader1 -> QuotaReport.fromJson(reader1)); - deserializedListQuotaReportResponseInner.value = value; - } else if ("nextLink".equals(fieldName)) { - deserializedListQuotaReportResponseInner.nextLink = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedListQuotaReportResponseInner; - }); - } -} diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/NetAppAccountInner.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/NetAppAccountInner.java index 72248dfa70b9..35293fa98930 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/NetAppAccountInner.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/NetAppAccountInner.java @@ -223,40 +223,6 @@ public Boolean disableShowmount() { return this.innerProperties() == null ? null : this.innerProperties().disableShowmount(); } - /** - * Get the nfsV4IdDomain property: Domain for NFSv4 user ID mapping. This property will be set for all NetApp - * accounts in the subscription and region and only affect non ldap NFSv4 volumes. - * - * @return the nfsV4IdDomain value. - */ - public String nfsV4IdDomain() { - return this.innerProperties() == null ? null : this.innerProperties().nfsV4IdDomain(); - } - - /** - * Set the nfsV4IdDomain property: Domain for NFSv4 user ID mapping. This property will be set for all NetApp - * accounts in the subscription and region and only affect non ldap NFSv4 volumes. - * - * @param nfsV4IdDomain the nfsV4IdDomain value to set. - * @return the NetAppAccountInner object itself. - */ - public NetAppAccountInner withNfsV4IdDomain(String nfsV4IdDomain) { - if (this.innerProperties() == null) { - this.innerProperties = new AccountProperties(); - } - this.innerProperties().withNfsV4IdDomain(nfsV4IdDomain); - return this; - } - - /** - * Get the isMultiAdEnabled property: This will have true value only if account is Multiple AD enabled. - * - * @return the isMultiAdEnabled value. - */ - public Boolean isMultiAdEnabled() { - return this.innerProperties() == null ? null : this.innerProperties().isMultiAdEnabled(); - } - /** * Validates the instance. * diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/PoolPatchProperties.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/PoolPatchProperties.java index 999f47974e1b..b73b809b72b5 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/PoolPatchProperties.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/PoolPatchProperties.java @@ -33,12 +33,6 @@ public final class PoolPatchProperties implements JsonSerializable { */ private Float utilizedThroughputMibps; - /* - * Maximum throughput in MiB/s that can be achieved by this pool and this will be accepted as input only for manual - * qosType pool with Flexible service level - */ - private Float customThroughputMibps; - /* * The qos type of the pool */ @@ -157,28 +151,6 @@ public Float utilizedThroughputMibps() { return this.utilizedThroughputMibps; } - /** - * Get the customThroughputMibps property: Maximum throughput in MiB/s that can be achieved by this pool and this - * will be accepted as input only for manual qosType pool with Flexible service level. - * - * @return the customThroughputMibps value. - */ - public Float customThroughputMibps() { - return this.customThroughputMibps; - } - - /** - * Set the customThroughputMibps property: Maximum throughput in MiB/s that can be achieved by this pool and this - * will be accepted as input only for manual qosType pool with Flexible service level. - * - * @param customThroughputMibps the customThroughputMibps value to set. - * @return the PoolProperties object itself. - */ - public PoolProperties withCustomThroughputMibps(Float customThroughputMibps) { - this.customThroughputMibps = customThroughputMibps; - return this; - } - /** * Get the qosType property: The qos type of the pool. * @@ -263,7 +235,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeLongField("size", this.size); jsonWriter.writeStringField("serviceLevel", this.serviceLevel == null ? null : this.serviceLevel.toString()); - jsonWriter.writeNumberField("customThroughputMibps", this.customThroughputMibps); jsonWriter.writeStringField("qosType", this.qosType == null ? null : this.qosType.toString()); jsonWriter.writeBooleanField("coolAccess", this.coolAccess); jsonWriter.writeStringField("encryptionType", @@ -299,8 +270,6 @@ public static PoolProperties fromJson(JsonReader jsonReader) throws IOException deserializedPoolProperties.totalThroughputMibps = reader.getNullable(JsonReader::getFloat); } else if ("utilizedThroughputMibps".equals(fieldName)) { deserializedPoolProperties.utilizedThroughputMibps = reader.getNullable(JsonReader::getFloat); - } else if ("customThroughputMibps".equals(fieldName)) { - deserializedPoolProperties.customThroughputMibps = reader.getNullable(JsonReader::getFloat); } else if ("qosType".equals(fieldName)) { deserializedPoolProperties.qosType = QosType.fromString(reader.getString()); } else if ("coolAccess".equals(fieldName)) { diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/VolumeInner.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/VolumeInner.java index aa2c9979d3d8..9dfe423bf287 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/VolumeInner.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/VolumeInner.java @@ -11,9 +11,9 @@ import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.azure.resourcemanager.netapp.models.AcceptGrowCapacityPoolForShortTermCloneSplit; import com.azure.resourcemanager.netapp.models.AvsDataStore; import com.azure.resourcemanager.netapp.models.CoolAccessRetrievalPolicy; +import com.azure.resourcemanager.netapp.models.CoolAccessTieringPolicy; import com.azure.resourcemanager.netapp.models.EnableSubvolumes; import com.azure.resourcemanager.netapp.models.EncryptionKeySource; import com.azure.resourcemanager.netapp.models.FileAccessLogs; @@ -23,7 +23,6 @@ import com.azure.resourcemanager.netapp.models.ServiceLevel; import com.azure.resourcemanager.netapp.models.SmbAccessBasedEnumeration; import com.azure.resourcemanager.netapp.models.SmbNonBrowsable; -import com.azure.resourcemanager.netapp.models.VolumeLanguage; import com.azure.resourcemanager.netapp.models.VolumePropertiesDataProtection; import com.azure.resourcemanager.netapp.models.VolumePropertiesExportPolicy; import com.azure.resourcemanager.netapp.models.VolumeStorageToNetworkProximity; @@ -230,7 +229,7 @@ public VolumeInner withServiceLevel(ServiceLevel serviceLevel) { /** * Get the usageThreshold property: Maximum storage quota allowed for a file system in bytes. This is a soft quota * used for alerting only. For regular volumes, valid values are in the range 50GiB to 100TiB. For large volumes, - * valid values are in the range 100TiB to 1PiB, and on an exceptional basis, from to 2400GiB to 2400TiB. Values + * valid values are in the range 100TiB to 500TiB, and on an exceptional basis, from to 2400GiB to 2400TiB. Values * expressed in bytes as multiples of 1 GiB. * * @return the usageThreshold value. @@ -242,7 +241,7 @@ public long usageThreshold() { /** * Set the usageThreshold property: Maximum storage quota allowed for a file system in bytes. This is a soft quota * used for alerting only. For regular volumes, valid values are in the range 50GiB to 100TiB. For large volumes, - * valid values are in the range 100TiB to 1PiB, and on an exceptional basis, from to 2400GiB to 2400TiB. Values + * valid values are in the range 100TiB to 500TiB, and on an exceptional basis, from to 2400GiB to 2400TiB. Values * expressed in bytes as multiples of 1 GiB. * * @param usageThreshold the usageThreshold value to set. @@ -481,7 +480,7 @@ public List mountTargets() { /** * Get the volumeType property: What type of volume is this. For destination volumes in Cross Region Replication, - * set type to DataProtection. For creating clone volume, set type to ShortTermClone. + * set type to DataProtection. * * @return the volumeType value. */ @@ -491,7 +490,7 @@ public String volumeType() { /** * Set the volumeType property: What type of volume is this. For destination volumes in Cross Region Replication, - * set type to DataProtection. For creating clone volume, set type to ShortTermClone. + * set type to DataProtection. * * @param volumeType the volumeType value to set. * @return the VolumeInner object itself. @@ -529,40 +528,6 @@ public VolumeInner withDataProtection(VolumePropertiesDataProtection dataProtect return this; } - /** - * Get the acceptGrowCapacityPoolForShortTermCloneSplit property: While auto splitting the short term clone volume, - * if the parent pool does not have enough space to accommodate the volume after split, it will be automatically - * resized, which will lead to increased billing. To accept capacity pool size auto grow and create a short term - * clone volume, set the property as accepted. - * - * @return the acceptGrowCapacityPoolForShortTermCloneSplit value. - */ - public AcceptGrowCapacityPoolForShortTermCloneSplit acceptGrowCapacityPoolForShortTermCloneSplit() { - return this.innerProperties() == null - ? null - : this.innerProperties().acceptGrowCapacityPoolForShortTermCloneSplit(); - } - - /** - * Set the acceptGrowCapacityPoolForShortTermCloneSplit property: While auto splitting the short term clone volume, - * if the parent pool does not have enough space to accommodate the volume after split, it will be automatically - * resized, which will lead to increased billing. To accept capacity pool size auto grow and create a short term - * clone volume, set the property as accepted. - * - * @param acceptGrowCapacityPoolForShortTermCloneSplit the acceptGrowCapacityPoolForShortTermCloneSplit value to - * set. - * @return the VolumeInner object itself. - */ - public VolumeInner withAcceptGrowCapacityPoolForShortTermCloneSplit( - AcceptGrowCapacityPoolForShortTermCloneSplit acceptGrowCapacityPoolForShortTermCloneSplit) { - if (this.innerProperties() == null) { - this.innerProperties = new VolumeProperties(); - } - this.innerProperties() - .withAcceptGrowCapacityPoolForShortTermCloneSplit(acceptGrowCapacityPoolForShortTermCloneSplit); - return this; - } - /** * Get the isRestoring property: Restoring. * @@ -954,15 +919,41 @@ public VolumeInner withCoolAccessRetrievalPolicy(CoolAccessRetrievalPolicy coolA return this; } + /** + * Get the coolAccessTieringPolicy property: coolAccessTieringPolicy determines which cold data blocks are moved to + * cool tier. The possible values for this field are: Auto - Moves cold user data blocks in both the Snapshot copies + * and the active file system to the cool tier tier. This policy is the default. SnapshotOnly - Moves user data + * blocks of the Volume Snapshot copies that are not associated with the active file system to the cool tier. + * + * @return the coolAccessTieringPolicy value. + */ + public CoolAccessTieringPolicy coolAccessTieringPolicy() { + return this.innerProperties() == null ? null : this.innerProperties().coolAccessTieringPolicy(); + } + + /** + * Set the coolAccessTieringPolicy property: coolAccessTieringPolicy determines which cold data blocks are moved to + * cool tier. The possible values for this field are: Auto - Moves cold user data blocks in both the Snapshot copies + * and the active file system to the cool tier tier. This policy is the default. SnapshotOnly - Moves user data + * blocks of the Volume Snapshot copies that are not associated with the active file system to the cool tier. + * + * @param coolAccessTieringPolicy the coolAccessTieringPolicy value to set. + * @return the VolumeInner object itself. + */ + public VolumeInner withCoolAccessTieringPolicy(CoolAccessTieringPolicy coolAccessTieringPolicy) { + if (this.innerProperties() == null) { + this.innerProperties = new VolumeProperties(); + } + this.innerProperties().withCoolAccessTieringPolicy(coolAccessTieringPolicy); + return this; + } + /** * Get the unixPermissions property: UNIX permissions for NFS volume accepted in octal 4 digit format. First digit * selects the set user ID(4), set group ID (2) and sticky (1) attributes. Second digit selects permission for the * owner of the file: read (4), write (2) and execute (1). Third selects permissions for other users in the same * group. the fourth for other users not in the group. 0755 - gives read/write/execute permissions to owner and - * read/execute to group and other users. Avoid passing null value for unixPermissions in volume update operation, - * As per the behavior, If Null value is passed then user-visible unixPermissions value will became null, and user - * will not be able to get unixPermissions value. On safer side, actual unixPermissions value on volume will remain - * as its last saved value only. + * read/execute to group and other users. * * @return the unixPermissions value. */ @@ -975,10 +966,7 @@ public String unixPermissions() { * selects the set user ID(4), set group ID (2) and sticky (1) attributes. Second digit selects permission for the * owner of the file: read (4), write (2) and execute (1). Third selects permissions for other users in the same * group. the fourth for other users not in the group. 0755 - gives read/write/execute permissions to owner and - * read/execute to group and other users. Avoid passing null value for unixPermissions in volume update operation, - * As per the behavior, If Null value is passed then user-visible unixPermissions value will became null, and user - * will not be able to get unixPermissions value. On safer side, actual unixPermissions value on volume will remain - * as its last saved value only. + * read/execute to group and other users. * * @param unixPermissions the unixPermissions value to set. * @return the VolumeInner object itself. @@ -1316,38 +1304,6 @@ public String originatingResourceId() { return this.innerProperties() == null ? null : this.innerProperties().originatingResourceId(); } - /** - * Get the inheritedSizeInBytes property: Space shared by short term clone volume with parent volume in bytes. - * - * @return the inheritedSizeInBytes value. - */ - public Long inheritedSizeInBytes() { - return this.innerProperties() == null ? null : this.innerProperties().inheritedSizeInBytes(); - } - - /** - * Get the language property: Language supported for volume. - * - * @return the language value. - */ - public VolumeLanguage language() { - return this.innerProperties() == null ? null : this.innerProperties().language(); - } - - /** - * Set the language property: Language supported for volume. - * - * @param language the language value to set. - * @return the VolumeInner object itself. - */ - public VolumeInner withLanguage(VolumeLanguage language) { - if (this.innerProperties() == null) { - this.innerProperties = new VolumeProperties(); - } - this.innerProperties().withLanguage(language); - return this; - } - /** * Validates the instance. * diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/VolumePatchProperties.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/VolumePatchProperties.java index 68855f824f62..b347a9f46624 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/VolumePatchProperties.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/fluent/models/VolumePatchProperties.java @@ -10,6 +10,7 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import com.azure.resourcemanager.netapp.models.CoolAccessRetrievalPolicy; +import com.azure.resourcemanager.netapp.models.CoolAccessTieringPolicy; import com.azure.resourcemanager.netapp.models.ServiceLevel; import com.azure.resourcemanager.netapp.models.SmbAccessBasedEnumeration; import com.azure.resourcemanager.netapp.models.SmbNonBrowsable; @@ -31,7 +32,7 @@ public final class VolumePatchProperties implements JsonSerializable mountTargets; /* - * What type of volume is this. For destination volumes in Cross Region Replication, set type to DataProtection. For - * creating clone volume, set type to ShortTermClone + * What type of volume is this. For destination volumes in Cross Region Replication, set type to DataProtection */ private String volumeType; @@ -134,13 +132,6 @@ public final class VolumeProperties implements JsonSerializable mountTargets() { /** * Get the volumeType property: What type of volume is this. For destination volumes in Cross Region Replication, - * set type to DataProtection. For creating clone volume, set type to ShortTermClone. + * set type to DataProtection. * * @return the volumeType value. */ @@ -649,7 +635,7 @@ public String volumeType() { /** * Set the volumeType property: What type of volume is this. For destination volumes in Cross Region Replication, - * set type to DataProtection. For creating clone volume, set type to ShortTermClone. + * set type to DataProtection. * * @param volumeType the volumeType value to set. * @return the VolumeProperties object itself. @@ -681,34 +667,6 @@ public VolumeProperties withDataProtection(VolumePropertiesDataProtection dataPr return this; } - /** - * Get the acceptGrowCapacityPoolForShortTermCloneSplit property: While auto splitting the short term clone volume, - * if the parent pool does not have enough space to accommodate the volume after split, it will be automatically - * resized, which will lead to increased billing. To accept capacity pool size auto grow and create a short term - * clone volume, set the property as accepted. - * - * @return the acceptGrowCapacityPoolForShortTermCloneSplit value. - */ - public AcceptGrowCapacityPoolForShortTermCloneSplit acceptGrowCapacityPoolForShortTermCloneSplit() { - return this.acceptGrowCapacityPoolForShortTermCloneSplit; - } - - /** - * Set the acceptGrowCapacityPoolForShortTermCloneSplit property: While auto splitting the short term clone volume, - * if the parent pool does not have enough space to accommodate the volume after split, it will be automatically - * resized, which will lead to increased billing. To accept capacity pool size auto grow and create a short term - * clone volume, set the property as accepted. - * - * @param acceptGrowCapacityPoolForShortTermCloneSplit the acceptGrowCapacityPoolForShortTermCloneSplit value to - * set. - * @return the VolumeProperties object itself. - */ - public VolumeProperties withAcceptGrowCapacityPoolForShortTermCloneSplit( - AcceptGrowCapacityPoolForShortTermCloneSplit acceptGrowCapacityPoolForShortTermCloneSplit) { - this.acceptGrowCapacityPoolForShortTermCloneSplit = acceptGrowCapacityPoolForShortTermCloneSplit; - return this; - } - /** * Get the isRestoring property: Restoring. * @@ -1055,15 +1013,38 @@ public VolumeProperties withCoolAccessRetrievalPolicy(CoolAccessRetrievalPolicy return this; } + /** + * Get the coolAccessTieringPolicy property: coolAccessTieringPolicy determines which cold data blocks are moved to + * cool tier. The possible values for this field are: Auto - Moves cold user data blocks in both the Snapshot copies + * and the active file system to the cool tier tier. This policy is the default. SnapshotOnly - Moves user data + * blocks of the Volume Snapshot copies that are not associated with the active file system to the cool tier. + * + * @return the coolAccessTieringPolicy value. + */ + public CoolAccessTieringPolicy coolAccessTieringPolicy() { + return this.coolAccessTieringPolicy; + } + + /** + * Set the coolAccessTieringPolicy property: coolAccessTieringPolicy determines which cold data blocks are moved to + * cool tier. The possible values for this field are: Auto - Moves cold user data blocks in both the Snapshot copies + * and the active file system to the cool tier tier. This policy is the default. SnapshotOnly - Moves user data + * blocks of the Volume Snapshot copies that are not associated with the active file system to the cool tier. + * + * @param coolAccessTieringPolicy the coolAccessTieringPolicy value to set. + * @return the VolumeProperties object itself. + */ + public VolumeProperties withCoolAccessTieringPolicy(CoolAccessTieringPolicy coolAccessTieringPolicy) { + this.coolAccessTieringPolicy = coolAccessTieringPolicy; + return this; + } + /** * Get the unixPermissions property: UNIX permissions for NFS volume accepted in octal 4 digit format. First digit * selects the set user ID(4), set group ID (2) and sticky (1) attributes. Second digit selects permission for the * owner of the file: read (4), write (2) and execute (1). Third selects permissions for other users in the same * group. the fourth for other users not in the group. 0755 - gives read/write/execute permissions to owner and - * read/execute to group and other users. Avoid passing null value for unixPermissions in volume update operation, - * As per the behavior, If Null value is passed then user-visible unixPermissions value will became null, and user - * will not be able to get unixPermissions value. On safer side, actual unixPermissions value on volume will remain - * as its last saved value only. + * read/execute to group and other users. * * @return the unixPermissions value. */ @@ -1076,10 +1057,7 @@ public String unixPermissions() { * selects the set user ID(4), set group ID (2) and sticky (1) attributes. Second digit selects permission for the * owner of the file: read (4), write (2) and execute (1). Third selects permissions for other users in the same * group. the fourth for other users not in the group. 0755 - gives read/write/execute permissions to owner and - * read/execute to group and other users. Avoid passing null value for unixPermissions in volume update operation, - * As per the behavior, If Null value is passed then user-visible unixPermissions value will became null, and user - * will not be able to get unixPermissions value. On safer side, actual unixPermissions value on volume will remain - * as its last saved value only. + * read/execute to group and other users. * * @param unixPermissions the unixPermissions value to set. * @return the VolumeProperties object itself. @@ -1384,35 +1362,6 @@ public String originatingResourceId() { return this.originatingResourceId; } - /** - * Get the inheritedSizeInBytes property: Space shared by short term clone volume with parent volume in bytes. - * - * @return the inheritedSizeInBytes value. - */ - public Long inheritedSizeInBytes() { - return this.inheritedSizeInBytes; - } - - /** - * Get the language property: Language supported for volume. - * - * @return the language value. - */ - public VolumeLanguage language() { - return this.language; - } - - /** - * Set the language property: Language supported for volume. - * - * @param language the language value to set. - * @return the VolumeProperties object itself. - */ - public VolumeProperties withLanguage(VolumeLanguage language) { - this.language = language; - return this; - } - /** * Validates the instance. * @@ -1463,10 +1412,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { this.networkFeatures == null ? null : this.networkFeatures.toString()); jsonWriter.writeStringField("volumeType", this.volumeType); jsonWriter.writeJsonField("dataProtection", this.dataProtection); - jsonWriter.writeStringField("acceptGrowCapacityPoolForShortTermCloneSplit", - this.acceptGrowCapacityPoolForShortTermCloneSplit == null - ? null - : this.acceptGrowCapacityPoolForShortTermCloneSplit.toString()); jsonWriter.writeBooleanField("isRestoring", this.isRestoring); jsonWriter.writeBooleanField("snapshotDirectoryVisible", this.snapshotDirectoryVisible); jsonWriter.writeBooleanField("kerberosEnabled", this.kerberosEnabled); @@ -1486,6 +1431,8 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeNumberField("coolnessPeriod", this.coolnessPeriod); jsonWriter.writeStringField("coolAccessRetrievalPolicy", this.coolAccessRetrievalPolicy == null ? null : this.coolAccessRetrievalPolicy.toString()); + jsonWriter.writeStringField("coolAccessTieringPolicy", + this.coolAccessTieringPolicy == null ? null : this.coolAccessTieringPolicy.toString()); jsonWriter.writeStringField("unixPermissions", this.unixPermissions); jsonWriter.writeStringField("avsDataStore", this.avsDataStore == null ? null : this.avsDataStore.toString()); jsonWriter.writeBooleanField("isDefaultQuotaEnabled", this.isDefaultQuotaEnabled); @@ -1499,7 +1446,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStringField("enableSubvolumes", this.enableSubvolumes == null ? null : this.enableSubvolumes.toString()); jsonWriter.writeBooleanField("isLargeVolume", this.isLargeVolume); - jsonWriter.writeStringField("language", this.language == null ? null : this.language.toString()); return jsonWriter.writeEndObject(); } @@ -1562,9 +1508,6 @@ public static VolumeProperties fromJson(JsonReader jsonReader) throws IOExceptio deserializedVolumeProperties.volumeType = reader.getString(); } else if ("dataProtection".equals(fieldName)) { deserializedVolumeProperties.dataProtection = VolumePropertiesDataProtection.fromJson(reader); - } else if ("acceptGrowCapacityPoolForShortTermCloneSplit".equals(fieldName)) { - deserializedVolumeProperties.acceptGrowCapacityPoolForShortTermCloneSplit - = AcceptGrowCapacityPoolForShortTermCloneSplit.fromString(reader.getString()); } else if ("isRestoring".equals(fieldName)) { deserializedVolumeProperties.isRestoring = reader.getNullable(JsonReader::getBoolean); } else if ("snapshotDirectoryVisible".equals(fieldName)) { @@ -1600,6 +1543,9 @@ public static VolumeProperties fromJson(JsonReader jsonReader) throws IOExceptio } else if ("coolAccessRetrievalPolicy".equals(fieldName)) { deserializedVolumeProperties.coolAccessRetrievalPolicy = CoolAccessRetrievalPolicy.fromString(reader.getString()); + } else if ("coolAccessTieringPolicy".equals(fieldName)) { + deserializedVolumeProperties.coolAccessTieringPolicy + = CoolAccessTieringPolicy.fromString(reader.getString()); } else if ("unixPermissions".equals(fieldName)) { deserializedVolumeProperties.unixPermissions = reader.getString(); } else if ("cloneProgress".equals(fieldName)) { @@ -1643,10 +1589,6 @@ public static VolumeProperties fromJson(JsonReader jsonReader) throws IOExceptio deserializedVolumeProperties.isLargeVolume = reader.getNullable(JsonReader::getBoolean); } else if ("originatingResourceId".equals(fieldName)) { deserializedVolumeProperties.originatingResourceId = reader.getString(); - } else if ("inheritedSizeInBytes".equals(fieldName)) { - deserializedVolumeProperties.inheritedSizeInBytes = reader.getNullable(JsonReader::getLong); - } else if ("language".equals(fieldName)) { - deserializedVolumeProperties.language = VolumeLanguage.fromString(reader.getString()); } else { reader.skipChildren(); } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/AccountsClientImpl.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/AccountsClientImpl.java index 85d2468a85ef..f36d7ad51743 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/AccountsClientImpl.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/AccountsClientImpl.java @@ -34,6 +34,7 @@ import com.azure.core.util.polling.PollerFlux; import com.azure.core.util.polling.SyncPoller; import com.azure.resourcemanager.netapp.fluent.AccountsClient; +import com.azure.resourcemanager.netapp.fluent.models.GetKeyVaultStatusResponseInner; import com.azure.resourcemanager.netapp.fluent.models.NetAppAccountInner; import com.azure.resourcemanager.netapp.models.ChangeKeyVault; import com.azure.resourcemanager.netapp.models.EncryptionTransitionRequest; @@ -151,7 +152,7 @@ Mono>> transitionToCmk(@HostParam("$host") String endp @Headers({ "Content-Type: application/json" }) @Post("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/getKeyVaultStatus") - @ExpectedResponses({ 202 }) + @ExpectedResponses({ 200, 202 }) @UnexpectedResponseExceptionType(ManagementException.class) Mono>> getChangeKeyVaultInformation(@HostParam("$host") String endpoint, @PathParam("subscriptionId") String subscriptionId, @@ -1829,7 +1830,8 @@ public void transitionToCmk(String resourceGroupName, String accountName, Encryp * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. + * @return result of getKeyVaultStatus with information about how volumes under NetApp account are encrypted along + * with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono>> getChangeKeyVaultInformationWithResponseAsync(String resourceGroupName, @@ -1870,7 +1872,8 @@ private Mono>> getChangeKeyVaultInformationWithRespons * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. + * @return result of getKeyVaultStatus with information about how volumes under NetApp account are encrypted along + * with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono>> getChangeKeyVaultInformationWithResponseAsync(String resourceGroupName, @@ -1908,14 +1911,16 @@ private Mono>> getChangeKeyVaultInformationWithRespons * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of long-running operation. + * @return the {@link PollerFlux} for polling of result of getKeyVaultStatus with information about how volumes + * under NetApp account are encrypted. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, Void> beginGetChangeKeyVaultInformationAsync(String resourceGroupName, - String accountName) { + private PollerFlux, GetKeyVaultStatusResponseInner> + beginGetChangeKeyVaultInformationAsync(String resourceGroupName, String accountName) { Mono>> mono = getChangeKeyVaultInformationWithResponseAsync(resourceGroupName, accountName); - return this.client.getLroResult(mono, this.client.getHttpPipeline(), Void.class, Void.class, + return this.client.getLroResult(mono, + this.client.getHttpPipeline(), GetKeyVaultStatusResponseInner.class, GetKeyVaultStatusResponseInner.class, this.client.getContext()); } @@ -1932,15 +1937,17 @@ private PollerFlux, Void> beginGetChangeKeyVaultInformationAsyn * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of long-running operation. + * @return the {@link PollerFlux} for polling of result of getKeyVaultStatus with information about how volumes + * under NetApp account are encrypted. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, Void> beginGetChangeKeyVaultInformationAsync(String resourceGroupName, - String accountName, Context context) { + private PollerFlux, GetKeyVaultStatusResponseInner> + beginGetChangeKeyVaultInformationAsync(String resourceGroupName, String accountName, Context context) { context = this.client.mergeContext(context); Mono>> mono = getChangeKeyVaultInformationWithResponseAsync(resourceGroupName, accountName, context); - return this.client.getLroResult(mono, this.client.getHttpPipeline(), Void.class, Void.class, + return this.client.getLroResult(mono, + this.client.getHttpPipeline(), GetKeyVaultStatusResponseInner.class, GetKeyVaultStatusResponseInner.class, context); } @@ -1956,11 +1963,12 @@ private PollerFlux, Void> beginGetChangeKeyVaultInformationAsyn * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of long-running operation. + * @return the {@link SyncPoller} for polling of result of getKeyVaultStatus with information about how volumes + * under NetApp account are encrypted. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, Void> beginGetChangeKeyVaultInformation(String resourceGroupName, - String accountName) { + public SyncPoller, GetKeyVaultStatusResponseInner> + beginGetChangeKeyVaultInformation(String resourceGroupName, String accountName) { return this.beginGetChangeKeyVaultInformationAsync(resourceGroupName, accountName).getSyncPoller(); } @@ -1977,11 +1985,12 @@ public SyncPoller, Void> beginGetChangeKeyVaultInformation(Stri * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of long-running operation. + * @return the {@link SyncPoller} for polling of result of getKeyVaultStatus with information about how volumes + * under NetApp account are encrypted. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, Void> beginGetChangeKeyVaultInformation(String resourceGroupName, - String accountName, Context context) { + public SyncPoller, GetKeyVaultStatusResponseInner> + beginGetChangeKeyVaultInformation(String resourceGroupName, String accountName, Context context) { return this.beginGetChangeKeyVaultInformationAsync(resourceGroupName, accountName, context).getSyncPoller(); } @@ -1997,10 +2006,12 @@ public SyncPoller, Void> beginGetChangeKeyVaultInformation(Stri * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. + * @return result of getKeyVaultStatus with information about how volumes under NetApp account are encrypted on + * successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono getChangeKeyVaultInformationAsync(String resourceGroupName, String accountName) { + private Mono getChangeKeyVaultInformationAsync(String resourceGroupName, + String accountName) { return beginGetChangeKeyVaultInformationAsync(resourceGroupName, accountName).last() .flatMap(this.client::getLroFinalResultOrError); } @@ -2018,11 +2029,12 @@ private Mono getChangeKeyVaultInformationAsync(String resourceGroupName, S * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. + * @return result of getKeyVaultStatus with information about how volumes under NetApp account are encrypted on + * successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono getChangeKeyVaultInformationAsync(String resourceGroupName, String accountName, - Context context) { + private Mono getChangeKeyVaultInformationAsync(String resourceGroupName, + String accountName, Context context) { return beginGetChangeKeyVaultInformationAsync(resourceGroupName, accountName, context).last() .flatMap(this.client::getLroFinalResultOrError); } @@ -2039,10 +2051,11 @@ private Mono getChangeKeyVaultInformationAsync(String resourceGroupName, S * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return result of getKeyVaultStatus with information about how volumes under NetApp account are encrypted. */ @ServiceMethod(returns = ReturnType.SINGLE) - public void getChangeKeyVaultInformation(String resourceGroupName, String accountName) { - getChangeKeyVaultInformationAsync(resourceGroupName, accountName).block(); + public GetKeyVaultStatusResponseInner getChangeKeyVaultInformation(String resourceGroupName, String accountName) { + return getChangeKeyVaultInformationAsync(resourceGroupName, accountName).block(); } /** @@ -2058,10 +2071,12 @@ public void getChangeKeyVaultInformation(String resourceGroupName, String accoun * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return result of getKeyVaultStatus with information about how volumes under NetApp account are encrypted. */ @ServiceMethod(returns = ReturnType.SINGLE) - public void getChangeKeyVaultInformation(String resourceGroupName, String accountName, Context context) { - getChangeKeyVaultInformationAsync(resourceGroupName, accountName, context).block(); + public GetKeyVaultStatusResponseInner getChangeKeyVaultInformation(String resourceGroupName, String accountName, + Context context) { + return getChangeKeyVaultInformationAsync(resourceGroupName, accountName, context).block(); } /** diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/AccountsImpl.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/AccountsImpl.java index 87d1c2a4fca0..709303aa2571 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/AccountsImpl.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/AccountsImpl.java @@ -10,10 +10,12 @@ import com.azure.core.util.Context; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.netapp.fluent.AccountsClient; +import com.azure.resourcemanager.netapp.fluent.models.GetKeyVaultStatusResponseInner; import com.azure.resourcemanager.netapp.fluent.models.NetAppAccountInner; import com.azure.resourcemanager.netapp.models.Accounts; import com.azure.resourcemanager.netapp.models.ChangeKeyVault; import com.azure.resourcemanager.netapp.models.EncryptionTransitionRequest; +import com.azure.resourcemanager.netapp.models.GetKeyVaultStatusResponse; import com.azure.resourcemanager.netapp.models.NetAppAccount; public final class AccountsImpl implements Accounts { @@ -95,12 +97,25 @@ public void transitionToCmk(String resourceGroupName, String accountName, Encryp this.serviceClient().transitionToCmk(resourceGroupName, accountName, body, context); } - public void getChangeKeyVaultInformation(String resourceGroupName, String accountName) { - this.serviceClient().getChangeKeyVaultInformation(resourceGroupName, accountName); + public GetKeyVaultStatusResponse getChangeKeyVaultInformation(String resourceGroupName, String accountName) { + GetKeyVaultStatusResponseInner inner + = this.serviceClient().getChangeKeyVaultInformation(resourceGroupName, accountName); + if (inner != null) { + return new GetKeyVaultStatusResponseImpl(inner, this.manager()); + } else { + return null; + } } - public void getChangeKeyVaultInformation(String resourceGroupName, String accountName, Context context) { - this.serviceClient().getChangeKeyVaultInformation(resourceGroupName, accountName, context); + public GetKeyVaultStatusResponse getChangeKeyVaultInformation(String resourceGroupName, String accountName, + Context context) { + GetKeyVaultStatusResponseInner inner + = this.serviceClient().getChangeKeyVaultInformation(resourceGroupName, accountName, context); + if (inner != null) { + return new GetKeyVaultStatusResponseImpl(inner, this.manager()); + } else { + return null; + } } public void changeKeyVault(String resourceGroupName, String accountName) { diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/BackupImpl.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/BackupImpl.java index 7614bcb17e61..89412ac1a317 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/BackupImpl.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/BackupImpl.java @@ -77,10 +77,6 @@ public String backupPolicyResourceId() { return this.innerModel().backupPolicyResourceId(); } - public Boolean isLargeVolume() { - return this.innerModel().isLargeVolume(); - } - public String resourceGroupName() { return resourceGroupName; } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/CapacityPoolImpl.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/CapacityPoolImpl.java index e32e2c32926f..ec6c998cf8c3 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/CapacityPoolImpl.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/CapacityPoolImpl.java @@ -78,10 +78,6 @@ public Float utilizedThroughputMibps() { return this.innerModel().utilizedThroughputMibps(); } - public Float customThroughputMibps() { - return this.innerModel().customThroughputMibps(); - } - public QosType qosType() { return this.innerModel().qosType(); } @@ -222,16 +218,6 @@ public CapacityPoolImpl withTags(Map tags) { } } - public CapacityPoolImpl withCustomThroughputMibps(Float customThroughputMibps) { - if (isInCreateMode()) { - this.innerModel().withCustomThroughputMibps(customThroughputMibps); - return this; - } else { - this.updateBody.withCustomThroughputMibps(customThroughputMibps); - return this; - } - } - public CapacityPoolImpl withQosType(QosType qosType) { if (isInCreateMode()) { this.innerModel().withQosType(qosType); diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/GetKeyVaultStatusResponseImpl.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/GetKeyVaultStatusResponseImpl.java new file mode 100644 index 000000000000..490a00634be1 --- /dev/null +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/GetKeyVaultStatusResponseImpl.java @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.netapp.implementation; + +import com.azure.resourcemanager.netapp.fluent.models.GetKeyVaultStatusResponseInner; +import com.azure.resourcemanager.netapp.models.GetKeyVaultStatusResponse; +import com.azure.resourcemanager.netapp.models.KeyVaultPrivateEndpoint; +import java.util.Collections; +import java.util.List; + +public final class GetKeyVaultStatusResponseImpl implements GetKeyVaultStatusResponse { + private GetKeyVaultStatusResponseInner innerObject; + + private final com.azure.resourcemanager.netapp.NetAppFilesManager serviceManager; + + GetKeyVaultStatusResponseImpl(GetKeyVaultStatusResponseInner innerObject, + com.azure.resourcemanager.netapp.NetAppFilesManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String keyVaultUri() { + return this.innerModel().keyVaultUri(); + } + + public String keyName() { + return this.innerModel().keyName(); + } + + public String keyVaultResourceId() { + return this.innerModel().keyVaultResourceId(); + } + + public List keyVaultPrivateEndpoints() { + List inner = this.innerModel().keyVaultPrivateEndpoints(); + if (inner != null) { + return Collections.unmodifiableList(inner); + } else { + return Collections.emptyList(); + } + } + + public GetKeyVaultStatusResponseInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.netapp.NetAppFilesManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/ListQuotaReportResponseImpl.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/ListQuotaReportResponseImpl.java deleted file mode 100644 index 9114159e75eb..000000000000 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/ListQuotaReportResponseImpl.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.resourcemanager.netapp.implementation; - -import com.azure.resourcemanager.netapp.fluent.models.ListQuotaReportResponseInner; -import com.azure.resourcemanager.netapp.models.ListQuotaReportResponse; -import com.azure.resourcemanager.netapp.models.QuotaReport; -import java.util.Collections; -import java.util.List; - -public final class ListQuotaReportResponseImpl implements ListQuotaReportResponse { - private ListQuotaReportResponseInner innerObject; - - private final com.azure.resourcemanager.netapp.NetAppFilesManager serviceManager; - - ListQuotaReportResponseImpl(ListQuotaReportResponseInner innerObject, - com.azure.resourcemanager.netapp.NetAppFilesManager serviceManager) { - this.innerObject = innerObject; - this.serviceManager = serviceManager; - } - - public List value() { - List inner = this.innerModel().value(); - if (inner != null) { - return Collections.unmodifiableList(inner); - } else { - return Collections.emptyList(); - } - } - - public String nextLink() { - return this.innerModel().nextLink(); - } - - public ListQuotaReportResponseInner innerModel() { - return this.innerObject; - } - - private com.azure.resourcemanager.netapp.NetAppFilesManager manager() { - return this.serviceManager; - } -} diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/NetAppAccountImpl.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/NetAppAccountImpl.java index a220efe91640..221aa025815b 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/NetAppAccountImpl.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/NetAppAccountImpl.java @@ -12,6 +12,7 @@ import com.azure.resourcemanager.netapp.models.ActiveDirectory; import com.azure.resourcemanager.netapp.models.ChangeKeyVault; import com.azure.resourcemanager.netapp.models.EncryptionTransitionRequest; +import com.azure.resourcemanager.netapp.models.GetKeyVaultStatusResponse; import com.azure.resourcemanager.netapp.models.ManagedServiceIdentity; import com.azure.resourcemanager.netapp.models.NetAppAccount; import com.azure.resourcemanager.netapp.models.NetAppAccountPatch; @@ -82,14 +83,6 @@ public Boolean disableShowmount() { return this.innerModel().disableShowmount(); } - public String nfsV4IdDomain() { - return this.innerModel().nfsV4IdDomain(); - } - - public Boolean isMultiAdEnabled() { - return this.innerModel().isMultiAdEnabled(); - } - public Region region() { return Region.fromName(this.regionName()); } @@ -199,12 +192,12 @@ public void transitionToCmk(EncryptionTransitionRequest body, Context context) { serviceManager.accounts().transitionToCmk(resourceGroupName, accountName, body, context); } - public void getChangeKeyVaultInformation() { - serviceManager.accounts().getChangeKeyVaultInformation(resourceGroupName, accountName); + public GetKeyVaultStatusResponse getChangeKeyVaultInformation() { + return serviceManager.accounts().getChangeKeyVaultInformation(resourceGroupName, accountName); } - public void getChangeKeyVaultInformation(Context context) { - serviceManager.accounts().getChangeKeyVaultInformation(resourceGroupName, accountName, context); + public GetKeyVaultStatusResponse getChangeKeyVaultInformation(Context context) { + return serviceManager.accounts().getChangeKeyVaultInformation(resourceGroupName, accountName, context); } public void changeKeyVault() { @@ -265,16 +258,6 @@ public NetAppAccountImpl withEncryption(AccountEncryption encryption) { } } - public NetAppAccountImpl withNfsV4IdDomain(String nfsV4IdDomain) { - if (isInCreateMode()) { - this.innerModel().withNfsV4IdDomain(nfsV4IdDomain); - return this; - } else { - this.updateBody.withNfsV4IdDomain(nfsV4IdDomain); - return this; - } - } - private boolean isInCreateMode() { return this.innerModel().id() == null; } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/NetAppManagementClientImpl.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/NetAppManagementClientImpl.java index 41f6e739b5e4..fc2c55ae85c9 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/NetAppManagementClientImpl.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/NetAppManagementClientImpl.java @@ -409,7 +409,7 @@ public BackupsUnderAccountsClient getBackupsUnderAccounts() { this.defaultPollInterval = defaultPollInterval; this.subscriptionId = subscriptionId; this.endpoint = endpoint; - this.apiVersion = "2024-07-01-preview"; + this.apiVersion = "2024-09-01"; this.operations = new OperationsClientImpl(this); this.netAppResources = new NetAppResourcesClientImpl(this); this.netAppResourceQuotaLimits = new NetAppResourceQuotaLimitsClientImpl(this); diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/VolumeImpl.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/VolumeImpl.java index 14e70d9a7243..415391080d14 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/VolumeImpl.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/VolumeImpl.java @@ -10,19 +10,18 @@ import com.azure.core.util.Context; import com.azure.resourcemanager.netapp.fluent.models.MountTargetProperties; import com.azure.resourcemanager.netapp.fluent.models.VolumeInner; -import com.azure.resourcemanager.netapp.models.AcceptGrowCapacityPoolForShortTermCloneSplit; import com.azure.resourcemanager.netapp.models.AuthorizeRequest; import com.azure.resourcemanager.netapp.models.AvsDataStore; import com.azure.resourcemanager.netapp.models.BreakFileLocksRequest; import com.azure.resourcemanager.netapp.models.BreakReplicationRequest; import com.azure.resourcemanager.netapp.models.ClusterPeerCommandResponse; import com.azure.resourcemanager.netapp.models.CoolAccessRetrievalPolicy; +import com.azure.resourcemanager.netapp.models.CoolAccessTieringPolicy; import com.azure.resourcemanager.netapp.models.EnableSubvolumes; import com.azure.resourcemanager.netapp.models.EncryptionKeySource; import com.azure.resourcemanager.netapp.models.FileAccessLogs; import com.azure.resourcemanager.netapp.models.GetGroupIdListForLdapUserRequest; import com.azure.resourcemanager.netapp.models.GetGroupIdListForLdapUserResponse; -import com.azure.resourcemanager.netapp.models.ListQuotaReportResponse; import com.azure.resourcemanager.netapp.models.NetworkFeatures; import com.azure.resourcemanager.netapp.models.PeerClusterForVolumeMigrationRequest; import com.azure.resourcemanager.netapp.models.PlacementKeyValuePairs; @@ -36,7 +35,6 @@ import com.azure.resourcemanager.netapp.models.SmbNonBrowsable; import com.azure.resourcemanager.netapp.models.SvmPeerCommandResponse; import com.azure.resourcemanager.netapp.models.Volume; -import com.azure.resourcemanager.netapp.models.VolumeLanguage; import com.azure.resourcemanager.netapp.models.VolumePatch; import com.azure.resourcemanager.netapp.models.VolumePatchPropertiesDataProtection; import com.azure.resourcemanager.netapp.models.VolumePatchPropertiesExportPolicy; @@ -181,10 +179,6 @@ public VolumePropertiesDataProtection dataProtection() { return this.innerModel().dataProtection(); } - public AcceptGrowCapacityPoolForShortTermCloneSplit acceptGrowCapacityPoolForShortTermCloneSplit() { - return this.innerModel().acceptGrowCapacityPoolForShortTermCloneSplit(); - } - public Boolean isRestoring() { return this.innerModel().isRestoring(); } @@ -249,6 +243,10 @@ public CoolAccessRetrievalPolicy coolAccessRetrievalPolicy() { return this.innerModel().coolAccessRetrievalPolicy(); } + public CoolAccessTieringPolicy coolAccessTieringPolicy() { + return this.innerModel().coolAccessTieringPolicy(); + } + public String unixPermissions() { return this.innerModel().unixPermissions(); } @@ -339,14 +337,6 @@ public String originatingResourceId() { return this.innerModel().originatingResourceId(); } - public Long inheritedSizeInBytes() { - return this.innerModel().inheritedSizeInBytes(); - } - - public VolumeLanguage language() { - return this.innerModel().language(); - } - public Region region() { return Region.fromName(this.regionName()); } @@ -473,14 +463,6 @@ public void resetCifsPassword(Context context) { serviceManager.volumes().resetCifsPassword(resourceGroupName, accountName, poolName, volumeName, context); } - public void splitCloneFromParent() { - serviceManager.volumes().splitCloneFromParent(resourceGroupName, accountName, poolName, volumeName); - } - - public void splitCloneFromParent(Context context) { - serviceManager.volumes().splitCloneFromParent(resourceGroupName, accountName, poolName, volumeName, context); - } - public void breakFileLocks() { serviceManager.volumes().breakFileLocks(resourceGroupName, accountName, poolName, volumeName); } @@ -500,14 +482,6 @@ public GetGroupIdListForLdapUserResponse listGetGroupIdListForLdapUser(GetGroupI .listGetGroupIdListForLdapUser(resourceGroupName, accountName, poolName, volumeName, body, context); } - public ListQuotaReportResponse listQuotaReport() { - return serviceManager.volumes().listQuotaReport(resourceGroupName, accountName, poolName, volumeName); - } - - public ListQuotaReportResponse listQuotaReport(Context context) { - return serviceManager.volumes().listQuotaReport(resourceGroupName, accountName, poolName, volumeName, context); - } - public void breakReplication() { serviceManager.volumes().breakReplication(resourceGroupName, accountName, poolName, volumeName); } @@ -730,13 +704,6 @@ public VolumeImpl withDataProtection(VolumePropertiesDataProtection dataProtecti return this; } - public VolumeImpl withAcceptGrowCapacityPoolForShortTermCloneSplit( - AcceptGrowCapacityPoolForShortTermCloneSplit acceptGrowCapacityPoolForShortTermCloneSplit) { - this.innerModel() - .withAcceptGrowCapacityPoolForShortTermCloneSplit(acceptGrowCapacityPoolForShortTermCloneSplit); - return this; - } - public VolumeImpl withIsRestoring(Boolean isRestoring) { this.innerModel().withIsRestoring(isRestoring); return this; @@ -847,6 +814,16 @@ public VolumeImpl withCoolAccessRetrievalPolicy(CoolAccessRetrievalPolicy coolAc } } + public VolumeImpl withCoolAccessTieringPolicy(CoolAccessTieringPolicy coolAccessTieringPolicy) { + if (isInCreateMode()) { + this.innerModel().withCoolAccessTieringPolicy(coolAccessTieringPolicy); + return this; + } else { + this.updateBody.withCoolAccessTieringPolicy(coolAccessTieringPolicy); + return this; + } + } + public VolumeImpl withUnixPermissions(String unixPermissions) { if (isInCreateMode()) { this.innerModel().withUnixPermissions(unixPermissions); @@ -922,11 +899,6 @@ public VolumeImpl withIsLargeVolume(Boolean isLargeVolume) { return this; } - public VolumeImpl withLanguage(VolumeLanguage language) { - this.innerModel().withLanguage(language); - return this; - } - public VolumeImpl withUsageThreshold(Long usageThreshold) { this.updateBody.withUsageThreshold(usageThreshold); return this; diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/VolumesClientImpl.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/VolumesClientImpl.java index ed05189f14f5..071d7f856b43 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/VolumesClientImpl.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/VolumesClientImpl.java @@ -36,7 +36,6 @@ import com.azure.resourcemanager.netapp.fluent.VolumesClient; import com.azure.resourcemanager.netapp.fluent.models.ClusterPeerCommandResponseInner; import com.azure.resourcemanager.netapp.fluent.models.GetGroupIdListForLdapUserResponseInner; -import com.azure.resourcemanager.netapp.fluent.models.ListQuotaReportResponseInner; import com.azure.resourcemanager.netapp.fluent.models.ReplicationInner; import com.azure.resourcemanager.netapp.fluent.models.ReplicationStatusInner; import com.azure.resourcemanager.netapp.fluent.models.SvmPeerCommandResponseInner; @@ -172,16 +171,6 @@ Mono>> resetCifsPassword(@HostParam("$host") String en @PathParam("poolName") String poolName, @PathParam("volumeName") String volumeName, @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - @Headers({ "Content-Type: application/json" }) - @Post("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/splitCloneFromParent") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono>> splitCloneFromParent(@HostParam("$host") String endpoint, - @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, @PathParam("accountName") String accountName, - @PathParam("poolName") String poolName, @PathParam("volumeName") String volumeName, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - @Headers({ "Content-Type: application/json" }) @Post("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/breakFileLocks") @ExpectedResponses({ 200, 202 }) @@ -205,16 +194,6 @@ Mono>> listGetGroupIdListForLdapUser(@HostParam("$host @BodyParam("application/json") GetGroupIdListForLdapUserRequest body, @HeaderParam("Accept") String accept, Context context); - @Headers({ "Content-Type: application/json" }) - @Post("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/listQuotaReport") - @ExpectedResponses({ 200, 202 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono>> listQuotaReport(@HostParam("$host") String endpoint, - @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, @PathParam("accountName") String accountName, - @PathParam("poolName") String poolName, @PathParam("volumeName") String volumeName, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - @Headers({ "Content-Type: application/json" }) @Post("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/breakReplication") @ExpectedResponses({ 200, 202 }) @@ -2414,269 +2393,6 @@ public void resetCifsPassword(String resourceGroupName, String accountName, Stri resetCifsPasswordAsync(resourceGroupName, accountName, poolName, volumeName, context).block(); } - /** - * Split clone from parent volume - * - * Split operation to convert clone volume to an independent volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> splitCloneFromParentWithResponseAsync(String resourceGroupName, - String accountName, String poolName, String volumeName) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (accountName == null) { - return Mono.error(new IllegalArgumentException("Parameter accountName is required and cannot be null.")); - } - if (poolName == null) { - return Mono.error(new IllegalArgumentException("Parameter poolName is required and cannot be null.")); - } - if (volumeName == null) { - return Mono.error(new IllegalArgumentException("Parameter volumeName is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext( - context -> service.splitCloneFromParent(this.client.getEndpoint(), this.client.getSubscriptionId(), - resourceGroupName, accountName, poolName, volumeName, this.client.getApiVersion(), accept, context)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Split clone from parent volume - * - * Split operation to convert clone volume to an independent volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> splitCloneFromParentWithResponseAsync(String resourceGroupName, - String accountName, String poolName, String volumeName, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (accountName == null) { - return Mono.error(new IllegalArgumentException("Parameter accountName is required and cannot be null.")); - } - if (poolName == null) { - return Mono.error(new IllegalArgumentException("Parameter poolName is required and cannot be null.")); - } - if (volumeName == null) { - return Mono.error(new IllegalArgumentException("Parameter volumeName is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.splitCloneFromParent(this.client.getEndpoint(), this.client.getSubscriptionId(), - resourceGroupName, accountName, poolName, volumeName, this.client.getApiVersion(), accept, context); - } - - /** - * Split clone from parent volume - * - * Split operation to convert clone volume to an independent volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of long-running operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, Void> beginSplitCloneFromParentAsync(String resourceGroupName, - String accountName, String poolName, String volumeName) { - Mono>> mono - = splitCloneFromParentWithResponseAsync(resourceGroupName, accountName, poolName, volumeName); - return this.client.getLroResult(mono, this.client.getHttpPipeline(), Void.class, Void.class, - this.client.getContext()); - } - - /** - * Split clone from parent volume - * - * Split operation to convert clone volume to an independent volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of long-running operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, Void> beginSplitCloneFromParentAsync(String resourceGroupName, - String accountName, String poolName, String volumeName, Context context) { - context = this.client.mergeContext(context); - Mono>> mono - = splitCloneFromParentWithResponseAsync(resourceGroupName, accountName, poolName, volumeName, context); - return this.client.getLroResult(mono, this.client.getHttpPipeline(), Void.class, Void.class, - context); - } - - /** - * Split clone from parent volume - * - * Split operation to convert clone volume to an independent volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of long-running operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, Void> beginSplitCloneFromParent(String resourceGroupName, String accountName, - String poolName, String volumeName) { - return this.beginSplitCloneFromParentAsync(resourceGroupName, accountName, poolName, volumeName) - .getSyncPoller(); - } - - /** - * Split clone from parent volume - * - * Split operation to convert clone volume to an independent volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of long-running operation. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, Void> beginSplitCloneFromParent(String resourceGroupName, String accountName, - String poolName, String volumeName, Context context) { - return this.beginSplitCloneFromParentAsync(resourceGroupName, accountName, poolName, volumeName, context) - .getSyncPoller(); - } - - /** - * Split clone from parent volume - * - * Split operation to convert clone volume to an independent volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono splitCloneFromParentAsync(String resourceGroupName, String accountName, String poolName, - String volumeName) { - return beginSplitCloneFromParentAsync(resourceGroupName, accountName, poolName, volumeName).last() - .flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Split clone from parent volume - * - * Split operation to convert clone volume to an independent volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono splitCloneFromParentAsync(String resourceGroupName, String accountName, String poolName, - String volumeName, Context context) { - return beginSplitCloneFromParentAsync(resourceGroupName, accountName, poolName, volumeName, context).last() - .flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Split clone from parent volume - * - * Split operation to convert clone volume to an independent volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void splitCloneFromParent(String resourceGroupName, String accountName, String poolName, String volumeName) { - splitCloneFromParentAsync(resourceGroupName, accountName, poolName, volumeName).block(); - } - - /** - * Split clone from parent volume - * - * Split operation to convert clone volume to an independent volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void splitCloneFromParent(String resourceGroupName, String accountName, String poolName, String volumeName, - Context context) { - splitCloneFromParentAsync(resourceGroupName, accountName, poolName, volumeName, context).block(); - } - /** * Break file locks * @@ -3301,273 +3017,6 @@ public GetGroupIdListForLdapUserResponseInner listGetGroupIdListForLdapUser(Stri .block(); } - /** - * Lists Quota Report for the volume - * - * Returns report of quotas for the volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return quota Report for volume along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> listQuotaReportWithResponseAsync(String resourceGroupName, - String accountName, String poolName, String volumeName) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (accountName == null) { - return Mono.error(new IllegalArgumentException("Parameter accountName is required and cannot be null.")); - } - if (poolName == null) { - return Mono.error(new IllegalArgumentException("Parameter poolName is required and cannot be null.")); - } - if (volumeName == null) { - return Mono.error(new IllegalArgumentException("Parameter volumeName is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.listQuotaReport(this.client.getEndpoint(), this.client.getSubscriptionId(), - resourceGroupName, accountName, poolName, volumeName, this.client.getApiVersion(), accept, context)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Lists Quota Report for the volume - * - * Returns report of quotas for the volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return quota Report for volume along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> listQuotaReportWithResponseAsync(String resourceGroupName, - String accountName, String poolName, String volumeName, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (accountName == null) { - return Mono.error(new IllegalArgumentException("Parameter accountName is required and cannot be null.")); - } - if (poolName == null) { - return Mono.error(new IllegalArgumentException("Parameter poolName is required and cannot be null.")); - } - if (volumeName == null) { - return Mono.error(new IllegalArgumentException("Parameter volumeName is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.listQuotaReport(this.client.getEndpoint(), this.client.getSubscriptionId(), resourceGroupName, - accountName, poolName, volumeName, this.client.getApiVersion(), accept, context); - } - - /** - * Lists Quota Report for the volume - * - * Returns report of quotas for the volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of quota Report for volume. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, ListQuotaReportResponseInner> - beginListQuotaReportAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { - Mono>> mono - = listQuotaReportWithResponseAsync(resourceGroupName, accountName, poolName, volumeName); - return this.client.getLroResult(mono, - this.client.getHttpPipeline(), ListQuotaReportResponseInner.class, ListQuotaReportResponseInner.class, - this.client.getContext()); - } - - /** - * Lists Quota Report for the volume - * - * Returns report of quotas for the volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of quota Report for volume. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, ListQuotaReportResponseInner> - beginListQuotaReportAsync(String resourceGroupName, String accountName, String poolName, String volumeName, - Context context) { - context = this.client.mergeContext(context); - Mono>> mono - = listQuotaReportWithResponseAsync(resourceGroupName, accountName, poolName, volumeName, context); - return this.client.getLroResult(mono, - this.client.getHttpPipeline(), ListQuotaReportResponseInner.class, ListQuotaReportResponseInner.class, - context); - } - - /** - * Lists Quota Report for the volume - * - * Returns report of quotas for the volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of quota Report for volume. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, ListQuotaReportResponseInner> - beginListQuotaReport(String resourceGroupName, String accountName, String poolName, String volumeName) { - return this.beginListQuotaReportAsync(resourceGroupName, accountName, poolName, volumeName).getSyncPoller(); - } - - /** - * Lists Quota Report for the volume - * - * Returns report of quotas for the volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of quota Report for volume. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, ListQuotaReportResponseInner> beginListQuotaReport( - String resourceGroupName, String accountName, String poolName, String volumeName, Context context) { - return this.beginListQuotaReportAsync(resourceGroupName, accountName, poolName, volumeName, context) - .getSyncPoller(); - } - - /** - * Lists Quota Report for the volume - * - * Returns report of quotas for the volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return quota Report for volume on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono listQuotaReportAsync(String resourceGroupName, String accountName, - String poolName, String volumeName) { - return beginListQuotaReportAsync(resourceGroupName, accountName, poolName, volumeName).last() - .flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Lists Quota Report for the volume - * - * Returns report of quotas for the volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return quota Report for volume on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono listQuotaReportAsync(String resourceGroupName, String accountName, - String poolName, String volumeName, Context context) { - return beginListQuotaReportAsync(resourceGroupName, accountName, poolName, volumeName, context).last() - .flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Lists Quota Report for the volume - * - * Returns report of quotas for the volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return quota Report for volume. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public ListQuotaReportResponseInner listQuotaReport(String resourceGroupName, String accountName, String poolName, - String volumeName) { - return listQuotaReportAsync(resourceGroupName, accountName, poolName, volumeName).block(); - } - - /** - * Lists Quota Report for the volume - * - * Returns report of quotas for the volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return quota Report for volume. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public ListQuotaReportResponseInner listQuotaReport(String resourceGroupName, String accountName, String poolName, - String volumeName, Context context) { - return listQuotaReportAsync(resourceGroupName, accountName, poolName, volumeName, context).block(); - } - /** * Break volume replication * diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/VolumesImpl.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/VolumesImpl.java index a271be5571ee..22b21792e6b4 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/VolumesImpl.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/implementation/VolumesImpl.java @@ -12,7 +12,6 @@ import com.azure.resourcemanager.netapp.fluent.VolumesClient; import com.azure.resourcemanager.netapp.fluent.models.ClusterPeerCommandResponseInner; import com.azure.resourcemanager.netapp.fluent.models.GetGroupIdListForLdapUserResponseInner; -import com.azure.resourcemanager.netapp.fluent.models.ListQuotaReportResponseInner; import com.azure.resourcemanager.netapp.fluent.models.ReplicationInner; import com.azure.resourcemanager.netapp.fluent.models.ReplicationStatusInner; import com.azure.resourcemanager.netapp.fluent.models.SvmPeerCommandResponseInner; @@ -23,7 +22,6 @@ import com.azure.resourcemanager.netapp.models.ClusterPeerCommandResponse; import com.azure.resourcemanager.netapp.models.GetGroupIdListForLdapUserRequest; import com.azure.resourcemanager.netapp.models.GetGroupIdListForLdapUserResponse; -import com.azure.resourcemanager.netapp.models.ListQuotaReportResponse; import com.azure.resourcemanager.netapp.models.PeerClusterForVolumeMigrationRequest; import com.azure.resourcemanager.netapp.models.PoolChangeRequest; import com.azure.resourcemanager.netapp.models.ReestablishReplicationRequest; @@ -128,15 +126,6 @@ public void resetCifsPassword(String resourceGroupName, String accountName, Stri this.serviceClient().resetCifsPassword(resourceGroupName, accountName, poolName, volumeName, context); } - public void splitCloneFromParent(String resourceGroupName, String accountName, String poolName, String volumeName) { - this.serviceClient().splitCloneFromParent(resourceGroupName, accountName, poolName, volumeName); - } - - public void splitCloneFromParent(String resourceGroupName, String accountName, String poolName, String volumeName, - Context context) { - this.serviceClient().splitCloneFromParent(resourceGroupName, accountName, poolName, volumeName, context); - } - public void breakFileLocks(String resourceGroupName, String accountName, String poolName, String volumeName) { this.serviceClient().breakFileLocks(resourceGroupName, accountName, poolName, volumeName); } @@ -168,28 +157,6 @@ public GetGroupIdListForLdapUserResponse listGetGroupIdListForLdapUser(String re } } - public ListQuotaReportResponse listQuotaReport(String resourceGroupName, String accountName, String poolName, - String volumeName) { - ListQuotaReportResponseInner inner - = this.serviceClient().listQuotaReport(resourceGroupName, accountName, poolName, volumeName); - if (inner != null) { - return new ListQuotaReportResponseImpl(inner, this.manager()); - } else { - return null; - } - } - - public ListQuotaReportResponse listQuotaReport(String resourceGroupName, String accountName, String poolName, - String volumeName, Context context) { - ListQuotaReportResponseInner inner - = this.serviceClient().listQuotaReport(resourceGroupName, accountName, poolName, volumeName, context); - if (inner != null) { - return new ListQuotaReportResponseImpl(inner, this.manager()); - } else { - return null; - } - } - public void breakReplication(String resourceGroupName, String accountName, String poolName, String volumeName) { this.serviceClient().breakReplication(resourceGroupName, accountName, poolName, volumeName); } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/AcceptGrowCapacityPoolForShortTermCloneSplit.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/AcceptGrowCapacityPoolForShortTermCloneSplit.java deleted file mode 100644 index f2bd95ef875b..000000000000 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/AcceptGrowCapacityPoolForShortTermCloneSplit.java +++ /dev/null @@ -1,56 +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.resourcemanager.netapp.models; - -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * acceptGrowCapacityPoolForShortTermCloneSplit - * - * While auto splitting the short term clone volume, if the parent pool does not have enough space to accommodate the - * volume after split, it will be automatically resized, which will lead to increased billing. To accept capacity pool - * size auto grow and create a short term clone volume, set the property as accepted. - */ -public final class AcceptGrowCapacityPoolForShortTermCloneSplit - extends ExpandableStringEnum { - /** - * Static value Accepted for AcceptGrowCapacityPoolForShortTermCloneSplit. - */ - public static final AcceptGrowCapacityPoolForShortTermCloneSplit ACCEPTED = fromString("Accepted"); - - /** - * Static value Declined for AcceptGrowCapacityPoolForShortTermCloneSplit. - */ - public static final AcceptGrowCapacityPoolForShortTermCloneSplit DECLINED = fromString("Declined"); - - /** - * Creates a new instance of AcceptGrowCapacityPoolForShortTermCloneSplit value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Deprecated - public AcceptGrowCapacityPoolForShortTermCloneSplit() { - } - - /** - * Creates or finds a AcceptGrowCapacityPoolForShortTermCloneSplit from its string representation. - * - * @param name a name to look for. - * @return the corresponding AcceptGrowCapacityPoolForShortTermCloneSplit. - */ - public static AcceptGrowCapacityPoolForShortTermCloneSplit fromString(String name) { - return fromString(name, AcceptGrowCapacityPoolForShortTermCloneSplit.class); - } - - /** - * Gets known AcceptGrowCapacityPoolForShortTermCloneSplit values. - * - * @return known AcceptGrowCapacityPoolForShortTermCloneSplit values. - */ - public static Collection values() { - return values(AcceptGrowCapacityPoolForShortTermCloneSplit.class); - } -} diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/Accounts.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/Accounts.java index 3628d34c3999..c58c50361676 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/Accounts.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/Accounts.java @@ -192,8 +192,9 @@ void transitionToCmk(String resourceGroupName, String accountName, EncryptionTra * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return result of getKeyVaultStatus with information about how volumes under NetApp account are encrypted. */ - void getChangeKeyVaultInformation(String resourceGroupName, String accountName); + GetKeyVaultStatusResponse getChangeKeyVaultInformation(String resourceGroupName, String accountName); /** * Get information about how volumes under NetApp account are encrypted. @@ -208,8 +209,10 @@ void transitionToCmk(String resourceGroupName, String accountName, EncryptionTra * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return result of getKeyVaultStatus with information about how volumes under NetApp account are encrypted. */ - void getChangeKeyVaultInformation(String resourceGroupName, String accountName, Context context); + GetKeyVaultStatusResponse getChangeKeyVaultInformation(String resourceGroupName, String accountName, + Context context); /** * Change Key Vault/Managed HSM that is used for encryption of volumes under NetApp account. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/Backup.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/Backup.java index 16b9955038d1..03f8e64bd226 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/Backup.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/Backup.java @@ -119,13 +119,6 @@ public interface Backup { */ String backupPolicyResourceId(); - /** - * Gets the isLargeVolume property: Specifies if the backup is for a large volume. - * - * @return the isLargeVolume value. - */ - Boolean isLargeVolume(); - /** * Gets the name of the resource group. * diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/BackupPolicy.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/BackupPolicy.java index 6a1bc36c1db6..450df2f734f5 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/BackupPolicy.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/BackupPolicy.java @@ -65,7 +65,7 @@ public interface BackupPolicy { SystemData systemData(); /** - * Gets the backupPolicyId property: Backup Policy Resource ID. + * Gets the backupPolicyId property: Backup Policy GUID ID. * * @return the backupPolicyId value. */ diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/BackupPolicyPatch.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/BackupPolicyPatch.java index 7b207f110b94..808fb4577eb8 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/BackupPolicyPatch.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/BackupPolicyPatch.java @@ -103,7 +103,7 @@ public BackupPolicyPatch withTags(Map tags) { } /** - * Get the backupPolicyId property: Backup Policy Resource ID. + * Get the backupPolicyId property: Backup Policy GUID ID. * * @return the backupPolicyId value. */ diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/CapacityPool.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/CapacityPool.java index a4de2a68c44d..439aa151a768 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/CapacityPool.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/CapacityPool.java @@ -106,14 +106,6 @@ public interface CapacityPool { */ Float utilizedThroughputMibps(); - /** - * Gets the customThroughputMibps property: Maximum throughput in MiB/s that can be achieved by this pool and this - * will be accepted as input only for manual qosType pool with Flexible service level. - * - * @return the customThroughputMibps value. - */ - Float customThroughputMibps(); - /** * Gets the qosType property: The qos type of the pool. * @@ -249,8 +241,8 @@ interface WithServiceLevel { * The stage of the CapacityPool definition which contains all the minimum required properties for the resource * to be created, but also allows for any other optional properties to be specified. */ - interface WithCreate extends DefinitionStages.WithTags, DefinitionStages.WithCustomThroughputMibps, - DefinitionStages.WithQosType, DefinitionStages.WithCoolAccess, DefinitionStages.WithEncryptionType { + interface WithCreate extends DefinitionStages.WithTags, DefinitionStages.WithQosType, + DefinitionStages.WithCoolAccess, DefinitionStages.WithEncryptionType { /** * Executes the create request. * @@ -280,21 +272,6 @@ interface WithTags { WithCreate withTags(Map tags); } - /** - * The stage of the CapacityPool definition allowing to specify customThroughputMibps. - */ - interface WithCustomThroughputMibps { - /** - * Specifies the customThroughputMibps property: Maximum throughput in MiB/s that can be achieved by this - * pool and this will be accepted as input only for manual qosType pool with Flexible service level. - * - * @param customThroughputMibps Maximum throughput in MiB/s that can be achieved by this pool and this will - * be accepted as input only for manual qosType pool with Flexible service level. - * @return the next definition stage. - */ - WithCreate withCustomThroughputMibps(Float customThroughputMibps); - } - /** * The stage of the CapacityPool definition allowing to specify qosType. */ @@ -347,8 +324,8 @@ interface WithEncryptionType { /** * The template for CapacityPool update. */ - interface Update extends UpdateStages.WithTags, UpdateStages.WithSize, UpdateStages.WithQosType, - UpdateStages.WithCoolAccess, UpdateStages.WithCustomThroughputMibps { + interface Update + extends UpdateStages.WithTags, UpdateStages.WithSize, UpdateStages.WithQosType, UpdateStages.WithCoolAccess { /** * Executes the update request. * @@ -422,21 +399,6 @@ interface WithCoolAccess { */ Update withCoolAccess(Boolean coolAccess); } - - /** - * The stage of the CapacityPool update allowing to specify customThroughputMibps. - */ - interface WithCustomThroughputMibps { - /** - * Specifies the customThroughputMibps property: Maximum throughput in MiB/s that can be achieved by this - * pool and this will be accepted as input only for manual qosType pool with Flexible service level. - * - * @param customThroughputMibps Maximum throughput in MiB/s that can be achieved by this pool and this will - * be accepted as input only for manual qosType pool with Flexible service level. - * @return the next definition stage. - */ - Update withCustomThroughputMibps(Float customThroughputMibps); - } } /** diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/CapacityPoolPatch.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/CapacityPoolPatch.java index 28787795f85d..e43fd6ab8cbc 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/CapacityPoolPatch.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/CapacityPoolPatch.java @@ -172,31 +172,6 @@ public CapacityPoolPatch withCoolAccess(Boolean coolAccess) { return this; } - /** - * Get the customThroughputMibps property: Maximum throughput in MiB/s that can be achieved by this pool and this - * will be accepted as input only for manual qosType pool with Flexible service level. - * - * @return the customThroughputMibps value. - */ - public Float customThroughputMibps() { - return this.innerProperties() == null ? null : this.innerProperties().customThroughputMibps(); - } - - /** - * Set the customThroughputMibps property: Maximum throughput in MiB/s that can be achieved by this pool and this - * will be accepted as input only for manual qosType pool with Flexible service level. - * - * @param customThroughputMibps the customThroughputMibps value to set. - * @return the CapacityPoolPatch object itself. - */ - public CapacityPoolPatch withCustomThroughputMibps(Float customThroughputMibps) { - if (this.innerProperties() == null) { - this.innerProperties = new PoolPatchProperties(); - } - this.innerProperties().withCustomThroughputMibps(customThroughputMibps); - return this; - } - /** * Validates the instance. * diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/CoolAccessTieringPolicy.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/CoolAccessTieringPolicy.java new file mode 100644 index 000000000000..6dede55008df --- /dev/null +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/CoolAccessTieringPolicy.java @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.netapp.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * coolAccessTieringPolicy determines which cold data blocks are moved to cool tier. The possible values for this field + * are: Auto - Moves cold user data blocks in both the Snapshot copies and the active file system to the cool tier tier. + * This policy is the default. SnapshotOnly - Moves user data blocks of the Volume Snapshot copies that are not + * associated with the active file system to the cool tier. + */ +public final class CoolAccessTieringPolicy extends ExpandableStringEnum { + /** + * Static value Auto for CoolAccessTieringPolicy. + */ + public static final CoolAccessTieringPolicy AUTO = fromString("Auto"); + + /** + * Static value SnapshotOnly for CoolAccessTieringPolicy. + */ + public static final CoolAccessTieringPolicy SNAPSHOT_ONLY = fromString("SnapshotOnly"); + + /** + * Creates a new instance of CoolAccessTieringPolicy value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public CoolAccessTieringPolicy() { + } + + /** + * Creates or finds a CoolAccessTieringPolicy from its string representation. + * + * @param name a name to look for. + * @return the corresponding CoolAccessTieringPolicy. + */ + public static CoolAccessTieringPolicy fromString(String name) { + return fromString(name, CoolAccessTieringPolicy.class); + } + + /** + * Gets known CoolAccessTieringPolicy values. + * + * @return known CoolAccessTieringPolicy values. + */ + public static Collection values() { + return values(CoolAccessTieringPolicy.class); + } +} diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/DestinationReplication.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/DestinationReplication.java deleted file mode 100644 index fb747234bc48..000000000000 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/DestinationReplication.java +++ /dev/null @@ -1,178 +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.resourcemanager.netapp.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; - -/** - * Destination replication properties. - */ -@Fluent -public final class DestinationReplication implements JsonSerializable { - /* - * The resource ID of the remote volume - */ - private String resourceId; - - /* - * Indicates whether the replication is cross zone or cross region. - */ - private ReplicationType replicationType; - - /* - * The remote region for the destination volume. - */ - private String region; - - /* - * The remote zone for the destination volume. - */ - private String zone; - - /** - * Creates an instance of DestinationReplication class. - */ - public DestinationReplication() { - } - - /** - * Get the resourceId property: The resource ID of the remote volume. - * - * @return the resourceId value. - */ - public String resourceId() { - return this.resourceId; - } - - /** - * Set the resourceId property: The resource ID of the remote volume. - * - * @param resourceId the resourceId value to set. - * @return the DestinationReplication object itself. - */ - public DestinationReplication withResourceId(String resourceId) { - this.resourceId = resourceId; - return this; - } - - /** - * Get the replicationType property: Indicates whether the replication is cross zone or cross region. - * - * @return the replicationType value. - */ - public ReplicationType replicationType() { - return this.replicationType; - } - - /** - * Set the replicationType property: Indicates whether the replication is cross zone or cross region. - * - * @param replicationType the replicationType value to set. - * @return the DestinationReplication object itself. - */ - public DestinationReplication withReplicationType(ReplicationType replicationType) { - this.replicationType = replicationType; - return this; - } - - /** - * Get the region property: The remote region for the destination volume. - * - * @return the region value. - */ - public String region() { - return this.region; - } - - /** - * Set the region property: The remote region for the destination volume. - * - * @param region the region value to set. - * @return the DestinationReplication object itself. - */ - public DestinationReplication withRegion(String region) { - this.region = region; - return this; - } - - /** - * Get the zone property: The remote zone for the destination volume. - * - * @return the zone value. - */ - public String zone() { - return this.zone; - } - - /** - * Set the zone property: The remote zone for the destination volume. - * - * @param zone the zone value to set. - * @return the DestinationReplication object itself. - */ - public DestinationReplication withZone(String zone) { - this.zone = zone; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("resourceId", this.resourceId); - jsonWriter.writeStringField("replicationType", - this.replicationType == null ? null : this.replicationType.toString()); - jsonWriter.writeStringField("region", this.region); - jsonWriter.writeStringField("zone", this.zone); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of DestinationReplication from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of DestinationReplication 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 DestinationReplication. - */ - public static DestinationReplication fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - DestinationReplication deserializedDestinationReplication = new DestinationReplication(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("resourceId".equals(fieldName)) { - deserializedDestinationReplication.resourceId = reader.getString(); - } else if ("replicationType".equals(fieldName)) { - deserializedDestinationReplication.replicationType = ReplicationType.fromString(reader.getString()); - } else if ("region".equals(fieldName)) { - deserializedDestinationReplication.region = reader.getString(); - } else if ("zone".equals(fieldName)) { - deserializedDestinationReplication.zone = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedDestinationReplication; - }); - } -} diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/EncryptionIdentity.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/EncryptionIdentity.java index 15b02e5e0e29..2fd76144f364 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/EncryptionIdentity.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/EncryptionIdentity.java @@ -27,11 +27,6 @@ public final class EncryptionIdentity implements JsonSerializable keyVaultPrivateEndpoints(); + + /** + * Gets the inner com.azure.resourcemanager.netapp.fluent.models.GetKeyVaultStatusResponseInner object. + * + * @return the inner object. + */ + GetKeyVaultStatusResponseInner innerModel(); +} diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/ListQuotaReportResponse.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/ListQuotaReportResponse.java deleted file mode 100644 index 743dd7e29be5..000000000000 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/ListQuotaReportResponse.java +++ /dev/null @@ -1,34 +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.resourcemanager.netapp.models; - -import com.azure.resourcemanager.netapp.fluent.models.ListQuotaReportResponseInner; -import java.util.List; - -/** - * An immutable client-side representation of ListQuotaReportResponse. - */ -public interface ListQuotaReportResponse { - /** - * Gets the value property: List of volume quota report records. - * - * @return the value value. - */ - List value(); - - /** - * Gets the nextLink property: URL to get the next set of results. - * - * @return the nextLink value. - */ - String nextLink(); - - /** - * Gets the inner com.azure.resourcemanager.netapp.fluent.models.ListQuotaReportResponseInner object. - * - * @return the inner object. - */ - ListQuotaReportResponseInner innerModel(); -} diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/NetAppAccount.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/NetAppAccount.java index 6a0d646784fe..7da136ac980d 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/NetAppAccount.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/NetAppAccount.java @@ -100,21 +100,6 @@ public interface NetAppAccount { */ Boolean disableShowmount(); - /** - * Gets the nfsV4IdDomain property: Domain for NFSv4 user ID mapping. This property will be set for all NetApp - * accounts in the subscription and region and only affect non ldap NFSv4 volumes. - * - * @return the nfsV4IdDomain value. - */ - String nfsV4IdDomain(); - - /** - * Gets the isMultiAdEnabled property: This will have true value only if account is Multiple AD enabled. - * - * @return the isMultiAdEnabled value. - */ - Boolean isMultiAdEnabled(); - /** * Gets the region of the resource. * @@ -198,9 +183,8 @@ interface WithResourceGroup { * The stage of the NetAppAccount definition which contains all the minimum required properties for the resource * to be created, but also allows for any other optional properties to be specified. */ - interface WithCreate - extends DefinitionStages.WithTags, DefinitionStages.WithIdentity, DefinitionStages.WithActiveDirectories, - DefinitionStages.WithEncryption, DefinitionStages.WithNfsV4IdDomain { + interface WithCreate extends DefinitionStages.WithTags, DefinitionStages.WithIdentity, + DefinitionStages.WithActiveDirectories, DefinitionStages.WithEncryption { /** * Executes the create request. * @@ -268,21 +252,6 @@ interface WithEncryption { */ WithCreate withEncryption(AccountEncryption encryption); } - - /** - * The stage of the NetAppAccount definition allowing to specify nfsV4IdDomain. - */ - interface WithNfsV4IdDomain { - /** - * Specifies the nfsV4IdDomain property: Domain for NFSv4 user ID mapping. This property will be set for all - * NetApp accounts in the subscription and region and only affect non ldap NFSv4 volumes.. - * - * @param nfsV4IdDomain Domain for NFSv4 user ID mapping. This property will be set for all NetApp accounts - * in the subscription and region and only affect non ldap NFSv4 volumes. - * @return the next definition stage. - */ - WithCreate withNfsV4IdDomain(String nfsV4IdDomain); - } } /** @@ -296,7 +265,7 @@ interface WithNfsV4IdDomain { * The template for NetAppAccount update. */ interface Update extends UpdateStages.WithTags, UpdateStages.WithIdentity, UpdateStages.WithActiveDirectories, - UpdateStages.WithEncryption, UpdateStages.WithNfsV4IdDomain { + UpdateStages.WithEncryption { /** * Executes the update request. * @@ -368,21 +337,6 @@ interface WithEncryption { */ Update withEncryption(AccountEncryption encryption); } - - /** - * The stage of the NetAppAccount update allowing to specify nfsV4IdDomain. - */ - interface WithNfsV4IdDomain { - /** - * Specifies the nfsV4IdDomain property: Domain for NFSv4 user ID mapping. This property will be set for all - * NetApp accounts in the subscription and region and only affect non ldap NFSv4 volumes.. - * - * @param nfsV4IdDomain Domain for NFSv4 user ID mapping. This property will be set for all NetApp accounts - * in the subscription and region and only affect non ldap NFSv4 volumes. - * @return the next definition stage. - */ - Update withNfsV4IdDomain(String nfsV4IdDomain); - } } /** @@ -458,8 +412,9 @@ interface WithNfsV4IdDomain { * * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return result of getKeyVaultStatus with information about how volumes under NetApp account are encrypted. */ - void getChangeKeyVaultInformation(); + GetKeyVaultStatusResponse getChangeKeyVaultInformation(); /** * Get information about how volumes under NetApp account are encrypted. @@ -472,8 +427,9 @@ interface WithNfsV4IdDomain { * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return result of getKeyVaultStatus with information about how volumes under NetApp account are encrypted. */ - void getChangeKeyVaultInformation(Context context); + GetKeyVaultStatusResponse getChangeKeyVaultInformation(Context context); /** * Change Key Vault/Managed HSM that is used for encryption of volumes under NetApp account. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/NetAppAccountPatch.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/NetAppAccountPatch.java index ab1b41608a9c..5fc459941670 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/NetAppAccountPatch.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/NetAppAccountPatch.java @@ -192,40 +192,6 @@ public Boolean disableShowmount() { return this.innerProperties() == null ? null : this.innerProperties().disableShowmount(); } - /** - * Get the nfsV4IdDomain property: Domain for NFSv4 user ID mapping. This property will be set for all NetApp - * accounts in the subscription and region and only affect non ldap NFSv4 volumes. - * - * @return the nfsV4IdDomain value. - */ - public String nfsV4IdDomain() { - return this.innerProperties() == null ? null : this.innerProperties().nfsV4IdDomain(); - } - - /** - * Set the nfsV4IdDomain property: Domain for NFSv4 user ID mapping. This property will be set for all NetApp - * accounts in the subscription and region and only affect non ldap NFSv4 volumes. - * - * @param nfsV4IdDomain the nfsV4IdDomain value to set. - * @return the NetAppAccountPatch object itself. - */ - public NetAppAccountPatch withNfsV4IdDomain(String nfsV4IdDomain) { - if (this.innerProperties() == null) { - this.innerProperties = new AccountProperties(); - } - this.innerProperties().withNfsV4IdDomain(nfsV4IdDomain); - return this; - } - - /** - * Get the isMultiAdEnabled property: This will have true value only if account is Multiple AD enabled. - * - * @return the isMultiAdEnabled value. - */ - public Boolean isMultiAdEnabled() { - return this.innerProperties() == null ? null : this.innerProperties().isMultiAdEnabled(); - } - /** * Validates the instance. * diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/QuotaReport.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/QuotaReport.java deleted file mode 100644 index a30e5c5d9e71..000000000000 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/QuotaReport.java +++ /dev/null @@ -1,238 +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.resourcemanager.netapp.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; - -/** - * Quota report record properties. - */ -@Fluent -public final class QuotaReport implements JsonSerializable { - /* - * Type of quota - */ - private Type quotaType; - - /* - * UserID/GroupID/SID based on the quota target type. UserID and groupID can be found by running ‘id’ or ‘getent’ - * command for the user or group and SID can be found by running - */ - private String quotaTarget; - - /* - * Specifies the current usage in kibibytes for the user/group quota. - */ - private Long quotaLimitUsedInKiBs; - - /* - * Specifies the total size limit in kibibytes for the user/group quota. - */ - private Long quotaLimitTotalInKiBs; - - /* - * Percentage of used size compared to total size. - */ - private Float percentageUsed; - - /* - * Flag to indicate whether the quota is derived from default quota. - */ - private Boolean isDerivedQuota; - - /** - * Creates an instance of QuotaReport class. - */ - public QuotaReport() { - } - - /** - * Get the quotaType property: Type of quota. - * - * @return the quotaType value. - */ - public Type quotaType() { - return this.quotaType; - } - - /** - * Set the quotaType property: Type of quota. - * - * @param quotaType the quotaType value to set. - * @return the QuotaReport object itself. - */ - public QuotaReport withQuotaType(Type quotaType) { - this.quotaType = quotaType; - return this; - } - - /** - * Get the quotaTarget property: UserID/GroupID/SID based on the quota target type. UserID and groupID can be found - * by running ‘id’ or ‘getent’ command for the user or group and SID can be found by running <wmic useraccount - * where name='user-name' get sid>. - * - * @return the quotaTarget value. - */ - public String quotaTarget() { - return this.quotaTarget; - } - - /** - * Set the quotaTarget property: UserID/GroupID/SID based on the quota target type. UserID and groupID can be found - * by running ‘id’ or ‘getent’ command for the user or group and SID can be found by running <wmic useraccount - * where name='user-name' get sid>. - * - * @param quotaTarget the quotaTarget value to set. - * @return the QuotaReport object itself. - */ - public QuotaReport withQuotaTarget(String quotaTarget) { - this.quotaTarget = quotaTarget; - return this; - } - - /** - * Get the quotaLimitUsedInKiBs property: Specifies the current usage in kibibytes for the user/group quota. - * - * @return the quotaLimitUsedInKiBs value. - */ - public Long quotaLimitUsedInKiBs() { - return this.quotaLimitUsedInKiBs; - } - - /** - * Set the quotaLimitUsedInKiBs property: Specifies the current usage in kibibytes for the user/group quota. - * - * @param quotaLimitUsedInKiBs the quotaLimitUsedInKiBs value to set. - * @return the QuotaReport object itself. - */ - public QuotaReport withQuotaLimitUsedInKiBs(Long quotaLimitUsedInKiBs) { - this.quotaLimitUsedInKiBs = quotaLimitUsedInKiBs; - return this; - } - - /** - * Get the quotaLimitTotalInKiBs property: Specifies the total size limit in kibibytes for the user/group quota. - * - * @return the quotaLimitTotalInKiBs value. - */ - public Long quotaLimitTotalInKiBs() { - return this.quotaLimitTotalInKiBs; - } - - /** - * Set the quotaLimitTotalInKiBs property: Specifies the total size limit in kibibytes for the user/group quota. - * - * @param quotaLimitTotalInKiBs the quotaLimitTotalInKiBs value to set. - * @return the QuotaReport object itself. - */ - public QuotaReport withQuotaLimitTotalInKiBs(Long quotaLimitTotalInKiBs) { - this.quotaLimitTotalInKiBs = quotaLimitTotalInKiBs; - return this; - } - - /** - * Get the percentageUsed property: Percentage of used size compared to total size. - * - * @return the percentageUsed value. - */ - public Float percentageUsed() { - return this.percentageUsed; - } - - /** - * Set the percentageUsed property: Percentage of used size compared to total size. - * - * @param percentageUsed the percentageUsed value to set. - * @return the QuotaReport object itself. - */ - public QuotaReport withPercentageUsed(Float percentageUsed) { - this.percentageUsed = percentageUsed; - return this; - } - - /** - * Get the isDerivedQuota property: Flag to indicate whether the quota is derived from default quota. - * - * @return the isDerivedQuota value. - */ - public Boolean isDerivedQuota() { - return this.isDerivedQuota; - } - - /** - * Set the isDerivedQuota property: Flag to indicate whether the quota is derived from default quota. - * - * @param isDerivedQuota the isDerivedQuota value to set. - * @return the QuotaReport object itself. - */ - public QuotaReport withIsDerivedQuota(Boolean isDerivedQuota) { - this.isDerivedQuota = isDerivedQuota; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("quotaType", this.quotaType == null ? null : this.quotaType.toString()); - jsonWriter.writeStringField("quotaTarget", this.quotaTarget); - jsonWriter.writeNumberField("quotaLimitUsedInKiBs", this.quotaLimitUsedInKiBs); - jsonWriter.writeNumberField("quotaLimitTotalInKiBs", this.quotaLimitTotalInKiBs); - jsonWriter.writeNumberField("percentageUsed", this.percentageUsed); - jsonWriter.writeBooleanField("isDerivedQuota", this.isDerivedQuota); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of QuotaReport from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of QuotaReport 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 QuotaReport. - */ - public static QuotaReport fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - QuotaReport deserializedQuotaReport = new QuotaReport(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("quotaType".equals(fieldName)) { - deserializedQuotaReport.quotaType = Type.fromString(reader.getString()); - } else if ("quotaTarget".equals(fieldName)) { - deserializedQuotaReport.quotaTarget = reader.getString(); - } else if ("quotaLimitUsedInKiBs".equals(fieldName)) { - deserializedQuotaReport.quotaLimitUsedInKiBs = reader.getNullable(JsonReader::getLong); - } else if ("quotaLimitTotalInKiBs".equals(fieldName)) { - deserializedQuotaReport.quotaLimitTotalInKiBs = reader.getNullable(JsonReader::getLong); - } else if ("percentageUsed".equals(fieldName)) { - deserializedQuotaReport.percentageUsed = reader.getNullable(JsonReader::getFloat); - } else if ("isDerivedQuota".equals(fieldName)) { - deserializedQuotaReport.isDerivedQuota = reader.getNullable(JsonReader::getBoolean); - } else { - reader.skipChildren(); - } - } - - return deserializedQuotaReport; - }); - } -} diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/ReplicationObject.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/ReplicationObject.java index 2e0d13254be4..5667c07c15b7 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/ReplicationObject.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/ReplicationObject.java @@ -10,7 +10,6 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.List; /** * Replication properties. @@ -47,11 +46,6 @@ public final class ReplicationObject implements JsonSerializable destinationReplications; - /** * Creates an instance of ReplicationObject class. */ @@ -173,15 +167,6 @@ public ReplicationObject withRemoteVolumeRegion(String remoteVolumeRegion) { return this; } - /** - * Get the destinationReplications property: A list of destination replications. - * - * @return the destinationReplications value. - */ - public List destinationReplications() { - return this.destinationReplications; - } - /** * Validates the instance. * @@ -191,9 +176,6 @@ public void validate() { if (remotePath() != null) { remotePath().validate(); } - if (destinationReplications() != null) { - destinationReplications().forEach(e -> e.validate()); - } } /** @@ -239,10 +221,6 @@ public static ReplicationObject fromJson(JsonReader jsonReader) throws IOExcepti deserializedReplicationObject.remotePath = RemotePath.fromJson(reader); } else if ("remoteVolumeRegion".equals(fieldName)) { deserializedReplicationObject.remoteVolumeRegion = reader.getString(); - } else if ("destinationReplications".equals(fieldName)) { - List destinationReplications - = reader.readArray(reader1 -> DestinationReplication.fromJson(reader1)); - deserializedReplicationObject.destinationReplications = destinationReplications; } else { reader.skipChildren(); } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/ReplicationType.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/ReplicationType.java deleted file mode 100644 index 36f09f42710b..000000000000 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/ReplicationType.java +++ /dev/null @@ -1,51 +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.resourcemanager.netapp.models; - -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * Indicates whether the replication is cross zone or cross region. - */ -public final class ReplicationType extends ExpandableStringEnum { - /** - * Static value CrossRegionReplication for ReplicationType. - */ - public static final ReplicationType CROSS_REGION_REPLICATION = fromString("CrossRegionReplication"); - - /** - * Static value CrossZoneReplication for ReplicationType. - */ - public static final ReplicationType CROSS_ZONE_REPLICATION = fromString("CrossZoneReplication"); - - /** - * Creates a new instance of ReplicationType value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Deprecated - public ReplicationType() { - } - - /** - * Creates or finds a ReplicationType from its string representation. - * - * @param name a name to look for. - * @return the corresponding ReplicationType. - */ - public static ReplicationType fromString(String name) { - return fromString(name, ReplicationType.class); - } - - /** - * Gets known ReplicationType values. - * - * @return known ReplicationType values. - */ - public static Collection values() { - return values(ReplicationType.class); - } -} diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/ServiceLevel.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/ServiceLevel.java index e4f0cb97a054..50199244bda4 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/ServiceLevel.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/ServiceLevel.java @@ -33,11 +33,6 @@ public final class ServiceLevel extends ExpandableStringEnum { */ public static final ServiceLevel STANDARD_ZRS = fromString("StandardZRS"); - /** - * Static value Flexible for ServiceLevel. - */ - public static final ServiceLevel FLEXIBLE = fromString("Flexible"); - /** * Creates a new instance of ServiceLevel value. * diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/Type.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/Type.java index abe9a850b6b0..7e6c467bdb64 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/Type.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/Type.java @@ -10,7 +10,7 @@ /** * quotaType * - * Type of quota rule. + * Type of quota. */ public final class Type extends ExpandableStringEnum { /** diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/Volume.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/Volume.java index 8b14261d52a2..48d9c7d66fce 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/Volume.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/Volume.java @@ -97,7 +97,7 @@ public interface Volume { /** * Gets the usageThreshold property: Maximum storage quota allowed for a file system in bytes. This is a soft quota * used for alerting only. For regular volumes, valid values are in the range 50GiB to 100TiB. For large volumes, - * valid values are in the range 100TiB to 1PiB, and on an exceptional basis, from to 2400GiB to 2400TiB. Values + * valid values are in the range 100TiB to 500TiB, and on an exceptional basis, from to 2400GiB to 2400TiB. Values * expressed in bytes as multiples of 1 GiB. * * @return the usageThreshold value. @@ -202,7 +202,7 @@ public interface Volume { /** * Gets the volumeType property: What type of volume is this. For destination volumes in Cross Region Replication, - * set type to DataProtection. For creating clone volume, set type to ShortTermClone. + * set type to DataProtection. * * @return the volumeType value. */ @@ -216,16 +216,6 @@ public interface Volume { */ VolumePropertiesDataProtection dataProtection(); - /** - * Gets the acceptGrowCapacityPoolForShortTermCloneSplit property: While auto splitting the short term clone volume, - * if the parent pool does not have enough space to accommodate the volume after split, it will be automatically - * resized, which will lead to increased billing. To accept capacity pool size auto grow and create a short term - * clone volume, set the property as accepted. - * - * @return the acceptGrowCapacityPoolForShortTermCloneSplit value. - */ - AcceptGrowCapacityPoolForShortTermCloneSplit acceptGrowCapacityPoolForShortTermCloneSplit(); - /** * Gets the isRestoring property: Restoring. * @@ -357,15 +347,22 @@ public interface Volume { */ CoolAccessRetrievalPolicy coolAccessRetrievalPolicy(); + /** + * Gets the coolAccessTieringPolicy property: coolAccessTieringPolicy determines which cold data blocks are moved to + * cool tier. The possible values for this field are: Auto - Moves cold user data blocks in both the Snapshot copies + * and the active file system to the cool tier tier. This policy is the default. SnapshotOnly - Moves user data + * blocks of the Volume Snapshot copies that are not associated with the active file system to the cool tier. + * + * @return the coolAccessTieringPolicy value. + */ + CoolAccessTieringPolicy coolAccessTieringPolicy(); + /** * Gets the unixPermissions property: UNIX permissions for NFS volume accepted in octal 4 digit format. First digit * selects the set user ID(4), set group ID (2) and sticky (1) attributes. Second digit selects permission for the * owner of the file: read (4), write (2) and execute (1). Third selects permissions for other users in the same * group. the fourth for other users not in the group. 0755 - gives read/write/execute permissions to owner and - * read/execute to group and other users. Avoid passing null value for unixPermissions in volume update operation, - * As per the behavior, If Null value is passed then user-visible unixPermissions value will became null, and user - * will not be able to get unixPermissions value. On safer side, actual unixPermissions value on volume will remain - * as its last saved value only. + * read/execute to group and other users. * * @return the unixPermissions value. */ @@ -515,20 +512,6 @@ public interface Volume { */ String originatingResourceId(); - /** - * Gets the inheritedSizeInBytes property: Space shared by short term clone volume with parent volume in bytes. - * - * @return the inheritedSizeInBytes value. - */ - Long inheritedSizeInBytes(); - - /** - * Gets the language property: Language supported for volume. - * - * @return the language value. - */ - VolumeLanguage language(); - /** * Gets the region of the resource. * @@ -632,12 +615,12 @@ interface WithUsageThreshold { /** * Specifies the usageThreshold property: Maximum storage quota allowed for a file system in bytes. This is * a soft quota used for alerting only. For regular volumes, valid values are in the range 50GiB to 100TiB. - * For large volumes, valid values are in the range 100TiB to 1PiB, and on an exceptional basis, from to + * For large volumes, valid values are in the range 100TiB to 500TiB, and on an exceptional basis, from to * 2400GiB to 2400TiB. Values expressed in bytes as multiples of 1 GiB.. * * @param usageThreshold Maximum storage quota allowed for a file system in bytes. This is a soft quota used * for alerting only. For regular volumes, valid values are in the range 50GiB to 100TiB. For large volumes, - * valid values are in the range 100TiB to 1PiB, and on an exceptional basis, from to 2400GiB to 2400TiB. + * valid values are in the range 100TiB to 500TiB, and on an exceptional basis, from to 2400GiB to 2400TiB. * Values expressed in bytes as multiples of 1 GiB. * @return the next definition stage. */ @@ -667,19 +650,20 @@ interface WithCreate extends DefinitionStages.WithTags, DefinitionStages.WithZon DefinitionStages.WithServiceLevel, DefinitionStages.WithExportPolicy, DefinitionStages.WithProtocolTypes, DefinitionStages.WithSnapshotId, DefinitionStages.WithDeleteBaseSnapshot, DefinitionStages.WithBackupId, DefinitionStages.WithNetworkFeatures, DefinitionStages.WithVolumeType, DefinitionStages.WithDataProtection, - DefinitionStages.WithAcceptGrowCapacityPoolForShortTermCloneSplit, DefinitionStages.WithIsRestoring, - DefinitionStages.WithSnapshotDirectoryVisible, DefinitionStages.WithKerberosEnabled, - DefinitionStages.WithSecurityStyle, DefinitionStages.WithSmbEncryption, - DefinitionStages.WithSmbAccessBasedEnumeration, DefinitionStages.WithSmbNonBrowsable, - DefinitionStages.WithSmbContinuouslyAvailable, DefinitionStages.WithThroughputMibps, - DefinitionStages.WithEncryptionKeySource, DefinitionStages.WithKeyVaultPrivateEndpointResourceId, - DefinitionStages.WithLdapEnabled, DefinitionStages.WithCoolAccess, DefinitionStages.WithCoolnessPeriod, - DefinitionStages.WithCoolAccessRetrievalPolicy, DefinitionStages.WithUnixPermissions, - DefinitionStages.WithAvsDataStore, DefinitionStages.WithIsDefaultQuotaEnabled, - DefinitionStages.WithDefaultUserQuotaInKiBs, DefinitionStages.WithDefaultGroupQuotaInKiBs, - DefinitionStages.WithCapacityPoolResourceId, DefinitionStages.WithProximityPlacementGroup, - DefinitionStages.WithVolumeSpecName, DefinitionStages.WithPlacementRules, - DefinitionStages.WithEnableSubvolumes, DefinitionStages.WithIsLargeVolume, DefinitionStages.WithLanguage { + DefinitionStages.WithIsRestoring, DefinitionStages.WithSnapshotDirectoryVisible, + DefinitionStages.WithKerberosEnabled, DefinitionStages.WithSecurityStyle, + DefinitionStages.WithSmbEncryption, DefinitionStages.WithSmbAccessBasedEnumeration, + DefinitionStages.WithSmbNonBrowsable, DefinitionStages.WithSmbContinuouslyAvailable, + DefinitionStages.WithThroughputMibps, DefinitionStages.WithEncryptionKeySource, + DefinitionStages.WithKeyVaultPrivateEndpointResourceId, DefinitionStages.WithLdapEnabled, + DefinitionStages.WithCoolAccess, DefinitionStages.WithCoolnessPeriod, + DefinitionStages.WithCoolAccessRetrievalPolicy, DefinitionStages.WithCoolAccessTieringPolicy, + DefinitionStages.WithUnixPermissions, DefinitionStages.WithAvsDataStore, + DefinitionStages.WithIsDefaultQuotaEnabled, DefinitionStages.WithDefaultUserQuotaInKiBs, + DefinitionStages.WithDefaultGroupQuotaInKiBs, DefinitionStages.WithCapacityPoolResourceId, + DefinitionStages.WithProximityPlacementGroup, DefinitionStages.WithVolumeSpecName, + DefinitionStages.WithPlacementRules, DefinitionStages.WithEnableSubvolumes, + DefinitionStages.WithIsLargeVolume { /** * Executes the create request. * @@ -823,10 +807,10 @@ interface WithNetworkFeatures { interface WithVolumeType { /** * Specifies the volumeType property: What type of volume is this. For destination volumes in Cross Region - * Replication, set type to DataProtection. For creating clone volume, set type to ShortTermClone. + * Replication, set type to DataProtection. * * @param volumeType What type of volume is this. For destination volumes in Cross Region Replication, set - * type to DataProtection. For creating clone volume, set type to ShortTermClone. + * type to DataProtection. * @return the next definition stage. */ WithCreate withVolumeType(String volumeType); @@ -847,26 +831,6 @@ interface WithDataProtection { WithCreate withDataProtection(VolumePropertiesDataProtection dataProtection); } - /** - * The stage of the Volume definition allowing to specify acceptGrowCapacityPoolForShortTermCloneSplit. - */ - interface WithAcceptGrowCapacityPoolForShortTermCloneSplit { - /** - * Specifies the acceptGrowCapacityPoolForShortTermCloneSplit property: While auto splitting the short term - * clone volume, if the parent pool does not have enough space to accommodate the volume after split, it - * will be automatically resized, which will lead to increased billing. To accept capacity pool size auto - * grow and create a short term clone volume, set the property as accepted.. - * - * @param acceptGrowCapacityPoolForShortTermCloneSplit While auto splitting the short term clone volume, if - * the parent pool does not have enough space to accommodate the volume after split, it will be - * automatically resized, which will lead to increased billing. To accept capacity pool size auto grow and - * create a short term clone volume, set the property as accepted. - * @return the next definition stage. - */ - WithCreate withAcceptGrowCapacityPoolForShortTermCloneSplit( - AcceptGrowCapacityPoolForShortTermCloneSplit acceptGrowCapacityPoolForShortTermCloneSplit); - } - /** * The stage of the Volume definition allowing to specify isRestoring. */ @@ -1101,6 +1065,27 @@ interface WithCoolAccessRetrievalPolicy { WithCreate withCoolAccessRetrievalPolicy(CoolAccessRetrievalPolicy coolAccessRetrievalPolicy); } + /** + * The stage of the Volume definition allowing to specify coolAccessTieringPolicy. + */ + interface WithCoolAccessTieringPolicy { + /** + * Specifies the coolAccessTieringPolicy property: coolAccessTieringPolicy determines which cold data blocks + * are moved to cool tier. The possible values for this field are: Auto - Moves cold user data blocks in + * both the Snapshot copies and the active file system to the cool tier tier. This policy is the default. + * SnapshotOnly - Moves user data blocks of the Volume Snapshot copies that are not associated with the + * active file system to the cool tier.. + * + * @param coolAccessTieringPolicy coolAccessTieringPolicy determines which cold data blocks are moved to + * cool tier. The possible values for this field are: Auto - Moves cold user data blocks in both the + * Snapshot copies and the active file system to the cool tier tier. This policy is the default. + * SnapshotOnly - Moves user data blocks of the Volume Snapshot copies that are not associated with the + * active file system to the cool tier. + * @return the next definition stage. + */ + WithCreate withCoolAccessTieringPolicy(CoolAccessTieringPolicy coolAccessTieringPolicy); + } + /** * The stage of the Volume definition allowing to specify unixPermissions. */ @@ -1110,19 +1095,13 @@ interface WithUnixPermissions { * First digit selects the set user ID(4), set group ID (2) and sticky (1) attributes. Second digit selects * permission for the owner of the file: read (4), write (2) and execute (1). Third selects permissions for * other users in the same group. the fourth for other users not in the group. 0755 - gives - * read/write/execute permissions to owner and read/execute to group and other users. Avoid passing null - * value for unixPermissions in volume update operation, As per the behavior, If Null value is passed then - * user-visible unixPermissions value will became null, and user will not be able to get unixPermissions - * value. On safer side, actual unixPermissions value on volume will remain as its last saved value only.. + * read/write/execute permissions to owner and read/execute to group and other users.. * * @param unixPermissions UNIX permissions for NFS volume accepted in octal 4 digit format. First digit * selects the set user ID(4), set group ID (2) and sticky (1) attributes. Second digit selects permission * for the owner of the file: read (4), write (2) and execute (1). Third selects permissions for other users * in the same group. the fourth for other users not in the group. 0755 - gives read/write/execute - * permissions to owner and read/execute to group and other users. Avoid passing null value for - * unixPermissions in volume update operation, As per the behavior, If Null value is passed then - * user-visible unixPermissions value will became null, and user will not be able to get unixPermissions - * value. On safer side, actual unixPermissions value on volume will remain as its last saved value only. + * permissions to owner and read/execute to group and other users. * @return the next definition stage. */ WithCreate withUnixPermissions(String unixPermissions); @@ -1267,19 +1246,6 @@ interface WithIsLargeVolume { */ WithCreate withIsLargeVolume(Boolean isLargeVolume); } - - /** - * The stage of the Volume definition allowing to specify language. - */ - interface WithLanguage { - /** - * Specifies the language property: Language supported for volume.. - * - * @param language Language supported for volume. - * @return the next definition stage. - */ - WithCreate withLanguage(VolumeLanguage language); - } } /** @@ -1297,8 +1263,9 @@ interface Update extends UpdateStages.WithTags, UpdateStages.WithServiceLevel, U UpdateStages.WithDataProtection, UpdateStages.WithIsDefaultQuotaEnabled, UpdateStages.WithDefaultUserQuotaInKiBs, UpdateStages.WithDefaultGroupQuotaInKiBs, UpdateStages.WithUnixPermissions, UpdateStages.WithCoolAccess, UpdateStages.WithCoolnessPeriod, - UpdateStages.WithCoolAccessRetrievalPolicy, UpdateStages.WithSnapshotDirectoryVisible, - UpdateStages.WithSmbAccessBasedEnumeration, UpdateStages.WithSmbNonBrowsable { + UpdateStages.WithCoolAccessRetrievalPolicy, UpdateStages.WithCoolAccessTieringPolicy, + UpdateStages.WithSnapshotDirectoryVisible, UpdateStages.WithSmbAccessBasedEnumeration, + UpdateStages.WithSmbNonBrowsable { /** * Executes the update request. * @@ -1352,12 +1319,12 @@ interface WithUsageThreshold { /** * Specifies the usageThreshold property: Maximum storage quota allowed for a file system in bytes. This is * a soft quota used for alerting only. For regular volumes, valid values are in the range 50GiB to 100TiB. - * For large volumes, valid values are in the range 100TiB to 1PiB, and on an exceptional basis, from to + * For large volumes, valid values are in the range 100TiB to 500TiB, and on an exceptional basis, from to * 2400GiB to 2400TiB. Values expressed in bytes as multiples of 1 GiB.. * * @param usageThreshold Maximum storage quota allowed for a file system in bytes. This is a soft quota used * for alerting only. For regular volumes, valid values are in the range 50GiB to 100TiB. For large volumes, - * valid values are in the range 100TiB to 1PiB, and on an exceptional basis, from to 2400GiB to 2400TiB. + * valid values are in the range 100TiB to 500TiB, and on an exceptional basis, from to 2400GiB to 2400TiB. * Values expressed in bytes as multiples of 1 GiB. * @return the next definition stage. */ @@ -1539,6 +1506,27 @@ interface WithCoolAccessRetrievalPolicy { Update withCoolAccessRetrievalPolicy(CoolAccessRetrievalPolicy coolAccessRetrievalPolicy); } + /** + * The stage of the Volume update allowing to specify coolAccessTieringPolicy. + */ + interface WithCoolAccessTieringPolicy { + /** + * Specifies the coolAccessTieringPolicy property: coolAccessTieringPolicy determines which cold data blocks + * are moved to cool tier. The possible values for this field are: Auto - Moves cold user data blocks in + * both the Snapshot copies and the active file system to the cool tier tier. This policy is the default. + * SnapshotOnly - Moves user data blocks of the Volume Snapshot copies that are not associated with the + * active file system to the cool tier.. + * + * @param coolAccessTieringPolicy coolAccessTieringPolicy determines which cold data blocks are moved to + * cool tier. The possible values for this field are: Auto - Moves cold user data blocks in both the + * Snapshot copies and the active file system to the cool tier tier. This policy is the default. + * SnapshotOnly - Moves user data blocks of the Volume Snapshot copies that are not associated with the + * active file system to the cool tier. + * @return the next definition stage. + */ + Update withCoolAccessTieringPolicy(CoolAccessTieringPolicy coolAccessTieringPolicy); + } + /** * The stage of the Volume update allowing to specify snapshotDirectoryVisible. */ @@ -1671,28 +1659,6 @@ interface WithSmbNonBrowsable { */ void resetCifsPassword(Context context); - /** - * Split clone from parent volume - * - * Split operation to convert clone volume to an independent volume. - * - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - void splitCloneFromParent(); - - /** - * Split clone from parent volume - * - * Split operation to convert clone volume to an independent volume. - * - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - void splitCloneFromParent(Context context); - /** * Break file locks * @@ -1744,30 +1710,6 @@ interface WithSmbNonBrowsable { GetGroupIdListForLdapUserResponse listGetGroupIdListForLdapUser(GetGroupIdListForLdapUserRequest body, Context context); - /** - * Lists Quota Report for the volume - * - * Returns report of quotas for the volume. - * - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return quota Report for volume. - */ - ListQuotaReportResponse listQuotaReport(); - - /** - * Lists Quota Report for the volume - * - * Returns report of quotas for the volume. - * - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return quota Report for volume. - */ - ListQuotaReportResponse listQuotaReport(Context context); - /** * Break volume replication * diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/VolumeGroupVolumeProperties.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/VolumeGroupVolumeProperties.java index bf61333f6a7e..5571ccacfb0d 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/VolumeGroupVolumeProperties.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/VolumeGroupVolumeProperties.java @@ -204,7 +204,7 @@ public VolumeGroupVolumeProperties withServiceLevel(ServiceLevel serviceLevel) { /** * Get the usageThreshold property: Maximum storage quota allowed for a file system in bytes. This is a soft quota * used for alerting only. For regular volumes, valid values are in the range 50GiB to 100TiB. For large volumes, - * valid values are in the range 100TiB to 1PiB, and on an exceptional basis, from to 2400GiB to 2400TiB. Values + * valid values are in the range 100TiB to 500TiB, and on an exceptional basis, from to 2400GiB to 2400TiB. Values * expressed in bytes as multiples of 1 GiB. * * @return the usageThreshold value. @@ -216,7 +216,7 @@ public long usageThreshold() { /** * Set the usageThreshold property: Maximum storage quota allowed for a file system in bytes. This is a soft quota * used for alerting only. For regular volumes, valid values are in the range 50GiB to 100TiB. For large volumes, - * valid values are in the range 100TiB to 1PiB, and on an exceptional basis, from to 2400GiB to 2400TiB. Values + * valid values are in the range 100TiB to 500TiB, and on an exceptional basis, from to 2400GiB to 2400TiB. Values * expressed in bytes as multiples of 1 GiB. * * @param usageThreshold the usageThreshold value to set. @@ -455,7 +455,7 @@ public List mountTargets() { /** * Get the volumeType property: What type of volume is this. For destination volumes in Cross Region Replication, - * set type to DataProtection. For creating clone volume, set type to ShortTermClone. + * set type to DataProtection. * * @return the volumeType value. */ @@ -465,7 +465,7 @@ public String volumeType() { /** * Set the volumeType property: What type of volume is this. For destination volumes in Cross Region Replication, - * set type to DataProtection. For creating clone volume, set type to ShortTermClone. + * set type to DataProtection. * * @param volumeType the volumeType value to set. * @return the VolumeGroupVolumeProperties object itself. @@ -503,40 +503,6 @@ public VolumeGroupVolumeProperties withDataProtection(VolumePropertiesDataProtec return this; } - /** - * Get the acceptGrowCapacityPoolForShortTermCloneSplit property: While auto splitting the short term clone volume, - * if the parent pool does not have enough space to accommodate the volume after split, it will be automatically - * resized, which will lead to increased billing. To accept capacity pool size auto grow and create a short term - * clone volume, set the property as accepted. - * - * @return the acceptGrowCapacityPoolForShortTermCloneSplit value. - */ - public AcceptGrowCapacityPoolForShortTermCloneSplit acceptGrowCapacityPoolForShortTermCloneSplit() { - return this.innerProperties() == null - ? null - : this.innerProperties().acceptGrowCapacityPoolForShortTermCloneSplit(); - } - - /** - * Set the acceptGrowCapacityPoolForShortTermCloneSplit property: While auto splitting the short term clone volume, - * if the parent pool does not have enough space to accommodate the volume after split, it will be automatically - * resized, which will lead to increased billing. To accept capacity pool size auto grow and create a short term - * clone volume, set the property as accepted. - * - * @param acceptGrowCapacityPoolForShortTermCloneSplit the acceptGrowCapacityPoolForShortTermCloneSplit value to - * set. - * @return the VolumeGroupVolumeProperties object itself. - */ - public VolumeGroupVolumeProperties withAcceptGrowCapacityPoolForShortTermCloneSplit( - AcceptGrowCapacityPoolForShortTermCloneSplit acceptGrowCapacityPoolForShortTermCloneSplit) { - if (this.innerProperties() == null) { - this.innerProperties = new VolumeProperties(); - } - this.innerProperties() - .withAcceptGrowCapacityPoolForShortTermCloneSplit(acceptGrowCapacityPoolForShortTermCloneSplit); - return this; - } - /** * Get the isRestoring property: Restoring. * @@ -930,15 +896,41 @@ public CoolAccessRetrievalPolicy coolAccessRetrievalPolicy() { return this; } + /** + * Get the coolAccessTieringPolicy property: coolAccessTieringPolicy determines which cold data blocks are moved to + * cool tier. The possible values for this field are: Auto - Moves cold user data blocks in both the Snapshot copies + * and the active file system to the cool tier tier. This policy is the default. SnapshotOnly - Moves user data + * blocks of the Volume Snapshot copies that are not associated with the active file system to the cool tier. + * + * @return the coolAccessTieringPolicy value. + */ + public CoolAccessTieringPolicy coolAccessTieringPolicy() { + return this.innerProperties() == null ? null : this.innerProperties().coolAccessTieringPolicy(); + } + + /** + * Set the coolAccessTieringPolicy property: coolAccessTieringPolicy determines which cold data blocks are moved to + * cool tier. The possible values for this field are: Auto - Moves cold user data blocks in both the Snapshot copies + * and the active file system to the cool tier tier. This policy is the default. SnapshotOnly - Moves user data + * blocks of the Volume Snapshot copies that are not associated with the active file system to the cool tier. + * + * @param coolAccessTieringPolicy the coolAccessTieringPolicy value to set. + * @return the VolumeGroupVolumeProperties object itself. + */ + public VolumeGroupVolumeProperties withCoolAccessTieringPolicy(CoolAccessTieringPolicy coolAccessTieringPolicy) { + if (this.innerProperties() == null) { + this.innerProperties = new VolumeProperties(); + } + this.innerProperties().withCoolAccessTieringPolicy(coolAccessTieringPolicy); + return this; + } + /** * Get the unixPermissions property: UNIX permissions for NFS volume accepted in octal 4 digit format. First digit * selects the set user ID(4), set group ID (2) and sticky (1) attributes. Second digit selects permission for the * owner of the file: read (4), write (2) and execute (1). Third selects permissions for other users in the same * group. the fourth for other users not in the group. 0755 - gives read/write/execute permissions to owner and - * read/execute to group and other users. Avoid passing null value for unixPermissions in volume update operation, - * As per the behavior, If Null value is passed then user-visible unixPermissions value will became null, and user - * will not be able to get unixPermissions value. On safer side, actual unixPermissions value on volume will remain - * as its last saved value only. + * read/execute to group and other users. * * @return the unixPermissions value. */ @@ -951,10 +943,7 @@ public String unixPermissions() { * selects the set user ID(4), set group ID (2) and sticky (1) attributes. Second digit selects permission for the * owner of the file: read (4), write (2) and execute (1). Third selects permissions for other users in the same * group. the fourth for other users not in the group. 0755 - gives read/write/execute permissions to owner and - * read/execute to group and other users. Avoid passing null value for unixPermissions in volume update operation, - * As per the behavior, If Null value is passed then user-visible unixPermissions value will became null, and user - * will not be able to get unixPermissions value. On safer side, actual unixPermissions value on volume will remain - * as its last saved value only. + * read/execute to group and other users. * * @param unixPermissions the unixPermissions value to set. * @return the VolumeGroupVolumeProperties object itself. @@ -1292,38 +1281,6 @@ public String originatingResourceId() { return this.innerProperties() == null ? null : this.innerProperties().originatingResourceId(); } - /** - * Get the inheritedSizeInBytes property: Space shared by short term clone volume with parent volume in bytes. - * - * @return the inheritedSizeInBytes value. - */ - public Long inheritedSizeInBytes() { - return this.innerProperties() == null ? null : this.innerProperties().inheritedSizeInBytes(); - } - - /** - * Get the language property: Language supported for volume. - * - * @return the language value. - */ - public VolumeLanguage language() { - return this.innerProperties() == null ? null : this.innerProperties().language(); - } - - /** - * Set the language property: Language supported for volume. - * - * @param language the language value to set. - * @return the VolumeGroupVolumeProperties object itself. - */ - public VolumeGroupVolumeProperties withLanguage(VolumeLanguage language) { - if (this.innerProperties() == null) { - this.innerProperties = new VolumeProperties(); - } - this.innerProperties().withLanguage(language); - return this; - } - /** * Validates the instance. * diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/VolumeLanguage.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/VolumeLanguage.java deleted file mode 100644 index 02c49feff81b..000000000000 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/VolumeLanguage.java +++ /dev/null @@ -1,388 +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.resourcemanager.netapp.models; - -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * VolumeLanguage - * - * Language supported for volume. - */ -public final class VolumeLanguage extends ExpandableStringEnum { - /** - * Static value c.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage C_UTF_8 = fromString("c.utf-8"); - - /** - * Static value utf8mb4 for VolumeLanguage. - */ - public static final VolumeLanguage UTF8MB4 = fromString("utf8mb4"); - - /** - * Static value ar for VolumeLanguage. - */ - public static final VolumeLanguage AR = fromString("ar"); - - /** - * Static value ar.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage AR_UTF_8 = fromString("ar.utf-8"); - - /** - * Static value hr for VolumeLanguage. - */ - public static final VolumeLanguage HR = fromString("hr"); - - /** - * Static value hr.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage HR_UTF_8 = fromString("hr.utf-8"); - - /** - * Static value cs for VolumeLanguage. - */ - public static final VolumeLanguage CS = fromString("cs"); - - /** - * Static value cs.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage CS_UTF_8 = fromString("cs.utf-8"); - - /** - * Static value da for VolumeLanguage. - */ - public static final VolumeLanguage DA = fromString("da"); - - /** - * Static value da.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage DA_UTF_8 = fromString("da.utf-8"); - - /** - * Static value nl for VolumeLanguage. - */ - public static final VolumeLanguage NL = fromString("nl"); - - /** - * Static value nl.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage NL_UTF_8 = fromString("nl.utf-8"); - - /** - * Static value en for VolumeLanguage. - */ - public static final VolumeLanguage EN = fromString("en"); - - /** - * Static value en.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage EN_UTF_8 = fromString("en.utf-8"); - - /** - * Static value fi for VolumeLanguage. - */ - public static final VolumeLanguage FI = fromString("fi"); - - /** - * Static value fi.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage FI_UTF_8 = fromString("fi.utf-8"); - - /** - * Static value fr for VolumeLanguage. - */ - public static final VolumeLanguage FR = fromString("fr"); - - /** - * Static value fr.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage FR_UTF_8 = fromString("fr.utf-8"); - - /** - * Static value de for VolumeLanguage. - */ - public static final VolumeLanguage DE = fromString("de"); - - /** - * Static value de.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage DE_UTF_8 = fromString("de.utf-8"); - - /** - * Static value he for VolumeLanguage. - */ - public static final VolumeLanguage HE = fromString("he"); - - /** - * Static value he.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage HE_UTF_8 = fromString("he.utf-8"); - - /** - * Static value hu for VolumeLanguage. - */ - public static final VolumeLanguage HU = fromString("hu"); - - /** - * Static value hu.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage HU_UTF_8 = fromString("hu.utf-8"); - - /** - * Static value it for VolumeLanguage. - */ - public static final VolumeLanguage IT = fromString("it"); - - /** - * Static value it.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage IT_UTF_8 = fromString("it.utf-8"); - - /** - * Static value ja for VolumeLanguage. - */ - public static final VolumeLanguage JA = fromString("ja"); - - /** - * Static value ja.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage JA_UTF_8 = fromString("ja.utf-8"); - - /** - * Static value ja-v1 for VolumeLanguage. - */ - public static final VolumeLanguage JA_V1 = fromString("ja-v1"); - - /** - * Static value ja-v1.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage JA_V1_UTF_8 = fromString("ja-v1.utf-8"); - - /** - * Static value ja-jp.pck for VolumeLanguage. - */ - public static final VolumeLanguage JA_JP_PCK = fromString("ja-jp.pck"); - - /** - * Static value ja-jp.pck.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage JA_JP_PCK_UTF_8 = fromString("ja-jp.pck.utf-8"); - - /** - * Static value ja-jp.932 for VolumeLanguage. - */ - public static final VolumeLanguage JA_JP_932 = fromString("ja-jp.932"); - - /** - * Static value ja-jp.932.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage JA_JP_932_UTF_8 = fromString("ja-jp.932.utf-8"); - - /** - * Static value ja-jp.pck-v2 for VolumeLanguage. - */ - public static final VolumeLanguage JA_JP_PCK_V2 = fromString("ja-jp.pck-v2"); - - /** - * Static value ja-jp.pck-v2.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage JA_JP_PCK_V2_UTF_8 = fromString("ja-jp.pck-v2.utf-8"); - - /** - * Static value ko for VolumeLanguage. - */ - public static final VolumeLanguage KO = fromString("ko"); - - /** - * Static value ko.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage KO_UTF_8 = fromString("ko.utf-8"); - - /** - * Static value no for VolumeLanguage. - */ - public static final VolumeLanguage NO = fromString("no"); - - /** - * Static value no.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage NO_UTF_8 = fromString("no.utf-8"); - - /** - * Static value pl for VolumeLanguage. - */ - public static final VolumeLanguage PL = fromString("pl"); - - /** - * Static value pl.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage PL_UTF_8 = fromString("pl.utf-8"); - - /** - * Static value pt for VolumeLanguage. - */ - public static final VolumeLanguage PT = fromString("pt"); - - /** - * Static value pt.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage PT_UTF_8 = fromString("pt.utf-8"); - - /** - * Static value c for VolumeLanguage. - */ - public static final VolumeLanguage C = fromString("c"); - - /** - * Static value ro for VolumeLanguage. - */ - public static final VolumeLanguage RO = fromString("ro"); - - /** - * Static value ro.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage RO_UTF_8 = fromString("ro.utf-8"); - - /** - * Static value ru for VolumeLanguage. - */ - public static final VolumeLanguage RU = fromString("ru"); - - /** - * Static value ru.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage RU_UTF_8 = fromString("ru.utf-8"); - - /** - * Static value zh for VolumeLanguage. - */ - public static final VolumeLanguage ZH = fromString("zh"); - - /** - * Static value zh.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage ZH_UTF_8 = fromString("zh.utf-8"); - - /** - * Static value zh.gbk for VolumeLanguage. - */ - public static final VolumeLanguage ZH_GBK = fromString("zh.gbk"); - - /** - * Static value zh.gbk.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage ZH_GBK_UTF_8 = fromString("zh.gbk.utf-8"); - - /** - * Static value zh-tw.big5 for VolumeLanguage. - */ - public static final VolumeLanguage ZH_TW_BIG5 = fromString("zh-tw.big5"); - - /** - * Static value zh-tw.big5.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage ZH_TW_BIG5_UTF_8 = fromString("zh-tw.big5.utf-8"); - - /** - * Static value zh-tw for VolumeLanguage. - */ - public static final VolumeLanguage ZH_TW = fromString("zh-tw"); - - /** - * Static value zh-tw.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage ZH_TW_UTF_8 = fromString("zh-tw.utf-8"); - - /** - * Static value sk for VolumeLanguage. - */ - public static final VolumeLanguage SK = fromString("sk"); - - /** - * Static value sk.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage SK_UTF_8 = fromString("sk.utf-8"); - - /** - * Static value sl for VolumeLanguage. - */ - public static final VolumeLanguage SL = fromString("sl"); - - /** - * Static value sl.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage SL_UTF_8 = fromString("sl.utf-8"); - - /** - * Static value es for VolumeLanguage. - */ - public static final VolumeLanguage ES = fromString("es"); - - /** - * Static value es.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage ES_UTF_8 = fromString("es.utf-8"); - - /** - * Static value sv for VolumeLanguage. - */ - public static final VolumeLanguage SV = fromString("sv"); - - /** - * Static value sv.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage SV_UTF_8 = fromString("sv.utf-8"); - - /** - * Static value tr for VolumeLanguage. - */ - public static final VolumeLanguage TR = fromString("tr"); - - /** - * Static value tr.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage TR_UTF_8 = fromString("tr.utf-8"); - - /** - * Static value en-us for VolumeLanguage. - */ - public static final VolumeLanguage EN_US = fromString("en-us"); - - /** - * Static value en-us.utf-8 for VolumeLanguage. - */ - public static final VolumeLanguage EN_US_UTF_8 = fromString("en-us.utf-8"); - - /** - * Creates a new instance of VolumeLanguage value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Deprecated - public VolumeLanguage() { - } - - /** - * Creates or finds a VolumeLanguage from its string representation. - * - * @param name a name to look for. - * @return the corresponding VolumeLanguage. - */ - public static VolumeLanguage fromString(String name) { - return fromString(name, VolumeLanguage.class); - } - - /** - * Gets known VolumeLanguage values. - * - * @return known VolumeLanguage values. - */ - public static Collection values() { - return values(VolumeLanguage.class); - } -} diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/VolumePatch.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/VolumePatch.java index e94c3a797855..977072ee4386 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/VolumePatch.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/VolumePatch.java @@ -128,7 +128,7 @@ public VolumePatch withServiceLevel(ServiceLevel serviceLevel) { /** * Get the usageThreshold property: Maximum storage quota allowed for a file system in bytes. This is a soft quota * used for alerting only. For regular volumes, valid values are in the range 50GiB to 100TiB. For large volumes, - * valid values are in the range 100TiB to 1PiB, and on an exceptional basis, from to 2400GiB to 2400TiB. Values + * valid values are in the range 100TiB to 500TiB, and on an exceptional basis, from to 2400GiB to 2400TiB. Values * expressed in bytes as multiples of 1 GiB. * * @return the usageThreshold value. @@ -140,7 +140,7 @@ public Long usageThreshold() { /** * Set the usageThreshold property: Maximum storage quota allowed for a file system in bytes. This is a soft quota * used for alerting only. For regular volumes, valid values are in the range 50GiB to 100TiB. For large volumes, - * valid values are in the range 100TiB to 1PiB, and on an exceptional basis, from to 2400GiB to 2400TiB. Values + * valid values are in the range 100TiB to 500TiB, and on an exceptional basis, from to 2400GiB to 2400TiB. Values * expressed in bytes as multiples of 1 GiB. * * @param usageThreshold the usageThreshold value to set. @@ -437,6 +437,35 @@ public VolumePatch withCoolAccessRetrievalPolicy(CoolAccessRetrievalPolicy coolA return this; } + /** + * Get the coolAccessTieringPolicy property: coolAccessTieringPolicy determines which cold data blocks are moved to + * cool tier. The possible values for this field are: Auto - Moves cold user data blocks in both the Snapshot copies + * and the active file system to the cool tier tier. This policy is the default. SnapshotOnly - Moves user data + * blocks of the Volume Snapshot copies that are not associated with the active file system to the cool tier. + * + * @return the coolAccessTieringPolicy value. + */ + public CoolAccessTieringPolicy coolAccessTieringPolicy() { + return this.innerProperties() == null ? null : this.innerProperties().coolAccessTieringPolicy(); + } + + /** + * Set the coolAccessTieringPolicy property: coolAccessTieringPolicy determines which cold data blocks are moved to + * cool tier. The possible values for this field are: Auto - Moves cold user data blocks in both the Snapshot copies + * and the active file system to the cool tier tier. This policy is the default. SnapshotOnly - Moves user data + * blocks of the Volume Snapshot copies that are not associated with the active file system to the cool tier. + * + * @param coolAccessTieringPolicy the coolAccessTieringPolicy value to set. + * @return the VolumePatch object itself. + */ + public VolumePatch withCoolAccessTieringPolicy(CoolAccessTieringPolicy coolAccessTieringPolicy) { + if (this.innerProperties() == null) { + this.innerProperties = new VolumePatchProperties(); + } + this.innerProperties().withCoolAccessTieringPolicy(coolAccessTieringPolicy); + return this; + } + /** * Get the snapshotDirectoryVisible property: If enabled (true) the volume will contain a read-only snapshot * directory which provides access to each of the volume's snapshots. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/Volumes.java b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/Volumes.java index 1e5865b37180..21701962e706 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/Volumes.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/java/com/azure/resourcemanager/netapp/models/Volumes.java @@ -211,38 +211,6 @@ void revert(String resourceGroupName, String accountName, String poolName, Strin void resetCifsPassword(String resourceGroupName, String accountName, String poolName, String volumeName, Context context); - /** - * Split clone from parent volume - * - * Split operation to convert clone volume to an independent volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - void splitCloneFromParent(String resourceGroupName, String accountName, String poolName, String volumeName); - - /** - * Split clone from parent volume - * - * Split operation to convert clone volume to an independent volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - void splitCloneFromParent(String resourceGroupName, String accountName, String poolName, String volumeName, - Context context); - /** * Break file locks * @@ -313,41 +281,6 @@ GetGroupIdListForLdapUserResponse listGetGroupIdListForLdapUser(String resourceG GetGroupIdListForLdapUserResponse listGetGroupIdListForLdapUser(String resourceGroupName, String accountName, String poolName, String volumeName, GetGroupIdListForLdapUserRequest body, Context context); - /** - * Lists Quota Report for the volume - * - * Returns report of quotas for the volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return quota Report for volume. - */ - ListQuotaReportResponse listQuotaReport(String resourceGroupName, String accountName, String poolName, - String volumeName); - - /** - * Lists Quota Report for the volume - * - * Returns report of quotas for the volume. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param accountName The name of the NetApp account. - * @param poolName The name of the capacity pool. - * @param volumeName The name of the volume. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return quota Report for volume. - */ - ListQuotaReportResponse listQuotaReport(String resourceGroupName, String accountName, String poolName, - String volumeName, Context context); - /** * Break volume replication * diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/main/resources/azure-resourcemanager-netapp.properties b/sdk/netapp/azure-resourcemanager-netapp/src/main/resources/azure-resourcemanager-netapp.properties new file mode 100644 index 000000000000..defbd48204e4 --- /dev/null +++ b/sdk/netapp/azure-resourcemanager-netapp/src/main/resources/azure-resourcemanager-netapp.properties @@ -0,0 +1 @@ +version=${project.version} diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsChangeKeyVaultSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsChangeKeyVaultSamples.java index 97e6f5a571e6..6f57cb199456 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsChangeKeyVaultSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsChangeKeyVaultSamples.java @@ -13,8 +13,8 @@ */ public final class AccountsChangeKeyVaultSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Accounts_ChangeKeyVault.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Accounts_ChangeKeyVault.json */ /** * Sample code: Accounts_ChangeKeyVault. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsCreateOrUpdateSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsCreateOrUpdateSamples.java index a79f59aafa83..73aaa0d75f62 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsCreateOrUpdateSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsCreateOrUpdateSamples.java @@ -12,8 +12,8 @@ */ public final class AccountsCreateOrUpdateSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Accounts_CreateOrUpdate.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Accounts_CreateOrUpdate.json */ /** * Sample code: Accounts_CreateOrUpdate. @@ -25,8 +25,8 @@ public static void accountsCreateOrUpdate(com.azure.resourcemanager.netapp.NetAp } /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Accounts_CreateOrUpdateAD.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Accounts_CreateOrUpdateAD.json */ /** * Sample code: Accounts_CreateOrUpdateWithActiveDirectory. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsDeleteSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsDeleteSamples.java index a876d879e84c..2a2b68e4391b 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsDeleteSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsDeleteSamples.java @@ -10,7 +10,7 @@ public final class AccountsDeleteSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Accounts_Delete.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Accounts_Delete.json */ /** * Sample code: Accounts_Delete. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsGetByResourceGroupSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsGetByResourceGroupSamples.java index 59b0898122c7..82e8cc2fe29e 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsGetByResourceGroupSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsGetByResourceGroupSamples.java @@ -10,7 +10,7 @@ public final class AccountsGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Accounts_Get.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Accounts_Get.json */ /** * Sample code: Accounts_Get. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsGetChangeKeyVaultInformationSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsGetChangeKeyVaultInformationSamples.java index ff87a99e5285..c8f680fd10d6 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsGetChangeKeyVaultInformationSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsGetChangeKeyVaultInformationSamples.java @@ -9,7 +9,7 @@ */ public final class AccountsGetChangeKeyVaultInformationSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ + * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/ * Accounts_GetChangeKeyVaultInformation.json */ /** diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsListByResourceGroupSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsListByResourceGroupSamples.java index 20c8034ad08c..98fa57e08d5d 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsListByResourceGroupSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsListByResourceGroupSamples.java @@ -10,7 +10,7 @@ public final class AccountsListByResourceGroupSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Accounts_List.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Accounts_List.json */ /** * Sample code: Accounts_List. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsListSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsListSamples.java index 700721e5764f..b7147bd9a521 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsListSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsListSamples.java @@ -10,7 +10,7 @@ public final class AccountsListSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Accounts_List.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Accounts_List.json */ /** * Sample code: Accounts_List. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsRenewCredentialsSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsRenewCredentialsSamples.java index fea17a15266c..13d5069682cd 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsRenewCredentialsSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsRenewCredentialsSamples.java @@ -9,8 +9,8 @@ */ public final class AccountsRenewCredentialsSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Accounts_RenewCredentials.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Accounts_RenewCredentials.json */ /** * Sample code: Accounts_RenewCredentials. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsTransitionToCmkSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsTransitionToCmkSamples.java index 010826d4ddc9..5d4b423750fc 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsTransitionToCmkSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsTransitionToCmkSamples.java @@ -11,7 +11,7 @@ */ public final class AccountsTransitionToCmkSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ + * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/ * Accounts_TransitionEncryptionKey.json */ /** diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsUpdateSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsUpdateSamples.java index 3cd0fc7068a3..a5cf48069ed9 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsUpdateSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/AccountsUpdateSamples.java @@ -14,7 +14,7 @@ public final class AccountsUpdateSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Accounts_Update.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Accounts_Update.json */ /** * Sample code: Accounts_Update. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesCreateSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesCreateSamples.java index ce78aa5272d4..9a76d98a4214 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesCreateSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesCreateSamples.java @@ -10,8 +10,7 @@ public final class BackupPoliciesCreateSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/BackupPolicies_Create. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupPolicies_Create.json */ /** * Sample code: BackupPolicies_Create. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesDeleteSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesDeleteSamples.java index ee8a6f95a077..0dcf33ee4c87 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesDeleteSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesDeleteSamples.java @@ -10,8 +10,7 @@ public final class BackupPoliciesDeleteSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/BackupPolicies_Delete. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupPolicies_Delete.json */ /** * Sample code: BackupPolicies_Delete. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesGetSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesGetSamples.java index 092e777ed9a4..c76fb5b1140a 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesGetSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesGetSamples.java @@ -10,8 +10,7 @@ public final class BackupPoliciesGetSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/BackupPolicies_Get. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupPolicies_Get.json */ /** * Sample code: Backups_Get. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesListSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesListSamples.java index 828841c9dfb6..9bda9c6c397d 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesListSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesListSamples.java @@ -10,8 +10,7 @@ public final class BackupPoliciesListSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/BackupPolicies_List. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupPolicies_List.json */ /** * Sample code: BackupPolicies_List. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesUpdateSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesUpdateSamples.java index 74eeecf4ea4d..3b3161407a3d 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesUpdateSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesUpdateSamples.java @@ -12,8 +12,7 @@ public final class BackupPoliciesUpdateSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/BackupPolicies_Update. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupPolicies_Update.json */ /** * Sample code: BackupPolicies_Update. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupVaultsCreateOrUpdateSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupVaultsCreateOrUpdateSamples.java index 843213bbe660..6081a41b51e8 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupVaultsCreateOrUpdateSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupVaultsCreateOrUpdateSamples.java @@ -10,8 +10,7 @@ public final class BackupVaultsCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/BackupVaults_Create. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupVaults_Create.json */ /** * Sample code: BackupVault_CreateOrUpdate. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupVaultsDeleteSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupVaultsDeleteSamples.java index db9fa4816348..7ff7d6ba7670 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupVaultsDeleteSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupVaultsDeleteSamples.java @@ -10,8 +10,7 @@ public final class BackupVaultsDeleteSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/BackupVaults_Delete. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupVaults_Delete.json */ /** * Sample code: BackupVaults_Delete. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupVaultsGetSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupVaultsGetSamples.java index c76f35c7d62e..7a88331f3193 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupVaultsGetSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupVaultsGetSamples.java @@ -10,7 +10,7 @@ public final class BackupVaultsGetSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/BackupVaults_Get.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupVaults_Get.json */ /** * Sample code: BackupVaults_Get. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupVaultsListByNetAppAccountSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupVaultsListByNetAppAccountSamples.java index 113875949929..1318269c3ef2 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupVaultsListByNetAppAccountSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupVaultsListByNetAppAccountSamples.java @@ -10,7 +10,7 @@ public final class BackupVaultsListByNetAppAccountSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/BackupVaults_List.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupVaults_List.json */ /** * Sample code: BackupVaults_List. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupVaultsUpdateSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupVaultsUpdateSamples.java index e52cd37a80a3..add662a46355 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupVaultsUpdateSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupVaultsUpdateSamples.java @@ -14,8 +14,7 @@ public final class BackupVaultsUpdateSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/BackupVaults_Update. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupVaults_Update.json */ /** * Sample code: BackupVaults_Update. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsCreateSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsCreateSamples.java index 35b97a6dddba..3a6c6fd7abef 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsCreateSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsCreateSamples.java @@ -9,8 +9,9 @@ */ public final class BackupsCreateSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * BackupsUnderBackupVault_Create.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupsUnderBackupVault_Create. + * json */ /** * Sample code: BackupsUnderBackupVault_Create. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsDeleteSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsDeleteSamples.java index 89aa3dd84052..7c13d5ea3ede 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsDeleteSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsDeleteSamples.java @@ -9,8 +9,9 @@ */ public final class BackupsDeleteSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * BackupsUnderBackupVault_Delete.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupsUnderBackupVault_Delete. + * json */ /** * Sample code: BackupsUnderBackupVault_Delete. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsGetLatestStatusSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsGetLatestStatusSamples.java index 80ddcafbfaae..4bdb3d86f840 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsGetLatestStatusSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsGetLatestStatusSamples.java @@ -9,8 +9,8 @@ */ public final class BackupsGetLatestStatusSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_LatestBackupStatus.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_LatestBackupStatus.json */ /** * Sample code: Volumes_BackupStatus. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsGetSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsGetSamples.java index 820da4bdb9aa..38152b757e9c 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsGetSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsGetSamples.java @@ -9,8 +9,9 @@ */ public final class BackupsGetSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * BackupsUnderBackupVault_Get.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupsUnderBackupVault_Get. + * json */ /** * Sample code: BackupsUnderBackupVault_Get. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsGetVolumeLatestRestoreStatusSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsGetVolumeLatestRestoreStatusSamples.java index 6bbdd5da4d09..4f4719055587 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsGetVolumeLatestRestoreStatusSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsGetVolumeLatestRestoreStatusSamples.java @@ -9,8 +9,9 @@ */ public final class BackupsGetVolumeLatestRestoreStatusSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_LatestRestoreStatus.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_LatestRestoreStatus. + * json */ /** * Sample code: Volumes_RestoreStatus. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsListByVaultSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsListByVaultSamples.java index 2641be9cfb9e..5dd4a7ff09d6 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsListByVaultSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsListByVaultSamples.java @@ -9,8 +9,9 @@ */ public final class BackupsListByVaultSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * BackupsUnderBackupVault_List.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupsUnderBackupVault_List. + * json */ /** * Sample code: Backups_List. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsUnderAccountMigrateBackupsSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsUnderAccountMigrateBackupsSamples.java index f846349a7011..2a437e2b7ae8 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsUnderAccountMigrateBackupsSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsUnderAccountMigrateBackupsSamples.java @@ -11,8 +11,9 @@ */ public final class BackupsUnderAccountMigrateBackupsSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * BackupsUnderAccount_Migrate.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupsUnderAccount_Migrate. + * json */ /** * Sample code: BackupsUnderAccount_Migrate. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsUnderBackupVaultRestoreFilesSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsUnderBackupVaultRestoreFilesSamples.java index 1ec29df35be7..58e1b2d544a1 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsUnderBackupVaultRestoreFilesSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsUnderBackupVaultRestoreFilesSamples.java @@ -12,7 +12,7 @@ */ public final class BackupsUnderBackupVaultRestoreFilesSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ + * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/ * BackupsUnderBackupVault_SingleFileRestore.json */ /** diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsUnderVolumeMigrateBackupsSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsUnderVolumeMigrateBackupsSamples.java index 6dbefa9612b0..8fde385112b2 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsUnderVolumeMigrateBackupsSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsUnderVolumeMigrateBackupsSamples.java @@ -11,8 +11,8 @@ */ public final class BackupsUnderVolumeMigrateBackupsSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * BackupsUnderVolume_Migrate.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupsUnderVolume_Migrate.json */ /** * Sample code: BackupsUnderVolume_Migrate. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsUpdateSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsUpdateSamples.java index 08b98be8ed23..77fe9b72c20e 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsUpdateSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/BackupsUpdateSamples.java @@ -11,8 +11,9 @@ */ public final class BackupsUpdateSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * BackupsUnderBackupVault_Update.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/BackupsUnderBackupVault_Update. + * json */ /** * Sample code: BackupsUnderBackupVault_Update. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceCheckFilePathAvailabilitySamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceCheckFilePathAvailabilitySamples.java index 197000c1434e..2e39d9c2d605 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceCheckFilePathAvailabilitySamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceCheckFilePathAvailabilitySamples.java @@ -11,8 +11,8 @@ */ public final class NetAppResourceCheckFilePathAvailabilitySamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * CheckFilePathAvailability.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/CheckFilePathAvailability.json */ /** * Sample code: CheckFilePathAvailability. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceCheckNameAvailabilitySamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceCheckNameAvailabilitySamples.java index 993ab0c43078..5b0dbe33d040 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceCheckNameAvailabilitySamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceCheckNameAvailabilitySamples.java @@ -13,8 +13,7 @@ public final class NetAppResourceCheckNameAvailabilitySamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/CheckNameAvailability. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/CheckNameAvailability.json */ /** * Sample code: CheckNameAvailability. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceCheckQuotaAvailabilitySamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceCheckQuotaAvailabilitySamples.java index 8fa6ac668e65..c2ac91733ba8 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceCheckQuotaAvailabilitySamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceCheckQuotaAvailabilitySamples.java @@ -13,8 +13,7 @@ public final class NetAppResourceCheckQuotaAvailabilitySamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/CheckQuotaAvailability - * .json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/CheckQuotaAvailability.json */ /** * Sample code: CheckQuotaAvailability. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceQueryNetworkSiblingSetSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceQueryNetworkSiblingSetSamples.java index 867300ac5560..cd74147f4e28 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceQueryNetworkSiblingSetSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceQueryNetworkSiblingSetSamples.java @@ -11,8 +11,8 @@ */ public final class NetAppResourceQueryNetworkSiblingSetSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * NetworkSiblingSet_Query.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/NetworkSiblingSet_Query.json */ /** * Sample code: NetworkSiblingSet_Query. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceQueryRegionInfoSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceQueryRegionInfoSamples.java index 73919ab66972..b95fc47f544a 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceQueryRegionInfoSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceQueryRegionInfoSamples.java @@ -10,7 +10,7 @@ public final class NetAppResourceQueryRegionInfoSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/RegionInfo.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/RegionInfo.json */ /** * Sample code: RegionInfo_Query. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceQuotaLimitsGetSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceQuotaLimitsGetSamples.java index 9871a0edadec..5dc735ac2638 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceQuotaLimitsGetSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceQuotaLimitsGetSamples.java @@ -10,7 +10,7 @@ public final class NetAppResourceQuotaLimitsGetSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/QuotaLimits_Get.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/QuotaLimits_Get.json */ /** * Sample code: QuotaLimits. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceQuotaLimitsListSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceQuotaLimitsListSamples.java index e3d6294a02cd..cf02a81d15cb 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceQuotaLimitsListSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceQuotaLimitsListSamples.java @@ -10,7 +10,7 @@ public final class NetAppResourceQuotaLimitsListSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/QuotaLimits_List.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/QuotaLimits_List.json */ /** * Sample code: QuotaLimits. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceRegionInfosGetSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceRegionInfosGetSamples.java index 5178766c06cb..1e980a2c12b0 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceRegionInfosGetSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceRegionInfosGetSamples.java @@ -10,7 +10,7 @@ public final class NetAppResourceRegionInfosGetSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/RegionInfos_Get.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/RegionInfos_Get.json */ /** * Sample code: RegionInfos_Get. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceRegionInfosListSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceRegionInfosListSamples.java index 66f57f317a72..1ddfe1d92fd7 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceRegionInfosListSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceRegionInfosListSamples.java @@ -10,7 +10,7 @@ public final class NetAppResourceRegionInfosListSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/RegionInfos_List.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/RegionInfos_List.json */ /** * Sample code: RegionInfos_List. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceUpdateNetworkSiblingSetSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceUpdateNetworkSiblingSetSamples.java index 8ac934ada779..b7b418702b83 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceUpdateNetworkSiblingSetSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/NetAppResourceUpdateNetworkSiblingSetSamples.java @@ -12,8 +12,8 @@ */ public final class NetAppResourceUpdateNetworkSiblingSetSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * NetworkSiblingSet_Update.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/NetworkSiblingSet_Update.json */ /** * Sample code: NetworkFeatures_Update. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/OperationsListSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/OperationsListSamples.java index 6e8b1cc50706..00a2f7e0bd67 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/OperationsListSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/OperationsListSamples.java @@ -10,7 +10,7 @@ public final class OperationsListSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/OperationList.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/OperationList.json */ /** * Sample code: OperationList. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/PoolsCreateOrUpdateSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/PoolsCreateOrUpdateSamples.java index 945f5ceecc71..b5f06b56854b 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/PoolsCreateOrUpdateSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/PoolsCreateOrUpdateSamples.java @@ -13,8 +13,7 @@ public final class PoolsCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Pools_CreateOrUpdate. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Pools_CreateOrUpdate.json */ /** * Sample code: Pools_CreateOrUpdate. @@ -31,26 +30,4 @@ public static void poolsCreateOrUpdate(com.azure.resourcemanager.netapp.NetAppFi .withQosType(QosType.AUTO) .create(); } - - /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Pools_CreateOrUpdate_CustomThroughput.json - */ - /** - * Sample code: Pools_CreateOrUpdate_CustomThroughput. - * - * @param manager Entry point to NetAppFilesManager. - */ - public static void - poolsCreateOrUpdateCustomThroughput(com.azure.resourcemanager.netapp.NetAppFilesManager manager) { - manager.pools() - .define("customPool1") - .withRegion("eastus") - .withExistingNetAppAccount("myRG", "account1") - .withSize(4398046511104L) - .withServiceLevel(ServiceLevel.FLEXIBLE) - .withCustomThroughputMibps(128.0F) - .withQosType(QosType.MANUAL) - .create(); - } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/PoolsDeleteSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/PoolsDeleteSamples.java index 204d34127626..db2c90975f06 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/PoolsDeleteSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/PoolsDeleteSamples.java @@ -10,7 +10,7 @@ public final class PoolsDeleteSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Pools_Delete.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Pools_Delete.json */ /** * Sample code: Pools_Delete. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/PoolsGetSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/PoolsGetSamples.java index 1cba91a385a6..2d7f37fed6e1 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/PoolsGetSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/PoolsGetSamples.java @@ -8,22 +8,9 @@ * Samples for Pools Get. */ public final class PoolsGetSamples { - /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Pools_Get_CustomThroughput.json - */ - /** - * Sample code: Pools_Get_CustomThroughput. - * - * @param manager Entry point to NetAppFilesManager. - */ - public static void poolsGetCustomThroughput(com.azure.resourcemanager.netapp.NetAppFilesManager manager) { - manager.pools().getWithResponse("myRG", "account1", "customPool1", com.azure.core.util.Context.NONE); - } - /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Pools_Get.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Pools_Get.json */ /** * Sample code: Pools_Get. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/PoolsListSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/PoolsListSamples.java index e7ba45aecffb..5e978e1e9c7f 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/PoolsListSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/PoolsListSamples.java @@ -10,7 +10,7 @@ public final class PoolsListSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Pools_List.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Pools_List.json */ /** * Sample code: Pools_List. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/PoolsUpdateSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/PoolsUpdateSamples.java index 1fd3591c9d77..ecf0b741c61d 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/PoolsUpdateSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/PoolsUpdateSamples.java @@ -12,7 +12,7 @@ public final class PoolsUpdateSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Pools_Update.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Pools_Update.json */ /** * Sample code: Pools_Update. @@ -24,20 +24,4 @@ public static void poolsUpdate(com.azure.resourcemanager.netapp.NetAppFilesManag = manager.pools().getWithResponse("myRG", "account1", "pool1", com.azure.core.util.Context.NONE).getValue(); resource.update().apply(); } - - /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Pools_Update_CustomThroughput.json - */ - /** - * Sample code: Pools_Update_CustomThroughput. - * - * @param manager Entry point to NetAppFilesManager. - */ - public static void poolsUpdateCustomThroughput(com.azure.resourcemanager.netapp.NetAppFilesManager manager) { - CapacityPool resource = manager.pools() - .getWithResponse("myRG", "account1", "customPool1", com.azure.core.util.Context.NONE) - .getValue(); - resource.update().apply(); - } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesCreateSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesCreateSamples.java index b8ea4995a2aa..21544f70893d 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesCreateSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesCreateSamples.java @@ -14,8 +14,8 @@ */ public final class SnapshotPoliciesCreateSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * SnapshotPolicies_Create.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/SnapshotPolicies_Create.json */ /** * Sample code: SnapshotPolicies_Create. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesDeleteSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesDeleteSamples.java index 6684c4283789..153577c8845a 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesDeleteSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesDeleteSamples.java @@ -9,8 +9,8 @@ */ public final class SnapshotPoliciesDeleteSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * SnapshotPolicies_Delete.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/SnapshotPolicies_Delete.json */ /** * Sample code: SnapshotPolicies_Delete. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesGetSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesGetSamples.java index 8c3b33a92e29..1855d6f96cdd 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesGetSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesGetSamples.java @@ -10,8 +10,7 @@ public final class SnapshotPoliciesGetSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/SnapshotPolicies_Get. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/SnapshotPolicies_Get.json */ /** * Sample code: SnapshotPolicies_Get. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesListSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesListSamples.java index 33fd38caf4b8..6ad01038cce0 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesListSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesListSamples.java @@ -10,8 +10,7 @@ public final class SnapshotPoliciesListSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/SnapshotPolicies_List. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/SnapshotPolicies_List.json */ /** * Sample code: SnapshotPolicies_List. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesListVolumesSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesListVolumesSamples.java index 03734e9159e6..430ee5c034e9 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesListVolumesSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesListVolumesSamples.java @@ -9,8 +9,9 @@ */ public final class SnapshotPoliciesListVolumesSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * SnapshotPolicies_ListVolumes.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/SnapshotPolicies_ListVolumes. + * json */ /** * Sample code: SnapshotPolicies_ListVolumes. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesUpdateSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesUpdateSamples.java index 4f0e629d9a0c..41f2ff002554 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesUpdateSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesUpdateSamples.java @@ -15,8 +15,8 @@ */ public final class SnapshotPoliciesUpdateSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * SnapshotPolicies_Update.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/SnapshotPolicies_Update.json */ /** * Sample code: SnapshotPolicies_Update. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotsCreateSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotsCreateSamples.java index 21d92f8caeb2..45a02153d036 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotsCreateSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotsCreateSamples.java @@ -10,7 +10,7 @@ public final class SnapshotsCreateSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Snapshots_Create.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Snapshots_Create.json */ /** * Sample code: Snapshots_Create. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotsDeleteSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotsDeleteSamples.java index a55b2527861e..81d823a78e91 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotsDeleteSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotsDeleteSamples.java @@ -10,7 +10,7 @@ public final class SnapshotsDeleteSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Snapshots_Delete.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Snapshots_Delete.json */ /** * Sample code: Snapshots_Delete. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotsGetSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotsGetSamples.java index f3f6e1e49ab9..b4c16df088a6 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotsGetSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotsGetSamples.java @@ -10,7 +10,7 @@ public final class SnapshotsGetSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Snapshots_Get.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Snapshots_Get.json */ /** * Sample code: Snapshots_Get. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotsListSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotsListSamples.java index 27bf13d93ab8..600ef6cd5b23 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotsListSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotsListSamples.java @@ -10,7 +10,7 @@ public final class SnapshotsListSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Snapshots_List.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Snapshots_List.json */ /** * Sample code: Snapshots_List. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotsRestoreFilesSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotsRestoreFilesSamples.java index 5331108104df..f57f36de25ed 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotsRestoreFilesSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotsRestoreFilesSamples.java @@ -12,8 +12,9 @@ */ public final class SnapshotsRestoreFilesSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Snapshots_SingleFileRestore.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Snapshots_SingleFileRestore. + * json */ /** * Sample code: Snapshots_SingleFileRestore. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotsUpdateSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotsUpdateSamples.java index 151cc234ff2f..0ca3e6c91c66 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotsUpdateSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SnapshotsUpdateSamples.java @@ -14,7 +14,7 @@ public final class SnapshotsUpdateSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Snapshots_Update.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Snapshots_Update.json */ /** * Sample code: Snapshots_Update. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SubvolumesCreateSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SubvolumesCreateSamples.java index 2f88002a21fb..fbb8508b75b1 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SubvolumesCreateSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SubvolumesCreateSamples.java @@ -10,7 +10,7 @@ public final class SubvolumesCreateSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Subvolumes_Create.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Subvolumes_Create.json */ /** * Sample code: Subvolumes_Create. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SubvolumesDeleteSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SubvolumesDeleteSamples.java index 3defebaba3c1..4ac0c3711a81 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SubvolumesDeleteSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SubvolumesDeleteSamples.java @@ -10,7 +10,7 @@ public final class SubvolumesDeleteSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Subvolumes_Delete.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Subvolumes_Delete.json */ /** * Sample code: Subvolumes_Delete. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SubvolumesGetMetadataSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SubvolumesGetMetadataSamples.java index c5d04c7a89e4..dab6f78a04ed 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SubvolumesGetMetadataSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SubvolumesGetMetadataSamples.java @@ -10,8 +10,7 @@ public final class SubvolumesGetMetadataSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Subvolumes_Metadata. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Subvolumes_Metadata.json */ /** * Sample code: Subvolumes_Metadata. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SubvolumesGetSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SubvolumesGetSamples.java index 3646dcdee787..7a6db65659fc 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SubvolumesGetSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SubvolumesGetSamples.java @@ -10,7 +10,7 @@ public final class SubvolumesGetSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Subvolumes_Get.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Subvolumes_Get.json */ /** * Sample code: Subvolumes_Get. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SubvolumesListByVolumeSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SubvolumesListByVolumeSamples.java index e8aad516ab61..d212f36f8ab3 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SubvolumesListByVolumeSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SubvolumesListByVolumeSamples.java @@ -10,7 +10,7 @@ public final class SubvolumesListByVolumeSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Subvolumes_List.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Subvolumes_List.json */ /** * Sample code: Subvolumes_List. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SubvolumesUpdateSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SubvolumesUpdateSamples.java index ace89f405f25..231d531b192e 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SubvolumesUpdateSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/SubvolumesUpdateSamples.java @@ -12,7 +12,7 @@ public final class SubvolumesUpdateSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Subvolumes_Update.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Subvolumes_Update.json */ /** * Sample code: Subvolumes_Update. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeGroupsCreateSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeGroupsCreateSamples.java index b8f710fa2839..2850e3752324 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeGroupsCreateSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeGroupsCreateSamples.java @@ -17,8 +17,9 @@ */ public final class VolumeGroupsCreateSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * VolumeGroups_Create_SapHana.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/VolumeGroups_Create_SapHana. + * json */ /** * Sample code: VolumeGroups_Create_SapHana. @@ -178,8 +179,8 @@ public static void volumeGroupsCreateSapHana(com.azure.resourcemanager.netapp.Ne } /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * VolumeGroups_Create_Oracle.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/VolumeGroups_Create_Oracle.json */ /** * Sample code: VolumeGroups_Create_Oracle. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeGroupsDeleteSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeGroupsDeleteSamples.java index 618bdd82394a..a3d0f248933e 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeGroupsDeleteSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeGroupsDeleteSamples.java @@ -10,8 +10,7 @@ public final class VolumeGroupsDeleteSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/VolumeGroups_Delete. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/VolumeGroups_Delete.json */ /** * Sample code: VolumeGroups_Delete. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeGroupsGetSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeGroupsGetSamples.java index 104661c01e59..f82ee0f62e3a 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeGroupsGetSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeGroupsGetSamples.java @@ -9,8 +9,8 @@ */ public final class VolumeGroupsGetSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * VolumeGroups_Get_SapHana.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/VolumeGroups_Get_SapHana.json */ /** * Sample code: VolumeGroups_Get_SapHana. @@ -22,8 +22,8 @@ public static void volumeGroupsGetSapHana(com.azure.resourcemanager.netapp.NetAp } /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * VolumeGroups_Get_Oracle.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/VolumeGroups_Get_Oracle.json */ /** * Sample code: VolumeGroups_Get_Oracle. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeGroupsListByNetAppAccountSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeGroupsListByNetAppAccountSamples.java index 1fdf3c7ca7bf..5b05da68802d 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeGroupsListByNetAppAccountSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeGroupsListByNetAppAccountSamples.java @@ -9,8 +9,8 @@ */ public final class VolumeGroupsListByNetAppAccountSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * VolumeGroups_List_Oracle.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/VolumeGroups_List_Oracle.json */ /** * Sample code: VolumeGroups_List_Oracle. @@ -22,8 +22,8 @@ public static void volumeGroupsListOracle(com.azure.resourcemanager.netapp.NetAp } /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * VolumeGroups_List_SapHana.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/VolumeGroups_List_SapHana.json */ /** * Sample code: VolumeGroups_List_SapHana. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesCreateSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesCreateSamples.java index d66c88096216..443a6bcb643c 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesCreateSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesCreateSamples.java @@ -11,8 +11,8 @@ */ public final class VolumeQuotaRulesCreateSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * VolumeQuotaRules_Create.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/VolumeQuotaRules_Create.json */ /** * Sample code: VolumeQuotaRules_Create. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesDeleteSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesDeleteSamples.java index 38ea64d89b0c..acda72f50220 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesDeleteSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesDeleteSamples.java @@ -9,8 +9,8 @@ */ public final class VolumeQuotaRulesDeleteSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * VolumeQuotaRules_Delete.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/VolumeQuotaRules_Delete.json */ /** * Sample code: VolumeQuotaRules_Delete. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesGetSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesGetSamples.java index dcec8795abef..2e34cdbef05b 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesGetSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesGetSamples.java @@ -10,8 +10,7 @@ public final class VolumeQuotaRulesGetSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/VolumeQuotaRules_Get. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/VolumeQuotaRules_Get.json */ /** * Sample code: VolumeQuotaRules_Get. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesListByVolumeSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesListByVolumeSamples.java index 1ca54aad4dfb..b4cac1ef24d5 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesListByVolumeSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesListByVolumeSamples.java @@ -10,8 +10,7 @@ public final class VolumeQuotaRulesListByVolumeSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/VolumeQuotaRules_List. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/VolumeQuotaRules_List.json */ /** * Sample code: VolumeQuotaRules_List. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesUpdateSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesUpdateSamples.java index fd1858b92956..359af3f5263c 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesUpdateSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesUpdateSamples.java @@ -11,8 +11,8 @@ */ public final class VolumeQuotaRulesUpdateSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * VolumeQuotaRules_Update.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/VolumeQuotaRules_Update.json */ /** * Sample code: VolumeQuotaRules_Update. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesAuthorizeExternalReplicationSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesAuthorizeExternalReplicationSamples.java index 76c961e4fe7e..df361d43c987 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesAuthorizeExternalReplicationSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesAuthorizeExternalReplicationSamples.java @@ -9,7 +9,7 @@ */ public final class VolumesAuthorizeExternalReplicationSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ + * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/ * Volumes_AuthorizeExternalReplication.json */ /** diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesAuthorizeReplicationSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesAuthorizeReplicationSamples.java index 5862f1e9b7cb..a3c5f15ea6d9 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesAuthorizeReplicationSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesAuthorizeReplicationSamples.java @@ -11,8 +11,9 @@ */ public final class VolumesAuthorizeReplicationSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_AuthorizeReplication.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_AuthorizeReplication. + * json */ /** * Sample code: Volumes_AuthorizeReplication. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesBreakFileLocksSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesBreakFileLocksSamples.java index 7118959a95bd..19ef4dc5a2fe 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesBreakFileLocksSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesBreakFileLocksSamples.java @@ -12,8 +12,7 @@ public final class VolumesBreakFileLocksSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Volumes_BreakFileLocks - * .json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_BreakFileLocks.json */ /** * Sample code: Volumes_BreakFileLocks. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesBreakReplicationSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesBreakReplicationSamples.java index 2f2a8280c9be..61ab54141b21 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesBreakReplicationSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesBreakReplicationSamples.java @@ -11,8 +11,8 @@ */ public final class VolumesBreakReplicationSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_BreakReplication.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_BreakReplication.json */ /** * Sample code: Volumes_BreakReplication. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesCreateOrUpdateSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesCreateOrUpdateSamples.java index f5bb6475b899..453d3e23604a 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesCreateOrUpdateSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesCreateOrUpdateSamples.java @@ -12,8 +12,7 @@ public final class VolumesCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Volumes_CreateOrUpdate - * .json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_CreateOrUpdate.json */ /** * Sample code: Volumes_CreateOrUpdate. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesDeleteReplicationSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesDeleteReplicationSamples.java index d3b1cbed5006..92f7f3a26609 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesDeleteReplicationSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesDeleteReplicationSamples.java @@ -9,8 +9,8 @@ */ public final class VolumesDeleteReplicationSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_DeleteReplication.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_DeleteReplication.json */ /** * Sample code: Volumes_DeleteReplication. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesDeleteSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesDeleteSamples.java index 2fdbdecab41d..7f638aec98da 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesDeleteSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesDeleteSamples.java @@ -10,7 +10,7 @@ public final class VolumesDeleteSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Volumes_Delete.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_Delete.json */ /** * Sample code: Volumes_Delete. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesFinalizeExternalReplicationSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesFinalizeExternalReplicationSamples.java index d0cf9d26578c..838e3936af97 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesFinalizeExternalReplicationSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesFinalizeExternalReplicationSamples.java @@ -9,7 +9,7 @@ */ public final class VolumesFinalizeExternalReplicationSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ + * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/ * Volumes_FinalizeExternalReplication.json */ /** diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesFinalizeRelocationSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesFinalizeRelocationSamples.java index 764d9c077bab..37a2a65a98ed 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesFinalizeRelocationSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesFinalizeRelocationSamples.java @@ -9,8 +9,8 @@ */ public final class VolumesFinalizeRelocationSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_FinalizeRelocation.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_FinalizeRelocation.json */ /** * Sample code: Volumes_FinalizeRelocation. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesGetSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesGetSamples.java index 8be9df3df8b8..0d8bf2d1afbb 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesGetSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesGetSamples.java @@ -10,7 +10,7 @@ public final class VolumesGetSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Volumes_Get.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_Get.json */ /** * Sample code: Volumes_Get. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesListGetGroupIdListForLdapUserSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesListGetGroupIdListForLdapUserSamples.java index 6f8e4916e77c..555d371635b5 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesListGetGroupIdListForLdapUserSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesListGetGroupIdListForLdapUserSamples.java @@ -12,8 +12,7 @@ public final class VolumesListGetGroupIdListForLdapUserSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/GroupIdListForLDAPUser - * .json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/GroupIdListForLDAPUser.json */ /** * Sample code: GetGroupIdListForUser. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesListQuotaReportSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesListQuotaReportSamples.java deleted file mode 100644 index b8d85de15647..000000000000 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesListQuotaReportSamples.java +++ /dev/null @@ -1,23 +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.resourcemanager.netapp.generated; - -/** - * Samples for Volumes ListQuotaReport. - */ -public final class VolumesListQuotaReportSamples { - /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_ListQuotaReport.json - */ - /** - * Sample code: ListQuotaReport. - * - * @param manager Entry point to NetAppFilesManager. - */ - public static void listQuotaReport(com.azure.resourcemanager.netapp.NetAppFilesManager manager) { - manager.volumes().listQuotaReport("myRG", "account1", "pool1", "volume1", com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesListReplicationsSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesListReplicationsSamples.java index 743e659724c2..d97bb05a9f5b 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesListReplicationsSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesListReplicationsSamples.java @@ -9,8 +9,8 @@ */ public final class VolumesListReplicationsSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_ListReplications.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_ListReplications.json */ /** * Sample code: Volumes_ListReplications. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesListSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesListSamples.java index 0af7a24061ff..261fe3bc27c6 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesListSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesListSamples.java @@ -10,7 +10,7 @@ public final class VolumesListSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Volumes_List.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_List.json */ /** * Sample code: Volumes_List. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesPeerExternalClusterSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesPeerExternalClusterSamples.java index f851efd5355f..b3e79c92eaec 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesPeerExternalClusterSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesPeerExternalClusterSamples.java @@ -12,8 +12,9 @@ */ public final class VolumesPeerExternalClusterSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_PeerExternalCluster.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_PeerExternalCluster. + * json */ /** * Sample code: Volumes_PeerExternalCluster. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesPerformReplicationTransferSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesPerformReplicationTransferSamples.java index 7919c088cf24..e8b7ef28bba0 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesPerformReplicationTransferSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesPerformReplicationTransferSamples.java @@ -9,7 +9,7 @@ */ public final class VolumesPerformReplicationTransferSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ + * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/ * Volumes_PerformReplicationTransfer.json */ /** diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesPoolChangeSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesPoolChangeSamples.java index 48314bffd890..bc53409dd86c 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesPoolChangeSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesPoolChangeSamples.java @@ -12,8 +12,7 @@ public final class VolumesPoolChangeSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Volumes_PoolChange. - * json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_PoolChange.json */ /** * Sample code: Volumes_AuthorizeReplication. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesPopulateAvailabilityZoneSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesPopulateAvailabilityZoneSamples.java index bdc51ca09dba..501d6de16499 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesPopulateAvailabilityZoneSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesPopulateAvailabilityZoneSamples.java @@ -9,7 +9,7 @@ */ public final class VolumesPopulateAvailabilityZoneSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ + * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/ * Volumes_PopulateAvailabilityZones.json */ /** diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesReInitializeReplicationSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesReInitializeReplicationSamples.java index 7b518972a034..c80e86a7aec4 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesReInitializeReplicationSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesReInitializeReplicationSamples.java @@ -9,8 +9,9 @@ */ public final class VolumesReInitializeReplicationSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_ReInitializeReplication.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_ReInitializeReplication + * .json */ /** * Sample code: Volumes_ReInitializeReplication. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesReestablishReplicationSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesReestablishReplicationSamples.java index 233bbf332e98..28bbb51a9dcd 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesReestablishReplicationSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesReestablishReplicationSamples.java @@ -11,8 +11,9 @@ */ public final class VolumesReestablishReplicationSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_ReestablishReplication.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_ReestablishReplication. + * json */ /** * Sample code: Volumes_ReestablishReplication. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesRelocateSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesRelocateSamples.java index b90c5db2fe9d..e0e19da866b0 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesRelocateSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesRelocateSamples.java @@ -12,7 +12,7 @@ public final class VolumesRelocateSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Volumes_Relocate.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_Relocate.json */ /** * Sample code: Volumes_Relocate. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesReplicationStatusSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesReplicationStatusSamples.java index ba1c1606a5b8..db3d82d53d9e 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesReplicationStatusSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesReplicationStatusSamples.java @@ -9,8 +9,8 @@ */ public final class VolumesReplicationStatusSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_ReplicationStatus.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_ReplicationStatus.json */ /** * Sample code: Volumes_ReplicationStatus. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesResetCifsPasswordSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesResetCifsPasswordSamples.java index 4883b39c701a..53e124eaed49 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesResetCifsPasswordSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesResetCifsPasswordSamples.java @@ -9,8 +9,8 @@ */ public final class VolumesResetCifsPasswordSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_ResetCifsPassword.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_ResetCifsPassword.json */ /** * Sample code: Volumes_ResetCifsPassword. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesResyncReplicationSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesResyncReplicationSamples.java index 73757a82a516..6c3efba46062 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesResyncReplicationSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesResyncReplicationSamples.java @@ -9,8 +9,8 @@ */ public final class VolumesResyncReplicationSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_ResyncReplication.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_ResyncReplication.json */ /** * Sample code: Volumes_ResyncReplication. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesRevertRelocationSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesRevertRelocationSamples.java index fc77c0d86c55..63157aa8aed1 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesRevertRelocationSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesRevertRelocationSamples.java @@ -9,8 +9,8 @@ */ public final class VolumesRevertRelocationSamples { /* - * x-ms-original-file: specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/ - * Volumes_RevertRelocation.json + * x-ms-original-file: + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_RevertRelocation.json */ /** * Sample code: Volumes_RevertRelocation. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesRevertSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesRevertSamples.java index 174505c88031..88d73ef79d68 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesRevertSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesRevertSamples.java @@ -12,7 +12,7 @@ public final class VolumesRevertSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Volumes_Revert.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_Revert.json */ /** * Sample code: Volumes_Revert. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesSplitCloneFromParentSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesSplitCloneFromParentSamples.java deleted file mode 100644 index 9e36117d5f35..000000000000 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesSplitCloneFromParentSamples.java +++ /dev/null @@ -1,25 +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.resourcemanager.netapp.generated; - -/** - * Samples for Volumes SplitCloneFromParent. - */ -public final class VolumesSplitCloneFromParentSamples { - /* - * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Volumes_SplitClone. - * json - */ - /** - * Sample code: Volumes_SplitClone. - * - * @param manager Entry point to NetAppFilesManager. - */ - public static void volumesSplitClone(com.azure.resourcemanager.netapp.NetAppFilesManager manager) { - manager.volumes() - .splitCloneFromParent("myRG", "account1", "pool1", "volume1", com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesUpdateSamples.java b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesUpdateSamples.java index aecd4ae5f259..960b6c3fc2eb 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesUpdateSamples.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/samples/java/com/azure/resourcemanager/netapp/generated/VolumesUpdateSamples.java @@ -12,7 +12,7 @@ public final class VolumesUpdateSamples { /* * x-ms-original-file: - * specification/netapp/resource-manager/Microsoft.NetApp/preview/2024-07-01-preview/examples/Volumes_Update.json + * specification/netapp/resource-manager/Microsoft.NetApp/stable/2024-09-01/examples/Volumes_Update.json */ /** * Sample code: Volumes_Update. diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/AccountsRenewCredentialsMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/AccountsRenewCredentialsMockTests.java index 96c2174739a2..870a906a7700 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/AccountsRenewCredentialsMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/AccountsRenewCredentialsMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import java.nio.charset.StandardCharsets; @@ -25,9 +25,9 @@ public void testRenewCredentials() throws Exception { NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); - manager.accounts().renewCredentials("tujwsawdd", "ibabxvititvtzeex", com.azure.core.util.Context.NONE); + manager.accounts().renewCredentials("qvdaeyyguxakjsq", "hzbezkgi", com.azure.core.util.Context.NONE); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/AuthorizeRequestTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/AuthorizeRequestTests.java index 2e0291e1af54..0b82ecd814b5 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/AuthorizeRequestTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/AuthorizeRequestTests.java @@ -12,14 +12,14 @@ public final class AuthorizeRequestTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { AuthorizeRequest model - = BinaryData.fromString("{\"remoteVolumeResourceId\":\"nyga\"}").toObject(AuthorizeRequest.class); - Assertions.assertEquals("nyga", model.remoteVolumeResourceId()); + = BinaryData.fromString("{\"remoteVolumeResourceId\":\"d\"}").toObject(AuthorizeRequest.class); + Assertions.assertEquals("d", model.remoteVolumeResourceId()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - AuthorizeRequest model = new AuthorizeRequest().withRemoteVolumeResourceId("nyga"); + AuthorizeRequest model = new AuthorizeRequest().withRemoteVolumeResourceId("d"); model = BinaryData.fromObject(model).toObject(AuthorizeRequest.class); - Assertions.assertEquals("nyga", model.remoteVolumeResourceId()); + Assertions.assertEquals("d", model.remoteVolumeResourceId()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupInnerTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupInnerTests.java index 3d9c0b1fbfcb..0715848bc71c 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupInnerTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupInnerTests.java @@ -12,24 +12,24 @@ public final class BackupInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { BackupInner model = BinaryData.fromString( - "{\"properties\":{\"backupId\":\"wlvwlyoupf\",\"creationDate\":\"2021-07-15T15:51:01Z\",\"provisioningState\":\"jub\",\"size\":7578973114042008670,\"label\":\"fminsgowzf\",\"backupType\":\"Scheduled\",\"failureReason\":\"t\",\"volumeResourceId\":\"tlahbq\",\"useExistingSnapshot\":false,\"snapshotName\":\"tgzukxitmmqt\",\"backupPolicyResourceId\":\"qqxhrnxrxcpj\",\"isLargeVolume\":true},\"id\":\"vokqdzfv\",\"name\":\"zivj\",\"type\":\"frqttbajlkatnw\"}") + "{\"properties\":{\"backupId\":\"zukxitmmqtgqq\",\"creationDate\":\"2021-05-22T07:03:57Z\",\"provisioningState\":\"n\",\"size\":7842491154861301070,\"label\":\"juisavokqdzf\",\"backupType\":\"Manual\",\"failureReason\":\"vjlfrqtt\",\"volumeResourceId\":\"ajlkatnw\",\"useExistingSnapshot\":false,\"snapshotName\":\"pidkqqfkuvscxkdm\",\"backupPolicyResourceId\":\"govibrxkpmloazu\"},\"id\":\"ocbgoorbteoyb\",\"name\":\"hjxa\",\"type\":\"vvjgslor\"}") .toObject(BackupInner.class); - Assertions.assertEquals("fminsgowzf", model.label()); - Assertions.assertEquals("tlahbq", model.volumeResourceId()); + Assertions.assertEquals("juisavokqdzf", model.label()); + Assertions.assertEquals("ajlkatnw", model.volumeResourceId()); Assertions.assertEquals(false, model.useExistingSnapshot()); - Assertions.assertEquals("tgzukxitmmqt", model.snapshotName()); + Assertions.assertEquals("pidkqqfkuvscxkdm", model.snapshotName()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - BackupInner model = new BackupInner().withLabel("fminsgowzf") - .withVolumeResourceId("tlahbq") + BackupInner model = new BackupInner().withLabel("juisavokqdzf") + .withVolumeResourceId("ajlkatnw") .withUseExistingSnapshot(false) - .withSnapshotName("tgzukxitmmqt"); + .withSnapshotName("pidkqqfkuvscxkdm"); model = BinaryData.fromObject(model).toObject(BackupInner.class); - Assertions.assertEquals("fminsgowzf", model.label()); - Assertions.assertEquals("tlahbq", model.volumeResourceId()); + Assertions.assertEquals("juisavokqdzf", model.label()); + Assertions.assertEquals("ajlkatnw", model.volumeResourceId()); Assertions.assertEquals(false, model.useExistingSnapshot()); - Assertions.assertEquals("tgzukxitmmqt", model.snapshotName()); + Assertions.assertEquals("pidkqqfkuvscxkdm", model.snapshotName()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPatchPropertiesTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPatchPropertiesTests.java index a1b766a71db8..c597cc13004c 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPatchPropertiesTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPatchPropertiesTests.java @@ -11,14 +11,15 @@ public final class BackupPatchPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - BackupPatchProperties model = BinaryData.fromString("{\"label\":\"b\"}").toObject(BackupPatchProperties.class); - Assertions.assertEquals("b", model.label()); + BackupPatchProperties model + = BinaryData.fromString("{\"label\":\"nwqjnoba\"}").toObject(BackupPatchProperties.class); + Assertions.assertEquals("nwqjnoba", model.label()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - BackupPatchProperties model = new BackupPatchProperties().withLabel("b"); + BackupPatchProperties model = new BackupPatchProperties().withLabel("nwqjnoba"); model = BinaryData.fromObject(model).toObject(BackupPatchProperties.class); - Assertions.assertEquals("b", model.label()); + Assertions.assertEquals("nwqjnoba", model.label()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPatchTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPatchTests.java index f0983cdab416..9ea2860a5fd9 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPatchTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPatchTests.java @@ -11,14 +11,14 @@ public final class BackupPatchTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - BackupPatch model = BinaryData.fromString("{\"properties\":{\"label\":\"nye\"}}").toObject(BackupPatch.class); - Assertions.assertEquals("nye", model.label()); + BackupPatch model = BinaryData.fromString("{\"properties\":{\"label\":\"gsj\"}}").toObject(BackupPatch.class); + Assertions.assertEquals("gsj", model.label()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - BackupPatch model = new BackupPatch().withLabel("nye"); + BackupPatch model = new BackupPatch().withLabel("gsj"); model = BinaryData.fromObject(model).toObject(BackupPatch.class); - Assertions.assertEquals("nye", model.label()); + Assertions.assertEquals("gsj", model.label()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesCreateMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesCreateMockTests.java index 2733aff81caf..ef582257e233 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesCreateMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesCreateMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.BackupPolicy; @@ -23,32 +23,32 @@ public final class BackupPoliciesCreateMockTests { @Test public void testCreate() throws Exception { String responseStr - = "{\"etag\":\"mlbnseq\",\"properties\":{\"backupPolicyId\":\"jjvpilguooqja\",\"provisioningState\":\"Succeeded\",\"dailyBackupsToKeep\":1892935943,\"weeklyBackupsToKeep\":436205084,\"monthlyBackupsToKeep\":1799619217,\"volumesAssigned\":1412186545,\"enabled\":false,\"volumeBackups\":[{\"volumeName\":\"rtdtpdelq\",\"volumeResourceId\":\"slmot\",\"backupsCount\":1927909421,\"policyEnabled\":false},{\"volumeName\":\"o\",\"volumeResourceId\":\"cjkgdirazftxej\",\"backupsCount\":1368771016,\"policyEnabled\":true},{\"volumeName\":\"jtmvc\",\"volumeResourceId\":\"excmjurbuhhl\",\"backupsCount\":492324140,\"policyEnabled\":true},{\"volumeName\":\"srogtu\",\"volumeResourceId\":\"ffdjktsysidfvclg\",\"backupsCount\":35443299,\"policyEnabled\":false}]},\"location\":\"jtkbusqogsfika\",\"tags\":{\"ttvwkpqh\":\"nsharujtjiqxfzyj\",\"bqeqqekewvnqvcd\":\"penuy\",\"punj\":\"guaucmfdjwnla\",\"sserxhtvsoxhlwn\":\"ikczvvitacgxmf\"},\"id\":\"sjgqrsxyp\",\"name\":\"uuuybnchrsziz\",\"type\":\"yuel\"}"; + = "{\"etag\":\"qw\",\"properties\":{\"backupPolicyId\":\"d\",\"provisioningState\":\"Succeeded\",\"dailyBackupsToKeep\":999177682,\"weeklyBackupsToKeep\":1674371037,\"monthlyBackupsToKeep\":703161426,\"volumesAssigned\":1221271560,\"enabled\":true,\"volumeBackups\":[{\"volumeName\":\"gwgcl\",\"volumeResourceId\":\"oebqinjipn\",\"backupsCount\":296049099,\"policyEnabled\":true}]},\"location\":\"lafcbahh\",\"tags\":{\"w\":\"ofoiy\",\"ndviauogphuartvt\":\"filkmkkholv\"},\"id\":\"ukyefchnmnahmnxh\",\"name\":\"xjqirwrweoox\",\"type\":\"fifhxwrsnew\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); BackupPolicy response = manager.backupPolicies() - .define("henlusfnr") - .withRegion("epbnwgfm") - .withExistingNetAppAccount("fjmyccxlzhco", "ovne") - .withTags(mapOf("y", "cgbjbgdlfgt", "ctqhamzjrwdk", "naquflq")) - .withDailyBackupsToKeep(2094654345) - .withWeeklyBackupsToKeep(791127597) - .withMonthlyBackupsToKeep(1952443392) + .define("vsg") + .withRegion("xmcuqud") + .withExistingNetAppAccount("fr", "xousxauzl") + .withTags(mapOf("dkvgfabuiyjibuzp", "clxyn")) + .withDailyBackupsToKeep(1994434352) + .withWeeklyBackupsToKeep(468470130) + .withMonthlyBackupsToKeep(1587731345) .withEnabled(false) .create(); - Assertions.assertEquals("jtkbusqogsfika", response.location()); - Assertions.assertEquals("nsharujtjiqxfzyj", response.tags().get("ttvwkpqh")); - Assertions.assertEquals(1892935943, response.dailyBackupsToKeep()); - Assertions.assertEquals(436205084, response.weeklyBackupsToKeep()); - Assertions.assertEquals(1799619217, response.monthlyBackupsToKeep()); - Assertions.assertEquals(false, response.enabled()); + Assertions.assertEquals("lafcbahh", response.location()); + Assertions.assertEquals("ofoiy", response.tags().get("w")); + Assertions.assertEquals(999177682, response.dailyBackupsToKeep()); + Assertions.assertEquals(1674371037, response.weeklyBackupsToKeep()); + Assertions.assertEquals(703161426, response.monthlyBackupsToKeep()); + Assertions.assertEquals(true, response.enabled()); } // Use "Map.of" if available diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesDeleteMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesDeleteMockTests.java index 8dc3d9bbfb5a..99a788b2aa37 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesDeleteMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesDeleteMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import java.nio.charset.StandardCharsets; @@ -25,9 +25,10 @@ public void testDelete() throws Exception { NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); - manager.backupPolicies().delete("iropionszon", "pngajin", "ixjawrtm", com.azure.core.util.Context.NONE); + manager.backupPolicies() + .delete("picrmnzhrgmqgjsx", "pqcbfrmbodthsq", "gvriibakclac", com.azure.core.util.Context.NONE); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesGetWithResponseMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesGetWithResponseMockTests.java index ae5c43f646cf..d6f3fdc1c1f9 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesGetWithResponseMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesGetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.BackupPolicy; @@ -21,24 +21,24 @@ public final class BackupPoliciesGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"etag\":\"qylkmqpzoyhlf\",\"properties\":{\"backupPolicyId\":\"gwgcl\",\"provisioningState\":\"oebqinjipn\",\"dailyBackupsToKeep\":296049099,\"weeklyBackupsToKeep\":1159366069,\"monthlyBackupsToKeep\":2022448357,\"volumesAssigned\":1724104669,\"enabled\":true,\"volumeBackups\":[{\"volumeName\":\"pzpofoiyjw\",\"volumeResourceId\":\"ilkmk\",\"backupsCount\":1346038267,\"policyEnabled\":true},{\"volumeName\":\"ndviauogphuartvt\",\"volumeResourceId\":\"kyefchnmnahmnxhk\",\"backupsCount\":475134082,\"policyEnabled\":true},{\"volumeName\":\"rweooxffifhx\",\"volumeResourceId\":\"snewmozqvbub\",\"backupsCount\":1359553105,\"policyEnabled\":true},{\"volumeName\":\"ycxhxzgaztta\",\"volumeResourceId\":\"idvmfqhppubo\",\"backupsCount\":1380428673,\"policyEnabled\":false}]},\"location\":\"g\",\"tags\":{\"ahokqtobkauxofsh\":\"dherngbtcj\",\"whslwkoj\":\"phwpnulaiywzej\",\"rpqaf\":\"llndnpd\",\"oc\":\"fugsnnfhyetefy\"},\"id\":\"ctfjgtixr\",\"name\":\"vzuyturmlmu\",\"type\":\"wolba\"}"; + = "{\"etag\":\"lqivbgkcv\",\"properties\":{\"backupPolicyId\":\"pzvuqdflvo\",\"provisioningState\":\"yp\",\"dailyBackupsToKeep\":401021303,\"weeklyBackupsToKeep\":38455799,\"monthlyBackupsToKeep\":783120706,\"volumesAssigned\":1879073988,\"enabled\":true,\"volumeBackups\":[{\"volumeName\":\"j\",\"volumeResourceId\":\"idibgqjxgpn\",\"backupsCount\":1622110038,\"policyEnabled\":true},{\"volumeName\":\"gpikqmh\",\"volumeResourceId\":\"owjrmzvuporqz\",\"backupsCount\":1356794202,\"policyEnabled\":true}]},\"location\":\"vkfvxcnqmxqpswok\",\"tags\":{\"gdhbe\":\"hl\"},\"id\":\"zqkzszuwi\",\"name\":\"tglxx\",\"type\":\"ljfp\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); BackupPolicy response = manager.backupPolicies() - .getWithResponse("btozipqwje", "mur", "xxgewpk", com.azure.core.util.Context.NONE) + .getWithResponse("zkc", "yxrxmunj", "xvglnkvxlxp", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("g", response.location()); - Assertions.assertEquals("dherngbtcj", response.tags().get("ahokqtobkauxofsh")); - Assertions.assertEquals(296049099, response.dailyBackupsToKeep()); - Assertions.assertEquals(1159366069, response.weeklyBackupsToKeep()); - Assertions.assertEquals(2022448357, response.monthlyBackupsToKeep()); + Assertions.assertEquals("vkfvxcnqmxqpswok", response.location()); + Assertions.assertEquals("hl", response.tags().get("gdhbe")); + Assertions.assertEquals(401021303, response.dailyBackupsToKeep()); + Assertions.assertEquals(38455799, response.weeklyBackupsToKeep()); + Assertions.assertEquals(783120706, response.monthlyBackupsToKeep()); Assertions.assertEquals(true, response.enabled()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesListMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesListMockTests.java index 4fe728395239..72e7a312c8fe 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesListMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.BackupPolicy; @@ -22,23 +22,23 @@ public final class BackupPoliciesListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"etag\":\"qpswokmvkhlggdhb\",\"properties\":{\"backupPolicyId\":\"zqkzszuwi\",\"provisioningState\":\"glxxhljfpgpic\",\"dailyBackupsToKeep\":1974760632,\"weeklyBackupsToKeep\":285978627,\"monthlyBackupsToKeep\":1409620818,\"volumesAssigned\":1972611629,\"enabled\":false,\"volumeBackups\":[{\"volumeName\":\"pqcbfrmbodthsq\",\"volumeResourceId\":\"vriibakclacjfr\",\"backupsCount\":1419015231,\"policyEnabled\":true}]},\"location\":\"au\",\"tags\":{\"wohqfzizvu\":\"vsg\",\"vmribiat\":\"mmkjsvthnwpztek\",\"zcugswvxwlmzqw\":\"gplucfotangcfhny\",\"cvclxynpdk\":\"vtxnjmxmcuqud\"},\"id\":\"gfabuiyjibuzphdu\",\"name\":\"neiknpg\",\"type\":\"xgjiuqh\"}]}"; + = "{\"value\":[{\"etag\":\"ujztcz\",\"properties\":{\"backupPolicyId\":\"qjtwhauu\",\"provisioningState\":\"prnjletlxsmr\",\"dailyBackupsToKeep\":436134303,\"weeklyBackupsToKeep\":2070557844,\"monthlyBackupsToKeep\":453207888,\"volumesAssigned\":2066157212,\"enabled\":false,\"volumeBackups\":[{\"volumeName\":\"yn\",\"volumeResourceId\":\"lqwzdvpiwhxqsz\",\"backupsCount\":1059489407,\"policyEnabled\":true}]},\"location\":\"quhuxylrj\",\"tags\":{\"kfkyjp\":\"ygjbmzyospspsh\"},\"id\":\"sp\",\"name\":\"pssdfppyogtie\",\"type\":\"ujtv\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response - = manager.backupPolicies().list("zvuporqzdfuydz", "kfvxcnq", com.azure.core.util.Context.NONE); + = manager.backupPolicies().list("quvre", "mrnjh", com.azure.core.util.Context.NONE); - Assertions.assertEquals("au", response.iterator().next().location()); - Assertions.assertEquals("vsg", response.iterator().next().tags().get("wohqfzizvu")); - Assertions.assertEquals(1974760632, response.iterator().next().dailyBackupsToKeep()); - Assertions.assertEquals(285978627, response.iterator().next().weeklyBackupsToKeep()); - Assertions.assertEquals(1409620818, response.iterator().next().monthlyBackupsToKeep()); + Assertions.assertEquals("quhuxylrj", response.iterator().next().location()); + Assertions.assertEquals("ygjbmzyospspsh", response.iterator().next().tags().get("kfkyjp")); + Assertions.assertEquals(436134303, response.iterator().next().dailyBackupsToKeep()); + Assertions.assertEquals(2070557844, response.iterator().next().weeklyBackupsToKeep()); + Assertions.assertEquals(453207888, response.iterator().next().monthlyBackupsToKeep()); Assertions.assertEquals(false, response.iterator().next().enabled()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesListTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesListTests.java index 5e73070025a8..c02a1c94cf45 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesListTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPoliciesListTests.java @@ -16,50 +16,50 @@ public final class BackupPoliciesListTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { BackupPoliciesList model = BinaryData.fromString( - "{\"value\":[{\"etag\":\"cccnxqhuexmktt\",\"properties\":{\"backupPolicyId\":\"tvlz\",\"provisioningState\":\"emhzrncsdtc\",\"dailyBackupsToKeep\":1367209105,\"weeklyBackupsToKeep\":2121256273,\"monthlyBackupsToKeep\":1137275627,\"volumesAssigned\":1674447280,\"enabled\":false,\"volumeBackups\":[{\"volumeName\":\"sl\",\"volumeResourceId\":\"adcy\",\"backupsCount\":448514309,\"policyEnabled\":true}]},\"location\":\"ejhzisxg\",\"tags\":{\"vk\":\"lolp\",\"qvujzraehtwdwrf\":\"r\",\"dl\":\"swibyr\",\"hfwpracstwit\":\"h\"},\"id\":\"khevxccedc\",\"name\":\"nmdyodnwzxl\",\"type\":\"jc\"},{\"etag\":\"hlt\",\"properties\":{\"backupPolicyId\":\"gcxn\",\"provisioningState\":\"vwxqibyqunyo\",\"dailyBackupsToKeep\":2001486807,\"weeklyBackupsToKeep\":1090974611,\"monthlyBackupsToKeep\":1597116231,\"volumesAssigned\":351776134,\"enabled\":true,\"volumeBackups\":[{\"volumeName\":\"fvpdbo\",\"volumeResourceId\":\"cizsjqlhkrribdei\",\"backupsCount\":1262026177,\"policyEnabled\":false},{\"volumeName\":\"ghvxndzwmkrefa\",\"volumeResourceId\":\"jorwkqnyhgbij\",\"backupsCount\":1741167059,\"policyEnabled\":true},{\"volumeName\":\"zs\",\"volumeResourceId\":\"bibsystawfsdjpvk\",\"backupsCount\":250834954,\"policyEnabled\":true}]},\"location\":\"kzbzkdvncjabudu\",\"tags\":{\"hmouwqlgzrfze\":\"akmokzhjjklf\",\"lbjbsyb\":\"yebizikayuh\"},\"id\":\"qwrvtldgmfp\",\"name\":\"vm\",\"type\":\"ipaslthaqfxssmwu\"},{\"etag\":\"bdsrez\",\"properties\":{\"backupPolicyId\":\"rhneuyowq\",\"provisioningState\":\"wyt\",\"dailyBackupsToKeep\":372277345,\"weeklyBackupsToKeep\":97621763,\"monthlyBackupsToKeep\":1145560346,\"volumesAssigned\":1229797985,\"enabled\":false,\"volumeBackups\":[{\"volumeName\":\"mejzanlfzxia\",\"volumeResourceId\":\"mbzonokix\",\"backupsCount\":115638191,\"policyEnabled\":false},{\"volumeName\":\"gzpfrla\",\"volumeResourceId\":\"zrnw\",\"backupsCount\":409653705,\"policyEnabled\":true},{\"volumeName\":\"pwp\",\"volumeResourceId\":\"lwbtlhf\",\"backupsCount\":901371312,\"policyEnabled\":false}]},\"location\":\"szfjvfbgofelja\",\"tags\":{\"ojnal\":\"mqhldvrii\",\"qhhahhxvrhmzkwpj\":\"hfkvtvsexsowuel\",\"ughftqsx\":\"wws\"},\"id\":\"qxujxukndxd\",\"name\":\"grjguufzd\",\"type\":\"syqtfi\"}]}") + "{\"value\":[{\"etag\":\"ggicccnxqhue\",\"properties\":{\"backupPolicyId\":\"ktt\",\"provisioningState\":\"tvlz\",\"dailyBackupsToKeep\":798208756,\"weeklyBackupsToKeep\":471536025,\"monthlyBackupsToKeep\":218184123,\"volumesAssigned\":1311146203,\"enabled\":true,\"volumeBackups\":[{\"volumeName\":\"u\",\"volumeResourceId\":\"ypbsfgytguslfead\",\"backupsCount\":358703588,\"policyEnabled\":true},{\"volumeName\":\"yhejhzisxgfp\",\"volumeResourceId\":\"olppvksrpqvujz\",\"backupsCount\":126730684,\"policyEnabled\":false}]},\"location\":\"dw\",\"tags\":{\"dl\":\"swibyr\",\"hfwpracstwit\":\"h\"},\"id\":\"khevxccedc\",\"name\":\"nmdyodnwzxl\",\"type\":\"jc\"},{\"etag\":\"hlt\",\"properties\":{\"backupPolicyId\":\"gcxn\",\"provisioningState\":\"vwxqibyqunyo\",\"dailyBackupsToKeep\":2001486807,\"weeklyBackupsToKeep\":1090974611,\"monthlyBackupsToKeep\":1597116231,\"volumesAssigned\":351776134,\"enabled\":true,\"volumeBackups\":[{\"volumeName\":\"fvpdbo\",\"volumeResourceId\":\"cizsjqlhkrribdei\",\"backupsCount\":1262026177,\"policyEnabled\":false},{\"volumeName\":\"ghvxndzwmkrefa\",\"volumeResourceId\":\"jorwkqnyhgbij\",\"backupsCount\":1741167059,\"policyEnabled\":true},{\"volumeName\":\"zs\",\"volumeResourceId\":\"bibsystawfsdjpvk\",\"backupsCount\":250834954,\"policyEnabled\":true}]},\"location\":\"kzbzkdvncjabudu\",\"tags\":{\"hmouwqlgzrfze\":\"akmokzhjjklf\",\"lbjbsyb\":\"yebizikayuh\"},\"id\":\"qwrvtldgmfp\",\"name\":\"vm\",\"type\":\"ipaslthaqfxssmwu\"},{\"etag\":\"bdsrez\",\"properties\":{\"backupPolicyId\":\"rhneuyowq\",\"provisioningState\":\"wyt\",\"dailyBackupsToKeep\":372277345,\"weeklyBackupsToKeep\":97621763,\"monthlyBackupsToKeep\":1145560346,\"volumesAssigned\":1229797985,\"enabled\":false,\"volumeBackups\":[{\"volumeName\":\"mejzanlfzxia\",\"volumeResourceId\":\"mbzonokix\",\"backupsCount\":115638191,\"policyEnabled\":false},{\"volumeName\":\"gzpfrla\",\"volumeResourceId\":\"zrnw\",\"backupsCount\":409653705,\"policyEnabled\":true},{\"volumeName\":\"pwp\",\"volumeResourceId\":\"lwbtlhf\",\"backupsCount\":901371312,\"policyEnabled\":false}]},\"location\":\"szfjvfbgofelja\",\"tags\":{\"ojnal\":\"mqhldvrii\",\"qhhahhxvrhmzkwpj\":\"hfkvtvsexsowuel\",\"ughftqsx\":\"wws\"},\"id\":\"qxujxukndxd\",\"name\":\"grjguufzd\",\"type\":\"syqtfi\"},{\"etag\":\"hbotzingamvppho\",\"properties\":{\"backupPolicyId\":\"qzudphq\",\"provisioningState\":\"vdkfwynwcvtbvk\",\"dailyBackupsToKeep\":1479821561,\"weeklyBackupsToKeep\":911796600,\"monthlyBackupsToKeep\":1206519159,\"volumesAssigned\":565781188,\"enabled\":true,\"volumeBackups\":[{\"volumeName\":\"wp\",\"volumeResourceId\":\"p\",\"backupsCount\":219155482,\"policyEnabled\":false},{\"volumeName\":\"sgvvsccyajguq\",\"volumeResourceId\":\"wygzlvdnkfxusem\",\"backupsCount\":1095077901,\"policyEnabled\":true}]},\"location\":\"hapfcqdpsqx\",\"tags\":{\"mgccelvezrypq\":\"svuo\",\"kerqwkyh\":\"mfe\",\"pg\":\"ob\"},\"id\":\"edkowepbqpcrfk\",\"name\":\"wccsnjvcdwxlpqek\",\"type\":\"tn\"}]}") .toObject(BackupPoliciesList.class); - Assertions.assertEquals("ejhzisxg", model.value().get(0).location()); - Assertions.assertEquals("lolp", model.value().get(0).tags().get("vk")); - Assertions.assertEquals(1367209105, model.value().get(0).dailyBackupsToKeep()); - Assertions.assertEquals(2121256273, model.value().get(0).weeklyBackupsToKeep()); - Assertions.assertEquals(1137275627, model.value().get(0).monthlyBackupsToKeep()); - Assertions.assertEquals(false, model.value().get(0).enabled()); + Assertions.assertEquals("dw", model.value().get(0).location()); + Assertions.assertEquals("swibyr", model.value().get(0).tags().get("dl")); + Assertions.assertEquals(798208756, model.value().get(0).dailyBackupsToKeep()); + Assertions.assertEquals(471536025, model.value().get(0).weeklyBackupsToKeep()); + Assertions.assertEquals(218184123, model.value().get(0).monthlyBackupsToKeep()); + Assertions.assertEquals(true, model.value().get(0).enabled()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - BackupPoliciesList model - = new BackupPoliciesList() - .withValue( - Arrays - .asList( - new BackupPolicyInner().withLocation("ejhzisxg") - .withTags( - mapOf("vk", "lolp", "qvujzraehtwdwrf", "r", "dl", "swibyr", "hfwpracstwit", "h")) - .withDailyBackupsToKeep(1367209105) - .withWeeklyBackupsToKeep(2121256273) - .withMonthlyBackupsToKeep(1137275627) - .withEnabled(false), - new BackupPolicyInner().withLocation("kzbzkdvncjabudu") - .withTags(mapOf("hmouwqlgzrfze", "akmokzhjjklf", "lbjbsyb", "yebizikayuh")) - .withDailyBackupsToKeep(2001486807) - .withWeeklyBackupsToKeep(1090974611) - .withMonthlyBackupsToKeep(1597116231) - .withEnabled(true), - new BackupPolicyInner().withLocation("szfjvfbgofelja") - .withTags(mapOf("ojnal", "mqhldvrii", "qhhahhxvrhmzkwpj", "hfkvtvsexsowuel", "ughftqsx", - "wws")) - .withDailyBackupsToKeep(372277345) - .withWeeklyBackupsToKeep(97621763) - .withMonthlyBackupsToKeep(1145560346) - .withEnabled(false))); + BackupPoliciesList model = new BackupPoliciesList().withValue(Arrays.asList( + new BackupPolicyInner().withLocation("dw") + .withTags(mapOf("dl", "swibyr", "hfwpracstwit", "h")) + .withDailyBackupsToKeep(798208756) + .withWeeklyBackupsToKeep(471536025) + .withMonthlyBackupsToKeep(218184123) + .withEnabled(true), + new BackupPolicyInner().withLocation("kzbzkdvncjabudu") + .withTags(mapOf("hmouwqlgzrfze", "akmokzhjjklf", "lbjbsyb", "yebizikayuh")) + .withDailyBackupsToKeep(2001486807) + .withWeeklyBackupsToKeep(1090974611) + .withMonthlyBackupsToKeep(1597116231) + .withEnabled(true), + new BackupPolicyInner().withLocation("szfjvfbgofelja") + .withTags(mapOf("ojnal", "mqhldvrii", "qhhahhxvrhmzkwpj", "hfkvtvsexsowuel", "ughftqsx", "wws")) + .withDailyBackupsToKeep(372277345) + .withWeeklyBackupsToKeep(97621763) + .withMonthlyBackupsToKeep(1145560346) + .withEnabled(false), + new BackupPolicyInner().withLocation("hapfcqdpsqx") + .withTags(mapOf("mgccelvezrypq", "svuo", "kerqwkyh", "mfe", "pg", "ob")) + .withDailyBackupsToKeep(1479821561) + .withWeeklyBackupsToKeep(911796600) + .withMonthlyBackupsToKeep(1206519159) + .withEnabled(true))); model = BinaryData.fromObject(model).toObject(BackupPoliciesList.class); - Assertions.assertEquals("ejhzisxg", model.value().get(0).location()); - Assertions.assertEquals("lolp", model.value().get(0).tags().get("vk")); - Assertions.assertEquals(1367209105, model.value().get(0).dailyBackupsToKeep()); - Assertions.assertEquals(2121256273, model.value().get(0).weeklyBackupsToKeep()); - Assertions.assertEquals(1137275627, model.value().get(0).monthlyBackupsToKeep()); - Assertions.assertEquals(false, model.value().get(0).enabled()); + Assertions.assertEquals("dw", model.value().get(0).location()); + Assertions.assertEquals("swibyr", model.value().get(0).tags().get("dl")); + Assertions.assertEquals(798208756, model.value().get(0).dailyBackupsToKeep()); + Assertions.assertEquals(471536025, model.value().get(0).weeklyBackupsToKeep()); + Assertions.assertEquals(218184123, model.value().get(0).monthlyBackupsToKeep()); + Assertions.assertEquals(true, model.value().get(0).enabled()); } // Use "Map.of" if available diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPolicyInnerTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPolicyInnerTests.java index d85451931ea7..9f375aa2dcfb 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPolicyInnerTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPolicyInnerTests.java @@ -14,31 +14,32 @@ public final class BackupPolicyInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { BackupPolicyInner model = BinaryData.fromString( - "{\"etag\":\"hbotzingamvppho\",\"properties\":{\"backupPolicyId\":\"qzudphq\",\"provisioningState\":\"vdkfwynwcvtbvk\",\"dailyBackupsToKeep\":1479821561,\"weeklyBackupsToKeep\":911796600,\"monthlyBackupsToKeep\":1206519159,\"volumesAssigned\":565781188,\"enabled\":true,\"volumeBackups\":[{\"volumeName\":\"wp\",\"volumeResourceId\":\"p\",\"backupsCount\":219155482,\"policyEnabled\":false},{\"volumeName\":\"sgvvsccyajguq\",\"volumeResourceId\":\"wygzlvdnkfxusem\",\"backupsCount\":1095077901,\"policyEnabled\":true}]},\"location\":\"hapfcqdpsqx\",\"tags\":{\"mgccelvezrypq\":\"svuo\",\"kerqwkyh\":\"mfe\",\"pg\":\"ob\"},\"id\":\"edkowepbqpcrfk\",\"name\":\"wccsnjvcdwxlpqek\",\"type\":\"tn\"}") + "{\"etag\":\"tjsyin\",\"properties\":{\"backupPolicyId\":\"fq\",\"provisioningState\":\"mtdh\",\"dailyBackupsToKeep\":709166537,\"weeklyBackupsToKeep\":1330472875,\"monthlyBackupsToKeep\":1700439966,\"volumesAssigned\":811019553,\"enabled\":false,\"volumeBackups\":[{\"volumeName\":\"w\",\"volumeResourceId\":\"irryuzhlh\",\"backupsCount\":904307607,\"policyEnabled\":false},{\"volumeName\":\"qqaatjinrvgou\",\"volumeResourceId\":\"fiibfggjioolvr\",\"backupsCount\":1483667739,\"policyEnabled\":true}]},\"location\":\"k\",\"tags\":{\"vblm\":\"qwjygvja\",\"byrqufeg\":\"vkzuhbxvvyhgso\",\"mctlpdngitv\":\"uvwzfbnh\",\"grhbpn\":\"bmhrixkwmyijejv\"},\"id\":\"ixexcc\",\"name\":\"dreaxh\",\"type\":\"exdrrvqahqkg\"}") .toObject(BackupPolicyInner.class); - Assertions.assertEquals("hapfcqdpsqx", model.location()); - Assertions.assertEquals("svuo", model.tags().get("mgccelvezrypq")); - Assertions.assertEquals(1479821561, model.dailyBackupsToKeep()); - Assertions.assertEquals(911796600, model.weeklyBackupsToKeep()); - Assertions.assertEquals(1206519159, model.monthlyBackupsToKeep()); - Assertions.assertEquals(true, model.enabled()); + Assertions.assertEquals("k", model.location()); + Assertions.assertEquals("qwjygvja", model.tags().get("vblm")); + Assertions.assertEquals(709166537, model.dailyBackupsToKeep()); + Assertions.assertEquals(1330472875, model.weeklyBackupsToKeep()); + Assertions.assertEquals(1700439966, model.monthlyBackupsToKeep()); + Assertions.assertEquals(false, model.enabled()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - BackupPolicyInner model = new BackupPolicyInner().withLocation("hapfcqdpsqx") - .withTags(mapOf("mgccelvezrypq", "svuo", "kerqwkyh", "mfe", "pg", "ob")) - .withDailyBackupsToKeep(1479821561) - .withWeeklyBackupsToKeep(911796600) - .withMonthlyBackupsToKeep(1206519159) - .withEnabled(true); + BackupPolicyInner model = new BackupPolicyInner().withLocation("k") + .withTags(mapOf("vblm", "qwjygvja", "byrqufeg", "vkzuhbxvvyhgso", "mctlpdngitv", "uvwzfbnh", "grhbpn", + "bmhrixkwmyijejv")) + .withDailyBackupsToKeep(709166537) + .withWeeklyBackupsToKeep(1330472875) + .withMonthlyBackupsToKeep(1700439966) + .withEnabled(false); model = BinaryData.fromObject(model).toObject(BackupPolicyInner.class); - Assertions.assertEquals("hapfcqdpsqx", model.location()); - Assertions.assertEquals("svuo", model.tags().get("mgccelvezrypq")); - Assertions.assertEquals(1479821561, model.dailyBackupsToKeep()); - Assertions.assertEquals(911796600, model.weeklyBackupsToKeep()); - Assertions.assertEquals(1206519159, model.monthlyBackupsToKeep()); - Assertions.assertEquals(true, model.enabled()); + Assertions.assertEquals("k", model.location()); + Assertions.assertEquals("qwjygvja", model.tags().get("vblm")); + Assertions.assertEquals(709166537, model.dailyBackupsToKeep()); + Assertions.assertEquals(1330472875, model.weeklyBackupsToKeep()); + Assertions.assertEquals(1700439966, model.monthlyBackupsToKeep()); + Assertions.assertEquals(false, model.enabled()); } // Use "Map.of" if available diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPolicyPatchTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPolicyPatchTests.java index b0dc82a5f7a7..6261a45ee28e 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPolicyPatchTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPolicyPatchTests.java @@ -14,30 +14,30 @@ public final class BackupPolicyPatchTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { BackupPolicyPatch model = BinaryData.fromString( - "{\"properties\":{\"backupPolicyId\":\"llqwjygvjayvblmh\",\"provisioningState\":\"zuhbxvvyhgsopb\",\"dailyBackupsToKeep\":1164866415,\"weeklyBackupsToKeep\":338245093,\"monthlyBackupsToKeep\":175567556,\"volumesAssigned\":2128318759,\"enabled\":false,\"volumeBackups\":[{\"volumeName\":\"nhlmctlpdng\",\"volumeResourceId\":\"vgbmhr\",\"backupsCount\":283160638,\"policyEnabled\":true}]},\"location\":\"yijejvegrhbpnaix\",\"tags\":{\"rvqahqkghtpwi\":\"cbdreaxhcexd\",\"ycxzbfvoo\":\"nhyjsv\"},\"id\":\"vrvmtgjqppyost\",\"name\":\"on\",\"type\":\"myhgfipnsxkmc\"}") + "{\"properties\":{\"backupPolicyId\":\"vfelfktgplcrpwj\",\"provisioningState\":\"znoigbrn\",\"dailyBackupsToKeep\":509080980,\"weeklyBackupsToKeep\":820542416,\"monthlyBackupsToKeep\":1312335759,\"volumesAssigned\":650056423,\"enabled\":false,\"volumeBackups\":[{\"volumeName\":\"oqkag\",\"volumeResourceId\":\"sxtta\",\"backupsCount\":1689987065,\"policyEnabled\":true},{\"volumeName\":\"aa\",\"volumeResourceId\":\"xdtnkdmkqjjlw\",\"backupsCount\":953269937,\"policyEnabled\":true}]},\"location\":\"kpyouaibrebqaay\",\"tags\":{\"ttezlw\":\"ixqtn\",\"pqqmted\":\"ffiakp\",\"wau\":\"tmmjihyeozph\"},\"id\":\"qncygupkvi\",\"name\":\"mdscwxqupev\",\"type\":\"hfstotxhojujbyp\"}") .toObject(BackupPolicyPatch.class); - Assertions.assertEquals("yijejvegrhbpnaix", model.location()); - Assertions.assertEquals("cbdreaxhcexd", model.tags().get("rvqahqkghtpwi")); - Assertions.assertEquals(1164866415, model.dailyBackupsToKeep()); - Assertions.assertEquals(338245093, model.weeklyBackupsToKeep()); - Assertions.assertEquals(175567556, model.monthlyBackupsToKeep()); + Assertions.assertEquals("kpyouaibrebqaay", model.location()); + Assertions.assertEquals("ixqtn", model.tags().get("ttezlw")); + Assertions.assertEquals(509080980, model.dailyBackupsToKeep()); + Assertions.assertEquals(820542416, model.weeklyBackupsToKeep()); + Assertions.assertEquals(1312335759, model.monthlyBackupsToKeep()); Assertions.assertEquals(false, model.enabled()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - BackupPolicyPatch model = new BackupPolicyPatch().withLocation("yijejvegrhbpnaix") - .withTags(mapOf("rvqahqkghtpwi", "cbdreaxhcexd", "ycxzbfvoo", "nhyjsv")) - .withDailyBackupsToKeep(1164866415) - .withWeeklyBackupsToKeep(338245093) - .withMonthlyBackupsToKeep(175567556) + BackupPolicyPatch model = new BackupPolicyPatch().withLocation("kpyouaibrebqaay") + .withTags(mapOf("ttezlw", "ixqtn", "pqqmted", "ffiakp", "wau", "tmmjihyeozph")) + .withDailyBackupsToKeep(509080980) + .withWeeklyBackupsToKeep(820542416) + .withMonthlyBackupsToKeep(1312335759) .withEnabled(false); model = BinaryData.fromObject(model).toObject(BackupPolicyPatch.class); - Assertions.assertEquals("yijejvegrhbpnaix", model.location()); - Assertions.assertEquals("cbdreaxhcexd", model.tags().get("rvqahqkghtpwi")); - Assertions.assertEquals(1164866415, model.dailyBackupsToKeep()); - Assertions.assertEquals(338245093, model.weeklyBackupsToKeep()); - Assertions.assertEquals(175567556, model.monthlyBackupsToKeep()); + Assertions.assertEquals("kpyouaibrebqaay", model.location()); + Assertions.assertEquals("ixqtn", model.tags().get("ttezlw")); + Assertions.assertEquals(509080980, model.dailyBackupsToKeep()); + Assertions.assertEquals(820542416, model.weeklyBackupsToKeep()); + Assertions.assertEquals(1312335759, model.monthlyBackupsToKeep()); Assertions.assertEquals(false, model.enabled()); } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPolicyPropertiesTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPolicyPropertiesTests.java index f2442f76295f..c12d511ed039 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPolicyPropertiesTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPolicyPropertiesTests.java @@ -12,24 +12,24 @@ public final class BackupPolicyPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { BackupPolicyProperties model = BinaryData.fromString( - "{\"backupPolicyId\":\"tjsyin\",\"provisioningState\":\"fq\",\"dailyBackupsToKeep\":881453963,\"weeklyBackupsToKeep\":942135651,\"monthlyBackupsToKeep\":872729199,\"volumesAssigned\":709166537,\"enabled\":false,\"volumeBackups\":[{\"volumeName\":\"kdgszywkbirr\",\"volumeResourceId\":\"zh\",\"backupsCount\":524454595,\"policyEnabled\":true},{\"volumeName\":\"rvqqaatj\",\"volumeResourceId\":\"rv\",\"backupsCount\":162856777,\"policyEnabled\":true}]}") + "{\"backupPolicyId\":\"pwijnhy\",\"provisioningState\":\"vfycxzb\",\"dailyBackupsToKeep\":1564652638,\"weeklyBackupsToKeep\":1626035296,\"monthlyBackupsToKeep\":1844906639,\"volumesAssigned\":561750427,\"enabled\":false,\"volumeBackups\":[{\"volumeName\":\"pyostronzmyhgfi\",\"volumeResourceId\":\"sxkm\",\"backupsCount\":115360224,\"policyEnabled\":false}]}") .toObject(BackupPolicyProperties.class); - Assertions.assertEquals(881453963, model.dailyBackupsToKeep()); - Assertions.assertEquals(942135651, model.weeklyBackupsToKeep()); - Assertions.assertEquals(872729199, model.monthlyBackupsToKeep()); + Assertions.assertEquals(1564652638, model.dailyBackupsToKeep()); + Assertions.assertEquals(1626035296, model.weeklyBackupsToKeep()); + Assertions.assertEquals(1844906639, model.monthlyBackupsToKeep()); Assertions.assertEquals(false, model.enabled()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - BackupPolicyProperties model = new BackupPolicyProperties().withDailyBackupsToKeep(881453963) - .withWeeklyBackupsToKeep(942135651) - .withMonthlyBackupsToKeep(872729199) + BackupPolicyProperties model = new BackupPolicyProperties().withDailyBackupsToKeep(1564652638) + .withWeeklyBackupsToKeep(1626035296) + .withMonthlyBackupsToKeep(1844906639) .withEnabled(false); model = BinaryData.fromObject(model).toObject(BackupPolicyProperties.class); - Assertions.assertEquals(881453963, model.dailyBackupsToKeep()); - Assertions.assertEquals(942135651, model.weeklyBackupsToKeep()); - Assertions.assertEquals(872729199, model.monthlyBackupsToKeep()); + Assertions.assertEquals(1564652638, model.dailyBackupsToKeep()); + Assertions.assertEquals(1626035296, model.weeklyBackupsToKeep()); + Assertions.assertEquals(1844906639, model.monthlyBackupsToKeep()); Assertions.assertEquals(false, model.enabled()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPropertiesTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPropertiesTests.java index e9026880ff60..dd25ba97a954 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPropertiesTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupPropertiesTests.java @@ -12,24 +12,24 @@ public final class BackupPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { BackupProperties model = BinaryData.fromString( - "{\"backupId\":\"iopid\",\"creationDate\":\"2021-07-26T10:21:10Z\",\"provisioningState\":\"kuvscxkdm\",\"size\":7887453097536877840,\"label\":\"ibrxkp\",\"backupType\":\"Manual\",\"failureReason\":\"zuruocbgo\",\"volumeResourceId\":\"rb\",\"useExistingSnapshot\":true,\"snapshotName\":\"bfhjxakvvjgsl\",\"backupPolicyResourceId\":\"dilmyww\",\"isLargeVolume\":true}") + "{\"backupId\":\"lmywwtkgkxnyed\",\"creationDate\":\"2021-04-02T22:41:49Z\",\"provisioningState\":\"vudtjuewbcihx\",\"size\":8529210988663924924,\"label\":\"j\",\"backupType\":\"Manual\",\"failureReason\":\"ybvpay\",\"volumeResourceId\":\"kkudzp\",\"useExistingSnapshot\":false,\"snapshotName\":\"plmag\",\"backupPolicyResourceId\":\"cyohpfkyrkdbd\"}") .toObject(BackupProperties.class); - Assertions.assertEquals("ibrxkp", model.label()); - Assertions.assertEquals("rb", model.volumeResourceId()); - Assertions.assertEquals(true, model.useExistingSnapshot()); - Assertions.assertEquals("bfhjxakvvjgsl", model.snapshotName()); + Assertions.assertEquals("j", model.label()); + Assertions.assertEquals("kkudzp", model.volumeResourceId()); + Assertions.assertEquals(false, model.useExistingSnapshot()); + Assertions.assertEquals("plmag", model.snapshotName()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - BackupProperties model = new BackupProperties().withLabel("ibrxkp") - .withVolumeResourceId("rb") - .withUseExistingSnapshot(true) - .withSnapshotName("bfhjxakvvjgsl"); + BackupProperties model = new BackupProperties().withLabel("j") + .withVolumeResourceId("kkudzp") + .withUseExistingSnapshot(false) + .withSnapshotName("plmag"); model = BinaryData.fromObject(model).toObject(BackupProperties.class); - Assertions.assertEquals("ibrxkp", model.label()); - Assertions.assertEquals("rb", model.volumeResourceId()); - Assertions.assertEquals(true, model.useExistingSnapshot()); - Assertions.assertEquals("bfhjxakvvjgsl", model.snapshotName()); + Assertions.assertEquals("j", model.label()); + Assertions.assertEquals("kkudzp", model.volumeResourceId()); + Assertions.assertEquals(false, model.useExistingSnapshot()); + Assertions.assertEquals("plmag", model.snapshotName()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupRestoreFilesTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupRestoreFilesTests.java index 2f074e7199dd..4621e19cda80 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupRestoreFilesTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupRestoreFilesTests.java @@ -13,21 +13,21 @@ public final class BackupRestoreFilesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { BackupRestoreFiles model = BinaryData.fromString( - "{\"fileList\":[\"raauzzpt\",\"a\"],\"restoreFilePath\":\"sdzhezww\",\"destinationVolumeId\":\"aiqyuvvfo\"}") + "{\"fileList\":[\"eewchpxlktw\",\"uziycsl\",\"vu\"],\"restoreFilePath\":\"ztcktyh\",\"destinationVolumeId\":\"tqedcgzulwm\"}") .toObject(BackupRestoreFiles.class); - Assertions.assertEquals("raauzzpt", model.fileList().get(0)); - Assertions.assertEquals("sdzhezww", model.restoreFilePath()); - Assertions.assertEquals("aiqyuvvfo", model.destinationVolumeId()); + Assertions.assertEquals("eewchpxlktw", model.fileList().get(0)); + Assertions.assertEquals("ztcktyh", model.restoreFilePath()); + Assertions.assertEquals("tqedcgzulwm", model.destinationVolumeId()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - BackupRestoreFiles model = new BackupRestoreFiles().withFileList(Arrays.asList("raauzzpt", "a")) - .withRestoreFilePath("sdzhezww") - .withDestinationVolumeId("aiqyuvvfo"); + BackupRestoreFiles model = new BackupRestoreFiles().withFileList(Arrays.asList("eewchpxlktw", "uziycsl", "vu")) + .withRestoreFilePath("ztcktyh") + .withDestinationVolumeId("tqedcgzulwm"); model = BinaryData.fromObject(model).toObject(BackupRestoreFiles.class); - Assertions.assertEquals("raauzzpt", model.fileList().get(0)); - Assertions.assertEquals("sdzhezww", model.restoreFilePath()); - Assertions.assertEquals("aiqyuvvfo", model.destinationVolumeId()); + Assertions.assertEquals("eewchpxlktw", model.fileList().get(0)); + Assertions.assertEquals("ztcktyh", model.restoreFilePath()); + Assertions.assertEquals("tqedcgzulwm", model.destinationVolumeId()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupStatusInnerTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupStatusInnerTests.java index 9f9ca495c0e2..8a830433ac9d 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupStatusInnerTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupStatusInnerTests.java @@ -11,7 +11,7 @@ public final class BackupStatusInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { BackupStatusInner model = BinaryData.fromString( - "{\"healthy\":false,\"relationshipStatus\":\"Unknown\",\"mirrorState\":\"Uninitialized\",\"unhealthyReason\":\"gzslesjcbhernnti\",\"errorMessage\":\"djc\",\"lastTransferSize\":1220945276828738413,\"lastTransferType\":\"rbe\",\"totalTransferBytes\":8622823251017389633,\"transferProgressBytes\":226230104431146502}") + "{\"healthy\":true,\"relationshipStatus\":\"Failed\",\"mirrorState\":\"Broken\",\"unhealthyReason\":\"s\",\"errorMessage\":\"dotcubiipuip\",\"lastTransferSize\":7194165159471944548,\"lastTransferType\":\"macjekn\",\"totalTransferBytes\":1517216245064921581,\"transferProgressBytes\":7133413366116679058}") .toObject(BackupStatusInner.class); } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupVaultInnerTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupVaultInnerTests.java index b36db69e0ffd..348a13f5692d 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupVaultInnerTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupVaultInnerTests.java @@ -14,19 +14,20 @@ public final class BackupVaultInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { BackupVaultInner model = BinaryData.fromString( - "{\"properties\":{\"provisioningState\":\"vqeevtoep\"},\"location\":\"utnwytpzdmovzvf\",\"tags\":{\"f\":\"wzqa\",\"cokpv\":\"gzuriglaecxndt\"},\"id\":\"mlqtmldgxob\",\"name\":\"irclnpk\",\"type\":\"iayz\"}") + "{\"properties\":{\"provisioningState\":\"jvlpjxxkzbr\"},\"location\":\"geivsiykzkdncj\",\"tags\":{\"apzwyrpgog\":\"nbzoggcu\",\"yjt\":\"qxepnylbfuaj\",\"byfmowuxr\":\"vofqzhvfc\",\"xfzwi\":\"jpvd\"},\"id\":\"vwzjbhyz\",\"name\":\"xjrk\",\"type\":\"mbtrnegvmnvu\"}") .toObject(BackupVaultInner.class); - Assertions.assertEquals("utnwytpzdmovzvf", model.location()); - Assertions.assertEquals("wzqa", model.tags().get("f")); + Assertions.assertEquals("geivsiykzkdncj", model.location()); + Assertions.assertEquals("nbzoggcu", model.tags().get("apzwyrpgog")); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - BackupVaultInner model = new BackupVaultInner().withLocation("utnwytpzdmovzvf") - .withTags(mapOf("f", "wzqa", "cokpv", "gzuriglaecxndt")); + BackupVaultInner model = new BackupVaultInner().withLocation("geivsiykzkdncj") + .withTags( + mapOf("apzwyrpgog", "nbzoggcu", "yjt", "qxepnylbfuaj", "byfmowuxr", "vofqzhvfc", "xfzwi", "jpvd")); model = BinaryData.fromObject(model).toObject(BackupVaultInner.class); - Assertions.assertEquals("utnwytpzdmovzvf", model.location()); - Assertions.assertEquals("wzqa", model.tags().get("f")); + Assertions.assertEquals("geivsiykzkdncj", model.location()); + Assertions.assertEquals("nbzoggcu", model.tags().get("apzwyrpgog")); } // Use "Map.of" if available diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupVaultPatchTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupVaultPatchTests.java index dac4ff827cbb..7af4d09934cf 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupVaultPatchTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupVaultPatchTests.java @@ -14,15 +14,15 @@ public final class BackupVaultPatchTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { BackupVaultPatch model - = BinaryData.fromString("{\"tags\":{\"ynhdwdigum\":\"xhom\"}}").toObject(BackupVaultPatch.class); - Assertions.assertEquals("xhom", model.tags().get("ynhdwdigum")); + = BinaryData.fromString("{\"tags\":{\"rriloz\":\"vestmjl\"}}").toObject(BackupVaultPatch.class); + Assertions.assertEquals("vestmjl", model.tags().get("rriloz")); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - BackupVaultPatch model = new BackupVaultPatch().withTags(mapOf("ynhdwdigum", "xhom")); + BackupVaultPatch model = new BackupVaultPatch().withTags(mapOf("rriloz", "vestmjl")); model = BinaryData.fromObject(model).toObject(BackupVaultPatch.class); - Assertions.assertEquals("xhom", model.tags().get("ynhdwdigum")); + Assertions.assertEquals("vestmjl", model.tags().get("rriloz")); } // Use "Map.of" if available diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupVaultPropertiesTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupVaultPropertiesTests.java index 18b3cfbd819e..10de68c5dad9 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupVaultPropertiesTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupVaultPropertiesTests.java @@ -10,8 +10,8 @@ public final class BackupVaultPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - BackupVaultProperties model = BinaryData.fromString("{\"provisioningState\":\"ykhyawfvjlboxqvk\"}") - .toObject(BackupVaultProperties.class); + BackupVaultProperties model + = BinaryData.fromString("{\"provisioningState\":\"qvldspastjbkkd\"}").toObject(BackupVaultProperties.class); } @org.junit.jupiter.api.Test diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupVaultsCreateOrUpdateMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupVaultsCreateOrUpdateMockTests.java index d9471b88a3ce..982d5b191656 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupVaultsCreateOrUpdateMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupVaultsCreateOrUpdateMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.BackupVault; @@ -23,25 +23,24 @@ public final class BackupVaultsCreateOrUpdateMockTests { @Test public void testCreateOrUpdate() throws Exception { String responseStr - = "{\"properties\":{\"provisioningState\":\"Succeeded\"},\"location\":\"atzuuv\",\"tags\":{\"ajqfutlx\":\"grebwggahttzlsw\",\"unwqr\":\"oqza\"},\"id\":\"zfrgqhaohcm\",\"name\":\"uocnjrohmbpyr\",\"type\":\"xameblydyvkfkm\"}"; + = "{\"properties\":{\"provisioningState\":\"Succeeded\"},\"location\":\"uihywart\",\"tags\":{\"emmucfxh\":\"hkixkykxdssj\",\"s\":\"kkflrmymyincqlhr\",\"iiiovgqcgxuugq\":\"sl\",\"e\":\"ctotiowlx\"},\"id\":\"dptjgwdtgukranb\",\"name\":\"wphqlkccuzgygqw\",\"type\":\"hoi\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); BackupVault response = manager.backupVaults() - .define("razisg") - .withRegion("nbwzohmnrxxbso") - .withExistingNetAppAccount("xcptsoqfyiaseqc", "krtt") - .withTags( - mapOf("rqsgnzx", "inhmdptys", "lsvjgpliu", "jp", "oucqpqojx", "iqwoyxqvapcoh", "rzdcgdzbenribcaw", "x")) + .define("blycsxzujksr") + .withRegion("bidyv") + .withExistingNetAppAccount("ywaeeczgf", "ukklelss") + .withTags(mapOf("paxwkufyk", "wxvgpiudeugfsxze")) .create(); - Assertions.assertEquals("atzuuv", response.location()); - Assertions.assertEquals("grebwggahttzlsw", response.tags().get("ajqfutlx")); + Assertions.assertEquals("uihywart", response.location()); + Assertions.assertEquals("hkixkykxdssj", response.tags().get("emmucfxh")); } // Use "Map.of" if available diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupVaultsGetWithResponseMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupVaultsGetWithResponseMockTests.java index 8e2706207938..e141e8da0f1c 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupVaultsGetWithResponseMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupVaultsGetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.BackupVault; @@ -21,20 +21,20 @@ public final class BackupVaultsGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"provisioningState\":\"rrczezkhhltnj\"},\"location\":\"hqo\",\"tags\":{\"rrueqthwmg\":\"qoyueayfbpcmsplb\",\"gdhxi\":\"mbscbbx\",\"opedbwdpyqyybxub\":\"d\",\"jelaqacigele\":\"dnafcbqwre\"},\"id\":\"hdbvqvwzkjop\",\"name\":\"beonrlkwzdq\",\"type\":\"bxcea\"}"; + = "{\"properties\":{\"provisioningState\":\"sqowxwc\"},\"location\":\"likytwvczcswka\",\"tags\":{\"b\":\"jyfdvlv\",\"th\":\"rnfxtgddp\",\"naoyank\":\"hn\",\"swankltytmh\":\"oe\"},\"id\":\"roznnhdrlktgj\",\"name\":\"sggux\",\"type\":\"eml\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); BackupVault response = manager.backupVaults() - .getWithResponse("wqagnepzwa", "lsbs", "qqqagwwrxaomzi", com.azure.core.util.Context.NONE) + .getWithResponse("o", "gkkumuikjcj", "aztb", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("hqo", response.location()); - Assertions.assertEquals("qoyueayfbpcmsplb", response.tags().get("rrueqthwmg")); + Assertions.assertEquals("likytwvczcswka", response.location()); + Assertions.assertEquals("jyfdvlv", response.tags().get("b")); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupVaultsListByNetAppAccountMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupVaultsListByNetAppAccountMockTests.java index d4815cee17c4..8cf0972edcbf 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupVaultsListByNetAppAccountMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupVaultsListByNetAppAccountMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.BackupVault; @@ -22,19 +22,19 @@ public final class BackupVaultsListByNetAppAccountMockTests { @Test public void testListByNetAppAccount() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"provisioningState\":\"zjijpvuaurkihcir\"},\"location\":\"efxrdcoxnbk\",\"tags\":{\"nqbpi\":\"nurnnq\",\"gypxrxvbfihwuhvc\":\"xqltgrd\"},\"id\":\"a\",\"name\":\"s\",\"type\":\"bxrblmliowxihspn\"}]}"; + = "{\"value\":[{\"properties\":{\"provisioningState\":\"jqo\"},\"location\":\"pihehce\",\"tags\":{\"kfrexcrseqwjks\":\"mrqbrjbbmpxdlv\",\"zhxogjggsvo\":\"hud\",\"hrkmdyomkxfbvfbh\":\"jkxibda\"},\"id\":\"y\",\"name\":\"rhpw\",\"type\":\"gddeimaw\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response - = manager.backupVaults().listByNetAppAccount("bkdq", "rdzsylollgtrczzy", com.azure.core.util.Context.NONE); + = manager.backupVaults().listByNetAppAccount("qejo", "ovyrrleaesinu", com.azure.core.util.Context.NONE); - Assertions.assertEquals("efxrdcoxnbk", response.iterator().next().location()); - Assertions.assertEquals("nurnnq", response.iterator().next().tags().get("nqbpi")); + Assertions.assertEquals("pihehce", response.iterator().next().location()); + Assertions.assertEquals("mrqbrjbbmpxdlv", response.iterator().next().tags().get("kfrexcrseqwjks")); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupVaultsListTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupVaultsListTests.java index 99ab205723f0..49fde8a366ba 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupVaultsListTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupVaultsListTests.java @@ -16,35 +16,23 @@ public final class BackupVaultsListTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { BackupVaultsList model = BinaryData.fromString( - "{\"value\":[{\"properties\":{\"provisioningState\":\"tjuewbcihx\"},\"location\":\"whcjyxcc\",\"tags\":{\"px\":\"payakkud\",\"stcyohpfkyrkdbd\":\"wjplma\",\"nobaiyhddviacegf\":\"iogsjkmnwq\"},\"id\":\"m\",\"name\":\"tfpmvmemfnczdw\",\"type\":\"vbalxlllc\"},{\"properties\":{\"provisioningState\":\"db\"},\"location\":\"vwrdnhfukuvsj\",\"tags\":{\"lerchpq\":\"smystuluqypfc\",\"dfc\":\"mfpjbabw\",\"qddrihpfhoqcaae\":\"sspuunnoxyhkx\",\"djvlpj\":\"dao\"},\"id\":\"xkzb\",\"name\":\"msgeivsiykzk\",\"type\":\"ncj\"},{\"properties\":{\"provisioningState\":\"nbzoggcu\"},\"location\":\"p\",\"tags\":{\"ylbf\":\"rpgogtqxep\"},\"id\":\"ajlyjtlvofqzhv\",\"name\":\"cib\",\"type\":\"fmo\"},{\"properties\":{\"provisioningState\":\"rkjpvdwxfzwii\"},\"location\":\"zjb\",\"tags\":{\"mbtrnegvmnvu\":\"sxjrk\",\"bkkd\":\"eqvldspast\",\"apeewchpxlkt\":\"flvestmjlxrrilo\",\"ufuztcktyhjtq\":\"kuziycsle\"},\"id\":\"dcgzul\",\"name\":\"mmrqz\",\"type\":\"rr\"}],\"nextLink\":\"pglydz\"}") + "{\"value\":[{\"properties\":{\"provisioningState\":\"viacegfnmntfpmv\"},\"location\":\"mfnczd\",\"tags\":{\"lxlllchpo\":\"b\",\"hfuk\":\"bzevwrd\",\"fcvlerch\":\"vsjcswsmystuluqy\"},\"id\":\"qbmfpjbabwidf\",\"name\":\"xsspuunnoxyhk\",\"type\":\"g\"}],\"nextLink\":\"drihpfhoqcaaewda\"}") .toObject(BackupVaultsList.class); - Assertions.assertEquals("whcjyxcc", model.value().get(0).location()); - Assertions.assertEquals("payakkud", model.value().get(0).tags().get("px")); - Assertions.assertEquals("pglydz", model.nextLink()); + Assertions.assertEquals("mfnczd", model.value().get(0).location()); + Assertions.assertEquals("b", model.value().get(0).tags().get("lxlllchpo")); + Assertions.assertEquals("drihpfhoqcaaewda", model.nextLink()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - BackupVaultsList model - = new BackupVaultsList() - .withValue( - Arrays - .asList( - new BackupVaultInner().withLocation("whcjyxcc") - .withTags(mapOf("px", "payakkud", "stcyohpfkyrkdbd", "wjplma", "nobaiyhddviacegf", - "iogsjkmnwq")), - new BackupVaultInner().withLocation("vwrdnhfukuvsj") - .withTags(mapOf("lerchpq", "smystuluqypfc", "dfc", "mfpjbabw", "qddrihpfhoqcaae", - "sspuunnoxyhkx", "djvlpj", "dao")), - new BackupVaultInner().withLocation("p").withTags(mapOf("ylbf", "rpgogtqxep")), - new BackupVaultInner().withLocation("zjb") - .withTags(mapOf("mbtrnegvmnvu", "sxjrk", "bkkd", "eqvldspast", "apeewchpxlkt", - "flvestmjlxrrilo", "ufuztcktyhjtq", "kuziycsle")))) - .withNextLink("pglydz"); + BackupVaultsList model = new BackupVaultsList() + .withValue(Arrays.asList(new BackupVaultInner().withLocation("mfnczd") + .withTags(mapOf("lxlllchpo", "b", "hfuk", "bzevwrd", "fcvlerch", "vsjcswsmystuluqy")))) + .withNextLink("drihpfhoqcaaewda"); model = BinaryData.fromObject(model).toObject(BackupVaultsList.class); - Assertions.assertEquals("whcjyxcc", model.value().get(0).location()); - Assertions.assertEquals("payakkud", model.value().get(0).tags().get("px")); - Assertions.assertEquals("pglydz", model.nextLink()); + Assertions.assertEquals("mfnczd", model.value().get(0).location()); + Assertions.assertEquals("b", model.value().get(0).tags().get("lxlllchpo")); + Assertions.assertEquals("drihpfhoqcaaewda", model.nextLink()); } // Use "Map.of" if available diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupsCreateMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupsCreateMockTests.java index ad85f817a84e..05d1aa150d54 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupsCreateMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupsCreateMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.Backup; @@ -21,27 +21,27 @@ public final class BackupsCreateMockTests { @Test public void testCreate() throws Exception { String responseStr - = "{\"properties\":{\"backupId\":\"l\",\"creationDate\":\"2021-07-10T12:24:24Z\",\"provisioningState\":\"Succeeded\",\"size\":2190540767152653017,\"label\":\"kympqanxrjkixtw\",\"backupType\":\"Manual\",\"failureReason\":\"ypnyghshxc\",\"volumeResourceId\":\"lhkgmnsghp\",\"useExistingSnapshot\":true,\"snapshotName\":\"hdrwjjkh\",\"backupPolicyResourceId\":\"omacluzvxnqmhr\",\"isLargeVolume\":false},\"id\":\"fwmkoisqcssffxui\",\"name\":\"mcs\",\"type\":\"p\"}"; + = "{\"properties\":{\"backupId\":\"fhjirwgdnqzbrfk\",\"creationDate\":\"2021-02-01T12:15:25Z\",\"provisioningState\":\"Succeeded\",\"size\":4152875994708456428,\"label\":\"xcdglj\",\"backupType\":\"Scheduled\",\"failureReason\":\"ua\",\"volumeResourceId\":\"htomflrytswfp\",\"useExistingSnapshot\":true,\"snapshotName\":\"ycxnmskw\",\"backupPolicyResourceId\":\"jjyslurlps\"},\"id\":\"kvp\",\"name\":\"dwqslsrhmpqvw\",\"type\":\"skondcbrwimu\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); Backup response = manager.backups() - .define("kdfrdbiqmrjgeihf") - .withExistingBackupVault("phavpmhbrb", "gvgovpbbttefjo", "nssqyzqed") - .withVolumeResourceId("augmrmfjlr") - .withLabel("gxhnpomyqwcabv") + .define("nmzlanru") + .withExistingBackupVault("agpgdph", "vdulajv", "ejchcsrlz") + .withVolumeResourceId("gydlhqv") + .withLabel("hlaiwd") .withUseExistingSnapshot(true) - .withSnapshotName("aukhfkvcisiz") + .withSnapshotName("xybafiqgea") .create(); - Assertions.assertEquals("kympqanxrjkixtw", response.label()); - Assertions.assertEquals("lhkgmnsghp", response.volumeResourceId()); + Assertions.assertEquals("xcdglj", response.label()); + Assertions.assertEquals("htomflrytswfp", response.volumeResourceId()); Assertions.assertEquals(true, response.useExistingSnapshot()); - Assertions.assertEquals("hdrwjjkh", response.snapshotName()); + Assertions.assertEquals("ycxnmskw", response.snapshotName()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupsGetLatestStatusWithResponseMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupsGetLatestStatusWithResponseMockTests.java index aa23c6d7a174..55379c4cb470 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupsGetLatestStatusWithResponseMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupsGetLatestStatusWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.BackupStatus; @@ -20,17 +20,17 @@ public final class BackupsGetLatestStatusWithResponseMockTests { @Test public void testGetLatestStatusWithResponse() throws Exception { String responseStr - = "{\"healthy\":false,\"relationshipStatus\":\"Unknown\",\"mirrorState\":\"Mirrored\",\"unhealthyReason\":\"mkxfbvfbhdyir\",\"errorMessage\":\"wpg\",\"lastTransferSize\":7111618905085369192,\"lastTransferType\":\"awzovgkk\",\"totalTransferBytes\":1860576085434847248,\"transferProgressBytes\":7795929404530107867}"; + = "{\"healthy\":false,\"relationshipStatus\":\"Unknown\",\"mirrorState\":\"Mirrored\",\"unhealthyReason\":\"r\",\"errorMessage\":\"uyzlw\",\"lastTransferSize\":5515716031108163936,\"lastTransferType\":\"hoocl\",\"totalTransferBytes\":839239832013822699,\"transferProgressBytes\":3448292460840142228}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); BackupStatus response = manager.backups() - .getLatestStatusWithResponse("crse", "wjksghudgzhxo", "jggsvo", "jkxibda", com.azure.core.util.Context.NONE) + .getLatestStatusWithResponse("pjrtws", "hv", "uic", "hvtrrmhwrbfdpyf", com.azure.core.util.Context.NONE) .getValue(); } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupsGetVolumeLatestRestoreStatusWithResponseMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupsGetVolumeLatestRestoreStatusWithResponseMockTests.java index 9d8bc1dd042f..9459dfdd9977 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupsGetVolumeLatestRestoreStatusWithResponseMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupsGetVolumeLatestRestoreStatusWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.RestoreStatus; @@ -20,17 +20,17 @@ public final class BackupsGetVolumeLatestRestoreStatusWithResponseMockTests { @Test public void testGetVolumeLatestRestoreStatusWithResponse() throws Exception { String responseStr - = "{\"healthy\":true,\"relationshipStatus\":\"Unknown\",\"mirrorState\":\"Broken\",\"unhealthyReason\":\"lvhbwrnf\",\"errorMessage\":\"gddpq\",\"totalTransferBytes\":5655380419005649480}"; + = "{\"healthy\":true,\"relationshipStatus\":\"Transferring\",\"mirrorState\":\"Broken\",\"unhealthyReason\":\"zj\",\"errorMessage\":\"refqy\",\"totalTransferBytes\":9207554581349131081}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); RestoreStatus response = manager.backups() - .getVolumeLatestRestoreStatusWithResponse("jcazt", "wsnsqowx", "comlikytwvczc", "wka", + .getVolumeLatestRestoreStatusWithResponse("mczjkm", "ykyujxsg", "hsrrryejylmbkz", "dnigrfihot", com.azure.core.util.Context.NONE) .getValue(); diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupsGetWithResponseMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupsGetWithResponseMockTests.java index 33e255377b44..5ef5b9be13e0 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupsGetWithResponseMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupsGetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.Backup; @@ -21,22 +21,22 @@ public final class BackupsGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"backupId\":\"kflrmymy\",\"creationDate\":\"2021-01-15T03:01:33Z\",\"provisioningState\":\"lhrisw\",\"size\":4374005645819181573,\"label\":\"iov\",\"backupType\":\"Scheduled\",\"failureReason\":\"xuugqkc\",\"volumeResourceId\":\"otiowlxteqd\",\"useExistingSnapshot\":true,\"snapshotName\":\"wdtgukranblw\",\"backupPolicyResourceId\":\"qlkccuzgygqwaho\",\"isLargeVolume\":true},\"id\":\"gniiprglvaw\",\"name\":\"wzdufypivlsbb\",\"type\":\"pmcubkmifoxxkub\"}"; + = "{\"properties\":{\"backupId\":\"vvtzejetjkl\",\"creationDate\":\"2021-03-04T18:59:07Z\",\"provisioningState\":\"yjuzkdb\",\"size\":700409671675457936,\"label\":\"rzvh\",\"backupType\":\"Manual\",\"failureReason\":\"rhtgvgzpcrrkol\",\"volumeResourceId\":\"w\",\"useExistingSnapshot\":false,\"snapshotName\":\"mwrokcdxfzzzwyja\",\"backupPolicyResourceId\":\"tlhguynuchl\"},\"id\":\"ltxdwhmozu\",\"name\":\"gzvlnsnn\",\"type\":\"zfpafolpymwamxqz\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); Backup response = manager.backups() - .getWithResponse("ihywartspph", "ixkykxd", "sj", "emmucfxh", com.azure.core.util.Context.NONE) + .getWithResponse("z", "iblkujr", "lfojuidjp", "uyjucejikzo", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("iov", response.label()); - Assertions.assertEquals("otiowlxteqd", response.volumeResourceId()); - Assertions.assertEquals(true, response.useExistingSnapshot()); - Assertions.assertEquals("wdtgukranblw", response.snapshotName()); + Assertions.assertEquals("rzvh", response.label()); + Assertions.assertEquals("w", response.volumeResourceId()); + Assertions.assertEquals(false, response.useExistingSnapshot()); + Assertions.assertEquals("mwrokcdxfzzzwyja", response.snapshotName()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupsListByVaultMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupsListByVaultMockTests.java index e30076a9396a..12a45476d52c 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupsListByVaultMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupsListByVaultMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.Backup; @@ -22,21 +22,21 @@ public final class BackupsListByVaultMockTests { @Test public void testListByVault() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"backupId\":\"oznnhdrlktgj\",\"creationDate\":\"2021-11-15T20:11:36Z\",\"provisioningState\":\"uxhemlwywaeeczg\",\"size\":8887879852420122717,\"label\":\"lelssxblycsxzujk\",\"backupType\":\"Scheduled\",\"failureReason\":\"mdesqp\",\"volumeResourceId\":\"pvmjcdoewbid\",\"useExistingSnapshot\":false,\"snapshotName\":\"owx\",\"backupPolicyResourceId\":\"piudeugfsxzecpa\",\"isLargeVolume\":false},\"id\":\"fykhvuhxepmru\",\"name\":\"znabaobns\",\"type\":\"ujdjltymkmvg\"}]}"; + = "{\"value\":[{\"properties\":{\"backupId\":\"qaxsipietgbebjf\",\"creationDate\":\"2021-08-07T23:47:59Z\",\"provisioningState\":\"oichdlpnfpubnt\",\"size\":6824297515299919028,\"label\":\"viqsowsaaelcattc\",\"backupType\":\"Scheduled\",\"failureReason\":\"lrvkmjc\",\"volumeResourceId\":\"mjvlgfgg\",\"useExistingSnapshot\":false,\"snapshotName\":\"y\",\"backupPolicyResourceId\":\"zrzbjpsfxs\"},\"id\":\"ztlvtmvagbwidqlv\",\"name\":\"ukoveofi\",\"type\":\"rvjfnmjmvlw\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response - = manager.backups().listByVault("n", "naoyank", "oe", "swankltytmh", com.azure.core.util.Context.NONE); + = manager.backups().listByVault("oihiqak", "diw", "brkwpzdqt", "hcspo", com.azure.core.util.Context.NONE); - Assertions.assertEquals("lelssxblycsxzujk", response.iterator().next().label()); - Assertions.assertEquals("pvmjcdoewbid", response.iterator().next().volumeResourceId()); + Assertions.assertEquals("viqsowsaaelcattc", response.iterator().next().label()); + Assertions.assertEquals("mjvlgfgg", response.iterator().next().volumeResourceId()); Assertions.assertEquals(false, response.iterator().next().useExistingSnapshot()); - Assertions.assertEquals("owx", response.iterator().next().snapshotName()); + Assertions.assertEquals("y", response.iterator().next().snapshotName()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupsListTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupsListTests.java index df30fc9f02bb..16bd267c553f 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupsListTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupsListTests.java @@ -14,36 +14,26 @@ public final class BackupsListTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { BackupsList model = BinaryData.fromString( - "{\"value\":[{\"properties\":{\"backupId\":\"jvewzcjznmwcp\",\"creationDate\":\"2021-03-18T03:28:02Z\",\"provisioningState\":\"adraufactkahzo\",\"size\":1201221594494672823,\"label\":\"iuxxpshneekulfg\",\"backupType\":\"Manual\",\"failureReason\":\"bkwdlenrds\",\"volumeResourceId\":\"tujbazpju\",\"useExistingSnapshot\":true,\"snapshotName\":\"nyfln\",\"backupPolicyResourceId\":\"wmd\",\"isLargeVolume\":false},\"id\":\"klvxwmyg\",\"name\":\"xpgpq\",\"type\":\"hiszepnnbjcrxgib\"},{\"properties\":{\"backupId\":\"axconfozauo\",\"creationDate\":\"2021-03-03T08:46:38Z\",\"provisioningState\":\"okwbqplh\",\"size\":928202540530969399,\"label\":\"epzl\",\"backupType\":\"Manual\",\"failureReason\":\"zsoldwey\",\"volumeResourceId\":\"qdunvmnnrwrbior\",\"useExistingSnapshot\":true,\"snapshotName\":\"ywjhhgdnhx\",\"backupPolicyResourceId\":\"ivfomiloxgg\",\"isLargeVolume\":false},\"id\":\"q\",\"name\":\"dieuzaofj\",\"type\":\"hvcyyysfg\"},{\"properties\":{\"backupId\":\"tcubiipuipwoqonm\",\"creationDate\":\"2021-06-06T06:49:44Z\",\"provisioningState\":\"k\",\"size\":4474116569169804323,\"label\":\"qvci\",\"backupType\":\"Manual\",\"failureReason\":\"fgmblrrilbywdxsm\",\"volumeResourceId\":\"ccwr\",\"useExistingSnapshot\":false,\"snapshotName\":\"jfnynszqujizdvoq\",\"backupPolicyResourceId\":\"ibyowbblgyavutp\",\"isLargeVolume\":false},\"id\":\"xoi\",\"name\":\"msksbp\",\"type\":\"mlqoljx\"}],\"nextLink\":\"gxxlxsffgcvizq\"}") + "{\"value\":[{\"properties\":{\"backupId\":\"dvoqyt\",\"creationDate\":\"2021-11-02T20:40:47Z\",\"provisioningState\":\"wb\",\"size\":5557233869903086465,\"label\":\"vutpthjoxo\",\"backupType\":\"Manual\",\"failureReason\":\"ksbpimlqoljx\",\"volumeResourceId\":\"cgxxlxs\",\"useExistingSnapshot\":true,\"snapshotName\":\"vizqzdwl\",\"backupPolicyResourceId\":\"lyoupfgfbkju\"},\"id\":\"yhgk\",\"name\":\"minsgowzf\",\"type\":\"tsttktlahbq\"}],\"nextLink\":\"tx\"}") .toObject(BackupsList.class); - Assertions.assertEquals("iuxxpshneekulfg", model.value().get(0).label()); - Assertions.assertEquals("tujbazpju", model.value().get(0).volumeResourceId()); + Assertions.assertEquals("vutpthjoxo", model.value().get(0).label()); + Assertions.assertEquals("cgxxlxs", model.value().get(0).volumeResourceId()); Assertions.assertEquals(true, model.value().get(0).useExistingSnapshot()); - Assertions.assertEquals("nyfln", model.value().get(0).snapshotName()); - Assertions.assertEquals("gxxlxsffgcvizq", model.nextLink()); + Assertions.assertEquals("vizqzdwl", model.value().get(0).snapshotName()); + Assertions.assertEquals("tx", model.nextLink()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - BackupsList model = new BackupsList().withValue(Arrays.asList( - new BackupInner().withLabel("iuxxpshneekulfg") - .withVolumeResourceId("tujbazpju") - .withUseExistingSnapshot(true) - .withSnapshotName("nyfln"), - new BackupInner().withLabel("epzl") - .withVolumeResourceId("qdunvmnnrwrbior") - .withUseExistingSnapshot(true) - .withSnapshotName("ywjhhgdnhx"), - new BackupInner().withLabel("qvci") - .withVolumeResourceId("ccwr") - .withUseExistingSnapshot(false) - .withSnapshotName("jfnynszqujizdvoq"))) - .withNextLink("gxxlxsffgcvizq"); + BackupsList model = new BackupsList().withValue(Arrays.asList(new BackupInner().withLabel("vutpthjoxo") + .withVolumeResourceId("cgxxlxs") + .withUseExistingSnapshot(true) + .withSnapshotName("vizqzdwl"))).withNextLink("tx"); model = BinaryData.fromObject(model).toObject(BackupsList.class); - Assertions.assertEquals("iuxxpshneekulfg", model.value().get(0).label()); - Assertions.assertEquals("tujbazpju", model.value().get(0).volumeResourceId()); + Assertions.assertEquals("vutpthjoxo", model.value().get(0).label()); + Assertions.assertEquals("cgxxlxs", model.value().get(0).volumeResourceId()); Assertions.assertEquals(true, model.value().get(0).useExistingSnapshot()); - Assertions.assertEquals("nyfln", model.value().get(0).snapshotName()); - Assertions.assertEquals("gxxlxsffgcvizq", model.nextLink()); + Assertions.assertEquals("vizqzdwl", model.value().get(0).snapshotName()); + Assertions.assertEquals("tx", model.nextLink()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupsMigrationRequestTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupsMigrationRequestTests.java index 67faa8c62153..b849b48490ec 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupsMigrationRequestTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BackupsMigrationRequestTests.java @@ -12,14 +12,14 @@ public final class BackupsMigrationRequestTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { BackupsMigrationRequest model - = BinaryData.fromString("{\"backupVaultId\":\"kphhq\"}").toObject(BackupsMigrationRequest.class); - Assertions.assertEquals("kphhq", model.backupVaultId()); + = BinaryData.fromString("{\"backupVaultId\":\"rqzz\"}").toObject(BackupsMigrationRequest.class); + Assertions.assertEquals("rqzz", model.backupVaultId()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - BackupsMigrationRequest model = new BackupsMigrationRequest().withBackupVaultId("kphhq"); + BackupsMigrationRequest model = new BackupsMigrationRequest().withBackupVaultId("rqzz"); model = BinaryData.fromObject(model).toObject(BackupsMigrationRequest.class); - Assertions.assertEquals("kphhq", model.backupVaultId()); + Assertions.assertEquals("rqzz", model.backupVaultId()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BreakFileLocksRequestTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BreakFileLocksRequestTests.java index c071ec61ce39..7f3dde7e9a43 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BreakFileLocksRequestTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BreakFileLocksRequestTests.java @@ -12,18 +12,18 @@ public final class BreakFileLocksRequestTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { BreakFileLocksRequest model - = BinaryData.fromString("{\"clientIp\":\"gsyocogj\",\"confirmRunningDisruptiveOperation\":false}") + = BinaryData.fromString("{\"clientIp\":\"fsynljphuop\",\"confirmRunningDisruptiveOperation\":true}") .toObject(BreakFileLocksRequest.class); - Assertions.assertEquals("gsyocogj", model.clientIp()); - Assertions.assertEquals(false, model.confirmRunningDisruptiveOperation()); + Assertions.assertEquals("fsynljphuop", model.clientIp()); + Assertions.assertEquals(true, model.confirmRunningDisruptiveOperation()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { BreakFileLocksRequest model - = new BreakFileLocksRequest().withClientIp("gsyocogj").withConfirmRunningDisruptiveOperation(false); + = new BreakFileLocksRequest().withClientIp("fsynljphuop").withConfirmRunningDisruptiveOperation(true); model = BinaryData.fromObject(model).toObject(BreakFileLocksRequest.class); - Assertions.assertEquals("gsyocogj", model.clientIp()); - Assertions.assertEquals(false, model.confirmRunningDisruptiveOperation()); + Assertions.assertEquals("fsynljphuop", model.clientIp()); + Assertions.assertEquals(true, model.confirmRunningDisruptiveOperation()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BreakReplicationRequestTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BreakReplicationRequestTests.java index cc82c1729a12..fee942f4e888 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BreakReplicationRequestTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/BreakReplicationRequestTests.java @@ -12,14 +12,14 @@ public final class BreakReplicationRequestTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { BreakReplicationRequest model - = BinaryData.fromString("{\"forceBreakReplication\":false}").toObject(BreakReplicationRequest.class); - Assertions.assertEquals(false, model.forceBreakReplication()); + = BinaryData.fromString("{\"forceBreakReplication\":true}").toObject(BreakReplicationRequest.class); + Assertions.assertEquals(true, model.forceBreakReplication()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - BreakReplicationRequest model = new BreakReplicationRequest().withForceBreakReplication(false); + BreakReplicationRequest model = new BreakReplicationRequest().withForceBreakReplication(true); model = BinaryData.fromObject(model).toObject(BreakReplicationRequest.class); - Assertions.assertEquals(false, model.forceBreakReplication()); + Assertions.assertEquals(true, model.forceBreakReplication()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/CapacityPoolInnerTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/CapacityPoolInnerTests.java index e4e10c9ad96a..1a0ea54bf4bb 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/CapacityPoolInnerTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/CapacityPoolInnerTests.java @@ -17,38 +17,34 @@ public final class CapacityPoolInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { CapacityPoolInner model = BinaryData.fromString( - "{\"etag\":\"wmdyvxqtay\",\"properties\":{\"poolId\":\"ww\",\"size\":3113078757672630652,\"serviceLevel\":\"Flexible\",\"provisioningState\":\"exrmcqibycnojvk\",\"totalThroughputMibps\":0.19367337,\"utilizedThroughputMibps\":58.457565,\"customThroughputMibps\":19.153065,\"qosType\":\"Auto\",\"coolAccess\":true,\"encryptionType\":\"Single\"},\"location\":\"y\",\"tags\":{\"zlmwlxkvugfhz\":\"vgqzcjrvxd\",\"hnnpr\":\"vawjvzunlu\",\"ultskzbbtdz\":\"xipeilpjzuaejx\",\"ekg\":\"mv\"},\"id\":\"wozuhkf\",\"name\":\"bsjyofdx\",\"type\":\"uusdttouwa\"}") + "{\"etag\":\"bexrmcq\",\"properties\":{\"poolId\":\"ycnojvknmefqsg\",\"size\":2641489064592308886,\"serviceLevel\":\"Ultra\",\"provisioningState\":\"pjyzhpv\",\"totalThroughputMibps\":87.25675,\"utilizedThroughputMibps\":3.2978177,\"qosType\":\"Manual\",\"coolAccess\":false,\"encryptionType\":\"Double\"},\"location\":\"mwlxk\",\"tags\":{\"n\":\"fhzovawjvzunluth\",\"pjzu\":\"rnxipei\",\"xdult\":\"e\",\"umveekgpwozuhkf\":\"kzbbtd\"},\"id\":\"bsjyofdx\",\"name\":\"uusdttouwa\",\"type\":\"oekqvk\"}") .toObject(CapacityPoolInner.class); - Assertions.assertEquals("y", model.location()); - Assertions.assertEquals("vgqzcjrvxd", model.tags().get("zlmwlxkvugfhz")); - Assertions.assertEquals(3113078757672630652L, model.size()); - Assertions.assertEquals(ServiceLevel.FLEXIBLE, model.serviceLevel()); - Assertions.assertEquals(19.153065F, model.customThroughputMibps()); - Assertions.assertEquals(QosType.AUTO, model.qosType()); - Assertions.assertEquals(true, model.coolAccess()); - Assertions.assertEquals(EncryptionType.SINGLE, model.encryptionType()); + Assertions.assertEquals("mwlxk", model.location()); + Assertions.assertEquals("fhzovawjvzunluth", model.tags().get("n")); + Assertions.assertEquals(2641489064592308886L, model.size()); + Assertions.assertEquals(ServiceLevel.ULTRA, model.serviceLevel()); + Assertions.assertEquals(QosType.MANUAL, model.qosType()); + Assertions.assertEquals(false, model.coolAccess()); + Assertions.assertEquals(EncryptionType.DOUBLE, model.encryptionType()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - CapacityPoolInner model = new CapacityPoolInner().withLocation("y") - .withTags(mapOf("zlmwlxkvugfhz", "vgqzcjrvxd", "hnnpr", "vawjvzunlu", "ultskzbbtdz", "xipeilpjzuaejx", - "ekg", "mv")) - .withSize(3113078757672630652L) - .withServiceLevel(ServiceLevel.FLEXIBLE) - .withCustomThroughputMibps(19.153065F) - .withQosType(QosType.AUTO) - .withCoolAccess(true) - .withEncryptionType(EncryptionType.SINGLE); + CapacityPoolInner model = new CapacityPoolInner().withLocation("mwlxk") + .withTags(mapOf("n", "fhzovawjvzunluth", "pjzu", "rnxipei", "xdult", "e", "umveekgpwozuhkf", "kzbbtd")) + .withSize(2641489064592308886L) + .withServiceLevel(ServiceLevel.ULTRA) + .withQosType(QosType.MANUAL) + .withCoolAccess(false) + .withEncryptionType(EncryptionType.DOUBLE); model = BinaryData.fromObject(model).toObject(CapacityPoolInner.class); - Assertions.assertEquals("y", model.location()); - Assertions.assertEquals("vgqzcjrvxd", model.tags().get("zlmwlxkvugfhz")); - Assertions.assertEquals(3113078757672630652L, model.size()); - Assertions.assertEquals(ServiceLevel.FLEXIBLE, model.serviceLevel()); - Assertions.assertEquals(19.153065F, model.customThroughputMibps()); - Assertions.assertEquals(QosType.AUTO, model.qosType()); - Assertions.assertEquals(true, model.coolAccess()); - Assertions.assertEquals(EncryptionType.SINGLE, model.encryptionType()); + Assertions.assertEquals("mwlxk", model.location()); + Assertions.assertEquals("fhzovawjvzunluth", model.tags().get("n")); + Assertions.assertEquals(2641489064592308886L, model.size()); + Assertions.assertEquals(ServiceLevel.ULTRA, model.serviceLevel()); + Assertions.assertEquals(QosType.MANUAL, model.qosType()); + Assertions.assertEquals(false, model.coolAccess()); + Assertions.assertEquals(EncryptionType.DOUBLE, model.encryptionType()); } // Use "Map.of" if available diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/CapacityPoolListTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/CapacityPoolListTests.java index 37ecb1c7fa53..d885041ec33a 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/CapacityPoolListTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/CapacityPoolListTests.java @@ -19,62 +19,52 @@ public final class CapacityPoolListTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { CapacityPoolList model = BinaryData.fromString( - "{\"value\":[{\"etag\":\"kfrlhrxsbky\",\"properties\":{\"poolId\":\"ycanuzbpzkafku\",\"size\":574839923891984639,\"serviceLevel\":\"Premium\",\"provisioningState\":\"wbme\",\"totalThroughputMibps\":27.898956,\"utilizedThroughputMibps\":69.774155,\"customThroughputMibps\":66.04007,\"qosType\":\"Manual\",\"coolAccess\":true,\"encryptionType\":\"Single\"},\"location\":\"spkdee\",\"tags\":{\"ag\":\"fm\",\"elmqk\":\"vt\",\"hcdhmdual\":\"hahvljuahaq\",\"vfadmws\":\"exq\"},\"id\":\"crgvxpvgom\",\"name\":\"lf\",\"type\":\"isgwbnbbeldawkz\"},{\"etag\":\"liourqhak\",\"properties\":{\"poolId\":\"hashsfwxosow\",\"size\":4305995232309135618,\"serviceLevel\":\"Flexible\",\"provisioningState\":\"i\",\"totalThroughputMibps\":63.03288,\"utilizedThroughputMibps\":19.326263,\"customThroughputMibps\":1.4710963,\"qosType\":\"Manual\",\"coolAccess\":true,\"encryptionType\":\"Double\"},\"location\":\"wfvovbv\",\"tags\":{\"ce\":\"ecivyh\",\"ytdxwit\":\"ojgjrwjueiotwmc\"},\"id\":\"nrjawgqwg\",\"name\":\"hniskxfbkpyc\",\"type\":\"klwndnhjdauwhv\"},{\"etag\":\"wzbtdhxu\",\"properties\":{\"poolId\":\"nbmpowuwprzq\",\"size\":5586335519469665747,\"serviceLevel\":\"Flexible\",\"provisioningState\":\"lupj\",\"totalThroughputMibps\":80.70111,\"utilizedThroughputMibps\":59.238964,\"customThroughputMibps\":67.89579,\"qosType\":\"Manual\",\"coolAccess\":true,\"encryptionType\":\"Double\"},\"location\":\"jriplrbpbewtghf\",\"tags\":{\"wxzvlvqhjkb\":\"c\",\"iebwwaloayqcgwrt\":\"gibtnm\",\"zg\":\"j\"},\"id\":\"yzm\",\"name\":\"txon\",\"type\":\"mtsavjcbpwxqp\"}],\"nextLink\":\"knftguvriuh\"}") + "{\"value\":[{\"etag\":\"bpzkafkuwbc\",\"properties\":{\"poolId\":\"wbme\",\"size\":7252038308965637311,\"serviceLevel\":\"StandardZRS\",\"provisioningState\":\"v\",\"totalThroughputMibps\":77.41172,\"utilizedThroughputMibps\":64.93837,\"qosType\":\"Auto\",\"coolAccess\":false,\"encryptionType\":\"Double\"},\"location\":\"eemaofmxagkvtme\",\"tags\":{\"hvljuahaquh\":\"krh\",\"aex\":\"dhmdua\",\"vxpvgomz\":\"pvfadmwsrcr\"},\"id\":\"fmisg\",\"name\":\"bnbbeldawkz\",\"type\":\"ali\"},{\"etag\":\"rqhakauha\",\"properties\":{\"poolId\":\"sfwxosowzxc\",\"size\":2516732809766062265,\"serviceLevel\":\"StandardZRS\",\"provisioningState\":\"ooxdjebwpuc\",\"totalThroughputMibps\":83.48158,\"utilizedThroughputMibps\":65.76169,\"qosType\":\"Manual\",\"coolAccess\":false,\"encryptionType\":\"Single\"},\"location\":\"civyhzceuo\",\"tags\":{\"ueiotwmcdyt\":\"rw\",\"it\":\"x\",\"hniskxfbkpyc\":\"nrjawgqwg\"},\"id\":\"klwndnhjdauwhv\",\"name\":\"l\",\"type\":\"zbtd\"},{\"etag\":\"ujznb\",\"properties\":{\"poolId\":\"ow\",\"size\":3222705953592047297,\"serviceLevel\":\"Premium\",\"provisioningState\":\"qlveualupjmkh\",\"totalThroughputMibps\":23.892725,\"utilizedThroughputMibps\":43.313354,\"qosType\":\"Auto\",\"coolAccess\":false,\"encryptionType\":\"Single\"},\"location\":\"riplrbpbewtg\",\"tags\":{\"xzvlvqhjkbegib\":\"blcg\",\"wrtz\":\"nmxiebwwaloayqc\",\"ngmtsavjcb\":\"uzgwyzmhtx\"},\"id\":\"wxqpsrknftguvri\",\"name\":\"hprwmdyv\",\"type\":\"qtayri\"}],\"nextLink\":\"ro\"}") .toObject(CapacityPoolList.class); - Assertions.assertEquals("spkdee", model.value().get(0).location()); - Assertions.assertEquals("fm", model.value().get(0).tags().get("ag")); - Assertions.assertEquals(574839923891984639L, model.value().get(0).size()); - Assertions.assertEquals(ServiceLevel.PREMIUM, model.value().get(0).serviceLevel()); - Assertions.assertEquals(66.04007F, model.value().get(0).customThroughputMibps()); - Assertions.assertEquals(QosType.MANUAL, model.value().get(0).qosType()); - Assertions.assertEquals(true, model.value().get(0).coolAccess()); - Assertions.assertEquals(EncryptionType.SINGLE, model.value().get(0).encryptionType()); - Assertions.assertEquals("knftguvriuh", model.nextLink()); + Assertions.assertEquals("eemaofmxagkvtme", model.value().get(0).location()); + Assertions.assertEquals("krh", model.value().get(0).tags().get("hvljuahaquh")); + Assertions.assertEquals(7252038308965637311L, model.value().get(0).size()); + Assertions.assertEquals(ServiceLevel.STANDARD_ZRS, model.value().get(0).serviceLevel()); + Assertions.assertEquals(QosType.AUTO, model.value().get(0).qosType()); + Assertions.assertEquals(false, model.value().get(0).coolAccess()); + Assertions.assertEquals(EncryptionType.DOUBLE, model.value().get(0).encryptionType()); + Assertions.assertEquals("ro", model.nextLink()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - CapacityPoolList model - = new CapacityPoolList() - .withValue( - Arrays - .asList( - new CapacityPoolInner().withLocation("spkdee") - .withTags( - mapOf("ag", "fm", "elmqk", "vt", "hcdhmdual", "hahvljuahaq", "vfadmws", "exq")) - .withSize(574839923891984639L) - .withServiceLevel(ServiceLevel.PREMIUM) - .withCustomThroughputMibps(66.04007F) - .withQosType(QosType.MANUAL) - .withCoolAccess(true) - .withEncryptionType(EncryptionType.SINGLE), - new CapacityPoolInner().withLocation("wfvovbv") - .withTags(mapOf("ce", "ecivyh", "ytdxwit", "ojgjrwjueiotwmc")) - .withSize(4305995232309135618L) - .withServiceLevel(ServiceLevel.FLEXIBLE) - .withCustomThroughputMibps(1.4710963F) - .withQosType(QosType.MANUAL) - .withCoolAccess(true) - .withEncryptionType(EncryptionType.DOUBLE), - new CapacityPoolInner().withLocation("jriplrbpbewtghf") - .withTags(mapOf("wxzvlvqhjkb", "c", "iebwwaloayqcgwrt", "gibtnm", "zg", "j")) - .withSize(5586335519469665747L) - .withServiceLevel(ServiceLevel.FLEXIBLE) - .withCustomThroughputMibps(67.89579F) - .withQosType(QosType.MANUAL) - .withCoolAccess(true) - .withEncryptionType(EncryptionType.DOUBLE))) - .withNextLink("knftguvriuh"); + CapacityPoolList model = new CapacityPoolList().withValue(Arrays.asList( + new CapacityPoolInner().withLocation("eemaofmxagkvtme") + .withTags(mapOf("hvljuahaquh", "krh", "aex", "dhmdua", "vxpvgomz", "pvfadmwsrcr")) + .withSize(7252038308965637311L) + .withServiceLevel(ServiceLevel.STANDARD_ZRS) + .withQosType(QosType.AUTO) + .withCoolAccess(false) + .withEncryptionType(EncryptionType.DOUBLE), + new CapacityPoolInner().withLocation("civyhzceuo") + .withTags(mapOf("ueiotwmcdyt", "rw", "it", "x", "hniskxfbkpyc", "nrjawgqwg")) + .withSize(2516732809766062265L) + .withServiceLevel(ServiceLevel.STANDARD_ZRS) + .withQosType(QosType.MANUAL) + .withCoolAccess(false) + .withEncryptionType(EncryptionType.SINGLE), + new CapacityPoolInner().withLocation("riplrbpbewtg") + .withTags(mapOf("xzvlvqhjkbegib", "blcg", "wrtz", "nmxiebwwaloayqc", "ngmtsavjcb", "uzgwyzmhtx")) + .withSize(3222705953592047297L) + .withServiceLevel(ServiceLevel.PREMIUM) + .withQosType(QosType.AUTO) + .withCoolAccess(false) + .withEncryptionType(EncryptionType.SINGLE))) + .withNextLink("ro"); model = BinaryData.fromObject(model).toObject(CapacityPoolList.class); - Assertions.assertEquals("spkdee", model.value().get(0).location()); - Assertions.assertEquals("fm", model.value().get(0).tags().get("ag")); - Assertions.assertEquals(574839923891984639L, model.value().get(0).size()); - Assertions.assertEquals(ServiceLevel.PREMIUM, model.value().get(0).serviceLevel()); - Assertions.assertEquals(66.04007F, model.value().get(0).customThroughputMibps()); - Assertions.assertEquals(QosType.MANUAL, model.value().get(0).qosType()); - Assertions.assertEquals(true, model.value().get(0).coolAccess()); - Assertions.assertEquals(EncryptionType.SINGLE, model.value().get(0).encryptionType()); - Assertions.assertEquals("knftguvriuh", model.nextLink()); + Assertions.assertEquals("eemaofmxagkvtme", model.value().get(0).location()); + Assertions.assertEquals("krh", model.value().get(0).tags().get("hvljuahaquh")); + Assertions.assertEquals(7252038308965637311L, model.value().get(0).size()); + Assertions.assertEquals(ServiceLevel.STANDARD_ZRS, model.value().get(0).serviceLevel()); + Assertions.assertEquals(QosType.AUTO, model.value().get(0).qosType()); + Assertions.assertEquals(false, model.value().get(0).coolAccess()); + Assertions.assertEquals(EncryptionType.DOUBLE, model.value().get(0).encryptionType()); + Assertions.assertEquals("ro", model.nextLink()); } // Use "Map.of" if available diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/CapacityPoolPatchTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/CapacityPoolPatchTests.java index 29dcfe51324f..687cfba493e1 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/CapacityPoolPatchTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/CapacityPoolPatchTests.java @@ -15,31 +15,28 @@ public final class CapacityPoolPatchTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { CapacityPoolPatch model = BinaryData.fromString( - "{\"properties\":{\"size\":9075398800966169751,\"qosType\":\"Manual\",\"coolAccess\":true,\"customThroughputMibps\":22.889233},\"location\":\"exznelixhnr\",\"tags\":{\"hb\":\"o\",\"dtpnapnyiropuhp\":\"xknalaulppg\",\"gqgitxmedjvcsl\":\"gvpgy\"},\"id\":\"n\",\"name\":\"wwncwzzhxgk\",\"type\":\"rmgucnap\"}") + "{\"properties\":{\"size\":7703908538660559056,\"qosType\":\"Auto\",\"coolAccess\":true},\"location\":\"znelixhnrztfolh\",\"tags\":{\"dtpnapnyiropuhp\":\"knalaulppg\",\"gqgitxmedjvcsl\":\"gvpgy\",\"wwncwzzhxgk\":\"n\"},\"id\":\"rmgucnap\",\"name\":\"t\",\"type\":\"oellwp\"}") .toObject(CapacityPoolPatch.class); - Assertions.assertEquals("exznelixhnr", model.location()); - Assertions.assertEquals("o", model.tags().get("hb")); - Assertions.assertEquals(9075398800966169751L, model.size()); - Assertions.assertEquals(QosType.MANUAL, model.qosType()); + Assertions.assertEquals("znelixhnrztfolh", model.location()); + Assertions.assertEquals("knalaulppg", model.tags().get("dtpnapnyiropuhp")); + Assertions.assertEquals(7703908538660559056L, model.size()); + Assertions.assertEquals(QosType.AUTO, model.qosType()); Assertions.assertEquals(true, model.coolAccess()); - Assertions.assertEquals(22.889233F, model.customThroughputMibps()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - CapacityPoolPatch model = new CapacityPoolPatch().withLocation("exznelixhnr") - .withTags(mapOf("hb", "o", "dtpnapnyiropuhp", "xknalaulppg", "gqgitxmedjvcsl", "gvpgy")) - .withSize(9075398800966169751L) - .withQosType(QosType.MANUAL) - .withCoolAccess(true) - .withCustomThroughputMibps(22.889233F); + CapacityPoolPatch model = new CapacityPoolPatch().withLocation("znelixhnrztfolh") + .withTags(mapOf("dtpnapnyiropuhp", "knalaulppg", "gqgitxmedjvcsl", "gvpgy", "wwncwzzhxgk", "n")) + .withSize(7703908538660559056L) + .withQosType(QosType.AUTO) + .withCoolAccess(true); model = BinaryData.fromObject(model).toObject(CapacityPoolPatch.class); - Assertions.assertEquals("exznelixhnr", model.location()); - Assertions.assertEquals("o", model.tags().get("hb")); - Assertions.assertEquals(9075398800966169751L, model.size()); - Assertions.assertEquals(QosType.MANUAL, model.qosType()); + Assertions.assertEquals("znelixhnrztfolh", model.location()); + Assertions.assertEquals("knalaulppg", model.tags().get("dtpnapnyiropuhp")); + Assertions.assertEquals(7703908538660559056L, model.size()); + Assertions.assertEquals(QosType.AUTO, model.qosType()); Assertions.assertEquals(true, model.coolAccess()); - Assertions.assertEquals(22.889233F, model.customThroughputMibps()); } // Use "Map.of" if available diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ClusterPeerCommandResponseInnerTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ClusterPeerCommandResponseInnerTests.java index aa131fedab78..05aef84dd7d1 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ClusterPeerCommandResponseInnerTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ClusterPeerCommandResponseInnerTests.java @@ -11,15 +11,16 @@ public final class ClusterPeerCommandResponseInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - ClusterPeerCommandResponseInner model = BinaryData.fromString("{\"peerAcceptCommand\":\"dmjsjqb\"}") + ClusterPeerCommandResponseInner model = BinaryData.fromString("{\"peerAcceptCommand\":\"ukghimdblxgw\"}") .toObject(ClusterPeerCommandResponseInner.class); - Assertions.assertEquals("dmjsjqb", model.peerAcceptCommand()); + Assertions.assertEquals("ukghimdblxgw", model.peerAcceptCommand()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - ClusterPeerCommandResponseInner model = new ClusterPeerCommandResponseInner().withPeerAcceptCommand("dmjsjqb"); + ClusterPeerCommandResponseInner model + = new ClusterPeerCommandResponseInner().withPeerAcceptCommand("ukghimdblxgw"); model = BinaryData.fromObject(model).toObject(ClusterPeerCommandResponseInner.class); - Assertions.assertEquals("dmjsjqb", model.peerAcceptCommand()); + Assertions.assertEquals("ukghimdblxgw", model.peerAcceptCommand()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/DailyScheduleTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/DailyScheduleTests.java index 9ab2b3c142c1..61cfd89180cf 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/DailyScheduleTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/DailyScheduleTests.java @@ -12,24 +12,24 @@ public final class DailyScheduleTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { DailySchedule model = BinaryData.fromString( - "{\"snapshotsToKeep\":69904268,\"hour\":1823569828,\"minute\":357082526,\"usedBytes\":8541287149443830864}") + "{\"snapshotsToKeep\":631648587,\"hour\":2100538893,\"minute\":648975494,\"usedBytes\":1997277075464106267}") .toObject(DailySchedule.class); - Assertions.assertEquals(69904268, model.snapshotsToKeep()); - Assertions.assertEquals(1823569828, model.hour()); - Assertions.assertEquals(357082526, model.minute()); - Assertions.assertEquals(8541287149443830864L, model.usedBytes()); + Assertions.assertEquals(631648587, model.snapshotsToKeep()); + Assertions.assertEquals(2100538893, model.hour()); + Assertions.assertEquals(648975494, model.minute()); + Assertions.assertEquals(1997277075464106267L, model.usedBytes()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - DailySchedule model = new DailySchedule().withSnapshotsToKeep(69904268) - .withHour(1823569828) - .withMinute(357082526) - .withUsedBytes(8541287149443830864L); + DailySchedule model = new DailySchedule().withSnapshotsToKeep(631648587) + .withHour(2100538893) + .withMinute(648975494) + .withUsedBytes(1997277075464106267L); model = BinaryData.fromObject(model).toObject(DailySchedule.class); - Assertions.assertEquals(69904268, model.snapshotsToKeep()); - Assertions.assertEquals(1823569828, model.hour()); - Assertions.assertEquals(357082526, model.minute()); - Assertions.assertEquals(8541287149443830864L, model.usedBytes()); + Assertions.assertEquals(631648587, model.snapshotsToKeep()); + Assertions.assertEquals(2100538893, model.hour()); + Assertions.assertEquals(648975494, model.minute()); + Assertions.assertEquals(1997277075464106267L, model.usedBytes()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/DestinationReplicationTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/DestinationReplicationTests.java deleted file mode 100644 index 62e6836baa89..000000000000 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/DestinationReplicationTests.java +++ /dev/null @@ -1,36 +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.resourcemanager.netapp.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.netapp.models.DestinationReplication; -import com.azure.resourcemanager.netapp.models.ReplicationType; -import org.junit.jupiter.api.Assertions; - -public final class DestinationReplicationTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - DestinationReplication model = BinaryData.fromString( - "{\"resourceId\":\"ggbhcohfwds\",\"replicationType\":\"CrossRegionReplication\",\"region\":\"ljuti\",\"zone\":\"wacf\"}") - .toObject(DestinationReplication.class); - Assertions.assertEquals("ggbhcohfwds", model.resourceId()); - Assertions.assertEquals(ReplicationType.CROSS_REGION_REPLICATION, model.replicationType()); - Assertions.assertEquals("ljuti", model.region()); - Assertions.assertEquals("wacf", model.zone()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - DestinationReplication model = new DestinationReplication().withResourceId("ggbhcohfwds") - .withReplicationType(ReplicationType.CROSS_REGION_REPLICATION) - .withRegion("ljuti") - .withZone("wacf"); - model = BinaryData.fromObject(model).toObject(DestinationReplication.class); - Assertions.assertEquals("ggbhcohfwds", model.resourceId()); - Assertions.assertEquals(ReplicationType.CROSS_REGION_REPLICATION, model.replicationType()); - Assertions.assertEquals("ljuti", model.region()); - Assertions.assertEquals("wacf", model.zone()); - } -} diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/EncryptionIdentityTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/EncryptionIdentityTests.java index 1715678ca12d..96a6ec56bdff 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/EncryptionIdentityTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/EncryptionIdentityTests.java @@ -11,19 +11,16 @@ public final class EncryptionIdentityTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - EncryptionIdentity model = BinaryData.fromString( - "{\"principalId\":\"ogtwrupqsxvnmi\",\"userAssignedIdentity\":\"kvceoveilovnotyf\",\"federatedClientId\":\"cnjbkcnxdhbt\"}") + EncryptionIdentity model = BinaryData + .fromString("{\"principalId\":\"ogtwrupqsxvnmi\",\"userAssignedIdentity\":\"kvceoveilovnotyf\"}") .toObject(EncryptionIdentity.class); Assertions.assertEquals("kvceoveilovnotyf", model.userAssignedIdentity()); - Assertions.assertEquals("cnjbkcnxdhbt", model.federatedClientId()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - EncryptionIdentity model = new EncryptionIdentity().withUserAssignedIdentity("kvceoveilovnotyf") - .withFederatedClientId("cnjbkcnxdhbt"); + EncryptionIdentity model = new EncryptionIdentity().withUserAssignedIdentity("kvceoveilovnotyf"); model = BinaryData.fromObject(model).toObject(EncryptionIdentity.class); Assertions.assertEquals("kvceoveilovnotyf", model.userAssignedIdentity()); - Assertions.assertEquals("cnjbkcnxdhbt", model.federatedClientId()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/EncryptionTransitionRequestTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/EncryptionTransitionRequestTests.java index 1cf2d5c745b1..b5728acf178b 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/EncryptionTransitionRequestTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/EncryptionTransitionRequestTests.java @@ -11,19 +11,19 @@ public final class EncryptionTransitionRequestTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - EncryptionTransitionRequest model - = BinaryData.fromString("{\"virtualNetworkId\":\"yonobgl\",\"privateEndpointId\":\"ocqxtccmg\"}") - .toObject(EncryptionTransitionRequest.class); - Assertions.assertEquals("yonobgl", model.virtualNetworkId()); - Assertions.assertEquals("ocqxtccmg", model.privateEndpointId()); + EncryptionTransitionRequest model = BinaryData + .fromString("{\"virtualNetworkId\":\"qugxywpmueefjzwf\",\"privateEndpointId\":\"kqujidsuyono\"}") + .toObject(EncryptionTransitionRequest.class); + Assertions.assertEquals("qugxywpmueefjzwf", model.virtualNetworkId()); + Assertions.assertEquals("kqujidsuyono", model.privateEndpointId()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - EncryptionTransitionRequest model - = new EncryptionTransitionRequest().withVirtualNetworkId("yonobgl").withPrivateEndpointId("ocqxtccmg"); + EncryptionTransitionRequest model = new EncryptionTransitionRequest().withVirtualNetworkId("qugxywpmueefjzwf") + .withPrivateEndpointId("kqujidsuyono"); model = BinaryData.fromObject(model).toObject(EncryptionTransitionRequest.class); - Assertions.assertEquals("yonobgl", model.virtualNetworkId()); - Assertions.assertEquals("ocqxtccmg", model.privateEndpointId()); + Assertions.assertEquals("qugxywpmueefjzwf", model.virtualNetworkId()); + Assertions.assertEquals("kqujidsuyono", model.privateEndpointId()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ExportPolicyRuleTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ExportPolicyRuleTests.java index 58ea3691e4ee..1b6c1ff0a8c5 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ExportPolicyRuleTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ExportPolicyRuleTests.java @@ -13,57 +13,57 @@ public final class ExportPolicyRuleTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ExportPolicyRule model = BinaryData.fromString( - "{\"ruleIndex\":1235013026,\"unixReadOnly\":false,\"unixReadWrite\":false,\"kerberos5ReadOnly\":true,\"kerberos5ReadWrite\":true,\"kerberos5iReadOnly\":false,\"kerberos5iReadWrite\":false,\"kerberos5pReadOnly\":false,\"kerberos5pReadWrite\":true,\"cifs\":true,\"nfsv3\":true,\"nfsv41\":true,\"allowedClients\":\"mkcjhwqytjrybn\",\"hasRootAccess\":true,\"chownMode\":\"Unrestricted\"}") + "{\"ruleIndex\":151199466,\"unixReadOnly\":true,\"unixReadWrite\":true,\"kerberos5ReadOnly\":true,\"kerberos5ReadWrite\":true,\"kerberos5iReadOnly\":true,\"kerberos5iReadWrite\":true,\"kerberos5pReadOnly\":false,\"kerberos5pReadWrite\":false,\"cifs\":false,\"nfsv3\":true,\"nfsv41\":false,\"allowedClients\":\"ygmi\",\"hasRootAccess\":true,\"chownMode\":\"Restricted\"}") .toObject(ExportPolicyRule.class); - Assertions.assertEquals(1235013026, model.ruleIndex()); - Assertions.assertEquals(false, model.unixReadOnly()); - Assertions.assertEquals(false, model.unixReadWrite()); + Assertions.assertEquals(151199466, model.ruleIndex()); + Assertions.assertEquals(true, model.unixReadOnly()); + Assertions.assertEquals(true, model.unixReadWrite()); Assertions.assertEquals(true, model.kerberos5ReadOnly()); Assertions.assertEquals(true, model.kerberos5ReadWrite()); - Assertions.assertEquals(false, model.kerberos5IReadOnly()); - Assertions.assertEquals(false, model.kerberos5IReadWrite()); + Assertions.assertEquals(true, model.kerberos5IReadOnly()); + Assertions.assertEquals(true, model.kerberos5IReadWrite()); Assertions.assertEquals(false, model.kerberos5PReadOnly()); - Assertions.assertEquals(true, model.kerberos5PReadWrite()); - Assertions.assertEquals(true, model.cifs()); + Assertions.assertEquals(false, model.kerberos5PReadWrite()); + Assertions.assertEquals(false, model.cifs()); Assertions.assertEquals(true, model.nfsv3()); - Assertions.assertEquals(true, model.nfsv41()); - Assertions.assertEquals("mkcjhwqytjrybn", model.allowedClients()); + Assertions.assertEquals(false, model.nfsv41()); + Assertions.assertEquals("ygmi", model.allowedClients()); Assertions.assertEquals(true, model.hasRootAccess()); - Assertions.assertEquals(ChownMode.UNRESTRICTED, model.chownMode()); + Assertions.assertEquals(ChownMode.RESTRICTED, model.chownMode()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - ExportPolicyRule model = new ExportPolicyRule().withRuleIndex(1235013026) - .withUnixReadOnly(false) - .withUnixReadWrite(false) + ExportPolicyRule model = new ExportPolicyRule().withRuleIndex(151199466) + .withUnixReadOnly(true) + .withUnixReadWrite(true) .withKerberos5ReadOnly(true) .withKerberos5ReadWrite(true) - .withKerberos5IReadOnly(false) - .withKerberos5IReadWrite(false) + .withKerberos5IReadOnly(true) + .withKerberos5IReadWrite(true) .withKerberos5PReadOnly(false) - .withKerberos5PReadWrite(true) - .withCifs(true) + .withKerberos5PReadWrite(false) + .withCifs(false) .withNfsv3(true) - .withNfsv41(true) - .withAllowedClients("mkcjhwqytjrybn") + .withNfsv41(false) + .withAllowedClients("ygmi") .withHasRootAccess(true) - .withChownMode(ChownMode.UNRESTRICTED); + .withChownMode(ChownMode.RESTRICTED); model = BinaryData.fromObject(model).toObject(ExportPolicyRule.class); - Assertions.assertEquals(1235013026, model.ruleIndex()); - Assertions.assertEquals(false, model.unixReadOnly()); - Assertions.assertEquals(false, model.unixReadWrite()); + Assertions.assertEquals(151199466, model.ruleIndex()); + Assertions.assertEquals(true, model.unixReadOnly()); + Assertions.assertEquals(true, model.unixReadWrite()); Assertions.assertEquals(true, model.kerberos5ReadOnly()); Assertions.assertEquals(true, model.kerberos5ReadWrite()); - Assertions.assertEquals(false, model.kerberos5IReadOnly()); - Assertions.assertEquals(false, model.kerberos5IReadWrite()); + Assertions.assertEquals(true, model.kerberos5IReadOnly()); + Assertions.assertEquals(true, model.kerberos5IReadWrite()); Assertions.assertEquals(false, model.kerberos5PReadOnly()); - Assertions.assertEquals(true, model.kerberos5PReadWrite()); - Assertions.assertEquals(true, model.cifs()); + Assertions.assertEquals(false, model.kerberos5PReadWrite()); + Assertions.assertEquals(false, model.cifs()); Assertions.assertEquals(true, model.nfsv3()); - Assertions.assertEquals(true, model.nfsv41()); - Assertions.assertEquals("mkcjhwqytjrybn", model.allowedClients()); + Assertions.assertEquals(false, model.nfsv41()); + Assertions.assertEquals("ygmi", model.allowedClients()); Assertions.assertEquals(true, model.hasRootAccess()); - Assertions.assertEquals(ChownMode.UNRESTRICTED, model.chownMode()); + Assertions.assertEquals(ChownMode.RESTRICTED, model.chownMode()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/GetGroupIdListForLdapUserRequestTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/GetGroupIdListForLdapUserRequestTests.java index 08f7c92a604c..79dde852b57d 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/GetGroupIdListForLdapUserRequestTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/GetGroupIdListForLdapUserRequestTests.java @@ -12,14 +12,14 @@ public final class GetGroupIdListForLdapUserRequestTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { GetGroupIdListForLdapUserRequest model - = BinaryData.fromString("{\"username\":\"tbnnha\"}").toObject(GetGroupIdListForLdapUserRequest.class); - Assertions.assertEquals("tbnnha", model.username()); + = BinaryData.fromString("{\"username\":\"lqiyntorzihl\"}").toObject(GetGroupIdListForLdapUserRequest.class); + Assertions.assertEquals("lqiyntorzihl", model.username()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - GetGroupIdListForLdapUserRequest model = new GetGroupIdListForLdapUserRequest().withUsername("tbnnha"); + GetGroupIdListForLdapUserRequest model = new GetGroupIdListForLdapUserRequest().withUsername("lqiyntorzihl"); model = BinaryData.fromObject(model).toObject(GetGroupIdListForLdapUserRequest.class); - Assertions.assertEquals("tbnnha", model.username()); + Assertions.assertEquals("lqiyntorzihl", model.username()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/GetGroupIdListForLdapUserResponseInnerTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/GetGroupIdListForLdapUserResponseInnerTests.java index c8d306913df8..33e69fea432f 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/GetGroupIdListForLdapUserResponseInnerTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/GetGroupIdListForLdapUserResponseInnerTests.java @@ -13,16 +13,16 @@ public final class GetGroupIdListForLdapUserResponseInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { GetGroupIdListForLdapUserResponseInner model - = BinaryData.fromString("{\"groupIdsForLdapUser\":[\"crkvcikhnv\",\"amqgxqquezikyw\",\"gxk\"]}") + = BinaryData.fromString("{\"groupIdsForLdapUser\":[\"jswsrmslyz\",\"pzbchck\"]}") .toObject(GetGroupIdListForLdapUserResponseInner.class); - Assertions.assertEquals("crkvcikhnv", model.groupIdsForLdapUser().get(0)); + Assertions.assertEquals("jswsrmslyz", model.groupIdsForLdapUser().get(0)); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { GetGroupIdListForLdapUserResponseInner model = new GetGroupIdListForLdapUserResponseInner() - .withGroupIdsForLdapUser(Arrays.asList("crkvcikhnv", "amqgxqquezikyw", "gxk")); + .withGroupIdsForLdapUser(Arrays.asList("jswsrmslyz", "pzbchck")); model = BinaryData.fromObject(model).toObject(GetGroupIdListForLdapUserResponseInner.class); - Assertions.assertEquals("crkvcikhnv", model.groupIdsForLdapUser().get(0)); + Assertions.assertEquals("jswsrmslyz", model.groupIdsForLdapUser().get(0)); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/HourlyScheduleTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/HourlyScheduleTests.java index c97257cfa363..a7c51e2d251c 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/HourlyScheduleTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/HourlyScheduleTests.java @@ -12,21 +12,21 @@ public final class HourlyScheduleTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { HourlySchedule model = BinaryData - .fromString("{\"snapshotsToKeep\":1422593899,\"minute\":1663606623,\"usedBytes\":6545007324610605379}") + .fromString("{\"snapshotsToKeep\":1161774579,\"minute\":83276112,\"usedBytes\":9085826358534396336}") .toObject(HourlySchedule.class); - Assertions.assertEquals(1422593899, model.snapshotsToKeep()); - Assertions.assertEquals(1663606623, model.minute()); - Assertions.assertEquals(6545007324610605379L, model.usedBytes()); + Assertions.assertEquals(1161774579, model.snapshotsToKeep()); + Assertions.assertEquals(83276112, model.minute()); + Assertions.assertEquals(9085826358534396336L, model.usedBytes()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - HourlySchedule model = new HourlySchedule().withSnapshotsToKeep(1422593899) - .withMinute(1663606623) - .withUsedBytes(6545007324610605379L); + HourlySchedule model = new HourlySchedule().withSnapshotsToKeep(1161774579) + .withMinute(83276112) + .withUsedBytes(9085826358534396336L); model = BinaryData.fromObject(model).toObject(HourlySchedule.class); - Assertions.assertEquals(1422593899, model.snapshotsToKeep()); - Assertions.assertEquals(1663606623, model.minute()); - Assertions.assertEquals(6545007324610605379L, model.usedBytes()); + Assertions.assertEquals(1161774579, model.snapshotsToKeep()); + Assertions.assertEquals(83276112, model.minute()); + Assertions.assertEquals(9085826358534396336L, model.usedBytes()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/KeyVaultPrivateEndpointTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/KeyVaultPrivateEndpointTests.java index ad1c4e300b98..c73df44f1326 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/KeyVaultPrivateEndpointTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/KeyVaultPrivateEndpointTests.java @@ -12,18 +12,18 @@ public final class KeyVaultPrivateEndpointTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { KeyVaultPrivateEndpoint model - = BinaryData.fromString("{\"virtualNetworkId\":\"fudwpznt\",\"privateEndpointId\":\"dzhlrq\"}") + = BinaryData.fromString("{\"virtualNetworkId\":\"moyrxvwfudwpz\",\"privateEndpointId\":\"xhdzhlrqjbhckf\"}") .toObject(KeyVaultPrivateEndpoint.class); - Assertions.assertEquals("fudwpznt", model.virtualNetworkId()); - Assertions.assertEquals("dzhlrq", model.privateEndpointId()); + Assertions.assertEquals("moyrxvwfudwpz", model.virtualNetworkId()); + Assertions.assertEquals("xhdzhlrqjbhckf", model.privateEndpointId()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - KeyVaultPrivateEndpoint model - = new KeyVaultPrivateEndpoint().withVirtualNetworkId("fudwpznt").withPrivateEndpointId("dzhlrq"); + KeyVaultPrivateEndpoint model = new KeyVaultPrivateEndpoint().withVirtualNetworkId("moyrxvwfudwpz") + .withPrivateEndpointId("xhdzhlrqjbhckf"); model = BinaryData.fromObject(model).toObject(KeyVaultPrivateEndpoint.class); - Assertions.assertEquals("fudwpznt", model.virtualNetworkId()); - Assertions.assertEquals("dzhlrq", model.privateEndpointId()); + Assertions.assertEquals("moyrxvwfudwpz", model.virtualNetworkId()); + Assertions.assertEquals("xhdzhlrqjbhckf", model.privateEndpointId()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ListQuotaReportResponseInnerTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ListQuotaReportResponseInnerTests.java deleted file mode 100644 index b33bc54d688b..000000000000 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ListQuotaReportResponseInnerTests.java +++ /dev/null @@ -1,48 +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.resourcemanager.netapp.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.netapp.fluent.models.ListQuotaReportResponseInner; -import com.azure.resourcemanager.netapp.models.QuotaReport; -import com.azure.resourcemanager.netapp.models.Type; -import java.util.Arrays; -import org.junit.jupiter.api.Assertions; - -public final class ListQuotaReportResponseInnerTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - ListQuotaReportResponseInner model = BinaryData.fromString( - "{\"value\":[{\"quotaType\":\"DefaultGroupQuota\",\"quotaTarget\":\"elwuipi\",\"quotaLimitUsedInKiBs\":5147167923805665994,\"quotaLimitTotalInKiBs\":518441316636125291,\"percentageUsed\":67.856186,\"isDerivedQuota\":false}],\"nextLink\":\"nayrhyrnxxmueedn\"}") - .toObject(ListQuotaReportResponseInner.class); - Assertions.assertEquals(Type.DEFAULT_GROUP_QUOTA, model.value().get(0).quotaType()); - Assertions.assertEquals("elwuipi", model.value().get(0).quotaTarget()); - Assertions.assertEquals(5147167923805665994L, model.value().get(0).quotaLimitUsedInKiBs()); - Assertions.assertEquals(518441316636125291L, model.value().get(0).quotaLimitTotalInKiBs()); - Assertions.assertEquals(67.856186F, model.value().get(0).percentageUsed()); - Assertions.assertEquals(false, model.value().get(0).isDerivedQuota()); - Assertions.assertEquals("nayrhyrnxxmueedn", model.nextLink()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - ListQuotaReportResponseInner model = new ListQuotaReportResponseInner() - .withValue(Arrays.asList(new QuotaReport().withQuotaType(Type.DEFAULT_GROUP_QUOTA) - .withQuotaTarget("elwuipi") - .withQuotaLimitUsedInKiBs(5147167923805665994L) - .withQuotaLimitTotalInKiBs(518441316636125291L) - .withPercentageUsed(67.856186F) - .withIsDerivedQuota(false))) - .withNextLink("nayrhyrnxxmueedn"); - model = BinaryData.fromObject(model).toObject(ListQuotaReportResponseInner.class); - Assertions.assertEquals(Type.DEFAULT_GROUP_QUOTA, model.value().get(0).quotaType()); - Assertions.assertEquals("elwuipi", model.value().get(0).quotaTarget()); - Assertions.assertEquals(5147167923805665994L, model.value().get(0).quotaLimitUsedInKiBs()); - Assertions.assertEquals(518441316636125291L, model.value().get(0).quotaLimitTotalInKiBs()); - Assertions.assertEquals(67.856186F, model.value().get(0).percentageUsed()); - Assertions.assertEquals(false, model.value().get(0).isDerivedQuota()); - Assertions.assertEquals("nayrhyrnxxmueedn", model.nextLink()); - } -} diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ListReplicationsTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ListReplicationsTests.java index cb552952e74b..44687ec5f58f 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ListReplicationsTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ListReplicationsTests.java @@ -16,33 +16,37 @@ public final class ListReplicationsTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ListReplications model = BinaryData.fromString( - "{\"value\":[{\"replicationId\":\"fnjhfjxwmszkkfo\",\"endpointType\":\"dst\",\"replicationSchedule\":\"daily\",\"remoteVolumeResourceId\":\"kzikfjawneaivxwc\",\"remoteVolumeRegion\":\"lpcirelsf\"},{\"replicationId\":\"enwabfatk\",\"endpointType\":\"dst\",\"replicationSchedule\":\"daily\",\"remoteVolumeResourceId\":\"jhwuaanozjos\",\"remoteVolumeRegion\":\"youlp\"},{\"replicationId\":\"v\",\"endpointType\":\"dst\",\"replicationSchedule\":\"daily\",\"remoteVolumeResourceId\":\"vimjwos\",\"remoteVolumeRegion\":\"xitc\"}]}") + "{\"value\":[{\"replicationId\":\"mwzn\",\"endpointType\":\"dst\",\"replicationSchedule\":\"_10minutely\",\"remoteVolumeResourceId\":\"nsorgjhxbldt\",\"remoteVolumeRegion\":\"wrlkdmtn\"},{\"replicationId\":\"ok\",\"endpointType\":\"src\",\"replicationSchedule\":\"hourly\",\"remoteVolumeResourceId\":\"d\",\"remoteVolumeRegion\":\"gsyocogj\"},{\"replicationId\":\"dtbnnha\",\"endpointType\":\"dst\",\"replicationSchedule\":\"daily\",\"remoteVolumeResourceId\":\"kvci\",\"remoteVolumeRegion\":\"nvpamq\"},{\"replicationId\":\"qqu\",\"endpointType\":\"src\",\"replicationSchedule\":\"daily\",\"remoteVolumeResourceId\":\"wggxkallat\",\"remoteVolumeRegion\":\"lwuip\"}]}") .toObject(ListReplications.class); Assertions.assertEquals(EndpointType.DST, model.value().get(0).endpointType()); - Assertions.assertEquals(ReplicationSchedule.DAILY, model.value().get(0).replicationSchedule()); - Assertions.assertEquals("kzikfjawneaivxwc", model.value().get(0).remoteVolumeResourceId()); - Assertions.assertEquals("lpcirelsf", model.value().get(0).remoteVolumeRegion()); + Assertions.assertEquals(ReplicationSchedule.ONE_ZEROMINUTELY, model.value().get(0).replicationSchedule()); + Assertions.assertEquals("nsorgjhxbldt", model.value().get(0).remoteVolumeResourceId()); + Assertions.assertEquals("wrlkdmtn", model.value().get(0).remoteVolumeRegion()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { ListReplications model = new ListReplications().withValue(Arrays.asList( new ReplicationInner().withEndpointType(EndpointType.DST) - .withReplicationSchedule(ReplicationSchedule.DAILY) - .withRemoteVolumeResourceId("kzikfjawneaivxwc") - .withRemoteVolumeRegion("lpcirelsf"), + .withReplicationSchedule(ReplicationSchedule.ONE_ZEROMINUTELY) + .withRemoteVolumeResourceId("nsorgjhxbldt") + .withRemoteVolumeRegion("wrlkdmtn"), + new ReplicationInner().withEndpointType(EndpointType.SRC) + .withReplicationSchedule(ReplicationSchedule.HOURLY) + .withRemoteVolumeResourceId("d") + .withRemoteVolumeRegion("gsyocogj"), new ReplicationInner().withEndpointType(EndpointType.DST) .withReplicationSchedule(ReplicationSchedule.DAILY) - .withRemoteVolumeResourceId("jhwuaanozjos") - .withRemoteVolumeRegion("youlp"), - new ReplicationInner().withEndpointType(EndpointType.DST) + .withRemoteVolumeResourceId("kvci") + .withRemoteVolumeRegion("nvpamq"), + new ReplicationInner().withEndpointType(EndpointType.SRC) .withReplicationSchedule(ReplicationSchedule.DAILY) - .withRemoteVolumeResourceId("vimjwos") - .withRemoteVolumeRegion("xitc"))); + .withRemoteVolumeResourceId("wggxkallat") + .withRemoteVolumeRegion("lwuip"))); model = BinaryData.fromObject(model).toObject(ListReplications.class); Assertions.assertEquals(EndpointType.DST, model.value().get(0).endpointType()); - Assertions.assertEquals(ReplicationSchedule.DAILY, model.value().get(0).replicationSchedule()); - Assertions.assertEquals("kzikfjawneaivxwc", model.value().get(0).remoteVolumeResourceId()); - Assertions.assertEquals("lpcirelsf", model.value().get(0).remoteVolumeRegion()); + Assertions.assertEquals(ReplicationSchedule.ONE_ZEROMINUTELY, model.value().get(0).replicationSchedule()); + Assertions.assertEquals("nsorgjhxbldt", model.value().get(0).remoteVolumeResourceId()); + Assertions.assertEquals("wrlkdmtn", model.value().get(0).remoteVolumeRegion()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ManagedServiceIdentityTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ManagedServiceIdentityTests.java index aa43d4fc0acf..a63a2438c55a 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ManagedServiceIdentityTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ManagedServiceIdentityTests.java @@ -16,17 +16,18 @@ public final class ManagedServiceIdentityTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ManagedServiceIdentity model = BinaryData.fromString( - "{\"principalId\":\"41c7a153-6273-463c-b066-966e097e42be\",\"tenantId\":\"2c1b9806-c637-44f7-85dd-2a03829088c8\",\"type\":\"None\",\"userAssignedIdentities\":{\"vjtoqnermclfp\":{\"principalId\":\"2b1f7f21-889b-4491-8c3e-669307c4e824\",\"clientId\":\"85b37a0c-16df-4697-b7b1-404dcf4e0115\"}}}") + "{\"principalId\":\"ffc8f9ec-c146-4461-ad09-20b556560ae3\",\"tenantId\":\"90206e44-1b6e-4fe7-ac0d-05ccf8f00c7d\",\"type\":\"SystemAssigned,UserAssigned\",\"userAssignedIdentities\":{\"nxdhbt\":{\"principalId\":\"f4ceed15-b816-4747-bead-595262ba4518\",\"clientId\":\"6c510a4a-25fb-4160-a053-1633ede03a47\"}}}") .toObject(ManagedServiceIdentity.class); - Assertions.assertEquals(ManagedServiceIdentityType.NONE, model.type()); + Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, model.type()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - ManagedServiceIdentity model = new ManagedServiceIdentity().withType(ManagedServiceIdentityType.NONE) - .withUserAssignedIdentities(mapOf("vjtoqnermclfp", new UserAssignedIdentity())); + ManagedServiceIdentity model + = new ManagedServiceIdentity().withType(ManagedServiceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED) + .withUserAssignedIdentities(mapOf("nxdhbt", new UserAssignedIdentity())); model = BinaryData.fromObject(model).toObject(ManagedServiceIdentity.class); - Assertions.assertEquals(ManagedServiceIdentityType.NONE, model.type()); + Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, model.type()); } // Use "Map.of" if available diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/MonthlyScheduleTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/MonthlyScheduleTests.java index 505ed5c22867..a7bba97032a7 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/MonthlyScheduleTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/MonthlyScheduleTests.java @@ -12,27 +12,27 @@ public final class MonthlyScheduleTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { MonthlySchedule model = BinaryData.fromString( - "{\"snapshotsToKeep\":1383706321,\"daysOfMonth\":\"t\",\"hour\":1465227251,\"minute\":951051183,\"usedBytes\":8653383903490664837}") + "{\"snapshotsToKeep\":1037639668,\"daysOfMonth\":\"ux\",\"hour\":69904268,\"minute\":1823569828,\"usedBytes\":1533657771044530360}") .toObject(MonthlySchedule.class); - Assertions.assertEquals(1383706321, model.snapshotsToKeep()); - Assertions.assertEquals("t", model.daysOfMonth()); - Assertions.assertEquals(1465227251, model.hour()); - Assertions.assertEquals(951051183, model.minute()); - Assertions.assertEquals(8653383903490664837L, model.usedBytes()); + Assertions.assertEquals(1037639668, model.snapshotsToKeep()); + Assertions.assertEquals("ux", model.daysOfMonth()); + Assertions.assertEquals(69904268, model.hour()); + Assertions.assertEquals(1823569828, model.minute()); + Assertions.assertEquals(1533657771044530360L, model.usedBytes()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - MonthlySchedule model = new MonthlySchedule().withSnapshotsToKeep(1383706321) - .withDaysOfMonth("t") - .withHour(1465227251) - .withMinute(951051183) - .withUsedBytes(8653383903490664837L); + MonthlySchedule model = new MonthlySchedule().withSnapshotsToKeep(1037639668) + .withDaysOfMonth("ux") + .withHour(69904268) + .withMinute(1823569828) + .withUsedBytes(1533657771044530360L); model = BinaryData.fromObject(model).toObject(MonthlySchedule.class); - Assertions.assertEquals(1383706321, model.snapshotsToKeep()); - Assertions.assertEquals("t", model.daysOfMonth()); - Assertions.assertEquals(1465227251, model.hour()); - Assertions.assertEquals(951051183, model.minute()); - Assertions.assertEquals(8653383903490664837L, model.usedBytes()); + Assertions.assertEquals(1037639668, model.snapshotsToKeep()); + Assertions.assertEquals("ux", model.daysOfMonth()); + Assertions.assertEquals(69904268, model.hour()); + Assertions.assertEquals(1823569828, model.minute()); + Assertions.assertEquals(1533657771044530360L, model.usedBytes()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/MountTargetPropertiesTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/MountTargetPropertiesTests.java index 6f16be31f51a..e7dc53bf52a5 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/MountTargetPropertiesTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/MountTargetPropertiesTests.java @@ -11,19 +11,19 @@ public final class MountTargetPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - MountTargetProperties model = BinaryData - .fromString( - "{\"mountTargetId\":\"rjerv\",\"fileSystemId\":\"aen\",\"ipAddress\":\"eh\",\"smbServerFqdn\":\"doy\"}") + MountTargetProperties model = BinaryData.fromString( + "{\"mountTargetId\":\"ndslgnayqigynduh\",\"fileSystemId\":\"vhqlkthumaqo\",\"ipAddress\":\"gycdu\",\"smbServerFqdn\":\"r\"}") .toObject(MountTargetProperties.class); - Assertions.assertEquals("aen", model.fileSystemId()); - Assertions.assertEquals("doy", model.smbServerFqdn()); + Assertions.assertEquals("vhqlkthumaqo", model.fileSystemId()); + Assertions.assertEquals("r", model.smbServerFqdn()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - MountTargetProperties model = new MountTargetProperties().withFileSystemId("aen").withSmbServerFqdn("doy"); + MountTargetProperties model + = new MountTargetProperties().withFileSystemId("vhqlkthumaqo").withSmbServerFqdn("r"); model = BinaryData.fromObject(model).toObject(MountTargetProperties.class); - Assertions.assertEquals("aen", model.fileSystemId()); - Assertions.assertEquals("doy", model.smbServerFqdn()); + Assertions.assertEquals("vhqlkthumaqo", model.fileSystemId()); + Assertions.assertEquals("r", model.smbServerFqdn()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourceQuotaLimitsGetWithResponseMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourceQuotaLimitsGetWithResponseMockTests.java index 1fe09e89ff16..3c987a11243e 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourceQuotaLimitsGetWithResponseMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourceQuotaLimitsGetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.SubscriptionQuotaItem; @@ -20,17 +20,17 @@ public final class NetAppResourceQuotaLimitsGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"current\":651460177,\"default\":840782124},\"id\":\"ynsqyrpfoobr\",\"name\":\"ttymsjny\",\"type\":\"qdnfwqzdz\"}"; + = "{\"properties\":{\"current\":437881905,\"default\":1054969690},\"id\":\"kneuvyinzqo\",\"name\":\"fvpgshoxgsg\",\"type\":\"p\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); SubscriptionQuotaItem response = manager.netAppResourceQuotaLimits() - .getWithResponse("qsxvmhf", "uzjyihsasbhudypo", com.azure.core.util.Context.NONE) + .getWithResponse("mtggu", "pijrajcivmmghf", com.azure.core.util.Context.NONE) .getValue(); } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourceQuotaLimitsListMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourceQuotaLimitsListMockTests.java index 575e492a83b6..731a3003310e 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourceQuotaLimitsListMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourceQuotaLimitsListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.SubscriptionQuotaItem; @@ -21,17 +21,17 @@ public final class NetAppResourceQuotaLimitsListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"current\":1638200879,\"default\":892169795},\"id\":\"etw\",\"name\":\"hhzjhfj\",\"type\":\"hvvmuvgpmun\"}]}"; + = "{\"value\":[{\"properties\":{\"current\":1056443499,\"default\":2111689562},\"id\":\"xcjzhqizxfpxt\",\"name\":\"qscjavftjuh\",\"type\":\"qaz\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response - = manager.netAppResourceQuotaLimits().list("gsjj", com.azure.core.util.Context.NONE); + = manager.netAppResourceQuotaLimits().list("h", com.azure.core.util.Context.NONE); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourceRegionInfosGetWithResponseMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourceRegionInfosGetWithResponseMockTests.java index 986a11dd7d65..23c8fc83defb 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourceRegionInfosGetWithResponseMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourceRegionInfosGetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.RegionInfoResource; @@ -22,20 +22,21 @@ public final class NetAppResourceRegionInfosGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"storageToNetworkProximity\":\"T2AndAcrossT2\",\"availabilityZoneMappings\":[{\"availabilityZone\":\"pmpdn\",\"isAvailable\":true},{\"availabilityZone\":\"awaoqvmmbnpqfrt\",\"isAvailable\":true},{\"availabilityZone\":\"megni\",\"isAvailable\":false},{\"availabilityZone\":\"xlzyqd\",\"isAvailable\":false}]},\"id\":\"cealzxwh\",\"name\":\"ansym\",\"type\":\"yqhlwigdivbkbx\"}"; + = "{\"properties\":{\"storageToNetworkProximity\":\"AcrossT2\",\"availabilityZoneMappings\":[{\"availabilityZone\":\"gpmuneqsxvmhfbuz\",\"isAvailable\":false}]},\"id\":\"sasbhu\",\"name\":\"ypoh\",\"type\":\"uemsly\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); - RegionInfoResource response - = manager.netAppResourceRegionInfos().getWithResponse("kenx", com.azure.core.util.Context.NONE).getValue(); + RegionInfoResource response = manager.netAppResourceRegionInfos() + .getWithResponse("hhzjhfj", com.azure.core.util.Context.NONE) + .getValue(); - Assertions.assertEquals(RegionStorageToNetworkProximity.T2AND_ACROSS_T2, response.storageToNetworkProximity()); - Assertions.assertEquals("pmpdn", response.availabilityZoneMappings().get(0).availabilityZone()); - Assertions.assertEquals(true, response.availabilityZoneMappings().get(0).isAvailable()); + Assertions.assertEquals(RegionStorageToNetworkProximity.ACROSS_T2, response.storageToNetworkProximity()); + Assertions.assertEquals("gpmuneqsxvmhfbuz", response.availabilityZoneMappings().get(0).availabilityZone()); + Assertions.assertEquals(false, response.availabilityZoneMappings().get(0).isAvailable()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourceRegionInfosListMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourceRegionInfosListMockTests.java index fd134c9b1c9a..ae71ff503ed2 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourceRegionInfosListMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourceRegionInfosListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.RegionInfoResource; @@ -23,22 +23,21 @@ public final class NetAppResourceRegionInfosListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"storageToNetworkProximity\":\"AcrossT2\",\"availabilityZoneMappings\":[{\"availabilityZone\":\"ijouwivkxoyzunb\",\"isAvailable\":true}]},\"id\":\"ti\",\"name\":\"vcpwpgclrc\",\"type\":\"vtsoxf\"}]}"; + = "{\"value\":[{\"properties\":{\"storageToNetworkProximity\":\"Default\",\"availabilityZoneMappings\":[{\"availabilityZone\":\"vl\",\"isAvailable\":false},{\"availabilityZone\":\"qusrdvetnws\",\"isAvailable\":false},{\"availabilityZone\":\"nwlduycvuzhyrmew\",\"isAvailable\":true}]},\"id\":\"ekdxuku\",\"name\":\"gsjj\",\"type\":\"undxgketw\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response - = manager.netAppResourceRegionInfos().list("tilaxh", com.azure.core.util.Context.NONE); + = manager.netAppResourceRegionInfos().list("gzdjtxvzf", com.azure.core.util.Context.NONE); - Assertions.assertEquals(RegionStorageToNetworkProximity.ACROSS_T2, + Assertions.assertEquals(RegionStorageToNetworkProximity.DEFAULT, response.iterator().next().storageToNetworkProximity()); - Assertions.assertEquals("ijouwivkxoyzunb", - response.iterator().next().availabilityZoneMappings().get(0).availabilityZone()); - Assertions.assertEquals(true, response.iterator().next().availabilityZoneMappings().get(0).isAvailable()); + Assertions.assertEquals("vl", response.iterator().next().availabilityZoneMappings().get(0).availabilityZone()); + Assertions.assertEquals(false, response.iterator().next().availabilityZoneMappings().get(0).isAvailable()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourcesCheckFilePathAvailabilityWithResponseMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourcesCheckFilePathAvailabilityWithResponseMockTests.java index 5368be44703c..a539761c811c 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourcesCheckFilePathAvailabilityWithResponseMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourcesCheckFilePathAvailabilityWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.CheckAvailabilityResponse; @@ -22,25 +22,25 @@ public final class NetAppResourcesCheckFilePathAvailabilityWithResponseMockTests { @Test public void testCheckFilePathAvailabilityWithResponse() throws Exception { - String responseStr = "{\"isAvailable\":false,\"reason\":\"AlreadyExists\",\"message\":\"t\"}"; + String responseStr = "{\"isAvailable\":false,\"reason\":\"AlreadyExists\",\"message\":\"cojocqwogfnzjvus\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); CheckAvailabilityResponse response = manager.netAppResources() - .checkFilePathAvailabilityWithResponse("cvhrfsp", - new FilePathAvailabilityRequest().withName("uagrttikteusqc") - .withSubnetId("kvyklxubyjaffmm") - .withAvailabilityZone("lcqcuubgqibrt"), + .checkFilePathAvailabilityWithResponse("vodggxdbee", + new FilePathAvailabilityRequest().withName("mieknlraria") + .withSubnetId("wiuagydwqf") + .withAvailabilityZone("lyr"), com.azure.core.util.Context.NONE) .getValue(); Assertions.assertEquals(false, response.isAvailable()); Assertions.assertEquals(InAvailabilityReasonType.ALREADY_EXISTS, response.reason()); - Assertions.assertEquals("t", response.message()); + Assertions.assertEquals("cojocqwogfnzjvus", response.message()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourcesCheckNameAvailabilityWithResponseMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourcesCheckNameAvailabilityWithResponseMockTests.java index 2b96c200007d..4ab7ed442f2b 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourcesCheckNameAvailabilityWithResponseMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourcesCheckNameAvailabilityWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.CheckAvailabilityResponse; @@ -23,25 +23,25 @@ public final class NetAppResourcesCheckNameAvailabilityWithResponseMockTests { @Test public void testCheckNameAvailabilityWithResponse() throws Exception { - String responseStr = "{\"isAvailable\":true,\"reason\":\"AlreadyExists\",\"message\":\"ikf\"}"; + String responseStr = "{\"isAvailable\":false,\"reason\":\"AlreadyExists\",\"message\":\"zqlqhyc\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); CheckAvailabilityResponse response = manager.netAppResources() - .checkNameAvailabilityWithResponse("wotey", - new ResourceNameAvailabilityRequest().withName("wcluqovekqvgq") - .withType(CheckNameResourceTypes.MICROSOFT_NET_APP_NET_APP_ACCOUNTS_CAPACITY_POOLS_VOLUMES) - .withResourceGroup("wifzmp"), + .checkNameAvailabilityWithResponse("srvhmgorffuki", + new ResourceNameAvailabilityRequest().withName("cvwmzhwplefa") + .withType(CheckNameResourceTypes.MICROSOFT_NET_APP_NET_APP_ACCOUNTS_CAPACITY_POOLS) + .withResourceGroup("xilcbtgnhnzey"), com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals(true, response.isAvailable()); + Assertions.assertEquals(false, response.isAvailable()); Assertions.assertEquals(InAvailabilityReasonType.ALREADY_EXISTS, response.reason()); - Assertions.assertEquals("ikf", response.message()); + Assertions.assertEquals("zqlqhyc", response.message()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourcesCheckQuotaAvailabilityWithResponseMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourcesCheckQuotaAvailabilityWithResponseMockTests.java index b50bf5a8c10f..b4faee1e19b9 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourcesCheckQuotaAvailabilityWithResponseMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourcesCheckQuotaAvailabilityWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.CheckAvailabilityResponse; @@ -23,25 +23,25 @@ public final class NetAppResourcesCheckQuotaAvailabilityWithResponseMockTests { @Test public void testCheckQuotaAvailabilityWithResponse() throws Exception { - String responseStr = "{\"isAvailable\":true,\"reason\":\"Invalid\",\"message\":\"bjoxs\"}"; + String responseStr = "{\"isAvailable\":true,\"reason\":\"AlreadyExists\",\"message\":\"kb\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); - CheckAvailabilityResponse response - = manager.netAppResources() - .checkQuotaAvailabilityWithResponse("gdslqxihhrmoo", new QuotaAvailabilityRequest().withName("z") - .withType( - CheckQuotaNameResourceTypes.MICROSOFT_NET_APP_NET_APP_ACCOUNTS_CAPACITY_POOLS_VOLUMES_SNAPSHOTS) - .withResourceGroup("eypxiutcxapzhyr"), com.azure.core.util.Context.NONE) - .getValue(); + CheckAvailabilityResponse response = manager.netAppResources() + .checkQuotaAvailabilityWithResponse("zldmozuxy", + new QuotaAvailabilityRequest().withName("fsbtkad") + .withType(CheckQuotaNameResourceTypes.MICROSOFT_NET_APP_NET_APP_ACCOUNTS_CAPACITY_POOLS_VOLUMES) + .withResourceGroup("s"), + com.azure.core.util.Context.NONE) + .getValue(); Assertions.assertEquals(true, response.isAvailable()); - Assertions.assertEquals(InAvailabilityReasonType.INVALID, response.reason()); - Assertions.assertEquals("bjoxs", response.message()); + Assertions.assertEquals(InAvailabilityReasonType.ALREADY_EXISTS, response.reason()); + Assertions.assertEquals("kb", response.message()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourcesQueryNetworkSiblingSetWithResponseMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourcesQueryNetworkSiblingSetWithResponseMockTests.java index ef0c079d32a7..78a4c98c2ab1 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourcesQueryNetworkSiblingSetWithResponseMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourcesQueryNetworkSiblingSetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.NetworkFeatures; @@ -23,25 +23,25 @@ public final class NetAppResourcesQueryNetworkSiblingSetWithResponseMockTests { @Test public void testQueryNetworkSiblingSetWithResponse() throws Exception { String responseStr - = "{\"networkSiblingSetId\":\"ft\",\"subnetId\":\"gfcwqmpimaqxzhem\",\"networkSiblingSetStateId\":\"h\",\"networkFeatures\":\"Basic\",\"provisioningState\":\"Canceled\",\"nicInfoList\":[{\"ipAddress\":\"kozzwculkb\",\"volumeResourceIds\":[\"fajnjwltlwtjjguk\",\"alhsnvkc\",\"mxzrpoa\",\"mlnwiaaomylweazu\"]}]}"; + = "{\"networkSiblingSetId\":\"ekqvgqouwif\",\"subnetId\":\"pjwyiv\",\"networkSiblingSetStateId\":\"kfxcvhrfs\",\"networkFeatures\":\"Standard_Basic\",\"provisioningState\":\"Updating\",\"nicInfoList\":[{\"ipAddress\":\"ikteusqczkvyk\",\"volumeResourceIds\":[\"byjaffmmf\",\"lcqcuubgqibrt\",\"lmetttwgdslqxi\"]},{\"ipAddress\":\"rmooizqse\",\"volumeResourceIds\":[\"iut\",\"xapzhyrpet\"]},{\"ipAddress\":\"e\",\"volumeResourceIds\":[\"xslhvnhlabrqnkk\",\"jcjbt\"]},{\"ipAddress\":\"aehvvibrxjjstoq\",\"volumeResourceIds\":[\"tpkxztmoobklft\"]}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); NetworkSiblingSet response = manager.netAppResources() - .queryNetworkSiblingSetWithResponse("vibr", - new QueryNetworkSiblingSetRequest().withNetworkSiblingSetId("jj").withSubnetId("toqbeitpkxztmoob"), + .queryNetworkSiblingSetWithResponse("tzbsrgnowcjhf", + new QueryNetworkSiblingSetRequest().withNetworkSiblingSetId("mvec").withSubnetId("ctxmwoteyowcluq"), com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("ft", response.networkSiblingSetId()); - Assertions.assertEquals("gfcwqmpimaqxzhem", response.subnetId()); - Assertions.assertEquals("h", response.networkSiblingSetStateId()); - Assertions.assertEquals(NetworkFeatures.BASIC, response.networkFeatures()); - Assertions.assertEquals("fajnjwltlwtjjguk", response.nicInfoList().get(0).volumeResourceIds().get(0)); + Assertions.assertEquals("ekqvgqouwif", response.networkSiblingSetId()); + Assertions.assertEquals("pjwyiv", response.subnetId()); + Assertions.assertEquals("kfxcvhrfs", response.networkSiblingSetStateId()); + Assertions.assertEquals(NetworkFeatures.STANDARD_BASIC, response.networkFeatures()); + Assertions.assertEquals("byjaffmmf", response.nicInfoList().get(0).volumeResourceIds().get(0)); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourcesQueryRegionInfoWithResponseMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourcesQueryRegionInfoWithResponseMockTests.java index c727154235cf..abe955f78657 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourcesQueryRegionInfoWithResponseMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourcesQueryRegionInfoWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.RegionInfo; @@ -22,21 +22,22 @@ public final class NetAppResourcesQueryRegionInfoWithResponseMockTests { @Test public void testQueryRegionInfoWithResponse() throws Exception { String responseStr - = "{\"storageToNetworkProximity\":\"T1AndAcrossT2\",\"availabilityZoneMappings\":[{\"availabilityZone\":\"kkzjcjbtrga\",\"isAvailable\":false}]}"; + = "{\"storageToNetworkProximity\":\"T1AndT2AndAcrossT2\",\"availabilityZoneMappings\":[{\"availabilityZone\":\"pe\",\"isAvailable\":false},{\"availabilityZone\":\"qdhcu\",\"isAvailable\":false},{\"availabilityZone\":\"lcwkhihihlhz\",\"isAvailable\":false}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); RegionInfo response = manager.netAppResources() - .queryRegionInfoWithResponse("hvnh", com.azure.core.util.Context.NONE) + .queryRegionInfoWithResponse("grjqctojcmi", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals(RegionStorageToNetworkProximity.T1AND_ACROSS_T2, response.storageToNetworkProximity()); - Assertions.assertEquals("kkzjcjbtrga", response.availabilityZoneMappings().get(0).availabilityZone()); + Assertions.assertEquals(RegionStorageToNetworkProximity.T1AND_T2AND_ACROSS_T2, + response.storageToNetworkProximity()); + Assertions.assertEquals("pe", response.availabilityZoneMappings().get(0).availabilityZone()); Assertions.assertEquals(false, response.availabilityZoneMappings().get(0).isAvailable()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourcesUpdateNetworkSiblingSetMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourcesUpdateNetworkSiblingSetMockTests.java index e43e5bb8a069..6851e9ba8309 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourcesUpdateNetworkSiblingSetMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/NetAppResourcesUpdateNetworkSiblingSetMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.NetworkFeatures; @@ -23,27 +23,27 @@ public final class NetAppResourcesUpdateNetworkSiblingSetMockTests { @Test public void testUpdateNetworkSiblingSet() throws Exception { String responseStr - = "{\"networkSiblingSetId\":\"yxgncxykxhdjhli\",\"subnetId\":\"bcxf\",\"networkSiblingSetStateId\":\"cporxvxcjz\",\"networkFeatures\":\"Standard\",\"provisioningState\":\"Canceled\",\"nicInfoList\":[{\"ipAddress\":\"tgqscjavftjuh\",\"volumeResourceIds\":[\"zkmtgguwpijrajci\",\"m\",\"ghfcfiwrxgkneuvy\"]},{\"ipAddress\":\"zqodfvpgshox\",\"volumeResourceIds\":[\"bpfgzdj\",\"xvzflbqv\"]},{\"ipAddress\":\"qvlgafcqusrdvetn\",\"volumeResourceIds\":[\"tutnwlduycvuzhyr\",\"ewipm\",\"ekdxuku\"]}]}"; + = "{\"networkSiblingSetId\":\"uktalhsnvkcdmxz\",\"subnetId\":\"oaimlnw\",\"networkSiblingSetStateId\":\"aomylwea\",\"networkFeatures\":\"Basic_Standard\",\"provisioningState\":\"Failed\",\"nicInfoList\":[{\"ipAddress\":\"wwnpj\",\"volumeResourceIds\":[\"zswpchwa\"]},{\"ipAddress\":\"bousn\",\"volumeResourceIds\":[\"gfewetwlyxgnc\",\"ykxhdjh\",\"immbcx\"]}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); NetworkSiblingSet response = manager.netAppResources() - .updateNetworkSiblingSet("cse", - new UpdateNetworkSiblingSetRequest().withNetworkSiblingSetId("hwwn") - .withSubnetId("jhlfzswpchwahf") - .withNetworkSiblingSetStateId("ousnfepgfewe") - .withNetworkFeatures(NetworkFeatures.BASIC_STANDARD), + .updateNetworkSiblingSet("dgfcwqmp", + new UpdateNetworkSiblingSetRequest().withNetworkSiblingSetId("maqxzhemjyh") + .withSubnetId("hujswtwkozzwcul") + .withNetworkSiblingSetStateId("bawpfajnjwltlwt") + .withNetworkFeatures(NetworkFeatures.BASIC), com.azure.core.util.Context.NONE); - Assertions.assertEquals("yxgncxykxhdjhli", response.networkSiblingSetId()); - Assertions.assertEquals("bcxf", response.subnetId()); - Assertions.assertEquals("cporxvxcjz", response.networkSiblingSetStateId()); - Assertions.assertEquals(NetworkFeatures.STANDARD, response.networkFeatures()); - Assertions.assertEquals("zkmtgguwpijrajci", response.nicInfoList().get(0).volumeResourceIds().get(0)); + Assertions.assertEquals("uktalhsnvkcdmxz", response.networkSiblingSetId()); + Assertions.assertEquals("oaimlnw", response.subnetId()); + Assertions.assertEquals("aomylwea", response.networkSiblingSetStateId()); + Assertions.assertEquals(NetworkFeatures.BASIC_STANDARD, response.networkFeatures()); + Assertions.assertEquals("zswpchwa", response.nicInfoList().get(0).volumeResourceIds().get(0)); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/OperationsListMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/OperationsListMockTests.java index 8e784b62f2af..bd7661979b17 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/OperationsListMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/OperationsListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.MetricAggregationType; @@ -23,30 +23,30 @@ public final class OperationsListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"name\":\"kvylauyavl\",\"display\":{\"provider\":\"ncstt\",\"resource\":\"fybvpoek\",\"operation\":\"gsgbdhuzq\",\"description\":\"j\"},\"origin\":\"kynscliqhzv\",\"properties\":{\"serviceSpecification\":{\"metricSpecifications\":[{\"name\":\"tkubotppn\",\"displayName\":\"xz\",\"displayDescription\":\"ihfrbbcevqa\",\"unit\":\"ltd\",\"supportedAggregationTypes\":[\"Average\",\"Average\"],\"supportedTimeGrainTypes\":[\"py\",\"vgtrdcnifmzzs\",\"ymbrnysuxmpraf\",\"g\"],\"internalMetricName\":\"hocxvdfffwafqrou\",\"enableRegionalMdmAccount\":false,\"sourceMdmAccount\":\"avehhrvkbunzo\",\"sourceMdmNamespace\":\"dhcxgkmoy\",\"dimensions\":[{},{}],\"aggregationType\":\"uibhmfdnbzydvfv\",\"fillGapWithZero\":false,\"category\":\"aeoisrvh\",\"resourceIdDimensionNameOverride\":\"orffukiscv\",\"isInternal\":true},{\"name\":\"wplefaxvxil\",\"displayName\":\"tg\",\"displayDescription\":\"nzeyqxtjj\",\"unit\":\"qlqhycavodg\",\"supportedAggregationTypes\":[\"Average\",\"Average\"],\"supportedTimeGrainTypes\":[\"mieknlraria\",\"wiuagydwqf\",\"ylyrfgiagtco\"],\"internalMetricName\":\"cqwogfnzjvusfzl\",\"enableRegionalMdmAccount\":true,\"sourceMdmAccount\":\"uxylfsbtkadpy\",\"sourceMdmNamespace\":\"wn\",\"dimensions\":[{},{},{}],\"aggregationType\":\"bugrj\",\"fillGapWithZero\":false,\"category\":\"jc\",\"resourceIdDimensionNameOverride\":\"sofieypefojyqd\",\"isInternal\":false}],\"logSpecifications\":[{\"name\":\"plcwkhi\",\"displayName\":\"hlhzdsqtzbsrgno\"},{\"name\":\"jhf\",\"displayName\":\"vecactx\"}]}}}]}"; + = "{\"value\":[{\"name\":\"jvpglydzgk\",\"display\":{\"provider\":\"eevt\",\"resource\":\"pryu\",\"operation\":\"wytpzdmovz\",\"description\":\"va\"},\"origin\":\"zqadf\",\"properties\":{\"serviceSpecification\":{\"metricSpecifications\":[{\"name\":\"glae\",\"displayName\":\"ndtic\",\"displayDescription\":\"pvz\",\"unit\":\"qtmldgxo\",\"supportedAggregationTypes\":[\"Average\",\"Average\"],\"supportedTimeGrainTypes\":[\"pkc\"],\"internalMetricName\":\"yzriykhy\",\"enableRegionalMdmAccount\":true,\"sourceMdmAccount\":\"jlb\",\"sourceMdmNamespace\":\"qvkjlmxho\",\"dimensions\":[{},{},{}],\"aggregationType\":\"hdwdi\",\"fillGapWithZero\":true,\"category\":\"nraauzz\",\"resourceIdDimensionNameOverride\":\"jazysdzhezwwvaiq\",\"isInternal\":false},{\"name\":\"fonkphhqyikvyla\",\"displayName\":\"avluwmncs\",\"displayDescription\":\"ijf\",\"unit\":\"vpo\",\"supportedAggregationTypes\":[\"Average\"],\"supportedTimeGrainTypes\":[\"gbdhuzqgnjdg\",\"ynscl\"],\"internalMetricName\":\"hzvhxnkomtkubo\",\"enableRegionalMdmAccount\":false,\"sourceMdmAccount\":\"vdxzxhihfrbbc\",\"sourceMdmNamespace\":\"qagt\",\"dimensions\":[{},{},{},{}],\"aggregationType\":\"lfkqojpy\",\"fillGapWithZero\":false,\"category\":\"rdcnifmzzsdy\",\"resourceIdDimensionNameOverride\":\"rnysux\",\"isInternal\":true}],\"logSpecifications\":[{\"name\":\"g\",\"displayName\":\"hocxvdfffwafqrou\"},{\"name\":\"spave\",\"displayName\":\"r\"},{\"name\":\"bunzozudh\",\"displayName\":\"gkmoyxcdyuibhmfd\"},{\"name\":\"zydvfvf\",\"displayName\":\"naeo\"}]}}}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.operations().list(com.azure.core.util.Context.NONE); - Assertions.assertEquals("kvylauyavl", response.iterator().next().name()); - Assertions.assertEquals("ncstt", response.iterator().next().display().provider()); - Assertions.assertEquals("fybvpoek", response.iterator().next().display().resource()); - Assertions.assertEquals("gsgbdhuzq", response.iterator().next().display().operation()); - Assertions.assertEquals("j", response.iterator().next().display().description()); - Assertions.assertEquals("kynscliqhzv", response.iterator().next().origin()); - Assertions.assertEquals("tkubotppn", + Assertions.assertEquals("jvpglydzgk", response.iterator().next().name()); + Assertions.assertEquals("eevt", response.iterator().next().display().provider()); + Assertions.assertEquals("pryu", response.iterator().next().display().resource()); + Assertions.assertEquals("wytpzdmovz", response.iterator().next().display().operation()); + Assertions.assertEquals("va", response.iterator().next().display().description()); + Assertions.assertEquals("zqadf", response.iterator().next().origin()); + Assertions.assertEquals("glae", response.iterator().next().serviceSpecification().metricSpecifications().get(0).name()); - Assertions.assertEquals("xz", + Assertions.assertEquals("ndtic", response.iterator().next().serviceSpecification().metricSpecifications().get(0).displayName()); - Assertions.assertEquals("ihfrbbcevqa", + Assertions.assertEquals("pvz", response.iterator().next().serviceSpecification().metricSpecifications().get(0).displayDescription()); - Assertions.assertEquals("ltd", + Assertions.assertEquals("qtmldgxo", response.iterator().next().serviceSpecification().metricSpecifications().get(0).unit()); Assertions.assertEquals(MetricAggregationType.AVERAGE, response.iterator() @@ -56,7 +56,7 @@ public void testList() throws Exception { .get(0) .supportedAggregationTypes() .get(0)); - Assertions.assertEquals("py", + Assertions.assertEquals("pkc", response.iterator() .next() .serviceSpecification() @@ -64,32 +64,32 @@ public void testList() throws Exception { .get(0) .supportedTimeGrainTypes() .get(0)); - Assertions.assertEquals("hocxvdfffwafqrou", + Assertions.assertEquals("yzriykhy", response.iterator().next().serviceSpecification().metricSpecifications().get(0).internalMetricName()); - Assertions.assertEquals(false, + Assertions.assertEquals(true, response.iterator().next().serviceSpecification().metricSpecifications().get(0).enableRegionalMdmAccount()); - Assertions.assertEquals("avehhrvkbunzo", + Assertions.assertEquals("jlb", response.iterator().next().serviceSpecification().metricSpecifications().get(0).sourceMdmAccount()); - Assertions.assertEquals("dhcxgkmoy", + Assertions.assertEquals("qvkjlmxho", response.iterator().next().serviceSpecification().metricSpecifications().get(0).sourceMdmNamespace()); - Assertions.assertEquals("uibhmfdnbzydvfv", + Assertions.assertEquals("hdwdi", response.iterator().next().serviceSpecification().metricSpecifications().get(0).aggregationType()); - Assertions.assertEquals(false, + Assertions.assertEquals(true, response.iterator().next().serviceSpecification().metricSpecifications().get(0).fillGapWithZero()); - Assertions.assertEquals("aeoisrvh", + Assertions.assertEquals("nraauzz", response.iterator().next().serviceSpecification().metricSpecifications().get(0).category()); - Assertions.assertEquals("orffukiscv", + Assertions.assertEquals("jazysdzhezwwvaiq", response.iterator() .next() .serviceSpecification() .metricSpecifications() .get(0) .resourceIdDimensionNameOverride()); - Assertions.assertEquals(true, + Assertions.assertEquals(false, response.iterator().next().serviceSpecification().metricSpecifications().get(0).isInternal()); - Assertions.assertEquals("plcwkhi", + Assertions.assertEquals("g", response.iterator().next().serviceSpecification().logSpecifications().get(0).name()); - Assertions.assertEquals("hlhzdsqtzbsrgno", + Assertions.assertEquals("hocxvdfffwafqrou", response.iterator().next().serviceSpecification().logSpecifications().get(0).displayName()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/PeerClusterForVolumeMigrationRequestTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/PeerClusterForVolumeMigrationRequestTests.java index 13b7d1a92992..a54191ce99f6 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/PeerClusterForVolumeMigrationRequestTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/PeerClusterForVolumeMigrationRequestTests.java @@ -13,16 +13,16 @@ public final class PeerClusterForVolumeMigrationRequestTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { PeerClusterForVolumeMigrationRequest model - = BinaryData.fromString("{\"peerIpAddresses\":[\"idb\",\"fatpxllrxcyjmoa\",\"su\",\"arm\"]}") + = BinaryData.fromString("{\"peerIpAddresses\":[\"ygdvwv\",\"piohgwxrtfu\",\"xepxgyqagvrvmn\"]}") .toObject(PeerClusterForVolumeMigrationRequest.class); - Assertions.assertEquals("idb", model.peerIpAddresses().get(0)); + Assertions.assertEquals("ygdvwv", model.peerIpAddresses().get(0)); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { PeerClusterForVolumeMigrationRequest model = new PeerClusterForVolumeMigrationRequest() - .withPeerIpAddresses(Arrays.asList("idb", "fatpxllrxcyjmoa", "su", "arm")); + .withPeerIpAddresses(Arrays.asList("ygdvwv", "piohgwxrtfu", "xepxgyqagvrvmn")); model = BinaryData.fromObject(model).toObject(PeerClusterForVolumeMigrationRequest.class); - Assertions.assertEquals("idb", model.peerIpAddresses().get(0)); + Assertions.assertEquals("ygdvwv", model.peerIpAddresses().get(0)); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/PoolChangeRequestTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/PoolChangeRequestTests.java index a0db69839da0..e0f8b128d2fc 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/PoolChangeRequestTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/PoolChangeRequestTests.java @@ -12,14 +12,14 @@ public final class PoolChangeRequestTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { PoolChangeRequest model - = BinaryData.fromString("{\"newPoolResourceId\":\"kgymareqnajxqug\"}").toObject(PoolChangeRequest.class); - Assertions.assertEquals("kgymareqnajxqug", model.newPoolResourceId()); + = BinaryData.fromString("{\"newPoolResourceId\":\"rey\"}").toObject(PoolChangeRequest.class); + Assertions.assertEquals("rey", model.newPoolResourceId()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - PoolChangeRequest model = new PoolChangeRequest().withNewPoolResourceId("kgymareqnajxqug"); + PoolChangeRequest model = new PoolChangeRequest().withNewPoolResourceId("rey"); model = BinaryData.fromObject(model).toObject(PoolChangeRequest.class); - Assertions.assertEquals("kgymareqnajxqug", model.newPoolResourceId()); + Assertions.assertEquals("rey", model.newPoolResourceId()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/PoolPatchPropertiesTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/PoolPatchPropertiesTests.java index c8bc3970ad21..7e29ec32b48e 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/PoolPatchPropertiesTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/PoolPatchPropertiesTests.java @@ -12,25 +12,21 @@ public final class PoolPatchPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - PoolPatchProperties model = BinaryData.fromString( - "{\"size\":5688325155939436400,\"qosType\":\"Auto\",\"coolAccess\":false,\"customThroughputMibps\":54.82628}") - .toObject(PoolPatchProperties.class); - Assertions.assertEquals(5688325155939436400L, model.size()); - Assertions.assertEquals(QosType.AUTO, model.qosType()); - Assertions.assertEquals(false, model.coolAccess()); - Assertions.assertEquals(54.82628F, model.customThroughputMibps()); + PoolPatchProperties model + = BinaryData.fromString("{\"size\":946944160211123587,\"qosType\":\"Manual\",\"coolAccess\":true}") + .toObject(PoolPatchProperties.class); + Assertions.assertEquals(946944160211123587L, model.size()); + Assertions.assertEquals(QosType.MANUAL, model.qosType()); + Assertions.assertEquals(true, model.coolAccess()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - PoolPatchProperties model = new PoolPatchProperties().withSize(5688325155939436400L) - .withQosType(QosType.AUTO) - .withCoolAccess(false) - .withCustomThroughputMibps(54.82628F); + PoolPatchProperties model + = new PoolPatchProperties().withSize(946944160211123587L).withQosType(QosType.MANUAL).withCoolAccess(true); model = BinaryData.fromObject(model).toObject(PoolPatchProperties.class); - Assertions.assertEquals(5688325155939436400L, model.size()); - Assertions.assertEquals(QosType.AUTO, model.qosType()); - Assertions.assertEquals(false, model.coolAccess()); - Assertions.assertEquals(54.82628F, model.customThroughputMibps()); + Assertions.assertEquals(946944160211123587L, model.size()); + Assertions.assertEquals(QosType.MANUAL, model.qosType()); + Assertions.assertEquals(true, model.coolAccess()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/PoolPropertiesTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/PoolPropertiesTests.java index b76ab1b8a9fa..221e129f62ea 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/PoolPropertiesTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/PoolPropertiesTests.java @@ -15,30 +15,27 @@ public final class PoolPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { PoolProperties model = BinaryData.fromString( - "{\"poolId\":\"ekqvkeln\",\"size\":2597163492495193220,\"serviceLevel\":\"Standard\",\"provisioningState\":\"wyjsflhhcaalnjix\",\"totalThroughputMibps\":26.624393,\"utilizedThroughputMibps\":79.06187,\"customThroughputMibps\":21.879053,\"qosType\":\"Manual\",\"coolAccess\":true,\"encryptionType\":\"Double\"}") + "{\"poolId\":\"nsmvbxwyj\",\"size\":9187109765948314327,\"serviceLevel\":\"Premium\",\"provisioningState\":\"caalnjixisxyaw\",\"totalThroughputMibps\":82.835205,\"utilizedThroughputMibps\":64.62957,\"qosType\":\"Manual\",\"coolAccess\":true,\"encryptionType\":\"Single\"}") .toObject(PoolProperties.class); - Assertions.assertEquals(2597163492495193220L, model.size()); - Assertions.assertEquals(ServiceLevel.STANDARD, model.serviceLevel()); - Assertions.assertEquals(21.879053F, model.customThroughputMibps()); + Assertions.assertEquals(9187109765948314327L, model.size()); + Assertions.assertEquals(ServiceLevel.PREMIUM, model.serviceLevel()); Assertions.assertEquals(QosType.MANUAL, model.qosType()); Assertions.assertEquals(true, model.coolAccess()); - Assertions.assertEquals(EncryptionType.DOUBLE, model.encryptionType()); + Assertions.assertEquals(EncryptionType.SINGLE, model.encryptionType()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - PoolProperties model = new PoolProperties().withSize(2597163492495193220L) - .withServiceLevel(ServiceLevel.STANDARD) - .withCustomThroughputMibps(21.879053F) + PoolProperties model = new PoolProperties().withSize(9187109765948314327L) + .withServiceLevel(ServiceLevel.PREMIUM) .withQosType(QosType.MANUAL) .withCoolAccess(true) - .withEncryptionType(EncryptionType.DOUBLE); + .withEncryptionType(EncryptionType.SINGLE); model = BinaryData.fromObject(model).toObject(PoolProperties.class); - Assertions.assertEquals(2597163492495193220L, model.size()); - Assertions.assertEquals(ServiceLevel.STANDARD, model.serviceLevel()); - Assertions.assertEquals(21.879053F, model.customThroughputMibps()); + Assertions.assertEquals(9187109765948314327L, model.size()); + Assertions.assertEquals(ServiceLevel.PREMIUM, model.serviceLevel()); Assertions.assertEquals(QosType.MANUAL, model.qosType()); Assertions.assertEquals(true, model.coolAccess()); - Assertions.assertEquals(EncryptionType.DOUBLE, model.encryptionType()); + Assertions.assertEquals(EncryptionType.SINGLE, model.encryptionType()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/PoolsCreateOrUpdateMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/PoolsCreateOrUpdateMockTests.java index 499d02a972c3..d13f1362d26b 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/PoolsCreateOrUpdateMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/PoolsCreateOrUpdateMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.CapacityPool; @@ -26,36 +26,35 @@ public final class PoolsCreateOrUpdateMockTests { @Test public void testCreateOrUpdate() throws Exception { String responseStr - = "{\"etag\":\"v\",\"properties\":{\"poolId\":\"ufuqyrx\",\"size\":6853300792215489751,\"serviceLevel\":\"Premium\",\"provisioningState\":\"Succeeded\",\"totalThroughputMibps\":78.630066,\"utilizedThroughputMibps\":62.450417,\"customThroughputMibps\":8.434969,\"qosType\":\"Manual\",\"coolAccess\":false,\"encryptionType\":\"Double\"},\"location\":\"fcdis\",\"tags\":{\"rxzbujr\":\"nxzhcze\",\"nlnzonzlrpi\":\"rhqvwrevkh\"},\"id\":\"yw\",\"name\":\"cvjtszcofiz\",\"type\":\"htd\"}"; + = "{\"etag\":\"qxnmwmqt\",\"properties\":{\"poolId\":\"xyi\",\"size\":8723326269402268094,\"serviceLevel\":\"StandardZRS\",\"provisioningState\":\"Succeeded\",\"totalThroughputMibps\":15.086746,\"utilizedThroughputMibps\":61.958694,\"qosType\":\"Manual\",\"coolAccess\":false,\"encryptionType\":\"Single\"},\"location\":\"dqmeqwigpibudq\",\"tags\":{\"ybpmzznrtffyaq\":\"eb\",\"hvseufuqyrx\":\"tmhheioqa\",\"dgamquhiosrsj\":\"dlcgqlsismjqfr\"},\"id\":\"ivfcdisyirnx\",\"name\":\"hcz\",\"type\":\"xrxzbujrtr\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); CapacityPool response = manager.pools() - .define("emwmdxmebwjs") - .withRegion("kpn") - .withExistingNetAppAccount("wxdzaumweoohgu", "fuzboyjathwtzolb") - .withSize(8437685781238493437L) - .withServiceLevel(ServiceLevel.FLEXIBLE) - .withTags(mapOf("dqmeqwigpibudq", "apm")) - .withCustomThroughputMibps(12.6477F) + .define("pifhpfeoajvgcxtx") + .withRegion("wsldrizetpwbr") + .withExistingNetAppAccount("bwnhhtql", "ehgpp") + .withSize(8087831620363185447L) + .withServiceLevel(ServiceLevel.STANDARD) + .withTags(mapOf("qzmiza", "libph", "ankjpdnjzh", "a", "lmuoyxprimrsopte", "joylh", "wxdzaumweoohgu", + "cjmeislstvasy")) .withQosType(QosType.AUTO) - .withCoolAccess(true) - .withEncryptionType(EncryptionType.SINGLE) + .withCoolAccess(false) + .withEncryptionType(EncryptionType.DOUBLE) .create(); - Assertions.assertEquals("fcdis", response.location()); - Assertions.assertEquals("nxzhcze", response.tags().get("rxzbujr")); - Assertions.assertEquals(6853300792215489751L, response.size()); - Assertions.assertEquals(ServiceLevel.PREMIUM, response.serviceLevel()); - Assertions.assertEquals(8.434969F, response.customThroughputMibps()); + Assertions.assertEquals("dqmeqwigpibudq", response.location()); + Assertions.assertEquals("eb", response.tags().get("ybpmzznrtffyaq")); + Assertions.assertEquals(8723326269402268094L, response.size()); + Assertions.assertEquals(ServiceLevel.STANDARD_ZRS, response.serviceLevel()); Assertions.assertEquals(QosType.MANUAL, response.qosType()); Assertions.assertEquals(false, response.coolAccess()); - Assertions.assertEquals(EncryptionType.DOUBLE, response.encryptionType()); + Assertions.assertEquals(EncryptionType.SINGLE, response.encryptionType()); } // Use "Map.of" if available diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/PoolsGetWithResponseMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/PoolsGetWithResponseMockTests.java index f8ec41ee1ab6..02c6683639e3 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/PoolsGetWithResponseMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/PoolsGetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.CapacityPool; @@ -24,26 +24,24 @@ public final class PoolsGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"etag\":\"sheafid\",\"properties\":{\"poolId\":\"ugsresmkssjhoi\",\"size\":8087831620363185447,\"serviceLevel\":\"Premium\",\"provisioningState\":\"fwegprhptillu\",\"totalThroughputMibps\":48.5814,\"utilizedThroughputMibps\":88.57164,\"customThroughputMibps\":34.170998,\"qosType\":\"Auto\",\"coolAccess\":true,\"encryptionType\":\"Double\"},\"location\":\"ldrizetpwbra\",\"tags\":{\"qzmiza\":\"ibph\",\"ankjpdnjzh\":\"a\"},\"id\":\"joylh\",\"name\":\"lmuoyxprimrsopte\",\"type\":\"cjmeislstvasy\"}"; + = "{\"etag\":\"rcxfailcfxwmdb\",\"properties\":{\"poolId\":\"dfgsftufqobrj\",\"size\":3034279146046559675,\"serviceLevel\":\"StandardZRS\",\"provisioningState\":\"cc\",\"totalThroughputMibps\":18.878342,\"utilizedThroughputMibps\":32.467564,\"qosType\":\"Auto\",\"coolAccess\":false,\"encryptionType\":\"Double\"},\"location\":\"rzvul\",\"tags\":{\"roylaxxu\":\"aeranokqgukkjqnv\",\"sfjbjsvg\":\"cdisd\",\"lxgccknfnwmbtm\":\"rwhryvycytd\",\"hchrphkmcrjdqn\":\"pdvjdhttzaefedx\"},\"id\":\"dfzpbgtgkylkdg\",\"name\":\"rjeuut\",\"type\":\"wxezwzhok\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); - CapacityPool response = manager.pools() - .getWithResponse("kvbwnhhtqlgeh", "ppipifhpfeoa", "vgcxtx", com.azure.core.util.Context.NONE) - .getValue(); + CapacityPool response + = manager.pools().getWithResponse("m", "es", "kdlpa", com.azure.core.util.Context.NONE).getValue(); - Assertions.assertEquals("ldrizetpwbra", response.location()); - Assertions.assertEquals("ibph", response.tags().get("qzmiza")); - Assertions.assertEquals(8087831620363185447L, response.size()); - Assertions.assertEquals(ServiceLevel.PREMIUM, response.serviceLevel()); - Assertions.assertEquals(34.170998F, response.customThroughputMibps()); + Assertions.assertEquals("rzvul", response.location()); + Assertions.assertEquals("aeranokqgukkjqnv", response.tags().get("roylaxxu")); + Assertions.assertEquals(3034279146046559675L, response.size()); + Assertions.assertEquals(ServiceLevel.STANDARD_ZRS, response.serviceLevel()); Assertions.assertEquals(QosType.AUTO, response.qosType()); - Assertions.assertEquals(true, response.coolAccess()); + Assertions.assertEquals(false, response.coolAccess()); Assertions.assertEquals(EncryptionType.DOUBLE, response.encryptionType()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/PoolsListMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/PoolsListMockTests.java index 9082cf8d24aa..f9ff95e43ed6 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/PoolsListMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/PoolsListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.CapacityPool; @@ -25,25 +25,24 @@ public final class PoolsListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"etag\":\"ckknhxkizvy\",\"properties\":{\"poolId\":\"rzvul\",\"size\":149873479955101826,\"serviceLevel\":\"Premium\",\"provisioningState\":\"rano\",\"totalThroughputMibps\":72.54921,\"utilizedThroughputMibps\":92.12962,\"customThroughputMibps\":20.17358,\"qosType\":\"Manual\",\"coolAccess\":false,\"encryptionType\":\"Single\"},\"location\":\"laxxulc\",\"tags\":{\"r\":\"dosfjbjsvgjrw\",\"t\":\"vyc\",\"xgccknfnw\":\"c\",\"fedxihchrphkm\":\"btmvpdvjdhttza\"},\"id\":\"rjdqnsdfzp\",\"name\":\"gtgkylkdghr\",\"type\":\"euutlwxezwzh\"}]}"; + = "{\"value\":[{\"etag\":\"zddrt\",\"properties\":{\"poolId\":\"doj\",\"size\":3326683287722087129,\"serviceLevel\":\"Ultra\",\"provisioningState\":\"vrefdeesv\",\"totalThroughputMibps\":14.100099,\"utilizedThroughputMibps\":78.21149,\"qosType\":\"Manual\",\"coolAccess\":false,\"encryptionType\":\"Double\"},\"location\":\"prtujwsawdd\",\"tags\":{\"itvtzeexavo\":\"abxvi\",\"dmdqb\":\"tfgle\",\"cbslhhx\":\"pypqtgsfj\"},\"id\":\"db\",\"name\":\"vodhtn\",\"type\":\"irudh\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response - = manager.pools().list("dfgsftufqobrj", "nac", com.azure.core.util.Context.NONE); + = manager.pools().list("cxcktpi", "merteeammxqiek", com.azure.core.util.Context.NONE); - Assertions.assertEquals("laxxulc", response.iterator().next().location()); - Assertions.assertEquals("dosfjbjsvgjrw", response.iterator().next().tags().get("r")); - Assertions.assertEquals(149873479955101826L, response.iterator().next().size()); - Assertions.assertEquals(ServiceLevel.PREMIUM, response.iterator().next().serviceLevel()); - Assertions.assertEquals(20.17358F, response.iterator().next().customThroughputMibps()); + Assertions.assertEquals("prtujwsawdd", response.iterator().next().location()); + Assertions.assertEquals("abxvi", response.iterator().next().tags().get("itvtzeexavo")); + Assertions.assertEquals(3326683287722087129L, response.iterator().next().size()); + Assertions.assertEquals(ServiceLevel.ULTRA, response.iterator().next().serviceLevel()); Assertions.assertEquals(QosType.MANUAL, response.iterator().next().qosType()); Assertions.assertEquals(false, response.iterator().next().coolAccess()); - Assertions.assertEquals(EncryptionType.SINGLE, response.iterator().next().encryptionType()); + Assertions.assertEquals(EncryptionType.DOUBLE, response.iterator().next().encryptionType()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/QuotaReportTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/QuotaReportTests.java deleted file mode 100644 index fc9144529ad8..000000000000 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/QuotaReportTests.java +++ /dev/null @@ -1,42 +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.resourcemanager.netapp.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.netapp.models.QuotaReport; -import com.azure.resourcemanager.netapp.models.Type; -import org.junit.jupiter.api.Assertions; - -public final class QuotaReportTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - QuotaReport model = BinaryData.fromString( - "{\"quotaType\":\"DefaultGroupQuota\",\"quotaTarget\":\"stkwqqtch\",\"quotaLimitUsedInKiBs\":416295343158305691,\"quotaLimitTotalInKiBs\":5417188415846728288,\"percentageUsed\":24.116516,\"isDerivedQuota\":false}") - .toObject(QuotaReport.class); - Assertions.assertEquals(Type.DEFAULT_GROUP_QUOTA, model.quotaType()); - Assertions.assertEquals("stkwqqtch", model.quotaTarget()); - Assertions.assertEquals(416295343158305691L, model.quotaLimitUsedInKiBs()); - Assertions.assertEquals(5417188415846728288L, model.quotaLimitTotalInKiBs()); - Assertions.assertEquals(24.116516F, model.percentageUsed()); - Assertions.assertEquals(false, model.isDerivedQuota()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - QuotaReport model = new QuotaReport().withQuotaType(Type.DEFAULT_GROUP_QUOTA) - .withQuotaTarget("stkwqqtch") - .withQuotaLimitUsedInKiBs(416295343158305691L) - .withQuotaLimitTotalInKiBs(5417188415846728288L) - .withPercentageUsed(24.116516F) - .withIsDerivedQuota(false); - model = BinaryData.fromObject(model).toObject(QuotaReport.class); - Assertions.assertEquals(Type.DEFAULT_GROUP_QUOTA, model.quotaType()); - Assertions.assertEquals("stkwqqtch", model.quotaTarget()); - Assertions.assertEquals(416295343158305691L, model.quotaLimitUsedInKiBs()); - Assertions.assertEquals(5417188415846728288L, model.quotaLimitTotalInKiBs()); - Assertions.assertEquals(24.116516F, model.percentageUsed()); - Assertions.assertEquals(false, model.isDerivedQuota()); - } -} diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ReestablishReplicationRequestTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ReestablishReplicationRequestTests.java index 8f1d647a8f9d..44e4fd7ed2b3 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ReestablishReplicationRequestTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ReestablishReplicationRequestTests.java @@ -11,15 +11,15 @@ public final class ReestablishReplicationRequestTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - ReestablishReplicationRequest model - = BinaryData.fromString("{\"sourceVolumeId\":\"wvgpiohg\"}").toObject(ReestablishReplicationRequest.class); - Assertions.assertEquals("wvgpiohg", model.sourceVolumeId()); + ReestablishReplicationRequest model = BinaryData.fromString("{\"sourceVolumeId\":\"ioxiysuiizyn\"}") + .toObject(ReestablishReplicationRequest.class); + Assertions.assertEquals("ioxiysuiizyn", model.sourceVolumeId()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - ReestablishReplicationRequest model = new ReestablishReplicationRequest().withSourceVolumeId("wvgpiohg"); + ReestablishReplicationRequest model = new ReestablishReplicationRequest().withSourceVolumeId("ioxiysuiizyn"); model = BinaryData.fromObject(model).toObject(ReestablishReplicationRequest.class); - Assertions.assertEquals("wvgpiohg", model.sourceVolumeId()); + Assertions.assertEquals("ioxiysuiizyn", model.sourceVolumeId()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/RemotePathTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/RemotePathTests.java index 4d640fae4078..ed55cc679bd7 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/RemotePathTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/RemotePathTests.java @@ -13,21 +13,21 @@ public final class RemotePathTests { public void testDeserialize() throws Exception { RemotePath model = BinaryData .fromString( - "{\"externalHostName\":\"htozfikdow\",\"serverName\":\"quuvxzxcl\",\"volumeName\":\"ithhqzon\"}") + "{\"externalHostName\":\"zxmhhvhgu\",\"serverName\":\"eodkwobda\",\"volumeName\":\"xtibqdxbxwakbog\"}") .toObject(RemotePath.class); - Assertions.assertEquals("htozfikdow", model.externalHostname()); - Assertions.assertEquals("quuvxzxcl", model.serverName()); - Assertions.assertEquals("ithhqzon", model.volumeName()); + Assertions.assertEquals("zxmhhvhgu", model.externalHostname()); + Assertions.assertEquals("eodkwobda", model.serverName()); + Assertions.assertEquals("xtibqdxbxwakbog", model.volumeName()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - RemotePath model = new RemotePath().withExternalHostname("htozfikdow") - .withServerName("quuvxzxcl") - .withVolumeName("ithhqzon"); + RemotePath model = new RemotePath().withExternalHostname("zxmhhvhgu") + .withServerName("eodkwobda") + .withVolumeName("xtibqdxbxwakbog"); model = BinaryData.fromObject(model).toObject(RemotePath.class); - Assertions.assertEquals("htozfikdow", model.externalHostname()); - Assertions.assertEquals("quuvxzxcl", model.serverName()); - Assertions.assertEquals("ithhqzon", model.volumeName()); + Assertions.assertEquals("zxmhhvhgu", model.externalHostname()); + Assertions.assertEquals("eodkwobda", model.serverName()); + Assertions.assertEquals("xtibqdxbxwakbog", model.volumeName()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ReplicationInnerTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ReplicationInnerTests.java index 0a9fdf97df54..4c9fcb473c98 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ReplicationInnerTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ReplicationInnerTests.java @@ -14,24 +14,24 @@ public final class ReplicationInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ReplicationInner model = BinaryData.fromString( - "{\"replicationId\":\"fcktqumiekke\",\"endpointType\":\"src\",\"replicationSchedule\":\"hourly\",\"remoteVolumeResourceId\":\"ly\",\"remoteVolumeRegion\":\"hdgqggeb\"}") + "{\"replicationId\":\"cjzkzivgvvcna\",\"endpointType\":\"src\",\"replicationSchedule\":\"_10minutely\",\"remoteVolumeResourceId\":\"nxxmueedndrdv\",\"remoteVolumeRegion\":\"kwqqtchealmf\"}") .toObject(ReplicationInner.class); Assertions.assertEquals(EndpointType.SRC, model.endpointType()); - Assertions.assertEquals(ReplicationSchedule.HOURLY, model.replicationSchedule()); - Assertions.assertEquals("ly", model.remoteVolumeResourceId()); - Assertions.assertEquals("hdgqggeb", model.remoteVolumeRegion()); + Assertions.assertEquals(ReplicationSchedule.ONE_ZEROMINUTELY, model.replicationSchedule()); + Assertions.assertEquals("nxxmueedndrdv", model.remoteVolumeResourceId()); + Assertions.assertEquals("kwqqtchealmf", model.remoteVolumeRegion()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { ReplicationInner model = new ReplicationInner().withEndpointType(EndpointType.SRC) - .withReplicationSchedule(ReplicationSchedule.HOURLY) - .withRemoteVolumeResourceId("ly") - .withRemoteVolumeRegion("hdgqggeb"); + .withReplicationSchedule(ReplicationSchedule.ONE_ZEROMINUTELY) + .withRemoteVolumeResourceId("nxxmueedndrdv") + .withRemoteVolumeRegion("kwqqtchealmf"); model = BinaryData.fromObject(model).toObject(ReplicationInner.class); Assertions.assertEquals(EndpointType.SRC, model.endpointType()); - Assertions.assertEquals(ReplicationSchedule.HOURLY, model.replicationSchedule()); - Assertions.assertEquals("ly", model.remoteVolumeResourceId()); - Assertions.assertEquals("hdgqggeb", model.remoteVolumeRegion()); + Assertions.assertEquals(ReplicationSchedule.ONE_ZEROMINUTELY, model.replicationSchedule()); + Assertions.assertEquals("nxxmueedndrdv", model.remoteVolumeResourceId()); + Assertions.assertEquals("kwqqtchealmf", model.remoteVolumeRegion()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ReplicationObjectTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ReplicationObjectTests.java index 12a58f06a826..ed2467e80325 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ReplicationObjectTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ReplicationObjectTests.java @@ -15,33 +15,32 @@ public final class ReplicationObjectTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ReplicationObject model = BinaryData.fromString( - "{\"replicationId\":\"kqze\",\"endpointType\":\"dst\",\"replicationSchedule\":\"hourly\",\"remoteVolumeResourceId\":\"fzxmhhvhgureodkw\",\"remotePath\":{\"externalHostName\":\"dagxtibqd\",\"serverName\":\"bxwakbog\",\"volumeName\":\"xndlkzgxhu\"},\"remoteVolumeRegion\":\"plbpodxun\",\"destinationReplications\":[{\"resourceId\":\"xmubyyntwlrbq\",\"replicationType\":\"CrossZoneReplication\",\"region\":\"evseotgqrlltmuwl\",\"zone\":\"wzizxbmpgcjefuzm\"},{\"resourceId\":\"pbttdum\",\"replicationType\":\"CrossRegionReplication\",\"region\":\"xe\",\"zone\":\"nzbtbhj\"},{\"resourceId\":\"lkfg\",\"replicationType\":\"CrossRegionReplication\",\"region\":\"euel\",\"zone\":\"hsd\"}]}") + "{\"replicationId\":\"shhszhedplvwiw\",\"endpointType\":\"src\",\"replicationSchedule\":\"daily\",\"remoteVolumeResourceId\":\"esl\",\"remotePath\":{\"externalHostName\":\"k\",\"serverName\":\"wtppjflcxogaoko\",\"volumeName\":\"z\"},\"remoteVolumeRegion\":\"sikvmkqzeqqkdlt\"}") .toObject(ReplicationObject.class); - Assertions.assertEquals(EndpointType.DST, model.endpointType()); - Assertions.assertEquals(ReplicationSchedule.HOURLY, model.replicationSchedule()); - Assertions.assertEquals("fzxmhhvhgureodkw", model.remoteVolumeResourceId()); - Assertions.assertEquals("dagxtibqd", model.remotePath().externalHostname()); - Assertions.assertEquals("bxwakbog", model.remotePath().serverName()); - Assertions.assertEquals("xndlkzgxhu", model.remotePath().volumeName()); - Assertions.assertEquals("plbpodxun", model.remoteVolumeRegion()); + Assertions.assertEquals(EndpointType.SRC, model.endpointType()); + Assertions.assertEquals(ReplicationSchedule.DAILY, model.replicationSchedule()); + Assertions.assertEquals("esl", model.remoteVolumeResourceId()); + Assertions.assertEquals("k", model.remotePath().externalHostname()); + Assertions.assertEquals("wtppjflcxogaoko", model.remotePath().serverName()); + Assertions.assertEquals("z", model.remotePath().volumeName()); + Assertions.assertEquals("sikvmkqzeqqkdlt", model.remoteVolumeRegion()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - ReplicationObject model = new ReplicationObject().withEndpointType(EndpointType.DST) - .withReplicationSchedule(ReplicationSchedule.HOURLY) - .withRemoteVolumeResourceId("fzxmhhvhgureodkw") - .withRemotePath(new RemotePath().withExternalHostname("dagxtibqd") - .withServerName("bxwakbog") - .withVolumeName("xndlkzgxhu")) - .withRemoteVolumeRegion("plbpodxun"); + ReplicationObject model = new ReplicationObject().withEndpointType(EndpointType.SRC) + .withReplicationSchedule(ReplicationSchedule.DAILY) + .withRemoteVolumeResourceId("esl") + .withRemotePath( + new RemotePath().withExternalHostname("k").withServerName("wtppjflcxogaoko").withVolumeName("z")) + .withRemoteVolumeRegion("sikvmkqzeqqkdlt"); model = BinaryData.fromObject(model).toObject(ReplicationObject.class); - Assertions.assertEquals(EndpointType.DST, model.endpointType()); - Assertions.assertEquals(ReplicationSchedule.HOURLY, model.replicationSchedule()); - Assertions.assertEquals("fzxmhhvhgureodkw", model.remoteVolumeResourceId()); - Assertions.assertEquals("dagxtibqd", model.remotePath().externalHostname()); - Assertions.assertEquals("bxwakbog", model.remotePath().serverName()); - Assertions.assertEquals("xndlkzgxhu", model.remotePath().volumeName()); - Assertions.assertEquals("plbpodxun", model.remoteVolumeRegion()); + Assertions.assertEquals(EndpointType.SRC, model.endpointType()); + Assertions.assertEquals(ReplicationSchedule.DAILY, model.replicationSchedule()); + Assertions.assertEquals("esl", model.remoteVolumeResourceId()); + Assertions.assertEquals("k", model.remotePath().externalHostname()); + Assertions.assertEquals("wtppjflcxogaoko", model.remotePath().serverName()); + Assertions.assertEquals("z", model.remotePath().volumeName()); + Assertions.assertEquals("sikvmkqzeqqkdlt", model.remoteVolumeRegion()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ReplicationStatusInnerTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ReplicationStatusInnerTests.java index e41dec0c0d35..78bc12656486 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ReplicationStatusInnerTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/ReplicationStatusInnerTests.java @@ -14,27 +14,27 @@ public final class ReplicationStatusInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ReplicationStatusInner model = BinaryData.fromString( - "{\"healthy\":true,\"relationshipStatus\":\"Unknown\",\"mirrorState\":\"Broken\",\"totalProgress\":\"epxgyqagvr\",\"errorMessage\":\"npkukghimdblx\"}") + "{\"healthy\":false,\"relationshipStatus\":\"Unknown\",\"mirrorState\":\"Broken\",\"totalProgress\":\"yhqmibzyhwi\",\"errorMessage\":\"mypyynpcdpu\"}") .toObject(ReplicationStatusInner.class); - Assertions.assertEquals(true, model.healthy()); + Assertions.assertEquals(false, model.healthy()); Assertions.assertEquals(RelationshipStatus.UNKNOWN, model.relationshipStatus()); Assertions.assertEquals(MirrorState.BROKEN, model.mirrorState()); - Assertions.assertEquals("epxgyqagvr", model.totalProgress()); - Assertions.assertEquals("npkukghimdblx", model.errorMessage()); + Assertions.assertEquals("yhqmibzyhwi", model.totalProgress()); + Assertions.assertEquals("mypyynpcdpu", model.errorMessage()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - ReplicationStatusInner model = new ReplicationStatusInner().withHealthy(true) + ReplicationStatusInner model = new ReplicationStatusInner().withHealthy(false) .withRelationshipStatus(RelationshipStatus.UNKNOWN) .withMirrorState(MirrorState.BROKEN) - .withTotalProgress("epxgyqagvr") - .withErrorMessage("npkukghimdblx"); + .withTotalProgress("yhqmibzyhwi") + .withErrorMessage("mypyynpcdpu"); model = BinaryData.fromObject(model).toObject(ReplicationStatusInner.class); - Assertions.assertEquals(true, model.healthy()); + Assertions.assertEquals(false, model.healthy()); Assertions.assertEquals(RelationshipStatus.UNKNOWN, model.relationshipStatus()); Assertions.assertEquals(MirrorState.BROKEN, model.mirrorState()); - Assertions.assertEquals("epxgyqagvr", model.totalProgress()); - Assertions.assertEquals("npkukghimdblx", model.errorMessage()); + Assertions.assertEquals("yhqmibzyhwi", model.totalProgress()); + Assertions.assertEquals("mypyynpcdpu", model.errorMessage()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/RestoreStatusInnerTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/RestoreStatusInnerTests.java index 5bb24fb5fe69..73f42620d10e 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/RestoreStatusInnerTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/RestoreStatusInnerTests.java @@ -11,7 +11,7 @@ public final class RestoreStatusInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { RestoreStatusInner model = BinaryData.fromString( - "{\"healthy\":false,\"relationshipStatus\":\"Idle\",\"mirrorState\":\"Broken\",\"unhealthyReason\":\"emvvhm\",\"errorMessage\":\"drjf\",\"totalTransferBytes\":6646451916229099217}") + "{\"healthy\":false,\"relationshipStatus\":\"Idle\",\"mirrorState\":\"Mirrored\",\"unhealthyReason\":\"mblrrilbywd\",\"errorMessage\":\"miccwrwfscjfnyn\",\"totalTransferBytes\":8587420366319258397}") .toObject(RestoreStatusInner.class); } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotInnerTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotInnerTests.java index 2d6f16bc5065..3041ee703ded 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotInnerTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotInnerTests.java @@ -12,15 +12,15 @@ public final class SnapshotInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { SnapshotInner model = BinaryData.fromString( - "{\"location\":\"oo\",\"properties\":{\"snapshotId\":\"nuj\",\"created\":\"2021-09-22T15:19:18Z\",\"provisioningState\":\"sbvdkcrodtjinfw\"},\"id\":\"fltkacjv\",\"name\":\"f\",\"type\":\"dlfoakggkfp\"}") + "{\"location\":\"moadsuvarmy\",\"properties\":{\"snapshotId\":\"jsjqbjhhyx\",\"created\":\"2021-08-08T09:59:53Z\",\"provisioningState\":\"yc\"},\"id\":\"uhpkxkgymar\",\"name\":\"qnajxqugj\",\"type\":\"ky\"}") .toObject(SnapshotInner.class); - Assertions.assertEquals("oo", model.location()); + Assertions.assertEquals("moadsuvarmy", model.location()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - SnapshotInner model = new SnapshotInner().withLocation("oo"); + SnapshotInner model = new SnapshotInner().withLocation("moadsuvarmy"); model = BinaryData.fromObject(model).toObject(SnapshotInner.class); - Assertions.assertEquals("oo", model.location()); + Assertions.assertEquals("moadsuvarmy", model.location()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesCreateWithResponseMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesCreateWithResponseMockTests.java index 37e3de8de84c..cb09b666586b 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesCreateWithResponseMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesCreateWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.DailySchedule; @@ -27,60 +27,60 @@ public final class SnapshotPoliciesCreateWithResponseMockTests { @Test public void testCreateWithResponse() throws Exception { String responseStr - = "{\"etag\":\"h\",\"properties\":{\"hourlySchedule\":{\"snapshotsToKeep\":897856665,\"minute\":828921483,\"usedBytes\":3522262881342173226},\"dailySchedule\":{\"snapshotsToKeep\":1072949444,\"hour\":1744260958,\"minute\":373432473,\"usedBytes\":8927877098345650470},\"weeklySchedule\":{\"snapshotsToKeep\":2070557844,\"day\":\"fa\",\"hour\":1329774917,\"minute\":244946884,\"usedBytes\":1721764598490696593},\"monthlySchedule\":{\"snapshotsToKeep\":1562293671,\"daysOfMonth\":\"wzdvpiwh\",\"hour\":801550005,\"minute\":1096789874,\"usedBytes\":4550472352331294604},\"enabled\":true,\"provisioningState\":\"uhuxylrjvmtyg\"},\"location\":\"mzyospspshck\",\"tags\":{\"gt\":\"jpmspbpssdfppy\",\"unjdx\":\"eyujtvczkcnyxrx\",\"ivbgkcv\":\"glnkvxlxpagl\",\"pubcpzgpxtivhjk\":\"hpzvuqdflvoniyp\"},\"id\":\"idibgqjxgpn\",\"name\":\"hgovfgp\",\"type\":\"kqmhhaowjr\"}"; + = "{\"etag\":\"kdk\",\"properties\":{\"hourlySchedule\":{\"snapshotsToKeep\":2145222324,\"minute\":211340974,\"usedBytes\":2755469222712772213},\"dailySchedule\":{\"snapshotsToKeep\":1667262093,\"hour\":1385405898,\"minute\":1193273500,\"usedBytes\":1035962610522456238},\"weeklySchedule\":{\"snapshotsToKeep\":644079964,\"day\":\"eyirdhlisngw\",\"hour\":1258635298,\"minute\":1354932365,\"usedBytes\":7225725672768775525},\"monthlySchedule\":{\"snapshotsToKeep\":21737184,\"daysOfMonth\":\"pqxpx\",\"hour\":1760888733,\"minute\":2135849980,\"usedBytes\":3198963628835972526},\"enabled\":false,\"provisioningState\":\"iixtmkzj\"},\"location\":\"viirhgfgrws\",\"tags\":{\"zvzbglbyv\":\"ra\",\"rgxffmshkw\":\"ctctbrxkjz\",\"qaclnapxbiy\":\"bkgozxwopdbydpi\",\"nfsm\":\"nugj\"},\"id\":\"cttuxuu\",\"name\":\"i\",\"type\":\"flqo\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); SnapshotPolicy response = manager.snapshotPolicies() - .define("wtqabpxuckp") - .withRegion("ctctbrxkjz") - .withExistingNetAppAccount("ulkpakd", "ifmjnn") - .withTags(mapOf("shkwfbkgozxwopd", "xff", "izqaclnapxbiyg", "yd", "mfcttux", "ugjknf")) - .withHourlySchedule(new HourlySchedule().withSnapshotsToKeep(1189308614) - .withMinute(351115849) - .withUsedBytes(5405797443088065857L)) - .withDailySchedule(new DailySchedule().withSnapshotsToKeep(1682370359) - .withHour(254570862) - .withMinute(21737184) - .withUsedBytes(4881754570538060934L)) - .withWeeklySchedule(new WeeklySchedule().withSnapshotsToKeep(717298847) - .withDay("wfcngjsaas") - .withHour(1007355900) - .withMinute(352154258) - .withUsedBytes(7947475498891793194L)) - .withMonthlySchedule(new MonthlySchedule().withSnapshotsToKeep(671429821) - .withDaysOfMonth("irhgfgrwsdp") - .withHour(1006538190) - .withMinute(145136330) - .withUsedBytes(1716738927704410418L)) - .withEnabled(true) + .define("laprlt") + .withRegion("lmjjyuo") + .withExistingNetAppAccount("ktcqio", "mgbzahgxqdlyrtl") + .withTags(mapOf("lbfjkwr", "obaxkjeytu")) + .withHourlySchedule(new HourlySchedule().withSnapshotsToKeep(1452545825) + .withMinute(1574788888) + .withUsedBytes(4404103409694460959L)) + .withDailySchedule(new DailySchedule().withSnapshotsToKeep(1340564567) + .withHour(1515346381) + .withMinute(226736084) + .withUsedBytes(9185198515701434959L)) + .withWeeklySchedule(new WeeklySchedule().withSnapshotsToKeep(860612333) + .withDay("l") + .withHour(101279026) + .withMinute(1797453594) + .withUsedBytes(448677184186092036L)) + .withMonthlySchedule(new MonthlySchedule().withSnapshotsToKeep(721207223) + .withDaysOfMonth("av") + .withHour(1704124687) + .withMinute(1319470940) + .withUsedBytes(1465450309959087886L)) + .withEnabled(false) .create(); - Assertions.assertEquals("mzyospspshck", response.location()); - Assertions.assertEquals("jpmspbpssdfppy", response.tags().get("gt")); - Assertions.assertEquals(897856665, response.hourlySchedule().snapshotsToKeep()); - Assertions.assertEquals(828921483, response.hourlySchedule().minute()); - Assertions.assertEquals(3522262881342173226L, response.hourlySchedule().usedBytes()); - Assertions.assertEquals(1072949444, response.dailySchedule().snapshotsToKeep()); - Assertions.assertEquals(1744260958, response.dailySchedule().hour()); - Assertions.assertEquals(373432473, response.dailySchedule().minute()); - Assertions.assertEquals(8927877098345650470L, response.dailySchedule().usedBytes()); - Assertions.assertEquals(2070557844, response.weeklySchedule().snapshotsToKeep()); - Assertions.assertEquals("fa", response.weeklySchedule().day()); - Assertions.assertEquals(1329774917, response.weeklySchedule().hour()); - Assertions.assertEquals(244946884, response.weeklySchedule().minute()); - Assertions.assertEquals(1721764598490696593L, response.weeklySchedule().usedBytes()); - Assertions.assertEquals(1562293671, response.monthlySchedule().snapshotsToKeep()); - Assertions.assertEquals("wzdvpiwh", response.monthlySchedule().daysOfMonth()); - Assertions.assertEquals(801550005, response.monthlySchedule().hour()); - Assertions.assertEquals(1096789874, response.monthlySchedule().minute()); - Assertions.assertEquals(4550472352331294604L, response.monthlySchedule().usedBytes()); - Assertions.assertEquals(true, response.enabled()); + Assertions.assertEquals("viirhgfgrws", response.location()); + Assertions.assertEquals("ra", response.tags().get("zvzbglbyv")); + Assertions.assertEquals(2145222324, response.hourlySchedule().snapshotsToKeep()); + Assertions.assertEquals(211340974, response.hourlySchedule().minute()); + Assertions.assertEquals(2755469222712772213L, response.hourlySchedule().usedBytes()); + Assertions.assertEquals(1667262093, response.dailySchedule().snapshotsToKeep()); + Assertions.assertEquals(1385405898, response.dailySchedule().hour()); + Assertions.assertEquals(1193273500, response.dailySchedule().minute()); + Assertions.assertEquals(1035962610522456238L, response.dailySchedule().usedBytes()); + Assertions.assertEquals(644079964, response.weeklySchedule().snapshotsToKeep()); + Assertions.assertEquals("eyirdhlisngw", response.weeklySchedule().day()); + Assertions.assertEquals(1258635298, response.weeklySchedule().hour()); + Assertions.assertEquals(1354932365, response.weeklySchedule().minute()); + Assertions.assertEquals(7225725672768775525L, response.weeklySchedule().usedBytes()); + Assertions.assertEquals(21737184, response.monthlySchedule().snapshotsToKeep()); + Assertions.assertEquals("pqxpx", response.monthlySchedule().daysOfMonth()); + Assertions.assertEquals(1760888733, response.monthlySchedule().hour()); + Assertions.assertEquals(2135849980, response.monthlySchedule().minute()); + Assertions.assertEquals(3198963628835972526L, response.monthlySchedule().usedBytes()); + Assertions.assertEquals(false, response.enabled()); } // Use "Map.of" if available diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesDeleteMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesDeleteMockTests.java index 86db7f59ee11..df77c2a22254 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesDeleteMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesDeleteMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import java.nio.charset.StandardCharsets; @@ -25,9 +25,9 @@ public void testDelete() throws Exception { NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); - manager.snapshotPolicies().delete("tgfebwln", "mhyreeudz", "av", com.azure.core.util.Context.NONE); + manager.snapshotPolicies().delete("tsxoatftgz", "npbs", "vefloccsrmozihmi", com.azure.core.util.Context.NONE); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesGetWithResponseMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesGetWithResponseMockTests.java index 619585cc8109..729f533e1d11 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesGetWithResponseMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesGetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.SnapshotPolicy; @@ -21,38 +21,38 @@ public final class SnapshotPoliciesGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"etag\":\"npbs\",\"properties\":{\"hourlySchedule\":{\"snapshotsToKeep\":850012212,\"minute\":1075307971,\"usedBytes\":1298535123525566512},\"dailySchedule\":{\"snapshotsToKeep\":583656217,\"hour\":1317782310,\"minute\":152817823,\"usedBytes\":9008218506530550951},\"weeklySchedule\":{\"snapshotsToKeep\":639665928,\"day\":\"xp\",\"hour\":2137168460,\"minute\":1198784321,\"usedBytes\":59350505754780702},\"monthlySchedule\":{\"snapshotsToKeep\":1519575286,\"daysOfMonth\":\"fmpcycilrmca\",\"hour\":740438524,\"minute\":297687924,\"usedBytes\":1184351512319513135},\"enabled\":false,\"provisioningState\":\"ksxwpnd\"},\"location\":\"pfnznthjtwkj\",\"tags\":{\"tcqiosmg\":\"rxuzvoam\",\"xqdlyrtltlapr\":\"zah\",\"atbhjmznn\":\"tz\"},\"id\":\"s\",\"name\":\"qeqala\",\"type\":\"vlagun\"}"; + = "{\"etag\":\"yxgvelfcld\",\"properties\":{\"hourlySchedule\":{\"snapshotsToKeep\":1806892496,\"minute\":667519337,\"usedBytes\":3451295234524077317},\"dailySchedule\":{\"snapshotsToKeep\":1949096000,\"hour\":228727125,\"minute\":1462697228,\"usedBytes\":7919003630386505885},\"weeklySchedule\":{\"snapshotsToKeep\":885473318,\"day\":\"wjizcilnghgsh\",\"hour\":884114239,\"minute\":1075398674,\"usedBytes\":1841698857513805001},\"monthlySchedule\":{\"snapshotsToKeep\":732294522,\"daysOfMonth\":\"lxqzvn\",\"hour\":1381551038,\"minute\":1534178183,\"usedBytes\":8510007533425740916},\"enabled\":false,\"provisioningState\":\"amikzebrqbsm\"},\"location\":\"ziqgfuh\",\"tags\":{\"czznvfbycjsxj\":\"ruswhv\",\"vumwmxqh\":\"wix\"},\"id\":\"dvnoamldsehaohdj\",\"name\":\"hflzokxco\",\"type\":\"pelnjetag\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); SnapshotPolicy response = manager.snapshotPolicies() - .getWithResponse("coxpelnjeta", "ltsxoatf", "g", com.azure.core.util.Context.NONE) + .getWithResponse("yinljqe", "qwhix", "onsts", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("pfnznthjtwkj", response.location()); - Assertions.assertEquals("rxuzvoam", response.tags().get("tcqiosmg")); - Assertions.assertEquals(850012212, response.hourlySchedule().snapshotsToKeep()); - Assertions.assertEquals(1075307971, response.hourlySchedule().minute()); - Assertions.assertEquals(1298535123525566512L, response.hourlySchedule().usedBytes()); - Assertions.assertEquals(583656217, response.dailySchedule().snapshotsToKeep()); - Assertions.assertEquals(1317782310, response.dailySchedule().hour()); - Assertions.assertEquals(152817823, response.dailySchedule().minute()); - Assertions.assertEquals(9008218506530550951L, response.dailySchedule().usedBytes()); - Assertions.assertEquals(639665928, response.weeklySchedule().snapshotsToKeep()); - Assertions.assertEquals("xp", response.weeklySchedule().day()); - Assertions.assertEquals(2137168460, response.weeklySchedule().hour()); - Assertions.assertEquals(1198784321, response.weeklySchedule().minute()); - Assertions.assertEquals(59350505754780702L, response.weeklySchedule().usedBytes()); - Assertions.assertEquals(1519575286, response.monthlySchedule().snapshotsToKeep()); - Assertions.assertEquals("fmpcycilrmca", response.monthlySchedule().daysOfMonth()); - Assertions.assertEquals(740438524, response.monthlySchedule().hour()); - Assertions.assertEquals(297687924, response.monthlySchedule().minute()); - Assertions.assertEquals(1184351512319513135L, response.monthlySchedule().usedBytes()); + Assertions.assertEquals("ziqgfuh", response.location()); + Assertions.assertEquals("ruswhv", response.tags().get("czznvfbycjsxj")); + Assertions.assertEquals(1806892496, response.hourlySchedule().snapshotsToKeep()); + Assertions.assertEquals(667519337, response.hourlySchedule().minute()); + Assertions.assertEquals(3451295234524077317L, response.hourlySchedule().usedBytes()); + Assertions.assertEquals(1949096000, response.dailySchedule().snapshotsToKeep()); + Assertions.assertEquals(228727125, response.dailySchedule().hour()); + Assertions.assertEquals(1462697228, response.dailySchedule().minute()); + Assertions.assertEquals(7919003630386505885L, response.dailySchedule().usedBytes()); + Assertions.assertEquals(885473318, response.weeklySchedule().snapshotsToKeep()); + Assertions.assertEquals("wjizcilnghgsh", response.weeklySchedule().day()); + Assertions.assertEquals(884114239, response.weeklySchedule().hour()); + Assertions.assertEquals(1075398674, response.weeklySchedule().minute()); + Assertions.assertEquals(1841698857513805001L, response.weeklySchedule().usedBytes()); + Assertions.assertEquals(732294522, response.monthlySchedule().snapshotsToKeep()); + Assertions.assertEquals("lxqzvn", response.monthlySchedule().daysOfMonth()); + Assertions.assertEquals(1381551038, response.monthlySchedule().hour()); + Assertions.assertEquals(1534178183, response.monthlySchedule().minute()); + Assertions.assertEquals(8510007533425740916L, response.monthlySchedule().usedBytes()); Assertions.assertEquals(false, response.enabled()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesListMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesListMockTests.java index c0b028c64c5a..2bdc2c9c908a 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesListMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.SnapshotPolicy; @@ -22,37 +22,37 @@ public final class SnapshotPoliciesListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"etag\":\"gicgaaoepttaq\",\"properties\":{\"hourlySchedule\":{\"snapshotsToKeep\":1354970767,\"minute\":153395237,\"usedBytes\":6222106413777972482},\"dailySchedule\":{\"snapshotsToKeep\":827241082,\"hour\":140983404,\"minute\":466668490,\"usedBytes\":6482628412909459959},\"weeklySchedule\":{\"snapshotsToKeep\":744984595,\"day\":\"kimrt\",\"hour\":2101404470,\"minute\":2017974836,\"usedBytes\":5182793984668664248},\"monthlySchedule\":{\"snapshotsToKeep\":1426347910,\"daysOfMonth\":\"qepqwhixmon\",\"hour\":927727255,\"minute\":171287650,\"usedBytes\":9072157943517962123},\"enabled\":true,\"provisioningState\":\"fclduccbirdsv\"},\"location\":\"cobiegstmninwjiz\",\"tags\":{\"tbxqmuluxlxq\":\"nghgshej\",\"amikzebrqbsm\":\"vnersbycucrw\",\"swhvhczznvfbycj\":\"wziqgfuhokzr\",\"xzv\":\"xjww\"},\"id\":\"mwmxqhndvnoamld\",\"name\":\"ehaohdjhh\",\"type\":\"lzok\"}]}"; + = "{\"value\":[{\"etag\":\"n\",\"properties\":{\"hourlySchedule\":{\"snapshotsToKeep\":1310458507,\"minute\":416565759,\"usedBytes\":363191384797208698},\"dailySchedule\":{\"snapshotsToKeep\":362710224,\"hour\":2027194811,\"minute\":1192657678,\"usedBytes\":8283915751167918851},\"weeklySchedule\":{\"snapshotsToKeep\":691935711,\"day\":\"zelfwyfwl\",\"hour\":953163194,\"minute\":139746588,\"usedBytes\":979869830822712459},\"monthlySchedule\":{\"snapshotsToKeep\":1420965357,\"daysOfMonth\":\"lafzvaylptr\",\"hour\":294199057,\"minute\":1346932281,\"usedBytes\":3411367963754147437},\"enabled\":false,\"provisioningState\":\"chcxwaxfewzj\"},\"location\":\"exfdeqvhpsylk\",\"tags\":{\"jrgywwpgjxsn\":\"kbffmbmx\",\"jgicgaao\":\"tf\"},\"id\":\"pttaqutd\",\"name\":\"wemxswvruunzz\",\"type\":\"gehkfkimrtixokff\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response - = manager.snapshotPolicies().list("jrgywwpgjxsn", "tf", com.azure.core.util.Context.NONE); + = manager.snapshotPolicies().list("nktwfansnvpdibmi", "ostbzbkiwb", com.azure.core.util.Context.NONE); - Assertions.assertEquals("cobiegstmninwjiz", response.iterator().next().location()); - Assertions.assertEquals("nghgshej", response.iterator().next().tags().get("tbxqmuluxlxq")); - Assertions.assertEquals(1354970767, response.iterator().next().hourlySchedule().snapshotsToKeep()); - Assertions.assertEquals(153395237, response.iterator().next().hourlySchedule().minute()); - Assertions.assertEquals(6222106413777972482L, response.iterator().next().hourlySchedule().usedBytes()); - Assertions.assertEquals(827241082, response.iterator().next().dailySchedule().snapshotsToKeep()); - Assertions.assertEquals(140983404, response.iterator().next().dailySchedule().hour()); - Assertions.assertEquals(466668490, response.iterator().next().dailySchedule().minute()); - Assertions.assertEquals(6482628412909459959L, response.iterator().next().dailySchedule().usedBytes()); - Assertions.assertEquals(744984595, response.iterator().next().weeklySchedule().snapshotsToKeep()); - Assertions.assertEquals("kimrt", response.iterator().next().weeklySchedule().day()); - Assertions.assertEquals(2101404470, response.iterator().next().weeklySchedule().hour()); - Assertions.assertEquals(2017974836, response.iterator().next().weeklySchedule().minute()); - Assertions.assertEquals(5182793984668664248L, response.iterator().next().weeklySchedule().usedBytes()); - Assertions.assertEquals(1426347910, response.iterator().next().monthlySchedule().snapshotsToKeep()); - Assertions.assertEquals("qepqwhixmon", response.iterator().next().monthlySchedule().daysOfMonth()); - Assertions.assertEquals(927727255, response.iterator().next().monthlySchedule().hour()); - Assertions.assertEquals(171287650, response.iterator().next().monthlySchedule().minute()); - Assertions.assertEquals(9072157943517962123L, response.iterator().next().monthlySchedule().usedBytes()); - Assertions.assertEquals(true, response.iterator().next().enabled()); + Assertions.assertEquals("exfdeqvhpsylk", response.iterator().next().location()); + Assertions.assertEquals("kbffmbmx", response.iterator().next().tags().get("jrgywwpgjxsn")); + Assertions.assertEquals(1310458507, response.iterator().next().hourlySchedule().snapshotsToKeep()); + Assertions.assertEquals(416565759, response.iterator().next().hourlySchedule().minute()); + Assertions.assertEquals(363191384797208698L, response.iterator().next().hourlySchedule().usedBytes()); + Assertions.assertEquals(362710224, response.iterator().next().dailySchedule().snapshotsToKeep()); + Assertions.assertEquals(2027194811, response.iterator().next().dailySchedule().hour()); + Assertions.assertEquals(1192657678, response.iterator().next().dailySchedule().minute()); + Assertions.assertEquals(8283915751167918851L, response.iterator().next().dailySchedule().usedBytes()); + Assertions.assertEquals(691935711, response.iterator().next().weeklySchedule().snapshotsToKeep()); + Assertions.assertEquals("zelfwyfwl", response.iterator().next().weeklySchedule().day()); + Assertions.assertEquals(953163194, response.iterator().next().weeklySchedule().hour()); + Assertions.assertEquals(139746588, response.iterator().next().weeklySchedule().minute()); + Assertions.assertEquals(979869830822712459L, response.iterator().next().weeklySchedule().usedBytes()); + Assertions.assertEquals(1420965357, response.iterator().next().monthlySchedule().snapshotsToKeep()); + Assertions.assertEquals("lafzvaylptr", response.iterator().next().monthlySchedule().daysOfMonth()); + Assertions.assertEquals(294199057, response.iterator().next().monthlySchedule().hour()); + Assertions.assertEquals(1346932281, response.iterator().next().monthlySchedule().minute()); + Assertions.assertEquals(3411367963754147437L, response.iterator().next().monthlySchedule().usedBytes()); + Assertions.assertEquals(false, response.iterator().next().enabled()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesListTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesListTests.java index ef5bed6406bf..1a5b7aea5847 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesListTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPoliciesListTests.java @@ -20,73 +20,93 @@ public final class SnapshotPoliciesListTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { SnapshotPoliciesList model = BinaryData.fromString( - "{\"value\":[{\"etag\":\"beyvpnqicvinvkjj\",\"properties\":{\"hourlySchedule\":{\"snapshotsToKeep\":1970800751,\"minute\":1127292795,\"usedBytes\":8804003083177191933},\"dailySchedule\":{\"snapshotsToKeep\":1482696459,\"hour\":553106392,\"minute\":1827391658,\"usedBytes\":1979647328600963385},\"weeklySchedule\":{\"snapshotsToKeep\":1363862891,\"day\":\"pofncck\",\"hour\":335733577,\"minute\":2123947982,\"usedBytes\":3042520873756069098},\"monthlySchedule\":{\"snapshotsToKeep\":1513228319,\"daysOfMonth\":\"qa\",\"hour\":804013471,\"minute\":1280631673,\"usedBytes\":2612817560508512911},\"enabled\":true,\"provisioningState\":\"o\"},\"location\":\"or\",\"tags\":{\"sdbnwdcfhucqdpf\":\"tolmncwsobqw\"},\"id\":\"vglsbjjca\",\"name\":\"vxb\",\"type\":\"t\"}]}") + "{\"value\":[{\"etag\":\"yvayffimrzr\",\"properties\":{\"hourlySchedule\":{\"snapshotsToKeep\":641301519,\"minute\":1575788840,\"usedBytes\":2600368177720718932},\"dailySchedule\":{\"snapshotsToKeep\":2124595132,\"hour\":779817958,\"minute\":2105512839,\"usedBytes\":8870331151727110664},\"weeklySchedule\":{\"snapshotsToKeep\":473497877,\"day\":\"yyceuzsoi\",\"hour\":414197490,\"minute\":862946119,\"usedBytes\":2021331363267121666},\"monthlySchedule\":{\"snapshotsToKeep\":1839855586,\"daysOfMonth\":\"zvaytdwkqbr\",\"hour\":1725477484,\"minute\":749295202,\"usedBytes\":134576264669262403},\"enabled\":true,\"provisioningState\":\"livpdt\"},\"location\":\"r\",\"tags\":{\"uyfxrxxleptramxj\":\"qoaxoruzfgs\"},\"id\":\"zwl\",\"name\":\"nwxuqlcvydyp\",\"type\":\"tdooaoj\"},{\"etag\":\"iodkooebwnujhem\",\"properties\":{\"hourlySchedule\":{\"snapshotsToKeep\":191965310,\"minute\":640428654,\"usedBytes\":5638108058648089710},\"dailySchedule\":{\"snapshotsToKeep\":1291411043,\"hour\":1997229408,\"minute\":291950475,\"usedBytes\":6410034847924566454},\"weeklySchedule\":{\"snapshotsToKeep\":896449803,\"day\":\"cjvefkdlfo\",\"hour\":1252976241,\"minute\":1706699033,\"usedBytes\":5309095811404897814},\"monthlySchedule\":{\"snapshotsToKeep\":1709159088,\"daysOfMonth\":\"pulpqblylsyxk\",\"hour\":648285682,\"minute\":1830521196,\"usedBytes\":1136404486876218562},\"enabled\":true,\"provisioningState\":\"gxsds\"},\"location\":\"e\",\"tags\":{\"icvi\":\"bzkfzbeyvpn\",\"jjxd\":\"v\"},\"id\":\"rbuukzclewyhmlwp\",\"name\":\"ztzp\",\"type\":\"fn\"}]}") .toObject(SnapshotPoliciesList.class); - Assertions.assertEquals("or", model.value().get(0).location()); - Assertions.assertEquals("tolmncwsobqw", model.value().get(0).tags().get("sdbnwdcfhucqdpf")); - Assertions.assertEquals(1970800751, model.value().get(0).hourlySchedule().snapshotsToKeep()); - Assertions.assertEquals(1127292795, model.value().get(0).hourlySchedule().minute()); - Assertions.assertEquals(8804003083177191933L, model.value().get(0).hourlySchedule().usedBytes()); - Assertions.assertEquals(1482696459, model.value().get(0).dailySchedule().snapshotsToKeep()); - Assertions.assertEquals(553106392, model.value().get(0).dailySchedule().hour()); - Assertions.assertEquals(1827391658, model.value().get(0).dailySchedule().minute()); - Assertions.assertEquals(1979647328600963385L, model.value().get(0).dailySchedule().usedBytes()); - Assertions.assertEquals(1363862891, model.value().get(0).weeklySchedule().snapshotsToKeep()); - Assertions.assertEquals("pofncck", model.value().get(0).weeklySchedule().day()); - Assertions.assertEquals(335733577, model.value().get(0).weeklySchedule().hour()); - Assertions.assertEquals(2123947982, model.value().get(0).weeklySchedule().minute()); - Assertions.assertEquals(3042520873756069098L, model.value().get(0).weeklySchedule().usedBytes()); - Assertions.assertEquals(1513228319, model.value().get(0).monthlySchedule().snapshotsToKeep()); - Assertions.assertEquals("qa", model.value().get(0).monthlySchedule().daysOfMonth()); - Assertions.assertEquals(804013471, model.value().get(0).monthlySchedule().hour()); - Assertions.assertEquals(1280631673, model.value().get(0).monthlySchedule().minute()); - Assertions.assertEquals(2612817560508512911L, model.value().get(0).monthlySchedule().usedBytes()); + Assertions.assertEquals("r", model.value().get(0).location()); + Assertions.assertEquals("qoaxoruzfgs", model.value().get(0).tags().get("uyfxrxxleptramxj")); + Assertions.assertEquals(641301519, model.value().get(0).hourlySchedule().snapshotsToKeep()); + Assertions.assertEquals(1575788840, model.value().get(0).hourlySchedule().minute()); + Assertions.assertEquals(2600368177720718932L, model.value().get(0).hourlySchedule().usedBytes()); + Assertions.assertEquals(2124595132, model.value().get(0).dailySchedule().snapshotsToKeep()); + Assertions.assertEquals(779817958, model.value().get(0).dailySchedule().hour()); + Assertions.assertEquals(2105512839, model.value().get(0).dailySchedule().minute()); + Assertions.assertEquals(8870331151727110664L, model.value().get(0).dailySchedule().usedBytes()); + Assertions.assertEquals(473497877, model.value().get(0).weeklySchedule().snapshotsToKeep()); + Assertions.assertEquals("yyceuzsoi", model.value().get(0).weeklySchedule().day()); + Assertions.assertEquals(414197490, model.value().get(0).weeklySchedule().hour()); + Assertions.assertEquals(862946119, model.value().get(0).weeklySchedule().minute()); + Assertions.assertEquals(2021331363267121666L, model.value().get(0).weeklySchedule().usedBytes()); + Assertions.assertEquals(1839855586, model.value().get(0).monthlySchedule().snapshotsToKeep()); + Assertions.assertEquals("zvaytdwkqbr", model.value().get(0).monthlySchedule().daysOfMonth()); + Assertions.assertEquals(1725477484, model.value().get(0).monthlySchedule().hour()); + Assertions.assertEquals(749295202, model.value().get(0).monthlySchedule().minute()); + Assertions.assertEquals(134576264669262403L, model.value().get(0).monthlySchedule().usedBytes()); Assertions.assertEquals(true, model.value().get(0).enabled()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - SnapshotPoliciesList model - = new SnapshotPoliciesList().withValue(Arrays.asList(new SnapshotPolicyInner().withLocation("or") - .withTags(mapOf("sdbnwdcfhucqdpf", "tolmncwsobqw")) - .withHourlySchedule(new HourlySchedule().withSnapshotsToKeep(1970800751) - .withMinute(1127292795) - .withUsedBytes(8804003083177191933L)) - .withDailySchedule(new DailySchedule().withSnapshotsToKeep(1482696459) - .withHour(553106392) - .withMinute(1827391658) - .withUsedBytes(1979647328600963385L)) - .withWeeklySchedule(new WeeklySchedule().withSnapshotsToKeep(1363862891) - .withDay("pofncck") - .withHour(335733577) - .withMinute(2123947982) - .withUsedBytes(3042520873756069098L)) - .withMonthlySchedule(new MonthlySchedule().withSnapshotsToKeep(1513228319) - .withDaysOfMonth("qa") - .withHour(804013471) - .withMinute(1280631673) - .withUsedBytes(2612817560508512911L)) + SnapshotPoliciesList model = new SnapshotPoliciesList().withValue(Arrays.asList( + new SnapshotPolicyInner().withLocation("r") + .withTags(mapOf("uyfxrxxleptramxj", "qoaxoruzfgs")) + .withHourlySchedule(new HourlySchedule().withSnapshotsToKeep(641301519) + .withMinute(1575788840) + .withUsedBytes(2600368177720718932L)) + .withDailySchedule(new DailySchedule().withSnapshotsToKeep(2124595132) + .withHour(779817958) + .withMinute(2105512839) + .withUsedBytes(8870331151727110664L)) + .withWeeklySchedule(new WeeklySchedule().withSnapshotsToKeep(473497877) + .withDay("yyceuzsoi") + .withHour(414197490) + .withMinute(862946119) + .withUsedBytes(2021331363267121666L)) + .withMonthlySchedule(new MonthlySchedule().withSnapshotsToKeep(1839855586) + .withDaysOfMonth("zvaytdwkqbr") + .withHour(1725477484) + .withMinute(749295202) + .withUsedBytes(134576264669262403L)) + .withEnabled(true), + new SnapshotPolicyInner().withLocation("e") + .withTags(mapOf("icvi", "bzkfzbeyvpn", "jjxd", "v")) + .withHourlySchedule(new HourlySchedule().withSnapshotsToKeep(191965310) + .withMinute(640428654) + .withUsedBytes(5638108058648089710L)) + .withDailySchedule(new DailySchedule().withSnapshotsToKeep(1291411043) + .withHour(1997229408) + .withMinute(291950475) + .withUsedBytes(6410034847924566454L)) + .withWeeklySchedule(new WeeklySchedule().withSnapshotsToKeep(896449803) + .withDay("cjvefkdlfo") + .withHour(1252976241) + .withMinute(1706699033) + .withUsedBytes(5309095811404897814L)) + .withMonthlySchedule(new MonthlySchedule().withSnapshotsToKeep(1709159088) + .withDaysOfMonth("pulpqblylsyxk") + .withHour(648285682) + .withMinute(1830521196) + .withUsedBytes(1136404486876218562L)) .withEnabled(true))); model = BinaryData.fromObject(model).toObject(SnapshotPoliciesList.class); - Assertions.assertEquals("or", model.value().get(0).location()); - Assertions.assertEquals("tolmncwsobqw", model.value().get(0).tags().get("sdbnwdcfhucqdpf")); - Assertions.assertEquals(1970800751, model.value().get(0).hourlySchedule().snapshotsToKeep()); - Assertions.assertEquals(1127292795, model.value().get(0).hourlySchedule().minute()); - Assertions.assertEquals(8804003083177191933L, model.value().get(0).hourlySchedule().usedBytes()); - Assertions.assertEquals(1482696459, model.value().get(0).dailySchedule().snapshotsToKeep()); - Assertions.assertEquals(553106392, model.value().get(0).dailySchedule().hour()); - Assertions.assertEquals(1827391658, model.value().get(0).dailySchedule().minute()); - Assertions.assertEquals(1979647328600963385L, model.value().get(0).dailySchedule().usedBytes()); - Assertions.assertEquals(1363862891, model.value().get(0).weeklySchedule().snapshotsToKeep()); - Assertions.assertEquals("pofncck", model.value().get(0).weeklySchedule().day()); - Assertions.assertEquals(335733577, model.value().get(0).weeklySchedule().hour()); - Assertions.assertEquals(2123947982, model.value().get(0).weeklySchedule().minute()); - Assertions.assertEquals(3042520873756069098L, model.value().get(0).weeklySchedule().usedBytes()); - Assertions.assertEquals(1513228319, model.value().get(0).monthlySchedule().snapshotsToKeep()); - Assertions.assertEquals("qa", model.value().get(0).monthlySchedule().daysOfMonth()); - Assertions.assertEquals(804013471, model.value().get(0).monthlySchedule().hour()); - Assertions.assertEquals(1280631673, model.value().get(0).monthlySchedule().minute()); - Assertions.assertEquals(2612817560508512911L, model.value().get(0).monthlySchedule().usedBytes()); + Assertions.assertEquals("r", model.value().get(0).location()); + Assertions.assertEquals("qoaxoruzfgs", model.value().get(0).tags().get("uyfxrxxleptramxj")); + Assertions.assertEquals(641301519, model.value().get(0).hourlySchedule().snapshotsToKeep()); + Assertions.assertEquals(1575788840, model.value().get(0).hourlySchedule().minute()); + Assertions.assertEquals(2600368177720718932L, model.value().get(0).hourlySchedule().usedBytes()); + Assertions.assertEquals(2124595132, model.value().get(0).dailySchedule().snapshotsToKeep()); + Assertions.assertEquals(779817958, model.value().get(0).dailySchedule().hour()); + Assertions.assertEquals(2105512839, model.value().get(0).dailySchedule().minute()); + Assertions.assertEquals(8870331151727110664L, model.value().get(0).dailySchedule().usedBytes()); + Assertions.assertEquals(473497877, model.value().get(0).weeklySchedule().snapshotsToKeep()); + Assertions.assertEquals("yyceuzsoi", model.value().get(0).weeklySchedule().day()); + Assertions.assertEquals(414197490, model.value().get(0).weeklySchedule().hour()); + Assertions.assertEquals(862946119, model.value().get(0).weeklySchedule().minute()); + Assertions.assertEquals(2021331363267121666L, model.value().get(0).weeklySchedule().usedBytes()); + Assertions.assertEquals(1839855586, model.value().get(0).monthlySchedule().snapshotsToKeep()); + Assertions.assertEquals("zvaytdwkqbr", model.value().get(0).monthlySchedule().daysOfMonth()); + Assertions.assertEquals(1725477484, model.value().get(0).monthlySchedule().hour()); + Assertions.assertEquals(749295202, model.value().get(0).monthlySchedule().minute()); + Assertions.assertEquals(134576264669262403L, model.value().get(0).monthlySchedule().usedBytes()); Assertions.assertEquals(true, model.value().get(0).enabled()); } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPolicyInnerTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPolicyInnerTests.java index 8dde4512472e..c35a17f75c7d 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPolicyInnerTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPolicyInnerTests.java @@ -18,72 +18,73 @@ public final class SnapshotPolicyInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { SnapshotPolicyInner model = BinaryData.fromString( - "{\"etag\":\"dut\",\"properties\":{\"hourlySchedule\":{\"snapshotsToKeep\":574519404,\"minute\":175295404,\"usedBytes\":8357004354243931890},\"dailySchedule\":{\"snapshotsToKeep\":1229712399,\"hour\":754766432,\"minute\":1395198209,\"usedBytes\":5859921089947739287},\"weeklySchedule\":{\"snapshotsToKeep\":585875953,\"day\":\"bgdknnqv\",\"hour\":1989846717,\"minute\":2039923498,\"usedBytes\":3284262391210683675},\"monthlySchedule\":{\"snapshotsToKeep\":577659304,\"daysOfMonth\":\"gsahmkycgrauw\",\"hour\":1509662637,\"minute\":391026651,\"usedBytes\":6617635569838446210},\"enabled\":false,\"provisioningState\":\"dmovsm\"},\"location\":\"xwabmqoe\",\"tags\":{\"mqlgk\":\"frvtpuqu\",\"ongbjcnt\":\"btndo\"},\"id\":\"jitcjedftwwaez\",\"name\":\"ojvdcpzfoqo\",\"type\":\"i\"}") + "{\"etag\":\"kwyfzqwhxxbuyqax\",\"properties\":{\"hourlySchedule\":{\"snapshotsToKeep\":1280631673,\"minute\":608343994,\"usedBytes\":5894027165628852811},\"dailySchedule\":{\"snapshotsToKeep\":1872827948,\"hour\":411799174,\"minute\":110839155,\"usedBytes\":1269488169933236475},\"weeklySchedule\":{\"snapshotsToKeep\":1325987050,\"day\":\"cwsobqwcs\",\"hour\":1806206586,\"minute\":358085488,\"usedBytes\":1296933680465064139},\"monthlySchedule\":{\"snapshotsToKeep\":1589501712,\"daysOfMonth\":\"pfuvglsbjjca\",\"hour\":1995846414,\"minute\":1075232734,\"usedBytes\":652867049720214090},\"enabled\":false,\"provisioningState\":\"ncormrlxqtvcof\"},\"location\":\"f\",\"tags\":{\"bgdknnqv\":\"gj\",\"sgsahmkycgr\":\"aznqntoru\",\"s\":\"uwjuetaeburuvdmo\",\"tpuqujmq\":\"zlxwabmqoefkifr\"},\"id\":\"gkfbtndoaong\",\"name\":\"jcntuj\",\"type\":\"tcje\"}") .toObject(SnapshotPolicyInner.class); - Assertions.assertEquals("xwabmqoe", model.location()); - Assertions.assertEquals("frvtpuqu", model.tags().get("mqlgk")); - Assertions.assertEquals(574519404, model.hourlySchedule().snapshotsToKeep()); - Assertions.assertEquals(175295404, model.hourlySchedule().minute()); - Assertions.assertEquals(8357004354243931890L, model.hourlySchedule().usedBytes()); - Assertions.assertEquals(1229712399, model.dailySchedule().snapshotsToKeep()); - Assertions.assertEquals(754766432, model.dailySchedule().hour()); - Assertions.assertEquals(1395198209, model.dailySchedule().minute()); - Assertions.assertEquals(5859921089947739287L, model.dailySchedule().usedBytes()); - Assertions.assertEquals(585875953, model.weeklySchedule().snapshotsToKeep()); - Assertions.assertEquals("bgdknnqv", model.weeklySchedule().day()); - Assertions.assertEquals(1989846717, model.weeklySchedule().hour()); - Assertions.assertEquals(2039923498, model.weeklySchedule().minute()); - Assertions.assertEquals(3284262391210683675L, model.weeklySchedule().usedBytes()); - Assertions.assertEquals(577659304, model.monthlySchedule().snapshotsToKeep()); - Assertions.assertEquals("gsahmkycgrauw", model.monthlySchedule().daysOfMonth()); - Assertions.assertEquals(1509662637, model.monthlySchedule().hour()); - Assertions.assertEquals(391026651, model.monthlySchedule().minute()); - Assertions.assertEquals(6617635569838446210L, model.monthlySchedule().usedBytes()); + Assertions.assertEquals("f", model.location()); + Assertions.assertEquals("gj", model.tags().get("bgdknnqv")); + Assertions.assertEquals(1280631673, model.hourlySchedule().snapshotsToKeep()); + Assertions.assertEquals(608343994, model.hourlySchedule().minute()); + Assertions.assertEquals(5894027165628852811L, model.hourlySchedule().usedBytes()); + Assertions.assertEquals(1872827948, model.dailySchedule().snapshotsToKeep()); + Assertions.assertEquals(411799174, model.dailySchedule().hour()); + Assertions.assertEquals(110839155, model.dailySchedule().minute()); + Assertions.assertEquals(1269488169933236475L, model.dailySchedule().usedBytes()); + Assertions.assertEquals(1325987050, model.weeklySchedule().snapshotsToKeep()); + Assertions.assertEquals("cwsobqwcs", model.weeklySchedule().day()); + Assertions.assertEquals(1806206586, model.weeklySchedule().hour()); + Assertions.assertEquals(358085488, model.weeklySchedule().minute()); + Assertions.assertEquals(1296933680465064139L, model.weeklySchedule().usedBytes()); + Assertions.assertEquals(1589501712, model.monthlySchedule().snapshotsToKeep()); + Assertions.assertEquals("pfuvglsbjjca", model.monthlySchedule().daysOfMonth()); + Assertions.assertEquals(1995846414, model.monthlySchedule().hour()); + Assertions.assertEquals(1075232734, model.monthlySchedule().minute()); + Assertions.assertEquals(652867049720214090L, model.monthlySchedule().usedBytes()); Assertions.assertEquals(false, model.enabled()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - SnapshotPolicyInner model = new SnapshotPolicyInner().withLocation("xwabmqoe") - .withTags(mapOf("mqlgk", "frvtpuqu", "ongbjcnt", "btndo")) - .withHourlySchedule(new HourlySchedule().withSnapshotsToKeep(574519404) - .withMinute(175295404) - .withUsedBytes(8357004354243931890L)) - .withDailySchedule(new DailySchedule().withSnapshotsToKeep(1229712399) - .withHour(754766432) - .withMinute(1395198209) - .withUsedBytes(5859921089947739287L)) - .withWeeklySchedule(new WeeklySchedule().withSnapshotsToKeep(585875953) - .withDay("bgdknnqv") - .withHour(1989846717) - .withMinute(2039923498) - .withUsedBytes(3284262391210683675L)) - .withMonthlySchedule(new MonthlySchedule().withSnapshotsToKeep(577659304) - .withDaysOfMonth("gsahmkycgrauw") - .withHour(1509662637) - .withMinute(391026651) - .withUsedBytes(6617635569838446210L)) + SnapshotPolicyInner model = new SnapshotPolicyInner().withLocation("f") + .withTags(mapOf("bgdknnqv", "gj", "sgsahmkycgr", "aznqntoru", "s", "uwjuetaeburuvdmo", "tpuqujmq", + "zlxwabmqoefkifr")) + .withHourlySchedule(new HourlySchedule().withSnapshotsToKeep(1280631673) + .withMinute(608343994) + .withUsedBytes(5894027165628852811L)) + .withDailySchedule(new DailySchedule().withSnapshotsToKeep(1872827948) + .withHour(411799174) + .withMinute(110839155) + .withUsedBytes(1269488169933236475L)) + .withWeeklySchedule(new WeeklySchedule().withSnapshotsToKeep(1325987050) + .withDay("cwsobqwcs") + .withHour(1806206586) + .withMinute(358085488) + .withUsedBytes(1296933680465064139L)) + .withMonthlySchedule(new MonthlySchedule().withSnapshotsToKeep(1589501712) + .withDaysOfMonth("pfuvglsbjjca") + .withHour(1995846414) + .withMinute(1075232734) + .withUsedBytes(652867049720214090L)) .withEnabled(false); model = BinaryData.fromObject(model).toObject(SnapshotPolicyInner.class); - Assertions.assertEquals("xwabmqoe", model.location()); - Assertions.assertEquals("frvtpuqu", model.tags().get("mqlgk")); - Assertions.assertEquals(574519404, model.hourlySchedule().snapshotsToKeep()); - Assertions.assertEquals(175295404, model.hourlySchedule().minute()); - Assertions.assertEquals(8357004354243931890L, model.hourlySchedule().usedBytes()); - Assertions.assertEquals(1229712399, model.dailySchedule().snapshotsToKeep()); - Assertions.assertEquals(754766432, model.dailySchedule().hour()); - Assertions.assertEquals(1395198209, model.dailySchedule().minute()); - Assertions.assertEquals(5859921089947739287L, model.dailySchedule().usedBytes()); - Assertions.assertEquals(585875953, model.weeklySchedule().snapshotsToKeep()); - Assertions.assertEquals("bgdknnqv", model.weeklySchedule().day()); - Assertions.assertEquals(1989846717, model.weeklySchedule().hour()); - Assertions.assertEquals(2039923498, model.weeklySchedule().minute()); - Assertions.assertEquals(3284262391210683675L, model.weeklySchedule().usedBytes()); - Assertions.assertEquals(577659304, model.monthlySchedule().snapshotsToKeep()); - Assertions.assertEquals("gsahmkycgrauw", model.monthlySchedule().daysOfMonth()); - Assertions.assertEquals(1509662637, model.monthlySchedule().hour()); - Assertions.assertEquals(391026651, model.monthlySchedule().minute()); - Assertions.assertEquals(6617635569838446210L, model.monthlySchedule().usedBytes()); + Assertions.assertEquals("f", model.location()); + Assertions.assertEquals("gj", model.tags().get("bgdknnqv")); + Assertions.assertEquals(1280631673, model.hourlySchedule().snapshotsToKeep()); + Assertions.assertEquals(608343994, model.hourlySchedule().minute()); + Assertions.assertEquals(5894027165628852811L, model.hourlySchedule().usedBytes()); + Assertions.assertEquals(1872827948, model.dailySchedule().snapshotsToKeep()); + Assertions.assertEquals(411799174, model.dailySchedule().hour()); + Assertions.assertEquals(110839155, model.dailySchedule().minute()); + Assertions.assertEquals(1269488169933236475L, model.dailySchedule().usedBytes()); + Assertions.assertEquals(1325987050, model.weeklySchedule().snapshotsToKeep()); + Assertions.assertEquals("cwsobqwcs", model.weeklySchedule().day()); + Assertions.assertEquals(1806206586, model.weeklySchedule().hour()); + Assertions.assertEquals(358085488, model.weeklySchedule().minute()); + Assertions.assertEquals(1296933680465064139L, model.weeklySchedule().usedBytes()); + Assertions.assertEquals(1589501712, model.monthlySchedule().snapshotsToKeep()); + Assertions.assertEquals("pfuvglsbjjca", model.monthlySchedule().daysOfMonth()); + Assertions.assertEquals(1995846414, model.monthlySchedule().hour()); + Assertions.assertEquals(1075232734, model.monthlySchedule().minute()); + Assertions.assertEquals(652867049720214090L, model.monthlySchedule().usedBytes()); Assertions.assertEquals(false, model.enabled()); } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPolicyPatchTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPolicyPatchTests.java index 1f9b74126dc3..962509556dc8 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPolicyPatchTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPolicyPatchTests.java @@ -18,72 +18,72 @@ public final class SnapshotPolicyPatchTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { SnapshotPolicyPatch model = BinaryData.fromString( - "{\"location\":\"r\",\"id\":\"dsnfdsdoakgtdl\",\"name\":\"kzevdlhewpusds\",\"type\":\"wvogvbbejdc\",\"tags\":{\"ufgmjzrwrdg\":\"qmoa\",\"bminrfdwoyuhhzi\":\"twaenuuzko\"},\"properties\":{\"hourlySchedule\":{\"snapshotsToKeep\":1032750510,\"minute\":1209152959,\"usedBytes\":6074773218082221902},\"dailySchedule\":{\"snapshotsToKeep\":9753041,\"hour\":1101350352,\"minute\":1130868680,\"usedBytes\":1203862565285552699},\"weeklySchedule\":{\"snapshotsToKeep\":466480272,\"day\":\"qu\",\"hour\":674060065,\"minute\":1894418598,\"usedBytes\":4284376679308974213},\"monthlySchedule\":{\"snapshotsToKeep\":326357229,\"daysOfMonth\":\"z\",\"hour\":1413149705,\"minute\":2064945633,\"usedBytes\":4209147679224285340},\"enabled\":true,\"provisioningState\":\"hc\"}}") + "{\"location\":\"uximerqfobw\",\"id\":\"nkbykutwpfhp\",\"name\":\"m\",\"type\":\"skdsnfdsdoakg\",\"tags\":{\"pusdstt\":\"mkkzevdlhe\"},\"properties\":{\"hourlySchedule\":{\"snapshotsToKeep\":221713689,\"minute\":1374887959,\"usedBytes\":8961912277389186223},\"dailySchedule\":{\"snapshotsToKeep\":764265895,\"hour\":963593520,\"minute\":1707404477,\"usedBytes\":6280653773540023560},\"weeklySchedule\":{\"snapshotsToKeep\":127978460,\"day\":\"zr\",\"hour\":1964426059,\"minute\":632499232,\"usedBytes\":3176004789206636237},\"monthlySchedule\":{\"snapshotsToKeep\":130436359,\"daysOfMonth\":\"zkopb\",\"hour\":1224978784,\"minute\":2010767026,\"usedBytes\":3596766973567409685},\"enabled\":true,\"provisioningState\":\"hziuiefozbhdms\"}}") .toObject(SnapshotPolicyPatch.class); - Assertions.assertEquals("r", model.location()); - Assertions.assertEquals("qmoa", model.tags().get("ufgmjzrwrdg")); - Assertions.assertEquals(1032750510, model.hourlySchedule().snapshotsToKeep()); - Assertions.assertEquals(1209152959, model.hourlySchedule().minute()); - Assertions.assertEquals(6074773218082221902L, model.hourlySchedule().usedBytes()); - Assertions.assertEquals(9753041, model.dailySchedule().snapshotsToKeep()); - Assertions.assertEquals(1101350352, model.dailySchedule().hour()); - Assertions.assertEquals(1130868680, model.dailySchedule().minute()); - Assertions.assertEquals(1203862565285552699L, model.dailySchedule().usedBytes()); - Assertions.assertEquals(466480272, model.weeklySchedule().snapshotsToKeep()); - Assertions.assertEquals("qu", model.weeklySchedule().day()); - Assertions.assertEquals(674060065, model.weeklySchedule().hour()); - Assertions.assertEquals(1894418598, model.weeklySchedule().minute()); - Assertions.assertEquals(4284376679308974213L, model.weeklySchedule().usedBytes()); - Assertions.assertEquals(326357229, model.monthlySchedule().snapshotsToKeep()); - Assertions.assertEquals("z", model.monthlySchedule().daysOfMonth()); - Assertions.assertEquals(1413149705, model.monthlySchedule().hour()); - Assertions.assertEquals(2064945633, model.monthlySchedule().minute()); - Assertions.assertEquals(4209147679224285340L, model.monthlySchedule().usedBytes()); + Assertions.assertEquals("uximerqfobw", model.location()); + Assertions.assertEquals("mkkzevdlhe", model.tags().get("pusdstt")); + Assertions.assertEquals(221713689, model.hourlySchedule().snapshotsToKeep()); + Assertions.assertEquals(1374887959, model.hourlySchedule().minute()); + Assertions.assertEquals(8961912277389186223L, model.hourlySchedule().usedBytes()); + Assertions.assertEquals(764265895, model.dailySchedule().snapshotsToKeep()); + Assertions.assertEquals(963593520, model.dailySchedule().hour()); + Assertions.assertEquals(1707404477, model.dailySchedule().minute()); + Assertions.assertEquals(6280653773540023560L, model.dailySchedule().usedBytes()); + Assertions.assertEquals(127978460, model.weeklySchedule().snapshotsToKeep()); + Assertions.assertEquals("zr", model.weeklySchedule().day()); + Assertions.assertEquals(1964426059, model.weeklySchedule().hour()); + Assertions.assertEquals(632499232, model.weeklySchedule().minute()); + Assertions.assertEquals(3176004789206636237L, model.weeklySchedule().usedBytes()); + Assertions.assertEquals(130436359, model.monthlySchedule().snapshotsToKeep()); + Assertions.assertEquals("zkopb", model.monthlySchedule().daysOfMonth()); + Assertions.assertEquals(1224978784, model.monthlySchedule().hour()); + Assertions.assertEquals(2010767026, model.monthlySchedule().minute()); + Assertions.assertEquals(3596766973567409685L, model.monthlySchedule().usedBytes()); Assertions.assertEquals(true, model.enabled()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - SnapshotPolicyPatch model = new SnapshotPolicyPatch().withLocation("r") - .withTags(mapOf("ufgmjzrwrdg", "qmoa", "bminrfdwoyuhhzi", "twaenuuzko")) - .withHourlySchedule(new HourlySchedule().withSnapshotsToKeep(1032750510) - .withMinute(1209152959) - .withUsedBytes(6074773218082221902L)) - .withDailySchedule(new DailySchedule().withSnapshotsToKeep(9753041) - .withHour(1101350352) - .withMinute(1130868680) - .withUsedBytes(1203862565285552699L)) - .withWeeklySchedule(new WeeklySchedule().withSnapshotsToKeep(466480272) - .withDay("qu") - .withHour(674060065) - .withMinute(1894418598) - .withUsedBytes(4284376679308974213L)) - .withMonthlySchedule(new MonthlySchedule().withSnapshotsToKeep(326357229) - .withDaysOfMonth("z") - .withHour(1413149705) - .withMinute(2064945633) - .withUsedBytes(4209147679224285340L)) + SnapshotPolicyPatch model = new SnapshotPolicyPatch().withLocation("uximerqfobw") + .withTags(mapOf("pusdstt", "mkkzevdlhe")) + .withHourlySchedule(new HourlySchedule().withSnapshotsToKeep(221713689) + .withMinute(1374887959) + .withUsedBytes(8961912277389186223L)) + .withDailySchedule(new DailySchedule().withSnapshotsToKeep(764265895) + .withHour(963593520) + .withMinute(1707404477) + .withUsedBytes(6280653773540023560L)) + .withWeeklySchedule(new WeeklySchedule().withSnapshotsToKeep(127978460) + .withDay("zr") + .withHour(1964426059) + .withMinute(632499232) + .withUsedBytes(3176004789206636237L)) + .withMonthlySchedule(new MonthlySchedule().withSnapshotsToKeep(130436359) + .withDaysOfMonth("zkopb") + .withHour(1224978784) + .withMinute(2010767026) + .withUsedBytes(3596766973567409685L)) .withEnabled(true); model = BinaryData.fromObject(model).toObject(SnapshotPolicyPatch.class); - Assertions.assertEquals("r", model.location()); - Assertions.assertEquals("qmoa", model.tags().get("ufgmjzrwrdg")); - Assertions.assertEquals(1032750510, model.hourlySchedule().snapshotsToKeep()); - Assertions.assertEquals(1209152959, model.hourlySchedule().minute()); - Assertions.assertEquals(6074773218082221902L, model.hourlySchedule().usedBytes()); - Assertions.assertEquals(9753041, model.dailySchedule().snapshotsToKeep()); - Assertions.assertEquals(1101350352, model.dailySchedule().hour()); - Assertions.assertEquals(1130868680, model.dailySchedule().minute()); - Assertions.assertEquals(1203862565285552699L, model.dailySchedule().usedBytes()); - Assertions.assertEquals(466480272, model.weeklySchedule().snapshotsToKeep()); - Assertions.assertEquals("qu", model.weeklySchedule().day()); - Assertions.assertEquals(674060065, model.weeklySchedule().hour()); - Assertions.assertEquals(1894418598, model.weeklySchedule().minute()); - Assertions.assertEquals(4284376679308974213L, model.weeklySchedule().usedBytes()); - Assertions.assertEquals(326357229, model.monthlySchedule().snapshotsToKeep()); - Assertions.assertEquals("z", model.monthlySchedule().daysOfMonth()); - Assertions.assertEquals(1413149705, model.monthlySchedule().hour()); - Assertions.assertEquals(2064945633, model.monthlySchedule().minute()); - Assertions.assertEquals(4209147679224285340L, model.monthlySchedule().usedBytes()); + Assertions.assertEquals("uximerqfobw", model.location()); + Assertions.assertEquals("mkkzevdlhe", model.tags().get("pusdstt")); + Assertions.assertEquals(221713689, model.hourlySchedule().snapshotsToKeep()); + Assertions.assertEquals(1374887959, model.hourlySchedule().minute()); + Assertions.assertEquals(8961912277389186223L, model.hourlySchedule().usedBytes()); + Assertions.assertEquals(764265895, model.dailySchedule().snapshotsToKeep()); + Assertions.assertEquals(963593520, model.dailySchedule().hour()); + Assertions.assertEquals(1707404477, model.dailySchedule().minute()); + Assertions.assertEquals(6280653773540023560L, model.dailySchedule().usedBytes()); + Assertions.assertEquals(127978460, model.weeklySchedule().snapshotsToKeep()); + Assertions.assertEquals("zr", model.weeklySchedule().day()); + Assertions.assertEquals(1964426059, model.weeklySchedule().hour()); + Assertions.assertEquals(632499232, model.weeklySchedule().minute()); + Assertions.assertEquals(3176004789206636237L, model.weeklySchedule().usedBytes()); + Assertions.assertEquals(130436359, model.monthlySchedule().snapshotsToKeep()); + Assertions.assertEquals("zkopb", model.monthlySchedule().daysOfMonth()); + Assertions.assertEquals(1224978784, model.monthlySchedule().hour()); + Assertions.assertEquals(2010767026, model.monthlySchedule().minute()); + Assertions.assertEquals(3596766973567409685L, model.monthlySchedule().usedBytes()); Assertions.assertEquals(true, model.enabled()); } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPolicyPropertiesTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPolicyPropertiesTests.java index 24b89f03f48f..70d9df17b65b 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPolicyPropertiesTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPolicyPropertiesTests.java @@ -16,67 +16,67 @@ public final class SnapshotPolicyPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { SnapshotPolicyProperties model = BinaryData.fromString( - "{\"hourlySchedule\":{\"snapshotsToKeep\":1540347463,\"minute\":708336176,\"usedBytes\":6230905056677671460},\"dailySchedule\":{\"snapshotsToKeep\":1453287617,\"hour\":37759464,\"minute\":1319234884,\"usedBytes\":4059865532309630153},\"weeklySchedule\":{\"snapshotsToKeep\":2028743450,\"day\":\"mciodhkhazxkhn\",\"hour\":240189382,\"minute\":1895789611,\"usedBytes\":4122808446567257102},\"monthlySchedule\":{\"snapshotsToKeep\":364905356,\"daysOfMonth\":\"kdwbwhkszz\",\"hour\":2022074677,\"minute\":1970109066,\"usedBytes\":1268636454015112326},\"enabled\":false,\"provisioningState\":\"qgsfraoyzkoow\"}") + "{\"hourlySchedule\":{\"snapshotsToKeep\":659482239,\"minute\":456630661,\"usedBytes\":4579200553418378126},\"dailySchedule\":{\"snapshotsToKeep\":229411798,\"hour\":242462331,\"minute\":1248397235,\"usedBytes\":8938255747572389920},\"weeklySchedule\":{\"snapshotsToKeep\":242787208,\"day\":\"ybxarzgszu\",\"hour\":37759464,\"minute\":1319234884,\"usedBytes\":4059865532309630153},\"monthlySchedule\":{\"snapshotsToKeep\":2028743450,\"daysOfMonth\":\"mciodhkhazxkhn\",\"hour\":240189382,\"minute\":1895789611,\"usedBytes\":4122808446567257102},\"enabled\":true,\"provisioningState\":\"okdwb\"}") .toObject(SnapshotPolicyProperties.class); - Assertions.assertEquals(1540347463, model.hourlySchedule().snapshotsToKeep()); - Assertions.assertEquals(708336176, model.hourlySchedule().minute()); - Assertions.assertEquals(6230905056677671460L, model.hourlySchedule().usedBytes()); - Assertions.assertEquals(1453287617, model.dailySchedule().snapshotsToKeep()); - Assertions.assertEquals(37759464, model.dailySchedule().hour()); - Assertions.assertEquals(1319234884, model.dailySchedule().minute()); - Assertions.assertEquals(4059865532309630153L, model.dailySchedule().usedBytes()); - Assertions.assertEquals(2028743450, model.weeklySchedule().snapshotsToKeep()); - Assertions.assertEquals("mciodhkhazxkhn", model.weeklySchedule().day()); - Assertions.assertEquals(240189382, model.weeklySchedule().hour()); - Assertions.assertEquals(1895789611, model.weeklySchedule().minute()); - Assertions.assertEquals(4122808446567257102L, model.weeklySchedule().usedBytes()); - Assertions.assertEquals(364905356, model.monthlySchedule().snapshotsToKeep()); - Assertions.assertEquals("kdwbwhkszz", model.monthlySchedule().daysOfMonth()); - Assertions.assertEquals(2022074677, model.monthlySchedule().hour()); - Assertions.assertEquals(1970109066, model.monthlySchedule().minute()); - Assertions.assertEquals(1268636454015112326L, model.monthlySchedule().usedBytes()); - Assertions.assertEquals(false, model.enabled()); + Assertions.assertEquals(659482239, model.hourlySchedule().snapshotsToKeep()); + Assertions.assertEquals(456630661, model.hourlySchedule().minute()); + Assertions.assertEquals(4579200553418378126L, model.hourlySchedule().usedBytes()); + Assertions.assertEquals(229411798, model.dailySchedule().snapshotsToKeep()); + Assertions.assertEquals(242462331, model.dailySchedule().hour()); + Assertions.assertEquals(1248397235, model.dailySchedule().minute()); + Assertions.assertEquals(8938255747572389920L, model.dailySchedule().usedBytes()); + Assertions.assertEquals(242787208, model.weeklySchedule().snapshotsToKeep()); + Assertions.assertEquals("ybxarzgszu", model.weeklySchedule().day()); + Assertions.assertEquals(37759464, model.weeklySchedule().hour()); + Assertions.assertEquals(1319234884, model.weeklySchedule().minute()); + Assertions.assertEquals(4059865532309630153L, model.weeklySchedule().usedBytes()); + Assertions.assertEquals(2028743450, model.monthlySchedule().snapshotsToKeep()); + Assertions.assertEquals("mciodhkhazxkhn", model.monthlySchedule().daysOfMonth()); + Assertions.assertEquals(240189382, model.monthlySchedule().hour()); + Assertions.assertEquals(1895789611, model.monthlySchedule().minute()); + Assertions.assertEquals(4122808446567257102L, model.monthlySchedule().usedBytes()); + Assertions.assertEquals(true, model.enabled()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { SnapshotPolicyProperties model = new SnapshotPolicyProperties() - .withHourlySchedule(new HourlySchedule().withSnapshotsToKeep(1540347463) - .withMinute(708336176) - .withUsedBytes(6230905056677671460L)) - .withDailySchedule(new DailySchedule().withSnapshotsToKeep(1453287617) + .withHourlySchedule(new HourlySchedule().withSnapshotsToKeep(659482239) + .withMinute(456630661) + .withUsedBytes(4579200553418378126L)) + .withDailySchedule(new DailySchedule().withSnapshotsToKeep(229411798) + .withHour(242462331) + .withMinute(1248397235) + .withUsedBytes(8938255747572389920L)) + .withWeeklySchedule(new WeeklySchedule().withSnapshotsToKeep(242787208) + .withDay("ybxarzgszu") .withHour(37759464) .withMinute(1319234884) .withUsedBytes(4059865532309630153L)) - .withWeeklySchedule(new WeeklySchedule().withSnapshotsToKeep(2028743450) - .withDay("mciodhkhazxkhn") + .withMonthlySchedule(new MonthlySchedule().withSnapshotsToKeep(2028743450) + .withDaysOfMonth("mciodhkhazxkhn") .withHour(240189382) .withMinute(1895789611) .withUsedBytes(4122808446567257102L)) - .withMonthlySchedule(new MonthlySchedule().withSnapshotsToKeep(364905356) - .withDaysOfMonth("kdwbwhkszz") - .withHour(2022074677) - .withMinute(1970109066) - .withUsedBytes(1268636454015112326L)) - .withEnabled(false); + .withEnabled(true); model = BinaryData.fromObject(model).toObject(SnapshotPolicyProperties.class); - Assertions.assertEquals(1540347463, model.hourlySchedule().snapshotsToKeep()); - Assertions.assertEquals(708336176, model.hourlySchedule().minute()); - Assertions.assertEquals(6230905056677671460L, model.hourlySchedule().usedBytes()); - Assertions.assertEquals(1453287617, model.dailySchedule().snapshotsToKeep()); - Assertions.assertEquals(37759464, model.dailySchedule().hour()); - Assertions.assertEquals(1319234884, model.dailySchedule().minute()); - Assertions.assertEquals(4059865532309630153L, model.dailySchedule().usedBytes()); - Assertions.assertEquals(2028743450, model.weeklySchedule().snapshotsToKeep()); - Assertions.assertEquals("mciodhkhazxkhn", model.weeklySchedule().day()); - Assertions.assertEquals(240189382, model.weeklySchedule().hour()); - Assertions.assertEquals(1895789611, model.weeklySchedule().minute()); - Assertions.assertEquals(4122808446567257102L, model.weeklySchedule().usedBytes()); - Assertions.assertEquals(364905356, model.monthlySchedule().snapshotsToKeep()); - Assertions.assertEquals("kdwbwhkszz", model.monthlySchedule().daysOfMonth()); - Assertions.assertEquals(2022074677, model.monthlySchedule().hour()); - Assertions.assertEquals(1970109066, model.monthlySchedule().minute()); - Assertions.assertEquals(1268636454015112326L, model.monthlySchedule().usedBytes()); - Assertions.assertEquals(false, model.enabled()); + Assertions.assertEquals(659482239, model.hourlySchedule().snapshotsToKeep()); + Assertions.assertEquals(456630661, model.hourlySchedule().minute()); + Assertions.assertEquals(4579200553418378126L, model.hourlySchedule().usedBytes()); + Assertions.assertEquals(229411798, model.dailySchedule().snapshotsToKeep()); + Assertions.assertEquals(242462331, model.dailySchedule().hour()); + Assertions.assertEquals(1248397235, model.dailySchedule().minute()); + Assertions.assertEquals(8938255747572389920L, model.dailySchedule().usedBytes()); + Assertions.assertEquals(242787208, model.weeklySchedule().snapshotsToKeep()); + Assertions.assertEquals("ybxarzgszu", model.weeklySchedule().day()); + Assertions.assertEquals(37759464, model.weeklySchedule().hour()); + Assertions.assertEquals(1319234884, model.weeklySchedule().minute()); + Assertions.assertEquals(4059865532309630153L, model.weeklySchedule().usedBytes()); + Assertions.assertEquals(2028743450, model.monthlySchedule().snapshotsToKeep()); + Assertions.assertEquals("mciodhkhazxkhn", model.monthlySchedule().daysOfMonth()); + Assertions.assertEquals(240189382, model.monthlySchedule().hour()); + Assertions.assertEquals(1895789611, model.monthlySchedule().minute()); + Assertions.assertEquals(4122808446567257102L, model.monthlySchedule().usedBytes()); + Assertions.assertEquals(true, model.enabled()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPropertiesTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPropertiesTests.java index 2168bf1e6b56..3b2d9476af20 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPropertiesTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotPropertiesTests.java @@ -10,8 +10,9 @@ public final class SnapshotPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - SnapshotProperties model = BinaryData.fromString( - "{\"snapshotId\":\"ao\",\"created\":\"2021-02-23T21:26:17Z\",\"provisioningState\":\"pqblylsyxkqjnsj\"}") + SnapshotProperties model = BinaryData + .fromString( + "{\"snapshotId\":\"beddgssofw\",\"created\":\"2021-08-12T00:48:32Z\",\"provisioningState\":\"alkrmn\"}") .toObject(SnapshotProperties.class); } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotRestoreFilesTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotRestoreFilesTests.java index 09792b548b02..783aa96346c0 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotRestoreFilesTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotRestoreFilesTests.java @@ -13,18 +13,18 @@ public final class SnapshotRestoreFilesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { SnapshotRestoreFiles model - = BinaryData.fromString("{\"filePaths\":[\"vti\"],\"destinationPath\":\"xsdszuempsb\"}") + = BinaryData.fromString("{\"filePaths\":[\"jpxac\"],\"destinationPath\":\"udfnbyxba\"}") .toObject(SnapshotRestoreFiles.class); - Assertions.assertEquals("vti", model.filePaths().get(0)); - Assertions.assertEquals("xsdszuempsb", model.destinationPath()); + Assertions.assertEquals("jpxac", model.filePaths().get(0)); + Assertions.assertEquals("udfnbyxba", model.destinationPath()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { SnapshotRestoreFiles model - = new SnapshotRestoreFiles().withFilePaths(Arrays.asList("vti")).withDestinationPath("xsdszuempsb"); + = new SnapshotRestoreFiles().withFilePaths(Arrays.asList("jpxac")).withDestinationPath("udfnbyxba"); model = BinaryData.fromObject(model).toObject(SnapshotRestoreFiles.class); - Assertions.assertEquals("vti", model.filePaths().get(0)); - Assertions.assertEquals("xsdszuempsb", model.destinationPath()); + Assertions.assertEquals("jpxac", model.filePaths().get(0)); + Assertions.assertEquals("udfnbyxba", model.destinationPath()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotsDeleteMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotsDeleteMockTests.java index 4018cb54e871..5f0f169695e5 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotsDeleteMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotsDeleteMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import java.nio.charset.StandardCharsets; @@ -25,10 +25,10 @@ public void testDelete() throws Exception { NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); manager.snapshots() - .delete("bmikost", "z", "kiwbuqnyoph", "fy", "sgcrpfbcunezzce", com.azure.core.util.Context.NONE); + .delete("iiqbi", "htmwwinh", "hfqpofv", "bcblemb", "kbwvqvxkdiv", com.azure.core.util.Context.NONE); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotsGetWithResponseMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotsGetWithResponseMockTests.java index 760052b9dbc5..c66229bfa0fb 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotsGetWithResponseMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotsGetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.Snapshot; @@ -21,20 +21,20 @@ public final class SnapshotsGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"location\":\"yqo\",\"properties\":{\"snapshotId\":\"qoxwd\",\"created\":\"2021-07-30T17:53:09Z\",\"provisioningState\":\"xiqxeiiqbimh\"},\"id\":\"wwinhehf\",\"name\":\"pofvwb\",\"type\":\"blembnkbwvqvxkd\"}"; + = "{\"location\":\"ickpz\",\"properties\":{\"snapshotId\":\"opmx\",\"created\":\"2021-03-28T13:12:17Z\",\"provisioningState\":\"clt\"},\"id\":\"edexxmlfm\",\"name\":\"qscazuawxtz\",\"type\":\"puamwabzxr\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); Snapshot response = manager.snapshots() - .getWithResponse("zotqyryuzcb", "qqvxmvwfgtayxons", "peujlzqn", "cvsql", "nzoibgsxgnx", + .getWithResponse("ojphslhc", "wjutifdwfmv", "gorqjbttzh", "aglkafhon", "juj", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("yqo", response.location()); + Assertions.assertEquals("ickpz", response.location()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotsListMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotsListMockTests.java index 9cfba7cab76b..a69945d85df3 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotsListMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotsListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.Snapshot; @@ -22,18 +22,18 @@ public final class SnapshotsListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"location\":\"kqscazuawxtzx\",\"properties\":{\"snapshotId\":\"mwabzxrvxc\",\"created\":\"2021-11-23T17:17:10Z\",\"provisioningState\":\"phai\"},\"id\":\"xyasflvgsgzw\",\"name\":\"wakoihkn\",\"type\":\"mjblmljhlny\"}]}"; + = "{\"value\":[{\"location\":\"hv\",\"properties\":{\"snapshotId\":\"kvntjlrigjkskyri\",\"created\":\"2020-12-31T15:34:24Z\",\"provisioningState\":\"idsxwaabzmifry\"},\"id\":\"nmmaxrizkzob\",\"name\":\"opxlhslnelxieixy\",\"type\":\"llxecwc\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.snapshots() - .list("lkafhonqjuje", "ckpzvcpopmxeln", "clt", "jedexxmlf", com.azure.core.util.Context.NONE); + .list("jqg", "cfhmlrqryxyn", "nzrdpsovwxz", "ptgoeiybbabp", com.azure.core.util.Context.NONE); - Assertions.assertEquals("kqscazuawxtzx", response.iterator().next().location()); + Assertions.assertEquals("hv", response.iterator().next().location()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotsListTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotsListTests.java index 2801e9081a04..fbbe26adcf8e 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotsListTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotsListTests.java @@ -14,16 +14,16 @@ public final class SnapshotsListTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { SnapshotsList model = BinaryData.fromString( - "{\"value\":[{\"location\":\"eddgssofw\",\"properties\":{\"snapshotId\":\"qal\",\"created\":\"2021-10-24T21:45:29Z\",\"provisioningState\":\"jijpxac\"},\"id\":\"udfnbyxba\",\"name\":\"abjy\",\"type\":\"ayffim\"},{\"location\":\"zrtuzq\",\"properties\":{\"snapshotId\":\"exn\",\"created\":\"2021-10-08T20:33:25Z\",\"provisioningState\":\"nwnwme\"},\"id\":\"syyceuzsoibjud\",\"name\":\"frxtrthzvaytdwk\",\"type\":\"brqubp\"},{\"location\":\"xhexiilivpdti\",\"properties\":{\"snapshotId\":\"tdqoaxoruzfgsq\",\"created\":\"2021-04-24T02:41:36Z\",\"provisioningState\":\"rxxle\"},\"id\":\"ramxjezwlwnw\",\"name\":\"uqlcvydy\",\"type\":\"atdooaojkniod\"}]}") + "{\"value\":[{\"location\":\"aw\",\"properties\":{\"snapshotId\":\"ivx\",\"created\":\"2021-12-04T11:19:32Z\",\"provisioningState\":\"lpcirelsf\"},\"id\":\"enwabfatk\",\"name\":\"ddxbjhwuaanoz\",\"type\":\"osphyoul\"},{\"location\":\"jrvxaglrv\",\"properties\":{\"snapshotId\":\"wosytxitcskf\",\"created\":\"2021-07-26T14:22:18Z\",\"provisioningState\":\"umiekkezzi\"},\"id\":\"ly\",\"name\":\"jhdgqggebdunyga\",\"type\":\"qidbqfatpxllrxcy\"}]}") .toObject(SnapshotsList.class); - Assertions.assertEquals("eddgssofw", model.value().get(0).location()); + Assertions.assertEquals("aw", model.value().get(0).location()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - SnapshotsList model = new SnapshotsList().withValue(Arrays.asList(new SnapshotInner().withLocation("eddgssofw"), - new SnapshotInner().withLocation("zrtuzq"), new SnapshotInner().withLocation("xhexiilivpdti"))); + SnapshotsList model = new SnapshotsList().withValue( + Arrays.asList(new SnapshotInner().withLocation("aw"), new SnapshotInner().withLocation("jrvxaglrv"))); model = BinaryData.fromObject(model).toObject(SnapshotsList.class); - Assertions.assertEquals("eddgssofw", model.value().get(0).location()); + Assertions.assertEquals("aw", model.value().get(0).location()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotsRestoreFilesMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotsRestoreFilesMockTests.java index 58a0471a7bdf..2adbf9f9ebac 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotsRestoreFilesMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotsRestoreFilesMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.SnapshotRestoreFiles; @@ -27,12 +27,12 @@ public void testRestoreFiles() throws Exception { NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); manager.snapshots() - .restoreFiles("elfwy", "wl", "xjwet", "psihcla", "zvaylptrsqqw", - new SnapshotRestoreFiles().withFilePaths(Arrays.asList("cmwqkchcxwa", "fewz", "kjexfdeqvhp")) - .withDestinationPath("lkkshkbffmbmx"), + .restoreFiles("ihebwtsw", "zuwfmdur", "gegizvcjfel", "sdjubggbqigkxkbs", "zgakgacyrcmj", + new SnapshotRestoreFiles().withFilePaths(Arrays.asList("spofapvuhry", "ni", "frzgbzjed", "st")) + .withDestinationPath("nlvxbcuii"), com.azure.core.util.Context.NONE); } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotsUpdateMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotsUpdateMockTests.java index 652af7db6d3b..feff12715080 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotsUpdateMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SnapshotsUpdateMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.Snapshot; @@ -21,19 +21,19 @@ public final class SnapshotsUpdateMockTests { @Test public void testUpdate() throws Exception { String responseStr - = "{\"location\":\"dmspof\",\"properties\":{\"snapshotId\":\"uhrylniofr\",\"created\":\"2021-07-21T02:06:58Z\",\"provisioningState\":\"Succeeded\"},\"id\":\"tkvnlvxbcuiiznkt\",\"name\":\"f\",\"type\":\"nsnvpd\"}"; + = "{\"location\":\"mv\",\"properties\":{\"snapshotId\":\"tayx\",\"created\":\"2021-06-26T17:58:31Z\",\"provisioningState\":\"Succeeded\"},\"id\":\"vsqltnzoibgsxg\",\"name\":\"xfyqonmpqoxwdo\",\"type\":\"dbxiqx\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); Snapshot response = manager.snapshots() - .update("vqihebwtswbzuwf", "duragegizvc", "felisdjub", "gbqi", "kxkbsazgakgacyr", "datam", + .update("xcushs", "haivm", "yasflvgsgzwy", "akoi", "knsmjblmljhlnymz", "datatqyryuzcbmqqv", com.azure.core.util.Context.NONE); - Assertions.assertEquals("dmspof", response.location()); + Assertions.assertEquals("mv", response.location()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumeInfoInnerTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumeInfoInnerTests.java index 610e706a8ff8..1eee26b03f3f 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumeInfoInnerTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumeInfoInnerTests.java @@ -12,20 +12,20 @@ public final class SubvolumeInfoInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { SubvolumeInfoInner model = BinaryData.fromString( - "{\"properties\":{\"path\":\"ftul\",\"size\":9148960841724922095,\"parentPath\":\"ceamtm\",\"provisioningState\":\"u\"},\"id\":\"ejwcwwqiok\",\"name\":\"ssxmojms\",\"type\":\"p\"}") + "{\"properties\":{\"path\":\"vbquwr\",\"size\":6955991643413022423,\"parentPath\":\"gohbuffkmrq\",\"provisioningState\":\"vvhmxtdrj\"},\"id\":\"tac\",\"name\":\"ebjvewzcjzn\",\"type\":\"wcpmguaadraufac\"}") .toObject(SubvolumeInfoInner.class); - Assertions.assertEquals("ftul", model.path()); - Assertions.assertEquals(9148960841724922095L, model.size()); - Assertions.assertEquals("ceamtm", model.parentPath()); + Assertions.assertEquals("vbquwr", model.path()); + Assertions.assertEquals(6955991643413022423L, model.size()); + Assertions.assertEquals("gohbuffkmrq", model.parentPath()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { SubvolumeInfoInner model - = new SubvolumeInfoInner().withPath("ftul").withSize(9148960841724922095L).withParentPath("ceamtm"); + = new SubvolumeInfoInner().withPath("vbquwr").withSize(6955991643413022423L).withParentPath("gohbuffkmrq"); model = BinaryData.fromObject(model).toObject(SubvolumeInfoInner.class); - Assertions.assertEquals("ftul", model.path()); - Assertions.assertEquals(9148960841724922095L, model.size()); - Assertions.assertEquals("ceamtm", model.parentPath()); + Assertions.assertEquals("vbquwr", model.path()); + Assertions.assertEquals(6955991643413022423L, model.size()); + Assertions.assertEquals("gohbuffkmrq", model.parentPath()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumeModelInnerTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumeModelInnerTests.java index e396d43022b4..633a8a7038d1 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumeModelInnerTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumeModelInnerTests.java @@ -13,42 +13,42 @@ public final class SubvolumeModelInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { SubvolumeModelInner model = BinaryData.fromString( - "{\"id\":\"yklyhpluodpvruud\",\"name\":\"zibt\",\"type\":\"stgktst\",\"properties\":{\"path\":\"eclze\",\"parentPath\":\"bcvhzlhpl\",\"size\":4639837566947642597,\"bytesUsed\":7621126373333808650,\"permissions\":\"qfbumlkxtrqjf\",\"creationTimeStamp\":\"2021-09-13T05:47Z\",\"accessedTimeStamp\":\"2021-09-19T15:04:58Z\",\"modifiedTimeStamp\":\"2021-04-24T16:12:25Z\",\"changedTimeStamp\":\"2021-03-23T13:40:47Z\",\"provisioningState\":\"fwsrtawcoezbrhu\"}}") + "{\"id\":\"klvxwmyg\",\"name\":\"pgpqchiszepnnb\",\"type\":\"rxgibbd\",\"properties\":{\"path\":\"onfo\",\"parentPath\":\"uors\",\"size\":8150670572969062689,\"bytesUsed\":5619179077709143106,\"permissions\":\"lhlv\",\"creationTimeStamp\":\"2021-01-24T14:33:20Z\",\"accessedTimeStamp\":\"2021-08-29T14:02:44Z\",\"modifiedTimeStamp\":\"2021-05-23T19:05:13Z\",\"changedTimeStamp\":\"2021-03-16T20:13:21Z\",\"provisioningState\":\"wzsoldweyuqdunv\"}}") .toObject(SubvolumeModelInner.class); - Assertions.assertEquals("eclze", model.path()); - Assertions.assertEquals("bcvhzlhpl", model.parentPath()); - Assertions.assertEquals(4639837566947642597L, model.size()); - Assertions.assertEquals(7621126373333808650L, model.bytesUsed()); - Assertions.assertEquals("qfbumlkxtrqjf", model.permissions()); - Assertions.assertEquals(OffsetDateTime.parse("2021-09-13T05:47Z"), model.creationTimestamp()); - Assertions.assertEquals(OffsetDateTime.parse("2021-09-19T15:04:58Z"), model.accessedTimestamp()); - Assertions.assertEquals(OffsetDateTime.parse("2021-04-24T16:12:25Z"), model.modifiedTimestamp()); - Assertions.assertEquals(OffsetDateTime.parse("2021-03-23T13:40:47Z"), model.changedTimestamp()); - Assertions.assertEquals("fwsrtawcoezbrhu", model.provisioningState()); + Assertions.assertEquals("onfo", model.path()); + Assertions.assertEquals("uors", model.parentPath()); + Assertions.assertEquals(8150670572969062689L, model.size()); + Assertions.assertEquals(5619179077709143106L, model.bytesUsed()); + Assertions.assertEquals("lhlv", model.permissions()); + Assertions.assertEquals(OffsetDateTime.parse("2021-01-24T14:33:20Z"), model.creationTimestamp()); + Assertions.assertEquals(OffsetDateTime.parse("2021-08-29T14:02:44Z"), model.accessedTimestamp()); + Assertions.assertEquals(OffsetDateTime.parse("2021-05-23T19:05:13Z"), model.modifiedTimestamp()); + Assertions.assertEquals(OffsetDateTime.parse("2021-03-16T20:13:21Z"), model.changedTimestamp()); + Assertions.assertEquals("wzsoldweyuqdunv", model.provisioningState()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - SubvolumeModelInner model = new SubvolumeModelInner().withPath("eclze") - .withParentPath("bcvhzlhpl") - .withSize(4639837566947642597L) - .withBytesUsed(7621126373333808650L) - .withPermissions("qfbumlkxtrqjf") - .withCreationTimestamp(OffsetDateTime.parse("2021-09-13T05:47Z")) - .withAccessedTimestamp(OffsetDateTime.parse("2021-09-19T15:04:58Z")) - .withModifiedTimestamp(OffsetDateTime.parse("2021-04-24T16:12:25Z")) - .withChangedTimestamp(OffsetDateTime.parse("2021-03-23T13:40:47Z")) - .withProvisioningState("fwsrtawcoezbrhu"); + SubvolumeModelInner model = new SubvolumeModelInner().withPath("onfo") + .withParentPath("uors") + .withSize(8150670572969062689L) + .withBytesUsed(5619179077709143106L) + .withPermissions("lhlv") + .withCreationTimestamp(OffsetDateTime.parse("2021-01-24T14:33:20Z")) + .withAccessedTimestamp(OffsetDateTime.parse("2021-08-29T14:02:44Z")) + .withModifiedTimestamp(OffsetDateTime.parse("2021-05-23T19:05:13Z")) + .withChangedTimestamp(OffsetDateTime.parse("2021-03-16T20:13:21Z")) + .withProvisioningState("wzsoldweyuqdunv"); model = BinaryData.fromObject(model).toObject(SubvolumeModelInner.class); - Assertions.assertEquals("eclze", model.path()); - Assertions.assertEquals("bcvhzlhpl", model.parentPath()); - Assertions.assertEquals(4639837566947642597L, model.size()); - Assertions.assertEquals(7621126373333808650L, model.bytesUsed()); - Assertions.assertEquals("qfbumlkxtrqjf", model.permissions()); - Assertions.assertEquals(OffsetDateTime.parse("2021-09-13T05:47Z"), model.creationTimestamp()); - Assertions.assertEquals(OffsetDateTime.parse("2021-09-19T15:04:58Z"), model.accessedTimestamp()); - Assertions.assertEquals(OffsetDateTime.parse("2021-04-24T16:12:25Z"), model.modifiedTimestamp()); - Assertions.assertEquals(OffsetDateTime.parse("2021-03-23T13:40:47Z"), model.changedTimestamp()); - Assertions.assertEquals("fwsrtawcoezbrhu", model.provisioningState()); + Assertions.assertEquals("onfo", model.path()); + Assertions.assertEquals("uors", model.parentPath()); + Assertions.assertEquals(8150670572969062689L, model.size()); + Assertions.assertEquals(5619179077709143106L, model.bytesUsed()); + Assertions.assertEquals("lhlv", model.permissions()); + Assertions.assertEquals(OffsetDateTime.parse("2021-01-24T14:33:20Z"), model.creationTimestamp()); + Assertions.assertEquals(OffsetDateTime.parse("2021-08-29T14:02:44Z"), model.accessedTimestamp()); + Assertions.assertEquals(OffsetDateTime.parse("2021-05-23T19:05:13Z"), model.modifiedTimestamp()); + Assertions.assertEquals(OffsetDateTime.parse("2021-03-16T20:13:21Z"), model.changedTimestamp()); + Assertions.assertEquals("wzsoldweyuqdunv", model.provisioningState()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumeModelPropertiesTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumeModelPropertiesTests.java index 98533070087b..fe7ca664b7db 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumeModelPropertiesTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumeModelPropertiesTests.java @@ -13,42 +13,42 @@ public final class SubvolumeModelPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { SubvolumeModelProperties model = BinaryData.fromString( - "{\"path\":\"kh\",\"parentPath\":\"ygo\",\"size\":1410009075037068900,\"bytesUsed\":9221028808795014470,\"permissions\":\"bvleorfmluiqtqzf\",\"creationTimeStamp\":\"2021-05-04T19:19:19Z\",\"accessedTimeStamp\":\"2021-06-05T20:28:23Z\",\"modifiedTimeStamp\":\"2021-03-05T04:35Z\",\"changedTimeStamp\":\"2021-05-23T06:21:06Z\",\"provisioningState\":\"ryeu\"}") + "{\"path\":\"nrwrbiork\",\"parentPath\":\"lywjhh\",\"size\":6322848214394065275,\"bytesUsed\":3127614334065666845,\"permissions\":\"v\",\"creationTimeStamp\":\"2021-07-20T04:17:10Z\",\"accessedTimeStamp\":\"2021-04-28T21:19:50Z\",\"modifiedTimeStamp\":\"2020-12-27T23:16:18Z\",\"changedTimeStamp\":\"2021-10-29T08:24:04Z\",\"provisioningState\":\"ufiqndieuzaof\"}") .toObject(SubvolumeModelProperties.class); - Assertions.assertEquals("kh", model.path()); - Assertions.assertEquals("ygo", model.parentPath()); - Assertions.assertEquals(1410009075037068900L, model.size()); - Assertions.assertEquals(9221028808795014470L, model.bytesUsed()); - Assertions.assertEquals("bvleorfmluiqtqzf", model.permissions()); - Assertions.assertEquals(OffsetDateTime.parse("2021-05-04T19:19:19Z"), model.creationTimestamp()); - Assertions.assertEquals(OffsetDateTime.parse("2021-06-05T20:28:23Z"), model.accessedTimestamp()); - Assertions.assertEquals(OffsetDateTime.parse("2021-03-05T04:35Z"), model.modifiedTimestamp()); - Assertions.assertEquals(OffsetDateTime.parse("2021-05-23T06:21:06Z"), model.changedTimestamp()); - Assertions.assertEquals("ryeu", model.provisioningState()); + Assertions.assertEquals("nrwrbiork", model.path()); + Assertions.assertEquals("lywjhh", model.parentPath()); + Assertions.assertEquals(6322848214394065275L, model.size()); + Assertions.assertEquals(3127614334065666845L, model.bytesUsed()); + Assertions.assertEquals("v", model.permissions()); + Assertions.assertEquals(OffsetDateTime.parse("2021-07-20T04:17:10Z"), model.creationTimestamp()); + Assertions.assertEquals(OffsetDateTime.parse("2021-04-28T21:19:50Z"), model.accessedTimestamp()); + Assertions.assertEquals(OffsetDateTime.parse("2020-12-27T23:16:18Z"), model.modifiedTimestamp()); + Assertions.assertEquals(OffsetDateTime.parse("2021-10-29T08:24:04Z"), model.changedTimestamp()); + Assertions.assertEquals("ufiqndieuzaof", model.provisioningState()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - SubvolumeModelProperties model = new SubvolumeModelProperties().withPath("kh") - .withParentPath("ygo") - .withSize(1410009075037068900L) - .withBytesUsed(9221028808795014470L) - .withPermissions("bvleorfmluiqtqzf") - .withCreationTimestamp(OffsetDateTime.parse("2021-05-04T19:19:19Z")) - .withAccessedTimestamp(OffsetDateTime.parse("2021-06-05T20:28:23Z")) - .withModifiedTimestamp(OffsetDateTime.parse("2021-03-05T04:35Z")) - .withChangedTimestamp(OffsetDateTime.parse("2021-05-23T06:21:06Z")) - .withProvisioningState("ryeu"); + SubvolumeModelProperties model = new SubvolumeModelProperties().withPath("nrwrbiork") + .withParentPath("lywjhh") + .withSize(6322848214394065275L) + .withBytesUsed(3127614334065666845L) + .withPermissions("v") + .withCreationTimestamp(OffsetDateTime.parse("2021-07-20T04:17:10Z")) + .withAccessedTimestamp(OffsetDateTime.parse("2021-04-28T21:19:50Z")) + .withModifiedTimestamp(OffsetDateTime.parse("2020-12-27T23:16:18Z")) + .withChangedTimestamp(OffsetDateTime.parse("2021-10-29T08:24:04Z")) + .withProvisioningState("ufiqndieuzaof"); model = BinaryData.fromObject(model).toObject(SubvolumeModelProperties.class); - Assertions.assertEquals("kh", model.path()); - Assertions.assertEquals("ygo", model.parentPath()); - Assertions.assertEquals(1410009075037068900L, model.size()); - Assertions.assertEquals(9221028808795014470L, model.bytesUsed()); - Assertions.assertEquals("bvleorfmluiqtqzf", model.permissions()); - Assertions.assertEquals(OffsetDateTime.parse("2021-05-04T19:19:19Z"), model.creationTimestamp()); - Assertions.assertEquals(OffsetDateTime.parse("2021-06-05T20:28:23Z"), model.accessedTimestamp()); - Assertions.assertEquals(OffsetDateTime.parse("2021-03-05T04:35Z"), model.modifiedTimestamp()); - Assertions.assertEquals(OffsetDateTime.parse("2021-05-23T06:21:06Z"), model.changedTimestamp()); - Assertions.assertEquals("ryeu", model.provisioningState()); + Assertions.assertEquals("nrwrbiork", model.path()); + Assertions.assertEquals("lywjhh", model.parentPath()); + Assertions.assertEquals(6322848214394065275L, model.size()); + Assertions.assertEquals(3127614334065666845L, model.bytesUsed()); + Assertions.assertEquals("v", model.permissions()); + Assertions.assertEquals(OffsetDateTime.parse("2021-07-20T04:17:10Z"), model.creationTimestamp()); + Assertions.assertEquals(OffsetDateTime.parse("2021-04-28T21:19:50Z"), model.accessedTimestamp()); + Assertions.assertEquals(OffsetDateTime.parse("2020-12-27T23:16:18Z"), model.modifiedTimestamp()); + Assertions.assertEquals(OffsetDateTime.parse("2021-10-29T08:24:04Z"), model.changedTimestamp()); + Assertions.assertEquals("ufiqndieuzaof", model.provisioningState()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumePatchParamsTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumePatchParamsTests.java index 9ef3897f2d6c..390be57054e0 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumePatchParamsTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumePatchParamsTests.java @@ -11,17 +11,19 @@ public final class SubvolumePatchParamsTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - SubvolumePatchParams model = BinaryData.fromString("{\"size\":3671939650811911074,\"path\":\"rc\"}") - .toObject(SubvolumePatchParams.class); - Assertions.assertEquals(3671939650811911074L, model.size()); - Assertions.assertEquals("rc", model.path()); + SubvolumePatchParams model + = BinaryData.fromString("{\"size\":5977101318302182370,\"path\":\"hminyflnorwmduv\"}") + .toObject(SubvolumePatchParams.class); + Assertions.assertEquals(5977101318302182370L, model.size()); + Assertions.assertEquals("hminyflnorwmduv", model.path()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - SubvolumePatchParams model = new SubvolumePatchParams().withSize(3671939650811911074L).withPath("rc"); + SubvolumePatchParams model + = new SubvolumePatchParams().withSize(5977101318302182370L).withPath("hminyflnorwmduv"); model = BinaryData.fromObject(model).toObject(SubvolumePatchParams.class); - Assertions.assertEquals(3671939650811911074L, model.size()); - Assertions.assertEquals("rc", model.path()); + Assertions.assertEquals(5977101318302182370L, model.size()); + Assertions.assertEquals("hminyflnorwmduv", model.path()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumePatchRequestTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumePatchRequestTests.java index ed2a779b6210..595b3136c3ef 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumePatchRequestTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumePatchRequestTests.java @@ -12,17 +12,17 @@ public final class SubvolumePatchRequestTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { SubvolumePatchRequest model - = BinaryData.fromString("{\"properties\":{\"size\":5324799638709264406,\"path\":\"x\"}}") + = BinaryData.fromString("{\"properties\":{\"size\":8719106593186514083,\"path\":\"sutujba\"}}") .toObject(SubvolumePatchRequest.class); - Assertions.assertEquals(5324799638709264406L, model.size()); - Assertions.assertEquals("x", model.path()); + Assertions.assertEquals(8719106593186514083L, model.size()); + Assertions.assertEquals("sutujba", model.path()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - SubvolumePatchRequest model = new SubvolumePatchRequest().withSize(5324799638709264406L).withPath("x"); + SubvolumePatchRequest model = new SubvolumePatchRequest().withSize(8719106593186514083L).withPath("sutujba"); model = BinaryData.fromObject(model).toObject(SubvolumePatchRequest.class); - Assertions.assertEquals(5324799638709264406L, model.size()); - Assertions.assertEquals("x", model.path()); + Assertions.assertEquals(8719106593186514083L, model.size()); + Assertions.assertEquals("sutujba", model.path()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumePropertiesTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumePropertiesTests.java index a5a19974c0bf..eba2748b52e8 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumePropertiesTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumePropertiesTests.java @@ -12,21 +12,21 @@ public final class SubvolumePropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { SubvolumeProperties model = BinaryData.fromString( - "{\"path\":\"prvkwcfzqljyxgtc\",\"size\":6617307512008189308,\"parentPath\":\"bsdshmkxmaehvbbx\",\"provisioningState\":\"iplt\"}") + "{\"path\":\"ahzovajjziuxxp\",\"size\":8416190533050507867,\"parentPath\":\"kulfg\",\"provisioningState\":\"qubkw\"}") .toObject(SubvolumeProperties.class); - Assertions.assertEquals("prvkwcfzqljyxgtc", model.path()); - Assertions.assertEquals(6617307512008189308L, model.size()); - Assertions.assertEquals("bsdshmkxmaehvbbx", model.parentPath()); + Assertions.assertEquals("ahzovajjziuxxp", model.path()); + Assertions.assertEquals(8416190533050507867L, model.size()); + Assertions.assertEquals("kulfg", model.parentPath()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - SubvolumeProperties model = new SubvolumeProperties().withPath("prvkwcfzqljyxgtc") - .withSize(6617307512008189308L) - .withParentPath("bsdshmkxmaehvbbx"); + SubvolumeProperties model = new SubvolumeProperties().withPath("ahzovajjziuxxp") + .withSize(8416190533050507867L) + .withParentPath("kulfg"); model = BinaryData.fromObject(model).toObject(SubvolumeProperties.class); - Assertions.assertEquals("prvkwcfzqljyxgtc", model.path()); - Assertions.assertEquals(6617307512008189308L, model.size()); - Assertions.assertEquals("bsdshmkxmaehvbbx", model.parentPath()); + Assertions.assertEquals("ahzovajjziuxxp", model.path()); + Assertions.assertEquals(8416190533050507867L, model.size()); + Assertions.assertEquals("kulfg", model.parentPath()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumesCreateMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumesCreateMockTests.java index 29e5afff120c..d7ef8931c334 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumesCreateMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumesCreateMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.SubvolumeInfo; @@ -21,25 +21,25 @@ public final class SubvolumesCreateMockTests { @Test public void testCreate() throws Exception { String responseStr - = "{\"properties\":{\"path\":\"vwwskondcbr\",\"size\":4473926182933643908,\"parentPath\":\"qejo\",\"provisioningState\":\"Succeeded\"},\"id\":\"jqo\",\"name\":\"bpihehcecybmrqbr\",\"type\":\"bbmpxdlvykfre\"}"; + = "{\"properties\":{\"path\":\"ohec\",\"size\":4724039728117987325,\"parentPath\":\"ndyqleal\",\"provisioningState\":\"Succeeded\"},\"id\":\"br\",\"name\":\"fjmzsyzfho\",\"type\":\"lhikcyychunsj\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); SubvolumeInfo response = manager.subvolumes() - .define("fhjirwgdnqzbrfk") - .withExistingVolume("rbgjekglkl", "yulidwcwvm", "eg", "o") - .withPath("hzmtksjc") - .withSize(650585422726036151L) - .withParentPath("sxcdgljplkeuach") + .define("bsxtkcudfbsfarfs") + .withExistingVolume("orim", "rsrrmoucsofldp", "viyfcaabeolhbhlv", "mxuq") + .withPath("lkjxnqpvwgf") + .withSize(4335540278124764929L) + .withParentPath("ykizmdksaoaf") .create(); - Assertions.assertEquals("vwwskondcbr", response.path()); - Assertions.assertEquals(4473926182933643908L, response.size()); - Assertions.assertEquals("qejo", response.parentPath()); + Assertions.assertEquals("ohec", response.path()); + Assertions.assertEquals(4724039728117987325L, response.size()); + Assertions.assertEquals("ndyqleal", response.parentPath()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumesDeleteMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumesDeleteMockTests.java index 7dbb4b2b74ab..1eea6cc0d0fc 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumesDeleteMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumesDeleteMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import java.nio.charset.StandardCharsets; @@ -25,10 +25,9 @@ public void testDelete() throws Exception { NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); - manager.subvolumes() - .delete("rkolawjm", "smwr", "kcdxfzzzw", "jafi", "lhguyn", com.azure.core.util.Context.NONE); + manager.subvolumes().delete("fg", "qbawpcbbnzqcykn", "p", "ofyuicd", "zb", com.azure.core.util.Context.NONE); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumesGetMetadataMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumesGetMetadataMockTests.java index 624031502e69..b978a358c0d1 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumesGetMetadataMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumesGetMetadataMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.SubvolumeModel; @@ -21,27 +21,28 @@ public final class SubvolumesGetMetadataMockTests { @Test public void testGetMetadata() throws Exception { String responseStr - = "{\"id\":\"dphtv\",\"name\":\"lajv\",\"type\":\"jchcsrlzknmzla\",\"properties\":{\"path\":\"pdwvnphcn\",\"parentPath\":\"tpjhm\",\"size\":5508989168713615858,\"bytesUsed\":6447183236703446242,\"permissions\":\"iwdcxsmlzzhzd\",\"creationTimeStamp\":\"2021-11-09T09:45:39Z\",\"accessedTimeStamp\":\"2021-07-29T14:49:37Z\",\"modifiedTimeStamp\":\"2021-06-28T09:26:46Z\",\"changedTimeStamp\":\"2021-09-17T08:33:19Z\",\"provisioningState\":\"Succeeded\"}}"; + = "{\"id\":\"qboshbra\",\"name\":\"pyyrmfs\",\"type\":\"pavbo\",\"properties\":{\"path\":\"pdbwnupgahxkum\",\"parentPath\":\"jcaacfdmmcpugm\",\"size\":2799453974287418624,\"bytesUsed\":5289288139576843863,\"permissions\":\"hbzehewho\",\"creationTimeStamp\":\"2021-08-24T10:40:17Z\",\"accessedTimeStamp\":\"2021-07-22T20:31:39Z\",\"modifiedTimeStamp\":\"2021-02-23T10:26:16Z\",\"changedTimeStamp\":\"2021-07-12T10:48:01Z\",\"provisioningState\":\"Succeeded\"}}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); SubvolumeModel response = manager.subvolumes() - .getMetadata("chl", "mltx", "whmozusgzvlnsnnj", "fpafolpymwamxq", "rag", com.azure.core.util.Context.NONE); + .getMetadata("ybww", "bdvibidmhmwffpl", "muvapc", "ccrrvweyoxoyyu", "phaimmoi", + com.azure.core.util.Context.NONE); - Assertions.assertEquals("pdwvnphcn", response.path()); - Assertions.assertEquals("tpjhm", response.parentPath()); - Assertions.assertEquals(5508989168713615858L, response.size()); - Assertions.assertEquals(6447183236703446242L, response.bytesUsed()); - Assertions.assertEquals("iwdcxsmlzzhzd", response.permissions()); - Assertions.assertEquals(OffsetDateTime.parse("2021-11-09T09:45:39Z"), response.creationTimestamp()); - Assertions.assertEquals(OffsetDateTime.parse("2021-07-29T14:49:37Z"), response.accessedTimestamp()); - Assertions.assertEquals(OffsetDateTime.parse("2021-06-28T09:26:46Z"), response.modifiedTimestamp()); - Assertions.assertEquals(OffsetDateTime.parse("2021-09-17T08:33:19Z"), response.changedTimestamp()); + Assertions.assertEquals("pdbwnupgahxkum", response.path()); + Assertions.assertEquals("jcaacfdmmcpugm", response.parentPath()); + Assertions.assertEquals(2799453974287418624L, response.size()); + Assertions.assertEquals(5289288139576843863L, response.bytesUsed()); + Assertions.assertEquals("hbzehewho", response.permissions()); + Assertions.assertEquals(OffsetDateTime.parse("2021-08-24T10:40:17Z"), response.creationTimestamp()); + Assertions.assertEquals(OffsetDateTime.parse("2021-07-22T20:31:39Z"), response.accessedTimestamp()); + Assertions.assertEquals(OffsetDateTime.parse("2021-02-23T10:26:16Z"), response.modifiedTimestamp()); + Assertions.assertEquals(OffsetDateTime.parse("2021-07-12T10:48:01Z"), response.changedTimestamp()); Assertions.assertEquals("Succeeded", response.provisioningState()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumesGetWithResponseMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumesGetWithResponseMockTests.java index d4017e719146..e0b7baa1d0b2 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumesGetWithResponseMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumesGetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.SubvolumeInfo; @@ -21,22 +21,22 @@ public final class SubvolumesGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"path\":\"uuyjucejikz\",\"size\":4989085639302436817,\"parentPath\":\"tzejetjklnt\",\"provisioningState\":\"yjuzkdb\"},\"id\":\"o\",\"name\":\"xrzvhqjwtrhtgvgz\",\"type\":\"c\"}"; + = "{\"properties\":{\"path\":\"rymo\",\"size\":8486820161769932410,\"parentPath\":\"klobdxnazpmk\",\"provisioningState\":\"mv\"},\"id\":\"f\",\"name\":\"zopjhbzxliohr\",\"type\":\"dd\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); SubvolumeInfo response = manager.subvolumes() - .getWithResponse("sfuztlvtmv", "gbwidqlvh", "koveof", "zrvjfnmjmvlwyzgi", "lkujrllfojui", + .getWithResponse("zna", "xbannovvoxc", "ytprwnwvroev", "tlyo", "rrrouuxvnsa", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("uuyjucejikz", response.path()); - Assertions.assertEquals(4989085639302436817L, response.size()); - Assertions.assertEquals("tzejetjklnt", response.parentPath()); + Assertions.assertEquals("rymo", response.path()); + Assertions.assertEquals(8486820161769932410L, response.size()); + Assertions.assertEquals("klobdxnazpmk", response.parentPath()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumesListByVolumeMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumesListByVolumeMockTests.java index b1b2dc9dde1e..ac80dbc1bba7 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumesListByVolumeMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumesListByVolumeMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.SubvolumeInfo; @@ -22,20 +22,20 @@ public final class SubvolumesListByVolumeMockTests { @Test public void testListByVolume() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"path\":\"ulbmoichdlp\",\"size\":1458552691352112238,\"parentPath\":\"nt\",\"provisioningState\":\"atzviqsowsaael\"},\"id\":\"ttcjuhplrvkmjc\",\"name\":\"mjvlgfgg\",\"type\":\"vkyylizrzbjpsf\"}]}"; + = "{\"value\":[{\"properties\":{\"path\":\"qxypokkhminq\",\"size\":6418388718617598308,\"parentPath\":\"ngnbdxxew\",\"provisioningState\":\"invudbch\"},\"id\":\"dtvqe\",\"name\":\"rqctmxxdtdd\",\"type\":\"flhuytxzv\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.subvolumes() - .listByVolume("qotoihiqakydiwfb", "kwpzdqtvh", "spodaqax", "ipietgbe", com.azure.core.util.Context.NONE); + .listByVolume("kfuarenlv", "htkln", "nafvvkyfedev", "bo", com.azure.core.util.Context.NONE); - Assertions.assertEquals("ulbmoichdlp", response.iterator().next().path()); - Assertions.assertEquals(1458552691352112238L, response.iterator().next().size()); - Assertions.assertEquals("nt", response.iterator().next().parentPath()); + Assertions.assertEquals("qxypokkhminq", response.iterator().next().path()); + Assertions.assertEquals(6418388718617598308L, response.iterator().next().size()); + Assertions.assertEquals("ngnbdxxew", response.iterator().next().parentPath()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumesListTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumesListTests.java index 8c381f4653bb..87a1ae4cb579 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumesListTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SubvolumesListTests.java @@ -14,24 +14,23 @@ public final class SubvolumesListTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { SubvolumesList model = BinaryData.fromString( - "{\"value\":[{\"properties\":{\"path\":\"aeqphchqnr\",\"size\":4162908248726599775,\"parentPath\":\"huwrykqgaifm\",\"provisioningState\":\"klbydv\"},\"id\":\"bejdznxcv\",\"name\":\"srhnjivo\",\"type\":\"v\"}],\"nextLink\":\"ovqfzge\"}") + "{\"value\":[{\"properties\":{\"path\":\"tawc\",\"size\":5744786061005129903,\"parentPath\":\"hubskhudygooo\",\"provisioningState\":\"qfqjbvleorfm\"},\"id\":\"iqtqzfavyvnq\",\"name\":\"ybar\",\"type\":\"euayjkqabqgzsles\"}],\"nextLink\":\"bhernntiew\"}") .toObject(SubvolumesList.class); - Assertions.assertEquals("aeqphchqnr", model.value().get(0).path()); - Assertions.assertEquals(4162908248726599775L, model.value().get(0).size()); - Assertions.assertEquals("huwrykqgaifm", model.value().get(0).parentPath()); - Assertions.assertEquals("ovqfzge", model.nextLink()); + Assertions.assertEquals("tawc", model.value().get(0).path()); + Assertions.assertEquals(5744786061005129903L, model.value().get(0).size()); + Assertions.assertEquals("hubskhudygooo", model.value().get(0).parentPath()); + Assertions.assertEquals("bhernntiew", model.nextLink()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - SubvolumesList model - = new SubvolumesList().withValue(Arrays.asList(new SubvolumeInfoInner().withPath("aeqphchqnr") - .withSize(4162908248726599775L) - .withParentPath("huwrykqgaifm"))).withNextLink("ovqfzge"); + SubvolumesList model = new SubvolumesList().withValue(Arrays.asList( + new SubvolumeInfoInner().withPath("tawc").withSize(5744786061005129903L).withParentPath("hubskhudygooo"))) + .withNextLink("bhernntiew"); model = BinaryData.fromObject(model).toObject(SubvolumesList.class); - Assertions.assertEquals("aeqphchqnr", model.value().get(0).path()); - Assertions.assertEquals(4162908248726599775L, model.value().get(0).size()); - Assertions.assertEquals("huwrykqgaifm", model.value().get(0).parentPath()); - Assertions.assertEquals("ovqfzge", model.nextLink()); + Assertions.assertEquals("tawc", model.value().get(0).path()); + Assertions.assertEquals(5744786061005129903L, model.value().get(0).size()); + Assertions.assertEquals("hubskhudygooo", model.value().get(0).parentPath()); + Assertions.assertEquals("bhernntiew", model.nextLink()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SvmPeerCommandResponseInnerTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SvmPeerCommandResponseInnerTests.java index 3c2f7bd40ab7..f3fc3673e436 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SvmPeerCommandResponseInnerTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/SvmPeerCommandResponseInnerTests.java @@ -11,15 +11,15 @@ public final class SvmPeerCommandResponseInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - SvmPeerCommandResponseInner model = BinaryData.fromString("{\"svmPeeringCommand\":\"hyxxrwlycoduhpk\"}") + SvmPeerCommandResponseInner model = BinaryData.fromString("{\"svmPeeringCommand\":\"fnjhfjxwmszkkfo\"}") .toObject(SvmPeerCommandResponseInner.class); - Assertions.assertEquals("hyxxrwlycoduhpk", model.svmPeeringCommand()); + Assertions.assertEquals("fnjhfjxwmszkkfo", model.svmPeeringCommand()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - SvmPeerCommandResponseInner model = new SvmPeerCommandResponseInner().withSvmPeeringCommand("hyxxrwlycoduhpk"); + SvmPeerCommandResponseInner model = new SvmPeerCommandResponseInner().withSvmPeeringCommand("fnjhfjxwmszkkfo"); model = BinaryData.fromObject(model).toObject(SvmPeerCommandResponseInner.class); - Assertions.assertEquals("hyxxrwlycoduhpk", model.svmPeeringCommand()); + Assertions.assertEquals("fnjhfjxwmszkkfo", model.svmPeeringCommand()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/UserAssignedIdentityTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/UserAssignedIdentityTests.java index 6d7ddbd06897..98a7d549f47c 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/UserAssignedIdentityTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/UserAssignedIdentityTests.java @@ -11,7 +11,7 @@ public final class UserAssignedIdentityTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { UserAssignedIdentity model = BinaryData.fromString( - "{\"principalId\":\"21f4a1bf-897e-4508-b0d7-cb1bbbdf1afa\",\"clientId\":\"c9d9b013-01f2-44e3-9534-5f81ffb1ac2f\"}") + "{\"principalId\":\"4b3ced31-5092-4786-b255-70aa21c5276d\",\"clientId\":\"3036db3a-7ee3-4dee-998f-06f401d1e400\"}") .toObject(UserAssignedIdentity.class); } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeBackupPropertiesTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeBackupPropertiesTests.java index 62481499d388..9c0e2e685715 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeBackupPropertiesTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeBackupPropertiesTests.java @@ -12,22 +12,21 @@ public final class VolumeBackupPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { VolumeBackupProperties model = BinaryData - .fromString( - "{\"backupPolicyId\":\"ldnkwwtppjfl\",\"policyEnforced\":false,\"backupVaultId\":\"aokonzmnsik\"}") + .fromString("{\"backupPolicyId\":\"riofzpyqse\",\"policyEnforced\":false,\"backupVaultId\":\"n\"}") .toObject(VolumeBackupProperties.class); - Assertions.assertEquals("ldnkwwtppjfl", model.backupPolicyId()); + Assertions.assertEquals("riofzpyqse", model.backupPolicyId()); Assertions.assertEquals(false, model.policyEnforced()); - Assertions.assertEquals("aokonzmnsik", model.backupVaultId()); + Assertions.assertEquals("n", model.backupVaultId()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - VolumeBackupProperties model = new VolumeBackupProperties().withBackupPolicyId("ldnkwwtppjfl") + VolumeBackupProperties model = new VolumeBackupProperties().withBackupPolicyId("riofzpyqse") .withPolicyEnforced(false) - .withBackupVaultId("aokonzmnsik"); + .withBackupVaultId("n"); model = BinaryData.fromObject(model).toObject(VolumeBackupProperties.class); - Assertions.assertEquals("ldnkwwtppjfl", model.backupPolicyId()); + Assertions.assertEquals("riofzpyqse", model.backupPolicyId()); Assertions.assertEquals(false, model.policyEnforced()); - Assertions.assertEquals("aokonzmnsik", model.backupVaultId()); + Assertions.assertEquals("n", model.backupVaultId()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeBackupsTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeBackupsTests.java index 1fd9a6facfaf..0b11a3cad09e 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeBackupsTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeBackupsTests.java @@ -12,24 +12,24 @@ public final class VolumeBackupsTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { VolumeBackups model = BinaryData.fromString( - "{\"volumeName\":\"iibfggj\",\"volumeResourceId\":\"olvrw\",\"backupsCount\":148831092,\"policyEnabled\":false}") + "{\"volumeName\":\"rjreafxts\",\"volumeResourceId\":\"mhjglikkxwslolb\",\"backupsCount\":1224144822,\"policyEnabled\":true}") .toObject(VolumeBackups.class); - Assertions.assertEquals("iibfggj", model.volumeName()); - Assertions.assertEquals("olvrw", model.volumeResourceId()); - Assertions.assertEquals(148831092, model.backupsCount()); - Assertions.assertEquals(false, model.policyEnabled()); + Assertions.assertEquals("rjreafxts", model.volumeName()); + Assertions.assertEquals("mhjglikkxwslolb", model.volumeResourceId()); + Assertions.assertEquals(1224144822, model.backupsCount()); + Assertions.assertEquals(true, model.policyEnabled()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - VolumeBackups model = new VolumeBackups().withVolumeName("iibfggj") - .withVolumeResourceId("olvrw") - .withBackupsCount(148831092) - .withPolicyEnabled(false); + VolumeBackups model = new VolumeBackups().withVolumeName("rjreafxts") + .withVolumeResourceId("mhjglikkxwslolb") + .withBackupsCount(1224144822) + .withPolicyEnabled(true); model = BinaryData.fromObject(model).toObject(VolumeBackups.class); - Assertions.assertEquals("iibfggj", model.volumeName()); - Assertions.assertEquals("olvrw", model.volumeResourceId()); - Assertions.assertEquals(148831092, model.backupsCount()); - Assertions.assertEquals(false, model.policyEnabled()); + Assertions.assertEquals("rjreafxts", model.volumeName()); + Assertions.assertEquals("mhjglikkxwslolb", model.volumeResourceId()); + Assertions.assertEquals(1224144822, model.backupsCount()); + Assertions.assertEquals(true, model.policyEnabled()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeGroupsDeleteMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeGroupsDeleteMockTests.java index 465d163b27e1..84c99e4e61d2 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeGroupsDeleteMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeGroupsDeleteMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import java.nio.charset.StandardCharsets; @@ -25,9 +25,9 @@ public void testDelete() throws Exception { NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); - manager.volumeGroups().delete("hotj", "wlpxuzzjg", "refqy", com.azure.core.util.Context.NONE); + manager.volumeGroups().delete("qwtehtuevr", "rljyoogwxhnsdu", "gwbsreurf", com.azure.core.util.Context.NONE); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumePatchPropertiesDataProtectionTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumePatchPropertiesDataProtectionTests.java index 8796f4803ac9..511b3b5aab5f 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumePatchPropertiesDataProtectionTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumePatchPropertiesDataProtectionTests.java @@ -14,25 +14,25 @@ public final class VolumePatchPropertiesDataProtectionTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { VolumePatchPropertiesDataProtection model = BinaryData.fromString( - "{\"backup\":{\"backupPolicyId\":\"knso\",\"policyEnforced\":false,\"backupVaultId\":\"xbldtlwwrlkdmtn\"},\"snapshot\":{\"snapshotPolicyId\":\"kotl\"}}") + "{\"backup\":{\"backupPolicyId\":\"jfqka\",\"policyEnforced\":false,\"backupVaultId\":\"ipfpubji\"},\"snapshot\":{\"snapshotPolicyId\":\"iftohqkvpu\"}}") .toObject(VolumePatchPropertiesDataProtection.class); - Assertions.assertEquals("knso", model.backup().backupPolicyId()); + Assertions.assertEquals("jfqka", model.backup().backupPolicyId()); Assertions.assertEquals(false, model.backup().policyEnforced()); - Assertions.assertEquals("xbldtlwwrlkdmtn", model.backup().backupVaultId()); - Assertions.assertEquals("kotl", model.snapshot().snapshotPolicyId()); + Assertions.assertEquals("ipfpubji", model.backup().backupVaultId()); + Assertions.assertEquals("iftohqkvpu", model.snapshot().snapshotPolicyId()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { VolumePatchPropertiesDataProtection model = new VolumePatchPropertiesDataProtection() - .withBackup(new VolumeBackupProperties().withBackupPolicyId("knso") + .withBackup(new VolumeBackupProperties().withBackupPolicyId("jfqka") .withPolicyEnforced(false) - .withBackupVaultId("xbldtlwwrlkdmtn")) - .withSnapshot(new VolumeSnapshotProperties().withSnapshotPolicyId("kotl")); + .withBackupVaultId("ipfpubji")) + .withSnapshot(new VolumeSnapshotProperties().withSnapshotPolicyId("iftohqkvpu")); model = BinaryData.fromObject(model).toObject(VolumePatchPropertiesDataProtection.class); - Assertions.assertEquals("knso", model.backup().backupPolicyId()); + Assertions.assertEquals("jfqka", model.backup().backupPolicyId()); Assertions.assertEquals(false, model.backup().policyEnforced()); - Assertions.assertEquals("xbldtlwwrlkdmtn", model.backup().backupVaultId()); - Assertions.assertEquals("kotl", model.snapshot().snapshotPolicyId()); + Assertions.assertEquals("ipfpubji", model.backup().backupVaultId()); + Assertions.assertEquals("iftohqkvpu", model.snapshot().snapshotPolicyId()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumePatchPropertiesExportPolicyTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumePatchPropertiesExportPolicyTests.java index 08f562b3a03d..3b9294d0bc8d 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumePatchPropertiesExportPolicyTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumePatchPropertiesExportPolicyTests.java @@ -15,9 +15,9 @@ public final class VolumePatchPropertiesExportPolicyTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { VolumePatchPropertiesExportPolicy model = BinaryData.fromString( - "{\"rules\":[{\"ruleIndex\":486073857,\"unixReadOnly\":true,\"unixReadWrite\":true,\"kerberos5ReadOnly\":true,\"kerberos5ReadWrite\":false,\"kerberos5iReadOnly\":true,\"kerberos5iReadWrite\":false,\"kerberos5pReadOnly\":false,\"kerberos5pReadWrite\":true,\"cifs\":true,\"nfsv3\":true,\"nfsv41\":true,\"allowedClients\":\"npcdpumnzgm\",\"hasRootAccess\":false,\"chownMode\":\"Restricted\"}]}") + "{\"rules\":[{\"ruleIndex\":1951399012,\"unixReadOnly\":true,\"unixReadWrite\":true,\"kerberos5ReadOnly\":true,\"kerberos5ReadWrite\":false,\"kerberos5iReadOnly\":true,\"kerberos5iReadWrite\":false,\"kerberos5pReadOnly\":false,\"kerberos5pReadWrite\":false,\"cifs\":true,\"nfsv3\":false,\"nfsv41\":true,\"allowedClients\":\"k\",\"hasRootAccess\":false,\"chownMode\":\"Restricted\"},{\"ruleIndex\":270127219,\"unixReadOnly\":true,\"unixReadWrite\":true,\"kerberos5ReadOnly\":true,\"kerberos5ReadWrite\":false,\"kerberos5iReadOnly\":false,\"kerberos5iReadWrite\":false,\"kerberos5pReadOnly\":false,\"kerberos5pReadWrite\":false,\"cifs\":false,\"nfsv3\":false,\"nfsv41\":true,\"allowedClients\":\"reqnovvqfov\",\"hasRootAccess\":false,\"chownMode\":\"Restricted\"},{\"ruleIndex\":1676739337,\"unixReadOnly\":true,\"unixReadWrite\":true,\"kerberos5ReadOnly\":true,\"kerberos5ReadWrite\":true,\"kerberos5iReadOnly\":true,\"kerberos5iReadWrite\":true,\"kerberos5pReadOnly\":false,\"kerberos5pReadWrite\":false,\"cifs\":false,\"nfsv3\":false,\"nfsv41\":false,\"allowedClients\":\"nzar\",\"hasRootAccess\":true,\"chownMode\":\"Restricted\"}]}") .toObject(VolumePatchPropertiesExportPolicy.class); - Assertions.assertEquals(486073857, model.rules().get(0).ruleIndex()); + Assertions.assertEquals(1951399012, model.rules().get(0).ruleIndex()); Assertions.assertEquals(true, model.rules().get(0).unixReadOnly()); Assertions.assertEquals(true, model.rules().get(0).unixReadWrite()); Assertions.assertEquals(true, model.rules().get(0).kerberos5ReadOnly()); @@ -25,19 +25,19 @@ public void testDeserialize() throws Exception { Assertions.assertEquals(true, model.rules().get(0).kerberos5IReadOnly()); Assertions.assertEquals(false, model.rules().get(0).kerberos5IReadWrite()); Assertions.assertEquals(false, model.rules().get(0).kerberos5PReadOnly()); - Assertions.assertEquals(true, model.rules().get(0).kerberos5PReadWrite()); + Assertions.assertEquals(false, model.rules().get(0).kerberos5PReadWrite()); Assertions.assertEquals(true, model.rules().get(0).cifs()); - Assertions.assertEquals(true, model.rules().get(0).nfsv3()); + Assertions.assertEquals(false, model.rules().get(0).nfsv3()); Assertions.assertEquals(true, model.rules().get(0).nfsv41()); - Assertions.assertEquals("npcdpumnzgm", model.rules().get(0).allowedClients()); + Assertions.assertEquals("k", model.rules().get(0).allowedClients()); Assertions.assertEquals(false, model.rules().get(0).hasRootAccess()); Assertions.assertEquals(ChownMode.RESTRICTED, model.rules().get(0).chownMode()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - VolumePatchPropertiesExportPolicy model = new VolumePatchPropertiesExportPolicy() - .withRules(Arrays.asList(new ExportPolicyRule().withRuleIndex(486073857) + VolumePatchPropertiesExportPolicy model = new VolumePatchPropertiesExportPolicy().withRules(Arrays.asList( + new ExportPolicyRule().withRuleIndex(1951399012) .withUnixReadOnly(true) .withUnixReadWrite(true) .withKerberos5ReadOnly(true) @@ -45,15 +45,45 @@ public void testSerialize() throws Exception { .withKerberos5IReadOnly(true) .withKerberos5IReadWrite(false) .withKerberos5PReadOnly(false) - .withKerberos5PReadWrite(true) + .withKerberos5PReadWrite(false) .withCifs(true) - .withNfsv3(true) + .withNfsv3(false) .withNfsv41(true) - .withAllowedClients("npcdpumnzgm") + .withAllowedClients("k") .withHasRootAccess(false) + .withChownMode(ChownMode.RESTRICTED), + new ExportPolicyRule().withRuleIndex(270127219) + .withUnixReadOnly(true) + .withUnixReadWrite(true) + .withKerberos5ReadOnly(true) + .withKerberos5ReadWrite(false) + .withKerberos5IReadOnly(false) + .withKerberos5IReadWrite(false) + .withKerberos5PReadOnly(false) + .withKerberos5PReadWrite(false) + .withCifs(false) + .withNfsv3(false) + .withNfsv41(true) + .withAllowedClients("reqnovvqfov") + .withHasRootAccess(false) + .withChownMode(ChownMode.RESTRICTED), + new ExportPolicyRule().withRuleIndex(1676739337) + .withUnixReadOnly(true) + .withUnixReadWrite(true) + .withKerberos5ReadOnly(true) + .withKerberos5ReadWrite(true) + .withKerberos5IReadOnly(true) + .withKerberos5IReadWrite(true) + .withKerberos5PReadOnly(false) + .withKerberos5PReadWrite(false) + .withCifs(false) + .withNfsv3(false) + .withNfsv41(false) + .withAllowedClients("nzar") + .withHasRootAccess(true) .withChownMode(ChownMode.RESTRICTED))); model = BinaryData.fromObject(model).toObject(VolumePatchPropertiesExportPolicy.class); - Assertions.assertEquals(486073857, model.rules().get(0).ruleIndex()); + Assertions.assertEquals(1951399012, model.rules().get(0).ruleIndex()); Assertions.assertEquals(true, model.rules().get(0).unixReadOnly()); Assertions.assertEquals(true, model.rules().get(0).unixReadWrite()); Assertions.assertEquals(true, model.rules().get(0).kerberos5ReadOnly()); @@ -61,11 +91,11 @@ public void testSerialize() throws Exception { Assertions.assertEquals(true, model.rules().get(0).kerberos5IReadOnly()); Assertions.assertEquals(false, model.rules().get(0).kerberos5IReadWrite()); Assertions.assertEquals(false, model.rules().get(0).kerberos5PReadOnly()); - Assertions.assertEquals(true, model.rules().get(0).kerberos5PReadWrite()); + Assertions.assertEquals(false, model.rules().get(0).kerberos5PReadWrite()); Assertions.assertEquals(true, model.rules().get(0).cifs()); - Assertions.assertEquals(true, model.rules().get(0).nfsv3()); + Assertions.assertEquals(false, model.rules().get(0).nfsv3()); Assertions.assertEquals(true, model.rules().get(0).nfsv41()); - Assertions.assertEquals("npcdpumnzgm", model.rules().get(0).allowedClients()); + Assertions.assertEquals("k", model.rules().get(0).allowedClients()); Assertions.assertEquals(false, model.rules().get(0).hasRootAccess()); Assertions.assertEquals(ChownMode.RESTRICTED, model.rules().get(0).chownMode()); } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumePatchPropertiesTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumePatchPropertiesTests.java index c81eefbdb4eb..47fa624ea9ae 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumePatchPropertiesTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumePatchPropertiesTests.java @@ -8,6 +8,7 @@ import com.azure.resourcemanager.netapp.fluent.models.VolumePatchProperties; import com.azure.resourcemanager.netapp.models.ChownMode; import com.azure.resourcemanager.netapp.models.CoolAccessRetrievalPolicy; +import com.azure.resourcemanager.netapp.models.CoolAccessTieringPolicy; import com.azure.resourcemanager.netapp.models.ExportPolicyRule; import com.azure.resourcemanager.netapp.models.ServiceLevel; import com.azure.resourcemanager.netapp.models.SmbAccessBasedEnumeration; @@ -23,128 +24,116 @@ public final class VolumePatchPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { VolumePatchProperties model = BinaryData.fromString( - "{\"serviceLevel\":\"Premium\",\"usageThreshold\":5529528892048026868,\"exportPolicy\":{\"rules\":[{\"ruleIndex\":1736041382,\"unixReadOnly\":false,\"unixReadWrite\":true,\"kerberos5ReadOnly\":false,\"kerberos5ReadWrite\":true,\"kerberos5iReadOnly\":false,\"kerberos5iReadWrite\":true,\"kerberos5pReadOnly\":true,\"kerberos5pReadWrite\":false,\"cifs\":false,\"nfsv3\":false,\"nfsv41\":true,\"allowedClients\":\"hkoymkcdyhbp\",\"hasRootAccess\":true,\"chownMode\":\"Unrestricted\"},{\"ruleIndex\":668813662,\"unixReadOnly\":true,\"unixReadWrite\":true,\"kerberos5ReadOnly\":true,\"kerberos5ReadWrite\":true,\"kerberos5iReadOnly\":false,\"kerberos5iReadWrite\":false,\"kerberos5pReadOnly\":false,\"kerberos5pReadWrite\":true,\"cifs\":true,\"nfsv3\":true,\"nfsv41\":true,\"allowedClients\":\"sytgadgvraea\",\"hasRootAccess\":false,\"chownMode\":\"Restricted\"}]},\"protocolTypes\":[\"rrwlquuijfqkace\",\"iipfpubj\"],\"throughputMibps\":80.4325,\"dataProtection\":{\"backup\":{\"backupPolicyId\":\"tohqkvpuvksgp\",\"policyEnforced\":true,\"backupVaultId\":\"nynfsynljphuo\"},\"snapshot\":{\"snapshotPolicyId\":\"dlqiyntorzih\"}},\"isDefaultQuotaEnabled\":false,\"defaultUserQuotaInKiBs\":1763238729707641338,\"defaultGroupQuotaInKiBs\":8731733727418388460,\"unixPermissions\":\"slyzrpzbchckqq\",\"coolAccess\":true,\"coolnessPeriod\":671328296,\"coolAccessRetrievalPolicy\":\"OnRead\",\"snapshotDirectoryVisible\":false,\"smbAccessBasedEnumeration\":\"Disabled\",\"smbNonBrowsable\":\"Enabled\"}") + "{\"serviceLevel\":\"StandardZRS\",\"usageThreshold\":4652181983896123622,\"exportPolicy\":{\"rules\":[{\"ruleIndex\":1838860649,\"unixReadOnly\":true,\"unixReadWrite\":false,\"kerberos5ReadOnly\":false,\"kerberos5ReadWrite\":false,\"kerberos5iReadOnly\":false,\"kerberos5iReadWrite\":false,\"kerberos5pReadOnly\":false,\"kerberos5pReadWrite\":false,\"cifs\":true,\"nfsv3\":false,\"nfsv41\":false,\"allowedClients\":\"qvmkcxo\",\"hasRootAccess\":true,\"chownMode\":\"Unrestricted\"}]},\"protocolTypes\":[\"xprglyatddc\",\"cbcuejrjxgciqi\",\"rhos\",\"sdqrhzoymibmrq\"],\"throughputMibps\":32.402683,\"dataProtection\":{\"backup\":{\"backupPolicyId\":\"fluszdtm\",\"policyEnforced\":true,\"backupVaultId\":\"ofyyvoqacpi\"},\"snapshot\":{\"snapshotPolicyId\":\"btgiwbwoenwas\"}},\"isDefaultQuotaEnabled\":false,\"defaultUserQuotaInKiBs\":9149907061758969702,\"defaultGroupQuotaInKiBs\":6553380675095809006,\"unixPermissions\":\"wbpokulpiujwaasi\",\"coolAccess\":false,\"coolnessPeriod\":1035814224,\"coolAccessRetrievalPolicy\":\"Never\",\"coolAccessTieringPolicy\":\"SnapshotOnly\",\"snapshotDirectoryVisible\":false,\"smbAccessBasedEnumeration\":\"Enabled\",\"smbNonBrowsable\":\"Enabled\"}") .toObject(VolumePatchProperties.class); - Assertions.assertEquals(ServiceLevel.PREMIUM, model.serviceLevel()); - Assertions.assertEquals(5529528892048026868L, model.usageThreshold()); - Assertions.assertEquals(1736041382, model.exportPolicy().rules().get(0).ruleIndex()); - Assertions.assertEquals(false, model.exportPolicy().rules().get(0).unixReadOnly()); - Assertions.assertEquals(true, model.exportPolicy().rules().get(0).unixReadWrite()); + Assertions.assertEquals(ServiceLevel.STANDARD_ZRS, model.serviceLevel()); + Assertions.assertEquals(4652181983896123622L, model.usageThreshold()); + Assertions.assertEquals(1838860649, model.exportPolicy().rules().get(0).ruleIndex()); + Assertions.assertEquals(true, model.exportPolicy().rules().get(0).unixReadOnly()); + Assertions.assertEquals(false, model.exportPolicy().rules().get(0).unixReadWrite()); Assertions.assertEquals(false, model.exportPolicy().rules().get(0).kerberos5ReadOnly()); - Assertions.assertEquals(true, model.exportPolicy().rules().get(0).kerberos5ReadWrite()); + Assertions.assertEquals(false, model.exportPolicy().rules().get(0).kerberos5ReadWrite()); Assertions.assertEquals(false, model.exportPolicy().rules().get(0).kerberos5IReadOnly()); - Assertions.assertEquals(true, model.exportPolicy().rules().get(0).kerberos5IReadWrite()); - Assertions.assertEquals(true, model.exportPolicy().rules().get(0).kerberos5PReadOnly()); + Assertions.assertEquals(false, model.exportPolicy().rules().get(0).kerberos5IReadWrite()); + Assertions.assertEquals(false, model.exportPolicy().rules().get(0).kerberos5PReadOnly()); Assertions.assertEquals(false, model.exportPolicy().rules().get(0).kerberos5PReadWrite()); - Assertions.assertEquals(false, model.exportPolicy().rules().get(0).cifs()); + Assertions.assertEquals(true, model.exportPolicy().rules().get(0).cifs()); Assertions.assertEquals(false, model.exportPolicy().rules().get(0).nfsv3()); - Assertions.assertEquals(true, model.exportPolicy().rules().get(0).nfsv41()); - Assertions.assertEquals("hkoymkcdyhbp", model.exportPolicy().rules().get(0).allowedClients()); + Assertions.assertEquals(false, model.exportPolicy().rules().get(0).nfsv41()); + Assertions.assertEquals("qvmkcxo", model.exportPolicy().rules().get(0).allowedClients()); Assertions.assertEquals(true, model.exportPolicy().rules().get(0).hasRootAccess()); Assertions.assertEquals(ChownMode.UNRESTRICTED, model.exportPolicy().rules().get(0).chownMode()); - Assertions.assertEquals("rrwlquuijfqkace", model.protocolTypes().get(0)); - Assertions.assertEquals(80.4325F, model.throughputMibps()); - Assertions.assertEquals("tohqkvpuvksgp", model.dataProtection().backup().backupPolicyId()); + Assertions.assertEquals("xprglyatddc", model.protocolTypes().get(0)); + Assertions.assertEquals(32.402683F, model.throughputMibps()); + Assertions.assertEquals("fluszdtm", model.dataProtection().backup().backupPolicyId()); Assertions.assertEquals(true, model.dataProtection().backup().policyEnforced()); - Assertions.assertEquals("nynfsynljphuo", model.dataProtection().backup().backupVaultId()); - Assertions.assertEquals("dlqiyntorzih", model.dataProtection().snapshot().snapshotPolicyId()); + Assertions.assertEquals("ofyyvoqacpi", model.dataProtection().backup().backupVaultId()); + Assertions.assertEquals("btgiwbwoenwas", model.dataProtection().snapshot().snapshotPolicyId()); Assertions.assertEquals(false, model.isDefaultQuotaEnabled()); - Assertions.assertEquals(1763238729707641338L, model.defaultUserQuotaInKiBs()); - Assertions.assertEquals(8731733727418388460L, model.defaultGroupQuotaInKiBs()); - Assertions.assertEquals("slyzrpzbchckqq", model.unixPermissions()); - Assertions.assertEquals(true, model.coolAccess()); - Assertions.assertEquals(671328296, model.coolnessPeriod()); - Assertions.assertEquals(CoolAccessRetrievalPolicy.ON_READ, model.coolAccessRetrievalPolicy()); + Assertions.assertEquals(9149907061758969702L, model.defaultUserQuotaInKiBs()); + Assertions.assertEquals(6553380675095809006L, model.defaultGroupQuotaInKiBs()); + Assertions.assertEquals("wbpokulpiujwaasi", model.unixPermissions()); + Assertions.assertEquals(false, model.coolAccess()); + Assertions.assertEquals(1035814224, model.coolnessPeriod()); + Assertions.assertEquals(CoolAccessRetrievalPolicy.NEVER, model.coolAccessRetrievalPolicy()); + Assertions.assertEquals(CoolAccessTieringPolicy.SNAPSHOT_ONLY, model.coolAccessTieringPolicy()); Assertions.assertEquals(false, model.snapshotDirectoryVisible()); - Assertions.assertEquals(SmbAccessBasedEnumeration.DISABLED, model.smbAccessBasedEnumeration()); + Assertions.assertEquals(SmbAccessBasedEnumeration.ENABLED, model.smbAccessBasedEnumeration()); Assertions.assertEquals(SmbNonBrowsable.ENABLED, model.smbNonBrowsable()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - VolumePatchProperties model = new VolumePatchProperties().withServiceLevel(ServiceLevel.PREMIUM) - .withUsageThreshold(5529528892048026868L) - .withExportPolicy(new VolumePatchPropertiesExportPolicy().withRules(Arrays.asList( - new ExportPolicyRule().withRuleIndex(1736041382) - .withUnixReadOnly(false) - .withUnixReadWrite(true) - .withKerberos5ReadOnly(false) - .withKerberos5ReadWrite(true) - .withKerberos5IReadOnly(false) - .withKerberos5IReadWrite(true) - .withKerberos5PReadOnly(true) - .withKerberos5PReadWrite(false) - .withCifs(false) - .withNfsv3(false) - .withNfsv41(true) - .withAllowedClients("hkoymkcdyhbp") - .withHasRootAccess(true) - .withChownMode(ChownMode.UNRESTRICTED), - new ExportPolicyRule().withRuleIndex(668813662) + VolumePatchProperties model = new VolumePatchProperties().withServiceLevel(ServiceLevel.STANDARD_ZRS) + .withUsageThreshold(4652181983896123622L) + .withExportPolicy(new VolumePatchPropertiesExportPolicy() + .withRules(Arrays.asList(new ExportPolicyRule().withRuleIndex(1838860649) .withUnixReadOnly(true) - .withUnixReadWrite(true) - .withKerberos5ReadOnly(true) - .withKerberos5ReadWrite(true) + .withUnixReadWrite(false) + .withKerberos5ReadOnly(false) + .withKerberos5ReadWrite(false) .withKerberos5IReadOnly(false) .withKerberos5IReadWrite(false) .withKerberos5PReadOnly(false) - .withKerberos5PReadWrite(true) + .withKerberos5PReadWrite(false) .withCifs(true) - .withNfsv3(true) - .withNfsv41(true) - .withAllowedClients("sytgadgvraea") - .withHasRootAccess(false) - .withChownMode(ChownMode.RESTRICTED)))) - .withProtocolTypes(Arrays.asList("rrwlquuijfqkace", "iipfpubj")) - .withThroughputMibps(80.4325F) + .withNfsv3(false) + .withNfsv41(false) + .withAllowedClients("qvmkcxo") + .withHasRootAccess(true) + .withChownMode(ChownMode.UNRESTRICTED)))) + .withProtocolTypes(Arrays.asList("xprglyatddc", "cbcuejrjxgciqi", "rhos", "sdqrhzoymibmrq")) + .withThroughputMibps(32.402683F) .withDataProtection(new VolumePatchPropertiesDataProtection() - .withBackup(new VolumeBackupProperties().withBackupPolicyId("tohqkvpuvksgp") + .withBackup(new VolumeBackupProperties().withBackupPolicyId("fluszdtm") .withPolicyEnforced(true) - .withBackupVaultId("nynfsynljphuo")) - .withSnapshot(new VolumeSnapshotProperties().withSnapshotPolicyId("dlqiyntorzih"))) + .withBackupVaultId("ofyyvoqacpi")) + .withSnapshot(new VolumeSnapshotProperties().withSnapshotPolicyId("btgiwbwoenwas"))) .withIsDefaultQuotaEnabled(false) - .withDefaultUserQuotaInKiBs(1763238729707641338L) - .withDefaultGroupQuotaInKiBs(8731733727418388460L) - .withUnixPermissions("slyzrpzbchckqq") - .withCoolAccess(true) - .withCoolnessPeriod(671328296) - .withCoolAccessRetrievalPolicy(CoolAccessRetrievalPolicy.ON_READ) + .withDefaultUserQuotaInKiBs(9149907061758969702L) + .withDefaultGroupQuotaInKiBs(6553380675095809006L) + .withUnixPermissions("wbpokulpiujwaasi") + .withCoolAccess(false) + .withCoolnessPeriod(1035814224) + .withCoolAccessRetrievalPolicy(CoolAccessRetrievalPolicy.NEVER) + .withCoolAccessTieringPolicy(CoolAccessTieringPolicy.SNAPSHOT_ONLY) .withSnapshotDirectoryVisible(false) - .withSmbAccessBasedEnumeration(SmbAccessBasedEnumeration.DISABLED) + .withSmbAccessBasedEnumeration(SmbAccessBasedEnumeration.ENABLED) .withSmbNonBrowsable(SmbNonBrowsable.ENABLED); model = BinaryData.fromObject(model).toObject(VolumePatchProperties.class); - Assertions.assertEquals(ServiceLevel.PREMIUM, model.serviceLevel()); - Assertions.assertEquals(5529528892048026868L, model.usageThreshold()); - Assertions.assertEquals(1736041382, model.exportPolicy().rules().get(0).ruleIndex()); - Assertions.assertEquals(false, model.exportPolicy().rules().get(0).unixReadOnly()); - Assertions.assertEquals(true, model.exportPolicy().rules().get(0).unixReadWrite()); + Assertions.assertEquals(ServiceLevel.STANDARD_ZRS, model.serviceLevel()); + Assertions.assertEquals(4652181983896123622L, model.usageThreshold()); + Assertions.assertEquals(1838860649, model.exportPolicy().rules().get(0).ruleIndex()); + Assertions.assertEquals(true, model.exportPolicy().rules().get(0).unixReadOnly()); + Assertions.assertEquals(false, model.exportPolicy().rules().get(0).unixReadWrite()); Assertions.assertEquals(false, model.exportPolicy().rules().get(0).kerberos5ReadOnly()); - Assertions.assertEquals(true, model.exportPolicy().rules().get(0).kerberos5ReadWrite()); + Assertions.assertEquals(false, model.exportPolicy().rules().get(0).kerberos5ReadWrite()); Assertions.assertEquals(false, model.exportPolicy().rules().get(0).kerberos5IReadOnly()); - Assertions.assertEquals(true, model.exportPolicy().rules().get(0).kerberos5IReadWrite()); - Assertions.assertEquals(true, model.exportPolicy().rules().get(0).kerberos5PReadOnly()); + Assertions.assertEquals(false, model.exportPolicy().rules().get(0).kerberos5IReadWrite()); + Assertions.assertEquals(false, model.exportPolicy().rules().get(0).kerberos5PReadOnly()); Assertions.assertEquals(false, model.exportPolicy().rules().get(0).kerberos5PReadWrite()); - Assertions.assertEquals(false, model.exportPolicy().rules().get(0).cifs()); + Assertions.assertEquals(true, model.exportPolicy().rules().get(0).cifs()); Assertions.assertEquals(false, model.exportPolicy().rules().get(0).nfsv3()); - Assertions.assertEquals(true, model.exportPolicy().rules().get(0).nfsv41()); - Assertions.assertEquals("hkoymkcdyhbp", model.exportPolicy().rules().get(0).allowedClients()); + Assertions.assertEquals(false, model.exportPolicy().rules().get(0).nfsv41()); + Assertions.assertEquals("qvmkcxo", model.exportPolicy().rules().get(0).allowedClients()); Assertions.assertEquals(true, model.exportPolicy().rules().get(0).hasRootAccess()); Assertions.assertEquals(ChownMode.UNRESTRICTED, model.exportPolicy().rules().get(0).chownMode()); - Assertions.assertEquals("rrwlquuijfqkace", model.protocolTypes().get(0)); - Assertions.assertEquals(80.4325F, model.throughputMibps()); - Assertions.assertEquals("tohqkvpuvksgp", model.dataProtection().backup().backupPolicyId()); + Assertions.assertEquals("xprglyatddc", model.protocolTypes().get(0)); + Assertions.assertEquals(32.402683F, model.throughputMibps()); + Assertions.assertEquals("fluszdtm", model.dataProtection().backup().backupPolicyId()); Assertions.assertEquals(true, model.dataProtection().backup().policyEnforced()); - Assertions.assertEquals("nynfsynljphuo", model.dataProtection().backup().backupVaultId()); - Assertions.assertEquals("dlqiyntorzih", model.dataProtection().snapshot().snapshotPolicyId()); + Assertions.assertEquals("ofyyvoqacpi", model.dataProtection().backup().backupVaultId()); + Assertions.assertEquals("btgiwbwoenwas", model.dataProtection().snapshot().snapshotPolicyId()); Assertions.assertEquals(false, model.isDefaultQuotaEnabled()); - Assertions.assertEquals(1763238729707641338L, model.defaultUserQuotaInKiBs()); - Assertions.assertEquals(8731733727418388460L, model.defaultGroupQuotaInKiBs()); - Assertions.assertEquals("slyzrpzbchckqq", model.unixPermissions()); - Assertions.assertEquals(true, model.coolAccess()); - Assertions.assertEquals(671328296, model.coolnessPeriod()); - Assertions.assertEquals(CoolAccessRetrievalPolicy.ON_READ, model.coolAccessRetrievalPolicy()); + Assertions.assertEquals(9149907061758969702L, model.defaultUserQuotaInKiBs()); + Assertions.assertEquals(6553380675095809006L, model.defaultGroupQuotaInKiBs()); + Assertions.assertEquals("wbpokulpiujwaasi", model.unixPermissions()); + Assertions.assertEquals(false, model.coolAccess()); + Assertions.assertEquals(1035814224, model.coolnessPeriod()); + Assertions.assertEquals(CoolAccessRetrievalPolicy.NEVER, model.coolAccessRetrievalPolicy()); + Assertions.assertEquals(CoolAccessTieringPolicy.SNAPSHOT_ONLY, model.coolAccessTieringPolicy()); Assertions.assertEquals(false, model.snapshotDirectoryVisible()); - Assertions.assertEquals(SmbAccessBasedEnumeration.DISABLED, model.smbAccessBasedEnumeration()); + Assertions.assertEquals(SmbAccessBasedEnumeration.ENABLED, model.smbAccessBasedEnumeration()); Assertions.assertEquals(SmbNonBrowsable.ENABLED, model.smbNonBrowsable()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumePatchTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumePatchTests.java index eabbafa23296..640bdf6fbee5 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumePatchTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumePatchTests.java @@ -7,6 +7,7 @@ import com.azure.core.util.BinaryData; import com.azure.resourcemanager.netapp.models.ChownMode; import com.azure.resourcemanager.netapp.models.CoolAccessRetrievalPolicy; +import com.azure.resourcemanager.netapp.models.CoolAccessTieringPolicy; import com.azure.resourcemanager.netapp.models.ExportPolicyRule; import com.azure.resourcemanager.netapp.models.ServiceLevel; import com.azure.resourcemanager.netapp.models.SmbAccessBasedEnumeration; @@ -25,165 +26,168 @@ public final class VolumePatchTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { VolumePatch model = BinaryData.fromString( - "{\"properties\":{\"serviceLevel\":\"Flexible\",\"usageThreshold\":5460739394049509501,\"exportPolicy\":{\"rules\":[{\"ruleIndex\":1665526827,\"unixReadOnly\":false,\"unixReadWrite\":true,\"kerberos5ReadOnly\":false,\"kerberos5ReadWrite\":true,\"kerberos5iReadOnly\":false,\"kerberos5iReadWrite\":true,\"kerberos5pReadOnly\":true,\"kerberos5pReadWrite\":true,\"cifs\":false,\"nfsv3\":true,\"nfsv41\":false,\"allowedClients\":\"dcvd\",\"hasRootAccess\":false,\"chownMode\":\"Unrestricted\"},{\"ruleIndex\":1383619855,\"unixReadOnly\":false,\"unixReadWrite\":true,\"kerberos5ReadOnly\":true,\"kerberos5ReadWrite\":true,\"kerberos5iReadOnly\":false,\"kerberos5iReadWrite\":true,\"kerberos5pReadOnly\":true,\"kerberos5pReadWrite\":false,\"cifs\":false,\"nfsv3\":true,\"nfsv41\":false,\"allowedClients\":\"xrslpm\",\"hasRootAccess\":false,\"chownMode\":\"Unrestricted\"},{\"ruleIndex\":966378800,\"unixReadOnly\":false,\"unixReadWrite\":true,\"kerberos5ReadOnly\":true,\"kerberos5ReadWrite\":false,\"kerberos5iReadOnly\":false,\"kerberos5iReadWrite\":true,\"kerberos5pReadOnly\":false,\"kerberos5pReadWrite\":true,\"cifs\":true,\"nfsv3\":true,\"nfsv41\":false,\"allowedClients\":\"vmbmp\",\"hasRootAccess\":true,\"chownMode\":\"Restricted\"},{\"ruleIndex\":1745081298,\"unixReadOnly\":false,\"unixReadWrite\":false,\"kerberos5ReadOnly\":true,\"kerberos5ReadWrite\":true,\"kerberos5iReadOnly\":false,\"kerberos5iReadWrite\":true,\"kerberos5pReadOnly\":false,\"kerberos5pReadWrite\":false,\"cifs\":false,\"nfsv3\":false,\"nfsv41\":false,\"allowedClients\":\"kcpwiy\",\"hasRootAccess\":true,\"chownMode\":\"Unrestricted\"}]},\"protocolTypes\":[\"bexkpzksmondj\"],\"throughputMibps\":87.20647,\"dataProtection\":{\"backup\":{\"backupPolicyId\":\"pomgkopkwhojvp\",\"policyEnforced\":false,\"backupVaultId\":\"xysmoc\"},\"snapshot\":{\"snapshotPolicyId\":\"fqvm\"}},\"isDefaultQuotaEnabled\":false,\"defaultUserQuotaInKiBs\":9205614201426151802,\"defaultGroupQuotaInKiBs\":5899001695027882086,\"unixPermissions\":\"lxprglyatddckcbc\",\"coolAccess\":true,\"coolnessPeriod\":465544934,\"coolAccessRetrievalPolicy\":\"Never\",\"snapshotDirectoryVisible\":false,\"smbAccessBasedEnumeration\":\"Enabled\",\"smbNonBrowsable\":\"Disabled\"},\"location\":\"hos\",\"tags\":{\"hwflu\":\"qrhzoymibmrqyib\",\"voqacpiexpbt\":\"zdtmhrkwofy\",\"nqxwbp\":\"iwbwoenwashrtdtk\"},\"id\":\"kulpiujwaasi\",\"name\":\"qiiobyuqer\",\"type\":\"qlpqwcciuq\"}") + "{\"properties\":{\"serviceLevel\":\"StandardZRS\",\"usageThreshold\":3596731806020428455,\"exportPolicy\":{\"rules\":[{\"ruleIndex\":506973706,\"unixReadOnly\":true,\"unixReadWrite\":true,\"kerberos5ReadOnly\":true,\"kerberos5ReadWrite\":true,\"kerberos5iReadOnly\":true,\"kerberos5iReadWrite\":true,\"kerberos5pReadOnly\":true,\"kerberos5pReadWrite\":true,\"cifs\":true,\"nfsv3\":false,\"nfsv41\":true,\"allowedClients\":\"gcj\",\"hasRootAccess\":false,\"chownMode\":\"Restricted\"},{\"ruleIndex\":1571088052,\"unixReadOnly\":true,\"unixReadWrite\":false,\"kerberos5ReadOnly\":false,\"kerberos5ReadWrite\":true,\"kerberos5iReadOnly\":false,\"kerberos5iReadWrite\":false,\"kerberos5pReadOnly\":true,\"kerberos5pReadWrite\":false,\"cifs\":true,\"nfsv3\":true,\"nfsv41\":true,\"allowedClients\":\"glkfg\",\"hasRootAccess\":false,\"chownMode\":\"Restricted\"},{\"ruleIndex\":458990624,\"unixReadOnly\":true,\"unixReadWrite\":false,\"kerberos5ReadOnly\":true,\"kerberos5ReadWrite\":true,\"kerberos5iReadOnly\":true,\"kerberos5iReadWrite\":true,\"kerberos5pReadOnly\":false,\"kerberos5pReadWrite\":true,\"cifs\":false,\"nfsv3\":false,\"nfsv41\":false,\"allowedClients\":\"zx\",\"hasRootAccess\":false,\"chownMode\":\"Unrestricted\"},{\"ruleIndex\":1591350946,\"unixReadOnly\":false,\"unixReadWrite\":true,\"kerberos5ReadOnly\":false,\"kerberos5ReadWrite\":true,\"kerberos5iReadOnly\":true,\"kerberos5iReadWrite\":false,\"kerberos5pReadOnly\":false,\"kerberos5pReadWrite\":false,\"cifs\":true,\"nfsv3\":false,\"nfsv41\":false,\"allowedClients\":\"utiiswacf\",\"hasRootAccess\":true,\"chownMode\":\"Unrestricted\"}]},\"protocolTypes\":[\"wkfvhqcrailvp\",\"ppfufl\",\"wdmhdlxyjrxs\"],\"throughputMibps\":37.06115,\"dataProtection\":{\"backup\":{\"backupPolicyId\":\"ihgwqapnedgfbcv\",\"policyEnforced\":false,\"backupVaultId\":\"vpk\"},\"snapshot\":{\"snapshotPolicyId\":\"cvdrhvoodsot\"}},\"isDefaultQuotaEnabled\":false,\"defaultUserQuotaInKiBs\":596884672630210595,\"defaultGroupQuotaInKiBs\":4925429058781882288,\"unixPermissions\":\"vnhdldwmgxcxr\",\"coolAccess\":false,\"coolnessPeriod\":1073132708,\"coolAccessRetrievalPolicy\":\"Never\",\"coolAccessTieringPolicy\":\"SnapshotOnly\",\"snapshotDirectoryVisible\":true,\"smbAccessBasedEnumeration\":\"Disabled\",\"smbNonBrowsable\":\"Enabled\"},\"location\":\"jw\",\"tags\":{\"ggkzzlvmbmpa\":\"qsluicp\",\"yhrfouyftaakcpw\":\"modfvuefywsbpfvm\"},\"id\":\"yzvqt\",\"name\":\"nubexk\",\"type\":\"zksmondj\"}") .toObject(VolumePatch.class); - Assertions.assertEquals("hos", model.location()); - Assertions.assertEquals("qrhzoymibmrqyib", model.tags().get("hwflu")); - Assertions.assertEquals(ServiceLevel.FLEXIBLE, model.serviceLevel()); - Assertions.assertEquals(5460739394049509501L, model.usageThreshold()); - Assertions.assertEquals(1665526827, model.exportPolicy().rules().get(0).ruleIndex()); - Assertions.assertEquals(false, model.exportPolicy().rules().get(0).unixReadOnly()); + Assertions.assertEquals("jw", model.location()); + Assertions.assertEquals("qsluicp", model.tags().get("ggkzzlvmbmpa")); + Assertions.assertEquals(ServiceLevel.STANDARD_ZRS, model.serviceLevel()); + Assertions.assertEquals(3596731806020428455L, model.usageThreshold()); + Assertions.assertEquals(506973706, model.exportPolicy().rules().get(0).ruleIndex()); + Assertions.assertEquals(true, model.exportPolicy().rules().get(0).unixReadOnly()); Assertions.assertEquals(true, model.exportPolicy().rules().get(0).unixReadWrite()); - Assertions.assertEquals(false, model.exportPolicy().rules().get(0).kerberos5ReadOnly()); + Assertions.assertEquals(true, model.exportPolicy().rules().get(0).kerberos5ReadOnly()); Assertions.assertEquals(true, model.exportPolicy().rules().get(0).kerberos5ReadWrite()); - Assertions.assertEquals(false, model.exportPolicy().rules().get(0).kerberos5IReadOnly()); + Assertions.assertEquals(true, model.exportPolicy().rules().get(0).kerberos5IReadOnly()); Assertions.assertEquals(true, model.exportPolicy().rules().get(0).kerberos5IReadWrite()); Assertions.assertEquals(true, model.exportPolicy().rules().get(0).kerberos5PReadOnly()); Assertions.assertEquals(true, model.exportPolicy().rules().get(0).kerberos5PReadWrite()); - Assertions.assertEquals(false, model.exportPolicy().rules().get(0).cifs()); - Assertions.assertEquals(true, model.exportPolicy().rules().get(0).nfsv3()); - Assertions.assertEquals(false, model.exportPolicy().rules().get(0).nfsv41()); - Assertions.assertEquals("dcvd", model.exportPolicy().rules().get(0).allowedClients()); + Assertions.assertEquals(true, model.exportPolicy().rules().get(0).cifs()); + Assertions.assertEquals(false, model.exportPolicy().rules().get(0).nfsv3()); + Assertions.assertEquals(true, model.exportPolicy().rules().get(0).nfsv41()); + Assertions.assertEquals("gcj", model.exportPolicy().rules().get(0).allowedClients()); Assertions.assertEquals(false, model.exportPolicy().rules().get(0).hasRootAccess()); - Assertions.assertEquals(ChownMode.UNRESTRICTED, model.exportPolicy().rules().get(0).chownMode()); - Assertions.assertEquals("bexkpzksmondj", model.protocolTypes().get(0)); - Assertions.assertEquals(87.20647F, model.throughputMibps()); - Assertions.assertEquals("pomgkopkwhojvp", model.dataProtection().backup().backupPolicyId()); + Assertions.assertEquals(ChownMode.RESTRICTED, model.exportPolicy().rules().get(0).chownMode()); + Assertions.assertEquals("wkfvhqcrailvp", model.protocolTypes().get(0)); + Assertions.assertEquals(37.06115F, model.throughputMibps()); + Assertions.assertEquals("ihgwqapnedgfbcv", model.dataProtection().backup().backupPolicyId()); Assertions.assertEquals(false, model.dataProtection().backup().policyEnforced()); - Assertions.assertEquals("xysmoc", model.dataProtection().backup().backupVaultId()); - Assertions.assertEquals("fqvm", model.dataProtection().snapshot().snapshotPolicyId()); + Assertions.assertEquals("vpk", model.dataProtection().backup().backupVaultId()); + Assertions.assertEquals("cvdrhvoodsot", model.dataProtection().snapshot().snapshotPolicyId()); Assertions.assertEquals(false, model.isDefaultQuotaEnabled()); - Assertions.assertEquals(9205614201426151802L, model.defaultUserQuotaInKiBs()); - Assertions.assertEquals(5899001695027882086L, model.defaultGroupQuotaInKiBs()); - Assertions.assertEquals("lxprglyatddckcbc", model.unixPermissions()); - Assertions.assertEquals(true, model.coolAccess()); - Assertions.assertEquals(465544934, model.coolnessPeriod()); + Assertions.assertEquals(596884672630210595L, model.defaultUserQuotaInKiBs()); + Assertions.assertEquals(4925429058781882288L, model.defaultGroupQuotaInKiBs()); + Assertions.assertEquals("vnhdldwmgxcxr", model.unixPermissions()); + Assertions.assertEquals(false, model.coolAccess()); + Assertions.assertEquals(1073132708, model.coolnessPeriod()); Assertions.assertEquals(CoolAccessRetrievalPolicy.NEVER, model.coolAccessRetrievalPolicy()); - Assertions.assertEquals(false, model.snapshotDirectoryVisible()); - Assertions.assertEquals(SmbAccessBasedEnumeration.ENABLED, model.smbAccessBasedEnumeration()); - Assertions.assertEquals(SmbNonBrowsable.DISABLED, model.smbNonBrowsable()); + Assertions.assertEquals(CoolAccessTieringPolicy.SNAPSHOT_ONLY, model.coolAccessTieringPolicy()); + Assertions.assertEquals(true, model.snapshotDirectoryVisible()); + Assertions.assertEquals(SmbAccessBasedEnumeration.DISABLED, model.smbAccessBasedEnumeration()); + Assertions.assertEquals(SmbNonBrowsable.ENABLED, model.smbNonBrowsable()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - VolumePatch model = new VolumePatch().withLocation("hos") - .withTags(mapOf("hwflu", "qrhzoymibmrqyib", "voqacpiexpbt", "zdtmhrkwofy", "nqxwbp", "iwbwoenwashrtdtk")) - .withServiceLevel(ServiceLevel.FLEXIBLE) - .withUsageThreshold(5460739394049509501L) + VolumePatch model = new VolumePatch().withLocation("jw") + .withTags(mapOf("ggkzzlvmbmpa", "qsluicp", "yhrfouyftaakcpw", "modfvuefywsbpfvm")) + .withServiceLevel(ServiceLevel.STANDARD_ZRS) + .withUsageThreshold(3596731806020428455L) .withExportPolicy(new VolumePatchPropertiesExportPolicy().withRules(Arrays.asList( - new ExportPolicyRule().withRuleIndex(1665526827) - .withUnixReadOnly(false) + new ExportPolicyRule().withRuleIndex(506973706) + .withUnixReadOnly(true) .withUnixReadWrite(true) - .withKerberos5ReadOnly(false) + .withKerberos5ReadOnly(true) .withKerberos5ReadWrite(true) - .withKerberos5IReadOnly(false) + .withKerberos5IReadOnly(true) .withKerberos5IReadWrite(true) .withKerberos5PReadOnly(true) .withKerberos5PReadWrite(true) - .withCifs(false) - .withNfsv3(true) - .withNfsv41(false) - .withAllowedClients("dcvd") + .withCifs(true) + .withNfsv3(false) + .withNfsv41(true) + .withAllowedClients("gcj") .withHasRootAccess(false) - .withChownMode(ChownMode.UNRESTRICTED), - new ExportPolicyRule().withRuleIndex(1383619855) - .withUnixReadOnly(false) - .withUnixReadWrite(true) - .withKerberos5ReadOnly(true) + .withChownMode(ChownMode.RESTRICTED), + new ExportPolicyRule().withRuleIndex(1571088052) + .withUnixReadOnly(true) + .withUnixReadWrite(false) + .withKerberos5ReadOnly(false) .withKerberos5ReadWrite(true) .withKerberos5IReadOnly(false) - .withKerberos5IReadWrite(true) + .withKerberos5IReadWrite(false) .withKerberos5PReadOnly(true) .withKerberos5PReadWrite(false) - .withCifs(false) + .withCifs(true) .withNfsv3(true) - .withNfsv41(false) - .withAllowedClients("xrslpm") + .withNfsv41(true) + .withAllowedClients("glkfg") .withHasRootAccess(false) - .withChownMode(ChownMode.UNRESTRICTED), - new ExportPolicyRule().withRuleIndex(966378800) - .withUnixReadOnly(false) - .withUnixReadWrite(true) + .withChownMode(ChownMode.RESTRICTED), + new ExportPolicyRule().withRuleIndex(458990624) + .withUnixReadOnly(true) + .withUnixReadWrite(false) .withKerberos5ReadOnly(true) - .withKerberos5ReadWrite(false) - .withKerberos5IReadOnly(false) + .withKerberos5ReadWrite(true) + .withKerberos5IReadOnly(true) .withKerberos5IReadWrite(true) .withKerberos5PReadOnly(false) .withKerberos5PReadWrite(true) - .withCifs(true) - .withNfsv3(true) + .withCifs(false) + .withNfsv3(false) .withNfsv41(false) - .withAllowedClients("vmbmp") - .withHasRootAccess(true) - .withChownMode(ChownMode.RESTRICTED), - new ExportPolicyRule().withRuleIndex(1745081298) + .withAllowedClients("zx") + .withHasRootAccess(false) + .withChownMode(ChownMode.UNRESTRICTED), + new ExportPolicyRule().withRuleIndex(1591350946) .withUnixReadOnly(false) - .withUnixReadWrite(false) - .withKerberos5ReadOnly(true) + .withUnixReadWrite(true) + .withKerberos5ReadOnly(false) .withKerberos5ReadWrite(true) - .withKerberos5IReadOnly(false) - .withKerberos5IReadWrite(true) + .withKerberos5IReadOnly(true) + .withKerberos5IReadWrite(false) .withKerberos5PReadOnly(false) .withKerberos5PReadWrite(false) - .withCifs(false) + .withCifs(true) .withNfsv3(false) .withNfsv41(false) - .withAllowedClients("kcpwiy") + .withAllowedClients("utiiswacf") .withHasRootAccess(true) .withChownMode(ChownMode.UNRESTRICTED)))) - .withProtocolTypes(Arrays.asList("bexkpzksmondj")) - .withThroughputMibps(87.20647F) + .withProtocolTypes(Arrays.asList("wkfvhqcrailvp", "ppfufl", "wdmhdlxyjrxs")) + .withThroughputMibps(37.06115F) .withDataProtection(new VolumePatchPropertiesDataProtection() - .withBackup(new VolumeBackupProperties().withBackupPolicyId("pomgkopkwhojvp") + .withBackup(new VolumeBackupProperties().withBackupPolicyId("ihgwqapnedgfbcv") .withPolicyEnforced(false) - .withBackupVaultId("xysmoc")) - .withSnapshot(new VolumeSnapshotProperties().withSnapshotPolicyId("fqvm"))) + .withBackupVaultId("vpk")) + .withSnapshot(new VolumeSnapshotProperties().withSnapshotPolicyId("cvdrhvoodsot"))) .withIsDefaultQuotaEnabled(false) - .withDefaultUserQuotaInKiBs(9205614201426151802L) - .withDefaultGroupQuotaInKiBs(5899001695027882086L) - .withUnixPermissions("lxprglyatddckcbc") - .withCoolAccess(true) - .withCoolnessPeriod(465544934) + .withDefaultUserQuotaInKiBs(596884672630210595L) + .withDefaultGroupQuotaInKiBs(4925429058781882288L) + .withUnixPermissions("vnhdldwmgxcxr") + .withCoolAccess(false) + .withCoolnessPeriod(1073132708) .withCoolAccessRetrievalPolicy(CoolAccessRetrievalPolicy.NEVER) - .withSnapshotDirectoryVisible(false) - .withSmbAccessBasedEnumeration(SmbAccessBasedEnumeration.ENABLED) - .withSmbNonBrowsable(SmbNonBrowsable.DISABLED); + .withCoolAccessTieringPolicy(CoolAccessTieringPolicy.SNAPSHOT_ONLY) + .withSnapshotDirectoryVisible(true) + .withSmbAccessBasedEnumeration(SmbAccessBasedEnumeration.DISABLED) + .withSmbNonBrowsable(SmbNonBrowsable.ENABLED); model = BinaryData.fromObject(model).toObject(VolumePatch.class); - Assertions.assertEquals("hos", model.location()); - Assertions.assertEquals("qrhzoymibmrqyib", model.tags().get("hwflu")); - Assertions.assertEquals(ServiceLevel.FLEXIBLE, model.serviceLevel()); - Assertions.assertEquals(5460739394049509501L, model.usageThreshold()); - Assertions.assertEquals(1665526827, model.exportPolicy().rules().get(0).ruleIndex()); - Assertions.assertEquals(false, model.exportPolicy().rules().get(0).unixReadOnly()); + Assertions.assertEquals("jw", model.location()); + Assertions.assertEquals("qsluicp", model.tags().get("ggkzzlvmbmpa")); + Assertions.assertEquals(ServiceLevel.STANDARD_ZRS, model.serviceLevel()); + Assertions.assertEquals(3596731806020428455L, model.usageThreshold()); + Assertions.assertEquals(506973706, model.exportPolicy().rules().get(0).ruleIndex()); + Assertions.assertEquals(true, model.exportPolicy().rules().get(0).unixReadOnly()); Assertions.assertEquals(true, model.exportPolicy().rules().get(0).unixReadWrite()); - Assertions.assertEquals(false, model.exportPolicy().rules().get(0).kerberos5ReadOnly()); + Assertions.assertEquals(true, model.exportPolicy().rules().get(0).kerberos5ReadOnly()); Assertions.assertEquals(true, model.exportPolicy().rules().get(0).kerberos5ReadWrite()); - Assertions.assertEquals(false, model.exportPolicy().rules().get(0).kerberos5IReadOnly()); + Assertions.assertEquals(true, model.exportPolicy().rules().get(0).kerberos5IReadOnly()); Assertions.assertEquals(true, model.exportPolicy().rules().get(0).kerberos5IReadWrite()); Assertions.assertEquals(true, model.exportPolicy().rules().get(0).kerberos5PReadOnly()); Assertions.assertEquals(true, model.exportPolicy().rules().get(0).kerberos5PReadWrite()); - Assertions.assertEquals(false, model.exportPolicy().rules().get(0).cifs()); - Assertions.assertEquals(true, model.exportPolicy().rules().get(0).nfsv3()); - Assertions.assertEquals(false, model.exportPolicy().rules().get(0).nfsv41()); - Assertions.assertEquals("dcvd", model.exportPolicy().rules().get(0).allowedClients()); + Assertions.assertEquals(true, model.exportPolicy().rules().get(0).cifs()); + Assertions.assertEquals(false, model.exportPolicy().rules().get(0).nfsv3()); + Assertions.assertEquals(true, model.exportPolicy().rules().get(0).nfsv41()); + Assertions.assertEquals("gcj", model.exportPolicy().rules().get(0).allowedClients()); Assertions.assertEquals(false, model.exportPolicy().rules().get(0).hasRootAccess()); - Assertions.assertEquals(ChownMode.UNRESTRICTED, model.exportPolicy().rules().get(0).chownMode()); - Assertions.assertEquals("bexkpzksmondj", model.protocolTypes().get(0)); - Assertions.assertEquals(87.20647F, model.throughputMibps()); - Assertions.assertEquals("pomgkopkwhojvp", model.dataProtection().backup().backupPolicyId()); + Assertions.assertEquals(ChownMode.RESTRICTED, model.exportPolicy().rules().get(0).chownMode()); + Assertions.assertEquals("wkfvhqcrailvp", model.protocolTypes().get(0)); + Assertions.assertEquals(37.06115F, model.throughputMibps()); + Assertions.assertEquals("ihgwqapnedgfbcv", model.dataProtection().backup().backupPolicyId()); Assertions.assertEquals(false, model.dataProtection().backup().policyEnforced()); - Assertions.assertEquals("xysmoc", model.dataProtection().backup().backupVaultId()); - Assertions.assertEquals("fqvm", model.dataProtection().snapshot().snapshotPolicyId()); + Assertions.assertEquals("vpk", model.dataProtection().backup().backupVaultId()); + Assertions.assertEquals("cvdrhvoodsot", model.dataProtection().snapshot().snapshotPolicyId()); Assertions.assertEquals(false, model.isDefaultQuotaEnabled()); - Assertions.assertEquals(9205614201426151802L, model.defaultUserQuotaInKiBs()); - Assertions.assertEquals(5899001695027882086L, model.defaultGroupQuotaInKiBs()); - Assertions.assertEquals("lxprglyatddckcbc", model.unixPermissions()); - Assertions.assertEquals(true, model.coolAccess()); - Assertions.assertEquals(465544934, model.coolnessPeriod()); + Assertions.assertEquals(596884672630210595L, model.defaultUserQuotaInKiBs()); + Assertions.assertEquals(4925429058781882288L, model.defaultGroupQuotaInKiBs()); + Assertions.assertEquals("vnhdldwmgxcxr", model.unixPermissions()); + Assertions.assertEquals(false, model.coolAccess()); + Assertions.assertEquals(1073132708, model.coolnessPeriod()); Assertions.assertEquals(CoolAccessRetrievalPolicy.NEVER, model.coolAccessRetrievalPolicy()); - Assertions.assertEquals(false, model.snapshotDirectoryVisible()); - Assertions.assertEquals(SmbAccessBasedEnumeration.ENABLED, model.smbAccessBasedEnumeration()); - Assertions.assertEquals(SmbNonBrowsable.DISABLED, model.smbNonBrowsable()); + Assertions.assertEquals(CoolAccessTieringPolicy.SNAPSHOT_ONLY, model.coolAccessTieringPolicy()); + Assertions.assertEquals(true, model.snapshotDirectoryVisible()); + Assertions.assertEquals(SmbAccessBasedEnumeration.DISABLED, model.smbAccessBasedEnumeration()); + Assertions.assertEquals(SmbNonBrowsable.ENABLED, model.smbNonBrowsable()); } // Use "Map.of" if available diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumePropertiesDataProtectionTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumePropertiesDataProtectionTests.java index d93c1f343576..3c5f762feabf 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumePropertiesDataProtectionTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumePropertiesDataProtectionTests.java @@ -19,49 +19,49 @@ public final class VolumePropertiesDataProtectionTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { VolumePropertiesDataProtection model = BinaryData.fromString( - "{\"backup\":{\"backupPolicyId\":\"fthnzdn\",\"policyEnforced\":false,\"backupVaultId\":\"nayqi\"},\"replication\":{\"replicationId\":\"duhavhqlkt\",\"endpointType\":\"dst\",\"replicationSchedule\":\"hourly\",\"remoteVolumeResourceId\":\"lbg\",\"remotePath\":{\"externalHostName\":\"duiertgcc\",\"serverName\":\"mvaolps\",\"volumeName\":\"lqlfm\"},\"remoteVolumeRegion\":\"n\",\"destinationReplications\":[{\"resourceId\":\"zpswiydmc\",\"replicationType\":\"CrossZoneReplication\",\"region\":\"dxssadbzm\",\"zone\":\"dfznudaodv\"},{\"resourceId\":\"bncblylpstdbhhx\",\"replicationType\":\"CrossZoneReplication\",\"region\":\"zucerscdntnev\",\"zone\":\"wjmy\"},{\"resourceId\":\"dsslswt\",\"replicationType\":\"CrossZoneReplication\",\"region\":\"iofz\",\"zone\":\"qsemwabne\"}]},\"snapshot\":{\"snapshotPolicyId\":\"hszhedplvwiwu\"},\"volumeRelocation\":{\"relocationRequested\":false,\"readyToBeFinalized\":false}}") + "{\"backup\":{\"backupPolicyId\":\"cym\",\"policyEnforced\":true,\"backupVaultId\":\"psslqlfmm\"},\"replication\":{\"replicationId\":\"bglzpswi\",\"endpointType\":\"dst\",\"replicationSchedule\":\"hourly\",\"remoteVolumeResourceId\":\"hzdxssadbzm\",\"remotePath\":{\"externalHostName\":\"dfznudaodv\",\"serverName\":\"zbn\",\"volumeName\":\"blylpstdbh\"},\"remoteVolumeRegion\":\"srzdzucerscdn\"},\"snapshot\":{\"snapshotPolicyId\":\"vfiwjmygtdss\"},\"volumeRelocation\":{\"relocationRequested\":true,\"readyToBeFinalized\":true}}") .toObject(VolumePropertiesDataProtection.class); - Assertions.assertEquals("fthnzdn", model.backup().backupPolicyId()); - Assertions.assertEquals(false, model.backup().policyEnforced()); - Assertions.assertEquals("nayqi", model.backup().backupVaultId()); + Assertions.assertEquals("cym", model.backup().backupPolicyId()); + Assertions.assertEquals(true, model.backup().policyEnforced()); + Assertions.assertEquals("psslqlfmm", model.backup().backupVaultId()); Assertions.assertEquals(EndpointType.DST, model.replication().endpointType()); Assertions.assertEquals(ReplicationSchedule.HOURLY, model.replication().replicationSchedule()); - Assertions.assertEquals("lbg", model.replication().remoteVolumeResourceId()); - Assertions.assertEquals("duiertgcc", model.replication().remotePath().externalHostname()); - Assertions.assertEquals("mvaolps", model.replication().remotePath().serverName()); - Assertions.assertEquals("lqlfm", model.replication().remotePath().volumeName()); - Assertions.assertEquals("n", model.replication().remoteVolumeRegion()); - Assertions.assertEquals("hszhedplvwiwu", model.snapshot().snapshotPolicyId()); - Assertions.assertEquals(false, model.volumeRelocation().relocationRequested()); + Assertions.assertEquals("hzdxssadbzm", model.replication().remoteVolumeResourceId()); + Assertions.assertEquals("dfznudaodv", model.replication().remotePath().externalHostname()); + Assertions.assertEquals("zbn", model.replication().remotePath().serverName()); + Assertions.assertEquals("blylpstdbh", model.replication().remotePath().volumeName()); + Assertions.assertEquals("srzdzucerscdn", model.replication().remoteVolumeRegion()); + Assertions.assertEquals("vfiwjmygtdss", model.snapshot().snapshotPolicyId()); + Assertions.assertEquals(true, model.volumeRelocation().relocationRequested()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { VolumePropertiesDataProtection model = new VolumePropertiesDataProtection() - .withBackup(new VolumeBackupProperties().withBackupPolicyId("fthnzdn") - .withPolicyEnforced(false) - .withBackupVaultId("nayqi")) + .withBackup(new VolumeBackupProperties().withBackupPolicyId("cym") + .withPolicyEnforced(true) + .withBackupVaultId("psslqlfmm")) .withReplication(new ReplicationObject().withEndpointType(EndpointType.DST) .withReplicationSchedule(ReplicationSchedule.HOURLY) - .withRemoteVolumeResourceId("lbg") - .withRemotePath(new RemotePath().withExternalHostname("duiertgcc") - .withServerName("mvaolps") - .withVolumeName("lqlfm")) - .withRemoteVolumeRegion("n")) - .withSnapshot(new VolumeSnapshotProperties().withSnapshotPolicyId("hszhedplvwiwu")) - .withVolumeRelocation(new VolumeRelocationProperties().withRelocationRequested(false)); + .withRemoteVolumeResourceId("hzdxssadbzm") + .withRemotePath(new RemotePath().withExternalHostname("dfznudaodv") + .withServerName("zbn") + .withVolumeName("blylpstdbh")) + .withRemoteVolumeRegion("srzdzucerscdn")) + .withSnapshot(new VolumeSnapshotProperties().withSnapshotPolicyId("vfiwjmygtdss")) + .withVolumeRelocation(new VolumeRelocationProperties().withRelocationRequested(true)); model = BinaryData.fromObject(model).toObject(VolumePropertiesDataProtection.class); - Assertions.assertEquals("fthnzdn", model.backup().backupPolicyId()); - Assertions.assertEquals(false, model.backup().policyEnforced()); - Assertions.assertEquals("nayqi", model.backup().backupVaultId()); + Assertions.assertEquals("cym", model.backup().backupPolicyId()); + Assertions.assertEquals(true, model.backup().policyEnforced()); + Assertions.assertEquals("psslqlfmm", model.backup().backupVaultId()); Assertions.assertEquals(EndpointType.DST, model.replication().endpointType()); Assertions.assertEquals(ReplicationSchedule.HOURLY, model.replication().replicationSchedule()); - Assertions.assertEquals("lbg", model.replication().remoteVolumeResourceId()); - Assertions.assertEquals("duiertgcc", model.replication().remotePath().externalHostname()); - Assertions.assertEquals("mvaolps", model.replication().remotePath().serverName()); - Assertions.assertEquals("lqlfm", model.replication().remotePath().volumeName()); - Assertions.assertEquals("n", model.replication().remoteVolumeRegion()); - Assertions.assertEquals("hszhedplvwiwu", model.snapshot().snapshotPolicyId()); - Assertions.assertEquals(false, model.volumeRelocation().relocationRequested()); + Assertions.assertEquals("hzdxssadbzm", model.replication().remoteVolumeResourceId()); + Assertions.assertEquals("dfznudaodv", model.replication().remotePath().externalHostname()); + Assertions.assertEquals("zbn", model.replication().remotePath().serverName()); + Assertions.assertEquals("blylpstdbh", model.replication().remotePath().volumeName()); + Assertions.assertEquals("srzdzucerscdn", model.replication().remoteVolumeRegion()); + Assertions.assertEquals("vfiwjmygtdss", model.snapshot().snapshotPolicyId()); + Assertions.assertEquals(true, model.volumeRelocation().relocationRequested()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumePropertiesExportPolicyTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumePropertiesExportPolicyTests.java index 0dd8cba91b54..e013e866ce68 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumePropertiesExportPolicyTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumePropertiesExportPolicyTests.java @@ -15,21 +15,21 @@ public final class VolumePropertiesExportPolicyTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { VolumePropertiesExportPolicy model = BinaryData.fromString( - "{\"rules\":[{\"ruleIndex\":393815457,\"unixReadOnly\":false,\"unixReadWrite\":true,\"kerberos5ReadOnly\":true,\"kerberos5ReadWrite\":false,\"kerberos5iReadOnly\":true,\"kerberos5iReadWrite\":false,\"kerberos5pReadOnly\":true,\"kerberos5pReadWrite\":false,\"cifs\":false,\"nfsv3\":false,\"nfsv41\":true,\"allowedClients\":\"blytk\",\"hasRootAccess\":false,\"chownMode\":\"Unrestricted\"},{\"ruleIndex\":1562521656,\"unixReadOnly\":true,\"unixReadWrite\":false,\"kerberos5ReadOnly\":true,\"kerberos5ReadWrite\":false,\"kerberos5iReadOnly\":true,\"kerberos5iReadWrite\":true,\"kerberos5pReadOnly\":false,\"kerberos5pReadWrite\":false,\"cifs\":true,\"nfsv3\":false,\"nfsv41\":false,\"allowedClients\":\"vasrruvwb\",\"hasRootAccess\":true,\"chownMode\":\"Restricted\"},{\"ruleIndex\":332567109,\"unixReadOnly\":false,\"unixReadWrite\":false,\"kerberos5ReadOnly\":false,\"kerberos5ReadWrite\":true,\"kerberos5iReadOnly\":true,\"kerberos5iReadWrite\":true,\"kerberos5pReadOnly\":true,\"kerberos5pReadWrite\":true,\"cifs\":false,\"nfsv3\":false,\"nfsv41\":false,\"allowedClients\":\"t\",\"hasRootAccess\":false,\"chownMode\":\"Unrestricted\"}]}") + "{\"rules\":[{\"ruleIndex\":92665469,\"unixReadOnly\":false,\"unixReadWrite\":false,\"kerberos5ReadOnly\":true,\"kerberos5ReadWrite\":false,\"kerberos5iReadOnly\":false,\"kerberos5iReadWrite\":true,\"kerberos5pReadOnly\":true,\"kerberos5pReadWrite\":true,\"cifs\":false,\"nfsv3\":true,\"nfsv41\":false,\"allowedClients\":\"vshqjohxcr\",\"hasRootAccess\":false,\"chownMode\":\"Unrestricted\"},{\"ruleIndex\":1966093769,\"unixReadOnly\":false,\"unixReadWrite\":false,\"kerberos5ReadOnly\":true,\"kerberos5ReadWrite\":true,\"kerberos5iReadOnly\":true,\"kerberos5iReadWrite\":true,\"kerberos5pReadOnly\":true,\"kerberos5pReadWrite\":false,\"cifs\":false,\"nfsv3\":false,\"nfsv41\":true,\"allowedClients\":\"bsrfbj\",\"hasRootAccess\":false,\"chownMode\":\"Restricted\"},{\"ruleIndex\":1365200524,\"unixReadOnly\":true,\"unixReadWrite\":false,\"kerberos5ReadOnly\":true,\"kerberos5ReadWrite\":true,\"kerberos5iReadOnly\":false,\"kerberos5iReadWrite\":false,\"kerberos5pReadOnly\":true,\"kerberos5pReadWrite\":true,\"cifs\":false,\"nfsv3\":false,\"nfsv41\":false,\"allowedClients\":\"qtaruoujmkcjhwq\",\"hasRootAccess\":true,\"chownMode\":\"Restricted\"}]}") .toObject(VolumePropertiesExportPolicy.class); - Assertions.assertEquals(393815457, model.rules().get(0).ruleIndex()); + Assertions.assertEquals(92665469, model.rules().get(0).ruleIndex()); Assertions.assertEquals(false, model.rules().get(0).unixReadOnly()); - Assertions.assertEquals(true, model.rules().get(0).unixReadWrite()); + Assertions.assertEquals(false, model.rules().get(0).unixReadWrite()); Assertions.assertEquals(true, model.rules().get(0).kerberos5ReadOnly()); Assertions.assertEquals(false, model.rules().get(0).kerberos5ReadWrite()); - Assertions.assertEquals(true, model.rules().get(0).kerberos5IReadOnly()); - Assertions.assertEquals(false, model.rules().get(0).kerberos5IReadWrite()); + Assertions.assertEquals(false, model.rules().get(0).kerberos5IReadOnly()); + Assertions.assertEquals(true, model.rules().get(0).kerberos5IReadWrite()); Assertions.assertEquals(true, model.rules().get(0).kerberos5PReadOnly()); - Assertions.assertEquals(false, model.rules().get(0).kerberos5PReadWrite()); + Assertions.assertEquals(true, model.rules().get(0).kerberos5PReadWrite()); Assertions.assertEquals(false, model.rules().get(0).cifs()); - Assertions.assertEquals(false, model.rules().get(0).nfsv3()); - Assertions.assertEquals(true, model.rules().get(0).nfsv41()); - Assertions.assertEquals("blytk", model.rules().get(0).allowedClients()); + Assertions.assertEquals(true, model.rules().get(0).nfsv3()); + Assertions.assertEquals(false, model.rules().get(0).nfsv41()); + Assertions.assertEquals("vshqjohxcr", model.rules().get(0).allowedClients()); Assertions.assertEquals(false, model.rules().get(0).hasRootAccess()); Assertions.assertEquals(ChownMode.UNRESTRICTED, model.rules().get(0).chownMode()); } @@ -37,65 +37,65 @@ public void testDeserialize() throws Exception { @org.junit.jupiter.api.Test public void testSerialize() throws Exception { VolumePropertiesExportPolicy model = new VolumePropertiesExportPolicy().withRules(Arrays.asList( - new ExportPolicyRule().withRuleIndex(393815457) + new ExportPolicyRule().withRuleIndex(92665469) .withUnixReadOnly(false) - .withUnixReadWrite(true) + .withUnixReadWrite(false) .withKerberos5ReadOnly(true) .withKerberos5ReadWrite(false) - .withKerberos5IReadOnly(true) - .withKerberos5IReadWrite(false) + .withKerberos5IReadOnly(false) + .withKerberos5IReadWrite(true) .withKerberos5PReadOnly(true) - .withKerberos5PReadWrite(false) + .withKerberos5PReadWrite(true) .withCifs(false) - .withNfsv3(false) - .withNfsv41(true) - .withAllowedClients("blytk") + .withNfsv3(true) + .withNfsv41(false) + .withAllowedClients("vshqjohxcr") .withHasRootAccess(false) .withChownMode(ChownMode.UNRESTRICTED), - new ExportPolicyRule().withRuleIndex(1562521656) - .withUnixReadOnly(true) + new ExportPolicyRule().withRuleIndex(1966093769) + .withUnixReadOnly(false) .withUnixReadWrite(false) .withKerberos5ReadOnly(true) - .withKerberos5ReadWrite(false) + .withKerberos5ReadWrite(true) .withKerberos5IReadOnly(true) .withKerberos5IReadWrite(true) - .withKerberos5PReadOnly(false) + .withKerberos5PReadOnly(true) .withKerberos5PReadWrite(false) - .withCifs(true) + .withCifs(false) .withNfsv3(false) - .withNfsv41(false) - .withAllowedClients("vasrruvwb") - .withHasRootAccess(true) + .withNfsv41(true) + .withAllowedClients("bsrfbj") + .withHasRootAccess(false) .withChownMode(ChownMode.RESTRICTED), - new ExportPolicyRule().withRuleIndex(332567109) - .withUnixReadOnly(false) + new ExportPolicyRule().withRuleIndex(1365200524) + .withUnixReadOnly(true) .withUnixReadWrite(false) - .withKerberos5ReadOnly(false) + .withKerberos5ReadOnly(true) .withKerberos5ReadWrite(true) - .withKerberos5IReadOnly(true) - .withKerberos5IReadWrite(true) + .withKerberos5IReadOnly(false) + .withKerberos5IReadWrite(false) .withKerberos5PReadOnly(true) .withKerberos5PReadWrite(true) .withCifs(false) .withNfsv3(false) .withNfsv41(false) - .withAllowedClients("t") - .withHasRootAccess(false) - .withChownMode(ChownMode.UNRESTRICTED))); + .withAllowedClients("qtaruoujmkcjhwq") + .withHasRootAccess(true) + .withChownMode(ChownMode.RESTRICTED))); model = BinaryData.fromObject(model).toObject(VolumePropertiesExportPolicy.class); - Assertions.assertEquals(393815457, model.rules().get(0).ruleIndex()); + Assertions.assertEquals(92665469, model.rules().get(0).ruleIndex()); Assertions.assertEquals(false, model.rules().get(0).unixReadOnly()); - Assertions.assertEquals(true, model.rules().get(0).unixReadWrite()); + Assertions.assertEquals(false, model.rules().get(0).unixReadWrite()); Assertions.assertEquals(true, model.rules().get(0).kerberos5ReadOnly()); Assertions.assertEquals(false, model.rules().get(0).kerberos5ReadWrite()); - Assertions.assertEquals(true, model.rules().get(0).kerberos5IReadOnly()); - Assertions.assertEquals(false, model.rules().get(0).kerberos5IReadWrite()); + Assertions.assertEquals(false, model.rules().get(0).kerberos5IReadOnly()); + Assertions.assertEquals(true, model.rules().get(0).kerberos5IReadWrite()); Assertions.assertEquals(true, model.rules().get(0).kerberos5PReadOnly()); - Assertions.assertEquals(false, model.rules().get(0).kerberos5PReadWrite()); + Assertions.assertEquals(true, model.rules().get(0).kerberos5PReadWrite()); Assertions.assertEquals(false, model.rules().get(0).cifs()); - Assertions.assertEquals(false, model.rules().get(0).nfsv3()); - Assertions.assertEquals(true, model.rules().get(0).nfsv41()); - Assertions.assertEquals("blytk", model.rules().get(0).allowedClients()); + Assertions.assertEquals(true, model.rules().get(0).nfsv3()); + Assertions.assertEquals(false, model.rules().get(0).nfsv41()); + Assertions.assertEquals("vshqjohxcr", model.rules().get(0).allowedClients()); Assertions.assertEquals(false, model.rules().get(0).hasRootAccess()); Assertions.assertEquals(ChownMode.UNRESTRICTED, model.rules().get(0).chownMode()); } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRuleInnerTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRuleInnerTests.java index ba6a5a1f3e12..1367da14731f 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRuleInnerTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRuleInnerTests.java @@ -15,28 +15,28 @@ public final class VolumeQuotaRuleInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { VolumeQuotaRuleInner model = BinaryData.fromString( - "{\"properties\":{\"provisioningState\":\"Moving\",\"quotaSizeInKiBs\":2185926262396381637,\"quotaType\":\"DefaultGroupQuota\",\"quotaTarget\":\"zphv\"},\"location\":\"uyqncygupkvipmd\",\"tags\":{\"totxhojujb\":\"xqupevzhf\"},\"id\":\"pelmcuvhixbjxyf\",\"name\":\"n\",\"type\":\"lrcoolsttpki\"}") + "{\"properties\":{\"provisioningState\":\"Accepted\",\"quotaSizeInKiBs\":7094966123838230661,\"quotaType\":\"IndividualGroupQuota\",\"quotaTarget\":\"fcdmqnrojlpijn\"},\"location\":\"xfrdd\",\"tags\":{\"ronasxift\":\"atiz\",\"zh\":\"zq\"},\"id\":\"tw\",\"name\":\"sgogczhonnxk\",\"type\":\"lgnyhmo\"}") .toObject(VolumeQuotaRuleInner.class); - Assertions.assertEquals("uyqncygupkvipmd", model.location()); - Assertions.assertEquals("xqupevzhf", model.tags().get("totxhojujb")); - Assertions.assertEquals(2185926262396381637L, model.quotaSizeInKiBs()); - Assertions.assertEquals(Type.DEFAULT_GROUP_QUOTA, model.quotaType()); - Assertions.assertEquals("zphv", model.quotaTarget()); + Assertions.assertEquals("xfrdd", model.location()); + Assertions.assertEquals("atiz", model.tags().get("ronasxift")); + Assertions.assertEquals(7094966123838230661L, model.quotaSizeInKiBs()); + Assertions.assertEquals(Type.INDIVIDUAL_GROUP_QUOTA, model.quotaType()); + Assertions.assertEquals("fcdmqnrojlpijn", model.quotaTarget()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - VolumeQuotaRuleInner model = new VolumeQuotaRuleInner().withLocation("uyqncygupkvipmd") - .withTags(mapOf("totxhojujb", "xqupevzhf")) - .withQuotaSizeInKiBs(2185926262396381637L) - .withQuotaType(Type.DEFAULT_GROUP_QUOTA) - .withQuotaTarget("zphv"); + VolumeQuotaRuleInner model = new VolumeQuotaRuleInner().withLocation("xfrdd") + .withTags(mapOf("ronasxift", "atiz", "zh", "zq")) + .withQuotaSizeInKiBs(7094966123838230661L) + .withQuotaType(Type.INDIVIDUAL_GROUP_QUOTA) + .withQuotaTarget("fcdmqnrojlpijn"); model = BinaryData.fromObject(model).toObject(VolumeQuotaRuleInner.class); - Assertions.assertEquals("uyqncygupkvipmd", model.location()); - Assertions.assertEquals("xqupevzhf", model.tags().get("totxhojujb")); - Assertions.assertEquals(2185926262396381637L, model.quotaSizeInKiBs()); - Assertions.assertEquals(Type.DEFAULT_GROUP_QUOTA, model.quotaType()); - Assertions.assertEquals("zphv", model.quotaTarget()); + Assertions.assertEquals("xfrdd", model.location()); + Assertions.assertEquals("atiz", model.tags().get("ronasxift")); + Assertions.assertEquals(7094966123838230661L, model.quotaSizeInKiBs()); + Assertions.assertEquals(Type.INDIVIDUAL_GROUP_QUOTA, model.quotaType()); + Assertions.assertEquals("fcdmqnrojlpijn", model.quotaTarget()); } // Use "Map.of" if available diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulePatchTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulePatchTests.java index 95e5b79eced7..f2b58f7abe93 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulePatchTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulePatchTests.java @@ -15,25 +15,27 @@ public final class VolumeQuotaRulePatchTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { VolumeQuotaRulePatch model = BinaryData.fromString( - "{\"tags\":{\"xcbihw\":\"ithtywu\",\"twjchrdg\":\"knfd\"},\"properties\":{\"provisioningState\":\"Creating\",\"quotaSizeInKiBs\":7107037042754238104,\"quotaType\":\"DefaultUserQuota\",\"quotaTarget\":\"ndz\"}}") + "{\"tags\":{\"svbuswdvzyy\":\"xvcxgfrpdsofbshr\",\"awnopqgikyzirtxd\":\"ycnunvjsrtk\",\"ioilqukrydxtq\":\"uxzejntpsew\",\"ghhavgrvkffo\":\"ieoxorggufhyaomt\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"quotaSizeInKiBs\":5645922877678061686,\"quotaType\":\"DefaultUserQuota\",\"quotaTarget\":\"jmfxumvf\"}}") .toObject(VolumeQuotaRulePatch.class); - Assertions.assertEquals("ithtywu", model.tags().get("xcbihw")); - Assertions.assertEquals(7107037042754238104L, model.quotaSizeInKiBs()); + Assertions.assertEquals("xvcxgfrpdsofbshr", model.tags().get("svbuswdvzyy")); + Assertions.assertEquals(5645922877678061686L, model.quotaSizeInKiBs()); Assertions.assertEquals(Type.DEFAULT_USER_QUOTA, model.quotaType()); - Assertions.assertEquals("ndz", model.quotaTarget()); + Assertions.assertEquals("jmfxumvf", model.quotaTarget()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - VolumeQuotaRulePatch model = new VolumeQuotaRulePatch().withTags(mapOf("xcbihw", "ithtywu", "twjchrdg", "knfd")) - .withQuotaSizeInKiBs(7107037042754238104L) + VolumeQuotaRulePatch model = new VolumeQuotaRulePatch() + .withTags(mapOf("svbuswdvzyy", "xvcxgfrpdsofbshr", "awnopqgikyzirtxd", "ycnunvjsrtk", "ioilqukrydxtq", + "uxzejntpsew", "ghhavgrvkffo", "ieoxorggufhyaomt")) + .withQuotaSizeInKiBs(5645922877678061686L) .withQuotaType(Type.DEFAULT_USER_QUOTA) - .withQuotaTarget("ndz"); + .withQuotaTarget("jmfxumvf"); model = BinaryData.fromObject(model).toObject(VolumeQuotaRulePatch.class); - Assertions.assertEquals("ithtywu", model.tags().get("xcbihw")); - Assertions.assertEquals(7107037042754238104L, model.quotaSizeInKiBs()); + Assertions.assertEquals("xvcxgfrpdsofbshr", model.tags().get("svbuswdvzyy")); + Assertions.assertEquals(5645922877678061686L, model.quotaSizeInKiBs()); Assertions.assertEquals(Type.DEFAULT_USER_QUOTA, model.quotaType()); - Assertions.assertEquals("ndz", model.quotaTarget()); + Assertions.assertEquals("jmfxumvf", model.quotaTarget()); } // Use "Map.of" if available diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesCreateMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesCreateMockTests.java index 252460f4a509..757e39fda969 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesCreateMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesCreateMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.Type; @@ -24,30 +24,30 @@ public final class VolumeQuotaRulesCreateMockTests { @Test public void testCreate() throws Exception { String responseStr - = "{\"properties\":{\"provisioningState\":\"Succeeded\",\"quotaSizeInKiBs\":8137290998530659210,\"quotaType\":\"IndividualGroupQuota\",\"quotaTarget\":\"bze\"},\"location\":\"whoqhnlbqnbldxe\",\"tags\":{\"oucs\":\"gschorimkrsrr\"},\"id\":\"fldpuviyfc\",\"name\":\"abeolhbhlvbm\",\"type\":\"uqibsxtkcu\"}"; + = "{\"properties\":{\"provisioningState\":\"Succeeded\",\"quotaSizeInKiBs\":4495626237459310184,\"quotaType\":\"DefaultUserQuota\",\"quotaTarget\":\"urbuhhlkyqltq\"},\"location\":\"ogtu\",\"tags\":{\"n\":\"fdjktsysidfvclgl\",\"qogsfikayian\":\"uijtkbu\",\"t\":\"haru\",\"yjqtt\":\"iqxf\"},\"id\":\"wkpqhjpenuygbq\",\"name\":\"qqekewvnqvcdlgu\",\"type\":\"ucmfdj\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); VolumeQuotaRule response = manager.volumeQuotaRules() - .define("ybww") - .withRegion("f") - .withExistingVolume("dtfgxqbawpcbb", "zqcyknap", "ofyuicd", "zb") - .withTags(mapOf("ccrrvweyoxoyyu", "muvapc", "oqboshbragapyyr", "phaimmoi", "pavbo", "fsv")) - .withQuotaSizeInKiBs(3215408047972779814L) - .withQuotaType(Type.DEFAULT_GROUP_QUOTA) - .withQuotaTarget("m") + .define("jbgdlfgtdysnaquf") + .withRegion("yjleziunjx") + .withExistingVolume("o", "gebx", "cnwfepbnwgfmxjg", "g") + .withTags(mapOf("qa", "antkwcegyamlbns", "m", "jjvpilguooqja", "hrtdtpdelq", "itgueiookjbs")) + .withQuotaSizeInKiBs(989283416847724320L) + .withQuotaType(Type.DEFAULT_USER_QUOTA) + .withQuotaTarget("jrwdkqz") .create(); - Assertions.assertEquals("whoqhnlbqnbldxe", response.location()); - Assertions.assertEquals("gschorimkrsrr", response.tags().get("oucs")); - Assertions.assertEquals(8137290998530659210L, response.quotaSizeInKiBs()); - Assertions.assertEquals(Type.INDIVIDUAL_GROUP_QUOTA, response.quotaType()); - Assertions.assertEquals("bze", response.quotaTarget()); + Assertions.assertEquals("ogtu", response.location()); + Assertions.assertEquals("fdjktsysidfvclgl", response.tags().get("n")); + Assertions.assertEquals(4495626237459310184L, response.quotaSizeInKiBs()); + Assertions.assertEquals(Type.DEFAULT_USER_QUOTA, response.quotaType()); + Assertions.assertEquals("urbuhhlkyqltq", response.quotaTarget()); } // Use "Map.of" if available diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesDeleteMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesDeleteMockTests.java index 91bee8bea1f8..4d7e6a64ca08 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesDeleteMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesDeleteMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import java.nio.charset.StandardCharsets; @@ -25,10 +25,10 @@ public void testDelete() throws Exception { NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); manager.volumeQuotaRules() - .delete("rxklobdxnazpmk", "lmv", "vfxzopjh", "zxlioh", "d", com.azure.core.util.Context.NONE); + .delete("cbuewmrswnjlxuz", "hwpusxj", "aqehg", "dohzjq", "tu", com.azure.core.util.Context.NONE); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesGetWithResponseMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesGetWithResponseMockTests.java index bd16d98cf489..8629d703b3b0 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesGetWithResponseMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesGetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.Type; @@ -22,24 +22,24 @@ public final class VolumeQuotaRulesGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"provisioningState\":\"Patching\",\"quotaSizeInKiBs\":8259010476237708124,\"quotaType\":\"IndividualUserQuota\",\"quotaTarget\":\"ngnbdxxew\"},\"location\":\"invudbch\",\"tags\":{\"crqctmxxdtddmflh\":\"tvq\",\"voxczytpr\":\"ytxzvtznapxbanno\"},\"id\":\"nwvroevytlyokrr\",\"name\":\"o\",\"type\":\"uxvnsasbcrymodi\"}"; + = "{\"properties\":{\"provisioningState\":\"Succeeded\",\"quotaSizeInKiBs\":907482374428904956,\"quotaType\":\"IndividualGroupQuota\",\"quotaTarget\":\"fjmyccxlzhco\"},\"location\":\"vnekhenlusfnrdtj\",\"tags\":{\"cq\":\"r\",\"uslvyjtcvuwkasi\":\"jvidttge\"},\"id\":\"iesfuug\",\"name\":\"tuqfecjxeygtu\",\"type\":\"xu\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); VolumeQuotaRule response = manager.volumeQuotaRules() - .getWithResponse("nsduugwbsre", "rfqkfuar", "nlvhhtklnvnafvv", "yfedevjbo", "lcqxypokk", + .getWithResponse("ctfjgtixr", "vzuyturmlmu", "wolba", "iropionszon", "pngajin", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("invudbch", response.location()); - Assertions.assertEquals("tvq", response.tags().get("crqctmxxdtddmflh")); - Assertions.assertEquals(8259010476237708124L, response.quotaSizeInKiBs()); - Assertions.assertEquals(Type.INDIVIDUAL_USER_QUOTA, response.quotaType()); - Assertions.assertEquals("ngnbdxxew", response.quotaTarget()); + Assertions.assertEquals("vnekhenlusfnrdtj", response.location()); + Assertions.assertEquals("r", response.tags().get("cq")); + Assertions.assertEquals(907482374428904956L, response.quotaSizeInKiBs()); + Assertions.assertEquals(Type.INDIVIDUAL_GROUP_QUOTA, response.quotaType()); + Assertions.assertEquals("fjmyccxlzhco", response.quotaTarget()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesListByVolumeMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesListByVolumeMockTests.java index 5b98db532702..667d6190df0d 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesListByVolumeMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesListByVolumeMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.Type; @@ -23,23 +23,23 @@ public final class VolumeQuotaRulesListByVolumeMockTests { @Test public void testListByVolume() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"provisioningState\":\"Succeeded\",\"quotaSizeInKiBs\":3989297053775783525,\"quotaType\":\"IndividualUserQuota\",\"quotaTarget\":\"oxaxm\"},\"location\":\"qalhhjnh\",\"tags\":{\"qtanarfdlpuk\":\"dyynfsvkhgb\",\"neizjcpe\":\"py\",\"hpfpazjzoywjxhp\":\"gkhnmgbrouxddbh\"},\"id\":\"ulontacnpqwteht\",\"name\":\"evrh\",\"type\":\"ljyoogwx\"}]}"; + = "{\"value\":[{\"properties\":{\"provisioningState\":\"Creating\",\"quotaSizeInKiBs\":1476688386116323232,\"quotaType\":\"DefaultUserQuota\",\"quotaTarget\":\"uahokq\"},\"location\":\"bkau\",\"tags\":{\"phwpnulaiywzej\":\"sh\",\"llndnpd\":\"whslwkoj\"},\"id\":\"rpqaf\",\"name\":\"fugsnnfhyetefy\",\"type\":\"oc\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.volumeQuotaRules() - .listByVolume("etndnbfqyggagf", "nlgmtrwahzjmu", "ftbyrplro", "kpigqfusu", + .listByVolume("ozqvbubqmam", "sycxhxzgaz", "taboidvmf", "hppubowsepdfgkmt", com.azure.core.util.Context.NONE); - Assertions.assertEquals("qalhhjnh", response.iterator().next().location()); - Assertions.assertEquals("dyynfsvkhgb", response.iterator().next().tags().get("qtanarfdlpuk")); - Assertions.assertEquals(3989297053775783525L, response.iterator().next().quotaSizeInKiBs()); - Assertions.assertEquals(Type.INDIVIDUAL_USER_QUOTA, response.iterator().next().quotaType()); - Assertions.assertEquals("oxaxm", response.iterator().next().quotaTarget()); + Assertions.assertEquals("bkau", response.iterator().next().location()); + Assertions.assertEquals("sh", response.iterator().next().tags().get("phwpnulaiywzej")); + Assertions.assertEquals(1476688386116323232L, response.iterator().next().quotaSizeInKiBs()); + Assertions.assertEquals(Type.DEFAULT_USER_QUOTA, response.iterator().next().quotaType()); + Assertions.assertEquals("uahokq", response.iterator().next().quotaTarget()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesListTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesListTests.java index e27de5a7e022..bebce5cef1f7 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesListTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesListTests.java @@ -17,34 +17,30 @@ public final class VolumeQuotaRulesListTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { VolumeQuotaRulesList model = BinaryData.fromString( - "{\"value\":[{\"properties\":{\"provisioningState\":\"Deleting\",\"quotaSizeInKiBs\":4753379128237183611,\"quotaType\":\"DefaultGroupQuota\",\"quotaTarget\":\"tsgumhj\"},\"location\":\"ikkx\",\"tags\":{\"vuzlm\":\"olbq\"},\"id\":\"felfktg\",\"name\":\"lcrpw\",\"type\":\"xeznoi\"},{\"properties\":{\"provisioningState\":\"Patching\",\"quotaSizeInKiBs\":336408309015246228,\"quotaType\":\"DefaultUserQuota\",\"quotaTarget\":\"nbsazejjoqkag\"},\"location\":\"sxtta\",\"tags\":{\"mkqjj\":\"xnfaazpxdtnk\",\"pyouaibrebqaays\":\"wuenvr\"},\"id\":\"kixqtnqtt\",\"name\":\"zlwfffiakp\",\"type\":\"pqqmted\"}]}") + "{\"value\":[{\"properties\":{\"provisioningState\":\"Deleting\",\"quotaSizeInKiBs\":4971111949791382837,\"quotaType\":\"IndividualGroupQuota\",\"quotaTarget\":\"yfwnylr\"},\"location\":\"o\",\"tags\":{\"vtylbfpncu\":\"tpkiwkkbnujry\",\"thtywub\":\"doiwi\",\"fdntwjchrdgoih\":\"cbihwqk\",\"luudfdlwggytsb\":\"umwctondz\"},\"id\":\"tov\",\"name\":\"tgseinqfiufxqkn\",\"type\":\"irgne\"}]}") .toObject(VolumeQuotaRulesList.class); - Assertions.assertEquals("ikkx", model.value().get(0).location()); - Assertions.assertEquals("olbq", model.value().get(0).tags().get("vuzlm")); - Assertions.assertEquals(4753379128237183611L, model.value().get(0).quotaSizeInKiBs()); - Assertions.assertEquals(Type.DEFAULT_GROUP_QUOTA, model.value().get(0).quotaType()); - Assertions.assertEquals("tsgumhj", model.value().get(0).quotaTarget()); + Assertions.assertEquals("o", model.value().get(0).location()); + Assertions.assertEquals("tpkiwkkbnujry", model.value().get(0).tags().get("vtylbfpncu")); + Assertions.assertEquals(4971111949791382837L, model.value().get(0).quotaSizeInKiBs()); + Assertions.assertEquals(Type.INDIVIDUAL_GROUP_QUOTA, model.value().get(0).quotaType()); + Assertions.assertEquals("yfwnylr", model.value().get(0).quotaTarget()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - VolumeQuotaRulesList model = new VolumeQuotaRulesList().withValue(Arrays.asList( - new VolumeQuotaRuleInner().withLocation("ikkx") - .withTags(mapOf("vuzlm", "olbq")) - .withQuotaSizeInKiBs(4753379128237183611L) - .withQuotaType(Type.DEFAULT_GROUP_QUOTA) - .withQuotaTarget("tsgumhj"), - new VolumeQuotaRuleInner().withLocation("sxtta") - .withTags(mapOf("mkqjj", "xnfaazpxdtnk", "pyouaibrebqaays", "wuenvr")) - .withQuotaSizeInKiBs(336408309015246228L) - .withQuotaType(Type.DEFAULT_USER_QUOTA) - .withQuotaTarget("nbsazejjoqkag"))); + VolumeQuotaRulesList model + = new VolumeQuotaRulesList().withValue(Arrays.asList(new VolumeQuotaRuleInner().withLocation("o") + .withTags(mapOf("vtylbfpncu", "tpkiwkkbnujry", "thtywub", "doiwi", "fdntwjchrdgoih", "cbihwqk", + "luudfdlwggytsb", "umwctondz")) + .withQuotaSizeInKiBs(4971111949791382837L) + .withQuotaType(Type.INDIVIDUAL_GROUP_QUOTA) + .withQuotaTarget("yfwnylr"))); model = BinaryData.fromObject(model).toObject(VolumeQuotaRulesList.class); - Assertions.assertEquals("ikkx", model.value().get(0).location()); - Assertions.assertEquals("olbq", model.value().get(0).tags().get("vuzlm")); - Assertions.assertEquals(4753379128237183611L, model.value().get(0).quotaSizeInKiBs()); - Assertions.assertEquals(Type.DEFAULT_GROUP_QUOTA, model.value().get(0).quotaType()); - Assertions.assertEquals("tsgumhj", model.value().get(0).quotaTarget()); + Assertions.assertEquals("o", model.value().get(0).location()); + Assertions.assertEquals("tpkiwkkbnujry", model.value().get(0).tags().get("vtylbfpncu")); + Assertions.assertEquals(4971111949791382837L, model.value().get(0).quotaSizeInKiBs()); + Assertions.assertEquals(Type.INDIVIDUAL_GROUP_QUOTA, model.value().get(0).quotaType()); + Assertions.assertEquals("yfwnylr", model.value().get(0).quotaTarget()); } // Use "Map.of" if available diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesPropertiesTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesPropertiesTests.java index bc3634a52bf7..fc1dd40ef74a 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesPropertiesTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeQuotaRulesPropertiesTests.java @@ -13,21 +13,21 @@ public final class VolumeQuotaRulesPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { VolumeQuotaRulesProperties model = BinaryData.fromString( - "{\"provisioningState\":\"Moving\",\"quotaSizeInKiBs\":1232834909698748994,\"quotaType\":\"IndividualUserQuota\",\"quotaTarget\":\"wvtylbfpncurdo\"}") + "{\"provisioningState\":\"Deleting\",\"quotaSizeInKiBs\":4099152250021383812,\"quotaType\":\"DefaultUserQuota\",\"quotaTarget\":\"rghxjb\"}") .toObject(VolumeQuotaRulesProperties.class); - Assertions.assertEquals(1232834909698748994L, model.quotaSizeInKiBs()); - Assertions.assertEquals(Type.INDIVIDUAL_USER_QUOTA, model.quotaType()); - Assertions.assertEquals("wvtylbfpncurdo", model.quotaTarget()); + Assertions.assertEquals(4099152250021383812L, model.quotaSizeInKiBs()); + Assertions.assertEquals(Type.DEFAULT_USER_QUOTA, model.quotaType()); + Assertions.assertEquals("rghxjb", model.quotaTarget()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - VolumeQuotaRulesProperties model = new VolumeQuotaRulesProperties().withQuotaSizeInKiBs(1232834909698748994L) - .withQuotaType(Type.INDIVIDUAL_USER_QUOTA) - .withQuotaTarget("wvtylbfpncurdo"); + VolumeQuotaRulesProperties model = new VolumeQuotaRulesProperties().withQuotaSizeInKiBs(4099152250021383812L) + .withQuotaType(Type.DEFAULT_USER_QUOTA) + .withQuotaTarget("rghxjb"); model = BinaryData.fromObject(model).toObject(VolumeQuotaRulesProperties.class); - Assertions.assertEquals(1232834909698748994L, model.quotaSizeInKiBs()); - Assertions.assertEquals(Type.INDIVIDUAL_USER_QUOTA, model.quotaType()); - Assertions.assertEquals("wvtylbfpncurdo", model.quotaTarget()); + Assertions.assertEquals(4099152250021383812L, model.quotaSizeInKiBs()); + Assertions.assertEquals(Type.DEFAULT_USER_QUOTA, model.quotaType()); + Assertions.assertEquals("rghxjb", model.quotaTarget()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeRelocationPropertiesTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeRelocationPropertiesTests.java index 7ebdaf532ab9..18914d4f5775 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeRelocationPropertiesTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeRelocationPropertiesTests.java @@ -12,7 +12,7 @@ public final class VolumeRelocationPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { VolumeRelocationProperties model - = BinaryData.fromString("{\"relocationRequested\":false,\"readyToBeFinalized\":false}") + = BinaryData.fromString("{\"relocationRequested\":false,\"readyToBeFinalized\":true}") .toObject(VolumeRelocationProperties.class); Assertions.assertEquals(false, model.relocationRequested()); } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeRevertTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeRevertTests.java index bb66f6858295..cda7b1e52efb 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeRevertTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeRevertTests.java @@ -11,14 +11,14 @@ public final class VolumeRevertTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - VolumeRevert model = BinaryData.fromString("{\"snapshotId\":\"d\"}").toObject(VolumeRevert.class); - Assertions.assertEquals("d", model.snapshotId()); + VolumeRevert model = BinaryData.fromString("{\"snapshotId\":\"sgplsakn\"}").toObject(VolumeRevert.class); + Assertions.assertEquals("sgplsakn", model.snapshotId()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - VolumeRevert model = new VolumeRevert().withSnapshotId("d"); + VolumeRevert model = new VolumeRevert().withSnapshotId("sgplsakn"); model = BinaryData.fromObject(model).toObject(VolumeRevert.class); - Assertions.assertEquals("d", model.snapshotId()); + Assertions.assertEquals("sgplsakn", model.snapshotId()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeSnapshotPropertiesTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeSnapshotPropertiesTests.java index 3915fa036e8c..05bb74538d82 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeSnapshotPropertiesTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumeSnapshotPropertiesTests.java @@ -11,15 +11,15 @@ public final class VolumeSnapshotPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - VolumeSnapshotProperties model = BinaryData.fromString("{\"snapshotPolicyId\":\"dkzzewkfvhqcrail\"}") - .toObject(VolumeSnapshotProperties.class); - Assertions.assertEquals("dkzzewkfvhqcrail", model.snapshotPolicyId()); + VolumeSnapshotProperties model + = BinaryData.fromString("{\"snapshotPolicyId\":\"ndlkzgxhurip\"}").toObject(VolumeSnapshotProperties.class); + Assertions.assertEquals("ndlkzgxhurip", model.snapshotPolicyId()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - VolumeSnapshotProperties model = new VolumeSnapshotProperties().withSnapshotPolicyId("dkzzewkfvhqcrail"); + VolumeSnapshotProperties model = new VolumeSnapshotProperties().withSnapshotPolicyId("ndlkzgxhurip"); model = BinaryData.fromObject(model).toObject(VolumeSnapshotProperties.class); - Assertions.assertEquals("dkzzewkfvhqcrail", model.snapshotPolicyId()); + Assertions.assertEquals("ndlkzgxhurip", model.snapshotPolicyId()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesAuthorizeExternalReplicationMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesAuthorizeExternalReplicationMockTests.java index a4764c1b14fd..267190b9f4a0 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesAuthorizeExternalReplicationMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesAuthorizeExternalReplicationMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.SvmPeerCommandResponse; @@ -20,19 +20,18 @@ public final class VolumesAuthorizeExternalReplicationMockTests { @Test public void testAuthorizeExternalReplication() throws Exception { - String responseStr = "{\"svmPeeringCommand\":\"ex\"}"; + String responseStr = "{\"svmPeeringCommand\":\"pqhe\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); SvmPeerCommandResponse response = manager.volumes() - .authorizeExternalReplication("hzvechndbnwieho", "ewjwiuubw", "fqsfa", "aqtferr", - com.azure.core.util.Context.NONE); + .authorizeExternalReplication("e", "pqxbkwvzgnzvdf", "zdix", "mqpnoda", com.azure.core.util.Context.NONE); - Assertions.assertEquals("ex", response.svmPeeringCommand()); + Assertions.assertEquals("pqhe", response.svmPeeringCommand()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesAuthorizeReplicationMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesAuthorizeReplicationMockTests.java index 587ea7e7bb7e..39579b30c7d5 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesAuthorizeReplicationMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesAuthorizeReplicationMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.AuthorizeRequest; @@ -26,11 +26,11 @@ public void testAuthorizeReplication() throws Exception { NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); manager.volumes() - .authorizeReplication("onqzinkfkbgbzbow", "eqocljmygvk", "qkjjeokbz", "fezrx", - new AuthorizeRequest().withRemoteVolumeResourceId("zurtleipqxbkwvz"), com.azure.core.util.Context.NONE); + .authorizeReplication("tzfjltf", "nzcyjtotp", "opv", "bdb", + new AuthorizeRequest().withRemoteVolumeResourceId("gqqihedsvqwt"), com.azure.core.util.Context.NONE); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesBreakFileLocksMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesBreakFileLocksMockTests.java index 36bfdb8e8324..10dfba9186cd 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesBreakFileLocksMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesBreakFileLocksMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.BreakFileLocksRequest; @@ -26,7 +26,7 @@ public void testBreakFileLocks() throws Exception { NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); manager.volumes() .breakFileLocks("jrcg", "gydcw", "oxjumvqqo", "ihrraiouaub", diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesBreakReplicationMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesBreakReplicationMockTests.java index 3df46a64a3ea..c66473bd296c 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesBreakReplicationMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesBreakReplicationMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.BreakReplicationRequest; @@ -26,10 +26,10 @@ public void testBreakReplication() throws Exception { NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); manager.volumes() - .breakReplication("etnluankrrfx", "eebtijvacvb", "qzbqqxlajrnwxa", "evehjkuyxoaf", + .breakReplication("dgug", "yzihgrkyuizabsn", "fpphoj", "evy", new BreakReplicationRequest().withForceBreakReplication(false), com.azure.core.util.Context.NONE); } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesDeleteReplicationMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesDeleteReplicationMockTests.java index 54e1616eafa3..dd25607af2e4 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesDeleteReplicationMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesDeleteReplicationMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import java.nio.charset.StandardCharsets; @@ -25,11 +25,10 @@ public void testDeleteReplication() throws Exception { NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); manager.volumes() - .deleteReplication("ibcysihsgqc", "dhohsdtmcdzsuf", "ohdxbzlmcmu", "pcvhdbevwqqxeys", - com.azure.core.util.Context.NONE); + .deleteReplication("oudorhcgyyp", "otwypundmb", "hu", "cmjkavlgorbmftpm", com.azure.core.util.Context.NONE); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesFinalizeRelocationMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesFinalizeRelocationMockTests.java index 3b3d85988d68..8ad48fdfa323 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesFinalizeRelocationMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesFinalizeRelocationMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import java.nio.charset.StandardCharsets; @@ -25,10 +25,9 @@ public void testFinalizeRelocation() throws Exception { NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); - manager.volumes() - .finalizeRelocation("bjwgnyfus", "zsvtuikzhajqgl", "fh", "l", com.azure.core.util.Context.NONE); + manager.volumes().finalizeRelocation("cpilj", "a", "zv", "chndbnwie", com.azure.core.util.Context.NONE); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesListGetGroupIdListForLdapUserMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesListGetGroupIdListForLdapUserMockTests.java index 500401d7c638..1e1628e6476d 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesListGetGroupIdListForLdapUserMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesListGetGroupIdListForLdapUserMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.GetGroupIdListForLdapUserRequest; @@ -28,7 +28,7 @@ public void testListGetGroupIdListForLdapUser() throws Exception { NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); GetGroupIdListForLdapUserResponse response = manager.volumes() .listGetGroupIdListForLdapUser("l", "z", "asccbiui", "zdlyjdfqw", diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesListQuotaReportMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesListQuotaReportMockTests.java deleted file mode 100644 index fef5c7dbc1a6..000000000000 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesListQuotaReportMockTests.java +++ /dev/null @@ -1,45 +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.resourcemanager.netapp.generated; - -import com.azure.core.credential.AccessToken; -import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.profile.AzureProfile; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.resourcemanager.netapp.NetAppFilesManager; -import com.azure.resourcemanager.netapp.models.ListQuotaReportResponse; -import com.azure.resourcemanager.netapp.models.Type; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -public final class VolumesListQuotaReportMockTests { - @Test - public void testListQuotaReport() throws Exception { - String responseStr - = "{\"value\":[{\"quotaType\":\"DefaultUserQuota\",\"quotaTarget\":\"fczbgom\",\"quotaLimitUsedInKiBs\":6180206974862965470,\"quotaLimitTotalInKiBs\":2354871388013628710,\"percentageUsed\":90.87945,\"isDerivedQuota\":false}],\"nextLink\":\"i\"}"; - - HttpClient httpClient - = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); - NetAppFilesManager manager = NetAppFilesManager.configure() - .withHttpClient(httpClient) - .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); - - ListQuotaReportResponse response = manager.volumes() - .listQuotaReport("dgug", "yzihgrkyuizabsn", "fpphoj", "evy", com.azure.core.util.Context.NONE); - - Assertions.assertEquals(Type.DEFAULT_USER_QUOTA, response.value().get(0).quotaType()); - Assertions.assertEquals("fczbgom", response.value().get(0).quotaTarget()); - Assertions.assertEquals(6180206974862965470L, response.value().get(0).quotaLimitUsedInKiBs()); - Assertions.assertEquals(2354871388013628710L, response.value().get(0).quotaLimitTotalInKiBs()); - Assertions.assertEquals(90.87945F, response.value().get(0).percentageUsed()); - Assertions.assertEquals(false, response.value().get(0).isDerivedQuota()); - Assertions.assertEquals("i", response.nextLink()); - } -} diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesListReplicationsMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesListReplicationsMockTests.java index b8f81ca1ce88..f70ca71cb93b 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesListReplicationsMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesListReplicationsMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.EndpointType; @@ -24,21 +24,21 @@ public final class VolumesListReplicationsMockTests { @Test public void testListReplications() throws Exception { String responseStr - = "{\"value\":[{\"replicationId\":\"ypundmbxhugc\",\"endpointType\":\"src\",\"replicationSchedule\":\"hourly\",\"remoteVolumeResourceId\":\"lgorb\",\"remoteVolumeRegion\":\"tp\"}]}"; + = "{\"value\":[{\"replicationId\":\"riypoqeyhlqhyk\",\"endpointType\":\"dst\",\"replicationSchedule\":\"_10minutely\",\"remoteVolumeResourceId\":\"znuciqdsm\",\"remoteVolumeRegion\":\"iitdfuxt\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.volumes() - .listReplications("jh", "mgixhcmavmqfou", "or", "cgyypro", com.azure.core.util.Context.NONE); + .listReplications("wxacevehj", "uyxoaf", "aoqltfaey", "inmfgvxirp", com.azure.core.util.Context.NONE); - Assertions.assertEquals(EndpointType.SRC, response.iterator().next().endpointType()); - Assertions.assertEquals(ReplicationSchedule.HOURLY, response.iterator().next().replicationSchedule()); - Assertions.assertEquals("lgorb", response.iterator().next().remoteVolumeResourceId()); - Assertions.assertEquals("tp", response.iterator().next().remoteVolumeRegion()); + Assertions.assertEquals(EndpointType.DST, response.iterator().next().endpointType()); + Assertions.assertEquals(ReplicationSchedule.ONE_ZEROMINUTELY, response.iterator().next().replicationSchedule()); + Assertions.assertEquals("znuciqdsm", response.iterator().next().remoteVolumeResourceId()); + Assertions.assertEquals("iitdfuxt", response.iterator().next().remoteVolumeRegion()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesPeerExternalClusterMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesPeerExternalClusterMockTests.java index 326759cd245c..5c487246d4c0 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesPeerExternalClusterMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesPeerExternalClusterMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.ClusterPeerCommandResponse; @@ -22,20 +22,21 @@ public final class VolumesPeerExternalClusterMockTests { @Test public void testPeerExternalCluster() throws Exception { - String responseStr = "{\"peerAcceptCommand\":\"bkpbzpcpiljh\"}"; + String responseStr = "{\"peerAcceptCommand\":\"kbzefezrxcczurt\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); ClusterPeerCommandResponse response = manager.volumes() - .peerExternalCluster("dlat", "tmzlbiojlv", "hrbbpneqvcwwyy", "r", - new PeerClusterForVolumeMigrationRequest().withPeerIpAddresses(Arrays.asList("chpp", "prsnmokayzejn")), + .peerExternalCluster( + "sufco", "dxbzlmcmuap", "vhdbevwqqxey", "ko", new PeerClusterForVolumeMigrationRequest() + .withPeerIpAddresses(Arrays.asList("zinkfkbgbzbowxeq", "clj", "ygvkzqkjj")), com.azure.core.util.Context.NONE); - Assertions.assertEquals("bkpbzpcpiljh", response.peerAcceptCommand()); + Assertions.assertEquals("kbzefezrxcczurt", response.peerAcceptCommand()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesPoolChangeMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesPoolChangeMockTests.java index 776a218afb4f..1be6b1d25917 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesPoolChangeMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesPoolChangeMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.PoolChangeRequest; @@ -26,11 +26,11 @@ public void testPoolChange() throws Exception { NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); manager.volumes() - .poolChange("kmfx", "pjwogqqno", "pud", "dabtqwp", - new PoolChangeRequest().withNewPoolResourceId("yawbzasqbu"), com.azure.core.util.Context.NONE); + .poolChange("jptmcgsbost", "eln", "la", "utmzlbiojlvfhrbb", + new PoolChangeRequest().withNewPoolResourceId("neqvcwwyyurmo"), com.azure.core.util.Context.NONE); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesReInitializeReplicationMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesReInitializeReplicationMockTests.java index cb69a5eebdf4..b3c42573fd09 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesReInitializeReplicationMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesReInitializeReplicationMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import java.nio.charset.StandardCharsets; @@ -25,11 +25,10 @@ public void testReInitializeReplication() throws Exception { NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); manager.volumes() - .reInitializeReplication("nzvdfbzdixzmq", "noda", "opqhewjptmc", "sbostzel", - com.azure.core.util.Context.NONE); + .reInitializeReplication("mkyi", "cysihs", "qcwdhoh", "dtmcd", com.azure.core.util.Context.NONE); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesReplicationStatusWithResponseMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesReplicationStatusWithResponseMockTests.java index e8f3cc7d2997..807bc5931b9b 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesReplicationStatusWithResponseMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesReplicationStatusWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.MirrorState; @@ -23,24 +23,24 @@ public final class VolumesReplicationStatusWithResponseMockTests { @Test public void testReplicationStatusWithResponse() throws Exception { String responseStr - = "{\"healthy\":false,\"relationshipStatus\":\"Idle\",\"mirrorState\":\"Broken\",\"totalProgress\":\"mexiitdfuxt\",\"errorMessage\":\"siibmiybnnustgn\"}"; + = "{\"healthy\":false,\"relationshipStatus\":\"Transferring\",\"mirrorState\":\"Uninitialized\",\"totalProgress\":\"mq\",\"errorMessage\":\"qqxlajr\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); ReplicationStatus response = manager.volumes() - .replicationStatusWithResponse("qltfaey", "inmfgvxirp", "hriypoqeyhlqhy", "prlpy", + .replicationStatusWithResponse("sgzfczbg", "mfg", "eglqgleohibetn", "uankrrfxeeeb", com.azure.core.util.Context.NONE) .getValue(); Assertions.assertEquals(false, response.healthy()); - Assertions.assertEquals(RelationshipStatus.IDLE, response.relationshipStatus()); - Assertions.assertEquals(MirrorState.BROKEN, response.mirrorState()); - Assertions.assertEquals("mexiitdfuxt", response.totalProgress()); - Assertions.assertEquals("siibmiybnnustgn", response.errorMessage()); + Assertions.assertEquals(RelationshipStatus.TRANSFERRING, response.relationshipStatus()); + Assertions.assertEquals(MirrorState.UNINITIALIZED, response.mirrorState()); + Assertions.assertEquals("mq", response.totalProgress()); + Assertions.assertEquals("qqxlajr", response.errorMessage()); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesResyncReplicationMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesResyncReplicationMockTests.java index 43f11fb6ca51..58bbf1b05720 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesResyncReplicationMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesResyncReplicationMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import java.nio.charset.StandardCharsets; @@ -25,11 +25,10 @@ public void testResyncReplication() throws Exception { NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); manager.volumes() - .resyncReplication("dtzfjltfvnzcy", "t", "tpvopvpbdb", "qgqqihedsvqwthmk", - com.azure.core.util.Context.NONE); + .resyncReplication("asiibmiybnnust", "nlj", "nmgixh", "mavmq", com.azure.core.util.Context.NONE); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesRevertMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesRevertMockTests.java index 33ec7287ca1e..00c67238d14c 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesRevertMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesRevertMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import com.azure.resourcemanager.netapp.models.VolumeRevert; @@ -26,7 +26,7 @@ public void testRevert() throws Exception { NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); manager.volumes() .revert("ntvlwijpsttexo", "qpwcyyufmh", "uncuw", "qspkcdqzhlctd", diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesRevertRelocationMockTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesRevertRelocationMockTests.java index 236ebe98aa97..fee00359fcc9 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesRevertRelocationMockTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/VolumesRevertRelocationMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.netapp.NetAppFilesManager; import java.nio.charset.StandardCharsets; @@ -25,10 +25,10 @@ public void testRevertRelocation() throws Exception { NetAppFilesManager manager = NetAppFilesManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); manager.volumes() - .revertRelocation("qryxyn", "nzrdpsovwxz", "ptgoeiybbabp", "hv", com.azure.core.util.Context.NONE); + .revertRelocation("olewjwi", "ubwefqs", "ap", "qtferrqwexjkmf", com.azure.core.util.Context.NONE); } } diff --git a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/WeeklyScheduleTests.java b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/WeeklyScheduleTests.java index a92b5011b563..3a6e2797367a 100644 --- a/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/WeeklyScheduleTests.java +++ b/sdk/netapp/azure-resourcemanager-netapp/src/test/java/com/azure/resourcemanager/netapp/generated/WeeklyScheduleTests.java @@ -12,27 +12,27 @@ public final class WeeklyScheduleTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { WeeklySchedule model = BinaryData.fromString( - "{\"snapshotsToKeep\":1074129183,\"day\":\"erqf\",\"hour\":62182202,\"minute\":2077702872,\"usedBytes\":2726192915830006028}") + "{\"snapshotsToKeep\":991988200,\"day\":\"frao\",\"hour\":1573760550,\"minute\":1614629592,\"usedBytes\":5941634021066560611}") .toObject(WeeklySchedule.class); - Assertions.assertEquals(1074129183, model.snapshotsToKeep()); - Assertions.assertEquals("erqf", model.day()); - Assertions.assertEquals(62182202, model.hour()); - Assertions.assertEquals(2077702872, model.minute()); - Assertions.assertEquals(2726192915830006028L, model.usedBytes()); + Assertions.assertEquals(991988200, model.snapshotsToKeep()); + Assertions.assertEquals("frao", model.day()); + Assertions.assertEquals(1573760550, model.hour()); + Assertions.assertEquals(1614629592, model.minute()); + Assertions.assertEquals(5941634021066560611L, model.usedBytes()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - WeeklySchedule model = new WeeklySchedule().withSnapshotsToKeep(1074129183) - .withDay("erqf") - .withHour(62182202) - .withMinute(2077702872) - .withUsedBytes(2726192915830006028L); + WeeklySchedule model = new WeeklySchedule().withSnapshotsToKeep(991988200) + .withDay("frao") + .withHour(1573760550) + .withMinute(1614629592) + .withUsedBytes(5941634021066560611L); model = BinaryData.fromObject(model).toObject(WeeklySchedule.class); - Assertions.assertEquals(1074129183, model.snapshotsToKeep()); - Assertions.assertEquals("erqf", model.day()); - Assertions.assertEquals(62182202, model.hour()); - Assertions.assertEquals(2077702872, model.minute()); - Assertions.assertEquals(2726192915830006028L, model.usedBytes()); + Assertions.assertEquals(991988200, model.snapshotsToKeep()); + Assertions.assertEquals("frao", model.day()); + Assertions.assertEquals(1573760550, model.hour()); + Assertions.assertEquals(1614629592, model.minute()); + Assertions.assertEquals(5941634021066560611L, model.usedBytes()); } } diff --git a/sdk/networkanalytics/azure-resourcemanager-networkanalytics/CHANGELOG.md b/sdk/networkanalytics/azure-resourcemanager-networkanalytics/CHANGELOG.md index 9121c655ade8..94c7231e4b78 100644 --- a/sdk/networkanalytics/azure-resourcemanager-networkanalytics/CHANGELOG.md +++ b/sdk/networkanalytics/azure-resourcemanager-networkanalytics/CHANGELOG.md @@ -10,6 +10,14 @@ ### Other Changes +## 1.0.1 (2025-02-24) + +Please note, this package has been deprecated and will no longer be maintained after 03/14/2025. Refer to our deprecation policy (https://aka.ms/azsdk/support-policies) for more details. + +### Other Changes + +- Please note, this package has been deprecated and will no longer be maintained after 03/14/2025. + ## 1.0.0 (2024-01-24) - Azure Resource Manager Network Analytics client library for Java. This package contains Microsoft Azure SDK for Network Analytics Management SDK. Package tag package-2023-11-15. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). diff --git a/sdk/networkanalytics/azure-resourcemanager-networkanalytics/README.md b/sdk/networkanalytics/azure-resourcemanager-networkanalytics/README.md index 5954f2714efb..7f4ba1b32201 100644 --- a/sdk/networkanalytics/azure-resourcemanager-networkanalytics/README.md +++ b/sdk/networkanalytics/azure-resourcemanager-networkanalytics/README.md @@ -1,5 +1,7 @@ # Azure Resource Manager Network Analytics client library for Java +Please note, this package has been deprecated and will no longer be maintained after 03/14/2025. Refer to our deprecation policy (https://aka.ms/azsdk/support-policies) for more details. + Azure Resource Manager Network Analytics client library for Java. This package contains Microsoft Azure SDK for Network Analytics Management SDK. Package tag package-2023-11-15. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). @@ -32,7 +34,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-networkanalytics - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -104,4 +106,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fnetworkanalytics%2Fazure-resourcemanager-networkanalytics%2FREADME.png) + diff --git a/sdk/networkanalytics/azure-resourcemanager-networkanalytics/pom.xml b/sdk/networkanalytics/azure-resourcemanager-networkanalytics/pom.xml index 07e4c5d8c15d..a2296f521144 100644 --- a/sdk/networkanalytics/azure-resourcemanager-networkanalytics/pom.xml +++ b/sdk/networkanalytics/azure-resourcemanager-networkanalytics/pom.xml @@ -18,7 +18,7 @@ jar Microsoft Azure SDK for Network Analytics Management - This package contains Microsoft Azure SDK for Network Analytics Management SDK. For documentation on how to use this package, please see https://aka.ms/azsdk/java/mgmt. Package tag package-2023-11-15. + Please note, this package has been deprecated and will no longer be maintained after 03/14/2025. Refer to our deprecation policy (https://aka.ms/azsdk/support-policies) for more details. https://github.com/Azure/azure-sdk-for-java @@ -50,23 +50,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/CHANGELOG.md b/sdk/networkcloud/azure-resourcemanager-networkcloud/CHANGELOG.md index 640c9b375ab9..eeeb4ad9a936 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/CHANGELOG.md +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.1.0-beta.2 (Unreleased) +## 1.2.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,808 @@ ### Other Changes +## 1.1.0 (2025-02-21) + +- Azure Resource Manager NetworkCloud client library for Java. This package contains Microsoft Azure SDK for NetworkCloud Management SDK. The Network Cloud APIs provide management of the Azure Operator Nexus compute resources such as on-premises clusters, hardware resources, and workload infrastructure resources. Package tag package-2024-07-01. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). + +### Breaking Changes + +#### `models.BareMetalMachineKeySets` was modified + +* `void deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` +* `void delete(java.lang.String,java.lang.String,java.lang.String)` -> `models.OperationStatusResult delete(java.lang.String,java.lang.String,java.lang.String)` +* `void deleteById(java.lang.String)` -> `models.OperationStatusResult deleteById(java.lang.String)` +* `void delete(java.lang.String,java.lang.String,java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult delete(java.lang.String,java.lang.String,java.lang.String,com.azure.core.util.Context)` + +#### `models.Racks` was modified + +* `void deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` +* `void deleteByResourceGroup(java.lang.String,java.lang.String)` -> `models.OperationStatusResult deleteByResourceGroup(java.lang.String,java.lang.String)` +* `void delete(java.lang.String,java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult delete(java.lang.String,java.lang.String,com.azure.core.util.Context)` +* `void deleteById(java.lang.String)` -> `models.OperationStatusResult deleteById(java.lang.String)` + +#### `models.StorageAppliances` was modified + +* `void deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` +* `void deleteById(java.lang.String)` -> `models.OperationStatusResult deleteById(java.lang.String)` +* `void deleteByResourceGroup(java.lang.String,java.lang.String)` -> `models.OperationStatusResult deleteByResourceGroup(java.lang.String,java.lang.String)` +* `void delete(java.lang.String,java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult delete(java.lang.String,java.lang.String,com.azure.core.util.Context)` + +#### `models.Clusters` was modified + +* `void delete(java.lang.String,java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult delete(java.lang.String,java.lang.String,com.azure.core.util.Context)` +* `void deleteById(java.lang.String)` -> `models.OperationStatusResult deleteById(java.lang.String)` +* `void deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` +* `void deleteByResourceGroup(java.lang.String,java.lang.String)` -> `models.OperationStatusResult deleteByResourceGroup(java.lang.String,java.lang.String)` + +#### `models.MetricsConfigurations` was modified + +* `void deleteById(java.lang.String)` -> `models.OperationStatusResult deleteById(java.lang.String)` +* `void deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` +* `void delete(java.lang.String,java.lang.String,java.lang.String)` -> `models.OperationStatusResult delete(java.lang.String,java.lang.String,java.lang.String)` +* `void delete(java.lang.String,java.lang.String,java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult delete(java.lang.String,java.lang.String,java.lang.String,com.azure.core.util.Context)` + +#### `models.Volumes` was modified + +* `void delete(java.lang.String,java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult delete(java.lang.String,java.lang.String,com.azure.core.util.Context)` +* `void deleteById(java.lang.String)` -> `models.OperationStatusResult deleteById(java.lang.String)` +* `void deleteByResourceGroup(java.lang.String,java.lang.String)` -> `models.OperationStatusResult deleteByResourceGroup(java.lang.String,java.lang.String)` +* `void deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` + +#### `models.KubernetesClusters` was modified + +* `void deleteByResourceGroup(java.lang.String,java.lang.String)` -> `models.OperationStatusResult deleteByResourceGroup(java.lang.String,java.lang.String)` +* `void delete(java.lang.String,java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult delete(java.lang.String,java.lang.String,com.azure.core.util.Context)` +* `void deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` +* `void deleteById(java.lang.String)` -> `models.OperationStatusResult deleteById(java.lang.String)` + +#### `models.Consoles` was modified + +* `void deleteById(java.lang.String)` -> `models.OperationStatusResult deleteById(java.lang.String)` +* `void deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` +* `void delete(java.lang.String,java.lang.String,java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult delete(java.lang.String,java.lang.String,java.lang.String,com.azure.core.util.Context)` +* `void delete(java.lang.String,java.lang.String,java.lang.String)` -> `models.OperationStatusResult delete(java.lang.String,java.lang.String,java.lang.String)` + +#### `models.L3Networks` was modified + +* `void deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` +* `void delete(java.lang.String,java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult delete(java.lang.String,java.lang.String,com.azure.core.util.Context)` +* `void deleteById(java.lang.String)` -> `models.OperationStatusResult deleteById(java.lang.String)` +* `void deleteByResourceGroup(java.lang.String,java.lang.String)` -> `models.OperationStatusResult deleteByResourceGroup(java.lang.String,java.lang.String)` + +#### `models.CloudServicesNetworks` was modified + +* `void deleteByResourceGroup(java.lang.String,java.lang.String)` -> `models.OperationStatusResult deleteByResourceGroup(java.lang.String,java.lang.String)` +* `void deleteById(java.lang.String)` -> `models.OperationStatusResult deleteById(java.lang.String)` +* `void deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` +* `void delete(java.lang.String,java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult delete(java.lang.String,java.lang.String,com.azure.core.util.Context)` + +#### `models.ClusterManagers` was modified + +* `void deleteById(java.lang.String)` -> `models.OperationStatusResult deleteById(java.lang.String)` +* `void deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` +* `void deleteByResourceGroup(java.lang.String,java.lang.String)` -> `models.OperationStatusResult deleteByResourceGroup(java.lang.String,java.lang.String)` +* `void delete(java.lang.String,java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult delete(java.lang.String,java.lang.String,com.azure.core.util.Context)` + +#### `models.AgentPools` was modified + +* `void delete(java.lang.String,java.lang.String,java.lang.String)` -> `models.OperationStatusResult delete(java.lang.String,java.lang.String,java.lang.String)` +* `void delete(java.lang.String,java.lang.String,java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult delete(java.lang.String,java.lang.String,java.lang.String,com.azure.core.util.Context)` +* `void deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` +* `void deleteById(java.lang.String)` -> `models.OperationStatusResult deleteById(java.lang.String)` + +#### `models.BmcKeySets` was modified + +* `void delete(java.lang.String,java.lang.String,java.lang.String)` -> `models.OperationStatusResult delete(java.lang.String,java.lang.String,java.lang.String)` +* `void deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` +* `void delete(java.lang.String,java.lang.String,java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult delete(java.lang.String,java.lang.String,java.lang.String,com.azure.core.util.Context)` +* `void deleteById(java.lang.String)` -> `models.OperationStatusResult deleteById(java.lang.String)` + +#### `models.BareMetalMachines` was modified + +* `void deleteByResourceGroup(java.lang.String,java.lang.String)` -> `models.OperationStatusResult deleteByResourceGroup(java.lang.String,java.lang.String)` +* `void deleteById(java.lang.String)` -> `models.OperationStatusResult deleteById(java.lang.String)` +* `void delete(java.lang.String,java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult delete(java.lang.String,java.lang.String,com.azure.core.util.Context)` +* `void deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` + +#### `models.VirtualMachines` was modified + +* `void deleteById(java.lang.String)` -> `models.OperationStatusResult deleteById(java.lang.String)` +* `void deleteByResourceGroup(java.lang.String,java.lang.String)` -> `models.OperationStatusResult deleteByResourceGroup(java.lang.String,java.lang.String)` +* `void delete(java.lang.String,java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult delete(java.lang.String,java.lang.String,com.azure.core.util.Context)` +* `void deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` + +#### `models.TrunkedNetworks` was modified + +* `void deleteByResourceGroup(java.lang.String,java.lang.String)` -> `models.OperationStatusResult deleteByResourceGroup(java.lang.String,java.lang.String)` +* `void deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` +* `void delete(java.lang.String,java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult delete(java.lang.String,java.lang.String,com.azure.core.util.Context)` +* `void deleteById(java.lang.String)` -> `models.OperationStatusResult deleteById(java.lang.String)` + +#### `models.L2Networks` was modified + +* `void delete(java.lang.String,java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult delete(java.lang.String,java.lang.String,com.azure.core.util.Context)` +* `void deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` -> `models.OperationStatusResult deleteByIdWithResponse(java.lang.String,com.azure.core.util.Context)` +* `void deleteById(java.lang.String)` -> `models.OperationStatusResult deleteById(java.lang.String)` +* `void deleteByResourceGroup(java.lang.String,java.lang.String)` -> `models.OperationStatusResult deleteByResourceGroup(java.lang.String,java.lang.String)` + +### Features Added + +* `models.ClusterContinueUpdateVersionParameters` was added + +* `models.KubernetesClusterFeatureProvisioningState` was added + +* `models.ClusterUpdateStrategyType` was added + +* `models.RuntimeProtectionConfiguration` was added + +* `models.NodePoolAdministratorConfigurationPatch` was added + +* `models.KubernetesClusterFeature$Update` was added + +* `models.UserAssignedIdentity` was added + +* `models.KubernetesClusterFeatureAvailabilityLifecycle` was added + +* `models.AdministratorConfigurationPatch` was added + +* `models.IdentitySelector` was added + +* `models.ClusterScanRuntimeParametersScanActivity` was added + +* `models.L2ServiceLoadBalancerConfiguration` was added + +* `models.KubernetesClusterFeatureRequired` was added + +* `models.KubernetesClusterFeatureDetailedStatus` was added + +* `models.KubernetesClusterFeatures` was added + +* `models.ClusterUpdateStrategy` was added + +* `models.KubernetesClusterFeaturePatchParameters` was added + +* `models.KubernetesClusterFeature$Definition` was added + +* `models.KubernetesClusterFeature$UpdateStages` was added + +* `models.KubernetesClusterFeature$DefinitionStages` was added + +* `models.ManagedServiceIdentitySelectorType` was added + +* `models.ManagedServiceIdentity` was added + +* `models.RuntimeProtectionEnforcementLevel` was added + +* `models.ClusterScanRuntimeParameters` was added + +* `models.SecretRotationStatus` was added + +* `models.KubernetesClusterFeature` was added + +* `models.StringKeyValuePair` was added + +* `models.SecretArchiveReference` was added + +* `models.KubernetesClusterFeatureList` was added + +* `models.CommandOutputSettings` was added + +* `models.ClusterContinueUpdateVersionMachineGroupTargetingMode` was added + +* `models.RuntimeProtectionStatus` was added + +* `models.ClusterSecretArchive` was added + +* `models.ManagedServiceIdentityType` was added + +* `models.ClusterSecretArchiveEnabled` was added + +#### `models.VirtualMachinePatchParameters` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.EndpointDependency` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.BareMetalMachineKeySetList` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.BareMetalMachinePowerOffParameters` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.BareMetalMachineCordonParameters` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.Nic` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.AgentPool$Update` was modified + +* `withAdministratorConfiguration(models.NodePoolAdministratorConfigurationPatch)` was added + +#### `models.ServicePrincipalInformation` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.ClusterMetricsConfigurationList` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.BareMetalMachine` was modified + +* `secretRotationStatus()` was added +* `machineClusterVersion()` was added +* `machineRoles()` was added +* `runtimeProtectionStatus()` was added + +#### `models.TrunkedNetworkAttachmentConfiguration` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.BmcKeySetList` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.StorageApplianceEnableRemoteVendorManagementParameters` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.ClusterManagerList` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.KeySetUserStatus` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.ClusterDeployParameters` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.ClusterCapacity` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.ClusterAvailableUpgradeVersion` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.StorageProfile` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.MachineDisk` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.KubernetesClusterList` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.CloudServicesNetworkList` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.BareMetalMachineKeySetPatchParameters` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.NetworkConfiguration` was modified + +* `l2ServiceLoadBalancerConfiguration()` was added +* `withL2ServiceLoadBalancerConfiguration(models.L2ServiceLoadBalancerConfiguration)` was added +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.IpAddressPool` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.AgentOptions` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.RackPatchParameters` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.ClusterManagerPatchParameters` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added +* `identity()` was added +* `withIdentity(models.ManagedServiceIdentity)` was added + +#### `models.BareMetalMachineCommandSpecification` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.Cluster` was modified + +* `identity()` was added +* `continueUpdateVersion(models.ClusterContinueUpdateVersionParameters)` was added +* `runtimeProtectionConfiguration()` was added +* `updateStrategy()` was added +* `scanRuntime()` was added +* `commandOutputSettings()` was added +* `continueUpdateVersion(models.ClusterContinueUpdateVersionParameters,com.azure.core.util.Context)` was added +* `scanRuntime(models.ClusterScanRuntimeParameters,com.azure.core.util.Context)` was added +* `secretArchive()` was added + +#### `models.AadConfiguration` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.BareMetalMachineRunReadCommandsParameters` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.ConsolePatchParameters` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.Clusters` was modified + +* `scanRuntime(java.lang.String,java.lang.String)` was added +* `scanRuntime(java.lang.String,java.lang.String,models.ClusterScanRuntimeParameters,com.azure.core.util.Context)` was added +* `continueUpdateVersion(java.lang.String,java.lang.String,models.ClusterContinueUpdateVersionParameters,com.azure.core.util.Context)` was added +* `continueUpdateVersion(java.lang.String,java.lang.String,models.ClusterContinueUpdateVersionParameters)` was added + +#### `models.HardwareValidationStatus` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.ControlPlaneNodeConfiguration` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.BgpAdvertisement` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.KubernetesLabel` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.BareMetalMachineReplaceParameters` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.OperationStatusResult` was modified + +* `outputHead()` was added +* `exitCode()` was added +* `resultRef()` was added +* `resultUrl()` was added + +#### `models.BareMetalMachineList` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.LldpNeighbor` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.StorageAppliance` was modified + +* `manufacturer()` was added +* `secretRotationStatus()` was added +* `model()` was added +* `version()` was added + +#### `models.AgentPoolPatchParameters` was modified + +* `administratorConfiguration()` was added +* `withAdministratorConfiguration(models.NodePoolAdministratorConfigurationPatch)` was added +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.VirtualMachinePowerOffParameters` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.CloudServicesNetworkPatchParameters` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.StorageApplianceList` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.ValidationThreshold` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.OperationListResult` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.FeatureStatus` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.BareMetalMachinePatchParameters` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.ExtendedLocation` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.BareMetalMachine$Definition` was modified + +* `withMachineClusterVersion(java.lang.String)` was added + +#### `models.TrunkedNetworkList` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.ManagedResourceGroupConfiguration` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.TrunkedNetworkPatchParameters` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.HardwareInventory` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.ImageRepositoryCredentials` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.BareMetalMachineRunDataExtractsParameters` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.BareMetalMachineRunCommandParameters` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.ClusterPatchParameters` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `secretArchive()` was added +* `withRuntimeProtectionConfiguration(models.RuntimeProtectionConfiguration)` was added +* `withUpdateStrategy(models.ClusterUpdateStrategy)` was added +* `withIdentity(models.ManagedServiceIdentity)` was added +* `commandOutputSettings()` was added +* `updateStrategy()` was added +* `identity()` was added +* `runtimeProtectionConfiguration()` was added +* `fromJson(com.azure.json.JsonReader)` was added +* `withCommandOutputSettings(models.CommandOutputSettings)` was added +* `withSecretArchive(models.ClusterSecretArchive)` was added + +#### `models.OsDisk` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.ClusterManager$Update` was modified + +* `withIdentity(models.ManagedServiceIdentity)` was added + +#### `models.ControlPlaneNodePatchConfiguration` was modified + +* `withAdministratorConfiguration(models.AdministratorConfigurationPatch)` was added +* `fromJson(com.azure.json.JsonReader)` was added +* `administratorConfiguration()` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.RackList` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.L3NetworkPatchParameters` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `NetworkCloudManager` was modified + +* `kubernetesClusterFeatures()` was added + +#### `models.BgpServiceLoadBalancerConfiguration` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.AdministratorConfiguration` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.VolumeList` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.ClusterAvailableVersion` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.StorageApplianceSkuSlot` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.AdministrativeCredentials` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.VirtualMachineList` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.BareMetalMachineConfigurationData` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.BmcKeySetPatchParameters` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.SshPublicKey` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.RackSkuList` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.ClusterUpdateVersionParameters` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.ConsoleList` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.ClusterList` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.AgentPoolUpgradeSettings` was modified + +* `drainTimeout()` was added +* `fromJson(com.azure.json.JsonReader)` was added +* `withDrainTimeout(java.lang.Long)` was added +* `withMaxUnavailable(java.lang.String)` was added +* `maxUnavailable()` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.ClusterManager$Definition` was modified + +* `withIdentity(models.ManagedServiceIdentity)` was added + +#### `models.KeySetUser` was modified + +* `withUserPrincipalName(java.lang.String)` was added +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added +* `userPrincipalName()` was added + +#### `models.VolumePatchParameters` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.AgentPoolList` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.NetworkAttachment` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.HardwareInventoryNetworkInterface` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.KubernetesCluster$Update` was modified + +* `withAdministratorConfiguration(models.AdministratorConfigurationPatch)` was added + +#### `models.AvailableUpgrade` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.Cluster$Definition` was modified + +* `withRuntimeProtectionConfiguration(models.RuntimeProtectionConfiguration)` was added +* `withCommandOutputSettings(models.CommandOutputSettings)` was added +* `withSecretArchive(models.ClusterSecretArchive)` was added +* `withIdentity(models.ManagedServiceIdentity)` was added +* `withUpdateStrategy(models.ClusterUpdateStrategy)` was added + +#### `models.KubernetesClusterRestartNodeParameters` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.EgressEndpoint` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.L3NetworkAttachmentConfiguration` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.Cluster$Update` was modified + +* `withSecretArchive(models.ClusterSecretArchive)` was added +* `withUpdateStrategy(models.ClusterUpdateStrategy)` was added +* `withIdentity(models.ManagedServiceIdentity)` was added +* `withCommandOutputSettings(models.CommandOutputSettings)` was added +* `withRuntimeProtectionConfiguration(models.RuntimeProtectionConfiguration)` was added + +#### `models.StorageApplianceConfigurationData` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.AttachedNetworkConfiguration` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.L3NetworkList` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.MachineSkuSlot` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.L2NetworkPatchParameters` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.StorageAppliancePatchParameters` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.KubernetesClusterPatchParameters` was modified + +* `withAdministratorConfiguration(models.AdministratorConfigurationPatch)` was added +* `toJson(com.azure.json.JsonWriter)` was added +* `administratorConfiguration()` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.RackDefinition` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.VirtualMachinePlacementHint` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.ClusterMetricsConfigurationPatchParameters` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.L2NetworkAttachmentConfiguration` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.L2NetworkList` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.KubernetesClusterNode` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.NetworkInterface` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.OperationDisplay` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.ClusterManager` was modified + +* `identity()` was added + +#### `models.ServiceLoadBalancerBgpPeer` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.InitialAgentPoolConfiguration` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + ## 1.1.0-beta.1 (2024-11-21) - Azure Resource Manager NetworkCloud client library for Java. This package contains Microsoft Azure SDK for NetworkCloud Management SDK. The Network Cloud APIs provide management of the Azure Operator Nexus compute resources such as on-premises clusters, hardware resources, and workload infrastructure resources. Package tag package-2024-06-01-preview. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/README.md b/sdk/networkcloud/azure-resourcemanager-networkcloud/README.md index 05e54f25f52a..43a0c41dd76e 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/README.md +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/README.md @@ -2,7 +2,7 @@ Azure Resource Manager NetworkCloud client library for Java. -This package contains Microsoft Azure SDK for NetworkCloud Management SDK. The Network Cloud APIs provide management of the Azure Operator Nexus compute resources such as on-premises clusters, hardware resources, and workload infrastructure resources. Package tag package-2024-06-01-preview. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). +This package contains Microsoft Azure SDK for NetworkCloud Management SDK. The Network Cloud APIs provide management of the Azure Operator Nexus compute resources such as on-premises clusters, hardware resources, and workload infrastructure resources. Package tag package-2024-07-01. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). ## We'd love to hear your feedback @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-networkcloud - 1.1.0-beta.1 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -52,7 +52,7 @@ Azure subscription ID can be configured via `AZURE_SUBSCRIPTION_ID` environment Assuming the use of the `DefaultAzureCredential` credential class, the client can be authenticated using the following code: ```java -AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); +AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); @@ -60,7 +60,7 @@ NetworkCloudManager manager = NetworkCloudManager .authenticate(credential, profile); ``` -The sample code assumes global Azure. Please change `AzureEnvironment.AZURE` variable if otherwise. +The sample code assumes global Azure. Please change the `AzureCloud.AZURE_PUBLIC_CLOUD` variable if otherwise. See [Authentication][authenticate] for more options. @@ -100,5 +100,3 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [cg]: https://github.com/Azure/azure-sdk-for-java/blob/main/CONTRIBUTING.md [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ - -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fnetworkcloud%2Fazure-resourcemanager-networkcloud%2FREADME.png) diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/SAMPLE.md b/sdk/networkcloud/azure-resourcemanager-networkcloud/SAMPLE.md index cf82527d4cc0..49ed863b900d 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/SAMPLE.md +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/SAMPLE.md @@ -213,8 +213,8 @@ import java.util.Map; public final class AgentPoolsCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * AgentPools_Create.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/AgentPools_Create. + * json */ /** * Sample code: Create or update Kubernetes cluster agent pool. @@ -229,7 +229,7 @@ public final class AgentPoolsCreateOrUpdateSamples { .withExistingKubernetesCluster("resourceGroupName", "kubernetesClusterName") .withCount(3L) .withMode(AgentPoolMode.SYSTEM) - .withVmSkuName("NC_XXXX") + .withVmSkuName("NC_P46_224_v1") .withTags(mapOf("key1", "fakeTokenPlaceholder", "key2", "fakeTokenPlaceholder")) .withExtendedLocation(new ExtendedLocation().withName( "/subscriptions/123e4567-e89b-12d3-a456-426655440000/resourceGroups/resourceGroupName/providers/Microsoft.ExtendedLocation/customLocations/clusterExtendedLocationName") @@ -251,7 +251,8 @@ public final class AgentPoolsCreateOrUpdateSamples { .withPluginType(KubernetesPluginType.MACVLAN)))) .withAvailabilityZones(Arrays.asList("1", "2", "3")) .withLabels(Arrays.asList(new KubernetesLabel().withKey("fakeTokenPlaceholder").withValue("true"))) - .withTaints(Arrays.asList(new KubernetesLabel().withKey("fakeTokenPlaceholder").withValue("true"))) + .withTaints( + Arrays.asList(new KubernetesLabel().withKey("fakeTokenPlaceholder").withValue("true:NoSchedule"))) .withUpgradeSettings(new AgentPoolUpgradeSettings().withMaxSurge("1")) .create(); } @@ -279,8 +280,8 @@ public final class AgentPoolsCreateOrUpdateSamples { public final class AgentPoolsDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * AgentPools_Delete.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/AgentPools_Delete. + * json */ /** * Sample code: Delete Kubernetes cluster agent pool. @@ -304,8 +305,7 @@ public final class AgentPoolsDeleteSamples { public final class AgentPoolsGetSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * AgentPools_Get.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/AgentPools_Get.json */ /** * Sample code: Get Kubernetes cluster agent pool. @@ -330,7 +330,7 @@ public final class AgentPoolsGetSamples { public final class AgentPoolsListByKubernetesClusterSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * AgentPools_ListByKubernetesCluster.json */ /** @@ -363,8 +363,8 @@ import java.util.Map; public final class AgentPoolsUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * AgentPools_Patch.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/AgentPools_Patch. + * json */ /** * Sample code: Patch Kubernetes cluster agent pool. @@ -419,7 +419,7 @@ import java.util.Map; public final class BareMetalMachineKeySetsCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachineKeySets_Create.json */ /** @@ -477,7 +477,7 @@ public final class BareMetalMachineKeySetsCreateOrUpdateSamples { public final class BareMetalMachineKeySetsDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachineKeySets_Delete.json */ /** @@ -502,7 +502,7 @@ public final class BareMetalMachineKeySetsDeleteSamples { public final class BareMetalMachineKeySetsGetSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachineKeySets_Get.json */ /** @@ -528,7 +528,7 @@ public final class BareMetalMachineKeySetsGetSamples { public final class BareMetalMachineKeySetsListByClusterSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachineKeySets_ListByCluster.json */ /** @@ -561,7 +561,7 @@ import java.util.Map; public final class BareMetalMachineKeySetsUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachineKeySets_Patch.json */ /** @@ -617,7 +617,7 @@ import com.azure.resourcemanager.networkcloud.models.BareMetalMachineEvacuate; public final class BareMetalMachinesCordonSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_Cordon.json */ /** @@ -648,7 +648,7 @@ import java.util.Map; public final class BareMetalMachinesCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_Create.json */ /** @@ -704,7 +704,7 @@ public final class BareMetalMachinesCreateOrUpdateSamples { public final class BareMetalMachinesDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_Delete.json */ /** @@ -728,7 +728,7 @@ public final class BareMetalMachinesDeleteSamples { public final class BareMetalMachinesGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_Get.json */ /** @@ -753,7 +753,7 @@ public final class BareMetalMachinesGetByResourceGroupSamples { public final class BareMetalMachinesListSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_ListBySubscription.json */ /** @@ -777,7 +777,7 @@ public final class BareMetalMachinesListSamples { public final class BareMetalMachinesListByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_ListByResourceGroup.json */ /** @@ -804,7 +804,7 @@ import com.azure.resourcemanager.networkcloud.models.BareMetalMachineSkipShutdow public final class BareMetalMachinesPowerOffSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_PowerOff.json */ /** @@ -830,7 +830,7 @@ public final class BareMetalMachinesPowerOffSamples { public final class BareMetalMachinesReimageSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_Reimage.json */ /** @@ -857,7 +857,7 @@ import com.azure.resourcemanager.networkcloud.models.BareMetalMachineReplacePara public final class BareMetalMachinesReplaceSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_Replace.json */ /** @@ -889,7 +889,7 @@ public final class BareMetalMachinesReplaceSamples { public final class BareMetalMachinesRestartSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_Restart.json */ /** @@ -916,7 +916,7 @@ import java.util.Arrays; public final class BareMetalMachinesRunCommandSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_RunCommand.json */ /** @@ -949,7 +949,7 @@ import java.util.Arrays; public final class BareMetalMachinesRunDataExtractsSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_RunDataExtracts.json */ /** @@ -983,7 +983,7 @@ import java.util.Arrays; public final class BareMetalMachinesRunReadCommandsSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_RunReadCommands.json */ /** @@ -1015,7 +1015,7 @@ public final class BareMetalMachinesRunReadCommandsSamples { public final class BareMetalMachinesStartSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_Start.json */ /** @@ -1039,7 +1039,7 @@ public final class BareMetalMachinesStartSamples { public final class BareMetalMachinesUncordonSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_Uncordon.json */ /** @@ -1067,7 +1067,7 @@ import java.util.Map; public final class BareMetalMachinesUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_Patch.json */ /** @@ -1118,8 +1118,8 @@ import java.util.Map; public final class BmcKeySetsCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * BmcKeySets_Create.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/BmcKeySets_Create. + * json */ /** * Sample code: Create or update baseboard management controller key set of cluster. @@ -1174,8 +1174,8 @@ public final class BmcKeySetsCreateOrUpdateSamples { public final class BmcKeySetsDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * BmcKeySets_Delete.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/BmcKeySets_Delete. + * json */ /** * Sample code: Delete baseboard management controller key set of cluster. @@ -1199,8 +1199,7 @@ public final class BmcKeySetsDeleteSamples { public final class BmcKeySetsGetSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * BmcKeySets_Get.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/BmcKeySets_Get.json */ /** * Sample code: Get baseboard management controller key set of cluster. @@ -1224,7 +1223,7 @@ public final class BmcKeySetsGetSamples { public final class BmcKeySetsListByClusterSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BmcKeySets_ListByCluster.json */ /** @@ -1256,8 +1255,8 @@ import java.util.Map; public final class BmcKeySetsUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * BmcKeySets_Patch.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/BmcKeySets_Patch. + * json */ /** * Sample code: Patch baseboard management controller key set of cluster. @@ -1315,7 +1314,7 @@ import java.util.Map; public final class CloudServicesNetworksCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * CloudServicesNetworks_Create.json */ /** @@ -1363,7 +1362,7 @@ public final class CloudServicesNetworksCreateOrUpdateSamples { public final class CloudServicesNetworksDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * CloudServicesNetworks_Delete.json */ /** @@ -1387,7 +1386,7 @@ public final class CloudServicesNetworksDeleteSamples { public final class CloudServicesNetworksGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * CloudServicesNetworks_Get.json */ /** @@ -1412,7 +1411,7 @@ public final class CloudServicesNetworksGetByResourceGroupSamples { public final class CloudServicesNetworksListSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * CloudServicesNetworks_ListBySubscription.json */ /** @@ -1436,7 +1435,7 @@ public final class CloudServicesNetworksListSamples { public final class CloudServicesNetworksListByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * CloudServicesNetworks_ListByResourceGroup.json */ /** @@ -1468,7 +1467,7 @@ import java.util.Map; public final class CloudServicesNetworksUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * CloudServicesNetworks_Patch.json */ /** @@ -1520,7 +1519,7 @@ import java.util.Map; public final class ClusterManagersCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * ClusterManagers_Create.json */ /** @@ -1547,7 +1546,7 @@ public final class ClusterManagersCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * ClusterManagers_Create_Uami.json */ /** @@ -1598,7 +1597,7 @@ public final class ClusterManagersCreateOrUpdateSamples { public final class ClusterManagersDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * ClusterManagers_Delete.json */ /** @@ -1621,8 +1620,8 @@ public final class ClusterManagersDeleteSamples { public final class ClusterManagersGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * ClusterManagers_Get.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ClusterManagers_Get + * .json */ /** * Sample code: Get cluster manager. @@ -1646,7 +1645,7 @@ public final class ClusterManagersGetByResourceGroupSamples { public final class ClusterManagersListSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * ClusterManagers_ListBySubscription.json */ /** @@ -1670,7 +1669,7 @@ public final class ClusterManagersListSamples { public final class ClusterManagersListByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * ClusterManagers_ListByResourceGroup.json */ /** @@ -1701,7 +1700,7 @@ import java.util.Map; public final class ClusterManagersUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * ClusterManagers_Patch.json */ /** @@ -1750,7 +1749,7 @@ import com.azure.resourcemanager.networkcloud.models.ClusterContinueUpdateVersio public final class ClustersContinueUpdateVersionSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Clusters_ContinueUpdateVersion.json */ /** @@ -1805,8 +1804,8 @@ import java.util.Map; public final class ClustersCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Clusters_Create.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Clusters_Create. + * json */ /** * Sample code: Create or update cluster. @@ -1946,8 +1945,8 @@ public final class ClustersCreateOrUpdateSamples { public final class ClustersDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Clusters_Delete.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Clusters_Delete. + * json */ /** * Sample code: Delete cluster. @@ -1972,8 +1971,8 @@ import java.util.Arrays; public final class ClustersDeploySamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Clusters_Deploy.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Clusters_Deploy. + * json */ /** * Sample code: Deploy cluster. @@ -1988,7 +1987,7 @@ public final class ClustersDeploySamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Clusters_Deploy_SkipValidation.json */ /** @@ -2015,8 +2014,7 @@ public final class ClustersDeploySamples { public final class ClustersGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Clusters_Get.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Clusters_Get.json */ /** * Sample code: Get cluster. @@ -2039,7 +2037,7 @@ public final class ClustersGetByResourceGroupSamples { public final class ClustersListSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Clusters_ListBySubscription.json */ /** @@ -2062,7 +2060,7 @@ public final class ClustersListSamples { public final class ClustersListByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Clusters_ListByResourceGroup.json */ /** @@ -2089,7 +2087,7 @@ import com.azure.resourcemanager.networkcloud.models.ClusterScanRuntimeParameter public final class ClustersScanRuntimeSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Clusters_ScanRuntime.json */ /** @@ -2140,7 +2138,7 @@ import java.util.Map; public final class ClustersUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Clusters_Patch_UpdateStrategy.json */ /** @@ -2164,7 +2162,7 @@ public final class ClustersUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Clusters_Patch_Location.json */ /** @@ -2184,7 +2182,7 @@ public final class ClustersUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Clusters_Patch_AggregatorOrSingleRackDefinition.json */ /** @@ -2243,7 +2241,7 @@ public final class ClustersUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Clusters_Patch_CommandOutput.json */ /** @@ -2273,7 +2271,7 @@ public final class ClustersUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Clusters_Patch_RuntimeProtectionConfiguration.json */ /** @@ -2295,7 +2293,7 @@ public final class ClustersUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Clusters_Patch_SecretArchive.json */ /** @@ -2339,7 +2337,7 @@ import com.azure.resourcemanager.networkcloud.models.ClusterUpdateVersionParamet public final class ClustersUpdateVersionSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Clusters_UpdateVersion.json */ /** @@ -2371,8 +2369,8 @@ import java.util.Map; public final class ConsolesCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Consoles_Create.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Consoles_Create. + * json */ /** * Sample code: Create or update virtual machine console. @@ -2418,8 +2416,8 @@ public final class ConsolesCreateOrUpdateSamples { public final class ConsolesDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Consoles_Delete.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Consoles_Delete. + * json */ /** * Sample code: Delete virtual machine console. @@ -2442,8 +2440,7 @@ public final class ConsolesDeleteSamples { public final class ConsolesGetSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Consoles_Get.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Consoles_Get.json */ /** * Sample code: Get virtual machine console. @@ -2466,7 +2463,7 @@ public final class ConsolesGetSamples { public final class ConsolesListByVirtualMachineSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Consoles_ListByVirtualMachine.json */ /** @@ -2498,8 +2495,7 @@ import java.util.Map; public final class ConsolesUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Consoles_Patch.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Consoles_Patch.json */ /** * Sample code: Patch virtual machine console. @@ -2546,7 +2542,7 @@ import java.util.Map; public final class KubernetesClusterFeaturesCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * KubernetesClusterFeatures_Create.json */ /** @@ -2589,7 +2585,7 @@ public final class KubernetesClusterFeaturesCreateOrUpdateSamples { public final class KubernetesClusterFeaturesDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * KubernetesClusterFeatures_Delete.json */ /** @@ -2614,7 +2610,7 @@ public final class KubernetesClusterFeaturesDeleteSamples { public final class KubernetesClusterFeaturesGetSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * KubernetesClusterFeatures_Get.json */ /** @@ -2639,7 +2635,7 @@ public final class KubernetesClusterFeaturesGetSamples { public final class KubernetesClusterFeaturesListByKubernetesClusterSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * KubernetesClusterFeatures_ListByKubernetesCluster.json */ /** @@ -2670,7 +2666,7 @@ import java.util.Map; public final class KubernetesClusterFeaturesUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * KubernetesClusterFeatures_Patch.json */ /** @@ -2746,7 +2742,7 @@ import java.util.Map; public final class KubernetesClustersCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * KubernetesClusters_Create.json */ /** @@ -2768,7 +2764,7 @@ public final class KubernetesClustersCreateOrUpdateSamples { .withSshPublicKeys(Arrays.asList(new SshPublicKey().withKeyData("fakeTokenPlaceholder")))) .withAvailabilityZones(Arrays.asList("1", "2", "3")) .withCount(3L) - .withVmSkuName("NC_XXXX")) + .withVmSkuName("NC_G6_28_v1")) .withInitialAgentPoolConfigurations(Arrays.asList(new InitialAgentPoolConfiguration() .withAdministratorConfiguration(new AdministratorConfiguration().withAdminUsername("azure") .withSshPublicKeys(Arrays.asList(new SshPublicKey().withKeyData("fakeTokenPlaceholder")))) @@ -2790,9 +2786,10 @@ public final class KubernetesClustersCreateOrUpdateSamples { .withLabels(Arrays.asList(new KubernetesLabel().withKey("fakeTokenPlaceholder").withValue("true"))) .withMode(AgentPoolMode.SYSTEM) .withName("SystemPool-1") - .withTaints(Arrays.asList(new KubernetesLabel().withKey("fakeTokenPlaceholder").withValue("true"))) + .withTaints( + Arrays.asList(new KubernetesLabel().withKey("fakeTokenPlaceholder").withValue("true:NoSchedule"))) .withUpgradeSettings(new AgentPoolUpgradeSettings().withMaxSurge("1")) - .withVmSkuName("NC_XXXX"))) + .withVmSkuName("NC_P46_224_v1"))) .withKubernetesVersion("1.XX.Y") .withNetworkConfiguration(new NetworkConfiguration() .withAttachedNetworkConfiguration(new AttachedNetworkConfiguration() @@ -2847,7 +2844,7 @@ public final class KubernetesClustersCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * KubernetesClusters_L2LoadBalancer_Create.json */ /** @@ -2869,7 +2866,7 @@ public final class KubernetesClustersCreateOrUpdateSamples { .withSshPublicKeys(Arrays.asList(new SshPublicKey().withKeyData("fakeTokenPlaceholder")))) .withAvailabilityZones(Arrays.asList("1", "2", "3")) .withCount(3L) - .withVmSkuName("NC_XXXX")) + .withVmSkuName("NC_G6_28_v1")) .withInitialAgentPoolConfigurations(Arrays.asList(new InitialAgentPoolConfiguration() .withAdministratorConfiguration(new AdministratorConfiguration().withAdminUsername("azure") .withSshPublicKeys(Arrays.asList(new SshPublicKey().withKeyData("fakeTokenPlaceholder")))) @@ -2891,9 +2888,10 @@ public final class KubernetesClustersCreateOrUpdateSamples { .withLabels(Arrays.asList(new KubernetesLabel().withKey("fakeTokenPlaceholder").withValue("true"))) .withMode(AgentPoolMode.SYSTEM) .withName("SystemPool-1") - .withTaints(Arrays.asList(new KubernetesLabel().withKey("fakeTokenPlaceholder").withValue("true"))) + .withTaints( + Arrays.asList(new KubernetesLabel().withKey("fakeTokenPlaceholder").withValue("true:NoSchedule"))) .withUpgradeSettings(new AgentPoolUpgradeSettings().withMaxSurge("1")) - .withVmSkuName("NC_XXXX"))) + .withVmSkuName("NC_P46_224_v1"))) .withKubernetesVersion("1.XX.Y") .withNetworkConfiguration(new NetworkConfiguration() .withAttachedNetworkConfiguration(new AttachedNetworkConfiguration() @@ -2952,7 +2950,7 @@ public final class KubernetesClustersCreateOrUpdateSamples { public final class KubernetesClustersDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * KubernetesClusters_Delete.json */ /** @@ -2976,7 +2974,7 @@ public final class KubernetesClustersDeleteSamples { public final class KubernetesClustersGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * KubernetesClusters_Get.json */ /** @@ -3001,7 +2999,7 @@ public final class KubernetesClustersGetByResourceGroupSamples { public final class KubernetesClustersListSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * KubernetesClusters_ListBySubscription.json */ /** @@ -3025,7 +3023,7 @@ public final class KubernetesClustersListSamples { public final class KubernetesClustersListByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * KubernetesClusters_ListByResourceGroup.json */ /** @@ -3051,7 +3049,7 @@ import com.azure.resourcemanager.networkcloud.models.KubernetesClusterRestartNod public final class KubernetesClustersRestartNodeSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * KubernetesClusters_RestartNode.json */ /** @@ -3086,7 +3084,7 @@ import java.util.Map; public final class KubernetesClustersUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * KubernetesClusters_Patch.json */ /** @@ -3139,8 +3137,8 @@ import java.util.Map; public final class L2NetworksCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * L2Networks_Create.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/L2Networks_Create. + * json */ /** * Sample code: Create or update L2 network. @@ -3186,8 +3184,8 @@ public final class L2NetworksCreateOrUpdateSamples { public final class L2NetworksDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * L2Networks_Delete.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/L2Networks_Delete. + * json */ /** * Sample code: Delete L2 network. @@ -3209,8 +3207,7 @@ public final class L2NetworksDeleteSamples { public final class L2NetworksGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * L2Networks_Get.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/L2Networks_Get.json */ /** * Sample code: Get L2 network. @@ -3233,7 +3230,7 @@ public final class L2NetworksGetByResourceGroupSamples { public final class L2NetworksListSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * L2Networks_ListBySubscription.json */ /** @@ -3257,7 +3254,7 @@ public final class L2NetworksListSamples { public final class L2NetworksListByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * L2Networks_ListByResourceGroup.json */ /** @@ -3285,8 +3282,8 @@ import java.util.Map; public final class L2NetworksUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * L2Networks_Patch.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/L2Networks_Patch. + * json */ /** * Sample code: Patch L2 network. @@ -3328,8 +3325,8 @@ import java.util.Map; public final class L3NetworksCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * L3Networks_Create.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/L3Networks_Create. + * json */ /** * Sample code: Create or update L3 network. @@ -3378,8 +3375,8 @@ public final class L3NetworksCreateOrUpdateSamples { public final class L3NetworksDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * L3Networks_Delete.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/L3Networks_Delete. + * json */ /** * Sample code: Delete L3 network. @@ -3401,8 +3398,7 @@ public final class L3NetworksDeleteSamples { public final class L3NetworksGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * L3Networks_Get.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/L3Networks_Get.json */ /** * Sample code: Get L3network. @@ -3425,7 +3421,7 @@ public final class L3NetworksGetByResourceGroupSamples { public final class L3NetworksListSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * L3Networks_ListBySubscription.json */ /** @@ -3449,7 +3445,7 @@ public final class L3NetworksListSamples { public final class L3NetworksListByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * L3Networks_ListByResourceGroup.json */ /** @@ -3477,8 +3473,8 @@ import java.util.Map; public final class L3NetworksUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * L3Networks_Patch.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/L3Networks_Patch. + * json */ /** * Sample code: Patch L3 network. @@ -3520,7 +3516,7 @@ import java.util.Map; public final class MetricsConfigurationsCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * ClusterMetricsConfigurations_Create.json */ /** @@ -3566,7 +3562,7 @@ public final class MetricsConfigurationsCreateOrUpdateSamples { public final class MetricsConfigurationsDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * ClusterMetricsConfigurations_Delete.json */ /** @@ -3591,7 +3587,7 @@ public final class MetricsConfigurationsDeleteSamples { public final class MetricsConfigurationsGetSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * ClusterMetricsConfigurations_Get.json */ /** @@ -3616,7 +3612,7 @@ public final class MetricsConfigurationsGetSamples { public final class MetricsConfigurationsListByClusterSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * ClusterMetricsConfigurations_ListByCluster.json */ /** @@ -3646,7 +3642,7 @@ import java.util.Map; public final class MetricsConfigurationsUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * ClusterMetricsConfigurations_Patch.json */ /** @@ -3689,8 +3685,8 @@ public final class MetricsConfigurationsUpdateSamples { public final class OperationsListSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Operations_List.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Operations_List. + * json */ /** * Sample code: List resource provider operations. @@ -3713,8 +3709,7 @@ public final class OperationsListSamples { public final class RackSkusGetSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * RackSkus_Get.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/RackSkus_Get.json */ /** * Sample code: Get rack SKU resource. @@ -3736,7 +3731,7 @@ public final class RackSkusGetSamples { public final class RackSkusListSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * RackSkus_ListBySubscription.json */ /** @@ -3763,8 +3758,7 @@ import java.util.Map; public final class RacksCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Racks_Create.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Racks_Create.json */ /** * Sample code: Create or update rack. @@ -3811,8 +3805,7 @@ public final class RacksCreateOrUpdateSamples { public final class RacksDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Racks_Delete.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Racks_Delete.json */ /** * Sample code: Delete rack. @@ -3834,8 +3827,7 @@ public final class RacksDeleteSamples { public final class RacksGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/Racks_Get. - * json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Racks_Get.json */ /** * Sample code: Get rack. @@ -3858,7 +3850,7 @@ public final class RacksGetByResourceGroupSamples { public final class RacksListSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Racks_ListBySubscription.json */ /** @@ -3881,7 +3873,7 @@ public final class RacksListSamples { public final class RacksListByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Racks_ListByResourceGroup.json */ /** @@ -3908,8 +3900,7 @@ import java.util.Map; public final class RacksUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Racks_Patch.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Racks_Patch.json */ /** * Sample code: Patch rack. @@ -3955,7 +3946,7 @@ import java.util.Map; public final class StorageAppliancesCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * StorageAppliances_Create.json */ /** @@ -4006,7 +3997,7 @@ public final class StorageAppliancesCreateOrUpdateSamples { public final class StorageAppliancesDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * StorageAppliances_Delete.json */ /** @@ -4030,7 +4021,7 @@ public final class StorageAppliancesDeleteSamples { public final class StorageAppliancesDisableRemoteVendorManagementSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * StorageAppliances_DisableRemoteVendorManagement.json */ /** @@ -4059,7 +4050,7 @@ import java.util.Arrays; public final class StorageAppliancesEnableRemoteVendorManagementSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * StorageAppliances_EnableRemoteVendorManagement.json */ /** @@ -4087,7 +4078,7 @@ public final class StorageAppliancesEnableRemoteVendorManagementSamples { public final class StorageAppliancesGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * StorageAppliances_Get.json */ /** @@ -4112,7 +4103,7 @@ public final class StorageAppliancesGetByResourceGroupSamples { public final class StorageAppliancesListSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * StorageAppliances_ListBySubscription.json */ /** @@ -4136,7 +4127,7 @@ public final class StorageAppliancesListSamples { public final class StorageAppliancesListByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * StorageAppliances_ListByResourceGroup.json */ /** @@ -4164,7 +4155,7 @@ import java.util.Map; public final class StorageAppliancesUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * StorageAppliances_Patch.json */ /** @@ -4211,7 +4202,7 @@ import java.util.Map; public final class TrunkedNetworksCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * TrunkedNetworks_Create.json */ /** @@ -4260,7 +4251,7 @@ public final class TrunkedNetworksCreateOrUpdateSamples { public final class TrunkedNetworksDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * TrunkedNetworks_Delete.json */ /** @@ -4283,8 +4274,8 @@ public final class TrunkedNetworksDeleteSamples { public final class TrunkedNetworksGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * TrunkedNetworks_Get.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/TrunkedNetworks_Get + * .json */ /** * Sample code: Get Trunked network. @@ -4308,7 +4299,7 @@ public final class TrunkedNetworksGetByResourceGroupSamples { public final class TrunkedNetworksListSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * TrunkedNetworks_ListBySubscription.json */ /** @@ -4332,7 +4323,7 @@ public final class TrunkedNetworksListSamples { public final class TrunkedNetworksListByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * TrunkedNetworks_ListByResourceGroup.json */ /** @@ -4360,7 +4351,7 @@ import java.util.Map; public final class TrunkedNetworksUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * TrunkedNetworks_Patch.json */ /** @@ -4418,7 +4409,7 @@ import java.util.Map; public final class VirtualMachinesCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * VirtualMachines_Create.json */ /** @@ -4496,7 +4487,7 @@ public final class VirtualMachinesCreateOrUpdateSamples { public final class VirtualMachinesDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * VirtualMachines_Delete.json */ /** @@ -4519,8 +4510,8 @@ public final class VirtualMachinesDeleteSamples { public final class VirtualMachinesGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * VirtualMachines_Get.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/VirtualMachines_Get + * .json */ /** * Sample code: Get virtual machine. @@ -4544,7 +4535,7 @@ public final class VirtualMachinesGetByResourceGroupSamples { public final class VirtualMachinesListSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * VirtualMachines_ListBySubscription.json */ /** @@ -4568,7 +4559,7 @@ public final class VirtualMachinesListSamples { public final class VirtualMachinesListByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * VirtualMachines_ListByResourceGroup.json */ /** @@ -4595,7 +4586,7 @@ import com.azure.resourcemanager.networkcloud.models.VirtualMachinePowerOffParam public final class VirtualMachinesPowerOffSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * VirtualMachines_PowerOff.json */ /** @@ -4621,7 +4612,7 @@ public final class VirtualMachinesPowerOffSamples { public final class VirtualMachinesReimageSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * VirtualMachines_Reimage.json */ /** @@ -4644,7 +4635,7 @@ public final class VirtualMachinesReimageSamples { public final class VirtualMachinesRestartSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * VirtualMachines_Restart.json */ /** @@ -4667,7 +4658,7 @@ public final class VirtualMachinesRestartSamples { public final class VirtualMachinesStartSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * VirtualMachines_Start.json */ /** @@ -4695,7 +4686,7 @@ import java.util.Map; public final class VirtualMachinesUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * VirtualMachines_Patch.json */ /** @@ -4742,8 +4733,7 @@ import java.util.Map; public final class VolumesCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Volumes_Create.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Volumes_Create.json */ /** * Sample code: Create or update volume. @@ -4786,8 +4776,7 @@ public final class VolumesCreateOrUpdateSamples { public final class VolumesDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Volumes_Delete.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Volumes_Delete.json */ /** * Sample code: Delete volume. @@ -4809,8 +4798,7 @@ public final class VolumesDeleteSamples { public final class VolumesGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Volumes_Get.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Volumes_Get.json */ /** * Sample code: Get volume. @@ -4833,7 +4821,7 @@ public final class VolumesGetByResourceGroupSamples { public final class VolumesListSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Volumes_ListBySubscription.json */ /** @@ -4856,7 +4844,7 @@ public final class VolumesListSamples { public final class VolumesListByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Volumes_ListByResourceGroup.json */ /** @@ -4883,8 +4871,7 @@ import java.util.Map; public final class VolumesUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Volumes_Patch.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Volumes_Patch.json */ /** * Sample code: Patch volume. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/pom.xml b/sdk/networkcloud/azure-resourcemanager-networkcloud/pom.xml index 781f0ee2e7f9..71288c578642 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/pom.xml +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/pom.xml @@ -14,11 +14,11 @@ com.azure.resourcemanager azure-resourcemanager-networkcloud - 1.1.0-beta.2 + 1.2.0-beta.1 jar Microsoft Azure SDK for NetworkCloud Management - This package contains Microsoft Azure SDK for NetworkCloud Management SDK. For documentation on how to use this package, please see https://aka.ms/azsdk/java/mgmt. The Network Cloud APIs provide management of the Azure Operator Nexus compute resources such as on-premises clusters, hardware resources, and workload infrastructure resources. Package tag package-2024-06-01-preview. + This package contains Microsoft Azure SDK for NetworkCloud Management SDK. For documentation on how to use this package, please see https://aka.ms/azsdk/java/mgmt. The Network Cloud APIs provide management of the Azure Operator Nexus compute resources such as on-premises clusters, hardware resources, and workload infrastructure resources. Package tag package-2024-07-01. https://github.com/Azure/azure-sdk-for-java @@ -52,23 +52,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/main/java/com/azure/resourcemanager/networkcloud/NetworkCloudManager.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/main/java/com/azure/resourcemanager/networkcloud/NetworkCloudManager.java index 3693f811cf42..5b69e0dfa9ff 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/main/java/com/azure/resourcemanager/networkcloud/NetworkCloudManager.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/main/java/com/azure/resourcemanager/networkcloud/NetworkCloudManager.java @@ -22,6 +22,7 @@ import com.azure.core.http.policy.UserAgentPolicy; import com.azure.core.management.profile.AzureProfile; import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.networkcloud.fluent.NetworkCloud; import com.azure.resourcemanager.networkcloud.implementation.AgentPoolsImpl; @@ -69,6 +70,7 @@ import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; @@ -170,6 +172,9 @@ public static Configurable configure() { */ public static final class Configurable { private static final ClientLogger LOGGER = new ClientLogger(Configurable.class); + private static final String SDK_VERSION = "version"; + private static final Map PROPERTIES + = CoreUtils.getProperties("azure-resourcemanager-networkcloud.properties"); private HttpClient httpClient; private HttpLogOptions httpLogOptions; @@ -277,12 +282,14 @@ public NetworkCloudManager authenticate(TokenCredential credential, AzureProfile Objects.requireNonNull(credential, "'credential' cannot be null."); Objects.requireNonNull(profile, "'profile' cannot be null."); + String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); + StringBuilder userAgentBuilder = new StringBuilder(); userAgentBuilder.append("azsdk-java") .append("-") .append("com.azure.resourcemanager.networkcloud") .append("/") - .append("1.1.0-beta.1"); + .append(clientVersion); if (!Configuration.getGlobalConfiguration().get("AZURE_TELEMETRY_DISABLED", false)) { userAgentBuilder.append(" (") .append(Configuration.getGlobalConfiguration().get("java.version")) diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/main/java/com/azure/resourcemanager/networkcloud/implementation/NetworkCloudImpl.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/main/java/com/azure/resourcemanager/networkcloud/implementation/NetworkCloudImpl.java index a84712d0664c..947b4c6f86d7 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/main/java/com/azure/resourcemanager/networkcloud/implementation/NetworkCloudImpl.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/main/java/com/azure/resourcemanager/networkcloud/implementation/NetworkCloudImpl.java @@ -439,7 +439,7 @@ public ConsolesClient getConsoles() { this.defaultPollInterval = defaultPollInterval; this.subscriptionId = subscriptionId; this.endpoint = endpoint; - this.apiVersion = "2024-06-01-preview"; + this.apiVersion = "2024-07-01"; this.operations = new OperationsClientImpl(this); this.bareMetalMachines = new BareMetalMachinesClientImpl(this); this.cloudServicesNetworks = new CloudServicesNetworksClientImpl(this); diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/main/resources/azure-resourcemanager-networkcloud.properties b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/main/resources/azure-resourcemanager-networkcloud.properties new file mode 100644 index 000000000000..defbd48204e4 --- /dev/null +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/main/resources/azure-resourcemanager-networkcloud.properties @@ -0,0 +1 @@ +version=${project.version} diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/AgentPoolsCreateOrUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/AgentPoolsCreateOrUpdateSamples.java index a85624b3d475..1cadb4d5a372 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/AgentPoolsCreateOrUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/AgentPoolsCreateOrUpdateSamples.java @@ -28,8 +28,8 @@ public final class AgentPoolsCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * AgentPools_Create.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/AgentPools_Create. + * json */ /** * Sample code: Create or update Kubernetes cluster agent pool. @@ -44,7 +44,7 @@ public final class AgentPoolsCreateOrUpdateSamples { .withExistingKubernetesCluster("resourceGroupName", "kubernetesClusterName") .withCount(3L) .withMode(AgentPoolMode.SYSTEM) - .withVmSkuName("NC_XXXX") + .withVmSkuName("NC_P46_224_v1") .withTags(mapOf("key1", "fakeTokenPlaceholder", "key2", "fakeTokenPlaceholder")) .withExtendedLocation(new ExtendedLocation().withName( "/subscriptions/123e4567-e89b-12d3-a456-426655440000/resourceGroups/resourceGroupName/providers/Microsoft.ExtendedLocation/customLocations/clusterExtendedLocationName") @@ -66,7 +66,8 @@ public final class AgentPoolsCreateOrUpdateSamples { .withPluginType(KubernetesPluginType.MACVLAN)))) .withAvailabilityZones(Arrays.asList("1", "2", "3")) .withLabels(Arrays.asList(new KubernetesLabel().withKey("fakeTokenPlaceholder").withValue("true"))) - .withTaints(Arrays.asList(new KubernetesLabel().withKey("fakeTokenPlaceholder").withValue("true"))) + .withTaints( + Arrays.asList(new KubernetesLabel().withKey("fakeTokenPlaceholder").withValue("true:NoSchedule"))) .withUpgradeSettings(new AgentPoolUpgradeSettings().withMaxSurge("1")) .create(); } diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/AgentPoolsDeleteSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/AgentPoolsDeleteSamples.java index 8f1ff69168cd..1892d4587cb5 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/AgentPoolsDeleteSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/AgentPoolsDeleteSamples.java @@ -10,8 +10,8 @@ public final class AgentPoolsDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * AgentPools_Delete.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/AgentPools_Delete. + * json */ /** * Sample code: Delete Kubernetes cluster agent pool. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/AgentPoolsGetSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/AgentPoolsGetSamples.java index a113ec47351c..6ec656d8958e 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/AgentPoolsGetSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/AgentPoolsGetSamples.java @@ -10,8 +10,7 @@ public final class AgentPoolsGetSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * AgentPools_Get.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/AgentPools_Get.json */ /** * Sample code: Get Kubernetes cluster agent pool. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/AgentPoolsListByKubernetesClusterSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/AgentPoolsListByKubernetesClusterSamples.java index c2554256efce..631e20e1626a 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/AgentPoolsListByKubernetesClusterSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/AgentPoolsListByKubernetesClusterSamples.java @@ -10,7 +10,7 @@ public final class AgentPoolsListByKubernetesClusterSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * AgentPools_ListByKubernetesCluster.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/AgentPoolsUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/AgentPoolsUpdateSamples.java index b65d485bcab9..e4c64ae97700 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/AgentPoolsUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/AgentPoolsUpdateSamples.java @@ -18,8 +18,8 @@ public final class AgentPoolsUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * AgentPools_Patch.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/AgentPools_Patch. + * json */ /** * Sample code: Patch Kubernetes cluster agent pool. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachineKeySetsCreateOrUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachineKeySetsCreateOrUpdateSamples.java index 68b9cc0376db..1b1e86304b52 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachineKeySetsCreateOrUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachineKeySetsCreateOrUpdateSamples.java @@ -19,7 +19,7 @@ public final class BareMetalMachineKeySetsCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachineKeySets_Create.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachineKeySetsDeleteSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachineKeySetsDeleteSamples.java index 5a86ddec420b..f4a266e8f179 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachineKeySetsDeleteSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachineKeySetsDeleteSamples.java @@ -10,7 +10,7 @@ public final class BareMetalMachineKeySetsDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachineKeySets_Delete.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachineKeySetsGetSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachineKeySetsGetSamples.java index 1edf5a7e55fe..74066730744b 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachineKeySetsGetSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachineKeySetsGetSamples.java @@ -10,7 +10,7 @@ public final class BareMetalMachineKeySetsGetSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachineKeySets_Get.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachineKeySetsListByClusterSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachineKeySetsListByClusterSamples.java index b6367c325440..3e1f731230cc 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachineKeySetsListByClusterSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachineKeySetsListByClusterSamples.java @@ -10,7 +10,7 @@ public final class BareMetalMachineKeySetsListByClusterSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachineKeySets_ListByCluster.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachineKeySetsUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachineKeySetsUpdateSamples.java index f8fa89e851cf..9ecdb5d14f7e 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachineKeySetsUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachineKeySetsUpdateSamples.java @@ -18,7 +18,7 @@ public final class BareMetalMachineKeySetsUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachineKeySets_Patch.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesCordonSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesCordonSamples.java index a1fcc895a3ec..4e454cfbf469 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesCordonSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesCordonSamples.java @@ -13,7 +13,7 @@ public final class BareMetalMachinesCordonSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_Cordon.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesCreateOrUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesCreateOrUpdateSamples.java index edeeac9d0dbc..ef689b9b22df 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesCreateOrUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesCreateOrUpdateSamples.java @@ -15,7 +15,7 @@ public final class BareMetalMachinesCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_Create.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesDeleteSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesDeleteSamples.java index c6fd3ac1f352..914cfa212066 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesDeleteSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesDeleteSamples.java @@ -10,7 +10,7 @@ public final class BareMetalMachinesDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_Delete.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesGetByResourceGroupSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesGetByResourceGroupSamples.java index ff233106e80a..8263ce32128b 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesGetByResourceGroupSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesGetByResourceGroupSamples.java @@ -10,7 +10,7 @@ public final class BareMetalMachinesGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_Get.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesListByResourceGroupSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesListByResourceGroupSamples.java index b97ab16628f9..f56fe321bad2 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesListByResourceGroupSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesListByResourceGroupSamples.java @@ -10,7 +10,7 @@ public final class BareMetalMachinesListByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_ListByResourceGroup.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesListSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesListSamples.java index 7edf0fe075e1..33876739f2ae 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesListSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesListSamples.java @@ -10,7 +10,7 @@ public final class BareMetalMachinesListSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_ListBySubscription.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesPowerOffSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesPowerOffSamples.java index e6bbc4bb09b8..3f1c1c4ca4e1 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesPowerOffSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesPowerOffSamples.java @@ -13,7 +13,7 @@ public final class BareMetalMachinesPowerOffSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_PowerOff.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesReimageSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesReimageSamples.java index 933089a5faaa..1f24ed057725 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesReimageSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesReimageSamples.java @@ -10,7 +10,7 @@ public final class BareMetalMachinesReimageSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_Reimage.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesReplaceSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesReplaceSamples.java index ebc0593c507d..79ffe9ae0f8d 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesReplaceSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesReplaceSamples.java @@ -13,7 +13,7 @@ public final class BareMetalMachinesReplaceSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_Replace.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesRestartSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesRestartSamples.java index 282ea2c7281a..d547f5757846 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesRestartSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesRestartSamples.java @@ -10,7 +10,7 @@ public final class BareMetalMachinesRestartSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_Restart.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesRunCommandSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesRunCommandSamples.java index d60b648afabb..1f9d85216b61 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesRunCommandSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesRunCommandSamples.java @@ -13,7 +13,7 @@ public final class BareMetalMachinesRunCommandSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_RunCommand.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesRunDataExtractsSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesRunDataExtractsSamples.java index 61e7cfc23959..fcdb0f3eb3a9 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesRunDataExtractsSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesRunDataExtractsSamples.java @@ -14,7 +14,7 @@ public final class BareMetalMachinesRunDataExtractsSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_RunDataExtracts.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesRunReadCommandsSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesRunReadCommandsSamples.java index 74d7be2e4388..599d8166722d 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesRunReadCommandsSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesRunReadCommandsSamples.java @@ -14,7 +14,7 @@ public final class BareMetalMachinesRunReadCommandsSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_RunReadCommands.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesStartSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesStartSamples.java index 66464eef3b22..07e4c2b93888 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesStartSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesStartSamples.java @@ -10,7 +10,7 @@ public final class BareMetalMachinesStartSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_Start.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesUncordonSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesUncordonSamples.java index 21b73acd6003..e8ce0f868982 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesUncordonSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesUncordonSamples.java @@ -10,7 +10,7 @@ public final class BareMetalMachinesUncordonSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_Uncordon.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesUpdateSamples.java index b65d30473635..0103cc0fc9be 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BareMetalMachinesUpdateSamples.java @@ -14,7 +14,7 @@ public final class BareMetalMachinesUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BareMetalMachines_Patch.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BmcKeySetsCreateOrUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BmcKeySetsCreateOrUpdateSamples.java index 8a72e03493e8..2e819a9b44bf 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BmcKeySetsCreateOrUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BmcKeySetsCreateOrUpdateSamples.java @@ -19,8 +19,8 @@ public final class BmcKeySetsCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * BmcKeySets_Create.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/BmcKeySets_Create. + * json */ /** * Sample code: Create or update baseboard management controller key set of cluster. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BmcKeySetsDeleteSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BmcKeySetsDeleteSamples.java index dbc3b8a53c7f..6088b561c7fe 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BmcKeySetsDeleteSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BmcKeySetsDeleteSamples.java @@ -10,8 +10,8 @@ public final class BmcKeySetsDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * BmcKeySets_Delete.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/BmcKeySets_Delete. + * json */ /** * Sample code: Delete baseboard management controller key set of cluster. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BmcKeySetsGetSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BmcKeySetsGetSamples.java index 45927aef22e4..4e39dfa522f5 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BmcKeySetsGetSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BmcKeySetsGetSamples.java @@ -10,8 +10,7 @@ public final class BmcKeySetsGetSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * BmcKeySets_Get.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/BmcKeySets_Get.json */ /** * Sample code: Get baseboard management controller key set of cluster. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BmcKeySetsListByClusterSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BmcKeySetsListByClusterSamples.java index d6bdf5004e7b..4de690f9b3b0 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BmcKeySetsListByClusterSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BmcKeySetsListByClusterSamples.java @@ -10,7 +10,7 @@ public final class BmcKeySetsListByClusterSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * BmcKeySets_ListByCluster.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BmcKeySetsUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BmcKeySetsUpdateSamples.java index 255eacf817b5..942c5fc801c8 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BmcKeySetsUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/BmcKeySetsUpdateSamples.java @@ -18,8 +18,8 @@ public final class BmcKeySetsUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * BmcKeySets_Patch.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/BmcKeySets_Patch. + * json */ /** * Sample code: Patch baseboard management controller key set of cluster. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksCreateOrUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksCreateOrUpdateSamples.java index 2ca2214447c5..7ef9deee03d0 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksCreateOrUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksCreateOrUpdateSamples.java @@ -18,7 +18,7 @@ public final class CloudServicesNetworksCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * CloudServicesNetworks_Create.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksDeleteSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksDeleteSamples.java index 669f93845a1f..d6ac3e13e482 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksDeleteSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksDeleteSamples.java @@ -10,7 +10,7 @@ public final class CloudServicesNetworksDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * CloudServicesNetworks_Delete.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksGetByResourceGroupSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksGetByResourceGroupSamples.java index 787688c28d6a..bf23c2eea576 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksGetByResourceGroupSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksGetByResourceGroupSamples.java @@ -10,7 +10,7 @@ public final class CloudServicesNetworksGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * CloudServicesNetworks_Get.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksListByResourceGroupSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksListByResourceGroupSamples.java index 5c710067b787..3a5d3f0858c9 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksListByResourceGroupSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksListByResourceGroupSamples.java @@ -10,7 +10,7 @@ public final class CloudServicesNetworksListByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * CloudServicesNetworks_ListByResourceGroup.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksListSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksListSamples.java index ef37977b1f35..32370dba1a88 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksListSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksListSamples.java @@ -10,7 +10,7 @@ public final class CloudServicesNetworksListSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * CloudServicesNetworks_ListBySubscription.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksUpdateSamples.java index ef41b86173fe..ab04972b7444 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksUpdateSamples.java @@ -18,7 +18,7 @@ public final class CloudServicesNetworksUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * CloudServicesNetworks_Patch.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersCreateOrUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersCreateOrUpdateSamples.java index 8ad1bd3f19e7..c0bc190e8a2b 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersCreateOrUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersCreateOrUpdateSamples.java @@ -17,7 +17,7 @@ public final class ClusterManagersCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * ClusterManagers_Create.json */ /** @@ -44,7 +44,7 @@ public final class ClusterManagersCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * ClusterManagers_Create_Uami.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersDeleteSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersDeleteSamples.java index 6c5264c484ef..9839b9617a9e 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersDeleteSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersDeleteSamples.java @@ -10,7 +10,7 @@ public final class ClusterManagersDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * ClusterManagers_Delete.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersGetByResourceGroupSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersGetByResourceGroupSamples.java index f478983d8684..fee945b6cc14 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersGetByResourceGroupSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersGetByResourceGroupSamples.java @@ -10,8 +10,8 @@ public final class ClusterManagersGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * ClusterManagers_Get.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ClusterManagers_Get + * .json */ /** * Sample code: Get cluster manager. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersListByResourceGroupSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersListByResourceGroupSamples.java index 4874bfb52e49..baff0e299121 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersListByResourceGroupSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersListByResourceGroupSamples.java @@ -10,7 +10,7 @@ public final class ClusterManagersListByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * ClusterManagers_ListByResourceGroup.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersListSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersListSamples.java index 4d2feeedfe45..98af40537608 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersListSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersListSamples.java @@ -10,7 +10,7 @@ public final class ClusterManagersListSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * ClusterManagers_ListBySubscription.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersUpdateSamples.java index bbea735ccf75..0469ade45ed8 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersUpdateSamples.java @@ -17,7 +17,7 @@ public final class ClusterManagersUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * ClusterManagers_Patch.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersContinueUpdateVersionSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersContinueUpdateVersionSamples.java index 7d7288e1ba39..4e4e9b6a6652 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersContinueUpdateVersionSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersContinueUpdateVersionSamples.java @@ -13,7 +13,7 @@ public final class ClustersContinueUpdateVersionSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Clusters_ContinueUpdateVersion.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersCreateOrUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersCreateOrUpdateSamples.java index f48517d11fa6..a61c2b417575 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersCreateOrUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersCreateOrUpdateSamples.java @@ -37,8 +37,8 @@ public final class ClustersCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Clusters_Create.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Clusters_Create. + * json */ /** * Sample code: Create or update cluster. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersDeleteSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersDeleteSamples.java index 1dad5dce9094..31e601bfd441 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersDeleteSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersDeleteSamples.java @@ -10,8 +10,8 @@ public final class ClustersDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Clusters_Delete.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Clusters_Delete. + * json */ /** * Sample code: Delete cluster. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersDeploySamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersDeploySamples.java index 6ba036921bb5..2a193d6e5cd5 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersDeploySamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersDeploySamples.java @@ -13,8 +13,8 @@ public final class ClustersDeploySamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Clusters_Deploy.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Clusters_Deploy. + * json */ /** * Sample code: Deploy cluster. @@ -29,7 +29,7 @@ public static void deployCluster(com.azure.resourcemanager.networkcloud.NetworkC /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Clusters_Deploy_SkipValidation.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersGetByResourceGroupSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersGetByResourceGroupSamples.java index b1eaa5e8eb47..850d05ab553a 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersGetByResourceGroupSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersGetByResourceGroupSamples.java @@ -10,8 +10,7 @@ public final class ClustersGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Clusters_Get.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Clusters_Get.json */ /** * Sample code: Get cluster. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersListByResourceGroupSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersListByResourceGroupSamples.java index aaeffd6f2057..86bb6d4e3e0d 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersListByResourceGroupSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersListByResourceGroupSamples.java @@ -10,7 +10,7 @@ public final class ClustersListByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Clusters_ListByResourceGroup.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersListSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersListSamples.java index 3fb9f4db1a5d..be653f498537 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersListSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersListSamples.java @@ -10,7 +10,7 @@ public final class ClustersListSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Clusters_ListBySubscription.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersScanRuntimeSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersScanRuntimeSamples.java index c330c8c90a91..f28350ee4a8b 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersScanRuntimeSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersScanRuntimeSamples.java @@ -13,7 +13,7 @@ public final class ClustersScanRuntimeSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Clusters_ScanRuntime.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersUpdateSamples.java index b2f9738584b7..0d30a181d628 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersUpdateSamples.java @@ -34,7 +34,7 @@ public final class ClustersUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Clusters_Patch_UpdateStrategy.json */ /** @@ -58,7 +58,7 @@ public static void patchUpdateStrategy(com.azure.resourcemanager.networkcloud.Ne /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Clusters_Patch_Location.json */ /** @@ -78,7 +78,7 @@ public static void patchClusterLocation(com.azure.resourcemanager.networkcloud.N /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Clusters_Patch_AggregatorOrSingleRackDefinition.json */ /** @@ -137,7 +137,7 @@ public static void patchClusterAggregatorOrSingleRackDefinition( /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Clusters_Patch_CommandOutput.json */ /** @@ -167,7 +167,7 @@ public static void patchClusterCommandOutput(com.azure.resourcemanager.networkcl /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Clusters_Patch_RuntimeProtectionConfiguration.json */ /** @@ -189,7 +189,7 @@ public static void patchClusterCommandOutput(com.azure.resourcemanager.networkcl /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Clusters_Patch_SecretArchive.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersUpdateVersionSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersUpdateVersionSamples.java index a7458b185b73..7cc6928bdbfc 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersUpdateVersionSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ClustersUpdateVersionSamples.java @@ -12,7 +12,7 @@ public final class ClustersUpdateVersionSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Clusters_UpdateVersion.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ConsolesCreateOrUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ConsolesCreateOrUpdateSamples.java index 59a4a7a892af..13b6c7660159 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ConsolesCreateOrUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ConsolesCreateOrUpdateSamples.java @@ -17,8 +17,8 @@ public final class ConsolesCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Consoles_Create.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Consoles_Create. + * json */ /** * Sample code: Create or update virtual machine console. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ConsolesDeleteSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ConsolesDeleteSamples.java index 293fd27334e3..dd6f06cec884 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ConsolesDeleteSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ConsolesDeleteSamples.java @@ -10,8 +10,8 @@ public final class ConsolesDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Consoles_Delete.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Consoles_Delete. + * json */ /** * Sample code: Delete virtual machine console. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ConsolesGetSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ConsolesGetSamples.java index ecc8924b4a1b..55cdbe60591c 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ConsolesGetSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ConsolesGetSamples.java @@ -10,8 +10,7 @@ public final class ConsolesGetSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Consoles_Get.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Consoles_Get.json */ /** * Sample code: Get virtual machine console. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ConsolesListByVirtualMachineSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ConsolesListByVirtualMachineSamples.java index bb379943671d..31a6e6270334 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ConsolesListByVirtualMachineSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ConsolesListByVirtualMachineSamples.java @@ -10,7 +10,7 @@ public final class ConsolesListByVirtualMachineSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Consoles_ListByVirtualMachine.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ConsolesUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ConsolesUpdateSamples.java index b0236f90fc2a..b5a45e65c73f 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ConsolesUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/ConsolesUpdateSamples.java @@ -17,8 +17,7 @@ public final class ConsolesUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Consoles_Patch.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Consoles_Patch.json */ /** * Sample code: Patch virtual machine console. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClusterFeaturesCreateOrUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClusterFeaturesCreateOrUpdateSamples.java index 193c6eaf2485..35271f333549 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClusterFeaturesCreateOrUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClusterFeaturesCreateOrUpdateSamples.java @@ -15,7 +15,7 @@ public final class KubernetesClusterFeaturesCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * KubernetesClusterFeatures_Create.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClusterFeaturesDeleteSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClusterFeaturesDeleteSamples.java index bee647bebc48..ed70fdcdc92a 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClusterFeaturesDeleteSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClusterFeaturesDeleteSamples.java @@ -10,7 +10,7 @@ public final class KubernetesClusterFeaturesDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * KubernetesClusterFeatures_Delete.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClusterFeaturesGetSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClusterFeaturesGetSamples.java index 3c4da68720bf..ff0dff16833a 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClusterFeaturesGetSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClusterFeaturesGetSamples.java @@ -10,7 +10,7 @@ public final class KubernetesClusterFeaturesGetSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * KubernetesClusterFeatures_Get.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClusterFeaturesListByKubernetesClusterSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClusterFeaturesListByKubernetesClusterSamples.java index d9c00d961718..88398a5febcd 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClusterFeaturesListByKubernetesClusterSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClusterFeaturesListByKubernetesClusterSamples.java @@ -10,7 +10,7 @@ public final class KubernetesClusterFeaturesListByKubernetesClusterSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * KubernetesClusterFeatures_ListByKubernetesCluster.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClusterFeaturesUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClusterFeaturesUpdateSamples.java index ff5169500d1c..a75dd6e7780e 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClusterFeaturesUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClusterFeaturesUpdateSamples.java @@ -16,7 +16,7 @@ public final class KubernetesClusterFeaturesUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * KubernetesClusterFeatures_Patch.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClustersCreateOrUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClustersCreateOrUpdateSamples.java index 720fb0197825..f9c43ef20414 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClustersCreateOrUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClustersCreateOrUpdateSamples.java @@ -42,7 +42,7 @@ public final class KubernetesClustersCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * KubernetesClusters_Create.json */ /** @@ -64,7 +64,7 @@ public final class KubernetesClustersCreateOrUpdateSamples { .withSshPublicKeys(Arrays.asList(new SshPublicKey().withKeyData("fakeTokenPlaceholder")))) .withAvailabilityZones(Arrays.asList("1", "2", "3")) .withCount(3L) - .withVmSkuName("NC_XXXX")) + .withVmSkuName("NC_G6_28_v1")) .withInitialAgentPoolConfigurations(Arrays.asList(new InitialAgentPoolConfiguration() .withAdministratorConfiguration(new AdministratorConfiguration().withAdminUsername("azure") .withSshPublicKeys(Arrays.asList(new SshPublicKey().withKeyData("fakeTokenPlaceholder")))) @@ -86,9 +86,10 @@ public final class KubernetesClustersCreateOrUpdateSamples { .withLabels(Arrays.asList(new KubernetesLabel().withKey("fakeTokenPlaceholder").withValue("true"))) .withMode(AgentPoolMode.SYSTEM) .withName("SystemPool-1") - .withTaints(Arrays.asList(new KubernetesLabel().withKey("fakeTokenPlaceholder").withValue("true"))) + .withTaints( + Arrays.asList(new KubernetesLabel().withKey("fakeTokenPlaceholder").withValue("true:NoSchedule"))) .withUpgradeSettings(new AgentPoolUpgradeSettings().withMaxSurge("1")) - .withVmSkuName("NC_XXXX"))) + .withVmSkuName("NC_P46_224_v1"))) .withKubernetesVersion("1.XX.Y") .withNetworkConfiguration(new NetworkConfiguration() .withAttachedNetworkConfiguration(new AttachedNetworkConfiguration() @@ -143,7 +144,7 @@ public final class KubernetesClustersCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * KubernetesClusters_L2LoadBalancer_Create.json */ /** @@ -165,7 +166,7 @@ public static void createOrUpdateKubernetesClusterWithALayer2LoadBalancer( .withSshPublicKeys(Arrays.asList(new SshPublicKey().withKeyData("fakeTokenPlaceholder")))) .withAvailabilityZones(Arrays.asList("1", "2", "3")) .withCount(3L) - .withVmSkuName("NC_XXXX")) + .withVmSkuName("NC_G6_28_v1")) .withInitialAgentPoolConfigurations(Arrays.asList(new InitialAgentPoolConfiguration() .withAdministratorConfiguration(new AdministratorConfiguration().withAdminUsername("azure") .withSshPublicKeys(Arrays.asList(new SshPublicKey().withKeyData("fakeTokenPlaceholder")))) @@ -187,9 +188,10 @@ public static void createOrUpdateKubernetesClusterWithALayer2LoadBalancer( .withLabels(Arrays.asList(new KubernetesLabel().withKey("fakeTokenPlaceholder").withValue("true"))) .withMode(AgentPoolMode.SYSTEM) .withName("SystemPool-1") - .withTaints(Arrays.asList(new KubernetesLabel().withKey("fakeTokenPlaceholder").withValue("true"))) + .withTaints( + Arrays.asList(new KubernetesLabel().withKey("fakeTokenPlaceholder").withValue("true:NoSchedule"))) .withUpgradeSettings(new AgentPoolUpgradeSettings().withMaxSurge("1")) - .withVmSkuName("NC_XXXX"))) + .withVmSkuName("NC_P46_224_v1"))) .withKubernetesVersion("1.XX.Y") .withNetworkConfiguration(new NetworkConfiguration() .withAttachedNetworkConfiguration(new AttachedNetworkConfiguration() diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClustersDeleteSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClustersDeleteSamples.java index 2c77946d04b6..3dc7b1198e17 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClustersDeleteSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClustersDeleteSamples.java @@ -10,7 +10,7 @@ public final class KubernetesClustersDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * KubernetesClusters_Delete.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClustersGetByResourceGroupSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClustersGetByResourceGroupSamples.java index 59e2bc517896..5041cab818da 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClustersGetByResourceGroupSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClustersGetByResourceGroupSamples.java @@ -10,7 +10,7 @@ public final class KubernetesClustersGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * KubernetesClusters_Get.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClustersListByResourceGroupSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClustersListByResourceGroupSamples.java index 3b5fced0f5d9..9bd54c0f63a9 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClustersListByResourceGroupSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClustersListByResourceGroupSamples.java @@ -10,7 +10,7 @@ public final class KubernetesClustersListByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * KubernetesClusters_ListByResourceGroup.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClustersListSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClustersListSamples.java index b79ba2a10c73..cdc814566ead 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClustersListSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClustersListSamples.java @@ -10,7 +10,7 @@ public final class KubernetesClustersListSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * KubernetesClusters_ListBySubscription.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClustersRestartNodeSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClustersRestartNodeSamples.java index 228ee4b52395..e27694881b8f 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClustersRestartNodeSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClustersRestartNodeSamples.java @@ -12,7 +12,7 @@ public final class KubernetesClustersRestartNodeSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * KubernetesClusters_RestartNode.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClustersUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClustersUpdateSamples.java index cbbff2ab4e64..a963b80a56c5 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClustersUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/KubernetesClustersUpdateSamples.java @@ -18,7 +18,7 @@ public final class KubernetesClustersUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * KubernetesClusters_Patch.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksCreateOrUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksCreateOrUpdateSamples.java index 73904034051a..e7568770013c 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksCreateOrUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksCreateOrUpdateSamples.java @@ -15,8 +15,8 @@ public final class L2NetworksCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * L2Networks_Create.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/L2Networks_Create. + * json */ /** * Sample code: Create or update L2 network. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksDeleteSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksDeleteSamples.java index 16573f649bd9..fe3194523ad0 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksDeleteSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksDeleteSamples.java @@ -10,8 +10,8 @@ public final class L2NetworksDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * L2Networks_Delete.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/L2Networks_Delete. + * json */ /** * Sample code: Delete L2 network. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksGetByResourceGroupSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksGetByResourceGroupSamples.java index 2224dc3f679e..02c6d8aeb308 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksGetByResourceGroupSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksGetByResourceGroupSamples.java @@ -10,8 +10,7 @@ public final class L2NetworksGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * L2Networks_Get.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/L2Networks_Get.json */ /** * Sample code: Get L2 network. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksListByResourceGroupSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksListByResourceGroupSamples.java index b56af27dba6f..26cdea6deac6 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksListByResourceGroupSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksListByResourceGroupSamples.java @@ -10,7 +10,7 @@ public final class L2NetworksListByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * L2Networks_ListByResourceGroup.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksListSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksListSamples.java index d02f88c57eba..fec1814afc2f 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksListSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksListSamples.java @@ -10,7 +10,7 @@ public final class L2NetworksListSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * L2Networks_ListBySubscription.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksUpdateSamples.java index 57b8da64b21d..6443d82fd3fb 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksUpdateSamples.java @@ -14,8 +14,8 @@ public final class L2NetworksUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * L2Networks_Patch.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/L2Networks_Patch. + * json */ /** * Sample code: Patch L2 network. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksCreateOrUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksCreateOrUpdateSamples.java index b8f4f65b76eb..3e57e0971a77 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksCreateOrUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksCreateOrUpdateSamples.java @@ -15,8 +15,8 @@ public final class L3NetworksCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * L3Networks_Create.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/L3Networks_Create. + * json */ /** * Sample code: Create or update L3 network. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksDeleteSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksDeleteSamples.java index e4aab59817a4..92f24f18dd1b 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksDeleteSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksDeleteSamples.java @@ -10,8 +10,8 @@ public final class L3NetworksDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * L3Networks_Delete.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/L3Networks_Delete. + * json */ /** * Sample code: Delete L3 network. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksGetByResourceGroupSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksGetByResourceGroupSamples.java index e61acb9f18a1..badb8d3a6163 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksGetByResourceGroupSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksGetByResourceGroupSamples.java @@ -10,8 +10,7 @@ public final class L3NetworksGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * L3Networks_Get.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/L3Networks_Get.json */ /** * Sample code: Get L3network. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksListByResourceGroupSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksListByResourceGroupSamples.java index e9eaa95794f4..1f2f8966a1ef 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksListByResourceGroupSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksListByResourceGroupSamples.java @@ -10,7 +10,7 @@ public final class L3NetworksListByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * L3Networks_ListByResourceGroup.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksListSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksListSamples.java index 4f024a189fbc..2182df6b0726 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksListSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksListSamples.java @@ -10,7 +10,7 @@ public final class L3NetworksListSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * L3Networks_ListBySubscription.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksUpdateSamples.java index 27628db4ae28..8bacd4c52aa3 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksUpdateSamples.java @@ -14,8 +14,8 @@ public final class L3NetworksUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * L3Networks_Patch.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/L3Networks_Patch. + * json */ /** * Sample code: Patch L3 network. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsCreateOrUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsCreateOrUpdateSamples.java index 67a1a4c1a64f..8940d3ecfcfb 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsCreateOrUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsCreateOrUpdateSamples.java @@ -15,7 +15,7 @@ public final class MetricsConfigurationsCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * ClusterMetricsConfigurations_Create.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsDeleteSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsDeleteSamples.java index c0899ad042a5..02cf25aa8a3c 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsDeleteSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsDeleteSamples.java @@ -10,7 +10,7 @@ public final class MetricsConfigurationsDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * ClusterMetricsConfigurations_Delete.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsGetSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsGetSamples.java index 21199c14e02b..ceb5d13bd907 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsGetSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsGetSamples.java @@ -10,7 +10,7 @@ public final class MetricsConfigurationsGetSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * ClusterMetricsConfigurations_Get.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsListByClusterSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsListByClusterSamples.java index 87395b110671..9e4335e79467 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsListByClusterSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsListByClusterSamples.java @@ -10,7 +10,7 @@ public final class MetricsConfigurationsListByClusterSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * ClusterMetricsConfigurations_ListByCluster.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsUpdateSamples.java index e78dc095f226..efbb0253221f 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsUpdateSamples.java @@ -15,7 +15,7 @@ public final class MetricsConfigurationsUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * ClusterMetricsConfigurations_Patch.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/OperationsListSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/OperationsListSamples.java index eae38b4d6bba..c66e56d84faf 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/OperationsListSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/OperationsListSamples.java @@ -10,8 +10,8 @@ public final class OperationsListSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Operations_List.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Operations_List. + * json */ /** * Sample code: List resource provider operations. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RackSkusGetSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RackSkusGetSamples.java index 0916178b5e2c..7c0b49fc00db 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RackSkusGetSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RackSkusGetSamples.java @@ -10,8 +10,7 @@ public final class RackSkusGetSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * RackSkus_Get.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/RackSkus_Get.json */ /** * Sample code: Get rack SKU resource. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RackSkusListSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RackSkusListSamples.java index f9e02040cdba..5104a2c90490 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RackSkusListSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RackSkusListSamples.java @@ -10,7 +10,7 @@ public final class RackSkusListSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * RackSkus_ListBySubscription.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RacksCreateOrUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RacksCreateOrUpdateSamples.java index fd2e334ed294..24c213384f5e 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RacksCreateOrUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RacksCreateOrUpdateSamples.java @@ -14,8 +14,7 @@ public final class RacksCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Racks_Create.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Racks_Create.json */ /** * Sample code: Create or update rack. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RacksDeleteSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RacksDeleteSamples.java index 96b0ad12399f..a6d8bec0187e 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RacksDeleteSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RacksDeleteSamples.java @@ -10,8 +10,7 @@ public final class RacksDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Racks_Delete.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Racks_Delete.json */ /** * Sample code: Delete rack. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RacksGetByResourceGroupSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RacksGetByResourceGroupSamples.java index c097254f575e..6ac5ef5918de 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RacksGetByResourceGroupSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RacksGetByResourceGroupSamples.java @@ -10,8 +10,7 @@ public final class RacksGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/Racks_Get. - * json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Racks_Get.json */ /** * Sample code: Get rack. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RacksListByResourceGroupSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RacksListByResourceGroupSamples.java index f742f0c192aa..9ec926a84b98 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RacksListByResourceGroupSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RacksListByResourceGroupSamples.java @@ -10,7 +10,7 @@ public final class RacksListByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Racks_ListByResourceGroup.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RacksListSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RacksListSamples.java index 795971b53871..5307ff824438 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RacksListSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RacksListSamples.java @@ -10,7 +10,7 @@ public final class RacksListSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Racks_ListBySubscription.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RacksUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RacksUpdateSamples.java index 2c001b2309b9..0e79f4224476 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RacksUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/RacksUpdateSamples.java @@ -14,8 +14,7 @@ public final class RacksUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Racks_Patch.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Racks_Patch.json */ /** * Sample code: Patch rack. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesCreateOrUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesCreateOrUpdateSamples.java index 081fbf8b0f91..6415b5b0c073 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesCreateOrUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesCreateOrUpdateSamples.java @@ -15,7 +15,7 @@ public final class StorageAppliancesCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * StorageAppliances_Create.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesDeleteSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesDeleteSamples.java index 168a8db0ddc6..82ae7d7e1bba 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesDeleteSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesDeleteSamples.java @@ -10,7 +10,7 @@ public final class StorageAppliancesDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * StorageAppliances_Delete.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesDisableRemoteVendorManagementSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesDisableRemoteVendorManagementSamples.java index 39bee69ce5c2..9d4fb7a2a38d 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesDisableRemoteVendorManagementSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesDisableRemoteVendorManagementSamples.java @@ -10,7 +10,7 @@ public final class StorageAppliancesDisableRemoteVendorManagementSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * StorageAppliances_DisableRemoteVendorManagement.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesEnableRemoteVendorManagementSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesEnableRemoteVendorManagementSamples.java index 418415f742c5..102d79e82bfe 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesEnableRemoteVendorManagementSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesEnableRemoteVendorManagementSamples.java @@ -13,7 +13,7 @@ public final class StorageAppliancesEnableRemoteVendorManagementSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * StorageAppliances_EnableRemoteVendorManagement.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesGetByResourceGroupSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesGetByResourceGroupSamples.java index 8c38f9ffd861..c2646fcfce4a 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesGetByResourceGroupSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesGetByResourceGroupSamples.java @@ -10,7 +10,7 @@ public final class StorageAppliancesGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * StorageAppliances_Get.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesListByResourceGroupSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesListByResourceGroupSamples.java index 2401178370aa..33de046058dd 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesListByResourceGroupSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesListByResourceGroupSamples.java @@ -10,7 +10,7 @@ public final class StorageAppliancesListByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * StorageAppliances_ListByResourceGroup.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesListSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesListSamples.java index 0b9b8393bac2..22207b4741e8 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesListSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesListSamples.java @@ -10,7 +10,7 @@ public final class StorageAppliancesListSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * StorageAppliances_ListBySubscription.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesUpdateSamples.java index 95aa0ea89cdf..87ab7461124d 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/StorageAppliancesUpdateSamples.java @@ -14,7 +14,7 @@ public final class StorageAppliancesUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * StorageAppliances_Patch.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksCreateOrUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksCreateOrUpdateSamples.java index 4360a730e94e..0e1397b80a0d 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksCreateOrUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksCreateOrUpdateSamples.java @@ -15,7 +15,7 @@ public final class TrunkedNetworksCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * TrunkedNetworks_Create.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksDeleteSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksDeleteSamples.java index 69eb97a5f628..abe3c622388d 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksDeleteSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksDeleteSamples.java @@ -10,7 +10,7 @@ public final class TrunkedNetworksDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * TrunkedNetworks_Delete.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksGetByResourceGroupSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksGetByResourceGroupSamples.java index e036c1c36407..aada59962e03 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksGetByResourceGroupSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksGetByResourceGroupSamples.java @@ -10,8 +10,8 @@ public final class TrunkedNetworksGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * TrunkedNetworks_Get.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/TrunkedNetworks_Get + * .json */ /** * Sample code: Get Trunked network. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksListByResourceGroupSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksListByResourceGroupSamples.java index 146e73ae89a5..c5f52e0002f1 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksListByResourceGroupSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksListByResourceGroupSamples.java @@ -10,7 +10,7 @@ public final class TrunkedNetworksListByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * TrunkedNetworks_ListByResourceGroup.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksListSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksListSamples.java index 182087096e61..98d311fe09fa 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksListSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksListSamples.java @@ -10,7 +10,7 @@ public final class TrunkedNetworksListSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * TrunkedNetworks_ListBySubscription.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksUpdateSamples.java index 6e1385f6ace8..1714af654aa7 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksUpdateSamples.java @@ -14,7 +14,7 @@ public final class TrunkedNetworksUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * TrunkedNetworks_Patch.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesCreateOrUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesCreateOrUpdateSamples.java index cf54a362006c..ae85f6ce35ee 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesCreateOrUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesCreateOrUpdateSamples.java @@ -30,7 +30,7 @@ public final class VirtualMachinesCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * VirtualMachines_Create.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesDeleteSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesDeleteSamples.java index 0aae3c8b47e0..4a3421fc87c7 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesDeleteSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesDeleteSamples.java @@ -10,7 +10,7 @@ public final class VirtualMachinesDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * VirtualMachines_Delete.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesGetByResourceGroupSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesGetByResourceGroupSamples.java index 159c8540c67c..4bdfcc6f1192 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesGetByResourceGroupSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesGetByResourceGroupSamples.java @@ -10,8 +10,8 @@ public final class VirtualMachinesGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * VirtualMachines_Get.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/VirtualMachines_Get + * .json */ /** * Sample code: Get virtual machine. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesListByResourceGroupSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesListByResourceGroupSamples.java index d187bc0863d6..d2f82a8e4cd4 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesListByResourceGroupSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesListByResourceGroupSamples.java @@ -10,7 +10,7 @@ public final class VirtualMachinesListByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * VirtualMachines_ListByResourceGroup.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesListSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesListSamples.java index 73a16d3c8912..0dd970c382ae 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesListSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesListSamples.java @@ -10,7 +10,7 @@ public final class VirtualMachinesListSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * VirtualMachines_ListBySubscription.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesPowerOffSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesPowerOffSamples.java index bbcd17e091f6..2f7d5a757e4b 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesPowerOffSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesPowerOffSamples.java @@ -13,7 +13,7 @@ public final class VirtualMachinesPowerOffSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * VirtualMachines_PowerOff.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesReimageSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesReimageSamples.java index 0a8b25bd617c..cc1ef968401c 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesReimageSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesReimageSamples.java @@ -10,7 +10,7 @@ public final class VirtualMachinesReimageSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * VirtualMachines_Reimage.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesRestartSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesRestartSamples.java index db6ac8bc160b..338ad993cdf6 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesRestartSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesRestartSamples.java @@ -10,7 +10,7 @@ public final class VirtualMachinesRestartSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * VirtualMachines_Restart.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesStartSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesStartSamples.java index 268776aeb17d..2aad6457ed35 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesStartSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesStartSamples.java @@ -10,7 +10,7 @@ public final class VirtualMachinesStartSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * VirtualMachines_Start.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesUpdateSamples.java index db65c5d5fff8..c9c07b902699 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VirtualMachinesUpdateSamples.java @@ -15,7 +15,7 @@ public final class VirtualMachinesUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * VirtualMachines_Patch.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VolumesCreateOrUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VolumesCreateOrUpdateSamples.java index bddeb308cf9f..44c78cdd8355 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VolumesCreateOrUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VolumesCreateOrUpdateSamples.java @@ -14,8 +14,7 @@ public final class VolumesCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Volumes_Create.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Volumes_Create.json */ /** * Sample code: Create or update volume. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VolumesDeleteSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VolumesDeleteSamples.java index 842b4722af6e..19ae0e1cf0cb 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VolumesDeleteSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VolumesDeleteSamples.java @@ -10,8 +10,7 @@ public final class VolumesDeleteSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Volumes_Delete.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Volumes_Delete.json */ /** * Sample code: Delete volume. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VolumesGetByResourceGroupSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VolumesGetByResourceGroupSamples.java index 1df6dcc05d3b..f462519d3563 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VolumesGetByResourceGroupSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VolumesGetByResourceGroupSamples.java @@ -10,8 +10,7 @@ public final class VolumesGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Volumes_Get.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Volumes_Get.json */ /** * Sample code: Get volume. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VolumesListByResourceGroupSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VolumesListByResourceGroupSamples.java index 5b40a4e2557c..55a4b06188ab 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VolumesListByResourceGroupSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VolumesListByResourceGroupSamples.java @@ -10,7 +10,7 @@ public final class VolumesListByResourceGroupSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Volumes_ListByResourceGroup.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VolumesListSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VolumesListSamples.java index 194694ba2f01..38e7025b740a 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VolumesListSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VolumesListSamples.java @@ -10,7 +10,7 @@ public final class VolumesListSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/ * Volumes_ListBySubscription.json */ /** diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VolumesUpdateSamples.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VolumesUpdateSamples.java index 835670f35f31..10e228a56e2a 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VolumesUpdateSamples.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/samples/java/com/azure/resourcemanager/networkcloud/generated/VolumesUpdateSamples.java @@ -14,8 +14,7 @@ public final class VolumesUpdateSamples { /* * x-ms-original-file: - * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/preview/2024-06-01-preview/examples/ - * Volumes_Patch.json + * specification/networkcloud/resource-manager/Microsoft.NetworkCloud/stable/2024-07-01/examples/Volumes_Patch.json */ /** * Sample code: Patch volume. diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksCreateOrUpdateMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksCreateOrUpdateMockTests.java index 2a56cc218564..625fb2dd9150 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksCreateOrUpdateMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksCreateOrUpdateMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.CloudServicesNetwork; @@ -35,7 +35,7 @@ public void testCreateOrUpdate() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); CloudServicesNetwork response = manager.cloudServicesNetworks() .define("mclujyxkyxlzgs") diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksGetByResourceGroupWithResponseMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksGetByResourceGroupWithResponseMockTests.java index 310a37905696..f17b167446b6 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksGetByResourceGroupWithResponseMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksGetByResourceGroupWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.CloudServicesNetwork; @@ -29,7 +29,7 @@ public void testGetByResourceGroupWithResponse() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); CloudServicesNetwork response = manager.cloudServicesNetworks() .getByResourceGroupWithResponse("qxfx", "elgcmpzqjhhhqx", com.azure.core.util.Context.NONE) diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksListByResourceGroupMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksListByResourceGroupMockTests.java index 84f2539fc355..264d5c94ef4a 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksListByResourceGroupMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksListByResourceGroupMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.CloudServicesNetwork; @@ -30,7 +30,7 @@ public void testListByResourceGroup() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.cloudServicesNetworks().listByResourceGroup("akpoldtvevbo", com.azure.core.util.Context.NONE); diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksListMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksListMockTests.java index 09667526eb9f..32c179816386 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksListMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/CloudServicesNetworksListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.CloudServicesNetwork; @@ -30,7 +30,7 @@ public void testList() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.cloudServicesNetworks().list(com.azure.core.util.Context.NONE); diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagerInnerTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagerInnerTests.java index 7c974428c151..009391ef65d1 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagerInnerTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagerInnerTests.java @@ -19,7 +19,7 @@ public final class ClusterManagerInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ClusterManagerInner model = BinaryData.fromString( - "{\"identity\":{\"principalId\":\"6a219ae8-bf79-4c1d-ad7c-710d9c4e4572\",\"tenantId\":\"9394c260-5644-4f16-b350-200dccfdf47e\",\"type\":\"SystemAssigned\",\"userAssignedIdentities\":{\"ndslgnayqigynduh\":{\"principalId\":\"067013cc-6ca8-413b-a8e9-6669afb17f10\",\"clientId\":\"0e2d10a9-5d5a-431c-8327-890f1e2547cd\"},\"qlkth\":{\"principalId\":\"5c5d5f50-fa35-488d-bb1c-c262471d1d76\",\"clientId\":\"5ced5514-81e1-4ce7-8f48-ad7e3e4871d1\"},\"qolbgyc\":{\"principalId\":\"473245fd-e236-4482-9a2a-6c557d13d760\",\"clientId\":\"f42102df-3377-4e68-a42a-992ff3574173\"}}},\"properties\":{\"analyticsWorkspaceId\":\"iertgccymvaolp\",\"availabilityZones\":[\"qlfmmdnbb\",\"lzpswiydm\"],\"clusterVersions\":[{\"supportExpiryDate\":\"zdxss\",\"targetClusterVersion\":\"bzmnvdfznud\"}],\"detailedStatus\":\"Error\",\"detailedStatusMessage\":\"xzb\",\"fabricControllerId\":\"cblylpstdbhhxsr\",\"managedResourceGroupConfiguration\":{\"location\":\"ucerscdntnevfi\",\"name\":\"mygtdssls\"},\"managerExtendedLocation\":{\"name\":\"mweriofzpy\",\"type\":\"semwabnet\"},\"provisioningState\":\"Failed\",\"vmSize\":\"zhedplvwiw\"},\"location\":\"mwmbes\",\"tags\":{\"wtppjflcxogaoko\":\"k\"},\"id\":\"z\",\"name\":\"nsikvmkqzeqqkdl\",\"type\":\"fzxmhhvhgureodkw\"}") + "{\"identity\":{\"principalId\":\"0cfa93d8-5315-4ae1-8267-d34d02c92066\",\"tenantId\":\"efec5ce4-971d-44d0-8b76-659db9a2bb65\",\"type\":\"SystemAssigned\",\"userAssignedIdentities\":{\"ndslgnayqigynduh\":{\"principalId\":\"4daf14d7-a9d3-4bcc-865b-c1dc40da6c36\",\"clientId\":\"eb28694c-3d9c-4e0d-96b5-8b1c44149622\"},\"qlkth\":{\"principalId\":\"88fcbbce-bcd3-45a1-b637-637413ec6eef\",\"clientId\":\"004f8698-37cb-4ca9-81d1-3baa23ff0c9b\"},\"qolbgyc\":{\"principalId\":\"955de4f8-f0ef-4159-a306-a11367a2a7b8\",\"clientId\":\"771e1761-d831-4f00-9480-8f6728773db3\"}}},\"properties\":{\"analyticsWorkspaceId\":\"iertgccymvaolp\",\"availabilityZones\":[\"qlfmmdnbb\",\"lzpswiydm\"],\"clusterVersions\":[{\"supportExpiryDate\":\"zdxss\",\"targetClusterVersion\":\"bzmnvdfznud\"}],\"detailedStatus\":\"Error\",\"detailedStatusMessage\":\"xzb\",\"fabricControllerId\":\"cblylpstdbhhxsr\",\"managedResourceGroupConfiguration\":{\"location\":\"ucerscdntnevfi\",\"name\":\"mygtdssls\"},\"managerExtendedLocation\":{\"name\":\"mweriofzpy\",\"type\":\"semwabnet\"},\"provisioningState\":\"Failed\",\"vmSize\":\"zhedplvwiw\"},\"location\":\"mwmbes\",\"tags\":{\"wtppjflcxogaoko\":\"k\"},\"id\":\"z\",\"name\":\"nsikvmkqzeqqkdl\",\"type\":\"fzxmhhvhgureodkw\"}") .toObject(ClusterManagerInner.class); Assertions.assertEquals("mwmbes", model.location()); Assertions.assertEquals("k", model.tags().get("wtppjflcxogaoko")); diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagerListTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagerListTests.java index 1f5bd05a1a60..af1c6f70ce3a 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagerListTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagerListTests.java @@ -20,7 +20,7 @@ public final class ClusterManagerListTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ClusterManagerList model = BinaryData.fromString( - "{\"nextLink\":\"ali\",\"value\":[{\"identity\":{\"principalId\":\"49a09063-aa36-479d-9551-00187b1b7428\",\"tenantId\":\"758d0c53-3250-4f27-9968-90f643842156\",\"type\":\"UserAssigned\",\"userAssignedIdentities\":{\"shsfwxosowzxcu\":{\"principalId\":\"38774de8-4b88-4148-9feb-4b6b8b7b9229\",\"clientId\":\"d45b640d-e10c-4488-b5c4-15edd9d6958c\"},\"jooxdjebw\":{\"principalId\":\"548464c7-fe28-4dae-96e7-fa92bf6cfc2f\",\"clientId\":\"7e90a6ce-b44d-4a28-9ddc-cdc8c4489c0e\"},\"wwfvov\":{\"principalId\":\"fe58d95f-95d5-4696-b0ab-5726d560f651\",\"clientId\":\"b5675bdf-17af-47b4-b08b-8895f0381054\"}}},\"properties\":{\"analyticsWorkspaceId\":\"meue\",\"availabilityZones\":[\"yhz\",\"euojgjrwju\",\"iotwmcdytdxwit\",\"nrjawgqwg\"],\"clusterVersions\":[{\"supportExpiryDate\":\"skxfbk\",\"targetClusterVersion\":\"cg\"}],\"detailedStatus\":\"ProvisioningFailed\",\"detailedStatusMessage\":\"dnhjdauwhvylw\",\"fabricControllerId\":\"btdhxujznbm\",\"managedResourceGroupConfiguration\":{\"location\":\"uwprzql\",\"name\":\"ualupjmkh\"},\"managerExtendedLocation\":{\"name\":\"obbc\",\"type\":\"wsrtjriplrbpbe\"},\"provisioningState\":\"Updating\",\"vmSize\":\"fgb\"},\"location\":\"gw\",\"tags\":{\"ebwwaloayqc\":\"lvqhjkbegibtnmx\",\"uzgwyzmhtx\":\"wrtz\",\"wxqpsrknftguvri\":\"ngmtsavjcb\"},\"id\":\"hprwmdyv\",\"name\":\"qtayri\",\"type\":\"wroyqbexrmcq\"},{\"identity\":{\"principalId\":\"19dad387-8a89-4baf-a63f-080001245d99\",\"tenantId\":\"b5e2ee71-4ebb-4e56-95c1-359f53c88932\",\"type\":\"UserAssigned\",\"userAssignedIdentities\":{\"nmefqsgzvahapj\":{\"principalId\":\"6965eb73-482e-4d14-ae32-1d0518d079e5\",\"clientId\":\"d01d9d87-5bdb-4a6a-a324-c58d6969f07c\"}}},\"properties\":{\"analyticsWorkspaceId\":\"hpvgqz\",\"availabilityZones\":[\"vxdjzlmwlxkvugf\",\"zovawjvz\",\"nluthnnp\"],\"clusterVersions\":[{\"supportExpiryDate\":\"peilpjzuaejxdu\",\"targetClusterVersion\":\"skzbb\"},{\"supportExpiryDate\":\"zumveekgpwo\",\"targetClusterVersion\":\"hkfpbs\"},{\"supportExpiryDate\":\"ofd\",\"targetClusterVersion\":\"uusdttouwa\"},{\"supportExpiryDate\":\"ekqvkeln\",\"targetClusterVersion\":\"vbxwyjsflhh\"}],\"detailedStatus\":\"Provisioning\",\"detailedStatusMessage\":\"n\",\"fabricControllerId\":\"ixisxyawjoy\",\"managedResourceGroupConfiguration\":{\"location\":\"slyjpkiid\",\"name\":\"exznelixhnr\"},\"managerExtendedLocation\":{\"name\":\"folhbnxknal\",\"type\":\"ulppggdtpnapnyir\"},\"provisioningState\":\"Updating\",\"vmSize\":\"pigvpgylgqgitx\"},\"location\":\"djvcsl\",\"tags\":{\"rmgucnap\":\"wwncwzzhxgk\",\"oellwp\":\"t\"},\"id\":\"fdygpfqbuaceopz\",\"name\":\"qrhhu\",\"type\":\"opppcqeq\"},{\"identity\":{\"principalId\":\"5c4cab3e-f69e-4a03-aa69-262b1c3080cb\",\"tenantId\":\"d1adf45f-a687-4007-90d1-8ca7aa58b89e\",\"type\":\"UserAssigned\",\"userAssignedIdentities\":{\"ctobg\":{\"principalId\":\"6c643165-fa7b-4736-a580-5ced82c851a8\",\"clientId\":\"c49b4da3-628d-4dc8-88fb-13afa8f8eb7d\"},\"moizpos\":{\"principalId\":\"87f1646e-cc50-4f67-ad47-9eb4a0ce7860\",\"clientId\":\"085bb405-4662-46df-b524-7228ff57db76\"}}},\"properties\":{\"analyticsWorkspaceId\":\"grcfb\",\"availabilityZones\":[\"mfqjhhkxbp\",\"jy\",\"jhxxjyn\",\"u\"],\"clusterVersions\":[{\"supportExpiryDate\":\"r\",\"targetClusterVersion\":\"wbxqzvszjfau\"}],\"detailedStatus\":\"Available\",\"detailedStatusMessage\":\"xxivetv\",\"fabricControllerId\":\"cqaqtdoqmcbx\",\"managedResourceGroupConfiguration\":{\"location\":\"xyslqbh\",\"name\":\"xoblytkbl\"},\"managerExtendedLocation\":{\"name\":\"ewwwfbkrvrnsv\",\"type\":\"hqjohxcrsbfova\"},\"provisioningState\":\"Failed\",\"vmSize\":\"v\"},\"location\":\"hsqfsubcgjbirxbp\",\"tags\":{\"twss\":\"rfbjf\",\"tpvjzbexilzznfqq\":\"t\",\"taruoujmkcj\":\"vwpm\"},\"id\":\"wqytjrybnwjewgdr\",\"name\":\"ervnaenqpehi\",\"type\":\"doy\"}]}") + "{\"nextLink\":\"ali\",\"value\":[{\"identity\":{\"principalId\":\"774bb6e9-2227-4a5e-9260-efa9a40e670c\",\"tenantId\":\"996ab2c2-3195-4177-be52-de57e2870fc2\",\"type\":\"UserAssigned\",\"userAssignedIdentities\":{\"shsfwxosowzxcu\":{\"principalId\":\"00360df8-a097-489a-9686-d7e36c9e1e61\",\"clientId\":\"bacb47df-b5dd-4db8-9ca9-8f93cc003aa8\"},\"jooxdjebw\":{\"principalId\":\"cb6c6eb6-4280-475a-9433-361e83e1cb3e\",\"clientId\":\"ffd445e9-3c46-4b4a-8af0-a59f514e8100\"},\"wwfvov\":{\"principalId\":\"882df8b1-bc98-429e-ac17-6a8810814e39\",\"clientId\":\"d708f44a-e390-4d86-8297-ba7adc2fc59c\"}}},\"properties\":{\"analyticsWorkspaceId\":\"meue\",\"availabilityZones\":[\"yhz\",\"euojgjrwju\",\"iotwmcdytdxwit\",\"nrjawgqwg\"],\"clusterVersions\":[{\"supportExpiryDate\":\"skxfbk\",\"targetClusterVersion\":\"cg\"}],\"detailedStatus\":\"ProvisioningFailed\",\"detailedStatusMessage\":\"dnhjdauwhvylw\",\"fabricControllerId\":\"btdhxujznbm\",\"managedResourceGroupConfiguration\":{\"location\":\"uwprzql\",\"name\":\"ualupjmkh\"},\"managerExtendedLocation\":{\"name\":\"obbc\",\"type\":\"wsrtjriplrbpbe\"},\"provisioningState\":\"Updating\",\"vmSize\":\"fgb\"},\"location\":\"gw\",\"tags\":{\"ebwwaloayqc\":\"lvqhjkbegibtnmx\",\"uzgwyzmhtx\":\"wrtz\",\"wxqpsrknftguvri\":\"ngmtsavjcb\"},\"id\":\"hprwmdyv\",\"name\":\"qtayri\",\"type\":\"wroyqbexrmcq\"},{\"identity\":{\"principalId\":\"96567ddc-c959-4025-a483-b7859f3b9204\",\"tenantId\":\"96f0e8f3-ca19-4354-a446-0ff7bbb9a7eb\",\"type\":\"UserAssigned\",\"userAssignedIdentities\":{\"nmefqsgzvahapj\":{\"principalId\":\"09227b1b-2aa8-4d68-a517-2760bbf2f7d1\",\"clientId\":\"198eb677-7015-4f17-aa28-e0d6bd8c6542\"}}},\"properties\":{\"analyticsWorkspaceId\":\"hpvgqz\",\"availabilityZones\":[\"vxdjzlmwlxkvugf\",\"zovawjvz\",\"nluthnnp\"],\"clusterVersions\":[{\"supportExpiryDate\":\"peilpjzuaejxdu\",\"targetClusterVersion\":\"skzbb\"},{\"supportExpiryDate\":\"zumveekgpwo\",\"targetClusterVersion\":\"hkfpbs\"},{\"supportExpiryDate\":\"ofd\",\"targetClusterVersion\":\"uusdttouwa\"},{\"supportExpiryDate\":\"ekqvkeln\",\"targetClusterVersion\":\"vbxwyjsflhh\"}],\"detailedStatus\":\"Provisioning\",\"detailedStatusMessage\":\"n\",\"fabricControllerId\":\"ixisxyawjoy\",\"managedResourceGroupConfiguration\":{\"location\":\"slyjpkiid\",\"name\":\"exznelixhnr\"},\"managerExtendedLocation\":{\"name\":\"folhbnxknal\",\"type\":\"ulppggdtpnapnyir\"},\"provisioningState\":\"Updating\",\"vmSize\":\"pigvpgylgqgitx\"},\"location\":\"djvcsl\",\"tags\":{\"rmgucnap\":\"wwncwzzhxgk\",\"oellwp\":\"t\"},\"id\":\"fdygpfqbuaceopz\",\"name\":\"qrhhu\",\"type\":\"opppcqeq\"},{\"identity\":{\"principalId\":\"4ca34c49-d6de-46f6-9016-8987030f6037\",\"tenantId\":\"b360e908-c1ff-4967-aff8-2de08cfd1043\",\"type\":\"UserAssigned\",\"userAssignedIdentities\":{\"ctobg\":{\"principalId\":\"733f210e-45e3-4113-8a1c-304b8bec8435\",\"clientId\":\"b0966229-3307-4ccb-a7c5-7e2e93ef9234\"},\"moizpos\":{\"principalId\":\"46eba6a5-7669-4bca-89d9-a6ebe5a38984\",\"clientId\":\"7f88261d-9a96-430e-957a-419934da1a74\"}}},\"properties\":{\"analyticsWorkspaceId\":\"grcfb\",\"availabilityZones\":[\"mfqjhhkxbp\",\"jy\",\"jhxxjyn\",\"u\"],\"clusterVersions\":[{\"supportExpiryDate\":\"r\",\"targetClusterVersion\":\"wbxqzvszjfau\"}],\"detailedStatus\":\"Available\",\"detailedStatusMessage\":\"xxivetv\",\"fabricControllerId\":\"cqaqtdoqmcbx\",\"managedResourceGroupConfiguration\":{\"location\":\"xyslqbh\",\"name\":\"xoblytkbl\"},\"managerExtendedLocation\":{\"name\":\"ewwwfbkrvrnsv\",\"type\":\"hqjohxcrsbfova\"},\"provisioningState\":\"Failed\",\"vmSize\":\"v\"},\"location\":\"hsqfsubcgjbirxbp\",\"tags\":{\"twss\":\"rfbjf\",\"tpvjzbexilzznfqq\":\"t\",\"taruoujmkcj\":\"vwpm\"},\"id\":\"wqytjrybnwjewgdr\",\"name\":\"ervnaenqpehi\",\"type\":\"doy\"}]}") .toObject(ClusterManagerList.class); Assertions.assertEquals("ali", model.nextLink()); Assertions.assertEquals("gw", model.value().get(0).location()); diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagerPatchParametersTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagerPatchParametersTests.java index 8ce2e86f0da3..533b4df2c061 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagerPatchParametersTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagerPatchParametersTests.java @@ -17,7 +17,7 @@ public final class ClusterManagerPatchParametersTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ClusterManagerPatchParameters model = BinaryData.fromString( - "{\"identity\":{\"principalId\":\"7b4a5a81-f88a-4c6d-a5db-35a0641bdf90\",\"tenantId\":\"40f9ac5e-c21c-4158-831d-d3569e891df6\",\"type\":\"SystemAssigned\",\"userAssignedIdentities\":{\"lu\":{\"principalId\":\"050ddab3-f26f-4462-bff3-aaf69d12a188\",\"clientId\":\"dbf82f40-a210-425c-a5aa-aa54a3e7a689\"},\"tangcfhnykzcu\":{\"principalId\":\"e1e3d571-6385-4a48-9ee6-c0c5df9cfce2\",\"clientId\":\"020f20f7-8027-4f55-8dac-929382302c9c\"},\"vxwlmzqwmvtxnj\":{\"principalId\":\"fa0aec32-dc1c-414f-a1fa-dbf7a8a7f8ce\",\"clientId\":\"59682341-4e23-4639-9f51-5b4830c091b6\"}}},\"tags\":{\"pdkvg\":\"cuqudtcvclxy\",\"ibuz\":\"abuiy\",\"xgjiuqh\":\"hdugneiknpg\"}}") + "{\"identity\":{\"principalId\":\"c4295c82-9d6e-491d-a4ad-a457bc6954e7\",\"tenantId\":\"f28fd806-a4aa-4239-9d59-6501c3550fd8\",\"type\":\"SystemAssigned\",\"userAssignedIdentities\":{\"lu\":{\"principalId\":\"ea4341fe-b3ba-4457-b096-5b2981bc77c7\",\"clientId\":\"a63d3fb5-d31e-4556-86d1-47c203e9b215\"},\"tangcfhnykzcu\":{\"principalId\":\"eccb7617-4b93-441d-bfa3-590faf3fda1d\",\"clientId\":\"09be1f40-d778-4b32-9b8d-cfc9904aaa31\"},\"vxwlmzqwmvtxnj\":{\"principalId\":\"ef2c8fa3-0ac6-4601-82a6-f633cfe68be2\",\"clientId\":\"fa10b3c9-1b4e-485c-8709-fd8c42facf4e\"}}},\"tags\":{\"pdkvg\":\"cuqudtcvclxy\",\"ibuz\":\"abuiy\",\"xgjiuqh\":\"hdugneiknpg\"}}") .toObject(ClusterManagerPatchParameters.class); Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_ASSIGNED, model.identity().type()); Assertions.assertEquals("cuqudtcvclxy", model.tags().get("pdkvg")); diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersCreateOrUpdateMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersCreateOrUpdateMockTests.java index 7a8478fac190..2787998b0679 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersCreateOrUpdateMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersCreateOrUpdateMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.ClusterManager; @@ -28,14 +28,14 @@ public final class ClusterManagersCreateOrUpdateMockTests { @Test public void testCreateOrUpdate() throws Exception { String responseStr - = "{\"identity\":{\"principalId\":\"e268ac60-edd9-4fab-9292-3acd76011c78\",\"tenantId\":\"1615f97b-1321-4f0a-8b71-872bbb4fede2\",\"type\":\"UserAssigned\",\"userAssignedIdentities\":{\"dnaienhqhskndnel\":{\"principalId\":\"005c1ee7-f0ec-4faa-96f9-0377b7224ef7\",\"clientId\":\"16f1a90c-acd1-446d-9656-a59ed1137a47\"},\"adlknwfoanni\":{\"principalId\":\"32ae87aa-3137-47d4-80f0-66fe56d4933e\",\"clientId\":\"daa7a91a-dfd1-4ea6-9c9e-dea4fe198728\"}}},\"properties\":{\"analyticsWorkspaceId\":\"petxivcnrlyxnu\",\"availabilityZones\":[\"p\",\"blkwqpatvbqs\",\"tcjb\",\"tvivuzqym\"],\"clusterVersions\":[{\"supportExpiryDate\":\"o\",\"targetClusterVersion\":\"gitsqh\"}],\"detailedStatus\":\"ProvisioningFailed\",\"detailedStatusMessage\":\"zcdba\",\"fabricControllerId\":\"fzndscxmxeatkd\",\"managedResourceGroupConfiguration\":{\"location\":\"nrd\",\"name\":\"ibqbnaomhjrm\"},\"managerExtendedLocation\":{\"name\":\"hmaxljalfi\",\"type\":\"cjmobcanc\"},\"provisioningState\":\"Succeeded\",\"vmSize\":\"qcwgaxfgvaknokz\"},\"location\":\"jzrltixldzy\",\"tags\":{\"ixymmpujivyql\":\"tpq\",\"dbpqvybefgvm\":\"juvsmbmslzoyovw\",\"lubses\":\"nokcv\",\"pirykycndzfqiv\":\"vcuartrhun\"},\"id\":\"reuykbbmnwagl\",\"name\":\"bxoeeonql\",\"type\":\"fwmyymv\"}"; + = "{\"identity\":{\"principalId\":\"09e35414-2870-45ba-b504-39cebd50abc8\",\"tenantId\":\"87f9e9b0-57cc-48af-bc08-110bf896e455\",\"type\":\"UserAssigned\",\"userAssignedIdentities\":{\"dnaienhqhskndnel\":{\"principalId\":\"49c3ad80-9a83-425c-9084-68e85a2cf003\",\"clientId\":\"d664d2df-88e3-4131-bd27-31316867f43e\"},\"adlknwfoanni\":{\"principalId\":\"191cc5cf-e491-485f-8521-0b21de3131d4\",\"clientId\":\"b5a19a6c-06a0-43ae-bac5-ef749aa7597e\"}}},\"properties\":{\"analyticsWorkspaceId\":\"petxivcnrlyxnu\",\"availabilityZones\":[\"p\",\"blkwqpatvbqs\",\"tcjb\",\"tvivuzqym\"],\"clusterVersions\":[{\"supportExpiryDate\":\"o\",\"targetClusterVersion\":\"gitsqh\"}],\"detailedStatus\":\"ProvisioningFailed\",\"detailedStatusMessage\":\"zcdba\",\"fabricControllerId\":\"fzndscxmxeatkd\",\"managedResourceGroupConfiguration\":{\"location\":\"nrd\",\"name\":\"ibqbnaomhjrm\"},\"managerExtendedLocation\":{\"name\":\"hmaxljalfi\",\"type\":\"cjmobcanc\"},\"provisioningState\":\"Succeeded\",\"vmSize\":\"qcwgaxfgvaknokz\"},\"location\":\"jzrltixldzy\",\"tags\":{\"ixymmpujivyql\":\"tpq\",\"dbpqvybefgvm\":\"juvsmbmslzoyovw\",\"lubses\":\"nokcv\",\"pirykycndzfqiv\":\"vcuartrhun\"},\"id\":\"reuykbbmnwagl\",\"name\":\"bxoeeonql\",\"type\":\"fwmyymv\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); ClusterManager response = manager.clusterManagers() .define("mcqmiciijqp") diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersGetByResourceGroupWithResponseMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersGetByResourceGroupWithResponseMockTests.java index 430a89e442d9..c88946649add 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersGetByResourceGroupWithResponseMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersGetByResourceGroupWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.ClusterManager; @@ -22,14 +22,14 @@ public final class ClusterManagersGetByResourceGroupWithResponseMockTests { @Test public void testGetByResourceGroupWithResponse() throws Exception { String responseStr - = "{\"identity\":{\"principalId\":\"453b87f5-f3fe-4e4e-8723-1c80d857bbe7\",\"tenantId\":\"2ea81332-bd17-44c5-95b5-afd76520ffd2\",\"type\":\"UserAssigned\",\"userAssignedIdentities\":{\"qnzmnhiil\":{\"principalId\":\"6133586e-eb63-4217-b204-04a52b432c07\",\"clientId\":\"f65aef5d-bd78-43f3-b682-bb8f78469262\"},\"w\":{\"principalId\":\"858b76c1-c8c5-4eb2-a0c8-dc169dba1383\",\"clientId\":\"d80e91b8-cc09-4844-9681-6a1a8f47e937\"},\"ckbbcc\":{\"principalId\":\"c630ecaa-d778-402c-a023-7d29f1394d0d\",\"clientId\":\"993e74e3-e74b-47b8-912e-ea8c1741f39c\"}}},\"properties\":{\"analyticsWorkspaceId\":\"zpraoxn\",\"availabilityZones\":[\"fa\",\"sgftipwc\",\"byubhiqdxyurnpn\"],\"clusterVersions\":[{\"supportExpiryDate\":\"fccnuhiigb\",\"targetClusterVersion\":\"bui\"},{\"supportExpiryDate\":\"xvatvcr\",\"targetClusterVersion\":\"lbnb\"},{\"supportExpiryDate\":\"vhcs\",\"targetClusterVersion\":\"zlwxaeaovur\"}],\"detailedStatus\":\"ProvisioningFailed\",\"detailedStatusMessage\":\"d\",\"fabricControllerId\":\"bdweade\",\"managedResourceGroupConfiguration\":{\"location\":\"wntopag\",\"name\":\"mvmmagoaqylkjz\"},\"managerExtendedLocation\":{\"name\":\"iua\",\"type\":\"jcg\"},\"provisioningState\":\"Updating\",\"vmSize\":\"pfinzcpdltkrlg\"},\"location\":\"tbdrvcqgue\",\"tags\":{\"lyujlfyoump\":\"ompheqdur\",\"brzmqxucycijoclx\":\"kyeclcdigpta\",\"zjd\":\"utgjcyz\",\"jb\":\"r\"},\"id\":\"xjeaoqaqbzgyh\",\"name\":\"w\",\"type\":\"v\"}"; + = "{\"identity\":{\"principalId\":\"b8e093ea-b1dd-41b3-b2ce-1c11809a1fad\",\"tenantId\":\"cf461f0c-d0f3-438d-a4b8-2a8bb1eaa90c\",\"type\":\"UserAssigned\",\"userAssignedIdentities\":{\"qnzmnhiil\":{\"principalId\":\"5b7850fe-b31d-4299-a546-b06e6a706f1a\",\"clientId\":\"5a823cc2-d5fd-4d79-8998-cfeffd07db3d\"},\"w\":{\"principalId\":\"57f5dfaa-c35b-4b48-9a9d-07aa37619c83\",\"clientId\":\"c7cdb073-1b99-4201-a0ec-4a5c9414b938\"},\"ckbbcc\":{\"principalId\":\"0c6ba647-3bf3-46ab-991c-c0fb6ff7e56a\",\"clientId\":\"9713f72d-843b-4822-9336-4a7e1c0abf41\"}}},\"properties\":{\"analyticsWorkspaceId\":\"zpraoxn\",\"availabilityZones\":[\"fa\",\"sgftipwc\",\"byubhiqdxyurnpn\"],\"clusterVersions\":[{\"supportExpiryDate\":\"fccnuhiigb\",\"targetClusterVersion\":\"bui\"},{\"supportExpiryDate\":\"xvatvcr\",\"targetClusterVersion\":\"lbnb\"},{\"supportExpiryDate\":\"vhcs\",\"targetClusterVersion\":\"zlwxaeaovur\"}],\"detailedStatus\":\"ProvisioningFailed\",\"detailedStatusMessage\":\"d\",\"fabricControllerId\":\"bdweade\",\"managedResourceGroupConfiguration\":{\"location\":\"wntopag\",\"name\":\"mvmmagoaqylkjz\"},\"managerExtendedLocation\":{\"name\":\"iua\",\"type\":\"jcg\"},\"provisioningState\":\"Updating\",\"vmSize\":\"pfinzcpdltkrlg\"},\"location\":\"tbdrvcqgue\",\"tags\":{\"lyujlfyoump\":\"ompheqdur\",\"brzmqxucycijoclx\":\"kyeclcdigpta\",\"zjd\":\"utgjcyz\",\"jb\":\"r\"},\"id\":\"xjeaoqaqbzgyh\",\"name\":\"w\",\"type\":\"v\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); ClusterManager response = manager.clusterManagers() .getByResourceGroupWithResponse("iuxegth", "rtudawlpjfel", com.azure.core.util.Context.NONE) diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersListByResourceGroupMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersListByResourceGroupMockTests.java index 411f2a19279e..f3c8b34a129b 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersListByResourceGroupMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersListByResourceGroupMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.ClusterManager; @@ -23,14 +23,14 @@ public final class ClusterManagersListByResourceGroupMockTests { @Test public void testListByResourceGroup() throws Exception { String responseStr - = "{\"value\":[{\"identity\":{\"principalId\":\"ee09de5e-0b08-4077-a972-e27caad4a133\",\"tenantId\":\"2aaba3bc-371e-4ade-8b3d-73b670498c78\",\"type\":\"None\",\"userAssignedIdentities\":{\"zuqnwsithuqo\":{\"principalId\":\"26a21559-c5cf-4ae8-a241-9e197a7bd553\",\"clientId\":\"5d113e77-1142-452e-ab6b-cac4377743af\"}}},\"properties\":{\"analyticsWorkspaceId\":\"ah\",\"availabilityZones\":[\"wqulsutrjbhxykf\",\"y\"],\"clusterVersions\":[{\"supportExpiryDate\":\"qqug\",\"targetClusterVersion\":\"ftbcvexreuquow\"},{\"supportExpiryDate\":\"jv\",\"targetClusterVersion\":\"hreagk\"},{\"supportExpiryDate\":\"xv\",\"targetClusterVersion\":\"tvbczsulm\"},{\"supportExpiryDate\":\"glmep\",\"targetClusterVersion\":\"fs\"}],\"detailedStatus\":\"Provisioning\",\"detailedStatusMessage\":\"sa\",\"fabricControllerId\":\"gpszngafpg\",\"managedResourceGroupConfiguration\":{\"location\":\"vecjujcn\",\"name\":\"adyedmzrgjfok\"},\"managerExtendedLocation\":{\"name\":\"bnoit\",\"type\":\"kpztrgd\"},\"provisioningState\":\"Provisioning\",\"vmSize\":\"oqraswugyxpqi\"},\"location\":\"eialwvskb\",\"tags\":{\"pdsxzakuejkm\":\"acaqtyltcoqcu\"},\"id\":\"bizt\",\"name\":\"ofqcvovjufycsjm\",\"type\":\"bemyeji\"}]}"; + = "{\"value\":[{\"identity\":{\"principalId\":\"c7ec64ab-7d46-43ea-97d4-b9f4e186cb3a\",\"tenantId\":\"10e98832-9cf9-4ec4-a589-db3b6a635ed8\",\"type\":\"None\",\"userAssignedIdentities\":{\"zuqnwsithuqo\":{\"principalId\":\"080437d2-cf6c-4bb2-8890-7ae20b9b958d\",\"clientId\":\"7028199d-b077-4a97-b7af-e7266f437dfb\"}}},\"properties\":{\"analyticsWorkspaceId\":\"ah\",\"availabilityZones\":[\"wqulsutrjbhxykf\",\"y\"],\"clusterVersions\":[{\"supportExpiryDate\":\"qqug\",\"targetClusterVersion\":\"ftbcvexreuquow\"},{\"supportExpiryDate\":\"jv\",\"targetClusterVersion\":\"hreagk\"},{\"supportExpiryDate\":\"xv\",\"targetClusterVersion\":\"tvbczsulm\"},{\"supportExpiryDate\":\"glmep\",\"targetClusterVersion\":\"fs\"}],\"detailedStatus\":\"Provisioning\",\"detailedStatusMessage\":\"sa\",\"fabricControllerId\":\"gpszngafpg\",\"managedResourceGroupConfiguration\":{\"location\":\"vecjujcn\",\"name\":\"adyedmzrgjfok\"},\"managerExtendedLocation\":{\"name\":\"bnoit\",\"type\":\"kpztrgd\"},\"provisioningState\":\"Provisioning\",\"vmSize\":\"oqraswugyxpqi\"},\"location\":\"eialwvskb\",\"tags\":{\"pdsxzakuejkm\":\"acaqtyltcoqcu\"},\"id\":\"bizt\",\"name\":\"ofqcvovjufycsjm\",\"type\":\"bemyeji\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.clusterManagers().listByResourceGroup("phlkksnm", com.azure.core.util.Context.NONE); diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersListMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersListMockTests.java index 335f0706737b..8b02fa527e26 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersListMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ClusterManagersListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.ClusterManager; @@ -23,14 +23,14 @@ public final class ClusterManagersListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"identity\":{\"principalId\":\"a303995d-39d1-4709-ad26-984194e7e717\",\"tenantId\":\"9a26af15-17df-45aa-9ddb-8ce2e8dd266f\",\"type\":\"SystemAssigned,UserAssigned\",\"userAssignedIdentities\":{\"zkkdtnhqs\":{\"principalId\":\"d547ea19-a2f8-432f-afa3-18ff9d3c4885\",\"clientId\":\"6af7925a-d5da-4836-8263-138718258e04\"},\"jselpkpbafvafh\":{\"principalId\":\"90e4e34c-111a-4a66-8d72-a04d074a4f74\",\"clientId\":\"32daae6b-0565-4e8c-b1b5-d00dd47c6301\"}}},\"properties\":{\"analyticsWorkspaceId\":\"ylcc\",\"availabilityZones\":[\"xrhyzdfwrsofplt\"],\"clusterVersions\":[{\"supportExpiryDate\":\"irrhv\",\"targetClusterVersion\":\"nracw\"},{\"supportExpiryDate\":\"qigtuujwouhdaws\",\"targetClusterVersion\":\"rb\"}],\"detailedStatus\":\"Available\",\"detailedStatusMessage\":\"jybvit\",\"fabricControllerId\":\"qkj\",\"managedResourceGroupConfiguration\":{\"location\":\"nu\",\"name\":\"ggmuwdcho\"},\"managerExtendedLocation\":{\"name\":\"nkf\",\"type\":\"xlvxnoakiz\"},\"provisioningState\":\"Canceled\",\"vmSize\":\"knaqlnuwig\"},\"location\":\"xly\",\"tags\":{\"jtlkexaonwivkcqh\":\"hvxzcwxhmp\",\"rmmkyupiju\":\"xhxknlc\"},\"id\":\"yqjf\",\"name\":\"akfqfrkemyildud\",\"type\":\"jascowvfdjkpd\"}]}"; + = "{\"value\":[{\"identity\":{\"principalId\":\"4a1b8dfe-3120-471b-950b-02e0c87a5380\",\"tenantId\":\"148a9ad3-000f-49ff-8274-88119a8fe89f\",\"type\":\"SystemAssigned,UserAssigned\",\"userAssignedIdentities\":{\"zkkdtnhqs\":{\"principalId\":\"392f005c-2042-46f7-978f-3993f445e090\",\"clientId\":\"f5a78a7f-90f6-4aff-aa3c-8e9a9efd0353\"},\"jselpkpbafvafh\":{\"principalId\":\"83b712ba-585f-4f61-b2c6-12da3c9217a2\",\"clientId\":\"9cc2a6db-9edd-49a3-a6a0-e64f995bbc23\"}}},\"properties\":{\"analyticsWorkspaceId\":\"ylcc\",\"availabilityZones\":[\"xrhyzdfwrsofplt\"],\"clusterVersions\":[{\"supportExpiryDate\":\"irrhv\",\"targetClusterVersion\":\"nracw\"},{\"supportExpiryDate\":\"qigtuujwouhdaws\",\"targetClusterVersion\":\"rb\"}],\"detailedStatus\":\"Available\",\"detailedStatusMessage\":\"jybvit\",\"fabricControllerId\":\"qkj\",\"managedResourceGroupConfiguration\":{\"location\":\"nu\",\"name\":\"ggmuwdcho\"},\"managerExtendedLocation\":{\"name\":\"nkf\",\"type\":\"xlvxnoakiz\"},\"provisioningState\":\"Canceled\",\"vmSize\":\"knaqlnuwig\"},\"location\":\"xly\",\"tags\":{\"jtlkexaonwivkcqh\":\"hvxzcwxhmp\",\"rmmkyupiju\":\"xhxknlc\"},\"id\":\"yqjf\",\"name\":\"akfqfrkemyildud\",\"type\":\"jascowvfdjkpd\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.clusterManagers().list(com.azure.core.util.Context.NONE); diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksCreateOrUpdateMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksCreateOrUpdateMockTests.java index 60c25368c0f5..1db81063ddc7 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksCreateOrUpdateMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksCreateOrUpdateMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.ExtendedLocation; @@ -32,7 +32,7 @@ public void testCreateOrUpdate() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); L2Network response = manager.l2Networks() .define("khgsnxuwwkpphefs") diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksGetByResourceGroupWithResponseMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksGetByResourceGroupWithResponseMockTests.java index 63d63a8f5479..3848b33e52c9 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksGetByResourceGroupWithResponseMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksGetByResourceGroupWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.HybridAksPluginType; @@ -29,7 +29,7 @@ public void testGetByResourceGroupWithResponse() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); L2Network response = manager.l2Networks() .getByResourceGroupWithResponse("qmje", "jcx", com.azure.core.util.Context.NONE) diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksListByResourceGroupMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksListByResourceGroupMockTests.java index 28fd4837116c..cd7577da5976 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksListByResourceGroupMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksListByResourceGroupMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.HybridAksPluginType; @@ -30,7 +30,7 @@ public void testListByResourceGroup() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.l2Networks().listByResourceGroup("wxdcvjwcyz", com.azure.core.util.Context.NONE); diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksListMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksListMockTests.java index 2a30d37da7cd..b43ea069acc4 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksListMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L2NetworksListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.HybridAksPluginType; @@ -30,7 +30,7 @@ public void testList() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.l2Networks().list(com.azure.core.util.Context.NONE); diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksCreateOrUpdateMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksCreateOrUpdateMockTests.java index 9d431a2c1106..68eeee16c6c2 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksCreateOrUpdateMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksCreateOrUpdateMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.ExtendedLocation; @@ -34,7 +34,7 @@ public void testCreateOrUpdate() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); L3Network response = manager.l3Networks() .define("vfejvqnttmbqda") diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksGetByResourceGroupWithResponseMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksGetByResourceGroupWithResponseMockTests.java index 780c0fe6db66..dc293084a920 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksGetByResourceGroupWithResponseMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksGetByResourceGroupWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.HybridAksIpamEnabled; @@ -31,7 +31,7 @@ public void testGetByResourceGroupWithResponse() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); L3Network response = manager.l3Networks() .getByResourceGroupWithResponse("xhmt", "tvegwqiukvzwy", com.azure.core.util.Context.NONE) diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksListByResourceGroupMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksListByResourceGroupMockTests.java index 00ddc7d4914a..32c62dd00dc7 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksListByResourceGroupMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksListByResourceGroupMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.HybridAksIpamEnabled; @@ -32,7 +32,7 @@ public void testListByResourceGroup() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.l3Networks().listByResourceGroup("slojfkqidnqt", com.azure.core.util.Context.NONE); diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksListMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksListMockTests.java index e74273c2529d..a47a38584759 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksListMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/L3NetworksListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.HybridAksIpamEnabled; @@ -32,7 +32,7 @@ public void testList() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.l3Networks().list(com.azure.core.util.Context.NONE); diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ManagedServiceIdentityTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ManagedServiceIdentityTests.java index e7ce0894a5db..145a26db5341 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ManagedServiceIdentityTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/ManagedServiceIdentityTests.java @@ -16,7 +16,7 @@ public final class ManagedServiceIdentityTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ManagedServiceIdentity model = BinaryData.fromString( - "{\"principalId\":\"5f1efe55-ed9a-4338-b1c8-6eb7307e3a35\",\"tenantId\":\"45fb55fa-8c2f-4b63-8ab6-df515b9abada\",\"type\":\"SystemAssigned\",\"userAssignedIdentities\":{\"bqdxbx\":{\"principalId\":\"9cb7ff49-3db9-4e2b-9168-faf70f8cb95c\",\"clientId\":\"75cd94db-42cd-49a9-93c1-88b3ffca57fc\"},\"bogqxndlkzgxhu\":{\"principalId\":\"5bbd7b15-f7df-4fff-87c4-366c8362fbeb\",\"clientId\":\"04212cfc-e886-45bd-9f3a-1c792d5641ec\"},\"lbpodxunk\":{\"principalId\":\"33edc721-8ec0-4e2c-896d-636280f0606c\",\"clientId\":\"a36c8268-efeb-489a-9a97-cd5d9467fadf\"},\"xmubyyntwlrbq\":{\"principalId\":\"0bc664ab-1c77-427a-aa00-cafde0c06823\",\"clientId\":\"c1018d5a-8dd3-4766-b268-f0bb1934ae96\"}}}") + "{\"principalId\":\"343b7cd4-ec94-4d64-a045-8a8a073dec79\",\"tenantId\":\"863d875b-a8c6-4650-bf9c-17be7262b765\",\"type\":\"SystemAssigned\",\"userAssignedIdentities\":{\"bqdxbx\":{\"principalId\":\"9aac8354-a4b9-4624-a6d5-e881d4a84923\",\"clientId\":\"40f8da2b-8f26-414e-81c1-450026c7c9cc\"},\"bogqxndlkzgxhu\":{\"principalId\":\"563caa6c-4fc7-4b49-9910-fc3019802761\",\"clientId\":\"ed2232d2-0f84-467f-af78-25143d97ac0f\"},\"lbpodxunk\":{\"principalId\":\"7f479f8e-5658-4344-8919-b57944b40d21\",\"clientId\":\"94652ece-153c-45f6-bffa-f24c36ee7c04\"},\"xmubyyntwlrbq\":{\"principalId\":\"a799108f-8523-4f4d-ba15-2c889ee277fb\",\"clientId\":\"b177384e-ab7a-40f3-88c1-f38786e54d29\"}}}") .toObject(ManagedServiceIdentity.class); Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_ASSIGNED, model.type()); } diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsCreateOrUpdateMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsCreateOrUpdateMockTests.java index ffcba5e7a0d1..b32da20dd9fe 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsCreateOrUpdateMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsCreateOrUpdateMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.ClusterMetricsConfiguration; @@ -32,7 +32,7 @@ public void testCreateOrUpdate() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); ClusterMetricsConfiguration response = manager.metricsConfigurations() .define("tvdxxhe") diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsGetWithResponseMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsGetWithResponseMockTests.java index ed15b82dce01..f587063a9e66 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsGetWithResponseMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsGetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.ClusterMetricsConfiguration; @@ -28,7 +28,7 @@ public void testGetWithResponse() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); ClusterMetricsConfiguration response = manager.metricsConfigurations() .getWithResponse("fpjbqggwe", "iwdhdmncgbfzu", "cstu", com.azure.core.util.Context.NONE) diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsListByClusterMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsListByClusterMockTests.java index b0aab32ec57a..4b2ab7520225 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsListByClusterMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/MetricsConfigurationsListByClusterMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.ClusterMetricsConfiguration; @@ -29,7 +29,7 @@ public void testListByCluster() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.metricsConfigurations().listByCluster("odfcbjq", "wmtqsmoxsaz", com.azure.core.util.Context.NONE); diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/OperationsListMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/OperationsListMockTests.java index 787e2404ca35..b0b3852fdcab 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/OperationsListMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/OperationsListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.Operation; @@ -28,7 +28,7 @@ public void testList() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.operations().list(com.azure.core.util.Context.NONE); diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/RackSkusGetWithResponseMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/RackSkusGetWithResponseMockTests.java index 45f801b82384..4ddebecd6b0d 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/RackSkusGetWithResponseMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/RackSkusGetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.RackSku; @@ -27,7 +27,7 @@ public void testGetWithResponse() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); RackSku response = manager.rackSkus().getWithResponse("uwj", com.azure.core.util.Context.NONE).getValue(); diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/RackSkusListMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/RackSkusListMockTests.java index 6c183c274bcb..24c5e3c04b83 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/RackSkusListMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/RackSkusListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.RackSku; @@ -28,7 +28,7 @@ public void testList() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.rackSkus().list(com.azure.core.util.Context.NONE); diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/RacksCreateOrUpdateMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/RacksCreateOrUpdateMockTests.java index aa688ad90a8d..ac2dd353373e 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/RacksCreateOrUpdateMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/RacksCreateOrUpdateMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.ExtendedLocation; @@ -31,7 +31,7 @@ public void testCreateOrUpdate() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); Rack response = manager.racks() .define("ptpqayamkn") diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/RacksGetByResourceGroupWithResponseMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/RacksGetByResourceGroupWithResponseMockTests.java index 8bf57aa58338..362058129f50 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/RacksGetByResourceGroupWithResponseMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/RacksGetByResourceGroupWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.Rack; @@ -28,7 +28,7 @@ public void testGetByResourceGroupWithResponse() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); Rack response = manager.racks() .getByResourceGroupWithResponse("zp", "admskx", com.azure.core.util.Context.NONE) diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/RacksListByResourceGroupMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/RacksListByResourceGroupMockTests.java index 92ee594ccd05..f56c46ed4d61 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/RacksListByResourceGroupMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/RacksListByResourceGroupMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.Rack; @@ -29,7 +29,7 @@ public void testListByResourceGroup() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.racks().listByResourceGroup("cu", com.azure.core.util.Context.NONE); diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/RacksListMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/RacksListMockTests.java index dfbb9ce77e5d..88d929e98948 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/RacksListMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/RacksListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.Rack; @@ -29,7 +29,7 @@ public void testList() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.racks().list(com.azure.core.util.Context.NONE); diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksCreateOrUpdateMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksCreateOrUpdateMockTests.java index 3e4efc2e5339..5ba38dd16d25 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksCreateOrUpdateMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksCreateOrUpdateMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.ExtendedLocation; @@ -33,7 +33,7 @@ public void testCreateOrUpdate() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); TrunkedNetwork response = manager.trunkedNetworks() .define("exkydfb") diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksGetByResourceGroupWithResponseMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksGetByResourceGroupWithResponseMockTests.java index c236f943b499..88e646b437a2 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksGetByResourceGroupWithResponseMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksGetByResourceGroupWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.HybridAksPluginType; @@ -29,7 +29,7 @@ public void testGetByResourceGroupWithResponse() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); TrunkedNetwork response = manager.trunkedNetworks() .getByResourceGroupWithResponse("sbvr", "aqgvto", com.azure.core.util.Context.NONE) diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksListByResourceGroupMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksListByResourceGroupMockTests.java index 24a3d9a56ca5..29a0f79bdc77 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksListByResourceGroupMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksListByResourceGroupMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.HybridAksPluginType; @@ -30,7 +30,7 @@ public void testListByResourceGroup() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.trunkedNetworks().listByResourceGroup("pqht", com.azure.core.util.Context.NONE); diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksListMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksListMockTests.java index e3bc7c2f02e2..4c07c703b66f 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksListMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/TrunkedNetworksListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.HybridAksPluginType; @@ -30,7 +30,7 @@ public void testList() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.trunkedNetworks().list(com.azure.core.util.Context.NONE); diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/UserAssignedIdentityTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/UserAssignedIdentityTests.java index a5d6a55dae58..8eed0fa9c430 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/UserAssignedIdentityTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/UserAssignedIdentityTests.java @@ -11,7 +11,7 @@ public final class UserAssignedIdentityTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { UserAssignedIdentity model = BinaryData.fromString( - "{\"principalId\":\"ef93c325-8cf8-4a49-9cd9-82efc5355b76\",\"clientId\":\"18c9709e-b2c4-40bb-9622-5071a7849b5c\"}") + "{\"principalId\":\"bcd5b4f1-baf3-4e40-9de8-70f79b57aaae\",\"clientId\":\"83b2a94e-0cfd-4fc7-a5ba-9dd3b9b4c564\"}") .toObject(UserAssignedIdentity.class); } diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/VolumesCreateOrUpdateMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/VolumesCreateOrUpdateMockTests.java index 3cf7c2fb9146..8d1d0a708bca 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/VolumesCreateOrUpdateMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/VolumesCreateOrUpdateMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.ExtendedLocation; @@ -31,7 +31,7 @@ public void testCreateOrUpdate() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); Volume response = manager.volumes() .define("h") diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/VolumesGetByResourceGroupWithResponseMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/VolumesGetByResourceGroupWithResponseMockTests.java index bed3fb88815b..5e13ad72e800 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/VolumesGetByResourceGroupWithResponseMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/VolumesGetByResourceGroupWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.Volume; @@ -28,7 +28,7 @@ public void testGetByResourceGroupWithResponse() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); Volume response = manager.volumes() .getByResourceGroupWithResponse("ucbdaom", "wiinjdllw", com.azure.core.util.Context.NONE) diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/VolumesListByResourceGroupMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/VolumesListByResourceGroupMockTests.java index 159d16ed302e..2b5d9e26362e 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/VolumesListByResourceGroupMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/VolumesListByResourceGroupMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.Volume; @@ -29,7 +29,7 @@ public void testListByResourceGroup() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.volumes().listByResourceGroup("jsb", com.azure.core.util.Context.NONE); diff --git a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/VolumesListMockTests.java b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/VolumesListMockTests.java index 5bb61feb2869..bee1c9146f43 100644 --- a/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/VolumesListMockTests.java +++ b/sdk/networkcloud/azure-resourcemanager-networkcloud/src/test/java/com/azure/resourcemanager/networkcloud/generated/VolumesListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.networkcloud.NetworkCloudManager; import com.azure.resourcemanager.networkcloud.models.Volume; @@ -29,7 +29,7 @@ public void testList() throws Exception { NetworkCloudManager manager = NetworkCloudManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.volumes().list(com.azure.core.util.Context.NONE); diff --git a/sdk/networkfunction/azure-resourcemanager-networkfunction/README.md b/sdk/networkfunction/azure-resourcemanager-networkfunction/README.md index 801faa5e8051..1b13f505c8c1 100644 --- a/sdk/networkfunction/azure-resourcemanager-networkfunction/README.md +++ b/sdk/networkfunction/azure-resourcemanager-networkfunction/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-networkfunction - 1.0.0-beta.3 + 1.0.0-beta.4 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fnetworkfunction%2Fazure-resourcemanager-networkfunction%2FREADME.png) + diff --git a/sdk/networkfunction/azure-resourcemanager-networkfunction/pom.xml b/sdk/networkfunction/azure-resourcemanager-networkfunction/pom.xml index be38812d66c4..5aff7025a8f6 100644 --- a/sdk/networkfunction/azure-resourcemanager-networkfunction/pom.xml +++ b/sdk/networkfunction/azure-resourcemanager-networkfunction/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/newrelicobservability/azure-resourcemanager-newrelicobservability/README.md b/sdk/newrelicobservability/azure-resourcemanager-newrelicobservability/README.md index 7136c4502fd8..c59c56d1ba2b 100644 --- a/sdk/newrelicobservability/azure-resourcemanager-newrelicobservability/README.md +++ b/sdk/newrelicobservability/azure-resourcemanager-newrelicobservability/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-newrelicobservability - 1.2.0 + 1.3.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fnewrelicobservability%2Fazure-resourcemanager-newrelicobservability%2FREADME.png) + diff --git a/sdk/newrelicobservability/azure-resourcemanager-newrelicobservability/pom.xml b/sdk/newrelicobservability/azure-resourcemanager-newrelicobservability/pom.xml index 16d98481b8d7..ed968e9ff6c5 100644 --- a/sdk/newrelicobservability/azure-resourcemanager-newrelicobservability/pom.xml +++ b/sdk/newrelicobservability/azure-resourcemanager-newrelicobservability/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/nginx/azure-resourcemanager-nginx/CHANGELOG.md b/sdk/nginx/azure-resourcemanager-nginx/CHANGELOG.md index 1ade1ea4df11..6023bd0fb9f0 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/CHANGELOG.md +++ b/sdk/nginx/azure-resourcemanager-nginx/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.1.0-beta.3 (Unreleased) +## 1.1.0-beta.4 (Unreleased) ### Features Added @@ -10,6 +10,117 @@ ### Other Changes +## 1.1.0-beta.3 (2025-02-26) + +- Azure Resource Manager Nginx client library for Java. This package contains Microsoft Azure SDK for Nginx Management SDK. Package tag package-2024-11-01-preview. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). + +### Breaking Changes + +#### `models.NginxConfiguration` was removed + +#### `models.NginxConfiguration$Update` was removed + +#### `models.NginxConfiguration$Definition` was removed + +#### `models.NginxConfiguration$DefinitionStages` was removed + +#### `models.NginxConfiguration$UpdateStages` was removed + +#### `models.NginxConfigurationProperties` was removed + +#### `models.NginxDeploymentProperties` was modified + +* `managedResourceGroup()` was removed +* `withManagedResourceGroup(java.lang.String)` was removed + +#### `models.Configurations` was modified + +* `models.NginxConfiguration getById(java.lang.String)` -> `models.NginxConfigurationResponse getById(java.lang.String)` +* `models.NginxConfiguration$DefinitionStages$Blank define(java.lang.String)` -> `models.NginxConfigurationResponse$DefinitionStages$Blank define(java.lang.String)` +* `models.NginxConfiguration get(java.lang.String,java.lang.String,java.lang.String)` -> `models.NginxConfigurationResponse get(java.lang.String,java.lang.String,java.lang.String)` + +### Features Added + +* `models.NginxConfigurationResponse$Update` was added + +* `models.WebApplicationFirewallSettings` was added + +* `models.NginxDeploymentApiKeyResponse$Definition` was added + +* `models.NginxDeploymentApiKeyResponse$DefinitionStages` was added + +* `models.NginxConfigurationResponse$UpdateStages` was added + +* `models.NginxConfigurationResponse$Definition` was added + +* `models.Level` was added + +* `models.DiagnosticItem` was added + +* `models.ActivationState` was added + +* `models.NginxDeploymentApiKeyListResponse` was added + +* `models.NginxDeploymentApiKeyResponse$Update` was added + +* `models.NginxDeploymentApiKeyRequest` was added + +* `models.NginxConfigurationRequestProperties` was added + +* `models.NginxDeploymentApiKeyResponse` was added + +* `models.NginxConfigurationResponseProperties` was added + +* `models.NginxConfigurationRequest` was added + +* `models.NginxDeploymentApiKeyResponseProperties` was added + +* `models.NginxDeploymentPropertiesNginxAppProtect` was added + +* `models.WebApplicationFirewallComponentVersions` was added + +* `models.NginxConfigurationProtectedFileRequest` was added + +* `models.WebApplicationFirewallStatus` was added + +* `models.NginxConfigurationResponse$DefinitionStages` was added + +* `models.NginxDeploymentApiKeyResponse$UpdateStages` was added + +* `models.WebApplicationFirewallPackage` was added + +* `models.ApiKeys` was added + +* `models.NginxDeploymentUpdatePropertiesNginxAppProtect` was added + +* `models.NginxConfigurationResponse` was added + +* `models.NginxConfigurationProtectedFileResponse` was added + +* `models.NginxDeploymentApiKeyRequestProperties` was added + +#### `models.NginxDeploymentUpdateProperties` was modified + +* `withNginxAppProtect(models.NginxDeploymentUpdatePropertiesNginxAppProtect)` was added +* `nginxAppProtect()` was added +* `networkProfile()` was added +* `withNetworkProfile(models.NginxNetworkProfile)` was added + +#### `models.NginxDeploymentProperties` was modified + +* `withNginxAppProtect(models.NginxDeploymentPropertiesNginxAppProtect)` was added +* `nginxAppProtect()` was added +* `dataplaneApiEndpoint()` was added + +#### `models.AnalysisResultData` was modified + +* `diagnostics()` was added +* `withDiagnostics(java.util.List)` was added + +#### `NginxManager` was modified + +* `apiKeys()` was added + ## 1.1.0-beta.2 (2024-12-04) - Azure Resource Manager Nginx client library for Java. This package contains Microsoft Azure SDK for Nginx Management SDK. Package tag package-2024-01-01-preview. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). diff --git a/sdk/nginx/azure-resourcemanager-nginx/README.md b/sdk/nginx/azure-resourcemanager-nginx/README.md index 3ebf641b02a7..a4cef05c1551 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/README.md +++ b/sdk/nginx/azure-resourcemanager-nginx/README.md @@ -2,7 +2,7 @@ Azure Resource Manager Nginx client library for Java. -This package contains Microsoft Azure SDK for Nginx Management SDK. Package tag package-2024-01-01-preview. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). +This package contains Microsoft Azure SDK for Nginx Management SDK. Package tag package-2024-11-01-preview. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). ## We'd love to hear your feedback @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-nginx - 1.1.0-beta.2 + 1.1.0-beta.4 ``` [//]: # ({x-version-update-end}) @@ -52,7 +52,7 @@ Azure subscription ID can be configured via `AZURE_SUBSCRIPTION_ID` environment Assuming the use of the `DefaultAzureCredential` credential class, the client can be authenticated using the following code: ```java -AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); +AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); @@ -60,7 +60,7 @@ NginxManager manager = NginxManager .authenticate(credential, profile); ``` -The sample code assumes global Azure. Please change `AzureEnvironment.AZURE` variable if otherwise. +The sample code assumes global Azure. Please change the `AzureCloud.AZURE_PUBLIC_CLOUD` variable if otherwise. See [Authentication][authenticate] for more options. @@ -100,5 +100,3 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [cg]: https://github.com/Azure/azure-sdk-for-java/blob/main/CONTRIBUTING.md [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ - -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fnginx%2Fazure-resourcemanager-nginx%2FREADME.png) diff --git a/sdk/nginx/azure-resourcemanager-nginx/SAMPLE.md b/sdk/nginx/azure-resourcemanager-nginx/SAMPLE.md index dc23dfe29db8..690718f9390c 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/SAMPLE.md +++ b/sdk/nginx/azure-resourcemanager-nginx/SAMPLE.md @@ -1,6 +1,13 @@ # Code snippets and samples +## ApiKeys + +- [CreateOrUpdate](#apikeys_createorupdate) +- [Delete](#apikeys_delete) +- [Get](#apikeys_get) +- [List](#apikeys_list) + ## Certificates - [CreateOrUpdate](#certificates_createorupdate) @@ -28,17 +35,106 @@ ## Operations - [List](#operations_list) -### Certificates_CreateOrUpdate +### ApiKeys_CreateOrUpdate + +```java +/** + * Samples for ApiKeys CreateOrUpdate. + */ +public final class ApiKeysCreateOrUpdateSamples { + /* + * x-ms-original-file: + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/ApiKeys_CreateOrUpdate. + * json + */ + /** + * Sample code: ApiKeys_CreateOrUpdate. + * + * @param manager Entry point to NginxManager. + */ + public static void apiKeysCreateOrUpdate(com.azure.resourcemanager.nginx.NginxManager manager) { + manager.apiKeys().define("myApiKey").withExistingNginxDeployment("myResourceGroup", "myDeployment").create(); + } +} +``` + +### ApiKeys_Delete + +```java +/** + * Samples for ApiKeys Delete. + */ +public final class ApiKeysDeleteSamples { + /* + * x-ms-original-file: + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/ApiKeys_Delete.json + */ + /** + * Sample code: ApiKeys_Delete. + * + * @param manager Entry point to NginxManager. + */ + public static void apiKeysDelete(com.azure.resourcemanager.nginx.NginxManager manager) { + manager.apiKeys() + .deleteWithResponse("myResourceGroup", "myDeployment", "myApiKey", com.azure.core.util.Context.NONE); + } +} +``` + +### ApiKeys_Get + +```java +/** + * Samples for ApiKeys Get. + */ +public final class ApiKeysGetSamples { + /* + * x-ms-original-file: + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/ApiKeys_Get.json + */ + /** + * Sample code: ApiKeys_Get. + * + * @param manager Entry point to NginxManager. + */ + public static void apiKeysGet(com.azure.resourcemanager.nginx.NginxManager manager) { + manager.apiKeys() + .getWithResponse("myResourceGroup", "myDeployment", "myApiKey", com.azure.core.util.Context.NONE); + } +} +``` + +### ApiKeys_List ```java -import com.azure.resourcemanager.nginx.models.NginxCertificateProperties; +/** + * Samples for ApiKeys List. + */ +public final class ApiKeysListSamples { + /* + * x-ms-original-file: + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/ApiKeys_List.json + */ + /** + * Sample code: ApiKeys_List. + * + * @param manager Entry point to NginxManager. + */ + public static void apiKeysList(com.azure.resourcemanager.nginx.NginxManager manager) { + manager.apiKeys().list("myResourceGroup", "myDeployment", com.azure.core.util.Context.NONE); + } +} +``` +### Certificates_CreateOrUpdate + +```java /** * Samples for Certificates CreateOrUpdate. */ public final class CertificatesCreateOrUpdateSamples { /* - * x-ms-original-file: specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/ + * x-ms-original-file: specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/ * Certificates_CreateOrUpdate.json */ /** @@ -50,9 +146,6 @@ public final class CertificatesCreateOrUpdateSamples { manager.certificates() .define("default") .withExistingNginxDeployment("myResourceGroup", "myDeployment") - .withProperties(new NginxCertificateProperties().withKeyVirtualPath("fakeTokenPlaceholder") - .withCertificateVirtualPath("/src/cert/somePath.cert") - .withKeyVaultSecretId("fakeTokenPlaceholder")) .create(); } } @@ -67,7 +160,7 @@ public final class CertificatesCreateOrUpdateSamples { public final class CertificatesDeleteSamples { /* * x-ms-original-file: - * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/Certificates_Delete.json + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/Certificates_Delete.json */ /** * Sample code: Certificates_Delete. @@ -89,7 +182,7 @@ public final class CertificatesDeleteSamples { public final class CertificatesGetSamples { /* * x-ms-original-file: - * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/Certificates_Get.json + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/Certificates_Get.json */ /** * Sample code: Certificates_Get. @@ -112,7 +205,7 @@ public final class CertificatesGetSamples { public final class CertificatesListSamples { /* * x-ms-original-file: - * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/Certificates_List.json + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/Certificates_List.json */ /** * Sample code: Certificates_List. @@ -128,11 +221,6 @@ public final class CertificatesListSamples { ### Configurations_Analysis ```java -import com.azure.resourcemanager.nginx.models.AnalysisCreate; -import com.azure.resourcemanager.nginx.models.AnalysisCreateConfig; -import com.azure.resourcemanager.nginx.models.NginxConfigurationFile; -import com.azure.resourcemanager.nginx.models.NginxConfigurationPackage; -import java.util.Arrays; /** * Samples for Configurations Analysis. @@ -140,7 +228,7 @@ import java.util.Arrays; public final class ConfigurationsAnalysisSamples { /* * x-ms-original-file: - * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/Configurations_Analysis. + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/Configurations_Analysis. * json */ /** @@ -150,12 +238,7 @@ public final class ConfigurationsAnalysisSamples { */ public static void configurationsAnalysis(com.azure.resourcemanager.nginx.NginxManager manager) { manager.configurations() - .analysisWithResponse("myResourceGroup", "myDeployment", "default", - new AnalysisCreate().withConfig(new AnalysisCreateConfig().withRootFile("/etc/nginx/nginx.conf") - .withFiles(Arrays.asList( - new NginxConfigurationFile().withContent("ABCDEF==").withVirtualPath("/etc/nginx/nginx.conf"))) - .withPackageProperty(new NginxConfigurationPackage())), - com.azure.core.util.Context.NONE); + .analysisWithResponse("myResourceGroup", "myDeployment", "default", null, com.azure.core.util.Context.NONE); } } ``` @@ -163,17 +246,12 @@ public final class ConfigurationsAnalysisSamples { ### Configurations_CreateOrUpdate ```java -import com.azure.resourcemanager.nginx.models.NginxConfigurationFile; -import com.azure.resourcemanager.nginx.models.NginxConfigurationPackage; -import com.azure.resourcemanager.nginx.models.NginxConfigurationProperties; -import java.util.Arrays; - /** * Samples for Configurations CreateOrUpdate. */ public final class ConfigurationsCreateOrUpdateSamples { /* - * x-ms-original-file: specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/ + * x-ms-original-file: specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/ * Configurations_CreateOrUpdate.json */ /** @@ -185,11 +263,6 @@ public final class ConfigurationsCreateOrUpdateSamples { manager.configurations() .define("default") .withExistingNginxDeployment("myResourceGroup", "myDeployment") - .withProperties(new NginxConfigurationProperties() - .withFiles(Arrays.asList( - new NginxConfigurationFile().withContent("ABCDEF==").withVirtualPath("/etc/nginx/nginx.conf"))) - .withPackageProperty(new NginxConfigurationPackage()) - .withRootFile("/etc/nginx/nginx.conf")) .create(); } } @@ -204,7 +277,7 @@ public final class ConfigurationsCreateOrUpdateSamples { public final class ConfigurationsDeleteSamples { /* * x-ms-original-file: - * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/Configurations_Delete. + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/Configurations_Delete. * json */ /** @@ -227,7 +300,7 @@ public final class ConfigurationsDeleteSamples { public final class ConfigurationsGetSamples { /* * x-ms-original-file: - * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/Configurations_Get.json + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/Configurations_Get.json */ /** * Sample code: Configurations_Get. @@ -250,7 +323,7 @@ public final class ConfigurationsGetSamples { public final class ConfigurationsListSamples { /* * x-ms-original-file: - * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/Configurations_List.json + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/Configurations_List.json */ /** * Sample code: Configurations_List. @@ -266,27 +339,13 @@ public final class ConfigurationsListSamples { ### Deployments_CreateOrUpdate ```java -import com.azure.resourcemanager.nginx.models.AutoUpgradeProfile; -import com.azure.resourcemanager.nginx.models.NginxDeploymentProperties; -import com.azure.resourcemanager.nginx.models.NginxDeploymentScalingProperties; -import com.azure.resourcemanager.nginx.models.NginxDeploymentUserProfile; -import com.azure.resourcemanager.nginx.models.NginxFrontendIpConfiguration; -import com.azure.resourcemanager.nginx.models.NginxNetworkInterfaceConfiguration; -import com.azure.resourcemanager.nginx.models.NginxNetworkProfile; -import com.azure.resourcemanager.nginx.models.NginxPrivateIpAddress; -import com.azure.resourcemanager.nginx.models.NginxPrivateIpAllocationMethod; -import com.azure.resourcemanager.nginx.models.NginxPublicIpAddress; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - /** * Samples for Deployments CreateOrUpdate. */ public final class DeploymentsCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/Deployments_Create.json + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/Deployments_Create.json */ /** * Sample code: Deployments_Create. @@ -296,38 +355,10 @@ public final class DeploymentsCreateOrUpdateSamples { public static void deploymentsCreate(com.azure.resourcemanager.nginx.NginxManager manager) { manager.deployments() .define("myDeployment") - .withRegion("West US") + .withRegion((String) null) .withExistingResourceGroup("myResourceGroup") - .withTags(mapOf("Environment", "Dev")) - .withProperties(new NginxDeploymentProperties().withManagedResourceGroup("myManagedResourceGroup") - .withNetworkProfile(new NginxNetworkProfile() - .withFrontEndIpConfiguration(new NginxFrontendIpConfiguration() - .withPublicIpAddresses(Arrays.asList(new NginxPublicIpAddress().withId( - "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Network/publicIPAddresses/myPublicIPAddress"))) - .withPrivateIpAddresses(Arrays.asList(new NginxPrivateIpAddress() - .withPrivateIpAddress("1.1.1.1") - .withPrivateIpAllocationMethod(NginxPrivateIpAllocationMethod.STATIC) - .withSubnetId( - "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/myVnet/subnets/mySubnet")))) - .withNetworkInterfaceConfiguration(new NginxNetworkInterfaceConfiguration().withSubnetId( - "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/myVnet/subnets/mySubnet"))) - .withScalingProperties(new NginxDeploymentScalingProperties().withCapacity(10)) - .withAutoUpgradeProfile(new AutoUpgradeProfile().withUpgradeChannel("stable")) - .withUserProfile(new NginxDeploymentUserProfile().withPreferredEmail("example@example.email"))) .create(); } - - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; - } } ``` @@ -340,7 +371,7 @@ public final class DeploymentsCreateOrUpdateSamples { public final class DeploymentsDeleteSamples { /* * x-ms-original-file: - * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/Deployments_Delete.json + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/Deployments_Delete.json */ /** * Sample code: Deployments_Delete. @@ -362,7 +393,7 @@ public final class DeploymentsDeleteSamples { public final class DeploymentsGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/Deployments_Get.json + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/Deployments_Get.json */ /** * Sample code: Deployments_Get. @@ -375,7 +406,7 @@ public final class DeploymentsGetByResourceGroupSamples { } /* - * x-ms-original-file: specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/ + * x-ms-original-file: specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/ * Deployments_Get_AutoScale.json */ /** @@ -399,7 +430,7 @@ public final class DeploymentsGetByResourceGroupSamples { public final class DeploymentsListSamples { /* * x-ms-original-file: - * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/Deployments_List.json + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/Deployments_List.json */ /** * Sample code: Deployments_List. @@ -420,7 +451,7 @@ public final class DeploymentsListSamples { */ public final class DeploymentsListByResourceGroupSamples { /* - * x-ms-original-file: specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/ + * x-ms-original-file: specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/ * Deployments_ListByResourceGroup.json */ /** @@ -438,8 +469,6 @@ public final class DeploymentsListByResourceGroupSamples { ```java import com.azure.resourcemanager.nginx.models.NginxDeployment; -import java.util.HashMap; -import java.util.Map; /** * Samples for Deployments Update. @@ -447,7 +476,7 @@ import java.util.Map; public final class DeploymentsUpdateSamples { /* * x-ms-original-file: - * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/Deployments_Update.json + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/Deployments_Update.json */ /** * Sample code: Deployments_Update. @@ -458,19 +487,24 @@ public final class DeploymentsUpdateSamples { NginxDeployment resource = manager.deployments() .getByResourceGroupWithResponse("myResourceGroup", "myDeployment", com.azure.core.util.Context.NONE) .getValue(); - resource.update().withTags(mapOf("Environment", "Dev")).apply(); + resource.update().apply(); } - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; + /* + * x-ms-original-file: + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/Deployments_UpdateSubnet + * .json + */ + /** + * Sample code: Deployments_UpdateSubnet. + * + * @param manager Entry point to NginxManager. + */ + public static void deploymentsUpdateSubnet(com.azure.resourcemanager.nginx.NginxManager manager) { + NginxDeployment resource = manager.deployments() + .getByResourceGroupWithResponse("myResourceGroup", "myDeployment", com.azure.core.util.Context.NONE) + .getValue(); + resource.update().apply(); } } ``` @@ -484,7 +518,7 @@ public final class DeploymentsUpdateSamples { public final class OperationsListSamples { /* * x-ms-original-file: - * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/Operations_List.json + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/Operations_List.json */ /** * Sample code: Operations_List. diff --git a/sdk/nginx/azure-resourcemanager-nginx/pom.xml b/sdk/nginx/azure-resourcemanager-nginx/pom.xml index d5997459b15a..a913bc594f0d 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/pom.xml +++ b/sdk/nginx/azure-resourcemanager-nginx/pom.xml @@ -14,11 +14,11 @@ com.azure.resourcemanager azure-resourcemanager-nginx - 1.1.0-beta.3 + 1.1.0-beta.4 jar Microsoft Azure SDK for Nginx Management - This package contains Microsoft Azure SDK for Nginx Management SDK. For documentation on how to use this package, please see https://aka.ms/azsdk/java/mgmt. Package tag package-2024-01-01-preview. + This package contains Microsoft Azure SDK for Nginx Management SDK. For documentation on how to use this package, please see https://aka.ms/azsdk/java/mgmt. Package tag package-2024-11-01-preview. https://github.com/Azure/azure-sdk-for-java @@ -52,23 +52,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/NginxManager.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/NginxManager.java index 03932ba78692..663857029f3a 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/NginxManager.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/NginxManager.java @@ -22,13 +22,16 @@ import com.azure.core.http.policy.UserAgentPolicy; import com.azure.core.management.profile.AzureProfile; import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.nginx.fluent.NginxManagementClient; +import com.azure.resourcemanager.nginx.implementation.ApiKeysImpl; import com.azure.resourcemanager.nginx.implementation.CertificatesImpl; import com.azure.resourcemanager.nginx.implementation.ConfigurationsImpl; import com.azure.resourcemanager.nginx.implementation.DeploymentsImpl; import com.azure.resourcemanager.nginx.implementation.NginxManagementClientBuilder; import com.azure.resourcemanager.nginx.implementation.OperationsImpl; +import com.azure.resourcemanager.nginx.models.ApiKeys; import com.azure.resourcemanager.nginx.models.Certificates; import com.azure.resourcemanager.nginx.models.Configurations; import com.azure.resourcemanager.nginx.models.Deployments; @@ -37,6 +40,7 @@ import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; @@ -44,6 +48,8 @@ * Entry point to NginxManager. */ public final class NginxManager { + private ApiKeys apiKeys; + private Certificates certificates; private Configurations configurations; @@ -104,6 +110,9 @@ public static Configurable configure() { */ public static final class Configurable { private static final ClientLogger LOGGER = new ClientLogger(Configurable.class); + private static final String SDK_VERSION = "version"; + private static final Map PROPERTIES + = CoreUtils.getProperties("azure-resourcemanager-nginx.properties"); private HttpClient httpClient; private HttpLogOptions httpLogOptions; @@ -211,12 +220,14 @@ public NginxManager authenticate(TokenCredential credential, AzureProfile profil Objects.requireNonNull(credential, "'credential' cannot be null."); Objects.requireNonNull(profile, "'profile' cannot be null."); + String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); + StringBuilder userAgentBuilder = new StringBuilder(); userAgentBuilder.append("azsdk-java") .append("-") .append("com.azure.resourcemanager.nginx") .append("/") - .append("1.1.0-beta.2"); + .append(clientVersion); if (!Configuration.getGlobalConfiguration().get("AZURE_TELEMETRY_DISABLED", false)) { userAgentBuilder.append(" (") .append(Configuration.getGlobalConfiguration().get("java.version")) @@ -262,6 +273,18 @@ public NginxManager authenticate(TokenCredential credential, AzureProfile profil } } + /** + * Gets the resource collection API of ApiKeys. It manages NginxDeploymentApiKeyResponse. + * + * @return Resource collection API of ApiKeys. + */ + public ApiKeys apiKeys() { + if (this.apiKeys == null) { + this.apiKeys = new ApiKeysImpl(clientObject.getApiKeys(), this); + } + return apiKeys; + } + /** * Gets the resource collection API of Certificates. It manages NginxCertificate. * @@ -275,7 +298,7 @@ public Certificates certificates() { } /** - * Gets the resource collection API of Configurations. It manages NginxConfiguration. + * Gets the resource collection API of Configurations. It manages NginxConfigurationResponse. * * @return Resource collection API of Configurations. */ diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/fluent/ApiKeysClient.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/fluent/ApiKeysClient.java new file mode 100644 index 000000000000..ce0eef06bc5a --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/fluent/ApiKeysClient.java @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.resourcemanager.nginx.fluent.models.NginxDeploymentApiKeyResponseInner; +import com.azure.resourcemanager.nginx.models.NginxDeploymentApiKeyRequest; + +/** + * An instance of this class provides access to all the operations defined in ApiKeysClient. + */ +public interface ApiKeysClient { + /** + * Create or update an API Key for the Nginx deployment in order to access the dataplane API endpoint. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param apiKeyName The resource name of the API key. + * @param body The API Key object containing fields (e.g. secret text, expiration date) to upsert the key. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response createOrUpdateWithResponse(String resourceGroupName, + String deploymentName, String apiKeyName, NginxDeploymentApiKeyRequest body, Context context); + + /** + * Create or update an API Key for the Nginx deployment in order to access the dataplane API endpoint. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param apiKeyName The resource name of the API key. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + NginxDeploymentApiKeyResponseInner createOrUpdate(String resourceGroupName, String deploymentName, + String apiKeyName); + + /** + * Delete API key for Nginx deployment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param apiKeyName The resource name of the API key. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response deleteWithResponse(String resourceGroupName, String deploymentName, String apiKeyName, + Context context); + + /** + * Delete API key for Nginx deployment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param apiKeyName The resource name of the API key. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void delete(String resourceGroupName, String deploymentName, String apiKeyName); + + /** + * Get the specified API Key of the given Nginx deployment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param apiKeyName The resource name of the API key. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the specified API Key of the given Nginx deployment along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String resourceGroupName, String deploymentName, + String apiKeyName, Context context); + + /** + * Get the specified API Key of the given Nginx deployment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param apiKeyName The resource name of the API key. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the specified API Key of the given Nginx deployment. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + NginxDeploymentApiKeyResponseInner get(String resourceGroupName, String deploymentName, String apiKeyName); + + /** + * List all API Keys of the given Nginx deployment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(String resourceGroupName, String deploymentName); + + /** + * List all API Keys of the given Nginx deployment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(String resourceGroupName, String deploymentName, + Context context); +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/fluent/ConfigurationsClient.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/fluent/ConfigurationsClient.java index 449060113289..3cfa48548954 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/fluent/ConfigurationsClient.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/fluent/ConfigurationsClient.java @@ -12,8 +12,9 @@ import com.azure.core.util.Context; import com.azure.core.util.polling.SyncPoller; import com.azure.resourcemanager.nginx.fluent.models.AnalysisResultInner; -import com.azure.resourcemanager.nginx.fluent.models.NginxConfigurationInner; +import com.azure.resourcemanager.nginx.fluent.models.NginxConfigurationResponseInner; import com.azure.resourcemanager.nginx.models.AnalysisCreate; +import com.azure.resourcemanager.nginx.models.NginxConfigurationRequest; /** * An instance of this class provides access to all the operations defined in ConfigurationsClient. @@ -30,7 +31,7 @@ public interface ConfigurationsClient { * @return response of a list operation as paginated response with {@link PagedIterable}. */ @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable list(String resourceGroupName, String deploymentName); + PagedIterable list(String resourceGroupName, String deploymentName); /** * List the NGINX configuration of given NGINX deployment. @@ -44,7 +45,8 @@ public interface ConfigurationsClient { * @return response of a list operation as paginated response with {@link PagedIterable}. */ @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable list(String resourceGroupName, String deploymentName, Context context); + PagedIterable list(String resourceGroupName, String deploymentName, + Context context); /** * Get the NGINX configuration of given NGINX deployment. @@ -60,7 +62,7 @@ public interface ConfigurationsClient { * @return the NGINX configuration of given NGINX deployment along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - Response getWithResponse(String resourceGroupName, String deploymentName, + Response getWithResponse(String resourceGroupName, String deploymentName, String configurationName, Context context); /** @@ -76,7 +78,7 @@ Response getWithResponse(String resourceGroupName, Stri * @return the NGINX configuration of given NGINX deployment. */ @ServiceMethod(returns = ReturnType.SINGLE) - NginxConfigurationInner get(String resourceGroupName, String deploymentName, String configurationName); + NginxConfigurationResponseInner get(String resourceGroupName, String deploymentName, String configurationName); /** * Create or update the NGINX configuration for given NGINX deployment. @@ -91,7 +93,7 @@ Response getWithResponse(String resourceGroupName, Stri * @return the {@link SyncPoller} for polling of long-running operation. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, NginxConfigurationInner> + SyncPoller, NginxConfigurationResponseInner> beginCreateOrUpdate(String resourceGroupName, String deploymentName, String configurationName); /** @@ -109,8 +111,8 @@ Response getWithResponse(String resourceGroupName, Stri * @return the {@link SyncPoller} for polling of long-running operation. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, NginxConfigurationInner> beginCreateOrUpdate( - String resourceGroupName, String deploymentName, String configurationName, NginxConfigurationInner body, + SyncPoller, NginxConfigurationResponseInner> beginCreateOrUpdate( + String resourceGroupName, String deploymentName, String configurationName, NginxConfigurationRequest body, Context context); /** @@ -126,7 +128,8 @@ SyncPoller, NginxConfigurationInner> beginCr * @return the response. */ @ServiceMethod(returns = ReturnType.SINGLE) - NginxConfigurationInner createOrUpdate(String resourceGroupName, String deploymentName, String configurationName); + NginxConfigurationResponseInner createOrUpdate(String resourceGroupName, String deploymentName, + String configurationName); /** * Create or update the NGINX configuration for given NGINX deployment. @@ -143,8 +146,8 @@ SyncPoller, NginxConfigurationInner> beginCr * @return the response. */ @ServiceMethod(returns = ReturnType.SINGLE) - NginxConfigurationInner createOrUpdate(String resourceGroupName, String deploymentName, String configurationName, - NginxConfigurationInner body, Context context); + NginxConfigurationResponseInner createOrUpdate(String resourceGroupName, String deploymentName, + String configurationName, NginxConfigurationRequest body, Context context); /** * Reset the NGINX configuration of given NGINX deployment to default. diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/fluent/NginxManagementClient.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/fluent/NginxManagementClient.java index 68df3fc3de5a..61c60ad89dff 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/fluent/NginxManagementClient.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/fluent/NginxManagementClient.java @@ -12,7 +12,7 @@ */ public interface NginxManagementClient { /** - * Gets The ID of the target subscription. + * Gets The ID of the target subscription. The value must be an UUID. * * @return the subscriptionId value. */ @@ -46,6 +46,13 @@ public interface NginxManagementClient { */ Duration getDefaultPollInterval(); + /** + * Gets the ApiKeysClient object to access its operations. + * + * @return the ApiKeysClient object. + */ + ApiKeysClient getApiKeys(); + /** * Gets the CertificatesClient object to access its operations. * diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/fluent/OperationsClient.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/fluent/OperationsClient.java index 63a12124e50d..1613e2f07bea 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/fluent/OperationsClient.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/fluent/OperationsClient.java @@ -15,7 +15,7 @@ */ public interface OperationsClient { /** - * List all operations provided by Nginx.NginxPlus for the 2024-01-01-preview api version. + * List all operations provided by Nginx.NginxPlus for the 2024-11-01-preview api version. * * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -26,7 +26,7 @@ public interface OperationsClient { PagedIterable list(); /** - * List all operations provided by Nginx.NginxPlus for the 2024-01-01-preview api version. + * List all operations provided by Nginx.NginxPlus for the 2024-11-01-preview api version. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/fluent/models/NginxConfigurationInner.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/fluent/models/NginxConfigurationInner.java deleted file mode 100644 index d7deaf862a12..000000000000 --- a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/fluent/models/NginxConfigurationInner.java +++ /dev/null @@ -1,194 +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.resourcemanager.nginx.fluent.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.management.ProxyResource; -import com.azure.core.management.SystemData; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.resourcemanager.nginx.models.NginxConfigurationProperties; -import java.io.IOException; - -/** - * The NginxConfiguration model. - */ -@Fluent -public final class NginxConfigurationInner extends ProxyResource { - /* - * The properties property. - */ - private NginxConfigurationProperties properties; - - /* - * The location property. - */ - private String location; - - /* - * Metadata pertaining to creation and last modification of the resource. - */ - private SystemData systemData; - - /* - * The type of the resource. - */ - private String type; - - /* - * The name of the resource. - */ - private String name; - - /* - * Fully qualified resource Id for the resource. - */ - private String id; - - /** - * Creates an instance of NginxConfigurationInner class. - */ - public NginxConfigurationInner() { - } - - /** - * Get the properties property: The properties property. - * - * @return the properties value. - */ - public NginxConfigurationProperties properties() { - return this.properties; - } - - /** - * Set the properties property: The properties property. - * - * @param properties the properties value to set. - * @return the NginxConfigurationInner object itself. - */ - public NginxConfigurationInner withProperties(NginxConfigurationProperties properties) { - this.properties = properties; - return this; - } - - /** - * Get the location property: The location property. - * - * @return the location value. - */ - public String location() { - return this.location; - } - - /** - * Set the location property: The location property. - * - * @param location the location value to set. - * @return the NginxConfigurationInner object itself. - */ - public NginxConfigurationInner withLocation(String location) { - this.location = location; - return this; - } - - /** - * Get the systemData property: Metadata pertaining to creation and last modification of the resource. - * - * @return the systemData value. - */ - public SystemData systemData() { - return this.systemData; - } - - /** - * Get the type property: The type of the resource. - * - * @return the type value. - */ - @Override - public String type() { - return this.type; - } - - /** - * Get the name property: The name of the resource. - * - * @return the name value. - */ - @Override - public String name() { - return this.name; - } - - /** - * Get the id property: Fully qualified resource Id for the resource. - * - * @return the id value. - */ - @Override - public String id() { - return this.id; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (properties() != null) { - properties().validate(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeJsonField("properties", this.properties); - jsonWriter.writeStringField("location", this.location); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of NginxConfigurationInner from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of NginxConfigurationInner 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 NginxConfigurationInner. - */ - public static NginxConfigurationInner fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - NginxConfigurationInner deserializedNginxConfigurationInner = new NginxConfigurationInner(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("id".equals(fieldName)) { - deserializedNginxConfigurationInner.id = reader.getString(); - } else if ("name".equals(fieldName)) { - deserializedNginxConfigurationInner.name = reader.getString(); - } else if ("type".equals(fieldName)) { - deserializedNginxConfigurationInner.type = reader.getString(); - } else if ("properties".equals(fieldName)) { - deserializedNginxConfigurationInner.properties = NginxConfigurationProperties.fromJson(reader); - } else if ("location".equals(fieldName)) { - deserializedNginxConfigurationInner.location = reader.getString(); - } else if ("systemData".equals(fieldName)) { - deserializedNginxConfigurationInner.systemData = SystemData.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedNginxConfigurationInner; - }); - } -} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/fluent/models/NginxConfigurationResponseInner.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/fluent/models/NginxConfigurationResponseInner.java new file mode 100644 index 000000000000..cc1ab7dd7cde --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/fluent/models/NginxConfigurationResponseInner.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. + +package com.azure.resourcemanager.nginx.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.nginx.models.NginxConfigurationResponseProperties; +import java.io.IOException; + +/** + * The NginxConfigurationResponse model. + */ +@Fluent +public final class NginxConfigurationResponseInner extends ProxyResource { + /* + * The properties property. + */ + private NginxConfigurationResponseProperties properties; + + /* + * Metadata pertaining to creation and last modification of the resource. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of NginxConfigurationResponseInner class. + */ + public NginxConfigurationResponseInner() { + } + + /** + * Get the properties property: The properties property. + * + * @return the properties value. + */ + public NginxConfigurationResponseProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The properties property. + * + * @param properties the properties value to set. + * @return the NginxConfigurationResponseInner object itself. + */ + public NginxConfigurationResponseInner withProperties(NginxConfigurationResponseProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Metadata pertaining to creation and last modification of the resource. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of NginxConfigurationResponseInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of NginxConfigurationResponseInner 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 NginxConfigurationResponseInner. + */ + public static NginxConfigurationResponseInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + NginxConfigurationResponseInner deserializedNginxConfigurationResponseInner + = new NginxConfigurationResponseInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedNginxConfigurationResponseInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedNginxConfigurationResponseInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedNginxConfigurationResponseInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedNginxConfigurationResponseInner.properties + = NginxConfigurationResponseProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedNginxConfigurationResponseInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedNginxConfigurationResponseInner; + }); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/fluent/models/NginxDeploymentApiKeyResponseInner.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/fluent/models/NginxDeploymentApiKeyResponseInner.java new file mode 100644 index 000000000000..12805d1b8293 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/fluent/models/NginxDeploymentApiKeyResponseInner.java @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.nginx.models.NginxDeploymentApiKeyResponseProperties; +import java.io.IOException; + +/** + * The NginxDeploymentApiKeyResponse model. + */ +@Fluent +public final class NginxDeploymentApiKeyResponseInner extends ProxyResource { + /* + * The properties property. + */ + private NginxDeploymentApiKeyResponseProperties properties; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of NginxDeploymentApiKeyResponseInner class. + */ + public NginxDeploymentApiKeyResponseInner() { + } + + /** + * Get the properties property: The properties property. + * + * @return the properties value. + */ + public NginxDeploymentApiKeyResponseProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The properties property. + * + * @param properties the properties value to set. + * @return the NginxDeploymentApiKeyResponseInner object itself. + */ + public NginxDeploymentApiKeyResponseInner withProperties(NginxDeploymentApiKeyResponseProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of NginxDeploymentApiKeyResponseInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of NginxDeploymentApiKeyResponseInner 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 NginxDeploymentApiKeyResponseInner. + */ + public static NginxDeploymentApiKeyResponseInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + NginxDeploymentApiKeyResponseInner deserializedNginxDeploymentApiKeyResponseInner + = new NginxDeploymentApiKeyResponseInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedNginxDeploymentApiKeyResponseInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedNginxDeploymentApiKeyResponseInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedNginxDeploymentApiKeyResponseInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedNginxDeploymentApiKeyResponseInner.properties + = NginxDeploymentApiKeyResponseProperties.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedNginxDeploymentApiKeyResponseInner; + }); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/ApiKeysClientImpl.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/ApiKeysClientImpl.java new file mode 100644 index 000000000000..d7bedf8a4f91 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/ApiKeysClientImpl.java @@ -0,0 +1,712 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Put; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.resourcemanager.nginx.fluent.ApiKeysClient; +import com.azure.resourcemanager.nginx.fluent.models.NginxDeploymentApiKeyResponseInner; +import com.azure.resourcemanager.nginx.models.NginxDeploymentApiKeyListResponse; +import com.azure.resourcemanager.nginx.models.NginxDeploymentApiKeyRequest; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in ApiKeysClient. + */ +public final class ApiKeysClientImpl implements ApiKeysClient { + /** + * The proxy service used to perform REST calls. + */ + private final ApiKeysService service; + + /** + * The service client containing this operation class. + */ + private final NginxManagementClientImpl client; + + /** + * Initializes an instance of ApiKeysClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + ApiKeysClientImpl(NginxManagementClientImpl client) { + this.service = RestProxy.create(ApiKeysService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for NginxManagementClientApiKeys to be used by the proxy service to + * perform REST calls. + */ + @Host("{$host}") + @ServiceInterface(name = "NginxManagementClien") + public interface ApiKeysService { + @Headers({ "Content-Type: application/json" }) + @Put("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Nginx.NginxPlus/nginxDeployments/{deploymentName}/apiKeys/{apiKeyName}") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> createOrUpdate(@HostParam("$host") String endpoint, + @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, + @PathParam("deploymentName") String deploymentName, @PathParam("apiKeyName") String apiKeyName, + @QueryParam("api-version") String apiVersion, + @BodyParam("application/json") NginxDeploymentApiKeyRequest body, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Delete("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Nginx.NginxPlus/nginxDeployments/{deploymentName}/apiKeys/{apiKeyName}") + @ExpectedResponses({ 200, 204 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> delete(@HostParam("$host") String endpoint, + @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, + @PathParam("deploymentName") String deploymentName, @PathParam("apiKeyName") String apiKeyName, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Nginx.NginxPlus/nginxDeployments/{deploymentName}/apiKeys/{apiKeyName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> get(@HostParam("$host") String endpoint, + @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, + @PathParam("deploymentName") String deploymentName, @PathParam("apiKeyName") String apiKeyName, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Nginx.NginxPlus/nginxDeployments/{deploymentName}/apiKeys") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> list(@HostParam("$host") String endpoint, + @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, + @PathParam("deploymentName") String deploymentName, @QueryParam("api-version") String apiVersion, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * Create or update an API Key for the Nginx deployment in order to access the dataplane API endpoint. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param apiKeyName The resource name of the API key. + * @param body The API Key object containing fields (e.g. secret text, expiration date) to upsert the key. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> createOrUpdateWithResponseAsync(String resourceGroupName, + String deploymentName, String apiKeyName, NginxDeploymentApiKeyRequest body) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (deploymentName == null) { + return Mono.error(new IllegalArgumentException("Parameter deploymentName is required and cannot be null.")); + } + if (apiKeyName == null) { + return Mono.error(new IllegalArgumentException("Parameter apiKeyName is required and cannot be null.")); + } + if (body != null) { + body.validate(); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.createOrUpdate(this.client.getEndpoint(), this.client.getSubscriptionId(), + resourceGroupName, deploymentName, apiKeyName, this.client.getApiVersion(), body, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Create or update an API Key for the Nginx deployment in order to access the dataplane API endpoint. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param apiKeyName The resource name of the API key. + * @param body The API Key object containing fields (e.g. secret text, expiration date) to upsert the key. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> createOrUpdateWithResponseAsync(String resourceGroupName, + String deploymentName, String apiKeyName, NginxDeploymentApiKeyRequest body, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (deploymentName == null) { + return Mono.error(new IllegalArgumentException("Parameter deploymentName is required and cannot be null.")); + } + if (apiKeyName == null) { + return Mono.error(new IllegalArgumentException("Parameter apiKeyName is required and cannot be null.")); + } + if (body != null) { + body.validate(); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.createOrUpdate(this.client.getEndpoint(), this.client.getSubscriptionId(), resourceGroupName, + deploymentName, apiKeyName, this.client.getApiVersion(), body, accept, context); + } + + /** + * Create or update an API Key for the Nginx deployment in order to access the dataplane API endpoint. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param apiKeyName The resource name of the API key. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createOrUpdateAsync(String resourceGroupName, + String deploymentName, String apiKeyName) { + final NginxDeploymentApiKeyRequest body = null; + return createOrUpdateWithResponseAsync(resourceGroupName, deploymentName, apiKeyName, body) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Create or update an API Key for the Nginx deployment in order to access the dataplane API endpoint. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param apiKeyName The resource name of the API key. + * @param body The API Key object containing fields (e.g. secret text, expiration date) to upsert the key. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createOrUpdateWithResponse(String resourceGroupName, + String deploymentName, String apiKeyName, NginxDeploymentApiKeyRequest body, Context context) { + return createOrUpdateWithResponseAsync(resourceGroupName, deploymentName, apiKeyName, body, context).block(); + } + + /** + * Create or update an API Key for the Nginx deployment in order to access the dataplane API endpoint. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param apiKeyName The resource name of the API key. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public NginxDeploymentApiKeyResponseInner createOrUpdate(String resourceGroupName, String deploymentName, + String apiKeyName) { + final NginxDeploymentApiKeyRequest body = null; + return createOrUpdateWithResponse(resourceGroupName, deploymentName, apiKeyName, body, Context.NONE).getValue(); + } + + /** + * Delete API key for Nginx deployment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param apiKeyName The resource name of the API key. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String deploymentName, + String apiKeyName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (deploymentName == null) { + return Mono.error(new IllegalArgumentException("Parameter deploymentName is required and cannot be null.")); + } + if (apiKeyName == null) { + return Mono.error(new IllegalArgumentException("Parameter apiKeyName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.delete(this.client.getEndpoint(), this.client.getSubscriptionId(), + resourceGroupName, deploymentName, apiKeyName, this.client.getApiVersion(), accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Delete API key for Nginx deployment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param apiKeyName The resource name of the API key. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> deleteWithResponseAsync(String resourceGroupName, String deploymentName, + String apiKeyName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (deploymentName == null) { + return Mono.error(new IllegalArgumentException("Parameter deploymentName is required and cannot be null.")); + } + if (apiKeyName == null) { + return Mono.error(new IllegalArgumentException("Parameter apiKeyName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.delete(this.client.getEndpoint(), this.client.getSubscriptionId(), resourceGroupName, + deploymentName, apiKeyName, this.client.getApiVersion(), accept, context); + } + + /** + * Delete API key for Nginx deployment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param apiKeyName The resource name of the API key. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono deleteAsync(String resourceGroupName, String deploymentName, String apiKeyName) { + return deleteWithResponseAsync(resourceGroupName, deploymentName, apiKeyName).flatMap(ignored -> Mono.empty()); + } + + /** + * Delete API key for Nginx deployment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param apiKeyName The resource name of the API key. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String resourceGroupName, String deploymentName, String apiKeyName, + Context context) { + return deleteWithResponseAsync(resourceGroupName, deploymentName, apiKeyName, context).block(); + } + + /** + * Delete API key for Nginx deployment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param apiKeyName The resource name of the API key. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String resourceGroupName, String deploymentName, String apiKeyName) { + deleteWithResponse(resourceGroupName, deploymentName, apiKeyName, Context.NONE); + } + + /** + * Get the specified API Key of the given Nginx deployment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param apiKeyName The resource name of the API key. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the specified API Key of the given Nginx deployment along with {@link Response} on successful completion + * of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, + String deploymentName, String apiKeyName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (deploymentName == null) { + return Mono.error(new IllegalArgumentException("Parameter deploymentName is required and cannot be null.")); + } + if (apiKeyName == null) { + return Mono.error(new IllegalArgumentException("Parameter apiKeyName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.get(this.client.getEndpoint(), this.client.getSubscriptionId(), + resourceGroupName, deploymentName, apiKeyName, this.client.getApiVersion(), accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the specified API Key of the given Nginx deployment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param apiKeyName The resource name of the API key. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the specified API Key of the given Nginx deployment along with {@link Response} on successful completion + * of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getWithResponseAsync(String resourceGroupName, + String deploymentName, String apiKeyName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (deploymentName == null) { + return Mono.error(new IllegalArgumentException("Parameter deploymentName is required and cannot be null.")); + } + if (apiKeyName == null) { + return Mono.error(new IllegalArgumentException("Parameter apiKeyName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.get(this.client.getEndpoint(), this.client.getSubscriptionId(), resourceGroupName, + deploymentName, apiKeyName, this.client.getApiVersion(), accept, context); + } + + /** + * Get the specified API Key of the given Nginx deployment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param apiKeyName The resource name of the API key. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the specified API Key of the given Nginx deployment on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String resourceGroupName, String deploymentName, + String apiKeyName) { + return getWithResponseAsync(resourceGroupName, deploymentName, apiKeyName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get the specified API Key of the given Nginx deployment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param apiKeyName The resource name of the API key. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the specified API Key of the given Nginx deployment along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String resourceGroupName, String deploymentName, + String apiKeyName, Context context) { + return getWithResponseAsync(resourceGroupName, deploymentName, apiKeyName, context).block(); + } + + /** + * Get the specified API Key of the given Nginx deployment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param apiKeyName The resource name of the API key. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the specified API Key of the given Nginx deployment. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public NginxDeploymentApiKeyResponseInner get(String resourceGroupName, String deploymentName, String apiKeyName) { + return getWithResponse(resourceGroupName, deploymentName, apiKeyName, Context.NONE).getValue(); + } + + /** + * List all API Keys of the given Nginx deployment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link PagedResponse} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync(String resourceGroupName, + String deploymentName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (deploymentName == null) { + return Mono.error(new IllegalArgumentException("Parameter deploymentName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.list(this.client.getEndpoint(), this.client.getSubscriptionId(), + resourceGroupName, deploymentName, this.client.getApiVersion(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List all API Keys of the given Nginx deployment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link PagedResponse} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync(String resourceGroupName, + String deploymentName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (deploymentName == null) { + return Mono.error(new IllegalArgumentException("Parameter deploymentName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .list(this.client.getEndpoint(), this.client.getSubscriptionId(), resourceGroupName, deploymentName, + this.client.getApiVersion(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List all API Keys of the given Nginx deployment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync(String resourceGroupName, String deploymentName) { + return new PagedFlux<>(() -> listSinglePageAsync(resourceGroupName, deploymentName), + nextLink -> listNextSinglePageAsync(nextLink)); + } + + /** + * List all API Keys of the given Nginx deployment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync(String resourceGroupName, String deploymentName, + Context context) { + return new PagedFlux<>(() -> listSinglePageAsync(resourceGroupName, deploymentName, context), + nextLink -> listNextSinglePageAsync(nextLink, context)); + } + + /** + * List all API Keys of the given Nginx deployment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(String resourceGroupName, String deploymentName) { + return new PagedIterable<>(listAsync(resourceGroupName, deploymentName)); + } + + /** + * List all API Keys of the given Nginx deployment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(String resourceGroupName, String deploymentName, + Context context) { + return new PagedIterable<>(listAsync(resourceGroupName, deploymentName, context)); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link PagedResponse} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.listNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link PagedResponse} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/ApiKeysImpl.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/ApiKeysImpl.java new file mode 100644 index 000000000000..f929b2607cc7 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/ApiKeysImpl.java @@ -0,0 +1,162 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.nginx.fluent.ApiKeysClient; +import com.azure.resourcemanager.nginx.fluent.models.NginxDeploymentApiKeyResponseInner; +import com.azure.resourcemanager.nginx.models.ApiKeys; +import com.azure.resourcemanager.nginx.models.NginxDeploymentApiKeyResponse; + +public final class ApiKeysImpl implements ApiKeys { + private static final ClientLogger LOGGER = new ClientLogger(ApiKeysImpl.class); + + private final ApiKeysClient innerClient; + + private final com.azure.resourcemanager.nginx.NginxManager serviceManager; + + public ApiKeysImpl(ApiKeysClient innerClient, com.azure.resourcemanager.nginx.NginxManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public Response deleteWithResponse(String resourceGroupName, String deploymentName, String apiKeyName, + Context context) { + return this.serviceClient().deleteWithResponse(resourceGroupName, deploymentName, apiKeyName, context); + } + + public void delete(String resourceGroupName, String deploymentName, String apiKeyName) { + this.serviceClient().delete(resourceGroupName, deploymentName, apiKeyName); + } + + public Response getWithResponse(String resourceGroupName, String deploymentName, + String apiKeyName, Context context) { + Response inner + = this.serviceClient().getWithResponse(resourceGroupName, deploymentName, apiKeyName, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new NginxDeploymentApiKeyResponseImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public NginxDeploymentApiKeyResponse get(String resourceGroupName, String deploymentName, String apiKeyName) { + NginxDeploymentApiKeyResponseInner inner + = this.serviceClient().get(resourceGroupName, deploymentName, apiKeyName); + if (inner != null) { + return new NginxDeploymentApiKeyResponseImpl(inner, this.manager()); + } else { + return null; + } + } + + public PagedIterable list(String resourceGroupName, String deploymentName) { + PagedIterable inner + = this.serviceClient().list(resourceGroupName, deploymentName); + return ResourceManagerUtils.mapPage(inner, + inner1 -> new NginxDeploymentApiKeyResponseImpl(inner1, this.manager())); + } + + public PagedIterable list(String resourceGroupName, String deploymentName, + Context context) { + PagedIterable inner + = this.serviceClient().list(resourceGroupName, deploymentName, context); + return ResourceManagerUtils.mapPage(inner, + inner1 -> new NginxDeploymentApiKeyResponseImpl(inner1, this.manager())); + } + + public NginxDeploymentApiKeyResponse getById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String deploymentName = ResourceManagerUtils.getValueFromIdByName(id, "nginxDeployments"); + if (deploymentName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'nginxDeployments'.", id))); + } + String apiKeyName = ResourceManagerUtils.getValueFromIdByName(id, "apiKeys"); + if (apiKeyName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'apiKeys'.", id))); + } + return this.getWithResponse(resourceGroupName, deploymentName, apiKeyName, Context.NONE).getValue(); + } + + public Response getByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String deploymentName = ResourceManagerUtils.getValueFromIdByName(id, "nginxDeployments"); + if (deploymentName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'nginxDeployments'.", id))); + } + String apiKeyName = ResourceManagerUtils.getValueFromIdByName(id, "apiKeys"); + if (apiKeyName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'apiKeys'.", id))); + } + return this.getWithResponse(resourceGroupName, deploymentName, apiKeyName, context); + } + + public void deleteById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String deploymentName = ResourceManagerUtils.getValueFromIdByName(id, "nginxDeployments"); + if (deploymentName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'nginxDeployments'.", id))); + } + String apiKeyName = ResourceManagerUtils.getValueFromIdByName(id, "apiKeys"); + if (apiKeyName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'apiKeys'.", id))); + } + this.deleteWithResponse(resourceGroupName, deploymentName, apiKeyName, Context.NONE); + } + + public Response deleteByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String deploymentName = ResourceManagerUtils.getValueFromIdByName(id, "nginxDeployments"); + if (deploymentName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'nginxDeployments'.", id))); + } + String apiKeyName = ResourceManagerUtils.getValueFromIdByName(id, "apiKeys"); + if (apiKeyName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'apiKeys'.", id))); + } + return this.deleteWithResponse(resourceGroupName, deploymentName, apiKeyName, context); + } + + private ApiKeysClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.nginx.NginxManager manager() { + return this.serviceManager; + } + + public NginxDeploymentApiKeyResponseImpl define(String name) { + return new NginxDeploymentApiKeyResponseImpl(name, this.manager()); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/ConfigurationsClientImpl.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/ConfigurationsClientImpl.java index b77984118a41..1ce9464f24d0 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/ConfigurationsClientImpl.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/ConfigurationsClientImpl.java @@ -34,9 +34,10 @@ import com.azure.core.util.polling.SyncPoller; import com.azure.resourcemanager.nginx.fluent.ConfigurationsClient; import com.azure.resourcemanager.nginx.fluent.models.AnalysisResultInner; -import com.azure.resourcemanager.nginx.fluent.models.NginxConfigurationInner; +import com.azure.resourcemanager.nginx.fluent.models.NginxConfigurationResponseInner; import com.azure.resourcemanager.nginx.models.AnalysisCreate; import com.azure.resourcemanager.nginx.models.NginxConfigurationListResponse; +import com.azure.resourcemanager.nginx.models.NginxConfigurationRequest; import java.nio.ByteBuffer; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -87,7 +88,7 @@ Mono> list(@HostParam("$host") String e @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Nginx.NginxPlus/nginxDeployments/{deploymentName}/configurations/{configurationName}") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono> get(@HostParam("$host") String endpoint, + Mono> get(@HostParam("$host") String endpoint, @PathParam("subscriptionId") String subscriptionId, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("deploymentName") String deploymentName, @@ -103,7 +104,7 @@ Mono>> createOrUpdate(@HostParam("$host") String endpo @PathParam("resourceGroupName") String resourceGroupName, @PathParam("deploymentName") String deploymentName, @PathParam("configurationName") String configurationName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") NginxConfigurationInner body, @HeaderParam("Accept") String accept, + @BodyParam("application/json") NginxConfigurationRequest body, @HeaderParam("Accept") String accept, Context context); @Headers({ "Content-Type: application/json" }) @@ -148,7 +149,7 @@ Mono> listNext( * @return response of a list operation along with {@link PagedResponse} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listSinglePageAsync(String resourceGroupName, + private Mono> listSinglePageAsync(String resourceGroupName, String deploymentName) { if (this.client.getEndpoint() == null) { return Mono.error( @@ -169,7 +170,7 @@ private Mono> listSinglePageAsync(String return FluxUtil .withContext(context -> service.list(this.client.getEndpoint(), this.client.getSubscriptionId(), resourceGroupName, deploymentName, this.client.getApiVersion(), accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } @@ -186,7 +187,7 @@ private Mono> listSinglePageAsync(String * @return response of a list operation along with {@link PagedResponse} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listSinglePageAsync(String resourceGroupName, + private Mono> listSinglePageAsync(String resourceGroupName, String deploymentName, Context context) { if (this.client.getEndpoint() == null) { return Mono.error( @@ -223,7 +224,7 @@ private Mono> listSinglePageAsync(String * @return response of a list operation as paginated response with {@link PagedFlux}. */ @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listAsync(String resourceGroupName, String deploymentName) { + private PagedFlux listAsync(String resourceGroupName, String deploymentName) { return new PagedFlux<>(() -> listSinglePageAsync(resourceGroupName, deploymentName), nextLink -> listNextSinglePageAsync(nextLink)); } @@ -240,7 +241,7 @@ private PagedFlux listAsync(String resourceGroupName, S * @return response of a list operation as paginated response with {@link PagedFlux}. */ @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listAsync(String resourceGroupName, String deploymentName, + private PagedFlux listAsync(String resourceGroupName, String deploymentName, Context context) { return new PagedFlux<>(() -> listSinglePageAsync(resourceGroupName, deploymentName, context), nextLink -> listNextSinglePageAsync(nextLink, context)); @@ -257,7 +258,7 @@ private PagedFlux listAsync(String resourceGroupName, S * @return response of a list operation as paginated response with {@link PagedIterable}. */ @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list(String resourceGroupName, String deploymentName) { + public PagedIterable list(String resourceGroupName, String deploymentName) { return new PagedIterable<>(listAsync(resourceGroupName, deploymentName)); } @@ -273,7 +274,7 @@ public PagedIterable list(String resourceGroupName, Str * @return response of a list operation as paginated response with {@link PagedIterable}. */ @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list(String resourceGroupName, String deploymentName, + public PagedIterable list(String resourceGroupName, String deploymentName, Context context) { return new PagedIterable<>(listAsync(resourceGroupName, deploymentName, context)); } @@ -292,7 +293,7 @@ public PagedIterable list(String resourceGroupName, Str * {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> getWithResponseAsync(String resourceGroupName, + private Mono> getWithResponseAsync(String resourceGroupName, String deploymentName, String configurationName) { if (this.client.getEndpoint() == null) { return Mono.error( @@ -335,7 +336,7 @@ private Mono> getWithResponseAsync(String reso * {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> getWithResponseAsync(String resourceGroupName, + private Mono> getWithResponseAsync(String resourceGroupName, String deploymentName, String configurationName, Context context) { if (this.client.getEndpoint() == null) { return Mono.error( @@ -375,7 +376,7 @@ private Mono> getWithResponseAsync(String reso * @return the NGINX configuration of given NGINX deployment on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono getAsync(String resourceGroupName, String deploymentName, + private Mono getAsync(String resourceGroupName, String deploymentName, String configurationName) { return getWithResponseAsync(resourceGroupName, deploymentName, configurationName) .flatMap(res -> Mono.justOrEmpty(res.getValue())); @@ -395,7 +396,7 @@ private Mono getAsync(String resourceGroupName, String * @return the NGINX configuration of given NGINX deployment along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response getWithResponse(String resourceGroupName, String deploymentName, + public Response getWithResponse(String resourceGroupName, String deploymentName, String configurationName, Context context) { return getWithResponseAsync(resourceGroupName, deploymentName, configurationName, context).block(); } @@ -413,7 +414,8 @@ public Response getWithResponse(String resourceGroupNam * @return the NGINX configuration of given NGINX deployment. */ @ServiceMethod(returns = ReturnType.SINGLE) - public NginxConfigurationInner get(String resourceGroupName, String deploymentName, String configurationName) { + public NginxConfigurationResponseInner get(String resourceGroupName, String deploymentName, + String configurationName) { return getWithResponse(resourceGroupName, deploymentName, configurationName, Context.NONE).getValue(); } @@ -432,7 +434,7 @@ public NginxConfigurationInner get(String resourceGroupName, String deploymentNa */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono>> createOrUpdateWithResponseAsync(String resourceGroupName, - String deploymentName, String configurationName, NginxConfigurationInner body) { + String deploymentName, String configurationName, NginxConfigurationRequest body) { if (this.client.getEndpoint() == null) { return Mono.error( new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); @@ -479,7 +481,7 @@ private Mono>> createOrUpdateWithResponseAsync(String */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono>> createOrUpdateWithResponseAsync(String resourceGroupName, - String deploymentName, String configurationName, NginxConfigurationInner body, Context context) { + String deploymentName, String configurationName, NginxConfigurationRequest body, Context context) { if (this.client.getEndpoint() == null) { return Mono.error( new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); @@ -522,12 +524,13 @@ private Mono>> createOrUpdateWithResponseAsync(String * @return the {@link PollerFlux} for polling of long-running operation. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, NginxConfigurationInner> beginCreateOrUpdateAsync( - String resourceGroupName, String deploymentName, String configurationName, NginxConfigurationInner body) { + private PollerFlux, NginxConfigurationResponseInner> + beginCreateOrUpdateAsync(String resourceGroupName, String deploymentName, String configurationName, + NginxConfigurationRequest body) { Mono>> mono = createOrUpdateWithResponseAsync(resourceGroupName, deploymentName, configurationName, body); - return this.client.getLroResult(mono, - this.client.getHttpPipeline(), NginxConfigurationInner.class, NginxConfigurationInner.class, + return this.client.getLroResult(mono, + this.client.getHttpPipeline(), NginxConfigurationResponseInner.class, NginxConfigurationResponseInner.class, this.client.getContext()); } @@ -544,13 +547,13 @@ private PollerFlux, NginxConfigurationInner> * @return the {@link PollerFlux} for polling of long-running operation. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, NginxConfigurationInner> + private PollerFlux, NginxConfigurationResponseInner> beginCreateOrUpdateAsync(String resourceGroupName, String deploymentName, String configurationName) { - final NginxConfigurationInner body = null; + final NginxConfigurationRequest body = null; Mono>> mono = createOrUpdateWithResponseAsync(resourceGroupName, deploymentName, configurationName, body); - return this.client.getLroResult(mono, - this.client.getHttpPipeline(), NginxConfigurationInner.class, NginxConfigurationInner.class, + return this.client.getLroResult(mono, + this.client.getHttpPipeline(), NginxConfigurationResponseInner.class, NginxConfigurationResponseInner.class, this.client.getContext()); } @@ -569,14 +572,15 @@ private PollerFlux, NginxConfigurationInner> * @return the {@link PollerFlux} for polling of long-running operation. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, NginxConfigurationInner> beginCreateOrUpdateAsync( - String resourceGroupName, String deploymentName, String configurationName, NginxConfigurationInner body, - Context context) { + private PollerFlux, NginxConfigurationResponseInner> + beginCreateOrUpdateAsync(String resourceGroupName, String deploymentName, String configurationName, + NginxConfigurationRequest body, Context context) { context = this.client.mergeContext(context); Mono>> mono = createOrUpdateWithResponseAsync(resourceGroupName, deploymentName, configurationName, body, context); - return this.client.getLroResult(mono, - this.client.getHttpPipeline(), NginxConfigurationInner.class, NginxConfigurationInner.class, context); + return this.client.getLroResult(mono, + this.client.getHttpPipeline(), NginxConfigurationResponseInner.class, NginxConfigurationResponseInner.class, + context); } /** @@ -592,9 +596,9 @@ private PollerFlux, NginxConfigurationInner> * @return the {@link SyncPoller} for polling of long-running operation. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, NginxConfigurationInner> + public SyncPoller, NginxConfigurationResponseInner> beginCreateOrUpdate(String resourceGroupName, String deploymentName, String configurationName) { - final NginxConfigurationInner body = null; + final NginxConfigurationRequest body = null; return this.beginCreateOrUpdateAsync(resourceGroupName, deploymentName, configurationName, body) .getSyncPoller(); } @@ -614,8 +618,8 @@ private PollerFlux, NginxConfigurationInner> * @return the {@link SyncPoller} for polling of long-running operation. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, NginxConfigurationInner> beginCreateOrUpdate( - String resourceGroupName, String deploymentName, String configurationName, NginxConfigurationInner body, + public SyncPoller, NginxConfigurationResponseInner> beginCreateOrUpdate( + String resourceGroupName, String deploymentName, String configurationName, NginxConfigurationRequest body, Context context) { return this.beginCreateOrUpdateAsync(resourceGroupName, deploymentName, configurationName, body, context) .getSyncPoller(); @@ -635,8 +639,8 @@ public SyncPoller, NginxConfigurationInner> * @return the response body on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono createOrUpdateAsync(String resourceGroupName, String deploymentName, - String configurationName, NginxConfigurationInner body) { + private Mono createOrUpdateAsync(String resourceGroupName, String deploymentName, + String configurationName, NginxConfigurationRequest body) { return beginCreateOrUpdateAsync(resourceGroupName, deploymentName, configurationName, body).last() .flatMap(this.client::getLroFinalResultOrError); } @@ -654,9 +658,9 @@ private Mono createOrUpdateAsync(String resourceGroupNa * @return the response body on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono createOrUpdateAsync(String resourceGroupName, String deploymentName, + private Mono createOrUpdateAsync(String resourceGroupName, String deploymentName, String configurationName) { - final NginxConfigurationInner body = null; + final NginxConfigurationRequest body = null; return beginCreateOrUpdateAsync(resourceGroupName, deploymentName, configurationName, body).last() .flatMap(this.client::getLroFinalResultOrError); } @@ -676,8 +680,8 @@ private Mono createOrUpdateAsync(String resourceGroupNa * @return the response body on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono createOrUpdateAsync(String resourceGroupName, String deploymentName, - String configurationName, NginxConfigurationInner body, Context context) { + private Mono createOrUpdateAsync(String resourceGroupName, String deploymentName, + String configurationName, NginxConfigurationRequest body, Context context) { return beginCreateOrUpdateAsync(resourceGroupName, deploymentName, configurationName, body, context).last() .flatMap(this.client::getLroFinalResultOrError); } @@ -695,9 +699,9 @@ private Mono createOrUpdateAsync(String resourceGroupNa * @return the response. */ @ServiceMethod(returns = ReturnType.SINGLE) - public NginxConfigurationInner createOrUpdate(String resourceGroupName, String deploymentName, + public NginxConfigurationResponseInner createOrUpdate(String resourceGroupName, String deploymentName, String configurationName) { - final NginxConfigurationInner body = null; + final NginxConfigurationRequest body = null; return createOrUpdateAsync(resourceGroupName, deploymentName, configurationName, body).block(); } @@ -716,8 +720,8 @@ public NginxConfigurationInner createOrUpdate(String resourceGroupName, String d * @return the response. */ @ServiceMethod(returns = ReturnType.SINGLE) - public NginxConfigurationInner createOrUpdate(String resourceGroupName, String deploymentName, - String configurationName, NginxConfigurationInner body, Context context) { + public NginxConfigurationResponseInner createOrUpdate(String resourceGroupName, String deploymentName, + String configurationName, NginxConfigurationRequest body, Context context) { return createOrUpdateAsync(resourceGroupName, deploymentName, configurationName, body, context).block(); } @@ -1117,7 +1121,7 @@ public AnalysisResultInner analysis(String resourceGroupName, String deploymentN * @return response of a list operation along with {@link PagedResponse} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listNextSinglePageAsync(String nextLink) { + private Mono> listNextSinglePageAsync(String nextLink) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); } @@ -1127,7 +1131,7 @@ private Mono> listNextSinglePageAsync(Str } final String accept = "application/json"; return FluxUtil.withContext(context -> service.listNext(nextLink, this.client.getEndpoint(), accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } @@ -1143,7 +1147,8 @@ private Mono> listNextSinglePageAsync(Str * @return response of a list operation along with {@link PagedResponse} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listNextSinglePageAsync(String nextLink, Context context) { + private Mono> listNextSinglePageAsync(String nextLink, + Context context) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/ConfigurationsImpl.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/ConfigurationsImpl.java index f43975deea75..f165898a97d0 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/ConfigurationsImpl.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/ConfigurationsImpl.java @@ -11,11 +11,11 @@ import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.nginx.fluent.ConfigurationsClient; import com.azure.resourcemanager.nginx.fluent.models.AnalysisResultInner; -import com.azure.resourcemanager.nginx.fluent.models.NginxConfigurationInner; +import com.azure.resourcemanager.nginx.fluent.models.NginxConfigurationResponseInner; import com.azure.resourcemanager.nginx.models.AnalysisCreate; import com.azure.resourcemanager.nginx.models.AnalysisResult; import com.azure.resourcemanager.nginx.models.Configurations; -import com.azure.resourcemanager.nginx.models.NginxConfiguration; +import com.azure.resourcemanager.nginx.models.NginxConfigurationResponse; public final class ConfigurationsImpl implements Configurations { private static final ClientLogger LOGGER = new ClientLogger(ConfigurationsImpl.class); @@ -30,33 +30,38 @@ public ConfigurationsImpl(ConfigurationsClient innerClient, this.serviceManager = serviceManager; } - public PagedIterable list(String resourceGroupName, String deploymentName) { - PagedIterable inner = this.serviceClient().list(resourceGroupName, deploymentName); - return ResourceManagerUtils.mapPage(inner, inner1 -> new NginxConfigurationImpl(inner1, this.manager())); + public PagedIterable list(String resourceGroupName, String deploymentName) { + PagedIterable inner + = this.serviceClient().list(resourceGroupName, deploymentName); + return ResourceManagerUtils.mapPage(inner, + inner1 -> new NginxConfigurationResponseImpl(inner1, this.manager())); } - public PagedIterable list(String resourceGroupName, String deploymentName, Context context) { - PagedIterable inner + public PagedIterable list(String resourceGroupName, String deploymentName, + Context context) { + PagedIterable inner = this.serviceClient().list(resourceGroupName, deploymentName, context); - return ResourceManagerUtils.mapPage(inner, inner1 -> new NginxConfigurationImpl(inner1, this.manager())); + return ResourceManagerUtils.mapPage(inner, + inner1 -> new NginxConfigurationResponseImpl(inner1, this.manager())); } - public Response getWithResponse(String resourceGroupName, String deploymentName, + public Response getWithResponse(String resourceGroupName, String deploymentName, String configurationName, Context context) { - Response inner + Response inner = this.serviceClient().getWithResponse(resourceGroupName, deploymentName, configurationName, context); if (inner != null) { return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), - new NginxConfigurationImpl(inner.getValue(), this.manager())); + new NginxConfigurationResponseImpl(inner.getValue(), this.manager())); } else { return null; } } - public NginxConfiguration get(String resourceGroupName, String deploymentName, String configurationName) { - NginxConfigurationInner inner = this.serviceClient().get(resourceGroupName, deploymentName, configurationName); + public NginxConfigurationResponse get(String resourceGroupName, String deploymentName, String configurationName) { + NginxConfigurationResponseInner inner + = this.serviceClient().get(resourceGroupName, deploymentName, configurationName); if (inner != null) { - return new NginxConfigurationImpl(inner, this.manager()); + return new NginxConfigurationResponseImpl(inner, this.manager()); } else { return null; } @@ -91,7 +96,7 @@ public AnalysisResult analysis(String resourceGroupName, String deploymentName, } } - public NginxConfiguration getById(String id) { + public NginxConfigurationResponse getById(String id) { String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); if (resourceGroupName == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( @@ -110,7 +115,7 @@ public NginxConfiguration getById(String id) { return this.getWithResponse(resourceGroupName, deploymentName, configurationName, Context.NONE).getValue(); } - public Response getByIdWithResponse(String id, Context context) { + public Response getByIdWithResponse(String id, Context context) { String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); if (resourceGroupName == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( @@ -175,7 +180,7 @@ private com.azure.resourcemanager.nginx.NginxManager manager() { return this.serviceManager; } - public NginxConfigurationImpl define(String name) { - return new NginxConfigurationImpl(name, this.manager()); + public NginxConfigurationResponseImpl define(String name) { + return new NginxConfigurationResponseImpl(name, this.manager()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/NginxConfigurationImpl.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/NginxConfigurationImpl.java deleted file mode 100644 index 53c909c56057..000000000000 --- a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/NginxConfigurationImpl.java +++ /dev/null @@ -1,165 +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.resourcemanager.nginx.implementation; - -import com.azure.core.http.rest.Response; -import com.azure.core.management.Region; -import com.azure.core.management.SystemData; -import com.azure.core.util.Context; -import com.azure.resourcemanager.nginx.fluent.models.NginxConfigurationInner; -import com.azure.resourcemanager.nginx.models.AnalysisCreate; -import com.azure.resourcemanager.nginx.models.AnalysisResult; -import com.azure.resourcemanager.nginx.models.NginxConfiguration; -import com.azure.resourcemanager.nginx.models.NginxConfigurationProperties; - -public final class NginxConfigurationImpl - implements NginxConfiguration, NginxConfiguration.Definition, NginxConfiguration.Update { - private NginxConfigurationInner innerObject; - - private final com.azure.resourcemanager.nginx.NginxManager serviceManager; - - public String id() { - return this.innerModel().id(); - } - - public String name() { - return this.innerModel().name(); - } - - public String type() { - return this.innerModel().type(); - } - - public NginxConfigurationProperties properties() { - return this.innerModel().properties(); - } - - public String location() { - return this.innerModel().location(); - } - - public SystemData systemData() { - return this.innerModel().systemData(); - } - - public Region region() { - return Region.fromName(this.regionName()); - } - - public String regionName() { - return this.location(); - } - - public String resourceGroupName() { - return resourceGroupName; - } - - public NginxConfigurationInner innerModel() { - return this.innerObject; - } - - private com.azure.resourcemanager.nginx.NginxManager manager() { - return this.serviceManager; - } - - private String resourceGroupName; - - private String deploymentName; - - private String configurationName; - - public NginxConfigurationImpl withExistingNginxDeployment(String resourceGroupName, String deploymentName) { - this.resourceGroupName = resourceGroupName; - this.deploymentName = deploymentName; - return this; - } - - public NginxConfiguration create() { - this.innerObject = serviceManager.serviceClient() - .getConfigurations() - .createOrUpdate(resourceGroupName, deploymentName, configurationName, this.innerModel(), Context.NONE); - return this; - } - - public NginxConfiguration create(Context context) { - this.innerObject = serviceManager.serviceClient() - .getConfigurations() - .createOrUpdate(resourceGroupName, deploymentName, configurationName, this.innerModel(), context); - return this; - } - - NginxConfigurationImpl(String name, com.azure.resourcemanager.nginx.NginxManager serviceManager) { - this.innerObject = new NginxConfigurationInner(); - this.serviceManager = serviceManager; - this.configurationName = name; - } - - public NginxConfigurationImpl update() { - return this; - } - - public NginxConfiguration apply() { - this.innerObject = serviceManager.serviceClient() - .getConfigurations() - .createOrUpdate(resourceGroupName, deploymentName, configurationName, this.innerModel(), Context.NONE); - return this; - } - - public NginxConfiguration apply(Context context) { - this.innerObject = serviceManager.serviceClient() - .getConfigurations() - .createOrUpdate(resourceGroupName, deploymentName, configurationName, this.innerModel(), context); - return this; - } - - NginxConfigurationImpl(NginxConfigurationInner innerObject, - com.azure.resourcemanager.nginx.NginxManager serviceManager) { - this.innerObject = innerObject; - this.serviceManager = serviceManager; - this.resourceGroupName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "resourceGroups"); - this.deploymentName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "nginxDeployments"); - this.configurationName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "configurations"); - } - - public NginxConfiguration refresh() { - this.innerObject = serviceManager.serviceClient() - .getConfigurations() - .getWithResponse(resourceGroupName, deploymentName, configurationName, Context.NONE) - .getValue(); - return this; - } - - public NginxConfiguration refresh(Context context) { - this.innerObject = serviceManager.serviceClient() - .getConfigurations() - .getWithResponse(resourceGroupName, deploymentName, configurationName, context) - .getValue(); - return this; - } - - public Response analysisWithResponse(AnalysisCreate body, Context context) { - return serviceManager.configurations() - .analysisWithResponse(resourceGroupName, deploymentName, configurationName, body, context); - } - - public AnalysisResult analysis() { - return serviceManager.configurations().analysis(resourceGroupName, deploymentName, configurationName); - } - - public NginxConfigurationImpl withRegion(Region location) { - this.innerModel().withLocation(location.toString()); - return this; - } - - public NginxConfigurationImpl withRegion(String location) { - this.innerModel().withLocation(location); - return this; - } - - public NginxConfigurationImpl withProperties(NginxConfigurationProperties properties) { - this.innerModel().withProperties(properties); - return this; - } -} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/NginxConfigurationResponseImpl.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/NginxConfigurationResponseImpl.java new file mode 100644 index 000000000000..0bcdff0ac576 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/NginxConfigurationResponseImpl.java @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.implementation; + +import com.azure.core.http.rest.Response; +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.nginx.fluent.models.NginxConfigurationResponseInner; +import com.azure.resourcemanager.nginx.models.AnalysisCreate; +import com.azure.resourcemanager.nginx.models.AnalysisResult; +import com.azure.resourcemanager.nginx.models.NginxConfigurationRequest; +import com.azure.resourcemanager.nginx.models.NginxConfigurationRequestProperties; +import com.azure.resourcemanager.nginx.models.NginxConfigurationResponse; +import com.azure.resourcemanager.nginx.models.NginxConfigurationResponseProperties; + +public final class NginxConfigurationResponseImpl + implements NginxConfigurationResponse, NginxConfigurationResponse.Definition, NginxConfigurationResponse.Update { + private NginxConfigurationResponseInner innerObject; + + private final com.azure.resourcemanager.nginx.NginxManager serviceManager; + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public NginxConfigurationResponseProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public String resourceGroupName() { + return resourceGroupName; + } + + public NginxConfigurationResponseInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.nginx.NginxManager manager() { + return this.serviceManager; + } + + private String resourceGroupName; + + private String deploymentName; + + private String configurationName; + + private NginxConfigurationRequest createBody; + + private NginxConfigurationRequest updateBody; + + public NginxConfigurationResponseImpl withExistingNginxDeployment(String resourceGroupName, String deploymentName) { + this.resourceGroupName = resourceGroupName; + this.deploymentName = deploymentName; + return this; + } + + public NginxConfigurationResponse create() { + this.innerObject = serviceManager.serviceClient() + .getConfigurations() + .createOrUpdate(resourceGroupName, deploymentName, configurationName, createBody, Context.NONE); + return this; + } + + public NginxConfigurationResponse create(Context context) { + this.innerObject = serviceManager.serviceClient() + .getConfigurations() + .createOrUpdate(resourceGroupName, deploymentName, configurationName, createBody, context); + return this; + } + + NginxConfigurationResponseImpl(String name, com.azure.resourcemanager.nginx.NginxManager serviceManager) { + this.innerObject = new NginxConfigurationResponseInner(); + this.serviceManager = serviceManager; + this.configurationName = name; + this.createBody = new NginxConfigurationRequest(); + } + + public NginxConfigurationResponseImpl update() { + this.updateBody = new NginxConfigurationRequest(); + return this; + } + + public NginxConfigurationResponse apply() { + this.innerObject = serviceManager.serviceClient() + .getConfigurations() + .createOrUpdate(resourceGroupName, deploymentName, configurationName, updateBody, Context.NONE); + return this; + } + + public NginxConfigurationResponse apply(Context context) { + this.innerObject = serviceManager.serviceClient() + .getConfigurations() + .createOrUpdate(resourceGroupName, deploymentName, configurationName, updateBody, context); + return this; + } + + NginxConfigurationResponseImpl(NginxConfigurationResponseInner innerObject, + com.azure.resourcemanager.nginx.NginxManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + this.resourceGroupName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "resourceGroups"); + this.deploymentName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "nginxDeployments"); + this.configurationName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "configurations"); + } + + public NginxConfigurationResponse refresh() { + this.innerObject = serviceManager.serviceClient() + .getConfigurations() + .getWithResponse(resourceGroupName, deploymentName, configurationName, Context.NONE) + .getValue(); + return this; + } + + public NginxConfigurationResponse refresh(Context context) { + this.innerObject = serviceManager.serviceClient() + .getConfigurations() + .getWithResponse(resourceGroupName, deploymentName, configurationName, context) + .getValue(); + return this; + } + + public Response analysisWithResponse(AnalysisCreate body, Context context) { + return serviceManager.configurations() + .analysisWithResponse(resourceGroupName, deploymentName, configurationName, body, context); + } + + public AnalysisResult analysis() { + return serviceManager.configurations().analysis(resourceGroupName, deploymentName, configurationName); + } + + public NginxConfigurationResponseImpl withProperties(NginxConfigurationRequestProperties properties) { + if (isInCreateMode()) { + this.createBody.withProperties(properties); + return this; + } else { + this.updateBody.withProperties(properties); + return this; + } + } + + private boolean isInCreateMode() { + return this.innerModel().id() == null; + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/NginxDeploymentApiKeyResponseImpl.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/NginxDeploymentApiKeyResponseImpl.java new file mode 100644 index 000000000000..8106e9bfb425 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/NginxDeploymentApiKeyResponseImpl.java @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.implementation; + +import com.azure.core.util.Context; +import com.azure.resourcemanager.nginx.fluent.models.NginxDeploymentApiKeyResponseInner; +import com.azure.resourcemanager.nginx.models.NginxDeploymentApiKeyRequest; +import com.azure.resourcemanager.nginx.models.NginxDeploymentApiKeyRequestProperties; +import com.azure.resourcemanager.nginx.models.NginxDeploymentApiKeyResponse; +import com.azure.resourcemanager.nginx.models.NginxDeploymentApiKeyResponseProperties; + +public final class NginxDeploymentApiKeyResponseImpl implements NginxDeploymentApiKeyResponse, + NginxDeploymentApiKeyResponse.Definition, NginxDeploymentApiKeyResponse.Update { + private NginxDeploymentApiKeyResponseInner innerObject; + + private final com.azure.resourcemanager.nginx.NginxManager serviceManager; + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public NginxDeploymentApiKeyResponseProperties properties() { + return this.innerModel().properties(); + } + + public String resourceGroupName() { + return resourceGroupName; + } + + public NginxDeploymentApiKeyResponseInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.nginx.NginxManager manager() { + return this.serviceManager; + } + + private String resourceGroupName; + + private String deploymentName; + + private String apiKeyName; + + private NginxDeploymentApiKeyRequest createBody; + + private NginxDeploymentApiKeyRequest updateBody; + + public NginxDeploymentApiKeyResponseImpl withExistingNginxDeployment(String resourceGroupName, + String deploymentName) { + this.resourceGroupName = resourceGroupName; + this.deploymentName = deploymentName; + return this; + } + + public NginxDeploymentApiKeyResponse create() { + this.innerObject = serviceManager.serviceClient() + .getApiKeys() + .createOrUpdateWithResponse(resourceGroupName, deploymentName, apiKeyName, createBody, Context.NONE) + .getValue(); + return this; + } + + public NginxDeploymentApiKeyResponse create(Context context) { + this.innerObject = serviceManager.serviceClient() + .getApiKeys() + .createOrUpdateWithResponse(resourceGroupName, deploymentName, apiKeyName, createBody, context) + .getValue(); + return this; + } + + NginxDeploymentApiKeyResponseImpl(String name, com.azure.resourcemanager.nginx.NginxManager serviceManager) { + this.innerObject = new NginxDeploymentApiKeyResponseInner(); + this.serviceManager = serviceManager; + this.apiKeyName = name; + this.createBody = new NginxDeploymentApiKeyRequest(); + } + + public NginxDeploymentApiKeyResponseImpl update() { + this.updateBody = new NginxDeploymentApiKeyRequest(); + return this; + } + + public NginxDeploymentApiKeyResponse apply() { + this.innerObject = serviceManager.serviceClient() + .getApiKeys() + .createOrUpdateWithResponse(resourceGroupName, deploymentName, apiKeyName, updateBody, Context.NONE) + .getValue(); + return this; + } + + public NginxDeploymentApiKeyResponse apply(Context context) { + this.innerObject = serviceManager.serviceClient() + .getApiKeys() + .createOrUpdateWithResponse(resourceGroupName, deploymentName, apiKeyName, updateBody, context) + .getValue(); + return this; + } + + NginxDeploymentApiKeyResponseImpl(NginxDeploymentApiKeyResponseInner innerObject, + com.azure.resourcemanager.nginx.NginxManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + this.resourceGroupName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "resourceGroups"); + this.deploymentName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "nginxDeployments"); + this.apiKeyName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "apiKeys"); + } + + public NginxDeploymentApiKeyResponse refresh() { + this.innerObject = serviceManager.serviceClient() + .getApiKeys() + .getWithResponse(resourceGroupName, deploymentName, apiKeyName, Context.NONE) + .getValue(); + return this; + } + + public NginxDeploymentApiKeyResponse refresh(Context context) { + this.innerObject = serviceManager.serviceClient() + .getApiKeys() + .getWithResponse(resourceGroupName, deploymentName, apiKeyName, context) + .getValue(); + return this; + } + + public NginxDeploymentApiKeyResponseImpl withProperties(NginxDeploymentApiKeyRequestProperties properties) { + if (isInCreateMode()) { + this.createBody.withProperties(properties); + return this; + } else { + this.updateBody.withProperties(properties); + return this; + } + } + + private boolean isInCreateMode() { + return this.innerModel().id() == null; + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/NginxManagementClientBuilder.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/NginxManagementClientBuilder.java index 0e833aceefe8..f563e369c6a8 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/NginxManagementClientBuilder.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/NginxManagementClientBuilder.java @@ -20,12 +20,12 @@ @ServiceClientBuilder(serviceClients = { NginxManagementClientImpl.class }) public final class NginxManagementClientBuilder { /* - * The ID of the target subscription. + * The ID of the target subscription. The value must be an UUID. */ private String subscriptionId; /** - * Sets The ID of the target subscription. + * Sets The ID of the target subscription. The value must be an UUID. * * @param subscriptionId the subscriptionId value. * @return the NginxManagementClientBuilder. diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/NginxManagementClientImpl.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/NginxManagementClientImpl.java index 8098ad1e1d75..72ac3670635f 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/NginxManagementClientImpl.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/NginxManagementClientImpl.java @@ -23,6 +23,7 @@ import com.azure.core.util.polling.PollerFlux; import com.azure.core.util.serializer.SerializerAdapter; import com.azure.core.util.serializer.SerializerEncoding; +import com.azure.resourcemanager.nginx.fluent.ApiKeysClient; import com.azure.resourcemanager.nginx.fluent.CertificatesClient; import com.azure.resourcemanager.nginx.fluent.ConfigurationsClient; import com.azure.resourcemanager.nginx.fluent.DeploymentsClient; @@ -43,12 +44,12 @@ @ServiceClient(builder = NginxManagementClientBuilder.class) public final class NginxManagementClientImpl implements NginxManagementClient { /** - * The ID of the target subscription. + * The ID of the target subscription. The value must be an UUID. */ private final String subscriptionId; /** - * Gets The ID of the target subscription. + * Gets The ID of the target subscription. The value must be an UUID. * * @return the subscriptionId value. */ @@ -126,6 +127,20 @@ public Duration getDefaultPollInterval() { return this.defaultPollInterval; } + /** + * The ApiKeysClient object to access its operations. + */ + private final ApiKeysClient apiKeys; + + /** + * Gets the ApiKeysClient object to access its operations. + * + * @return the ApiKeysClient object. + */ + public ApiKeysClient getApiKeys() { + return this.apiKeys; + } + /** * The CertificatesClient object to access its operations. */ @@ -189,7 +204,7 @@ public OperationsClient getOperations() { * @param serializerAdapter The serializer to serialize an object into a string. * @param defaultPollInterval The default poll interval for long-running operation. * @param environment The Azure environment. - * @param subscriptionId The ID of the target subscription. + * @param subscriptionId The ID of the target subscription. The value must be an UUID. * @param endpoint server parameter. */ NginxManagementClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, @@ -199,7 +214,8 @@ public OperationsClient getOperations() { this.defaultPollInterval = defaultPollInterval; this.subscriptionId = subscriptionId; this.endpoint = endpoint; - this.apiVersion = "2024-01-01-preview"; + this.apiVersion = "2024-11-01-preview"; + this.apiKeys = new ApiKeysClientImpl(this); this.certificates = new CertificatesClientImpl(this); this.configurations = new ConfigurationsClientImpl(this); this.deployments = new DeploymentsClientImpl(this); diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/OperationsClientImpl.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/OperationsClientImpl.java index d17aa306511e..c657baf67306 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/OperationsClientImpl.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/implementation/OperationsClientImpl.java @@ -78,7 +78,7 @@ Mono> listNext(@PathParam(value = "nextLink", enco } /** - * List all operations provided by Nginx.NginxPlus for the 2024-01-01-preview api version. + * List all operations provided by Nginx.NginxPlus for the 2024-11-01-preview api version. * * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -101,7 +101,7 @@ private Mono> listSinglePageAsync() { } /** - * List all operations provided by Nginx.NginxPlus for the 2024-01-01-preview api version. + * List all operations provided by Nginx.NginxPlus for the 2024-11-01-preview api version. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -124,7 +124,7 @@ private Mono> listSinglePageAsync(Context co } /** - * List all operations provided by Nginx.NginxPlus for the 2024-01-01-preview api version. + * List all operations provided by Nginx.NginxPlus for the 2024-11-01-preview api version. * * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -136,7 +136,7 @@ private PagedFlux listAsync() { } /** - * List all operations provided by Nginx.NginxPlus for the 2024-01-01-preview api version. + * List all operations provided by Nginx.NginxPlus for the 2024-11-01-preview api version. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -151,7 +151,7 @@ private PagedFlux listAsync(Context context) { } /** - * List all operations provided by Nginx.NginxPlus for the 2024-01-01-preview api version. + * List all operations provided by Nginx.NginxPlus for the 2024-11-01-preview api version. * * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -164,7 +164,7 @@ public PagedIterable list() { } /** - * List all operations provided by Nginx.NginxPlus for the 2024-01-01-preview api version. + * List all operations provided by Nginx.NginxPlus for the 2024-11-01-preview api version. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/ActivationState.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/ActivationState.java new file mode 100644 index 000000000000..042cbf437d2e --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/ActivationState.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The activation state of the WAF. Use 'Enabled' to enable the WAF and 'Disabled' to disable it. + */ +public final class ActivationState extends ExpandableStringEnum { + /** + * Static value Enabled for ActivationState. + */ + public static final ActivationState ENABLED = fromString("Enabled"); + + /** + * Static value Disabled for ActivationState. + */ + public static final ActivationState DISABLED = fromString("Disabled"); + + /** + * Creates a new instance of ActivationState value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public ActivationState() { + } + + /** + * Creates or finds a ActivationState from its string representation. + * + * @param name a name to look for. + * @return the corresponding ActivationState. + */ + public static ActivationState fromString(String name) { + return fromString(name, ActivationState.class); + } + + /** + * Gets known ActivationState values. + * + * @return known ActivationState values. + */ + public static Collection values() { + return values(ActivationState.class); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/AnalysisCreateConfig.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/AnalysisCreateConfig.java index 66886dc55642..88e4389ca21f 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/AnalysisCreateConfig.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/AnalysisCreateConfig.java @@ -30,7 +30,7 @@ public final class AnalysisCreateConfig implements JsonSerializable protectedFiles; + private List protectedFiles; /* * The package property. @@ -88,7 +88,7 @@ public AnalysisCreateConfig withFiles(List files) { * * @return the protectedFiles value. */ - public List protectedFiles() { + public List protectedFiles() { return this.protectedFiles; } @@ -98,7 +98,7 @@ public List protectedFiles() { * @param protectedFiles the protectedFiles value to set. * @return the AnalysisCreateConfig object itself. */ - public AnalysisCreateConfig withProtectedFiles(List protectedFiles) { + public AnalysisCreateConfig withProtectedFiles(List protectedFiles) { this.protectedFiles = protectedFiles; return this; } @@ -176,8 +176,8 @@ public static AnalysisCreateConfig fromJson(JsonReader jsonReader) throws IOExce = reader.readArray(reader1 -> NginxConfigurationFile.fromJson(reader1)); deserializedAnalysisCreateConfig.files = files; } else if ("protectedFiles".equals(fieldName)) { - List protectedFiles - = reader.readArray(reader1 -> NginxConfigurationFile.fromJson(reader1)); + List protectedFiles + = reader.readArray(reader1 -> NginxConfigurationProtectedFileRequest.fromJson(reader1)); deserializedAnalysisCreateConfig.protectedFiles = protectedFiles; } else if ("package".equals(fieldName)) { deserializedAnalysisCreateConfig.packageProperty = NginxConfigurationPackage.fromJson(reader); diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/AnalysisResultData.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/AnalysisResultData.java index 7ddfa92b5fd0..fe539db69035 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/AnalysisResultData.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/AnalysisResultData.java @@ -22,6 +22,11 @@ public final class AnalysisResultData implements JsonSerializable errors; + /* + * The diagnostics property. + */ + private List diagnostics; + /** * Creates an instance of AnalysisResultData class. */ @@ -48,6 +53,26 @@ public AnalysisResultData withErrors(List errors) { return this; } + /** + * Get the diagnostics property: The diagnostics property. + * + * @return the diagnostics value. + */ + public List diagnostics() { + return this.diagnostics; + } + + /** + * Set the diagnostics property: The diagnostics property. + * + * @param diagnostics the diagnostics value to set. + * @return the AnalysisResultData object itself. + */ + public AnalysisResultData withDiagnostics(List diagnostics) { + this.diagnostics = diagnostics; + return this; + } + /** * Validates the instance. * @@ -57,6 +82,9 @@ public void validate() { if (errors() != null) { errors().forEach(e -> e.validate()); } + if (diagnostics() != null) { + diagnostics().forEach(e -> e.validate()); + } } /** @@ -66,6 +94,7 @@ public void validate() { public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeArrayField("errors", this.errors, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeArrayField("diagnostics", this.diagnostics, (writer, element) -> writer.writeJson(element)); return jsonWriter.writeEndObject(); } @@ -87,6 +116,9 @@ public static AnalysisResultData fromJson(JsonReader jsonReader) throws IOExcept if ("errors".equals(fieldName)) { List errors = reader.readArray(reader1 -> AnalysisDiagnostic.fromJson(reader1)); deserializedAnalysisResultData.errors = errors; + } else if ("diagnostics".equals(fieldName)) { + List diagnostics = reader.readArray(reader1 -> DiagnosticItem.fromJson(reader1)); + deserializedAnalysisResultData.diagnostics = diagnostics; } else { reader.skipChildren(); } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/ApiKeys.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/ApiKeys.java new file mode 100644 index 000000000000..9d0cb5785046 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/ApiKeys.java @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of ApiKeys. + */ +public interface ApiKeys { + /** + * Delete API key for Nginx deployment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param apiKeyName The resource name of the API key. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteWithResponse(String resourceGroupName, String deploymentName, String apiKeyName, + Context context); + + /** + * Delete API key for Nginx deployment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param apiKeyName The resource name of the API key. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void delete(String resourceGroupName, String deploymentName, String apiKeyName); + + /** + * Get the specified API Key of the given Nginx deployment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param apiKeyName The resource name of the API key. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the specified API Key of the given Nginx deployment along with {@link Response}. + */ + Response getWithResponse(String resourceGroupName, String deploymentName, + String apiKeyName, Context context); + + /** + * Get the specified API Key of the given Nginx deployment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param apiKeyName The resource name of the API key. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the specified API Key of the given Nginx deployment. + */ + NginxDeploymentApiKeyResponse get(String resourceGroupName, String deploymentName, String apiKeyName); + + /** + * List all API Keys of the given Nginx deployment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the paginated response with {@link PagedIterable}. + */ + PagedIterable list(String resourceGroupName, String deploymentName); + + /** + * List all API Keys of the given Nginx deployment. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the paginated response with {@link PagedIterable}. + */ + PagedIterable list(String resourceGroupName, String deploymentName, Context context); + + /** + * Get the specified API Key of the given Nginx deployment. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the specified API Key of the given Nginx deployment along with {@link Response}. + */ + NginxDeploymentApiKeyResponse getById(String id); + + /** + * Get the specified API Key of the given Nginx deployment. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the specified API Key of the given Nginx deployment along with {@link Response}. + */ + Response getByIdWithResponse(String id, Context context); + + /** + * Delete API key for Nginx deployment. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteById(String id); + + /** + * Delete API key for Nginx deployment. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + Response deleteByIdWithResponse(String id, Context context); + + /** + * Begins definition for a new NginxDeploymentApiKeyResponse resource. + * + * @param name resource name. + * @return the first stage of the new NginxDeploymentApiKeyResponse definition. + */ + NginxDeploymentApiKeyResponse.DefinitionStages.Blank define(String name); +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/Configurations.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/Configurations.java index 91c7dbd47fdb..fbb71b302ee9 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/Configurations.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/Configurations.java @@ -22,7 +22,7 @@ public interface Configurations { * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response of a list operation as paginated response with {@link PagedIterable}. */ - PagedIterable list(String resourceGroupName, String deploymentName); + PagedIterable list(String resourceGroupName, String deploymentName); /** * List the NGINX configuration of given NGINX deployment. @@ -35,7 +35,7 @@ public interface Configurations { * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response of a list operation as paginated response with {@link PagedIterable}. */ - PagedIterable list(String resourceGroupName, String deploymentName, Context context); + PagedIterable list(String resourceGroupName, String deploymentName, Context context); /** * Get the NGINX configuration of given NGINX deployment. @@ -50,7 +50,7 @@ public interface Configurations { * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the NGINX configuration of given NGINX deployment along with {@link Response}. */ - Response getWithResponse(String resourceGroupName, String deploymentName, + Response getWithResponse(String resourceGroupName, String deploymentName, String configurationName, Context context); /** @@ -65,7 +65,7 @@ Response getWithResponse(String resourceGroupName, String de * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the NGINX configuration of given NGINX deployment. */ - NginxConfiguration get(String resourceGroupName, String deploymentName, String configurationName); + NginxConfigurationResponse get(String resourceGroupName, String deploymentName, String configurationName); /** * Reset the NGINX configuration of given NGINX deployment to default. @@ -134,7 +134,7 @@ Response analysisWithResponse(String resourceGroupName, String d * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the NGINX configuration of given NGINX deployment along with {@link Response}. */ - NginxConfiguration getById(String id); + NginxConfigurationResponse getById(String id); /** * Get the NGINX configuration of given NGINX deployment. @@ -146,7 +146,7 @@ Response analysisWithResponse(String resourceGroupName, String d * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the NGINX configuration of given NGINX deployment along with {@link Response}. */ - Response getByIdWithResponse(String id, Context context); + Response getByIdWithResponse(String id, Context context); /** * Reset the NGINX configuration of given NGINX deployment to default. @@ -170,10 +170,10 @@ Response analysisWithResponse(String resourceGroupName, String d void deleteByIdWithResponse(String id, Context context); /** - * Begins definition for a new NginxConfiguration resource. + * Begins definition for a new NginxConfigurationResponse resource. * * @param name resource name. - * @return the first stage of the new NginxConfiguration definition. + * @return the first stage of the new NginxConfigurationResponse definition. */ - NginxConfiguration.DefinitionStages.Blank define(String name); + NginxConfigurationResponse.DefinitionStages.Blank define(String name); } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/DiagnosticItem.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/DiagnosticItem.java new file mode 100644 index 000000000000..399736240f53 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/DiagnosticItem.java @@ -0,0 +1,346 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +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 diagnostic is a message associated with an NGINX config. The Analyzer returns diagnostics with a level indicating + * the importance of the diagnostic with optional category. + */ +@Fluent +public final class DiagnosticItem implements JsonSerializable { + /* + * Unique identifier for the diagnostic. + */ + private String id; + + /* + * The directive property. + */ + private String directive; + + /* + * The description property. + */ + private String description; + + /* + * The filepath of the most relevant config file. + */ + private String file; + + /* + * The line property. + */ + private float line; + + /* + * The message property. + */ + private String message; + + /* + * The rule property. + */ + private String rule; + + /* + * Warning or Info + */ + private Level level; + + /* + * Category of warning like Best-practices, Recommendation, Security etc. + */ + private String category; + + /** + * Creates an instance of DiagnosticItem class. + */ + public DiagnosticItem() { + } + + /** + * Get the id property: Unique identifier for the diagnostic. + * + * @return the id value. + */ + public String id() { + return this.id; + } + + /** + * Set the id property: Unique identifier for the diagnostic. + * + * @param id the id value to set. + * @return the DiagnosticItem object itself. + */ + public DiagnosticItem withId(String id) { + this.id = id; + return this; + } + + /** + * Get the directive property: The directive property. + * + * @return the directive value. + */ + public String directive() { + return this.directive; + } + + /** + * Set the directive property: The directive property. + * + * @param directive the directive value to set. + * @return the DiagnosticItem object itself. + */ + public DiagnosticItem withDirective(String directive) { + this.directive = directive; + return this; + } + + /** + * Get the description property: The description property. + * + * @return the description value. + */ + public String description() { + return this.description; + } + + /** + * Set the description property: The description property. + * + * @param description the description value to set. + * @return the DiagnosticItem object itself. + */ + public DiagnosticItem withDescription(String description) { + this.description = description; + return this; + } + + /** + * Get the file property: The filepath of the most relevant config file. + * + * @return the file value. + */ + public String file() { + return this.file; + } + + /** + * Set the file property: The filepath of the most relevant config file. + * + * @param file the file value to set. + * @return the DiagnosticItem object itself. + */ + public DiagnosticItem withFile(String file) { + this.file = file; + return this; + } + + /** + * Get the line property: The line property. + * + * @return the line value. + */ + public float line() { + return this.line; + } + + /** + * Set the line property: The line property. + * + * @param line the line value to set. + * @return the DiagnosticItem object itself. + */ + public DiagnosticItem withLine(float line) { + this.line = line; + return this; + } + + /** + * Get the message property: The message property. + * + * @return the message value. + */ + public String message() { + return this.message; + } + + /** + * Set the message property: The message property. + * + * @param message the message value to set. + * @return the DiagnosticItem object itself. + */ + public DiagnosticItem withMessage(String message) { + this.message = message; + return this; + } + + /** + * Get the rule property: The rule property. + * + * @return the rule value. + */ + public String rule() { + return this.rule; + } + + /** + * Set the rule property: The rule property. + * + * @param rule the rule value to set. + * @return the DiagnosticItem object itself. + */ + public DiagnosticItem withRule(String rule) { + this.rule = rule; + return this; + } + + /** + * Get the level property: Warning or Info. + * + * @return the level value. + */ + public Level level() { + return this.level; + } + + /** + * Set the level property: Warning or Info. + * + * @param level the level value to set. + * @return the DiagnosticItem object itself. + */ + public DiagnosticItem withLevel(Level level) { + this.level = level; + return this; + } + + /** + * Get the category property: Category of warning like Best-practices, Recommendation, Security etc. + * + * @return the category value. + */ + public String category() { + return this.category; + } + + /** + * Set the category property: Category of warning like Best-practices, Recommendation, Security etc. + * + * @param category the category value to set. + * @return the DiagnosticItem object itself. + */ + public DiagnosticItem withCategory(String category) { + this.category = category; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (directive() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property directive in model DiagnosticItem")); + } + if (description() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property description in model DiagnosticItem")); + } + if (file() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property file in model DiagnosticItem")); + } + if (message() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property message in model DiagnosticItem")); + } + if (rule() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property rule in model DiagnosticItem")); + } + if (level() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property level in model DiagnosticItem")); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(DiagnosticItem.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("directive", this.directive); + jsonWriter.writeStringField("description", this.description); + jsonWriter.writeStringField("file", this.file); + jsonWriter.writeFloatField("line", this.line); + jsonWriter.writeStringField("message", this.message); + jsonWriter.writeStringField("rule", this.rule); + jsonWriter.writeStringField("level", this.level == null ? null : this.level.toString()); + jsonWriter.writeStringField("id", this.id); + jsonWriter.writeStringField("category", this.category); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of DiagnosticItem from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of DiagnosticItem 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 DiagnosticItem. + */ + public static DiagnosticItem fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + DiagnosticItem deserializedDiagnosticItem = new DiagnosticItem(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("directive".equals(fieldName)) { + deserializedDiagnosticItem.directive = reader.getString(); + } else if ("description".equals(fieldName)) { + deserializedDiagnosticItem.description = reader.getString(); + } else if ("file".equals(fieldName)) { + deserializedDiagnosticItem.file = reader.getString(); + } else if ("line".equals(fieldName)) { + deserializedDiagnosticItem.line = reader.getFloat(); + } else if ("message".equals(fieldName)) { + deserializedDiagnosticItem.message = reader.getString(); + } else if ("rule".equals(fieldName)) { + deserializedDiagnosticItem.rule = reader.getString(); + } else if ("level".equals(fieldName)) { + deserializedDiagnosticItem.level = Level.fromString(reader.getString()); + } else if ("id".equals(fieldName)) { + deserializedDiagnosticItem.id = reader.getString(); + } else if ("category".equals(fieldName)) { + deserializedDiagnosticItem.category = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedDiagnosticItem; + }); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/Level.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/Level.java new file mode 100644 index 000000000000..6ceb7cc1a214 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/Level.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Warning or Info. + */ +public final class Level extends ExpandableStringEnum { + /** + * Static value Info for Level. + */ + public static final Level INFO = fromString("Info"); + + /** + * Static value Warning for Level. + */ + public static final Level WARNING = fromString("Warning"); + + /** + * Creates a new instance of Level value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public Level() { + } + + /** + * Creates or finds a Level from its string representation. + * + * @param name a name to look for. + * @return the corresponding Level. + */ + public static Level fromString(String name) { + return fromString(name, Level.class); + } + + /** + * Gets known Level values. + * + * @return known Level values. + */ + public static Collection values() { + return values(Level.class); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxConfiguration.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxConfiguration.java deleted file mode 100644 index 9dadd4569217..000000000000 --- a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxConfiguration.java +++ /dev/null @@ -1,254 +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.resourcemanager.nginx.models; - -import com.azure.core.http.rest.Response; -import com.azure.core.management.Region; -import com.azure.core.management.SystemData; -import com.azure.core.util.Context; -import com.azure.resourcemanager.nginx.fluent.models.NginxConfigurationInner; - -/** - * An immutable client-side representation of NginxConfiguration. - */ -public interface NginxConfiguration { - /** - * Gets the id property: Fully qualified resource Id for the resource. - * - * @return the id value. - */ - String id(); - - /** - * Gets the name property: The name of the resource. - * - * @return the name value. - */ - String name(); - - /** - * Gets the type property: The type of the resource. - * - * @return the type value. - */ - String type(); - - /** - * Gets the properties property: The properties property. - * - * @return the properties value. - */ - NginxConfigurationProperties properties(); - - /** - * Gets the location property: The location property. - * - * @return the location value. - */ - String location(); - - /** - * Gets the systemData property: Metadata pertaining to creation and last modification of the resource. - * - * @return the systemData value. - */ - SystemData systemData(); - - /** - * Gets the region of the resource. - * - * @return the region of the resource. - */ - Region region(); - - /** - * Gets the name of the resource region. - * - * @return the name of the resource region. - */ - String regionName(); - - /** - * Gets the name of the resource group. - * - * @return the name of the resource group. - */ - String resourceGroupName(); - - /** - * Gets the inner com.azure.resourcemanager.nginx.fluent.models.NginxConfigurationInner object. - * - * @return the inner object. - */ - NginxConfigurationInner innerModel(); - - /** - * The entirety of the NginxConfiguration definition. - */ - interface Definition - extends DefinitionStages.Blank, DefinitionStages.WithParentResource, DefinitionStages.WithCreate { - } - - /** - * The NginxConfiguration definition stages. - */ - interface DefinitionStages { - /** - * The first stage of the NginxConfiguration definition. - */ - interface Blank extends WithParentResource { - } - - /** - * The stage of the NginxConfiguration definition allowing to specify parent resource. - */ - interface WithParentResource { - /** - * Specifies resourceGroupName, deploymentName. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param deploymentName The name of targeted NGINX deployment. - * @return the next definition stage. - */ - WithCreate withExistingNginxDeployment(String resourceGroupName, String deploymentName); - } - - /** - * The stage of the NginxConfiguration definition which contains all the minimum required properties for the - * resource to be created, but also allows for any other optional properties to be specified. - */ - interface WithCreate extends DefinitionStages.WithLocation, DefinitionStages.WithProperties { - /** - * Executes the create request. - * - * @return the created resource. - */ - NginxConfiguration create(); - - /** - * Executes the create request. - * - * @param context The context to associate with this operation. - * @return the created resource. - */ - NginxConfiguration create(Context context); - } - - /** - * The stage of the NginxConfiguration definition allowing to specify location. - */ - interface WithLocation { - /** - * Specifies the region for the resource. - * - * @param location The location property. - * @return the next definition stage. - */ - WithCreate withRegion(Region location); - - /** - * Specifies the region for the resource. - * - * @param location The location property. - * @return the next definition stage. - */ - WithCreate withRegion(String location); - } - - /** - * The stage of the NginxConfiguration definition allowing to specify properties. - */ - interface WithProperties { - /** - * Specifies the properties property: The properties property.. - * - * @param properties The properties property. - * @return the next definition stage. - */ - WithCreate withProperties(NginxConfigurationProperties properties); - } - } - - /** - * Begins update for the NginxConfiguration resource. - * - * @return the stage of resource update. - */ - NginxConfiguration.Update update(); - - /** - * The template for NginxConfiguration update. - */ - interface Update extends UpdateStages.WithProperties { - /** - * Executes the update request. - * - * @return the updated resource. - */ - NginxConfiguration apply(); - - /** - * Executes the update request. - * - * @param context The context to associate with this operation. - * @return the updated resource. - */ - NginxConfiguration apply(Context context); - } - - /** - * The NginxConfiguration update stages. - */ - interface UpdateStages { - /** - * The stage of the NginxConfiguration update allowing to specify properties. - */ - interface WithProperties { - /** - * Specifies the properties property: The properties property.. - * - * @param properties The properties property. - * @return the next definition stage. - */ - Update withProperties(NginxConfigurationProperties properties); - } - } - - /** - * Refreshes the resource to sync with Azure. - * - * @return the refreshed resource. - */ - NginxConfiguration refresh(); - - /** - * Refreshes the resource to sync with Azure. - * - * @param context The context to associate with this operation. - * @return the refreshed resource. - */ - NginxConfiguration refresh(Context context); - - /** - * Analyze an NGINX configuration without applying it to the NGINXaaS deployment. - * - * @param body The NGINX configuration to analyze. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response body for an analysis request along with {@link Response}. - */ - Response analysisWithResponse(AnalysisCreate body, Context context); - - /** - * Analyze an NGINX configuration without applying it to the NGINXaaS deployment. - * - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response body for an analysis request. - */ - AnalysisResult analysis(); -} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxConfigurationListResponse.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxConfigurationListResponse.java index 5e325d00d981..9e7889a84e27 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxConfigurationListResponse.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxConfigurationListResponse.java @@ -9,7 +9,7 @@ import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.azure.resourcemanager.nginx.fluent.models.NginxConfigurationInner; +import com.azure.resourcemanager.nginx.fluent.models.NginxConfigurationResponseInner; import java.io.IOException; import java.util.List; @@ -21,7 +21,7 @@ public final class NginxConfigurationListResponse implements JsonSerializable value; + private List value; /* * Link to the next set of results, if any. @@ -39,7 +39,7 @@ public NginxConfigurationListResponse() { * * @return the value value. */ - public List value() { + public List value() { return this.value; } @@ -49,7 +49,7 @@ public List value() { * @param value the value value to set. * @return the NginxConfigurationListResponse object itself. */ - public NginxConfigurationListResponse withValue(List value) { + public NginxConfigurationListResponse withValue(List value) { this.value = value; return this; } @@ -113,8 +113,8 @@ public static NginxConfigurationListResponse fromJson(JsonReader jsonReader) thr reader.nextToken(); if ("value".equals(fieldName)) { - List value - = reader.readArray(reader1 -> NginxConfigurationInner.fromJson(reader1)); + List value + = reader.readArray(reader1 -> NginxConfigurationResponseInner.fromJson(reader1)); deserializedNginxConfigurationListResponse.value = value; } else if ("nextLink".equals(fieldName)) { deserializedNginxConfigurationListResponse.nextLink = reader.getString(); diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxConfigurationProperties.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxConfigurationProperties.java deleted file mode 100644 index 392e091d6004..000000000000 --- a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxConfigurationProperties.java +++ /dev/null @@ -1,210 +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.resourcemanager.nginx.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.List; - -/** - * The NginxConfigurationProperties model. - */ -@Fluent -public final class NginxConfigurationProperties implements JsonSerializable { - /* - * The provisioningState property. - */ - private ProvisioningState provisioningState; - - /* - * The files property. - */ - private List files; - - /* - * The protectedFiles property. - */ - private List protectedFiles; - - /* - * The package property. - */ - private NginxConfigurationPackage packageProperty; - - /* - * The rootFile property. - */ - private String rootFile; - - /** - * Creates an instance of NginxConfigurationProperties class. - */ - public NginxConfigurationProperties() { - } - - /** - * Get the provisioningState property: The provisioningState property. - * - * @return the provisioningState value. - */ - public ProvisioningState provisioningState() { - return this.provisioningState; - } - - /** - * Get the files property: The files property. - * - * @return the files value. - */ - public List files() { - return this.files; - } - - /** - * Set the files property: The files property. - * - * @param files the files value to set. - * @return the NginxConfigurationProperties object itself. - */ - public NginxConfigurationProperties withFiles(List files) { - this.files = files; - return this; - } - - /** - * Get the protectedFiles property: The protectedFiles property. - * - * @return the protectedFiles value. - */ - public List protectedFiles() { - return this.protectedFiles; - } - - /** - * Set the protectedFiles property: The protectedFiles property. - * - * @param protectedFiles the protectedFiles value to set. - * @return the NginxConfigurationProperties object itself. - */ - public NginxConfigurationProperties withProtectedFiles(List protectedFiles) { - this.protectedFiles = protectedFiles; - return this; - } - - /** - * Get the packageProperty property: The package property. - * - * @return the packageProperty value. - */ - public NginxConfigurationPackage packageProperty() { - return this.packageProperty; - } - - /** - * Set the packageProperty property: The package property. - * - * @param packageProperty the packageProperty value to set. - * @return the NginxConfigurationProperties object itself. - */ - public NginxConfigurationProperties withPackageProperty(NginxConfigurationPackage packageProperty) { - this.packageProperty = packageProperty; - return this; - } - - /** - * Get the rootFile property: The rootFile property. - * - * @return the rootFile value. - */ - public String rootFile() { - return this.rootFile; - } - - /** - * Set the rootFile property: The rootFile property. - * - * @param rootFile the rootFile value to set. - * @return the NginxConfigurationProperties object itself. - */ - public NginxConfigurationProperties withRootFile(String rootFile) { - this.rootFile = rootFile; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (files() != null) { - files().forEach(e -> e.validate()); - } - if (protectedFiles() != null) { - protectedFiles().forEach(e -> e.validate()); - } - if (packageProperty() != null) { - packageProperty().validate(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeArrayField("files", this.files, (writer, element) -> writer.writeJson(element)); - jsonWriter.writeArrayField("protectedFiles", this.protectedFiles, - (writer, element) -> writer.writeJson(element)); - jsonWriter.writeJsonField("package", this.packageProperty); - jsonWriter.writeStringField("rootFile", this.rootFile); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of NginxConfigurationProperties from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of NginxConfigurationProperties 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 NginxConfigurationProperties. - */ - public static NginxConfigurationProperties fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - NginxConfigurationProperties deserializedNginxConfigurationProperties = new NginxConfigurationProperties(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("provisioningState".equals(fieldName)) { - deserializedNginxConfigurationProperties.provisioningState - = ProvisioningState.fromString(reader.getString()); - } else if ("files".equals(fieldName)) { - List files - = reader.readArray(reader1 -> NginxConfigurationFile.fromJson(reader1)); - deserializedNginxConfigurationProperties.files = files; - } else if ("protectedFiles".equals(fieldName)) { - List protectedFiles - = reader.readArray(reader1 -> NginxConfigurationFile.fromJson(reader1)); - deserializedNginxConfigurationProperties.protectedFiles = protectedFiles; - } else if ("package".equals(fieldName)) { - deserializedNginxConfigurationProperties.packageProperty - = NginxConfigurationPackage.fromJson(reader); - } else if ("rootFile".equals(fieldName)) { - deserializedNginxConfigurationProperties.rootFile = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedNginxConfigurationProperties; - }); - } -} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxConfigurationProtectedFileRequest.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxConfigurationProtectedFileRequest.java new file mode 100644 index 000000000000..d66eb577e2a7 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxConfigurationProtectedFileRequest.java @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.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; + +/** + * The NginxConfigurationProtectedFileRequest model. + */ +@Fluent +public final class NginxConfigurationProtectedFileRequest + implements JsonSerializable { + /* + * The content of the protected file. This value is a PUT only value. If you perform a GET request on this value, it + * will be empty because it is a protected file. + */ + private String content; + + /* + * The virtual path of the protected file. + */ + private String virtualPath; + + /* + * The hash of the content of the file. This value is used to determine if the file has changed. + */ + private String contentHash; + + /** + * Creates an instance of NginxConfigurationProtectedFileRequest class. + */ + public NginxConfigurationProtectedFileRequest() { + } + + /** + * Get the content property: The content of the protected file. This value is a PUT only value. If you perform a GET + * request on this value, it will be empty because it is a protected file. + * + * @return the content value. + */ + public String content() { + return this.content; + } + + /** + * Set the content property: The content of the protected file. This value is a PUT only value. If you perform a GET + * request on this value, it will be empty because it is a protected file. + * + * @param content the content value to set. + * @return the NginxConfigurationProtectedFileRequest object itself. + */ + public NginxConfigurationProtectedFileRequest withContent(String content) { + this.content = content; + return this; + } + + /** + * Get the virtualPath property: The virtual path of the protected file. + * + * @return the virtualPath value. + */ + public String virtualPath() { + return this.virtualPath; + } + + /** + * Set the virtualPath property: The virtual path of the protected file. + * + * @param virtualPath the virtualPath value to set. + * @return the NginxConfigurationProtectedFileRequest object itself. + */ + public NginxConfigurationProtectedFileRequest withVirtualPath(String virtualPath) { + this.virtualPath = virtualPath; + return this; + } + + /** + * Get the contentHash property: The hash of the content of the file. This value is used to determine if the file + * has changed. + * + * @return the contentHash value. + */ + public String contentHash() { + return this.contentHash; + } + + /** + * Set the contentHash property: The hash of the content of the file. This value is used to determine if the file + * has changed. + * + * @param contentHash the contentHash value to set. + * @return the NginxConfigurationProtectedFileRequest object itself. + */ + public NginxConfigurationProtectedFileRequest withContentHash(String contentHash) { + this.contentHash = contentHash; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("content", this.content); + jsonWriter.writeStringField("virtualPath", this.virtualPath); + jsonWriter.writeStringField("contentHash", this.contentHash); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of NginxConfigurationProtectedFileRequest from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of NginxConfigurationProtectedFileRequest 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 NginxConfigurationProtectedFileRequest. + */ + public static NginxConfigurationProtectedFileRequest fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + NginxConfigurationProtectedFileRequest deserializedNginxConfigurationProtectedFileRequest + = new NginxConfigurationProtectedFileRequest(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("content".equals(fieldName)) { + deserializedNginxConfigurationProtectedFileRequest.content = reader.getString(); + } else if ("virtualPath".equals(fieldName)) { + deserializedNginxConfigurationProtectedFileRequest.virtualPath = reader.getString(); + } else if ("contentHash".equals(fieldName)) { + deserializedNginxConfigurationProtectedFileRequest.contentHash = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedNginxConfigurationProtectedFileRequest; + }); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxConfigurationProtectedFileResponse.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxConfigurationProtectedFileResponse.java new file mode 100644 index 000000000000..29704220e9ec --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxConfigurationProtectedFileResponse.java @@ -0,0 +1,125 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.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; + +/** + * The NginxConfigurationProtectedFileResponse model. + */ +@Fluent +public final class NginxConfigurationProtectedFileResponse + implements JsonSerializable { + /* + * The virtual path of the protected file. + */ + private String virtualPath; + + /* + * The hash of the content of the file. This value is used to determine if the file has changed. + */ + private String contentHash; + + /** + * Creates an instance of NginxConfigurationProtectedFileResponse class. + */ + public NginxConfigurationProtectedFileResponse() { + } + + /** + * Get the virtualPath property: The virtual path of the protected file. + * + * @return the virtualPath value. + */ + public String virtualPath() { + return this.virtualPath; + } + + /** + * Set the virtualPath property: The virtual path of the protected file. + * + * @param virtualPath the virtualPath value to set. + * @return the NginxConfigurationProtectedFileResponse object itself. + */ + public NginxConfigurationProtectedFileResponse withVirtualPath(String virtualPath) { + this.virtualPath = virtualPath; + return this; + } + + /** + * Get the contentHash property: The hash of the content of the file. This value is used to determine if the file + * has changed. + * + * @return the contentHash value. + */ + public String contentHash() { + return this.contentHash; + } + + /** + * Set the contentHash property: The hash of the content of the file. This value is used to determine if the file + * has changed. + * + * @param contentHash the contentHash value to set. + * @return the NginxConfigurationProtectedFileResponse object itself. + */ + public NginxConfigurationProtectedFileResponse withContentHash(String contentHash) { + this.contentHash = contentHash; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("virtualPath", this.virtualPath); + jsonWriter.writeStringField("contentHash", this.contentHash); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of NginxConfigurationProtectedFileResponse from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of NginxConfigurationProtectedFileResponse 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 NginxConfigurationProtectedFileResponse. + */ + public static NginxConfigurationProtectedFileResponse fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + NginxConfigurationProtectedFileResponse deserializedNginxConfigurationProtectedFileResponse + = new NginxConfigurationProtectedFileResponse(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("virtualPath".equals(fieldName)) { + deserializedNginxConfigurationProtectedFileResponse.virtualPath = reader.getString(); + } else if ("contentHash".equals(fieldName)) { + deserializedNginxConfigurationProtectedFileResponse.contentHash = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedNginxConfigurationProtectedFileResponse; + }); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxConfigurationRequest.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxConfigurationRequest.java new file mode 100644 index 000000000000..663283221b76 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxConfigurationRequest.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. + +package com.azure.resourcemanager.nginx.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * The NginxConfigurationRequest model. + */ +@Fluent +public final class NginxConfigurationRequest extends ProxyResource { + /* + * The properties property. + */ + private NginxConfigurationRequestProperties properties; + + /* + * Metadata pertaining to creation and last modification of the resource. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of NginxConfigurationRequest class. + */ + public NginxConfigurationRequest() { + } + + /** + * Get the properties property: The properties property. + * + * @return the properties value. + */ + public NginxConfigurationRequestProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The properties property. + * + * @param properties the properties value to set. + * @return the NginxConfigurationRequest object itself. + */ + public NginxConfigurationRequest withProperties(NginxConfigurationRequestProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Metadata pertaining to creation and last modification of the resource. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of NginxConfigurationRequest from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of NginxConfigurationRequest 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 NginxConfigurationRequest. + */ + public static NginxConfigurationRequest fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + NginxConfigurationRequest deserializedNginxConfigurationRequest = new NginxConfigurationRequest(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedNginxConfigurationRequest.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedNginxConfigurationRequest.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedNginxConfigurationRequest.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedNginxConfigurationRequest.properties + = NginxConfigurationRequestProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedNginxConfigurationRequest.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedNginxConfigurationRequest; + }); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxConfigurationRequestProperties.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxConfigurationRequestProperties.java new file mode 100644 index 000000000000..26a3b66cbbf5 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxConfigurationRequestProperties.java @@ -0,0 +1,213 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.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.List; + +/** + * The NginxConfigurationRequestProperties model. + */ +@Fluent +public final class NginxConfigurationRequestProperties + implements JsonSerializable { + /* + * The provisioningState property. + */ + private ProvisioningState provisioningState; + + /* + * The files property. + */ + private List files; + + /* + * The protectedFiles property. + */ + private List protectedFiles; + + /* + * The package property. + */ + private NginxConfigurationPackage packageProperty; + + /* + * The rootFile property. + */ + private String rootFile; + + /** + * Creates an instance of NginxConfigurationRequestProperties class. + */ + public NginxConfigurationRequestProperties() { + } + + /** + * Get the provisioningState property: The provisioningState property. + * + * @return the provisioningState value. + */ + public ProvisioningState provisioningState() { + return this.provisioningState; + } + + /** + * Get the files property: The files property. + * + * @return the files value. + */ + public List files() { + return this.files; + } + + /** + * Set the files property: The files property. + * + * @param files the files value to set. + * @return the NginxConfigurationRequestProperties object itself. + */ + public NginxConfigurationRequestProperties withFiles(List files) { + this.files = files; + return this; + } + + /** + * Get the protectedFiles property: The protectedFiles property. + * + * @return the protectedFiles value. + */ + public List protectedFiles() { + return this.protectedFiles; + } + + /** + * Set the protectedFiles property: The protectedFiles property. + * + * @param protectedFiles the protectedFiles value to set. + * @return the NginxConfigurationRequestProperties object itself. + */ + public NginxConfigurationRequestProperties + withProtectedFiles(List protectedFiles) { + this.protectedFiles = protectedFiles; + return this; + } + + /** + * Get the packageProperty property: The package property. + * + * @return the packageProperty value. + */ + public NginxConfigurationPackage packageProperty() { + return this.packageProperty; + } + + /** + * Set the packageProperty property: The package property. + * + * @param packageProperty the packageProperty value to set. + * @return the NginxConfigurationRequestProperties object itself. + */ + public NginxConfigurationRequestProperties withPackageProperty(NginxConfigurationPackage packageProperty) { + this.packageProperty = packageProperty; + return this; + } + + /** + * Get the rootFile property: The rootFile property. + * + * @return the rootFile value. + */ + public String rootFile() { + return this.rootFile; + } + + /** + * Set the rootFile property: The rootFile property. + * + * @param rootFile the rootFile value to set. + * @return the NginxConfigurationRequestProperties object itself. + */ + public NginxConfigurationRequestProperties withRootFile(String rootFile) { + this.rootFile = rootFile; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (files() != null) { + files().forEach(e -> e.validate()); + } + if (protectedFiles() != null) { + protectedFiles().forEach(e -> e.validate()); + } + if (packageProperty() != null) { + packageProperty().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("files", this.files, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeArrayField("protectedFiles", this.protectedFiles, + (writer, element) -> writer.writeJson(element)); + jsonWriter.writeJsonField("package", this.packageProperty); + jsonWriter.writeStringField("rootFile", this.rootFile); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of NginxConfigurationRequestProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of NginxConfigurationRequestProperties 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 NginxConfigurationRequestProperties. + */ + public static NginxConfigurationRequestProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + NginxConfigurationRequestProperties deserializedNginxConfigurationRequestProperties + = new NginxConfigurationRequestProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("provisioningState".equals(fieldName)) { + deserializedNginxConfigurationRequestProperties.provisioningState + = ProvisioningState.fromString(reader.getString()); + } else if ("files".equals(fieldName)) { + List files + = reader.readArray(reader1 -> NginxConfigurationFile.fromJson(reader1)); + deserializedNginxConfigurationRequestProperties.files = files; + } else if ("protectedFiles".equals(fieldName)) { + List protectedFiles + = reader.readArray(reader1 -> NginxConfigurationProtectedFileRequest.fromJson(reader1)); + deserializedNginxConfigurationRequestProperties.protectedFiles = protectedFiles; + } else if ("package".equals(fieldName)) { + deserializedNginxConfigurationRequestProperties.packageProperty + = NginxConfigurationPackage.fromJson(reader); + } else if ("rootFile".equals(fieldName)) { + deserializedNginxConfigurationRequestProperties.rootFile = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedNginxConfigurationRequestProperties; + }); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxConfigurationResponse.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxConfigurationResponse.java new file mode 100644 index 000000000000..4033ef9df6c2 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxConfigurationResponse.java @@ -0,0 +1,211 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.models; + +import com.azure.core.http.rest.Response; +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.nginx.fluent.models.NginxConfigurationResponseInner; + +/** + * An immutable client-side representation of NginxConfigurationResponse. + */ +public interface NginxConfigurationResponse { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The properties property. + * + * @return the properties value. + */ + NginxConfigurationResponseProperties properties(); + + /** + * Gets the systemData property: Metadata pertaining to creation and last modification of the resource. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the name of the resource group. + * + * @return the name of the resource group. + */ + String resourceGroupName(); + + /** + * Gets the inner com.azure.resourcemanager.nginx.fluent.models.NginxConfigurationResponseInner object. + * + * @return the inner object. + */ + NginxConfigurationResponseInner innerModel(); + + /** + * The entirety of the NginxConfigurationResponse definition. + */ + interface Definition + extends DefinitionStages.Blank, DefinitionStages.WithParentResource, DefinitionStages.WithCreate { + } + + /** + * The NginxConfigurationResponse definition stages. + */ + interface DefinitionStages { + /** + * The first stage of the NginxConfigurationResponse definition. + */ + interface Blank extends WithParentResource { + } + + /** + * The stage of the NginxConfigurationResponse definition allowing to specify parent resource. + */ + interface WithParentResource { + /** + * Specifies resourceGroupName, deploymentName. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @return the next definition stage. + */ + WithCreate withExistingNginxDeployment(String resourceGroupName, String deploymentName); + } + + /** + * The stage of the NginxConfigurationResponse definition which contains all the minimum required properties for + * the resource to be created, but also allows for any other optional properties to be specified. + */ + interface WithCreate extends DefinitionStages.WithProperties { + /** + * Executes the create request. + * + * @return the created resource. + */ + NginxConfigurationResponse create(); + + /** + * Executes the create request. + * + * @param context The context to associate with this operation. + * @return the created resource. + */ + NginxConfigurationResponse create(Context context); + } + + /** + * The stage of the NginxConfigurationResponse definition allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The properties property.. + * + * @param properties The properties property. + * @return the next definition stage. + */ + WithCreate withProperties(NginxConfigurationRequestProperties properties); + } + } + + /** + * Begins update for the NginxConfigurationResponse resource. + * + * @return the stage of resource update. + */ + NginxConfigurationResponse.Update update(); + + /** + * The template for NginxConfigurationResponse update. + */ + interface Update extends UpdateStages.WithProperties { + /** + * Executes the update request. + * + * @return the updated resource. + */ + NginxConfigurationResponse apply(); + + /** + * Executes the update request. + * + * @param context The context to associate with this operation. + * @return the updated resource. + */ + NginxConfigurationResponse apply(Context context); + } + + /** + * The NginxConfigurationResponse update stages. + */ + interface UpdateStages { + /** + * The stage of the NginxConfigurationResponse update allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The properties property.. + * + * @param properties The properties property. + * @return the next definition stage. + */ + Update withProperties(NginxConfigurationRequestProperties properties); + } + } + + /** + * Refreshes the resource to sync with Azure. + * + * @return the refreshed resource. + */ + NginxConfigurationResponse refresh(); + + /** + * Refreshes the resource to sync with Azure. + * + * @param context The context to associate with this operation. + * @return the refreshed resource. + */ + NginxConfigurationResponse refresh(Context context); + + /** + * Analyze an NGINX configuration without applying it to the NGINXaaS deployment. + * + * @param body The NGINX configuration to analyze. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body for an analysis request along with {@link Response}. + */ + Response analysisWithResponse(AnalysisCreate body, Context context); + + /** + * Analyze an NGINX configuration without applying it to the NGINXaaS deployment. + * + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body for an analysis request. + */ + AnalysisResult analysis(); +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxConfigurationResponseProperties.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxConfigurationResponseProperties.java new file mode 100644 index 000000000000..0d8977b17c2a --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxConfigurationResponseProperties.java @@ -0,0 +1,213 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.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.List; + +/** + * The NginxConfigurationResponseProperties model. + */ +@Fluent +public final class NginxConfigurationResponseProperties + implements JsonSerializable { + /* + * The provisioningState property. + */ + private ProvisioningState provisioningState; + + /* + * The files property. + */ + private List files; + + /* + * The protectedFiles property. + */ + private List protectedFiles; + + /* + * The package property. + */ + private NginxConfigurationPackage packageProperty; + + /* + * The rootFile property. + */ + private String rootFile; + + /** + * Creates an instance of NginxConfigurationResponseProperties class. + */ + public NginxConfigurationResponseProperties() { + } + + /** + * Get the provisioningState property: The provisioningState property. + * + * @return the provisioningState value. + */ + public ProvisioningState provisioningState() { + return this.provisioningState; + } + + /** + * Get the files property: The files property. + * + * @return the files value. + */ + public List files() { + return this.files; + } + + /** + * Set the files property: The files property. + * + * @param files the files value to set. + * @return the NginxConfigurationResponseProperties object itself. + */ + public NginxConfigurationResponseProperties withFiles(List files) { + this.files = files; + return this; + } + + /** + * Get the protectedFiles property: The protectedFiles property. + * + * @return the protectedFiles value. + */ + public List protectedFiles() { + return this.protectedFiles; + } + + /** + * Set the protectedFiles property: The protectedFiles property. + * + * @param protectedFiles the protectedFiles value to set. + * @return the NginxConfigurationResponseProperties object itself. + */ + public NginxConfigurationResponseProperties + withProtectedFiles(List protectedFiles) { + this.protectedFiles = protectedFiles; + return this; + } + + /** + * Get the packageProperty property: The package property. + * + * @return the packageProperty value. + */ + public NginxConfigurationPackage packageProperty() { + return this.packageProperty; + } + + /** + * Set the packageProperty property: The package property. + * + * @param packageProperty the packageProperty value to set. + * @return the NginxConfigurationResponseProperties object itself. + */ + public NginxConfigurationResponseProperties withPackageProperty(NginxConfigurationPackage packageProperty) { + this.packageProperty = packageProperty; + return this; + } + + /** + * Get the rootFile property: The rootFile property. + * + * @return the rootFile value. + */ + public String rootFile() { + return this.rootFile; + } + + /** + * Set the rootFile property: The rootFile property. + * + * @param rootFile the rootFile value to set. + * @return the NginxConfigurationResponseProperties object itself. + */ + public NginxConfigurationResponseProperties withRootFile(String rootFile) { + this.rootFile = rootFile; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (files() != null) { + files().forEach(e -> e.validate()); + } + if (protectedFiles() != null) { + protectedFiles().forEach(e -> e.validate()); + } + if (packageProperty() != null) { + packageProperty().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("files", this.files, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeArrayField("protectedFiles", this.protectedFiles, + (writer, element) -> writer.writeJson(element)); + jsonWriter.writeJsonField("package", this.packageProperty); + jsonWriter.writeStringField("rootFile", this.rootFile); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of NginxConfigurationResponseProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of NginxConfigurationResponseProperties 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 NginxConfigurationResponseProperties. + */ + public static NginxConfigurationResponseProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + NginxConfigurationResponseProperties deserializedNginxConfigurationResponseProperties + = new NginxConfigurationResponseProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("provisioningState".equals(fieldName)) { + deserializedNginxConfigurationResponseProperties.provisioningState + = ProvisioningState.fromString(reader.getString()); + } else if ("files".equals(fieldName)) { + List files + = reader.readArray(reader1 -> NginxConfigurationFile.fromJson(reader1)); + deserializedNginxConfigurationResponseProperties.files = files; + } else if ("protectedFiles".equals(fieldName)) { + List protectedFiles + = reader.readArray(reader1 -> NginxConfigurationProtectedFileResponse.fromJson(reader1)); + deserializedNginxConfigurationResponseProperties.protectedFiles = protectedFiles; + } else if ("package".equals(fieldName)) { + deserializedNginxConfigurationResponseProperties.packageProperty + = NginxConfigurationPackage.fromJson(reader); + } else if ("rootFile".equals(fieldName)) { + deserializedNginxConfigurationResponseProperties.rootFile = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedNginxConfigurationResponseProperties; + }); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxDeploymentApiKeyListResponse.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxDeploymentApiKeyListResponse.java new file mode 100644 index 000000000000..8a83b6f42ca9 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxDeploymentApiKeyListResponse.java @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.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.resourcemanager.nginx.fluent.models.NginxDeploymentApiKeyResponseInner; +import java.io.IOException; +import java.util.List; + +/** + * The NginxDeploymentApiKeyListResponse model. + */ +@Fluent +public final class NginxDeploymentApiKeyListResponse implements JsonSerializable { + /* + * The value property. + */ + private List value; + + /* + * The nextLink property. + */ + private String nextLink; + + /** + * Creates an instance of NginxDeploymentApiKeyListResponse class. + */ + public NginxDeploymentApiKeyListResponse() { + } + + /** + * Get the value property: The value property. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Set the value property: The value property. + * + * @param value the value value to set. + * @return the NginxDeploymentApiKeyListResponse object itself. + */ + public NginxDeploymentApiKeyListResponse withValue(List value) { + this.value = value; + return this; + } + + /** + * Get the nextLink property: The nextLink property. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Set the nextLink property: The nextLink property. + * + * @param nextLink the nextLink value to set. + * @return the NginxDeploymentApiKeyListResponse object itself. + */ + public NginxDeploymentApiKeyListResponse withNextLink(String nextLink) { + this.nextLink = nextLink; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() != null) { + value().forEach(e -> e.validate()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of NginxDeploymentApiKeyListResponse from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of NginxDeploymentApiKeyListResponse 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 NginxDeploymentApiKeyListResponse. + */ + public static NginxDeploymentApiKeyListResponse fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + NginxDeploymentApiKeyListResponse deserializedNginxDeploymentApiKeyListResponse + = new NginxDeploymentApiKeyListResponse(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> NginxDeploymentApiKeyResponseInner.fromJson(reader1)); + deserializedNginxDeploymentApiKeyListResponse.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedNginxDeploymentApiKeyListResponse.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedNginxDeploymentApiKeyListResponse; + }); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxDeploymentApiKeyRequest.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxDeploymentApiKeyRequest.java new file mode 100644 index 000000000000..9620b8a05044 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxDeploymentApiKeyRequest.java @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * The NginxDeploymentApiKeyRequest model. + */ +@Fluent +public final class NginxDeploymentApiKeyRequest extends ProxyResource { + /* + * The properties property. + */ + private NginxDeploymentApiKeyRequestProperties properties; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of NginxDeploymentApiKeyRequest class. + */ + public NginxDeploymentApiKeyRequest() { + } + + /** + * Get the properties property: The properties property. + * + * @return the properties value. + */ + public NginxDeploymentApiKeyRequestProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The properties property. + * + * @param properties the properties value to set. + * @return the NginxDeploymentApiKeyRequest object itself. + */ + public NginxDeploymentApiKeyRequest withProperties(NginxDeploymentApiKeyRequestProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of NginxDeploymentApiKeyRequest from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of NginxDeploymentApiKeyRequest 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 NginxDeploymentApiKeyRequest. + */ + public static NginxDeploymentApiKeyRequest fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + NginxDeploymentApiKeyRequest deserializedNginxDeploymentApiKeyRequest = new NginxDeploymentApiKeyRequest(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedNginxDeploymentApiKeyRequest.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedNginxDeploymentApiKeyRequest.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedNginxDeploymentApiKeyRequest.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedNginxDeploymentApiKeyRequest.properties + = NginxDeploymentApiKeyRequestProperties.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedNginxDeploymentApiKeyRequest; + }); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxDeploymentApiKeyRequestProperties.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxDeploymentApiKeyRequestProperties.java new file mode 100644 index 000000000000..6f0267f43088 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxDeploymentApiKeyRequestProperties.java @@ -0,0 +1,131 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * The NginxDeploymentApiKeyRequestProperties model. + */ +@Fluent +public final class NginxDeploymentApiKeyRequestProperties + implements JsonSerializable { + /* + * Secret text to be used as a Dataplane API Key. This is a write only property that can never be read back, but the + * first three characters will be returned in the 'hint' property. + */ + private String secretText; + + /* + * The time after which this Dataplane API Key is no longer valid. + */ + private OffsetDateTime endDateTime; + + /** + * Creates an instance of NginxDeploymentApiKeyRequestProperties class. + */ + public NginxDeploymentApiKeyRequestProperties() { + } + + /** + * Get the secretText property: Secret text to be used as a Dataplane API Key. This is a write only property that + * can never be read back, but the first three characters will be returned in the 'hint' property. + * + * @return the secretText value. + */ + public String secretText() { + return this.secretText; + } + + /** + * Set the secretText property: Secret text to be used as a Dataplane API Key. This is a write only property that + * can never be read back, but the first three characters will be returned in the 'hint' property. + * + * @param secretText the secretText value to set. + * @return the NginxDeploymentApiKeyRequestProperties object itself. + */ + public NginxDeploymentApiKeyRequestProperties withSecretText(String secretText) { + this.secretText = secretText; + return this; + } + + /** + * Get the endDateTime property: The time after which this Dataplane API Key is no longer valid. + * + * @return the endDateTime value. + */ + public OffsetDateTime endDateTime() { + return this.endDateTime; + } + + /** + * Set the endDateTime property: The time after which this Dataplane API Key is no longer valid. + * + * @param endDateTime the endDateTime value to set. + * @return the NginxDeploymentApiKeyRequestProperties object itself. + */ + public NginxDeploymentApiKeyRequestProperties withEndDateTime(OffsetDateTime endDateTime) { + this.endDateTime = endDateTime; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("secretText", this.secretText); + jsonWriter.writeStringField("endDateTime", + this.endDateTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.endDateTime)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of NginxDeploymentApiKeyRequestProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of NginxDeploymentApiKeyRequestProperties 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 NginxDeploymentApiKeyRequestProperties. + */ + public static NginxDeploymentApiKeyRequestProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + NginxDeploymentApiKeyRequestProperties deserializedNginxDeploymentApiKeyRequestProperties + = new NginxDeploymentApiKeyRequestProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("secretText".equals(fieldName)) { + deserializedNginxDeploymentApiKeyRequestProperties.secretText = reader.getString(); + } else if ("endDateTime".equals(fieldName)) { + deserializedNginxDeploymentApiKeyRequestProperties.endDateTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else { + reader.skipChildren(); + } + } + + return deserializedNginxDeploymentApiKeyRequestProperties; + }); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxDeploymentApiKeyResponse.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxDeploymentApiKeyResponse.java new file mode 100644 index 000000000000..495111fb4f98 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxDeploymentApiKeyResponse.java @@ -0,0 +1,181 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.models; + +import com.azure.core.util.Context; +import com.azure.resourcemanager.nginx.fluent.models.NginxDeploymentApiKeyResponseInner; + +/** + * An immutable client-side representation of NginxDeploymentApiKeyResponse. + */ +public interface NginxDeploymentApiKeyResponse { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the properties property: The properties property. + * + * @return the properties value. + */ + NginxDeploymentApiKeyResponseProperties properties(); + + /** + * Gets the name of the resource group. + * + * @return the name of the resource group. + */ + String resourceGroupName(); + + /** + * Gets the inner com.azure.resourcemanager.nginx.fluent.models.NginxDeploymentApiKeyResponseInner object. + * + * @return the inner object. + */ + NginxDeploymentApiKeyResponseInner innerModel(); + + /** + * The entirety of the NginxDeploymentApiKeyResponse definition. + */ + interface Definition + extends DefinitionStages.Blank, DefinitionStages.WithParentResource, DefinitionStages.WithCreate { + } + + /** + * The NginxDeploymentApiKeyResponse definition stages. + */ + interface DefinitionStages { + /** + * The first stage of the NginxDeploymentApiKeyResponse definition. + */ + interface Blank extends WithParentResource { + } + + /** + * The stage of the NginxDeploymentApiKeyResponse definition allowing to specify parent resource. + */ + interface WithParentResource { + /** + * Specifies resourceGroupName, deploymentName. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param deploymentName The name of targeted NGINX deployment. + * @return the next definition stage. + */ + WithCreate withExistingNginxDeployment(String resourceGroupName, String deploymentName); + } + + /** + * The stage of the NginxDeploymentApiKeyResponse definition which contains all the minimum required properties + * for the resource to be created, but also allows for any other optional properties to be specified. + */ + interface WithCreate extends DefinitionStages.WithProperties { + /** + * Executes the create request. + * + * @return the created resource. + */ + NginxDeploymentApiKeyResponse create(); + + /** + * Executes the create request. + * + * @param context The context to associate with this operation. + * @return the created resource. + */ + NginxDeploymentApiKeyResponse create(Context context); + } + + /** + * The stage of the NginxDeploymentApiKeyResponse definition allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The properties property.. + * + * @param properties The properties property. + * @return the next definition stage. + */ + WithCreate withProperties(NginxDeploymentApiKeyRequestProperties properties); + } + } + + /** + * Begins update for the NginxDeploymentApiKeyResponse resource. + * + * @return the stage of resource update. + */ + NginxDeploymentApiKeyResponse.Update update(); + + /** + * The template for NginxDeploymentApiKeyResponse update. + */ + interface Update extends UpdateStages.WithProperties { + /** + * Executes the update request. + * + * @return the updated resource. + */ + NginxDeploymentApiKeyResponse apply(); + + /** + * Executes the update request. + * + * @param context The context to associate with this operation. + * @return the updated resource. + */ + NginxDeploymentApiKeyResponse apply(Context context); + } + + /** + * The NginxDeploymentApiKeyResponse update stages. + */ + interface UpdateStages { + /** + * The stage of the NginxDeploymentApiKeyResponse update allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The properties property.. + * + * @param properties The properties property. + * @return the next definition stage. + */ + Update withProperties(NginxDeploymentApiKeyRequestProperties properties); + } + } + + /** + * Refreshes the resource to sync with Azure. + * + * @return the refreshed resource. + */ + NginxDeploymentApiKeyResponse refresh(); + + /** + * Refreshes the resource to sync with Azure. + * + * @param context The context to associate with this operation. + * @return the refreshed resource. + */ + NginxDeploymentApiKeyResponse refresh(Context context); +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxDeploymentApiKeyResponseProperties.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxDeploymentApiKeyResponseProperties.java new file mode 100644 index 000000000000..ee4df20ad2ce --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxDeploymentApiKeyResponseProperties.java @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * The NginxDeploymentApiKeyResponseProperties model. + */ +@Fluent +public final class NginxDeploymentApiKeyResponseProperties + implements JsonSerializable { + /* + * The first three characters of the secret text to help identify it in use. This property is read-only. + */ + private String hint; + + /* + * The time after which this Dataplane API Key is no longer valid. + */ + private OffsetDateTime endDateTime; + + /** + * Creates an instance of NginxDeploymentApiKeyResponseProperties class. + */ + public NginxDeploymentApiKeyResponseProperties() { + } + + /** + * Get the hint property: The first three characters of the secret text to help identify it in use. This property is + * read-only. + * + * @return the hint value. + */ + public String hint() { + return this.hint; + } + + /** + * Get the endDateTime property: The time after which this Dataplane API Key is no longer valid. + * + * @return the endDateTime value. + */ + public OffsetDateTime endDateTime() { + return this.endDateTime; + } + + /** + * Set the endDateTime property: The time after which this Dataplane API Key is no longer valid. + * + * @param endDateTime the endDateTime value to set. + * @return the NginxDeploymentApiKeyResponseProperties object itself. + */ + public NginxDeploymentApiKeyResponseProperties withEndDateTime(OffsetDateTime endDateTime) { + this.endDateTime = endDateTime; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("endDateTime", + this.endDateTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.endDateTime)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of NginxDeploymentApiKeyResponseProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of NginxDeploymentApiKeyResponseProperties 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 NginxDeploymentApiKeyResponseProperties. + */ + public static NginxDeploymentApiKeyResponseProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + NginxDeploymentApiKeyResponseProperties deserializedNginxDeploymentApiKeyResponseProperties + = new NginxDeploymentApiKeyResponseProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("hint".equals(fieldName)) { + deserializedNginxDeploymentApiKeyResponseProperties.hint = reader.getString(); + } else if ("endDateTime".equals(fieldName)) { + deserializedNginxDeploymentApiKeyResponseProperties.endDateTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else { + reader.skipChildren(); + } + } + + return deserializedNginxDeploymentApiKeyResponseProperties; + }); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxDeploymentProperties.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxDeploymentProperties.java index 441280b9aed6..46524fff8778 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxDeploymentProperties.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxDeploymentProperties.java @@ -26,11 +26,6 @@ public final class NginxDeploymentProperties implements JsonSerializable { + /* + * Settings for the NGINX App Protect Web Application Firewall (WAF) + */ + private WebApplicationFirewallSettings webApplicationFirewallSettings; + + /* + * The status of the NGINX App Protect Web Application Firewall + */ + private WebApplicationFirewallStatus webApplicationFirewallStatus; + + /** + * Creates an instance of NginxDeploymentPropertiesNginxAppProtect class. + */ + public NginxDeploymentPropertiesNginxAppProtect() { + } + + /** + * Get the webApplicationFirewallSettings property: Settings for the NGINX App Protect Web Application Firewall + * (WAF). + * + * @return the webApplicationFirewallSettings value. + */ + public WebApplicationFirewallSettings webApplicationFirewallSettings() { + return this.webApplicationFirewallSettings; + } + + /** + * Set the webApplicationFirewallSettings property: Settings for the NGINX App Protect Web Application Firewall + * (WAF). + * + * @param webApplicationFirewallSettings the webApplicationFirewallSettings value to set. + * @return the NginxDeploymentPropertiesNginxAppProtect object itself. + */ + public NginxDeploymentPropertiesNginxAppProtect + withWebApplicationFirewallSettings(WebApplicationFirewallSettings webApplicationFirewallSettings) { + this.webApplicationFirewallSettings = webApplicationFirewallSettings; + return this; + } + + /** + * Get the webApplicationFirewallStatus property: The status of the NGINX App Protect Web Application Firewall. + * + * @return the webApplicationFirewallStatus value. + */ + public WebApplicationFirewallStatus webApplicationFirewallStatus() { + return this.webApplicationFirewallStatus; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (webApplicationFirewallSettings() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property webApplicationFirewallSettings in model NginxDeploymentPropertiesNginxAppProtect")); + } else { + webApplicationFirewallSettings().validate(); + } + if (webApplicationFirewallStatus() != null) { + webApplicationFirewallStatus().validate(); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(NginxDeploymentPropertiesNginxAppProtect.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("webApplicationFirewallSettings", this.webApplicationFirewallSettings); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of NginxDeploymentPropertiesNginxAppProtect from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of NginxDeploymentPropertiesNginxAppProtect 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 NginxDeploymentPropertiesNginxAppProtect. + */ + public static NginxDeploymentPropertiesNginxAppProtect fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + NginxDeploymentPropertiesNginxAppProtect deserializedNginxDeploymentPropertiesNginxAppProtect + = new NginxDeploymentPropertiesNginxAppProtect(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("webApplicationFirewallSettings".equals(fieldName)) { + deserializedNginxDeploymentPropertiesNginxAppProtect.webApplicationFirewallSettings + = WebApplicationFirewallSettings.fromJson(reader); + } else if ("webApplicationFirewallStatus".equals(fieldName)) { + deserializedNginxDeploymentPropertiesNginxAppProtect.webApplicationFirewallStatus + = WebApplicationFirewallStatus.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedNginxDeploymentPropertiesNginxAppProtect; + }); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxDeploymentUpdateProperties.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxDeploymentUpdateProperties.java index 249879ff5850..e4a1aa82c6a8 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxDeploymentUpdateProperties.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/NginxDeploymentUpdateProperties.java @@ -36,11 +36,21 @@ public final class NginxDeploymentUpdateProperties implements JsonSerializable { + /* + * Settings for the NGINX App Protect Web Application Firewall (WAF) + */ + private WebApplicationFirewallSettings webApplicationFirewallSettings; + + /** + * Creates an instance of NginxDeploymentUpdatePropertiesNginxAppProtect class. + */ + public NginxDeploymentUpdatePropertiesNginxAppProtect() { + } + + /** + * Get the webApplicationFirewallSettings property: Settings for the NGINX App Protect Web Application Firewall + * (WAF). + * + * @return the webApplicationFirewallSettings value. + */ + public WebApplicationFirewallSettings webApplicationFirewallSettings() { + return this.webApplicationFirewallSettings; + } + + /** + * Set the webApplicationFirewallSettings property: Settings for the NGINX App Protect Web Application Firewall + * (WAF). + * + * @param webApplicationFirewallSettings the webApplicationFirewallSettings value to set. + * @return the NginxDeploymentUpdatePropertiesNginxAppProtect object itself. + */ + public NginxDeploymentUpdatePropertiesNginxAppProtect + withWebApplicationFirewallSettings(WebApplicationFirewallSettings webApplicationFirewallSettings) { + this.webApplicationFirewallSettings = webApplicationFirewallSettings; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (webApplicationFirewallSettings() != null) { + webApplicationFirewallSettings().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("webApplicationFirewallSettings", this.webApplicationFirewallSettings); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of NginxDeploymentUpdatePropertiesNginxAppProtect from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of NginxDeploymentUpdatePropertiesNginxAppProtect 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 NginxDeploymentUpdatePropertiesNginxAppProtect. + */ + public static NginxDeploymentUpdatePropertiesNginxAppProtect fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + NginxDeploymentUpdatePropertiesNginxAppProtect deserializedNginxDeploymentUpdatePropertiesNginxAppProtect + = new NginxDeploymentUpdatePropertiesNginxAppProtect(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("webApplicationFirewallSettings".equals(fieldName)) { + deserializedNginxDeploymentUpdatePropertiesNginxAppProtect.webApplicationFirewallSettings + = WebApplicationFirewallSettings.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedNginxDeploymentUpdatePropertiesNginxAppProtect; + }); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/Operations.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/Operations.java index e4961fb6b2e4..aacae2479104 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/Operations.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/Operations.java @@ -12,7 +12,7 @@ */ public interface Operations { /** - * List all operations provided by Nginx.NginxPlus for the 2024-01-01-preview api version. + * List all operations provided by Nginx.NginxPlus for the 2024-11-01-preview api version. * * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -22,7 +22,7 @@ public interface Operations { PagedIterable list(); /** - * List all operations provided by Nginx.NginxPlus for the 2024-01-01-preview api version. + * List all operations provided by Nginx.NginxPlus for the 2024-11-01-preview api version. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/WebApplicationFirewallComponentVersions.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/WebApplicationFirewallComponentVersions.java new file mode 100644 index 000000000000..1d791f63f2df --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/WebApplicationFirewallComponentVersions.java @@ -0,0 +1,139 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Versions of the NGINX App Protect Web Application Firewall (WAF) components. + */ +@Fluent +public final class WebApplicationFirewallComponentVersions + implements JsonSerializable { + /* + * The version of the NGINX App Protect Web Application Firewall (WAF) engine. + */ + private String wafEngineVersion; + + /* + * The version of the NGINX App Protect Web Application Firewall (WAF) module for NGINX. + */ + private String wafNginxVersion; + + /** + * Creates an instance of WebApplicationFirewallComponentVersions class. + */ + public WebApplicationFirewallComponentVersions() { + } + + /** + * Get the wafEngineVersion property: The version of the NGINX App Protect Web Application Firewall (WAF) engine. + * + * @return the wafEngineVersion value. + */ + public String wafEngineVersion() { + return this.wafEngineVersion; + } + + /** + * Set the wafEngineVersion property: The version of the NGINX App Protect Web Application Firewall (WAF) engine. + * + * @param wafEngineVersion the wafEngineVersion value to set. + * @return the WebApplicationFirewallComponentVersions object itself. + */ + public WebApplicationFirewallComponentVersions withWafEngineVersion(String wafEngineVersion) { + this.wafEngineVersion = wafEngineVersion; + return this; + } + + /** + * Get the wafNginxVersion property: The version of the NGINX App Protect Web Application Firewall (WAF) module for + * NGINX. + * + * @return the wafNginxVersion value. + */ + public String wafNginxVersion() { + return this.wafNginxVersion; + } + + /** + * Set the wafNginxVersion property: The version of the NGINX App Protect Web Application Firewall (WAF) module for + * NGINX. + * + * @param wafNginxVersion the wafNginxVersion value to set. + * @return the WebApplicationFirewallComponentVersions object itself. + */ + public WebApplicationFirewallComponentVersions withWafNginxVersion(String wafNginxVersion) { + this.wafNginxVersion = wafNginxVersion; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (wafEngineVersion() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property wafEngineVersion in model WebApplicationFirewallComponentVersions")); + } + if (wafNginxVersion() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property wafNginxVersion in model WebApplicationFirewallComponentVersions")); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(WebApplicationFirewallComponentVersions.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("wafEngineVersion", this.wafEngineVersion); + jsonWriter.writeStringField("wafNginxVersion", this.wafNginxVersion); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of WebApplicationFirewallComponentVersions from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of WebApplicationFirewallComponentVersions 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 WebApplicationFirewallComponentVersions. + */ + public static WebApplicationFirewallComponentVersions fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + WebApplicationFirewallComponentVersions deserializedWebApplicationFirewallComponentVersions + = new WebApplicationFirewallComponentVersions(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("wafEngineVersion".equals(fieldName)) { + deserializedWebApplicationFirewallComponentVersions.wafEngineVersion = reader.getString(); + } else if ("wafNginxVersion".equals(fieldName)) { + deserializedWebApplicationFirewallComponentVersions.wafNginxVersion = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedWebApplicationFirewallComponentVersions; + }); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/WebApplicationFirewallPackage.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/WebApplicationFirewallPackage.java new file mode 100644 index 000000000000..43b07d2a67c5 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/WebApplicationFirewallPackage.java @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; +import com.azure.core.util.logging.ClientLogger; +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.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * NGINX App Protect Web Application Firewall (WAF) Package. Contains the version and revision date of the package. + */ +@Fluent +public final class WebApplicationFirewallPackage implements JsonSerializable { + /* + * The version of the NGINX App Protect Web Application Firewall (WAF) package. + */ + private String version; + + /* + * The date and time of the package revision. + */ + private OffsetDateTime revisionDatetime; + + /** + * Creates an instance of WebApplicationFirewallPackage class. + */ + public WebApplicationFirewallPackage() { + } + + /** + * Get the version property: The version of the NGINX App Protect Web Application Firewall (WAF) package. + * + * @return the version value. + */ + public String version() { + return this.version; + } + + /** + * Set the version property: The version of the NGINX App Protect Web Application Firewall (WAF) package. + * + * @param version the version value to set. + * @return the WebApplicationFirewallPackage object itself. + */ + public WebApplicationFirewallPackage withVersion(String version) { + this.version = version; + return this; + } + + /** + * Get the revisionDatetime property: The date and time of the package revision. + * + * @return the revisionDatetime value. + */ + public OffsetDateTime revisionDatetime() { + return this.revisionDatetime; + } + + /** + * Set the revisionDatetime property: The date and time of the package revision. + * + * @param revisionDatetime the revisionDatetime value to set. + * @return the WebApplicationFirewallPackage object itself. + */ + public WebApplicationFirewallPackage withRevisionDatetime(OffsetDateTime revisionDatetime) { + this.revisionDatetime = revisionDatetime; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (version() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property version in model WebApplicationFirewallPackage")); + } + if (revisionDatetime() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property revisionDatetime in model WebApplicationFirewallPackage")); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(WebApplicationFirewallPackage.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", this.version); + jsonWriter.writeStringField("revisionDatetime", + this.revisionDatetime == null + ? null + : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.revisionDatetime)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of WebApplicationFirewallPackage from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of WebApplicationFirewallPackage 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 WebApplicationFirewallPackage. + */ + public static WebApplicationFirewallPackage fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + WebApplicationFirewallPackage deserializedWebApplicationFirewallPackage + = new WebApplicationFirewallPackage(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("version".equals(fieldName)) { + deserializedWebApplicationFirewallPackage.version = reader.getString(); + } else if ("revisionDatetime".equals(fieldName)) { + deserializedWebApplicationFirewallPackage.revisionDatetime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else { + reader.skipChildren(); + } + } + + return deserializedWebApplicationFirewallPackage; + }); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/WebApplicationFirewallSettings.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/WebApplicationFirewallSettings.java new file mode 100644 index 000000000000..86ed71f3d5c1 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/WebApplicationFirewallSettings.java @@ -0,0 +1,98 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.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; + +/** + * Settings for the NGINX App Protect Web Application Firewall (WAF). + */ +@Fluent +public final class WebApplicationFirewallSettings implements JsonSerializable { + /* + * The activation state of the WAF. Use 'Enabled' to enable the WAF and 'Disabled' to disable it. + */ + private ActivationState activationState; + + /** + * Creates an instance of WebApplicationFirewallSettings class. + */ + public WebApplicationFirewallSettings() { + } + + /** + * Get the activationState property: The activation state of the WAF. Use 'Enabled' to enable the WAF and 'Disabled' + * to disable it. + * + * @return the activationState value. + */ + public ActivationState activationState() { + return this.activationState; + } + + /** + * Set the activationState property: The activation state of the WAF. Use 'Enabled' to enable the WAF and 'Disabled' + * to disable it. + * + * @param activationState the activationState value to set. + * @return the WebApplicationFirewallSettings object itself. + */ + public WebApplicationFirewallSettings withActivationState(ActivationState activationState) { + this.activationState = activationState; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("activationState", + this.activationState == null ? null : this.activationState.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of WebApplicationFirewallSettings from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of WebApplicationFirewallSettings 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 WebApplicationFirewallSettings. + */ + public static WebApplicationFirewallSettings fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + WebApplicationFirewallSettings deserializedWebApplicationFirewallSettings + = new WebApplicationFirewallSettings(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("activationState".equals(fieldName)) { + deserializedWebApplicationFirewallSettings.activationState + = ActivationState.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedWebApplicationFirewallSettings; + }); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/WebApplicationFirewallStatus.java b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/WebApplicationFirewallStatus.java new file mode 100644 index 000000000000..44c0238e6a22 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/java/com/azure/resourcemanager/nginx/models/WebApplicationFirewallStatus.java @@ -0,0 +1,148 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.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 status of the NGINX App Protect Web Application Firewall. + */ +@Immutable +public final class WebApplicationFirewallStatus implements JsonSerializable { + /* + * Package containing attack signatures for the NGINX App Protect Web Application Firewall (WAF). + */ + private WebApplicationFirewallPackage attackSignaturesPackage; + + /* + * Package containing bot signatures for the NGINX App Protect Web Application Firewall (WAF). + */ + private WebApplicationFirewallPackage botSignaturesPackage; + + /* + * Package containing threat campaigns for the NGINX App Protect Web Application Firewall (WAF). + */ + private WebApplicationFirewallPackage threatCampaignsPackage; + + /* + * Versions of the NGINX App Protect Web Application Firewall (WAF) components. + */ + private WebApplicationFirewallComponentVersions componentVersions; + + /** + * Creates an instance of WebApplicationFirewallStatus class. + */ + public WebApplicationFirewallStatus() { + } + + /** + * Get the attackSignaturesPackage property: Package containing attack signatures for the NGINX App Protect Web + * Application Firewall (WAF). + * + * @return the attackSignaturesPackage value. + */ + public WebApplicationFirewallPackage attackSignaturesPackage() { + return this.attackSignaturesPackage; + } + + /** + * Get the botSignaturesPackage property: Package containing bot signatures for the NGINX App Protect Web + * Application Firewall (WAF). + * + * @return the botSignaturesPackage value. + */ + public WebApplicationFirewallPackage botSignaturesPackage() { + return this.botSignaturesPackage; + } + + /** + * Get the threatCampaignsPackage property: Package containing threat campaigns for the NGINX App Protect Web + * Application Firewall (WAF). + * + * @return the threatCampaignsPackage value. + */ + public WebApplicationFirewallPackage threatCampaignsPackage() { + return this.threatCampaignsPackage; + } + + /** + * Get the componentVersions property: Versions of the NGINX App Protect Web Application Firewall (WAF) components. + * + * @return the componentVersions value. + */ + public WebApplicationFirewallComponentVersions componentVersions() { + return this.componentVersions; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (attackSignaturesPackage() != null) { + attackSignaturesPackage().validate(); + } + if (botSignaturesPackage() != null) { + botSignaturesPackage().validate(); + } + if (threatCampaignsPackage() != null) { + threatCampaignsPackage().validate(); + } + if (componentVersions() != null) { + componentVersions().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of WebApplicationFirewallStatus from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of WebApplicationFirewallStatus 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 WebApplicationFirewallStatus. + */ + public static WebApplicationFirewallStatus fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + WebApplicationFirewallStatus deserializedWebApplicationFirewallStatus = new WebApplicationFirewallStatus(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("attackSignaturesPackage".equals(fieldName)) { + deserializedWebApplicationFirewallStatus.attackSignaturesPackage + = WebApplicationFirewallPackage.fromJson(reader); + } else if ("botSignaturesPackage".equals(fieldName)) { + deserializedWebApplicationFirewallStatus.botSignaturesPackage + = WebApplicationFirewallPackage.fromJson(reader); + } else if ("threatCampaignsPackage".equals(fieldName)) { + deserializedWebApplicationFirewallStatus.threatCampaignsPackage + = WebApplicationFirewallPackage.fromJson(reader); + } else if ("componentVersions".equals(fieldName)) { + deserializedWebApplicationFirewallStatus.componentVersions + = WebApplicationFirewallComponentVersions.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedWebApplicationFirewallStatus; + }); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-nginx/proxy-config.json b/sdk/nginx/azure-resourcemanager-nginx/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-nginx/proxy-config.json index fa397baef5fe..6041e4af3bd5 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-nginx/proxy-config.json +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-nginx/proxy-config.json @@ -1 +1 @@ -[["com.azure.resourcemanager.nginx.implementation.CertificatesClientImpl$CertificatesService"],["com.azure.resourcemanager.nginx.implementation.ConfigurationsClientImpl$ConfigurationsService"],["com.azure.resourcemanager.nginx.implementation.DeploymentsClientImpl$DeploymentsService"],["com.azure.resourcemanager.nginx.implementation.OperationsClientImpl$OperationsService"]] \ No newline at end of file +[["com.azure.resourcemanager.nginx.implementation.ApiKeysClientImpl$ApiKeysService"],["com.azure.resourcemanager.nginx.implementation.CertificatesClientImpl$CertificatesService"],["com.azure.resourcemanager.nginx.implementation.ConfigurationsClientImpl$ConfigurationsService"],["com.azure.resourcemanager.nginx.implementation.DeploymentsClientImpl$DeploymentsService"],["com.azure.resourcemanager.nginx.implementation.OperationsClientImpl$OperationsService"]] \ No newline at end of file diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/main/resources/azure-resourcemanager-nginx.properties b/sdk/nginx/azure-resourcemanager-nginx/src/main/resources/azure-resourcemanager-nginx.properties new file mode 100644 index 000000000000..defbd48204e4 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/main/resources/azure-resourcemanager-nginx.properties @@ -0,0 +1 @@ +version=${project.version} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ApiKeysCreateOrUpdateSamples.java b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ApiKeysCreateOrUpdateSamples.java new file mode 100644 index 000000000000..9cab6b9b96a9 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ApiKeysCreateOrUpdateSamples.java @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.generated; + +/** + * Samples for ApiKeys CreateOrUpdate. + */ +public final class ApiKeysCreateOrUpdateSamples { + /* + * x-ms-original-file: + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/ApiKeys_CreateOrUpdate. + * json + */ + /** + * Sample code: ApiKeys_CreateOrUpdate. + * + * @param manager Entry point to NginxManager. + */ + public static void apiKeysCreateOrUpdate(com.azure.resourcemanager.nginx.NginxManager manager) { + manager.apiKeys().define("myApiKey").withExistingNginxDeployment("myResourceGroup", "myDeployment").create(); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ApiKeysDeleteSamples.java b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ApiKeysDeleteSamples.java new file mode 100644 index 000000000000..1f32e1ca3b0b --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ApiKeysDeleteSamples.java @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.generated; + +/** + * Samples for ApiKeys Delete. + */ +public final class ApiKeysDeleteSamples { + /* + * x-ms-original-file: + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/ApiKeys_Delete.json + */ + /** + * Sample code: ApiKeys_Delete. + * + * @param manager Entry point to NginxManager. + */ + public static void apiKeysDelete(com.azure.resourcemanager.nginx.NginxManager manager) { + manager.apiKeys() + .deleteWithResponse("myResourceGroup", "myDeployment", "myApiKey", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ApiKeysGetSamples.java b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ApiKeysGetSamples.java new file mode 100644 index 000000000000..0ba09a92e67c --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ApiKeysGetSamples.java @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.generated; + +/** + * Samples for ApiKeys Get. + */ +public final class ApiKeysGetSamples { + /* + * x-ms-original-file: + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/ApiKeys_Get.json + */ + /** + * Sample code: ApiKeys_Get. + * + * @param manager Entry point to NginxManager. + */ + public static void apiKeysGet(com.azure.resourcemanager.nginx.NginxManager manager) { + manager.apiKeys() + .getWithResponse("myResourceGroup", "myDeployment", "myApiKey", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ApiKeysListSamples.java b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ApiKeysListSamples.java new file mode 100644 index 000000000000..bee05174a806 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ApiKeysListSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.generated; + +/** + * Samples for ApiKeys List. + */ +public final class ApiKeysListSamples { + /* + * x-ms-original-file: + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/ApiKeys_List.json + */ + /** + * Sample code: ApiKeys_List. + * + * @param manager Entry point to NginxManager. + */ + public static void apiKeysList(com.azure.resourcemanager.nginx.NginxManager manager) { + manager.apiKeys().list("myResourceGroup", "myDeployment", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/CertificatesCreateOrUpdateSamples.java b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/CertificatesCreateOrUpdateSamples.java index 554732e9d3d8..cf3b4ecefe1a 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/CertificatesCreateOrUpdateSamples.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/CertificatesCreateOrUpdateSamples.java @@ -4,14 +4,12 @@ package com.azure.resourcemanager.nginx.generated; -import com.azure.resourcemanager.nginx.models.NginxCertificateProperties; - /** * Samples for Certificates CreateOrUpdate. */ public final class CertificatesCreateOrUpdateSamples { /* - * x-ms-original-file: specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/ + * x-ms-original-file: specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/ * Certificates_CreateOrUpdate.json */ /** @@ -23,9 +21,6 @@ public static void certificatesCreateOrUpdate(com.azure.resourcemanager.nginx.Ng manager.certificates() .define("default") .withExistingNginxDeployment("myResourceGroup", "myDeployment") - .withProperties(new NginxCertificateProperties().withKeyVirtualPath("fakeTokenPlaceholder") - .withCertificateVirtualPath("/src/cert/somePath.cert") - .withKeyVaultSecretId("fakeTokenPlaceholder")) .create(); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/CertificatesDeleteSamples.java b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/CertificatesDeleteSamples.java index 52eb6bce4bc2..2ea2bf77a18b 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/CertificatesDeleteSamples.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/CertificatesDeleteSamples.java @@ -10,7 +10,7 @@ public final class CertificatesDeleteSamples { /* * x-ms-original-file: - * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/Certificates_Delete.json + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/Certificates_Delete.json */ /** * Sample code: Certificates_Delete. diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/CertificatesGetSamples.java b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/CertificatesGetSamples.java index ca18e4ac5d05..4a422d0225c1 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/CertificatesGetSamples.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/CertificatesGetSamples.java @@ -10,7 +10,7 @@ public final class CertificatesGetSamples { /* * x-ms-original-file: - * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/Certificates_Get.json + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/Certificates_Get.json */ /** * Sample code: Certificates_Get. diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/CertificatesListSamples.java b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/CertificatesListSamples.java index dd9a5dfdf748..3203a500ebdf 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/CertificatesListSamples.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/CertificatesListSamples.java @@ -10,7 +10,7 @@ public final class CertificatesListSamples { /* * x-ms-original-file: - * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/Certificates_List.json + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/Certificates_List.json */ /** * Sample code: Certificates_List. diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ConfigurationsAnalysisSamples.java b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ConfigurationsAnalysisSamples.java index d6c1194d05e2..a6a3c13ec29b 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ConfigurationsAnalysisSamples.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ConfigurationsAnalysisSamples.java @@ -4,19 +4,13 @@ package com.azure.resourcemanager.nginx.generated; -import com.azure.resourcemanager.nginx.models.AnalysisCreate; -import com.azure.resourcemanager.nginx.models.AnalysisCreateConfig; -import com.azure.resourcemanager.nginx.models.NginxConfigurationFile; -import com.azure.resourcemanager.nginx.models.NginxConfigurationPackage; -import java.util.Arrays; - /** * Samples for Configurations Analysis. */ public final class ConfigurationsAnalysisSamples { /* * x-ms-original-file: - * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/Configurations_Analysis. + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/Configurations_Analysis. * json */ /** @@ -26,11 +20,6 @@ public final class ConfigurationsAnalysisSamples { */ public static void configurationsAnalysis(com.azure.resourcemanager.nginx.NginxManager manager) { manager.configurations() - .analysisWithResponse("myResourceGroup", "myDeployment", "default", - new AnalysisCreate().withConfig(new AnalysisCreateConfig().withRootFile("/etc/nginx/nginx.conf") - .withFiles(Arrays.asList( - new NginxConfigurationFile().withContent("ABCDEF==").withVirtualPath("/etc/nginx/nginx.conf"))) - .withPackageProperty(new NginxConfigurationPackage())), - com.azure.core.util.Context.NONE); + .analysisWithResponse("myResourceGroup", "myDeployment", "default", null, com.azure.core.util.Context.NONE); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ConfigurationsCreateOrUpdateSamples.java b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ConfigurationsCreateOrUpdateSamples.java index 450f37c20db7..079187e1711c 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ConfigurationsCreateOrUpdateSamples.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ConfigurationsCreateOrUpdateSamples.java @@ -4,17 +4,12 @@ package com.azure.resourcemanager.nginx.generated; -import com.azure.resourcemanager.nginx.models.NginxConfigurationFile; -import com.azure.resourcemanager.nginx.models.NginxConfigurationPackage; -import com.azure.resourcemanager.nginx.models.NginxConfigurationProperties; -import java.util.Arrays; - /** * Samples for Configurations CreateOrUpdate. */ public final class ConfigurationsCreateOrUpdateSamples { /* - * x-ms-original-file: specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/ + * x-ms-original-file: specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/ * Configurations_CreateOrUpdate.json */ /** @@ -26,11 +21,6 @@ public static void configurationsCreateOrUpdate(com.azure.resourcemanager.nginx. manager.configurations() .define("default") .withExistingNginxDeployment("myResourceGroup", "myDeployment") - .withProperties(new NginxConfigurationProperties() - .withFiles(Arrays.asList( - new NginxConfigurationFile().withContent("ABCDEF==").withVirtualPath("/etc/nginx/nginx.conf"))) - .withPackageProperty(new NginxConfigurationPackage()) - .withRootFile("/etc/nginx/nginx.conf")) .create(); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ConfigurationsDeleteSamples.java b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ConfigurationsDeleteSamples.java index 2838ef5b4db3..b61679d246d1 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ConfigurationsDeleteSamples.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ConfigurationsDeleteSamples.java @@ -10,7 +10,7 @@ public final class ConfigurationsDeleteSamples { /* * x-ms-original-file: - * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/Configurations_Delete. + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/Configurations_Delete. * json */ /** diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ConfigurationsGetSamples.java b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ConfigurationsGetSamples.java index fd7ce0f0b0c0..a8d450b25706 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ConfigurationsGetSamples.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ConfigurationsGetSamples.java @@ -10,7 +10,7 @@ public final class ConfigurationsGetSamples { /* * x-ms-original-file: - * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/Configurations_Get.json + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/Configurations_Get.json */ /** * Sample code: Configurations_Get. diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ConfigurationsListSamples.java b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ConfigurationsListSamples.java index 8d8602bf632e..05855eafbb14 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ConfigurationsListSamples.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/ConfigurationsListSamples.java @@ -10,7 +10,7 @@ public final class ConfigurationsListSamples { /* * x-ms-original-file: - * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/Configurations_List.json + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/Configurations_List.json */ /** * Sample code: Configurations_List. diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/DeploymentsCreateOrUpdateSamples.java b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/DeploymentsCreateOrUpdateSamples.java index c2bfa1d152d9..122b616fe2b3 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/DeploymentsCreateOrUpdateSamples.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/DeploymentsCreateOrUpdateSamples.java @@ -4,27 +4,13 @@ package com.azure.resourcemanager.nginx.generated; -import com.azure.resourcemanager.nginx.models.AutoUpgradeProfile; -import com.azure.resourcemanager.nginx.models.NginxDeploymentProperties; -import com.azure.resourcemanager.nginx.models.NginxDeploymentScalingProperties; -import com.azure.resourcemanager.nginx.models.NginxDeploymentUserProfile; -import com.azure.resourcemanager.nginx.models.NginxFrontendIpConfiguration; -import com.azure.resourcemanager.nginx.models.NginxNetworkInterfaceConfiguration; -import com.azure.resourcemanager.nginx.models.NginxNetworkProfile; -import com.azure.resourcemanager.nginx.models.NginxPrivateIpAddress; -import com.azure.resourcemanager.nginx.models.NginxPrivateIpAllocationMethod; -import com.azure.resourcemanager.nginx.models.NginxPublicIpAddress; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - /** * Samples for Deployments CreateOrUpdate. */ public final class DeploymentsCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/Deployments_Create.json + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/Deployments_Create.json */ /** * Sample code: Deployments_Create. @@ -34,36 +20,8 @@ public final class DeploymentsCreateOrUpdateSamples { public static void deploymentsCreate(com.azure.resourcemanager.nginx.NginxManager manager) { manager.deployments() .define("myDeployment") - .withRegion("West US") + .withRegion((String) null) .withExistingResourceGroup("myResourceGroup") - .withTags(mapOf("Environment", "Dev")) - .withProperties(new NginxDeploymentProperties().withManagedResourceGroup("myManagedResourceGroup") - .withNetworkProfile(new NginxNetworkProfile() - .withFrontEndIpConfiguration(new NginxFrontendIpConfiguration() - .withPublicIpAddresses(Arrays.asList(new NginxPublicIpAddress().withId( - "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Network/publicIPAddresses/myPublicIPAddress"))) - .withPrivateIpAddresses(Arrays.asList(new NginxPrivateIpAddress() - .withPrivateIpAddress("1.1.1.1") - .withPrivateIpAllocationMethod(NginxPrivateIpAllocationMethod.STATIC) - .withSubnetId( - "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/myVnet/subnets/mySubnet")))) - .withNetworkInterfaceConfiguration(new NginxNetworkInterfaceConfiguration().withSubnetId( - "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/myVnet/subnets/mySubnet"))) - .withScalingProperties(new NginxDeploymentScalingProperties().withCapacity(10)) - .withAutoUpgradeProfile(new AutoUpgradeProfile().withUpgradeChannel("stable")) - .withUserProfile(new NginxDeploymentUserProfile().withPreferredEmail("example@example.email"))) .create(); } - - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; - } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/DeploymentsDeleteSamples.java b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/DeploymentsDeleteSamples.java index d8a699394c25..2a3cf584a742 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/DeploymentsDeleteSamples.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/DeploymentsDeleteSamples.java @@ -10,7 +10,7 @@ public final class DeploymentsDeleteSamples { /* * x-ms-original-file: - * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/Deployments_Delete.json + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/Deployments_Delete.json */ /** * Sample code: Deployments_Delete. diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/DeploymentsGetByResourceGroupSamples.java b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/DeploymentsGetByResourceGroupSamples.java index b56c80ee5954..e33c42e526d9 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/DeploymentsGetByResourceGroupSamples.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/DeploymentsGetByResourceGroupSamples.java @@ -10,7 +10,7 @@ public final class DeploymentsGetByResourceGroupSamples { /* * x-ms-original-file: - * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/Deployments_Get.json + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/Deployments_Get.json */ /** * Sample code: Deployments_Get. @@ -23,7 +23,7 @@ public static void deploymentsGet(com.azure.resourcemanager.nginx.NginxManager m } /* - * x-ms-original-file: specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/ + * x-ms-original-file: specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/ * Deployments_Get_AutoScale.json */ /** diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/DeploymentsListByResourceGroupSamples.java b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/DeploymentsListByResourceGroupSamples.java index a7ee54a956ad..2c9aef6ec5a6 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/DeploymentsListByResourceGroupSamples.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/DeploymentsListByResourceGroupSamples.java @@ -9,7 +9,7 @@ */ public final class DeploymentsListByResourceGroupSamples { /* - * x-ms-original-file: specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/ + * x-ms-original-file: specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/ * Deployments_ListByResourceGroup.json */ /** diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/DeploymentsListSamples.java b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/DeploymentsListSamples.java index 9f09bac23c63..602baa30cdf7 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/DeploymentsListSamples.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/DeploymentsListSamples.java @@ -10,7 +10,7 @@ public final class DeploymentsListSamples { /* * x-ms-original-file: - * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/Deployments_List.json + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/Deployments_List.json */ /** * Sample code: Deployments_List. diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/DeploymentsUpdateSamples.java b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/DeploymentsUpdateSamples.java index 601d1a57f74a..47bccc3d8b65 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/DeploymentsUpdateSamples.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/DeploymentsUpdateSamples.java @@ -5,8 +5,6 @@ package com.azure.resourcemanager.nginx.generated; import com.azure.resourcemanager.nginx.models.NginxDeployment; -import java.util.HashMap; -import java.util.Map; /** * Samples for Deployments Update. @@ -14,7 +12,7 @@ public final class DeploymentsUpdateSamples { /* * x-ms-original-file: - * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/Deployments_Update.json + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/Deployments_Update.json */ /** * Sample code: Deployments_Update. @@ -25,18 +23,23 @@ public static void deploymentsUpdate(com.azure.resourcemanager.nginx.NginxManage NginxDeployment resource = manager.deployments() .getByResourceGroupWithResponse("myResourceGroup", "myDeployment", com.azure.core.util.Context.NONE) .getValue(); - resource.update().withTags(mapOf("Environment", "Dev")).apply(); + resource.update().apply(); } - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; + /* + * x-ms-original-file: + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/Deployments_UpdateSubnet + * .json + */ + /** + * Sample code: Deployments_UpdateSubnet. + * + * @param manager Entry point to NginxManager. + */ + public static void deploymentsUpdateSubnet(com.azure.resourcemanager.nginx.NginxManager manager) { + NginxDeployment resource = manager.deployments() + .getByResourceGroupWithResponse("myResourceGroup", "myDeployment", com.azure.core.util.Context.NONE) + .getValue(); + resource.update().apply(); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/OperationsListSamples.java b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/OperationsListSamples.java index c56308f9ab65..ed5c967de9fc 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/OperationsListSamples.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/samples/java/com/azure/resourcemanager/nginx/generated/OperationsListSamples.java @@ -10,7 +10,7 @@ public final class OperationsListSamples { /* * x-ms-original-file: - * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-01-01-preview/examples/Operations_List.json + * specification/nginx/resource-manager/NGINX.NGINXPLUS/preview/2024-11-01-preview/examples/Operations_List.json */ /** * Sample code: Operations_List. diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/AnalysisCreateConfigTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/AnalysisCreateConfigTests.java index c5cecf7522d3..9d4f66bec40b 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/AnalysisCreateConfigTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/AnalysisCreateConfigTests.java @@ -8,6 +8,7 @@ import com.azure.resourcemanager.nginx.models.AnalysisCreateConfig; import com.azure.resourcemanager.nginx.models.NginxConfigurationFile; import com.azure.resourcemanager.nginx.models.NginxConfigurationPackage; +import com.azure.resourcemanager.nginx.models.NginxConfigurationProtectedFileRequest; import java.util.Arrays; import org.junit.jupiter.api.Assertions; @@ -15,33 +16,37 @@ public final class AnalysisCreateConfigTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { AnalysisCreateConfig model = BinaryData.fromString( - "{\"rootFile\":\"qrglssainqpjwn\",\"files\":[{\"content\":\"fmppe\",\"virtualPath\":\"vmgxsab\"},{\"content\":\"qduujitcjczdz\",\"virtualPath\":\"ndhkrw\"}],\"protectedFiles\":[{\"content\":\"p\",\"virtualPath\":\"bdkvwrwjf\"}],\"package\":{\"data\":\"nhutjeltmrldhugj\",\"protectedFiles\":[\"atqxho\",\"dgeablgphu\",\"icndvkaozwyifty\",\"xhurok\"]}}") + "{\"rootFile\":\"lkhbz\",\"files\":[{\"content\":\"gzgqexzlo\",\"virtualPath\":\"scpai\"},{\"content\":\"hhbcsglummajtjao\",\"virtualPath\":\"obnbdxkqpxokaj\"},{\"content\":\"npime\",\"virtualPath\":\"stxgc\"}],\"protectedFiles\":[{\"content\":\"maajrmvdjwzrlo\",\"virtualPath\":\"clwhijcoejctbz\",\"contentHash\":\"s\"}],\"package\":{\"data\":\"cbkbfkg\",\"protectedFiles\":[\"kexxppof\",\"xaxcfjpgddtocjjx\",\"vpmouexhdzxib\"]}}") .toObject(AnalysisCreateConfig.class); - Assertions.assertEquals("qrglssainqpjwn", model.rootFile()); - Assertions.assertEquals("fmppe", model.files().get(0).content()); - Assertions.assertEquals("vmgxsab", model.files().get(0).virtualPath()); - Assertions.assertEquals("p", model.protectedFiles().get(0).content()); - Assertions.assertEquals("bdkvwrwjf", model.protectedFiles().get(0).virtualPath()); - Assertions.assertEquals("nhutjeltmrldhugj", model.packageProperty().data()); - Assertions.assertEquals("atqxho", model.packageProperty().protectedFiles().get(0)); + Assertions.assertEquals("lkhbz", model.rootFile()); + Assertions.assertEquals("gzgqexzlo", model.files().get(0).content()); + Assertions.assertEquals("scpai", model.files().get(0).virtualPath()); + Assertions.assertEquals("maajrmvdjwzrlo", model.protectedFiles().get(0).content()); + Assertions.assertEquals("clwhijcoejctbz", model.protectedFiles().get(0).virtualPath()); + Assertions.assertEquals("s", model.protectedFiles().get(0).contentHash()); + Assertions.assertEquals("cbkbfkg", model.packageProperty().data()); + Assertions.assertEquals("kexxppof", model.packageProperty().protectedFiles().get(0)); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - AnalysisCreateConfig model = new AnalysisCreateConfig().withRootFile("qrglssainqpjwn") - .withFiles(Arrays.asList(new NginxConfigurationFile().withContent("fmppe").withVirtualPath("vmgxsab"), - new NginxConfigurationFile().withContent("qduujitcjczdz").withVirtualPath("ndhkrw"))) - .withProtectedFiles( - Arrays.asList(new NginxConfigurationFile().withContent("p").withVirtualPath("bdkvwrwjf"))) - .withPackageProperty(new NginxConfigurationPackage().withData("nhutjeltmrldhugj") - .withProtectedFiles(Arrays.asList("atqxho", "dgeablgphu", "icndvkaozwyifty", "xhurok"))); + AnalysisCreateConfig model = new AnalysisCreateConfig().withRootFile("lkhbz") + .withFiles(Arrays.asList(new NginxConfigurationFile().withContent("gzgqexzlo").withVirtualPath("scpai"), + new NginxConfigurationFile().withContent("hhbcsglummajtjao").withVirtualPath("obnbdxkqpxokaj"), + new NginxConfigurationFile().withContent("npime").withVirtualPath("stxgc"))) + .withProtectedFiles(Arrays.asList(new NginxConfigurationProtectedFileRequest().withContent("maajrmvdjwzrlo") + .withVirtualPath("clwhijcoejctbz") + .withContentHash("s"))) + .withPackageProperty(new NginxConfigurationPackage().withData("cbkbfkg") + .withProtectedFiles(Arrays.asList("kexxppof", "xaxcfjpgddtocjjx", "vpmouexhdzxib"))); model = BinaryData.fromObject(model).toObject(AnalysisCreateConfig.class); - Assertions.assertEquals("qrglssainqpjwn", model.rootFile()); - Assertions.assertEquals("fmppe", model.files().get(0).content()); - Assertions.assertEquals("vmgxsab", model.files().get(0).virtualPath()); - Assertions.assertEquals("p", model.protectedFiles().get(0).content()); - Assertions.assertEquals("bdkvwrwjf", model.protectedFiles().get(0).virtualPath()); - Assertions.assertEquals("nhutjeltmrldhugj", model.packageProperty().data()); - Assertions.assertEquals("atqxho", model.packageProperty().protectedFiles().get(0)); + Assertions.assertEquals("lkhbz", model.rootFile()); + Assertions.assertEquals("gzgqexzlo", model.files().get(0).content()); + Assertions.assertEquals("scpai", model.files().get(0).virtualPath()); + Assertions.assertEquals("maajrmvdjwzrlo", model.protectedFiles().get(0).content()); + Assertions.assertEquals("clwhijcoejctbz", model.protectedFiles().get(0).virtualPath()); + Assertions.assertEquals("s", model.protectedFiles().get(0).contentHash()); + Assertions.assertEquals("cbkbfkg", model.packageProperty().data()); + Assertions.assertEquals("kexxppof", model.packageProperty().protectedFiles().get(0)); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/AnalysisCreateTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/AnalysisCreateTests.java index 2c2329dec664..521ee8564882 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/AnalysisCreateTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/AnalysisCreateTests.java @@ -9,6 +9,7 @@ import com.azure.resourcemanager.nginx.models.AnalysisCreateConfig; import com.azure.resourcemanager.nginx.models.NginxConfigurationFile; import com.azure.resourcemanager.nginx.models.NginxConfigurationPackage; +import com.azure.resourcemanager.nginx.models.NginxConfigurationProtectedFileRequest; import java.util.Arrays; import org.junit.jupiter.api.Assertions; @@ -16,38 +17,45 @@ public final class AnalysisCreateTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { AnalysisCreate model = BinaryData.fromString( - "{\"config\":{\"rootFile\":\"zoxxjtf\",\"files\":[{\"content\":\"wfzitonpeqfpjk\",\"virtualPath\":\"xofpdvhpfxxypi\"},{\"content\":\"nmayhuybb\",\"virtualPath\":\"odepoogin\"},{\"content\":\"amiheognarxz\",\"virtualPath\":\"heotusiv\"},{\"content\":\"v\",\"virtualPath\":\"iqihn\"}],\"protectedFiles\":[{\"content\":\"bwjzr\",\"virtualPath\":\"ygxgispemvtz\"},{\"content\":\"ufubl\",\"virtualPath\":\"fxqeof\"}],\"package\":{\"data\":\"qjhqjbas\",\"protectedFiles\":[\"mjqulngsn\",\"nbybkzgcwrwcl\",\"xwrljdouskcqvkoc\",\"cjdkwtnhxbnjbi\"]}}}") + "{\"config\":{\"rootFile\":\"dkfthwxmnt\",\"files\":[{\"content\":\"opvkmijcm\",\"virtualPath\":\"dcuf\"},{\"content\":\"srp\",\"virtualPath\":\"zidnsezcxtbzsgfy\"},{\"content\":\"sne\",\"virtualPath\":\"dwzjeiach\"},{\"content\":\"osfln\",\"virtualPath\":\"sfqpteehz\"}],\"protectedFiles\":[{\"content\":\"yqrimzin\",\"virtualPath\":\"swjdkirso\",\"contentHash\":\"qxhcrmn\"},{\"content\":\"jtckwhdso\",\"virtualPath\":\"iy\",\"contentHash\":\"jxsqwpgrjbz\"},{\"content\":\"rcjxvsnbyxqabn\",\"virtualPath\":\"cpc\",\"contentHash\":\"hurzafblj\"}],\"package\":{\"data\":\"btoqcjmkljavbqid\",\"protectedFiles\":[\"jzyulpk\",\"dj\"]}}}") .toObject(AnalysisCreate.class); - Assertions.assertEquals("zoxxjtf", model.config().rootFile()); - Assertions.assertEquals("wfzitonpeqfpjk", model.config().files().get(0).content()); - Assertions.assertEquals("xofpdvhpfxxypi", model.config().files().get(0).virtualPath()); - Assertions.assertEquals("bwjzr", model.config().protectedFiles().get(0).content()); - Assertions.assertEquals("ygxgispemvtz", model.config().protectedFiles().get(0).virtualPath()); - Assertions.assertEquals("qjhqjbas", model.config().packageProperty().data()); - Assertions.assertEquals("mjqulngsn", model.config().packageProperty().protectedFiles().get(0)); + Assertions.assertEquals("dkfthwxmnt", model.config().rootFile()); + Assertions.assertEquals("opvkmijcm", model.config().files().get(0).content()); + Assertions.assertEquals("dcuf", model.config().files().get(0).virtualPath()); + Assertions.assertEquals("yqrimzin", model.config().protectedFiles().get(0).content()); + Assertions.assertEquals("swjdkirso", model.config().protectedFiles().get(0).virtualPath()); + Assertions.assertEquals("qxhcrmn", model.config().protectedFiles().get(0).contentHash()); + Assertions.assertEquals("btoqcjmkljavbqid", model.config().packageProperty().data()); + Assertions.assertEquals("jzyulpk", model.config().packageProperty().protectedFiles().get(0)); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - AnalysisCreate model = new AnalysisCreate().withConfig(new AnalysisCreateConfig().withRootFile("zoxxjtf") - .withFiles(Arrays.asList( - new NginxConfigurationFile().withContent("wfzitonpeqfpjk").withVirtualPath("xofpdvhpfxxypi"), - new NginxConfigurationFile().withContent("nmayhuybb").withVirtualPath("odepoogin"), - new NginxConfigurationFile().withContent("amiheognarxz").withVirtualPath("heotusiv"), - new NginxConfigurationFile().withContent("v").withVirtualPath("iqihn"))) - .withProtectedFiles( - Arrays.asList(new NginxConfigurationFile().withContent("bwjzr").withVirtualPath("ygxgispemvtz"), - new NginxConfigurationFile().withContent("ufubl").withVirtualPath("fxqeof"))) - .withPackageProperty(new NginxConfigurationPackage().withData("qjhqjbas") - .withProtectedFiles( - Arrays.asList("mjqulngsn", "nbybkzgcwrwcl", "xwrljdouskcqvkoc", "cjdkwtnhxbnjbi")))); + AnalysisCreate model = new AnalysisCreate().withConfig(new AnalysisCreateConfig().withRootFile("dkfthwxmnt") + .withFiles(Arrays.asList(new NginxConfigurationFile().withContent("opvkmijcm").withVirtualPath("dcuf"), + new NginxConfigurationFile().withContent("srp").withVirtualPath("zidnsezcxtbzsgfy"), + new NginxConfigurationFile().withContent("sne").withVirtualPath("dwzjeiach"), + new NginxConfigurationFile().withContent("osfln").withVirtualPath("sfqpteehz"))) + .withProtectedFiles(Arrays.asList( + new NginxConfigurationProtectedFileRequest().withContent("yqrimzin") + .withVirtualPath("swjdkirso") + .withContentHash("qxhcrmn"), + new NginxConfigurationProtectedFileRequest().withContent("jtckwhdso") + .withVirtualPath("iy") + .withContentHash("jxsqwpgrjbz"), + new NginxConfigurationProtectedFileRequest().withContent("rcjxvsnbyxqabn") + .withVirtualPath("cpc") + .withContentHash("hurzafblj"))) + .withPackageProperty(new NginxConfigurationPackage().withData("btoqcjmkljavbqid") + .withProtectedFiles(Arrays.asList("jzyulpk", "dj")))); model = BinaryData.fromObject(model).toObject(AnalysisCreate.class); - Assertions.assertEquals("zoxxjtf", model.config().rootFile()); - Assertions.assertEquals("wfzitonpeqfpjk", model.config().files().get(0).content()); - Assertions.assertEquals("xofpdvhpfxxypi", model.config().files().get(0).virtualPath()); - Assertions.assertEquals("bwjzr", model.config().protectedFiles().get(0).content()); - Assertions.assertEquals("ygxgispemvtz", model.config().protectedFiles().get(0).virtualPath()); - Assertions.assertEquals("qjhqjbas", model.config().packageProperty().data()); - Assertions.assertEquals("mjqulngsn", model.config().packageProperty().protectedFiles().get(0)); + Assertions.assertEquals("dkfthwxmnt", model.config().rootFile()); + Assertions.assertEquals("opvkmijcm", model.config().files().get(0).content()); + Assertions.assertEquals("dcuf", model.config().files().get(0).virtualPath()); + Assertions.assertEquals("yqrimzin", model.config().protectedFiles().get(0).content()); + Assertions.assertEquals("swjdkirso", model.config().protectedFiles().get(0).virtualPath()); + Assertions.assertEquals("qxhcrmn", model.config().protectedFiles().get(0).contentHash()); + Assertions.assertEquals("btoqcjmkljavbqid", model.config().packageProperty().data()); + Assertions.assertEquals("jzyulpk", model.config().packageProperty().protectedFiles().get(0)); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/AnalysisDiagnosticTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/AnalysisDiagnosticTests.java index e19ff6caffe1..71f0f46c3e80 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/AnalysisDiagnosticTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/AnalysisDiagnosticTests.java @@ -12,33 +12,33 @@ public final class AnalysisDiagnosticTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { AnalysisDiagnostic model = BinaryData.fromString( - "{\"id\":\"wrlyxwjkcprb\",\"directive\":\"wbxgjvt\",\"description\":\"vpys\",\"file\":\"zdn\",\"line\":7.3524117,\"message\":\"jq\",\"rule\":\"uhmuouqfprwzwbn\"}") + "{\"id\":\"n\",\"directive\":\"ulexxbczwtr\",\"description\":\"wiqzbqjvsovmyo\",\"file\":\"acspkwl\",\"line\":98.89727,\"message\":\"dobpxjmflbvvn\",\"rule\":\"hrk\"}") .toObject(AnalysisDiagnostic.class); - Assertions.assertEquals("wrlyxwjkcprb", model.id()); - Assertions.assertEquals("wbxgjvt", model.directive()); - Assertions.assertEquals("vpys", model.description()); - Assertions.assertEquals("zdn", model.file()); - Assertions.assertEquals(7.3524117f, model.line()); - Assertions.assertEquals("jq", model.message()); - Assertions.assertEquals("uhmuouqfprwzwbn", model.rule()); + Assertions.assertEquals("n", model.id()); + Assertions.assertEquals("ulexxbczwtr", model.directive()); + Assertions.assertEquals("wiqzbqjvsovmyo", model.description()); + Assertions.assertEquals("acspkwl", model.file()); + Assertions.assertEquals(98.89727f, model.line()); + Assertions.assertEquals("dobpxjmflbvvn", model.message()); + Assertions.assertEquals("hrk", model.rule()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - AnalysisDiagnostic model = new AnalysisDiagnostic().withId("wrlyxwjkcprb") - .withDirective("wbxgjvt") - .withDescription("vpys") - .withFile("zdn") - .withLine(7.3524117f) - .withMessage("jq") - .withRule("uhmuouqfprwzwbn"); + AnalysisDiagnostic model = new AnalysisDiagnostic().withId("n") + .withDirective("ulexxbczwtr") + .withDescription("wiqzbqjvsovmyo") + .withFile("acspkwl") + .withLine(98.89727f) + .withMessage("dobpxjmflbvvn") + .withRule("hrk"); model = BinaryData.fromObject(model).toObject(AnalysisDiagnostic.class); - Assertions.assertEquals("wrlyxwjkcprb", model.id()); - Assertions.assertEquals("wbxgjvt", model.directive()); - Assertions.assertEquals("vpys", model.description()); - Assertions.assertEquals("zdn", model.file()); - Assertions.assertEquals(7.3524117f, model.line()); - Assertions.assertEquals("jq", model.message()); - Assertions.assertEquals("uhmuouqfprwzwbn", model.rule()); + Assertions.assertEquals("n", model.id()); + Assertions.assertEquals("ulexxbczwtr", model.directive()); + Assertions.assertEquals("wiqzbqjvsovmyo", model.description()); + Assertions.assertEquals("acspkwl", model.file()); + Assertions.assertEquals(98.89727f, model.line()); + Assertions.assertEquals("dobpxjmflbvvn", model.message()); + Assertions.assertEquals("hrk", model.rule()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/AnalysisResultDataTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/AnalysisResultDataTests.java index a5f81cdf1547..8a4ae180052f 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/AnalysisResultDataTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/AnalysisResultDataTests.java @@ -7,6 +7,8 @@ import com.azure.core.util.BinaryData; import com.azure.resourcemanager.nginx.models.AnalysisDiagnostic; import com.azure.resourcemanager.nginx.models.AnalysisResultData; +import com.azure.resourcemanager.nginx.models.DiagnosticItem; +import com.azure.resourcemanager.nginx.models.Level; import java.util.Arrays; import org.junit.jupiter.api.Assertions; @@ -14,41 +16,86 @@ public final class AnalysisResultDataTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { AnalysisResultData model = BinaryData.fromString( - "{\"errors\":[{\"id\":\"kwtmutduqktapspw\",\"directive\":\"cuertu\",\"description\":\"kdosvqw\",\"file\":\"bmdg\",\"line\":14.188546,\"message\":\"jfddgmbmbe\",\"rule\":\"ppbhtqqrolfp\"},{\"id\":\"s\",\"directive\":\"lgbquxig\",\"description\":\"yjgzjaoyfhrtxiln\",\"file\":\"rkujy\",\"line\":55.834507,\"message\":\"l\",\"rule\":\"juvf\"}]}") + "{\"errors\":[{\"id\":\"bqvudwxdndn\",\"directive\":\"owgujjugwdkcglhs\",\"description\":\"azjdyggd\",\"file\":\"jixhbk\",\"line\":99.83777,\"message\":\"fqweykhmene\",\"rule\":\"fyexfwhy\"},{\"id\":\"i\",\"directive\":\"vyvdcs\",\"description\":\"tynnaamdectehfi\",\"file\":\"scjeypv\",\"line\":78.81726,\"message\":\"zrkgqhcjrefovg\",\"rule\":\"kqsleyyvxy\"},{\"id\":\"pkc\",\"directive\":\"t\",\"description\":\"pngjcrcczsqpjhvm\",\"file\":\"ajvnysounqe\",\"line\":2.2711873,\"message\":\"noae\",\"rule\":\"pfhyhl\"}],\"diagnostics\":[{\"id\":\"opjmcmatuokthfui\",\"directive\":\"aodsfcpkv\",\"description\":\"odpuozmyzydag\",\"file\":\"uaxbezyiuokkt\",\"line\":75.16582,\"message\":\"rdxwzywqsm\",\"rule\":\"surex\",\"level\":\"Warning\",\"category\":\"ryocfsfksymdd\"},{\"id\":\"tki\",\"directive\":\"uxh\",\"description\":\"yudxorrqnbp\",\"file\":\"czvyifq\",\"line\":13.800919,\"message\":\"kdvjsll\",\"rule\":\"mvvd\",\"level\":\"Warning\",\"category\":\"t\"}]}") .toObject(AnalysisResultData.class); - Assertions.assertEquals("kwtmutduqktapspw", model.errors().get(0).id()); - Assertions.assertEquals("cuertu", model.errors().get(0).directive()); - Assertions.assertEquals("kdosvqw", model.errors().get(0).description()); - Assertions.assertEquals("bmdg", model.errors().get(0).file()); - Assertions.assertEquals(14.188546f, model.errors().get(0).line()); - Assertions.assertEquals("jfddgmbmbe", model.errors().get(0).message()); - Assertions.assertEquals("ppbhtqqrolfp", model.errors().get(0).rule()); + Assertions.assertEquals("bqvudwxdndn", model.errors().get(0).id()); + Assertions.assertEquals("owgujjugwdkcglhs", model.errors().get(0).directive()); + Assertions.assertEquals("azjdyggd", model.errors().get(0).description()); + Assertions.assertEquals("jixhbk", model.errors().get(0).file()); + Assertions.assertEquals(99.83777f, model.errors().get(0).line()); + Assertions.assertEquals("fqweykhmene", model.errors().get(0).message()); + Assertions.assertEquals("fyexfwhy", model.errors().get(0).rule()); + Assertions.assertEquals("opjmcmatuokthfui", model.diagnostics().get(0).id()); + Assertions.assertEquals("aodsfcpkv", model.diagnostics().get(0).directive()); + Assertions.assertEquals("odpuozmyzydag", model.diagnostics().get(0).description()); + Assertions.assertEquals("uaxbezyiuokkt", model.diagnostics().get(0).file()); + Assertions.assertEquals(75.16582f, model.diagnostics().get(0).line()); + Assertions.assertEquals("rdxwzywqsm", model.diagnostics().get(0).message()); + Assertions.assertEquals("surex", model.diagnostics().get(0).rule()); + Assertions.assertEquals(Level.WARNING, model.diagnostics().get(0).level()); + Assertions.assertEquals("ryocfsfksymdd", model.diagnostics().get(0).category()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - AnalysisResultData model = new AnalysisResultData().withErrors(Arrays.asList( - new AnalysisDiagnostic().withId("kwtmutduqktapspw") - .withDirective("cuertu") - .withDescription("kdosvqw") - .withFile("bmdg") - .withLine(14.188546f) - .withMessage("jfddgmbmbe") - .withRule("ppbhtqqrolfp"), - new AnalysisDiagnostic().withId("s") - .withDirective("lgbquxig") - .withDescription("yjgzjaoyfhrtxiln") - .withFile("rkujy") - .withLine(55.834507f) - .withMessage("l") - .withRule("juvf"))); + AnalysisResultData model = new AnalysisResultData() + .withErrors(Arrays.asList( + new AnalysisDiagnostic().withId("bqvudwxdndn") + .withDirective("owgujjugwdkcglhs") + .withDescription("azjdyggd") + .withFile("jixhbk") + .withLine(99.83777f) + .withMessage("fqweykhmene") + .withRule("fyexfwhy"), + new AnalysisDiagnostic().withId("i") + .withDirective("vyvdcs") + .withDescription("tynnaamdectehfi") + .withFile("scjeypv") + .withLine(78.81726f) + .withMessage("zrkgqhcjrefovg") + .withRule("kqsleyyvxy"), + new AnalysisDiagnostic().withId("pkc") + .withDirective("t") + .withDescription("pngjcrcczsqpjhvm") + .withFile("ajvnysounqe") + .withLine(2.2711873f) + .withMessage("noae") + .withRule("pfhyhl"))) + .withDiagnostics(Arrays.asList( + new DiagnosticItem().withId("opjmcmatuokthfui") + .withDirective("aodsfcpkv") + .withDescription("odpuozmyzydag") + .withFile("uaxbezyiuokkt") + .withLine(75.16582f) + .withMessage("rdxwzywqsm") + .withRule("surex") + .withLevel(Level.WARNING) + .withCategory("ryocfsfksymdd"), + new DiagnosticItem().withId("tki") + .withDirective("uxh") + .withDescription("yudxorrqnbp") + .withFile("czvyifq") + .withLine(13.800919f) + .withMessage("kdvjsll") + .withRule("mvvd") + .withLevel(Level.WARNING) + .withCategory("t"))); model = BinaryData.fromObject(model).toObject(AnalysisResultData.class); - Assertions.assertEquals("kwtmutduqktapspw", model.errors().get(0).id()); - Assertions.assertEquals("cuertu", model.errors().get(0).directive()); - Assertions.assertEquals("kdosvqw", model.errors().get(0).description()); - Assertions.assertEquals("bmdg", model.errors().get(0).file()); - Assertions.assertEquals(14.188546f, model.errors().get(0).line()); - Assertions.assertEquals("jfddgmbmbe", model.errors().get(0).message()); - Assertions.assertEquals("ppbhtqqrolfp", model.errors().get(0).rule()); + Assertions.assertEquals("bqvudwxdndn", model.errors().get(0).id()); + Assertions.assertEquals("owgujjugwdkcglhs", model.errors().get(0).directive()); + Assertions.assertEquals("azjdyggd", model.errors().get(0).description()); + Assertions.assertEquals("jixhbk", model.errors().get(0).file()); + Assertions.assertEquals(99.83777f, model.errors().get(0).line()); + Assertions.assertEquals("fqweykhmene", model.errors().get(0).message()); + Assertions.assertEquals("fyexfwhy", model.errors().get(0).rule()); + Assertions.assertEquals("opjmcmatuokthfui", model.diagnostics().get(0).id()); + Assertions.assertEquals("aodsfcpkv", model.diagnostics().get(0).directive()); + Assertions.assertEquals("odpuozmyzydag", model.diagnostics().get(0).description()); + Assertions.assertEquals("uaxbezyiuokkt", model.diagnostics().get(0).file()); + Assertions.assertEquals(75.16582f, model.diagnostics().get(0).line()); + Assertions.assertEquals("rdxwzywqsm", model.diagnostics().get(0).message()); + Assertions.assertEquals("surex", model.diagnostics().get(0).rule()); + Assertions.assertEquals(Level.WARNING, model.diagnostics().get(0).level()); + Assertions.assertEquals("ryocfsfksymdd", model.diagnostics().get(0).category()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/AnalysisResultInnerTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/AnalysisResultInnerTests.java index d1bed829475e..dc8459788357 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/AnalysisResultInnerTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/AnalysisResultInnerTests.java @@ -8,6 +8,8 @@ import com.azure.resourcemanager.nginx.fluent.models.AnalysisResultInner; import com.azure.resourcemanager.nginx.models.AnalysisDiagnostic; import com.azure.resourcemanager.nginx.models.AnalysisResultData; +import com.azure.resourcemanager.nginx.models.DiagnosticItem; +import com.azure.resourcemanager.nginx.models.Level; import java.util.Arrays; import org.junit.jupiter.api.Assertions; @@ -15,44 +17,107 @@ public final class AnalysisResultInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { AnalysisResultInner model = BinaryData.fromString( - "{\"status\":\"tyxolniwpwc\",\"data\":{\"errors\":[{\"id\":\"giawx\",\"directive\":\"lryplwckbasyy\",\"description\":\"nddhsgcbacph\",\"file\":\"jkot\",\"line\":64.57916,\"message\":\"qgoulznd\",\"rule\":\"i\"},{\"id\":\"yqkgfg\",\"directive\":\"bmadgak\",\"description\":\"qsrxybzqqed\",\"file\":\"ytb\",\"line\":72.395676,\"message\":\"qfou\",\"rule\":\"lmmnkzsmodmglo\"}]}}") + "{\"status\":\"eojnxqbzvddn\",\"data\":{\"errors\":[{\"id\":\"icbtwnpzao\",\"directive\":\"vuhrhcffcyddgl\",\"description\":\"jthjqkwpyei\",\"file\":\"xmqci\",\"line\":2.3759544,\"message\":\"vhkhixu\",\"rule\":\"gdtopbobjogh\"},{\"id\":\"w\",\"directive\":\"a\",\"description\":\"a\",\"file\":\"hrzayvvtpgvdf\",\"line\":66.835686,\"message\":\"otkftutqxlngx\",\"rule\":\"efgugnxk\"},{\"id\":\"dqmidtt\",\"directive\":\"zrvqdr\",\"description\":\"bhj\",\"file\":\"big\",\"line\":4.9429297,\"message\":\"oqfbowskanyk\",\"rule\":\"zlcuiywgqywgndrv\"}],\"diagnostics\":[{\"id\":\"gpphrcgyn\",\"directive\":\"ocpecfvmmco\",\"description\":\"fsxlzevgbmqjqa\",\"file\":\"c\",\"line\":53.236153,\"message\":\"mivkwlzuvcc\",\"rule\":\"wnfnbacf\",\"level\":\"Warning\",\"category\":\"l\"},{\"id\":\"x\",\"directive\":\"tqgtzxdpnqbqq\",\"description\":\"xrjfeallnwsub\",\"file\":\"snjampmng\",\"line\":44.95027,\"message\":\"scxaq\",\"rule\":\"ooch\",\"level\":\"Warning\",\"category\":\"nqvpkvlrxnje\"},{\"id\":\"eipheoflokeyy\",\"directive\":\"enjbdlwtgrhp\",\"description\":\"jp\",\"file\":\"umasxazjpq\",\"line\":4.29253,\"message\":\"gual\",\"rule\":\"b\",\"level\":\"Warning\",\"category\":\"e\"},{\"id\":\"zzvdudgwds\",\"directive\":\"fhotw\",\"description\":\"cynpwlbjnp\",\"file\":\"acfta\",\"line\":63.682568,\"message\":\"h\",\"rule\":\"nltyfsoppusuesnz\",\"level\":\"Info\",\"category\":\"jbavorxzdm\"}]}}") .toObject(AnalysisResultInner.class); - Assertions.assertEquals("tyxolniwpwc", model.status()); - Assertions.assertEquals("giawx", model.data().errors().get(0).id()); - Assertions.assertEquals("lryplwckbasyy", model.data().errors().get(0).directive()); - Assertions.assertEquals("nddhsgcbacph", model.data().errors().get(0).description()); - Assertions.assertEquals("jkot", model.data().errors().get(0).file()); - Assertions.assertEquals(64.57916f, model.data().errors().get(0).line()); - Assertions.assertEquals("qgoulznd", model.data().errors().get(0).message()); - Assertions.assertEquals("i", model.data().errors().get(0).rule()); + Assertions.assertEquals("eojnxqbzvddn", model.status()); + Assertions.assertEquals("icbtwnpzao", model.data().errors().get(0).id()); + Assertions.assertEquals("vuhrhcffcyddgl", model.data().errors().get(0).directive()); + Assertions.assertEquals("jthjqkwpyei", model.data().errors().get(0).description()); + Assertions.assertEquals("xmqci", model.data().errors().get(0).file()); + Assertions.assertEquals(2.3759544f, model.data().errors().get(0).line()); + Assertions.assertEquals("vhkhixu", model.data().errors().get(0).message()); + Assertions.assertEquals("gdtopbobjogh", model.data().errors().get(0).rule()); + Assertions.assertEquals("gpphrcgyn", model.data().diagnostics().get(0).id()); + Assertions.assertEquals("ocpecfvmmco", model.data().diagnostics().get(0).directive()); + Assertions.assertEquals("fsxlzevgbmqjqa", model.data().diagnostics().get(0).description()); + Assertions.assertEquals("c", model.data().diagnostics().get(0).file()); + Assertions.assertEquals(53.236153f, model.data().diagnostics().get(0).line()); + Assertions.assertEquals("mivkwlzuvcc", model.data().diagnostics().get(0).message()); + Assertions.assertEquals("wnfnbacf", model.data().diagnostics().get(0).rule()); + Assertions.assertEquals(Level.WARNING, model.data().diagnostics().get(0).level()); + Assertions.assertEquals("l", model.data().diagnostics().get(0).category()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - AnalysisResultInner model = new AnalysisResultInner().withStatus("tyxolniwpwc") - .withData(new AnalysisResultData().withErrors(Arrays.asList( - new AnalysisDiagnostic().withId("giawx") - .withDirective("lryplwckbasyy") - .withDescription("nddhsgcbacph") - .withFile("jkot") - .withLine(64.57916f) - .withMessage("qgoulznd") - .withRule("i"), - new AnalysisDiagnostic().withId("yqkgfg") - .withDirective("bmadgak") - .withDescription("qsrxybzqqed") - .withFile("ytb") - .withLine(72.395676f) - .withMessage("qfou") - .withRule("lmmnkzsmodmglo")))); + AnalysisResultInner model = new AnalysisResultInner().withStatus("eojnxqbzvddn") + .withData(new AnalysisResultData() + .withErrors(Arrays.asList( + new AnalysisDiagnostic().withId("icbtwnpzao") + .withDirective("vuhrhcffcyddgl") + .withDescription("jthjqkwpyei") + .withFile("xmqci") + .withLine(2.3759544f) + .withMessage("vhkhixu") + .withRule("gdtopbobjogh"), + new AnalysisDiagnostic().withId("w") + .withDirective("a") + .withDescription("a") + .withFile("hrzayvvtpgvdf") + .withLine(66.835686f) + .withMessage("otkftutqxlngx") + .withRule("efgugnxk"), + new AnalysisDiagnostic().withId("dqmidtt") + .withDirective("zrvqdr") + .withDescription("bhj") + .withFile("big") + .withLine(4.9429297f) + .withMessage("oqfbowskanyk") + .withRule("zlcuiywgqywgndrv"))) + .withDiagnostics(Arrays.asList( + new DiagnosticItem().withId("gpphrcgyn") + .withDirective("ocpecfvmmco") + .withDescription("fsxlzevgbmqjqa") + .withFile("c") + .withLine(53.236153f) + .withMessage("mivkwlzuvcc") + .withRule("wnfnbacf") + .withLevel(Level.WARNING) + .withCategory("l"), + new DiagnosticItem().withId("x") + .withDirective("tqgtzxdpnqbqq") + .withDescription("xrjfeallnwsub") + .withFile("snjampmng") + .withLine(44.95027f) + .withMessage("scxaq") + .withRule("ooch") + .withLevel(Level.WARNING) + .withCategory("nqvpkvlrxnje"), + new DiagnosticItem().withId("eipheoflokeyy") + .withDirective("enjbdlwtgrhp") + .withDescription("jp") + .withFile("umasxazjpq") + .withLine(4.29253f) + .withMessage("gual") + .withRule("b") + .withLevel(Level.WARNING) + .withCategory("e"), + new DiagnosticItem().withId("zzvdudgwds") + .withDirective("fhotw") + .withDescription("cynpwlbjnp") + .withFile("acfta") + .withLine(63.682568f) + .withMessage("h") + .withRule("nltyfsoppusuesnz") + .withLevel(Level.INFO) + .withCategory("jbavorxzdm")))); model = BinaryData.fromObject(model).toObject(AnalysisResultInner.class); - Assertions.assertEquals("tyxolniwpwc", model.status()); - Assertions.assertEquals("giawx", model.data().errors().get(0).id()); - Assertions.assertEquals("lryplwckbasyy", model.data().errors().get(0).directive()); - Assertions.assertEquals("nddhsgcbacph", model.data().errors().get(0).description()); - Assertions.assertEquals("jkot", model.data().errors().get(0).file()); - Assertions.assertEquals(64.57916f, model.data().errors().get(0).line()); - Assertions.assertEquals("qgoulznd", model.data().errors().get(0).message()); - Assertions.assertEquals("i", model.data().errors().get(0).rule()); + Assertions.assertEquals("eojnxqbzvddn", model.status()); + Assertions.assertEquals("icbtwnpzao", model.data().errors().get(0).id()); + Assertions.assertEquals("vuhrhcffcyddgl", model.data().errors().get(0).directive()); + Assertions.assertEquals("jthjqkwpyei", model.data().errors().get(0).description()); + Assertions.assertEquals("xmqci", model.data().errors().get(0).file()); + Assertions.assertEquals(2.3759544f, model.data().errors().get(0).line()); + Assertions.assertEquals("vhkhixu", model.data().errors().get(0).message()); + Assertions.assertEquals("gdtopbobjogh", model.data().errors().get(0).rule()); + Assertions.assertEquals("gpphrcgyn", model.data().diagnostics().get(0).id()); + Assertions.assertEquals("ocpecfvmmco", model.data().diagnostics().get(0).directive()); + Assertions.assertEquals("fsxlzevgbmqjqa", model.data().diagnostics().get(0).description()); + Assertions.assertEquals("c", model.data().diagnostics().get(0).file()); + Assertions.assertEquals(53.236153f, model.data().diagnostics().get(0).line()); + Assertions.assertEquals("mivkwlzuvcc", model.data().diagnostics().get(0).message()); + Assertions.assertEquals("wnfnbacf", model.data().diagnostics().get(0).rule()); + Assertions.assertEquals(Level.WARNING, model.data().diagnostics().get(0).level()); + Assertions.assertEquals("l", model.data().diagnostics().get(0).category()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ApiKeysDeleteWithResponseMockTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ApiKeysDeleteWithResponseMockTests.java new file mode 100644 index 000000000000..83529b0ee1da --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ApiKeysDeleteWithResponseMockTests.java @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.nginx.NginxManager; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class ApiKeysDeleteWithResponseMockTests { + @Test + public void testDeleteWithResponse() throws Exception { + String responseStr = "{}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + NginxManager manager = NginxManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + manager.apiKeys().deleteWithResponse("wzsyyceuzs", "i", "judpfrxt", com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ApiKeysGetWithResponseMockTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ApiKeysGetWithResponseMockTests.java new file mode 100644 index 000000000000..552ff6d6a0db --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ApiKeysGetWithResponseMockTests.java @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.nginx.NginxManager; +import com.azure.resourcemanager.nginx.models.NginxDeploymentApiKeyResponse; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class ApiKeysGetWithResponseMockTests { + @Test + public void testGetWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"hint\":\"axoruzfgsquy\",\"endDateTime\":\"2021-03-18T06:01:03Z\"},\"id\":\"xxle\",\"name\":\"tramxjez\",\"type\":\"lwnwxuqlcvydyp\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + NginxManager manager = NginxManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + NginxDeploymentApiKeyResponse response = manager.apiKeys() + .getWithResponse("thzvaytdwkqbrqu", "paxh", "xiilivpdtiirqt", com.azure.core.util.Context.NONE) + .getValue(); + + Assertions.assertEquals(OffsetDateTime.parse("2021-03-18T06:01:03Z"), response.properties().endDateTime()); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ApiKeysListMockTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ApiKeysListMockTests.java new file mode 100644 index 000000000000..37ffa75624ab --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ApiKeysListMockTests.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.resourcemanager.nginx.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.nginx.NginxManager; +import com.azure.resourcemanager.nginx.models.NginxDeploymentApiKeyResponse; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class ApiKeysListMockTests { + @Test + public void testList() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"hint\":\"jhemms\",\"endDateTime\":\"2021-07-03T07:44:33Z\"},\"id\":\"kcrodtjinfw\",\"name\":\"lfltka\",\"type\":\"jvefkdlfoakggkfp\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + NginxManager manager = NginxManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + PagedIterable response + = manager.apiKeys().list("tdooaoj", "niodkooeb", com.azure.core.util.Context.NONE); + + Assertions.assertEquals(OffsetDateTime.parse("2021-07-03T07:44:33Z"), + response.iterator().next().properties().endDateTime()); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/AutoUpgradeProfileTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/AutoUpgradeProfileTests.java index d83631c77fcc..2cb59bc60cc9 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/AutoUpgradeProfileTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/AutoUpgradeProfileTests.java @@ -12,14 +12,14 @@ public final class AutoUpgradeProfileTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { AutoUpgradeProfile model - = BinaryData.fromString("{\"upgradeChannel\":\"kktwhrdxw\"}").toObject(AutoUpgradeProfile.class); - Assertions.assertEquals("kktwhrdxw", model.upgradeChannel()); + = BinaryData.fromString("{\"upgradeChannel\":\"c\"}").toObject(AutoUpgradeProfile.class); + Assertions.assertEquals("c", model.upgradeChannel()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - AutoUpgradeProfile model = new AutoUpgradeProfile().withUpgradeChannel("kktwhrdxw"); + AutoUpgradeProfile model = new AutoUpgradeProfile().withUpgradeChannel("c"); model = BinaryData.fromObject(model).toObject(AutoUpgradeProfile.class); - Assertions.assertEquals("kktwhrdxw", model.upgradeChannel()); + Assertions.assertEquals("c", model.upgradeChannel()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/CertificatesDeleteMockTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/CertificatesDeleteMockTests.java index b05b33acf6a8..357681a891c3 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/CertificatesDeleteMockTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/CertificatesDeleteMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.nginx.NginxManager; import java.nio.charset.StandardCharsets; @@ -25,9 +25,9 @@ public void testDelete() throws Exception { NginxManager manager = NginxManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); - manager.certificates().delete("euojgjrwju", "iotwmcdytdxwit", "nrjawgqwg", com.azure.core.util.Context.NONE); + manager.certificates().delete("yfzqwhxxbu", "qa", "zfeqztppri", com.azure.core.util.Context.NONE); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ConfigurationsAnalysisWithResponseMockTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ConfigurationsAnalysisWithResponseMockTests.java index 4e7f0d5b9221..538f67771ca8 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ConfigurationsAnalysisWithResponseMockTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ConfigurationsAnalysisWithResponseMockTests.java @@ -6,15 +6,17 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.nginx.NginxManager; import com.azure.resourcemanager.nginx.models.AnalysisCreate; import com.azure.resourcemanager.nginx.models.AnalysisCreateConfig; import com.azure.resourcemanager.nginx.models.AnalysisResult; +import com.azure.resourcemanager.nginx.models.Level; import com.azure.resourcemanager.nginx.models.NginxConfigurationFile; import com.azure.resourcemanager.nginx.models.NginxConfigurationPackage; +import com.azure.resourcemanager.nginx.models.NginxConfigurationProtectedFileRequest; import java.nio.charset.StandardCharsets; import java.time.OffsetDateTime; import java.util.Arrays; @@ -26,34 +28,55 @@ public final class ConfigurationsAnalysisWithResponseMockTests { @Test public void testAnalysisWithResponse() throws Exception { String responseStr - = "{\"status\":\"eh\",\"data\":{\"errors\":[{\"id\":\"gmifthnzd\",\"directive\":\"dslgnayqigynduh\",\"description\":\"vhqlkthumaqo\",\"file\":\"bgycduiertgccym\",\"line\":30.20277,\"message\":\"olpsslqlf\",\"rule\":\"mdnbbglzpswiy\"},{\"id\":\"cwyhzdxssa\",\"directive\":\"bzmnvdfznud\",\"description\":\"od\",\"file\":\"xzb\",\"line\":92.67567,\"message\":\"blylpstdbh\",\"rule\":\"xsrz\"}]}}"; + = "{\"status\":\"lmdjrkvfgbvfvpdb\",\"data\":{\"errors\":[{\"id\":\"zsjqlh\",\"directive\":\"rribd\",\"description\":\"ibqipqkg\",\"file\":\"vxndz\",\"line\":86.36127,\"message\":\"krefajpjo\",\"rule\":\"wkqnyhg\"},{\"id\":\"j\",\"directive\":\"jivfxzsjabib\",\"description\":\"ystawfsdjpvkvp\",\"file\":\"jxbkzbzkdvn\",\"line\":76.89379,\"message\":\"abudurgk\",\"rule\":\"kmokz\"},{\"id\":\"jk\",\"directive\":\"ffhmouwqlgzr\",\"description\":\"zeeyebi\",\"file\":\"ikayuhqlbjbsybb\",\"line\":12.803698,\"message\":\"r\",\"rule\":\"t\"},{\"id\":\"gmfpgvmp\",\"directive\":\"paslthaqfxssmwu\",\"description\":\"wbdsr\",\"file\":\"zpdrhneu\",\"line\":67.33827,\"message\":\"wqkdwytisibi\",\"rule\":\"cgpik\"}],\"diagnostics\":[{\"id\":\"ejzanlfz\",\"directive\":\"iavrm\",\"description\":\"zonokixrjqci\",\"file\":\"gzpfrla\",\"line\":33.48236,\"message\":\"zrnw\",\"rule\":\"iin\",\"level\":\"Warning\",\"category\":\"wp\"},{\"id\":\"lwbtlhf\",\"directive\":\"sj\",\"description\":\"dhszfjv\",\"file\":\"bgofeljag\",\"line\":66.963486,\"message\":\"mqhldvrii\",\"rule\":\"ojnal\",\"level\":\"Warning\",\"category\":\"kvtvsexso\"}]}}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NginxManager manager = NginxManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); AnalysisResult response = manager.configurations() - .analysisWithResponse("tkblmpewww", "bkrvrnsvshqj", "hxcr", - new AnalysisCreate().withConfig(new AnalysisCreateConfig().withRootFile("fovasr") - .withFiles(Arrays - .asList(new NginxConfigurationFile().withContent("bhsqfsubcgjbirxb").withVirtualPath("bsrfbj"))) - .withProtectedFiles(Arrays - .asList(new NginxConfigurationFile().withContent("ssotftpv").withVirtualPath("bexilzznfqqnv"))) - .withPackageProperty(new NginxConfigurationPackage().withData("qtaruoujmkcjhwq") - .withProtectedFiles(Arrays.asList("r", "bnw", "ewgdrjervn", "enq")))), + .analysisWithResponse("rmaequ", "ah", "icslfaoq", new AnalysisCreate().withConfig(new AnalysisCreateConfig() + .withRootFile("iyylhalnswhccsp") + .withFiles(Arrays.asList(new NginxConfigurationFile().withContent("vwitqscyw").withVirtualPath("gwol"), + new NginxConfigurationFile().withContent("czbwemhairsbr").withVirtualPath("dwmsweypqwd"), + new NginxConfigurationFile().withContent("gicccnxqhuex").withVirtualPath("ttlstvlzywemhz"))) + .withProtectedFiles(Arrays.asList( + new NginxConfigurationProtectedFileRequest().withContent("dtclusiypb") + .withVirtualPath("gytguslfead") + .withContentHash("gq"), + new NginxConfigurationProtectedFileRequest().withContent("yhejhzisxgfp") + .withVirtualPath("olppvksrpqvujz") + .withContentHash("ehtwdwrft"), + new NginxConfigurationProtectedFileRequest().withContent("iby") + .withVirtualPath("dl") + .withContentHash("shfwpracstwity"), + new NginxConfigurationProtectedFileRequest().withContent("evxccedcp") + .withVirtualPath("dyodnwzxltj") + .withContentHash("nhltiugcxn"))) + .withPackageProperty( + new NginxConfigurationPackage().withData("wxqibyq").withProtectedFiles(Arrays.asList("owx")))), com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("eh", response.status()); - Assertions.assertEquals("gmifthnzd", response.data().errors().get(0).id()); - Assertions.assertEquals("dslgnayqigynduh", response.data().errors().get(0).directive()); - Assertions.assertEquals("vhqlkthumaqo", response.data().errors().get(0).description()); - Assertions.assertEquals("bgycduiertgccym", response.data().errors().get(0).file()); - Assertions.assertEquals(30.20277f, response.data().errors().get(0).line()); - Assertions.assertEquals("olpsslqlf", response.data().errors().get(0).message()); - Assertions.assertEquals("mdnbbglzpswiy", response.data().errors().get(0).rule()); + Assertions.assertEquals("lmdjrkvfgbvfvpdb", response.status()); + Assertions.assertEquals("zsjqlh", response.data().errors().get(0).id()); + Assertions.assertEquals("rribd", response.data().errors().get(0).directive()); + Assertions.assertEquals("ibqipqkg", response.data().errors().get(0).description()); + Assertions.assertEquals("vxndz", response.data().errors().get(0).file()); + Assertions.assertEquals(86.36127f, response.data().errors().get(0).line()); + Assertions.assertEquals("krefajpjo", response.data().errors().get(0).message()); + Assertions.assertEquals("wkqnyhg", response.data().errors().get(0).rule()); + Assertions.assertEquals("ejzanlfz", response.data().diagnostics().get(0).id()); + Assertions.assertEquals("iavrm", response.data().diagnostics().get(0).directive()); + Assertions.assertEquals("zonokixrjqci", response.data().diagnostics().get(0).description()); + Assertions.assertEquals("gzpfrla", response.data().diagnostics().get(0).file()); + Assertions.assertEquals(33.48236f, response.data().diagnostics().get(0).line()); + Assertions.assertEquals("zrnw", response.data().diagnostics().get(0).message()); + Assertions.assertEquals("iin", response.data().diagnostics().get(0).rule()); + Assertions.assertEquals(Level.WARNING, response.data().diagnostics().get(0).level()); + Assertions.assertEquals("wp", response.data().diagnostics().get(0).category()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ConfigurationsCreateOrUpdateMockTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ConfigurationsCreateOrUpdateMockTests.java index 351e94db853a..90f9481b40e4 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ConfigurationsCreateOrUpdateMockTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ConfigurationsCreateOrUpdateMockTests.java @@ -6,14 +6,15 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.nginx.NginxManager; -import com.azure.resourcemanager.nginx.models.NginxConfiguration; import com.azure.resourcemanager.nginx.models.NginxConfigurationFile; import com.azure.resourcemanager.nginx.models.NginxConfigurationPackage; -import com.azure.resourcemanager.nginx.models.NginxConfigurationProperties; +import com.azure.resourcemanager.nginx.models.NginxConfigurationProtectedFileRequest; +import com.azure.resourcemanager.nginx.models.NginxConfigurationRequestProperties; +import com.azure.resourcemanager.nginx.models.NginxConfigurationResponse; import java.nio.charset.StandardCharsets; import java.time.OffsetDateTime; import java.util.Arrays; @@ -25,38 +26,44 @@ public final class ConfigurationsCreateOrUpdateMockTests { @Test public void testCreateOrUpdate() throws Exception { String responseStr - = "{\"properties\":{\"provisioningState\":\"Succeeded\",\"files\":[{\"content\":\"hjpglkf\",\"virtualPath\":\"hdneuelfph\"},{\"content\":\"yhtozfikdowwqu\",\"virtualPath\":\"xzxcl\"},{\"content\":\"thhqzonosggbh\",\"virtualPath\":\"hfwdsjnkaljutiis\"},{\"content\":\"cffgdkzzewk\",\"virtualPath\":\"hqcrailvpnpp\"}],\"protectedFiles\":[{\"content\":\"rwdmhdlxyjrxsa\",\"virtualPath\":\"fcnihgwq\"},{\"content\":\"nedgfbc\",\"virtualPath\":\"cvqvpkeqdcv\"}],\"package\":{\"data\":\"vo\",\"protectedFiles\":[\"otbobzdopcj\",\"vnhdldwmgxcxr\"]},\"rootFile\":\"pmutwuo\"},\"location\":\"rpkhjwn\",\"id\":\"qsluicp\",\"name\":\"ggkzzlvmbmpa\",\"type\":\"modfvuefywsbpfvm\"}"; + = "{\"properties\":{\"provisioningState\":\"Succeeded\",\"files\":[{\"content\":\"ypgik\",\"virtualPath\":\"szywkbirryu\"},{\"content\":\"lhkjoqrvqq\",\"virtualPath\":\"t\"},{\"content\":\"nrvgoupmfiibfgg\",\"virtualPath\":\"ool\"}],\"protectedFiles\":[{\"virtualPath\":\"kvtkkg\",\"contentHash\":\"qwjygvja\"},{\"virtualPath\":\"blmhvkzuhb\",\"contentHash\":\"vyhgs\"},{\"virtualPath\":\"byrqufeg\",\"contentHash\":\"vwz\"}],\"package\":{\"data\":\"hlmctlpdngitvgb\",\"protectedFiles\":[\"ixkwmyijejveg\",\"hbpnaixexccbd\",\"eaxhcexdrrvqahqk\",\"htpwij\"]},\"rootFile\":\"yjsvfyc\"},\"id\":\"bfvoowvrv\",\"name\":\"t\",\"type\":\"jqppyostronzmy\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NginxManager manager = NginxManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); - NginxConfiguration response = manager.configurations() - .define("tmweriofzpyq") - .withExistingNginxDeployment("zucerscdntnev", "iwjmygtdssls") - .withRegion("pgcjefuzmuvp") - .withProperties(new NginxConfigurationProperties() - .withFiles(Arrays.asList(new NginxConfigurationFile().withContent("ets").withVirtualPath("szhedplvw"), - new NginxConfigurationFile().withContent("ubmwmbesld").withVirtualPath("wwtppj"))) - .withProtectedFiles( - Arrays.asList(new NginxConfigurationFile().withContent("ogaok").withVirtualPath("z"), - new NginxConfigurationFile().withContent("sikvmkqzeqqkdlt").withVirtualPath("xmhhvhgureo"), - new NginxConfigurationFile().withContent("wobdagxtibqdx").withVirtualPath("wakbogqxndl"))) - .withPackageProperty(new NginxConfigurationPackage().withData("xhuri") - .withProtectedFiles(Arrays.asList("podxunkb", "bxmubyynt", "lrb", "tkoievseotgq"))) - .withRootFile("ltmuwlauwzizx")) + NginxConfigurationResponse response = manager.configurations() + .define("ughftqsx") + .withExistingNginxDeployment("ueluqhhahhxvrhmz", "wpjgwws") + .withProperties(new NginxConfigurationRequestProperties() + .withFiles( + Arrays.asList(new NginxConfigurationFile().withContent("kndxdigrjgu").withVirtualPath("zdmsyqtfi"), + new NginxConfigurationFile().withContent("hbotzingamvppho").withVirtualPath("qzudphq"), + new NginxConfigurationFile().withContent("vdkfwynwcvtbvk").withVirtualPath("hmtnvy"))) + .withProtectedFiles(Arrays.asList( + new NginxConfigurationProtectedFileRequest().withContent("kzwpcnpw") + .withVirtualPath("jaesgvvsccya") + .withContentHash("uq"), + new NginxConfigurationProtectedFileRequest().withContent("wygzlvdnkfxusem") + .withVirtualPath("zrmuhapfcqdps") + .withContentHash("qvpsvuoymg"), + new NginxConfigurationProtectedFileRequest().withContent("elvezrypq") + .withVirtualPath("feo") + .withContentHash("rqwky"))) + .withPackageProperty(new NginxConfigurationPackage().withData("bopgxedkowepbqp") + .withProtectedFiles(Arrays.asList("kbwcc"))) + .withRootFile("jvcdwxlpqekf")) .create(); - Assertions.assertEquals("hjpglkf", response.properties().files().get(0).content()); - Assertions.assertEquals("hdneuelfph", response.properties().files().get(0).virtualPath()); - Assertions.assertEquals("rwdmhdlxyjrxsa", response.properties().protectedFiles().get(0).content()); - Assertions.assertEquals("fcnihgwq", response.properties().protectedFiles().get(0).virtualPath()); - Assertions.assertEquals("vo", response.properties().packageProperty().data()); - Assertions.assertEquals("otbobzdopcj", response.properties().packageProperty().protectedFiles().get(0)); - Assertions.assertEquals("pmutwuo", response.properties().rootFile()); - Assertions.assertEquals("rpkhjwn", response.location()); + Assertions.assertEquals("ypgik", response.properties().files().get(0).content()); + Assertions.assertEquals("szywkbirryu", response.properties().files().get(0).virtualPath()); + Assertions.assertEquals("kvtkkg", response.properties().protectedFiles().get(0).virtualPath()); + Assertions.assertEquals("qwjygvja", response.properties().protectedFiles().get(0).contentHash()); + Assertions.assertEquals("hlmctlpdngitvgb", response.properties().packageProperty().data()); + Assertions.assertEquals("ixkwmyijejveg", response.properties().packageProperty().protectedFiles().get(0)); + Assertions.assertEquals("yjsvfyc", response.properties().rootFile()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ConfigurationsDeleteMockTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ConfigurationsDeleteMockTests.java index 2e7d3aecd5bf..0a6f8c0dfd15 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ConfigurationsDeleteMockTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ConfigurationsDeleteMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.nginx.NginxManager; import java.nio.charset.StandardCharsets; @@ -25,9 +25,9 @@ public void testDelete() throws Exception { NginxManager manager = NginxManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); - manager.configurations().delete("qaqtdoqmcbxvwvxy", "lqbhsf", "obl", com.azure.core.util.Context.NONE); + manager.configurations().delete("bminrfdwoyuhhzi", "iefozbhdmsml", "zqhof", com.azure.core.util.Context.NONE); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ConfigurationsGetWithResponseMockTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ConfigurationsGetWithResponseMockTests.java index 62cea59da5cd..1b7de8a7c393 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ConfigurationsGetWithResponseMockTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ConfigurationsGetWithResponseMockTests.java @@ -6,11 +6,11 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.nginx.NginxManager; -import com.azure.resourcemanager.nginx.models.NginxConfiguration; +import com.azure.resourcemanager.nginx.models.NginxConfigurationResponse; import java.nio.charset.StandardCharsets; import java.time.OffsetDateTime; import org.junit.jupiter.api.Assertions; @@ -21,26 +21,25 @@ public final class ConfigurationsGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"provisioningState\":\"Deleting\",\"files\":[{\"content\":\"xisxyawjoyaqcsl\",\"virtualPath\":\"pkii\"},{\"content\":\"yexz\",\"virtualPath\":\"lixhnrztfol\"},{\"content\":\"nxknalaulp\",\"virtualPath\":\"gdtpnapnyiro\"},{\"content\":\"hpigv\",\"virtualPath\":\"ylgqgitxmedjvcsl\"}],\"protectedFiles\":[{\"content\":\"wncwzzhxgktrmg\",\"virtualPath\":\"napkteoellw\"},{\"content\":\"fdygpfqbuaceopz\",\"virtualPath\":\"rhhuaopppcqeqx\"}],\"package\":{\"data\":\"dahzxctobg\",\"protectedFiles\":[\"moizpos\",\"mgrcfbu\",\"rmfqjhhkxbpvj\"]},\"rootFile\":\"jhxxjyn\"},\"location\":\"divkrt\",\"id\":\"bxqz\",\"name\":\"szjfauvjfdxxivet\",\"type\":\"t\"}"; + = "{\"properties\":{\"provisioningState\":\"NotSpecified\",\"files\":[{\"content\":\"oyzko\",\"virtualPath\":\"tlmngu\"}],\"protectedFiles\":[{\"virtualPath\":\"aldsy\",\"contentHash\":\"ximerqfobwyznk\"},{\"virtualPath\":\"kutwpf\",\"contentHash\":\"a\"}],\"package\":{\"data\":\"r\",\"protectedFiles\":[\"snfdsdoakgtdl\",\"kkze\",\"dlhewp\",\"sdsttwvog\"]},\"rootFile\":\"bejdcn\"},\"id\":\"qmoa\",\"name\":\"ufgmjzrwrdg\",\"type\":\"twaenuuzko\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NginxManager manager = NginxManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); - NginxConfiguration response = manager.configurations() - .getWithResponse("oekqvk", "lns", "vbxwyjsflhh", com.azure.core.util.Context.NONE) + NginxConfigurationResponse response = manager.configurations() + .getWithResponse("zxkhnzbonlwnto", "gokdwbwhks", "zcmrvexztvb", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("xisxyawjoyaqcsl", response.properties().files().get(0).content()); - Assertions.assertEquals("pkii", response.properties().files().get(0).virtualPath()); - Assertions.assertEquals("wncwzzhxgktrmg", response.properties().protectedFiles().get(0).content()); - Assertions.assertEquals("napkteoellw", response.properties().protectedFiles().get(0).virtualPath()); - Assertions.assertEquals("dahzxctobg", response.properties().packageProperty().data()); - Assertions.assertEquals("moizpos", response.properties().packageProperty().protectedFiles().get(0)); - Assertions.assertEquals("jhxxjyn", response.properties().rootFile()); - Assertions.assertEquals("divkrt", response.location()); + Assertions.assertEquals("oyzko", response.properties().files().get(0).content()); + Assertions.assertEquals("tlmngu", response.properties().files().get(0).virtualPath()); + Assertions.assertEquals("aldsy", response.properties().protectedFiles().get(0).virtualPath()); + Assertions.assertEquals("ximerqfobwyznk", response.properties().protectedFiles().get(0).contentHash()); + Assertions.assertEquals("r", response.properties().packageProperty().data()); + Assertions.assertEquals("snfdsdoakgtdl", response.properties().packageProperty().protectedFiles().get(0)); + Assertions.assertEquals("bejdcn", response.properties().rootFile()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ConfigurationsListMockTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ConfigurationsListMockTests.java index 2a0ee50c1e26..e8dc29c6ea4d 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ConfigurationsListMockTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ConfigurationsListMockTests.java @@ -7,11 +7,11 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.nginx.NginxManager; -import com.azure.resourcemanager.nginx.models.NginxConfiguration; +import com.azure.resourcemanager.nginx.models.NginxConfigurationResponse; import java.nio.charset.StandardCharsets; import java.time.OffsetDateTime; import org.junit.jupiter.api.Assertions; @@ -22,27 +22,27 @@ public final class ConfigurationsListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"provisioningState\":\"Accepted\",\"files\":[{\"content\":\"wyzmhtxon\",\"virtualPath\":\"ts\"}],\"protectedFiles\":[{\"content\":\"bp\",\"virtualPath\":\"qpsrknftguvri\"},{\"content\":\"prwmdyvxqt\",\"virtualPath\":\"riwwroy\"},{\"content\":\"exrmcqibycnojvk\",\"virtualPath\":\"e\"},{\"content\":\"sgzvahapjyzhpv\",\"virtualPath\":\"zcjrvxdjzlmwlx\"}],\"package\":{\"data\":\"gfhzovawjvzunlut\",\"protectedFiles\":[\"prnxipeil\"]},\"rootFile\":\"zuaejxd\"},\"location\":\"tskzbbtdzumveek\",\"id\":\"wozuhkf\",\"name\":\"bsjyofdx\",\"type\":\"uusdttouwa\"}]}"; + = "{\"value\":[{\"properties\":{\"provisioningState\":\"NotSpecified\",\"files\":[{\"content\":\"kycgrauwj\",\"virtualPath\":\"taeburuvdm\"}],\"protectedFiles\":[{\"virtualPath\":\"zlxwabmqoefkifr\",\"contentHash\":\"puqujmqlgkfbtn\"}],\"package\":{\"data\":\"ongbjcnt\",\"protectedFiles\":[\"tcje\"]},\"rootFile\":\"twwaezkojvdcpzf\"},\"id\":\"ouicybxarzgszu\",\"name\":\"oxciqopidoamcio\",\"type\":\"hkh\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NginxManager manager = NginxManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); - PagedIterable response - = manager.configurations().list("jkbegibtnmxiebww", "loayqcgw", com.azure.core.util.Context.NONE); + PagedIterable response + = manager.configurations().list("bgdknnqv", "aznqntoru", com.azure.core.util.Context.NONE); - Assertions.assertEquals("wyzmhtxon", response.iterator().next().properties().files().get(0).content()); - Assertions.assertEquals("ts", response.iterator().next().properties().files().get(0).virtualPath()); - Assertions.assertEquals("bp", response.iterator().next().properties().protectedFiles().get(0).content()); - Assertions.assertEquals("qpsrknftguvri", + Assertions.assertEquals("kycgrauwj", response.iterator().next().properties().files().get(0).content()); + Assertions.assertEquals("taeburuvdm", response.iterator().next().properties().files().get(0).virtualPath()); + Assertions.assertEquals("zlxwabmqoefkifr", response.iterator().next().properties().protectedFiles().get(0).virtualPath()); - Assertions.assertEquals("gfhzovawjvzunlut", response.iterator().next().properties().packageProperty().data()); - Assertions.assertEquals("prnxipeil", + Assertions.assertEquals("puqujmqlgkfbtn", + response.iterator().next().properties().protectedFiles().get(0).contentHash()); + Assertions.assertEquals("ongbjcnt", response.iterator().next().properties().packageProperty().data()); + Assertions.assertEquals("tcje", response.iterator().next().properties().packageProperty().protectedFiles().get(0)); - Assertions.assertEquals("zuaejxd", response.iterator().next().properties().rootFile()); - Assertions.assertEquals("tskzbbtdzumveek", response.iterator().next().location()); + Assertions.assertEquals("twwaezkojvdcpzf", response.iterator().next().properties().rootFile()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/DeploymentsCreateOrUpdateMockTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/DeploymentsCreateOrUpdateMockTests.java index 5c694af1c5a8..e45e033f5d24 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/DeploymentsCreateOrUpdateMockTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/DeploymentsCreateOrUpdateMockTests.java @@ -6,15 +6,17 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.nginx.NginxManager; +import com.azure.resourcemanager.nginx.models.ActivationState; import com.azure.resourcemanager.nginx.models.AutoUpgradeProfile; import com.azure.resourcemanager.nginx.models.IdentityProperties; import com.azure.resourcemanager.nginx.models.IdentityType; import com.azure.resourcemanager.nginx.models.NginxDeployment; import com.azure.resourcemanager.nginx.models.NginxDeploymentProperties; +import com.azure.resourcemanager.nginx.models.NginxDeploymentPropertiesNginxAppProtect; import com.azure.resourcemanager.nginx.models.NginxDeploymentScalingProperties; import com.azure.resourcemanager.nginx.models.NginxDeploymentUserProfile; import com.azure.resourcemanager.nginx.models.NginxFrontendIpConfiguration; @@ -28,6 +30,7 @@ import com.azure.resourcemanager.nginx.models.ScaleProfile; import com.azure.resourcemanager.nginx.models.ScaleProfileCapacity; import com.azure.resourcemanager.nginx.models.UserIdentityProperties; +import com.azure.resourcemanager.nginx.models.WebApplicationFirewallSettings; import java.nio.charset.StandardCharsets; import java.time.OffsetDateTime; import java.util.Arrays; @@ -41,66 +44,66 @@ public final class DeploymentsCreateOrUpdateMockTests { @Test public void testCreateOrUpdate() throws Exception { String responseStr - = "{\"identity\":{\"principalId\":\"xwabmqoe\",\"tenantId\":\"ifrvtpu\",\"type\":\"UserAssigned\",\"userAssignedIdentities\":{\"ujitcjedftww\":{\"principalId\":\"gkfbtndoaong\",\"clientId\":\"cn\"},\"zfoqouicybxar\":{\"principalId\":\"zkoj\",\"clientId\":\"c\"}}},\"properties\":{\"provisioningState\":\"Succeeded\",\"nginxVersion\":\"foxciq\",\"managedResourceGroup\":\"idoamciodhkha\",\"networkProfile\":{\"frontEndIPConfiguration\":{\"publicIPAddresses\":[{}],\"privateIPAddresses\":[{}]},\"networkInterfaceConfiguration\":{\"subnetId\":\"lwntoego\"}},\"ipAddress\":\"wbw\",\"enableDiagnosticsSupport\":true,\"logging\":{\"storageAccount\":{\"accountName\":\"mrv\",\"containerName\":\"ztvbtqgsfr\"}},\"scalingProperties\":{\"capacity\":2100359325,\"autoScaleSettings\":{\"profiles\":[{\"name\":\"owtlmnguxawqald\",\"capacity\":{\"min\":2048944312,\"max\":1988673385}},{\"name\":\"uximerqfobw\",\"capacity\":{\"min\":2077702872,\"max\":880028215}},{\"name\":\"kby\",\"capacity\":{\"min\":1828204425,\"max\":189482477}}]}},\"autoUpgradeProfile\":{\"upgradeChannel\":\"pfhpagmhrskdsnfd\"},\"userProfile\":{\"preferredEmail\":\"akgtdlmkkzevdlh\"}},\"sku\":{\"name\":\"pusdstt\"},\"location\":\"ogvbbejdcngq\",\"tags\":{\"wr\":\"akufgmjz\",\"u\":\"grtwae\"},\"id\":\"zkopb\",\"name\":\"inrfdwoyu\",\"type\":\"hziuiefozbhdms\"}"; + = "{\"identity\":{\"principalId\":\"cgxxlxs\",\"tenantId\":\"gcvizqzdwlvwlyou\",\"type\":\"SystemAssigned, UserAssigned\",\"userAssignedIdentities\":{\"g\":{\"principalId\":\"jub\",\"clientId\":\"hgkfmin\"},\"mmqtgqqqxhr\":{\"principalId\":\"zfttsttktlahb\",\"clientId\":\"ctxtgzukxi\"},\"azivjlfrqttbajl\":{\"principalId\":\"rxcpjuisavo\",\"clientId\":\"dzf\"},\"igovi\":{\"principalId\":\"tnwxy\",\"clientId\":\"pidkqqfkuvscxkdm\"}}},\"properties\":{\"provisioningState\":\"Succeeded\",\"nginxVersion\":\"mloazuru\",\"networkProfile\":{\"frontEndIPConfiguration\":{\"publicIPAddresses\":[{}],\"privateIPAddresses\":[{}]},\"networkInterfaceConfiguration\":{\"subnetId\":\"eoybfhjxakvvjgs\"}},\"ipAddress\":\"r\",\"enableDiagnosticsSupport\":true,\"logging\":{\"storageAccount\":{\"accountName\":\"wt\",\"containerName\":\"kxn\"}},\"scalingProperties\":{\"capacity\":2104896567,\"autoScaleSettings\":{\"profiles\":[{\"name\":\"yvudtjuewbci\",\"capacity\":{\"min\":1871891438,\"max\":535543031}},{\"name\":\"uwhcjyxccybv\",\"capacity\":{\"min\":436827826,\"max\":940165825}},{\"name\":\"akkud\",\"capacity\":{\"min\":417091375,\"max\":1773964666}}]}},\"autoUpgradeProfile\":{\"upgradeChannel\":\"wjplma\"},\"userProfile\":{\"preferredEmail\":\"cyohpfkyrkdbd\"},\"nginxAppProtect\":{\"webApplicationFirewallSettings\":{\"activationState\":\"Enabled\"},\"webApplicationFirewallStatus\":{\"attackSignaturesPackage\":{\"version\":\"kmnwqjnobaiyhddv\",\"revisionDatetime\":\"2021-06-21T06:23:06Z\"},\"botSignaturesPackage\":{\"version\":\"egfnmntfpmvmemfn\",\"revisionDatetime\":\"2021-02-26T15:37:04Z\"},\"threatCampaignsPackage\":{\"version\":\"wvvb\",\"revisionDatetime\":\"2020-12-21T10:32:32Z\"},\"componentVersions\":{\"wafEngineVersion\":\"lllchpodb\",\"wafNginxVersion\":\"evwrdnhfuk\"}}},\"dataplaneApiEndpoint\":\"sjcswsmystuluqyp\"},\"sku\":{\"name\":\"vlerchpqbmfpjba\"},\"location\":\"idfcxsspuunnoxyh\",\"tags\":{\"dao\":\"qddrihpfhoqcaae\"},\"id\":\"djvlpj\",\"name\":\"xkzb\",\"type\":\"msgeivsiykzk\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NginxManager manager = NginxManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); - NginxDeployment response - = manager.deployments() - .define("l") - .withRegion("kgjubgdknnqvsazn") - .withExistingResourceGroup("yfxrx") - .withTags(mapOf("mkycgra", "orudsgsa")) - .withIdentity( - new IdentityProperties().withType(IdentityType.USER_ASSIGNED) - .withUserAssignedIdentities(mapOf("msbvdkcrodtjinf", new UserIdentityProperties(), "pagao", - new UserIdentityProperties(), "sz", new UserIdentityProperties(), "vinvkj", - new UserIdentityProperties()))) - .withProperties(new NginxDeploymentProperties().withManagedResourceGroup("aztz") - .withNetworkProfile(new NginxNetworkProfile() - .withFrontEndIpConfiguration(new NginxFrontendIpConfiguration() - .withPublicIpAddresses(Arrays.asList(new NginxPublicIpAddress(), new NginxPublicIpAddress(), - new NginxPublicIpAddress(), new NginxPublicIpAddress())) - .withPrivateIpAddresses(Arrays.asList(new NginxPrivateIpAddress(), - new NginxPrivateIpAddress(), new NginxPrivateIpAddress(), new NginxPrivateIpAddress()))) - .withNetworkInterfaceConfiguration(new NginxNetworkInterfaceConfiguration().withSubnetId("fz"))) - .withEnableDiagnosticsSupport(false) - .withLogging(new NginxLogging().withStorageAccount( - new NginxStorageAccount().withAccountName("zfeqztppri").withContainerName("xorjaltolmncwsob"))) - .withScalingProperties(new NginxDeploymentScalingProperties().withCapacity(1713401176) - .withProfiles(Arrays.asList( - new ScaleProfile().withName("nwdcfhu") - .withCapacity(new ScaleProfileCapacity().withMin(1589501712).withMax(1491398356)), - new ScaleProfile().withName("pfuvglsbjjca") - .withCapacity(new ScaleProfileCapacity().withMin(615108235).withMax(1995846414))))) - .withAutoUpgradeProfile(new AutoUpgradeProfile().withUpgradeChannel("vtvudutncormr")) - .withUserProfile(new NginxDeploymentUserProfile().withPreferredEmail("tvcof"))) - .withSku(new ResourceSku().withName("f")) - .create(); + NginxDeployment response = manager.deployments() + .define("jjziuxxpsh") + .withRegion("icc") + .withExistingResourceGroup("v") + .withTags(mapOf("dvoqyt", "fscjfnynszquji", "hjoxo", "byowbblgyavutp")) + .withIdentity(new IdentityProperties().withType(IdentityType.SYSTEM_ASSIGNED) + .withUserAssignedIdentities(mapOf("duvwpklvxwmygd", new UserIdentityProperties()))) + .withProperties(new NginxDeploymentProperties() + .withNetworkProfile(new NginxNetworkProfile() + .withFrontEndIpConfiguration(new NginxFrontendIpConfiguration() + .withPublicIpAddresses(Arrays.asList(new NginxPublicIpAddress(), new NginxPublicIpAddress(), + new NginxPublicIpAddress(), new NginxPublicIpAddress())) + .withPrivateIpAddresses( + Arrays.asList(new NginxPrivateIpAddress(), new NginxPrivateIpAddress()))) + .withNetworkInterfaceConfiguration( + new NginxNetworkInterfaceConfiguration().withSubnetId("ibbdaxconfoza"))) + .withEnableDiagnosticsSupport(true) + .withLogging(new NginxLogging().withStorageAccount( + new NginxStorageAccount().withAccountName("pzlrphw").withContainerName("oldweyuqdu"))) + .withScalingProperties(new NginxDeploymentScalingProperties().withCapacity(375067057) + .withProfiles(Arrays.asList( + new ScaleProfile().withName("wrbiorkt") + .withCapacity(new ScaleProfileCapacity().withMin(1451955961).withMax(476504183)), + new ScaleProfile().withName("wjhhgdnhxmsivf") + .withCapacity(new ScaleProfileCapacity().withMin(2010806413).withMax(601340793))))) + .withAutoUpgradeProfile(new AutoUpgradeProfile().withUpgradeChannel("ox")) + .withUserProfile(new NginxDeploymentUserProfile().withPreferredEmail("ufiqndieuzaof")) + .withNginxAppProtect(new NginxDeploymentPropertiesNginxAppProtect().withWebApplicationFirewallSettings( + new WebApplicationFirewallSettings().withActivationState(ActivationState.ENABLED)))) + .withSku(new ResourceSku().withName("rilbywdx")) + .create(); - Assertions.assertEquals("ogvbbejdcngq", response.location()); - Assertions.assertEquals("akufgmjz", response.tags().get("wr")); - Assertions.assertEquals(IdentityType.USER_ASSIGNED, response.identity().type()); - Assertions.assertEquals("idoamciodhkha", response.properties().managedResourceGroup()); - Assertions.assertEquals("lwntoego", + Assertions.assertEquals("idfcxsspuunnoxyh", response.location()); + Assertions.assertEquals("qddrihpfhoqcaae", response.tags().get("dao")); + Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, response.identity().type()); + Assertions.assertEquals("eoybfhjxakvvjgs", response.properties().networkProfile().networkInterfaceConfiguration().subnetId()); Assertions.assertEquals(true, response.properties().enableDiagnosticsSupport()); - Assertions.assertEquals("mrv", response.properties().logging().storageAccount().accountName()); - Assertions.assertEquals("ztvbtqgsfr", response.properties().logging().storageAccount().containerName()); - Assertions.assertEquals(2100359325, response.properties().scalingProperties().capacity()); - Assertions.assertEquals("owtlmnguxawqald", response.properties().scalingProperties().profiles().get(0).name()); - Assertions.assertEquals(2048944312, + Assertions.assertEquals("wt", response.properties().logging().storageAccount().accountName()); + Assertions.assertEquals("kxn", response.properties().logging().storageAccount().containerName()); + Assertions.assertEquals(2104896567, response.properties().scalingProperties().capacity()); + Assertions.assertEquals("yvudtjuewbci", response.properties().scalingProperties().profiles().get(0).name()); + Assertions.assertEquals(1871891438, response.properties().scalingProperties().profiles().get(0).capacity().min()); - Assertions.assertEquals(1988673385, + Assertions.assertEquals(535543031, response.properties().scalingProperties().profiles().get(0).capacity().max()); - Assertions.assertEquals("pfhpagmhrskdsnfd", response.properties().autoUpgradeProfile().upgradeChannel()); - Assertions.assertEquals("akgtdlmkkzevdlh", response.properties().userProfile().preferredEmail()); - Assertions.assertEquals("pusdstt", response.sku().name()); + Assertions.assertEquals("wjplma", response.properties().autoUpgradeProfile().upgradeChannel()); + Assertions.assertEquals("cyohpfkyrkdbd", response.properties().userProfile().preferredEmail()); + Assertions.assertEquals(ActivationState.ENABLED, + response.properties().nginxAppProtect().webApplicationFirewallSettings().activationState()); + Assertions.assertEquals("vlerchpqbmfpjba", response.sku().name()); } // Use "Map.of" if available diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/DeploymentsDeleteMockTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/DeploymentsDeleteMockTests.java index a5ea7a6467f2..3096d6d603f8 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/DeploymentsDeleteMockTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/DeploymentsDeleteMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.nginx.NginxManager; import java.nio.charset.StandardCharsets; @@ -25,9 +25,9 @@ public void testDelete() throws Exception { NginxManager manager = NginxManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); - manager.deployments().delete("e", "iipfpubj", com.azure.core.util.Context.NONE); + manager.deployments().delete("h", "rghxjb", com.azure.core.util.Context.NONE); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/DeploymentsGetByResourceGroupWithResponseMockTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/DeploymentsGetByResourceGroupWithResponseMockTests.java index b6305dadbbf3..4bcc1d93834b 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/DeploymentsGetByResourceGroupWithResponseMockTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/DeploymentsGetByResourceGroupWithResponseMockTests.java @@ -6,10 +6,11 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.nginx.NginxManager; +import com.azure.resourcemanager.nginx.models.ActivationState; import com.azure.resourcemanager.nginx.models.IdentityType; import com.azure.resourcemanager.nginx.models.NginxDeployment; import java.nio.charset.StandardCharsets; @@ -22,36 +23,37 @@ public final class DeploymentsGetByResourceGroupWithResponseMockTests { @Test public void testGetByResourceGroupWithResponse() throws Exception { String responseStr - = "{\"identity\":{\"principalId\":\"bexkpzksmondj\",\"tenantId\":\"uxvypomgkopkwh\",\"type\":\"SystemAssigned\",\"userAssignedIdentities\":{\"vhelxprglyatdd\":{\"principalId\":\"qgxy\",\"clientId\":\"ocmbqfqvmkcxoza\"},\"sdqrhzoymibmrq\":{\"principalId\":\"cbcuejrjxgciqi\",\"clientId\":\"hos\"}}},\"properties\":{\"provisioningState\":\"Failed\",\"nginxVersion\":\"wfluszdt\",\"managedResourceGroup\":\"rkwofyyvoqa\",\"networkProfile\":{\"frontEndIPConfiguration\":{\"publicIPAddresses\":[{},{},{}],\"privateIPAddresses\":[{},{},{},{}]},\"networkInterfaceConfiguration\":{\"subnetId\":\"iwbwoenwashrtdtk\"}},\"ipAddress\":\"qxwbpokulpiu\",\"enableDiagnosticsSupport\":false,\"logging\":{\"storageAccount\":{\"accountName\":\"pqiiobyuqe\",\"containerName\":\"qlpqwcciuq\"}},\"scalingProperties\":{\"capacity\":1924773766,\"autoScaleSettings\":{\"profiles\":[{\"name\":\"auvfbtkuwhhmhyk\",\"capacity\":{\"min\":697722485,\"max\":1183832331}}]}},\"autoUpgradeProfile\":{\"upgradeChannel\":\"afnn\"},\"userProfile\":{\"preferredEmail\":\"ichkoymkcdyhb\"}},\"sku\":{\"name\":\"kpw\"},\"location\":\"eqnovvqfovl\",\"tags\":{\"ndsytgadg\":\"wsuwsyr\",\"ea\":\"r\"},\"id\":\"neqn\",\"name\":\"arrwlquu\",\"type\":\"jfqka\"}"; + = "{\"identity\":{\"principalId\":\"tsgumhj\",\"tenantId\":\"ikkx\",\"type\":\"SystemAssigned\",\"userAssignedIdentities\":{\"njwmwkpnbsazejj\":{\"principalId\":\"qpvuzlmvfelf\",\"clientId\":\"gplcrpwjxeznoigb\"},\"mkqjj\":{\"principalId\":\"kagfhsxtt\",\"clientId\":\"gzxnfaazpxdtnk\"},\"ixqtn\":{\"principalId\":\"uenvrkp\",\"clientId\":\"uaibrebqaaysj\"},\"mjihyeozphv\":{\"principalId\":\"tezlwff\",\"clientId\":\"akpjpqqmtedlt\"}}},\"properties\":{\"provisioningState\":\"Deleting\",\"nginxVersion\":\"ncyg\",\"networkProfile\":{\"frontEndIPConfiguration\":{\"publicIPAddresses\":[{},{}],\"privateIPAddresses\":[{},{},{}]},\"networkInterfaceConfiguration\":{\"subnetId\":\"cwxqu\"}},\"ipAddress\":\"vzhfstotxhoj\",\"enableDiagnosticsSupport\":false,\"logging\":{\"storageAccount\":{\"accountName\":\"lmcuvhixb\",\"containerName\":\"yfwnylr\"}},\"scalingProperties\":{\"capacity\":1448571025,\"autoScaleSettings\":{\"profiles\":[{\"name\":\"tpkiwkkbnujry\",\"capacity\":{\"min\":429689436,\"max\":1368964811}},{\"name\":\"y\",\"capacity\":{\"min\":151793614,\"max\":2136343303}},{\"name\":\"pncur\",\"capacity\":{\"min\":1036989495,\"max\":913086384}},{\"name\":\"wiithtywub\",\"capacity\":{\"min\":1797172930,\"max\":709721668}}]}},\"autoUpgradeProfile\":{\"upgradeChannel\":\"h\"},\"userProfile\":{\"preferredEmail\":\"nfdn\"},\"nginxAppProtect\":{\"webApplicationFirewallSettings\":{\"activationState\":\"Disabled\"},\"webApplicationFirewallStatus\":{\"attackSignaturesPackage\":{\"version\":\"dgoihxumwctondzj\",\"revisionDatetime\":\"2021-05-20T02:25:29Z\"},\"botSignaturesPackage\":{\"version\":\"dfdlwggyts\",\"revisionDatetime\":\"2020-12-29T04:47:45Z\"},\"threatCampaignsPackage\":{\"version\":\"ovvtgseinqfiu\",\"revisionDatetime\":\"2021-02-21T15:59:19Z\"},\"componentVersions\":{\"wafEngineVersion\":\"knpirgnepttwq\",\"wafNginxVersion\":\"sniffc\"}}},\"dataplaneApiEndpoint\":\"qnrojlpijnkrxfrd\"},\"sku\":{\"name\":\"c\"},\"location\":\"tizzronasxif\",\"tags\":{\"wesgogczh\":\"qyzhf\"},\"id\":\"nnxk\",\"name\":\"lgnyhmo\",\"type\":\"sxkkg\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NginxManager manager = NginxManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); NginxDeployment response = manager.deployments() - .getByResourceGroupWithResponse("yhrfouyftaakcpw", "yzvqt", com.azure.core.util.Context.NONE) + .getByResourceGroupWithResponse("gfipnsxk", "cwaekrrjre", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("eqnovvqfovl", response.location()); - Assertions.assertEquals("wsuwsyr", response.tags().get("ndsytgadg")); + Assertions.assertEquals("tizzronasxif", response.location()); + Assertions.assertEquals("qyzhf", response.tags().get("wesgogczh")); Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, response.identity().type()); - Assertions.assertEquals("rkwofyyvoqa", response.properties().managedResourceGroup()); - Assertions.assertEquals("iwbwoenwashrtdtk", + Assertions.assertEquals("cwxqu", response.properties().networkProfile().networkInterfaceConfiguration().subnetId()); Assertions.assertEquals(false, response.properties().enableDiagnosticsSupport()); - Assertions.assertEquals("pqiiobyuqe", response.properties().logging().storageAccount().accountName()); - Assertions.assertEquals("qlpqwcciuq", response.properties().logging().storageAccount().containerName()); - Assertions.assertEquals(1924773766, response.properties().scalingProperties().capacity()); - Assertions.assertEquals("auvfbtkuwhhmhyk", response.properties().scalingProperties().profiles().get(0).name()); - Assertions.assertEquals(697722485, + Assertions.assertEquals("lmcuvhixb", response.properties().logging().storageAccount().accountName()); + Assertions.assertEquals("yfwnylr", response.properties().logging().storageAccount().containerName()); + Assertions.assertEquals(1448571025, response.properties().scalingProperties().capacity()); + Assertions.assertEquals("tpkiwkkbnujry", response.properties().scalingProperties().profiles().get(0).name()); + Assertions.assertEquals(429689436, response.properties().scalingProperties().profiles().get(0).capacity().min()); - Assertions.assertEquals(1183832331, + Assertions.assertEquals(1368964811, response.properties().scalingProperties().profiles().get(0).capacity().max()); - Assertions.assertEquals("afnn", response.properties().autoUpgradeProfile().upgradeChannel()); - Assertions.assertEquals("ichkoymkcdyhb", response.properties().userProfile().preferredEmail()); - Assertions.assertEquals("kpw", response.sku().name()); + Assertions.assertEquals("h", response.properties().autoUpgradeProfile().upgradeChannel()); + Assertions.assertEquals("nfdn", response.properties().userProfile().preferredEmail()); + Assertions.assertEquals(ActivationState.DISABLED, + response.properties().nginxAppProtect().webApplicationFirewallSettings().activationState()); + Assertions.assertEquals("c", response.sku().name()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/DeploymentsListByResourceGroupMockTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/DeploymentsListByResourceGroupMockTests.java index 177a231f93dd..40ff98c4d8e2 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/DeploymentsListByResourceGroupMockTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/DeploymentsListByResourceGroupMockTests.java @@ -7,10 +7,11 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.nginx.NginxManager; +import com.azure.resourcemanager.nginx.models.ActivationState; import com.azure.resourcemanager.nginx.models.IdentityType; import com.azure.resourcemanager.nginx.models.NginxDeployment; import java.nio.charset.StandardCharsets; @@ -23,39 +24,45 @@ public final class DeploymentsListByResourceGroupMockTests { @Test public void testListByResourceGroup() throws Exception { String responseStr - = "{\"value\":[{\"identity\":{\"principalId\":\"tkl\",\"tenantId\":\"xbjhwuaanozjosph\",\"type\":\"UserAssigned\",\"userAssignedIdentities\":{\"kfcktqum\":{\"principalId\":\"rvxaglrvimjwosy\",\"clientId\":\"itc\"},\"eqidbqfatpx\":{\"principalId\":\"kkezzikhlyfjhdgq\",\"clientId\":\"ebdunyg\"}}},\"properties\":{\"provisioningState\":\"Succeeded\",\"nginxVersion\":\"yjmoadsu\",\"managedResourceGroup\":\"r\",\"networkProfile\":{\"frontEndIPConfiguration\":{\"publicIPAddresses\":[{},{}],\"privateIPAddresses\":[{},{},{}]},\"networkInterfaceConfiguration\":{\"subnetId\":\"bjhhyx\"}},\"ipAddress\":\"wlycoduhpkxkg\",\"enableDiagnosticsSupport\":false,\"logging\":{\"storageAccount\":{\"accountName\":\"n\",\"containerName\":\"xqugjhkycubedd\"}},\"scalingProperties\":{\"capacity\":947899145,\"autoScaleSettings\":{\"profiles\":[{\"name\":\"qmzqalkrmnjijpx\",\"capacity\":{\"min\":1400063393,\"max\":222517676}}]}},\"autoUpgradeProfile\":{\"upgradeChannel\":\"udfnbyxba\"},\"userProfile\":{\"preferredEmail\":\"jyvayffimrzrtuz\"}},\"sku\":{\"name\":\"gsexne\"},\"location\":\"dnw\",\"tags\":{\"ud\":\"ewzsyyceuzsoib\",\"brqubp\":\"frxtrthzvaytdwk\"},\"id\":\"xhexiilivpdti\",\"name\":\"r\",\"type\":\"tdqoaxoruzfgsq\"}]}"; + = "{\"value\":[{\"identity\":{\"principalId\":\"iklbydvkhb\",\"tenantId\":\"dznx\",\"type\":\"UserAssigned\",\"userAssignedIdentities\":{\"eamtmcz\":{\"principalId\":\"njivolvtnovq\",\"clientId\":\"gemjdftuljltdu\"}}},\"properties\":{\"provisioningState\":\"Failed\",\"nginxVersion\":\"wcw\",\"networkProfile\":{\"frontEndIPConfiguration\":{\"publicIPAddresses\":[{},{},{}],\"privateIPAddresses\":[{},{}]},\"networkInterfaceConfiguration\":{\"subnetId\":\"mojmsvpkjprvkw\"}},\"ipAddress\":\"zqljyxgtczh\",\"enableDiagnosticsSupport\":false,\"logging\":{\"storageAccount\":{\"accountName\":\"shmkxmaehvbbxur\",\"containerName\":\"ltfnhtbaxkgx\"}},\"scalingProperties\":{\"capacity\":674255307,\"autoScaleSettings\":{\"profiles\":[{\"name\":\"yklyhpluodpvruud\",\"capacity\":{\"min\":1795826446,\"max\":1016035136}},{\"name\":\"ibthostgktstvd\",\"capacity\":{\"min\":1128262143,\"max\":318971885}},{\"name\":\"lzedqbcvhzlhplo\",\"capacity\":{\"min\":1080296367,\"max\":695028965}},{\"name\":\"dlwwqfbumlkxt\",\"capacity\":{\"min\":983643035,\"max\":2123873865}}]}},\"autoUpgradeProfile\":{\"upgradeChannel\":\"smlmbtxhwgfwsrta\"},\"userProfile\":{\"preferredEmail\":\"ezbrhubskh\"},\"nginxAppProtect\":{\"webApplicationFirewallSettings\":{\"activationState\":\"Enabled\"},\"webApplicationFirewallStatus\":{\"attackSignaturesPackage\":{\"version\":\"okkqfqjbvleo\",\"revisionDatetime\":\"2020-12-31T22:39:11Z\"},\"botSignaturesPackage\":{\"version\":\"luiqtqzfavyvnqq\",\"revisionDatetime\":\"2021-05-23T06:21:06Z\"},\"threatCampaignsPackage\":{\"version\":\"ryeu\",\"revisionDatetime\":\"2021-02-15T18:43:44Z\"},\"componentVersions\":{\"wafEngineVersion\":\"kq\",\"wafNginxVersion\":\"bqgzslesjcbhern\"}}},\"dataplaneApiEndpoint\":\"iew\"},\"sku\":{\"name\":\"cv\"},\"location\":\"uwrbehwagoh\",\"tags\":{\"emvvhm\":\"fkmr\"},\"id\":\"tdrjfutacoebj\",\"name\":\"ewzcjznmwcp\",\"type\":\"guaadraufactkahz\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NginxManager manager = NginxManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response - = manager.deployments().listByResourceGroup("elpcirelsfeaenwa", com.azure.core.util.Context.NONE); + = manager.deployments().listByResourceGroup("wrykqgai", com.azure.core.util.Context.NONE); - Assertions.assertEquals("dnw", response.iterator().next().location()); - Assertions.assertEquals("ewzsyyceuzsoib", response.iterator().next().tags().get("ud")); + Assertions.assertEquals("uwrbehwagoh", response.iterator().next().location()); + Assertions.assertEquals("fkmr", response.iterator().next().tags().get("emvvhm")); Assertions.assertEquals(IdentityType.USER_ASSIGNED, response.iterator().next().identity().type()); - Assertions.assertEquals("r", response.iterator().next().properties().managedResourceGroup()); - Assertions.assertEquals("bjhhyx", + Assertions.assertEquals("mojmsvpkjprvkw", response.iterator().next().properties().networkProfile().networkInterfaceConfiguration().subnetId()); Assertions.assertEquals(false, response.iterator().next().properties().enableDiagnosticsSupport()); - Assertions.assertEquals("n", response.iterator().next().properties().logging().storageAccount().accountName()); - Assertions.assertEquals("xqugjhkycubedd", + Assertions.assertEquals("shmkxmaehvbbxur", + response.iterator().next().properties().logging().storageAccount().accountName()); + Assertions.assertEquals("ltfnhtbaxkgx", response.iterator().next().properties().logging().storageAccount().containerName()); - Assertions.assertEquals(947899145, response.iterator().next().properties().scalingProperties().capacity()); - Assertions.assertEquals("qmzqalkrmnjijpx", + Assertions.assertEquals(674255307, response.iterator().next().properties().scalingProperties().capacity()); + Assertions.assertEquals("yklyhpluodpvruud", response.iterator().next().properties().scalingProperties().profiles().get(0).name()); - Assertions.assertEquals(1400063393, + Assertions.assertEquals(1795826446, response.iterator().next().properties().scalingProperties().profiles().get(0).capacity().min()); - Assertions.assertEquals(222517676, + Assertions.assertEquals(1016035136, response.iterator().next().properties().scalingProperties().profiles().get(0).capacity().max()); - Assertions.assertEquals("udfnbyxba", + Assertions.assertEquals("smlmbtxhwgfwsrta", response.iterator().next().properties().autoUpgradeProfile().upgradeChannel()); - Assertions.assertEquals("jyvayffimrzrtuz", - response.iterator().next().properties().userProfile().preferredEmail()); - Assertions.assertEquals("gsexne", response.iterator().next().sku().name()); + Assertions.assertEquals("ezbrhubskh", response.iterator().next().properties().userProfile().preferredEmail()); + Assertions.assertEquals(ActivationState.ENABLED, + response.iterator() + .next() + .properties() + .nginxAppProtect() + .webApplicationFirewallSettings() + .activationState()); + Assertions.assertEquals("cv", response.iterator().next().sku().name()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/DeploymentsListMockTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/DeploymentsListMockTests.java index 41f347b02f04..c2b865b57f20 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/DeploymentsListMockTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/DeploymentsListMockTests.java @@ -7,10 +7,11 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.nginx.NginxManager; +import com.azure.resourcemanager.nginx.models.ActivationState; import com.azure.resourcemanager.nginx.models.IdentityType; import com.azure.resourcemanager.nginx.models.NginxDeployment; import java.nio.charset.StandardCharsets; @@ -23,38 +24,43 @@ public final class DeploymentsListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"identity\":{\"principalId\":\"wifto\",\"tenantId\":\"kvpuvksgplsaknyn\",\"type\":\"SystemAssigned\",\"userAssignedIdentities\":{\"eosjswsr\":{\"principalId\":\"ph\",\"clientId\":\"pxodlqiyntorzih\"},\"zynkedya\":{\"principalId\":\"lyzrpzbchckqqzqi\",\"clientId\":\"iysui\"},\"pcdpumnz\":{\"principalId\":\"wyhqmibzyhwits\",\"clientId\":\"pyy\"}}},\"properties\":{\"provisioningState\":\"Deleting\",\"nginxVersion\":\"mabiknsorgjhxb\",\"managedResourceGroup\":\"tlwwrlk\",\"networkProfile\":{\"frontEndIPConfiguration\":{\"publicIPAddresses\":[{},{},{},{}],\"privateIPAddresses\":[{}]},\"networkInterfaceConfiguration\":{\"subnetId\":\"tllxdyhgsyocogj\"}},\"ipAddress\":\"dtbnnha\",\"enableDiagnosticsSupport\":true,\"logging\":{\"storageAccount\":{\"accountName\":\"vcikhnvpamqgx\",\"containerName\":\"u\"}},\"scalingProperties\":{\"capacity\":1817330156,\"autoScaleSettings\":{\"profiles\":[{\"name\":\"ggxkallatmelwuip\",\"capacity\":{\"min\":555730544,\"max\":1103817240}},{\"name\":\"jzkzi\",\"capacity\":{\"min\":766917495,\"max\":1783583685}},{\"name\":\"vc\",\"capacity\":{\"min\":2028866606,\"max\":192957128}}]}},\"autoUpgradeProfile\":{\"upgradeChannel\":\"hyrnxxmu\"},\"userProfile\":{\"preferredEmail\":\"ndrdvstkwq\"}},\"sku\":{\"name\":\"chea\"},\"location\":\"fmtdaaygdvwvgp\",\"tags\":{\"xrtfudxep\":\"g\",\"himdbl\":\"gyqagvrvmnpkuk\",\"hfjx\":\"gwimfn\"},\"id\":\"mszkkfo\",\"name\":\"rey\",\"type\":\"kzikfjawneaivxwc\"}]}"; + = "{\"value\":[{\"identity\":{\"principalId\":\"xvcxgfrpdsofbshr\",\"tenantId\":\"vbuswd\",\"type\":\"UserAssigned\",\"userAssignedIdentities\":{\"wnopqgikyzirtx\":{\"principalId\":\"cnunvjsr\",\"clientId\":\"f\"},\"qukrydxt\":{\"principalId\":\"uxzejntpsew\",\"clientId\":\"oi\"},\"pjbi\":{\"principalId\":\"ieoxorggufhyaomt\",\"clientId\":\"hhavgrvkffovjz\"},\"nbkfezzxscy\":{\"principalId\":\"jmfxumvf\",\"clientId\":\"uyovw\"}}},\"properties\":{\"provisioningState\":\"Deleting\",\"nginxVersion\":\"irujbz\",\"networkProfile\":{\"frontEndIPConfiguration\":{\"publicIPAddresses\":[{},{},{},{}],\"privateIPAddresses\":[{},{},{},{}]},\"networkInterfaceConfiguration\":{\"subnetId\":\"c\"}},\"ipAddress\":\"pniyujviyl\",\"enableDiagnosticsSupport\":true,\"logging\":{\"storageAccount\":{\"accountName\":\"snrbgyefrymsgao\",\"containerName\":\"mwn\"}},\"scalingProperties\":{\"capacity\":1012441055,\"autoScaleSettings\":{\"profiles\":[{\"name\":\"hirctymoxoftpipi\",\"capacity\":{\"min\":420468172,\"max\":1383298252}}]}},\"autoUpgradeProfile\":{\"upgradeChannel\":\"uh\"},\"userProfile\":{\"preferredEmail\":\"pqjlihhyusps\"},\"nginxAppProtect\":{\"webApplicationFirewallSettings\":{\"activationState\":\"Disabled\"},\"webApplicationFirewallStatus\":{\"attackSignaturesPackage\":{\"version\":\"mfwdgzxu\",\"revisionDatetime\":\"2021-04-20T13:27:45Z\"},\"botSignaturesPackage\":{\"version\":\"vpa\",\"revisionDatetime\":\"2021-12-09T14:22:52Z\"},\"threatCampaignsPackage\":{\"version\":\"reuzvxurisjn\",\"revisionDatetime\":\"2021-02-10T22:06:59Z\"},\"componentVersions\":{\"wafEngineVersion\":\"txifqj\",\"wafNginxVersion\":\"gxmrhublwp\"}}},\"dataplaneApiEndpoint\":\"sutrgjup\"},\"sku\":{\"name\":\"utpwoqhihejqgw\"},\"location\":\"nfqn\",\"tags\":{\"imwkslircizj\":\"psxjvf\",\"t\":\"vydfceacvlhvygdy\",\"jslb\":\"mrtwna\"},\"id\":\"wkojgcyztsfmzn\",\"name\":\"aeqphchqnr\",\"type\":\"rpxeh\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NginxManager manager = NginxManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.deployments().list(com.azure.core.util.Context.NONE); - Assertions.assertEquals("fmtdaaygdvwvgp", response.iterator().next().location()); - Assertions.assertEquals("g", response.iterator().next().tags().get("xrtfudxep")); - Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, response.iterator().next().identity().type()); - Assertions.assertEquals("tlwwrlk", response.iterator().next().properties().managedResourceGroup()); - Assertions.assertEquals("tllxdyhgsyocogj", + Assertions.assertEquals("nfqn", response.iterator().next().location()); + Assertions.assertEquals("psxjvf", response.iterator().next().tags().get("imwkslircizj")); + Assertions.assertEquals(IdentityType.USER_ASSIGNED, response.iterator().next().identity().type()); + Assertions.assertEquals("c", response.iterator().next().properties().networkProfile().networkInterfaceConfiguration().subnetId()); Assertions.assertEquals(true, response.iterator().next().properties().enableDiagnosticsSupport()); - Assertions.assertEquals("vcikhnvpamqgx", + Assertions.assertEquals("snrbgyefrymsgao", response.iterator().next().properties().logging().storageAccount().accountName()); - Assertions.assertEquals("u", + Assertions.assertEquals("mwn", response.iterator().next().properties().logging().storageAccount().containerName()); - Assertions.assertEquals(1817330156, response.iterator().next().properties().scalingProperties().capacity()); - Assertions.assertEquals("ggxkallatmelwuip", + Assertions.assertEquals(1012441055, response.iterator().next().properties().scalingProperties().capacity()); + Assertions.assertEquals("hirctymoxoftpipi", response.iterator().next().properties().scalingProperties().profiles().get(0).name()); - Assertions.assertEquals(555730544, + Assertions.assertEquals(420468172, response.iterator().next().properties().scalingProperties().profiles().get(0).capacity().min()); - Assertions.assertEquals(1103817240, + Assertions.assertEquals(1383298252, response.iterator().next().properties().scalingProperties().profiles().get(0).capacity().max()); - Assertions.assertEquals("hyrnxxmu", - response.iterator().next().properties().autoUpgradeProfile().upgradeChannel()); - Assertions.assertEquals("ndrdvstkwq", response.iterator().next().properties().userProfile().preferredEmail()); - Assertions.assertEquals("chea", response.iterator().next().sku().name()); + Assertions.assertEquals("uh", response.iterator().next().properties().autoUpgradeProfile().upgradeChannel()); + Assertions.assertEquals("pqjlihhyusps", response.iterator().next().properties().userProfile().preferredEmail()); + Assertions.assertEquals(ActivationState.DISABLED, + response.iterator() + .next() + .properties() + .nginxAppProtect() + .webApplicationFirewallSettings() + .activationState()); + Assertions.assertEquals("utpwoqhihejqgw", response.iterator().next().sku().name()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/DiagnosticItemTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/DiagnosticItemTests.java new file mode 100644 index 000000000000..55b42b2a7405 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/DiagnosticItemTests.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.nginx.models.DiagnosticItem; +import com.azure.resourcemanager.nginx.models.Level; +import org.junit.jupiter.api.Assertions; + +public final class DiagnosticItemTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + DiagnosticItem model = BinaryData.fromString( + "{\"id\":\"iwwzjuqk\",\"directive\":\"rsa\",\"description\":\"iwkuofos\",\"file\":\"ghsauuimjmvxied\",\"line\":44.474648,\"message\":\"gidyjrrf\",\"rule\":\"y\",\"level\":\"Warning\",\"category\":\"v\"}") + .toObject(DiagnosticItem.class); + Assertions.assertEquals("iwwzjuqk", model.id()); + Assertions.assertEquals("rsa", model.directive()); + Assertions.assertEquals("iwkuofos", model.description()); + Assertions.assertEquals("ghsauuimjmvxied", model.file()); + Assertions.assertEquals(44.474648f, model.line()); + Assertions.assertEquals("gidyjrrf", model.message()); + Assertions.assertEquals("y", model.rule()); + Assertions.assertEquals(Level.WARNING, model.level()); + Assertions.assertEquals("v", model.category()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + DiagnosticItem model = new DiagnosticItem().withId("iwwzjuqk") + .withDirective("rsa") + .withDescription("iwkuofos") + .withFile("ghsauuimjmvxied") + .withLine(44.474648f) + .withMessage("gidyjrrf") + .withRule("y") + .withLevel(Level.WARNING) + .withCategory("v"); + model = BinaryData.fromObject(model).toObject(DiagnosticItem.class); + Assertions.assertEquals("iwwzjuqk", model.id()); + Assertions.assertEquals("rsa", model.directive()); + Assertions.assertEquals("iwkuofos", model.description()); + Assertions.assertEquals("ghsauuimjmvxied", model.file()); + Assertions.assertEquals(44.474648f, model.line()); + Assertions.assertEquals("gidyjrrf", model.message()); + Assertions.assertEquals("y", model.rule()); + Assertions.assertEquals(Level.WARNING, model.level()); + Assertions.assertEquals("v", model.category()); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/IdentityPropertiesTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/IdentityPropertiesTests.java index b3a3c0b38f8a..d47ccaccdda7 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/IdentityPropertiesTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/IdentityPropertiesTests.java @@ -16,7 +16,7 @@ public final class IdentityPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { IdentityProperties model = BinaryData.fromString( - "{\"principalId\":\"k\",\"tenantId\":\"xo\",\"type\":\"None\",\"userAssignedIdentities\":{\"whijcoejctbza\":{\"principalId\":\"pimexgstxgcpodg\",\"clientId\":\"ajrmvdjwzrlovmc\"},\"xaxcfjpgddtocjjx\":{\"principalId\":\"qsycbkbfkgu\",\"clientId\":\"kexxppof\"},\"jnxqbzvddntwn\":{\"principalId\":\"pmouexhdz\",\"clientId\":\"bqe\"}}}") + "{\"principalId\":\"cxgod\",\"tenantId\":\"fqkkr\",\"type\":\"None\",\"userAssignedIdentities\":{\"cispnqzahmgkbr\":{\"principalId\":\"riwflzlfb\",\"clientId\":\"puz\"},\"drgvtqagn\":{\"principalId\":\"y\",\"clientId\":\"ibnuqqkpik\"},\"zzmhjrunmpxttd\":{\"principalId\":\"ynhijggme\",\"clientId\":\"siarbutrcvpn\"}}}") .toObject(IdentityProperties.class); Assertions.assertEquals(IdentityType.NONE, model.type()); } @@ -24,8 +24,8 @@ public void testDeserialize() throws Exception { @org.junit.jupiter.api.Test public void testSerialize() throws Exception { IdentityProperties model = new IdentityProperties().withType(IdentityType.NONE) - .withUserAssignedIdentities(mapOf("whijcoejctbza", new UserIdentityProperties(), "xaxcfjpgddtocjjx", - new UserIdentityProperties(), "jnxqbzvddntwn", new UserIdentityProperties())); + .withUserAssignedIdentities(mapOf("cispnqzahmgkbr", new UserIdentityProperties(), "drgvtqagn", + new UserIdentityProperties(), "zzmhjrunmpxttd", new UserIdentityProperties())); model = BinaryData.fromObject(model).toObject(IdentityProperties.class); Assertions.assertEquals(IdentityType.NONE, model.type()); } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationFileTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationFileTests.java index c9a296152dad..20541cd8af59 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationFileTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationFileTests.java @@ -12,18 +12,18 @@ public final class NginxConfigurationFileTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { NginxConfigurationFile model - = BinaryData.fromString("{\"content\":\"fdosyg\",\"virtualPath\":\"paojakhmsbzjh\"}") + = BinaryData.fromString("{\"content\":\"fygxgispemvtzfk\",\"virtualPath\":\"ubljofxqe\"}") .toObject(NginxConfigurationFile.class); - Assertions.assertEquals("fdosyg", model.content()); - Assertions.assertEquals("paojakhmsbzjh", model.virtualPath()); + Assertions.assertEquals("fygxgispemvtzfk", model.content()); + Assertions.assertEquals("ubljofxqe", model.virtualPath()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { NginxConfigurationFile model - = new NginxConfigurationFile().withContent("fdosyg").withVirtualPath("paojakhmsbzjh"); + = new NginxConfigurationFile().withContent("fygxgispemvtzfk").withVirtualPath("ubljofxqe"); model = BinaryData.fromObject(model).toObject(NginxConfigurationFile.class); - Assertions.assertEquals("fdosyg", model.content()); - Assertions.assertEquals("paojakhmsbzjh", model.virtualPath()); + Assertions.assertEquals("fygxgispemvtzfk", model.content()); + Assertions.assertEquals("ubljofxqe", model.virtualPath()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationInnerTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationInnerTests.java deleted file mode 100644 index 7098d709ac23..000000000000 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationInnerTests.java +++ /dev/null @@ -1,52 +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.resourcemanager.nginx.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.nginx.fluent.models.NginxConfigurationInner; -import com.azure.resourcemanager.nginx.models.NginxConfigurationFile; -import com.azure.resourcemanager.nginx.models.NginxConfigurationPackage; -import com.azure.resourcemanager.nginx.models.NginxConfigurationProperties; -import java.util.Arrays; -import org.junit.jupiter.api.Assertions; - -public final class NginxConfigurationInnerTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - NginxConfigurationInner model = BinaryData.fromString( - "{\"properties\":{\"provisioningState\":\"Failed\",\"files\":[{\"content\":\"fp\",\"virtualPath\":\"qobmtukk\"},{\"content\":\"yrtih\",\"virtualPath\":\"tijbpzvgnwzsymgl\"},{\"content\":\"fcyzkohdbihanufh\",\"virtualPath\":\"bj\"}],\"protectedFiles\":[{\"content\":\"ithxqhabifpi\",\"virtualPath\":\"wczbys\"}],\"package\":{\"data\":\"q\",\"protectedFiles\":[\"ivyqniwbybrkxvd\"]},\"rootFile\":\"jgrtfwvukxga\"},\"location\":\"ccsnhsjc\",\"id\":\"ejhkry\",\"name\":\"tnapczwlokjyemkk\",\"type\":\"ni\"}") - .toObject(NginxConfigurationInner.class); - Assertions.assertEquals("fp", model.properties().files().get(0).content()); - Assertions.assertEquals("qobmtukk", model.properties().files().get(0).virtualPath()); - Assertions.assertEquals("ithxqhabifpi", model.properties().protectedFiles().get(0).content()); - Assertions.assertEquals("wczbys", model.properties().protectedFiles().get(0).virtualPath()); - Assertions.assertEquals("q", model.properties().packageProperty().data()); - Assertions.assertEquals("ivyqniwbybrkxvd", model.properties().packageProperty().protectedFiles().get(0)); - Assertions.assertEquals("jgrtfwvukxga", model.properties().rootFile()); - Assertions.assertEquals("ccsnhsjc", model.location()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - NginxConfigurationInner model = new NginxConfigurationInner().withProperties(new NginxConfigurationProperties() - .withFiles(Arrays.asList(new NginxConfigurationFile().withContent("fp").withVirtualPath("qobmtukk"), - new NginxConfigurationFile().withContent("yrtih").withVirtualPath("tijbpzvgnwzsymgl"), - new NginxConfigurationFile().withContent("fcyzkohdbihanufh").withVirtualPath("bj"))) - .withProtectedFiles( - Arrays.asList(new NginxConfigurationFile().withContent("ithxqhabifpi").withVirtualPath("wczbys"))) - .withPackageProperty( - new NginxConfigurationPackage().withData("q").withProtectedFiles(Arrays.asList("ivyqniwbybrkxvd"))) - .withRootFile("jgrtfwvukxga")).withLocation("ccsnhsjc"); - model = BinaryData.fromObject(model).toObject(NginxConfigurationInner.class); - Assertions.assertEquals("fp", model.properties().files().get(0).content()); - Assertions.assertEquals("qobmtukk", model.properties().files().get(0).virtualPath()); - Assertions.assertEquals("ithxqhabifpi", model.properties().protectedFiles().get(0).content()); - Assertions.assertEquals("wczbys", model.properties().protectedFiles().get(0).virtualPath()); - Assertions.assertEquals("q", model.properties().packageProperty().data()); - Assertions.assertEquals("ivyqniwbybrkxvd", model.properties().packageProperty().protectedFiles().get(0)); - Assertions.assertEquals("jgrtfwvukxga", model.properties().rootFile()); - Assertions.assertEquals("ccsnhsjc", model.location()); - } -} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationListResponseTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationListResponseTests.java index 49ee1a677106..2cd17672a8a2 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationListResponseTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationListResponseTests.java @@ -5,11 +5,12 @@ package com.azure.resourcemanager.nginx.generated; import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.nginx.fluent.models.NginxConfigurationInner; +import com.azure.resourcemanager.nginx.fluent.models.NginxConfigurationResponseInner; import com.azure.resourcemanager.nginx.models.NginxConfigurationFile; import com.azure.resourcemanager.nginx.models.NginxConfigurationListResponse; import com.azure.resourcemanager.nginx.models.NginxConfigurationPackage; -import com.azure.resourcemanager.nginx.models.NginxConfigurationProperties; +import com.azure.resourcemanager.nginx.models.NginxConfigurationProtectedFileResponse; +import com.azure.resourcemanager.nginx.models.NginxConfigurationResponseProperties; import java.util.Arrays; import org.junit.jupiter.api.Assertions; @@ -17,53 +18,47 @@ public final class NginxConfigurationListResponseTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { NginxConfigurationListResponse model = BinaryData.fromString( - "{\"value\":[{\"properties\":{\"provisioningState\":\"Canceled\",\"files\":[{\"content\":\"mtqio\",\"virtualPath\":\"zehtbmu\"},{\"content\":\"ownoizhw\",\"virtualPath\":\"xybqsoqij\"},{\"content\":\"dmbpazlobcufpdz\",\"virtualPath\":\"btcqq\"}],\"protectedFiles\":[{\"content\":\"lhqgnufooojy\",\"virtualPath\":\"fsqesaagdfmglzlh\"},{\"content\":\"rifkwm\",\"virtualPath\":\"ktsizntocipaou\"}],\"package\":{\"data\":\"s\",\"protectedFiles\":[\"mpoyfd\",\"fogknygjofjdde\",\"s\",\"deupewnwrei\"]},\"rootFile\":\"zyf\"},\"location\":\"sarhmofc\",\"id\":\"smy\",\"name\":\"rkdtmlxh\",\"type\":\"kuksjtxukcdm\"}],\"nextLink\":\"rcryuanzwuxzdxta\"}") + "{\"value\":[{\"properties\":{\"provisioningState\":\"Deleting\",\"files\":[{\"content\":\"ddeqsrdeupewnwre\",\"virtualPath\":\"jzyflu\"},{\"content\":\"rh\",\"virtualPath\":\"fcqhsmyurkd\"}],\"protectedFiles\":[{\"virtualPath\":\"he\",\"contentHash\":\"k\"}],\"package\":{\"data\":\"xukcdmpar\",\"protectedFiles\":[\"uanzwuxzdx\"]},\"rootFile\":\"yrlhmwhfpmrqobm\"},\"id\":\"kknryrtihf\",\"name\":\"tijbpzvgnwzsymgl\",\"type\":\"uf\"}],\"nextLink\":\"zk\"}") .toObject(NginxConfigurationListResponse.class); - Assertions.assertEquals("mtqio", model.value().get(0).properties().files().get(0).content()); - Assertions.assertEquals("zehtbmu", model.value().get(0).properties().files().get(0).virtualPath()); - Assertions.assertEquals("lhqgnufooojy", model.value().get(0).properties().protectedFiles().get(0).content()); - Assertions.assertEquals("fsqesaagdfmglzlh", - model.value().get(0).properties().protectedFiles().get(0).virtualPath()); - Assertions.assertEquals("s", model.value().get(0).properties().packageProperty().data()); - Assertions.assertEquals("mpoyfd", model.value().get(0).properties().packageProperty().protectedFiles().get(0)); - Assertions.assertEquals("zyf", model.value().get(0).properties().rootFile()); - Assertions.assertEquals("sarhmofc", model.value().get(0).location()); - Assertions.assertEquals("rcryuanzwuxzdxta", model.nextLink()); + Assertions.assertEquals("ddeqsrdeupewnwre", model.value().get(0).properties().files().get(0).content()); + Assertions.assertEquals("jzyflu", model.value().get(0).properties().files().get(0).virtualPath()); + Assertions.assertEquals("he", model.value().get(0).properties().protectedFiles().get(0).virtualPath()); + Assertions.assertEquals("k", model.value().get(0).properties().protectedFiles().get(0).contentHash()); + Assertions.assertEquals("xukcdmpar", model.value().get(0).properties().packageProperty().data()); + Assertions.assertEquals("uanzwuxzdx", + model.value().get(0).properties().packageProperty().protectedFiles().get(0)); + Assertions.assertEquals("yrlhmwhfpmrqobm", model.value().get(0).properties().rootFile()); + Assertions.assertEquals("zk", model.nextLink()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { NginxConfigurationListResponse model = new NginxConfigurationListResponse() - .withValue(Arrays.asList( - new NginxConfigurationInner() - .withProperties( - new NginxConfigurationProperties() + .withValue( + Arrays + .asList(new NginxConfigurationResponseInner() + .withProperties(new NginxConfigurationResponseProperties() .withFiles(Arrays.asList( - new NginxConfigurationFile().withContent("mtqio").withVirtualPath("zehtbmu"), - new NginxConfigurationFile().withContent("ownoizhw").withVirtualPath("xybqsoqij"), - new NginxConfigurationFile().withContent("dmbpazlobcufpdz") - .withVirtualPath("btcqq"))) - .withProtectedFiles(Arrays.asList( - new NginxConfigurationFile().withContent("lhqgnufooojy") - .withVirtualPath("fsqesaagdfmglzlh"), - new NginxConfigurationFile().withContent("rifkwm") - .withVirtualPath("ktsizntocipaou"))) - .withPackageProperty(new NginxConfigurationPackage().withData("s") - .withProtectedFiles(Arrays.asList("mpoyfd", "fogknygjofjdde", "s", "deupewnwrei"))) - .withRootFile("zyf")) - .withLocation("sarhmofc"))) - .withNextLink("rcryuanzwuxzdxta"); + new NginxConfigurationFile().withContent("ddeqsrdeupewnwre") + .withVirtualPath("jzyflu"), + new NginxConfigurationFile().withContent("rh").withVirtualPath("fcqhsmyurkd"))) + .withProtectedFiles( + Arrays.asList(new NginxConfigurationProtectedFileResponse().withVirtualPath("he") + .withContentHash("k"))) + .withPackageProperty(new NginxConfigurationPackage().withData("xukcdmpar") + .withProtectedFiles(Arrays.asList("uanzwuxzdx"))) + .withRootFile("yrlhmwhfpmrqobm")))) + .withNextLink("zk"); model = BinaryData.fromObject(model).toObject(NginxConfigurationListResponse.class); - Assertions.assertEquals("mtqio", model.value().get(0).properties().files().get(0).content()); - Assertions.assertEquals("zehtbmu", model.value().get(0).properties().files().get(0).virtualPath()); - Assertions.assertEquals("lhqgnufooojy", model.value().get(0).properties().protectedFiles().get(0).content()); - Assertions.assertEquals("fsqesaagdfmglzlh", - model.value().get(0).properties().protectedFiles().get(0).virtualPath()); - Assertions.assertEquals("s", model.value().get(0).properties().packageProperty().data()); - Assertions.assertEquals("mpoyfd", model.value().get(0).properties().packageProperty().protectedFiles().get(0)); - Assertions.assertEquals("zyf", model.value().get(0).properties().rootFile()); - Assertions.assertEquals("sarhmofc", model.value().get(0).location()); - Assertions.assertEquals("rcryuanzwuxzdxta", model.nextLink()); + Assertions.assertEquals("ddeqsrdeupewnwre", model.value().get(0).properties().files().get(0).content()); + Assertions.assertEquals("jzyflu", model.value().get(0).properties().files().get(0).virtualPath()); + Assertions.assertEquals("he", model.value().get(0).properties().protectedFiles().get(0).virtualPath()); + Assertions.assertEquals("k", model.value().get(0).properties().protectedFiles().get(0).contentHash()); + Assertions.assertEquals("xukcdmpar", model.value().get(0).properties().packageProperty().data()); + Assertions.assertEquals("uanzwuxzdx", + model.value().get(0).properties().packageProperty().protectedFiles().get(0)); + Assertions.assertEquals("yrlhmwhfpmrqobm", model.value().get(0).properties().rootFile()); + Assertions.assertEquals("zk", model.nextLink()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationPackageTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationPackageTests.java index f2fcf2200e05..16bf0d49f335 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationPackageTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationPackageTests.java @@ -12,19 +12,19 @@ public final class NginxConfigurationPackageTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - NginxConfigurationPackage model - = BinaryData.fromString("{\"data\":\"zevdphlx\",\"protectedFiles\":[\"thqt\",\"gqjbpfzfsin\",\"gvfcj\"]}") - .toObject(NginxConfigurationPackage.class); - Assertions.assertEquals("zevdphlx", model.data()); - Assertions.assertEquals("thqt", model.protectedFiles().get(0)); + NginxConfigurationPackage model = BinaryData + .fromString("{\"data\":\"qulngsntnbybkzgc\",\"protectedFiles\":[\"clxxwrljdo\",\"skcqvkocrcjd\"]}") + .toObject(NginxConfigurationPackage.class); + Assertions.assertEquals("qulngsntnbybkzgc", model.data()); + Assertions.assertEquals("clxxwrljdo", model.protectedFiles().get(0)); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - NginxConfigurationPackage model = new NginxConfigurationPackage().withData("zevdphlx") - .withProtectedFiles(Arrays.asList("thqt", "gqjbpfzfsin", "gvfcj")); + NginxConfigurationPackage model = new NginxConfigurationPackage().withData("qulngsntnbybkzgc") + .withProtectedFiles(Arrays.asList("clxxwrljdo", "skcqvkocrcjd")); model = BinaryData.fromObject(model).toObject(NginxConfigurationPackage.class); - Assertions.assertEquals("zevdphlx", model.data()); - Assertions.assertEquals("thqt", model.protectedFiles().get(0)); + Assertions.assertEquals("qulngsntnbybkzgc", model.data()); + Assertions.assertEquals("clxxwrljdo", model.protectedFiles().get(0)); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationPropertiesTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationPropertiesTests.java deleted file mode 100644 index 1584502804e6..000000000000 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationPropertiesTests.java +++ /dev/null @@ -1,47 +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.resourcemanager.nginx.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.nginx.models.NginxConfigurationFile; -import com.azure.resourcemanager.nginx.models.NginxConfigurationPackage; -import com.azure.resourcemanager.nginx.models.NginxConfigurationProperties; -import java.util.Arrays; -import org.junit.jupiter.api.Assertions; - -public final class NginxConfigurationPropertiesTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - NginxConfigurationProperties model = BinaryData.fromString( - "{\"provisioningState\":\"Updating\",\"files\":[{\"content\":\"nchgej\",\"virtualPath\":\"odmailzyd\"}],\"protectedFiles\":[{\"content\":\"wyahuxinpmqnja\",\"virtualPath\":\"ixjsprozvcputeg\"}],\"package\":{\"data\":\"mfdatscmdvpj\",\"protectedFiles\":[\"suuv\",\"kjozkrwfnd\",\"odjpslwejd\",\"vwryoqpso\"]},\"rootFile\":\"ctazakljlahbcryf\"}") - .toObject(NginxConfigurationProperties.class); - Assertions.assertEquals("nchgej", model.files().get(0).content()); - Assertions.assertEquals("odmailzyd", model.files().get(0).virtualPath()); - Assertions.assertEquals("wyahuxinpmqnja", model.protectedFiles().get(0).content()); - Assertions.assertEquals("ixjsprozvcputeg", model.protectedFiles().get(0).virtualPath()); - Assertions.assertEquals("mfdatscmdvpj", model.packageProperty().data()); - Assertions.assertEquals("suuv", model.packageProperty().protectedFiles().get(0)); - Assertions.assertEquals("ctazakljlahbcryf", model.rootFile()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - NginxConfigurationProperties model = new NginxConfigurationProperties() - .withFiles(Arrays.asList(new NginxConfigurationFile().withContent("nchgej").withVirtualPath("odmailzyd"))) - .withProtectedFiles(Arrays - .asList(new NginxConfigurationFile().withContent("wyahuxinpmqnja").withVirtualPath("ixjsprozvcputeg"))) - .withPackageProperty(new NginxConfigurationPackage().withData("mfdatscmdvpj") - .withProtectedFiles(Arrays.asList("suuv", "kjozkrwfnd", "odjpslwejd", "vwryoqpso"))) - .withRootFile("ctazakljlahbcryf"); - model = BinaryData.fromObject(model).toObject(NginxConfigurationProperties.class); - Assertions.assertEquals("nchgej", model.files().get(0).content()); - Assertions.assertEquals("odmailzyd", model.files().get(0).virtualPath()); - Assertions.assertEquals("wyahuxinpmqnja", model.protectedFiles().get(0).content()); - Assertions.assertEquals("ixjsprozvcputeg", model.protectedFiles().get(0).virtualPath()); - Assertions.assertEquals("mfdatscmdvpj", model.packageProperty().data()); - Assertions.assertEquals("suuv", model.packageProperty().protectedFiles().get(0)); - Assertions.assertEquals("ctazakljlahbcryf", model.rootFile()); - } -} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationProtectedFileRequestTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationProtectedFileRequestTests.java new file mode 100644 index 000000000000..141fcd23e7b2 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationProtectedFileRequestTests.java @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.nginx.models.NginxConfigurationProtectedFileRequest; +import org.junit.jupiter.api.Assertions; + +public final class NginxConfigurationProtectedFileRequestTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + NginxConfigurationProtectedFileRequest model = BinaryData + .fromString("{\"content\":\"ufizuckyf\",\"virtualPath\":\"rfidfvzwdz\",\"contentHash\":\"tymw\"}") + .toObject(NginxConfigurationProtectedFileRequest.class); + Assertions.assertEquals("ufizuckyf", model.content()); + Assertions.assertEquals("rfidfvzwdz", model.virtualPath()); + Assertions.assertEquals("tymw", model.contentHash()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + NginxConfigurationProtectedFileRequest model + = new NginxConfigurationProtectedFileRequest().withContent("ufizuckyf") + .withVirtualPath("rfidfvzwdz") + .withContentHash("tymw"); + model = BinaryData.fromObject(model).toObject(NginxConfigurationProtectedFileRequest.class); + Assertions.assertEquals("ufizuckyf", model.content()); + Assertions.assertEquals("rfidfvzwdz", model.virtualPath()); + Assertions.assertEquals("tymw", model.contentHash()); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationProtectedFileResponseTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationProtectedFileResponseTests.java new file mode 100644 index 000000000000..2f5d756cf2ca --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationProtectedFileResponseTests.java @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.nginx.models.NginxConfigurationProtectedFileResponse; +import org.junit.jupiter.api.Assertions; + +public final class NginxConfigurationProtectedFileResponseTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + NginxConfigurationProtectedFileResponse model + = BinaryData.fromString("{\"virtualPath\":\"jaeq\",\"contentHash\":\"qjbasvms\"}") + .toObject(NginxConfigurationProtectedFileResponse.class); + Assertions.assertEquals("jaeq", model.virtualPath()); + Assertions.assertEquals("qjbasvms", model.contentHash()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + NginxConfigurationProtectedFileResponse model + = new NginxConfigurationProtectedFileResponse().withVirtualPath("jaeq").withContentHash("qjbasvms"); + model = BinaryData.fromObject(model).toObject(NginxConfigurationProtectedFileResponse.class); + Assertions.assertEquals("jaeq", model.virtualPath()); + Assertions.assertEquals("qjbasvms", model.contentHash()); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationRequestPropertiesTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationRequestPropertiesTests.java new file mode 100644 index 000000000000..9c173864bf17 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationRequestPropertiesTests.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.nginx.models.NginxConfigurationFile; +import com.azure.resourcemanager.nginx.models.NginxConfigurationPackage; +import com.azure.resourcemanager.nginx.models.NginxConfigurationProtectedFileRequest; +import com.azure.resourcemanager.nginx.models.NginxConfigurationRequestProperties; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class NginxConfigurationRequestPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + NginxConfigurationRequestProperties model = BinaryData.fromString( + "{\"provisioningState\":\"Succeeded\",\"files\":[{\"content\":\"modmglougpb\",\"virtualPath\":\"tmut\"}],\"protectedFiles\":[{\"content\":\"ta\",\"virtualPath\":\"pwgcuertu\",\"contentHash\":\"dosvqwhbmdgbbjf\"},{\"content\":\"gmbmbexppbh\",\"virtualPath\":\"qrolfpf\",\"contentHash\":\"algbquxigjyjg\"},{\"content\":\"aoyfhrtxilnerkuj\",\"virtualPath\":\"vlejuvfqa\",\"contentHash\":\"lyxwjkcprbnwbx\"},{\"content\":\"vtb\",\"virtualPath\":\"ysszdnrujqguh\",\"contentHash\":\"ouqfprwz\"}],\"package\":{\"data\":\"g\",\"protectedFiles\":[\"nwui\"]},\"rootFile\":\"a\"}") + .toObject(NginxConfigurationRequestProperties.class); + Assertions.assertEquals("modmglougpb", model.files().get(0).content()); + Assertions.assertEquals("tmut", model.files().get(0).virtualPath()); + Assertions.assertEquals("ta", model.protectedFiles().get(0).content()); + Assertions.assertEquals("pwgcuertu", model.protectedFiles().get(0).virtualPath()); + Assertions.assertEquals("dosvqwhbmdgbbjf", model.protectedFiles().get(0).contentHash()); + Assertions.assertEquals("g", model.packageProperty().data()); + Assertions.assertEquals("nwui", model.packageProperty().protectedFiles().get(0)); + Assertions.assertEquals("a", model.rootFile()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + NginxConfigurationRequestProperties model = new NginxConfigurationRequestProperties() + .withFiles(Arrays.asList(new NginxConfigurationFile().withContent("modmglougpb").withVirtualPath("tmut"))) + .withProtectedFiles(Arrays.asList( + new NginxConfigurationProtectedFileRequest().withContent("ta") + .withVirtualPath("pwgcuertu") + .withContentHash("dosvqwhbmdgbbjf"), + new NginxConfigurationProtectedFileRequest().withContent("gmbmbexppbh") + .withVirtualPath("qrolfpf") + .withContentHash("algbquxigjyjg"), + new NginxConfigurationProtectedFileRequest().withContent("aoyfhrtxilnerkuj") + .withVirtualPath("vlejuvfqa") + .withContentHash("lyxwjkcprbnwbx"), + new NginxConfigurationProtectedFileRequest().withContent("vtb") + .withVirtualPath("ysszdnrujqguh") + .withContentHash("ouqfprwz"))) + .withPackageProperty( + new NginxConfigurationPackage().withData("g").withProtectedFiles(Arrays.asList("nwui"))) + .withRootFile("a"); + model = BinaryData.fromObject(model).toObject(NginxConfigurationRequestProperties.class); + Assertions.assertEquals("modmglougpb", model.files().get(0).content()); + Assertions.assertEquals("tmut", model.files().get(0).virtualPath()); + Assertions.assertEquals("ta", model.protectedFiles().get(0).content()); + Assertions.assertEquals("pwgcuertu", model.protectedFiles().get(0).virtualPath()); + Assertions.assertEquals("dosvqwhbmdgbbjf", model.protectedFiles().get(0).contentHash()); + Assertions.assertEquals("g", model.packageProperty().data()); + Assertions.assertEquals("nwui", model.packageProperty().protectedFiles().get(0)); + Assertions.assertEquals("a", model.rootFile()); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationRequestTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationRequestTests.java new file mode 100644 index 000000000000..2f382de48f57 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationRequestTests.java @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.nginx.models.NginxConfigurationFile; +import com.azure.resourcemanager.nginx.models.NginxConfigurationPackage; +import com.azure.resourcemanager.nginx.models.NginxConfigurationProtectedFileRequest; +import com.azure.resourcemanager.nginx.models.NginxConfigurationRequest; +import com.azure.resourcemanager.nginx.models.NginxConfigurationRequestProperties; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class NginxConfigurationRequestTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + NginxConfigurationRequest model = BinaryData.fromString( + "{\"properties\":{\"provisioningState\":\"NotSpecified\",\"files\":[{\"content\":\"njbiksqrglssain\",\"virtualPath\":\"jwnzlljfmp\"},{\"content\":\"ebvmgxsabkyqd\",\"virtualPath\":\"jitcjczdzevn\"},{\"content\":\"krwpdap\",\"virtualPath\":\"sbdkvwr\"}],\"protectedFiles\":[{\"content\":\"usnhutje\",\"virtualPath\":\"mrldhu\",\"contentHash\":\"zzd\"},{\"content\":\"qxhocdgeablgphut\",\"virtualPath\":\"ndv\",\"contentHash\":\"ozwyiftyhxhuro\"}],\"package\":{\"data\":\"yxolniwp\",\"protectedFiles\":[\"kjfkg\",\"awxklr\",\"plwckbas\",\"ypnddhsgcb\"]},\"rootFile\":\"phejkotynqgoulz\"},\"id\":\"likwyqkgfgib\",\"name\":\"adgakeqsrxybz\",\"type\":\"qedqytbciqfoufl\"}") + .toObject(NginxConfigurationRequest.class); + Assertions.assertEquals("njbiksqrglssain", model.properties().files().get(0).content()); + Assertions.assertEquals("jwnzlljfmp", model.properties().files().get(0).virtualPath()); + Assertions.assertEquals("usnhutje", model.properties().protectedFiles().get(0).content()); + Assertions.assertEquals("mrldhu", model.properties().protectedFiles().get(0).virtualPath()); + Assertions.assertEquals("zzd", model.properties().protectedFiles().get(0).contentHash()); + Assertions.assertEquals("yxolniwp", model.properties().packageProperty().data()); + Assertions.assertEquals("kjfkg", model.properties().packageProperty().protectedFiles().get(0)); + Assertions.assertEquals("phejkotynqgoulz", model.properties().rootFile()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + NginxConfigurationRequest model + = new NginxConfigurationRequest().withProperties(new NginxConfigurationRequestProperties() + .withFiles(Arrays.asList( + new NginxConfigurationFile().withContent("njbiksqrglssain").withVirtualPath("jwnzlljfmp"), + new NginxConfigurationFile().withContent("ebvmgxsabkyqd").withVirtualPath("jitcjczdzevn"), + new NginxConfigurationFile().withContent("krwpdap").withVirtualPath("sbdkvwr"))) + .withProtectedFiles(Arrays.asList( + new NginxConfigurationProtectedFileRequest().withContent("usnhutje") + .withVirtualPath("mrldhu") + .withContentHash("zzd"), + new NginxConfigurationProtectedFileRequest().withContent("qxhocdgeablgphut") + .withVirtualPath("ndv") + .withContentHash("ozwyiftyhxhuro"))) + .withPackageProperty(new NginxConfigurationPackage().withData("yxolniwp") + .withProtectedFiles(Arrays.asList("kjfkg", "awxklr", "plwckbas", "ypnddhsgcb"))) + .withRootFile("phejkotynqgoulz")); + model = BinaryData.fromObject(model).toObject(NginxConfigurationRequest.class); + Assertions.assertEquals("njbiksqrglssain", model.properties().files().get(0).content()); + Assertions.assertEquals("jwnzlljfmp", model.properties().files().get(0).virtualPath()); + Assertions.assertEquals("usnhutje", model.properties().protectedFiles().get(0).content()); + Assertions.assertEquals("mrldhu", model.properties().protectedFiles().get(0).virtualPath()); + Assertions.assertEquals("zzd", model.properties().protectedFiles().get(0).contentHash()); + Assertions.assertEquals("yxolniwp", model.properties().packageProperty().data()); + Assertions.assertEquals("kjfkg", model.properties().packageProperty().protectedFiles().get(0)); + Assertions.assertEquals("phejkotynqgoulz", model.properties().rootFile()); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationResponseInnerTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationResponseInnerTests.java new file mode 100644 index 000000000000..2b0c530e18c7 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationResponseInnerTests.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.nginx.fluent.models.NginxConfigurationResponseInner; +import com.azure.resourcemanager.nginx.models.NginxConfigurationFile; +import com.azure.resourcemanager.nginx.models.NginxConfigurationPackage; +import com.azure.resourcemanager.nginx.models.NginxConfigurationProtectedFileResponse; +import com.azure.resourcemanager.nginx.models.NginxConfigurationResponseProperties; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class NginxConfigurationResponseInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + NginxConfigurationResponseInner model = BinaryData.fromString( + "{\"properties\":{\"provisioningState\":\"Creating\",\"files\":[{\"content\":\"nufhf\",\"virtualPath\":\"jysagith\"},{\"content\":\"hab\",\"virtualPath\":\"pikxwczbyscnpqxu\"},{\"content\":\"vyq\",\"virtualPath\":\"wby\"},{\"content\":\"k\",\"virtualPath\":\"dumjgrtfwvuk\"}],\"protectedFiles\":[{\"virtualPath\":\"dcc\",\"contentHash\":\"h\"},{\"virtualPath\":\"cnyejhkryhtnapcz\",\"contentHash\":\"okjye\"},{\"virtualPath\":\"kvnipjoxz\",\"contentHash\":\"chgejspodm\"}],\"package\":{\"data\":\"zyde\",\"protectedFiles\":[\"wyahuxinpmqnja\",\"wixjsprozvcp\",\"tegjvwmf\",\"atscmd\"]},\"rootFile\":\"jhulsuuvmkjo\"},\"id\":\"rwfndiod\",\"name\":\"pslwejdpvw\",\"type\":\"yoqpsoaccta\"}") + .toObject(NginxConfigurationResponseInner.class); + Assertions.assertEquals("nufhf", model.properties().files().get(0).content()); + Assertions.assertEquals("jysagith", model.properties().files().get(0).virtualPath()); + Assertions.assertEquals("dcc", model.properties().protectedFiles().get(0).virtualPath()); + Assertions.assertEquals("h", model.properties().protectedFiles().get(0).contentHash()); + Assertions.assertEquals("zyde", model.properties().packageProperty().data()); + Assertions.assertEquals("wyahuxinpmqnja", model.properties().packageProperty().protectedFiles().get(0)); + Assertions.assertEquals("jhulsuuvmkjo", model.properties().rootFile()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + NginxConfigurationResponseInner model + = new NginxConfigurationResponseInner().withProperties(new NginxConfigurationResponseProperties() + .withFiles(Arrays.asList(new NginxConfigurationFile().withContent("nufhf").withVirtualPath("jysagith"), + new NginxConfigurationFile().withContent("hab").withVirtualPath("pikxwczbyscnpqxu"), + new NginxConfigurationFile().withContent("vyq").withVirtualPath("wby"), + new NginxConfigurationFile().withContent("k").withVirtualPath("dumjgrtfwvuk"))) + .withProtectedFiles(Arrays.asList( + new NginxConfigurationProtectedFileResponse().withVirtualPath("dcc").withContentHash("h"), + new NginxConfigurationProtectedFileResponse().withVirtualPath("cnyejhkryhtnapcz") + .withContentHash("okjye"), + new NginxConfigurationProtectedFileResponse().withVirtualPath("kvnipjoxz") + .withContentHash("chgejspodm"))) + .withPackageProperty(new NginxConfigurationPackage().withData("zyde") + .withProtectedFiles(Arrays.asList("wyahuxinpmqnja", "wixjsprozvcp", "tegjvwmf", "atscmd"))) + .withRootFile("jhulsuuvmkjo")); + model = BinaryData.fromObject(model).toObject(NginxConfigurationResponseInner.class); + Assertions.assertEquals("nufhf", model.properties().files().get(0).content()); + Assertions.assertEquals("jysagith", model.properties().files().get(0).virtualPath()); + Assertions.assertEquals("dcc", model.properties().protectedFiles().get(0).virtualPath()); + Assertions.assertEquals("h", model.properties().protectedFiles().get(0).contentHash()); + Assertions.assertEquals("zyde", model.properties().packageProperty().data()); + Assertions.assertEquals("wyahuxinpmqnja", model.properties().packageProperty().protectedFiles().get(0)); + Assertions.assertEquals("jhulsuuvmkjo", model.properties().rootFile()); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationResponsePropertiesTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationResponsePropertiesTests.java new file mode 100644 index 000000000000..ec8ab28cefb1 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxConfigurationResponsePropertiesTests.java @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.nginx.models.NginxConfigurationFile; +import com.azure.resourcemanager.nginx.models.NginxConfigurationPackage; +import com.azure.resourcemanager.nginx.models.NginxConfigurationProtectedFileResponse; +import com.azure.resourcemanager.nginx.models.NginxConfigurationResponseProperties; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class NginxConfigurationResponsePropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + NginxConfigurationResponseProperties model = BinaryData.fromString( + "{\"provisioningState\":\"Failed\",\"files\":[{\"content\":\"ahbc\",\"virtualPath\":\"ffdfdosygexpa\"}],\"protectedFiles\":[{\"virtualPath\":\"hmsbzjhcrzevdp\",\"contentHash\":\"xaolth\"},{\"virtualPath\":\"rgqjbpfzfsinzg\",\"contentHash\":\"cjrwzoxxjtfellu\"},{\"virtualPath\":\"zitonpeqfpjkjl\",\"contentHash\":\"fpdvhpfxxypi\"}],\"package\":{\"data\":\"mayhuybbkpodepoo\",\"protectedFiles\":[\"uvamiheognarxzxt\",\"eotusivyevc\",\"iqihn\"]},\"rootFile\":\"ngbwjz\"}") + .toObject(NginxConfigurationResponseProperties.class); + Assertions.assertEquals("ahbc", model.files().get(0).content()); + Assertions.assertEquals("ffdfdosygexpa", model.files().get(0).virtualPath()); + Assertions.assertEquals("hmsbzjhcrzevdp", model.protectedFiles().get(0).virtualPath()); + Assertions.assertEquals("xaolth", model.protectedFiles().get(0).contentHash()); + Assertions.assertEquals("mayhuybbkpodepoo", model.packageProperty().data()); + Assertions.assertEquals("uvamiheognarxzxt", model.packageProperty().protectedFiles().get(0)); + Assertions.assertEquals("ngbwjz", model.rootFile()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + NginxConfigurationResponseProperties model = new NginxConfigurationResponseProperties() + .withFiles(Arrays.asList(new NginxConfigurationFile().withContent("ahbc").withVirtualPath("ffdfdosygexpa"))) + .withProtectedFiles(Arrays.asList( + new NginxConfigurationProtectedFileResponse().withVirtualPath("hmsbzjhcrzevdp") + .withContentHash("xaolth"), + new NginxConfigurationProtectedFileResponse().withVirtualPath("rgqjbpfzfsinzg") + .withContentHash("cjrwzoxxjtfellu"), + new NginxConfigurationProtectedFileResponse().withVirtualPath("zitonpeqfpjkjl") + .withContentHash("fpdvhpfxxypi"))) + .withPackageProperty(new NginxConfigurationPackage().withData("mayhuybbkpodepoo") + .withProtectedFiles(Arrays.asList("uvamiheognarxzxt", "eotusivyevc", "iqihn"))) + .withRootFile("ngbwjz"); + model = BinaryData.fromObject(model).toObject(NginxConfigurationResponseProperties.class); + Assertions.assertEquals("ahbc", model.files().get(0).content()); + Assertions.assertEquals("ffdfdosygexpa", model.files().get(0).virtualPath()); + Assertions.assertEquals("hmsbzjhcrzevdp", model.protectedFiles().get(0).virtualPath()); + Assertions.assertEquals("xaolth", model.protectedFiles().get(0).contentHash()); + Assertions.assertEquals("mayhuybbkpodepoo", model.packageProperty().data()); + Assertions.assertEquals("uvamiheognarxzxt", model.packageProperty().protectedFiles().get(0)); + Assertions.assertEquals("ngbwjz", model.rootFile()); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentApiKeyListResponseTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentApiKeyListResponseTests.java new file mode 100644 index 000000000000..554ad449374b --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentApiKeyListResponseTests.java @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.nginx.fluent.models.NginxDeploymentApiKeyResponseInner; +import com.azure.resourcemanager.nginx.models.NginxDeploymentApiKeyListResponse; +import com.azure.resourcemanager.nginx.models.NginxDeploymentApiKeyResponseProperties; +import java.time.OffsetDateTime; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class NginxDeploymentApiKeyListResponseTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + NginxDeploymentApiKeyListResponse model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"hint\":\"bqsoqijg\",\"endDateTime\":\"2021-10-01T09:23:29Z\"},\"id\":\"bpazlobcufpdzn\",\"name\":\"btcqq\",\"type\":\"nq\"},{\"properties\":{\"hint\":\"qgn\",\"endDateTime\":\"2021-06-16T07:30:55Z\"},\"id\":\"oo\",\"name\":\"ywifsqesaag\",\"type\":\"f\"}],\"nextLink\":\"lzl\"}") + .toObject(NginxDeploymentApiKeyListResponse.class); + Assertions.assertEquals(OffsetDateTime.parse("2021-10-01T09:23:29Z"), + model.value().get(0).properties().endDateTime()); + Assertions.assertEquals("lzl", model.nextLink()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + NginxDeploymentApiKeyListResponse model = new NginxDeploymentApiKeyListResponse().withValue(Arrays.asList( + new NginxDeploymentApiKeyResponseInner().withProperties(new NginxDeploymentApiKeyResponseProperties() + .withEndDateTime(OffsetDateTime.parse("2021-10-01T09:23:29Z"))), + new NginxDeploymentApiKeyResponseInner().withProperties(new NginxDeploymentApiKeyResponseProperties() + .withEndDateTime(OffsetDateTime.parse("2021-06-16T07:30:55Z"))))) + .withNextLink("lzl"); + model = BinaryData.fromObject(model).toObject(NginxDeploymentApiKeyListResponse.class); + Assertions.assertEquals(OffsetDateTime.parse("2021-10-01T09:23:29Z"), + model.value().get(0).properties().endDateTime()); + Assertions.assertEquals("lzl", model.nextLink()); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentApiKeyResponseInnerTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentApiKeyResponseInnerTests.java new file mode 100644 index 000000000000..8499e7b64a47 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentApiKeyResponseInnerTests.java @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.nginx.fluent.models.NginxDeploymentApiKeyResponseInner; +import com.azure.resourcemanager.nginx.models.NginxDeploymentApiKeyResponseProperties; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; + +public final class NginxDeploymentApiKeyResponseInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + NginxDeploymentApiKeyResponseInner model = BinaryData.fromString( + "{\"properties\":{\"hint\":\"bsphrupidgsybbe\",\"endDateTime\":\"2021-02-20T13:53:07Z\"},\"id\":\"hoycm\",\"name\":\"xaobhdxbmtqioqjz\",\"type\":\"htbmuf\"}") + .toObject(NginxDeploymentApiKeyResponseInner.class); + Assertions.assertEquals(OffsetDateTime.parse("2021-02-20T13:53:07Z"), model.properties().endDateTime()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + NginxDeploymentApiKeyResponseInner model + = new NginxDeploymentApiKeyResponseInner().withProperties(new NginxDeploymentApiKeyResponseProperties() + .withEndDateTime(OffsetDateTime.parse("2021-02-20T13:53:07Z"))); + model = BinaryData.fromObject(model).toObject(NginxDeploymentApiKeyResponseInner.class); + Assertions.assertEquals(OffsetDateTime.parse("2021-02-20T13:53:07Z"), model.properties().endDateTime()); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentApiKeyResponsePropertiesTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentApiKeyResponsePropertiesTests.java new file mode 100644 index 000000000000..05df99ae758e --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentApiKeyResponsePropertiesTests.java @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.nginx.models.NginxDeploymentApiKeyResponseProperties; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; + +public final class NginxDeploymentApiKeyResponsePropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + NginxDeploymentApiKeyResponseProperties model + = BinaryData.fromString("{\"hint\":\"wnoi\",\"endDateTime\":\"2021-08-05T07:19:53Z\"}") + .toObject(NginxDeploymentApiKeyResponseProperties.class); + Assertions.assertEquals(OffsetDateTime.parse("2021-08-05T07:19:53Z"), model.endDateTime()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + NginxDeploymentApiKeyResponseProperties model = new NginxDeploymentApiKeyResponseProperties() + .withEndDateTime(OffsetDateTime.parse("2021-08-05T07:19:53Z")); + model = BinaryData.fromObject(model).toObject(NginxDeploymentApiKeyResponseProperties.class); + Assertions.assertEquals(OffsetDateTime.parse("2021-08-05T07:19:53Z"), model.endDateTime()); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentInnerTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentInnerTests.java index 9594323571d6..5dbb1427da62 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentInnerTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentInnerTests.java @@ -6,10 +6,12 @@ import com.azure.core.util.BinaryData; import com.azure.resourcemanager.nginx.fluent.models.NginxDeploymentInner; +import com.azure.resourcemanager.nginx.models.ActivationState; import com.azure.resourcemanager.nginx.models.AutoUpgradeProfile; import com.azure.resourcemanager.nginx.models.IdentityProperties; import com.azure.resourcemanager.nginx.models.IdentityType; import com.azure.resourcemanager.nginx.models.NginxDeploymentProperties; +import com.azure.resourcemanager.nginx.models.NginxDeploymentPropertiesNginxAppProtect; import com.azure.resourcemanager.nginx.models.NginxDeploymentScalingProperties; import com.azure.resourcemanager.nginx.models.NginxDeploymentUserProfile; import com.azure.resourcemanager.nginx.models.NginxFrontendIpConfiguration; @@ -24,6 +26,7 @@ import com.azure.resourcemanager.nginx.models.ScaleProfile; import com.azure.resourcemanager.nginx.models.ScaleProfileCapacity; import com.azure.resourcemanager.nginx.models.UserIdentityProperties; +import com.azure.resourcemanager.nginx.models.WebApplicationFirewallSettings; import java.util.Arrays; import java.util.HashMap; import java.util.Map; @@ -33,15 +36,14 @@ public final class NginxDeploymentInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { NginxDeploymentInner model = BinaryData.fromString( - "{\"identity\":{\"principalId\":\"tnwu\",\"tenantId\":\"gazxuf\",\"type\":\"UserAssigned\",\"userAssignedIdentities\":{\"kfthwxmntei\":{\"principalId\":\"fihrfi\",\"clientId\":\"vzwdzuhtymwis\"}}},\"properties\":{\"provisioningState\":\"Deleting\",\"nginxVersion\":\"km\",\"managedResourceGroup\":\"c\",\"networkProfile\":{\"frontEndIPConfiguration\":{\"publicIPAddresses\":[{\"id\":\"fufsrpymzi\"},{\"id\":\"sezcxtb\"},{\"id\":\"gfycc\"}],\"privateIPAddresses\":[{\"privateIPAddress\":\"mdwzjeiachboo\",\"privateIPAllocationMethod\":\"Static\",\"subnetId\":\"ro\"},{\"privateIPAddress\":\"qpteeh\",\"privateIPAllocationMethod\":\"Dynamic\",\"subnetId\":\"pyqr\"}]},\"networkInterfaceConfiguration\":{\"subnetId\":\"inpvswjdkirsoodq\"}},\"ipAddress\":\"crmnohjtckwhds\",\"enableDiagnosticsSupport\":true,\"logging\":{\"storageAccount\":{\"accountName\":\"pjxsqwpgrjbznor\",\"containerName\":\"xv\"}},\"scalingProperties\":{\"capacity\":1906799262,\"autoScaleSettings\":{\"profiles\":[{\"name\":\"abnmocpcyshu\",\"capacity\":{\"min\":818060655,\"max\":2023442123}},{\"name\":\"fblj\",\"capacity\":{\"min\":844718571,\"max\":527758336}}]}},\"autoUpgradeProfile\":{\"upgradeChannel\":\"toqcjmklja\"},\"userProfile\":{\"preferredEmail\":\"idtqajzyu\"}},\"sku\":{\"name\":\"kudjkrlkhb\"},\"location\":\"fepgzgq\",\"tags\":{\"c\":\"locx\"},\"id\":\"aierhhb\",\"name\":\"sglumma\",\"type\":\"tjaodxobnb\"}") + "{\"identity\":{\"principalId\":\"sonpclhocohs\",\"tenantId\":\"ev\",\"type\":\"UserAssigned\",\"userAssignedIdentities\":{\"shxmzsbbzoggigrx\":{\"principalId\":\"buhfmvfaxkffeiit\",\"clientId\":\"vmezy\"},\"enkouknvudw\":{\"principalId\":\"ur\",\"clientId\":\"xxjnspydptk\"}}},\"properties\":{\"provisioningState\":\"Canceled\",\"nginxVersion\":\"ldngkpoci\",\"networkProfile\":{\"frontEndIPConfiguration\":{\"publicIPAddresses\":[{\"id\":\"egukgjnpiucg\"},{\"id\":\"evqzntypmrbp\"},{\"id\":\"c\"},{\"id\":\"qjsdpydnfyhxdeo\"}],\"privateIPAddresses\":[{\"privateIPAddress\":\"cwif\",\"privateIPAllocationMethod\":\"Static\",\"subnetId\":\"gzfbishcbk\"}]},\"networkInterfaceConfiguration\":{\"subnetId\":\"deyeamdphagalpbu\"}},\"ipAddress\":\"gipwhonowkg\",\"enableDiagnosticsSupport\":true,\"logging\":{\"storageAccount\":{\"accountName\":\"ixzbinjeputtmryw\",\"containerName\":\"zoqftiyqzrnkcqvy\"}},\"scalingProperties\":{\"capacity\":1062459417,\"autoScaleSettings\":{\"profiles\":[{\"name\":\"sicohoqqnwvlry\",\"capacity\":{\"min\":1416786049,\"max\":240696862}},{\"name\":\"hheunmmqhgyx\",\"capacity\":{\"min\":1391467998,\"max\":1953555312}},{\"name\":\"noc\",\"capacity\":{\"min\":1493031892,\"max\":820959200}}]}},\"autoUpgradeProfile\":{\"upgradeChannel\":\"lyaxuc\"},\"userProfile\":{\"preferredEmail\":\"qszf\"},\"nginxAppProtect\":{\"webApplicationFirewallSettings\":{\"activationState\":\"Disabled\"},\"webApplicationFirewallStatus\":{\"attackSignaturesPackage\":{\"version\":\"wrmjmwvvjektc\",\"revisionDatetime\":\"2021-03-20T12:50:25Z\"},\"botSignaturesPackage\":{\"version\":\"nhwlrsffrzpwvl\",\"revisionDatetime\":\"2021-01-03T19:26:04Z\"},\"threatCampaignsPackage\":{\"version\":\"gbiqylihkaet\",\"revisionDatetime\":\"2021-03-28T05:06:34Z\"},\"componentVersions\":{\"wafEngineVersion\":\"vfcivfsnkymuc\",\"wafNginxVersion\":\"qhjfbebr\"}}},\"dataplaneApiEndpoint\":\"xerf\"},\"sku\":{\"name\":\"utttxfvjrbirp\"},\"location\":\"epcyvahfnlj\",\"tags\":{\"ljyoxgvcltb\":\"xjvuujqgidokg\"},\"id\":\"sncghkjeszz\",\"name\":\"bijhtxfvgxbf\",\"type\":\"mxnehmp\"}") .toObject(NginxDeploymentInner.class); - Assertions.assertEquals("fepgzgq", model.location()); - Assertions.assertEquals("locx", model.tags().get("c")); + Assertions.assertEquals("epcyvahfnlj", model.location()); + Assertions.assertEquals("xjvuujqgidokg", model.tags().get("ljyoxgvcltb")); Assertions.assertEquals(IdentityType.USER_ASSIGNED, model.identity().type()); - Assertions.assertEquals("c", model.properties().managedResourceGroup()); - Assertions.assertEquals("fufsrpymzi", + Assertions.assertEquals("egukgjnpiucg", model.properties().networkProfile().frontEndIpConfiguration().publicIpAddresses().get(0).id()); - Assertions.assertEquals("mdwzjeiachboo", + Assertions.assertEquals("cwif", model.properties() .networkProfile() .frontEndIpConfiguration() @@ -55,71 +57,66 @@ public void testDeserialize() throws Exception { .privateIpAddresses() .get(0) .privateIpAllocationMethod()); - Assertions.assertEquals("ro", + Assertions.assertEquals("gzfbishcbk", model.properties().networkProfile().frontEndIpConfiguration().privateIpAddresses().get(0).subnetId()); - Assertions.assertEquals("inpvswjdkirsoodq", + Assertions.assertEquals("deyeamdphagalpbu", model.properties().networkProfile().networkInterfaceConfiguration().subnetId()); Assertions.assertEquals(true, model.properties().enableDiagnosticsSupport()); - Assertions.assertEquals("pjxsqwpgrjbznor", model.properties().logging().storageAccount().accountName()); - Assertions.assertEquals("xv", model.properties().logging().storageAccount().containerName()); - Assertions.assertEquals(1906799262, model.properties().scalingProperties().capacity()); - Assertions.assertEquals("abnmocpcyshu", model.properties().scalingProperties().profiles().get(0).name()); - Assertions.assertEquals(818060655, model.properties().scalingProperties().profiles().get(0).capacity().min()); - Assertions.assertEquals(2023442123, model.properties().scalingProperties().profiles().get(0).capacity().max()); - Assertions.assertEquals("toqcjmklja", model.properties().autoUpgradeProfile().upgradeChannel()); - Assertions.assertEquals("idtqajzyu", model.properties().userProfile().preferredEmail()); - Assertions.assertEquals("kudjkrlkhb", model.sku().name()); + Assertions.assertEquals("ixzbinjeputtmryw", model.properties().logging().storageAccount().accountName()); + Assertions.assertEquals("zoqftiyqzrnkcqvy", model.properties().logging().storageAccount().containerName()); + Assertions.assertEquals(1062459417, model.properties().scalingProperties().capacity()); + Assertions.assertEquals("sicohoqqnwvlry", model.properties().scalingProperties().profiles().get(0).name()); + Assertions.assertEquals(1416786049, model.properties().scalingProperties().profiles().get(0).capacity().min()); + Assertions.assertEquals(240696862, model.properties().scalingProperties().profiles().get(0).capacity().max()); + Assertions.assertEquals("lyaxuc", model.properties().autoUpgradeProfile().upgradeChannel()); + Assertions.assertEquals("qszf", model.properties().userProfile().preferredEmail()); + Assertions.assertEquals(ActivationState.DISABLED, + model.properties().nginxAppProtect().webApplicationFirewallSettings().activationState()); + Assertions.assertEquals("utttxfvjrbirp", model.sku().name()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - NginxDeploymentInner model - = new NginxDeploymentInner().withLocation("fepgzgq") - .withTags(mapOf("c", "locx")) - .withIdentity(new IdentityProperties().withType(IdentityType.USER_ASSIGNED) - .withUserAssignedIdentities(mapOf("kfthwxmntei", new UserIdentityProperties()))) - .withProperties( - new NginxDeploymentProperties().withManagedResourceGroup("c") - .withNetworkProfile( - new NginxNetworkProfile() - .withFrontEndIpConfiguration( - new NginxFrontendIpConfiguration() - .withPublicIpAddresses( - Arrays.asList(new NginxPublicIpAddress().withId("fufsrpymzi"), - new NginxPublicIpAddress().withId("sezcxtb"), - new NginxPublicIpAddress().withId("gfycc"))) - .withPrivateIpAddresses( - Arrays.asList( - new NginxPrivateIpAddress().withPrivateIpAddress("mdwzjeiachboo") - .withPrivateIpAllocationMethod( - NginxPrivateIpAllocationMethod.STATIC) - .withSubnetId("ro"), - new NginxPrivateIpAddress().withPrivateIpAddress("qpteeh") - .withPrivateIpAllocationMethod( - NginxPrivateIpAllocationMethod.DYNAMIC) - .withSubnetId("pyqr")))) - .withNetworkInterfaceConfiguration( - new NginxNetworkInterfaceConfiguration().withSubnetId("inpvswjdkirsoodq"))) - .withEnableDiagnosticsSupport(true) - .withLogging(new NginxLogging().withStorageAccount( - new NginxStorageAccount().withAccountName("pjxsqwpgrjbznor").withContainerName("xv"))) - .withScalingProperties(new NginxDeploymentScalingProperties().withCapacity(1906799262) - .withProfiles(Arrays.asList( - new ScaleProfile().withName("abnmocpcyshu") - .withCapacity(new ScaleProfileCapacity().withMin(818060655).withMax(2023442123)), - new ScaleProfile().withName("fblj") - .withCapacity(new ScaleProfileCapacity().withMin(844718571).withMax(527758336))))) - .withAutoUpgradeProfile(new AutoUpgradeProfile().withUpgradeChannel("toqcjmklja")) - .withUserProfile(new NginxDeploymentUserProfile().withPreferredEmail("idtqajzyu"))) - .withSku(new ResourceSku().withName("kudjkrlkhb")); + NginxDeploymentInner model = new NginxDeploymentInner().withLocation("epcyvahfnlj") + .withTags(mapOf("ljyoxgvcltb", "xjvuujqgidokg")) + .withIdentity(new IdentityProperties().withType(IdentityType.USER_ASSIGNED) + .withUserAssignedIdentities(mapOf("shxmzsbbzoggigrx", new UserIdentityProperties(), "enkouknvudw", + new UserIdentityProperties()))) + .withProperties(new NginxDeploymentProperties() + .withNetworkProfile(new NginxNetworkProfile() + .withFrontEndIpConfiguration(new NginxFrontendIpConfiguration() + .withPublicIpAddresses(Arrays.asList(new NginxPublicIpAddress().withId("egukgjnpiucg"), + new NginxPublicIpAddress().withId("evqzntypmrbp"), new NginxPublicIpAddress().withId("c"), + new NginxPublicIpAddress().withId("qjsdpydnfyhxdeo"))) + .withPrivateIpAddresses(Arrays.asList(new NginxPrivateIpAddress().withPrivateIpAddress("cwif") + .withPrivateIpAllocationMethod(NginxPrivateIpAllocationMethod.STATIC) + .withSubnetId("gzfbishcbk")))) + .withNetworkInterfaceConfiguration( + new NginxNetworkInterfaceConfiguration().withSubnetId("deyeamdphagalpbu"))) + .withEnableDiagnosticsSupport(true) + .withLogging( + new NginxLogging().withStorageAccount(new NginxStorageAccount().withAccountName("ixzbinjeputtmryw") + .withContainerName("zoqftiyqzrnkcqvy"))) + .withScalingProperties(new NginxDeploymentScalingProperties().withCapacity(1062459417) + .withProfiles(Arrays.asList( + new ScaleProfile().withName("sicohoqqnwvlry") + .withCapacity(new ScaleProfileCapacity().withMin(1416786049).withMax(240696862)), + new ScaleProfile().withName("hheunmmqhgyx") + .withCapacity(new ScaleProfileCapacity().withMin(1391467998).withMax(1953555312)), + new ScaleProfile().withName("noc") + .withCapacity(new ScaleProfileCapacity().withMin(1493031892).withMax(820959200))))) + .withAutoUpgradeProfile(new AutoUpgradeProfile().withUpgradeChannel("lyaxuc")) + .withUserProfile(new NginxDeploymentUserProfile().withPreferredEmail("qszf")) + .withNginxAppProtect(new NginxDeploymentPropertiesNginxAppProtect().withWebApplicationFirewallSettings( + new WebApplicationFirewallSettings().withActivationState(ActivationState.DISABLED)))) + .withSku(new ResourceSku().withName("utttxfvjrbirp")); model = BinaryData.fromObject(model).toObject(NginxDeploymentInner.class); - Assertions.assertEquals("fepgzgq", model.location()); - Assertions.assertEquals("locx", model.tags().get("c")); + Assertions.assertEquals("epcyvahfnlj", model.location()); + Assertions.assertEquals("xjvuujqgidokg", model.tags().get("ljyoxgvcltb")); Assertions.assertEquals(IdentityType.USER_ASSIGNED, model.identity().type()); - Assertions.assertEquals("c", model.properties().managedResourceGroup()); - Assertions.assertEquals("fufsrpymzi", + Assertions.assertEquals("egukgjnpiucg", model.properties().networkProfile().frontEndIpConfiguration().publicIpAddresses().get(0).id()); - Assertions.assertEquals("mdwzjeiachboo", + Assertions.assertEquals("cwif", model.properties() .networkProfile() .frontEndIpConfiguration() @@ -133,20 +130,22 @@ public void testSerialize() throws Exception { .privateIpAddresses() .get(0) .privateIpAllocationMethod()); - Assertions.assertEquals("ro", + Assertions.assertEquals("gzfbishcbk", model.properties().networkProfile().frontEndIpConfiguration().privateIpAddresses().get(0).subnetId()); - Assertions.assertEquals("inpvswjdkirsoodq", + Assertions.assertEquals("deyeamdphagalpbu", model.properties().networkProfile().networkInterfaceConfiguration().subnetId()); Assertions.assertEquals(true, model.properties().enableDiagnosticsSupport()); - Assertions.assertEquals("pjxsqwpgrjbznor", model.properties().logging().storageAccount().accountName()); - Assertions.assertEquals("xv", model.properties().logging().storageAccount().containerName()); - Assertions.assertEquals(1906799262, model.properties().scalingProperties().capacity()); - Assertions.assertEquals("abnmocpcyshu", model.properties().scalingProperties().profiles().get(0).name()); - Assertions.assertEquals(818060655, model.properties().scalingProperties().profiles().get(0).capacity().min()); - Assertions.assertEquals(2023442123, model.properties().scalingProperties().profiles().get(0).capacity().max()); - Assertions.assertEquals("toqcjmklja", model.properties().autoUpgradeProfile().upgradeChannel()); - Assertions.assertEquals("idtqajzyu", model.properties().userProfile().preferredEmail()); - Assertions.assertEquals("kudjkrlkhb", model.sku().name()); + Assertions.assertEquals("ixzbinjeputtmryw", model.properties().logging().storageAccount().accountName()); + Assertions.assertEquals("zoqftiyqzrnkcqvy", model.properties().logging().storageAccount().containerName()); + Assertions.assertEquals(1062459417, model.properties().scalingProperties().capacity()); + Assertions.assertEquals("sicohoqqnwvlry", model.properties().scalingProperties().profiles().get(0).name()); + Assertions.assertEquals(1416786049, model.properties().scalingProperties().profiles().get(0).capacity().min()); + Assertions.assertEquals(240696862, model.properties().scalingProperties().profiles().get(0).capacity().max()); + Assertions.assertEquals("lyaxuc", model.properties().autoUpgradeProfile().upgradeChannel()); + Assertions.assertEquals("qszf", model.properties().userProfile().preferredEmail()); + Assertions.assertEquals(ActivationState.DISABLED, + model.properties().nginxAppProtect().webApplicationFirewallSettings().activationState()); + Assertions.assertEquals("utttxfvjrbirp", model.sku().name()); } // Use "Map.of" if available diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentListResponseTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentListResponseTests.java index 3e942f1abb72..d3189705d238 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentListResponseTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentListResponseTests.java @@ -6,11 +6,13 @@ import com.azure.core.util.BinaryData; import com.azure.resourcemanager.nginx.fluent.models.NginxDeploymentInner; +import com.azure.resourcemanager.nginx.models.ActivationState; import com.azure.resourcemanager.nginx.models.AutoUpgradeProfile; import com.azure.resourcemanager.nginx.models.IdentityProperties; import com.azure.resourcemanager.nginx.models.IdentityType; import com.azure.resourcemanager.nginx.models.NginxDeploymentListResponse; import com.azure.resourcemanager.nginx.models.NginxDeploymentProperties; +import com.azure.resourcemanager.nginx.models.NginxDeploymentPropertiesNginxAppProtect; import com.azure.resourcemanager.nginx.models.NginxDeploymentScalingProperties; import com.azure.resourcemanager.nginx.models.NginxDeploymentUserProfile; import com.azure.resourcemanager.nginx.models.NginxFrontendIpConfiguration; @@ -24,6 +26,7 @@ import com.azure.resourcemanager.nginx.models.ScaleProfile; import com.azure.resourcemanager.nginx.models.ScaleProfileCapacity; import com.azure.resourcemanager.nginx.models.UserIdentityProperties; +import com.azure.resourcemanager.nginx.models.WebApplicationFirewallSettings; import java.util.Arrays; import java.util.HashMap; import java.util.Map; @@ -33,172 +36,214 @@ public final class NginxDeploymentListResponseTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { NginxDeploymentListResponse model = BinaryData.fromString( - "{\"value\":[{\"identity\":{\"principalId\":\"xoegukgjnpiucgy\",\"tenantId\":\"vqzntypmrbpizcdr\",\"type\":\"None\",\"userAssignedIdentities\":{\"ishc\":{\"principalId\":\"dnfyhxdeoejzicwi\",\"clientId\":\"jttgzf\"}}},\"properties\":{\"provisioningState\":\"Creating\",\"nginxVersion\":\"deyeamdphagalpbu\",\"managedResourceGroup\":\"gipwhonowkg\",\"networkProfile\":{\"frontEndIPConfiguration\":{\"publicIPAddresses\":[{},{},{}],\"privateIPAddresses\":[{},{},{},{}]},\"networkInterfaceConfiguration\":{\"subnetId\":\"bin\"}},\"ipAddress\":\"pu\",\"enableDiagnosticsSupport\":false,\"logging\":{\"storageAccount\":{\"accountName\":\"nuzo\",\"containerName\":\"tiyqzrnkcqv\"}},\"scalingProperties\":{\"capacity\":798441434,\"autoScaleSettings\":{\"profiles\":[{\"name\":\"lsicohoqqnwv\",\"capacity\":{\"min\":1444459691,\"max\":759862878}},{\"name\":\"avwhheunm\",\"capacity\":{\"min\":1861834573,\"max\":375848936}}]}},\"autoUpgradeProfile\":{\"upgradeChannel\":\"yxzk\"},\"userProfile\":{\"preferredEmail\":\"cukoklyaxuconu\"}},\"sku\":{\"name\":\"zf\"},\"location\":\"eyp\",\"tags\":{\"enhwlrs\":\"mjmwvvjektcx\",\"qylihkaetckt\":\"frzpwvlqdqgb\",\"ctq\":\"fcivfsnkym\"},\"id\":\"jf\",\"name\":\"ebrjcxe\",\"type\":\"fuwutttxf\"},{\"identity\":{\"principalId\":\"birphxepcyva\",\"tenantId\":\"nljky\",\"type\":\"SystemAssigned\",\"userAssignedIdentities\":{\"oxgvclt\":{\"principalId\":\"j\",\"clientId\":\"idokgjlj\"},\"gx\":{\"principalId\":\"sncghkjeszz\",\"clientId\":\"ijhtxf\"},\"odebfqkkrbmpu\":{\"principalId\":\"smx\",\"clientId\":\"hmpvecx\"},\"cispnqzahmgkbr\":{\"principalId\":\"riwflzlfb\",\"clientId\":\"puz\"}}},\"properties\":{\"provisioningState\":\"Updating\",\"nginxVersion\":\"ibnuqqkpik\",\"managedResourceGroup\":\"rgvtqag\",\"networkProfile\":{\"frontEndIPConfiguration\":{\"publicIPAddresses\":[{},{},{}],\"privateIPAddresses\":[{},{},{}]},\"networkInterfaceConfiguration\":{\"subnetId\":\"gmebfsiarbutrcv\"}},\"ipAddress\":\"azzmhjrunmpxt\",\"enableDiagnosticsSupport\":false,\"logging\":{\"storageAccount\":{\"accountName\":\"nlankxmyskpb\",\"containerName\":\"nbtkcxywnytnr\"}},\"scalingProperties\":{\"capacity\":1641130583,\"autoScaleSettings\":{\"profiles\":[{\"name\":\"dybyxczfclhaa\",\"capacity\":{\"min\":1122692891,\"max\":904573366}},{\"name\":\"abphlw\",\"capacity\":{\"min\":77204722,\"max\":2142840160}},{\"name\":\"fkts\",\"capacity\":{\"min\":1572483367,\"max\":1927626418}}]}},\"autoUpgradeProfile\":{\"upgradeChannel\":\"cocmnyyaztt\"},\"userProfile\":{\"preferredEmail\":\"wrqpue\"}},\"sku\":{\"name\":\"kzywbiex\"},\"location\":\"eyueaxibxujwb\",\"tags\":{\"cuxrhdwbavx\":\"almuzyoxaepdkzja\"},\"id\":\"niwdjsw\",\"name\":\"tsdbpgn\",\"type\":\"ytxhp\"},{\"identity\":{\"principalId\":\"zpfzabglc\",\"tenantId\":\"xwtctyqiklbbovpl\",\"type\":\"UserAssigned\",\"userAssignedIdentities\":{\"mg\":{\"principalId\":\"yuguosvmkfssx\",\"clientId\":\"kkfpl\"},\"wzbaiue\":{\"principalId\":\"nkjzkdeslpvlop\",\"clientId\":\"yighxpk\"}}},\"properties\":{\"provisioningState\":\"Canceled\",\"nginxVersion\":\"nyqupedeojnabck\",\"managedResourceGroup\":\"mtxpsiebtfh\",\"networkProfile\":{\"frontEndIPConfiguration\":{\"publicIPAddresses\":[{},{}],\"privateIPAddresses\":[{},{},{}]},\"networkInterfaceConfiguration\":{\"subnetId\":\"dqmh\"}},\"ipAddress\":\"dhtldwkyz\",\"enableDiagnosticsSupport\":false,\"logging\":{\"storageAccount\":{\"accountName\":\"cwscwsvlx\",\"containerName\":\"ogtwrupqsxvnmi\"}},\"scalingProperties\":{\"capacity\":560100496,\"autoScaleSettings\":{\"profiles\":[{\"name\":\"o\",\"capacity\":{\"min\":579723655,\"max\":1739821364}},{\"name\":\"lo\",\"capacity\":{\"min\":1344905503,\"max\":660644635}},{\"name\":\"tyfjfcnjbkcnxdhb\",\"capacity\":{\"min\":1418382226,\"max\":657781919}},{\"name\":\"phywpnvj\",\"capacity\":{\"min\":597860603,\"max\":1633235296}}]}},\"autoUpgradeProfile\":{\"upgradeChannel\":\"ermclfplphoxuscr\"},\"userProfile\":{\"preferredEmail\":\"gyepsbjt\"}},\"sku\":{\"name\":\"qugxywpmueefjzwf\"},\"location\":\"q\",\"tags\":{\"cq\":\"dsuyonobgla\"},\"id\":\"tcc\",\"name\":\"g\",\"type\":\"udxytlmoyrx\"}],\"nextLink\":\"fudwpznt\"}") + "{\"value\":[{\"identity\":{\"principalId\":\"zfq\",\"tenantId\":\"huaoppp\",\"type\":\"SystemAssigned\",\"userAssignedIdentities\":{\"rmfqjhhkxbpvj\":{\"principalId\":\"lzdahzxctobgbkdm\",\"clientId\":\"zpostmgrcfbu\"},\"wbxqzvszjfau\":{\"principalId\":\"jhxxjyn\",\"clientId\":\"divkrt\"},\"bhsfxob\":{\"principalId\":\"fdxxivetvtcqaqtd\",\"clientId\":\"mcbxvwvxysl\"}}},\"properties\":{\"provisioningState\":\"Updating\",\"nginxVersion\":\"lmpewwwfbkr\",\"networkProfile\":{\"frontEndIPConfiguration\":{\"publicIPAddresses\":[{},{},{}],\"privateIPAddresses\":[{},{},{},{}]},\"networkInterfaceConfiguration\":{\"subnetId\":\"ohxcrsbfova\"}},\"ipAddress\":\"ruvw\",\"enableDiagnosticsSupport\":true,\"logging\":{\"storageAccount\":{\"accountName\":\"ubcgjbirxb\",\"containerName\":\"bsrfbj\"}},\"scalingProperties\":{\"capacity\":157171235,\"autoScaleSettings\":{\"profiles\":[{\"name\":\"otftpvjzbexilz\",\"capacity\":{\"min\":1948356330,\"max\":1551412306}},{\"name\":\"qqnvwpmq\",\"capacity\":{\"min\":1787439694,\"max\":1628769376}}]}},\"autoUpgradeProfile\":{\"upgradeChannel\":\"oujmkcjhwqytj\"},\"userProfile\":{\"preferredEmail\":\"n\"},\"nginxAppProtect\":{\"webApplicationFirewallSettings\":{\"activationState\":\"Disabled\"},\"webApplicationFirewallStatus\":{\"attackSignaturesPackage\":{\"version\":\"rjerv\",\"revisionDatetime\":\"2021-10-08T09:31:49Z\"},\"botSignaturesPackage\":{\"version\":\"nqpeh\",\"revisionDatetime\":\"2021-05-26T12:17:52Z\"},\"threatCampaignsPackage\":{\"version\":\"oygmift\",\"revisionDatetime\":\"2021-11-26T05:12:43Z\"},\"componentVersions\":{\"wafEngineVersion\":\"d\",\"wafNginxVersion\":\"dslgnayqigynduh\"}}},\"dataplaneApiEndpoint\":\"hqlkthumaqo\"},\"sku\":{\"name\":\"gycdu\"},\"location\":\"r\",\"tags\":{\"aolps\":\"cym\",\"dnbbglzps\":\"lqlfm\",\"adbzmnvdfznud\":\"iydmcwyhzdxs\",\"xzb\":\"od\"},\"id\":\"cblylpstdbhhxsr\",\"name\":\"dzu\",\"type\":\"erscdntne\"},{\"identity\":{\"principalId\":\"wjmy\",\"tenantId\":\"dsslswt\",\"type\":\"SystemAssigned, UserAssigned\",\"userAssignedIdentities\":{\"hhszh\":{\"principalId\":\"fzp\",\"clientId\":\"semwabnet\"}}},\"properties\":{\"provisioningState\":\"Succeeded\",\"nginxVersion\":\"wiwubm\",\"networkProfile\":{\"frontEndIPConfiguration\":{\"publicIPAddresses\":[{},{},{},{}],\"privateIPAddresses\":[{},{},{},{}]},\"networkInterfaceConfiguration\":{\"subnetId\":\"wwtppj\"}},\"ipAddress\":\"cxogaokonzm\",\"enableDiagnosticsSupport\":true,\"logging\":{\"storageAccount\":{\"accountName\":\"kqze\",\"containerName\":\"kdltfzxmhhvhg\"}},\"scalingProperties\":{\"capacity\":1748485864,\"autoScaleSettings\":{\"profiles\":[{\"name\":\"wobdagxtibqdx\",\"capacity\":{\"min\":1020209011,\"max\":709641319}},{\"name\":\"akbogqxndlkzgxh\",\"capacity\":{\"min\":975056149,\"max\":1924988063}},{\"name\":\"plbpodxun\",\"capacity\":{\"min\":1102783029,\"max\":405149242}}]}},\"autoUpgradeProfile\":{\"upgradeChannel\":\"xmubyyntwlrbq\"},\"userProfile\":{\"preferredEmail\":\"ievseotgqrllt\"},\"nginxAppProtect\":{\"webApplicationFirewallSettings\":{\"activationState\":\"Disabled\"},\"webApplicationFirewallStatus\":{\"attackSignaturesPackage\":{\"version\":\"wzizxbmpgcjefuzm\",\"revisionDatetime\":\"2021-06-29T22:40:26Z\"},\"botSignaturesPackage\":{\"version\":\"bttdumorppxe\",\"revisionDatetime\":\"2021-08-17T23:26:57Z\"},\"threatCampaignsPackage\":{\"version\":\"zbtbhj\",\"revisionDatetime\":\"2021-08-30T17:38:27Z\"},\"componentVersions\":{\"wafEngineVersion\":\"kfgohdneue\",\"wafNginxVersion\":\"fphsdyhtozfikdow\"}}},\"dataplaneApiEndpoint\":\"uuvxz\"},\"sku\":{\"name\":\"lvithhqzonosgg\"},\"location\":\"c\",\"tags\":{\"iiswacffgdkzze\":\"wdsjnkalju\",\"pfuflrw\":\"kfvhqcrailvpn\"},\"id\":\"mh\",\"name\":\"lxyjr\",\"type\":\"sag\"},{\"identity\":{\"principalId\":\"nihgwqapnedg\",\"tenantId\":\"cvkcvqvpkeqdcv\",\"type\":\"None\",\"userAssignedIdentities\":{\"dldwmgxc\":{\"principalId\":\"dsotbobzd\",\"clientId\":\"cjwvn\"}}},\"properties\":{\"provisioningState\":\"Updating\",\"nginxVersion\":\"mutwuoe\",\"networkProfile\":{\"frontEndIPConfiguration\":{\"publicIPAddresses\":[{},{},{}],\"privateIPAddresses\":[{},{},{}]},\"networkInterfaceConfiguration\":{\"subnetId\":\"yqsluic\"}},\"ipAddress\":\"ggkzzlvmbmpa\",\"enableDiagnosticsSupport\":true,\"logging\":{\"storageAccount\":{\"accountName\":\"uefywsbpfvmwy\",\"containerName\":\"fouyf\"}},\"scalingProperties\":{\"capacity\":1378791233,\"autoScaleSettings\":{\"profiles\":[{\"name\":\"wiyzvqtmnubexkp\",\"capacity\":{\"min\":1583015875,\"max\":1254452597}},{\"name\":\"mond\",\"capacity\":{\"min\":1929847054,\"max\":1007666972}},{\"name\":\"uxvypomgkopkwh\",\"capacity\":{\"min\":664596221,\"max\":10985850}}]}},\"autoUpgradeProfile\":{\"upgradeChannel\":\"ajqgxy\"},\"userProfile\":{\"preferredEmail\":\"cmbqfqvmk\"},\"nginxAppProtect\":{\"webApplicationFirewallSettings\":{\"activationState\":\"Enabled\"},\"webApplicationFirewallStatus\":{\"attackSignaturesPackage\":{\"version\":\"vhelxprglyatdd\",\"revisionDatetime\":\"2021-09-28T08:18:40Z\"},\"botSignaturesPackage\":{\"version\":\"bcuejrjxgci\",\"revisionDatetime\":\"2021-08-15T14:27:38Z\"},\"threatCampaignsPackage\":{\"version\":\"rhos\",\"revisionDatetime\":\"2021-01-18T20:01:11Z\"},\"componentVersions\":{\"wafEngineVersion\":\"qrhzoymibmrqyib\",\"wafNginxVersion\":\"hwflu\"}}},\"dataplaneApiEndpoint\":\"dtmhrkwofyyvoqa\"},\"sku\":{\"name\":\"iexpbtgiwbwo\"},\"location\":\"washr\",\"tags\":{\"ulpiuj\":\"kcnqxwbpo\",\"obyu\":\"aasipqi\"},\"id\":\"erpqlpqwcciuqg\",\"name\":\"dbutauvfbtkuwhh\",\"type\":\"hykojoxafnndlpic\"},{\"identity\":{\"principalId\":\"ymkcdyhb\",\"tenantId\":\"kpw\",\"type\":\"SystemAssigned, UserAssigned\",\"userAssignedIdentities\":{\"aeneqnzarrwl\":{\"principalId\":\"vvqfovljxyws\",\"clientId\":\"syrsndsytgadgvra\"},\"iipfpubj\":{\"principalId\":\"uijfqk\",\"clientId\":\"e\"},\"ynl\":{\"principalId\":\"wwiftohqkvpuv\",\"clientId\":\"gplsaknynf\"}}},\"properties\":{\"provisioningState\":\"Updating\",\"nginxVersion\":\"pxodlqiyntorzih\",\"networkProfile\":{\"frontEndIPConfiguration\":{\"publicIPAddresses\":[{},{},{}],\"privateIPAddresses\":[{}]},\"networkInterfaceConfiguration\":{\"subnetId\":\"mslyzrpzbchckqqz\"}},\"ipAddress\":\"ox\",\"enableDiagnosticsSupport\":true,\"logging\":{\"storageAccount\":{\"accountName\":\"zynkedya\",\"containerName\":\"wyhqmibzyhwits\"}},\"scalingProperties\":{\"capacity\":1679951474,\"autoScaleSettings\":{\"profiles\":[{\"name\":\"pcdpumnz\",\"capacity\":{\"min\":998287381,\"max\":944462660}},{\"name\":\"z\",\"capacity\":{\"min\":1443914942,\"max\":1417683929}},{\"name\":\"biknsorgjhxbld\",\"capacity\":{\"min\":1166597262,\"max\":706339919}}]}},\"autoUpgradeProfile\":{\"upgradeChannel\":\"rlkdmtncvokotl\"},\"userProfile\":{\"preferredEmail\":\"yhgsy\"},\"nginxAppProtect\":{\"webApplicationFirewallSettings\":{\"activationState\":\"Disabled\"},\"webApplicationFirewallStatus\":{\"attackSignaturesPackage\":{\"version\":\"tdtbnnhadooc\",\"revisionDatetime\":\"2021-05-16T20:34:23Z\"},\"botSignaturesPackage\":{\"version\":\"cikhnv\",\"revisionDatetime\":\"2021-10-11T09:13:27Z\"},\"threatCampaignsPackage\":{\"version\":\"qgxqquezikyw\",\"revisionDatetime\":\"2021-03-04T16:24:34Z\"},\"componentVersions\":{\"wafEngineVersion\":\"kallatmel\",\"wafNginxVersion\":\"uipiccjzk\"}}},\"dataplaneApiEndpoint\":\"v\"},\"sku\":{\"name\":\"vc\"},\"location\":\"y\",\"tags\":{\"drd\":\"rnxxmueed\",\"alm\":\"stkwqqtch\",\"gdv\":\"mtdaa\"},\"id\":\"vgpiohgwxrt\",\"name\":\"udxepxgyqagv\",\"type\":\"vmnpkukghimdblx\"}],\"nextLink\":\"imfnjhfjx\"}") .toObject(NginxDeploymentListResponse.class); - Assertions.assertEquals("eyp", model.value().get(0).location()); - Assertions.assertEquals("mjmwvvjektcx", model.value().get(0).tags().get("enhwlrs")); - Assertions.assertEquals(IdentityType.NONE, model.value().get(0).identity().type()); - Assertions.assertEquals("gipwhonowkg", model.value().get(0).properties().managedResourceGroup()); - Assertions.assertEquals("bin", + Assertions.assertEquals("r", model.value().get(0).location()); + Assertions.assertEquals("cym", model.value().get(0).tags().get("aolps")); + Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, model.value().get(0).identity().type()); + Assertions.assertEquals("ohxcrsbfova", model.value().get(0).properties().networkProfile().networkInterfaceConfiguration().subnetId()); - Assertions.assertEquals(false, model.value().get(0).properties().enableDiagnosticsSupport()); - Assertions.assertEquals("nuzo", model.value().get(0).properties().logging().storageAccount().accountName()); - Assertions.assertEquals("tiyqzrnkcqv", - model.value().get(0).properties().logging().storageAccount().containerName()); - Assertions.assertEquals(798441434, model.value().get(0).properties().scalingProperties().capacity()); - Assertions.assertEquals("lsicohoqqnwv", + Assertions.assertEquals(true, model.value().get(0).properties().enableDiagnosticsSupport()); + Assertions.assertEquals("ubcgjbirxb", + model.value().get(0).properties().logging().storageAccount().accountName()); + Assertions.assertEquals("bsrfbj", model.value().get(0).properties().logging().storageAccount().containerName()); + Assertions.assertEquals(157171235, model.value().get(0).properties().scalingProperties().capacity()); + Assertions.assertEquals("otftpvjzbexilz", model.value().get(0).properties().scalingProperties().profiles().get(0).name()); - Assertions.assertEquals(1444459691, + Assertions.assertEquals(1948356330, model.value().get(0).properties().scalingProperties().profiles().get(0).capacity().min()); - Assertions.assertEquals(759862878, + Assertions.assertEquals(1551412306, model.value().get(0).properties().scalingProperties().profiles().get(0).capacity().max()); - Assertions.assertEquals("yxzk", model.value().get(0).properties().autoUpgradeProfile().upgradeChannel()); - Assertions.assertEquals("cukoklyaxuconu", model.value().get(0).properties().userProfile().preferredEmail()); - Assertions.assertEquals("zf", model.value().get(0).sku().name()); - Assertions.assertEquals("fudwpznt", model.nextLink()); + Assertions.assertEquals("oujmkcjhwqytj", + model.value().get(0).properties().autoUpgradeProfile().upgradeChannel()); + Assertions.assertEquals("n", model.value().get(0).properties().userProfile().preferredEmail()); + Assertions.assertEquals(ActivationState.DISABLED, + model.value().get(0).properties().nginxAppProtect().webApplicationFirewallSettings().activationState()); + Assertions.assertEquals("gycdu", model.value().get(0).sku().name()); + Assertions.assertEquals("imfnjhfjx", model.nextLink()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { NginxDeploymentListResponse model = new NginxDeploymentListResponse() - .withValue( - Arrays - .asList( - new NginxDeploymentInner().withLocation("eyp") - .withTags(mapOf("enhwlrs", "mjmwvvjektcx", "qylihkaetckt", "frzpwvlqdqgb", "ctq", - "fcivfsnkym")) - .withIdentity(new IdentityProperties().withType(IdentityType.NONE) - .withUserAssignedIdentities(mapOf("ishc", new UserIdentityProperties()))) - .withProperties( - new NginxDeploymentProperties().withManagedResourceGroup("gipwhonowkg") - .withNetworkProfile( - new NginxNetworkProfile() - .withFrontEndIpConfiguration(new NginxFrontendIpConfiguration() - .withPublicIpAddresses(Arrays.asList(new NginxPublicIpAddress(), - new NginxPublicIpAddress(), new NginxPublicIpAddress())) - .withPrivateIpAddresses(Arrays.asList(new NginxPrivateIpAddress(), - new NginxPrivateIpAddress(), new NginxPrivateIpAddress(), - new NginxPrivateIpAddress()))) - .withNetworkInterfaceConfiguration( - new NginxNetworkInterfaceConfiguration().withSubnetId("bin"))) - .withEnableDiagnosticsSupport(false) - .withLogging(new NginxLogging().withStorageAccount( - new NginxStorageAccount().withAccountName("nuzo") - .withContainerName("tiyqzrnkcqv"))) - .withScalingProperties(new NginxDeploymentScalingProperties().withCapacity( - 798441434) - .withProfiles(Arrays.asList( - new ScaleProfile().withName("lsicohoqqnwv") - .withCapacity(new ScaleProfileCapacity().withMin(1444459691) - .withMax(759862878)), - new ScaleProfile().withName("avwhheunm") - .withCapacity(new ScaleProfileCapacity().withMin(1861834573) - .withMax(375848936))))) - .withAutoUpgradeProfile(new AutoUpgradeProfile().withUpgradeChannel("yxzk")) - .withUserProfile( - new NginxDeploymentUserProfile().withPreferredEmail("cukoklyaxuconu"))) - .withSku(new ResourceSku().withName("zf")), - new NginxDeploymentInner().withLocation("eyueaxibxujwb") - .withTags(mapOf("cuxrhdwbavx", "almuzyoxaepdkzja")) - .withIdentity(new IdentityProperties().withType(IdentityType.SYSTEM_ASSIGNED) - .withUserAssignedIdentities(mapOf("oxgvclt", new UserIdentityProperties(), "gx", - new UserIdentityProperties(), "odebfqkkrbmpu", new UserIdentityProperties(), - "cispnqzahmgkbr", new UserIdentityProperties()))) - .withProperties( - new NginxDeploymentProperties().withManagedResourceGroup("rgvtqag") - .withNetworkProfile( - new NginxNetworkProfile() - .withFrontEndIpConfiguration(new NginxFrontendIpConfiguration() - .withPublicIpAddresses(Arrays.asList(new NginxPublicIpAddress(), - new NginxPublicIpAddress(), new NginxPublicIpAddress())) - .withPrivateIpAddresses(Arrays.asList(new NginxPrivateIpAddress(), - new NginxPrivateIpAddress(), new NginxPrivateIpAddress()))) - .withNetworkInterfaceConfiguration( - new NginxNetworkInterfaceConfiguration() - .withSubnetId("gmebfsiarbutrcv"))) - .withEnableDiagnosticsSupport(false) - .withLogging(new NginxLogging().withStorageAccount( - new NginxStorageAccount().withAccountName("nlankxmyskpb") - .withContainerName("nbtkcxywnytnr"))) - .withScalingProperties(new NginxDeploymentScalingProperties().withCapacity( - 1641130583) - .withProfiles(Arrays.asList( - new ScaleProfile().withName("dybyxczfclhaa") - .withCapacity(new ScaleProfileCapacity().withMin(1122692891) - .withMax(904573366)), - new ScaleProfile().withName("abphlw") - .withCapacity(new ScaleProfileCapacity().withMin(77204722) - .withMax(2142840160)), - new ScaleProfile().withName("fkts") - .withCapacity(new ScaleProfileCapacity().withMin(1572483367) - .withMax(1927626418))))) - .withAutoUpgradeProfile( - new AutoUpgradeProfile().withUpgradeChannel("cocmnyyaztt")) - .withUserProfile(new NginxDeploymentUserProfile().withPreferredEmail("wrqpue"))) - .withSku(new ResourceSku().withName("kzywbiex")), - new NginxDeploymentInner().withLocation("q") - .withTags(mapOf("cq", "dsuyonobgla")) - .withIdentity(new IdentityProperties().withType(IdentityType.USER_ASSIGNED) - .withUserAssignedIdentities(mapOf("mg", new UserIdentityProperties(), "wzbaiue", - new UserIdentityProperties()))) - .withProperties( - new NginxDeploymentProperties().withManagedResourceGroup("mtxpsiebtfh") - .withNetworkProfile(new NginxNetworkProfile() - .withFrontEndIpConfiguration(new NginxFrontendIpConfiguration() - .withPublicIpAddresses(Arrays.asList(new NginxPublicIpAddress(), - new NginxPublicIpAddress())) - .withPrivateIpAddresses(Arrays.asList(new NginxPrivateIpAddress(), - new NginxPrivateIpAddress(), new NginxPrivateIpAddress()))) - .withNetworkInterfaceConfiguration( - new NginxNetworkInterfaceConfiguration().withSubnetId("dqmh"))) - .withEnableDiagnosticsSupport(false) - .withLogging(new NginxLogging() - .withStorageAccount(new NginxStorageAccount().withAccountName("cwscwsvlx") - .withContainerName("ogtwrupqsxvnmi"))) - .withScalingProperties( - new NginxDeploymentScalingProperties().withCapacity(560100496) - .withProfiles(Arrays.asList( - new ScaleProfile().withName("o") - .withCapacity(new ScaleProfileCapacity().withMin(579723655) - .withMax(1739821364)), - new ScaleProfile().withName("lo") - .withCapacity(new ScaleProfileCapacity().withMin(1344905503) - .withMax(660644635)), - new ScaleProfile().withName("tyfjfcnjbkcnxdhb") - .withCapacity(new ScaleProfileCapacity().withMin(1418382226) - .withMax(657781919)), - new ScaleProfile().withName("phywpnvj") - .withCapacity(new ScaleProfileCapacity().withMin(597860603) - .withMax(1633235296))))) - .withAutoUpgradeProfile( - new AutoUpgradeProfile().withUpgradeChannel("ermclfplphoxuscr")) - .withUserProfile( - new NginxDeploymentUserProfile().withPreferredEmail("gyepsbjt"))) - .withSku(new ResourceSku().withName("qugxywpmueefjzwf")))) - .withNextLink("fudwpznt"); + .withValue(Arrays.asList( + new NginxDeploymentInner().withLocation("r") + .withTags( + mapOf("aolps", "cym", "dnbbglzps", "lqlfm", "adbzmnvdfznud", "iydmcwyhzdxs", "xzb", "od")) + .withIdentity(new IdentityProperties() + .withType(IdentityType.SYSTEM_ASSIGNED) + .withUserAssignedIdentities(mapOf("rmfqjhhkxbpvj", new UserIdentityProperties(), + "wbxqzvszjfau", new UserIdentityProperties(), "bhsfxob", new UserIdentityProperties()))) + .withProperties(new NginxDeploymentProperties() + .withNetworkProfile(new NginxNetworkProfile() + .withFrontEndIpConfiguration(new NginxFrontendIpConfiguration() + .withPublicIpAddresses(Arrays.asList(new NginxPublicIpAddress(), + new NginxPublicIpAddress(), new NginxPublicIpAddress())) + .withPrivateIpAddresses( + Arrays.asList(new NginxPrivateIpAddress(), new NginxPrivateIpAddress(), + new NginxPrivateIpAddress(), new NginxPrivateIpAddress()))) + .withNetworkInterfaceConfiguration( + new NginxNetworkInterfaceConfiguration().withSubnetId("ohxcrsbfova"))) + .withEnableDiagnosticsSupport(true) + .withLogging(new NginxLogging().withStorageAccount( + new NginxStorageAccount().withAccountName("ubcgjbirxb").withContainerName("bsrfbj"))) + .withScalingProperties( + new NginxDeploymentScalingProperties().withCapacity(157171235) + .withProfiles( + Arrays + .asList( + new ScaleProfile().withName("otftpvjzbexilz") + .withCapacity(new ScaleProfileCapacity().withMin(1948356330) + .withMax(1551412306)), + new ScaleProfile() + .withName("qqnvwpmq") + .withCapacity(new ScaleProfileCapacity() + .withMin(1787439694) + .withMax(1628769376))))) + .withAutoUpgradeProfile(new AutoUpgradeProfile().withUpgradeChannel("oujmkcjhwqytj")) + .withUserProfile(new NginxDeploymentUserProfile().withPreferredEmail("n")) + .withNginxAppProtect(new NginxDeploymentPropertiesNginxAppProtect() + .withWebApplicationFirewallSettings(new WebApplicationFirewallSettings() + .withActivationState(ActivationState.DISABLED)))) + .withSku(new ResourceSku().withName("gycdu")), + new NginxDeploymentInner().withLocation("c") + .withTags(mapOf("iiswacffgdkzze", "wdsjnkalju", "pfuflrw", "kfvhqcrailvpn")) + .withIdentity(new IdentityProperties() + .withType(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED) + .withUserAssignedIdentities(mapOf("hhszh", new UserIdentityProperties()))) + .withProperties(new NginxDeploymentProperties() + .withNetworkProfile(new NginxNetworkProfile() + .withFrontEndIpConfiguration(new NginxFrontendIpConfiguration() + .withPublicIpAddresses( + Arrays.asList(new NginxPublicIpAddress(), new NginxPublicIpAddress(), + new NginxPublicIpAddress(), new NginxPublicIpAddress())) + .withPrivateIpAddresses( + Arrays.asList(new NginxPrivateIpAddress(), new NginxPrivateIpAddress(), + new NginxPrivateIpAddress(), new NginxPrivateIpAddress()))) + .withNetworkInterfaceConfiguration( + new NginxNetworkInterfaceConfiguration().withSubnetId("wwtppj"))) + .withEnableDiagnosticsSupport(true) + .withLogging(new NginxLogging().withStorageAccount( + new NginxStorageAccount().withAccountName("kqze").withContainerName("kdltfzxmhhvhg"))) + .withScalingProperties( + new NginxDeploymentScalingProperties().withCapacity(1748485864) + .withProfiles( + Arrays + .asList( + new ScaleProfile().withName("wobdagxtibqdx") + .withCapacity(new ScaleProfileCapacity().withMin(1020209011) + .withMax(709641319)), + new ScaleProfile().withName("akbogqxndlkzgxh") + .withCapacity(new ScaleProfileCapacity().withMin(975056149) + .withMax(1924988063)), + new ScaleProfile().withName("plbpodxun") + .withCapacity(new ScaleProfileCapacity().withMin(1102783029) + .withMax(405149242))))) + .withAutoUpgradeProfile(new AutoUpgradeProfile().withUpgradeChannel("xmubyyntwlrbq")) + .withUserProfile(new NginxDeploymentUserProfile().withPreferredEmail("ievseotgqrllt")) + .withNginxAppProtect(new NginxDeploymentPropertiesNginxAppProtect() + .withWebApplicationFirewallSettings(new WebApplicationFirewallSettings() + .withActivationState(ActivationState.DISABLED)))) + .withSku(new ResourceSku().withName("lvithhqzonosgg")), + new NginxDeploymentInner().withLocation("washr") + .withTags(mapOf("ulpiuj", "kcnqxwbpo", "obyu", "aasipqi")) + .withIdentity(new IdentityProperties().withType(IdentityType.NONE) + .withUserAssignedIdentities(mapOf("dldwmgxc", new UserIdentityProperties()))) + .withProperties(new NginxDeploymentProperties() + .withNetworkProfile(new NginxNetworkProfile() + .withFrontEndIpConfiguration(new NginxFrontendIpConfiguration() + .withPublicIpAddresses(Arrays.asList(new NginxPublicIpAddress(), + new NginxPublicIpAddress(), new NginxPublicIpAddress())) + .withPrivateIpAddresses(Arrays.asList(new NginxPrivateIpAddress(), + new NginxPrivateIpAddress(), new NginxPrivateIpAddress()))) + .withNetworkInterfaceConfiguration( + new NginxNetworkInterfaceConfiguration().withSubnetId("yqsluic"))) + .withEnableDiagnosticsSupport(true) + .withLogging(new NginxLogging().withStorageAccount( + new NginxStorageAccount().withAccountName("uefywsbpfvmwy").withContainerName("fouyf"))) + .withScalingProperties( + new NginxDeploymentScalingProperties().withCapacity(1378791233) + .withProfiles( + Arrays + .asList( + new ScaleProfile().withName("wiyzvqtmnubexkp") + .withCapacity(new ScaleProfileCapacity().withMin(1583015875) + .withMax(1254452597)), + new ScaleProfile().withName("mond") + .withCapacity(new ScaleProfileCapacity().withMin(1929847054) + .withMax(1007666972)), + new ScaleProfile().withName("uxvypomgkopkwh") + .withCapacity(new ScaleProfileCapacity().withMin(664596221) + .withMax(10985850))))) + .withAutoUpgradeProfile(new AutoUpgradeProfile().withUpgradeChannel("ajqgxy")) + .withUserProfile(new NginxDeploymentUserProfile().withPreferredEmail("cmbqfqvmk")) + .withNginxAppProtect( + new NginxDeploymentPropertiesNginxAppProtect().withWebApplicationFirewallSettings( + new WebApplicationFirewallSettings().withActivationState(ActivationState.ENABLED)))) + .withSku(new ResourceSku().withName("iexpbtgiwbwo")), + new NginxDeploymentInner().withLocation("y") + .withTags(mapOf("drd", "rnxxmueed", "alm", "stkwqqtch", "gdv", "mtdaa")) + .withIdentity(new IdentityProperties().withType(IdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED) + .withUserAssignedIdentities(mapOf("aeneqnzarrwl", new UserIdentityProperties(), "iipfpubj", + new UserIdentityProperties(), "ynl", new UserIdentityProperties()))) + .withProperties(new NginxDeploymentProperties() + .withNetworkProfile(new NginxNetworkProfile() + .withFrontEndIpConfiguration(new NginxFrontendIpConfiguration() + .withPublicIpAddresses(Arrays.asList(new NginxPublicIpAddress(), + new NginxPublicIpAddress(), new NginxPublicIpAddress())) + .withPrivateIpAddresses(Arrays.asList(new NginxPrivateIpAddress()))) + .withNetworkInterfaceConfiguration( + new NginxNetworkInterfaceConfiguration().withSubnetId("mslyzrpzbchckqqz"))) + .withEnableDiagnosticsSupport(true) + .withLogging(new NginxLogging() + .withStorageAccount(new NginxStorageAccount().withAccountName("zynkedya") + .withContainerName("wyhqmibzyhwits"))) + .withScalingProperties( + new NginxDeploymentScalingProperties().withCapacity(1679951474) + .withProfiles( + Arrays + .asList( + new ScaleProfile().withName("pcdpumnz") + .withCapacity(new ScaleProfileCapacity().withMin(998287381) + .withMax(944462660)), + new ScaleProfile().withName("z") + .withCapacity(new ScaleProfileCapacity().withMin(1443914942) + .withMax(1417683929)), + new ScaleProfile().withName("biknsorgjhxbld") + .withCapacity(new ScaleProfileCapacity().withMin(1166597262) + .withMax(706339919))))) + .withAutoUpgradeProfile(new AutoUpgradeProfile().withUpgradeChannel("rlkdmtncvokotl")) + .withUserProfile(new NginxDeploymentUserProfile().withPreferredEmail("yhgsy")) + .withNginxAppProtect(new NginxDeploymentPropertiesNginxAppProtect() + .withWebApplicationFirewallSettings(new WebApplicationFirewallSettings() + .withActivationState(ActivationState.DISABLED)))) + .withSku(new ResourceSku().withName("vc")))) + .withNextLink("imfnjhfjx"); model = BinaryData.fromObject(model).toObject(NginxDeploymentListResponse.class); - Assertions.assertEquals("eyp", model.value().get(0).location()); - Assertions.assertEquals("mjmwvvjektcx", model.value().get(0).tags().get("enhwlrs")); - Assertions.assertEquals(IdentityType.NONE, model.value().get(0).identity().type()); - Assertions.assertEquals("gipwhonowkg", model.value().get(0).properties().managedResourceGroup()); - Assertions.assertEquals("bin", + Assertions.assertEquals("r", model.value().get(0).location()); + Assertions.assertEquals("cym", model.value().get(0).tags().get("aolps")); + Assertions.assertEquals(IdentityType.SYSTEM_ASSIGNED, model.value().get(0).identity().type()); + Assertions.assertEquals("ohxcrsbfova", model.value().get(0).properties().networkProfile().networkInterfaceConfiguration().subnetId()); - Assertions.assertEquals(false, model.value().get(0).properties().enableDiagnosticsSupport()); - Assertions.assertEquals("nuzo", model.value().get(0).properties().logging().storageAccount().accountName()); - Assertions.assertEquals("tiyqzrnkcqv", - model.value().get(0).properties().logging().storageAccount().containerName()); - Assertions.assertEquals(798441434, model.value().get(0).properties().scalingProperties().capacity()); - Assertions.assertEquals("lsicohoqqnwv", + Assertions.assertEquals(true, model.value().get(0).properties().enableDiagnosticsSupport()); + Assertions.assertEquals("ubcgjbirxb", + model.value().get(0).properties().logging().storageAccount().accountName()); + Assertions.assertEquals("bsrfbj", model.value().get(0).properties().logging().storageAccount().containerName()); + Assertions.assertEquals(157171235, model.value().get(0).properties().scalingProperties().capacity()); + Assertions.assertEquals("otftpvjzbexilz", model.value().get(0).properties().scalingProperties().profiles().get(0).name()); - Assertions.assertEquals(1444459691, + Assertions.assertEquals(1948356330, model.value().get(0).properties().scalingProperties().profiles().get(0).capacity().min()); - Assertions.assertEquals(759862878, + Assertions.assertEquals(1551412306, model.value().get(0).properties().scalingProperties().profiles().get(0).capacity().max()); - Assertions.assertEquals("yxzk", model.value().get(0).properties().autoUpgradeProfile().upgradeChannel()); - Assertions.assertEquals("cukoklyaxuconu", model.value().get(0).properties().userProfile().preferredEmail()); - Assertions.assertEquals("zf", model.value().get(0).sku().name()); - Assertions.assertEquals("fudwpznt", model.nextLink()); + Assertions.assertEquals("oujmkcjhwqytj", + model.value().get(0).properties().autoUpgradeProfile().upgradeChannel()); + Assertions.assertEquals("n", model.value().get(0).properties().userProfile().preferredEmail()); + Assertions.assertEquals(ActivationState.DISABLED, + model.value().get(0).properties().nginxAppProtect().webApplicationFirewallSettings().activationState()); + Assertions.assertEquals("gycdu", model.value().get(0).sku().name()); + Assertions.assertEquals("imfnjhfjx", model.nextLink()); } // Use "Map.of" if available diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentPropertiesNginxAppProtectTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentPropertiesNginxAppProtectTests.java new file mode 100644 index 000000000000..be1dce89d066 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentPropertiesNginxAppProtectTests.java @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.nginx.models.ActivationState; +import com.azure.resourcemanager.nginx.models.NginxDeploymentPropertiesNginxAppProtect; +import com.azure.resourcemanager.nginx.models.WebApplicationFirewallSettings; +import org.junit.jupiter.api.Assertions; + +public final class NginxDeploymentPropertiesNginxAppProtectTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + NginxDeploymentPropertiesNginxAppProtect model = BinaryData.fromString( + "{\"webApplicationFirewallSettings\":{\"activationState\":\"Enabled\"},\"webApplicationFirewallStatus\":{\"attackSignaturesPackage\":{\"version\":\"pvfadmwsrcr\",\"revisionDatetime\":\"2021-01-28T15:16:12Z\"},\"botSignaturesPackage\":{\"version\":\"pv\",\"revisionDatetime\":\"2021-07-02T00:35:52Z\"},\"threatCampaignsPackage\":{\"version\":\"zlfmisgwbnbbeld\",\"revisionDatetime\":\"2021-03-30T10:55:40Z\"},\"componentVersions\":{\"wafEngineVersion\":\"zbaliourqha\",\"wafNginxVersion\":\"auhashsfwx\"}}}") + .toObject(NginxDeploymentPropertiesNginxAppProtect.class); + Assertions.assertEquals(ActivationState.ENABLED, model.webApplicationFirewallSettings().activationState()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + NginxDeploymentPropertiesNginxAppProtect model + = new NginxDeploymentPropertiesNginxAppProtect().withWebApplicationFirewallSettings( + new WebApplicationFirewallSettings().withActivationState(ActivationState.ENABLED)); + model = BinaryData.fromObject(model).toObject(NginxDeploymentPropertiesNginxAppProtect.class); + Assertions.assertEquals(ActivationState.ENABLED, model.webApplicationFirewallSettings().activationState()); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentPropertiesTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentPropertiesTests.java index b6987bdcab1d..35bf7fc06233 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentPropertiesTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentPropertiesTests.java @@ -5,8 +5,10 @@ package com.azure.resourcemanager.nginx.generated; import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.nginx.models.ActivationState; import com.azure.resourcemanager.nginx.models.AutoUpgradeProfile; import com.azure.resourcemanager.nginx.models.NginxDeploymentProperties; +import com.azure.resourcemanager.nginx.models.NginxDeploymentPropertiesNginxAppProtect; import com.azure.resourcemanager.nginx.models.NginxDeploymentScalingProperties; import com.azure.resourcemanager.nginx.models.NginxDeploymentUserProfile; import com.azure.resourcemanager.nginx.models.NginxFrontendIpConfiguration; @@ -19,6 +21,7 @@ import com.azure.resourcemanager.nginx.models.NginxStorageAccount; import com.azure.resourcemanager.nginx.models.ScaleProfile; import com.azure.resourcemanager.nginx.models.ScaleProfileCapacity; +import com.azure.resourcemanager.nginx.models.WebApplicationFirewallSettings; import java.util.Arrays; import org.junit.jupiter.api.Assertions; @@ -26,80 +29,78 @@ public final class NginxDeploymentPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { NginxDeploymentProperties model = BinaryData.fromString( - "{\"provisioningState\":\"Creating\",\"nginxVersion\":\"jqkwpyeicx\",\"managedResourceGroup\":\"ciwqvhk\",\"networkProfile\":{\"frontEndIPConfiguration\":{\"publicIPAddresses\":[{\"id\":\"dtopbob\"},{\"id\":\"ghmewuam\"},{\"id\":\"hrzayvvtpgvdf\"}],\"privateIPAddresses\":[{\"privateIPAddress\":\"kftutqxlngxlefg\",\"privateIPAllocationMethod\":\"Static\",\"subnetId\":\"krxd\"},{\"privateIPAddress\":\"i\",\"privateIPAllocationMethod\":\"Static\",\"subnetId\":\"zrvqdr\"},{\"privateIPAddress\":\"hjybigehoqfbo\",\"privateIPAllocationMethod\":\"Dynamic\",\"subnetId\":\"nyktzlcuiy\"},{\"privateIPAddress\":\"qyw\",\"privateIPAllocationMethod\":\"Static\",\"subnetId\":\"vynhzgpphrcg\"}]},\"networkInterfaceConfiguration\":{\"subnetId\":\"ocpecfvmmco\"}},\"ipAddress\":\"sxlzevgbmqj\",\"enableDiagnosticsSupport\":false,\"logging\":{\"storageAccount\":{\"accountName\":\"mivkwlzuvcc\",\"containerName\":\"nfnbacfionlebxe\"}},\"scalingProperties\":{\"capacity\":853562932,\"autoScaleSettings\":{\"profiles\":[{\"name\":\"dpnqbq\",\"capacity\":{\"min\":1376492737,\"max\":1208210765}},{\"name\":\"rjfeallnwsubisnj\",\"capacity\":{\"min\":1708150837,\"max\":1066254045}}]}},\"autoUpgradeProfile\":{\"upgradeChannel\":\"ngnzscxaqwoochc\"},\"userProfile\":{\"preferredEmail\":\"qvpkvlrxnjeaseip\"}}") + "{\"provisioningState\":\"Succeeded\",\"nginxVersion\":\"yn\",\"networkProfile\":{\"frontEndIPConfiguration\":{\"publicIPAddresses\":[{\"id\":\"yxczfclh\"},{\"id\":\"xdbabphlwr\"}],\"privateIPAddresses\":[{\"privateIPAddress\":\"tsthsucocm\",\"privateIPAllocationMethod\":\"Dynamic\",\"subnetId\":\"zt\"}]},\"networkInterfaceConfiguration\":{\"subnetId\":\"wwrq\"}},\"ipAddress\":\"edckzywbiexzfey\",\"enableDiagnosticsSupport\":false,\"logging\":{\"storageAccount\":{\"accountName\":\"xujwbhqwalmuzyo\",\"containerName\":\"epdkzja\"}},\"scalingProperties\":{\"capacity\":1987726952,\"autoScaleSettings\":{\"profiles\":[{\"name\":\"d\",\"capacity\":{\"min\":1400002261,\"max\":1879785159}},{\"name\":\"v\",\"capacity\":{\"min\":1605187994,\"max\":1767161087}},{\"name\":\"iwdjswztsdbpgn\",\"capacity\":{\"min\":1127167490,\"max\":862771413}},{\"name\":\"x\",\"capacity\":{\"min\":1275335894,\"max\":999605731}}]}},\"autoUpgradeProfile\":{\"upgradeChannel\":\"bzpfzab\"},\"userProfile\":{\"preferredEmail\":\"uhxwtctyqiklbbov\"},\"nginxAppProtect\":{\"webApplicationFirewallSettings\":{\"activationState\":\"Disabled\"},\"webApplicationFirewallStatus\":{\"attackSignaturesPackage\":{\"version\":\"vgyuguos\",\"revisionDatetime\":\"2021-01-13T18:03:39Z\"},\"botSignaturesPackage\":{\"version\":\"fssxqukkfplg\",\"revisionDatetime\":\"2021-01-07T21:55:14Z\"},\"threatCampaignsPackage\":{\"version\":\"xnkjzkdesl\",\"revisionDatetime\":\"2021-03-03T09:58:01Z\"},\"componentVersions\":{\"wafEngineVersion\":\"opwi\",\"wafNginxVersion\":\"ighxpk\"}}},\"dataplaneApiEndpoint\":\"zb\"}") .toObject(NginxDeploymentProperties.class); - Assertions.assertEquals("ciwqvhk", model.managedResourceGroup()); - Assertions.assertEquals("dtopbob", + Assertions.assertEquals("yxczfclh", model.networkProfile().frontEndIpConfiguration().publicIpAddresses().get(0).id()); - Assertions.assertEquals("kftutqxlngxlefg", + Assertions.assertEquals("tsthsucocm", model.networkProfile().frontEndIpConfiguration().privateIpAddresses().get(0).privateIpAddress()); - Assertions.assertEquals(NginxPrivateIpAllocationMethod.STATIC, + Assertions.assertEquals(NginxPrivateIpAllocationMethod.DYNAMIC, model.networkProfile().frontEndIpConfiguration().privateIpAddresses().get(0).privateIpAllocationMethod()); - Assertions.assertEquals("krxd", + Assertions.assertEquals("zt", model.networkProfile().frontEndIpConfiguration().privateIpAddresses().get(0).subnetId()); - Assertions.assertEquals("ocpecfvmmco", model.networkProfile().networkInterfaceConfiguration().subnetId()); + Assertions.assertEquals("wwrq", model.networkProfile().networkInterfaceConfiguration().subnetId()); Assertions.assertEquals(false, model.enableDiagnosticsSupport()); - Assertions.assertEquals("mivkwlzuvcc", model.logging().storageAccount().accountName()); - Assertions.assertEquals("nfnbacfionlebxe", model.logging().storageAccount().containerName()); - Assertions.assertEquals(853562932, model.scalingProperties().capacity()); - Assertions.assertEquals("dpnqbq", model.scalingProperties().profiles().get(0).name()); - Assertions.assertEquals(1376492737, model.scalingProperties().profiles().get(0).capacity().min()); - Assertions.assertEquals(1208210765, model.scalingProperties().profiles().get(0).capacity().max()); - Assertions.assertEquals("ngnzscxaqwoochc", model.autoUpgradeProfile().upgradeChannel()); - Assertions.assertEquals("qvpkvlrxnjeaseip", model.userProfile().preferredEmail()); + Assertions.assertEquals("xujwbhqwalmuzyo", model.logging().storageAccount().accountName()); + Assertions.assertEquals("epdkzja", model.logging().storageAccount().containerName()); + Assertions.assertEquals(1987726952, model.scalingProperties().capacity()); + Assertions.assertEquals("d", model.scalingProperties().profiles().get(0).name()); + Assertions.assertEquals(1400002261, model.scalingProperties().profiles().get(0).capacity().min()); + Assertions.assertEquals(1879785159, model.scalingProperties().profiles().get(0).capacity().max()); + Assertions.assertEquals("bzpfzab", model.autoUpgradeProfile().upgradeChannel()); + Assertions.assertEquals("uhxwtctyqiklbbov", model.userProfile().preferredEmail()); + Assertions.assertEquals(ActivationState.DISABLED, + model.nginxAppProtect().webApplicationFirewallSettings().activationState()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - NginxDeploymentProperties model = new NginxDeploymentProperties().withManagedResourceGroup("ciwqvhk") - .withNetworkProfile(new NginxNetworkProfile().withFrontEndIpConfiguration(new NginxFrontendIpConfiguration() - .withPublicIpAddresses(Arrays.asList(new NginxPublicIpAddress().withId("dtopbob"), - new NginxPublicIpAddress().withId("ghmewuam"), new NginxPublicIpAddress().withId("hrzayvvtpgvdf"))) - .withPrivateIpAddresses(Arrays.asList( - new NginxPrivateIpAddress().withPrivateIpAddress("kftutqxlngxlefg") - .withPrivateIpAllocationMethod(NginxPrivateIpAllocationMethod.STATIC) - .withSubnetId("krxd"), - new NginxPrivateIpAddress().withPrivateIpAddress("i") - .withPrivateIpAllocationMethod(NginxPrivateIpAllocationMethod.STATIC) - .withSubnetId("zrvqdr"), - new NginxPrivateIpAddress().withPrivateIpAddress("hjybigehoqfbo") + NginxDeploymentProperties model = new NginxDeploymentProperties() + .withNetworkProfile(new NginxNetworkProfile() + .withFrontEndIpConfiguration(new NginxFrontendIpConfiguration() + .withPublicIpAddresses(Arrays.asList(new NginxPublicIpAddress().withId("yxczfclh"), + new NginxPublicIpAddress().withId("xdbabphlwr"))) + .withPrivateIpAddresses(Arrays.asList(new NginxPrivateIpAddress().withPrivateIpAddress("tsthsucocm") .withPrivateIpAllocationMethod(NginxPrivateIpAllocationMethod.DYNAMIC) - .withSubnetId("nyktzlcuiy"), - new NginxPrivateIpAddress().withPrivateIpAddress("qyw") - .withPrivateIpAllocationMethod(NginxPrivateIpAllocationMethod.STATIC) - .withSubnetId("vynhzgpphrcg")))) - .withNetworkInterfaceConfiguration( - new NginxNetworkInterfaceConfiguration().withSubnetId("ocpecfvmmco"))) + .withSubnetId("zt")))) + .withNetworkInterfaceConfiguration(new NginxNetworkInterfaceConfiguration().withSubnetId("wwrq"))) .withEnableDiagnosticsSupport(false) .withLogging(new NginxLogging().withStorageAccount( - new NginxStorageAccount().withAccountName("mivkwlzuvcc").withContainerName("nfnbacfionlebxe"))) - .withScalingProperties(new NginxDeploymentScalingProperties().withCapacity(853562932) + new NginxStorageAccount().withAccountName("xujwbhqwalmuzyo").withContainerName("epdkzja"))) + .withScalingProperties(new NginxDeploymentScalingProperties().withCapacity(1987726952) .withProfiles(Arrays.asList( - new ScaleProfile().withName("dpnqbq") - .withCapacity(new ScaleProfileCapacity().withMin(1376492737).withMax(1208210765)), - new ScaleProfile().withName("rjfeallnwsubisnj") - .withCapacity(new ScaleProfileCapacity().withMin(1708150837).withMax(1066254045))))) - .withAutoUpgradeProfile(new AutoUpgradeProfile().withUpgradeChannel("ngnzscxaqwoochc")) - .withUserProfile(new NginxDeploymentUserProfile().withPreferredEmail("qvpkvlrxnjeaseip")); + new ScaleProfile().withName("d") + .withCapacity(new ScaleProfileCapacity().withMin(1400002261).withMax(1879785159)), + new ScaleProfile().withName("v") + .withCapacity(new ScaleProfileCapacity().withMin(1605187994).withMax(1767161087)), + new ScaleProfile().withName("iwdjswztsdbpgn") + .withCapacity(new ScaleProfileCapacity().withMin(1127167490).withMax(862771413)), + new ScaleProfile().withName("x") + .withCapacity(new ScaleProfileCapacity().withMin(1275335894).withMax(999605731))))) + .withAutoUpgradeProfile(new AutoUpgradeProfile().withUpgradeChannel("bzpfzab")) + .withUserProfile(new NginxDeploymentUserProfile().withPreferredEmail("uhxwtctyqiklbbov")) + .withNginxAppProtect(new NginxDeploymentPropertiesNginxAppProtect().withWebApplicationFirewallSettings( + new WebApplicationFirewallSettings().withActivationState(ActivationState.DISABLED))); model = BinaryData.fromObject(model).toObject(NginxDeploymentProperties.class); - Assertions.assertEquals("ciwqvhk", model.managedResourceGroup()); - Assertions.assertEquals("dtopbob", + Assertions.assertEquals("yxczfclh", model.networkProfile().frontEndIpConfiguration().publicIpAddresses().get(0).id()); - Assertions.assertEquals("kftutqxlngxlefg", + Assertions.assertEquals("tsthsucocm", model.networkProfile().frontEndIpConfiguration().privateIpAddresses().get(0).privateIpAddress()); - Assertions.assertEquals(NginxPrivateIpAllocationMethod.STATIC, + Assertions.assertEquals(NginxPrivateIpAllocationMethod.DYNAMIC, model.networkProfile().frontEndIpConfiguration().privateIpAddresses().get(0).privateIpAllocationMethod()); - Assertions.assertEquals("krxd", + Assertions.assertEquals("zt", model.networkProfile().frontEndIpConfiguration().privateIpAddresses().get(0).subnetId()); - Assertions.assertEquals("ocpecfvmmco", model.networkProfile().networkInterfaceConfiguration().subnetId()); + Assertions.assertEquals("wwrq", model.networkProfile().networkInterfaceConfiguration().subnetId()); Assertions.assertEquals(false, model.enableDiagnosticsSupport()); - Assertions.assertEquals("mivkwlzuvcc", model.logging().storageAccount().accountName()); - Assertions.assertEquals("nfnbacfionlebxe", model.logging().storageAccount().containerName()); - Assertions.assertEquals(853562932, model.scalingProperties().capacity()); - Assertions.assertEquals("dpnqbq", model.scalingProperties().profiles().get(0).name()); - Assertions.assertEquals(1376492737, model.scalingProperties().profiles().get(0).capacity().min()); - Assertions.assertEquals(1208210765, model.scalingProperties().profiles().get(0).capacity().max()); - Assertions.assertEquals("ngnzscxaqwoochc", model.autoUpgradeProfile().upgradeChannel()); - Assertions.assertEquals("qvpkvlrxnjeaseip", model.userProfile().preferredEmail()); + Assertions.assertEquals("xujwbhqwalmuzyo", model.logging().storageAccount().accountName()); + Assertions.assertEquals("epdkzja", model.logging().storageAccount().containerName()); + Assertions.assertEquals(1987726952, model.scalingProperties().capacity()); + Assertions.assertEquals("d", model.scalingProperties().profiles().get(0).name()); + Assertions.assertEquals(1400002261, model.scalingProperties().profiles().get(0).capacity().min()); + Assertions.assertEquals(1879785159, model.scalingProperties().profiles().get(0).capacity().max()); + Assertions.assertEquals("bzpfzab", model.autoUpgradeProfile().upgradeChannel()); + Assertions.assertEquals("uhxwtctyqiklbbov", model.userProfile().preferredEmail()); + Assertions.assertEquals(ActivationState.DISABLED, + model.nginxAppProtect().webApplicationFirewallSettings().activationState()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentScalingPropertiesAutoScaleSettingsTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentScalingPropertiesAutoScaleSettingsTests.java index af9b15811e2a..6977563c3868 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentScalingPropertiesAutoScaleSettingsTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentScalingPropertiesAutoScaleSettingsTests.java @@ -15,24 +15,24 @@ public final class NginxDeploymentScalingPropertiesAutoScaleSettingsTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { NginxDeploymentScalingPropertiesAutoScaleSettings model = BinaryData.fromString( - "{\"profiles\":[{\"name\":\"opjmcmatuokthfui\",\"capacity\":{\"min\":94424945,\"max\":1958511129}},{\"name\":\"dsfcpkvxodpuoz\",\"capacity\":{\"min\":1621494681,\"max\":2044584540}}]}") + "{\"profiles\":[{\"name\":\"mehhseyvjusrtsl\",\"capacity\":{\"min\":1593935423,\"max\":1948338560}},{\"name\":\"kdeemaofmxagkvtm\",\"capacity\":{\"min\":696697077,\"max\":2048736715}}]}") .toObject(NginxDeploymentScalingPropertiesAutoScaleSettings.class); - Assertions.assertEquals("opjmcmatuokthfui", model.profiles().get(0).name()); - Assertions.assertEquals(94424945, model.profiles().get(0).capacity().min()); - Assertions.assertEquals(1958511129, model.profiles().get(0).capacity().max()); + Assertions.assertEquals("mehhseyvjusrtsl", model.profiles().get(0).name()); + Assertions.assertEquals(1593935423, model.profiles().get(0).capacity().min()); + Assertions.assertEquals(1948338560, model.profiles().get(0).capacity().max()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { NginxDeploymentScalingPropertiesAutoScaleSettings model = new NginxDeploymentScalingPropertiesAutoScaleSettings().withProfiles(Arrays.asList( - new ScaleProfile().withName("opjmcmatuokthfui") - .withCapacity(new ScaleProfileCapacity().withMin(94424945).withMax(1958511129)), - new ScaleProfile().withName("dsfcpkvxodpuoz") - .withCapacity(new ScaleProfileCapacity().withMin(1621494681).withMax(2044584540)))); + new ScaleProfile().withName("mehhseyvjusrtsl") + .withCapacity(new ScaleProfileCapacity().withMin(1593935423).withMax(1948338560)), + new ScaleProfile().withName("kdeemaofmxagkvtm") + .withCapacity(new ScaleProfileCapacity().withMin(696697077).withMax(2048736715)))); model = BinaryData.fromObject(model).toObject(NginxDeploymentScalingPropertiesAutoScaleSettings.class); - Assertions.assertEquals("opjmcmatuokthfui", model.profiles().get(0).name()); - Assertions.assertEquals(94424945, model.profiles().get(0).capacity().min()); - Assertions.assertEquals(1958511129, model.profiles().get(0).capacity().max()); + Assertions.assertEquals("mehhseyvjusrtsl", model.profiles().get(0).name()); + Assertions.assertEquals(1593935423, model.profiles().get(0).capacity().min()); + Assertions.assertEquals(1948338560, model.profiles().get(0).capacity().max()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentScalingPropertiesTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentScalingPropertiesTests.java index 133567f300db..789b48564943 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentScalingPropertiesTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentScalingPropertiesTests.java @@ -15,30 +15,30 @@ public final class NginxDeploymentScalingPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { NginxDeploymentScalingProperties model = BinaryData.fromString( - "{\"capacity\":1493374876,\"autoScaleSettings\":{\"profiles\":[{\"name\":\"pngjcrcczsqpjhvm\",\"capacity\":{\"min\":747144042,\"max\":330627677}},{\"name\":\"v\",\"capacity\":{\"min\":1022740915,\"max\":1223642392}},{\"name\":\"ounqecano\",\"capacity\":{\"min\":1054713689,\"max\":996084293}},{\"name\":\"pfhyhl\",\"capacity\":{\"min\":2062075015,\"max\":1743077422}}]}}") + "{\"capacity\":1613065996,\"autoScaleSettings\":{\"profiles\":[{\"name\":\"oyrxvwfudwpzntxh\",\"capacity\":{\"min\":1710146471,\"max\":328563559}},{\"name\":\"lrqjbhckfr\",\"capacity\":{\"min\":1523615779,\"max\":2044526914}},{\"name\":\"xsbkyvpyca\",\"capacity\":{\"min\":427278595,\"max\":106855620}},{\"name\":\"bpzkafkuwbc\",\"capacity\":{\"min\":1514524475,\"max\":946722582}}]}}") .toObject(NginxDeploymentScalingProperties.class); - Assertions.assertEquals(1493374876, model.capacity()); - Assertions.assertEquals("pngjcrcczsqpjhvm", model.profiles().get(0).name()); - Assertions.assertEquals(747144042, model.profiles().get(0).capacity().min()); - Assertions.assertEquals(330627677, model.profiles().get(0).capacity().max()); + Assertions.assertEquals(1613065996, model.capacity()); + Assertions.assertEquals("oyrxvwfudwpzntxh", model.profiles().get(0).name()); + Assertions.assertEquals(1710146471, model.profiles().get(0).capacity().min()); + Assertions.assertEquals(328563559, model.profiles().get(0).capacity().max()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - NginxDeploymentScalingProperties model = new NginxDeploymentScalingProperties().withCapacity(1493374876) + NginxDeploymentScalingProperties model = new NginxDeploymentScalingProperties().withCapacity(1613065996) .withProfiles(Arrays.asList( - new ScaleProfile().withName("pngjcrcczsqpjhvm") - .withCapacity(new ScaleProfileCapacity().withMin(747144042).withMax(330627677)), - new ScaleProfile().withName("v") - .withCapacity(new ScaleProfileCapacity().withMin(1022740915).withMax(1223642392)), - new ScaleProfile().withName("ounqecano") - .withCapacity(new ScaleProfileCapacity().withMin(1054713689).withMax(996084293)), - new ScaleProfile().withName("pfhyhl") - .withCapacity(new ScaleProfileCapacity().withMin(2062075015).withMax(1743077422)))); + new ScaleProfile().withName("oyrxvwfudwpzntxh") + .withCapacity(new ScaleProfileCapacity().withMin(1710146471).withMax(328563559)), + new ScaleProfile().withName("lrqjbhckfr") + .withCapacity(new ScaleProfileCapacity().withMin(1523615779).withMax(2044526914)), + new ScaleProfile().withName("xsbkyvpyca") + .withCapacity(new ScaleProfileCapacity().withMin(427278595).withMax(106855620)), + new ScaleProfile().withName("bpzkafkuwbc") + .withCapacity(new ScaleProfileCapacity().withMin(1514524475).withMax(946722582)))); model = BinaryData.fromObject(model).toObject(NginxDeploymentScalingProperties.class); - Assertions.assertEquals(1493374876, model.capacity()); - Assertions.assertEquals("pngjcrcczsqpjhvm", model.profiles().get(0).name()); - Assertions.assertEquals(747144042, model.profiles().get(0).capacity().min()); - Assertions.assertEquals(330627677, model.profiles().get(0).capacity().max()); + Assertions.assertEquals(1613065996, model.capacity()); + Assertions.assertEquals("oyrxvwfudwpzntxh", model.profiles().get(0).name()); + Assertions.assertEquals(1710146471, model.profiles().get(0).capacity().min()); + Assertions.assertEquals(328563559, model.profiles().get(0).capacity().max()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentUpdateParametersTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentUpdateParametersTests.java index 3cc7405acfe1..b673488d24cd 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentUpdateParametersTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentUpdateParametersTests.java @@ -5,19 +5,28 @@ package com.azure.resourcemanager.nginx.generated; import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.nginx.models.ActivationState; import com.azure.resourcemanager.nginx.models.AutoUpgradeProfile; import com.azure.resourcemanager.nginx.models.IdentityProperties; import com.azure.resourcemanager.nginx.models.IdentityType; import com.azure.resourcemanager.nginx.models.NginxDeploymentScalingProperties; import com.azure.resourcemanager.nginx.models.NginxDeploymentUpdateParameters; import com.azure.resourcemanager.nginx.models.NginxDeploymentUpdateProperties; +import com.azure.resourcemanager.nginx.models.NginxDeploymentUpdatePropertiesNginxAppProtect; import com.azure.resourcemanager.nginx.models.NginxDeploymentUserProfile; +import com.azure.resourcemanager.nginx.models.NginxFrontendIpConfiguration; import com.azure.resourcemanager.nginx.models.NginxLogging; +import com.azure.resourcemanager.nginx.models.NginxNetworkInterfaceConfiguration; +import com.azure.resourcemanager.nginx.models.NginxNetworkProfile; +import com.azure.resourcemanager.nginx.models.NginxPrivateIpAddress; +import com.azure.resourcemanager.nginx.models.NginxPrivateIpAllocationMethod; +import com.azure.resourcemanager.nginx.models.NginxPublicIpAddress; import com.azure.resourcemanager.nginx.models.NginxStorageAccount; import com.azure.resourcemanager.nginx.models.ResourceSku; import com.azure.resourcemanager.nginx.models.ScaleProfile; import com.azure.resourcemanager.nginx.models.ScaleProfileCapacity; import com.azure.resourcemanager.nginx.models.UserIdentityProperties; +import com.azure.resourcemanager.nginx.models.WebApplicationFirewallSettings; import java.util.Arrays; import java.util.HashMap; import java.util.Map; @@ -27,60 +36,128 @@ public final class NginxDeploymentUpdateParametersTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { NginxDeploymentUpdateParameters model = BinaryData.fromString( - "{\"identity\":{\"principalId\":\"ocfs\",\"tenantId\":\"s\",\"type\":\"None\",\"userAssignedIdentities\":{\"oczvy\":{\"principalId\":\"tki\",\"clientId\":\"xhqyudxorrqnb\"}}},\"tags\":{\"vdfwatkpn\":\"rvkdvjsllrm\",\"wiqzbqjvsovmyo\":\"ulexxbczwtr\"},\"sku\":{\"name\":\"cspkwlhzdobpxjmf\"},\"location\":\"vvnchrkcc\",\"properties\":{\"enableDiagnosticsSupport\":true,\"logging\":{\"storageAccount\":{\"accountName\":\"khrs\",\"containerName\":\"iwkuofos\"}},\"scalingProperties\":{\"capacity\":1623882899,\"autoScaleSettings\":{\"profiles\":[{\"name\":\"uimjmvx\",\"capacity\":{\"min\":1584034364,\"max\":192455104}},{\"name\":\"uugidyjrrfby\",\"capacity\":{\"min\":1774598517,\"max\":1874197992}},{\"name\":\"v\",\"capacity\":{\"min\":499062312,\"max\":766224962}},{\"name\":\"sonpclhocohs\",\"capacity\":{\"min\":1118484246,\"max\":442163665}}]}},\"userProfile\":{\"preferredEmail\":\"eggzfb\"},\"autoUpgradeProfile\":{\"upgradeChannel\":\"fmvfaxkffeiit\"}}}") + "{\"identity\":{\"principalId\":\"btdhxujznbm\",\"tenantId\":\"wuwprzqlv\",\"type\":\"UserAssigned\",\"userAssignedIdentities\":{\"iplrbpbewtghfgb\":{\"principalId\":\"j\",\"clientId\":\"hfxobbcswsrtj\"}}},\"tags\":{\"gibtnm\":\"wxzvlvqhjkb\"},\"sku\":{\"name\":\"ebwwaloayqc\"},\"location\":\"rtzju\",\"properties\":{\"enableDiagnosticsSupport\":false,\"logging\":{\"storageAccount\":{\"accountName\":\"txon\",\"containerName\":\"ts\"}},\"scalingProperties\":{\"capacity\":1151721891,\"autoScaleSettings\":{\"profiles\":[{\"name\":\"wxqpsrknftguvri\",\"capacity\":{\"min\":2067966148,\"max\":346256186}},{\"name\":\"rwmdyvxqtay\",\"capacity\":{\"min\":1285325454,\"max\":357638492}}]}},\"userProfile\":{\"preferredEmail\":\"oyq\"},\"networkProfile\":{\"frontEndIPConfiguration\":{\"publicIPAddresses\":[{\"id\":\"qibycnojvknm\"},{\"id\":\"qsgzvahapj\"},{\"id\":\"hpvgqz\"}],\"privateIPAddresses\":[{\"privateIPAddress\":\"xdjzlmwlxk\",\"privateIPAllocationMethod\":\"Dynamic\",\"subnetId\":\"hzovawjvzunlut\"},{\"privateIPAddress\":\"n\",\"privateIPAllocationMethod\":\"Static\",\"subnetId\":\"i\"},{\"privateIPAddress\":\"ilpjzuaejxdult\",\"privateIPAllocationMethod\":\"Dynamic\",\"subnetId\":\"btdzumveekg\"}]},\"networkInterfaceConfiguration\":{\"subnetId\":\"zuhkfpbsjyof\"}},\"autoUpgradeProfile\":{\"upgradeChannel\":\"luu\"},\"nginxAppProtect\":{\"webApplicationFirewallSettings\":{\"activationState\":\"Disabled\"}}}}") .toObject(NginxDeploymentUpdateParameters.class); - Assertions.assertEquals(IdentityType.NONE, model.identity().type()); - Assertions.assertEquals("rvkdvjsllrm", model.tags().get("vdfwatkpn")); - Assertions.assertEquals("cspkwlhzdobpxjmf", model.sku().name()); - Assertions.assertEquals("vvnchrkcc", model.location()); - Assertions.assertEquals(true, model.properties().enableDiagnosticsSupport()); - Assertions.assertEquals("khrs", model.properties().logging().storageAccount().accountName()); - Assertions.assertEquals("iwkuofos", model.properties().logging().storageAccount().containerName()); - Assertions.assertEquals(1623882899, model.properties().scalingProperties().capacity()); - Assertions.assertEquals("uimjmvx", model.properties().scalingProperties().profiles().get(0).name()); - Assertions.assertEquals(1584034364, model.properties().scalingProperties().profiles().get(0).capacity().min()); - Assertions.assertEquals(192455104, model.properties().scalingProperties().profiles().get(0).capacity().max()); - Assertions.assertEquals("eggzfb", model.properties().userProfile().preferredEmail()); - Assertions.assertEquals("fmvfaxkffeiit", model.properties().autoUpgradeProfile().upgradeChannel()); + Assertions.assertEquals(IdentityType.USER_ASSIGNED, model.identity().type()); + Assertions.assertEquals("wxzvlvqhjkb", model.tags().get("gibtnm")); + Assertions.assertEquals("ebwwaloayqc", model.sku().name()); + Assertions.assertEquals("rtzju", model.location()); + Assertions.assertEquals(false, model.properties().enableDiagnosticsSupport()); + Assertions.assertEquals("txon", model.properties().logging().storageAccount().accountName()); + Assertions.assertEquals("ts", model.properties().logging().storageAccount().containerName()); + Assertions.assertEquals(1151721891, model.properties().scalingProperties().capacity()); + Assertions.assertEquals("wxqpsrknftguvri", model.properties().scalingProperties().profiles().get(0).name()); + Assertions.assertEquals(2067966148, model.properties().scalingProperties().profiles().get(0).capacity().min()); + Assertions.assertEquals(346256186, model.properties().scalingProperties().profiles().get(0).capacity().max()); + Assertions.assertEquals("oyq", model.properties().userProfile().preferredEmail()); + Assertions.assertEquals("qibycnojvknm", + model.properties().networkProfile().frontEndIpConfiguration().publicIpAddresses().get(0).id()); + Assertions.assertEquals("xdjzlmwlxk", + model.properties() + .networkProfile() + .frontEndIpConfiguration() + .privateIpAddresses() + .get(0) + .privateIpAddress()); + Assertions.assertEquals(NginxPrivateIpAllocationMethod.DYNAMIC, + model.properties() + .networkProfile() + .frontEndIpConfiguration() + .privateIpAddresses() + .get(0) + .privateIpAllocationMethod()); + Assertions.assertEquals("hzovawjvzunlut", + model.properties().networkProfile().frontEndIpConfiguration().privateIpAddresses().get(0).subnetId()); + Assertions.assertEquals("zuhkfpbsjyof", + model.properties().networkProfile().networkInterfaceConfiguration().subnetId()); + Assertions.assertEquals("luu", model.properties().autoUpgradeProfile().upgradeChannel()); + Assertions.assertEquals(ActivationState.DISABLED, + model.properties().nginxAppProtect().webApplicationFirewallSettings().activationState()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - NginxDeploymentUpdateParameters model = new NginxDeploymentUpdateParameters() - .withIdentity(new IdentityProperties().withType(IdentityType.NONE) - .withUserAssignedIdentities(mapOf("oczvy", new UserIdentityProperties()))) - .withTags(mapOf("vdfwatkpn", "rvkdvjsllrm", "wiqzbqjvsovmyo", "ulexxbczwtr")) - .withSku(new ResourceSku().withName("cspkwlhzdobpxjmf")) - .withLocation("vvnchrkcc") - .withProperties(new NginxDeploymentUpdateProperties().withEnableDiagnosticsSupport(true) - .withLogging(new NginxLogging().withStorageAccount( - new NginxStorageAccount().withAccountName("khrs").withContainerName("iwkuofos"))) - .withScalingProperties(new NginxDeploymentScalingProperties().withCapacity(1623882899) - .withProfiles(Arrays.asList( - new ScaleProfile().withName("uimjmvx") - .withCapacity(new ScaleProfileCapacity().withMin(1584034364).withMax(192455104)), - new ScaleProfile().withName("uugidyjrrfby") - .withCapacity(new ScaleProfileCapacity().withMin(1774598517).withMax(1874197992)), - new ScaleProfile().withName("v") - .withCapacity(new ScaleProfileCapacity().withMin(499062312).withMax(766224962)), - new ScaleProfile().withName("sonpclhocohs") - .withCapacity(new ScaleProfileCapacity().withMin(1118484246).withMax(442163665))))) - .withUserProfile(new NginxDeploymentUserProfile().withPreferredEmail("eggzfb")) - .withAutoUpgradeProfile(new AutoUpgradeProfile().withUpgradeChannel("fmvfaxkffeiit"))); + NginxDeploymentUpdateParameters model + = new NginxDeploymentUpdateParameters() + .withIdentity(new IdentityProperties().withType(IdentityType.USER_ASSIGNED) + .withUserAssignedIdentities(mapOf("iplrbpbewtghfgb", new UserIdentityProperties()))) + .withTags(mapOf("gibtnm", "wxzvlvqhjkb")) + .withSku(new ResourceSku().withName("ebwwaloayqc")) + .withLocation("rtzju") + .withProperties( + new NginxDeploymentUpdateProperties().withEnableDiagnosticsSupport(false) + .withLogging(new NginxLogging().withStorageAccount( + new NginxStorageAccount().withAccountName("txon").withContainerName("ts"))) + .withScalingProperties(new NginxDeploymentScalingProperties().withCapacity(1151721891) + .withProfiles(Arrays.asList(new ScaleProfile().withName("wxqpsrknftguvri") + .withCapacity(new ScaleProfileCapacity().withMin(2067966148).withMax(346256186)), + new ScaleProfile().withName("rwmdyvxqtay") + .withCapacity(new ScaleProfileCapacity().withMin(1285325454).withMax(357638492))))) + .withUserProfile(new NginxDeploymentUserProfile().withPreferredEmail("oyq")) + .withNetworkProfile( + new NginxNetworkProfile() + .withFrontEndIpConfiguration( + new NginxFrontendIpConfiguration() + .withPublicIpAddresses( + Arrays.asList(new NginxPublicIpAddress().withId("qibycnojvknm"), + new NginxPublicIpAddress().withId("qsgzvahapj"), + new NginxPublicIpAddress().withId("hpvgqz"))) + .withPrivateIpAddresses( + Arrays.asList( + new NginxPrivateIpAddress().withPrivateIpAddress("xdjzlmwlxk") + .withPrivateIpAllocationMethod( + NginxPrivateIpAllocationMethod.DYNAMIC) + .withSubnetId("hzovawjvzunlut"), + new NginxPrivateIpAddress().withPrivateIpAddress("n") + .withPrivateIpAllocationMethod( + NginxPrivateIpAllocationMethod.STATIC) + .withSubnetId("i"), + new NginxPrivateIpAddress().withPrivateIpAddress("ilpjzuaejxdult") + .withPrivateIpAllocationMethod( + NginxPrivateIpAllocationMethod.DYNAMIC) + .withSubnetId("btdzumveekg")))) + .withNetworkInterfaceConfiguration( + new NginxNetworkInterfaceConfiguration().withSubnetId("zuhkfpbsjyof"))) + .withAutoUpgradeProfile(new AutoUpgradeProfile().withUpgradeChannel("luu")) + .withNginxAppProtect( + new NginxDeploymentUpdatePropertiesNginxAppProtect().withWebApplicationFirewallSettings( + new WebApplicationFirewallSettings().withActivationState(ActivationState.DISABLED)))); model = BinaryData.fromObject(model).toObject(NginxDeploymentUpdateParameters.class); - Assertions.assertEquals(IdentityType.NONE, model.identity().type()); - Assertions.assertEquals("rvkdvjsllrm", model.tags().get("vdfwatkpn")); - Assertions.assertEquals("cspkwlhzdobpxjmf", model.sku().name()); - Assertions.assertEquals("vvnchrkcc", model.location()); - Assertions.assertEquals(true, model.properties().enableDiagnosticsSupport()); - Assertions.assertEquals("khrs", model.properties().logging().storageAccount().accountName()); - Assertions.assertEquals("iwkuofos", model.properties().logging().storageAccount().containerName()); - Assertions.assertEquals(1623882899, model.properties().scalingProperties().capacity()); - Assertions.assertEquals("uimjmvx", model.properties().scalingProperties().profiles().get(0).name()); - Assertions.assertEquals(1584034364, model.properties().scalingProperties().profiles().get(0).capacity().min()); - Assertions.assertEquals(192455104, model.properties().scalingProperties().profiles().get(0).capacity().max()); - Assertions.assertEquals("eggzfb", model.properties().userProfile().preferredEmail()); - Assertions.assertEquals("fmvfaxkffeiit", model.properties().autoUpgradeProfile().upgradeChannel()); + Assertions.assertEquals(IdentityType.USER_ASSIGNED, model.identity().type()); + Assertions.assertEquals("wxzvlvqhjkb", model.tags().get("gibtnm")); + Assertions.assertEquals("ebwwaloayqc", model.sku().name()); + Assertions.assertEquals("rtzju", model.location()); + Assertions.assertEquals(false, model.properties().enableDiagnosticsSupport()); + Assertions.assertEquals("txon", model.properties().logging().storageAccount().accountName()); + Assertions.assertEquals("ts", model.properties().logging().storageAccount().containerName()); + Assertions.assertEquals(1151721891, model.properties().scalingProperties().capacity()); + Assertions.assertEquals("wxqpsrknftguvri", model.properties().scalingProperties().profiles().get(0).name()); + Assertions.assertEquals(2067966148, model.properties().scalingProperties().profiles().get(0).capacity().min()); + Assertions.assertEquals(346256186, model.properties().scalingProperties().profiles().get(0).capacity().max()); + Assertions.assertEquals("oyq", model.properties().userProfile().preferredEmail()); + Assertions.assertEquals("qibycnojvknm", + model.properties().networkProfile().frontEndIpConfiguration().publicIpAddresses().get(0).id()); + Assertions.assertEquals("xdjzlmwlxk", + model.properties() + .networkProfile() + .frontEndIpConfiguration() + .privateIpAddresses() + .get(0) + .privateIpAddress()); + Assertions.assertEquals(NginxPrivateIpAllocationMethod.DYNAMIC, + model.properties() + .networkProfile() + .frontEndIpConfiguration() + .privateIpAddresses() + .get(0) + .privateIpAllocationMethod()); + Assertions.assertEquals("hzovawjvzunlut", + model.properties().networkProfile().frontEndIpConfiguration().privateIpAddresses().get(0).subnetId()); + Assertions.assertEquals("zuhkfpbsjyof", + model.properties().networkProfile().networkInterfaceConfiguration().subnetId()); + Assertions.assertEquals("luu", model.properties().autoUpgradeProfile().upgradeChannel()); + Assertions.assertEquals(ActivationState.DISABLED, + model.properties().nginxAppProtect().webApplicationFirewallSettings().activationState()); } // Use "Map.of" if available diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentUpdatePropertiesNginxAppProtectTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentUpdatePropertiesNginxAppProtectTests.java new file mode 100644 index 000000000000..6455f03af4ab --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentUpdatePropertiesNginxAppProtectTests.java @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.nginx.models.ActivationState; +import com.azure.resourcemanager.nginx.models.NginxDeploymentUpdatePropertiesNginxAppProtect; +import com.azure.resourcemanager.nginx.models.WebApplicationFirewallSettings; +import org.junit.jupiter.api.Assertions; + +public final class NginxDeploymentUpdatePropertiesNginxAppProtectTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + NginxDeploymentUpdatePropertiesNginxAppProtect model + = BinaryData.fromString("{\"webApplicationFirewallSettings\":{\"activationState\":\"Enabled\"}}") + .toObject(NginxDeploymentUpdatePropertiesNginxAppProtect.class); + Assertions.assertEquals(ActivationState.ENABLED, model.webApplicationFirewallSettings().activationState()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + NginxDeploymentUpdatePropertiesNginxAppProtect model + = new NginxDeploymentUpdatePropertiesNginxAppProtect().withWebApplicationFirewallSettings( + new WebApplicationFirewallSettings().withActivationState(ActivationState.ENABLED)); + model = BinaryData.fromObject(model).toObject(NginxDeploymentUpdatePropertiesNginxAppProtect.class); + Assertions.assertEquals(ActivationState.ENABLED, model.webApplicationFirewallSettings().activationState()); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentUpdatePropertiesTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentUpdatePropertiesTests.java index 45a72f89a8fa..bf7f3522b999 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentUpdatePropertiesTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentUpdatePropertiesTests.java @@ -5,14 +5,23 @@ package com.azure.resourcemanager.nginx.generated; import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.nginx.models.ActivationState; import com.azure.resourcemanager.nginx.models.AutoUpgradeProfile; import com.azure.resourcemanager.nginx.models.NginxDeploymentScalingProperties; import com.azure.resourcemanager.nginx.models.NginxDeploymentUpdateProperties; +import com.azure.resourcemanager.nginx.models.NginxDeploymentUpdatePropertiesNginxAppProtect; import com.azure.resourcemanager.nginx.models.NginxDeploymentUserProfile; +import com.azure.resourcemanager.nginx.models.NginxFrontendIpConfiguration; import com.azure.resourcemanager.nginx.models.NginxLogging; +import com.azure.resourcemanager.nginx.models.NginxNetworkInterfaceConfiguration; +import com.azure.resourcemanager.nginx.models.NginxNetworkProfile; +import com.azure.resourcemanager.nginx.models.NginxPrivateIpAddress; +import com.azure.resourcemanager.nginx.models.NginxPrivateIpAllocationMethod; +import com.azure.resourcemanager.nginx.models.NginxPublicIpAddress; import com.azure.resourcemanager.nginx.models.NginxStorageAccount; import com.azure.resourcemanager.nginx.models.ScaleProfile; import com.azure.resourcemanager.nginx.models.ScaleProfileCapacity; +import com.azure.resourcemanager.nginx.models.WebApplicationFirewallSettings; import java.util.Arrays; import org.junit.jupiter.api.Assertions; @@ -20,17 +29,28 @@ public final class NginxDeploymentUpdatePropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { NginxDeploymentUpdateProperties model = BinaryData.fromString( - "{\"enableDiagnosticsSupport\":false,\"logging\":{\"storageAccount\":{\"accountName\":\"yvshxmz\",\"containerName\":\"bzoggigrx\"}},\"scalingProperties\":{\"capacity\":849896725,\"autoScaleSettings\":{\"profiles\":[{\"name\":\"xxjnspydptk\",\"capacity\":{\"min\":668833312,\"max\":1482419493}}]}},\"userProfile\":{\"preferredEmail\":\"uknvudwti\"},\"autoUpgradeProfile\":{\"upgradeChannel\":\"bldngkpoc\"}}") + "{\"enableDiagnosticsSupport\":false,\"logging\":{\"storageAccount\":{\"accountName\":\"ekqvkeln\",\"containerName\":\"vbxwyjsflhh\"}},\"scalingProperties\":{\"capacity\":290339428,\"autoScaleSettings\":{\"profiles\":[{\"name\":\"ixisxyawjoy\",\"capacity\":{\"min\":628335164,\"max\":1772436776}},{\"name\":\"slyjpkiid\",\"capacity\":{\"min\":983085062,\"max\":787836165}},{\"name\":\"xznelixhnrztf\",\"capacity\":{\"min\":1975568377,\"max\":434458515}},{\"name\":\"bnxknalaulppg\",\"capacity\":{\"min\":1784168921,\"max\":1987785731}}]}},\"userProfile\":{\"preferredEmail\":\"apnyiropuhpig\"},\"networkProfile\":{\"frontEndIPConfiguration\":{\"publicIPAddresses\":[{\"id\":\"qgitxmed\"}],\"privateIPAddresses\":[{\"privateIPAddress\":\"lynqwwncwzzh\",\"privateIPAllocationMethod\":\"Dynamic\",\"subnetId\":\"rmgucnap\"}]},\"networkInterfaceConfiguration\":{\"subnetId\":\"oellwp\"}},\"autoUpgradeProfile\":{\"upgradeChannel\":\"d\"},\"nginxAppProtect\":{\"webApplicationFirewallSettings\":{\"activationState\":\"Disabled\"}}}") .toObject(NginxDeploymentUpdateProperties.class); Assertions.assertEquals(false, model.enableDiagnosticsSupport()); - Assertions.assertEquals("yvshxmz", model.logging().storageAccount().accountName()); - Assertions.assertEquals("bzoggigrx", model.logging().storageAccount().containerName()); - Assertions.assertEquals(849896725, model.scalingProperties().capacity()); - Assertions.assertEquals("xxjnspydptk", model.scalingProperties().profiles().get(0).name()); - Assertions.assertEquals(668833312, model.scalingProperties().profiles().get(0).capacity().min()); - Assertions.assertEquals(1482419493, model.scalingProperties().profiles().get(0).capacity().max()); - Assertions.assertEquals("uknvudwti", model.userProfile().preferredEmail()); - Assertions.assertEquals("bldngkpoc", model.autoUpgradeProfile().upgradeChannel()); + Assertions.assertEquals("ekqvkeln", model.logging().storageAccount().accountName()); + Assertions.assertEquals("vbxwyjsflhh", model.logging().storageAccount().containerName()); + Assertions.assertEquals(290339428, model.scalingProperties().capacity()); + Assertions.assertEquals("ixisxyawjoy", model.scalingProperties().profiles().get(0).name()); + Assertions.assertEquals(628335164, model.scalingProperties().profiles().get(0).capacity().min()); + Assertions.assertEquals(1772436776, model.scalingProperties().profiles().get(0).capacity().max()); + Assertions.assertEquals("apnyiropuhpig", model.userProfile().preferredEmail()); + Assertions.assertEquals("qgitxmed", + model.networkProfile().frontEndIpConfiguration().publicIpAddresses().get(0).id()); + Assertions.assertEquals("lynqwwncwzzh", + model.networkProfile().frontEndIpConfiguration().privateIpAddresses().get(0).privateIpAddress()); + Assertions.assertEquals(NginxPrivateIpAllocationMethod.DYNAMIC, + model.networkProfile().frontEndIpConfiguration().privateIpAddresses().get(0).privateIpAllocationMethod()); + Assertions.assertEquals("rmgucnap", + model.networkProfile().frontEndIpConfiguration().privateIpAddresses().get(0).subnetId()); + Assertions.assertEquals("oellwp", model.networkProfile().networkInterfaceConfiguration().subnetId()); + Assertions.assertEquals("d", model.autoUpgradeProfile().upgradeChannel()); + Assertions.assertEquals(ActivationState.DISABLED, + model.nginxAppProtect().webApplicationFirewallSettings().activationState()); } @org.junit.jupiter.api.Test @@ -38,21 +58,50 @@ public void testSerialize() throws Exception { NginxDeploymentUpdateProperties model = new NginxDeploymentUpdateProperties().withEnableDiagnosticsSupport(false) .withLogging(new NginxLogging().withStorageAccount( - new NginxStorageAccount().withAccountName("yvshxmz").withContainerName("bzoggigrx"))) - .withScalingProperties(new NginxDeploymentScalingProperties().withCapacity(849896725) - .withProfiles(Arrays.asList(new ScaleProfile().withName("xxjnspydptk") - .withCapacity(new ScaleProfileCapacity().withMin(668833312).withMax(1482419493))))) - .withUserProfile(new NginxDeploymentUserProfile().withPreferredEmail("uknvudwti")) - .withAutoUpgradeProfile(new AutoUpgradeProfile().withUpgradeChannel("bldngkpoc")); + new NginxStorageAccount().withAccountName("ekqvkeln").withContainerName("vbxwyjsflhh"))) + .withScalingProperties(new NginxDeploymentScalingProperties().withCapacity(290339428) + .withProfiles(Arrays.asList( + new ScaleProfile().withName("ixisxyawjoy") + .withCapacity(new ScaleProfileCapacity().withMin(628335164).withMax(1772436776)), + new ScaleProfile().withName("slyjpkiid") + .withCapacity(new ScaleProfileCapacity().withMin(983085062).withMax(787836165)), + new ScaleProfile().withName("xznelixhnrztf") + .withCapacity(new ScaleProfileCapacity().withMin(1975568377).withMax(434458515)), + new ScaleProfile().withName("bnxknalaulppg") + .withCapacity(new ScaleProfileCapacity().withMin(1784168921).withMax(1987785731))))) + .withUserProfile(new NginxDeploymentUserProfile().withPreferredEmail("apnyiropuhpig")) + .withNetworkProfile(new NginxNetworkProfile() + .withFrontEndIpConfiguration(new NginxFrontendIpConfiguration() + .withPublicIpAddresses(Arrays.asList(new NginxPublicIpAddress().withId("qgitxmed"))) + .withPrivateIpAddresses( + Arrays.asList(new NginxPrivateIpAddress().withPrivateIpAddress("lynqwwncwzzh") + .withPrivateIpAllocationMethod(NginxPrivateIpAllocationMethod.DYNAMIC) + .withSubnetId("rmgucnap")))) + .withNetworkInterfaceConfiguration(new NginxNetworkInterfaceConfiguration().withSubnetId("oellwp"))) + .withAutoUpgradeProfile(new AutoUpgradeProfile().withUpgradeChannel("d")) + .withNginxAppProtect( + new NginxDeploymentUpdatePropertiesNginxAppProtect().withWebApplicationFirewallSettings( + new WebApplicationFirewallSettings().withActivationState(ActivationState.DISABLED))); model = BinaryData.fromObject(model).toObject(NginxDeploymentUpdateProperties.class); Assertions.assertEquals(false, model.enableDiagnosticsSupport()); - Assertions.assertEquals("yvshxmz", model.logging().storageAccount().accountName()); - Assertions.assertEquals("bzoggigrx", model.logging().storageAccount().containerName()); - Assertions.assertEquals(849896725, model.scalingProperties().capacity()); - Assertions.assertEquals("xxjnspydptk", model.scalingProperties().profiles().get(0).name()); - Assertions.assertEquals(668833312, model.scalingProperties().profiles().get(0).capacity().min()); - Assertions.assertEquals(1482419493, model.scalingProperties().profiles().get(0).capacity().max()); - Assertions.assertEquals("uknvudwti", model.userProfile().preferredEmail()); - Assertions.assertEquals("bldngkpoc", model.autoUpgradeProfile().upgradeChannel()); + Assertions.assertEquals("ekqvkeln", model.logging().storageAccount().accountName()); + Assertions.assertEquals("vbxwyjsflhh", model.logging().storageAccount().containerName()); + Assertions.assertEquals(290339428, model.scalingProperties().capacity()); + Assertions.assertEquals("ixisxyawjoy", model.scalingProperties().profiles().get(0).name()); + Assertions.assertEquals(628335164, model.scalingProperties().profiles().get(0).capacity().min()); + Assertions.assertEquals(1772436776, model.scalingProperties().profiles().get(0).capacity().max()); + Assertions.assertEquals("apnyiropuhpig", model.userProfile().preferredEmail()); + Assertions.assertEquals("qgitxmed", + model.networkProfile().frontEndIpConfiguration().publicIpAddresses().get(0).id()); + Assertions.assertEquals("lynqwwncwzzh", + model.networkProfile().frontEndIpConfiguration().privateIpAddresses().get(0).privateIpAddress()); + Assertions.assertEquals(NginxPrivateIpAllocationMethod.DYNAMIC, + model.networkProfile().frontEndIpConfiguration().privateIpAddresses().get(0).privateIpAllocationMethod()); + Assertions.assertEquals("rmgucnap", + model.networkProfile().frontEndIpConfiguration().privateIpAddresses().get(0).subnetId()); + Assertions.assertEquals("oellwp", model.networkProfile().networkInterfaceConfiguration().subnetId()); + Assertions.assertEquals("d", model.autoUpgradeProfile().upgradeChannel()); + Assertions.assertEquals(ActivationState.DISABLED, + model.nginxAppProtect().webApplicationFirewallSettings().activationState()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentUserProfileTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentUserProfileTests.java index a4b7369b7639..0cc2e6e23492 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentUserProfileTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxDeploymentUserProfileTests.java @@ -12,14 +12,14 @@ public final class NginxDeploymentUserProfileTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { NginxDeploymentUserProfile model - = BinaryData.fromString("{\"preferredEmail\":\"wqsmbsur\"}").toObject(NginxDeploymentUserProfile.class); - Assertions.assertEquals("wqsmbsur", model.preferredEmail()); + = BinaryData.fromString("{\"preferredEmail\":\"mdua\"}").toObject(NginxDeploymentUserProfile.class); + Assertions.assertEquals("mdua", model.preferredEmail()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - NginxDeploymentUserProfile model = new NginxDeploymentUserProfile().withPreferredEmail("wqsmbsur"); + NginxDeploymentUserProfile model = new NginxDeploymentUserProfile().withPreferredEmail("mdua"); model = BinaryData.fromObject(model).toObject(NginxDeploymentUserProfile.class); - Assertions.assertEquals("wqsmbsur", model.preferredEmail()); + Assertions.assertEquals("mdua", model.preferredEmail()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxFrontendIpConfigurationTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxFrontendIpConfigurationTests.java index c3f211c5bf76..416241c88f85 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxFrontendIpConfigurationTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxFrontendIpConfigurationTests.java @@ -16,32 +16,27 @@ public final class NginxFrontendIpConfigurationTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { NginxFrontendIpConfiguration model = BinaryData.fromString( - "{\"publicIPAddresses\":[{\"id\":\"nzwdejba\"},{\"id\":\"rxzdmohctbqvudwx\"}],\"privateIPAddresses\":[{\"privateIPAddress\":\"vo\",\"privateIPAllocationMethod\":\"Dynamic\",\"subnetId\":\"jugwdkcglhsl\"},{\"privateIPAddress\":\"jdyggdtji\",\"privateIPAllocationMethod\":\"Static\",\"subnetId\":\"uofqwe\"}]}") + "{\"publicIPAddresses\":[{\"id\":\"lo\"}],\"privateIPAddresses\":[{\"privateIPAddress\":\"yfjfcnjbkcn\",\"privateIPAllocationMethod\":\"Dynamic\",\"subnetId\":\"ttkphywpnvjtoqne\"}]}") .toObject(NginxFrontendIpConfiguration.class); - Assertions.assertEquals("nzwdejba", model.publicIpAddresses().get(0).id()); - Assertions.assertEquals("vo", model.privateIpAddresses().get(0).privateIpAddress()); + Assertions.assertEquals("lo", model.publicIpAddresses().get(0).id()); + Assertions.assertEquals("yfjfcnjbkcn", model.privateIpAddresses().get(0).privateIpAddress()); Assertions.assertEquals(NginxPrivateIpAllocationMethod.DYNAMIC, model.privateIpAddresses().get(0).privateIpAllocationMethod()); - Assertions.assertEquals("jugwdkcglhsl", model.privateIpAddresses().get(0).subnetId()); + Assertions.assertEquals("ttkphywpnvjtoqne", model.privateIpAddresses().get(0).subnetId()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { NginxFrontendIpConfiguration model = new NginxFrontendIpConfiguration() - .withPublicIpAddresses(Arrays.asList(new NginxPublicIpAddress().withId("nzwdejba"), - new NginxPublicIpAddress().withId("rxzdmohctbqvudwx"))) - .withPrivateIpAddresses(Arrays.asList( - new NginxPrivateIpAddress().withPrivateIpAddress("vo") - .withPrivateIpAllocationMethod(NginxPrivateIpAllocationMethod.DYNAMIC) - .withSubnetId("jugwdkcglhsl"), - new NginxPrivateIpAddress().withPrivateIpAddress("jdyggdtji") - .withPrivateIpAllocationMethod(NginxPrivateIpAllocationMethod.STATIC) - .withSubnetId("uofqwe"))); + .withPublicIpAddresses(Arrays.asList(new NginxPublicIpAddress().withId("lo"))) + .withPrivateIpAddresses(Arrays.asList(new NginxPrivateIpAddress().withPrivateIpAddress("yfjfcnjbkcn") + .withPrivateIpAllocationMethod(NginxPrivateIpAllocationMethod.DYNAMIC) + .withSubnetId("ttkphywpnvjtoqne"))); model = BinaryData.fromObject(model).toObject(NginxFrontendIpConfiguration.class); - Assertions.assertEquals("nzwdejba", model.publicIpAddresses().get(0).id()); - Assertions.assertEquals("vo", model.privateIpAddresses().get(0).privateIpAddress()); + Assertions.assertEquals("lo", model.publicIpAddresses().get(0).id()); + Assertions.assertEquals("yfjfcnjbkcn", model.privateIpAddresses().get(0).privateIpAddress()); Assertions.assertEquals(NginxPrivateIpAllocationMethod.DYNAMIC, model.privateIpAddresses().get(0).privateIpAllocationMethod()); - Assertions.assertEquals("jugwdkcglhsl", model.privateIpAddresses().get(0).subnetId()); + Assertions.assertEquals("ttkphywpnvjtoqne", model.privateIpAddresses().get(0).subnetId()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxLoggingTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxLoggingTests.java index 16bce87e1554..9ddf45bba3c8 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxLoggingTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxLoggingTests.java @@ -13,18 +13,18 @@ public final class NginxLoggingTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { NginxLogging model = BinaryData - .fromString("{\"storageAccount\":{\"accountName\":\"scjeypv\",\"containerName\":\"zrkgqhcjrefovg\"}}") + .fromString("{\"storageAccount\":{\"accountName\":\"ywpmueefjzwfqkq\",\"containerName\":\"ids\"}}") .toObject(NginxLogging.class); - Assertions.assertEquals("scjeypv", model.storageAccount().accountName()); - Assertions.assertEquals("zrkgqhcjrefovg", model.storageAccount().containerName()); + Assertions.assertEquals("ywpmueefjzwfqkq", model.storageAccount().accountName()); + Assertions.assertEquals("ids", model.storageAccount().containerName()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - NginxLogging model = new NginxLogging().withStorageAccount( - new NginxStorageAccount().withAccountName("scjeypv").withContainerName("zrkgqhcjrefovg")); + NginxLogging model = new NginxLogging() + .withStorageAccount(new NginxStorageAccount().withAccountName("ywpmueefjzwfqkq").withContainerName("ids")); model = BinaryData.fromObject(model).toObject(NginxLogging.class); - Assertions.assertEquals("scjeypv", model.storageAccount().accountName()); - Assertions.assertEquals("zrkgqhcjrefovg", model.storageAccount().containerName()); + Assertions.assertEquals("ywpmueefjzwfqkq", model.storageAccount().accountName()); + Assertions.assertEquals("ids", model.storageAccount().containerName()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxNetworkInterfaceConfigurationTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxNetworkInterfaceConfigurationTests.java index 33d34137fb59..037c0e63912f 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxNetworkInterfaceConfigurationTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxNetworkInterfaceConfigurationTests.java @@ -12,14 +12,14 @@ public final class NginxNetworkInterfaceConfigurationTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { NginxNetworkInterfaceConfiguration model - = BinaryData.fromString("{\"subnetId\":\"eh\"}").toObject(NginxNetworkInterfaceConfiguration.class); - Assertions.assertEquals("eh", model.subnetId()); + = BinaryData.fromString("{\"subnetId\":\"zq\"}").toObject(NginxNetworkInterfaceConfiguration.class); + Assertions.assertEquals("zq", model.subnetId()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - NginxNetworkInterfaceConfiguration model = new NginxNetworkInterfaceConfiguration().withSubnetId("eh"); + NginxNetworkInterfaceConfiguration model = new NginxNetworkInterfaceConfiguration().withSubnetId("zq"); model = BinaryData.fromObject(model).toObject(NginxNetworkInterfaceConfiguration.class); - Assertions.assertEquals("eh", model.subnetId()); + Assertions.assertEquals("zq", model.subnetId()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxNetworkProfileTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxNetworkProfileTests.java index e1d302f55356..aeffee86d390 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxNetworkProfileTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxNetworkProfileTests.java @@ -18,42 +18,40 @@ public final class NginxNetworkProfileTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { NginxNetworkProfile model = BinaryData.fromString( - "{\"frontEndIPConfiguration\":{\"publicIPAddresses\":[{\"id\":\"okeyyienj\"}],\"privateIPAddresses\":[{\"privateIPAddress\":\"tgrhpdjpjumas\",\"privateIPAllocationMethod\":\"Static\",\"subnetId\":\"pqyegualhbxxh\"},{\"privateIPAddress\":\"jzzvdud\",\"privateIPAllocationMethod\":\"Dynamic\",\"subnetId\":\"lfh\"},{\"privateIPAddress\":\"wmc\",\"privateIPAllocationMethod\":\"Static\",\"subnetId\":\"lbjnpgacftadehx\"}]},\"networkInterfaceConfiguration\":{\"subnetId\":\"yfsoppu\"}}") + "{\"frontEndIPConfiguration\":{\"publicIPAddresses\":[{\"id\":\"baumnyqupedeoj\"}],\"privateIPAddresses\":[{\"privateIPAddress\":\"khsmtxpsiebt\",\"privateIPAllocationMethod\":\"Dynamic\",\"subnetId\":\"esap\"},{\"privateIPAddress\":\"rdqmhjjdhtldwkyz\",\"privateIPAllocationMethod\":\"Static\",\"subnetId\":\"kn\"},{\"privateIPAddress\":\"scwsv\",\"privateIPAllocationMethod\":\"Dynamic\",\"subnetId\":\"ogtwrupqsxvnmi\"}]},\"networkInterfaceConfiguration\":{\"subnetId\":\"vce\"}}") .toObject(NginxNetworkProfile.class); - Assertions.assertEquals("okeyyienj", model.frontEndIpConfiguration().publicIpAddresses().get(0).id()); - Assertions.assertEquals("tgrhpdjpjumas", + Assertions.assertEquals("baumnyqupedeoj", model.frontEndIpConfiguration().publicIpAddresses().get(0).id()); + Assertions.assertEquals("khsmtxpsiebt", model.frontEndIpConfiguration().privateIpAddresses().get(0).privateIpAddress()); - Assertions.assertEquals(NginxPrivateIpAllocationMethod.STATIC, + Assertions.assertEquals(NginxPrivateIpAllocationMethod.DYNAMIC, model.frontEndIpConfiguration().privateIpAddresses().get(0).privateIpAllocationMethod()); - Assertions.assertEquals("pqyegualhbxxh", - model.frontEndIpConfiguration().privateIpAddresses().get(0).subnetId()); - Assertions.assertEquals("yfsoppu", model.networkInterfaceConfiguration().subnetId()); + Assertions.assertEquals("esap", model.frontEndIpConfiguration().privateIpAddresses().get(0).subnetId()); + Assertions.assertEquals("vce", model.networkInterfaceConfiguration().subnetId()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { NginxNetworkProfile model = new NginxNetworkProfile() .withFrontEndIpConfiguration(new NginxFrontendIpConfiguration() - .withPublicIpAddresses(Arrays.asList(new NginxPublicIpAddress().withId("okeyyienj"))) + .withPublicIpAddresses(Arrays.asList(new NginxPublicIpAddress().withId("baumnyqupedeoj"))) .withPrivateIpAddresses(Arrays.asList( - new NginxPrivateIpAddress().withPrivateIpAddress("tgrhpdjpjumas") - .withPrivateIpAllocationMethod(NginxPrivateIpAllocationMethod.STATIC) - .withSubnetId("pqyegualhbxxh"), - new NginxPrivateIpAddress().withPrivateIpAddress("jzzvdud") + new NginxPrivateIpAddress().withPrivateIpAddress("khsmtxpsiebt") .withPrivateIpAllocationMethod(NginxPrivateIpAllocationMethod.DYNAMIC) - .withSubnetId("lfh"), - new NginxPrivateIpAddress().withPrivateIpAddress("wmc") + .withSubnetId("esap"), + new NginxPrivateIpAddress().withPrivateIpAddress("rdqmhjjdhtldwkyz") .withPrivateIpAllocationMethod(NginxPrivateIpAllocationMethod.STATIC) - .withSubnetId("lbjnpgacftadehx")))) - .withNetworkInterfaceConfiguration(new NginxNetworkInterfaceConfiguration().withSubnetId("yfsoppu")); + .withSubnetId("kn"), + new NginxPrivateIpAddress().withPrivateIpAddress("scwsv") + .withPrivateIpAllocationMethod(NginxPrivateIpAllocationMethod.DYNAMIC) + .withSubnetId("ogtwrupqsxvnmi")))) + .withNetworkInterfaceConfiguration(new NginxNetworkInterfaceConfiguration().withSubnetId("vce")); model = BinaryData.fromObject(model).toObject(NginxNetworkProfile.class); - Assertions.assertEquals("okeyyienj", model.frontEndIpConfiguration().publicIpAddresses().get(0).id()); - Assertions.assertEquals("tgrhpdjpjumas", + Assertions.assertEquals("baumnyqupedeoj", model.frontEndIpConfiguration().publicIpAddresses().get(0).id()); + Assertions.assertEquals("khsmtxpsiebt", model.frontEndIpConfiguration().privateIpAddresses().get(0).privateIpAddress()); - Assertions.assertEquals(NginxPrivateIpAllocationMethod.STATIC, + Assertions.assertEquals(NginxPrivateIpAllocationMethod.DYNAMIC, model.frontEndIpConfiguration().privateIpAddresses().get(0).privateIpAllocationMethod()); - Assertions.assertEquals("pqyegualhbxxh", - model.frontEndIpConfiguration().privateIpAddresses().get(0).subnetId()); - Assertions.assertEquals("yfsoppu", model.networkInterfaceConfiguration().subnetId()); + Assertions.assertEquals("esap", model.frontEndIpConfiguration().privateIpAddresses().get(0).subnetId()); + Assertions.assertEquals("vce", model.networkInterfaceConfiguration().subnetId()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxPrivateIpAddressTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxPrivateIpAddressTests.java index eec26e0105e5..0eab114b6199 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxPrivateIpAddressTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxPrivateIpAddressTests.java @@ -14,21 +14,21 @@ public final class NginxPrivateIpAddressTests { public void testDeserialize() throws Exception { NginxPrivateIpAddress model = BinaryData .fromString( - "{\"privateIPAddress\":\"vyvdcs\",\"privateIPAllocationMethod\":\"Static\",\"subnetId\":\"naamde\"}") + "{\"privateIPAddress\":\"hoxus\",\"privateIPAllocationMethod\":\"Static\",\"subnetId\":\"bgyepsbj\"}") .toObject(NginxPrivateIpAddress.class); - Assertions.assertEquals("vyvdcs", model.privateIpAddress()); + Assertions.assertEquals("hoxus", model.privateIpAddress()); Assertions.assertEquals(NginxPrivateIpAllocationMethod.STATIC, model.privateIpAllocationMethod()); - Assertions.assertEquals("naamde", model.subnetId()); + Assertions.assertEquals("bgyepsbj", model.subnetId()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - NginxPrivateIpAddress model = new NginxPrivateIpAddress().withPrivateIpAddress("vyvdcs") + NginxPrivateIpAddress model = new NginxPrivateIpAddress().withPrivateIpAddress("hoxus") .withPrivateIpAllocationMethod(NginxPrivateIpAllocationMethod.STATIC) - .withSubnetId("naamde"); + .withSubnetId("bgyepsbj"); model = BinaryData.fromObject(model).toObject(NginxPrivateIpAddress.class); - Assertions.assertEquals("vyvdcs", model.privateIpAddress()); + Assertions.assertEquals("hoxus", model.privateIpAddress()); Assertions.assertEquals(NginxPrivateIpAllocationMethod.STATIC, model.privateIpAllocationMethod()); - Assertions.assertEquals("naamde", model.subnetId()); + Assertions.assertEquals("bgyepsbj", model.subnetId()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxPublicIpAddressTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxPublicIpAddressTests.java index 82806f541fed..b6170375f169 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxPublicIpAddressTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxPublicIpAddressTests.java @@ -11,15 +11,14 @@ public final class NginxPublicIpAddressTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - NginxPublicIpAddress model - = BinaryData.fromString("{\"id\":\"hmenevfyexfwhybc\"}").toObject(NginxPublicIpAddress.class); - Assertions.assertEquals("hmenevfyexfwhybc", model.id()); + NginxPublicIpAddress model = BinaryData.fromString("{\"id\":\"clfp\"}").toObject(NginxPublicIpAddress.class); + Assertions.assertEquals("clfp", model.id()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - NginxPublicIpAddress model = new NginxPublicIpAddress().withId("hmenevfyexfwhybc"); + NginxPublicIpAddress model = new NginxPublicIpAddress().withId("clfp"); model = BinaryData.fromObject(model).toObject(NginxPublicIpAddress.class); - Assertions.assertEquals("hmenevfyexfwhybc", model.id()); + Assertions.assertEquals("clfp", model.id()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxStorageAccountTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxStorageAccountTests.java index feaeabbaa3f4..f5484edbdb6b 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxStorageAccountTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/NginxStorageAccountTests.java @@ -11,17 +11,19 @@ public final class NginxStorageAccountTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - NginxStorageAccount model = BinaryData.fromString("{\"accountName\":\"qsl\",\"containerName\":\"yvxyqjp\"}") - .toObject(NginxStorageAccount.class); - Assertions.assertEquals("qsl", model.accountName()); - Assertions.assertEquals("yvxyqjp", model.containerName()); + NginxStorageAccount model + = BinaryData.fromString("{\"accountName\":\"onobglaocqx\",\"containerName\":\"cmgyud\"}") + .toObject(NginxStorageAccount.class); + Assertions.assertEquals("onobglaocqx", model.accountName()); + Assertions.assertEquals("cmgyud", model.containerName()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - NginxStorageAccount model = new NginxStorageAccount().withAccountName("qsl").withContainerName("yvxyqjp"); + NginxStorageAccount model + = new NginxStorageAccount().withAccountName("onobglaocqx").withContainerName("cmgyud"); model = BinaryData.fromObject(model).toObject(NginxStorageAccount.class); - Assertions.assertEquals("qsl", model.accountName()); - Assertions.assertEquals("yvxyqjp", model.containerName()); + Assertions.assertEquals("onobglaocqx", model.accountName()); + Assertions.assertEquals("cmgyud", model.containerName()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/OperationDisplayTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/OperationDisplayTests.java index e8a6f616274c..f44f68e27222 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/OperationDisplayTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/OperationDisplayTests.java @@ -11,26 +11,25 @@ public final class OperationDisplayTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - OperationDisplay model = BinaryData - .fromString( - "{\"provider\":\"ali\",\"resource\":\"rqhakauha\",\"operation\":\"sfwxosowzxc\",\"description\":\"i\"}") + OperationDisplay model = BinaryData.fromString( + "{\"provider\":\"baaa\",\"resource\":\"yvayffimrzr\",\"operation\":\"zqogse\",\"description\":\"evfdnwnwm\"}") .toObject(OperationDisplay.class); - Assertions.assertEquals("ali", model.provider()); - Assertions.assertEquals("rqhakauha", model.resource()); - Assertions.assertEquals("sfwxosowzxc", model.operation()); - Assertions.assertEquals("i", model.description()); + Assertions.assertEquals("baaa", model.provider()); + Assertions.assertEquals("yvayffimrzr", model.resource()); + Assertions.assertEquals("zqogse", model.operation()); + Assertions.assertEquals("evfdnwnwm", model.description()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - OperationDisplay model = new OperationDisplay().withProvider("ali") - .withResource("rqhakauha") - .withOperation("sfwxosowzxc") - .withDescription("i"); + OperationDisplay model = new OperationDisplay().withProvider("baaa") + .withResource("yvayffimrzr") + .withOperation("zqogse") + .withDescription("evfdnwnwm"); model = BinaryData.fromObject(model).toObject(OperationDisplay.class); - Assertions.assertEquals("ali", model.provider()); - Assertions.assertEquals("rqhakauha", model.resource()); - Assertions.assertEquals("sfwxosowzxc", model.operation()); - Assertions.assertEquals("i", model.description()); + Assertions.assertEquals("baaa", model.provider()); + Assertions.assertEquals("yvayffimrzr", model.resource()); + Assertions.assertEquals("zqogse", model.operation()); + Assertions.assertEquals("evfdnwnwm", model.description()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/OperationListResultTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/OperationListResultTests.java index a0c87b83ff48..1a346e8a48ab 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/OperationListResultTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/OperationListResultTests.java @@ -15,40 +15,46 @@ public final class OperationListResultTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { OperationListResult model = BinaryData.fromString( - "{\"value\":[{\"name\":\"hl\",\"display\":{\"provider\":\"bh\",\"resource\":\"frlh\",\"operation\":\"sbkyvpycanuzbp\",\"description\":\"afkuwb\"},\"isDataAction\":false},{\"name\":\"bmehh\",\"display\":{\"provider\":\"v\",\"resource\":\"srtslhspkdeem\",\"operation\":\"fm\",\"description\":\"gkvtmelmqkrhah\"},\"isDataAction\":true}],\"nextLink\":\"ahaquh\"}") + "{\"value\":[{\"name\":\"kkfoqr\",\"display\":{\"provider\":\"kzikfjawneaivxwc\",\"resource\":\"lpcirelsf\",\"operation\":\"enwabfatk\",\"description\":\"dxbjhwuaanozj\"},\"isDataAction\":false},{\"name\":\"youlp\",\"display\":{\"provider\":\"xagl\",\"resource\":\"imjwosyt\",\"operation\":\"tcs\",\"description\":\"cktqumiekkezzi\"},\"isDataAction\":false},{\"name\":\"fjhdg\",\"display\":{\"provider\":\"ebdunyg\",\"resource\":\"qidbqfatpxllrxcy\",\"operation\":\"oadsuvar\",\"description\":\"wdmjsjqbjhhyx\"},\"isDataAction\":true}],\"nextLink\":\"yc\"}") .toObject(OperationListResult.class); - Assertions.assertEquals("hl", model.value().get(0).name()); - Assertions.assertEquals("bh", model.value().get(0).display().provider()); - Assertions.assertEquals("frlh", model.value().get(0).display().resource()); - Assertions.assertEquals("sbkyvpycanuzbp", model.value().get(0).display().operation()); - Assertions.assertEquals("afkuwb", model.value().get(0).display().description()); + Assertions.assertEquals("kkfoqr", model.value().get(0).name()); + Assertions.assertEquals("kzikfjawneaivxwc", model.value().get(0).display().provider()); + Assertions.assertEquals("lpcirelsf", model.value().get(0).display().resource()); + Assertions.assertEquals("enwabfatk", model.value().get(0).display().operation()); + Assertions.assertEquals("dxbjhwuaanozj", model.value().get(0).display().description()); Assertions.assertEquals(false, model.value().get(0).isDataAction()); - Assertions.assertEquals("ahaquh", model.nextLink()); + Assertions.assertEquals("yc", model.nextLink()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { OperationListResult model = new OperationListResult().withValue(Arrays.asList( - new OperationResultInner().withName("hl") - .withDisplay(new OperationDisplay().withProvider("bh") - .withResource("frlh") - .withOperation("sbkyvpycanuzbp") - .withDescription("afkuwb")) + new OperationResultInner().withName("kkfoqr") + .withDisplay(new OperationDisplay().withProvider("kzikfjawneaivxwc") + .withResource("lpcirelsf") + .withOperation("enwabfatk") + .withDescription("dxbjhwuaanozj")) .withIsDataAction(false), - new OperationResultInner().withName("bmehh") - .withDisplay(new OperationDisplay().withProvider("v") - .withResource("srtslhspkdeem") - .withOperation("fm") - .withDescription("gkvtmelmqkrhah")) + new OperationResultInner().withName("youlp") + .withDisplay(new OperationDisplay().withProvider("xagl") + .withResource("imjwosyt") + .withOperation("tcs") + .withDescription("cktqumiekkezzi")) + .withIsDataAction(false), + new OperationResultInner().withName("fjhdg") + .withDisplay(new OperationDisplay().withProvider("ebdunyg") + .withResource("qidbqfatpxllrxcy") + .withOperation("oadsuvar") + .withDescription("wdmjsjqbjhhyx")) .withIsDataAction(true))) - .withNextLink("ahaquh"); + .withNextLink("yc"); model = BinaryData.fromObject(model).toObject(OperationListResult.class); - Assertions.assertEquals("hl", model.value().get(0).name()); - Assertions.assertEquals("bh", model.value().get(0).display().provider()); - Assertions.assertEquals("frlh", model.value().get(0).display().resource()); - Assertions.assertEquals("sbkyvpycanuzbp", model.value().get(0).display().operation()); - Assertions.assertEquals("afkuwb", model.value().get(0).display().description()); + Assertions.assertEquals("kkfoqr", model.value().get(0).name()); + Assertions.assertEquals("kzikfjawneaivxwc", model.value().get(0).display().provider()); + Assertions.assertEquals("lpcirelsf", model.value().get(0).display().resource()); + Assertions.assertEquals("enwabfatk", model.value().get(0).display().operation()); + Assertions.assertEquals("dxbjhwuaanozj", model.value().get(0).display().description()); Assertions.assertEquals(false, model.value().get(0).isDataAction()); - Assertions.assertEquals("ahaquh", model.nextLink()); + Assertions.assertEquals("yc", model.nextLink()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/OperationResultInnerTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/OperationResultInnerTests.java index c2efc4ddf0b8..e0e5946049b8 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/OperationResultInnerTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/OperationResultInnerTests.java @@ -13,30 +13,30 @@ public final class OperationResultInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { OperationResultInner model = BinaryData.fromString( - "{\"name\":\"hmdua\",\"display\":{\"provider\":\"xqpvfadmw\",\"resource\":\"crgvxpvgom\",\"operation\":\"fmisg\",\"description\":\"nbbelda\"},\"isDataAction\":true}") + "{\"name\":\"uhpkxkgymar\",\"display\":{\"provider\":\"ajxq\",\"resource\":\"jhkycub\",\"operation\":\"dgssofwqmzqal\",\"description\":\"mnjijpxacqqudf\"},\"isDataAction\":true}") .toObject(OperationResultInner.class); - Assertions.assertEquals("hmdua", model.name()); - Assertions.assertEquals("xqpvfadmw", model.display().provider()); - Assertions.assertEquals("crgvxpvgom", model.display().resource()); - Assertions.assertEquals("fmisg", model.display().operation()); - Assertions.assertEquals("nbbelda", model.display().description()); + Assertions.assertEquals("uhpkxkgymar", model.name()); + Assertions.assertEquals("ajxq", model.display().provider()); + Assertions.assertEquals("jhkycub", model.display().resource()); + Assertions.assertEquals("dgssofwqmzqal", model.display().operation()); + Assertions.assertEquals("mnjijpxacqqudf", model.display().description()); Assertions.assertEquals(true, model.isDataAction()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - OperationResultInner model = new OperationResultInner().withName("hmdua") - .withDisplay(new OperationDisplay().withProvider("xqpvfadmw") - .withResource("crgvxpvgom") - .withOperation("fmisg") - .withDescription("nbbelda")) + OperationResultInner model = new OperationResultInner().withName("uhpkxkgymar") + .withDisplay(new OperationDisplay().withProvider("ajxq") + .withResource("jhkycub") + .withOperation("dgssofwqmzqal") + .withDescription("mnjijpxacqqudf")) .withIsDataAction(true); model = BinaryData.fromObject(model).toObject(OperationResultInner.class); - Assertions.assertEquals("hmdua", model.name()); - Assertions.assertEquals("xqpvfadmw", model.display().provider()); - Assertions.assertEquals("crgvxpvgom", model.display().resource()); - Assertions.assertEquals("fmisg", model.display().operation()); - Assertions.assertEquals("nbbelda", model.display().description()); + Assertions.assertEquals("uhpkxkgymar", model.name()); + Assertions.assertEquals("ajxq", model.display().provider()); + Assertions.assertEquals("jhkycub", model.display().resource()); + Assertions.assertEquals("dgssofwqmzqal", model.display().operation()); + Assertions.assertEquals("mnjijpxacqqudf", model.display().description()); Assertions.assertEquals(true, model.isDataAction()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/OperationsListMockTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/OperationsListMockTests.java index 0c472d484459..5ab6459243d2 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/OperationsListMockTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/OperationsListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.nginx.NginxManager; import com.azure.resourcemanager.nginx.models.OperationResult; @@ -22,22 +22,22 @@ public final class OperationsListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"name\":\"mzqhoftrmaequi\",\"display\":{\"provider\":\"icslfaoq\",\"resource\":\"iyylhalnswhccsp\",\"operation\":\"aivwitqscywu\",\"description\":\"woluhczbwemhair\"},\"isDataAction\":true}]}"; + = "{\"value\":[{\"name\":\"cjdx\",\"display\":{\"provider\":\"zoggculapz\",\"resource\":\"rpgogtqxep\",\"operation\":\"lbfu\",\"description\":\"lyjt\"},\"isDataAction\":false}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); NginxManager manager = NginxManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.operations().list(com.azure.core.util.Context.NONE); - Assertions.assertEquals("mzqhoftrmaequi", response.iterator().next().name()); - Assertions.assertEquals("icslfaoq", response.iterator().next().display().provider()); - Assertions.assertEquals("iyylhalnswhccsp", response.iterator().next().display().resource()); - Assertions.assertEquals("aivwitqscywu", response.iterator().next().display().operation()); - Assertions.assertEquals("woluhczbwemhair", response.iterator().next().display().description()); - Assertions.assertEquals(true, response.iterator().next().isDataAction()); + Assertions.assertEquals("cjdx", response.iterator().next().name()); + Assertions.assertEquals("zoggculapz", response.iterator().next().display().provider()); + Assertions.assertEquals("rpgogtqxep", response.iterator().next().display().resource()); + Assertions.assertEquals("lbfu", response.iterator().next().display().operation()); + Assertions.assertEquals("lyjt", response.iterator().next().display().description()); + Assertions.assertEquals(false, response.iterator().next().isDataAction()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ResourceSkuTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ResourceSkuTests.java index f4df07d8e1cf..9f31ae165a0a 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ResourceSkuTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ResourceSkuTests.java @@ -11,14 +11,14 @@ public final class ResourceSkuTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - ResourceSku model = BinaryData.fromString("{\"name\":\"xim\"}").toObject(ResourceSku.class); - Assertions.assertEquals("xim", model.name()); + ResourceSku model = BinaryData.fromString("{\"name\":\"jdauwhvy\"}").toObject(ResourceSku.class); + Assertions.assertEquals("jdauwhvy", model.name()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - ResourceSku model = new ResourceSku().withName("xim"); + ResourceSku model = new ResourceSku().withName("jdauwhvy"); model = BinaryData.fromObject(model).toObject(ResourceSku.class); - Assertions.assertEquals("xim", model.name()); + Assertions.assertEquals("jdauwhvy", model.name()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ScaleProfileCapacityTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ScaleProfileCapacityTests.java index d8d059d00226..12bedc8b1b30 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ScaleProfileCapacityTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ScaleProfileCapacityTests.java @@ -12,16 +12,16 @@ public final class ScaleProfileCapacityTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ScaleProfileCapacity model - = BinaryData.fromString("{\"min\":1016147904,\"max\":269303909}").toObject(ScaleProfileCapacity.class); - Assertions.assertEquals(1016147904, model.min()); - Assertions.assertEquals(269303909, model.max()); + = BinaryData.fromString("{\"min\":1520620796,\"max\":14767496}").toObject(ScaleProfileCapacity.class); + Assertions.assertEquals(1520620796, model.min()); + Assertions.assertEquals(14767496, model.max()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - ScaleProfileCapacity model = new ScaleProfileCapacity().withMin(1016147904).withMax(269303909); + ScaleProfileCapacity model = new ScaleProfileCapacity().withMin(1520620796).withMax(14767496); model = BinaryData.fromObject(model).toObject(ScaleProfileCapacity.class); - Assertions.assertEquals(1016147904, model.min()); - Assertions.assertEquals(269303909, model.max()); + Assertions.assertEquals(1520620796, model.min()); + Assertions.assertEquals(14767496, model.max()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ScaleProfileTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ScaleProfileTests.java index 391c755f4b7b..3d21800efb3e 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ScaleProfileTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/ScaleProfileTests.java @@ -13,20 +13,20 @@ public final class ScaleProfileTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { ScaleProfile model - = BinaryData.fromString("{\"name\":\"ydagfuaxbe\",\"capacity\":{\"min\":45811298,\"max\":427242708}}") + = BinaryData.fromString("{\"name\":\"qkrhahvljua\",\"capacity\":{\"min\":1935710102,\"max\":836090349}}") .toObject(ScaleProfile.class); - Assertions.assertEquals("ydagfuaxbe", model.name()); - Assertions.assertEquals(45811298, model.capacity().min()); - Assertions.assertEquals(427242708, model.capacity().max()); + Assertions.assertEquals("qkrhahvljua", model.name()); + Assertions.assertEquals(1935710102, model.capacity().min()); + Assertions.assertEquals(836090349, model.capacity().max()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - ScaleProfile model = new ScaleProfile().withName("ydagfuaxbe") - .withCapacity(new ScaleProfileCapacity().withMin(45811298).withMax(427242708)); + ScaleProfile model = new ScaleProfile().withName("qkrhahvljua") + .withCapacity(new ScaleProfileCapacity().withMin(1935710102).withMax(836090349)); model = BinaryData.fromObject(model).toObject(ScaleProfile.class); - Assertions.assertEquals("ydagfuaxbe", model.name()); - Assertions.assertEquals(45811298, model.capacity().min()); - Assertions.assertEquals(427242708, model.capacity().max()); + Assertions.assertEquals("qkrhahvljua", model.name()); + Assertions.assertEquals(1935710102, model.capacity().min()); + Assertions.assertEquals(836090349, model.capacity().max()); } } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/UserIdentityPropertiesTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/UserIdentityPropertiesTests.java index 4bfe1543df25..c64eba4aab03 100644 --- a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/UserIdentityPropertiesTests.java +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/UserIdentityPropertiesTests.java @@ -11,7 +11,7 @@ public final class UserIdentityPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { UserIdentityProperties model - = BinaryData.fromString("{\"principalId\":\"icbtwnpzao\",\"clientId\":\"uhrhcffcyddgl\"}") + = BinaryData.fromString("{\"principalId\":\"rbnlankxmyskp\",\"clientId\":\"enbtkcxywny\"}") .toObject(UserIdentityProperties.class); } diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/WebApplicationFirewallComponentVersionsTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/WebApplicationFirewallComponentVersionsTests.java new file mode 100644 index 000000000000..bf0c8a0df2f0 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/WebApplicationFirewallComponentVersionsTests.java @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.nginx.models.WebApplicationFirewallComponentVersions; +import org.junit.jupiter.api.Assertions; + +public final class WebApplicationFirewallComponentVersionsTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + WebApplicationFirewallComponentVersions model + = BinaryData.fromString("{\"wafEngineVersion\":\"ni\",\"wafNginxVersion\":\"kxfbkpycgklwndn\"}") + .toObject(WebApplicationFirewallComponentVersions.class); + Assertions.assertEquals("ni", model.wafEngineVersion()); + Assertions.assertEquals("kxfbkpycgklwndn", model.wafNginxVersion()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + WebApplicationFirewallComponentVersions model + = new WebApplicationFirewallComponentVersions().withWafEngineVersion("ni") + .withWafNginxVersion("kxfbkpycgklwndn"); + model = BinaryData.fromObject(model).toObject(WebApplicationFirewallComponentVersions.class); + Assertions.assertEquals("ni", model.wafEngineVersion()); + Assertions.assertEquals("kxfbkpycgklwndn", model.wafNginxVersion()); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/WebApplicationFirewallPackageTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/WebApplicationFirewallPackageTests.java new file mode 100644 index 000000000000..b7f2bbec8eda --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/WebApplicationFirewallPackageTests.java @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.nginx.models.WebApplicationFirewallPackage; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; + +public final class WebApplicationFirewallPackageTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + WebApplicationFirewallPackage model + = BinaryData.fromString("{\"version\":\"nrjawgqwg\",\"revisionDatetime\":\"2021-10-10T15:46:25Z\"}") + .toObject(WebApplicationFirewallPackage.class); + Assertions.assertEquals("nrjawgqwg", model.version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-10-10T15:46:25Z"), model.revisionDatetime()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + WebApplicationFirewallPackage model = new WebApplicationFirewallPackage().withVersion("nrjawgqwg") + .withRevisionDatetime(OffsetDateTime.parse("2021-10-10T15:46:25Z")); + model = BinaryData.fromObject(model).toObject(WebApplicationFirewallPackage.class); + Assertions.assertEquals("nrjawgqwg", model.version()); + Assertions.assertEquals(OffsetDateTime.parse("2021-10-10T15:46:25Z"), model.revisionDatetime()); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/WebApplicationFirewallSettingsTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/WebApplicationFirewallSettingsTests.java new file mode 100644 index 000000000000..57b830c17692 --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/WebApplicationFirewallSettingsTests.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.nginx.models.ActivationState; +import com.azure.resourcemanager.nginx.models.WebApplicationFirewallSettings; +import org.junit.jupiter.api.Assertions; + +public final class WebApplicationFirewallSettingsTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + WebApplicationFirewallSettings model + = BinaryData.fromString("{\"activationState\":\"Enabled\"}").toObject(WebApplicationFirewallSettings.class); + Assertions.assertEquals(ActivationState.ENABLED, model.activationState()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + WebApplicationFirewallSettings model + = new WebApplicationFirewallSettings().withActivationState(ActivationState.ENABLED); + model = BinaryData.fromObject(model).toObject(WebApplicationFirewallSettings.class); + Assertions.assertEquals(ActivationState.ENABLED, model.activationState()); + } +} diff --git a/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/WebApplicationFirewallStatusTests.java b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/WebApplicationFirewallStatusTests.java new file mode 100644 index 000000000000..291c374286cf --- /dev/null +++ b/sdk/nginx/azure-resourcemanager-nginx/src/test/java/com/azure/resourcemanager/nginx/generated/WebApplicationFirewallStatusTests.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.nginx.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.nginx.models.WebApplicationFirewallStatus; + +public final class WebApplicationFirewallStatusTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + WebApplicationFirewallStatus model = BinaryData.fromString( + "{\"attackSignaturesPackage\":{\"version\":\"z\",\"revisionDatetime\":\"2021-06-30T00:10:41Z\"},\"botSignaturesPackage\":{\"version\":\"gicjooxdjeb\",\"revisionDatetime\":\"2021-10-10T15:28:34Z\"},\"threatCampaignsPackage\":{\"version\":\"cwwfvovbvme\",\"revisionDatetime\":\"2021-06-02T22:02:30Z\"},\"componentVersions\":{\"wafEngineVersion\":\"ivyhzceuojgjrwju\",\"wafNginxVersion\":\"iotwmcdytdxwit\"}}") + .toObject(WebApplicationFirewallStatus.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + WebApplicationFirewallStatus model = new WebApplicationFirewallStatus(); + model = BinaryData.fromObject(model).toObject(WebApplicationFirewallStatus.class); + } +} diff --git a/sdk/notificationhubs/azure-resourcemanager-notificationhubs/README.md b/sdk/notificationhubs/azure-resourcemanager-notificationhubs/README.md index 114998d7a186..20d5496823da 100644 --- a/sdk/notificationhubs/azure-resourcemanager-notificationhubs/README.md +++ b/sdk/notificationhubs/azure-resourcemanager-notificationhubs/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-notificationhubs - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fnotificationhubs%2Fazure-resourcemanager-notificationhubs%2FREADME.png) + diff --git a/sdk/notificationhubs/azure-resourcemanager-notificationhubs/pom.xml b/sdk/notificationhubs/azure-resourcemanager-notificationhubs/pom.xml index 5df443e6424a..03ad40ed84f4 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.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/oep/azure-resourcemanager-oep/README.md b/sdk/oep/azure-resourcemanager-oep/README.md index c8468bcc6a6f..34c511eadf46 100644 --- a/sdk/oep/azure-resourcemanager-oep/README.md +++ b/sdk/oep/azure-resourcemanager-oep/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-oep - 1.0.0-beta.2 + 1.0.0-beta.3 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Foep%2Fazure-resourcemanager-oep%2FREADME.png) + diff --git a/sdk/oep/azure-resourcemanager-oep/pom.xml b/sdk/oep/azure-resourcemanager-oep/pom.xml index 2b46eb349076..93b53a157a46 100644 --- a/sdk/oep/azure-resourcemanager-oep/pom.xml +++ b/sdk/oep/azure-resourcemanager-oep/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/openai/azure-ai-openai-assistants/CHANGELOG.md b/sdk/openai/azure-ai-openai-assistants/CHANGELOG.md index 410fb13bab05..1015f31986eb 100644 --- a/sdk/openai/azure-ai-openai-assistants/CHANGELOG.md +++ b/sdk/openai/azure-ai-openai-assistants/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.0.0-beta.5 (Unreleased) +## 1.0.0-beta.6 (Unreleased) ### Features Added @@ -10,6 +10,28 @@ ### Other Changes +## 1.0.0-beta.5 (2025-02-21) + +### Features Added + +- Added `include[]` query parameter for `getRunStep` methods to specify additional fields for the request. Currently only files are supported. + - Results added to run step details file search tool calls instances +- Added more `VectorStoreFileErrorCode`s. Specifically, `server_error`, `unsupported_file` and `invalid_file`. +- Added `AssistantsApiResponseFormatJsonSchema` as a possible value (previously, `text` and `json_object` where the only supported ones). +- Added Azure OpenAI services labels: `V2024_09_01_PREVIEW`, `V2024_10_01_PREVIEW`, `V2025_01_01_PREVIEW`. + +### Breaking Changes + +- Removed `AssistantsApiResponseFormatMode.NONE`. + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-json` to version `1.4.0`. +- Upgraded `azure-core` to version `1.55.2`. +- Upgraded `azure-core-http-netty` to version `1.15.10`. + ## 1.0.0-beta.4 (2024-08-29) ### Features Added diff --git a/sdk/openai/azure-ai-openai-assistants/README.md b/sdk/openai/azure-ai-openai-assistants/README.md index bc8394c2136c..b98a26a3c0a7 100644 --- a/sdk/openai/azure-ai-openai-assistants/README.md +++ b/sdk/openai/azure-ai-openai-assistants/README.md @@ -25,7 +25,7 @@ Use this library to: com.azure azure-ai-openai-assistants - 1.0.0-beta.3 + 1.0.0-beta.6 ``` [//]: # ({x-version-update-end}) @@ -354,4 +354,4 @@ For details on contributing to this repository, see the [contributing guide](htt [azure_subscription]: https://azure.microsoft.com/free/ [azure_identity]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/identity/azure-identity [function_tool_call_full_sample]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/openai/azure-ai-openai-assistants/src/samples/java/com/azure/ai/openai/assistants/FunctionToolCallSample.java -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fopenai%2Fassistants%2Fazure-ai-openai-assistants%2FREADME.png) + diff --git a/sdk/openai/azure-ai-openai-assistants/assets.json b/sdk/openai/azure-ai-openai-assistants/assets.json index 7de07bd5a222..ec7156dfb8e0 100644 --- a/sdk/openai/azure-ai-openai-assistants/assets.json +++ b/sdk/openai/azure-ai-openai-assistants/assets.json @@ -2,5 +2,5 @@ "AssetsRepo" : "Azure/azure-sdk-assets", "AssetsRepoPrefixPath" : "java", "TagPrefix" : "java/assistants/azure-ai-openai-assistants", - "Tag" : "java/assistants/azure-ai-openai-assistants_19cb2164a3" + "Tag" : "java/assistants/azure-ai-openai-assistants_f834cc9de4" } diff --git a/sdk/openai/azure-ai-openai-assistants/pom.xml b/sdk/openai/azure-ai-openai-assistants/pom.xml index afce4b3251ef..455790f1841c 100644 --- a/sdk/openai/azure-ai-openai-assistants/pom.xml +++ b/sdk/openai/azure-ai-openai-assistants/pom.xml @@ -14,7 +14,7 @@ com.azure azure-ai-openai-assistants - 1.0.0-beta.5 + 1.0.0-beta.6 jar Microsoft Azure Client Library for OpenAI Assistants @@ -60,17 +60,17 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 @@ -85,13 +85,13 @@ com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/AssistantsAsyncClient.java b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/AssistantsAsyncClient.java index cc7816580544..43f3d8e96f53 100644 --- a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/AssistantsAsyncClient.java +++ b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/AssistantsAsyncClient.java @@ -36,6 +36,7 @@ import com.azure.ai.openai.assistants.models.ListSortOrder; import com.azure.ai.openai.assistants.models.OpenAIFile; import com.azure.ai.openai.assistants.models.PageableList; +import com.azure.ai.openai.assistants.models.RunIncludes; import com.azure.ai.openai.assistants.models.RunStep; import com.azure.ai.openai.assistants.models.StreamUpdate; import com.azure.ai.openai.assistants.models.ThreadDeletionStatus; @@ -70,6 +71,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.stream.Collectors; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -1893,6 +1895,33 @@ public Mono> listRunSteps(String threadId, String runId, I assistantList.getLastId(), assistantList.isHasMore())); } + /** + * Gets a list of run steps from a thread run with additional included fields. + * + * @param threadId The ID of the thread that was run. + * @param runId The ID of the run to list steps from. + * @param runInclude A list of additional fields to include in the response. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of run steps from a thread run on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> listRunSteps(String threadId, String runId, List runInclude) { + RequestOptions requestOptions = new RequestOptions(); + if (runInclude != null && !runInclude.isEmpty()) { + requestOptions.addQueryParam("include[]", + runInclude.stream().map(item -> Objects.toString(item, "")).collect(Collectors.joining(",")), false); + } + return listRunStepsWithResponse(threadId, runId, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(OpenAIPageableListOfRunStep.class)) + .map(assistantList -> PageableListAccessHelper.create(assistantList.getData(), assistantList.getFirstId(), + assistantList.getLastId(), assistantList.isHasMore())); + } + /** * Gets a list of run steps from a thread run. * @@ -2475,6 +2504,63 @@ public Flux createRunStream(String threadId, CreateRunOptions crea return openAIServerSentEvents.getEvents(); } + /** + * Creates a new run for an assistant thread with additional included fields. + * + * @param threadId The ID of the thread to run. + * @param createRunOptions The details used when creating a new run of an assistant thread. + * @param runInclude A list of additional fields to include in the response. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by the server. + * @throws ClientAuthenticationException thrown if the request is rejected by the server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by the server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by the server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return data representing a single evaluation run of an assistant thread on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createRun(String threadId, CreateRunOptions createRunOptions, List runInclude) { + RequestOptions requestOptions = new RequestOptions(); + if (runInclude != null && !runInclude.isEmpty()) { + requestOptions.addQueryParam("include[]", + runInclude.stream().map(Object::toString).collect(Collectors.joining(",")), false); + } + return createRunWithResponse(threadId, BinaryData.fromObject(createRunOptions), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(ThreadRun.class)); + } + + /** + * Creates a new run for an assistant thread returning a stream of updates with additional included fields. + * + * @param threadId The ID of the thread to run. + * @param createRunOptions The details for the run to create. + * @param runInclude A list of additional fields to include in the response. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by the server. + * @throws ClientAuthenticationException thrown if the request is rejected by the server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by the server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by the server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a stream of updates from the assistant thread run on successful completion of {@link Flux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public Flux createRunStream(String threadId, CreateRunOptions createRunOptions, + List runInclude) { + RequestOptions requestOptions = new RequestOptions(); + if (runInclude != null && !runInclude.isEmpty()) { + requestOptions.addQueryParam("include[]", + runInclude.stream().map(Object::toString).collect(Collectors.joining(",")), false); + } + BinaryData inputJson = BinaryData.fromObject(createRunOptions); + BinaryData adjustedJson = OpenAIUtils.injectStreamJsonField(inputJson, true); + Flux responseStream = createRunWithResponse(threadId, adjustedJson, requestOptions) + .flatMapMany(response -> response.getValue().toFluxByteBuffer()); + OpenAIServerSentEvents openAIServerSentEvents = new OpenAIServerSentEvents(responseStream); + return openAIServerSentEvents.getEvents(); + } + /** * Modifies an existing thread run. * @@ -3919,4 +4005,35 @@ public Mono createVectorStoreFileBatch(String vectorStoreI .flatMap(FluxUtil::toMono) .map(protocolMethodData -> protocolMethodData.toObject(VectorStoreFileBatch.class)); } + + /** + * Gets a single run step from a thread run. + * + * @param threadId The ID of the thread that was run. + * @param runId The ID of the specific run to retrieve the step from. + * @param stepId The ID of the step to retrieve information about. + * @param runInclude A list of additional fields to include in the response. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a single run step from a thread run on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getRunStep(String threadId, String runId, String stepId, List runInclude) { + // Generated convenience method for getRunStepWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (runInclude != null) { + requestOptions.addQueryParam("include[]", + runInclude.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); + } + return getRunStepWithResponse(threadId, runId, stepId, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(RunStep.class)); + } } diff --git a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/AssistantsClient.java b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/AssistantsClient.java index 876d522fbcad..568f65783726 100644 --- a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/AssistantsClient.java +++ b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/AssistantsClient.java @@ -36,6 +36,7 @@ import com.azure.ai.openai.assistants.models.ListSortOrder; import com.azure.ai.openai.assistants.models.OpenAIFile; import com.azure.ai.openai.assistants.models.PageableList; +import com.azure.ai.openai.assistants.models.RunIncludes; import com.azure.ai.openai.assistants.models.RunStep; import com.azure.ai.openai.assistants.models.StreamUpdate; import com.azure.ai.openai.assistants.models.ThreadDeletionStatus; @@ -70,6 +71,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.stream.Collectors; import reactor.core.publisher.Flux; /** @@ -1940,6 +1942,32 @@ public PageableList listRunSteps(String threadId, String runId) { runStepList.isHasMore()); } + /** + * Gets a list of run steps from a thread run with additional run include parameters. + * + * @param threadId The ID of the thread that was run. + * @param runId The ID of the run from which to list steps. + * @param runInclude A list of extra fields to include in the response. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by the server. + * @throws ClientAuthenticationException thrown if the request is rejected by the server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by the server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by the server on status code 409. + * @return a {@link PageableList} of {@link RunStep} from the thread run. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public PageableList listRunSteps(String threadId, String runId, List runInclude) { + RequestOptions requestOptions = new RequestOptions(); + if (runInclude != null && !runInclude.isEmpty()) { + requestOptions.addQueryParam("include[]", + runInclude.stream().map(Object::toString).collect(Collectors.joining(",")), false); + } + OpenAIPageableListOfRunStep runStepList = listRunStepsWithResponse(threadId, runId, requestOptions).getValue() + .toObject(OpenAIPageableListOfRunStep.class); + return PageableListAccessHelper.create(runStepList.getData(), runStepList.getFirstId(), runStepList.getLastId(), + runStepList.isHasMore()); + } + /** * Gets a list of previously uploaded files. * @@ -2485,6 +2513,59 @@ public IterableStream createRunStream(String threadId, String assi return new IterableStream<>(eventStream.getEvents()); } + /** + * Creates a new run for an assistant thread with additional run include parameters. + * + * @param threadId The ID of the thread to run. + * @param createRunOptions The details for creating a new run. + * @param runInclude A list of extra fields to include in the response. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by the server. + * @throws ClientAuthenticationException thrown if the request is rejected by the server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by the server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by the server on status code 409. + * @return a {@link ThreadRun} representing the created run. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public ThreadRun createRun(String threadId, CreateRunOptions createRunOptions, List runInclude) { + RequestOptions requestOptions = new RequestOptions(); + if (runInclude != null && !runInclude.isEmpty()) { + requestOptions.addQueryParam("include[]", + runInclude.stream().map(Object::toString).collect(Collectors.joining(",")), false); + } + return createRunWithResponse(threadId, BinaryData.fromObject(createRunOptions), requestOptions).getValue() + .toObject(ThreadRun.class); + } + + /** + * Creates a new run for an assistant thread returning a stream of updates with additional run include parameters. + * + * @param threadId The ID of the thread to run. + * @param createRunOptions The details for creating the run. + * @param runInclude A list of extra fields to include in the response. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by the server. + * @throws ClientAuthenticationException thrown if the request is rejected by the server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by the server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by the server on status code 409. + * @return an {@link IterableStream} of {@link StreamUpdate} representing the response stream. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public IterableStream createRunStream(String threadId, CreateRunOptions createRunOptions, + List runInclude) { + RequestOptions requestOptions = new RequestOptions(); + if (runInclude != null && !runInclude.isEmpty()) { + requestOptions.addQueryParam("include[]", + runInclude.stream().map(Object::toString).collect(Collectors.joining(",")), false); + } + BinaryData inputJson = BinaryData.fromObject(createRunOptions); + BinaryData adjustedJson = OpenAIUtils.injectStreamJsonField(inputJson, true); + Flux responseStream + = createRunWithResponse(threadId, adjustedJson, requestOptions).getValue().toFluxByteBuffer(); + OpenAIServerSentEvents eventStream = new OpenAIServerSentEvents(responseStream); + return new IterableStream<>(eventStream.getEvents()); + } + /** * Modifies an existing thread run. * @@ -3932,4 +4013,34 @@ public VectorStoreFileBatch createVectorStoreFileBatch(String vectorStoreId, Lis .getValue() .toObject(VectorStoreFileBatch.class); } + + /** + * Gets a single run step from a thread run. + * + * @param threadId The ID of the thread that was run. + * @param runId The ID of the specific run to retrieve the step from. + * @param stepId The ID of the step to retrieve information about. + * @param runInclude A list of additional fields to include in the response. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a single run step from a thread run. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public RunStep getRunStep(String threadId, String runId, String stepId, List runInclude) { + // Generated convenience method for getRunStepWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (runInclude != null) { + requestOptions.addQueryParam("include[]", + runInclude.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); + } + return getRunStepWithResponse(threadId, runId, stepId, requestOptions).getValue().toObject(RunStep.class); + } } diff --git a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/AssistantsServiceVersion.java b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/AssistantsServiceVersion.java index 9e9fadb08ff1..7e5c0409fd8c 100644 --- a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/AssistantsServiceVersion.java +++ b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/AssistantsServiceVersion.java @@ -23,7 +23,22 @@ public enum AssistantsServiceVersion implements ServiceVersion { /** * Enum value 2024-07-01-preview. */ - V2024_07_01_PREVIEW("2024-07-01-preview"); + V2024_07_01_PREVIEW("2024-07-01-preview"), + + /** + * Enum value 2024-09-01-preview. + */ + V2024_09_01_PREVIEW("2024-09-01-preview"), + + /** + * Enum value 2024-10-01-preview. + */ + V2024_10_01_PREVIEW("2024-10-01-preview"), + + /** + * Enum value 2025-01-01-preview. + */ + V2025_01_01_PREVIEW("2025-01-01-preview"); private final String version; @@ -45,6 +60,6 @@ public String getVersion() { * @return The latest {@link AssistantsServiceVersion}. */ public static AssistantsServiceVersion getLatest() { - return V2024_07_01_PREVIEW; + return V2025_01_01_PREVIEW; } } diff --git a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/implementation/AssistantsClientImpl.java b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/implementation/AssistantsClientImpl.java index 098ebf6cd585..b1be05b67947 100644 --- a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/implementation/AssistantsClientImpl.java +++ b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/implementation/AssistantsClientImpl.java @@ -1178,7 +1178,7 @@ public Response createAssistantWithResponse(BinaryData assistantCrea * defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with * obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * beforeStringNoA cursor for use in pagination. before is an object ID that - * defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with + * defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with * obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the * list. * @@ -1259,7 +1259,7 @@ public Mono> listAssistantsWithResponseAsync(RequestOptions * defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with * obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * beforeStringNoA cursor for use in pagination. before is an object ID that - * defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with + * defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with * obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the * list. * @@ -2320,7 +2320,7 @@ public Response createMessageWithResponse(String threadId, BinaryDat * defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with * obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * beforeStringNoA cursor for use in pagination. before is an object ID that - * defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with + * defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with * obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the * list. * @@ -2402,7 +2402,7 @@ public Mono> listMessagesWithResponseAsync(String threadId, * defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with * obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * beforeStringNoA cursor for use in pagination. before is an object ID that - * defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with + * defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with * obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the * list. * @@ -2726,6 +2726,14 @@ public Response updateMessageWithResponse(String threadId, String me /** * Creates a new run for an assistant thread. + *

        Query Parameters

        + * + * + * + * + *
        Query Parameters
        NameTypeRequiredDescription
        include[]List<String>NoA list of additional fields to include in the + * response. In the form of "," separated string.
        + * You can add these to a request with {@link RequestOptions#addQueryParam} *

        Request Body Schema

        * *
        @@ -2773,6 +2781,7 @@ public Response updateMessageWithResponse(String threadId, String me
              *             type: String (Required)
              *         }
              *     ]
        +     *     parallel_tool_calls: Boolean (Optional)
              *     stream: Boolean (Optional)
              *     temperature: Double (Optional)
              *     top_p: Double (Optional)
        @@ -2836,6 +2845,7 @@ public Response updateMessageWithResponse(String threadId, String me
              *         last_messages: Integer (Optional)
              *     }
              *     tool_choice: BinaryData (Required)
        +     *     parallel_tool_calls: boolean (Required)
              *     response_format: BinaryData (Required)
              *     metadata (Required): {
              *         String: String (Required)
        @@ -2865,6 +2875,14 @@ public Mono> createRunWithResponseAsync(String threadId, Bi
         
             /**
              * Creates a new run for an assistant thread.
        +     * 

        Query Parameters

        + * + * + * + * + *
        Query Parameters
        NameTypeRequiredDescription
        include[]List<String>NoA list of additional fields to include in the + * response. In the form of "," separated string.
        + * You can add these to a request with {@link RequestOptions#addQueryParam} *

        Request Body Schema

        * *
        @@ -2912,6 +2930,7 @@ public Mono> createRunWithResponseAsync(String threadId, Bi
              *             type: String (Required)
              *         }
              *     ]
        +     *     parallel_tool_calls: Boolean (Optional)
              *     stream: Boolean (Optional)
              *     temperature: Double (Optional)
              *     top_p: Double (Optional)
        @@ -2975,6 +2994,7 @@ public Mono> createRunWithResponseAsync(String threadId, Bi
              *         last_messages: Integer (Optional)
              *     }
              *     tool_choice: BinaryData (Required)
        +     *     parallel_tool_calls: boolean (Required)
              *     response_format: BinaryData (Required)
              *     metadata (Required): {
              *         String: String (Required)
        @@ -3015,7 +3035,7 @@ public Response createRunWithResponse(String threadId, BinaryData cr
              * defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with
              * obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.
              * beforeStringNoA cursor for use in pagination. before is an object ID that
        -     * defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with
        +     * defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with
              * obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the
              * list.
              * 
        @@ -3068,6 +3088,7 @@ public Response createRunWithResponse(String threadId, BinaryData cr
              *                 last_messages: Integer (Optional)
              *             }
              *             tool_choice: BinaryData (Required)
        +     *             parallel_tool_calls: boolean (Required)
              *             response_format: BinaryData (Required)
              *             metadata (Required): {
              *                 String: String (Required)
        @@ -3111,7 +3132,7 @@ public Mono> listRunsWithResponseAsync(String threadId, Req
              * defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with
              * obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.
              * beforeStringNoA cursor for use in pagination. before is an object ID that
        -     * defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with
        +     * defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with
              * obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the
              * list.
              * 
        @@ -3164,6 +3185,7 @@ public Mono> listRunsWithResponseAsync(String threadId, Req
              *                 last_messages: Integer (Optional)
              *             }
              *             tool_choice: BinaryData (Required)
        +     *             parallel_tool_calls: boolean (Required)
              *             response_format: BinaryData (Required)
              *             metadata (Required): {
              *                 String: String (Required)
        @@ -3238,6 +3260,7 @@ public Response listRunsWithResponse(String threadId, RequestOptions
              *         last_messages: Integer (Optional)
              *     }
              *     tool_choice: BinaryData (Required)
        +     *     parallel_tool_calls: boolean (Required)
              *     response_format: BinaryData (Required)
              *     metadata (Required): {
              *         String: String (Required)
        @@ -3311,6 +3334,7 @@ public Mono> getRunWithResponseAsync(String threadId, Strin
              *         last_messages: Integer (Optional)
              *     }
              *     tool_choice: BinaryData (Required)
        +     *     parallel_tool_calls: boolean (Required)
              *     response_format: BinaryData (Required)
              *     metadata (Required): {
              *         String: String (Required)
        @@ -3393,6 +3417,7 @@ public Response getRunWithResponse(String threadId, String runId, Re
              *         last_messages: Integer (Optional)
              *     }
              *     tool_choice: BinaryData (Required)
        +     *     parallel_tool_calls: boolean (Required)
              *     response_format: BinaryData (Required)
              *     metadata (Required): {
              *         String: String (Required)
        @@ -3480,6 +3505,7 @@ public Mono> updateRunWithResponseAsync(String threadId, St
              *         last_messages: Integer (Optional)
              *     }
              *     tool_choice: BinaryData (Required)
        +     *     parallel_tool_calls: boolean (Required)
              *     response_format: BinaryData (Required)
              *     metadata (Required): {
              *         String: String (Required)
        @@ -3571,6 +3597,7 @@ public Response updateRunWithResponse(String threadId, String runId,
              *         last_messages: Integer (Optional)
              *     }
              *     tool_choice: BinaryData (Required)
        +     *     parallel_tool_calls: boolean (Required)
              *     response_format: BinaryData (Required)
              *     metadata (Required): {
              *         String: String (Required)
        @@ -3663,6 +3690,7 @@ public Mono> submitToolOutputsToRunWithResponseAsync(String
              *         last_messages: Integer (Optional)
              *     }
              *     tool_choice: BinaryData (Required)
        +     *     parallel_tool_calls: boolean (Required)
              *     response_format: BinaryData (Required)
              *     metadata (Required): {
              *         String: String (Required)
        @@ -3737,6 +3765,7 @@ public Response submitToolOutputsToRunWithResponse(String threadId,
              *         last_messages: Integer (Optional)
              *     }
              *     tool_choice: BinaryData (Required)
        +     *     parallel_tool_calls: boolean (Required)
              *     response_format: BinaryData (Required)
              *     metadata (Required): {
              *         String: String (Required)
        @@ -3810,6 +3839,7 @@ public Mono> cancelRunWithResponseAsync(String threadId, St
              *         last_messages: Integer (Optional)
              *     }
              *     tool_choice: BinaryData (Required)
        +     *     parallel_tool_calls: boolean (Required)
              *     response_format: BinaryData (Required)
              *     metadata (Required): {
              *         String: String (Required)
        @@ -3878,6 +3908,7 @@ public Response cancelRunWithResponse(String threadId, String runId,
              *             type: String (Required)
              *         }
              *     ]
        +     *     parallel_tool_calls: Boolean (Optional)
              *     tool_resources (Optional): {
              *         code_interpreter (Optional): {
              *             file_ids (Optional): [
        @@ -3953,6 +3984,7 @@ public Response cancelRunWithResponse(String threadId, String runId,
              *         last_messages: Integer (Optional)
              *     }
              *     tool_choice: BinaryData (Required)
        +     *     parallel_tool_calls: boolean (Required)
              *     response_format: BinaryData (Required)
              *     metadata (Required): {
              *         String: String (Required)
        @@ -4024,6 +4056,7 @@ public Mono> createThreadAndRunWithResponseAsync(BinaryData
              *             type: String (Required)
              *         }
              *     ]
        +     *     parallel_tool_calls: Boolean (Optional)
              *     tool_resources (Optional): {
              *         code_interpreter (Optional): {
              *             file_ids (Optional): [
        @@ -4099,6 +4132,7 @@ public Mono> createThreadAndRunWithResponseAsync(BinaryData
              *         last_messages: Integer (Optional)
              *     }
              *     tool_choice: BinaryData (Required)
        +     *     parallel_tool_calls: boolean (Required)
              *     response_format: BinaryData (Required)
              *     metadata (Required): {
              *         String: String (Required)
        @@ -4126,6 +4160,14 @@ public Response createThreadAndRunWithResponse(BinaryData createAndR
         
             /**
              * Gets a single run step from a thread run.
        +     * 

        Query Parameters

        + * + * + * + * + *
        Query Parameters
        NameTypeRequiredDescription
        include[]List<String>NoA list of additional fields to include in the + * response. In the form of "," separated string.
        + * You can add these to a request with {@link RequestOptions#addQueryParam} *

        Response Body Schema

        * *
        @@ -4182,6 +4224,14 @@ public Mono> getRunStepWithResponseAsync(String threadId, S
         
             /**
              * Gets a single run step from a thread run.
        +     * 

        Query Parameters

        + * + * + * + * + *
        Query Parameters
        NameTypeRequiredDescription
        include[]List<String>NoA list of additional fields to include in the + * response. In the form of "," separated string.
        + * You can add these to a request with {@link RequestOptions#addQueryParam} *

        Response Body Schema

        * *
        @@ -4242,6 +4292,8 @@ public Response getRunStepWithResponse(String threadId, String runId
              * 
              * 
              * 
        +     * 
              * 
              * 
              * 
              * 
        Query Parameters
        NameTypeRequiredDescription
        include[]List<String>NoA list of additional fields to include in the + * response. In the form of "," separated string.
        limitIntegerNoA limit on the number of objects to be returned. Limit can range * between 1 and 100, and the default is 20.
        orderStringNoSort order by the created_at timestamp of the objects. asc for @@ -4250,7 +4302,7 @@ public Response getRunStepWithResponse(String threadId, String runId * defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with * obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.
        beforeStringNoA cursor for use in pagination. before is an object ID that - * defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with + * defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with * obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the * list.
        @@ -4323,6 +4375,8 @@ public Mono> listRunStepsWithResponseAsync(String threadId, * * * + * * * * *
        Query Parameters
        NameTypeRequiredDescription
        include[]List<String>NoA list of additional fields to include in the + * response. In the form of "," separated string.
        limitIntegerNoA limit on the number of objects to be returned. Limit can range * between 1 and 100, and the default is 20.
        orderStringNoSort order by the created_at timestamp of the objects. asc for @@ -4331,7 +4385,7 @@ public Mono> listRunStepsWithResponseAsync(String threadId, * defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with * obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.
        beforeStringNoA cursor for use in pagination. before is an object ID that - * defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with + * defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with * obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the * list.
        @@ -4748,7 +4802,7 @@ public Response getFileContentWithResponse(String fileId, RequestOpt * defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with * obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * beforeStringNoA cursor for use in pagination. before is an object ID that - * defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with + * defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with * obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the * list. * @@ -4821,7 +4875,7 @@ public Mono> listVectorStoresWithResponseAsync(RequestOptio * defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with * obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * beforeStringNoA cursor for use in pagination. before is an object ID that - * defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with + * defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with * obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the * list. * @@ -5337,7 +5391,7 @@ public Response deleteVectorStoreWithResponse(String vectorStoreId, * defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with * obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * beforeStringNoA cursor for use in pagination. before is an object ID that - * defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with + * defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with * obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the * list. * @@ -5357,7 +5411,7 @@ public Response deleteVectorStoreWithResponse(String vectorStoreId, * vector_store_id: String (Required) * status: String(in_progress/completed/failed/cancelled) (Required) * last_error (Required): { - * code: String(internal_error/file_not_found/parsing_error/unhandled_mime_type) (Required) + * code: String(server_error/unsupported_file/invalid_file) (Required) * message: String (Required) * } * chunking_strategy (Required): { @@ -5405,7 +5459,7 @@ public Mono> listVectorStoreFilesWithResponseAsync(String v * defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with * obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * beforeStringNoA cursor for use in pagination. before is an object ID that - * defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with + * defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with * obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the * list. * @@ -5425,7 +5479,7 @@ public Mono> listVectorStoreFilesWithResponseAsync(String v * vector_store_id: String (Required) * status: String(in_progress/completed/failed/cancelled) (Required) * last_error (Required): { - * code: String(internal_error/file_not_found/parsing_error/unhandled_mime_type) (Required) + * code: String(server_error/unsupported_file/invalid_file) (Required) * message: String (Required) * } * chunking_strategy (Required): { @@ -5482,7 +5536,7 @@ public Response listVectorStoreFilesWithResponse(String vectorStoreI * vector_store_id: String (Required) * status: String(in_progress/completed/failed/cancelled) (Required) * last_error (Required): { - * code: String(internal_error/file_not_found/parsing_error/unhandled_mime_type) (Required) + * code: String(server_error/unsupported_file/invalid_file) (Required) * message: String (Required) * } * chunking_strategy (Required): { @@ -5538,7 +5592,7 @@ public Mono> createVectorStoreFileWithResponseAsync(String * vector_store_id: String (Required) * status: String(in_progress/completed/failed/cancelled) (Required) * last_error (Required): { - * code: String(internal_error/file_not_found/parsing_error/unhandled_mime_type) (Required) + * code: String(server_error/unsupported_file/invalid_file) (Required) * message: String (Required) * } * chunking_strategy (Required): { @@ -5580,7 +5634,7 @@ public Response createVectorStoreFileWithResponse(String vectorStore * vector_store_id: String (Required) * status: String(in_progress/completed/failed/cancelled) (Required) * last_error (Required): { - * code: String(internal_error/file_not_found/parsing_error/unhandled_mime_type) (Required) + * code: String(server_error/unsupported_file/invalid_file) (Required) * message: String (Required) * } * chunking_strategy (Required): { @@ -5622,7 +5676,7 @@ public Mono> getVectorStoreFileWithResponseAsync(String vec * vector_store_id: String (Required) * status: String(in_progress/completed/failed/cancelled) (Required) * last_error (Required): { - * code: String(internal_error/file_not_found/parsing_error/unhandled_mime_type) (Required) + * code: String(server_error/unsupported_file/invalid_file) (Required) * message: String (Required) * } * chunking_strategy (Required): { @@ -6009,7 +6063,7 @@ public Response cancelVectorStoreFileBatchWithResponse(String vector * defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with * obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * beforeStringNoA cursor for use in pagination. before is an object ID that - * defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with + * defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with * obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the * list. * @@ -6029,7 +6083,7 @@ public Response cancelVectorStoreFileBatchWithResponse(String vector * vector_store_id: String (Required) * status: String(in_progress/completed/failed/cancelled) (Required) * last_error (Required): { - * code: String(internal_error/file_not_found/parsing_error/unhandled_mime_type) (Required) + * code: String(server_error/unsupported_file/invalid_file) (Required) * message: String (Required) * } * chunking_strategy (Required): { @@ -6078,7 +6132,7 @@ public Mono> listVectorStoreFileBatchFilesWithResponseAsync * defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with * obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. * beforeStringNoA cursor for use in pagination. before is an object ID that - * defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with + * defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with * obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the * list. * @@ -6098,7 +6152,7 @@ public Mono> listVectorStoreFileBatchFilesWithResponseAsync * vector_store_id: String (Required) * status: String(in_progress/completed/failed/cancelled) (Required) * last_error (Required): { - * code: String(internal_error/file_not_found/parsing_error/unhandled_mime_type) (Required) + * code: String(server_error/unsupported_file/invalid_file) (Required) * message: String (Required) * } * chunking_strategy (Required): { diff --git a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/ApiResponseFormat.java b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/ApiResponseFormat.java index 084aba93e31b..4fc29e8e7089 100644 --- a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/ApiResponseFormat.java +++ b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/ApiResponseFormat.java @@ -54,4 +54,10 @@ public static ApiResponseFormat fromString(String name) { public static Collection values() { return values(ApiResponseFormat.class); } + + /** + * Using `json_schema` format will ensure the model matches the supplied JSON schema. + */ + @Generated + public static final ApiResponseFormat JSON_SCHEMA = fromString("json_schema"); } diff --git a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/AssistantsApiResponseFormat.java b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/AssistantsApiResponseFormat.java index 01d625f8a308..b9c42534504c 100644 --- a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/AssistantsApiResponseFormat.java +++ b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/AssistantsApiResponseFormat.java @@ -3,8 +3,8 @@ // Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.ai.openai.assistants.models; -import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -16,19 +16,20 @@ * be passed to the Run. * If `text` the model can return text or any value needed. */ -@Fluent -public final class AssistantsApiResponseFormat implements JsonSerializable { +@Immutable +public class AssistantsApiResponseFormat implements JsonSerializable { /* - * Must be one of `text` or `json_object`. + * Must be one of `text`, `json_object` or `json_schema` . */ @Generated - private ApiResponseFormat type; + private ApiResponseFormat type = ApiResponseFormat.fromString("AssistantsApiResponseFormat"); /** * Creates an instance of AssistantsApiResponseFormat class. */ - private AssistantsApiResponseFormat() { + @Generated + public AssistantsApiResponseFormat() { } /** @@ -41,7 +42,7 @@ public AssistantsApiResponseFormat(ApiResponseFormat type) { } /** - * Get the type property: Must be one of `text` or `json_object`. + * Get the type property: Must be one of `text`, `json_object` or `json_schema` . * * @return the type value. */ @@ -50,18 +51,6 @@ public ApiResponseFormat getType() { return this.type; } - /** - * Set the type property: Must be one of `text` or `json_object`. - * - * @param type the type value to set. - * @return the AssistantsApiResponseFormat object itself. - */ - @Generated - public AssistantsApiResponseFormat setType(ApiResponseFormat type) { - this.type = type; - return this; - } - /** * {@inheritDoc} */ @@ -83,6 +72,37 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { */ @Generated public static AssistantsApiResponseFormat 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 AssistantsApiResponseFormatText.fromJson(readerToUse.reset()); + } else if ("json_object".equals(discriminatorValue)) { + return AssistantsApiResponseFormatJsonObject.fromJson(readerToUse.reset()); + } else if ("json_schema".equals(discriminatorValue)) { + return AssistantsApiResponseFormatJsonSchema.fromJson(readerToUse.reset()); + } else { + return fromJsonKnownDiscriminator(readerToUse.reset()); + } + } + }); + } + + @Generated + static AssistantsApiResponseFormat fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { AssistantsApiResponseFormat deserializedAssistantsApiResponseFormat = new AssistantsApiResponseFormat(); while (reader.nextToken() != JsonToken.END_OBJECT) { diff --git a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/AssistantsApiResponseFormatJsonObject.java b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/AssistantsApiResponseFormatJsonObject.java new file mode 100644 index 000000000000..21ca6d2c6bb7 --- /dev/null +++ b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/AssistantsApiResponseFormatJsonObject.java @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.openai.assistants.models; + +import com.azure.core.annotation.Generated; +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; + +/** + * An object describing expected output of the model as a JSON object. + */ +@Immutable +public final class AssistantsApiResponseFormatJsonObject extends AssistantsApiResponseFormat { + + /* + * Must be one of `text`, `json_object` or `json_schema` . + */ + @Generated + private ApiResponseFormat type = ApiResponseFormat.JSON_OBJECT; + + /** + * Creates an instance of AssistantsApiResponseFormatJsonObject class. + */ + @Generated + public AssistantsApiResponseFormatJsonObject() { + } + + /** + * Get the type property: Must be one of `text`, `json_object` or `json_schema` . + * + * @return the type value. + */ + @Generated + @Override + public ApiResponseFormat 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 AssistantsApiResponseFormatJsonObject from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssistantsApiResponseFormatJsonObject 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 AssistantsApiResponseFormatJsonObject. + */ + @Generated + public static AssistantsApiResponseFormatJsonObject fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssistantsApiResponseFormatJsonObject deserializedAssistantsApiResponseFormatJsonObject + = new AssistantsApiResponseFormatJsonObject(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("type".equals(fieldName)) { + deserializedAssistantsApiResponseFormatJsonObject.type + = ApiResponseFormat.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + return deserializedAssistantsApiResponseFormatJsonObject; + }); + } +} diff --git a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/AssistantsApiResponseFormatJsonSchema.java b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/AssistantsApiResponseFormatJsonSchema.java new file mode 100644 index 000000000000..6a559315aae5 --- /dev/null +++ b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/AssistantsApiResponseFormatJsonSchema.java @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.openai.assistants.models; + +import com.azure.core.annotation.Generated; +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; + +/** + * An object describing expected output of the model to match a JSON schema. + */ +@Immutable +public final class AssistantsApiResponseFormatJsonSchema extends AssistantsApiResponseFormat { + + /* + * Must be one of `text`, `json_object` or `json_schema` . + */ + @Generated + private ApiResponseFormat type = ApiResponseFormat.JSON_SCHEMA; + + /* + * The JSON schema that the model must output. + */ + @Generated + private final AssistantsApiResponseFormatJsonSchemaJsonSchema jsonSchema; + + /** + * Creates an instance of AssistantsApiResponseFormatJsonSchema class. + * + * @param jsonSchema the jsonSchema value to set. + */ + @Generated + public AssistantsApiResponseFormatJsonSchema(AssistantsApiResponseFormatJsonSchemaJsonSchema jsonSchema) { + this.jsonSchema = jsonSchema; + } + + /** + * Get the type property: Must be one of `text`, `json_object` or `json_schema` . + * + * @return the type value. + */ + @Generated + @Override + public ApiResponseFormat getType() { + return this.type; + } + + /** + * Get the jsonSchema property: The JSON schema that the model must output. + * + * @return the jsonSchema value. + */ + @Generated + public AssistantsApiResponseFormatJsonSchemaJsonSchema getJsonSchema() { + return this.jsonSchema; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("json_schema", this.jsonSchema); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssistantsApiResponseFormatJsonSchema from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssistantsApiResponseFormatJsonSchema 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 AssistantsApiResponseFormatJsonSchema. + */ + @Generated + public static AssistantsApiResponseFormatJsonSchema fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssistantsApiResponseFormatJsonSchemaJsonSchema jsonSchema = null; + ApiResponseFormat type = ApiResponseFormat.JSON_SCHEMA; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("json_schema".equals(fieldName)) { + jsonSchema = AssistantsApiResponseFormatJsonSchemaJsonSchema.fromJson(reader); + } else if ("type".equals(fieldName)) { + type = ApiResponseFormat.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + AssistantsApiResponseFormatJsonSchema deserializedAssistantsApiResponseFormatJsonSchema + = new AssistantsApiResponseFormatJsonSchema(jsonSchema); + deserializedAssistantsApiResponseFormatJsonSchema.type = type; + return deserializedAssistantsApiResponseFormatJsonSchema; + }); + } +} diff --git a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/AssistantsApiResponseFormatJsonSchemaJsonSchema.java b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/AssistantsApiResponseFormatJsonSchemaJsonSchema.java new file mode 100644 index 000000000000..152e48f6342e --- /dev/null +++ b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/AssistantsApiResponseFormatJsonSchemaJsonSchema.java @@ -0,0 +1,185 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.openai.assistants.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.util.BinaryData; +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 AssistantsApiResponseFormatJsonSchemaJsonSchema model. + */ +@Fluent +public final class AssistantsApiResponseFormatJsonSchemaJsonSchema + implements JsonSerializable { + + /* + * A description of what the response format is for, used by the model to determine how to respond in the format. + */ + @Generated + private String description; + + /* + * The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length + * of 64. + */ + @Generated + private final String name; + + /* + * The schema for the response format, described as a JSON Schema object. + */ + @Generated + private final BinaryData schema; + + /* + * Whether to enable strict schema adherence when generating the output. If set to true, the model will always + * follow the exact schema defined in the `schema` field. Only a subset of JSON Schema is supported when `strict` is + * `true`. To learn more, read the Structured Outputs guide. + */ + @Generated + private Boolean strict; + + /** + * Creates an instance of AssistantsApiResponseFormatJsonSchemaJsonSchema class. + * + * @param name the name value to set. + * @param schema the schema value to set. + */ + @Generated + public AssistantsApiResponseFormatJsonSchemaJsonSchema(String name, BinaryData schema) { + this.name = name; + this.schema = schema; + } + + /** + * Get the description property: A description of what the response format is for, used by the model to determine + * how to respond in the format. + * + * @return the description value. + */ + @Generated + public String getDescription() { + return this.description; + } + + /** + * Set the description property: A description of what the response format is for, used by the model to determine + * how to respond in the format. + * + * @param description the description value to set. + * @return the AssistantsApiResponseFormatJsonSchemaJsonSchema object itself. + */ + @Generated + public AssistantsApiResponseFormatJsonSchemaJsonSchema setDescription(String description) { + this.description = description; + return this; + } + + /** + * Get the name property: The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores and dashes, + * with a maximum length of 64. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the schema property: The schema for the response format, described as a JSON Schema object. + * + * @return the schema value. + */ + @Generated + public BinaryData getSchema() { + return this.schema; + } + + /** + * Get the strict property: Whether to enable strict schema adherence when generating the output. If set to true, + * the model will always follow the exact schema defined in the `schema` field. Only a subset of JSON Schema is + * supported when `strict` is `true`. To learn more, read the Structured Outputs guide. + * + * @return the strict value. + */ + @Generated + public Boolean isStrict() { + return this.strict; + } + + /** + * Set the strict property: Whether to enable strict schema adherence when generating the output. If set to true, + * the model will always follow the exact schema defined in the `schema` field. Only a subset of JSON Schema is + * supported when `strict` is `true`. To learn more, read the Structured Outputs guide. + * + * @param strict the strict value to set. + * @return the AssistantsApiResponseFormatJsonSchemaJsonSchema object itself. + */ + @Generated + public AssistantsApiResponseFormatJsonSchemaJsonSchema setStrict(Boolean strict) { + this.strict = strict; + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeFieldName("schema"); + this.schema.writeTo(jsonWriter); + jsonWriter.writeStringField("description", this.description); + jsonWriter.writeBooleanField("strict", this.strict); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssistantsApiResponseFormatJsonSchemaJsonSchema from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssistantsApiResponseFormatJsonSchemaJsonSchema 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 AssistantsApiResponseFormatJsonSchemaJsonSchema. + */ + @Generated + public static AssistantsApiResponseFormatJsonSchemaJsonSchema fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String name = null; + BinaryData schema = null; + String description = null; + Boolean strict = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("name".equals(fieldName)) { + name = reader.getString(); + } else if ("schema".equals(fieldName)) { + schema = reader.getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped())); + } else if ("description".equals(fieldName)) { + description = reader.getString(); + } else if ("strict".equals(fieldName)) { + strict = reader.getNullable(JsonReader::getBoolean); + } else { + reader.skipChildren(); + } + } + AssistantsApiResponseFormatJsonSchemaJsonSchema deserializedAssistantsApiResponseFormatJsonSchemaJsonSchema + = new AssistantsApiResponseFormatJsonSchemaJsonSchema(name, schema); + deserializedAssistantsApiResponseFormatJsonSchemaJsonSchema.description = description; + deserializedAssistantsApiResponseFormatJsonSchemaJsonSchema.strict = strict; + return deserializedAssistantsApiResponseFormatJsonSchemaJsonSchema; + }); + } +} diff --git a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/AssistantsApiResponseFormatMode.java b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/AssistantsApiResponseFormatMode.java index eafae255a1ad..ef3aa7012a54 100644 --- a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/AssistantsApiResponseFormatMode.java +++ b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/AssistantsApiResponseFormatMode.java @@ -18,12 +18,6 @@ public final class AssistantsApiResponseFormatMode extends ExpandableStringEnum< @Generated public static final AssistantsApiResponseFormatMode AUTO = fromString("auto"); - /** - * Setting the value to `none`, will result in a 400 Bad request. - */ - @Generated - public static final AssistantsApiResponseFormatMode NONE = fromString("none"); - /** * Creates a new instance of AssistantsApiResponseFormatMode value. * diff --git a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/AssistantsApiResponseFormatText.java b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/AssistantsApiResponseFormatText.java new file mode 100644 index 000000000000..79f548696852 --- /dev/null +++ b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/AssistantsApiResponseFormatText.java @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.openai.assistants.models; + +import com.azure.core.annotation.Generated; +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; + +/** + * An object describing expected output of the model as text. + */ +@Immutable +public final class AssistantsApiResponseFormatText extends AssistantsApiResponseFormat { + + /* + * Must be one of `text`, `json_object` or `json_schema` . + */ + @Generated + private ApiResponseFormat type = ApiResponseFormat.TEXT; + + /** + * Creates an instance of AssistantsApiResponseFormatText class. + */ + @Generated + public AssistantsApiResponseFormatText() { + } + + /** + * Get the type property: Must be one of `text`, `json_object` or `json_schema` . + * + * @return the type value. + */ + @Generated + @Override + public ApiResponseFormat 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 AssistantsApiResponseFormatText from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssistantsApiResponseFormatText 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 AssistantsApiResponseFormatText. + */ + @Generated + public static AssistantsApiResponseFormatText fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AssistantsApiResponseFormatText deserializedAssistantsApiResponseFormatText + = new AssistantsApiResponseFormatText(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("type".equals(fieldName)) { + deserializedAssistantsApiResponseFormatText.type = ApiResponseFormat.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + return deserializedAssistantsApiResponseFormatText; + }); + } +} diff --git a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/AssistantsApiResponseFormatType.java b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/AssistantsApiResponseFormatType.java new file mode 100644 index 000000000000..7bd5e15af378 --- /dev/null +++ b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/AssistantsApiResponseFormatType.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.ai.openai.assistants.models; + +/** + * Defines values for AssistantsApiResponseFormatType. + */ +public enum AssistantsApiResponseFormatType { + /** + * Enum value text. + */ + TEXT("text"); + + /** + * The actual serialized value for a AssistantsApiResponseFormatType instance. + */ + private final String value; + + AssistantsApiResponseFormatType(String value) { + this.value = value; + } + + /** + * Parses a serialized value to a AssistantsApiResponseFormatType instance. + * + * @param value the serialized value to parse. + * @return the parsed AssistantsApiResponseFormatType object, or null if unable to parse. + */ + public static AssistantsApiResponseFormatType fromString(String value) { + if (value == null) { + return null; + } + AssistantsApiResponseFormatType[] items = AssistantsApiResponseFormatType.values(); + for (AssistantsApiResponseFormatType item : items) { + if (item.toString().equalsIgnoreCase(value)) { + return item; + } + } + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return this.value; + } +} diff --git a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/CreateAndRunThreadOptions.java b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/CreateAndRunThreadOptions.java index 10493076d589..c27351a674ad 100644 --- a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/CreateAndRunThreadOptions.java +++ b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/CreateAndRunThreadOptions.java @@ -206,6 +206,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStringField("model", this.model); jsonWriter.writeStringField("instructions", this.instructions); jsonWriter.writeArrayField("tools", this.tools, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeBooleanField("parallel_tool_calls", this.parallelToolCalls); jsonWriter.writeJsonField("tool_resources", this.toolResources); jsonWriter.writeBooleanField("stream", this.stream); jsonWriter.writeNumberField("temperature", this.temperature); @@ -242,6 +243,7 @@ public static CreateAndRunThreadOptions fromJson(JsonReader jsonReader) throws I String model = null; String instructions = null; List tools = null; + Boolean parallelToolCalls = null; UpdateToolResourcesOptions toolResources = null; Boolean stream = null; Double temperature = null; @@ -265,6 +267,8 @@ public static CreateAndRunThreadOptions fromJson(JsonReader jsonReader) throws I instructions = reader.getString(); } else if ("tools".equals(fieldName)) { tools = reader.readArray(reader1 -> ToolDefinition.fromJson(reader1)); + } else if ("parallel_tool_calls".equals(fieldName)) { + parallelToolCalls = reader.getNullable(JsonReader::getBoolean); } else if ("tool_resources".equals(fieldName)) { toolResources = UpdateToolResourcesOptions.fromJson(reader); } else if ("stream".equals(fieldName)) { @@ -297,6 +301,7 @@ public static CreateAndRunThreadOptions fromJson(JsonReader jsonReader) throws I deserializedCreateAndRunThreadOptions.model = model; deserializedCreateAndRunThreadOptions.instructions = instructions; deserializedCreateAndRunThreadOptions.tools = tools; + deserializedCreateAndRunThreadOptions.parallelToolCalls = parallelToolCalls; deserializedCreateAndRunThreadOptions.toolResources = toolResources; deserializedCreateAndRunThreadOptions.stream = stream; deserializedCreateAndRunThreadOptions.temperature = temperature; @@ -617,4 +622,32 @@ public CreateAndRunThreadOptions setResponseFormat(AssistantsApiResponseFormatOp } return this; } + + /* + * Whether to enable parallel function calling during tool use. + */ + @Generated + private Boolean parallelToolCalls; + + /** + * Get the parallelToolCalls property: Whether to enable parallel function calling during tool use. + * + * @return the parallelToolCalls value. + */ + @Generated + public Boolean isParallelToolCalls() { + return this.parallelToolCalls; + } + + /** + * Set the parallelToolCalls property: Whether to enable parallel function calling during tool use. + * + * @param parallelToolCalls the parallelToolCalls value to set. + * @return the CreateAndRunThreadOptions object itself. + */ + @Generated + public CreateAndRunThreadOptions setParallelToolCalls(Boolean parallelToolCalls) { + this.parallelToolCalls = parallelToolCalls; + return this; + } } diff --git a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/CreateRunOptions.java b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/CreateRunOptions.java index 6048bd34d1fb..6f46951a03ec 100644 --- a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/CreateRunOptions.java +++ b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/CreateRunOptions.java @@ -214,6 +214,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeArrayField("additional_messages", this.additionalMessages, (writer, element) -> writer.writeJson(element)); jsonWriter.writeArrayField("tools", this.tools, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeBooleanField("parallel_tool_calls", this.parallelToolCalls); jsonWriter.writeBooleanField("stream", this.stream); jsonWriter.writeNumberField("temperature", this.temperature); jsonWriter.writeNumberField("top_p", this.topP); @@ -250,6 +251,7 @@ public static CreateRunOptions fromJson(JsonReader jsonReader) throws IOExceptio String additionalInstructions = null; List additionalMessages = null; List tools = null; + Boolean parallelToolCalls = null; Boolean stream = null; Double temperature = null; Double topP = null; @@ -274,6 +276,8 @@ public static CreateRunOptions fromJson(JsonReader jsonReader) throws IOExceptio additionalMessages = reader.readArray(reader1 -> ThreadMessage.fromJson(reader1)); } else if ("tools".equals(fieldName)) { tools = reader.readArray(reader1 -> ToolDefinition.fromJson(reader1)); + } else if ("parallel_tool_calls".equals(fieldName)) { + parallelToolCalls = reader.getNullable(JsonReader::getBoolean); } else if ("stream".equals(fieldName)) { stream = reader.getNullable(JsonReader::getBoolean); } else if ("temperature".equals(fieldName)) { @@ -304,6 +308,7 @@ public static CreateRunOptions fromJson(JsonReader jsonReader) throws IOExceptio deserializedCreateRunOptions.additionalInstructions = additionalInstructions; deserializedCreateRunOptions.additionalMessages = additionalMessages; deserializedCreateRunOptions.tools = tools; + deserializedCreateRunOptions.parallelToolCalls = parallelToolCalls; deserializedCreateRunOptions.stream = stream; deserializedCreateRunOptions.temperature = temperature; deserializedCreateRunOptions.topP = topP; @@ -620,4 +625,32 @@ public CreateRunOptions setResponseFormat(AssistantsApiResponseFormatOption resp } return this; } + + /* + * Whether to enable parallel function calling during tool use. + */ + @Generated + private Boolean parallelToolCalls; + + /** + * Get the parallelToolCalls property: Whether to enable parallel function calling during tool use. + * + * @return the parallelToolCalls value. + */ + @Generated + public Boolean isParallelToolCalls() { + return this.parallelToolCalls; + } + + /** + * Set the parallelToolCalls property: Whether to enable parallel function calling during tool use. + * + * @param parallelToolCalls the parallelToolCalls value to set. + * @return the CreateRunOptions object itself. + */ + @Generated + public CreateRunOptions setParallelToolCalls(Boolean parallelToolCalls) { + this.parallelToolCalls = parallelToolCalls; + return this; + } } diff --git a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/FileSearchToolCallResult.java b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/FileSearchToolCallResult.java new file mode 100644 index 000000000000..6574b5a8aa30 --- /dev/null +++ b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/FileSearchToolCallResult.java @@ -0,0 +1,152 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.openai.assistants.models; + +import com.azure.core.annotation.Generated; +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; +import java.util.List; + +/** + * File search tool call result. + */ +@Immutable +public final class FileSearchToolCallResult implements JsonSerializable { + + /* + * The ID of the file that result was found in. + */ + @Generated + private final String fileId; + + /* + * The name of the file that result was found in. + */ + @Generated + private final String fileName; + + /* + * The score of the result. All values must be a floating point number between 0 and 1. + */ + @Generated + private final double score; + + /* + * The content of the result that was found. The content is only included if requested via the include query + * parameter. + */ + @Generated + private List content; + + /** + * Creates an instance of FileSearchToolCallResult class. + * + * @param fileId the fileId value to set. + * @param fileName the fileName value to set. + * @param score the score value to set. + */ + @Generated + private FileSearchToolCallResult(String fileId, String fileName, double score) { + this.fileId = fileId; + this.fileName = fileName; + this.score = score; + } + + /** + * Get the fileId property: The ID of the file that result was found in. + * + * @return the fileId value. + */ + @Generated + public String getFileId() { + return this.fileId; + } + + /** + * Get the fileName property: The name of the file that result was found in. + * + * @return the fileName value. + */ + @Generated + public String getFileName() { + return this.fileName; + } + + /** + * Get the score property: The score of the result. All values must be a floating point number between 0 and 1. + * + * @return the score value. + */ + @Generated + public double getScore() { + return this.score; + } + + /** + * Get the content property: The content of the result that was found. The content is only included if requested via + * the include query parameter. + * + * @return the content value. + */ + @Generated + public List getContent() { + return this.content; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("file_id", this.fileId); + jsonWriter.writeStringField("file_name", this.fileName); + jsonWriter.writeDoubleField("score", this.score); + jsonWriter.writeArrayField("content", this.content, (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of FileSearchToolCallResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of FileSearchToolCallResult 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 FileSearchToolCallResult. + */ + @Generated + public static FileSearchToolCallResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String fileId = null; + String fileName = null; + double score = 0.0; + List content = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("file_id".equals(fieldName)) { + fileId = reader.getString(); + } else if ("file_name".equals(fieldName)) { + fileName = reader.getString(); + } else if ("score".equals(fieldName)) { + score = reader.getDouble(); + } else if ("content".equals(fieldName)) { + content = reader.readArray(reader1 -> FileSearchToolCallResultContentItem.fromJson(reader1)); + } else { + reader.skipChildren(); + } + } + FileSearchToolCallResult deserializedFileSearchToolCallResult + = new FileSearchToolCallResult(fileId, fileName, score); + deserializedFileSearchToolCallResult.content = content; + return deserializedFileSearchToolCallResult; + }); + } +} diff --git a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/FileSearchToolCallResultContentItem.java b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/FileSearchToolCallResultContentItem.java new file mode 100644 index 000000000000..1fe388fb85e3 --- /dev/null +++ b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/FileSearchToolCallResultContentItem.java @@ -0,0 +1,100 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.openai.assistants.models; + +import com.azure.core.annotation.Generated; +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; + +/** + * Content item in a file search result. + */ +@Immutable +public final class FileSearchToolCallResultContentItem + implements JsonSerializable { + + /* + * The type of the content. + */ + @Generated + private AssistantsApiResponseFormatType type; + + /* + * The text content of the file. + */ + @Generated + private String text; + + /** + * Creates an instance of FileSearchToolCallResultContentItem class. + */ + @Generated + private FileSearchToolCallResultContentItem() { + } + + /** + * Get the type property: The type of the content. + * + * @return the type value. + */ + @Generated + public AssistantsApiResponseFormatType getType() { + return this.type; + } + + /** + * Get the text property: The text content of the file. + * + * @return the text value. + */ + @Generated + public String getText() { + return this.text; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + jsonWriter.writeStringField("text", this.text); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of FileSearchToolCallResultContentItem from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of FileSearchToolCallResultContentItem 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 FileSearchToolCallResultContentItem. + */ + @Generated + public static FileSearchToolCallResultContentItem fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + FileSearchToolCallResultContentItem deserializedFileSearchToolCallResultContentItem + = new FileSearchToolCallResultContentItem(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("type".equals(fieldName)) { + deserializedFileSearchToolCallResultContentItem.type + = AssistantsApiResponseFormatType.fromString(reader.getString()); + } else if ("text".equals(fieldName)) { + deserializedFileSearchToolCallResultContentItem.text = reader.getString(); + } else { + reader.skipChildren(); + } + } + return deserializedFileSearchToolCallResultContentItem; + }); + } +} diff --git a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/RunIncludes.java b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/RunIncludes.java new file mode 100644 index 000000000000..12296e4ca20c --- /dev/null +++ b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/RunIncludes.java @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.openai.assistants.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Values to for the includes parameter in the create run operation. + */ +public final class RunIncludes extends ExpandableStringEnum { + + /** + * Fetch the file search result content. + */ + @Generated + public static final RunIncludes FILE_SEARCH_CONTENT + = fromString("step_details.tool_calls[*].file_search.results[*].content"); + + /** + * Creates a new instance of RunIncludes value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public RunIncludes() { + } + + /** + * Creates or finds a RunIncludes from its string representation. + * + * @param name a name to look for. + * @return the corresponding RunIncludes. + */ + @Generated + public static RunIncludes fromString(String name) { + return fromString(name, RunIncludes.class); + } + + /** + * Gets known RunIncludes values. + * + * @return known RunIncludes values. + */ + @Generated + public static Collection values() { + return values(RunIncludes.class); + } +} diff --git a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/RunStepFileSearchToolCall.java b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/RunStepFileSearchToolCall.java index 309bef61d241..147e02f3b296 100644 --- a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/RunStepFileSearchToolCall.java +++ b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/RunStepFileSearchToolCall.java @@ -9,7 +9,7 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.Map; +import java.util.List; /** * A record of a call to a file search tool, issued by the model in evaluation of a defined tool, that represents @@ -25,22 +25,10 @@ public final class RunStepFileSearchToolCall extends RunStepToolCall { private String type = "file_search"; /* - * Reserved for future use. + * The results of the file search. */ @Generated - private final Map fileSearch; - - /** - * Creates an instance of RunStepFileSearchToolCall class. - * - * @param id the id value to set. - * @param fileSearch the fileSearch value to set. - */ - @Generated - private RunStepFileSearchToolCall(String id, Map fileSearch) { - super(id); - this.fileSearch = fileSearch; - } + private final List fileSearch; /** * Get the type property: The object type. @@ -54,12 +42,12 @@ public String getType() { } /** - * Get the fileSearch property: Reserved for future use. + * Get the fileSearch property: The results of the file search. * * @return the fileSearch value. */ @Generated - public Map getFileSearch() { + public List getFileSearch() { return this.fileSearch; } @@ -71,7 +59,7 @@ public Map getFileSearch() { public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("id", getId()); - jsonWriter.writeMapField("file_search", this.fileSearch, (writer, element) -> writer.writeString(element)); + jsonWriter.writeArrayField("file_search", this.fileSearch, (writer, element) -> writer.writeJson(element)); jsonWriter.writeStringField("type", this.type); return jsonWriter.writeEndObject(); } @@ -89,7 +77,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { public static RunStepFileSearchToolCall fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { String id = null; - Map fileSearch = null; + List fileSearch = null; String type = "file_search"; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); @@ -97,7 +85,7 @@ public static RunStepFileSearchToolCall fromJson(JsonReader jsonReader) throws I if ("id".equals(fieldName)) { id = reader.getString(); } else if ("file_search".equals(fieldName)) { - fileSearch = reader.readMap(reader1 -> reader1.getString()); + fileSearch = reader.readArray(reader1 -> FileSearchToolCallResult.fromJson(reader1)); } else if ("type".equals(fieldName)) { type = reader.getString(); } else { @@ -110,4 +98,16 @@ public static RunStepFileSearchToolCall fromJson(JsonReader jsonReader) throws I return deserializedRunStepFileSearchToolCall; }); } + + /** + * Creates an instance of RunStepFileSearchToolCall class. + * + * @param id the id value to set. + * @param fileSearch the fileSearch value to set. + */ + @Generated + private RunStepFileSearchToolCall(String id, List fileSearch) { + super(id); + this.fileSearch = fileSearch; + } } diff --git a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/ThreadRun.java b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/ThreadRun.java index dc6411977191..c4a52e359f84 100644 --- a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/ThreadRun.java +++ b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/ThreadRun.java @@ -344,6 +344,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeJsonField("truncation_strategy", this.truncationStrategy); jsonWriter.writeFieldName("tool_choice"); this.toolChoice.writeTo(jsonWriter); + jsonWriter.writeBooleanField("parallel_tool_calls", this.parallelToolCalls); jsonWriter.writeFieldName("response_format"); this.responseFormat.writeTo(jsonWriter); jsonWriter.writeMapField("metadata", this.metadata, (writer, element) -> writer.writeString(element)); @@ -385,6 +386,7 @@ public static ThreadRun fromJson(JsonReader jsonReader) throws IOException { Integer maxCompletionTokens = null; TruncationObject truncationStrategy = null; BinaryData toolChoice = null; + boolean parallelToolCalls = false; BinaryData responseFormat = null; Map metadata = null; RequiredAction requiredAction = null; @@ -451,6 +453,8 @@ public static ThreadRun fromJson(JsonReader jsonReader) throws IOException { } else if ("tool_choice".equals(fieldName)) { toolChoice = reader.getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped())); + } else if ("parallel_tool_calls".equals(fieldName)) { + parallelToolCalls = reader.getBoolean(); } else if ("response_format".equals(fieldName)) { responseFormat = reader.getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped())); @@ -469,7 +473,7 @@ public static ThreadRun fromJson(JsonReader jsonReader) throws IOException { ThreadRun deserializedThreadRun = new ThreadRun(id, threadId, assistantId, status, lastError, model, instructions, tools, createdAt, expiresAt, startedAt, completedAt, cancelledAt, failedAt, incompleteDetails, usage, maxPromptTokens, - maxCompletionTokens, truncationStrategy, toolChoice, responseFormat, metadata); + maxCompletionTokens, truncationStrategy, toolChoice, parallelToolCalls, responseFormat, metadata); deserializedThreadRun.requiredAction = requiredAction; deserializedThreadRun.temperature = temperature; deserializedThreadRun.topP = topP; @@ -554,6 +558,83 @@ public IncompleteRunDetails getIncompleteDetails() { @Generated private final BinaryData responseFormat; + /** + * Get the temperature property: The sampling temperature used for this run. If not set, defaults to 1. + * + * @return the temperature value. + */ + @Generated + public Double getTemperature() { + return this.temperature; + } + + /** + * Get the topP property: The nucleus sampling value used for this run. If not set, defaults to 1. + * + * @return the topP value. + */ + @Generated + public Double getTopP() { + return this.topP; + } + + /** + * Get the maxPromptTokens property: The maximum number of prompt tokens specified to have been used over the course + * of the run. + * + * @return the maxPromptTokens value. + */ + @Generated + public Integer getMaxPromptTokens() { + return this.maxPromptTokens; + } + + /** + * Get the maxCompletionTokens property: The maximum number of completion tokens specified to have been used over + * the course of the run. + * + * @return the maxCompletionTokens value. + */ + @Generated + public Integer getMaxCompletionTokens() { + return this.maxCompletionTokens; + } + + /** + * Get the truncationStrategy property: The strategy to use for dropping messages as the context windows moves + * forward. + * + * @return the truncationStrategy value. + */ + @Generated + public TruncationObject getTruncationStrategy() { + return this.truncationStrategy; + } + + /** + * Get the toolChoice property: Controls whether or not and which tool is called by the model. + * + * @return the toolChoice value. + */ + public AssistantsApiToolChoiceOption getToolChoice() { + return AssistantsApiToolChoiceOption.fromBinaryData(this.toolChoice); + } + + /** + * Get the responseFormat property: The response format of the tool calls used in this run. + * + * @return the responseFormat value. + */ + public AssistantsApiResponseFormatOption getResponseFormat() { + return AssistantsApiResponseFormatOption.fromBinaryData(this.responseFormat); + } + + /* + * Whether to enable parallel function calling during tool use. + */ + @Generated + private final boolean parallelToolCalls; + /** * Creates an instance of ThreadRun class. * @@ -577,6 +658,7 @@ public IncompleteRunDetails getIncompleteDetails() { * @param maxCompletionTokens the maxCompletionTokens value to set. * @param truncationStrategy the truncationStrategy value to set. * @param toolChoice the toolChoice value to set. + * @param parallelToolCalls the parallelToolCalls value to set. * @param responseFormat the responseFormat value to set. * @param metadata the metadata value to set. */ @@ -586,7 +668,7 @@ private ThreadRun(String id, String threadId, String assistantId, RunStatus stat OffsetDateTime expiresAt, OffsetDateTime startedAt, OffsetDateTime completedAt, OffsetDateTime cancelledAt, OffsetDateTime failedAt, IncompleteRunDetails incompleteDetails, RunCompletionUsage usage, Integer maxPromptTokens, Integer maxCompletionTokens, TruncationObject truncationStrategy, - BinaryData toolChoice, BinaryData responseFormat, Map metadata) { + BinaryData toolChoice, boolean parallelToolCalls, BinaryData responseFormat, Map metadata) { this.id = id; this.threadId = threadId; this.assistantId = assistantId; @@ -631,78 +713,18 @@ private ThreadRun(String id, String threadId, String assistantId, RunStatus stat this.maxCompletionTokens = maxCompletionTokens; this.truncationStrategy = truncationStrategy; this.toolChoice = toolChoice; + this.parallelToolCalls = parallelToolCalls; this.responseFormat = responseFormat; this.metadata = metadata; } /** - * Get the temperature property: The sampling temperature used for this run. If not set, defaults to 1. - * - * @return the temperature value. - */ - @Generated - public Double getTemperature() { - return this.temperature; - } - - /** - * Get the topP property: The nucleus sampling value used for this run. If not set, defaults to 1. - * - * @return the topP value. - */ - @Generated - public Double getTopP() { - return this.topP; - } - - /** - * Get the maxPromptTokens property: The maximum number of prompt tokens specified to have been used over the course - * of the run. - * - * @return the maxPromptTokens value. - */ - @Generated - public Integer getMaxPromptTokens() { - return this.maxPromptTokens; - } - - /** - * Get the maxCompletionTokens property: The maximum number of completion tokens specified to have been used over - * the course of the run. - * - * @return the maxCompletionTokens value. - */ - @Generated - public Integer getMaxCompletionTokens() { - return this.maxCompletionTokens; - } - - /** - * Get the truncationStrategy property: The strategy to use for dropping messages as the context windows moves - * forward. + * Get the parallelToolCalls property: Whether to enable parallel function calling during tool use. * - * @return the truncationStrategy value. + * @return the parallelToolCalls value. */ @Generated - public TruncationObject getTruncationStrategy() { - return this.truncationStrategy; - } - - /** - * Get the toolChoice property: Controls whether or not and which tool is called by the model. - * - * @return the toolChoice value. - */ - public AssistantsApiToolChoiceOption getToolChoice() { - return AssistantsApiToolChoiceOption.fromBinaryData(this.toolChoice); - } - - /** - * Get the responseFormat property: The response format of the tool calls used in this run. - * - * @return the responseFormat value. - */ - public AssistantsApiResponseFormatOption getResponseFormat() { - return AssistantsApiResponseFormatOption.fromBinaryData(this.responseFormat); + public boolean isParallelToolCalls() { + return this.parallelToolCalls; } } diff --git a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/VectorStoreFileErrorCode.java b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/VectorStoreFileErrorCode.java index 8f84f3c38a1f..e7c578e2fc08 100644 --- a/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/VectorStoreFileErrorCode.java +++ b/sdk/openai/azure-ai-openai-assistants/src/main/java/com/azure/ai/openai/assistants/models/VectorStoreFileErrorCode.java @@ -12,30 +12,6 @@ */ public final class VectorStoreFileErrorCode extends ExpandableStringEnum { - /** - * An internal error occurred. - */ - @Generated - public static final VectorStoreFileErrorCode INTERNAL_ERROR = fromString("internal_error"); - - /** - * The file was not found. - */ - @Generated - public static final VectorStoreFileErrorCode FILE_NOT_FOUND = fromString("file_not_found"); - - /** - * The file could not be parsed. - */ - @Generated - public static final VectorStoreFileErrorCode PARSING_ERROR = fromString("parsing_error"); - - /** - * The file has an unhandled mime type. - */ - @Generated - public static final VectorStoreFileErrorCode UNHANDLED_MIME_TYPE = fromString("unhandled_mime_type"); - /** * Creates a new instance of VectorStoreFileErrorCode value. * @@ -66,4 +42,22 @@ public static VectorStoreFileErrorCode fromString(String name) { public static Collection values() { return values(VectorStoreFileErrorCode.class); } + + /** + * The server encountered an error. + */ + @Generated + public static final VectorStoreFileErrorCode SERVER_ERROR = fromString("server_error"); + + /** + * The file format is not supported. + */ + @Generated + public static final VectorStoreFileErrorCode UNSUPPORTED_FILE = fromString("unsupported_file"); + + /** + * The file is invalid. + */ + @Generated + public static final VectorStoreFileErrorCode INVALID_FILE = fromString("invalid_file"); } diff --git a/sdk/openai/azure-ai-openai-assistants/src/main/resources/META-INF/azure-ai-openai-assistants_apiview_properties.json b/sdk/openai/azure-ai-openai-assistants/src/main/resources/META-INF/azure-ai-openai-assistants_apiview_properties.json index a86dad23ca77..5e204d9ef5e5 100644 --- a/sdk/openai/azure-ai-openai-assistants/src/main/resources/META-INF/azure-ai-openai-assistants_apiview_properties.json +++ b/sdk/openai/azure-ai-openai-assistants/src/main/resources/META-INF/azure-ai-openai-assistants_apiview_properties.json @@ -185,7 +185,12 @@ "com.azure.ai.openai.assistants.models.AssistantThread": "Azure.AI.OpenAI.Assistants.AssistantThread", "com.azure.ai.openai.assistants.models.AssistantThreadCreationOptions": "Azure.AI.OpenAI.Assistants.AssistantThreadCreationOptions", "com.azure.ai.openai.assistants.models.AssistantsApiResponseFormat": "Azure.AI.OpenAI.Assistants.AssistantsApiResponseFormat", + "com.azure.ai.openai.assistants.models.AssistantsApiResponseFormatJsonObject": "Azure.AI.OpenAI.Assistants.AssistantsApiResponseFormatJsonObject", + "com.azure.ai.openai.assistants.models.AssistantsApiResponseFormatJsonSchema": "Azure.AI.OpenAI.Assistants.AssistantsApiResponseFormatJsonSchema", + "com.azure.ai.openai.assistants.models.AssistantsApiResponseFormatJsonSchemaJsonSchema": "Azure.AI.OpenAI.Assistants.AssistantsApiResponseFormatJsonSchema.jsonSchema.anonymous", "com.azure.ai.openai.assistants.models.AssistantsApiResponseFormatMode": "Azure.AI.OpenAI.Assistants.AssistantsApiResponseFormatMode", + "com.azure.ai.openai.assistants.models.AssistantsApiResponseFormatText": "Azure.AI.OpenAI.Assistants.AssistantsApiResponseFormatText", + "com.azure.ai.openai.assistants.models.AssistantsApiResponseFormatType": null, "com.azure.ai.openai.assistants.models.AssistantsApiToolChoiceOptionMode": "Azure.AI.OpenAI.Assistants.AssistantsApiToolChoiceOptionMode", "com.azure.ai.openai.assistants.models.AssistantsNamedToolChoice": "Azure.AI.OpenAI.Assistants.AssistantsNamedToolChoice", "com.azure.ai.openai.assistants.models.AssistantsNamedToolChoiceType": "Azure.AI.OpenAI.Assistants.AssistantsNamedToolChoiceType", @@ -201,6 +206,8 @@ "com.azure.ai.openai.assistants.models.FileDeletionStatus": "Azure.AI.OpenAI.Assistants.FileDeletionStatus", "com.azure.ai.openai.assistants.models.FileDetails": null, "com.azure.ai.openai.assistants.models.FilePurpose": "Azure.AI.OpenAI.Assistants.FilePurpose", + "com.azure.ai.openai.assistants.models.FileSearchToolCallResult": "Azure.AI.OpenAI.Assistants.FileSearchToolCallResult", + "com.azure.ai.openai.assistants.models.FileSearchToolCallResultContentItem": "Azure.AI.OpenAI.Assistants.FileSearchToolCallResultContentItem", "com.azure.ai.openai.assistants.models.FileSearchToolDefinition": "Azure.AI.OpenAI.Assistants.FileSearchToolDefinition", "com.azure.ai.openai.assistants.models.FileSearchToolDefinitionDetails": "Azure.AI.OpenAI.Assistants.FileSearchToolDefinitionDetails", "com.azure.ai.openai.assistants.models.FileSearchToolResource": "Azure.AI.OpenAI.Assistants.FileSearchToolResource", @@ -245,6 +252,7 @@ "com.azure.ai.openai.assistants.models.RequiredToolCall": "Azure.AI.OpenAI.Assistants.RequiredToolCall", "com.azure.ai.openai.assistants.models.RunCompletionUsage": "Azure.AI.OpenAI.Assistants.RunCompletionUsage", "com.azure.ai.openai.assistants.models.RunError": "Azure.AI.OpenAI.Assistants.RunError", + "com.azure.ai.openai.assistants.models.RunIncludes": "Azure.AI.OpenAI.Assistants.RunIncludes", "com.azure.ai.openai.assistants.models.RunStatus": "Azure.AI.OpenAI.Assistants.RunStatus", "com.azure.ai.openai.assistants.models.RunStep": "Azure.AI.OpenAI.Assistants.RunStep", "com.azure.ai.openai.assistants.models.RunStepCodeInterpreterImageOutput": "Azure.AI.OpenAI.Assistants.RunStepCodeInterpreterImageOutput", 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 b15eb7737e86..c7cbcdc734a3 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 @@ -33,7 +33,7 @@ public class AzureRunThreadAsyncTest extends AssistantsClientTestBase { @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.assistants.TestUtils#getTestParameters") public void submitMessageAndRun(HttpClient httpClient, AssistantsServiceVersion serviceVersion) { - client = getAssistantsAsyncClient(httpClient); + client = getAssistantsAsyncClient(httpClient, serviceVersion); String mathTutorAssistantId = createMathTutorAssistant(client); String threadId = createThread(client); submitMessageAndRunRunner(message -> { @@ -91,7 +91,7 @@ public void submitMessageAndRun(HttpClient httpClient, AssistantsServiceVersion @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.assistants.TestUtils#getTestParameters") public void submitMessageAndRunWithResponse(HttpClient httpClient, AssistantsServiceVersion serviceVersion) { - client = getAssistantsAsyncClient(httpClient); + client = getAssistantsAsyncClient(httpClient, serviceVersion); String mathTutorAssistantId = createMathTutorAssistant(client); String threadId = createThread(client); submitMessageAndRunRunner(message -> { @@ -152,7 +152,7 @@ public void submitMessageAndRunWithResponse(HttpClient httpClient, AssistantsSer @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.assistants.TestUtils#getTestParameters") public void createThreadAndRun(HttpClient httpClient, AssistantsServiceVersion serviceVersion) { - client = getAssistantsAsyncClient(httpClient); + client = getAssistantsAsyncClient(httpClient, serviceVersion); String mathTutorAssistantId = createMathTutorAssistant(client); createThreadAndRunRunner(createAndRunThreadOptions -> { AtomicReference runReference = new AtomicReference<>(); @@ -204,7 +204,7 @@ public void createThreadAndRun(HttpClient httpClient, AssistantsServiceVersion s @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.assistants.TestUtils#getTestParameters") public void createThreadAndRunWithResponse(HttpClient httpClient, AssistantsServiceVersion serviceVersion) { - client = getAssistantsAsyncClient(httpClient); + client = getAssistantsAsyncClient(httpClient, serviceVersion); String mathTutorAssistantId = createMathTutorAssistant(client); createThreadAndRunRunner(createAndRunThreadOptions -> { AtomicReference runReference = new AtomicReference<>(); diff --git a/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/implementation/AssistantApiFormatSerializerTests.java b/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/implementation/AssistantApiFormatSerializerTests.java index 72dc06c87df9..341a9fa8833e 100644 --- a/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/implementation/AssistantApiFormatSerializerTests.java +++ b/sdk/openai/azure-ai-openai-assistants/src/test/java/com/azure/ai/openai/assistants/implementation/AssistantApiFormatSerializerTests.java @@ -58,32 +58,32 @@ public void assistantCreationOptionJsonObjectFormat() { } @Test - public void assistantCreationOptionAutoMode() { + public void assistantCreationOptionJsonSchemaFormat() { AssistantCreationOptions assistantCreationOptions = new AssistantCreationOptions("gpt-4"); - assistantCreationOptions - .setResponseFormat(new AssistantsApiResponseFormatOption(AssistantsApiResponseFormatMode.AUTO)); + assistantCreationOptions.setResponseFormat( + new AssistantsApiResponseFormatOption(new AssistantsApiResponseFormat(ApiResponseFormat.JSON_SCHEMA))); AssistantsApiResponseFormatOption responseFormat = assistantCreationOptions.getResponseFormat(); BinaryData jsonBinaryData = BinaryData.fromObject(assistantCreationOptions); String json = jsonBinaryData.toString(); - assertEquals(AssistantsApiResponseFormatMode.AUTO, responseFormat.getMode()); - assertTrue(json.contains("\"response_format\":\"auto\"}")); + assertEquals(ApiResponseFormat.JSON_SCHEMA, responseFormat.getFormat().getType()); + assertTrue(json.contains("\"response_format\":{\"type\":\"json_schema\"}")); assertTrue(json.contains("\"model\":\"gpt-4\"")); } @Test - public void assistantCreationOptionNoneMode() { + public void assistantCreationOptionAutoMode() { AssistantCreationOptions assistantCreationOptions = new AssistantCreationOptions("gpt-4"); assistantCreationOptions - .setResponseFormat(new AssistantsApiResponseFormatOption(AssistantsApiResponseFormatMode.NONE)); + .setResponseFormat(new AssistantsApiResponseFormatOption(AssistantsApiResponseFormatMode.AUTO)); AssistantsApiResponseFormatOption responseFormat = assistantCreationOptions.getResponseFormat(); BinaryData jsonBinaryData = BinaryData.fromObject(assistantCreationOptions); String json = jsonBinaryData.toString(); - assertEquals(AssistantsApiResponseFormatMode.NONE, responseFormat.getMode()); - assertTrue(json.contains("\"response_format\":\"none\"}")); + assertEquals(AssistantsApiResponseFormatMode.AUTO, responseFormat.getMode()); + assertTrue(json.contains("\"response_format\":\"auto\"}")); assertTrue(json.contains("\"model\":\"gpt-4\"")); } @@ -118,30 +118,31 @@ public void createRunOptionJsonObjectFormat() { } @Test - public void createRunOptionAutoMode() { + public void createRunOptionJsonSchemaFormat() { CreateRunOptions createRunOptions = new CreateRunOptions("abc123"); - createRunOptions.setResponseFormat(new AssistantsApiResponseFormatOption(AssistantsApiResponseFormatMode.AUTO)); + createRunOptions.setResponseFormat( + new AssistantsApiResponseFormatOption(new AssistantsApiResponseFormat(ApiResponseFormat.JSON_SCHEMA))); AssistantsApiResponseFormatOption responseFormat = createRunOptions.getResponseFormat(); BinaryData jsonBinaryData = BinaryData.fromObject(createRunOptions); String json = jsonBinaryData.toString(); - assertEquals(AssistantsApiResponseFormatMode.AUTO, responseFormat.getMode()); - assertTrue(json.contains("\"response_format\":\"auto\"}")); + assertEquals(ApiResponseFormat.JSON_SCHEMA, responseFormat.getFormat().getType()); + assertTrue(json.contains("\"response_format\":{\"type\":\"json_schema\"}")); assertTrue(json.contains("\"assistant_id\":\"abc123\"")); } @Test - public void createRunOptionNoneMode() { + public void createRunOptionAutoMode() { CreateRunOptions createRunOptions = new CreateRunOptions("abc123"); - createRunOptions.setResponseFormat(new AssistantsApiResponseFormatOption(AssistantsApiResponseFormatMode.NONE)); + createRunOptions.setResponseFormat(new AssistantsApiResponseFormatOption(AssistantsApiResponseFormatMode.AUTO)); AssistantsApiResponseFormatOption responseFormat = createRunOptions.getResponseFormat(); BinaryData jsonBinaryData = BinaryData.fromObject(createRunOptions); String json = jsonBinaryData.toString(); - assertEquals(AssistantsApiResponseFormatMode.NONE, responseFormat.getMode()); - assertTrue(json.contains("\"response_format\":\"none\"}")); + assertEquals(AssistantsApiResponseFormatMode.AUTO, responseFormat.getMode()); + assertTrue(json.contains("\"response_format\":\"auto\"}")); assertTrue(json.contains("\"assistant_id\":\"abc123\"")); } @@ -176,30 +177,31 @@ public void createAndRunThreadOptionJsonObjectFormat() { } @Test - public void createAndRunThreadOptionAutoMode() { + public void createAndRunThreadOptionJsonSchemaFormat() { CreateAndRunThreadOptions options = new CreateAndRunThreadOptions("abc123"); - options.setResponseFormat(new AssistantsApiResponseFormatOption(AssistantsApiResponseFormatMode.AUTO)); + options.setResponseFormat( + new AssistantsApiResponseFormatOption(new AssistantsApiResponseFormat(ApiResponseFormat.JSON_SCHEMA))); AssistantsApiResponseFormatOption responseFormat = options.getResponseFormat(); BinaryData jsonBinaryData = BinaryData.fromObject(options); String json = jsonBinaryData.toString(); - assertEquals(AssistantsApiResponseFormatMode.AUTO, responseFormat.getMode()); - assertTrue(json.contains("\"response_format\":\"auto\"")); + assertEquals(ApiResponseFormat.JSON_SCHEMA, responseFormat.getFormat().getType()); + assertTrue(json.contains("\"response_format\":{\"type\":\"json_schema\"}")); assertTrue(json.contains("\"assistant_id\":\"abc123\"")); } @Test - public void createAndRunThreadOptionNoneMode() { + public void createAndRunThreadOptionAutoMode() { CreateAndRunThreadOptions options = new CreateAndRunThreadOptions("abc123"); - options.setResponseFormat(new AssistantsApiResponseFormatOption(AssistantsApiResponseFormatMode.NONE)); + options.setResponseFormat(new AssistantsApiResponseFormatOption(AssistantsApiResponseFormatMode.AUTO)); AssistantsApiResponseFormatOption responseFormat = options.getResponseFormat(); BinaryData jsonBinaryData = BinaryData.fromObject(options); String json = jsonBinaryData.toString(); - assertEquals(AssistantsApiResponseFormatMode.NONE, responseFormat.getMode()); - assertTrue(json.contains("\"response_format\":\"none\"")); + assertEquals(AssistantsApiResponseFormatMode.AUTO, responseFormat.getMode()); + assertTrue(json.contains("\"response_format\":\"auto\"")); assertTrue(json.contains("\"assistant_id\":\"abc123\"")); } @@ -232,29 +234,30 @@ public void updateAssistantOptionJsonObjectFormat() { } @Test - public void updateAssistantOptionAutoMode() { + public void updateAssistantOptionJsonSchemaFormat() { UpdateAssistantOptions options = new UpdateAssistantOptions(); - options.setResponseFormat(new AssistantsApiResponseFormatOption(AssistantsApiResponseFormatMode.AUTO)); + options.setResponseFormat( + new AssistantsApiResponseFormatOption(new AssistantsApiResponseFormat(ApiResponseFormat.JSON_SCHEMA))); AssistantsApiResponseFormatOption responseFormat = options.getResponseFormat(); BinaryData jsonBinaryData = BinaryData.fromObject(options); String json = jsonBinaryData.toString(); - assertEquals(AssistantsApiResponseFormatMode.AUTO, responseFormat.getMode()); - assertTrue(json.contains("\"response_format\":\"auto\"")); + assertEquals(ApiResponseFormat.JSON_SCHEMA, responseFormat.getFormat().getType()); + assertTrue(json.contains("\"response_format\":{\"type\":\"json_schema\"}")); } @Test - public void updateAssistantOptionNoneMode() { + public void updateAssistantOptionAutoMode() { UpdateAssistantOptions options = new UpdateAssistantOptions(); - options.setResponseFormat(new AssistantsApiResponseFormatOption(AssistantsApiResponseFormatMode.NONE)); + options.setResponseFormat(new AssistantsApiResponseFormatOption(AssistantsApiResponseFormatMode.AUTO)); AssistantsApiResponseFormatOption responseFormat = options.getResponseFormat(); BinaryData jsonBinaryData = BinaryData.fromObject(options); String json = jsonBinaryData.toString(); - assertEquals(AssistantsApiResponseFormatMode.NONE, responseFormat.getMode()); - assertTrue(json.contains("\"response_format\":\"none\"")); + assertEquals(AssistantsApiResponseFormatMode.AUTO, responseFormat.getMode()); + assertTrue(json.contains("\"response_format\":\"auto\"")); } @Test @@ -280,23 +283,24 @@ public void assistantJsonObjectFormat() { } @Test - public void assistantAutoMode() { - Assistant assistant = BinaryData.fromString("{\"response_format\":\"auto\"}").toObject(Assistant.class); + public void assistantJsonSchemaFormat() { + Assistant assistant + = BinaryData.fromString("{\"response_format\":{\"type\":\"json_schema\"}}").toObject(Assistant.class); AssistantsApiResponseFormatOption responseFormat = assistant.getResponseFormat(); - assertNotNull(responseFormat.getMode()); - assertNull(responseFormat.getFormat()); - assertEquals(AssistantsApiResponseFormatMode.AUTO, responseFormat.getMode()); + assertNull(responseFormat.getMode()); + assertNotNull(responseFormat.getFormat()); + assertEquals(ApiResponseFormat.JSON_SCHEMA, responseFormat.getFormat().getType()); } @Test - public void assistantNoneMode() { - Assistant assistant = BinaryData.fromString("{\"response_format\":\"none\"}").toObject(Assistant.class); + public void assistantAutoMode() { + Assistant assistant = BinaryData.fromString("{\"response_format\":\"auto\"}").toObject(Assistant.class); AssistantsApiResponseFormatOption responseFormat = assistant.getResponseFormat(); assertNotNull(responseFormat.getMode()); assertNull(responseFormat.getFormat()); - assertEquals(AssistantsApiResponseFormatMode.NONE, responseFormat.getMode()); + assertEquals(AssistantsApiResponseFormatMode.AUTO, responseFormat.getMode()); } @Test @@ -330,23 +334,24 @@ public void threadRunJsonObjectFormat() { } @Test - public void threadRunAutoMode() { - ThreadRun threadRun = BinaryData.fromString("{\"response_format\":\"auto\"}").toObject(ThreadRun.class); + public void threadRunJsonSchemaFormat() { + ThreadRun threadRun + = BinaryData.fromString("{\"response_format\":{\"type\":\"json_schema\"}}").toObject(ThreadRun.class); AssistantsApiResponseFormatOption responseFormat = threadRun.getResponseFormat(); - assertNotNull(responseFormat.getMode()); - assertNull(responseFormat.getFormat()); - assertEquals(AssistantsApiResponseFormatMode.AUTO, responseFormat.getMode()); + assertNull(responseFormat.getMode()); + assertNotNull(responseFormat.getFormat()); + assertEquals(ApiResponseFormat.JSON_SCHEMA, responseFormat.getFormat().getType()); } @Test - public void threadRunNoneMode() { - ThreadRun threadRun = BinaryData.fromString("{\"response_format\":\"none\"}").toObject(ThreadRun.class); + public void threadRunAutoMode() { + ThreadRun threadRun = BinaryData.fromString("{\"response_format\":\"auto\"}").toObject(ThreadRun.class); AssistantsApiResponseFormatOption responseFormat = threadRun.getResponseFormat(); assertNotNull(responseFormat.getMode()); assertNull(responseFormat.getFormat()); - assertEquals(AssistantsApiResponseFormatMode.NONE, responseFormat.getMode()); + assertEquals(AssistantsApiResponseFormatMode.AUTO, responseFormat.getMode()); } @Test diff --git a/sdk/openai/azure-ai-openai-assistants/tsp-location.yaml b/sdk/openai/azure-ai-openai-assistants/tsp-location.yaml index c6f8abad0641..c346c1b3f8f5 100644 --- a/sdk/openai/azure-ai-openai-assistants/tsp-location.yaml +++ b/sdk/openai/azure-ai-openai-assistants/tsp-location.yaml @@ -1,3 +1,3 @@ directory: specification/ai/OpenAI.Assistants -commit: cd41ba31a6af51dae34b0a5930eeb2e77a04b481 +commit: e50d53d8f4b940b6d994cd1ed1213425c269cc07 repo: Azure/azure-rest-api-specs diff --git a/sdk/openai/azure-ai-openai-realtime/pom.xml b/sdk/openai/azure-ai-openai-realtime/pom.xml index 365d898b7444..a3a8f1ef4062 100644 --- a/sdk/openai/azure-ai-openai-realtime/pom.xml +++ b/sdk/openai/azure-ai-openai-realtime/pom.xml @@ -59,14 +59,14 @@ com.azure azure-core - 1.54.1 + 1.55.3 io.netty netty-codec-http - 4.1.115.Final + 4.1.118.Final @@ -81,13 +81,13 @@ com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test @@ -103,8 +103,7 @@ - io.netty:netty-codec-http:[4.1.115.Final] - + io.netty:netty-codec-http:[4.1.118.Final] diff --git a/sdk/openai/azure-ai-openai-realtime/src/main/java/com/azure/ai/openai/realtime/RealtimeAsyncClient.java b/sdk/openai/azure-ai-openai-realtime/src/main/java/com/azure/ai/openai/realtime/RealtimeAsyncClient.java index 1af9b3249e5d..d4153b466ec8 100644 --- a/sdk/openai/azure-ai-openai-realtime/src/main/java/com/azure/ai/openai/realtime/RealtimeAsyncClient.java +++ b/sdk/openai/azure-ai-openai-realtime/src/main/java/com/azure/ai/openai/realtime/RealtimeAsyncClient.java @@ -197,7 +197,7 @@ Mono start(Runnable postStartTask) { .flatMap(authenticationHeader -> Mono.fromRunnable(() -> { this.webSocketSession .set(webSocketClient.connectToServer(this.clientEndpointConfiguration, () -> authenticationHeader, - loggerReference, this::handleMessage, this::handleSessionOpen, this::handleSessionClose)); + this::handleMessage, this::handleSessionOpen, this::handleSessionClose)); })) .subscribeOn(Schedulers.boundedElastic()) .doOnError(error -> { diff --git a/sdk/openai/azure-ai-openai-realtime/src/main/java/com/azure/ai/openai/realtime/implementation/websocket/KeepAliveHandler.java b/sdk/openai/azure-ai-openai-realtime/src/main/java/com/azure/ai/openai/realtime/implementation/websocket/KeepAliveHandler.java new file mode 100644 index 000000000000..086ffda99766 --- /dev/null +++ b/sdk/openai/azure-ai-openai-realtime/src/main/java/com/azure/ai/openai/realtime/implementation/websocket/KeepAliveHandler.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.openai.realtime.implementation.websocket; + +import com.azure.core.util.logging.ClientLogger; +import io.netty.channel.Channel; +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.http.FullHttpResponse; +import io.netty.handler.codec.http.websocketx.PingWebSocketFrame; +import io.netty.handler.codec.http.websocketx.PongWebSocketFrame; +import io.netty.handler.codec.http.websocketx.WebSocketFrame; +import io.netty.util.CharsetUtil; + +/** + * Dedicated handler for server-side ping messages. + */ +public final class KeepAliveHandler extends ChannelDuplexHandler { + private static final ClientLogger LOGGER = new ClientLogger(KeepAliveHandler.class); + + /** + * {@inheritDoc} + */ + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + if (msg instanceof FullHttpResponse) { + FullHttpResponse response = (FullHttpResponse) msg; + throw LOGGER.logExceptionAsError(new IllegalStateException("Unexpected FullHttpResponse (getStatus=" + + response.status() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')')); + } + Channel ch = ctx.channel(); + + LOGGER.atVerbose().log("Processing message: "); + WebSocketFrame frame = (WebSocketFrame) msg; + if (frame instanceof PingWebSocketFrame) { + // Ping, reply Pong + LOGGER.atVerbose().log(() -> "Received PingWebSocketFrame"); + LOGGER.atVerbose().log(() -> "Sending PongWebSocketFrame"); + ch.writeAndFlush(new PongWebSocketFrame()); + } else if (frame instanceof PongWebSocketFrame) { + // Pong + LOGGER.atVerbose().log(() -> "Received PongWebSocketFrame"); + } else { + // Pass other frames down the pipeline + // We only pass down the pipeline messages this handler doesn't process + ctx.fireChannelRead(msg); + } + + } +} diff --git a/sdk/openai/azure-ai-openai-realtime/src/main/java/com/azure/ai/openai/realtime/implementation/websocket/WebSocketClient.java b/sdk/openai/azure-ai-openai-realtime/src/main/java/com/azure/ai/openai/realtime/implementation/websocket/WebSocketClient.java index 62b06fc4b347..6321ead18312 100644 --- a/sdk/openai/azure-ai-openai-realtime/src/main/java/com/azure/ai/openai/realtime/implementation/websocket/WebSocketClient.java +++ b/sdk/openai/azure-ai-openai-realtime/src/main/java/com/azure/ai/openai/realtime/implementation/websocket/WebSocketClient.java @@ -3,9 +3,6 @@ package com.azure.ai.openai.realtime.implementation.websocket; -import com.azure.core.util.logging.ClientLogger; - -import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.function.Supplier; @@ -14,6 +11,5 @@ public interface WebSocketClient { WebSocketSession connectToServer(ClientEndpointConfiguration cec, Supplier authenticationHeaderSupplier, - AtomicReference loggerReference, Consumer messageHandler, - Consumer openHandler, Consumer closeHandler); + Consumer messageHandler, Consumer openHandler, Consumer closeHandler); } diff --git a/sdk/openai/azure-ai-openai-realtime/src/main/java/com/azure/ai/openai/realtime/implementation/websocket/WebSocketClientHandler.java b/sdk/openai/azure-ai-openai-realtime/src/main/java/com/azure/ai/openai/realtime/implementation/websocket/WebSocketClientHandler.java index c1f006f55bb0..37cd15b980ba 100644 --- a/sdk/openai/azure-ai-openai-realtime/src/main/java/com/azure/ai/openai/realtime/implementation/websocket/WebSocketClientHandler.java +++ b/sdk/openai/azure-ai-openai-realtime/src/main/java/com/azure/ai/openai/realtime/implementation/websocket/WebSocketClientHandler.java @@ -11,8 +11,6 @@ import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; -import io.netty.handler.codec.http.websocketx.PingWebSocketFrame; -import io.netty.handler.codec.http.websocketx.PongWebSocketFrame; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker; import io.netty.handler.codec.http.websocketx.WebSocketFrame; @@ -20,7 +18,6 @@ import io.netty.util.CharsetUtil; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; final class WebSocketClientHandler extends SimpleChannelInboundHandler { @@ -28,14 +25,13 @@ final class WebSocketClientHandler extends SimpleChannelInboundHandler { private final WebSocketClientHandshaker handShaker; private ChannelPromise handshakeFuture; - private final AtomicReference loggerReference; + private static final ClientLogger LOGGER = new ClientLogger(WebSocketClientHandler.class); private final MessageDecoder messageDecoder; private final Consumer messageHandler; - WebSocketClientHandler(WebSocketClientHandshaker handShaker, AtomicReference loggerReference, - MessageDecoder messageDecoder, Consumer messageHandler) { + WebSocketClientHandler(WebSocketClientHandshaker handShaker, MessageDecoder messageDecoder, + Consumer messageHandler) { this.handShaker = handShaker; - this.loggerReference = loggerReference; this.messageDecoder = messageDecoder; this.messageHandler = messageHandler; } @@ -62,42 +58,31 @@ protected void channelRead0(ChannelHandlerContext ctx, Object msg) { handShaker.finishHandshake(ch, (FullHttpResponse) msg); handshakeFuture.setSuccess(); } catch (WebSocketHandshakeException e) { - handshakeFuture.setFailure(e); + handshakeFuture.setFailure(LOGGER.atError().log(e)); } return; } if (msg instanceof FullHttpResponse) { FullHttpResponse response = (FullHttpResponse) msg; - throw loggerReference.get() - .logExceptionAsError(new IllegalStateException("Unexpected FullHttpResponse (getStatus=" - + response.status() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')')); + throw LOGGER.logExceptionAsError(new IllegalStateException("Unexpected FullHttpResponse (getStatus=" + + response.status() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')')); } WebSocketFrame frame = (WebSocketFrame) msg; + LOGGER.atInfo().log("Processing frame: " + frame.toString()); + if (frame instanceof TextWebSocketFrame) { // Text TextWebSocketFrame textFrame = (TextWebSocketFrame) frame; - loggerReference.get() - .atVerbose() - .addKeyValue("text", textFrame.text()) - .log(() -> "Received TextWebSocketFrame"); + LOGGER.atVerbose().addKeyValue("text", textFrame.text()).log(() -> "Received TextWebSocketFrame"); Object wpsMessage = messageDecoder.decode(textFrame.text()); messageHandler.accept(wpsMessage); - } else if (frame instanceof PingWebSocketFrame) { - // Ping, reply Pong - loggerReference.get().atVerbose().log(() -> "Received PingWebSocketFrame"); - loggerReference.get().atVerbose().log(() -> "Send PongWebSocketFrame"); - ch.writeAndFlush(new PongWebSocketFrame()); - } else if (frame instanceof PongWebSocketFrame) { - // Pong - loggerReference.get().atVerbose().log(() -> "Received PongWebSocketFrame"); } else if (frame instanceof CloseWebSocketFrame) { // Close CloseWebSocketFrame closeFrame = (CloseWebSocketFrame) frame; - loggerReference.get() - .atVerbose() + LOGGER.atVerbose() .addKeyValue("statusCode", closeFrame.statusCode()) .addKeyValue("reasonText", closeFrame.reasonText()) .log(() -> "Received CloseWebSocketFrame"); @@ -106,25 +91,24 @@ protected void channelRead0(ChannelHandlerContext ctx, Object msg) { if (closeCallbackFuture == null) { // close initiated from server, reply CloseWebSocketFrame, then close connection - loggerReference.get().atVerbose().log(() -> "Send CloseWebSocketFrame"); + LOGGER.atVerbose().log(() -> "Sending CloseWebSocketFrame"); closeFrame.retain(); // retain before write it back ch.writeAndFlush(closeFrame).addListener(future -> ch.close()); } else { // close initiated from client, client already sent CloseWebSocketFrame ch.close(); } + } else { + // Pass other frames down the pipeline + // We only pass down the pipeline messages this handler doesn't process + ctx.fireChannelRead(msg); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { - ClientLogger logger = loggerReference.get(); - if (logger != null) { - logger.atError().log(cause); - } - // cause.printStackTrace(); if (handshakeFuture != null && !handshakeFuture.isDone()) { - handshakeFuture.setFailure(cause); + handshakeFuture.setFailure(LOGGER.atError().log(cause)); } ctx.close(); } diff --git a/sdk/openai/azure-ai-openai-realtime/src/main/java/com/azure/ai/openai/realtime/implementation/websocket/WebSocketClientNettyImpl.java b/sdk/openai/azure-ai-openai-realtime/src/main/java/com/azure/ai/openai/realtime/implementation/websocket/WebSocketClientNettyImpl.java index d9560ceb0769..9a6e0add08fe 100644 --- a/sdk/openai/azure-ai-openai-realtime/src/main/java/com/azure/ai/openai/realtime/implementation/websocket/WebSocketClientNettyImpl.java +++ b/sdk/openai/azure-ai-openai-realtime/src/main/java/com/azure/ai/openai/realtime/implementation/websocket/WebSocketClientNettyImpl.java @@ -6,23 +6,24 @@ import com.azure.ai.openai.realtime.models.ConnectFailedException; import com.azure.core.util.logging.ClientLogger; -import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.function.Supplier; public final class WebSocketClientNettyImpl implements WebSocketClient { + + private static final ClientLogger LOGGER = new ClientLogger(WebSocketClientNettyImpl.class); + @Override public WebSocketSession connectToServer(ClientEndpointConfiguration cec, Supplier authenticationHeaderSupplier, - AtomicReference loggerReference, Consumer messageHandler, - Consumer openHandler, Consumer closeHandler) { + Consumer messageHandler, Consumer openHandler, Consumer closeHandler) { try { WebSocketSessionNettyImpl session = new WebSocketSessionNettyImpl(cec, authenticationHeaderSupplier, - loggerReference, messageHandler, openHandler, closeHandler); + messageHandler, openHandler, closeHandler); session.connect(); return session; } catch (Exception e) { - throw loggerReference.get().logExceptionAsError(new ConnectFailedException("Failed to connect", e)); + throw LOGGER.logExceptionAsError(new ConnectFailedException("Failed to connect", e)); } } } diff --git a/sdk/openai/azure-ai-openai-realtime/src/main/java/com/azure/ai/openai/realtime/implementation/websocket/WebSocketPingHandler.java b/sdk/openai/azure-ai-openai-realtime/src/main/java/com/azure/ai/openai/realtime/implementation/websocket/WebSocketPingHandler.java new file mode 100644 index 000000000000..42bbdec2c091 --- /dev/null +++ b/sdk/openai/azure-ai-openai-realtime/src/main/java/com/azure/ai/openai/realtime/implementation/websocket/WebSocketPingHandler.java @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.openai.realtime.implementation.websocket; + +import com.azure.core.util.logging.ClientLogger; +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.http.websocketx.PingWebSocketFrame; +import io.netty.handler.timeout.IdleStateEvent; + +/** + * Handler that sends a ping frame to the server when the channel is idle to prevent keep-alive timeouts. + */ +public final class WebSocketPingHandler extends ChannelDuplexHandler { + private static final ClientLogger LOGGER = new ClientLogger(WebSocketPingHandler.class); + + /** + * {@inheritDoc} + */ + @Override + public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { + if (evt instanceof IdleStateEvent) { + LOGGER.atVerbose().log("Received IdleStateEvent"); + IdleStateEvent event = (IdleStateEvent) evt; + if (event.state() == IdleStateEvent.ALL_IDLE_STATE_EVENT.state()) { + LOGGER.atVerbose().log("Sending PingWebSocketFrame"); + ctx.writeAndFlush(new PingWebSocketFrame()); + } + } + super.userEventTriggered(ctx, evt); + } +} diff --git a/sdk/openai/azure-ai-openai-realtime/src/main/java/com/azure/ai/openai/realtime/implementation/websocket/WebSocketSessionNettyImpl.java b/sdk/openai/azure-ai-openai-realtime/src/main/java/com/azure/ai/openai/realtime/implementation/websocket/WebSocketSessionNettyImpl.java index ffcb9772c8f2..8fd4d3b4de13 100644 --- a/sdk/openai/azure-ai-openai-realtime/src/main/java/com/azure/ai/openai/realtime/implementation/websocket/WebSocketSessionNettyImpl.java +++ b/sdk/openai/azure-ai-openai-realtime/src/main/java/com/azure/ai/openai/realtime/implementation/websocket/WebSocketSessionNettyImpl.java @@ -7,8 +7,10 @@ import com.azure.ai.openai.realtime.models.RealtimeClientEvent; import com.azure.core.util.logging.ClientLogger; import io.netty.bootstrap.Bootstrap; +import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; +import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; @@ -28,13 +30,14 @@ import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.util.InsecureTrustManagerFactory; +import io.netty.handler.timeout.IdleStateHandler; import javax.net.ssl.SSLException; import java.net.URI; import java.net.URISyntaxException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; -import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Supplier; @@ -42,7 +45,7 @@ final class WebSocketSessionNettyImpl implements WebSocketSession { private static final int MAX_FRAME_SIZE = 65536; - private final AtomicReference loggerReference; + private static final ClientLogger LOGGER = new ClientLogger(WebSocketSessionNettyImpl.class); private final MessageEncoder messageEncoder; private final MessageDecoder messageDecoder; @@ -81,15 +84,16 @@ protected void initChannel(SocketChannel ch) { } p.addLast(new HttpClientCodec(), new HttpObjectAggregator(MAX_FRAME_SIZE), WebSocketClientCompressionHandler.INSTANCE, new WebSocketFrameAggregator(MAX_FRAME_SIZE), handler); + p.addLast(new KeepAliveHandler()); + p.addLast(new IdleStateHandler(0, 0, 30, TimeUnit.SECONDS)); + p.addLast(new WebSocketPingHandler()); } } WebSocketSessionNettyImpl(ClientEndpointConfiguration cec, Supplier authenticationHeaderSupplier, - AtomicReference loggerReference, Consumer messageHandler, - Consumer openHandler, Consumer closeHandler) { + Consumer messageHandler, Consumer openHandler, Consumer closeHandler) { this.uri = cec.getUri(); - this.loggerReference = loggerReference; this.messageEncoder = cec.getMessageEncoder(); this.messageDecoder = cec.getMessageDecoder(); this.subProtocol = cec.getSubProtocol(); @@ -132,11 +136,16 @@ void connect() throws URISyntaxException, SSLException, InterruptedException, Ex handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, this.subProtocol, true, this.headers); - clientHandler = new WebSocketClientHandler(handshaker, loggerReference, messageDecoder, messageHandler); + clientHandler = new WebSocketClientHandler(handshaker, messageDecoder, messageHandler); Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) + .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000) // Connection establishment timeout + .option(ChannelOption.SO_KEEPALIVE, true) // Enable TCP-level keep-alive + .option(ChannelOption.TCP_NODELAY, true) // Disable Nagle's algorithm for low latency + .option(ChannelOption.SO_REUSEADDR, true) // Allow address reuse + .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) // Efficient memory allocation .handler(new WebSocketChannelHandler(host, port, sslCtx, clientHandler)); final CompletableFuture handshakeCallbackFuture = new CompletableFuture<>(); @@ -183,7 +192,6 @@ public boolean isOpen() { @Override public void sendObjectAsync(Object data, Consumer handler) { if (ch != null && ch.isOpen()) { - // TODO: jpalvarezl adjust to the right type for casting String msg = messageEncoder.encode((RealtimeClientEvent) data); sendTextAsync(msg, handler); } else { @@ -195,7 +203,7 @@ public void sendObjectAsync(Object data, Consumer handler) { public void sendTextAsync(String text, Consumer handler) { if (ch != null && ch.isOpen()) { TextWebSocketFrame frame = new TextWebSocketFrame(text); - loggerReference.get().atVerbose().addKeyValue("text", frame.text()).log(() -> "Send TextWebSocketFrame"); + LOGGER.atVerbose().addKeyValue("text", frame.text()).log(() -> "Send TextWebSocketFrame"); ch.writeAndFlush(frame).addListener(future -> { if (future.isSuccess()) { handler.accept(new SendResult()); @@ -219,7 +227,7 @@ public void closeSocket() { group.shutdownGracefully(); } catch (InterruptedException e) { - throw loggerReference.get().logExceptionAsError(new ConnectFailedException("Failed to disconnect", e)); + throw LOGGER.logExceptionAsError(new ConnectFailedException("Failed to disconnect", e)); } } } @@ -235,8 +243,7 @@ public void close() { clientHandler.setClientCloseCallbackFuture(closeCallbackFuture); CloseWebSocketFrame closeFrame = new CloseWebSocketFrame(WebSocketCloseStatus.NORMAL_CLOSURE); - loggerReference.get() - .atVerbose() + LOGGER.atVerbose() .addKeyValue("statusCode", closeFrame.statusCode()) .addKeyValue("reasonText", closeFrame.reasonText()) .log(() -> "Send CloseWebSocketFrame"); @@ -252,7 +259,7 @@ public void close() { closeCallbackFuture.get(); } } catch (InterruptedException | ExecutionException e) { - throw loggerReference.get().logExceptionAsError(new ConnectFailedException("Failed to disconnect", e)); + throw LOGGER.logExceptionAsError(new ConnectFailedException("Failed to disconnect", e)); } } } diff --git a/sdk/openai/azure-ai-openai-realtime/src/samples/README.md b/sdk/openai/azure-ai-openai-realtime/src/samples/README.md index 3c7bf0527978..f67947d97bec 100644 --- a/sdk/openai/azure-ai-openai-realtime/src/samples/README.md +++ b/sdk/openai/azure-ai-openai-realtime/src/samples/README.md @@ -58,4 +58,3 @@ This project welcomes contributions and suggestions. Find [more contributing][SD [low_level_client_non_azure]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/openai/azure-ai-openai-realtime/src/samples/java/com/azure/ai/openai/realtime/NonAzureLowLevelClient.java [tool_call]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/openai/azure-ai-openai-realtime/src/samples/java/com/azure/ai/openai/realtime/ToolCall.java -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fopenai%2Fazure-ai-openai%2FREADME.png) \ No newline at end of file diff --git a/sdk/openai/azure-ai-openai/CHANGELOG.md b/sdk/openai/azure-ai-openai/CHANGELOG.md index 0b81278568b6..a3adb376e7d3 100644 --- a/sdk/openai/azure-ai-openai/CHANGELOG.md +++ b/sdk/openai/azure-ai-openai/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.0.0-beta.14 (Unreleased) +## 1.0.0-beta.15 (Unreleased) ### Features Added @@ -10,6 +10,36 @@ ### Other Changes +## 1.0.0-beta.14 (2025-02-21) + +### Features Added + +- For `ChatCompletionOptions`: + - `store` (bool), which enables saving outputs for FT (distillation) + - `metadata` (string/string map), used with `store` + - `reasoning_effort` (enum string, `low`, `medium`, `high`) to configure how hard `o1` thinks + - `developer` message role (`system` replacement for `o1` and newer models) now available. Other than the name, it's identical + - `prediction` added for predicted outputs + - `modalities` added ("text" | "audio") for audio input support + - `audio` added for audio content options (voice, format, etc.) + - user role message content part representation for audio input added + - **AZURE-ONLY** User Security Context (for Defender for Cloud Integration) + - Azure chat request bodies now have a user_security_context property + - These are JSON objects that have application_name, end_user_id, end_user_tenant_id, and source_ip, all optional string properties + +- For `ChatCompletions`: + - audio output added as `ChatMessageAudioContentItem` + - parity usage updates: + - `PromptTokensDetails` gets `AudioTokens` + - `CompletionTokensDetails` gets `AcceptedPredictionTokens`, `RejectedPredictionTokens`, and `AudioTokens` + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` to version `1.55.2`. +- Upgraded `azure-core-http-netty` to version `1.15.10`. + ## 1.0.0-beta.13 (2024-12-04) ### Features Added diff --git a/sdk/openai/azure-ai-openai/README.md b/sdk/openai/azure-ai-openai/README.md index 1db351975b9e..7d7369d6da80 100644 --- a/sdk/openai/azure-ai-openai/README.md +++ b/sdk/openai/azure-ai-openai/README.md @@ -47,7 +47,7 @@ If you want to see the full code for these snippets check out our [samples folde com.azure azure-ai-openai - 1.0.0-beta.12 + 1.0.0-beta.15 ``` [//]: # ({x-version-update-end}) @@ -108,7 +108,7 @@ Authentication with Entra ID requires some initial setup: com.azure azure-identity - 1.14.2 + 1.15.3 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/openai/azure-ai-openai/assets.json b/sdk/openai/azure-ai-openai/assets.json index 2f08b700e74d..045b1866db5b 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_23e887b74b" + "Tag": "java/openai/azure-ai-openai_ed18509e4e" } diff --git a/sdk/openai/azure-ai-openai/pom.xml b/sdk/openai/azure-ai-openai/pom.xml index 5ed72a475b38..f9b9f989ace2 100644 --- a/sdk/openai/azure-ai-openai/pom.xml +++ b/sdk/openai/azure-ai-openai/pom.xml @@ -14,7 +14,7 @@ com.azure azure-ai-openai - 1.0.0-beta.14 + 1.0.0-beta.15 jar Microsoft Azure Client Library For OpenAI @@ -64,12 +64,12 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 @@ -84,13 +84,13 @@ com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 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 f6634a675203..4bfbb6474b92 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 @@ -967,8 +967,8 @@ public Flux getChatCompletionsStream(String deploymentOrModelNa @ServiceMethod(returns = ReturnType.SINGLE) Mono> getAudioTranscriptionAsResponseObjectWithResponse(String deploymentOrModelName, BinaryData audioTranscriptionOptions, RequestOptions requestOptions) { - // Protocol API requires serialization of parts with content-disposition and data, as operation - // 'getAudioTranscriptionAsResponseObject' is 'multipart/form-data' + // Operation 'getAudioTranscriptionAsResponseObject' is of content-type 'multipart/form-data'. Protocol API is + // not usable and hence not generated. return this.serviceClient.getAudioTranscriptionAsResponseObjectWithResponseAsync(deploymentOrModelName, audioTranscriptionOptions, requestOptions); } @@ -1331,8 +1331,8 @@ public Mono> getAudioTranslationTextWithResponse(String deploym @ServiceMethod(returns = ReturnType.SINGLE) Mono> getAudioTranscriptionAsPlainTextWithResponse(String deploymentOrModelName, BinaryData audioTranscriptionOptions, RequestOptions requestOptions) { - // Protocol API requires serialization of parts with content-disposition and data, as operation - // 'getAudioTranscriptionAsPlainText' is 'multipart/form-data' + // Operation 'getAudioTranscriptionAsPlainText' is of content-type 'multipart/form-data'. Protocol API is not + // usable and hence not generated. return this.serviceClient.getAudioTranscriptionAsPlainTextWithResponseAsync(deploymentOrModelName, audioTranscriptionOptions, requestOptions); } @@ -1383,8 +1383,8 @@ Mono> getAudioTranscriptionAsPlainTextWithResponse(String d @ServiceMethod(returns = ReturnType.SINGLE) Mono> getAudioTranslationAsResponseObjectWithResponse(String deploymentOrModelName, BinaryData audioTranslationOptions, RequestOptions requestOptions) { - // Protocol API requires serialization of parts with content-disposition and data, as operation - // 'getAudioTranslationAsResponseObject' is 'multipart/form-data' + // Operation 'getAudioTranslationAsResponseObject' is of content-type 'multipart/form-data'. Protocol API is not + // usable and hence not generated. return this.serviceClient.getAudioTranslationAsResponseObjectWithResponseAsync(deploymentOrModelName, audioTranslationOptions, requestOptions); } @@ -1414,8 +1414,8 @@ Mono> getAudioTranslationAsResponseObjectWithResponse(Strin @ServiceMethod(returns = ReturnType.SINGLE) Mono> getAudioTranslationAsPlainTextWithResponse(String deploymentOrModelName, BinaryData audioTranslationOptions, RequestOptions requestOptions) { - // Protocol API requires serialization of parts with content-disposition and data, as operation - // 'getAudioTranslationAsPlainText' is 'multipart/form-data' + // Operation 'getAudioTranslationAsPlainText' is of content-type 'multipart/form-data'. Protocol API is not + // usable and hence not generated. return this.serviceClient.getAudioTranslationAsPlainTextWithResponseAsync(deploymentOrModelName, audioTranslationOptions, 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 3b1b8ec81f47..04b7441eaa0f 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 @@ -1265,8 +1265,8 @@ public Response getAudioTranslationTextWithResponse(String deploymentOrM @ServiceMethod(returns = ReturnType.SINGLE) Response getAudioTranscriptionAsResponseObjectWithResponse(String deploymentOrModelName, BinaryData audioTranscriptionOptions, RequestOptions requestOptions) { - // Protocol API requires serialization of parts with content-disposition and data, as operation - // 'getAudioTranscriptionAsResponseObject' is 'multipart/form-data' + // Operation 'getAudioTranscriptionAsResponseObject' is of content-type 'multipart/form-data'. Protocol API is + // not usable and hence not generated. return this.serviceClient.getAudioTranscriptionAsResponseObjectWithResponse(deploymentOrModelName, audioTranscriptionOptions, requestOptions); } @@ -1296,8 +1296,8 @@ Response getAudioTranscriptionAsResponseObjectWithResponse(String de @ServiceMethod(returns = ReturnType.SINGLE) Response getAudioTranscriptionAsPlainTextWithResponse(String deploymentOrModelName, BinaryData audioTranscriptionOptions, RequestOptions requestOptions) { - // Protocol API requires serialization of parts with content-disposition and data, as operation - // 'getAudioTranscriptionAsPlainText' is 'multipart/form-data' + // Operation 'getAudioTranscriptionAsPlainText' is of content-type 'multipart/form-data'. Protocol API is not + // usable and hence not generated. return this.serviceClient.getAudioTranscriptionAsPlainTextWithResponse(deploymentOrModelName, audioTranscriptionOptions, requestOptions); } @@ -1348,8 +1348,8 @@ Response getAudioTranscriptionAsPlainTextWithResponse(String deploym @ServiceMethod(returns = ReturnType.SINGLE) Response getAudioTranslationAsResponseObjectWithResponse(String deploymentOrModelName, BinaryData audioTranslationOptions, RequestOptions requestOptions) { - // Protocol API requires serialization of parts with content-disposition and data, as operation - // 'getAudioTranslationAsResponseObject' is 'multipart/form-data' + // Operation 'getAudioTranslationAsResponseObject' is of content-type 'multipart/form-data'. Protocol API is not + // usable and hence not generated. return this.serviceClient.getAudioTranslationAsResponseObjectWithResponse(deploymentOrModelName, audioTranslationOptions, requestOptions); } @@ -1379,8 +1379,8 @@ Response getAudioTranslationAsResponseObjectWithResponse(String depl @ServiceMethod(returns = ReturnType.SINGLE) Response getAudioTranslationAsPlainTextWithResponse(String deploymentOrModelName, BinaryData audioTranslationOptions, RequestOptions requestOptions) { - // Protocol API requires serialization of parts with content-disposition and data, as operation - // 'getAudioTranslationAsPlainText' is 'multipart/form-data' + // Operation 'getAudioTranslationAsPlainText' is of content-type 'multipart/form-data'. Protocol API is not + // usable and hence not generated. return this.serviceClient.getAudioTranslationAsPlainTextWithResponse(deploymentOrModelName, audioTranslationOptions, requestOptions); } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/OpenAIServiceVersion.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/OpenAIServiceVersion.java index 22a8df010a42..7399e8898070 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/OpenAIServiceVersion.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/OpenAIServiceVersion.java @@ -78,7 +78,12 @@ public enum OpenAIServiceVersion implements ServiceVersion { /** * Enum value 2024-10-01-preview. */ - V2024_10_01_PREVIEW("2024-10-01-preview"); + V2024_10_01_PREVIEW("2024-10-01-preview"), + + /** + * Enum value 2025-01-01-preview. + */ + V2025_01_01_PREVIEW("2025-01-01-preview"); private final String version; @@ -100,6 +105,6 @@ public String getVersion() { * @return The latest {@link OpenAIServiceVersion}. */ public static OpenAIServiceVersion getLatest() { - return V2024_10_01_PREVIEW; + return V2025_01_01_PREVIEW; } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/implementation/OpenAIClientImpl.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/implementation/OpenAIClientImpl.java index 8d2e5e615044..0f769683b1c3 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/implementation/OpenAIClientImpl.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/implementation/OpenAIClientImpl.java @@ -1128,10 +1128,14 @@ public Response getAudioTranslationAsResponseObjectWithResponse(Stri * prompt_tokens: int (Required) * total_tokens: int (Required) * prompt_tokens_details (Optional): { + * audio_tokens: Integer (Optional) * cached_tokens: Integer (Optional) * } * completion_tokens_details (Optional): { + * accepted_prediction_tokens: Integer (Optional) + * audio_tokens: Integer (Optional) * reasoning_tokens: Integer (Optional) + * rejected_prediction_tokens: Integer (Optional) * } * } * system_fingerprint: String (Optional) @@ -1304,10 +1308,14 @@ public Mono> getCompletionsWithResponseAsync(String deploym * prompt_tokens: int (Required) * total_tokens: int (Required) * prompt_tokens_details (Optional): { + * audio_tokens: Integer (Optional) * cached_tokens: Integer (Optional) * } * completion_tokens_details (Optional): { + * accepted_prediction_tokens: Integer (Optional) + * audio_tokens: Integer (Optional) * reasoning_tokens: Integer (Optional) + * rejected_prediction_tokens: Integer (Optional) * } * } * system_fingerprint: String (Optional) @@ -1349,7 +1357,7 @@ public Response getCompletionsWithResponse(String deploymentOrModelN * { * messages (Required): [ * (Required){ - * role: String(system/assistant/user/function/tool) (Required) + * role: String(system/assistant/user/function/tool/developer) (Required) * } * ] * functions (Optional): [ @@ -1405,6 +1413,28 @@ public Response getCompletionsWithResponse(String deploymentOrModelN * ] * tool_choice: BinaryData (Optional) * parallel_tool_calls: Boolean (Optional) + * store: Boolean (Optional) + * metadata (Optional): { + * String: String (Required) + * } + * reasoning_effort: String(low/medium/high) (Optional) + * user_security_context (Optional): { + * application_name: String (Optional) + * end_user_id: String (Optional) + * end_user_tenant_id: String (Optional) + * source_ip: String (Optional) + * } + * modalities (Optional): [ + * String(text/audio) (Optional) + * ] + * prediction (Optional): { + * type: String(content) (Required) + * content: BinaryData (Required) + * } + * audio (Optional): { + * voice: String(alloy/echo/fable/onyx/nova/shimmer) (Required) + * format: String(wav/mp3/flac/opus/pcm16) (Required) + * } * } * } * @@ -1419,7 +1449,7 @@ public Response getCompletionsWithResponse(String deploymentOrModelN * choices (Required): [ * (Required){ * message (Optional): { - * role: String(system/assistant/user/function/tool) (Required) + * role: String(system/assistant/user/function/tool/developer) (Required) * refusal: String (Required) * content: String (Required) * tool_calls (Optional): [ @@ -1432,6 +1462,12 @@ public Response getCompletionsWithResponse(String deploymentOrModelN * name: String (Required) * arguments: String (Required) * } + * audio (Optional): { + * id: String (Required) + * expires_at: long (Required) + * data: String (Required) + * transcript: String (Required) + * } * context (Optional): { * citations (Optional): [ * (Optional){ @@ -1586,10 +1622,14 @@ public Response getCompletionsWithResponse(String deploymentOrModelN * prompt_tokens: int (Required) * total_tokens: int (Required) * prompt_tokens_details (Optional): { + * audio_tokens: Integer (Optional) * cached_tokens: Integer (Optional) * } * completion_tokens_details (Optional): { + * accepted_prediction_tokens: Integer (Optional) + * audio_tokens: Integer (Optional) * reasoning_tokens: Integer (Optional) + * rejected_prediction_tokens: Integer (Optional) * } * } * } @@ -1631,7 +1671,7 @@ public Mono> getChatCompletionsWithResponseAsync(String dep * { * messages (Required): [ * (Required){ - * role: String(system/assistant/user/function/tool) (Required) + * role: String(system/assistant/user/function/tool/developer) (Required) * } * ] * functions (Optional): [ @@ -1687,6 +1727,28 @@ public Mono> getChatCompletionsWithResponseAsync(String dep * ] * tool_choice: BinaryData (Optional) * parallel_tool_calls: Boolean (Optional) + * store: Boolean (Optional) + * metadata (Optional): { + * String: String (Required) + * } + * reasoning_effort: String(low/medium/high) (Optional) + * user_security_context (Optional): { + * application_name: String (Optional) + * end_user_id: String (Optional) + * end_user_tenant_id: String (Optional) + * source_ip: String (Optional) + * } + * modalities (Optional): [ + * String(text/audio) (Optional) + * ] + * prediction (Optional): { + * type: String(content) (Required) + * content: BinaryData (Required) + * } + * audio (Optional): { + * voice: String(alloy/echo/fable/onyx/nova/shimmer) (Required) + * format: String(wav/mp3/flac/opus/pcm16) (Required) + * } * } * } * @@ -1701,7 +1763,7 @@ public Mono> getChatCompletionsWithResponseAsync(String dep * choices (Required): [ * (Required){ * message (Optional): { - * role: String(system/assistant/user/function/tool) (Required) + * role: String(system/assistant/user/function/tool/developer) (Required) * refusal: String (Required) * content: String (Required) * tool_calls (Optional): [ @@ -1714,6 +1776,12 @@ public Mono> getChatCompletionsWithResponseAsync(String dep * name: String (Required) * arguments: String (Required) * } + * audio (Optional): { + * id: String (Required) + * expires_at: long (Required) + * data: String (Required) + * transcript: String (Required) + * } * context (Optional): { * citations (Optional): [ * (Optional){ @@ -1868,10 +1936,14 @@ public Mono> getChatCompletionsWithResponseAsync(String dep * prompt_tokens: int (Required) * total_tokens: int (Required) * prompt_tokens_details (Optional): { + * audio_tokens: Integer (Optional) * cached_tokens: Integer (Optional) * } * completion_tokens_details (Optional): { + * accepted_prediction_tokens: Integer (Optional) + * audio_tokens: Integer (Optional) * reasoning_tokens: Integer (Optional) + * rejected_prediction_tokens: Integer (Optional) * } * } * } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioOutputParameters.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioOutputParameters.java new file mode 100644 index 000000000000..45ccacea8bcb --- /dev/null +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioOutputParameters.java @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.openai.models; + +import com.azure.core.annotation.Generated; +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; + +/** + * Describes the parameters for audio output. + */ +@Immutable +public final class AudioOutputParameters implements JsonSerializable { + + /* + * Specifies the voice type. + */ + @Generated + private final SpeechVoice voice; + + /* + * Specifies the output audio format. + */ + @Generated + private final OutputAudioFormat format; + + /** + * Creates an instance of AudioOutputParameters class. + * + * @param voice the voice value to set. + * @param format the format value to set. + */ + @Generated + public AudioOutputParameters(SpeechVoice voice, OutputAudioFormat format) { + this.voice = voice; + this.format = format; + } + + /** + * Get the voice property: Specifies the voice type. + * + * @return the voice value. + */ + @Generated + public SpeechVoice getVoice() { + return this.voice; + } + + /** + * Get the format property: Specifies the output audio format. + * + * @return the format value. + */ + @Generated + public OutputAudioFormat getFormat() { + return this.format; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("voice", this.voice == null ? null : this.voice.toString()); + jsonWriter.writeStringField("format", this.format == null ? null : this.format.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AudioOutputParameters from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AudioOutputParameters 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 AudioOutputParameters. + */ + @Generated + public static AudioOutputParameters fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SpeechVoice voice = null; + OutputAudioFormat format = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("voice".equals(fieldName)) { + voice = SpeechVoice.fromString(reader.getString()); + } else if ("format".equals(fieldName)) { + format = OutputAudioFormat.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + return new AudioOutputParameters(voice, format); + }); + } +} diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioResponseData.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioResponseData.java new file mode 100644 index 000000000000..5d4093253a1d --- /dev/null +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/AudioResponseData.java @@ -0,0 +1,161 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.openai.models; + +import com.azure.core.annotation.Generated; +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; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; + +/** + * Object containing audio response data and its metadata. + */ +@Immutable +public final class AudioResponseData implements JsonSerializable { + + /* + * Unique identifier for this audio response. + */ + @Generated + private final String id; + + /* + * The Unix timestamp (in seconds) for when this audio response + * will no longer be accessible on the server for use in multi-turn + * conversations. + */ + @Generated + private final long expiresAt; + + /* + * Base64 encoded audio bytes generated by the model, in the format + * specified in the request. + */ + @Generated + private final String data; + + /* + * Transcript of the audio generated by the model. + */ + @Generated + private final String transcript; + + /** + * Creates an instance of AudioResponseData class. + * + * @param id the id value to set. + * @param expiresAt the expiresAt value to set. + * @param data the data value to set. + * @param transcript the transcript value to set. + */ + @Generated + private AudioResponseData(String id, OffsetDateTime expiresAt, String data, String transcript) { + this.id = id; + if (expiresAt == null) { + this.expiresAt = 0L; + } else { + this.expiresAt = expiresAt.toEpochSecond(); + } + this.data = data; + this.transcript = transcript; + } + + /** + * Get the id property: Unique identifier for this audio response. + * + * @return the id value. + */ + @Generated + public String getId() { + return this.id; + } + + /** + * Get the expiresAt property: The Unix timestamp (in seconds) for when this audio response + * will no longer be accessible on the server for use in multi-turn + * conversations. + * + * @return the expiresAt value. + */ + @Generated + public OffsetDateTime getExpiresAt() { + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(this.expiresAt), ZoneOffset.UTC); + } + + /** + * Get the data property: Base64 encoded audio bytes generated by the model, in the format + * specified in the request. + * + * @return the data value. + */ + @Generated + public String getData() { + return this.data; + } + + /** + * Get the transcript property: Transcript of the audio generated by the model. + * + * @return the transcript value. + */ + @Generated + public String getTranscript() { + return this.transcript; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("id", this.id); + jsonWriter.writeLongField("expires_at", this.expiresAt); + jsonWriter.writeStringField("data", this.data); + jsonWriter.writeStringField("transcript", this.transcript); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AudioResponseData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AudioResponseData 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 AudioResponseData. + */ + @Generated + public static AudioResponseData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String id = null; + OffsetDateTime expiresAt = null; + String data = null; + String transcript = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("id".equals(fieldName)) { + id = reader.getString(); + } else if ("expires_at".equals(fieldName)) { + expiresAt = OffsetDateTime.ofInstant(Instant.ofEpochSecond(reader.getLong()), ZoneOffset.UTC); + } else if ("data".equals(fieldName)) { + data = reader.getString(); + } else if ("transcript".equals(fieldName)) { + transcript = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new AudioResponseData(id, expiresAt, data, transcript); + }); + } +} diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionModality.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionModality.java new file mode 100644 index 000000000000..b0fb6199dfd3 --- /dev/null +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatCompletionModality.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.openai.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Values to specified the required modality for the model to use. + */ +public final class ChatCompletionModality extends ExpandableStringEnum { + + /** + * The model is to generate text output. + */ + @Generated + public static final ChatCompletionModality TEXT = fromString("text"); + + /** + * The model is to generate audio output. + */ + @Generated + public static final ChatCompletionModality AUDIO = fromString("audio"); + + /** + * Creates a new instance of ChatCompletionModality value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public ChatCompletionModality() { + } + + /** + * Creates or finds a ChatCompletionModality from its string representation. + * + * @param name a name to look for. + * @return the corresponding ChatCompletionModality. + */ + @Generated + public static ChatCompletionModality fromString(String name) { + return fromString(name, ChatCompletionModality.class); + } + + /** + * Gets known ChatCompletionModality values. + * + * @return known ChatCompletionModality values. + */ + @Generated + public static Collection values() { + return values(ChatCompletionModality.class); + } +} 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 b153d0687af8..7d908e2f335c 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 @@ -906,13 +906,10 @@ public ChatCompletionsOptions setParallelToolCalls(Boolean parallelToolCalls) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeArrayField("tools", this.tools, (writer, element) -> writer.writeJson(element)); - if (this.toolChoice != null) { - jsonWriter.writeRawField("tool_choice", this.toolChoice.toString()); - } jsonWriter.writeArrayField("messages", this.messages, (writer, element) -> writer.writeJson(element)); jsonWriter.writeArrayField("functions", this.functions, (writer, element) -> writer.writeJson(element)); if (this.functionCall != null) { @@ -938,7 +935,21 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { 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.writeFieldName("tool_choice"); + this.toolChoice.writeTo(jsonWriter); + } jsonWriter.writeBooleanField("parallel_tool_calls", this.parallelToolCalls); + jsonWriter.writeBooleanField("store", this.store); + jsonWriter.writeMapField("metadata", this.metadata, (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("reasoning_effort", + this.reasoningEffort == null ? null : this.reasoningEffort.toString()); + jsonWriter.writeJsonField("user_security_context", this.userSecurityContext); + jsonWriter.writeArrayField("modalities", this.modalities, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); + jsonWriter.writeJsonField("prediction", this.prediction); + jsonWriter.writeJsonField("audio", this.audio); return jsonWriter.writeEndObject(); } @@ -979,6 +990,13 @@ public static ChatCompletionsOptions fromJson(JsonReader jsonReader) throws IOEx List tools = null; BinaryData toolChoice = null; Boolean parallelToolCalls = null; + Boolean store = null; + Map metadata = null; + ReasoningEffortValue reasoningEffort = null; + UserSecurityContext userSecurityContext = null; + List modalities = null; + PredictionContent prediction = null; + AudioOutputParameters audio = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); @@ -1034,6 +1052,20 @@ public static ChatCompletionsOptions fromJson(JsonReader jsonReader) throws IOEx = reader.getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped())); } else if ("parallel_tool_calls".equals(fieldName)) { parallelToolCalls = reader.getNullable(JsonReader::getBoolean); + } else if ("store".equals(fieldName)) { + store = reader.getNullable(JsonReader::getBoolean); + } else if ("metadata".equals(fieldName)) { + metadata = reader.readMap(reader1 -> reader1.getString()); + } else if ("reasoning_effort".equals(fieldName)) { + reasoningEffort = ReasoningEffortValue.fromString(reader.getString()); + } else if ("user_security_context".equals(fieldName)) { + userSecurityContext = UserSecurityContext.fromJson(reader); + } else if ("modalities".equals(fieldName)) { + modalities = reader.readArray(reader1 -> ChatCompletionModality.fromString(reader1.getString())); + } else if ("prediction".equals(fieldName)) { + prediction = PredictionContent.fromJson(reader); + } else if ("audio".equals(fieldName)) { + audio = AudioOutputParameters.fromJson(reader); } else { reader.skipChildren(); } @@ -1063,6 +1095,13 @@ public static ChatCompletionsOptions fromJson(JsonReader jsonReader) throws IOEx deserializedChatCompletionsOptions.tools = tools; deserializedChatCompletionsOptions.toolChoice = toolChoice; deserializedChatCompletionsOptions.parallelToolCalls = parallelToolCalls; + deserializedChatCompletionsOptions.store = store; + deserializedChatCompletionsOptions.metadata = metadata; + deserializedChatCompletionsOptions.reasoningEffort = reasoningEffort; + deserializedChatCompletionsOptions.userSecurityContext = userSecurityContext; + deserializedChatCompletionsOptions.modalities = modalities; + deserializedChatCompletionsOptions.prediction = prediction; + deserializedChatCompletionsOptions.audio = audio; return deserializedChatCompletionsOptions; }); } @@ -1083,4 +1122,244 @@ public void setStreamOptions(ChatCompletionsOptions options, } }); } + + /* + * Whether or not to store the output of this chat completion request for use in our model distillation or + * evaluation products. + */ + @Generated + private Boolean store; + + /* + * Developer-defined tags and values used for filtering completions in the stored completions dashboard. + */ + @Generated + private Map metadata; + + /* + * This option is only valid for o1 models, + * + * Constrains effort on reasoning for reasoning models (see https://platform.openai.com/docs/guides/reasoning). + * + * Currently supported values are `low`, `medium`, and `high`. Reducing reasoning effort can result in faster + * responses and fewer tokens used on reasoning in a response. + */ + @Generated + private ReasoningEffortValue reasoningEffort; + + /* + * The security context identifies and authenticates users and applications in your multi-tenant AI system, helping + * security teams investigate and mitigate incidents. + */ + @Generated + private UserSecurityContext userSecurityContext; + + /* + * Output types that you would like the model to generate for this request. + * Most models are capable of generating text, which is the default: `["text"]` + * The `gpt-4o-audio-preview` model can also be used to generate audio. To + * request that this model generate both text and audio responses, you can + * use: `["text", "audio"]` + */ + @Generated + private List modalities; + + /* + * Configuration for a Predicted Output, which can greatly improve response times + * when large parts of the model response are known ahead of time. This is most + * common when you are regenerating a file with only minor changes to most of the content. + */ + @Generated + private PredictionContent prediction; + + /* + * Parameters for audio output. Required when audio output is requested + * with `modalities: ["audio"]` + */ + @Generated + private AudioOutputParameters audio; + + /** + * Get the store property: Whether or not to store the output of this chat completion request for use in our model + * distillation or evaluation products. + * + * @return the store value. + */ + @Generated + public Boolean isStore() { + return this.store; + } + + /** + * Set the store property: Whether or not to store the output of this chat completion request for use in our model + * distillation or evaluation products. + * + * @param store the store value to set. + * @return the ChatCompletionsOptions object itself. + */ + @Generated + public ChatCompletionsOptions setStore(Boolean store) { + this.store = store; + return this; + } + + /** + * Get the metadata property: Developer-defined tags and values used for filtering completions in the stored + * completions dashboard. + * + * @return the metadata value. + */ + @Generated + public Map getMetadata() { + return this.metadata; + } + + /** + * Set the metadata property: Developer-defined tags and values used for filtering completions in the stored + * completions dashboard. + * + * @param metadata the metadata value to set. + * @return the ChatCompletionsOptions object itself. + */ + @Generated + public ChatCompletionsOptions setMetadata(Map metadata) { + this.metadata = metadata; + return this; + } + + /** + * Get the reasoningEffort property: This option is only valid for o1 models, + * + * Constrains effort on reasoning for reasoning models (see https://platform.openai.com/docs/guides/reasoning). + * + * Currently supported values are `low`, `medium`, and `high`. Reducing reasoning effort can result in faster + * responses and fewer tokens used on reasoning in a response. + * + * @return the reasoningEffort value. + */ + @Generated + public ReasoningEffortValue getReasoningEffort() { + return this.reasoningEffort; + } + + /** + * Set the reasoningEffort property: This option is only valid for o1 models, + * + * Constrains effort on reasoning for reasoning models (see https://platform.openai.com/docs/guides/reasoning). + * + * Currently supported values are `low`, `medium`, and `high`. Reducing reasoning effort can result in faster + * responses and fewer tokens used on reasoning in a response. + * + * @param reasoningEffort the reasoningEffort value to set. + * @return the ChatCompletionsOptions object itself. + */ + @Generated + public ChatCompletionsOptions setReasoningEffort(ReasoningEffortValue reasoningEffort) { + this.reasoningEffort = reasoningEffort; + return this; + } + + /** + * Get the userSecurityContext property: The security context identifies and authenticates users and applications in + * your multi-tenant AI system, helping security teams investigate and mitigate incidents. + * + * @return the userSecurityContext value. + */ + @Generated + public UserSecurityContext getUserSecurityContext() { + return this.userSecurityContext; + } + + /** + * Set the userSecurityContext property: The security context identifies and authenticates users and applications in + * your multi-tenant AI system, helping security teams investigate and mitigate incidents. + * + * @param userSecurityContext the userSecurityContext value to set. + * @return the ChatCompletionsOptions object itself. + */ + @Generated + public ChatCompletionsOptions setUserSecurityContext(UserSecurityContext userSecurityContext) { + this.userSecurityContext = userSecurityContext; + return this; + } + + /** + * Get the modalities property: Output types that you would like the model to generate for this request. + * Most models are capable of generating text, which is the default: `["text"]` + * The `gpt-4o-audio-preview` model can also be used to generate audio. To + * request that this model generate both text and audio responses, you can + * use: `["text", "audio"]`. + * + * @return the modalities value. + */ + @Generated + public List getModalities() { + return this.modalities; + } + + /** + * Set the modalities property: Output types that you would like the model to generate for this request. + * Most models are capable of generating text, which is the default: `["text"]` + * The `gpt-4o-audio-preview` model can also be used to generate audio. To + * request that this model generate both text and audio responses, you can + * use: `["text", "audio"]`. + * + * @param modalities the modalities value to set. + * @return the ChatCompletionsOptions object itself. + */ + @Generated + public ChatCompletionsOptions setModalities(List modalities) { + this.modalities = modalities; + return this; + } + + /** + * Get the prediction property: Configuration for a Predicted Output, which can greatly improve response times + * when large parts of the model response are known ahead of time. This is most + * common when you are regenerating a file with only minor changes to most of the content. + * + * @return the prediction value. + */ + @Generated + public PredictionContent getPrediction() { + return this.prediction; + } + + /** + * Set the prediction property: Configuration for a Predicted Output, which can greatly improve response times + * when large parts of the model response are known ahead of time. This is most + * common when you are regenerating a file with only minor changes to most of the content. + * + * @param prediction the prediction value to set. + * @return the ChatCompletionsOptions object itself. + */ + @Generated + public ChatCompletionsOptions setPrediction(PredictionContent prediction) { + this.prediction = prediction; + return this; + } + + /** + * Get the audio property: Parameters for audio output. Required when audio output is requested + * with `modalities: ["audio"]`. + * + * @return the audio value. + */ + @Generated + public AudioOutputParameters getAudio() { + return this.audio; + } + + /** + * Set the audio property: Parameters for audio output. Required when audio output is requested + * with `modalities: ["audio"]`. + * + * @param audio the audio value to set. + * @return the ChatCompletionsOptions object itself. + */ + @Generated + public ChatCompletionsOptions setAudio(AudioOutputParameters audio) { + this.audio = audio; + return this; + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatMessageAudioContentItem.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatMessageAudioContentItem.java new file mode 100644 index 000000000000..f29d5d2163de --- /dev/null +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatMessageAudioContentItem.java @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.openai.models; + +import com.azure.core.annotation.Generated; +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; + +/** + * A structured chat content item containing audio data. + */ +@Immutable +public final class ChatMessageAudioContentItem extends ChatMessageContentItem { + + /* + * The discriminated object type. + */ + @Generated + private String type = "input_audio"; + + /* + * The audio data. + */ + @Generated + private final InputAudioContent inputAudio; + + /** + * Creates an instance of ChatMessageAudioContentItem class. + * + * @param inputAudio the inputAudio value to set. + */ + @Generated + public ChatMessageAudioContentItem(InputAudioContent inputAudio) { + this.inputAudio = inputAudio; + } + + /** + * Get the type property: The discriminated object type. + * + * @return the type value. + */ + @Generated + @Override + public String getType() { + return this.type; + } + + /** + * Get the inputAudio property: The audio data. + * + * @return the inputAudio value. + */ + @Generated + public InputAudioContent getInputAudio() { + return this.inputAudio; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("input_audio", this.inputAudio); + jsonWriter.writeStringField("type", this.type); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatMessageAudioContentItem from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatMessageAudioContentItem 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 ChatMessageAudioContentItem. + */ + @Generated + public static ChatMessageAudioContentItem fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + InputAudioContent inputAudio = null; + String type = "input_audio"; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("input_audio".equals(fieldName)) { + inputAudio = InputAudioContent.fromJson(reader); + } else if ("type".equals(fieldName)) { + type = reader.getString(); + } else { + reader.skipChildren(); + } + } + ChatMessageAudioContentItem deserializedChatMessageAudioContentItem + = new ChatMessageAudioContentItem(inputAudio); + deserializedChatMessageAudioContentItem.type = type; + return deserializedChatMessageAudioContentItem; + }); + } +} 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 eb36c06c2616..f1496490ce79 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 @@ -81,6 +81,8 @@ public static ChatMessageContentItem fromJson(JsonReader jsonReader) throws IOEx return ChatMessageRefusalContentItem.fromJson(readerToUse.reset()); } else if ("image_url".equals(discriminatorValue)) { return ChatMessageImageContentItem.fromJson(readerToUse.reset()); + } else if ("input_audio".equals(discriminatorValue)) { + return ChatMessageAudioContentItem.fromJson(readerToUse.reset()); } else if ("text".equals(discriminatorValue)) { return ChatMessageTextContentItem.fromJson(readerToUse.reset()); } else { diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRequestDeveloperMessage.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRequestDeveloperMessage.java new file mode 100644 index 000000000000..e130a912083a --- /dev/null +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ChatRequestDeveloperMessage.java @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.openai.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.util.BinaryData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Developer-provided instructions that the model should follow, regardless of messages sent by the user. + * With o1 models and newer, `developer` messages replace the previous `system` messages.". + */ +@Fluent +public final class ChatRequestDeveloperMessage extends ChatRequestMessage { + + /* + * The chat role associated with this message. + */ + @Generated + private ChatRole role = ChatRole.DEVELOPER; + + /* + * An array of content parts with a defined type. For developer messages, only type `text` is supported. + */ + @Generated + private final BinaryData content; + + /* + * An optional name for the participant. Provides the model information to differentiate between participants of the + * same role. + */ + @Generated + private String name; + + /** + * Creates an instance of ChatRequestDeveloperMessage class. + * + * @param content the content value to set. + */ + @Generated + public ChatRequestDeveloperMessage(BinaryData content) { + this.content = content; + } + + /** + * Get the role property: The chat role associated with this message. + * + * @return the role value. + */ + @Generated + @Override + public ChatRole getRole() { + return this.role; + } + + /** + * Get the content property: An array of content parts with a defined type. For developer messages, only type `text` + * is supported. + * + * @return the content value. + */ + @Generated + public BinaryData getContent() { + return this.content; + } + + /** + * Get the name property: An optional name for the participant. Provides the model information to differentiate + * between participants of the same role. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Set the name property: An optional name for the participant. Provides the model information to differentiate + * between participants of the same role. + * + * @param name the name value to set. + * @return the ChatRequestDeveloperMessage object itself. + */ + @Generated + public ChatRequestDeveloperMessage setName(String name) { + this.name = name; + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeFieldName("content"); + this.content.writeTo(jsonWriter); + jsonWriter.writeStringField("role", this.role == null ? null : this.role.toString()); + jsonWriter.writeStringField("name", this.name); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatRequestDeveloperMessage from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatRequestDeveloperMessage 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 ChatRequestDeveloperMessage. + */ + @Generated + public static ChatRequestDeveloperMessage fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + BinaryData content = null; + ChatRole role = ChatRole.DEVELOPER; + 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(); + } + } + ChatRequestDeveloperMessage deserializedChatRequestDeveloperMessage + = new ChatRequestDeveloperMessage(content); + deserializedChatRequestDeveloperMessage.role = role; + deserializedChatRequestDeveloperMessage.name = name; + return deserializedChatRequestDeveloperMessage; + }); + } +} 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 8659a4fa5f0c..8baa3ea6a7f7 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 @@ -79,6 +79,8 @@ public static ChatRequestMessage fromJson(JsonReader jsonReader) throws IOExcept // Use the discriminator value to determine which subtype should be deserialized. if ("system".equals(discriminatorValue)) { return ChatRequestSystemMessage.fromJson(readerToUse.reset()); + } else if ("developer".equals(discriminatorValue)) { + return ChatRequestDeveloperMessage.fromJson(readerToUse.reset()); } else if ("user".equals(discriminatorValue)) { return ChatRequestUserMessage.fromJson(readerToUse.reset()); } else if ("assistant".equals(discriminatorValue)) { 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 4d7247d993ce..00007916268e 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 @@ -119,6 +119,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStringField("content", this.content); jsonWriter.writeArrayField("tool_calls", this.toolCalls, (writer, element) -> writer.writeJson(element)); jsonWriter.writeJsonField("function_call", this.functionCall); + jsonWriter.writeJsonField("audio", this.audio); jsonWriter.writeJsonField("context", this.context); return jsonWriter.writeEndObject(); } @@ -140,6 +141,7 @@ public static ChatResponseMessage fromJson(JsonReader jsonReader) throws IOExcep String content = null; List toolCalls = null; FunctionCall functionCall = null; + AudioResponseData audio = null; AzureChatExtensionsMessageContext context = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); @@ -154,6 +156,8 @@ public static ChatResponseMessage fromJson(JsonReader jsonReader) throws IOExcep toolCalls = reader.readArray(reader1 -> ChatCompletionsToolCall.fromJson(reader1)); } else if ("function_call".equals(fieldName)) { functionCall = FunctionCall.fromJson(reader); + } else if ("audio".equals(fieldName)) { + audio = AudioResponseData.fromJson(reader); } else if ("context".equals(fieldName)) { context = AzureChatExtensionsMessageContext.fromJson(reader); } else { @@ -163,6 +167,7 @@ public static ChatResponseMessage fromJson(JsonReader jsonReader) throws IOExcep ChatResponseMessage deserializedChatResponseMessage = new ChatResponseMessage(role, refusal, content); deserializedChatResponseMessage.toolCalls = toolCalls; deserializedChatResponseMessage.functionCall = functionCall; + deserializedChatResponseMessage.audio = audio; deserializedChatResponseMessage.context = context; return deserializedChatResponseMessage; }); @@ -197,4 +202,22 @@ private ChatResponseMessage(ChatRole role, String refusal, String content) { public String getRefusal() { return this.refusal; } + + /* + * If the audio output modality is requested, this object contains data + * about the audio response from the model. + */ + @Generated + private AudioResponseData audio; + + /** + * Get the audio property: If the audio output modality is requested, this object contains data + * about the audio response from the model. + * + * @return the audio value. + */ + @Generated + public AudioResponseData getAudio() { + return this.audio; + } } 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 a21c71dacb68..4d5de6ad50e5 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 @@ -72,4 +72,10 @@ public static Collection values() { */ @Generated public static final ChatRole TOOL = fromString("tool"); + + /** + * The role that provides instructions that the model should follow. + */ + @Generated + public static final ChatRole DEVELOPER = fromString("developer"); } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/CompletionsUsageCompletionTokensDetails.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/CompletionsUsageCompletionTokensDetails.java index f71528a136a2..315d870fc55b 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/CompletionsUsageCompletionTokensDetails.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/CompletionsUsageCompletionTokensDetails.java @@ -48,7 +48,10 @@ public Integer getReasoningTokens() { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeNumberField("accepted_prediction_tokens", this.acceptedPredictionTokens); + jsonWriter.writeNumberField("audio_tokens", this.audioTokens); jsonWriter.writeNumberField("reasoning_tokens", this.reasoningTokens); + jsonWriter.writeNumberField("rejected_prediction_tokens", this.rejectedPredictionTokens); return jsonWriter.writeEndObject(); } @@ -68,9 +71,18 @@ public static CompletionsUsageCompletionTokensDetails fromJson(JsonReader jsonRe while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("reasoning_tokens".equals(fieldName)) { + if ("accepted_prediction_tokens".equals(fieldName)) { + deserializedCompletionsUsageCompletionTokensDetails.acceptedPredictionTokens + = reader.getNullable(JsonReader::getInt); + } else if ("audio_tokens".equals(fieldName)) { + deserializedCompletionsUsageCompletionTokensDetails.audioTokens + = reader.getNullable(JsonReader::getInt); + } else if ("reasoning_tokens".equals(fieldName)) { deserializedCompletionsUsageCompletionTokensDetails.reasoningTokens = reader.getNullable(JsonReader::getInt); + } else if ("rejected_prediction_tokens".equals(fieldName)) { + deserializedCompletionsUsageCompletionTokensDetails.rejectedPredictionTokens + = reader.getNullable(JsonReader::getInt); } else { reader.skipChildren(); } @@ -78,4 +90,62 @@ public static CompletionsUsageCompletionTokensDetails fromJson(JsonReader jsonRe return deserializedCompletionsUsageCompletionTokensDetails; }); } + + /* + * When using Predicted Outputs, the number of tokens in the + * prediction that appeared in the completion. + */ + @Generated + private Integer acceptedPredictionTokens; + + /* + * Audio input tokens generated by the model. + */ + @Generated + private Integer audioTokens; + + /* + * When using Predicted Outputs, the number of tokens in the + * prediction that did not appear in the completion. However, like + * reasoning tokens, these tokens are still counted in the total + * completion tokens for purposes of billing, output, and context + * window limits. + */ + @Generated + private Integer rejectedPredictionTokens; + + /** + * Get the acceptedPredictionTokens property: When using Predicted Outputs, the number of tokens in the + * prediction that appeared in the completion. + * + * @return the acceptedPredictionTokens value. + */ + @Generated + public Integer getAcceptedPredictionTokens() { + return this.acceptedPredictionTokens; + } + + /** + * Get the audioTokens property: Audio input tokens generated by the model. + * + * @return the audioTokens value. + */ + @Generated + public Integer getAudioTokens() { + return this.audioTokens; + } + + /** + * Get the rejectedPredictionTokens property: When using Predicted Outputs, the number of tokens in the + * prediction that did not appear in the completion. However, like + * reasoning tokens, these tokens are still counted in the total + * completion tokens for purposes of billing, output, and context + * window limits. + * + * @return the rejectedPredictionTokens value. + */ + @Generated + public Integer getRejectedPredictionTokens() { + return this.rejectedPredictionTokens; + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/CompletionsUsagePromptTokensDetails.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/CompletionsUsagePromptTokensDetails.java index 3736d383a6b2..54ed6d365f83 100644 --- a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/CompletionsUsagePromptTokensDetails.java +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/CompletionsUsagePromptTokensDetails.java @@ -19,7 +19,7 @@ public final class CompletionsUsagePromptTokensDetails implements JsonSerializable { /* - * The number of cached prompt tokens. + * Cached tokens present in the prompt. */ @Generated private Integer cachedTokens; @@ -32,7 +32,7 @@ private CompletionsUsagePromptTokensDetails() { } /** - * Get the cachedTokens property: The number of cached prompt tokens. + * Get the cachedTokens property: Cached tokens present in the prompt. * * @return the cachedTokens value. */ @@ -48,6 +48,7 @@ public Integer getCachedTokens() { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeNumberField("audio_tokens", this.audioTokens); jsonWriter.writeNumberField("cached_tokens", this.cachedTokens); return jsonWriter.writeEndObject(); } @@ -68,7 +69,10 @@ public static CompletionsUsagePromptTokensDetails fromJson(JsonReader jsonReader while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("cached_tokens".equals(fieldName)) { + if ("audio_tokens".equals(fieldName)) { + deserializedCompletionsUsagePromptTokensDetails.audioTokens + = reader.getNullable(JsonReader::getInt); + } else if ("cached_tokens".equals(fieldName)) { deserializedCompletionsUsagePromptTokensDetails.cachedTokens = reader.getNullable(JsonReader::getInt); } else { @@ -78,4 +82,20 @@ public static CompletionsUsagePromptTokensDetails fromJson(JsonReader jsonReader return deserializedCompletionsUsagePromptTokensDetails; }); } + + /* + * Audio input tokens present in the prompt. + */ + @Generated + private Integer audioTokens; + + /** + * Get the audioTokens property: Audio input tokens present in the prompt. + * + * @return the audioTokens value. + */ + @Generated + public Integer getAudioTokens() { + return this.audioTokens; + } } diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/InputAudioContent.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/InputAudioContent.java new file mode 100644 index 000000000000..855ff2929048 --- /dev/null +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/InputAudioContent.java @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.openai.models; + +import com.azure.core.annotation.Generated; +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; +import java.util.Base64; + +/** + * A structured chat content item containing audio data. + */ +@Immutable +public final class InputAudioContent implements JsonSerializable { + + /* + * Base64-encoded audio data. + */ + @Generated + private final String data; + + /* + * The format of the audio data. + */ + @Generated + private final InputAudioFormat format; + + /** + * Creates an instance of InputAudioContent class. + * + * @param data the data value to set. + * @param format the format value to set. + */ + @Generated + public InputAudioContent(String data, InputAudioFormat format) { + this.data = data; + this.format = format; + } + + /** + * Creates an instance of InputAudioContent class. + * + * @param data - the audio data to set. + * @param format - the format to set. + */ + public InputAudioContent(byte[] data, InputAudioFormat format) { + this.data = Base64.getEncoder().encodeToString(data); + this.format = format; + } + + /** + * Get the data property: Base64-encoded audio data. + * + * @return the data value. + */ + @Generated + public String getData() { + return this.data; + } + + /** + * Get the format property: The format of the audio data. + * + * @return the format value. + */ + @Generated + public InputAudioFormat getFormat() { + return this.format; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("data", this.data); + jsonWriter.writeStringField("format", this.format == null ? null : this.format.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of InputAudioContent from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of InputAudioContent 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 InputAudioContent. + */ + @Generated + public static InputAudioContent fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String data = null; + InputAudioFormat format = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("data".equals(fieldName)) { + data = reader.getString(); + } else if ("format".equals(fieldName)) { + format = InputAudioFormat.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + return new InputAudioContent(data, format); + }); + } +} diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/InputAudioFormat.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/InputAudioFormat.java new file mode 100644 index 000000000000..b8559028198a --- /dev/null +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/InputAudioFormat.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.openai.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Values to describe the format of the input audio data. + */ +public final class InputAudioFormat extends ExpandableStringEnum { + + /** + * Specifies that the audio data is in the WAV format. + */ + @Generated + public static final InputAudioFormat WAV = fromString("wav"); + + /** + * Specifies that the audio data is in the MP3 format. + */ + @Generated + public static final InputAudioFormat MP3 = fromString("mp3"); + + /** + * Creates a new instance of InputAudioFormat value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public InputAudioFormat() { + } + + /** + * Creates or finds a InputAudioFormat from its string representation. + * + * @param name a name to look for. + * @return the corresponding InputAudioFormat. + */ + @Generated + public static InputAudioFormat fromString(String name) { + return fromString(name, InputAudioFormat.class); + } + + /** + * Gets known InputAudioFormat values. + * + * @return known InputAudioFormat values. + */ + @Generated + public static Collection values() { + return values(InputAudioFormat.class); + } +} diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OutputAudioFormat.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OutputAudioFormat.java new file mode 100644 index 000000000000..afb2e8d77505 --- /dev/null +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/OutputAudioFormat.java @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.openai.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The output audio format. + */ +public final class OutputAudioFormat extends ExpandableStringEnum { + + /** + * The output audio format is WAV. + */ + @Generated + public static final OutputAudioFormat WAV = fromString("wav"); + + /** + * The output audio format is MP3. + */ + @Generated + public static final OutputAudioFormat MP3 = fromString("mp3"); + + /** + * The output audio format is FLAC. + */ + @Generated + public static final OutputAudioFormat FLAC = fromString("flac"); + + /** + * The output audio format is OPUS. + */ + @Generated + public static final OutputAudioFormat OPUS = fromString("opus"); + + /** + * The output audio format is PCM16. + */ + @Generated + public static final OutputAudioFormat PCM16 = fromString("pcm16"); + + /** + * Creates a new instance of OutputAudioFormat value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public OutputAudioFormat() { + } + + /** + * Creates or finds a OutputAudioFormat from its string representation. + * + * @param name a name to look for. + * @return the corresponding OutputAudioFormat. + */ + @Generated + public static OutputAudioFormat fromString(String name) { + return fromString(name, OutputAudioFormat.class); + } + + /** + * Gets known OutputAudioFormat values. + * + * @return known OutputAudioFormat values. + */ + @Generated + public static Collection values() { + return values(OutputAudioFormat.class); + } +} diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/PredictionContent.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/PredictionContent.java new file mode 100644 index 000000000000..9693ca77af67 --- /dev/null +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/PredictionContent.java @@ -0,0 +1,107 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.openai.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.BinaryData; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Static predicted output content, such as the content of a text file that is being regenerated. + */ +@Immutable +public final class PredictionContent implements JsonSerializable { + + /* + * The type of the predicted content you want to provide. This type is + * currently always `content`. + */ + @Generated + private final PredictionContentType type = PredictionContentType.CONTENT; + + /* + * The content that should be matched when generating a model response. + * If generated tokens would match this content, the entire model response + * can be returned much more quickly. + */ + @Generated + private final BinaryData content; + + /** + * Creates an instance of PredictionContent class. + * + * @param content the content value to set. + */ + @Generated + public PredictionContent(BinaryData content) { + this.content = content; + } + + /** + * Get the type property: The type of the predicted content you want to provide. This type is + * currently always `content`. + * + * @return the type value. + */ + @Generated + public PredictionContentType getType() { + return this.type; + } + + /** + * Get the content property: The content that should be matched when generating a model response. + * If generated tokens would match this content, the entire model response + * can be returned much more quickly. + * + * @return the content value. + */ + @Generated + public BinaryData getContent() { + return this.content; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + jsonWriter.writeFieldName("content"); + this.content.writeTo(jsonWriter); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of PredictionContent from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of PredictionContent 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 PredictionContent. + */ + @Generated + public static PredictionContent fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + BinaryData content = 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 { + reader.skipChildren(); + } + } + return new PredictionContent(content); + }); + } +} diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/PredictionContentType.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/PredictionContentType.java new file mode 100644 index 000000000000..77ebfdd15f49 --- /dev/null +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/PredictionContentType.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.openai.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The types of predicted content. + */ +public final class PredictionContentType extends ExpandableStringEnum { + + /** + * Predicted content is of type content. + */ + @Generated + public static final PredictionContentType CONTENT = fromString("content"); + + /** + * Creates a new instance of PredictionContentType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public PredictionContentType() { + } + + /** + * Creates or finds a PredictionContentType from its string representation. + * + * @param name a name to look for. + * @return the corresponding PredictionContentType. + */ + @Generated + public static PredictionContentType fromString(String name) { + return fromString(name, PredictionContentType.class); + } + + /** + * Gets known PredictionContentType values. + * + * @return known PredictionContentType values. + */ + @Generated + public static Collection values() { + return values(PredictionContentType.class); + } +} diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ReasoningEffortValue.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ReasoningEffortValue.java new file mode 100644 index 000000000000..5d43cf96c4fb --- /dev/null +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/ReasoningEffortValue.java @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.openai.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Values for the reasoning. + */ +public final class ReasoningEffortValue extends ExpandableStringEnum { + + /** + * The reasoning effort is low. + */ + @Generated + public static final ReasoningEffortValue LOW = fromString("low"); + + /** + * The reasoning effort is medium. + */ + @Generated + public static final ReasoningEffortValue MEDIUM = fromString("medium"); + + /** + * The reasoning effort is high. + */ + @Generated + public static final ReasoningEffortValue HIGH = fromString("high"); + + /** + * Creates a new instance of ReasoningEffortValue value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public ReasoningEffortValue() { + } + + /** + * Creates or finds a ReasoningEffortValue from its string representation. + * + * @param name a name to look for. + * @return the corresponding ReasoningEffortValue. + */ + @Generated + public static ReasoningEffortValue fromString(String name) { + return fromString(name, ReasoningEffortValue.class); + } + + /** + * Gets known ReasoningEffortValue values. + * + * @return known ReasoningEffortValue values. + */ + @Generated + public static Collection values() { + return values(ReasoningEffortValue.class); + } +} diff --git a/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/UserSecurityContext.java b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/UserSecurityContext.java new file mode 100644 index 000000000000..9fd94f9924fc --- /dev/null +++ b/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/models/UserSecurityContext.java @@ -0,0 +1,198 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.openai.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * User security context contains several parameters that describe the AI application itself, + * and the end user that interacts with the AI application. These fields assist your security + * operations teams to investigate and mitigate security incidents by providing a comprehensive + * approach to protecting your AI applications. (Learn more at https://aka.ms/TP4AI/Documentation/EndUserContext) + * about protecting AI applications using Microsoft Defender for Cloud. + */ +@Fluent +public final class UserSecurityContext implements JsonSerializable { + + /* + * The name of the application. Sensitive personal information should not be included in this field. + */ + @Generated + private String applicationName; + + /* + * This identifier is the Microsoft Entra ID (formerly Azure Active Directory) user object ID used to authenticate + * end-users within the generative AI application. Sensitive personal information should not be included in this + * field. + */ + @Generated + private String endUserId; + + /* + * The Microsoft 365 tenant ID the end user belongs to. It's required when the generative AI application is multi + * tenant. + */ + @Generated + private String endUserTenantId; + + /* + * Captures the original client's IP address, accepting both IPv4 and IPv6 formats. + */ + @Generated + private String sourceIp; + + /** + * Creates an instance of UserSecurityContext class. + */ + @Generated + public UserSecurityContext() { + } + + /** + * Get the applicationName property: The name of the application. Sensitive personal information should not be + * included in this field. + * + * @return the applicationName value. + */ + @Generated + public String getApplicationName() { + return this.applicationName; + } + + /** + * Set the applicationName property: The name of the application. Sensitive personal information should not be + * included in this field. + * + * @param applicationName the applicationName value to set. + * @return the UserSecurityContext object itself. + */ + @Generated + public UserSecurityContext setApplicationName(String applicationName) { + this.applicationName = applicationName; + return this; + } + + /** + * Get the endUserId property: This identifier is the Microsoft Entra ID (formerly Azure Active Directory) user + * object ID used to authenticate end-users within the generative AI application. Sensitive personal information + * should not be included in this field. + * + * @return the endUserId value. + */ + @Generated + public String getEndUserId() { + return this.endUserId; + } + + /** + * Set the endUserId property: This identifier is the Microsoft Entra ID (formerly Azure Active Directory) user + * object ID used to authenticate end-users within the generative AI application. Sensitive personal information + * should not be included in this field. + * + * @param endUserId the endUserId value to set. + * @return the UserSecurityContext object itself. + */ + @Generated + public UserSecurityContext setEndUserId(String endUserId) { + this.endUserId = endUserId; + return this; + } + + /** + * Get the endUserTenantId property: The Microsoft 365 tenant ID the end user belongs to. It's required when the + * generative AI application is multi tenant. + * + * @return the endUserTenantId value. + */ + @Generated + public String getEndUserTenantId() { + return this.endUserTenantId; + } + + /** + * Set the endUserTenantId property: The Microsoft 365 tenant ID the end user belongs to. It's required when the + * generative AI application is multi tenant. + * + * @param endUserTenantId the endUserTenantId value to set. + * @return the UserSecurityContext object itself. + */ + @Generated + public UserSecurityContext setEndUserTenantId(String endUserTenantId) { + this.endUserTenantId = endUserTenantId; + return this; + } + + /** + * Get the sourceIp property: Captures the original client's IP address, accepting both IPv4 and IPv6 formats. + * + * @return the sourceIp value. + */ + @Generated + public String getSourceIp() { + return this.sourceIp; + } + + /** + * Set the sourceIp property: Captures the original client's IP address, accepting both IPv4 and IPv6 formats. + * + * @param sourceIp the sourceIp value to set. + * @return the UserSecurityContext object itself. + */ + @Generated + public UserSecurityContext setSourceIp(String sourceIp) { + this.sourceIp = sourceIp; + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("application_name", this.applicationName); + jsonWriter.writeStringField("end_user_id", this.endUserId); + jsonWriter.writeStringField("end_user_tenant_id", this.endUserTenantId); + jsonWriter.writeStringField("source_ip", this.sourceIp); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of UserSecurityContext from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of UserSecurityContext 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 UserSecurityContext. + */ + @Generated + public static UserSecurityContext fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + UserSecurityContext deserializedUserSecurityContext = new UserSecurityContext(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("application_name".equals(fieldName)) { + deserializedUserSecurityContext.applicationName = reader.getString(); + } else if ("end_user_id".equals(fieldName)) { + deserializedUserSecurityContext.endUserId = reader.getString(); + } else if ("end_user_tenant_id".equals(fieldName)) { + deserializedUserSecurityContext.endUserTenantId = reader.getString(); + } else if ("source_ip".equals(fieldName)) { + deserializedUserSecurityContext.sourceIp = reader.getString(); + } else { + reader.skipChildren(); + } + } + return deserializedUserSecurityContext; + }); + } +} diff --git a/sdk/openai/azure-ai-openai/src/main/resources/META-INF/azure-ai-openai_apiview_properties.json b/sdk/openai/azure-ai-openai/src/main/resources/META-INF/azure-ai-openai_apiview_properties.json index 5682444df68d..7852ed3973d2 100644 --- a/sdk/openai/azure-ai-openai/src/main/resources/META-INF/azure-ai-openai_apiview_properties.json +++ b/sdk/openai/azure-ai-openai/src/main/resources/META-INF/azure-ai-openai_apiview_properties.json @@ -97,6 +97,8 @@ "com.azure.ai.openai.implementation.models.OpenAIPageableListOfBatch": "Azure.OpenAI.OpenAIPageableListOf", "com.azure.ai.openai.implementation.models.UploadFileRequest": "Client.uploadFile.Request.anonymous", "com.azure.ai.openai.models.AddUploadPartRequest": "Azure.OpenAI.AddUploadPartRequest", + "com.azure.ai.openai.models.AudioOutputParameters": "Azure.OpenAI.AudioOutputParameters", + "com.azure.ai.openai.models.AudioResponseData": "Azure.OpenAI.AudioResponseData", "com.azure.ai.openai.models.AudioTaskLabel": "Azure.OpenAI.AudioTaskLabel", "com.azure.ai.openai.models.AudioTranscription": "Azure.OpenAI.AudioTranscription", "com.azure.ai.openai.models.AudioTranscriptionFormat": "Azure.OpenAI.AudioTranscriptionFormat", @@ -137,6 +139,7 @@ "com.azure.ai.openai.models.BatchStatus": "Azure.OpenAI.BatchStatus", "com.azure.ai.openai.models.ChatChoice": "Azure.OpenAI.ChatChoice", "com.azure.ai.openai.models.ChatChoiceLogProbabilityInfo": "Azure.OpenAI.ChatChoiceLogProbabilityInfo", + "com.azure.ai.openai.models.ChatCompletionModality": "Azure.OpenAI.ChatCompletionModality", "com.azure.ai.openai.models.ChatCompletionStreamOptions": "Azure.OpenAI.ChatCompletionStreamOptions", "com.azure.ai.openai.models.ChatCompletions": "Azure.OpenAI.ChatCompletions", "com.azure.ai.openai.models.ChatCompletionsFunctionToolCall": "Azure.OpenAI.ChatCompletionsFunctionToolCall", @@ -154,6 +157,7 @@ "com.azure.ai.openai.models.ChatCompletionsToolCall": "Azure.OpenAI.ChatCompletionsToolCall", "com.azure.ai.openai.models.ChatCompletionsToolDefinition": "Azure.OpenAI.ChatCompletionsToolDefinition", "com.azure.ai.openai.models.ChatCompletionsToolSelectionPreset": "Azure.OpenAI.ChatCompletionsToolSelectionPreset", + "com.azure.ai.openai.models.ChatMessageAudioContentItem": "Azure.OpenAI.ChatMessageAudioContentItem", "com.azure.ai.openai.models.ChatMessageContentItem": "Azure.OpenAI.ChatMessageContentItem", "com.azure.ai.openai.models.ChatMessageImageContentItem": "Azure.OpenAI.ChatMessageImageContentItem", "com.azure.ai.openai.models.ChatMessageImageDetailLevel": "Azure.OpenAI.ChatMessageImageDetailLevel", @@ -161,6 +165,7 @@ "com.azure.ai.openai.models.ChatMessageRefusalContentItem": "Azure.OpenAI.ChatMessageRefusalContentItem", "com.azure.ai.openai.models.ChatMessageTextContentItem": "Azure.OpenAI.ChatMessageTextContentItem", "com.azure.ai.openai.models.ChatRequestAssistantMessage": "Azure.OpenAI.ChatRequestAssistantMessage", + "com.azure.ai.openai.models.ChatRequestDeveloperMessage": "Azure.OpenAI.ChatRequestDeveloperMessage", "com.azure.ai.openai.models.ChatRequestFunctionMessage": "Azure.OpenAI.ChatRequestFunctionMessage", "com.azure.ai.openai.models.ChatRequestMessage": "Azure.OpenAI.ChatRequestMessage", "com.azure.ai.openai.models.ChatRequestSystemMessage": "Azure.OpenAI.ChatRequestSystemMessage", @@ -218,6 +223,8 @@ "com.azure.ai.openai.models.ImageGenerationStyle": "Azure.OpenAI.ImageGenerationStyle", "com.azure.ai.openai.models.ImageGenerations": "Azure.OpenAI.ImageGenerations", "com.azure.ai.openai.models.ImageSize": "Azure.OpenAI.ImageSize", + "com.azure.ai.openai.models.InputAudioContent": "Azure.OpenAI.InputAudioContent", + "com.azure.ai.openai.models.InputAudioFormat": "Azure.OpenAI.InputAudioFormat", "com.azure.ai.openai.models.MongoDBChatExtensionConfiguration": "Azure.OpenAI.MongoDBChatExtensionConfiguration", "com.azure.ai.openai.models.MongoDBChatExtensionParameters": "Azure.OpenAI.MongoDBChatExtensionParameters", "com.azure.ai.openai.models.MongoDBChatExtensionParametersFieldsMapping": "Azure.OpenAI.MongoDBChatExtensionParameters.fields_mapping.anonymous", @@ -243,9 +250,13 @@ "com.azure.ai.openai.models.OnYourDataVectorizationSource": "Azure.OpenAI.OnYourDataVectorizationSource", "com.azure.ai.openai.models.OnYourDataVectorizationSourceType": "Azure.OpenAI.OnYourDataVectorizationSourceType", "com.azure.ai.openai.models.OpenAIFile": "Azure.OpenAI.OpenAIFile", + "com.azure.ai.openai.models.OutputAudioFormat": "Azure.OpenAI.OutputAudioFormat", "com.azure.ai.openai.models.PineconeChatExtensionConfiguration": "Azure.OpenAI.PineconeChatExtensionConfiguration", "com.azure.ai.openai.models.PineconeChatExtensionParameters": "Azure.OpenAI.PineconeChatExtensionParameters", "com.azure.ai.openai.models.PineconeFieldMappingOptions": "Azure.OpenAI.PineconeFieldMappingOptions", + "com.azure.ai.openai.models.PredictionContent": "Azure.OpenAI.PredictionContent", + "com.azure.ai.openai.models.PredictionContentType": "Azure.OpenAI.PredictionContentType", + "com.azure.ai.openai.models.ReasoningEffortValue": "Azure.OpenAI.ReasoningEffortValue", "com.azure.ai.openai.models.SpeechGenerationOptions": "Azure.OpenAI.SpeechGenerationOptions", "com.azure.ai.openai.models.SpeechGenerationResponseFormat": "Azure.OpenAI.SpeechGenerationResponseFormat", "com.azure.ai.openai.models.SpeechVoice": "Azure.OpenAI.SpeechVoice", @@ -253,6 +264,7 @@ "com.azure.ai.openai.models.UploadObject": null, "com.azure.ai.openai.models.UploadPart": "Azure.OpenAI.UploadPart", "com.azure.ai.openai.models.UploadPurpose": "Azure.OpenAI.Upload.purpose.anonymous", - "com.azure.ai.openai.models.UploadStatus": "Azure.OpenAI.Upload.status.anonymous" + "com.azure.ai.openai.models.UploadStatus": "Azure.OpenAI.Upload.status.anonymous", + "com.azure.ai.openai.models.UserSecurityContext": "Azure.OpenAI.UserSecurityContext" } } diff --git a/sdk/openai/azure-ai-openai/src/samples/README.md b/sdk/openai/azure-ai-openai/src/samples/README.md index abc01c0e3043..7929cf7e336d 100644 --- a/sdk/openai/azure-ai-openai/src/samples/README.md +++ b/sdk/openai/azure-ai-openai/src/samples/README.md @@ -109,4 +109,4 @@ This project welcomes contributions and suggestions. Find [more contributing][SD [cookbook_summarize_text]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/openai/azure-ai-openai/src/samples/java/com/azure/ai/openai/SummarizeTextSample.java [cookbook_streaming_tool_call]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/openai/azure-ai-openai/src/samples/java/com/azure/ai/openai/StreamingToolCall.java [cookbook_structured_output_response_format]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/openai/azure-ai-openai/src/samples/java/com/azure/ai/openai/StructuredOutputsResponseFormat.java -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fopenai%2Fazure-ai-openai%2FREADME.png) + diff --git a/sdk/openai/azure-ai-openai/src/samples/java/com/azure/ai/openai/AudioChatCompletions.java b/sdk/openai/azure-ai-openai/src/samples/java/com/azure/ai/openai/AudioChatCompletions.java new file mode 100644 index 000000000000..75fda3d155ff --- /dev/null +++ b/sdk/openai/azure-ai-openai/src/samples/java/com/azure/ai/openai/AudioChatCompletions.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.ai.openai.models.AudioOutputParameters; +import com.azure.ai.openai.models.AudioResponseData; +import com.azure.ai.openai.models.ChatChoice; +import com.azure.ai.openai.models.ChatCompletionModality; +import com.azure.ai.openai.models.ChatCompletions; +import com.azure.ai.openai.models.ChatCompletionsOptions; +import com.azure.ai.openai.models.ChatMessageAudioContentItem; +import com.azure.ai.openai.models.ChatRequestUserMessage; +import com.azure.ai.openai.models.ChatResponseMessage; +import com.azure.ai.openai.models.InputAudioContent; +import com.azure.ai.openai.models.InputAudioFormat; +import com.azure.ai.openai.models.OutputAudioFormat; +import com.azure.ai.openai.models.SpeechVoice; +import com.azure.core.credential.AzureKeyCredential; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Configuration; + +import java.nio.file.Paths; +import java.util.Arrays; + +/** + * Sample demonstrates how to use the Azure OpenAI Service to get chat completions with audio input and output. + */ +public class AudioChatCompletions { + + /** + * Main method to run the sample. + * + * @param args Command line arguments. Unused. + */ + public static void main(String[] args) { + String azureOpenaiKey = Configuration.getGlobalConfiguration().get("AZURE_OPENAI_KEY"); + String endpoint = Configuration.getGlobalConfiguration().get("AZURE_OPENAI_ENDPOINT"); + String deploymentOrModelId = "{azure-open-ai-deployment-model-id}"; //gpt-4o-audio-preview + + OpenAIClient client = new OpenAIClientBuilder() + .endpoint(endpoint) + .credential(new AzureKeyCredential(azureOpenaiKey)) + .buildClient(); + + byte[] file + = BinaryData.fromFile(Paths.get("path/file/prompt.wav")).toBytes(); + + ChatCompletionsOptions options = new ChatCompletionsOptions(Arrays.asList( + new ChatRequestUserMessage(Arrays.asList(new ChatMessageAudioContentItem( + new InputAudioContent(file, InputAudioFormat.WAV)))))); + options.setModalities(Arrays.asList(ChatCompletionModality.TEXT, ChatCompletionModality.AUDIO)); + options.setStore(true); + options.setAudio(new AudioOutputParameters(SpeechVoice.ALLOY, OutputAudioFormat.WAV)); + + ChatCompletions chatCompletions = client.getChatCompletions(deploymentOrModelId, options); + ChatChoice choice = chatCompletions.getChoices().get(0); + ChatResponseMessage message = choice.getMessage(); + + // Assert that the message has content + AudioResponseData audioResponse = message.getAudio(); + + String audioData = audioResponse.getData(); // Base64 encoded audio data + String transcript = audioResponse.getTranscript(); // Transcription of the audio + } +} diff --git a/sdk/openai/azure-ai-openai/src/samples/java/com/azure/ai/openai/PredictionChatCompletion.java b/sdk/openai/azure-ai-openai/src/samples/java/com/azure/ai/openai/PredictionChatCompletion.java new file mode 100644 index 000000000000..478f4529a074 --- /dev/null +++ b/sdk/openai/azure-ai-openai/src/samples/java/com/azure/ai/openai/PredictionChatCompletion.java @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.openai; + +import com.azure.ai.openai.models.ChatChoice; +import com.azure.ai.openai.models.ChatCompletions; +import com.azure.ai.openai.models.ChatCompletionsOptions; +import com.azure.ai.openai.models.ChatRequestUserMessage; +import com.azure.ai.openai.models.ChatResponseMessage; +import com.azure.ai.openai.models.PredictionContent; +import com.azure.core.credential.AzureKeyCredential; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Configuration; + +import java.util.Arrays; + +/** + * This samples demonstrates how to use the Azure OpenAI client to get chat completions with prediction. + */ +public class PredictionChatCompletion { + + /** + * This samples demonstrates how to use the Azure OpenAI client to get chat completions with prediction. + * + * @param args Unused. + */ + public static void main(String[] args) { + String azureOpenaiKey = Configuration.getGlobalConfiguration().get("AZURE_OPENAI_KEY"); + String endpoint = Configuration.getGlobalConfiguration().get("AZURE_OPENAI_ENDPOINT"); + String deploymentOrModelId = "{azure-open-ai-deployment-model-id}"; // o3-mini + + OpenAIClient client = new OpenAIClientBuilder() + .endpoint(endpoint) + .credential(new AzureKeyCredential(azureOpenaiKey)) + .buildClient(); + + String code = "class User {firstName: string; lastName: string;username: string;}"; + String prompt = "Replace the \"username\" property with an \"email\" property. Respond only " + + "with code, and with no markdown formatting."; + ChatCompletionsOptions options = new ChatCompletionsOptions( + Arrays.asList(new ChatRequestUserMessage(code), new ChatRequestUserMessage(prompt))); + options.setStore(true); + options.setPrediction(new PredictionContent(BinaryData.fromString(code))); + + + ChatCompletions chatCompletions = client.getChatCompletions(deploymentOrModelId, options); + ChatChoice choice = chatCompletions.getChoices().get(0); + ChatResponseMessage message = choice.getMessage(); + + // you can get a measurement of the tokens used for the prediction + chatCompletions.getUsage().getCompletionTokensDetails().getAcceptedPredictionTokens(); + chatCompletions.getUsage().getCompletionTokensDetails().getRejectedPredictionTokens(); + } +} diff --git a/sdk/openai/azure-ai-openai/src/samples/java/com/azure/ai/openai/ReasoningEffort.java b/sdk/openai/azure-ai-openai/src/samples/java/com/azure/ai/openai/ReasoningEffort.java new file mode 100644 index 000000000000..5b6b54b48314 --- /dev/null +++ b/sdk/openai/azure-ai-openai/src/samples/java/com/azure/ai/openai/ReasoningEffort.java @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.openai; + +import com.azure.ai.openai.models.ChatChoice; +import com.azure.ai.openai.models.ChatCompletions; +import com.azure.ai.openai.models.ChatCompletionsOptions; +import com.azure.ai.openai.models.ChatRequestUserMessage; +import com.azure.ai.openai.models.ChatResponseMessage; +import com.azure.ai.openai.models.ReasoningEffortValue; +import com.azure.core.credential.AzureKeyCredential; +import com.azure.core.util.Configuration; + +import java.util.Arrays; + +/** + * Sample demonstrates how to use the Azure OpenAI client to get chat completions with reasoning effort. + */ +public class ReasoningEffort { + + /** + * Main method to invoke this demo about how to use the Azure OpenAI client to get chat completions with reasoning + * @param args Unused. + */ + public static void main(String[] args) { + String azureOpenaiKey = Configuration.getGlobalConfiguration().get("AZURE_OPENAI_KEY"); + String endpoint = Configuration.getGlobalConfiguration().get("AZURE_OPENAI_ENDPOINT"); + String deploymentOrModelId = "{azure-open-ai-deployment-model-id}"; // o3-mini + + OpenAIClient client = new OpenAIClientBuilder() + .endpoint(endpoint) + .credential(new AzureKeyCredential(azureOpenaiKey)) + .buildClient(); + + ChatCompletionsOptions options = new ChatCompletionsOptions(Arrays + .asList(new ChatRequestUserMessage("Write a bash script that takes a matrix represented as a string with " + + "format '[1,2],[3,4],[5,6]' and prints the transpose in the same format."))); + options.setStore(true); + options.setReasoningEffort(ReasoningEffortValue.MEDIUM); + + ChatCompletions chatCompletions = client.getChatCompletions(deploymentOrModelId, options); + ChatChoice choice = chatCompletions.getChoices().get(0); + ChatResponseMessage message = choice.getMessage(); + + // you can get a measurement of the tokens used for reasoning + chatCompletions.getUsage().getCompletionTokensDetails().getReasoningTokens(); + } +} 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 6ab78a2039ec..3d694701d3bf 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,6 +3,7 @@ package com.azure.ai.openai; +import com.azure.ai.openai.models.AudioResponseData; import com.azure.ai.openai.models.AudioTaskLabel; import com.azure.ai.openai.models.AudioTranscriptionFormat; import com.azure.ai.openai.models.AudioTranscriptionTimestampGranularity; @@ -229,6 +230,130 @@ public void testGetChatCompletions(HttpClient httpClient, OpenAIServiceVersion s }); } + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.openai.TestUtils#getTestParameters") + public void testGetChatCompletionsTextPromptAudioResponse(HttpClient httpClient, + OpenAIServiceVersion serviceVersion) { + client = getNonAzureOpenAIAsyncClient(httpClient); + getChatCompletionsWithTextPromptAudioResponse((deploymentId, options) -> { + StepVerifier.create(client.getChatCompletions(deploymentId, options)).assertNext(chatCompletions -> { + ChatChoice choice = chatCompletions.getChoices().get(0); + ChatResponseMessage message = choice.getMessage(); + + // Assert that the message has content + assertEquals(ChatRole.ASSISTANT, message.getRole()); + AudioResponseData audioResponse = message.getAudio(); + assertNotNull(audioResponse); + assertFalse(CoreUtils.isNullOrEmpty(audioResponse.getId())); + assertFalse(CoreUtils.isNullOrEmpty(audioResponse.getData())); + assertFalse(CoreUtils.isNullOrEmpty(audioResponse.getTranscript())); + assertNotNull(audioResponse.getExpiresAt()); + + // Assert finish reason + assertEquals(CompletionsFinishReason.STOPPED, choice.getFinishReason()); + CompletionsUsage usage = chatCompletions.getUsage(); + + // assert that we only used audio tokens for the response + assertNotNull(usage); + assertNotNull(usage.getPromptTokensDetails()); + assertNotNull(usage.getCompletionTokensDetails()); + + assertEquals(0, usage.getPromptTokensDetails().getAudioTokens()); + assertTrue(usage.getCompletionTokensDetails().getAudioTokens() > 0); + }).verifyComplete(); + }); + } + + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.openai.TestUtils#getTestParameters") + public void testGetChatCompletionsAudioPromptAudioResponse(HttpClient httpClient, + OpenAIServiceVersion serviceVersion) { + client = getNonAzureOpenAIAsyncClient(httpClient); + getChatCompletionsWithAudioPromptAudioResponse((deploymentId, options) -> { + StepVerifier.create(client.getChatCompletions(deploymentId, options)).assertNext(chatCompletions -> { + ChatChoice choice = chatCompletions.getChoices().get(0); + ChatResponseMessage message = choice.getMessage(); + + // Assert that the message has content + assertEquals(ChatRole.ASSISTANT, message.getRole()); + AudioResponseData audioResponse = message.getAudio(); + assertNotNull(audioResponse); + assertFalse(CoreUtils.isNullOrEmpty(audioResponse.getId())); + assertFalse(CoreUtils.isNullOrEmpty(audioResponse.getData())); + assertFalse(CoreUtils.isNullOrEmpty(audioResponse.getTranscript())); + assertNotNull(audioResponse.getExpiresAt()); + + // Assert finish reason + assertEquals(CompletionsFinishReason.STOPPED, choice.getFinishReason()); + CompletionsUsage usage = chatCompletions.getUsage(); + + // assert that we only used audio tokens for the response + assertNotNull(usage); + assertNotNull(usage.getPromptTokensDetails()); + assertNotNull(usage.getCompletionTokensDetails()); + + assertTrue(usage.getPromptTokensDetails().getAudioTokens() > 0); + assertTrue(usage.getCompletionTokensDetails().getAudioTokens() > 0); + }).verifyComplete(); + }); + } + + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.openai.TestUtils#getTestParameters") + public void testGetChatCompletionsReasoningEffortMedium(HttpClient httpClient, + OpenAIServiceVersion serviceVersion) { + client = getNonAzureOpenAIAsyncClient(httpClient); + getChatCompletionsWithReasoningEffort((deploymentId, options) -> { + StepVerifier.create(client.getChatCompletions(deploymentId, options)).assertNext(chatCompletions -> { + ChatChoice choice = chatCompletions.getChoices().get(0); + ChatResponseMessage message = choice.getMessage(); + + // Assert that the message has content + assertEquals(ChatRole.ASSISTANT, message.getRole()); + assertFalse(CoreUtils.isNullOrEmpty(message.getContent())); + + // Assert finish reason + assertEquals(CompletionsFinishReason.STOPPED, choice.getFinishReason()); + CompletionsUsage usage = chatCompletions.getUsage(); + + // assert that we only used audio tokens for the response + assertNotNull(usage); + assertNotNull(usage.getPromptTokensDetails()); + assertNotNull(usage.getCompletionTokensDetails()); + + assertTrue(usage.getCompletionTokensDetails().getReasoningTokens() > 0); + }).verifyComplete(); + }); + } + + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.openai.TestUtils#getTestParameters") + public void testGetChatCompletionsPrediction(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { + client = getNonAzureOpenAIAsyncClient(httpClient); + getChatCompletionsWithPrediction((deploymentId, options) -> { + StepVerifier.create(client.getChatCompletions(deploymentId, options)).assertNext(chatCompletions -> { + ChatChoice choice = chatCompletions.getChoices().get(0); + ChatResponseMessage message = choice.getMessage(); + + // Assert that the message has content + assertEquals(ChatRole.ASSISTANT, message.getRole()); + assertFalse(CoreUtils.isNullOrEmpty(message.getContent())); + + // Assert finish reason + assertEquals(CompletionsFinishReason.STOPPED, choice.getFinishReason()); + CompletionsUsage usage = chatCompletions.getUsage(); + + // assert that we only used audio tokens for the response + assertNotNull(usage); + assertNotNull(usage.getPromptTokensDetails()); + assertNotNull(usage.getCompletionTokensDetails()); + + assertTrue(usage.getCompletionTokensDetails().getAcceptedPredictionTokens() > 0); + assertTrue(usage.getCompletionTokensDetails().getRejectedPredictionTokens() > 0); + }).verifyComplete(); + }); + } + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils#getTestParameters") public void testGetChatCompletionsTokenCutoff(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { 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 e41fe8492f17..234cdd47a338 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,6 +3,7 @@ package com.azure.ai.openai; +import com.azure.ai.openai.models.AudioResponseData; import com.azure.ai.openai.models.AudioTaskLabel; import com.azure.ai.openai.models.AudioTranscription; import com.azure.ai.openai.models.AudioTranscriptionFormat; @@ -209,6 +210,127 @@ public void testGetChatCompletions(HttpClient httpClient, OpenAIServiceVersion s }); } + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.openai.TestUtils#getTestParameters") + public void testGetChatCompletionsTextPromptAudioResponse(HttpClient httpClient, + OpenAIServiceVersion serviceVersion) { + client = getNonAzureOpenAISyncClient(httpClient); + getChatCompletionsWithTextPromptAudioResponse((deploymentId, options) -> { + ChatCompletions chatCompletions = client.getChatCompletions(deploymentId, options); + ChatChoice choice = chatCompletions.getChoices().get(0); + ChatResponseMessage message = choice.getMessage(); + + // Assert that the message has content + assertEquals(ChatRole.ASSISTANT, message.getRole()); + AudioResponseData audioResponse = message.getAudio(); + assertNotNull(audioResponse); + assertFalse(CoreUtils.isNullOrEmpty(audioResponse.getId())); + assertFalse(CoreUtils.isNullOrEmpty(audioResponse.getData())); + assertFalse(CoreUtils.isNullOrEmpty(audioResponse.getTranscript())); + assertNotNull(audioResponse.getExpiresAt()); + + // Assert finish reason + assertEquals(CompletionsFinishReason.STOPPED, choice.getFinishReason()); + CompletionsUsage usage = chatCompletions.getUsage(); + + // assert that we only used audio tokens for the response + assertNotNull(usage); + assertNotNull(usage.getPromptTokensDetails()); + assertNotNull(usage.getCompletionTokensDetails()); + + assertEquals(0, usage.getPromptTokensDetails().getAudioTokens()); + assertTrue(usage.getCompletionTokensDetails().getAudioTokens() > 0); + }); + } + + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.openai.TestUtils#getTestParameters") + public void testGetChatCompletionsAudioPromptAudioResponse(HttpClient httpClient, + OpenAIServiceVersion serviceVersion) { + client = getNonAzureOpenAISyncClient(httpClient); + getChatCompletionsWithAudioPromptAudioResponse((deploymentId, options) -> { + ChatCompletions chatCompletions = client.getChatCompletions(deploymentId, options); + ChatChoice choice = chatCompletions.getChoices().get(0); + ChatResponseMessage message = choice.getMessage(); + + // Assert that the message has content + assertEquals(ChatRole.ASSISTANT, message.getRole()); + AudioResponseData audioResponse = message.getAudio(); + assertNotNull(audioResponse); + assertFalse(CoreUtils.isNullOrEmpty(audioResponse.getId())); + assertFalse(CoreUtils.isNullOrEmpty(audioResponse.getData())); + assertFalse(CoreUtils.isNullOrEmpty(audioResponse.getTranscript())); + assertNotNull(audioResponse.getExpiresAt()); + + // Assert finish reason + assertEquals(CompletionsFinishReason.STOPPED, choice.getFinishReason()); + CompletionsUsage usage = chatCompletions.getUsage(); + + // assert that we only used audio tokens for the response + assertNotNull(usage); + assertNotNull(usage.getPromptTokensDetails()); + assertNotNull(usage.getCompletionTokensDetails()); + + assertTrue(usage.getPromptTokensDetails().getAudioTokens() > 0); + assertTrue(usage.getCompletionTokensDetails().getAudioTokens() > 0); + }); + } + + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.openai.TestUtils#getTestParameters") + public void testGetChatCompletionsReasoningEffortMedium(HttpClient httpClient, + OpenAIServiceVersion serviceVersion) { + client = getNonAzureOpenAISyncClient(httpClient); + getChatCompletionsWithReasoningEffort((deploymentId, options) -> { + ChatCompletions chatCompletions = client.getChatCompletions(deploymentId, options); + ChatChoice choice = chatCompletions.getChoices().get(0); + ChatResponseMessage message = choice.getMessage(); + + // Assert that the message has content + assertEquals(ChatRole.ASSISTANT, message.getRole()); + assertFalse(CoreUtils.isNullOrEmpty(message.getContent())); + + // Assert finish reason + assertEquals(CompletionsFinishReason.STOPPED, choice.getFinishReason()); + CompletionsUsage usage = chatCompletions.getUsage(); + + // assert that we only used audio tokens for the response + assertNotNull(usage); + assertNotNull(usage.getPromptTokensDetails()); + assertNotNull(usage.getCompletionTokensDetails()); + + assertTrue(usage.getCompletionTokensDetails().getReasoningTokens() > 0); + }); + } + + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.openai.TestUtils#getTestParameters") + public void testGetChatCompletionsPrediction(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { + client = getNonAzureOpenAISyncClient(httpClient); + getChatCompletionsWithPrediction((deploymentId, options) -> { + ChatCompletions chatCompletions = client.getChatCompletions(deploymentId, options); + ChatChoice choice = chatCompletions.getChoices().get(0); + ChatResponseMessage message = choice.getMessage(); + + // Assert that the message has content + assertEquals(ChatRole.ASSISTANT, message.getRole()); + assertFalse(CoreUtils.isNullOrEmpty(message.getContent())); + + // Assert finish reason + assertEquals(CompletionsFinishReason.STOPPED, choice.getFinishReason()); + CompletionsUsage usage = chatCompletions.getUsage(); + + // assert that we only used audio tokens for the response + assertNotNull(usage); + assertNotNull(usage.getPromptTokensDetails()); + assertNotNull(usage.getCompletionTokensDetails()); + + assertTrue(usage.getCompletionTokensDetails().getAcceptedPredictionTokens() > 0); + assertTrue(usage.getCompletionTokensDetails().getRejectedPredictionTokens() > 0); + + }); + } + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils#getTestParameters") public void testGetChatCompletionsTokenCutoff(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { 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 bb66c8152ba6..b20a9666a6a2 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,6 +3,7 @@ package com.azure.ai.openai; +import com.azure.ai.openai.models.AudioResponseData; import com.azure.ai.openai.models.AudioTaskLabel; import com.azure.ai.openai.models.AudioTranscriptionFormat; import com.azure.ai.openai.models.AudioTranscriptionTimestampGranularity; @@ -100,11 +101,24 @@ public void testGetCompletionsStream(HttpClient httpClient, OpenAIServiceVersion getCompletionsRunner((deploymentId, prompt) -> { StepVerifier.create(client.getCompletionsStream(deploymentId, new CompletionsOptions(prompt))) .recordWith(ArrayList::new) - .thenConsumeWhile(chatCompletions -> { - assertCompletionsStream(chatCompletions); - return true; + .thenConsumeWhile(completions -> true) + .consumeRecordedWith(messageList -> { + assertTrue(messageList.size() > 1); + + Object[] result = messageList.stream().toArray(); + Completions[] completionsArray = Arrays.copyOf(result, result.length, Completions[].class); + + assertTrue(completionsArray.length > 1); + // First element returns the prompt filter results (no output tokens are present) + assertFalse(CoreUtils.isNullOrEmpty(completionsArray[0].getPromptFilterResults())); + // Choices (output tokens) are present in all the elements in between + for (int i = 1; i < completionsArray.length - 2; i++) { + assertCompletionsStream(completionsArray[i]); + } + + // Last element returns the completion tokens (no output tokens are present) + assertNotNull(completionsArray[completionsArray.length - 1].getUsage()); }) - .consumeRecordedWith(messageList -> assertTrue(messageList.size() > 1)) .verifyComplete(); }); } @@ -229,6 +243,130 @@ public void testGetChatCompletions(HttpClient httpClient, OpenAIServiceVersion s }); } + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.openai.TestUtils#getTestParameters") + public void testGetChatCompletionsTextPromptAudioResponse(HttpClient httpClient, + OpenAIServiceVersion serviceVersion) { + client = getOpenAIAsyncClient(httpClient, serviceVersion); + getChatCompletionsWithTextPromptAudioResponse((deploymentId, options) -> { + StepVerifier.create(client.getChatCompletions(deploymentId, options)).assertNext(chatCompletions -> { + ChatChoice choice = chatCompletions.getChoices().get(0); + ChatResponseMessage message = choice.getMessage(); + + // Assert that the message has content + assertEquals(ChatRole.ASSISTANT, message.getRole()); + AudioResponseData audioResponse = message.getAudio(); + assertNotNull(audioResponse); + assertFalse(CoreUtils.isNullOrEmpty(audioResponse.getId())); + assertFalse(CoreUtils.isNullOrEmpty(audioResponse.getData())); + assertFalse(CoreUtils.isNullOrEmpty(audioResponse.getTranscript())); + assertNotNull(audioResponse.getExpiresAt()); + + // Assert finish reason + assertEquals(CompletionsFinishReason.STOPPED, choice.getFinishReason()); + CompletionsUsage usage = chatCompletions.getUsage(); + + // assert that we only used audio tokens for the response + assertNotNull(usage); + assertNotNull(usage.getPromptTokensDetails()); + assertNotNull(usage.getCompletionTokensDetails()); + + assertEquals(0, usage.getPromptTokensDetails().getAudioTokens()); + assertTrue(usage.getCompletionTokensDetails().getAudioTokens() > 0); + }).verifyComplete(); + }); + } + + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.openai.TestUtils#getTestParameters") + public void testGetChatCompletionsAudioPromptAudioResponse(HttpClient httpClient, + OpenAIServiceVersion serviceVersion) { + client = getOpenAIAsyncClient(httpClient, serviceVersion); + getChatCompletionsWithAudioPromptAudioResponse((deploymentId, options) -> { + StepVerifier.create(client.getChatCompletions(deploymentId, options)).assertNext(chatCompletions -> { + ChatChoice choice = chatCompletions.getChoices().get(0); + ChatResponseMessage message = choice.getMessage(); + + // Assert that the message has content + assertEquals(ChatRole.ASSISTANT, message.getRole()); + AudioResponseData audioResponse = message.getAudio(); + assertNotNull(audioResponse); + assertFalse(CoreUtils.isNullOrEmpty(audioResponse.getId())); + assertFalse(CoreUtils.isNullOrEmpty(audioResponse.getData())); + assertFalse(CoreUtils.isNullOrEmpty(audioResponse.getTranscript())); + assertNotNull(audioResponse.getExpiresAt()); + + // Assert finish reason + assertEquals(CompletionsFinishReason.STOPPED, choice.getFinishReason()); + CompletionsUsage usage = chatCompletions.getUsage(); + + // assert that we only used audio tokens for the response + assertNotNull(usage); + assertNotNull(usage.getPromptTokensDetails()); + assertNotNull(usage.getCompletionTokensDetails()); + + assertTrue(usage.getPromptTokensDetails().getAudioTokens() > 0); + assertTrue(usage.getCompletionTokensDetails().getAudioTokens() > 0); + }).verifyComplete(); + }); + } + + @Disabled("There is no instance supporting this feature yet") + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.openai.TestUtils#getTestParameters") + public void testGetChatCompletionsReasoningEffortLow(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { + client = getOpenAIAsyncClient(httpClient, serviceVersion); + getChatCompletionsWithReasoningEffortForAzure((deploymentId, options) -> { + StepVerifier.create(client.getChatCompletions(deploymentId, options)).assertNext(chatCompletions -> { + ChatChoice choice = chatCompletions.getChoices().get(0); + ChatResponseMessage message = choice.getMessage(); + + // Assert that the message has content + assertEquals(ChatRole.ASSISTANT, message.getRole()); + assertFalse(CoreUtils.isNullOrEmpty(message.getContent())); + + // Assert finish reason + assertEquals(CompletionsFinishReason.STOPPED, choice.getFinishReason()); + CompletionsUsage usage = chatCompletions.getUsage(); + + // assert that we only used audio tokens for the response + assertNotNull(usage); + assertNotNull(usage.getPromptTokensDetails()); + assertNotNull(usage.getCompletionTokensDetails()); + + assertTrue(usage.getCompletionTokensDetails().getReasoningTokens() > 0); + }).verifyComplete(); + }); + } + + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.openai.TestUtils#getTestParameters") + public void testGetChatCompletionsPrediction(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { + client = getOpenAIAsyncClient(httpClient, serviceVersion); + getChatCompletionsWithPredictionForAzure((deploymentId, options) -> { + StepVerifier.create(client.getChatCompletions(deploymentId, options)).assertNext(chatCompletions -> { + ChatChoice choice = chatCompletions.getChoices().get(0); + ChatResponseMessage message = choice.getMessage(); + + // Assert that the message has content + assertEquals(ChatRole.ASSISTANT, message.getRole()); + assertFalse(CoreUtils.isNullOrEmpty(message.getContent())); + + // Assert finish reason + assertEquals(CompletionsFinishReason.STOPPED, choice.getFinishReason()); + CompletionsUsage usage = chatCompletions.getUsage(); + + // assert that we only used audio tokens for the response + assertNotNull(usage); + assertNotNull(usage.getPromptTokensDetails()); + assertNotNull(usage.getCompletionTokensDetails()); + + assertTrue(usage.getCompletionTokensDetails().getAcceptedPredictionTokens() > 0); + assertTrue(usage.getCompletionTokensDetails().getRejectedPredictionTokens() > 0); + }).verifyComplete(); + }); + } + @Disabled("Unrecognized request argument supplied: max_completion_tokens") @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils#getTestParameters") @@ -567,13 +705,9 @@ public void testCompletionStreamContentFiltering(HttpClient httpClient, OpenAISe CompletionsOptions completionsOptions = new CompletionsOptions(Arrays.asList(prompt)); StepVerifier.create(client.getCompletionsStream(modelId, completionsOptions)) .recordWith(ArrayList::new) - .thenConsumeWhile(chatCompletions -> { - assertCompletionsStream(chatCompletions); - return true; - }) + .thenConsumeWhile(chatCompletions -> true) .consumeRecordedWith(messageList -> { assertTrue(messageList.size() > 1); - int i = 0; for (Iterator it = messageList.iterator(); it.hasNext();) { Completions completions = it.next(); @@ -581,19 +715,19 @@ public void testCompletionStreamContentFiltering(HttpClient httpClient, OpenAISe assertEquals(1, completions.getPromptFilterResults().size()); assertSafePromptContentFilterResults(completions.getPromptFilterResults().get(0)); } else if (i == messageList.size() - 1) { - // The last stream message is empty with all the filters set to null - assertEquals(1, completions.getChoices().size()); - Choice choice = completions.getChoices().get(0); - assertEquals(CompletionsFinishReason.fromString("stop"), choice.getFinishReason()); - assertNotNull(choice.getText()); - // TODO (team): change in behaviour, this used to be uncommented - // assertSafeChoiceContentFilterResults(choice.getContentFilterResults()); + // The last contains only the token usage + assertEquals(0, completions.getChoices().size()); + assertEquals( + completions.getUsage().getCompletionTokens() + completions.getUsage().getPromptTokens(), + completions.getUsage().getTotalTokens()); } else { // The rest of the intermediary messages have the text generation content filter set assertNull(completions.getPromptFilterResults()); - assertNotNull(completions.getChoices().get(0)); - assertSafeChoiceContentFilterResults( - completions.getChoices().get(0).getContentFilterResults()); + Choice choice = completions.getChoices().get(0); + assertNotNull(choice); + if (choice.getFinishReason() == null) { + assertSafeChoiceContentFilterResults(choice.getContentFilterResults()); + } } i++; } 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 02fc3fec5135..d36b89504c0f 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 @@ -10,6 +10,7 @@ import com.azure.ai.openai.implementation.accesshelpers.ChatCompletionsOptionsAccessHelper; import com.azure.ai.openai.implementation.accesshelpers.CompletionsOptionsAccessHelper; import com.azure.ai.openai.models.AddUploadPartRequest; +import com.azure.ai.openai.models.AudioOutputParameters; import com.azure.ai.openai.models.AudioTaskLabel; import com.azure.ai.openai.models.AudioTranscription; import com.azure.ai.openai.models.AudioTranscriptionOptions; @@ -21,6 +22,7 @@ import com.azure.ai.openai.models.AzureChatExtensionRetrievedDocument; import com.azure.ai.openai.models.AzureChatExtensionsMessageContext; import com.azure.ai.openai.models.ChatChoice; +import com.azure.ai.openai.models.ChatCompletionModality; import com.azure.ai.openai.models.ChatCompletionStreamOptions; import com.azure.ai.openai.models.ChatCompletions; import com.azure.ai.openai.models.ChatCompletionsFunctionToolCall; @@ -30,6 +32,7 @@ import com.azure.ai.openai.models.ChatCompletionsJsonSchemaResponseFormatJsonSchema; import com.azure.ai.openai.models.ChatCompletionsOptions; import com.azure.ai.openai.models.ChatCompletionsToolDefinition; +import com.azure.ai.openai.models.ChatMessageAudioContentItem; import com.azure.ai.openai.models.ChatMessageImageContentItem; import com.azure.ai.openai.models.ChatMessageImageUrl; import com.azure.ai.openai.models.ChatMessageTextContentItem; @@ -67,7 +70,12 @@ import com.azure.ai.openai.models.ImageGenerationData; import com.azure.ai.openai.models.ImageGenerationOptions; import com.azure.ai.openai.models.ImageGenerations; +import com.azure.ai.openai.models.InputAudioContent; +import com.azure.ai.openai.models.InputAudioFormat; import com.azure.ai.openai.models.OpenAIFile; +import com.azure.ai.openai.models.OutputAudioFormat; +import com.azure.ai.openai.models.PredictionContent; +import com.azure.ai.openai.models.ReasoningEffortValue; import com.azure.ai.openai.models.SpeechGenerationOptions; import com.azure.ai.openai.models.SpeechVoice; import com.azure.core.credential.AzureKeyCredential; @@ -483,6 +491,68 @@ void textToSpeechRunnerForNonAzure(BiConsumer t testRunner.accept("tts-1", getSpeechGenerationOptions()); } + void getChatCompletionsWithTextPromptAudioResponse(BiConsumer testRunner) { + ChatCompletionsOptions chatCompletionsOptions + = new ChatCompletionsOptions(Arrays.asList(new ChatRequestUserMessage("What is the weather in Seattle?"))); + chatCompletionsOptions.setModalities(Arrays.asList(ChatCompletionModality.TEXT, ChatCompletionModality.AUDIO)); + chatCompletionsOptions.setStore(true); + chatCompletionsOptions.setAudio(new AudioOutputParameters(SpeechVoice.ALLOY, OutputAudioFormat.WAV)); + testRunner.accept("gpt-4o-audio-preview", chatCompletionsOptions); + } + + void getChatCompletionsWithAudioPromptAudioResponse(BiConsumer testRunner) { + byte[] file + = BinaryData.fromFile(openTestResourceFile("realtime_whats_the_weather_pcm16_24khz_mono.wav")).toBytes(); + + ChatCompletionsOptions chatCompletionsOptions + = new ChatCompletionsOptions(Arrays.asList(new ChatRequestUserMessage( + Arrays.asList(new ChatMessageAudioContentItem(new InputAudioContent(file, InputAudioFormat.WAV)))))); + chatCompletionsOptions.setModalities(Arrays.asList(ChatCompletionModality.TEXT, ChatCompletionModality.AUDIO)); + chatCompletionsOptions.setStore(true); + chatCompletionsOptions.setAudio(new AudioOutputParameters(SpeechVoice.ALLOY, OutputAudioFormat.WAV)); + testRunner.accept("gpt-4o-audio-preview", chatCompletionsOptions); + } + + void getChatCompletionsWithReasoningEffort(BiConsumer testRunner) { + ChatCompletionsOptions chatCompletionsOptions = new ChatCompletionsOptions(Arrays + .asList(new ChatRequestUserMessage("Write a bash script that takes a matrix represented as a string with " + + "format '[1,2],[3,4],[5,6]' and prints the transpose in the same format."))); + chatCompletionsOptions.setStore(true); + chatCompletionsOptions.setReasoningEffort(ReasoningEffortValue.MEDIUM); + testRunner.accept("o3-mini", chatCompletionsOptions); + } + + void getChatCompletionsWithReasoningEffortForAzure(BiConsumer testRunner) { + ChatCompletionsOptions chatCompletionsOptions = new ChatCompletionsOptions(Arrays + .asList(new ChatRequestUserMessage("Write a bash script that takes a matrix represented as a string with " + + "format '[1,2],[3,4],[5,6]' and prints the transpose in the same format."))); + chatCompletionsOptions.setStore(true); + chatCompletionsOptions.setReasoningEffort(ReasoningEffortValue.LOW); + testRunner.accept("o3-mini-2025-01-31", chatCompletionsOptions); + } + + void getChatCompletionsWithPrediction(BiConsumer testRunner) { + String code = "class User {firstName: string; lastName: string;username: string;}"; + String prompt = "Replace the \"username\" property with an \"email\" property. Respond only " + + "with code, and with no markdown formatting."; + ChatCompletionsOptions chatCompletionsOptions = new ChatCompletionsOptions( + Arrays.asList(new ChatRequestUserMessage(code), new ChatRequestUserMessage(prompt))); + chatCompletionsOptions.setStore(true); + chatCompletionsOptions.setPrediction(new PredictionContent(BinaryData.fromString(code))); + testRunner.accept("gpt-4o", chatCompletionsOptions); + } + + void getChatCompletionsWithPredictionForAzure(BiConsumer testRunner) { + String code = "class User {firstName: string; lastName: string;username: string;}"; + String prompt = "Replace the \"username\" property with an \"email\" property. Respond only " + + "with code, and with no markdown formatting."; + ChatCompletionsOptions chatCompletionsOptions = new ChatCompletionsOptions( + Arrays.asList(new ChatRequestUserMessage(code), new ChatRequestUserMessage(prompt))); + chatCompletionsOptions.setStore(true); + chatCompletionsOptions.setPrediction(new PredictionContent(BinaryData.fromString(code))); + testRunner.accept("gpt-4o-0806", chatCompletionsOptions); + } + // Files void uploadTextFileRunner(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 6ddecd7f59cc..9af40a745ed2 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,6 +2,7 @@ // Licensed under the MIT License. package com.azure.ai.openai; +import com.azure.ai.openai.models.AudioResponseData; import com.azure.ai.openai.models.AudioTaskLabel; import com.azure.ai.openai.models.AudioTranscription; import com.azure.ai.openai.models.AudioTranscriptionFormat; @@ -102,8 +103,20 @@ public void testGetCompletionsStream(HttpClient httpClient, OpenAIServiceVersion getCompletionsRunner((deploymentId, prompt) -> { IterableStream resultCompletions = client.getCompletionsStream(deploymentId, new CompletionsOptions(prompt)); - assertTrue(resultCompletions.stream().toArray().length > 1); - resultCompletions.forEach(OpenAIClientTestBase::assertCompletionsStream); + + Object[] result = resultCompletions.stream().toArray(); + Completions[] completionsArray = Arrays.copyOf(result, result.length, Completions[].class); + + assertTrue(completionsArray.length > 1); + // First element returns the prompt filter results (no output tokens are present) + assertFalse(CoreUtils.isNullOrEmpty(completionsArray[0].getPromptFilterResults())); + // Choices (output tokens) are present in all the elements in between + for (int i = 1; i < completionsArray.length - 2; i++) { + assertCompletionsStream(completionsArray[i]); + } + + // Last element returns the completion tokens (no output tokens are present) + assertNotNull(completionsArray[completionsArray.length - 1].getUsage()); }); } @@ -212,6 +225,127 @@ public void testGetChatCompletions(HttpClient httpClient, OpenAIServiceVersion s }); } + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.openai.TestUtils#getTestParameters") + public void testGetChatCompletionsTextPromptAudioResponse(HttpClient httpClient, + OpenAIServiceVersion serviceVersion) { + client = getOpenAIClient(httpClient, serviceVersion); + getChatCompletionsWithTextPromptAudioResponse((deploymentId, options) -> { + ChatCompletions chatCompletions = client.getChatCompletions(deploymentId, options); + ChatChoice choice = chatCompletions.getChoices().get(0); + ChatResponseMessage message = choice.getMessage(); + + // Assert that the message has content + assertEquals(ChatRole.ASSISTANT, message.getRole()); + AudioResponseData audioResponse = message.getAudio(); + assertNotNull(audioResponse); + assertFalse(CoreUtils.isNullOrEmpty(audioResponse.getId())); + assertFalse(CoreUtils.isNullOrEmpty(audioResponse.getData())); + assertFalse(CoreUtils.isNullOrEmpty(audioResponse.getTranscript())); + assertNotNull(audioResponse.getExpiresAt()); + + // Assert finish reason + assertEquals(CompletionsFinishReason.STOPPED, choice.getFinishReason()); + CompletionsUsage usage = chatCompletions.getUsage(); + + // assert that we only used audio tokens for the response + assertNotNull(usage); + assertNotNull(usage.getPromptTokensDetails()); + assertNotNull(usage.getCompletionTokensDetails()); + + assertEquals(0, usage.getPromptTokensDetails().getAudioTokens()); + assertTrue(usage.getCompletionTokensDetails().getAudioTokens() > 0); + }); + } + + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.openai.TestUtils#getTestParameters") + public void testGetChatCompletionsAudioPromptAudioResponse(HttpClient httpClient, + OpenAIServiceVersion serviceVersion) { + client = getOpenAIClient(httpClient, serviceVersion); + getChatCompletionsWithAudioPromptAudioResponse((deploymentId, options) -> { + ChatCompletions chatCompletions = client.getChatCompletions(deploymentId, options); + ChatChoice choice = chatCompletions.getChoices().get(0); + ChatResponseMessage message = choice.getMessage(); + + // Assert that the message has content + assertEquals(ChatRole.ASSISTANT, message.getRole()); + AudioResponseData audioResponse = message.getAudio(); + assertNotNull(audioResponse); + assertFalse(CoreUtils.isNullOrEmpty(audioResponse.getId())); + assertFalse(CoreUtils.isNullOrEmpty(audioResponse.getData())); + assertFalse(CoreUtils.isNullOrEmpty(audioResponse.getTranscript())); + assertNotNull(audioResponse.getExpiresAt()); + + // Assert finish reason + assertEquals(CompletionsFinishReason.STOPPED, choice.getFinishReason()); + CompletionsUsage usage = chatCompletions.getUsage(); + + // assert that we only used audio tokens for the response + assertNotNull(usage); + assertNotNull(usage.getPromptTokensDetails()); + assertNotNull(usage.getCompletionTokensDetails()); + + assertTrue(usage.getPromptTokensDetails().getAudioTokens() > 0); + assertTrue(usage.getCompletionTokensDetails().getAudioTokens() > 0); + }); + } + + @Disabled("There is no instance supporting this feature yet") + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.openai.TestUtils#getTestParameters") + public void testGetChatCompletionsReasoningEffortLow(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { + client = getOpenAIClient(httpClient, serviceVersion); + getChatCompletionsWithReasoningEffortForAzure((deploymentId, options) -> { + ChatCompletions chatCompletions = client.getChatCompletions(deploymentId, options); + ChatChoice choice = chatCompletions.getChoices().get(0); + ChatResponseMessage message = choice.getMessage(); + + // Assert that the message has content + assertEquals(ChatRole.ASSISTANT, message.getRole()); + assertFalse(CoreUtils.isNullOrEmpty(message.getContent())); + + // Assert finish reason + assertEquals(CompletionsFinishReason.STOPPED, choice.getFinishReason()); + CompletionsUsage usage = chatCompletions.getUsage(); + + // assert that we only used audio tokens for the response + assertNotNull(usage); + assertNotNull(usage.getPromptTokensDetails()); + assertNotNull(usage.getCompletionTokensDetails()); + + assertTrue(usage.getCompletionTokensDetails().getReasoningTokens() > 0); + }); + } + + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.openai.TestUtils#getTestParameters") + public void testGetChatCompletionsPrediction(HttpClient httpClient, OpenAIServiceVersion serviceVersion) { + client = getOpenAIClient(httpClient, serviceVersion); + getChatCompletionsWithPredictionForAzure((deploymentId, options) -> { + ChatCompletions chatCompletions = client.getChatCompletions(deploymentId, options); + ChatChoice choice = chatCompletions.getChoices().get(0); + ChatResponseMessage message = choice.getMessage(); + + // Assert that the message has content + assertEquals(ChatRole.ASSISTANT, message.getRole()); + assertFalse(CoreUtils.isNullOrEmpty(message.getContent())); + + // Assert finish reason + assertEquals(CompletionsFinishReason.STOPPED, choice.getFinishReason()); + CompletionsUsage usage = chatCompletions.getUsage(); + + // assert that we only used audio tokens for the response + assertNotNull(usage); + assertNotNull(usage.getPromptTokensDetails()); + assertNotNull(usage.getCompletionTokensDetails()); + + assertTrue(usage.getCompletionTokensDetails().getAcceptedPredictionTokens() > 0); + assertTrue(usage.getCompletionTokensDetails().getRejectedPredictionTokens() > 0); + + }); + } + @Disabled("Unrecognized request argument supplied: max_completion_tokens") @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.openai.TestUtils#getTestParameters") @@ -502,24 +636,24 @@ public void testCompletionStreamContentFiltering(HttpClient httpClient, OpenAISe int totalCompletions = resultCompletions.stream().toArray().length; for (Iterator it = resultCompletions.iterator(); it.hasNext();) { Completions completions = it.next(); - assertCompletionsStream(completions); if (i == 0) { // The first stream message has the prompt filter result assertEquals(1, completions.getPromptFilterResults().size()); assertSafePromptContentFilterResults(completions.getPromptFilterResults().get(0)); } else if (i == totalCompletions - 1) { - // The last stream message is empty with all the filters set to null - assertEquals(1, completions.getChoices().size()); - Choice choice = completions.getChoices().get(0); - assertEquals(CompletionsFinishReason.fromString("stop"), choice.getFinishReason()); - assertNotNull(choice.getText()); - // TODO (team): change in behaviour, this used to be uncommented - // assertSafeChoiceContentFilterResults(choice.getContentFilterResults()); + // The last contains only the token usage + assertEquals(0, completions.getChoices().size()); + assertEquals( + completions.getUsage().getCompletionTokens() + completions.getUsage().getPromptTokens(), + completions.getUsage().getTotalTokens()); } else { // The rest of the intermediary messages have the text generation content filter set assertNull(completions.getPromptFilterResults()); - assertNotNull(completions.getChoices().get(0)); - assertSafeChoiceContentFilterResults(completions.getChoices().get(0).getContentFilterResults()); + Choice choice = completions.getChoices().get(0); + assertNotNull(choice); + if (choice.getFinishReason() == null) { + assertSafeChoiceContentFilterResults(choice.getContentFilterResults()); + } } i++; } diff --git a/sdk/openai/azure-ai-openai/src/test/resources/realtime_whats_the_weather_pcm16_24khz_mono.wav b/sdk/openai/azure-ai-openai/src/test/resources/realtime_whats_the_weather_pcm16_24khz_mono.wav new file mode 100644 index 000000000000..399cd5ad3bae Binary files /dev/null and b/sdk/openai/azure-ai-openai/src/test/resources/realtime_whats_the_weather_pcm16_24khz_mono.wav differ diff --git a/sdk/openai/azure-ai-openai/tsp-location.yaml b/sdk/openai/azure-ai-openai/tsp-location.yaml index 32823dcf5e56..16619ff97757 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: 85d5b0a9ca473629426bb7898abffe9274d5f147 +commit: a378d871adcadc6c29994a2b99e008b5f0f9f5cf repo: Azure/azure-rest-api-specs diff --git a/sdk/operationsmanagement/azure-resourcemanager-operationsmanagement/README.md b/sdk/operationsmanagement/azure-resourcemanager-operationsmanagement/README.md index f8a4a6544c0a..b72798946045 100644 --- a/sdk/operationsmanagement/azure-resourcemanager-operationsmanagement/README.md +++ b/sdk/operationsmanagement/azure-resourcemanager-operationsmanagement/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-operationsmanagement - 1.0.0-beta.3 + 1.0.0-beta.4 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Foperationsmanagement%2Fazure-resourcemanager-operationsmanagement%2FREADME.png) + diff --git a/sdk/operationsmanagement/azure-resourcemanager-operationsmanagement/pom.xml b/sdk/operationsmanagement/azure-resourcemanager-operationsmanagement/pom.xml index 2c73a59c4dcc..3cece237b32e 100644 --- a/sdk/operationsmanagement/azure-resourcemanager-operationsmanagement/pom.xml +++ b/sdk/operationsmanagement/azure-resourcemanager-operationsmanagement/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/oracledatabase/azure-resourcemanager-oracledatabase/README.md b/sdk/oracledatabase/azure-resourcemanager-oracledatabase/README.md index bf32bc4cc4d4..6f63d61f0465 100644 --- a/sdk/oracledatabase/azure-resourcemanager-oracledatabase/README.md +++ b/sdk/oracledatabase/azure-resourcemanager-oracledatabase/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-oracledatabase - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Foracledatabase%2Fazure-resourcemanager-oracledatabase%2FREADME.png) + diff --git a/sdk/oracledatabase/azure-resourcemanager-oracledatabase/pom.xml b/sdk/oracledatabase/azure-resourcemanager-oracledatabase/pom.xml index 44f20b8d62e1..470e2a9a42a9 100644 --- a/sdk/oracledatabase/azure-resourcemanager-oracledatabase/pom.xml +++ b/sdk/oracledatabase/azure-resourcemanager-oracledatabase/pom.xml @@ -50,28 +50,28 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/orbital/azure-resourcemanager-orbital/README.md b/sdk/orbital/azure-resourcemanager-orbital/README.md index 69130419918a..838ae8c4a127 100644 --- a/sdk/orbital/azure-resourcemanager-orbital/README.md +++ b/sdk/orbital/azure-resourcemanager-orbital/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-orbital - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Forbital%2Fazure-resourcemanager-orbital%2FREADME.png) + diff --git a/sdk/orbital/azure-resourcemanager-orbital/pom.xml b/sdk/orbital/azure-resourcemanager-orbital/pom.xml index bb300a0371ab..83339dba89e9 100644 --- a/sdk/orbital/azure-resourcemanager-orbital/pom.xml +++ b/sdk/orbital/azure-resourcemanager-orbital/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/paloaltonetworks/azure-resourcemanager-paloaltonetworks-ngfw/README.md b/sdk/paloaltonetworks/azure-resourcemanager-paloaltonetworks-ngfw/README.md index 0d739675f634..34c2656949d7 100644 --- a/sdk/paloaltonetworks/azure-resourcemanager-paloaltonetworks-ngfw/README.md +++ b/sdk/paloaltonetworks/azure-resourcemanager-paloaltonetworks-ngfw/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-paloaltonetworks-ngfw - 1.2.0 + 1.3.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -110,4 +110,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fpaloaltonetworks%2Fazure-resourcemanager-paloaltonetworks-ngfw%2FREADME.png) + diff --git a/sdk/paloaltonetworks/azure-resourcemanager-paloaltonetworks-ngfw/pom.xml b/sdk/paloaltonetworks/azure-resourcemanager-paloaltonetworks-ngfw/pom.xml index cd5f79787153..02a4483a365d 100644 --- a/sdk/paloaltonetworks/azure-resourcemanager-paloaltonetworks-ngfw/pom.xml +++ b/sdk/paloaltonetworks/azure-resourcemanager-paloaltonetworks-ngfw/pom.xml @@ -51,29 +51,29 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/parents/azure-client-sdk-parent-v2/CHANGELOG.md b/sdk/parents/azure-client-sdk-parent-v2/CHANGELOG.md new file mode 100644 index 000000000000..2a2738d96381 --- /dev/null +++ b/sdk/parents/azure-client-sdk-parent-v2/CHANGELOG.md @@ -0,0 +1,5 @@ +# Release History + +## 1.0.0-beta.1 (Unreleased) + + diff --git a/sdk/parents/azure-client-sdk-parent-v2/README.md b/sdk/parents/azure-client-sdk-parent-v2/README.md new file mode 100644 index 000000000000..888574899bf2 --- /dev/null +++ b/sdk/parents/azure-client-sdk-parent-v2/README.md @@ -0,0 +1 @@ +# Microsoft Azure SDK for Java - Client Libraries V2 diff --git a/sdk/parents/azure-client-sdk-parent-v2/pom.xml b/sdk/parents/azure-client-sdk-parent-v2/pom.xml new file mode 100644 index 000000000000..16435b6b7d40 --- /dev/null +++ b/sdk/parents/azure-client-sdk-parent-v2/pom.xml @@ -0,0 +1,1605 @@ + + + 4.0.0 + com.azure.v2 + azure-client-sdk-parent + pom + 2.0.0-beta.1 + + Microsoft Azure SDK for Java V2 - Client Libraries + Parent POM for Microsoft Azure SDK for Java V2 + https://github.com/Azure/azure-sdk-for-java + + Microsoft Corporation + http://microsoft.com + + + + com.azure + azure-sdk-parent + 1.6.0 + ../azure-sdk-parent/pom.xml + + + + + The MIT License (MIT) + http://opensource.org/licenses/MIT + repo + + + + + + microsoft + Microsoft Corporation + + + + + + + ossrh + Sonatype Snapshots + https://oss.sonatype.org/content/repositories/snapshots/ + default + + true + daily + + + + + + + ossrh + Sonatype Snapshots + https://oss.sonatype.org/content/repositories/snapshots/ + default + + true + always + + + + + + + ossrh + Sonatype Snapshots + https://oss.sonatype.org/content/repositories/snapshots/ + true + default + + + azure-java-build-docs + ${site.url}/site/ + + + + + GitHub + ${issues.url} + + + + https://github.com/Azure/azure-sdk-for-java + scm:git:https://github.com/Azure/azure-sdk-for-java.git + + HEAD + + + + UTF-8 + ${project.build.directory} + ${project.build.testSourceDirectory} + + playback + + https://azuresdkartifacts.blob.core.windows.net/azure-sdk-for-java + https://github.com/Azure/azure-sdk-for-java/issues + azure-client-sdk-parent-v2 + 0.40 + 0.30 + false + false + + + ../../.. + + + 4096m + + + -Xmx${surefireXmx} + + + + -XX:+HeapDumpOnOutOfMemoryError + -XX:HeapDumpPath=${packageOutputDirectory}${file.separator}${project.artifactId}-oom.hprof + + -XX:+CrashOnOutOfMemoryError + + + + + + + @{jacocoUnitTestAgent} + ${surefireJvmXmx} + ${heapDumpOnOom} + + + + + + + + + + + + + + + @{jacocoIntegrationTestAgent} + ${surefireJvmXmx} + ${heapDumpOnOom} + + + + + + ${javaModulesSurefireArgLine} + + + + + + ${additionalSurefireArgLine} + + + + + concurrent + + + + same_thread + + + false + + + + false + + + true + true + + + + + + true + + + ${project.basedir}/${relative.path.to.eng.folder}/eng/code-quality-reports/src/main/resources/checkstyle/checkstyle-suppressions.xml + + + + true + + + false + + + true + + + spotbugs/spotbugs-exclude.xml + + true + + + + true + + + + + + false + false + + + - + + + + + com.azure.core.v2.* + + + + + + false + + + + false + + + false + + + false + + + true + + + false + false + + + + + + org.jacoco + org.jacoco.agent + runtime + 0.8.12 + test + + + org.slf4j + slf4j-simple + 1.7.36 + test + + + + + + + src/main/resources + true + + **.properties + + + + src/main/resources + false + + **.properties + + + + + + + + org.codehaus.mojo + animal-sniffer-maven-plugin + 1.24 + + + package + + check + + + ${animal.sniffer.skip} + + com.toasttab.android + gummy-bears-api-26 + 0.10.0 + + false + ${animal.sniffer.ignores} + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.13.0 + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + 3.6.0 + + + verify + + check + + + + + + + + com.github.spotbugs + spotbugs-maven-plugin + 4.8.3.1 + + + verify + + check + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.4.2 + + ${packageOutputDirectory} + + + true + + + + + + + + com.azure.tools + codesnippet-maven-plugin + 1.0.0-beta.10 + + ${codesnippet.skip} + **/*.md + + + + update-codesnippets + + update-codesnippet + + + + verify-codesnippets + + verify-codesnippet + + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.10.1 + + + attach-javadocs + + jar + + + + + + + + org.apache.maven.plugins + maven-source-plugin + 3.3.1 + + + attach-sources + + jar + + + ${packageOutputDirectory} + + + + + + + + org.apache.maven.plugins + maven-antrun-plugin + 3.1.0 + + + copy + package + + + + + + + run + + + + + + + org.jacoco + jacoco-maven-plugin + 0.8.12 + + + ${project.build.directory}/jacoco.exec + + + META-INF/** + + + + + prepare-agent + process-test-classes + + prepare-agent + + + ${project.build.directory}/jacoco-unit.exec + jacocoUnitTestAgent + + + + integration-prepare-agent + pre-integration-test + + prepare-agent + + + ${project.build.directory}/jacoco-it.exec + jacocoIntegrationTestAgent + + + + merge-unit-and-integration + verify + + merge + + + + + ${project.build.directory} + + jacoco-unit.exec + jacoco-it.exec + + + + + + + post-unit-test + verify + + report + + + ${project.reporting.outputDirectory}/test-coverage + + **/com/azure/cosmos/implementation/apachecommons/**/* + **/com/azure/cosmos/implementation/guava25/**/* + **/com/azure/cosmos/implementation/guava27/**/* + **/com/azure/cosmos/encryption/implementation/mdesrc/**/* + + + + + check + verify + + check + + + ${jacoco.skip} + ${project.build.directory}/jacoco.exec + + + BUNDLE + + + LINE + COVEREDRATIO + ${jacoco.min.linecoverage} + + + BRANCH + COVEREDRATIO + ${jacoco.min.branchcoverage} + + + + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.6.0 + + + attach-artifacts + package + + attach-artifact + + + + + ${basedir}/README.md + md + readme + + + ${basedir}/CHANGELOG.md + md + changelog + + + + + + + + + + org.revapi + revapi-maven-plugin + 0.14.6 + + + + check + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.5.0 + + + + + false + + + *:*:*:*:runtime + *:*:*:*:compile + *:*:*:*:provided + + + com.azure.v2:* + io.clientcore:* + + + com.google.code.findbugs:jsr305:[3.0.2] + + + + + + No Snapshots Allowed! + + + + + true + + + + default-cli + + enforce + + + + + + + com.diffplug.spotless + spotless-maven-plugin + 2.30.0 + + ${spotless.apply.skip} + ${spotless.check.skip} + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.13.0 + + true + true + ${skipCompile} + ${skipTestCompile} + + + -Xlint:cast + -Xlint:classfile + -Xlint:${compiler.failondeprecatedstatus}deprecation + -Xlint:dep-ann + -Xlint:divzero + -Xlint:empty + -Xlint:fallthrough + -Xlint:finally + -Xlint:options + -Xlint:overrides + -Xlint:path + + -Xlint:rawtypes + + -Xlint:static + -Xlint:try + -Xlint:unchecked + -Xlint:varargs + + + + ${compiler.proc} + + false + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + 3.6.0 + + + com.azure + sdk-build-tools + 1.0.0 + + + com.puppycrawl.tools + checkstyle + 9.3 + + + + ${checkstyle.skip} + ${project.basedir}/${relative.path.to.eng.folder}/eng/code-quality-reports/src/main/resources/checkstyle/checkstyle.xml + ${checkstyle.suppressionsLocation} + ${project.basedir}/${relative.path.to.eng.folder}/eng/code-quality-reports/src/main/resources/checkstyle/java.header + ${checkstyle.excludes} + samedir= + UTF-8 + true + ${checkstyle.includeTestSourceDirectory} + true + ${checkstyle.failsOnError} + ${checkstyle.failOnViolation} + + + + + + com.github.spotbugs + spotbugs-maven-plugin + 4.8.3.1 + + + com.azure + sdk-build-tools + 1.0.0 + + + com.github.spotbugs + spotbugs + 4.8.3 + + + + org.ow2.asm + asm + 9.7.1 + + + + ${spotbugs.skip} + max + low + true + ${project.build.directory}/spotbugs + ${spotbugs.excludeFilterFile} + spotbugs/spotbugs-include.xml + true + ${spotbugs.failOnError} + + ${spotbugs.includeTests} + + + + + + + + + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.10.1 + + ${maven.javadoc.skip} + 1.8 + Azure SDK for Java Reference Documentation + Azure SDK for Java Reference Documentation + Visit the <a href="https://docs.microsoft.com/java/azure/">Azure for Java Developers</a> site + for more Java documentation, including quick starts, tutorials, and code samples. + + false + + *.impl*: + *.implementation: + *.implementation*: + *.samples: + com.azure.tools.checkstyle*: + ${javadoc.excludePackageNames} + + + + module-info.java + + + ${javadoc.sourcepath} + + + + https://docs.oracle.com/javase/8/docs/api/ + + false + true + + + + https://docs.oracle.com/javase/8/docs/api/ + ${project.basedir}/${relative.path.to.eng.folder}/eng/javadoc-package-lists/java8/ + + + true + true + all + true + ${packageOutputDirectory} + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.5.2 + + ${maven.test.skip} + alphabetical + false + + true + + + + + true + + + ${parallelizeTests} + ${project.build.directory}/${project.artifactId}-test.log + true + dd MMM yyyy HH:mm:ss,SSS + info + debug + + 1 + false + + ${defaultSurefireArgLine} + ${additionalSurefireArgLine} + + + + + + + org.ow2.asm + asm + 9.7.1 + + + + org.jacoco + org.jacoco.agent + runtime + 0.8.12 + + + + + + + org.apache.maven.plugins + maven-failsafe-plugin + 3.5.2 + + ${maven.test.skip} + alphabetical + false + + true + + + + + true + + + ${parallelizeTests} + ${project.build.directory}/${project.artifactId}-test.log + true + dd MMM yyyy HH:mm:ss,SSS + info + debug + + 1 + false + + ${defaultFailsafeArgLine} + ${additionalFailsafeArgLine} + + + + + + + org.ow2.asm + asm + 9.7.1 + + + + org.jacoco + org.jacoco.agent + runtime + 0.8.12 + + + + + + + org.revapi + revapi-maven-plugin + 0.14.6 + + ${revapi.skip} + true + + + revapi/revapi.json + + + ^\d+\.\d+\.\d+$ + false + ${revapi.failBuildOnProblemsFound} + + + + NON_BREAKING + error + true + ${project.build.directory}/revapi.json + false + + + + + + class-and-package-tree-filter-provider + + + + + + + com.azure + sdk-build-tools + 1.0.0 + + + org.revapi + revapi-java + 0.26.1 + + + org.revapi + revapi-reporter-json + 0.5.0 + + + com.fasterxml.jackson.core + jackson-databind + 2.17.2 + + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.6.0 + + ${shade.skip} + + + + + + com.diffplug.spotless + spotless-maven-plugin + 2.30.0 + + ${spotless.skip} + + + 4.21.0 + ${project.basedir}/${relative.path.to.eng.folder}/.vscode/eclipse-format-azure-sdk-for-java.xml + + + + + + spotless-apply + + apply + + process-sources + + + spotless-check + + check + + verify + + + + + + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + 3.6.0 + + + non-aggregate + + checkstyle + + + + + + com.github.spotbugs + spotbugs-maven-plugin + 4.8.3.1 + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.10.1 + + + non-aggregate + + javadoc + + + + + + org.apache.maven.plugins + maven-project-info-reports-plugin + 3.8.0 + + + + index + summary + dependency-info + dependency-management + dependency-convergence + ci-management + dependencies + issue-management + + + + + + org.revapi + revapi-maven-plugin + 0.14.6 + + false + + + + + report + + + + + + + + + + + + java8 + + [1.8,9) + + + 8 + 8 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.13.0 + + 1.8 + 1.8 + + module-info.java + + + module-info.java + + + 1.8 + 1.8 + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.10.1 + + + module-info.java + + + + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.10.1 + + + module-info.java + + + + + + + + + + java9plus + + [9,) + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.13.0 + + + -Xlint:-module + -Xlint:removal + -Xlint:-requires-transitive-automatic + + + + + + + default-compile + + compile + + + ${java.vm.specification.version} + + + + + + + + base-modules-compile + + compile + + + 11 + + module-info.java + + + + + + + base-compile + + compile + + + + -Xlint:-options + + 8 + + module-info.java + + + + + + + default-testCompile + + testCompile + + + ${java.vm.specification.version} + ${java.vm.specification.version} + false + + + + + + base-testCompile + + testCompile + + + + -Xlint:-options + + 8 + 8 + + module-info.java + + false + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.5.2 + + + ${defaultSurefireArgLine} + ${javaModulesSurefireArgLine} + ${additionalSurefireArgLine} + + + + + + org.apache.maven.plugins + maven-failsafe-plugin + 3.5.2 + + + ${defaultFailsafeArgLine} + ${javaModulesFailsafeArgLine} + ${additionalFailsafeArgLine} + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.6.0 + + + add-generated-sources + generate-sources + + add-source + + + + ${project.build.directory}/generated-sources/ + + + + + + + + + + + + generate-overview-from-readme + + + generate-overview + + + ${basedir}/${relative.path.to.eng.folder}/eng/pipelines/scripts/generate_overview_from_readme.py + + + + + + org.codehaus.mojo + exec-maven-plugin + 3.5.0 + + + generate-overview-from-readme + prepare-package + + exec + + + python + ${project.basedir} + + ${project.basedir}/${relative.path.to.eng.folder}/eng/pipelines/scripts/generate_overview_from_readme.py + --rf + ${project.basedir}/README.md + --ofp + ${project.build.directory}${file.separator} + --v + ${project.version} + + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.10.1 + + ${project.build.directory}/readme_overview.html + + + + + + + + + verify-changelog + + + verify-changelog + + + + + + org.codehaus.mojo + exec-maven-plugin + 3.5.0 + + + verify-readme-codesnippet + prepare-package + + exec + + + pwsh + + ${project.basedir}/${relative.path.to.eng.folder}/eng/common/scripts/Verify-Changelog.ps1 + -ChangeLogLocation + ${project.basedir}/CHANGELOG.md + -VersionString + ${project.version} + + + + + + + + + + + sequential-test-azure-test-mode-live-env + + + env.AZURE_TEST_MODE + LIVE + + + + ${parallelizeLiveTests} + + + + + sequential-test-azure-test-mode-record-env + + + env.AZURE_TEST_MODE + RECORD + + + + ${parallelizeLiveTests} + + + + + sequential-test-azure-test-mode-live-prop + + + AZURE_TEST_MODE + LIVE + + + + ${parallelizeLiveTests} + + + + + sequential-test-azure-test-mode-record-prop + + + AZURE_TEST_MODE + RECORD + + + + ${parallelizeLiveTests} + + + + + transform-spotbugs + + + ${packageOutputDirectory}/spotbugs/spotbugsXml.xml + + + + + + + org.codehaus.mojo + xml-maven-plugin + 1.1.0 + + + verify + + transform + + + + + + + ${packageOutputDirectory}/spotbugs + + spotbugsXml.xml + + ${packageOutputDirectory}/spotbugs + fancy-hist.xsl + + + .html + + + + + + + + com.github.spotbugs + spotbugs + 4.8.3 + + + + + + + + + native + + + + org.graalvm.buildtools + junit-platform-native + 0.9.19 + test + + + + + + org.graalvm.buildtools + native-maven-plugin + 0.10.5 + + ${graalvm.disable} + --no-fallback ${nativeImage.buildArgs} -H:IncludeResources=.* + + true + + + test-native + + test + + test + + + + + + + + + + + + external-dependency-version-overrides + + + env.VERSION_OVERRIDE_TESTS + + + + + repository.spring.milestone + Spring Milestone Repository + https://repo.spring.io/milestone + + true + + + true + + + + + + + test-module-base-compile + + + ${projectTestSourceDirectory}/module-info.java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.13.0 + + + + + + base-modules-testCompile + + testCompile + + + 11 + 11 + + module-info.java + + + + + + + + + + diff --git a/sdk/parents/azure-client-sdk-parent/pom.xml b/sdk/parents/azure-client-sdk-parent/pom.xml index 9455cff5feec..00187ee716b9 100644 --- a/sdk/parents/azure-client-sdk-parent/pom.xml +++ b/sdk/parents/azure-client-sdk-parent/pom.xml @@ -338,7 +338,7 @@ org.apache.maven.plugins maven-checkstyle-plugin - 3.5.0 + 3.6.0 verify @@ -715,7 +715,7 @@ org.apache.maven.plugins maven-checkstyle-plugin - 3.5.0 + 3.6.0 com.azure @@ -764,7 +764,7 @@ org.ow2.asm asm - 9.7 + 9.7.1 @@ -909,7 +909,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 ${maven.test.skip} alphabetical @@ -943,7 +943,7 @@ org.ow2.asm asm - 9.7 + 9.7.1 @@ -959,7 +959,7 @@ org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 ${maven.test.skip} alphabetical @@ -993,7 +993,7 @@ org.ow2.asm asm - 9.7 + 9.7.1 @@ -1053,7 +1053,7 @@ org.revapi revapi-reporter-json - 0.4.5 + 0.5.0 com.fasterxml.jackson.core @@ -1112,7 +1112,7 @@ org.apache.maven.plugins maven-checkstyle-plugin - 3.5.0 + 3.6.0 non-aggregate @@ -1143,7 +1143,7 @@ org.apache.maven.plugins maven-project-info-reports-plugin - 3.7.0 + 3.8.0 @@ -1343,7 +1343,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 ${defaultSurefireArgLine} @@ -1359,7 +1359,7 @@ org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 ${defaultFailsafeArgLine} @@ -1394,7 +1394,7 @@ org.codehaus.mojo exec-maven-plugin - 3.4.1 + 3.5.0 generate-overview-from-readme @@ -1444,7 +1444,7 @@ org.codehaus.mojo exec-maven-plugin - 3.4.1 + 3.5.0 verify-readme-codesnippet @@ -1481,7 +1481,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 ${AZURE_TEST_SYSTEM_PLAYBACK_PROPERTIES_FILE} @@ -1503,7 +1503,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 ${AZURE_TEST_SYSTEM_PLAYBACK_PROPERTIES_FILE} @@ -1524,7 +1524,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 ${AZURE_TEST_SYSTEM_PLAYBACK_PROPERTIES_FILE} @@ -1546,7 +1546,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 ${AZURE_TEST_SYSTEM_PLAYBACK_PROPERTIES_FILE} @@ -1674,7 +1674,7 @@ org.graalvm.buildtools native-maven-plugin - 0.9.19 + 0.10.5 ${graalvm.disable} --no-fallback ${nativeImage.buildArgs} -H:IncludeResources=.* diff --git a/sdk/parents/azure-data-sdk-parent/pom.xml b/sdk/parents/azure-data-sdk-parent/pom.xml index fa2efa1a9681..2e2c7778313b 100644 --- a/sdk/parents/azure-data-sdk-parent/pom.xml +++ b/sdk/parents/azure-data-sdk-parent/pom.xml @@ -70,7 +70,7 @@ org.apache.maven.plugins maven-checkstyle-plugin - 3.5.0 + 3.6.0 com.azure @@ -127,7 +127,7 @@ org.ow2.asm asm - 9.7 + 9.7.1 @@ -294,7 +294,7 @@ org.ow2.asm asm - 9.7 + 9.7.1 @@ -311,7 +311,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 ${testMode} @@ -343,7 +343,7 @@ org.apache.maven.plugins maven-checkstyle-plugin - 3.5.0 + 3.6.0 checkstyle/checkstyle.xml checkstyle/checkstyle-suppressions.xml @@ -417,7 +417,7 @@ org.apache.maven.plugins maven-project-info-reports-plugin - 3.7.0 + 3.8.0 @@ -515,7 +515,7 @@ org.codehaus.mojo exec-maven-plugin - 3.4.1 + 3.5.0 generate-overview-from-readme diff --git a/sdk/parents/azure-sdk-parent/pom.xml b/sdk/parents/azure-sdk-parent/pom.xml index c76d92292a1f..9b2b51c11dca 100644 --- a/sdk/parents/azure-sdk-parent/pom.xml +++ b/sdk/parents/azure-sdk-parent/pom.xml @@ -145,7 +145,7 @@ org.codehaus.mojo exec-maven-plugin - 3.4.1 + 3.5.0 @@ -170,7 +170,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 ${surefireArgLine} @@ -242,7 +242,7 @@ org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 @@ -274,7 +274,7 @@ org.apache.maven.plugins maven-project-info-reports-plugin - 3.7.0 + 3.8.0 @@ -283,6 +283,22 @@ maven-install-plugin 3.1.3 + + + org.owasp + dependency-check-maven + 11.1.1 + + true + + + + + check + + + + diff --git a/sdk/parents/ci.yml b/sdk/parents/ci.yml index 156ee6bb4a22..1b66f783dcb1 100644 --- a/sdk/parents/ci.yml +++ b/sdk/parents/ci.yml @@ -1,43 +1,57 @@ # NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. -trigger: - branches: - include: - - main - - hotfix/* - - release/* - paths: - include: - - sdk/parents/ +# This is pretty much a release only pipeline as there are no libraries being built +# or tests being run and because of this, it shouldn't have triggers. Other +# sdk/ have triggers if particular parents change. +trigger: none -pr: - branches: - include: - - main - - feature/* - - hotfix/* - - release/* - paths: - include: - - sdk/parents/ +pr: none + +# Note: azure-code-customization-parent and azure-perf-test-parent are not shipping parents +parameters: + - name: release_azuresdkparent + displayName: 'azure-sdk-parent' + type: boolean + default: false + - name: release_azureclientsdkparent + displayName: 'azure-client-sdk-parent' + type: boolean + default: false + - name: release_azureclientsdkparentv2 + displayName: 'azure-client-sdk-parent-v2' + type: boolean + default: false + - name: release_clientcoreioparent + displayName: 'clientcore-parent' + type: boolean + default: false + - name: release_azuredatasdkparent + displayName: 'azure-data-sdk-parent' + type: boolean + default: false extends: template: /eng/pipelines/templates/stages/archetype-sdk-pom-only.yml parameters: ServiceDirectory: parents Artifacts: - - name: azure-client-sdk-parent - groupId: com.azure - safeName: azureclientsdkparent - - name: azure-data-sdk-parent - groupId: com.azure - safeName: azuredatasdkparent - name: azure-sdk-parent groupId: com.azure safeName: azuresdkparent - - name: azure-perf-test-parent + releaseInBatch: ${{ parameters.release_azuresdkparent }} + - name: azure-client-sdk-parent + groupId: com.azure + safeName: azureclientsdkparent + releaseInBatch: ${{ parameters.release_azureclientsdkparent }} + - name: azure-client-sdk-parent-v2 groupId: com.azure - safeName: azureperftestparent + safeName: azureclientsdkparentv2 + releaseInBatch: ${{ parameters.release_azureclientsdkparentv2 }} - name: clientcore-parent groupId: io.clientcore safeName: clientcoreioparent + releaseInBatch: ${{ parameters.release_clientcoreioparent }} + - name: azure-data-sdk-parent + groupId: com.azure + safeName: azuredatasdkparent + releaseInBatch: ${{ parameters.release_azuredatasdkparent }} diff --git a/sdk/parents/clientcore-parent/pom.xml b/sdk/parents/clientcore-parent/pom.xml index 4617a1c40aa9..0ef486028307 100644 --- a/sdk/parents/clientcore-parent/pom.xml +++ b/sdk/parents/clientcore-parent/pom.xml @@ -7,7 +7,7 @@ io.clientcore clientcore-parent pom - 1.0.0-beta.1 + 1.0.0-beta.3 SDK for Java - Client Libraries Parent POM for SDK for Java @@ -205,8 +205,6 @@ false false - none - + 3.5.0 @@ -339,7 +337,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 **/Test*.java @@ -389,7 +387,7 @@ org.apache.maven.plugins maven-checkstyle-plugin - 3.5.0 + 3.6.0 verify @@ -698,6 +696,47 @@ + + org.codehaus.mojo + build-helper-maven-plugin + 3.6.0 + + + + compile-samples-source + generate-test-sources + + add-test-source + + + + src/samples/java + + + + + + + add-properties-to-test + generate-test-resources + + add-test-resource + + + + + src/main/resources + true + + *.properties + + + + + + + + org.apache.maven.plugins @@ -728,15 +767,11 @@ -Xlint:try -Xlint:unchecked -Xlint:varargs - -Xlint:-module - -Xlint:removal - -Xlint:-requires-transitive-automatic - - ${compiler.proc} - false + + none @@ -744,7 +779,7 @@ org.apache.maven.plugins maven-checkstyle-plugin - 3.5.0 + 3.6.0 com.azure @@ -793,7 +828,7 @@ org.ow2.asm asm - 9.7 + 9.7.1 @@ -826,7 +861,7 @@ maven-javadoc-plugin 3.10.1 - 17 + 1.8 ClientCore SDK for Java Reference Documentation ClientCore SDK for Java Reference Documentation Visit the <a href="https://docs.microsoft.com/java/azure/">Azure for Java Developers</a> site @@ -858,7 +893,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 alphabetical false @@ -877,7 +912,6 @@ false ${defaultSurefireArgLine} - ${javaModulesSurefireArgLine} ${additionalSurefireArgLine} @@ -887,7 +921,7 @@ org.ow2.asm asm - 9.7 + 9.7.1 @@ -903,7 +937,7 @@ org.apache.maven.plugins maven-failsafe-plugin - 3.5.1 + 3.5.2 @@ -930,7 +964,6 @@ false ${defaultFailsafeArgLine} - ${javaModulesFailsafeArgLine} ${additionalFailsafeArgLine} @@ -940,7 +973,7 @@ org.ow2.asm asm - 9.7 + 9.7.1 @@ -966,7 +999,7 @@ ^\d+\.\d+\.\d+$ - true + false ${revapi.failBuildOnProblemsFound} @@ -1000,7 +1033,7 @@ org.revapi revapi-reporter-json - 0.4.5 + 0.5.0 com.fasterxml.jackson.core @@ -1059,7 +1092,7 @@ org.apache.maven.plugins maven-checkstyle-plugin - 3.5.0 + 3.6.0 non-aggregate @@ -1090,7 +1123,7 @@ org.apache.maven.plugins maven-project-info-reports-plugin - 3.7.0 + 3.8.0 @@ -1125,42 +1158,71 @@ + - java-baseline + java8 - 17 + [1.8,9) - 17 - 17 + 8 + 8 + org.apache.maven.plugins maven-compiler-plugin 3.13.0 - - - default-testCompile - - testCompile - - - false - - - + + 1.8 + 1.8 + + module-info.java + + + module-info.java + + 1.8 + 1.8 + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.10.1 + + + module-info.java + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.10.1 + + + module-info.java + + + + + - + - java-18-plus + java9plus - [18,) + [9,) @@ -1168,6 +1230,13 @@ org.apache.maven.plugins maven-compiler-plugin 3.13.0 + + + -Xlint:-module + -Xlint:removal + -Xlint:-requires-transitive-automatic + + @@ -1177,23 +1246,40 @@ compile - - -Xlint:-options - ${java.vm.specification.version} - - + + + + + base-modules-compile + + compile + + + 11 + + module-info.java + + + + base-compile compile - 17 + + -Xlint:-options + + 8 + + module-info.java + @@ -1204,29 +1290,63 @@ testCompile - - -Xlint:-options - ${java.vm.specification.version} ${java.vm.specification.version} false - + base-testCompile testCompile - 17 - 17 + + -Xlint:-options + + 8 + 8 + + module-info.java + false + + + org.apache.maven.plugins + maven-surefire-plugin + 3.5.2 + + + ${defaultSurefireArgLine} + ${javaModulesSurefireArgLine} + + + --add-opens java.base/java.lang.invoke=io.clientcore.core + ${additionalSurefireArgLine} + + + + + org.apache.maven.plugins + maven-failsafe-plugin + 3.5.2 + + + ${defaultFailsafeArgLine} + ${javaModulesFailsafeArgLine} + + + --add-opens java.base/java.lang.invoke=io.clientcore.core + ${additionalFailsafeArgLine} + + + @@ -1249,7 +1369,7 @@ org.codehaus.mojo exec-maven-plugin - 3.4.1 + 3.5.0 generate-overview-from-readme @@ -1299,7 +1419,7 @@ org.codehaus.mojo exec-maven-plugin - 3.4.1 + 3.5.0 verify-readme-codesnippet @@ -1443,7 +1563,7 @@ org.graalvm.buildtools native-maven-plugin - 0.9.19 + 0.10.5 ${graalvm.disable} --no-fallback ${nativeImage.buildArgs} -H:IncludeResources=.* @@ -1528,5 +1648,42 @@ + + + test-module-base-compile + + + ${projectTestSourceDirectory}/module-info.java + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.13.0 + + + + + + base-modules-testCompile + + testCompile + + + 11 + 11 + + module-info.java + + + + + + + + diff --git a/sdk/parents/pom.xml b/sdk/parents/pom.xml index 88d8d4a0a747..885574b52599 100644 --- a/sdk/parents/pom.xml +++ b/sdk/parents/pom.xml @@ -17,6 +17,7 @@ azure-client-sdk-parent + azure-client-sdk-parent-v2 azure-code-customization-parent azure-data-sdk-parent azure-perf-test-parent diff --git a/sdk/peering/azure-resourcemanager-peering/README.md b/sdk/peering/azure-resourcemanager-peering/README.md index 0565bd424133..239d05a1670a 100644 --- a/sdk/peering/azure-resourcemanager-peering/README.md +++ b/sdk/peering/azure-resourcemanager-peering/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-peering - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fpeering%2Fazure-resourcemanager-peering%2FREADME.png) + diff --git a/sdk/peering/azure-resourcemanager-peering/pom.xml b/sdk/peering/azure-resourcemanager-peering/pom.xml index 949098373b7c..a33bb0981023 100644 --- a/sdk/peering/azure-resourcemanager-peering/pom.xml +++ b/sdk/peering/azure-resourcemanager-peering/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/personalizer/azure-ai-personalizer/README.md b/sdk/personalizer/azure-ai-personalizer/README.md index 6fe5f2bf299e..cfb98af13e4d 100644 --- a/sdk/personalizer/azure-ai-personalizer/README.md +++ b/sdk/personalizer/azure-ai-personalizer/README.md @@ -18,7 +18,7 @@ Include the dependency in the dependencies' section. Ignoring the version tag wi com.azure azure-ai-personalizer - 1.0.0-beta.1 + 1.0.0-beta.2 ``` @@ -27,7 +27,7 @@ This table shows the relationship between SDK versions and supported API version |SDK version|Supported API version of service |-|- -|1.0.0-beta.1 | 1.1-preview.3 +|1.0.0-beta.2 | 1.1-preview.3 ## Key concepts The [PersonalizerAdministrationClient][personalizer_admin_sync_client] and @@ -79,4 +79,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ [coc_contact]: mailto:opencode@microsoft.com -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fpersonalizer%2Fazure-ai-personalizer%2FREADME.png) + diff --git a/sdk/personalizer/azure-ai-personalizer/pom.xml b/sdk/personalizer/azure-ai-personalizer/pom.xml index eadd9cf12975..9dba4ee4e134 100644 --- a/sdk/personalizer/azure-ai-personalizer/pom.xml +++ b/sdk/personalizer/azure-ai-personalizer/pom.xml @@ -51,25 +51,25 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/CHANGELOG.md b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/CHANGELOG.md new file mode 100644 index 000000000000..1557256b403c --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/CHANGELOG.md @@ -0,0 +1,19 @@ +# Release History + +## 1.0.0-beta.2 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + +## 1.0.0-beta.1 (2025-02-06) + +- Azure Resource Manager Pinecone Vector Db client library for Java. This package contains Microsoft Azure SDK for Pinecone Vector Db Management SDK. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). + +### Features Added + +- Initial release for the azure-resourcemanager-pineconevectordb Java SDK. diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/README.md b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/README.md new file mode 100644 index 000000000000..a572648911dd --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/README.md @@ -0,0 +1,104 @@ +# Azure Resource Manager Pinecone Vector Db client library for Java + +Azure Resource Manager Pinecone Vector Db client library for Java. + +This package contains Microsoft Azure SDK for Pinecone Vector Db Management SDK. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). + +## We'd love to hear your feedback + +We're always working on improving our products and the way we communicate with our users. So we'd love to learn what's working and how we can do better. + +If you haven't already, please take a few minutes to [complete this short survey][survey] we have put together. + +Thank you in advance for your collaboration. We really appreciate your time! + +## Documentation + +Various documentation is available to help you get started + +- [API reference documentation][docs] + +## Getting started + +### Prerequisites + +- [Java Development Kit (JDK)][jdk] with version 8 or above +- [Azure Subscription][azure_subscription] + +### Adding the package to your product + +[//]: # ({x-version-update-start;com.azure.resourcemanager:azure-resourcemanager-pineconevectordb;current}) +```xml + + com.azure.resourcemanager + azure-resourcemanager-pineconevectordb + 1.0.0-beta.2 + +``` +[//]: # ({x-version-update-end}) + +### Include the recommended packages + +Azure Management Libraries require a `TokenCredential` implementation for authentication and an `HttpClient` implementation for HTTP client. + +[Azure Identity][azure_identity] and [Azure Core Netty HTTP][azure_core_http_netty] packages provide the default implementation. + +### Authentication + +Microsoft Entra ID token authentication relies on the [credential class][azure_identity_credentials] from [Azure Identity][azure_identity] package. + +Azure subscription ID can be configured via `AZURE_SUBSCRIPTION_ID` environment variable. + +Assuming the use of the `DefaultAzureCredential` credential class, the client can be authenticated using the following code: + +```java +AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); +TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); +PineconeVectorDbManager manager = PineconeVectorDbManager + .authenticate(credential, profile); +``` + +The sample code assumes global Azure. Please change `AzureEnvironment.AZURE` variable if otherwise. + +See [Authentication][authenticate] for more options. + +## Key concepts + +See [API design][design] for general introduction on design and key concepts on Azure Management Libraries. + +## Examples + +[Code snippets and samples](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/SAMPLE.md) + + +## Troubleshooting + +## Next steps + +## Contributing + +For details on contributing to this repository, see the [contributing guide][cg]. + +This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit . + +When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repositories using our CLA. + +This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For more information see the [Code of Conduct FAQ][coc_faq] or contact with any additional questions or comments. + + +[survey]: https://microsoft.qualtrics.com/jfe/form/SV_ehN0lIk2FKEBkwd?Q_CHL=DOCS +[docs]: https://azure.github.io/azure-sdk-for-java/ +[jdk]: https://learn.microsoft.com/azure/developer/java/fundamentals/ +[azure_subscription]: https://azure.microsoft.com/free/ +[azure_identity]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/identity/azure-identity +[azure_identity_credentials]: https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/identity/azure-identity#credentials +[azure_core_http_netty]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/core/azure-core-http-netty +[authenticate]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/resourcemanager/docs/AUTH.md +[design]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/resourcemanager/docs/DESIGN.md +[cg]: https://github.com/Azure/azure-sdk-for-java/blob/main/CONTRIBUTING.md +[coc]: https://opensource.microsoft.com/codeofconduct/ +[coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ + + diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/SAMPLE.md b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/SAMPLE.md new file mode 100644 index 000000000000..9d15a00b21f5 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/SAMPLE.md @@ -0,0 +1,262 @@ +# Code snippets and samples + + +## Operations + +- [List](#operations_list) + +## Organizations + +- [CreateOrUpdate](#organizations_createorupdate) +- [Delete](#organizations_delete) +- [GetByResourceGroup](#organizations_getbyresourcegroup) +- [List](#organizations_list) +- [ListByResourceGroup](#organizations_listbyresourcegroup) +- [Update](#organizations_update) +### Operations_List + +```java +/** + * Samples for Operations List. + */ +public final class OperationsListSamples { + /* + * x-ms-original-file: 2024-10-22-preview/Operations_List_MinimumSet_Gen.json + */ + /** + * Sample code: Operations_List_MinimumSet. + * + * @param manager Entry point to PineconeVectorDbManager. + */ + public static void + operationsListMinimumSet(com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager manager) { + manager.operations().list(com.azure.core.util.Context.NONE); + } + + /* + * x-ms-original-file: 2024-10-22-preview/Operations_List_MaximumSet_Gen.json + */ + /** + * Sample code: Operations_List_MaximumSet. + * + * @param manager Entry point to PineconeVectorDbManager. + */ + public static void + operationsListMaximumSet(com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager manager) { + manager.operations().list(com.azure.core.util.Context.NONE); + } +} +``` + +### Organizations_CreateOrUpdate + +```java +import com.azure.resourcemanager.pineconevectordb.models.ManagedServiceIdentity; +import com.azure.resourcemanager.pineconevectordb.models.ManagedServiceIdentityType; +import com.azure.resourcemanager.pineconevectordb.models.MarketplaceDetails; +import com.azure.resourcemanager.pineconevectordb.models.OfferDetails; +import com.azure.resourcemanager.pineconevectordb.models.OrganizationProperties; +import com.azure.resourcemanager.pineconevectordb.models.PartnerProperties; +import com.azure.resourcemanager.pineconevectordb.models.SingleSignOnPropertiesV2; +import com.azure.resourcemanager.pineconevectordb.models.SingleSignOnStates; +import com.azure.resourcemanager.pineconevectordb.models.SingleSignOnType; +import com.azure.resourcemanager.pineconevectordb.models.UserAssignedIdentity; +import com.azure.resourcemanager.pineconevectordb.models.UserDetails; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * Samples for Organizations CreateOrUpdate. + */ +public final class OrganizationsCreateOrUpdateSamples { + /* + * x-ms-original-file: 2024-10-22-preview/Organizations_CreateOrUpdate_MaximumSet_Gen.json + */ + /** + * Sample code: Organizations_CreateOrUpdate_MaximumSet. + * + * @param manager Entry point to PineconeVectorDbManager. + */ + public static void organizationsCreateOrUpdateMaximumSet( + com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager manager) { + manager.organizations() + .define("example-organization-name") + .withRegion("us-east") + .withExistingResourceGroup("rgopenapi") + .withTags(mapOf("my-tag", "tag.value")) + .withProperties(new OrganizationProperties() + .withMarketplace(new MarketplaceDetails().withSubscriptionId("76a38ef6-c8c1-4f0d-bfe0-00ec782c8077") + .withOfferDetails(new OfferDetails().withPublisherId("4d194daf-fa20-46a8-bfb4-5b7d96cae009") + .withOfferId("013124d0-bf05-4eab-a6bb-01fa83870642") + .withPlanId("62dda065-5acd-4ac5-b418-8610beed92a2") + .withPlanName("Freemium") + .withTermUnit("der") + .withTermId("a2b7ce01-f06d-4874-9f77-6ea4a4875c16"))) + .withUser(new UserDetails().withFirstName("Jimmy") + .withLastName("McExample") + .withEmailAddress("example.user@example.com") + .withUpn("example.user@example.com") + .withPhoneNumber("555-555-5555")) + .withPartnerProperties(new PartnerProperties().withDisplayName("My Example Organization")) + .withSingleSignOnProperties(new SingleSignOnPropertiesV2().withType(SingleSignOnType.SAML) + .withState(SingleSignOnStates.INITIAL) + .withEnterpriseAppId("44d3fb26-d8d5-41ff-9b9a-769737f22f13") + .withUrl("https://login.pinecone.io/?sso=true&connection=dfwgsqzkbrjqrglcsa") + .withAadDomains(Arrays.asList("exampledomain")))) + .withIdentity(new ManagedServiceIdentity().withType(ManagedServiceIdentityType.NONE) + .withUserAssignedIdentities(mapOf("ident904655400", new UserAssignedIdentity()))) + .create(); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} +``` + +### Organizations_Delete + +```java +/** + * Samples for Organizations Delete. + */ +public final class OrganizationsDeleteSamples { + /* + * x-ms-original-file: 2024-10-22-preview/Organizations_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: Organizations_Delete_MaximumSet. + * + * @param manager Entry point to PineconeVectorDbManager. + */ + public static void + organizationsDeleteMaximumSet(com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager manager) { + manager.organizations().delete("rgopenapi", "example-organization-name", com.azure.core.util.Context.NONE); + } +} +``` + +### Organizations_GetByResourceGroup + +```java +/** + * Samples for Organizations GetByResourceGroup. + */ +public final class OrganizationsGetByResourceGroupSamples { + /* + * x-ms-original-file: 2024-10-22-preview/Organizations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: Organizations_Get_MaximumSet. + * + * @param manager Entry point to PineconeVectorDbManager. + */ + public static void + organizationsGetMaximumSet(com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager manager) { + manager.organizations() + .getByResourceGroupWithResponse("rgopenapi", "example-organization-name", com.azure.core.util.Context.NONE); + } +} +``` + +### Organizations_List + +```java +/** + * Samples for Organizations List. + */ +public final class OrganizationsListSamples { + /* + * x-ms-original-file: 2024-10-22-preview/Organizations_ListBySubscription_MaximumSet_Gen.json + */ + /** + * Sample code: Organizations_ListBySubscription_MaximumSet. + * + * @param manager Entry point to PineconeVectorDbManager. + */ + public static void organizationsListBySubscriptionMaximumSet( + com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager manager) { + manager.organizations().list(com.azure.core.util.Context.NONE); + } +} +``` + +### Organizations_ListByResourceGroup + +```java +/** + * Samples for Organizations ListByResourceGroup. + */ +public final class OrganizationsListByResourceGroupSamples { + /* + * x-ms-original-file: 2024-10-22-preview/Organizations_ListByResourceGroup_MaximumSet_Gen.json + */ + /** + * Sample code: Organizations_ListByResourceGroup_MaximumSet. + * + * @param manager Entry point to PineconeVectorDbManager. + */ + public static void organizationsListByResourceGroupMaximumSet( + com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager manager) { + manager.organizations().listByResourceGroup("rgopenapi", com.azure.core.util.Context.NONE); + } +} +``` + +### Organizations_Update + +```java +import com.azure.resourcemanager.pineconevectordb.models.ManagedServiceIdentity; +import com.azure.resourcemanager.pineconevectordb.models.ManagedServiceIdentityType; +import com.azure.resourcemanager.pineconevectordb.models.OrganizationResource; +import com.azure.resourcemanager.pineconevectordb.models.UserAssignedIdentity; +import java.util.HashMap; +import java.util.Map; + +/** + * Samples for Organizations Update. + */ +public final class OrganizationsUpdateSamples { + /* + * x-ms-original-file: 2024-10-22-preview/Organizations_Update_MaximumSet_Gen.json + */ + /** + * Sample code: Organizations_Update_MaximumSet. + * + * @param manager Entry point to PineconeVectorDbManager. + */ + public static void + organizationsUpdateMaximumSet(com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager manager) { + OrganizationResource resource = manager.organizations() + .getByResourceGroupWithResponse("rgopenapi", "example-organization-name", com.azure.core.util.Context.NONE) + .getValue(); + resource.update() + .withTags(mapOf("new-tag", "new.tag.value")) + .withIdentity(new ManagedServiceIdentity().withType(ManagedServiceIdentityType.NONE) + .withUserAssignedIdentities(mapOf("ident573739201", new UserAssignedIdentity()))) + .apply(); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} +``` + diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/pom.xml b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/pom.xml new file mode 100644 index 000000000000..c0b9ddc32c4b --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/pom.xml @@ -0,0 +1,75 @@ + + + 4.0.0 + + com.azure + azure-client-sdk-parent + 1.7.0 + ../../parents/azure-client-sdk-parent + + + com.azure.resourcemanager + azure-resourcemanager-pineconevectordb + 1.0.0-beta.2 + jar + + Microsoft Azure SDK for Pinecone Vector Db Management + This package contains Microsoft Azure SDK for Pinecone Vector Db Management SDK. For documentation on how to use this package, please see https://aka.ms/azsdk/java/mgmt. + https://github.com/Azure/azure-sdk-for-java + + + + The MIT License (MIT) + http://opensource.org/licenses/MIT + repo + + + + + https://github.com/Azure/azure-sdk-for-java + scm:git:git@github.com:Azure/azure-sdk-for-java.git + scm:git:git@github.com:Azure/azure-sdk-for-java.git + HEAD + + + + microsoft + Microsoft + + + + UTF-8 + 0 + 0 + true + false + + + + com.azure + azure-core + 1.55.3 + + + com.azure + azure-core-management + 1.17.0 + + + com.azure + azure-core-test + 1.27.0-beta.8 + test + + + com.azure + azure-identity + 1.15.4 + test + + + diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/PineconeVectorDbManager.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/PineconeVectorDbManager.java new file mode 100644 index 000000000000..3d654751b5d9 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/PineconeVectorDbManager.java @@ -0,0 +1,297 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.HttpPipelinePosition; +import com.azure.core.http.policy.AddDatePolicy; +import com.azure.core.http.policy.AddHeadersFromContextPolicy; +import com.azure.core.http.policy.BearerTokenAuthenticationPolicy; +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.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.management.profile.AzureProfile; +import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.pineconevectordb.fluent.PineconeVectorDbMgmtClient; +import com.azure.resourcemanager.pineconevectordb.implementation.OperationsImpl; +import com.azure.resourcemanager.pineconevectordb.implementation.OrganizationsImpl; +import com.azure.resourcemanager.pineconevectordb.implementation.PineconeVectorDbMgmtClientBuilder; +import com.azure.resourcemanager.pineconevectordb.models.Operations; +import com.azure.resourcemanager.pineconevectordb.models.Organizations; +import java.time.Duration; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +/** + * Entry point to PineconeVectorDbManager. + */ +public final class PineconeVectorDbManager { + private Operations operations; + + private Organizations organizations; + + private final PineconeVectorDbMgmtClient clientObject; + + private PineconeVectorDbManager(HttpPipeline httpPipeline, AzureProfile profile, Duration defaultPollInterval) { + Objects.requireNonNull(httpPipeline, "'httpPipeline' cannot be null."); + Objects.requireNonNull(profile, "'profile' cannot be null."); + this.clientObject = new PineconeVectorDbMgmtClientBuilder().pipeline(httpPipeline) + .endpoint(profile.getEnvironment().getResourceManagerEndpoint()) + .subscriptionId(profile.getSubscriptionId()) + .defaultPollInterval(defaultPollInterval) + .buildClient(); + } + + /** + * Creates an instance of Pinecone Vector Db service API entry point. + * + * @param credential the credential to use. + * @param profile the Azure profile for client. + * @return the Pinecone Vector Db service API instance. + */ + public static PineconeVectorDbManager authenticate(TokenCredential credential, AzureProfile profile) { + Objects.requireNonNull(credential, "'credential' cannot be null."); + Objects.requireNonNull(profile, "'profile' cannot be null."); + return configure().authenticate(credential, profile); + } + + /** + * Creates an instance of Pinecone Vector Db service API entry point. + * + * @param httpPipeline the {@link HttpPipeline} configured with Azure authentication credential. + * @param profile the Azure profile for client. + * @return the Pinecone Vector Db service API instance. + */ + public static PineconeVectorDbManager authenticate(HttpPipeline httpPipeline, AzureProfile profile) { + Objects.requireNonNull(httpPipeline, "'httpPipeline' cannot be null."); + Objects.requireNonNull(profile, "'profile' cannot be null."); + return new PineconeVectorDbManager(httpPipeline, profile, null); + } + + /** + * Gets a Configurable instance that can be used to create PineconeVectorDbManager with optional configuration. + * + * @return the Configurable instance allowing configurations. + */ + public static Configurable configure() { + return new PineconeVectorDbManager.Configurable(); + } + + /** + * The Configurable allowing configurations to be set. + */ + public static final class Configurable { + private static final ClientLogger LOGGER = new ClientLogger(Configurable.class); + private static final String SDK_VERSION = "version"; + private static final Map PROPERTIES + = CoreUtils.getProperties("azure-resourcemanager-pineconevectordb.properties"); + + private HttpClient httpClient; + private HttpLogOptions httpLogOptions; + private final List policies = new ArrayList<>(); + private final List scopes = new ArrayList<>(); + private RetryPolicy retryPolicy; + private RetryOptions retryOptions; + private Duration defaultPollInterval; + + private Configurable() { + } + + /** + * Sets the http client. + * + * @param httpClient the HTTP client. + * @return the configurable object itself. + */ + public Configurable withHttpClient(HttpClient httpClient) { + this.httpClient = Objects.requireNonNull(httpClient, "'httpClient' cannot be null."); + return this; + } + + /** + * Sets the logging options to the HTTP pipeline. + * + * @param httpLogOptions the HTTP log options. + * @return the configurable object itself. + */ + public Configurable withLogOptions(HttpLogOptions httpLogOptions) { + this.httpLogOptions = Objects.requireNonNull(httpLogOptions, "'httpLogOptions' cannot be null."); + return this; + } + + /** + * Adds the pipeline policy to the HTTP pipeline. + * + * @param policy the HTTP pipeline policy. + * @return the configurable object itself. + */ + public Configurable withPolicy(HttpPipelinePolicy policy) { + this.policies.add(Objects.requireNonNull(policy, "'policy' cannot be null.")); + return this; + } + + /** + * Adds the scope to permission sets. + * + * @param scope the scope. + * @return the configurable object itself. + */ + public Configurable withScope(String scope) { + this.scopes.add(Objects.requireNonNull(scope, "'scope' cannot be null.")); + return this; + } + + /** + * Sets the retry policy to the HTTP pipeline. + * + * @param retryPolicy the HTTP pipeline retry policy. + * @return the configurable object itself. + */ + public Configurable withRetryPolicy(RetryPolicy retryPolicy) { + this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null."); + return this; + } + + /** + * Sets the retry options for the HTTP pipeline retry policy. + *

        + * This setting has no effect, if retry policy is set via {@link #withRetryPolicy(RetryPolicy)}. + * + * @param retryOptions the retry options for the HTTP pipeline retry policy. + * @return the configurable object itself. + */ + public Configurable withRetryOptions(RetryOptions retryOptions) { + this.retryOptions = Objects.requireNonNull(retryOptions, "'retryOptions' cannot be null."); + return this; + } + + /** + * Sets the default poll interval, used when service does not provide "Retry-After" header. + * + * @param defaultPollInterval the default poll interval. + * @return the configurable object itself. + */ + public Configurable withDefaultPollInterval(Duration defaultPollInterval) { + this.defaultPollInterval + = Objects.requireNonNull(defaultPollInterval, "'defaultPollInterval' cannot be null."); + if (this.defaultPollInterval.isNegative()) { + throw LOGGER + .logExceptionAsError(new IllegalArgumentException("'defaultPollInterval' cannot be negative")); + } + return this; + } + + /** + * Creates an instance of Pinecone Vector Db service API entry point. + * + * @param credential the credential to use. + * @param profile the Azure profile for client. + * @return the Pinecone Vector Db service API instance. + */ + public PineconeVectorDbManager authenticate(TokenCredential credential, AzureProfile profile) { + Objects.requireNonNull(credential, "'credential' cannot be null."); + Objects.requireNonNull(profile, "'profile' cannot be null."); + + String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); + + StringBuilder userAgentBuilder = new StringBuilder(); + userAgentBuilder.append("azsdk-java") + .append("-") + .append("com.azure.resourcemanager.pineconevectordb") + .append("/") + .append(clientVersion); + if (!Configuration.getGlobalConfiguration().get("AZURE_TELEMETRY_DISABLED", false)) { + userAgentBuilder.append(" (") + .append(Configuration.getGlobalConfiguration().get("java.version")) + .append("; ") + .append(Configuration.getGlobalConfiguration().get("os.name")) + .append("; ") + .append(Configuration.getGlobalConfiguration().get("os.version")) + .append("; auto-generated)"); + } else { + userAgentBuilder.append(" (auto-generated)"); + } + + if (scopes.isEmpty()) { + scopes.add(profile.getEnvironment().getManagementEndpoint() + "/.default"); + } + if (retryPolicy == null) { + if (retryOptions != null) { + retryPolicy = new RetryPolicy(retryOptions); + } else { + retryPolicy = new RetryPolicy("Retry-After", ChronoUnit.SECONDS); + } + } + List policies = new ArrayList<>(); + policies.add(new UserAgentPolicy(userAgentBuilder.toString())); + policies.add(new AddHeadersFromContextPolicy()); + policies.add(new RequestIdPolicy()); + policies.addAll(this.policies.stream() + .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) + .collect(Collectors.toList())); + HttpPolicyProviders.addBeforeRetryPolicies(policies); + policies.add(retryPolicy); + policies.add(new AddDatePolicy()); + policies.add(new BearerTokenAuthenticationPolicy(credential, scopes.toArray(new String[0]))); + policies.addAll(this.policies.stream() + .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) + .collect(Collectors.toList())); + HttpPolicyProviders.addAfterRetryPolicies(policies); + policies.add(new HttpLoggingPolicy(httpLogOptions)); + HttpPipeline httpPipeline = new HttpPipelineBuilder().httpClient(httpClient) + .policies(policies.toArray(new HttpPipelinePolicy[0])) + .build(); + return new PineconeVectorDbManager(httpPipeline, profile, defaultPollInterval); + } + } + + /** + * Gets the resource collection API of Operations. + * + * @return Resource collection API of Operations. + */ + public Operations operations() { + if (this.operations == null) { + this.operations = new OperationsImpl(clientObject.getOperations(), this); + } + return operations; + } + + /** + * Gets the resource collection API of Organizations. It manages OrganizationResource. + * + * @return Resource collection API of Organizations. + */ + public Organizations organizations() { + if (this.organizations == null) { + this.organizations = new OrganizationsImpl(clientObject.getOrganizations(), this); + } + return organizations; + } + + /** + * Gets wrapped service client PineconeVectorDbMgmtClient providing direct access to the underlying auto-generated + * API implementation, based on Azure REST API. + * + * @return Wrapped service client PineconeVectorDbMgmtClient. + */ + public PineconeVectorDbMgmtClient serviceClient() { + return this.clientObject; + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/fluent/OperationsClient.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/fluent/OperationsClient.java new file mode 100644 index 000000000000..32d290e70a3d --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/fluent/OperationsClient.java @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.Context; +import com.azure.resourcemanager.pineconevectordb.fluent.models.OperationInner; + +/** + * An instance of this class provides access to all the operations defined in OperationsClient. + */ +public interface OperationsClient { + /** + * List the operations for the provider. + * + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(); + + /** + * List the operations for the provider. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(Context context); +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/fluent/OrganizationsClient.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/fluent/OrganizationsClient.java new file mode 100644 index 000000000000..ab04f51f437e --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/fluent/OrganizationsClient.java @@ -0,0 +1,243 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.fluent; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.pineconevectordb.fluent.models.OrganizationResourceInner; +import com.azure.resourcemanager.pineconevectordb.models.OrganizationResourceUpdate; + +/** + * An instance of this class provides access to all the operations defined in OrganizationsClient. + */ +public interface OrganizationsClient { + /** + * Get a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a OrganizationResource along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getByResourceGroupWithResponse(String resourceGroupName, + String organizationname, Context context); + + /** + * Get a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a OrganizationResource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + OrganizationResourceInner getByResourceGroup(String resourceGroupName, String organizationname); + + /** + * Create a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of concrete tracked resource types can be created by aliasing this + * type using a specific property type. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, OrganizationResourceInner> + beginCreateOrUpdate(String resourceGroupName, String organizationname, OrganizationResourceInner resource); + + /** + * Create a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of concrete tracked resource types can be created by aliasing this + * type using a specific property type. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, OrganizationResourceInner> beginCreateOrUpdate( + String resourceGroupName, String organizationname, OrganizationResourceInner resource, Context context); + + /** + * Create a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete tracked resource types can be created by aliasing this type using a specific property type. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + OrganizationResourceInner createOrUpdate(String resourceGroupName, String organizationname, + OrganizationResourceInner resource); + + /** + * Create a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete tracked resource types can be created by aliasing this type using a specific property type. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + OrganizationResourceInner createOrUpdate(String resourceGroupName, String organizationname, + OrganizationResourceInner resource, Context context); + + /** + * Update a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param properties The resource properties to be updated. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete tracked resource types can be created by aliasing this type using a specific property type along + * with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response updateWithResponse(String resourceGroupName, String organizationname, + OrganizationResourceUpdate properties, Context context); + + /** + * Update a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete tracked resource types can be created by aliasing this type using a specific property type. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + OrganizationResourceInner update(String resourceGroupName, String organizationname, + OrganizationResourceUpdate properties); + + /** + * Delete a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, Void> beginDelete(String resourceGroupName, String organizationname); + + /** + * Delete a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + SyncPoller, Void> beginDelete(String resourceGroupName, String organizationname, Context context); + + /** + * Delete a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void delete(String resourceGroupName, String organizationname); + + /** + * Delete a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + void delete(String resourceGroupName, String organizationname, Context context); + + /** + * List OrganizationResource resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a OrganizationResource list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByResourceGroup(String resourceGroupName); + + /** + * List OrganizationResource resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a OrganizationResource list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByResourceGroup(String resourceGroupName, Context context); + + /** + * List OrganizationResource resources by subscription ID. + * + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a OrganizationResource list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(); + + /** + * List OrganizationResource resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a OrganizationResource list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(Context context); +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/fluent/PineconeVectorDbMgmtClient.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/fluent/PineconeVectorDbMgmtClient.java new file mode 100644 index 000000000000..a41629233d7f --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/fluent/PineconeVectorDbMgmtClient.java @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.fluent; + +import com.azure.core.http.HttpPipeline; +import java.time.Duration; + +/** + * The interface for PineconeVectorDbMgmtClient class. + */ +public interface PineconeVectorDbMgmtClient { + /** + * Gets Service host. + * + * @return the endpoint value. + */ + String getEndpoint(); + + /** + * Gets Version parameter. + * + * @return the apiVersion value. + */ + String getApiVersion(); + + /** + * Gets The ID of the target subscription. The value must be an UUID. + * + * @return the subscriptionId value. + */ + String getSubscriptionId(); + + /** + * Gets The HTTP pipeline to send requests through. + * + * @return the httpPipeline value. + */ + HttpPipeline getHttpPipeline(); + + /** + * Gets The default poll interval for long-running operation. + * + * @return the defaultPollInterval value. + */ + Duration getDefaultPollInterval(); + + /** + * Gets the OperationsClient object to access its operations. + * + * @return the OperationsClient object. + */ + OperationsClient getOperations(); + + /** + * Gets the OrganizationsClient object to access its operations. + * + * @return the OrganizationsClient object. + */ + OrganizationsClient getOrganizations(); +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/fluent/models/OperationInner.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/fluent/models/OperationInner.java new file mode 100644 index 000000000000..22bd6ee3756d --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/fluent/models/OperationInner.java @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.fluent.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 com.azure.resourcemanager.pineconevectordb.models.ActionType; +import com.azure.resourcemanager.pineconevectordb.models.OperationDisplay; +import com.azure.resourcemanager.pineconevectordb.models.Origin; +import java.io.IOException; + +/** + * Details of a REST API operation, returned from the Resource Provider Operations API. + */ +@Immutable +public final class OperationInner implements JsonSerializable { + /* + * The name of the operation, as per Resource-Based Access Control (RBAC). Examples: + * "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action" + */ + private String name; + + /* + * Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure + * Resource Manager/control-plane operations. + */ + private Boolean isDataAction; + + /* + * Localized display information for this particular operation. + */ + private OperationDisplay display; + + /* + * The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default + * value is "user,system" + */ + private Origin origin; + + /* + * Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + */ + private ActionType actionType; + + /** + * Creates an instance of OperationInner class. + */ + private OperationInner() { + } + + /** + * Get the name property: The name of the operation, as per Resource-Based Access Control (RBAC). Examples: + * "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action". + * + * @return the name value. + */ + public String name() { + return this.name; + } + + /** + * Get the isDataAction property: Whether the operation applies to data-plane. This is "true" for data-plane + * operations and "false" for Azure Resource Manager/control-plane operations. + * + * @return the isDataAction value. + */ + public Boolean isDataAction() { + return this.isDataAction; + } + + /** + * Get the display property: Localized display information for this particular operation. + * + * @return the display value. + */ + public OperationDisplay display() { + return this.display; + } + + /** + * Get the origin property: The intended executor of the operation; as in Resource Based Access Control (RBAC) and + * audit logs UX. Default value is "user,system". + * + * @return the origin value. + */ + public Origin origin() { + return this.origin; + } + + /** + * Get the actionType property: Extensible enum. Indicates the action type. "Internal" refers to actions that are + * for internal only APIs. + * + * @return the actionType value. + */ + public ActionType actionType() { + return this.actionType; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (display() != null) { + display().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("display", this.display); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OperationInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OperationInner 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 OperationInner. + */ + public static OperationInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OperationInner deserializedOperationInner = new OperationInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("name".equals(fieldName)) { + deserializedOperationInner.name = reader.getString(); + } else if ("isDataAction".equals(fieldName)) { + deserializedOperationInner.isDataAction = reader.getNullable(JsonReader::getBoolean); + } else if ("display".equals(fieldName)) { + deserializedOperationInner.display = OperationDisplay.fromJson(reader); + } else if ("origin".equals(fieldName)) { + deserializedOperationInner.origin = Origin.fromString(reader.getString()); + } else if ("actionType".equals(fieldName)) { + deserializedOperationInner.actionType = ActionType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedOperationInner; + }); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/fluent/models/OrganizationResourceInner.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/fluent/models/OrganizationResourceInner.java new file mode 100644 index 000000000000..b291e07b355a --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/fluent/models/OrganizationResourceInner.java @@ -0,0 +1,224 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.Resource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.pineconevectordb.models.ManagedServiceIdentity; +import com.azure.resourcemanager.pineconevectordb.models.OrganizationProperties; +import java.io.IOException; +import java.util.Map; + +/** + * Concrete tracked resource types can be created by aliasing this type using a specific property type. + */ +@Fluent +public final class OrganizationResourceInner extends Resource { + /* + * The resource-specific properties for this resource. + */ + private OrganizationProperties properties; + + /* + * The managed service identities assigned to this resource. + */ + private ManagedServiceIdentity identity; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of OrganizationResourceInner class. + */ + public OrganizationResourceInner() { + } + + /** + * Get the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + public OrganizationProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The resource-specific properties for this resource. + * + * @param properties the properties value to set. + * @return the OrganizationResourceInner object itself. + */ + public OrganizationResourceInner withProperties(OrganizationProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the identity property: The managed service identities assigned to this resource. + * + * @return the identity value. + */ + public ManagedServiceIdentity identity() { + return this.identity; + } + + /** + * Set the identity property: The managed service identities assigned to this resource. + * + * @param identity the identity value to set. + * @return the OrganizationResourceInner object itself. + */ + public OrganizationResourceInner withIdentity(ManagedServiceIdentity identity) { + this.identity = identity; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * {@inheritDoc} + */ + @Override + public OrganizationResourceInner withLocation(String location) { + super.withLocation(location); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public OrganizationResourceInner withTags(Map tags) { + super.withTags(tags); + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + if (identity() != null) { + identity().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("location", location()); + jsonWriter.writeMapField("tags", tags(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeJsonField("properties", this.properties); + jsonWriter.writeJsonField("identity", this.identity); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OrganizationResourceInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OrganizationResourceInner 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 OrganizationResourceInner. + */ + public static OrganizationResourceInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OrganizationResourceInner deserializedOrganizationResourceInner = new OrganizationResourceInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedOrganizationResourceInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedOrganizationResourceInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedOrganizationResourceInner.type = reader.getString(); + } else if ("location".equals(fieldName)) { + deserializedOrganizationResourceInner.withLocation(reader.getString()); + } else if ("tags".equals(fieldName)) { + Map tags = reader.readMap(reader1 -> reader1.getString()); + deserializedOrganizationResourceInner.withTags(tags); + } else if ("properties".equals(fieldName)) { + deserializedOrganizationResourceInner.properties = OrganizationProperties.fromJson(reader); + } else if ("identity".equals(fieldName)) { + deserializedOrganizationResourceInner.identity = ManagedServiceIdentity.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedOrganizationResourceInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedOrganizationResourceInner; + }); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/fluent/models/package-info.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/fluent/models/package-info.java new file mode 100644 index 000000000000..a70d5cc3d8f7 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/fluent/models/package-info.java @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +/** + * Package containing the inner data models for PineconeVectorDb. + */ +package com.azure.resourcemanager.pineconevectordb.fluent.models; diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/fluent/package-info.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/fluent/package-info.java new file mode 100644 index 000000000000..36d997db9912 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/fluent/package-info.java @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +/** + * Package containing the service clients for PineconeVectorDb. + */ +package com.azure.resourcemanager.pineconevectordb.fluent; diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/OperationImpl.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/OperationImpl.java new file mode 100644 index 000000000000..196eb5fd7377 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/OperationImpl.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.implementation; + +import com.azure.resourcemanager.pineconevectordb.fluent.models.OperationInner; +import com.azure.resourcemanager.pineconevectordb.models.ActionType; +import com.azure.resourcemanager.pineconevectordb.models.Operation; +import com.azure.resourcemanager.pineconevectordb.models.OperationDisplay; +import com.azure.resourcemanager.pineconevectordb.models.Origin; + +public final class OperationImpl implements Operation { + private OperationInner innerObject; + + private final com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager serviceManager; + + OperationImpl(OperationInner innerObject, + com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String name() { + return this.innerModel().name(); + } + + public Boolean isDataAction() { + return this.innerModel().isDataAction(); + } + + public OperationDisplay display() { + return this.innerModel().display(); + } + + public Origin origin() { + return this.innerModel().origin(); + } + + public ActionType actionType() { + return this.innerModel().actionType(); + } + + public OperationInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/OperationsClientImpl.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/OperationsClientImpl.java new file mode 100644 index 000000000000..c01c34ccc8bd --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/OperationsClientImpl.java @@ -0,0 +1,235 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.implementation; + +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.resourcemanager.pineconevectordb.fluent.OperationsClient; +import com.azure.resourcemanager.pineconevectordb.fluent.models.OperationInner; +import com.azure.resourcemanager.pineconevectordb.implementation.models.OperationListResult; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in OperationsClient. + */ +public final class OperationsClientImpl implements OperationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final OperationsService service; + + /** + * The service client containing this operation class. + */ + private final PineconeVectorDbMgmtClientImpl client; + + /** + * Initializes an instance of OperationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + OperationsClientImpl(PineconeVectorDbMgmtClientImpl client) { + this.service + = RestProxy.create(OperationsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for PineconeVectorDbMgmtClientOperations to be used by the proxy service + * to perform REST calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "PineconeVectorDbMgmt") + public interface OperationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/providers/Pinecone.VectorDb/operations") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> list(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listNext(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("endpoint") String endpoint, @HeaderParam("Accept") String accept, Context context); + } + + /** + * List the operations for the provider. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider along with {@link PagedResponse} on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync() { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.list(this.client.getEndpoint(), this.client.getApiVersion(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), + res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List the operations for the provider. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider along with {@link PagedResponse} on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync(Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.list(this.client.getEndpoint(), this.client.getApiVersion(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List the operations for the provider. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync() { + return new PagedFlux<>(() -> listSinglePageAsync(), nextLink -> listNextSinglePageAsync(nextLink)); + } + + /** + * List the operations for the provider. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync(Context context) { + return new PagedFlux<>(() -> listSinglePageAsync(context), + nextLink -> listNextSinglePageAsync(nextLink, context)); + } + + /** + * List the operations for the provider. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list() { + return new PagedIterable<>(listAsync()); + } + + /** + * List the operations for the provider. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(Context context) { + return new PagedIterable<>(listAsync(context)); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider along with {@link PagedResponse} on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.listNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), + res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider along with {@link PagedResponse} on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listNextSinglePageAsync(String nextLink, Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/OperationsImpl.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/OperationsImpl.java new file mode 100644 index 000000000000..b8c56b7b73b4 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/OperationsImpl.java @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.pineconevectordb.fluent.OperationsClient; +import com.azure.resourcemanager.pineconevectordb.fluent.models.OperationInner; +import com.azure.resourcemanager.pineconevectordb.models.Operation; +import com.azure.resourcemanager.pineconevectordb.models.Operations; + +public final class OperationsImpl implements Operations { + private static final ClientLogger LOGGER = new ClientLogger(OperationsImpl.class); + + private final OperationsClient innerClient; + + private final com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager serviceManager; + + public OperationsImpl(OperationsClient innerClient, + com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public PagedIterable list() { + PagedIterable inner = this.serviceClient().list(); + return ResourceManagerUtils.mapPage(inner, inner1 -> new OperationImpl(inner1, this.manager())); + } + + public PagedIterable list(Context context) { + PagedIterable inner = this.serviceClient().list(context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new OperationImpl(inner1, this.manager())); + } + + private OperationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/OrganizationResourceImpl.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/OrganizationResourceImpl.java new file mode 100644 index 000000000000..cdf1cadc1832 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/OrganizationResourceImpl.java @@ -0,0 +1,196 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.implementation; + +import com.azure.core.management.Region; +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.pineconevectordb.fluent.models.OrganizationResourceInner; +import com.azure.resourcemanager.pineconevectordb.models.ManagedServiceIdentity; +import com.azure.resourcemanager.pineconevectordb.models.OrganizationProperties; +import com.azure.resourcemanager.pineconevectordb.models.OrganizationResource; +import com.azure.resourcemanager.pineconevectordb.models.OrganizationResourceUpdate; +import java.util.Collections; +import java.util.Map; + +public final class OrganizationResourceImpl + implements OrganizationResource, OrganizationResource.Definition, OrganizationResource.Update { + private OrganizationResourceInner innerObject; + + private final com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager serviceManager; + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public String location() { + return this.innerModel().location(); + } + + public Map tags() { + Map inner = this.innerModel().tags(); + if (inner != null) { + return Collections.unmodifiableMap(inner); + } else { + return Collections.emptyMap(); + } + } + + public OrganizationProperties properties() { + return this.innerModel().properties(); + } + + public ManagedServiceIdentity identity() { + return this.innerModel().identity(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public Region region() { + return Region.fromName(this.regionName()); + } + + public String regionName() { + return this.location(); + } + + public String resourceGroupName() { + return resourceGroupName; + } + + public OrganizationResourceInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager manager() { + return this.serviceManager; + } + + private String resourceGroupName; + + private String organizationname; + + private OrganizationResourceUpdate updateProperties; + + public OrganizationResourceImpl withExistingResourceGroup(String resourceGroupName) { + this.resourceGroupName = resourceGroupName; + return this; + } + + public OrganizationResource create() { + this.innerObject = serviceManager.serviceClient() + .getOrganizations() + .createOrUpdate(resourceGroupName, organizationname, this.innerModel(), Context.NONE); + return this; + } + + public OrganizationResource create(Context context) { + this.innerObject = serviceManager.serviceClient() + .getOrganizations() + .createOrUpdate(resourceGroupName, organizationname, this.innerModel(), context); + return this; + } + + OrganizationResourceImpl(String name, + com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager serviceManager) { + this.innerObject = new OrganizationResourceInner(); + this.serviceManager = serviceManager; + this.organizationname = name; + } + + public OrganizationResourceImpl update() { + this.updateProperties = new OrganizationResourceUpdate(); + return this; + } + + public OrganizationResource apply() { + this.innerObject = serviceManager.serviceClient() + .getOrganizations() + .updateWithResponse(resourceGroupName, organizationname, updateProperties, Context.NONE) + .getValue(); + return this; + } + + public OrganizationResource apply(Context context) { + this.innerObject = serviceManager.serviceClient() + .getOrganizations() + .updateWithResponse(resourceGroupName, organizationname, updateProperties, context) + .getValue(); + return this; + } + + OrganizationResourceImpl(OrganizationResourceInner innerObject, + com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + this.resourceGroupName = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "resourceGroups"); + this.organizationname = ResourceManagerUtils.getValueFromIdByName(innerObject.id(), "organizations"); + } + + public OrganizationResource refresh() { + this.innerObject = serviceManager.serviceClient() + .getOrganizations() + .getByResourceGroupWithResponse(resourceGroupName, organizationname, Context.NONE) + .getValue(); + return this; + } + + public OrganizationResource refresh(Context context) { + this.innerObject = serviceManager.serviceClient() + .getOrganizations() + .getByResourceGroupWithResponse(resourceGroupName, organizationname, context) + .getValue(); + return this; + } + + public OrganizationResourceImpl withRegion(Region location) { + this.innerModel().withLocation(location.toString()); + return this; + } + + public OrganizationResourceImpl withRegion(String location) { + this.innerModel().withLocation(location); + return this; + } + + public OrganizationResourceImpl withTags(Map tags) { + if (isInCreateMode()) { + this.innerModel().withTags(tags); + return this; + } else { + this.updateProperties.withTags(tags); + return this; + } + } + + public OrganizationResourceImpl withProperties(OrganizationProperties properties) { + this.innerModel().withProperties(properties); + return this; + } + + public OrganizationResourceImpl withIdentity(ManagedServiceIdentity identity) { + if (isInCreateMode()) { + this.innerModel().withIdentity(identity); + return this; + } else { + this.updateProperties.withIdentity(identity); + return this; + } + } + + private boolean isInCreateMode() { + return this.innerModel().id() == null; + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/OrganizationsClientImpl.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/OrganizationsClientImpl.java new file mode 100644 index 000000000000..ee901eb88c6a --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/OrganizationsClientImpl.java @@ -0,0 +1,1212 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Headers; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.Patch; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Put; +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.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.management.polling.PollResult; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.core.util.polling.PollerFlux; +import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.pineconevectordb.fluent.OrganizationsClient; +import com.azure.resourcemanager.pineconevectordb.fluent.models.OrganizationResourceInner; +import com.azure.resourcemanager.pineconevectordb.implementation.models.OrganizationResourceListResult; +import com.azure.resourcemanager.pineconevectordb.models.OrganizationResourceUpdate; +import java.nio.ByteBuffer; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in OrganizationsClient. + */ +public final class OrganizationsClientImpl implements OrganizationsClient { + /** + * The proxy service used to perform REST calls. + */ + private final OrganizationsService service; + + /** + * The service client containing this operation class. + */ + private final PineconeVectorDbMgmtClientImpl client; + + /** + * Initializes an instance of OrganizationsClientImpl. + * + * @param client the instance of the service client containing this operation class. + */ + OrganizationsClientImpl(PineconeVectorDbMgmtClientImpl client) { + this.service + = RestProxy.create(OrganizationsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for PineconeVectorDbMgmtClientOrganizations to be used by the proxy + * service to perform REST calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "PineconeVectorDbMgmt") + public interface OrganizationsService { + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Pinecone.VectorDb/organizations/{organizationname}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> getByResourceGroup(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, + @PathParam("organizationname") String organizationname, @HeaderParam("Accept") String accept, + Context context); + + @Put("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Pinecone.VectorDb/organizations/{organizationname}") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> createOrUpdate(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, + @PathParam("organizationname") String organizationname, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") OrganizationResourceInner resource, + Context context); + + @Patch("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Pinecone.VectorDb/organizations/{organizationname}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> update(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, + @PathParam("organizationname") String organizationname, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") OrganizationResourceUpdate properties, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Delete("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Pinecone.VectorDb/organizations/{organizationname}") + @ExpectedResponses({ 202, 204 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono>> delete(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, + @PathParam("organizationname") String organizationname, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Pinecone.VectorDb/organizations") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByResourceGroup(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/providers/Pinecone.VectorDb/organizations") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> list(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByResourceGroupNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listBySubscriptionNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, + @HeaderParam("Accept") String accept, Context context); + } + + /** + * Get a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a OrganizationResource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getByResourceGroupWithResponseAsync(String resourceGroupName, + String organizationname) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (organizationname == null) { + return Mono + .error(new IllegalArgumentException("Parameter organizationname is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.getByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, organizationname, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a OrganizationResource along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getByResourceGroupWithResponseAsync(String resourceGroupName, + String organizationname, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (organizationname == null) { + return Mono + .error(new IllegalArgumentException("Parameter organizationname is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.getByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, organizationname, accept, context); + } + + /** + * Get a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a OrganizationResource on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getByResourceGroupAsync(String resourceGroupName, String organizationname) { + return getByResourceGroupWithResponseAsync(resourceGroupName, organizationname) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Get a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a OrganizationResource along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getByResourceGroupWithResponse(String resourceGroupName, + String organizationname, Context context) { + return getByResourceGroupWithResponseAsync(resourceGroupName, organizationname, context).block(); + } + + /** + * Get a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a OrganizationResource. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public OrganizationResourceInner getByResourceGroup(String resourceGroupName, String organizationname) { + return getByResourceGroupWithResponse(resourceGroupName, organizationname, Context.NONE).getValue(); + } + + /** + * Create a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete tracked resource types can be created by aliasing this type using a specific property type along + * with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createOrUpdateWithResponseAsync(String resourceGroupName, + String organizationname, OrganizationResourceInner resource) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (organizationname == null) { + return Mono + .error(new IllegalArgumentException("Parameter organizationname is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.createOrUpdate(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, organizationname, contentType, accept, resource, + context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Create a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete tracked resource types can be created by aliasing this type using a specific property type along + * with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> createOrUpdateWithResponseAsync(String resourceGroupName, + String organizationname, OrganizationResourceInner resource, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (organizationname == null) { + return Mono + .error(new IllegalArgumentException("Parameter organizationname is required and cannot be null.")); + } + if (resource == null) { + return Mono.error(new IllegalArgumentException("Parameter resource is required and cannot be null.")); + } else { + resource.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.createOrUpdate(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, organizationname, contentType, accept, resource, + context); + } + + /** + * Create a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of concrete tracked resource types can be created by aliasing this + * type using a specific property type. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, OrganizationResourceInner> beginCreateOrUpdateAsync( + String resourceGroupName, String organizationname, OrganizationResourceInner resource) { + Mono>> mono + = createOrUpdateWithResponseAsync(resourceGroupName, organizationname, resource); + return this.client.getLroResult(mono, + this.client.getHttpPipeline(), OrganizationResourceInner.class, OrganizationResourceInner.class, + this.client.getContext()); + } + + /** + * Create a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of concrete tracked resource types can be created by aliasing this + * type using a specific property type. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, OrganizationResourceInner> beginCreateOrUpdateAsync( + String resourceGroupName, String organizationname, OrganizationResourceInner resource, Context context) { + context = this.client.mergeContext(context); + Mono>> mono + = createOrUpdateWithResponseAsync(resourceGroupName, organizationname, resource, context); + return this.client.getLroResult(mono, + this.client.getHttpPipeline(), OrganizationResourceInner.class, OrganizationResourceInner.class, context); + } + + /** + * Create a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of concrete tracked resource types can be created by aliasing this + * type using a specific property type. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, OrganizationResourceInner> + beginCreateOrUpdate(String resourceGroupName, String organizationname, OrganizationResourceInner resource) { + return this.beginCreateOrUpdateAsync(resourceGroupName, organizationname, resource).getSyncPoller(); + } + + /** + * Create a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of concrete tracked resource types can be created by aliasing this + * type using a specific property type. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, OrganizationResourceInner> beginCreateOrUpdate( + String resourceGroupName, String organizationname, OrganizationResourceInner resource, Context context) { + return this.beginCreateOrUpdateAsync(resourceGroupName, organizationname, resource, context).getSyncPoller(); + } + + /** + * Create a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete tracked resource types can be created by aliasing this type using a specific property type on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createOrUpdateAsync(String resourceGroupName, String organizationname, + OrganizationResourceInner resource) { + return beginCreateOrUpdateAsync(resourceGroupName, organizationname, resource).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete tracked resource types can be created by aliasing this type using a specific property type on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono createOrUpdateAsync(String resourceGroupName, String organizationname, + OrganizationResourceInner resource, Context context) { + return beginCreateOrUpdateAsync(resourceGroupName, organizationname, resource, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Create a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param resource Resource create parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete tracked resource types can be created by aliasing this type using a specific property type. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public OrganizationResourceInner createOrUpdate(String resourceGroupName, String organizationname, + OrganizationResourceInner resource) { + return createOrUpdateAsync(resourceGroupName, organizationname, resource).block(); + } + + /** + * Create a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param resource Resource create parameters. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete tracked resource types can be created by aliasing this type using a specific property type. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public OrganizationResourceInner createOrUpdate(String resourceGroupName, String organizationname, + OrganizationResourceInner resource, Context context) { + return createOrUpdateAsync(resourceGroupName, organizationname, resource, context).block(); + } + + /** + * Update a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete tracked resource types can be created by aliasing this type using a specific property type along + * with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> updateWithResponseAsync(String resourceGroupName, + String organizationname, OrganizationResourceUpdate properties) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (organizationname == null) { + return Mono + .error(new IllegalArgumentException("Parameter organizationname is required and cannot be null.")); + } + if (properties == null) { + return Mono.error(new IllegalArgumentException("Parameter properties is required and cannot be null.")); + } else { + properties.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.update(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, organizationname, contentType, accept, properties, + context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Update a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param properties The resource properties to be updated. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete tracked resource types can be created by aliasing this type using a specific property type along + * with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> updateWithResponseAsync(String resourceGroupName, + String organizationname, OrganizationResourceUpdate properties, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (organizationname == null) { + return Mono + .error(new IllegalArgumentException("Parameter organizationname is required and cannot be null.")); + } + if (properties == null) { + return Mono.error(new IllegalArgumentException("Parameter properties is required and cannot be null.")); + } else { + properties.validate(); + } + final String contentType = "application/json"; + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.update(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, organizationname, contentType, accept, properties, context); + } + + /** + * Update a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete tracked resource types can be created by aliasing this type using a specific property type on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono updateAsync(String resourceGroupName, String organizationname, + OrganizationResourceUpdate properties) { + return updateWithResponseAsync(resourceGroupName, organizationname, properties) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Update a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param properties The resource properties to be updated. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete tracked resource types can be created by aliasing this type using a specific property type along + * with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response updateWithResponse(String resourceGroupName, String organizationname, + OrganizationResourceUpdate properties, Context context) { + return updateWithResponseAsync(resourceGroupName, organizationname, properties, context).block(); + } + + /** + * Update a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param properties The resource properties to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return concrete tracked resource types can be created by aliasing this type using a specific property type. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public OrganizationResourceInner update(String resourceGroupName, String organizationname, + OrganizationResourceUpdate properties) { + return updateWithResponse(resourceGroupName, organizationname, properties, Context.NONE).getValue(); + } + + /** + * Delete a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> deleteWithResponseAsync(String resourceGroupName, + String organizationname) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (organizationname == null) { + return Mono + .error(new IllegalArgumentException("Parameter organizationname is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.delete(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, organizationname, accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Delete a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono>> deleteWithResponseAsync(String resourceGroupName, String organizationname, + Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (organizationname == null) { + return Mono + .error(new IllegalArgumentException("Parameter organizationname is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.delete(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), + resourceGroupName, organizationname, accept, context); + } + + /** + * Delete a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, Void> beginDeleteAsync(String resourceGroupName, String organizationname) { + Mono>> mono = deleteWithResponseAsync(resourceGroupName, organizationname); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), Void.class, Void.class, + this.client.getContext()); + } + + /** + * Delete a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link PollerFlux} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, Void> beginDeleteAsync(String resourceGroupName, String organizationname, + Context context) { + context = this.client.mergeContext(context); + Mono>> mono = deleteWithResponseAsync(resourceGroupName, organizationname, context); + return this.client.getLroResult(mono, this.client.getHttpPipeline(), Void.class, Void.class, + context); + } + + /** + * Delete a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, Void> beginDelete(String resourceGroupName, String organizationname) { + return this.beginDeleteAsync(resourceGroupName, organizationname).getSyncPoller(); + } + + /** + * Delete a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link SyncPoller} for polling of long-running operation. + */ + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, Void> beginDelete(String resourceGroupName, String organizationname, + Context context) { + return this.beginDeleteAsync(resourceGroupName, organizationname, context).getSyncPoller(); + } + + /** + * Delete a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono deleteAsync(String resourceGroupName, String organizationname) { + return beginDeleteAsync(resourceGroupName, organizationname).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Delete a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono deleteAsync(String resourceGroupName, String organizationname, Context context) { + return beginDeleteAsync(resourceGroupName, organizationname, context).last() + .flatMap(this.client::getLroFinalResultOrError); + } + + /** + * Delete a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String resourceGroupName, String organizationname) { + deleteAsync(resourceGroupName, organizationname).block(); + } + + /** + * Delete a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String resourceGroupName, String organizationname, Context context) { + deleteAsync(resourceGroupName, organizationname, context).block(); + } + + /** + * List OrganizationResource resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a OrganizationResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> + listByResourceGroupSinglePageAsync(String resourceGroupName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List OrganizationResource resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a OrganizationResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByResourceGroupSinglePageAsync(String resourceGroupName, + Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List OrganizationResource resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a OrganizationResource list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByResourceGroupAsync(String resourceGroupName) { + return new PagedFlux<>(() -> listByResourceGroupSinglePageAsync(resourceGroupName), + nextLink -> listByResourceGroupNextSinglePageAsync(nextLink)); + } + + /** + * List OrganizationResource resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a OrganizationResource list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByResourceGroupAsync(String resourceGroupName, Context context) { + return new PagedFlux<>(() -> listByResourceGroupSinglePageAsync(resourceGroupName, context), + nextLink -> listByResourceGroupNextSinglePageAsync(nextLink, context)); + } + + /** + * List OrganizationResource resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a OrganizationResource list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByResourceGroup(String resourceGroupName) { + return new PagedIterable<>(listByResourceGroupAsync(resourceGroupName)); + } + + /** + * List OrganizationResource resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a OrganizationResource list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByResourceGroup(String resourceGroupName, Context context) { + return new PagedIterable<>(listByResourceGroupAsync(resourceGroupName, context)); + } + + /** + * List OrganizationResource resources by subscription ID. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a OrganizationResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync() { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.list(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List OrganizationResource resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a OrganizationResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync(Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .list(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), accept, + context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List OrganizationResource resources by subscription ID. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a OrganizationResource list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync() { + return new PagedFlux<>(() -> listSinglePageAsync(), + nextLink -> listBySubscriptionNextSinglePageAsync(nextLink)); + } + + /** + * List OrganizationResource resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a OrganizationResource list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync(Context context) { + return new PagedFlux<>(() -> listSinglePageAsync(context), + nextLink -> listBySubscriptionNextSinglePageAsync(nextLink, context)); + } + + /** + * List OrganizationResource resources by subscription ID. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a OrganizationResource list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list() { + return new PagedIterable<>(listAsync()); + } + + /** + * List OrganizationResource resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a OrganizationResource list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(Context context) { + return new PagedIterable<>(listAsync(context)); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a OrganizationResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByResourceGroupNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByResourceGroupNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a OrganizationResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByResourceGroupNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listByResourceGroupNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a OrganizationResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySubscriptionNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a OrganizationResource list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listBySubscriptionNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/OrganizationsImpl.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/OrganizationsImpl.java new file mode 100644 index 000000000000..2901e156e525 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/OrganizationsImpl.java @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.implementation; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.resourcemanager.pineconevectordb.fluent.OrganizationsClient; +import com.azure.resourcemanager.pineconevectordb.fluent.models.OrganizationResourceInner; +import com.azure.resourcemanager.pineconevectordb.models.OrganizationResource; +import com.azure.resourcemanager.pineconevectordb.models.Organizations; + +public final class OrganizationsImpl implements Organizations { + private static final ClientLogger LOGGER = new ClientLogger(OrganizationsImpl.class); + + private final OrganizationsClient innerClient; + + private final com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager serviceManager; + + public OrganizationsImpl(OrganizationsClient innerClient, + com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager serviceManager) { + this.innerClient = innerClient; + this.serviceManager = serviceManager; + } + + public Response getByResourceGroupWithResponse(String resourceGroupName, + String organizationname, Context context) { + Response inner + = this.serviceClient().getByResourceGroupWithResponse(resourceGroupName, organizationname, context); + if (inner != null) { + return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), + new OrganizationResourceImpl(inner.getValue(), this.manager())); + } else { + return null; + } + } + + public OrganizationResource getByResourceGroup(String resourceGroupName, String organizationname) { + OrganizationResourceInner inner = this.serviceClient().getByResourceGroup(resourceGroupName, organizationname); + if (inner != null) { + return new OrganizationResourceImpl(inner, this.manager()); + } else { + return null; + } + } + + public void deleteByResourceGroup(String resourceGroupName, String organizationname) { + this.serviceClient().delete(resourceGroupName, organizationname); + } + + public void delete(String resourceGroupName, String organizationname, Context context) { + this.serviceClient().delete(resourceGroupName, organizationname, context); + } + + public PagedIterable listByResourceGroup(String resourceGroupName) { + PagedIterable inner = this.serviceClient().listByResourceGroup(resourceGroupName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new OrganizationResourceImpl(inner1, this.manager())); + } + + public PagedIterable listByResourceGroup(String resourceGroupName, Context context) { + PagedIterable inner + = this.serviceClient().listByResourceGroup(resourceGroupName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new OrganizationResourceImpl(inner1, this.manager())); + } + + public PagedIterable list() { + PagedIterable inner = this.serviceClient().list(); + return ResourceManagerUtils.mapPage(inner, inner1 -> new OrganizationResourceImpl(inner1, this.manager())); + } + + public PagedIterable list(Context context) { + PagedIterable inner = this.serviceClient().list(context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new OrganizationResourceImpl(inner1, this.manager())); + } + + public OrganizationResource getById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String organizationname = ResourceManagerUtils.getValueFromIdByName(id, "organizations"); + if (organizationname == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'organizations'.", id))); + } + return this.getByResourceGroupWithResponse(resourceGroupName, organizationname, Context.NONE).getValue(); + } + + public Response getByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String organizationname = ResourceManagerUtils.getValueFromIdByName(id, "organizations"); + if (organizationname == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'organizations'.", id))); + } + return this.getByResourceGroupWithResponse(resourceGroupName, organizationname, context); + } + + public void deleteById(String id) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String organizationname = ResourceManagerUtils.getValueFromIdByName(id, "organizations"); + if (organizationname == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'organizations'.", id))); + } + this.delete(resourceGroupName, organizationname, Context.NONE); + } + + public void deleteByIdWithResponse(String id, Context context) { + String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); + if (resourceGroupName == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id))); + } + String organizationname = ResourceManagerUtils.getValueFromIdByName(id, "organizations"); + if (organizationname == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + String.format("The resource ID '%s' is not valid. Missing path segment 'organizations'.", id))); + } + this.delete(resourceGroupName, organizationname, context); + } + + private OrganizationsClient serviceClient() { + return this.innerClient; + } + + private com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager manager() { + return this.serviceManager; + } + + public OrganizationResourceImpl define(String name) { + return new OrganizationResourceImpl(name, this.manager()); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/PineconeVectorDbMgmtClientBuilder.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/PineconeVectorDbMgmtClientBuilder.java new file mode 100644 index 000000000000..3a1e2fb3fb71 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/PineconeVectorDbMgmtClientBuilder.java @@ -0,0 +1,138 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.implementation; + +import com.azure.core.annotation.ServiceClientBuilder; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.policy.RetryPolicy; +import com.azure.core.http.policy.UserAgentPolicy; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.serializer.SerializerFactory; +import com.azure.core.util.serializer.SerializerAdapter; +import java.time.Duration; + +/** + * A builder for creating a new instance of the PineconeVectorDbMgmtClientImpl type. + */ +@ServiceClientBuilder(serviceClients = { PineconeVectorDbMgmtClientImpl.class }) +public final class PineconeVectorDbMgmtClientBuilder { + /* + * Service host + */ + private String endpoint; + + /** + * Sets Service host. + * + * @param endpoint the endpoint value. + * @return the PineconeVectorDbMgmtClientBuilder. + */ + public PineconeVectorDbMgmtClientBuilder endpoint(String endpoint) { + this.endpoint = endpoint; + return this; + } + + /* + * The ID of the target subscription. The value must be an UUID. + */ + private String subscriptionId; + + /** + * Sets The ID of the target subscription. The value must be an UUID. + * + * @param subscriptionId the subscriptionId value. + * @return the PineconeVectorDbMgmtClientBuilder. + */ + public PineconeVectorDbMgmtClientBuilder subscriptionId(String subscriptionId) { + this.subscriptionId = subscriptionId; + return this; + } + + /* + * The environment to connect to + */ + private AzureEnvironment environment; + + /** + * Sets The environment to connect to. + * + * @param environment the environment value. + * @return the PineconeVectorDbMgmtClientBuilder. + */ + public PineconeVectorDbMgmtClientBuilder environment(AzureEnvironment environment) { + this.environment = environment; + 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 PineconeVectorDbMgmtClientBuilder. + */ + public PineconeVectorDbMgmtClientBuilder pipeline(HttpPipeline pipeline) { + this.pipeline = pipeline; + return this; + } + + /* + * The default poll interval for long-running operation + */ + private Duration defaultPollInterval; + + /** + * Sets The default poll interval for long-running operation. + * + * @param defaultPollInterval the defaultPollInterval value. + * @return the PineconeVectorDbMgmtClientBuilder. + */ + public PineconeVectorDbMgmtClientBuilder defaultPollInterval(Duration defaultPollInterval) { + this.defaultPollInterval = defaultPollInterval; + 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 PineconeVectorDbMgmtClientBuilder. + */ + public PineconeVectorDbMgmtClientBuilder serializerAdapter(SerializerAdapter serializerAdapter) { + this.serializerAdapter = serializerAdapter; + return this; + } + + /** + * Builds an instance of PineconeVectorDbMgmtClientImpl with the provided parameters. + * + * @return an instance of PineconeVectorDbMgmtClientImpl. + */ + public PineconeVectorDbMgmtClientImpl buildClient() { + String localEndpoint = (endpoint != null) ? endpoint : "https://management.azure.com"; + AzureEnvironment localEnvironment = (environment != null) ? environment : AzureEnvironment.AZURE; + HttpPipeline localPipeline = (pipeline != null) + ? pipeline + : new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build(); + Duration localDefaultPollInterval + = (defaultPollInterval != null) ? defaultPollInterval : Duration.ofSeconds(30); + SerializerAdapter localSerializerAdapter = (serializerAdapter != null) + ? serializerAdapter + : SerializerFactory.createDefaultManagementSerializerAdapter(); + PineconeVectorDbMgmtClientImpl client = new PineconeVectorDbMgmtClientImpl(localPipeline, + localSerializerAdapter, localDefaultPollInterval, localEnvironment, localEndpoint, this.subscriptionId); + return client; + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/PineconeVectorDbMgmtClientImpl.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/PineconeVectorDbMgmtClientImpl.java new file mode 100644 index 000000000000..2d95b1d806f2 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/PineconeVectorDbMgmtClientImpl.java @@ -0,0 +1,304 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.implementation; + +import com.azure.core.annotation.ServiceClient; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.HttpHeaders; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpResponse; +import com.azure.core.http.rest.Response; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.exception.ManagementError; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.management.polling.PollResult; +import com.azure.core.management.polling.PollerFactory; +import com.azure.core.util.Context; +import com.azure.core.util.CoreUtils; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.polling.AsyncPollResponse; +import com.azure.core.util.polling.LongRunningOperationStatus; +import com.azure.core.util.polling.PollerFlux; +import com.azure.core.util.serializer.SerializerAdapter; +import com.azure.core.util.serializer.SerializerEncoding; +import com.azure.resourcemanager.pineconevectordb.fluent.OperationsClient; +import com.azure.resourcemanager.pineconevectordb.fluent.OrganizationsClient; +import com.azure.resourcemanager.pineconevectordb.fluent.PineconeVectorDbMgmtClient; +import java.io.IOException; +import java.lang.reflect.Type; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * Initializes a new instance of the PineconeVectorDbMgmtClientImpl type. + */ +@ServiceClient(builder = PineconeVectorDbMgmtClientBuilder.class) +public final class PineconeVectorDbMgmtClientImpl implements PineconeVectorDbMgmtClient { + /** + * Service host. + */ + private final String endpoint; + + /** + * Gets Service host. + * + * @return the endpoint value. + */ + public String getEndpoint() { + return this.endpoint; + } + + /** + * Version parameter. + */ + private final String apiVersion; + + /** + * Gets Version parameter. + * + * @return the apiVersion value. + */ + public String getApiVersion() { + return this.apiVersion; + } + + /** + * The ID of the target subscription. The value must be an UUID. + */ + private final String subscriptionId; + + /** + * Gets The ID of the target subscription. The value must be an UUID. + * + * @return the subscriptionId value. + */ + public String getSubscriptionId() { + return this.subscriptionId; + } + + /** + * 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. + */ + SerializerAdapter getSerializerAdapter() { + return this.serializerAdapter; + } + + /** + * The default poll interval for long-running operation. + */ + private final Duration defaultPollInterval; + + /** + * Gets The default poll interval for long-running operation. + * + * @return the defaultPollInterval value. + */ + public Duration getDefaultPollInterval() { + return this.defaultPollInterval; + } + + /** + * The OperationsClient object to access its operations. + */ + private final OperationsClient operations; + + /** + * Gets the OperationsClient object to access its operations. + * + * @return the OperationsClient object. + */ + public OperationsClient getOperations() { + return this.operations; + } + + /** + * The OrganizationsClient object to access its operations. + */ + private final OrganizationsClient organizations; + + /** + * Gets the OrganizationsClient object to access its operations. + * + * @return the OrganizationsClient object. + */ + public OrganizationsClient getOrganizations() { + return this.organizations; + } + + /** + * Initializes an instance of PineconeVectorDbMgmtClient client. + * + * @param httpPipeline The HTTP pipeline to send requests through. + * @param serializerAdapter The serializer to serialize an object into a string. + * @param defaultPollInterval The default poll interval for long-running operation. + * @param environment The Azure environment. + * @param endpoint Service host. + * @param subscriptionId The ID of the target subscription. The value must be an UUID. + */ + PineconeVectorDbMgmtClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, + Duration defaultPollInterval, AzureEnvironment environment, String endpoint, String subscriptionId) { + this.httpPipeline = httpPipeline; + this.serializerAdapter = serializerAdapter; + this.defaultPollInterval = defaultPollInterval; + this.endpoint = endpoint; + this.subscriptionId = subscriptionId; + this.apiVersion = "2024-10-22-preview"; + this.operations = new OperationsClientImpl(this); + this.organizations = new OrganizationsClientImpl(this); + } + + /** + * Gets default client context. + * + * @return the default client context. + */ + public Context getContext() { + return Context.NONE; + } + + /** + * Merges default client context with provided context. + * + * @param context the context to be merged with default client context. + * @return the merged context. + */ + public Context mergeContext(Context context) { + return CoreUtils.mergeContexts(this.getContext(), context); + } + + /** + * Gets long running operation result. + * + * @param activationResponse the response of activation operation. + * @param httpPipeline the http pipeline. + * @param pollResultType type of poll result. + * @param finalResultType type of final result. + * @param context the context shared by all requests. + * @param type of poll result. + * @param type of final result. + * @return poller flux for poll result and final result. + */ + public PollerFlux, U> getLroResult(Mono>> activationResponse, + HttpPipeline httpPipeline, Type pollResultType, Type finalResultType, Context context) { + return PollerFactory.create(serializerAdapter, httpPipeline, pollResultType, finalResultType, + defaultPollInterval, activationResponse, context); + } + + /** + * Gets the final result, or an error, based on last async poll response. + * + * @param response the last async poll response. + * @param type of poll result. + * @param type of final result. + * @return the final result, or an error. + */ + public Mono getLroFinalResultOrError(AsyncPollResponse, U> response) { + if (response.getStatus() != LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { + String errorMessage; + ManagementError managementError = null; + HttpResponse errorResponse = null; + PollResult.Error lroError = response.getValue().getError(); + if (lroError != null) { + errorResponse = new HttpResponseImpl(lroError.getResponseStatusCode(), lroError.getResponseHeaders(), + lroError.getResponseBody()); + + errorMessage = response.getValue().getError().getMessage(); + String errorBody = response.getValue().getError().getResponseBody(); + if (errorBody != null) { + // try to deserialize error body to ManagementError + try { + managementError = this.getSerializerAdapter() + .deserialize(errorBody, ManagementError.class, SerializerEncoding.JSON); + if (managementError.getCode() == null || managementError.getMessage() == null) { + managementError = null; + } + } catch (IOException | RuntimeException ioe) { + LOGGER.logThrowableAsWarning(ioe); + } + } + } else { + // fallback to default error message + errorMessage = "Long running operation failed."; + } + if (managementError == null) { + // fallback to default ManagementError + managementError = new ManagementError(response.getStatus().toString(), errorMessage); + } + return Mono.error(new ManagementException(errorMessage, errorResponse, managementError)); + } else { + return response.getFinalResult(); + } + } + + private static final class HttpResponseImpl extends HttpResponse { + private final int statusCode; + + private final byte[] responseBody; + + private final HttpHeaders httpHeaders; + + HttpResponseImpl(int statusCode, HttpHeaders httpHeaders, String responseBody) { + super(null); + this.statusCode = statusCode; + this.httpHeaders = httpHeaders; + this.responseBody = responseBody == null ? null : responseBody.getBytes(StandardCharsets.UTF_8); + } + + public int getStatusCode() { + return statusCode; + } + + public String getHeaderValue(String s) { + return httpHeaders.getValue(HttpHeaderName.fromString(s)); + } + + public HttpHeaders getHeaders() { + return httpHeaders; + } + + public Flux getBody() { + return Flux.just(ByteBuffer.wrap(responseBody)); + } + + public Mono getBodyAsByteArray() { + return Mono.just(responseBody); + } + + public Mono getBodyAsString() { + return Mono.just(new String(responseBody, StandardCharsets.UTF_8)); + } + + public Mono getBodyAsString(Charset charset) { + return Mono.just(new String(responseBody, charset)); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(PineconeVectorDbMgmtClientImpl.class); +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/ResourceManagerUtils.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/ResourceManagerUtils.java new file mode 100644 index 000000000000..6ea513cfc54d --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/ResourceManagerUtils.java @@ -0,0 +1,195 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.implementation; + +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.util.CoreUtils; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import reactor.core.publisher.Flux; + +final class ResourceManagerUtils { + private ResourceManagerUtils() { + } + + static String getValueFromIdByName(String id, String name) { + if (id == null) { + return null; + } + Iterator itr = Arrays.stream(id.split("/")).iterator(); + while (itr.hasNext()) { + String part = itr.next(); + if (part != null && !part.trim().isEmpty()) { + if (part.equalsIgnoreCase(name)) { + if (itr.hasNext()) { + return itr.next(); + } else { + return null; + } + } + } + } + return null; + } + + static String getValueFromIdByParameterName(String id, String pathTemplate, String parameterName) { + if (id == null || pathTemplate == null) { + return null; + } + String parameterNameParentheses = "{" + parameterName + "}"; + List idSegmentsReverted = Arrays.asList(id.split("/")); + List pathSegments = Arrays.asList(pathTemplate.split("/")); + Collections.reverse(idSegmentsReverted); + Iterator idItrReverted = idSegmentsReverted.iterator(); + int pathIndex = pathSegments.size(); + while (idItrReverted.hasNext() && pathIndex > 0) { + String idSegment = idItrReverted.next(); + String pathSegment = pathSegments.get(--pathIndex); + if (!CoreUtils.isNullOrEmpty(idSegment) && !CoreUtils.isNullOrEmpty(pathSegment)) { + if (pathSegment.equalsIgnoreCase(parameterNameParentheses)) { + if (pathIndex == 0 || (pathIndex == 1 && pathSegments.get(0).isEmpty())) { + List segments = new ArrayList<>(); + segments.add(idSegment); + idItrReverted.forEachRemaining(segments::add); + Collections.reverse(segments); + if (!segments.isEmpty() && segments.get(0).isEmpty()) { + segments.remove(0); + } + return String.join("/", segments); + } else { + return idSegment; + } + } + } + } + return null; + } + + static PagedIterable mapPage(PagedIterable pageIterable, Function mapper) { + return new PagedIterableImpl<>(pageIterable, mapper); + } + + private static final class PagedIterableImpl extends PagedIterable { + + private final PagedIterable pagedIterable; + private final Function mapper; + private final Function, PagedResponse> pageMapper; + + private PagedIterableImpl(PagedIterable pagedIterable, Function mapper) { + super(PagedFlux.create(() -> (continuationToken, pageSize) -> Flux + .fromStream(pagedIterable.streamByPage().map(getPageMapper(mapper))))); + this.pagedIterable = pagedIterable; + this.mapper = mapper; + this.pageMapper = getPageMapper(mapper); + } + + private static Function, PagedResponse> getPageMapper(Function mapper) { + return page -> new PagedResponseBase(page.getRequest(), page.getStatusCode(), page.getHeaders(), + page.getElements().stream().map(mapper).collect(Collectors.toList()), page.getContinuationToken(), + null); + } + + @Override + public Stream stream() { + return pagedIterable.stream().map(mapper); + } + + @Override + public Stream> streamByPage() { + return pagedIterable.streamByPage().map(pageMapper); + } + + @Override + public Stream> streamByPage(String continuationToken) { + return pagedIterable.streamByPage(continuationToken).map(pageMapper); + } + + @Override + public Stream> streamByPage(int preferredPageSize) { + return pagedIterable.streamByPage(preferredPageSize).map(pageMapper); + } + + @Override + public Stream> streamByPage(String continuationToken, int preferredPageSize) { + return pagedIterable.streamByPage(continuationToken, preferredPageSize).map(pageMapper); + } + + @Override + public Iterator iterator() { + return new IteratorImpl<>(pagedIterable.iterator(), mapper); + } + + @Override + public Iterable> iterableByPage() { + return new IterableImpl<>(pagedIterable.iterableByPage(), pageMapper); + } + + @Override + public Iterable> iterableByPage(String continuationToken) { + return new IterableImpl<>(pagedIterable.iterableByPage(continuationToken), pageMapper); + } + + @Override + public Iterable> iterableByPage(int preferredPageSize) { + return new IterableImpl<>(pagedIterable.iterableByPage(preferredPageSize), pageMapper); + } + + @Override + public Iterable> iterableByPage(String continuationToken, int preferredPageSize) { + return new IterableImpl<>(pagedIterable.iterableByPage(continuationToken, preferredPageSize), pageMapper); + } + } + + private static final class IteratorImpl implements Iterator { + + private final Iterator iterator; + private final Function mapper; + + private IteratorImpl(Iterator iterator, Function mapper) { + this.iterator = iterator; + this.mapper = mapper; + } + + @Override + public boolean hasNext() { + return iterator.hasNext(); + } + + @Override + public S next() { + return mapper.apply(iterator.next()); + } + + @Override + public void remove() { + iterator.remove(); + } + } + + private static final class IterableImpl implements Iterable { + + private final Iterable iterable; + private final Function mapper; + + private IterableImpl(Iterable iterable, Function mapper) { + this.iterable = iterable; + this.mapper = mapper; + } + + @Override + public Iterator iterator() { + return new IteratorImpl<>(iterable.iterator(), mapper); + } + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/models/OperationListResult.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/models/OperationListResult.java new file mode 100644 index 000000000000..59cc51f6bea0 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/models/OperationListResult.java @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.implementation.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.pineconevectordb.fluent.models.OperationInner; +import java.io.IOException; +import java.util.List; + +/** + * A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + * results. + */ +@Immutable +public final class OperationListResult implements JsonSerializable { + /* + * The Operation items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of OperationListResult class. + */ + private OperationListResult() { + } + + /** + * Get the value property: The Operation items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property value in model OperationListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(OperationListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OperationListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OperationListResult 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 OperationListResult. + */ + public static OperationListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OperationListResult deserializedOperationListResult = new OperationListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value = reader.readArray(reader1 -> OperationInner.fromJson(reader1)); + deserializedOperationListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedOperationListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedOperationListResult; + }); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/models/OrganizationResourceListResult.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/models/OrganizationResourceListResult.java new file mode 100644 index 000000000000..bbed5bee5a1a --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/models/OrganizationResourceListResult.java @@ -0,0 +1,115 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.implementation.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.pineconevectordb.fluent.models.OrganizationResourceInner; +import java.io.IOException; +import java.util.List; + +/** + * The response of a OrganizationResource list operation. + */ +@Immutable +public final class OrganizationResourceListResult implements JsonSerializable { + /* + * The OrganizationResource items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of OrganizationResourceListResult class. + */ + private OrganizationResourceListResult() { + } + + /** + * Get the value property: The OrganizationResource items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property value in model OrganizationResourceListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(OrganizationResourceListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OrganizationResourceListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OrganizationResourceListResult 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 OrganizationResourceListResult. + */ + public static OrganizationResourceListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OrganizationResourceListResult deserializedOrganizationResourceListResult + = new OrganizationResourceListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> OrganizationResourceInner.fromJson(reader1)); + deserializedOrganizationResourceListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedOrganizationResourceListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedOrganizationResourceListResult; + }); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/package-info.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/package-info.java new file mode 100644 index 000000000000..96b80f0657a9 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/implementation/package-info.java @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +/** + * Package containing the implementations for PineconeVectorDb. + */ +package com.azure.resourcemanager.pineconevectordb.implementation; diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/ActionType.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/ActionType.java new file mode 100644 index 000000000000..2abf5e848f10 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/ActionType.java @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + */ +public final class ActionType extends ExpandableStringEnum { + /** + * Actions are for internal-only APIs. + */ + public static final ActionType INTERNAL = fromString("Internal"); + + /** + * Creates a new instance of ActionType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public ActionType() { + } + + /** + * Creates or finds a ActionType from its string representation. + * + * @param name a name to look for. + * @return the corresponding ActionType. + */ + public static ActionType fromString(String name) { + return fromString(name, ActionType.class); + } + + /** + * Gets known ActionType values. + * + * @return known ActionType values. + */ + public static Collection values() { + return values(ActionType.class); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/ManagedServiceIdentity.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/ManagedServiceIdentity.java new file mode 100644 index 000000000000..6974e414ccc1 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/ManagedServiceIdentity.java @@ -0,0 +1,176 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +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.Map; + +/** + * Managed service identity (system assigned and/or user assigned identities). + */ +@Fluent +public final class ManagedServiceIdentity implements JsonSerializable { + /* + * The service principal ID of the system assigned identity. This property will only be provided for a system + * assigned identity. + */ + private String principalId; + + /* + * The tenant ID of the system assigned identity. This property will only be provided for a system assigned + * identity. + */ + private String tenantId; + + /* + * The type of managed identity assigned to this resource. + */ + private ManagedServiceIdentityType type; + + /* + * The identities assigned to this resource by the user. + */ + private Map userAssignedIdentities; + + /** + * Creates an instance of ManagedServiceIdentity class. + */ + public ManagedServiceIdentity() { + } + + /** + * Get the principalId property: The service principal ID of the system assigned identity. This property will only + * be provided for a system assigned identity. + * + * @return the principalId value. + */ + public String principalId() { + return this.principalId; + } + + /** + * Get the tenantId property: The tenant ID of the system assigned identity. This property will only be provided for + * a system assigned identity. + * + * @return the tenantId value. + */ + public String tenantId() { + return this.tenantId; + } + + /** + * Get the type property: The type of managed identity assigned to this resource. + * + * @return the type value. + */ + public ManagedServiceIdentityType type() { + return this.type; + } + + /** + * Set the type property: The type of managed identity assigned to this resource. + * + * @param type the type value to set. + * @return the ManagedServiceIdentity object itself. + */ + public ManagedServiceIdentity withType(ManagedServiceIdentityType type) { + this.type = type; + return this; + } + + /** + * Get the userAssignedIdentities property: The identities assigned to this resource by the user. + * + * @return the userAssignedIdentities value. + */ + public Map userAssignedIdentities() { + return this.userAssignedIdentities; + } + + /** + * Set the userAssignedIdentities property: The identities assigned to this resource by the user. + * + * @param userAssignedIdentities the userAssignedIdentities value to set. + * @return the ManagedServiceIdentity object itself. + */ + public ManagedServiceIdentity withUserAssignedIdentities(Map userAssignedIdentities) { + this.userAssignedIdentities = userAssignedIdentities; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (type() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property type in model ManagedServiceIdentity")); + } + if (userAssignedIdentities() != null) { + userAssignedIdentities().values().forEach(e -> { + if (e != null) { + e.validate(); + } + }); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(ManagedServiceIdentity.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + jsonWriter.writeMapField("userAssignedIdentities", this.userAssignedIdentities, + (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ManagedServiceIdentity from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ManagedServiceIdentity 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 ManagedServiceIdentity. + */ + public static ManagedServiceIdentity fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ManagedServiceIdentity deserializedManagedServiceIdentity = new ManagedServiceIdentity(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("type".equals(fieldName)) { + deserializedManagedServiceIdentity.type = ManagedServiceIdentityType.fromString(reader.getString()); + } else if ("principalId".equals(fieldName)) { + deserializedManagedServiceIdentity.principalId = reader.getString(); + } else if ("tenantId".equals(fieldName)) { + deserializedManagedServiceIdentity.tenantId = reader.getString(); + } else if ("userAssignedIdentities".equals(fieldName)) { + Map userAssignedIdentities + = reader.readMap(reader1 -> UserAssignedIdentity.fromJson(reader1)); + deserializedManagedServiceIdentity.userAssignedIdentities = userAssignedIdentities; + } else { + reader.skipChildren(); + } + } + + return deserializedManagedServiceIdentity; + }); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/ManagedServiceIdentityType.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/ManagedServiceIdentityType.java new file mode 100644 index 000000000000..f8d3169ab015 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/ManagedServiceIdentityType.java @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). + */ +public final class ManagedServiceIdentityType extends ExpandableStringEnum { + /** + * No managed identity. + */ + public static final ManagedServiceIdentityType NONE = fromString("None"); + + /** + * System assigned managed identity. + */ + public static final ManagedServiceIdentityType SYSTEM_ASSIGNED = fromString("SystemAssigned"); + + /** + * User assigned managed identity. + */ + public static final ManagedServiceIdentityType USER_ASSIGNED = fromString("UserAssigned"); + + /** + * System and user assigned managed identity. + */ + public static final ManagedServiceIdentityType SYSTEM_ASSIGNED_USER_ASSIGNED + = fromString("SystemAssigned,UserAssigned"); + + /** + * Creates a new instance of ManagedServiceIdentityType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public ManagedServiceIdentityType() { + } + + /** + * Creates or finds a ManagedServiceIdentityType from its string representation. + * + * @param name a name to look for. + * @return the corresponding ManagedServiceIdentityType. + */ + public static ManagedServiceIdentityType fromString(String name) { + return fromString(name, ManagedServiceIdentityType.class); + } + + /** + * Gets known ManagedServiceIdentityType values. + * + * @return known ManagedServiceIdentityType values. + */ + public static Collection values() { + return values(ManagedServiceIdentityType.class); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/MarketplaceDetails.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/MarketplaceDetails.java new file mode 100644 index 000000000000..ac286465bfb6 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/MarketplaceDetails.java @@ -0,0 +1,154 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Marketplace details for an organization. + */ +@Fluent +public final class MarketplaceDetails implements JsonSerializable { + /* + * Azure subscription id for the the marketplace offer is purchased from + */ + private String subscriptionId; + + /* + * Marketplace subscription status + */ + private MarketplaceSubscriptionStatus subscriptionStatus; + + /* + * Offer details for the marketplace that is selected by the user + */ + private OfferDetails offerDetails; + + /** + * Creates an instance of MarketplaceDetails class. + */ + public MarketplaceDetails() { + } + + /** + * Get the subscriptionId property: Azure subscription id for the the marketplace offer is purchased from. + * + * @return the subscriptionId value. + */ + public String subscriptionId() { + return this.subscriptionId; + } + + /** + * Set the subscriptionId property: Azure subscription id for the the marketplace offer is purchased from. + * + * @param subscriptionId the subscriptionId value to set. + * @return the MarketplaceDetails object itself. + */ + public MarketplaceDetails withSubscriptionId(String subscriptionId) { + this.subscriptionId = subscriptionId; + return this; + } + + /** + * Get the subscriptionStatus property: Marketplace subscription status. + * + * @return the subscriptionStatus value. + */ + public MarketplaceSubscriptionStatus subscriptionStatus() { + return this.subscriptionStatus; + } + + /** + * Get the offerDetails property: Offer details for the marketplace that is selected by the user. + * + * @return the offerDetails value. + */ + public OfferDetails offerDetails() { + return this.offerDetails; + } + + /** + * Set the offerDetails property: Offer details for the marketplace that is selected by the user. + * + * @param offerDetails the offerDetails value to set. + * @return the MarketplaceDetails object itself. + */ + public MarketplaceDetails withOfferDetails(OfferDetails offerDetails) { + this.offerDetails = offerDetails; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (subscriptionId() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property subscriptionId in model MarketplaceDetails")); + } + if (offerDetails() == null) { + throw LOGGER.atError() + .log( + new IllegalArgumentException("Missing required property offerDetails in model MarketplaceDetails")); + } else { + offerDetails().validate(); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(MarketplaceDetails.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("subscriptionId", this.subscriptionId); + jsonWriter.writeJsonField("offerDetails", this.offerDetails); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of MarketplaceDetails from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of MarketplaceDetails 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 MarketplaceDetails. + */ + public static MarketplaceDetails fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + MarketplaceDetails deserializedMarketplaceDetails = new MarketplaceDetails(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("subscriptionId".equals(fieldName)) { + deserializedMarketplaceDetails.subscriptionId = reader.getString(); + } else if ("offerDetails".equals(fieldName)) { + deserializedMarketplaceDetails.offerDetails = OfferDetails.fromJson(reader); + } else if ("subscriptionStatus".equals(fieldName)) { + deserializedMarketplaceDetails.subscriptionStatus + = MarketplaceSubscriptionStatus.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedMarketplaceDetails; + }); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/MarketplaceSubscriptionStatus.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/MarketplaceSubscriptionStatus.java new file mode 100644 index 000000000000..47315186a7ff --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/MarketplaceSubscriptionStatus.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Marketplace subscription status of a resource. + */ +public final class MarketplaceSubscriptionStatus extends ExpandableStringEnum { + /** + * Purchased but not yet activated. + */ + public static final MarketplaceSubscriptionStatus PENDING_FULFILLMENT_START = fromString("PendingFulfillmentStart"); + + /** + * Marketplace subscription is activated. + */ + public static final MarketplaceSubscriptionStatus SUBSCRIBED = fromString("Subscribed"); + + /** + * This state indicates that a customer's payment for the Marketplace service was not received. + */ + public static final MarketplaceSubscriptionStatus SUSPENDED = fromString("Suspended"); + + /** + * Customer has cancelled the subscription. + */ + public static final MarketplaceSubscriptionStatus UNSUBSCRIBED = fromString("Unsubscribed"); + + /** + * Creates a new instance of MarketplaceSubscriptionStatus value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public MarketplaceSubscriptionStatus() { + } + + /** + * Creates or finds a MarketplaceSubscriptionStatus from its string representation. + * + * @param name a name to look for. + * @return the corresponding MarketplaceSubscriptionStatus. + */ + public static MarketplaceSubscriptionStatus fromString(String name) { + return fromString(name, MarketplaceSubscriptionStatus.class); + } + + /** + * Gets known MarketplaceSubscriptionStatus values. + * + * @return known MarketplaceSubscriptionStatus values. + */ + public static Collection values() { + return values(MarketplaceSubscriptionStatus.class); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/OfferDetails.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/OfferDetails.java new file mode 100644 index 000000000000..50fe0382605f --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/OfferDetails.java @@ -0,0 +1,249 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Offer details for the marketplace that is selected by the user. + */ +@Fluent +public final class OfferDetails implements JsonSerializable { + /* + * Publisher Id for the marketplace offer + */ + private String publisherId; + + /* + * Offer Id for the marketplace offer + */ + private String offerId; + + /* + * Plan Id for the marketplace offer + */ + private String planId; + + /* + * Plan Name for the marketplace offer + */ + private String planName; + + /* + * Plan Display Name for the marketplace offer + */ + private String termUnit; + + /* + * Plan Display Name for the marketplace offer + */ + private String termId; + + /** + * Creates an instance of OfferDetails class. + */ + public OfferDetails() { + } + + /** + * Get the publisherId property: Publisher Id for the marketplace offer. + * + * @return the publisherId value. + */ + public String publisherId() { + return this.publisherId; + } + + /** + * Set the publisherId property: Publisher Id for the marketplace offer. + * + * @param publisherId the publisherId value to set. + * @return the OfferDetails object itself. + */ + public OfferDetails withPublisherId(String publisherId) { + this.publisherId = publisherId; + return this; + } + + /** + * Get the offerId property: Offer Id for the marketplace offer. + * + * @return the offerId value. + */ + public String offerId() { + return this.offerId; + } + + /** + * Set the offerId property: Offer Id for the marketplace offer. + * + * @param offerId the offerId value to set. + * @return the OfferDetails object itself. + */ + public OfferDetails withOfferId(String offerId) { + this.offerId = offerId; + return this; + } + + /** + * Get the planId property: Plan Id for the marketplace offer. + * + * @return the planId value. + */ + public String planId() { + return this.planId; + } + + /** + * Set the planId property: Plan Id for the marketplace offer. + * + * @param planId the planId value to set. + * @return the OfferDetails object itself. + */ + public OfferDetails withPlanId(String planId) { + this.planId = planId; + return this; + } + + /** + * Get the planName property: Plan Name for the marketplace offer. + * + * @return the planName value. + */ + public String planName() { + return this.planName; + } + + /** + * Set the planName property: Plan Name for the marketplace offer. + * + * @param planName the planName value to set. + * @return the OfferDetails object itself. + */ + public OfferDetails withPlanName(String planName) { + this.planName = planName; + return this; + } + + /** + * Get the termUnit property: Plan Display Name for the marketplace offer. + * + * @return the termUnit value. + */ + public String termUnit() { + return this.termUnit; + } + + /** + * Set the termUnit property: Plan Display Name for the marketplace offer. + * + * @param termUnit the termUnit value to set. + * @return the OfferDetails object itself. + */ + public OfferDetails withTermUnit(String termUnit) { + this.termUnit = termUnit; + return this; + } + + /** + * Get the termId property: Plan Display Name for the marketplace offer. + * + * @return the termId value. + */ + public String termId() { + return this.termId; + } + + /** + * Set the termId property: Plan Display Name for the marketplace offer. + * + * @param termId the termId value to set. + * @return the OfferDetails object itself. + */ + public OfferDetails withTermId(String termId) { + this.termId = termId; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (publisherId() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property publisherId in model OfferDetails")); + } + if (offerId() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property offerId in model OfferDetails")); + } + if (planId() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property planId in model OfferDetails")); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(OfferDetails.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("publisherId", this.publisherId); + jsonWriter.writeStringField("offerId", this.offerId); + jsonWriter.writeStringField("planId", this.planId); + jsonWriter.writeStringField("planName", this.planName); + jsonWriter.writeStringField("termUnit", this.termUnit); + jsonWriter.writeStringField("termId", this.termId); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OfferDetails from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OfferDetails 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 OfferDetails. + */ + public static OfferDetails fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OfferDetails deserializedOfferDetails = new OfferDetails(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("publisherId".equals(fieldName)) { + deserializedOfferDetails.publisherId = reader.getString(); + } else if ("offerId".equals(fieldName)) { + deserializedOfferDetails.offerId = reader.getString(); + } else if ("planId".equals(fieldName)) { + deserializedOfferDetails.planId = reader.getString(); + } else if ("planName".equals(fieldName)) { + deserializedOfferDetails.planName = reader.getString(); + } else if ("termUnit".equals(fieldName)) { + deserializedOfferDetails.termUnit = reader.getString(); + } else if ("termId".equals(fieldName)) { + deserializedOfferDetails.termId = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedOfferDetails; + }); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/Operation.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/Operation.java new file mode 100644 index 000000000000..7f2701fd77cd --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/Operation.java @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.models; + +import com.azure.resourcemanager.pineconevectordb.fluent.models.OperationInner; + +/** + * An immutable client-side representation of Operation. + */ +public interface Operation { + /** + * Gets the name property: The name of the operation, as per Resource-Based Access Control (RBAC). Examples: + * "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action". + * + * @return the name value. + */ + String name(); + + /** + * Gets the isDataAction property: Whether the operation applies to data-plane. This is "true" for data-plane + * operations and "false" for Azure Resource Manager/control-plane operations. + * + * @return the isDataAction value. + */ + Boolean isDataAction(); + + /** + * Gets the display property: Localized display information for this particular operation. + * + * @return the display value. + */ + OperationDisplay display(); + + /** + * Gets the origin property: The intended executor of the operation; as in Resource Based Access Control (RBAC) and + * audit logs UX. Default value is "user,system". + * + * @return the origin value. + */ + Origin origin(); + + /** + * Gets the actionType property: Extensible enum. Indicates the action type. "Internal" refers to actions that are + * for internal only APIs. + * + * @return the actionType value. + */ + ActionType actionType(); + + /** + * Gets the inner com.azure.resourcemanager.pineconevectordb.fluent.models.OperationInner object. + * + * @return the inner object. + */ + OperationInner innerModel(); +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/OperationDisplay.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/OperationDisplay.java new file mode 100644 index 000000000000..5bdc51eee46f --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/OperationDisplay.java @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.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; + +/** + * Localized display information for and operation. + */ +@Immutable +public final class OperationDisplay implements JsonSerializable { + /* + * The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or + * "Microsoft Compute". + */ + private String provider; + + /* + * The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or + * "Job Schedule Collections". + */ + private String resource; + + /* + * The concise, localized friendly name for the operation; suitable for dropdowns. E.g. + * "Create or Update Virtual Machine", "Restart Virtual Machine". + */ + private String operation; + + /* + * The short, localized friendly description of the operation; suitable for tool tips and detailed views. + */ + private String description; + + /** + * Creates an instance of OperationDisplay class. + */ + private OperationDisplay() { + } + + /** + * Get the provider property: The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring + * Insights" or "Microsoft Compute". + * + * @return the provider value. + */ + public String provider() { + return this.provider; + } + + /** + * Get the resource property: The localized friendly name of the resource type related to this operation. E.g. + * "Virtual Machines" or "Job Schedule Collections". + * + * @return the resource value. + */ + public String resource() { + return this.resource; + } + + /** + * Get the operation property: The concise, localized friendly name for the operation; suitable for dropdowns. E.g. + * "Create or Update Virtual Machine", "Restart Virtual Machine". + * + * @return the operation value. + */ + public String operation() { + return this.operation; + } + + /** + * Get the description property: The short, localized friendly description of the operation; suitable for tool tips + * and detailed views. + * + * @return the description value. + */ + public String description() { + return this.description; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OperationDisplay from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OperationDisplay 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 OperationDisplay. + */ + public static OperationDisplay fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OperationDisplay deserializedOperationDisplay = new OperationDisplay(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("provider".equals(fieldName)) { + deserializedOperationDisplay.provider = reader.getString(); + } else if ("resource".equals(fieldName)) { + deserializedOperationDisplay.resource = reader.getString(); + } else if ("operation".equals(fieldName)) { + deserializedOperationDisplay.operation = reader.getString(); + } else if ("description".equals(fieldName)) { + deserializedOperationDisplay.description = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedOperationDisplay; + }); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/Operations.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/Operations.java new file mode 100644 index 000000000000..0fa6604ced52 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/Operations.java @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.Context; + +/** + * Resource collection API of Operations. + */ +public interface Operations { + /** + * List the operations for the provider. + * + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedIterable}. + */ + PagedIterable list(); + + /** + * List the operations for the provider. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of REST API operations supported by an Azure Resource Provider as paginated response with + * {@link PagedIterable}. + */ + PagedIterable list(Context context); +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/OrganizationProperties.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/OrganizationProperties.java new file mode 100644 index 000000000000..c2de621e4667 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/OrganizationProperties.java @@ -0,0 +1,218 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Properties specific to Organization. + */ +@Fluent +public final class OrganizationProperties implements JsonSerializable { + /* + * Marketplace details of the resource. + */ + private MarketplaceDetails marketplace; + + /* + * Details of the user. + */ + private UserDetails user; + + /* + * Provisioning state of the resource. + */ + private ResourceProvisioningState provisioningState; + + /* + * partner properties + */ + private PartnerProperties partnerProperties; + + /* + * Single sign-on properties + */ + private SingleSignOnPropertiesV2 singleSignOnProperties; + + /** + * Creates an instance of OrganizationProperties class. + */ + public OrganizationProperties() { + } + + /** + * Get the marketplace property: Marketplace details of the resource. + * + * @return the marketplace value. + */ + public MarketplaceDetails marketplace() { + return this.marketplace; + } + + /** + * Set the marketplace property: Marketplace details of the resource. + * + * @param marketplace the marketplace value to set. + * @return the OrganizationProperties object itself. + */ + public OrganizationProperties withMarketplace(MarketplaceDetails marketplace) { + this.marketplace = marketplace; + return this; + } + + /** + * Get the user property: Details of the user. + * + * @return the user value. + */ + public UserDetails user() { + return this.user; + } + + /** + * Set the user property: Details of the user. + * + * @param user the user value to set. + * @return the OrganizationProperties object itself. + */ + public OrganizationProperties withUser(UserDetails user) { + this.user = user; + return this; + } + + /** + * Get the provisioningState property: Provisioning state of the resource. + * + * @return the provisioningState value. + */ + public ResourceProvisioningState provisioningState() { + return this.provisioningState; + } + + /** + * Get the partnerProperties property: partner properties. + * + * @return the partnerProperties value. + */ + public PartnerProperties partnerProperties() { + return this.partnerProperties; + } + + /** + * Set the partnerProperties property: partner properties. + * + * @param partnerProperties the partnerProperties value to set. + * @return the OrganizationProperties object itself. + */ + public OrganizationProperties withPartnerProperties(PartnerProperties partnerProperties) { + this.partnerProperties = partnerProperties; + return this; + } + + /** + * Get the singleSignOnProperties property: Single sign-on properties. + * + * @return the singleSignOnProperties value. + */ + public SingleSignOnPropertiesV2 singleSignOnProperties() { + return this.singleSignOnProperties; + } + + /** + * Set the singleSignOnProperties property: Single sign-on properties. + * + * @param singleSignOnProperties the singleSignOnProperties value to set. + * @return the OrganizationProperties object itself. + */ + public OrganizationProperties withSingleSignOnProperties(SingleSignOnPropertiesV2 singleSignOnProperties) { + this.singleSignOnProperties = singleSignOnProperties; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (marketplace() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException( + "Missing required property marketplace in model OrganizationProperties")); + } else { + marketplace().validate(); + } + if (user() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property user in model OrganizationProperties")); + } else { + user().validate(); + } + if (partnerProperties() != null) { + partnerProperties().validate(); + } + if (singleSignOnProperties() != null) { + singleSignOnProperties().validate(); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(OrganizationProperties.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("marketplace", this.marketplace); + jsonWriter.writeJsonField("user", this.user); + jsonWriter.writeJsonField("partnerProperties", this.partnerProperties); + jsonWriter.writeJsonField("singleSignOnProperties", this.singleSignOnProperties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OrganizationProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OrganizationProperties 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 OrganizationProperties. + */ + public static OrganizationProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OrganizationProperties deserializedOrganizationProperties = new OrganizationProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("marketplace".equals(fieldName)) { + deserializedOrganizationProperties.marketplace = MarketplaceDetails.fromJson(reader); + } else if ("user".equals(fieldName)) { + deserializedOrganizationProperties.user = UserDetails.fromJson(reader); + } else if ("provisioningState".equals(fieldName)) { + deserializedOrganizationProperties.provisioningState + = ResourceProvisioningState.fromString(reader.getString()); + } else if ("partnerProperties".equals(fieldName)) { + deserializedOrganizationProperties.partnerProperties = PartnerProperties.fromJson(reader); + } else if ("singleSignOnProperties".equals(fieldName)) { + deserializedOrganizationProperties.singleSignOnProperties + = SingleSignOnPropertiesV2.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedOrganizationProperties; + }); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/OrganizationResource.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/OrganizationResource.java new file mode 100644 index 000000000000..12f9fa361873 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/OrganizationResource.java @@ -0,0 +1,286 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.models; + +import com.azure.core.management.Region; +import com.azure.core.management.SystemData; +import com.azure.core.util.Context; +import com.azure.resourcemanager.pineconevectordb.fluent.models.OrganizationResourceInner; +import java.util.Map; + +/** + * An immutable client-side representation of OrganizationResource. + */ +public interface OrganizationResource { + /** + * Gets the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + String id(); + + /** + * Gets the name property: The name of the resource. + * + * @return the name value. + */ + String name(); + + /** + * Gets the type property: The type of the resource. + * + * @return the type value. + */ + String type(); + + /** + * Gets the location property: The geo-location where the resource lives. + * + * @return the location value. + */ + String location(); + + /** + * Gets the tags property: Resource tags. + * + * @return the tags value. + */ + Map tags(); + + /** + * Gets the properties property: The resource-specific properties for this resource. + * + * @return the properties value. + */ + OrganizationProperties properties(); + + /** + * Gets the identity property: The managed service identities assigned to this resource. + * + * @return the identity value. + */ + ManagedServiceIdentity identity(); + + /** + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + SystemData systemData(); + + /** + * Gets the region of the resource. + * + * @return the region of the resource. + */ + Region region(); + + /** + * Gets the name of the resource region. + * + * @return the name of the resource region. + */ + String regionName(); + + /** + * Gets the name of the resource group. + * + * @return the name of the resource group. + */ + String resourceGroupName(); + + /** + * Gets the inner com.azure.resourcemanager.pineconevectordb.fluent.models.OrganizationResourceInner object. + * + * @return the inner object. + */ + OrganizationResourceInner innerModel(); + + /** + * The entirety of the OrganizationResource definition. + */ + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithLocation, + DefinitionStages.WithResourceGroup, DefinitionStages.WithCreate { + } + + /** + * The OrganizationResource definition stages. + */ + interface DefinitionStages { + /** + * The first stage of the OrganizationResource definition. + */ + interface Blank extends WithLocation { + } + + /** + * The stage of the OrganizationResource definition allowing to specify location. + */ + interface WithLocation { + /** + * Specifies the region for the resource. + * + * @param location The geo-location where the resource lives. + * @return the next definition stage. + */ + WithResourceGroup withRegion(Region location); + + /** + * Specifies the region for the resource. + * + * @param location The geo-location where the resource lives. + * @return the next definition stage. + */ + WithResourceGroup withRegion(String location); + } + + /** + * The stage of the OrganizationResource definition allowing to specify parent resource. + */ + interface WithResourceGroup { + /** + * Specifies resourceGroupName. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @return the next definition stage. + */ + WithCreate withExistingResourceGroup(String resourceGroupName); + } + + /** + * The stage of the OrganizationResource definition which contains all the minimum required properties for the + * resource to be created, but also allows for any other optional properties to be specified. + */ + interface WithCreate + extends DefinitionStages.WithTags, DefinitionStages.WithProperties, DefinitionStages.WithIdentity { + /** + * Executes the create request. + * + * @return the created resource. + */ + OrganizationResource create(); + + /** + * Executes the create request. + * + * @param context The context to associate with this operation. + * @return the created resource. + */ + OrganizationResource create(Context context); + } + + /** + * The stage of the OrganizationResource definition allowing to specify tags. + */ + interface WithTags { + /** + * Specifies the tags property: Resource tags.. + * + * @param tags Resource tags. + * @return the next definition stage. + */ + WithCreate withTags(Map tags); + } + + /** + * The stage of the OrganizationResource definition allowing to specify properties. + */ + interface WithProperties { + /** + * Specifies the properties property: The resource-specific properties for this resource.. + * + * @param properties The resource-specific properties for this resource. + * @return the next definition stage. + */ + WithCreate withProperties(OrganizationProperties properties); + } + + /** + * The stage of the OrganizationResource definition allowing to specify identity. + */ + interface WithIdentity { + /** + * Specifies the identity property: The managed service identities assigned to this resource.. + * + * @param identity The managed service identities assigned to this resource. + * @return the next definition stage. + */ + WithCreate withIdentity(ManagedServiceIdentity identity); + } + } + + /** + * Begins update for the OrganizationResource resource. + * + * @return the stage of resource update. + */ + OrganizationResource.Update update(); + + /** + * The template for OrganizationResource update. + */ + interface Update extends UpdateStages.WithTags, UpdateStages.WithIdentity { + /** + * Executes the update request. + * + * @return the updated resource. + */ + OrganizationResource apply(); + + /** + * Executes the update request. + * + * @param context The context to associate with this operation. + * @return the updated resource. + */ + OrganizationResource apply(Context context); + } + + /** + * The OrganizationResource update stages. + */ + interface UpdateStages { + /** + * The stage of the OrganizationResource update allowing to specify tags. + */ + interface WithTags { + /** + * Specifies the tags property: Resource tags.. + * + * @param tags Resource tags. + * @return the next definition stage. + */ + Update withTags(Map tags); + } + + /** + * The stage of the OrganizationResource update allowing to specify identity. + */ + interface WithIdentity { + /** + * Specifies the identity property: The managed service identities assigned to this resource.. + * + * @param identity The managed service identities assigned to this resource. + * @return the next definition stage. + */ + Update withIdentity(ManagedServiceIdentity identity); + } + } + + /** + * Refreshes the resource to sync with Azure. + * + * @return the refreshed resource. + */ + OrganizationResource refresh(); + + /** + * Refreshes the resource to sync with Azure. + * + * @param context The context to associate with this operation. + * @return the refreshed resource. + */ + OrganizationResource refresh(Context context); +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/OrganizationResourceUpdate.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/OrganizationResourceUpdate.java new file mode 100644 index 000000000000..ea88c696ff50 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/OrganizationResourceUpdate.java @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.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.Map; + +/** + * The type used for update operations of the Organization Resource. + */ +@Fluent +public final class OrganizationResourceUpdate implements JsonSerializable { + /* + * Resource tags. + */ + private Map tags; + + /* + * The managed service identities assigned to this resource. + */ + private ManagedServiceIdentity identity; + + /** + * Creates an instance of OrganizationResourceUpdate class. + */ + public OrganizationResourceUpdate() { + } + + /** + * Get the tags property: Resource tags. + * + * @return the tags value. + */ + public Map tags() { + return this.tags; + } + + /** + * Set the tags property: Resource tags. + * + * @param tags the tags value to set. + * @return the OrganizationResourceUpdate object itself. + */ + public OrganizationResourceUpdate withTags(Map tags) { + this.tags = tags; + return this; + } + + /** + * Get the identity property: The managed service identities assigned to this resource. + * + * @return the identity value. + */ + public ManagedServiceIdentity identity() { + return this.identity; + } + + /** + * Set the identity property: The managed service identities assigned to this resource. + * + * @param identity the identity value to set. + * @return the OrganizationResourceUpdate object itself. + */ + public OrganizationResourceUpdate withIdentity(ManagedServiceIdentity identity) { + this.identity = identity; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (identity() != null) { + identity().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); + jsonWriter.writeJsonField("identity", this.identity); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OrganizationResourceUpdate from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OrganizationResourceUpdate 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 OrganizationResourceUpdate. + */ + public static OrganizationResourceUpdate fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OrganizationResourceUpdate deserializedOrganizationResourceUpdate = new OrganizationResourceUpdate(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("tags".equals(fieldName)) { + Map tags = reader.readMap(reader1 -> reader1.getString()); + deserializedOrganizationResourceUpdate.tags = tags; + } else if ("identity".equals(fieldName)) { + deserializedOrganizationResourceUpdate.identity = ManagedServiceIdentity.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedOrganizationResourceUpdate; + }); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/Organizations.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/Organizations.java new file mode 100644 index 000000000000..0933a0bbea77 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/Organizations.java @@ -0,0 +1,158 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.models; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +/** + * Resource collection API of Organizations. + */ +public interface Organizations { + /** + * Get a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a OrganizationResource along with {@link Response}. + */ + Response getByResourceGroupWithResponse(String resourceGroupName, String organizationname, + Context context); + + /** + * Get a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a OrganizationResource. + */ + OrganizationResource getByResourceGroup(String resourceGroupName, String organizationname); + + /** + * Delete a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteByResourceGroup(String resourceGroupName, String organizationname); + + /** + * Delete a OrganizationResource. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param organizationname Name of the Organization resource. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void delete(String resourceGroupName, String organizationname, Context context); + + /** + * List OrganizationResource resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a OrganizationResource list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByResourceGroup(String resourceGroupName); + + /** + * List OrganizationResource resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a OrganizationResource list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable listByResourceGroup(String resourceGroupName, Context context); + + /** + * List OrganizationResource resources by subscription ID. + * + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a OrganizationResource list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable list(); + + /** + * List OrganizationResource resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a OrganizationResource list operation as paginated response with {@link PagedIterable}. + */ + PagedIterable list(Context context); + + /** + * Get a OrganizationResource. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a OrganizationResource along with {@link Response}. + */ + OrganizationResource getById(String id); + + /** + * Get a OrganizationResource. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a OrganizationResource along with {@link Response}. + */ + Response getByIdWithResponse(String id, Context context); + + /** + * Delete a OrganizationResource. + * + * @param id the resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteById(String id); + + /** + * Delete a OrganizationResource. + * + * @param id the resource ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + void deleteByIdWithResponse(String id, Context context); + + /** + * Begins definition for a new OrganizationResource resource. + * + * @param name resource name. + * @return the first stage of the new OrganizationResource definition. + */ + OrganizationResource.DefinitionStages.Blank define(String name); +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/Origin.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/Origin.java new file mode 100644 index 000000000000..51676cf402a9 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/Origin.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value + * is "user,system". + */ +public final class Origin extends ExpandableStringEnum { + /** + * Indicates the operation is initiated by a user. + */ + public static final Origin USER = fromString("user"); + + /** + * Indicates the operation is initiated by a system. + */ + public static final Origin SYSTEM = fromString("system"); + + /** + * Indicates the operation is initiated by a user or system. + */ + public static final Origin USER_SYSTEM = fromString("user,system"); + + /** + * Creates a new instance of Origin value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public Origin() { + } + + /** + * Creates or finds a Origin from its string representation. + * + * @param name a name to look for. + * @return the corresponding Origin. + */ + public static Origin fromString(String name) { + return fromString(name, Origin.class); + } + + /** + * Gets known Origin values. + * + * @return known Origin values. + */ + public static Collection values() { + return values(Origin.class); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/PartnerProperties.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/PartnerProperties.java new file mode 100644 index 000000000000..d51a78823a59 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/PartnerProperties.java @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Partner's specific Properties. + */ +@Fluent +public final class PartnerProperties implements JsonSerializable { + /* + * Pinecone Organization Name + */ + private String displayName; + + /** + * Creates an instance of PartnerProperties class. + */ + public PartnerProperties() { + } + + /** + * Get the displayName property: Pinecone Organization Name. + * + * @return the displayName value. + */ + public String displayName() { + return this.displayName; + } + + /** + * Set the displayName property: Pinecone Organization Name. + * + * @param displayName the displayName value to set. + * @return the PartnerProperties object itself. + */ + public PartnerProperties withDisplayName(String displayName) { + this.displayName = displayName; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (displayName() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property displayName in model PartnerProperties")); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(PartnerProperties.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("displayName", this.displayName); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of PartnerProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of PartnerProperties 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 PartnerProperties. + */ + public static PartnerProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + PartnerProperties deserializedPartnerProperties = new PartnerProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("displayName".equals(fieldName)) { + deserializedPartnerProperties.displayName = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedPartnerProperties; + }); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/ResourceProvisioningState.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/ResourceProvisioningState.java new file mode 100644 index 000000000000..986aedbcaed5 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/ResourceProvisioningState.java @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The provisioning state of a resource type. + */ +public final class ResourceProvisioningState extends ExpandableStringEnum { + /** + * Resource has been created. + */ + public static final ResourceProvisioningState SUCCEEDED = fromString("Succeeded"); + + /** + * Resource creation failed. + */ + public static final ResourceProvisioningState FAILED = fromString("Failed"); + + /** + * Resource creation was canceled. + */ + public static final ResourceProvisioningState CANCELED = fromString("Canceled"); + + /** + * Creates a new instance of ResourceProvisioningState value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public ResourceProvisioningState() { + } + + /** + * Creates or finds a ResourceProvisioningState from its string representation. + * + * @param name a name to look for. + * @return the corresponding ResourceProvisioningState. + */ + public static ResourceProvisioningState fromString(String name) { + return fromString(name, ResourceProvisioningState.class); + } + + /** + * Gets known ResourceProvisioningState values. + * + * @return known ResourceProvisioningState values. + */ + public static Collection values() { + return values(ResourceProvisioningState.class); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/SingleSignOnPropertiesV2.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/SingleSignOnPropertiesV2.java new file mode 100644 index 000000000000..7f158f7cf799 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/SingleSignOnPropertiesV2.java @@ -0,0 +1,215 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +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; + +/** + * Properties specific to Single Sign On Resource. + */ +@Fluent +public final class SingleSignOnPropertiesV2 implements JsonSerializable { + /* + * Type of Single Sign-On mechanism being used + */ + private SingleSignOnType type; + + /* + * State of the Single Sign On for the resource + */ + private SingleSignOnStates state; + + /* + * AAD enterprise application Id used to setup SSO + */ + private String enterpriseAppId; + + /* + * URL for SSO to be used by the partner to redirect the user to their system + */ + private String url; + + /* + * List of AAD domains fetched from Microsoft Graph for user. + */ + private List aadDomains; + + /** + * Creates an instance of SingleSignOnPropertiesV2 class. + */ + public SingleSignOnPropertiesV2() { + } + + /** + * Get the type property: Type of Single Sign-On mechanism being used. + * + * @return the type value. + */ + public SingleSignOnType type() { + return this.type; + } + + /** + * Set the type property: Type of Single Sign-On mechanism being used. + * + * @param type the type value to set. + * @return the SingleSignOnPropertiesV2 object itself. + */ + public SingleSignOnPropertiesV2 withType(SingleSignOnType type) { + this.type = type; + return this; + } + + /** + * Get the state property: State of the Single Sign On for the resource. + * + * @return the state value. + */ + public SingleSignOnStates state() { + return this.state; + } + + /** + * Set the state property: State of the Single Sign On for the resource. + * + * @param state the state value to set. + * @return the SingleSignOnPropertiesV2 object itself. + */ + public SingleSignOnPropertiesV2 withState(SingleSignOnStates state) { + this.state = state; + return this; + } + + /** + * Get the enterpriseAppId property: AAD enterprise application Id used to setup SSO. + * + * @return the enterpriseAppId value. + */ + public String enterpriseAppId() { + return this.enterpriseAppId; + } + + /** + * Set the enterpriseAppId property: AAD enterprise application Id used to setup SSO. + * + * @param enterpriseAppId the enterpriseAppId value to set. + * @return the SingleSignOnPropertiesV2 object itself. + */ + public SingleSignOnPropertiesV2 withEnterpriseAppId(String enterpriseAppId) { + this.enterpriseAppId = enterpriseAppId; + return this; + } + + /** + * Get the url property: URL for SSO to be used by the partner to redirect the user to their system. + * + * @return the url value. + */ + public String url() { + return this.url; + } + + /** + * Set the url property: URL for SSO to be used by the partner to redirect the user to their system. + * + * @param url the url value to set. + * @return the SingleSignOnPropertiesV2 object itself. + */ + public SingleSignOnPropertiesV2 withUrl(String url) { + this.url = url; + return this; + } + + /** + * Get the aadDomains property: List of AAD domains fetched from Microsoft Graph for user. + * + * @return the aadDomains value. + */ + public List aadDomains() { + return this.aadDomains; + } + + /** + * Set the aadDomains property: List of AAD domains fetched from Microsoft Graph for user. + * + * @param aadDomains the aadDomains value to set. + * @return the SingleSignOnPropertiesV2 object itself. + */ + public SingleSignOnPropertiesV2 withAadDomains(List aadDomains) { + this.aadDomains = aadDomains; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (type() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property type in model SingleSignOnPropertiesV2")); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(SingleSignOnPropertiesV2.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + jsonWriter.writeStringField("state", this.state == null ? null : this.state.toString()); + jsonWriter.writeStringField("enterpriseAppId", this.enterpriseAppId); + jsonWriter.writeStringField("url", this.url); + jsonWriter.writeArrayField("aadDomains", this.aadDomains, (writer, element) -> writer.writeString(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SingleSignOnPropertiesV2 from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SingleSignOnPropertiesV2 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 SingleSignOnPropertiesV2. + */ + public static SingleSignOnPropertiesV2 fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SingleSignOnPropertiesV2 deserializedSingleSignOnPropertiesV2 = new SingleSignOnPropertiesV2(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("type".equals(fieldName)) { + deserializedSingleSignOnPropertiesV2.type = SingleSignOnType.fromString(reader.getString()); + } else if ("state".equals(fieldName)) { + deserializedSingleSignOnPropertiesV2.state = SingleSignOnStates.fromString(reader.getString()); + } else if ("enterpriseAppId".equals(fieldName)) { + deserializedSingleSignOnPropertiesV2.enterpriseAppId = reader.getString(); + } else if ("url".equals(fieldName)) { + deserializedSingleSignOnPropertiesV2.url = reader.getString(); + } else if ("aadDomains".equals(fieldName)) { + List aadDomains = reader.readArray(reader1 -> reader1.getString()); + deserializedSingleSignOnPropertiesV2.aadDomains = aadDomains; + } else { + reader.skipChildren(); + } + } + + return deserializedSingleSignOnPropertiesV2; + }); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/SingleSignOnStates.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/SingleSignOnStates.java new file mode 100644 index 000000000000..5ed28b5fa1f4 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/SingleSignOnStates.java @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Various states of the SSO resource. + */ +public final class SingleSignOnStates extends ExpandableStringEnum { + /** + * Initial state of the SSO resource. + */ + public static final SingleSignOnStates INITIAL = fromString("Initial"); + + /** + * State of the SSO resource when it is enabled. + */ + public static final SingleSignOnStates ENABLE = fromString("Enable"); + + /** + * State of the SSO resource when it is disabled. + */ + public static final SingleSignOnStates DISABLE = fromString("Disable"); + + /** + * Creates a new instance of SingleSignOnStates value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public SingleSignOnStates() { + } + + /** + * Creates or finds a SingleSignOnStates from its string representation. + * + * @param name a name to look for. + * @return the corresponding SingleSignOnStates. + */ + public static SingleSignOnStates fromString(String name) { + return fromString(name, SingleSignOnStates.class); + } + + /** + * Gets known SingleSignOnStates values. + * + * @return known SingleSignOnStates values. + */ + public static Collection values() { + return values(SingleSignOnStates.class); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/SingleSignOnType.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/SingleSignOnType.java new file mode 100644 index 000000000000..b5dac4c4ed1b --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/SingleSignOnType.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines the type of Single Sign-On (SSO) mechanism being used. + */ +public final class SingleSignOnType extends ExpandableStringEnum { + /** + * Security Assertion Markup Language (SAML) based Single Sign-On. + */ + public static final SingleSignOnType SAML = fromString("Saml"); + + /** + * OpenID Connect based Single Sign-On. + */ + public static final SingleSignOnType OPEN_ID = fromString("OpenId"); + + /** + * Creates a new instance of SingleSignOnType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public SingleSignOnType() { + } + + /** + * Creates or finds a SingleSignOnType from its string representation. + * + * @param name a name to look for. + * @return the corresponding SingleSignOnType. + */ + public static SingleSignOnType fromString(String name) { + return fromString(name, SingleSignOnType.class); + } + + /** + * Gets known SingleSignOnType values. + * + * @return known SingleSignOnType values. + */ + public static Collection values() { + return values(SingleSignOnType.class); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/UserAssignedIdentity.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/UserAssignedIdentity.java new file mode 100644 index 000000000000..b79f8b43cca8 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/UserAssignedIdentity.java @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.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; + +/** + * User assigned identity properties. + */ +@Immutable +public final class UserAssignedIdentity implements JsonSerializable { + /* + * The client ID of the assigned identity. + */ + private String clientId; + + /* + * The principal ID of the assigned identity. + */ + private String principalId; + + /** + * Creates an instance of UserAssignedIdentity class. + */ + public UserAssignedIdentity() { + } + + /** + * Get the clientId property: The client ID of the assigned identity. + * + * @return the clientId value. + */ + public String clientId() { + return this.clientId; + } + + /** + * Get the principalId property: The principal ID of the assigned identity. + * + * @return the principalId value. + */ + public String principalId() { + return this.principalId; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of UserAssignedIdentity from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of UserAssignedIdentity 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 UserAssignedIdentity. + */ + public static UserAssignedIdentity fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + UserAssignedIdentity deserializedUserAssignedIdentity = new UserAssignedIdentity(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("clientId".equals(fieldName)) { + deserializedUserAssignedIdentity.clientId = reader.getString(); + } else if ("principalId".equals(fieldName)) { + deserializedUserAssignedIdentity.principalId = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedUserAssignedIdentity; + }); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/UserDetails.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/UserDetails.java new file mode 100644 index 000000000000..9e9771f0490c --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/UserDetails.java @@ -0,0 +1,221 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * User details for an organization. + */ +@Fluent +public final class UserDetails implements JsonSerializable { + /* + * First name of the user + */ + private String firstName; + + /* + * Last name of the user + */ + private String lastName; + + /* + * Email address of the user + */ + private String emailAddress; + + /* + * User's principal name + */ + private String upn; + + /* + * User's phone number + */ + private String phoneNumber; + + /** + * Creates an instance of UserDetails class. + */ + public UserDetails() { + } + + /** + * Get the firstName property: First name of the user. + * + * @return the firstName value. + */ + public String firstName() { + return this.firstName; + } + + /** + * Set the firstName property: First name of the user. + * + * @param firstName the firstName value to set. + * @return the UserDetails object itself. + */ + public UserDetails withFirstName(String firstName) { + this.firstName = firstName; + return this; + } + + /** + * Get the lastName property: Last name of the user. + * + * @return the lastName value. + */ + public String lastName() { + return this.lastName; + } + + /** + * Set the lastName property: Last name of the user. + * + * @param lastName the lastName value to set. + * @return the UserDetails object itself. + */ + public UserDetails withLastName(String lastName) { + this.lastName = lastName; + return this; + } + + /** + * Get the emailAddress property: Email address of the user. + * + * @return the emailAddress value. + */ + public String emailAddress() { + return this.emailAddress; + } + + /** + * Set the emailAddress property: Email address of the user. + * + * @param emailAddress the emailAddress value to set. + * @return the UserDetails object itself. + */ + public UserDetails withEmailAddress(String emailAddress) { + this.emailAddress = emailAddress; + return this; + } + + /** + * Get the upn property: User's principal name. + * + * @return the upn value. + */ + public String upn() { + return this.upn; + } + + /** + * Set the upn property: User's principal name. + * + * @param upn the upn value to set. + * @return the UserDetails object itself. + */ + public UserDetails withUpn(String upn) { + this.upn = upn; + return this; + } + + /** + * Get the phoneNumber property: User's phone number. + * + * @return the phoneNumber value. + */ + public String phoneNumber() { + return this.phoneNumber; + } + + /** + * Set the phoneNumber property: User's phone number. + * + * @param phoneNumber the phoneNumber value to set. + * @return the UserDetails object itself. + */ + public UserDetails withPhoneNumber(String phoneNumber) { + this.phoneNumber = phoneNumber; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (firstName() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property firstName in model UserDetails")); + } + if (lastName() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property lastName in model UserDetails")); + } + if (emailAddress() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property emailAddress in model UserDetails")); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(UserDetails.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("firstName", this.firstName); + jsonWriter.writeStringField("lastName", this.lastName); + jsonWriter.writeStringField("emailAddress", this.emailAddress); + jsonWriter.writeStringField("upn", this.upn); + jsonWriter.writeStringField("phoneNumber", this.phoneNumber); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of UserDetails from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of UserDetails 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 UserDetails. + */ + public static UserDetails fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + UserDetails deserializedUserDetails = new UserDetails(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("firstName".equals(fieldName)) { + deserializedUserDetails.firstName = reader.getString(); + } else if ("lastName".equals(fieldName)) { + deserializedUserDetails.lastName = reader.getString(); + } else if ("emailAddress".equals(fieldName)) { + deserializedUserDetails.emailAddress = reader.getString(); + } else if ("upn".equals(fieldName)) { + deserializedUserDetails.upn = reader.getString(); + } else if ("phoneNumber".equals(fieldName)) { + deserializedUserDetails.phoneNumber = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedUserDetails; + }); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/package-info.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/package-info.java new file mode 100644 index 000000000000..f64872aa3120 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/models/package-info.java @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +/** + * Package containing the data models for PineconeVectorDb. + */ +package com.azure.resourcemanager.pineconevectordb.models; diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/package-info.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/package-info.java new file mode 100644 index 000000000000..d5eebf706e75 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/com/azure/resourcemanager/pineconevectordb/package-info.java @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +/** + * Package containing the classes for PineconeVectorDb. + */ +package com.azure.resourcemanager.pineconevectordb; diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/module-info.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/module-info.java new file mode 100644 index 000000000000..e435a0c62082 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/java/module-info.java @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +module com.azure.resourcemanager.pineconevectordb { + requires transitive com.azure.core.management; + + exports com.azure.resourcemanager.pineconevectordb; + exports com.azure.resourcemanager.pineconevectordb.fluent; + exports com.azure.resourcemanager.pineconevectordb.fluent.models; + exports com.azure.resourcemanager.pineconevectordb.models; + + opens com.azure.resourcemanager.pineconevectordb.fluent.models to com.azure.core; + opens com.azure.resourcemanager.pineconevectordb.models to com.azure.core; + opens com.azure.resourcemanager.pineconevectordb.implementation.models to com.azure.core; +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-pineconevectordb/proxy-config.json b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-pineconevectordb/proxy-config.json new file mode 100644 index 000000000000..447510e74b1a --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-pineconevectordb/proxy-config.json @@ -0,0 +1 @@ +[["com.azure.resourcemanager.pineconevectordb.implementation.OperationsClientImpl$OperationsService"],["com.azure.resourcemanager.pineconevectordb.implementation.OrganizationsClientImpl$OrganizationsService"]] \ No newline at end of file diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-pineconevectordb/reflect-config.json b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-pineconevectordb/reflect-config.json new file mode 100644 index 000000000000..0637a088a01e --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-pineconevectordb/reflect-config.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/resources/azure-resourcemanager-pineconevectordb.properties b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/resources/azure-resourcemanager-pineconevectordb.properties new file mode 100644 index 000000000000..defbd48204e4 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/main/resources/azure-resourcemanager-pineconevectordb.properties @@ -0,0 +1 @@ +version=${project.version} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/samples/java/com/azure/resourcemanager/pineconevectordb/generated/OperationsListSamples.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/samples/java/com/azure/resourcemanager/pineconevectordb/generated/OperationsListSamples.java new file mode 100644 index 000000000000..a08028aac478 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/samples/java/com/azure/resourcemanager/pineconevectordb/generated/OperationsListSamples.java @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.generated; + +/** + * Samples for Operations List. + */ +public final class OperationsListSamples { + /* + * x-ms-original-file: 2024-10-22-preview/Operations_List_MinimumSet_Gen.json + */ + /** + * Sample code: Operations_List_MinimumSet. + * + * @param manager Entry point to PineconeVectorDbManager. + */ + public static void + operationsListMinimumSet(com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager manager) { + manager.operations().list(com.azure.core.util.Context.NONE); + } + + /* + * x-ms-original-file: 2024-10-22-preview/Operations_List_MaximumSet_Gen.json + */ + /** + * Sample code: Operations_List_MaximumSet. + * + * @param manager Entry point to PineconeVectorDbManager. + */ + public static void + operationsListMaximumSet(com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager manager) { + manager.operations().list(com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/samples/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsCreateOrUpdateSamples.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/samples/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsCreateOrUpdateSamples.java new file mode 100644 index 000000000000..88b33f416614 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/samples/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsCreateOrUpdateSamples.java @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.generated; + +import com.azure.resourcemanager.pineconevectordb.models.ManagedServiceIdentity; +import com.azure.resourcemanager.pineconevectordb.models.ManagedServiceIdentityType; +import com.azure.resourcemanager.pineconevectordb.models.MarketplaceDetails; +import com.azure.resourcemanager.pineconevectordb.models.OfferDetails; +import com.azure.resourcemanager.pineconevectordb.models.OrganizationProperties; +import com.azure.resourcemanager.pineconevectordb.models.PartnerProperties; +import com.azure.resourcemanager.pineconevectordb.models.SingleSignOnPropertiesV2; +import com.azure.resourcemanager.pineconevectordb.models.SingleSignOnStates; +import com.azure.resourcemanager.pineconevectordb.models.SingleSignOnType; +import com.azure.resourcemanager.pineconevectordb.models.UserAssignedIdentity; +import com.azure.resourcemanager.pineconevectordb.models.UserDetails; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * Samples for Organizations CreateOrUpdate. + */ +public final class OrganizationsCreateOrUpdateSamples { + /* + * x-ms-original-file: 2024-10-22-preview/Organizations_CreateOrUpdate_MaximumSet_Gen.json + */ + /** + * Sample code: Organizations_CreateOrUpdate_MaximumSet. + * + * @param manager Entry point to PineconeVectorDbManager. + */ + public static void organizationsCreateOrUpdateMaximumSet( + com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager manager) { + manager.organizations() + .define("example-organization-name") + .withRegion("us-east") + .withExistingResourceGroup("rgopenapi") + .withTags(mapOf("my-tag", "tag.value")) + .withProperties(new OrganizationProperties() + .withMarketplace(new MarketplaceDetails().withSubscriptionId("76a38ef6-c8c1-4f0d-bfe0-00ec782c8077") + .withOfferDetails(new OfferDetails().withPublisherId("4d194daf-fa20-46a8-bfb4-5b7d96cae009") + .withOfferId("013124d0-bf05-4eab-a6bb-01fa83870642") + .withPlanId("62dda065-5acd-4ac5-b418-8610beed92a2") + .withPlanName("Freemium") + .withTermUnit("der") + .withTermId("a2b7ce01-f06d-4874-9f77-6ea4a4875c16"))) + .withUser(new UserDetails().withFirstName("Jimmy") + .withLastName("McExample") + .withEmailAddress("example.user@example.com") + .withUpn("example.user@example.com") + .withPhoneNumber("555-555-5555")) + .withPartnerProperties(new PartnerProperties().withDisplayName("My Example Organization")) + .withSingleSignOnProperties(new SingleSignOnPropertiesV2().withType(SingleSignOnType.SAML) + .withState(SingleSignOnStates.INITIAL) + .withEnterpriseAppId("44d3fb26-d8d5-41ff-9b9a-769737f22f13") + .withUrl("https://login.pinecone.io/?sso=true&connection=dfwgsqzkbrjqrglcsa") + .withAadDomains(Arrays.asList("exampledomain")))) + .withIdentity(new ManagedServiceIdentity().withType(ManagedServiceIdentityType.NONE) + .withUserAssignedIdentities(mapOf("ident904655400", new UserAssignedIdentity()))) + .create(); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/samples/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsDeleteSamples.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/samples/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsDeleteSamples.java new file mode 100644 index 000000000000..589fdd2d7644 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/samples/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsDeleteSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.generated; + +/** + * Samples for Organizations Delete. + */ +public final class OrganizationsDeleteSamples { + /* + * x-ms-original-file: 2024-10-22-preview/Organizations_Delete_MaximumSet_Gen.json + */ + /** + * Sample code: Organizations_Delete_MaximumSet. + * + * @param manager Entry point to PineconeVectorDbManager. + */ + public static void + organizationsDeleteMaximumSet(com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager manager) { + manager.organizations().delete("rgopenapi", "example-organization-name", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/samples/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsGetByResourceGroupSamples.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/samples/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsGetByResourceGroupSamples.java new file mode 100644 index 000000000000..0f133dc0b310 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/samples/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsGetByResourceGroupSamples.java @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.generated; + +/** + * Samples for Organizations GetByResourceGroup. + */ +public final class OrganizationsGetByResourceGroupSamples { + /* + * x-ms-original-file: 2024-10-22-preview/Organizations_Get_MaximumSet_Gen.json + */ + /** + * Sample code: Organizations_Get_MaximumSet. + * + * @param manager Entry point to PineconeVectorDbManager. + */ + public static void + organizationsGetMaximumSet(com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager manager) { + manager.organizations() + .getByResourceGroupWithResponse("rgopenapi", "example-organization-name", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/samples/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsListByResourceGroupSamples.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/samples/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsListByResourceGroupSamples.java new file mode 100644 index 000000000000..8cfacbf01c56 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/samples/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsListByResourceGroupSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.generated; + +/** + * Samples for Organizations ListByResourceGroup. + */ +public final class OrganizationsListByResourceGroupSamples { + /* + * x-ms-original-file: 2024-10-22-preview/Organizations_ListByResourceGroup_MaximumSet_Gen.json + */ + /** + * Sample code: Organizations_ListByResourceGroup_MaximumSet. + * + * @param manager Entry point to PineconeVectorDbManager. + */ + public static void organizationsListByResourceGroupMaximumSet( + com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager manager) { + manager.organizations().listByResourceGroup("rgopenapi", com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/samples/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsListSamples.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/samples/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsListSamples.java new file mode 100644 index 000000000000..4fd9247eed4b --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/samples/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsListSamples.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.generated; + +/** + * Samples for Organizations List. + */ +public final class OrganizationsListSamples { + /* + * x-ms-original-file: 2024-10-22-preview/Organizations_ListBySubscription_MaximumSet_Gen.json + */ + /** + * Sample code: Organizations_ListBySubscription_MaximumSet. + * + * @param manager Entry point to PineconeVectorDbManager. + */ + public static void organizationsListBySubscriptionMaximumSet( + com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager manager) { + manager.organizations().list(com.azure.core.util.Context.NONE); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/samples/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsUpdateSamples.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/samples/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsUpdateSamples.java new file mode 100644 index 000000000000..e94463650c52 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/samples/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsUpdateSamples.java @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.generated; + +import com.azure.resourcemanager.pineconevectordb.models.ManagedServiceIdentity; +import com.azure.resourcemanager.pineconevectordb.models.ManagedServiceIdentityType; +import com.azure.resourcemanager.pineconevectordb.models.OrganizationResource; +import com.azure.resourcemanager.pineconevectordb.models.UserAssignedIdentity; +import java.util.HashMap; +import java.util.Map; + +/** + * Samples for Organizations Update. + */ +public final class OrganizationsUpdateSamples { + /* + * x-ms-original-file: 2024-10-22-preview/Organizations_Update_MaximumSet_Gen.json + */ + /** + * Sample code: Organizations_Update_MaximumSet. + * + * @param manager Entry point to PineconeVectorDbManager. + */ + public static void + organizationsUpdateMaximumSet(com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager manager) { + OrganizationResource resource = manager.organizations() + .getByResourceGroupWithResponse("rgopenapi", "example-organization-name", com.azure.core.util.Context.NONE) + .getValue(); + resource.update() + .withTags(mapOf("new-tag", "new.tag.value")) + .withIdentity(new ManagedServiceIdentity().withType(ManagedServiceIdentityType.NONE) + .withUserAssignedIdentities(mapOf("ident573739201", new UserAssignedIdentity()))) + .apply(); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/ManagedServiceIdentityTests.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/ManagedServiceIdentityTests.java new file mode 100644 index 000000000000..c605b9571df6 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/ManagedServiceIdentityTests.java @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.pineconevectordb.models.ManagedServiceIdentity; +import com.azure.resourcemanager.pineconevectordb.models.ManagedServiceIdentityType; +import com.azure.resourcemanager.pineconevectordb.models.UserAssignedIdentity; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Assertions; + +public final class ManagedServiceIdentityTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + ManagedServiceIdentity model = BinaryData.fromString( + "{\"principalId\":\"ol\",\"tenantId\":\"fpsalgbqu\",\"type\":\"SystemAssigned\",\"userAssignedIdentities\":{\"rkujy\":{\"principalId\":\"jgzjaoyfhrtx\",\"clientId\":\"n\"}}}") + .toObject(ManagedServiceIdentity.class); + Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_ASSIGNED, model.type()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + ManagedServiceIdentity model = new ManagedServiceIdentity().withType(ManagedServiceIdentityType.SYSTEM_ASSIGNED) + .withUserAssignedIdentities(mapOf("rkujy", new UserAssignedIdentity())); + model = BinaryData.fromObject(model).toObject(ManagedServiceIdentity.class); + Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_ASSIGNED, model.type()); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/MarketplaceDetailsTests.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/MarketplaceDetailsTests.java new file mode 100644 index 000000000000..f5a67a7b3255 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/MarketplaceDetailsTests.java @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.pineconevectordb.models.MarketplaceDetails; +import com.azure.resourcemanager.pineconevectordb.models.OfferDetails; +import org.junit.jupiter.api.Assertions; + +public final class MarketplaceDetailsTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + MarketplaceDetails model = BinaryData.fromString( + "{\"subscriptionId\":\"bdkvwrwjf\",\"subscriptionStatus\":\"PendingFulfillmentStart\",\"offerDetails\":{\"publisherId\":\"nhutjeltmrldhugj\",\"offerId\":\"zdatqxhocdg\",\"planId\":\"ablgphuticndvk\",\"planName\":\"zwyiftyhxhur\",\"termUnit\":\"ftyxolniw\",\"termId\":\"cukjf\"}}") + .toObject(MarketplaceDetails.class); + Assertions.assertEquals("bdkvwrwjf", model.subscriptionId()); + Assertions.assertEquals("nhutjeltmrldhugj", model.offerDetails().publisherId()); + Assertions.assertEquals("zdatqxhocdg", model.offerDetails().offerId()); + Assertions.assertEquals("ablgphuticndvk", model.offerDetails().planId()); + Assertions.assertEquals("zwyiftyhxhur", model.offerDetails().planName()); + Assertions.assertEquals("ftyxolniw", model.offerDetails().termUnit()); + Assertions.assertEquals("cukjf", model.offerDetails().termId()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + MarketplaceDetails model = new MarketplaceDetails().withSubscriptionId("bdkvwrwjf") + .withOfferDetails(new OfferDetails().withPublisherId("nhutjeltmrldhugj") + .withOfferId("zdatqxhocdg") + .withPlanId("ablgphuticndvk") + .withPlanName("zwyiftyhxhur") + .withTermUnit("ftyxolniw") + .withTermId("cukjf")); + model = BinaryData.fromObject(model).toObject(MarketplaceDetails.class); + Assertions.assertEquals("bdkvwrwjf", model.subscriptionId()); + Assertions.assertEquals("nhutjeltmrldhugj", model.offerDetails().publisherId()); + Assertions.assertEquals("zdatqxhocdg", model.offerDetails().offerId()); + Assertions.assertEquals("ablgphuticndvk", model.offerDetails().planId()); + Assertions.assertEquals("zwyiftyhxhur", model.offerDetails().planName()); + Assertions.assertEquals("ftyxolniw", model.offerDetails().termUnit()); + Assertions.assertEquals("cukjf", model.offerDetails().termId()); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OfferDetailsTests.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OfferDetailsTests.java new file mode 100644 index 000000000000..90e39a5bbcc1 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OfferDetailsTests.java @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.pineconevectordb.models.OfferDetails; +import org.junit.jupiter.api.Assertions; + +public final class OfferDetailsTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + OfferDetails model = BinaryData.fromString( + "{\"publisherId\":\"giawx\",\"offerId\":\"lryplwckbasyy\",\"planId\":\"nddhsgcbacph\",\"planName\":\"koty\",\"termUnit\":\"gou\",\"termId\":\"ndlik\"}") + .toObject(OfferDetails.class); + Assertions.assertEquals("giawx", model.publisherId()); + Assertions.assertEquals("lryplwckbasyy", model.offerId()); + Assertions.assertEquals("nddhsgcbacph", model.planId()); + Assertions.assertEquals("koty", model.planName()); + Assertions.assertEquals("gou", model.termUnit()); + Assertions.assertEquals("ndlik", model.termId()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + OfferDetails model = new OfferDetails().withPublisherId("giawx") + .withOfferId("lryplwckbasyy") + .withPlanId("nddhsgcbacph") + .withPlanName("koty") + .withTermUnit("gou") + .withTermId("ndlik"); + model = BinaryData.fromObject(model).toObject(OfferDetails.class); + Assertions.assertEquals("giawx", model.publisherId()); + Assertions.assertEquals("lryplwckbasyy", model.offerId()); + Assertions.assertEquals("nddhsgcbacph", model.planId()); + Assertions.assertEquals("koty", model.planName()); + Assertions.assertEquals("gou", model.termUnit()); + Assertions.assertEquals("ndlik", model.termId()); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OperationDisplayTests.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OperationDisplayTests.java new file mode 100644 index 000000000000..abb0752a4eb8 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OperationDisplayTests.java @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.pineconevectordb.models.OperationDisplay; + +public final class OperationDisplayTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + OperationDisplay model = BinaryData.fromString( + "{\"provider\":\"cdm\",\"resource\":\"rcryuanzwuxzdxta\",\"operation\":\"lhmwhfpmrqobm\",\"description\":\"kknryrtihf\"}") + .toObject(OperationDisplay.class); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OperationInnerTests.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OperationInnerTests.java new file mode 100644 index 000000000000..7b4cdb25ea47 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OperationInnerTests.java @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.pineconevectordb.fluent.models.OperationInner; + +public final class OperationInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + OperationInner model = BinaryData.fromString( + "{\"name\":\"nygj\",\"isDataAction\":true,\"display\":{\"provider\":\"eqsrdeupewnwreit\",\"resource\":\"yflusarhmofc\",\"operation\":\"smy\",\"description\":\"kdtmlxhekuk\"},\"origin\":\"user,system\",\"actionType\":\"Internal\"}") + .toObject(OperationInner.class); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OperationListResultTests.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OperationListResultTests.java new file mode 100644 index 000000000000..2c2e7fbb941b --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OperationListResultTests.java @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.pineconevectordb.implementation.models.OperationListResult; +import org.junit.jupiter.api.Assertions; + +public final class OperationListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + OperationListResult model = BinaryData.fromString( + "{\"value\":[{\"name\":\"hq\",\"isDataAction\":true,\"display\":{\"provider\":\"pybczmehmtzopb\",\"resource\":\"h\",\"operation\":\"pidgsybbejhphoyc\",\"description\":\"xaobhdxbmtqioqjz\"},\"origin\":\"system\",\"actionType\":\"Internal\"},{\"name\":\"fpownoizhwlr\",\"isDataAction\":false,\"display\":{\"provider\":\"oqijgkdmbpaz\",\"resource\":\"bc\",\"operation\":\"pdznrbtcqqjnqgl\",\"description\":\"gnufoooj\"},\"origin\":\"system\",\"actionType\":\"Internal\"},{\"name\":\"esaagdfm\",\"isDataAction\":true,\"display\":{\"provider\":\"j\",\"resource\":\"ifkwmrvktsizntoc\",\"operation\":\"a\",\"description\":\"ajpsquc\"},\"origin\":\"system\",\"actionType\":\"Internal\"}],\"nextLink\":\"kfo\"}") + .toObject(OperationListResult.class); + Assertions.assertEquals("kfo", model.nextLink()); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OperationsListMockTests.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OperationsListMockTests.java new file mode 100644 index 000000000000..ae6d8ba4082e --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OperationsListMockTests.java @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager; +import com.azure.resourcemanager.pineconevectordb.models.Operation; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class OperationsListMockTests { + @Test + public void testList() throws Exception { + String responseStr + = "{\"value\":[{\"name\":\"a\",\"isDataAction\":true,\"display\":{\"provider\":\"z\",\"resource\":\"vvtpgvdfgio\",\"operation\":\"ftutqxlngxlefgu\",\"description\":\"xkrxdqmi\"},\"origin\":\"user\",\"actionType\":\"Internal\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + PineconeVectorDbManager manager = PineconeVectorDbManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureEnvironment.AZURE)); + + PagedIterable response = manager.operations().list(com.azure.core.util.Context.NONE); + + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationPropertiesTests.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationPropertiesTests.java new file mode 100644 index 000000000000..f7a3295e15a1 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationPropertiesTests.java @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.pineconevectordb.models.MarketplaceDetails; +import com.azure.resourcemanager.pineconevectordb.models.OfferDetails; +import com.azure.resourcemanager.pineconevectordb.models.OrganizationProperties; +import com.azure.resourcemanager.pineconevectordb.models.PartnerProperties; +import com.azure.resourcemanager.pineconevectordb.models.SingleSignOnPropertiesV2; +import com.azure.resourcemanager.pineconevectordb.models.SingleSignOnStates; +import com.azure.resourcemanager.pineconevectordb.models.SingleSignOnType; +import com.azure.resourcemanager.pineconevectordb.models.UserDetails; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class OrganizationPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + OrganizationProperties model = BinaryData.fromString( + "{\"marketplace\":{\"subscriptionId\":\"zrnf\",\"subscriptionStatus\":\"Unsubscribed\",\"offerDetails\":{\"publisherId\":\"gispemvtzfkufubl\",\"offerId\":\"ofx\",\"planId\":\"eofjaeqjh\",\"planName\":\"b\",\"termUnit\":\"v\",\"termId\":\"mjqulngsn\"}},\"user\":{\"firstName\":\"nbybkzgcwrwcl\",\"lastName\":\"xwrljdouskcqvkoc\",\"emailAddress\":\"cjdkwtnhxbnjbi\",\"upn\":\"qrglssainqpjwn\",\"phoneNumber\":\"ljfmppee\"},\"provisioningState\":\"Canceled\",\"partnerProperties\":{\"displayName\":\"xsabkyqdu\"},\"singleSignOnProperties\":{\"type\":\"Saml\",\"state\":\"Disable\",\"enterpriseAppId\":\"czdzev\",\"url\":\"hkr\",\"aadDomains\":[\"appd\"]}}") + .toObject(OrganizationProperties.class); + Assertions.assertEquals("zrnf", model.marketplace().subscriptionId()); + Assertions.assertEquals("gispemvtzfkufubl", model.marketplace().offerDetails().publisherId()); + Assertions.assertEquals("ofx", model.marketplace().offerDetails().offerId()); + Assertions.assertEquals("eofjaeqjh", model.marketplace().offerDetails().planId()); + Assertions.assertEquals("b", model.marketplace().offerDetails().planName()); + Assertions.assertEquals("v", model.marketplace().offerDetails().termUnit()); + Assertions.assertEquals("mjqulngsn", model.marketplace().offerDetails().termId()); + Assertions.assertEquals("nbybkzgcwrwcl", model.user().firstName()); + Assertions.assertEquals("xwrljdouskcqvkoc", model.user().lastName()); + Assertions.assertEquals("cjdkwtnhxbnjbi", model.user().emailAddress()); + Assertions.assertEquals("qrglssainqpjwn", model.user().upn()); + Assertions.assertEquals("ljfmppee", model.user().phoneNumber()); + Assertions.assertEquals("xsabkyqdu", model.partnerProperties().displayName()); + Assertions.assertEquals(SingleSignOnType.SAML, model.singleSignOnProperties().type()); + Assertions.assertEquals(SingleSignOnStates.DISABLE, model.singleSignOnProperties().state()); + Assertions.assertEquals("czdzev", model.singleSignOnProperties().enterpriseAppId()); + Assertions.assertEquals("hkr", model.singleSignOnProperties().url()); + Assertions.assertEquals("appd", model.singleSignOnProperties().aadDomains().get(0)); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + OrganizationProperties model = new OrganizationProperties() + .withMarketplace(new MarketplaceDetails().withSubscriptionId("zrnf") + .withOfferDetails(new OfferDetails().withPublisherId("gispemvtzfkufubl") + .withOfferId("ofx") + .withPlanId("eofjaeqjh") + .withPlanName("b") + .withTermUnit("v") + .withTermId("mjqulngsn"))) + .withUser(new UserDetails().withFirstName("nbybkzgcwrwcl") + .withLastName("xwrljdouskcqvkoc") + .withEmailAddress("cjdkwtnhxbnjbi") + .withUpn("qrglssainqpjwn") + .withPhoneNumber("ljfmppee")) + .withPartnerProperties(new PartnerProperties().withDisplayName("xsabkyqdu")) + .withSingleSignOnProperties(new SingleSignOnPropertiesV2().withType(SingleSignOnType.SAML) + .withState(SingleSignOnStates.DISABLE) + .withEnterpriseAppId("czdzev") + .withUrl("hkr") + .withAadDomains(Arrays.asList("appd"))); + model = BinaryData.fromObject(model).toObject(OrganizationProperties.class); + Assertions.assertEquals("zrnf", model.marketplace().subscriptionId()); + Assertions.assertEquals("gispemvtzfkufubl", model.marketplace().offerDetails().publisherId()); + Assertions.assertEquals("ofx", model.marketplace().offerDetails().offerId()); + Assertions.assertEquals("eofjaeqjh", model.marketplace().offerDetails().planId()); + Assertions.assertEquals("b", model.marketplace().offerDetails().planName()); + Assertions.assertEquals("v", model.marketplace().offerDetails().termUnit()); + Assertions.assertEquals("mjqulngsn", model.marketplace().offerDetails().termId()); + Assertions.assertEquals("nbybkzgcwrwcl", model.user().firstName()); + Assertions.assertEquals("xwrljdouskcqvkoc", model.user().lastName()); + Assertions.assertEquals("cjdkwtnhxbnjbi", model.user().emailAddress()); + Assertions.assertEquals("qrglssainqpjwn", model.user().upn()); + Assertions.assertEquals("ljfmppee", model.user().phoneNumber()); + Assertions.assertEquals("xsabkyqdu", model.partnerProperties().displayName()); + Assertions.assertEquals(SingleSignOnType.SAML, model.singleSignOnProperties().type()); + Assertions.assertEquals(SingleSignOnStates.DISABLE, model.singleSignOnProperties().state()); + Assertions.assertEquals("czdzev", model.singleSignOnProperties().enterpriseAppId()); + Assertions.assertEquals("hkr", model.singleSignOnProperties().url()); + Assertions.assertEquals("appd", model.singleSignOnProperties().aadDomains().get(0)); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationResourceInnerTests.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationResourceInnerTests.java new file mode 100644 index 000000000000..c412970361c2 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationResourceInnerTests.java @@ -0,0 +1,115 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.pineconevectordb.fluent.models.OrganizationResourceInner; +import com.azure.resourcemanager.pineconevectordb.models.ManagedServiceIdentity; +import com.azure.resourcemanager.pineconevectordb.models.ManagedServiceIdentityType; +import com.azure.resourcemanager.pineconevectordb.models.MarketplaceDetails; +import com.azure.resourcemanager.pineconevectordb.models.OfferDetails; +import com.azure.resourcemanager.pineconevectordb.models.OrganizationProperties; +import com.azure.resourcemanager.pineconevectordb.models.PartnerProperties; +import com.azure.resourcemanager.pineconevectordb.models.SingleSignOnPropertiesV2; +import com.azure.resourcemanager.pineconevectordb.models.SingleSignOnStates; +import com.azure.resourcemanager.pineconevectordb.models.SingleSignOnType; +import com.azure.resourcemanager.pineconevectordb.models.UserAssignedIdentity; +import com.azure.resourcemanager.pineconevectordb.models.UserDetails; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Assertions; + +public final class OrganizationResourceInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + OrganizationResourceInner model = BinaryData.fromString( + "{\"properties\":{\"marketplace\":{\"subscriptionId\":\"ijbpzvgnwzsymgl\",\"subscriptionStatus\":\"Unsubscribed\",\"offerDetails\":{\"publisherId\":\"cyzkohdbihanuf\",\"offerId\":\"fcbjysagithxqha\",\"planId\":\"ifpikxwczby\",\"planName\":\"npqxuh\",\"termUnit\":\"y\",\"termId\":\"iwbybrkxvdumjg\"}},\"user\":{\"firstName\":\"tfwvukxgaudc\",\"lastName\":\"snhsjcnyejhkryh\",\"emailAddress\":\"napczwlokjy\",\"upn\":\"kkvnipjox\",\"phoneNumber\":\"nchgej\"},\"provisioningState\":\"Failed\",\"partnerProperties\":{\"displayName\":\"mailzydehojw\"},\"singleSignOnProperties\":{\"type\":\"OpenId\",\"state\":\"Initial\",\"enterpriseAppId\":\"npmqnjaqwixjspro\",\"url\":\"cputegjvwmfdats\",\"aadDomains\":[\"vpjhulsuuv\",\"kjozkrwfnd\",\"odjpslwejd\",\"vwryoqpso\"]}},\"identity\":{\"principalId\":\"tazak\",\"tenantId\":\"lahbcryff\",\"type\":\"SystemAssigned\",\"userAssignedIdentities\":{\"hlxaolthqtr\":{\"principalId\":\"ygexpaojakhmsb\",\"clientId\":\"hcrzevd\"},\"tfell\":{\"principalId\":\"jbp\",\"clientId\":\"fsinzgvfcjrwzoxx\"}}},\"location\":\"fziton\",\"tags\":{\"vhpfxxypininmay\":\"fpjkjlxofp\",\"oginuvamiheognar\":\"uybbkpodep\"},\"id\":\"zxtheotusivyevcc\",\"name\":\"qi\",\"type\":\"nhungbw\"}") + .toObject(OrganizationResourceInner.class); + Assertions.assertEquals("fziton", model.location()); + Assertions.assertEquals("fpjkjlxofp", model.tags().get("vhpfxxypininmay")); + Assertions.assertEquals("ijbpzvgnwzsymgl", model.properties().marketplace().subscriptionId()); + Assertions.assertEquals("cyzkohdbihanuf", model.properties().marketplace().offerDetails().publisherId()); + Assertions.assertEquals("fcbjysagithxqha", model.properties().marketplace().offerDetails().offerId()); + Assertions.assertEquals("ifpikxwczby", model.properties().marketplace().offerDetails().planId()); + Assertions.assertEquals("npqxuh", model.properties().marketplace().offerDetails().planName()); + Assertions.assertEquals("y", model.properties().marketplace().offerDetails().termUnit()); + Assertions.assertEquals("iwbybrkxvdumjg", model.properties().marketplace().offerDetails().termId()); + Assertions.assertEquals("tfwvukxgaudc", model.properties().user().firstName()); + Assertions.assertEquals("snhsjcnyejhkryh", model.properties().user().lastName()); + Assertions.assertEquals("napczwlokjy", model.properties().user().emailAddress()); + Assertions.assertEquals("kkvnipjox", model.properties().user().upn()); + Assertions.assertEquals("nchgej", model.properties().user().phoneNumber()); + Assertions.assertEquals("mailzydehojw", model.properties().partnerProperties().displayName()); + Assertions.assertEquals(SingleSignOnType.OPEN_ID, model.properties().singleSignOnProperties().type()); + Assertions.assertEquals(SingleSignOnStates.INITIAL, model.properties().singleSignOnProperties().state()); + Assertions.assertEquals("npmqnjaqwixjspro", model.properties().singleSignOnProperties().enterpriseAppId()); + Assertions.assertEquals("cputegjvwmfdats", model.properties().singleSignOnProperties().url()); + Assertions.assertEquals("vpjhulsuuv", model.properties().singleSignOnProperties().aadDomains().get(0)); + Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_ASSIGNED, model.identity().type()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + OrganizationResourceInner model = new OrganizationResourceInner().withLocation("fziton") + .withTags(mapOf("vhpfxxypininmay", "fpjkjlxofp", "oginuvamiheognar", "uybbkpodep")) + .withProperties(new OrganizationProperties() + .withMarketplace(new MarketplaceDetails().withSubscriptionId("ijbpzvgnwzsymgl") + .withOfferDetails(new OfferDetails().withPublisherId("cyzkohdbihanuf") + .withOfferId("fcbjysagithxqha") + .withPlanId("ifpikxwczby") + .withPlanName("npqxuh") + .withTermUnit("y") + .withTermId("iwbybrkxvdumjg"))) + .withUser(new UserDetails().withFirstName("tfwvukxgaudc") + .withLastName("snhsjcnyejhkryh") + .withEmailAddress("napczwlokjy") + .withUpn("kkvnipjox") + .withPhoneNumber("nchgej")) + .withPartnerProperties(new PartnerProperties().withDisplayName("mailzydehojw")) + .withSingleSignOnProperties(new SingleSignOnPropertiesV2().withType(SingleSignOnType.OPEN_ID) + .withState(SingleSignOnStates.INITIAL) + .withEnterpriseAppId("npmqnjaqwixjspro") + .withUrl("cputegjvwmfdats") + .withAadDomains(Arrays.asList("vpjhulsuuv", "kjozkrwfnd", "odjpslwejd", "vwryoqpso")))) + .withIdentity(new ManagedServiceIdentity().withType(ManagedServiceIdentityType.SYSTEM_ASSIGNED) + .withUserAssignedIdentities( + mapOf("hlxaolthqtr", new UserAssignedIdentity(), "tfell", new UserAssignedIdentity()))); + model = BinaryData.fromObject(model).toObject(OrganizationResourceInner.class); + Assertions.assertEquals("fziton", model.location()); + Assertions.assertEquals("fpjkjlxofp", model.tags().get("vhpfxxypininmay")); + Assertions.assertEquals("ijbpzvgnwzsymgl", model.properties().marketplace().subscriptionId()); + Assertions.assertEquals("cyzkohdbihanuf", model.properties().marketplace().offerDetails().publisherId()); + Assertions.assertEquals("fcbjysagithxqha", model.properties().marketplace().offerDetails().offerId()); + Assertions.assertEquals("ifpikxwczby", model.properties().marketplace().offerDetails().planId()); + Assertions.assertEquals("npqxuh", model.properties().marketplace().offerDetails().planName()); + Assertions.assertEquals("y", model.properties().marketplace().offerDetails().termUnit()); + Assertions.assertEquals("iwbybrkxvdumjg", model.properties().marketplace().offerDetails().termId()); + Assertions.assertEquals("tfwvukxgaudc", model.properties().user().firstName()); + Assertions.assertEquals("snhsjcnyejhkryh", model.properties().user().lastName()); + Assertions.assertEquals("napczwlokjy", model.properties().user().emailAddress()); + Assertions.assertEquals("kkvnipjox", model.properties().user().upn()); + Assertions.assertEquals("nchgej", model.properties().user().phoneNumber()); + Assertions.assertEquals("mailzydehojw", model.properties().partnerProperties().displayName()); + Assertions.assertEquals(SingleSignOnType.OPEN_ID, model.properties().singleSignOnProperties().type()); + Assertions.assertEquals(SingleSignOnStates.INITIAL, model.properties().singleSignOnProperties().state()); + Assertions.assertEquals("npmqnjaqwixjspro", model.properties().singleSignOnProperties().enterpriseAppId()); + Assertions.assertEquals("cputegjvwmfdats", model.properties().singleSignOnProperties().url()); + Assertions.assertEquals("vpjhulsuuv", model.properties().singleSignOnProperties().aadDomains().get(0)); + Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_ASSIGNED, model.identity().type()); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationResourceListResultTests.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationResourceListResultTests.java new file mode 100644 index 000000000000..484ad07b09df --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationResourceListResultTests.java @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.pineconevectordb.implementation.models.OrganizationResourceListResult; +import com.azure.resourcemanager.pineconevectordb.models.ManagedServiceIdentityType; +import com.azure.resourcemanager.pineconevectordb.models.SingleSignOnStates; +import com.azure.resourcemanager.pineconevectordb.models.SingleSignOnType; +import org.junit.jupiter.api.Assertions; + +public final class OrganizationResourceListResultTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + OrganizationResourceListResult model = BinaryData.fromString( + "{\"value\":[{\"properties\":{\"marketplace\":{\"subscriptionId\":\"nb\",\"subscriptionStatus\":\"Subscribed\",\"offerDetails\":{\"publisherId\":\"abnmocpcyshu\",\"offerId\":\"zafb\",\"planId\":\"jjgpb\",\"planName\":\"qcjm\",\"termUnit\":\"javbqidtqajz\",\"termId\":\"l\"}},\"user\":{\"firstName\":\"kudjkrlkhb\",\"lastName\":\"hfepgzgqex\",\"emailAddress\":\"locx\",\"upn\":\"paierh\",\"phoneNumber\":\"csglum\"},\"provisioningState\":\"Canceled\",\"partnerProperties\":{\"displayName\":\"j\"},\"singleSignOnProperties\":{\"type\":\"Saml\",\"state\":\"Initial\",\"enterpriseAppId\":\"nbdxk\",\"url\":\"xo\",\"aadDomains\":[\"ionpimexg\",\"txgcpodgmaajr\",\"vdjwzrlovm\",\"lwhijcoejctbzaq\"]}},\"identity\":{\"principalId\":\"y\",\"tenantId\":\"kbfkg\",\"type\":\"SystemAssigned\",\"userAssignedIdentities\":{\"fjpgddtocjjxhvp\":{\"principalId\":\"xxppofm\",\"clientId\":\"x\"},\"deicbtwnpzao\":{\"principalId\":\"uexhdzx\",\"clientId\":\"qeojnxqbzvddntw\"}}},\"location\":\"uhrhcffcyddgl\",\"tags\":{\"wpyeicxmqciwqvh\":\"hjq\"},\"id\":\"hix\",\"name\":\"igdtopbob\",\"type\":\"og\"}],\"nextLink\":\"e\"}") + .toObject(OrganizationResourceListResult.class); + Assertions.assertEquals("uhrhcffcyddgl", model.value().get(0).location()); + Assertions.assertEquals("hjq", model.value().get(0).tags().get("wpyeicxmqciwqvh")); + Assertions.assertEquals("nb", model.value().get(0).properties().marketplace().subscriptionId()); + Assertions.assertEquals("abnmocpcyshu", + model.value().get(0).properties().marketplace().offerDetails().publisherId()); + Assertions.assertEquals("zafb", model.value().get(0).properties().marketplace().offerDetails().offerId()); + Assertions.assertEquals("jjgpb", model.value().get(0).properties().marketplace().offerDetails().planId()); + Assertions.assertEquals("qcjm", model.value().get(0).properties().marketplace().offerDetails().planName()); + Assertions.assertEquals("javbqidtqajz", + model.value().get(0).properties().marketplace().offerDetails().termUnit()); + Assertions.assertEquals("l", model.value().get(0).properties().marketplace().offerDetails().termId()); + Assertions.assertEquals("kudjkrlkhb", model.value().get(0).properties().user().firstName()); + Assertions.assertEquals("hfepgzgqex", model.value().get(0).properties().user().lastName()); + Assertions.assertEquals("locx", model.value().get(0).properties().user().emailAddress()); + Assertions.assertEquals("paierh", model.value().get(0).properties().user().upn()); + Assertions.assertEquals("csglum", model.value().get(0).properties().user().phoneNumber()); + Assertions.assertEquals("j", model.value().get(0).properties().partnerProperties().displayName()); + Assertions.assertEquals(SingleSignOnType.SAML, + model.value().get(0).properties().singleSignOnProperties().type()); + Assertions.assertEquals(SingleSignOnStates.INITIAL, + model.value().get(0).properties().singleSignOnProperties().state()); + Assertions.assertEquals("nbdxk", model.value().get(0).properties().singleSignOnProperties().enterpriseAppId()); + Assertions.assertEquals("xo", model.value().get(0).properties().singleSignOnProperties().url()); + Assertions.assertEquals("ionpimexg", + model.value().get(0).properties().singleSignOnProperties().aadDomains().get(0)); + Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_ASSIGNED, model.value().get(0).identity().type()); + Assertions.assertEquals("e", model.nextLink()); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationResourceUpdateTests.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationResourceUpdateTests.java new file mode 100644 index 000000000000..aa7f05081908 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationResourceUpdateTests.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.pineconevectordb.models.ManagedServiceIdentity; +import com.azure.resourcemanager.pineconevectordb.models.ManagedServiceIdentityType; +import com.azure.resourcemanager.pineconevectordb.models.OrganizationResourceUpdate; +import com.azure.resourcemanager.pineconevectordb.models.UserAssignedIdentity; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Assertions; + +public final class OrganizationResourceUpdateTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + OrganizationResourceUpdate model = BinaryData.fromString( + "{\"tags\":{\"szdnr\":\"rbnwbxgjvtbvpy\",\"uhmuouqfprwzwbn\":\"jq\",\"a\":\"uitnwuiz\",\"fizuckyf\":\"x\"},\"identity\":{\"principalId\":\"fidfvzw\",\"tenantId\":\"uht\",\"type\":\"SystemAssigned,UserAssigned\",\"userAssignedIdentities\":{\"ufufsrp\":{\"principalId\":\"dkfthwxmnt\",\"clientId\":\"waopvkmijcmmxd\"},\"mdwzjeiachboo\":{\"principalId\":\"zidnsezcxtbzsgfy\",\"clientId\":\"sne\"},\"inpvswjdkirsoodq\":{\"principalId\":\"lnrosfqp\",\"clientId\":\"ehzzvypyqrim\"},\"znorcj\":{\"principalId\":\"crmnohjtckwhds\",\"clientId\":\"fiyipjxsqwpgrj\"}}}}") + .toObject(OrganizationResourceUpdate.class); + Assertions.assertEquals("rbnwbxgjvtbvpy", model.tags().get("szdnr")); + Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, model.identity().type()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + OrganizationResourceUpdate model = new OrganizationResourceUpdate() + .withTags(mapOf("szdnr", "rbnwbxgjvtbvpy", "uhmuouqfprwzwbn", "jq", "a", "uitnwuiz", "fizuckyf", "x")) + .withIdentity( + new ManagedServiceIdentity().withType(ManagedServiceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED) + .withUserAssignedIdentities( + mapOf("ufufsrp", new UserAssignedIdentity(), "mdwzjeiachboo", new UserAssignedIdentity(), + "inpvswjdkirsoodq", new UserAssignedIdentity(), "znorcj", new UserAssignedIdentity()))); + model = BinaryData.fromObject(model).toObject(OrganizationResourceUpdate.class); + Assertions.assertEquals("rbnwbxgjvtbvpy", model.tags().get("szdnr")); + Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, model.identity().type()); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsCreateOrUpdateMockTests.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsCreateOrUpdateMockTests.java new file mode 100644 index 000000000000..f88fa832569e --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsCreateOrUpdateMockTests.java @@ -0,0 +1,112 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager; +import com.azure.resourcemanager.pineconevectordb.models.ManagedServiceIdentity; +import com.azure.resourcemanager.pineconevectordb.models.ManagedServiceIdentityType; +import com.azure.resourcemanager.pineconevectordb.models.MarketplaceDetails; +import com.azure.resourcemanager.pineconevectordb.models.OfferDetails; +import com.azure.resourcemanager.pineconevectordb.models.OrganizationProperties; +import com.azure.resourcemanager.pineconevectordb.models.OrganizationResource; +import com.azure.resourcemanager.pineconevectordb.models.PartnerProperties; +import com.azure.resourcemanager.pineconevectordb.models.SingleSignOnPropertiesV2; +import com.azure.resourcemanager.pineconevectordb.models.SingleSignOnStates; +import com.azure.resourcemanager.pineconevectordb.models.SingleSignOnType; +import com.azure.resourcemanager.pineconevectordb.models.UserAssignedIdentity; +import com.azure.resourcemanager.pineconevectordb.models.UserDetails; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class OrganizationsCreateOrUpdateMockTests { + @Test + public void testCreateOrUpdate() throws Exception { + String responseStr + = "{\"properties\":{\"marketplace\":{\"subscriptionId\":\"dqmh\",\"subscriptionStatus\":\"Suspended\",\"offerDetails\":{\"publisherId\":\"htldwk\",\"offerId\":\"zxuutkncwscwsvl\",\"planId\":\"otogtwrupqs\",\"planName\":\"nmic\",\"termUnit\":\"vce\",\"termId\":\"eil\"}},\"user\":{\"firstName\":\"vnotyfjfcnj\",\"lastName\":\"k\",\"emailAddress\":\"nxdhbt\",\"upn\":\"phywpnvj\",\"phoneNumber\":\"qnermclfplphoxu\"},\"provisioningState\":\"Succeeded\",\"partnerProperties\":{\"displayName\":\"abgy\"},\"singleSignOnProperties\":{\"type\":\"Saml\",\"state\":\"Initial\",\"enterpriseAppId\":\"azqugxywpmueefj\",\"url\":\"fqkquj\",\"aadDomains\":[\"uyonobglaoc\",\"xtccmg\",\"udxytlmoyrx\",\"wfudwpzntxhdzhl\"]}},\"identity\":{\"principalId\":\"bh\",\"tenantId\":\"frlh\",\"type\":\"UserAssigned\",\"userAssignedIdentities\":{\"ehhseyvjusrts\":{\"principalId\":\"yvpycanuzbpzk\",\"clientId\":\"kuwbcrnwb\"},\"ahvljuaha\":{\"principalId\":\"spkdee\",\"clientId\":\"ofmxagkvtmelmqkr\"}}},\"location\":\"hcdhmdual\",\"tags\":{\"adm\":\"qpv\",\"r\":\"sr\",\"fmisg\":\"vxpvgomz\"},\"id\":\"bnbbeldawkz\",\"name\":\"ali\",\"type\":\"urqhaka\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + PineconeVectorDbManager manager = PineconeVectorDbManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureEnvironment.AZURE)); + + OrganizationResource response = manager.organizations() + .define("mpvecxgodebfqk") + .withRegion("bhvgy") + .withExistingResourceGroup("jhtxfvgxbfsmxne") + .withTags(mapOf("ss", "osvmk", "gmgsxnkjzkde", "qukkfp", "yighxpk", "lpvlopw", "baumnyqupedeoj", "wzbaiue")) + .withProperties(new OrganizationProperties() + .withMarketplace(new MarketplaceDetails().withSubscriptionId("bmpukgriwflz") + .withOfferDetails(new OfferDetails().withPublisherId("xzpuzycisp") + .withOfferId("qzahmgkbrp") + .withPlanId("y") + .withPlanName("ibnuqqkpik") + .withTermUnit("rgvtqag") + .withTermId("uynhijg"))) + .withUser(new UserDetails().withFirstName("mebf") + .withLastName("iarbutrcvpna") + .withEmailAddress("zmhjrunmp") + .withUpn("tdbhrbnla") + .withPhoneNumber("xmyskp")) + .withPartnerProperties(new PartnerProperties().withDisplayName("btkcxywnytnrsyn")) + .withSingleSignOnProperties(new SingleSignOnPropertiesV2().withType(SingleSignOnType.OPEN_ID) + .withState(SingleSignOnStates.DISABLE) + .withEnterpriseAppId("yxczfclh") + .withUrl("xdbabphlwr") + .withAadDomains(Arrays.asList("ktsthsucocmny")))) + .withIdentity( + new ManagedServiceIdentity().withType(ManagedServiceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED) + .withUserAssignedIdentities( + mapOf("qwalmuzyoxaepd", new UserAssignedIdentity(), "zt", new UserAssignedIdentity(), + "xbzpfzab", new UserAssignedIdentity(), "iklbbovpl", new UserAssignedIdentity()))) + .create(); + + Assertions.assertEquals("hcdhmdual", response.location()); + Assertions.assertEquals("qpv", response.tags().get("adm")); + Assertions.assertEquals("dqmh", response.properties().marketplace().subscriptionId()); + Assertions.assertEquals("htldwk", response.properties().marketplace().offerDetails().publisherId()); + Assertions.assertEquals("zxuutkncwscwsvl", response.properties().marketplace().offerDetails().offerId()); + Assertions.assertEquals("otogtwrupqs", response.properties().marketplace().offerDetails().planId()); + Assertions.assertEquals("nmic", response.properties().marketplace().offerDetails().planName()); + Assertions.assertEquals("vce", response.properties().marketplace().offerDetails().termUnit()); + Assertions.assertEquals("eil", response.properties().marketplace().offerDetails().termId()); + Assertions.assertEquals("vnotyfjfcnj", response.properties().user().firstName()); + Assertions.assertEquals("k", response.properties().user().lastName()); + Assertions.assertEquals("nxdhbt", response.properties().user().emailAddress()); + Assertions.assertEquals("phywpnvj", response.properties().user().upn()); + Assertions.assertEquals("qnermclfplphoxu", response.properties().user().phoneNumber()); + Assertions.assertEquals("abgy", response.properties().partnerProperties().displayName()); + Assertions.assertEquals(SingleSignOnType.SAML, response.properties().singleSignOnProperties().type()); + Assertions.assertEquals(SingleSignOnStates.INITIAL, response.properties().singleSignOnProperties().state()); + Assertions.assertEquals("azqugxywpmueefj", response.properties().singleSignOnProperties().enterpriseAppId()); + Assertions.assertEquals("fqkquj", response.properties().singleSignOnProperties().url()); + Assertions.assertEquals("uyonobglaoc", response.properties().singleSignOnProperties().aadDomains().get(0)); + Assertions.assertEquals(ManagedServiceIdentityType.USER_ASSIGNED, response.identity().type()); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsGetByResourceGroupWithResponseMockTests.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsGetByResourceGroupWithResponseMockTests.java new file mode 100644 index 000000000000..8b3a22ce754e --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsGetByResourceGroupWithResponseMockTests.java @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager; +import com.azure.resourcemanager.pineconevectordb.models.ManagedServiceIdentityType; +import com.azure.resourcemanager.pineconevectordb.models.OrganizationResource; +import com.azure.resourcemanager.pineconevectordb.models.SingleSignOnStates; +import com.azure.resourcemanager.pineconevectordb.models.SingleSignOnType; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class OrganizationsGetByResourceGroupWithResponseMockTests { + @Test + public void testGetByResourceGroupWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"marketplace\":{\"subscriptionId\":\"kanyktzlcuiywg\",\"subscriptionStatus\":\"Unsubscribed\",\"offerDetails\":{\"publisherId\":\"gndrvynh\",\"offerId\":\"gpphrcgyn\",\"planId\":\"ocpecfvmmco\",\"planName\":\"sxlzevgbmqj\",\"termUnit\":\"bcypmi\",\"termId\":\"w\"}},\"user\":{\"firstName\":\"zuvccfwnfnbacfio\",\"lastName\":\"l\",\"emailAddress\":\"bxetqgtzxdpn\",\"upn\":\"qqwx\",\"phoneNumber\":\"feallnwsu\"},\"provisioningState\":\"Failed\",\"partnerProperties\":{\"displayName\":\"jampmngnzscxaqw\"},\"singleSignOnProperties\":{\"type\":\"OpenId\",\"state\":\"Enable\",\"enterpriseAppId\":\"onq\",\"url\":\"kvlrxnj\",\"aadDomains\":[\"eipheoflokeyy\",\"enjbdlwtgrhp\"]}},\"identity\":{\"principalId\":\"jumasx\",\"tenantId\":\"jpqyegu\",\"type\":\"SystemAssigned,UserAssigned\",\"userAssignedIdentities\":{\"pwlbjnpg\":{\"principalId\":\"xhejjzzvdud\",\"clientId\":\"dslfhotwmcy\"}}},\"location\":\"ftadehxnltyfs\",\"tags\":{\"nzwdejba\":\"usue\",\"xdn\":\"orxzdmohctbqvud\"},\"id\":\"nvowgujju\",\"name\":\"wdkcglhsl\",\"type\":\"zj\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + PineconeVectorDbManager manager = PineconeVectorDbManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureEnvironment.AZURE)); + + OrganizationResource response = manager.organizations() + .getByResourceGroupWithResponse("rvqdra", "hjybigehoqfbo", com.azure.core.util.Context.NONE) + .getValue(); + + Assertions.assertEquals("ftadehxnltyfs", response.location()); + Assertions.assertEquals("usue", response.tags().get("nzwdejba")); + Assertions.assertEquals("kanyktzlcuiywg", response.properties().marketplace().subscriptionId()); + Assertions.assertEquals("gndrvynh", response.properties().marketplace().offerDetails().publisherId()); + Assertions.assertEquals("gpphrcgyn", response.properties().marketplace().offerDetails().offerId()); + Assertions.assertEquals("ocpecfvmmco", response.properties().marketplace().offerDetails().planId()); + Assertions.assertEquals("sxlzevgbmqj", response.properties().marketplace().offerDetails().planName()); + Assertions.assertEquals("bcypmi", response.properties().marketplace().offerDetails().termUnit()); + Assertions.assertEquals("w", response.properties().marketplace().offerDetails().termId()); + Assertions.assertEquals("zuvccfwnfnbacfio", response.properties().user().firstName()); + Assertions.assertEquals("l", response.properties().user().lastName()); + Assertions.assertEquals("bxetqgtzxdpn", response.properties().user().emailAddress()); + Assertions.assertEquals("qqwx", response.properties().user().upn()); + Assertions.assertEquals("feallnwsu", response.properties().user().phoneNumber()); + Assertions.assertEquals("jampmngnzscxaqw", response.properties().partnerProperties().displayName()); + Assertions.assertEquals(SingleSignOnType.OPEN_ID, response.properties().singleSignOnProperties().type()); + Assertions.assertEquals(SingleSignOnStates.ENABLE, response.properties().singleSignOnProperties().state()); + Assertions.assertEquals("onq", response.properties().singleSignOnProperties().enterpriseAppId()); + Assertions.assertEquals("kvlrxnj", response.properties().singleSignOnProperties().url()); + Assertions.assertEquals("eipheoflokeyy", response.properties().singleSignOnProperties().aadDomains().get(0)); + Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, response.identity().type()); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsListByResourceGroupMockTests.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsListByResourceGroupMockTests.java new file mode 100644 index 000000000000..25e2bbef5925 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsListByResourceGroupMockTests.java @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager; +import com.azure.resourcemanager.pineconevectordb.models.ManagedServiceIdentityType; +import com.azure.resourcemanager.pineconevectordb.models.OrganizationResource; +import com.azure.resourcemanager.pineconevectordb.models.SingleSignOnStates; +import com.azure.resourcemanager.pineconevectordb.models.SingleSignOnType; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class OrganizationsListByResourceGroupMockTests { + @Test + public void testListByResourceGroup() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"marketplace\":{\"subscriptionId\":\"uofqwe\",\"subscriptionStatus\":\"Unsubscribed\",\"offerDetails\":{\"publisherId\":\"menevfyexfwh\",\"offerId\":\"bcibvyvdcsitynn\",\"planId\":\"amdecte\",\"planName\":\"iqscjeypv\",\"termUnit\":\"zrkgqhcjrefovg\",\"termId\":\"qsl\"}},\"user\":{\"firstName\":\"yyvxyqjpkcattpn\",\"lastName\":\"jcrcczsqpjhvmda\",\"emailAddress\":\"v\",\"upn\":\"sounqecanoaeu\",\"phoneNumber\":\"hy\"},\"provisioningState\":\"Succeeded\",\"partnerProperties\":{\"displayName\":\"pmopjmc\"},\"singleSignOnProperties\":{\"type\":\"Saml\",\"state\":\"Enable\",\"enterpriseAppId\":\"thfuiuaodsfcpkvx\",\"url\":\"puozmyzydag\",\"aadDomains\":[\"xbezyiuokktwh\",\"dxwzywqsmbsurexi\",\"o\"]}},\"identity\":{\"principalId\":\"cfsf\",\"tenantId\":\"ymddys\",\"type\":\"SystemAssigned,UserAssigned\",\"userAssignedIdentities\":{\"vkd\":{\"principalId\":\"xhqyudxorrqnb\",\"clientId\":\"czvyifq\"},\"ulexxbczwtr\":{\"principalId\":\"sllr\",\"clientId\":\"vdfwatkpn\"},\"zdobpxjmflbvvnch\":{\"principalId\":\"iqzbq\",\"clientId\":\"sovmyokacspkwl\"}}},\"location\":\"cciw\",\"tags\":{\"foskghsauuimj\":\"uqkhrsajiwku\"},\"id\":\"vxieduugidyj\",\"name\":\"rfbyaosvexcso\",\"type\":\"pclhocohslk\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + PineconeVectorDbManager manager = PineconeVectorDbManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureEnvironment.AZURE)); + + PagedIterable response + = manager.organizations().listByResourceGroup("yggdtjixh", com.azure.core.util.Context.NONE); + + Assertions.assertEquals("cciw", response.iterator().next().location()); + Assertions.assertEquals("uqkhrsajiwku", response.iterator().next().tags().get("foskghsauuimj")); + Assertions.assertEquals("uofqwe", response.iterator().next().properties().marketplace().subscriptionId()); + Assertions.assertEquals("menevfyexfwh", + response.iterator().next().properties().marketplace().offerDetails().publisherId()); + Assertions.assertEquals("bcibvyvdcsitynn", + response.iterator().next().properties().marketplace().offerDetails().offerId()); + Assertions.assertEquals("amdecte", + response.iterator().next().properties().marketplace().offerDetails().planId()); + Assertions.assertEquals("iqscjeypv", + response.iterator().next().properties().marketplace().offerDetails().planName()); + Assertions.assertEquals("zrkgqhcjrefovg", + response.iterator().next().properties().marketplace().offerDetails().termUnit()); + Assertions.assertEquals("qsl", response.iterator().next().properties().marketplace().offerDetails().termId()); + Assertions.assertEquals("yyvxyqjpkcattpn", response.iterator().next().properties().user().firstName()); + Assertions.assertEquals("jcrcczsqpjhvmda", response.iterator().next().properties().user().lastName()); + Assertions.assertEquals("v", response.iterator().next().properties().user().emailAddress()); + Assertions.assertEquals("sounqecanoaeu", response.iterator().next().properties().user().upn()); + Assertions.assertEquals("hy", response.iterator().next().properties().user().phoneNumber()); + Assertions.assertEquals("pmopjmc", response.iterator().next().properties().partnerProperties().displayName()); + Assertions.assertEquals(SingleSignOnType.SAML, + response.iterator().next().properties().singleSignOnProperties().type()); + Assertions.assertEquals(SingleSignOnStates.ENABLE, + response.iterator().next().properties().singleSignOnProperties().state()); + Assertions.assertEquals("thfuiuaodsfcpkvx", + response.iterator().next().properties().singleSignOnProperties().enterpriseAppId()); + Assertions.assertEquals("puozmyzydag", response.iterator().next().properties().singleSignOnProperties().url()); + Assertions.assertEquals("xbezyiuokktwh", + response.iterator().next().properties().singleSignOnProperties().aadDomains().get(0)); + Assertions.assertEquals(ManagedServiceIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, + response.iterator().next().identity().type()); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsListMockTests.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsListMockTests.java new file mode 100644 index 000000000000..f9ee5394265a --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/OrganizationsListMockTests.java @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.pineconevectordb.PineconeVectorDbManager; +import com.azure.resourcemanager.pineconevectordb.models.ManagedServiceIdentityType; +import com.azure.resourcemanager.pineconevectordb.models.OrganizationResource; +import com.azure.resourcemanager.pineconevectordb.models.SingleSignOnStates; +import com.azure.resourcemanager.pineconevectordb.models.SingleSignOnType; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class OrganizationsListMockTests { + @Test + public void testList() throws Exception { + String responseStr + = "{\"value\":[{\"properties\":{\"marketplace\":{\"subscriptionId\":\"leggzfbu\",\"subscriptionStatus\":\"Unsubscribed\",\"offerDetails\":{\"publisherId\":\"vfaxkffeiith\",\"offerId\":\"vmezy\",\"planId\":\"shxmzsbbzoggigrx\",\"planName\":\"ur\",\"termUnit\":\"xxjnspydptk\",\"termId\":\"nkoukn\"}},\"user\":{\"firstName\":\"udwtiukbl\",\"lastName\":\"ngkpocipazy\",\"emailAddress\":\"o\",\"upn\":\"ukgjnpiucgygevq\",\"phoneNumber\":\"typmrbpizcdrqjsd\"},\"provisioningState\":\"Succeeded\",\"partnerProperties\":{\"displayName\":\"fyhxde\"},\"singleSignOnProperties\":{\"type\":\"OpenId\",\"state\":\"Enable\",\"enterpriseAppId\":\"w\",\"url\":\"sjttgzfbish\",\"aadDomains\":[\"hajdeyeamdpha\"]}},\"identity\":{\"principalId\":\"pbuxwgipwhon\",\"tenantId\":\"kgshwa\",\"type\":\"None\",\"userAssignedIdentities\":{\"tmryw\":{\"principalId\":\"bin\",\"clientId\":\"pu\"},\"nwvlryavwhheunmm\":{\"principalId\":\"zoqftiyqzrnkcqvy\",\"clientId\":\"whzlsicohoq\"},\"conuqszfkbeype\":{\"principalId\":\"gyxzk\",\"clientId\":\"ocukoklyax\"}}},\"location\":\"mjmwvvjektcx\",\"tags\":{\"rzpwvlqdqgbiq\":\"hwlrsf\",\"vf\":\"lihkaetcktvfc\",\"xerf\":\"nkymuctqhjfbebrj\",\"phxepcyvahf\":\"wutttxfvjrbi\"},\"id\":\"ljkyqxjvuuj\",\"name\":\"gidokgjljyoxgvcl\",\"type\":\"bgsncghkjeszzhb\"}]}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + PineconeVectorDbManager manager = PineconeVectorDbManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureEnvironment.AZURE)); + + PagedIterable response = manager.organizations().list(com.azure.core.util.Context.NONE); + + Assertions.assertEquals("mjmwvvjektcx", response.iterator().next().location()); + Assertions.assertEquals("hwlrsf", response.iterator().next().tags().get("rzpwvlqdqgbiq")); + Assertions.assertEquals("leggzfbu", response.iterator().next().properties().marketplace().subscriptionId()); + Assertions.assertEquals("vfaxkffeiith", + response.iterator().next().properties().marketplace().offerDetails().publisherId()); + Assertions.assertEquals("vmezy", + response.iterator().next().properties().marketplace().offerDetails().offerId()); + Assertions.assertEquals("shxmzsbbzoggigrx", + response.iterator().next().properties().marketplace().offerDetails().planId()); + Assertions.assertEquals("ur", response.iterator().next().properties().marketplace().offerDetails().planName()); + Assertions.assertEquals("xxjnspydptk", + response.iterator().next().properties().marketplace().offerDetails().termUnit()); + Assertions.assertEquals("nkoukn", + response.iterator().next().properties().marketplace().offerDetails().termId()); + Assertions.assertEquals("udwtiukbl", response.iterator().next().properties().user().firstName()); + Assertions.assertEquals("ngkpocipazy", response.iterator().next().properties().user().lastName()); + Assertions.assertEquals("o", response.iterator().next().properties().user().emailAddress()); + Assertions.assertEquals("ukgjnpiucgygevq", response.iterator().next().properties().user().upn()); + Assertions.assertEquals("typmrbpizcdrqjsd", response.iterator().next().properties().user().phoneNumber()); + Assertions.assertEquals("fyhxde", response.iterator().next().properties().partnerProperties().displayName()); + Assertions.assertEquals(SingleSignOnType.OPEN_ID, + response.iterator().next().properties().singleSignOnProperties().type()); + Assertions.assertEquals(SingleSignOnStates.ENABLE, + response.iterator().next().properties().singleSignOnProperties().state()); + Assertions.assertEquals("w", + response.iterator().next().properties().singleSignOnProperties().enterpriseAppId()); + Assertions.assertEquals("sjttgzfbish", response.iterator().next().properties().singleSignOnProperties().url()); + Assertions.assertEquals("hajdeyeamdpha", + response.iterator().next().properties().singleSignOnProperties().aadDomains().get(0)); + Assertions.assertEquals(ManagedServiceIdentityType.NONE, response.iterator().next().identity().type()); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/PartnerPropertiesTests.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/PartnerPropertiesTests.java new file mode 100644 index 000000000000..6a667071240e --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/PartnerPropertiesTests.java @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.pineconevectordb.models.PartnerProperties; +import org.junit.jupiter.api.Assertions; + +public final class PartnerPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + PartnerProperties model + = BinaryData.fromString("{\"displayName\":\"dmgloug\"}").toObject(PartnerProperties.class); + Assertions.assertEquals("dmgloug", model.displayName()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + PartnerProperties model = new PartnerProperties().withDisplayName("dmgloug"); + model = BinaryData.fromObject(model).toObject(PartnerProperties.class); + Assertions.assertEquals("dmgloug", model.displayName()); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/SingleSignOnPropertiesV2Tests.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/SingleSignOnPropertiesV2Tests.java new file mode 100644 index 000000000000..7f6517485157 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/SingleSignOnPropertiesV2Tests.java @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.pineconevectordb.models.SingleSignOnPropertiesV2; +import com.azure.resourcemanager.pineconevectordb.models.SingleSignOnStates; +import com.azure.resourcemanager.pineconevectordb.models.SingleSignOnType; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class SingleSignOnPropertiesV2Tests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SingleSignOnPropertiesV2 model = BinaryData.fromString( + "{\"type\":\"Saml\",\"state\":\"Disable\",\"enterpriseAppId\":\"mutduqktaps\",\"url\":\"gcue\",\"aadDomains\":[\"mkdo\",\"vqwhbmdgbbjfd\",\"gmbmbexppbh\",\"q\"]}") + .toObject(SingleSignOnPropertiesV2.class); + Assertions.assertEquals(SingleSignOnType.SAML, model.type()); + Assertions.assertEquals(SingleSignOnStates.DISABLE, model.state()); + Assertions.assertEquals("mutduqktaps", model.enterpriseAppId()); + Assertions.assertEquals("gcue", model.url()); + Assertions.assertEquals("mkdo", model.aadDomains().get(0)); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SingleSignOnPropertiesV2 model = new SingleSignOnPropertiesV2().withType(SingleSignOnType.SAML) + .withState(SingleSignOnStates.DISABLE) + .withEnterpriseAppId("mutduqktaps") + .withUrl("gcue") + .withAadDomains(Arrays.asList("mkdo", "vqwhbmdgbbjfd", "gmbmbexppbh", "q")); + model = BinaryData.fromObject(model).toObject(SingleSignOnPropertiesV2.class); + Assertions.assertEquals(SingleSignOnType.SAML, model.type()); + Assertions.assertEquals(SingleSignOnStates.DISABLE, model.state()); + Assertions.assertEquals("mutduqktaps", model.enterpriseAppId()); + Assertions.assertEquals("gcue", model.url()); + Assertions.assertEquals("mkdo", model.aadDomains().get(0)); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/UserAssignedIdentityTests.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/UserAssignedIdentityTests.java new file mode 100644 index 000000000000..4ebf4f8b833c --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/UserAssignedIdentityTests.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.pineconevectordb.models.UserAssignedIdentity; + +public final class UserAssignedIdentityTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + UserAssignedIdentity model = BinaryData.fromString("{\"principalId\":\"l\",\"clientId\":\"uvfqawrlyxwj\"}") + .toObject(UserAssignedIdentity.class); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + UserAssignedIdentity model = new UserAssignedIdentity(); + model = BinaryData.fromObject(model).toObject(UserAssignedIdentity.class); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/UserDetailsTests.java b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/UserDetailsTests.java new file mode 100644 index 000000000000..fd59833eca88 --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/src/test/java/com/azure/resourcemanager/pineconevectordb/generated/UserDetailsTests.java @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.pineconevectordb.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.pineconevectordb.models.UserDetails; +import org.junit.jupiter.api.Assertions; + +public final class UserDetailsTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + UserDetails model = BinaryData.fromString( + "{\"firstName\":\"yqkgfg\",\"lastName\":\"bmadgak\",\"emailAddress\":\"qsrxybzqqed\",\"upn\":\"tbciqfouflmm\",\"phoneNumber\":\"zsm\"}") + .toObject(UserDetails.class); + Assertions.assertEquals("yqkgfg", model.firstName()); + Assertions.assertEquals("bmadgak", model.lastName()); + Assertions.assertEquals("qsrxybzqqed", model.emailAddress()); + Assertions.assertEquals("tbciqfouflmm", model.upn()); + Assertions.assertEquals("zsm", model.phoneNumber()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + UserDetails model = new UserDetails().withFirstName("yqkgfg") + .withLastName("bmadgak") + .withEmailAddress("qsrxybzqqed") + .withUpn("tbciqfouflmm") + .withPhoneNumber("zsm"); + model = BinaryData.fromObject(model).toObject(UserDetails.class); + Assertions.assertEquals("yqkgfg", model.firstName()); + Assertions.assertEquals("bmadgak", model.lastName()); + Assertions.assertEquals("qsrxybzqqed", model.emailAddress()); + Assertions.assertEquals("tbciqfouflmm", model.upn()); + Assertions.assertEquals("zsm", model.phoneNumber()); + } +} diff --git a/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/tsp-location.yaml b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/tsp-location.yaml new file mode 100644 index 000000000000..611609a44b7d --- /dev/null +++ b/sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/liftrpinecone/Pinecone.VectorDb.Management +commit: 3a17b429e962d7a1a01c3c8fcdded8c8a2364196 +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/pineconevectordb/ci.yml b/sdk/pineconevectordb/ci.yml new file mode 100644 index 000000000000..b32d56ae31d9 --- /dev/null +++ b/sdk/pineconevectordb/ci.yml @@ -0,0 +1,46 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. + +trigger: + branches: + include: + - main + - hotfix/* + - release/* + paths: + include: + - sdk/pineconevectordb/ci.yml + - sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/ + exclude: + - sdk/pineconevectordb/pom.xml + - sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/pom.xml + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/pineconevectordb/ci.yml + - sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/ + exclude: + - sdk/pineconevectordb/pom.xml + - sdk/pineconevectordb/azure-resourcemanager-pineconevectordb/pom.xml + +parameters: + - name: release_azureresourcemanagerpineconevectordb + displayName: azure-resourcemanager-pineconevectordb + type: boolean + default: false + +extends: + template: ../../eng/pipelines/templates/stages/archetype-sdk-client.yml + parameters: + ServiceDirectory: pineconevectordb + Artifacts: + - name: azure-resourcemanager-pineconevectordb + groupId: com.azure.resourcemanager + safeName: azureresourcemanagerpineconevectordb + releaseInBatch: ${{ parameters.release_azureresourcemanagerpineconevectordb }} diff --git a/sdk/pineconevectordb/pom.xml b/sdk/pineconevectordb/pom.xml new file mode 100644 index 000000000000..45830a9448f8 --- /dev/null +++ b/sdk/pineconevectordb/pom.xml @@ -0,0 +1,15 @@ + + + 4.0.0 + com.azure + azure-pineconevectordb-service + pom + 1.0.0 + + + azure-resourcemanager-pineconevectordb + + diff --git a/sdk/playwrighttesting/azure-resourcemanager-playwrighttesting/README.md b/sdk/playwrighttesting/azure-resourcemanager-playwrighttesting/README.md index f83b098d8233..6c4313bcf4c0 100644 --- a/sdk/playwrighttesting/azure-resourcemanager-playwrighttesting/README.md +++ b/sdk/playwrighttesting/azure-resourcemanager-playwrighttesting/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-playwrighttesting - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fplaywrighttesting%2Fazure-resourcemanager-playwrighttesting%2FREADME.png) + diff --git a/sdk/playwrighttesting/azure-resourcemanager-playwrighttesting/pom.xml b/sdk/playwrighttesting/azure-resourcemanager-playwrighttesting/pom.xml index 23ee74a1a70f..4c78d10eb28a 100644 --- a/sdk/playwrighttesting/azure-resourcemanager-playwrighttesting/pom.xml +++ b/sdk/playwrighttesting/azure-resourcemanager-playwrighttesting/pom.xml @@ -52,23 +52,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test @@ -92,7 +92,7 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/playwrighttesting/azure-resourcemanager-playwrighttesting/src/main/java/com/azure/resourcemanager/playwrighttesting/PlaywrightTestingManager.java b/sdk/playwrighttesting/azure-resourcemanager-playwrighttesting/src/main/java/com/azure/resourcemanager/playwrighttesting/PlaywrightTestingManager.java index 36a07f5fb275..971a5a64e8f0 100644 --- a/sdk/playwrighttesting/azure-resourcemanager-playwrighttesting/src/main/java/com/azure/resourcemanager/playwrighttesting/PlaywrightTestingManager.java +++ b/sdk/playwrighttesting/azure-resourcemanager-playwrighttesting/src/main/java/com/azure/resourcemanager/playwrighttesting/PlaywrightTestingManager.java @@ -22,6 +22,7 @@ import com.azure.core.http.policy.UserAgentPolicy; import com.azure.core.management.profile.AzureProfile; import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.playwrighttesting.fluent.PlaywrightTestingMgmtClient; import com.azure.resourcemanager.playwrighttesting.implementation.AccountQuotasImpl; @@ -37,6 +38,7 @@ import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; @@ -105,6 +107,9 @@ public static Configurable configure() { */ public static final class Configurable { private static final ClientLogger LOGGER = new ClientLogger(Configurable.class); + private static final String SDK_VERSION = "version"; + private static final Map PROPERTIES + = CoreUtils.getProperties("azure-resourcemanager-playwrighttesting.properties"); private HttpClient httpClient; private HttpLogOptions httpLogOptions; @@ -212,12 +217,14 @@ public PlaywrightTestingManager authenticate(TokenCredential credential, AzurePr Objects.requireNonNull(credential, "'credential' cannot be null."); Objects.requireNonNull(profile, "'profile' cannot be null."); + String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); + StringBuilder userAgentBuilder = new StringBuilder(); userAgentBuilder.append("azsdk-java") .append("-") .append("com.azure.resourcemanager.playwrighttesting") .append("/") - .append("1.0.0-beta.1"); + .append(clientVersion); if (!Configuration.getGlobalConfiguration().get("AZURE_TELEMETRY_DISABLED", false)) { userAgentBuilder.append(" (") .append(Configuration.getGlobalConfiguration().get("java.version")) diff --git a/sdk/playwrighttesting/azure-resourcemanager-playwrighttesting/src/main/resources/azure-resourcemanager-playwrighttesting.properties b/sdk/playwrighttesting/azure-resourcemanager-playwrighttesting/src/main/resources/azure-resourcemanager-playwrighttesting.properties new file mode 100644 index 000000000000..defbd48204e4 --- /dev/null +++ b/sdk/playwrighttesting/azure-resourcemanager-playwrighttesting/src/main/resources/azure-resourcemanager-playwrighttesting.properties @@ -0,0 +1 @@ +version=${project.version} diff --git a/sdk/policyinsights/azure-resourcemanager-policyinsights/README.md b/sdk/policyinsights/azure-resourcemanager-policyinsights/README.md index db6844fe01a8..4bc06613fee1 100644 --- a/sdk/policyinsights/azure-resourcemanager-policyinsights/README.md +++ b/sdk/policyinsights/azure-resourcemanager-policyinsights/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-policyinsights - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fpolicyinsights%2Fazure-resourcemanager-policyinsights%2FREADME.png) + diff --git a/sdk/policyinsights/azure-resourcemanager-policyinsights/pom.xml b/sdk/policyinsights/azure-resourcemanager-policyinsights/pom.xml index 67ec1bb38aac..55d7db87763e 100644 --- a/sdk/policyinsights/azure-resourcemanager-policyinsights/pom.xml +++ b/sdk/policyinsights/azure-resourcemanager-policyinsights/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/postgresql/azure-resourcemanager-postgresql/README.md b/sdk/postgresql/azure-resourcemanager-postgresql/README.md index cc574d5a9f70..cb7a63dadbbc 100644 --- a/sdk/postgresql/azure-resourcemanager-postgresql/README.md +++ b/sdk/postgresql/azure-resourcemanager-postgresql/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-postgresql - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -123,4 +123,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fpostgresql%2Fazure-resourcemanager-postgresql%2FREADME.png) + diff --git a/sdk/postgresql/azure-resourcemanager-postgresql/pom.xml b/sdk/postgresql/azure-resourcemanager-postgresql/pom.xml index 279432f12cb9..37a9c39157ae 100644 --- a/sdk/postgresql/azure-resourcemanager-postgresql/pom.xml +++ b/sdk/postgresql/azure-resourcemanager-postgresql/pom.xml @@ -52,29 +52,29 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/postgresqlflexibleserver/azure-resourcemanager-postgresqlflexibleserver/README.md b/sdk/postgresqlflexibleserver/azure-resourcemanager-postgresqlflexibleserver/README.md index 21531cd762e6..88cbc56c538a 100644 --- a/sdk/postgresqlflexibleserver/azure-resourcemanager-postgresqlflexibleserver/README.md +++ b/sdk/postgresqlflexibleserver/azure-resourcemanager-postgresqlflexibleserver/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-postgresqlflexibleserver - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -122,4 +122,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fpostgresqlflexibleserver%2Fazure-resourcemanager-postgresqlflexibleserver%2FREADME.png) + diff --git a/sdk/postgresqlflexibleserver/azure-resourcemanager-postgresqlflexibleserver/pom.xml b/sdk/postgresqlflexibleserver/azure-resourcemanager-postgresqlflexibleserver/pom.xml index 651c40df9ae6..1bbb7618672b 100644 --- a/sdk/postgresqlflexibleserver/azure-resourcemanager-postgresqlflexibleserver/pom.xml +++ b/sdk/postgresqlflexibleserver/azure-resourcemanager-postgresqlflexibleserver/pom.xml @@ -52,29 +52,29 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/powerbidedicated/azure-resourcemanager-powerbidedicated/README.md b/sdk/powerbidedicated/azure-resourcemanager-powerbidedicated/README.md index 54970d6da63f..f130e4c6135f 100644 --- a/sdk/powerbidedicated/azure-resourcemanager-powerbidedicated/README.md +++ b/sdk/powerbidedicated/azure-resourcemanager-powerbidedicated/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-powerbidedicated - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fpowerbidedicated%2Fazure-resourcemanager-powerbidedicated%2FREADME.png) + diff --git a/sdk/powerbidedicated/azure-resourcemanager-powerbidedicated/pom.xml b/sdk/powerbidedicated/azure-resourcemanager-powerbidedicated/pom.xml index 783658fb791e..596cc226f338 100644 --- a/sdk/powerbidedicated/azure-resourcemanager-powerbidedicated/pom.xml +++ b/sdk/powerbidedicated/azure-resourcemanager-powerbidedicated/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/providerhub/azure-resourcemanager-providerhub/README.md b/sdk/providerhub/azure-resourcemanager-providerhub/README.md index 2bbd3971743b..b83c27bfcf90 100644 --- a/sdk/providerhub/azure-resourcemanager-providerhub/README.md +++ b/sdk/providerhub/azure-resourcemanager-providerhub/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-providerhub - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -111,4 +111,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fproviderhub%2Fazure-resourcemanager-providerhub%2FREADME.png) + diff --git a/sdk/providerhub/azure-resourcemanager-providerhub/pom.xml b/sdk/providerhub/azure-resourcemanager-providerhub/pom.xml index 8dcca4b0527d..90c63f03fe05 100644 --- a/sdk/providerhub/azure-resourcemanager-providerhub/pom.xml +++ b/sdk/providerhub/azure-resourcemanager-providerhub/pom.xml @@ -51,29 +51,29 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/purview/azure-analytics-purview-administration/README.md b/sdk/purview/azure-analytics-purview-administration/README.md index 27f4f6ed6249..96983e781f56 100644 --- a/sdk/purview/azure-analytics-purview-administration/README.md +++ b/sdk/purview/azure-analytics-purview-administration/README.md @@ -26,7 +26,7 @@ For more information about permissions, see [here][azure_purview_permissions]. com.azure azure-analytics-purview-administration - 1.0.0-beta.1 + 1.0.0-beta.2 ``` [//]: # ({x-version-update-end}) @@ -48,7 +48,7 @@ To use the [DefaultAzureCredential][DefaultAzureCredential] provider shown below com.azure azure-identity - 1.14.2 + 1.15.3 ``` [//]: # ({x-version-update-end}) @@ -111,4 +111,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [azure_purview_permissions]: https://learn.microsoft.com/azure/purview/catalog-permissions [logging]: https://github.com/Azure/azure-sdk-for-java/wiki/Logging-in-Azure-SDK -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fpurview%2Fazure-analytics-purview-administration%2FREADME.png) + diff --git a/sdk/purview/azure-analytics-purview-administration/pom.xml b/sdk/purview/azure-analytics-purview-administration/pom.xml index ba23133b2837..6db178b2b0c8 100644 --- a/sdk/purview/azure-analytics-purview-administration/pom.xml +++ b/sdk/purview/azure-analytics-purview-administration/pom.xml @@ -46,25 +46,25 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/purview/azure-analytics-purview-datamap/README.md b/sdk/purview/azure-analytics-purview-datamap/README.md index 9fc1a707b20e..5c6c6df6befe 100644 --- a/sdk/purview/azure-analytics-purview-datamap/README.md +++ b/sdk/purview/azure-analytics-purview-datamap/README.md @@ -25,7 +25,7 @@ Various documentation is available to help you get started com.azure azure-analytics-purview-datamap - 1.0.0-beta.1 + 1.0.0-beta.2 ``` [//]: # ({x-version-update-end}) @@ -78,4 +78,4 @@ For details on contributing to this repository, see the [contributing guide](htt [azure_subscription]: https://azure.microsoft.com/free/ [azure_identity]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/identity/azure-identity -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fpurview%2Fazure-analytics-purview-datamap%2FREADME.png) + diff --git a/sdk/purview/azure-analytics-purview-datamap/pom.xml b/sdk/purview/azure-analytics-purview-datamap/pom.xml index 6f00823650b7..6f86d16deadb 100644 --- a/sdk/purview/azure-analytics-purview-datamap/pom.xml +++ b/sdk/purview/azure-analytics-purview-datamap/pom.xml @@ -54,28 +54,28 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/purview/azure-analytics-purview-datamap/src/main/java/com/azure/analytics/purview/datamap/EntityAsyncClient.java b/sdk/purview/azure-analytics-purview-datamap/src/main/java/com/azure/analytics/purview/datamap/EntityAsyncClient.java index 24b36b858f3d..69083b5c4bce 100644 --- a/sdk/purview/azure-analytics-purview-datamap/src/main/java/com/azure/analytics/purview/datamap/EntityAsyncClient.java +++ b/sdk/purview/azure-analytics-purview-datamap/src/main/java/com/azure/analytics/purview/datamap/EntityAsyncClient.java @@ -2231,8 +2231,8 @@ public Mono> getBusinessMetadataTemplateWithResponse(Reques @Generated @ServiceMethod(returns = ReturnType.SINGLE) Mono> importBusinessMetadataWithResponse(BinaryData body, RequestOptions requestOptions) { - // Protocol API requires serialization of parts with content-disposition and data, as operation - // 'importBusinessMetadata' is 'multipart/form-data' + // Operation 'importBusinessMetadata' is of content-type 'multipart/form-data'. Protocol API is not usable and + // hence not generated. return this.serviceClient.importBusinessMetadataWithResponseAsync(body, requestOptions); } diff --git a/sdk/purview/azure-analytics-purview-datamap/src/main/java/com/azure/analytics/purview/datamap/EntityClient.java b/sdk/purview/azure-analytics-purview-datamap/src/main/java/com/azure/analytics/purview/datamap/EntityClient.java index 33592acdd579..5b5eab663686 100644 --- a/sdk/purview/azure-analytics-purview-datamap/src/main/java/com/azure/analytics/purview/datamap/EntityClient.java +++ b/sdk/purview/azure-analytics-purview-datamap/src/main/java/com/azure/analytics/purview/datamap/EntityClient.java @@ -2213,8 +2213,8 @@ public Response getBusinessMetadataTemplateWithResponse(RequestOptio @Generated @ServiceMethod(returns = ReturnType.SINGLE) Response importBusinessMetadataWithResponse(BinaryData body, RequestOptions requestOptions) { - // Protocol API requires serialization of parts with content-disposition and data, as operation - // 'importBusinessMetadata' is 'multipart/form-data' + // Operation 'importBusinessMetadata' is of content-type 'multipart/form-data'. Protocol API is not usable and + // hence not generated. return this.serviceClient.importBusinessMetadataWithResponse(body, requestOptions); } diff --git a/sdk/purview/azure-analytics-purview-scanning/README.md b/sdk/purview/azure-analytics-purview-scanning/README.md index efe61e545791..989736255cc4 100644 --- a/sdk/purview/azure-analytics-purview-scanning/README.md +++ b/sdk/purview/azure-analytics-purview-scanning/README.md @@ -27,7 +27,7 @@ For more information about creating the account see [here][create_azure_purview_ com.azure azure-analytics-purview-scanning - 1.0.0-beta.2 + 1.0.0-beta.3 ``` [//]: # ({x-version-update-end}) @@ -50,7 +50,7 @@ To use the [DefaultAzureCredential][DefaultAzureCredential] provider shown below com.azure azure-identity - 1.14.2 + 1.15.3 ``` [//]: # ({x-version-update-end}) @@ -108,4 +108,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ [coc_contact]: mailto:opencode@microsoft.com -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fpurview%2Fazure-analytics-purview-scanning%2FREADME.png) + diff --git a/sdk/purview/azure-analytics-purview-scanning/pom.xml b/sdk/purview/azure-analytics-purview-scanning/pom.xml index e59422cdbc92..d24d04386efc 100644 --- a/sdk/purview/azure-analytics-purview-scanning/pom.xml +++ b/sdk/purview/azure-analytics-purview-scanning/pom.xml @@ -46,25 +46,25 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/purview/azure-analytics-purview-sharing/README.md b/sdk/purview/azure-analytics-purview-sharing/README.md index 5e3c6bd11f09..3bc559e8af79 100644 --- a/sdk/purview/azure-analytics-purview-sharing/README.md +++ b/sdk/purview/azure-analytics-purview-sharing/README.md @@ -43,7 +43,7 @@ Various documentation is available to help you get started com.azure azure-analytics-purview-sharing - 1.0.0-beta.2 + 1.0.0-beta.3 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/purview/azure-analytics-purview-sharing/pom.xml b/sdk/purview/azure-analytics-purview-sharing/pom.xml index 4ba24fe0be79..4c3f21b7e56f 100644 --- a/sdk/purview/azure-analytics-purview-sharing/pom.xml +++ b/sdk/purview/azure-analytics-purview-sharing/pom.xml @@ -53,23 +53,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/purview/azure-analytics-purview-workflow/README.md b/sdk/purview/azure-analytics-purview-workflow/README.md index 5da668faa8f0..b78661ea0502 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.14.2 + 1.15.3 ``` @@ -111,5 +111,5 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [azure_identity]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/identity/azure-identity/README.md [app_registration]:https://learn.microsoft.com/azure/active-directory/develop/quickstart-register-app [username_password_credential]: https://learn.microsoft.com/java/api/com.azure.identity.usernamepasswordcredential?source=recommendations&view=azure-java-stable -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fpurview%2Fazure-analytics-purview-workflow%2FREADME.png) + diff --git a/sdk/purview/azure-analytics-purview-workflow/pom.xml b/sdk/purview/azure-analytics-purview-workflow/pom.xml index b828178732a1..70d1df8eb956 100644 --- a/sdk/purview/azure-analytics-purview-workflow/pom.xml +++ b/sdk/purview/azure-analytics-purview-workflow/pom.xml @@ -55,23 +55,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/purview/azure-resourcemanager-purview/README.md b/sdk/purview/azure-resourcemanager-purview/README.md index a191eb62afe5..5e39fe0e3d11 100644 --- a/sdk/purview/azure-resourcemanager-purview/README.md +++ b/sdk/purview/azure-resourcemanager-purview/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-purview - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fpurview%2Fazure-resourcemanager-purview%2FREADME.png) + diff --git a/sdk/purview/azure-resourcemanager-purview/pom.xml b/sdk/purview/azure-resourcemanager-purview/pom.xml index d9dd76040e55..1a03264456a1 100644 --- a/sdk/purview/azure-resourcemanager-purview/pom.xml +++ b/sdk/purview/azure-resourcemanager-purview/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/quantum/azure-quantum-jobs/README.md b/sdk/quantum/azure-quantum-jobs/README.md index 52054319359b..a28399de73cd 100644 --- a/sdk/quantum/azure-quantum-jobs/README.md +++ b/sdk/quantum/azure-quantum-jobs/README.md @@ -20,7 +20,7 @@ Install the Azure Quantum Jobs client library for Java by adding the following t com.azure azure-quantum-jobs - 1.0.0-beta.1 + 1.0.0-beta.2 ``` [//]: # ({x-version-update-end}) @@ -226,4 +226,4 @@ additional questions or comments. [coc_contact]: mailto:opencode@microsoft.com [samples]: https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/quantum/azure-quantum-jobs/src/samples/java/com/azure/quantum/jobs -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Ftemplate%2Fazure-sdk-template%2FREADME.png) + diff --git a/sdk/quantum/azure-quantum-jobs/pom.xml b/sdk/quantum/azure-quantum-jobs/pom.xml index 859de43449a7..2463ff53e143 100644 --- a/sdk/quantum/azure-quantum-jobs/pom.xml +++ b/sdk/quantum/azure-quantum-jobs/pom.xml @@ -49,17 +49,17 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 @@ -67,19 +67,19 @@ com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-storage-blob - 12.29.0 + 12.29.1 test diff --git a/sdk/quantum/azure-resourcemanager-quantum/README.md b/sdk/quantum/azure-resourcemanager-quantum/README.md index 33fc9390ddee..2bead3ccc12a 100644 --- a/sdk/quantum/azure-resourcemanager-quantum/README.md +++ b/sdk/quantum/azure-resourcemanager-quantum/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-quantum - 1.0.0-beta.3 + 1.0.0-beta.4 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fquantum%2Fazure-resourcemanager-quantum%2FREADME.png) + diff --git a/sdk/quantum/azure-resourcemanager-quantum/pom.xml b/sdk/quantum/azure-resourcemanager-quantum/pom.xml index 6a8ffb3075fa..604ab3032ebe 100644 --- a/sdk/quantum/azure-resourcemanager-quantum/pom.xml +++ b/sdk/quantum/azure-resourcemanager-quantum/pom.xml @@ -52,23 +52,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/qumulo/azure-resourcemanager-qumulo/README.md b/sdk/qumulo/azure-resourcemanager-qumulo/README.md index f84256225caa..a7d61f09178f 100644 --- a/sdk/qumulo/azure-resourcemanager-qumulo/README.md +++ b/sdk/qumulo/azure-resourcemanager-qumulo/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-qumulo - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fqumulo%2Fazure-resourcemanager-qumulo%2FREADME.png) + diff --git a/sdk/qumulo/azure-resourcemanager-qumulo/pom.xml b/sdk/qumulo/azure-resourcemanager-qumulo/pom.xml index 6ec1566a4257..90a626d0dbea 100644 --- a/sdk/qumulo/azure-resourcemanager-qumulo/pom.xml +++ b/sdk/qumulo/azure-resourcemanager-qumulo/pom.xml @@ -51,28 +51,28 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/quota/azure-resourcemanager-quota/CHANGELOG.md b/sdk/quota/azure-resourcemanager-quota/CHANGELOG.md index e4427ad61abd..7958543fd4d4 100644 --- a/sdk/quota/azure-resourcemanager-quota/CHANGELOG.md +++ b/sdk/quota/azure-resourcemanager-quota/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.1.0-beta.3 (Unreleased) +## 1.2.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,391 @@ ### Other Changes +## 1.1.0 (2025-02-21) + +- Azure Resource Manager quota client library for Java. This package contains Microsoft Azure SDK for quota Management SDK. Microsoft Azure Quota Resource Provider. This Swagger is for Azure Group Quota using GroupQuota Entity. Package tag package-2025-03-01. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). + +### Features Added + +* `models.SubscriptionQuotaAllocationsListProperties` was added + +* `models.GroupQuotasEntityBasePatch` was added + +* `models.GroupQuotaRequestBase` was added + +* `models.SubscriptionQuotaAllocationsProperties` was added + +* `models.GroupQuotasEntityBase` was added + +* `models.GroupQuotasEntityPatch` was added + +* `models.SubscriptionQuotaDetails` was added + +* `models.GroupQuotas` was added + +* `models.GroupQuotaSubscriptionRequests` was added + +* `models.GroupQuotaSubscriptionRequestStatus` was added + +* `models.GroupQuotasEntityPatchProperties` was added + +* `models.SubscriptionQuotaAllocations` was added + +* `models.GroupQuotasEntityProperties` was added + +* `models.RequestState` was added + +* `models.GroupQuotaLimits` was added + +* `models.GroupQuotaLimitProperties` was added + +* `models.QuotaAllocationRequestBase` was added + +* `models.GroupQuotaSubscriptionIdProperties` was added + +* `models.GroupQuotaSubscriptions` was added + +* `models.SubscriptionQuotaAllocationsList` was added + +* `models.QuotaAllocationRequestStatusList` was added + +* `models.GroupQuotaSubscriptionAllocationRequests` was added + +* `models.AllocatedQuotaToSubscriptionList` was added + +* `models.SubmittedResourceRequestStatusProperties` was added + +* `models.SubmittedResourceRequestStatus` was added + +* `models.SubmittedResourceRequestStatusList` was added + +* `models.GroupQuotaList` was added + +* `models.QuotaAllocationRequestStatus` was added + +* `models.LroResponseProperties` was added + +* `models.LroResponse` was added + +* `models.GroupQuotaSubscriptionRequestStatusProperties` was added + +* `models.GroupQuotaLimitsRequests` was added + +* `models.GroupQuotaLimit` was added + +* `models.GroupQuotaLimitList` was added + +* `models.GroupQuotaDetails` was added + +* `models.GroupQuotaSubscriptionAllocations` was added + +* `models.GroupQuotaLimitListProperties` was added + +* `models.GroupQuotaSubscriptionRequestStatusList` was added + +* `models.GroupQuotaSubscriptionIdList` was added + +* `models.AllocatedToSubscription` was added + +* `models.GroupQuotasEntity` was added + +* `models.GroupQuotaSubscriptionId` was added + +#### `models.UsagesLimits` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.UsagesObject` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.QuotaProperties` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.ServiceErrorDetail` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `QuotaManager` was modified + +* `groupQuotas()` was added +* `groupQuotaSubscriptions()` was added +* `groupQuotaSubscriptionAllocationRequests()` was added +* `groupQuotaSubscriptionRequests()` was added +* `groupQuotaLimits()` was added +* `groupQuotaLimitsRequests()` was added +* `groupQuotaSubscriptionAllocations()` was added + +#### `models.ResourceName` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.QuotaLimits` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.QuotaRequestDetailsList` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.OperationDisplay` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.LimitObject` was modified + +* `limitObjectType()` was added +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.LimitJsonObject` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `limitObjectType()` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.SubRequest` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.OperationList` was modified + +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.UsagesProperties` was modified + +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +## 1.1.0-beta.3 (2025-01-22) + +- Azure Resource Manager quota client library for Java. This package contains Microsoft Azure SDK for quota Management SDK. Microsoft Azure Quota Resource Provider. This Swagger is for Azure Group Quota using GroupQuota Entity. Package tag package-2024-12-18-preview. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). + +### Breaking Changes + +#### `models.GroupingId` was removed + +#### `models.EnforcementState` was removed + +#### `models.GroupQuotasEnforcementResponse` was removed + +#### `models.ResourceUsages` was removed + +#### `models.AdditionalAttributes` was removed + +#### `models.GroupingIdType` was removed + +#### `models.GroupQuotasEnforcementListResponse` was removed + +#### `models.EnvironmentType` was removed + +#### `models.GroupQuotasEnforcementResponseProperties` was removed + +#### `models.GroupQuotaLocationSettings` was removed + +#### `models.ResourceUsageList` was removed + +#### `models.AdditionalAttributesPatch` was removed + +#### `models.GroupQuotaUsages` was removed + +#### `models.GroupQuotaUsagesBase` was removed + +#### `models.GroupQuotasEntityBase` was modified + +* `withAdditionalAttributes(models.AdditionalAttributes)` was removed +* `additionalAttributes()` was removed + +#### `models.GroupQuotasEntityPatch` was modified + +* `models.GroupQuotasEntityBasePatch properties()` -> `models.GroupQuotasEntityPatchProperties properties()` +* `withProperties(models.GroupQuotasEntityBasePatch)` was removed + +#### `models.GroupQuotaLimits` was modified + +* `get(java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String)` was removed +* `com.azure.core.http.rest.PagedIterable list(java.lang.String,java.lang.String,java.lang.String,java.lang.String)` -> `models.GroupQuotaLimitList list(java.lang.String,java.lang.String,java.lang.String,java.lang.String)` +* `list(java.lang.String,java.lang.String,java.lang.String,java.lang.String,com.azure.core.util.Context)` was removed +* `getWithResponse(java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,com.azure.core.util.Context)` was removed + +#### `models.GroupQuotaLimitList` was modified + +* `value()` was removed +* `toJson(com.azure.json.JsonWriter)` was removed +* `nextLink()` was removed +* `withValue(java.util.List)` was removed +* `validate()` was removed +* `fromJson(com.azure.json.JsonReader)` was removed + +#### `models.GroupQuotasEntity` was modified + +* `models.GroupQuotasEntityBase properties()` -> `models.GroupQuotasEntityProperties properties()` + +#### `models.GroupQuotasEntityBasePatch` was modified + +* `withAdditionalAttributes(models.AdditionalAttributesPatch)` was removed +* `additionalAttributes()` was removed + +#### `models.SubscriptionQuotaDetails` was modified + +* `region()` was removed +* `withRegion(java.lang.String)` was removed + +#### `models.SubscriptionQuotaAllocations` was modified + +* `innerModel()` was removed +* `name()` was removed +* `type()` was removed +* `id()` was removed +* `systemData()` was removed +* `models.SubscriptionQuotaDetails properties()` -> `models.SubscriptionQuotaAllocationsProperties properties()` + +#### `models.SubscriptionQuotaAllocationsList` was modified + +* `value()` was removed +* `validate()` was removed +* `toJson(com.azure.json.JsonWriter)` was removed +* `withValue(java.util.List)` was removed +* `fromJson(com.azure.json.JsonReader)` was removed +* `nextLink()` was removed + +#### `QuotaManager` was modified + +* `groupQuotaLocationSettings()` was removed +* `groupQuotaUsages()` was removed + +#### `models.GroupQuotaSubscriptionAllocationRequests` was modified + +* `getWithResponse(java.lang.String,java.lang.String,java.lang.String,com.azure.core.util.Context)` was removed +* `get(java.lang.String,java.lang.String,java.lang.String)` was removed +* `createOrUpdate(java.lang.String,java.lang.String,java.lang.String,java.lang.String,fluent.models.QuotaAllocationRequestStatusInner,com.azure.core.util.Context)` was removed +* `createOrUpdate(java.lang.String,java.lang.String,java.lang.String,java.lang.String,fluent.models.QuotaAllocationRequestStatusInner)` was removed +* `update(java.lang.String,java.lang.String,java.lang.String,java.lang.String,fluent.models.QuotaAllocationRequestStatusInner)` was removed +* `update(java.lang.String,java.lang.String,java.lang.String,java.lang.String,fluent.models.QuotaAllocationRequestStatusInner,com.azure.core.util.Context)` was removed + +#### `models.GroupQuotaLimitsRequests` was modified + +* `createOrUpdate(java.lang.String,java.lang.String,java.lang.String,java.lang.String)` was removed +* `createOrUpdate(java.lang.String,java.lang.String,java.lang.String,java.lang.String,fluent.models.SubmittedResourceRequestStatusInner,com.azure.core.util.Context)` was removed +* `models.SubmittedResourceRequestStatus update(java.lang.String,java.lang.String,java.lang.String,java.lang.String)` -> `models.GroupQuotaLimitList update(java.lang.String,java.lang.String,java.lang.String,java.lang.String)` +* `update(java.lang.String,java.lang.String,java.lang.String,java.lang.String,fluent.models.SubmittedResourceRequestStatusInner,com.azure.core.util.Context)` was removed + +#### `models.GroupQuotaLimit` was modified + +* `type()` was removed +* `innerModel()` was removed +* `name()` was removed +* `systemData()` was removed +* `id()` was removed +* `models.GroupQuotaDetails properties()` -> `models.GroupQuotaLimitProperties properties()` + +#### `models.GroupQuotaDetails` was modified + +* `withRegion(java.lang.String)` was removed +* `region()` was removed + +#### `models.GroupQuotaSubscriptionAllocations` was modified + +* `get(java.lang.String,java.lang.String,java.lang.String,java.lang.String)` was removed +* `getWithResponse(java.lang.String,java.lang.String,java.lang.String,java.lang.String,com.azure.core.util.Context)` was removed +* `list(java.lang.String,java.lang.String,java.lang.String)` was removed +* `list(java.lang.String,java.lang.String,java.lang.String,com.azure.core.util.Context)` was removed + +### Features Added + +* `models.SubscriptionQuotaAllocationsProperties` was added + +* `models.GroupQuotasEntityPatchProperties` was added + +* `models.GroupQuotasEntityProperties` was added + +* `models.GroupQuotaLimitProperties` was added + +* `models.GroupQuotaLimitListProperties` was added + +* `models.SubscriptionQuotaAllocationsListProperties` was added + +#### `models.GroupQuotasEntityPatch` was modified + +* `withProperties(models.GroupQuotasEntityPatchProperties)` was added + +#### `models.GroupQuotaLimits` was modified + +* `listWithResponse(java.lang.String,java.lang.String,java.lang.String,java.lang.String,com.azure.core.util.Context)` was added + +#### `models.GroupQuotaLimitList` was modified + +* `systemData()` was added +* `innerModel()` was added +* `id()` was added +* `name()` was added +* `type()` was added +* `properties()` was added + +#### `models.SubscriptionQuotaDetails` was modified + +* `resourceName()` was added +* `withResourceName(java.lang.String)` was added + +#### `models.SubscriptionQuotaAllocations` was modified + +* `validate()` was added +* `withProperties(models.SubscriptionQuotaAllocationsProperties)` was added +* `toJson(com.azure.json.JsonWriter)` was added +* `fromJson(com.azure.json.JsonReader)` was added + +#### `models.GroupQuotaSubscriptionIdProperties` was modified + +* `withSubscriptionId(java.lang.String)` was added + +#### `models.SubscriptionQuotaAllocationsList` was modified + +* `properties()` was added +* `innerModel()` was added +* `name()` was added +* `type()` was added +* `systemData()` was added +* `id()` was added + +#### `models.GroupQuotaSubscriptionAllocationRequests` was modified + +* `update(java.lang.String,java.lang.String,java.lang.String,java.lang.String,fluent.models.SubscriptionQuotaAllocationsListInner,com.azure.core.util.Context)` was added +* `update(java.lang.String,java.lang.String,java.lang.String,java.lang.String,fluent.models.SubscriptionQuotaAllocationsListInner)` was added +* `getWithResponse(java.lang.String,java.lang.String,java.lang.String,java.lang.String,com.azure.core.util.Context)` was added +* `get(java.lang.String,java.lang.String,java.lang.String,java.lang.String)` was added + +#### `models.GroupQuotaLimitsRequests` was modified + +* `update(java.lang.String,java.lang.String,java.lang.String,java.lang.String,fluent.models.GroupQuotaLimitListInner,com.azure.core.util.Context)` was added + +#### `models.GroupQuotaLimit` was modified + +* `validate()` was added +* `withProperties(models.GroupQuotaLimitProperties)` was added +* `fromJson(com.azure.json.JsonReader)` was added +* `toJson(com.azure.json.JsonWriter)` was added + +#### `models.GroupQuotaDetails` was modified + +* `withResourceName(java.lang.String)` was added +* `resourceName()` was added + +#### `models.GroupQuotaSubscriptionAllocations` was modified + +* `listWithResponse(java.lang.String,java.lang.String,java.lang.String,java.lang.String,com.azure.core.util.Context)` was added +* `list(java.lang.String,java.lang.String,java.lang.String,java.lang.String)` was added + ## 1.1.0-beta.2 (2024-12-04) - Azure Resource Manager quota client library for Java. This package contains Microsoft Azure SDK for quota Management SDK. Microsoft Azure Quota Resource Provider. This Swagger is for Azure Group Quota using GroupQuota Entity. Package tag package-2023-06-01-preview. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). diff --git a/sdk/quota/azure-resourcemanager-quota/README.md b/sdk/quota/azure-resourcemanager-quota/README.md index 5ad19112c221..bc7b5044c409 100644 --- a/sdk/quota/azure-resourcemanager-quota/README.md +++ b/sdk/quota/azure-resourcemanager-quota/README.md @@ -2,7 +2,7 @@ Azure Resource Manager quota client library for Java. -This package contains Microsoft Azure SDK for quota Management SDK. Microsoft Azure Quota Resource Provider. This Swagger is for Azure Group Quota using GroupQuota Entity. Package tag package-2023-06-01-preview. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). +This package contains Microsoft Azure SDK for quota Management SDK. Microsoft Azure Quota Resource Provider. This Swagger is for Azure Group Quota using GroupQuota Entity. Package tag package-2025-03-01. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). ## We'd love to hear your feedback @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-quota - 1.1.0-beta.2 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -52,7 +52,7 @@ Azure subscription ID can be configured via `AZURE_SUBSCRIPTION_ID` environment Assuming the use of the `DefaultAzureCredential` credential class, the client can be authenticated using the following code: ```java -AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); +AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); @@ -60,7 +60,7 @@ QuotaManager manager = QuotaManager .authenticate(credential, profile); ``` -The sample code assumes global Azure. Please change `AzureEnvironment.AZURE` variable if otherwise. +The sample code assumes global Azure. Please change the `AzureCloud.AZURE_PUBLIC_CLOUD` variable if otherwise. See [Authentication][authenticate] for more options. @@ -100,5 +100,3 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [cg]: https://github.com/Azure/azure-sdk-for-java/blob/main/CONTRIBUTING.md [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ - -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fquota%2Fazure-resourcemanager-quota%2FREADME.png) diff --git a/sdk/quota/azure-resourcemanager-quota/SAMPLE.md b/sdk/quota/azure-resourcemanager-quota/SAMPLE.md index 0bbb13249f62..6a0bb026a974 100644 --- a/sdk/quota/azure-resourcemanager-quota/SAMPLE.md +++ b/sdk/quota/azure-resourcemanager-quota/SAMPLE.md @@ -3,31 +3,20 @@ ## GroupQuotaLimits -- [Get](#groupquotalimits_get) - [List](#groupquotalimits_list) ## GroupQuotaLimitsRequest -- [CreateOrUpdate](#groupquotalimitsrequest_createorupdate) - [Get](#groupquotalimitsrequest_get) - [List](#groupquotalimitsrequest_list) - [Update](#groupquotalimitsrequest_update) -## GroupQuotaLocationSettings - -- [CreateOrUpdate](#groupquotalocationsettings_createorupdate) -- [Get](#groupquotalocationsettings_get) -- [List](#groupquotalocationsettings_list) -- [Update](#groupquotalocationsettings_update) - ## GroupQuotaSubscriptionAllocation -- [Get](#groupquotasubscriptionallocation_get) - [List](#groupquotasubscriptionallocation_list) ## GroupQuotaSubscriptionAllocationRequest -- [CreateOrUpdate](#groupquotasubscriptionallocationrequest_createorupdate) - [Get](#groupquotasubscriptionallocationrequest_get) - [List](#groupquotasubscriptionallocationrequest_list) - [Update](#groupquotasubscriptionallocationrequest_update) @@ -45,10 +34,6 @@ - [List](#groupquotasubscriptions_list) - [Update](#groupquotasubscriptions_update) -## GroupQuotaUsages - -- [List](#groupquotausages_list) - ## GroupQuotas - [CreateOrUpdate](#groupquotas_createorupdate) @@ -77,31 +62,6 @@ - [Get](#usages_get) - [List](#usages_list) -### GroupQuotaLimits_Get - -```java -/** - * Samples for GroupQuotaLimits Get. - */ -public final class GroupQuotaLimitsGetSamples { - /* - * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotaLimits/ - * GetGroupQuotaLimits-Compute.json - */ - /** - * Sample code: GroupQuotaLimits_Get_Request_ForCompute. - * - * @param manager Entry point to QuotaManager. - */ - public static void groupQuotaLimitsGetRequestForCompute(com.azure.resourcemanager.quota.QuotaManager manager) { - manager.groupQuotaLimits() - .getWithResponse("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", "cores", - "location eq westus", com.azure.core.util.Context.NONE); - } -} -``` - ### GroupQuotaLimits_List ```java @@ -111,48 +71,22 @@ public final class GroupQuotaLimitsGetSamples { public final class GroupQuotaLimitsListSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotaLimits/ + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GroupQuotaLimits/ * ListGroupQuotaLimits-Compute.json */ /** - * Sample code: GroupQuotaLimits_List_Request_ForCompute. + * Sample code: GroupQuotaLimits_Get_Request_ForCompute. * * @param manager Entry point to QuotaManager. */ - public static void groupQuotaLimitsListRequestForCompute(com.azure.resourcemanager.quota.QuotaManager manager) { + public static void groupQuotaLimitsGetRequestForCompute(com.azure.resourcemanager.quota.QuotaManager manager) { manager.groupQuotaLimits() - .list("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", "location eq westus", + .listWithResponse("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", "westus", com.azure.core.util.Context.NONE); } } ``` -### GroupQuotaLimitsRequest_CreateOrUpdate - -```java - -/** - * Samples for GroupQuotaLimitsRequest CreateOrUpdate. - */ -public final class GroupQuotaLimitsRequestCreateOrUpdateSamples { - /* - * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotaLimitsRequests - * /PutGroupQuotaLimitsRequests-Compute.json - */ - /** - * Sample code: GroupQuotaLimitsRequests_CreateOrUpdate. - * - * @param manager Entry point to QuotaManager. - */ - public static void groupQuotaLimitsRequestsCreateOrUpdate(com.azure.resourcemanager.quota.QuotaManager manager) { - manager.groupQuotaLimitsRequests() - .createOrUpdate("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", - "standardav2family", null, com.azure.core.util.Context.NONE); - } -} -``` - ### GroupQuotaLimitsRequest_Get ```java @@ -162,8 +96,8 @@ public final class GroupQuotaLimitsRequestCreateOrUpdateSamples { public final class GroupQuotaLimitsRequestGetSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotaLimitsRequests - * /GroupQuotaLimitsRequests_Get.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GroupQuotaLimitsRequests/ + * GroupQuotaLimitsRequests_Get.json */ /** * Sample code: GroupQuotaLimitsRequests_Get. @@ -187,8 +121,8 @@ public final class GroupQuotaLimitsRequestGetSamples { public final class GroupQuotaLimitsRequestListSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotaLimitsRequests - * /GroupQuotaLimitsRequests_List.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GroupQuotaLimitsRequests/ + * GroupQuotaLimitsRequests_List.json */ /** * Sample code: GroupQuotaLimitsRequest_List. @@ -206,6 +140,11 @@ public final class GroupQuotaLimitsRequestListSamples { ### GroupQuotaLimitsRequest_Update ```java +import com.azure.resourcemanager.quota.fluent.models.GroupQuotaLimitListInner; +import com.azure.resourcemanager.quota.models.GroupQuotaLimit; +import com.azure.resourcemanager.quota.models.GroupQuotaLimitListProperties; +import com.azure.resourcemanager.quota.models.GroupQuotaLimitProperties; +import java.util.Arrays; /** * Samples for GroupQuotaLimitsRequest Update. @@ -213,8 +152,8 @@ public final class GroupQuotaLimitsRequestListSamples { public final class GroupQuotaLimitsRequestUpdateSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotaLimitsRequests - * /PatchGroupQuotaLimitsRequests-Compute.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GroupQuotaLimitsRequests/ + * PatchGroupQuotaLimitsRequests-Compute.json */ /** * Sample code: GroupQuotaLimitsRequests_Update. @@ -223,168 +162,22 @@ public final class GroupQuotaLimitsRequestUpdateSamples { */ public static void groupQuotaLimitsRequestsUpdate(com.azure.resourcemanager.quota.QuotaManager manager) { manager.groupQuotaLimitsRequests() - .update("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", "standardav2family", - null, com.azure.core.util.Context.NONE); - } -} -``` - -### GroupQuotaLocationSettings_CreateOrUpdate - -```java -import com.azure.resourcemanager.quota.fluent.models.GroupQuotasEnforcementResponseInner; -import com.azure.resourcemanager.quota.models.EnforcementState; -import com.azure.resourcemanager.quota.models.GroupQuotasEnforcementResponseProperties; - -/** - * Samples for GroupQuotaLocationSettings CreateOrUpdate. - */ -public final class GroupQuotaLocationSettingsCreateOrUpdateSamples { - /* - * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotasEnforcement/ - * PutGroupQuotaEnforcement.json - */ - /** - * Sample code: GroupQuotaLocationSettings_CreateOrUpdate. - * - * @param manager Entry point to QuotaManager. - */ - public static void groupQuotaLocationSettingsCreateOrUpdate(com.azure.resourcemanager.quota.QuotaManager manager) { - manager.groupQuotaLocationSettings() - .createOrUpdate("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", "eastus", - new GroupQuotasEnforcementResponseInner().withProperties( - new GroupQuotasEnforcementResponseProperties().withEnforcementEnabled(EnforcementState.ENABLED)), - com.azure.core.util.Context.NONE); - } - - /* - * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotasEnforcement/ - * PutGroupQuotaEnforcementFailed.json - */ - /** - * Sample code: GroupQuotaLocationSettings_CreateOrUpdate_Failed. - * - * @param manager Entry point to QuotaManager. - */ - public static void - groupQuotaLocationSettingsCreateOrUpdateFailed(com.azure.resourcemanager.quota.QuotaManager manager) { - manager.groupQuotaLocationSettings() - .createOrUpdate("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", "eastus", - new GroupQuotasEnforcementResponseInner().withProperties( - new GroupQuotasEnforcementResponseProperties().withEnforcementEnabled(EnforcementState.ENABLED)), - com.azure.core.util.Context.NONE); - } -} -``` - -### GroupQuotaLocationSettings_Get - -```java -/** - * Samples for GroupQuotaLocationSettings Get. - */ -public final class GroupQuotaLocationSettingsGetSamples { - /* - * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotasEnforcement/ - * GetGroupQuotaEnforcement.json - */ - /** - * Sample code: GroupQuotasEnforcement_Get. - * - * @param manager Entry point to QuotaManager. - */ - public static void groupQuotasEnforcementGet(com.azure.resourcemanager.quota.QuotaManager manager) { - manager.groupQuotaLocationSettings() - .getWithResponse("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", "eastus", - com.azure.core.util.Context.NONE); - } -} -``` - -### GroupQuotaLocationSettings_List - -```java -/** - * Samples for GroupQuotaLocationSettings List. - */ -public final class GroupQuotaLocationSettingsListSamples { - /* - * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotasEnforcement/ - * ListGroupQuotaEnforcement.json - */ - /** - * Sample code: GroupQuotaEnforcement_List. - * - * @param manager Entry point to QuotaManager. - */ - public static void groupQuotaEnforcementList(com.azure.resourcemanager.quota.QuotaManager manager) { - manager.groupQuotaLocationSettings() - .list("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", - com.azure.core.util.Context.NONE); - } -} -``` - -### GroupQuotaLocationSettings_Update - -```java -import com.azure.resourcemanager.quota.fluent.models.GroupQuotasEnforcementResponseInner; -import com.azure.resourcemanager.quota.models.EnforcementState; -import com.azure.resourcemanager.quota.models.GroupQuotasEnforcementResponseProperties; - -/** - * Samples for GroupQuotaLocationSettings Update. - */ -public final class GroupQuotaLocationSettingsUpdateSamples { - /* - * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotasEnforcement/ - * PatchGroupQuotaEnforcement.json - */ - /** - * Sample code: GroupQuotaLocationSettings_Patch. - * - * @param manager Entry point to QuotaManager. - */ - public static void groupQuotaLocationSettingsPatch(com.azure.resourcemanager.quota.QuotaManager manager) { - manager.groupQuotaLocationSettings() - .update("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", "eastus", - new GroupQuotasEnforcementResponseInner().withProperties( - new GroupQuotasEnforcementResponseProperties().withEnforcementEnabled(EnforcementState.ENABLED)), + .update("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", "westus", + new GroupQuotaLimitListInner() + .withProperties(new GroupQuotaLimitListProperties().withValue(Arrays.asList( + new GroupQuotaLimit() + .withProperties(new GroupQuotaLimitProperties().withResourceName("standardddv4family") + .withLimit(110L) + .withComment("Contoso requires more quota.")), + new GroupQuotaLimit() + .withProperties(new GroupQuotaLimitProperties().withResourceName("standardav2family") + .withLimit(110L) + .withComment("Contoso requires more quota."))))), com.azure.core.util.Context.NONE); } } ``` -### GroupQuotaSubscriptionAllocation_Get - -```java -/** - * Samples for GroupQuotaSubscriptionAllocation Get. - */ -public final class GroupQuotaSubscriptionAllocationGetSamples { - /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ - * SubscriptionQuotaAllocation/SubscriptionQuotaAllocation_Get-Compute.json - */ - /** - * Sample code: SubscriptionQuotaAllocation_Get_Request_ForCompute. - * - * @param manager Entry point to QuotaManager. - */ - public static void - subscriptionQuotaAllocationGetRequestForCompute(com.azure.resourcemanager.quota.QuotaManager manager) { - manager.groupQuotaSubscriptionAllocations() - .getWithResponse("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "standardav2family", - "provider eq Microsoft.Compute & location eq westus", com.azure.core.util.Context.NONE); - } -} -``` - ### GroupQuotaSubscriptionAllocation_List ```java @@ -393,8 +186,9 @@ public final class GroupQuotaSubscriptionAllocationGetSamples { */ public final class GroupQuotaSubscriptionAllocationListSamples { /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ - * SubscriptionQuotaAllocation/SubscriptionQuotaAllocation_List-Compute.json + * x-ms-original-file: + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/SubscriptionQuotaAllocation/ + * SubscriptionQuotaAllocation_List-Compute.json */ /** * Sample code: SubscriptionQuotaAllocation_List_ForCompute. @@ -403,38 +197,7 @@ public final class GroupQuotaSubscriptionAllocationListSamples { */ public static void subscriptionQuotaAllocationListForCompute(com.azure.resourcemanager.quota.QuotaManager manager) { manager.groupQuotaSubscriptionAllocations() - .list("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", - "provider eq Microsoft.Compute & location eq westus", com.azure.core.util.Context.NONE); - } -} -``` - -### GroupQuotaSubscriptionAllocationRequest_CreateOrUpdate - -```java -import com.azure.resourcemanager.quota.fluent.models.QuotaAllocationRequestStatusInner; -import com.azure.resourcemanager.quota.models.QuotaAllocationRequestBase; - -/** - * Samples for GroupQuotaSubscriptionAllocationRequest CreateOrUpdate. - */ -public final class GroupQuotaSubscriptionAllocationRequestCreateOrUpdateSamples { - /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ - * SubscriptionQuotaAllocationRequests/PutSubscriptionQuotaAllocationRequest-Compute.json - */ - /** - * Sample code: SubscriptionQuotaAllocation_Put_Request_ForCompute. - * - * @param manager Entry point to QuotaManager. - */ - public static void - subscriptionQuotaAllocationPutRequestForCompute(com.azure.resourcemanager.quota.QuotaManager manager) { - manager.groupQuotaSubscriptionAllocationRequests() - .createOrUpdate("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", - "standardav2family", - new QuotaAllocationRequestStatusInner() - .withRequestedResource(new QuotaAllocationRequestBase().withLimit(10L).withRegion("westus")), + .listWithResponse("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", "westus", com.azure.core.util.Context.NONE); } } @@ -448,7 +211,7 @@ public final class GroupQuotaSubscriptionAllocationRequestCreateOrUpdateSamples */ public final class GroupQuotaSubscriptionAllocationRequestGetSamples { /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ + * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/ * SubscriptionQuotaAllocationRequests/SubscriptionQuotaAllocationRequests_Get-Compute.json */ /** @@ -459,7 +222,7 @@ public final class GroupQuotaSubscriptionAllocationRequestGetSamples { public static void subscriptionQuotaAllocationRequestsGetRequestForCompute(com.azure.resourcemanager.quota.QuotaManager manager) { manager.groupQuotaSubscriptionAllocationRequests() - .getWithResponse("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", + .getWithResponse("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", "AE000000-0000-0000-0000-00000000000A", com.azure.core.util.Context.NONE); } } @@ -473,7 +236,7 @@ public final class GroupQuotaSubscriptionAllocationRequestGetSamples { */ public final class GroupQuotaSubscriptionAllocationRequestListSamples { /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ + * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/ * SubscriptionQuotaAllocationRequests/SubscriptionQuotaAllocationRequests_List-Compute.json */ /** @@ -493,15 +256,18 @@ public final class GroupQuotaSubscriptionAllocationRequestListSamples { ### GroupQuotaSubscriptionAllocationRequest_Update ```java -import com.azure.resourcemanager.quota.fluent.models.QuotaAllocationRequestStatusInner; -import com.azure.resourcemanager.quota.models.QuotaAllocationRequestBase; +import com.azure.resourcemanager.quota.fluent.models.SubscriptionQuotaAllocationsListInner; +import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocations; +import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocationsListProperties; +import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocationsProperties; +import java.util.Arrays; /** * Samples for GroupQuotaSubscriptionAllocationRequest Update. */ public final class GroupQuotaSubscriptionAllocationRequestUpdateSamples { /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ + * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/ * SubscriptionQuotaAllocationRequests/PatchSubscriptionQuotaAllocationRequest-Compute.json */ /** @@ -512,9 +278,15 @@ public final class GroupQuotaSubscriptionAllocationRequestUpdateSamples { public static void subscriptionQuotaAllocationPatchRequestForCompute(com.azure.resourcemanager.quota.QuotaManager manager) { manager.groupQuotaSubscriptionAllocationRequests() - .update("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", "standardav2family", - new QuotaAllocationRequestStatusInner() - .withRequestedResource(new QuotaAllocationRequestBase().withLimit(10L).withRegion("westus")), + .update("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", "westus", + new SubscriptionQuotaAllocationsListInner() + .withProperties(new SubscriptionQuotaAllocationsListProperties().withValue(Arrays.asList( + new SubscriptionQuotaAllocations().withProperties( + new SubscriptionQuotaAllocationsProperties().withResourceName("standardddv4family") + .withLimit(110L)), + new SubscriptionQuotaAllocations().withProperties( + new SubscriptionQuotaAllocationsProperties().withResourceName("standardav2family") + .withLimit(110L))))), com.azure.core.util.Context.NONE); } } @@ -529,7 +301,7 @@ public final class GroupQuotaSubscriptionAllocationRequestUpdateSamples { public final class GroupQuotaSubscriptionRequestsGetSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/SubscriptionRequests/ + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/SubscriptionRequests/ * SubscriptionRequests_Get.json */ /** @@ -554,7 +326,7 @@ public final class GroupQuotaSubscriptionRequestsGetSamples { public final class GroupQuotaSubscriptionRequestsListSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/SubscriptionRequests/ + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/SubscriptionRequests/ * SubscriptionRequests_List.json */ /** @@ -578,8 +350,8 @@ public final class GroupQuotaSubscriptionRequestsListSamples { public final class GroupQuotaSubscriptionsCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotasSubscriptions - * /PutGroupQuotasSubscription.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GroupQuotasSubscriptions/ + * PutGroupQuotasSubscription.json */ /** * Sample code: GroupQuotaSubscriptions_Put_Subscriptions. @@ -602,8 +374,8 @@ public final class GroupQuotaSubscriptionsCreateOrUpdateSamples { public final class GroupQuotaSubscriptionsDeleteSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotasSubscriptions - * /DeleteGroupQuotaSubscriptions.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GroupQuotasSubscriptions/ + * DeleteGroupQuotaSubscriptions.json */ /** * Sample code: GroupQuotaSubscriptions_Delete_Subscriptions. @@ -627,8 +399,8 @@ public final class GroupQuotaSubscriptionsDeleteSamples { public final class GroupQuotaSubscriptionsGetSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotasSubscriptions - * /GetGroupQuotaSubscriptions.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GroupQuotasSubscriptions/ + * GetGroupQuotaSubscriptions.json */ /** * Sample code: GroupQuotaSubscriptions_Get_Subscriptions. @@ -651,8 +423,8 @@ public final class GroupQuotaSubscriptionsGetSamples { public final class GroupQuotaSubscriptionsListSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotasSubscriptions - * /ListGroupQuotaSubscriptions.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GroupQuotasSubscriptions/ + * ListGroupQuotaSubscriptions.json */ /** * Sample code: GroupQuotaSubscriptions_List_Subscriptions. @@ -675,8 +447,8 @@ public final class GroupQuotaSubscriptionsListSamples { public final class GroupQuotaSubscriptionsUpdateSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotasSubscriptions - * /PatchGroupQuotasSubscription.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GroupQuotasSubscriptions/ + * PatchGroupQuotasSubscription.json */ /** * Sample code: GroupQuotaSubscriptions_Patch_Subscriptions. @@ -690,40 +462,11 @@ public final class GroupQuotaSubscriptionsUpdateSamples { } ``` -### GroupQuotaUsages_List - -```java -/** - * Samples for GroupQuotaUsages List. - */ -public final class GroupQuotaUsagesListSamples { - /* - * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotaUsages/ - * GetGroupQuotaUsages.json - */ - /** - * Sample code: GroupQuotasUsages_List. - * - * @param manager Entry point to QuotaManager. - */ - public static void groupQuotasUsagesList(com.azure.resourcemanager.quota.QuotaManager manager) { - manager.groupQuotaUsages() - .list("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", "westus", - com.azure.core.util.Context.NONE); - } -} -``` - ### GroupQuotas_CreateOrUpdate ```java import com.azure.resourcemanager.quota.fluent.models.GroupQuotasEntityInner; -import com.azure.resourcemanager.quota.models.AdditionalAttributes; -import com.azure.resourcemanager.quota.models.EnvironmentType; -import com.azure.resourcemanager.quota.models.GroupQuotasEntityBase; -import com.azure.resourcemanager.quota.models.GroupingId; -import com.azure.resourcemanager.quota.models.GroupingIdType; +import com.azure.resourcemanager.quota.models.GroupQuotasEntityProperties; /** * Samples for GroupQuotas CreateOrUpdate. @@ -731,8 +474,7 @@ import com.azure.resourcemanager.quota.models.GroupingIdType; public final class GroupQuotasCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotas/ - * PutGroupQuotas.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GroupQuotas/PutGroupQuotas.json */ /** * Sample code: GroupQuotas_Put_Request_ForCompute. @@ -743,13 +485,7 @@ public final class GroupQuotasCreateOrUpdateSamples { manager.groupQuotas() .createOrUpdate("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", new GroupQuotasEntityInner() - .withProperties( - new GroupQuotasEntityBase().withDisplayName("GroupQuota1") - .withAdditionalAttributes( - new AdditionalAttributes() - .withGroupId(new GroupingId().withGroupingIdType(GroupingIdType.SERVICE_TREE_ID) - .withValue("yourServiceTreeIdHere")) - .withEnvironment(EnvironmentType.PRODUCTION))), + .withProperties(new GroupQuotasEntityProperties().withDisplayName("GroupQuota1")), com.azure.core.util.Context.NONE); } } @@ -764,8 +500,8 @@ public final class GroupQuotasCreateOrUpdateSamples { public final class GroupQuotasDeleteSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotas/ - * DeleteGroupQuotas.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GroupQuotas/DeleteGroupQuotas. + * json */ /** * Sample code: GroupQuotas_Delete_Request_ForCompute. @@ -788,8 +524,7 @@ public final class GroupQuotasDeleteSamples { public final class GroupQuotasGetSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotas/ - * GetGroupQuotas.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GroupQuotas/GetGroupQuotas.json */ /** * Sample code: GroupQuotas_Get_Request_ForCompute. @@ -812,8 +547,8 @@ public final class GroupQuotasGetSamples { public final class GroupQuotasListSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotas/ - * GetGroupQuotasList.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GroupQuotas/GetGroupQuotasList. + * json */ /** * Sample code: GroupQuotas_List_Request_ForCompute. @@ -829,12 +564,8 @@ public final class GroupQuotasListSamples { ### GroupQuotas_Update ```java -import com.azure.resourcemanager.quota.models.AdditionalAttributesPatch; -import com.azure.resourcemanager.quota.models.EnvironmentType; -import com.azure.resourcemanager.quota.models.GroupQuotasEntityBasePatch; import com.azure.resourcemanager.quota.models.GroupQuotasEntityPatch; -import com.azure.resourcemanager.quota.models.GroupingId; -import com.azure.resourcemanager.quota.models.GroupingIdType; +import com.azure.resourcemanager.quota.models.GroupQuotasEntityPatchProperties; /** * Samples for GroupQuotas Update. @@ -842,8 +573,7 @@ import com.azure.resourcemanager.quota.models.GroupingIdType; public final class GroupQuotasUpdateSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotas/ - * PatchGroupQuotas.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GroupQuotas/PatchGroupQuotas.json */ /** * Sample code: GroupQuotas_Patch_Request_ForCompute. @@ -854,12 +584,7 @@ public final class GroupQuotasUpdateSamples { manager.groupQuotas() .update("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", new GroupQuotasEntityPatch() - .withProperties( - new GroupQuotasEntityBasePatch().withDisplayName("UpdatedGroupQuota1") - .withAdditionalAttributes(new AdditionalAttributesPatch() - .withGroupId(new GroupingId().withGroupingIdType(GroupingIdType.SERVICE_TREE_ID) - .withValue("UpdatedServiceTreeIdHere")) - .withEnvironment(EnvironmentType.PRODUCTION))), + .withProperties(new GroupQuotasEntityPatchProperties().withDisplayName("UpdatedGroupQuota1")), com.azure.core.util.Context.NONE); } } @@ -877,7 +602,7 @@ import com.azure.resourcemanager.quota.models.ResourceName; */ public final class QuotaCreateOrUpdateSamples { /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ + * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/ * putMachineLearningServicesQuotaRequestLowPriority.json */ /** @@ -898,7 +623,7 @@ public final class QuotaCreateOrUpdateSamples { } /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ + * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/ * putNetworkOneSkuQuotaRequestStandardSkuPublicIpAddresses.json */ /** @@ -919,8 +644,8 @@ public final class QuotaCreateOrUpdateSamples { } /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ - * putComputeOneSkuQuotaRequest.json + * x-ms-original-file: + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/putComputeOneSkuQuotaRequest.json */ /** * Sample code: Quotas_Put_Request_ForCompute. @@ -938,8 +663,8 @@ public final class QuotaCreateOrUpdateSamples { } /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ - * putNetworkOneSkuQuotaRequest.json + * x-ms-original-file: + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/putNetworkOneSkuQuotaRequest.json */ /** * Sample code: Quotas_PutRequest_ForNetwork. @@ -967,8 +692,8 @@ public final class QuotaCreateOrUpdateSamples { */ public final class QuotaGetSamples { /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ - * getNetworkOneSkuQuotaLimit.json + * x-ms-original-file: + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/getNetworkOneSkuQuotaLimit.json */ /** * Sample code: Quotas_UsagesRequest_ForNetwork. @@ -983,8 +708,8 @@ public final class QuotaGetSamples { } /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ - * getComputeOneSkuQuotaLimit.json + * x-ms-original-file: + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/getComputeOneSkuQuotaLimit.json */ /** * Sample code: Quotas_Get_Request_ForCompute. @@ -1008,7 +733,7 @@ public final class QuotaGetSamples { */ public final class QuotaListSamples { /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ + * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/ * getMachineLearningServicesQuotaLimits.json */ /** @@ -1026,8 +751,7 @@ public final class QuotaListSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/getComputeQuotaLimits. - * json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/getComputeQuotaLimits.json */ /** * Sample code: Quotas_listQuotaLimitsForCompute. @@ -1042,8 +766,7 @@ public final class QuotaListSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/getNetworkQuotaLimits. - * json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/getNetworkQuotaLimits.json */ /** * Sample code: Quotas_listQuotaLimitsForNetwork. @@ -1072,8 +795,7 @@ import com.azure.resourcemanager.quota.models.ResourceName; public final class QuotaUpdateSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/patchComputeQuotaRequest - * .json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/patchComputeQuotaRequest.json */ /** * Sample code: Quotas_Request_PatchForCompute. @@ -1093,8 +815,9 @@ public final class QuotaUpdateSamples { } /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ - * patchNetworkOneSkuQuotaRequest.json + * x-ms-original-file: + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/patchNetworkOneSkuQuotaRequest. + * json */ /** * Sample code: Quotas_Request_PatchForNetwork. @@ -1125,7 +848,7 @@ public final class QuotaUpdateSamples { public final class QuotaOperationListSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GetOperations.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GetOperations.json */ /** * Sample code: GetOperations. @@ -1146,8 +869,8 @@ public final class QuotaOperationListSamples { */ public final class QuotaRequestStatusGetSamples { /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ - * getQuotaRequestStatusFailed.json + * x-ms-original-file: + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/getQuotaRequestStatusFailed.json */ /** * Sample code: QuotaRequestFailed. @@ -1162,8 +885,8 @@ public final class QuotaRequestStatusGetSamples { } /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ - * getQuotaRequestStatusById.json + * x-ms-original-file: + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/getQuotaRequestStatusById.json */ /** * Sample code: QuotaRequestStatus. @@ -1178,8 +901,9 @@ public final class QuotaRequestStatusGetSamples { } /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ - * getQuotaRequestStatusInProgress.json + * x-ms-original-file: + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/getQuotaRequestStatusInProgress. + * json */ /** * Sample code: QuotaRequestInProgress. @@ -1204,8 +928,7 @@ public final class QuotaRequestStatusGetSamples { public final class QuotaRequestStatusListSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/getQuotaRequestsHistory. - * json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/getQuotaRequestsHistory.json */ /** * Sample code: QuotaRequestHistory. @@ -1229,8 +952,7 @@ public final class QuotaRequestStatusListSamples { public final class UsagesGetSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/getNetworkOneSkuUsages. - * json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/getNetworkOneSkuUsages.json */ /** * Sample code: Quotas_UsagesRequest_ForNetwork. @@ -1246,8 +968,7 @@ public final class UsagesGetSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/getComputeOneSkuUsages. - * json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/getComputeOneSkuUsages.json */ /** * Sample code: Quotas_UsagesRequest_ForCompute. @@ -1272,7 +993,7 @@ public final class UsagesGetSamples { public final class UsagesListSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/getComputeUsages.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/getComputeUsages.json */ /** * Sample code: Quotas_listUsagesForCompute. @@ -1287,7 +1008,7 @@ public final class UsagesListSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/getNetworkUsages.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/getNetworkUsages.json */ /** * Sample code: Quotas_listUsagesForNetwork. @@ -1301,8 +1022,9 @@ public final class UsagesListSamples { } /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ - * getMachineLearningServicesUsages.json + * x-ms-original-file: + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/getMachineLearningServicesUsages. + * json */ /** * Sample code: Quotas_listUsagesMachineLearningServices. diff --git a/sdk/quota/azure-resourcemanager-quota/pom.xml b/sdk/quota/azure-resourcemanager-quota/pom.xml index a567a58cdbec..7acb33a40e8f 100644 --- a/sdk/quota/azure-resourcemanager-quota/pom.xml +++ b/sdk/quota/azure-resourcemanager-quota/pom.xml @@ -14,11 +14,11 @@ com.azure.resourcemanager azure-resourcemanager-quota - 1.1.0-beta.3 + 1.2.0-beta.1 jar Microsoft Azure SDK for quota Management - This package contains Microsoft Azure SDK for quota Management SDK. For documentation on how to use this package, please see https://aka.ms/azsdk/java/mgmt. Microsoft Azure Quota Resource Provider. This Swagger is for Azure Group Quota using GroupQuota Entity. Package tag package-2023-06-01-preview. + This package contains Microsoft Azure SDK for quota Management SDK. For documentation on how to use this package, please see https://aka.ms/azsdk/java/mgmt. Microsoft Azure Quota Resource Provider. This Swagger is for Azure Group Quota using GroupQuota Entity. Package tag package-2025-03-01. https://github.com/Azure/azure-sdk-for-java @@ -45,30 +45,29 @@ UTF-8 0 0 - true false com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/QuotaManager.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/QuotaManager.java index 2ad7d787c26f..5782be854a68 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/QuotaManager.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/QuotaManager.java @@ -22,17 +22,16 @@ import com.azure.core.http.policy.UserAgentPolicy; import com.azure.core.management.profile.AzureProfile; import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.quota.fluent.AzureQuotaExtensionApi; import com.azure.resourcemanager.quota.implementation.AzureQuotaExtensionApiBuilder; import com.azure.resourcemanager.quota.implementation.GroupQuotaLimitsImpl; import com.azure.resourcemanager.quota.implementation.GroupQuotaLimitsRequestsImpl; -import com.azure.resourcemanager.quota.implementation.GroupQuotaLocationSettingsImpl; import com.azure.resourcemanager.quota.implementation.GroupQuotaSubscriptionAllocationRequestsImpl; import com.azure.resourcemanager.quota.implementation.GroupQuotaSubscriptionAllocationsImpl; import com.azure.resourcemanager.quota.implementation.GroupQuotaSubscriptionRequestsImpl; import com.azure.resourcemanager.quota.implementation.GroupQuotaSubscriptionsImpl; -import com.azure.resourcemanager.quota.implementation.GroupQuotaUsagesImpl; import com.azure.resourcemanager.quota.implementation.GroupQuotasImpl; import com.azure.resourcemanager.quota.implementation.QuotaOperationsImpl; import com.azure.resourcemanager.quota.implementation.QuotaRequestStatusImpl; @@ -40,12 +39,10 @@ import com.azure.resourcemanager.quota.implementation.UsagesImpl; import com.azure.resourcemanager.quota.models.GroupQuotaLimits; import com.azure.resourcemanager.quota.models.GroupQuotaLimitsRequests; -import com.azure.resourcemanager.quota.models.GroupQuotaLocationSettings; import com.azure.resourcemanager.quota.models.GroupQuotaSubscriptionAllocationRequests; import com.azure.resourcemanager.quota.models.GroupQuotaSubscriptionAllocations; import com.azure.resourcemanager.quota.models.GroupQuotaSubscriptionRequests; import com.azure.resourcemanager.quota.models.GroupQuotaSubscriptions; -import com.azure.resourcemanager.quota.models.GroupQuotaUsages; import com.azure.resourcemanager.quota.models.GroupQuotas; import com.azure.resourcemanager.quota.models.QuotaOperations; import com.azure.resourcemanager.quota.models.QuotaRequestStatus; @@ -55,6 +52,7 @@ import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; @@ -69,17 +67,13 @@ public final class QuotaManager { private GroupQuotaSubscriptionRequests groupQuotaSubscriptionRequests; - private GroupQuotaLimits groupQuotaLimits; - private GroupQuotaLimitsRequests groupQuotaLimitsRequests; - private GroupQuotaSubscriptionAllocations groupQuotaSubscriptionAllocations; + private GroupQuotaLimits groupQuotaLimits; private GroupQuotaSubscriptionAllocationRequests groupQuotaSubscriptionAllocationRequests; - private GroupQuotaUsages groupQuotaUsages; - - private GroupQuotaLocationSettings groupQuotaLocationSettings; + private GroupQuotaSubscriptionAllocations groupQuotaSubscriptionAllocations; private Usages usages; @@ -141,6 +135,9 @@ public static Configurable configure() { */ public static final class Configurable { private static final ClientLogger LOGGER = new ClientLogger(Configurable.class); + private static final String SDK_VERSION = "version"; + private static final Map PROPERTIES + = CoreUtils.getProperties("azure-resourcemanager-quota.properties"); private HttpClient httpClient; private HttpLogOptions httpLogOptions; @@ -248,12 +245,14 @@ public QuotaManager authenticate(TokenCredential credential, AzureProfile profil Objects.requireNonNull(credential, "'credential' cannot be null."); Objects.requireNonNull(profile, "'profile' cannot be null."); + String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); + StringBuilder userAgentBuilder = new StringBuilder(); userAgentBuilder.append("azsdk-java") .append("-") .append("com.azure.resourcemanager.quota") .append("/") - .append("1.1.0-beta.2"); + .append(clientVersion); if (!Configuration.getGlobalConfiguration().get("AZURE_TELEMETRY_DISABLED", false)) { userAgentBuilder.append(" (") .append(Configuration.getGlobalConfiguration().get("java.version")) @@ -337,18 +336,6 @@ public GroupQuotaSubscriptionRequests groupQuotaSubscriptionRequests() { return groupQuotaSubscriptionRequests; } - /** - * Gets the resource collection API of GroupQuotaLimits. - * - * @return Resource collection API of GroupQuotaLimits. - */ - public GroupQuotaLimits groupQuotaLimits() { - if (this.groupQuotaLimits == null) { - this.groupQuotaLimits = new GroupQuotaLimitsImpl(clientObject.getGroupQuotaLimits(), this); - } - return groupQuotaLimits; - } - /** * Gets the resource collection API of GroupQuotaLimitsRequests. * @@ -363,16 +350,15 @@ public GroupQuotaLimitsRequests groupQuotaLimitsRequests() { } /** - * Gets the resource collection API of GroupQuotaSubscriptionAllocations. + * Gets the resource collection API of GroupQuotaLimits. * - * @return Resource collection API of GroupQuotaSubscriptionAllocations. + * @return Resource collection API of GroupQuotaLimits. */ - public GroupQuotaSubscriptionAllocations groupQuotaSubscriptionAllocations() { - if (this.groupQuotaSubscriptionAllocations == null) { - this.groupQuotaSubscriptionAllocations - = new GroupQuotaSubscriptionAllocationsImpl(clientObject.getGroupQuotaSubscriptionAllocations(), this); + public GroupQuotaLimits groupQuotaLimits() { + if (this.groupQuotaLimits == null) { + this.groupQuotaLimits = new GroupQuotaLimitsImpl(clientObject.getGroupQuotaLimits(), this); } - return groupQuotaSubscriptionAllocations; + return groupQuotaLimits; } /** @@ -389,28 +375,16 @@ public GroupQuotaSubscriptionAllocationRequests groupQuotaSubscriptionAllocation } /** - * Gets the resource collection API of GroupQuotaUsages. - * - * @return Resource collection API of GroupQuotaUsages. - */ - public GroupQuotaUsages groupQuotaUsages() { - if (this.groupQuotaUsages == null) { - this.groupQuotaUsages = new GroupQuotaUsagesImpl(clientObject.getGroupQuotaUsages(), this); - } - return groupQuotaUsages; - } - - /** - * Gets the resource collection API of GroupQuotaLocationSettings. + * Gets the resource collection API of GroupQuotaSubscriptionAllocations. * - * @return Resource collection API of GroupQuotaLocationSettings. + * @return Resource collection API of GroupQuotaSubscriptionAllocations. */ - public GroupQuotaLocationSettings groupQuotaLocationSettings() { - if (this.groupQuotaLocationSettings == null) { - this.groupQuotaLocationSettings - = new GroupQuotaLocationSettingsImpl(clientObject.getGroupQuotaLocationSettings(), this); + public GroupQuotaSubscriptionAllocations groupQuotaSubscriptionAllocations() { + if (this.groupQuotaSubscriptionAllocations == null) { + this.groupQuotaSubscriptionAllocations + = new GroupQuotaSubscriptionAllocationsImpl(clientObject.getGroupQuotaSubscriptionAllocations(), this); } - return groupQuotaLocationSettings; + return groupQuotaSubscriptionAllocations; } /** diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/AzureQuotaExtensionApi.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/AzureQuotaExtensionApi.java index 44d3db678de3..708c3a71301f 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/AzureQuotaExtensionApi.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/AzureQuotaExtensionApi.java @@ -67,13 +67,6 @@ public interface AzureQuotaExtensionApi { */ GroupQuotaSubscriptionRequestsClient getGroupQuotaSubscriptionRequests(); - /** - * Gets the GroupQuotaLimitsClient object to access its operations. - * - * @return the GroupQuotaLimitsClient object. - */ - GroupQuotaLimitsClient getGroupQuotaLimits(); - /** * Gets the GroupQuotaLimitsRequestsClient object to access its operations. * @@ -82,11 +75,11 @@ public interface AzureQuotaExtensionApi { GroupQuotaLimitsRequestsClient getGroupQuotaLimitsRequests(); /** - * Gets the GroupQuotaSubscriptionAllocationsClient object to access its operations. + * Gets the GroupQuotaLimitsClient object to access its operations. * - * @return the GroupQuotaSubscriptionAllocationsClient object. + * @return the GroupQuotaLimitsClient object. */ - GroupQuotaSubscriptionAllocationsClient getGroupQuotaSubscriptionAllocations(); + GroupQuotaLimitsClient getGroupQuotaLimits(); /** * Gets the GroupQuotaSubscriptionAllocationRequestsClient object to access its operations. @@ -96,18 +89,11 @@ public interface AzureQuotaExtensionApi { GroupQuotaSubscriptionAllocationRequestsClient getGroupQuotaSubscriptionAllocationRequests(); /** - * Gets the GroupQuotaUsagesClient object to access its operations. - * - * @return the GroupQuotaUsagesClient object. - */ - GroupQuotaUsagesClient getGroupQuotaUsages(); - - /** - * Gets the GroupQuotaLocationSettingsClient object to access its operations. + * Gets the GroupQuotaSubscriptionAllocationsClient object to access its operations. * - * @return the GroupQuotaLocationSettingsClient object. + * @return the GroupQuotaSubscriptionAllocationsClient object. */ - GroupQuotaLocationSettingsClient getGroupQuotaLocationSettings(); + GroupQuotaSubscriptionAllocationsClient getGroupQuotaSubscriptionAllocations(); /** * Gets the UsagesClient object to access its operations. diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/GroupQuotaLimitsClient.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/GroupQuotaLimitsClient.java index 54f07d679d1c..2d3e8592d3c7 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/GroupQuotaLimitsClient.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/GroupQuotaLimitsClient.java @@ -6,123 +6,50 @@ import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; -import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.Response; import com.azure.core.util.Context; -import com.azure.resourcemanager.quota.fluent.models.GroupQuotaLimitInner; +import com.azure.resourcemanager.quota.fluent.models.GroupQuotaLimitListInner; /** * An instance of this class provides access to all the operations defined in GroupQuotaLimitsClient. */ public interface GroupQuotaLimitsClient { /** - * Gets the GroupQuotaLimits for the specific resource. - * - * Gets the GroupQuotaLimits for the specific resource for a specific resource based on the resourceProviders, - * resourceName and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota. + * Gets the GroupQuotaLimits for the specified resource provider and location for resource names passed in + * $filter=resourceName eq {SKU}. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. + * @param location The name of the Azure region. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotaLimits for the specific resource for a specific resource based on the resourceProviders, - * resourceName and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota along with - * {@link Response}. + * @return the GroupQuotaLimits for the specified resource provider and location for resource names passed in + * $filter=resourceName eq {SKU} along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - Response getWithResponse(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName, String filter, Context context); + Response listWithResponse(String managementGroupId, String groupQuotaName, + String resourceProviderName, String location, Context context); /** - * Gets the GroupQuotaLimits for the specific resource. - * - * Gets the GroupQuotaLimits for the specific resource for a specific resource based on the resourceProviders, - * resourceName and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota. + * Gets the GroupQuotaLimits for the specified resource provider and location for resource names passed in + * $filter=resourceName eq {SKU}. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. + * @param location The name of the Azure region. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotaLimits for the specific resource for a specific resource based on the resourceProviders, - * resourceName and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota. + * @return the GroupQuotaLimits for the specified resource provider and location for resource names passed in + * $filter=resourceName eq {SKU}. */ @ServiceMethod(returns = ReturnType.SINGLE) - GroupQuotaLimitInner get(String managementGroupId, String groupQuotaName, String resourceProviderName, - String resourceName, String filter); - - /** - * Gets the GroupQuotaLimits for all the resources for the specified location in $filter=location eq {location}. - * - * Gets the GroupQuotaLimits for the all resource for a specific resourceProvider and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotaLimits for the all resource for a specific resourceProvider and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota as paginated response - * with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable list(String managementGroupId, String groupQuotaName, - String resourceProviderName, String filter); - - /** - * Gets the GroupQuotaLimits for all the resources for the specified location in $filter=location eq {location}. - * - * Gets the GroupQuotaLimits for the all resource for a specific resourceProvider and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotaLimits for the all resource for a specific resourceProvider and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota as paginated response - * with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable list(String managementGroupId, String groupQuotaName, - String resourceProviderName, String filter, Context context); + GroupQuotaLimitListInner list(String managementGroupId, String groupQuotaName, String resourceProviderName, + String location); } diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/GroupQuotaLimitsRequestsClient.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/GroupQuotaLimitsRequestsClient.java index 26640734c033..ec4e563d5c06 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/GroupQuotaLimitsRequestsClient.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/GroupQuotaLimitsRequestsClient.java @@ -8,123 +8,22 @@ import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.Response; -import com.azure.core.management.ProxyResource; import com.azure.core.management.polling.PollResult; import com.azure.core.util.Context; import com.azure.core.util.polling.SyncPoller; +import com.azure.resourcemanager.quota.fluent.models.GroupQuotaLimitListInner; import com.azure.resourcemanager.quota.fluent.models.SubmittedResourceRequestStatusInner; /** * An instance of this class provides access to all the operations defined in GroupQuotaLimitsRequestsClient. */ public interface GroupQuotaLimitsRequestsClient { - /** - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. - * - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * ("name": {"value" : "resourceName") properties are specified in the request body. Only 1 resource quota can be - * requested. - * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after - * duration in seconds to check the intermediate status. This API provides the finals status with the request - * details and status. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of status of a single GroupQuota request. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, ProxyResource> beginCreateOrUpdate(String managementGroupId, - String groupQuotaName, String resourceProviderName, String resourceName); - - /** - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. - * - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * ("name": {"value" : "resourceName") properties are specified in the request body. Only 1 resource quota can be - * requested. - * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after - * duration in seconds to check the intermediate status. This API provides the finals status with the request - * details and status. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param groupQuotaRequest The GroupQuotaRequest body details for specific resourceProvider/location/resources. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of status of a single GroupQuota request. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, ProxyResource> beginCreateOrUpdate(String managementGroupId, - String groupQuotaName, String resourceProviderName, String resourceName, - SubmittedResourceRequestStatusInner groupQuotaRequest, Context context); - - /** - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. - * - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * ("name": {"value" : "resourceName") properties are specified in the request body. Only 1 resource quota can be - * requested. - * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after - * duration in seconds to check the intermediate status. This API provides the finals status with the request - * details and status. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return status of a single GroupQuota request. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - ProxyResource createOrUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, - String resourceName); - - /** - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. - * - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * ("name": {"value" : "resourceName") properties are specified in the request body. Only 1 resource quota can be - * requested. - * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after - * duration in seconds to check the intermediate status. This API provides the finals status with the request - * details and status. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param groupQuotaRequest The GroupQuotaRequest body details for specific resourceProvider/location/resources. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return status of a single GroupQuota request. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - ProxyResource createOrUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, - String resourceName, SubmittedResourceRequestStatusInner groupQuotaRequest, Context context); - /** * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. * - * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * properties are specified in the request body. Only 1 resource quota can be requested. Please note that patch - * request creates a new groupQuota request. + * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. The resourceName properties are + * specified in the request body. Only 1 resource quota can be requested. Please note that patch request creates a + * new groupQuota request. * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after * duration in seconds to check the intermediate status. This API provides the finals status with the request * details and status. @@ -133,22 +32,22 @@ ProxyResource createOrUpdate(String managementGroupId, String groupQuotaName, St * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. + * @param location The name of the Azure region. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of status of a single GroupQuota request. + * @return the {@link SyncPoller} for polling of list of Group Quota Limit details. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, SubmittedResourceRequestStatusInner> - beginUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, String resourceName); + SyncPoller, GroupQuotaLimitListInner> beginUpdate(String managementGroupId, + String groupQuotaName, String resourceProviderName, String location); /** * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. * - * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * properties are specified in the request body. Only 1 resource quota can be requested. Please note that patch - * request creates a new groupQuota request. + * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. The resourceName properties are + * specified in the request body. Only 1 resource quota can be requested. Please note that patch request creates a + * new groupQuota request. * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after * duration in seconds to check the intermediate status. This API provides the finals status with the request * details and status. @@ -157,25 +56,25 @@ ProxyResource createOrUpdate(String managementGroupId, String groupQuotaName, St * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. + * @param location The name of the Azure region. * @param groupQuotaRequest The GroupQuotaRequest body details for specific resourceProvider/location/resources. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of status of a single GroupQuota request. + * @return the {@link SyncPoller} for polling of list of Group Quota Limit details. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, SubmittedResourceRequestStatusInner> beginUpdate( - String managementGroupId, String groupQuotaName, String resourceProviderName, String resourceName, - SubmittedResourceRequestStatusInner groupQuotaRequest, Context context); + SyncPoller, GroupQuotaLimitListInner> beginUpdate(String managementGroupId, + String groupQuotaName, String resourceProviderName, String location, GroupQuotaLimitListInner groupQuotaRequest, + Context context); /** * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. * - * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * properties are specified in the request body. Only 1 resource quota can be requested. Please note that patch - * request creates a new groupQuota request. + * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. The resourceName properties are + * specified in the request body. Only 1 resource quota can be requested. Please note that patch request creates a + * new groupQuota request. * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after * duration in seconds to check the intermediate status. This API provides the finals status with the request * details and status. @@ -184,22 +83,22 @@ SyncPoller, SubmittedResourceReq * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. + * @param location The name of the Azure region. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return status of a single GroupQuota request. + * @return list of Group Quota Limit details. */ @ServiceMethod(returns = ReturnType.SINGLE) - SubmittedResourceRequestStatusInner update(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName); + GroupQuotaLimitListInner update(String managementGroupId, String groupQuotaName, String resourceProviderName, + String location); /** * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. * - * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * properties are specified in the request body. Only 1 resource quota can be requested. Please note that patch - * request creates a new groupQuota request. + * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. The resourceName properties are + * specified in the request body. Only 1 resource quota can be requested. Please note that patch request creates a + * new groupQuota request. * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after * duration in seconds to check the intermediate status. This API provides the finals status with the request * details and status. @@ -208,18 +107,17 @@ SubmittedResourceRequestStatusInner update(String managementGroupId, String grou * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. + * @param location The name of the Azure region. * @param groupQuotaRequest The GroupQuotaRequest body details for specific resourceProvider/location/resources. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return status of a single GroupQuota request. + * @return list of Group Quota Limit details. */ @ServiceMethod(returns = ReturnType.SINGLE) - SubmittedResourceRequestStatusInner update(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName, SubmittedResourceRequestStatusInner groupQuotaRequest, - Context context); + GroupQuotaLimitListInner update(String managementGroupId, String groupQuotaName, String resourceProviderName, + String location, GroupQuotaLimitListInner groupQuotaRequest, Context context); /** * Get the status of a single GroupQuota request by requestId. diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/GroupQuotaLocationSettingsClient.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/GroupQuotaLocationSettingsClient.java deleted file mode 100644 index 1616a67df060..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/GroupQuotaLocationSettingsClient.java +++ /dev/null @@ -1,339 +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.resourcemanager.quota.fluent; - -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.Response; -import com.azure.core.management.ProxyResource; -import com.azure.core.management.polling.PollResult; -import com.azure.core.util.Context; -import com.azure.core.util.polling.SyncPoller; -import com.azure.resourcemanager.quota.fluent.models.GroupQuotasEnforcementResponseInner; - -/** - * An instance of this class provides access to all the operations defined in GroupQuotaLocationSettingsClient. - */ -public interface GroupQuotaLocationSettingsClient { - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of the GroupQuota Enforcement status for a Azure Location/Region. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, ProxyResource> beginCreateOrUpdate(String managementGroupId, - String groupQuotaName, String resourceProviderName, String location); - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param locationSettings The GroupQuota body details for creation or update of a GroupQuota entity. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of the GroupQuota Enforcement status for a Azure Location/Region. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, ProxyResource> beginCreateOrUpdate(String managementGroupId, - String groupQuotaName, String resourceProviderName, String location, - GroupQuotasEnforcementResponseInner locationSettings, Context context); - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuota Enforcement status for a Azure Location/Region. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - ProxyResource createOrUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, - String location); - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param locationSettings The GroupQuota body details for creation or update of a GroupQuota entity. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuota Enforcement status for a Azure Location/Region. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - ProxyResource createOrUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, - String location, GroupQuotasEnforcementResponseInner locationSettings, Context context); - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of the GroupQuota Enforcement status for a Azure Location/Region. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, GroupQuotasEnforcementResponseInner> - beginUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, String location); - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param locationSettings The GroupQuota body details for creation or update of a GroupQuota entity. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of the GroupQuota Enforcement status for a Azure Location/Region. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, GroupQuotasEnforcementResponseInner> beginUpdate( - String managementGroupId, String groupQuotaName, String resourceProviderName, String location, - GroupQuotasEnforcementResponseInner locationSettings, Context context); - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuota Enforcement status for a Azure Location/Region. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - GroupQuotasEnforcementResponseInner update(String managementGroupId, String groupQuotaName, - String resourceProviderName, String location); - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param locationSettings The GroupQuota body details for creation or update of a GroupQuota entity. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuota Enforcement status for a Azure Location/Region. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - GroupQuotasEnforcementResponseInner update(String managementGroupId, String groupQuotaName, - String resourceProviderName, String location, GroupQuotasEnforcementResponseInner locationSettings, - Context context); - - /** - * Gets the GroupQuotas enforcement settings for the resource provider/location. - * - * Gets the GroupQuotas enforcement settings for the ResourceProvider/location. The locations, where GroupQuota - * enforcement is not enabled will return Not Found. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotas enforcement settings for the ResourceProvider/location along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - Response getWithResponse(String managementGroupId, String groupQuotaName, - String resourceProviderName, String location, Context context); - - /** - * Gets the GroupQuotas enforcement settings for the resource provider/location. - * - * Gets the GroupQuotas enforcement settings for the ResourceProvider/location. The locations, where GroupQuota - * enforcement is not enabled will return Not Found. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotas enforcement settings for the ResourceProvider/location. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - GroupQuotasEnforcementResponseInner get(String managementGroupId, String groupQuotaName, - String resourceProviderName, String location); - - /** - * Returns a list of the Azure regions settings, where the GroupQuotas enforcement is enabled. - * - * Returns only the list of the Azure regions settings, where the GroupQuotas enforcement is enabled. The locations - * not included in GroupQuota Enforcement will not be listed, the regions in failed status with listed as status - * Failed. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return list of Azure regions, where the group quotas is enabled for enforcement as paginated response with - * {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable list(String managementGroupId, String groupQuotaName, - String resourceProviderName); - - /** - * Returns a list of the Azure regions settings, where the GroupQuotas enforcement is enabled. - * - * Returns only the list of the Azure regions settings, where the GroupQuotas enforcement is enabled. The locations - * not included in GroupQuota Enforcement will not be listed, the regions in failed status with listed as status - * Failed. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return list of Azure regions, where the group quotas is enabled for enforcement as paginated response with - * {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable list(String managementGroupId, String groupQuotaName, - String resourceProviderName, Context context); -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/GroupQuotaSubscriptionAllocationRequestsClient.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/GroupQuotaSubscriptionAllocationRequestsClient.java index 533d86da7403..94274ef71ff5 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/GroupQuotaSubscriptionAllocationRequestsClient.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/GroupQuotaSubscriptionAllocationRequestsClient.java @@ -8,308 +8,209 @@ import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.Response; -import com.azure.core.management.ProxyResource; import com.azure.core.management.polling.PollResult; import com.azure.core.util.Context; import com.azure.core.util.polling.SyncPoller; import com.azure.resourcemanager.quota.fluent.models.QuotaAllocationRequestStatusInner; +import com.azure.resourcemanager.quota.fluent.models.SubscriptionQuotaAllocationsListInner; /** * An instance of this class provides access to all the operations defined in * GroupQuotaSubscriptionAllocationRequestsClient. */ public interface GroupQuotaSubscriptionAllocationRequestsClient { - /** - * Get the status of the quota allocation request for the subscriptionId. - * - * Get the quota allocation request status for the subscriptionId by allocationId. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param allocationId Request Id. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the quota allocation request status for the subscriptionId by allocationId along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - Response getWithResponse(String managementGroupId, String groupQuotaName, - String allocationId, Context context); - - /** - * Get the status of the quota allocation request for the subscriptionId. - * - * Get the quota allocation request status for the subscriptionId by allocationId. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param allocationId Request Id. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the quota allocation request status for the subscriptionId by allocationId. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - QuotaAllocationRequestStatusInner get(String managementGroupId, String groupQuotaName, String allocationId); - - /** - * Get all the quotaAllocationRequests for a resourceProvider/location. - * - * Get all the quotaAllocationRequests for a resourceProvider/location. The filter paramter for location is - * required. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all the quotaAllocationRequests for a resourceProvider/location as paginated response with - * {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable list(String managementGroupId, String groupQuotaName, - String resourceProviderName, String filter); - - /** - * Get all the quotaAllocationRequests for a resourceProvider/location. - * - * Get all the quotaAllocationRequests for a resourceProvider/location. The filter paramter for location is - * required. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all the quotaAllocationRequests for a resourceProvider/location as paginated response with - * {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable list(String managementGroupId, String groupQuotaName, - String resourceProviderName, String filter, Context context); - /** * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * to check the status using Async polling as standards defined at - - * https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/async-api-reference.md#asynchronous-operations. + * with 202 response and status polling API. * * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. + * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple + * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. + * @param location The name of the Azure region. * @param allocateQuotaRequest Quota requests payload. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of the subscription quota allocation status. + * @return the {@link SyncPoller} for polling of subscription quota list. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, ProxyResource> beginCreateOrUpdate(String managementGroupId, - String groupQuotaName, String resourceProviderName, String resourceName, - QuotaAllocationRequestStatusInner allocateQuotaRequest); + SyncPoller, SubscriptionQuotaAllocationsListInner> beginUpdate( + String managementGroupId, String groupQuotaName, String resourceProviderName, String location, + SubscriptionQuotaAllocationsListInner allocateQuotaRequest); /** * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * to check the status using Async polling as standards defined at - - * https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/async-api-reference.md#asynchronous-operations. + * with 202 response and status polling API. * * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. + * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple + * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. + * @param location The name of the Azure region. * @param allocateQuotaRequest Quota requests payload. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of the subscription quota allocation status. + * @return the {@link SyncPoller} for polling of subscription quota list. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, ProxyResource> beginCreateOrUpdate(String managementGroupId, - String groupQuotaName, String resourceProviderName, String resourceName, - QuotaAllocationRequestStatusInner allocateQuotaRequest, Context context); + SyncPoller, SubscriptionQuotaAllocationsListInner> beginUpdate( + String managementGroupId, String groupQuotaName, String resourceProviderName, String location, + SubscriptionQuotaAllocationsListInner allocateQuotaRequest, Context context); /** * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * to check the status using Async polling as standards defined at - - * https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/async-api-reference.md#asynchronous-operations. + * with 202 response and status polling API. * * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. + * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple + * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. + * @param location The name of the Azure region. * @param allocateQuotaRequest Quota requests payload. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the subscription quota allocation status. + * @return subscription quota list. */ @ServiceMethod(returns = ReturnType.SINGLE) - ProxyResource createOrUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, - String resourceName, QuotaAllocationRequestStatusInner allocateQuotaRequest); + SubscriptionQuotaAllocationsListInner update(String managementGroupId, String groupQuotaName, + String resourceProviderName, String location, SubscriptionQuotaAllocationsListInner allocateQuotaRequest); /** * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * to check the status using Async polling as standards defined at - - * https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/async-api-reference.md#asynchronous-operations. + * with 202 response and status polling API. * * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. + * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple + * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. + * @param location The name of the Azure region. * @param allocateQuotaRequest Quota requests payload. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the subscription quota allocation status. + * @return subscription quota list. */ @ServiceMethod(returns = ReturnType.SINGLE) - ProxyResource createOrUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, - String resourceName, QuotaAllocationRequestStatusInner allocateQuotaRequest, Context context); + SubscriptionQuotaAllocationsListInner update(String managementGroupId, String groupQuotaName, + String resourceProviderName, String location, SubscriptionQuotaAllocationsListInner allocateQuotaRequest, + Context context); /** - * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * with 202 response and status polling API. + * Get the status of the quota allocation request for the subscriptionId. * - * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or - * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. - * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple - * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. + * Get the quota allocation request status for the subscriptionId by allocationId. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param allocateQuotaRequest Quota requests payload. + * @param allocationId Request Id. + * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of the subscription quota allocation status. + * @return the quota allocation request status for the subscriptionId by allocationId along with {@link Response}. */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, QuotaAllocationRequestStatusInner> beginUpdate( - String managementGroupId, String groupQuotaName, String resourceProviderName, String resourceName, - QuotaAllocationRequestStatusInner allocateQuotaRequest); + @ServiceMethod(returns = ReturnType.SINGLE) + Response getWithResponse(String managementGroupId, String groupQuotaName, + String resourceProviderName, String allocationId, Context context); /** - * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * with 202 response and status polling API. + * Get the status of the quota allocation request for the subscriptionId. * - * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or - * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. - * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple - * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. + * Get the quota allocation request status for the subscriptionId by allocationId. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param allocateQuotaRequest Quota requests payload. - * @param context The context to associate with this operation. + * @param allocationId Request Id. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of the subscription quota allocation status. + * @return the quota allocation request status for the subscriptionId by allocationId. */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - SyncPoller, QuotaAllocationRequestStatusInner> beginUpdate( - String managementGroupId, String groupQuotaName, String resourceProviderName, String resourceName, - QuotaAllocationRequestStatusInner allocateQuotaRequest, Context context); + @ServiceMethod(returns = ReturnType.SINGLE) + QuotaAllocationRequestStatusInner get(String managementGroupId, String groupQuotaName, String resourceProviderName, + String allocationId); /** - * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * with 202 response and status polling API. + * Get all the quotaAllocationRequests for a resourceProvider/location. * - * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or - * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. - * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple - * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. + * Get all the quotaAllocationRequests for a resourceProvider/location. The filter paramter for location is + * required. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param allocateQuotaRequest Quota requests payload. + * @param filter | Field | Supported operators + * |---------------------|------------------------ + * + * location eq {location} + * Example: $filter=location eq eastus. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the subscription quota allocation status. + * @return all the quotaAllocationRequests for a resourceProvider/location as paginated response with + * {@link PagedIterable}. */ - @ServiceMethod(returns = ReturnType.SINGLE) - QuotaAllocationRequestStatusInner update(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName, QuotaAllocationRequestStatusInner allocateQuotaRequest); + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(String managementGroupId, String groupQuotaName, + String resourceProviderName, String filter); /** - * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * with 202 response and status polling API. + * Get all the quotaAllocationRequests for a resourceProvider/location. * - * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or - * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. - * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple - * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. + * Get all the quotaAllocationRequests for a resourceProvider/location. The filter paramter for location is + * required. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param allocateQuotaRequest Quota requests payload. + * @param filter | Field | Supported operators + * |---------------------|------------------------ + * + * location eq {location} + * Example: $filter=location eq eastus. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the subscription quota allocation status. + * @return all the quotaAllocationRequests for a resourceProvider/location as paginated response with + * {@link PagedIterable}. */ - @ServiceMethod(returns = ReturnType.SINGLE) - QuotaAllocationRequestStatusInner update(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName, QuotaAllocationRequestStatusInner allocateQuotaRequest, - Context context); + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(String managementGroupId, String groupQuotaName, + String resourceProviderName, String filter, Context context); } diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/GroupQuotaSubscriptionAllocationsClient.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/GroupQuotaSubscriptionAllocationsClient.java index 6aa718444d0a..38f5cf64598b 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/GroupQuotaSubscriptionAllocationsClient.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/GroupQuotaSubscriptionAllocationsClient.java @@ -6,113 +6,58 @@ import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; -import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.Response; import com.azure.core.util.Context; -import com.azure.resourcemanager.quota.fluent.models.SubscriptionQuotaAllocationsInner; +import com.azure.resourcemanager.quota.fluent.models.SubscriptionQuotaAllocationsListInner; /** * An instance of this class provides access to all the operations defined in GroupQuotaSubscriptionAllocationsClient. */ public interface GroupQuotaSubscriptionAllocationsClient { /** - * Gets all the quota allocated to a subscription for the specific Resource Provider, Location. + * Gets all the quota allocated to a subscription for the specified resource provider and location for resource + * names passed in $filter=resourceName eq {SKU}. * - * Gets all the quota allocated to a subscription for the specific Resource Provider, Location. This will include - * the GroupQuota and total quota allocated to the subscription. Only the Group quota allocated to the subscription - * can be allocated back to the MG Group Quota. Use the $filter parameter to filter out the specific resource based - * on the ResourceProvider/Location. $filter is a required parameter. + * Gets all the quota allocated to a subscription for the specified resource provider and location for resource + * names passed in $filter=resourceName eq {SKU}. This will include the GroupQuota and total quota allocated to the + * subscription. Only the Group quota allocated to the subscription can be allocated back to the MG Group Quota. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all the quota allocated to a subscription for the specific Resource Provider, Location as paginated - * response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable list(String managementGroupId, String groupQuotaName, - String filter); - - /** - * Gets all the quota allocated to a subscription for the specific Resource Provider, Location. - * - * Gets all the quota allocated to a subscription for the specific Resource Provider, Location. This will include - * the GroupQuota and total quota allocated to the subscription. Only the Group quota allocated to the subscription - * can be allocated back to the MG Group Quota. Use the $filter parameter to filter out the specific resource based - * on the ResourceProvider/Location. $filter is a required parameter. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. + * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only + * Microsoft.Compute resource provider supports this API. + * @param location The name of the Azure region. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all the quota allocated to a subscription for the specific Resource Provider, Location as paginated - * response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable list(String managementGroupId, String groupQuotaName, - String filter, Context context); - - /** - * Gets Quota allocated to a subscription for the specific Resource Provider, Location, ResourceName. - * - * Gets Quota allocated to a subscription for the specific Resource Provider, Location, ResourceName. This will - * include the GroupQuota and total quota allocated to the subscription. Only the Group quota allocated to the - * subscription can be allocated back to the MG Group Quota. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceName Resource name. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return quota allocated to a subscription for the specific Resource Provider, Location, ResourceName along with - * {@link Response}. + * @return all the quota allocated to a subscription for the specified resource provider and location for resource + * names passed in $filter=resourceName eq {SKU} along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - Response getWithResponse(String managementGroupId, String groupQuotaName, - String resourceName, String filter, Context context); + Response listWithResponse(String managementGroupId, String groupQuotaName, + String resourceProviderName, String location, Context context); /** - * Gets Quota allocated to a subscription for the specific Resource Provider, Location, ResourceName. + * Gets all the quota allocated to a subscription for the specified resource provider and location for resource + * names passed in $filter=resourceName eq {SKU}. * - * Gets Quota allocated to a subscription for the specific Resource Provider, Location, ResourceName. This will - * include the GroupQuota and total quota allocated to the subscription. Only the Group quota allocated to the - * subscription can be allocated back to the MG Group Quota. + * Gets all the quota allocated to a subscription for the specified resource provider and location for resource + * names passed in $filter=resourceName eq {SKU}. This will include the GroupQuota and total quota allocated to the + * subscription. Only the Group quota allocated to the subscription can be allocated back to the MG Group Quota. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceName Resource name. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. + * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only + * Microsoft.Compute resource provider supports this API. + * @param location The name of the Azure region. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return quota allocated to a subscription for the specific Resource Provider, Location, ResourceName. + * @return all the quota allocated to a subscription for the specified resource provider and location for resource + * names passed in $filter=resourceName eq {SKU}. */ @ServiceMethod(returns = ReturnType.SINGLE) - SubscriptionQuotaAllocationsInner get(String managementGroupId, String groupQuotaName, String resourceName, - String filter); + SubscriptionQuotaAllocationsListInner list(String managementGroupId, String groupQuotaName, + String resourceProviderName, String location); } diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/GroupQuotaUsagesClient.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/GroupQuotaUsagesClient.java deleted file mode 100644 index 45e838d69824..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/GroupQuotaUsagesClient.java +++ /dev/null @@ -1,55 +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.resourcemanager.quota.fluent; - -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.util.Context; -import com.azure.resourcemanager.quota.fluent.models.ResourceUsagesInner; - -/** - * An instance of this class provides access to all the operations defined in GroupQuotaUsagesClient. - */ -public interface GroupQuotaUsagesClient { - /** - * Gets the GroupQuotas usages and limits(quota) for the resourceProvider/location. - * - * Gets the GroupQuotas usages and limits(quota). Location is required paramter. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotas usages and limits(quota) as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable list(String managementGroupId, String groupQuotaName, - String resourceProviderName, String location); - - /** - * Gets the GroupQuotas usages and limits(quota) for the resourceProvider/location. - * - * Gets the GroupQuotas usages and limits(quota). Location is required paramter. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotas usages and limits(quota) as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable list(String managementGroupId, String groupQuotaName, - String resourceProviderName, String location, Context context); -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/models/GroupQuotaLimitInner.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/models/GroupQuotaLimitInner.java deleted file mode 100644 index bab9f6529dc2..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/models/GroupQuotaLimitInner.java +++ /dev/null @@ -1,166 +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.resourcemanager.quota.fluent.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.management.ProxyResource; -import com.azure.core.management.SystemData; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.resourcemanager.quota.models.GroupQuotaDetails; -import java.io.IOException; - -/** - * Group Quota limit. - */ -@Fluent -public final class GroupQuotaLimitInner extends ProxyResource { - /* - * Group Quota properties for the specified resource. - */ - private GroupQuotaDetails properties; - - /* - * Azure Resource Manager metadata containing createdBy and modifiedBy information. - */ - private SystemData systemData; - - /* - * The type of the resource. - */ - private String type; - - /* - * The name of the resource. - */ - private String name; - - /* - * Fully qualified resource Id for the resource. - */ - private String id; - - /** - * Creates an instance of GroupQuotaLimitInner class. - */ - public GroupQuotaLimitInner() { - } - - /** - * Get the properties property: Group Quota properties for the specified resource. - * - * @return the properties value. - */ - public GroupQuotaDetails properties() { - return this.properties; - } - - /** - * Set the properties property: Group Quota properties for the specified resource. - * - * @param properties the properties value to set. - * @return the GroupQuotaLimitInner object itself. - */ - public GroupQuotaLimitInner withProperties(GroupQuotaDetails properties) { - this.properties = properties; - return this; - } - - /** - * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. - * - * @return the systemData value. - */ - public SystemData systemData() { - return this.systemData; - } - - /** - * Get the type property: The type of the resource. - * - * @return the type value. - */ - @Override - public String type() { - return this.type; - } - - /** - * Get the name property: The name of the resource. - * - * @return the name value. - */ - @Override - public String name() { - return this.name; - } - - /** - * Get the id property: Fully qualified resource Id for the resource. - * - * @return the id value. - */ - @Override - public String id() { - return this.id; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (properties() != null) { - properties().validate(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeJsonField("properties", this.properties); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of GroupQuotaLimitInner from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of GroupQuotaLimitInner 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 GroupQuotaLimitInner. - */ - public static GroupQuotaLimitInner fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - GroupQuotaLimitInner deserializedGroupQuotaLimitInner = new GroupQuotaLimitInner(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("id".equals(fieldName)) { - deserializedGroupQuotaLimitInner.id = reader.getString(); - } else if ("name".equals(fieldName)) { - deserializedGroupQuotaLimitInner.name = reader.getString(); - } else if ("type".equals(fieldName)) { - deserializedGroupQuotaLimitInner.type = reader.getString(); - } else if ("properties".equals(fieldName)) { - deserializedGroupQuotaLimitInner.properties = GroupQuotaDetails.fromJson(reader); - } else if ("systemData".equals(fieldName)) { - deserializedGroupQuotaLimitInner.systemData = SystemData.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedGroupQuotaLimitInner; - }); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/models/GroupQuotaLimitListInner.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/models/GroupQuotaLimitListInner.java new file mode 100644 index 000000000000..144b286842ea --- /dev/null +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/models/GroupQuotaLimitListInner.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. + +package com.azure.resourcemanager.quota.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.quota.models.GroupQuotaLimitListProperties; +import java.io.IOException; + +/** + * List of Group Quota Limit details. + */ +@Fluent +public final class GroupQuotaLimitListInner extends ProxyResource { + /* + * The properties property. + */ + private GroupQuotaLimitListProperties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of GroupQuotaLimitListInner class. + */ + public GroupQuotaLimitListInner() { + } + + /** + * Get the properties property: The properties property. + * + * @return the properties value. + */ + public GroupQuotaLimitListProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The properties property. + * + * @param properties the properties value to set. + * @return the GroupQuotaLimitListInner object itself. + */ + public GroupQuotaLimitListInner withProperties(GroupQuotaLimitListProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of GroupQuotaLimitListInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of GroupQuotaLimitListInner 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 GroupQuotaLimitListInner. + */ + public static GroupQuotaLimitListInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + GroupQuotaLimitListInner deserializedGroupQuotaLimitListInner = new GroupQuotaLimitListInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedGroupQuotaLimitListInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedGroupQuotaLimitListInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedGroupQuotaLimitListInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedGroupQuotaLimitListInner.properties = GroupQuotaLimitListProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedGroupQuotaLimitListInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedGroupQuotaLimitListInner; + }); + } +} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/models/GroupQuotaUsagesBaseName.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/models/GroupQuotaUsagesBaseName.java deleted file mode 100644 index df895d094d8d..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/models/GroupQuotaUsagesBaseName.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.resourcemanager.quota.fluent.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; - -/** - * Name of the resource provided by the resource provider. This property is already included in the request URI, so it - * is a readonly property returned in the response. - */ -@Fluent -public final class GroupQuotaUsagesBaseName implements JsonSerializable { - /* - * Resource name. - */ - private String value; - - /* - * Resource display name. - */ - private String localizedValue; - - /** - * Creates an instance of GroupQuotaUsagesBaseName class. - */ - public GroupQuotaUsagesBaseName() { - } - - /** - * Get the value property: Resource name. - * - * @return the value value. - */ - public String value() { - return this.value; - } - - /** - * Set the value property: Resource name. - * - * @param value the value value to set. - * @return the GroupQuotaUsagesBaseName object itself. - */ - public GroupQuotaUsagesBaseName withValue(String value) { - this.value = value; - return this; - } - - /** - * Get the localizedValue property: Resource display name. - * - * @return the localizedValue value. - */ - public String localizedValue() { - return this.localizedValue; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("value", this.value); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of GroupQuotaUsagesBaseName from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of GroupQuotaUsagesBaseName 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 GroupQuotaUsagesBaseName. - */ - public static GroupQuotaUsagesBaseName fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - GroupQuotaUsagesBaseName deserializedGroupQuotaUsagesBaseName = new GroupQuotaUsagesBaseName(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - deserializedGroupQuotaUsagesBaseName.value = reader.getString(); - } else if ("localizedValue".equals(fieldName)) { - deserializedGroupQuotaUsagesBaseName.localizedValue = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedGroupQuotaUsagesBaseName; - }); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/models/GroupQuotasEnforcementResponseInner.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/models/GroupQuotasEnforcementResponseInner.java deleted file mode 100644 index 944dafb7735c..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/models/GroupQuotasEnforcementResponseInner.java +++ /dev/null @@ -1,168 +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.resourcemanager.quota.fluent.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.management.ProxyResource; -import com.azure.core.management.SystemData; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.resourcemanager.quota.models.GroupQuotasEnforcementResponseProperties; -import java.io.IOException; - -/** - * The GroupQuota Enforcement status for a Azure Location/Region. - */ -@Fluent -public final class GroupQuotasEnforcementResponseInner extends ProxyResource { - /* - * The properties property. - */ - private GroupQuotasEnforcementResponseProperties properties; - - /* - * Azure Resource Manager metadata containing createdBy and modifiedBy information. - */ - private SystemData systemData; - - /* - * The type of the resource. - */ - private String type; - - /* - * The name of the resource. - */ - private String name; - - /* - * Fully qualified resource Id for the resource. - */ - private String id; - - /** - * Creates an instance of GroupQuotasEnforcementResponseInner class. - */ - public GroupQuotasEnforcementResponseInner() { - } - - /** - * Get the properties property: The properties property. - * - * @return the properties value. - */ - public GroupQuotasEnforcementResponseProperties properties() { - return this.properties; - } - - /** - * Set the properties property: The properties property. - * - * @param properties the properties value to set. - * @return the GroupQuotasEnforcementResponseInner object itself. - */ - public GroupQuotasEnforcementResponseInner withProperties(GroupQuotasEnforcementResponseProperties properties) { - this.properties = properties; - return this; - } - - /** - * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. - * - * @return the systemData value. - */ - public SystemData systemData() { - return this.systemData; - } - - /** - * Get the type property: The type of the resource. - * - * @return the type value. - */ - @Override - public String type() { - return this.type; - } - - /** - * Get the name property: The name of the resource. - * - * @return the name value. - */ - @Override - public String name() { - return this.name; - } - - /** - * Get the id property: Fully qualified resource Id for the resource. - * - * @return the id value. - */ - @Override - public String id() { - return this.id; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (properties() != null) { - properties().validate(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeJsonField("properties", this.properties); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of GroupQuotasEnforcementResponseInner from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of GroupQuotasEnforcementResponseInner 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 GroupQuotasEnforcementResponseInner. - */ - public static GroupQuotasEnforcementResponseInner fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - GroupQuotasEnforcementResponseInner deserializedGroupQuotasEnforcementResponseInner - = new GroupQuotasEnforcementResponseInner(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("id".equals(fieldName)) { - deserializedGroupQuotasEnforcementResponseInner.id = reader.getString(); - } else if ("name".equals(fieldName)) { - deserializedGroupQuotasEnforcementResponseInner.name = reader.getString(); - } else if ("type".equals(fieldName)) { - deserializedGroupQuotasEnforcementResponseInner.type = reader.getString(); - } else if ("properties".equals(fieldName)) { - deserializedGroupQuotasEnforcementResponseInner.properties - = GroupQuotasEnforcementResponseProperties.fromJson(reader); - } else if ("systemData".equals(fieldName)) { - deserializedGroupQuotasEnforcementResponseInner.systemData = SystemData.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedGroupQuotasEnforcementResponseInner; - }); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/models/GroupQuotasEntityInner.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/models/GroupQuotasEntityInner.java index 2723af0efbaa..1a1a051189a7 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/models/GroupQuotasEntityInner.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/models/GroupQuotasEntityInner.java @@ -10,7 +10,7 @@ import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.azure.resourcemanager.quota.models.GroupQuotasEntityBase; +import com.azure.resourcemanager.quota.models.GroupQuotasEntityProperties; import java.io.IOException; /** @@ -19,9 +19,9 @@ @Fluent public final class GroupQuotasEntityInner extends ProxyResource { /* - * Properties and filters for ShareQuota. The request parameter is optional, if there are no filters specified. + * Properties */ - private GroupQuotasEntityBase properties; + private GroupQuotasEntityProperties properties; /* * Azure Resource Manager metadata containing createdBy and modifiedBy information. @@ -50,23 +50,21 @@ public GroupQuotasEntityInner() { } /** - * Get the properties property: Properties and filters for ShareQuota. The request parameter is optional, if there - * are no filters specified. + * Get the properties property: Properties. * * @return the properties value. */ - public GroupQuotasEntityBase properties() { + public GroupQuotasEntityProperties properties() { return this.properties; } /** - * Set the properties property: Properties and filters for ShareQuota. The request parameter is optional, if there - * are no filters specified. + * Set the properties property: Properties. * * @param properties the properties value to set. * @return the GroupQuotasEntityInner object itself. */ - public GroupQuotasEntityInner withProperties(GroupQuotasEntityBase properties) { + public GroupQuotasEntityInner withProperties(GroupQuotasEntityProperties properties) { this.properties = properties; return this; } @@ -154,7 +152,7 @@ public static GroupQuotasEntityInner fromJson(JsonReader jsonReader) throws IOEx } else if ("type".equals(fieldName)) { deserializedGroupQuotasEntityInner.type = reader.getString(); } else if ("properties".equals(fieldName)) { - deserializedGroupQuotasEntityInner.properties = GroupQuotasEntityBase.fromJson(reader); + deserializedGroupQuotasEntityInner.properties = GroupQuotasEntityProperties.fromJson(reader); } else if ("systemData".equals(fieldName)) { deserializedGroupQuotasEntityInner.systemData = SystemData.fromJson(reader); } else { diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/models/ResourceUsagesInner.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/models/ResourceUsagesInner.java deleted file mode 100644 index ce8ba184776c..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/models/ResourceUsagesInner.java +++ /dev/null @@ -1,166 +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.resourcemanager.quota.fluent.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.management.ProxyResource; -import com.azure.core.management.SystemData; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.resourcemanager.quota.models.GroupQuotaUsagesBase; -import java.io.IOException; - -/** - * Resource details with usages and GroupQuota. - */ -@Fluent -public final class ResourceUsagesInner extends ProxyResource { - /* - * Resource details with usages and GroupQuota. - */ - private GroupQuotaUsagesBase properties; - - /* - * Azure Resource Manager metadata containing createdBy and modifiedBy information. - */ - private SystemData systemData; - - /* - * The type of the resource. - */ - private String type; - - /* - * The name of the resource. - */ - private String name; - - /* - * Fully qualified resource Id for the resource. - */ - private String id; - - /** - * Creates an instance of ResourceUsagesInner class. - */ - public ResourceUsagesInner() { - } - - /** - * Get the properties property: Resource details with usages and GroupQuota. - * - * @return the properties value. - */ - public GroupQuotaUsagesBase properties() { - return this.properties; - } - - /** - * Set the properties property: Resource details with usages and GroupQuota. - * - * @param properties the properties value to set. - * @return the ResourceUsagesInner object itself. - */ - public ResourceUsagesInner withProperties(GroupQuotaUsagesBase properties) { - this.properties = properties; - return this; - } - - /** - * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. - * - * @return the systemData value. - */ - public SystemData systemData() { - return this.systemData; - } - - /** - * Get the type property: The type of the resource. - * - * @return the type value. - */ - @Override - public String type() { - return this.type; - } - - /** - * Get the name property: The name of the resource. - * - * @return the name value. - */ - @Override - public String name() { - return this.name; - } - - /** - * Get the id property: Fully qualified resource Id for the resource. - * - * @return the id value. - */ - @Override - public String id() { - return this.id; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (properties() != null) { - properties().validate(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeJsonField("properties", this.properties); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of ResourceUsagesInner from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of ResourceUsagesInner 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 ResourceUsagesInner. - */ - public static ResourceUsagesInner fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - ResourceUsagesInner deserializedResourceUsagesInner = new ResourceUsagesInner(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("id".equals(fieldName)) { - deserializedResourceUsagesInner.id = reader.getString(); - } else if ("name".equals(fieldName)) { - deserializedResourceUsagesInner.name = reader.getString(); - } else if ("type".equals(fieldName)) { - deserializedResourceUsagesInner.type = reader.getString(); - } else if ("properties".equals(fieldName)) { - deserializedResourceUsagesInner.properties = GroupQuotaUsagesBase.fromJson(reader); - } else if ("systemData".equals(fieldName)) { - deserializedResourceUsagesInner.systemData = SystemData.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedResourceUsagesInner; - }); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/models/SubscriptionQuotaAllocationsInner.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/models/SubscriptionQuotaAllocationsInner.java deleted file mode 100644 index dcd781149225..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/models/SubscriptionQuotaAllocationsInner.java +++ /dev/null @@ -1,170 +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.resourcemanager.quota.fluent.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.management.ProxyResource; -import com.azure.core.management.SystemData; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.resourcemanager.quota.models.SubscriptionQuotaDetails; -import java.io.IOException; - -/** - * Quota allocated to a subscription for the specific Resource Provider, Location, ResourceName. This will include the - * GroupQuota and total quota allocated to the subscription. Only the Group quota allocated to the subscription can be - * allocated back to the MG Group Quota. - */ -@Fluent -public final class SubscriptionQuotaAllocationsInner extends ProxyResource { - /* - * Quota properties for the specified resource. - */ - private SubscriptionQuotaDetails properties; - - /* - * Azure Resource Manager metadata containing createdBy and modifiedBy information. - */ - private SystemData systemData; - - /* - * The type of the resource. - */ - private String type; - - /* - * The name of the resource. - */ - private String name; - - /* - * Fully qualified resource Id for the resource. - */ - private String id; - - /** - * Creates an instance of SubscriptionQuotaAllocationsInner class. - */ - public SubscriptionQuotaAllocationsInner() { - } - - /** - * Get the properties property: Quota properties for the specified resource. - * - * @return the properties value. - */ - public SubscriptionQuotaDetails properties() { - return this.properties; - } - - /** - * Set the properties property: Quota properties for the specified resource. - * - * @param properties the properties value to set. - * @return the SubscriptionQuotaAllocationsInner object itself. - */ - public SubscriptionQuotaAllocationsInner withProperties(SubscriptionQuotaDetails properties) { - this.properties = properties; - return this; - } - - /** - * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. - * - * @return the systemData value. - */ - public SystemData systemData() { - return this.systemData; - } - - /** - * Get the type property: The type of the resource. - * - * @return the type value. - */ - @Override - public String type() { - return this.type; - } - - /** - * Get the name property: The name of the resource. - * - * @return the name value. - */ - @Override - public String name() { - return this.name; - } - - /** - * Get the id property: Fully qualified resource Id for the resource. - * - * @return the id value. - */ - @Override - public String id() { - return this.id; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (properties() != null) { - properties().validate(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeJsonField("properties", this.properties); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SubscriptionQuotaAllocationsInner from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SubscriptionQuotaAllocationsInner 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 SubscriptionQuotaAllocationsInner. - */ - public static SubscriptionQuotaAllocationsInner fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SubscriptionQuotaAllocationsInner deserializedSubscriptionQuotaAllocationsInner - = new SubscriptionQuotaAllocationsInner(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("id".equals(fieldName)) { - deserializedSubscriptionQuotaAllocationsInner.id = reader.getString(); - } else if ("name".equals(fieldName)) { - deserializedSubscriptionQuotaAllocationsInner.name = reader.getString(); - } else if ("type".equals(fieldName)) { - deserializedSubscriptionQuotaAllocationsInner.type = reader.getString(); - } else if ("properties".equals(fieldName)) { - deserializedSubscriptionQuotaAllocationsInner.properties - = SubscriptionQuotaDetails.fromJson(reader); - } else if ("systemData".equals(fieldName)) { - deserializedSubscriptionQuotaAllocationsInner.systemData = SystemData.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedSubscriptionQuotaAllocationsInner; - }); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/models/SubscriptionQuotaAllocationsListInner.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/models/SubscriptionQuotaAllocationsListInner.java new file mode 100644 index 000000000000..99bc7270d5db --- /dev/null +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/fluent/models/SubscriptionQuotaAllocationsListInner.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. + +package com.azure.resourcemanager.quota.fluent.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.management.ProxyResource; +import com.azure.core.management.SystemData; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocationsListProperties; +import java.io.IOException; + +/** + * Subscription quota list. + */ +@Fluent +public final class SubscriptionQuotaAllocationsListInner extends ProxyResource { + /* + * The properties property. + */ + private SubscriptionQuotaAllocationsListProperties properties; + + /* + * Azure Resource Manager metadata containing createdBy and modifiedBy information. + */ + private SystemData systemData; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of SubscriptionQuotaAllocationsListInner class. + */ + public SubscriptionQuotaAllocationsListInner() { + } + + /** + * Get the properties property: The properties property. + * + * @return the properties value. + */ + public SubscriptionQuotaAllocationsListProperties properties() { + return this.properties; + } + + /** + * Set the properties property: The properties property. + * + * @param properties the properties value to set. + * @return the SubscriptionQuotaAllocationsListInner object itself. + */ + public SubscriptionQuotaAllocationsListInner withProperties(SubscriptionQuotaAllocationsListProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. + */ + public SystemData systemData() { + return this.systemData; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SubscriptionQuotaAllocationsListInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SubscriptionQuotaAllocationsListInner 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 SubscriptionQuotaAllocationsListInner. + */ + public static SubscriptionQuotaAllocationsListInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SubscriptionQuotaAllocationsListInner deserializedSubscriptionQuotaAllocationsListInner + = new SubscriptionQuotaAllocationsListInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedSubscriptionQuotaAllocationsListInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedSubscriptionQuotaAllocationsListInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedSubscriptionQuotaAllocationsListInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedSubscriptionQuotaAllocationsListInner.properties + = SubscriptionQuotaAllocationsListProperties.fromJson(reader); + } else if ("systemData".equals(fieldName)) { + deserializedSubscriptionQuotaAllocationsListInner.systemData = SystemData.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedSubscriptionQuotaAllocationsListInner; + }); + } +} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/AzureQuotaExtensionApiImpl.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/AzureQuotaExtensionApiImpl.java index 7109619c4e87..37187893113d 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/AzureQuotaExtensionApiImpl.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/AzureQuotaExtensionApiImpl.java @@ -26,12 +26,10 @@ import com.azure.resourcemanager.quota.fluent.AzureQuotaExtensionApi; import com.azure.resourcemanager.quota.fluent.GroupQuotaLimitsClient; import com.azure.resourcemanager.quota.fluent.GroupQuotaLimitsRequestsClient; -import com.azure.resourcemanager.quota.fluent.GroupQuotaLocationSettingsClient; import com.azure.resourcemanager.quota.fluent.GroupQuotaSubscriptionAllocationRequestsClient; import com.azure.resourcemanager.quota.fluent.GroupQuotaSubscriptionAllocationsClient; import com.azure.resourcemanager.quota.fluent.GroupQuotaSubscriptionRequestsClient; import com.azure.resourcemanager.quota.fluent.GroupQuotaSubscriptionsClient; -import com.azure.resourcemanager.quota.fluent.GroupQuotaUsagesClient; import com.azure.resourcemanager.quota.fluent.GroupQuotasClient; import com.azure.resourcemanager.quota.fluent.QuotaOperationsClient; import com.azure.resourcemanager.quota.fluent.QuotaRequestStatusClient; @@ -177,20 +175,6 @@ public GroupQuotaSubscriptionRequestsClient getGroupQuotaSubscriptionRequests() return this.groupQuotaSubscriptionRequests; } - /** - * The GroupQuotaLimitsClient object to access its operations. - */ - private final GroupQuotaLimitsClient groupQuotaLimits; - - /** - * Gets the GroupQuotaLimitsClient object to access its operations. - * - * @return the GroupQuotaLimitsClient object. - */ - public GroupQuotaLimitsClient getGroupQuotaLimits() { - return this.groupQuotaLimits; - } - /** * The GroupQuotaLimitsRequestsClient object to access its operations. */ @@ -206,17 +190,17 @@ public GroupQuotaLimitsRequestsClient getGroupQuotaLimitsRequests() { } /** - * The GroupQuotaSubscriptionAllocationsClient object to access its operations. + * The GroupQuotaLimitsClient object to access its operations. */ - private final GroupQuotaSubscriptionAllocationsClient groupQuotaSubscriptionAllocations; + private final GroupQuotaLimitsClient groupQuotaLimits; /** - * Gets the GroupQuotaSubscriptionAllocationsClient object to access its operations. + * Gets the GroupQuotaLimitsClient object to access its operations. * - * @return the GroupQuotaSubscriptionAllocationsClient object. + * @return the GroupQuotaLimitsClient object. */ - public GroupQuotaSubscriptionAllocationsClient getGroupQuotaSubscriptionAllocations() { - return this.groupQuotaSubscriptionAllocations; + public GroupQuotaLimitsClient getGroupQuotaLimits() { + return this.groupQuotaLimits; } /** @@ -234,31 +218,17 @@ public GroupQuotaSubscriptionAllocationRequestsClient getGroupQuotaSubscriptionA } /** - * The GroupQuotaUsagesClient object to access its operations. - */ - private final GroupQuotaUsagesClient groupQuotaUsages; - - /** - * Gets the GroupQuotaUsagesClient object to access its operations. - * - * @return the GroupQuotaUsagesClient object. - */ - public GroupQuotaUsagesClient getGroupQuotaUsages() { - return this.groupQuotaUsages; - } - - /** - * The GroupQuotaLocationSettingsClient object to access its operations. + * The GroupQuotaSubscriptionAllocationsClient object to access its operations. */ - private final GroupQuotaLocationSettingsClient groupQuotaLocationSettings; + private final GroupQuotaSubscriptionAllocationsClient groupQuotaSubscriptionAllocations; /** - * Gets the GroupQuotaLocationSettingsClient object to access its operations. + * Gets the GroupQuotaSubscriptionAllocationsClient object to access its operations. * - * @return the GroupQuotaLocationSettingsClient object. + * @return the GroupQuotaSubscriptionAllocationsClient object. */ - public GroupQuotaLocationSettingsClient getGroupQuotaLocationSettings() { - return this.groupQuotaLocationSettings; + public GroupQuotaSubscriptionAllocationsClient getGroupQuotaSubscriptionAllocations() { + return this.groupQuotaSubscriptionAllocations; } /** @@ -334,16 +304,14 @@ public QuotaOperationsClient getQuotaOperations() { this.defaultPollInterval = defaultPollInterval; this.subscriptionId = subscriptionId; this.endpoint = endpoint; - this.apiVersion = "2023-06-01-preview"; + this.apiVersion = "2025-03-01"; this.groupQuotas = new GroupQuotasClientImpl(this); this.groupQuotaSubscriptions = new GroupQuotaSubscriptionsClientImpl(this); this.groupQuotaSubscriptionRequests = new GroupQuotaSubscriptionRequestsClientImpl(this); - this.groupQuotaLimits = new GroupQuotaLimitsClientImpl(this); this.groupQuotaLimitsRequests = new GroupQuotaLimitsRequestsClientImpl(this); - this.groupQuotaSubscriptionAllocations = new GroupQuotaSubscriptionAllocationsClientImpl(this); + this.groupQuotaLimits = new GroupQuotaLimitsClientImpl(this); this.groupQuotaSubscriptionAllocationRequests = new GroupQuotaSubscriptionAllocationRequestsClientImpl(this); - this.groupQuotaUsages = new GroupQuotaUsagesClientImpl(this); - this.groupQuotaLocationSettings = new GroupQuotaLocationSettingsClientImpl(this); + this.groupQuotaSubscriptionAllocations = new GroupQuotaSubscriptionAllocationsClientImpl(this); this.usages = new UsagesClientImpl(this); this.quotas = new QuotasClientImpl(this); this.quotaRequestStatus = new QuotaRequestStatusClientImpl(this); diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaLimitImpl.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaLimitImpl.java deleted file mode 100644 index bd8ac2a0f09d..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaLimitImpl.java +++ /dev/null @@ -1,49 +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.resourcemanager.quota.implementation; - -import com.azure.core.management.SystemData; -import com.azure.resourcemanager.quota.fluent.models.GroupQuotaLimitInner; -import com.azure.resourcemanager.quota.models.GroupQuotaDetails; -import com.azure.resourcemanager.quota.models.GroupQuotaLimit; - -public final class GroupQuotaLimitImpl implements GroupQuotaLimit { - private GroupQuotaLimitInner innerObject; - - private final com.azure.resourcemanager.quota.QuotaManager serviceManager; - - GroupQuotaLimitImpl(GroupQuotaLimitInner innerObject, com.azure.resourcemanager.quota.QuotaManager serviceManager) { - this.innerObject = innerObject; - this.serviceManager = serviceManager; - } - - public String id() { - return this.innerModel().id(); - } - - public String name() { - return this.innerModel().name(); - } - - public String type() { - return this.innerModel().type(); - } - - public GroupQuotaDetails properties() { - return this.innerModel().properties(); - } - - public SystemData systemData() { - return this.innerModel().systemData(); - } - - public GroupQuotaLimitInner innerModel() { - return this.innerObject; - } - - private com.azure.resourcemanager.quota.QuotaManager manager() { - return this.serviceManager; - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaLimitListImpl.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaLimitListImpl.java new file mode 100644 index 000000000000..01bcc6bcbcf7 --- /dev/null +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaLimitListImpl.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.quota.implementation; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.quota.fluent.models.GroupQuotaLimitListInner; +import com.azure.resourcemanager.quota.models.GroupQuotaLimitList; +import com.azure.resourcemanager.quota.models.GroupQuotaLimitListProperties; + +public final class GroupQuotaLimitListImpl implements GroupQuotaLimitList { + private GroupQuotaLimitListInner innerObject; + + private final com.azure.resourcemanager.quota.QuotaManager serviceManager; + + GroupQuotaLimitListImpl(GroupQuotaLimitListInner innerObject, + com.azure.resourcemanager.quota.QuotaManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public GroupQuotaLimitListProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public GroupQuotaLimitListInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.quota.QuotaManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaLimitsClientImpl.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaLimitsClientImpl.java index 97c9435025fe..32f9a9a0e799 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaLimitsClientImpl.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaLimitsClientImpl.java @@ -16,18 +16,13 @@ import com.azure.core.annotation.ServiceInterface; import com.azure.core.annotation.ServiceMethod; import com.azure.core.annotation.UnexpectedResponseExceptionType; -import com.azure.core.http.rest.PagedFlux; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.PagedResponse; -import com.azure.core.http.rest.PagedResponseBase; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.RestProxy; import com.azure.core.management.exception.ManagementException; import com.azure.core.util.Context; import com.azure.core.util.FluxUtil; import com.azure.resourcemanager.quota.fluent.GroupQuotaLimitsClient; -import com.azure.resourcemanager.quota.fluent.models.GroupQuotaLimitInner; -import com.azure.resourcemanager.quota.models.GroupQuotaLimitList; +import com.azure.resourcemanager.quota.fluent.models.GroupQuotaLimitListInner; import reactor.core.publisher.Mono; /** @@ -63,63 +58,34 @@ public final class GroupQuotaLimitsClientImpl implements GroupQuotaLimitsClient @ServiceInterface(name = "AzureQuotaExtensionA") public interface GroupQuotaLimitsService { @Headers({ "Content-Type: application/json" }) - @Get("/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Quota/groupQuotas/{groupQuotaName}/resourceProviders/{resourceProviderName}/groupQuotaLimits/{resourceName}") + @Get("/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Quota/groupQuotas/{groupQuotaName}/resourceProviders/{resourceProviderName}/groupQuotaLimits/{location}") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono> get(@HostParam("$host") String endpoint, + Mono> list(@HostParam("$host") String endpoint, @PathParam("managementGroupId") String managementGroupId, @PathParam("groupQuotaName") String groupQuotaName, - @PathParam("resourceProviderName") String resourceProviderName, - @PathParam("resourceName") String resourceName, @QueryParam("api-version") String apiVersion, - @QueryParam("$filter") String filter, @HeaderParam("Accept") String accept, Context context); - - @Headers({ "Content-Type: application/json" }) - @Get("/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Quota/groupQuotas/{groupQuotaName}/resourceProviders/{resourceProviderName}/groupQuotaLimits") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> list(@HostParam("$host") String endpoint, - @PathParam("managementGroupId") String managementGroupId, - @PathParam("groupQuotaName") String groupQuotaName, - @PathParam("resourceProviderName") String resourceProviderName, - @QueryParam("api-version") String apiVersion, @QueryParam("$filter") String filter, - @HeaderParam("Accept") String accept, Context context); - - @Headers({ "Content-Type: application/json" }) - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> listNext(@PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("$host") String endpoint, @HeaderParam("Accept") String accept, Context context); + @PathParam("resourceProviderName") String resourceProviderName, @PathParam("location") String location, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); } /** - * Gets the GroupQuotaLimits for the specific resource. - * - * Gets the GroupQuotaLimits for the specific resource for a specific resource based on the resourceProviders, - * resourceName and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota. + * Gets the GroupQuotaLimits for the specified resource provider and location for resource names passed in + * $filter=resourceName eq {SKU}. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. + * @param location The name of the Azure region. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotaLimits for the specific resource for a specific resource based on the resourceProviders, - * resourceName and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota along with - * {@link Response} on successful completion of {@link Mono}. + * @return the GroupQuotaLimits for the specified resource provider and location for resource names passed in + * $filter=resourceName eq {SKU} along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> getWithResponseAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName, String filter) { + private Mono> listWithResponseAsync(String managementGroupId, + String groupQuotaName, String resourceProviderName, String location) { if (this.client.getEndpoint() == null) { return Mono.error( new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); @@ -135,48 +101,35 @@ private Mono> getWithResponseAsync(String managem return Mono .error(new IllegalArgumentException("Parameter resourceProviderName is required and cannot be null.")); } - if (resourceName == null) { - return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); - } - if (filter == null) { - return Mono.error(new IllegalArgumentException("Parameter filter is required and cannot be null.")); + if (location == null) { + return Mono.error(new IllegalArgumentException("Parameter location is required and cannot be null.")); } final String accept = "application/json"; return FluxUtil - .withContext(context -> service.get(this.client.getEndpoint(), managementGroupId, groupQuotaName, - resourceProviderName, resourceName, this.client.getApiVersion(), filter, accept, context)) + .withContext(context -> service.list(this.client.getEndpoint(), managementGroupId, groupQuotaName, + resourceProviderName, location, this.client.getApiVersion(), accept, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** - * Gets the GroupQuotaLimits for the specific resource. - * - * Gets the GroupQuotaLimits for the specific resource for a specific resource based on the resourceProviders, - * resourceName and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota. + * Gets the GroupQuotaLimits for the specified resource provider and location for resource names passed in + * $filter=resourceName eq {SKU}. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. + * @param location The name of the Azure region. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotaLimits for the specific resource for a specific resource based on the resourceProviders, - * resourceName and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota along with - * {@link Response} on successful completion of {@link Mono}. + * @return the GroupQuotaLimits for the specified resource provider and location for resource names passed in + * $filter=resourceName eq {SKU} along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> getWithResponseAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName, String filter, Context context) { + private Mono> listWithResponseAsync(String managementGroupId, + String groupQuotaName, String resourceProviderName, String location, Context context) { if (this.client.getEndpoint() == null) { return Mono.error( new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); @@ -192,387 +145,79 @@ private Mono> getWithResponseAsync(String managem return Mono .error(new IllegalArgumentException("Parameter resourceProviderName is required and cannot be null.")); } - if (resourceName == null) { - return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); - } - if (filter == null) { - return Mono.error(new IllegalArgumentException("Parameter filter is required and cannot be null.")); + if (location == null) { + return Mono.error(new IllegalArgumentException("Parameter location is required and cannot be null.")); } final String accept = "application/json"; context = this.client.mergeContext(context); - return service.get(this.client.getEndpoint(), managementGroupId, groupQuotaName, resourceProviderName, - resourceName, this.client.getApiVersion(), filter, accept, context); + return service.list(this.client.getEndpoint(), managementGroupId, groupQuotaName, resourceProviderName, + location, this.client.getApiVersion(), accept, context); } /** - * Gets the GroupQuotaLimits for the specific resource. - * - * Gets the GroupQuotaLimits for the specific resource for a specific resource based on the resourceProviders, - * resourceName and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota. + * Gets the GroupQuotaLimits for the specified resource provider and location for resource names passed in + * $filter=resourceName eq {SKU}. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. + * @param location The name of the Azure region. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotaLimits for the specific resource for a specific resource based on the resourceProviders, - * resourceName and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota on successful completion - * of {@link Mono}. + * @return the GroupQuotaLimits for the specified resource provider and location for resource names passed in + * $filter=resourceName eq {SKU} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono getAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName, String filter) { - return getWithResponseAsync(managementGroupId, groupQuotaName, resourceProviderName, resourceName, filter) + private Mono listAsync(String managementGroupId, String groupQuotaName, + String resourceProviderName, String location) { + return listWithResponseAsync(managementGroupId, groupQuotaName, resourceProviderName, location) .flatMap(res -> Mono.justOrEmpty(res.getValue())); } /** - * Gets the GroupQuotaLimits for the specific resource. - * - * Gets the GroupQuotaLimits for the specific resource for a specific resource based on the resourceProviders, - * resourceName and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota. + * Gets the GroupQuotaLimits for the specified resource provider and location for resource names passed in + * $filter=resourceName eq {SKU}. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. + * @param location The name of the Azure region. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotaLimits for the specific resource for a specific resource based on the resourceProviders, - * resourceName and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota along with - * {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getWithResponse(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName, String filter, Context context) { - return getWithResponseAsync(managementGroupId, groupQuotaName, resourceProviderName, resourceName, filter, - context).block(); - } - - /** - * Gets the GroupQuotaLimits for the specific resource. - * - * Gets the GroupQuotaLimits for the specific resource for a specific resource based on the resourceProviders, - * resourceName and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotaLimits for the specific resource for a specific resource based on the resourceProviders, - * resourceName and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public GroupQuotaLimitInner get(String managementGroupId, String groupQuotaName, String resourceProviderName, - String resourceName, String filter) { - return getWithResponse(managementGroupId, groupQuotaName, resourceProviderName, resourceName, filter, - Context.NONE).getValue(); - } - - /** - * Gets the GroupQuotaLimits for all the resources for the specified location in $filter=location eq {location}. - * - * Gets the GroupQuotaLimits for the all resource for a specific resourceProvider and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotaLimits for the all resource for a specific resourceProvider and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota along with - * {@link PagedResponse} on successful completion of {@link Mono}. + * @return the GroupQuotaLimits for the specified resource provider and location for resource names passed in + * $filter=resourceName eq {SKU} along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listSinglePageAsync(String managementGroupId, - String groupQuotaName, String resourceProviderName, String filter) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (managementGroupId == null) { - return Mono - .error(new IllegalArgumentException("Parameter managementGroupId is required and cannot be null.")); - } - if (groupQuotaName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupQuotaName is required and cannot be null.")); - } - if (resourceProviderName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceProviderName is required and cannot be null.")); - } - if (filter == null) { - return Mono.error(new IllegalArgumentException("Parameter filter is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.list(this.client.getEndpoint(), managementGroupId, groupQuotaName, - resourceProviderName, this.client.getApiVersion(), filter, accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), - res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + public Response listWithResponse(String managementGroupId, String groupQuotaName, + String resourceProviderName, String location, Context context) { + return listWithResponseAsync(managementGroupId, groupQuotaName, resourceProviderName, location, context) + .block(); } /** - * Gets the GroupQuotaLimits for all the resources for the specified location in $filter=location eq {location}. - * - * Gets the GroupQuotaLimits for the all resource for a specific resourceProvider and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota. + * Gets the GroupQuotaLimits for the specified resource provider and location for resource names passed in + * $filter=resourceName eq {SKU}. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. - * @param context The context to associate with this operation. + * @param location The name of the Azure region. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotaLimits for the all resource for a specific resourceProvider and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota along with - * {@link PagedResponse} on successful completion of {@link Mono}. + * @return the GroupQuotaLimits for the specified resource provider and location for resource names passed in + * $filter=resourceName eq {SKU}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listSinglePageAsync(String managementGroupId, - String groupQuotaName, String resourceProviderName, String filter, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (managementGroupId == null) { - return Mono - .error(new IllegalArgumentException("Parameter managementGroupId is required and cannot be null.")); - } - if (groupQuotaName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupQuotaName is required and cannot be null.")); - } - if (resourceProviderName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceProviderName is required and cannot be null.")); - } - if (filter == null) { - return Mono.error(new IllegalArgumentException("Parameter filter is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service - .list(this.client.getEndpoint(), managementGroupId, groupQuotaName, resourceProviderName, - this.client.getApiVersion(), filter, accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } - - /** - * Gets the GroupQuotaLimits for all the resources for the specified location in $filter=location eq {location}. - * - * Gets the GroupQuotaLimits for the all resource for a specific resourceProvider and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotaLimits for the all resource for a specific resourceProvider and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota as paginated response - * with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String filter) { - return new PagedFlux<>( - () -> listSinglePageAsync(managementGroupId, groupQuotaName, resourceProviderName, filter), - nextLink -> listNextSinglePageAsync(nextLink)); - } - - /** - * Gets the GroupQuotaLimits for all the resources for the specified location in $filter=location eq {location}. - * - * Gets the GroupQuotaLimits for the all resource for a specific resourceProvider and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotaLimits for the all resource for a specific resourceProvider and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota as paginated response - * with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String filter, Context context) { - return new PagedFlux<>( - () -> listSinglePageAsync(managementGroupId, groupQuotaName, resourceProviderName, filter, context), - nextLink -> listNextSinglePageAsync(nextLink, context)); - } - - /** - * Gets the GroupQuotaLimits for all the resources for the specified location in $filter=location eq {location}. - * - * Gets the GroupQuotaLimits for the all resource for a specific resourceProvider and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotaLimits for the all resource for a specific resourceProvider and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota as paginated response - * with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list(String managementGroupId, String groupQuotaName, - String resourceProviderName, String filter) { - return new PagedIterable<>(listAsync(managementGroupId, groupQuotaName, resourceProviderName, filter)); - } - - /** - * Gets the GroupQuotaLimits for all the resources for the specified location in $filter=location eq {location}. - * - * Gets the GroupQuotaLimits for the all resource for a specific resourceProvider and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotaLimits for the all resource for a specific resourceProvider and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota as paginated response - * with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list(String managementGroupId, String groupQuotaName, - String resourceProviderName, String filter, Context context) { - return new PagedIterable<>(listAsync(managementGroupId, groupQuotaName, resourceProviderName, filter, context)); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return list of Group Quota Limit details along with {@link PagedResponse} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listNextSinglePageAsync(String nextLink) { - if (nextLink == null) { - return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - } - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.listNext(nextLink, this.client.getEndpoint(), accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), - res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return list of Group Quota Limit details along with {@link PagedResponse} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listNextSinglePageAsync(String nextLink, Context context) { - if (nextLink == null) { - return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - } - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.listNext(nextLink, this.client.getEndpoint(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); + public GroupQuotaLimitListInner list(String managementGroupId, String groupQuotaName, String resourceProviderName, + String location) { + return listWithResponse(managementGroupId, groupQuotaName, resourceProviderName, location, Context.NONE) + .getValue(); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaLimitsImpl.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaLimitsImpl.java index 8fc70a38820e..3b14b090e101 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaLimitsImpl.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaLimitsImpl.java @@ -4,14 +4,13 @@ package com.azure.resourcemanager.quota.implementation; -import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.SimpleResponse; import com.azure.core.util.Context; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.quota.fluent.GroupQuotaLimitsClient; -import com.azure.resourcemanager.quota.fluent.models.GroupQuotaLimitInner; -import com.azure.resourcemanager.quota.models.GroupQuotaLimit; +import com.azure.resourcemanager.quota.fluent.models.GroupQuotaLimitListInner; +import com.azure.resourcemanager.quota.models.GroupQuotaLimitList; import com.azure.resourcemanager.quota.models.GroupQuotaLimits; public final class GroupQuotaLimitsImpl implements GroupQuotaLimits { @@ -27,43 +26,29 @@ public GroupQuotaLimitsImpl(GroupQuotaLimitsClient innerClient, this.serviceManager = serviceManager; } - public Response getWithResponse(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName, String filter, Context context) { - Response inner = this.serviceClient() - .getWithResponse(managementGroupId, groupQuotaName, resourceProviderName, resourceName, filter, context); + public Response listWithResponse(String managementGroupId, String groupQuotaName, + String resourceProviderName, String location, Context context) { + Response inner = this.serviceClient() + .listWithResponse(managementGroupId, groupQuotaName, resourceProviderName, location, context); if (inner != null) { return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), - new GroupQuotaLimitImpl(inner.getValue(), this.manager())); + new GroupQuotaLimitListImpl(inner.getValue(), this.manager())); } else { return null; } } - public GroupQuotaLimit get(String managementGroupId, String groupQuotaName, String resourceProviderName, - String resourceName, String filter) { - GroupQuotaLimitInner inner - = this.serviceClient().get(managementGroupId, groupQuotaName, resourceProviderName, resourceName, filter); + public GroupQuotaLimitList list(String managementGroupId, String groupQuotaName, String resourceProviderName, + String location) { + GroupQuotaLimitListInner inner + = this.serviceClient().list(managementGroupId, groupQuotaName, resourceProviderName, location); if (inner != null) { - return new GroupQuotaLimitImpl(inner, this.manager()); + return new GroupQuotaLimitListImpl(inner, this.manager()); } else { return null; } } - public PagedIterable list(String managementGroupId, String groupQuotaName, - String resourceProviderName, String filter) { - PagedIterable inner - = this.serviceClient().list(managementGroupId, groupQuotaName, resourceProviderName, filter); - return ResourceManagerUtils.mapPage(inner, inner1 -> new GroupQuotaLimitImpl(inner1, this.manager())); - } - - public PagedIterable list(String managementGroupId, String groupQuotaName, - String resourceProviderName, String filter, Context context) { - PagedIterable inner - = this.serviceClient().list(managementGroupId, groupQuotaName, resourceProviderName, filter, context); - return ResourceManagerUtils.mapPage(inner, inner1 -> new GroupQuotaLimitImpl(inner1, this.manager())); - } - private GroupQuotaLimitsClient serviceClient() { return this.innerClient; } diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaLimitsRequestsClientImpl.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaLimitsRequestsClientImpl.java index 783e76dc84a5..5129963836d4 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaLimitsRequestsClientImpl.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaLimitsRequestsClientImpl.java @@ -13,7 +13,6 @@ import com.azure.core.annotation.HostParam; import com.azure.core.annotation.Patch; import com.azure.core.annotation.PathParam; -import com.azure.core.annotation.Put; import com.azure.core.annotation.QueryParam; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceInterface; @@ -25,7 +24,6 @@ import com.azure.core.http.rest.PagedResponseBase; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.RestProxy; -import com.azure.core.management.ProxyResource; import com.azure.core.management.exception.ManagementException; import com.azure.core.management.polling.PollResult; import com.azure.core.util.Context; @@ -33,6 +31,7 @@ import com.azure.core.util.polling.PollerFlux; import com.azure.core.util.polling.SyncPoller; import com.azure.resourcemanager.quota.fluent.GroupQuotaLimitsRequestsClient; +import com.azure.resourcemanager.quota.fluent.models.GroupQuotaLimitListInner; import com.azure.resourcemanager.quota.fluent.models.SubmittedResourceRequestStatusInner; import com.azure.resourcemanager.quota.models.SubmittedResourceRequestStatusList; import java.nio.ByteBuffer; @@ -72,27 +71,15 @@ public final class GroupQuotaLimitsRequestsClientImpl implements GroupQuotaLimit @ServiceInterface(name = "AzureQuotaExtensionA") public interface GroupQuotaLimitsRequestsService { @Headers({ "Content-Type: application/json" }) - @Put("/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Quota/groupQuotas/{groupQuotaName}/resourceProviders/{resourceProviderName}/groupQuotaRequests/{resourceName}") - @ExpectedResponses({ 200, 201 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono>> createOrUpdate(@HostParam("$host") String endpoint, - @PathParam("managementGroupId") String managementGroupId, - @PathParam("groupQuotaName") String groupQuotaName, - @PathParam("resourceProviderName") String resourceProviderName, - @PathParam("resourceName") String resourceName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") SubmittedResourceRequestStatusInner groupQuotaRequest, - @HeaderParam("Accept") String accept, Context context); - - @Headers({ "Content-Type: application/json" }) - @Patch("/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Quota/groupQuotas/{groupQuotaName}/resourceProviders/{resourceProviderName}/groupQuotaRequests/{resourceName}") + @Patch("/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Quota/groupQuotas/{groupQuotaName}/resourceProviders/{resourceProviderName}/groupQuotaLimits/{location}") @ExpectedResponses({ 200, 202 }) @UnexpectedResponseExceptionType(ManagementException.class) Mono>> update(@HostParam("$host") String endpoint, @PathParam("managementGroupId") String managementGroupId, @PathParam("groupQuotaName") String groupQuotaName, - @PathParam("resourceProviderName") String resourceProviderName, - @PathParam("resourceName") String resourceName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") SubmittedResourceRequestStatusInner groupQuotaRequest, + @PathParam("resourceProviderName") String resourceProviderName, @PathParam("location") String location, + @QueryParam("api-version") String apiVersion, + @BodyParam("application/json") GroupQuotaLimitListInner groupQuotaRequest, @HeaderParam("Accept") String accept, Context context); @Headers({ "Content-Type: application/json" }) @@ -124,419 +111,12 @@ Mono> listNext( @HeaderParam("Accept") String accept, Context context); } - /** - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. - * - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * ("name": {"value" : "resourceName") properties are specified in the request body. Only 1 resource quota can be - * requested. - * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after - * duration in seconds to check the intermediate status. This API provides the finals status with the request - * details and status. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param groupQuotaRequest The GroupQuotaRequest body details for specific resourceProvider/location/resources. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return status of a single GroupQuota request along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> createOrUpdateWithResponseAsync(String managementGroupId, - String groupQuotaName, String resourceProviderName, String resourceName, - SubmittedResourceRequestStatusInner groupQuotaRequest) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (managementGroupId == null) { - return Mono - .error(new IllegalArgumentException("Parameter managementGroupId is required and cannot be null.")); - } - if (groupQuotaName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupQuotaName is required and cannot be null.")); - } - if (resourceProviderName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceProviderName is required and cannot be null.")); - } - if (resourceName == null) { - return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); - } - if (groupQuotaRequest != null) { - groupQuotaRequest.validate(); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.createOrUpdate(this.client.getEndpoint(), managementGroupId, groupQuotaName, - resourceProviderName, resourceName, this.client.getApiVersion(), groupQuotaRequest, accept, context)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. - * - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * ("name": {"value" : "resourceName") properties are specified in the request body. Only 1 resource quota can be - * requested. - * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after - * duration in seconds to check the intermediate status. This API provides the finals status with the request - * details and status. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param groupQuotaRequest The GroupQuotaRequest body details for specific resourceProvider/location/resources. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return status of a single GroupQuota request along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> createOrUpdateWithResponseAsync(String managementGroupId, - String groupQuotaName, String resourceProviderName, String resourceName, - SubmittedResourceRequestStatusInner groupQuotaRequest, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (managementGroupId == null) { - return Mono - .error(new IllegalArgumentException("Parameter managementGroupId is required and cannot be null.")); - } - if (groupQuotaName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupQuotaName is required and cannot be null.")); - } - if (resourceProviderName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceProviderName is required and cannot be null.")); - } - if (resourceName == null) { - return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); - } - if (groupQuotaRequest != null) { - groupQuotaRequest.validate(); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.createOrUpdate(this.client.getEndpoint(), managementGroupId, groupQuotaName, - resourceProviderName, resourceName, this.client.getApiVersion(), groupQuotaRequest, accept, context); - } - - /** - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. - * - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * ("name": {"value" : "resourceName") properties are specified in the request body. Only 1 resource quota can be - * requested. - * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after - * duration in seconds to check the intermediate status. This API provides the finals status with the request - * details and status. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param groupQuotaRequest The GroupQuotaRequest body details for specific resourceProvider/location/resources. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of status of a single GroupQuota request. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, ProxyResource> beginCreateOrUpdateAsync(String managementGroupId, - String groupQuotaName, String resourceProviderName, String resourceName, - SubmittedResourceRequestStatusInner groupQuotaRequest) { - Mono>> mono = createOrUpdateWithResponseAsync(managementGroupId, groupQuotaName, - resourceProviderName, resourceName, groupQuotaRequest); - return this.client.getLroResult(mono, this.client.getHttpPipeline(), - ProxyResource.class, ProxyResource.class, this.client.getContext()); - } - - /** - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. - * - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * ("name": {"value" : "resourceName") properties are specified in the request body. Only 1 resource quota can be - * requested. - * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after - * duration in seconds to check the intermediate status. This API provides the finals status with the request - * details and status. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of status of a single GroupQuota request. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, ProxyResource> beginCreateOrUpdateAsync(String managementGroupId, - String groupQuotaName, String resourceProviderName, String resourceName) { - final SubmittedResourceRequestStatusInner groupQuotaRequest = null; - Mono>> mono = createOrUpdateWithResponseAsync(managementGroupId, groupQuotaName, - resourceProviderName, resourceName, groupQuotaRequest); - return this.client.getLroResult(mono, this.client.getHttpPipeline(), - ProxyResource.class, ProxyResource.class, this.client.getContext()); - } - - /** - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. - * - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * ("name": {"value" : "resourceName") properties are specified in the request body. Only 1 resource quota can be - * requested. - * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after - * duration in seconds to check the intermediate status. This API provides the finals status with the request - * details and status. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param groupQuotaRequest The GroupQuotaRequest body details for specific resourceProvider/location/resources. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of status of a single GroupQuota request. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, ProxyResource> beginCreateOrUpdateAsync(String managementGroupId, - String groupQuotaName, String resourceProviderName, String resourceName, - SubmittedResourceRequestStatusInner groupQuotaRequest, Context context) { - context = this.client.mergeContext(context); - Mono>> mono = createOrUpdateWithResponseAsync(managementGroupId, groupQuotaName, - resourceProviderName, resourceName, groupQuotaRequest, context); - return this.client.getLroResult(mono, this.client.getHttpPipeline(), - ProxyResource.class, ProxyResource.class, context); - } - - /** - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. - * - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * ("name": {"value" : "resourceName") properties are specified in the request body. Only 1 resource quota can be - * requested. - * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after - * duration in seconds to check the intermediate status. This API provides the finals status with the request - * details and status. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of status of a single GroupQuota request. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, ProxyResource> beginCreateOrUpdate(String managementGroupId, - String groupQuotaName, String resourceProviderName, String resourceName) { - final SubmittedResourceRequestStatusInner groupQuotaRequest = null; - return this - .beginCreateOrUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, resourceName, - groupQuotaRequest) - .getSyncPoller(); - } - - /** - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. - * - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * ("name": {"value" : "resourceName") properties are specified in the request body. Only 1 resource quota can be - * requested. - * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after - * duration in seconds to check the intermediate status. This API provides the finals status with the request - * details and status. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param groupQuotaRequest The GroupQuotaRequest body details for specific resourceProvider/location/resources. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of status of a single GroupQuota request. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, ProxyResource> beginCreateOrUpdate(String managementGroupId, - String groupQuotaName, String resourceProviderName, String resourceName, - SubmittedResourceRequestStatusInner groupQuotaRequest, Context context) { - return this - .beginCreateOrUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, resourceName, - groupQuotaRequest, context) - .getSyncPoller(); - } - - /** - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. - * - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * ("name": {"value" : "resourceName") properties are specified in the request body. Only 1 resource quota can be - * requested. - * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after - * duration in seconds to check the intermediate status. This API provides the finals status with the request - * details and status. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param groupQuotaRequest The GroupQuotaRequest body details for specific resourceProvider/location/resources. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return status of a single GroupQuota request on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono createOrUpdateAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName, SubmittedResourceRequestStatusInner groupQuotaRequest) { - return beginCreateOrUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, resourceName, - groupQuotaRequest).last().flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. - * - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * ("name": {"value" : "resourceName") properties are specified in the request body. Only 1 resource quota can be - * requested. - * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after - * duration in seconds to check the intermediate status. This API provides the finals status with the request - * details and status. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return status of a single GroupQuota request on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono createOrUpdateAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName) { - final SubmittedResourceRequestStatusInner groupQuotaRequest = null; - return beginCreateOrUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, resourceName, - groupQuotaRequest).last().flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. - * - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * ("name": {"value" : "resourceName") properties are specified in the request body. Only 1 resource quota can be - * requested. - * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after - * duration in seconds to check the intermediate status. This API provides the finals status with the request - * details and status. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param groupQuotaRequest The GroupQuotaRequest body details for specific resourceProvider/location/resources. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return status of a single GroupQuota request on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono createOrUpdateAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName, SubmittedResourceRequestStatusInner groupQuotaRequest, - Context context) { - return beginCreateOrUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, resourceName, - groupQuotaRequest, context).last().flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. - * - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * ("name": {"value" : "resourceName") properties are specified in the request body. Only 1 resource quota can be - * requested. - * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after - * duration in seconds to check the intermediate status. This API provides the finals status with the request - * details and status. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return status of a single GroupQuota request. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public ProxyResource createOrUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, - String resourceName) { - final SubmittedResourceRequestStatusInner groupQuotaRequest = null; - return createOrUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, resourceName, - groupQuotaRequest).block(); - } - - /** - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. - * - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * ("name": {"value" : "resourceName") properties are specified in the request body. Only 1 resource quota can be - * requested. - * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after - * duration in seconds to check the intermediate status. This API provides the finals status with the request - * details and status. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param groupQuotaRequest The GroupQuotaRequest body details for specific resourceProvider/location/resources. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return status of a single GroupQuota request. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public ProxyResource createOrUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, - String resourceName, SubmittedResourceRequestStatusInner groupQuotaRequest, Context context) { - return createOrUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, resourceName, - groupQuotaRequest, context).block(); - } - /** * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. * - * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * properties are specified in the request body. Only 1 resource quota can be requested. Please note that patch - * request creates a new groupQuota request. + * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. The resourceName properties are + * specified in the request body. Only 1 resource quota can be requested. Please note that patch request creates a + * new groupQuota request. * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after * duration in seconds to check the intermediate status. This API provides the finals status with the request * details and status. @@ -545,17 +125,16 @@ public ProxyResource createOrUpdate(String managementGroupId, String groupQuotaN * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. + * @param location The name of the Azure region. * @param groupQuotaRequest The GroupQuotaRequest body details for specific resourceProvider/location/resources. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return status of a single GroupQuota request along with {@link Response} on successful completion of - * {@link Mono}. + * @return list of Group Quota Limit details along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono>> updateWithResponseAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName, SubmittedResourceRequestStatusInner groupQuotaRequest) { + String resourceProviderName, String location, GroupQuotaLimitListInner groupQuotaRequest) { if (this.client.getEndpoint() == null) { return Mono.error( new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); @@ -571,8 +150,8 @@ private Mono>> updateWithResponseAsync(String manageme return Mono .error(new IllegalArgumentException("Parameter resourceProviderName is required and cannot be null.")); } - if (resourceName == null) { - return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); + if (location == null) { + return Mono.error(new IllegalArgumentException("Parameter location is required and cannot be null.")); } if (groupQuotaRequest != null) { groupQuotaRequest.validate(); @@ -580,16 +159,16 @@ private Mono>> updateWithResponseAsync(String manageme final String accept = "application/json"; return FluxUtil .withContext(context -> service.update(this.client.getEndpoint(), managementGroupId, groupQuotaName, - resourceProviderName, resourceName, this.client.getApiVersion(), groupQuotaRequest, accept, context)) + resourceProviderName, location, this.client.getApiVersion(), groupQuotaRequest, accept, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. * - * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * properties are specified in the request body. Only 1 resource quota can be requested. Please note that patch - * request creates a new groupQuota request. + * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. The resourceName properties are + * specified in the request body. Only 1 resource quota can be requested. Please note that patch request creates a + * new groupQuota request. * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after * duration in seconds to check the intermediate status. This API provides the finals status with the request * details and status. @@ -598,19 +177,17 @@ private Mono>> updateWithResponseAsync(String manageme * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. + * @param location The name of the Azure region. * @param groupQuotaRequest The GroupQuotaRequest body details for specific resourceProvider/location/resources. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return status of a single GroupQuota request along with {@link Response} on successful completion of - * {@link Mono}. + * @return list of Group Quota Limit details along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono>> updateWithResponseAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName, SubmittedResourceRequestStatusInner groupQuotaRequest, - Context context) { + String resourceProviderName, String location, GroupQuotaLimitListInner groupQuotaRequest, Context context) { if (this.client.getEndpoint() == null) { return Mono.error( new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); @@ -626,8 +203,8 @@ private Mono>> updateWithResponseAsync(String manageme return Mono .error(new IllegalArgumentException("Parameter resourceProviderName is required and cannot be null.")); } - if (resourceName == null) { - return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); + if (location == null) { + return Mono.error(new IllegalArgumentException("Parameter location is required and cannot be null.")); } if (groupQuotaRequest != null) { groupQuotaRequest.validate(); @@ -635,15 +212,15 @@ private Mono>> updateWithResponseAsync(String manageme final String accept = "application/json"; context = this.client.mergeContext(context); return service.update(this.client.getEndpoint(), managementGroupId, groupQuotaName, resourceProviderName, - resourceName, this.client.getApiVersion(), groupQuotaRequest, accept, context); + location, this.client.getApiVersion(), groupQuotaRequest, accept, context); } /** * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. * - * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * properties are specified in the request body. Only 1 resource quota can be requested. Please note that patch - * request creates a new groupQuota request. + * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. The resourceName properties are + * specified in the request body. Only 1 resource quota can be requested. Please note that patch request creates a + * new groupQuota request. * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after * duration in seconds to check the intermediate status. This API provides the finals status with the request * details and status. @@ -652,30 +229,30 @@ private Mono>> updateWithResponseAsync(String manageme * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. + * @param location The name of the Azure region. * @param groupQuotaRequest The GroupQuotaRequest body details for specific resourceProvider/location/resources. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of status of a single GroupQuota request. + * @return the {@link PollerFlux} for polling of list of Group Quota Limit details. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, SubmittedResourceRequestStatusInner> - beginUpdateAsync(String managementGroupId, String groupQuotaName, String resourceProviderName, - String resourceName, SubmittedResourceRequestStatusInner groupQuotaRequest) { + private PollerFlux, GroupQuotaLimitListInner> beginUpdateAsync( + String managementGroupId, String groupQuotaName, String resourceProviderName, String location, + GroupQuotaLimitListInner groupQuotaRequest) { Mono>> mono = updateWithResponseAsync(managementGroupId, groupQuotaName, - resourceProviderName, resourceName, groupQuotaRequest); - return this.client.getLroResult(mono, - this.client.getHttpPipeline(), SubmittedResourceRequestStatusInner.class, - SubmittedResourceRequestStatusInner.class, this.client.getContext()); + resourceProviderName, location, groupQuotaRequest); + return this.client.getLroResult(mono, + this.client.getHttpPipeline(), GroupQuotaLimitListInner.class, GroupQuotaLimitListInner.class, + this.client.getContext()); } /** * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. * - * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * properties are specified in the request body. Only 1 resource quota can be requested. Please note that patch - * request creates a new groupQuota request. + * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. The resourceName properties are + * specified in the request body. Only 1 resource quota can be requested. Please note that patch request creates a + * new groupQuota request. * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after * duration in seconds to check the intermediate status. This API provides the finals status with the request * details and status. @@ -684,30 +261,29 @@ private Mono>> updateWithResponseAsync(String manageme * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. + * @param location The name of the Azure region. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of status of a single GroupQuota request. + * @return the {@link PollerFlux} for polling of list of Group Quota Limit details. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, SubmittedResourceRequestStatusInner> - beginUpdateAsync(String managementGroupId, String groupQuotaName, String resourceProviderName, - String resourceName) { - final SubmittedResourceRequestStatusInner groupQuotaRequest = null; + private PollerFlux, GroupQuotaLimitListInner> beginUpdateAsync( + String managementGroupId, String groupQuotaName, String resourceProviderName, String location) { + final GroupQuotaLimitListInner groupQuotaRequest = null; Mono>> mono = updateWithResponseAsync(managementGroupId, groupQuotaName, - resourceProviderName, resourceName, groupQuotaRequest); - return this.client.getLroResult(mono, - this.client.getHttpPipeline(), SubmittedResourceRequestStatusInner.class, - SubmittedResourceRequestStatusInner.class, this.client.getContext()); + resourceProviderName, location, groupQuotaRequest); + return this.client.getLroResult(mono, + this.client.getHttpPipeline(), GroupQuotaLimitListInner.class, GroupQuotaLimitListInner.class, + this.client.getContext()); } /** * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. * - * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * properties are specified in the request body. Only 1 resource quota can be requested. Please note that patch - * request creates a new groupQuota request. + * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. The resourceName properties are + * specified in the request body. Only 1 resource quota can be requested. Please note that patch request creates a + * new groupQuota request. * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after * duration in seconds to check the intermediate status. This API provides the finals status with the request * details and status. @@ -716,32 +292,31 @@ private Mono>> updateWithResponseAsync(String manageme * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. + * @param location The name of the Azure region. * @param groupQuotaRequest The GroupQuotaRequest body details for specific resourceProvider/location/resources. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of status of a single GroupQuota request. + * @return the {@link PollerFlux} for polling of list of Group Quota Limit details. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, SubmittedResourceRequestStatusInner> - beginUpdateAsync(String managementGroupId, String groupQuotaName, String resourceProviderName, - String resourceName, SubmittedResourceRequestStatusInner groupQuotaRequest, Context context) { + private PollerFlux, GroupQuotaLimitListInner> beginUpdateAsync( + String managementGroupId, String groupQuotaName, String resourceProviderName, String location, + GroupQuotaLimitListInner groupQuotaRequest, Context context) { context = this.client.mergeContext(context); Mono>> mono = updateWithResponseAsync(managementGroupId, groupQuotaName, - resourceProviderName, resourceName, groupQuotaRequest, context); - return this.client.getLroResult(mono, - this.client.getHttpPipeline(), SubmittedResourceRequestStatusInner.class, - SubmittedResourceRequestStatusInner.class, context); + resourceProviderName, location, groupQuotaRequest, context); + return this.client.getLroResult(mono, + this.client.getHttpPipeline(), GroupQuotaLimitListInner.class, GroupQuotaLimitListInner.class, context); } /** * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. * - * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * properties are specified in the request body. Only 1 resource quota can be requested. Please note that patch - * request creates a new groupQuota request. + * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. The resourceName properties are + * specified in the request body. Only 1 resource quota can be requested. Please note that patch request creates a + * new groupQuota request. * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after * duration in seconds to check the intermediate status. This API provides the finals status with the request * details and status. @@ -750,27 +325,27 @@ private Mono>> updateWithResponseAsync(String manageme * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. + * @param location The name of the Azure region. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of status of a single GroupQuota request. + * @return the {@link SyncPoller} for polling of list of Group Quota Limit details. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, SubmittedResourceRequestStatusInner> - beginUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, String resourceName) { - final SubmittedResourceRequestStatusInner groupQuotaRequest = null; + public SyncPoller, GroupQuotaLimitListInner> + beginUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, String location) { + final GroupQuotaLimitListInner groupQuotaRequest = null; return this - .beginUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, resourceName, groupQuotaRequest) + .beginUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, location, groupQuotaRequest) .getSyncPoller(); } /** * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. * - * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * properties are specified in the request body. Only 1 resource quota can be requested. Please note that patch - * request creates a new groupQuota request. + * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. The resourceName properties are + * specified in the request body. Only 1 resource quota can be requested. Please note that patch request creates a + * new groupQuota request. * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after * duration in seconds to check the intermediate status. This API provides the finals status with the request * details and status. @@ -779,20 +354,20 @@ private Mono>> updateWithResponseAsync(String manageme * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. + * @param location The name of the Azure region. * @param groupQuotaRequest The GroupQuotaRequest body details for specific resourceProvider/location/resources. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of status of a single GroupQuota request. + * @return the {@link SyncPoller} for polling of list of Group Quota Limit details. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, SubmittedResourceRequestStatusInner> beginUpdate( - String managementGroupId, String groupQuotaName, String resourceProviderName, String resourceName, - SubmittedResourceRequestStatusInner groupQuotaRequest, Context context) { + public SyncPoller, GroupQuotaLimitListInner> beginUpdate( + String managementGroupId, String groupQuotaName, String resourceProviderName, String location, + GroupQuotaLimitListInner groupQuotaRequest, Context context) { return this - .beginUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, resourceName, groupQuotaRequest, + .beginUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, location, groupQuotaRequest, context) .getSyncPoller(); } @@ -800,9 +375,9 @@ public SyncPoller, SubmittedReso /** * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. * - * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * properties are specified in the request body. Only 1 resource quota can be requested. Please note that patch - * request creates a new groupQuota request. + * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. The resourceName properties are + * specified in the request body. Only 1 resource quota can be requested. Please note that patch request creates a + * new groupQuota request. * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after * duration in seconds to check the intermediate status. This API provides the finals status with the request * details and status. @@ -811,26 +386,27 @@ public SyncPoller, SubmittedReso * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. + * @param location The name of the Azure region. * @param groupQuotaRequest The GroupQuotaRequest body details for specific resourceProvider/location/resources. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return status of a single GroupQuota request on successful completion of {@link Mono}. + * @return list of Group Quota Limit details on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono updateAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName, SubmittedResourceRequestStatusInner groupQuotaRequest) { - return beginUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, resourceName, - groupQuotaRequest).last().flatMap(this.client::getLroFinalResultOrError); + private Mono updateAsync(String managementGroupId, String groupQuotaName, + String resourceProviderName, String location, GroupQuotaLimitListInner groupQuotaRequest) { + return beginUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, location, groupQuotaRequest) + .last() + .flatMap(this.client::getLroFinalResultOrError); } /** * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. * - * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * properties are specified in the request body. Only 1 resource quota can be requested. Please note that patch - * request creates a new groupQuota request. + * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. The resourceName properties are + * specified in the request body. Only 1 resource quota can be requested. Please note that patch request creates a + * new groupQuota request. * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after * duration in seconds to check the intermediate status. This API provides the finals status with the request * details and status. @@ -839,26 +415,27 @@ private Mono updateAsync(String managementG * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. + * @param location The name of the Azure region. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return status of a single GroupQuota request on successful completion of {@link Mono}. + * @return list of Group Quota Limit details on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono updateAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName) { - final SubmittedResourceRequestStatusInner groupQuotaRequest = null; - return beginUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, resourceName, - groupQuotaRequest).last().flatMap(this.client::getLroFinalResultOrError); + private Mono updateAsync(String managementGroupId, String groupQuotaName, + String resourceProviderName, String location) { + final GroupQuotaLimitListInner groupQuotaRequest = null; + return beginUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, location, groupQuotaRequest) + .last() + .flatMap(this.client::getLroFinalResultOrError); } /** * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. * - * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * properties are specified in the request body. Only 1 resource quota can be requested. Please note that patch - * request creates a new groupQuota request. + * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. The resourceName properties are + * specified in the request body. Only 1 resource quota can be requested. Please note that patch request creates a + * new groupQuota request. * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after * duration in seconds to check the intermediate status. This API provides the finals status with the request * details and status. @@ -867,28 +444,27 @@ private Mono updateAsync(String managementG * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. + * @param location The name of the Azure region. * @param groupQuotaRequest The GroupQuotaRequest body details for specific resourceProvider/location/resources. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return status of a single GroupQuota request on successful completion of {@link Mono}. + * @return list of Group Quota Limit details on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono updateAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName, SubmittedResourceRequestStatusInner groupQuotaRequest, - Context context) { - return beginUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, resourceName, - groupQuotaRequest, context).last().flatMap(this.client::getLroFinalResultOrError); + private Mono updateAsync(String managementGroupId, String groupQuotaName, + String resourceProviderName, String location, GroupQuotaLimitListInner groupQuotaRequest, Context context) { + return beginUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, location, groupQuotaRequest, + context).last().flatMap(this.client::getLroFinalResultOrError); } /** * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. * - * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * properties are specified in the request body. Only 1 resource quota can be requested. Please note that patch - * request creates a new groupQuota request. + * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. The resourceName properties are + * specified in the request body. Only 1 resource quota can be requested. Please note that patch request creates a + * new groupQuota request. * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after * duration in seconds to check the intermediate status. This API provides the finals status with the request * details and status. @@ -897,26 +473,26 @@ private Mono updateAsync(String managementG * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. + * @param location The name of the Azure region. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return status of a single GroupQuota request. + * @return list of Group Quota Limit details. */ @ServiceMethod(returns = ReturnType.SINGLE) - public SubmittedResourceRequestStatusInner update(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName) { - final SubmittedResourceRequestStatusInner groupQuotaRequest = null; - return updateAsync(managementGroupId, groupQuotaName, resourceProviderName, resourceName, groupQuotaRequest) + public GroupQuotaLimitListInner update(String managementGroupId, String groupQuotaName, String resourceProviderName, + String location) { + final GroupQuotaLimitListInner groupQuotaRequest = null; + return updateAsync(managementGroupId, groupQuotaName, resourceProviderName, location, groupQuotaRequest) .block(); } /** * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. * - * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * properties are specified in the request body. Only 1 resource quota can be requested. Please note that patch - * request creates a new groupQuota request. + * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. The resourceName properties are + * specified in the request body. Only 1 resource quota can be requested. Please note that patch request creates a + * new groupQuota request. * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after * duration in seconds to check the intermediate status. This API provides the finals status with the request * details and status. @@ -925,19 +501,18 @@ public SubmittedResourceRequestStatusInner update(String managementGroupId, Stri * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. + * @param location The name of the Azure region. * @param groupQuotaRequest The GroupQuotaRequest body details for specific resourceProvider/location/resources. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return status of a single GroupQuota request. + * @return list of Group Quota Limit details. */ @ServiceMethod(returns = ReturnType.SINGLE) - public SubmittedResourceRequestStatusInner update(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName, SubmittedResourceRequestStatusInner groupQuotaRequest, - Context context) { - return updateAsync(managementGroupId, groupQuotaName, resourceProviderName, resourceName, groupQuotaRequest, + public GroupQuotaLimitListInner update(String managementGroupId, String groupQuotaName, String resourceProviderName, + String location, GroupQuotaLimitListInner groupQuotaRequest, Context context) { + return updateAsync(managementGroupId, groupQuotaName, resourceProviderName, location, groupQuotaRequest, context).block(); } diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaLimitsRequestsImpl.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaLimitsRequestsImpl.java index e6af14e9daaa..6edd2fb4b4ef 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaLimitsRequestsImpl.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaLimitsRequestsImpl.java @@ -7,11 +7,12 @@ import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.SimpleResponse; -import com.azure.core.management.ProxyResource; import com.azure.core.util.Context; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.quota.fluent.GroupQuotaLimitsRequestsClient; +import com.azure.resourcemanager.quota.fluent.models.GroupQuotaLimitListInner; import com.azure.resourcemanager.quota.fluent.models.SubmittedResourceRequestStatusInner; +import com.azure.resourcemanager.quota.models.GroupQuotaLimitList; import com.azure.resourcemanager.quota.models.GroupQuotaLimitsRequests; import com.azure.resourcemanager.quota.models.SubmittedResourceRequestStatus; @@ -28,37 +29,23 @@ public GroupQuotaLimitsRequestsImpl(GroupQuotaLimitsRequestsClient innerClient, this.serviceManager = serviceManager; } - public ProxyResource createOrUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, - String resourceName) { - return this.serviceClient() - .createOrUpdate(managementGroupId, groupQuotaName, resourceProviderName, resourceName); - } - - public ProxyResource createOrUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, - String resourceName, SubmittedResourceRequestStatusInner groupQuotaRequest, Context context) { - return this.serviceClient() - .createOrUpdate(managementGroupId, groupQuotaName, resourceProviderName, resourceName, groupQuotaRequest, - context); - } - - public SubmittedResourceRequestStatus update(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName) { - SubmittedResourceRequestStatusInner inner - = this.serviceClient().update(managementGroupId, groupQuotaName, resourceProviderName, resourceName); + public GroupQuotaLimitList update(String managementGroupId, String groupQuotaName, String resourceProviderName, + String location) { + GroupQuotaLimitListInner inner + = this.serviceClient().update(managementGroupId, groupQuotaName, resourceProviderName, location); if (inner != null) { - return new SubmittedResourceRequestStatusImpl(inner, this.manager()); + return new GroupQuotaLimitListImpl(inner, this.manager()); } else { return null; } } - public SubmittedResourceRequestStatus update(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName, SubmittedResourceRequestStatusInner groupQuotaRequest, - Context context) { - SubmittedResourceRequestStatusInner inner = this.serviceClient() - .update(managementGroupId, groupQuotaName, resourceProviderName, resourceName, groupQuotaRequest, context); + public GroupQuotaLimitList update(String managementGroupId, String groupQuotaName, String resourceProviderName, + String location, GroupQuotaLimitListInner groupQuotaRequest, Context context) { + GroupQuotaLimitListInner inner = this.serviceClient() + .update(managementGroupId, groupQuotaName, resourceProviderName, location, groupQuotaRequest, context); if (inner != null) { - return new SubmittedResourceRequestStatusImpl(inner, this.manager()); + return new GroupQuotaLimitListImpl(inner, this.manager()); } else { return null; } diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaLocationSettingsClientImpl.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaLocationSettingsClientImpl.java deleted file mode 100644 index 7f58c00b9982..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaLocationSettingsClientImpl.java +++ /dev/null @@ -1,1440 +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.resourcemanager.quota.implementation; - -import com.azure.core.annotation.BodyParam; -import com.azure.core.annotation.ExpectedResponses; -import com.azure.core.annotation.Get; -import com.azure.core.annotation.HeaderParam; -import com.azure.core.annotation.Headers; -import com.azure.core.annotation.Host; -import com.azure.core.annotation.HostParam; -import com.azure.core.annotation.Patch; -import com.azure.core.annotation.PathParam; -import com.azure.core.annotation.Put; -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.PagedFlux; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.PagedResponse; -import com.azure.core.http.rest.PagedResponseBase; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.RestProxy; -import com.azure.core.management.ProxyResource; -import com.azure.core.management.exception.ManagementException; -import com.azure.core.management.polling.PollResult; -import com.azure.core.util.Context; -import com.azure.core.util.FluxUtil; -import com.azure.core.util.polling.PollerFlux; -import com.azure.core.util.polling.SyncPoller; -import com.azure.resourcemanager.quota.fluent.GroupQuotaLocationSettingsClient; -import com.azure.resourcemanager.quota.fluent.models.GroupQuotasEnforcementResponseInner; -import com.azure.resourcemanager.quota.models.GroupQuotasEnforcementListResponse; -import java.nio.ByteBuffer; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -/** - * An instance of this class provides access to all the operations defined in GroupQuotaLocationSettingsClient. - */ -public final class GroupQuotaLocationSettingsClientImpl implements GroupQuotaLocationSettingsClient { - /** - * The proxy service used to perform REST calls. - */ - private final GroupQuotaLocationSettingsService service; - - /** - * The service client containing this operation class. - */ - private final AzureQuotaExtensionApiImpl client; - - /** - * Initializes an instance of GroupQuotaLocationSettingsClientImpl. - * - * @param client the instance of the service client containing this operation class. - */ - GroupQuotaLocationSettingsClientImpl(AzureQuotaExtensionApiImpl client) { - this.service = RestProxy.create(GroupQuotaLocationSettingsService.class, client.getHttpPipeline(), - client.getSerializerAdapter()); - this.client = client; - } - - /** - * The interface defining all the services for AzureQuotaExtensionApiGroupQuotaLocationSettings to be used by the - * proxy service to perform REST calls. - */ - @Host("{$host}") - @ServiceInterface(name = "AzureQuotaExtensionA") - public interface GroupQuotaLocationSettingsService { - @Headers({ "Content-Type: application/json" }) - @Put("/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Quota/groupQuotas/{groupQuotaName}/resourceProviders/{resourceProviderName}/locationSettings/{location}") - @ExpectedResponses({ 200, 201 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono>> createOrUpdate(@HostParam("$host") String endpoint, - @PathParam("managementGroupId") String managementGroupId, - @PathParam("groupQuotaName") String groupQuotaName, - @PathParam("resourceProviderName") String resourceProviderName, @PathParam("location") String location, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") GroupQuotasEnforcementResponseInner locationSettings, - @HeaderParam("Accept") String accept, Context context); - - @Headers({ "Content-Type: application/json" }) - @Patch("/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Quota/groupQuotas/{groupQuotaName}/resourceProviders/{resourceProviderName}/locationSettings/{location}") - @ExpectedResponses({ 200, 202 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono>> update(@HostParam("$host") String endpoint, - @PathParam("managementGroupId") String managementGroupId, - @PathParam("groupQuotaName") String groupQuotaName, - @PathParam("resourceProviderName") String resourceProviderName, @PathParam("location") String location, - @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") GroupQuotasEnforcementResponseInner locationSettings, - @HeaderParam("Accept") String accept, Context context); - - @Headers({ "Content-Type: application/json" }) - @Get("/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Quota/groupQuotas/{groupQuotaName}/resourceProviders/{resourceProviderName}/locationSettings/{location}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> get(@HostParam("$host") String endpoint, - @PathParam("managementGroupId") String managementGroupId, - @PathParam("groupQuotaName") String groupQuotaName, - @PathParam("resourceProviderName") String resourceProviderName, @PathParam("location") String location, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Headers({ "Content-Type: application/json" }) - @Get("/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Quota/groupQuotas/{groupQuotaName}/resourceProviders/{resourceProviderName}/locationSettings") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> list(@HostParam("$host") String endpoint, - @PathParam("managementGroupId") String managementGroupId, - @PathParam("groupQuotaName") String groupQuotaName, - @PathParam("resourceProviderName") String resourceProviderName, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Headers({ "Content-Type: application/json" }) - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> listNext( - @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, - @HeaderParam("Accept") String accept, Context context); - } - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param locationSettings The GroupQuota body details for creation or update of a GroupQuota entity. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuota Enforcement status for a Azure Location/Region along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> createOrUpdateWithResponseAsync(String managementGroupId, - String groupQuotaName, String resourceProviderName, String location, - GroupQuotasEnforcementResponseInner locationSettings) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (managementGroupId == null) { - return Mono - .error(new IllegalArgumentException("Parameter managementGroupId is required and cannot be null.")); - } - if (groupQuotaName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupQuotaName is required and cannot be null.")); - } - if (resourceProviderName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceProviderName is required and cannot be null.")); - } - if (location == null) { - return Mono.error(new IllegalArgumentException("Parameter location is required and cannot be null.")); - } - if (locationSettings != null) { - locationSettings.validate(); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.createOrUpdate(this.client.getEndpoint(), managementGroupId, groupQuotaName, - resourceProviderName, location, this.client.getApiVersion(), locationSettings, accept, context)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param locationSettings The GroupQuota body details for creation or update of a GroupQuota entity. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuota Enforcement status for a Azure Location/Region along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> createOrUpdateWithResponseAsync(String managementGroupId, - String groupQuotaName, String resourceProviderName, String location, - GroupQuotasEnforcementResponseInner locationSettings, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (managementGroupId == null) { - return Mono - .error(new IllegalArgumentException("Parameter managementGroupId is required and cannot be null.")); - } - if (groupQuotaName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupQuotaName is required and cannot be null.")); - } - if (resourceProviderName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceProviderName is required and cannot be null.")); - } - if (location == null) { - return Mono.error(new IllegalArgumentException("Parameter location is required and cannot be null.")); - } - if (locationSettings != null) { - locationSettings.validate(); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.createOrUpdate(this.client.getEndpoint(), managementGroupId, groupQuotaName, - resourceProviderName, location, this.client.getApiVersion(), locationSettings, accept, context); - } - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param locationSettings The GroupQuota body details for creation or update of a GroupQuota entity. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of the GroupQuota Enforcement status for a Azure Location/Region. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, ProxyResource> beginCreateOrUpdateAsync(String managementGroupId, - String groupQuotaName, String resourceProviderName, String location, - GroupQuotasEnforcementResponseInner locationSettings) { - Mono>> mono = createOrUpdateWithResponseAsync(managementGroupId, groupQuotaName, - resourceProviderName, location, locationSettings); - return this.client.getLroResult(mono, this.client.getHttpPipeline(), - ProxyResource.class, ProxyResource.class, this.client.getContext()); - } - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of the GroupQuota Enforcement status for a Azure Location/Region. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, ProxyResource> beginCreateOrUpdateAsync(String managementGroupId, - String groupQuotaName, String resourceProviderName, String location) { - final GroupQuotasEnforcementResponseInner locationSettings = null; - Mono>> mono = createOrUpdateWithResponseAsync(managementGroupId, groupQuotaName, - resourceProviderName, location, locationSettings); - return this.client.getLroResult(mono, this.client.getHttpPipeline(), - ProxyResource.class, ProxyResource.class, this.client.getContext()); - } - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param locationSettings The GroupQuota body details for creation or update of a GroupQuota entity. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of the GroupQuota Enforcement status for a Azure Location/Region. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, ProxyResource> beginCreateOrUpdateAsync(String managementGroupId, - String groupQuotaName, String resourceProviderName, String location, - GroupQuotasEnforcementResponseInner locationSettings, Context context) { - context = this.client.mergeContext(context); - Mono>> mono = createOrUpdateWithResponseAsync(managementGroupId, groupQuotaName, - resourceProviderName, location, locationSettings, context); - return this.client.getLroResult(mono, this.client.getHttpPipeline(), - ProxyResource.class, ProxyResource.class, context); - } - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of the GroupQuota Enforcement status for a Azure Location/Region. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, ProxyResource> beginCreateOrUpdate(String managementGroupId, - String groupQuotaName, String resourceProviderName, String location) { - final GroupQuotasEnforcementResponseInner locationSettings = null; - return this - .beginCreateOrUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, location, - locationSettings) - .getSyncPoller(); - } - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param locationSettings The GroupQuota body details for creation or update of a GroupQuota entity. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of the GroupQuota Enforcement status for a Azure Location/Region. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, ProxyResource> beginCreateOrUpdate(String managementGroupId, - String groupQuotaName, String resourceProviderName, String location, - GroupQuotasEnforcementResponseInner locationSettings, Context context) { - return this - .beginCreateOrUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, location, - locationSettings, context) - .getSyncPoller(); - } - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param locationSettings The GroupQuota body details for creation or update of a GroupQuota entity. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuota Enforcement status for a Azure Location/Region on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono createOrUpdateAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String location, GroupQuotasEnforcementResponseInner locationSettings) { - return beginCreateOrUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, location, - locationSettings).last().flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuota Enforcement status for a Azure Location/Region on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono createOrUpdateAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String location) { - final GroupQuotasEnforcementResponseInner locationSettings = null; - return beginCreateOrUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, location, - locationSettings).last().flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param locationSettings The GroupQuota body details for creation or update of a GroupQuota entity. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuota Enforcement status for a Azure Location/Region on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono createOrUpdateAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String location, GroupQuotasEnforcementResponseInner locationSettings, - Context context) { - return beginCreateOrUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, location, - locationSettings, context).last().flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuota Enforcement status for a Azure Location/Region. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public ProxyResource createOrUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, - String location) { - final GroupQuotasEnforcementResponseInner locationSettings = null; - return createOrUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, location, locationSettings) - .block(); - } - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param locationSettings The GroupQuota body details for creation or update of a GroupQuota entity. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuota Enforcement status for a Azure Location/Region. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public ProxyResource createOrUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, - String location, GroupQuotasEnforcementResponseInner locationSettings, Context context) { - return createOrUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, location, locationSettings, - context).block(); - } - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param locationSettings The GroupQuota body details for creation or update of a GroupQuota entity. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuota Enforcement status for a Azure Location/Region along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> updateWithResponseAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String location, GroupQuotasEnforcementResponseInner locationSettings) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (managementGroupId == null) { - return Mono - .error(new IllegalArgumentException("Parameter managementGroupId is required and cannot be null.")); - } - if (groupQuotaName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupQuotaName is required and cannot be null.")); - } - if (resourceProviderName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceProviderName is required and cannot be null.")); - } - if (location == null) { - return Mono.error(new IllegalArgumentException("Parameter location is required and cannot be null.")); - } - if (locationSettings != null) { - locationSettings.validate(); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.update(this.client.getEndpoint(), managementGroupId, groupQuotaName, - resourceProviderName, location, this.client.getApiVersion(), locationSettings, accept, context)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param locationSettings The GroupQuota body details for creation or update of a GroupQuota entity. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuota Enforcement status for a Azure Location/Region along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> updateWithResponseAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String location, GroupQuotasEnforcementResponseInner locationSettings, - Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (managementGroupId == null) { - return Mono - .error(new IllegalArgumentException("Parameter managementGroupId is required and cannot be null.")); - } - if (groupQuotaName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupQuotaName is required and cannot be null.")); - } - if (resourceProviderName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceProviderName is required and cannot be null.")); - } - if (location == null) { - return Mono.error(new IllegalArgumentException("Parameter location is required and cannot be null.")); - } - if (locationSettings != null) { - locationSettings.validate(); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.update(this.client.getEndpoint(), managementGroupId, groupQuotaName, resourceProviderName, - location, this.client.getApiVersion(), locationSettings, accept, context); - } - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param locationSettings The GroupQuota body details for creation or update of a GroupQuota entity. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of the GroupQuota Enforcement status for a Azure Location/Region. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, GroupQuotasEnforcementResponseInner> - beginUpdateAsync(String managementGroupId, String groupQuotaName, String resourceProviderName, String location, - GroupQuotasEnforcementResponseInner locationSettings) { - Mono>> mono = updateWithResponseAsync(managementGroupId, groupQuotaName, - resourceProviderName, location, locationSettings); - return this.client.getLroResult(mono, - this.client.getHttpPipeline(), GroupQuotasEnforcementResponseInner.class, - GroupQuotasEnforcementResponseInner.class, this.client.getContext()); - } - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of the GroupQuota Enforcement status for a Azure Location/Region. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, GroupQuotasEnforcementResponseInner> - beginUpdateAsync(String managementGroupId, String groupQuotaName, String resourceProviderName, - String location) { - final GroupQuotasEnforcementResponseInner locationSettings = null; - Mono>> mono = updateWithResponseAsync(managementGroupId, groupQuotaName, - resourceProviderName, location, locationSettings); - return this.client.getLroResult(mono, - this.client.getHttpPipeline(), GroupQuotasEnforcementResponseInner.class, - GroupQuotasEnforcementResponseInner.class, this.client.getContext()); - } - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param locationSettings The GroupQuota body details for creation or update of a GroupQuota entity. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of the GroupQuota Enforcement status for a Azure Location/Region. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, GroupQuotasEnforcementResponseInner> - beginUpdateAsync(String managementGroupId, String groupQuotaName, String resourceProviderName, String location, - GroupQuotasEnforcementResponseInner locationSettings, Context context) { - context = this.client.mergeContext(context); - Mono>> mono = updateWithResponseAsync(managementGroupId, groupQuotaName, - resourceProviderName, location, locationSettings, context); - return this.client.getLroResult(mono, - this.client.getHttpPipeline(), GroupQuotasEnforcementResponseInner.class, - GroupQuotasEnforcementResponseInner.class, context); - } - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of the GroupQuota Enforcement status for a Azure Location/Region. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, GroupQuotasEnforcementResponseInner> - beginUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, String location) { - final GroupQuotasEnforcementResponseInner locationSettings = null; - return this - .beginUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, location, locationSettings) - .getSyncPoller(); - } - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param locationSettings The GroupQuota body details for creation or update of a GroupQuota entity. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of the GroupQuota Enforcement status for a Azure Location/Region. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, GroupQuotasEnforcementResponseInner> beginUpdate( - String managementGroupId, String groupQuotaName, String resourceProviderName, String location, - GroupQuotasEnforcementResponseInner locationSettings, Context context) { - return this - .beginUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, location, locationSettings, - context) - .getSyncPoller(); - } - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param locationSettings The GroupQuota body details for creation or update of a GroupQuota entity. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuota Enforcement status for a Azure Location/Region on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono updateAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String location, GroupQuotasEnforcementResponseInner locationSettings) { - return beginUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, location, locationSettings) - .last() - .flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuota Enforcement status for a Azure Location/Region on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono updateAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String location) { - final GroupQuotasEnforcementResponseInner locationSettings = null; - return beginUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, location, locationSettings) - .last() - .flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param locationSettings The GroupQuota body details for creation or update of a GroupQuota entity. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuota Enforcement status for a Azure Location/Region on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono updateAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String location, GroupQuotasEnforcementResponseInner locationSettings, - Context context) { - return beginUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, location, locationSettings, - context).last().flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuota Enforcement status for a Azure Location/Region. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public GroupQuotasEnforcementResponseInner update(String managementGroupId, String groupQuotaName, - String resourceProviderName, String location) { - final GroupQuotasEnforcementResponseInner locationSettings = null; - return updateAsync(managementGroupId, groupQuotaName, resourceProviderName, location, locationSettings).block(); - } - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param locationSettings The GroupQuota body details for creation or update of a GroupQuota entity. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuota Enforcement status for a Azure Location/Region. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public GroupQuotasEnforcementResponseInner update(String managementGroupId, String groupQuotaName, - String resourceProviderName, String location, GroupQuotasEnforcementResponseInner locationSettings, - Context context) { - return updateAsync(managementGroupId, groupQuotaName, resourceProviderName, location, locationSettings, context) - .block(); - } - - /** - * Gets the GroupQuotas enforcement settings for the resource provider/location. - * - * Gets the GroupQuotas enforcement settings for the ResourceProvider/location. The locations, where GroupQuota - * enforcement is not enabled will return Not Found. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotas enforcement settings for the ResourceProvider/location along with {@link Response} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> getWithResponseAsync(String managementGroupId, - String groupQuotaName, String resourceProviderName, String location) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (managementGroupId == null) { - return Mono - .error(new IllegalArgumentException("Parameter managementGroupId is required and cannot be null.")); - } - if (groupQuotaName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupQuotaName is required and cannot be null.")); - } - if (resourceProviderName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceProviderName is required and cannot be null.")); - } - if (location == null) { - return Mono.error(new IllegalArgumentException("Parameter location is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.get(this.client.getEndpoint(), managementGroupId, groupQuotaName, - resourceProviderName, location, this.client.getApiVersion(), accept, context)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Gets the GroupQuotas enforcement settings for the resource provider/location. - * - * Gets the GroupQuotas enforcement settings for the ResourceProvider/location. The locations, where GroupQuota - * enforcement is not enabled will return Not Found. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotas enforcement settings for the ResourceProvider/location along with {@link Response} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> getWithResponseAsync(String managementGroupId, - String groupQuotaName, String resourceProviderName, String location, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (managementGroupId == null) { - return Mono - .error(new IllegalArgumentException("Parameter managementGroupId is required and cannot be null.")); - } - if (groupQuotaName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupQuotaName is required and cannot be null.")); - } - if (resourceProviderName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceProviderName is required and cannot be null.")); - } - if (location == null) { - return Mono.error(new IllegalArgumentException("Parameter location is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.get(this.client.getEndpoint(), managementGroupId, groupQuotaName, resourceProviderName, location, - this.client.getApiVersion(), accept, context); - } - - /** - * Gets the GroupQuotas enforcement settings for the resource provider/location. - * - * Gets the GroupQuotas enforcement settings for the ResourceProvider/location. The locations, where GroupQuota - * enforcement is not enabled will return Not Found. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotas enforcement settings for the ResourceProvider/location on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono getAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String location) { - return getWithResponseAsync(managementGroupId, groupQuotaName, resourceProviderName, location) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Gets the GroupQuotas enforcement settings for the resource provider/location. - * - * Gets the GroupQuotas enforcement settings for the ResourceProvider/location. The locations, where GroupQuota - * enforcement is not enabled will return Not Found. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotas enforcement settings for the ResourceProvider/location along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getWithResponse(String managementGroupId, - String groupQuotaName, String resourceProviderName, String location, Context context) { - return getWithResponseAsync(managementGroupId, groupQuotaName, resourceProviderName, location, context).block(); - } - - /** - * Gets the GroupQuotas enforcement settings for the resource provider/location. - * - * Gets the GroupQuotas enforcement settings for the ResourceProvider/location. The locations, where GroupQuota - * enforcement is not enabled will return Not Found. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotas enforcement settings for the ResourceProvider/location. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public GroupQuotasEnforcementResponseInner get(String managementGroupId, String groupQuotaName, - String resourceProviderName, String location) { - return getWithResponse(managementGroupId, groupQuotaName, resourceProviderName, location, Context.NONE) - .getValue(); - } - - /** - * Returns a list of the Azure regions settings, where the GroupQuotas enforcement is enabled. - * - * Returns only the list of the Azure regions settings, where the GroupQuotas enforcement is enabled. The locations - * not included in GroupQuota Enforcement will not be listed, the regions in failed status with listed as status - * Failed. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return list of Azure regions, where the group quotas is enabled for enforcement along with {@link PagedResponse} - * on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listSinglePageAsync(String managementGroupId, - String groupQuotaName, String resourceProviderName) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (managementGroupId == null) { - return Mono - .error(new IllegalArgumentException("Parameter managementGroupId is required and cannot be null.")); - } - if (groupQuotaName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupQuotaName is required and cannot be null.")); - } - if (resourceProviderName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceProviderName is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.list(this.client.getEndpoint(), managementGroupId, groupQuotaName, - resourceProviderName, this.client.getApiVersion(), accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), - res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Returns a list of the Azure regions settings, where the GroupQuotas enforcement is enabled. - * - * Returns only the list of the Azure regions settings, where the GroupQuotas enforcement is enabled. The locations - * not included in GroupQuota Enforcement will not be listed, the regions in failed status with listed as status - * Failed. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return list of Azure regions, where the group quotas is enabled for enforcement along with {@link PagedResponse} - * on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listSinglePageAsync(String managementGroupId, - String groupQuotaName, String resourceProviderName, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (managementGroupId == null) { - return Mono - .error(new IllegalArgumentException("Parameter managementGroupId is required and cannot be null.")); - } - if (groupQuotaName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupQuotaName is required and cannot be null.")); - } - if (resourceProviderName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceProviderName is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service - .list(this.client.getEndpoint(), managementGroupId, groupQuotaName, resourceProviderName, - this.client.getApiVersion(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } - - /** - * Returns a list of the Azure regions settings, where the GroupQuotas enforcement is enabled. - * - * Returns only the list of the Azure regions settings, where the GroupQuotas enforcement is enabled. The locations - * not included in GroupQuota Enforcement will not be listed, the regions in failed status with listed as status - * Failed. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return list of Azure regions, where the group quotas is enabled for enforcement as paginated response with - * {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName) { - return new PagedFlux<>(() -> listSinglePageAsync(managementGroupId, groupQuotaName, resourceProviderName), - nextLink -> listNextSinglePageAsync(nextLink)); - } - - /** - * Returns a list of the Azure regions settings, where the GroupQuotas enforcement is enabled. - * - * Returns only the list of the Azure regions settings, where the GroupQuotas enforcement is enabled. The locations - * not included in GroupQuota Enforcement will not be listed, the regions in failed status with listed as status - * Failed. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return list of Azure regions, where the group quotas is enabled for enforcement as paginated response with - * {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, Context context) { - return new PagedFlux<>( - () -> listSinglePageAsync(managementGroupId, groupQuotaName, resourceProviderName, context), - nextLink -> listNextSinglePageAsync(nextLink, context)); - } - - /** - * Returns a list of the Azure regions settings, where the GroupQuotas enforcement is enabled. - * - * Returns only the list of the Azure regions settings, where the GroupQuotas enforcement is enabled. The locations - * not included in GroupQuota Enforcement will not be listed, the regions in failed status with listed as status - * Failed. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return list of Azure regions, where the group quotas is enabled for enforcement as paginated response with - * {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list(String managementGroupId, String groupQuotaName, - String resourceProviderName) { - return new PagedIterable<>(listAsync(managementGroupId, groupQuotaName, resourceProviderName)); - } - - /** - * Returns a list of the Azure regions settings, where the GroupQuotas enforcement is enabled. - * - * Returns only the list of the Azure regions settings, where the GroupQuotas enforcement is enabled. The locations - * not included in GroupQuota Enforcement will not be listed, the regions in failed status with listed as status - * Failed. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return list of Azure regions, where the group quotas is enabled for enforcement as paginated response with - * {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list(String managementGroupId, String groupQuotaName, - String resourceProviderName, Context context) { - return new PagedIterable<>(listAsync(managementGroupId, groupQuotaName, resourceProviderName, context)); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return list of Azure regions, where the group quotas is enabled for enforcement along with {@link PagedResponse} - * on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listNextSinglePageAsync(String nextLink) { - if (nextLink == null) { - return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - } - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.listNext(nextLink, this.client.getEndpoint(), accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), - res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return list of Azure regions, where the group quotas is enabled for enforcement along with {@link PagedResponse} - * on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listNextSinglePageAsync(String nextLink, - Context context) { - if (nextLink == null) { - return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - } - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.listNext(nextLink, this.client.getEndpoint(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaLocationSettingsImpl.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaLocationSettingsImpl.java deleted file mode 100644 index 7a9a6908d883..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaLocationSettingsImpl.java +++ /dev/null @@ -1,112 +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.resourcemanager.quota.implementation; - -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.SimpleResponse; -import com.azure.core.management.ProxyResource; -import com.azure.core.util.Context; -import com.azure.core.util.logging.ClientLogger; -import com.azure.resourcemanager.quota.fluent.GroupQuotaLocationSettingsClient; -import com.azure.resourcemanager.quota.fluent.models.GroupQuotasEnforcementResponseInner; -import com.azure.resourcemanager.quota.models.GroupQuotaLocationSettings; -import com.azure.resourcemanager.quota.models.GroupQuotasEnforcementResponse; - -public final class GroupQuotaLocationSettingsImpl implements GroupQuotaLocationSettings { - private static final ClientLogger LOGGER = new ClientLogger(GroupQuotaLocationSettingsImpl.class); - - private final GroupQuotaLocationSettingsClient innerClient; - - private final com.azure.resourcemanager.quota.QuotaManager serviceManager; - - public GroupQuotaLocationSettingsImpl(GroupQuotaLocationSettingsClient innerClient, - com.azure.resourcemanager.quota.QuotaManager serviceManager) { - this.innerClient = innerClient; - this.serviceManager = serviceManager; - } - - public ProxyResource createOrUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, - String location) { - return this.serviceClient().createOrUpdate(managementGroupId, groupQuotaName, resourceProviderName, location); - } - - public ProxyResource createOrUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, - String location, GroupQuotasEnforcementResponseInner locationSettings, Context context) { - return this.serviceClient() - .createOrUpdate(managementGroupId, groupQuotaName, resourceProviderName, location, locationSettings, - context); - } - - public GroupQuotasEnforcementResponse update(String managementGroupId, String groupQuotaName, - String resourceProviderName, String location) { - GroupQuotasEnforcementResponseInner inner - = this.serviceClient().update(managementGroupId, groupQuotaName, resourceProviderName, location); - if (inner != null) { - return new GroupQuotasEnforcementResponseImpl(inner, this.manager()); - } else { - return null; - } - } - - public GroupQuotasEnforcementResponse update(String managementGroupId, String groupQuotaName, - String resourceProviderName, String location, GroupQuotasEnforcementResponseInner locationSettings, - Context context) { - GroupQuotasEnforcementResponseInner inner = this.serviceClient() - .update(managementGroupId, groupQuotaName, resourceProviderName, location, locationSettings, context); - if (inner != null) { - return new GroupQuotasEnforcementResponseImpl(inner, this.manager()); - } else { - return null; - } - } - - public Response getWithResponse(String managementGroupId, String groupQuotaName, - String resourceProviderName, String location, Context context) { - Response inner = this.serviceClient() - .getWithResponse(managementGroupId, groupQuotaName, resourceProviderName, location, context); - if (inner != null) { - return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), - new GroupQuotasEnforcementResponseImpl(inner.getValue(), this.manager())); - } else { - return null; - } - } - - public GroupQuotasEnforcementResponse get(String managementGroupId, String groupQuotaName, - String resourceProviderName, String location) { - GroupQuotasEnforcementResponseInner inner - = this.serviceClient().get(managementGroupId, groupQuotaName, resourceProviderName, location); - if (inner != null) { - return new GroupQuotasEnforcementResponseImpl(inner, this.manager()); - } else { - return null; - } - } - - public PagedIterable list(String managementGroupId, String groupQuotaName, - String resourceProviderName) { - PagedIterable inner - = this.serviceClient().list(managementGroupId, groupQuotaName, resourceProviderName); - return ResourceManagerUtils.mapPage(inner, - inner1 -> new GroupQuotasEnforcementResponseImpl(inner1, this.manager())); - } - - public PagedIterable list(String managementGroupId, String groupQuotaName, - String resourceProviderName, Context context) { - PagedIterable inner - = this.serviceClient().list(managementGroupId, groupQuotaName, resourceProviderName, context); - return ResourceManagerUtils.mapPage(inner, - inner1 -> new GroupQuotasEnforcementResponseImpl(inner1, this.manager())); - } - - private GroupQuotaLocationSettingsClient serviceClient() { - return this.innerClient; - } - - private com.azure.resourcemanager.quota.QuotaManager manager() { - return this.serviceManager; - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaSubscriptionAllocationRequestsClientImpl.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaSubscriptionAllocationRequestsClientImpl.java index 36587b3a786d..0ec77f277a5d 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaSubscriptionAllocationRequestsClientImpl.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaSubscriptionAllocationRequestsClientImpl.java @@ -13,7 +13,6 @@ import com.azure.core.annotation.HostParam; import com.azure.core.annotation.Patch; import com.azure.core.annotation.PathParam; -import com.azure.core.annotation.Put; import com.azure.core.annotation.QueryParam; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceInterface; @@ -25,7 +24,6 @@ import com.azure.core.http.rest.PagedResponseBase; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.RestProxy; -import com.azure.core.management.ProxyResource; import com.azure.core.management.exception.ManagementException; import com.azure.core.management.polling.PollResult; import com.azure.core.util.Context; @@ -34,6 +32,7 @@ import com.azure.core.util.polling.SyncPoller; import com.azure.resourcemanager.quota.fluent.GroupQuotaSubscriptionAllocationRequestsClient; import com.azure.resourcemanager.quota.fluent.models.QuotaAllocationRequestStatusInner; +import com.azure.resourcemanager.quota.fluent.models.SubscriptionQuotaAllocationsListInner; import com.azure.resourcemanager.quota.models.QuotaAllocationRequestStatusList; import java.nio.ByteBuffer; import reactor.core.publisher.Flux; @@ -74,48 +73,37 @@ public final class GroupQuotaSubscriptionAllocationRequestsClientImpl @ServiceInterface(name = "AzureQuotaExtensionA") public interface GroupQuotaSubscriptionAllocationRequestsService { @Headers({ "Content-Type: application/json" }) - @Get("/providers/Microsoft.Management/managementGroups/{managementGroupId}/subscriptions/{subscriptionId}/providers/Microsoft.Quota/groupQuotas/{groupQuotaName}/quotaAllocationRequests/{allocationId}") - @ExpectedResponses({ 200 }) + @Patch("/providers/Microsoft.Management/managementGroups/{managementGroupId}/subscriptions/{subscriptionId}/providers/Microsoft.Quota/groupQuotas/{groupQuotaName}/resourceProviders/{resourceProviderName}/quotaAllocations/{location}") + @ExpectedResponses({ 200, 202 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono> get(@HostParam("$host") String endpoint, + Mono>> update(@HostParam("$host") String endpoint, @PathParam("managementGroupId") String managementGroupId, @PathParam("subscriptionId") String subscriptionId, @PathParam("groupQuotaName") String groupQuotaName, - @PathParam("allocationId") String allocationId, @QueryParam("api-version") String apiVersion, + @PathParam("resourceProviderName") String resourceProviderName, @PathParam("location") String location, + @QueryParam("api-version") String apiVersion, + @BodyParam("application/json") SubscriptionQuotaAllocationsListInner allocateQuotaRequest, @HeaderParam("Accept") String accept, Context context); @Headers({ "Content-Type: application/json" }) - @Get("/providers/Microsoft.Management/managementGroups/{managementGroupId}/subscriptions/{subscriptionId}/providers/Microsoft.Quota/groupQuotas/{groupQuotaName}/resourceProviders/{resourceProviderName}/quotaAllocationRequests") + @Get("/providers/Microsoft.Management/managementGroups/{managementGroupId}/subscriptions/{subscriptionId}/providers/Microsoft.Quota/groupQuotas/{groupQuotaName}/resourceProviders/{resourceProviderName}/quotaAllocationRequests/{allocationId}") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono> list(@HostParam("$host") String endpoint, - @PathParam("managementGroupId") String managementGroupId, - @PathParam("subscriptionId") String subscriptionId, @PathParam("groupQuotaName") String groupQuotaName, - @PathParam("resourceProviderName") String resourceProviderName, - @QueryParam("api-version") String apiVersion, @QueryParam("$filter") String filter, - @HeaderParam("Accept") String accept, Context context); - - @Headers({ "Content-Type: application/json" }) - @Put("/providers/Microsoft.Management/managementGroups/{managementGroupId}/subscriptions/{subscriptionId}/providers/Microsoft.Quota/groupQuotas/{groupQuotaName}/resourceProviders/{resourceProviderName}/quotaAllocationRequests/{resourceName}") - @ExpectedResponses({ 200, 201 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono>> createOrUpdate(@HostParam("$host") String endpoint, + Mono> get(@HostParam("$host") String endpoint, @PathParam("managementGroupId") String managementGroupId, @PathParam("subscriptionId") String subscriptionId, @PathParam("groupQuotaName") String groupQuotaName, @PathParam("resourceProviderName") String resourceProviderName, - @PathParam("resourceName") String resourceName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") QuotaAllocationRequestStatusInner allocateQuotaRequest, + @PathParam("allocationId") String allocationId, @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); @Headers({ "Content-Type: application/json" }) - @Patch("/providers/Microsoft.Management/managementGroups/{managementGroupId}/subscriptions/{subscriptionId}/providers/Microsoft.Quota/groupQuotas/{groupQuotaName}/resourceProviders/{resourceProviderName}/quotaAllocationRequests/{resourceName}") - @ExpectedResponses({ 200, 202 }) + @Get("/providers/Microsoft.Management/managementGroups/{managementGroupId}/subscriptions/{subscriptionId}/providers/Microsoft.Quota/groupQuotas/{groupQuotaName}/resourceProviders/{resourceProviderName}/quotaAllocationRequests") + @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono>> update(@HostParam("$host") String endpoint, + Mono> list(@HostParam("$host") String endpoint, @PathParam("managementGroupId") String managementGroupId, @PathParam("subscriptionId") String subscriptionId, @PathParam("groupQuotaName") String groupQuotaName, @PathParam("resourceProviderName") String resourceProviderName, - @PathParam("resourceName") String resourceName, @QueryParam("api-version") String apiVersion, - @BodyParam("application/json") QuotaAllocationRequestStatusInner allocateQuotaRequest, + @QueryParam("api-version") String apiVersion, @QueryParam("$filter") String filter, @HeaderParam("Accept") String accept, Context context); @Headers({ "Content-Type: application/json" }) @@ -128,22 +116,29 @@ Mono> listNext( } /** - * Get the status of the quota allocation request for the subscriptionId. + * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern + * with 202 response and status polling API. * - * Get the quota allocation request status for the subscriptionId by allocationId. + * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or + * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. + * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can + * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple + * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param allocationId Request Id. + * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only + * Microsoft.Compute resource provider supports this API. + * @param location The name of the Azure region. + * @param allocateQuotaRequest Quota requests payload. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the quota allocation request status for the subscriptionId by allocationId along with {@link Response} on - * successful completion of {@link Mono}. + * @return subscription quota list along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> getWithResponseAsync(String managementGroupId, - String groupQuotaName, String allocationId) { + private Mono>> updateWithResponseAsync(String managementGroupId, String groupQuotaName, + String resourceProviderName, String location, SubscriptionQuotaAllocationsListInner allocateQuotaRequest) { if (this.client.getEndpoint() == null) { return Mono.error( new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); @@ -159,35 +154,53 @@ private Mono> getWithResponseAsync(S if (groupQuotaName == null) { return Mono.error(new IllegalArgumentException("Parameter groupQuotaName is required and cannot be null.")); } - if (allocationId == null) { - return Mono.error(new IllegalArgumentException("Parameter allocationId is required and cannot be null.")); + if (resourceProviderName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceProviderName is required and cannot be null.")); + } + if (location == null) { + return Mono.error(new IllegalArgumentException("Parameter location is required and cannot be null.")); + } + if (allocateQuotaRequest == null) { + return Mono + .error(new IllegalArgumentException("Parameter allocateQuotaRequest is required and cannot be null.")); + } else { + allocateQuotaRequest.validate(); } final String accept = "application/json"; return FluxUtil - .withContext( - context -> service.get(this.client.getEndpoint(), managementGroupId, this.client.getSubscriptionId(), - groupQuotaName, allocationId, this.client.getApiVersion(), accept, context)) + .withContext(context -> service.update(this.client.getEndpoint(), managementGroupId, + this.client.getSubscriptionId(), groupQuotaName, resourceProviderName, location, + this.client.getApiVersion(), allocateQuotaRequest, accept, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** - * Get the status of the quota allocation request for the subscriptionId. + * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern + * with 202 response and status polling API. * - * Get the quota allocation request status for the subscriptionId by allocationId. + * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or + * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. + * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can + * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple + * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param allocationId Request Id. + * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only + * Microsoft.Compute resource provider supports this API. + * @param location The name of the Azure region. + * @param allocateQuotaRequest Quota requests payload. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the quota allocation request status for the subscriptionId by allocationId along with {@link Response} on - * successful completion of {@link Mono}. + * @return subscription quota list along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> getWithResponseAsync(String managementGroupId, - String groupQuotaName, String allocationId, Context context) { + private Mono>> updateWithResponseAsync(String managementGroupId, String groupQuotaName, + String resourceProviderName, String location, SubscriptionQuotaAllocationsListInner allocateQuotaRequest, + Context context) { if (this.client.getEndpoint() == null) { return Mono.error( new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); @@ -203,326 +216,290 @@ private Mono> getWithResponseAsync(S if (groupQuotaName == null) { return Mono.error(new IllegalArgumentException("Parameter groupQuotaName is required and cannot be null.")); } - if (allocationId == null) { - return Mono.error(new IllegalArgumentException("Parameter allocationId is required and cannot be null.")); + if (resourceProviderName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceProviderName is required and cannot be null.")); + } + if (location == null) { + return Mono.error(new IllegalArgumentException("Parameter location is required and cannot be null.")); + } + if (allocateQuotaRequest == null) { + return Mono + .error(new IllegalArgumentException("Parameter allocateQuotaRequest is required and cannot be null.")); + } else { + allocateQuotaRequest.validate(); } final String accept = "application/json"; context = this.client.mergeContext(context); - return service.get(this.client.getEndpoint(), managementGroupId, this.client.getSubscriptionId(), - groupQuotaName, allocationId, this.client.getApiVersion(), accept, context); + return service.update(this.client.getEndpoint(), managementGroupId, this.client.getSubscriptionId(), + groupQuotaName, resourceProviderName, location, this.client.getApiVersion(), allocateQuotaRequest, accept, + context); } /** - * Get the status of the quota allocation request for the subscriptionId. + * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern + * with 202 response and status polling API. * - * Get the quota allocation request status for the subscriptionId by allocationId. + * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or + * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. + * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can + * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple + * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param allocationId Request Id. + * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only + * Microsoft.Compute resource provider supports this API. + * @param location The name of the Azure region. + * @param allocateQuotaRequest Quota requests payload. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the quota allocation request status for the subscriptionId by allocationId on successful completion of - * {@link Mono}. + * @return the {@link PollerFlux} for polling of subscription quota list. */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono getAsync(String managementGroupId, String groupQuotaName, - String allocationId) { - return getWithResponseAsync(managementGroupId, groupQuotaName, allocationId) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, SubscriptionQuotaAllocationsListInner> + beginUpdateAsync(String managementGroupId, String groupQuotaName, String resourceProviderName, String location, + SubscriptionQuotaAllocationsListInner allocateQuotaRequest) { + Mono>> mono = updateWithResponseAsync(managementGroupId, groupQuotaName, + resourceProviderName, location, allocateQuotaRequest); + return this.client.getLroResult( + mono, this.client.getHttpPipeline(), SubscriptionQuotaAllocationsListInner.class, + SubscriptionQuotaAllocationsListInner.class, this.client.getContext()); } /** - * Get the status of the quota allocation request for the subscriptionId. + * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern + * with 202 response and status polling API. * - * Get the quota allocation request status for the subscriptionId by allocationId. + * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or + * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. + * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can + * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple + * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param allocationId Request Id. + * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only + * Microsoft.Compute resource provider supports this API. + * @param location The name of the Azure region. + * @param allocateQuotaRequest Quota requests payload. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the quota allocation request status for the subscriptionId by allocationId along with {@link Response}. + * @return the {@link PollerFlux} for polling of subscription quota list. */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getWithResponse(String managementGroupId, String groupQuotaName, - String allocationId, Context context) { - return getWithResponseAsync(managementGroupId, groupQuotaName, allocationId, context).block(); + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + private PollerFlux, SubscriptionQuotaAllocationsListInner> + beginUpdateAsync(String managementGroupId, String groupQuotaName, String resourceProviderName, String location, + SubscriptionQuotaAllocationsListInner allocateQuotaRequest, Context context) { + context = this.client.mergeContext(context); + Mono>> mono = updateWithResponseAsync(managementGroupId, groupQuotaName, + resourceProviderName, location, allocateQuotaRequest, context); + return this.client.getLroResult( + mono, this.client.getHttpPipeline(), SubscriptionQuotaAllocationsListInner.class, + SubscriptionQuotaAllocationsListInner.class, context); } /** - * Get the status of the quota allocation request for the subscriptionId. + * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern + * with 202 response and status polling API. * - * Get the quota allocation request status for the subscriptionId by allocationId. + * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or + * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. + * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can + * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple + * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param allocationId Request Id. + * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only + * Microsoft.Compute resource provider supports this API. + * @param location The name of the Azure region. + * @param allocateQuotaRequest Quota requests payload. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the quota allocation request status for the subscriptionId by allocationId. + * @return the {@link SyncPoller} for polling of subscription quota list. */ - @ServiceMethod(returns = ReturnType.SINGLE) - public QuotaAllocationRequestStatusInner get(String managementGroupId, String groupQuotaName, String allocationId) { - return getWithResponse(managementGroupId, groupQuotaName, allocationId, Context.NONE).getValue(); + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, SubscriptionQuotaAllocationsListInner> + beginUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, String location, + SubscriptionQuotaAllocationsListInner allocateQuotaRequest) { + return this + .beginUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, location, allocateQuotaRequest) + .getSyncPoller(); } /** - * Get all the quotaAllocationRequests for a resourceProvider/location. + * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern + * with 202 response and status polling API. * - * Get all the quotaAllocationRequests for a resourceProvider/location. The filter paramter for location is - * required. + * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or + * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. + * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can + * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple + * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. + * @param location The name of the Azure region. + * @param allocateQuotaRequest Quota requests payload. + * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all the quotaAllocationRequests for a resourceProvider/location along with {@link PagedResponse} on - * successful completion of {@link Mono}. + * @return the {@link SyncPoller} for polling of subscription quota list. */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listSinglePageAsync(String managementGroupId, - String groupQuotaName, String resourceProviderName, String filter) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (managementGroupId == null) { - return Mono - .error(new IllegalArgumentException("Parameter managementGroupId is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (groupQuotaName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupQuotaName is required and cannot be null.")); - } - if (resourceProviderName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceProviderName is required and cannot be null.")); - } - if (filter == null) { - return Mono.error(new IllegalArgumentException("Parameter filter is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext( - context -> service.list(this.client.getEndpoint(), managementGroupId, this.client.getSubscriptionId(), - groupQuotaName, resourceProviderName, this.client.getApiVersion(), filter, accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), - res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) + public SyncPoller, SubscriptionQuotaAllocationsListInner> + beginUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, String location, + SubscriptionQuotaAllocationsListInner allocateQuotaRequest, Context context) { + return this + .beginUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, location, allocateQuotaRequest, + context) + .getSyncPoller(); } /** - * Get all the quotaAllocationRequests for a resourceProvider/location. + * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern + * with 202 response and status polling API. * - * Get all the quotaAllocationRequests for a resourceProvider/location. The filter paramter for location is - * required. + * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or + * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. + * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can + * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple + * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. - * @param context The context to associate with this operation. + * @param location The name of the Azure region. + * @param allocateQuotaRequest Quota requests payload. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all the quotaAllocationRequests for a resourceProvider/location along with {@link PagedResponse} on - * successful completion of {@link Mono}. + * @return subscription quota list on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listSinglePageAsync(String managementGroupId, - String groupQuotaName, String resourceProviderName, String filter, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (managementGroupId == null) { - return Mono - .error(new IllegalArgumentException("Parameter managementGroupId is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (groupQuotaName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupQuotaName is required and cannot be null.")); - } - if (resourceProviderName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceProviderName is required and cannot be null.")); - } - if (filter == null) { - return Mono.error(new IllegalArgumentException("Parameter filter is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service - .list(this.client.getEndpoint(), managementGroupId, this.client.getSubscriptionId(), groupQuotaName, - resourceProviderName, this.client.getApiVersion(), filter, accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); + private Mono updateAsync(String managementGroupId, String groupQuotaName, + String resourceProviderName, String location, SubscriptionQuotaAllocationsListInner allocateQuotaRequest) { + return beginUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, location, allocateQuotaRequest) + .last() + .flatMap(this.client::getLroFinalResultOrError); } /** - * Get all the quotaAllocationRequests for a resourceProvider/location. - * - * Get all the quotaAllocationRequests for a resourceProvider/location. The filter paramter for location is - * required. + * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern + * with 202 response and status polling API. * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all the quotaAllocationRequests for a resourceProvider/location as paginated response with - * {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String filter) { - return new PagedFlux<>( - () -> listSinglePageAsync(managementGroupId, groupQuotaName, resourceProviderName, filter), - nextLink -> listNextSinglePageAsync(nextLink)); - } - - /** - * Get all the quotaAllocationRequests for a resourceProvider/location. - * - * Get all the quotaAllocationRequests for a resourceProvider/location. The filter paramter for location is - * required. + * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or + * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. + * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can + * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple + * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. + * @param location The name of the Azure region. + * @param allocateQuotaRequest Quota requests payload. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all the quotaAllocationRequests for a resourceProvider/location as paginated response with - * {@link PagedFlux}. + * @return subscription quota list on successful completion of {@link Mono}. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String filter, Context context) { - return new PagedFlux<>( - () -> listSinglePageAsync(managementGroupId, groupQuotaName, resourceProviderName, filter, context), - nextLink -> listNextSinglePageAsync(nextLink, context)); + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono updateAsync(String managementGroupId, String groupQuotaName, + String resourceProviderName, String location, SubscriptionQuotaAllocationsListInner allocateQuotaRequest, + Context context) { + return beginUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, location, allocateQuotaRequest, + context).last().flatMap(this.client::getLroFinalResultOrError); } /** - * Get all the quotaAllocationRequests for a resourceProvider/location. + * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern + * with 202 response and status polling API. * - * Get all the quotaAllocationRequests for a resourceProvider/location. The filter paramter for location is - * required. + * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or + * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. + * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can + * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple + * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. + * @param location The name of the Azure region. + * @param allocateQuotaRequest Quota requests payload. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all the quotaAllocationRequests for a resourceProvider/location as paginated response with - * {@link PagedIterable}. + * @return subscription quota list. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list(String managementGroupId, String groupQuotaName, - String resourceProviderName, String filter) { - return new PagedIterable<>(listAsync(managementGroupId, groupQuotaName, resourceProviderName, filter)); + @ServiceMethod(returns = ReturnType.SINGLE) + public SubscriptionQuotaAllocationsListInner update(String managementGroupId, String groupQuotaName, + String resourceProviderName, String location, SubscriptionQuotaAllocationsListInner allocateQuotaRequest) { + return updateAsync(managementGroupId, groupQuotaName, resourceProviderName, location, allocateQuotaRequest) + .block(); } /** - * Get all the quotaAllocationRequests for a resourceProvider/location. + * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern + * with 202 response and status polling API. * - * Get all the quotaAllocationRequests for a resourceProvider/location. The filter paramter for location is - * required. + * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or + * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. + * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can + * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple + * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. + * @param location The name of the Azure region. + * @param allocateQuotaRequest Quota requests payload. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all the quotaAllocationRequests for a resourceProvider/location as paginated response with - * {@link PagedIterable}. + * @return subscription quota list. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list(String managementGroupId, String groupQuotaName, - String resourceProviderName, String filter, Context context) { - return new PagedIterable<>(listAsync(managementGroupId, groupQuotaName, resourceProviderName, filter, context)); + @ServiceMethod(returns = ReturnType.SINGLE) + public SubscriptionQuotaAllocationsListInner update(String managementGroupId, String groupQuotaName, + String resourceProviderName, String location, SubscriptionQuotaAllocationsListInner allocateQuotaRequest, + Context context) { + return updateAsync(managementGroupId, groupQuotaName, resourceProviderName, location, allocateQuotaRequest, + context).block(); } /** - * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * to check the status using Async polling as standards defined at - - * https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/async-api-reference.md#asynchronous-operations. + * Get the status of the quota allocation request for the subscriptionId. * - * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or - * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. - * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. + * Get the quota allocation request status for the subscriptionId by allocationId. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param allocateQuotaRequest Quota requests payload. + * @param allocationId Request Id. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the subscription quota allocation status along with {@link Response} on successful completion of - * {@link Mono}. + * @return the quota allocation request status for the subscriptionId by allocationId along with {@link Response} on + * successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> createOrUpdateWithResponseAsync(String managementGroupId, - String groupQuotaName, String resourceProviderName, String resourceName, - QuotaAllocationRequestStatusInner allocateQuotaRequest) { + private Mono> getWithResponseAsync(String managementGroupId, + String groupQuotaName, String resourceProviderName, String allocationId) { if (this.client.getEndpoint() == null) { return Mono.error( new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); @@ -542,50 +519,37 @@ private Mono>> createOrUpdateWithResponseAsync(String return Mono .error(new IllegalArgumentException("Parameter resourceProviderName is required and cannot be null.")); } - if (resourceName == null) { - return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); - } - if (allocateQuotaRequest == null) { - return Mono - .error(new IllegalArgumentException("Parameter allocateQuotaRequest is required and cannot be null.")); - } else { - allocateQuotaRequest.validate(); + if (allocationId == null) { + return Mono.error(new IllegalArgumentException("Parameter allocationId is required and cannot be null.")); } final String accept = "application/json"; return FluxUtil - .withContext(context -> service.createOrUpdate(this.client.getEndpoint(), managementGroupId, - this.client.getSubscriptionId(), groupQuotaName, resourceProviderName, resourceName, - this.client.getApiVersion(), allocateQuotaRequest, accept, context)) + .withContext( + context -> service.get(this.client.getEndpoint(), managementGroupId, this.client.getSubscriptionId(), + groupQuotaName, resourceProviderName, allocationId, this.client.getApiVersion(), accept, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** - * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * to check the status using Async polling as standards defined at - - * https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/async-api-reference.md#asynchronous-operations. + * Get the status of the quota allocation request for the subscriptionId. * - * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or - * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. - * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. + * Get the quota allocation request status for the subscriptionId by allocationId. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param allocateQuotaRequest Quota requests payload. + * @param allocationId Request Id. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the subscription quota allocation status along with {@link Response} on successful completion of - * {@link Mono}. + * @return the quota allocation request status for the subscriptionId by allocationId along with {@link Response} on + * successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> createOrUpdateWithResponseAsync(String managementGroupId, - String groupQuotaName, String resourceProviderName, String resourceName, - QuotaAllocationRequestStatusInner allocateQuotaRequest, Context context) { + private Mono> getWithResponseAsync(String managementGroupId, + String groupQuotaName, String resourceProviderName, String allocationId, Context context) { if (this.client.getEndpoint() == null) { return Mono.error( new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); @@ -605,352 +569,164 @@ private Mono>> createOrUpdateWithResponseAsync(String return Mono .error(new IllegalArgumentException("Parameter resourceProviderName is required and cannot be null.")); } - if (resourceName == null) { - return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); - } - if (allocateQuotaRequest == null) { - return Mono - .error(new IllegalArgumentException("Parameter allocateQuotaRequest is required and cannot be null.")); - } else { - allocateQuotaRequest.validate(); + if (allocationId == null) { + return Mono.error(new IllegalArgumentException("Parameter allocationId is required and cannot be null.")); } final String accept = "application/json"; context = this.client.mergeContext(context); - return service.createOrUpdate(this.client.getEndpoint(), managementGroupId, this.client.getSubscriptionId(), - groupQuotaName, resourceProviderName, resourceName, this.client.getApiVersion(), allocateQuotaRequest, - accept, context); + return service.get(this.client.getEndpoint(), managementGroupId, this.client.getSubscriptionId(), + groupQuotaName, resourceProviderName, allocationId, this.client.getApiVersion(), accept, context); } /** - * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * to check the status using Async polling as standards defined at - - * https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/async-api-reference.md#asynchronous-operations. + * Get the status of the quota allocation request for the subscriptionId. * - * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or - * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. - * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. + * Get the quota allocation request status for the subscriptionId by allocationId. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param allocateQuotaRequest Quota requests payload. + * @param allocationId Request Id. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of the subscription quota allocation status. + * @return the quota allocation request status for the subscriptionId by allocationId on successful completion of + * {@link Mono}. */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, ProxyResource> beginCreateOrUpdateAsync(String managementGroupId, - String groupQuotaName, String resourceProviderName, String resourceName, - QuotaAllocationRequestStatusInner allocateQuotaRequest) { - Mono>> mono = createOrUpdateWithResponseAsync(managementGroupId, groupQuotaName, - resourceProviderName, resourceName, allocateQuotaRequest); - return this.client.getLroResult(mono, this.client.getHttpPipeline(), - ProxyResource.class, ProxyResource.class, this.client.getContext()); + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono getAsync(String managementGroupId, String groupQuotaName, + String resourceProviderName, String allocationId) { + return getWithResponseAsync(managementGroupId, groupQuotaName, resourceProviderName, allocationId) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); } /** - * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * to check the status using Async polling as standards defined at - - * https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/async-api-reference.md#asynchronous-operations. + * Get the status of the quota allocation request for the subscriptionId. * - * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or - * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. - * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. + * Get the quota allocation request status for the subscriptionId by allocationId. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param allocateQuotaRequest Quota requests payload. + * @param allocationId Request Id. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of the subscription quota allocation status. + * @return the quota allocation request status for the subscriptionId by allocationId along with {@link Response}. */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, ProxyResource> beginCreateOrUpdateAsync(String managementGroupId, - String groupQuotaName, String resourceProviderName, String resourceName, - QuotaAllocationRequestStatusInner allocateQuotaRequest, Context context) { - context = this.client.mergeContext(context); - Mono>> mono = createOrUpdateWithResponseAsync(managementGroupId, groupQuotaName, - resourceProviderName, resourceName, allocateQuotaRequest, context); - return this.client.getLroResult(mono, this.client.getHttpPipeline(), - ProxyResource.class, ProxyResource.class, context); + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String managementGroupId, String groupQuotaName, + String resourceProviderName, String allocationId, Context context) { + return getWithResponseAsync(managementGroupId, groupQuotaName, resourceProviderName, allocationId, context) + .block(); } /** - * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * to check the status using Async polling as standards defined at - - * https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/async-api-reference.md#asynchronous-operations. + * Get the status of the quota allocation request for the subscriptionId. * - * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or - * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. - * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. + * Get the quota allocation request status for the subscriptionId by allocationId. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param allocateQuotaRequest Quota requests payload. + * @param allocationId Request Id. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of the subscription quota allocation status. + * @return the quota allocation request status for the subscriptionId by allocationId. */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, ProxyResource> beginCreateOrUpdate(String managementGroupId, - String groupQuotaName, String resourceProviderName, String resourceName, - QuotaAllocationRequestStatusInner allocateQuotaRequest) { - return this - .beginCreateOrUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, resourceName, - allocateQuotaRequest) - .getSyncPoller(); + @ServiceMethod(returns = ReturnType.SINGLE) + public QuotaAllocationRequestStatusInner get(String managementGroupId, String groupQuotaName, + String resourceProviderName, String allocationId) { + return getWithResponse(managementGroupId, groupQuotaName, resourceProviderName, allocationId, Context.NONE) + .getValue(); } /** - * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * to check the status using Async polling as standards defined at - - * https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/async-api-reference.md#asynchronous-operations. + * Get all the quotaAllocationRequests for a resourceProvider/location. * - * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or - * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. - * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. + * Get all the quotaAllocationRequests for a resourceProvider/location. The filter paramter for location is + * required. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param allocateQuotaRequest Quota requests payload. - * @param context The context to associate with this operation. + * @param filter | Field | Supported operators + * |---------------------|------------------------ + * + * location eq {location} + * Example: $filter=location eq eastus. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of the subscription quota allocation status. + * @return all the quotaAllocationRequests for a resourceProvider/location along with {@link PagedResponse} on + * successful completion of {@link Mono}. */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, ProxyResource> beginCreateOrUpdate(String managementGroupId, - String groupQuotaName, String resourceProviderName, String resourceName, - QuotaAllocationRequestStatusInner allocateQuotaRequest, Context context) { - return this - .beginCreateOrUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, resourceName, - allocateQuotaRequest, context) - .getSyncPoller(); + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync(String managementGroupId, + String groupQuotaName, String resourceProviderName, String filter) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (managementGroupId == null) { + return Mono + .error(new IllegalArgumentException("Parameter managementGroupId is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (groupQuotaName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupQuotaName is required and cannot be null.")); + } + if (resourceProviderName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceProviderName is required and cannot be null.")); + } + if (filter == null) { + return Mono.error(new IllegalArgumentException("Parameter filter is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.list(this.client.getEndpoint(), managementGroupId, this.client.getSubscriptionId(), + groupQuotaName, resourceProviderName, this.client.getApiVersion(), filter, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** - * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * to check the status using Async polling as standards defined at - - * https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/async-api-reference.md#asynchronous-operations. + * Get all the quotaAllocationRequests for a resourceProvider/location. * - * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or - * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. - * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. + * Get all the quotaAllocationRequests for a resourceProvider/location. The filter paramter for location is + * required. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param allocateQuotaRequest Quota requests payload. + * @param filter | Field | Supported operators + * |---------------------|------------------------ + * + * location eq {location} + * Example: $filter=location eq eastus. + * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the subscription quota allocation status on successful completion of {@link Mono}. + * @return all the quotaAllocationRequests for a resourceProvider/location along with {@link PagedResponse} on + * successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono createOrUpdateAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName, QuotaAllocationRequestStatusInner allocateQuotaRequest) { - return beginCreateOrUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, resourceName, - allocateQuotaRequest).last().flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * to check the status using Async polling as standards defined at - - * https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/async-api-reference.md#asynchronous-operations. - * - * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or - * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. - * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param allocateQuotaRequest Quota requests payload. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the subscription quota allocation status on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono createOrUpdateAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName, QuotaAllocationRequestStatusInner allocateQuotaRequest, - Context context) { - return beginCreateOrUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, resourceName, - allocateQuotaRequest, context).last().flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * to check the status using Async polling as standards defined at - - * https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/async-api-reference.md#asynchronous-operations. - * - * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or - * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. - * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param allocateQuotaRequest Quota requests payload. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the subscription quota allocation status. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public ProxyResource createOrUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, - String resourceName, QuotaAllocationRequestStatusInner allocateQuotaRequest) { - return createOrUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, resourceName, - allocateQuotaRequest).block(); - } - - /** - * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * to check the status using Async polling as standards defined at - - * https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/async-api-reference.md#asynchronous-operations. - * - * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or - * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. - * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param allocateQuotaRequest Quota requests payload. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the subscription quota allocation status. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public ProxyResource createOrUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, - String resourceName, QuotaAllocationRequestStatusInner allocateQuotaRequest, Context context) { - return createOrUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, resourceName, - allocateQuotaRequest, context).block(); - } - - /** - * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * with 202 response and status polling API. - * - * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or - * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. - * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple - * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param allocateQuotaRequest Quota requests payload. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the subscription quota allocation status along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> updateWithResponseAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName, QuotaAllocationRequestStatusInner allocateQuotaRequest) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (managementGroupId == null) { - return Mono - .error(new IllegalArgumentException("Parameter managementGroupId is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (groupQuotaName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupQuotaName is required and cannot be null.")); - } - if (resourceProviderName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceProviderName is required and cannot be null.")); - } - if (resourceName == null) { - return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); - } - if (allocateQuotaRequest == null) { - return Mono - .error(new IllegalArgumentException("Parameter allocateQuotaRequest is required and cannot be null.")); - } else { - allocateQuotaRequest.validate(); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.update(this.client.getEndpoint(), managementGroupId, - this.client.getSubscriptionId(), groupQuotaName, resourceProviderName, resourceName, - this.client.getApiVersion(), allocateQuotaRequest, accept, context)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * with 202 response and status polling API. - * - * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or - * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. - * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple - * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param allocateQuotaRequest Quota requests payload. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the subscription quota allocation status along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono>> updateWithResponseAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName, QuotaAllocationRequestStatusInner allocateQuotaRequest, - Context context) { + private Mono> listSinglePageAsync(String managementGroupId, + String groupQuotaName, String resourceProviderName, String filter, Context context) { if (this.client.getEndpoint() == null) { return Mono.error( new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); @@ -970,265 +746,130 @@ private Mono>> updateWithResponseAsync(String manageme return Mono .error(new IllegalArgumentException("Parameter resourceProviderName is required and cannot be null.")); } - if (resourceName == null) { - return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); - } - if (allocateQuotaRequest == null) { - return Mono - .error(new IllegalArgumentException("Parameter allocateQuotaRequest is required and cannot be null.")); - } else { - allocateQuotaRequest.validate(); + if (filter == null) { + return Mono.error(new IllegalArgumentException("Parameter filter is required and cannot be null.")); } final String accept = "application/json"; context = this.client.mergeContext(context); - return service.update(this.client.getEndpoint(), managementGroupId, this.client.getSubscriptionId(), - groupQuotaName, resourceProviderName, resourceName, this.client.getApiVersion(), allocateQuotaRequest, - accept, context); + return service + .list(this.client.getEndpoint(), managementGroupId, this.client.getSubscriptionId(), groupQuotaName, + resourceProviderName, this.client.getApiVersion(), filter, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); } /** - * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * with 202 response and status polling API. + * Get all the quotaAllocationRequests for a resourceProvider/location. * - * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or - * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. - * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple - * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. + * Get all the quotaAllocationRequests for a resourceProvider/location. The filter paramter for location is + * required. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param allocateQuotaRequest Quota requests payload. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of the subscription quota allocation status. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, QuotaAllocationRequestStatusInner> - beginUpdateAsync(String managementGroupId, String groupQuotaName, String resourceProviderName, - String resourceName, QuotaAllocationRequestStatusInner allocateQuotaRequest) { - Mono>> mono = updateWithResponseAsync(managementGroupId, groupQuotaName, - resourceProviderName, resourceName, allocateQuotaRequest); - return this.client.getLroResult(mono, - this.client.getHttpPipeline(), QuotaAllocationRequestStatusInner.class, - QuotaAllocationRequestStatusInner.class, this.client.getContext()); - } - - /** - * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * with 202 response and status polling API. - * - * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or - * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. - * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple - * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. + * @param filter | Field | Supported operators + * |---------------------|------------------------ * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param allocateQuotaRequest Quota requests payload. - * @param context The context to associate with this operation. + * location eq {location} + * Example: $filter=location eq eastus. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link PollerFlux} for polling of the subscription quota allocation status. + * @return all the quotaAllocationRequests for a resourceProvider/location as paginated response with + * {@link PagedFlux}. */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - private PollerFlux, QuotaAllocationRequestStatusInner> - beginUpdateAsync(String managementGroupId, String groupQuotaName, String resourceProviderName, - String resourceName, QuotaAllocationRequestStatusInner allocateQuotaRequest, Context context) { - context = this.client.mergeContext(context); - Mono>> mono = updateWithResponseAsync(managementGroupId, groupQuotaName, - resourceProviderName, resourceName, allocateQuotaRequest, context); - return this.client.getLroResult(mono, - this.client.getHttpPipeline(), QuotaAllocationRequestStatusInner.class, - QuotaAllocationRequestStatusInner.class, context); + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync(String managementGroupId, String groupQuotaName, + String resourceProviderName, String filter) { + return new PagedFlux<>( + () -> listSinglePageAsync(managementGroupId, groupQuotaName, resourceProviderName, filter), + nextLink -> listNextSinglePageAsync(nextLink)); } /** - * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * with 202 response and status polling API. + * Get all the quotaAllocationRequests for a resourceProvider/location. * - * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or - * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. - * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple - * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. + * Get all the quotaAllocationRequests for a resourceProvider/location. The filter paramter for location is + * required. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param allocateQuotaRequest Quota requests payload. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of the subscription quota allocation status. - */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, QuotaAllocationRequestStatusInner> beginUpdate( - String managementGroupId, String groupQuotaName, String resourceProviderName, String resourceName, - QuotaAllocationRequestStatusInner allocateQuotaRequest) { - return this - .beginUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, resourceName, - allocateQuotaRequest) - .getSyncPoller(); - } - - /** - * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * with 202 response and status polling API. - * - * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or - * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. - * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple - * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. + * @param filter | Field | Supported operators + * |---------------------|------------------------ * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param allocateQuotaRequest Quota requests payload. + * location eq {location} + * Example: $filter=location eq eastus. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link SyncPoller} for polling of the subscription quota allocation status. + * @return all the quotaAllocationRequests for a resourceProvider/location as paginated response with + * {@link PagedFlux}. */ - @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) - public SyncPoller, QuotaAllocationRequestStatusInner> beginUpdate( - String managementGroupId, String groupQuotaName, String resourceProviderName, String resourceName, - QuotaAllocationRequestStatusInner allocateQuotaRequest, Context context) { - return this - .beginUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, resourceName, - allocateQuotaRequest, context) - .getSyncPoller(); + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync(String managementGroupId, String groupQuotaName, + String resourceProviderName, String filter, Context context) { + return new PagedFlux<>( + () -> listSinglePageAsync(managementGroupId, groupQuotaName, resourceProviderName, filter, context), + nextLink -> listNextSinglePageAsync(nextLink, context)); } /** - * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * with 202 response and status polling API. + * Get all the quotaAllocationRequests for a resourceProvider/location. * - * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or - * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. - * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple - * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. + * Get all the quotaAllocationRequests for a resourceProvider/location. The filter paramter for location is + * required. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param allocateQuotaRequest Quota requests payload. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the subscription quota allocation status on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono updateAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName, QuotaAllocationRequestStatusInner allocateQuotaRequest) { - return beginUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, resourceName, - allocateQuotaRequest).last().flatMap(this.client::getLroFinalResultOrError); - } - - /** - * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * with 202 response and status polling API. - * - * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or - * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. - * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple - * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. + * @param filter | Field | Supported operators + * |---------------------|------------------------ * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param allocateQuotaRequest Quota requests payload. - * @param context The context to associate with this operation. + * location eq {location} + * Example: $filter=location eq eastus. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the subscription quota allocation status on successful completion of {@link Mono}. + * @return all the quotaAllocationRequests for a resourceProvider/location as paginated response with + * {@link PagedIterable}. */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono updateAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName, QuotaAllocationRequestStatusInner allocateQuotaRequest, - Context context) { - return beginUpdateAsync(managementGroupId, groupQuotaName, resourceProviderName, resourceName, - allocateQuotaRequest, context).last().flatMap(this.client::getLroFinalResultOrError); + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(String managementGroupId, String groupQuotaName, + String resourceProviderName, String filter) { + return new PagedIterable<>(listAsync(managementGroupId, groupQuotaName, resourceProviderName, filter)); } /** - * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * with 202 response and status polling API. + * Get all the quotaAllocationRequests for a resourceProvider/location. * - * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or - * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. - * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple - * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. + * Get all the quotaAllocationRequests for a resourceProvider/location. The filter paramter for location is + * required. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param allocateQuotaRequest Quota requests payload. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the subscription quota allocation status. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public QuotaAllocationRequestStatusInner update(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName, QuotaAllocationRequestStatusInner allocateQuotaRequest) { - return updateAsync(managementGroupId, groupQuotaName, resourceProviderName, resourceName, allocateQuotaRequest) - .block(); - } - - /** - * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * with 202 response and status polling API. - * - * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or - * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. - * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple - * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. + * @param filter | Field | Supported operators + * |---------------------|------------------------ * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param allocateQuotaRequest Quota requests payload. + * location eq {location} + * Example: $filter=location eq eastus. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the subscription quota allocation status. + * @return all the quotaAllocationRequests for a resourceProvider/location as paginated response with + * {@link PagedIterable}. */ - @ServiceMethod(returns = ReturnType.SINGLE) - public QuotaAllocationRequestStatusInner update(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName, QuotaAllocationRequestStatusInner allocateQuotaRequest, - Context context) { - return updateAsync(managementGroupId, groupQuotaName, resourceProviderName, resourceName, allocateQuotaRequest, - context).block(); + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(String managementGroupId, String groupQuotaName, + String resourceProviderName, String filter, Context context) { + return new PagedIterable<>(listAsync(managementGroupId, groupQuotaName, resourceProviderName, filter, context)); } /** diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaSubscriptionAllocationRequestsImpl.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaSubscriptionAllocationRequestsImpl.java index 797791c0bd47..3ccb583a7c42 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaSubscriptionAllocationRequestsImpl.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaSubscriptionAllocationRequestsImpl.java @@ -7,13 +7,14 @@ import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.SimpleResponse; -import com.azure.core.management.ProxyResource; import com.azure.core.util.Context; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.quota.fluent.GroupQuotaSubscriptionAllocationRequestsClient; import com.azure.resourcemanager.quota.fluent.models.QuotaAllocationRequestStatusInner; +import com.azure.resourcemanager.quota.fluent.models.SubscriptionQuotaAllocationsListInner; import com.azure.resourcemanager.quota.models.GroupQuotaSubscriptionAllocationRequests; import com.azure.resourcemanager.quota.models.QuotaAllocationRequestStatus; +import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocationsList; public final class GroupQuotaSubscriptionAllocationRequestsImpl implements GroupQuotaSubscriptionAllocationRequests { private static final ClientLogger LOGGER = new ClientLogger(GroupQuotaSubscriptionAllocationRequestsImpl.class); @@ -28,10 +29,33 @@ public GroupQuotaSubscriptionAllocationRequestsImpl(GroupQuotaSubscriptionAlloca this.serviceManager = serviceManager; } + public SubscriptionQuotaAllocationsList update(String managementGroupId, String groupQuotaName, + String resourceProviderName, String location, SubscriptionQuotaAllocationsListInner allocateQuotaRequest) { + SubscriptionQuotaAllocationsListInner inner = this.serviceClient() + .update(managementGroupId, groupQuotaName, resourceProviderName, location, allocateQuotaRequest); + if (inner != null) { + return new SubscriptionQuotaAllocationsListImpl(inner, this.manager()); + } else { + return null; + } + } + + public SubscriptionQuotaAllocationsList update(String managementGroupId, String groupQuotaName, + String resourceProviderName, String location, SubscriptionQuotaAllocationsListInner allocateQuotaRequest, + Context context) { + SubscriptionQuotaAllocationsListInner inner = this.serviceClient() + .update(managementGroupId, groupQuotaName, resourceProviderName, location, allocateQuotaRequest, context); + if (inner != null) { + return new SubscriptionQuotaAllocationsListImpl(inner, this.manager()); + } else { + return null; + } + } + public Response getWithResponse(String managementGroupId, String groupQuotaName, - String allocationId, Context context) { - Response inner - = this.serviceClient().getWithResponse(managementGroupId, groupQuotaName, allocationId, context); + String resourceProviderName, String allocationId, Context context) { + Response inner = this.serviceClient() + .getWithResponse(managementGroupId, groupQuotaName, resourceProviderName, allocationId, context); if (inner != null) { return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), new QuotaAllocationRequestStatusImpl(inner.getValue(), this.manager())); @@ -40,9 +64,10 @@ public Response getWithResponse(String managementG } } - public QuotaAllocationRequestStatus get(String managementGroupId, String groupQuotaName, String allocationId) { + public QuotaAllocationRequestStatus get(String managementGroupId, String groupQuotaName, + String resourceProviderName, String allocationId) { QuotaAllocationRequestStatusInner inner - = this.serviceClient().get(managementGroupId, groupQuotaName, allocationId); + = this.serviceClient().get(managementGroupId, groupQuotaName, resourceProviderName, allocationId); if (inner != null) { return new QuotaAllocationRequestStatusImpl(inner, this.manager()); } else { @@ -66,44 +91,6 @@ public PagedIterable list(String managementGroupId inner1 -> new QuotaAllocationRequestStatusImpl(inner1, this.manager())); } - public ProxyResource createOrUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, - String resourceName, QuotaAllocationRequestStatusInner allocateQuotaRequest) { - return this.serviceClient() - .createOrUpdate(managementGroupId, groupQuotaName, resourceProviderName, resourceName, - allocateQuotaRequest); - } - - public ProxyResource createOrUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, - String resourceName, QuotaAllocationRequestStatusInner allocateQuotaRequest, Context context) { - return this.serviceClient() - .createOrUpdate(managementGroupId, groupQuotaName, resourceProviderName, resourceName, allocateQuotaRequest, - context); - } - - public QuotaAllocationRequestStatus update(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName, QuotaAllocationRequestStatusInner allocateQuotaRequest) { - QuotaAllocationRequestStatusInner inner = this.serviceClient() - .update(managementGroupId, groupQuotaName, resourceProviderName, resourceName, allocateQuotaRequest); - if (inner != null) { - return new QuotaAllocationRequestStatusImpl(inner, this.manager()); - } else { - return null; - } - } - - public QuotaAllocationRequestStatus update(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName, QuotaAllocationRequestStatusInner allocateQuotaRequest, - Context context) { - QuotaAllocationRequestStatusInner inner = this.serviceClient() - .update(managementGroupId, groupQuotaName, resourceProviderName, resourceName, allocateQuotaRequest, - context); - if (inner != null) { - return new QuotaAllocationRequestStatusImpl(inner, this.manager()); - } else { - return null; - } - } - private GroupQuotaSubscriptionAllocationRequestsClient serviceClient() { return this.innerClient; } diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaSubscriptionAllocationsClientImpl.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaSubscriptionAllocationsClientImpl.java index e95269c5038b..c3c15ea3a12c 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaSubscriptionAllocationsClientImpl.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaSubscriptionAllocationsClientImpl.java @@ -16,18 +16,13 @@ import com.azure.core.annotation.ServiceInterface; import com.azure.core.annotation.ServiceMethod; import com.azure.core.annotation.UnexpectedResponseExceptionType; -import com.azure.core.http.rest.PagedFlux; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.PagedResponse; -import com.azure.core.http.rest.PagedResponseBase; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.RestProxy; import com.azure.core.management.exception.ManagementException; import com.azure.core.util.Context; import com.azure.core.util.FluxUtil; import com.azure.resourcemanager.quota.fluent.GroupQuotaSubscriptionAllocationsClient; -import com.azure.resourcemanager.quota.fluent.models.SubscriptionQuotaAllocationsInner; -import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocationsList; +import com.azure.resourcemanager.quota.fluent.models.SubscriptionQuotaAllocationsListInner; import reactor.core.publisher.Mono; /** @@ -63,58 +58,39 @@ public final class GroupQuotaSubscriptionAllocationsClientImpl implements GroupQ @ServiceInterface(name = "AzureQuotaExtensionA") public interface GroupQuotaSubscriptionAllocationsService { @Headers({ "Content-Type: application/json" }) - @Get("/providers/Microsoft.Management/managementGroups/{managementGroupId}/subscriptions/{subscriptionId}/providers/Microsoft.Quota/groupQuotas/{groupQuotaName}/quotaAllocations") + @Get("/providers/Microsoft.Management/managementGroups/{managementGroupId}/subscriptions/{subscriptionId}/providers/Microsoft.Quota/groupQuotas/{groupQuotaName}/resourceProviders/{resourceProviderName}/quotaAllocations/{location}") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono> list(@HostParam("$host") String endpoint, + Mono> list(@HostParam("$host") String endpoint, @PathParam("managementGroupId") String managementGroupId, @PathParam("subscriptionId") String subscriptionId, @PathParam("groupQuotaName") String groupQuotaName, - @QueryParam("api-version") String apiVersion, @QueryParam("$filter") String filter, - @HeaderParam("Accept") String accept, Context context); - - @Headers({ "Content-Type: application/json" }) - @Get("/providers/Microsoft.Management/managementGroups/{managementGroupId}/subscriptions/{subscriptionId}/providers/Microsoft.Quota/groupQuotas/{groupQuotaName}/quotaAllocations/{resourceName}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> get(@HostParam("$host") String endpoint, - @PathParam("managementGroupId") String managementGroupId, - @PathParam("subscriptionId") String subscriptionId, @PathParam("groupQuotaName") String groupQuotaName, - @PathParam("resourceName") String resourceName, @QueryParam("api-version") String apiVersion, - @QueryParam("$filter") String filter, @HeaderParam("Accept") String accept, Context context); - - @Headers({ "Content-Type: application/json" }) - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> listNext( - @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, - @HeaderParam("Accept") String accept, Context context); + @PathParam("resourceProviderName") String resourceProviderName, @PathParam("location") String location, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); } /** - * Gets all the quota allocated to a subscription for the specific Resource Provider, Location. + * Gets all the quota allocated to a subscription for the specified resource provider and location for resource + * names passed in $filter=resourceName eq {SKU}. * - * Gets all the quota allocated to a subscription for the specific Resource Provider, Location. This will include - * the GroupQuota and total quota allocated to the subscription. Only the Group quota allocated to the subscription - * can be allocated back to the MG Group Quota. Use the $filter parameter to filter out the specific resource based - * on the ResourceProvider/Location. $filter is a required parameter. + * Gets all the quota allocated to a subscription for the specified resource provider and location for resource + * names passed in $filter=resourceName eq {SKU}. This will include the GroupQuota and total quota allocated to the + * subscription. Only the Group quota allocated to the subscription can be allocated back to the MG Group Quota. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. + * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only + * Microsoft.Compute resource provider supports this API. + * @param location The name of the Azure region. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all the quota allocated to a subscription for the specific Resource Provider, Location along with - * {@link PagedResponse} on successful completion of {@link Mono}. + * @return all the quota allocated to a subscription for the specified resource provider and location for resource + * names passed in $filter=resourceName eq {SKU} along with {@link Response} on successful completion of + * {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listSinglePageAsync(String managementGroupId, - String groupQuotaName, String filter) { + private Mono> listWithResponseAsync(String managementGroupId, + String groupQuotaName, String resourceProviderName, String location) { if (this.client.getEndpoint() == null) { return Mono.error( new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); @@ -130,260 +106,45 @@ private Mono> listSinglePageAsy if (groupQuotaName == null) { return Mono.error(new IllegalArgumentException("Parameter groupQuotaName is required and cannot be null.")); } - if (filter == null) { - return Mono.error(new IllegalArgumentException("Parameter filter is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.list(this.client.getEndpoint(), managementGroupId, - this.client.getSubscriptionId(), groupQuotaName, this.client.getApiVersion(), filter, accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), - res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Gets all the quota allocated to a subscription for the specific Resource Provider, Location. - * - * Gets all the quota allocated to a subscription for the specific Resource Provider, Location. This will include - * the GroupQuota and total quota allocated to the subscription. Only the Group quota allocated to the subscription - * can be allocated back to the MG Group Quota. Use the $filter parameter to filter out the specific resource based - * on the ResourceProvider/Location. $filter is a required parameter. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all the quota allocated to a subscription for the specific Resource Provider, Location along with - * {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listSinglePageAsync(String managementGroupId, - String groupQuotaName, String filter, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (managementGroupId == null) { - return Mono - .error(new IllegalArgumentException("Parameter managementGroupId is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (groupQuotaName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupQuotaName is required and cannot be null.")); - } - if (filter == null) { - return Mono.error(new IllegalArgumentException("Parameter filter is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service - .list(this.client.getEndpoint(), managementGroupId, this.client.getSubscriptionId(), groupQuotaName, - this.client.getApiVersion(), filter, accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } - - /** - * Gets all the quota allocated to a subscription for the specific Resource Provider, Location. - * - * Gets all the quota allocated to a subscription for the specific Resource Provider, Location. This will include - * the GroupQuota and total quota allocated to the subscription. Only the Group quota allocated to the subscription - * can be allocated back to the MG Group Quota. Use the $filter parameter to filter out the specific resource based - * on the ResourceProvider/Location. $filter is a required parameter. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all the quota allocated to a subscription for the specific Resource Provider, Location as paginated - * response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listAsync(String managementGroupId, String groupQuotaName, - String filter) { - return new PagedFlux<>(() -> listSinglePageAsync(managementGroupId, groupQuotaName, filter), - nextLink -> listNextSinglePageAsync(nextLink)); - } - - /** - * Gets all the quota allocated to a subscription for the specific Resource Provider, Location. - * - * Gets all the quota allocated to a subscription for the specific Resource Provider, Location. This will include - * the GroupQuota and total quota allocated to the subscription. Only the Group quota allocated to the subscription - * can be allocated back to the MG Group Quota. Use the $filter parameter to filter out the specific resource based - * on the ResourceProvider/Location. $filter is a required parameter. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all the quota allocated to a subscription for the specific Resource Provider, Location as paginated - * response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listAsync(String managementGroupId, String groupQuotaName, - String filter, Context context) { - return new PagedFlux<>(() -> listSinglePageAsync(managementGroupId, groupQuotaName, filter, context), - nextLink -> listNextSinglePageAsync(nextLink, context)); - } - - /** - * Gets all the quota allocated to a subscription for the specific Resource Provider, Location. - * - * Gets all the quota allocated to a subscription for the specific Resource Provider, Location. This will include - * the GroupQuota and total quota allocated to the subscription. Only the Group quota allocated to the subscription - * can be allocated back to the MG Group Quota. Use the $filter parameter to filter out the specific resource based - * on the ResourceProvider/Location. $filter is a required parameter. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all the quota allocated to a subscription for the specific Resource Provider, Location as paginated - * response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list(String managementGroupId, String groupQuotaName, - String filter) { - return new PagedIterable<>(listAsync(managementGroupId, groupQuotaName, filter)); - } - - /** - * Gets all the quota allocated to a subscription for the specific Resource Provider, Location. - * - * Gets all the quota allocated to a subscription for the specific Resource Provider, Location. This will include - * the GroupQuota and total quota allocated to the subscription. Only the Group quota allocated to the subscription - * can be allocated back to the MG Group Quota. Use the $filter parameter to filter out the specific resource based - * on the ResourceProvider/Location. $filter is a required parameter. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all the quota allocated to a subscription for the specific Resource Provider, Location as paginated - * response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list(String managementGroupId, String groupQuotaName, - String filter, Context context) { - return new PagedIterable<>(listAsync(managementGroupId, groupQuotaName, filter, context)); - } - - /** - * Gets Quota allocated to a subscription for the specific Resource Provider, Location, ResourceName. - * - * Gets Quota allocated to a subscription for the specific Resource Provider, Location, ResourceName. This will - * include the GroupQuota and total quota allocated to the subscription. Only the Group quota allocated to the - * subscription can be allocated back to the MG Group Quota. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceName Resource name. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return quota allocated to a subscription for the specific Resource Provider, Location, ResourceName along with - * {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> getWithResponseAsync(String managementGroupId, - String groupQuotaName, String resourceName, String filter) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (managementGroupId == null) { + if (resourceProviderName == null) { return Mono - .error(new IllegalArgumentException("Parameter managementGroupId is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + .error(new IllegalArgumentException("Parameter resourceProviderName is required and cannot be null.")); } - if (groupQuotaName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupQuotaName is required and cannot be null.")); - } - if (resourceName == null) { - return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); - } - if (filter == null) { - return Mono.error(new IllegalArgumentException("Parameter filter is required and cannot be null.")); + if (location == null) { + return Mono.error(new IllegalArgumentException("Parameter location is required and cannot be null.")); } final String accept = "application/json"; return FluxUtil .withContext( - context -> service.get(this.client.getEndpoint(), managementGroupId, this.client.getSubscriptionId(), - groupQuotaName, resourceName, this.client.getApiVersion(), filter, accept, context)) + context -> service.list(this.client.getEndpoint(), managementGroupId, this.client.getSubscriptionId(), + groupQuotaName, resourceProviderName, location, this.client.getApiVersion(), accept, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** - * Gets Quota allocated to a subscription for the specific Resource Provider, Location, ResourceName. + * Gets all the quota allocated to a subscription for the specified resource provider and location for resource + * names passed in $filter=resourceName eq {SKU}. * - * Gets Quota allocated to a subscription for the specific Resource Provider, Location, ResourceName. This will - * include the GroupQuota and total quota allocated to the subscription. Only the Group quota allocated to the - * subscription can be allocated back to the MG Group Quota. + * Gets all the quota allocated to a subscription for the specified resource provider and location for resource + * names passed in $filter=resourceName eq {SKU}. This will include the GroupQuota and total quota allocated to the + * subscription. Only the Group quota allocated to the subscription can be allocated back to the MG Group Quota. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceName Resource name. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. + * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only + * Microsoft.Compute resource provider supports this API. + * @param location The name of the Azure region. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return quota allocated to a subscription for the specific Resource Provider, Location, ResourceName along with - * {@link Response} on successful completion of {@link Mono}. + * @return all the quota allocated to a subscription for the specified resource provider and location for resource + * names passed in $filter=resourceName eq {SKU} along with {@link Response} on successful completion of + * {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> getWithResponseAsync(String managementGroupId, - String groupQuotaName, String resourceName, String filter, Context context) { + private Mono> listWithResponseAsync(String managementGroupId, + String groupQuotaName, String resourceProviderName, String location, Context context) { if (this.client.getEndpoint() == null) { return Mono.error( new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); @@ -399,149 +160,95 @@ private Mono> getWithResponseAsync(S if (groupQuotaName == null) { return Mono.error(new IllegalArgumentException("Parameter groupQuotaName is required and cannot be null.")); } - if (resourceName == null) { - return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); + if (resourceProviderName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceProviderName is required and cannot be null.")); } - if (filter == null) { - return Mono.error(new IllegalArgumentException("Parameter filter is required and cannot be null.")); + if (location == null) { + return Mono.error(new IllegalArgumentException("Parameter location is required and cannot be null.")); } final String accept = "application/json"; context = this.client.mergeContext(context); - return service.get(this.client.getEndpoint(), managementGroupId, this.client.getSubscriptionId(), - groupQuotaName, resourceName, this.client.getApiVersion(), filter, accept, context); + return service.list(this.client.getEndpoint(), managementGroupId, this.client.getSubscriptionId(), + groupQuotaName, resourceProviderName, location, this.client.getApiVersion(), accept, context); } /** - * Gets Quota allocated to a subscription for the specific Resource Provider, Location, ResourceName. + * Gets all the quota allocated to a subscription for the specified resource provider and location for resource + * names passed in $filter=resourceName eq {SKU}. * - * Gets Quota allocated to a subscription for the specific Resource Provider, Location, ResourceName. This will - * include the GroupQuota and total quota allocated to the subscription. Only the Group quota allocated to the - * subscription can be allocated back to the MG Group Quota. + * Gets all the quota allocated to a subscription for the specified resource provider and location for resource + * names passed in $filter=resourceName eq {SKU}. This will include the GroupQuota and total quota allocated to the + * subscription. Only the Group quota allocated to the subscription can be allocated back to the MG Group Quota. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceName Resource name. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. + * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only + * Microsoft.Compute resource provider supports this API. + * @param location The name of the Azure region. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return quota allocated to a subscription for the specific Resource Provider, Location, ResourceName on - * successful completion of {@link Mono}. + * @return all the quota allocated to a subscription for the specified resource provider and location for resource + * names passed in $filter=resourceName eq {SKU} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono getAsync(String managementGroupId, String groupQuotaName, - String resourceName, String filter) { - return getWithResponseAsync(managementGroupId, groupQuotaName, resourceName, filter) + private Mono listAsync(String managementGroupId, String groupQuotaName, + String resourceProviderName, String location) { + return listWithResponseAsync(managementGroupId, groupQuotaName, resourceProviderName, location) .flatMap(res -> Mono.justOrEmpty(res.getValue())); } /** - * Gets Quota allocated to a subscription for the specific Resource Provider, Location, ResourceName. + * Gets all the quota allocated to a subscription for the specified resource provider and location for resource + * names passed in $filter=resourceName eq {SKU}. * - * Gets Quota allocated to a subscription for the specific Resource Provider, Location, ResourceName. This will - * include the GroupQuota and total quota allocated to the subscription. Only the Group quota allocated to the - * subscription can be allocated back to the MG Group Quota. + * Gets all the quota allocated to a subscription for the specified resource provider and location for resource + * names passed in $filter=resourceName eq {SKU}. This will include the GroupQuota and total quota allocated to the + * subscription. Only the Group quota allocated to the subscription can be allocated back to the MG Group Quota. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceName Resource name. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. + * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only + * Microsoft.Compute resource provider supports this API. + * @param location The name of the Azure region. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return quota allocated to a subscription for the specific Resource Provider, Location, ResourceName along with - * {@link Response}. + * @return all the quota allocated to a subscription for the specified resource provider and location for resource + * names passed in $filter=resourceName eq {SKU} along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response getWithResponse(String managementGroupId, String groupQuotaName, - String resourceName, String filter, Context context) { - return getWithResponseAsync(managementGroupId, groupQuotaName, resourceName, filter, context).block(); + public Response listWithResponse(String managementGroupId, + String groupQuotaName, String resourceProviderName, String location, Context context) { + return listWithResponseAsync(managementGroupId, groupQuotaName, resourceProviderName, location, context) + .block(); } /** - * Gets Quota allocated to a subscription for the specific Resource Provider, Location, ResourceName. + * Gets all the quota allocated to a subscription for the specified resource provider and location for resource + * names passed in $filter=resourceName eq {SKU}. * - * Gets Quota allocated to a subscription for the specific Resource Provider, Location, ResourceName. This will - * include the GroupQuota and total quota allocated to the subscription. Only the Group quota allocated to the - * subscription can be allocated back to the MG Group Quota. + * Gets all the quota allocated to a subscription for the specified resource provider and location for resource + * names passed in $filter=resourceName eq {SKU}. This will include the GroupQuota and total quota allocated to the + * subscription. Only the Group quota allocated to the subscription can be allocated back to the MG Group Quota. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceName Resource name. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return quota allocated to a subscription for the specific Resource Provider, Location, ResourceName. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SubscriptionQuotaAllocationsInner get(String managementGroupId, String groupQuotaName, String resourceName, - String filter) { - return getWithResponse(managementGroupId, groupQuotaName, resourceName, filter, Context.NONE).getValue(); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return subscription quota list along with {@link PagedResponse} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listNextSinglePageAsync(String nextLink) { - if (nextLink == null) { - return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - } - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.listNext(nextLink, this.client.getEndpoint(), accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), - res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param context The context to associate with this operation. + * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only + * Microsoft.Compute resource provider supports this API. + * @param location The name of the Azure region. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return subscription quota list along with {@link PagedResponse} on successful completion of {@link Mono}. + * @return all the quota allocated to a subscription for the specified resource provider and location for resource + * names passed in $filter=resourceName eq {SKU}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listNextSinglePageAsync(String nextLink, - Context context) { - if (nextLink == null) { - return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - } - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.listNext(nextLink, this.client.getEndpoint(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); + public SubscriptionQuotaAllocationsListInner list(String managementGroupId, String groupQuotaName, + String resourceProviderName, String location) { + return listWithResponse(managementGroupId, groupQuotaName, resourceProviderName, location, Context.NONE) + .getValue(); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaSubscriptionAllocationsImpl.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaSubscriptionAllocationsImpl.java index c38015940147..039f544978dd 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaSubscriptionAllocationsImpl.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaSubscriptionAllocationsImpl.java @@ -4,15 +4,14 @@ package com.azure.resourcemanager.quota.implementation; -import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.SimpleResponse; import com.azure.core.util.Context; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.quota.fluent.GroupQuotaSubscriptionAllocationsClient; -import com.azure.resourcemanager.quota.fluent.models.SubscriptionQuotaAllocationsInner; +import com.azure.resourcemanager.quota.fluent.models.SubscriptionQuotaAllocationsListInner; import com.azure.resourcemanager.quota.models.GroupQuotaSubscriptionAllocations; -import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocations; +import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocationsList; public final class GroupQuotaSubscriptionAllocationsImpl implements GroupQuotaSubscriptionAllocations { private static final ClientLogger LOGGER = new ClientLogger(GroupQuotaSubscriptionAllocationsImpl.class); @@ -27,40 +26,24 @@ public GroupQuotaSubscriptionAllocationsImpl(GroupQuotaSubscriptionAllocationsCl this.serviceManager = serviceManager; } - public PagedIterable list(String managementGroupId, String groupQuotaName, - String filter) { - PagedIterable inner - = this.serviceClient().list(managementGroupId, groupQuotaName, filter); - return ResourceManagerUtils.mapPage(inner, - inner1 -> new SubscriptionQuotaAllocationsImpl(inner1, this.manager())); - } - - public PagedIterable list(String managementGroupId, String groupQuotaName, - String filter, Context context) { - PagedIterable inner - = this.serviceClient().list(managementGroupId, groupQuotaName, filter, context); - return ResourceManagerUtils.mapPage(inner, - inner1 -> new SubscriptionQuotaAllocationsImpl(inner1, this.manager())); - } - - public Response getWithResponse(String managementGroupId, String groupQuotaName, - String resourceName, String filter, Context context) { - Response inner - = this.serviceClient().getWithResponse(managementGroupId, groupQuotaName, resourceName, filter, context); + public Response listWithResponse(String managementGroupId, String groupQuotaName, + String resourceProviderName, String location, Context context) { + Response inner = this.serviceClient() + .listWithResponse(managementGroupId, groupQuotaName, resourceProviderName, location, context); if (inner != null) { return new SimpleResponse<>(inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), - new SubscriptionQuotaAllocationsImpl(inner.getValue(), this.manager())); + new SubscriptionQuotaAllocationsListImpl(inner.getValue(), this.manager())); } else { return null; } } - public SubscriptionQuotaAllocations get(String managementGroupId, String groupQuotaName, String resourceName, - String filter) { - SubscriptionQuotaAllocationsInner inner - = this.serviceClient().get(managementGroupId, groupQuotaName, resourceName, filter); + public SubscriptionQuotaAllocationsList list(String managementGroupId, String groupQuotaName, + String resourceProviderName, String location) { + SubscriptionQuotaAllocationsListInner inner + = this.serviceClient().list(managementGroupId, groupQuotaName, resourceProviderName, location); if (inner != null) { - return new SubscriptionQuotaAllocationsImpl(inner, this.manager()); + return new SubscriptionQuotaAllocationsListImpl(inner, this.manager()); } else { return null; } diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaUsagesClientImpl.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaUsagesClientImpl.java deleted file mode 100644 index 29db7b886ebf..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaUsagesClientImpl.java +++ /dev/null @@ -1,319 +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.resourcemanager.quota.implementation; - -import com.azure.core.annotation.ExpectedResponses; -import com.azure.core.annotation.Get; -import com.azure.core.annotation.HeaderParam; -import com.azure.core.annotation.Headers; -import com.azure.core.annotation.Host; -import com.azure.core.annotation.HostParam; -import com.azure.core.annotation.PathParam; -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.PagedFlux; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.PagedResponse; -import com.azure.core.http.rest.PagedResponseBase; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.RestProxy; -import com.azure.core.management.exception.ManagementException; -import com.azure.core.util.Context; -import com.azure.core.util.FluxUtil; -import com.azure.resourcemanager.quota.fluent.GroupQuotaUsagesClient; -import com.azure.resourcemanager.quota.fluent.models.ResourceUsagesInner; -import com.azure.resourcemanager.quota.models.ResourceUsageList; -import reactor.core.publisher.Mono; - -/** - * An instance of this class provides access to all the operations defined in GroupQuotaUsagesClient. - */ -public final class GroupQuotaUsagesClientImpl implements GroupQuotaUsagesClient { - /** - * The proxy service used to perform REST calls. - */ - private final GroupQuotaUsagesService service; - - /** - * The service client containing this operation class. - */ - private final AzureQuotaExtensionApiImpl client; - - /** - * Initializes an instance of GroupQuotaUsagesClientImpl. - * - * @param client the instance of the service client containing this operation class. - */ - GroupQuotaUsagesClientImpl(AzureQuotaExtensionApiImpl client) { - this.service - = RestProxy.create(GroupQuotaUsagesService.class, client.getHttpPipeline(), client.getSerializerAdapter()); - this.client = client; - } - - /** - * The interface defining all the services for AzureQuotaExtensionApiGroupQuotaUsages to be used by the proxy - * service to perform REST calls. - */ - @Host("{$host}") - @ServiceInterface(name = "AzureQuotaExtensionA") - public interface GroupQuotaUsagesService { - @Headers({ "Content-Type: application/json" }) - @Get("/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Quota/groupQuotas/{groupQuotaName}/resourceProviders/{resourceProviderName}/locationUsages/{location}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> list(@HostParam("$host") String endpoint, - @PathParam("managementGroupId") String managementGroupId, - @PathParam("groupQuotaName") String groupQuotaName, - @PathParam("resourceProviderName") String resourceProviderName, @PathParam("location") String location, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Headers({ "Content-Type: application/json" }) - @Get("{nextLink}") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> listNext(@PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("$host") String endpoint, @HeaderParam("Accept") String accept, Context context); - } - - /** - * Gets the GroupQuotas usages and limits(quota) for the resourceProvider/location. - * - * Gets the GroupQuotas usages and limits(quota). Location is required paramter. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotas usages and limits(quota) along with {@link PagedResponse} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listSinglePageAsync(String managementGroupId, - String groupQuotaName, String resourceProviderName, String location) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (managementGroupId == null) { - return Mono - .error(new IllegalArgumentException("Parameter managementGroupId is required and cannot be null.")); - } - if (groupQuotaName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupQuotaName is required and cannot be null.")); - } - if (resourceProviderName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceProviderName is required and cannot be null.")); - } - if (location == null) { - return Mono.error(new IllegalArgumentException("Parameter location is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.list(this.client.getEndpoint(), managementGroupId, groupQuotaName, - resourceProviderName, location, this.client.getApiVersion(), accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), - res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Gets the GroupQuotas usages and limits(quota) for the resourceProvider/location. - * - * Gets the GroupQuotas usages and limits(quota). Location is required paramter. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotas usages and limits(quota) along with {@link PagedResponse} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listSinglePageAsync(String managementGroupId, - String groupQuotaName, String resourceProviderName, String location, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (managementGroupId == null) { - return Mono - .error(new IllegalArgumentException("Parameter managementGroupId is required and cannot be null.")); - } - if (groupQuotaName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupQuotaName is required and cannot be null.")); - } - if (resourceProviderName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceProviderName is required and cannot be null.")); - } - if (location == null) { - return Mono.error(new IllegalArgumentException("Parameter location is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service - .list(this.client.getEndpoint(), managementGroupId, groupQuotaName, resourceProviderName, location, - this.client.getApiVersion(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } - - /** - * Gets the GroupQuotas usages and limits(quota) for the resourceProvider/location. - * - * Gets the GroupQuotas usages and limits(quota). Location is required paramter. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotas usages and limits(quota) as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String location) { - return new PagedFlux<>( - () -> listSinglePageAsync(managementGroupId, groupQuotaName, resourceProviderName, location), - nextLink -> listNextSinglePageAsync(nextLink)); - } - - /** - * Gets the GroupQuotas usages and limits(quota) for the resourceProvider/location. - * - * Gets the GroupQuotas usages and limits(quota). Location is required paramter. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotas usages and limits(quota) as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listAsync(String managementGroupId, String groupQuotaName, - String resourceProviderName, String location, Context context) { - return new PagedFlux<>( - () -> listSinglePageAsync(managementGroupId, groupQuotaName, resourceProviderName, location, context), - nextLink -> listNextSinglePageAsync(nextLink, context)); - } - - /** - * Gets the GroupQuotas usages and limits(quota) for the resourceProvider/location. - * - * Gets the GroupQuotas usages and limits(quota). Location is required paramter. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotas usages and limits(quota) as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list(String managementGroupId, String groupQuotaName, - String resourceProviderName, String location) { - return new PagedIterable<>(listAsync(managementGroupId, groupQuotaName, resourceProviderName, location)); - } - - /** - * Gets the GroupQuotas usages and limits(quota) for the resourceProvider/location. - * - * Gets the GroupQuotas usages and limits(quota). Location is required paramter. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotas usages and limits(quota) as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list(String managementGroupId, String groupQuotaName, - String resourceProviderName, String location, Context context) { - return new PagedIterable<>( - listAsync(managementGroupId, groupQuotaName, resourceProviderName, location, context)); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return list of resource usages and quotas for GroupQuota along with {@link PagedResponse} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listNextSinglePageAsync(String nextLink) { - if (nextLink == null) { - return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - } - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil.withContext(context -> service.listNext(nextLink, this.client.getEndpoint(), accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), - res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * Get the next page of items. - * - * @param nextLink The URL to get the next list of items. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return list of resource usages and quotas for GroupQuota along with {@link PagedResponse} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listNextSinglePageAsync(String nextLink, Context context) { - if (nextLink == null) { - return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - } - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service.listNext(nextLink, this.client.getEndpoint(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaUsagesImpl.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaUsagesImpl.java deleted file mode 100644 index 804730198b1d..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotaUsagesImpl.java +++ /dev/null @@ -1,49 +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.resourcemanager.quota.implementation; - -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.util.Context; -import com.azure.core.util.logging.ClientLogger; -import com.azure.resourcemanager.quota.fluent.GroupQuotaUsagesClient; -import com.azure.resourcemanager.quota.fluent.models.ResourceUsagesInner; -import com.azure.resourcemanager.quota.models.GroupQuotaUsages; -import com.azure.resourcemanager.quota.models.ResourceUsages; - -public final class GroupQuotaUsagesImpl implements GroupQuotaUsages { - private static final ClientLogger LOGGER = new ClientLogger(GroupQuotaUsagesImpl.class); - - private final GroupQuotaUsagesClient innerClient; - - private final com.azure.resourcemanager.quota.QuotaManager serviceManager; - - public GroupQuotaUsagesImpl(GroupQuotaUsagesClient innerClient, - com.azure.resourcemanager.quota.QuotaManager serviceManager) { - this.innerClient = innerClient; - this.serviceManager = serviceManager; - } - - public PagedIterable list(String managementGroupId, String groupQuotaName, - String resourceProviderName, String location) { - PagedIterable inner - = this.serviceClient().list(managementGroupId, groupQuotaName, resourceProviderName, location); - return ResourceManagerUtils.mapPage(inner, inner1 -> new ResourceUsagesImpl(inner1, this.manager())); - } - - public PagedIterable list(String managementGroupId, String groupQuotaName, - String resourceProviderName, String location, Context context) { - PagedIterable inner - = this.serviceClient().list(managementGroupId, groupQuotaName, resourceProviderName, location, context); - return ResourceManagerUtils.mapPage(inner, inner1 -> new ResourceUsagesImpl(inner1, this.manager())); - } - - private GroupQuotaUsagesClient serviceClient() { - return this.innerClient; - } - - private com.azure.resourcemanager.quota.QuotaManager manager() { - return this.serviceManager; - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotasEnforcementResponseImpl.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotasEnforcementResponseImpl.java deleted file mode 100644 index 5c13e68d8e04..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotasEnforcementResponseImpl.java +++ /dev/null @@ -1,50 +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.resourcemanager.quota.implementation; - -import com.azure.core.management.SystemData; -import com.azure.resourcemanager.quota.fluent.models.GroupQuotasEnforcementResponseInner; -import com.azure.resourcemanager.quota.models.GroupQuotasEnforcementResponse; -import com.azure.resourcemanager.quota.models.GroupQuotasEnforcementResponseProperties; - -public final class GroupQuotasEnforcementResponseImpl implements GroupQuotasEnforcementResponse { - private GroupQuotasEnforcementResponseInner innerObject; - - private final com.azure.resourcemanager.quota.QuotaManager serviceManager; - - GroupQuotasEnforcementResponseImpl(GroupQuotasEnforcementResponseInner innerObject, - com.azure.resourcemanager.quota.QuotaManager serviceManager) { - this.innerObject = innerObject; - this.serviceManager = serviceManager; - } - - public String id() { - return this.innerModel().id(); - } - - public String name() { - return this.innerModel().name(); - } - - public String type() { - return this.innerModel().type(); - } - - public GroupQuotasEnforcementResponseProperties properties() { - return this.innerModel().properties(); - } - - public SystemData systemData() { - return this.innerModel().systemData(); - } - - public GroupQuotasEnforcementResponseInner innerModel() { - return this.innerObject; - } - - private com.azure.resourcemanager.quota.QuotaManager manager() { - return this.serviceManager; - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotasEntityImpl.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotasEntityImpl.java index c5e217912977..641da4affc15 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotasEntityImpl.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/GroupQuotasEntityImpl.java @@ -7,7 +7,7 @@ import com.azure.core.management.SystemData; import com.azure.resourcemanager.quota.fluent.models.GroupQuotasEntityInner; import com.azure.resourcemanager.quota.models.GroupQuotasEntity; -import com.azure.resourcemanager.quota.models.GroupQuotasEntityBase; +import com.azure.resourcemanager.quota.models.GroupQuotasEntityProperties; public final class GroupQuotasEntityImpl implements GroupQuotasEntity { private GroupQuotasEntityInner innerObject; @@ -32,7 +32,7 @@ public String type() { return this.innerModel().type(); } - public GroupQuotasEntityBase properties() { + public GroupQuotasEntityProperties properties() { return this.innerModel().properties(); } diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/ResourceUsagesImpl.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/ResourceUsagesImpl.java deleted file mode 100644 index abc196e27dea..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/ResourceUsagesImpl.java +++ /dev/null @@ -1,49 +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.resourcemanager.quota.implementation; - -import com.azure.core.management.SystemData; -import com.azure.resourcemanager.quota.fluent.models.ResourceUsagesInner; -import com.azure.resourcemanager.quota.models.GroupQuotaUsagesBase; -import com.azure.resourcemanager.quota.models.ResourceUsages; - -public final class ResourceUsagesImpl implements ResourceUsages { - private ResourceUsagesInner innerObject; - - private final com.azure.resourcemanager.quota.QuotaManager serviceManager; - - ResourceUsagesImpl(ResourceUsagesInner innerObject, com.azure.resourcemanager.quota.QuotaManager serviceManager) { - this.innerObject = innerObject; - this.serviceManager = serviceManager; - } - - public String id() { - return this.innerModel().id(); - } - - public String name() { - return this.innerModel().name(); - } - - public String type() { - return this.innerModel().type(); - } - - public GroupQuotaUsagesBase properties() { - return this.innerModel().properties(); - } - - public SystemData systemData() { - return this.innerModel().systemData(); - } - - public ResourceUsagesInner innerModel() { - return this.innerObject; - } - - private com.azure.resourcemanager.quota.QuotaManager manager() { - return this.serviceManager; - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/SubscriptionQuotaAllocationsImpl.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/SubscriptionQuotaAllocationsImpl.java deleted file mode 100644 index d1c9fd945f8e..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/SubscriptionQuotaAllocationsImpl.java +++ /dev/null @@ -1,50 +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.resourcemanager.quota.implementation; - -import com.azure.core.management.SystemData; -import com.azure.resourcemanager.quota.fluent.models.SubscriptionQuotaAllocationsInner; -import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocations; -import com.azure.resourcemanager.quota.models.SubscriptionQuotaDetails; - -public final class SubscriptionQuotaAllocationsImpl implements SubscriptionQuotaAllocations { - private SubscriptionQuotaAllocationsInner innerObject; - - private final com.azure.resourcemanager.quota.QuotaManager serviceManager; - - SubscriptionQuotaAllocationsImpl(SubscriptionQuotaAllocationsInner innerObject, - com.azure.resourcemanager.quota.QuotaManager serviceManager) { - this.innerObject = innerObject; - this.serviceManager = serviceManager; - } - - public String id() { - return this.innerModel().id(); - } - - public String name() { - return this.innerModel().name(); - } - - public String type() { - return this.innerModel().type(); - } - - public SubscriptionQuotaDetails properties() { - return this.innerModel().properties(); - } - - public SystemData systemData() { - return this.innerModel().systemData(); - } - - public SubscriptionQuotaAllocationsInner innerModel() { - return this.innerObject; - } - - private com.azure.resourcemanager.quota.QuotaManager manager() { - return this.serviceManager; - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/SubscriptionQuotaAllocationsListImpl.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/SubscriptionQuotaAllocationsListImpl.java new file mode 100644 index 000000000000..6fd2ec61b1da --- /dev/null +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/implementation/SubscriptionQuotaAllocationsListImpl.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.quota.implementation; + +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.quota.fluent.models.SubscriptionQuotaAllocationsListInner; +import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocationsList; +import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocationsListProperties; + +public final class SubscriptionQuotaAllocationsListImpl implements SubscriptionQuotaAllocationsList { + private SubscriptionQuotaAllocationsListInner innerObject; + + private final com.azure.resourcemanager.quota.QuotaManager serviceManager; + + SubscriptionQuotaAllocationsListImpl(SubscriptionQuotaAllocationsListInner innerObject, + com.azure.resourcemanager.quota.QuotaManager serviceManager) { + this.innerObject = innerObject; + this.serviceManager = serviceManager; + } + + public String id() { + return this.innerModel().id(); + } + + public String name() { + return this.innerModel().name(); + } + + public String type() { + return this.innerModel().type(); + } + + public SubscriptionQuotaAllocationsListProperties properties() { + return this.innerModel().properties(); + } + + public SystemData systemData() { + return this.innerModel().systemData(); + } + + public SubscriptionQuotaAllocationsListInner innerModel() { + return this.innerObject; + } + + private com.azure.resourcemanager.quota.QuotaManager manager() { + return this.serviceManager; + } +} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/AdditionalAttributes.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/AdditionalAttributes.java deleted file mode 100644 index 1d1634341876..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/AdditionalAttributes.java +++ /dev/null @@ -1,133 +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.resourcemanager.quota.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.util.logging.ClientLogger; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * Additional attribute or filter to allow subscriptions meeting the requirements to be part of the GroupQuota. - */ -@Fluent -public final class AdditionalAttributes implements JsonSerializable { - /* - * The grouping Id for the group quota. It can be Billing Id or ServiceTreeId if applicable. - */ - private GroupingId groupId; - - /* - * Environment name. - */ - private EnvironmentType environment; - - /** - * Creates an instance of AdditionalAttributes class. - */ - public AdditionalAttributes() { - } - - /** - * Get the groupId property: The grouping Id for the group quota. It can be Billing Id or ServiceTreeId if - * applicable. - * - * @return the groupId value. - */ - public GroupingId groupId() { - return this.groupId; - } - - /** - * Set the groupId property: The grouping Id for the group quota. It can be Billing Id or ServiceTreeId if - * applicable. - * - * @param groupId the groupId value to set. - * @return the AdditionalAttributes object itself. - */ - public AdditionalAttributes withGroupId(GroupingId groupId) { - this.groupId = groupId; - return this; - } - - /** - * Get the environment property: Environment name. - * - * @return the environment value. - */ - public EnvironmentType environment() { - return this.environment; - } - - /** - * Set the environment property: Environment name. - * - * @param environment the environment value to set. - * @return the AdditionalAttributes object itself. - */ - public AdditionalAttributes withEnvironment(EnvironmentType environment) { - this.environment = environment; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (groupId() == null) { - throw LOGGER.atError() - .log(new IllegalArgumentException("Missing required property groupId in model AdditionalAttributes")); - } else { - groupId().validate(); - } - } - - private static final ClientLogger LOGGER = new ClientLogger(AdditionalAttributes.class); - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeJsonField("groupId", this.groupId); - jsonWriter.writeStringField("environment", this.environment == null ? null : this.environment.toString()); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of AdditionalAttributes from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of AdditionalAttributes 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 AdditionalAttributes. - */ - public static AdditionalAttributes fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - AdditionalAttributes deserializedAdditionalAttributes = new AdditionalAttributes(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("groupId".equals(fieldName)) { - deserializedAdditionalAttributes.groupId = GroupingId.fromJson(reader); - } else if ("environment".equals(fieldName)) { - deserializedAdditionalAttributes.environment = EnvironmentType.fromString(reader.getString()); - } else { - reader.skipChildren(); - } - } - - return deserializedAdditionalAttributes; - }); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/AdditionalAttributesPatch.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/AdditionalAttributesPatch.java deleted file mode 100644 index e535c502a876..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/AdditionalAttributesPatch.java +++ /dev/null @@ -1,126 +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.resourcemanager.quota.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; - -/** - * Additional attribute or filter to allow subscriptions meeting the requirements to be part of the GroupQuota. - */ -@Fluent -public final class AdditionalAttributesPatch implements JsonSerializable { - /* - * The grouping Id for the group quota. It can be Billing Id or ServiceTreeId if applicable. - */ - private GroupingId groupId; - - /* - * Environment name. - */ - private EnvironmentType environment; - - /** - * Creates an instance of AdditionalAttributesPatch class. - */ - public AdditionalAttributesPatch() { - } - - /** - * Get the groupId property: The grouping Id for the group quota. It can be Billing Id or ServiceTreeId if - * applicable. - * - * @return the groupId value. - */ - public GroupingId groupId() { - return this.groupId; - } - - /** - * Set the groupId property: The grouping Id for the group quota. It can be Billing Id or ServiceTreeId if - * applicable. - * - * @param groupId the groupId value to set. - * @return the AdditionalAttributesPatch object itself. - */ - public AdditionalAttributesPatch withGroupId(GroupingId groupId) { - this.groupId = groupId; - return this; - } - - /** - * Get the environment property: Environment name. - * - * @return the environment value. - */ - public EnvironmentType environment() { - return this.environment; - } - - /** - * Set the environment property: Environment name. - * - * @param environment the environment value to set. - * @return the AdditionalAttributesPatch object itself. - */ - public AdditionalAttributesPatch withEnvironment(EnvironmentType environment) { - this.environment = environment; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (groupId() != null) { - groupId().validate(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeJsonField("groupId", this.groupId); - jsonWriter.writeStringField("environment", this.environment == null ? null : this.environment.toString()); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of AdditionalAttributesPatch from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of AdditionalAttributesPatch 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 AdditionalAttributesPatch. - */ - public static AdditionalAttributesPatch fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - AdditionalAttributesPatch deserializedAdditionalAttributesPatch = new AdditionalAttributesPatch(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("groupId".equals(fieldName)) { - deserializedAdditionalAttributesPatch.groupId = GroupingId.fromJson(reader); - } else if ("environment".equals(fieldName)) { - deserializedAdditionalAttributesPatch.environment = EnvironmentType.fromString(reader.getString()); - } else { - reader.skipChildren(); - } - } - - return deserializedAdditionalAttributesPatch; - }); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/EnforcementState.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/EnforcementState.java deleted file mode 100644 index 1d41b4a14830..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/EnforcementState.java +++ /dev/null @@ -1,56 +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.resourcemanager.quota.models; - -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * Enforcement status. - */ -public final class EnforcementState extends ExpandableStringEnum { - /** - * Static value Enabled for EnforcementState. - */ - public static final EnforcementState ENABLED = fromString("Enabled"); - - /** - * Static value Disabled for EnforcementState. - */ - public static final EnforcementState DISABLED = fromString("Disabled"); - - /** - * Static value NotAvailable for EnforcementState. - */ - public static final EnforcementState NOT_AVAILABLE = fromString("NotAvailable"); - - /** - * Creates a new instance of EnforcementState value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Deprecated - public EnforcementState() { - } - - /** - * Creates or finds a EnforcementState from its string representation. - * - * @param name a name to look for. - * @return the corresponding EnforcementState. - */ - public static EnforcementState fromString(String name) { - return fromString(name, EnforcementState.class); - } - - /** - * Gets known EnforcementState values. - * - * @return known EnforcementState values. - */ - public static Collection values() { - return values(EnforcementState.class); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaDetails.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaDetails.java index 37d804cc4087..41f0e58f9081 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaDetails.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaDetails.java @@ -16,11 +16,11 @@ * Group Quota details. */ @Fluent -public final class GroupQuotaDetails implements JsonSerializable { +public class GroupQuotaDetails implements JsonSerializable { /* - * Location/Azure region for the quota requested for resource. + * The resource name, such as SKU name. */ - private String region; + private String resourceName; /* * The current Group Quota Limit at the parentId level. @@ -32,18 +32,18 @@ public final class GroupQuotaDetails implements JsonSerializable { + /* + * Group Quota properties for the specified resource. + */ + private GroupQuotaLimitProperties properties; + /** - * Gets the id property: Fully qualified resource Id for the resource. - * - * @return the id value. + * Creates an instance of GroupQuotaLimit class. */ - String id(); + public GroupQuotaLimit() { + } /** - * Gets the name property: The name of the resource. + * Get the properties property: Group Quota properties for the specified resource. * - * @return the name value. + * @return the properties value. */ - String name(); + public GroupQuotaLimitProperties properties() { + return this.properties; + } /** - * Gets the type property: The type of the resource. + * Set the properties property: Group Quota properties for the specified resource. * - * @return the type value. + * @param properties the properties value to set. + * @return the GroupQuotaLimit object itself. */ - String type(); + public GroupQuotaLimit withProperties(GroupQuotaLimitProperties properties) { + this.properties = properties; + return this; + } /** - * Gets the properties property: Group Quota properties for the specified resource. + * Validates the instance. * - * @return the properties value. + * @throws IllegalArgumentException thrown if the instance is not valid. */ - GroupQuotaDetails properties(); + public void validate() { + if (properties() != null) { + properties().validate(); + } + } /** - * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. - * - * @return the systemData value. + * {@inheritDoc} */ - SystemData systemData(); + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } /** - * Gets the inner com.azure.resourcemanager.quota.fluent.models.GroupQuotaLimitInner object. + * Reads an instance of GroupQuotaLimit from the JsonReader. * - * @return the inner object. + * @param jsonReader The JsonReader being read. + * @return An instance of GroupQuotaLimit 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 GroupQuotaLimit. */ - GroupQuotaLimitInner innerModel(); + public static GroupQuotaLimit fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + GroupQuotaLimit deserializedGroupQuotaLimit = new GroupQuotaLimit(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("properties".equals(fieldName)) { + deserializedGroupQuotaLimit.properties = GroupQuotaLimitProperties.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedGroupQuotaLimit; + }); + } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaLimitList.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaLimitList.java index 46978bc53ed7..e97ec8df7e47 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaLimitList.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaLimitList.java @@ -4,113 +4,52 @@ package com.azure.resourcemanager.quota.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.resourcemanager.quota.fluent.models.GroupQuotaLimitInner; -import java.io.IOException; -import java.util.List; +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.quota.fluent.models.GroupQuotaLimitListInner; /** - * List of Group Quota Limit details. + * An immutable client-side representation of GroupQuotaLimitList. */ -@Fluent -public final class GroupQuotaLimitList implements JsonSerializable { - /* - * List of Group Quota Limit details. - */ - private List value; - - /* - * The URL to use for getting the next set of results. - */ - private String nextLink; - - /** - * Creates an instance of GroupQuotaLimitList class. - */ - public GroupQuotaLimitList() { - } - +public interface GroupQuotaLimitList { /** - * Get the value property: List of Group Quota Limit details. + * Gets the id property: Fully qualified resource Id for the resource. * - * @return the value value. + * @return the id value. */ - public List value() { - return this.value; - } + String id(); /** - * Set the value property: List of Group Quota Limit details. + * Gets the name property: The name of the resource. * - * @param value the value value to set. - * @return the GroupQuotaLimitList object itself. + * @return the name value. */ - public GroupQuotaLimitList withValue(List value) { - this.value = value; - return this; - } + String name(); /** - * Get the nextLink property: The URL to use for getting the next set of results. + * Gets the type property: The type of the resource. * - * @return the nextLink value. + * @return the type value. */ - public String nextLink() { - return this.nextLink; - } + String type(); /** - * Validates the instance. + * Gets the properties property: The properties property. * - * @throws IllegalArgumentException thrown if the instance is not valid. + * @return the properties value. */ - public void validate() { - if (value() != null) { - value().forEach(e -> e.validate()); - } - } + GroupQuotaLimitListProperties properties(); /** - * {@inheritDoc} + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); - return jsonWriter.writeEndObject(); - } + SystemData systemData(); /** - * Reads an instance of GroupQuotaLimitList from the JsonReader. + * Gets the inner com.azure.resourcemanager.quota.fluent.models.GroupQuotaLimitListInner object. * - * @param jsonReader The JsonReader being read. - * @return An instance of GroupQuotaLimitList 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 GroupQuotaLimitList. + * @return the inner object. */ - public static GroupQuotaLimitList fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - GroupQuotaLimitList deserializedGroupQuotaLimitList = new GroupQuotaLimitList(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - List value - = reader.readArray(reader1 -> GroupQuotaLimitInner.fromJson(reader1)); - deserializedGroupQuotaLimitList.value = value; - } else if ("nextLink".equals(fieldName)) { - deserializedGroupQuotaLimitList.nextLink = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedGroupQuotaLimitList; - }); - } + GroupQuotaLimitListInner innerModel(); } diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaLimitListProperties.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaLimitListProperties.java new file mode 100644 index 000000000000..e0b2723239d0 --- /dev/null +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaLimitListProperties.java @@ -0,0 +1,132 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.quota.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.List; + +/** + * The GroupQuotaLimitListProperties model. + */ +@Fluent +public final class GroupQuotaLimitListProperties implements JsonSerializable { + /* + * Request status. + */ + private RequestState provisioningState; + + /* + * List of Group Quota Limit details. + */ + private List value; + + /* + * The URL to use for getting the next set of results. + */ + private String nextLink; + + /** + * Creates an instance of GroupQuotaLimitListProperties class. + */ + public GroupQuotaLimitListProperties() { + } + + /** + * Get the provisioningState property: Request status. + * + * @return the provisioningState value. + */ + public RequestState provisioningState() { + return this.provisioningState; + } + + /** + * Get the value property: List of Group Quota Limit details. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Set the value property: List of Group Quota Limit details. + * + * @param value the value value to set. + * @return the GroupQuotaLimitListProperties object itself. + */ + public GroupQuotaLimitListProperties withValue(List value) { + this.value = value; + return this; + } + + /** + * Get the nextLink property: The URL to use for getting the next set of results. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() != null) { + value().forEach(e -> e.validate()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of GroupQuotaLimitListProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of GroupQuotaLimitListProperties 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 GroupQuotaLimitListProperties. + */ + public static GroupQuotaLimitListProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + GroupQuotaLimitListProperties deserializedGroupQuotaLimitListProperties + = new GroupQuotaLimitListProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("provisioningState".equals(fieldName)) { + deserializedGroupQuotaLimitListProperties.provisioningState + = RequestState.fromString(reader.getString()); + } else if ("value".equals(fieldName)) { + List value = reader.readArray(reader1 -> GroupQuotaLimit.fromJson(reader1)); + deserializedGroupQuotaLimitListProperties.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedGroupQuotaLimitListProperties.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedGroupQuotaLimitListProperties; + }); + } +} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaLimitProperties.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaLimitProperties.java new file mode 100644 index 000000000000..ab7057edefc8 --- /dev/null +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaLimitProperties.java @@ -0,0 +1,199 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.quota.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.resourcemanager.quota.fluent.models.GroupQuotaDetailsName; +import java.io.IOException; + +/** + * Group Quota properties for the specified resource. + */ +@Fluent +public final class GroupQuotaLimitProperties extends GroupQuotaDetails { + /* + * Quota allocated to subscriptions + */ + private AllocatedQuotaToSubscriptionList allocatedToSubscriptions; + + /* + * The available Group Quota Limit at the MG level. This Group quota can be allocated to subscription(s). + */ + private Long availableLimit; + + /* + * Name of the resource provided by the resource provider. This property is already included in the request URI, so + * it is a readonly property returned in the response. + */ + private GroupQuotaDetailsName innerName; + + /* + * The usages units, such as Count and Bytes. When requesting quota, use the **unit** value returned in the GET + * response in the request body of your PUT operation. + */ + private String unit; + + /** + * Creates an instance of GroupQuotaLimitProperties class. + */ + public GroupQuotaLimitProperties() { + } + + /** + * Get the allocatedToSubscriptions property: Quota allocated to subscriptions. + * + * @return the allocatedToSubscriptions value. + */ + @Override + public AllocatedQuotaToSubscriptionList allocatedToSubscriptions() { + return this.allocatedToSubscriptions; + } + + /** + * Get the availableLimit property: The available Group Quota Limit at the MG level. This Group quota can be + * allocated to subscription(s). + * + * @return the availableLimit value. + */ + @Override + public Long availableLimit() { + return this.availableLimit; + } + + /** + * Get the innerName property: Name of the resource provided by the resource provider. This property is already + * included in the request URI, so it is a readonly property returned in the response. + * + * @return the innerName value. + */ + private GroupQuotaDetailsName innerName() { + return this.innerName; + } + + /** + * Get the unit property: The usages units, such as Count and Bytes. When requesting quota, use the **unit** value + * returned in the GET response in the request body of your PUT operation. + * + * @return the unit value. + */ + @Override + public String unit() { + return this.unit; + } + + /** + * {@inheritDoc} + */ + @Override + public GroupQuotaLimitProperties withResourceName(String resourceName) { + super.withResourceName(resourceName); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public GroupQuotaLimitProperties withLimit(Long limit) { + super.withLimit(limit); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public GroupQuotaLimitProperties withComment(String comment) { + super.withComment(comment); + return this; + } + + /** + * Get the value property: Resource name. + * + * @return the value value. + */ + public String value() { + return this.innerName() == null ? null : this.innerName().value(); + } + + /** + * Get the localizedValue property: Resource display name. + * + * @return the localizedValue value. + */ + public String localizedValue() { + return this.innerName() == null ? null : this.innerName().localizedValue(); + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + @Override + public void validate() { + if (innerName() != null) { + innerName().validate(); + } + if (allocatedToSubscriptions() != null) { + allocatedToSubscriptions().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceName", resourceName()); + jsonWriter.writeNumberField("limit", limit()); + jsonWriter.writeStringField("comment", comment()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of GroupQuotaLimitProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of GroupQuotaLimitProperties 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 GroupQuotaLimitProperties. + */ + public static GroupQuotaLimitProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + GroupQuotaLimitProperties deserializedGroupQuotaLimitProperties = new GroupQuotaLimitProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceName".equals(fieldName)) { + deserializedGroupQuotaLimitProperties.withResourceName(reader.getString()); + } else if ("limit".equals(fieldName)) { + deserializedGroupQuotaLimitProperties.withLimit(reader.getNullable(JsonReader::getLong)); + } else if ("comment".equals(fieldName)) { + deserializedGroupQuotaLimitProperties.withComment(reader.getString()); + } else if ("unit".equals(fieldName)) { + deserializedGroupQuotaLimitProperties.unit = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedGroupQuotaLimitProperties.innerName = GroupQuotaDetailsName.fromJson(reader); + } else if ("availableLimit".equals(fieldName)) { + deserializedGroupQuotaLimitProperties.availableLimit = reader.getNullable(JsonReader::getLong); + } else if ("allocatedToSubscriptions".equals(fieldName)) { + deserializedGroupQuotaLimitProperties.allocatedToSubscriptions + = AllocatedQuotaToSubscriptionList.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedGroupQuotaLimitProperties; + }); + } +} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaLimits.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaLimits.java index 571c729e2e5d..2c4294864350 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaLimits.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaLimits.java @@ -4,7 +4,6 @@ package com.azure.resourcemanager.quota.models; -import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.Response; import com.azure.core.util.Context; @@ -13,109 +12,39 @@ */ public interface GroupQuotaLimits { /** - * Gets the GroupQuotaLimits for the specific resource. - * - * Gets the GroupQuotaLimits for the specific resource for a specific resource based on the resourceProviders, - * resourceName and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota. + * Gets the GroupQuotaLimits for the specified resource provider and location for resource names passed in + * $filter=resourceName eq {SKU}. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. + * @param location The name of the Azure region. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotaLimits for the specific resource for a specific resource based on the resourceProviders, - * resourceName and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota along with - * {@link Response}. - */ - Response getWithResponse(String managementGroupId, String groupQuotaName, - String resourceProviderName, String resourceName, String filter, Context context); - - /** - * Gets the GroupQuotaLimits for the specific resource. - * - * Gets the GroupQuotaLimits for the specific resource for a specific resource based on the resourceProviders, - * resourceName and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotaLimits for the specific resource for a specific resource based on the resourceProviders, - * resourceName and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota. + * @return the GroupQuotaLimits for the specified resource provider and location for resource names passed in + * $filter=resourceName eq {SKU} along with {@link Response}. */ - GroupQuotaLimit get(String managementGroupId, String groupQuotaName, String resourceProviderName, - String resourceName, String filter); + Response listWithResponse(String managementGroupId, String groupQuotaName, + String resourceProviderName, String location, Context context); /** - * Gets the GroupQuotaLimits for all the resources for the specified location in $filter=location eq {location}. - * - * Gets the GroupQuotaLimits for the all resource for a specific resourceProvider and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota. + * Gets the GroupQuotaLimits for the specified resource provider and location for resource names passed in + * $filter=resourceName eq {SKU}. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotaLimits for the all resource for a specific resourceProvider and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota as paginated response - * with {@link PagedIterable}. - */ - PagedIterable list(String managementGroupId, String groupQuotaName, String resourceProviderName, - String filter); - - /** - * Gets the GroupQuotaLimits for all the resources for the specified location in $filter=location eq {location}. - * - * Gets the GroupQuotaLimits for the all resource for a specific resourceProvider and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. - * @param context The context to associate with this operation. + * @param location The name of the Azure region. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotaLimits for the all resource for a specific resourceProvider and $filter passed. - * The $filter=location eq {location} is required to location specific resources groupQuota as paginated response - * with {@link PagedIterable}. + * @return the GroupQuotaLimits for the specified resource provider and location for resource names passed in + * $filter=resourceName eq {SKU}. */ - PagedIterable list(String managementGroupId, String groupQuotaName, String resourceProviderName, - String filter, Context context); + GroupQuotaLimitList list(String managementGroupId, String groupQuotaName, String resourceProviderName, + String location); } diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaLimitsRequests.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaLimitsRequests.java index a35169769764..44a14a592049 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaLimitsRequests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaLimitsRequests.java @@ -6,68 +6,19 @@ import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.Response; -import com.azure.core.management.ProxyResource; import com.azure.core.util.Context; -import com.azure.resourcemanager.quota.fluent.models.SubmittedResourceRequestStatusInner; +import com.azure.resourcemanager.quota.fluent.models.GroupQuotaLimitListInner; /** * Resource collection API of GroupQuotaLimitsRequests. */ public interface GroupQuotaLimitsRequests { - /** - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. - * - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * ("name": {"value" : "resourceName") properties are specified in the request body. Only 1 resource quota can be - * requested. - * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after - * duration in seconds to check the intermediate status. This API provides the finals status with the request - * details and status. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return status of a single GroupQuota request. - */ - ProxyResource createOrUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, - String resourceName); - - /** - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. - * - * Put the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * ("name": {"value" : "resourceName") properties are specified in the request body. Only 1 resource quota can be - * requested. - * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after - * duration in seconds to check the intermediate status. This API provides the finals status with the request - * details and status. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param groupQuotaRequest The GroupQuotaRequest body details for specific resourceProvider/location/resources. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return status of a single GroupQuota request. - */ - ProxyResource createOrUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, - String resourceName, SubmittedResourceRequestStatusInner groupQuotaRequest, Context context); - /** * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. * - * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * properties are specified in the request body. Only 1 resource quota can be requested. Please note that patch - * request creates a new groupQuota request. + * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. The resourceName properties are + * specified in the request body. Only 1 resource quota can be requested. Please note that patch request creates a + * new groupQuota request. * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after * duration in seconds to check the intermediate status. This API provides the finals status with the request * details and status. @@ -76,21 +27,21 @@ ProxyResource createOrUpdate(String managementGroupId, String groupQuotaName, St * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. + * @param location The name of the Azure region. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return status of a single GroupQuota request. + * @return list of Group Quota Limit details. */ - SubmittedResourceRequestStatus update(String managementGroupId, String groupQuotaName, String resourceProviderName, - String resourceName); + GroupQuotaLimitList update(String managementGroupId, String groupQuotaName, String resourceProviderName, + String location); /** * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. * - * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. the location and resourceName - * properties are specified in the request body. Only 1 resource quota can be requested. Please note that patch - * request creates a new groupQuota request. + * Create the GroupQuota requests for a specific ResourceProvider/Location/Resource. The resourceName properties are + * specified in the request body. Only 1 resource quota can be requested. Please note that patch request creates a + * new groupQuota request. * Use the polling API - OperationsStatus URI specified in Azure-AsyncOperation header field, with retry-after * duration in seconds to check the intermediate status. This API provides the finals status with the request * details and status. @@ -99,16 +50,16 @@ SubmittedResourceRequestStatus update(String managementGroupId, String groupQuot * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. + * @param location The name of the Azure region. * @param groupQuotaRequest The GroupQuotaRequest body details for specific resourceProvider/location/resources. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return status of a single GroupQuota request. + * @return list of Group Quota Limit details. */ - SubmittedResourceRequestStatus update(String managementGroupId, String groupQuotaName, String resourceProviderName, - String resourceName, SubmittedResourceRequestStatusInner groupQuotaRequest, Context context); + GroupQuotaLimitList update(String managementGroupId, String groupQuotaName, String resourceProviderName, + String location, GroupQuotaLimitListInner groupQuotaRequest, Context context); /** * Get the status of a single GroupQuota request by requestId. diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaLocationSettings.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaLocationSettings.java deleted file mode 100644 index e947c6fc1f54..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaLocationSettings.java +++ /dev/null @@ -1,208 +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.resourcemanager.quota.models; - -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.Response; -import com.azure.core.management.ProxyResource; -import com.azure.core.util.Context; -import com.azure.resourcemanager.quota.fluent.models.GroupQuotasEnforcementResponseInner; - -/** - * Resource collection API of GroupQuotaLocationSettings. - */ -public interface GroupQuotaLocationSettings { - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuota Enforcement status for a Azure Location/Region. - */ - ProxyResource createOrUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, - String location); - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param locationSettings The GroupQuota body details for creation or update of a GroupQuota entity. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuota Enforcement status for a Azure Location/Region. - */ - ProxyResource createOrUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, - String location, GroupQuotasEnforcementResponseInner locationSettings, Context context); - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuota Enforcement status for a Azure Location/Region. - */ - GroupQuotasEnforcementResponse update(String managementGroupId, String groupQuotaName, String resourceProviderName, - String location); - - /** - * Enables the GroupQuotas enforcement settings for the resource provider and the location specified. - * - * Enables the GroupQuotas enforcement for the resource provider and the location specified. The resource provider - * will start using the group quotas as the overall quota for the subscriptions included in the GroupQuota. The - * subscriptions cannot request quota at subscription level. - * The subscriptions share the GroupQuotaLimits assigned to the GroupQuota. If the GroupQuotaLimits is used, then - * submit a groupQuotaLimit request for the specific resource - provider/location/resource. - * Once the GroupQuota Enforcement is enabled then, it cannot be deleted or reverted back. To disable GroupQuota - * Enforcement - - * 1. Remove all the subscriptions from the groupQuota using the delete API for Subscriptions (Check the example - - * GroupQuotaSubscriptions_Delete). - * 2. Ten delete the GroupQuota (Check the example - GroupQuotas_Delete). - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param locationSettings The GroupQuota body details for creation or update of a GroupQuota entity. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuota Enforcement status for a Azure Location/Region. - */ - GroupQuotasEnforcementResponse update(String managementGroupId, String groupQuotaName, String resourceProviderName, - String location, GroupQuotasEnforcementResponseInner locationSettings, Context context); - - /** - * Gets the GroupQuotas enforcement settings for the resource provider/location. - * - * Gets the GroupQuotas enforcement settings for the ResourceProvider/location. The locations, where GroupQuota - * enforcement is not enabled will return Not Found. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotas enforcement settings for the ResourceProvider/location along with {@link Response}. - */ - Response getWithResponse(String managementGroupId, String groupQuotaName, - String resourceProviderName, String location, Context context); - - /** - * Gets the GroupQuotas enforcement settings for the resource provider/location. - * - * Gets the GroupQuotas enforcement settings for the ResourceProvider/location. The locations, where GroupQuota - * enforcement is not enabled will return Not Found. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotas enforcement settings for the ResourceProvider/location. - */ - GroupQuotasEnforcementResponse get(String managementGroupId, String groupQuotaName, String resourceProviderName, - String location); - - /** - * Returns a list of the Azure regions settings, where the GroupQuotas enforcement is enabled. - * - * Returns only the list of the Azure regions settings, where the GroupQuotas enforcement is enabled. The locations - * not included in GroupQuota Enforcement will not be listed, the regions in failed status with listed as status - * Failed. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return list of Azure regions, where the group quotas is enabled for enforcement as paginated response with - * {@link PagedIterable}. - */ - PagedIterable list(String managementGroupId, String groupQuotaName, - String resourceProviderName); - - /** - * Returns a list of the Azure regions settings, where the GroupQuotas enforcement is enabled. - * - * Returns only the list of the Azure regions settings, where the GroupQuotas enforcement is enabled. The locations - * not included in GroupQuota Enforcement will not be listed, the regions in failed status with listed as status - * Failed. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return list of Azure regions, where the group quotas is enabled for enforcement as paginated response with - * {@link PagedIterable}. - */ - PagedIterable list(String managementGroupId, String groupQuotaName, - String resourceProviderName, Context context); -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaSubscriptionAllocationRequests.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaSubscriptionAllocationRequests.java index d2fcc49c72c3..6fd89a263548 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaSubscriptionAllocationRequests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaSubscriptionAllocationRequests.java @@ -6,14 +6,63 @@ import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.Response; -import com.azure.core.management.ProxyResource; import com.azure.core.util.Context; -import com.azure.resourcemanager.quota.fluent.models.QuotaAllocationRequestStatusInner; +import com.azure.resourcemanager.quota.fluent.models.SubscriptionQuotaAllocationsListInner; /** * Resource collection API of GroupQuotaSubscriptionAllocationRequests. */ public interface GroupQuotaSubscriptionAllocationRequests { + /** + * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern + * with 202 response and status polling API. + * + * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or + * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. + * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can + * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple + * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. + * + * @param managementGroupId Management Group Id. + * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. + * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only + * Microsoft.Compute resource provider supports this API. + * @param location The name of the Azure region. + * @param allocateQuotaRequest Quota requests payload. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return subscription quota list. + */ + SubscriptionQuotaAllocationsList update(String managementGroupId, String groupQuotaName, + String resourceProviderName, String location, SubscriptionQuotaAllocationsListInner allocateQuotaRequest); + + /** + * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern + * with 202 response and status polling API. + * + * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or + * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. + * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can + * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple + * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. + * + * @param managementGroupId Management Group Id. + * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. + * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only + * Microsoft.Compute resource provider supports this API. + * @param location The name of the Azure region. + * @param allocateQuotaRequest Quota requests payload. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return subscription quota list. + */ + SubscriptionQuotaAllocationsList update(String managementGroupId, String groupQuotaName, + String resourceProviderName, String location, SubscriptionQuotaAllocationsListInner allocateQuotaRequest, + Context context); + /** * Get the status of the quota allocation request for the subscriptionId. * @@ -21,6 +70,8 @@ public interface GroupQuotaSubscriptionAllocationRequests { * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. + * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only + * Microsoft.Compute resource provider supports this API. * @param allocationId Request Id. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -29,7 +80,7 @@ public interface GroupQuotaSubscriptionAllocationRequests { * @return the quota allocation request status for the subscriptionId by allocationId along with {@link Response}. */ Response getWithResponse(String managementGroupId, String groupQuotaName, - String allocationId, Context context); + String resourceProviderName, String allocationId, Context context); /** * Get the status of the quota allocation request for the subscriptionId. @@ -38,13 +89,16 @@ Response getWithResponse(String managementGroupId, * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. + * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only + * Microsoft.Compute resource provider supports this API. * @param allocationId Request Id. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the quota allocation request status for the subscriptionId by allocationId. */ - QuotaAllocationRequestStatus get(String managementGroupId, String groupQuotaName, String allocationId); + QuotaAllocationRequestStatus get(String managementGroupId, String groupQuotaName, String resourceProviderName, + String allocationId); /** * Get all the quotaAllocationRequests for a resourceProvider/location. @@ -94,102 +148,4 @@ PagedIterable list(String managementGroupId, Strin */ PagedIterable list(String managementGroupId, String groupQuotaName, String resourceProviderName, String filter, Context context); - - /** - * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * to check the status using Async polling as standards defined at - - * https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/async-api-reference.md#asynchronous-operations. - * - * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or - * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. - * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param allocateQuotaRequest Quota requests payload. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the subscription quota allocation status. - */ - ProxyResource createOrUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, - String resourceName, QuotaAllocationRequestStatusInner allocateQuotaRequest); - - /** - * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * to check the status using Async polling as standards defined at - - * https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/async-api-reference.md#asynchronous-operations. - * - * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or - * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. - * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param allocateQuotaRequest Quota requests payload. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the subscription quota allocation status. - */ - ProxyResource createOrUpdate(String managementGroupId, String groupQuotaName, String resourceProviderName, - String resourceName, QuotaAllocationRequestStatusInner allocateQuotaRequest, Context context); - - /** - * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * with 202 response and status polling API. - * - * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or - * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. - * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple - * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param allocateQuotaRequest Quota requests payload. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the subscription quota allocation status. - */ - QuotaAllocationRequestStatus update(String managementGroupId, String groupQuotaName, String resourceProviderName, - String resourceName, QuotaAllocationRequestStatusInner allocateQuotaRequest); - - /** - * Request to assign quota from group quota to a specific Subscription. This request will use Asynchronous pattern - * with 202 response and status polling API. - * - * Request to assign quota from group quota to a specific Subscription. The assign GroupQuota to subscriptions or - * reduce the quota allocated to subscription to give back the unused quota ( quota >= usages) to the groupQuota. - * So, this API can be used to assign Quota to subscriptions and assign back unused quota to group quota, which can - * be assigned to another subscriptions in the GroupQuota. User can collect unused quotas from multiple - * subscriptions within the groupQuota and assign the groupQuota to the subscription, where it's needed. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param resourceName Resource name. - * @param allocateQuotaRequest Quota requests payload. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the subscription quota allocation status. - */ - QuotaAllocationRequestStatus update(String managementGroupId, String groupQuotaName, String resourceProviderName, - String resourceName, QuotaAllocationRequestStatusInner allocateQuotaRequest, Context context); } diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaSubscriptionAllocations.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaSubscriptionAllocations.java index 2924678b0d65..ef1f21ea4839 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaSubscriptionAllocations.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaSubscriptionAllocations.java @@ -4,7 +4,6 @@ package com.azure.resourcemanager.quota.models; -import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.Response; import com.azure.core.util.Context; @@ -13,98 +12,47 @@ */ public interface GroupQuotaSubscriptionAllocations { /** - * Gets all the quota allocated to a subscription for the specific Resource Provider, Location. + * Gets all the quota allocated to a subscription for the specified resource provider and location for resource + * names passed in $filter=resourceName eq {SKU}. * - * Gets all the quota allocated to a subscription for the specific Resource Provider, Location. This will include - * the GroupQuota and total quota allocated to the subscription. Only the Group quota allocated to the subscription - * can be allocated back to the MG Group Quota. Use the $filter parameter to filter out the specific resource based - * on the ResourceProvider/Location. $filter is a required parameter. + * Gets all the quota allocated to a subscription for the specified resource provider and location for resource + * names passed in $filter=resourceName eq {SKU}. This will include the GroupQuota and total quota allocated to the + * subscription. Only the Group quota allocated to the subscription can be allocated back to the MG Group Quota. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all the quota allocated to a subscription for the specific Resource Provider, Location as paginated - * response with {@link PagedIterable}. - */ - PagedIterable list(String managementGroupId, String groupQuotaName, String filter); - - /** - * Gets all the quota allocated to a subscription for the specific Resource Provider, Location. - * - * Gets all the quota allocated to a subscription for the specific Resource Provider, Location. This will include - * the GroupQuota and total quota allocated to the subscription. Only the Group quota allocated to the subscription - * can be allocated back to the MG Group Quota. Use the $filter parameter to filter out the specific resource based - * on the ResourceProvider/Location. $filter is a required parameter. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. + * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only + * Microsoft.Compute resource provider supports this API. + * @param location The name of the Azure region. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all the quota allocated to a subscription for the specific Resource Provider, Location as paginated - * response with {@link PagedIterable}. + * @return all the quota allocated to a subscription for the specified resource provider and location for resource + * names passed in $filter=resourceName eq {SKU} along with {@link Response}. */ - PagedIterable list(String managementGroupId, String groupQuotaName, String filter, - Context context); + Response listWithResponse(String managementGroupId, String groupQuotaName, + String resourceProviderName, String location, Context context); /** - * Gets Quota allocated to a subscription for the specific Resource Provider, Location, ResourceName. + * Gets all the quota allocated to a subscription for the specified resource provider and location for resource + * names passed in $filter=resourceName eq {SKU}. * - * Gets Quota allocated to a subscription for the specific Resource Provider, Location, ResourceName. This will - * include the GroupQuota and total quota allocated to the subscription. Only the Group quota allocated to the - * subscription can be allocated back to the MG Group Quota. + * Gets all the quota allocated to a subscription for the specified resource provider and location for resource + * names passed in $filter=resourceName eq {SKU}. This will include the GroupQuota and total quota allocated to the + * subscription. Only the Group quota allocated to the subscription can be allocated back to the MG Group Quota. * * @param managementGroupId Management Group Id. * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceName Resource name. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return quota allocated to a subscription for the specific Resource Provider, Location, ResourceName along with - * {@link Response}. - */ - Response getWithResponse(String managementGroupId, String groupQuotaName, - String resourceName, String filter, Context context); - - /** - * Gets Quota allocated to a subscription for the specific Resource Provider, Location, ResourceName. - * - * Gets Quota allocated to a subscription for the specific Resource Provider, Location, ResourceName. This will - * include the GroupQuota and total quota allocated to the subscription. Only the Group quota allocated to the - * subscription can be allocated back to the MG Group Quota. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceName Resource name. - * @param filter | Field | Supported operators - * |---------------------|------------------------ - * - * location eq {location} - * Example: $filter=location eq eastus. + * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only + * Microsoft.Compute resource provider supports this API. + * @param location The name of the Azure region. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return quota allocated to a subscription for the specific Resource Provider, Location, ResourceName. + * @return all the quota allocated to a subscription for the specified resource provider and location for resource + * names passed in $filter=resourceName eq {SKU}. */ - SubscriptionQuotaAllocations get(String managementGroupId, String groupQuotaName, String resourceName, - String filter); + SubscriptionQuotaAllocationsList list(String managementGroupId, String groupQuotaName, String resourceProviderName, + String location); } diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaSubscriptionIdProperties.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaSubscriptionIdProperties.java index 4046fff0b961..3630e952c77a 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaSubscriptionIdProperties.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaSubscriptionIdProperties.java @@ -4,7 +4,7 @@ package com.azure.resourcemanager.quota.models; -import com.azure.core.annotation.Immutable; +import com.azure.core.annotation.Fluent; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -14,7 +14,7 @@ /** * The GroupQuotaSubscriptionIdProperties model. */ -@Immutable +@Fluent public final class GroupQuotaSubscriptionIdProperties implements JsonSerializable { /* * An Azure subscriptionId. @@ -41,6 +41,17 @@ public String subscriptionId() { return this.subscriptionId; } + /** + * Set the subscriptionId property: An Azure subscriptionId. + * + * @param subscriptionId the subscriptionId value to set. + * @return the GroupQuotaSubscriptionIdProperties object itself. + */ + public GroupQuotaSubscriptionIdProperties withSubscriptionId(String subscriptionId) { + this.subscriptionId = subscriptionId; + return this; + } + /** * Get the provisioningState property: Status of this subscriptionId being associated with the GroupQuotasEntity. * @@ -64,6 +75,7 @@ public void validate() { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("subscriptionId", this.subscriptionId); return jsonWriter.writeEndObject(); } diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaUsages.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaUsages.java deleted file mode 100644 index 91c176de4ee8..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaUsages.java +++ /dev/null @@ -1,50 +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.resourcemanager.quota.models; - -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.util.Context; - -/** - * Resource collection API of GroupQuotaUsages. - */ -public interface GroupQuotaUsages { - /** - * Gets the GroupQuotas usages and limits(quota) for the resourceProvider/location. - * - * Gets the GroupQuotas usages and limits(quota). Location is required paramter. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotas usages and limits(quota) as paginated response with {@link PagedIterable}. - */ - PagedIterable list(String managementGroupId, String groupQuotaName, String resourceProviderName, - String location); - - /** - * Gets the GroupQuotas usages and limits(quota) for the resourceProvider/location. - * - * Gets the GroupQuotas usages and limits(quota). Location is required paramter. - * - * @param managementGroupId Management Group Id. - * @param groupQuotaName The GroupQuota name. The name should be unique for the provided context tenantId/MgId. - * @param resourceProviderName The resource provider name, such as - Microsoft.Compute. Currently only - * Microsoft.Compute resource provider supports this API. - * @param location The name of the Azure region. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the GroupQuotas usages and limits(quota) as paginated response with {@link PagedIterable}. - */ - PagedIterable list(String managementGroupId, String groupQuotaName, String resourceProviderName, - String location, Context context); -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaUsagesBase.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaUsagesBase.java deleted file mode 100644 index da498d0e0e75..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotaUsagesBase.java +++ /dev/null @@ -1,197 +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.resourcemanager.quota.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.resourcemanager.quota.fluent.models.GroupQuotaUsagesBaseName; -import java.io.IOException; - -/** - * Resource details with usages and GroupQuota. - */ -@Fluent -public final class GroupQuotaUsagesBase implements JsonSerializable { - /* - * Name of the resource provided by the resource provider. This property is already included in the request URI, so - * it is a readonly property returned in the response. - */ - private GroupQuotaUsagesBaseName innerName; - - /* - * Quota/limits for the resource. - */ - private Long limit; - - /* - * Usages for the resource. - */ - private Long usages; - - /* - * Representing the units of the usage quota. Possible values are: Count, Bytes, Seconds, Percent, CountPerSecond, - * BytesPerSecond. Based on - https://armwiki.azurewebsites.net/api_contracts/UsagesAPIContract.html?q=usages . - * Different RPs may have different units, Count, type as int64 should work for most of the integer values. - */ - private String unit; - - /** - * Creates an instance of GroupQuotaUsagesBase class. - */ - public GroupQuotaUsagesBase() { - } - - /** - * Get the innerName property: Name of the resource provided by the resource provider. This property is already - * included in the request URI, so it is a readonly property returned in the response. - * - * @return the innerName value. - */ - private GroupQuotaUsagesBaseName innerName() { - return this.innerName; - } - - /** - * Get the limit property: Quota/limits for the resource. - * - * @return the limit value. - */ - public Long limit() { - return this.limit; - } - - /** - * Set the limit property: Quota/limits for the resource. - * - * @param limit the limit value to set. - * @return the GroupQuotaUsagesBase object itself. - */ - public GroupQuotaUsagesBase withLimit(Long limit) { - this.limit = limit; - return this; - } - - /** - * Get the usages property: Usages for the resource. - * - * @return the usages value. - */ - public Long usages() { - return this.usages; - } - - /** - * Set the usages property: Usages for the resource. - * - * @param usages the usages value to set. - * @return the GroupQuotaUsagesBase object itself. - */ - public GroupQuotaUsagesBase withUsages(Long usages) { - this.usages = usages; - return this; - } - - /** - * Get the unit property: Representing the units of the usage quota. Possible values are: Count, Bytes, Seconds, - * Percent, CountPerSecond, BytesPerSecond. Based on - - * https://armwiki.azurewebsites.net/api_contracts/UsagesAPIContract.html?q=usages . Different RPs may have - * different units, Count, type as int64 should work for most of the integer values. - * - * @return the unit value. - */ - public String unit() { - return this.unit; - } - - /** - * Get the value property: Resource name. - * - * @return the value value. - */ - public String value() { - return this.innerName() == null ? null : this.innerName().value(); - } - - /** - * Set the value property: Resource name. - * - * @param value the value value to set. - * @return the GroupQuotaUsagesBase object itself. - */ - public GroupQuotaUsagesBase withValue(String value) { - if (this.innerName() == null) { - this.innerName = new GroupQuotaUsagesBaseName(); - } - this.innerName().withValue(value); - return this; - } - - /** - * Get the localizedValue property: Resource display name. - * - * @return the localizedValue value. - */ - public String localizedValue() { - return this.innerName() == null ? null : this.innerName().localizedValue(); - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (innerName() != null) { - innerName().validate(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeJsonField("name", this.innerName); - jsonWriter.writeNumberField("limit", this.limit); - jsonWriter.writeNumberField("usages", this.usages); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of GroupQuotaUsagesBase from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of GroupQuotaUsagesBase 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 GroupQuotaUsagesBase. - */ - public static GroupQuotaUsagesBase fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - GroupQuotaUsagesBase deserializedGroupQuotaUsagesBase = new GroupQuotaUsagesBase(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("name".equals(fieldName)) { - deserializedGroupQuotaUsagesBase.innerName = GroupQuotaUsagesBaseName.fromJson(reader); - } else if ("limit".equals(fieldName)) { - deserializedGroupQuotaUsagesBase.limit = reader.getNullable(JsonReader::getLong); - } else if ("usages".equals(fieldName)) { - deserializedGroupQuotaUsagesBase.usages = reader.getNullable(JsonReader::getLong); - } else if ("unit".equals(fieldName)) { - deserializedGroupQuotaUsagesBase.unit = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedGroupQuotaUsagesBase; - }); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEnforcementListResponse.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEnforcementListResponse.java deleted file mode 100644 index 77a45b7bc65d..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEnforcementListResponse.java +++ /dev/null @@ -1,117 +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.resourcemanager.quota.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.resourcemanager.quota.fluent.models.GroupQuotasEnforcementResponseInner; -import java.io.IOException; -import java.util.List; - -/** - * List of Azure regions, where the group quotas is enabled for enforcement. - */ -@Fluent -public final class GroupQuotasEnforcementListResponse implements JsonSerializable { - /* - * List of Azure Regions. - */ - private List value; - - /* - * The URL to use for getting the next set of results. - */ - private String nextLink; - - /** - * Creates an instance of GroupQuotasEnforcementListResponse class. - */ - public GroupQuotasEnforcementListResponse() { - } - - /** - * Get the value property: List of Azure Regions. - * - * @return the value value. - */ - public List value() { - return this.value; - } - - /** - * Set the value property: List of Azure Regions. - * - * @param value the value value to set. - * @return the GroupQuotasEnforcementListResponse object itself. - */ - public GroupQuotasEnforcementListResponse withValue(List value) { - this.value = value; - return this; - } - - /** - * Get the nextLink property: The URL to use for getting the next set of results. - * - * @return the nextLink value. - */ - public String nextLink() { - return this.nextLink; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (value() != null) { - value().forEach(e -> e.validate()); - } - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of GroupQuotasEnforcementListResponse from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of GroupQuotasEnforcementListResponse 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 GroupQuotasEnforcementListResponse. - */ - public static GroupQuotasEnforcementListResponse fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - GroupQuotasEnforcementListResponse deserializedGroupQuotasEnforcementListResponse - = new GroupQuotasEnforcementListResponse(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - List value - = reader.readArray(reader1 -> GroupQuotasEnforcementResponseInner.fromJson(reader1)); - deserializedGroupQuotasEnforcementListResponse.value = value; - } else if ("nextLink".equals(fieldName)) { - deserializedGroupQuotasEnforcementListResponse.nextLink = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedGroupQuotasEnforcementListResponse; - }); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEnforcementResponse.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEnforcementResponse.java deleted file mode 100644 index d35a5d0d46a3..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEnforcementResponse.java +++ /dev/null @@ -1,55 +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.resourcemanager.quota.models; - -import com.azure.core.management.SystemData; -import com.azure.resourcemanager.quota.fluent.models.GroupQuotasEnforcementResponseInner; - -/** - * An immutable client-side representation of GroupQuotasEnforcementResponse. - */ -public interface GroupQuotasEnforcementResponse { - /** - * Gets the id property: Fully qualified resource Id for the resource. - * - * @return the id value. - */ - String id(); - - /** - * Gets the name property: The name of the resource. - * - * @return the name value. - */ - String name(); - - /** - * Gets the type property: The type of the resource. - * - * @return the type value. - */ - String type(); - - /** - * Gets the properties property: The properties property. - * - * @return the properties value. - */ - GroupQuotasEnforcementResponseProperties properties(); - - /** - * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. - * - * @return the systemData value. - */ - SystemData systemData(); - - /** - * Gets the inner com.azure.resourcemanager.quota.fluent.models.GroupQuotasEnforcementResponseInner object. - * - * @return the inner object. - */ - GroupQuotasEnforcementResponseInner innerModel(); -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEnforcementResponseProperties.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEnforcementResponseProperties.java deleted file mode 100644 index d94c51fc2e19..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEnforcementResponseProperties.java +++ /dev/null @@ -1,130 +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.resourcemanager.quota.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; - -/** - * The GroupQuotasEnforcementResponseProperties model. - */ -@Fluent -public final class GroupQuotasEnforcementResponseProperties - implements JsonSerializable { - /* - * Is the GroupQuota Enforcement enabled for the Azure region. - */ - private EnforcementState enforcementEnabled; - - /* - * Request status. - */ - private RequestState provisioningState; - - /* - * Details of the failure. - */ - private String faultCode; - - /** - * Creates an instance of GroupQuotasEnforcementResponseProperties class. - */ - public GroupQuotasEnforcementResponseProperties() { - } - - /** - * Get the enforcementEnabled property: Is the GroupQuota Enforcement enabled for the Azure region. - * - * @return the enforcementEnabled value. - */ - public EnforcementState enforcementEnabled() { - return this.enforcementEnabled; - } - - /** - * Set the enforcementEnabled property: Is the GroupQuota Enforcement enabled for the Azure region. - * - * @param enforcementEnabled the enforcementEnabled value to set. - * @return the GroupQuotasEnforcementResponseProperties object itself. - */ - public GroupQuotasEnforcementResponseProperties withEnforcementEnabled(EnforcementState enforcementEnabled) { - this.enforcementEnabled = enforcementEnabled; - return this; - } - - /** - * Get the provisioningState property: Request status. - * - * @return the provisioningState value. - */ - public RequestState provisioningState() { - return this.provisioningState; - } - - /** - * Get the faultCode property: Details of the failure. - * - * @return the faultCode value. - */ - public String faultCode() { - return this.faultCode; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("enforcementEnabled", - this.enforcementEnabled == null ? null : this.enforcementEnabled.toString()); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of GroupQuotasEnforcementResponseProperties from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of GroupQuotasEnforcementResponseProperties 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 GroupQuotasEnforcementResponseProperties. - */ - public static GroupQuotasEnforcementResponseProperties fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - GroupQuotasEnforcementResponseProperties deserializedGroupQuotasEnforcementResponseProperties - = new GroupQuotasEnforcementResponseProperties(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("enforcementEnabled".equals(fieldName)) { - deserializedGroupQuotasEnforcementResponseProperties.enforcementEnabled - = EnforcementState.fromString(reader.getString()); - } else if ("provisioningState".equals(fieldName)) { - deserializedGroupQuotasEnforcementResponseProperties.provisioningState - = RequestState.fromString(reader.getString()); - } else if ("faultCode".equals(fieldName)) { - deserializedGroupQuotasEnforcementResponseProperties.faultCode = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedGroupQuotasEnforcementResponseProperties; - }); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEntity.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEntity.java index 0b26c44c9cb2..722287fde0d7 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEntity.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEntity.java @@ -33,12 +33,11 @@ public interface GroupQuotasEntity { String type(); /** - * Gets the properties property: Properties and filters for ShareQuota. The request parameter is optional, if there - * are no filters specified. + * Gets the properties property: Properties. * * @return the properties value. */ - GroupQuotasEntityBase properties(); + GroupQuotasEntityProperties properties(); /** * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEntityBase.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEntityBase.java index 182ebd88398f..9514feae6c8a 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEntityBase.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEntityBase.java @@ -15,17 +15,12 @@ * Properties and filters for ShareQuota. The request parameter is optional, if there are no filters specified. */ @Fluent -public final class GroupQuotasEntityBase implements JsonSerializable { +public class GroupQuotasEntityBase implements JsonSerializable { /* * Display name of the GroupQuota entity. */ private String displayName; - /* - * Additional attributes to filter/restrict the subscriptions, which can be added to the subscriptionIds. - */ - private AdditionalAttributes additionalAttributes; - /* * Provisioning state of the operation. */ @@ -58,45 +53,31 @@ public GroupQuotasEntityBase withDisplayName(String displayName) { } /** - * Get the additionalAttributes property: Additional attributes to filter/restrict the subscriptions, which can be - * added to the subscriptionIds. + * Get the provisioningState property: Provisioning state of the operation. * - * @return the additionalAttributes value. + * @return the provisioningState value. */ - public AdditionalAttributes additionalAttributes() { - return this.additionalAttributes; + public RequestState provisioningState() { + return this.provisioningState; } /** - * Set the additionalAttributes property: Additional attributes to filter/restrict the subscriptions, which can be - * added to the subscriptionIds. + * Set the provisioningState property: Provisioning state of the operation. * - * @param additionalAttributes the additionalAttributes value to set. + * @param provisioningState the provisioningState value to set. * @return the GroupQuotasEntityBase object itself. */ - public GroupQuotasEntityBase withAdditionalAttributes(AdditionalAttributes additionalAttributes) { - this.additionalAttributes = additionalAttributes; + GroupQuotasEntityBase withProvisioningState(RequestState provisioningState) { + this.provisioningState = provisioningState; return this; } - /** - * Get the provisioningState property: Provisioning state of the operation. - * - * @return the provisioningState value. - */ - public RequestState provisioningState() { - return this.provisioningState; - } - /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { - if (additionalAttributes() != null) { - additionalAttributes().validate(); - } } /** @@ -106,7 +87,6 @@ public void validate() { public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("displayName", this.displayName); - jsonWriter.writeJsonField("additionalAttributes", this.additionalAttributes); return jsonWriter.writeEndObject(); } @@ -127,8 +107,6 @@ public static GroupQuotasEntityBase fromJson(JsonReader jsonReader) throws IOExc if ("displayName".equals(fieldName)) { deserializedGroupQuotasEntityBase.displayName = reader.getString(); - } else if ("additionalAttributes".equals(fieldName)) { - deserializedGroupQuotasEntityBase.additionalAttributes = AdditionalAttributes.fromJson(reader); } else if ("provisioningState".equals(fieldName)) { deserializedGroupQuotasEntityBase.provisioningState = RequestState.fromString(reader.getString()); } else { diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEntityBasePatch.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEntityBasePatch.java index 27235d6277f2..7d39d0eff8aa 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEntityBasePatch.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEntityBasePatch.java @@ -15,17 +15,12 @@ * Properties and filters for ShareQuota. The request parameter is optional, if there are no filters specified. */ @Fluent -public final class GroupQuotasEntityBasePatch implements JsonSerializable { +public class GroupQuotasEntityBasePatch implements JsonSerializable { /* * Display name of the GroupQuota entity. */ private String displayName; - /* - * Additional attributes to filter/restrict the subscriptions, which can be added to the subscriptionIds. - */ - private AdditionalAttributesPatch additionalAttributes; - /* * Provisioning state of the operation. */ @@ -58,45 +53,31 @@ public GroupQuotasEntityBasePatch withDisplayName(String displayName) { } /** - * Get the additionalAttributes property: Additional attributes to filter/restrict the subscriptions, which can be - * added to the subscriptionIds. + * Get the provisioningState property: Provisioning state of the operation. * - * @return the additionalAttributes value. + * @return the provisioningState value. */ - public AdditionalAttributesPatch additionalAttributes() { - return this.additionalAttributes; + public RequestState provisioningState() { + return this.provisioningState; } /** - * Set the additionalAttributes property: Additional attributes to filter/restrict the subscriptions, which can be - * added to the subscriptionIds. + * Set the provisioningState property: Provisioning state of the operation. * - * @param additionalAttributes the additionalAttributes value to set. + * @param provisioningState the provisioningState value to set. * @return the GroupQuotasEntityBasePatch object itself. */ - public GroupQuotasEntityBasePatch withAdditionalAttributes(AdditionalAttributesPatch additionalAttributes) { - this.additionalAttributes = additionalAttributes; + GroupQuotasEntityBasePatch withProvisioningState(RequestState provisioningState) { + this.provisioningState = provisioningState; return this; } - /** - * Get the provisioningState property: Provisioning state of the operation. - * - * @return the provisioningState value. - */ - public RequestState provisioningState() { - return this.provisioningState; - } - /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { - if (additionalAttributes() != null) { - additionalAttributes().validate(); - } } /** @@ -106,7 +87,6 @@ public void validate() { public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("displayName", this.displayName); - jsonWriter.writeJsonField("additionalAttributes", this.additionalAttributes); return jsonWriter.writeEndObject(); } @@ -127,9 +107,6 @@ public static GroupQuotasEntityBasePatch fromJson(JsonReader jsonReader) throws if ("displayName".equals(fieldName)) { deserializedGroupQuotasEntityBasePatch.displayName = reader.getString(); - } else if ("additionalAttributes".equals(fieldName)) { - deserializedGroupQuotasEntityBasePatch.additionalAttributes - = AdditionalAttributesPatch.fromJson(reader); } else if ("provisioningState".equals(fieldName)) { deserializedGroupQuotasEntityBasePatch.provisioningState = RequestState.fromString(reader.getString()); diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEntityPatch.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEntityPatch.java index 40872e623831..eea2a4fce5d8 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEntityPatch.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEntityPatch.java @@ -18,9 +18,9 @@ @Fluent public final class GroupQuotasEntityPatch extends ProxyResource { /* - * Properties and filters for ShareQuota. The request parameter is optional, if there are no filters specified. + * Properties */ - private GroupQuotasEntityBasePatch properties; + private GroupQuotasEntityPatchProperties properties; /* * Azure Resource Manager metadata containing createdBy and modifiedBy information. @@ -49,23 +49,21 @@ public GroupQuotasEntityPatch() { } /** - * Get the properties property: Properties and filters for ShareQuota. The request parameter is optional, if there - * are no filters specified. + * Get the properties property: Properties. * * @return the properties value. */ - public GroupQuotasEntityBasePatch properties() { + public GroupQuotasEntityPatchProperties properties() { return this.properties; } /** - * Set the properties property: Properties and filters for ShareQuota. The request parameter is optional, if there - * are no filters specified. + * Set the properties property: Properties. * * @param properties the properties value to set. * @return the GroupQuotasEntityPatch object itself. */ - public GroupQuotasEntityPatch withProperties(GroupQuotasEntityBasePatch properties) { + public GroupQuotasEntityPatch withProperties(GroupQuotasEntityPatchProperties properties) { this.properties = properties; return this; } @@ -153,7 +151,7 @@ public static GroupQuotasEntityPatch fromJson(JsonReader jsonReader) throws IOEx } else if ("type".equals(fieldName)) { deserializedGroupQuotasEntityPatch.type = reader.getString(); } else if ("properties".equals(fieldName)) { - deserializedGroupQuotasEntityPatch.properties = GroupQuotasEntityBasePatch.fromJson(reader); + deserializedGroupQuotasEntityPatch.properties = GroupQuotasEntityPatchProperties.fromJson(reader); } else if ("systemData".equals(fieldName)) { deserializedGroupQuotasEntityPatch.systemData = SystemData.fromJson(reader); } else { diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEntityPatchProperties.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEntityPatchProperties.java new file mode 100644 index 000000000000..2ee8906793a0 --- /dev/null +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEntityPatchProperties.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. + +package com.azure.resourcemanager.quota.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; + +/** + * Properties. + */ +@Fluent +public final class GroupQuotasEntityPatchProperties extends GroupQuotasEntityBasePatch { + /* + * Provisioning state of the operation. + */ + private RequestState provisioningState; + + /** + * Creates an instance of GroupQuotasEntityPatchProperties class. + */ + public GroupQuotasEntityPatchProperties() { + } + + /** + * Get the provisioningState property: Provisioning state of the operation. + * + * @return the provisioningState value. + */ + @Override + public RequestState provisioningState() { + return this.provisioningState; + } + + /** + * {@inheritDoc} + */ + @Override + public GroupQuotasEntityPatchProperties withDisplayName(String displayName) { + super.withDisplayName(displayName); + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + @Override + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("displayName", displayName()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of GroupQuotasEntityPatchProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of GroupQuotasEntityPatchProperties 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 GroupQuotasEntityPatchProperties. + */ + public static GroupQuotasEntityPatchProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + GroupQuotasEntityPatchProperties deserializedGroupQuotasEntityPatchProperties + = new GroupQuotasEntityPatchProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("displayName".equals(fieldName)) { + deserializedGroupQuotasEntityPatchProperties.withDisplayName(reader.getString()); + } else if ("provisioningState".equals(fieldName)) { + deserializedGroupQuotasEntityPatchProperties.provisioningState + = RequestState.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedGroupQuotasEntityPatchProperties; + }); + } +} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEntityProperties.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEntityProperties.java new file mode 100644 index 000000000000..8d19cafd0052 --- /dev/null +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupQuotasEntityProperties.java @@ -0,0 +1,95 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.quota.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; + +/** + * Properties. + */ +@Fluent +public final class GroupQuotasEntityProperties extends GroupQuotasEntityBase { + /* + * Provisioning state of the operation. + */ + private RequestState provisioningState; + + /** + * Creates an instance of GroupQuotasEntityProperties class. + */ + public GroupQuotasEntityProperties() { + } + + /** + * Get the provisioningState property: Provisioning state of the operation. + * + * @return the provisioningState value. + */ + @Override + public RequestState provisioningState() { + return this.provisioningState; + } + + /** + * {@inheritDoc} + */ + @Override + public GroupQuotasEntityProperties withDisplayName(String displayName) { + super.withDisplayName(displayName); + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + @Override + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("displayName", displayName()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of GroupQuotasEntityProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of GroupQuotasEntityProperties 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 GroupQuotasEntityProperties. + */ + public static GroupQuotasEntityProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + GroupQuotasEntityProperties deserializedGroupQuotasEntityProperties = new GroupQuotasEntityProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("displayName".equals(fieldName)) { + deserializedGroupQuotasEntityProperties.withDisplayName(reader.getString()); + } else if ("provisioningState".equals(fieldName)) { + deserializedGroupQuotasEntityProperties.provisioningState + = RequestState.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedGroupQuotasEntityProperties; + }); + } +} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupingId.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupingId.java deleted file mode 100644 index 49731f6e6dc1..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupingId.java +++ /dev/null @@ -1,124 +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.resourcemanager.quota.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; - -/** - * The grouping Id for the group quota. It can be Billing Id or ServiceTreeId if applicable. - */ -@Fluent -public final class GroupingId implements JsonSerializable { - /* - * GroupingId type. It is a required property. More types of groupIds can be supported in future. - */ - private GroupingIdType groupingIdType; - - /* - * GroupId value based on the groupingType selected - Billing Id or ServiceTreeId. - */ - private String value; - - /** - * Creates an instance of GroupingId class. - */ - public GroupingId() { - } - - /** - * Get the groupingIdType property: GroupingId type. It is a required property. More types of groupIds can be - * supported in future. - * - * @return the groupingIdType value. - */ - public GroupingIdType groupingIdType() { - return this.groupingIdType; - } - - /** - * Set the groupingIdType property: GroupingId type. It is a required property. More types of groupIds can be - * supported in future. - * - * @param groupingIdType the groupingIdType value to set. - * @return the GroupingId object itself. - */ - public GroupingId withGroupingIdType(GroupingIdType groupingIdType) { - this.groupingIdType = groupingIdType; - return this; - } - - /** - * Get the value property: GroupId value based on the groupingType selected - Billing Id or ServiceTreeId. - * - * @return the value value. - */ - public String value() { - return this.value; - } - - /** - * Set the value property: GroupId value based on the groupingType selected - Billing Id or ServiceTreeId. - * - * @param value the value value to set. - * @return the GroupingId object itself. - */ - public GroupingId withValue(String value) { - this.value = value; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("groupingIdType", - this.groupingIdType == null ? null : this.groupingIdType.toString()); - jsonWriter.writeStringField("value", this.value); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of GroupingId from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of GroupingId 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 GroupingId. - */ - public static GroupingId fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - GroupingId deserializedGroupingId = new GroupingId(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("groupingIdType".equals(fieldName)) { - deserializedGroupingId.groupingIdType = GroupingIdType.fromString(reader.getString()); - } else if ("value".equals(fieldName)) { - deserializedGroupingId.value = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedGroupingId; - }); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupingIdType.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupingIdType.java deleted file mode 100644 index 3c1ae62b60b2..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/GroupingIdType.java +++ /dev/null @@ -1,51 +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.resourcemanager.quota.models; - -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * GroupingId type. It is a required property. More types of groupIds can be supported in future. - */ -public final class GroupingIdType extends ExpandableStringEnum { - /** - * Static value ServiceTreeId for GroupingIdType. - */ - public static final GroupingIdType SERVICE_TREE_ID = fromString("ServiceTreeId"); - - /** - * Static value BillingId for GroupingIdType. - */ - public static final GroupingIdType BILLING_ID = fromString("BillingId"); - - /** - * Creates a new instance of GroupingIdType value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Deprecated - public GroupingIdType() { - } - - /** - * Creates or finds a GroupingIdType from its string representation. - * - * @param name a name to look for. - * @return the corresponding GroupingIdType. - */ - public static GroupingIdType fromString(String name) { - return fromString(name, GroupingIdType.class); - } - - /** - * Gets known GroupingIdType values. - * - * @return known GroupingIdType values. - */ - public static Collection values() { - return values(GroupingIdType.class); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/ResourceUsageList.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/ResourceUsageList.java deleted file mode 100644 index cbcb18595792..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/ResourceUsageList.java +++ /dev/null @@ -1,116 +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.resourcemanager.quota.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.resourcemanager.quota.fluent.models.ResourceUsagesInner; -import java.io.IOException; -import java.util.List; - -/** - * List of resource usages and quotas for GroupQuota. - */ -@Fluent -public final class ResourceUsageList implements JsonSerializable { - /* - * List of resource usages at Group Quotas. - */ - private List value; - - /* - * The URL to use for getting the next set of results. - */ - private String nextLink; - - /** - * Creates an instance of ResourceUsageList class. - */ - public ResourceUsageList() { - } - - /** - * Get the value property: List of resource usages at Group Quotas. - * - * @return the value value. - */ - public List value() { - return this.value; - } - - /** - * Set the value property: List of resource usages at Group Quotas. - * - * @param value the value value to set. - * @return the ResourceUsageList object itself. - */ - public ResourceUsageList withValue(List value) { - this.value = value; - return this; - } - - /** - * Get the nextLink property: The URL to use for getting the next set of results. - * - * @return the nextLink value. - */ - public String nextLink() { - return this.nextLink; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (value() != null) { - value().forEach(e -> e.validate()); - } - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of ResourceUsageList from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of ResourceUsageList 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 ResourceUsageList. - */ - public static ResourceUsageList fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - ResourceUsageList deserializedResourceUsageList = new ResourceUsageList(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - List value - = reader.readArray(reader1 -> ResourceUsagesInner.fromJson(reader1)); - deserializedResourceUsageList.value = value; - } else if ("nextLink".equals(fieldName)) { - deserializedResourceUsageList.nextLink = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedResourceUsageList; - }); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/ResourceUsages.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/ResourceUsages.java deleted file mode 100644 index 6f4a13caa7cd..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/ResourceUsages.java +++ /dev/null @@ -1,55 +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.resourcemanager.quota.models; - -import com.azure.core.management.SystemData; -import com.azure.resourcemanager.quota.fluent.models.ResourceUsagesInner; - -/** - * An immutable client-side representation of ResourceUsages. - */ -public interface ResourceUsages { - /** - * Gets the id property: Fully qualified resource Id for the resource. - * - * @return the id value. - */ - String id(); - - /** - * Gets the name property: The name of the resource. - * - * @return the name value. - */ - String name(); - - /** - * Gets the type property: The type of the resource. - * - * @return the type value. - */ - String type(); - - /** - * Gets the properties property: Resource details with usages and GroupQuota. - * - * @return the properties value. - */ - GroupQuotaUsagesBase properties(); - - /** - * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. - * - * @return the systemData value. - */ - SystemData systemData(); - - /** - * Gets the inner com.azure.resourcemanager.quota.fluent.models.ResourceUsagesInner object. - * - * @return the inner object. - */ - ResourceUsagesInner innerModel(); -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/SubscriptionQuotaAllocations.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/SubscriptionQuotaAllocations.java index 549c579fe6e3..5ec35802e9ca 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/SubscriptionQuotaAllocations.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/SubscriptionQuotaAllocations.java @@ -4,52 +4,96 @@ package com.azure.resourcemanager.quota.models; -import com.azure.core.management.SystemData; -import com.azure.resourcemanager.quota.fluent.models.SubscriptionQuotaAllocationsInner; +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; /** - * An immutable client-side representation of SubscriptionQuotaAllocations. + * Quota allocated to a subscription for the specific Resource Provider, Location, ResourceName. This will include the + * GroupQuota and total quota allocated to the subscription. Only the Group quota allocated to the subscription can be + * allocated back to the MG Group Quota. */ -public interface SubscriptionQuotaAllocations { +@Fluent +public final class SubscriptionQuotaAllocations implements JsonSerializable { + /* + * Quota properties for the specified resource. + */ + private SubscriptionQuotaAllocationsProperties properties; + /** - * Gets the id property: Fully qualified resource Id for the resource. - * - * @return the id value. + * Creates an instance of SubscriptionQuotaAllocations class. */ - String id(); + public SubscriptionQuotaAllocations() { + } /** - * Gets the name property: The name of the resource. + * Get the properties property: Quota properties for the specified resource. * - * @return the name value. + * @return the properties value. */ - String name(); + public SubscriptionQuotaAllocationsProperties properties() { + return this.properties; + } /** - * Gets the type property: The type of the resource. + * Set the properties property: Quota properties for the specified resource. * - * @return the type value. + * @param properties the properties value to set. + * @return the SubscriptionQuotaAllocations object itself. */ - String type(); + public SubscriptionQuotaAllocations withProperties(SubscriptionQuotaAllocationsProperties properties) { + this.properties = properties; + return this; + } /** - * Gets the properties property: Quota properties for the specified resource. + * Validates the instance. * - * @return the properties value. + * @throws IllegalArgumentException thrown if the instance is not valid. */ - SubscriptionQuotaDetails properties(); + public void validate() { + if (properties() != null) { + properties().validate(); + } + } /** - * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. - * - * @return the systemData value. + * {@inheritDoc} */ - SystemData systemData(); + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("properties", this.properties); + return jsonWriter.writeEndObject(); + } /** - * Gets the inner com.azure.resourcemanager.quota.fluent.models.SubscriptionQuotaAllocationsInner object. + * Reads an instance of SubscriptionQuotaAllocations from the JsonReader. * - * @return the inner object. + * @param jsonReader The JsonReader being read. + * @return An instance of SubscriptionQuotaAllocations 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 SubscriptionQuotaAllocations. */ - SubscriptionQuotaAllocationsInner innerModel(); + public static SubscriptionQuotaAllocations fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SubscriptionQuotaAllocations deserializedSubscriptionQuotaAllocations = new SubscriptionQuotaAllocations(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("properties".equals(fieldName)) { + deserializedSubscriptionQuotaAllocations.properties + = SubscriptionQuotaAllocationsProperties.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedSubscriptionQuotaAllocations; + }); + } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/SubscriptionQuotaAllocationsList.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/SubscriptionQuotaAllocationsList.java index 3ec0e2f073df..f446f421570c 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/SubscriptionQuotaAllocationsList.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/SubscriptionQuotaAllocationsList.java @@ -4,114 +4,52 @@ package com.azure.resourcemanager.quota.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.resourcemanager.quota.fluent.models.SubscriptionQuotaAllocationsInner; -import java.io.IOException; -import java.util.List; +import com.azure.core.management.SystemData; +import com.azure.resourcemanager.quota.fluent.models.SubscriptionQuotaAllocationsListInner; /** - * Subscription quota list. + * An immutable client-side representation of SubscriptionQuotaAllocationsList. */ -@Fluent -public final class SubscriptionQuotaAllocationsList implements JsonSerializable { - /* - * Subscription quota list. - */ - private List value; - - /* - * The URL to use for getting the next set of results. - */ - private String nextLink; - - /** - * Creates an instance of SubscriptionQuotaAllocationsList class. - */ - public SubscriptionQuotaAllocationsList() { - } - +public interface SubscriptionQuotaAllocationsList { /** - * Get the value property: Subscription quota list. + * Gets the id property: Fully qualified resource Id for the resource. * - * @return the value value. + * @return the id value. */ - public List value() { - return this.value; - } + String id(); /** - * Set the value property: Subscription quota list. + * Gets the name property: The name of the resource. * - * @param value the value value to set. - * @return the SubscriptionQuotaAllocationsList object itself. + * @return the name value. */ - public SubscriptionQuotaAllocationsList withValue(List value) { - this.value = value; - return this; - } + String name(); /** - * Get the nextLink property: The URL to use for getting the next set of results. + * Gets the type property: The type of the resource. * - * @return the nextLink value. + * @return the type value. */ - public String nextLink() { - return this.nextLink; - } + String type(); /** - * Validates the instance. + * Gets the properties property: The properties property. * - * @throws IllegalArgumentException thrown if the instance is not valid. + * @return the properties value. */ - public void validate() { - if (value() != null) { - value().forEach(e -> e.validate()); - } - } + SubscriptionQuotaAllocationsListProperties properties(); /** - * {@inheritDoc} + * Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * + * @return the systemData value. */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); - return jsonWriter.writeEndObject(); - } + SystemData systemData(); /** - * Reads an instance of SubscriptionQuotaAllocationsList from the JsonReader. + * Gets the inner com.azure.resourcemanager.quota.fluent.models.SubscriptionQuotaAllocationsListInner object. * - * @param jsonReader The JsonReader being read. - * @return An instance of SubscriptionQuotaAllocationsList 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 SubscriptionQuotaAllocationsList. + * @return the inner object. */ - public static SubscriptionQuotaAllocationsList fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SubscriptionQuotaAllocationsList deserializedSubscriptionQuotaAllocationsList - = new SubscriptionQuotaAllocationsList(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - List value - = reader.readArray(reader1 -> SubscriptionQuotaAllocationsInner.fromJson(reader1)); - deserializedSubscriptionQuotaAllocationsList.value = value; - } else if ("nextLink".equals(fieldName)) { - deserializedSubscriptionQuotaAllocationsList.nextLink = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedSubscriptionQuotaAllocationsList; - }); - } + SubscriptionQuotaAllocationsListInner innerModel(); } diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/SubscriptionQuotaAllocationsListProperties.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/SubscriptionQuotaAllocationsListProperties.java new file mode 100644 index 000000000000..d04dcc4fb00f --- /dev/null +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/SubscriptionQuotaAllocationsListProperties.java @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.quota.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.List; + +/** + * The SubscriptionQuotaAllocationsListProperties model. + */ +@Fluent +public final class SubscriptionQuotaAllocationsListProperties + implements JsonSerializable { + /* + * Request status. + */ + private RequestState provisioningState; + + /* + * Subscription quota list. + */ + private List value; + + /* + * The URL to use for getting the next set of results. + */ + private String nextLink; + + /** + * Creates an instance of SubscriptionQuotaAllocationsListProperties class. + */ + public SubscriptionQuotaAllocationsListProperties() { + } + + /** + * Get the provisioningState property: Request status. + * + * @return the provisioningState value. + */ + public RequestState provisioningState() { + return this.provisioningState; + } + + /** + * Get the value property: Subscription quota list. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Set the value property: Subscription quota list. + * + * @param value the value value to set. + * @return the SubscriptionQuotaAllocationsListProperties object itself. + */ + public SubscriptionQuotaAllocationsListProperties withValue(List value) { + this.value = value; + return this; + } + + /** + * Get the nextLink property: The URL to use for getting the next set of results. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() != null) { + value().forEach(e -> e.validate()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SubscriptionQuotaAllocationsListProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SubscriptionQuotaAllocationsListProperties 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 SubscriptionQuotaAllocationsListProperties. + */ + public static SubscriptionQuotaAllocationsListProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SubscriptionQuotaAllocationsListProperties deserializedSubscriptionQuotaAllocationsListProperties + = new SubscriptionQuotaAllocationsListProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("provisioningState".equals(fieldName)) { + deserializedSubscriptionQuotaAllocationsListProperties.provisioningState + = RequestState.fromString(reader.getString()); + } else if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> SubscriptionQuotaAllocations.fromJson(reader1)); + deserializedSubscriptionQuotaAllocationsListProperties.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedSubscriptionQuotaAllocationsListProperties.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedSubscriptionQuotaAllocationsListProperties; + }); + } +} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/SubscriptionQuotaAllocationsProperties.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/SubscriptionQuotaAllocationsProperties.java new file mode 100644 index 000000000000..c8182f68cdb4 --- /dev/null +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/SubscriptionQuotaAllocationsProperties.java @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.quota.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.resourcemanager.quota.fluent.models.SubscriptionQuotaDetailsName; +import java.io.IOException; + +/** + * Quota properties for the specified resource. + */ +@Fluent +public final class SubscriptionQuotaAllocationsProperties extends SubscriptionQuotaDetails { + /* + * Name of the resource provided by the resource provider. This property is already included in the request URI, so + * it is a readonly property returned in the response. + */ + private SubscriptionQuotaDetailsName innerName; + + /* + * The shareable quota for the subscription. + */ + private Long shareableQuota; + + /** + * Creates an instance of SubscriptionQuotaAllocationsProperties class. + */ + public SubscriptionQuotaAllocationsProperties() { + } + + /** + * Get the innerName property: Name of the resource provided by the resource provider. This property is already + * included in the request URI, so it is a readonly property returned in the response. + * + * @return the innerName value. + */ + private SubscriptionQuotaDetailsName innerName() { + return this.innerName; + } + + /** + * Get the shareableQuota property: The shareable quota for the subscription. + * + * @return the shareableQuota value. + */ + @Override + public Long shareableQuota() { + return this.shareableQuota; + } + + /** + * {@inheritDoc} + */ + @Override + public SubscriptionQuotaAllocationsProperties withResourceName(String resourceName) { + super.withResourceName(resourceName); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SubscriptionQuotaAllocationsProperties withLimit(Long limit) { + super.withLimit(limit); + return this; + } + + /** + * Get the value property: Resource name. + * + * @return the value value. + */ + public String value() { + return this.innerName() == null ? null : this.innerName().value(); + } + + /** + * Get the localizedValue property: Resource display name. + * + * @return the localizedValue value. + */ + public String localizedValue() { + return this.innerName() == null ? null : this.innerName().localizedValue(); + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + @Override + public void validate() { + if (innerName() != null) { + innerName().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("resourceName", resourceName()); + jsonWriter.writeNumberField("limit", limit()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SubscriptionQuotaAllocationsProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SubscriptionQuotaAllocationsProperties 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 SubscriptionQuotaAllocationsProperties. + */ + public static SubscriptionQuotaAllocationsProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SubscriptionQuotaAllocationsProperties deserializedSubscriptionQuotaAllocationsProperties + = new SubscriptionQuotaAllocationsProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("resourceName".equals(fieldName)) { + deserializedSubscriptionQuotaAllocationsProperties.withResourceName(reader.getString()); + } else if ("limit".equals(fieldName)) { + deserializedSubscriptionQuotaAllocationsProperties + .withLimit(reader.getNullable(JsonReader::getLong)); + } else if ("shareableQuota".equals(fieldName)) { + deserializedSubscriptionQuotaAllocationsProperties.shareableQuota + = reader.getNullable(JsonReader::getLong); + } else if ("name".equals(fieldName)) { + deserializedSubscriptionQuotaAllocationsProperties.innerName + = SubscriptionQuotaDetailsName.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedSubscriptionQuotaAllocationsProperties; + }); + } +} diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/SubscriptionQuotaDetails.java b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/SubscriptionQuotaDetails.java index df65a8679c03..8f7a23d54b76 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/SubscriptionQuotaDetails.java +++ b/sdk/quota/azure-resourcemanager-quota/src/main/java/com/azure/resourcemanager/quota/models/SubscriptionQuotaDetails.java @@ -16,11 +16,11 @@ * Subscription Quota details. */ @Fluent -public final class SubscriptionQuotaDetails implements JsonSerializable { +public class SubscriptionQuotaDetails implements JsonSerializable { /* - * Location/Azure region for the quota requested for resource. + * The resource name, such as SKU name. */ - private String region; + private String resourceName; /* * The total quota limit for the subscription. @@ -45,22 +45,22 @@ public SubscriptionQuotaDetails() { } /** - * Get the region property: Location/Azure region for the quota requested for resource. + * Get the resourceName property: The resource name, such as SKU name. * - * @return the region value. + * @return the resourceName value. */ - public String region() { - return this.region; + public String resourceName() { + return this.resourceName; } /** - * Set the region property: Location/Azure region for the quota requested for resource. + * Set the resourceName property: The resource name, such as SKU name. * - * @param region the region value to set. + * @param resourceName the resourceName value to set. * @return the SubscriptionQuotaDetails object itself. */ - public SubscriptionQuotaDetails withRegion(String region) { - this.region = region; + public SubscriptionQuotaDetails withResourceName(String resourceName) { + this.resourceName = resourceName; return this; } @@ -93,6 +93,17 @@ public Long shareableQuota() { return this.shareableQuota; } + /** + * Set the shareableQuota property: The shareable quota for the subscription. + * + * @param shareableQuota the shareableQuota value to set. + * @return the SubscriptionQuotaDetails object itself. + */ + SubscriptionQuotaDetails withShareableQuota(Long shareableQuota) { + this.shareableQuota = shareableQuota; + return this; + } + /** * Get the innerName property: Name of the resource provided by the resource provider. This property is already * included in the request URI, so it is a readonly property returned in the response. @@ -103,6 +114,18 @@ private SubscriptionQuotaDetailsName innerName() { return this.innerName; } + /** + * Set the innerName property: Name of the resource provided by the resource provider. This property is already + * included in the request URI, so it is a readonly property returned in the response. + * + * @param innerName the innerName value to set. + * @return the SubscriptionQuotaDetails object itself. + */ + SubscriptionQuotaDetails withInnerName(SubscriptionQuotaDetailsName innerName) { + this.innerName = innerName; + return this; + } + /** * Get the value property: Resource name. * @@ -138,7 +161,7 @@ public void validate() { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeStringField("region", this.region); + jsonWriter.writeStringField("resourceName", this.resourceName); jsonWriter.writeNumberField("limit", this.limit); return jsonWriter.writeEndObject(); } @@ -158,8 +181,8 @@ public static SubscriptionQuotaDetails fromJson(JsonReader jsonReader) throws IO String fieldName = reader.getFieldName(); reader.nextToken(); - if ("region".equals(fieldName)) { - deserializedSubscriptionQuotaDetails.region = reader.getString(); + if ("resourceName".equals(fieldName)) { + deserializedSubscriptionQuotaDetails.resourceName = reader.getString(); } else if ("limit".equals(fieldName)) { deserializedSubscriptionQuotaDetails.limit = reader.getNullable(JsonReader::getLong); } else if ("shareableQuota".equals(fieldName)) { diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-quota/proxy-config.json b/sdk/quota/azure-resourcemanager-quota/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-quota/proxy-config.json index 903a9bbcceac..f5544dc4bb7d 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-quota/proxy-config.json +++ b/sdk/quota/azure-resourcemanager-quota/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-quota/proxy-config.json @@ -1 +1 @@ -[["com.azure.resourcemanager.quota.implementation.GroupQuotaLimitsClientImpl$GroupQuotaLimitsService"],["com.azure.resourcemanager.quota.implementation.GroupQuotaLimitsRequestsClientImpl$GroupQuotaLimitsRequestsService"],["com.azure.resourcemanager.quota.implementation.GroupQuotaLocationSettingsClientImpl$GroupQuotaLocationSettingsService"],["com.azure.resourcemanager.quota.implementation.GroupQuotaSubscriptionAllocationRequestsClientImpl$GroupQuotaSubscriptionAllocationRequestsService"],["com.azure.resourcemanager.quota.implementation.GroupQuotaSubscriptionAllocationsClientImpl$GroupQuotaSubscriptionAllocationsService"],["com.azure.resourcemanager.quota.implementation.GroupQuotaSubscriptionRequestsClientImpl$GroupQuotaSubscriptionRequestsService"],["com.azure.resourcemanager.quota.implementation.GroupQuotaSubscriptionsClientImpl$GroupQuotaSubscriptionsService"],["com.azure.resourcemanager.quota.implementation.GroupQuotaUsagesClientImpl$GroupQuotaUsagesService"],["com.azure.resourcemanager.quota.implementation.GroupQuotasClientImpl$GroupQuotasService"],["com.azure.resourcemanager.quota.implementation.QuotaOperationsClientImpl$QuotaOperationsService"],["com.azure.resourcemanager.quota.implementation.QuotaRequestStatusClientImpl$QuotaRequestStatusService"],["com.azure.resourcemanager.quota.implementation.QuotasClientImpl$QuotasService"],["com.azure.resourcemanager.quota.implementation.UsagesClientImpl$UsagesService"]] \ No newline at end of file +[["com.azure.resourcemanager.quota.implementation.GroupQuotaLimitsClientImpl$GroupQuotaLimitsService"],["com.azure.resourcemanager.quota.implementation.GroupQuotaLimitsRequestsClientImpl$GroupQuotaLimitsRequestsService"],["com.azure.resourcemanager.quota.implementation.GroupQuotaSubscriptionAllocationRequestsClientImpl$GroupQuotaSubscriptionAllocationRequestsService"],["com.azure.resourcemanager.quota.implementation.GroupQuotaSubscriptionAllocationsClientImpl$GroupQuotaSubscriptionAllocationsService"],["com.azure.resourcemanager.quota.implementation.GroupQuotaSubscriptionRequestsClientImpl$GroupQuotaSubscriptionRequestsService"],["com.azure.resourcemanager.quota.implementation.GroupQuotaSubscriptionsClientImpl$GroupQuotaSubscriptionsService"],["com.azure.resourcemanager.quota.implementation.GroupQuotasClientImpl$GroupQuotasService"],["com.azure.resourcemanager.quota.implementation.QuotaOperationsClientImpl$QuotaOperationsService"],["com.azure.resourcemanager.quota.implementation.QuotaRequestStatusClientImpl$QuotaRequestStatusService"],["com.azure.resourcemanager.quota.implementation.QuotasClientImpl$QuotasService"],["com.azure.resourcemanager.quota.implementation.UsagesClientImpl$UsagesService"]] \ No newline at end of file diff --git a/sdk/quota/azure-resourcemanager-quota/src/main/resources/azure-resourcemanager-quota.properties b/sdk/quota/azure-resourcemanager-quota/src/main/resources/azure-resourcemanager-quota.properties new file mode 100644 index 000000000000..defbd48204e4 --- /dev/null +++ b/sdk/quota/azure-resourcemanager-quota/src/main/resources/azure-resourcemanager-quota.properties @@ -0,0 +1 @@ +version=${project.version} diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsGetSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsGetSamples.java deleted file mode 100644 index b376448b588a..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsGetSamples.java +++ /dev/null @@ -1,26 +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.resourcemanager.quota.generated; - -/** - * Samples for GroupQuotaLimits Get. - */ -public final class GroupQuotaLimitsGetSamples { - /* - * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotaLimits/ - * GetGroupQuotaLimits-Compute.json - */ - /** - * Sample code: GroupQuotaLimits_Get_Request_ForCompute. - * - * @param manager Entry point to QuotaManager. - */ - public static void groupQuotaLimitsGetRequestForCompute(com.azure.resourcemanager.quota.QuotaManager manager) { - manager.groupQuotaLimits() - .getWithResponse("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", "cores", - "location eq westus", com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsListSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsListSamples.java index 652cc1f9fa28..d741a0990975 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsListSamples.java +++ b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsListSamples.java @@ -10,17 +10,17 @@ public final class GroupQuotaLimitsListSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotaLimits/ + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GroupQuotaLimits/ * ListGroupQuotaLimits-Compute.json */ /** - * Sample code: GroupQuotaLimits_List_Request_ForCompute. + * Sample code: GroupQuotaLimits_Get_Request_ForCompute. * * @param manager Entry point to QuotaManager. */ - public static void groupQuotaLimitsListRequestForCompute(com.azure.resourcemanager.quota.QuotaManager manager) { + public static void groupQuotaLimitsGetRequestForCompute(com.azure.resourcemanager.quota.QuotaManager manager) { manager.groupQuotaLimits() - .list("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", "location eq westus", + .listWithResponse("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", "westus", com.azure.core.util.Context.NONE); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsRequestCreateOrUpdateSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsRequestCreateOrUpdateSamples.java deleted file mode 100644 index bd621a39a2f4..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsRequestCreateOrUpdateSamples.java +++ /dev/null @@ -1,26 +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.resourcemanager.quota.generated; - -/** - * Samples for GroupQuotaLimitsRequest CreateOrUpdate. - */ -public final class GroupQuotaLimitsRequestCreateOrUpdateSamples { - /* - * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotaLimitsRequests - * /PutGroupQuotaLimitsRequests-Compute.json - */ - /** - * Sample code: GroupQuotaLimitsRequests_CreateOrUpdate. - * - * @param manager Entry point to QuotaManager. - */ - public static void groupQuotaLimitsRequestsCreateOrUpdate(com.azure.resourcemanager.quota.QuotaManager manager) { - manager.groupQuotaLimitsRequests() - .createOrUpdate("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", - "standardav2family", null, com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsRequestGetSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsRequestGetSamples.java index 16aee567b433..b3ce65a51c2f 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsRequestGetSamples.java +++ b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsRequestGetSamples.java @@ -10,8 +10,8 @@ public final class GroupQuotaLimitsRequestGetSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotaLimitsRequests - * /GroupQuotaLimitsRequests_Get.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GroupQuotaLimitsRequests/ + * GroupQuotaLimitsRequests_Get.json */ /** * Sample code: GroupQuotaLimitsRequests_Get. diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsRequestListSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsRequestListSamples.java index 4ab250432703..1b1c4a938250 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsRequestListSamples.java +++ b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsRequestListSamples.java @@ -10,8 +10,8 @@ public final class GroupQuotaLimitsRequestListSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotaLimitsRequests - * /GroupQuotaLimitsRequests_List.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GroupQuotaLimitsRequests/ + * GroupQuotaLimitsRequests_List.json */ /** * Sample code: GroupQuotaLimitsRequest_List. diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsRequestUpdateSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsRequestUpdateSamples.java index 826bad67ab46..8a923f892ee7 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsRequestUpdateSamples.java +++ b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsRequestUpdateSamples.java @@ -4,14 +4,20 @@ package com.azure.resourcemanager.quota.generated; +import com.azure.resourcemanager.quota.fluent.models.GroupQuotaLimitListInner; +import com.azure.resourcemanager.quota.models.GroupQuotaLimit; +import com.azure.resourcemanager.quota.models.GroupQuotaLimitListProperties; +import com.azure.resourcemanager.quota.models.GroupQuotaLimitProperties; +import java.util.Arrays; + /** * Samples for GroupQuotaLimitsRequest Update. */ public final class GroupQuotaLimitsRequestUpdateSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotaLimitsRequests - * /PatchGroupQuotaLimitsRequests-Compute.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GroupQuotaLimitsRequests/ + * PatchGroupQuotaLimitsRequests-Compute.json */ /** * Sample code: GroupQuotaLimitsRequests_Update. @@ -20,7 +26,17 @@ public final class GroupQuotaLimitsRequestUpdateSamples { */ public static void groupQuotaLimitsRequestsUpdate(com.azure.resourcemanager.quota.QuotaManager manager) { manager.groupQuotaLimitsRequests() - .update("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", "standardav2family", - null, com.azure.core.util.Context.NONE); + .update("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", "westus", + new GroupQuotaLimitListInner() + .withProperties(new GroupQuotaLimitListProperties().withValue(Arrays.asList( + new GroupQuotaLimit() + .withProperties(new GroupQuotaLimitProperties().withResourceName("standardddv4family") + .withLimit(110L) + .withComment("Contoso requires more quota.")), + new GroupQuotaLimit() + .withProperties(new GroupQuotaLimitProperties().withResourceName("standardav2family") + .withLimit(110L) + .withComment("Contoso requires more quota."))))), + com.azure.core.util.Context.NONE); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLocationSettingsCreateOrUpdateSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLocationSettingsCreateOrUpdateSamples.java deleted file mode 100644 index 125e3a29f25b..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLocationSettingsCreateOrUpdateSamples.java +++ /dev/null @@ -1,51 +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.resourcemanager.quota.generated; - -import com.azure.resourcemanager.quota.fluent.models.GroupQuotasEnforcementResponseInner; -import com.azure.resourcemanager.quota.models.EnforcementState; -import com.azure.resourcemanager.quota.models.GroupQuotasEnforcementResponseProperties; - -/** - * Samples for GroupQuotaLocationSettings CreateOrUpdate. - */ -public final class GroupQuotaLocationSettingsCreateOrUpdateSamples { - /* - * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotasEnforcement/ - * PutGroupQuotaEnforcement.json - */ - /** - * Sample code: GroupQuotaLocationSettings_CreateOrUpdate. - * - * @param manager Entry point to QuotaManager. - */ - public static void groupQuotaLocationSettingsCreateOrUpdate(com.azure.resourcemanager.quota.QuotaManager manager) { - manager.groupQuotaLocationSettings() - .createOrUpdate("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", "eastus", - new GroupQuotasEnforcementResponseInner().withProperties( - new GroupQuotasEnforcementResponseProperties().withEnforcementEnabled(EnforcementState.ENABLED)), - com.azure.core.util.Context.NONE); - } - - /* - * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotasEnforcement/ - * PutGroupQuotaEnforcementFailed.json - */ - /** - * Sample code: GroupQuotaLocationSettings_CreateOrUpdate_Failed. - * - * @param manager Entry point to QuotaManager. - */ - public static void - groupQuotaLocationSettingsCreateOrUpdateFailed(com.azure.resourcemanager.quota.QuotaManager manager) { - manager.groupQuotaLocationSettings() - .createOrUpdate("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", "eastus", - new GroupQuotasEnforcementResponseInner().withProperties( - new GroupQuotasEnforcementResponseProperties().withEnforcementEnabled(EnforcementState.ENABLED)), - com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLocationSettingsGetSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLocationSettingsGetSamples.java deleted file mode 100644 index 1cf715450327..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLocationSettingsGetSamples.java +++ /dev/null @@ -1,26 +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.resourcemanager.quota.generated; - -/** - * Samples for GroupQuotaLocationSettings Get. - */ -public final class GroupQuotaLocationSettingsGetSamples { - /* - * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotasEnforcement/ - * GetGroupQuotaEnforcement.json - */ - /** - * Sample code: GroupQuotasEnforcement_Get. - * - * @param manager Entry point to QuotaManager. - */ - public static void groupQuotasEnforcementGet(com.azure.resourcemanager.quota.QuotaManager manager) { - manager.groupQuotaLocationSettings() - .getWithResponse("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", "eastus", - com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLocationSettingsListSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLocationSettingsListSamples.java deleted file mode 100644 index 32b5976383ef..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLocationSettingsListSamples.java +++ /dev/null @@ -1,26 +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.resourcemanager.quota.generated; - -/** - * Samples for GroupQuotaLocationSettings List. - */ -public final class GroupQuotaLocationSettingsListSamples { - /* - * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotasEnforcement/ - * ListGroupQuotaEnforcement.json - */ - /** - * Sample code: GroupQuotaEnforcement_List. - * - * @param manager Entry point to QuotaManager. - */ - public static void groupQuotaEnforcementList(com.azure.resourcemanager.quota.QuotaManager manager) { - manager.groupQuotaLocationSettings() - .list("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", - com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLocationSettingsUpdateSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLocationSettingsUpdateSamples.java deleted file mode 100644 index 46f2630df387..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaLocationSettingsUpdateSamples.java +++ /dev/null @@ -1,32 +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.resourcemanager.quota.generated; - -import com.azure.resourcemanager.quota.fluent.models.GroupQuotasEnforcementResponseInner; -import com.azure.resourcemanager.quota.models.EnforcementState; -import com.azure.resourcemanager.quota.models.GroupQuotasEnforcementResponseProperties; - -/** - * Samples for GroupQuotaLocationSettings Update. - */ -public final class GroupQuotaLocationSettingsUpdateSamples { - /* - * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotasEnforcement/ - * PatchGroupQuotaEnforcement.json - */ - /** - * Sample code: GroupQuotaLocationSettings_Patch. - * - * @param manager Entry point to QuotaManager. - */ - public static void groupQuotaLocationSettingsPatch(com.azure.resourcemanager.quota.QuotaManager manager) { - manager.groupQuotaLocationSettings() - .update("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", "eastus", - new GroupQuotasEnforcementResponseInner().withProperties( - new GroupQuotasEnforcementResponseProperties().withEnforcementEnabled(EnforcementState.ENABLED)), - com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationGetSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationGetSamples.java deleted file mode 100644 index 6b538983f519..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationGetSamples.java +++ /dev/null @@ -1,26 +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.resourcemanager.quota.generated; - -/** - * Samples for GroupQuotaSubscriptionAllocation Get. - */ -public final class GroupQuotaSubscriptionAllocationGetSamples { - /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ - * SubscriptionQuotaAllocation/SubscriptionQuotaAllocation_Get-Compute.json - */ - /** - * Sample code: SubscriptionQuotaAllocation_Get_Request_ForCompute. - * - * @param manager Entry point to QuotaManager. - */ - public static void - subscriptionQuotaAllocationGetRequestForCompute(com.azure.resourcemanager.quota.QuotaManager manager) { - manager.groupQuotaSubscriptionAllocations() - .getWithResponse("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "standardav2family", - "provider eq Microsoft.Compute & location eq westus", com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationListSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationListSamples.java index a21215305c68..b287e464ca40 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationListSamples.java +++ b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationListSamples.java @@ -9,8 +9,9 @@ */ public final class GroupQuotaSubscriptionAllocationListSamples { /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ - * SubscriptionQuotaAllocation/SubscriptionQuotaAllocation_List-Compute.json + * x-ms-original-file: + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/SubscriptionQuotaAllocation/ + * SubscriptionQuotaAllocation_List-Compute.json */ /** * Sample code: SubscriptionQuotaAllocation_List_ForCompute. @@ -19,7 +20,7 @@ public final class GroupQuotaSubscriptionAllocationListSamples { */ public static void subscriptionQuotaAllocationListForCompute(com.azure.resourcemanager.quota.QuotaManager manager) { manager.groupQuotaSubscriptionAllocations() - .list("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", - "provider eq Microsoft.Compute & location eq westus", com.azure.core.util.Context.NONE); + .listWithResponse("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", "westus", + com.azure.core.util.Context.NONE); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationRequestCreateOrUpdateSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationRequestCreateOrUpdateSamples.java deleted file mode 100644 index 6ecc5c98264b..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationRequestCreateOrUpdateSamples.java +++ /dev/null @@ -1,32 +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.resourcemanager.quota.generated; - -import com.azure.resourcemanager.quota.fluent.models.QuotaAllocationRequestStatusInner; -import com.azure.resourcemanager.quota.models.QuotaAllocationRequestBase; - -/** - * Samples for GroupQuotaSubscriptionAllocationRequest CreateOrUpdate. - */ -public final class GroupQuotaSubscriptionAllocationRequestCreateOrUpdateSamples { - /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ - * SubscriptionQuotaAllocationRequests/PutSubscriptionQuotaAllocationRequest-Compute.json - */ - /** - * Sample code: SubscriptionQuotaAllocation_Put_Request_ForCompute. - * - * @param manager Entry point to QuotaManager. - */ - public static void - subscriptionQuotaAllocationPutRequestForCompute(com.azure.resourcemanager.quota.QuotaManager manager) { - manager.groupQuotaSubscriptionAllocationRequests() - .createOrUpdate("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", - "standardav2family", - new QuotaAllocationRequestStatusInner() - .withRequestedResource(new QuotaAllocationRequestBase().withLimit(10L).withRegion("westus")), - com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationRequestGetSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationRequestGetSamples.java index d2cce84c19ac..0564850c6e1a 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationRequestGetSamples.java +++ b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationRequestGetSamples.java @@ -9,7 +9,7 @@ */ public final class GroupQuotaSubscriptionAllocationRequestGetSamples { /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ + * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/ * SubscriptionQuotaAllocationRequests/SubscriptionQuotaAllocationRequests_Get-Compute.json */ /** @@ -20,7 +20,7 @@ public final class GroupQuotaSubscriptionAllocationRequestGetSamples { public static void subscriptionQuotaAllocationRequestsGetRequestForCompute(com.azure.resourcemanager.quota.QuotaManager manager) { manager.groupQuotaSubscriptionAllocationRequests() - .getWithResponse("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", + .getWithResponse("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", "AE000000-0000-0000-0000-00000000000A", com.azure.core.util.Context.NONE); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationRequestListSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationRequestListSamples.java index fa0040f7ac97..a8bfb87bd3ef 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationRequestListSamples.java +++ b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationRequestListSamples.java @@ -9,7 +9,7 @@ */ public final class GroupQuotaSubscriptionAllocationRequestListSamples { /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ + * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/ * SubscriptionQuotaAllocationRequests/SubscriptionQuotaAllocationRequests_List-Compute.json */ /** diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationRequestUpdateSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationRequestUpdateSamples.java index bcc3a310f473..367c2d381d42 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationRequestUpdateSamples.java +++ b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationRequestUpdateSamples.java @@ -4,15 +4,18 @@ package com.azure.resourcemanager.quota.generated; -import com.azure.resourcemanager.quota.fluent.models.QuotaAllocationRequestStatusInner; -import com.azure.resourcemanager.quota.models.QuotaAllocationRequestBase; +import com.azure.resourcemanager.quota.fluent.models.SubscriptionQuotaAllocationsListInner; +import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocations; +import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocationsListProperties; +import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocationsProperties; +import java.util.Arrays; /** * Samples for GroupQuotaSubscriptionAllocationRequest Update. */ public final class GroupQuotaSubscriptionAllocationRequestUpdateSamples { /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ + * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/ * SubscriptionQuotaAllocationRequests/PatchSubscriptionQuotaAllocationRequest-Compute.json */ /** @@ -23,9 +26,15 @@ public final class GroupQuotaSubscriptionAllocationRequestUpdateSamples { public static void subscriptionQuotaAllocationPatchRequestForCompute(com.azure.resourcemanager.quota.QuotaManager manager) { manager.groupQuotaSubscriptionAllocationRequests() - .update("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", "standardav2family", - new QuotaAllocationRequestStatusInner() - .withRequestedResource(new QuotaAllocationRequestBase().withLimit(10L).withRegion("westus")), + .update("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", "westus", + new SubscriptionQuotaAllocationsListInner() + .withProperties(new SubscriptionQuotaAllocationsListProperties().withValue(Arrays.asList( + new SubscriptionQuotaAllocations().withProperties( + new SubscriptionQuotaAllocationsProperties().withResourceName("standardddv4family") + .withLimit(110L)), + new SubscriptionQuotaAllocations().withProperties( + new SubscriptionQuotaAllocationsProperties().withResourceName("standardav2family") + .withLimit(110L))))), com.azure.core.util.Context.NONE); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionRequestsGetSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionRequestsGetSamples.java index 474528e4099a..ad739ef801fb 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionRequestsGetSamples.java +++ b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionRequestsGetSamples.java @@ -10,7 +10,7 @@ public final class GroupQuotaSubscriptionRequestsGetSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/SubscriptionRequests/ + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/SubscriptionRequests/ * SubscriptionRequests_Get.json */ /** diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionRequestsListSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionRequestsListSamples.java index 32fc6c62ad65..b5dec511b807 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionRequestsListSamples.java +++ b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionRequestsListSamples.java @@ -10,7 +10,7 @@ public final class GroupQuotaSubscriptionRequestsListSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/SubscriptionRequests/ + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/SubscriptionRequests/ * SubscriptionRequests_List.json */ /** diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsCreateOrUpdateSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsCreateOrUpdateSamples.java index b6fbb156487e..0555c3649e9b 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsCreateOrUpdateSamples.java +++ b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsCreateOrUpdateSamples.java @@ -10,8 +10,8 @@ public final class GroupQuotaSubscriptionsCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotasSubscriptions - * /PutGroupQuotasSubscription.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GroupQuotasSubscriptions/ + * PutGroupQuotasSubscription.json */ /** * Sample code: GroupQuotaSubscriptions_Put_Subscriptions. diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsDeleteSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsDeleteSamples.java index 572733e2dd01..7521a08e684b 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsDeleteSamples.java +++ b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsDeleteSamples.java @@ -10,8 +10,8 @@ public final class GroupQuotaSubscriptionsDeleteSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotasSubscriptions - * /DeleteGroupQuotaSubscriptions.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GroupQuotasSubscriptions/ + * DeleteGroupQuotaSubscriptions.json */ /** * Sample code: GroupQuotaSubscriptions_Delete_Subscriptions. diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsGetSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsGetSamples.java index 3c558d8fe860..966926457151 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsGetSamples.java +++ b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsGetSamples.java @@ -10,8 +10,8 @@ public final class GroupQuotaSubscriptionsGetSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotasSubscriptions - * /GetGroupQuotaSubscriptions.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GroupQuotasSubscriptions/ + * GetGroupQuotaSubscriptions.json */ /** * Sample code: GroupQuotaSubscriptions_Get_Subscriptions. diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsListSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsListSamples.java index 0ee733f9b600..e0ff67b5db86 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsListSamples.java +++ b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsListSamples.java @@ -10,8 +10,8 @@ public final class GroupQuotaSubscriptionsListSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotasSubscriptions - * /ListGroupQuotaSubscriptions.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GroupQuotasSubscriptions/ + * ListGroupQuotaSubscriptions.json */ /** * Sample code: GroupQuotaSubscriptions_List_Subscriptions. diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsUpdateSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsUpdateSamples.java index 335a5ae6a721..12858903c674 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsUpdateSamples.java +++ b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsUpdateSamples.java @@ -10,8 +10,8 @@ public final class GroupQuotaSubscriptionsUpdateSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotasSubscriptions - * /PatchGroupQuotasSubscription.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GroupQuotasSubscriptions/ + * PatchGroupQuotasSubscription.json */ /** * Sample code: GroupQuotaSubscriptions_Patch_Subscriptions. diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaUsagesListSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaUsagesListSamples.java deleted file mode 100644 index 4903304f869c..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotaUsagesListSamples.java +++ /dev/null @@ -1,26 +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.resourcemanager.quota.generated; - -/** - * Samples for GroupQuotaUsages List. - */ -public final class GroupQuotaUsagesListSamples { - /* - * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotaUsages/ - * GetGroupQuotaUsages.json - */ - /** - * Sample code: GroupQuotasUsages_List. - * - * @param manager Entry point to QuotaManager. - */ - public static void groupQuotasUsagesList(com.azure.resourcemanager.quota.QuotaManager manager) { - manager.groupQuotaUsages() - .list("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", "Microsoft.Compute", "westus", - com.azure.core.util.Context.NONE); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotasCreateOrUpdateSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotasCreateOrUpdateSamples.java index 9eb308aad059..10cf795acbd1 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotasCreateOrUpdateSamples.java +++ b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotasCreateOrUpdateSamples.java @@ -5,11 +5,7 @@ package com.azure.resourcemanager.quota.generated; import com.azure.resourcemanager.quota.fluent.models.GroupQuotasEntityInner; -import com.azure.resourcemanager.quota.models.AdditionalAttributes; -import com.azure.resourcemanager.quota.models.EnvironmentType; -import com.azure.resourcemanager.quota.models.GroupQuotasEntityBase; -import com.azure.resourcemanager.quota.models.GroupingId; -import com.azure.resourcemanager.quota.models.GroupingIdType; +import com.azure.resourcemanager.quota.models.GroupQuotasEntityProperties; /** * Samples for GroupQuotas CreateOrUpdate. @@ -17,8 +13,7 @@ public final class GroupQuotasCreateOrUpdateSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotas/ - * PutGroupQuotas.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GroupQuotas/PutGroupQuotas.json */ /** * Sample code: GroupQuotas_Put_Request_ForCompute. @@ -29,13 +24,7 @@ public static void groupQuotasPutRequestForCompute(com.azure.resourcemanager.quo manager.groupQuotas() .createOrUpdate("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", new GroupQuotasEntityInner() - .withProperties( - new GroupQuotasEntityBase().withDisplayName("GroupQuota1") - .withAdditionalAttributes( - new AdditionalAttributes() - .withGroupId(new GroupingId().withGroupingIdType(GroupingIdType.SERVICE_TREE_ID) - .withValue("yourServiceTreeIdHere")) - .withEnvironment(EnvironmentType.PRODUCTION))), + .withProperties(new GroupQuotasEntityProperties().withDisplayName("GroupQuota1")), com.azure.core.util.Context.NONE); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotasDeleteSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotasDeleteSamples.java index 98033f68e8ae..45df2a5798f2 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotasDeleteSamples.java +++ b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotasDeleteSamples.java @@ -10,8 +10,8 @@ public final class GroupQuotasDeleteSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotas/ - * DeleteGroupQuotas.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GroupQuotas/DeleteGroupQuotas. + * json */ /** * Sample code: GroupQuotas_Delete_Request_ForCompute. diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotasGetSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotasGetSamples.java index 20b415b86f8b..c12dfe155089 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotasGetSamples.java +++ b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotasGetSamples.java @@ -10,8 +10,7 @@ public final class GroupQuotasGetSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotas/ - * GetGroupQuotas.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GroupQuotas/GetGroupQuotas.json */ /** * Sample code: GroupQuotas_Get_Request_ForCompute. diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotasListSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotasListSamples.java index fc7b473e49e4..df121ee931d6 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotasListSamples.java +++ b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotasListSamples.java @@ -10,8 +10,8 @@ public final class GroupQuotasListSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotas/ - * GetGroupQuotasList.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GroupQuotas/GetGroupQuotasList. + * json */ /** * Sample code: GroupQuotas_List_Request_ForCompute. diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotasUpdateSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotasUpdateSamples.java index cc92164179ba..966df535ea62 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotasUpdateSamples.java +++ b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/GroupQuotasUpdateSamples.java @@ -4,12 +4,8 @@ package com.azure.resourcemanager.quota.generated; -import com.azure.resourcemanager.quota.models.AdditionalAttributesPatch; -import com.azure.resourcemanager.quota.models.EnvironmentType; -import com.azure.resourcemanager.quota.models.GroupQuotasEntityBasePatch; import com.azure.resourcemanager.quota.models.GroupQuotasEntityPatch; -import com.azure.resourcemanager.quota.models.GroupingId; -import com.azure.resourcemanager.quota.models.GroupingIdType; +import com.azure.resourcemanager.quota.models.GroupQuotasEntityPatchProperties; /** * Samples for GroupQuotas Update. @@ -17,8 +13,7 @@ public final class GroupQuotasUpdateSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GroupQuotas/ - * PatchGroupQuotas.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GroupQuotas/PatchGroupQuotas.json */ /** * Sample code: GroupQuotas_Patch_Request_ForCompute. @@ -29,12 +24,7 @@ public static void groupQuotasPatchRequestForCompute(com.azure.resourcemanager.q manager.groupQuotas() .update("E7EC67B3-7657-4966-BFFC-41EFD36BAA09", "groupquota1", new GroupQuotasEntityPatch() - .withProperties( - new GroupQuotasEntityBasePatch().withDisplayName("UpdatedGroupQuota1") - .withAdditionalAttributes(new AdditionalAttributesPatch() - .withGroupId(new GroupingId().withGroupingIdType(GroupingIdType.SERVICE_TREE_ID) - .withValue("UpdatedServiceTreeIdHere")) - .withEnvironment(EnvironmentType.PRODUCTION))), + .withProperties(new GroupQuotasEntityPatchProperties().withDisplayName("UpdatedGroupQuota1")), com.azure.core.util.Context.NONE); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/QuotaCreateOrUpdateSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/QuotaCreateOrUpdateSamples.java index fdc58ef3fa55..d64dcc55ac6c 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/QuotaCreateOrUpdateSamples.java +++ b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/QuotaCreateOrUpdateSamples.java @@ -13,7 +13,7 @@ */ public final class QuotaCreateOrUpdateSamples { /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ + * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/ * putMachineLearningServicesQuotaRequestLowPriority.json */ /** @@ -34,7 +34,7 @@ public static void quotasRequestForMachineLearningServicesLowPriorityResource( } /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ + * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/ * putNetworkOneSkuQuotaRequestStandardSkuPublicIpAddresses.json */ /** @@ -55,8 +55,8 @@ public static void quotasPutRequestForNetworkStandardSkuPublicIpAddressesResourc } /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ - * putComputeOneSkuQuotaRequest.json + * x-ms-original-file: + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/putComputeOneSkuQuotaRequest.json */ /** * Sample code: Quotas_Put_Request_ForCompute. @@ -74,8 +74,8 @@ public static void quotasPutRequestForCompute(com.azure.resourcemanager.quota.Qu } /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ - * putNetworkOneSkuQuotaRequest.json + * x-ms-original-file: + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/putNetworkOneSkuQuotaRequest.json */ /** * Sample code: Quotas_PutRequest_ForNetwork. diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/QuotaGetSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/QuotaGetSamples.java index c8475fb6b723..3658366df3d3 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/QuotaGetSamples.java +++ b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/QuotaGetSamples.java @@ -9,8 +9,8 @@ */ public final class QuotaGetSamples { /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ - * getNetworkOneSkuQuotaLimit.json + * x-ms-original-file: + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/getNetworkOneSkuQuotaLimit.json */ /** * Sample code: Quotas_UsagesRequest_ForNetwork. @@ -25,8 +25,8 @@ public static void quotasUsagesRequestForNetwork(com.azure.resourcemanager.quota } /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ - * getComputeOneSkuQuotaLimit.json + * x-ms-original-file: + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/getComputeOneSkuQuotaLimit.json */ /** * Sample code: Quotas_Get_Request_ForCompute. diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/QuotaListSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/QuotaListSamples.java index 8b73cf9fb7fd..34414e60011d 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/QuotaListSamples.java +++ b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/QuotaListSamples.java @@ -9,7 +9,7 @@ */ public final class QuotaListSamples { /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ + * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/ * getMachineLearningServicesQuotaLimits.json */ /** @@ -27,8 +27,7 @@ public final class QuotaListSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/getComputeQuotaLimits. - * json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/getComputeQuotaLimits.json */ /** * Sample code: Quotas_listQuotaLimitsForCompute. @@ -43,8 +42,7 @@ public static void quotasListQuotaLimitsForCompute(com.azure.resourcemanager.quo /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/getNetworkQuotaLimits. - * json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/getNetworkQuotaLimits.json */ /** * Sample code: Quotas_listQuotaLimitsForNetwork. diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/QuotaOperationListSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/QuotaOperationListSamples.java index 2cecef0fa85b..6f5857267276 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/QuotaOperationListSamples.java +++ b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/QuotaOperationListSamples.java @@ -10,7 +10,7 @@ public final class QuotaOperationListSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/GetOperations.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/GetOperations.json */ /** * Sample code: GetOperations. diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/QuotaRequestStatusGetSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/QuotaRequestStatusGetSamples.java index ce791ab8ad17..ad1097cc136f 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/QuotaRequestStatusGetSamples.java +++ b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/QuotaRequestStatusGetSamples.java @@ -9,8 +9,8 @@ */ public final class QuotaRequestStatusGetSamples { /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ - * getQuotaRequestStatusFailed.json + * x-ms-original-file: + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/getQuotaRequestStatusFailed.json */ /** * Sample code: QuotaRequestFailed. @@ -25,8 +25,8 @@ public static void quotaRequestFailed(com.azure.resourcemanager.quota.QuotaManag } /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ - * getQuotaRequestStatusById.json + * x-ms-original-file: + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/getQuotaRequestStatusById.json */ /** * Sample code: QuotaRequestStatus. @@ -41,8 +41,9 @@ public static void quotaRequestStatus(com.azure.resourcemanager.quota.QuotaManag } /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ - * getQuotaRequestStatusInProgress.json + * x-ms-original-file: + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/getQuotaRequestStatusInProgress. + * json */ /** * Sample code: QuotaRequestInProgress. diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/QuotaRequestStatusListSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/QuotaRequestStatusListSamples.java index 6b8deb9785bf..0d4a06425652 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/QuotaRequestStatusListSamples.java +++ b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/QuotaRequestStatusListSamples.java @@ -10,8 +10,7 @@ public final class QuotaRequestStatusListSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/getQuotaRequestsHistory. - * json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/getQuotaRequestsHistory.json */ /** * Sample code: QuotaRequestHistory. diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/QuotaUpdateSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/QuotaUpdateSamples.java index 4ac488b74e6e..fa39e1cff7e0 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/QuotaUpdateSamples.java +++ b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/QuotaUpdateSamples.java @@ -15,8 +15,7 @@ public final class QuotaUpdateSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/patchComputeQuotaRequest - * .json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/patchComputeQuotaRequest.json */ /** * Sample code: Quotas_Request_PatchForCompute. @@ -36,8 +35,9 @@ public static void quotasRequestPatchForCompute(com.azure.resourcemanager.quota. } /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ - * patchNetworkOneSkuQuotaRequest.json + * x-ms-original-file: + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/patchNetworkOneSkuQuotaRequest. + * json */ /** * Sample code: Quotas_Request_PatchForNetwork. diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/UsagesGetSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/UsagesGetSamples.java index e02cc3557b33..de21d7501d09 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/UsagesGetSamples.java +++ b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/UsagesGetSamples.java @@ -10,8 +10,7 @@ public final class UsagesGetSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/getNetworkOneSkuUsages. - * json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/getNetworkOneSkuUsages.json */ /** * Sample code: Quotas_UsagesRequest_ForNetwork. @@ -27,8 +26,7 @@ public static void quotasUsagesRequestForNetwork(com.azure.resourcemanager.quota /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/getComputeOneSkuUsages. - * json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/getComputeOneSkuUsages.json */ /** * Sample code: Quotas_UsagesRequest_ForCompute. diff --git a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/UsagesListSamples.java b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/UsagesListSamples.java index 6c1a7c7fb16a..95d4419b1ec2 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/UsagesListSamples.java +++ b/sdk/quota/azure-resourcemanager-quota/src/samples/java/com/azure/resourcemanager/quota/generated/UsagesListSamples.java @@ -10,7 +10,7 @@ public final class UsagesListSamples { /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/getComputeUsages.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/getComputeUsages.json */ /** * Sample code: Quotas_listUsagesForCompute. @@ -25,7 +25,7 @@ public static void quotasListUsagesForCompute(com.azure.resourcemanager.quota.Qu /* * x-ms-original-file: - * specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/getNetworkUsages.json + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/getNetworkUsages.json */ /** * Sample code: Quotas_listUsagesForNetwork. @@ -39,8 +39,9 @@ public static void quotasListUsagesForNetwork(com.azure.resourcemanager.quota.Qu } /* - * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2023-06-01-preview/examples/ - * getMachineLearningServicesUsages.json + * x-ms-original-file: + * specification/quota/resource-manager/Microsoft.Quota/stable/2025-03-01/examples/getMachineLearningServicesUsages. + * json */ /** * Sample code: Quotas_listUsagesMachineLearningServices. diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/AdditionalAttributesPatchTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/AdditionalAttributesPatchTests.java deleted file mode 100644 index 8a834404261b..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/AdditionalAttributesPatchTests.java +++ /dev/null @@ -1,35 +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.resourcemanager.quota.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.quota.models.AdditionalAttributesPatch; -import com.azure.resourcemanager.quota.models.EnvironmentType; -import com.azure.resourcemanager.quota.models.GroupingId; -import com.azure.resourcemanager.quota.models.GroupingIdType; -import org.junit.jupiter.api.Assertions; - -public final class AdditionalAttributesPatchTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - AdditionalAttributesPatch model = BinaryData.fromString( - "{\"groupId\":{\"groupingIdType\":\"BillingId\",\"value\":\"usarhmofc\"},\"environment\":\"NonProduction\"}") - .toObject(AdditionalAttributesPatch.class); - Assertions.assertEquals(GroupingIdType.BILLING_ID, model.groupId().groupingIdType()); - Assertions.assertEquals("usarhmofc", model.groupId().value()); - Assertions.assertEquals(EnvironmentType.NON_PRODUCTION, model.environment()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - AdditionalAttributesPatch model = new AdditionalAttributesPatch() - .withGroupId(new GroupingId().withGroupingIdType(GroupingIdType.BILLING_ID).withValue("usarhmofc")) - .withEnvironment(EnvironmentType.NON_PRODUCTION); - model = BinaryData.fromObject(model).toObject(AdditionalAttributesPatch.class); - Assertions.assertEquals(GroupingIdType.BILLING_ID, model.groupId().groupingIdType()); - Assertions.assertEquals("usarhmofc", model.groupId().value()); - Assertions.assertEquals(EnvironmentType.NON_PRODUCTION, model.environment()); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/AdditionalAttributesTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/AdditionalAttributesTests.java deleted file mode 100644 index 57dd660b9a2e..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/AdditionalAttributesTests.java +++ /dev/null @@ -1,35 +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.resourcemanager.quota.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.quota.models.AdditionalAttributes; -import com.azure.resourcemanager.quota.models.EnvironmentType; -import com.azure.resourcemanager.quota.models.GroupingId; -import com.azure.resourcemanager.quota.models.GroupingIdType; -import org.junit.jupiter.api.Assertions; - -public final class AdditionalAttributesTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - AdditionalAttributes model = BinaryData.fromString( - "{\"groupId\":{\"groupingIdType\":\"ServiceTreeId\",\"value\":\"gkdmb\"},\"environment\":\"Production\"}") - .toObject(AdditionalAttributes.class); - Assertions.assertEquals(GroupingIdType.SERVICE_TREE_ID, model.groupId().groupingIdType()); - Assertions.assertEquals("gkdmb", model.groupId().value()); - Assertions.assertEquals(EnvironmentType.PRODUCTION, model.environment()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - AdditionalAttributes model = new AdditionalAttributes() - .withGroupId(new GroupingId().withGroupingIdType(GroupingIdType.SERVICE_TREE_ID).withValue("gkdmb")) - .withEnvironment(EnvironmentType.PRODUCTION); - model = BinaryData.fromObject(model).toObject(AdditionalAttributes.class); - Assertions.assertEquals(GroupingIdType.SERVICE_TREE_ID, model.groupId().groupingIdType()); - Assertions.assertEquals("gkdmb", model.groupId().value()); - Assertions.assertEquals(EnvironmentType.PRODUCTION, model.environment()); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/AllocatedQuotaToSubscriptionListTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/AllocatedQuotaToSubscriptionListTests.java index a887c013d16e..f804bb56859b 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/AllocatedQuotaToSubscriptionListTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/AllocatedQuotaToSubscriptionListTests.java @@ -14,21 +14,19 @@ public final class AllocatedQuotaToSubscriptionListTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { AllocatedQuotaToSubscriptionList model = BinaryData.fromString( - "{\"value\":[{\"subscriptionId\":\"qw\",\"quotaAllocated\":1046762399333359388},{\"subscriptionId\":\"bbjfddgmbmbexp\",\"quotaAllocated\":313278106119438402},{\"subscriptionId\":\"qrolfpf\",\"quotaAllocated\":5108229152426032776},{\"subscriptionId\":\"bquxigjy\",\"quotaAllocated\":3662129632751771998}]}") + "{\"value\":[{\"subscriptionId\":\"dfvzwdzuhty\",\"quotaAllocated\":7933168556425721476},{\"subscriptionId\":\"kfthwxmntei\",\"quotaAllocated\":320495050152534005}]}") .toObject(AllocatedQuotaToSubscriptionList.class); - Assertions.assertEquals("qw", model.value().get(0).subscriptionId()); - Assertions.assertEquals(1046762399333359388L, model.value().get(0).quotaAllocated()); + Assertions.assertEquals("dfvzwdzuhty", model.value().get(0).subscriptionId()); + Assertions.assertEquals(7933168556425721476L, model.value().get(0).quotaAllocated()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { AllocatedQuotaToSubscriptionList model = new AllocatedQuotaToSubscriptionList().withValue(Arrays.asList( - new AllocatedToSubscription().withSubscriptionId("qw").withQuotaAllocated(1046762399333359388L), - new AllocatedToSubscription().withSubscriptionId("bbjfddgmbmbexp").withQuotaAllocated(313278106119438402L), - new AllocatedToSubscription().withSubscriptionId("qrolfpf").withQuotaAllocated(5108229152426032776L), - new AllocatedToSubscription().withSubscriptionId("bquxigjy").withQuotaAllocated(3662129632751771998L))); + new AllocatedToSubscription().withSubscriptionId("dfvzwdzuhty").withQuotaAllocated(7933168556425721476L), + new AllocatedToSubscription().withSubscriptionId("kfthwxmntei").withQuotaAllocated(320495050152534005L))); model = BinaryData.fromObject(model).toObject(AllocatedQuotaToSubscriptionList.class); - Assertions.assertEquals("qw", model.value().get(0).subscriptionId()); - Assertions.assertEquals(1046762399333359388L, model.value().get(0).quotaAllocated()); + Assertions.assertEquals("dfvzwdzuhty", model.value().get(0).subscriptionId()); + Assertions.assertEquals(7933168556425721476L, model.value().get(0).quotaAllocated()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/AllocatedToSubscriptionTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/AllocatedToSubscriptionTests.java index bf7fd5d83d74..7c0610065489 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/AllocatedToSubscriptionTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/AllocatedToSubscriptionTests.java @@ -12,18 +12,18 @@ public final class AllocatedToSubscriptionTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { AllocatedToSubscription model - = BinaryData.fromString("{\"subscriptionId\":\"o\",\"quotaAllocated\":1618958611063103358}") + = BinaryData.fromString("{\"subscriptionId\":\"km\",\"quotaAllocated\":400256039619718392}") .toObject(AllocatedToSubscription.class); - Assertions.assertEquals("o", model.subscriptionId()); - Assertions.assertEquals(1618958611063103358L, model.quotaAllocated()); + Assertions.assertEquals("km", model.subscriptionId()); + Assertions.assertEquals(400256039619718392L, model.quotaAllocated()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { AllocatedToSubscription model - = new AllocatedToSubscription().withSubscriptionId("o").withQuotaAllocated(1618958611063103358L); + = new AllocatedToSubscription().withSubscriptionId("km").withQuotaAllocated(400256039619718392L); model = BinaryData.fromObject(model).toObject(AllocatedToSubscription.class); - Assertions.assertEquals("o", model.subscriptionId()); - Assertions.assertEquals(1618958611063103358L, model.quotaAllocated()); + Assertions.assertEquals("km", model.subscriptionId()); + Assertions.assertEquals(400256039619718392L, model.quotaAllocated()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/CurrentQuotaLimitBaseInnerTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/CurrentQuotaLimitBaseInnerTests.java index 34e2c03512bf..cb1bdc39bbde 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/CurrentQuotaLimitBaseInnerTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/CurrentQuotaLimitBaseInnerTests.java @@ -15,21 +15,21 @@ public final class CurrentQuotaLimitBaseInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { CurrentQuotaLimitBaseInner model = BinaryData.fromString( - "{\"properties\":{\"limit\":{\"limitObjectType\":\"LimitJsonObject\"},\"unit\":\"qzrnkcqvyxlwhz\",\"name\":{\"value\":\"cohoq\",\"localizedValue\":\"wvl\"},\"resourceType\":\"avwhheunm\",\"quotaPeriod\":\"hgyxzkonoc\",\"isQuotaApplicable\":true,\"properties\":\"datalyaxuc\"},\"id\":\"nuqszfkbey\",\"name\":\"ewrmjmwvvjektc\",\"type\":\"senhwlrs\"}") + "{\"properties\":{\"limit\":{\"limitObjectType\":\"LimitJsonObject\"},\"unit\":\"ohoqqnwvlryav\",\"name\":{\"value\":\"eun\",\"localizedValue\":\"qhgyxzkonocukok\"},\"resourceType\":\"axuconuq\",\"quotaPeriod\":\"fkbey\",\"isQuotaApplicable\":true,\"properties\":\"datamjmwvvjektcx\"},\"id\":\"enhwlrs\",\"name\":\"frzpwvlqdqgb\",\"type\":\"qylihkaetckt\"}") .toObject(CurrentQuotaLimitBaseInner.class); - Assertions.assertEquals("cohoq", model.properties().name().value()); - Assertions.assertEquals("avwhheunm", model.properties().resourceType()); + Assertions.assertEquals("eun", model.properties().name().value()); + Assertions.assertEquals("axuconuq", model.properties().resourceType()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { CurrentQuotaLimitBaseInner model = new CurrentQuotaLimitBaseInner().withProperties(new QuotaProperties().withLimit(new LimitJsonObject()) - .withName(new ResourceName().withValue("cohoq")) - .withResourceType("avwhheunm") - .withProperties("datalyaxuc")); + .withName(new ResourceName().withValue("eun")) + .withResourceType("axuconuq") + .withProperties("datamjmwvvjektcx")); model = BinaryData.fromObject(model).toObject(CurrentQuotaLimitBaseInner.class); - Assertions.assertEquals("cohoq", model.properties().name().value()); - Assertions.assertEquals("avwhheunm", model.properties().resourceType()); + Assertions.assertEquals("eun", model.properties().name().value()); + Assertions.assertEquals("axuconuq", model.properties().resourceType()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/CurrentUsagesBaseInnerTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/CurrentUsagesBaseInnerTests.java index 87fd833753a8..307c6910483d 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/CurrentUsagesBaseInnerTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/CurrentUsagesBaseInnerTests.java @@ -16,25 +16,25 @@ public final class CurrentUsagesBaseInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { CurrentUsagesBaseInner model = BinaryData.fromString( - "{\"properties\":{\"usages\":{\"value\":206207279,\"usagesType\":\"Combined\"},\"unit\":\"hrk\",\"name\":{\"value\":\"wwzjuqkhrsajiwku\",\"localizedValue\":\"oskg\"},\"resourceType\":\"auu\",\"quotaPeriod\":\"jmvxie\",\"isQuotaApplicable\":false,\"properties\":\"dataidyjrrfbyaosvexc\"},\"id\":\"onpc\",\"name\":\"hocohslkev\",\"type\":\"eggzfb\"}") + "{\"properties\":{\"usages\":{\"value\":1709538743,\"usagesType\":\"Combined\"},\"unit\":\"pfhyhl\",\"name\":{\"value\":\"mopjmc\",\"localizedValue\":\"tuo\"},\"resourceType\":\"hfuiuaodsfc\",\"quotaPeriod\":\"vxodpu\",\"isQuotaApplicable\":true,\"properties\":\"datazydagfuaxbezyiuo\"},\"id\":\"ktwh\",\"name\":\"dxwzywqsmbsurexi\",\"type\":\"o\"}") .toObject(CurrentUsagesBaseInner.class); - Assertions.assertEquals(206207279, model.properties().usages().value()); + Assertions.assertEquals(1709538743, model.properties().usages().value()); Assertions.assertEquals(UsagesTypes.COMBINED, model.properties().usages().usagesType()); - Assertions.assertEquals("wwzjuqkhrsajiwku", model.properties().name().value()); - Assertions.assertEquals("auu", model.properties().resourceType()); + Assertions.assertEquals("mopjmc", model.properties().name().value()); + Assertions.assertEquals("hfuiuaodsfc", model.properties().resourceType()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { CurrentUsagesBaseInner model = new CurrentUsagesBaseInner().withProperties(new UsagesProperties() - .withUsages(new UsagesObject().withValue(206207279).withUsagesType(UsagesTypes.COMBINED)) - .withName(new ResourceName().withValue("wwzjuqkhrsajiwku")) - .withResourceType("auu") - .withProperties("dataidyjrrfbyaosvexc")); + .withUsages(new UsagesObject().withValue(1709538743).withUsagesType(UsagesTypes.COMBINED)) + .withName(new ResourceName().withValue("mopjmc")) + .withResourceType("hfuiuaodsfc") + .withProperties("datazydagfuaxbezyiuo")); model = BinaryData.fromObject(model).toObject(CurrentUsagesBaseInner.class); - Assertions.assertEquals(206207279, model.properties().usages().value()); + Assertions.assertEquals(1709538743, model.properties().usages().value()); Assertions.assertEquals(UsagesTypes.COMBINED, model.properties().usages().usagesType()); - Assertions.assertEquals("wwzjuqkhrsajiwku", model.properties().name().value()); - Assertions.assertEquals("auu", model.properties().resourceType()); + Assertions.assertEquals("mopjmc", model.properties().name().value()); + Assertions.assertEquals("hfuiuaodsfc", model.properties().resourceType()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaDetailsNameTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaDetailsNameTests.java index 3d262447e5cb..6521b522b369 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaDetailsNameTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaDetailsNameTests.java @@ -11,7 +11,7 @@ public final class GroupQuotaDetailsNameTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { GroupQuotaDetailsName model - = BinaryData.fromString("{\"value\":\"kwtmutduqktapspw\",\"localizedValue\":\"uertumk\"}") + = BinaryData.fromString("{\"value\":\"nguitnwuizgazxu\",\"localizedValue\":\"zuckyfi\"}") .toObject(GroupQuotaDetailsName.class); } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaDetailsTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaDetailsTests.java index f349cc0dacc4..db6d969ca06f 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaDetailsTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaDetailsTests.java @@ -12,20 +12,21 @@ public final class GroupQuotaDetailsTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { GroupQuotaDetails model = BinaryData.fromString( - "{\"region\":\"yxolniwp\",\"limit\":4659788042682990061,\"comment\":\"fkgiawxk\",\"name\":{\"value\":\"plwckbas\",\"localizedValue\":\"pnddhsgcbacphejk\"},\"unit\":\"ynqgoulzndlikwyq\",\"availableLimit\":3834014588009600234,\"allocatedToSubscriptions\":{\"value\":[{\"subscriptionId\":\"dgak\",\"quotaAllocated\":801620479699597544},{\"subscriptionId\":\"yb\",\"quotaAllocated\":7229748892246039848},{\"subscriptionId\":\"qytbciq\",\"quotaAllocated\":5348039389469426548},{\"subscriptionId\":\"mmnkzsmodmgl\",\"quotaAllocated\":800844315358769757}]}}") + "{\"resourceName\":\"ol\",\"limit\":728427044151085646,\"comment\":\"algbquxigjyjg\",\"unit\":\"aoyfhrtxilnerkuj\",\"name\":{\"value\":\"l\",\"localizedValue\":\"uvfqawrlyxwj\"},\"availableLimit\":4891061322345208982,\"allocatedToSubscriptions\":{\"value\":[{\"subscriptionId\":\"xgjvtbv\",\"quotaAllocated\":7661305214436261701},{\"subscriptionId\":\"dnrujqguhmuouqfp\",\"quotaAllocated\":1346703559786740146}]}}") .toObject(GroupQuotaDetails.class); - Assertions.assertEquals("yxolniwp", model.region()); - Assertions.assertEquals(4659788042682990061L, model.limit()); - Assertions.assertEquals("fkgiawxk", model.comment()); + Assertions.assertEquals("ol", model.resourceName()); + Assertions.assertEquals(728427044151085646L, model.limit()); + Assertions.assertEquals("algbquxigjyjg", model.comment()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - GroupQuotaDetails model - = new GroupQuotaDetails().withRegion("yxolniwp").withLimit(4659788042682990061L).withComment("fkgiawxk"); + GroupQuotaDetails model = new GroupQuotaDetails().withResourceName("ol") + .withLimit(728427044151085646L) + .withComment("algbquxigjyjg"); model = BinaryData.fromObject(model).toObject(GroupQuotaDetails.class); - Assertions.assertEquals("yxolniwp", model.region()); - Assertions.assertEquals(4659788042682990061L, model.limit()); - Assertions.assertEquals("fkgiawxk", model.comment()); + Assertions.assertEquals("ol", model.resourceName()); + Assertions.assertEquals(728427044151085646L, model.limit()); + Assertions.assertEquals("algbquxigjyjg", model.comment()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitInnerTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitInnerTests.java deleted file mode 100644 index f48c8ad94a06..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitInnerTests.java +++ /dev/null @@ -1,34 +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.resourcemanager.quota.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.quota.fluent.models.GroupQuotaLimitInner; -import com.azure.resourcemanager.quota.models.GroupQuotaDetails; -import org.junit.jupiter.api.Assertions; - -public final class GroupQuotaLimitInnerTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - GroupQuotaLimitInner model = BinaryData.fromString( - "{\"properties\":{\"region\":\"lljfmppeeb\",\"limit\":8706154927582120085,\"comment\":\"abkyqduujitcjcz\",\"name\":{\"value\":\"vndhkrwpdapp\",\"localizedValue\":\"bdkvwrwjf\"},\"unit\":\"snhu\",\"availableLimit\":8316497364859549457,\"allocatedToSubscriptions\":{\"value\":[{\"subscriptionId\":\"dhugjzzdatqxhocd\",\"quotaAllocated\":6124720690477162345}]}},\"id\":\"gphuticndvka\",\"name\":\"zwyiftyhxhur\",\"type\":\"k\"}") - .toObject(GroupQuotaLimitInner.class); - Assertions.assertEquals("lljfmppeeb", model.properties().region()); - Assertions.assertEquals(8706154927582120085L, model.properties().limit()); - Assertions.assertEquals("abkyqduujitcjcz", model.properties().comment()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - GroupQuotaLimitInner model - = new GroupQuotaLimitInner().withProperties(new GroupQuotaDetails().withRegion("lljfmppeeb") - .withLimit(8706154927582120085L) - .withComment("abkyqduujitcjcz")); - model = BinaryData.fromObject(model).toObject(GroupQuotaLimitInner.class); - Assertions.assertEquals("lljfmppeeb", model.properties().region()); - Assertions.assertEquals(8706154927582120085L, model.properties().limit()); - Assertions.assertEquals("abkyqduujitcjcz", model.properties().comment()); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitListInnerTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitListInnerTests.java new file mode 100644 index 000000000000..6345eb57a5e5 --- /dev/null +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitListInnerTests.java @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.quota.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.quota.fluent.models.GroupQuotaLimitListInner; +import com.azure.resourcemanager.quota.models.GroupQuotaLimit; +import com.azure.resourcemanager.quota.models.GroupQuotaLimitListProperties; +import com.azure.resourcemanager.quota.models.GroupQuotaLimitProperties; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class GroupQuotaLimitListInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + GroupQuotaLimitListInner model = BinaryData.fromString( + "{\"properties\":{\"provisioningState\":\"Canceled\",\"value\":[{\"properties\":{\"resourceName\":\"xpaojakhmsbz\",\"limit\":2192126563466196128,\"comment\":\"evdphlxaol\",\"unit\":\"qtrgqjbpfzfsinzg\",\"name\":{\"value\":\"jrwzox\",\"localizedValue\":\"tfell\"},\"availableLimit\":5924201566480225751,\"allocatedToSubscriptions\":{\"value\":[{},{},{},{}]}}},{\"properties\":{\"resourceName\":\"eqfpj\",\"limit\":8695706815258884351,\"comment\":\"fpdvhpfxxypi\",\"unit\":\"nmayhuybb\",\"name\":{\"value\":\"depoog\",\"localizedValue\":\"uvamiheognarxzxt\"},\"availableLimit\":955954291018869840,\"allocatedToSubscriptions\":{\"value\":[{},{},{},{}]}}},{\"properties\":{\"resourceName\":\"evcciqihnhun\",\"limit\":4957035002722095413,\"comment\":\"rnfygxgispem\",\"unit\":\"zfkufubljofx\",\"name\":{\"value\":\"fjaeq\",\"localizedValue\":\"qjbasvms\"},\"availableLimit\":8387185057930891317,\"allocatedToSubscriptions\":{\"value\":[{},{},{},{}]}}},{\"properties\":{\"resourceName\":\"tnb\",\"limit\":454639632917267725,\"comment\":\"cwrwclxxwrljdous\",\"unit\":\"qvkoc\",\"name\":{\"value\":\"dkwt\",\"localizedValue\":\"xbnjbiksq\"},\"availableLimit\":5232113112996361518,\"allocatedToSubscriptions\":{\"value\":[{},{},{}]}}}],\"nextLink\":\"qpjwnzlljfm\"},\"id\":\"eebvmgxsab\",\"name\":\"yqduujit\",\"type\":\"jczdzevndh\"}") + .toObject(GroupQuotaLimitListInner.class); + Assertions.assertEquals("xpaojakhmsbz", model.properties().value().get(0).properties().resourceName()); + Assertions.assertEquals(2192126563466196128L, model.properties().value().get(0).properties().limit()); + Assertions.assertEquals("evdphlxaol", model.properties().value().get(0).properties().comment()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + GroupQuotaLimitListInner model + = new GroupQuotaLimitListInner().withProperties(new GroupQuotaLimitListProperties().withValue(Arrays.asList( + new GroupQuotaLimit().withProperties(new GroupQuotaLimitProperties().withResourceName("xpaojakhmsbz") + .withLimit(2192126563466196128L) + .withComment("evdphlxaol")), + new GroupQuotaLimit().withProperties(new GroupQuotaLimitProperties().withResourceName("eqfpj") + .withLimit(8695706815258884351L) + .withComment("fpdvhpfxxypi")), + new GroupQuotaLimit().withProperties(new GroupQuotaLimitProperties().withResourceName("evcciqihnhun") + .withLimit(4957035002722095413L) + .withComment("rnfygxgispem")), + new GroupQuotaLimit().withProperties(new GroupQuotaLimitProperties().withResourceName("tnb") + .withLimit(454639632917267725L) + .withComment("cwrwclxxwrljdous"))))); + model = BinaryData.fromObject(model).toObject(GroupQuotaLimitListInner.class); + Assertions.assertEquals("xpaojakhmsbz", model.properties().value().get(0).properties().resourceName()); + Assertions.assertEquals(2192126563466196128L, model.properties().value().get(0).properties().limit()); + Assertions.assertEquals("evdphlxaol", model.properties().value().get(0).properties().comment()); + } +} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitListPropertiesTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitListPropertiesTests.java new file mode 100644 index 000000000000..48eb8d175eab --- /dev/null +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitListPropertiesTests.java @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.quota.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.quota.models.GroupQuotaLimit; +import com.azure.resourcemanager.quota.models.GroupQuotaLimitListProperties; +import com.azure.resourcemanager.quota.models.GroupQuotaLimitProperties; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class GroupQuotaLimitListPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + GroupQuotaLimitListProperties model = BinaryData.fromString( + "{\"provisioningState\":\"Succeeded\",\"value\":[{\"properties\":{\"resourceName\":\"p\",\"limit\":1133977935243283370,\"comment\":\"vwrwj\",\"unit\":\"usnhutje\",\"name\":{\"value\":\"rl\",\"localizedValue\":\"ugjzzdatqxhocdge\"},\"availableLimit\":5556090733611514478,\"allocatedToSubscriptions\":{\"value\":[{},{},{},{}]}}}],\"nextLink\":\"icndvkaozwyifty\"}") + .toObject(GroupQuotaLimitListProperties.class); + Assertions.assertEquals("p", model.value().get(0).properties().resourceName()); + Assertions.assertEquals(1133977935243283370L, model.value().get(0).properties().limit()); + Assertions.assertEquals("vwrwj", model.value().get(0).properties().comment()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + GroupQuotaLimitListProperties model = new GroupQuotaLimitListProperties().withValue( + Arrays.asList(new GroupQuotaLimit().withProperties(new GroupQuotaLimitProperties().withResourceName("p") + .withLimit(1133977935243283370L) + .withComment("vwrwj")))); + model = BinaryData.fromObject(model).toObject(GroupQuotaLimitListProperties.class); + Assertions.assertEquals("p", model.value().get(0).properties().resourceName()); + Assertions.assertEquals(1133977935243283370L, model.value().get(0).properties().limit()); + Assertions.assertEquals("vwrwj", model.value().get(0).properties().comment()); + } +} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitListTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitListTests.java deleted file mode 100644 index 115d352cc960..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitListTests.java +++ /dev/null @@ -1,37 +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.resourcemanager.quota.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.quota.fluent.models.GroupQuotaLimitInner; -import com.azure.resourcemanager.quota.models.GroupQuotaDetails; -import com.azure.resourcemanager.quota.models.GroupQuotaLimitList; -import java.util.Arrays; -import org.junit.jupiter.api.Assertions; - -public final class GroupQuotaLimitListTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - GroupQuotaLimitList model = BinaryData.fromString( - "{\"value\":[{\"properties\":{\"region\":\"n\",\"limit\":5477626889722442552,\"comment\":\"ysvlejuvf\",\"name\":{\"value\":\"rlyxwjkcprbnw\",\"localizedValue\":\"gjvtbv\"},\"unit\":\"sszdnru\",\"availableLimit\":3086796418296040300,\"allocatedToSubscriptions\":{\"value\":[{}]}},\"id\":\"uqfprwzw\",\"name\":\"nguitnwuizgazxu\",\"type\":\"izuckyfihrfidfvz\"},{\"properties\":{\"region\":\"uht\",\"limit\":7093196131799680709,\"comment\":\"dkfthwxmnt\",\"name\":{\"value\":\"aop\",\"localizedValue\":\"mijcmmxdcufufs\"},\"unit\":\"ymzidn\",\"availableLimit\":6857493203334050846,\"allocatedToSubscriptions\":{\"value\":[{},{},{}]}},\"id\":\"sgfyccsnew\",\"name\":\"dwzjeiach\",\"type\":\"oosflnr\"}],\"nextLink\":\"fqpte\"}") - .toObject(GroupQuotaLimitList.class); - Assertions.assertEquals("n", model.value().get(0).properties().region()); - Assertions.assertEquals(5477626889722442552L, model.value().get(0).properties().limit()); - Assertions.assertEquals("ysvlejuvf", model.value().get(0).properties().comment()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - GroupQuotaLimitList model = new GroupQuotaLimitList().withValue(Arrays.asList( - new GroupQuotaLimitInner().withProperties( - new GroupQuotaDetails().withRegion("n").withLimit(5477626889722442552L).withComment("ysvlejuvf")), - new GroupQuotaLimitInner().withProperties( - new GroupQuotaDetails().withRegion("uht").withLimit(7093196131799680709L).withComment("dkfthwxmnt")))); - model = BinaryData.fromObject(model).toObject(GroupQuotaLimitList.class); - Assertions.assertEquals("n", model.value().get(0).properties().region()); - Assertions.assertEquals(5477626889722442552L, model.value().get(0).properties().limit()); - Assertions.assertEquals("ysvlejuvf", model.value().get(0).properties().comment()); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitPropertiesTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitPropertiesTests.java new file mode 100644 index 000000000000..943381ee92bf --- /dev/null +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitPropertiesTests.java @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.quota.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.quota.models.GroupQuotaLimitProperties; +import org.junit.jupiter.api.Assertions; + +public final class GroupQuotaLimitPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + GroupQuotaLimitProperties model = BinaryData.fromString( + "{\"resourceName\":\"fgibmadgakeq\",\"limit\":4098961683533013138,\"comment\":\"zqqedq\",\"unit\":\"bciqfouflm\",\"name\":{\"value\":\"zsm\",\"localizedValue\":\"mglougpbkw\"},\"availableLimit\":7027727975634894937,\"allocatedToSubscriptions\":{\"value\":[{\"subscriptionId\":\"ta\",\"quotaAllocated\":52315490134475287},{\"subscriptionId\":\"cuertu\",\"quotaAllocated\":7897278653566127978},{\"subscriptionId\":\"vqwhbmdgbbjfd\",\"quotaAllocated\":1280362688253546892},{\"subscriptionId\":\"bexppb\",\"quotaAllocated\":907638754546671193}]}}") + .toObject(GroupQuotaLimitProperties.class); + Assertions.assertEquals("fgibmadgakeq", model.resourceName()); + Assertions.assertEquals(4098961683533013138L, model.limit()); + Assertions.assertEquals("zqqedq", model.comment()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + GroupQuotaLimitProperties model = new GroupQuotaLimitProperties().withResourceName("fgibmadgakeq") + .withLimit(4098961683533013138L) + .withComment("zqqedq"); + model = BinaryData.fromObject(model).toObject(GroupQuotaLimitProperties.class); + Assertions.assertEquals("fgibmadgakeq", model.resourceName()); + Assertions.assertEquals(4098961683533013138L, model.limit()); + Assertions.assertEquals("zqqedq", model.comment()); + } +} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitTests.java new file mode 100644 index 000000000000..a4737c50c5a6 --- /dev/null +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitTests.java @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.quota.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.quota.models.GroupQuotaLimit; +import com.azure.resourcemanager.quota.models.GroupQuotaLimitProperties; +import org.junit.jupiter.api.Assertions; + +public final class GroupQuotaLimitTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + GroupQuotaLimit model = BinaryData.fromString( + "{\"properties\":{\"resourceName\":\"urokft\",\"limit\":3868150209180294588,\"comment\":\"iwpwcuk\",\"unit\":\"kgiawxklryplwck\",\"name\":{\"value\":\"yypnddhsgcbacphe\",\"localizedValue\":\"ot\"},\"availableLimit\":9089023115541451089,\"allocatedToSubscriptions\":{\"value\":[{\"subscriptionId\":\"ndlik\",\"quotaAllocated\":1140250228405168}]}}}") + .toObject(GroupQuotaLimit.class); + Assertions.assertEquals("urokft", model.properties().resourceName()); + Assertions.assertEquals(3868150209180294588L, model.properties().limit()); + Assertions.assertEquals("iwpwcuk", model.properties().comment()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + GroupQuotaLimit model + = new GroupQuotaLimit().withProperties(new GroupQuotaLimitProperties().withResourceName("urokft") + .withLimit(3868150209180294588L) + .withComment("iwpwcuk")); + model = BinaryData.fromObject(model).toObject(GroupQuotaLimit.class); + Assertions.assertEquals("urokft", model.properties().resourceName()); + Assertions.assertEquals(3868150209180294588L, model.properties().limit()); + Assertions.assertEquals("iwpwcuk", model.properties().comment()); + } +} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsGetWithResponseMockTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsGetWithResponseMockTests.java deleted file mode 100644 index 93fe192951fd..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsGetWithResponseMockTests.java +++ /dev/null @@ -1,42 +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.resourcemanager.quota.generated; - -import com.azure.core.credential.AccessToken; -import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.profile.AzureProfile; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.resourcemanager.quota.QuotaManager; -import com.azure.resourcemanager.quota.models.GroupQuotaLimit; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -public final class GroupQuotaLimitsGetWithResponseMockTests { - @Test - public void testGetWithResponse() throws Exception { - String responseStr - = "{\"properties\":{\"region\":\"nayqi\",\"limit\":6131994767406394779,\"comment\":\"havhqlkthumaqolb\",\"name\":{\"value\":\"duiertgcc\",\"localizedValue\":\"vaolpsslqlf\"},\"unit\":\"dnbbglzps\",\"availableLimit\":5564635396435851396,\"allocatedToSubscriptions\":{\"value\":[{\"subscriptionId\":\"hzdxssadbzm\",\"quotaAllocated\":2094895457348601171},{\"subscriptionId\":\"n\",\"quotaAllocated\":1939763512135424116}]}},\"id\":\"vxzbncb\",\"name\":\"ylpstdbhhxsrzdz\",\"type\":\"cers\"}"; - - HttpClient httpClient - = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); - QuotaManager manager = QuotaManager.configure() - .withHttpClient(httpClient) - .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); - - GroupQuotaLimit response = manager.groupQuotaLimits() - .getWithResponse("taruoujmkcj", "wqytjrybnwjewgdr", "ervnaenqpehi", "doy", "mifthnzdnd", - com.azure.core.util.Context.NONE) - .getValue(); - - Assertions.assertEquals("nayqi", response.properties().region()); - Assertions.assertEquals(6131994767406394779L, response.properties().limit()); - Assertions.assertEquals("havhqlkthumaqolb", response.properties().comment()); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsListMockTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsListMockTests.java deleted file mode 100644 index 8e6a56f2e324..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsListMockTests.java +++ /dev/null @@ -1,41 +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.resourcemanager.quota.generated; - -import com.azure.core.credential.AccessToken; -import com.azure.core.http.HttpClient; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.profile.AzureProfile; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.resourcemanager.quota.QuotaManager; -import com.azure.resourcemanager.quota.models.GroupQuotaLimit; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -public final class GroupQuotaLimitsListMockTests { - @Test - public void testList() throws Exception { - String responseStr - = "{\"value\":[{\"properties\":{\"region\":\"weriofzpyqsem\",\"limit\":7559264864950811898,\"comment\":\"tshhszhedp\",\"name\":{\"value\":\"iwubmwmbesldnk\",\"localizedValue\":\"tppjflcx\"},\"unit\":\"aokonzmnsik\",\"availableLimit\":4352288907832795001,\"allocatedToSubscriptions\":{\"value\":[{\"subscriptionId\":\"kdltfzxmhhvhg\",\"quotaAllocated\":1046388892732212968},{\"subscriptionId\":\"kwobdagxtibq\",\"quotaAllocated\":8983172465678034803},{\"subscriptionId\":\"akbogqxndlkzgxh\",\"quotaAllocated\":8267760773772711252},{\"subscriptionId\":\"bpodxunkbebxm\",\"quotaAllocated\":5789185793221344217}]}},\"id\":\"twlrbqt\",\"name\":\"oievseotgqrlltm\",\"type\":\"wlauwzizxbmpg\"}]}"; - - HttpClient httpClient - = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); - QuotaManager manager = QuotaManager.configure() - .withHttpClient(httpClient) - .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); - - PagedIterable response - = manager.groupQuotaLimits().list("dntnevf", "wjmy", "tdss", "s", com.azure.core.util.Context.NONE); - - Assertions.assertEquals("weriofzpyqsem", response.iterator().next().properties().region()); - Assertions.assertEquals(7559264864950811898L, response.iterator().next().properties().limit()); - Assertions.assertEquals("tshhszhedp", response.iterator().next().properties().comment()); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsListWithResponseMockTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsListWithResponseMockTests.java new file mode 100644 index 000000000000..ee5ea6748713 --- /dev/null +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsListWithResponseMockTests.java @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.quota.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.quota.QuotaManager; +import com.azure.resourcemanager.quota.models.GroupQuotaLimitList; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class GroupQuotaLimitsListWithResponseMockTests { + @Test + public void testListWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"provisioningState\":\"Succeeded\",\"value\":[{\"properties\":{\"resourceName\":\"wmbesldnkw\",\"limit\":1517331756853567290,\"comment\":\"flcxoga\",\"unit\":\"onz\",\"name\":{},\"availableLimit\":2991398819380628456,\"allocatedToSubscriptions\":{}}},{\"properties\":{\"resourceName\":\"qzeqqkdltfzxm\",\"limit\":740779033834050622,\"comment\":\"ur\",\"unit\":\"dkwobdagx\",\"name\":{},\"availableLimit\":7711420344128490365,\"allocatedToSubscriptions\":{}}},{\"properties\":{\"resourceName\":\"wakbogqxndl\",\"limit\":1285418562522553116,\"comment\":\"uriplbpodxunkb\",\"unit\":\"xmubyyntwlrbq\",\"name\":{},\"availableLimit\":5325989537009881693,\"allocatedToSubscriptions\":{}}}],\"nextLink\":\"eotg\"},\"id\":\"l\",\"name\":\"tmuwlauwzi\",\"type\":\"xbmp\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + QuotaManager manager = QuotaManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + GroupQuotaLimitList response = manager.groupQuotaLimits() + .listWithResponse("ofz", "yqsemwa", "n", "tshhszhedp", com.azure.core.util.Context.NONE) + .getValue(); + + Assertions.assertEquals("wmbesldnkw", response.properties().value().get(0).properties().resourceName()); + Assertions.assertEquals(1517331756853567290L, response.properties().value().get(0).properties().limit()); + Assertions.assertEquals("flcxoga", response.properties().value().get(0).properties().comment()); + } +} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsRequestsUpdateMockTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsRequestsUpdateMockTests.java new file mode 100644 index 000000000000..e61ee40a8e52 --- /dev/null +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaLimitsRequestsUpdateMockTests.java @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.quota.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.quota.QuotaManager; +import com.azure.resourcemanager.quota.fluent.models.GroupQuotaLimitListInner; +import com.azure.resourcemanager.quota.models.GroupQuotaLimit; +import com.azure.resourcemanager.quota.models.GroupQuotaLimitList; +import com.azure.resourcemanager.quota.models.GroupQuotaLimitListProperties; +import com.azure.resourcemanager.quota.models.GroupQuotaLimitProperties; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class GroupQuotaLimitsRequestsUpdateMockTests { + @Test + public void testUpdate() throws Exception { + String responseStr + = "{\"properties\":{\"provisioningState\":\"Succeeded\",\"value\":[{\"properties\":{\"resourceName\":\"n\",\"limit\":6645046241079336375,\"comment\":\"krtswbxqz\",\"unit\":\"zjf\",\"name\":{},\"availableLimit\":147411949012367890,\"allocatedToSubscriptions\":{}}},{\"properties\":{\"resourceName\":\"ivetvtcq\",\"limit\":3137986994872936614,\"comment\":\"qmcbxvwvxyslqbhs\",\"unit\":\"obl\",\"name\":{},\"availableLimit\":8821646723184751795,\"allocatedToSubscriptions\":{}}},{\"properties\":{\"resourceName\":\"wwwfbkr\",\"limit\":3908578506994645119,\"comment\":\"shqjohxcrsbf\",\"unit\":\"asrru\",\"name\":{},\"availableLimit\":9213990294223427282,\"allocatedToSubscriptions\":{}}}],\"nextLink\":\"sub\"},\"id\":\"jbi\",\"name\":\"xb\",\"type\":\"ybsrfbjfdtwss\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + QuotaManager manager = QuotaManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + GroupQuotaLimitList response = manager.groupQuotaLimitsRequests() + .update("tfolhbnx", "nalaulppg", "dtpnapnyiropuhp", "gvpgy", new GroupQuotaLimitListInner() + .withProperties(new GroupQuotaLimitListProperties().withValue(Arrays.asList( + new GroupQuotaLimit().withProperties(new GroupQuotaLimitProperties().withResourceName("edjvcslynqw") + .withLimit(1214544725492398973L) + .withComment("zhxgktrmgucn")), + new GroupQuotaLimit().withProperties(new GroupQuotaLimitProperties().withResourceName("ygpfqb") + .withLimit(7440392727703500605L) + .withComment("pzfqrhhuaoppp"))))), + com.azure.core.util.Context.NONE); + + Assertions.assertEquals("n", response.properties().value().get(0).properties().resourceName()); + Assertions.assertEquals(6645046241079336375L, response.properties().value().get(0).properties().limit()); + Assertions.assertEquals("krtswbxqz", response.properties().value().get(0).properties().comment()); + } +} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaListTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaListTests.java index 2743561f2fde..f90bf632eff8 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaListTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaListTests.java @@ -6,12 +6,8 @@ import com.azure.core.util.BinaryData; import com.azure.resourcemanager.quota.fluent.models.GroupQuotasEntityInner; -import com.azure.resourcemanager.quota.models.AdditionalAttributes; -import com.azure.resourcemanager.quota.models.EnvironmentType; import com.azure.resourcemanager.quota.models.GroupQuotaList; -import com.azure.resourcemanager.quota.models.GroupQuotasEntityBase; -import com.azure.resourcemanager.quota.models.GroupingId; -import com.azure.resourcemanager.quota.models.GroupingIdType; +import com.azure.resourcemanager.quota.models.GroupQuotasEntityProperties; import java.util.Arrays; import org.junit.jupiter.api.Assertions; @@ -19,54 +15,21 @@ public final class GroupQuotaListTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { GroupQuotaList model = BinaryData.fromString( - "{\"value\":[{\"properties\":{\"displayName\":\"kdtmlxhekuk\",\"additionalAttributes\":{\"groupId\":{\"groupingIdType\":\"BillingId\",\"value\":\"kc\"},\"environment\":\"NonProduction\"},\"provisioningState\":\"Succeeded\"},\"id\":\"ryuanzwuxzdxtay\",\"name\":\"lhmwhfpmrqobm\",\"type\":\"u\"},{\"properties\":{\"displayName\":\"ryrtihfxtijbpzv\",\"additionalAttributes\":{\"groupId\":{\"groupingIdType\":\"BillingId\",\"value\":\"ymglzufcyz\"},\"environment\":\"NonProduction\"},\"provisioningState\":\"Invalid\"},\"id\":\"hanufhfcbjysagi\",\"name\":\"hxqh\",\"type\":\"bifpikxwczb\"},{\"properties\":{\"displayName\":\"npqxuh\",\"additionalAttributes\":{\"groupId\":{\"groupingIdType\":\"BillingId\",\"value\":\"iwbybrkxvdumjg\"},\"environment\":\"NonProduction\"},\"provisioningState\":\"InProgress\"},\"id\":\"k\",\"name\":\"gaudcc\",\"type\":\"nhsjcnyej\"},{\"properties\":{\"displayName\":\"yhtnapczwlokjye\",\"additionalAttributes\":{\"groupId\":{\"groupingIdType\":\"ServiceTreeId\",\"value\":\"ipjoxzjnchgejs\"},\"environment\":\"Production\"},\"provisioningState\":\"Accepted\"},\"id\":\"lzydehojwyahux\",\"name\":\"npmqnjaqwixjspro\",\"type\":\"vcputegj\"}],\"nextLink\":\"mfdatscmdvpj\"}") + "{\"value\":[{\"properties\":{\"displayName\":\"siznto\",\"provisioningState\":\"Failed\"},\"id\":\"ouajpsqucmpoyf\",\"name\":\"kfo\",\"type\":\"knygjofjddeq\"},{\"properties\":{\"displayName\":\"eupewnwreitjz\",\"provisioningState\":\"InProgress\"},\"id\":\"sarhmofc\",\"name\":\"hs\",\"type\":\"yurkdtmlxhekuksj\"},{\"properties\":{\"displayName\":\"kc\",\"provisioningState\":\"InProgress\"},\"id\":\"rcryuanzwuxzdxta\",\"name\":\"rlhm\",\"type\":\"hfpmrqobmtukknr\"},{\"properties\":{\"displayName\":\"ihfxtijbpzvgnwzs\",\"provisioningState\":\"Accepted\"},\"id\":\"zufcyzkohdbi\",\"name\":\"anufhfcbjysag\",\"type\":\"th\"}],\"nextLink\":\"hab\"}") .toObject(GroupQuotaList.class); - Assertions.assertEquals("kdtmlxhekuk", model.value().get(0).properties().displayName()); - Assertions.assertEquals(GroupingIdType.BILLING_ID, - model.value().get(0).properties().additionalAttributes().groupId().groupingIdType()); - Assertions.assertEquals("kc", model.value().get(0).properties().additionalAttributes().groupId().value()); - Assertions.assertEquals(EnvironmentType.NON_PRODUCTION, - model.value().get(0).properties().additionalAttributes().environment()); + Assertions.assertEquals("siznto", model.value().get(0).properties().displayName()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - GroupQuotaList model - = new GroupQuotaList() - .withValue( - Arrays.asList( - new GroupQuotasEntityInner() - .withProperties(new GroupQuotasEntityBase().withDisplayName("kdtmlxhekuk") - .withAdditionalAttributes(new AdditionalAttributes() - .withGroupId( - new GroupingId().withGroupingIdType(GroupingIdType.BILLING_ID).withValue("kc")) - .withEnvironment(EnvironmentType.NON_PRODUCTION))), - new GroupQuotasEntityInner().withProperties(new GroupQuotasEntityBase() - .withDisplayName("ryrtihfxtijbpzv") - .withAdditionalAttributes(new AdditionalAttributes() - .withGroupId(new GroupingId().withGroupingIdType(GroupingIdType.BILLING_ID) - .withValue("ymglzufcyz")) - .withEnvironment(EnvironmentType.NON_PRODUCTION))), - new GroupQuotasEntityInner() - .withProperties( - new GroupQuotasEntityBase().withDisplayName("npqxuh") - .withAdditionalAttributes(new AdditionalAttributes() - .withGroupId(new GroupingId().withGroupingIdType(GroupingIdType.BILLING_ID) - .withValue("iwbybrkxvdumjg")) - .withEnvironment(EnvironmentType.NON_PRODUCTION))), - new GroupQuotasEntityInner() - .withProperties( - new GroupQuotasEntityBase().withDisplayName("yhtnapczwlokjye") - .withAdditionalAttributes(new AdditionalAttributes() - .withGroupId(new GroupingId().withGroupingIdType(GroupingIdType.SERVICE_TREE_ID) - .withValue("ipjoxzjnchgejs")) - .withEnvironment(EnvironmentType.PRODUCTION))))); + GroupQuotaList model = new GroupQuotaList().withValue(Arrays.asList( + new GroupQuotasEntityInner().withProperties(new GroupQuotasEntityProperties().withDisplayName("siznto")), + new GroupQuotasEntityInner() + .withProperties(new GroupQuotasEntityProperties().withDisplayName("eupewnwreitjz")), + new GroupQuotasEntityInner().withProperties(new GroupQuotasEntityProperties().withDisplayName("kc")), + new GroupQuotasEntityInner() + .withProperties(new GroupQuotasEntityProperties().withDisplayName("ihfxtijbpzvgnwzs")))); model = BinaryData.fromObject(model).toObject(GroupQuotaList.class); - Assertions.assertEquals("kdtmlxhekuk", model.value().get(0).properties().displayName()); - Assertions.assertEquals(GroupingIdType.BILLING_ID, - model.value().get(0).properties().additionalAttributes().groupId().groupingIdType()); - Assertions.assertEquals("kc", model.value().get(0).properties().additionalAttributes().groupId().value()); - Assertions.assertEquals(EnvironmentType.NON_PRODUCTION, - model.value().get(0).properties().additionalAttributes().environment()); + Assertions.assertEquals("siznto", model.value().get(0).properties().displayName()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaRequestBasePropertiesNameTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaRequestBasePropertiesNameTests.java index 03e3233947be..62cf1982903e 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaRequestBasePropertiesNameTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaRequestBasePropertiesNameTests.java @@ -11,7 +11,7 @@ public final class GroupQuotaRequestBasePropertiesNameTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { GroupQuotaRequestBasePropertiesName model - = BinaryData.fromString("{\"value\":\"npime\",\"localizedValue\":\"stxgc\"}") + = BinaryData.fromString("{\"value\":\"c\",\"localizedValue\":\"ierhhbcsglummaj\"}") .toObject(GroupQuotaRequestBasePropertiesName.class); } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaRequestBasePropertiesTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaRequestBasePropertiesTests.java index 999b3cc22ecd..5a43876e198d 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaRequestBasePropertiesTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaRequestBasePropertiesTests.java @@ -12,21 +12,21 @@ public final class GroupQuotaRequestBasePropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { GroupQuotaRequestBaseProperties model = BinaryData.fromString( - "{\"limit\":7208610995998070397,\"name\":{\"value\":\"c\",\"localizedValue\":\"ierhhbcsglummaj\"},\"region\":\"aodxo\",\"comments\":\"bdxkqpxokaj\"}") + "{\"limit\":1000418976764057169,\"name\":{\"value\":\"idtqajzyu\",\"localizedValue\":\"kudjkrlkhb\"},\"region\":\"fepgzgq\",\"comments\":\"zloc\"}") .toObject(GroupQuotaRequestBaseProperties.class); - Assertions.assertEquals(7208610995998070397L, model.limit()); - Assertions.assertEquals("aodxo", model.region()); - Assertions.assertEquals("bdxkqpxokaj", model.comments()); + Assertions.assertEquals(1000418976764057169L, model.limit()); + Assertions.assertEquals("fepgzgq", model.region()); + Assertions.assertEquals("zloc", model.comments()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - GroupQuotaRequestBaseProperties model = new GroupQuotaRequestBaseProperties().withLimit(7208610995998070397L) - .withRegion("aodxo") - .withComments("bdxkqpxokaj"); + GroupQuotaRequestBaseProperties model = new GroupQuotaRequestBaseProperties().withLimit(1000418976764057169L) + .withRegion("fepgzgq") + .withComments("zloc"); model = BinaryData.fromObject(model).toObject(GroupQuotaRequestBaseProperties.class); - Assertions.assertEquals(7208610995998070397L, model.limit()); - Assertions.assertEquals("aodxo", model.region()); - Assertions.assertEquals("bdxkqpxokaj", model.comments()); + Assertions.assertEquals(1000418976764057169L, model.limit()); + Assertions.assertEquals("fepgzgq", model.region()); + Assertions.assertEquals("zloc", model.comments()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaRequestBaseTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaRequestBaseTests.java index 64eeddc10a56..46ed9036c537 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaRequestBaseTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaRequestBaseTests.java @@ -12,20 +12,21 @@ public final class GroupQuotaRequestBaseTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { GroupQuotaRequestBase model = BinaryData.fromString( - "{\"properties\":{\"limit\":270477454684900932,\"name\":{\"value\":\"ajzyul\",\"localizedValue\":\"u\"},\"region\":\"krlkhbzhfepg\",\"comments\":\"qex\"}}") + "{\"properties\":{\"limit\":73742112490406036,\"name\":{\"value\":\"rjb\",\"localizedValue\":\"orcjxvsnby\"},\"region\":\"abnmocpcyshu\",\"comments\":\"afbljjgpbtoqcjmk\"}}") .toObject(GroupQuotaRequestBase.class); - Assertions.assertEquals(270477454684900932L, model.limit()); - Assertions.assertEquals("krlkhbzhfepg", model.region()); - Assertions.assertEquals("qex", model.comments()); + Assertions.assertEquals(73742112490406036L, model.limit()); + Assertions.assertEquals("abnmocpcyshu", model.region()); + Assertions.assertEquals("afbljjgpbtoqcjmk", model.comments()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - GroupQuotaRequestBase model - = new GroupQuotaRequestBase().withLimit(270477454684900932L).withRegion("krlkhbzhfepg").withComments("qex"); + GroupQuotaRequestBase model = new GroupQuotaRequestBase().withLimit(73742112490406036L) + .withRegion("abnmocpcyshu") + .withComments("afbljjgpbtoqcjmk"); model = BinaryData.fromObject(model).toObject(GroupQuotaRequestBase.class); - Assertions.assertEquals(270477454684900932L, model.limit()); - Assertions.assertEquals("krlkhbzhfepg", model.region()); - Assertions.assertEquals("qex", model.comments()); + Assertions.assertEquals(73742112490406036L, model.limit()); + Assertions.assertEquals("abnmocpcyshu", model.region()); + Assertions.assertEquals("afbljjgpbtoqcjmk", model.comments()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationRequestsUpdateMockTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationRequestsUpdateMockTests.java new file mode 100644 index 000000000000..c2281d67319a --- /dev/null +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationRequestsUpdateMockTests.java @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.quota.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.quota.QuotaManager; +import com.azure.resourcemanager.quota.fluent.models.SubscriptionQuotaAllocationsListInner; +import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocations; +import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocationsList; +import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocationsListProperties; +import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocationsProperties; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class GroupQuotaSubscriptionAllocationRequestsUpdateMockTests { + @Test + public void testUpdate() throws Exception { + String responseStr + = "{\"properties\":{\"provisioningState\":\"Succeeded\",\"value\":[{\"properties\":{\"resourceName\":\"xyjrxsagafcnih\",\"limit\":3130876298104392093,\"shareableQuota\":7972426552267245030,\"name\":{}}},{\"properties\":{\"resourceName\":\"bcvkcvqvpkeq\",\"limit\":7022646379651256978,\"shareableQuota\":5404644626428061791,\"name\":{}}},{\"properties\":{\"resourceName\":\"sotbob\",\"limit\":288160158988796372,\"shareableQuota\":510217030550797810,\"name\":{}}},{\"properties\":{\"resourceName\":\"dldwmgxc\",\"limit\":521643942642292025,\"shareableQuota\":7930800985951614116,\"name\":{}}}],\"nextLink\":\"uoegrpkhjwniyqs\"},\"id\":\"i\",\"name\":\"pdggkzzlvm\",\"type\":\"mpaxmodfvuefywsb\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + QuotaManager manager = QuotaManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + SubscriptionQuotaAllocationsList response = manager.groupQuotaSubscriptionAllocationRequests() + .update("cjefuzmu", "pbttdum", "rp", "xe", new SubscriptionQuotaAllocationsListInner() + .withProperties(new SubscriptionQuotaAllocationsListProperties().withValue(Arrays.asList( + new SubscriptionQuotaAllocations() + .withProperties(new SubscriptionQuotaAllocationsProperties().withResourceName("jpglkfgohdne") + .withLimit(7022736295865930419L)), + new SubscriptionQuotaAllocations() + .withProperties(new SubscriptionQuotaAllocationsProperties().withResourceName("t") + .withLimit(960595332999400866L)), + new SubscriptionQuotaAllocations() + .withProperties(new SubscriptionQuotaAllocationsProperties().withResourceName("uuvxz") + .withLimit(6214959618688242083L)), + new SubscriptionQuotaAllocations() + .withProperties(new SubscriptionQuotaAllocationsProperties().withResourceName("o") + .withLimit(2084595584241101757L))))), + com.azure.core.util.Context.NONE); + + Assertions.assertEquals("xyjrxsagafcnih", response.properties().value().get(0).properties().resourceName()); + Assertions.assertEquals(3130876298104392093L, response.properties().value().get(0).properties().limit()); + } +} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationsGetWithResponseMockTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationsGetWithResponseMockTests.java deleted file mode 100644 index fdadf2494a99..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationsGetWithResponseMockTests.java +++ /dev/null @@ -1,40 +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.resourcemanager.quota.generated; - -import com.azure.core.credential.AccessToken; -import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.profile.AzureProfile; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.resourcemanager.quota.QuotaManager; -import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocations; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -public final class GroupQuotaSubscriptionAllocationsGetWithResponseMockTests { - @Test - public void testGetWithResponse() throws Exception { - String responseStr - = "{\"properties\":{\"region\":\"ywsuwsy\",\"limit\":859811408175724714,\"shareableQuota\":6260637349305399844,\"name\":{\"value\":\"dgvraeaeneq\",\"localizedValue\":\"arrwlquu\"}},\"id\":\"fqka\",\"name\":\"e\",\"type\":\"iipfpubj\"}"; - - HttpClient httpClient - = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); - QuotaManager manager = QuotaManager.configure() - .withHttpClient(httpClient) - .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); - - SubscriptionQuotaAllocations response = manager.groupQuotaSubscriptionAllocations() - .getWithResponse("joxafnndlpi", "hkoymkcdyhbp", "kpw", "reqnovvqfov", com.azure.core.util.Context.NONE) - .getValue(); - - Assertions.assertEquals("ywsuwsy", response.properties().region()); - Assertions.assertEquals(859811408175724714L, response.properties().limit()); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationsListMockTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationsListMockTests.java deleted file mode 100644 index 2598b551ec69..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationsListMockTests.java +++ /dev/null @@ -1,40 +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.resourcemanager.quota.generated; - -import com.azure.core.credential.AccessToken; -import com.azure.core.http.HttpClient; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.profile.AzureProfile; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.resourcemanager.quota.QuotaManager; -import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocations; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -public final class GroupQuotaSubscriptionAllocationsListMockTests { - @Test - public void testList() throws Exception { - String responseStr - = "{\"value\":[{\"properties\":{\"region\":\"enwash\",\"limit\":7707312982236790783,\"shareableQuota\":5267748012493523201,\"name\":{\"value\":\"wbpokulpiujwaasi\",\"localizedValue\":\"i\"}},\"id\":\"byuqerpqlp\",\"name\":\"wcciuqgbdbu\",\"type\":\"auvfbtkuwhhmhyk\"}]}"; - - HttpClient httpClient - = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); - QuotaManager manager = QuotaManager.configure() - .withHttpClient(httpClient) - .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); - - PagedIterable response = manager.groupQuotaSubscriptionAllocations() - .list("ibahwflus", "dtmhrkwofyyvoqa", "piexpbtgiw", com.azure.core.util.Context.NONE); - - Assertions.assertEquals("enwash", response.iterator().next().properties().region()); - Assertions.assertEquals(7707312982236790783L, response.iterator().next().properties().limit()); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationsListWithResponseMockTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationsListWithResponseMockTests.java new file mode 100644 index 000000000000..467747cb7188 --- /dev/null +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionAllocationsListWithResponseMockTests.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.resourcemanager.quota.generated; + +import com.azure.core.credential.AccessToken; +import com.azure.core.http.HttpClient; +import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.resourcemanager.quota.QuotaManager; +import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocationsList; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +public final class GroupQuotaSubscriptionAllocationsListWithResponseMockTests { + @Test + public void testListWithResponse() throws Exception { + String responseStr + = "{\"properties\":{\"provisioningState\":\"Succeeded\",\"value\":[{\"properties\":{\"resourceName\":\"vfbtkuwh\",\"limit\":8532271889690426142,\"shareableQuota\":2308997283285722741,\"name\":{}}}],\"nextLink\":\"afnn\"},\"id\":\"pichkoymkcdy\",\"name\":\"bpkkpwdre\",\"type\":\"novvqfovljxy\"}"; + + HttpClient httpClient + = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); + QuotaManager manager = QuotaManager.configure() + .withHttpClient(httpClient) + .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); + + SubscriptionQuotaAllocationsList response = manager.groupQuotaSubscriptionAllocations() + .listWithResponse("p", "kulpiujwaasi", "qiiobyuqer", "qlpqwcciuq", com.azure.core.util.Context.NONE) + .getValue(); + + Assertions.assertEquals("vfbtkuwh", response.properties().value().get(0).properties().resourceName()); + Assertions.assertEquals(8532271889690426142L, response.properties().value().get(0).properties().limit()); + } +} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionIdInnerTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionIdInnerTests.java index f08d47ea53da..c1d14e9a4f04 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionIdInnerTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionIdInnerTests.java @@ -7,19 +7,22 @@ import com.azure.core.util.BinaryData; import com.azure.resourcemanager.quota.fluent.models.GroupQuotaSubscriptionIdInner; import com.azure.resourcemanager.quota.models.GroupQuotaSubscriptionIdProperties; +import org.junit.jupiter.api.Assertions; public final class GroupQuotaSubscriptionIdInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { GroupQuotaSubscriptionIdInner model = BinaryData.fromString( - "{\"properties\":{\"subscriptionId\":\"suuv\",\"provisioningState\":\"Created\"},\"id\":\"zkrwfn\",\"name\":\"iodjp\",\"type\":\"lwejdpv\"}") + "{\"properties\":{\"subscriptionId\":\"ikxwc\",\"provisioningState\":\"Accepted\"},\"id\":\"cnpqxuhivyqniwby\",\"name\":\"rkxvdum\",\"type\":\"grtfwvu\"}") .toObject(GroupQuotaSubscriptionIdInner.class); + Assertions.assertEquals("ikxwc", model.properties().subscriptionId()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - GroupQuotaSubscriptionIdInner model - = new GroupQuotaSubscriptionIdInner().withProperties(new GroupQuotaSubscriptionIdProperties()); + GroupQuotaSubscriptionIdInner model = new GroupQuotaSubscriptionIdInner() + .withProperties(new GroupQuotaSubscriptionIdProperties().withSubscriptionId("ikxwc")); model = BinaryData.fromObject(model).toObject(GroupQuotaSubscriptionIdInner.class); + Assertions.assertEquals("ikxwc", model.properties().subscriptionId()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionIdListTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionIdListTests.java index 6de83b3c5742..58d2aa62f059 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionIdListTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionIdListTests.java @@ -9,19 +9,23 @@ import com.azure.resourcemanager.quota.models.GroupQuotaSubscriptionIdList; import com.azure.resourcemanager.quota.models.GroupQuotaSubscriptionIdProperties; import java.util.Arrays; +import org.junit.jupiter.api.Assertions; public final class GroupQuotaSubscriptionIdListTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { GroupQuotaSubscriptionIdList model = BinaryData.fromString( - "{\"value\":[{\"properties\":{\"subscriptionId\":\"hbcryffdfdosyge\",\"provisioningState\":\"Invalid\"},\"id\":\"jakhmsbzjh\",\"name\":\"rzevdphlxaol\",\"type\":\"hqtrgqjbpf\"}],\"nextLink\":\"s\"}") + "{\"value\":[{\"properties\":{\"subscriptionId\":\"yejhk\",\"provisioningState\":\"Invalid\"},\"id\":\"napczwlokjy\",\"name\":\"mkkvnip\",\"type\":\"oxzjnchgejspod\"}],\"nextLink\":\"ilzyd\"}") .toObject(GroupQuotaSubscriptionIdList.class); + Assertions.assertEquals("yejhk", model.value().get(0).properties().subscriptionId()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - GroupQuotaSubscriptionIdList model = new GroupQuotaSubscriptionIdList().withValue(Arrays - .asList(new GroupQuotaSubscriptionIdInner().withProperties(new GroupQuotaSubscriptionIdProperties()))); + GroupQuotaSubscriptionIdList model + = new GroupQuotaSubscriptionIdList().withValue(Arrays.asList(new GroupQuotaSubscriptionIdInner() + .withProperties(new GroupQuotaSubscriptionIdProperties().withSubscriptionId("yejhk")))); model = BinaryData.fromObject(model).toObject(GroupQuotaSubscriptionIdList.class); + Assertions.assertEquals("yejhk", model.value().get(0).properties().subscriptionId()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionIdPropertiesTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionIdPropertiesTests.java index 5817ddda4c46..676d3eefa2d5 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionIdPropertiesTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionIdPropertiesTests.java @@ -6,18 +6,22 @@ import com.azure.core.util.BinaryData; import com.azure.resourcemanager.quota.models.GroupQuotaSubscriptionIdProperties; +import org.junit.jupiter.api.Assertions; public final class GroupQuotaSubscriptionIdPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { GroupQuotaSubscriptionIdProperties model - = BinaryData.fromString("{\"subscriptionId\":\"yoqpsoaccta\",\"provisioningState\":\"Accepted\"}") + = BinaryData.fromString("{\"subscriptionId\":\"gaudcc\",\"provisioningState\":\"Accepted\"}") .toObject(GroupQuotaSubscriptionIdProperties.class); + Assertions.assertEquals("gaudcc", model.subscriptionId()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - GroupQuotaSubscriptionIdProperties model = new GroupQuotaSubscriptionIdProperties(); + GroupQuotaSubscriptionIdProperties model + = new GroupQuotaSubscriptionIdProperties().withSubscriptionId("gaudcc"); model = BinaryData.fromObject(model).toObject(GroupQuotaSubscriptionIdProperties.class); + Assertions.assertEquals("gaudcc", model.subscriptionId()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionRequestStatusInnerTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionRequestStatusInnerTests.java index 08a49d5d3cee..7f8fb806ef80 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionRequestStatusInnerTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionRequestStatusInnerTests.java @@ -14,19 +14,19 @@ public final class GroupQuotaSubscriptionRequestStatusInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { GroupQuotaSubscriptionRequestStatusInner model = BinaryData.fromString( - "{\"properties\":{\"subscriptionId\":\"kzgcwrwcl\",\"requestSubmitTime\":\"2021-06-21T13:48:53Z\",\"provisioningState\":\"Canceled\"},\"id\":\"douskcqvkocrcjdk\",\"name\":\"tnhxbn\",\"type\":\"biksq\"}") + "{\"properties\":{\"subscriptionId\":\"hulsuuvmkjozkrwf\",\"requestSubmitTime\":\"2021-02-17T13:52:13Z\",\"provisioningState\":\"Succeeded\"},\"id\":\"pslwejdpvw\",\"name\":\"yoqpsoaccta\",\"type\":\"akl\"}") .toObject(GroupQuotaSubscriptionRequestStatusInner.class); - Assertions.assertEquals("kzgcwrwcl", model.properties().subscriptionId()); - Assertions.assertEquals(OffsetDateTime.parse("2021-06-21T13:48:53Z"), model.properties().requestSubmitTime()); + Assertions.assertEquals("hulsuuvmkjozkrwf", model.properties().subscriptionId()); + Assertions.assertEquals(OffsetDateTime.parse("2021-02-17T13:52:13Z"), model.properties().requestSubmitTime()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { GroupQuotaSubscriptionRequestStatusInner model = new GroupQuotaSubscriptionRequestStatusInner() - .withProperties(new GroupQuotaSubscriptionRequestStatusProperties().withSubscriptionId("kzgcwrwcl") - .withRequestSubmitTime(OffsetDateTime.parse("2021-06-21T13:48:53Z"))); + .withProperties(new GroupQuotaSubscriptionRequestStatusProperties().withSubscriptionId("hulsuuvmkjozkrwf") + .withRequestSubmitTime(OffsetDateTime.parse("2021-02-17T13:52:13Z"))); model = BinaryData.fromObject(model).toObject(GroupQuotaSubscriptionRequestStatusInner.class); - Assertions.assertEquals("kzgcwrwcl", model.properties().subscriptionId()); - Assertions.assertEquals(OffsetDateTime.parse("2021-06-21T13:48:53Z"), model.properties().requestSubmitTime()); + Assertions.assertEquals("hulsuuvmkjozkrwf", model.properties().subscriptionId()); + Assertions.assertEquals(OffsetDateTime.parse("2021-02-17T13:52:13Z"), model.properties().requestSubmitTime()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionRequestStatusListTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionRequestStatusListTests.java index bf4374452e07..acfbd3e18772 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionRequestStatusListTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionRequestStatusListTests.java @@ -16,29 +16,22 @@ public final class GroupQuotaSubscriptionRequestStatusListTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { GroupQuotaSubscriptionRequestStatusList model = BinaryData.fromString( - "{\"value\":[{\"properties\":{\"subscriptionId\":\"f\",\"requestSubmitTime\":\"2021-02-14T20:28:05Z\",\"provisioningState\":\"Succeeded\"},\"id\":\"xxjtfe\",\"name\":\"luwfzitonpeqfpjk\",\"type\":\"lxofpdvhpfxxypin\"},{\"properties\":{\"subscriptionId\":\"ayhuy\",\"requestSubmitTime\":\"2021-05-05T04:33:07Z\",\"provisioningState\":\"Created\"},\"id\":\"epoo\",\"name\":\"inuvamiheogn\",\"type\":\"rxzxtheo\"},{\"properties\":{\"subscriptionId\":\"ivyevcciqihnhun\",\"requestSubmitTime\":\"2021-08-15T16:10:49Z\",\"provisioningState\":\"Created\"},\"id\":\"nfygxgispemvtz\",\"name\":\"kufubljo\",\"type\":\"xqeofjaeqjhqjba\"}],\"nextLink\":\"msmjqulngsntn\"}") + "{\"value\":[{\"properties\":{\"subscriptionId\":\"yahux\",\"requestSubmitTime\":\"2021-07-08T12:15:19Z\",\"provisioningState\":\"InProgress\"},\"id\":\"jaqwixjsp\",\"name\":\"ozvcput\",\"type\":\"gjvw\"}],\"nextLink\":\"datscmd\"}") .toObject(GroupQuotaSubscriptionRequestStatusList.class); - Assertions.assertEquals("f", model.value().get(0).properties().subscriptionId()); - Assertions.assertEquals(OffsetDateTime.parse("2021-02-14T20:28:05Z"), + Assertions.assertEquals("yahux", model.value().get(0).properties().subscriptionId()); + Assertions.assertEquals(OffsetDateTime.parse("2021-07-08T12:15:19Z"), model.value().get(0).properties().requestSubmitTime()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - GroupQuotaSubscriptionRequestStatusList model - = new GroupQuotaSubscriptionRequestStatusList().withValue(Arrays.asList( - new GroupQuotaSubscriptionRequestStatusInner() - .withProperties(new GroupQuotaSubscriptionRequestStatusProperties().withSubscriptionId("f") - .withRequestSubmitTime(OffsetDateTime.parse("2021-02-14T20:28:05Z"))), - new GroupQuotaSubscriptionRequestStatusInner() - .withProperties(new GroupQuotaSubscriptionRequestStatusProperties().withSubscriptionId("ayhuy") - .withRequestSubmitTime(OffsetDateTime.parse("2021-05-05T04:33:07Z"))), - new GroupQuotaSubscriptionRequestStatusInner().withProperties( - new GroupQuotaSubscriptionRequestStatusProperties().withSubscriptionId("ivyevcciqihnhun") - .withRequestSubmitTime(OffsetDateTime.parse("2021-08-15T16:10:49Z"))))); + GroupQuotaSubscriptionRequestStatusList model = new GroupQuotaSubscriptionRequestStatusList() + .withValue(Arrays.asList(new GroupQuotaSubscriptionRequestStatusInner() + .withProperties(new GroupQuotaSubscriptionRequestStatusProperties().withSubscriptionId("yahux") + .withRequestSubmitTime(OffsetDateTime.parse("2021-07-08T12:15:19Z"))))); model = BinaryData.fromObject(model).toObject(GroupQuotaSubscriptionRequestStatusList.class); - Assertions.assertEquals("f", model.value().get(0).properties().subscriptionId()); - Assertions.assertEquals(OffsetDateTime.parse("2021-02-14T20:28:05Z"), + Assertions.assertEquals("yahux", model.value().get(0).properties().subscriptionId()); + Assertions.assertEquals(OffsetDateTime.parse("2021-07-08T12:15:19Z"), model.value().get(0).properties().requestSubmitTime()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionRequestStatusPropertiesTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionRequestStatusPropertiesTests.java index db2f8473db60..bd46d91614a1 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionRequestStatusPropertiesTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionRequestStatusPropertiesTests.java @@ -13,19 +13,19 @@ public final class GroupQuotaSubscriptionRequestStatusPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { GroupQuotaSubscriptionRequestStatusProperties model = BinaryData.fromString( - "{\"subscriptionId\":\"lssai\",\"requestSubmitTime\":\"2021-09-05T10:45:28Z\",\"provisioningState\":\"Created\"}") + "{\"subscriptionId\":\"ahbc\",\"requestSubmitTime\":\"2021-05-25T21:39:12Z\",\"provisioningState\":\"Created\"}") .toObject(GroupQuotaSubscriptionRequestStatusProperties.class); - Assertions.assertEquals("lssai", model.subscriptionId()); - Assertions.assertEquals(OffsetDateTime.parse("2021-09-05T10:45:28Z"), model.requestSubmitTime()); + Assertions.assertEquals("ahbc", model.subscriptionId()); + Assertions.assertEquals(OffsetDateTime.parse("2021-05-25T21:39:12Z"), model.requestSubmitTime()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { GroupQuotaSubscriptionRequestStatusProperties model - = new GroupQuotaSubscriptionRequestStatusProperties().withSubscriptionId("lssai") - .withRequestSubmitTime(OffsetDateTime.parse("2021-09-05T10:45:28Z")); + = new GroupQuotaSubscriptionRequestStatusProperties().withSubscriptionId("ahbc") + .withRequestSubmitTime(OffsetDateTime.parse("2021-05-25T21:39:12Z")); model = BinaryData.fromObject(model).toObject(GroupQuotaSubscriptionRequestStatusProperties.class); - Assertions.assertEquals("lssai", model.subscriptionId()); - Assertions.assertEquals(OffsetDateTime.parse("2021-09-05T10:45:28Z"), model.requestSubmitTime()); + Assertions.assertEquals("ahbc", model.subscriptionId()); + Assertions.assertEquals(OffsetDateTime.parse("2021-05-25T21:39:12Z"), model.requestSubmitTime()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionRequestsGetWithResponseMockTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionRequestsGetWithResponseMockTests.java index db9b4f84f961..d2911ed4dd88 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionRequestsGetWithResponseMockTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionRequestsGetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.quota.QuotaManager; import com.azure.resourcemanager.quota.models.GroupQuotaSubscriptionRequestStatus; @@ -21,21 +21,21 @@ public final class GroupQuotaSubscriptionRequestsGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"subscriptionId\":\"bpybsrfbjf\",\"requestSubmitTime\":\"2021-07-05T13:20:17Z\",\"provisioningState\":\"Invalid\"},\"id\":\"t\",\"name\":\"tpvjzbexilzznfqq\",\"type\":\"vwpm\"}"; + = "{\"properties\":{\"subscriptionId\":\"xwyjsflhhc\",\"requestSubmitTime\":\"2021-07-31T18:32:18Z\",\"provisioningState\":\"Canceled\"},\"id\":\"xisxyawjoyaqcsl\",\"name\":\"jpkiidzyexznelix\",\"type\":\"nr\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); QuotaManager manager = QuotaManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); GroupQuotaSubscriptionRequestStatus response = manager.groupQuotaSubscriptionRequests() - .getWithResponse("rruvwbhsq", "sub", "gjb", com.azure.core.util.Context.NONE) + .getWithResponse("uusdttouwa", "oekqvk", "lns", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("bpybsrfbjf", response.properties().subscriptionId()); - Assertions.assertEquals(OffsetDateTime.parse("2021-07-05T13:20:17Z"), + Assertions.assertEquals("xwyjsflhhc", response.properties().subscriptionId()); + Assertions.assertEquals(OffsetDateTime.parse("2021-07-31T18:32:18Z"), response.properties().requestSubmitTime()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionRequestsListMockTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionRequestsListMockTests.java index d7c23949b4f9..3442ce8bcfa1 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionRequestsListMockTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionRequestsListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.quota.QuotaManager; import com.azure.resourcemanager.quota.models.GroupQuotaSubscriptionRequestStatus; @@ -22,20 +22,20 @@ public final class GroupQuotaSubscriptionRequestsListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"subscriptionId\":\"blmpewww\",\"requestSubmitTime\":\"2021-08-04T10:31:47Z\",\"provisioningState\":\"InProgress\"},\"id\":\"nsvs\",\"name\":\"q\",\"type\":\"ohxcrsbfova\"}]}"; + = "{\"value\":[{\"properties\":{\"subscriptionId\":\"peilpjzuaejxdu\",\"requestSubmitTime\":\"2021-04-04T06:42:49Z\",\"provisioningState\":\"Invalid\"},\"id\":\"btdzumveekg\",\"name\":\"wozuhkf\",\"type\":\"bsjyofdx\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); QuotaManager manager = QuotaManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response - = manager.groupQuotaSubscriptionRequests().list("lqbhsf", "obl", com.azure.core.util.Context.NONE); + = manager.groupQuotaSubscriptionRequests().list("vawjvzunlu", "hnnpr", com.azure.core.util.Context.NONE); - Assertions.assertEquals("blmpewww", response.iterator().next().properties().subscriptionId()); - Assertions.assertEquals(OffsetDateTime.parse("2021-08-04T10:31:47Z"), + Assertions.assertEquals("peilpjzuaejxdu", response.iterator().next().properties().subscriptionId()); + Assertions.assertEquals(OffsetDateTime.parse("2021-04-04T06:42:49Z"), response.iterator().next().properties().requestSubmitTime()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsCreateOrUpdateMockTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsCreateOrUpdateMockTests.java index 905f0b1190fd..bbc51048c129 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsCreateOrUpdateMockTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsCreateOrUpdateMockTests.java @@ -6,9 +6,9 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.ProxyResource; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.quota.QuotaManager; import java.nio.charset.StandardCharsets; @@ -19,17 +19,17 @@ public final class GroupQuotaSubscriptionsCreateOrUpdateMockTests { @Test public void testCreateOrUpdate() throws Exception { - String responseStr = "{\"id\":\"gvpgy\",\"name\":\"gqgitxmedjvcsl\",\"type\":\"n\"}"; + String responseStr = "{\"id\":\"klwndnhjdauwhv\",\"name\":\"l\",\"type\":\"zbtd\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); QuotaManager manager = QuotaManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); ProxyResource response = manager.groupQuotaSubscriptions() - .createOrUpdate("xknalaulppg", "dtpnapnyiropuhp", com.azure.core.util.Context.NONE); + .createOrUpdate("nrjawgqwg", "hniskxfbkpyc", com.azure.core.util.Context.NONE); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsGetWithResponseMockTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsGetWithResponseMockTests.java index 99a1ceff2b22..af9f99e2379b 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsGetWithResponseMockTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsGetWithResponseMockTests.java @@ -6,13 +6,14 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.quota.QuotaManager; import com.azure.resourcemanager.quota.models.GroupQuotaSubscriptionId; import java.nio.charset.StandardCharsets; import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; @@ -20,18 +21,19 @@ public final class GroupQuotaSubscriptionsGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"subscriptionId\":\"izpost\",\"provisioningState\":\"Failed\"},\"id\":\"fbunrmfqjhhk\",\"name\":\"bpvjymjhx\",\"type\":\"j\"}"; + = "{\"properties\":{\"subscriptionId\":\"gwyzm\",\"provisioningState\":\"InProgress\"},\"id\":\"ngmtsavjcb\",\"name\":\"wxqpsrknftguvri\",\"type\":\"hprwmdyv\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); QuotaManager manager = QuotaManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); GroupQuotaSubscriptionId response = manager.groupQuotaSubscriptions() - .getWithResponse("z", "ahzxctobgbk", com.azure.core.util.Context.NONE) + .getWithResponse("nmxiebwwaloayqc", "wrtz", com.azure.core.util.Context.NONE) .getValue(); + Assertions.assertEquals("gwyzm", response.properties().subscriptionId()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsListMockTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsListMockTests.java index 0e391ca2478c..238f225958ce 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsListMockTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsListMockTests.java @@ -7,13 +7,14 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.quota.QuotaManager; import com.azure.resourcemanager.quota.models.GroupQuotaSubscriptionId; import java.nio.charset.StandardCharsets; import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; @@ -21,17 +22,18 @@ public final class GroupQuotaSubscriptionsListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"subscriptionId\":\"krtswbxqz\",\"provisioningState\":\"Created\"},\"id\":\"fauvjfdxx\",\"name\":\"vetvt\",\"type\":\"qaqtdoqmcbxvwvxy\"}]}"; + = "{\"value\":[{\"properties\":{\"subscriptionId\":\"cnojvknmefqsg\",\"provisioningState\":\"Canceled\"},\"id\":\"apj\",\"name\":\"zhpvgqzcjrvxd\",\"type\":\"zlmwlxkvugfhz\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); QuotaManager manager = QuotaManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response - = manager.groupQuotaSubscriptions().list("n", "u", com.azure.core.util.Context.NONE); + = manager.groupQuotaSubscriptions().list("qtayri", "wroyqbexrmcq", com.azure.core.util.Context.NONE); + Assertions.assertEquals("cnojvknmefqsg", response.iterator().next().properties().subscriptionId()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsUpdateMockTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsUpdateMockTests.java index 930cae0f0489..986b346c38bd 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsUpdateMockTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaSubscriptionsUpdateMockTests.java @@ -6,13 +6,14 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.quota.QuotaManager; import com.azure.resourcemanager.quota.models.GroupQuotaSubscriptionId; import java.nio.charset.StandardCharsets; import java.time.OffsetDateTime; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; @@ -20,17 +21,18 @@ public final class GroupQuotaSubscriptionsUpdateMockTests { @Test public void testUpdate() throws Exception { String responseStr - = "{\"properties\":{\"subscriptionId\":\"oellwp\",\"provisioningState\":\"Succeeded\"},\"id\":\"gpfqbuace\",\"name\":\"pzfqrhhuaoppp\",\"type\":\"qeqxo\"}"; + = "{\"properties\":{\"subscriptionId\":\"pjmkhfxobbc\",\"provisioningState\":\"Succeeded\"},\"id\":\"tjrip\",\"name\":\"rbpbewtghfgblcg\",\"type\":\"xzvlvqhjkbegib\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); QuotaManager manager = QuotaManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); GroupQuotaSubscriptionId response - = manager.groupQuotaSubscriptions().update("wwncwzzhxgk", "rmgucnap", com.azure.core.util.Context.NONE); + = manager.groupQuotaSubscriptions().update("xujznbmpowu", "przqlveu", com.azure.core.util.Context.NONE); + Assertions.assertEquals("pjmkhfxobbc", response.properties().subscriptionId()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaUsagesBaseNameTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaUsagesBaseNameTests.java deleted file mode 100644 index 23f268a9d40b..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaUsagesBaseNameTests.java +++ /dev/null @@ -1,25 +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.resourcemanager.quota.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.quota.fluent.models.GroupQuotaUsagesBaseName; -import org.junit.jupiter.api.Assertions; - -public final class GroupQuotaUsagesBaseNameTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - GroupQuotaUsagesBaseName model = BinaryData.fromString("{\"value\":\"czvyifq\",\"localizedValue\":\"kdvjsll\"}") - .toObject(GroupQuotaUsagesBaseName.class); - Assertions.assertEquals("czvyifq", model.value()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - GroupQuotaUsagesBaseName model = new GroupQuotaUsagesBaseName().withValue("czvyifq"); - model = BinaryData.fromObject(model).toObject(GroupQuotaUsagesBaseName.class); - Assertions.assertEquals("czvyifq", model.value()); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaUsagesBaseTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaUsagesBaseTests.java deleted file mode 100644 index e0a51b47920e..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaUsagesBaseTests.java +++ /dev/null @@ -1,32 +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.resourcemanager.quota.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.quota.models.GroupQuotaUsagesBase; -import org.junit.jupiter.api.Assertions; - -public final class GroupQuotaUsagesBaseTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - GroupQuotaUsagesBase model = BinaryData.fromString( - "{\"name\":{\"value\":\"s\",\"localizedValue\":\"ddystkiiuxhqy\"},\"limit\":8019571825859646594,\"usages\":1501001026308983782,\"unit\":\"b\"}") - .toObject(GroupQuotaUsagesBase.class); - Assertions.assertEquals(8019571825859646594L, model.limit()); - Assertions.assertEquals(1501001026308983782L, model.usages()); - Assertions.assertEquals("s", model.value()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - GroupQuotaUsagesBase model = new GroupQuotaUsagesBase().withLimit(8019571825859646594L) - .withUsages(1501001026308983782L) - .withValue("s"); - model = BinaryData.fromObject(model).toObject(GroupQuotaUsagesBase.class); - Assertions.assertEquals(8019571825859646594L, model.limit()); - Assertions.assertEquals(1501001026308983782L, model.usages()); - Assertions.assertEquals("s", model.value()); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaUsagesListMockTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaUsagesListMockTests.java deleted file mode 100644 index 0774b2f9507b..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotaUsagesListMockTests.java +++ /dev/null @@ -1,41 +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.resourcemanager.quota.generated; - -import com.azure.core.credential.AccessToken; -import com.azure.core.http.HttpClient; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.profile.AzureProfile; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.resourcemanager.quota.QuotaManager; -import com.azure.resourcemanager.quota.models.ResourceUsages; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -public final class GroupQuotaUsagesListMockTests { - @Test - public void testList() throws Exception { - String responseStr - = "{\"value\":[{\"properties\":{\"name\":{\"value\":\"kl\",\"localizedValue\":\"xbjhwuaanozjosph\"},\"limit\":5037944209655699604,\"usages\":737566499822055742,\"unit\":\"xagl\"},\"id\":\"imjwosyt\",\"name\":\"itc\",\"type\":\"kfcktqum\"}]}"; - - HttpClient httpClient - = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); - QuotaManager manager = QuotaManager.configure() - .withHttpClient(httpClient) - .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); - - PagedIterable response = manager.groupQuotaUsages() - .list("fnjhfjxwmszkkfo", "rey", "kzikfjawneaivxwc", "elpcirelsfeaenwa", com.azure.core.util.Context.NONE); - - Assertions.assertEquals(5037944209655699604L, response.iterator().next().properties().limit()); - Assertions.assertEquals(737566499822055742L, response.iterator().next().properties().usages()); - Assertions.assertEquals("kl", response.iterator().next().properties().value()); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasCreateOrUpdateMockTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasCreateOrUpdateMockTests.java index 49e030c56d11..2168e289de3a 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasCreateOrUpdateMockTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasCreateOrUpdateMockTests.java @@ -6,17 +6,13 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.ProxyResource; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.quota.QuotaManager; import com.azure.resourcemanager.quota.fluent.models.GroupQuotasEntityInner; -import com.azure.resourcemanager.quota.models.AdditionalAttributes; -import com.azure.resourcemanager.quota.models.EnvironmentType; -import com.azure.resourcemanager.quota.models.GroupQuotasEntityBase; -import com.azure.resourcemanager.quota.models.GroupingId; -import com.azure.resourcemanager.quota.models.GroupingIdType; +import com.azure.resourcemanager.quota.models.GroupQuotasEntityProperties; import java.nio.charset.StandardCharsets; import java.time.OffsetDateTime; import org.junit.jupiter.api.Test; @@ -25,22 +21,21 @@ public final class GroupQuotasCreateOrUpdateMockTests { @Test public void testCreateOrUpdate() throws Exception { - String responseStr = "{\"id\":\"riplrbpbewtg\",\"name\":\"fgb\",\"type\":\"c\"}"; + String responseStr = "{\"id\":\"fudwpznt\",\"name\":\"hdzhlrqj\",\"type\":\"hckfrlhrx\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); QuotaManager manager = QuotaManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); - ProxyResource response = manager.groupQuotas() - .createOrUpdate("fbkp", "cg", - new GroupQuotasEntityInner().withProperties(new GroupQuotasEntityBase().withDisplayName("ndnhj") - .withAdditionalAttributes(new AdditionalAttributes().withGroupId( - new GroupingId().withGroupingIdType(GroupingIdType.SERVICE_TREE_ID).withValue("vylwzbtdhxuj")) - .withEnvironment(EnvironmentType.NON_PRODUCTION))), - com.azure.core.util.Context.NONE); + ProxyResource response + = manager.groupQuotas() + .createOrUpdate("bgyepsbj", "azqugxywpmueefj", + new GroupQuotasEntityInner() + .withProperties(new GroupQuotasEntityProperties().withDisplayName("qkqujidsu")), + com.azure.core.util.Context.NONE); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasEntityBasePatchTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasEntityBasePatchTests.java index c209e1a2d5a2..f19aa7461628 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasEntityBasePatchTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasEntityBasePatchTests.java @@ -5,37 +5,22 @@ package com.azure.resourcemanager.quota.generated; import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.quota.models.AdditionalAttributesPatch; -import com.azure.resourcemanager.quota.models.EnvironmentType; import com.azure.resourcemanager.quota.models.GroupQuotasEntityBasePatch; -import com.azure.resourcemanager.quota.models.GroupingId; -import com.azure.resourcemanager.quota.models.GroupingIdType; import org.junit.jupiter.api.Assertions; public final class GroupQuotasEntityBasePatchTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - GroupQuotasEntityBasePatch model = BinaryData.fromString( - "{\"displayName\":\"s\",\"additionalAttributes\":{\"groupId\":{\"groupingIdType\":\"ServiceTreeId\",\"value\":\"wnw\"},\"environment\":\"NonProduction\"},\"provisioningState\":\"Succeeded\"}") - .toObject(GroupQuotasEntityBasePatch.class); - Assertions.assertEquals("s", model.displayName()); - Assertions.assertEquals(GroupingIdType.SERVICE_TREE_ID, - model.additionalAttributes().groupId().groupingIdType()); - Assertions.assertEquals("wnw", model.additionalAttributes().groupId().value()); - Assertions.assertEquals(EnvironmentType.NON_PRODUCTION, model.additionalAttributes().environment()); + GroupQuotasEntityBasePatch model + = BinaryData.fromString("{\"displayName\":\"f\",\"provisioningState\":\"Failed\"}") + .toObject(GroupQuotasEntityBasePatch.class); + Assertions.assertEquals("f", model.displayName()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - GroupQuotasEntityBasePatch model = new GroupQuotasEntityBasePatch().withDisplayName("s") - .withAdditionalAttributes(new AdditionalAttributesPatch() - .withGroupId(new GroupingId().withGroupingIdType(GroupingIdType.SERVICE_TREE_ID).withValue("wnw")) - .withEnvironment(EnvironmentType.NON_PRODUCTION)); + GroupQuotasEntityBasePatch model = new GroupQuotasEntityBasePatch().withDisplayName("f"); model = BinaryData.fromObject(model).toObject(GroupQuotasEntityBasePatch.class); - Assertions.assertEquals("s", model.displayName()); - Assertions.assertEquals(GroupingIdType.SERVICE_TREE_ID, - model.additionalAttributes().groupId().groupingIdType()); - Assertions.assertEquals("wnw", model.additionalAttributes().groupId().value()); - Assertions.assertEquals(EnvironmentType.NON_PRODUCTION, model.additionalAttributes().environment()); + Assertions.assertEquals("f", model.displayName()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasEntityBaseTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasEntityBaseTests.java index d5001dd74ab0..539a9d198533 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasEntityBaseTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasEntityBaseTests.java @@ -5,37 +5,22 @@ package com.azure.resourcemanager.quota.generated; import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.quota.models.AdditionalAttributes; -import com.azure.resourcemanager.quota.models.EnvironmentType; import com.azure.resourcemanager.quota.models.GroupQuotasEntityBase; -import com.azure.resourcemanager.quota.models.GroupingId; -import com.azure.resourcemanager.quota.models.GroupingIdType; import org.junit.jupiter.api.Assertions; public final class GroupQuotasEntityBaseTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - GroupQuotasEntityBase model = BinaryData.fromString( - "{\"displayName\":\"tbmufpo\",\"additionalAttributes\":{\"groupId\":{\"groupingIdType\":\"ServiceTreeId\",\"value\":\"hwlrx\"},\"environment\":\"Production\"},\"provisioningState\":\"Succeeded\"}") - .toObject(GroupQuotasEntityBase.class); - Assertions.assertEquals("tbmufpo", model.displayName()); - Assertions.assertEquals(GroupingIdType.SERVICE_TREE_ID, - model.additionalAttributes().groupId().groupingIdType()); - Assertions.assertEquals("hwlrx", model.additionalAttributes().groupId().value()); - Assertions.assertEquals(EnvironmentType.PRODUCTION, model.additionalAttributes().environment()); + GroupQuotasEntityBase model + = BinaryData.fromString("{\"displayName\":\"msxaobhd\",\"provisioningState\":\"Succeeded\"}") + .toObject(GroupQuotasEntityBase.class); + Assertions.assertEquals("msxaobhd", model.displayName()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - GroupQuotasEntityBase model = new GroupQuotasEntityBase().withDisplayName("tbmufpo") - .withAdditionalAttributes(new AdditionalAttributes() - .withGroupId(new GroupingId().withGroupingIdType(GroupingIdType.SERVICE_TREE_ID).withValue("hwlrx")) - .withEnvironment(EnvironmentType.PRODUCTION)); + GroupQuotasEntityBase model = new GroupQuotasEntityBase().withDisplayName("msxaobhd"); model = BinaryData.fromObject(model).toObject(GroupQuotasEntityBase.class); - Assertions.assertEquals("tbmufpo", model.displayName()); - Assertions.assertEquals(GroupingIdType.SERVICE_TREE_ID, - model.additionalAttributes().groupId().groupingIdType()); - Assertions.assertEquals("hwlrx", model.additionalAttributes().groupId().value()); - Assertions.assertEquals(EnvironmentType.PRODUCTION, model.additionalAttributes().environment()); + Assertions.assertEquals("msxaobhd", model.displayName()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasEntityInnerTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasEntityInnerTests.java index 3ac23a5c4cdc..1eccc1b3d3a3 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasEntityInnerTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasEntityInnerTests.java @@ -6,40 +6,23 @@ import com.azure.core.util.BinaryData; import com.azure.resourcemanager.quota.fluent.models.GroupQuotasEntityInner; -import com.azure.resourcemanager.quota.models.AdditionalAttributes; -import com.azure.resourcemanager.quota.models.EnvironmentType; -import com.azure.resourcemanager.quota.models.GroupQuotasEntityBase; -import com.azure.resourcemanager.quota.models.GroupingId; -import com.azure.resourcemanager.quota.models.GroupingIdType; +import com.azure.resourcemanager.quota.models.GroupQuotasEntityProperties; import org.junit.jupiter.api.Assertions; public final class GroupQuotasEntityInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { GroupQuotasEntityInner model = BinaryData.fromString( - "{\"properties\":{\"displayName\":\"hq\",\"additionalAttributes\":{\"groupId\":{\"groupingIdType\":\"BillingId\",\"value\":\"pybczmehmtzopb\"},\"environment\":\"NonProduction\"},\"provisioningState\":\"InProgress\"},\"id\":\"idgsybbe\",\"name\":\"hphoycm\",\"type\":\"xaobhdxbmtqioqjz\"}") + "{\"properties\":{\"displayName\":\"hq\",\"provisioningState\":\"InProgress\"},\"id\":\"xpyb\",\"name\":\"zm\",\"type\":\"hmtzopbsphrup\"}") .toObject(GroupQuotasEntityInner.class); Assertions.assertEquals("hq", model.properties().displayName()); - Assertions.assertEquals(GroupingIdType.BILLING_ID, - model.properties().additionalAttributes().groupId().groupingIdType()); - Assertions.assertEquals("pybczmehmtzopb", model.properties().additionalAttributes().groupId().value()); - Assertions.assertEquals(EnvironmentType.NON_PRODUCTION, - model.properties().additionalAttributes().environment()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - GroupQuotasEntityInner model = new GroupQuotasEntityInner().withProperties(new GroupQuotasEntityBase() - .withDisplayName("hq") - .withAdditionalAttributes(new AdditionalAttributes() - .withGroupId(new GroupingId().withGroupingIdType(GroupingIdType.BILLING_ID).withValue("pybczmehmtzopb")) - .withEnvironment(EnvironmentType.NON_PRODUCTION))); + GroupQuotasEntityInner model + = new GroupQuotasEntityInner().withProperties(new GroupQuotasEntityProperties().withDisplayName("hq")); model = BinaryData.fromObject(model).toObject(GroupQuotasEntityInner.class); Assertions.assertEquals("hq", model.properties().displayName()); - Assertions.assertEquals(GroupingIdType.BILLING_ID, - model.properties().additionalAttributes().groupId().groupingIdType()); - Assertions.assertEquals("pybczmehmtzopb", model.properties().additionalAttributes().groupId().value()); - Assertions.assertEquals(EnvironmentType.NON_PRODUCTION, - model.properties().additionalAttributes().environment()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasEntityPatchPropertiesTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasEntityPatchPropertiesTests.java new file mode 100644 index 000000000000..5f9f63a16d74 --- /dev/null +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasEntityPatchPropertiesTests.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.quota.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.quota.models.GroupQuotasEntityPatchProperties; +import org.junit.jupiter.api.Assertions; + +public final class GroupQuotasEntityPatchPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + GroupQuotasEntityPatchProperties model + = BinaryData.fromString("{\"displayName\":\"fsqesaagdfmglzlh\",\"provisioningState\":\"Failed\"}") + .toObject(GroupQuotasEntityPatchProperties.class); + Assertions.assertEquals("fsqesaagdfmglzlh", model.displayName()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + GroupQuotasEntityPatchProperties model + = new GroupQuotasEntityPatchProperties().withDisplayName("fsqesaagdfmglzlh"); + model = BinaryData.fromObject(model).toObject(GroupQuotasEntityPatchProperties.class); + Assertions.assertEquals("fsqesaagdfmglzlh", model.displayName()); + } +} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasEntityPatchTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasEntityPatchTests.java index c80fa1706d82..73fbe5222d9c 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasEntityPatchTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasEntityPatchTests.java @@ -5,41 +5,24 @@ package com.azure.resourcemanager.quota.generated; import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.quota.models.AdditionalAttributesPatch; -import com.azure.resourcemanager.quota.models.EnvironmentType; -import com.azure.resourcemanager.quota.models.GroupQuotasEntityBasePatch; import com.azure.resourcemanager.quota.models.GroupQuotasEntityPatch; -import com.azure.resourcemanager.quota.models.GroupingId; -import com.azure.resourcemanager.quota.models.GroupingIdType; +import com.azure.resourcemanager.quota.models.GroupQuotasEntityPatchProperties; import org.junit.jupiter.api.Assertions; public final class GroupQuotasEntityPatchTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { GroupQuotasEntityPatch model = BinaryData.fromString( - "{\"properties\":{\"displayName\":\"xrifkwmrvkts\",\"additionalAttributes\":{\"groupId\":{\"groupingIdType\":\"BillingId\",\"value\":\"ipa\"},\"environment\":\"NonProduction\"},\"provisioningState\":\"Succeeded\"},\"id\":\"qucmpo\",\"name\":\"fdkfogk\",\"type\":\"ygjofjdd\"}") + "{\"properties\":{\"displayName\":\"oqijgkdmbpaz\",\"provisioningState\":\"Failed\"},\"id\":\"ufpdznrbtcqq\",\"name\":\"nq\",\"type\":\"lhqgnufooojy\"}") .toObject(GroupQuotasEntityPatch.class); - Assertions.assertEquals("xrifkwmrvkts", model.properties().displayName()); - Assertions.assertEquals(GroupingIdType.BILLING_ID, - model.properties().additionalAttributes().groupId().groupingIdType()); - Assertions.assertEquals("ipa", model.properties().additionalAttributes().groupId().value()); - Assertions.assertEquals(EnvironmentType.NON_PRODUCTION, - model.properties().additionalAttributes().environment()); + Assertions.assertEquals("oqijgkdmbpaz", model.properties().displayName()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { GroupQuotasEntityPatch model = new GroupQuotasEntityPatch() - .withProperties(new GroupQuotasEntityBasePatch().withDisplayName("xrifkwmrvkts") - .withAdditionalAttributes(new AdditionalAttributesPatch() - .withGroupId(new GroupingId().withGroupingIdType(GroupingIdType.BILLING_ID).withValue("ipa")) - .withEnvironment(EnvironmentType.NON_PRODUCTION))); + .withProperties(new GroupQuotasEntityPatchProperties().withDisplayName("oqijgkdmbpaz")); model = BinaryData.fromObject(model).toObject(GroupQuotasEntityPatch.class); - Assertions.assertEquals("xrifkwmrvkts", model.properties().displayName()); - Assertions.assertEquals(GroupingIdType.BILLING_ID, - model.properties().additionalAttributes().groupId().groupingIdType()); - Assertions.assertEquals("ipa", model.properties().additionalAttributes().groupId().value()); - Assertions.assertEquals(EnvironmentType.NON_PRODUCTION, - model.properties().additionalAttributes().environment()); + Assertions.assertEquals("oqijgkdmbpaz", model.properties().displayName()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasEntityPropertiesTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasEntityPropertiesTests.java new file mode 100644 index 000000000000..60643387118e --- /dev/null +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasEntityPropertiesTests.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.quota.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.quota.models.GroupQuotasEntityProperties; +import org.junit.jupiter.api.Assertions; + +public final class GroupQuotasEntityPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + GroupQuotasEntityProperties model + = BinaryData.fromString("{\"displayName\":\"gsybbejhp\",\"provisioningState\":\"Accepted\"}") + .toObject(GroupQuotasEntityProperties.class); + Assertions.assertEquals("gsybbejhp", model.displayName()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + GroupQuotasEntityProperties model = new GroupQuotasEntityProperties().withDisplayName("gsybbejhp"); + model = BinaryData.fromObject(model).toObject(GroupQuotasEntityProperties.class); + Assertions.assertEquals("gsybbejhp", model.displayName()); + } +} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasGetWithResponseMockTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasGetWithResponseMockTests.java index 59b7fe8673d7..94d75cc7331b 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasGetWithResponseMockTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasGetWithResponseMockTests.java @@ -6,13 +6,11 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.quota.QuotaManager; -import com.azure.resourcemanager.quota.models.EnvironmentType; import com.azure.resourcemanager.quota.models.GroupQuotasEntity; -import com.azure.resourcemanager.quota.models.GroupingIdType; import java.nio.charset.StandardCharsets; import java.time.OffsetDateTime; import org.junit.jupiter.api.Assertions; @@ -23,23 +21,18 @@ public final class GroupQuotasGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"displayName\":\"umveekgpwozuhkf\",\"additionalAttributes\":{\"groupId\":{\"groupingIdType\":\"BillingId\",\"value\":\"ofd\"},\"environment\":\"Production\"},\"provisioningState\":\"Failed\"},\"id\":\"ttouwaboekqvkel\",\"name\":\"smv\",\"type\":\"xwyjsflhhc\"}"; + = "{\"properties\":{\"displayName\":\"gwb\",\"provisioningState\":\"Canceled\"},\"id\":\"ldawkzbaliourqha\",\"name\":\"auhashsfwx\",\"type\":\"sowzxcugi\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); QuotaManager manager = QuotaManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); - GroupQuotasEntity response = manager.groupQuotas() - .getWithResponse("nxipeil", "jzuaejxdultskzbb", com.azure.core.util.Context.NONE) - .getValue(); + GroupQuotasEntity response + = manager.groupQuotas().getWithResponse("crgvxpvgom", "lf", com.azure.core.util.Context.NONE).getValue(); - Assertions.assertEquals("umveekgpwozuhkf", response.properties().displayName()); - Assertions.assertEquals(GroupingIdType.BILLING_ID, - response.properties().additionalAttributes().groupId().groupingIdType()); - Assertions.assertEquals("ofd", response.properties().additionalAttributes().groupId().value()); - Assertions.assertEquals(EnvironmentType.PRODUCTION, response.properties().additionalAttributes().environment()); + Assertions.assertEquals("gwb", response.properties().displayName()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasListMockTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasListMockTests.java index 82f6c4543990..d55e6eb69e1f 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasListMockTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasListMockTests.java @@ -7,13 +7,11 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.quota.QuotaManager; -import com.azure.resourcemanager.quota.models.EnvironmentType; import com.azure.resourcemanager.quota.models.GroupQuotasEntity; -import com.azure.resourcemanager.quota.models.GroupingIdType; import java.nio.charset.StandardCharsets; import java.time.OffsetDateTime; import org.junit.jupiter.api.Assertions; @@ -24,23 +22,18 @@ public final class GroupQuotasListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"displayName\":\"isxyawjoyaqcslyj\",\"additionalAttributes\":{\"groupId\":{\"groupingIdType\":\"BillingId\",\"value\":\"zyexzn\"},\"environment\":\"NonProduction\"},\"provisioningState\":\"Succeeded\"},\"id\":\"rzt\",\"name\":\"o\",\"type\":\"hb\"}]}"; + = "{\"value\":[{\"properties\":{\"displayName\":\"wwfvov\",\"provisioningState\":\"Created\"},\"id\":\"uecivyhz\",\"name\":\"euojgjrwju\",\"type\":\"iotwmcdytdxwit\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); QuotaManager manager = QuotaManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); - PagedIterable response = manager.groupQuotas().list("aln", com.azure.core.util.Context.NONE); + PagedIterable response + = manager.groupQuotas().list("jooxdjebw", com.azure.core.util.Context.NONE); - Assertions.assertEquals("isxyawjoyaqcslyj", response.iterator().next().properties().displayName()); - Assertions.assertEquals(GroupingIdType.BILLING_ID, - response.iterator().next().properties().additionalAttributes().groupId().groupingIdType()); - Assertions.assertEquals("zyexzn", - response.iterator().next().properties().additionalAttributes().groupId().value()); - Assertions.assertEquals(EnvironmentType.NON_PRODUCTION, - response.iterator().next().properties().additionalAttributes().environment()); + Assertions.assertEquals("wwfvov", response.iterator().next().properties().displayName()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasUpdateMockTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasUpdateMockTests.java index 59e58d9fe8a6..7bad4aa2a7d8 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasUpdateMockTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupQuotasUpdateMockTests.java @@ -6,17 +6,13 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.quota.QuotaManager; -import com.azure.resourcemanager.quota.models.AdditionalAttributesPatch; -import com.azure.resourcemanager.quota.models.EnvironmentType; import com.azure.resourcemanager.quota.models.GroupQuotasEntity; -import com.azure.resourcemanager.quota.models.GroupQuotasEntityBasePatch; import com.azure.resourcemanager.quota.models.GroupQuotasEntityPatch; -import com.azure.resourcemanager.quota.models.GroupingId; -import com.azure.resourcemanager.quota.models.GroupingIdType; +import com.azure.resourcemanager.quota.models.GroupQuotasEntityPatchProperties; import java.nio.charset.StandardCharsets; import java.time.OffsetDateTime; import org.junit.jupiter.api.Assertions; @@ -27,28 +23,21 @@ public final class GroupQuotasUpdateMockTests { @Test public void testUpdate() throws Exception { String responseStr - = "{\"properties\":{\"displayName\":\"cqibycnojv\",\"additionalAttributes\":{\"groupId\":{\"groupingIdType\":\"ServiceTreeId\",\"value\":\"qsgzvahapj\"},\"environment\":\"NonProduction\"},\"provisioningState\":\"Succeeded\"},\"id\":\"qzcjrvxdj\",\"name\":\"lmwlxkvugfhzo\",\"type\":\"awjvzunluthnnp\"}"; + = "{\"properties\":{\"displayName\":\"krh\",\"provisioningState\":\"Succeeded\"},\"id\":\"juahaquhcdhmdual\",\"name\":\"exq\",\"type\":\"vfadmws\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); QuotaManager manager = QuotaManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); GroupQuotasEntity response = manager.groupQuotas() - .update("wxzvlvqhjkb", "gibtnm", - new GroupQuotasEntityPatch().withProperties(new GroupQuotasEntityBasePatch().withDisplayName("bwwaloa") - .withAdditionalAttributes(new AdditionalAttributesPatch().withGroupId( - new GroupingId().withGroupingIdType(GroupingIdType.SERVICE_TREE_ID).withValue("tzjuzgwyzmhtxo")) - .withEnvironment(EnvironmentType.PRODUCTION))), + .update("bkyvp", "ca", + new GroupQuotasEntityPatch() + .withProperties(new GroupQuotasEntityPatchProperties().withDisplayName("bpzkafkuwbc")), com.azure.core.util.Context.NONE); - Assertions.assertEquals("cqibycnojv", response.properties().displayName()); - Assertions.assertEquals(GroupingIdType.SERVICE_TREE_ID, - response.properties().additionalAttributes().groupId().groupingIdType()); - Assertions.assertEquals("qsgzvahapj", response.properties().additionalAttributes().groupId().value()); - Assertions.assertEquals(EnvironmentType.NON_PRODUCTION, - response.properties().additionalAttributes().environment()); + Assertions.assertEquals("krh", response.properties().displayName()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupingIdTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupingIdTests.java deleted file mode 100644 index 9f703341b1c9..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/GroupingIdTests.java +++ /dev/null @@ -1,28 +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.resourcemanager.quota.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.quota.models.GroupingId; -import com.azure.resourcemanager.quota.models.GroupingIdType; -import org.junit.jupiter.api.Assertions; - -public final class GroupingIdTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - GroupingId model = BinaryData.fromString("{\"groupingIdType\":\"ServiceTreeId\",\"value\":\"c\"}") - .toObject(GroupingId.class); - Assertions.assertEquals(GroupingIdType.SERVICE_TREE_ID, model.groupingIdType()); - Assertions.assertEquals("c", model.value()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - GroupingId model = new GroupingId().withGroupingIdType(GroupingIdType.SERVICE_TREE_ID).withValue("c"); - model = BinaryData.fromObject(model).toObject(GroupingId.class); - Assertions.assertEquals(GroupingIdType.SERVICE_TREE_ID, model.groupingIdType()); - Assertions.assertEquals("c", model.value()); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/LimitObjectTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/LimitObjectTests.java index fcd4b542b0ab..7088e763be7e 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/LimitObjectTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/LimitObjectTests.java @@ -13,17 +13,17 @@ public final class LimitObjectTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { LimitObject model = BinaryData - .fromString("{\"limitObjectType\":\"LimitValue\",\"value\":1353933533,\"limitType\":\"Independent\"}") + .fromString("{\"limitObjectType\":\"LimitValue\",\"value\":1106219716,\"limitType\":\"Independent\"}") .toObject(LimitObject.class); - Assertions.assertEquals(1353933533, model.value()); + Assertions.assertEquals(1106219716, model.value()); Assertions.assertEquals(QuotaLimitTypes.INDEPENDENT, model.limitType()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - LimitObject model = new LimitObject().withValue(1353933533).withLimitType(QuotaLimitTypes.INDEPENDENT); + LimitObject model = new LimitObject().withValue(1106219716).withLimitType(QuotaLimitTypes.INDEPENDENT); model = BinaryData.fromObject(model).toObject(LimitObject.class); - Assertions.assertEquals(1353933533, model.value()); + Assertions.assertEquals(1106219716, model.value()); Assertions.assertEquals(QuotaLimitTypes.INDEPENDENT, model.limitType()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/LroResponseInnerTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/LroResponseInnerTests.java index 1e426e3c75b9..7d94a1e1ba48 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/LroResponseInnerTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/LroResponseInnerTests.java @@ -12,7 +12,7 @@ public final class LroResponseInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { LroResponseInner model = BinaryData.fromString( - "{\"properties\":{\"provisioningState\":\"Accepted\"},\"id\":\"nrbtcqqjnq\",\"name\":\"lhqgnufooojy\",\"type\":\"ifsqesaagdfmg\"}") + "{\"properties\":{\"provisioningState\":\"Succeeded\"},\"id\":\"qj\",\"name\":\"ehtbm\",\"type\":\"fpownoizhwlr\"}") .toObject(LroResponseInner.class); } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/LroResponsePropertiesTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/LroResponsePropertiesTests.java index b87f8db9e668..8cc31b815e43 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/LroResponsePropertiesTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/LroResponsePropertiesTests.java @@ -11,7 +11,7 @@ public final class LroResponsePropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { LroResponseProperties model - = BinaryData.fromString("{\"provisioningState\":\"Created\"}").toObject(LroResponseProperties.class); + = BinaryData.fromString("{\"provisioningState\":\"Accepted\"}").toObject(LroResponseProperties.class); } @org.junit.jupiter.api.Test diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/OperationDisplayTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/OperationDisplayTests.java index 8b81e21cc130..55a1f50550ce 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/OperationDisplayTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/OperationDisplayTests.java @@ -11,26 +11,25 @@ public final class OperationDisplayTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - OperationDisplay model = BinaryData - .fromString( - "{\"provider\":\"twm\",\"resource\":\"ytdxwit\",\"operation\":\"rjaw\",\"description\":\"wgxhn\"}") + OperationDisplay model = BinaryData.fromString( + "{\"provider\":\"fj\",\"resource\":\"njbkcnxdhbttkph\",\"operation\":\"pnvjtoqnermclf\",\"description\":\"phoxus\"}") .toObject(OperationDisplay.class); - Assertions.assertEquals("twm", model.provider()); - Assertions.assertEquals("ytdxwit", model.resource()); - Assertions.assertEquals("rjaw", model.operation()); - Assertions.assertEquals("wgxhn", model.description()); + Assertions.assertEquals("fj", model.provider()); + Assertions.assertEquals("njbkcnxdhbttkph", model.resource()); + Assertions.assertEquals("pnvjtoqnermclf", model.operation()); + Assertions.assertEquals("phoxus", model.description()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - OperationDisplay model = new OperationDisplay().withProvider("twm") - .withResource("ytdxwit") - .withOperation("rjaw") - .withDescription("wgxhn"); + OperationDisplay model = new OperationDisplay().withProvider("fj") + .withResource("njbkcnxdhbttkph") + .withOperation("pnvjtoqnermclf") + .withDescription("phoxus"); model = BinaryData.fromObject(model).toObject(OperationDisplay.class); - Assertions.assertEquals("twm", model.provider()); - Assertions.assertEquals("ytdxwit", model.resource()); - Assertions.assertEquals("rjaw", model.operation()); - Assertions.assertEquals("wgxhn", model.description()); + Assertions.assertEquals("fj", model.provider()); + Assertions.assertEquals("njbkcnxdhbttkph", model.resource()); + Assertions.assertEquals("pnvjtoqnermclf", model.operation()); + Assertions.assertEquals("phoxus", model.description()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/OperationListTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/OperationListTests.java index c5dad4b73a35..c01c35d20a84 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/OperationListTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/OperationListTests.java @@ -15,52 +15,33 @@ public final class OperationListTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { OperationList model = BinaryData.fromString( - "{\"value\":[{\"name\":\"vjtoqnermclfp\",\"display\":{\"provider\":\"oxuscrpabgyepsbj\",\"resource\":\"zq\",\"operation\":\"xywpmueefjzwfqkq\",\"description\":\"ids\"},\"origin\":\"onobglaocqx\"},{\"name\":\"cmgyud\",\"display\":{\"provider\":\"lmoyrx\",\"resource\":\"fudwpznt\",\"operation\":\"dzhlrq\",\"description\":\"hckfrlhrx\"},\"origin\":\"kyv\"},{\"name\":\"ca\",\"display\":{\"provider\":\"bpzkafkuwbc\",\"resource\":\"wbme\",\"operation\":\"seyvj\",\"description\":\"rts\"},\"origin\":\"spkdee\"},{\"name\":\"ofmxagkvtmelmqkr\",\"display\":{\"provider\":\"vljua\",\"resource\":\"quhcdhmduala\",\"operation\":\"qpv\",\"description\":\"dmwsrcrgvxpvgomz\"},\"origin\":\"misgwbnb\"}],\"nextLink\":\"ldawkzbaliourqha\"}") + "{\"value\":[{\"name\":\"qukkfp\",\"display\":{\"provider\":\"gsxnkjzkdeslpv\",\"resource\":\"pwiyig\",\"operation\":\"pkdwzbai\",\"description\":\"bbaumnyquped\"},\"origin\":\"jn\"}],\"nextLink\":\"ckhsmtxpsieb\"}") .toObject(OperationList.class); - Assertions.assertEquals("vjtoqnermclfp", model.value().get(0).name()); - Assertions.assertEquals("oxuscrpabgyepsbj", model.value().get(0).display().provider()); - Assertions.assertEquals("zq", model.value().get(0).display().resource()); - Assertions.assertEquals("xywpmueefjzwfqkq", model.value().get(0).display().operation()); - Assertions.assertEquals("ids", model.value().get(0).display().description()); - Assertions.assertEquals("onobglaocqx", model.value().get(0).origin()); - Assertions.assertEquals("ldawkzbaliourqha", model.nextLink()); + Assertions.assertEquals("qukkfp", model.value().get(0).name()); + Assertions.assertEquals("gsxnkjzkdeslpv", model.value().get(0).display().provider()); + Assertions.assertEquals("pwiyig", model.value().get(0).display().resource()); + Assertions.assertEquals("pkdwzbai", model.value().get(0).display().operation()); + Assertions.assertEquals("bbaumnyquped", model.value().get(0).display().description()); + Assertions.assertEquals("jn", model.value().get(0).origin()); + Assertions.assertEquals("ckhsmtxpsieb", model.nextLink()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - OperationList model = new OperationList().withValue(Arrays.asList( - new OperationResponseInner().withName("vjtoqnermclfp") - .withDisplay(new OperationDisplay().withProvider("oxuscrpabgyepsbj") - .withResource("zq") - .withOperation("xywpmueefjzwfqkq") - .withDescription("ids")) - .withOrigin("onobglaocqx"), - new OperationResponseInner().withName("cmgyud") - .withDisplay(new OperationDisplay().withProvider("lmoyrx") - .withResource("fudwpznt") - .withOperation("dzhlrq") - .withDescription("hckfrlhrx")) - .withOrigin("kyv"), - new OperationResponseInner().withName("ca") - .withDisplay(new OperationDisplay().withProvider("bpzkafkuwbc") - .withResource("wbme") - .withOperation("seyvj") - .withDescription("rts")) - .withOrigin("spkdee"), - new OperationResponseInner().withName("ofmxagkvtmelmqkr") - .withDisplay(new OperationDisplay().withProvider("vljua") - .withResource("quhcdhmduala") - .withOperation("qpv") - .withDescription("dmwsrcrgvxpvgomz")) - .withOrigin("misgwbnb"))) - .withNextLink("ldawkzbaliourqha"); + OperationList model + = new OperationList().withValue(Arrays.asList(new OperationResponseInner().withName("qukkfp") + .withDisplay(new OperationDisplay().withProvider("gsxnkjzkdeslpv") + .withResource("pwiyig") + .withOperation("pkdwzbai") + .withDescription("bbaumnyquped")) + .withOrigin("jn"))).withNextLink("ckhsmtxpsieb"); model = BinaryData.fromObject(model).toObject(OperationList.class); - Assertions.assertEquals("vjtoqnermclfp", model.value().get(0).name()); - Assertions.assertEquals("oxuscrpabgyepsbj", model.value().get(0).display().provider()); - Assertions.assertEquals("zq", model.value().get(0).display().resource()); - Assertions.assertEquals("xywpmueefjzwfqkq", model.value().get(0).display().operation()); - Assertions.assertEquals("ids", model.value().get(0).display().description()); - Assertions.assertEquals("onobglaocqx", model.value().get(0).origin()); - Assertions.assertEquals("ldawkzbaliourqha", model.nextLink()); + Assertions.assertEquals("qukkfp", model.value().get(0).name()); + Assertions.assertEquals("gsxnkjzkdeslpv", model.value().get(0).display().provider()); + Assertions.assertEquals("pwiyig", model.value().get(0).display().resource()); + Assertions.assertEquals("pkdwzbai", model.value().get(0).display().operation()); + Assertions.assertEquals("bbaumnyquped", model.value().get(0).display().description()); + Assertions.assertEquals("jn", model.value().get(0).origin()); + Assertions.assertEquals("ckhsmtxpsieb", model.nextLink()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/OperationResponseInnerTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/OperationResponseInnerTests.java index 64528c223324..96b87faae405 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/OperationResponseInnerTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/OperationResponseInnerTests.java @@ -13,30 +13,30 @@ public final class OperationResponseInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { OperationResponseInner model = BinaryData.fromString( - "{\"name\":\"uhashsfwx\",\"display\":{\"provider\":\"w\",\"resource\":\"cugicjoox\",\"operation\":\"ebwpucwwfvo\",\"description\":\"vmeueci\"},\"origin\":\"hzceuojgjrwjue\"}") + "{\"name\":\"hvpesapskrdqm\",\"display\":{\"provider\":\"dhtldwkyz\",\"resource\":\"utknc\",\"operation\":\"cwsvlxotog\",\"description\":\"rupqsxvnmicy\"},\"origin\":\"ceoveilovno\"}") .toObject(OperationResponseInner.class); - Assertions.assertEquals("uhashsfwx", model.name()); - Assertions.assertEquals("w", model.display().provider()); - Assertions.assertEquals("cugicjoox", model.display().resource()); - Assertions.assertEquals("ebwpucwwfvo", model.display().operation()); - Assertions.assertEquals("vmeueci", model.display().description()); - Assertions.assertEquals("hzceuojgjrwjue", model.origin()); + Assertions.assertEquals("hvpesapskrdqm", model.name()); + Assertions.assertEquals("dhtldwkyz", model.display().provider()); + Assertions.assertEquals("utknc", model.display().resource()); + Assertions.assertEquals("cwsvlxotog", model.display().operation()); + Assertions.assertEquals("rupqsxvnmicy", model.display().description()); + Assertions.assertEquals("ceoveilovno", model.origin()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - OperationResponseInner model = new OperationResponseInner().withName("uhashsfwx") - .withDisplay(new OperationDisplay().withProvider("w") - .withResource("cugicjoox") - .withOperation("ebwpucwwfvo") - .withDescription("vmeueci")) - .withOrigin("hzceuojgjrwjue"); + OperationResponseInner model = new OperationResponseInner().withName("hvpesapskrdqm") + .withDisplay(new OperationDisplay().withProvider("dhtldwkyz") + .withResource("utknc") + .withOperation("cwsvlxotog") + .withDescription("rupqsxvnmicy")) + .withOrigin("ceoveilovno"); model = BinaryData.fromObject(model).toObject(OperationResponseInner.class); - Assertions.assertEquals("uhashsfwx", model.name()); - Assertions.assertEquals("w", model.display().provider()); - Assertions.assertEquals("cugicjoox", model.display().resource()); - Assertions.assertEquals("ebwpucwwfvo", model.display().operation()); - Assertions.assertEquals("vmeueci", model.display().description()); - Assertions.assertEquals("hzceuojgjrwjue", model.origin()); + Assertions.assertEquals("hvpesapskrdqm", model.name()); + Assertions.assertEquals("dhtldwkyz", model.display().provider()); + Assertions.assertEquals("utknc", model.display().resource()); + Assertions.assertEquals("cwsvlxotog", model.display().operation()); + Assertions.assertEquals("rupqsxvnmicy", model.display().description()); + Assertions.assertEquals("ceoveilovno", model.origin()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotaAllocationRequestBasePropertiesNameTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotaAllocationRequestBasePropertiesNameTests.java index 8bec98565a8d..b54055725a55 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotaAllocationRequestBasePropertiesNameTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotaAllocationRequestBasePropertiesNameTests.java @@ -11,7 +11,7 @@ public final class QuotaAllocationRequestBasePropertiesNameTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { QuotaAllocationRequestBasePropertiesName model - = BinaryData.fromString("{\"value\":\"yggdtjixh\",\"localizedValue\":\"uofqwe\"}") + = BinaryData.fromString("{\"value\":\"zrkgqhcjrefovg\",\"localizedValue\":\"qsl\"}") .toObject(QuotaAllocationRequestBasePropertiesName.class); } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotaAllocationRequestBasePropertiesTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotaAllocationRequestBasePropertiesTests.java index 9a2691f12844..905f230abf45 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotaAllocationRequestBasePropertiesTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotaAllocationRequestBasePropertiesTests.java @@ -12,18 +12,18 @@ public final class QuotaAllocationRequestBasePropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { QuotaAllocationRequestBaseProperties model = BinaryData.fromString( - "{\"limit\":1364175055394963114,\"name\":{\"value\":\"orxzdmohctbqvud\",\"localizedValue\":\"dndnvow\"},\"region\":\"jjugwdkcglhslaz\"}") + "{\"limit\":6472421771400984812,\"name\":{\"value\":\"yvdcsitynnaa\",\"localizedValue\":\"ectehf\"},\"region\":\"scjeypv\"}") .toObject(QuotaAllocationRequestBaseProperties.class); - Assertions.assertEquals(1364175055394963114L, model.limit()); - Assertions.assertEquals("jjugwdkcglhslaz", model.region()); + Assertions.assertEquals(6472421771400984812L, model.limit()); + Assertions.assertEquals("scjeypv", model.region()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { QuotaAllocationRequestBaseProperties model - = new QuotaAllocationRequestBaseProperties().withLimit(1364175055394963114L).withRegion("jjugwdkcglhslaz"); + = new QuotaAllocationRequestBaseProperties().withLimit(6472421771400984812L).withRegion("scjeypv"); model = BinaryData.fromObject(model).toObject(QuotaAllocationRequestBaseProperties.class); - Assertions.assertEquals(1364175055394963114L, model.limit()); - Assertions.assertEquals("jjugwdkcglhslaz", model.region()); + Assertions.assertEquals(6472421771400984812L, model.limit()); + Assertions.assertEquals("scjeypv", model.region()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotaAllocationRequestBaseTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotaAllocationRequestBaseTests.java index 1e98965fed01..059cba592193 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotaAllocationRequestBaseTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotaAllocationRequestBaseTests.java @@ -12,18 +12,18 @@ public final class QuotaAllocationRequestBaseTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { QuotaAllocationRequestBase model = BinaryData.fromString( - "{\"properties\":{\"limit\":6981573049423863635,\"name\":{\"value\":\"h\",\"localizedValue\":\"ltyfsop\"},\"region\":\"suesnzw\"}}") + "{\"properties\":{\"limit\":753338547504300720,\"name\":{\"value\":\"hslazjdyggdtj\",\"localizedValue\":\"hbkuofqwey\"},\"region\":\"menevfyexfwh\"}}") .toObject(QuotaAllocationRequestBase.class); - Assertions.assertEquals(6981573049423863635L, model.limit()); - Assertions.assertEquals("suesnzw", model.region()); + Assertions.assertEquals(753338547504300720L, model.limit()); + Assertions.assertEquals("menevfyexfwh", model.region()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { QuotaAllocationRequestBase model - = new QuotaAllocationRequestBase().withLimit(6981573049423863635L).withRegion("suesnzw"); + = new QuotaAllocationRequestBase().withLimit(753338547504300720L).withRegion("menevfyexfwh"); model = BinaryData.fromObject(model).toObject(QuotaAllocationRequestBase.class); - Assertions.assertEquals(6981573049423863635L, model.limit()); - Assertions.assertEquals("suesnzw", model.region()); + Assertions.assertEquals(753338547504300720L, model.limit()); + Assertions.assertEquals("menevfyexfwh", model.region()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotaLimitsTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotaLimitsTests.java index a88e2f08ffd9..18a34fe6d6fa 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotaLimitsTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotaLimitsTests.java @@ -17,36 +17,28 @@ public final class QuotaLimitsTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { QuotaLimits model = BinaryData.fromString( - "{\"value\":[{\"properties\":{\"limit\":{\"limitObjectType\":\"LimitJsonObject\"},\"unit\":\"c\",\"name\":{\"value\":\"hfnljkyq\",\"localizedValue\":\"vuujq\"},\"resourceType\":\"dokgjl\",\"quotaPeriod\":\"oxgvclt\",\"isQuotaApplicable\":true,\"properties\":\"datac\"},\"id\":\"hkjeszzhbi\",\"name\":\"htxfvgxbfsmxnehm\",\"type\":\"vecxgodebfqkk\"},{\"properties\":{\"limit\":{\"limitObjectType\":\"LimitJsonObject\"},\"unit\":\"ukgri\",\"name\":{\"value\":\"zlfbxzpuzycispnq\",\"localizedValue\":\"hmgkbrpyy\"},\"resourceType\":\"ibnuqqkpik\",\"quotaPeriod\":\"rgvtqag\",\"isQuotaApplicable\":false,\"properties\":\"datanhijggmebfsi\"},\"id\":\"rbu\",\"name\":\"rcvpnazzmhjrunmp\",\"type\":\"ttdbhrbnl\"},{\"properties\":{\"limit\":{\"limitObjectType\":\"LimitJsonObject\"},\"unit\":\"myskpbhenbtkcxy\",\"name\":{\"value\":\"tnrsyn\",\"localizedValue\":\"idybyxczf\"},\"resourceType\":\"haaxdbabphl\",\"quotaPeriod\":\"qlfktsths\",\"isQuotaApplicable\":true,\"properties\":\"datamnyyazt\"},\"id\":\"bt\",\"name\":\"wrqpue\",\"type\":\"ckzywbiexzfeyue\"},{\"properties\":{\"limit\":{\"limitObjectType\":\"LimitJsonObject\"},\"unit\":\"xujwbhqwalmuzyo\",\"name\":{\"value\":\"pdkzjancuxr\",\"localizedValue\":\"wbavxbniwdj\"},\"resourceType\":\"zt\",\"quotaPeriod\":\"bpg\",\"isQuotaApplicable\":false,\"properties\":\"datax\"},\"id\":\"pzxbz\",\"name\":\"fzab\",\"type\":\"lcuhxwtctyqiklb\"}],\"nextLink\":\"vplwzbhv\"}") + "{\"value\":[{\"properties\":{\"limit\":{\"limitObjectType\":\"LimitJsonObject\"},\"unit\":\"idokgjlj\",\"name\":{\"value\":\"gvcl\",\"localizedValue\":\"gsncghkjeszz\"},\"resourceType\":\"ijhtxf\",\"quotaPeriod\":\"xbf\",\"isQuotaApplicable\":true,\"properties\":\"dataeh\"},\"id\":\"pvecxgodeb\",\"name\":\"qkkrb\",\"type\":\"pukgriwflzlfb\"},{\"properties\":{\"limit\":{\"limitObjectType\":\"LimitJsonObject\"},\"unit\":\"zycispn\",\"name\":{\"value\":\"hmgkbrpyy\",\"localizedValue\":\"ibnuqqkpik\"},\"resourceType\":\"rgvtqag\",\"quotaPeriod\":\"uynhijg\",\"isQuotaApplicable\":false,\"properties\":\"datafsiarbutr\"},\"id\":\"vpnazzm\",\"name\":\"jrunmpxtt\",\"type\":\"bh\"}],\"nextLink\":\"nlankxmyskpb\"}") .toObject(QuotaLimits.class); - Assertions.assertEquals("hfnljkyq", model.value().get(0).properties().name().value()); - Assertions.assertEquals("dokgjl", model.value().get(0).properties().resourceType()); - Assertions.assertEquals("vplwzbhv", model.nextLink()); + Assertions.assertEquals("gvcl", model.value().get(0).properties().name().value()); + Assertions.assertEquals("ijhtxf", model.value().get(0).properties().resourceType()); + Assertions.assertEquals("nlankxmyskpb", model.nextLink()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { QuotaLimits model = new QuotaLimits().withValue(Arrays.asList( new CurrentQuotaLimitBaseInner().withProperties(new QuotaProperties().withLimit(new LimitJsonObject()) - .withName(new ResourceName().withValue("hfnljkyq")) - .withResourceType("dokgjl") - .withProperties("datac")), + .withName(new ResourceName().withValue("gvcl")) + .withResourceType("ijhtxf") + .withProperties("dataeh")), new CurrentQuotaLimitBaseInner().withProperties(new QuotaProperties().withLimit(new LimitJsonObject()) - .withName(new ResourceName().withValue("zlfbxzpuzycispnq")) - .withResourceType("ibnuqqkpik") - .withProperties("datanhijggmebfsi")), - new CurrentQuotaLimitBaseInner().withProperties(new QuotaProperties().withLimit(new LimitJsonObject()) - .withName(new ResourceName().withValue("tnrsyn")) - .withResourceType("haaxdbabphl") - .withProperties("datamnyyazt")), - new CurrentQuotaLimitBaseInner().withProperties(new QuotaProperties().withLimit(new LimitJsonObject()) - .withName(new ResourceName().withValue("pdkzjancuxr")) - .withResourceType("zt") - .withProperties("datax")))) - .withNextLink("vplwzbhv"); + .withName(new ResourceName().withValue("hmgkbrpyy")) + .withResourceType("rgvtqag") + .withProperties("datafsiarbutr")))) + .withNextLink("nlankxmyskpb"); model = BinaryData.fromObject(model).toObject(QuotaLimits.class); - Assertions.assertEquals("hfnljkyq", model.value().get(0).properties().name().value()); - Assertions.assertEquals("dokgjl", model.value().get(0).properties().resourceType()); - Assertions.assertEquals("vplwzbhv", model.nextLink()); + Assertions.assertEquals("gvcl", model.value().get(0).properties().name().value()); + Assertions.assertEquals("ijhtxf", model.value().get(0).properties().resourceType()); + Assertions.assertEquals("nlankxmyskpb", model.nextLink()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotaOperationsListMockTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotaOperationsListMockTests.java index 2b7f800780c1..6950b9c99e57 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotaOperationsListMockTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotaOperationsListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.quota.QuotaManager; import com.azure.resourcemanager.quota.models.OperationResponse; @@ -22,22 +22,22 @@ public final class QuotaOperationsListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"name\":\"ehtwdwrft\",\"display\":{\"provider\":\"byrcdlbhshfwp\",\"resource\":\"cstwity\",\"operation\":\"evxccedcp\",\"description\":\"dyodnwzxltj\"},\"origin\":\"nhltiugcxn\"}]}"; + = "{\"value\":[{\"name\":\"nsj\",\"display\":{\"provider\":\"tiagx\",\"resource\":\"sz\",\"operation\":\"mpsbzkfzbeyv\",\"description\":\"qi\"},\"origin\":\"invkjjxdxrbuu\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); QuotaManager manager = QuotaManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response = manager.quotaOperations().list(com.azure.core.util.Context.NONE); - Assertions.assertEquals("ehtwdwrft", response.iterator().next().name()); - Assertions.assertEquals("byrcdlbhshfwp", response.iterator().next().display().provider()); - Assertions.assertEquals("cstwity", response.iterator().next().display().resource()); - Assertions.assertEquals("evxccedcp", response.iterator().next().display().operation()); - Assertions.assertEquals("dyodnwzxltj", response.iterator().next().display().description()); - Assertions.assertEquals("nhltiugcxn", response.iterator().next().origin()); + Assertions.assertEquals("nsj", response.iterator().next().name()); + Assertions.assertEquals("tiagx", response.iterator().next().display().provider()); + Assertions.assertEquals("sz", response.iterator().next().display().resource()); + Assertions.assertEquals("mpsbzkfzbeyv", response.iterator().next().display().operation()); + Assertions.assertEquals("qi", response.iterator().next().display().description()); + Assertions.assertEquals("invkjjxdxrbuu", response.iterator().next().origin()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotaPropertiesTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotaPropertiesTests.java index e0a71006d694..b79bdebe2233 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotaPropertiesTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotaPropertiesTests.java @@ -14,20 +14,20 @@ public final class QuotaPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { QuotaProperties model = BinaryData.fromString( - "{\"limit\":{\"limitObjectType\":\"LimitJsonObject\"},\"unit\":\"zpwv\",\"name\":{\"value\":\"q\",\"localizedValue\":\"iqylihkaetck\"},\"resourceType\":\"fcivfsnkym\",\"quotaPeriod\":\"tqhjfbebrjcx\",\"isQuotaApplicable\":true,\"properties\":\"datawutttxfvjrbi\"}") + "{\"limit\":{\"limitObjectType\":\"LimitJsonObject\"},\"unit\":\"ivfsnk\",\"name\":{\"value\":\"ctq\",\"localizedValue\":\"fbebrjcxer\"},\"resourceType\":\"wutttxfvjrbi\",\"quotaPeriod\":\"hxepcyvahfnlj\",\"isQuotaApplicable\":false,\"properties\":\"dataj\"}") .toObject(QuotaProperties.class); - Assertions.assertEquals("q", model.name().value()); - Assertions.assertEquals("fcivfsnkym", model.resourceType()); + Assertions.assertEquals("ctq", model.name().value()); + Assertions.assertEquals("wutttxfvjrbi", model.resourceType()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { QuotaProperties model = new QuotaProperties().withLimit(new LimitJsonObject()) - .withName(new ResourceName().withValue("q")) - .withResourceType("fcivfsnkym") - .withProperties("datawutttxfvjrbi"); + .withName(new ResourceName().withValue("ctq")) + .withResourceType("wutttxfvjrbi") + .withProperties("dataj"); model = BinaryData.fromObject(model).toObject(QuotaProperties.class); - Assertions.assertEquals("q", model.name().value()); - Assertions.assertEquals("fcivfsnkym", model.resourceType()); + Assertions.assertEquals("ctq", model.name().value()); + Assertions.assertEquals("wutttxfvjrbi", model.resourceType()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotasCreateOrUpdateMockTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotasCreateOrUpdateMockTests.java index 0acfccc0a7ff..848c8a556a54 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotasCreateOrUpdateMockTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotasCreateOrUpdateMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.quota.QuotaManager; import com.azure.resourcemanager.quota.models.CurrentQuotaLimitBase; @@ -24,25 +24,25 @@ public final class QuotasCreateOrUpdateMockTests { @Test public void testCreateOrUpdate() throws Exception { String responseStr - = "{\"properties\":{\"limit\":{\"limitObjectType\":\"LimitJsonObject\"},\"unit\":\"dsnfdsdoakgtdl\",\"name\":{\"value\":\"zev\",\"localizedValue\":\"hewpusdsttwv\"},\"resourceType\":\"vbbejdcng\",\"quotaPeriod\":\"m\",\"isQuotaApplicable\":false,\"properties\":\"datafgmjzrwrdgrt\"},\"id\":\"aenuuz\",\"name\":\"opbminrfdw\",\"type\":\"yuhhziu\"}"; + = "{\"properties\":{\"limit\":{\"limitObjectType\":\"LimitJsonObject\"},\"unit\":\"wqm\",\"name\":{\"value\":\"lkrm\",\"localizedValue\":\"i\"},\"resourceType\":\"xacqqudfnbyx\",\"quotaPeriod\":\"aabjyvayffimrz\",\"isQuotaApplicable\":true,\"properties\":\"dataqogsexnevfd\"},\"id\":\"wnwmewzs\",\"name\":\"yceuzsoib\",\"type\":\"ud\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); QuotaManager manager = QuotaManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); CurrentQuotaLimitBase response = manager.quotas() - .define("pzfoqoui") - .withExistingScope("ybxarzgszu") + .define("tcs") + .withExistingScope("fcktqumiekke") .withProperties(new QuotaProperties().withLimit(new LimitJsonObject()) - .withName(new ResourceName().withValue("azxkhnzbonlwnto")) - .withResourceType("kszzcmrvexztv") - .withProperties("dataguxawqaldsyuuxi")) + .withName(new ResourceName().withValue("unygaeqid")) + .withResourceType("uvarmywdmjsjq") + .withProperties("dataduhpk")) .create(); - Assertions.assertEquals("zev", response.properties().name().value()); - Assertions.assertEquals("vbbejdcng", response.properties().resourceType()); + Assertions.assertEquals("lkrm", response.properties().name().value()); + Assertions.assertEquals("xacqqudfnbyx", response.properties().resourceType()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotasGetWithResponseMockTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotasGetWithResponseMockTests.java index cdf1fd8b4e88..53d7c0b956cc 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotasGetWithResponseMockTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotasGetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.quota.QuotaManager; import com.azure.resourcemanager.quota.models.CurrentQuotaLimitBase; @@ -21,19 +21,20 @@ public final class QuotasGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"limit\":{\"limitObjectType\":\"LimitJsonObject\"},\"unit\":\"ztppriolxorjalto\",\"name\":{\"value\":\"cwsobqwcs\",\"localizedValue\":\"nwdcfhu\"},\"resourceType\":\"dpfuvg\",\"quotaPeriod\":\"bjj\",\"isQuotaApplicable\":false,\"properties\":\"dataxbvtvudu\"},\"id\":\"ncormrlxqtvcof\",\"name\":\"dflvkg\",\"type\":\"u\"}"; + = "{\"properties\":{\"limit\":{\"limitObjectType\":\"LimitJsonObject\"},\"unit\":\"fmtdaaygdvwvgp\",\"name\":{\"value\":\"g\",\"localizedValue\":\"rtfudxepxg\"},\"resourceType\":\"agvrvmnpkuk\",\"quotaPeriod\":\"i\",\"isQuotaApplicable\":false,\"properties\":\"dataxgwim\"},\"id\":\"njhf\",\"name\":\"xw\",\"type\":\"szkkfoqre\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); QuotaManager manager = QuotaManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); - CurrentQuotaLimitBase response - = manager.quotas().getWithResponse("fz", "whxxbuyqax", com.azure.core.util.Context.NONE).getValue(); + CurrentQuotaLimitBase response = manager.quotas() + .getWithResponse("nayrhyrnxxmueedn", "rdvstkwqqtch", com.azure.core.util.Context.NONE) + .getValue(); - Assertions.assertEquals("cwsobqwcs", response.properties().name().value()); - Assertions.assertEquals("dpfuvg", response.properties().resourceType()); + Assertions.assertEquals("g", response.properties().name().value()); + Assertions.assertEquals("agvrvmnpkuk", response.properties().resourceType()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotasListMockTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotasListMockTests.java index b13c05060760..409e1cf08b9c 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotasListMockTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/QuotasListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.quota.QuotaManager; import com.azure.resourcemanager.quota.models.CurrentQuotaLimitBase; @@ -22,19 +22,19 @@ public final class QuotasListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"limit\":{\"limitObjectType\":\"LimitJsonObject\"},\"unit\":\"qntorudsgsahmkyc\",\"name\":{\"value\":\"uwjuetaeburuvdmo\",\"localizedValue\":\"mz\"},\"resourceType\":\"wabm\",\"quotaPeriod\":\"efkifr\",\"isQuotaApplicable\":true,\"properties\":\"dataqujmqlgkf\"},\"id\":\"tndoaongbjc\",\"name\":\"tujitcjedft\",\"type\":\"waezkojvd\"}]}"; + = "{\"value\":[{\"properties\":{\"limit\":{\"limitObjectType\":\"LimitJsonObject\"},\"unit\":\"a\",\"name\":{\"value\":\"wczelpci\",\"localizedValue\":\"lsfeaenwabfatkld\"},\"resourceType\":\"bjhwuaan\",\"quotaPeriod\":\"jos\",\"isQuotaApplicable\":false,\"properties\":\"dataulpjr\"},\"id\":\"xagl\",\"name\":\"vimjwos\",\"type\":\"tx\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); QuotaManager manager = QuotaManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response - = manager.quotas().list("gdknnqv", com.azure.core.util.Context.NONE); + = manager.quotas().list("fkzikfj", com.azure.core.util.Context.NONE); - Assertions.assertEquals("uwjuetaeburuvdmo", response.iterator().next().properties().name().value()); - Assertions.assertEquals("wabm", response.iterator().next().properties().resourceType()); + Assertions.assertEquals("wczelpci", response.iterator().next().properties().name().value()); + Assertions.assertEquals("bjhwuaan", response.iterator().next().properties().resourceType()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/ResourceNameTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/ResourceNameTests.java index bee5ae628481..1555309cad76 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/ResourceNameTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/ResourceNameTests.java @@ -11,15 +11,15 @@ public final class ResourceNameTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - ResourceName model = BinaryData.fromString("{\"value\":\"ngkpocipazy\",\"localizedValue\":\"egukgjnpiucg\"}") + ResourceName model = BinaryData.fromString("{\"value\":\"bq\",\"localizedValue\":\"sovmyokacspkwl\"}") .toObject(ResourceName.class); - Assertions.assertEquals("ngkpocipazy", model.value()); + Assertions.assertEquals("bq", model.value()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - ResourceName model = new ResourceName().withValue("ngkpocipazy"); + ResourceName model = new ResourceName().withValue("bq"); model = BinaryData.fromObject(model).toObject(ResourceName.class); - Assertions.assertEquals("ngkpocipazy", model.value()); + Assertions.assertEquals("bq", model.value()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/ResourceUsageListTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/ResourceUsageListTests.java deleted file mode 100644 index cf36eed3b082..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/ResourceUsageListTests.java +++ /dev/null @@ -1,39 +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.resourcemanager.quota.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.quota.fluent.models.ResourceUsagesInner; -import com.azure.resourcemanager.quota.models.GroupQuotaUsagesBase; -import com.azure.resourcemanager.quota.models.ResourceUsageList; -import java.util.Arrays; -import org.junit.jupiter.api.Assertions; - -public final class ResourceUsageListTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - ResourceUsageList model = BinaryData.fromString( - "{\"value\":[{\"properties\":{\"name\":{\"value\":\"amdecte\",\"localizedValue\":\"iqscjeypv\"},\"limit\":5856868160780933935,\"usages\":2742951421766727417,\"unit\":\"c\"},\"id\":\"efovgmk\",\"name\":\"sle\",\"type\":\"yvxyqjp\"},{\"properties\":{\"name\":{\"value\":\"tpngjcrcczsqpjh\",\"localizedValue\":\"daj\"},\"limit\":4392638781282274584,\"usages\":1463154876474108196,\"unit\":\"e\"},\"id\":\"noae\",\"name\":\"pfhyhl\",\"type\":\"rpmopjmc\"}],\"nextLink\":\"tuo\"}") - .toObject(ResourceUsageList.class); - Assertions.assertEquals(5856868160780933935L, model.value().get(0).properties().limit()); - Assertions.assertEquals(2742951421766727417L, model.value().get(0).properties().usages()); - Assertions.assertEquals("amdecte", model.value().get(0).properties().value()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - ResourceUsageList model = new ResourceUsageList().withValue(Arrays.asList( - new ResourceUsagesInner().withProperties(new GroupQuotaUsagesBase().withLimit(5856868160780933935L) - .withUsages(2742951421766727417L) - .withValue("amdecte")), - new ResourceUsagesInner().withProperties(new GroupQuotaUsagesBase().withLimit(4392638781282274584L) - .withUsages(1463154876474108196L) - .withValue("tpngjcrcczsqpjh")))); - model = BinaryData.fromObject(model).toObject(ResourceUsageList.class); - Assertions.assertEquals(5856868160780933935L, model.value().get(0).properties().limit()); - Assertions.assertEquals(2742951421766727417L, model.value().get(0).properties().usages()); - Assertions.assertEquals("amdecte", model.value().get(0).properties().value()); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/ResourceUsagesInnerTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/ResourceUsagesInnerTests.java deleted file mode 100644 index 4eac9eb41d7f..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/ResourceUsagesInnerTests.java +++ /dev/null @@ -1,34 +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.resourcemanager.quota.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.quota.fluent.models.ResourceUsagesInner; -import com.azure.resourcemanager.quota.models.GroupQuotaUsagesBase; -import org.junit.jupiter.api.Assertions; - -public final class ResourceUsagesInnerTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - ResourceUsagesInner model = BinaryData.fromString( - "{\"properties\":{\"name\":{\"value\":\"uiuaodsfcpkvxodp\",\"localizedValue\":\"zmyzydagf\"},\"limit\":4781017836578252450,\"usages\":7954521876699219554,\"unit\":\"uokktwhrdxwz\"},\"id\":\"q\",\"name\":\"mbsureximo\",\"type\":\"yocf\"}") - .toObject(ResourceUsagesInner.class); - Assertions.assertEquals(4781017836578252450L, model.properties().limit()); - Assertions.assertEquals(7954521876699219554L, model.properties().usages()); - Assertions.assertEquals("uiuaodsfcpkvxodp", model.properties().value()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - ResourceUsagesInner model - = new ResourceUsagesInner().withProperties(new GroupQuotaUsagesBase().withLimit(4781017836578252450L) - .withUsages(7954521876699219554L) - .withValue("uiuaodsfcpkvxodp")); - model = BinaryData.fromObject(model).toObject(ResourceUsagesInner.class); - Assertions.assertEquals(4781017836578252450L, model.properties().limit()); - Assertions.assertEquals(7954521876699219554L, model.properties().usages()); - Assertions.assertEquals("uiuaodsfcpkvxodp", model.properties().value()); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubRequestTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubRequestTests.java index f475207b794d..b0993d4b2b8f 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubRequestTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubRequestTests.java @@ -14,19 +14,19 @@ public final class SubRequestTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { SubRequest model = BinaryData.fromString( - "{\"name\":{\"value\":\"nyqupedeojnabck\",\"localizedValue\":\"mtxpsiebtfh\"},\"resourceType\":\"esap\",\"unit\":\"rdqmhjjdhtldwkyz\",\"provisioningState\":\"InProgress\",\"message\":\"kn\",\"subRequestId\":\"scwsv\",\"limit\":{\"limitObjectType\":\"LimitJsonObject\"}}") + "{\"name\":{\"value\":\"yueaxibxujwb\",\"localizedValue\":\"walm\"},\"resourceType\":\"yoxa\",\"unit\":\"dkzjancuxrh\",\"provisioningState\":\"InProgress\",\"message\":\"v\",\"subRequestId\":\"niwdjsw\",\"limit\":{\"limitObjectType\":\"LimitJsonObject\"}}") .toObject(SubRequest.class); - Assertions.assertEquals("nyqupedeojnabck", model.name().value()); - Assertions.assertEquals("rdqmhjjdhtldwkyz", model.unit()); + Assertions.assertEquals("yueaxibxujwb", model.name().value()); + Assertions.assertEquals("dkzjancuxrh", model.unit()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - SubRequest model = new SubRequest().withName(new ResourceName().withValue("nyqupedeojnabck")) - .withUnit("rdqmhjjdhtldwkyz") + SubRequest model = new SubRequest().withName(new ResourceName().withValue("yueaxibxujwb")) + .withUnit("dkzjancuxrh") .withLimit(new LimitJsonObject()); model = BinaryData.fromObject(model).toObject(SubRequest.class); - Assertions.assertEquals("nyqupedeojnabck", model.name().value()); - Assertions.assertEquals("rdqmhjjdhtldwkyz", model.unit()); + Assertions.assertEquals("yueaxibxujwb", model.name().value()); + Assertions.assertEquals("dkzjancuxrh", model.unit()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubscriptionQuotaAllocationsInnerTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubscriptionQuotaAllocationsInnerTests.java deleted file mode 100644 index 6230bfe7bc10..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubscriptionQuotaAllocationsInnerTests.java +++ /dev/null @@ -1,30 +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.resourcemanager.quota.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.quota.fluent.models.SubscriptionQuotaAllocationsInner; -import com.azure.resourcemanager.quota.models.SubscriptionQuotaDetails; -import org.junit.jupiter.api.Assertions; - -public final class SubscriptionQuotaAllocationsInnerTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - SubscriptionQuotaAllocationsInner model = BinaryData.fromString( - "{\"properties\":{\"region\":\"m\",\"limit\":1354331063436305404,\"shareableQuota\":3154425840860812324,\"name\":{\"value\":\"evgbmqjq\",\"localizedValue\":\"c\"}},\"id\":\"mivkwlzuvcc\",\"name\":\"wnfnbacf\",\"type\":\"onlebxetqgtzxdpn\"}") - .toObject(SubscriptionQuotaAllocationsInner.class); - Assertions.assertEquals("m", model.properties().region()); - Assertions.assertEquals(1354331063436305404L, model.properties().limit()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - SubscriptionQuotaAllocationsInner model = new SubscriptionQuotaAllocationsInner() - .withProperties(new SubscriptionQuotaDetails().withRegion("m").withLimit(1354331063436305404L)); - model = BinaryData.fromObject(model).toObject(SubscriptionQuotaAllocationsInner.class); - Assertions.assertEquals("m", model.properties().region()); - Assertions.assertEquals(1354331063436305404L, model.properties().limit()); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubscriptionQuotaAllocationsListInnerTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubscriptionQuotaAllocationsListInnerTests.java new file mode 100644 index 000000000000..24498fa556c2 --- /dev/null +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubscriptionQuotaAllocationsListInnerTests.java @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.quota.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.quota.fluent.models.SubscriptionQuotaAllocationsListInner; +import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocations; +import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocationsListProperties; +import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocationsProperties; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class SubscriptionQuotaAllocationsListInnerTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SubscriptionQuotaAllocationsListInner model = BinaryData.fromString( + "{\"properties\":{\"provisioningState\":\"Created\",\"value\":[{\"properties\":{\"resourceName\":\"jctbza\",\"limit\":3226770590349878189,\"shareableQuota\":7357191703099930404,\"name\":{\"value\":\"fkgukdkexxppof\",\"localizedValue\":\"axcfjpgddtocjjx\"}}},{\"properties\":{\"resourceName\":\"mouexhdzx\",\"limit\":7433658867107362465,\"shareableQuota\":4614606581389875358,\"name\":{\"value\":\"bzv\",\"localizedValue\":\"ntwndeicbtwnpzao\"}}},{\"properties\":{\"resourceName\":\"hrhcffcyddglmjth\",\"limit\":2053663471357654885,\"shareableQuota\":6580467149244298104,\"name\":{\"value\":\"xmqci\",\"localizedValue\":\"vhkhixu\"}}}],\"nextLink\":\"dtopbob\"},\"id\":\"ghmewuam\",\"name\":\"uhrzayvvt\",\"type\":\"gvdfgiotkftutq\"}") + .toObject(SubscriptionQuotaAllocationsListInner.class); + Assertions.assertEquals("jctbza", model.properties().value().get(0).properties().resourceName()); + Assertions.assertEquals(3226770590349878189L, model.properties().value().get(0).properties().limit()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SubscriptionQuotaAllocationsListInner model = new SubscriptionQuotaAllocationsListInner() + .withProperties(new SubscriptionQuotaAllocationsListProperties().withValue(Arrays.asList( + new SubscriptionQuotaAllocations() + .withProperties(new SubscriptionQuotaAllocationsProperties().withResourceName("jctbza") + .withLimit(3226770590349878189L)), + new SubscriptionQuotaAllocations() + .withProperties(new SubscriptionQuotaAllocationsProperties().withResourceName("mouexhdzx") + .withLimit(7433658867107362465L)), + new SubscriptionQuotaAllocations() + .withProperties(new SubscriptionQuotaAllocationsProperties().withResourceName("hrhcffcyddglmjth") + .withLimit(2053663471357654885L))))); + model = BinaryData.fromObject(model).toObject(SubscriptionQuotaAllocationsListInner.class); + Assertions.assertEquals("jctbza", model.properties().value().get(0).properties().resourceName()); + Assertions.assertEquals(3226770590349878189L, model.properties().value().get(0).properties().limit()); + } +} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubscriptionQuotaAllocationsListPropertiesTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubscriptionQuotaAllocationsListPropertiesTests.java new file mode 100644 index 000000000000..a1c335698418 --- /dev/null +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubscriptionQuotaAllocationsListPropertiesTests.java @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.quota.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocations; +import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocationsListProperties; +import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocationsProperties; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; + +public final class SubscriptionQuotaAllocationsListPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SubscriptionQuotaAllocationsListProperties model = BinaryData.fromString( + "{\"provisioningState\":\"Failed\",\"value\":[{\"properties\":{\"resourceName\":\"fgugnxkrxdqmid\",\"limit\":6800420676916675082,\"shareableQuota\":4984174641988559486,\"name\":{\"value\":\"abhjybi\",\"localizedValue\":\"h\"}}},{\"properties\":{\"resourceName\":\"bowsk\",\"limit\":4187351799054769848,\"shareableQuota\":8321881464692032483,\"name\":{\"value\":\"iywgqywgndrvynh\",\"localizedValue\":\"pphrcgynco\"}}},{\"properties\":{\"resourceName\":\"cfvmmco\",\"limit\":3154425840860812324,\"shareableQuota\":5004526075994942910,\"name\":{\"value\":\"bmqj\",\"localizedValue\":\"bcypmi\"}}}],\"nextLink\":\"w\"}") + .toObject(SubscriptionQuotaAllocationsListProperties.class); + Assertions.assertEquals("fgugnxkrxdqmid", model.value().get(0).properties().resourceName()); + Assertions.assertEquals(6800420676916675082L, model.value().get(0).properties().limit()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SubscriptionQuotaAllocationsListProperties model + = new SubscriptionQuotaAllocationsListProperties().withValue(Arrays.asList( + new SubscriptionQuotaAllocations() + .withProperties(new SubscriptionQuotaAllocationsProperties().withResourceName("fgugnxkrxdqmid") + .withLimit(6800420676916675082L)), + new SubscriptionQuotaAllocations() + .withProperties(new SubscriptionQuotaAllocationsProperties().withResourceName("bowsk") + .withLimit(4187351799054769848L)), + new SubscriptionQuotaAllocations() + .withProperties(new SubscriptionQuotaAllocationsProperties().withResourceName("cfvmmco") + .withLimit(3154425840860812324L)))); + model = BinaryData.fromObject(model).toObject(SubscriptionQuotaAllocationsListProperties.class); + Assertions.assertEquals("fgugnxkrxdqmid", model.value().get(0).properties().resourceName()); + Assertions.assertEquals(6800420676916675082L, model.value().get(0).properties().limit()); + } +} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubscriptionQuotaAllocationsListTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubscriptionQuotaAllocationsListTests.java deleted file mode 100644 index 6ba825e2d2f1..000000000000 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubscriptionQuotaAllocationsListTests.java +++ /dev/null @@ -1,37 +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.resourcemanager.quota.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.quota.fluent.models.SubscriptionQuotaAllocationsInner; -import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocationsList; -import com.azure.resourcemanager.quota.models.SubscriptionQuotaDetails; -import java.util.Arrays; -import org.junit.jupiter.api.Assertions; - -public final class SubscriptionQuotaAllocationsListTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - SubscriptionQuotaAllocationsList model = BinaryData.fromString( - "{\"value\":[{\"properties\":{\"region\":\"xxppofm\",\"limit\":685251930368374403,\"shareableQuota\":3544936977106916903,\"name\":{\"value\":\"dtocj\",\"localizedValue\":\"hvpmoue\"}},\"id\":\"dzxibqeojnxqbzvd\",\"name\":\"ntwndeicbtwnpzao\",\"type\":\"vuhrhcffcyddgl\"},{\"properties\":{\"region\":\"hjq\",\"limit\":6943639735240918018,\"shareableQuota\":3955309032354146781,\"name\":{\"value\":\"qciwqvhkhixuigdt\",\"localizedValue\":\"bob\"}},\"id\":\"ghmewuam\",\"name\":\"uhrzayvvt\",\"type\":\"gvdfgiotkftutq\"},{\"properties\":{\"region\":\"gxlefgugnxkrxd\",\"limit\":979128831673863857,\"shareableQuota\":2903451662374924947,\"name\":{\"value\":\"vqdra\",\"localizedValue\":\"jybige\"}},\"id\":\"qfbow\",\"name\":\"kanyktzlcuiywg\",\"type\":\"ywgndrv\"}],\"nextLink\":\"hzgpphrcgyncocpe\"}") - .toObject(SubscriptionQuotaAllocationsList.class); - Assertions.assertEquals("xxppofm", model.value().get(0).properties().region()); - Assertions.assertEquals(685251930368374403L, model.value().get(0).properties().limit()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - SubscriptionQuotaAllocationsList model = new SubscriptionQuotaAllocationsList().withValue(Arrays.asList( - new SubscriptionQuotaAllocationsInner() - .withProperties(new SubscriptionQuotaDetails().withRegion("xxppofm").withLimit(685251930368374403L)), - new SubscriptionQuotaAllocationsInner() - .withProperties(new SubscriptionQuotaDetails().withRegion("hjq").withLimit(6943639735240918018L)), - new SubscriptionQuotaAllocationsInner().withProperties( - new SubscriptionQuotaDetails().withRegion("gxlefgugnxkrxd").withLimit(979128831673863857L)))); - model = BinaryData.fromObject(model).toObject(SubscriptionQuotaAllocationsList.class); - Assertions.assertEquals("xxppofm", model.value().get(0).properties().region()); - Assertions.assertEquals(685251930368374403L, model.value().get(0).properties().limit()); - } -} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubscriptionQuotaAllocationsPropertiesTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubscriptionQuotaAllocationsPropertiesTests.java new file mode 100644 index 000000000000..0ff248d8d373 --- /dev/null +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubscriptionQuotaAllocationsPropertiesTests.java @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.quota.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocationsProperties; +import org.junit.jupiter.api.Assertions; + +public final class SubscriptionQuotaAllocationsPropertiesTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SubscriptionQuotaAllocationsProperties model = BinaryData.fromString( + "{\"resourceName\":\"eallnwsubisnj\",\"limit\":4579526250927488523,\"shareableQuota\":1760019269315707973,\"name\":{\"value\":\"c\",\"localizedValue\":\"qwoochcbon\"}}") + .toObject(SubscriptionQuotaAllocationsProperties.class); + Assertions.assertEquals("eallnwsubisnj", model.resourceName()); + Assertions.assertEquals(4579526250927488523L, model.limit()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SubscriptionQuotaAllocationsProperties model + = new SubscriptionQuotaAllocationsProperties().withResourceName("eallnwsubisnj") + .withLimit(4579526250927488523L); + model = BinaryData.fromObject(model).toObject(SubscriptionQuotaAllocationsProperties.class); + Assertions.assertEquals("eallnwsubisnj", model.resourceName()); + Assertions.assertEquals(4579526250927488523L, model.limit()); + } +} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubscriptionQuotaAllocationsTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubscriptionQuotaAllocationsTests.java new file mode 100644 index 000000000000..ff0851e0ba73 --- /dev/null +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubscriptionQuotaAllocationsTests.java @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.quota.generated; + +import com.azure.core.util.BinaryData; +import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocations; +import com.azure.resourcemanager.quota.models.SubscriptionQuotaAllocationsProperties; +import org.junit.jupiter.api.Assertions; + +public final class SubscriptionQuotaAllocationsTests { + @org.junit.jupiter.api.Test + public void testDeserialize() throws Exception { + SubscriptionQuotaAllocations model = BinaryData.fromString( + "{\"properties\":{\"resourceName\":\"vccfw\",\"limit\":5806791582914319234,\"shareableQuota\":6738955803467738605,\"name\":{\"value\":\"nlebxetqgtzxd\",\"localizedValue\":\"qbqqwxr\"}}}") + .toObject(SubscriptionQuotaAllocations.class); + Assertions.assertEquals("vccfw", model.properties().resourceName()); + Assertions.assertEquals(5806791582914319234L, model.properties().limit()); + } + + @org.junit.jupiter.api.Test + public void testSerialize() throws Exception { + SubscriptionQuotaAllocations model = new SubscriptionQuotaAllocations().withProperties( + new SubscriptionQuotaAllocationsProperties().withResourceName("vccfw").withLimit(5806791582914319234L)); + model = BinaryData.fromObject(model).toObject(SubscriptionQuotaAllocations.class); + Assertions.assertEquals("vccfw", model.properties().resourceName()); + Assertions.assertEquals(5806791582914319234L, model.properties().limit()); + } +} diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubscriptionQuotaDetailsNameTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubscriptionQuotaDetailsNameTests.java index 84c731155dbc..801cc0a315a3 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubscriptionQuotaDetailsNameTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubscriptionQuotaDetailsNameTests.java @@ -10,8 +10,9 @@ public final class SubscriptionQuotaDetailsNameTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - SubscriptionQuotaDetailsName model = BinaryData.fromString("{\"value\":\"nzscxa\",\"localizedValue\":\"ooch\"}") - .toObject(SubscriptionQuotaDetailsName.class); + SubscriptionQuotaDetailsName model + = BinaryData.fromString("{\"value\":\"pj\",\"localizedValue\":\"asxazjpqyegualhb\"}") + .toObject(SubscriptionQuotaDetailsName.class); } @org.junit.jupiter.api.Test diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubscriptionQuotaDetailsTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubscriptionQuotaDetailsTests.java index 4ab4f1da97f2..af4ff85daaa2 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubscriptionQuotaDetailsTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/SubscriptionQuotaDetailsTests.java @@ -12,18 +12,18 @@ public final class SubscriptionQuotaDetailsTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { SubscriptionQuotaDetails model = BinaryData.fromString( - "{\"region\":\"qqwx\",\"limit\":83601086548866102,\"shareableQuota\":8559873821751147559,\"name\":{\"value\":\"sub\",\"localizedValue\":\"njampm\"}}") + "{\"resourceName\":\"pkvlrxn\",\"limit\":2730192604247648868,\"shareableQuota\":7721443017261516589,\"name\":{\"value\":\"oflokey\",\"localizedValue\":\"enjbdlwtgrhp\"}}") .toObject(SubscriptionQuotaDetails.class); - Assertions.assertEquals("qqwx", model.region()); - Assertions.assertEquals(83601086548866102L, model.limit()); + Assertions.assertEquals("pkvlrxn", model.resourceName()); + Assertions.assertEquals(2730192604247648868L, model.limit()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { SubscriptionQuotaDetails model - = new SubscriptionQuotaDetails().withRegion("qqwx").withLimit(83601086548866102L); + = new SubscriptionQuotaDetails().withResourceName("pkvlrxn").withLimit(2730192604247648868L); model = BinaryData.fromObject(model).toObject(SubscriptionQuotaDetails.class); - Assertions.assertEquals("qqwx", model.region()); - Assertions.assertEquals(83601086548866102L, model.limit()); + Assertions.assertEquals("pkvlrxn", model.resourceName()); + Assertions.assertEquals(2730192604247648868L, model.limit()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/UsagesGetWithResponseMockTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/UsagesGetWithResponseMockTests.java index 3fac75a94bb4..61e109575148 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/UsagesGetWithResponseMockTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/UsagesGetWithResponseMockTests.java @@ -6,8 +6,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.quota.QuotaManager; import com.azure.resourcemanager.quota.models.CurrentUsagesBase; @@ -22,22 +22,22 @@ public final class UsagesGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"usages\":{\"value\":1682572993,\"usagesType\":\"Individual\"},\"unit\":\"xleptramx\",\"name\":{\"value\":\"wlwnwxuqlcv\",\"localizedValue\":\"ypatdooaojkniod\"},\"resourceType\":\"oebwnujhemms\",\"quotaPeriod\":\"dkcrodt\",\"isQuotaApplicable\":true,\"properties\":\"datawj\"},\"id\":\"fltkacjv\",\"name\":\"f\",\"type\":\"dlfoakggkfp\"}"; + = "{\"properties\":{\"usages\":{\"value\":596140767,\"usagesType\":\"Combined\"},\"unit\":\"wlquuijfqkace\",\"name\":{\"value\":\"pfpubjibww\",\"localizedValue\":\"tohqkvpuvksgp\"},\"resourceType\":\"aknynfsynljphuop\",\"quotaPeriod\":\"dlqiyntorzih\",\"isQuotaApplicable\":false,\"properties\":\"datajswsrmslyz\"},\"id\":\"pzbchck\",\"name\":\"qzqioxiysuiizy\",\"type\":\"ked\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); QuotaManager manager = QuotaManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); CurrentUsagesBase response = manager.usages() - .getWithResponse("xiilivpdtiirqt", "qoaxoruzfgs", com.azure.core.util.Context.NONE) + .getWithResponse("suwsyrsnds", "tgadgvraeaen", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals(1682572993, response.properties().usages().value()); - Assertions.assertEquals(UsagesTypes.INDIVIDUAL, response.properties().usages().usagesType()); - Assertions.assertEquals("wlwnwxuqlcv", response.properties().name().value()); - Assertions.assertEquals("oebwnujhemms", response.properties().resourceType()); + Assertions.assertEquals(596140767, response.properties().usages().value()); + Assertions.assertEquals(UsagesTypes.COMBINED, response.properties().usages().usagesType()); + Assertions.assertEquals("pfpubjibww", response.properties().name().value()); + Assertions.assertEquals("aknynfsynljphuop", response.properties().resourceType()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/UsagesLimitsTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/UsagesLimitsTests.java index 3f122e9fd30b..1951a1a0ac27 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/UsagesLimitsTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/UsagesLimitsTests.java @@ -18,29 +18,47 @@ public final class UsagesLimitsTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { UsagesLimits model = BinaryData.fromString( - "{\"value\":[{\"properties\":{\"usages\":{\"value\":1616487247,\"usagesType\":\"Combined\"},\"unit\":\"pyd\",\"name\":{\"value\":\"hxdeoejz\",\"localizedValue\":\"w\"},\"resourceType\":\"sjttgzfbish\",\"quotaPeriod\":\"khaj\",\"isQuotaApplicable\":true,\"properties\":\"dataa\"},\"id\":\"dphagalpbuxwgip\",\"name\":\"honowkgshwank\",\"type\":\"xzbinjeputt\"}],\"nextLink\":\"ywnuzoq\"}") + "{\"value\":[{\"properties\":{\"usages\":{\"value\":682758161,\"usagesType\":\"Combined\"},\"unit\":\"zjuqkhrsaj\",\"name\":{\"value\":\"uo\",\"localizedValue\":\"skghsauuimj\"},\"resourceType\":\"xieduugidyjrr\",\"quotaPeriod\":\"y\",\"isQuotaApplicable\":true,\"properties\":\"datae\"},\"id\":\"csonpclhoco\",\"name\":\"slkevle\",\"type\":\"gz\"},{\"properties\":{\"usages\":{\"value\":635098272,\"usagesType\":\"Combined\"},\"unit\":\"faxkffeii\",\"name\":{\"value\":\"vmezy\",\"localizedValue\":\"hxmzsbbzoggig\"},\"resourceType\":\"wburvjxxjnspydpt\",\"quotaPeriod\":\"enkouknvudw\",\"isQuotaApplicable\":true,\"properties\":\"databldngkpoc\"},\"id\":\"pazyxoegukg\",\"name\":\"npiucgygevqznty\",\"type\":\"mrbpizcdrqj\"},{\"properties\":{\"usages\":{\"value\":1305658178,\"usagesType\":\"Individual\"},\"unit\":\"yhxdeoejzicwi\",\"name\":{\"value\":\"ttgzfbis\",\"localizedValue\":\"bkh\"},\"resourceType\":\"deyeamdphagalpbu\",\"quotaPeriod\":\"gipwhonowkg\",\"isQuotaApplicable\":true,\"properties\":\"datankixzbinj\"},\"id\":\"pu\",\"name\":\"tmryw\",\"type\":\"uzoqft\"}],\"nextLink\":\"qzrnkcqvyxlwhz\"}") .toObject(UsagesLimits.class); - Assertions.assertEquals(1616487247, model.value().get(0).properties().usages().value()); + Assertions.assertEquals(682758161, model.value().get(0).properties().usages().value()); Assertions.assertEquals(UsagesTypes.COMBINED, model.value().get(0).properties().usages().usagesType()); - Assertions.assertEquals("hxdeoejz", model.value().get(0).properties().name().value()); - Assertions.assertEquals("sjttgzfbish", model.value().get(0).properties().resourceType()); - Assertions.assertEquals("ywnuzoq", model.nextLink()); + Assertions.assertEquals("uo", model.value().get(0).properties().name().value()); + Assertions.assertEquals("xieduugidyjrr", model.value().get(0).properties().resourceType()); + Assertions.assertEquals("qzrnkcqvyxlwhz", model.nextLink()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - UsagesLimits model = new UsagesLimits() - .withValue(Arrays.asList(new CurrentUsagesBaseInner().withProperties(new UsagesProperties() - .withUsages(new UsagesObject().withValue(1616487247).withUsagesType(UsagesTypes.COMBINED)) - .withName(new ResourceName().withValue("hxdeoejz")) - .withResourceType("sjttgzfbish") - .withProperties("dataa")))) - .withNextLink("ywnuzoq"); + UsagesLimits model + = new UsagesLimits() + .withValue( + Arrays + .asList( + new CurrentUsagesBaseInner().withProperties( + new UsagesProperties() + .withUsages( + new UsagesObject().withValue(682758161).withUsagesType(UsagesTypes.COMBINED)) + .withName(new ResourceName().withValue("uo")) + .withResourceType("xieduugidyjrr") + .withProperties("datae")), + new CurrentUsagesBaseInner().withProperties(new UsagesProperties() + .withUsages( + new UsagesObject().withValue(635098272).withUsagesType(UsagesTypes.COMBINED)) + .withName(new ResourceName().withValue("vmezy")) + .withResourceType("wburvjxxjnspydpt") + .withProperties("databldngkpoc")), + new CurrentUsagesBaseInner().withProperties(new UsagesProperties() + .withUsages( + new UsagesObject().withValue(1305658178).withUsagesType(UsagesTypes.INDIVIDUAL)) + .withName(new ResourceName().withValue("ttgzfbis")) + .withResourceType("deyeamdphagalpbu") + .withProperties("datankixzbinj")))) + .withNextLink("qzrnkcqvyxlwhz"); model = BinaryData.fromObject(model).toObject(UsagesLimits.class); - Assertions.assertEquals(1616487247, model.value().get(0).properties().usages().value()); + Assertions.assertEquals(682758161, model.value().get(0).properties().usages().value()); Assertions.assertEquals(UsagesTypes.COMBINED, model.value().get(0).properties().usages().usagesType()); - Assertions.assertEquals("hxdeoejz", model.value().get(0).properties().name().value()); - Assertions.assertEquals("sjttgzfbish", model.value().get(0).properties().resourceType()); - Assertions.assertEquals("ywnuzoq", model.nextLink()); + Assertions.assertEquals("uo", model.value().get(0).properties().name().value()); + Assertions.assertEquals("xieduugidyjrr", model.value().get(0).properties().resourceType()); + Assertions.assertEquals("qzrnkcqvyxlwhz", model.nextLink()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/UsagesListMockTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/UsagesListMockTests.java index 55fb4f3dd8c2..4f46aaadc6d3 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/UsagesListMockTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/UsagesListMockTests.java @@ -7,8 +7,8 @@ import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.resourcemanager.quota.QuotaManager; import com.azure.resourcemanager.quota.models.CurrentUsagesBase; @@ -23,21 +23,21 @@ public final class UsagesListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"usages\":{\"value\":648285682,\"usagesType\":\"Individual\"},\"unit\":\"r\",\"name\":{\"value\":\"agxsdszuemps\",\"localizedValue\":\"kfzbeyvpnqicvi\"},\"resourceType\":\"kjj\",\"quotaPeriod\":\"xrbuukzclew\",\"isQuotaApplicable\":false,\"properties\":\"datawp\"},\"id\":\"ztzp\",\"name\":\"fn\",\"type\":\"ckw\"}]}"; + = "{\"value\":[{\"properties\":{\"usages\":{\"value\":159300714,\"usagesType\":\"Combined\"},\"unit\":\"yynpcdpumnzgmwz\",\"name\":{\"value\":\"biknsorgjhxbld\",\"localizedValue\":\"wwrlkdmtncv\"},\"resourceType\":\"otllxdyhgsyo\",\"quotaPeriod\":\"gjltdtbnnhado\",\"isQuotaApplicable\":true,\"properties\":\"datavcikhnvpamqgx\"},\"id\":\"queziky\",\"name\":\"ggxkallatmelwuip\",\"type\":\"ccjzkzivgvv\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); QuotaManager manager = QuotaManager.configure() .withHttpClient(httpClient) .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), - new AzureProfile("", "", AzureEnvironment.AZURE)); + new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD)); PagedIterable response - = manager.usages().list("gaowpulpqblylsyx", com.azure.core.util.Context.NONE); + = manager.usages().list("atrwyhqmibzyh", com.azure.core.util.Context.NONE); - Assertions.assertEquals(648285682, response.iterator().next().properties().usages().value()); - Assertions.assertEquals(UsagesTypes.INDIVIDUAL, response.iterator().next().properties().usages().usagesType()); - Assertions.assertEquals("agxsdszuemps", response.iterator().next().properties().name().value()); - Assertions.assertEquals("kjj", response.iterator().next().properties().resourceType()); + Assertions.assertEquals(159300714, response.iterator().next().properties().usages().value()); + Assertions.assertEquals(UsagesTypes.COMBINED, response.iterator().next().properties().usages().usagesType()); + Assertions.assertEquals("biknsorgjhxbld", response.iterator().next().properties().name().value()); + Assertions.assertEquals("otllxdyhgsyo", response.iterator().next().properties().resourceType()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/UsagesObjectTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/UsagesObjectTests.java index eecee48f1a7b..a275831761da 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/UsagesObjectTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/UsagesObjectTests.java @@ -13,16 +13,16 @@ public final class UsagesObjectTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { UsagesObject model - = BinaryData.fromString("{\"value\":1340454664,\"usagesType\":\"Combined\"}").toObject(UsagesObject.class); - Assertions.assertEquals(1340454664, model.value()); + = BinaryData.fromString("{\"value\":1520989721,\"usagesType\":\"Combined\"}").toObject(UsagesObject.class); + Assertions.assertEquals(1520989721, model.value()); Assertions.assertEquals(UsagesTypes.COMBINED, model.usagesType()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - UsagesObject model = new UsagesObject().withValue(1340454664).withUsagesType(UsagesTypes.COMBINED); + UsagesObject model = new UsagesObject().withValue(1520989721).withUsagesType(UsagesTypes.COMBINED); model = BinaryData.fromObject(model).toObject(UsagesObject.class); - Assertions.assertEquals(1340454664, model.value()); + Assertions.assertEquals(1520989721, model.value()); Assertions.assertEquals(UsagesTypes.COMBINED, model.usagesType()); } } diff --git a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/UsagesPropertiesTests.java b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/UsagesPropertiesTests.java index 214f5b11679c..182ac06fcee5 100644 --- a/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/UsagesPropertiesTests.java +++ b/sdk/quota/azure-resourcemanager-quota/src/test/java/com/azure/resourcemanager/quota/generated/UsagesPropertiesTests.java @@ -15,25 +15,25 @@ public final class UsagesPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { UsagesProperties model = BinaryData.fromString( - "{\"usages\":{\"value\":1146785059,\"usagesType\":\"Combined\"},\"unit\":\"axkffei\",\"name\":{\"value\":\"lvmezyvshxmzsbbz\",\"localizedValue\":\"gigr\"},\"resourceType\":\"burvjxxjnspy\",\"quotaPeriod\":\"tko\",\"isQuotaApplicable\":true,\"properties\":\"datauknvudwti\"}") + "{\"usages\":{\"value\":1010959661,\"usagesType\":\"Combined\"},\"unit\":\"fksymddystki\",\"name\":{\"value\":\"hqyudxorrqnbpoc\",\"localizedValue\":\"yifqrvkdvjsllrmv\"},\"resourceType\":\"f\",\"quotaPeriod\":\"t\",\"isQuotaApplicable\":false,\"properties\":\"dataulexxbczwtr\"}") .toObject(UsagesProperties.class); - Assertions.assertEquals(1146785059, model.usages().value()); + Assertions.assertEquals(1010959661, model.usages().value()); Assertions.assertEquals(UsagesTypes.COMBINED, model.usages().usagesType()); - Assertions.assertEquals("lvmezyvshxmzsbbz", model.name().value()); - Assertions.assertEquals("burvjxxjnspy", model.resourceType()); + Assertions.assertEquals("hqyudxorrqnbpoc", model.name().value()); + Assertions.assertEquals("f", model.resourceType()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { UsagesProperties model = new UsagesProperties() - .withUsages(new UsagesObject().withValue(1146785059).withUsagesType(UsagesTypes.COMBINED)) - .withName(new ResourceName().withValue("lvmezyvshxmzsbbz")) - .withResourceType("burvjxxjnspy") - .withProperties("datauknvudwti"); + .withUsages(new UsagesObject().withValue(1010959661).withUsagesType(UsagesTypes.COMBINED)) + .withName(new ResourceName().withValue("hqyudxorrqnbpoc")) + .withResourceType("f") + .withProperties("dataulexxbczwtr"); model = BinaryData.fromObject(model).toObject(UsagesProperties.class); - Assertions.assertEquals(1146785059, model.usages().value()); + Assertions.assertEquals(1010959661, model.usages().value()); Assertions.assertEquals(UsagesTypes.COMBINED, model.usages().usagesType()); - Assertions.assertEquals("lvmezyvshxmzsbbz", model.name().value()); - Assertions.assertEquals("burvjxxjnspy", model.resourceType()); + Assertions.assertEquals("hqyudxorrqnbpoc", model.name().value()); + Assertions.assertEquals("f", model.resourceType()); } } diff --git a/sdk/recoveryservices/azure-resourcemanager-recoveryservices/README.md b/sdk/recoveryservices/azure-resourcemanager-recoveryservices/README.md index 7bfecd17d96e..ebd74e01a39e 100644 --- a/sdk/recoveryservices/azure-resourcemanager-recoveryservices/README.md +++ b/sdk/recoveryservices/azure-resourcemanager-recoveryservices/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-recoveryservices - 1.4.0 + 1.5.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -116,4 +116,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Frecoveryservices%2Fazure-resourcemanager-recoveryservices%2FREADME.png) + diff --git a/sdk/recoveryservices/azure-resourcemanager-recoveryservices/pom.xml b/sdk/recoveryservices/azure-resourcemanager-recoveryservices/pom.xml index 02fdebae0ca6..2ba84926acfd 100644 --- a/sdk/recoveryservices/azure-resourcemanager-recoveryservices/pom.xml +++ b/sdk/recoveryservices/azure-resourcemanager-recoveryservices/pom.xml @@ -51,29 +51,29 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/recoveryservicesbackup/azure-resourcemanager-recoveryservicesbackup/README.md b/sdk/recoveryservicesbackup/azure-resourcemanager-recoveryservicesbackup/README.md index 3153ebfaae46..802cacf6fe29 100644 --- a/sdk/recoveryservicesbackup/azure-resourcemanager-recoveryservicesbackup/README.md +++ b/sdk/recoveryservicesbackup/azure-resourcemanager-recoveryservicesbackup/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-recoveryservicesbackup - 1.5.0 + 1.6.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -175,4 +175,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Frecoveryservicesbackup%2Fazure-resourcemanager-recoveryservicesbackup%2FREADME.png) + diff --git a/sdk/recoveryservicesbackup/azure-resourcemanager-recoveryservicesbackup/pom.xml b/sdk/recoveryservicesbackup/azure-resourcemanager-recoveryservicesbackup/pom.xml index af1d135c8298..b998bca60732 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.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test @@ -79,7 +79,7 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/recoveryservicesdatareplication/azure-resourcemanager-recoveryservicesdatareplication/README.md b/sdk/recoveryservicesdatareplication/azure-resourcemanager-recoveryservicesdatareplication/README.md index 693587c0320f..c4488674d10b 100644 --- a/sdk/recoveryservicesdatareplication/azure-resourcemanager-recoveryservicesdatareplication/README.md +++ b/sdk/recoveryservicesdatareplication/azure-resourcemanager-recoveryservicesdatareplication/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-recoveryservicesdatareplication - 1.0.0-beta.2 + 1.0.0-beta.3 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Frecoveryservicesdatareplication%2Fazure-resourcemanager-recoveryservicesdatareplication%2FREADME.png) + diff --git a/sdk/recoveryservicesdatareplication/azure-resourcemanager-recoveryservicesdatareplication/pom.xml b/sdk/recoveryservicesdatareplication/azure-resourcemanager-recoveryservicesdatareplication/pom.xml index b3064d816a3b..fb529a7ac4fd 100644 --- a/sdk/recoveryservicesdatareplication/azure-resourcemanager-recoveryservicesdatareplication/pom.xml +++ b/sdk/recoveryservicesdatareplication/azure-resourcemanager-recoveryservicesdatareplication/pom.xml @@ -52,23 +52,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/recoveryservicessiterecovery/azure-resourcemanager-recoveryservicessiterecovery/README.md b/sdk/recoveryservicessiterecovery/azure-resourcemanager-recoveryservicessiterecovery/README.md index ea8896071325..057759fa7668 100644 --- a/sdk/recoveryservicessiterecovery/azure-resourcemanager-recoveryservicessiterecovery/README.md +++ b/sdk/recoveryservicessiterecovery/azure-resourcemanager-recoveryservicessiterecovery/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-recoveryservicessiterecovery - 1.2.0 + 1.3.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Frecoveryservicessiterecovery%2Fazure-resourcemanager-recoveryservicessiterecovery%2FREADME.png) + diff --git a/sdk/recoveryservicessiterecovery/azure-resourcemanager-recoveryservicessiterecovery/pom.xml b/sdk/recoveryservicessiterecovery/azure-resourcemanager-recoveryservicessiterecovery/pom.xml index d19a1b6c077c..2cc4b3854c42 100644 --- a/sdk/recoveryservicessiterecovery/azure-resourcemanager-recoveryservicessiterecovery/pom.xml +++ b/sdk/recoveryservicessiterecovery/azure-resourcemanager-recoveryservicessiterecovery/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/redhatopenshift/azure-resourcemanager-redhatopenshift/README.md b/sdk/redhatopenshift/azure-resourcemanager-redhatopenshift/README.md index 022e11819738..709fa11c38de 100644 --- a/sdk/redhatopenshift/azure-resourcemanager-redhatopenshift/README.md +++ b/sdk/redhatopenshift/azure-resourcemanager-redhatopenshift/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-redhatopenshift - 1.0.0-beta.1 + 1.0.0-beta.2 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fredhatopenshift%2Fazure-resourcemanager-redhatopenshift%2FREADME.png) + diff --git a/sdk/redhatopenshift/azure-resourcemanager-redhatopenshift/pom.xml b/sdk/redhatopenshift/azure-resourcemanager-redhatopenshift/pom.xml index 476f815ca664..f9126d7c07da 100644 --- a/sdk/redhatopenshift/azure-resourcemanager-redhatopenshift/pom.xml +++ b/sdk/redhatopenshift/azure-resourcemanager-redhatopenshift/pom.xml @@ -51,28 +51,28 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/redisenterprise/azure-resourcemanager-redisenterprise/README.md b/sdk/redisenterprise/azure-resourcemanager-redisenterprise/README.md index 1ce5cc3c82eb..e3caadc151f6 100644 --- a/sdk/redisenterprise/azure-resourcemanager-redisenterprise/README.md +++ b/sdk/redisenterprise/azure-resourcemanager-redisenterprise/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-redisenterprise - 2.1.0-beta.2 + 2.1.0-beta.3 ``` [//]: # ({x-version-update-end}) @@ -111,4 +111,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fredisenterprise%2Fazure-resourcemanager-redisenterprise%2FREADME.png) + diff --git a/sdk/redisenterprise/azure-resourcemanager-redisenterprise/pom.xml b/sdk/redisenterprise/azure-resourcemanager-redisenterprise/pom.xml index cae68df98735..f9f1f15b2f82 100644 --- a/sdk/redisenterprise/azure-resourcemanager-redisenterprise/pom.xml +++ b/sdk/redisenterprise/azure-resourcemanager-redisenterprise/pom.xml @@ -51,29 +51,29 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/relay/azure-resourcemanager-relay/README.md b/sdk/relay/azure-resourcemanager-relay/README.md index 1b77ae473131..bd3169daa6f9 100644 --- a/sdk/relay/azure-resourcemanager-relay/README.md +++ b/sdk/relay/azure-resourcemanager-relay/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-relay - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Frelay%2Fazure-resourcemanager-relay%2FREADME.png) + diff --git a/sdk/relay/azure-resourcemanager-relay/pom.xml b/sdk/relay/azure-resourcemanager-relay/pom.xml index 4baa5001032d..e4c401428d3d 100644 --- a/sdk/relay/azure-resourcemanager-relay/pom.xml +++ b/sdk/relay/azure-resourcemanager-relay/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/remoterendering/azure-mixedreality-remoterendering/CHANGELOG.md b/sdk/remoterendering/azure-mixedreality-remoterendering/CHANGELOG.md index b9a8ee3b9907..acbdcb3748c5 100644 --- a/sdk/remoterendering/azure-mixedreality-remoterendering/CHANGELOG.md +++ b/sdk/remoterendering/azure-mixedreality-remoterendering/CHANGELOG.md @@ -10,6 +10,14 @@ ### Other Changes +## 1.1.36 (2025-02-27) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. +- Upgraded `azure-mixedreality-authentication` from `1.2.29` to version `1.2.31`. ## 1.1.35 (2024-12-04) diff --git a/sdk/remoterendering/azure-mixedreality-remoterendering/README.md b/sdk/remoterendering/azure-mixedreality-remoterendering/README.md index aefd2d40f2ea..77ed5679dc56 100644 --- a/sdk/remoterendering/azure-mixedreality-remoterendering/README.md +++ b/sdk/remoterendering/azure-mixedreality-remoterendering/README.md @@ -60,7 +60,7 @@ Add the following Maven dependency: com.azure azure-mixedreality-remoterendering - 1.1.20 + 1.1.36 ``` [//]: # ({x-version-update-end}) @@ -278,15 +278,6 @@ You can get information about your conversions using the `listConversions` metho This method may return conversions which have yet to start, conversions which are running and conversions which have finished. In this example, we just list the output URLs of successful conversions started in the last day. -```java readme-sample-listConversions -for (AssetConversion conversion : client.listConversions()) { - if ((conversion.getStatus() == AssetConversionStatus.SUCCEEDED) - && (conversion.getCreationTime().isAfter(OffsetDateTime.now().minusDays(1)))) { - logger.info("Output Asset URL: {}", conversion.getOutputAssetUrl()); - } -} -``` - ### Create a rendering session We assume that a RemoteRenderingClient has been constructed as described in the [Authenticate the Client](#authenticate-the-client) section. @@ -403,4 +394,4 @@ For more information see the [Code of Conduct FAQ](https://opensource.microsoft. [troubleshoot]: https://learn.microsoft.com/azure/remote-rendering/resources/troubleshoot [api_reference_doc]: https://learn.microsoft.com/rest/api/mixedreality/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fmixedreality%2Fazure-mixedreality-remoterendering%2FREADME.png) + diff --git a/sdk/remoterendering/azure-mixedreality-remoterendering/pom.xml b/sdk/remoterendering/azure-mixedreality-remoterendering/pom.xml index 4a4409fad755..e39ba8ccbf1a 100644 --- a/sdk/remoterendering/azure-mixedreality-remoterendering/pom.xml +++ b/sdk/remoterendering/azure-mixedreality-remoterendering/pom.xml @@ -37,31 +37,31 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-mixedreality-authentication - 1.2.30 + 1.2.31 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-core-http-netty - 1.15.7 + 1.15.11 compile diff --git a/sdk/reservations/azure-resourcemanager-reservations/README.md b/sdk/reservations/azure-resourcemanager-reservations/README.md index 2458858fb7f5..c157d4c20e95 100644 --- a/sdk/reservations/azure-resourcemanager-reservations/README.md +++ b/sdk/reservations/azure-resourcemanager-reservations/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-reservations - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Freservations%2Fazure-resourcemanager-reservations%2FREADME.png) + diff --git a/sdk/reservations/azure-resourcemanager-reservations/pom.xml b/sdk/reservations/azure-resourcemanager-reservations/pom.xml index 393246be3297..67b7cad3c377 100644 --- a/sdk/reservations/azure-resourcemanager-reservations/pom.xml +++ b/sdk/reservations/azure-resourcemanager-reservations/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/resourceconnector/azure-resourcemanager-resourceconnector/README.md b/sdk/resourceconnector/azure-resourcemanager-resourceconnector/README.md index ffe653f67fd7..acfd7dd8f35c 100644 --- a/sdk/resourceconnector/azure-resourcemanager-resourceconnector/README.md +++ b/sdk/resourceconnector/azure-resourcemanager-resourceconnector/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-resourceconnector - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fresourceconnector%2Fazure-resourcemanager-resourceconnector%2FREADME.png) + diff --git a/sdk/resourceconnector/azure-resourcemanager-resourceconnector/pom.xml b/sdk/resourceconnector/azure-resourcemanager-resourceconnector/pom.xml index 6684cc21cabb..b6d180ebb018 100644 --- a/sdk/resourceconnector/azure-resourcemanager-resourceconnector/pom.xml +++ b/sdk/resourceconnector/azure-resourcemanager-resourceconnector/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/resourcegraph/azure-resourcemanager-resourcegraph/README.md b/sdk/resourcegraph/azure-resourcemanager-resourcegraph/README.md index d761eb2c3335..83254ecd5402 100644 --- a/sdk/resourcegraph/azure-resourcemanager-resourcegraph/README.md +++ b/sdk/resourcegraph/azure-resourcemanager-resourcegraph/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-resourcegraph - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -114,4 +114,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fresourcegraph%2Fazure-resourcemanager-resourcegraph%2FREADME.png) + diff --git a/sdk/resourcegraph/azure-resourcemanager-resourcegraph/pom.xml b/sdk/resourcegraph/azure-resourcemanager-resourcegraph/pom.xml index 17b88eaacc24..d860fce258ce 100644 --- a/sdk/resourcegraph/azure-resourcemanager-resourcegraph/pom.xml +++ b/sdk/resourcegraph/azure-resourcemanager-resourcegraph/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/resourcehealth/azure-resourcemanager-resourcehealth/README.md b/sdk/resourcehealth/azure-resourcemanager-resourcehealth/README.md index e71633bac9ae..bbef5482494d 100644 --- a/sdk/resourcehealth/azure-resourcemanager-resourcehealth/README.md +++ b/sdk/resourcehealth/azure-resourcemanager-resourcehealth/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-resourcehealth - 1.1.0-beta.3 + 1.1.0-beta.4 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fresourcehealth%2Fazure-resourcemanager-resourcehealth%2FREADME.png) + diff --git a/sdk/resourcehealth/azure-resourcemanager-resourcehealth/pom.xml b/sdk/resourcehealth/azure-resourcemanager-resourcehealth/pom.xml index 2e35bb458038..d0e7a3a510a5 100644 --- a/sdk/resourcehealth/azure-resourcemanager-resourcehealth/pom.xml +++ b/sdk/resourcehealth/azure-resourcemanager-resourcehealth/pom.xml @@ -52,23 +52,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test @@ -92,7 +92,7 @@ com.azure.resourcemanager azure-resourcemanager-compute - 2.46.0 + 2.48.0 test diff --git a/sdk/resourcemanager/README.md b/sdk/resourcemanager/README.md index 60fdd77583e1..4cafbda28b1a 100644 --- a/sdk/resourcemanager/README.md +++ b/sdk/resourcemanager/README.md @@ -38,7 +38,7 @@ For your convenience, we have provided a multi-service package that includes som com.azure.resourcemanager azure-resourcemanager - 2.46.0 + 2.49.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -100,7 +100,7 @@ Azure Management Libraries require a `TokenCredential` implementation for authen com.azure azure-identity - 1.14.2 + 1.15.3 ``` [//]: # ({x-version-update-end}) @@ -112,7 +112,7 @@ Azure Management Libraries require a `TokenCredential` implementation for authen com.azure azure-core-http-netty - 1.15.7 + 1.15.10 ``` [//]: # ({x-version-update-end}) @@ -300,7 +300,7 @@ For example, here is sample maven dependency for Compute package. com.azure.resourcemanager azure-resourcemanager-compute - 2.46.0 + 2.49.0-beta.1 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/resourcemanager/api-specs.json b/sdk/resourcemanager/api-specs.json index c3015ac77974..4757a69c3884 100644 --- a/sdk/resourcemanager/api-specs.json +++ b/sdk/resourcemanager/api-specs.json @@ -70,7 +70,7 @@ "dir": "azure-resourcemanager-containerservice", "source": "specification/containerservice/resource-manager/Microsoft.ContainerService/aks/readme.md", "package": "com.azure.resourcemanager.containerservice", - "args": "--tag=package-2024-09 --modelerfour.lenient-model-deduplication --preserve-model=ContainerServiceVMSizeTypes --rename-model=Ossku:OSSku" + "args": "--tag=package-2024-10 --modelerfour.lenient-model-deduplication --preserve-model=ContainerServiceVMSizeTypes --rename-model=Ossku:OSSku" }, "containerservice-hybrid": { "dir": "../resourcemanagerhybrid/azure-resourcemanager-containerservice", @@ -226,7 +226,8 @@ "dir": "azure-resourcemanager-resources", "source": "specification/resources/resource-manager/readme.md", "package": "com.azure.resourcemanager.resources", - "args": "--tag=package-resources-2024-03 --add-inner=Deployment" + "args": "--tag=package-resources-2024-11 --add-inner=Deployment", + "note": "Remove `final` from `ResourceReference`, as it is used as superclass in deploymentstacks." }, "resources-hybrid": { "dir": "../resourcemanagerhybrid/azure-resourcemanager-resources", @@ -258,7 +259,7 @@ "dir": "azure-resourcemanager-storage", "source": "specification/storage/resource-manager/readme.md", "package": "com.azure.resourcemanager.storage", - "args": "--tag=package-2023-05 --modelerfour.lenient-model-deduplication --rename-model=AllowedMethods:CorsRuleAllowedMethodsItem,AccountType:ActiveDirectoryPropertiesAccountType --property-include-always=EncryptionIdentity.encryptionUserAssignedIdentity" + "args": "--tag=package-2024-01 --modelerfour.lenient-model-deduplication --rename-model=AllowedMethods:CorsRuleAllowedMethodsItem,AccountType:ActiveDirectoryPropertiesAccountType --property-include-always=EncryptionIdentity.encryptionUserAssignedIdentity" }, "storage-hybrid": { "dir": "../resourcemanagerhybrid/azure-resourcemanager-storage", diff --git a/sdk/resourcemanager/autocent.js b/sdk/resourcemanager/autocent.js index 11f2536becac..64068834bbd8 100644 --- a/sdk/resourcemanager/autocent.js +++ b/sdk/resourcemanager/autocent.js @@ -13,7 +13,9 @@ const pkgRegEx2 = /Package\s+tag\s+(.+)\. com.azure.resourcemanager azure-resourcemanager-appplatform - 2.46.0 + 2.49.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -39,7 +39,7 @@ Azure tenant ID can be configured via `AZURE_TENANT_ID` environment variable. Assuming the use of the `DefaultAzureCredential` credential class, the client can be authenticated using the following code: ```java readme-sample-authenticate -AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); +AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/pom.xml b/sdk/resourcemanager/azure-resourcemanager-appplatform/pom.xml index 333e08589f46..8ae17783a875 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/pom.xml @@ -14,7 +14,7 @@ com.azure.resourcemanager azure-resourcemanager-appplatform - 2.47.0-beta.1 + 2.49.0-beta.1 jar Microsoft Azure SDK for App Platform Management @@ -62,12 +62,12 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure azure-storage-file-share - 12.25.1 + 12.25.2 com.azure @@ -96,31 +96,31 @@ com.azure azure-core-http-netty - 1.15.7 + 1.15.11 test com.azure azure-security-keyvault-certificates - 4.7.1 + 4.7.3 test com.azure.resourcemanager azure-resourcemanager-keyvault - 2.47.0-beta.1 + 2.49.0-beta.1 test com.azure.resourcemanager azure-resourcemanager-dns - 2.47.0-beta.1 + 2.49.0-beta.1 test com.azure.resourcemanager azure-resourcemanager-appservice - 2.47.0-beta.1 + 2.49.0-beta.1 test diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/AppPlatformManagementClientBuilder.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/AppPlatformManagementClientBuilder.java index 9d8507212c5c..96d8a70fe9c9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/AppPlatformManagementClientBuilder.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/main/java/com/azure/resourcemanager/appplatform/implementation/AppPlatformManagementClientBuilder.java @@ -28,7 +28,7 @@ public final class AppPlatformManagementClientBuilder { /** * Sets Gets subscription ID which uniquely identify the Microsoft Azure subscription. The subscription ID forms * part of the URI for every service call. - * + * * @param subscriptionId the subscriptionId value. * @return the AppPlatformManagementClientBuilder. */ @@ -44,7 +44,7 @@ public AppPlatformManagementClientBuilder subscriptionId(String subscriptionId) /** * Sets server parameter. - * + * * @param endpoint the endpoint value. * @return the AppPlatformManagementClientBuilder. */ @@ -60,7 +60,7 @@ public AppPlatformManagementClientBuilder endpoint(String endpoint) { /** * Sets The environment to connect to. - * + * * @param environment the environment value. * @return the AppPlatformManagementClientBuilder. */ @@ -76,7 +76,7 @@ public AppPlatformManagementClientBuilder environment(AzureEnvironment environme /** * Sets The HTTP pipeline to send requests through. - * + * * @param pipeline the pipeline value. * @return the AppPlatformManagementClientBuilder. */ @@ -92,7 +92,7 @@ public AppPlatformManagementClientBuilder pipeline(HttpPipeline pipeline) { /** * Sets The default poll interval for long-running operation. - * + * * @param defaultPollInterval the defaultPollInterval value. * @return the AppPlatformManagementClientBuilder. */ @@ -108,7 +108,7 @@ public AppPlatformManagementClientBuilder defaultPollInterval(Duration defaultPo /** * Sets The serializer to serialize an object into a string. - * + * * @param serializerAdapter the serializerAdapter value. * @return the AppPlatformManagementClientBuilder. */ @@ -119,7 +119,7 @@ public AppPlatformManagementClientBuilder serializerAdapter(SerializerAdapter se /** * Builds an instance of AppPlatformManagementClientImpl with the provided parameters. - * + * * @return an instance of AppPlatformManagementClientImpl. */ public AppPlatformManagementClientImpl buildClient() { diff --git a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/samples/java/com/azure/resourcemanager/appplatform/ReadmeSamples.java b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/samples/java/com/azure/resourcemanager/appplatform/ReadmeSamples.java index 3c421422fe54..2f7ca8805712 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appplatform/src/samples/java/com/azure/resourcemanager/appplatform/ReadmeSamples.java +++ b/sdk/resourcemanager/azure-resourcemanager-appplatform/src/samples/java/com/azure/resourcemanager/appplatform/ReadmeSamples.java @@ -4,8 +4,8 @@ package com.azure.resourcemanager.appplatform; import com.azure.core.credential.TokenCredential; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; /** @@ -15,7 +15,7 @@ public class ReadmeSamples { public void authenticate() { // BEGIN: readme-sample-authenticate - AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/CHANGELOG.md b/sdk/resourcemanager/azure-resourcemanager-appservice/CHANGELOG.md index 02f924719973..ada45d203b34 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/CHANGELOG.md +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 2.47.0-beta.1 (Unreleased) +## 2.49.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,24 @@ ### Other Changes +## 2.48.0 (2025-02-28) + +### Features Added + +- Supported Java SE 21 in `RuntimeStack` for `WebApp`. +- Supported Tomcat 10.1, JBoss EAP 8 and Java 21 in `RuntimeStack` for `WebApp`. +- Supported .Net 6, 8, 9 in `RuntimeStack` for `WebApp`. +- Supported PHP 8.2, 8.3 in `RuntimeStack` for `WebApp`. +- Supported Python 3.9, 3.10, 3.11, 3.12 in `RuntimeStack` for `WebApp`. + +## 2.47.0 (2025-01-24) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + ## 2.46.0 (2024-12-23) ### Other Changes diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/README.md b/sdk/resourcemanager/azure-resourcemanager-appservice/README.md index 67ca6ac338ef..836764309887 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/README.md +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/README.md @@ -18,7 +18,7 @@ For documentation on how to use this package, please see [Azure Management Libra com.azure.resourcemanager azure-resourcemanager-appservice - 2.46.0 + 2.49.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -39,7 +39,7 @@ Azure tenant ID can be configured via `AZURE_TENANT_ID` environment variable. Assuming the use of the `DefaultAzureCredential` credential class, the client can be authenticated using the following code: ```java readme-sample-authenticate -AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); +AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/pom.xml b/sdk/resourcemanager/azure-resourcemanager-appservice/pom.xml index ea9c455fd407..55ba327eef10 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/pom.xml @@ -14,7 +14,7 @@ com.azure.resourcemanager azure-resourcemanager-appservice - 2.47.0-beta.1 + 2.49.0-beta.1 jar Microsoft Azure SDK for App Service Management @@ -64,27 +64,27 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-storage - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-msi - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-keyvault - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-dns - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/RuntimeStack.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/RuntimeStack.java index 4e05dd5db861..ebda43bdc326 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/RuntimeStack.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/RuntimeStack.java @@ -17,6 +17,12 @@ public class RuntimeStack { /** .NET Core v3.1. */ public static final RuntimeStack NETCORE_V3_1 = COLLECTION.addValue(new RuntimeStack("DOTNETCORE", "3.1")); + /** .NET Core v8.0. */ + public static final RuntimeStack NETCORE_V8_0 = COLLECTION.addValue(new RuntimeStack("DOTNETCORE", "8.0")); + + /** .NET Core v9.0. */ + public static final RuntimeStack NETCORE_V9_0 = COLLECTION.addValue(new RuntimeStack("DOTNETCORE", "9.0")); + /** JAVA JRE 8. */ public static final RuntimeStack JAVA_8_JRE8 = COLLECTION.addValue(new RuntimeStack("JAVA", "8-jre8")); @@ -26,6 +32,9 @@ public class RuntimeStack { /** JAVA JAVA 17. */ public static final RuntimeStack JAVA_17_JAVA17 = COLLECTION.addValue(new RuntimeStack("JAVA", "17-java17")); + /** JAVA JAVA 21. */ + public static final RuntimeStack JAVA_21_JAVA21 = COLLECTION.addValue(new RuntimeStack("JAVA", "21-java21")); + /** Node.JS 10.1. */ public static final RuntimeStack NODEJS_10_1 = COLLECTION.addValue(new RuntimeStack("NODE", "10.1")); @@ -44,6 +53,15 @@ public class RuntimeStack { /** Node.JS 14 LTS. */ public static final RuntimeStack NODEJS_14_LTS = COLLECTION.addValue(new RuntimeStack("NODE", "14-lts")); + /** Node.JS 18 LTS. */ + public static final RuntimeStack NODEJS_18_LTS = COLLECTION.addValue(new RuntimeStack("NODE", "18-lts")); + + /** Node.JS 20 LTS. */ + public static final RuntimeStack NODEJS_20_LTS = COLLECTION.addValue(new RuntimeStack("NODE", "20-lts")); + + /** Node.JS 22 LTS. */ + public static final RuntimeStack NODEJS_22_LTS = COLLECTION.addValue(new RuntimeStack("NODE", "22-lts")); + /** PHP 7.2. */ public static final RuntimeStack PHP_7_2 = COLLECTION.addValue(new RuntimeStack("PHP", "7.2")); @@ -53,6 +71,12 @@ public class RuntimeStack { /** PHP 7.4. */ public static final RuntimeStack PHP_7_4 = COLLECTION.addValue(new RuntimeStack("PHP", "7.4")); + /** PHP 8.2. */ + public static final RuntimeStack PHP_8_2 = COLLECTION.addValue(new RuntimeStack("PHP", "8.2")); + + /** PHP 8.3. */ + public static final RuntimeStack PHP_8_3 = COLLECTION.addValue(new RuntimeStack("PHP", "8.3")); + /** PYTHON 3.6. */ public static final RuntimeStack PYTHON_3_6 = COLLECTION.addValue(new RuntimeStack("PYTHON", "3.6")); @@ -62,6 +86,18 @@ public class RuntimeStack { /** PYTHON 3.8. */ public static final RuntimeStack PYTHON_3_8 = COLLECTION.addValue(new RuntimeStack("PYTHON", "3.8")); + /** PYTHON 3.9. */ + public static final RuntimeStack PYTHON_3_9 = COLLECTION.addValue(new RuntimeStack("PYTHON", "3.9")); + + /** PYTHON 3.10. */ + public static final RuntimeStack PYTHON_3_10 = COLLECTION.addValue(new RuntimeStack("PYTHON", "3.10")); + + /** PYTHON 3.11. */ + public static final RuntimeStack PYTHON_3_11 = COLLECTION.addValue(new RuntimeStack("PYTHON", "3.11")); + + /** PYTHON 3.12. */ + public static final RuntimeStack PYTHON_3_12 = COLLECTION.addValue(new RuntimeStack("PYTHON", "3.12")); + /** RUBY 2.5. */ public static final RuntimeStack RUBY_2_5 = COLLECTION.addValue(new RuntimeStack("RUBY", "2.5")); @@ -74,12 +110,30 @@ public class RuntimeStack { /** Tomcat 8.5-jre8 image with catalina root set to Azure wwwroot. */ public static final RuntimeStack TOMCAT_8_5_JRE8 = COLLECTION.addValue(new RuntimeStack("TOMCAT", "8.5-jre8")); + /** Tomcat 9.0-java21 image with catalina root set to Azure wwwroot. */ + public static final RuntimeStack TOMCAT_9_0_JAVA21 = COLLECTION.addValue(new RuntimeStack("TOMCAT", "9.0-java21")); + + /** Tomcat 9.0-java17 image with catalina root set to Azure wwwroot. */ + public static final RuntimeStack TOMCAT_9_0_JAVA17 = COLLECTION.addValue(new RuntimeStack("TOMCAT", "9.0-java17")); + /** Tomcat 9.0-java11 image with catalina root set to Azure wwwroot. */ public static final RuntimeStack TOMCAT_9_0_JAVA11 = COLLECTION.addValue(new RuntimeStack("TOMCAT", "9.0-java11")); /** Tomcat 9.0-jre8 image with catalina root set to Azure wwwroot. */ public static final RuntimeStack TOMCAT_9_0_JRE8 = COLLECTION.addValue(new RuntimeStack("TOMCAT", "9.0-jre8")); + /** Tomcat 10.1-java21 image with catalina root set to Azure wwwroot. */ + public static final RuntimeStack TOMCAT_10_1_JAVA21 + = COLLECTION.addValue(new RuntimeStack("TOMCAT", "10.1-java21")); + + /** Tomcat 10.1-java17 image with catalina root set to Azure wwwroot. */ + public static final RuntimeStack TOMCAT_10_1_JAVA17 + = COLLECTION.addValue(new RuntimeStack("TOMCAT", "10.1-java17")); + + /** Tomcat 10.1-java11 image with catalina root set to Azure wwwroot. */ + public static final RuntimeStack TOMCAT_10_1_JAVA11 + = COLLECTION.addValue(new RuntimeStack("TOMCAT", "10.1-java11")); + /** Tomcat 10.0-java17 image with catalina root set to Azure wwwroot. */ public static final RuntimeStack TOMCAT_10_0_JAVA17 = COLLECTION.addValue(new RuntimeStack("TOMCAT", "10.0-java17")); @@ -100,6 +154,12 @@ public class RuntimeStack { /** Tomcat 10.0-jre8 image with catalina root set to Azure wwwroot. */ public static final RuntimeStack TOMCAT_10_0_JRE8 = COLLECTION.addValue(new RuntimeStack("TOMCAT", "10.0-jre8")); + /** JBOSS EAP 8-java17. */ + public static final RuntimeStack JBOSS_EAP_8_JAVA17 = COLLECTION.addValue(new RuntimeStack("JBOSSEAP", "8-java17")); + + /** JBOSS EAP 8-java11. */ + public static final RuntimeStack JBOSS_EAP_8_JAVA11 = COLLECTION.addValue(new RuntimeStack("JBOSSEAP", "8-java11")); + /** JBOSS EAP 7.2-java8. */ public static final RuntimeStack JBOSS_EAP_7_2_JAVA8 = COLLECTION.addValue(new RuntimeStack("JBOSSEAP", "7.2-java8")); @@ -110,6 +170,9 @@ public class RuntimeStack { /** JBOSS EAP 7-java11. */ public static final RuntimeStack JBOSS_EAP_7_JAVA11 = COLLECTION.addValue(new RuntimeStack("JBOSSEAP", "7-java11")); + /** JBOSS EAP 7-java17. */ + public static final RuntimeStack JBOSS_EAP_7_JAVA17 = COLLECTION.addValue(new RuntimeStack("JBOSSEAP", "7-java17")); + /** The name of the language runtime stack. */ private final String stack; /** The version of the runtime. */ diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/samples/java/com/azure/resourcemanager/appservice/ReadmeSamples.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/samples/java/com/azure/resourcemanager/appservice/ReadmeSamples.java index 9b2f5d939844..773d1b54b216 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/samples/java/com/azure/resourcemanager/appservice/ReadmeSamples.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/samples/java/com/azure/resourcemanager/appservice/ReadmeSamples.java @@ -4,8 +4,8 @@ package com.azure.resourcemanager.appservice; import com.azure.core.credential.TokenCredential; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; /** @@ -15,7 +15,7 @@ public class ReadmeSamples { public void authenticate() { // BEGIN: readme-sample-authenticate - AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/RuntimeStackTests.java b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/RuntimeStackTests.java index 9ff85a688f9f..77c6009719b7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/RuntimeStackTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-appservice/src/test/java/com/azure/resourcemanager/appservice/RuntimeStackTests.java @@ -3,11 +3,19 @@ package com.azure.resourcemanager.appservice; +import com.azure.core.util.BinaryData; import com.azure.resourcemanager.appservice.models.RuntimeStack; +import com.azure.resourcemanager.test.utils.CliRunner; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import java.io.IOException; +import java.util.Arrays; import java.util.Collection; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; public class RuntimeStackTests { @@ -17,4 +25,46 @@ public void verifyDeprecatedNotInGetAll() { Assertions.assertTrue(stacks.contains(RuntimeStack.TOMCAT_10_0_JAVA11)); Assertions.assertFalse(stacks.contains(RuntimeStack.TOMCAT_10_0_JRE11)); } + + /** + * This test is for syncing RuntimeStack with latest supported stacks from backend. + * To run this test, upgrade Azure CLI to latest version by running "az upgrade", and remove "@Disabled". + */ + @Test + @Disabled + public void listNewRuntimeStacks() throws IOException, InterruptedException { + Set latestStacks = getLatestStacks(); + Set allCurrentStacks = Arrays.stream(RuntimeStack.class.getDeclaredFields()) + .filter(field -> field.getType() == RuntimeStack.class) + .map(field -> { + try { + return field.get(null).toString(); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + }) + .collect(Collectors.toSet()); + Set supportedStacks + = RuntimeStack.getAll().stream().map(RuntimeStack::toString).collect(Collectors.toSet()); + List newStacks = latestStacks.stream() + .filter(stack -> !allCurrentStacks.contains(stack)) + .distinct() + .sorted() + .collect(Collectors.toList()); + List newDeprecated = supportedStacks.stream() + .filter(stack -> !latestStacks.contains(stack)) + .distinct() + .sorted() + .collect(Collectors.toList()); + System.out.println("New stacks: " + newStacks); + System.out.println("New deprecated stacks: " + newDeprecated); + } + + @SuppressWarnings("unchecked") + private Set getLatestStacks() throws IOException, InterruptedException { + String cliOutput = CliRunner.run("az webapp list-runtimes --os linux"); + List outputList + = BinaryData.fromString(cliOutput.substring(cliOutput.indexOf("["))).toObject(List.class); + return outputList.stream().map(stack -> String.join(" ", stack.split(":"))).collect(Collectors.toSet()); + } } diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/CHANGELOG.md b/sdk/resourcemanager/azure-resourcemanager-authorization/CHANGELOG.md index 4873162f3172..5d277c925910 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/CHANGELOG.md +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 2.47.0-beta.1 (Unreleased) +## 2.49.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,22 @@ ### Other Changes +## 2.48.0 (2025-02-28) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + +## 2.47.0 (2025-01-24) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + ## 2.46.0 (2024-12-23) ### Other Changes diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/README.md b/sdk/resourcemanager/azure-resourcemanager-authorization/README.md index 879d237c5c71..25971183c7a6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/README.md +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/README.md @@ -18,7 +18,7 @@ For documentation on how to use this package, please see [Azure Management Libra com.azure.resourcemanager azure-resourcemanager-authorization - 2.46.0 + 2.49.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -39,7 +39,7 @@ Azure tenant ID can be configured via `AZURE_TENANT_ID` environment variable. Assuming the use of the `DefaultAzureCredential` credential class, the client can be authenticated using the following code: ```java readme-sample-authenticate -AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); +AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/pom.xml b/sdk/resourcemanager/azure-resourcemanager-authorization/pom.xml index c51f1002191a..6e5179412db9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/pom.xml @@ -14,7 +14,7 @@ com.azure.resourcemanager azure-resourcemanager-authorization - 2.47.0-beta.1 + 2.49.0-beta.1 jar Microsoft Azure SDK for Authorization Management @@ -60,7 +60,7 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.47.0-beta.1 + 2.49.0-beta.1 org.slf4j @@ -83,7 +83,7 @@ com.azure azure-core-http-netty - 1.15.7 + 1.15.11 test diff --git a/sdk/resourcemanager/azure-resourcemanager-authorization/src/samples/java/com/azure/resourcemanager/authorization/ReadmeSamples.java b/sdk/resourcemanager/azure-resourcemanager-authorization/src/samples/java/com/azure/resourcemanager/authorization/ReadmeSamples.java index 91a46242083f..67691a9436ad 100644 --- a/sdk/resourcemanager/azure-resourcemanager-authorization/src/samples/java/com/azure/resourcemanager/authorization/ReadmeSamples.java +++ b/sdk/resourcemanager/azure-resourcemanager-authorization/src/samples/java/com/azure/resourcemanager/authorization/ReadmeSamples.java @@ -4,8 +4,8 @@ package com.azure.resourcemanager.authorization; import com.azure.core.credential.TokenCredential; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; /** @@ -15,7 +15,7 @@ public class ReadmeSamples { public void authenticate() { // BEGIN: readme-sample-authenticate - AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-cdn/CHANGELOG.md b/sdk/resourcemanager/azure-resourcemanager-cdn/CHANGELOG.md index a60b1b53f8ce..be5a9812bfd5 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cdn/CHANGELOG.md +++ b/sdk/resourcemanager/azure-resourcemanager-cdn/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 2.47.0-beta.1 (Unreleased) +## 2.49.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,22 @@ ### Other Changes +## 2.48.0 (2025-02-28) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + +## 2.47.0 (2025-01-24) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + ## 2.46.0 (2024-12-23) ### Other Changes diff --git a/sdk/resourcemanager/azure-resourcemanager-cdn/README.md b/sdk/resourcemanager/azure-resourcemanager-cdn/README.md index 11fc009a00ae..532dcaa37867 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cdn/README.md +++ b/sdk/resourcemanager/azure-resourcemanager-cdn/README.md @@ -18,7 +18,7 @@ For documentation on how to use this package, please see [Azure Management Libra com.azure.resourcemanager azure-resourcemanager-cdn - 2.46.0 + 2.49.0-beta.1 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/resourcemanager/azure-resourcemanager-cdn/pom.xml b/sdk/resourcemanager/azure-resourcemanager-cdn/pom.xml index b3fda0193213..8c90468b1623 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cdn/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-cdn/pom.xml @@ -14,7 +14,7 @@ com.azure.resourcemanager azure-resourcemanager-cdn - 2.47.0-beta.1 + 2.49.0-beta.1 jar Microsoft Azure SDK for CDN Management @@ -58,7 +58,7 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.47.0-beta.1 + 2.49.0-beta.1 org.junit.jupiter @@ -81,7 +81,7 @@ com.azure azure-core-http-netty - 1.15.7 + 1.15.11 test diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/CHANGELOG.md b/sdk/resourcemanager/azure-resourcemanager-compute/CHANGELOG.md index 721345db911f..235d076d2e6f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/CHANGELOG.md +++ b/sdk/resourcemanager/azure-resourcemanager-compute/CHANGELOG.md @@ -1,6 +1,24 @@ # Release History -## 2.47.0-beta.1 (Unreleased) +## 2.49.0-beta.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + +## 2.48.0 (2025-02-28) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + +## 2.47.0 (2025-01-24) ### Other Changes diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/README.md b/sdk/resourcemanager/azure-resourcemanager-compute/README.md index 87a02a6f2f4f..6cf5a3e9f8cd 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/README.md +++ b/sdk/resourcemanager/azure-resourcemanager-compute/README.md @@ -18,7 +18,7 @@ For documentation on how to use this package, please see [Azure Management Libra com.azure.resourcemanager azure-resourcemanager-compute - 2.46.0 + 2.49.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -39,7 +39,7 @@ Azure tenant ID can be configured via `AZURE_TENANT_ID` environment variable. Assuming the use of the `DefaultAzureCredential` credential class, the client can be authenticated using the following code: ```java readme-sample-authenticate -AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); +AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/pom.xml b/sdk/resourcemanager/azure-resourcemanager-compute/pom.xml index 83d4b1ef78f5..5a5d7349564f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-compute/pom.xml @@ -14,7 +14,7 @@ com.azure.resourcemanager azure-resourcemanager-compute - 2.47.0-beta.1 + 2.49.0-beta.1 jar Microsoft Azure SDK for Compute Management @@ -69,27 +69,27 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-storage - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-network - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-msi - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-authorization - 2.47.0-beta.1 + 2.49.0-beta.1 org.slf4j @@ -112,19 +112,19 @@ com.azure azure-core-http-netty - 1.15.7 + 1.15.11 test com.azure.resourcemanager azure-resourcemanager-keyvault - 2.47.0-beta.1 + 2.49.0-beta.1 test com.azure azure-storage-blob - 12.29.0 + 12.29.1 test diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/samples/java/com/azure/resourcemanager/compute/ReadmeSamples.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/samples/java/com/azure/resourcemanager/compute/ReadmeSamples.java index c7693c8b7103..bba377e10d86 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/samples/java/com/azure/resourcemanager/compute/ReadmeSamples.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/samples/java/com/azure/resourcemanager/compute/ReadmeSamples.java @@ -4,8 +4,8 @@ package com.azure.resourcemanager.compute; import com.azure.core.credential.TokenCredential; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; /** @@ -15,7 +15,7 @@ public class ReadmeSamples { public void authenticate() { // BEGIN: readme-sample-authenticate - AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/implementation/VirtualMachineMockTests.java b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/implementation/VirtualMachineMockTests.java index 2a30ac5a9e49..eb7a860f6f7c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/implementation/VirtualMachineMockTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-compute/src/test/java/com/azure/resourcemanager/compute/implementation/VirtualMachineMockTests.java @@ -8,9 +8,9 @@ import com.azure.core.http.HttpRequest; import com.azure.core.http.HttpResponse; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; import com.azure.core.management.serializer.SerializerFactory; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.core.util.serializer.SerializerAdapter; import com.azure.core.util.serializer.SerializerEncoding; @@ -64,8 +64,8 @@ public void listByVmssByIdWithNextLinkEncoded() { private ComputeManager mockComputeManager() { HttpClient httpClient = mockHttpClient(); - AzureProfile mockProfile - = new AzureProfile(UUID.randomUUID().toString(), UUID.randomUUID().toString(), AzureEnvironment.AZURE); + AzureProfile mockProfile = new AzureProfile(UUID.randomUUID().toString(), UUID.randomUUID().toString(), + AzureCloud.AZURE_PUBLIC_CLOUD); ComputeManager computeManager = ComputeManager.authenticate(new HttpPipelineBuilder().httpClient(httpClient).build(), mockProfile); stateHolder.nextLinkUrl = String.format("%s%s?filter=%s", HOST, NEXT_LINK_PATH, QUERY); diff --git a/sdk/resourcemanager/azure-resourcemanager-containerinstance/CHANGELOG.md b/sdk/resourcemanager/azure-resourcemanager-containerinstance/CHANGELOG.md index facda021e6c6..c1464194cfc4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerinstance/CHANGELOG.md +++ b/sdk/resourcemanager/azure-resourcemanager-containerinstance/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 2.47.0-beta.1 (Unreleased) +## 2.49.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,22 @@ ### Other Changes +## 2.48.0 (2025-02-28) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + +## 2.47.0 (2025-01-24) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + ## 2.46.0 (2024-12-23) ### Other Changes diff --git a/sdk/resourcemanager/azure-resourcemanager-containerinstance/README.md b/sdk/resourcemanager/azure-resourcemanager-containerinstance/README.md index cbeaa6ee311e..9dde68890980 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerinstance/README.md +++ b/sdk/resourcemanager/azure-resourcemanager-containerinstance/README.md @@ -18,7 +18,7 @@ For documentation on how to use this package, please see [Azure Management Libra com.azure.resourcemanager azure-resourcemanager-containerinstance - 2.46.0 + 2.49.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -39,7 +39,7 @@ Azure tenant ID can be configured via `AZURE_TENANT_ID` environment variable. Assuming the use of the `DefaultAzureCredential` credential class, the client can be authenticated using the following code: ```java readme-sample-authenticate -AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); +AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-containerinstance/pom.xml b/sdk/resourcemanager/azure-resourcemanager-containerinstance/pom.xml index c1e20c0a3216..da3a8fa5bb86 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerinstance/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-containerinstance/pom.xml @@ -10,7 +10,7 @@ com.azure.resourcemanager azure-resourcemanager-containerinstance - 2.47.0-beta.1 + 2.49.0-beta.1 jar Microsoft Azure SDK for Container Instance Management @@ -60,32 +60,32 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-storage - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-authorization - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-msi - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-network - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure azure-storage-file-share - 12.25.1 + 12.25.2 com.azure @@ -114,7 +114,7 @@ com.azure azure-core-http-netty - 1.15.7 + 1.15.11 test diff --git a/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/samples/java/com/azure/resourcemanager/containerinstance/ReadmeSamples.java b/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/samples/java/com/azure/resourcemanager/containerinstance/ReadmeSamples.java index 6e8f26f82f36..5de16f7fa808 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/samples/java/com/azure/resourcemanager/containerinstance/ReadmeSamples.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerinstance/src/samples/java/com/azure/resourcemanager/containerinstance/ReadmeSamples.java @@ -4,8 +4,8 @@ package com.azure.resourcemanager.containerinstance; import com.azure.core.credential.TokenCredential; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; /** @@ -15,7 +15,7 @@ public class ReadmeSamples { public void authenticate() { // BEGIN: readme-sample-authenticate - AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/CHANGELOG.md b/sdk/resourcemanager/azure-resourcemanager-containerregistry/CHANGELOG.md index 955dc794cf53..94508572646c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/CHANGELOG.md +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 2.47.0-beta.1 (Unreleased) +## 2.49.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,22 @@ ### Other Changes +## 2.48.0 (2025-02-28) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + +## 2.47.0 (2025-01-24) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + ## 2.46.0 (2024-12-23) ### Other Changes diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/README.md b/sdk/resourcemanager/azure-resourcemanager-containerregistry/README.md index 689d106af53d..8d16d06e4e50 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/README.md +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/README.md @@ -18,7 +18,7 @@ For documentation on how to use this package, please see [Azure Management Libra com.azure.resourcemanager azure-resourcemanager-containerregistry - 2.46.0 + 2.49.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -39,7 +39,7 @@ Azure tenant ID can be configured via `AZURE_TENANT_ID` environment variable. Assuming the use of the `DefaultAzureCredential` credential class, the client can be authenticated using the following code: ```java readme-sample-authenticate -AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); +AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/pom.xml b/sdk/resourcemanager/azure-resourcemanager-containerregistry/pom.xml index 920be9c7bb16..2e30f85b81ee 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/pom.xml @@ -10,7 +10,7 @@ com.azure.resourcemanager azure-resourcemanager-containerregistry - 2.47.0-beta.1 + 2.49.0-beta.1 jar Microsoft Azure SDK for Container Registry Management @@ -54,7 +54,7 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.47.0-beta.1 + 2.49.0-beta.1 org.slf4j @@ -77,7 +77,7 @@ com.azure azure-core-http-netty - 1.15.7 + 1.15.11 test diff --git a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/samples/java/com/azure/resourcemanager/containerregistry/ReadmeSamples.java b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/samples/java/com/azure/resourcemanager/containerregistry/ReadmeSamples.java index 775e3b14833b..73226fb0a8cc 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/samples/java/com/azure/resourcemanager/containerregistry/ReadmeSamples.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerregistry/src/samples/java/com/azure/resourcemanager/containerregistry/ReadmeSamples.java @@ -4,8 +4,8 @@ package com.azure.resourcemanager.containerregistry; import com.azure.core.credential.TokenCredential; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; /** @@ -15,7 +15,7 @@ public class ReadmeSamples { public void authenticate() { // BEGIN: readme-sample-authenticate - AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/CHANGELOG.md b/sdk/resourcemanager/azure-resourcemanager-containerservice/CHANGELOG.md index b55e7fc9ee90..e676cfafce5e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/CHANGELOG.md +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 2.47.0-beta.1 (Unreleased) +## 2.49.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,22 @@ ### Other Changes +## 2.48.0 (2025-02-28) + +### Other Changes + +#### Dependency Updates + +- Updated `api-version` to `2024-10-01`. + +## 2.47.0 (2025-01-24) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + ## 2.46.0 (2024-12-23) ### Other Changes diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/README.md b/sdk/resourcemanager/azure-resourcemanager-containerservice/README.md index 45eae1c62cd2..0f610b269d0b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/README.md +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/README.md @@ -18,7 +18,7 @@ For documentation on how to use this package, please see [Azure Management Libra com.azure.resourcemanager azure-resourcemanager-containerservice - 2.46.0 + 2.49.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -39,7 +39,7 @@ Azure tenant ID can be configured via `AZURE_TENANT_ID` environment variable. Assuming the use of the `DefaultAzureCredential` credential class, the client can be authenticated using the following code: ```java readme-sample-authenticate -AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); +AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/assets.json b/sdk/resourcemanager/azure-resourcemanager-containerservice/assets.json index 7a8072130349..87a29fdc9cd8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/assets.json +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "java", "TagPrefix": "java/resourcemanager/azure-resourcemanager-containerservice", - "Tag": "java/resourcemanager/azure-resourcemanager-containerservice_ac00fa0812" + "Tag": "java/resourcemanager/azure-resourcemanager-containerservice_484aa19857" } diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/pom.xml b/sdk/resourcemanager/azure-resourcemanager-containerservice/pom.xml index 80c220cabe61..e72442d2060f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/pom.xml @@ -10,7 +10,7 @@ com.azure.resourcemanager azure-resourcemanager-containerservice - 2.47.0-beta.1 + 2.49.0-beta.1 jar Microsoft Azure SDK for Container Service Management @@ -55,7 +55,7 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.47.0-beta.1 + 2.49.0-beta.1 org.junit.jupiter @@ -78,7 +78,7 @@ com.azure azure-core-http-netty - 1.15.7 + 1.15.11 test diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/fluent/models/AgentPoolInner.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/fluent/models/AgentPoolInner.java index c9507d7356df..5904b5415e70 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/fluent/models/AgentPoolInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/fluent/models/AgentPoolInner.java @@ -260,6 +260,33 @@ public AgentPoolInner withWorkloadRuntime(WorkloadRuntime workloadRuntime) { return this; } + /** + * Get the messageOfTheDay property: A base64-encoded string which will be written to /etc/motd after decoding. This + * allows customization of the message of the day for Linux nodes. It must not be specified for Windows nodes. It + * must be a static string (i.e., will be printed raw and not be executed as a script). + * + * @return the messageOfTheDay value. + */ + public String messageOfTheDay() { + return this.innerProperties() == null ? null : this.innerProperties().messageOfTheDay(); + } + + /** + * Set the messageOfTheDay property: A base64-encoded string which will be written to /etc/motd after decoding. This + * allows customization of the message of the day for Linux nodes. It must not be specified for Windows nodes. It + * must be a static string (i.e., will be printed raw and not be executed as a script). + * + * @param messageOfTheDay the messageOfTheDay value to set. + * @return the AgentPoolInner object itself. + */ + public AgentPoolInner withMessageOfTheDay(String messageOfTheDay) { + if (this.innerProperties() == null) { + this.innerProperties = new ManagedClusterAgentPoolProfileProperties(); + } + this.innerProperties().withMessageOfTheDay(messageOfTheDay); + return this; + } + /** * Get the vnetSubnetId property: If this is not specified, a VNET and subnet will be generated and used. If no * podSubnetID is specified, this applies to nodes and pods, otherwise it applies to just nodes. This is of the diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/fluent/models/ManagedClusterAgentPoolProfileProperties.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/fluent/models/ManagedClusterAgentPoolProfileProperties.java index fc45544e8e1a..f267aac67331 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/fluent/models/ManagedClusterAgentPoolProfileProperties.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/fluent/models/ManagedClusterAgentPoolProfileProperties.java @@ -81,6 +81,13 @@ public class ManagedClusterAgentPoolProfileProperties */ private WorkloadRuntime workloadRuntime; + /* + * A base64-encoded string which will be written to /etc/motd after decoding. This allows customization of the + * message of the day for Linux nodes. It must not be specified for Windows nodes. It must be a static string (i.e., + * will be printed raw and not be executed as a script). + */ + private String messageOfTheDay; + /* * If this is not specified, a VNET and subnet will be generated and used. If no podSubnetID is specified, this * applies to nodes and pods, otherwise it applies to just nodes. This is of the form: @@ -476,6 +483,30 @@ public ManagedClusterAgentPoolProfileProperties withWorkloadRuntime(WorkloadRunt return this; } + /** + * Get the messageOfTheDay property: A base64-encoded string which will be written to /etc/motd after decoding. This + * allows customization of the message of the day for Linux nodes. It must not be specified for Windows nodes. It + * must be a static string (i.e., will be printed raw and not be executed as a script). + * + * @return the messageOfTheDay value. + */ + public String messageOfTheDay() { + return this.messageOfTheDay; + } + + /** + * Set the messageOfTheDay property: A base64-encoded string which will be written to /etc/motd after decoding. This + * allows customization of the message of the day for Linux nodes. It must not be specified for Windows nodes. It + * must be a static string (i.e., will be printed raw and not be executed as a script). + * + * @param messageOfTheDay the messageOfTheDay value to set. + * @return the ManagedClusterAgentPoolProfileProperties object itself. + */ + public ManagedClusterAgentPoolProfileProperties withMessageOfTheDay(String messageOfTheDay) { + this.messageOfTheDay = messageOfTheDay; + return this; + } + /** * Get the vnetSubnetId property: If this is not specified, a VNET and subnet will be generated and used. If no * podSubnetID is specified, this applies to nodes and pods, otherwise it applies to just nodes. This is of the @@ -1387,6 +1418,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { this.kubeletDiskType == null ? null : this.kubeletDiskType.toString()); jsonWriter.writeStringField("workloadRuntime", this.workloadRuntime == null ? null : this.workloadRuntime.toString()); + jsonWriter.writeStringField("messageOfTheDay", this.messageOfTheDay); jsonWriter.writeStringField("vnetSubnetID", this.vnetSubnetId); jsonWriter.writeStringField("podSubnetID", this.podSubnetId); jsonWriter.writeNumberField("maxPods", this.maxPods); @@ -1464,6 +1496,8 @@ public static ManagedClusterAgentPoolProfileProperties fromJson(JsonReader jsonR } else if ("workloadRuntime".equals(fieldName)) { deserializedManagedClusterAgentPoolProfileProperties.workloadRuntime = WorkloadRuntime.fromString(reader.getString()); + } else if ("messageOfTheDay".equals(fieldName)) { + deserializedManagedClusterAgentPoolProfileProperties.messageOfTheDay = reader.getString(); } else if ("vnetSubnetID".equals(fieldName)) { deserializedManagedClusterAgentPoolProfileProperties.vnetSubnetId = reader.getString(); } else if ("podSubnetID".equals(fieldName)) { diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/AgentPoolsClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/AgentPoolsClientImpl.java index 7c0c5af65af9..7749319582bd 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/AgentPoolsClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/AgentPoolsClientImpl.java @@ -206,7 +206,7 @@ public Mono>> abortLatestOperationWithResponseAsync(St if (agentPoolName == null) { return Mono.error(new IllegalArgumentException("Parameter agentPoolName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.abortLatestOperation(this.client.getEndpoint(), apiVersion, @@ -251,7 +251,7 @@ private Mono>> abortLatestOperationWithResponseAsync(S if (agentPoolName == null) { return Mono.error(new IllegalArgumentException("Parameter agentPoolName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.abortLatestOperation(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -464,7 +464,7 @@ private Mono> listSinglePageAsync(String resourceG if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.list(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -504,7 +504,7 @@ private Mono> listSinglePageAsync(String resourceG if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service @@ -611,7 +611,7 @@ public Mono> getWithResponseAsync(String resourceGroupN if (agentPoolName == null) { return Mono.error(new IllegalArgumentException("Parameter agentPoolName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.get(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -653,7 +653,7 @@ private Mono> getWithResponseAsync(String resourceGroup if (agentPoolName == null) { return Mono.error(new IllegalArgumentException("Parameter agentPoolName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.get(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), resourceGroupName, @@ -751,7 +751,7 @@ public Mono>> createOrUpdateWithResponseAsync(String r } else { parameters.validate(); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.createOrUpdate(this.client.getEndpoint(), apiVersion, @@ -802,7 +802,7 @@ private Mono>> createOrUpdateWithResponseAsync(String } else { parameters.validate(); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.createOrUpdate(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -1070,7 +1070,7 @@ public Mono>> deleteWithResponseAsync(String resourceG if (agentPoolName == null) { return Mono.error(new IllegalArgumentException("Parameter agentPoolName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.delete(this.client.getEndpoint(), apiVersion, @@ -1115,7 +1115,7 @@ private Mono>> deleteWithResponseAsync(String resource if (agentPoolName == null) { return Mono.error(new IllegalArgumentException("Parameter agentPoolName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.delete(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), resourceGroupName, @@ -1371,7 +1371,7 @@ public Mono> getUpgradeProfileWithRespons if (agentPoolName == null) { return Mono.error(new IllegalArgumentException("Parameter agentPoolName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.getUpgradeProfile(this.client.getEndpoint(), apiVersion, @@ -1413,7 +1413,7 @@ private Mono> getUpgradeProfileWithRespon if (agentPoolName == null) { return Mono.error(new IllegalArgumentException("Parameter agentPoolName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.getUpgradeProfile(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -1511,7 +1511,7 @@ public Mono>> deleteMachinesWithResponseAsync(String r } else { machines.validate(); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil.withContext(context -> service.deleteMachines(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), resourceGroupName, resourceName, agentPoolName, machines, accept, context)) @@ -1557,7 +1557,7 @@ private Mono>> deleteMachinesWithResponseAsync(String } else { machines.validate(); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.deleteMachines(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -1752,7 +1752,7 @@ public void deleteMachines(String resourceGroupName, String resourceName, String if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.getAvailableAgentPoolVersions(this.client.getEndpoint(), apiVersion, @@ -1793,7 +1793,7 @@ public void deleteMachines(String resourceGroupName, String resourceName, String if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.getAvailableAgentPoolVersions(this.client.getEndpoint(), apiVersion, @@ -1895,7 +1895,7 @@ public Mono>> upgradeNodeImageVersionWithResponseAsync if (agentPoolName == null) { return Mono.error(new IllegalArgumentException("Parameter agentPoolName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.upgradeNodeImageVersion(this.client.getEndpoint(), apiVersion, @@ -1940,7 +1940,7 @@ private Mono>> upgradeNodeImageVersionWithResponseAsyn if (agentPoolName == null) { return Mono.error(new IllegalArgumentException("Parameter agentPoolName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.upgradeNodeImageVersion(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClusterAgentPoolImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClusterAgentPoolImpl.java index ffa128cec6de..ded178d55b48 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClusterAgentPoolImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/KubernetesClusterAgentPoolImpl.java @@ -318,6 +318,7 @@ AgentPoolInner getAgentPoolInner() { agentPoolInner.withNetworkProfile(innerModel().networkProfile()); agentPoolInner.withWindowsProfile(innerModel().windowsProfile()); agentPoolInner.withSecurityProfile(innerModel().securityProfile()); + agentPoolInner.withMessageOfTheDay(innerModel().messageOfTheDay()); return agentPoolInner; } diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/MachinesClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/MachinesClientImpl.java index 101145a924dc..8ff91b63d59d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/MachinesClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/MachinesClientImpl.java @@ -121,7 +121,7 @@ private Mono> listSinglePageAsync(String resourceGro if (agentPoolName == null) { return Mono.error(new IllegalArgumentException("Parameter agentPoolName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.list(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -165,7 +165,7 @@ private Mono> listSinglePageAsync(String resourceGro if (agentPoolName == null) { return Mono.error(new IllegalArgumentException("Parameter agentPoolName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service @@ -282,7 +282,7 @@ public Mono> getWithResponseAsync(String resourceGroupNam if (machineName == null) { return Mono.error(new IllegalArgumentException("Parameter machineName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.get(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -328,7 +328,7 @@ private Mono> getWithResponseAsync(String resourceGroupNa if (machineName == null) { return Mono.error(new IllegalArgumentException("Parameter machineName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.get(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), resourceGroupName, diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/MaintenanceConfigurationsClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/MaintenanceConfigurationsClientImpl.java index 0fb94a5337e0..9f9403a822dd 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/MaintenanceConfigurationsClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/MaintenanceConfigurationsClientImpl.java @@ -141,7 +141,7 @@ Mono> listByManagedClusterNext( if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.listByManagedCluster(this.client.getEndpoint(), apiVersion, @@ -181,7 +181,7 @@ Mono> listByManagedClusterNext( if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service @@ -296,7 +296,7 @@ public Mono> getWithResponseAsync(String if (configName == null) { return Mono.error(new IllegalArgumentException("Parameter configName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.get(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -338,7 +338,7 @@ private Mono> getWithResponseAsync(Strin if (configName == null) { return Mono.error(new IllegalArgumentException("Parameter configName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.get(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), resourceGroupName, @@ -436,7 +436,7 @@ public Mono> createOrUpdateWithResponseA } else { parameters.validate(); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil.withContext(context -> service.createOrUpdate(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), resourceGroupName, resourceName, configName, parameters, accept, context)) @@ -483,7 +483,7 @@ private Mono> createOrUpdateWithResponse } else { parameters.validate(); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.createOrUpdate(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -582,7 +582,7 @@ public Mono> deleteWithResponseAsync(String resourceGroupName, St if (configName == null) { return Mono.error(new IllegalArgumentException("Parameter configName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.delete(this.client.getEndpoint(), apiVersion, @@ -623,7 +623,7 @@ private Mono> deleteWithResponseAsync(String resourceGroupName, S if (configName == null) { return Mono.error(new IllegalArgumentException("Parameter configName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.delete(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), resourceGroupName, diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/ManagedClustersClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/ManagedClustersClientImpl.java index 2ac99e9f5576..42b44ed7480e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/ManagedClustersClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/ManagedClustersClientImpl.java @@ -399,7 +399,7 @@ public Mono> listKubernetesVersionsWi if (location == null) { return Mono.error(new IllegalArgumentException("Parameter location is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.listKubernetesVersions(this.client.getEndpoint(), apiVersion, @@ -435,7 +435,7 @@ private Mono> listKubernetesVersionsW if (location == null) { return Mono.error(new IllegalArgumentException("Parameter location is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.listKubernetesVersions(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -513,7 +513,7 @@ private Mono> listSinglePageAsync() { return Mono.error(new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.list(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -543,7 +543,7 @@ private Mono> listSinglePageAsync(Context con return Mono.error(new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.list(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), accept, context) @@ -630,7 +630,7 @@ private Mono> listByResourceGroupSinglePageAs return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.listByResourceGroup(this.client.getEndpoint(), apiVersion, @@ -666,7 +666,7 @@ private Mono> listByResourceGroupSinglePageAs return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service @@ -765,7 +765,7 @@ public PagedIterable listByResourceGroup(String resourceGro if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.getUpgradeProfile(this.client.getEndpoint(), apiVersion, @@ -803,7 +803,7 @@ public PagedIterable listByResourceGroup(String resourceGro if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.getUpgradeProfile(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -897,7 +897,7 @@ public Mono> getAccessProfileWithResp if (roleName == null) { return Mono.error(new IllegalArgumentException("Parameter roleName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.getAccessProfile(this.client.getEndpoint(), apiVersion, @@ -944,7 +944,7 @@ private Mono> getAccessProfileWithRes if (roleName == null) { return Mono.error(new IllegalArgumentException("Parameter roleName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.getAccessProfile(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -1051,7 +1051,7 @@ public Mono> listClusterAdminCredentialsWithRes if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.listClusterAdminCredentials(this.client.getEndpoint(), apiVersion, @@ -1089,7 +1089,7 @@ private Mono> listClusterAdminCredentialsWithRe if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.listClusterAdminCredentials(this.client.getEndpoint(), apiVersion, @@ -1182,7 +1182,7 @@ public Mono> listClusterUserCredentialsWithResp if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.listClusterUserCredentials(this.client.getEndpoint(), apiVersion, @@ -1223,7 +1223,7 @@ private Mono> listClusterUserCredentialsWithRes if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.listClusterUserCredentials(this.client.getEndpoint(), apiVersion, @@ -1317,7 +1317,7 @@ public Mono> listClusterMonitoringUserCredentia if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.listClusterMonitoringUserCredentials(this.client.getEndpoint(), apiVersion, @@ -1355,7 +1355,7 @@ private Mono> listClusterMonitoringUserCredenti if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.listClusterMonitoringUserCredentials(this.client.getEndpoint(), apiVersion, @@ -1444,7 +1444,7 @@ public Mono> getByResourceGroupWithResponseAsync(S if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.getByResourceGroup(this.client.getEndpoint(), apiVersion, @@ -1481,7 +1481,7 @@ private Mono> getByResourceGroupWithResponseAsync( if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.getByResourceGroup(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -1572,7 +1572,7 @@ public Mono>> createOrUpdateWithResponseAsync(String r } else { parameters.validate(); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.createOrUpdate(this.client.getEndpoint(), apiVersion, @@ -1618,7 +1618,7 @@ private Mono>> createOrUpdateWithResponseAsync(String } else { parameters.validate(); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.createOrUpdate(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -1873,7 +1873,7 @@ public Mono>> updateTagsWithResponseAsync(String resou } else { parameters.validate(); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.updateTags(this.client.getEndpoint(), apiVersion, @@ -1917,7 +1917,7 @@ private Mono>> updateTagsWithResponseAsync(String reso } else { parameters.validate(); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.updateTags(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -2149,7 +2149,7 @@ public Mono>> deleteWithResponseAsync(String resourceG if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.delete(this.client.getEndpoint(), apiVersion, @@ -2187,7 +2187,7 @@ private Mono>> deleteWithResponseAsync(String resource if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.delete(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), resourceGroupName, @@ -2406,7 +2406,7 @@ public Mono>> resetServicePrincipalProfileWithResponse } else { parameters.validate(); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.resetServicePrincipalProfile(this.client.getEndpoint(), apiVersion, @@ -2451,7 +2451,7 @@ private Mono>> resetServicePrincipalProfileWithRespons } else { parameters.validate(); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.resetServicePrincipalProfile(this.client.getEndpoint(), apiVersion, @@ -2659,7 +2659,7 @@ public Mono>> resetAadProfileWithResponseAsync(String } else { parameters.validate(); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.resetAadProfile(this.client.getEndpoint(), apiVersion, @@ -2705,7 +2705,7 @@ private Mono>> resetAadProfileWithResponseAsync(String } else { parameters.validate(); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.resetAadProfile(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -2913,7 +2913,7 @@ public Mono>> rotateClusterCertificatesWithResponseAsy if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.rotateClusterCertificates(this.client.getEndpoint(), apiVersion, @@ -2953,7 +2953,7 @@ private Mono>> rotateClusterCertificatesWithResponseAs if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.rotateClusterCertificates(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -3151,7 +3151,7 @@ public Mono>> abortLatestOperationWithResponseAsync(St if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.abortLatestOperation(this.client.getEndpoint(), apiVersion, @@ -3192,7 +3192,7 @@ private Mono>> abortLatestOperationWithResponseAsync(S if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.abortLatestOperation(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -3392,7 +3392,7 @@ public Mono>> rotateServiceAccountSigningKeysWithRespo if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.rotateServiceAccountSigningKeys(this.client.getEndpoint(), apiVersion, @@ -3429,7 +3429,7 @@ private Mono>> rotateServiceAccountSigningKeysWithResp if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.rotateServiceAccountSigningKeys(this.client.getEndpoint(), apiVersion, @@ -3604,7 +3604,7 @@ public Mono>> stopWithResponseAsync(String resourceGro if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.stop(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -3646,7 +3646,7 @@ private Mono>> stopWithResponseAsync(String resourceGr if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.stop(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), resourceGroupName, @@ -3853,7 +3853,7 @@ public Mono>> startWithResponseAsync(String resourceGr if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.start(this.client.getEndpoint(), apiVersion, @@ -3893,7 +3893,7 @@ private Mono>> startWithResponseAsync(String resourceG if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.start(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), resourceGroupName, @@ -4091,7 +4091,7 @@ public Mono>> runCommandWithResponseAsync(String resou } else { requestPayload.validate(); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.runCommand(this.client.getEndpoint(), apiVersion, @@ -4137,7 +4137,7 @@ private Mono>> runCommandWithResponseAsync(String reso } else { requestPayload.validate(); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.runCommand(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -4351,7 +4351,7 @@ public Mono getCommandResultWithRespons if (commandId == null) { return Mono.error(new IllegalArgumentException("Parameter commandId is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.getCommandResult(this.client.getEndpoint(), apiVersion, @@ -4393,7 +4393,7 @@ private Mono getCommandResultWithRespon if (commandId == null) { return Mono.error(new IllegalArgumentException("Parameter commandId is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.getCommandResult(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -4486,7 +4486,7 @@ public RunCommandResultInner getCommandResult(String resourceGroupName, String r if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.listOutboundNetworkDependenciesEndpoints(this.client.getEndpoint(), @@ -4531,7 +4531,7 @@ public RunCommandResultInner getCommandResult(String resourceGroupName, String r if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service @@ -4658,7 +4658,7 @@ private Mono> listMeshRevisionProfilesSi if (location == null) { return Mono.error(new IllegalArgumentException("Parameter location is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.listMeshRevisionProfiles(this.client.getEndpoint(), apiVersion, @@ -4696,7 +4696,7 @@ private Mono> listMeshRevisionProfilesSi if (location == null) { return Mono.error(new IllegalArgumentException("Parameter location is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service @@ -4808,7 +4808,7 @@ public Mono> getMeshRevisionProfileWithRespon if (mode == null) { return Mono.error(new IllegalArgumentException("Parameter mode is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.getMeshRevisionProfile(this.client.getEndpoint(), apiVersion, @@ -4847,7 +4847,7 @@ private Mono> getMeshRevisionProfileWithRespo if (mode == null) { return Mono.error(new IllegalArgumentException("Parameter mode is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.getMeshRevisionProfile(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -4939,7 +4939,7 @@ public MeshRevisionProfileInner getMeshRevisionProfile(String location, String m if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.listMeshUpgradeProfiles(this.client.getEndpoint(), apiVersion, @@ -4979,7 +4979,7 @@ public MeshRevisionProfileInner getMeshRevisionProfile(String location, String m if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service @@ -5090,7 +5090,7 @@ public Mono> getMeshUpgradeProfileWithResponse if (mode == null) { return Mono.error(new IllegalArgumentException("Parameter mode is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.getMeshUpgradeProfile(this.client.getEndpoint(), apiVersion, @@ -5132,7 +5132,7 @@ private Mono> getMeshUpgradeProfileWithRespons if (mode == null) { return Mono.error(new IllegalArgumentException("Parameter mode is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.getMeshUpgradeProfile(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/OperationsClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/OperationsClientImpl.java index 51d89d154313..f381b63350b0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/OperationsClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/OperationsClientImpl.java @@ -82,7 +82,7 @@ private Mono> listSinglePageAsync() { return Mono.error( new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil.withContext(context -> service.list(this.client.getEndpoint(), apiVersion, accept, context)) .>map(res -> new PagedResponseBase<>(res.getRequest(), @@ -105,7 +105,7 @@ private Mono> listSinglePageAsync(Context con return Mono.error( new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.list(this.client.getEndpoint(), apiVersion, accept, context) diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/PrivateEndpointConnectionsClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/PrivateEndpointConnectionsClientImpl.java index 3350566d2167..0702d2552002 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/PrivateEndpointConnectionsClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/PrivateEndpointConnectionsClientImpl.java @@ -138,7 +138,7 @@ public Mono> listWithResponse if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.list(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -178,7 +178,7 @@ private Mono> listWithRespons if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.list(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), resourceGroupName, @@ -273,7 +273,7 @@ public Mono> getWithResponseAsync(Strin return Mono.error(new IllegalArgumentException( "Parameter privateEndpointConnectionName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.get(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -317,7 +317,7 @@ private Mono> getWithResponseAsync(Stri return Mono.error(new IllegalArgumentException( "Parameter privateEndpointConnectionName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.get(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), resourceGroupName, @@ -422,7 +422,7 @@ public Mono> updateWithResponseAsync(St } else { parameters.validate(); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext( @@ -472,7 +472,7 @@ private Mono> updateWithResponseAsync(S } else { parameters.validate(); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.update(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), resourceGroupName, @@ -570,7 +570,7 @@ public Mono>> deleteWithResponseAsync(String resourceG return Mono.error(new IllegalArgumentException( "Parameter privateEndpointConnectionName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext( @@ -613,7 +613,7 @@ private Mono>> deleteWithResponseAsync(String resource return Mono.error(new IllegalArgumentException( "Parameter privateEndpointConnectionName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.delete(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), resourceGroupName, diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/PrivateLinkResourcesClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/PrivateLinkResourcesClientImpl.java index e7922db2a401..b465a085e97f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/PrivateLinkResourcesClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/PrivateLinkResourcesClientImpl.java @@ -97,7 +97,7 @@ public Mono> listWithResponseAsync if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.list(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -136,7 +136,7 @@ private Mono> listWithResponseAsyn if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.list(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), resourceGroupName, diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/ResolvePrivateLinkServiceIdsClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/ResolvePrivateLinkServiceIdsClientImpl.java index 851dc921c25c..e60b6441d534 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/ResolvePrivateLinkServiceIdsClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/ResolvePrivateLinkServiceIdsClientImpl.java @@ -104,7 +104,7 @@ public Mono> postWithResponseAsync(String res } else { parameters.validate(); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.post(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -148,7 +148,7 @@ private Mono> postWithResponseAsync(String re } else { parameters.validate(); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.post(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), resourceGroupName, diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/SnapshotsClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/SnapshotsClientImpl.java index b3271173e588..6713872a6d01 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/SnapshotsClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/SnapshotsClientImpl.java @@ -160,7 +160,7 @@ private Mono> listSinglePageAsync() { return Mono.error(new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.list(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -190,7 +190,7 @@ private Mono> listSinglePageAsync(Context context) return Mono.error(new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.list(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), accept, context) @@ -275,7 +275,7 @@ private Mono> listByResourceGroupSinglePageAsync(St return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.listByResourceGroup(this.client.getEndpoint(), apiVersion, @@ -311,7 +311,7 @@ private Mono> listByResourceGroupSinglePageAsync(St return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service @@ -409,7 +409,7 @@ public Mono> getByResourceGroupWithResponseAsync(String if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.getByResourceGroup(this.client.getEndpoint(), apiVersion, @@ -446,7 +446,7 @@ private Mono> getByResourceGroupWithResponseAsync(String if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.getByResourceGroup(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -535,7 +535,7 @@ public Mono> createOrUpdateWithResponseAsync(String reso } else { parameters.validate(); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.createOrUpdate(this.client.getEndpoint(), apiVersion, @@ -578,7 +578,7 @@ private Mono> createOrUpdateWithResponseAsync(String res } else { parameters.validate(); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.createOrUpdate(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -671,7 +671,7 @@ public Mono> updateTagsWithResponseAsync(String resource } else { parameters.validate(); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.updateTags(this.client.getEndpoint(), apiVersion, @@ -714,7 +714,7 @@ private Mono> updateTagsWithResponseAsync(String resourc } else { parameters.validate(); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.updateTags(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -799,7 +799,7 @@ public Mono> deleteWithResponseAsync(String resourceGroupName, St if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.delete(this.client.getEndpoint(), apiVersion, @@ -836,7 +836,7 @@ private Mono> deleteWithResponseAsync(String resourceGroupName, S if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.delete(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), resourceGroupName, diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/TrustedAccessRoleBindingsClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/TrustedAccessRoleBindingsClientImpl.java index 91d533d29884..ba29343b49e5 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/TrustedAccessRoleBindingsClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/TrustedAccessRoleBindingsClientImpl.java @@ -148,7 +148,7 @@ private Mono> listSinglePageAsync(S if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.list(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -188,7 +188,7 @@ private Mono> listSinglePageAsync(S if (resourceName == null) { return Mono.error(new IllegalArgumentException("Parameter resourceName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service @@ -297,7 +297,7 @@ public Mono> getWithResponseAsync(String return Mono.error( new IllegalArgumentException("Parameter trustedAccessRoleBindingName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.get(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -339,7 +339,7 @@ private Mono> getWithResponseAsync(Strin return Mono.error( new IllegalArgumentException("Parameter trustedAccessRoleBindingName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.get(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), resourceGroupName, @@ -441,7 +441,7 @@ public Mono>> createOrUpdateWithResponseAsync(String r } else { trustedAccessRoleBinding.validate(); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.createOrUpdate(this.client.getEndpoint(), apiVersion, @@ -493,7 +493,7 @@ private Mono>> createOrUpdateWithResponseAsync(String } else { trustedAccessRoleBinding.validate(); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.createOrUpdate(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -704,7 +704,7 @@ public Mono>> deleteWithResponseAsync(String resourceG return Mono.error( new IllegalArgumentException("Parameter trustedAccessRoleBindingName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext( @@ -747,7 +747,7 @@ private Mono>> deleteWithResponseAsync(String resource return Mono.error( new IllegalArgumentException("Parameter trustedAccessRoleBindingName is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.delete(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), resourceGroupName, diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/TrustedAccessRolesClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/TrustedAccessRolesClientImpl.java index 05c82641a57f..970902d2c3e9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/TrustedAccessRolesClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/implementation/TrustedAccessRolesClientImpl.java @@ -101,7 +101,7 @@ private Mono> listSinglePageAsync(String l if (location == null) { return Mono.error(new IllegalArgumentException("Parameter location is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.list(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), @@ -134,7 +134,7 @@ private Mono> listSinglePageAsync(String l if (location == null) { return Mono.error(new IllegalArgumentException("Parameter location is required and cannot be null.")); } - final String apiVersion = "2024-09-01"; + final String apiVersion = "2024-10-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/models/ManagedClusterAgentPoolProfile.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/models/ManagedClusterAgentPoolProfile.java index ab334e24ccec..60121cd14aa1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/models/ManagedClusterAgentPoolProfile.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/models/ManagedClusterAgentPoolProfile.java @@ -171,6 +171,15 @@ public ManagedClusterAgentPoolProfile withWorkloadRuntime(WorkloadRuntime worklo return this; } + /** + * {@inheritDoc} + */ + @Override + public ManagedClusterAgentPoolProfile withMessageOfTheDay(String messageOfTheDay) { + super.withMessageOfTheDay(messageOfTheDay); + return this; + } + /** * {@inheritDoc} */ @@ -547,6 +556,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStringField("osDiskType", osDiskType() == null ? null : osDiskType().toString()); jsonWriter.writeStringField("kubeletDiskType", kubeletDiskType() == null ? null : kubeletDiskType().toString()); jsonWriter.writeStringField("workloadRuntime", workloadRuntime() == null ? null : workloadRuntime().toString()); + jsonWriter.writeStringField("messageOfTheDay", messageOfTheDay()); jsonWriter.writeStringField("vnetSubnetID", vnetSubnetId()); jsonWriter.writeStringField("podSubnetID", podSubnetId()); jsonWriter.writeNumberField("maxPods", maxPods()); @@ -625,6 +635,8 @@ public static ManagedClusterAgentPoolProfile fromJson(JsonReader jsonReader) thr } else if ("workloadRuntime".equals(fieldName)) { deserializedManagedClusterAgentPoolProfile .withWorkloadRuntime(WorkloadRuntime.fromString(reader.getString())); + } else if ("messageOfTheDay".equals(fieldName)) { + deserializedManagedClusterAgentPoolProfile.withMessageOfTheDay(reader.getString()); } else if ("vnetSubnetID".equals(fieldName)) { deserializedManagedClusterAgentPoolProfile.withVnetSubnetId(reader.getString()); } else if ("podSubnetID".equals(fieldName)) { diff --git a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/samples/java/com/azure/resourcemanager/containerservice/ReadmeSamples.java b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/samples/java/com/azure/resourcemanager/containerservice/ReadmeSamples.java index 2cf39400efbf..c58990066493 100644 --- a/sdk/resourcemanager/azure-resourcemanager-containerservice/src/samples/java/com/azure/resourcemanager/containerservice/ReadmeSamples.java +++ b/sdk/resourcemanager/azure-resourcemanager-containerservice/src/samples/java/com/azure/resourcemanager/containerservice/ReadmeSamples.java @@ -4,8 +4,8 @@ package com.azure.resourcemanager.containerservice; import com.azure.core.credential.TokenCredential; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; /** @@ -15,7 +15,7 @@ public class ReadmeSamples { public void authenticate() { // BEGIN: readme-sample-authenticate - AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-cosmos/CHANGELOG.md b/sdk/resourcemanager/azure-resourcemanager-cosmos/CHANGELOG.md index 28b52037e5af..595adb319908 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cosmos/CHANGELOG.md +++ b/sdk/resourcemanager/azure-resourcemanager-cosmos/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 2.47.0-beta.1 (Unreleased) +## 2.49.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,22 @@ ### Other Changes +## 2.48.0 (2025-02-28) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + +## 2.47.0 (2025-01-24) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + ## 2.46.0 (2024-12-23) ### Other Changes diff --git a/sdk/resourcemanager/azure-resourcemanager-cosmos/README.md b/sdk/resourcemanager/azure-resourcemanager-cosmos/README.md index de0dbb87255f..8b2e1a8b9b51 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cosmos/README.md +++ b/sdk/resourcemanager/azure-resourcemanager-cosmos/README.md @@ -18,7 +18,7 @@ For documentation on how to use this package, please see [Azure Management Libra com.azure.resourcemanager azure-resourcemanager-cosmos - 2.46.0 + 2.49.0-beta.1 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/resourcemanager/azure-resourcemanager-cosmos/pom.xml b/sdk/resourcemanager/azure-resourcemanager-cosmos/pom.xml index 75cf8935703b..33320e4f6e3b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-cosmos/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-cosmos/pom.xml @@ -10,7 +10,7 @@ com.azure.resourcemanager azure-resourcemanager-cosmos - 2.47.0-beta.1 + 2.49.0-beta.1 jar Microsoft Azure SDK for CosmosDB Management @@ -56,7 +56,7 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.47.0-beta.1 + 2.49.0-beta.1 org.junit.jupiter @@ -73,13 +73,13 @@ com.azure.resourcemanager azure-resourcemanager-storage - 2.47.0-beta.1 + 2.49.0-beta.1 test com.azure.resourcemanager azure-resourcemanager-network - 2.47.0-beta.1 + 2.49.0-beta.1 test @@ -91,7 +91,7 @@ com.azure azure-core-http-netty - 1.15.7 + 1.15.11 test diff --git a/sdk/resourcemanager/azure-resourcemanager-dns/CHANGELOG.md b/sdk/resourcemanager/azure-resourcemanager-dns/CHANGELOG.md index 91385042a77e..081285d6d32e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-dns/CHANGELOG.md +++ b/sdk/resourcemanager/azure-resourcemanager-dns/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 2.47.0-beta.1 (Unreleased) +## 2.49.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,22 @@ ### Other Changes +## 2.48.0 (2025-02-28) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + +## 2.47.0 (2025-01-24) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + ## 2.46.0 (2024-12-23) ### Other Changes diff --git a/sdk/resourcemanager/azure-resourcemanager-dns/README.md b/sdk/resourcemanager/azure-resourcemanager-dns/README.md index e5de5067a39e..f41676797042 100644 --- a/sdk/resourcemanager/azure-resourcemanager-dns/README.md +++ b/sdk/resourcemanager/azure-resourcemanager-dns/README.md @@ -18,7 +18,7 @@ For documentation on how to use this package, please see [Azure Management Libra com.azure.resourcemanager azure-resourcemanager-dns - 2.46.0 + 2.49.0-beta.1 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/resourcemanager/azure-resourcemanager-dns/pom.xml b/sdk/resourcemanager/azure-resourcemanager-dns/pom.xml index 20a1580eea32..dfd9feacfa74 100644 --- a/sdk/resourcemanager/azure-resourcemanager-dns/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-dns/pom.xml @@ -14,7 +14,7 @@ com.azure.resourcemanager azure-resourcemanager-dns - 2.47.0-beta.1 + 2.49.0-beta.1 jar Microsoft Azure SDK for DNS Management @@ -58,7 +58,7 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.47.0-beta.1 + 2.49.0-beta.1 commons-io @@ -87,7 +87,7 @@ com.azure azure-core-http-netty - 1.15.7 + 1.15.11 test diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/CHANGELOG.md b/sdk/resourcemanager/azure-resourcemanager-eventhubs/CHANGELOG.md index c00a69b5da84..72213559d249 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/CHANGELOG.md +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 2.47.0-beta.1 (Unreleased) +## 2.49.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,30 @@ ### Other Changes +## 2.48.0 (2025-02-28) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + +## 2.48.0-beta.1 (2025-02-14) + +### Other Changes + +#### Dependency Updates + +- Updated `api-version` to `2024-05-01-preview`. + +## 2.47.0 (2025-01-24) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + ## 2.46.0 (2024-12-23) ### Other Changes diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/README.md b/sdk/resourcemanager/azure-resourcemanager-eventhubs/README.md index 499f83aae9d5..b3894bf1fc9d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/README.md +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/README.md @@ -18,7 +18,7 @@ For documentation on how to use this package, please see [Azure Management Libra com.azure.resourcemanager azure-resourcemanager-eventhubs - 2.46.0 + 2.49.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -39,7 +39,7 @@ Azure tenant ID can be configured via `AZURE_TENANT_ID` environment variable. Assuming the use of the `DefaultAzureCredential` credential class, the client can be authenticated using the following code: ```java readme-sample-authenticate -AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); +AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/pom.xml b/sdk/resourcemanager/azure-resourcemanager-eventhubs/pom.xml index 96415575059c..ee1867855dab 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/pom.xml @@ -14,7 +14,7 @@ com.azure.resourcemanager azure-resourcemanager-eventhubs - 2.47.0-beta.1 + 2.49.0-beta.1 jar Microsoft Azure SDK for EventHubs Management @@ -59,12 +59,12 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-storage - 2.47.0-beta.1 + 2.49.0-beta.1 org.junit.jupiter @@ -81,7 +81,7 @@ com.azure azure-core-http-netty - 1.15.7 + 1.15.11 test diff --git a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/samples/java/com/azure/resourcemanager/eventhubs/ReadmeSamples.java b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/samples/java/com/azure/resourcemanager/eventhubs/ReadmeSamples.java index 8f087fca6274..ccd0d141d832 100644 --- a/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/samples/java/com/azure/resourcemanager/eventhubs/ReadmeSamples.java +++ b/sdk/resourcemanager/azure-resourcemanager-eventhubs/src/samples/java/com/azure/resourcemanager/eventhubs/ReadmeSamples.java @@ -4,8 +4,8 @@ package com.azure.resourcemanager.eventhubs; import com.azure.core.credential.TokenCredential; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; /** @@ -15,7 +15,7 @@ public class ReadmeSamples { public void authenticate() { // BEGIN: readme-sample-authenticate - AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-keyvault/CHANGELOG.md b/sdk/resourcemanager/azure-resourcemanager-keyvault/CHANGELOG.md index 6c46448019da..e2bcc1825235 100644 --- a/sdk/resourcemanager/azure-resourcemanager-keyvault/CHANGELOG.md +++ b/sdk/resourcemanager/azure-resourcemanager-keyvault/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 2.47.0-beta.1 (Unreleased) +## 2.49.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,22 @@ ### Other Changes +## 2.48.0 (2025-02-28) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + +## 2.47.0 (2025-01-24) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + ## 2.46.0 (2024-12-23) ### Other Changes diff --git a/sdk/resourcemanager/azure-resourcemanager-keyvault/README.md b/sdk/resourcemanager/azure-resourcemanager-keyvault/README.md index e81bdb247aae..5003e082a915 100644 --- a/sdk/resourcemanager/azure-resourcemanager-keyvault/README.md +++ b/sdk/resourcemanager/azure-resourcemanager-keyvault/README.md @@ -18,7 +18,7 @@ For documentation on how to use this package, please see [Azure Management Libra com.azure.resourcemanager azure-resourcemanager-keyvault - 2.46.0 + 2.49.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -39,7 +39,7 @@ Azure tenant ID can be configured via `AZURE_TENANT_ID` environment variable. Assuming the use of the `DefaultAzureCredential` credential class, the client can be authenticated using the following code: ```java readme-sample-authenticate -AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); +AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-keyvault/pom.xml b/sdk/resourcemanager/azure-resourcemanager-keyvault/pom.xml index 7e968ef9c046..fc2c8348a1d1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-keyvault/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-keyvault/pom.xml @@ -14,7 +14,7 @@ com.azure.resourcemanager azure-resourcemanager-keyvault - 2.47.0-beta.1 + 2.49.0-beta.1 jar Microsoft Azure SDK for Key Vault Management @@ -59,17 +59,17 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-authorization - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure azure-security-keyvault-keys - 4.9.1 + 4.9.3 com.azure @@ -80,7 +80,7 @@ com.azure azure-security-keyvault-secrets - 4.9.1 + 4.9.3 com.azure @@ -103,7 +103,7 @@ com.azure azure-core-http-netty - 1.15.7 + 1.15.11 test diff --git a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/samples/java/com/azure/resourcemanager/keyvault/ReadmeSamples.java b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/samples/java/com/azure/resourcemanager/keyvault/ReadmeSamples.java index 79fceea60bf8..54dfd9f36027 100644 --- a/sdk/resourcemanager/azure-resourcemanager-keyvault/src/samples/java/com/azure/resourcemanager/keyvault/ReadmeSamples.java +++ b/sdk/resourcemanager/azure-resourcemanager-keyvault/src/samples/java/com/azure/resourcemanager/keyvault/ReadmeSamples.java @@ -4,8 +4,8 @@ package com.azure.resourcemanager.keyvault; import com.azure.core.credential.TokenCredential; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; /** @@ -15,7 +15,7 @@ public class ReadmeSamples { public void authenticate() { // BEGIN: readme-sample-authenticate - AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/CHANGELOG.md b/sdk/resourcemanager/azure-resourcemanager-monitor/CHANGELOG.md index 4498e0e5a2e9..0ba5d443e565 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/CHANGELOG.md +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 2.47.0-beta.1 (Unreleased) +## 2.49.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,22 @@ ### Other Changes +## 2.48.0 (2025-02-28) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + +## 2.47.0 (2025-01-24) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + ## 2.46.0 (2024-12-23) ### Other Changes diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/README.md b/sdk/resourcemanager/azure-resourcemanager-monitor/README.md index 290ce1084dee..7609faef8696 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/README.md +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/README.md @@ -18,7 +18,7 @@ For documentation on how to use this package, please see [Azure Management Libra com.azure.resourcemanager azure-resourcemanager-monitor - 2.46.0 + 2.49.0-beta.1 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/resourcemanager/azure-resourcemanager-monitor/pom.xml b/sdk/resourcemanager/azure-resourcemanager-monitor/pom.xml index 88db8c4a421d..99aabb7bdc71 100644 --- a/sdk/resourcemanager/azure-resourcemanager-monitor/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-monitor/pom.xml @@ -10,7 +10,7 @@ com.azure.resourcemanager azure-resourcemanager-monitor - 2.47.0-beta.1 + 2.49.0-beta.1 jar Microsoft Azure SDK for Monitor Management @@ -61,7 +61,7 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.47.0-beta.1 + 2.49.0-beta.1 org.junit.jupiter @@ -78,37 +78,37 @@ com.azure azure-core-http-netty - 1.15.7 + 1.15.11 test com.azure.resourcemanager azure-resourcemanager-compute - 2.47.0-beta.1 + 2.49.0-beta.1 test com.azure.resourcemanager azure-resourcemanager-appservice - 2.47.0-beta.1 + 2.49.0-beta.1 test com.azure.resourcemanager azure-resourcemanager-storage - 2.47.0-beta.1 + 2.49.0-beta.1 test com.azure.resourcemanager azure-resourcemanager-eventhubs - 2.47.0-beta.1 + 2.49.0-beta.1 test com.azure.resourcemanager azure-resourcemanager-sql - 2.47.0-beta.1 + 2.49.0-beta.1 test diff --git a/sdk/resourcemanager/azure-resourcemanager-msi/CHANGELOG.md b/sdk/resourcemanager/azure-resourcemanager-msi/CHANGELOG.md index 27809d946aa9..dae3a45ef750 100644 --- a/sdk/resourcemanager/azure-resourcemanager-msi/CHANGELOG.md +++ b/sdk/resourcemanager/azure-resourcemanager-msi/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 2.47.0-beta.1 (Unreleased) +## 2.49.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,22 @@ ### Other Changes +## 2.48.0 (2025-02-28) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + +## 2.47.0 (2025-01-24) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + ## 2.46.0 (2024-12-23) ### Other Changes diff --git a/sdk/resourcemanager/azure-resourcemanager-msi/README.md b/sdk/resourcemanager/azure-resourcemanager-msi/README.md index 69bff936718a..50e973037128 100644 --- a/sdk/resourcemanager/azure-resourcemanager-msi/README.md +++ b/sdk/resourcemanager/azure-resourcemanager-msi/README.md @@ -18,7 +18,7 @@ For documentation on how to use this package, please see [Azure Management Libra com.azure.resourcemanager azure-resourcemanager-msi - 2.46.0 + 2.49.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -39,7 +39,7 @@ Azure tenant ID can be configured via `AZURE_TENANT_ID` environment variable. Assuming the use of the `DefaultAzureCredential` credential class, the client can be authenticated using the following code: ```java readme-sample-authenticate -AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); +AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-msi/pom.xml b/sdk/resourcemanager/azure-resourcemanager-msi/pom.xml index 5a712a558311..61b5d71b3b3c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-msi/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-msi/pom.xml @@ -10,7 +10,7 @@ com.azure.resourcemanager azure-resourcemanager-msi - 2.47.0-beta.1 + 2.49.0-beta.1 jar Microsoft Azure SDK for Managed Service Identity (MSI) Management @@ -57,12 +57,12 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-authorization - 2.47.0-beta.1 + 2.49.0-beta.1 org.junit.jupiter @@ -73,7 +73,7 @@ com.azure azure-core-http-netty - 1.15.7 + 1.15.11 test diff --git a/sdk/resourcemanager/azure-resourcemanager-msi/src/samples/java/com/azure/resourcemanager/msi/ReadmeSamples.java b/sdk/resourcemanager/azure-resourcemanager-msi/src/samples/java/com/azure/resourcemanager/msi/ReadmeSamples.java index 55ab271b0a92..530aa76a72b3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-msi/src/samples/java/com/azure/resourcemanager/msi/ReadmeSamples.java +++ b/sdk/resourcemanager/azure-resourcemanager-msi/src/samples/java/com/azure/resourcemanager/msi/ReadmeSamples.java @@ -4,8 +4,8 @@ package com.azure.resourcemanager.msi; import com.azure.core.credential.TokenCredential; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; /** @@ -15,7 +15,7 @@ public class ReadmeSamples { public void authenticate() { // BEGIN: readme-sample-authenticate - AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-network/CHANGELOG.md b/sdk/resourcemanager/azure-resourcemanager-network/CHANGELOG.md index c758fdfebde0..ab9eb62e2a69 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/CHANGELOG.md +++ b/sdk/resourcemanager/azure-resourcemanager-network/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 2.47.0-beta.1 (Unreleased) +## 2.49.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,22 @@ ### Other Changes +## 2.48.0 (2025-02-28) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + +## 2.47.0 (2025-01-24) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + ## 2.46.0 (2024-12-23) ### Other Changes diff --git a/sdk/resourcemanager/azure-resourcemanager-network/README.md b/sdk/resourcemanager/azure-resourcemanager-network/README.md index 585b177f36ae..db18f89a7a95 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/README.md +++ b/sdk/resourcemanager/azure-resourcemanager-network/README.md @@ -18,7 +18,7 @@ For documentation on how to use this package, please see [Azure Management Libra com.azure.resourcemanager azure-resourcemanager-network - 2.46.0 + 2.49.0-beta.1 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/resourcemanager/azure-resourcemanager-network/pom.xml b/sdk/resourcemanager/azure-resourcemanager-network/pom.xml index 9fd1e1e13eb6..f170d7f49b6b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-network/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-network/pom.xml @@ -14,7 +14,7 @@ com.azure.resourcemanager azure-resourcemanager-network - 2.47.0-beta.1 + 2.49.0-beta.1 jar Microsoft Azure SDK for Network Management @@ -64,7 +64,7 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.47.0-beta.1 + 2.49.0-beta.1 org.junit.jupiter @@ -81,25 +81,25 @@ com.azure azure-core-http-netty - 1.15.7 + 1.15.11 test com.azure azure-security-keyvault-certificates - 4.7.1 + 4.7.3 test com.azure.resourcemanager azure-resourcemanager-keyvault - 2.47.0-beta.1 + 2.49.0-beta.1 test com.azure.resourcemanager azure-resourcemanager-msi - 2.47.0-beta.1 + 2.49.0-beta.1 test diff --git a/sdk/resourcemanager/azure-resourcemanager-perf/pom.xml b/sdk/resourcemanager/azure-resourcemanager-perf/pom.xml index c2bf98e1170b..4988a83182e3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-perf/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-perf/pom.xml @@ -25,7 +25,7 @@ com.azure.resourcemanager azure-resourcemanager - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager @@ -41,12 +41,12 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 diff --git a/sdk/resourcemanager/azure-resourcemanager-privatedns/CHANGELOG.md b/sdk/resourcemanager/azure-resourcemanager-privatedns/CHANGELOG.md index 53ac0a408b9c..25c062d761b8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-privatedns/CHANGELOG.md +++ b/sdk/resourcemanager/azure-resourcemanager-privatedns/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 2.47.0-beta.1 (Unreleased) +## 2.49.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,22 @@ ### Other Changes +## 2.48.0 (2025-02-28) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + +## 2.47.0 (2025-01-24) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + ## 2.46.0 (2024-12-23) ### Other Changes diff --git a/sdk/resourcemanager/azure-resourcemanager-privatedns/README.md b/sdk/resourcemanager/azure-resourcemanager-privatedns/README.md index 476190032cb6..207c8bb54071 100644 --- a/sdk/resourcemanager/azure-resourcemanager-privatedns/README.md +++ b/sdk/resourcemanager/azure-resourcemanager-privatedns/README.md @@ -18,7 +18,7 @@ For documentation on how to use this package, please see [Azure Management Libra com.azure.resourcemanager azure-resourcemanager-privatedns - 2.46.0 + 2.49.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -39,7 +39,7 @@ Azure tenant ID can be configured via `AZURE_TENANT_ID` environment variable. Assuming the use of the `DefaultAzureCredential` credential class, the client can be authenticated using the following code: ```java readme-sample-authenticate -AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); +AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-privatedns/pom.xml b/sdk/resourcemanager/azure-resourcemanager-privatedns/pom.xml index e0bf3f07c90e..077c5d122585 100644 --- a/sdk/resourcemanager/azure-resourcemanager-privatedns/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-privatedns/pom.xml @@ -14,7 +14,7 @@ com.azure.resourcemanager azure-resourcemanager-privatedns - 2.47.0-beta.1 + 2.49.0-beta.1 jar Microsoft Azure SDK for Private DNS Management @@ -61,12 +61,12 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-network - 2.47.0-beta.1 + 2.49.0-beta.1 test @@ -84,7 +84,7 @@ com.azure azure-core-http-netty - 1.15.7 + 1.15.11 test diff --git a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/samples/java/com/azure/resourcemanager/privatedns/ReadmeSamples.java b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/samples/java/com/azure/resourcemanager/privatedns/ReadmeSamples.java index 209ff7efed87..9a69523073dc 100644 --- a/sdk/resourcemanager/azure-resourcemanager-privatedns/src/samples/java/com/azure/resourcemanager/privatedns/ReadmeSamples.java +++ b/sdk/resourcemanager/azure-resourcemanager-privatedns/src/samples/java/com/azure/resourcemanager/privatedns/ReadmeSamples.java @@ -4,8 +4,8 @@ package com.azure.resourcemanager.privatedns; import com.azure.core.credential.TokenCredential; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; /** @@ -15,7 +15,7 @@ public class ReadmeSamples { public void authenticate() { // BEGIN: readme-sample-authenticate - AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-redis/CHANGELOG.md b/sdk/resourcemanager/azure-resourcemanager-redis/CHANGELOG.md index 5708470d608d..bb2d74d6facd 100644 --- a/sdk/resourcemanager/azure-resourcemanager-redis/CHANGELOG.md +++ b/sdk/resourcemanager/azure-resourcemanager-redis/CHANGELOG.md @@ -1,6 +1,24 @@ # Release History -## 2.47.0-beta.1 (Unreleased) +## 2.49.0-beta.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + +## 2.48.0 (2025-02-28) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + +## 2.47.0 (2025-01-24) ### Other Changes diff --git a/sdk/resourcemanager/azure-resourcemanager-redis/README.md b/sdk/resourcemanager/azure-resourcemanager-redis/README.md index 757f236ee529..9daa2c6dd601 100644 --- a/sdk/resourcemanager/azure-resourcemanager-redis/README.md +++ b/sdk/resourcemanager/azure-resourcemanager-redis/README.md @@ -18,7 +18,7 @@ For documentation on how to use this package, please see [Azure Management Libra com.azure.resourcemanager azure-resourcemanager-redis - 2.46.0 + 2.49.0-beta.1 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/resourcemanager/azure-resourcemanager-redis/pom.xml b/sdk/resourcemanager/azure-resourcemanager-redis/pom.xml index ae8fd9c777a2..24369be76fa3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-redis/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-redis/pom.xml @@ -14,7 +14,7 @@ com.azure.resourcemanager azure-resourcemanager-redis - 2.47.0-beta.1 + 2.49.0-beta.1 jar Microsoft Azure SDK for Redis Cache Management @@ -61,7 +61,7 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.47.0-beta.1 + 2.49.0-beta.1 org.junit.jupiter @@ -78,13 +78,13 @@ com.azure azure-core-http-netty - 1.15.7 + 1.15.11 test com.azure.resourcemanager azure-resourcemanager-storage - 2.47.0-beta.1 + 2.49.0-beta.1 test diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/CHANGELOG.md b/sdk/resourcemanager/azure-resourcemanager-resources/CHANGELOG.md index 8af3058a66d3..c2b42366d726 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/CHANGELOG.md +++ b/sdk/resourcemanager/azure-resourcemanager-resources/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 2.47.0-beta.1 (Unreleased) +## 2.49.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,22 @@ ### Other Changes +## 2.48.0 (2025-02-28) + +### Other Changes + +#### Dependency Updates + +- Updated `api-version` of resources to `2024-11-01`. + +## 2.47.0 (2025-01-24) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + ## 2.46.0 (2024-12-23) ### Other Changes diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/README.md b/sdk/resourcemanager/azure-resourcemanager-resources/README.md index d0ee7ecb0492..91852bd79ed1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/README.md +++ b/sdk/resourcemanager/azure-resourcemanager-resources/README.md @@ -18,7 +18,7 @@ For documentation on how to use this package, please see [Azure Management Libra com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.49.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -39,7 +39,7 @@ Azure tenant ID can be configured via `AZURE_TENANT_ID` environment variable. Assuming the use of the `DefaultAzureCredential` credential class, the client can be authenticated using the following code: ```java readme-sample-authenticate -AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); +AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/assets.json b/sdk/resourcemanager/azure-resourcemanager-resources/assets.json index 1188baa11f2d..7675fb734380 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/assets.json +++ b/sdk/resourcemanager/azure-resourcemanager-resources/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "java", "TagPrefix": "java/resourcemanager/azure-resourcemanager-resources", - "Tag": "java/resourcemanager/azure-resourcemanager-resources_f8a1e5fca6" + "Tag": "java/resourcemanager/azure-resourcemanager-resources_f8b2a080f4" } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/pom.xml b/sdk/resourcemanager/azure-resourcemanager-resources/pom.xml index b8b7b79fb194..29eba5746a58 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-resources/pom.xml @@ -14,7 +14,7 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.47.0-beta.1 + 2.49.0-beta.1 jar Microsoft Azure SDK for Resource Management @@ -60,17 +60,17 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-json - 1.3.0 + 1.5.0 org.mockito diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/TagOperationsClient.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/TagOperationsClient.java index c21c898c0a3f..54be725b5782 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/TagOperationsClient.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/TagOperationsClient.java @@ -14,8 +14,8 @@ import com.azure.core.util.polling.PollerFlux; import com.azure.core.util.polling.SyncPoller; import com.azure.resourcemanager.resources.fluent.models.TagDetailsInner; -import com.azure.resourcemanager.resources.fluent.models.TagsResourceInner; import com.azure.resourcemanager.resources.fluent.models.TagValueInner; +import com.azure.resourcemanager.resources.fluent.models.TagsResourceInner; import com.azure.resourcemanager.resources.models.TagsPatchResource; import java.nio.ByteBuffer; import reactor.core.publisher.Flux; diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/ChangeResourceResultInner.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/ChangeResourceResultInner.java index 147d51ec1e61..63153975fb1d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/ChangeResourceResultInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/ChangeResourceResultInner.java @@ -23,9 +23,9 @@ public final class ChangeResourceResultInner extends ProxyResource { private ChangeProperties properties; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -33,9 +33,9 @@ public final class ChangeResourceResultInner extends ProxyResource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of ChangeResourceResultInner class. @@ -64,13 +64,13 @@ public ChangeResourceResultInner withProperties(ChangeProperties properties) { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -84,13 +84,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/DataPolicyManifestInner.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/DataPolicyManifestInner.java index 11aaf2002ed4..cf4cd45c3d0b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/DataPolicyManifestInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/DataPolicyManifestInner.java @@ -26,9 +26,9 @@ public final class DataPolicyManifestInner extends ProxyResource { private DataPolicyManifestProperties innerProperties; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -36,9 +36,9 @@ public final class DataPolicyManifestInner extends ProxyResource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of DataPolicyManifestInner class. @@ -56,13 +56,13 @@ private DataPolicyManifestProperties innerProperties() { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -76,13 +76,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/DeploymentExtendedInner.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/DeploymentExtendedInner.java index b548556552cf..4017a1989f11 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/DeploymentExtendedInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/DeploymentExtendedInner.java @@ -24,9 +24,9 @@ public final class DeploymentExtendedInner extends Resource { private DeploymentPropertiesExtended properties; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -34,9 +34,9 @@ public final class DeploymentExtendedInner extends Resource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of DeploymentExtendedInner class. @@ -65,13 +65,13 @@ public DeploymentExtendedInner withProperties(DeploymentPropertiesExtended prope } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -85,13 +85,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/DeploymentStackInner.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/DeploymentStackInner.java index e8c324210bc2..a716cc865de4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/DeploymentStackInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/DeploymentStackInner.java @@ -47,24 +47,24 @@ public final class DeploymentStackInner extends AzureResourceBase { private DeploymentStackProperties innerProperties; /* - * Fully qualified resource Id for the resource. + * Azure Resource Manager metadata containing createdBy and modifiedBy information. */ - private String id; + private SystemData systemData; /* - * The name of the resource. + * The type of the resource. */ - private String name; + private String type; /* - * The type of the resource. + * The name of the resource. */ - private String type; + private String name; /* - * Azure Resource Manager metadata containing createdBy and modifiedBy information. + * Fully qualified resource Id for the resource. */ - private SystemData systemData; + private String id; /** * Creates an instance of DeploymentStackInner class. @@ -124,43 +124,43 @@ private DeploymentStackProperties innerProperties() { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. * - * @return the id value. + * @return the systemData value. */ @Override - public String id() { - return this.id; + public SystemData systemData() { + return this.systemData; } /** - * Get the name property: The name of the resource. + * Get the type property: The type of the resource. * - * @return the name value. + * @return the type value. */ @Override - public String name() { - return this.name; + public String type() { + return this.type; } /** - * Get the type property: The type of the resource. + * Get the name property: The name of the resource. * - * @return the type value. + * @return the name value. */ @Override - public String type() { - return this.type; + public String name() { + return this.name; } /** - * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the systemData value. + * @return the id value. */ @Override - public SystemData systemData() { - return this.systemData; + public String id() { + return this.id; } /** @@ -534,7 +534,6 @@ public DeploymentStackInner withError(ManagementError error) { */ @Override public void validate() { - super.validate(); if (innerProperties() != null) { innerProperties().validate(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/DeploymentStackValidateResultInner.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/DeploymentStackValidateResultInner.java index 7f413898ec82..cc5223f6055a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/DeploymentStackValidateResultInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/DeploymentStackValidateResultInner.java @@ -30,24 +30,24 @@ public final class DeploymentStackValidateResultInner extends AzureResourceBase private ManagementError error; /* - * Fully qualified resource Id for the resource. + * Azure Resource Manager metadata containing createdBy and modifiedBy information. */ - private String id; + private SystemData systemData; /* - * The name of the resource. + * The type of the resource. */ - private String name; + private String type; /* - * The type of the resource. + * The name of the resource. */ - private String type; + private String name; /* - * Azure Resource Manager metadata containing createdBy and modifiedBy information. + * Fully qualified resource Id for the resource. */ - private SystemData systemData; + private String id; /** * Creates an instance of DeploymentStackValidateResultInner class. @@ -96,43 +96,43 @@ public DeploymentStackValidateResultInner withError(ManagementError error) { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. * - * @return the id value. + * @return the systemData value. */ @Override - public String id() { - return this.id; + public SystemData systemData() { + return this.systemData; } /** - * Get the name property: The name of the resource. + * Get the type property: The type of the resource. * - * @return the name value. + * @return the type value. */ @Override - public String name() { - return this.name; + public String type() { + return this.type; } /** - * Get the type property: The type of the resource. + * Get the name property: The name of the resource. * - * @return the type value. + * @return the name value. */ @Override - public String type() { - return this.type; + public String name() { + return this.name; } /** - * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the systemData value. + * @return the id value. */ @Override - public SystemData systemData() { - return this.systemData; + public String id() { + return this.id; } /** @@ -142,7 +142,6 @@ public SystemData systemData() { */ @Override public void validate() { - super.validate(); if (properties() != null) { properties().validate(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/DeploymentValidateResultInner.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/DeploymentValidateResultInner.java index 56ccab7993f1..22544a71e8c9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/DeploymentValidateResultInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/DeploymentValidateResultInner.java @@ -23,6 +23,21 @@ public final class DeploymentValidateResultInner implements JsonSerializable tags) { */ @Override public void validate() { - super.validate(); + if (plan() != null) { + plan().validate(); + } + if (sku() != null) { + sku().validate(); + } + if (identity() != null) { + identity().validate(); + } + if (extendedLocation() != null) { + extendedLocation().validate(); + } } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/GenericResourceInner.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/GenericResourceInner.java index 288368d0f9f8..55900ad7f81a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/GenericResourceInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/GenericResourceInner.java @@ -57,9 +57,9 @@ public class GenericResourceInner extends Resource { private ExtendedLocation extendedLocation; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -67,9 +67,9 @@ public class GenericResourceInner extends Resource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of GenericResourceInner class. @@ -218,13 +218,13 @@ public GenericResourceInner withExtendedLocation(ExtendedLocation extendedLocati } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -238,13 +238,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/ManagementLockObjectInner.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/ManagementLockObjectInner.java index f51059a5e243..c8f1e6191a3a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/ManagementLockObjectInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/ManagementLockObjectInner.java @@ -26,9 +26,9 @@ public final class ManagementLockObjectInner extends ProxyResource { private ManagementLockProperties innerProperties = new ManagementLockProperties(); /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -36,9 +36,9 @@ public final class ManagementLockObjectInner extends ProxyResource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of ManagementLockObjectInner class. @@ -56,13 +56,13 @@ private ManagementLockProperties innerProperties() { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -76,13 +76,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/PolicyAssignmentInner.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/PolicyAssignmentInner.java index fd256c39cdde..933618aba481 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/PolicyAssignmentInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/PolicyAssignmentInner.java @@ -46,9 +46,9 @@ public final class PolicyAssignmentInner extends ProxyResource { private SystemData systemData; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -56,9 +56,9 @@ public final class PolicyAssignmentInner extends ProxyResource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of PolicyAssignmentInner class. @@ -125,13 +125,13 @@ public SystemData systemData() { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -145,13 +145,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/PolicyDefinitionInner.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/PolicyDefinitionInner.java index 9ac54d52d6aa..4650f96ee9a4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/PolicyDefinitionInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/PolicyDefinitionInner.java @@ -31,9 +31,9 @@ public final class PolicyDefinitionInner extends ProxyResource { private SystemData systemData; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -41,9 +41,9 @@ public final class PolicyDefinitionInner extends ProxyResource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of PolicyDefinitionInner class. @@ -70,13 +70,13 @@ public SystemData systemData() { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -90,13 +90,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/PolicyExemptionInner.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/PolicyExemptionInner.java index 8369bb495b8c..e7a539d2b292 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/PolicyExemptionInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/PolicyExemptionInner.java @@ -34,9 +34,9 @@ public final class PolicyExemptionInner extends ProxyResource { private SystemData systemData; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -44,9 +44,9 @@ public final class PolicyExemptionInner extends ProxyResource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of PolicyExemptionInner class. @@ -73,13 +73,13 @@ public SystemData systemData() { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -93,13 +93,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/PolicySetDefinitionInner.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/PolicySetDefinitionInner.java index 681c95756a26..5b0fd8e41397 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/PolicySetDefinitionInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/PolicySetDefinitionInner.java @@ -34,9 +34,9 @@ public final class PolicySetDefinitionInner extends ProxyResource { private SystemData systemData; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -44,9 +44,9 @@ public final class PolicySetDefinitionInner extends ProxyResource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of PolicySetDefinitionInner class. @@ -73,13 +73,13 @@ public SystemData systemData() { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -93,13 +93,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/ResourceGroupInner.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/ResourceGroupInner.java index 940ace373c3e..9be1dd41a070 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/ResourceGroupInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/ResourceGroupInner.java @@ -29,9 +29,9 @@ public final class ResourceGroupInner extends Resource { private String managedBy; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -39,9 +39,9 @@ public final class ResourceGroupInner extends Resource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of ResourceGroupInner class. @@ -90,13 +90,13 @@ public ResourceGroupInner withManagedBy(String managedBy) { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -110,13 +110,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/SubscriptionFeatureRegistrationInner.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/SubscriptionFeatureRegistrationInner.java index 0a57c5fbb711..9503db7812cb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/SubscriptionFeatureRegistrationInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/SubscriptionFeatureRegistrationInner.java @@ -23,9 +23,9 @@ public final class SubscriptionFeatureRegistrationInner extends ProxyResource { private SubscriptionFeatureRegistrationProperties properties; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -33,9 +33,9 @@ public final class SubscriptionFeatureRegistrationInner extends ProxyResource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of SubscriptionFeatureRegistrationInner class. @@ -64,13 +64,13 @@ public SubscriptionFeatureRegistrationInner withProperties(SubscriptionFeatureRe } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -84,13 +84,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/TagsResourceInner.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/TagsResourceInner.java index 30ed6c0b0bcb..e46cabc08a01 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/TagsResourceInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/TagsResourceInner.java @@ -24,9 +24,9 @@ public final class TagsResourceInner extends ProxyResource { private Tags properties; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -34,9 +34,9 @@ public final class TagsResourceInner extends ProxyResource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of TagsResourceInner class. @@ -65,13 +65,13 @@ public TagsResourceInner withProperties(Tags properties) { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -85,13 +85,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/WhatIfOperationProperties.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/WhatIfOperationProperties.java index ac33341b5d4b..aee8bf6a1239 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/WhatIfOperationProperties.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/WhatIfOperationProperties.java @@ -9,6 +9,7 @@ import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; +import com.azure.resourcemanager.resources.models.DeploymentDiagnosticsDefinition; import com.azure.resourcemanager.resources.models.WhatIfChange; import java.io.IOException; import java.util.List; @@ -23,6 +24,16 @@ public final class WhatIfOperationProperties implements JsonSerializable changes; + /* + * List of resource changes predicted by What-If operation. + */ + private List potentialChanges; + + /* + * List of resource diagnostics detected by What-If operation. + */ + private List diagnostics; + /** * Creates an instance of WhatIfOperationProperties class. */ @@ -49,6 +60,35 @@ public WhatIfOperationProperties withChanges(List changes) { return this; } + /** + * Get the potentialChanges property: List of resource changes predicted by What-If operation. + * + * @return the potentialChanges value. + */ + public List potentialChanges() { + return this.potentialChanges; + } + + /** + * Set the potentialChanges property: List of resource changes predicted by What-If operation. + * + * @param potentialChanges the potentialChanges value to set. + * @return the WhatIfOperationProperties object itself. + */ + public WhatIfOperationProperties withPotentialChanges(List potentialChanges) { + this.potentialChanges = potentialChanges; + return this; + } + + /** + * Get the diagnostics property: List of resource diagnostics detected by What-If operation. + * + * @return the diagnostics value. + */ + public List diagnostics() { + return this.diagnostics; + } + /** * Validates the instance. * @@ -58,6 +98,12 @@ public void validate() { if (changes() != null) { changes().forEach(e -> e.validate()); } + if (potentialChanges() != null) { + potentialChanges().forEach(e -> e.validate()); + } + if (diagnostics() != null) { + diagnostics().forEach(e -> e.validate()); + } } /** @@ -67,6 +113,8 @@ public void validate() { public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeArrayField("changes", this.changes, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeArrayField("potentialChanges", this.potentialChanges, + (writer, element) -> writer.writeJson(element)); return jsonWriter.writeEndObject(); } @@ -88,6 +136,13 @@ public static WhatIfOperationProperties fromJson(JsonReader jsonReader) throws I if ("changes".equals(fieldName)) { List changes = reader.readArray(reader1 -> WhatIfChange.fromJson(reader1)); deserializedWhatIfOperationProperties.changes = changes; + } else if ("potentialChanges".equals(fieldName)) { + List potentialChanges = reader.readArray(reader1 -> WhatIfChange.fromJson(reader1)); + deserializedWhatIfOperationProperties.potentialChanges = potentialChanges; + } else if ("diagnostics".equals(fieldName)) { + List diagnostics + = reader.readArray(reader1 -> DeploymentDiagnosticsDefinition.fromJson(reader1)); + deserializedWhatIfOperationProperties.diagnostics = diagnostics; } else { reader.skipChildren(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/WhatIfOperationResultInner.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/WhatIfOperationResultInner.java index 31a900c9cc0d..583df84a433c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/WhatIfOperationResultInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/fluent/models/WhatIfOperationResultInner.java @@ -10,6 +10,7 @@ import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; +import com.azure.resourcemanager.resources.models.DeploymentDiagnosticsDefinition; import com.azure.resourcemanager.resources.models.WhatIfChange; import java.io.IOException; import java.util.List; @@ -113,6 +114,38 @@ public WhatIfOperationResultInner withChanges(List changes) { return this; } + /** + * Get the potentialChanges property: List of resource changes predicted by What-If operation. + * + * @return the potentialChanges value. + */ + public List potentialChanges() { + return this.innerProperties() == null ? null : this.innerProperties().potentialChanges(); + } + + /** + * Set the potentialChanges property: List of resource changes predicted by What-If operation. + * + * @param potentialChanges the potentialChanges value to set. + * @return the WhatIfOperationResultInner object itself. + */ + public WhatIfOperationResultInner withPotentialChanges(List potentialChanges) { + if (this.innerProperties() == null) { + this.innerProperties = new WhatIfOperationProperties(); + } + this.innerProperties().withPotentialChanges(potentialChanges); + return this; + } + + /** + * Get the diagnostics property: List of resource diagnostics detected by What-If operation. + * + * @return the diagnostics value. + */ + public List diagnostics() { + return this.innerProperties() == null ? null : this.innerProperties().diagnostics(); + } + /** * Validates the instance. * diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ResourceManagementClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ResourceManagementClientImpl.java index 8ddf9fa36516..dd98082f1df1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ResourceManagementClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/ResourceManagementClientImpl.java @@ -239,7 +239,7 @@ public DeploymentOperationsClient getDeploymentOperations() { this.defaultPollInterval = defaultPollInterval; this.subscriptionId = subscriptionId; this.endpoint = endpoint; - this.apiVersion = "2024-03-01"; + this.apiVersion = "2024-11-01"; this.operations = new OperationsClientImpl(this); this.deployments = new DeploymentsClientImpl(this); this.providers = new ProvidersClientImpl(this); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/TagOperationsClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/TagOperationsClientImpl.java index f757e18b1911..ac39c59de987 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/TagOperationsClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/implementation/TagOperationsClientImpl.java @@ -34,8 +34,8 @@ import com.azure.core.util.polling.SyncPoller; import com.azure.resourcemanager.resources.fluent.TagOperationsClient; import com.azure.resourcemanager.resources.fluent.models.TagDetailsInner; -import com.azure.resourcemanager.resources.fluent.models.TagsResourceInner; import com.azure.resourcemanager.resources.fluent.models.TagValueInner; +import com.azure.resourcemanager.resources.fluent.models.TagsResourceInner; import com.azure.resourcemanager.resources.models.TagsListResult; import com.azure.resourcemanager.resources.models.TagsPatchResource; import java.nio.ByteBuffer; diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/AzureResourceBase.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/AzureResourceBase.java index a66d177c8a5e..3efeb6d1dde1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/AzureResourceBase.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/AzureResourceBase.java @@ -23,9 +23,9 @@ public class AzureResourceBase extends ProxyResource { private SystemData systemData; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -33,9 +33,9 @@ public class AzureResourceBase extends ProxyResource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of AzureResourceBase class. @@ -64,13 +64,13 @@ AzureResourceBase withSystemData(SystemData systemData) { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -84,13 +84,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/DeploymentDiagnosticsDefinition.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/DeploymentDiagnosticsDefinition.java new file mode 100644 index 000000000000..ce949f1038a0 --- /dev/null +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/DeploymentDiagnosticsDefinition.java @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.resources.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; +import java.util.List; + +/** + * The DeploymentDiagnosticsDefinition model. + */ +@Immutable +public final class DeploymentDiagnosticsDefinition implements JsonSerializable { + /* + * Denotes the additional response level. + */ + private Level level; + + /* + * The error code. + */ + private String code; + + /* + * The error message. + */ + private String message; + + /* + * The error target. + */ + private String target; + + /* + * The error additional info. + */ + private List additionalInfo; + + /** + * Creates an instance of DeploymentDiagnosticsDefinition class. + */ + public DeploymentDiagnosticsDefinition() { + } + + /** + * Get the level property: Denotes the additional response level. + * + * @return the level value. + */ + public Level level() { + return this.level; + } + + /** + * Get the code property: The error code. + * + * @return the code value. + */ + public String code() { + return this.code; + } + + /** + * Get the message property: The error message. + * + * @return the message value. + */ + public String message() { + return this.message; + } + + /** + * Get the target property: The error target. + * + * @return the target value. + */ + public String target() { + return this.target; + } + + /** + * Get the additionalInfo property: The error additional info. + * + * @return the additionalInfo value. + */ + public List additionalInfo() { + return this.additionalInfo; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (additionalInfo() != null) { + additionalInfo().forEach(e -> e.validate()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of DeploymentDiagnosticsDefinition from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of DeploymentDiagnosticsDefinition 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 DeploymentDiagnosticsDefinition. + */ + public static DeploymentDiagnosticsDefinition fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + DeploymentDiagnosticsDefinition deserializedDeploymentDiagnosticsDefinition + = new DeploymentDiagnosticsDefinition(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("level".equals(fieldName)) { + deserializedDeploymentDiagnosticsDefinition.level = Level.fromString(reader.getString()); + } else if ("code".equals(fieldName)) { + deserializedDeploymentDiagnosticsDefinition.code = reader.getString(); + } else if ("message".equals(fieldName)) { + deserializedDeploymentDiagnosticsDefinition.message = reader.getString(); + } else if ("target".equals(fieldName)) { + deserializedDeploymentDiagnosticsDefinition.target = reader.getString(); + } else if ("additionalInfo".equals(fieldName)) { + List additionalInfo + = reader.readArray(reader1 -> ErrorAdditionalInfo.fromJson(reader1)); + deserializedDeploymentDiagnosticsDefinition.additionalInfo = additionalInfo; + } else { + reader.skipChildren(); + } + } + + return deserializedDeploymentDiagnosticsDefinition; + }); + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/DeploymentProperties.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/DeploymentProperties.java index 274180bb102e..7f4f832268be 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/DeploymentProperties.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/DeploymentProperties.java @@ -68,6 +68,11 @@ public class DeploymentProperties implements JsonSerializable { /* * Denotes the state of provisioning. @@ -106,6 +106,16 @@ public final class DeploymentPropertiesExtended implements JsonSerializable diagnostics; + + /* + * The validation level of the deployment + */ + private ValidationLevel validationLevel; + /** * Creates an instance of DeploymentPropertiesExtended class. */ @@ -265,6 +275,35 @@ public ManagementError error() { return this.error; } + /** + * Get the diagnostics property: Contains diagnostic information collected during validation process. + * + * @return the diagnostics value. + */ + public List diagnostics() { + return this.diagnostics; + } + + /** + * Get the validationLevel property: The validation level of the deployment. + * + * @return the validationLevel value. + */ + public ValidationLevel validationLevel() { + return this.validationLevel; + } + + /** + * Set the validationLevel property: The validation level of the deployment. + * + * @param validationLevel the validationLevel value to set. + * @return the DeploymentPropertiesExtended object itself. + */ + public DeploymentPropertiesExtended withValidationLevel(ValidationLevel validationLevel) { + this.validationLevel = validationLevel; + return this; + } + /** * Validates the instance. * @@ -295,6 +334,9 @@ public void validate() { if (validatedResources() != null) { validatedResources().forEach(e -> e.validate()); } + if (diagnostics() != null) { + diagnostics().forEach(e -> e.validate()); + } } /** @@ -303,6 +345,8 @@ public void validate() { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("validationLevel", + this.validationLevel == null ? null : this.validationLevel.toString()); return jsonWriter.writeEndObject(); } @@ -364,6 +408,13 @@ public static DeploymentPropertiesExtended fromJson(JsonReader jsonReader) throw deserializedDeploymentPropertiesExtended.validatedResources = validatedResources; } else if ("error".equals(fieldName)) { deserializedDeploymentPropertiesExtended.error = ManagementError.fromJson(reader); + } else if ("diagnostics".equals(fieldName)) { + List diagnostics + = reader.readArray(reader1 -> DeploymentDiagnosticsDefinition.fromJson(reader1)); + deserializedDeploymentPropertiesExtended.diagnostics = diagnostics; + } else if ("validationLevel".equals(fieldName)) { + deserializedDeploymentPropertiesExtended.validationLevel + = ValidationLevel.fromString(reader.getString()); } else { reader.skipChildren(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/DeploymentWhatIfProperties.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/DeploymentWhatIfProperties.java index 44ceefb76f2c..d9eaf7a8d762 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/DeploymentWhatIfProperties.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/DeploymentWhatIfProperties.java @@ -5,6 +5,7 @@ package com.azure.resourcemanager.resources.models; import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; @@ -120,6 +121,15 @@ public DeploymentWhatIfProperties withOnErrorDeployment(OnErrorDeployment onErro return this; } + /** + * {@inheritDoc} + */ + @Override + public DeploymentWhatIfProperties withValidationLevel(ValidationLevel validationLevel) { + super.withValidationLevel(validationLevel); + return this; + } + /** * Validates the instance. * @@ -127,12 +137,40 @@ public DeploymentWhatIfProperties withOnErrorDeployment(OnErrorDeployment onErro */ @Override public void validate() { - super.validate(); if (whatIfSettings() != null) { whatIfSettings().validate(); } + if (templateLink() != null) { + templateLink().validate(); + } + if (parameters() != null) { + parameters().values().forEach(e -> { + if (e != null) { + e.validate(); + } + }); + } + if (parametersLink() != null) { + parametersLink().validate(); + } + if (mode() == null) { + throw LOGGER.atError() + .log( + new IllegalArgumentException("Missing required property mode in model DeploymentWhatIfProperties")); + } + if (debugSetting() != null) { + debugSetting().validate(); + } + if (onErrorDeployment() != null) { + onErrorDeployment().validate(); + } + if (expressionEvaluationOptions() != null) { + expressionEvaluationOptions().validate(); + } } + private static final ClientLogger LOGGER = new ClientLogger(DeploymentWhatIfProperties.class); + /** * {@inheritDoc} */ @@ -147,6 +185,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeJsonField("debugSetting", debugSetting()); jsonWriter.writeJsonField("onErrorDeployment", onErrorDeployment()); jsonWriter.writeJsonField("expressionEvaluationOptions", expressionEvaluationOptions()); + jsonWriter.writeStringField("validationLevel", validationLevel() == null ? null : validationLevel().toString()); jsonWriter.writeJsonField("whatIfSettings", this.whatIfSettings); return jsonWriter.writeEndObject(); } @@ -186,6 +225,9 @@ public static DeploymentWhatIfProperties fromJson(JsonReader jsonReader) throws } else if ("expressionEvaluationOptions".equals(fieldName)) { deserializedDeploymentWhatIfProperties .withExpressionEvaluationOptions(ExpressionEvaluationOptions.fromJson(reader)); + } else if ("validationLevel".equals(fieldName)) { + deserializedDeploymentWhatIfProperties + .withValidationLevel(ValidationLevel.fromString(reader.getString())); } else if ("whatIfSettings".equals(fieldName)) { deserializedDeploymentWhatIfProperties.whatIfSettings = DeploymentWhatIfSettings.fromJson(reader); } else { diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ErrorAdditionalInfo.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ErrorAdditionalInfo.java new file mode 100644 index 000000000000..a4f1b8dc017f --- /dev/null +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ErrorAdditionalInfo.java @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.resources.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 resource management error additional info. + */ +@Immutable +public final class ErrorAdditionalInfo implements JsonSerializable { + /* + * The additional info type. + */ + private String type; + + /* + * The additional info. + */ + private Object info; + + /** + * Creates an instance of ErrorAdditionalInfo class. + */ + public ErrorAdditionalInfo() { + } + + /** + * Get the type property: The additional info type. + * + * @return the type value. + */ + public String type() { + return this.type; + } + + /** + * Get the info property: The additional info. + * + * @return the info value. + */ + public Object info() { + return this.info; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ErrorAdditionalInfo from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ErrorAdditionalInfo 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 ErrorAdditionalInfo. + */ + public static ErrorAdditionalInfo fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ErrorAdditionalInfo deserializedErrorAdditionalInfo = new ErrorAdditionalInfo(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("type".equals(fieldName)) { + deserializedErrorAdditionalInfo.type = reader.getString(); + } else if ("info".equals(fieldName)) { + deserializedErrorAdditionalInfo.info = reader.readUntyped(); + } else { + reader.skipChildren(); + } + } + + return deserializedErrorAdditionalInfo; + }); + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Level.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Level.java new file mode 100644 index 000000000000..b67176ab18eb --- /dev/null +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/Level.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. + +package com.azure.resourcemanager.resources.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Denotes the additional response level. + */ +public final class Level extends ExpandableStringEnum { + /** + * Static value Warning for Level. + */ + public static final Level WARNING = fromString("Warning"); + + /** + * Static value Info for Level. + */ + public static final Level INFO = fromString("Info"); + + /** + * Static value Error for Level. + */ + public static final Level ERROR = fromString("Error"); + + /** + * Creates a new instance of Level value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public Level() { + } + + /** + * Creates or finds a Level from its string representation. + * + * @param name a name to look for. + * @return the corresponding Level. + */ + public static Level fromString(String name) { + return fromString(name, Level.class); + } + + /** + * Gets known Level values. + * + * @return known Level values. + */ + public static Collection values() { + return values(Level.class); + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ManagedResourceReference.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ManagedResourceReference.java index 019a96e0a4b5..920f65684532 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ManagedResourceReference.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ManagedResourceReference.java @@ -93,7 +93,6 @@ public String id() { */ @Override public void validate() { - super.validate(); } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ResourceReference.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ResourceReference.java index d426ef4c736b..e39774f72740 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ResourceReference.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ResourceReference.java @@ -29,7 +29,7 @@ public ResourceReference() { /** * Get the id property: The fully qualified resource Id. - * + * * @return the id value. */ public String id() { @@ -38,7 +38,7 @@ public String id() { /** * Validates the instance. - * + * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { @@ -55,7 +55,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of ResourceReference from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of ResourceReference if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ResourceReferenceExtended.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ResourceReferenceExtended.java index 7c0a4e5200d0..e14356a8b7f9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ResourceReferenceExtended.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ResourceReferenceExtended.java @@ -69,7 +69,6 @@ public String id() { */ @Override public void validate() { - super.validate(); } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ValidationLevel.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ValidationLevel.java new file mode 100644 index 000000000000..a9e313edfb9e --- /dev/null +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/ValidationLevel.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. + +package com.azure.resourcemanager.resources.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The level of validation performed on the deployment. + */ +public final class ValidationLevel extends ExpandableStringEnum { + /** + * Static value Template for ValidationLevel. + */ + public static final ValidationLevel TEMPLATE = fromString("Template"); + + /** + * Static value Provider for ValidationLevel. + */ + public static final ValidationLevel PROVIDER = fromString("Provider"); + + /** + * Static value ProviderNoRbac for ValidationLevel. + */ + public static final ValidationLevel PROVIDER_NO_RBAC = fromString("ProviderNoRbac"); + + /** + * Creates a new instance of ValidationLevel value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public ValidationLevel() { + } + + /** + * Creates or finds a ValidationLevel from its string representation. + * + * @param name a name to look for. + * @return the corresponding ValidationLevel. + */ + public static ValidationLevel fromString(String name) { + return fromString(name, ValidationLevel.class); + } + + /** + * Gets known ValidationLevel values. + * + * @return known ValidationLevel values. + */ + public static Collection values() { + return values(ValidationLevel.class); + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/WhatIfChange.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/WhatIfChange.java index c233828b0773..f752c199719a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/WhatIfChange.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/WhatIfChange.java @@ -23,6 +23,22 @@ public final class WhatIfChange implements JsonSerializable { */ private String resourceId; + /* + * The resource id of the Deployment responsible for this change. + */ + private String deploymentId; + + /* + * The symbolic name of the resource responsible for this change. + */ + private String symbolicName; + + /* + * A subset of properties that uniquely identify a Bicep extensible resource because it lacks a resource id like an + * Azure resource has. + */ + private Object identifiers; + /* * Type of change that will be made to the resource when the deployment is executed. */ @@ -74,6 +90,68 @@ public WhatIfChange withResourceId(String resourceId) { return this; } + /** + * Get the deploymentId property: The resource id of the Deployment responsible for this change. + * + * @return the deploymentId value. + */ + public String deploymentId() { + return this.deploymentId; + } + + /** + * Set the deploymentId property: The resource id of the Deployment responsible for this change. + * + * @param deploymentId the deploymentId value to set. + * @return the WhatIfChange object itself. + */ + public WhatIfChange withDeploymentId(String deploymentId) { + this.deploymentId = deploymentId; + return this; + } + + /** + * Get the symbolicName property: The symbolic name of the resource responsible for this change. + * + * @return the symbolicName value. + */ + public String symbolicName() { + return this.symbolicName; + } + + /** + * Set the symbolicName property: The symbolic name of the resource responsible for this change. + * + * @param symbolicName the symbolicName value to set. + * @return the WhatIfChange object itself. + */ + public WhatIfChange withSymbolicName(String symbolicName) { + this.symbolicName = symbolicName; + return this; + } + + /** + * Get the identifiers property: A subset of properties that uniquely identify a Bicep extensible resource because + * it lacks a resource id like an Azure resource has. + * + * @return the identifiers value. + */ + public Object identifiers() { + return this.identifiers; + } + + /** + * Set the identifiers property: A subset of properties that uniquely identify a Bicep extensible resource because + * it lacks a resource id like an Azure resource has. + * + * @param identifiers the identifiers value to set. + * @return the WhatIfChange object itself. + */ + public WhatIfChange withIdentifiers(Object identifiers) { + this.identifiers = identifiers; + return this; + } + /** * Get the changeType property: Type of change that will be made to the resource when the deployment is executed. * @@ -203,6 +281,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("resourceId", this.resourceId); jsonWriter.writeStringField("changeType", this.changeType == null ? null : this.changeType.toString()); + jsonWriter.writeStringField("deploymentId", this.deploymentId); + jsonWriter.writeStringField("symbolicName", this.symbolicName); + jsonWriter.writeUntypedField("identifiers", this.identifiers); jsonWriter.writeStringField("unsupportedReason", this.unsupportedReason); jsonWriter.writeUntypedField("before", this.before); jsonWriter.writeUntypedField("after", this.after); @@ -230,6 +311,12 @@ public static WhatIfChange fromJson(JsonReader jsonReader) throws IOException { deserializedWhatIfChange.resourceId = reader.getString(); } else if ("changeType".equals(fieldName)) { deserializedWhatIfChange.changeType = ChangeType.fromString(reader.getString()); + } else if ("deploymentId".equals(fieldName)) { + deserializedWhatIfChange.deploymentId = reader.getString(); + } else if ("symbolicName".equals(fieldName)) { + deserializedWhatIfChange.symbolicName = reader.getString(); + } else if ("identifiers".equals(fieldName)) { + deserializedWhatIfChange.identifiers = reader.readUntyped(); } else if ("unsupportedReason".equals(fieldName)) { deserializedWhatIfChange.unsupportedReason = reader.getString(); } else if ("before".equals(fieldName)) { diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources/proxy-config.json b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources/proxy-config.json index ccbedca6ffc5..b5127bca0ad9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources/proxy-config.json +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources/proxy-config.json @@ -1 +1 @@ -[ [ "com.azure.resourcemanager.resources.implementation.DeploymentOperationsClientImpl$DeploymentOperationsService" ], [ "com.azure.resourcemanager.resources.implementation.DeploymentsClientImpl$DeploymentsService" ], [ "com.azure.resourcemanager.resources.implementation.OperationsClientImpl$OperationsService" ], [ "com.azure.resourcemanager.resources.implementation.ProviderResourceTypesClientImpl$ProviderResourceTypesService" ], [ "com.azure.resourcemanager.resources.implementation.ProvidersClientImpl$ProvidersService" ], [ "com.azure.resourcemanager.resources.implementation.ResourceGroupsClientImpl$ResourceGroupsService" ], [ "com.azure.resourcemanager.resources.implementation.ResourcesClientImpl$ResourcesService" ], [ "com.azure.resourcemanager.resources.implementation.TagOperationsClientImpl$TagOperationsService" ] ] \ No newline at end of file +[["com.azure.resourcemanager.resources.implementation.DeploymentOperationsClientImpl$DeploymentOperationsService"],["com.azure.resourcemanager.resources.implementation.DeploymentsClientImpl$DeploymentsService"],["com.azure.resourcemanager.resources.implementation.OperationsClientImpl$OperationsService"],["com.azure.resourcemanager.resources.implementation.ProviderResourceTypesClientImpl$ProviderResourceTypesService"],["com.azure.resourcemanager.resources.implementation.ProvidersClientImpl$ProvidersService"],["com.azure.resourcemanager.resources.implementation.ResourceGroupsClientImpl$ResourceGroupsService"],["com.azure.resourcemanager.resources.implementation.ResourcesClientImpl$ResourcesService"],["com.azure.resourcemanager.resources.implementation.TagOperationsClientImpl$TagOperationsService"]] \ No newline at end of file diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources/reflect-config.json b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources/reflect-config.json index 8878e547a798..811392535404 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources/reflect-config.json +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources/reflect-config.json @@ -1 +1 @@ -[ ] \ No newline at end of file +[{"name":"com.azure.resourcemanager.resources.models.ErrorAdditionalInfo","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true}] \ No newline at end of file diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_change/proxy-config.json b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_change/proxy-config.json index 51cb2139a1ef..3575864f459c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_change/proxy-config.json +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_change/proxy-config.json @@ -1 +1 @@ -[ [ "com.azure.resourcemanager.resources.implementation.ChangesClientImpl$ChangesService" ] ] \ No newline at end of file +[["com.azure.resourcemanager.resources.implementation.ChangesClientImpl$ChangesService"]] \ No newline at end of file diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_change/reflect-config.json b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_change/reflect-config.json index 8878e547a798..0637a088a01e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_change/reflect-config.json +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_change/reflect-config.json @@ -1 +1 @@ -[ ] \ No newline at end of file +[] \ No newline at end of file diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_deploymentstacks/proxy-config.json b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_deploymentstacks/proxy-config.json index 01dd44023432..ba55e501ce2c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_deploymentstacks/proxy-config.json +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_deploymentstacks/proxy-config.json @@ -1 +1 @@ -[ [ "com.azure.resourcemanager.resources.implementation.DeploymentStacksClientImpl$DeploymentStacksService" ] ] \ No newline at end of file +[["com.azure.resourcemanager.resources.implementation.DeploymentStacksClientImpl$DeploymentStacksService"]] \ No newline at end of file diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_deploymentstacks/reflect-config.json b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_deploymentstacks/reflect-config.json index 50d6c81cf1ec..70dbd6192c6f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_deploymentstacks/reflect-config.json +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_deploymentstacks/reflect-config.json @@ -1,81 +1 @@ -[ { - "name" : "com.azure.resourcemanager.resources.fluent.models.DeploymentStackInner", - "allDeclaredConstructors" : true, - "allDeclaredFields" : true, - "allDeclaredMethods" : true -}, { - "name" : "com.azure.resourcemanager.resources.fluent.models.DeploymentStackProperties", - "allDeclaredConstructors" : true, - "allDeclaredFields" : true, - "allDeclaredMethods" : true -}, { - "name" : "com.azure.resourcemanager.resources.fluent.models.DeploymentStackValidateResultInner", - "allDeclaredConstructors" : true, - "allDeclaredFields" : true, - "allDeclaredMethods" : true -}, { - "name" : "com.azure.resourcemanager.resources.models.ActionOnUnmanage", - "allDeclaredConstructors" : true, - "allDeclaredFields" : true, - "allDeclaredMethods" : true -}, { - "name" : "com.azure.resourcemanager.resources.models.AzureResourceBase", - "allDeclaredConstructors" : true, - "allDeclaredFields" : true, - "allDeclaredMethods" : true -}, { - "name" : "com.azure.resourcemanager.resources.models.DenySettings", - "allDeclaredConstructors" : true, - "allDeclaredFields" : true, - "allDeclaredMethods" : true -}, { - "name" : "com.azure.resourcemanager.resources.models.DeploymentParameter", - "allDeclaredConstructors" : true, - "allDeclaredFields" : true, - "allDeclaredMethods" : true -}, { - "name" : "com.azure.resourcemanager.resources.models.DeploymentStackValidateProperties", - "allDeclaredConstructors" : true, - "allDeclaredFields" : true, - "allDeclaredMethods" : true -}, { - "name" : "com.azure.resourcemanager.resources.models.DeploymentStacksDebugSetting", - "allDeclaredConstructors" : true, - "allDeclaredFields" : true, - "allDeclaredMethods" : true -}, { - "name" : "com.azure.resourcemanager.resources.models.DeploymentStacksParametersLink", - "allDeclaredConstructors" : true, - "allDeclaredFields" : true, - "allDeclaredMethods" : true -}, { - "name" : "com.azure.resourcemanager.resources.models.DeploymentStacksTemplateLink", - "allDeclaredConstructors" : true, - "allDeclaredFields" : true, - "allDeclaredMethods" : true -}, { - "name" : "com.azure.resourcemanager.resources.models.KeyVaultParameterReference", - "allDeclaredConstructors" : true, - "allDeclaredFields" : true, - "allDeclaredMethods" : true -}, { - "name" : "com.azure.resourcemanager.resources.models.KeyVaultReference", - "allDeclaredConstructors" : true, - "allDeclaredFields" : true, - "allDeclaredMethods" : true -}, { - "name" : "com.azure.resourcemanager.resources.models.ManagedResourceReference", - "allDeclaredConstructors" : true, - "allDeclaredFields" : true, - "allDeclaredMethods" : true -}, { - "name" : "com.azure.resourcemanager.resources.models.ResourceReference", - "allDeclaredConstructors" : true, - "allDeclaredFields" : true, - "allDeclaredMethods" : true -}, { - "name" : "com.azure.resourcemanager.resources.models.ResourceReferenceExtended", - "allDeclaredConstructors" : true, - "allDeclaredFields" : true, - "allDeclaredMethods" : true -} ] \ No newline at end of file +[{"name":"com.azure.resourcemanager.resources.fluent.models.DeploymentStackInner","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.resources.fluent.models.DeploymentStackProperties","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.resources.fluent.models.DeploymentStackValidateResultInner","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.resources.models.ActionOnUnmanage","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.resources.models.AzureResourceBase","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.resources.models.DenySettings","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.resources.models.DeploymentParameter","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.resources.models.DeploymentStackValidateProperties","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.resources.models.DeploymentStacksDebugSetting","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.resources.models.DeploymentStacksParametersLink","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.resources.models.DeploymentStacksTemplateLink","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.resources.models.KeyVaultParameterReference","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.resources.models.KeyVaultReference","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.resources.models.ManagedResourceReference","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.resources.models.ResourceReference","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true},{"name":"com.azure.resourcemanager.resources.models.ResourceReferenceExtended","allDeclaredConstructors":true,"allDeclaredFields":true,"allDeclaredMethods":true}] \ No newline at end of file diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_feature/proxy-config.json b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_feature/proxy-config.json index ceb4cab09a86..afdf8e1e226e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_feature/proxy-config.json +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_feature/proxy-config.json @@ -1 +1 @@ -[ [ "com.azure.resourcemanager.resources.implementation.FeatureClientImpl$FeatureClientService" ], [ "com.azure.resourcemanager.resources.implementation.FeaturesClientImpl$FeaturesService" ], [ "com.azure.resourcemanager.resources.implementation.SubscriptionFeatureRegistrationsClientImpl$SubscriptionFeatureRegistrationsService" ] ] \ No newline at end of file +[["com.azure.resourcemanager.resources.implementation.FeatureClientImpl$FeatureClientService"],["com.azure.resourcemanager.resources.implementation.FeaturesClientImpl$FeaturesService"],["com.azure.resourcemanager.resources.implementation.SubscriptionFeatureRegistrationsClientImpl$SubscriptionFeatureRegistrationsService"]] \ No newline at end of file diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_feature/reflect-config.json b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_feature/reflect-config.json index 8878e547a798..0637a088a01e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_feature/reflect-config.json +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_feature/reflect-config.json @@ -1 +1 @@ -[ ] \ No newline at end of file +[] \ No newline at end of file diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_lock/proxy-config.json b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_lock/proxy-config.json index 79a052c44458..a6bfb559853d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_lock/proxy-config.json +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_lock/proxy-config.json @@ -1 +1 @@ -[ [ "com.azure.resourcemanager.resources.implementation.AuthorizationOperationsClientImpl$AuthorizationOperationsService" ], [ "com.azure.resourcemanager.resources.implementation.ManagementLocksClientImpl$ManagementLocksService" ] ] \ No newline at end of file +[["com.azure.resourcemanager.resources.implementation.AuthorizationOperationsClientImpl$AuthorizationOperationsService"],["com.azure.resourcemanager.resources.implementation.ManagementLocksClientImpl$ManagementLocksService"]] \ No newline at end of file diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_lock/reflect-config.json b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_lock/reflect-config.json index 8878e547a798..0637a088a01e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_lock/reflect-config.json +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_lock/reflect-config.json @@ -1 +1 @@ -[ ] \ No newline at end of file +[] \ No newline at end of file diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_policy/proxy-config.json b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_policy/proxy-config.json index 9ff91bf2de1a..d2feb5b32544 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_policy/proxy-config.json +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_policy/proxy-config.json @@ -1 +1 @@ -[ [ "com.azure.resourcemanager.resources.implementation.DataPolicyManifestsClientImpl$DataPolicyManifestsService" ], [ "com.azure.resourcemanager.resources.implementation.PolicyAssignmentsClientImpl$PolicyAssignmentsService" ], [ "com.azure.resourcemanager.resources.implementation.PolicyDefinitionsClientImpl$PolicyDefinitionsService" ], [ "com.azure.resourcemanager.resources.implementation.PolicyExemptionsClientImpl$PolicyExemptionsService" ], [ "com.azure.resourcemanager.resources.implementation.PolicySetDefinitionsClientImpl$PolicySetDefinitionsService" ] ] \ No newline at end of file +[["com.azure.resourcemanager.resources.implementation.DataPolicyManifestsClientImpl$DataPolicyManifestsService"],["com.azure.resourcemanager.resources.implementation.PolicyAssignmentsClientImpl$PolicyAssignmentsService"],["com.azure.resourcemanager.resources.implementation.PolicyDefinitionsClientImpl$PolicyDefinitionsService"],["com.azure.resourcemanager.resources.implementation.PolicyExemptionsClientImpl$PolicyExemptionsService"],["com.azure.resourcemanager.resources.implementation.PolicySetDefinitionsClientImpl$PolicySetDefinitionsService"]] \ No newline at end of file diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_policy/reflect-config.json b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_policy/reflect-config.json index 8878e547a798..0637a088a01e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_policy/reflect-config.json +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_policy/reflect-config.json @@ -1 +1 @@ -[ ] \ No newline at end of file +[] \ No newline at end of file diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_subscription/proxy-config.json b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_subscription/proxy-config.json index 2ceb14c9b2cb..0a7da80e50d0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_subscription/proxy-config.json +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_subscription/proxy-config.json @@ -1 +1 @@ -[ [ "com.azure.resourcemanager.resources.implementation.ResourceNamesClientImpl$ResourceNamesService" ], [ "com.azure.resourcemanager.resources.implementation.SubscriptionsClientImpl$SubscriptionsService" ], [ "com.azure.resourcemanager.resources.implementation.TenantsClientImpl$TenantsService" ] ] \ No newline at end of file +[["com.azure.resourcemanager.resources.implementation.ResourceNamesClientImpl$ResourceNamesService"],["com.azure.resourcemanager.resources.implementation.SubscriptionsClientImpl$SubscriptionsService"],["com.azure.resourcemanager.resources.implementation.TenantsClientImpl$TenantsService"]] \ No newline at end of file diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_subscription/reflect-config.json b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_subscription/reflect-config.json index 8878e547a798..0637a088a01e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_subscription/reflect-config.json +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/main/resources/META-INF/native-image/com.azure.resourcemanager/azure-resourcemanager-resources_subscription/reflect-config.json @@ -1 +1 @@ -[ ] \ No newline at end of file +[] \ No newline at end of file diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/samples/java/com/azure/resourcemanager/resources/ReadmeSamples.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/samples/java/com/azure/resourcemanager/resources/ReadmeSamples.java index d46db1952465..5bbdcec071fb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/samples/java/com/azure/resourcemanager/resources/ReadmeSamples.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/samples/java/com/azure/resourcemanager/resources/ReadmeSamples.java @@ -4,8 +4,8 @@ package com.azure.resourcemanager.resources; import com.azure.core.credential.TokenCredential; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; /** @@ -15,7 +15,7 @@ public class ReadmeSamples { public void authenticate() { // BEGIN: readme-sample-authenticate - AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/DeploymentStacksTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/DeploymentStacksTests.java index ea0ba5013049..ca77e3ffe959 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/DeploymentStacksTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/DeploymentStacksTests.java @@ -6,18 +6,20 @@ import com.azure.core.http.HttpPipeline; import com.azure.core.management.Region; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.util.BinaryData; import com.azure.resourcemanager.resources.fluent.models.DeploymentStackInner; import com.azure.resourcemanager.resources.models.ActionOnUnmanage; import com.azure.resourcemanager.resources.models.DenySettings; import com.azure.resourcemanager.resources.models.DenySettingsMode; +import com.azure.resourcemanager.resources.models.DeploymentParameter; import com.azure.resourcemanager.resources.models.DeploymentStacksDeleteDetachEnum; -import com.azure.resourcemanager.resources.models.DeploymentStacksParametersLink; -import com.azure.resourcemanager.resources.models.DeploymentStacksTemplateLink; import com.azure.resourcemanager.resources.models.ResourceGroups; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.Collections; +import java.util.HashMap; +import java.util.Map; public class DeploymentStacksTests extends ResourceManagementTest { @@ -51,18 +53,21 @@ protected void cleanUpResources() { public void testDeploymentStacks() { final String dpName = "dpA" + testId; + Object template + = BinaryData.fromStream(DeploymentStacksTests.class.getResourceAsStream("/vnetTwoSubnetsTemplate.json")) + .toObject(Object.class); + Map templateParameters = new HashMap<>(); + DeploymentStackInner deploymentStack = resourceClient.deploymentStackClient() .getDeploymentStacks() - .createOrUpdateAtResourceGroup(rgName, dpName, new DeploymentStackInner() - .withTags(Collections.singletonMap("usage", "test")) - .withTemplateLink( - new DeploymentStacksTemplateLink().withUri(TEMPLATE_URI).withContentVersion(CONTENT_VERSION)) - .withParametersLink( - new DeploymentStacksParametersLink().withUri(PARAMETERS_URI).withContentVersion(CONTENT_VERSION)) - .withActionOnUnmanage(new ActionOnUnmanage().withResources(DeploymentStacksDeleteDetachEnum.DELETE) - .withResourceGroups(DeploymentStacksDeleteDetachEnum.DETACH) - .withManagementGroups(DeploymentStacksDeleteDetachEnum.DETACH)) - .withDenySettings(new DenySettings().withMode(DenySettingsMode.NONE))); + .createOrUpdateAtResourceGroup(rgName, dpName, + new DeploymentStackInner().withTags(Collections.singletonMap("usage", "test")) + .withTemplate(template) + .withParameters(templateParameters) + .withActionOnUnmanage(new ActionOnUnmanage().withResources(DeploymentStacksDeleteDetachEnum.DELETE) + .withResourceGroups(DeploymentStacksDeleteDetachEnum.DETACH) + .withManagementGroups(DeploymentStacksDeleteDetachEnum.DETACH)) + .withDenySettings(new DenySettings().withMode(DenySettingsMode.NONE))); Assertions.assertEquals(dpName, deploymentStack.name()); Assertions.assertEquals(DeploymentStacksDeleteDetachEnum.DELETE, diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/ProvidersTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/ProvidersTests.java index 9914dcab6856..c0ad88b5d913 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/ProvidersTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/ProvidersTests.java @@ -34,10 +34,11 @@ public void canUnregisterAndRegisterProvider() { List resourceTypes = provider.resourceTypes(); Assertions.assertFalse(resourceTypes.isEmpty()); Assertions.assertNotNull(provider); + boolean providerAlreadyRegistered = false; if ("Registered".equals(provider.registrationState())) { - Assertions.fail(String.format( - "Provider '%s' already registered, please test with a provider that not currently registered.", - providerNamespace)); + providerAlreadyRegistered = true; + // unregister it first + unregisterProvider(provider); } // register @@ -49,6 +50,12 @@ public void canUnregisterAndRegisterProvider() { } Assertions.assertEquals("Registered", provider.registrationState()); + if (!providerAlreadyRegistered) { + unregisterProvider(provider); + } + } + + private void unregisterProvider(Provider provider) { // unregister resourceClient.providers().unregister(provider.namespace()); provider = resourceClient.providers().getByName(provider.namespace()); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/AzureConfigurableTests.java b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/AzureConfigurableTests.java index 6f9ff25f353a..7872a678c83d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/AzureConfigurableTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/java/com/azure/resourcemanager/resources/fluentcore/AzureConfigurableTests.java @@ -11,8 +11,8 @@ import com.azure.core.http.policy.RetryOptions; import com.azure.core.http.policy.RetryPolicy; import com.azure.core.http.policy.RetryStrategy; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.http.MockHttpResponse; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.resources.ResourceManager; @@ -32,7 +32,7 @@ public void testRetryOptions() throws NoSuchFieldException, IllegalAccessExcepti ResourceManager resourceManager = ResourceManager.configure() .withRetryOptions(new RetryOptions(new FixedDelayOptions(3, Duration.ofSeconds(1)))) .withHttpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .authenticate(new DefaultAzureCredentialBuilder().build(), new AzureProfile(AzureEnvironment.AZURE)) + .authenticate(new DefaultAzureCredentialBuilder().build(), new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD)) .withSubscription(Mockito.anyString()); HttpPipeline httpPipeline = resourceManager.genericResources().manager().httpPipeline(); @@ -41,7 +41,7 @@ public void testRetryOptions() throws NoSuchFieldException, IllegalAccessExcepti // Default is RetryPolicy with ExponentialBackoff resourceManager = ResourceManager.configure() .withHttpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .authenticate(new DefaultAzureCredentialBuilder().build(), new AzureProfile(AzureEnvironment.AZURE)) + .authenticate(new DefaultAzureCredentialBuilder().build(), new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD)) .withSubscription(Mockito.anyString()); httpPipeline = resourceManager.genericResources().manager().httpPipeline(); @@ -49,7 +49,7 @@ public void testRetryOptions() throws NoSuchFieldException, IllegalAccessExcepti resourceManager = ResourceManager.configure() .withHttpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .authenticate(new DefaultAzureCredentialBuilder().build(), new AzureProfile(AzureEnvironment.AZURE)) + .authenticate(new DefaultAzureCredentialBuilder().build(), new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD)) .withSubscription(Mockito.anyString()); httpPipeline = resourceManager.genericResources().manager().httpPipeline(); diff --git a/sdk/resourcemanager/azure-resourcemanager-resources/src/test/resources/vnetTwoSubnetsTemplate.json b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/resources/vnetTwoSubnetsTemplate.json new file mode 100644 index 000000000000..4cbce888ad89 --- /dev/null +++ b/sdk/resourcemanager/azure-resourcemanager-resources/src/test/resources/vnetTwoSubnetsTemplate.json @@ -0,0 +1,91 @@ +{ + "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", + "contentVersion": "1.0.0.0", + "metadata": { + "_generator": { + "name": "bicep", + "version": "0.6.18.56646", + "templateHash": "10806234693722113459" + } + }, + "parameters": { + "vnetName": { + "type": "string", + "defaultValue": "VNet1", + "metadata": { + "description": "VNet name" + } + }, + "vnetAddressPrefix": { + "type": "string", + "defaultValue": "10.0.0.0/16", + "metadata": { + "description": "Address prefix" + } + }, + "subnet1Prefix": { + "type": "string", + "defaultValue": "10.0.0.0/24", + "metadata": { + "description": "Subnet 1 Prefix" + } + }, + "subnet1Name": { + "type": "string", + "defaultValue": "Subnet1", + "metadata": { + "description": "Subnet 1 Name" + } + }, + "subnet2Prefix": { + "type": "string", + "defaultValue": "10.0.1.0/24", + "metadata": { + "description": "Subnet 2 Prefix" + } + }, + "subnet2Name": { + "type": "string", + "defaultValue": "Subnet2", + "metadata": { + "description": "Subnet 2 Name" + } + }, + "location": { + "type": "string", + "defaultValue": "[resourceGroup().location]", + "metadata": { + "description": "Location for all resources." + } + } + }, + "resources": [ + { + "type": "Microsoft.Network/virtualNetworks", + "apiVersion": "2021-08-01", + "name": "[parameters('vnetName')]", + "location": "[parameters('location')]", + "properties": { + "addressSpace": { + "addressPrefixes": [ + "[parameters('vnetAddressPrefix')]" + ] + }, + "subnets": [ + { + "name": "[parameters('subnet1Name')]", + "properties": { + "addressPrefix": "[parameters('subnet1Prefix')]" + } + }, + { + "name": "[parameters('subnet2Name')]", + "properties": { + "addressPrefix": "[parameters('subnet2Prefix')]" + } + } + ] + } + } + ] +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/README.md b/sdk/resourcemanager/azure-resourcemanager-samples/README.md index f78db6da5d58..7bfbb49580d3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/README.md +++ b/sdk/resourcemanager/azure-resourcemanager-samples/README.md @@ -17,7 +17,7 @@ For documentation on how to use this package, please see [Azure Management Libra com.azure.resourcemanager azure-resourcemanager - 2.46.0 + 2.49.0-beta.1 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/pom.xml b/sdk/resourcemanager/azure-resourcemanager-samples/pom.xml index 1265a84e822b..6ce6279621d1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-samples/pom.xml @@ -54,7 +54,7 @@ com.azure.resourcemanager azure-resourcemanager - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager @@ -64,17 +64,17 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-identity - 1.15.0 + 1.15.4 com.jcraft @@ -109,22 +109,22 @@ com.azure azure-storage-blob - 12.29.0 + 12.29.1 com.azure azure-cosmos - 4.66.0 + 4.67.0 com.azure azure-security-keyvault-certificates - 4.7.1 + 4.7.3 com.azure azure-messaging-servicebus - 7.17.8 + 7.17.9 io.fabric8 @@ -144,7 +144,7 @@ com.azure azure-security-keyvault-administration - 4.6.1 + 4.6.3 test diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appplatform/samples/ManageSpringCloud.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appplatform/samples/ManageSpringCloud.java index 6c1a0bb96b9d..cb2410b3592a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appplatform/samples/ManageSpringCloud.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appplatform/samples/ManageSpringCloud.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.Region; import com.azure.core.management.profile.AzureProfile; import com.azure.core.util.Configuration; @@ -275,7 +275,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageFunctionAppBasic.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageFunctionAppBasic.java index e8c6bd3621f7..e3c8d5205c39 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageFunctionAppBasic.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageFunctionAppBasic.java @@ -4,7 +4,7 @@ package com.azure.resourcemanager.appservice.samples; import com.azure.core.credential.TokenCredential; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.appservice.models.AppServicePlan; @@ -152,7 +152,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageFunctionAppLogs.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageFunctionAppLogs.java index a687cf2f78e9..348cc270fadb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageFunctionAppLogs.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageFunctionAppLogs.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.appservice.fluent.models.CsmPublishingCredentialsPoliciesEntityProperties; @@ -183,7 +183,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageFunctionAppWithDomainSsl.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageFunctionAppWithDomainSsl.java index a5f142355814..8faeb03a5b76 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageFunctionAppWithDomainSsl.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageFunctionAppWithDomainSsl.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.appservice.models.AppServiceDomain; @@ -191,7 +191,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxFunctionAppSourceControl.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxFunctionAppSourceControl.java index d20598f74dec..40d6162cfdd9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxFunctionAppSourceControl.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxFunctionAppSourceControl.java @@ -4,7 +4,7 @@ package com.azure.resourcemanager.appservice.samples; import com.azure.core.credential.TokenCredential; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.appservice.models.FunctionApp; @@ -149,7 +149,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppBasic.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppBasic.java index ecd96a9efd7f..2aba46727dac 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppBasic.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppBasic.java @@ -4,7 +4,7 @@ package com.azure.resourcemanager.appservice.samples; import com.azure.core.credential.TokenCredential; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.appservice.models.AppServicePlan; @@ -168,7 +168,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppCosmosDbByMsi.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppCosmosDbByMsi.java index 008f82c991c8..67887c265bf0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppCosmosDbByMsi.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppCosmosDbByMsi.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.Region; import com.azure.core.management.profile.AzureProfile; import com.azure.identity.DefaultAzureCredentialBuilder; @@ -221,7 +221,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppSqlConnection.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppSqlConnection.java index 5e3a9613b9b0..7f2b6aafe744 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppSqlConnection.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppSqlConnection.java @@ -4,7 +4,7 @@ package com.azure.resourcemanager.appservice.samples; import com.azure.core.credential.TokenCredential; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.appservice.models.PricingTier; @@ -140,7 +140,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppStorageAccountConnection.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppStorageAccountConnection.java index eb2953d984f9..a90002f296be 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppStorageAccountConnection.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppStorageAccountConnection.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.appservice.fluent.models.CsmPublishingCredentialsPoliciesEntityProperties; @@ -172,7 +172,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithContainerRegistry.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithContainerRegistry.java index 9c4413b2e66a..500b369e66c9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithContainerRegistry.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithContainerRegistry.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.appservice.models.PricingTier; @@ -185,7 +185,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithDomainSsl.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithDomainSsl.java index 150c287f83f6..ebbc8f8061da 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithDomainSsl.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithDomainSsl.java @@ -4,7 +4,7 @@ package com.azure.resourcemanager.appservice.samples; import com.azure.core.credential.TokenCredential; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.appservice.models.AppServiceDomain; @@ -192,7 +192,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithTrafficManager.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithTrafficManager.java index a26ad95c9e5c..568de96b743d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithTrafficManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithTrafficManager.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.profile.AzureProfile; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; @@ -271,7 +271,7 @@ public static void main(String[] args) { //============================================================= // Authenticate // - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppBasic.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppBasic.java index c36e7f16c3db..59f355bb1aeb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppBasic.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppBasic.java @@ -4,7 +4,7 @@ package com.azure.resourcemanager.appservice.samples; import com.azure.core.credential.TokenCredential; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.appservice.models.AppServicePlan; @@ -164,7 +164,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppCosmosDbByMsi.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppCosmosDbByMsi.java index bdee3ceff9f1..eea9ed2b9620 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppCosmosDbByMsi.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppCosmosDbByMsi.java @@ -4,7 +4,7 @@ package com.azure.resourcemanager.appservice.samples; import com.azure.core.credential.TokenCredential; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.core.management.profile.AzureProfile; @@ -184,7 +184,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppCosmosDbThroughKeyVault.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppCosmosDbThroughKeyVault.java index 56096f0aa781..f0b4e2dd795c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppCosmosDbThroughKeyVault.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppCosmosDbThroughKeyVault.java @@ -4,7 +4,7 @@ package com.azure.resourcemanager.appservice.samples; import com.azure.core.credential.TokenCredential; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; @@ -182,7 +182,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppLogs.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppLogs.java index 734c86f4194c..8e4f45195432 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppLogs.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppLogs.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.appservice.models.JavaVersion; @@ -178,7 +178,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppSlots.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppSlots.java index a30105cbe95c..a206de0ae47f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppSlots.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppSlots.java @@ -4,7 +4,7 @@ package com.azure.resourcemanager.appservice.samples; import com.azure.core.credential.TokenCredential; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.appservice.models.DeploymentSlot; @@ -98,7 +98,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppSqlConnection.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppSqlConnection.java index b53dfef2a624..f210708dd01a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppSqlConnection.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppSqlConnection.java @@ -4,7 +4,7 @@ package com.azure.resourcemanager.appservice.samples; import com.azure.core.credential.TokenCredential; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.appservice.models.PhpVersion; @@ -138,7 +138,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppStorageAccountConnection.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppStorageAccountConnection.java index 47d521733217..70dc2f16694c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppStorageAccountConnection.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppStorageAccountConnection.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.HttpClient; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.appservice.fluent.models.CsmPublishingCredentialsPoliciesEntityProperties; @@ -172,7 +172,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithAuthentication.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithAuthentication.java index 2c4b55ef1e97..6761b29edd73 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithAuthentication.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithAuthentication.java @@ -4,7 +4,7 @@ package com.azure.resourcemanager.appservice.samples; import com.azure.core.credential.TokenCredential; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.appservice.models.AppServicePlan; @@ -222,7 +222,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithDomainSsl.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithDomainSsl.java index d66ba6715704..77c41456783b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithDomainSsl.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithDomainSsl.java @@ -4,7 +4,7 @@ package com.azure.resourcemanager.appservice.samples; import com.azure.core.credential.TokenCredential; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.appservice.models.AppServiceDomain; @@ -189,7 +189,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithTrafficManager.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithTrafficManager.java index 96b63d6b7ed1..99da0a7a9f1a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithTrafficManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithTrafficManager.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.profile.AzureProfile; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; @@ -268,7 +268,7 @@ public static void main(String[] args) { //============================================================= // Authenticate // - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/authorization/samples/ManageServicePrincipalCredentials.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/authorization/samples/ManageServicePrincipalCredentials.java index 1a7362131315..22a50b6aa1cc 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/authorization/samples/ManageServicePrincipalCredentials.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/authorization/samples/ManageServicePrincipalCredentials.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.ClientCertificateCredentialBuilder; import com.azure.identity.ClientSecretCredentialBuilder; import com.azure.identity.DefaultAzureCredentialBuilder; @@ -233,7 +233,7 @@ public void accept(PasswordCredential passwordCredential) { */ public static void main(String[] args) { try { - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/authorization/samples/ManageUsersGroupsAndRoles.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/authorization/samples/ManageUsersGroupsAndRoles.java index 9f7273c9ef2b..cfb13525a2c2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/authorization/samples/ManageUsersGroupsAndRoles.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/authorization/samples/ManageUsersGroupsAndRoles.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.core.management.profile.AzureProfile; import com.azure.resourcemanager.AzureResourceManager; @@ -167,7 +167,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Azure */ public static void main(String[] args) { try { - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cdn/samples/ManageCdn.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cdn/samples/ManageCdn.java index 612b8f08596c..6a2ec6f705cf 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cdn/samples/ManageCdn.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cdn/samples/ManageCdn.java @@ -5,8 +5,9 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.Region; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.appservice.models.JavaVersion; @@ -16,7 +17,6 @@ import com.azure.resourcemanager.cdn.models.CdnEndpoint; import com.azure.resourcemanager.cdn.models.CdnProfile; import com.azure.resourcemanager.cdn.models.QueryStringCachingBehavior; -import com.azure.core.management.Region; import com.azure.resourcemanager.resources.fluentcore.model.Creatable; import com.azure.resourcemanager.samples.Utils; @@ -135,7 +135,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_CHINA_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); AzureResourceManager azureResourceManager = AzureResourceManager.configure() diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cdn/samples/ManageCdnWithCustomDomain.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cdn/samples/ManageCdnWithCustomDomain.java index 2634c53c59c6..b71f8327fbed 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cdn/samples/ManageCdnWithCustomDomain.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cdn/samples/ManageCdnWithCustomDomain.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.profile.AzureProfile; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; @@ -152,7 +152,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); AzureResourceManager azureResourceManager = AzureResourceManager.configure() diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CloneVirtualMachineToNewRegion.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CloneVirtualMachineToNewRegion.java index 1a858af28a79..00e18ec4b62f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CloneVirtualMachineToNewRegion.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CloneVirtualMachineToNewRegion.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.Region; import com.azure.core.management.profile.AzureProfile; import com.azure.identity.DefaultAzureCredentialBuilder; @@ -261,7 +261,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ConvertVirtualMachineToManagedDisks.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ConvertVirtualMachineToManagedDisks.java index 416cf0fae439..8e01c1db657b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ConvertVirtualMachineToManagedDisks.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ConvertVirtualMachineToManagedDisks.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.KnownLinuxVirtualMachineImage; @@ -108,7 +108,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateMultipleVirtualMachinesAndBatchQueryStatus.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateMultipleVirtualMachinesAndBatchQueryStatus.java index 76fe3f13366f..28116b0f1e81 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateMultipleVirtualMachinesAndBatchQueryStatus.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateMultipleVirtualMachinesAndBatchQueryStatus.java @@ -6,7 +6,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.policy.HttpLogOptions; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.Region; import com.azure.core.management.profile.AzureProfile; import com.azure.identity.DefaultAzureCredentialBuilder; @@ -183,7 +183,7 @@ public static void main(String[] args) { try { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineEncryptedUsingCustomerManagedKey.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineEncryptedUsingCustomerManagedKey.java index 0b0bdd282dba..89e5e8682cdc 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineEncryptedUsingCustomerManagedKey.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineEncryptedUsingCustomerManagedKey.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.Region; import com.azure.core.management.profile.AzureProfile; import com.azure.core.util.Configuration; @@ -171,7 +171,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingCustomImageFromVHD.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingCustomImageFromVHD.java index 0cdffa181fde..62d70647ae4d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingCustomImageFromVHD.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingCustomImageFromVHD.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.KnownLinuxVirtualMachineImage; @@ -254,7 +254,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingCustomImageFromVM.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingCustomImageFromVM.java index e2db335ed88b..c440d1c8e028 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingCustomImageFromVM.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingCustomImageFromVM.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.core.management.profile.AzureProfile; import com.azure.resourcemanager.compute.models.RunCommandInput; @@ -236,7 +236,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingSpecializedDiskFromSnapshot.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingSpecializedDiskFromSnapshot.java index a383d543c877..3666825c3dda 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingSpecializedDiskFromSnapshot.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingSpecializedDiskFromSnapshot.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.CachingTypes; @@ -273,7 +273,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingSpecializedDiskFromVhd.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingSpecializedDiskFromVhd.java index 567ad0ec9275..4ccd71f707d1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingSpecializedDiskFromVhd.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineUsingSpecializedDiskFromVhd.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.CachingTypes; @@ -219,7 +219,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineWithTrustedLaunchFromGalleryImage.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineWithTrustedLaunchFromGalleryImage.java index ea0005c10fa1..949b60626732 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineWithTrustedLaunchFromGalleryImage.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachineWithTrustedLaunchFromGalleryImage.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.Region; import com.azure.core.management.profile.AzureProfile; import com.azure.identity.DefaultAzureCredentialBuilder; @@ -182,7 +182,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachinesAsyncTrackingRelatedResources.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachinesAsyncTrackingRelatedResources.java index 514225b40c07..771506eace53 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachinesAsyncTrackingRelatedResources.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachinesAsyncTrackingRelatedResources.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.exception.ManagementException; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; @@ -283,7 +283,7 @@ public static void main(String[] args) { //============================================================= // Authenticate // - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachinesInParallel.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachinesInParallel.java index 5c923cd2606a..20ded3d7ca68 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachinesInParallel.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachinesInParallel.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.KnownLinuxVirtualMachineImage; @@ -222,7 +222,7 @@ public static void main(String[] args) { //============================================================= // Authenticate // - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachinesUsingCustomImageOrSpecializedVHD.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachinesUsingCustomImageOrSpecializedVHD.java index 4b2441c682d5..dce411c88f0c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachinesUsingCustomImageOrSpecializedVHD.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/CreateVirtualMachinesUsingCustomImageOrSpecializedVHD.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.KnownLinuxVirtualMachineImage; @@ -191,7 +191,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ListComputeSkus.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ListComputeSkus.java index 4e4b453f8ce1..9bd42360b2e4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ListComputeSkus.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ListComputeSkus.java @@ -6,7 +6,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.ComputeResourceType; @@ -118,7 +118,7 @@ public static void main(String[] args) { //================================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ListVirtualMachineExtensionImages.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ListVirtualMachineExtensionImages.java index c5ad7ea5a747..7536c62052d0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ListVirtualMachineExtensionImages.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ListVirtualMachineExtensionImages.java @@ -6,7 +6,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.VirtualMachineExtensionImage; @@ -86,7 +86,7 @@ public static void main(String[] args) { //================================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ListVirtualMachineImages.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ListVirtualMachineImages.java index bef83ade4274..a6fc348272ef 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ListVirtualMachineImages.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ListVirtualMachineImages.java @@ -6,7 +6,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.VirtualMachineImage; @@ -89,7 +89,7 @@ public static void main(String[] args) { //================================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageAvailabilitySet.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageAvailabilitySet.java index 04798ed228b7..7859f0310487 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageAvailabilitySet.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageAvailabilitySet.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.AvailabilitySet; @@ -192,7 +192,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageDiskEncryptionSet.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageDiskEncryptionSet.java index 087b848615a3..906c6de20308 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageDiskEncryptionSet.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageDiskEncryptionSet.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.Region; import com.azure.core.management.profile.AzureProfile; import com.azure.core.util.Configuration; @@ -183,7 +183,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageManagedDisks.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageManagedDisks.java index 7cdd51abb7c0..63c4463ff825 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageManagedDisks.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageManagedDisks.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.core.management.profile.AzureProfile; import com.azure.resourcemanager.AzureResourceManager; @@ -366,7 +366,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageResourceFromMSIEnabledVirtualMachineBelongsToAADGroup.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageResourceFromMSIEnabledVirtualMachineBelongsToAADGroup.java index 9f097e6922a5..e597f2970e9d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageResourceFromMSIEnabledVirtualMachineBelongsToAADGroup.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageResourceFromMSIEnabledVirtualMachineBelongsToAADGroup.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.CachingTypes; @@ -193,7 +193,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageScaleSetUserAssignedMSIFromServicePrincipal.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageScaleSetUserAssignedMSIFromServicePrincipal.java index d6e04bfc6c97..3534ce2939c8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageScaleSetUserAssignedMSIFromServicePrincipal.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageScaleSetUserAssignedMSIFromServicePrincipal.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.exception.ManagementException; import com.azure.core.util.logging.ClientLogger; import com.azure.identity.ClientSecretCredential; @@ -113,13 +113,13 @@ public static boolean runSample(AzureResourceManager.Authenticated authenticated // ============================================================ // Login using created service principle and verify it can assign/remove identity #1, but not #2 + AzureProfile profile = new AzureProfile(null, subscription, AzureCloud.AZURE_PUBLIC_CLOUD); ClientSecretCredential credential = new ClientSecretCredentialBuilder().clientId(servicePrincipal.applicationId()) .tenantId(servicePrincipal.manager().tenantId()) .clientSecret("\"StrongPass!12\"") - .authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); - AzureProfile profile = new AzureProfile(null, subscription, AzureEnvironment.AZURE); ComputeManager computeManager1 = ComputeManager.authenticate(credential, profile); VirtualMachineScaleSet vmss @@ -176,7 +176,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageStorageFromMSIEnabledVirtualMachine.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageStorageFromMSIEnabledVirtualMachine.java index a3c943554398..832244d00d1d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageStorageFromMSIEnabledVirtualMachine.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageStorageFromMSIEnabledVirtualMachine.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.CachingTypes; @@ -126,7 +126,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageUserAssignedMSIEnabledVirtualMachine.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageUserAssignedMSIEnabledVirtualMachine.java index 23bf55f5e872..0cd3c9f625e5 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageUserAssignedMSIEnabledVirtualMachine.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageUserAssignedMSIEnabledVirtualMachine.java @@ -6,7 +6,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.InstanceViewStatus; @@ -180,7 +180,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachine.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachine.java index c0d264b076cf..87aff863aa49 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachine.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachine.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.Disk; @@ -209,7 +209,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineAsync.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineAsync.java index 081f8cb689e9..440776eff562 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineAsync.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineAsync.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.profile.AzureProfile; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; @@ -200,7 +200,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineExtension.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineExtension.java index 8e06a6c62ead..8ed696bd682c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineExtension.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineExtension.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.KnownWindowsVirtualMachineImage; @@ -298,7 +298,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineFromMSIEnabledVirtualMachine.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineFromMSIEnabledVirtualMachine.java index 9682abee8a76..e17776efa29f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineFromMSIEnabledVirtualMachine.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineFromMSIEnabledVirtualMachine.java @@ -4,7 +4,7 @@ package com.azure.resourcemanager.compute.samples; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.profile.AzureProfile; import com.azure.identity.ManagedIdentityCredential; import com.azure.identity.ManagedIdentityCredentialBuilder; @@ -52,7 +52,7 @@ public static void main(String[] args) { ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder().clientId(clientId).build(); - AzureProfile profile = new AzureProfile(null, subscriptionId, AzureEnvironment.AZURE); + AzureProfile profile = new AzureProfile(null, subscriptionId, AzureCloud.AZURE_PUBLIC_CLOUD); AzureResourceManager azure = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineScaleSet.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineScaleSet.java index 242875f474d8..fa59bec807e7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineScaleSet.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineScaleSet.java @@ -6,7 +6,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.CachingTypes; @@ -358,7 +358,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineScaleSetAsync.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineScaleSetAsync.java index 49a86d43f44b..fa47e0877bce 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineScaleSetAsync.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineScaleSetAsync.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.profile.AzureProfile; import com.azure.core.management.Region; import com.azure.identity.DefaultAzureCredentialBuilder; @@ -338,7 +338,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineScaleSetWithUnmanagedDisks.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineScaleSetWithUnmanagedDisks.java index 0d5ef2f07d6d..8c6943b69e44 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineScaleSetWithUnmanagedDisks.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineScaleSetWithUnmanagedDisks.java @@ -6,7 +6,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.ImageReference; @@ -347,7 +347,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineWithDisk.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineWithDisk.java index 051244a7c74c..363ff8ab97d3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineWithDisk.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineWithDisk.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.CachingTypes; @@ -203,7 +203,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineWithUnmanagedDisks.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineWithUnmanagedDisks.java index eed0e92cdc75..9eb78389ac7c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineWithUnmanagedDisks.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachineWithUnmanagedDisks.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.CachingTypes; @@ -237,7 +237,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachinesInParallel.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachinesInParallel.java index e2b68139c358..8b9778d4c282 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachinesInParallel.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageVirtualMachinesInParallel.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.KnownLinuxVirtualMachineImage; @@ -119,7 +119,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageZonalVirtualMachine.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageZonalVirtualMachine.java index 962be145b759..21c4b42d7efb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageZonalVirtualMachine.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageZonalVirtualMachine.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.Disk; @@ -156,7 +156,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageZonalVirtualMachineScaleSet.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageZonalVirtualMachineScaleSet.java index 0c7d3e493a97..4dc247ad4640 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageZonalVirtualMachineScaleSet.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/compute/samples/ManageZonalVirtualMachineScaleSet.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.KnownLinuxVirtualMachineImage; @@ -230,7 +230,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithAzureFileShareMount.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithAzureFileShareMount.java index 57f855d48cd5..9d09c228b647 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithAzureFileShareMount.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithAzureFileShareMount.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.containerinstance.models.ContainerGroup; @@ -129,7 +129,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithManualAzureFileShareMountCreation.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithManualAzureFileShareMountCreation.java index dd0cd2f5dfee..25cfbdae83e7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithManualAzureFileShareMountCreation.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithManualAzureFileShareMountCreation.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.containerinstance.models.ContainerGroup; @@ -144,7 +144,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithMultipleContainerImages.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithMultipleContainerImages.java index 0009a871b6d9..fbdeb940f9bc 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithMultipleContainerImages.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithMultipleContainerImages.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.containerinstance.models.ContainerGroup; @@ -114,7 +114,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceZeroToOneAndOneToManyUsingContainerServiceOrchestrator.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceZeroToOneAndOneToManyUsingContainerServiceOrchestrator.java index 1c0ffc61119d..4ca3c65d4ac9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceZeroToOneAndOneToManyUsingContainerServiceOrchestrator.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceZeroToOneAndOneToManyUsingContainerServiceOrchestrator.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.containerinstance.models.ContainerGroup; @@ -522,7 +522,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerregistry/samples/ManageContainerRegistry.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerregistry/samples/ManageContainerRegistry.java index 7cb21b689205..54588c678c0b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerregistry/samples/ManageContainerRegistry.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerregistry/samples/ManageContainerRegistry.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.containerregistry.models.AccessKeyType; @@ -181,7 +181,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerregistry/samples/ManageContainerRegistryWithWebhooks.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerregistry/samples/ManageContainerRegistryWithWebhooks.java index 17eb1655fefd..8358756f6faf 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerregistry/samples/ManageContainerRegistryWithWebhooks.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerregistry/samples/ManageContainerRegistryWithWebhooks.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.containerregistry.models.AccessKeyType; @@ -204,7 +204,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBTableWithVirtualNetworkRule.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBTableWithVirtualNetworkRule.java index ba6db3d4debc..c4a55990508e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBTableWithVirtualNetworkRule.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBTableWithVirtualNetworkRule.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.exception.ManagementException; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; @@ -141,7 +141,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBWithEventualConsistency.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBWithEventualConsistency.java index 540e00230ba4..47d643f7e62e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBWithEventualConsistency.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBWithEventualConsistency.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.exception.ManagementException; import com.azure.cosmos.ConsistencyLevel; import com.azure.cosmos.CosmosClient; @@ -130,7 +130,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBWithIPRange.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBWithIPRange.java index 0d33b97c69f6..43a8a6586a90 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBWithIPRange.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBWithIPRange.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.exception.ManagementException; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; @@ -87,7 +87,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBWithKindMongoDB.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBWithKindMongoDB.java index b0ee882f77bd..a10e0e4689c5 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBWithKindMongoDB.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/CreateCosmosDBWithKindMongoDB.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.exception.ManagementException; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; @@ -93,7 +93,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/ManageHACosmosDB.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/ManageHACosmosDB.java index 993ba40b4727..bf1928c2f166 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/ManageHACosmosDB.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cosmos/samples/ManageHACosmosDB.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.exception.ManagementException; import com.azure.cosmos.ConsistencyLevel; import com.azure.cosmos.CosmosClient; @@ -144,7 +144,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/dns/samples/ManageDns.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/dns/samples/ManageDns.java index 5970f8daf4b9..745d934f50e1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/dns/samples/ManageDns.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/dns/samples/ManageDns.java @@ -6,7 +6,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.appservice.models.PricingTier; @@ -275,7 +275,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHub.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHub.java index aa3399047f61..0804eb078679 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHub.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHub.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.eventhubs.models.EventHub; @@ -181,7 +181,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHubEvents.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHubEvents.java index b1fc9e46d5c4..4518c5d23808 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHubEvents.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHubEvents.java @@ -4,7 +4,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.cosmos.models.CosmosDBAccount; @@ -136,7 +136,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHubGeoDisasterRecovery.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHubGeoDisasterRecovery.java index 2b66a7432d8b..959249551ee7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHubGeoDisasterRecovery.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHubGeoDisasterRecovery.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.eventhubs.models.DisasterRecoveryPairingAuthorizationKey; @@ -171,7 +171,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/keyvault/samples/ManageKeyVault.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/keyvault/samples/ManageKeyVault.java index 108cfe72ef5f..a6d73e79fbbf 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/keyvault/samples/ManageKeyVault.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/keyvault/samples/ManageKeyVault.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; @@ -151,7 +151,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/DeployImageFromContainerRegistryToKubernetes.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/DeployImageFromContainerRegistryToKubernetes.java index 87fe095fe371..136e7ffb9423 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/DeployImageFromContainerRegistryToKubernetes.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/DeployImageFromContainerRegistryToKubernetes.java @@ -4,7 +4,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.containerregistry.models.AccessKeyType; @@ -468,7 +468,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/ManageKubernetesCluster.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/ManageKubernetesCluster.java index c22db1740d9a..f94f72adf2c7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/ManageKubernetesCluster.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/ManageKubernetesCluster.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.containerservice.models.AgentPoolMode; @@ -106,7 +106,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/ManageKubernetesClusterWithCustomerManagedKey.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/ManageKubernetesClusterWithCustomerManagedKey.java index 3577aa85c290..96030605d40e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/ManageKubernetesClusterWithCustomerManagedKey.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/ManageKubernetesClusterWithCustomerManagedKey.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.Region; import com.azure.core.management.profile.AzureProfile; import com.azure.core.util.Configuration; @@ -145,7 +145,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/ManagedKubernetesClusterWithAdvancedNetworking.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/ManagedKubernetesClusterWithAdvancedNetworking.java index 1211b9dfe0cb..b21b462ea4b7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/ManagedKubernetesClusterWithAdvancedNetworking.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/ManagedKubernetesClusterWithAdvancedNetworking.java @@ -4,7 +4,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.containerservice.models.AgentPoolMode; @@ -136,7 +136,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/AutoscaleSettingsBasedOnPerformanceOrSchedule.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/AutoscaleSettingsBasedOnPerformanceOrSchedule.java index b3ebd8127cdb..098e2f34ad4d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/AutoscaleSettingsBasedOnPerformanceOrSchedule.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/AutoscaleSettingsBasedOnPerformanceOrSchedule.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.appservice.models.PricingTier; @@ -139,7 +139,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { public static void main(String[] args) { try { - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/QueryMetricsAndActivityLogs.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/QueryMetricsAndActivityLogs.java index 98e809196612..c3c600576484 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/QueryMetricsAndActivityLogs.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/QueryMetricsAndActivityLogs.java @@ -7,7 +7,7 @@ import com.azure.core.http.HttpClient; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.monitor.models.EventData; @@ -174,7 +174,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw public static void main(String[] args) { try { - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/SecurityBreachOrRiskActivityLogAlerts.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/SecurityBreachOrRiskActivityLogAlerts.java index 081784e071a3..79366f6f5cef 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/SecurityBreachOrRiskActivityLogAlerts.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/SecurityBreachOrRiskActivityLogAlerts.java @@ -6,7 +6,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.monitor.models.ActionGroup; @@ -147,7 +147,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { public static void main(String[] args) { try { - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/WebAppPerformanceMonitoringAlerts.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/WebAppPerformanceMonitoringAlerts.java index 8f913c7a5dc5..a4e1cefab6d4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/WebAppPerformanceMonitoringAlerts.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/monitor/samples/WebAppPerformanceMonitoringAlerts.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.appservice.models.AppServicePlan; @@ -111,7 +111,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { public static void main(String[] args) { try { - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/CreateSimpleInternetFacingLoadBalancer.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/CreateSimpleInternetFacingLoadBalancer.java index 511f1eb80c8e..244fc2867875 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/CreateSimpleInternetFacingLoadBalancer.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/CreateSimpleInternetFacingLoadBalancer.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.AvailabilitySet; @@ -211,7 +211,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageApplicationGateway.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageApplicationGateway.java index 966de50ca1cb..13bf81c1e6a6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageApplicationGateway.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageApplicationGateway.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.KnownLinuxVirtualMachineImage; @@ -309,7 +309,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageExpressRoute.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageExpressRoute.java index a7d947c52c68..aa671a77464a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageExpressRoute.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageExpressRoute.java @@ -4,7 +4,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.network.models.ExpressRouteCircuit; @@ -130,7 +130,7 @@ public static void main(String[] args) { try { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageExpressRouteCrossConnection.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageExpressRouteCrossConnection.java index 77c18ad29129..c62894df3c03 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageExpressRouteCrossConnection.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageExpressRouteCrossConnection.java @@ -4,7 +4,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.network.models.ExpressRouteCrossConnection; @@ -109,7 +109,7 @@ public static void main(String[] args) { try { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageIPAddress.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageIPAddress.java index e3e31d716978..3e6810f8fe6d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageIPAddress.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageIPAddress.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.KnownWindowsVirtualMachineImage; @@ -166,7 +166,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageInternalLoadBalancer.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageInternalLoadBalancer.java index bd82f32d709b..1a313edd11c0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageInternalLoadBalancer.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageInternalLoadBalancer.java @@ -6,7 +6,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.AvailabilitySet; @@ -442,7 +442,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageInternetFacingLoadBalancer.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageInternetFacingLoadBalancer.java index c3761e4b2255..09d909616440 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageInternetFacingLoadBalancer.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageInternetFacingLoadBalancer.java @@ -6,7 +6,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.AvailabilitySet; @@ -501,7 +501,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkInterface.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkInterface.java index 57ffb17f144f..6c105f9da897 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkInterface.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkInterface.java @@ -6,7 +6,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.KnownWindowsVirtualMachineImage; @@ -209,7 +209,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkPeeringInSameSubscription.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkPeeringInSameSubscription.java index 41be1957b2a4..da70d1a1816a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkPeeringInSameSubscription.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkPeeringInSameSubscription.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.network.models.Network; @@ -170,7 +170,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkSecurityGroup.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkSecurityGroup.java index 57be006828dd..fea3b8f6aac3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkSecurityGroup.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkSecurityGroup.java @@ -6,7 +6,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.KnownLinuxVirtualMachineImage; @@ -305,7 +305,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkWatcher.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkWatcher.java index 3b8d4f343f48..f4f374bbe850 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkWatcher.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageNetworkWatcher.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.KnownLinuxVirtualMachineImage; @@ -328,7 +328,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManagePrivateLink.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManagePrivateLink.java index aea0d5e45011..b77693a8d51b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManagePrivateLink.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManagePrivateLink.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.Region; import com.azure.core.management.profile.AzureProfile; import com.azure.identity.DefaultAzureCredentialBuilder; @@ -267,7 +267,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageSimpleApplicationGateway.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageSimpleApplicationGateway.java index a5010994e0c2..d4256cfc8742 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageSimpleApplicationGateway.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageSimpleApplicationGateway.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.network.models.ApplicationGateway; @@ -166,7 +166,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVirtualMachinesInParallelWithNetwork.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVirtualMachinesInParallelWithNetwork.java index 9ccd8afebe0e..7359fa1e872f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVirtualMachinesInParallelWithNetwork.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVirtualMachinesInParallelWithNetwork.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.KnownLinuxVirtualMachineImage; @@ -251,7 +251,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVirtualNetwork.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVirtualNetwork.java index 97a1d9b7dc33..2bd1180f0b71 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVirtualNetwork.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVirtualNetwork.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.KnownLinuxVirtualMachineImage; @@ -259,7 +259,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVirtualNetworkAsync.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVirtualNetworkAsync.java index 8338a7c8a326..e3c22829b902 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVirtualNetworkAsync.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVirtualNetworkAsync.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.KnownLinuxVirtualMachineImage; @@ -274,7 +274,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVpnGatewayPoint2SiteConnection.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVpnGatewayPoint2SiteConnection.java index 927009b85fb8..4b709e661766 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVpnGatewayPoint2SiteConnection.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVpnGatewayPoint2SiteConnection.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.network.models.Network; @@ -136,7 +136,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVpnGatewaySite2SiteConnection.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVpnGatewaySite2SiteConnection.java index 8110d0e7b506..3a4a442b61d8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVpnGatewaySite2SiteConnection.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVpnGatewaySite2SiteConnection.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.network.models.LocalNetworkGateway; @@ -124,7 +124,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVpnGatewayVNet2VNetConnection.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVpnGatewayVNet2VNetConnection.java index f50ddfecf7b8..1d6602cc1433 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVpnGatewayVNet2VNetConnection.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/ManageVpnGatewayVNet2VNetConnection.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.KnownLinuxVirtualMachineImage; @@ -254,7 +254,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/VerifyNetworkPeeringWithNetworkWatcher.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/VerifyNetworkPeeringWithNetworkWatcher.java index 2af0a011f228..79fcf82af941 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/VerifyNetworkPeeringWithNetworkWatcher.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/network/samples/VerifyNetworkPeeringWithNetworkWatcher.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.KnownLinuxVirtualMachineImage; @@ -209,7 +209,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/privatedns/samples/ManagePrivateDns.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/privatedns/samples/ManagePrivateDns.java index 0c375cc6b767..11555417fe22 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/privatedns/samples/ManagePrivateDns.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/privatedns/samples/ManagePrivateDns.java @@ -4,7 +4,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.InstanceViewStatus; @@ -188,7 +188,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/rediscache/samples/ManageRedisCache.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/rediscache/samples/ManageRedisCache.java index 8c39d7a66f17..cf7b6a2a6539 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/rediscache/samples/ManageRedisCache.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/rediscache/samples/ManageRedisCache.java @@ -6,7 +6,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.redis.models.DayOfWeek; @@ -168,7 +168,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplate.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplate.java index 83822e3c58f1..47c368327de3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplate.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplate.java @@ -6,7 +6,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.resources.models.Deployment; @@ -112,7 +112,7 @@ public static void main(String[] args) { //================================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateAsync.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateAsync.java index ad9b7b4f03d4..165a8011e4a9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateAsync.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateAsync.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.profile.AzureProfile; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; @@ -136,7 +136,7 @@ public static void main(String[] args) { //================================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateWithDeploymentOperations.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateWithDeploymentOperations.java index fef3e0ae2dee..4b8f5701781b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateWithDeploymentOperations.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateWithDeploymentOperations.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.resources.models.Deployment; @@ -173,7 +173,7 @@ public static void main(String[] args) { //================================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateWithProgress.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateWithProgress.java index bbe2d653ae62..c9d0e64ab7b6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateWithProgress.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateWithProgress.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.resources.models.Deployment; @@ -103,7 +103,7 @@ public static void main(String[] args) { //================================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateWithTags.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateWithTags.java index e251346ace4f..45e2e66b18c8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateWithTags.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployUsingARMTemplateWithTags.java @@ -6,7 +6,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.resources.models.Deployment; @@ -126,7 +126,7 @@ public static void main(String[] args) { //================================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployVirtualMachineUsingARMTemplate.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployVirtualMachineUsingARMTemplate.java index 9b64b51433ed..d688572f5514 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployVirtualMachineUsingARMTemplate.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/DeployVirtualMachineUsingARMTemplate.java @@ -4,7 +4,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.core.management.Region; @@ -104,7 +104,7 @@ public static void main(String[] args) { //================================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/ManageLocks.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/ManageLocks.java index 4f40c4e2b085..e6dbabce7802 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/ManageLocks.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/ManageLocks.java @@ -6,7 +6,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.Region; import com.azure.core.management.profile.AzureProfile; import com.azure.identity.DefaultAzureCredentialBuilder; @@ -246,7 +246,7 @@ public static void main(String[] args) { //================================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/ManageResource.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/ManageResource.java index f488ef8345df..e980cf3f3f8d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/ManageResource.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/ManageResource.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.core.management.Region; @@ -121,7 +121,7 @@ public static void main(String[] args) { //================================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/ManageResourceGroup.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/ManageResourceGroup.java index a41a5217493c..67efeea57d66 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/ManageResourceGroup.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/resources/samples/ManageResourceGroup.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.resources.models.ResourceGroup; @@ -103,7 +103,7 @@ public static void main(String[] args) { //================================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/search/samples/ManageSearchService.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/search/samples/ManageSearchService.java index be4ed9ef4bd5..d33f8b77d47b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/search/samples/ManageSearchService.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/search/samples/ManageSearchService.java @@ -6,7 +6,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.Region; import com.azure.core.management.profile.AzureProfile; import com.azure.identity.DefaultAzureCredentialBuilder; @@ -184,7 +184,7 @@ public static void main(String[] args) { //============================================================= // Authenticate - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder().build(); AzureResourceManager azureResourceManager = AzureResourceManager.configure() diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusPublishSubscribeAdvanceFeatures.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusPublishSubscribeAdvanceFeatures.java index ba09dff9ebf1..4f09bc5738f4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusPublishSubscribeAdvanceFeatures.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusPublishSubscribeAdvanceFeatures.java @@ -6,7 +6,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.profile.AzureProfile; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.messaging.servicebus.ServiceBusClientBuilder; @@ -212,7 +212,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { */ public static void main(String[] args) { try { - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusPublishSubscribeBasic.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusPublishSubscribeBasic.java index 2a77f25247e4..dcf5f15c0d2a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusPublishSubscribeBasic.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusPublishSubscribeBasic.java @@ -6,7 +6,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.profile.AzureProfile; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.messaging.servicebus.ServiceBusClientBuilder; @@ -188,7 +188,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { */ public static void main(String[] args) { try { - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusQueueAdvanceFeatures.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusQueueAdvanceFeatures.java index 58023d596013..91a0cdc0eb93 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusQueueAdvanceFeatures.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusQueueAdvanceFeatures.java @@ -6,7 +6,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.profile.AzureProfile; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.messaging.servicebus.ServiceBusClientBuilder; @@ -184,7 +184,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { */ public static void main(String[] args) { try { - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusQueueBasic.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusQueueBasic.java index 2d5628a931e4..2a5c9ec76772 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusQueueBasic.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusQueueBasic.java @@ -6,7 +6,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.profile.AzureProfile; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.messaging.servicebus.ServiceBusClientBuilder; @@ -186,7 +186,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { */ public static void main(String[] args) { try { - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusWithClaimBasedAuthorization.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusWithClaimBasedAuthorization.java index 780d40e5ac02..75aec1345338 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusWithClaimBasedAuthorization.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusWithClaimBasedAuthorization.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.profile.AzureProfile; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.messaging.servicebus.ServiceBusClientBuilder; @@ -147,7 +147,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { */ public static void main(String[] args) { try { - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabase.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabase.java index 77c43d162042..818513ea606b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabase.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabase.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.Region; import com.azure.core.management.profile.AzureProfile; import com.azure.identity.DefaultAzureCredentialBuilder; @@ -130,7 +130,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { public static void main(String[] args) { try { - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabaseInElasticPool.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabaseInElasticPool.java index 7d80892c32e6..50472c42e0c3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabaseInElasticPool.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabaseInElasticPool.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.Region; import com.azure.core.management.profile.AzureProfile; import com.azure.identity.DefaultAzureCredentialBuilder; @@ -201,7 +201,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { */ public static void main(String[] args) { try { - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabasesAcrossDifferentDataCenters.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabasesAcrossDifferentDataCenters.java index e41c4561147d..960e58ca2350 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabasesAcrossDifferentDataCenters.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabasesAcrossDifferentDataCenters.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.Region; import com.azure.core.management.profile.AzureProfile; import com.azure.identity.DefaultAzureCredentialBuilder; @@ -219,7 +219,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { public static void main(String[] args) { try { - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlFailoverGroups.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlFailoverGroups.java index 6a02342eac9d..fcd4019e6ebf 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlFailoverGroups.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlFailoverGroups.java @@ -4,7 +4,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.core.management.Region; @@ -172,7 +172,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { */ public static void main(String[] args) { try { - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlFirewallRules.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlFirewallRules.java index 34590fc30888..a297e9d01c14 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlFirewallRules.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlFirewallRules.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.core.management.Region; @@ -131,7 +131,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { */ public static void main(String[] args) { try { - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlImportExportDatabase.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlImportExportDatabase.java index 20ab86c4e999..fb5f0a78ed50 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlImportExportDatabase.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlImportExportDatabase.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.core.management.Region; @@ -142,7 +142,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { public static void main(String[] args) { try { - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerDnsAliases.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerDnsAliases.java index 8cdc5d77d220..a86e64dcabbb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerDnsAliases.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerDnsAliases.java @@ -4,7 +4,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.core.management.Region; @@ -205,7 +205,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) */ public static void main(String[] args) { try { - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerKeysWithAzureKeyVaultKey.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerKeysWithAzureKeyVaultKey.java index b5064b1d8ee2..6312ab65a11a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerKeysWithAzureKeyVaultKey.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerKeysWithAzureKeyVaultKey.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; @@ -156,7 +156,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin */ public static void main(String[] args) { try { - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerSecurityAlertPolicy.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerSecurityAlertPolicy.java index f50883f9efc2..a55c4ae75ca5 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerSecurityAlertPolicy.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerSecurityAlertPolicy.java @@ -4,7 +4,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.core.management.Region; @@ -119,7 +119,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { */ public static void main(String[] args) { try { - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlVirtualNetworkRules.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlVirtualNetworkRules.java index 9eb552460259..1b0c5f8ab38e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlVirtualNetworkRules.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlVirtualNetworkRules.java @@ -4,7 +4,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.network.models.Network; @@ -140,7 +140,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { */ public static void main(String[] args) { try { - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlWithRecoveredOrRestoredDatabase.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlWithRecoveredOrRestoredDatabase.java index c9b7b178ce6a..b96cf0a599dd 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlWithRecoveredOrRestoredDatabase.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlWithRecoveredOrRestoredDatabase.java @@ -4,7 +4,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.core.management.Region; @@ -155,7 +155,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { public static void main(String[] args) { try { - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccount.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccount.java index 684489d0d39d..ba221ed968ae 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccount.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccount.java @@ -6,7 +6,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.core.management.Region; @@ -138,7 +138,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { */ public static void main(String[] args) { try { - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccountAsync.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccountAsync.java index e64e082f721d..e6954d781a25 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccountAsync.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccountAsync.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.profile.AzureProfile; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; @@ -105,7 +105,7 @@ public static boolean runSample(final AzureResourceManager azureResourceManager) */ public static void main(String[] args) { try { - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccountCustomerManagedKey.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccountCustomerManagedKey.java index 22bf4dc628ea..8539b0729917 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccountCustomerManagedKey.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccountCustomerManagedKey.java @@ -6,7 +6,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.exception.HttpResponseException; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.Region; import com.azure.core.management.profile.AzureProfile; import com.azure.core.util.BinaryData; @@ -198,7 +198,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin */ public static void main(String[] args) { try { - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccountNetworkRules.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccountNetworkRules.java index c1874ca44fab..416d9d1a0862 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccountNetworkRules.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/storage/samples/ManageStorageAccountNetworkRules.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.compute.models.KnownLinuxVirtualMachineImage; @@ -159,7 +159,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) { */ public static void main(String[] args) { try { - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/trafficmanager/samples/ManageSimpleTrafficManager.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/trafficmanager/samples/ManageSimpleTrafficManager.java index 14bc6a690256..9a4db9316140 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/trafficmanager/samples/ManageSimpleTrafficManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/trafficmanager/samples/ManageSimpleTrafficManager.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.profile.AzureProfile; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; @@ -155,7 +155,7 @@ public static void main(String[] args) { //============================================================= // Authenticate // - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/trafficmanager/samples/ManageTrafficManager.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/trafficmanager/samples/ManageTrafficManager.java index aead2f5aee40..83782015bc31 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/trafficmanager/samples/ManageTrafficManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/trafficmanager/samples/ManageTrafficManager.java @@ -5,7 +5,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.profile.AzureProfile; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; @@ -248,7 +248,7 @@ public static void main(String[] args) { //============================================================= // Authenticate // - final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/AppServiceSampleLiveOnlyTests.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/AppServiceSampleLiveOnlyTests.java index cd34707cec15..21f28b867325 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/AppServiceSampleLiveOnlyTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/AppServiceSampleLiveOnlyTests.java @@ -6,7 +6,7 @@ import com.azure.core.http.HttpPipeline; import com.azure.core.http.HttpPipelineBuilder; import com.azure.core.http.netty.NettyAsyncHttpClientBuilder; -import com.azure.core.management.AzureEnvironment; +import com.azure.core.models.AzureCloud; import com.azure.core.management.profile.AzureProfile; import com.azure.core.test.annotation.DoNotRecord; import com.azure.resourcemanager.AzureResourceManager; @@ -74,7 +74,7 @@ public void testManageFunctionAppLogs() throws IOException { azureResourceManager = buildManager(AzureResourceManager.class, setReadTimeout(azureResourceManager.storageAccounts().manager().httpPipeline(), Duration.ofMinutes(10)), new AzureProfile(azureResourceManager.tenantId(), azureResourceManager.subscriptionId(), - AzureEnvironment.AZURE)); + AzureCloud.AZURE_PUBLIC_CLOUD)); Assertions.assertTrue(ManageFunctionAppLogs.runSample(azureResourceManager)); } @@ -87,7 +87,7 @@ public void testManageWebAppLogs() throws IOException { azureResourceManager = buildManager(AzureResourceManager.class, setReadTimeout(azureResourceManager.storageAccounts().manager().httpPipeline(), Duration.ofMinutes(10)), new AzureProfile(azureResourceManager.tenantId(), azureResourceManager.subscriptionId(), - AzureEnvironment.AZURE)); + AzureCloud.AZURE_PUBLIC_CLOUD)); Assertions.assertTrue(ManageWebAppLogs.runSample(azureResourceManager)); } diff --git a/sdk/resourcemanager/azure-resourcemanager-search/CHANGELOG.md b/sdk/resourcemanager/azure-resourcemanager-search/CHANGELOG.md index 0e81677c892b..41ae3a6f2288 100644 --- a/sdk/resourcemanager/azure-resourcemanager-search/CHANGELOG.md +++ b/sdk/resourcemanager/azure-resourcemanager-search/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 2.47.0-beta.1 (Unreleased) +## 2.49.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,22 @@ ### Other Changes +## 2.48.0 (2025-02-28) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + +## 2.47.0 (2025-01-24) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + ## 2.46.0 (2024-12-23) ### Other Changes diff --git a/sdk/resourcemanager/azure-resourcemanager-search/README.md b/sdk/resourcemanager/azure-resourcemanager-search/README.md index 922ed5cdb5e0..bbd2d698eeef 100644 --- a/sdk/resourcemanager/azure-resourcemanager-search/README.md +++ b/sdk/resourcemanager/azure-resourcemanager-search/README.md @@ -18,7 +18,7 @@ For documentation on how to use this package, please see [Azure Management Libra com.azure.resourcemanager azure-resourcemanager-search - 2.46.0 + 2.49.0-beta.1 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/resourcemanager/azure-resourcemanager-search/pom.xml b/sdk/resourcemanager/azure-resourcemanager-search/pom.xml index 5d672463c91e..e8dd53fef577 100644 --- a/sdk/resourcemanager/azure-resourcemanager-search/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-search/pom.xml @@ -14,7 +14,7 @@ com.azure.resourcemanager azure-resourcemanager-search - 2.47.0-beta.1 + 2.49.0-beta.1 jar Microsoft Azure SDK for Cognitive Search Management @@ -58,7 +58,7 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.47.0-beta.1 + 2.49.0-beta.1 org.junit.jupiter @@ -75,7 +75,7 @@ com.azure azure-core-http-netty - 1.15.7 + 1.15.11 test diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/CHANGELOG.md b/sdk/resourcemanager/azure-resourcemanager-servicebus/CHANGELOG.md index 87782f76f69a..cda1c694d763 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/CHANGELOG.md +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 2.47.0-beta.1 (Unreleased) +## 2.49.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,22 @@ ### Other Changes +## 2.48.0 (2025-02-28) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + +## 2.47.0 (2025-01-24) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + ## 2.46.0 (2024-12-23) ### Other Changes diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/README.md b/sdk/resourcemanager/azure-resourcemanager-servicebus/README.md index 022a65dd0d4c..5d78d8fb8b3d 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/README.md +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/README.md @@ -18,7 +18,7 @@ For documentation on how to use this package, please see [Azure Management Libra com.azure.resourcemanager azure-resourcemanager-servicebus - 2.46.0 + 2.49.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -39,7 +39,7 @@ Azure tenant ID can be configured via `AZURE_TENANT_ID` environment variable. Assuming the use of the `DefaultAzureCredential` credential class, the client can be authenticated using the following code: ```java readme-sample-authenticate -AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); +AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/pom.xml b/sdk/resourcemanager/azure-resourcemanager-servicebus/pom.xml index ca6d03400ce0..e7f5d3ea5a67 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/pom.xml @@ -14,7 +14,7 @@ com.azure.resourcemanager azure-resourcemanager-servicebus - 2.47.0-beta.1 + 2.49.0-beta.1 jar Microsoft Azure SDK for ServiceBus Management @@ -58,7 +58,7 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.47.0-beta.1 + 2.49.0-beta.1 org.junit.jupiter @@ -75,7 +75,7 @@ com.azure azure-core-http-netty - 1.15.7 + 1.15.11 test diff --git a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/samples/java/com/azure/resourcemanager/servicebus/ReadmeSamples.java b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/samples/java/com/azure/resourcemanager/servicebus/ReadmeSamples.java index 3392766f29b4..37f3cb5ba4ea 100644 --- a/sdk/resourcemanager/azure-resourcemanager-servicebus/src/samples/java/com/azure/resourcemanager/servicebus/ReadmeSamples.java +++ b/sdk/resourcemanager/azure-resourcemanager-servicebus/src/samples/java/com/azure/resourcemanager/servicebus/ReadmeSamples.java @@ -4,8 +4,8 @@ package com.azure.resourcemanager.servicebus; import com.azure.core.credential.TokenCredential; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; /** @@ -15,7 +15,7 @@ public class ReadmeSamples { public void authenticate() { // BEGIN: readme-sample-authenticate - AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/CHANGELOG.md b/sdk/resourcemanager/azure-resourcemanager-sql/CHANGELOG.md index fbc306df902f..710fa442b862 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/CHANGELOG.md +++ b/sdk/resourcemanager/azure-resourcemanager-sql/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 2.47.0-beta.1 (Unreleased) +## 2.49.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,22 @@ ### Other Changes +## 2.48.0 (2025-02-28) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + +## 2.47.0 (2025-01-24) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + ## 2.46.0 (2024-12-23) ### Other Changes diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/README.md b/sdk/resourcemanager/azure-resourcemanager-sql/README.md index c4bedcdf95fd..78465c7a680b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/README.md +++ b/sdk/resourcemanager/azure-resourcemanager-sql/README.md @@ -18,7 +18,7 @@ For documentation on how to use this package, please see [Azure Management Libra com.azure.resourcemanager azure-resourcemanager-sql - 2.46.0 + 2.49.0-beta.1 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/resourcemanager/azure-resourcemanager-sql/pom.xml b/sdk/resourcemanager/azure-resourcemanager-sql/pom.xml index 182706bc08b6..0e9802bc1a7f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-sql/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-sql/pom.xml @@ -14,7 +14,7 @@ com.azure.resourcemanager azure-resourcemanager-sql - 2.47.0-beta.1 + 2.49.0-beta.1 jar Microsoft Azure SDK for Sql Management @@ -63,12 +63,12 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-storage - 2.47.0-beta.1 + 2.49.0-beta.1 org.junit.jupiter @@ -91,7 +91,7 @@ com.azure azure-core-http-netty - 1.15.7 + 1.15.11 test diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/CHANGELOG.md b/sdk/resourcemanager/azure-resourcemanager-storage/CHANGELOG.md index a8d2714e8d25..506338a29dfe 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/CHANGELOG.md +++ b/sdk/resourcemanager/azure-resourcemanager-storage/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 2.47.0-beta.1 (Unreleased) +## 2.49.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,22 @@ ### Other Changes +## 2.48.0 (2025-02-28) + +### Other Changes + +#### Dependency Updates + +- Updated `api-version` to `2024-01-01`. + +## 2.47.0 (2025-01-24) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + ## 2.46.0 (2024-12-23) ### Other Changes diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/README.md b/sdk/resourcemanager/azure-resourcemanager-storage/README.md index 2da991319dd5..4638792fdbaa 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/README.md +++ b/sdk/resourcemanager/azure-resourcemanager-storage/README.md @@ -18,7 +18,7 @@ For documentation on how to use this package, please see [Azure Management Libra com.azure.resourcemanager azure-resourcemanager-storage - 2.46.0 + 2.49.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -39,7 +39,7 @@ Azure tenant ID can be configured via `AZURE_TENANT_ID` environment variable. Assuming the use of the `DefaultAzureCredential` credential class, the client can be authenticated using the following code: ```java readme-sample-authenticate -AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); +AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/assets.json b/sdk/resourcemanager/azure-resourcemanager-storage/assets.json index 6481dfae78fc..826ca520021e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/assets.json +++ b/sdk/resourcemanager/azure-resourcemanager-storage/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "java", "TagPrefix": "java/resourcemanager/azure-resourcemanager-storage", - "Tag": "java/resourcemanager/azure-resourcemanager-storage_fcce26ee2b" + "Tag": "java/resourcemanager/azure-resourcemanager-storage_ceedd20777" } diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/pom.xml b/sdk/resourcemanager/azure-resourcemanager-storage/pom.xml index 19e8eb489b4a..6b8cd5876576 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-storage/pom.xml @@ -14,7 +14,7 @@ com.azure.resourcemanager azure-resourcemanager-storage - 2.47.0-beta.1 + 2.49.0-beta.1 jar Microsoft Azure SDK for Storage Management @@ -62,17 +62,17 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-msi - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-authorization - 2.47.0-beta.1 + 2.49.0-beta.1 org.slf4j @@ -89,13 +89,13 @@ com.azure azure-core-http-netty - 1.15.7 + 1.15.11 test com.azure azure-storage-blob - 12.29.0 + 12.29.1 test diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/FileServicesClient.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/FileServicesClient.java index c5a2af828662..b69965b7ccc0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/FileServicesClient.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/FileServicesClient.java @@ -6,10 +6,13 @@ import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.Response; import com.azure.core.util.Context; import com.azure.resourcemanager.storage.fluent.models.FileServiceItemsInner; import com.azure.resourcemanager.storage.fluent.models.FileServicePropertiesInner; +import com.azure.resourcemanager.storage.fluent.models.FileServiceUsageInner; import reactor.core.publisher.Mono; /** @@ -217,4 +220,143 @@ Response getServicePropertiesWithResponse(String res */ @ServiceMethod(returns = ReturnType.SINGLE) FileServicePropertiesInner getServiceProperties(String resourceGroupName, String accountName); + + /** + * Gets the usages of file service in storage account. + * + * @param resourceGroupName The name of the resource group within the user's subscription. The name is case + * insensitive. + * @param accountName The name of the storage account within the specified resource group. Storage account names + * must be between 3 and 24 characters in length and use numbers and lower-case letters only. + * @param maxpagesize Optional, specifies the maximum number of file service usages to be included in the list + * response. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the usages of file service in storage account as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedFlux listServiceUsagesAsync(String resourceGroupName, String accountName, + Integer maxpagesize); + + /** + * Gets the usages of file service in storage account. + * + * @param resourceGroupName The name of the resource group within the user's subscription. The name is case + * insensitive. + * @param accountName The name of the storage account within the specified resource group. Storage account names + * must be between 3 and 24 characters in length and use numbers and lower-case letters only. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the usages of file service in storage account as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedFlux listServiceUsagesAsync(String resourceGroupName, String accountName); + + /** + * Gets the usages of file service in storage account. + * + * @param resourceGroupName The name of the resource group within the user's subscription. The name is case + * insensitive. + * @param accountName The name of the storage account within the specified resource group. Storage account names + * must be between 3 and 24 characters in length and use numbers and lower-case letters only. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the usages of file service in storage account as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listServiceUsages(String resourceGroupName, String accountName); + + /** + * Gets the usages of file service in storage account. + * + * @param resourceGroupName The name of the resource group within the user's subscription. The name is case + * insensitive. + * @param accountName The name of the storage account within the specified resource group. Storage account names + * must be between 3 and 24 characters in length and use numbers and lower-case letters only. + * @param maxpagesize Optional, specifies the maximum number of file service usages to be included in the list + * response. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the usages of file service in storage account as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listServiceUsages(String resourceGroupName, String accountName, + Integer maxpagesize, Context context); + + /** + * Gets the usage of file service in storage account including account limits, file share limits and constants used + * in recommendations and bursting formula. + * + * @param resourceGroupName The name of the resource group within the user's subscription. The name is case + * insensitive. + * @param accountName The name of the storage account within the specified resource group. Storage account names + * must be between 3 and 24 characters in length and use numbers and lower-case letters only. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the usage of file service in storage account including account limits, file share limits and constants + * used in recommendations and bursting formula along with {@link Response} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Mono> getServiceUsageWithResponseAsync(String resourceGroupName, + String accountName); + + /** + * Gets the usage of file service in storage account including account limits, file share limits and constants used + * in recommendations and bursting formula. + * + * @param resourceGroupName The name of the resource group within the user's subscription. The name is case + * insensitive. + * @param accountName The name of the storage account within the specified resource group. Storage account names + * must be between 3 and 24 characters in length and use numbers and lower-case letters only. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the usage of file service in storage account including account limits, file share limits and constants + * used in recommendations and bursting formula on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Mono getServiceUsageAsync(String resourceGroupName, String accountName); + + /** + * Gets the usage of file service in storage account including account limits, file share limits and constants used + * in recommendations and bursting formula. + * + * @param resourceGroupName The name of the resource group within the user's subscription. The name is case + * insensitive. + * @param accountName The name of the storage account within the specified resource group. Storage account names + * must be between 3 and 24 characters in length and use numbers and lower-case letters only. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the usage of file service in storage account including account limits, file share limits and constants + * used in recommendations and bursting formula along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + Response getServiceUsageWithResponse(String resourceGroupName, String accountName, + Context context); + + /** + * Gets the usage of file service in storage account including account limits, file share limits and constants used + * in recommendations and bursting formula. + * + * @param resourceGroupName The name of the resource group within the user's subscription. The name is case + * insensitive. + * @param accountName The name of the storage account within the specified resource group. Storage account names + * must be between 3 and 24 characters in length and use numbers and lower-case letters only. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the usage of file service in storage account including account limits, file share limits and constants + * used in recommendations and bursting formula. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + FileServiceUsageInner getServiceUsage(String resourceGroupName, String accountName); } diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/BlobContainerInner.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/BlobContainerInner.java index c548bbcd26f5..fbf2e2522cd1 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/BlobContainerInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/BlobContainerInner.java @@ -31,24 +31,24 @@ public final class BlobContainerInner extends AzureEntityResource { private ContainerProperties innerContainerProperties; /* - * Fully qualified resource Id for the resource. + * Resource Etag. */ - private String id; + private String etag; /* - * The name of the resource. + * The type of the resource. */ - private String name; + private String type; /* - * The type of the resource. + * The name of the resource. */ - private String type; + private String name; /* - * Resource Etag. + * Fully qualified resource Id for the resource. */ - private String etag; + private String id; /** * Creates an instance of BlobContainerInner class. @@ -66,43 +66,43 @@ private ContainerProperties innerContainerProperties() { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the etag property: Resource Etag. * - * @return the id value. + * @return the etag value. */ @Override - public String id() { - return this.id; + public String etag() { + return this.etag; } /** - * Get the name property: The name of the resource. + * Get the type property: The type of the resource. * - * @return the name value. + * @return the type value. */ @Override - public String name() { - return this.name; + public String type() { + return this.type; } /** - * Get the type property: The type of the resource. + * Get the name property: The name of the resource. * - * @return the type value. + * @return the name value. */ @Override - public String type() { - return this.type; + public String name() { + return this.name; } /** - * Get the etag property: Resource Etag. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the etag value. + * @return the id value. */ @Override - public String etag() { - return this.etag; + public String id() { + return this.id; } /** @@ -401,7 +401,6 @@ public BlobContainerInner withEnableNfsV3AllSquash(Boolean enableNfsV3AllSquash) */ @Override public void validate() { - super.validate(); if (innerContainerProperties() != null) { innerContainerProperties().validate(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/BlobInventoryPolicyInner.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/BlobInventoryPolicyInner.java index 122d8bf22a66..20a3d141dd14 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/BlobInventoryPolicyInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/BlobInventoryPolicyInner.java @@ -30,9 +30,9 @@ public final class BlobInventoryPolicyInner extends ProxyResource { private SystemData systemData; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -40,9 +40,9 @@ public final class BlobInventoryPolicyInner extends ProxyResource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of BlobInventoryPolicyInner class. @@ -69,13 +69,13 @@ public SystemData systemData() { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -89,13 +89,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/BlobServicePropertiesInner.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/BlobServicePropertiesInner.java index 9ca50ef4dbe6..f193d6a5ebe9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/BlobServicePropertiesInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/BlobServicePropertiesInner.java @@ -33,9 +33,9 @@ public final class BlobServicePropertiesInner extends ProxyResource { private Sku sku; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -43,9 +43,9 @@ public final class BlobServicePropertiesInner extends ProxyResource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of BlobServicePropertiesInner class. @@ -72,13 +72,13 @@ public Sku sku() { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -92,13 +92,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/DeletedAccountInner.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/DeletedAccountInner.java index 388cfe4a037a..2eb577857d02 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/DeletedAccountInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/DeletedAccountInner.java @@ -22,9 +22,9 @@ public final class DeletedAccountInner extends ProxyResource { private DeletedAccountProperties innerProperties; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -32,9 +32,9 @@ public final class DeletedAccountInner extends ProxyResource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of DeletedAccountInner class. @@ -52,13 +52,13 @@ private DeletedAccountProperties innerProperties() { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -72,13 +72,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/EncryptionScopeInner.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/EncryptionScopeInner.java index 857f3b4e2b4b..3a0c4db3896c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/EncryptionScopeInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/EncryptionScopeInner.java @@ -26,9 +26,9 @@ public final class EncryptionScopeInner extends ProxyResource { private EncryptionScopeProperties innerEncryptionScopeProperties; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -36,9 +36,9 @@ public final class EncryptionScopeInner extends ProxyResource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of EncryptionScopeInner class. @@ -56,13 +56,13 @@ private EncryptionScopeProperties innerEncryptionScopeProperties() { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -76,13 +76,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/FileServicePropertiesInner.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/FileServicePropertiesInner.java index 6d8e9f77205e..00a7e2544019 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/FileServicePropertiesInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/FileServicePropertiesInner.java @@ -31,9 +31,9 @@ public final class FileServicePropertiesInner extends ProxyResource { private Sku sku; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -41,9 +41,9 @@ public final class FileServicePropertiesInner extends ProxyResource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of FileServicePropertiesInner class. @@ -70,13 +70,13 @@ public Sku sku() { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -90,13 +90,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/FileServiceUsageInner.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/FileServiceUsageInner.java new file mode 100644 index 000000000000..78f3bd1dcc83 --- /dev/null +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/FileServiceUsageInner.java @@ -0,0 +1,139 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.storage.fluent.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.management.ProxyResource; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.storage.models.FileServiceUsageProperties; +import java.io.IOException; + +/** + * The usage of file service in storage account. + */ +@Immutable +public final class FileServiceUsageInner extends ProxyResource { + /* + * File service usage in storage account including account limits, file share limits and constants used in + * recommendations and bursting formula. + */ + private FileServiceUsageProperties properties; + + /* + * The type of the resource. + */ + private String type; + + /* + * The name of the resource. + */ + private String name; + + /* + * Fully qualified resource Id for the resource. + */ + private String id; + + /** + * Creates an instance of FileServiceUsageInner class. + */ + public FileServiceUsageInner() { + } + + /** + * Get the properties property: File service usage in storage account including account limits, file share limits + * and constants used in recommendations and bursting formula. + * + * @return the properties value. + */ + public FileServiceUsageProperties properties() { + return this.properties; + } + + /** + * Get the type property: The type of the resource. + * + * @return the type value. + */ + @Override + public String type() { + return this.type; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Override + public String name() { + return this.name; + } + + /** + * Get the id property: Fully qualified resource Id for the resource. + * + * @return the id value. + */ + @Override + public String id() { + return this.id; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (properties() != null) { + properties().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of FileServiceUsageInner from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of FileServiceUsageInner 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 FileServiceUsageInner. + */ + public static FileServiceUsageInner fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + FileServiceUsageInner deserializedFileServiceUsageInner = new FileServiceUsageInner(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + deserializedFileServiceUsageInner.id = reader.getString(); + } else if ("name".equals(fieldName)) { + deserializedFileServiceUsageInner.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedFileServiceUsageInner.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedFileServiceUsageInner.properties = FileServiceUsageProperties.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedFileServiceUsageInner; + }); + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/FileShareInner.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/FileShareInner.java index beb2d2e3c1a3..c206aac454ed 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/FileShareInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/FileShareInner.java @@ -10,6 +10,7 @@ import com.azure.json.JsonWriter; import com.azure.resourcemanager.storage.models.AzureEntityResource; import com.azure.resourcemanager.storage.models.EnabledProtocols; +import com.azure.resourcemanager.storage.models.FileSharePropertiesFileSharePaidBursting; import com.azure.resourcemanager.storage.models.LeaseDuration; import com.azure.resourcemanager.storage.models.LeaseState; import com.azure.resourcemanager.storage.models.LeaseStatus; @@ -32,24 +33,24 @@ public final class FileShareInner extends AzureEntityResource { private FileShareProperties innerFileShareProperties; /* - * Fully qualified resource Id for the resource. + * Resource Etag. */ - private String id; + private String etag; /* - * The name of the resource. + * The type of the resource. */ - private String name; + private String type; /* - * The type of the resource. + * The name of the resource. */ - private String type; + private String name; /* - * Resource Etag. + * Fully qualified resource Id for the resource. */ - private String etag; + private String id; /** * Creates an instance of FileShareInner class. @@ -67,43 +68,43 @@ private FileShareProperties innerFileShareProperties() { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the etag property: Resource Etag. * - * @return the id value. + * @return the etag value. */ @Override - public String id() { - return this.id; + public String etag() { + return this.etag; } /** - * Get the name property: The name of the resource. + * Get the type property: The type of the resource. * - * @return the name value. + * @return the type value. */ @Override - public String name() { - return this.name; + public String type() { + return this.type; } /** - * Get the type property: The type of the resource. + * Get the name property: The name of the resource. * - * @return the type value. + * @return the name value. */ @Override - public String type() { - return this.type; + public String name() { + return this.name; } /** - * Get the etag property: Resource Etag. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the etag value. + * @return the id value. */ @Override - public String etag() { - return this.etag; + public String id() { + return this.id; } /** @@ -139,8 +140,10 @@ public FileShareInner withMetadata(Map metadata) { } /** - * Get the shareQuota property: The maximum size of the share, in gigabytes. Must be greater than 0, and less than - * or equal to 5TB (5120). For Large File Shares, the maximum size is 102400. + * Get the shareQuota property: The provisioned size of the share, in gibibytes. Must be greater than 0, and less + * than or equal to 5TB (5120). For Large File Shares, the maximum size is 102400. For file shares created under + * Files Provisioned v2 account type, please refer to the GetFileServiceUsage API response for the minimum and + * maximum allowed provisioned storage size. * * @return the shareQuota value. */ @@ -149,8 +152,10 @@ public Integer shareQuota() { } /** - * Set the shareQuota property: The maximum size of the share, in gigabytes. Must be greater than 0, and less than - * or equal to 5TB (5120). For Large File Shares, the maximum size is 102400. + * Set the shareQuota property: The provisioned size of the share, in gibibytes. Must be greater than 0, and less + * than or equal to 5TB (5120). For Large File Shares, the maximum size is 102400. For file shares created under + * Files Provisioned v2 account type, please refer to the GetFileServiceUsage API response for the minimum and + * maximum allowed provisioned storage size. * * @param shareQuota the shareQuota value to set. * @return the FileShareInner object itself. @@ -163,6 +168,122 @@ public FileShareInner withShareQuota(Integer shareQuota) { return this; } + /** + * Get the provisionedIops property: The provisioned IOPS of the share. This property is only for file shares + * created under Files Provisioned v2 account type. Please refer to the GetFileServiceUsage API response for the + * minimum and maximum allowed value for provisioned IOPS. + * + * @return the provisionedIops value. + */ + public Integer provisionedIops() { + return this.innerFileShareProperties() == null ? null : this.innerFileShareProperties().provisionedIops(); + } + + /** + * Set the provisionedIops property: The provisioned IOPS of the share. This property is only for file shares + * created under Files Provisioned v2 account type. Please refer to the GetFileServiceUsage API response for the + * minimum and maximum allowed value for provisioned IOPS. + * + * @param provisionedIops the provisionedIops value to set. + * @return the FileShareInner object itself. + */ + public FileShareInner withProvisionedIops(Integer provisionedIops) { + if (this.innerFileShareProperties() == null) { + this.innerFileShareProperties = new FileShareProperties(); + } + this.innerFileShareProperties().withProvisionedIops(provisionedIops); + return this; + } + + /** + * Get the provisionedBandwidthMibps property: The provisioned bandwidth of the share, in mebibytes per second. This + * property is only for file shares created under Files Provisioned v2 account type. Please refer to the + * GetFileServiceUsage API response for the minimum and maximum allowed value for provisioned bandwidth. + * + * @return the provisionedBandwidthMibps value. + */ + public Integer provisionedBandwidthMibps() { + return this.innerFileShareProperties() == null + ? null + : this.innerFileShareProperties().provisionedBandwidthMibps(); + } + + /** + * Set the provisionedBandwidthMibps property: The provisioned bandwidth of the share, in mebibytes per second. This + * property is only for file shares created under Files Provisioned v2 account type. Please refer to the + * GetFileServiceUsage API response for the minimum and maximum allowed value for provisioned bandwidth. + * + * @param provisionedBandwidthMibps the provisionedBandwidthMibps value to set. + * @return the FileShareInner object itself. + */ + public FileShareInner withProvisionedBandwidthMibps(Integer provisionedBandwidthMibps) { + if (this.innerFileShareProperties() == null) { + this.innerFileShareProperties = new FileShareProperties(); + } + this.innerFileShareProperties().withProvisionedBandwidthMibps(provisionedBandwidthMibps); + return this; + } + + /** + * Get the includedBurstIops property: The calculated burst IOPS of the share. This property is only for file shares + * created under Files Provisioned v2 account type. + * + * @return the includedBurstIops value. + */ + public Integer includedBurstIops() { + return this.innerFileShareProperties() == null ? null : this.innerFileShareProperties().includedBurstIops(); + } + + /** + * Get the maxBurstCreditsForIops property: The calculated maximum burst credits for the share. This property is + * only for file shares created under Files Provisioned v2 account type. + * + * @return the maxBurstCreditsForIops value. + */ + public Long maxBurstCreditsForIops() { + return this.innerFileShareProperties() == null + ? null + : this.innerFileShareProperties().maxBurstCreditsForIops(); + } + + /** + * Get the nextAllowedQuotaDowngradeTime property: Returns the next allowed provisioned storage size downgrade time + * for the share. This property is only for file shares created under Files Provisioned v1 SSD and Files Provisioned + * v2 account type. + * + * @return the nextAllowedQuotaDowngradeTime value. + */ + public OffsetDateTime nextAllowedQuotaDowngradeTime() { + return this.innerFileShareProperties() == null + ? null + : this.innerFileShareProperties().nextAllowedQuotaDowngradeTime(); + } + + /** + * Get the nextAllowedProvisionedIopsDowngradeTime property: Returns the next allowed provisioned IOPS downgrade + * time for the share. This property is only for file shares created under Files Provisioned v2 account type. + * + * @return the nextAllowedProvisionedIopsDowngradeTime value. + */ + public OffsetDateTime nextAllowedProvisionedIopsDowngradeTime() { + return this.innerFileShareProperties() == null + ? null + : this.innerFileShareProperties().nextAllowedProvisionedIopsDowngradeTime(); + } + + /** + * Get the nextAllowedProvisionedBandwidthDowngradeTime property: Returns the next allowed provisioned bandwidth + * downgrade time for the share. This property is only for file shares created under Files Provisioned v2 account + * type. + * + * @return the nextAllowedProvisionedBandwidthDowngradeTime value. + */ + public OffsetDateTime nextAllowedProvisionedBandwidthDowngradeTime() { + return this.innerFileShareProperties() == null + ? null + : this.innerFileShareProperties().nextAllowedProvisionedBandwidthDowngradeTime(); + } + /** * Get the enabledProtocols property: The authentication protocol that is used for the file share. Can only be * specified when creating a share. @@ -363,6 +484,29 @@ public OffsetDateTime snapshotTime() { return this.innerFileShareProperties() == null ? null : this.innerFileShareProperties().snapshotTime(); } + /** + * Get the fileSharePaidBursting property: File Share Paid Bursting properties. + * + * @return the fileSharePaidBursting value. + */ + public FileSharePropertiesFileSharePaidBursting fileSharePaidBursting() { + return this.innerFileShareProperties() == null ? null : this.innerFileShareProperties().fileSharePaidBursting(); + } + + /** + * Set the fileSharePaidBursting property: File Share Paid Bursting properties. + * + * @param fileSharePaidBursting the fileSharePaidBursting value to set. + * @return the FileShareInner object itself. + */ + public FileShareInner withFileSharePaidBursting(FileSharePropertiesFileSharePaidBursting fileSharePaidBursting) { + if (this.innerFileShareProperties() == null) { + this.innerFileShareProperties = new FileShareProperties(); + } + this.innerFileShareProperties().withFileSharePaidBursting(fileSharePaidBursting); + return this; + } + /** * Validates the instance. * @@ -370,7 +514,6 @@ public OffsetDateTime snapshotTime() { */ @Override public void validate() { - super.validate(); if (innerFileShareProperties() != null) { innerFileShareProperties().validate(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/FileShareItemInner.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/FileShareItemInner.java index e3a6fc91ba44..9e2175f06c93 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/FileShareItemInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/FileShareItemInner.java @@ -10,6 +10,7 @@ import com.azure.json.JsonWriter; import com.azure.resourcemanager.storage.models.AzureEntityResource; import com.azure.resourcemanager.storage.models.EnabledProtocols; +import com.azure.resourcemanager.storage.models.FileSharePropertiesFileSharePaidBursting; import com.azure.resourcemanager.storage.models.LeaseDuration; import com.azure.resourcemanager.storage.models.LeaseState; import com.azure.resourcemanager.storage.models.LeaseStatus; @@ -32,24 +33,24 @@ public final class FileShareItemInner extends AzureEntityResource { private FileShareProperties innerProperties; /* - * Fully qualified resource Id for the resource. + * Resource Etag. */ - private String id; + private String etag; /* - * The name of the resource. + * The type of the resource. */ - private String name; + private String type; /* - * The type of the resource. + * The name of the resource. */ - private String type; + private String name; /* - * Resource Etag. + * Fully qualified resource Id for the resource. */ - private String etag; + private String id; /** * Creates an instance of FileShareItemInner class. @@ -67,43 +68,43 @@ private FileShareProperties innerProperties() { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the etag property: Resource Etag. * - * @return the id value. + * @return the etag value. */ @Override - public String id() { - return this.id; + public String etag() { + return this.etag; } /** - * Get the name property: The name of the resource. + * Get the type property: The type of the resource. * - * @return the name value. + * @return the type value. */ @Override - public String name() { - return this.name; + public String type() { + return this.type; } /** - * Get the type property: The type of the resource. + * Get the name property: The name of the resource. * - * @return the type value. + * @return the name value. */ @Override - public String type() { - return this.type; + public String name() { + return this.name; } /** - * Get the etag property: Resource Etag. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the etag value. + * @return the id value. */ @Override - public String etag() { - return this.etag; + public String id() { + return this.id; } /** @@ -139,8 +140,10 @@ public FileShareItemInner withMetadata(Map metadata) { } /** - * Get the shareQuota property: The maximum size of the share, in gigabytes. Must be greater than 0, and less than - * or equal to 5TB (5120). For Large File Shares, the maximum size is 102400. + * Get the shareQuota property: The provisioned size of the share, in gibibytes. Must be greater than 0, and less + * than or equal to 5TB (5120). For Large File Shares, the maximum size is 102400. For file shares created under + * Files Provisioned v2 account type, please refer to the GetFileServiceUsage API response for the minimum and + * maximum allowed provisioned storage size. * * @return the shareQuota value. */ @@ -149,8 +152,10 @@ public Integer shareQuota() { } /** - * Set the shareQuota property: The maximum size of the share, in gigabytes. Must be greater than 0, and less than - * or equal to 5TB (5120). For Large File Shares, the maximum size is 102400. + * Set the shareQuota property: The provisioned size of the share, in gibibytes. Must be greater than 0, and less + * than or equal to 5TB (5120). For Large File Shares, the maximum size is 102400. For file shares created under + * Files Provisioned v2 account type, please refer to the GetFileServiceUsage API response for the minimum and + * maximum allowed provisioned storage size. * * @param shareQuota the shareQuota value to set. * @return the FileShareItemInner object itself. @@ -163,6 +168,114 @@ public FileShareItemInner withShareQuota(Integer shareQuota) { return this; } + /** + * Get the provisionedIops property: The provisioned IOPS of the share. This property is only for file shares + * created under Files Provisioned v2 account type. Please refer to the GetFileServiceUsage API response for the + * minimum and maximum allowed value for provisioned IOPS. + * + * @return the provisionedIops value. + */ + public Integer provisionedIops() { + return this.innerProperties() == null ? null : this.innerProperties().provisionedIops(); + } + + /** + * Set the provisionedIops property: The provisioned IOPS of the share. This property is only for file shares + * created under Files Provisioned v2 account type. Please refer to the GetFileServiceUsage API response for the + * minimum and maximum allowed value for provisioned IOPS. + * + * @param provisionedIops the provisionedIops value to set. + * @return the FileShareItemInner object itself. + */ + public FileShareItemInner withProvisionedIops(Integer provisionedIops) { + if (this.innerProperties() == null) { + this.innerProperties = new FileShareProperties(); + } + this.innerProperties().withProvisionedIops(provisionedIops); + return this; + } + + /** + * Get the provisionedBandwidthMibps property: The provisioned bandwidth of the share, in mebibytes per second. This + * property is only for file shares created under Files Provisioned v2 account type. Please refer to the + * GetFileServiceUsage API response for the minimum and maximum allowed value for provisioned bandwidth. + * + * @return the provisionedBandwidthMibps value. + */ + public Integer provisionedBandwidthMibps() { + return this.innerProperties() == null ? null : this.innerProperties().provisionedBandwidthMibps(); + } + + /** + * Set the provisionedBandwidthMibps property: The provisioned bandwidth of the share, in mebibytes per second. This + * property is only for file shares created under Files Provisioned v2 account type. Please refer to the + * GetFileServiceUsage API response for the minimum and maximum allowed value for provisioned bandwidth. + * + * @param provisionedBandwidthMibps the provisionedBandwidthMibps value to set. + * @return the FileShareItemInner object itself. + */ + public FileShareItemInner withProvisionedBandwidthMibps(Integer provisionedBandwidthMibps) { + if (this.innerProperties() == null) { + this.innerProperties = new FileShareProperties(); + } + this.innerProperties().withProvisionedBandwidthMibps(provisionedBandwidthMibps); + return this; + } + + /** + * Get the includedBurstIops property: The calculated burst IOPS of the share. This property is only for file shares + * created under Files Provisioned v2 account type. + * + * @return the includedBurstIops value. + */ + public Integer includedBurstIops() { + return this.innerProperties() == null ? null : this.innerProperties().includedBurstIops(); + } + + /** + * Get the maxBurstCreditsForIops property: The calculated maximum burst credits for the share. This property is + * only for file shares created under Files Provisioned v2 account type. + * + * @return the maxBurstCreditsForIops value. + */ + public Long maxBurstCreditsForIops() { + return this.innerProperties() == null ? null : this.innerProperties().maxBurstCreditsForIops(); + } + + /** + * Get the nextAllowedQuotaDowngradeTime property: Returns the next allowed provisioned storage size downgrade time + * for the share. This property is only for file shares created under Files Provisioned v1 SSD and Files Provisioned + * v2 account type. + * + * @return the nextAllowedQuotaDowngradeTime value. + */ + public OffsetDateTime nextAllowedQuotaDowngradeTime() { + return this.innerProperties() == null ? null : this.innerProperties().nextAllowedQuotaDowngradeTime(); + } + + /** + * Get the nextAllowedProvisionedIopsDowngradeTime property: Returns the next allowed provisioned IOPS downgrade + * time for the share. This property is only for file shares created under Files Provisioned v2 account type. + * + * @return the nextAllowedProvisionedIopsDowngradeTime value. + */ + public OffsetDateTime nextAllowedProvisionedIopsDowngradeTime() { + return this.innerProperties() == null ? null : this.innerProperties().nextAllowedProvisionedIopsDowngradeTime(); + } + + /** + * Get the nextAllowedProvisionedBandwidthDowngradeTime property: Returns the next allowed provisioned bandwidth + * downgrade time for the share. This property is only for file shares created under Files Provisioned v2 account + * type. + * + * @return the nextAllowedProvisionedBandwidthDowngradeTime value. + */ + public OffsetDateTime nextAllowedProvisionedBandwidthDowngradeTime() { + return this.innerProperties() == null + ? null + : this.innerProperties().nextAllowedProvisionedBandwidthDowngradeTime(); + } + /** * Get the enabledProtocols property: The authentication protocol that is used for the file share. Can only be * specified when creating a share. @@ -361,6 +474,30 @@ public OffsetDateTime snapshotTime() { return this.innerProperties() == null ? null : this.innerProperties().snapshotTime(); } + /** + * Get the fileSharePaidBursting property: File Share Paid Bursting properties. + * + * @return the fileSharePaidBursting value. + */ + public FileSharePropertiesFileSharePaidBursting fileSharePaidBursting() { + return this.innerProperties() == null ? null : this.innerProperties().fileSharePaidBursting(); + } + + /** + * Set the fileSharePaidBursting property: File Share Paid Bursting properties. + * + * @param fileSharePaidBursting the fileSharePaidBursting value to set. + * @return the FileShareItemInner object itself. + */ + public FileShareItemInner + withFileSharePaidBursting(FileSharePropertiesFileSharePaidBursting fileSharePaidBursting) { + if (this.innerProperties() == null) { + this.innerProperties = new FileShareProperties(); + } + this.innerProperties().withFileSharePaidBursting(fileSharePaidBursting); + return this; + } + /** * Validates the instance. * @@ -368,7 +505,6 @@ public OffsetDateTime snapshotTime() { */ @Override public void validate() { - super.validate(); if (innerProperties() != null) { innerProperties().validate(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/FileShareProperties.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/FileShareProperties.java index fa35729b14b0..3f2c389b6d13 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/FileShareProperties.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/FileShareProperties.java @@ -6,11 +6,13 @@ import com.azure.core.annotation.Fluent; import com.azure.core.util.CoreUtils; +import com.azure.core.util.DateTimeRfc1123; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import com.azure.resourcemanager.storage.models.EnabledProtocols; +import com.azure.resourcemanager.storage.models.FileSharePropertiesFileSharePaidBursting; import com.azure.resourcemanager.storage.models.LeaseDuration; import com.azure.resourcemanager.storage.models.LeaseState; import com.azure.resourcemanager.storage.models.LeaseStatus; @@ -38,11 +40,57 @@ public final class FileShareProperties implements JsonSerializable metadata; /* - * The maximum size of the share, in gigabytes. Must be greater than 0, and less than or equal to 5TB (5120). For - * Large File Shares, the maximum size is 102400. + * The provisioned size of the share, in gibibytes. Must be greater than 0, and less than or equal to 5TB (5120). + * For Large File Shares, the maximum size is 102400. For file shares created under Files Provisioned v2 account + * type, please refer to the GetFileServiceUsage API response for the minimum and maximum allowed provisioned + * storage size. */ private Integer shareQuota; + /* + * The provisioned IOPS of the share. This property is only for file shares created under Files Provisioned v2 + * account type. Please refer to the GetFileServiceUsage API response for the minimum and maximum allowed value for + * provisioned IOPS. + */ + private Integer provisionedIops; + + /* + * The provisioned bandwidth of the share, in mebibytes per second. This property is only for file shares created + * under Files Provisioned v2 account type. Please refer to the GetFileServiceUsage API response for the minimum and + * maximum allowed value for provisioned bandwidth. + */ + private Integer provisionedBandwidthMibps; + + /* + * The calculated burst IOPS of the share. This property is only for file shares created under Files Provisioned v2 + * account type. + */ + private Integer includedBurstIops; + + /* + * The calculated maximum burst credits for the share. This property is only for file shares created under Files + * Provisioned v2 account type. + */ + private Long maxBurstCreditsForIops; + + /* + * Returns the next allowed provisioned storage size downgrade time for the share. This property is only for file + * shares created under Files Provisioned v1 SSD and Files Provisioned v2 account type + */ + private DateTimeRfc1123 nextAllowedQuotaDowngradeTime; + + /* + * Returns the next allowed provisioned IOPS downgrade time for the share. This property is only for file shares + * created under Files Provisioned v2 account type. + */ + private DateTimeRfc1123 nextAllowedProvisionedIopsDowngradeTime; + + /* + * Returns the next allowed provisioned bandwidth downgrade time for the share. This property is only for file + * shares created under Files Provisioned v2 account type. + */ + private DateTimeRfc1123 nextAllowedProvisionedBandwidthDowngradeTime; + /* * The authentication protocol that is used for the file share. Can only be specified when creating a share. */ @@ -120,6 +168,11 @@ public final class FileShareProperties implements JsonSerializable metadata) { } /** - * Get the shareQuota property: The maximum size of the share, in gigabytes. Must be greater than 0, and less than - * or equal to 5TB (5120). For Large File Shares, the maximum size is 102400. + * Get the shareQuota property: The provisioned size of the share, in gibibytes. Must be greater than 0, and less + * than or equal to 5TB (5120). For Large File Shares, the maximum size is 102400. For file shares created under + * Files Provisioned v2 account type, please refer to the GetFileServiceUsage API response for the minimum and + * maximum allowed provisioned storage size. * * @return the shareQuota value. */ @@ -166,8 +221,10 @@ public Integer shareQuota() { } /** - * Set the shareQuota property: The maximum size of the share, in gigabytes. Must be greater than 0, and less than - * or equal to 5TB (5120). For Large File Shares, the maximum size is 102400. + * Set the shareQuota property: The provisioned size of the share, in gibibytes. Must be greater than 0, and less + * than or equal to 5TB (5120). For Large File Shares, the maximum size is 102400. For file shares created under + * Files Provisioned v2 account type, please refer to the GetFileServiceUsage API response for the minimum and + * maximum allowed provisioned storage size. * * @param shareQuota the shareQuota value to set. * @return the FileShareProperties object itself. @@ -177,6 +234,115 @@ public FileShareProperties withShareQuota(Integer shareQuota) { return this; } + /** + * Get the provisionedIops property: The provisioned IOPS of the share. This property is only for file shares + * created under Files Provisioned v2 account type. Please refer to the GetFileServiceUsage API response for the + * minimum and maximum allowed value for provisioned IOPS. + * + * @return the provisionedIops value. + */ + public Integer provisionedIops() { + return this.provisionedIops; + } + + /** + * Set the provisionedIops property: The provisioned IOPS of the share. This property is only for file shares + * created under Files Provisioned v2 account type. Please refer to the GetFileServiceUsage API response for the + * minimum and maximum allowed value for provisioned IOPS. + * + * @param provisionedIops the provisionedIops value to set. + * @return the FileShareProperties object itself. + */ + public FileShareProperties withProvisionedIops(Integer provisionedIops) { + this.provisionedIops = provisionedIops; + return this; + } + + /** + * Get the provisionedBandwidthMibps property: The provisioned bandwidth of the share, in mebibytes per second. This + * property is only for file shares created under Files Provisioned v2 account type. Please refer to the + * GetFileServiceUsage API response for the minimum and maximum allowed value for provisioned bandwidth. + * + * @return the provisionedBandwidthMibps value. + */ + public Integer provisionedBandwidthMibps() { + return this.provisionedBandwidthMibps; + } + + /** + * Set the provisionedBandwidthMibps property: The provisioned bandwidth of the share, in mebibytes per second. This + * property is only for file shares created under Files Provisioned v2 account type. Please refer to the + * GetFileServiceUsage API response for the minimum and maximum allowed value for provisioned bandwidth. + * + * @param provisionedBandwidthMibps the provisionedBandwidthMibps value to set. + * @return the FileShareProperties object itself. + */ + public FileShareProperties withProvisionedBandwidthMibps(Integer provisionedBandwidthMibps) { + this.provisionedBandwidthMibps = provisionedBandwidthMibps; + return this; + } + + /** + * Get the includedBurstIops property: The calculated burst IOPS of the share. This property is only for file shares + * created under Files Provisioned v2 account type. + * + * @return the includedBurstIops value. + */ + public Integer includedBurstIops() { + return this.includedBurstIops; + } + + /** + * Get the maxBurstCreditsForIops property: The calculated maximum burst credits for the share. This property is + * only for file shares created under Files Provisioned v2 account type. + * + * @return the maxBurstCreditsForIops value. + */ + public Long maxBurstCreditsForIops() { + return this.maxBurstCreditsForIops; + } + + /** + * Get the nextAllowedQuotaDowngradeTime property: Returns the next allowed provisioned storage size downgrade time + * for the share. This property is only for file shares created under Files Provisioned v1 SSD and Files Provisioned + * v2 account type. + * + * @return the nextAllowedQuotaDowngradeTime value. + */ + public OffsetDateTime nextAllowedQuotaDowngradeTime() { + if (this.nextAllowedQuotaDowngradeTime == null) { + return null; + } + return this.nextAllowedQuotaDowngradeTime.getDateTime(); + } + + /** + * Get the nextAllowedProvisionedIopsDowngradeTime property: Returns the next allowed provisioned IOPS downgrade + * time for the share. This property is only for file shares created under Files Provisioned v2 account type. + * + * @return the nextAllowedProvisionedIopsDowngradeTime value. + */ + public OffsetDateTime nextAllowedProvisionedIopsDowngradeTime() { + if (this.nextAllowedProvisionedIopsDowngradeTime == null) { + return null; + } + return this.nextAllowedProvisionedIopsDowngradeTime.getDateTime(); + } + + /** + * Get the nextAllowedProvisionedBandwidthDowngradeTime property: Returns the next allowed provisioned bandwidth + * downgrade time for the share. This property is only for file shares created under Files Provisioned v2 account + * type. + * + * @return the nextAllowedProvisionedBandwidthDowngradeTime value. + */ + public OffsetDateTime nextAllowedProvisionedBandwidthDowngradeTime() { + if (this.nextAllowedProvisionedBandwidthDowngradeTime == null) { + return null; + } + return this.nextAllowedProvisionedBandwidthDowngradeTime.getDateTime(); + } + /** * Get the enabledProtocols property: The authentication protocol that is used for the file share. Can only be * specified when creating a share. @@ -363,6 +529,27 @@ public OffsetDateTime snapshotTime() { return this.snapshotTime; } + /** + * Get the fileSharePaidBursting property: File Share Paid Bursting properties. + * + * @return the fileSharePaidBursting value. + */ + public FileSharePropertiesFileSharePaidBursting fileSharePaidBursting() { + return this.fileSharePaidBursting; + } + + /** + * Set the fileSharePaidBursting property: File Share Paid Bursting properties. + * + * @param fileSharePaidBursting the fileSharePaidBursting value to set. + * @return the FileShareProperties object itself. + */ + public FileShareProperties + withFileSharePaidBursting(FileSharePropertiesFileSharePaidBursting fileSharePaidBursting) { + this.fileSharePaidBursting = fileSharePaidBursting; + return this; + } + /** * Validates the instance. * @@ -372,6 +559,9 @@ public void validate() { if (signedIdentifiers() != null) { signedIdentifiers().forEach(e -> e.validate()); } + if (fileSharePaidBursting() != null) { + fileSharePaidBursting().validate(); + } } /** @@ -382,12 +572,15 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeMapField("metadata", this.metadata, (writer, element) -> writer.writeString(element)); jsonWriter.writeNumberField("shareQuota", this.shareQuota); + jsonWriter.writeNumberField("provisionedIops", this.provisionedIops); + jsonWriter.writeNumberField("provisionedBandwidthMibps", this.provisionedBandwidthMibps); jsonWriter.writeStringField("enabledProtocols", this.enabledProtocols == null ? null : this.enabledProtocols.toString()); jsonWriter.writeStringField("rootSquash", this.rootSquash == null ? null : this.rootSquash.toString()); jsonWriter.writeStringField("accessTier", this.accessTier == null ? null : this.accessTier.toString()); jsonWriter.writeArrayField("signedIdentifiers", this.signedIdentifiers, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeJsonField("fileSharePaidBursting", this.fileSharePaidBursting); return jsonWriter.writeEndObject(); } @@ -414,6 +607,23 @@ public static FileShareProperties fromJson(JsonReader jsonReader) throws IOExcep deserializedFileShareProperties.metadata = metadata; } else if ("shareQuota".equals(fieldName)) { deserializedFileShareProperties.shareQuota = reader.getNullable(JsonReader::getInt); + } else if ("provisionedIops".equals(fieldName)) { + deserializedFileShareProperties.provisionedIops = reader.getNullable(JsonReader::getInt); + } else if ("provisionedBandwidthMibps".equals(fieldName)) { + deserializedFileShareProperties.provisionedBandwidthMibps = reader.getNullable(JsonReader::getInt); + } else if ("includedBurstIops".equals(fieldName)) { + deserializedFileShareProperties.includedBurstIops = reader.getNullable(JsonReader::getInt); + } else if ("maxBurstCreditsForIops".equals(fieldName)) { + deserializedFileShareProperties.maxBurstCreditsForIops = reader.getNullable(JsonReader::getLong); + } else if ("nextAllowedQuotaDowngradeTime".equals(fieldName)) { + deserializedFileShareProperties.nextAllowedQuotaDowngradeTime + = reader.getNullable(nonNullReader -> new DateTimeRfc1123(nonNullReader.getString())); + } else if ("nextAllowedProvisionedIopsDowngradeTime".equals(fieldName)) { + deserializedFileShareProperties.nextAllowedProvisionedIopsDowngradeTime + = reader.getNullable(nonNullReader -> new DateTimeRfc1123(nonNullReader.getString())); + } else if ("nextAllowedProvisionedBandwidthDowngradeTime".equals(fieldName)) { + deserializedFileShareProperties.nextAllowedProvisionedBandwidthDowngradeTime + = reader.getNullable(nonNullReader -> new DateTimeRfc1123(nonNullReader.getString())); } else if ("enabledProtocols".equals(fieldName)) { deserializedFileShareProperties.enabledProtocols = EnabledProtocols.fromString(reader.getString()); } else if ("rootSquash".equals(fieldName)) { @@ -449,6 +659,9 @@ public static FileShareProperties fromJson(JsonReader jsonReader) throws IOExcep } else if ("snapshotTime".equals(fieldName)) { deserializedFileShareProperties.snapshotTime = reader .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("fileSharePaidBursting".equals(fieldName)) { + deserializedFileShareProperties.fileSharePaidBursting + = FileSharePropertiesFileSharePaidBursting.fromJson(reader); } else { reader.skipChildren(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/ImmutabilityPolicyInner.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/ImmutabilityPolicyInner.java index 496f7301f538..56e7b02bf993 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/ImmutabilityPolicyInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/ImmutabilityPolicyInner.java @@ -24,24 +24,24 @@ public final class ImmutabilityPolicyInner extends AzureEntityResource { private ImmutabilityPolicyProperty innerProperties = new ImmutabilityPolicyProperty(); /* - * Fully qualified resource Id for the resource. + * Resource Etag. */ - private String id; + private String etag; /* - * The name of the resource. + * The type of the resource. */ - private String name; + private String type; /* - * The type of the resource. + * The name of the resource. */ - private String type; + private String name; /* - * Resource Etag. + * Fully qualified resource Id for the resource. */ - private String etag; + private String id; /** * Creates an instance of ImmutabilityPolicyInner class. @@ -59,43 +59,43 @@ private ImmutabilityPolicyProperty innerProperties() { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the etag property: Resource Etag. * - * @return the id value. + * @return the etag value. */ @Override - public String id() { - return this.id; + public String etag() { + return this.etag; } /** - * Get the name property: The name of the resource. + * Get the type property: The type of the resource. * - * @return the name value. + * @return the type value. */ @Override - public String name() { - return this.name; + public String type() { + return this.type; } /** - * Get the type property: The type of the resource. + * Get the name property: The name of the resource. * - * @return the type value. + * @return the name value. */ @Override - public String type() { - return this.type; + public String name() { + return this.name; } /** - * Get the etag property: Resource Etag. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the etag value. + * @return the id value. */ @Override - public String etag() { - return this.etag; + public String id() { + return this.id; } /** @@ -201,7 +201,6 @@ public ImmutabilityPolicyInner withAllowProtectedAppendWritesAll(Boolean allowPr */ @Override public void validate() { - super.validate(); if (innerProperties() == null) { throw LOGGER.atError() .log(new IllegalArgumentException( diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/ListContainerItemInner.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/ListContainerItemInner.java index 935c8720eb36..3e9653af86d8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/ListContainerItemInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/ListContainerItemInner.java @@ -31,24 +31,24 @@ public final class ListContainerItemInner extends AzureEntityResource { private ContainerProperties innerProperties; /* - * Fully qualified resource Id for the resource. + * Resource Etag. */ - private String id; + private String etag; /* - * The name of the resource. + * The type of the resource. */ - private String name; + private String type; /* - * The type of the resource. + * The name of the resource. */ - private String type; + private String name; /* - * Resource Etag. + * Fully qualified resource Id for the resource. */ - private String etag; + private String id; /** * Creates an instance of ListContainerItemInner class. @@ -66,43 +66,43 @@ private ContainerProperties innerProperties() { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the etag property: Resource Etag. * - * @return the id value. + * @return the etag value. */ @Override - public String id() { - return this.id; + public String etag() { + return this.etag; } /** - * Get the name property: The name of the resource. + * Get the type property: The type of the resource. * - * @return the name value. + * @return the type value. */ @Override - public String name() { - return this.name; + public String type() { + return this.type; } /** - * Get the type property: The type of the resource. + * Get the name property: The name of the resource. * - * @return the type value. + * @return the name value. */ @Override - public String type() { - return this.type; + public String name() { + return this.name; } /** - * Get the etag property: Resource Etag. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the etag value. + * @return the id value. */ @Override - public String etag() { - return this.etag; + public String id() { + return this.id; } /** @@ -393,7 +393,6 @@ public ListContainerItemInner withEnableNfsV3AllSquash(Boolean enableNfsV3AllSqu */ @Override public void validate() { - super.validate(); if (innerProperties() != null) { innerProperties().validate(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/ListQueueInner.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/ListQueueInner.java index 01ddcea0a50f..00352859c2ba 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/ListQueueInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/ListQueueInner.java @@ -23,9 +23,9 @@ public final class ListQueueInner extends ProxyResource { private ListQueueProperties innerQueueProperties; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -33,9 +33,9 @@ public final class ListQueueInner extends ProxyResource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of ListQueueInner class. @@ -53,13 +53,13 @@ private ListQueueProperties innerQueueProperties() { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -73,13 +73,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/LocalUserInner.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/LocalUserInner.java index f238d1f3211c..03c9fe086fcb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/LocalUserInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/LocalUserInner.java @@ -31,9 +31,9 @@ public final class LocalUserInner extends ProxyResource { private SystemData systemData; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -41,9 +41,9 @@ public final class LocalUserInner extends ProxyResource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of LocalUserInner class. @@ -70,13 +70,13 @@ public SystemData systemData() { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -90,13 +90,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/ManagementPolicyInner.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/ManagementPolicyInner.java index f60f4d12e9e8..ac1786be9a06 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/ManagementPolicyInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/ManagementPolicyInner.java @@ -24,9 +24,9 @@ public final class ManagementPolicyInner extends ProxyResource { private ManagementPolicyProperties innerProperties; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -34,9 +34,9 @@ public final class ManagementPolicyInner extends ProxyResource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of ManagementPolicyInner class. @@ -54,13 +54,13 @@ private ManagementPolicyProperties innerProperties() { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -74,13 +74,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/NetworkSecurityPerimeterConfigurationInner.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/NetworkSecurityPerimeterConfigurationInner.java index 68cc83fc8d6c..26241cfc7a99 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/NetworkSecurityPerimeterConfigurationInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/NetworkSecurityPerimeterConfigurationInner.java @@ -34,9 +34,9 @@ public final class NetworkSecurityPerimeterConfigurationInner extends ProxyResou private SystemData systemData; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -44,9 +44,9 @@ public final class NetworkSecurityPerimeterConfigurationInner extends ProxyResou private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of NetworkSecurityPerimeterConfigurationInner class. @@ -73,13 +73,13 @@ public SystemData systemData() { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -93,13 +93,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/ObjectReplicationPolicyInner.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/ObjectReplicationPolicyInner.java index a2cb454b78d0..af26477d78f5 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/ObjectReplicationPolicyInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/ObjectReplicationPolicyInner.java @@ -9,6 +9,7 @@ import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; +import com.azure.resourcemanager.storage.models.ObjectReplicationPolicyPropertiesMetrics; import com.azure.resourcemanager.storage.models.ObjectReplicationPolicyRule; import java.io.IOException; import java.time.OffsetDateTime; @@ -25,9 +26,9 @@ public final class ObjectReplicationPolicyInner extends ProxyResource { private ObjectReplicationPolicyProperties innerProperties; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -35,9 +36,9 @@ public final class ObjectReplicationPolicyInner extends ProxyResource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of ObjectReplicationPolicyInner class. @@ -55,13 +56,13 @@ private ObjectReplicationPolicyProperties innerProperties() { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -75,13 +76,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** @@ -175,6 +176,29 @@ public ObjectReplicationPolicyInner withRules(List return this; } + /** + * Get the metrics property: Optional. The object replication policy metrics feature options. + * + * @return the metrics value. + */ + public ObjectReplicationPolicyPropertiesMetrics metrics() { + return this.innerProperties() == null ? null : this.innerProperties().metrics(); + } + + /** + * Set the metrics property: Optional. The object replication policy metrics feature options. + * + * @param metrics the metrics value to set. + * @return the ObjectReplicationPolicyInner object itself. + */ + public ObjectReplicationPolicyInner withMetrics(ObjectReplicationPolicyPropertiesMetrics metrics) { + if (this.innerProperties() == null) { + this.innerProperties = new ObjectReplicationPolicyProperties(); + } + this.innerProperties().withMetrics(metrics); + return this; + } + /** * Validates the instance. * diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/ObjectReplicationPolicyProperties.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/ObjectReplicationPolicyProperties.java index 3ac79178a733..fd7d6102a5bb 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/ObjectReplicationPolicyProperties.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/ObjectReplicationPolicyProperties.java @@ -11,6 +11,7 @@ import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; +import com.azure.resourcemanager.storage.models.ObjectReplicationPolicyPropertiesMetrics; import com.azure.resourcemanager.storage.models.ObjectReplicationPolicyRule; import java.io.IOException; import java.time.OffsetDateTime; @@ -46,6 +47,11 @@ public final class ObjectReplicationPolicyProperties implements JsonSerializable */ private List rules; + /* + * Optional. The object replication policy metrics feature options. + */ + private ObjectReplicationPolicyPropertiesMetrics metrics; + /** * Creates an instance of ObjectReplicationPolicyProperties class. */ @@ -134,6 +140,26 @@ public ObjectReplicationPolicyProperties withRules(List e.validate()); } + if (metrics() != null) { + metrics().validate(); + } } private static final ClientLogger LOGGER = new ClientLogger(ObjectReplicationPolicyProperties.class); @@ -166,6 +195,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStringField("sourceAccount", this.sourceAccount); jsonWriter.writeStringField("destinationAccount", this.destinationAccount); jsonWriter.writeArrayField("rules", this.rules, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeJsonField("metrics", this.metrics); return jsonWriter.writeEndObject(); } @@ -199,6 +229,9 @@ public static ObjectReplicationPolicyProperties fromJson(JsonReader jsonReader) List rules = reader.readArray(reader1 -> ObjectReplicationPolicyRule.fromJson(reader1)); deserializedObjectReplicationPolicyProperties.rules = rules; + } else if ("metrics".equals(fieldName)) { + deserializedObjectReplicationPolicyProperties.metrics + = ObjectReplicationPolicyPropertiesMetrics.fromJson(reader); } else { reader.skipChildren(); } diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/PrivateEndpointConnectionInner.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/PrivateEndpointConnectionInner.java index 3115b0fce8f6..7e450b1caa73 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/PrivateEndpointConnectionInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/PrivateEndpointConnectionInner.java @@ -25,9 +25,9 @@ public final class PrivateEndpointConnectionInner extends ProxyResource { private PrivateEndpointConnectionProperties innerProperties; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -35,9 +35,9 @@ public final class PrivateEndpointConnectionInner extends ProxyResource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of PrivateEndpointConnectionInner class. @@ -55,13 +55,13 @@ private PrivateEndpointConnectionProperties innerProperties() { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -75,13 +75,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/QueueServicePropertiesInner.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/QueueServicePropertiesInner.java index 8bdd2d0bb8d7..3f5049f5a11b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/QueueServicePropertiesInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/QueueServicePropertiesInner.java @@ -23,9 +23,9 @@ public final class QueueServicePropertiesInner extends ProxyResource { private QueueServicePropertiesProperties innerQueueServiceProperties; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -33,9 +33,9 @@ public final class QueueServicePropertiesInner extends ProxyResource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of QueueServicePropertiesInner class. @@ -53,13 +53,13 @@ private QueueServicePropertiesProperties innerQueueServiceProperties() { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -73,13 +73,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/StorageAccountInner.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/StorageAccountInner.java index 5259925bbecb..b142ec12bdad 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/StorageAccountInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/StorageAccountInner.java @@ -69,9 +69,9 @@ public final class StorageAccountInner extends Resource { private StorageAccountPropertiesInner innerProperties; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -79,9 +79,9 @@ public final class StorageAccountInner extends Resource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of StorageAccountInner class. @@ -157,13 +157,13 @@ private StorageAccountPropertiesInner innerProperties() { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -177,13 +177,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/StorageQueueInner.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/StorageQueueInner.java index 3ecdedb520f6..f7494c9cabc0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/StorageQueueInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/StorageQueueInner.java @@ -23,9 +23,9 @@ public final class StorageQueueInner extends ProxyResource { private QueueProperties innerQueueProperties; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -33,9 +33,9 @@ public final class StorageQueueInner extends ProxyResource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of StorageQueueInner class. @@ -53,13 +53,13 @@ private QueueProperties innerQueueProperties() { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -73,13 +73,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/StorageTaskAssignmentInner.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/StorageTaskAssignmentInner.java index ad077d4ac8a5..6a5a942a73b0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/StorageTaskAssignmentInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/StorageTaskAssignmentInner.java @@ -24,9 +24,9 @@ public final class StorageTaskAssignmentInner extends ProxyResource { private StorageTaskAssignmentProperties properties; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -34,9 +34,9 @@ public final class StorageTaskAssignmentInner extends ProxyResource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of StorageTaskAssignmentInner class. @@ -65,13 +65,13 @@ public StorageTaskAssignmentInner withProperties(StorageTaskAssignmentProperties } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -85,13 +85,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/StorageTaskReportInstanceInner.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/StorageTaskReportInstanceInner.java index a0cca9970e1c..83303b94b1ed 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/StorageTaskReportInstanceInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/StorageTaskReportInstanceInner.java @@ -23,9 +23,9 @@ public final class StorageTaskReportInstanceInner extends ProxyResource { private StorageTaskReportProperties properties; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -33,9 +33,9 @@ public final class StorageTaskReportInstanceInner extends ProxyResource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of StorageTaskReportInstanceInner class. @@ -64,13 +64,13 @@ public StorageTaskReportInstanceInner withProperties(StorageTaskReportProperties } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -84,13 +84,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/TableInner.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/TableInner.java index 5429cee7702d..c2ca6c41f94a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/TableInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/TableInner.java @@ -24,9 +24,9 @@ public final class TableInner extends ProxyResource { private TableProperties innerTableProperties; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -34,9 +34,9 @@ public final class TableInner extends ProxyResource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of TableInner class. @@ -54,13 +54,13 @@ private TableProperties innerTableProperties() { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -74,13 +74,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/TableServicePropertiesInner.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/TableServicePropertiesInner.java index b001d31062e8..f3190a4758a3 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/TableServicePropertiesInner.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/models/TableServicePropertiesInner.java @@ -23,9 +23,9 @@ public final class TableServicePropertiesInner extends ProxyResource { private TableServicePropertiesProperties innerTableServiceProperties; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -33,9 +33,9 @@ public final class TableServicePropertiesInner extends ProxyResource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of TableServicePropertiesInner class. @@ -53,13 +53,13 @@ private TableServicePropertiesProperties innerTableServiceProperties() { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -73,13 +73,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/FileServicesClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/FileServicesClientImpl.java index 1c45d3c0d946..679617a88666 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/FileServicesClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/FileServicesClientImpl.java @@ -18,6 +18,10 @@ import com.azure.core.annotation.ServiceInterface; import com.azure.core.annotation.ServiceMethod; import com.azure.core.annotation.UnexpectedResponseExceptionType; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.RestProxy; import com.azure.core.management.exception.ManagementException; @@ -26,6 +30,8 @@ import com.azure.resourcemanager.storage.fluent.FileServicesClient; import com.azure.resourcemanager.storage.fluent.models.FileServiceItemsInner; import com.azure.resourcemanager.storage.fluent.models.FileServicePropertiesInner; +import com.azure.resourcemanager.storage.fluent.models.FileServiceUsageInner; +import com.azure.resourcemanager.storage.models.FileServiceUsages; import reactor.core.publisher.Mono; /** @@ -89,6 +95,35 @@ Mono> getServiceProperties(@HostParam("$hos @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, @PathParam("FileServicesName") String fileServicesName, @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/fileServices/{FileServicesName}/usages") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listServiceUsages(@HostParam("$host") String endpoint, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("accountName") String accountName, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("FileServicesName") String fileServicesName, @QueryParam("$maxpagesize") Integer maxpagesize, + @HeaderParam("Accept") String accept, Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/fileServices/{FileServicesName}/usages/{fileServiceUsagesName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> getServiceUsage(@HostParam("$host") String endpoint, + @PathParam("resourceGroupName") String resourceGroupName, @PathParam("accountName") String accountName, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("FileServicesName") String fileServicesName, + @PathParam("fileServiceUsagesName") String fileServiceUsagesName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listServiceUsagesNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @HeaderParam("Accept") String accept, Context context); } /** @@ -508,4 +543,395 @@ public Response getServicePropertiesWithResponse(Str public FileServicePropertiesInner getServiceProperties(String resourceGroupName, String accountName) { return getServicePropertiesWithResponse(resourceGroupName, accountName, Context.NONE).getValue(); } + + /** + * Gets the usages of file service in storage account. + * + * @param resourceGroupName The name of the resource group within the user's subscription. The name is case + * insensitive. + * @param accountName The name of the storage account within the specified resource group. Storage account names + * must be between 3 and 24 characters in length and use numbers and lower-case letters only. + * @param maxpagesize Optional, specifies the maximum number of file service usages to be included in the list + * response. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the usages of file service in storage account along with {@link PagedResponse} on successful completion + * of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listServiceUsagesSinglePageAsync(String resourceGroupName, + String accountName, Integer maxpagesize) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (accountName == null) { + return Mono.error(new IllegalArgumentException("Parameter accountName is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + final String fileServicesName = "default"; + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listServiceUsages(this.client.getEndpoint(), resourceGroupName, accountName, + this.client.getApiVersion(), this.client.getSubscriptionId(), fileServicesName, maxpagesize, accept, + context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Gets the usages of file service in storage account. + * + * @param resourceGroupName The name of the resource group within the user's subscription. The name is case + * insensitive. + * @param accountName The name of the storage account within the specified resource group. Storage account names + * must be between 3 and 24 characters in length and use numbers and lower-case letters only. + * @param maxpagesize Optional, specifies the maximum number of file service usages to be included in the list + * response. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the usages of file service in storage account along with {@link PagedResponse} on successful completion + * of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listServiceUsagesSinglePageAsync(String resourceGroupName, + String accountName, Integer maxpagesize, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (accountName == null) { + return Mono.error(new IllegalArgumentException("Parameter accountName is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + final String fileServicesName = "default"; + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listServiceUsages(this.client.getEndpoint(), resourceGroupName, accountName, this.client.getApiVersion(), + this.client.getSubscriptionId(), fileServicesName, maxpagesize, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * Gets the usages of file service in storage account. + * + * @param resourceGroupName The name of the resource group within the user's subscription. The name is case + * insensitive. + * @param accountName The name of the storage account within the specified resource group. Storage account names + * must be between 3 and 24 characters in length and use numbers and lower-case letters only. + * @param maxpagesize Optional, specifies the maximum number of file service usages to be included in the list + * response. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the usages of file service in storage account as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listServiceUsagesAsync(String resourceGroupName, String accountName, + Integer maxpagesize) { + return new PagedFlux<>(() -> listServiceUsagesSinglePageAsync(resourceGroupName, accountName, maxpagesize), + nextLink -> listServiceUsagesNextSinglePageAsync(nextLink)); + } + + /** + * Gets the usages of file service in storage account. + * + * @param resourceGroupName The name of the resource group within the user's subscription. The name is case + * insensitive. + * @param accountName The name of the storage account within the specified resource group. Storage account names + * must be between 3 and 24 characters in length and use numbers and lower-case letters only. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the usages of file service in storage account as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listServiceUsagesAsync(String resourceGroupName, String accountName) { + final Integer maxpagesize = null; + return new PagedFlux<>(() -> listServiceUsagesSinglePageAsync(resourceGroupName, accountName, maxpagesize), + nextLink -> listServiceUsagesNextSinglePageAsync(nextLink)); + } + + /** + * Gets the usages of file service in storage account. + * + * @param resourceGroupName The name of the resource group within the user's subscription. The name is case + * insensitive. + * @param accountName The name of the storage account within the specified resource group. Storage account names + * must be between 3 and 24 characters in length and use numbers and lower-case letters only. + * @param maxpagesize Optional, specifies the maximum number of file service usages to be included in the list + * response. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the usages of file service in storage account as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listServiceUsagesAsync(String resourceGroupName, String accountName, + Integer maxpagesize, Context context) { + return new PagedFlux<>( + () -> listServiceUsagesSinglePageAsync(resourceGroupName, accountName, maxpagesize, context), + nextLink -> listServiceUsagesNextSinglePageAsync(nextLink, context)); + } + + /** + * Gets the usages of file service in storage account. + * + * @param resourceGroupName The name of the resource group within the user's subscription. The name is case + * insensitive. + * @param accountName The name of the storage account within the specified resource group. Storage account names + * must be between 3 and 24 characters in length and use numbers and lower-case letters only. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the usages of file service in storage account as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listServiceUsages(String resourceGroupName, String accountName) { + final Integer maxpagesize = null; + return new PagedIterable<>(listServiceUsagesAsync(resourceGroupName, accountName, maxpagesize)); + } + + /** + * Gets the usages of file service in storage account. + * + * @param resourceGroupName The name of the resource group within the user's subscription. The name is case + * insensitive. + * @param accountName The name of the storage account within the specified resource group. Storage account names + * must be between 3 and 24 characters in length and use numbers and lower-case letters only. + * @param maxpagesize Optional, specifies the maximum number of file service usages to be included in the list + * response. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the usages of file service in storage account as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listServiceUsages(String resourceGroupName, String accountName, + Integer maxpagesize, Context context) { + return new PagedIterable<>(listServiceUsagesAsync(resourceGroupName, accountName, maxpagesize, context)); + } + + /** + * Gets the usage of file service in storage account including account limits, file share limits and constants used + * in recommendations and bursting formula. + * + * @param resourceGroupName The name of the resource group within the user's subscription. The name is case + * insensitive. + * @param accountName The name of the storage account within the specified resource group. Storage account names + * must be between 3 and 24 characters in length and use numbers and lower-case letters only. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the usage of file service in storage account including account limits, file share limits and constants + * used in recommendations and bursting formula along with {@link Response} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getServiceUsageWithResponseAsync(String resourceGroupName, + String accountName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (accountName == null) { + return Mono.error(new IllegalArgumentException("Parameter accountName is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + final String fileServicesName = "default"; + final String fileServiceUsagesName = "default"; + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.getServiceUsage(this.client.getEndpoint(), resourceGroupName, accountName, + this.client.getApiVersion(), this.client.getSubscriptionId(), fileServicesName, fileServiceUsagesName, + accept, context)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Gets the usage of file service in storage account including account limits, file share limits and constants used + * in recommendations and bursting formula. + * + * @param resourceGroupName The name of the resource group within the user's subscription. The name is case + * insensitive. + * @param accountName The name of the storage account within the specified resource group. Storage account names + * must be between 3 and 24 characters in length and use numbers and lower-case letters only. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the usage of file service in storage account including account limits, file share limits and constants + * used in recommendations and bursting formula along with {@link Response} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getServiceUsageWithResponseAsync(String resourceGroupName, + String accountName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (accountName == null) { + return Mono.error(new IllegalArgumentException("Parameter accountName is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + final String fileServicesName = "default"; + final String fileServiceUsagesName = "default"; + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.getServiceUsage(this.client.getEndpoint(), resourceGroupName, accountName, + this.client.getApiVersion(), this.client.getSubscriptionId(), fileServicesName, fileServiceUsagesName, + accept, context); + } + + /** + * Gets the usage of file service in storage account including account limits, file share limits and constants used + * in recommendations and bursting formula. + * + * @param resourceGroupName The name of the resource group within the user's subscription. The name is case + * insensitive. + * @param accountName The name of the storage account within the specified resource group. Storage account names + * must be between 3 and 24 characters in length and use numbers and lower-case letters only. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the usage of file service in storage account including account limits, file share limits and constants + * used in recommendations and bursting formula on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getServiceUsageAsync(String resourceGroupName, String accountName) { + return getServiceUsageWithResponseAsync(resourceGroupName, accountName) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Gets the usage of file service in storage account including account limits, file share limits and constants used + * in recommendations and bursting formula. + * + * @param resourceGroupName The name of the resource group within the user's subscription. The name is case + * insensitive. + * @param accountName The name of the storage account within the specified resource group. Storage account names + * must be between 3 and 24 characters in length and use numbers and lower-case letters only. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the usage of file service in storage account including account limits, file share limits and constants + * used in recommendations and bursting formula along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getServiceUsageWithResponse(String resourceGroupName, String accountName, + Context context) { + return getServiceUsageWithResponseAsync(resourceGroupName, accountName, context).block(); + } + + /** + * Gets the usage of file service in storage account including account limits, file share limits and constants used + * in recommendations and bursting formula. + * + * @param resourceGroupName The name of the resource group within the user's subscription. The name is case + * insensitive. + * @param accountName The name of the storage account within the specified resource group. Storage account names + * must be between 3 and 24 characters in length and use numbers and lower-case letters only. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the usage of file service in storage account including account limits, file share limits and constants + * used in recommendations and bursting formula. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public FileServiceUsageInner getServiceUsage(String resourceGroupName, String accountName) { + return getServiceUsageWithResponse(resourceGroupName, accountName, Context.NONE).getValue(); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return list file service usages schema along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listServiceUsagesNextSinglePageAsync(String nextLink) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listServiceUsagesNext(nextLink, this.client.getEndpoint(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * Get the next page of items. + * + * @param nextLink The URL to get the next list of items. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return list file service usages schema along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listServiceUsagesNextSinglePageAsync(String nextLink, + Context context) { + if (nextLink == null) { + return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); + } + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service.listServiceUsagesNext(nextLink, this.client.getEndpoint(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } } diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/StorageManagementClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/StorageManagementClientImpl.java index 63ab393a5c2e..a0b8142bd370 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/StorageManagementClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/StorageManagementClientImpl.java @@ -23,16 +23,16 @@ import com.azure.resourcemanager.storage.fluent.OperationsClient; import com.azure.resourcemanager.storage.fluent.PrivateEndpointConnectionsClient; import com.azure.resourcemanager.storage.fluent.PrivateLinkResourcesClient; -import com.azure.resourcemanager.storage.fluent.QueuesClient; import com.azure.resourcemanager.storage.fluent.QueueServicesClient; +import com.azure.resourcemanager.storage.fluent.QueuesClient; import com.azure.resourcemanager.storage.fluent.SkusClient; import com.azure.resourcemanager.storage.fluent.StorageAccountsClient; import com.azure.resourcemanager.storage.fluent.StorageManagementClient; import com.azure.resourcemanager.storage.fluent.StorageTaskAssignmentInstancesReportsClient; import com.azure.resourcemanager.storage.fluent.StorageTaskAssignmentsClient; import com.azure.resourcemanager.storage.fluent.StorageTaskAssignmentsInstancesReportsClient; -import com.azure.resourcemanager.storage.fluent.TablesClient; import com.azure.resourcemanager.storage.fluent.TableServicesClient; +import com.azure.resourcemanager.storage.fluent.TablesClient; import com.azure.resourcemanager.storage.fluent.UsagesClient; import java.time.Duration; @@ -479,7 +479,7 @@ public StorageTaskAssignmentInstancesReportsClient getStorageTaskAssignmentInsta this.defaultPollInterval = defaultPollInterval; this.subscriptionId = subscriptionId; this.endpoint = endpoint; - this.apiVersion = "2023-05-01"; + this.apiVersion = "2024-01-01"; this.blobServices = new BlobServicesClientImpl(this); this.blobContainers = new BlobContainersClientImpl(this); this.fileServices = new FileServicesClientImpl(this); diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/StorageTaskAssignmentsClientImpl.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/StorageTaskAssignmentsClientImpl.java index e177bc5a6c17..4cc948814fce 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/StorageTaskAssignmentsClientImpl.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/StorageTaskAssignmentsClientImpl.java @@ -34,8 +34,8 @@ import com.azure.core.util.polling.SyncPoller; import com.azure.resourcemanager.storage.fluent.StorageTaskAssignmentsClient; import com.azure.resourcemanager.storage.fluent.models.StorageTaskAssignmentInner; -import com.azure.resourcemanager.storage.models.StorageTaskAssignmentsList; import com.azure.resourcemanager.storage.models.StorageTaskAssignmentUpdateParameters; +import com.azure.resourcemanager.storage.models.StorageTaskAssignmentsList; import java.nio.ByteBuffer; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/AccountLimits.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/AccountLimits.java new file mode 100644 index 000000000000..a0ff3618694d --- /dev/null +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/AccountLimits.java @@ -0,0 +1,131 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.storage.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; + +/** + * Maximum provisioned storage, IOPS, bandwidth and number of file shares limits for the storage account. + */ +@Immutable +public final class AccountLimits implements JsonSerializable { + /* + * The maximum number of file shares limit for the storage account. + */ + private Integer maxFileShares; + + /* + * The maximum provisioned storage quota limit in gibibytes for the storage account. + */ + private Integer maxProvisionedStorageGiB; + + /* + * The maximum provisioned IOPS limit for the storage account. + */ + private Integer maxProvisionedIops; + + /* + * The maximum provisioned bandwidth limit in mebibytes per second for the storage account. + */ + private Integer maxProvisionedBandwidthMiBPerSec; + + /** + * Creates an instance of AccountLimits class. + */ + public AccountLimits() { + } + + /** + * Get the maxFileShares property: The maximum number of file shares limit for the storage account. + * + * @return the maxFileShares value. + */ + public Integer maxFileShares() { + return this.maxFileShares; + } + + /** + * Get the maxProvisionedStorageGiB property: The maximum provisioned storage quota limit in gibibytes for the + * storage account. + * + * @return the maxProvisionedStorageGiB value. + */ + public Integer maxProvisionedStorageGiB() { + return this.maxProvisionedStorageGiB; + } + + /** + * Get the maxProvisionedIops property: The maximum provisioned IOPS limit for the storage account. + * + * @return the maxProvisionedIops value. + */ + public Integer maxProvisionedIops() { + return this.maxProvisionedIops; + } + + /** + * Get the maxProvisionedBandwidthMiBPerSec property: The maximum provisioned bandwidth limit in mebibytes per + * second for the storage account. + * + * @return the maxProvisionedBandwidthMiBPerSec value. + */ + public Integer maxProvisionedBandwidthMiBPerSec() { + return this.maxProvisionedBandwidthMiBPerSec; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AccountLimits from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AccountLimits 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 AccountLimits. + */ + public static AccountLimits fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AccountLimits deserializedAccountLimits = new AccountLimits(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("maxFileShares".equals(fieldName)) { + deserializedAccountLimits.maxFileShares = reader.getNullable(JsonReader::getInt); + } else if ("maxProvisionedStorageGiB".equals(fieldName)) { + deserializedAccountLimits.maxProvisionedStorageGiB = reader.getNullable(JsonReader::getInt); + } else if ("maxProvisionedIOPS".equals(fieldName)) { + deserializedAccountLimits.maxProvisionedIops = reader.getNullable(JsonReader::getInt); + } else if ("maxProvisionedBandwidthMiBPerSec".equals(fieldName)) { + deserializedAccountLimits.maxProvisionedBandwidthMiBPerSec = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + + return deserializedAccountLimits; + }); + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/AccountUsage.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/AccountUsage.java new file mode 100644 index 000000000000..0362ecb02caa --- /dev/null +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/AccountUsage.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.resourcemanager.storage.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; + +/** + * Usage of provisioned storage, IOPS, bandwidth and number of file shares across all live shares and soft-deleted + * shares in the account. + */ +@Immutable +public final class AccountUsage implements JsonSerializable { + /* + * Usage of provisioned storage, IOPS, bandwidth and number of file shares across all live shares or soft-deleted + * shares in the account. + */ + private AccountUsageElements liveShares; + + /* + * Usage of provisioned storage, IOPS, bandwidth and number of file shares across all live shares or soft-deleted + * shares in the account. + */ + private AccountUsageElements softDeletedShares; + + /** + * Creates an instance of AccountUsage class. + */ + public AccountUsage() { + } + + /** + * Get the liveShares property: Usage of provisioned storage, IOPS, bandwidth and number of file shares across all + * live shares or soft-deleted shares in the account. + * + * @return the liveShares value. + */ + public AccountUsageElements liveShares() { + return this.liveShares; + } + + /** + * Get the softDeletedShares property: Usage of provisioned storage, IOPS, bandwidth and number of file shares + * across all live shares or soft-deleted shares in the account. + * + * @return the softDeletedShares value. + */ + public AccountUsageElements softDeletedShares() { + return this.softDeletedShares; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (liveShares() != null) { + liveShares().validate(); + } + if (softDeletedShares() != null) { + softDeletedShares().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AccountUsage from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AccountUsage 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 AccountUsage. + */ + public static AccountUsage fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AccountUsage deserializedAccountUsage = new AccountUsage(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("liveShares".equals(fieldName)) { + deserializedAccountUsage.liveShares = AccountUsageElements.fromJson(reader); + } else if ("softDeletedShares".equals(fieldName)) { + deserializedAccountUsage.softDeletedShares = AccountUsageElements.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedAccountUsage; + }); + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/AccountUsageElements.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/AccountUsageElements.java new file mode 100644 index 000000000000..0571c842b89c --- /dev/null +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/AccountUsageElements.java @@ -0,0 +1,131 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.storage.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; + +/** + * Usage of provisioned storage, IOPS, bandwidth and number of file shares across all live shares or soft-deleted shares + * in the account. + */ +@Immutable +public final class AccountUsageElements implements JsonSerializable { + /* + * The total number of file shares. + */ + private Integer fileShareCount; + + /* + * The total provisioned storage quota in gibibytes. + */ + private Integer provisionedStorageGiB; + + /* + * The total provisioned IOPS. + */ + private Integer provisionedIops; + + /* + * The total provisioned bandwidth in mebibytes per second. + */ + private Integer provisionedBandwidthMiBPerSec; + + /** + * Creates an instance of AccountUsageElements class. + */ + public AccountUsageElements() { + } + + /** + * Get the fileShareCount property: The total number of file shares. + * + * @return the fileShareCount value. + */ + public Integer fileShareCount() { + return this.fileShareCount; + } + + /** + * Get the provisionedStorageGiB property: The total provisioned storage quota in gibibytes. + * + * @return the provisionedStorageGiB value. + */ + public Integer provisionedStorageGiB() { + return this.provisionedStorageGiB; + } + + /** + * Get the provisionedIops property: The total provisioned IOPS. + * + * @return the provisionedIops value. + */ + public Integer provisionedIops() { + return this.provisionedIops; + } + + /** + * Get the provisionedBandwidthMiBPerSec property: The total provisioned bandwidth in mebibytes per second. + * + * @return the provisionedBandwidthMiBPerSec value. + */ + public Integer provisionedBandwidthMiBPerSec() { + return this.provisionedBandwidthMiBPerSec; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AccountUsageElements from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AccountUsageElements 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 AccountUsageElements. + */ + public static AccountUsageElements fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AccountUsageElements deserializedAccountUsageElements = new AccountUsageElements(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("fileShareCount".equals(fieldName)) { + deserializedAccountUsageElements.fileShareCount = reader.getNullable(JsonReader::getInt); + } else if ("provisionedStorageGiB".equals(fieldName)) { + deserializedAccountUsageElements.provisionedStorageGiB = reader.getNullable(JsonReader::getInt); + } else if ("provisionedIOPS".equals(fieldName)) { + deserializedAccountUsageElements.provisionedIops = reader.getNullable(JsonReader::getInt); + } else if ("provisionedBandwidthMiBPerSec".equals(fieldName)) { + deserializedAccountUsageElements.provisionedBandwidthMiBPerSec + = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + + return deserializedAccountUsageElements; + }); + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/AzureEntityResource.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/AzureEntityResource.java index fe7eabdc95c3..3ee2fdfdd30f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/AzureEntityResource.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/AzureEntityResource.java @@ -24,9 +24,9 @@ public class AzureEntityResource extends ProxyResource { private String etag; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -34,9 +34,9 @@ public class AzureEntityResource extends ProxyResource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of AzureEntityResource class. @@ -65,13 +65,13 @@ AzureEntityResource withEtag(String etag) { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -85,13 +85,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/BurstingConstants.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/BurstingConstants.java new file mode 100644 index 000000000000..06bca2d54f06 --- /dev/null +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/BurstingConstants.java @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.storage.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; + +/** + * Constants used for calculating included burst IOPS and maximum burst credits for IOPS for a file share in the storage + * account. + */ +@Immutable +public final class BurstingConstants implements JsonSerializable { + /* + * The guaranteed floor of burst IOPS for small file shares. + */ + private Integer burstFloorIops; + + /* + * The scalar against provisioned IOPS in the file share included burst IOPS formula. + */ + private Double burstIOScalar; + + /* + * The time frame for bursting in seconds in the file share maximum burst credits for IOPS formula. + */ + private Integer burstTimeframeSeconds; + + /** + * Creates an instance of BurstingConstants class. + */ + public BurstingConstants() { + } + + /** + * Get the burstFloorIops property: The guaranteed floor of burst IOPS for small file shares. + * + * @return the burstFloorIops value. + */ + public Integer burstFloorIops() { + return this.burstFloorIops; + } + + /** + * Get the burstIOScalar property: The scalar against provisioned IOPS in the file share included burst IOPS + * formula. + * + * @return the burstIOScalar value. + */ + public Double burstIOScalar() { + return this.burstIOScalar; + } + + /** + * Get the burstTimeframeSeconds property: The time frame for bursting in seconds in the file share maximum burst + * credits for IOPS formula. + * + * @return the burstTimeframeSeconds value. + */ + public Integer burstTimeframeSeconds() { + return this.burstTimeframeSeconds; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of BurstingConstants from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of BurstingConstants 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 BurstingConstants. + */ + public static BurstingConstants fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + BurstingConstants deserializedBurstingConstants = new BurstingConstants(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("burstFloorIOPS".equals(fieldName)) { + deserializedBurstingConstants.burstFloorIops = reader.getNullable(JsonReader::getInt); + } else if ("burstIOScalar".equals(fieldName)) { + deserializedBurstingConstants.burstIOScalar = reader.getNullable(JsonReader::getDouble); + } else if ("burstTimeframeSeconds".equals(fieldName)) { + deserializedBurstingConstants.burstTimeframeSeconds = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + + return deserializedBurstingConstants; + }); + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/FileServiceUsageProperties.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/FileServiceUsageProperties.java new file mode 100644 index 000000000000..e64e660429ab --- /dev/null +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/FileServiceUsageProperties.java @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.storage.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; + +/** + * File service usage in storage account including account limits, file share limits and constants used in + * recommendations and bursting formula. + */ +@Immutable +public final class FileServiceUsageProperties implements JsonSerializable { + /* + * Maximum provisioned storage, IOPS, bandwidth and number of file shares limits for the storage account. + */ + private AccountLimits storageAccountLimits; + + /* + * Minimum and maximum provisioned storage, IOPS and bandwidth limits for a file share in the storage account. + */ + private FileShareLimits fileShareLimits; + + /* + * Constants used for calculating recommended provisioned IOPS and bandwidth for a file share in the storage + * account. + */ + private FileShareRecommendations fileShareRecommendations; + + /* + * Constants used for calculating included burst IOPS and maximum burst credits for IOPS for a file share in the + * storage account. + */ + private BurstingConstants burstingConstants; + + /* + * Usage of provisioned storage, IOPS, bandwidth and number of file shares across all live shares and soft-deleted + * shares in the account. + */ + private AccountUsage storageAccountUsage; + + /** + * Creates an instance of FileServiceUsageProperties class. + */ + public FileServiceUsageProperties() { + } + + /** + * Get the storageAccountLimits property: Maximum provisioned storage, IOPS, bandwidth and number of file shares + * limits for the storage account. + * + * @return the storageAccountLimits value. + */ + public AccountLimits storageAccountLimits() { + return this.storageAccountLimits; + } + + /** + * Get the fileShareLimits property: Minimum and maximum provisioned storage, IOPS and bandwidth limits for a file + * share in the storage account. + * + * @return the fileShareLimits value. + */ + public FileShareLimits fileShareLimits() { + return this.fileShareLimits; + } + + /** + * Get the fileShareRecommendations property: Constants used for calculating recommended provisioned IOPS and + * bandwidth for a file share in the storage account. + * + * @return the fileShareRecommendations value. + */ + public FileShareRecommendations fileShareRecommendations() { + return this.fileShareRecommendations; + } + + /** + * Get the burstingConstants property: Constants used for calculating included burst IOPS and maximum burst credits + * for IOPS for a file share in the storage account. + * + * @return the burstingConstants value. + */ + public BurstingConstants burstingConstants() { + return this.burstingConstants; + } + + /** + * Get the storageAccountUsage property: Usage of provisioned storage, IOPS, bandwidth and number of file shares + * across all live shares and soft-deleted shares in the account. + * + * @return the storageAccountUsage value. + */ + public AccountUsage storageAccountUsage() { + return this.storageAccountUsage; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (storageAccountLimits() != null) { + storageAccountLimits().validate(); + } + if (fileShareLimits() != null) { + fileShareLimits().validate(); + } + if (fileShareRecommendations() != null) { + fileShareRecommendations().validate(); + } + if (burstingConstants() != null) { + burstingConstants().validate(); + } + if (storageAccountUsage() != null) { + storageAccountUsage().validate(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of FileServiceUsageProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of FileServiceUsageProperties 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 FileServiceUsageProperties. + */ + public static FileServiceUsageProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + FileServiceUsageProperties deserializedFileServiceUsageProperties = new FileServiceUsageProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("storageAccountLimits".equals(fieldName)) { + deserializedFileServiceUsageProperties.storageAccountLimits = AccountLimits.fromJson(reader); + } else if ("fileShareLimits".equals(fieldName)) { + deserializedFileServiceUsageProperties.fileShareLimits = FileShareLimits.fromJson(reader); + } else if ("fileShareRecommendations".equals(fieldName)) { + deserializedFileServiceUsageProperties.fileShareRecommendations + = FileShareRecommendations.fromJson(reader); + } else if ("burstingConstants".equals(fieldName)) { + deserializedFileServiceUsageProperties.burstingConstants = BurstingConstants.fromJson(reader); + } else if ("storageAccountUsage".equals(fieldName)) { + deserializedFileServiceUsageProperties.storageAccountUsage = AccountUsage.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedFileServiceUsageProperties; + }); + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/FileServiceUsages.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/FileServiceUsages.java new file mode 100644 index 000000000000..fa12eed3904f --- /dev/null +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/FileServiceUsages.java @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.storage.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 com.azure.resourcemanager.storage.fluent.models.FileServiceUsageInner; +import java.io.IOException; +import java.util.List; + +/** + * List file service usages schema. + */ +@Immutable +public final class FileServiceUsages implements JsonSerializable { + /* + * List of file service usages returned. + */ + private List value; + + /* + * Request URL that can be used to query next page of file service usages. Returned when total number of requested + * file service usages exceed maximum page size. + */ + private String nextLink; + + /** + * Creates an instance of FileServiceUsages class. + */ + public FileServiceUsages() { + } + + /** + * Get the value property: List of file service usages returned. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Get the nextLink property: Request URL that can be used to query next page of file service usages. Returned when + * total number of requested file service usages exceed maximum page size. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() != null) { + value().forEach(e -> e.validate()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of FileServiceUsages from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of FileServiceUsages 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 FileServiceUsages. + */ + public static FileServiceUsages fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + FileServiceUsages deserializedFileServiceUsages = new FileServiceUsages(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value + = reader.readArray(reader1 -> FileServiceUsageInner.fromJson(reader1)); + deserializedFileServiceUsages.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedFileServiceUsages.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedFileServiceUsages; + }); + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/FileShareLimits.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/FileShareLimits.java new file mode 100644 index 000000000000..6553edb82805 --- /dev/null +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/FileShareLimits.java @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.storage.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; + +/** + * Minimum and maximum provisioned storage, IOPS and bandwidth limits for a file share in the storage account. + */ +@Immutable +public final class FileShareLimits implements JsonSerializable { + /* + * The minimum provisioned storage quota limit in gibibytes for a file share in the storage account. + */ + private Integer minProvisionedStorageGiB; + + /* + * The maximum provisioned storage quota limit in gibibytes for a file share in the storage account. + */ + private Integer maxProvisionedStorageGiB; + + /* + * The minimum provisioned IOPS limit for a file share in the storage account. + */ + private Integer minProvisionedIops; + + /* + * The maximum provisioned IOPS limit for a file share in the storage account. + */ + private Integer maxProvisionedIops; + + /* + * The minimum provisioned bandwidth limit in mebibytes per second for a file share in the storage account. + */ + private Integer minProvisionedBandwidthMiBPerSec; + + /* + * The maximum provisioned bandwidth limit in mebibytes per second for a file share in the storage account. + */ + private Integer maxProvisionedBandwidthMiBPerSec; + + /** + * Creates an instance of FileShareLimits class. + */ + public FileShareLimits() { + } + + /** + * Get the minProvisionedStorageGiB property: The minimum provisioned storage quota limit in gibibytes for a file + * share in the storage account. + * + * @return the minProvisionedStorageGiB value. + */ + public Integer minProvisionedStorageGiB() { + return this.minProvisionedStorageGiB; + } + + /** + * Get the maxProvisionedStorageGiB property: The maximum provisioned storage quota limit in gibibytes for a file + * share in the storage account. + * + * @return the maxProvisionedStorageGiB value. + */ + public Integer maxProvisionedStorageGiB() { + return this.maxProvisionedStorageGiB; + } + + /** + * Get the minProvisionedIops property: The minimum provisioned IOPS limit for a file share in the storage account. + * + * @return the minProvisionedIops value. + */ + public Integer minProvisionedIops() { + return this.minProvisionedIops; + } + + /** + * Get the maxProvisionedIops property: The maximum provisioned IOPS limit for a file share in the storage account. + * + * @return the maxProvisionedIops value. + */ + public Integer maxProvisionedIops() { + return this.maxProvisionedIops; + } + + /** + * Get the minProvisionedBandwidthMiBPerSec property: The minimum provisioned bandwidth limit in mebibytes per + * second for a file share in the storage account. + * + * @return the minProvisionedBandwidthMiBPerSec value. + */ + public Integer minProvisionedBandwidthMiBPerSec() { + return this.minProvisionedBandwidthMiBPerSec; + } + + /** + * Get the maxProvisionedBandwidthMiBPerSec property: The maximum provisioned bandwidth limit in mebibytes per + * second for a file share in the storage account. + * + * @return the maxProvisionedBandwidthMiBPerSec value. + */ + public Integer maxProvisionedBandwidthMiBPerSec() { + return this.maxProvisionedBandwidthMiBPerSec; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of FileShareLimits from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of FileShareLimits 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 FileShareLimits. + */ + public static FileShareLimits fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + FileShareLimits deserializedFileShareLimits = new FileShareLimits(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("minProvisionedStorageGiB".equals(fieldName)) { + deserializedFileShareLimits.minProvisionedStorageGiB = reader.getNullable(JsonReader::getInt); + } else if ("maxProvisionedStorageGiB".equals(fieldName)) { + deserializedFileShareLimits.maxProvisionedStorageGiB = reader.getNullable(JsonReader::getInt); + } else if ("minProvisionedIOPS".equals(fieldName)) { + deserializedFileShareLimits.minProvisionedIops = reader.getNullable(JsonReader::getInt); + } else if ("maxProvisionedIOPS".equals(fieldName)) { + deserializedFileShareLimits.maxProvisionedIops = reader.getNullable(JsonReader::getInt); + } else if ("minProvisionedBandwidthMiBPerSec".equals(fieldName)) { + deserializedFileShareLimits.minProvisionedBandwidthMiBPerSec + = reader.getNullable(JsonReader::getInt); + } else if ("maxProvisionedBandwidthMiBPerSec".equals(fieldName)) { + deserializedFileShareLimits.maxProvisionedBandwidthMiBPerSec + = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + + return deserializedFileShareLimits; + }); + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/FileSharePropertiesFileSharePaidBursting.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/FileSharePropertiesFileSharePaidBursting.java new file mode 100644 index 000000000000..7cef3801cfb4 --- /dev/null +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/FileSharePropertiesFileSharePaidBursting.java @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.storage.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; + +/** + * File Share Paid Bursting properties. + */ +@Fluent +public final class FileSharePropertiesFileSharePaidBursting + implements JsonSerializable { + /* + * Indicates whether paid bursting is enabled for the share. This property is only for file shares created under + * Files Provisioned v1 SSD account type. + */ + private Boolean paidBurstingEnabled; + + /* + * The maximum paid bursting IOPS for the share. This property is only for file shares created under Files + * Provisioned v1 SSD account type. The maximum allowed value is 102400 which is the maximum allowed IOPS for a + * share. + */ + private Integer paidBurstingMaxIops; + + /* + * The maximum paid bursting bandwidth for the share, in mebibytes per second. This property is only for file shares + * created under Files Provisioned v1 SSD account type. The maximum allowed value is 10340 which is the maximum + * allowed bandwidth for a share. + */ + private Integer paidBurstingMaxBandwidthMibps; + + /** + * Creates an instance of FileSharePropertiesFileSharePaidBursting class. + */ + public FileSharePropertiesFileSharePaidBursting() { + } + + /** + * Get the paidBurstingEnabled property: Indicates whether paid bursting is enabled for the share. This property is + * only for file shares created under Files Provisioned v1 SSD account type. + * + * @return the paidBurstingEnabled value. + */ + public Boolean paidBurstingEnabled() { + return this.paidBurstingEnabled; + } + + /** + * Set the paidBurstingEnabled property: Indicates whether paid bursting is enabled for the share. This property is + * only for file shares created under Files Provisioned v1 SSD account type. + * + * @param paidBurstingEnabled the paidBurstingEnabled value to set. + * @return the FileSharePropertiesFileSharePaidBursting object itself. + */ + public FileSharePropertiesFileSharePaidBursting withPaidBurstingEnabled(Boolean paidBurstingEnabled) { + this.paidBurstingEnabled = paidBurstingEnabled; + return this; + } + + /** + * Get the paidBurstingMaxIops property: The maximum paid bursting IOPS for the share. This property is only for + * file shares created under Files Provisioned v1 SSD account type. The maximum allowed value is 102400 which is the + * maximum allowed IOPS for a share. + * + * @return the paidBurstingMaxIops value. + */ + public Integer paidBurstingMaxIops() { + return this.paidBurstingMaxIops; + } + + /** + * Set the paidBurstingMaxIops property: The maximum paid bursting IOPS for the share. This property is only for + * file shares created under Files Provisioned v1 SSD account type. The maximum allowed value is 102400 which is the + * maximum allowed IOPS for a share. + * + * @param paidBurstingMaxIops the paidBurstingMaxIops value to set. + * @return the FileSharePropertiesFileSharePaidBursting object itself. + */ + public FileSharePropertiesFileSharePaidBursting withPaidBurstingMaxIops(Integer paidBurstingMaxIops) { + this.paidBurstingMaxIops = paidBurstingMaxIops; + return this; + } + + /** + * Get the paidBurstingMaxBandwidthMibps property: The maximum paid bursting bandwidth for the share, in mebibytes + * per second. This property is only for file shares created under Files Provisioned v1 SSD account type. The + * maximum allowed value is 10340 which is the maximum allowed bandwidth for a share. + * + * @return the paidBurstingMaxBandwidthMibps value. + */ + public Integer paidBurstingMaxBandwidthMibps() { + return this.paidBurstingMaxBandwidthMibps; + } + + /** + * Set the paidBurstingMaxBandwidthMibps property: The maximum paid bursting bandwidth for the share, in mebibytes + * per second. This property is only for file shares created under Files Provisioned v1 SSD account type. The + * maximum allowed value is 10340 which is the maximum allowed bandwidth for a share. + * + * @param paidBurstingMaxBandwidthMibps the paidBurstingMaxBandwidthMibps value to set. + * @return the FileSharePropertiesFileSharePaidBursting object itself. + */ + public FileSharePropertiesFileSharePaidBursting + withPaidBurstingMaxBandwidthMibps(Integer paidBurstingMaxBandwidthMibps) { + this.paidBurstingMaxBandwidthMibps = paidBurstingMaxBandwidthMibps; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeBooleanField("paidBurstingEnabled", this.paidBurstingEnabled); + jsonWriter.writeNumberField("paidBurstingMaxIops", this.paidBurstingMaxIops); + jsonWriter.writeNumberField("paidBurstingMaxBandwidthMibps", this.paidBurstingMaxBandwidthMibps); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of FileSharePropertiesFileSharePaidBursting from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of FileSharePropertiesFileSharePaidBursting 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 FileSharePropertiesFileSharePaidBursting. + */ + public static FileSharePropertiesFileSharePaidBursting fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + FileSharePropertiesFileSharePaidBursting deserializedFileSharePropertiesFileSharePaidBursting + = new FileSharePropertiesFileSharePaidBursting(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("paidBurstingEnabled".equals(fieldName)) { + deserializedFileSharePropertiesFileSharePaidBursting.paidBurstingEnabled + = reader.getNullable(JsonReader::getBoolean); + } else if ("paidBurstingMaxIops".equals(fieldName)) { + deserializedFileSharePropertiesFileSharePaidBursting.paidBurstingMaxIops + = reader.getNullable(JsonReader::getInt); + } else if ("paidBurstingMaxBandwidthMibps".equals(fieldName)) { + deserializedFileSharePropertiesFileSharePaidBursting.paidBurstingMaxBandwidthMibps + = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + + return deserializedFileSharePropertiesFileSharePaidBursting; + }); + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/FileShareRecommendations.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/FileShareRecommendations.java new file mode 100644 index 000000000000..0dce0e137a8b --- /dev/null +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/FileShareRecommendations.java @@ -0,0 +1,132 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.resourcemanager.storage.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; + +/** + * Constants used for calculating recommended provisioned IOPS and bandwidth for a file share in the storage account. + */ +@Immutable +public final class FileShareRecommendations implements JsonSerializable { + /* + * The base IOPS in the file share provisioned IOPS recommendation formula. + */ + private Integer baseIops; + + /* + * The scalar for IO in the file share provisioned IOPS recommendation formula. + */ + private Double ioScalar; + + /* + * The base bandwidth in the file share provisioned bandwidth recommendation formula. + */ + private Integer baseBandwidthMiBPerSec; + + /* + * The scalar for bandwidth in the file share provisioned bandwidth recommendation formula. + */ + private Double bandwidthScalar; + + /** + * Creates an instance of FileShareRecommendations class. + */ + public FileShareRecommendations() { + } + + /** + * Get the baseIops property: The base IOPS in the file share provisioned IOPS recommendation formula. + * + * @return the baseIops value. + */ + public Integer baseIops() { + return this.baseIops; + } + + /** + * Get the ioScalar property: The scalar for IO in the file share provisioned IOPS recommendation formula. + * + * @return the ioScalar value. + */ + public Double ioScalar() { + return this.ioScalar; + } + + /** + * Get the baseBandwidthMiBPerSec property: The base bandwidth in the file share provisioned bandwidth + * recommendation formula. + * + * @return the baseBandwidthMiBPerSec value. + */ + public Integer baseBandwidthMiBPerSec() { + return this.baseBandwidthMiBPerSec; + } + + /** + * Get the bandwidthScalar property: The scalar for bandwidth in the file share provisioned bandwidth recommendation + * formula. + * + * @return the bandwidthScalar value. + */ + public Double bandwidthScalar() { + return this.bandwidthScalar; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of FileShareRecommendations from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of FileShareRecommendations 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 FileShareRecommendations. + */ + public static FileShareRecommendations fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + FileShareRecommendations deserializedFileShareRecommendations = new FileShareRecommendations(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("baseIOPS".equals(fieldName)) { + deserializedFileShareRecommendations.baseIops = reader.getNullable(JsonReader::getInt); + } else if ("ioScalar".equals(fieldName)) { + deserializedFileShareRecommendations.ioScalar = reader.getNullable(JsonReader::getDouble); + } else if ("baseBandwidthMiBPerSec".equals(fieldName)) { + deserializedFileShareRecommendations.baseBandwidthMiBPerSec + = reader.getNullable(JsonReader::getInt); + } else if ("bandwidthScalar".equals(fieldName)) { + deserializedFileShareRecommendations.bandwidthScalar = reader.getNullable(JsonReader::getDouble); + } else { + reader.skipChildren(); + } + } + + return deserializedFileShareRecommendations; + }); + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/ObjectReplicationPolicyPropertiesMetrics.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/ObjectReplicationPolicyPropertiesMetrics.java new file mode 100644 index 000000000000..21ac30ebc09e --- /dev/null +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/ObjectReplicationPolicyPropertiesMetrics.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. + +package com.azure.resourcemanager.storage.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; + +/** + * Optional. The object replication policy metrics feature options. + */ +@Fluent +public final class ObjectReplicationPolicyPropertiesMetrics + implements JsonSerializable { + /* + * Indicates whether object replication metrics feature is enabled for the policy. + */ + private Boolean enabled; + + /** + * Creates an instance of ObjectReplicationPolicyPropertiesMetrics class. + */ + public ObjectReplicationPolicyPropertiesMetrics() { + } + + /** + * Get the enabled property: Indicates whether object replication metrics feature is enabled for the policy. + * + * @return the enabled value. + */ + public Boolean enabled() { + return this.enabled; + } + + /** + * Set the enabled property: Indicates whether object replication metrics feature is enabled for the policy. + * + * @param enabled the enabled value to set. + * @return the ObjectReplicationPolicyPropertiesMetrics object itself. + */ + public ObjectReplicationPolicyPropertiesMetrics withEnabled(Boolean enabled) { + this.enabled = enabled; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeBooleanField("enabled", this.enabled); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ObjectReplicationPolicyPropertiesMetrics from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ObjectReplicationPolicyPropertiesMetrics 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 ObjectReplicationPolicyPropertiesMetrics. + */ + public static ObjectReplicationPolicyPropertiesMetrics fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ObjectReplicationPolicyPropertiesMetrics deserializedObjectReplicationPolicyPropertiesMetrics + = new ObjectReplicationPolicyPropertiesMetrics(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("enabled".equals(fieldName)) { + deserializedObjectReplicationPolicyPropertiesMetrics.enabled + = reader.getNullable(JsonReader::getBoolean); + } else { + reader.skipChildren(); + } + } + + return deserializedObjectReplicationPolicyPropertiesMetrics; + }); + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/PrivateLinkResource.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/PrivateLinkResource.java index 2b1ea636d08b..8092e9f75a19 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/PrivateLinkResource.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/PrivateLinkResource.java @@ -24,9 +24,9 @@ public final class PrivateLinkResource extends ProxyResource { private PrivateLinkResourceProperties innerProperties; /* - * Fully qualified resource Id for the resource. + * The type of the resource. */ - private String id; + private String type; /* * The name of the resource. @@ -34,9 +34,9 @@ public final class PrivateLinkResource extends ProxyResource { private String name; /* - * The type of the resource. + * Fully qualified resource Id for the resource. */ - private String type; + private String id; /** * Creates an instance of PrivateLinkResource class. @@ -54,13 +54,13 @@ private PrivateLinkResourceProperties innerProperties() { } /** - * Get the id property: Fully qualified resource Id for the resource. + * Get the type property: The type of the resource. * - * @return the id value. + * @return the type value. */ @Override - public String id() { - return this.id; + public String type() { + return this.type; } /** @@ -74,13 +74,13 @@ public String name() { } /** - * Get the type property: The type of the resource. + * Get the id property: Fully qualified resource Id for the resource. * - * @return the type value. + * @return the id value. */ @Override - public String type() { - return this.type; + public String id() { + return this.id; } /** diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/SkuName.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/SkuName.java index 2b0b0d40c060..b8cdf7575c47 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/SkuName.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/SkuName.java @@ -52,6 +52,36 @@ public final class SkuName extends ExpandableStringEnum { */ public static final SkuName STANDARD_RAGZRS = fromString("Standard_RAGZRS"); + /** + * Static value StandardV2_LRS for SkuName. + */ + public static final SkuName STANDARD_V2_LRS = fromString("StandardV2_LRS"); + + /** + * Static value StandardV2_GRS for SkuName. + */ + public static final SkuName STANDARD_V2_GRS = fromString("StandardV2_GRS"); + + /** + * Static value StandardV2_ZRS for SkuName. + */ + public static final SkuName STANDARD_V2_ZRS = fromString("StandardV2_ZRS"); + + /** + * Static value StandardV2_GZRS for SkuName. + */ + public static final SkuName STANDARD_V2_GZRS = fromString("StandardV2_GZRS"); + + /** + * Static value PremiumV2_LRS for SkuName. + */ + public static final SkuName PREMIUM_V2_LRS = fromString("PremiumV2_LRS"); + + /** + * Static value PremiumV2_ZRS for SkuName. + */ + public static final SkuName PREMIUM_V2_ZRS = fromString("PremiumV2_ZRS"); + /** * Creates a new instance of SkuName value. * diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/StorageAccountCheckNameAvailabilityParameters.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/StorageAccountCheckNameAvailabilityParameters.java index 8550237f040b..39e2882aaec5 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/StorageAccountCheckNameAvailabilityParameters.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/models/StorageAccountCheckNameAvailabilityParameters.java @@ -26,7 +26,7 @@ public final class StorageAccountCheckNameAvailabilityParameters /* * The type of resource, Microsoft.Storage/storageAccounts */ - private String type = "Microsoft.Storage/storageAccounts"; + private final String type = "Microsoft.Storage/storageAccounts"; /** * Creates an instance of StorageAccountCheckNameAvailabilityParameters class. @@ -63,17 +63,6 @@ public String type() { return this.type; } - /** - * Set the type property: The type of resource, Microsoft.Storage/storageAccounts. - * - * @param type the type value to set. - * @return the StorageAccountCheckNameAvailabilityParameters object itself. - */ - public StorageAccountCheckNameAvailabilityParameters withType(String type) { - this.type = type; - return this; - } - /** * Validates the instance. * diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/samples/java/com/azure/resourcemanager/storage/ReadmeSamples.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/samples/java/com/azure/resourcemanager/storage/ReadmeSamples.java index 5193e1957254..b6e3dcc37101 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/samples/java/com/azure/resourcemanager/storage/ReadmeSamples.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/samples/java/com/azure/resourcemanager/storage/ReadmeSamples.java @@ -4,8 +4,8 @@ package com.azure.resourcemanager.storage; import com.azure.core.credential.TokenCredential; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; /** @@ -15,7 +15,7 @@ public class ReadmeSamples { public void authenticate() { // BEGIN: readme-sample-authenticate - AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageAccountOperationsTests.java b/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageAccountOperationsTests.java index 919745870796..6b88eeeccec4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageAccountOperationsTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-storage/src/test/java/com/azure/resourcemanager/storage/StorageAccountOperationsTests.java @@ -161,8 +161,8 @@ public void storageAccountDefault() { .disableSharedKeyAccess() .apply(); - Assertions.assertFalse(storageAccount.isHttpsTrafficOnly()); - Assertions.assertEquals(MinimumTlsVersion.TLS1_1, storageAccount.minimumTlsVersion()); + Assertions.assertTrue(storageAccount.isHttpsTrafficOnly()); + Assertions.assertEquals(MinimumTlsVersion.TLS1_2, storageAccount.minimumTlsVersion()); Assertions.assertFalse(storageAccount.isBlobPublicAccessAllowed()); Assertions.assertFalse(storageAccount.isSharedKeyAccessAllowed()); @@ -181,8 +181,8 @@ public void storageAccountDefault() { Assertions.assertEquals(Kind.STORAGE, storageAccount.kind()); Assertions.assertEquals(SkuName.STANDARD_LRS, storageAccount.skuType().name()); - Assertions.assertFalse(storageAccount.isHttpsTrafficOnly()); - Assertions.assertEquals(MinimumTlsVersion.TLS1_1, storageAccount.minimumTlsVersion()); + Assertions.assertTrue(storageAccount.isHttpsTrafficOnly()); + Assertions.assertEquals(MinimumTlsVersion.TLS1_2, storageAccount.minimumTlsVersion()); Assertions.assertFalse(storageAccount.isBlobPublicAccessAllowed()); Assertions.assertFalse(storageAccount.isSharedKeyAccessAllowed()); } diff --git a/sdk/resourcemanager/azure-resourcemanager-test/pom.xml b/sdk/resourcemanager/azure-resourcemanager-test/pom.xml index fca3903f07ee..06d9b535b755 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.27.0-beta.4 + 1.27.0-beta.8 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-identity - 1.15.0 + 1.15.4 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 diff --git a/sdk/resourcemanager/azure-resourcemanager-test/src/main/java/com/azure/resourcemanager/test/ResourceManagerTestProxyTestBase.java b/sdk/resourcemanager/azure-resourcemanager-test/src/main/java/com/azure/resourcemanager/test/ResourceManagerTestProxyTestBase.java index 1a4671c17d32..a240c756689b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-test/src/main/java/com/azure/resourcemanager/test/ResourceManagerTestProxyTestBase.java +++ b/sdk/resourcemanager/azure-resourcemanager-test/src/main/java/com/azure/resourcemanager/test/ResourceManagerTestProxyTestBase.java @@ -3,7 +3,6 @@ package com.azure.resourcemanager.test; import com.azure.core.credential.TokenCredential; -import com.azure.core.exception.ClientAuthenticationException; import com.azure.core.http.HttpClient; import com.azure.core.http.HttpPipeline; import com.azure.core.http.ProxyOptions; @@ -13,6 +12,7 @@ import com.azure.core.http.policy.HttpPipelinePolicy; import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.core.test.TestMode; import com.azure.core.test.TestProxyTestBase; import com.azure.core.test.models.CustomMatcher; @@ -21,14 +21,13 @@ import com.azure.core.test.utils.MockTokenCredential; import com.azure.core.test.utils.ResourceNamer; import com.azure.core.util.Configuration; -import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.identity.implementation.util.IdentityUtil; import com.azure.json.JsonProviders; import com.azure.json.JsonReader; import com.azure.resourcemanager.test.model.AzureUser; import com.azure.resourcemanager.test.policy.HttpDebugLoggingPolicy; +import com.azure.resourcemanager.test.utils.CliRunner; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.InvocationInterceptor; @@ -36,11 +35,9 @@ import org.junit.jupiter.api.extension.RegisterExtension; import reactor.core.Exceptions; -import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; -import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import java.io.UnsupportedEncodingException; @@ -68,7 +65,6 @@ import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -237,70 +233,8 @@ protected AzureUser azureCliSignedInUser() { if (!isPlaybackMode()) { String azCommand = "az ad signed-in-user show --output json"; - final Pattern windowsProcessErrorMessage = Pattern.compile("'azd?' is not recognized"); - final Pattern shProcessErrorMessage = Pattern.compile("azd?:.*not found"); try { - String starter; - String switcher; - if (IdentityUtil.isWindowsPlatform()) { - starter = "cmd.exe"; - switcher = "/c"; - } else { - starter = "/bin/sh"; - switcher = "-c"; - } - - ProcessBuilder builder = new ProcessBuilder(starter, switcher, azCommand.toString()); - // Redirects stdin to dev null, helps to avoid messages sent in by the cmd process to upgrade etc. - builder.redirectInput(ProcessBuilder.Redirect.from(IdentityUtil.NULL_FILE)); - - builder.redirectErrorStream(true); - Process process = builder.start(); - - StringBuilder output = new StringBuilder(); - try (BufferedReader reader - = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { - String line; - while (true) { - line = reader.readLine(); - if (line == null) { - break; - } - - if (windowsProcessErrorMessage.matcher(line).find() - || shProcessErrorMessage.matcher(line).find()) { - throw LOGGER.logExceptionAsError(new RuntimeException( - "AzureCliCredential authentication unavailable. Azure CLI not installed." - + "To mitigate this issue, please refer to the troubleshooting guidelines here at " - + "https://aka.ms/azsdk/java/identity/azclicredential/troubleshoot")); - } - output.append(line); - } - } - String processOutput = output.toString(); - - // wait(at most) 10 seconds for the process to complete - process.waitFor(10, TimeUnit.SECONDS); - - if (process.exitValue() != 0) { - if (processOutput.length() > 0) { - if (processOutput.contains("az login") || processOutput.contains("az account set")) { - throw LOGGER.logExceptionAsError(new RuntimeException( - "AzureCliCredential authentication unavailable. Azure CLI not installed." - + "To mitigate this issue, please refer to the troubleshooting guidelines here at " - + "https://aka.ms/azsdk/java/identity/azclicredential/troubleshoot")); - } - throw LOGGER.logExceptionAsError( - new ClientAuthenticationException("get Azure CLI current signed-in user failed", null)); - } else { - throw LOGGER.logExceptionAsError( - new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); - } - } - - LOGGER - .verbose("Get Azure CLI signed-in user => A response was received from Azure CLI, deserializing the" - + " response into an signed-in user."); + String processOutput = CliRunner.run(azCommand); try (JsonReader reader = JsonProviders.createReader(processOutput)) { Map signedInUserInfo = reader.readMap(JsonReader::readUntyped); String userPrincipalName = (String) signedInUserInfo.get("userPrincipalName"); @@ -314,15 +248,6 @@ protected AzureUser azureCliSignedInUser() { return azureCliUser; } - private static String getSafeWorkingDirectory() { - if (IdentityUtil.isWindowsPlatform()) { - String windowsSystemRoot = System.getenv("SystemRoot"); - return CoreUtils.isNullOrEmpty(windowsSystemRoot) ? null : windowsSystemRoot + "\\system32"; - } else { - return "/bin/"; - } - } - /** * Gets the test profile. * @return The test profile. @@ -400,10 +325,10 @@ protected void beforeTest() { String subscriptionId = Objects.requireNonNull(configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID), "'AZURE_SUBSCRIPTION_ID' environment variable cannot be null."); - credential - = new DefaultAzureCredentialBuilder().authorityHost(AzureEnvironment.AZURE.getActiveDirectoryEndpoint()) - .build(); - testProfile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE); + testProfile = new AzureProfile(tenantId, subscriptionId, AzureCloud.AZURE_PUBLIC_CLOUD); + credential = new DefaultAzureCredentialBuilder() + .authorityHost(testProfile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); List policies = new ArrayList<>(); if (interceptorManager.isRecordMode() && !testContextManager.doNotRecordTest()) { diff --git a/sdk/resourcemanager/azure-resourcemanager-test/src/main/java/com/azure/resourcemanager/test/utils/CliRunner.java b/sdk/resourcemanager/azure-resourcemanager-test/src/main/java/com/azure/resourcemanager/test/utils/CliRunner.java new file mode 100644 index 000000000000..faac8b679e7e --- /dev/null +++ b/sdk/resourcemanager/azure-resourcemanager-test/src/main/java/com/azure/resourcemanager/test/utils/CliRunner.java @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.resourcemanager.test.utils; + +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.util.logging.ClientLogger; +import com.azure.identity.implementation.util.IdentityUtil; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; + +/** + * Util to run Azure CLI command line and get result output string. + */ +public final class CliRunner { + private static final ClientLogger LOGGER = new ClientLogger(CliRunner.class); + + private CliRunner() { + } + + /** + * Run Azure CLI command and get output result. + * @param azCommand the Azure CLI command to run in command line + * @return command line output if successful + * @throws IOException if IOException occurs + * @throws InterruptedException if InterruptedException occurs + */ + public static String run(String azCommand) throws IOException, InterruptedException { + final Pattern windowsProcessErrorMessage = Pattern.compile("'azd?' is not recognized"); + final Pattern shProcessErrorMessage = Pattern.compile("azd?:.*not found"); + String starter; + String switcher; + if (IdentityUtil.isWindowsPlatform()) { + starter = "cmd.exe"; + switcher = "/c"; + } else { + starter = "/bin/sh"; + switcher = "-c"; + } + + ProcessBuilder builder = new ProcessBuilder(starter, switcher, azCommand); + // Redirects stdin to dev null, helps to avoid messages sent in by the cmd process to upgrade etc. + builder.redirectInput(ProcessBuilder.Redirect.from(IdentityUtil.NULL_FILE)); + + builder.redirectErrorStream(true); + Process process = builder.start(); + + StringBuilder output = new StringBuilder(); + try (BufferedReader reader + = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { + String line; + while (true) { + line = reader.readLine(); + if (line == null) { + break; + } + + if (windowsProcessErrorMessage.matcher(line).find() || shProcessErrorMessage.matcher(line).find()) { + throw LOGGER.logExceptionAsError( + new RuntimeException("AzureCliCredential authentication unavailable. Azure CLI not installed." + + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + + "https://aka.ms/azsdk/java/identity/azclicredential/troubleshoot")); + } + output.append(line); + } + } + String processOutput = output.toString(); + + // wait(at most) 10 seconds for the process to complete + boolean finished = process.waitFor(10, TimeUnit.SECONDS); + + if (!finished) { + throw LOGGER + .logExceptionAsError(new RuntimeException("Process did not complete within the expected time.")); + } + if (process.exitValue() != 0) { + if (processOutput.length() > 0) { + if (processOutput.contains("az login") || processOutput.contains("az account set")) { + throw LOGGER.logExceptionAsError( + new RuntimeException("AzureCliCredential authentication unavailable. Azure CLI not installed." + + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + + "https://aka.ms/azsdk/java/identity/azclicredential/troubleshoot")); + } + throw LOGGER.logExceptionAsError(new ClientAuthenticationException(azCommand + " failed", null)); + } else { + throw LOGGER + .logExceptionAsError(new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); + } + } + + LOGGER.verbose(azCommand + " => A response was received from Azure CLI, deserializing the" + " response."); + + return processOutput; + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/CHANGELOG.md b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/CHANGELOG.md index dfdd94fc0093..f3c1fe416b5e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/CHANGELOG.md +++ b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 2.47.0-beta.1 (Unreleased) +## 2.49.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,22 @@ ### Other Changes +## 2.48.0 (2025-02-28) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + +## 2.47.0 (2025-01-24) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + ## 2.46.0 (2024-12-23) ### Other Changes diff --git a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/README.md b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/README.md index 6788d0bfafe5..3b1a342cbf3b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/README.md +++ b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/README.md @@ -18,7 +18,7 @@ For documentation on how to use this package, please see [Azure Management Libra com.azure.resourcemanager azure-resourcemanager-trafficmanager - 2.46.0 + 2.49.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -39,7 +39,7 @@ Azure tenant ID can be configured via `AZURE_TENANT_ID` environment variable. Assuming the use of the `DefaultAzureCredential` credential class, the client can be authenticated using the following code: ```java readme-sample-authenticate -AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); +AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/pom.xml b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/pom.xml index 8eca1e9b8ea7..e726e5bcaa71 100644 --- a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/pom.xml @@ -14,7 +14,7 @@ com.azure.resourcemanager azure-resourcemanager-trafficmanager - 2.47.0-beta.1 + 2.49.0-beta.1 jar Microsoft Azure SDK for Traffic Manager Management @@ -58,7 +58,7 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.47.0-beta.1 + 2.49.0-beta.1 org.slf4j @@ -75,7 +75,7 @@ com.azure azure-core-http-netty - 1.15.7 + 1.15.11 test diff --git a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/samples/java/com/azure/resourcemanager/trafficmanager/ReadmeSamples.java b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/samples/java/com/azure/resourcemanager/trafficmanager/ReadmeSamples.java index ad5dd8feb73b..872b24f4d02c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/samples/java/com/azure/resourcemanager/trafficmanager/ReadmeSamples.java +++ b/sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/samples/java/com/azure/resourcemanager/trafficmanager/ReadmeSamples.java @@ -4,8 +4,8 @@ package com.azure.resourcemanager.trafficmanager; import com.azure.core.credential.TokenCredential; -import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; +import com.azure.core.models.AzureCloud; import com.azure.identity.DefaultAzureCredentialBuilder; /** @@ -15,7 +15,7 @@ public class ReadmeSamples { public void authenticate() { // BEGIN: readme-sample-authenticate - AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD); TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); diff --git a/sdk/resourcemanager/azure-resourcemanager/CHANGELOG.md b/sdk/resourcemanager/azure-resourcemanager/CHANGELOG.md index 1ff622f95504..a7dfa47940af 100644 --- a/sdk/resourcemanager/azure-resourcemanager/CHANGELOG.md +++ b/sdk/resourcemanager/azure-resourcemanager/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 2.47.0-beta.1 (Unreleased) +## 2.49.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,22 @@ ### Other Changes +## 2.48.0 (2025-02-28) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + +## 2.47.0 (2025-01-24) + +### Other Changes + +#### Dependency Updates + +- Updated core dependency from resources. + ## 2.46.0 (2024-12-23) ### Other Changes diff --git a/sdk/resourcemanager/azure-resourcemanager/README.md b/sdk/resourcemanager/azure-resourcemanager/README.md index 20e07b9ec50a..f72c2f867b81 100644 --- a/sdk/resourcemanager/azure-resourcemanager/README.md +++ b/sdk/resourcemanager/azure-resourcemanager/README.md @@ -18,7 +18,7 @@ For documentation on how to use this package, please see [Azure Management Libra com.azure.resourcemanager azure-resourcemanager - 2.46.0 + 2.49.0-beta.1 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/resourcemanager/azure-resourcemanager/pom.xml b/sdk/resourcemanager/azure-resourcemanager/pom.xml index 2fe016f8f261..53dfb41b4796 100644 --- a/sdk/resourcemanager/azure-resourcemanager/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager/pom.xml @@ -15,7 +15,7 @@ com.azure.resourcemanager azure-resourcemanager - 2.47.0-beta.1 + 2.49.0-beta.1 jar Microsoft Azure SDK for Management @@ -71,127 +71,127 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure.resourcemanager azure-resourcemanager-resources - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-storage - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-compute - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-network - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-keyvault - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-msi - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-sql - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-authorization - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-appservice - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-cosmos - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-containerservice - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-monitor - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-containerregistry - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-dns - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-appplatform - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-containerinstance - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-privatedns - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-redis - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-eventhubs - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-trafficmanager - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-servicebus - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-cdn - 2.47.0-beta.1 + 2.49.0-beta.1 com.azure.resourcemanager azure-resourcemanager-search - 2.47.0-beta.1 + 2.49.0-beta.1 org.junit.jupiter @@ -214,19 +214,19 @@ com.azure azure-core-http-netty - 1.15.7 + 1.15.11 test com.azure azure-core-http-okhttp - 1.12.6 + 1.12.10 test com.azure azure-core-http-vertx - 1.0.0-beta.24 + 1.0.3 test @@ -282,7 +282,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.19 + 1.0.3 test diff --git a/sdk/resourcemanager/azure-resourcemanager/src/main/java/com/azure/resourcemanager/AzureResourceManager.java b/sdk/resourcemanager/azure-resourcemanager/src/main/java/com/azure/resourcemanager/AzureResourceManager.java index b6a86eac41fe..37d32eda31ca 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/main/java/com/azure/resourcemanager/AzureResourceManager.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/main/java/com/azure/resourcemanager/AzureResourceManager.java @@ -133,7 +133,7 @@ * * *

        - * AzureProfile profile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE);
        + * AzureProfile profile = new AzureProfile(tenantId, subscriptionId, AzureCloud.AZURE_PUBLIC_CLOUD);
          * TokenCredential credential = new DefaultAzureCredentialBuilder()
          *     .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint())
          *     .build();
        @@ -177,7 +177,7 @@ public final class AzureResourceManager {
              *
              * 
              * 
        -     * AzureProfile profile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE);
        +     * AzureProfile profile = new AzureProfile(tenantId, subscriptionId, AzureCloud.AZURE_PUBLIC_CLOUD);
              * TokenCredential credential = new DefaultAzureCredentialBuilder()
              *     .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint())
              *     .build();
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/AuthSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/AuthSamples.java
        index b381ea35c604..0c058f5e3cdf 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/AuthSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/AuthSamples.java
        @@ -7,8 +7,8 @@
         import com.azure.core.http.HttpClient;
         import com.azure.core.http.policy.HttpPipelinePolicy;
         import com.azure.core.http.policy.RetryPolicy;
        -import com.azure.core.management.AzureEnvironment;
         import com.azure.core.management.profile.AzureProfile;
        +import com.azure.core.models.AzureCloud;
         import com.azure.identity.ClientSecretCredential;
         import com.azure.identity.ClientSecretCredentialBuilder;
         import com.azure.identity.EnvironmentCredential;
        @@ -44,14 +44,14 @@ public void buildManagedIdentityCredential() {
         
             public void buildAzureProfile() {
                 // BEGIN: readme-sample-buildAzureProfile
        -        // AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);
        -        AzureProfile profile = new AzureProfile("", "", AzureEnvironment.AZURE);
        +        // AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD);
        +        AzureProfile profile = new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD);
                 // END: readme-sample-buildAzureProfile
             }
         
             public void buildEnvironmentCredential() {
                 // BEGIN: readme-sample-buildEnvironmentCredential
        -        AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE_GERMANY);
        +        AzureProfile profile = new AzureProfile(AzureCloud.AZURE_CHINA_CLOUD);
                 EnvironmentCredential credential = new EnvironmentCredentialBuilder()
                     .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint())
                     .build();
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/AzureResourceManagerJavaDocSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/AzureResourceManagerJavaDocSamples.java
        index c11a5bbc1286..c97e58a68fcc 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/AzureResourceManagerJavaDocSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/AzureResourceManagerJavaDocSamples.java
        @@ -8,9 +8,9 @@
         import com.azure.core.http.policy.HttpLogDetailLevel;
         import com.azure.core.http.policy.HttpPipelinePolicy;
         import com.azure.core.http.policy.RetryPolicy;
        -import com.azure.core.management.AzureEnvironment;
         import com.azure.core.management.Region;
         import com.azure.core.management.profile.AzureProfile;
        +import com.azure.core.models.AzureCloud;
         import com.azure.identity.DefaultAzureCredentialBuilder;
         import com.azure.resourcemanager.appservice.models.AppServicePlan;
         import com.azure.resourcemanager.appservice.models.FunctionApp;
        @@ -29,7 +29,7 @@
         public class AzureResourceManagerJavaDocSamples {
             public void authenticateUsingTokenCredentialAndAzureProfile(String tenantId, String subscriptionId) {
                 // BEGIN: com.azure.resourcemanager.azureResourceManager.authenticate#credential-profile
        -        AzureProfile profile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE);
        +        AzureProfile profile = new AzureProfile(tenantId, subscriptionId, AzureCloud.AZURE_PUBLIC_CLOUD);
                 TokenCredential credential = new DefaultAzureCredentialBuilder()
                     .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint())
                     .build();
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsAbortLatestOperationSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsAbortLatestOperationSamples.java
        index 72da8929c11e..78ec06f9e110 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsAbortLatestOperationSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsAbortLatestOperationSamples.java
        @@ -10,7 +10,7 @@
         public final class AgentPoolsAbortLatestOperationSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * AgentPoolsAbortOperation.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsCreateOrUpdateSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsCreateOrUpdateSamples.java
        index 339eeb8f860c..965afaf7a158 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsCreateOrUpdateSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsCreateOrUpdateSamples.java
        @@ -30,7 +30,7 @@
         public final class AgentPoolsCreateOrUpdateSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * AgentPoolsCreate_EnableFIPS.json
              */
             /**
        @@ -54,7 +54,7 @@ public static void createAgentPoolWithFIPSEnabledOS(com.azure.resourcemanager.Az
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * AgentPools_Update.json
              */
             /**
        @@ -83,7 +83,7 @@ public static void updateAgentPool(com.azure.resourcemanager.AzureResourceManage
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * AgentPoolsCreate_GPUMIG.json
              */
             /**
        @@ -123,7 +123,7 @@ public static void createAgentPoolWithGPUMIG(com.azure.resourcemanager.AzureReso
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * AgentPoolsCreate_WindowsOSSKU.json
              */
             /**
        @@ -147,7 +147,7 @@ public static void createAgentPoolWithWindowsOSSKU(com.azure.resourcemanager.Azu
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * AgentPoolsCreate_DedicatedHostGroup.json
              */
             /**
        @@ -171,7 +171,7 @@ public static void createAgentPoolWithDedicatedHostGroup(com.azure.resourcemanag
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * AgentPoolsCreate_Update.json
              */
             /**
        @@ -200,7 +200,7 @@ public static void createUpdateAgentPool(com.azure.resourcemanager.AzureResource
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * AgentPoolsCreate_WindowsDisableOutboundNAT.json
              */
             /**
        @@ -226,7 +226,7 @@ public static void createUpdateAgentPool(com.azure.resourcemanager.AzureResource
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * AgentPools_Start.json
              */
             /**
        @@ -246,7 +246,7 @@ public static void startAgentPool(com.azure.resourcemanager.AzureResourceManager
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * AgentPoolsCreate_Spot.json
              */
             /**
        @@ -274,7 +274,7 @@ public static void createSpotAgentPool(com.azure.resourcemanager.AzureResourceMa
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * AgentPoolsCreate_Ephemeral.json
              */
             /**
        @@ -299,7 +299,7 @@ public static void createAgentPoolWithEphemeralOSDisk(com.azure.resourcemanager.
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * AgentPoolsCreate_EnableEncryptionAtHost.json
              */
             /**
        @@ -324,7 +324,7 @@ public static void createAgentPoolWithEphemeralOSDisk(com.azure.resourcemanager.
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * AgentPoolsCreate_EnableUltraSSD.json
              */
             /**
        @@ -348,7 +348,7 @@ public static void createAgentPoolWithUltraSSDEnabled(com.azure.resourcemanager.
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * AgentPoolsCreate_WasmWasi.json
              */
             /**
        @@ -375,7 +375,7 @@ public static void createAgentPoolWithUltraSSDEnabled(com.azure.resourcemanager.
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * AgentPoolsCreate_Snapshot.json
              */
             /**
        @@ -400,7 +400,7 @@ public static void createAgentPoolUsingAnAgentPoolSnapshot(com.azure.resourceman
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * AgentPoolsCreate_PPG.json
              */
             /**
        @@ -424,7 +424,7 @@ public static void createAgentPoolWithPPG(com.azure.resourcemanager.AzureResourc
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * AgentPoolsCreate_CustomNodeConfig.json
              */
             /**
        @@ -464,7 +464,7 @@ public static void createAgentPoolWithPPG(com.azure.resourcemanager.AzureResourc
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * AgentPools_Stop.json
              */
             /**
        @@ -484,7 +484,33 @@ public static void stopAgentPool(com.azure.resourcemanager.AzureResourceManager
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
        +     * AgentPoolsCreate_MessageOfTheDay.json
        +     */
        +    /**
        +     * Sample code: Create Agent Pool with Message of the Day.
        +     * 
        +     * @param azure The entry point for accessing resource management APIs in Azure.
        +     */
        +    public static void createAgentPoolWithMessageOfTheDay(com.azure.resourcemanager.AzureResourceManager azure) {
        +        azure.kubernetesClusters()
        +            .manager()
        +            .serviceClient()
        +            .getAgentPools()
        +            .createOrUpdate("rg1", "clustername1", "agentpool1",
        +                new AgentPoolInner().withCount(3)
        +                    .withVmSize("Standard_DS2_v2")
        +                    .withOsDiskSizeGB(64)
        +                    .withMessageOfTheDay("Zm9vCg==")
        +                    .withOsType(OSType.LINUX)
        +                    .withMode(AgentPoolMode.USER)
        +                    .withOrchestratorVersion(""),
        +                null, null, com.azure.core.util.Context.NONE);
        +    }
        +
        +    /*
        +     * x-ms-original-file:
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * AgentPoolsCreate_CRG.json
              */
             /**
        @@ -509,7 +535,7 @@ public static void stopAgentPool(com.azure.resourcemanager.AzureResourceManager
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * AgentPoolsCreate_OSSKU.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsDeleteMachinesSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsDeleteMachinesSamples.java
        index 816975f7c68b..13d400411f8a 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsDeleteMachinesSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsDeleteMachinesSamples.java
        @@ -13,7 +13,7 @@
         public final class AgentPoolsDeleteMachinesSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * AgentPoolsDeleteMachines.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsDeleteSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsDeleteSamples.java
        index 7c5005a15294..61e7622ea461 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsDeleteSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsDeleteSamples.java
        @@ -10,7 +10,7 @@
         public final class AgentPoolsDeleteSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * AgentPoolsDelete.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsGetAvailableAgentPoolVersionsSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsGetAvailableAgentPoolVersionsSamples.java
        index 2ef94ee80e0d..cea5da03842e 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsGetAvailableAgentPoolVersionsSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsGetAvailableAgentPoolVersionsSamples.java
        @@ -10,7 +10,7 @@
         public final class AgentPoolsGetAvailableAgentPoolVersionsSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * AgentPoolsGetAgentPoolAvailableVersions.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsGetSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsGetSamples.java
        index 25ab08618dcc..3a917b81ceab 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsGetSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsGetSamples.java
        @@ -10,7 +10,7 @@
         public final class AgentPoolsGetSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * AgentPoolsGet.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsGetUpgradeProfileSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsGetUpgradeProfileSamples.java
        index d4030a60868e..3d4668a896d3 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsGetUpgradeProfileSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsGetUpgradeProfileSamples.java
        @@ -10,7 +10,7 @@
         public final class AgentPoolsGetUpgradeProfileSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * AgentPoolsGetUpgradeProfile.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsListSamples.java
        index 384f07cde231..42e5e093ba43 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsListSamples.java
        @@ -10,7 +10,7 @@
         public final class AgentPoolsListSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * AgentPoolsList.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsUpgradeNodeImageVersionSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsUpgradeNodeImageVersionSamples.java
        index 96a8e78b1f17..ab16241dcc5b 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsUpgradeNodeImageVersionSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/AgentPoolsUpgradeNodeImageVersionSamples.java
        @@ -10,7 +10,7 @@
         public final class AgentPoolsUpgradeNodeImageVersionSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * AgentPoolsUpgradeNodeImageVersion.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/MachinesGetSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/MachinesGetSamples.java
        index a8efcc9f0b1a..aea32d4576e4 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/MachinesGetSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/MachinesGetSamples.java
        @@ -10,7 +10,7 @@
         public final class MachinesGetSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * MachineGet.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/MachinesListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/MachinesListSamples.java
        index e89f4362fc85..f3c090e2006a 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/MachinesListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/MachinesListSamples.java
        @@ -10,7 +10,7 @@
         public final class MachinesListSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * MachineList.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/MaintenanceConfigurationsCreateOrUpdateSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/MaintenanceConfigurationsCreateOrUpdateSamples.java
        index 6d036189c04e..d91049f66f9d 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/MaintenanceConfigurationsCreateOrUpdateSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/MaintenanceConfigurationsCreateOrUpdateSamples.java
        @@ -23,7 +23,7 @@
         public final class MaintenanceConfigurationsCreateOrUpdateSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * MaintenanceConfigurationsCreate_Update.json
              */
             /**
        @@ -46,7 +46,7 @@ public static void createUpdateMaintenanceConfiguration(com.azure.resourcemanage
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * MaintenanceConfigurationsCreate_Update_MaintenanceWindow.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/MaintenanceConfigurationsDeleteSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/MaintenanceConfigurationsDeleteSamples.java
        index 07849aa482c7..5a28b78feb09 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/MaintenanceConfigurationsDeleteSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/MaintenanceConfigurationsDeleteSamples.java
        @@ -10,7 +10,7 @@
         public final class MaintenanceConfigurationsDeleteSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * MaintenanceConfigurationsDelete.json
              */
             /**
        @@ -28,7 +28,7 @@ public static void deleteMaintenanceConfiguration(com.azure.resourcemanager.Azur
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * MaintenanceConfigurationsDelete_MaintenanceWindow.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/MaintenanceConfigurationsGetSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/MaintenanceConfigurationsGetSamples.java
        index 260fe0302e5a..376ceaa06f85 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/MaintenanceConfigurationsGetSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/MaintenanceConfigurationsGetSamples.java
        @@ -10,7 +10,7 @@
         public final class MaintenanceConfigurationsGetSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * MaintenanceConfigurationsGet.json
              */
             /**
        @@ -28,7 +28,7 @@ public static void getMaintenanceConfiguration(com.azure.resourcemanager.AzureRe
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * MaintenanceConfigurationsGet_MaintenanceWindow.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/MaintenanceConfigurationsListByManagedClusterSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/MaintenanceConfigurationsListByManagedClusterSamples.java
        index f6f4b267c651..25a8e83294b0 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/MaintenanceConfigurationsListByManagedClusterSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/MaintenanceConfigurationsListByManagedClusterSamples.java
        @@ -10,7 +10,7 @@
         public final class MaintenanceConfigurationsListByManagedClusterSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * MaintenanceConfigurationsList_MaintenanceWindow.json
              */
             /**
        @@ -29,7 +29,7 @@ public static void listMaintenanceConfigurationsConfiguredWithMaintenanceWindowB
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * MaintenanceConfigurationsList.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersAbortLatestOperationSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersAbortLatestOperationSamples.java
        index 6eb9a4a28308..c4c3e7fd7646 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersAbortLatestOperationSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersAbortLatestOperationSamples.java
        @@ -10,7 +10,7 @@
         public final class ManagedClustersAbortLatestOperationSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersAbortOperation.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersCreateOrUpdateSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersCreateOrUpdateSamples.java
        index 4df4a54f404c..d1845987819c 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersCreateOrUpdateSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersCreateOrUpdateSamples.java
        @@ -70,7 +70,7 @@
         public final class ManagedClustersCreateOrUpdateSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersCreate_CRG.json
              */
             /**
        @@ -122,7 +122,7 @@ public final class ManagedClustersCreateOrUpdateSamples {
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersCreate_DualStackNetworking.json
              */
             /**
        @@ -185,7 +185,7 @@ public final class ManagedClustersCreateOrUpdateSamples {
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersCreate_PodIdentity.json
              */
             /**
        @@ -237,7 +237,7 @@ public final class ManagedClustersCreateOrUpdateSamples {
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersCreate_UserAssignedNATGateway.json
              */
             /**
        @@ -286,7 +286,7 @@ public static void createManagedClusterWithUserAssignedNATGatewayAsOutboundType(
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersCreate_Update.json
              */
             /**
        @@ -350,7 +350,7 @@ public static void createUpdateManagedCluster(com.azure.resourcemanager.AzureRes
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersCreate_PrivateClusterFQDNSubdomain.json
              */
             /**
        @@ -402,7 +402,7 @@ public static void createUpdateManagedCluster(com.azure.resourcemanager.AzureRes
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersCreate_ManagedNATGateway.json
              */
             /**
        @@ -453,7 +453,7 @@ public static void createManagedClusterWithAKSManagedNATGatewayAsOutboundType(
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersCreate_Premium.json
              */
             /**
        @@ -503,7 +503,7 @@ public static void createManagedClusterWithLongTermSupport(com.azure.resourceman
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersCreate_NodePublicIPPrefix.json
              */
             /**
        @@ -555,7 +555,7 @@ public static void createManagedClusterWithLongTermSupport(com.azure.resourceman
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersCreate_EnableEncryptionAtHost.json
              */
             /**
        @@ -606,7 +606,7 @@ public static void createManagedClusterWithLongTermSupport(com.azure.resourceman
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersCreate_PrivateClusterPublicFQDN.json
              */
             /**
        @@ -657,7 +657,7 @@ public static void createManagedClusterWithLongTermSupport(com.azure.resourceman
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersCreate_HTTPProxy.json
              */
             /**
        @@ -711,7 +711,7 @@ public static void createManagedClusterWithLongTermSupport(com.azure.resourceman
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersCreate_DedicatedHostGroup.json
              */
             /**
        @@ -762,7 +762,7 @@ public static void createManagedClusterWithLongTermSupport(com.azure.resourceman
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersCreate_EnabledFIPS.json
              */
             /**
        @@ -812,7 +812,7 @@ public static void createManagedClusterWithFIPSEnabledOS(com.azure.resourcemanag
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersCreate_SecurityProfile.json
              */
             /**
        @@ -857,7 +857,7 @@ public static void createManagedClusterWithFIPSEnabledOS(com.azure.resourcemanag
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersCreate_PPG.json
              */
             /**
        @@ -908,7 +908,7 @@ public static void createManagedClusterWithPPG(com.azure.resourcemanager.AzureRe
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersCreate_IngressProfile_WebAppRouting.json
              */
             /**
        @@ -951,7 +951,7 @@ public static void createManagedClusterWithWebAppRoutingIngressProfileConfigured
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersCreate_UpdateWithAHUB.json
              */
             /**
        @@ -1006,7 +1006,7 @@ public static void createUpdateManagedClusterWithEnableAHUB(com.azure.resourcema
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersCreate_DisableRunCommand.json
              */
             /**
        @@ -1056,7 +1056,7 @@ public static void createUpdateManagedClusterWithEnableAHUB(com.azure.resourcema
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersCreate_Snapshot.json
              */
             /**
        @@ -1109,7 +1109,7 @@ public static void createUpdateManagedClusterWithEnableAHUB(com.azure.resourcema
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersCreate_AzureServiceMesh.json
              */
             /**
        @@ -1179,7 +1179,7 @@ public static void createUpdateManagedClusterWithEnableAHUB(com.azure.resourcema
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersCreate_AzureKeyvaultSecretsProvider.json
              */
             /**
        @@ -1236,7 +1236,7 @@ public static void createManagedClusterWithAzureKeyVaultSecretsProviderAddon(
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersCreate_OSSKU.json
              */
             /**
        @@ -1290,7 +1290,7 @@ public static void createManagedClusterWithOSSKU(com.azure.resourcemanager.Azure
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersCreate_UpdateWithEnableAzureRBAC.json
              */
             /**
        @@ -1342,7 +1342,7 @@ public static void createManagedClusterWithOSSKU(com.azure.resourcemanager.Azure
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersCreate_EnableUltraSSD.json
              */
             /**
        @@ -1392,7 +1392,7 @@ public static void createManagedClusterWithUltraSSDEnabled(com.azure.resourceman
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersCreate_UpdateWindowsGmsa.json
              */
             /**
        @@ -1448,7 +1448,7 @@ public static void createManagedClusterWithUltraSSDEnabled(com.azure.resourceman
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersCreate_GPUMIG.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersDeleteSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersDeleteSamples.java
        index 81a5ebf6a0fe..e69b6e42989e 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersDeleteSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersDeleteSamples.java
        @@ -10,7 +10,7 @@
         public final class ManagedClustersDeleteSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersDelete.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersGetAccessProfileSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersGetAccessProfileSamples.java
        index 4dc3f8e193fb..3ccbabcb0b50 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersGetAccessProfileSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersGetAccessProfileSamples.java
        @@ -10,7 +10,7 @@
         public final class ManagedClustersGetAccessProfileSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersGetAccessProfile.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersGetByResourceGroupSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersGetByResourceGroupSamples.java
        index 1d1ad7d9c382..921d0ea1d228 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersGetByResourceGroupSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersGetByResourceGroupSamples.java
        @@ -10,7 +10,7 @@
         public final class ManagedClustersGetByResourceGroupSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersGet.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersGetCommandResultSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersGetCommandResultSamples.java
        index bd3db16b3f59..0c102a15a35c 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersGetCommandResultSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersGetCommandResultSamples.java
        @@ -10,7 +10,7 @@
         public final class ManagedClustersGetCommandResultSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * RunCommandResultFailed.json
              */
             /**
        @@ -29,7 +29,7 @@ public static void commandFailedResult(com.azure.resourcemanager.AzureResourceMa
         
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * RunCommandResultSucceed.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersGetMeshRevisionProfileSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersGetMeshRevisionProfileSamples.java
        index e1e28d929c4c..bdf87ee78e1d 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersGetMeshRevisionProfileSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersGetMeshRevisionProfileSamples.java
        @@ -10,7 +10,7 @@
         public final class ManagedClustersGetMeshRevisionProfileSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersGet_MeshRevisionProfile.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersGetMeshUpgradeProfileSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersGetMeshUpgradeProfileSamples.java
        index 9ac93273e3c6..b5e9e9588483 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersGetMeshUpgradeProfileSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersGetMeshUpgradeProfileSamples.java
        @@ -10,7 +10,7 @@
         public final class ManagedClustersGetMeshUpgradeProfileSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersGet_MeshUpgradeProfile.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersGetUpgradeProfileSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersGetUpgradeProfileSamples.java
        index f181ad4900b5..f4be7f38aafa 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersGetUpgradeProfileSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersGetUpgradeProfileSamples.java
        @@ -10,7 +10,7 @@
         public final class ManagedClustersGetUpgradeProfileSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersGetUpgradeProfile.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListByResourceGroupSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListByResourceGroupSamples.java
        index a2d6d7e45438..1af9963f9347 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListByResourceGroupSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListByResourceGroupSamples.java
        @@ -10,7 +10,7 @@
         public final class ManagedClustersListByResourceGroupSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersListByResourceGroup.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListClusterAdminCredentialsSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListClusterAdminCredentialsSamples.java
        index c7a560daf64e..da8c2a645b66 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListClusterAdminCredentialsSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListClusterAdminCredentialsSamples.java
        @@ -10,7 +10,7 @@
         public final class ManagedClustersListClusterAdminCredentialsSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersListClusterAdminCredentials.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListClusterMonitoringUserCredentialsSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListClusterMonitoringUserCredentialsSamples.java
        index 2c8dcdd79427..8caec7788faa 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListClusterMonitoringUserCredentialsSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListClusterMonitoringUserCredentialsSamples.java
        @@ -10,7 +10,7 @@
         public final class ManagedClustersListClusterMonitoringUserCredentialsSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersListClusterMonitoringUserCredentials.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListClusterUserCredentialsSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListClusterUserCredentialsSamples.java
        index 74d871a5a288..57fbe7a136ea 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListClusterUserCredentialsSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListClusterUserCredentialsSamples.java
        @@ -10,7 +10,7 @@
         public final class ManagedClustersListClusterUserCredentialsSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersListClusterUserCredentials.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListKubernetesVersionsSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListKubernetesVersionsSamples.java
        index 7810058415d1..91dfb63c6758 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListKubernetesVersionsSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListKubernetesVersionsSamples.java
        @@ -10,7 +10,7 @@
         public final class ManagedClustersListKubernetesVersionsSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * KubernetesVersions_List.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListMeshRevisionProfilesSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListMeshRevisionProfilesSamples.java
        index a532bcf6ea1b..b7c459cb45a0 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListMeshRevisionProfilesSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListMeshRevisionProfilesSamples.java
        @@ -10,7 +10,7 @@
         public final class ManagedClustersListMeshRevisionProfilesSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersList_MeshRevisionProfiles.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListMeshUpgradeProfilesSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListMeshUpgradeProfilesSamples.java
        index 783fe1bf2187..700ec69fb9d4 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListMeshUpgradeProfilesSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListMeshUpgradeProfilesSamples.java
        @@ -10,7 +10,7 @@
         public final class ManagedClustersListMeshUpgradeProfilesSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersList_MeshUpgradeProfiles.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListOutboundNetworkDependenciesEndpointsSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListOutboundNetworkDependenciesEndpointsSamples.java
        index e9a6c6d8627b..249e116f4b8a 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListOutboundNetworkDependenciesEndpointsSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListOutboundNetworkDependenciesEndpointsSamples.java
        @@ -10,7 +10,7 @@
         public final class ManagedClustersListOutboundNetworkDependenciesEndpointsSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * OutboundNetworkDependenciesEndpointsList.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListSamples.java
        index d9f45d51ae1e..4d4bfafa313b 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListSamples.java
        @@ -10,7 +10,7 @@
         public final class ManagedClustersListSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersList.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersResetAadProfileSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersResetAadProfileSamples.java
        index 4d9fb57d77fd..52ac8dd99330 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersResetAadProfileSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersResetAadProfileSamples.java
        @@ -12,7 +12,7 @@
         public final class ManagedClustersResetAadProfileSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersResetAADProfile.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersResetServicePrincipalProfileSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersResetServicePrincipalProfileSamples.java
        index 1b90264fb075..091d4fd1a111 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersResetServicePrincipalProfileSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersResetServicePrincipalProfileSamples.java
        @@ -12,7 +12,7 @@
         public final class ManagedClustersResetServicePrincipalProfileSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersResetServicePrincipalProfile.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersRotateClusterCertificatesSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersRotateClusterCertificatesSamples.java
        index 4c7b02023f95..0bf8088ccfe8 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersRotateClusterCertificatesSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersRotateClusterCertificatesSamples.java
        @@ -10,7 +10,7 @@
         public final class ManagedClustersRotateClusterCertificatesSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersRotateClusterCertificates.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersRotateServiceAccountSigningKeysSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersRotateServiceAccountSigningKeysSamples.java
        index db1c82319e75..df9062222597 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersRotateServiceAccountSigningKeysSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersRotateServiceAccountSigningKeysSamples.java
        @@ -10,7 +10,7 @@
         public final class ManagedClustersRotateServiceAccountSigningKeysSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersRotateServiceAccountSigningKeys.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersRunCommandSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersRunCommandSamples.java
        index 78d3833d1513..ab80865a8b86 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersRunCommandSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersRunCommandSamples.java
        @@ -12,7 +12,7 @@
         public final class ManagedClustersRunCommandSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * RunCommandRequest.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersStartSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersStartSamples.java
        index 279382dbdfc4..806bf8bdc7ae 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersStartSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersStartSamples.java
        @@ -10,7 +10,7 @@
         public final class ManagedClustersStartSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersStart.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersStopSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersStopSamples.java
        index a435296c2ef6..363f926b3a3d 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersStopSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersStopSamples.java
        @@ -10,7 +10,7 @@
         public final class ManagedClustersStopSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersStop.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersUpdateTagsSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersUpdateTagsSamples.java
        index 20aa10d8d93a..96c11cdf55a7 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersUpdateTagsSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersUpdateTagsSamples.java
        @@ -14,7 +14,7 @@
         public final class ManagedClustersUpdateTagsSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ManagedClustersUpdateTags.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/OperationsListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/OperationsListSamples.java
        index ef39d3ccd9e0..245844b23f8d 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/OperationsListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/OperationsListSamples.java
        @@ -10,7 +10,7 @@
         public final class OperationsListSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * Operation_List.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/PrivateEndpointConnectionsDeleteSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/PrivateEndpointConnectionsDeleteSamples.java
        index 45ac4eadafe6..5aa9dfd3f30b 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/PrivateEndpointConnectionsDeleteSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/PrivateEndpointConnectionsDeleteSamples.java
        @@ -10,7 +10,7 @@
         public final class PrivateEndpointConnectionsDeleteSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * PrivateEndpointConnectionsDelete.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/PrivateEndpointConnectionsGetSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/PrivateEndpointConnectionsGetSamples.java
        index 47524bb2e409..af61c3c12ae2 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/PrivateEndpointConnectionsGetSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/PrivateEndpointConnectionsGetSamples.java
        @@ -10,7 +10,7 @@
         public final class PrivateEndpointConnectionsGetSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * PrivateEndpointConnectionsGet.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/PrivateEndpointConnectionsListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/PrivateEndpointConnectionsListSamples.java
        index 70b86fc4f9d6..d244107408fe 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/PrivateEndpointConnectionsListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/PrivateEndpointConnectionsListSamples.java
        @@ -10,7 +10,7 @@
         public final class PrivateEndpointConnectionsListSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * PrivateEndpointConnectionsList.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/PrivateEndpointConnectionsUpdateSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/PrivateEndpointConnectionsUpdateSamples.java
        index 1c65964e411f..0fce094c75c9 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/PrivateEndpointConnectionsUpdateSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/PrivateEndpointConnectionsUpdateSamples.java
        @@ -14,7 +14,7 @@
         public final class PrivateEndpointConnectionsUpdateSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * PrivateEndpointConnectionsUpdate.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/PrivateLinkResourcesListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/PrivateLinkResourcesListSamples.java
        index f11bebc54c46..5d68bf489d2c 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/PrivateLinkResourcesListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/PrivateLinkResourcesListSamples.java
        @@ -10,7 +10,7 @@
         public final class PrivateLinkResourcesListSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * PrivateLinkResourcesList.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ResolvePrivateLinkServiceIdPostSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ResolvePrivateLinkServiceIdPostSamples.java
        index e0082224da82..aa3c56afb39d 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ResolvePrivateLinkServiceIdPostSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ResolvePrivateLinkServiceIdPostSamples.java
        @@ -12,7 +12,7 @@
         public final class ResolvePrivateLinkServiceIdPostSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * ResolvePrivateLinkServiceId.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/SnapshotsCreateOrUpdateSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/SnapshotsCreateOrUpdateSamples.java
        index 76fe160b9a57..6a77ca3e22b5 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/SnapshotsCreateOrUpdateSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/SnapshotsCreateOrUpdateSamples.java
        @@ -15,7 +15,7 @@
         public final class SnapshotsCreateOrUpdateSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * SnapshotsCreate.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/SnapshotsDeleteSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/SnapshotsDeleteSamples.java
        index ddc08c7565a6..1c933c84284f 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/SnapshotsDeleteSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/SnapshotsDeleteSamples.java
        @@ -10,7 +10,7 @@
         public final class SnapshotsDeleteSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * SnapshotsDelete.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/SnapshotsGetByResourceGroupSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/SnapshotsGetByResourceGroupSamples.java
        index 9f483827aba2..a53a5793f3ad 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/SnapshotsGetByResourceGroupSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/SnapshotsGetByResourceGroupSamples.java
        @@ -10,7 +10,7 @@
         public final class SnapshotsGetByResourceGroupSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * SnapshotsGet.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/SnapshotsListByResourceGroupSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/SnapshotsListByResourceGroupSamples.java
        index 09ed427940b2..3b5d356f737e 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/SnapshotsListByResourceGroupSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/SnapshotsListByResourceGroupSamples.java
        @@ -10,7 +10,7 @@
         public final class SnapshotsListByResourceGroupSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * SnapshotsListByResourceGroup.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/SnapshotsListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/SnapshotsListSamples.java
        index cdf59b996f61..00804469484e 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/SnapshotsListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/SnapshotsListSamples.java
        @@ -10,7 +10,7 @@
         public final class SnapshotsListSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * SnapshotsList.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/SnapshotsUpdateTagsSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/SnapshotsUpdateTagsSamples.java
        index d921720f9c3f..892a1d2a8e4f 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/SnapshotsUpdateTagsSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/SnapshotsUpdateTagsSamples.java
        @@ -14,7 +14,7 @@
         public final class SnapshotsUpdateTagsSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * SnapshotsUpdateTags.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/TrustedAccessRoleBindingsCreateOrUpdateSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/TrustedAccessRoleBindingsCreateOrUpdateSamples.java
        index 28718c552c78..46d40e8a4c26 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/TrustedAccessRoleBindingsCreateOrUpdateSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/TrustedAccessRoleBindingsCreateOrUpdateSamples.java
        @@ -13,7 +13,7 @@
         public final class TrustedAccessRoleBindingsCreateOrUpdateSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * TrustedAccessRoleBindings_CreateOrUpdate.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/TrustedAccessRoleBindingsDeleteSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/TrustedAccessRoleBindingsDeleteSamples.java
        index 2c2fb172453b..6fc11f2e68e8 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/TrustedAccessRoleBindingsDeleteSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/TrustedAccessRoleBindingsDeleteSamples.java
        @@ -10,7 +10,7 @@
         public final class TrustedAccessRoleBindingsDeleteSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * TrustedAccessRoleBindings_Delete.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/TrustedAccessRoleBindingsGetSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/TrustedAccessRoleBindingsGetSamples.java
        index 2a241bf8d10c..1e8cb77f8cef 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/TrustedAccessRoleBindingsGetSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/TrustedAccessRoleBindingsGetSamples.java
        @@ -10,7 +10,7 @@
         public final class TrustedAccessRoleBindingsGetSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * TrustedAccessRoleBindings_Get.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/TrustedAccessRoleBindingsListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/TrustedAccessRoleBindingsListSamples.java
        index fa9f4c246a67..2fcb64890e46 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/TrustedAccessRoleBindingsListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/TrustedAccessRoleBindingsListSamples.java
        @@ -10,7 +10,7 @@
         public final class TrustedAccessRoleBindingsListSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * TrustedAccessRoleBindings_List.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/TrustedAccessRolesListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/TrustedAccessRolesListSamples.java
        index 1b8b07d9ba9f..45947c994e12 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/TrustedAccessRolesListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/TrustedAccessRolesListSamples.java
        @@ -10,7 +10,7 @@
         public final class TrustedAccessRolesListSamples {
             /*
              * x-ms-original-file:
        -     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-09-01/examples/
        +     * specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2024-10-01/examples/
              * TrustedAccessRoles_List.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsCalculateTemplateHashSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsCalculateTemplateHashSamples.java
        index 852498a9efc0..6e2964b72ab5 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsCalculateTemplateHashSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsCalculateTemplateHashSamples.java
        @@ -14,7 +14,7 @@
         public final class DeploymentsCalculateTemplateHashSamples {
             /*
              * x-ms-original-file:
        -     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/CalculateTemplateHash.
        +     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/CalculateTemplateHash.
              * json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsCreateOrUpdateAtManagementGroupScopeSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsCreateOrUpdateAtManagementGroupScopeSamples.java
        index a54b4590ae6f..39b514fa33ae 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsCreateOrUpdateAtManagementGroupScopeSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsCreateOrUpdateAtManagementGroupScopeSamples.java
        @@ -16,7 +16,7 @@
          */
         public final class DeploymentsCreateOrUpdateAtManagementGroupScopeSamples {
             /*
        -     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/
        +     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/
              * PutDeploymentAtManagementGroup.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsCreateOrUpdateAtScopeSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsCreateOrUpdateAtScopeSamples.java
        index f706f6e6fdbf..25f6ae8764e8 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsCreateOrUpdateAtScopeSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsCreateOrUpdateAtScopeSamples.java
        @@ -17,7 +17,7 @@
         public final class DeploymentsCreateOrUpdateAtScopeSamples {
             /*
              * x-ms-original-file:
        -     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/PutDeploymentAtScope.json
        +     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/PutDeploymentAtScope.json
              */
             /**
              * Sample code: Create deployment at a given scope.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsCreateOrUpdateAtSubscriptionScopeSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsCreateOrUpdateAtSubscriptionScopeSamples.java
        index 54a9a8e0af92..f4d5c309cc4e 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsCreateOrUpdateAtSubscriptionScopeSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsCreateOrUpdateAtSubscriptionScopeSamples.java
        @@ -16,7 +16,7 @@
          */
         public final class DeploymentsCreateOrUpdateAtSubscriptionScopeSamples {
             /*
        -     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/
        +     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/
              * PutDeploymentSubscriptionTemplateSpecsWithId.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsCreateOrUpdateAtTenantScopeSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsCreateOrUpdateAtTenantScopeSamples.java
        index dadefed5d23e..a5d14a5ab6f7 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsCreateOrUpdateAtTenantScopeSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsCreateOrUpdateAtTenantScopeSamples.java
        @@ -17,7 +17,7 @@
         public final class DeploymentsCreateOrUpdateAtTenantScopeSamples {
             /*
              * x-ms-original-file:
        -     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/PutDeploymentAtTenant.
        +     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/PutDeploymentAtTenant.
              * json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsCreateOrUpdateSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsCreateOrUpdateSamples.java
        index 63223beeb877..a0b92be00ea9 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsCreateOrUpdateSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsCreateOrUpdateSamples.java
        @@ -18,7 +18,7 @@
          */
         public final class DeploymentsCreateOrUpdateSamples {
             /*
        -     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/
        +     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/
              * PutDeploymentResourceGroup.json
              */
             /**
        @@ -43,7 +43,7 @@ public static void createADeploymentThatWillDeployATemplateWithAUriAndQueryStrin
             }
         
             /*
        -     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/
        +     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/
              * PutDeploymentResourceGroupTemplateSpecsWithId.json
              */
             /**
        @@ -66,7 +66,7 @@ public static void createADeploymentThatWillDeployATemplateSpecWithTheGivenResou
             }
         
             /*
        -     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/
        +     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/
              * PutDeploymentWithOnErrorDeploymentSpecificDeployment.json
              */
             /**
        @@ -91,7 +91,7 @@ public static void createADeploymentThatWillRedeployAnotherDeploymentOnFailure(
             }
         
             /*
        -     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/
        +     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/
              * PutDeploymentWithOnErrorDeploymentLastSuccessful.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsValidateAtManagementGroupScopeSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsValidateAtManagementGroupScopeSamples.java
        new file mode 100644
        index 000000000000..917dc67a5765
        --- /dev/null
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsValidateAtManagementGroupScopeSamples.java
        @@ -0,0 +1,52 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) AutoRest Code Generator.
        +
        +package com.azure.resourcemanager.resources.generated;
        +
        +import com.azure.resourcemanager.resources.models.DeploymentMode;
        +import com.azure.resourcemanager.resources.models.DeploymentProperties;
        +import com.azure.resourcemanager.resources.models.ScopedDeployment;
        +import com.azure.resourcemanager.resources.models.TemplateLink;
        +import java.util.HashMap;
        +import java.util.Map;
        +
        +/**
        + * Samples for Deployments ValidateAtManagementGroupScope.
        + */
        +public final class DeploymentsValidateAtManagementGroupScopeSamples {
        +    /*
        +     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/
        +     * PostDeploymentValidateOnManagementGroup.json
        +     */
        +    /**
        +     * Sample code: Validates a template at management group scope.
        +     * 
        +     * @param azure The entry point for accessing resource management APIs in Azure.
        +     */
        +    public static void validatesATemplateAtManagementGroupScope(com.azure.resourcemanager.AzureResourceManager azure) {
        +        azure.genericResources()
        +            .manager()
        +            .serviceClient()
        +            .getDeployments()
        +            .validateAtManagementGroupScope("my-management-group-id", "my-deployment",
        +                new ScopedDeployment().withLocation("eastus")
        +                    .withProperties(new DeploymentProperties()
        +                        .withTemplateLink(new TemplateLink().withUri("https://example.com/exampleTemplate.json"))
        +                        .withParameters(mapOf())
        +                        .withMode(DeploymentMode.INCREMENTAL)),
        +                com.azure.core.util.Context.NONE);
        +    }
        +
        +    // Use "Map.of" if available
        +    @SuppressWarnings("unchecked")
        +    private static  Map mapOf(Object... inputs) {
        +        Map map = new HashMap<>();
        +        for (int i = 0; i < inputs.length; i += 2) {
        +            String key = (String) inputs[i];
        +            T value = (T) inputs[i + 1];
        +            map.put(key, value);
        +        }
        +        return map;
        +    }
        +}
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsValidateAtScopeSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsValidateAtScopeSamples.java
        new file mode 100644
        index 000000000000..c46d7fdcfd29
        --- /dev/null
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsValidateAtScopeSamples.java
        @@ -0,0 +1,54 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) AutoRest Code Generator.
        +
        +package com.azure.resourcemanager.resources.generated;
        +
        +import com.azure.resourcemanager.resources.fluent.models.DeploymentInner;
        +import com.azure.resourcemanager.resources.models.DeploymentMode;
        +import com.azure.resourcemanager.resources.models.DeploymentProperties;
        +import com.azure.resourcemanager.resources.models.TemplateLink;
        +import java.util.HashMap;
        +import java.util.Map;
        +
        +/**
        + * Samples for Deployments ValidateAtScope.
        + */
        +public final class DeploymentsValidateAtScopeSamples {
        +    /*
        +     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/
        +     * PostDeploymentValidateOnScope.json
        +     */
        +    /**
        +     * Sample code: Validates a template at scope.
        +     * 
        +     * @param azure The entry point for accessing resource management APIs in Azure.
        +     */
        +    public static void validatesATemplateAtScope(com.azure.resourcemanager.AzureResourceManager azure) {
        +        azure.genericResources()
        +            .manager()
        +            .serviceClient()
        +            .getDeployments()
        +            .validateAtScope("subscriptions/00000000-0000-0000-0000-000000000001/resourceGroups/my-resource-group",
        +                "my-deployment",
        +                new DeploymentInner().withProperties(new DeploymentProperties().withTemplateLink(new TemplateLink()
        +                    .withUri("https://example.com/exampleTemplate.json")
        +                    .withQueryString(
        +                        "sv=2019-02-02&st=2019-04-29T22%3A18%3A26Z&se=2019-04-30T02%3A23%3A26Z&sr=b&sp=rw&sip=168.1.5.60-168.1.5.70&spr=https&sig=xxxxxxxx0xxxxxxxxxxxxx%2bxxxxxxxxxxxxxxxxxxxx%3d"))
        +                    .withParameters(mapOf())
        +                    .withMode(DeploymentMode.INCREMENTAL)),
        +                com.azure.core.util.Context.NONE);
        +    }
        +
        +    // Use "Map.of" if available
        +    @SuppressWarnings("unchecked")
        +    private static  Map mapOf(Object... inputs) {
        +        Map map = new HashMap<>();
        +        for (int i = 0; i < inputs.length; i += 2) {
        +            String key = (String) inputs[i];
        +            T value = (T) inputs[i + 1];
        +            map.put(key, value);
        +        }
        +        return map;
        +    }
        +}
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsValidateAtSubscriptionScopeSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsValidateAtSubscriptionScopeSamples.java
        new file mode 100644
        index 000000000000..29a14550c9da
        --- /dev/null
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsValidateAtSubscriptionScopeSamples.java
        @@ -0,0 +1,52 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) AutoRest Code Generator.
        +
        +package com.azure.resourcemanager.resources.generated;
        +
        +import com.azure.resourcemanager.resources.fluent.models.DeploymentInner;
        +import com.azure.resourcemanager.resources.models.DeploymentMode;
        +import com.azure.resourcemanager.resources.models.DeploymentProperties;
        +import com.azure.resourcemanager.resources.models.TemplateLink;
        +import java.util.HashMap;
        +import java.util.Map;
        +
        +/**
        + * Samples for Deployments ValidateAtSubscriptionScope.
        + */
        +public final class DeploymentsValidateAtSubscriptionScopeSamples {
        +    /*
        +     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/
        +     * PostDeploymentValidateOnSubscription.json
        +     */
        +    /**
        +     * Sample code: Validates a template at subscription scope.
        +     * 
        +     * @param azure The entry point for accessing resource management APIs in Azure.
        +     */
        +    public static void validatesATemplateAtSubscriptionScope(com.azure.resourcemanager.AzureResourceManager azure) {
        +        azure.genericResources()
        +            .manager()
        +            .serviceClient()
        +            .getDeployments()
        +            .validateAtSubscriptionScope("my-deployment",
        +                new DeploymentInner().withLocation("eastus")
        +                    .withProperties(new DeploymentProperties()
        +                        .withTemplateLink(new TemplateLink().withUri("https://example.com/exampleTemplate.json"))
        +                        .withParameters(mapOf())
        +                        .withMode(DeploymentMode.INCREMENTAL)),
        +                com.azure.core.util.Context.NONE);
        +    }
        +
        +    // Use "Map.of" if available
        +    @SuppressWarnings("unchecked")
        +    private static  Map mapOf(Object... inputs) {
        +        Map map = new HashMap<>();
        +        for (int i = 0; i < inputs.length; i += 2) {
        +            String key = (String) inputs[i];
        +            T value = (T) inputs[i + 1];
        +            map.put(key, value);
        +        }
        +        return map;
        +    }
        +}
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsValidateAtTenantScopeSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsValidateAtTenantScopeSamples.java
        new file mode 100644
        index 000000000000..30133014abdc
        --- /dev/null
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsValidateAtTenantScopeSamples.java
        @@ -0,0 +1,52 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) AutoRest Code Generator.
        +
        +package com.azure.resourcemanager.resources.generated;
        +
        +import com.azure.resourcemanager.resources.models.DeploymentMode;
        +import com.azure.resourcemanager.resources.models.DeploymentProperties;
        +import com.azure.resourcemanager.resources.models.ScopedDeployment;
        +import com.azure.resourcemanager.resources.models.TemplateLink;
        +import java.util.HashMap;
        +import java.util.Map;
        +
        +/**
        + * Samples for Deployments ValidateAtTenantScope.
        + */
        +public final class DeploymentsValidateAtTenantScopeSamples {
        +    /*
        +     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/
        +     * PostDeploymentValidateOnTenant.json
        +     */
        +    /**
        +     * Sample code: Validates a template at tenant scope.
        +     * 
        +     * @param azure The entry point for accessing resource management APIs in Azure.
        +     */
        +    public static void validatesATemplateAtTenantScope(com.azure.resourcemanager.AzureResourceManager azure) {
        +        azure.genericResources()
        +            .manager()
        +            .serviceClient()
        +            .getDeployments()
        +            .validateAtTenantScope("my-deployment",
        +                new ScopedDeployment().withLocation("eastus")
        +                    .withProperties(new DeploymentProperties()
        +                        .withTemplateLink(new TemplateLink().withUri("https://example.com/exampleTemplate.json"))
        +                        .withParameters(mapOf())
        +                        .withMode(DeploymentMode.INCREMENTAL)),
        +                com.azure.core.util.Context.NONE);
        +    }
        +
        +    // Use "Map.of" if available
        +    @SuppressWarnings("unchecked")
        +    private static  Map mapOf(Object... inputs) {
        +        Map map = new HashMap<>();
        +        for (int i = 0; i < inputs.length; i += 2) {
        +            String key = (String) inputs[i];
        +            T value = (T) inputs[i + 1];
        +            map.put(key, value);
        +        }
        +        return map;
        +    }
        +}
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsValidateSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsValidateSamples.java
        new file mode 100644
        index 000000000000..e852db6e7f10
        --- /dev/null
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsValidateSamples.java
        @@ -0,0 +1,53 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) AutoRest Code Generator.
        +
        +package com.azure.resourcemanager.resources.generated;
        +
        +import com.azure.resourcemanager.resources.fluent.models.DeploymentInner;
        +import com.azure.resourcemanager.resources.models.DeploymentMode;
        +import com.azure.resourcemanager.resources.models.DeploymentProperties;
        +import com.azure.resourcemanager.resources.models.TemplateLink;
        +import java.util.HashMap;
        +import java.util.Map;
        +
        +/**
        + * Samples for Deployments Validate.
        + */
        +public final class DeploymentsValidateSamples {
        +    /*
        +     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/
        +     * PostDeploymentValidateOnResourceGroup.json
        +     */
        +    /**
        +     * Sample code: Validates a template at resource group scope.
        +     * 
        +     * @param azure The entry point for accessing resource management APIs in Azure.
        +     */
        +    public static void validatesATemplateAtResourceGroupScope(com.azure.resourcemanager.AzureResourceManager azure) {
        +        azure.genericResources()
        +            .manager()
        +            .serviceClient()
        +            .getDeployments()
        +            .validate("my-resource-group", "my-deployment",
        +                new DeploymentInner().withProperties(new DeploymentProperties().withTemplateLink(new TemplateLink()
        +                    .withUri("https://example.com/exampleTemplate.json")
        +                    .withQueryString(
        +                        "sv=2019-02-02&st=2019-04-29T22%3A18%3A26Z&se=2019-04-30T02%3A23%3A26Z&sr=b&sp=rw&sip=168.1.5.60-168.1.5.70&spr=https&sig=xxxxxxxx0xxxxxxxxxxxxx%2bxxxxxxxxxxxxxxxxxxxx%3d"))
        +                    .withParameters(mapOf())
        +                    .withMode(DeploymentMode.INCREMENTAL)),
        +                com.azure.core.util.Context.NONE);
        +    }
        +
        +    // Use "Map.of" if available
        +    @SuppressWarnings("unchecked")
        +    private static  Map mapOf(Object... inputs) {
        +        Map map = new HashMap<>();
        +        for (int i = 0; i < inputs.length; i += 2) {
        +            String key = (String) inputs[i];
        +            T value = (T) inputs[i + 1];
        +            map.put(key, value);
        +        }
        +        return map;
        +    }
        +}
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsWhatIfAtManagementGroupScopeSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsWhatIfAtManagementGroupScopeSamples.java
        index a0c54147e5b5..40cfeb5c5a1f 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsWhatIfAtManagementGroupScopeSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsWhatIfAtManagementGroupScopeSamples.java
        @@ -16,7 +16,7 @@
          */
         public final class DeploymentsWhatIfAtManagementGroupScopeSamples {
             /*
        -     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/
        +     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/
              * PostDeploymentWhatIfOnManagementGroup.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsWhatIfAtSubscriptionScopeSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsWhatIfAtSubscriptionScopeSamples.java
        index c0308fd6f167..78fe4f2fd369 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsWhatIfAtSubscriptionScopeSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsWhatIfAtSubscriptionScopeSamples.java
        @@ -16,7 +16,7 @@
          */
         public final class DeploymentsWhatIfAtSubscriptionScopeSamples {
             /*
        -     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/
        +     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/
              * PostDeploymentWhatIfOnSubscription.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsWhatIfAtTenantScopeSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsWhatIfAtTenantScopeSamples.java
        index bdf1f6758a4f..ce278885001a 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsWhatIfAtTenantScopeSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsWhatIfAtTenantScopeSamples.java
        @@ -16,7 +16,7 @@
          */
         public final class DeploymentsWhatIfAtTenantScopeSamples {
             /*
        -     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/
        +     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/
              * PostDeploymentWhatIfOnTenant.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsWhatIfSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsWhatIfSamples.java
        index 6e9e6502bde7..e2faa18e8e9e 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsWhatIfSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/DeploymentsWhatIfSamples.java
        @@ -16,7 +16,7 @@
          */
         public final class DeploymentsWhatIfSamples {
             /*
        -     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/
        +     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/
              * PostDeploymentWhatIfOnResourceGroup.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ProviderResourceTypesListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ProviderResourceTypesListSamples.java
        index 7e080b20b1ad..bb0cad0bcce0 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ProviderResourceTypesListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ProviderResourceTypesListSamples.java
        @@ -10,7 +10,7 @@
         public final class ProviderResourceTypesListSamples {
             /*
              * x-ms-original-file:
        -     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/GetProviderResourceTypes.
        +     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/GetProviderResourceTypes.
              * json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ProvidersGetAtTenantScopeSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ProvidersGetAtTenantScopeSamples.java
        index e8f971d1e518..a74bdcd3842c 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ProvidersGetAtTenantScopeSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ProvidersGetAtTenantScopeSamples.java
        @@ -10,7 +10,7 @@
         public final class ProvidersGetAtTenantScopeSamples {
             /*
              * x-ms-original-file:
        -     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/GetNamedProviderAtTenant.
        +     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/GetNamedProviderAtTenant.
              * json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ProvidersGetSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ProvidersGetSamples.java
        index aa2c7f9002a5..363924841197 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ProvidersGetSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ProvidersGetSamples.java
        @@ -10,7 +10,7 @@
         public final class ProvidersGetSamples {
             /*
              * x-ms-original-file:
        -     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/GetProvider.json
        +     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/GetProvider.json
              */
             /**
              * Sample code: Get provider.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ProvidersListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ProvidersListSamples.java
        index 5605cae68963..05ee7203082a 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ProvidersListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ProvidersListSamples.java
        @@ -10,7 +10,7 @@
         public final class ProvidersListSamples {
             /*
              * x-ms-original-file:
        -     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/GetProviders.json
        +     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/GetProviders.json
              */
             /**
              * Sample code: Get providers.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ProvidersProviderPermissionsSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ProvidersProviderPermissionsSamples.java
        index 0207d56b1cfc..6cca244f4917 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ProvidersProviderPermissionsSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ProvidersProviderPermissionsSamples.java
        @@ -10,7 +10,7 @@
         public final class ProvidersProviderPermissionsSamples {
             /*
              * x-ms-original-file:
        -     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/GetProviderPermissions.
        +     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/GetProviderPermissions.
              * json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ResourceGroupsCreateOrUpdateSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ResourceGroupsCreateOrUpdateSamples.java
        index 599fb0529491..1e4c4896af3d 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ResourceGroupsCreateOrUpdateSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ResourceGroupsCreateOrUpdateSamples.java
        @@ -12,7 +12,7 @@
         public final class ResourceGroupsCreateOrUpdateSamples {
             /*
              * x-ms-original-file:
        -     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/CreateResourceGroup.json
        +     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/CreateResourceGroup.json
              */
             /**
              * Sample code: Create or update a resource group.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ResourceGroupsDeleteSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ResourceGroupsDeleteSamples.java
        index 117e6664c58b..aa6ba311a1d2 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ResourceGroupsDeleteSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ResourceGroupsDeleteSamples.java
        @@ -9,7 +9,7 @@
          */
         public final class ResourceGroupsDeleteSamples {
             /*
        -     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/
        +     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/
              * ForceDeleteVMsInResourceGroup.json
              */
             /**
        @@ -27,7 +27,7 @@ public final class ResourceGroupsDeleteSamples {
             }
         
             /*
        -     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/
        +     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/
              * ForceDeleteVMsAndVMSSInResourceGroup.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ResourceGroupsExportTemplateSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ResourceGroupsExportTemplateSamples.java
        index 1bc2f8db03d2..d28e2cb4b436 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ResourceGroupsExportTemplateSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/ResourceGroupsExportTemplateSamples.java
        @@ -13,7 +13,7 @@
          */
         public final class ResourceGroupsExportTemplateSamples {
             /*
        -     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/
        +     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/
              * ExportResourceGroupAsBicep.json
              */
             /**
        @@ -35,7 +35,7 @@ public static void exportAResourceGroupAsBicep(com.azure.resourcemanager.AzureRe
         
             /*
              * x-ms-original-file:
        -     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/ExportResourceGroup.json
        +     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/ExportResourceGroup.json
              */
             /**
              * Sample code: Export a resource group.
        @@ -52,7 +52,7 @@ public static void exportAResourceGroup(com.azure.resourcemanager.AzureResourceM
             }
         
             /*
        -     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/
        +     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/
              * ExportResourceGroupWithFiltering.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/TagOperationsCreateOrUpdateAtScopeSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/TagOperationsCreateOrUpdateAtScopeSamples.java
        index 1a5d7aef4eb8..25dea43aaf2d 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/TagOperationsCreateOrUpdateAtScopeSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/TagOperationsCreateOrUpdateAtScopeSamples.java
        @@ -15,7 +15,7 @@
         public final class TagOperationsCreateOrUpdateAtScopeSamples {
             /*
              * x-ms-original-file:
        -     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/PutTagsResource.json
        +     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/PutTagsResource.json
              */
             /**
              * Sample code: Update tags on a resource.
        @@ -36,7 +36,7 @@ public static void updateTagsOnAResource(com.azure.resourcemanager.AzureResource
         
             /*
              * x-ms-original-file:
        -     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/PutTagsSubscription.json
        +     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/PutTagsSubscription.json
              */
             /**
              * Sample code: Update tags on a subscription.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/TagOperationsDeleteAtScopeSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/TagOperationsDeleteAtScopeSamples.java
        index 232db1b5320b..65952dff836b 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/TagOperationsDeleteAtScopeSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/TagOperationsDeleteAtScopeSamples.java
        @@ -10,7 +10,7 @@
         public final class TagOperationsDeleteAtScopeSamples {
             /*
              * x-ms-original-file:
        -     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/DeleteTagsResource.json
        +     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/DeleteTagsResource.json
              */
             /**
              * Sample code: Update tags on a resource.
        @@ -29,7 +29,7 @@ public static void updateTagsOnAResource(com.azure.resourcemanager.AzureResource
         
             /*
              * x-ms-original-file:
        -     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/DeleteTagsSubscription.
        +     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/DeleteTagsSubscription.
              * json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/TagOperationsGetAtScopeSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/TagOperationsGetAtScopeSamples.java
        index 552d153244ce..970cd56118a0 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/TagOperationsGetAtScopeSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/TagOperationsGetAtScopeSamples.java
        @@ -10,7 +10,7 @@
         public final class TagOperationsGetAtScopeSamples {
             /*
              * x-ms-original-file:
        -     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/GetTagsResource.json
        +     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/GetTagsResource.json
              */
             /**
              * Sample code: Get tags on a resource.
        @@ -29,7 +29,7 @@ public static void getTagsOnAResource(com.azure.resourcemanager.AzureResourceMan
         
             /*
              * x-ms-original-file:
        -     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/GetTagsSubscription.json
        +     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/GetTagsSubscription.json
              */
             /**
              * Sample code: Get tags on a subscription.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/TagOperationsUpdateAtScopeSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/TagOperationsUpdateAtScopeSamples.java
        index d5483d262a0d..3960e131a440 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/TagOperationsUpdateAtScopeSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/resources/generated/TagOperationsUpdateAtScopeSamples.java
        @@ -16,7 +16,7 @@
         public final class TagOperationsUpdateAtScopeSamples {
             /*
              * x-ms-original-file:
        -     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/PatchTagsResource.json
        +     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/PatchTagsResource.json
              */
             /**
              * Sample code: Update tags on a resource.
        @@ -38,7 +38,7 @@ public static void updateTagsOnAResource(com.azure.resourcemanager.AzureResource
         
             /*
              * x-ms-original-file:
        -     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-03-01/examples/PatchTagsSubscription.
        +     * specification/resources/resource-manager/Microsoft.Resources/stable/2024-11-01/examples/PatchTagsSubscription.
              * json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersClearLegalHoldSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersClearLegalHoldSamples.java
        index fff2b674dee4..41ea6fb36fc8 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersClearLegalHoldSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersClearLegalHoldSamples.java
        @@ -13,7 +13,7 @@
         public final class BlobContainersClearLegalHoldSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/BlobContainersClearLegalHold.
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/BlobContainersClearLegalHold.
              * json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersCreateOrUpdateImmutabilityPolicySamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersCreateOrUpdateImmutabilityPolicySamples.java
        index 36b62364f1b5..640181c63b6c 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersCreateOrUpdateImmutabilityPolicySamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersCreateOrUpdateImmutabilityPolicySamples.java
        @@ -11,7 +11,7 @@
          */
         public final class BlobContainersCreateOrUpdateImmutabilityPolicySamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * BlobContainersPutImmutabilityPolicy.json
              */
             /**
        @@ -31,7 +31,7 @@ public static void createOrUpdateImmutabilityPolicy(com.azure.resourcemanager.Az
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * BlobContainersPutImmutabilityPolicyAllowProtectedAppendWritesAll.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersCreateSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersCreateSamples.java
        index 3272e5d248c1..36f4c1504675 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersCreateSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersCreateSamples.java
        @@ -12,7 +12,7 @@
          */
         public final class BlobContainersCreateSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * BlobContainersPutDefaultEncryptionScope.json
              */
             /**
        @@ -32,7 +32,7 @@ public static void putContainerWithDefaultEncryptionScope(com.azure.resourcemana
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * BlobContainersPutObjectLevelWorm.json
              */
             /**
        @@ -52,7 +52,7 @@ public static void putContainerWithObjectLevelWorm(com.azure.resourcemanager.Azu
         
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/BlobContainersPut.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/BlobContainersPut.json
              */
             /**
              * Sample code: PutContainers.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersDeleteImmutabilityPolicySamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersDeleteImmutabilityPolicySamples.java
        index ad8b367befb3..d8f5b7c8731f 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersDeleteImmutabilityPolicySamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersDeleteImmutabilityPolicySamples.java
        @@ -9,7 +9,7 @@
          */
         public final class BlobContainersDeleteImmutabilityPolicySamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * BlobContainersDeleteImmutabilityPolicy.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersDeleteSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersDeleteSamples.java
        index d840ad53b92d..e71fa1a1a153 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersDeleteSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersDeleteSamples.java
        @@ -10,7 +10,7 @@
         public final class BlobContainersDeleteSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/BlobContainersDelete.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/BlobContainersDelete.json
              */
             /**
              * Sample code: DeleteContainers.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersExtendImmutabilityPolicySamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersExtendImmutabilityPolicySamples.java
        index 2bf4f194ae6c..673328f24ad3 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersExtendImmutabilityPolicySamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersExtendImmutabilityPolicySamples.java
        @@ -11,7 +11,7 @@
          */
         public final class BlobContainersExtendImmutabilityPolicySamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * BlobContainersExtendImmutabilityPolicy.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersGetImmutabilityPolicySamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersGetImmutabilityPolicySamples.java
        index 3f78e46b182b..e4a5fd20c28f 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersGetImmutabilityPolicySamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersGetImmutabilityPolicySamples.java
        @@ -9,7 +9,7 @@
          */
         public final class BlobContainersGetImmutabilityPolicySamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * BlobContainersGetImmutabilityPolicy.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersGetSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersGetSamples.java
        index 2a4706af2b76..82fbf728eabc 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersGetSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersGetSamples.java
        @@ -10,7 +10,7 @@
         public final class BlobContainersGetSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/BlobContainersGet.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/BlobContainersGet.json
              */
             /**
              * Sample code: GetContainers.
        @@ -26,7 +26,7 @@ public static void getContainers(com.azure.resourcemanager.AzureResourceManager
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * BlobContainersGetWithAllowProtectedAppendWritesAll.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersLeaseSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersLeaseSamples.java
        index bdc2c82f435c..4b5db8ceb97e 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersLeaseSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersLeaseSamples.java
        @@ -13,7 +13,7 @@
         public final class BlobContainersLeaseSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/BlobContainersLease_Break.
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/BlobContainersLease_Break.
              * json
              */
             /**
        @@ -34,7 +34,7 @@ public static void breakALeaseOnAContainer(com.azure.resourcemanager.AzureResour
         
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/BlobContainersLease_Acquire.
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/BlobContainersLease_Acquire.
              * json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersListSamples.java
        index e556040e768b..3c1362be6597 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersListSamples.java
        @@ -12,7 +12,7 @@
         public final class BlobContainersListSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/BlobContainersList.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/BlobContainersList.json
              */
             /**
              * Sample code: ListContainers.
        @@ -29,7 +29,7 @@ public static void listContainers(com.azure.resourcemanager.AzureResourceManager
         
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/DeletedBlobContainersList.
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/DeletedBlobContainersList.
              * json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersLockImmutabilityPolicySamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersLockImmutabilityPolicySamples.java
        index f9d9852540e8..f3886464ed83 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersLockImmutabilityPolicySamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersLockImmutabilityPolicySamples.java
        @@ -9,7 +9,7 @@
          */
         public final class BlobContainersLockImmutabilityPolicySamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * BlobContainersLockImmutabilityPolicy.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersObjectLevelWormSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersObjectLevelWormSamples.java
        index 5f73036b1402..1133bcc742da 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersObjectLevelWormSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersObjectLevelWormSamples.java
        @@ -9,7 +9,7 @@
          */
         public final class BlobContainersObjectLevelWormSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * ObjectLevelWormContainerMigration.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersSetLegalHoldSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersSetLegalHoldSamples.java
        index bce6d3974a37..c5e11f205e88 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersSetLegalHoldSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersSetLegalHoldSamples.java
        @@ -13,7 +13,7 @@
         public final class BlobContainersSetLegalHoldSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/BlobContainersSetLegalHold.
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/BlobContainersSetLegalHold.
              * json
              */
             /**
        @@ -31,7 +31,7 @@ public static void setLegalHoldContainers(com.azure.resourcemanager.AzureResourc
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * BlobContainersSetLegalHoldAllowProtectedAppendWritesAll.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersUpdateSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersUpdateSamples.java
        index cd44115abfb9..164fd99484c3 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersUpdateSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobContainersUpdateSamples.java
        @@ -15,7 +15,7 @@
         public final class BlobContainersUpdateSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/BlobContainersPatch.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/BlobContainersPatch.json
              */
             /**
              * Sample code: UpdateContainers.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobInventoryPoliciesCreateOrUpdateSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobInventoryPoliciesCreateOrUpdateSamples.java
        index 0b4755a69d62..674a32cba5d0 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobInventoryPoliciesCreateOrUpdateSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobInventoryPoliciesCreateOrUpdateSamples.java
        @@ -22,7 +22,7 @@
          */
         public final class BlobInventoryPoliciesCreateOrUpdateSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountSetBlobInventoryPolicyIncludeDeleteAndNewSchemaForNonHnsAccount.json
              */
             /**
        @@ -84,7 +84,7 @@ public static void storageAccountSetBlobInventoryPolicyIncludeDeleteAndNewSchema
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountSetBlobInventoryPolicy.json
              */
             /**
        @@ -138,7 +138,7 @@ public static void storageAccountSetBlobInventoryPolicy(com.azure.resourcemanage
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountSetBlobInventoryPolicyIncludeDeleteAndNewSchemaForHnsAccount.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobInventoryPoliciesDeleteSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobInventoryPoliciesDeleteSamples.java
        index 8fecb11da05d..a3c3aaa20713 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobInventoryPoliciesDeleteSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobInventoryPoliciesDeleteSamples.java
        @@ -11,7 +11,7 @@
          */
         public final class BlobInventoryPoliciesDeleteSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountDeleteBlobInventoryPolicy.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobInventoryPoliciesGetSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobInventoryPoliciesGetSamples.java
        index 2f078bb226ce..02c9cb7f62c0 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobInventoryPoliciesGetSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobInventoryPoliciesGetSamples.java
        @@ -11,7 +11,7 @@
          */
         public final class BlobInventoryPoliciesGetSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountGetBlobInventoryPolicy.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobInventoryPoliciesListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobInventoryPoliciesListSamples.java
        index 1ae2190788cc..b5dab5b59a83 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobInventoryPoliciesListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobInventoryPoliciesListSamples.java
        @@ -9,7 +9,7 @@
          */
         public final class BlobInventoryPoliciesListSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountListBlobInventoryPolicy.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobServicesGetServicePropertiesSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobServicesGetServicePropertiesSamples.java
        index d1f6e540c8db..2dc81c0a255d 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobServicesGetServicePropertiesSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobServicesGetServicePropertiesSamples.java
        @@ -10,7 +10,7 @@
         public final class BlobServicesGetServicePropertiesSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/BlobServicesGet.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/BlobServicesGet.json
              */
             /**
              * Sample code: GetBlobServices.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobServicesListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobServicesListSamples.java
        index 586d6ac221f5..9e008a7052f0 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobServicesListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobServicesListSamples.java
        @@ -10,7 +10,7 @@
         public final class BlobServicesListSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/BlobServicesList.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/BlobServicesList.json
              */
             /**
              * Sample code: ListBlobServices.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobServicesSetServicePropertiesSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobServicesSetServicePropertiesSamples.java
        index da5cc3e798fe..d48f7bbf1296 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobServicesSetServicePropertiesSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/BlobServicesSetServicePropertiesSamples.java
        @@ -20,7 +20,7 @@
         public final class BlobServicesSetServicePropertiesSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/BlobServicesPut.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/BlobServicesPut.json
              */
             /**
              * Sample code: PutBlobServices.
        @@ -61,7 +61,7 @@ public static void putBlobServices(com.azure.resourcemanager.AzureResourceManage
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * BlobServicesPutAllowPermanentDelete.json
              */
             /**
        @@ -83,7 +83,7 @@ public static void blobServicesPutAllowPermanentDelete(com.azure.resourcemanager
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * BlobServicesPutLastAccessTimeBasedTracking.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/DeletedAccountsGetSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/DeletedAccountsGetSamples.java
        index f22374feb3df..7adb9f266280 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/DeletedAccountsGetSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/DeletedAccountsGetSamples.java
        @@ -10,7 +10,7 @@
         public final class DeletedAccountsGetSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/DeletedAccountGet.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/DeletedAccountGet.json
              */
             /**
              * Sample code: DeletedAccountGet.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/DeletedAccountsListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/DeletedAccountsListSamples.java
        index e1dce2b5d887..db75068ff9c0 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/DeletedAccountsListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/DeletedAccountsListSamples.java
        @@ -10,7 +10,7 @@
         public final class DeletedAccountsListSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/DeletedAccountList.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/DeletedAccountList.json
              */
             /**
              * Sample code: DeletedAccountList.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/EncryptionScopesGetSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/EncryptionScopesGetSamples.java
        index 98b97a022770..ec692f7d8d83 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/EncryptionScopesGetSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/EncryptionScopesGetSamples.java
        @@ -9,7 +9,7 @@
          */
         public final class EncryptionScopesGetSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountGetEncryptionScope.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/EncryptionScopesListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/EncryptionScopesListSamples.java
        index 841dc1b4770b..685a02602222 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/EncryptionScopesListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/EncryptionScopesListSamples.java
        @@ -9,7 +9,7 @@
          */
         public final class EncryptionScopesListSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountEncryptionScopeList.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/EncryptionScopesPatchSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/EncryptionScopesPatchSamples.java
        index 5e2af58b042b..88b7196e168c 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/EncryptionScopesPatchSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/EncryptionScopesPatchSamples.java
        @@ -13,7 +13,7 @@
          */
         public final class EncryptionScopesPatchSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountPatchEncryptionScope.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/EncryptionScopesPutSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/EncryptionScopesPutSamples.java
        index 0e3941d5201e..ad377917a205 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/EncryptionScopesPutSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/EncryptionScopesPutSamples.java
        @@ -11,7 +11,7 @@
          */
         public final class EncryptionScopesPutSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountPutEncryptionScopeWithInfrastructureEncryption.json
              */
             /**
        @@ -30,7 +30,7 @@ public static void storageAccountPutEncryptionScopeWithInfrastructureEncryption(
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountPutEncryptionScope.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileServicesGetServicePropertiesSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileServicesGetServicePropertiesSamples.java
        index 58a8c2b18619..57ea598bed0f 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileServicesGetServicePropertiesSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileServicesGetServicePropertiesSamples.java
        @@ -10,7 +10,7 @@
         public final class FileServicesGetServicePropertiesSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/FileServicesGet.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/FileServicesGet.json
              */
             /**
              * Sample code: GetFileServices.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileServicesGetServiceUsageSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileServicesGetServiceUsageSamples.java
        new file mode 100644
        index 000000000000..096502aeecef
        --- /dev/null
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileServicesGetServiceUsageSamples.java
        @@ -0,0 +1,27 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) AutoRest Code Generator.
        +
        +package com.azure.resourcemanager.storage.generated;
        +
        +/**
        + * Samples for FileServices GetServiceUsage.
        + */
        +public final class FileServicesGetServiceUsageSamples {
        +    /*
        +     * x-ms-original-file:
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/FileServicesGetUsage.json
        +     */
        +    /**
        +     * Sample code: GetFileServiceUsage.
        +     * 
        +     * @param azure The entry point for accessing resource management APIs in Azure.
        +     */
        +    public static void getFileServiceUsage(com.azure.resourcemanager.AzureResourceManager azure) {
        +        azure.storageAccounts()
        +            .manager()
        +            .serviceClient()
        +            .getFileServices()
        +            .getServiceUsageWithResponse("res4410", "sto8607", com.azure.core.util.Context.NONE);
        +    }
        +}
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileServicesListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileServicesListSamples.java
        index dc264dabebaa..655086628997 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileServicesListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileServicesListSamples.java
        @@ -10,7 +10,7 @@
         public final class FileServicesListSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/FileServicesList.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/FileServicesList.json
              */
             /**
              * Sample code: ListFileServices.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileServicesListServiceUsagesSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileServicesListServiceUsagesSamples.java
        new file mode 100644
        index 000000000000..df6823e0780a
        --- /dev/null
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileServicesListServiceUsagesSamples.java
        @@ -0,0 +1,27 @@
        +// Copyright (c) Microsoft Corporation. All rights reserved.
        +// Licensed under the MIT License.
        +// Code generated by Microsoft (R) AutoRest Code Generator.
        +
        +package com.azure.resourcemanager.storage.generated;
        +
        +/**
        + * Samples for FileServices ListServiceUsages.
        + */
        +public final class FileServicesListServiceUsagesSamples {
        +    /*
        +     * x-ms-original-file:
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/FileServicesListUsages.json
        +     */
        +    /**
        +     * Sample code: ListFileServiceUsages.
        +     * 
        +     * @param azure The entry point for accessing resource management APIs in Azure.
        +     */
        +    public static void listFileServiceUsages(com.azure.resourcemanager.AzureResourceManager azure) {
        +        azure.storageAccounts()
        +            .manager()
        +            .serviceClient()
        +            .getFileServices()
        +            .listServiceUsages("res4410", "sto8607", null, com.azure.core.util.Context.NONE);
        +    }
        +}
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileServicesSetServicePropertiesSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileServicesSetServicePropertiesSamples.java
        index 10492ada8c90..98cbd55886ee 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileServicesSetServicePropertiesSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileServicesSetServicePropertiesSamples.java
        @@ -19,7 +19,7 @@
         public final class FileServicesSetServicePropertiesSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/FileServicesPut.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/FileServicesPut.json
              */
             /**
              * Sample code: PutFileServices.
        @@ -56,7 +56,7 @@ public static void putFileServices(com.azure.resourcemanager.AzureResourceManage
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * FileServicesPut_EnableSecureSmbFeatures.json
              */
             /**
        @@ -79,7 +79,7 @@ public static void putFileServicesEnableSecureSmbFeatures(com.azure.resourcemana
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * FileServicesPut_EnableSMBMultichannel.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileSharesCreateSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileSharesCreateSamples.java
        index e09b75b5fcd8..3c31ad7d4c48 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileSharesCreateSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileSharesCreateSamples.java
        @@ -6,6 +6,7 @@
         
         import com.azure.resourcemanager.storage.fluent.models.FileShareInner;
         import com.azure.resourcemanager.storage.models.EnabledProtocols;
        +import com.azure.resourcemanager.storage.models.FileSharePropertiesFileSharePaidBursting;
         import com.azure.resourcemanager.storage.models.ShareAccessTier;
         
         /**
        @@ -14,7 +15,27 @@
         public final class FileSharesCreateSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/FileSharesPut_AccessTier.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/FileSharesPut_ProvisionedV2.
        +     * json
        +     */
        +    /**
        +     * Sample code: PutSharesProvisionedV2.
        +     * 
        +     * @param azure The entry point for accessing resource management APIs in Azure.
        +     */
        +    public static void putSharesProvisionedV2(com.azure.resourcemanager.AzureResourceManager azure) {
        +        azure.storageAccounts()
        +            .manager()
        +            .serviceClient()
        +            .getFileShares()
        +            .createWithResponse("res346", "sto666", "share1235",
        +                new FileShareInner().withShareQuota(100).withProvisionedIops(5000).withProvisionedBandwidthMibps(200),
        +                null, com.azure.core.util.Context.NONE);
        +    }
        +
        +    /*
        +     * x-ms-original-file:
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/FileSharesPut_AccessTier.json
              */
             /**
              * Sample code: PutShares with Access Tier.
        @@ -32,7 +53,7 @@ public static void putSharesWithAccessTier(com.azure.resourcemanager.AzureResour
         
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/FileSharesPut_NFS.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/FileSharesPut_NFS.json
              */
             /**
              * Sample code: Create NFS Shares.
        @@ -51,7 +72,30 @@ public static void createNFSShares(com.azure.resourcemanager.AzureResourceManage
         
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/FileSharesPut.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/FileSharesPut_PaidBursting.
        +     * json
        +     */
        +    /**
        +     * Sample code: PutShares with Paid Bursting.
        +     * 
        +     * @param azure The entry point for accessing resource management APIs in Azure.
        +     */
        +    public static void putSharesWithPaidBursting(com.azure.resourcemanager.AzureResourceManager azure) {
        +        azure.storageAccounts()
        +            .manager()
        +            .serviceClient()
        +            .getFileShares()
        +            .createWithResponse("res346", "sto666", "share1235",
        +                new FileShareInner().withFileSharePaidBursting(
        +                    new FileSharePropertiesFileSharePaidBursting().withPaidBurstingEnabled(true)
        +                        .withPaidBurstingMaxIops(102400)
        +                        .withPaidBurstingMaxBandwidthMibps(10340)),
        +                null, com.azure.core.util.Context.NONE);
        +    }
        +
        +    /*
        +     * x-ms-original-file:
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/FileSharesPut.json
              */
             /**
              * Sample code: PutShares.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileSharesDeleteSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileSharesDeleteSamples.java
        index 749260264bf0..a38bff0da044 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileSharesDeleteSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileSharesDeleteSamples.java
        @@ -10,7 +10,7 @@
         public final class FileSharesDeleteSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/FileSharesDelete.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/FileSharesDelete.json
              */
             /**
              * Sample code: DeleteShares.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileSharesGetSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileSharesGetSamples.java
        index 0bca1ef38944..e92739026be5 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileSharesGetSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileSharesGetSamples.java
        @@ -10,7 +10,7 @@
         public final class FileSharesGetSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/FileSharesGet_Stats.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/FileSharesGet_Stats.json
              */
             /**
              * Sample code: GetShareStats.
        @@ -27,7 +27,43 @@ public static void getShareStats(com.azure.resourcemanager.AzureResourceManager
         
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/FileSharesGet.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/FileSharesGet_PaidBursting.
        +     * json
        +     */
        +    /**
        +     * Sample code: GetSharePaidBursting.
        +     * 
        +     * @param azure The entry point for accessing resource management APIs in Azure.
        +     */
        +    public static void getSharePaidBursting(com.azure.resourcemanager.AzureResourceManager azure) {
        +        azure.storageAccounts()
        +            .manager()
        +            .serviceClient()
        +            .getFileShares()
        +            .getWithResponse("res9871", "sto6217", "share1634", null, null, com.azure.core.util.Context.NONE);
        +    }
        +
        +    /*
        +     * x-ms-original-file:
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/FileSharesGet_ProvisionedV2.
        +     * json
        +     */
        +    /**
        +     * Sample code: GetShareProvisionedV2.
        +     * 
        +     * @param azure The entry point for accessing resource management APIs in Azure.
        +     */
        +    public static void getShareProvisionedV2(com.azure.resourcemanager.AzureResourceManager azure) {
        +        azure.storageAccounts()
        +            .manager()
        +            .serviceClient()
        +            .getFileShares()
        +            .getWithResponse("res9871", "sto6217", "share1634", null, null, com.azure.core.util.Context.NONE);
        +    }
        +
        +    /*
        +     * x-ms-original-file:
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/FileSharesGet.json
              */
             /**
              * Sample code: GetShares.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileSharesLeaseSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileSharesLeaseSamples.java
        index fdadce1d4d1d..73863dbd898e 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileSharesLeaseSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileSharesLeaseSamples.java
        @@ -13,7 +13,7 @@
         public final class FileSharesLeaseSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/FileSharesLease_Break.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/FileSharesLease_Break.json
              */
             /**
              * Sample code: Break a lease on a share.
        @@ -33,7 +33,7 @@ public static void breakALeaseOnAShare(com.azure.resourcemanager.AzureResourceMa
         
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/FileSharesLease_Acquire.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/FileSharesLease_Acquire.json
              */
             /**
              * Sample code: Acquire a lease on a share.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileSharesListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileSharesListSamples.java
        index b72def2a0e08..4514defa2608 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileSharesListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileSharesListSamples.java
        @@ -10,7 +10,7 @@
         public final class FileSharesListSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/FileSharesList.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/FileSharesList.json
              */
             /**
              * Sample code: ListShares.
        @@ -27,7 +27,7 @@ public static void listShares(com.azure.resourcemanager.AzureResourceManager azu
         
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/DeletedFileSharesList.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/DeletedFileSharesList.json
              */
             /**
              * Sample code: ListDeletedShares.
        @@ -44,7 +44,25 @@ public static void listDeletedShares(com.azure.resourcemanager.AzureResourceMana
         
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/FileShareSnapshotsList.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/FileSharesList_ProvisionedV2.
        +     * json
        +     */
        +    /**
        +     * Sample code: ListSharesProvisionedV2.
        +     * 
        +     * @param azure The entry point for accessing resource management APIs in Azure.
        +     */
        +    public static void listSharesProvisionedV2(com.azure.resourcemanager.AzureResourceManager azure) {
        +        azure.storageAccounts()
        +            .manager()
        +            .serviceClient()
        +            .getFileShares()
        +            .list("res9290", "sto1590", null, null, null, com.azure.core.util.Context.NONE);
        +    }
        +
        +    /*
        +     * x-ms-original-file:
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/FileShareSnapshotsList.json
              */
             /**
              * Sample code: ListShareSnapshots.
        @@ -58,4 +76,22 @@ public static void listShareSnapshots(com.azure.resourcemanager.AzureResourceMan
                     .getFileShares()
                     .list("res9290", "sto1590", null, null, "snapshots", com.azure.core.util.Context.NONE);
             }
        +
        +    /*
        +     * x-ms-original-file:
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/FileSharesList_PaidBursting.
        +     * json
        +     */
        +    /**
        +     * Sample code: ListSharesPaidBursting.
        +     * 
        +     * @param azure The entry point for accessing resource management APIs in Azure.
        +     */
        +    public static void listSharesPaidBursting(com.azure.resourcemanager.AzureResourceManager azure) {
        +        azure.storageAccounts()
        +            .manager()
        +            .serviceClient()
        +            .getFileShares()
        +            .list("res9290", "sto1590", null, null, null, com.azure.core.util.Context.NONE);
        +    }
         }
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileSharesRestoreSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileSharesRestoreSamples.java
        index b2a7553ccb86..fa71196fa427 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileSharesRestoreSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileSharesRestoreSamples.java
        @@ -12,7 +12,7 @@
         public final class FileSharesRestoreSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/FileSharesRestore.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/FileSharesRestore.json
              */
             /**
              * Sample code: RestoreShares.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileSharesUpdateSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileSharesUpdateSamples.java
        index ec9d32afc047..78f340d5a1e6 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileSharesUpdateSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/FileSharesUpdateSamples.java
        @@ -6,6 +6,7 @@
         
         import com.azure.resourcemanager.storage.fluent.models.FileShareInner;
         import com.azure.resourcemanager.storage.models.AccessPolicy;
        +import com.azure.resourcemanager.storage.models.FileSharePropertiesFileSharePaidBursting;
         import com.azure.resourcemanager.storage.models.SignedIdentifier;
         import java.time.OffsetDateTime;
         import java.util.Arrays;
        @@ -18,7 +19,7 @@
         public final class FileSharesUpdateSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/FileSharesPatch.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/FileSharesPatch.json
              */
             /**
              * Sample code: UpdateShares.
        @@ -36,7 +37,7 @@ public static void updateShares(com.azure.resourcemanager.AzureResourceManager a
         
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/FileShareAclsPatch.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/FileShareAclsPatch.json
              */
             /**
              * Sample code: UpdateShareAcls.
        @@ -60,6 +61,49 @@ public static void updateShareAcls(com.azure.resourcemanager.AzureResourceManage
                         com.azure.core.util.Context.NONE);
             }
         
        +    /*
        +     * x-ms-original-file:
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/FileSharesPatch_PaidBursting.
        +     * json
        +     */
        +    /**
        +     * Sample code: UpdateSharePaidBursting.
        +     * 
        +     * @param azure The entry point for accessing resource management APIs in Azure.
        +     */
        +    public static void updateSharePaidBursting(com.azure.resourcemanager.AzureResourceManager azure) {
        +        azure.storageAccounts()
        +            .manager()
        +            .serviceClient()
        +            .getFileShares()
        +            .updateWithResponse("res3376", "sto328", "share6185",
        +                new FileShareInner().withFileSharePaidBursting(
        +                    new FileSharePropertiesFileSharePaidBursting().withPaidBurstingEnabled(true)
        +                        .withPaidBurstingMaxIops(102400)
        +                        .withPaidBurstingMaxBandwidthMibps(10340)),
        +                com.azure.core.util.Context.NONE);
        +    }
        +
        +    /*
        +     * x-ms-original-file:
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/FileSharesPatch_ProvisionedV2
        +     * .json
        +     */
        +    /**
        +     * Sample code: UpdateShareProvisionedV2.
        +     * 
        +     * @param azure The entry point for accessing resource management APIs in Azure.
        +     */
        +    public static void updateShareProvisionedV2(com.azure.resourcemanager.AzureResourceManager azure) {
        +        azure.storageAccounts()
        +            .manager()
        +            .serviceClient()
        +            .getFileShares()
        +            .updateWithResponse("res3376", "sto328", "share6185",
        +                new FileShareInner().withShareQuota(100).withProvisionedIops(5000).withProvisionedBandwidthMibps(200),
        +                com.azure.core.util.Context.NONE);
        +    }
        +
             // Use "Map.of" if available
             @SuppressWarnings("unchecked")
             private static  Map mapOf(Object... inputs) {
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/LocalUsersOperationCreateOrUpdateSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/LocalUsersOperationCreateOrUpdateSamples.java
        index 5b3bb3f08376..0c0c95e0191a 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/LocalUsersOperationCreateOrUpdateSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/LocalUsersOperationCreateOrUpdateSamples.java
        @@ -15,7 +15,7 @@
         public final class LocalUsersOperationCreateOrUpdateSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/LocalUserCreate.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/LocalUserCreate.json
              */
             /**
              * Sample code: CreateLocalUser.
        @@ -43,7 +43,7 @@ public static void createLocalUser(com.azure.resourcemanager.AzureResourceManage
         
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/LocalUserCreateNFSv3Enabled.
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/LocalUserCreateNFSv3Enabled.
              * json
              */
             /**
        @@ -63,7 +63,7 @@ public static void createNFSv3EnabledLocalUser(com.azure.resourcemanager.AzureRe
         
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/LocalUserUpdate.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/LocalUserUpdate.json
              */
             /**
              * Sample code: UpdateLocalUser.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/LocalUsersOperationDeleteSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/LocalUsersOperationDeleteSamples.java
        index 272446e1bba6..3451ef9ca6a6 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/LocalUsersOperationDeleteSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/LocalUsersOperationDeleteSamples.java
        @@ -10,7 +10,7 @@
         public final class LocalUsersOperationDeleteSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/LocalUserDelete.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/LocalUserDelete.json
              */
             /**
              * Sample code: DeleteLocalUser.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/LocalUsersOperationGetSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/LocalUsersOperationGetSamples.java
        index fde28a29277f..3f3f9d10e367 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/LocalUsersOperationGetSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/LocalUsersOperationGetSamples.java
        @@ -10,7 +10,7 @@
         public final class LocalUsersOperationGetSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/LocalUserGet.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/LocalUserGet.json
              */
             /**
              * Sample code: GetLocalUser.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/LocalUsersOperationListKeysSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/LocalUsersOperationListKeysSamples.java
        index 7b8d1a2889a8..e18b4b5b33b8 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/LocalUsersOperationListKeysSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/LocalUsersOperationListKeysSamples.java
        @@ -10,7 +10,7 @@
         public final class LocalUsersOperationListKeysSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/LocalUserListKeys.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/LocalUserListKeys.json
              */
             /**
              * Sample code: ListLocalUserKeys.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/LocalUsersOperationListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/LocalUsersOperationListSamples.java
        index 97f471ece359..96dccb23bff4 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/LocalUsersOperationListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/LocalUsersOperationListSamples.java
        @@ -12,7 +12,7 @@
         public final class LocalUsersOperationListSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/LocalUsersListNFSv3Enabled.
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/LocalUsersListNFSv3Enabled.
              * json
              */
             /**
        @@ -30,7 +30,7 @@ public static void listNFSv3EnabledLocalUsers(com.azure.resourcemanager.AzureRes
         
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/LocalUsersList.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/LocalUsersList.json
              */
             /**
              * Sample code: ListLocalUsers.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/LocalUsersOperationRegeneratePasswordSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/LocalUsersOperationRegeneratePasswordSamples.java
        index ac79b480c475..eadbc5da090d 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/LocalUsersOperationRegeneratePasswordSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/LocalUsersOperationRegeneratePasswordSamples.java
        @@ -10,7 +10,7 @@
         public final class LocalUsersOperationRegeneratePasswordSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/LocalUserRegeneratePassword.
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/LocalUserRegeneratePassword.
              * json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/ManagementPoliciesCreateOrUpdateSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/ManagementPoliciesCreateOrUpdateSamples.java
        index 71ac317b9b7c..a69d5ee9fc59 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/ManagementPoliciesCreateOrUpdateSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/ManagementPoliciesCreateOrUpdateSamples.java
        @@ -25,7 +25,7 @@
          */
         public final class ManagementPoliciesCreateOrUpdateSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountSetManagementPolicyColdTierActions.json
              */
             /**
        @@ -75,7 +75,7 @@ public final class ManagementPoliciesCreateOrUpdateSamples {
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountSetManagementPolicyWithSnapshotAndVersion.json
              */
             /**
        @@ -127,7 +127,7 @@ public final class ManagementPoliciesCreateOrUpdateSamples {
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountSetManagementPolicyForBlockAndAppendBlobs.json
              */
             /**
        @@ -165,7 +165,7 @@ public final class ManagementPoliciesCreateOrUpdateSamples {
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountSetManagementPolicyHotTierActions.json
              */
             /**
        @@ -203,7 +203,7 @@ public final class ManagementPoliciesCreateOrUpdateSamples {
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountSetManagementPolicy_LastAccessTimeBasedBlobActions.json
              */
             /**
        @@ -243,7 +243,7 @@ public static void storageAccountSetManagementPolicyLastAccessTimeBasedBlobActio
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountSetManagementPolicy.json
              */
             /**
        @@ -301,7 +301,7 @@ public static void storageAccountSetManagementPolicies(com.azure.resourcemanager
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountSetManagementPolicy_BaseBlobDaysAfterCreationActions.json
              */
             /**
        @@ -340,7 +340,7 @@ public static void storageAccountSetManagementPolicyBaseBlobDaysAfterCreationAct
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountSetManagementPolicy_LastTierChangeTimeActions.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/ManagementPoliciesDeleteSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/ManagementPoliciesDeleteSamples.java
        index 7f6e977ef272..3c448a87ad71 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/ManagementPoliciesDeleteSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/ManagementPoliciesDeleteSamples.java
        @@ -11,7 +11,7 @@
          */
         public final class ManagementPoliciesDeleteSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountDeleteManagementPolicy.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/ManagementPoliciesGetSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/ManagementPoliciesGetSamples.java
        index b93d5123efc3..5559b03610dc 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/ManagementPoliciesGetSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/ManagementPoliciesGetSamples.java
        @@ -11,7 +11,7 @@
          */
         public final class ManagementPoliciesGetSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountGetManagementPolicy.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/NetworkSecurityPerimeterConfigurationsGetSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/NetworkSecurityPerimeterConfigurationsGetSamples.java
        index 2c91ab0f522a..fb6858716bd6 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/NetworkSecurityPerimeterConfigurationsGetSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/NetworkSecurityPerimeterConfigurationsGetSamples.java
        @@ -9,7 +9,7 @@
          */
         public final class NetworkSecurityPerimeterConfigurationsGetSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * NetworkSecurityPerimeterConfigurationGet.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/NetworkSecurityPerimeterConfigurationsListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/NetworkSecurityPerimeterConfigurationsListSamples.java
        index a7bc65ba9094..53076ea2e0b5 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/NetworkSecurityPerimeterConfigurationsListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/NetworkSecurityPerimeterConfigurationsListSamples.java
        @@ -9,7 +9,7 @@
          */
         public final class NetworkSecurityPerimeterConfigurationsListSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * NetworkSecurityPerimeterConfigurationList.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/NetworkSecurityPerimeterConfigurationsReconcileSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/NetworkSecurityPerimeterConfigurationsReconcileSamples.java
        index 51bf6172bd69..9e6cfb924b75 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/NetworkSecurityPerimeterConfigurationsReconcileSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/NetworkSecurityPerimeterConfigurationsReconcileSamples.java
        @@ -9,7 +9,7 @@
          */
         public final class NetworkSecurityPerimeterConfigurationsReconcileSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * NetworkSecurityPerimeterConfigurationReconcile.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/ObjectReplicationPoliciesOperationCreateOrUpdateSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/ObjectReplicationPoliciesOperationCreateOrUpdateSamples.java
        index 684cc54c42fc..2bc66a4936d3 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/ObjectReplicationPoliciesOperationCreateOrUpdateSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/ObjectReplicationPoliciesOperationCreateOrUpdateSamples.java
        @@ -6,6 +6,7 @@
         
         import com.azure.resourcemanager.storage.fluent.models.ObjectReplicationPolicyInner;
         import com.azure.resourcemanager.storage.models.ObjectReplicationPolicyFilter;
        +import com.azure.resourcemanager.storage.models.ObjectReplicationPolicyPropertiesMetrics;
         import com.azure.resourcemanager.storage.models.ObjectReplicationPolicyRule;
         import java.util.Arrays;
         
        @@ -14,7 +15,7 @@
          */
         public final class ObjectReplicationPoliciesOperationCreateOrUpdateSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountCreateObjectReplicationPolicyOnSource.json
              */
             /**
        @@ -39,12 +40,13 @@ public final class ObjectReplicationPoliciesOperationCreateOrUpdateSamples {
                                             .withDestinationContainer("dcont139")
                                             .withFilters(new ObjectReplicationPolicyFilter()
                                                 .withPrefixMatch(Arrays.asList("blobA", "blobB"))
        -                                        .withMinCreationTime("2020-02-19T16:05:00Z")))),
        +                                        .withMinCreationTime("2020-02-19T16:05:00Z"))))
        +                    .withMetrics(new ObjectReplicationPolicyPropertiesMetrics().withEnabled(true)),
                         com.azure.core.util.Context.NONE);
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountUpdateObjectReplicationPolicyOnDestination.json
              */
             /**
        @@ -69,12 +71,13 @@ public final class ObjectReplicationPoliciesOperationCreateOrUpdateSamples {
                                         .withFilters(new ObjectReplicationPolicyFilter()
                                             .withPrefixMatch(Arrays.asList("blobA", "blobB"))),
                                     new ObjectReplicationPolicyRule().withSourceContainer("scont179")
        -                                .withDestinationContainer("dcont179"))),
        +                                .withDestinationContainer("dcont179")))
        +                    .withMetrics(new ObjectReplicationPolicyPropertiesMetrics().withEnabled(true)),
                         com.azure.core.util.Context.NONE);
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountCreateObjectReplicationPolicyOnDestination.json
              */
             /**
        @@ -93,13 +96,13 @@ public final class ObjectReplicationPoliciesOperationCreateOrUpdateSamples {
                         .withDestinationAccount("dst112")
                         .withRules(Arrays.asList(new ObjectReplicationPolicyRule().withSourceContainer("scont139")
                             .withDestinationContainer("dcont139")
        -                    .withFilters(
        -                        new ObjectReplicationPolicyFilter().withPrefixMatch(Arrays.asList("blobA", "blobB"))))),
        +                    .withFilters(new ObjectReplicationPolicyFilter().withPrefixMatch(Arrays.asList("blobA", "blobB")))))
        +                .withMetrics(new ObjectReplicationPolicyPropertiesMetrics().withEnabled(true)),
                         com.azure.core.util.Context.NONE);
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountUpdateObjectReplicationPolicyOnSource.json
              */
             /**
        @@ -125,7 +128,8 @@ public final class ObjectReplicationPoliciesOperationCreateOrUpdateSamples {
                                             .withPrefixMatch(Arrays.asList("blobA", "blobB"))),
                                     new ObjectReplicationPolicyRule().withRuleId("cfbb4bc2-8b60-429f-b05a-d1e0942b33b2")
                                         .withSourceContainer("scont179")
        -                                .withDestinationContainer("dcont179"))),
        +                                .withDestinationContainer("dcont179")))
        +                    .withMetrics(new ObjectReplicationPolicyPropertiesMetrics().withEnabled(true)),
                         com.azure.core.util.Context.NONE);
             }
         }
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/ObjectReplicationPoliciesOperationDeleteSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/ObjectReplicationPoliciesOperationDeleteSamples.java
        index 38398be917f9..b21e81755048 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/ObjectReplicationPoliciesOperationDeleteSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/ObjectReplicationPoliciesOperationDeleteSamples.java
        @@ -9,7 +9,7 @@
          */
         public final class ObjectReplicationPoliciesOperationDeleteSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountDeleteObjectReplicationPolicy.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/ObjectReplicationPoliciesOperationGetSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/ObjectReplicationPoliciesOperationGetSamples.java
        index 6c2e59afd0d2..79525dc7c8ae 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/ObjectReplicationPoliciesOperationGetSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/ObjectReplicationPoliciesOperationGetSamples.java
        @@ -9,7 +9,7 @@
          */
         public final class ObjectReplicationPoliciesOperationGetSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountGetObjectReplicationPolicy.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/ObjectReplicationPoliciesOperationListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/ObjectReplicationPoliciesOperationListSamples.java
        index 9d651036bc7f..520c691df82d 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/ObjectReplicationPoliciesOperationListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/ObjectReplicationPoliciesOperationListSamples.java
        @@ -9,7 +9,7 @@
          */
         public final class ObjectReplicationPoliciesOperationListSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountListObjectReplicationPolicies.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/OperationsListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/OperationsListSamples.java
        index caf70063ec50..4853f86de00d 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/OperationsListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/OperationsListSamples.java
        @@ -10,7 +10,7 @@
         public final class OperationsListSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/OperationsList.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/OperationsList.json
              */
             /**
              * Sample code: OperationsList.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/PrivateEndpointConnectionsDeleteSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/PrivateEndpointConnectionsDeleteSamples.java
        index b49bb48220fc..5b12ef36c7b5 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/PrivateEndpointConnectionsDeleteSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/PrivateEndpointConnectionsDeleteSamples.java
        @@ -9,7 +9,7 @@
          */
         public final class PrivateEndpointConnectionsDeleteSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountDeletePrivateEndpointConnection.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/PrivateEndpointConnectionsGetSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/PrivateEndpointConnectionsGetSamples.java
        index 81a1e2fa51ca..824dfd3673b4 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/PrivateEndpointConnectionsGetSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/PrivateEndpointConnectionsGetSamples.java
        @@ -9,7 +9,7 @@
          */
         public final class PrivateEndpointConnectionsGetSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountGetPrivateEndpointConnection.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/PrivateEndpointConnectionsListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/PrivateEndpointConnectionsListSamples.java
        index 1e667d7eee7a..d19586993660 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/PrivateEndpointConnectionsListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/PrivateEndpointConnectionsListSamples.java
        @@ -9,7 +9,7 @@
          */
         public final class PrivateEndpointConnectionsListSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountListPrivateEndpointConnections.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/PrivateEndpointConnectionsPutSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/PrivateEndpointConnectionsPutSamples.java
        index c75fa33244d2..eb914fedbea5 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/PrivateEndpointConnectionsPutSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/PrivateEndpointConnectionsPutSamples.java
        @@ -13,7 +13,7 @@
          */
         public final class PrivateEndpointConnectionsPutSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountPutPrivateEndpointConnection.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/PrivateLinkResourcesListByStorageAccountSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/PrivateLinkResourcesListByStorageAccountSamples.java
        index bc2bc197399a..80b9a01f30dc 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/PrivateLinkResourcesListByStorageAccountSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/PrivateLinkResourcesListByStorageAccountSamples.java
        @@ -9,7 +9,7 @@
          */
         public final class PrivateLinkResourcesListByStorageAccountSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountListPrivateLinkResources.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueCreateSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueCreateSamples.java
        index 5b361c5d4e34..6dbf88148ad5 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueCreateSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueCreateSamples.java
        @@ -14,7 +14,7 @@
         public final class QueueCreateSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/QueueOperationPut.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/QueueOperationPut.json
              */
             /**
              * Sample code: QueueOperationPut.
        @@ -32,7 +32,7 @@ public static void queueOperationPut(com.azure.resourcemanager.AzureResourceMana
         
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/QueueOperationPutWithMetadata
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/QueueOperationPutWithMetadata
              * .json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueDeleteSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueDeleteSamples.java
        index 1d808bb25f00..15a78962ed0e 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueDeleteSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueDeleteSamples.java
        @@ -10,7 +10,7 @@
         public final class QueueDeleteSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/QueueOperationDelete.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/QueueOperationDelete.json
              */
             /**
              * Sample code: QueueOperationDelete.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueGetSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueGetSamples.java
        index 033ef92fbb38..ff9b8d31402c 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueGetSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueGetSamples.java
        @@ -10,7 +10,7 @@
         public final class QueueGetSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/QueueOperationGet.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/QueueOperationGet.json
              */
             /**
              * Sample code: QueueOperationGet.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueListSamples.java
        index c5639dcf9fe0..0af779917aec 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueListSamples.java
        @@ -10,7 +10,7 @@
         public final class QueueListSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/QueueOperationList.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/QueueOperationList.json
              */
             /**
              * Sample code: QueueOperationList.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueServicesGetServicePropertiesSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueServicesGetServicePropertiesSamples.java
        index a6fc01074945..7c64176b1f7e 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueServicesGetServicePropertiesSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueServicesGetServicePropertiesSamples.java
        @@ -10,7 +10,7 @@
         public final class QueueServicesGetServicePropertiesSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/QueueServicesGet.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/QueueServicesGet.json
              */
             /**
              * Sample code: QueueServicesGet.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueServicesListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueServicesListSamples.java
        index 7cfdaf1ea835..ec3a0ce4b9b8 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueServicesListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueServicesListSamples.java
        @@ -10,7 +10,7 @@
         public final class QueueServicesListSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/QueueServicesList.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/QueueServicesList.json
              */
             /**
              * Sample code: QueueServicesList.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueServicesSetServicePropertiesSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueServicesSetServicePropertiesSamples.java
        index f0f387e3de42..0c8ae42a431b 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueServicesSetServicePropertiesSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueServicesSetServicePropertiesSamples.java
        @@ -16,7 +16,7 @@
         public final class QueueServicesSetServicePropertiesSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/QueueServicesPut.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/QueueServicesPut.json
              */
             /**
              * Sample code: QueueServicesPut.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueUpdateSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueUpdateSamples.java
        index d269f9acf3f3..4e0288b05e5e 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueUpdateSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/QueueUpdateSamples.java
        @@ -12,7 +12,7 @@
         public final class QueueUpdateSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/QueueOperationPatch.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/QueueOperationPatch.json
              */
             /**
              * Sample code: QueueOperationPatch.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/SkusListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/SkusListSamples.java
        index 218aa498724e..beb2d43ce872 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/SkusListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/SkusListSamples.java
        @@ -10,7 +10,7 @@
         public final class SkusListSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/SKUList.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/SKUList.json
              */
             /**
              * Sample code: SkuList.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsAbortHierarchicalNamespaceMigrationSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsAbortHierarchicalNamespaceMigrationSamples.java
        index 1468726286d9..64ed166a99c2 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsAbortHierarchicalNamespaceMigrationSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsAbortHierarchicalNamespaceMigrationSamples.java
        @@ -9,7 +9,7 @@
          */
         public final class StorageAccountsAbortHierarchicalNamespaceMigrationSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountAbortHierarchicalNamespaceMigration.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsCheckNameAvailabilitySamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsCheckNameAvailabilitySamples.java
        index ff1499cb0902..6d725e49e251 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsCheckNameAvailabilitySamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsCheckNameAvailabilitySamples.java
        @@ -11,7 +11,7 @@
          */
         public final class StorageAccountsCheckNameAvailabilitySamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountCheckNameAvailability.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsCreateSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsCreateSamples.java
        index b8816c95c472..07a3bc44a84d 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsCreateSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsCreateSamples.java
        @@ -46,7 +46,7 @@
         public final class StorageAccountsCreateSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/NfsV3AccountCreate.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/NfsV3AccountCreate.json
              */
             /**
              * Sample code: NfsV3AccountCreate.
        @@ -74,7 +74,7 @@ public static void nfsV3AccountCreate(com.azure.resourcemanager.AzureResourceMan
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountCreatePremiumBlockBlobStorage.json
              */
             /**
        @@ -105,7 +105,7 @@ public static void nfsV3AccountCreate(com.azure.resourcemanager.AzureResourceMan
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountCreateWithImmutabilityPolicy.json
              */
             /**
        @@ -134,7 +134,7 @@ public static void nfsV3AccountCreate(com.azure.resourcemanager.AzureResourceMan
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountCreateAllowedCopyScopeToPrivateLink.json
              */
             /**
        @@ -174,7 +174,7 @@ public static void nfsV3AccountCreate(com.azure.resourcemanager.AzureResourceMan
         
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/StorageAccountCreate.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/StorageAccountCreate.json
              */
             /**
              * Sample code: StorageAccountCreate.
        @@ -214,7 +214,7 @@ public static void storageAccountCreate(com.azure.resourcemanager.AzureResourceM
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountCreateEnablePublicNetworkAccess.json
              */
             /**
        @@ -255,7 +255,7 @@ public static void storageAccountCreate(com.azure.resourcemanager.AzureResourceM
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountCreateAllowedCopyScopeToAAD.json
              */
             /**
        @@ -293,7 +293,7 @@ public static void storageAccountCreateAllowedCopyScopeToAAD(com.azure.resourcem
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountCreateUserAssignedIdentityWithFederatedIdentityClientId.json
              */
             /**
        @@ -330,7 +330,7 @@ public static void storageAccountCreateUserAssignedIdentityWithFederatedIdentity
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountCreateDisallowPublicNetworkAccess.json
              */
             /**
        @@ -371,7 +371,7 @@ public static void storageAccountCreateUserAssignedIdentityWithFederatedIdentity
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountCreateDnsEndpointTypeToStandard.json
              */
             /**
        @@ -414,7 +414,7 @@ public static void storageAccountCreateUserAssignedIdentityWithFederatedIdentity
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountCreateDnsEndpointTypeToAzureDnsZone.json
              */
             /**
        @@ -457,7 +457,7 @@ public static void storageAccountCreateUserAssignedIdentityWithFederatedIdentity
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountCreateUserAssignedEncryptionIdentityWithCMK.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsCustomerInitiatedMigrationSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsCustomerInitiatedMigrationSamples.java
        index 3ef6720434b4..028e72dac08b 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsCustomerInitiatedMigrationSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsCustomerInitiatedMigrationSamples.java
        @@ -13,7 +13,7 @@
         public final class StorageAccountsCustomerInitiatedMigrationSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/StorageAccountPostMigration.
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/StorageAccountPostMigration.
              * json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsDeleteSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsDeleteSamples.java
        index 0b84ea59d230..3d7373d640c8 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsDeleteSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsDeleteSamples.java
        @@ -10,7 +10,7 @@
         public final class StorageAccountsDeleteSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/StorageAccountDelete.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/StorageAccountDelete.json
              */
             /**
              * Sample code: StorageAccountDelete.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsFailoverSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsFailoverSamples.java
        index 48b077a945ce..c2e3d7bf2e4d 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsFailoverSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsFailoverSamples.java
        @@ -12,7 +12,7 @@
         public final class StorageAccountsFailoverSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/StorageAccountFailover.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/StorageAccountFailover.json
              */
             /**
              * Sample code: StorageAccountFailover.
        @@ -29,7 +29,7 @@ public static void storageAccountFailover(com.azure.resourcemanager.AzureResourc
         
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/StorageAccountFailoverPlanned
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/StorageAccountFailoverPlanned
              * .json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsGetByResourceGroupSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsGetByResourceGroupSamples.java
        index 9fe441f4d39e..3d121b0dcc4c 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsGetByResourceGroupSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsGetByResourceGroupSamples.java
        @@ -11,7 +11,7 @@
          */
         public final class StorageAccountsGetByResourceGroupSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountGetPropertiesGeoReplicationStatscanFailoverTrue.json
              */
             /**
        @@ -31,7 +31,7 @@ public static void storageAccountGetPropertiesGeoReplicationStatscanFailoverTrue
         
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/StorageAccountGetProperties.
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/StorageAccountGetProperties.
              * json
              */
             /**
        @@ -48,7 +48,7 @@ public static void storageAccountGetProperties(com.azure.resourcemanager.AzureRe
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountGetPropertiesCMKVersionExpirationTime.json
              */
             /**
        @@ -66,7 +66,7 @@ public static void storageAccountGetProperties(com.azure.resourcemanager.AzureRe
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountGetPropertiesGeoReplicationStatscanFailoverFalse.json
              */
             /**
        @@ -85,7 +85,7 @@ public static void storageAccountGetPropertiesGeoReplicationStatscanFailoverFals
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountGetAsyncSkuConversionStatus.json
              */
             /**
        @@ -102,7 +102,7 @@ public static void storageAccountGetAsyncSkuConversionStatus(com.azure.resourcem
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountGetPropertiesCMKEnabled.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsGetCustomerInitiatedMigrationSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsGetCustomerInitiatedMigrationSamples.java
        index 2fbbaa6d4b1f..89f80c53d175 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsGetCustomerInitiatedMigrationSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsGetCustomerInitiatedMigrationSamples.java
        @@ -11,7 +11,7 @@
          */
         public final class StorageAccountsGetCustomerInitiatedMigrationSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountGetMigrationInProgress.json
              */
             /**
        @@ -29,7 +29,7 @@ public static void storageAccountGetMigrationInProgress(com.azure.resourcemanage
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountGetMigrationFailed.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsHierarchicalNamespaceMigrationSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsHierarchicalNamespaceMigrationSamples.java
        index bb19b60c1cfc..803b928afca4 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsHierarchicalNamespaceMigrationSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsHierarchicalNamespaceMigrationSamples.java
        @@ -9,7 +9,7 @@
          */
         public final class StorageAccountsHierarchicalNamespaceMigrationSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountHierarchicalNamespaceMigration.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsListAccountSasSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsListAccountSasSamples.java
        index 69815be3c682..35ca47d3c2eb 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsListAccountSasSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsListAccountSasSamples.java
        @@ -17,7 +17,7 @@
         public final class StorageAccountsListAccountSasSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/StorageAccountListAccountSAS.
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/StorageAccountListAccountSAS.
              * json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsListByResourceGroupSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsListByResourceGroupSamples.java
        index 58b4b1d03c32..601c98d4ce9a 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsListByResourceGroupSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsListByResourceGroupSamples.java
        @@ -9,7 +9,7 @@
          */
         public final class StorageAccountsListByResourceGroupSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountListByResourceGroup.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsListKeysSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsListKeysSamples.java
        index 8b327d01b9d5..ac312d5d8f0a 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsListKeysSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsListKeysSamples.java
        @@ -10,7 +10,7 @@
         public final class StorageAccountsListKeysSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/StorageAccountListKeys.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/StorageAccountListKeys.json
              */
             /**
              * Sample code: StorageAccountListKeys.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsListSamples.java
        index 8f08478e2466..9a11f29ba3c1 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsListSamples.java
        @@ -10,7 +10,7 @@
         public final class StorageAccountsListSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/StorageAccountList.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/StorageAccountList.json
              */
             /**
              * Sample code: StorageAccountList.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsListServiceSasSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsListServiceSasSamples.java
        index 912b8056ee90..384433b4cfca 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsListServiceSasSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsListServiceSasSamples.java
        @@ -15,7 +15,7 @@
         public final class StorageAccountsListServiceSasSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/StorageAccountListServiceSAS.
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/StorageAccountListServiceSAS.
              * json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsRegenerateKeySamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsRegenerateKeySamples.java
        index 0ebe1461876e..54fea9bc61c4 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsRegenerateKeySamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsRegenerateKeySamples.java
        @@ -12,7 +12,7 @@
         public final class StorageAccountsRegenerateKeySamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/StorageAccountRegenerateKey.
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/StorageAccountRegenerateKey.
              * json
              */
             /**
        @@ -31,7 +31,7 @@ public static void storageAccountRegenerateKey(com.azure.resourcemanager.AzureRe
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountRegenerateKerbKey.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsRestoreBlobRangesSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsRestoreBlobRangesSamples.java
        index ca9edea1ebe0..ca8374900196 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsRestoreBlobRangesSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsRestoreBlobRangesSamples.java
        @@ -15,7 +15,7 @@
         public final class StorageAccountsRestoreBlobRangesSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/BlobRangesRestore.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/BlobRangesRestore.json
              */
             /**
              * Sample code: BlobRangesRestore.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsRevokeUserDelegationKeysSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsRevokeUserDelegationKeysSamples.java
        index 5637232e0097..8b2dd67c2840 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsRevokeUserDelegationKeysSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsRevokeUserDelegationKeysSamples.java
        @@ -9,7 +9,7 @@
          */
         public final class StorageAccountsRevokeUserDelegationKeysSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountRevokeUserDelegationKeys.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsUpdateSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsUpdateSamples.java
        index eab299362dd3..f34735f87de2 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsUpdateSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageAccountsUpdateSamples.java
        @@ -45,7 +45,7 @@
          */
         public final class StorageAccountsUpdateSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountUpdateWithImmutabilityPolicy.json
              */
             /**
        @@ -70,7 +70,7 @@ public final class StorageAccountsUpdateSamples {
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountUpdateUserAssignedIdentityWithFederatedIdentityClientId.json
              */
             /**
        @@ -107,7 +107,7 @@ public static void storageAccountUpdateUserAssignedIdentityWithFederatedIdentity
         
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/StorageAccountEnableAD.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/StorageAccountEnableAD.json
              */
             /**
              * Sample code: StorageAccountEnableAD.
        @@ -134,7 +134,7 @@ public static void storageAccountEnableAD(com.azure.resourcemanager.AzureResourc
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountUpdateAllowedCopyScopeToAAD.json
              */
             /**
        @@ -174,7 +174,7 @@ public static void storageAccountUpdateAllowedCopyScopeToAAD(com.azure.resourcem
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountUpdateDisablePublicNetworkAccess.json
              */
             /**
        @@ -216,7 +216,7 @@ public static void storageAccountUpdateAllowedCopyScopeToAAD(com.azure.resourcem
         
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/StorageAccountEnableCMK.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/StorageAccountEnableCMK.json
              */
             /**
              * Sample code: StorageAccountEnableCMK.
        @@ -242,7 +242,7 @@ public static void storageAccountEnableCMK(com.azure.resourcemanager.AzureResour
         
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/StorageAccountUpdate.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/StorageAccountUpdate.json
              */
             /**
              * Sample code: StorageAccountUpdate.
        @@ -284,7 +284,7 @@ public static void storageAccountUpdate(com.azure.resourcemanager.AzureResourceM
             }
         
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountUpdateUserAssignedEncryptionIdentityWithCMK.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageTaskAssignmentInstancesReportListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageTaskAssignmentInstancesReportListSamples.java
        index e7271de69c51..d51f63f94a34 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageTaskAssignmentInstancesReportListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageTaskAssignmentInstancesReportListSamples.java
        @@ -10,7 +10,7 @@
         public final class StorageTaskAssignmentInstancesReportListSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/storageTaskAssignmentsList/
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/storageTaskAssignmentsList/
              * ListStorageTaskAssignmentInstancesReportSummary.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageTaskAssignmentsCreateSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageTaskAssignmentsCreateSamples.java
        index 89636b9c04b4..61dd32672b60 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageTaskAssignmentsCreateSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageTaskAssignmentsCreateSamples.java
        @@ -21,7 +21,7 @@
         public final class StorageTaskAssignmentsCreateSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/storageTaskAssignmentsCrud/
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/storageTaskAssignmentsCrud/
              * PutStorageTaskAssignment.json
              */
             /**
        @@ -51,7 +51,7 @@ public static void putStorageTaskAssignment(com.azure.resourcemanager.AzureResou
         
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/storageTaskAssignmentsCrud/
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/storageTaskAssignmentsCrud/
              * PutStorageTaskAssignmentRequiredProperties.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageTaskAssignmentsDeleteSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageTaskAssignmentsDeleteSamples.java
        index be5ce684f356..347ced556938 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageTaskAssignmentsDeleteSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageTaskAssignmentsDeleteSamples.java
        @@ -10,7 +10,7 @@
         public final class StorageTaskAssignmentsDeleteSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/storageTaskAssignmentsCrud/
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/storageTaskAssignmentsCrud/
              * DeleteStorageTaskAssignment.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageTaskAssignmentsGetSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageTaskAssignmentsGetSamples.java
        index 9826ff53e326..33310673045b 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageTaskAssignmentsGetSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageTaskAssignmentsGetSamples.java
        @@ -10,7 +10,7 @@
         public final class StorageTaskAssignmentsGetSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/storageTaskAssignmentsCrud/
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/storageTaskAssignmentsCrud/
              * GetStorageTaskAssignment.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageTaskAssignmentsInstancesReportListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageTaskAssignmentsInstancesReportListSamples.java
        index b4de18233375..92550ef553ef 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageTaskAssignmentsInstancesReportListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageTaskAssignmentsInstancesReportListSamples.java
        @@ -10,7 +10,7 @@
         public final class StorageTaskAssignmentsInstancesReportListSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/storageTaskAssignmentsList/
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/storageTaskAssignmentsList/
              * ListStorageTaskAssignmentsInstancesReportSummary.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageTaskAssignmentsListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageTaskAssignmentsListSamples.java
        index fcb588ce1d4e..282d444fe5ce 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageTaskAssignmentsListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageTaskAssignmentsListSamples.java
        @@ -10,7 +10,7 @@
         public final class StorageTaskAssignmentsListSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/storageTaskAssignmentsList/
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/storageTaskAssignmentsList/
              * ListStorageTaskAssignmentsForAccount.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageTaskAssignmentsUpdateSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageTaskAssignmentsUpdateSamples.java
        index 73dec807c46a..55eb56b4b170 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageTaskAssignmentsUpdateSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/StorageTaskAssignmentsUpdateSamples.java
        @@ -21,7 +21,7 @@
         public final class StorageTaskAssignmentsUpdateSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/storageTaskAssignmentsCrud/
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/storageTaskAssignmentsCrud/
              * PatchStorageTaskAssignment.json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableCreateSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableCreateSamples.java
        index b9b023e67979..7ae8ef8600d1 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableCreateSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableCreateSamples.java
        @@ -16,7 +16,7 @@
         public final class TableCreateSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/TableOperationPut.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/TableOperationPut.json
              */
             /**
              * Sample code: TableOperationPut.
        @@ -33,7 +33,7 @@ public static void tableOperationPut(com.azure.resourcemanager.AzureResourceMana
         
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/TableOperationPutOrPatchAcls.
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/TableOperationPutOrPatchAcls.
              * json
              */
             /**
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableDeleteSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableDeleteSamples.java
        index 0e211051b1bc..38779c978bf2 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableDeleteSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableDeleteSamples.java
        @@ -10,7 +10,7 @@
         public final class TableDeleteSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/TableOperationDelete.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/TableOperationDelete.json
              */
             /**
              * Sample code: TableOperationDelete.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableGetSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableGetSamples.java
        index 8c9b2935a274..befbc0e20ed8 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableGetSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableGetSamples.java
        @@ -10,7 +10,7 @@
         public final class TableGetSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/TableOperationGet.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/TableOperationGet.json
              */
             /**
              * Sample code: TableOperationGet.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableListSamples.java
        index 5da40cd119b7..ff3d0659ac41 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableListSamples.java
        @@ -10,7 +10,7 @@
         public final class TableListSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/TableOperationList.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/TableOperationList.json
              */
             /**
              * Sample code: TableOperationList.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableServicesGetServicePropertiesSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableServicesGetServicePropertiesSamples.java
        index c820a68c6652..77857dcf9eef 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableServicesGetServicePropertiesSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableServicesGetServicePropertiesSamples.java
        @@ -10,7 +10,7 @@
         public final class TableServicesGetServicePropertiesSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/TableServicesGet.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/TableServicesGet.json
              */
             /**
              * Sample code: TableServicesGet.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableServicesListSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableServicesListSamples.java
        index 270e17a196b2..8be15dc89b21 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableServicesListSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableServicesListSamples.java
        @@ -10,7 +10,7 @@
         public final class TableServicesListSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/TableServicesList.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/TableServicesList.json
              */
             /**
              * Sample code: TableServicesList.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableServicesSetServicePropertiesSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableServicesSetServicePropertiesSamples.java
        index 7076720bda7b..dfaa31e8c867 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableServicesSetServicePropertiesSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableServicesSetServicePropertiesSamples.java
        @@ -16,7 +16,7 @@
         public final class TableServicesSetServicePropertiesSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/TableServicesPut.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/TableServicesPut.json
              */
             /**
              * Sample code: TableServicesPut.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableUpdateSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableUpdateSamples.java
        index 1255d5ec3682..96fc9b4268dd 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableUpdateSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableUpdateSamples.java
        @@ -16,7 +16,7 @@
         public final class TableUpdateSamples {
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/TableOperationPutOrPatchAcls.
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/TableOperationPutOrPatchAcls.
              * json
              */
             /**
        @@ -48,7 +48,7 @@ public static void tableOperationPutOrPatchAcls(com.azure.resourcemanager.AzureR
         
             /*
              * x-ms-original-file:
        -     * specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/TableOperationPatch.json
        +     * specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/TableOperationPatch.json
              */
             /**
              * Sample code: TableOperationPatch.
        diff --git a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/UsagesListByLocationSamples.java b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/UsagesListByLocationSamples.java
        index d4b44ee11f40..72f64eac0fa0 100644
        --- a/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/UsagesListByLocationSamples.java
        +++ b/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/UsagesListByLocationSamples.java
        @@ -9,7 +9,7 @@
          */
         public final class UsagesListByLocationSamples {
             /*
        -     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2023-05-01/examples/
        +     * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2024-01-01/examples/
              * StorageAccountListLocationUsage.json
              */
             /**
        diff --git a/sdk/resourcemanager/docs/AUTH.md b/sdk/resourcemanager/docs/AUTH.md
        index 028d33382817..9adf3366dbf7 100644
        --- a/sdk/resourcemanager/docs/AUTH.md
        +++ b/sdk/resourcemanager/docs/AUTH.md
        @@ -53,8 +53,8 @@ The value of `AZURE_AUTHORITY_HOST` can be set via [`AzureAuthorityHosts`](https
         Sample code to create a `AzureProfile`:
         
         ```java readme-sample-buildAzureProfile
        -// AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);
        -AzureProfile profile = new AzureProfile("", "", AzureEnvironment.AZURE);
        +// AzureProfile profile = new AzureProfile(AzureCloud.AZURE_PUBLIC_CLOUD);
        +AzureProfile profile = new AzureProfile("", "", AzureCloud.AZURE_PUBLIC_CLOUD);
         ```
         
         The sample code assumes global Azure. Please change `AzureEnvironment.AZURE` variable if otherwise.
        @@ -62,7 +62,7 @@ The sample code assumes global Azure. Please change `AzureEnvironment.AZURE` var
         Sample code for Azure Germany, with `EnvironmentCredential`:
         
         ```java readme-sample-buildEnvironmentCredential
        -AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE_GERMANY);
        +AzureProfile profile = new AzureProfile(AzureCloud.AZURE_CHINA_CLOUD);
         EnvironmentCredential credential = new EnvironmentCredentialBuilder()
             .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint())
             .build();
        diff --git a/sdk/resourcemanager/docs/SINGLE_SERVICE_PACKAGES.md b/sdk/resourcemanager/docs/SINGLE_SERVICE_PACKAGES.md
        index b8f0522e118d..2dc53e22a3ff 100644
        --- a/sdk/resourcemanager/docs/SINGLE_SERVICE_PACKAGES.md
        +++ b/sdk/resourcemanager/docs/SINGLE_SERVICE_PACKAGES.md
        @@ -20,6 +20,7 @@ service
          advisor 
         
         * [package-2020-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/advisor/resource-manager#tag-package-2020-01)
        +    * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-advisor/1.0.0)
             * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-advisor/1.0.0-beta.3)
             * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-advisor/1.0.0-beta.2)
             * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-advisor/1.0.0-beta.1)
        @@ -59,6 +60,7 @@ service
          apimanagement 
         
         * [package-2022-08](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/apimanagement/resource-manager#tag-package-2022-08)
        +    * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-apimanagement/1.0.0)
             * [1.0.0-beta.5](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-apimanagement/1.0.0-beta.5)
             * [1.0.0-beta.4](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-apimanagement/1.0.0-beta.4)
         * [package-2021-08](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/apimanagement/resource-manager#tag-package-2021-08)
        @@ -127,6 +129,8 @@ service
         
        applicationinsights +* [package-2024-08-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/applicationinsights/resource-manager#tag-package-2024-08-01) + * [1.2.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-applicationinsights/1.2.0-beta.1) * [package-2022-06-15-java](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/applicationinsights/resource-manager/readme.java.md#tag-package-2022-06-15-java) * [1.1.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-applicationinsights/1.1.0) * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-applicationinsights/1.0.0) @@ -166,6 +170,7 @@ service automanage * [package-2022-05](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/automanage/resource-manager#tag-package-2022-05) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-automanage/1.0.0) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-automanage/1.0.0-beta.2) * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-automanage/1.0.0-beta.1)
        @@ -175,6 +180,7 @@ service automation * [package-2022-02-22](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/automation/resource-manager#tag-package-2022-02-22) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-automation/1.0.0) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-automation/1.0.0-beta.3) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-automation/1.0.0-beta.2) * [package-2019-06](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/automation/resource-manager#tag-package-2019-06) @@ -206,6 +212,7 @@ service azurearcdata * [package-2021-08-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/azurearcdata/resource-manager#tag-package-2021-08-01) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-azurearcdata/1.0.0) * [1.0.0-beta.4](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-azurearcdata/1.0.0-beta.4) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-azurearcdata/1.0.0-beta.3) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-azurearcdata/1.0.0-beta.2) @@ -217,6 +224,7 @@ service azurestack * [package-2022-06](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/azurestack/resource-manager#tag-package-2022-06) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-azurestack/1.0.0) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-azurestack/1.0.0-beta.3) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-azurestack/1.0.0-beta.2) * [package-preview-2020-06](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/azurestack/resource-manager#tag-package-preview-2020-06) @@ -243,12 +251,13 @@ service
        baremetalinfrastructure -* [package-preview-2023-08](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/baremetalinfrastructure/resource-manager#tag-package-preview-2023-08) - * [1.0.0-beta.4](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-baremetalinfrastructure/1.0.0-beta.4) - * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-baremetalinfrastructure/1.0.0-beta.3) * [package-2021-08-09](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/baremetalinfrastructure/resource-manager#tag-package-2021-08-09) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-baremetalinfrastructure/1.0.0) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-baremetalinfrastructure/1.0.0-beta.2) * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-baremetalinfrastructure/1.0.0-beta.1) +* [package-preview-2023-08](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/baremetalinfrastructure/resource-manager#tag-package-preview-2023-08) + * [1.0.0-beta.4](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-baremetalinfrastructure/1.0.0-beta.4) + * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-baremetalinfrastructure/1.0.0-beta.3)

        @@ -273,6 +282,14 @@ service * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-batch/1.0.0-beta.1) +
        +
        + batchai + +* package-2018-05 + * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-batchai/1.0.0-beta.1) +
        +
        billing @@ -298,14 +315,15 @@ service
        botservice +* [package-2021-03-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/botservice/resource-manager#tag-package-2021-03-01) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-botservice/1.0.0) + * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-botservice/1.0.0-beta.1) * [package-preview-2021-05](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/botservice/resource-manager#tag-package-preview-2021-05) * [1.0.0-beta.6](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-botservice/1.0.0-beta.6) * [1.0.0-beta.5](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-botservice/1.0.0-beta.5) * [1.0.0-beta.4](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-botservice/1.0.0-beta.4) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-botservice/1.0.0-beta.3) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-botservice/1.0.0-beta.2) -* [package-2021-03-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/botservice/resource-manager#tag-package-2021-03-01) - * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-botservice/1.0.0-beta.1)

        @@ -323,12 +341,12 @@ service
        chaos -* [package-2024-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/chaos/resource-manager#tag-package-2024-01) +* package-2024-01 * [1.2.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-chaos/1.2.0) * [1.1.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-chaos/1.1.0) -* [package-2023-11](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/chaos/resource-manager#tag-package-2023-11) +* package-2023-11 * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-chaos/1.0.0) -* [package-2023-04-15-preview](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/chaos/resource-manager#tag-package-2023-04-15-preview) +* package-2023-04-15-preview * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-chaos/1.0.0-beta.1)
        @@ -395,14 +413,15 @@ service
        confidentialledger +* [package-2022-05-13](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/confidentialledger/resource-manager#tag-package-2022-05-13) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-confidentialledger/1.0.0) + * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-confidentialledger/1.0.0-beta.1) * [package-preview-2023-06](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/confidentialledger/resource-manager#tag-package-preview-2023-06) * [1.0.0-beta.5](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-confidentialledger/1.0.0-beta.5) * [1.0.0-beta.4](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-confidentialledger/1.0.0-beta.4) * [package-preview-2023-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/confidentialledger/resource-manager#tag-package-preview-2023-01) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-confidentialledger/1.0.0-beta.3) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-confidentialledger/1.0.0-beta.2) -* [package-2022-05-13](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/confidentialledger/resource-manager#tag-package-2022-05-13) - * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-confidentialledger/1.0.0-beta.1)

        @@ -438,6 +457,7 @@ service consumption * [package-2021-10](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/consumption/resource-manager#tag-package-2021-10) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-consumption/1.0.0) * [1.0.0-beta.4](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-consumption/1.0.0-beta.4) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-consumption/1.0.0-beta.3) * [package-2019-10](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/consumption/resource-manager#tag-package-2019-10) @@ -482,6 +502,7 @@ service costmanagement * [package-2022-10](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/cost-management/resource-manager#tag-package-2022-10) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-costmanagement/1.0.0) * [1.0.0-beta.7](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-costmanagement/1.0.0-beta.7) * [1.0.0-beta.6](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-costmanagement/1.0.0-beta.6) * [1.0.0-beta.5](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-costmanagement/1.0.0-beta.5) @@ -521,6 +542,7 @@ service databox * [package-2022-12](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/databox/resource-manager#tag-package-2022-12) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-databox/1.0.0) * [1.0.0-beta.4](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-databox/1.0.0-beta.4) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-databox/1.0.0-beta.3) * [package-2021-03](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/databox/resource-manager#tag-package-2021-03) @@ -533,6 +555,7 @@ service databoxedge * [package-2019-08](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/databoxedge/resource-manager#tag-package-2019-08) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-databoxedge/1.0.0) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-databoxedge/1.0.0-beta.3) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-databoxedge/1.0.0-beta.2) * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-databoxedge/1.0.0-beta.1) @@ -543,6 +566,7 @@ service databricks * [package-2023-05-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/databricks/resource-manager#tag-package-2023-05-01) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-databricks/1.0.0) * [1.0.0-beta.5](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-databricks/1.0.0-beta.5) * [1.0.0-beta.4](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-databricks/1.0.0-beta.4) * [package-2021-04-01-preview](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/databricks/resource-manager#tag-package-2021-04-01-preview) @@ -610,6 +634,7 @@ service datalakeanalytics * [package-2016-11](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/datalake-analytics/resource-manager#tag-package-2016-11) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-datalakeanalytics/1.0.0) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-datalakeanalytics/1.0.0-beta.3) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-datalakeanalytics/1.0.0-beta.2) * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-datalakeanalytics/1.0.0-beta.1) @@ -620,6 +645,7 @@ service datalakestore * [package-2016-11](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/datalake-store/resource-manager#tag-package-2016-11) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-datalakestore/1.0.0) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-datalakestore/1.0.0-beta.3) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-datalakestore/1.0.0-beta.2) * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-datalakestore/1.0.0-beta.1) @@ -630,6 +656,7 @@ service datamigration * [package-2018-04-19](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/datamigration/resource-manager#tag-package-2018-04-19) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-datamigration/1.0.0) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-datamigration/1.0.0-beta.3) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-datamigration/1.0.0-beta.2) * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-datamigration/1.0.0-beta.1) @@ -704,6 +731,7 @@ service devcenter * [package-2024-02](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/devcenter/resource-manager#tag-package-2024-02) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-devcenter/1.0.0) * [1.0.0-beta.8](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-devcenter/1.0.0-beta.8) * [1.0.0-beta.7](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-devcenter/1.0.0-beta.7) * [package-preview-2023-10](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/devcenter/resource-manager#tag-package-preview-2023-10) @@ -736,6 +764,7 @@ service deviceprovisioningservices * [package-2022-02](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/deviceprovisioningservices/resource-manager#tag-package-2022-02) + * [1.1.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-deviceprovisioningservices/1.1.0) * [1.1.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-deviceprovisioningservices/1.1.0-beta.2) * [package-2021-10](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/deviceprovisioningservices/resource-manager#tag-package-2021-10) * [1.1.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-deviceprovisioningservices/1.1.0-beta.1) @@ -809,11 +838,12 @@ service
        dnsresolver -* [package-preview-2023-07](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/dnsresolver/resource-manager#tag-package-preview-2023-07) - * [1.0.0-beta.4](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-dnsresolver/1.0.0-beta.4) * [package-2022-07](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/dnsresolver/resource-manager#tag-package-2022-07) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-dnsresolver/1.0.0) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-dnsresolver/1.0.0-beta.3) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-dnsresolver/1.0.0-beta.2) +* [package-preview-2023-07](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/dnsresolver/resource-manager#tag-package-preview-2023-07) + * [1.0.0-beta.4](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-dnsresolver/1.0.0-beta.4) * [package-2020-04-preview](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/dnsresolver/resource-manager#tag-package-2020-04-preview) * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-dnsresolver/1.0.0-beta.1)
        @@ -823,6 +853,7 @@ service dynatrace * [package-2023-04-27](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/dynatrace/resource-manager#tag-package-2023-04-27) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-dynatrace/1.0.0) * [1.0.0-beta.4](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-dynatrace/1.0.0-beta.4) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-dynatrace/1.0.0-beta.3) * [package-2021-09-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/dynatrace/resource-manager#tag-package-2021-09-01) @@ -836,6 +867,7 @@ service edgeorder * [package-2021-12](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/edgeorder/resource-manager#tag-package-2021-12) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-edgeorder/1.0.0) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-edgeorder/1.0.0-beta.2) * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-edgeorder/1.0.0-beta.1)
        @@ -927,11 +959,12 @@ service
        extendedlocation +* [package-2021-08-15](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/extendedlocation/resource-manager#tag-package-2021-08-15) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-extendedlocation/1.0.0) + * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-extendedlocation/1.0.0-beta.1) * [package-2021-08-31-preview](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/extendedlocation/resource-manager#tag-package-2021-08-31-preview) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-extendedlocation/1.0.0-beta.3) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-extendedlocation/1.0.0-beta.2) -* [package-2021-08-15](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/extendedlocation/resource-manager#tag-package-2021-08-15) - * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-extendedlocation/1.0.0-beta.1)

        @@ -983,12 +1016,13 @@ service
        hardwaresecuritymodules +* [package-2021-11](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/hardwaresecuritymodules/resource-manager#tag-package-2021-11) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-hardwaresecuritymodules/1.0.0) + * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-hardwaresecuritymodules/1.0.0-beta.1) * [package-preview-2024-06](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/hardwaresecuritymodules/resource-manager#tag-package-preview-2024-06) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-hardwaresecuritymodules/1.0.0-beta.3) * [package-2023-12-preview](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/hardwaresecuritymodules/resource-manager#tag-package-2023-12-preview) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-hardwaresecuritymodules/1.0.0-beta.2) -* [package-2021-11](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/hardwaresecuritymodules/resource-manager#tag-package-2021-11) - * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-hardwaresecuritymodules/1.0.0-beta.1)

        @@ -1026,6 +1060,7 @@ service healthbot * [package-2020-12-08](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/healthbot/resource-manager#tag-package-2020-12-08) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-healthbot/1.0.0) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-healthbot/1.0.0-beta.3) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-healthbot/1.0.0-beta.2) * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-healthbot/1.0.0-beta.1) @@ -1097,6 +1132,7 @@ service hybridkubernetes * [package-2021-10-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/hybridkubernetes/resource-manager#tag-package-2021-10-01) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-hybridkubernetes/1.0.0) * [1.0.0-beta.4](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-hybridkubernetes/1.0.0-beta.4) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-hybridkubernetes/1.0.0-beta.3) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-hybridkubernetes/1.0.0-beta.2) @@ -1213,6 +1249,8 @@ service
        kusto +* [package-2024-04](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/azure-kusto/resource-manager#tag-package-2024-04) + * [1.2.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-kusto/1.2.0) * [package-2023-08](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/azure-kusto/resource-manager#tag-package-2023-08) * [1.1.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-kusto/1.1.0) * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-kusto/1.0.0) @@ -1237,6 +1275,7 @@ service labservices * [package-2022-08](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/labservices/resource-manager#tag-package-2022-08) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-labservices/1.0.0) * [1.0.0-beta.4](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-labservices/1.0.0-beta.4) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-labservices/1.0.0-beta.3) * [package-preview-2021-11](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/labservices/resource-manager#tag-package-preview-2021-11) @@ -1283,21 +1322,12 @@ service logic * [package-2019-05](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/logic/resource-manager#tag-package-2019-05) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-logic/1.0.0) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-logic/1.0.0-beta.3) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-logic/1.0.0-beta.2) * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-logic/1.0.0-beta.1)
        -
        -
        - logz - -* [package-2020-10-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/logz/resource-manager#tag-package-2020-10-01) - * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-logz/1.0.0-beta.3) - * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-logz/1.0.0-beta.2) - * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-logz/1.0.0-beta.1) -
        -
        machinelearning @@ -1312,6 +1342,14 @@ service * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-machinelearning/1.0.0-beta.1)
        +
        +
        + machinelearningservices + +* [package-2021-04-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/machinelearningservices/resource-manager#tag-package-2021-04-01) + * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-machinelearningservices/1.0.0-beta.1) +
        +
        maintenance @@ -1333,6 +1371,7 @@ service managedapplications * [package-managedapplications-2021-07](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/solutions/resource-manager#tag-package-managedapplications-2021-07) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-managedapplications/1.0.0) * [1.0.0-beta.4](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-managedapplications/1.0.0-beta.4) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-managedapplications/1.0.0-beta.3) * [package-managedapplications-2018-06](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/solutions/resource-manager#tag-package-managedapplications-2018-06) @@ -1377,6 +1416,7 @@ service mariadb * [package-2020-01-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/mariadb/resource-manager#tag-package-2020-01-01) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-mariadb/1.0.0) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-mariadb/1.0.0-beta.3) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-mariadb/1.0.0-beta.2) * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-mariadb/1.0.0-beta.1) @@ -1387,6 +1427,7 @@ service marketplaceordering * [package-2021-01-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/marketplaceordering/resource-manager#tag-package-2021-01-01) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-marketplaceordering/1.0.0) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-marketplaceordering/1.0.0-beta.3) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-marketplaceordering/1.0.0-beta.2) * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-marketplaceordering/1.0.0-beta.1) @@ -1420,6 +1461,14 @@ service * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-mediaservices/1.0.0-beta.1)
        +
        +
        + migration-assessment + +* [package-2023-03](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/migrate/resource-manager/Microsoft.Migrate/AssessmentProjects#tag-package-2023-03) + * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-migration-assessment/1.0.0-beta.1) +
        +
        migrationdiscoverysap @@ -1434,6 +1483,7 @@ service mixedreality * [package-2021-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/mixedreality/resource-manager#tag-package-2021-01) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-mixedreality/1.0.0) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-mixedreality/1.0.0-beta.3) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-mixedreality/1.0.0-beta.2) * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-mixedreality/1.0.0-beta.1) @@ -1444,6 +1494,7 @@ service mobilenetwork * [package-2024-04](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/mobilenetwork/resource-manager#tag-package-2024-04) + * [1.3.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-mobilenetwork/1.3.0) * [1.2.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-mobilenetwork/1.2.0) * [package-2024-02](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/mobilenetwork/resource-manager#tag-package-2024-02) * [1.1.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-mobilenetwork/1.1.0) @@ -1494,6 +1545,8 @@ service
        netapp +* [package-2024-09-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/netapp/resource-manager#tag-package-2024-09-01) + * [1.6.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-netapp/1.6.0) * [package-preview-2024-07-01-preview](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/netapp/resource-manager#tag-package-preview-2024-07-01-preview) * [1.6.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-netapp/1.6.0-beta.1) * [package-2024-07](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/netapp/resource-manager#tag-package-2024-07) @@ -1537,19 +1590,12 @@ service * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-netapp/1.0.0-beta.1)
        -
        -
        - networkanalytics - -* [package-2023-11-15](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/networkanalytics/resource-manager#tag-package-2023-11-15) - * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-networkanalytics/1.0.0) - * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-networkanalytics/1.0.0-beta.1) -
        -
        networkcloud +* [package-2024-07-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/networkcloud/resource-manager#tag-package-2024-07-01) + * [1.1.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-networkcloud/1.1.0) * [package-2024-06-01-preview](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/networkcloud/resource-manager#tag-package-2024-06-01-preview) * [1.1.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-networkcloud/1.1.0-beta.1) * [package-2023-07-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/networkcloud/resource-manager#tag-package-2023-07-01) @@ -1589,6 +1635,8 @@ service
        nginx +* [package-2024-11-01-preview](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/nginx/resource-manager#tag-package-2024-11-01-preview) + * [1.1.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-nginx/1.1.0-beta.3) * [package-2024-01-01-preview](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/nginx/resource-manager#tag-package-2024-01-01-preview) * [1.1.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-nginx/1.1.0-beta.2) * [1.1.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-nginx/1.1.0-beta.1) @@ -1603,13 +1651,14 @@ service
        notificationhubs -* [package-preview-2023-10](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/notificationhubs/resource-manager#tag-package-preview-2023-10) - * [1.0.0-beta.5](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-notificationhubs/1.0.0-beta.5) - * [1.0.0-beta.4](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-notificationhubs/1.0.0-beta.4) * [package-2017-04](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/notificationhubs/resource-manager#tag-package-2017-04) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-notificationhubs/1.0.0) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-notificationhubs/1.0.0-beta.3) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-notificationhubs/1.0.0-beta.2) * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-notificationhubs/1.0.0-beta.1) +* [package-preview-2023-10](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/notificationhubs/resource-manager#tag-package-preview-2023-10) + * [1.0.0-beta.5](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-notificationhubs/1.0.0-beta.5) + * [1.0.0-beta.4](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-notificationhubs/1.0.0-beta.4)

        @@ -1647,6 +1696,7 @@ service orbital * [package-2022-11-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/orbital/resource-manager#tag-package-2022-11-01) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-orbital/1.0.0) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-orbital/1.0.0-beta.3) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-orbital/1.0.0-beta.2) * [package-2022-03-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/orbital/resource-manager#tag-package-2022-03-01) @@ -1658,6 +1708,7 @@ service paloaltonetworks-ngfw * [package-2023-09-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/paloaltonetworks/resource-manager#tag-package-2023-09-01) + * [1.2.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-paloaltonetworks-ngfw/1.2.0) * [1.1.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-paloaltonetworks-ngfw/1.1.0) * [package-2022-08-29](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/paloaltonetworks/resource-manager#tag-package-2022-08-29) * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-paloaltonetworks-ngfw/1.0.0) @@ -1670,6 +1721,7 @@ service peering * [package-2021-01-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/peering/resource-manager#tag-package-2021-01-01) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-peering/1.0.0) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-peering/1.0.0-beta.3) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-peering/1.0.0-beta.2) * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-peering/1.0.0-beta.1) @@ -1690,6 +1742,7 @@ service policyinsights * [package-2022-09](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/policyinsights/resource-manager#tag-package-2022-09) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-policyinsights/1.0.0) * [1.0.0-beta.4](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-policyinsights/1.0.0-beta.4) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-policyinsights/1.0.0-beta.3) * [package-2021-10](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/policyinsights/resource-manager#tag-package-2021-10) @@ -1703,6 +1756,7 @@ service postgresql * [package-2020-01-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/postgresql/resource-manager#tag-package-2020-01-01) + * [1.1.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-postgresql/1.1.0) * [1.0.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-postgresql/1.0.2) * [1.0.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-postgresql/1.0.1) * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-postgresql/1.0.0) @@ -1713,6 +1767,8 @@ service
        postgresqlflexibleserver +* [package-flexibleserver-2024-08-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/postgresql/resource-manager#tag-package-flexibleserver-2024-08-01) + * [1.1.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-postgresqlflexibleserver/1.1.0) * [package-flexibleserver-2023-12-01-preview](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/postgresql/resource-manager#tag-package-flexibleserver-2023-12-01-preview) * [1.1.0-beta.4](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-postgresqlflexibleserver/1.1.0-beta.4) * [1.1.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-postgresqlflexibleserver/1.1.0-beta.3) @@ -1737,6 +1793,7 @@ service powerbidedicated * [package-2021-01-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/powerbidedicated/resource-manager#tag-package-2021-01-01) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-powerbidedicated/1.0.0) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-powerbidedicated/1.0.0-beta.3) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-powerbidedicated/1.0.0-beta.2) * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-powerbidedicated/1.0.0-beta.1) @@ -1757,6 +1814,7 @@ service purview * [package-2021-07-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/purview/resource-manager#tag-package-2021-07-01) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-purview/1.0.0) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-purview/1.0.0-beta.3) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-purview/1.0.0-beta.2) * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-purview/1.0.0-beta.1) @@ -1790,6 +1848,10 @@ service
        quota +* [package-2025-03-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/quota/resource-manager#tag-package-2025-03-01) + * [1.1.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-quota/1.1.0) +* [package-2024-12-18-preview](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/quota/resource-manager#tag-package-2024-12-18-preview) + * [1.1.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-quota/1.1.0-beta.3) * [package-2023-06-01-preview](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/quota/resource-manager#tag-package-2023-06-01-preview) * [1.1.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-quota/1.1.0-beta.2) * [1.1.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-quota/1.1.0-beta.1) @@ -1806,6 +1868,7 @@ service recoveryservices * [package-2024-04](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/recoveryservices/resource-manager#tag-package-2024-04) + * [1.4.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-recoveryservices/1.4.0) * [1.3.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-recoveryservices/1.3.0) * [package-2023-04](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/recoveryservices/resource-manager#tag-package-2023-04) * [1.2.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-recoveryservices/1.2.0) @@ -1867,6 +1930,7 @@ service recoveryservicessiterecovery * [package-2023-08](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/recoveryservicessiterecovery/resource-manager#tag-package-2023-08) + * [1.2.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-recoveryservicessiterecovery/1.2.0) * [1.1.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-recoveryservicessiterecovery/1.1.0) * [package-2023-06](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/recoveryservicessiterecovery/resource-manager#tag-package-2023-06) * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-recoveryservicessiterecovery/1.0.0) @@ -1920,6 +1984,7 @@ service reservations * [package-2022-11](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/reservations/resource-manager#tag-package-2022-11) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-reservations/1.0.0) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-reservations/1.0.0-beta.3) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-reservations/1.0.0-beta.2) * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-reservations/1.0.0-beta.1) @@ -1994,6 +2059,8 @@ service security * [package-composite-v3](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/security/resource-manager#tag-package-composite-v3) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-security/1.0.0) + * [1.0.0-beta.8](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-security/1.0.0-beta.8) * [1.0.0-beta.7](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-security/1.0.0-beta.7) * [1.0.0-beta.6](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-security/1.0.0-beta.6) * [1.0.0-beta.5](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-security/1.0.0-beta.5) @@ -2015,6 +2082,8 @@ service
        securityinsights +* [package-2022-11](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/securityinsights/resource-manager#tag-package-2022-11) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-securityinsights/1.0.0) * [package-preview-2022-09](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/securityinsights/resource-manager#tag-package-preview-2022-09) * [1.0.0-beta.5](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-securityinsights/1.0.0-beta.5) * [1.0.0-beta.4](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-securityinsights/1.0.0-beta.4) @@ -2047,6 +2116,7 @@ service servicefabric * [package-2021-06](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/servicefabric/resource-manager#tag-package-2021-06) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-servicefabric/1.0.0) * [1.0.0-beta.5](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-servicefabric/1.0.0-beta.5) * [1.0.0-beta.4](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-servicefabric/1.0.0-beta.4) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-servicefabric/1.0.0-beta.3) @@ -2059,24 +2129,26 @@ service
        servicefabricmanagedclusters +* [package-2024-04](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/servicefabricmanagedclusters/resource-manager#tag-package-2024-04) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-servicefabricmanagedclusters/1.0.0) + * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-servicefabricmanagedclusters/1.0.0-beta.1) * [package-2024-09-preview](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/servicefabricmanagedclusters/resource-manager#tag-package-2024-09-preview) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-servicefabricmanagedclusters/1.0.0-beta.3) * [package-2024-06-preview](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/servicefabricmanagedclusters/resource-manager#tag-package-2024-06-preview) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-servicefabricmanagedclusters/1.0.0-beta.2) -* [package-2024-04](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/servicefabricmanagedclusters/resource-manager#tag-package-2024-04) - * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-servicefabricmanagedclusters/1.0.0-beta.1)

        servicelinker -* [package-2024-07-01-preview](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/servicelinker/resource-manager#tag-package-2024-07-01-preview) - * [1.0.0-beta.4](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-servicelinker/1.0.0-beta.4) * [package-2022-05-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/servicelinker/resource-manager#tag-package-2022-05-01) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-servicelinker/1.0.0) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-servicelinker/1.0.0-beta.3) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-servicelinker/1.0.0-beta.2) * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-servicelinker/1.0.0-beta.1) +* [package-2024-07-01-preview](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/servicelinker/resource-manager#tag-package-2024-07-01-preview) + * [1.0.0-beta.4](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-servicelinker/1.0.0-beta.4)

        @@ -2097,13 +2169,14 @@ service
        signalr +* [package-2023-02-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/signalr/resource-manager#tag-package-2023-02-01) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-signalr/1.0.0) + * [1.0.0-beta.6](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-signalr/1.0.0-beta.6) * [package-2023-08-01-preview](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/signalr/resource-manager#tag-package-2023-08-01-preview) * [1.0.0-beta.9](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-signalr/1.0.0-beta.9) * [1.0.0-beta.8](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-signalr/1.0.0-beta.8) * [package-2023-06-01-preview](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/signalr/resource-manager#tag-package-2023-06-01-preview) * [1.0.0-beta.7](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-signalr/1.0.0-beta.7) -* [package-2023-02-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/signalr/resource-manager#tag-package-2023-02-01) - * [1.0.0-beta.6](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-signalr/1.0.0-beta.6) * [package-2022-08-01-preview](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/signalr/resource-manager#tag-package-2022-08-01-preview) * [1.0.0-beta.5](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-signalr/1.0.0-beta.5) * [package-2022-02-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/signalr/resource-manager#tag-package-2022-02-01) @@ -2173,6 +2246,7 @@ service storagecache * [package-2024-03](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/storagecache/resource-manager#tag-package-2024-03) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-storagecache/1.0.0) * [1.0.0-beta.12](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-storagecache/1.0.0-beta.12) * [1.0.0-beta.11](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-storagecache/1.0.0-beta.11) * [package-preview-2023-11](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/storagecache/resource-manager#tag-package-preview-2023-11) @@ -2212,6 +2286,7 @@ service storagemover * [package-2024-07](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/storagemover/resource-manager#tag-package-2024-07) + * [1.3.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-storagemover/1.3.0) * [1.2.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-storagemover/1.2.0) * [package-2023-10](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/storagemover/resource-manager#tag-package-2023-10) * [1.1.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-storagemover/1.1.0) @@ -2228,6 +2303,7 @@ service storagepool * [package-2021-08-01](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/storagepool/resource-manager#tag-package-2021-08-01) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-storagepool/1.0.0) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-storagepool/1.0.0-beta.3) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-storagepool/1.0.0-beta.2) * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-storagepool/1.0.0-beta.1) @@ -2237,11 +2313,12 @@ service
        streamanalytics +* [package-pure-2020-03](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/streamanalytics/resource-manager#tag-package-pure-2020-03) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-streamanalytics/1.0.0) + * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-streamanalytics/1.0.0-beta.2) * [package-2021-10-preview](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/streamanalytics/resource-manager#tag-package-2021-10-preview) * [1.0.0-beta.4](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-streamanalytics/1.0.0-beta.4) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-streamanalytics/1.0.0-beta.3) -* [package-pure-2020-03](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/streamanalytics/resource-manager#tag-package-pure-2020-03) - * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-streamanalytics/1.0.0-beta.2) * [package-2020-03-preview](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/streamanalytics/resource-manager#tag-package-2020-03-preview) * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-streamanalytics/1.0.0-beta.1)
        @@ -2251,6 +2328,7 @@ service subscription * [package-2020-09](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/subscription/resource-manager#tag-package-2020-09) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-subscription/1.0.0) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-subscription/1.0.0-beta.3) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-subscription/1.0.0-beta.2) * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-subscription/1.0.0-beta.1) @@ -2276,6 +2354,9 @@ service
        synapse +* [package-2021-03](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/synapse/resource-manager#tag-package-2021-03) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-synapse/1.0.0) + * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-synapse/1.0.0-beta.1) * [package-composite-v2](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/synapse/resource-manager#tag-package-composite-v2) * [1.0.0-beta.8](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-synapse/1.0.0-beta.8) * [1.0.0-beta.7](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-synapse/1.0.0-beta.7) @@ -2285,8 +2366,6 @@ service * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-synapse/1.0.0-beta.3) * [package-composite-v1](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/synapse/resource-manager#tag-package-composite-v1) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-synapse/1.0.0-beta.2) -* [package-2021-03](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/synapse/resource-manager#tag-package-2021-03) - * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-synapse/1.0.0-beta.1)

        @@ -2294,6 +2373,7 @@ service timeseriesinsights * [package-2020-05-15](https://github.com/Azure/azure-rest-api-specs/tree/main/specification/timeseriesinsights/resource-manager#tag-package-2020-05-15) + * [1.0.0](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-timeseriesinsights/1.0.0) * [1.0.0-beta.3](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-timeseriesinsights/1.0.0-beta.3) * [1.0.0-beta.2](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-timeseriesinsights/1.0.0-beta.2) * [1.0.0-beta.1](https://repo1.maven.org/maven2/com/azure/resourcemanager/azure-resourcemanager-timeseriesinsights/1.0.0-beta.1) diff --git a/sdk/resourcemanager/docs/THREAD_POOL_AND_CONNECTION_POOL.md b/sdk/resourcemanager/docs/THREAD_POOL_AND_CONNECTION_POOL.md index 0abebf4b6551..db57892ca743 100644 --- a/sdk/resourcemanager/docs/THREAD_POOL_AND_CONNECTION_POOL.md +++ b/sdk/resourcemanager/docs/THREAD_POOL_AND_CONNECTION_POOL.md @@ -116,5 +116,5 @@ Reference: * [DEFAULT_POOL_SIZE for Schedulers.parallel()](https://github.com/reactor/reactor-core/blob/3.4.x/reactor-core/src/main/java/reactor/core/scheduler/Schedulers.java#L72-L81) ## Other JVM thread configurations you might be interested: -* [Compiler threads for JIT compiler](https://docs.oracle.com/en/java/javase/17/docs/specs/man/java.html#advanced-jit-compiler-options-for-java) -* [GC threads](https://docs.oracle.com/en/java/javase/17/docs/specs/man/java.html#advanced-garbage-collection-options-for-java) +* [Compiler threads for JIT compiler](https://docs.oracle.com/en/java/javase/21/docs/specs/man/java.html#advanced-jit-compiler-options-for-java) +* [GC threads](https://docs.oracle.com/en/java/javase/21/docs/specs/man/java.html#advanced-garbage-collection-options-for-java) diff --git a/sdk/resourcemanagerhybrid/README.md b/sdk/resourcemanagerhybrid/README.md index bdf2313a9b78..f58d5c15b267 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.14.2 + 1.15.3 ``` [//]: # ({x-version-update-end}) @@ -97,7 +97,7 @@ Azure Management Libraries require a `TokenCredential` implementation for authen com.azure azure-core-http-netty - 1.10.2 + 1.15.10 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/resourcemanagerhybrid/azure-resourcemanager-appservice/pom.xml b/sdk/resourcemanagerhybrid/azure-resourcemanager-appservice/pom.xml index cf3c009ca815..1330348f00a6 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.15.7 + 1.15.11 test diff --git a/sdk/resourcemanagerhybrid/azure-resourcemanager-authorization/pom.xml b/sdk/resourcemanagerhybrid/azure-resourcemanager-authorization/pom.xml index 0f60fd1d95ef..6cd48180e21d 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.15.7 + 1.15.11 test diff --git a/sdk/resourcemanagerhybrid/azure-resourcemanager-compute/pom.xml b/sdk/resourcemanagerhybrid/azure-resourcemanager-compute/pom.xml index f14010d8a543..22e00c291d3e 100644 --- a/sdk/resourcemanagerhybrid/azure-resourcemanager-compute/pom.xml +++ b/sdk/resourcemanagerhybrid/azure-resourcemanager-compute/pom.xml @@ -83,7 +83,7 @@ com.azure.resourcemanager azure-resourcemanager-msi - 2.46.0 + 2.48.0 com.azure.resourcemanager @@ -111,7 +111,7 @@ com.azure azure-core-http-netty - 1.15.7 + 1.15.11 test @@ -123,7 +123,7 @@ com.azure azure-storage-blob - 12.29.0 + 12.29.1 test diff --git a/sdk/resourcemanagerhybrid/azure-resourcemanager-containerregistry/pom.xml b/sdk/resourcemanagerhybrid/azure-resourcemanager-containerregistry/pom.xml index b9c7eaa817ca..6a35372a723f 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.15.7 + 1.15.11 test diff --git a/sdk/resourcemanagerhybrid/azure-resourcemanager-containerservice/pom.xml b/sdk/resourcemanagerhybrid/azure-resourcemanager-containerservice/pom.xml index 3ca1171a0a84..9c05edd7e71b 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.15.7 + 1.15.11 test diff --git a/sdk/resourcemanagerhybrid/azure-resourcemanager-dns/pom.xml b/sdk/resourcemanagerhybrid/azure-resourcemanager-dns/pom.xml index 81d8051704bd..1f13fe636417 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.15.7 + 1.15.11 test diff --git a/sdk/resourcemanagerhybrid/azure-resourcemanager-eventhubs/pom.xml b/sdk/resourcemanagerhybrid/azure-resourcemanager-eventhubs/pom.xml index a1bdcc85a4b4..956652f70baf 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.15.7 + 1.15.11 test diff --git a/sdk/resourcemanagerhybrid/azure-resourcemanager-keyvault/pom.xml b/sdk/resourcemanagerhybrid/azure-resourcemanager-keyvault/pom.xml index 407d3feb53c9..baf3d99fdba0 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.9.1 + 4.9.3 com.azure @@ -79,7 +79,7 @@ com.azure azure-security-keyvault-secrets - 4.9.1 + 4.9.3 com.azure @@ -102,7 +102,7 @@ com.azure azure-core-http-netty - 1.15.7 + 1.15.11 test diff --git a/sdk/resourcemanagerhybrid/azure-resourcemanager-monitor/pom.xml b/sdk/resourcemanagerhybrid/azure-resourcemanager-monitor/pom.xml index df333be96d3d..63998d3dce49 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.15.7 + 1.15.11 test diff --git a/sdk/resourcemanagerhybrid/azure-resourcemanager-network/pom.xml b/sdk/resourcemanagerhybrid/azure-resourcemanager-network/pom.xml index b6cb3a2db0fe..fd2b598550f5 100644 --- a/sdk/resourcemanagerhybrid/azure-resourcemanager-network/pom.xml +++ b/sdk/resourcemanagerhybrid/azure-resourcemanager-network/pom.xml @@ -81,13 +81,13 @@ com.azure azure-core-http-netty - 1.15.7 + 1.15.11 test com.azure azure-security-keyvault-certificates - 4.7.1 + 4.7.3 test @@ -99,7 +99,7 @@ com.azure.resourcemanager azure-resourcemanager-msi - 2.46.0 + 2.48.0 test diff --git a/sdk/resourcemanagerhybrid/azure-resourcemanager-resources/pom.xml b/sdk/resourcemanagerhybrid/azure-resourcemanager-resources/pom.xml index 9633087dec08..ad57a42c816a 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.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 org.slf4j @@ -87,7 +87,7 @@ com.azure azure-core-http-netty - 1.15.7 + 1.15.11 test diff --git a/sdk/resourcemanagerhybrid/azure-resourcemanager-storage/pom.xml b/sdk/resourcemanagerhybrid/azure-resourcemanager-storage/pom.xml index f9886d74db19..4f67003f8235 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.15.7 + 1.15.11 test diff --git a/sdk/resourcemanagerhybrid/azure-resourcemanager-test/pom.xml b/sdk/resourcemanagerhybrid/azure-resourcemanager-test/pom.xml index d3e8864b39fe..5d6ae0bdb61a 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.27.0-beta.4 + 1.27.0-beta.8 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-identity - 1.15.0 + 1.15.4 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-serializer-json-jackson - 1.5.4 + 1.5.8 diff --git a/sdk/resourcemanagerhybrid/azure-resourcemanager/pom.xml b/sdk/resourcemanagerhybrid/azure-resourcemanager/pom.xml index 5604771e49e5..112745101e37 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.15.7 + 1.15.11 test com.azure azure-core-http-okhttp - 1.12.6 + 1.12.10 test com.azure azure-core-http-vertx - 1.0.0-beta.24 + 1.0.3 test @@ -196,7 +196,7 @@ com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.19 + 1.0.3 test diff --git a/sdk/resourcemover/azure-resourcemanager-resourcemover/README.md b/sdk/resourcemover/azure-resourcemanager-resourcemover/README.md index e1c15ff9cbcc..7fd6231fa3cc 100644 --- a/sdk/resourcemover/azure-resourcemanager-resourcemover/README.md +++ b/sdk/resourcemover/azure-resourcemanager-resourcemover/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-resourcemover - 1.2.0 + 1.3.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -110,4 +110,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fresourcemover%2Fazure-resourcemanager-resourcemover%2FREADME.png) + diff --git a/sdk/resourcemover/azure-resourcemanager-resourcemover/pom.xml b/sdk/resourcemover/azure-resourcemanager-resourcemover/pom.xml index fcc77e8a2ef5..c6fa8b00709a 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.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test @@ -91,7 +91,7 @@ com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/schemaregistry/azure-data-schemaregistry-apacheavro/README.md b/sdk/schemaregistry/azure-data-schemaregistry-apacheavro/README.md index 0e60bb10488a..f3eda2aab530 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry-apacheavro/README.md +++ b/sdk/schemaregistry/azure-data-schemaregistry-apacheavro/README.md @@ -23,7 +23,7 @@ and deserialization. com.azure azure-data-schemaregistry-apacheavro - 1.1.21 + 1.2.0-beta.3 ``` [//]: # ({x-version-update-end}) @@ -51,7 +51,7 @@ with the Azure SDK, please include the `azure-identity` package: com.azure azure-identity - 1.14.2 + 1.15.3 ``` @@ -164,4 +164,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ [coc_contact]: mailto:opencode@microsoft.com -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fschemaregistry%2Fazure-data-schemaregistry-apacheavro%2FREADME.png) + diff --git a/sdk/schemaregistry/azure-data-schemaregistry-apacheavro/pom.xml b/sdk/schemaregistry/azure-data-schemaregistry-apacheavro/pom.xml index 9bc69eeafa39..97f4d80a8e6c 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry-apacheavro/pom.xml +++ b/sdk/schemaregistry/azure-data-schemaregistry-apacheavro/pom.xml @@ -54,7 +54,7 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure @@ -71,19 +71,19 @@ com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-messaging-eventhubs - 5.19.2 + 5.20.1 test diff --git a/sdk/schemaregistry/azure-data-schemaregistry-apacheavro/src/samples/README.md b/sdk/schemaregistry/azure-data-schemaregistry-apacheavro/src/samples/README.md index 95afb95f20b7..8c5a70458fc6 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry-apacheavro/src/samples/README.md +++ b/sdk/schemaregistry/azure-data-schemaregistry-apacheavro/src/samples/README.md @@ -45,4 +45,4 @@ This project welcomes contributions and suggestions. See [Contributing][sdk_read [sample_avro_deserialization]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/schemaregistry/azure-data-schemaregistry-apacheavro/src/samples/java/com/azure/data/schemaregistry/apacheavro/SchemaRegistryApacheAvroDeserializationSample.java [sample_event_hubs]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/schemaregistry/azure-data-schemaregistry-apacheavro/src/samples/java/com/azure/data/schemaregistry/apacheavro/SchemaRegistryWithEventHubs.java -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%schemaregistry%2Fazure-data-schemaregistry-apacheavro%2Fsrc%2Fsamples%2README.png) + diff --git a/sdk/schemaregistry/azure-data-schemaregistry-jsonschema/README.md b/sdk/schemaregistry/azure-data-schemaregistry-jsonschema/README.md index f26eeeda2706..b3492bd3e5d7 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry-jsonschema/README.md +++ b/sdk/schemaregistry/azure-data-schemaregistry-jsonschema/README.md @@ -22,7 +22,7 @@ identifiers and JSON encoded data. com.azure azure-data-schemaregistry-jsonschema - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -50,7 +50,7 @@ with the Azure SDK, please include the `azure-identity` package: com.azure azure-identity - 1.14.2 + 1.15.3 ``` @@ -163,4 +163,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ [coc_contact]: mailto:opencode@microsoft.com -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fschemaregistry%2Fazure-data-schemaregistry-jsonschema%2FREADME.png) + diff --git a/sdk/schemaregistry/azure-data-schemaregistry-jsonschema/pom.xml b/sdk/schemaregistry/azure-data-schemaregistry-jsonschema/pom.xml index 92fa94f6094e..7b53687654d5 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry-jsonschema/pom.xml +++ b/sdk/schemaregistry/azure-data-schemaregistry-jsonschema/pom.xml @@ -53,7 +53,7 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure @@ -65,19 +65,19 @@ com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-messaging-eventhubs - 5.19.2 + 5.20.1 test diff --git a/sdk/schemaregistry/azure-data-schemaregistry-jsonschema/src/samples/README.md b/sdk/schemaregistry/azure-data-schemaregistry-jsonschema/src/samples/README.md index 95afb95f20b7..8c5a70458fc6 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry-jsonschema/src/samples/README.md +++ b/sdk/schemaregistry/azure-data-schemaregistry-jsonschema/src/samples/README.md @@ -45,4 +45,4 @@ This project welcomes contributions and suggestions. See [Contributing][sdk_read [sample_avro_deserialization]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/schemaregistry/azure-data-schemaregistry-apacheavro/src/samples/java/com/azure/data/schemaregistry/apacheavro/SchemaRegistryApacheAvroDeserializationSample.java [sample_event_hubs]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/schemaregistry/azure-data-schemaregistry-apacheavro/src/samples/java/com/azure/data/schemaregistry/apacheavro/SchemaRegistryWithEventHubs.java -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%schemaregistry%2Fazure-data-schemaregistry-apacheavro%2Fsrc%2Fsamples%2README.png) + diff --git a/sdk/schemaregistry/azure-data-schemaregistry/CHANGELOG.md b/sdk/schemaregistry/azure-data-schemaregistry/CHANGELOG.md index 6bf9b34474b2..dee77863d7d4 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/CHANGELOG.md +++ b/sdk/schemaregistry/azure-data-schemaregistry/CHANGELOG.md @@ -10,6 +10,16 @@ ### Other Changes +## 1.5.3 (2025-02-25) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`. +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. + + ## 1.5.2 (2024-12-04) ### Other Changes @@ -19,6 +29,7 @@ - Upgraded `azure-core` from `1.53.0` to version `1.54.1`. - Upgraded `azure-core-http-netty` from `1.15.5` to version `1.15.7`. + ## 1.5.1 (2024-10-25) ### Other Changes diff --git a/sdk/schemaregistry/azure-data-schemaregistry/README.md b/sdk/schemaregistry/azure-data-schemaregistry/README.md index b2bd102b825f..e68aa59a1567 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/README.md +++ b/sdk/schemaregistry/azure-data-schemaregistry/README.md @@ -54,7 +54,7 @@ add the direct dependency to your project as follows. com.azure azure-data-schemaregistry - 1.5.0 + 1.6.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -75,7 +75,7 @@ To use the [DefaultAzureCredential][DefaultAzureCredential] provider shown below com.azure azure-identity - 1.14.2 + 1.15.3 ``` @@ -218,4 +218,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ [coc_contact]: mailto:opencode@microsoft.com -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fschemaregistry%2Fazure-data-schemaregistry%2FREADME.png) + diff --git a/sdk/schemaregistry/azure-data-schemaregistry/pom.xml b/sdk/schemaregistry/azure-data-schemaregistry/pom.xml index 0187342f3550..457b35d11cc6 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/pom.xml +++ b/sdk/schemaregistry/azure-data-schemaregistry/pom.xml @@ -56,12 +56,12 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 @@ -74,13 +74,13 @@ com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/samples/README.md b/sdk/schemaregistry/azure-data-schemaregistry/src/samples/README.md index 023e90c3f17f..563467b23a69 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/samples/README.md +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/samples/README.md @@ -51,4 +51,4 @@ This project welcomes contributions and suggestions. See [Contributing][sdk_read [sample_get_schema_id]: https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/schemaregistry/azure-data-schemaregistry/src/samples/java/com/azure/data/schemaregistry/GetSchemaIdSample.java [sample_get_schema_id_async]: https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/schemaregistry/azure-data-schemaregistry/src/samples/java/com/azure/data/schemaregistry/GetSchemaIdSampleAsync.java -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%schemaregistry%2Fazure-data-schemaregistry%2Fsrc%2Fsamples%2README.png) + diff --git a/sdk/scvmm/azure-resourcemanager-scvmm/README.md b/sdk/scvmm/azure-resourcemanager-scvmm/README.md index d95947c8ea27..c3c6fa5b4d8d 100644 --- a/sdk/scvmm/azure-resourcemanager-scvmm/README.md +++ b/sdk/scvmm/azure-resourcemanager-scvmm/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-scvmm - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fscvmm%2Fazure-resourcemanager-scvmm%2FREADME.png) + diff --git a/sdk/scvmm/azure-resourcemanager-scvmm/pom.xml b/sdk/scvmm/azure-resourcemanager-scvmm/pom.xml index 696d168bdde4..00dd21297aac 100644 --- a/sdk/scvmm/azure-resourcemanager-scvmm/pom.xml +++ b/sdk/scvmm/azure-resourcemanager-scvmm/pom.xml @@ -50,28 +50,28 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/search/CONTRIBUTING.md b/sdk/search/CONTRIBUTING.md index 1594e01a495a..0d18bd779365 100644 --- a/sdk/search/CONTRIBUTING.md +++ b/sdk/search/CONTRIBUTING.md @@ -65,7 +65,7 @@ you should consider persisting these variables. Our samples are structured as test source code in `/src/samples/` so we can easily verify they're up-to-date and compile correctly. -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fsearch%2FCONTRIBUTING.png) + [core_tests]: https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/core/azure-core-test \ No newline at end of file diff --git a/sdk/search/README.md b/sdk/search/README.md index bbab7b752adb..f1b9318407ce 100644 --- a/sdk/search/README.md +++ b/sdk/search/README.md @@ -33,4 +33,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct](https://ope For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fsearch%2FREADME.png) + diff --git a/sdk/search/azure-search-documents/CHANGELOG.md b/sdk/search/azure-search-documents/CHANGELOG.md index 7a440aee28ee..0507e4845ea7 100644 --- a/sdk/search/azure-search-documents/CHANGELOG.md +++ b/sdk/search/azure-search-documents/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 11.8.0-beta.5 (Unreleased) +## 11.8.0-beta.6 (Unreleased) ### Features Added @@ -10,6 +10,30 @@ ### Other Changes +## 11.7.5 (2025-02-25) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`. +- Upgraded `azure-core-serializer-json-jackson` from `1.5.4` to version `1.5.7`. +- Upgraded `azure-json` from `1.3.0` to version `1.4.0`. +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. + +## 11.8.0-beta.5 (2025-02-18) + +### Bugs Fixed + +- Fixed bug that made 2024-11-01-preview service version inaccessible. + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.54.1` to version `1.55.1`. +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.9`. +- Upgraded `azure-core-serializer-json-jackson` from `1.5.4` to version `1.5.6`. ## 11.7.4 (2024-12-04) diff --git a/sdk/search/azure-search-documents/README.md b/sdk/search/azure-search-documents/README.md index ef2f748cf6d7..3a6e6875df06 100644 --- a/sdk/search/azure-search-documents/README.md +++ b/sdk/search/azure-search-documents/README.md @@ -75,7 +75,7 @@ add the direct dependency to your project as follows. com.azure azure-search-documents - 11.8.0-beta.4 + 11.8.0-beta.6 ``` [//]: # ({x-version-update-end}) @@ -595,4 +595,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [status_codes]: https://learn.microsoft.com/rest/api/searchservice/http-status-codes [search-get-started-portal]: https://learn.microsoft.com/azure/search/search-get-started-portal -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fsearch%2Fazure-search-documents%2FREADME.png) + diff --git a/sdk/search/azure-search-documents/TROUBLESHOOTING.md b/sdk/search/azure-search-documents/TROUBLESHOOTING.md index 0161a8a81060..db0e7bc31dd4 100644 --- a/sdk/search/azure-search-documents/TROUBLESHOOTING.md +++ b/sdk/search/azure-search-documents/TROUBLESHOOTING.md @@ -63,4 +63,4 @@ service side. One tip would be to start with a 'broad' query (one that returns a by giving a large value for or entirely removing, some [query parameters](https://docs.microsoft.com/rest/api/searchservice/search-documents#query-parameters)) and then progressively refining the query till it expresses the desired intent. -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fsearch%2Fazure-search-documents%2FTROUBLESHOOTING.png) + diff --git a/sdk/search/azure-search-documents/assets.json b/sdk/search/azure-search-documents/assets.json index 18c5f2dfc1b2..c17b86dda157 100644 --- a/sdk/search/azure-search-documents/assets.json +++ b/sdk/search/azure-search-documents/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "java", "TagPrefix": "java/search/azure-search-documents", - "Tag": "java/search/azure-search-documents_4ebd7ccc1a" + "Tag": "java/search/azure-search-documents_0bac7cbf4b" } diff --git a/sdk/search/azure-search-documents/pom.xml b/sdk/search/azure-search-documents/pom.xml index 8a08f0d331ff..8874904d2618 100644 --- a/sdk/search/azure-search-documents/pom.xml +++ b/sdk/search/azure-search-documents/pom.xml @@ -16,7 +16,7 @@ com.azure azure-search-documents - 11.8.0-beta.5 + 11.8.0-beta.6 jar @@ -62,22 +62,22 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-serializer-json-jackson - 1.5.4 + 1.5.8 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-ai-openai - 1.0.0-beta.13 + 1.0.0-beta.14 test diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchServiceVersion.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchServiceVersion.java index 0dfd7da10397..040dd4510280 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchServiceVersion.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchServiceVersion.java @@ -25,9 +25,9 @@ public enum SearchServiceVersion implements ServiceVersion { V2024_07_01("2024-07-01"), /** - * {@code 2024-09-01-preview} service version. + * {@code 2024-11-01-preview} service version. */ - V2024_09_01_PREVIEW("2024-09-01-preview"); + V2024_11_01_PREVIEW("2024-11-01-preview"); private final String version; @@ -49,6 +49,6 @@ public String getVersion() { * @return The latest version supported by this client library. */ public static SearchServiceVersion getLatest() { - return V2024_09_01_PREVIEW; + return V2024_11_01_PREVIEW; } } diff --git a/sdk/search/azure-search-documents/src/samples/README.md b/sdk/search/azure-search-documents/src/samples/README.md index b3e09f25caa2..6cdcb06c0a0d 100644 --- a/sdk/search/azure-search-documents/src/samples/README.md +++ b/sdk/search/azure-search-documents/src/samples/README.md @@ -61,7 +61,7 @@ add the direct dependency to your project as follows. com.azure azure-search-documents - 11.8.0-beta.4 + 11.8.0-beta.6 ``` [//]: # ({x-version-update-end}) @@ -117,4 +117,4 @@ This project welcomes contributions and suggestions. Find [more contributing][SD [SDK_README_DEPENDENCY]: ../../README.md#adding-the-package-to-your-product [azsearch_docs]: https://learn.microsoft.com/azure/search -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java/sdk/search/azure-search/samples/README.png) + diff --git a/sdk/search/azure-search-perf/pom.xml b/sdk/search/azure-search-perf/pom.xml index 7b10bf3f4afe..10108600a30a 100644 --- a/sdk/search/azure-search-perf/pom.xml +++ b/sdk/search/azure-search-perf/pom.xml @@ -29,18 +29,18 @@ com.azure azure-search-documents - 11.8.0-beta.5 + 11.8.0-beta.6 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 diff --git a/sdk/security/azure-resourcemanager-security/README.md b/sdk/security/azure-resourcemanager-security/README.md index a768255a18d0..071b03b0d824 100644 --- a/sdk/security/azure-resourcemanager-security/README.md +++ b/sdk/security/azure-resourcemanager-security/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-security - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fsecurity%2Fazure-resourcemanager-security%2FREADME.png) + diff --git a/sdk/security/azure-resourcemanager-security/pom.xml b/sdk/security/azure-resourcemanager-security/pom.xml index 4e0980e1ca85..83b5f8774751 100644 --- a/sdk/security/azure-resourcemanager-security/pom.xml +++ b/sdk/security/azure-resourcemanager-security/pom.xml @@ -51,23 +51,23 @@ Code generated by Microsoft (R) AutoRest Code Generator. com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/securitydevops/azure-resourcemanager-securitydevops/README.md b/sdk/securitydevops/azure-resourcemanager-securitydevops/README.md index 6199783e05c9..a2d5a50bffee 100644 --- a/sdk/securitydevops/azure-resourcemanager-securitydevops/README.md +++ b/sdk/securitydevops/azure-resourcemanager-securitydevops/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-securitydevops - 1.0.0-beta.1 + 1.0.0-beta.2 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/securitydevops/azure-resourcemanager-securitydevops/pom.xml b/sdk/securitydevops/azure-resourcemanager-securitydevops/pom.xml index ed21901a1dbf..c50e9aea82ce 100644 --- a/sdk/securitydevops/azure-resourcemanager-securitydevops/pom.xml +++ b/sdk/securitydevops/azure-resourcemanager-securitydevops/pom.xml @@ -45,23 +45,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/securityinsights/azure-resourcemanager-securityinsights/README.md b/sdk/securityinsights/azure-resourcemanager-securityinsights/README.md index a3020281b594..60f3f304b6e2 100644 --- a/sdk/securityinsights/azure-resourcemanager-securityinsights/README.md +++ b/sdk/securityinsights/azure-resourcemanager-securityinsights/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-securityinsights - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fsecurityinsights%2Fazure-resourcemanager-securityinsights%2FREADME.png) + diff --git a/sdk/securityinsights/azure-resourcemanager-securityinsights/pom.xml b/sdk/securityinsights/azure-resourcemanager-securityinsights/pom.xml index e084b64575fb..706bf58ce128 100644 --- a/sdk/securityinsights/azure-resourcemanager-securityinsights/pom.xml +++ b/sdk/securityinsights/azure-resourcemanager-securityinsights/pom.xml @@ -51,23 +51,23 @@ Code generated by Microsoft (R) AutoRest Code Generator. com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/selfhelp/azure-resourcemanager-selfhelp/README.md b/sdk/selfhelp/azure-resourcemanager-selfhelp/README.md index 909c1d28efec..cb09ecd1e243 100644 --- a/sdk/selfhelp/azure-resourcemanager-selfhelp/README.md +++ b/sdk/selfhelp/azure-resourcemanager-selfhelp/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-selfhelp - 1.1.0-beta.5 + 1.1.0-beta.6 ``` [//]: # ({x-version-update-end}) @@ -104,4 +104,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fselfhelp%2Fazure-resourcemanager-selfhelp%2FREADME.png) + diff --git a/sdk/selfhelp/azure-resourcemanager-selfhelp/pom.xml b/sdk/selfhelp/azure-resourcemanager-selfhelp/pom.xml index c54ab4cb7196..ba6caa2a12a0 100644 --- a/sdk/selfhelp/azure-resourcemanager-selfhelp/pom.xml +++ b/sdk/selfhelp/azure-resourcemanager-selfhelp/pom.xml @@ -51,28 +51,28 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/serialization/azure-json-gson/CHANGELOG.md b/sdk/serialization/azure-json-gson/CHANGELOG.md deleted file mode 100644 index e3204dd2b1e6..000000000000 --- a/sdk/serialization/azure-json-gson/CHANGELOG.md +++ /dev/null @@ -1,30 +0,0 @@ -# Release History - -## 1.0.0-beta.4 (Unreleased) - -### Features Added - -### Breaking Changes - -### Bugs Fixed - -### Other Changes - -## 1.0.0-beta.3 (2023-03-02) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-json` to `1.0.0-beta.3`. - -## 1.0.0-beta.2 (2023-02-01) - -### Bugs Fixed - -- Fixed a bug where `GsonJsonReader.bufferObject` would throw an exception if the starting `JsonToken` was a field name - not followed by a start object. Buffering now supports field starting points. - -## 1.0.0-beta.1 (2022-09-22) - -- Initial release. Please see the README for more information. diff --git a/sdk/serialization/azure-json-gson/README.md b/sdk/serialization/azure-json-gson/README.md index 772ed29ad6ca..a4c1725fb4d0 100644 --- a/sdk/serialization/azure-json-gson/README.md +++ b/sdk/serialization/azure-json-gson/README.md @@ -22,7 +22,7 @@ add the direct dependency to your project as follows. com.azure azure-json-gson - 1.0.0-beta.3 + 1.0.0-beta.4 ``` [//]: # ({x-version-update-end}) @@ -57,4 +57,4 @@ For details on contributing to this repository, see the [contributing guide](htt [jdk_link]: https://learn.microsoft.com/java/azure/jdk/?view=azure-java-stable -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fserialization%2Fazure-json-gson%2FREADME.png) + diff --git a/sdk/serialization/azure-json-gson/checkstyle-suppressions.xml b/sdk/serialization/azure-json-gson/checkstyle-suppressions.xml deleted file mode 100644 index 3ebd76e5ee40..000000000000 --- a/sdk/serialization/azure-json-gson/checkstyle-suppressions.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - diff --git a/sdk/serialization/azure-json-gson/pom.xml b/sdk/serialization/azure-json-gson/pom.xml deleted file mode 100644 index 8ea84c53c707..000000000000 --- a/sdk/serialization/azure-json-gson/pom.xml +++ /dev/null @@ -1,150 +0,0 @@ - - - 4.0.0 - - com.azure - azure-client-sdk-parent - 1.7.0 - ../../parents/azure-client-sdk-parent - - - com.azure - azure-json-gson - jar - 1.0.0-beta.4 - - Microsoft Azure Java GSON JSON Library - This package contains a GSON-based JSON implementation. - https://github.com/Azure/azure-sdk-for-java - - - - The MIT License (MIT) - http://opensource.org/licenses/MIT - repo - - - - - - azure-java-build-docs - ${site.url}/site/${project.artifactId} - - - - - https://github.com/Azure/azure-sdk-for-java - scm:git:https://github.com/Azure/azure-sdk-for-java.git - scm:git:https://github.com/Azure/azure-sdk-for-java.git - - - - UTF-8 - - - - --add-opens com.azure.json.gson/com.azure.json.gson=ALL-UNNAMED - - - ${basedir}/src/main/java - - checkstyle-suppressions.xml - - - - - microsoft - Microsoft - - - - - - com.azure - azure-json - 1.4.0-beta.1 - - - com.google.code.gson - gson - 2.11.0 - - - - com.azure - azure-json - 1.4.0-beta.1 - test-jar - test - - - - org.junit.jupiter - junit-jupiter-api - 5.11.2 - test - - - org.junit.jupiter - junit-jupiter-engine - 5.11.2 - test - - - org.junit.jupiter - junit-jupiter-params - 5.11.2 - test - - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - 3.5.0 - - - - - com.google.code.gson:gson:[2.11.0] - - - - - - - - - com.github.spotbugs - spotbugs-maven-plugin - 4.8.3.1 - - - - com.h3xstream.findsecbugs - findsecbugs-plugin - 1.9.0 - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.13.0 - - - -Xlint:deprecation - - - - - - diff --git a/sdk/serialization/azure-json-gson/src/main/java/com/azure/json/gson/GsonJsonProvider.java b/sdk/serialization/azure-json-gson/src/main/java/com/azure/json/gson/GsonJsonProvider.java deleted file mode 100644 index 034f9a7c67ed..000000000000 --- a/sdk/serialization/azure-json-gson/src/main/java/com/azure/json/gson/GsonJsonProvider.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.json.gson; - -import com.azure.json.JsonOptions; -import com.azure.json.JsonProvider; -import com.azure.json.JsonReader; -import com.azure.json.JsonWriter; - -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; -import java.io.Writer; - -/** - * Implementation of {@link JsonProvider} that creates instances using GSON. - */ -public class GsonJsonProvider implements JsonProvider { - /** - * Creates an instance of {@link GsonJsonProvider}. - */ - public GsonJsonProvider() { - } - - @Override - public JsonReader createReader(byte[] json, JsonOptions options) { - return GsonJsonReader.fromBytes(json, options); - } - - @Override - public JsonReader createReader(String json, JsonOptions options) { - return GsonJsonReader.fromString(json, options); - } - - @Override - public JsonReader createReader(InputStream json, JsonOptions options) { - return GsonJsonReader.fromStream(json, options); - } - - @Override - public JsonReader createReader(Reader json, JsonOptions options) { - return GsonJsonReader.fromReader(json, options); - } - - @Override - public JsonWriter createWriter(OutputStream json, JsonOptions options) { - return GsonJsonWriter.toStream(json, options); - } - - @Override - public JsonWriter createWriter(Writer json, JsonOptions options) { - return GsonJsonWriter.toWriter(json, options); - } -} diff --git a/sdk/serialization/azure-json-gson/src/main/java/com/azure/json/gson/GsonJsonReader.java b/sdk/serialization/azure-json-gson/src/main/java/com/azure/json/gson/GsonJsonReader.java deleted file mode 100644 index d012e365e817..000000000000 --- a/sdk/serialization/azure-json-gson/src/main/java/com/azure/json/gson/GsonJsonReader.java +++ /dev/null @@ -1,316 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.json.gson; - -import com.azure.json.JsonOptions; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringReader; -import java.nio.charset.StandardCharsets; -import java.util.Base64; -import java.util.Objects; - -/** - * GSON-based implementation of {@link JsonReader} - */ -public final class GsonJsonReader extends JsonReader { - private final com.google.gson.stream.JsonReader reader; - - private final byte[] jsonBytes; - private final String jsonString; - private final boolean resetSupported; - private final boolean nonNumericNumbersSupported; - - private JsonToken currentToken; - private boolean consumed = false; - private boolean complete = false; - - /** - * Constructs an instance of {@link JsonReader} from a {@code byte[]}. - * - * @param json JSON {@code byte[]}. - * @param options {@link JsonOptions} to configure the creation of the {@link JsonReader}. - * @return An instance of {@link JsonReader}. - * @throws NullPointerException If {@code json} is null. - */ - static JsonReader fromBytes(byte[] json, JsonOptions options) { - Objects.requireNonNull(json, "'json' cannot be null."); - return new GsonJsonReader(new InputStreamReader(new ByteArrayInputStream(json), StandardCharsets.UTF_8), true, - json, null, options); - } - - /** - * Constructs an instance of {@link JsonReader} from a String. - * - * @param json JSON String. - * @param options {@link JsonOptions} to configure the creation of the {@link JsonReader}. - * @return An instance of {@link JsonReader}. - * @throws NullPointerException If {@code json} is null. - */ - static JsonReader fromString(String json, JsonOptions options) { - Objects.requireNonNull(json, "'json' cannot be null."); - return new GsonJsonReader(new StringReader(json), true, null, json, options); - } - - /** - * Constructs an instance of {@link JsonReader} from an {@link InputStream}. - * - * @param json JSON {@link InputStream}. - * @param options {@link JsonOptions} to configure the creation of the {@link JsonReader}. - * @return An instance of {@link JsonReader}. - * @throws NullPointerException If {@code json} is null. - */ - static JsonReader fromStream(InputStream json, JsonOptions options) { - Objects.requireNonNull(json, "'json' cannot be null."); - return new GsonJsonReader(new InputStreamReader(json, StandardCharsets.UTF_8), json.markSupported(), null, null, - options); - } - - /** - * Constructs an instance of {@link GsonJsonReader} from a {@link Reader}. - * - * @param json JSON {@link Reader}. - * @param options {@link JsonOptions} to configure the creation of the {@link JsonReader}. - * @return An instance of {@link GsonJsonReader}. - * @throws NullPointerException If {@code json} is null. - */ - static JsonReader fromReader(Reader json, JsonOptions options) { - Objects.requireNonNull(json, "'json' cannot be null."); - return new GsonJsonReader(json, json.markSupported(), null, null, options); - } - - private GsonJsonReader(Reader reader, boolean resetSupported, byte[] jsonBytes, String jsonString, - JsonOptions options) { - this(reader, resetSupported, jsonBytes, jsonString, options.isNonNumericNumbersSupported()); - } - - @SuppressWarnings("deprecation") - private GsonJsonReader(Reader reader, boolean resetSupported, byte[] jsonBytes, String jsonString, - boolean nonNumericNumbersSupported) { - this.reader = new com.google.gson.stream.JsonReader(reader); - this.reader.setLenient(nonNumericNumbersSupported); - this.resetSupported = resetSupported; - this.jsonBytes = jsonBytes; - this.jsonString = jsonString; - this.nonNumericNumbersSupported = nonNumericNumbersSupported; - } - - @Override - public JsonToken currentToken() { - return currentToken; - } - - @Override - public JsonToken nextToken() throws IOException { - if (complete) { - return currentToken; - } - - // GSON requires explicitly beginning and ending arrays and objects and consuming null values. - // The contract of JsonReader implicitly overlooks these properties. - if (currentToken == JsonToken.START_OBJECT) { - reader.beginObject(); - } else if (currentToken == JsonToken.END_OBJECT) { - reader.endObject(); - } else if (currentToken == JsonToken.START_ARRAY) { - reader.beginArray(); - } else if (currentToken == JsonToken.END_ARRAY) { - reader.endArray(); - } else if (currentToken == JsonToken.NULL) { - reader.nextNull(); - } - - if (!consumed && currentToken != null) { - switch (currentToken) { - case FIELD_NAME: - reader.nextName(); - break; - - case BOOLEAN: - reader.nextBoolean(); - break; - - case NUMBER: - reader.nextDouble(); - break; - - case STRING: - reader.nextString(); - break; - - default: - break; - } - } - - com.google.gson.stream.JsonToken gsonToken = reader.peek(); - if (gsonToken == com.google.gson.stream.JsonToken.END_DOCUMENT) { - complete = true; - } - - currentToken = mapToken(reader.peek()); - consumed = false; - return currentToken; - } - - @Override - public byte[] getBinary() throws IOException { - consumed = true; - - if (currentToken == JsonToken.NULL) { - reader.nextNull(); - return null; - } else { - return Base64.getDecoder().decode(reader.nextString()); - } - } - - @Override - public boolean getBoolean() throws IOException { - consumed = true; - - return reader.nextBoolean(); - } - - @Override - public double getDouble() throws IOException { - consumed = true; - - return reader.nextDouble(); - } - - @Override - public float getFloat() throws IOException { - consumed = true; - - return (float) reader.nextDouble(); - } - - @Override - public int getInt() throws IOException { - consumed = true; - - return reader.nextInt(); - } - - @Override - public long getLong() throws IOException { - consumed = true; - - return reader.nextLong(); - } - - @Override - public String getString() throws IOException { - consumed = true; - - if (currentToken == JsonToken.NULL) { - return null; - } else { - return reader.nextString(); - } - } - - @Override - public String getFieldName() throws IOException { - consumed = true; - - return reader.nextName(); - } - - @Override - public void skipChildren() throws IOException { - consumed = true; - - reader.skipValue(); - } - - @Override - public JsonReader bufferObject() throws IOException { - if (currentToken == JsonToken.START_OBJECT || currentToken == JsonToken.FIELD_NAME) { - consumed = true; - String json = readRemainingFieldsAsJsonObject(); - return new GsonJsonReader(new StringReader(json), true, null, json, nonNumericNumbersSupported); - } else { - throw new IllegalStateException("Cannot buffer a JSON object from a non-object, non-field name " - + "starting location. Starting location: " + currentToken()); - } - } - - @Override - public boolean isResetSupported() { - return resetSupported; - } - - @Override - public JsonReader reset() throws IOException { - if (!resetSupported) { - throw new IllegalStateException("'reset' isn't supported by this JsonReader."); - } - - if (jsonBytes != null) { - return new GsonJsonReader( - new InputStreamReader(new ByteArrayInputStream(jsonBytes), StandardCharsets.UTF_8), true, jsonBytes, - null, nonNumericNumbersSupported); - } else { - return new GsonJsonReader(new StringReader(jsonString), true, null, jsonString, nonNumericNumbersSupported); - } - } - - @Override - public void close() throws IOException { - reader.close(); - } - - /* - * Maps the GSON JsonToken to the azure-json JsonToken. - */ - private static JsonToken mapToken(com.google.gson.stream.JsonToken token) { - // Special case for when currentToken is called after instantiating the JsonReader. - if (token == null) { - return null; - } - - switch (token) { - case BEGIN_OBJECT: - return JsonToken.START_OBJECT; - - case END_OBJECT: - return JsonToken.END_OBJECT; - - case BEGIN_ARRAY: - return JsonToken.START_ARRAY; - - case END_ARRAY: - return JsonToken.END_ARRAY; - - case NAME: - return JsonToken.FIELD_NAME; - - case STRING: - return JsonToken.STRING; - - case NUMBER: - return JsonToken.NUMBER; - - case BOOLEAN: - return JsonToken.BOOLEAN; - - case NULL: - return JsonToken.NULL; - - case END_DOCUMENT: - return JsonToken.END_DOCUMENT; - - default: - throw new IllegalStateException("Unsupported token type: '" + token + "'."); - } - } -} diff --git a/sdk/serialization/azure-json-gson/src/main/java/com/azure/json/gson/GsonJsonWriter.java b/sdk/serialization/azure-json-gson/src/main/java/com/azure/json/gson/GsonJsonWriter.java deleted file mode 100644 index 5f97e573d32b..000000000000 --- a/sdk/serialization/azure-json-gson/src/main/java/com/azure/json/gson/GsonJsonWriter.java +++ /dev/null @@ -1,226 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.json.gson; - -import com.azure.json.JsonOptions; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriteContext; -import com.azure.json.JsonWriter; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.nio.charset.StandardCharsets; -import java.util.Base64; -import java.util.Objects; - -/** - * GSON-based implementation of {@link JsonWriter}. - */ -public final class GsonJsonWriter extends JsonWriter { - private final com.google.gson.stream.JsonWriter writer; - - // Initial state is always root. - private JsonWriteContext context = JsonWriteContext.ROOT; - - /** - * Creates a {@link GsonJsonWriter} that writes the given {@link OutputStream}. - *

        - * The passed {@link OutputStream} won't be closed when {@link #close()} is called as the {@link GsonJsonWriter} - * isn't the owner of the stream. - * - * @param json The {@link OutputStream} that will be written. - * @param options {@link JsonOptions} to configure the creation of the {@link JsonWriter}. - * @return An instance of {@link GsonJsonWriter}. - * @throws NullPointerException If {@code json} is null. - * - */ - static JsonWriter toStream(OutputStream json, JsonOptions options) { - Objects.requireNonNull(json, "'json' cannot be null."); - return new GsonJsonWriter(new OutputStreamWriter(json, StandardCharsets.UTF_8), options); - } - - /** - * Creates a {@link GsonJsonWriter} that writes the given {@link Writer}. - *

        - * The passed {@link Writer} won't be closed when {@link #close()} is called as the {@link GsonJsonWriter} - * isn't the owner of the stream. - * - * @param json The {@link Writer} that will be written. - * @param options {@link JsonOptions} to configure the creation of the {@link JsonWriter}. - * @return An instance of {@link GsonJsonWriter}. - * @throws NullPointerException If {@code json} is null. - */ - static JsonWriter toWriter(Writer json, JsonOptions options) { - Objects.requireNonNull(json, "'json' cannot be null."); - return new GsonJsonWriter(json, options); - } - - @SuppressWarnings("deprecation") - private GsonJsonWriter(Writer writer, JsonOptions options) { - this.writer = new com.google.gson.stream.JsonWriter(writer); - this.writer.setLenient(options.isNonNumericNumbersSupported()); - } - - @Override - public JsonWriteContext getWriteContext() { - return context; - } - - @Override - public void close() throws IOException { - if (context != JsonWriteContext.COMPLETED) { - throw new IllegalStateException("Writing of the JSON object must be completed before the writer can be " - + "closed. Current writing state is '" + context.getWriteState() + "'."); - } - - writer.flush(); - writer.close(); - } - - @Override - public JsonWriter flush() throws IOException { - writer.flush(); - return this; - } - - @Override - public JsonWriter writeStartObject() throws IOException { - context.validateToken(JsonToken.START_OBJECT); - writer.beginObject(); - - context = context.updateContext(JsonToken.START_OBJECT); - return this; - } - - @Override - public JsonWriter writeEndObject() throws IOException { - context.validateToken(JsonToken.END_OBJECT); - writer.endObject(); - - context = context.updateContext(JsonToken.END_OBJECT); - return this; - } - - @Override - public JsonWriter writeStartArray() throws IOException { - context.validateToken(JsonToken.START_ARRAY); - writer.beginArray(); - - context = context.updateContext(JsonToken.START_ARRAY); - return this; - } - - @Override - public JsonWriter writeEndArray() throws IOException { - context.validateToken(JsonToken.END_ARRAY); - writer.endArray(); - - context = context.updateContext(JsonToken.END_ARRAY); - return this; - } - - @Override - public JsonWriter writeFieldName(String fieldName) throws IOException { - Objects.requireNonNull(fieldName, "'fieldName' cannot be null."); - - context.validateToken(JsonToken.FIELD_NAME); - writer.name(fieldName); - - context = context.updateContext(JsonToken.FIELD_NAME); - return this; - } - - @Override - public JsonWriter writeBinary(byte[] value) throws IOException { - context.validateToken(JsonToken.STRING); - writeBinaryInternal(value); - - context = context.updateContext(JsonToken.STRING); - return this; - } - - @Override - public JsonWriter writeBoolean(boolean value) throws IOException { - context.validateToken(JsonToken.BOOLEAN); - writer.value(value); - - context = context.updateContext(JsonToken.BOOLEAN); - return this; - } - - @Override - public JsonWriter writeDouble(double value) throws IOException { - context.validateToken(JsonToken.NUMBER); - writer.value(value); - - context = context.updateContext(JsonToken.NUMBER); - return this; - } - - @Override - public JsonWriter writeFloat(float value) throws IOException { - context.validateToken(JsonToken.NUMBER); - writer.value(value); - - context = context.updateContext(JsonToken.NUMBER); - return this; - } - - @Override - public JsonWriter writeInt(int value) throws IOException { - context.validateToken(JsonToken.NUMBER); - writer.value(value); - - context = context.updateContext(JsonToken.NUMBER); - return this; - } - - @Override - public JsonWriter writeLong(long value) throws IOException { - context.validateToken(JsonToken.NUMBER); - writer.value(value); - - context = context.updateContext(JsonToken.NUMBER); - return this; - } - - @Override - public JsonWriter writeNull() throws IOException { - context.validateToken(JsonToken.NULL); - writer.nullValue(); - - context = context.updateContext(JsonToken.NULL); - return this; - } - - @Override - public JsonWriter writeString(String value) throws IOException { - context.validateToken(JsonToken.STRING); - writer.value(value); - - context = context.updateContext(JsonToken.STRING); - return this; - } - - @Override - public JsonWriter writeRawValue(String value) throws IOException { - Objects.requireNonNull(value, "'value' cannot be null."); - - context.validateToken(JsonToken.STRING); - writer.jsonValue(value); - - context = context.updateContext(JsonToken.STRING); - return this; - } - - private void writeBinaryInternal(byte[] value) throws IOException { - if (value == null) { - writer.nullValue(); - } else { - writer.value(Base64.getEncoder().encodeToString(value)); - } - } -} diff --git a/sdk/serialization/azure-json-gson/src/main/java/com/azure/json/gson/package-info.java b/sdk/serialization/azure-json-gson/src/main/java/com/azure/json/gson/package-info.java deleted file mode 100644 index e47afeb35c09..000000000000 --- a/sdk/serialization/azure-json-gson/src/main/java/com/azure/json/gson/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - * Contains general classes for GSON-based handling JSON. - */ -package com.azure.json.gson; diff --git a/sdk/serialization/azure-json-gson/src/main/java/module-info.java b/sdk/serialization/azure-json-gson/src/main/java/module-info.java deleted file mode 100644 index 9ef2e6e8dc8d..000000000000 --- a/sdk/serialization/azure-json-gson/src/main/java/module-info.java +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -module com.azure.json.gson { - requires transitive com.azure.json; - - requires com.google.gson; - - exports com.azure.json.gson; - - provides com.azure.json.JsonProvider with com.azure.json.gson.GsonJsonProvider; -} diff --git a/sdk/serialization/azure-json-gson/src/main/resources/META-INF/services/com.azure.json.JsonProvider b/sdk/serialization/azure-json-gson/src/main/resources/META-INF/services/com.azure.json.JsonProvider deleted file mode 100644 index 2c52ef3599b3..000000000000 --- a/sdk/serialization/azure-json-gson/src/main/resources/META-INF/services/com.azure.json.JsonProvider +++ /dev/null @@ -1 +0,0 @@ -com.azure.json.gson.GsonJsonProvider diff --git a/sdk/serialization/azure-json-gson/src/test/java/com/azure/json/gson/GsonJsonInstantiationTests.java b/sdk/serialization/azure-json-gson/src/test/java/com/azure/json/gson/GsonJsonInstantiationTests.java deleted file mode 100644 index 20332cfae4a5..000000000000 --- a/sdk/serialization/azure-json-gson/src/test/java/com/azure/json/gson/GsonJsonInstantiationTests.java +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.json.gson; - -import org.junit.jupiter.api.function.Executable; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; - -import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.assertThrows; - -/** - * Tests instantiating {@link GsonJsonReader} and {@link GsonJsonWriter}. - */ -public class GsonJsonInstantiationTests { - @ParameterizedTest - @MethodSource("throwsNullPointerExceptionSupplier") - public void throwsNullPointerException(Executable executable) { - assertThrows(NullPointerException.class, executable); - } - - @SuppressWarnings("resource") - private static Stream throwsNullPointerExceptionSupplier() { - return Stream.of(() -> GsonJsonReader.fromBytes(null, null), () -> GsonJsonReader.fromReader(null, null), - () -> GsonJsonReader.fromString(null, null), () -> GsonJsonReader.fromStream(null, null), - - () -> GsonJsonWriter.toStream(null, null), () -> GsonJsonWriter.toWriter(null, null)); - } -} diff --git a/sdk/serialization/azure-json-gson/src/test/java/com/azure/json/gson/GsonJsonReaderContractTests.java b/sdk/serialization/azure-json-gson/src/test/java/com/azure/json/gson/GsonJsonReaderContractTests.java deleted file mode 100644 index 71abd8e5bdf7..000000000000 --- a/sdk/serialization/azure-json-gson/src/test/java/com/azure/json/gson/GsonJsonReaderContractTests.java +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.json.gson; - -import com.azure.json.JsonOptions; -import com.azure.json.JsonReader; -import com.azure.json.contract.JsonReaderContractTests; - -/** - * Tests {@link GsonJsonReader} against the contract required by {@link JsonReader}. - */ -public class GsonJsonReaderContractTests extends JsonReaderContractTests { - @Override - public JsonReader getJsonReader(String json) { - return GsonJsonReader.fromString(json, new JsonOptions()); - } -} diff --git a/sdk/serialization/azure-json-gson/src/test/java/com/azure/json/gson/GsonJsonWriterContractTests.java b/sdk/serialization/azure-json-gson/src/test/java/com/azure/json/gson/GsonJsonWriterContractTests.java deleted file mode 100644 index eaf10c9ad3dd..000000000000 --- a/sdk/serialization/azure-json-gson/src/test/java/com/azure/json/gson/GsonJsonWriterContractTests.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.json.gson; - -import com.azure.json.JsonOptions; -import com.azure.json.JsonWriter; -import com.azure.json.contract.JsonWriterContractTests; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.charset.StandardCharsets; - -/** - * Tests {@link GsonJsonWriter} against the contract required by {@link JsonWriter}. - */ -public class GsonJsonWriterContractTests extends JsonWriterContractTests { - private ByteArrayOutputStream outputStream; - private JsonWriter writer; - - @BeforeEach - public void beforeEach() throws IOException { - this.outputStream = new ByteArrayOutputStream(); - this.writer = GsonJsonWriter.toStream(outputStream, new JsonOptions()); - } - - @AfterEach - public void afterEach() throws IOException { - if (writer != null) { - try { - writer.close(); - } catch (IllegalStateException ignored) { - // Closing the JsonWriter may throw an IllegalStateException if the current writing state isn't valid - // for closing, ignore it in test. - } - } - } - - @Override - public JsonWriter getJsonWriter() { - return writer; - } - - @Override - public String getJsonWriterContents() { - try { - writer.flush(); - return outputStream.toString(StandardCharsets.UTF_8.name()); - } catch (IOException e) { - throw new RuntimeException(e); - } - } -} diff --git a/sdk/serialization/azure-json-reflect/CHANGELOG.md b/sdk/serialization/azure-json-reflect/CHANGELOG.md deleted file mode 100644 index a91cdb9d04ea..000000000000 --- a/sdk/serialization/azure-json-reflect/CHANGELOG.md +++ /dev/null @@ -1,22 +0,0 @@ -# Release History - -## 1.0.0-beta.3 (Unreleased) - -### Features Added - -### Breaking Changes - -### Bugs Fixed - -### Other Changes - -## 1.0.0-beta.2 (2023-03-02) -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-json` to `1.0.0-beta.3`. - -## 1.0.0-beta.1 (2023-02-01) - -- Initial release. Please see the README for more information. diff --git a/sdk/serialization/azure-json-reflect/README.md b/sdk/serialization/azure-json-reflect/README.md deleted file mode 100644 index 32203fa1aef1..000000000000 --- a/sdk/serialization/azure-json-reflect/README.md +++ /dev/null @@ -1,56 +0,0 @@ -# Azure Json Reflect shared library for Java - -Azure Json Reflect provides implementations of `azure-json` using reflection. -It uses Jackson and Gson but has no dependencies on these libraries. -To use Azure Json Reflect a compatible version of Jackson or Gson must be present on the classpath. - -## Getting started - -### Prerequisites - -- A [Java Development Kit (JDK)][jdk_link], version 8 or later. - -### Supported versions - -#### Jackson -- Versions 2.10.0 and newer - -#### Gson -- Versions 2.4 and newer - -## Key concepts - -See `azure-json` for more key concepts. - -This package searches the relative classpath for Jackson or Gson. -It will then search for all the methods that are required for the `JsonReader` and `JsonWriter` implementations. -These implementations provide abstractions of the JSON libraries. - -### Entry point -Use `JsonProviderFactory.getInstance()`, `JsonProviderFactory.getJacksonJsonProvider()`, or -`JsonProviderFactory.getGsonJsonProvider()` to get a `JsonProvider`. - -## Examples - -See `azure-json` for examples. - -## Next steps - -Get started with Azure libraries that are [built using Azure Core](https://azure.github.io/azure-sdk/releases/latest/#java). - -## Troubleshooting - -If you encounter any bugs, please file issues via [GitHub Issues](https://github.com/Azure/azure-sdk-for-java/issues/new/choose) -or checkout [StackOverflow for Azure Java SDK](https://stackoverflow.com/questions/tagged/azure-java-sdk). - -## Contributing - -For details on contributing to this repository, see the contributing guide. -1. Fork it -2. Create your feature branch (`git checkout -b my-new-feature`) -3. Commit your changes (`git commit -am 'Add some features`) -4. Push to the branch (`git push origin my-new-feature`) -5. Create new pull Request - - -[jdk_link]: https://learn.microsoft.com/java/azure/jdk/?view=azure-java-stable diff --git a/sdk/serialization/azure-json-reflect/checkstyle-suppressions.xml b/sdk/serialization/azure-json-reflect/checkstyle-suppressions.xml deleted file mode 100644 index c36207a9d76f..000000000000 --- a/sdk/serialization/azure-json-reflect/checkstyle-suppressions.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - diff --git a/sdk/serialization/azure-json-reflect/pom.xml b/sdk/serialization/azure-json-reflect/pom.xml deleted file mode 100644 index 2196a69a916c..000000000000 --- a/sdk/serialization/azure-json-reflect/pom.xml +++ /dev/null @@ -1,142 +0,0 @@ - - - 4.0.0 - - com.azure - azure-client-sdk-parent - 1.7.0 - ../../parents/azure-client-sdk-parent - - - com.azure - azure-json-reflect - jar - 1.0.0-beta.3 - - Microsoft Azure Java JSON Reflect Library - This package reflectively looks for a valid JSON library and provides an abstraction. - https://github.com/Azure/azure-sdk-for-java - - - - The MIT License (MIT) - http://opensource.org/licenses/MIT - repo - - - - - - azure-java-build-docs - ${site.url}/site/${project.artifactId} - - - - - https://github.com/Azure/azure-sdk-for-java - scm:git:https://github.com/Azure/azure-sdk-for-java.git - scm:git:https://github.com/Azure/azure-sdk-for-java.git - - - - UTF-8 - - - - --add-opens com.azure.json.reflect/com.azure.json.reflect=ALL-UNNAMED - - - - ${basedir}/src/main/java - - checkstyle-suppressions.xml - - - - - microsoft - Microsoft - - - - - - com.azure - azure-json - 1.4.0-beta.1 - - - - - com.google.code.gson - gson - 2.11.0 - test - - - com.fasterxml.jackson.core - jackson-core - 2.17.2 - test - - - com.azure - azure-json - 1.4.0-beta.1 - test-jar - test - - - org.junit.jupiter - junit-jupiter-api - 5.11.2 - test - - - org.junit.jupiter - junit-jupiter-engine - 5.11.2 - test - - - org.junit.jupiter - junit-jupiter-params - 5.11.2 - test - - - - - - - - com.github.spotbugs - spotbugs-maven-plugin - 4.8.3.1 - - - - com.h3xstream.findsecbugs - findsecbugs-plugin - 1.9.0 - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.13.0 - - - -Xlint:deprecation - - - - - - - diff --git a/sdk/serialization/azure-json-reflect/src/main/java/com/azure/json/reflect/GsonJsonProvider.java b/sdk/serialization/azure-json-reflect/src/main/java/com/azure/json/reflect/GsonJsonProvider.java deleted file mode 100644 index 9e97f5871dbc..000000000000 --- a/sdk/serialization/azure-json-reflect/src/main/java/com/azure/json/reflect/GsonJsonProvider.java +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.json.reflect; - -import com.azure.json.JsonOptions; -import com.azure.json.JsonProvider; -import com.azure.json.JsonReader; -import com.azure.json.JsonWriter; - -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; -import java.io.Writer; - -class GsonJsonProvider implements JsonProvider { - static final boolean INITIALIZED = GsonJsonReader.INITIALIZED && GsonJsonWriter.INITIALIZED; - - @Override - public JsonReader createReader(byte[] json, JsonOptions options) { - return GsonJsonReader.fromBytes(json, options); - } - - @Override - public JsonReader createReader(String json, JsonOptions options) { - return GsonJsonReader.fromString(json, options); - } - - @Override - public JsonReader createReader(InputStream json, JsonOptions options) { - return GsonJsonReader.fromStream(json, options); - } - - @Override - public JsonReader createReader(Reader json, JsonOptions options) { - return GsonJsonReader.fromReader(json, options); - } - - @Override - public JsonWriter createWriter(OutputStream json, JsonOptions options) { - return GsonJsonWriter.toStream(json, options); - } - - @Override - public JsonWriter createWriter(Writer json, JsonOptions options) { - return GsonJsonWriter.toWriter(json, options); - } -} diff --git a/sdk/serialization/azure-json-reflect/src/main/java/com/azure/json/reflect/GsonJsonReader.java b/sdk/serialization/azure-json-reflect/src/main/java/com/azure/json/reflect/GsonJsonReader.java deleted file mode 100644 index f0382fa21179..000000000000 --- a/sdk/serialization/azure-json-reflect/src/main/java/com/azure/json/reflect/GsonJsonReader.java +++ /dev/null @@ -1,493 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.json.reflect; - -import com.azure.json.JsonOptions; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.IOException; -import java.io.Reader; -import java.io.StringReader; -import java.lang.invoke.LambdaMetafactory; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; -import java.lang.invoke.MethodType; -import java.nio.charset.StandardCharsets; -import java.util.Base64; -import java.util.Objects; - -import static java.lang.invoke.MethodType.methodType; -import static com.azure.json.reflect.MetaFactoryFactory.createMetaFactory; - -final class GsonJsonReader extends JsonReader { - private static final Class GSON_JSON_TOKEN_ENUM; - - private static final JsonReaderConstructor JSON_READER_CONSTRUCTOR; - private static final JsonReaderSetLenient JSON_READER_SET_LENIENT; - private static final JsonReaderClose JSON_READER_CLOSE; - private static final JsonReaderPeek JSON_READER_PEEK; - private static final JsonReaderBeginObject JSON_READER_BEGIN_OBJECT; - private static final JsonReaderEndObject JSON_READER_END_OBJECT; - private static final JsonReaderBeginArray JSON_READER_BEGIN_ARRAY; - private static final JsonReaderEndArray JSON_READER_END_ARRAY; - private static final JsonReaderNextNull JSON_READER_NEXT_NULL; - private static final JsonReaderNextName JSON_READER_NEXT_NAME; - private static final JsonReaderNextString JSON_READER_NEXT_STRING; - private static final JsonReaderNextBoolean JSON_READER_NEXT_BOOLEAN; - private static final JsonReaderNextInt JSON_READER_NEXT_INT; - private static final JsonReaderNextLong JSON_READER_NEXT_LONG; - private static final JsonReaderNextDouble JSON_READER_NEXT_DOUBLE; - private static final JsonReaderSkipValue JSON_READER_SKIP_VALUE; - - static final boolean INITIALIZED; - - static { - final MethodHandles.Lookup lookup = MethodHandles.lookup(); - - final MethodType voidMT = methodType(void.class); - final MethodType voidObjectMT = methodType(void.class, Object.class); - - Class gsonJsonTokenEnum = null; - - JsonReaderConstructor jsonReaderConstructor = null; - JsonReaderSetLenient jsonReaderSetLenient = null; - JsonReaderClose jsonReaderClose = null; - JsonReaderPeek jsonReaderPeek = null; - JsonReaderBeginObject jsonReaderBeginObject = null; - JsonReaderEndObject jsonReaderEndObject = null; - JsonReaderBeginArray jsonReaderBeginArray = null; - JsonReaderEndArray jsonReaderEndArray = null; - JsonReaderNextNull jsonReaderNextNull = null; - JsonReaderNextName jsonReaderNextName = null; - JsonReaderNextString jsonReaderNextString = null; - JsonReaderNextBoolean jsonReaderNextBoolean = null; - JsonReaderNextInt jsonReaderNextInt = null; - JsonReaderNextLong jsonReaderNextLong = null; - JsonReaderNextDouble jsonReaderNextDouble = null; - JsonReaderSkipValue jsonReaderSkipValue = null; - - boolean initialized = false; - - try { - Class gsonJsonReaderClass = Class.forName("com.google.gson.stream.JsonReader"); - gsonJsonTokenEnum = Class.forName("com.google.gson.stream.JsonToken"); - - MethodHandle gsonReaderConstructor - = lookup.findConstructor(gsonJsonReaderClass, methodType(void.class, Reader.class)); - jsonReaderConstructor = (JsonReaderConstructor) LambdaMetafactory - .metafactory(lookup, "createJsonReader", methodType(JsonReaderConstructor.class), - methodType(Object.class, Reader.class), gsonReaderConstructor, gsonReaderConstructor.type()) - .getTarget() - .invoke(); - - jsonReaderSetLenient - = createMetaFactory("setLenient", gsonJsonReaderClass, methodType(void.class, boolean.class), - JsonReaderSetLenient.class, methodType(void.class, Object.class, boolean.class), lookup); - jsonReaderClose - = createMetaFactory("close", gsonJsonReaderClass, voidMT, JsonReaderClose.class, voidObjectMT, lookup); - jsonReaderPeek = createMetaFactory("peek", gsonJsonReaderClass, methodType(gsonJsonTokenEnum), - JsonReaderPeek.class, methodType(Object.class, Object.class), lookup); - jsonReaderBeginObject = createMetaFactory("beginObject", gsonJsonReaderClass, voidMT, - JsonReaderBeginObject.class, voidObjectMT, lookup); - jsonReaderEndObject = createMetaFactory("endObject", gsonJsonReaderClass, voidMT, JsonReaderEndObject.class, - voidObjectMT, lookup); - jsonReaderBeginArray = createMetaFactory("beginArray", gsonJsonReaderClass, voidMT, - JsonReaderBeginArray.class, voidObjectMT, lookup); - jsonReaderEndArray = createMetaFactory("endArray", gsonJsonReaderClass, voidMT, JsonReaderEndArray.class, - voidObjectMT, lookup); - jsonReaderNextNull = createMetaFactory("nextNull", gsonJsonReaderClass, voidMT, JsonReaderNextNull.class, - voidObjectMT, lookup); - jsonReaderNextName = createMetaFactory("nextName", gsonJsonReaderClass, methodType(String.class), - JsonReaderNextName.class, methodType(String.class, Object.class), lookup); - jsonReaderNextString = createMetaFactory("nextString", gsonJsonReaderClass, methodType(String.class), - JsonReaderNextString.class, methodType(String.class, Object.class), lookup); - jsonReaderNextBoolean = createMetaFactory("nextBoolean", gsonJsonReaderClass, methodType(boolean.class), - JsonReaderNextBoolean.class, methodType(boolean.class, Object.class), lookup); - jsonReaderNextInt = createMetaFactory("nextInt", gsonJsonReaderClass, methodType(int.class), - JsonReaderNextInt.class, methodType(int.class, Object.class), lookup); - jsonReaderNextLong = createMetaFactory("nextLong", gsonJsonReaderClass, methodType(long.class), - JsonReaderNextLong.class, methodType(long.class, Object.class), lookup); - jsonReaderNextDouble = createMetaFactory("nextDouble", gsonJsonReaderClass, methodType(double.class), - JsonReaderNextDouble.class, methodType(double.class, Object.class), lookup); - jsonReaderSkipValue = createMetaFactory("skipValue", gsonJsonReaderClass, voidMT, JsonReaderSkipValue.class, - voidObjectMT, lookup); - - initialized = true; - } catch (Throwable e) { - if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } else if (e instanceof Error) { - throw (Error) e; - } - } - - GSON_JSON_TOKEN_ENUM = gsonJsonTokenEnum; - - JSON_READER_CONSTRUCTOR = jsonReaderConstructor; - JSON_READER_SET_LENIENT = jsonReaderSetLenient; - JSON_READER_CLOSE = jsonReaderClose; - JSON_READER_PEEK = jsonReaderPeek; - JSON_READER_BEGIN_OBJECT = jsonReaderBeginObject; - JSON_READER_END_OBJECT = jsonReaderEndObject; - JSON_READER_BEGIN_ARRAY = jsonReaderBeginArray; - JSON_READER_END_ARRAY = jsonReaderEndArray; - JSON_READER_NEXT_NULL = jsonReaderNextNull; - JSON_READER_NEXT_NAME = jsonReaderNextName; - JSON_READER_NEXT_STRING = jsonReaderNextString; - JSON_READER_NEXT_BOOLEAN = jsonReaderNextBoolean; - JSON_READER_NEXT_INT = jsonReaderNextInt; - JSON_READER_NEXT_LONG = jsonReaderNextLong; - JSON_READER_NEXT_DOUBLE = jsonReaderNextDouble; - JSON_READER_SKIP_VALUE = jsonReaderSkipValue; - - INITIALIZED = initialized; - } - - private final Object gsonJsonReader; - private JsonToken currentToken; - - private final byte[] jsonBytes; - private final String jsonString; - private final boolean resetSupported; - private final boolean nonNumericNumbersSupported; - - private boolean consumed = false; - private boolean complete = false; - - static JsonReader fromBytes(byte[] json, JsonOptions options) { - Objects.requireNonNull(json, "'json' cannot be null."); - return new GsonJsonReader(new InputStreamReader(new ByteArrayInputStream(json), StandardCharsets.UTF_8), true, - json, null, options); - } - - static JsonReader fromString(String json, JsonOptions options) { - Objects.requireNonNull(json, "'json' cannot be null."); - return new GsonJsonReader(new StringReader(json), true, null, json, options); - } - - static JsonReader fromStream(InputStream json, JsonOptions options) { - Objects.requireNonNull(json, "'json' cannot be null."); - return new GsonJsonReader(new InputStreamReader(json, StandardCharsets.UTF_8), json.markSupported(), null, null, - options); - } - - static JsonReader fromReader(Reader json, JsonOptions options) { - Objects.requireNonNull(json, "'json' cannot be null."); - return new GsonJsonReader(json, json.markSupported(), null, null, options); - } - - private GsonJsonReader(Reader reader, boolean resetSupported, byte[] jsonBytes, String jsonString, - JsonOptions options) { - this(reader, resetSupported, jsonBytes, jsonString, options.isNonNumericNumbersSupported()); - } - - private GsonJsonReader(Reader reader, boolean resetSupported, byte[] jsonBytes, String jsonString, - boolean nonNumericNumbersSupported) { - if (!INITIALIZED) { - throw new IllegalStateException("No compatible version of Gson is present on the classpath."); - } - - gsonJsonReader = JSON_READER_CONSTRUCTOR.createJsonReader(reader); - JSON_READER_SET_LENIENT.setLenient(gsonJsonReader, nonNumericNumbersSupported); - - this.resetSupported = resetSupported; - this.jsonBytes = jsonBytes; - this.jsonString = jsonString; - this.nonNumericNumbersSupported = nonNumericNumbersSupported; - } - - @Override - public JsonToken currentToken() { - return currentToken; - } - - @Override - public JsonToken nextToken() throws IOException { - if (complete) { - return currentToken; - } - - // GSON requires explicitly beginning and ending arrays and objects and consuming null values. - // The contract of JsonReader implicitly overlooks these properties. - if (currentToken == JsonToken.START_OBJECT) { - JSON_READER_BEGIN_OBJECT.beginObject(gsonJsonReader); - } else if (currentToken == JsonToken.END_OBJECT) { - JSON_READER_END_OBJECT.endObject(gsonJsonReader); - } else if (currentToken == JsonToken.START_ARRAY) { - JSON_READER_BEGIN_ARRAY.beginArray(gsonJsonReader); - } else if (currentToken == JsonToken.END_ARRAY) { - JSON_READER_END_ARRAY.endArray(gsonJsonReader); - } else if (currentToken == JsonToken.NULL) { - JSON_READER_NEXT_NULL.nextNull(gsonJsonReader); - } - - if (!consumed && currentToken != null) { - switch (currentToken) { - case FIELD_NAME: - JSON_READER_NEXT_NAME.nextName(gsonJsonReader); - break; - - case BOOLEAN: - JSON_READER_NEXT_BOOLEAN.nextBoolean(gsonJsonReader); - break; - - case NUMBER: - JSON_READER_NEXT_DOUBLE.nextDouble(gsonJsonReader); - break; - - case STRING: - JSON_READER_NEXT_STRING.nextString(gsonJsonReader); - break; - - default: - break; - } - } - - currentToken = mapToken((Enum) JSON_READER_PEEK.peek(gsonJsonReader)); - - if (currentToken == JsonToken.END_DOCUMENT) { - complete = true; - } - - consumed = false; - return currentToken; - } - - @Override - public byte[] getBinary() throws IOException { - consumed = true; - - if (currentToken == JsonToken.NULL) { - JSON_READER_NEXT_NULL.nextNull(gsonJsonReader); - return null; - } else { - return Base64.getDecoder().decode(JSON_READER_NEXT_STRING.nextString(gsonJsonReader)); - } - } - - @Override - public boolean getBoolean() throws IOException { - consumed = true; - return JSON_READER_NEXT_BOOLEAN.nextBoolean(gsonJsonReader); - } - - @Override - public float getFloat() throws IOException { - consumed = true; - return (float) JSON_READER_NEXT_DOUBLE.nextDouble(gsonJsonReader); - } - - @Override - public double getDouble() throws IOException { - consumed = true; - return JSON_READER_NEXT_DOUBLE.nextDouble(gsonJsonReader); - } - - @Override - public int getInt() throws IOException { - consumed = true; - return JSON_READER_NEXT_INT.nextInt(gsonJsonReader); - } - - @Override - public long getLong() throws IOException { - consumed = true; - return JSON_READER_NEXT_LONG.nextLong(gsonJsonReader); - } - - @Override - public String getString() throws IOException { - consumed = true; - - if (currentToken == JsonToken.NULL) { - return null; - } else { - return JSON_READER_NEXT_STRING.nextString(gsonJsonReader); - } - } - - @Override - public String getFieldName() throws IOException { - consumed = true; - return JSON_READER_NEXT_NAME.nextName(gsonJsonReader); - } - - @Override - public void skipChildren() throws IOException { - consumed = true; - JSON_READER_SKIP_VALUE.skipValue(gsonJsonReader); - } - - @Override - public JsonReader bufferObject() throws IOException { - if (currentToken == JsonToken.START_OBJECT || currentToken == JsonToken.FIELD_NAME) { - consumed = true; - String json = readRemainingFieldsAsJsonObject(); - return new GsonJsonReader(new StringReader(json), true, null, json, nonNumericNumbersSupported); - } else { - throw new IllegalStateException("Cannot buffer a JSON object from a non-object, non-field name " - + "starting location. Starting location: " + currentToken()); - } - } - - @Override - public boolean isResetSupported() { - return resetSupported; - } - - @Override - public JsonReader reset() { - if (!resetSupported) { - throw new IllegalStateException("'reset' isn't supported by this JsonReader."); - } - - if (jsonBytes != null) { - return new GsonJsonReader( - new InputStreamReader(new ByteArrayInputStream(jsonBytes), StandardCharsets.UTF_8), true, jsonBytes, - null, nonNumericNumbersSupported); - } else { - return new GsonJsonReader(new StringReader(jsonString), true, null, jsonString, nonNumericNumbersSupported); - } - } - - @Override - public void close() throws IOException { - JSON_READER_CLOSE.close(gsonJsonReader); - } - - /* - * Maps the GSON JsonToken to the azure-json JsonToken. - */ - private JsonToken mapToken(Enum token) { - // Special case for when currentToken is called after instantiating the JsonReader. - if (token == null) { - return null; - } - - // Check token is GSON JsonToken - if (token.getClass() != GSON_JSON_TOKEN_ENUM) { - throw new IllegalStateException("Unsupported enum, pass a Gson JsonToken"); - } - - switch (token.name()) { - case "BEGIN_OBJECT": - return JsonToken.START_OBJECT; - - case "END_OBJECT": - return JsonToken.END_OBJECT; - - case "BEGIN_ARRAY": - return JsonToken.START_ARRAY; - - case "END_ARRAY": - return JsonToken.END_ARRAY; - - case "NAME": - return JsonToken.FIELD_NAME; - - case "STRING": - return JsonToken.STRING; - - case "NUMBER": - return JsonToken.NUMBER; - - case "BOOLEAN": - return JsonToken.BOOLEAN; - - case "NULL": - return JsonToken.NULL; - - case "END_DOCUMENT": - return JsonToken.END_DOCUMENT; - - default: - throw new IllegalStateException("Unsupported token type: '" + token + "'."); - } - } - - @FunctionalInterface - private interface JsonReaderConstructor { - Object createJsonReader(Reader reader); - } - - @FunctionalInterface - private interface JsonReaderSetLenient { - void setLenient(Object jsonReader, boolean lenient); - } - - @FunctionalInterface - private interface JsonReaderClose { - void close(Object jsonReader) throws IOException; - } - - @FunctionalInterface - private interface JsonReaderPeek { - Object peek(Object jsonReader) throws IOException; - } - - @FunctionalInterface - private interface JsonReaderBeginObject { - void beginObject(Object jsonReader) throws IOException; - } - - @FunctionalInterface - private interface JsonReaderEndObject { - void endObject(Object jsonReader) throws IOException; - } - - @FunctionalInterface - private interface JsonReaderBeginArray { - void beginArray(Object jsonReader) throws IOException; - } - - @FunctionalInterface - private interface JsonReaderEndArray { - void endArray(Object jsonReader) throws IOException; - } - - @FunctionalInterface - private interface JsonReaderNextNull { - void nextNull(Object jsonReader) throws IOException; - } - - @FunctionalInterface - private interface JsonReaderNextName { - String nextName(Object jsonReader) throws IOException; - } - - @FunctionalInterface - private interface JsonReaderNextString { - String nextString(Object jsonReader) throws IOException; - } - - @FunctionalInterface - private interface JsonReaderNextBoolean { - boolean nextBoolean(Object jsonReader) throws IOException; - } - - @FunctionalInterface - private interface JsonReaderNextInt { - int nextInt(Object jsonReader) throws IOException; - } - - @FunctionalInterface - private interface JsonReaderNextLong { - long nextLong(Object jsonReader) throws IOException; - } - - @FunctionalInterface - private interface JsonReaderNextDouble { - double nextDouble(Object jsonReader) throws IOException; - } - - @FunctionalInterface - private interface JsonReaderSkipValue { - void skipValue(Object jsonReader) throws IOException; - } -} diff --git a/sdk/serialization/azure-json-reflect/src/main/java/com/azure/json/reflect/GsonJsonWriter.java b/sdk/serialization/azure-json-reflect/src/main/java/com/azure/json/reflect/GsonJsonWriter.java deleted file mode 100644 index 6b86cb76c936..000000000000 --- a/sdk/serialization/azure-json-reflect/src/main/java/com/azure/json/reflect/GsonJsonWriter.java +++ /dev/null @@ -1,396 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.json.reflect; - -import com.azure.json.JsonOptions; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriteContext; -import com.azure.json.JsonWriter; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.lang.invoke.LambdaMetafactory; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; -import java.nio.charset.StandardCharsets; -import java.util.Base64; -import java.util.Objects; - -import static java.lang.invoke.MethodType.methodType; -import static com.azure.json.reflect.MetaFactoryFactory.createMetaFactory; - -final class GsonJsonWriter extends JsonWriter { - private static final JsonWriterConstructor JSON_WRITER_CONSTRUCTOR; - private static final JsonWriterSetLenient JSON_WRITER_SET_LENIENT; - private static final JsonWriterClose JSON_WRITER_CLOSE; - private static final JsonWriterFlush JSON_WRITER_FLUSH; - private static final JsonWriterBeginObject JSON_WRITER_BEGIN_OBJECT; - private static final JsonWriterEndObject JSON_WRITER_END_OBJECT; - private static final JsonWriterBeginArray JSON_WRITER_BEGIN_ARRAY; - private static final JsonWriterEndArray JSON_WRITER_END_ARRAY; - private static final JsonWriterNullValue JSON_WRITER_NULL_VALUE; - private static final JsonWriterName JSON_WRITER_NAME; - private static final JsonWriterStringValue JSON_WRITER_STRING_VALUE; - private static final JsonWriterBooleanValue JSON_WRITER_BOOLEAN_VALUE; - private static final JsonWriterLongValue JSON_WRITER_LONG_VALUE; - private static final JsonWriterDoubleValue JSON_WRITER_DOUBLE_VALUE; - private static final JsonWriterRawValue JSON_WRITER_RAW_VALUE; - - static final boolean INITIALIZED; - - static { - final MethodHandles.Lookup lookup = MethodHandles.lookup(); - - JsonWriterConstructor jsonWriterConstructor = null; - JsonWriterSetLenient jsonWriterSetLenient = null; - JsonWriterClose jsonWriterClose = null; - JsonWriterFlush jsonWriterFlush = null; - JsonWriterBeginObject jsonWriterBeginObject = null; - JsonWriterEndObject jsonWriterEndObject = null; - JsonWriterBeginArray jsonWriterBeginArray = null; - JsonWriterEndArray jsonWriterEndArray = null; - JsonWriterNullValue jsonWriterNullValue = null; - JsonWriterName jsonWriterName = null; - JsonWriterStringValue jsonWriterStringValue = null; - JsonWriterLongValue jsonWriterLongValue = null; - JsonWriterBooleanValue jsonWriterBooleanValue = null; - JsonWriterDoubleValue jsonWriterDoubleValue = null; - JsonWriterRawValue jsonWriterRawValue = null; - - boolean initialized = false; - - try { - Class gsonJsonWriterClass = Class.forName("com.google.gson.stream.JsonWriter"); - - MethodHandle gsonWriterConstructor - = lookup.findConstructor(gsonJsonWriterClass, methodType(void.class, Writer.class)); - jsonWriterConstructor = (JsonWriterConstructor) LambdaMetafactory - .metafactory(lookup, "createJsonWriter", methodType(JsonWriterConstructor.class), - methodType(Object.class, Writer.class), gsonWriterConstructor, gsonWriterConstructor.type()) - .getTarget() - .invoke(); - - jsonWriterSetLenient - = createMetaFactory("setLenient", gsonJsonWriterClass, methodType(void.class, boolean.class), - JsonWriterSetLenient.class, methodType(void.class, Object.class, boolean.class), lookup); - jsonWriterClose = createMetaFactory("close", gsonJsonWriterClass, methodType(void.class), - JsonWriterClose.class, methodType(void.class, Object.class), lookup); - jsonWriterFlush = createMetaFactory("flush", gsonJsonWriterClass, methodType(void.class), - JsonWriterFlush.class, methodType(void.class, Object.class), lookup); - jsonWriterBeginObject - = createMetaFactory("beginObject", gsonJsonWriterClass, methodType(gsonJsonWriterClass), - JsonWriterBeginObject.class, methodType(Object.class, Object.class), lookup); - jsonWriterEndObject = createMetaFactory("endObject", gsonJsonWriterClass, methodType(gsonJsonWriterClass), - JsonWriterEndObject.class, methodType(Object.class, Object.class), lookup); - jsonWriterBeginArray = createMetaFactory("beginArray", gsonJsonWriterClass, methodType(gsonJsonWriterClass), - JsonWriterBeginArray.class, methodType(Object.class, Object.class), lookup); - jsonWriterEndArray = createMetaFactory("endArray", gsonJsonWriterClass, methodType(gsonJsonWriterClass), - JsonWriterEndArray.class, methodType(Object.class, Object.class), lookup); - jsonWriterNullValue = createMetaFactory("nullValue", gsonJsonWriterClass, methodType(gsonJsonWriterClass), - JsonWriterNullValue.class, methodType(Object.class, Object.class), lookup); - jsonWriterName - = createMetaFactory("name", gsonJsonWriterClass, methodType(gsonJsonWriterClass, String.class), - JsonWriterName.class, methodType(Object.class, Object.class, String.class), lookup); - jsonWriterStringValue - = createMetaFactory("value", gsonJsonWriterClass, methodType(gsonJsonWriterClass, String.class), - JsonWriterStringValue.class, methodType(Object.class, Object.class, String.class), lookup); - jsonWriterBooleanValue - = createMetaFactory("value", gsonJsonWriterClass, methodType(gsonJsonWriterClass, boolean.class), - JsonWriterBooleanValue.class, methodType(Object.class, Object.class, boolean.class), lookup); - jsonWriterLongValue - = createMetaFactory("value", gsonJsonWriterClass, methodType(gsonJsonWriterClass, long.class), - JsonWriterLongValue.class, methodType(Object.class, Object.class, long.class), lookup); - jsonWriterDoubleValue - = createMetaFactory("value", gsonJsonWriterClass, methodType(gsonJsonWriterClass, double.class), - JsonWriterDoubleValue.class, methodType(Object.class, Object.class, double.class), lookup); - jsonWriterRawValue - = createMetaFactory("jsonValue", gsonJsonWriterClass, methodType(gsonJsonWriterClass, String.class), - JsonWriterRawValue.class, methodType(Object.class, Object.class, String.class), lookup); - - initialized = true; - } catch (Throwable e) { - if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } else if (e instanceof Error) { - throw (Error) e; - } - } - - JSON_WRITER_CONSTRUCTOR = jsonWriterConstructor; - JSON_WRITER_SET_LENIENT = jsonWriterSetLenient; - JSON_WRITER_CLOSE = jsonWriterClose; - JSON_WRITER_FLUSH = jsonWriterFlush; - JSON_WRITER_BEGIN_OBJECT = jsonWriterBeginObject; - JSON_WRITER_END_OBJECT = jsonWriterEndObject; - JSON_WRITER_BEGIN_ARRAY = jsonWriterBeginArray; - JSON_WRITER_END_ARRAY = jsonWriterEndArray; - JSON_WRITER_NULL_VALUE = jsonWriterNullValue; - JSON_WRITER_NAME = jsonWriterName; - JSON_WRITER_STRING_VALUE = jsonWriterStringValue; - JSON_WRITER_BOOLEAN_VALUE = jsonWriterBooleanValue; - JSON_WRITER_LONG_VALUE = jsonWriterLongValue; - JSON_WRITER_DOUBLE_VALUE = jsonWriterDoubleValue; - JSON_WRITER_RAW_VALUE = jsonWriterRawValue; - - INITIALIZED = initialized; - - } - - private final Object gsonJsonWriter; - private JsonWriteContext context = JsonWriteContext.ROOT; - - static JsonWriter toStream(OutputStream json, JsonOptions options) { - Objects.requireNonNull(json, "'json' cannot be null."); - return new GsonJsonWriter(new OutputStreamWriter(json, StandardCharsets.UTF_8), options); - } - - static JsonWriter toWriter(Writer json, JsonOptions options) { - Objects.requireNonNull(json, "'json' cannot be null."); - return new GsonJsonWriter(json, options); - } - - private GsonJsonWriter(Writer writer, JsonOptions options) { - if (!INITIALIZED) { - throw new IllegalStateException("No compatible version of Gson is present on the classpath."); - } - - gsonJsonWriter = JSON_WRITER_CONSTRUCTOR.createJsonWriter(writer); - JSON_WRITER_SET_LENIENT.setLenient(gsonJsonWriter, options.isNonNumericNumbersSupported()); - } - - @Override - public JsonWriteContext getWriteContext() { - return context; - } - - @Override - public void close() throws IOException { - if (context != JsonWriteContext.COMPLETED) { - throw new IllegalStateException("Writing of the JSON object must be completed before the writer can be " - + "closed. Current writing state is '" + context.getWriteState() + "'."); - } - - flush(); - JSON_WRITER_CLOSE.close(gsonJsonWriter); - } - - @Override - public JsonWriter flush() throws IOException { - JSON_WRITER_FLUSH.flush(gsonJsonWriter); - return this; - } - - @Override - public JsonWriter writeStartObject() throws IOException { - context.validateToken(JsonToken.START_OBJECT); - - JSON_WRITER_BEGIN_OBJECT.beginObject(gsonJsonWriter); - - context = context.updateContext(JsonToken.START_OBJECT); - return this; - } - - @Override - public JsonWriter writeEndObject() throws IOException { - context.validateToken(JsonToken.END_OBJECT); - - JSON_WRITER_END_OBJECT.endObject(gsonJsonWriter); - - context = context.updateContext(JsonToken.END_OBJECT); - return this; - } - - @Override - public JsonWriter writeStartArray() throws IOException { - context.validateToken(JsonToken.START_ARRAY); - - JSON_WRITER_BEGIN_ARRAY.beginArray(gsonJsonWriter); - - context = context.updateContext(JsonToken.START_ARRAY); - return this; - } - - @Override - public JsonWriter writeEndArray() throws IOException { - context.validateToken(JsonToken.END_ARRAY); - - JSON_WRITER_END_ARRAY.endArray(gsonJsonWriter); - - context = context.updateContext(JsonToken.END_ARRAY); - return this; - } - - @Override - public JsonWriter writeFieldName(String fieldName) throws IOException { - Objects.requireNonNull(fieldName, "'fieldName cannot be null."); - context.validateToken(JsonToken.FIELD_NAME); - - JSON_WRITER_NAME.name(gsonJsonWriter, fieldName); - - context = context.updateContext(JsonToken.FIELD_NAME); - return this; - } - - @Override - public JsonWriter writeBinary(byte[] value) throws IOException { - context.validateToken(JsonToken.STRING); - - if (value == null) { - JSON_WRITER_NULL_VALUE.nullValue(gsonJsonWriter); - } else { - JSON_WRITER_STRING_VALUE.value(gsonJsonWriter, Base64.getEncoder().encodeToString(value)); - } - - context = context.updateContext(JsonToken.STRING); - return this; - } - - @Override - public JsonWriter writeBoolean(boolean value) throws IOException { - context.validateToken(JsonToken.BOOLEAN); - - JSON_WRITER_BOOLEAN_VALUE.value(gsonJsonWriter, value); - - context = context.updateContext(JsonToken.BOOLEAN); - return this; - } - - @Override - public JsonWriter writeDouble(double value) throws IOException { - context.validateToken(JsonToken.NUMBER); - - JSON_WRITER_DOUBLE_VALUE.value(gsonJsonWriter, value); - - context = context.updateContext(JsonToken.NUMBER); - return this; - } - - @Override - public JsonWriter writeFloat(float value) throws IOException { - return writeDouble(value); - } - - @Override - public JsonWriter writeInt(int value) throws IOException { - return writeLong(value); - } - - @Override - public JsonWriter writeLong(long value) throws IOException { - context.validateToken(JsonToken.NUMBER); - - JSON_WRITER_LONG_VALUE.value(gsonJsonWriter, value); - - context = context.updateContext(JsonToken.NUMBER); - return this; - } - - @Override - public JsonWriter writeNull() throws IOException { - context.validateToken(JsonToken.NULL); - - JSON_WRITER_NULL_VALUE.nullValue(gsonJsonWriter); - - context = context.updateContext(JsonToken.NULL); - return this; - } - - @Override - public JsonWriter writeString(String value) throws IOException { - context.validateToken(JsonToken.STRING); - - JSON_WRITER_STRING_VALUE.value(gsonJsonWriter, value); - - context = context.updateContext(JsonToken.STRING); - return this; - } - - @Override - public JsonWriter writeRawValue(String value) throws IOException { - Objects.requireNonNull(value, "'value' cannot be null."); - context.validateToken(JsonToken.STRING); - - JSON_WRITER_RAW_VALUE.jsonValue(gsonJsonWriter, value); - - context = context.updateContext(JsonToken.STRING); - return this; - } - - @FunctionalInterface - private interface JsonWriterConstructor { - Object createJsonWriter(Writer writer); - } - - @FunctionalInterface - private interface JsonWriterSetLenient { - void setLenient(Object jsonWriter, boolean lenient); - } - - @FunctionalInterface - private interface JsonWriterClose { - void close(Object jsonWriter) throws IOException; - } - - @FunctionalInterface - private interface JsonWriterFlush { - void flush(Object jsonWriter) throws IOException; - } - - @FunctionalInterface - private interface JsonWriterBeginObject { - Object beginObject(Object jsonWriter) throws IOException; - } - - @FunctionalInterface - private interface JsonWriterEndObject { - Object endObject(Object jsonWriter) throws IOException; - } - - @FunctionalInterface - private interface JsonWriterBeginArray { - Object beginArray(Object jsonWriter) throws IOException; - } - - @FunctionalInterface - private interface JsonWriterEndArray { - Object endArray(Object jsonWriter) throws IOException; - } - - @FunctionalInterface - private interface JsonWriterNullValue { - Object nullValue(Object jsonWriter) throws IOException; - } - - @FunctionalInterface - private interface JsonWriterName { - Object name(Object jsonWriter, String name) throws IOException; - } - - @FunctionalInterface - private interface JsonWriterStringValue { - Object value(Object jsonWriter, String value) throws IOException; - } - - @FunctionalInterface - private interface JsonWriterBooleanValue { - Object value(Object jsonWriter, boolean value) throws IOException; - } - - @FunctionalInterface - private interface JsonWriterLongValue { - Object value(Object jsonWriter, long value) throws IOException; - } - - @FunctionalInterface - private interface JsonWriterDoubleValue { - Object value(Object jsonWriter, double value) throws IOException; - } - - @FunctionalInterface - private interface JsonWriterRawValue { - Object jsonValue(Object jsonWriter, String value) throws IOException; - } -} diff --git a/sdk/serialization/azure-json-reflect/src/main/java/com/azure/json/reflect/JacksonJsonProvider.java b/sdk/serialization/azure-json-reflect/src/main/java/com/azure/json/reflect/JacksonJsonProvider.java deleted file mode 100644 index 6e4ac2ee43fe..000000000000 --- a/sdk/serialization/azure-json-reflect/src/main/java/com/azure/json/reflect/JacksonJsonProvider.java +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.json.reflect; - -import com.azure.json.JsonOptions; -import com.azure.json.JsonProvider; -import com.azure.json.JsonReader; -import com.azure.json.JsonWriter; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; -import java.io.Writer; - -class JacksonJsonProvider implements JsonProvider { - static final boolean INITIALIZED = JacksonJsonReader.INITIALIZED && JacksonJsonWriter.INITIALIZED; - - @Override - public JsonReader createReader(byte[] json, JsonOptions options) throws IOException { - return JacksonJsonReader.fromBytes(json, options); - } - - @Override - public JsonReader createReader(String json, JsonOptions options) throws IOException { - return JacksonJsonReader.fromString(json, options); - } - - @Override - public JsonReader createReader(InputStream json, JsonOptions options) throws IOException { - return JacksonJsonReader.fromStream(json, options); - } - - @Override - public JsonReader createReader(Reader json, JsonOptions options) throws IOException { - return JacksonJsonReader.fromReader(json, options); - } - - @Override - public JsonWriter createWriter(OutputStream json, JsonOptions options) throws IOException { - return JacksonJsonWriter.toStream(json, options); - } - - @Override - public JsonWriter createWriter(Writer json, JsonOptions options) throws IOException { - return JacksonJsonWriter.toWriter(json, options); - } -} diff --git a/sdk/serialization/azure-json-reflect/src/main/java/com/azure/json/reflect/JacksonJsonReader.java b/sdk/serialization/azure-json-reflect/src/main/java/com/azure/json/reflect/JacksonJsonReader.java deleted file mode 100644 index a85fe71f68aa..000000000000 --- a/sdk/serialization/azure-json-reflect/src/main/java/com/azure/json/reflect/JacksonJsonReader.java +++ /dev/null @@ -1,411 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.json.reflect; - -import com.azure.json.JsonOptions; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringReader; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; - -import static java.lang.invoke.MethodType.methodType; -import static com.azure.json.reflect.MetaFactoryFactory.createMetaFactory; - -final class JacksonJsonReader extends JsonReader { - private static final Class JACKSON_JSON_TOKEN; - private static final Object ALLOW_NAN_MAPPED; - private static final Object JSON_FACTORY; - - private static final JsonFactoryCreateJsonParser JSON_FACTORY_CREATE_JSON_PARSER; - private static final JsonParserConfigure JSON_PARSER_CONFIGURE; - private static final JsonParserClose JSON_PARSER_CLOSE; - private static final JsonParserSkipChildren JSON_PARSER_SKIP_CHILDREN; - private static final JsonParserNextToken JSON_PARSER_NEXT_TOKEN; - private static final JsonParserCurrentName JSON_PARSER_CURRENT_NAME; - private static final JsonParserGetValueAsString JSON_PARSER_GET_VALUE_AS_STRING; - private static final JsonParserGetBinaryValue JSON_PARSER_GET_BINARY_VALUE; - private static final JsonParserGetBooleanValue JSON_PARSER_GET_BOOLEAN_VALUE; - private static final JsonParserGetIntValue JSON_PARSER_GET_INT_VALUE; - private static final JsonParserGetLongValue JSON_PARSER_GET_LONG_VALUE; - private static final JsonParserGetFloatValue JSON_PARSER_GET_FLOAT_VALUE; - private static final JsonParserGetDoubleValue JSON_PARSER_GET_DOUBLE_VALUE; - - static final boolean INITIALIZED; - - static { - final MethodHandles.Lookup lookup = MethodHandles.lookup(); - - Class jacksonJsonToken = null; - - Object allowNaNMapped = null; - Object jsonFactory = null; - - JsonFactoryCreateJsonParser jsonFactoryCreateJsonParser = null; - JsonParserConfigure jsonParserConfigure = null; - JsonParserClose jsonParserClose = null; - JsonParserSkipChildren jsonParserSkipChildren = null; - JsonParserNextToken jsonParserNextToken = null; - JsonParserCurrentName jsonParserCurrentName = null; - JsonParserGetValueAsString jsonParserGetValueAsString = null; - JsonParserGetBinaryValue jsonParserGetBinaryValue = null; - JsonParserGetBooleanValue jsonParserGetBooleanValue = null; - JsonParserGetIntValue jsonParserGetIntValue = null; - JsonParserGetLongValue jsonParserGetLongValue = null; - JsonParserGetFloatValue jsonParserGetFloatValue = null; - JsonParserGetDoubleValue jsonParserGetDoubleValue = null; - - boolean initialized = false; - - try { - Class jacksonJsonFactoryClass = Class.forName("com.fasterxml.jackson.core.JsonFactory"); - Class jacksonJsonParserClass = Class.forName("com.fasterxml.jackson.core.JsonParser"); - - jacksonJsonToken = Class.forName("com.fasterxml.jackson.core.JsonToken"); - - // Get JsonParser.Feature enum value for allowing non-numeric numbers - Class jsonParserFeature = Arrays.stream(jacksonJsonParserClass.getDeclaredClasses()) - .filter(c -> "Feature".equals(c.getSimpleName())) - .findAny() - .orElse(null); - Class jsonReadFeature = Class.forName("com.fasterxml.jackson.core.json.JsonReadFeature"); - MethodHandle jsonReadFeatureMappedFeature - = lookup.findVirtual(jsonReadFeature, "mappedFeature", methodType(jsonParserFeature)); - MethodHandle jsonReadFeatureValueOf - = lookup.findStatic(jsonReadFeature, "valueOf", methodType(jsonReadFeature, String.class)); - allowNaNMapped - = jsonReadFeatureMappedFeature.invoke(jsonReadFeatureValueOf.invoke("ALLOW_NON_NUMERIC_NUMBERS")); - - jsonFactory = lookup.findConstructor(jacksonJsonFactoryClass, methodType(void.class)).invoke(); - - jsonFactoryCreateJsonParser = createMetaFactory("createParser", jacksonJsonFactoryClass, - methodType(jacksonJsonParserClass, Reader.class), JsonFactoryCreateJsonParser.class, - methodType(Object.class, Object.class, Reader.class), lookup); - jsonParserConfigure = createMetaFactory("configure", jacksonJsonParserClass, - methodType(jacksonJsonParserClass, jsonParserFeature, boolean.class), JsonParserConfigure.class, - methodType(Object.class, Object.class, Object.class, boolean.class), lookup); - jsonParserClose = createMetaFactory("close", jacksonJsonParserClass, methodType(void.class), - JsonParserClose.class, methodType(void.class, Object.class), lookup); - jsonParserSkipChildren - = createMetaFactory("skipChildren", jacksonJsonParserClass, methodType(jacksonJsonParserClass), - JsonParserSkipChildren.class, methodType(Object.class, Object.class), lookup); - jsonParserNextToken = createMetaFactory("nextToken", jacksonJsonParserClass, methodType(jacksonJsonToken), - JsonParserNextToken.class, methodType(Object.class, Object.class), lookup); - jsonParserCurrentName = createMetaFactory("currentName", jacksonJsonParserClass, methodType(String.class), - JsonParserCurrentName.class, methodType(String.class, Object.class), lookup); - jsonParserGetValueAsString - = createMetaFactory("getValueAsString", jacksonJsonParserClass, methodType(String.class), - JsonParserGetValueAsString.class, methodType(String.class, Object.class), lookup); - jsonParserGetBinaryValue - = createMetaFactory("getBinaryValue", jacksonJsonParserClass, methodType(byte[].class), - JsonParserGetBinaryValue.class, methodType(byte[].class, Object.class), lookup); - jsonParserGetBooleanValue - = createMetaFactory("getBooleanValue", jacksonJsonParserClass, methodType(boolean.class), - JsonParserGetBooleanValue.class, methodType(boolean.class, Object.class), lookup); - jsonParserGetIntValue = createMetaFactory("getIntValue", jacksonJsonParserClass, methodType(int.class), - JsonParserGetIntValue.class, methodType(int.class, Object.class), lookup); - jsonParserGetLongValue = createMetaFactory("getLongValue", jacksonJsonParserClass, methodType(long.class), - JsonParserGetLongValue.class, methodType(long.class, Object.class), lookup); - jsonParserGetFloatValue = createMetaFactory("getFloatValue", jacksonJsonParserClass, - methodType(float.class), JsonParserGetFloatValue.class, methodType(float.class, Object.class), lookup); - jsonParserGetDoubleValue - = createMetaFactory("getDoubleValue", jacksonJsonParserClass, methodType(double.class), - JsonParserGetDoubleValue.class, methodType(double.class, Object.class), lookup); - - initialized = true; - } catch (Throwable e) { - if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } else if (e instanceof Error) { - throw (Error) e; - } - } - - JACKSON_JSON_TOKEN = jacksonJsonToken; - ALLOW_NAN_MAPPED = allowNaNMapped; - JSON_FACTORY = jsonFactory; - - JSON_FACTORY_CREATE_JSON_PARSER = jsonFactoryCreateJsonParser; - JSON_PARSER_CONFIGURE = jsonParserConfigure; - JSON_PARSER_CLOSE = jsonParserClose; - JSON_PARSER_SKIP_CHILDREN = jsonParserSkipChildren; - JSON_PARSER_NEXT_TOKEN = jsonParserNextToken; - JSON_PARSER_CURRENT_NAME = jsonParserCurrentName; - JSON_PARSER_GET_VALUE_AS_STRING = jsonParserGetValueAsString; - JSON_PARSER_GET_BINARY_VALUE = jsonParserGetBinaryValue; - JSON_PARSER_GET_BOOLEAN_VALUE = jsonParserGetBooleanValue; - JSON_PARSER_GET_INT_VALUE = jsonParserGetIntValue; - JSON_PARSER_GET_LONG_VALUE = jsonParserGetLongValue; - JSON_PARSER_GET_FLOAT_VALUE = jsonParserGetFloatValue; - JSON_PARSER_GET_DOUBLE_VALUE = jsonParserGetDoubleValue; - - INITIALIZED = initialized; - } - - private final Object jacksonJsonParser; - private JsonToken currentToken; - - private final byte[] jsonBytes; - private final String jsonString; - private final boolean resetSupported; - private final boolean nonNumericNumbersSupported; - - static JsonReader fromBytes(byte[] json, JsonOptions options) throws IOException { - return new JacksonJsonReader(new InputStreamReader(new ByteArrayInputStream(json), StandardCharsets.UTF_8), - true, json, null, options); - } - - static JsonReader fromString(String json, JsonOptions options) throws IOException { - return new JacksonJsonReader(new StringReader(json), true, null, json, options); - } - - static JsonReader fromStream(InputStream json, JsonOptions options) throws IOException { - return new JacksonJsonReader(new InputStreamReader(json, StandardCharsets.UTF_8), false, null, null, options); - } - - static JsonReader fromReader(Reader reader, JsonOptions options) throws IOException { - return new JacksonJsonReader(reader, reader.markSupported(), null, null, options); - } - - private JacksonJsonReader(Reader reader, boolean resetSupported, byte[] jsonBytes, String jsonString, - JsonOptions options) throws IOException { - this(reader, resetSupported, jsonBytes, jsonString, options.isNonNumericNumbersSupported()); - } - - private JacksonJsonReader(Reader reader, boolean resetSupported, byte[] jsonBytes, String jsonString, - boolean nonNumericNumbersSupported) throws IOException { - if (!INITIALIZED) { - throw new IllegalStateException("No compatible version of Jackson is present on the classpath."); - } - - jacksonJsonParser = JSON_FACTORY_CREATE_JSON_PARSER.createParser(JSON_FACTORY, reader); - // Configure Jackson to support non-numeric numbers - JSON_PARSER_CONFIGURE.configure(jacksonJsonParser, ALLOW_NAN_MAPPED, nonNumericNumbersSupported); - - this.resetSupported = resetSupported; - this.jsonBytes = jsonBytes; - this.jsonString = jsonString; - this.nonNumericNumbersSupported = nonNumericNumbersSupported; - } - - @Override - public JsonToken currentToken() { - return currentToken; - } - - @Override - public JsonToken nextToken() throws IOException { - currentToken = mapToken((Enum) JSON_PARSER_NEXT_TOKEN.nextToken(jacksonJsonParser)); - return currentToken; - } - - @Override - public byte[] getBinary() throws IOException { - // GetBinaryValue cannot handle a Null token - if (currentToken() == JsonToken.NULL) { - return null; - } - - return JSON_PARSER_GET_BINARY_VALUE.getBinaryValue(jacksonJsonParser); - } - - @Override - public boolean getBoolean() throws IOException { - return JSON_PARSER_GET_BOOLEAN_VALUE.getBooleanValue(jacksonJsonParser); - } - - @Override - public float getFloat() throws IOException { - return JSON_PARSER_GET_FLOAT_VALUE.getFloatValue(jacksonJsonParser); - } - - @Override - public double getDouble() throws IOException { - return JSON_PARSER_GET_DOUBLE_VALUE.getDoubleValue(jacksonJsonParser); - } - - @Override - public int getInt() throws IOException { - return JSON_PARSER_GET_INT_VALUE.getIntValue(jacksonJsonParser); - } - - @Override - public long getLong() throws IOException { - return JSON_PARSER_GET_LONG_VALUE.getLongValue(jacksonJsonParser); - } - - @Override - public String getString() throws IOException { - return JSON_PARSER_GET_VALUE_AS_STRING.getValueAsString(jacksonJsonParser); - } - - @Override - public String getFieldName() throws IOException { - return JSON_PARSER_CURRENT_NAME.currentName(jacksonJsonParser); - } - - @Override - public void skipChildren() throws IOException { - JSON_PARSER_SKIP_CHILDREN.skipChildren(jacksonJsonParser); - } - - @Override - public JsonReader bufferObject() throws IOException { - JsonToken currentToken = currentToken(); - if (currentToken == JsonToken.START_OBJECT || currentToken == JsonToken.FIELD_NAME) { - String json = readRemainingFieldsAsJsonObject(); - return new JacksonJsonReader(new StringReader(json), true, null, json, nonNumericNumbersSupported); - } else { - throw new IllegalStateException("Cannot buffer a JSON object from a non-object, non-field name " - + "starting location. Starting location: " + currentToken()); - } - } - - @Override - public boolean isResetSupported() { - return this.resetSupported; - } - - @Override - public JsonReader reset() throws IOException { - if (!resetSupported) { - throw new IllegalStateException("'reset' isn't supported by this JsonReader."); - } - - if (jsonBytes != null) { - return new JacksonJsonReader( - new InputStreamReader(new ByteArrayInputStream(jsonBytes), StandardCharsets.UTF_8), true, jsonBytes, - null, nonNumericNumbersSupported); - } else { - return new JacksonJsonReader(new StringReader(jsonString), true, null, jsonString, - nonNumericNumbersSupported); - } - } - - @Override - public void close() throws IOException { - JSON_PARSER_CLOSE.close(jacksonJsonParser); - } - - /* - * Maps the Jackson JsonToken to azure-json JsonToken - */ - private JsonToken mapToken(Enum token) { - if (token == null) { - return null; - } - - // Check token is Jackson token - if (token.getClass() != JACKSON_JSON_TOKEN) { - throw new IllegalStateException("Unsupported enum, pass a Jackson JsonToken"); - } - - switch (token.name()) { - case "START_OBJECT": - return JsonToken.START_OBJECT; - - case "END_OBJECT": - return JsonToken.END_OBJECT; - - case "START_ARRAY": - return JsonToken.START_ARRAY; - - case "END_ARRAY": - return JsonToken.END_ARRAY; - - case "FIELD_NAME": - return JsonToken.FIELD_NAME; - - case "VALUE_STRING": - return JsonToken.STRING; - - case "VALUE_NUMBER_INT": - case "VALUE_NUMBER_FLOAT": - return JsonToken.NUMBER; - - case "VALUE_TRUE": - case "VALUE_FALSE": - return JsonToken.BOOLEAN; - - case "VALUE_NULL": - return JsonToken.NULL; - - default: - throw new IllegalStateException("Unsupported token type: '" + token + "'."); - } - } - - @FunctionalInterface - private interface JsonFactoryCreateJsonParser { - Object createParser(Object jsonFactory, Reader reader) throws IOException; - } - - @FunctionalInterface - private interface JsonParserConfigure { - Object configure(Object jsonParser, Object feature, boolean state); - } - - @FunctionalInterface - private interface JsonParserClose { - void close(Object jsonParser) throws IOException; - } - - @FunctionalInterface - private interface JsonParserSkipChildren { - Object skipChildren(Object jsonParser) throws IOException; - } - - @FunctionalInterface - private interface JsonParserNextToken { - Object nextToken(Object jsonParser) throws IOException; - } - - @FunctionalInterface - private interface JsonParserCurrentName { - String currentName(Object jsonParser) throws IOException; - } - - @FunctionalInterface - private interface JsonParserGetValueAsString { - String getValueAsString(Object jsonParser) throws IOException; - } - - @FunctionalInterface - private interface JsonParserGetBinaryValue { - byte[] getBinaryValue(Object jsonParser) throws IOException; - } - - @FunctionalInterface - private interface JsonParserGetBooleanValue { - boolean getBooleanValue(Object jsonParser) throws IOException; - } - - @FunctionalInterface - private interface JsonParserGetIntValue { - int getIntValue(Object jsonParser) throws IOException; - } - - @FunctionalInterface - private interface JsonParserGetLongValue { - long getLongValue(Object jsonParser) throws IOException; - } - - @FunctionalInterface - private interface JsonParserGetFloatValue { - float getFloatValue(Object jsonParser) throws IOException; - } - - @FunctionalInterface - private interface JsonParserGetDoubleValue { - double getDoubleValue(Object jsonParser) throws IOException; - } -} diff --git a/sdk/serialization/azure-json-reflect/src/main/java/com/azure/json/reflect/JacksonJsonWriter.java b/sdk/serialization/azure-json-reflect/src/main/java/com/azure/json/reflect/JacksonJsonWriter.java deleted file mode 100644 index d6312c8fe871..000000000000 --- a/sdk/serialization/azure-json-reflect/src/main/java/com/azure/json/reflect/JacksonJsonWriter.java +++ /dev/null @@ -1,431 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.json.reflect; - -import com.azure.json.JsonOptions; -import com.azure.json.JsonWriteContext; -import com.azure.json.JsonWriter; -import com.azure.json.JsonToken; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; -import java.lang.invoke.MethodType; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Objects; - -import static java.lang.invoke.MethodType.methodType; -import static com.azure.json.reflect.MetaFactoryFactory.createMetaFactory; - -final class JacksonJsonWriter extends JsonWriter { - private static final Object ALLOW_NAN_MAPPED; - private static final Object JSON_FACTORY; - - private static final JsonFactoryCreateJsonGenerator JSON_FACTORY_CREATE_JSON_GENERATOR; - private static final JsonGeneratorWriteRawValue JSON_GENERATOR_WRITE_RAW_VALUE; - private static final JsonGeneratorFlush JSON_GENERATOR_FLUSH; - private static final JsonGeneratorClose JSON_GENERATOR_CLOSE; - private static final JsonGeneratorWriteStartObject JSON_GENERATOR_WRITE_START_OBJECT; - private static final JsonGeneratorWriteEndObject JSON_GENERATOR_WRITE_END_OBJECT; - private static final JsonGeneratorWriteStartArray JSON_GENERATOR_WRITE_START_ARRAY; - private static final JsonGeneratorWriteEndArray JSON_GENERATOR_WRITE_END_ARRAY; - private static final JsonGeneratorWriteFieldName JSON_GENERATOR_WRITE_FIELD_NAME; - private static final JsonGeneratorWriteNull JSON_GENERATOR_WRITE_NULL; - private static final JsonGeneratorWriteBinary JSON_GENERATOR_WRITE_BINARY; - private static final JsonGeneratorWriteBoolean JSON_GENERATOR_WRITE_BOOLEAN; - private static final JsonGeneratorWriteDouble JSON_GENERATOR_WRITE_DOUBLE; - private static final JsonGeneratorWriteFloat JSON_GENERATOR_WRITE_FLOAT; - private static final JsonGeneratorWriteInt JSON_GENERATOR_WRITE_INT; - private static final JsonGeneratorWriteLong JSON_GENERATOR_WRITE_LONG; - private static final JsonGeneratorWriteString JSON_GENERATOR_WRITE_STRING; - private static final JsonGeneratorConfigure JSON_GENERATOR_CONFIGURE; - - static final boolean INITIALIZED; - - static { - MethodHandles.Lookup lookup = MethodHandles.lookup(); - - Object allowNaNMapped = null; - Object jsonFactory = null; - - JsonFactoryCreateJsonGenerator jsonFactoryCreateJsonGenerator = null; - JsonGeneratorWriteRawValue jsonGeneratorWriteRawValue = null; - JsonGeneratorFlush jsonGeneratorFlush = null; - JsonGeneratorClose jsonGeneratorClose = null; - JsonGeneratorWriteStartObject jsonGeneratorWriteStartObject = null; - JsonGeneratorWriteEndObject jsonGeneratorWriteEndObject = null; - JsonGeneratorWriteStartArray jsonGeneratorWriteStartArray = null; - JsonGeneratorWriteEndArray jsonGeneratorWriteEndArray = null; - JsonGeneratorWriteFieldName jsonGeneratorWriteFieldName = null; - JsonGeneratorWriteNull jsonGeneratorWriteNull = null; - JsonGeneratorWriteBinary jsonGeneratorWriteBinary = null; - JsonGeneratorWriteBoolean jsonGeneratorWriteBoolean = null; - JsonGeneratorWriteDouble jsonGeneratorWriteDouble = null; - JsonGeneratorWriteFloat jsonGeneratorWriteFloat = null; - JsonGeneratorWriteInt jsonGeneratorWriteInt = null; - JsonGeneratorWriteLong jsonGeneratorWriteLong = null; - JsonGeneratorWriteString jsonGeneratorWriteString = null; - JsonGeneratorConfigure jsonGeneratorConfigure = null; - - boolean initialized = false; - - try { - Class jacksonJsonFactoryClass = Class.forName("com.fasterxml.jackson.core.JsonFactory"); - Class jacksonJsonGeneratorClass = Class.forName("com.fasterxml.jackson.core.JsonGenerator"); - - // Get JsonGenerator.Feature enum value for allowing non-numeric numbers - Class jsonGeneratorFeature = Arrays.stream(jacksonJsonGeneratorClass.getDeclaredClasses()) - .filter(c -> "Feature".equals(c.getSimpleName())) - .findAny() - .orElse(null); - Class jsonWriteFeature = Class.forName("com.fasterxml.jackson.core.json.JsonWriteFeature"); - MethodHandle jsonWriteFeatureMappedFeature - = lookup.findVirtual(jsonWriteFeature, "mappedFeature", methodType(jsonGeneratorFeature)); - MethodHandle jsonWriteFeatureValueOf - = lookup.findStatic(jsonWriteFeature, "valueOf", methodType(jsonWriteFeature, String.class)); - allowNaNMapped - = jsonWriteFeatureMappedFeature.invoke(jsonWriteFeatureValueOf.invoke("WRITE_NAN_AS_STRINGS")); - - jsonFactory = lookup.findConstructor(jacksonJsonFactoryClass, methodType(void.class)).invoke(); - - MethodType voidMT = methodType(void.class); - MethodType voidStringMt = methodType(void.class, String.class); - MethodType voidObjectMT = methodType(void.class, Object.class); - - jsonFactoryCreateJsonGenerator = createMetaFactory("createGenerator", jacksonJsonFactoryClass, - methodType(jacksonJsonGeneratorClass, Writer.class), JsonFactoryCreateJsonGenerator.class, - methodType(Object.class, Object.class, Writer.class), lookup); - jsonGeneratorWriteRawValue = createMetaFactory("writeRawValue", jacksonJsonGeneratorClass, voidStringMt, - JsonGeneratorWriteRawValue.class, methodType(void.class, Object.class, String.class), lookup); - jsonGeneratorFlush = createMetaFactory("flush", jacksonJsonGeneratorClass, voidMT, JsonGeneratorFlush.class, - voidObjectMT, lookup); - jsonGeneratorClose = createMetaFactory("close", jacksonJsonGeneratorClass, voidMT, JsonGeneratorClose.class, - voidObjectMT, lookup); - jsonGeneratorWriteStartObject = createMetaFactory("writeStartObject", jacksonJsonGeneratorClass, voidMT, - JsonGeneratorWriteStartObject.class, voidObjectMT, lookup); - jsonGeneratorWriteEndObject = createMetaFactory("writeEndObject", jacksonJsonGeneratorClass, voidMT, - JsonGeneratorWriteEndObject.class, voidObjectMT, lookup); - jsonGeneratorWriteStartArray = createMetaFactory("writeStartArray", jacksonJsonGeneratorClass, voidMT, - JsonGeneratorWriteStartArray.class, voidObjectMT, lookup); - jsonGeneratorWriteEndArray = createMetaFactory("writeEndArray", jacksonJsonGeneratorClass, voidMT, - JsonGeneratorWriteEndArray.class, voidObjectMT, lookup); - jsonGeneratorWriteFieldName = createMetaFactory("writeFieldName", jacksonJsonGeneratorClass, voidStringMt, - JsonGeneratorWriteFieldName.class, methodType(void.class, Object.class, String.class), lookup); - jsonGeneratorWriteNull = createMetaFactory("writeNull", jacksonJsonGeneratorClass, voidMT, - JsonGeneratorWriteNull.class, voidObjectMT, lookup); - jsonGeneratorWriteBinary - = createMetaFactory("writeBinary", jacksonJsonGeneratorClass, methodType(void.class, byte[].class), - JsonGeneratorWriteBinary.class, methodType(void.class, Object.class, byte[].class), lookup); - jsonGeneratorWriteBoolean - = createMetaFactory("writeBoolean", jacksonJsonGeneratorClass, methodType(void.class, boolean.class), - JsonGeneratorWriteBoolean.class, methodType(void.class, Object.class, boolean.class), lookup); - jsonGeneratorWriteDouble - = createMetaFactory("writeNumber", jacksonJsonGeneratorClass, methodType(void.class, double.class), - JsonGeneratorWriteDouble.class, methodType(void.class, Object.class, double.class), lookup); - jsonGeneratorWriteFloat - = createMetaFactory("writeNumber", jacksonJsonGeneratorClass, methodType(void.class, float.class), - JsonGeneratorWriteFloat.class, methodType(void.class, Object.class, float.class), lookup); - jsonGeneratorWriteInt - = createMetaFactory("writeNumber", jacksonJsonGeneratorClass, methodType(void.class, int.class), - JsonGeneratorWriteInt.class, methodType(void.class, Object.class, int.class), lookup); - jsonGeneratorWriteLong - = createMetaFactory("writeNumber", jacksonJsonGeneratorClass, methodType(void.class, long.class), - JsonGeneratorWriteLong.class, methodType(void.class, Object.class, long.class), lookup); - jsonGeneratorWriteString = createMetaFactory("writeString", jacksonJsonGeneratorClass, voidStringMt, - JsonGeneratorWriteString.class, methodType(void.class, Object.class, String.class), lookup); - jsonGeneratorConfigure = createMetaFactory("configure", jacksonJsonGeneratorClass, - methodType(jacksonJsonGeneratorClass, jsonGeneratorFeature, boolean.class), - JsonGeneratorConfigure.class, methodType(Object.class, Object.class, Object.class, boolean.class), - lookup); - - initialized = true; - } catch (Throwable e) { - if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } else if (e instanceof Error) { - throw (Error) e; - } - } - - ALLOW_NAN_MAPPED = allowNaNMapped; - JSON_FACTORY = jsonFactory; - - JSON_FACTORY_CREATE_JSON_GENERATOR = jsonFactoryCreateJsonGenerator; - JSON_GENERATOR_WRITE_RAW_VALUE = jsonGeneratorWriteRawValue; - JSON_GENERATOR_FLUSH = jsonGeneratorFlush; - JSON_GENERATOR_CLOSE = jsonGeneratorClose; - JSON_GENERATOR_WRITE_START_OBJECT = jsonGeneratorWriteStartObject; - JSON_GENERATOR_WRITE_END_OBJECT = jsonGeneratorWriteEndObject; - JSON_GENERATOR_WRITE_START_ARRAY = jsonGeneratorWriteStartArray; - JSON_GENERATOR_WRITE_END_ARRAY = jsonGeneratorWriteEndArray; - JSON_GENERATOR_WRITE_FIELD_NAME = jsonGeneratorWriteFieldName; - JSON_GENERATOR_WRITE_NULL = jsonGeneratorWriteNull; - JSON_GENERATOR_WRITE_BINARY = jsonGeneratorWriteBinary; - JSON_GENERATOR_WRITE_BOOLEAN = jsonGeneratorWriteBoolean; - JSON_GENERATOR_WRITE_DOUBLE = jsonGeneratorWriteDouble; - JSON_GENERATOR_WRITE_FLOAT = jsonGeneratorWriteFloat; - JSON_GENERATOR_WRITE_INT = jsonGeneratorWriteInt; - JSON_GENERATOR_WRITE_LONG = jsonGeneratorWriteLong; - JSON_GENERATOR_WRITE_STRING = jsonGeneratorWriteString; - JSON_GENERATOR_CONFIGURE = jsonGeneratorConfigure; - - INITIALIZED = initialized; - } - - private final Object jacksonGenerator; - JsonWriteContext context = JsonWriteContext.ROOT; - - static JsonWriter toStream(OutputStream json, JsonOptions options) throws IOException { - Objects.requireNonNull(json, "'json' cannot be null."); - return new JacksonJsonWriter(new OutputStreamWriter(json, StandardCharsets.UTF_8), options); - } - - static JsonWriter toWriter(Writer json, JsonOptions options) throws IOException { - Objects.requireNonNull(json, "'json' cannot be null."); - return new JacksonJsonWriter(json, options); - } - - private JacksonJsonWriter(Writer writer, JsonOptions options) throws IOException { - if (!INITIALIZED) { - throw new IllegalStateException("No compatible version of Jackson is present on the classpath."); - } - - jacksonGenerator = JSON_FACTORY_CREATE_JSON_GENERATOR.createGenerator(JSON_FACTORY, writer); - // Configure Jackson to support non-numeric numbers - JSON_GENERATOR_CONFIGURE.configure(jacksonGenerator, ALLOW_NAN_MAPPED, options.isNonNumericNumbersSupported()); - } - - @Override - public JsonWriteContext getWriteContext() { - return context; - } - - @Override - public void close() throws IOException { - if (context != JsonWriteContext.COMPLETED) { - throw new IllegalStateException("Writing of the JSON object must be completed before the writer can be " - + "closed. Current writing state is '" + context.getWriteState() + "'."); - } - JSON_GENERATOR_CLOSE.close(jacksonGenerator); - } - - @Override - public JsonWriter flush() throws IOException { - JSON_GENERATOR_FLUSH.flush(jacksonGenerator); - return this; - } - - @Override - public JsonWriter writeStartObject() throws IOException { - context.validateToken(JsonToken.START_OBJECT); - JSON_GENERATOR_WRITE_START_OBJECT.writeStartObject(jacksonGenerator); - context = context.updateContext(JsonToken.START_OBJECT); - return this; - } - - @Override - public JsonWriter writeEndObject() throws IOException { - context.validateToken(JsonToken.END_OBJECT); - JSON_GENERATOR_WRITE_END_OBJECT.writeEndObject(jacksonGenerator); - context = context.updateContext(JsonToken.END_OBJECT); - return this; - } - - @Override - public JsonWriter writeStartArray() throws IOException { - context.validateToken(JsonToken.START_ARRAY); - JSON_GENERATOR_WRITE_START_ARRAY.writeStartArray(jacksonGenerator); - context = context.updateContext(JsonToken.START_ARRAY); - return this; - } - - @Override - public JsonWriter writeEndArray() throws IOException { - context.validateToken(JsonToken.END_ARRAY); - JSON_GENERATOR_WRITE_END_ARRAY.writeEndArray(jacksonGenerator); - context = context.updateContext(JsonToken.END_ARRAY); - return this; - } - - @Override - public JsonWriter writeFieldName(String fieldName) throws IOException { - Objects.requireNonNull(fieldName, "'fieldName' cannot be null."); - context.validateToken(JsonToken.FIELD_NAME); - JSON_GENERATOR_WRITE_FIELD_NAME.writeFieldName(jacksonGenerator, fieldName); - context = context.updateContext(JsonToken.FIELD_NAME); - return this; - } - - @Override - public JsonWriter writeBinary(byte[] value) throws IOException { - context.validateToken(JsonToken.STRING); - if (value == null) { - JSON_GENERATOR_WRITE_NULL.writeNull(jacksonGenerator); - } else { - JSON_GENERATOR_WRITE_BINARY.writeBinary(jacksonGenerator, value); - } - context = context.updateContext(JsonToken.STRING); - return this; - } - - @Override - public JsonWriter writeBoolean(boolean value) throws IOException { - context.validateToken(JsonToken.BOOLEAN); - JSON_GENERATOR_WRITE_BOOLEAN.writeBoolean(jacksonGenerator, value); - context = context.updateContext(JsonToken.BOOLEAN); - return this; - } - - @Override - public JsonWriter writeDouble(double value) throws IOException { - context.validateToken(JsonToken.NUMBER); - JSON_GENERATOR_WRITE_DOUBLE.writeNumber(jacksonGenerator, value); - context = context.updateContext(JsonToken.NUMBER); - return this; - } - - @Override - public JsonWriter writeFloat(float value) throws IOException { - context.validateToken(JsonToken.NUMBER); - JSON_GENERATOR_WRITE_FLOAT.writeNumber(jacksonGenerator, value); - context = context.updateContext(JsonToken.NUMBER); - return this; - } - - @Override - public JsonWriter writeInt(int value) throws IOException { - context.validateToken(JsonToken.NUMBER); - JSON_GENERATOR_WRITE_INT.writeNumber(jacksonGenerator, value); - context = context.updateContext(JsonToken.NUMBER); - return this; - } - - @Override - public JsonWriter writeLong(long value) throws IOException { - context.validateToken(JsonToken.NUMBER); - JSON_GENERATOR_WRITE_LONG.writeNumber(jacksonGenerator, value); - context = context.updateContext(JsonToken.NUMBER); - return this; - } - - @Override - public JsonWriter writeNull() throws IOException { - context.validateToken(JsonToken.NULL); - JSON_GENERATOR_WRITE_NULL.writeNull(jacksonGenerator); - context = context.updateContext(JsonToken.NULL); - return this; - } - - @Override - public JsonWriter writeString(String value) throws IOException { - context.validateToken(JsonToken.STRING); - JSON_GENERATOR_WRITE_STRING.writeString(jacksonGenerator, value); - context = context.updateContext(JsonToken.STRING); - return this; - } - - @Override - public JsonWriter writeRawValue(String value) throws IOException { - Objects.requireNonNull(value, "'value' cannot be null."); - context.validateToken(JsonToken.STRING); - JSON_GENERATOR_WRITE_RAW_VALUE.writeRawValue(jacksonGenerator, value); - context = context.updateContext(JsonToken.STRING); - return this; - } - - @FunctionalInterface - private interface JsonFactoryCreateJsonGenerator { - Object createGenerator(Object jsonFactory, Writer writer) throws IOException; - } - - @FunctionalInterface - private interface JsonGeneratorWriteRawValue { - void writeRawValue(Object jsonWriter, String value) throws IOException; - } - - @FunctionalInterface - private interface JsonGeneratorFlush { - void flush(Object jsonWriter) throws IOException; - } - - @FunctionalInterface - private interface JsonGeneratorClose { - void close(Object jsonWriter) throws IOException; - } - - @FunctionalInterface - private interface JsonGeneratorWriteStartObject { - void writeStartObject(Object jsonWriter) throws IOException; - } - - @FunctionalInterface - private interface JsonGeneratorWriteEndObject { - void writeEndObject(Object jsonWriter) throws IOException; - } - - @FunctionalInterface - private interface JsonGeneratorWriteStartArray { - void writeStartArray(Object jsonWriter) throws IOException; - } - - @FunctionalInterface - private interface JsonGeneratorWriteEndArray { - void writeEndArray(Object jsonWriter) throws IOException; - } - - @FunctionalInterface - private interface JsonGeneratorWriteFieldName { - void writeFieldName(Object jsonWriter, String fieldName) throws IOException; - } - - @FunctionalInterface - private interface JsonGeneratorWriteNull { - void writeNull(Object jsonWriter) throws IOException; - } - - @FunctionalInterface - private interface JsonGeneratorWriteBinary { - void writeBinary(Object jsonWriter, byte[] value) throws IOException; - } - - @FunctionalInterface - private interface JsonGeneratorWriteBoolean { - void writeBoolean(Object jsonWriter, boolean value) throws IOException; - } - - @FunctionalInterface - private interface JsonGeneratorWriteDouble { - void writeNumber(Object jsonWriter, double value) throws IOException; - } - - @FunctionalInterface - private interface JsonGeneratorWriteFloat { - void writeNumber(Object jsonWriter, float value) throws IOException; - } - - @FunctionalInterface - private interface JsonGeneratorWriteInt { - void writeNumber(Object jsonWriter, int value) throws IOException; - } - - @FunctionalInterface - private interface JsonGeneratorWriteLong { - void writeNumber(Object jsonWriter, long value) throws IOException; - } - - @FunctionalInterface - private interface JsonGeneratorWriteString { - void writeString(Object jsonWriter, String value) throws IOException; - } - - @FunctionalInterface - private interface JsonGeneratorConfigure { - Object configure(Object jsonWriter, Object featureEnum, boolean options); - } - -} diff --git a/sdk/serialization/azure-json-reflect/src/main/java/com/azure/json/reflect/JsonProviderFactory.java b/sdk/serialization/azure-json-reflect/src/main/java/com/azure/json/reflect/JsonProviderFactory.java deleted file mode 100644 index 1e54903f75fa..000000000000 --- a/sdk/serialization/azure-json-reflect/src/main/java/com/azure/json/reflect/JsonProviderFactory.java +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.json.reflect; - -import com.azure.json.JsonProvider; -import com.azure.json.JsonReader; -import com.azure.json.JsonWriter; - -/** - * The main factory class of Azure Json Reflect package, used to - * construct {@link JsonProvider} instances. - *

        - * Returned {@link JsonProvider} instances create instances of - * {@link JsonReader} and {@link JsonWriter} that reflectively - * search for either Jackson or Gson on the class path and - * provide abstractions of these libraries without having any - * hard dependencies on them. - * - * @author Jack Sandford - */ -public final class JsonProviderFactory { - private static JsonProvider jacksonJsonProvider = null; - private static JsonProvider gsonJsonProvider = null; - - private JsonProviderFactory() { - throw new UnsupportedOperationException(); - } - - /** - * Constructs a singleton instance of {@link JsonProvider} prioritizing Jackson over Gson. - * - * @return An instance of {@link JsonProvider}. - * @throws IllegalStateException If no compatible versions of Jackson or Gson are present on the classpath. - */ - public static JsonProvider getJsonProvider() { - if (JacksonJsonProvider.INITIALIZED) { - return getJacksonJsonProvider(); - } else if (GsonJsonProvider.INITIALIZED) { - return getGsonJsonProvider(); - } - - throw new IllegalStateException("No compatible versions of Jackson or Gson are present on the classpath."); - } - - /** - * Constructs a singleton instance of {@link JsonProvider} that uses Jackson. - * - * @return An instance of {@link JsonProvider}. - * @throws IllegalStateException If no compatible version of Jackson is present on the classpath. - */ - public static synchronized JsonProvider getJacksonJsonProvider() { - if (!JacksonJsonProvider.INITIALIZED) { - throw new IllegalStateException("No compatible version of Jackson is present on the classpath."); - } - - if (jacksonJsonProvider == null) { - jacksonJsonProvider = new JacksonJsonProvider(); - } - - return jacksonJsonProvider; - } - - /** - * Constructs a singleton instance of {@link JsonProvider} that uses Gson. - * - * @return An instance of {@link JsonProvider}. - * @throws IllegalStateException If no compatible version of Gson is present on the classpath. - */ - public static synchronized JsonProvider getGsonJsonProvider() { - if (!GsonJsonProvider.INITIALIZED) { - throw new IllegalStateException("No compatible version of Gson is present on the classpath."); - } - - if (gsonJsonProvider == null) { - gsonJsonProvider = new GsonJsonProvider(); - } - - return gsonJsonProvider; - } -} diff --git a/sdk/serialization/azure-json-reflect/src/main/java/com/azure/json/reflect/MetaFactoryFactory.java b/sdk/serialization/azure-json-reflect/src/main/java/com/azure/json/reflect/MetaFactoryFactory.java deleted file mode 100644 index e8bbc0356eff..000000000000 --- a/sdk/serialization/azure-json-reflect/src/main/java/com/azure/json/reflect/MetaFactoryFactory.java +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.json.reflect; - -import java.lang.invoke.LambdaMetafactory; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; -import java.lang.invoke.MethodType; - -import static java.lang.invoke.MethodType.methodType; - -final class MetaFactoryFactory { - private MetaFactoryFactory() { - throw new UnsupportedOperationException(); - } - - @SuppressWarnings("unchecked") - static T createMetaFactory(String methodName, Class implClass, MethodType implType, Class invokedClass, - MethodType invokedType, MethodHandles.Lookup lookup) throws Throwable { - MethodHandle handle = lookup.findVirtual(implClass, methodName, implType); - return (T) LambdaMetafactory - .metafactory(lookup, methodName, methodType(invokedClass), invokedType, handle, handle.type()) - .getTarget() - .invoke(); - } -} diff --git a/sdk/serialization/azure-json-reflect/src/main/java/com/azure/json/reflect/package-info.java b/sdk/serialization/azure-json-reflect/src/main/java/com/azure/json/reflect/package-info.java deleted file mode 100644 index 51c99d95b86c..000000000000 --- a/sdk/serialization/azure-json-reflect/src/main/java/com/azure/json/reflect/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - * Contains general classes for handling JSON reflectively. - */ -package com.azure.json.reflect; diff --git a/sdk/serialization/azure-json-reflect/src/main/java/module-info.java b/sdk/serialization/azure-json-reflect/src/main/java/module-info.java deleted file mode 100644 index ea3cbf95be77..000000000000 --- a/sdk/serialization/azure-json-reflect/src/main/java/module-info.java +++ /dev/null @@ -1,8 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -module com.azure.json.reflect { - requires transitive com.azure.json; - - exports com.azure.json.reflect; -} diff --git a/sdk/serialization/azure-json-reflect/src/test/java/com/azure/json/reflect/GsonJsonReaderContractTests.java b/sdk/serialization/azure-json-reflect/src/test/java/com/azure/json/reflect/GsonJsonReaderContractTests.java deleted file mode 100644 index 65524cd3bfca..000000000000 --- a/sdk/serialization/azure-json-reflect/src/test/java/com/azure/json/reflect/GsonJsonReaderContractTests.java +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.json.reflect; - -import com.azure.json.JsonOptions; -import com.azure.json.JsonReader; -import com.azure.json.contract.JsonReaderContractTests; - -import java.io.IOException; - -/** - * Tests {@link GsonJsonReader} against the contract required by {@link JsonReader}. - */ -public class GsonJsonReaderContractTests extends JsonReaderContractTests { - @Override - public JsonReader getJsonReader(String json) throws IOException { - return JsonProviderFactory.getGsonJsonProvider().createReader(json, new JsonOptions()); - } -} diff --git a/sdk/serialization/azure-json-reflect/src/test/java/com/azure/json/reflect/GsonJsonWriterContractTests.java b/sdk/serialization/azure-json-reflect/src/test/java/com/azure/json/reflect/GsonJsonWriterContractTests.java deleted file mode 100644 index 41a1671ffd92..000000000000 --- a/sdk/serialization/azure-json-reflect/src/test/java/com/azure/json/reflect/GsonJsonWriterContractTests.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.json.reflect; - -import com.azure.json.JsonOptions; -import com.azure.json.JsonWriter; -import com.azure.json.contract.JsonWriterContractTests; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.charset.StandardCharsets; - -/** - * Tests {@link GsonJsonWriter} against the contract required by {@link JsonWriter}. - */ -public class GsonJsonWriterContractTests extends JsonWriterContractTests { - private ByteArrayOutputStream outputStream; - private JsonWriter writer; - - @BeforeEach - public void beforeEach() throws IOException { - this.outputStream = new ByteArrayOutputStream(); - this.writer = JsonProviderFactory.getGsonJsonProvider().createWriter(outputStream, new JsonOptions()); - } - - @AfterEach - public void afterEach() throws IOException { - if (writer != null) { - try { - writer.close(); - } catch (IllegalStateException ignored) { - // Closing the JsonWriter may throw an IllegalStateException if the current writing state isn't valid - // for closing, ignore it in test. - } - } - } - - @Override - public JsonWriter getJsonWriter() { - return writer; - } - - @Override - public String getJsonWriterContents() { - try { - writer.flush(); - return outputStream.toString(StandardCharsets.UTF_8.name()); - } catch (IOException e) { - throw new RuntimeException(e); - } - } -} diff --git a/sdk/serialization/azure-json-reflect/src/test/java/com/azure/json/reflect/JacksonJsonReaderContractTests.java b/sdk/serialization/azure-json-reflect/src/test/java/com/azure/json/reflect/JacksonJsonReaderContractTests.java deleted file mode 100644 index 24c72ac6db31..000000000000 --- a/sdk/serialization/azure-json-reflect/src/test/java/com/azure/json/reflect/JacksonJsonReaderContractTests.java +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.json.reflect; - -import com.azure.json.JsonOptions; -import com.azure.json.JsonReader; -import com.azure.json.contract.JsonReaderContractTests; - -import java.io.IOException; - -/** - * Tests {@link JacksonJsonReader} against the contract required by {@link JsonReader}. - */ -public class JacksonJsonReaderContractTests extends JsonReaderContractTests { - @Override - public JsonReader getJsonReader(String json) throws IOException { - return JsonProviderFactory.getJacksonJsonProvider().createReader(json, new JsonOptions()); - } -} diff --git a/sdk/serialization/azure-json-reflect/src/test/java/com/azure/json/reflect/JacksonJsonWriterContractTests.java b/sdk/serialization/azure-json-reflect/src/test/java/com/azure/json/reflect/JacksonJsonWriterContractTests.java deleted file mode 100644 index cdd2a88006db..000000000000 --- a/sdk/serialization/azure-json-reflect/src/test/java/com/azure/json/reflect/JacksonJsonWriterContractTests.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.json.reflect; - -import com.azure.json.JsonOptions; -import com.azure.json.JsonWriter; -import com.azure.json.contract.JsonWriterContractTests; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.charset.StandardCharsets; - -/** - * Tests {@link JacksonJsonWriter} against the contract required by {@link JsonWriter}. - */ -public class JacksonJsonWriterContractTests extends JsonWriterContractTests { - private ByteArrayOutputStream outputStream; - private JsonWriter writer; - - @BeforeEach - public void beforeEach() throws IOException { - this.outputStream = new ByteArrayOutputStream(); - this.writer = JsonProviderFactory.getJacksonJsonProvider().createWriter(outputStream, new JsonOptions()); - } - - @AfterEach - public void afterEach() throws IOException { - if (writer != null) { - try { - writer.close(); - } catch (IllegalStateException ignored) { - // Closing the JsonWriter may throw an IllegalStateException if the current writing state isn't valid - // for closing, ignore it in test. - } - } - } - - @Override - public JsonWriter getJsonWriter() { - return writer; - } - - @Override - public String getJsonWriterContents() { - try { - writer.flush(); - return outputStream.toString(StandardCharsets.UTF_8.name()); - } catch (IOException e) { - throw new RuntimeException(e); - } - } -} diff --git a/sdk/serialization/azure-json/CHANGELOG.md b/sdk/serialization/azure-json/CHANGELOG.md index 82194686d7bb..900fed758492 100644 --- a/sdk/serialization/azure-json/CHANGELOG.md +++ b/sdk/serialization/azure-json/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.4.0-beta.1 (Unreleased) +## 1.6.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,32 @@ ### Other Changes +## 1.5.0 (2025-03-07) + +### Breaking Changes + +- `JsonNumber` previously would use `float` when the floating point number was small enough to fit in `float` but it + now aligns behavior with `JsonReader.readUntyped()` where `double` will be the smallest floating point type used. + This aligns with floating point number behavior in Java where `double` is the default if no type is specified. +- Support for special numeric `INF`, `-INF`, and `+INF` values have been removed to align with behaviors of `Float` + and `Double` in Java where only the `Infinity` variants are supported. + +### Bugs Fixed + +- `JsonReader.readUntyped()` had incomplete support for untyped numerics. Numerics too large for `double` and `long` are + now supported and a bug where exponents were not being parsed correctly is fixed. + +## 1.4.0 (2025-01-27) + +### Features Added + +- Added convenience APIs to `JsonArray` for adding a `boolean`, `Number`, or `String` without needing to instantiate the + corresponding `JsonElement` subtype. +- Added convenience APIs to `JsonObject` for setting `boolean`, `Number`, and `String` without needing to instantiate the + corresponding `JsonElement` subtype. +- Added `JsonObject.hasProperty` to check if a property exists in the object. +- Added convenience fluent methods to `JsonElement` to cast to a specific subtype if the element is of that type. + ## 1.3.0 (2024-09-11) ### Features Added diff --git a/sdk/serialization/azure-json/README.md b/sdk/serialization/azure-json/README.md index 82fd29e6eb2f..afa02eea5874 100644 --- a/sdk/serialization/azure-json/README.md +++ b/sdk/serialization/azure-json/README.md @@ -17,7 +17,7 @@ Azure JSON provides shared primitives, abstractions, and helpers for JSON. com.azure azure-json - 1.3.0 + 1.6.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -48,7 +48,7 @@ could be called indefinitely returning the same integer without error until `nex forward. `JsonReader` allows for type conversion between JSON types, such as trying to convert a JSON string to a number or vice -versa, and for commonly used nonstandard JSON values, such as `NaN`, `INF`, `-INF`, `Infinity`, and `-Infinity`. +versa, and for commonly used nonstandard JSON values, such as `NaN`, `Infinity`, `+Infinity`, and `-Infinity`. `JsonReader` doesn't take ownership of the JSON input source and therefore doesn't close any resources if the JSON is provided using an `InputStream` or `Reader`. @@ -65,7 +65,7 @@ and objects, APIs for writing JSON. `JsonWriter` is provided to allow for any un such as Jackson or GSON, as long as the implementation passes the tests provided by the package's test-jar (`JsonWriterContractTests`). -`JsonWriter` allows for commonly used nonstandard JSON values, such as `NaN`, `INF`, `-INF`, `Infinity`, and +`JsonWriter` allows for commonly used nonstandard JSON values, such as `NaN`, `Infinity`, `+Infinity`, and `-Infinity`, to be written using `writeNumberField` or `writeRawValue`. `JsonWriter` doesn't write null `byte[]`, `Boolean`, `Number`, or `String` values when written as a field, @@ -96,7 +96,7 @@ by this package if an implementation isn't found on the classpath. #### JsonOptions `JsonOptions` contains configurations that must be respected by all implementations of `JsonReader`s and `JsonWriter`s. -At this time, there's only one configuration for determining whether non-numeric numbers, `NaN`, `INF`, `-INF`, `Infinity`, +At this time, there's only one configuration for determining whether non-numeric numbers, `NaN`, `Infinity`, `+Infinity`, and `-Infinity` are supported in JSON reading and writing with a default setting of `true`, that non-numeric numbers are allowed. @@ -138,4 +138,4 @@ For details on contributing to this repository, see the [contributing guide](htt [jdk_link]: https://learn.microsoft.com/java/azure/jdk/?view=azure-java-stable [samples_readme]: https://github.com/Azure/azure-sdk-for-java/blob/8517f855a79ea23dce94397c58e4368738016fc4/sdk/core/azure-json/src/samples/README.md -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fserialization%2Fazure-json%2FREADME.png) + diff --git a/sdk/serialization/azure-json/checkstyle-suppressions.xml b/sdk/serialization/azure-json/checkstyle-suppressions.xml index 9d5c8fb24a34..755747bad2de 100644 --- a/sdk/serialization/azure-json/checkstyle-suppressions.xml +++ b/sdk/serialization/azure-json/checkstyle-suppressions.xml @@ -1,20 +1,12 @@ - + + - - - - - - - - - - - - - + + + + + + diff --git a/sdk/serialization/azure-json/pom.xml b/sdk/serialization/azure-json/pom.xml index 13563ec0e180..c52107447f3f 100644 --- a/sdk/serialization/azure-json/pom.xml +++ b/sdk/serialization/azure-json/pom.xml @@ -15,7 +15,7 @@ com.azure azure-json jar - 1.4.0-beta.1 + 1.6.0-beta.1 Microsoft Azure Java JSON Library This package provides interfaces for reading and writing JSON. @@ -248,7 +248,7 @@ org.codehaus.mojo exec-maven-plugin - 3.4.1 + 3.5.0 add-license-comment diff --git a/sdk/serialization/azure-json/spotbugs-exclude.xml b/sdk/serialization/azure-json/spotbugs-exclude.xml index 74272c84e801..a4a142e7e43c 100644 --- a/sdk/serialization/azure-json/spotbugs-exclude.xml +++ b/sdk/serialization/azure-json/spotbugs-exclude.xml @@ -1,14 +1,79 @@ + xsi:schemaLocation="https://github.com/spotbugs/filter/3.0.0 https://raw.githubusercontent.com/spotbugs/spotbugs/3.1.0/spotbugs/etc/findbugsfilter.xsd"> - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - + + diff --git a/sdk/serialization/azure-json/src/main/java/com/azure/json/JsonOptions.java b/sdk/serialization/azure-json/src/main/java/com/azure/json/JsonOptions.java index 9dd3e8f31229..e2a4167e4a0d 100644 --- a/sdk/serialization/azure-json/src/main/java/com/azure/json/JsonOptions.java +++ b/sdk/serialization/azure-json/src/main/java/com/azure/json/JsonOptions.java @@ -22,7 +22,8 @@ public JsonOptions() { } /** - * Whether non-numeric numbers such as {@code NaN} and {@code INF} and {@code -INF} are supported. + * Whether non-numeric numbers such as {@code NaN}, {@code Infinity}, {@code +Infinity} and {@code -Infinity} are + * supported. *

        * By default, this is configured to true. * @@ -33,7 +34,8 @@ public boolean isNonNumericNumbersSupported() { } /** - * Sets whether non-numeric numbers such as {@code NaN} and {@code INF} and {@code -INF} are supported. + * Whether non-numeric numbers such as {@code NaN}, {@code Infinity}, {@code +Infinity} and {@code -Infinity} are + * supported. *

        * By default, this is configured to true. * diff --git a/sdk/serialization/azure-json/src/main/java/com/azure/json/JsonReader.java b/sdk/serialization/azure-json/src/main/java/com/azure/json/JsonReader.java index e09d79947779..03d9f5c3dba9 100644 --- a/sdk/serialization/azure-json/src/main/java/com/azure/json/JsonReader.java +++ b/sdk/serialization/azure-json/src/main/java/com/azure/json/JsonReader.java @@ -3,10 +3,13 @@ package com.azure.json; +import com.azure.json.implementation.JsonUtils; import com.azure.json.implementation.jackson.core.io.JsonStringEncoder; import java.io.Closeable; import java.io.IOException; +import java.math.BigDecimal; +import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Base64; @@ -566,8 +569,8 @@ private T readMapOrObject(ReadValueCallback valueReaderFunc, *

          *
        • null if the starting token is null or {@link JsonToken#NULL}
        • *
        • true or false if the starting token is {@link JsonToken#BOOLEAN}
        • - *
        • One of int, long, float, or double is the starting token is {@link JsonToken#NUMBER}, the smallest - * containing value will be used if the number is an integer
        • + *
        • One of int, long, {@link BigInteger}, double, or {@link BigDecimal} if the starting token is + * {@link JsonToken#NUMBER}, the smallest containing value will be used
        • *
        • An array of untyped elements if the starting point is {@link JsonToken#START_ARRAY}
        • *
        • A map of String-untyped value if the starting point is {@link JsonToken#START_OBJECT}
        • *
        @@ -603,26 +606,7 @@ private Object readUntypedHelper(int depth) throws IOException { } else if (token == JsonToken.BOOLEAN) { return getBoolean(); } else if (token == JsonToken.NUMBER) { - String numberText = getText(); - - if ("INF".equals(numberText) - || "Infinity".equals(numberText) - || "-INF".equals(numberText) - || "-Infinity".equals(numberText) - || "NaN".equals(numberText)) { - // Return special Double values as text as not all implementations of JsonReader may be able to handle - // them as Doubles when parsing generically. - return numberText; - } else if (numberText.contains(".")) { - // Unlike integers always use Double to prevent floating point rounding issues. - return Double.parseDouble(numberText); - } else { - try { - return Integer.parseInt(numberText); - } catch (NumberFormatException ex) { - return Long.parseLong(numberText); - } - } + return JsonUtils.parseNumber(getText()); } else if (token == JsonToken.STRING) { return getString(); } else if (token == JsonToken.START_ARRAY) { diff --git a/sdk/serialization/azure-json/src/main/java/com/azure/json/implementation/JsonUtils.java b/sdk/serialization/azure-json/src/main/java/com/azure/json/implementation/JsonUtils.java new file mode 100644 index 000000000000..9f8030ee9d46 --- /dev/null +++ b/sdk/serialization/azure-json/src/main/java/com/azure/json/implementation/JsonUtils.java @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.json.implementation; + +import java.math.BigDecimal; +import java.math.BigInteger; + +/** + * Utility class containing helper methods for serialization. + */ +public final class JsonUtils { + /** + * Parses a number from a string. + *

        + * Callers to this method should ensure that the number string isn't null or empty before calling this method. + *

        + * For integer numbers, this method will return the smallest number type that can represent the number. Where + * {@link Integer} is preferred over {@link Long} and {@link Long} is preferred over {@link BigInteger}. + *

        + * For floating point numbers, {@link Double} will be preferred but {@link BigDecimal} will be used if the number + * is too large to fit in a {@link Double}. + *

        + * Unlike the JSON specification, this method will handle the special floating point representations + * ({@code NaN}, {@code Infinity}, etc) and will return a {@link Double} for those values. + * + * @param numberString The string representation of the number. + * @return The number represented by the string. + * @throws NumberFormatException If the string is not a valid number. + */ + public static Number parseNumber(String numberString) { + int length = numberString.length(); + + // Use the length of the number and checks for special values to determine if the number is a special + // floating point representation. + // The special floating point representations are: NaN, Infinity, +Infinity, and -Infinity. + // These will be returned using Double. + if (length == 3 && "NaN".equals(numberString)) { + return Double.NaN; + } else if (length == 8 && "Infinity".equals(numberString)) { + return Double.POSITIVE_INFINITY; + } else if (length == 9) { + if ("+Infinity".equals(numberString)) { + return Double.POSITIVE_INFINITY; + } else if ("-Infinity".equals(numberString)) { + return Double.NEGATIVE_INFINITY; + } + } + + boolean floatingPoint = false; + for (int i = 0; i < length; i++) { + char c = numberString.charAt(i); + if (c == '.' || c == 'e' || c == 'E') { + floatingPoint = true; + break; + } + } + + return floatingPoint ? handleFloatingPoint(numberString) : handleInteger(numberString); + } + + private static Number handleFloatingPoint(String value) { + // Floating point parsing will return Infinity if the String value is larger than what can be contained by + // the numeric type. Check if the String contains the Infinity representation to know when to scale up the + // numeric type. + // Additionally, due to the handling of values that can't fit into the numeric type, the only time floating + // point parsing will throw is when the string value is invalid. + double d = Double.parseDouble(value); + if (!Double.isInfinite(d)) { + return d; + } + + return new BigDecimal(value); + } + + private static Number handleInteger(String value) { + try { + return Integer.parseInt(value); + } catch (NumberFormatException failedInteger) { + try { + return Long.parseLong(value); + } catch (NumberFormatException failedLong) { + failedLong.addSuppressed(failedInteger); + try { + return new BigInteger(value); + } catch (NumberFormatException failedBigDecimal) { + failedBigDecimal.addSuppressed(failedLong); + throw failedBigDecimal; + } + } + } + } +} diff --git a/sdk/serialization/azure-json/src/main/java/com/azure/json/implementation/jackson/core/JsonParser.java b/sdk/serialization/azure-json/src/main/java/com/azure/json/implementation/jackson/core/JsonParser.java index bcb56b40e8f9..2f1ba05790cd 100644 --- a/sdk/serialization/azure-json/src/main/java/com/azure/json/implementation/jackson/core/JsonParser.java +++ b/sdk/serialization/azure-json/src/main/java/com/azure/json/implementation/jackson/core/JsonParser.java @@ -197,8 +197,8 @@ public enum Feature { * (see section 3.2.4.1, Lexical Representation) * allows (tokens are quoted contents, not including quotes): *

          - *
        • "INF" (for positive infinity), as well as alias of "Infinity" - *
        • "-INF" (for negative infinity), alias "-Infinity" + *
        • "Infinity" (for positive infinity) + *
        • "-Infinity" (for negative infinity) *
        • "NaN" (for other not-a-numbers, like result of division by zero) *
        *

        diff --git a/sdk/serialization/azure-json/src/main/java/com/azure/json/implementation/jackson/core/base/ParserBase.java b/sdk/serialization/azure-json/src/main/java/com/azure/json/implementation/jackson/core/base/ParserBase.java index bd2f4e842f99..2f6ddcc0f947 100644 --- a/sdk/serialization/azure-json/src/main/java/com/azure/json/implementation/jackson/core/base/ParserBase.java +++ b/sdk/serialization/azure-json/src/main/java/com/azure/json/implementation/jackson/core/base/ParserBase.java @@ -1122,7 +1122,7 @@ protected String _validJsonTokenList() { @SuppressWarnings("deprecation") protected String _validJsonValueList() { if (isEnabled(Feature.ALLOW_NON_NUMERIC_NUMBERS)) { - return "(JSON String, Number (or 'NaN'/'INF'/'+INF'), Array, Object or token 'null', 'true' or 'false')"; + return "(JSON String, Number (or 'NaN'/'Infinity'/'+Infinity'/'-Infinity'), Array, Object or token 'null', 'true' or 'false')"; } return "(JSON String, Number, Array, Object or token 'null', 'true' or 'false')"; } diff --git a/sdk/serialization/azure-json/src/main/java/com/azure/json/implementation/jackson/core/json/JsonReadFeature.java b/sdk/serialization/azure-json/src/main/java/com/azure/json/implementation/jackson/core/json/JsonReadFeature.java index 5314e92a6525..bb5ddf9875be 100644 --- a/sdk/serialization/azure-json/src/main/java/com/azure/json/implementation/jackson/core/json/JsonReadFeature.java +++ b/sdk/serialization/azure-json/src/main/java/com/azure/json/implementation/jackson/core/json/JsonReadFeature.java @@ -130,8 +130,8 @@ public enum JsonReadFeature implements FormatFeature { * (see section 3.2.4.1, Lexical Representation) * allows (tokens are quoted contents, not including quotes): *

          - *
        • "INF" (for positive infinity), as well as alias of "Infinity" - *
        • "-INF" (for negative infinity), alias "-Infinity" + *
        • "Infinity" (for positive infinity) + *
        • "-Infinity" (for negative infinity) *
        • "NaN" (for other not-a-numbers, like result of division by zero) *
        *

        diff --git a/sdk/serialization/azure-json/src/main/java/com/azure/json/implementation/jackson/core/json/ReaderBasedJsonParser.java b/sdk/serialization/azure-json/src/main/java/com/azure/json/implementation/jackson/core/json/ReaderBasedJsonParser.java index bf7d59e0f905..045c797f9b47 100644 --- a/sdk/serialization/azure-json/src/main/java/com/azure/json/implementation/jackson/core/json/ReaderBasedJsonParser.java +++ b/sdk/serialization/azure-json/src/main/java/com/azure/json/implementation/jackson/core/json/ReaderBasedJsonParser.java @@ -1244,15 +1244,7 @@ protected JsonToken _handleInvalidNumberStart(int ch, boolean negative) throws I } } ch = _inputBuffer[_inputPtr++]; - if (ch == 'N') { - String match = negative ? "-INF" : "+INF"; - _matchToken(match, 3); - if ((_features & FEAT_MASK_NON_NUM_NUMBERS) != 0) { - return resetAsNaN(match, negative ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY); - } - _reportError( - "Non-standard token '" + match + "': enable JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS to allow"); - } else if (ch == 'n') { + if (ch == 'n') { String match = negative ? "-Infinity" : "+Infinity"; _matchToken(match, 3); if ((_features & FEAT_MASK_NON_NUM_NUMBERS) != 0) { diff --git a/sdk/serialization/azure-json/src/main/java/com/azure/json/implementation/jackson/core/json/UTF8StreamJsonParser.java b/sdk/serialization/azure-json/src/main/java/com/azure/json/implementation/jackson/core/json/UTF8StreamJsonParser.java index f522f4a555f5..5daefedcb11f 100644 --- a/sdk/serialization/azure-json/src/main/java/com/azure/json/implementation/jackson/core/json/UTF8StreamJsonParser.java +++ b/sdk/serialization/azure-json/src/main/java/com/azure/json/implementation/jackson/core/json/UTF8StreamJsonParser.java @@ -2350,9 +2350,7 @@ protected JsonToken _handleInvalidNumberStart(int ch, boolean neg) throws IOExce } ch = _inputBuffer[_inputPtr++]; String match; - if (ch == 'N') { - match = neg ? "-INF" : "+INF"; - } else if (ch == 'n') { + if (ch == 'n') { match = neg ? "-Infinity" : "+Infinity"; } else { break; diff --git a/sdk/serialization/azure-json/src/main/java/com/azure/json/models/JsonNumber.java b/sdk/serialization/azure-json/src/main/java/com/azure/json/models/JsonNumber.java index c7f5b097d640..40c38b56032a 100644 --- a/sdk/serialization/azure-json/src/main/java/com/azure/json/models/JsonNumber.java +++ b/sdk/serialization/azure-json/src/main/java/com/azure/json/models/JsonNumber.java @@ -6,6 +6,7 @@ import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; +import com.azure.json.implementation.JsonUtils; import java.io.IOException; import java.math.BigDecimal; @@ -29,76 +30,20 @@ public final class JsonNumber extends JsonElement { * ({@code .}) or an exponent ({@code e} or {@code E}), the string will be parsed as a floating point number, * otherwise it will be parsed as an integer. *

        - * Parsing attempts to use the smallest container that can represent the number. For floating points it'll attempt - * to use {@link Float#parseFloat(String)}, if that fails it'll use {@link Double#parseDouble(String)}, and finally - * if that fails it'll use {@link BigDecimal#BigDecimal(String)}. For integers it'll attempt to use - * {@link Integer#parseInt(String)}, if that fails it'll use {@link Long#parseLong(String)}, and finally if that - * fails it'll use {@link BigInteger#BigInteger(String)}. + * For integer numbers, this method will return the smallest number type that can represent the number. Where + * {@link Integer} is preferred over {@link Long} and {@link Long} is preferred over {@link BigInteger}. + *

        + * For floating point numbers, {@link Double} will be preferred but {@link BigDecimal} will be used if the number + * is too large to fit in a {@link Double}. *

        * If the string is one of the special floating point representations ({@code NaN}, {@code Infinity}, etc), then - * the value will be represented using {@link Float}. + * the value will be represented using {@link Double}. * * @param value The string-based numeric value the JsonNumber will represent. * @throws NumberFormatException If the string is not a valid number. */ JsonNumber(String value) throws IllegalArgumentException { - int length = value.length(); - boolean floatingPoint = false; - boolean infinity = value.contains("Infinity"); - if (infinity) { - // Use Double.parseDouble to handle Infinity. - this.value = Double.parseDouble(value); - return; - } - - for (int i = 0; i < length; i++) { - char c = value.charAt(i); - if (c == '.' || c == 'e' || c == 'E') { - floatingPoint = true; - break; - } - } - - this.value = floatingPoint ? handleFloatingPoint(value) : handleInteger(value); - } - - private static Number handleFloatingPoint(String value) { - // Floating point parsing will return Infinity if the String value is larger than what can be contained by - // the numeric type. Check if the String contains the Infinity representation to know when to scale up the - // numeric type. - // Additionally, due to the handling of values that can't fit into the numeric type, the only time floating - // point parsing will throw is when the string value is invalid. - float f = Float.parseFloat(value); - - // If the float wasn't infinite, return it. - if (!Float.isInfinite(f)) { - return f; - } - - double d = Double.parseDouble(value); - if (!Double.isInfinite(d)) { - return d; - } - - return new BigDecimal(value); - } - - private static Number handleInteger(String value) { - try { - return Integer.parseInt(value); - } catch (NumberFormatException failedInteger) { - try { - return Long.parseLong(value); - } catch (NumberFormatException failedLong) { - failedLong.addSuppressed(failedInteger); - try { - return new BigInteger(value); - } catch (NumberFormatException failedBigDecimal) { - failedBigDecimal.addSuppressed(failedLong); - throw failedBigDecimal; - } - } - } + this.value = JsonUtils.parseNumber(value); } /** @@ -147,9 +92,14 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * {@link IllegalStateException} will be thrown. Otherwise, a JSON number representing the numeric value will be * created and returned. *

        - * The {@link JsonNumber} returned will have a {@link JsonNumber#getValue()} that is the smallest type that can - * represent the numeric value. Numeric types used are {@link Integer}, {@link Long}, {@link BigInteger}, - * {@link Float}, {@link Double}, and {@link BigDecimal}. + * For integer numbers, this method will return the smallest number type that can represent the number. Where + * {@link Integer} is preferred over {@link Long} and {@link Long} is preferred over {@link BigInteger}. + *

        + * For floating point numbers, {@link Double} will be preferred but {@link BigDecimal} will be used if the number + * is too large to fit in a {@link Double}. + *

        + * If the string is one of the special floating point representations ({@code NaN}, {@code Infinity}, etc), then + * the value will be represented using {@link Double}. * * @param jsonReader The JsonReader to deserialize from. * @return The deserialized JSON number. diff --git a/sdk/serialization/azure-json/src/samples/README.md b/sdk/serialization/azure-json/src/samples/README.md index 3290942675ef..ed394ebbde15 100644 --- a/sdk/serialization/azure-json/src/samples/README.md +++ b/sdk/serialization/azure-json/src/samples/README.md @@ -52,4 +52,4 @@ See the [Contributing][sdk_readme_contributing] section of the library's root RE [sdk_readme_next_steps]: https://github.com/Azure/azure-sdk-for-java/blob/4b6100b019036da82904911f05bb8f45f62505d7/sdk/serialization/azure-json/README.md#next-steps [sdk_readme_contributing]: https://github.com/Azure/azure-sdk-for-java/blob/4b6100b019036da82904911f05bb8f45f62505d7/sdk/serialization/azure-json/README.md#contributing -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fserialization%2Fazure-json%2Fsrc%2Fsamples%2README.png) + diff --git a/sdk/serialization/azure-json/src/test/java/com/azure/json/contract/JsonReaderContractTests.java b/sdk/serialization/azure-json/src/test/java/com/azure/json/contract/JsonReaderContractTests.java index 337062480318..62c94b91d02e 100644 --- a/sdk/serialization/azure-json/src/test/java/com/azure/json/contract/JsonReaderContractTests.java +++ b/sdk/serialization/azure-json/src/test/java/com/azure/json/contract/JsonReaderContractTests.java @@ -3,6 +3,7 @@ package com.azure.json.contract; +import com.azure.json.JsonOptions; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -10,6 +11,8 @@ import com.azure.json.ReadValueCallback; import org.junit.jupiter.api.Named; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -30,6 +33,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertIterableEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -42,16 +46,24 @@ * written to be considered an acceptable implementation. *

        * Each test will only create a single instance of {@link JsonReader} to simplify the usage of - * {@link #getJsonReader(String)}. + * {@link #getJsonReader(String, JsonOptions)}. */ public abstract class JsonReaderContractTests { + private static final String JSON_WITH_COMMENTS = "{// single line comment\n\"single-line\":\"comment\"," + + "\n/*\nmulti-line comment\n*/\n\"multi-line\":\"comment\"}"; + + private JsonReader getJsonReader(String json) throws IOException { + return getJsonReader(json, new JsonOptions()); + } + /** * Creates an instance of {@link JsonReader} that will be used by a test. * * @param json The JSON to be read. + * @param options The {@link JsonOptions} to be used. * @return The {@link JsonReader} that a test will use. */ - protected abstract JsonReader getJsonReader(String json) throws IOException; + protected abstract JsonReader getJsonReader(String json, JsonOptions options) throws IOException; @ParameterizedTest @MethodSource("basicOperationsSupplier") @@ -445,9 +457,9 @@ public void readUntypedSimple(String json, int nextCount, Object expected) throw private static Stream readUntypedSimpleSupplier() { return Stream.of(Arguments.of("null", 1, null), Arguments.of("true", 1, true), Arguments.of("false", 1, false), - Arguments.of("3.14", 1, 3.14), Arguments.of("NaN", 1, String.valueOf(Double.NaN)), - Arguments.of("-Infinity", 1, String.valueOf(Double.NEGATIVE_INFINITY)), - Arguments.of("Infinity", 1, String.valueOf(Double.POSITIVE_INFINITY)), Arguments.of("42", 1, 42), + Arguments.of("3.14", 1, 3.14D), Arguments.of("NaN", 1, Double.NaN), + Arguments.of("-Infinity", 1, Double.NEGATIVE_INFINITY), + Arguments.of("Infinity", 1, Double.POSITIVE_INFINITY), Arguments.of("42", 1, 42), Arguments.of("420000000000", 1, 420000000000L), Arguments.of("\"hello\"", 1, "hello")); } @@ -745,6 +757,42 @@ private static Stream readMapSupplier() { Arguments.of("{\"boolean\":true,\"int\":42,\"decimal\":42.0,\"string\":\"hello\"}", reader, map)); } + @Execution(ExecutionMode.SAME_THREAD) + @ParameterizedTest + @MethodSource("readUntypedExponentNumbersSupplier") + public void readUntypedExponentNumbers(String numberString, Number expected) throws IOException { + readAndValidate(numberString, JsonReader::readUntyped, actual -> assertEquals(expected, actual)); + } + + private static Stream readUntypedExponentNumbersSupplier() { + return Stream.of(Arguments.of("1e-1", 0.1D), Arguments.of("1E-1", 0.1D), Arguments.of("1e+1", 10D), + Arguments.of("1E+1", 10D), Arguments.of("1e-01", 0.1D), Arguments.of("1E-01", 0.1D), + Arguments.of("1e+01", 10D), Arguments.of("1E+01", 10D), Arguments.of("1e0", 1D), Arguments.of("1E0", 1D), + + Arguments.of("Infinity", Double.POSITIVE_INFINITY), Arguments.of("+Infinity", Double.POSITIVE_INFINITY), + Arguments.of("-Infinity", Double.NEGATIVE_INFINITY), Arguments.of("NaN", Double.NaN)); + } + + @Test + public void readJsonc() throws IOException { + try (JsonReader jsonReader = getJsonReader(JSON_WITH_COMMENTS, new JsonOptions().setJsoncSupported(true))) { + jsonReader.nextToken(); + String outputJson = jsonReader.readChildren(); + assertNotNull(outputJson); + } + } + + @Test + public void readJsoncFails() { + assertThrows(IOException.class, () -> { + try (JsonReader jsonReader = getJsonReader(JSON_WITH_COMMENTS)) { + jsonReader.nextToken(); + String outputJson = jsonReader.readChildren(); + assertNotNull(outputJson); + } + }); + } + private static void assertJsonReaderStructInitialization(JsonReader reader, JsonToken expectedInitialToken) throws IOException { assertNull(reader.currentToken()); @@ -772,9 +820,8 @@ public String getTest() { return test; } - public TestData setTest(String test) { + public void setTest(String test) { this.test = test; - return this; } @Override diff --git a/sdk/serialization/azure-json/src/test/java/com/azure/json/contract/models/JsonNumberContractTests.java b/sdk/serialization/azure-json/src/test/java/com/azure/json/contract/models/JsonNumberContractTests.java index ed9f36c89284..873d9819c499 100644 --- a/sdk/serialization/azure-json/src/test/java/com/azure/json/contract/models/JsonNumberContractTests.java +++ b/sdk/serialization/azure-json/src/test/java/com/azure/json/contract/models/JsonNumberContractTests.java @@ -73,10 +73,10 @@ private static Stream fromJsonSupplier() { return Stream.of(Arguments.of("0", 0), Arguments.of("-1", -1), Arguments.of("10000000000", 10000000000L), Arguments.of("-10000000000", -10000000000L), Arguments.of("100000000000000000000", new BigInteger("100000000000000000000")), - Arguments.of("-100000000000000000000", new BigInteger("-100000000000000000000")), Arguments.of("0.0", 0.0F), - Arguments.of("-1.0", -1.0F), Arguments.of("1E6", 1E6F), Arguments.of("-1E6", -1E6F), - Arguments.of("1.0E6", 1E6F), Arguments.of("-1.0E6", -1E6F), Arguments.of("1e6", 1E6F), - Arguments.of("-1e6", -1E6F), Arguments.of("1.0e6", 1E6F), Arguments.of("-1.0e6", -1E6F), + Arguments.of("-100000000000000000000", new BigInteger("-100000000000000000000")), Arguments.of("0.0", 0.0D), + Arguments.of("-1.0", -1.0D), Arguments.of("1E6", 1E6D), Arguments.of("-1E6", -1E6D), + Arguments.of("1.0E6", 1E6D), Arguments.of("-1.0E6", -1E6D), Arguments.of("1e6", 1E6D), + Arguments.of("-1e6", -1E6D), Arguments.of("1.0e6", 1E6D), Arguments.of("-1.0e6", -1E6D), Arguments.of("1E39", 1E39D), Arguments.of("-1E39", -1E39D), Arguments.of("1.0E39", 1E39D), Arguments.of("-1.0E39", -1E39D), Arguments.of("1e39", 1E39D), Arguments.of("-1e39", -1E39D), Arguments.of("1.0e39", 1E39D), Arguments.of("-1.0e39", -1E39D), diff --git a/sdk/serialization/azure-json/src/test/java/com/azure/json/implementation/DefaultJsonReaderContractTests.java b/sdk/serialization/azure-json/src/test/java/com/azure/json/implementation/DefaultJsonReaderContractTests.java index a4887d58b633..eb8e07df119d 100644 --- a/sdk/serialization/azure-json/src/test/java/com/azure/json/implementation/DefaultJsonReaderContractTests.java +++ b/sdk/serialization/azure-json/src/test/java/com/azure/json/implementation/DefaultJsonReaderContractTests.java @@ -6,26 +6,19 @@ import com.azure.json.JsonOptions; import com.azure.json.JsonReader; import com.azure.json.contract.JsonReaderContractTests; -import com.azure.json.implementation.jackson.core.JsonParseException; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; - /** * Tests {@link DefaultJsonReader} against the contract required by {@link JsonReader}. */ public class DefaultJsonReaderContractTests extends JsonReaderContractTests { private JsonReader reader; - String jsonWithComments = "{ // single line comment\n" + " \"single-line\": \"comment\",\n" + " /*\n" - + " multi-line comment\n" + " */\n" + " \"multi-line\": \"comment\"}"; @Override - public JsonReader getJsonReader(String json) throws IOException { - this.reader = DefaultJsonReader.fromString(json, new JsonOptions()); + public JsonReader getJsonReader(String json, JsonOptions options) throws IOException { + this.reader = DefaultJsonReader.fromString(json, options); return reader; } @@ -35,26 +28,4 @@ public void afterEach() throws IOException { reader.close(); } } - - @Test - public void readJsonc() throws IOException { - - try (JsonReader jsonReader - = DefaultJsonReader.fromString(jsonWithComments, new JsonOptions().setJsoncSupported(true))) { - jsonReader.nextToken(); - String outputJson = jsonReader.readChildren(); - assertNotNull(outputJson); - } - } - - @Test - public void readJsoncFails() throws IOException { - assertThrows(JsonParseException.class, () -> { - try (JsonReader jsonReader = getJsonReader(jsonWithComments)) { - jsonReader.nextToken(); - String outputJson = jsonReader.readChildren(); - assertNotNull(outputJson); - } - }); - } } diff --git a/sdk/serialization/azure-xml/CHANGELOG.md b/sdk/serialization/azure-xml/CHANGELOG.md index eb75add19573..acdbd73d336c 100644 --- a/sdk/serialization/azure-xml/CHANGELOG.md +++ b/sdk/serialization/azure-xml/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.2.0-beta.1 (Unreleased) +## 1.3.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,22 @@ ### Other Changes +## 1.2.0 (2025-01-27) + +### Features Added + +- Added APIs to `XmlReader` that may reduce `QName`, and other allocations, depending on the XML implementation. + `XmlElementConsumer` and usage with `XmlReader.processNextElement(XmlElementConsumer)` allow for processing an element + without using `QName`. `XmlReader.elementNameMathes(String)` and `XmlReader.elementNameMatches(String, String)` allow + for checking the current element name without using `QName`. `XmlReader.getElementLocalName()` and + `XmlReader.getElementNamespaceUri()` allow for inspecting the current element name and namespace without using + `QName`. Depending on the implementation, using these methods may reduce allocations and improve performance. + +### Other Changes + +- Shaded Aalto XML 1.3.3 into `azure-xml` and updated `XmlReader` and `XmlWriter` to use that implementation by default + if the `XMLInputFactory` or `XMLOutputFactory` `newInstance` returned the default JDK implementation. + ## 1.1.0 (2024-07-26) ### Other Changes diff --git a/sdk/serialization/azure-xml/README.md b/sdk/serialization/azure-xml/README.md index 706d7f6f144d..e3c3b7e79672 100644 --- a/sdk/serialization/azure-xml/README.md +++ b/sdk/serialization/azure-xml/README.md @@ -22,7 +22,7 @@ add the direct dependency to your project as follows. com.azure azure-xml - 1.1.0 + 1.3.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -167,6 +167,13 @@ Get started with Azure libraries that are [built using Azure Core](https://azure If you encounter any bugs, please file issues via [GitHub Issues](https://github.com/Azure/azure-sdk-for-java/issues/new/choose) or checkout [StackOverflow for Azure Java SDK](https://stackoverflow.com/questions/tagged/azure-java-sdk). +### Android Support + +While the Azure SDKs for Java do not explicitly support Android, `azure-xml` is capable of being used in an Android +application. However, for `azure-xml` to work on Android the Android application needs to add a dependency on +[javax.xml.stream:stax-api](https://central.sonatype.com/artifact/javax.xml.stream/stax-api) which provides +`javax.xml.stream` to environments that don't have them (such as Android). + ## Contributing For details on contributing to this repository, see the [contributing guide](https://github.com/Azure/azure-sdk-for-java/blob/main/CONTRIBUTING.md). @@ -180,4 +187,4 @@ For details on contributing to this repository, see the [contributing guide](htt [jdk_link]: https://learn.microsoft.com/java/azure/jdk/?view=azure-java-stable -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fserialization%2Fazure-xml%2FREADME.png) + diff --git a/sdk/serialization/azure-xml/pom.xml b/sdk/serialization/azure-xml/pom.xml index 25d81da99790..f423ee04572c 100644 --- a/sdk/serialization/azure-xml/pom.xml +++ b/sdk/serialization/azure-xml/pom.xml @@ -15,7 +15,7 @@ com.azure azure-xml jar - 1.2.0-beta.1 + 1.3.0-beta.1 Microsoft Azure Java XML Library This package provides interfaces for reading and writing XML. @@ -264,7 +264,7 @@ org.codehaus.mojo exec-maven-plugin - 3.4.1 + 3.5.0 add-license-comment diff --git a/sdk/serialization/ci.yml b/sdk/serialization/ci.yml index 41a0e70d29bf..5be7967910d4 100644 --- a/sdk/serialization/ci.yml +++ b/sdk/serialization/ci.yml @@ -45,36 +45,14 @@ extends: groupId: com.azure safeName: azurexml releaseInBatch: ${{ parameters.release_azurexml }} - AdditionalStagesAfterBuild: - - stage: AzureJsonReflectVersionSupport - displayName: 'azure-json-reflect Version Support' - dependsOn: [] - jobs: - - template: /eng/pipelines/templates/jobs/ci.versions.tests.yml - parameters: - Artifacts: - - name: azure-json-reflect - groupId: com.azure - safeName: azurejsonreflect - VersionOverrides: - - gson_2.4 - - gson_2.5 - - gson_2.6 - - gson_2.7 - - gson_2.8 - - gson_2.9 - - gson_2.10 - - gson_2.11 - - jackson_2.10 - - jackson_2.11 - - jackson_2.12 - - jackson_2.13 - - jackson_2.14 - - jackson_2.15 - - jackson_2.16 - - jackson_2.17 - - jackson_2.18 - TestGoals: surefire:test + + # This needs to be temporarily here for the PR pipeline. + MatrixConfigs: + - Name: Java_ci_test_base + Path: eng/pipelines/templates/stages/platform-matrix.json + Selection: sparse + NonSparseParameters: Agent + GenerateVMJobs: true LiveTestStages: - template: /eng/pipelines/templates/stages/archetype-sdk-tests-isolated.yml diff --git a/sdk/serialization/pom.xml b/sdk/serialization/pom.xml index 60ffa8d637cd..1f35bfbffeaa 100644 --- a/sdk/serialization/pom.xml +++ b/sdk/serialization/pom.xml @@ -11,8 +11,6 @@ azure-json - azure-json-gson - azure-json-reflect azure-xml diff --git a/sdk/servicebus/azure-messaging-servicebus-stress/pom.xml b/sdk/servicebus/azure-messaging-servicebus-stress/pom.xml index d4254d8a5cde..447b2fc2e6fa 100644 --- a/sdk/servicebus/azure-messaging-servicebus-stress/pom.xml +++ b/sdk/servicebus/azure-messaging-servicebus-stress/pom.xml @@ -51,28 +51,28 @@ com.azure - azure-monitor-opentelemetry-exporter - 1.0.0-beta.31 + azure-monitor-opentelemetry-autoconfigure + 1.0.0 io.opentelemetry.instrumentation opentelemetry-runtime-telemetry-java8 - 2.9.0-alpha + 2.12.0-alpha io.opentelemetry.instrumentation opentelemetry-logback-appender-1.0 - 2.9.0-alpha + 2.12.0-alpha com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.52 + 1.0.0-beta.56 com.azure azure-core-metrics-opentelemetry - 1.0.0-beta.25 + 1.0.0-beta.29 @@ -100,8 +100,8 @@ org.springframework.boot:spring-boot-starter:[2.7.18] - io.opentelemetry.instrumentation:opentelemetry-runtime-telemetry-java8:[2.9.0-alpha] - io.opentelemetry.instrumentation:opentelemetry-logback-appender-1.0:[2.9.0-alpha] + io.opentelemetry.instrumentation:opentelemetry-runtime-telemetry-java8:[2.12.0-alpha] + io.opentelemetry.instrumentation:opentelemetry-logback-appender-1.0:[2.12.0-alpha] diff --git a/sdk/servicebus/azure-messaging-servicebus-stress/src/main/java/com/azure/messaging/servicebus/stress/util/TelemetryHelper.java b/sdk/servicebus/azure-messaging-servicebus-stress/src/main/java/com/azure/messaging/servicebus/stress/util/TelemetryHelper.java index d043f1bb7729..e80d3b6cbff6 100644 --- a/sdk/servicebus/azure-messaging-servicebus-stress/src/main/java/com/azure/messaging/servicebus/stress/util/TelemetryHelper.java +++ b/sdk/servicebus/azure-messaging-servicebus-stress/src/main/java/com/azure/messaging/servicebus/stress/util/TelemetryHelper.java @@ -7,7 +7,7 @@ import com.azure.core.util.logging.LoggingEventBuilder; import com.azure.messaging.servicebus.ServiceBusClientBuilder; import com.azure.messaging.servicebus.ServiceBusException; -import com.azure.monitor.opentelemetry.exporter.AzureMonitorExporter; +import com.azure.monitor.opentelemetry.autoconfigure.AzureMonitorAutoConfigure; import io.opentelemetry.api.OpenTelemetry; import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; @@ -75,7 +75,7 @@ private static OpenTelemetry init() { } AutoConfiguredOpenTelemetrySdkBuilder sdkBuilder = AutoConfiguredOpenTelemetrySdk.builder(); if (applicationInsightsConnectionString != null) { - AzureMonitorExporter.customize(sdkBuilder, applicationInsightsConnectionString); + AzureMonitorAutoConfigure.customize(sdkBuilder, applicationInsightsConnectionString); } String instanceId = System.getenv("CONTAINER_NAME"); diff --git a/sdk/servicebus/azure-messaging-servicebus-track2-perf/README.md b/sdk/servicebus/azure-messaging-servicebus-track2-perf/README.md index 44ed279e1765..7f3ddea85854 100644 --- a/sdk/servicebus/azure-messaging-servicebus-track2-perf/README.md +++ b/sdk/servicebus/azure-messaging-servicebus-track2-perf/README.md @@ -30,4 +30,4 @@ For details on contributing to this repository, see the [contributing guide](htt 4. Push to the branch (`git push origin my-new-feature`) 5. Create new Pull Request -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fservicebus%2Fazure-messaging-servicebus-track2-perf%2FREADME.png) + diff --git a/sdk/servicebus/azure-messaging-servicebus-track2-perf/pom.xml b/sdk/servicebus/azure-messaging-servicebus-track2-perf/pom.xml index 2899a47b0ecf..9f1b18c98a08 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.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 diff --git a/sdk/servicebus/azure-messaging-servicebus/CHANGELOG.md b/sdk/servicebus/azure-messaging-servicebus/CHANGELOG.md index 46e7c33e4b40..e464711a0be9 100644 --- a/sdk/servicebus/azure-messaging-servicebus/CHANGELOG.md +++ b/sdk/servicebus/azure-messaging-servicebus/CHANGELOG.md @@ -10,8 +10,18 @@ * Fixed issue where OffsetDateTimeDescribedType would be translated to user's system time instead of UTC. ([42995](https://github.com/Azure/azure-sdk-for-java/pull/42995)) +## 7.17.9 (2025-02-25) + ### Other Changes +#### Dependency Updates + +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`. +- Upgraded `azure-core-amqp` from `2.9.12` to version `2.9.15`. +- Upgraded `azure-xml` from `1.1.0` to version `1.2.0`. +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. + + ## 7.17.8 (2025-01-09) ### Features Added @@ -856,4 +866,4 @@ our efforts can be found in the [Azure SDK Design Guidelines for [known-issue-binarydata-notfound]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/servicebus/azure-messaging-servicebus/known-issues.md#can-not-resolve-binarydata-or-noclassdeffounderror-version-700 -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fservicebus%2Fazure-messaging-servicebus%2FCHANGELOG.png) + diff --git a/sdk/servicebus/azure-messaging-servicebus/README.md b/sdk/servicebus/azure-messaging-servicebus/README.md index 29207e389e2d..60abc66a69da 100644 --- a/sdk/servicebus/azure-messaging-servicebus/README.md +++ b/sdk/servicebus/azure-messaging-servicebus/README.md @@ -70,7 +70,7 @@ add the direct dependency to your project as follows. com.azure azure-messaging-servicebus - 7.17.8 + 7.18.0-beta.2 ``` [//]: # ({x-version-update-end}) @@ -90,7 +90,7 @@ First, add the package: com.azure azure-identity - 1.14.2 + 1.15.3 ``` [//]: # ({x-version-update-end}) @@ -557,4 +557,4 @@ Guidelines](https://github.com/Azure/azure-sdk-for-java/blob/main/CONTRIBUTING.m [sync_receivemessages_implicit_prefetch]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/servicebus/azure-messaging-servicebus/docs/SyncReceiveAndPrefetch.md [peek_lock_mode_docs]: https://learn.microsoft.com/azure/service-bus-messaging/message-transfers-locks-settlement#peeklock [receive_and_delete_mode_docs]: https://learn.microsoft.com/azure/service-bus-messaging/message-transfers-locks-settlement#receiveanddelete -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fservicebus%2Fazure-messaging-servicebus%2FREADME.png) + diff --git a/sdk/servicebus/azure-messaging-servicebus/TROUBLESHOOTING.md b/sdk/servicebus/azure-messaging-servicebus/TROUBLESHOOTING.md index a48c5d94437d..c1e4316724c4 100644 --- a/sdk/servicebus/azure-messaging-servicebus/TROUBLESHOOTING.md +++ b/sdk/servicebus/azure-messaging-servicebus/TROUBLESHOOTING.md @@ -98,4 +98,4 @@ Error and warning level logs do not provide enough information. The period of at [Samples]: https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/servicebus/azure-messaging-servicebus/src/samples [SUPPORT]: https://github.com/Azure/azure-sdk-for-java/blob/main/SUPPORT.md -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fservicebus%2Fazure-messaging-servicebus%2FTROUBLESHOOTING.png) + diff --git a/sdk/servicebus/azure-messaging-servicebus/migration-guide.md b/sdk/servicebus/azure-messaging-servicebus/migration-guide.md index cf15a975b0c7..78c488006df3 100644 --- a/sdk/servicebus/azure-messaging-servicebus/migration-guide.md +++ b/sdk/servicebus/azure-messaging-servicebus/migration-guide.md @@ -494,7 +494,7 @@ the transaction is committed because it cannot route a receive operation through }); ``` -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fservicebus%2Fservice-bus%2FMIGRATIONGUIDE.png) + ## Additional samples diff --git a/sdk/servicebus/azure-messaging-servicebus/pom.xml b/sdk/servicebus/azure-messaging-servicebus/pom.xml index ad9fd468b492..01c179eedd7c 100644 --- a/sdk/servicebus/azure-messaging-servicebus/pom.xml +++ b/sdk/servicebus/azure-messaging-servicebus/pom.xml @@ -62,35 +62,35 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-xml - 1.1.0 + 1.2.0 com.azure azure-core-amqp - 2.9.12 + 2.9.16 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test @@ -117,28 +117,28 @@ com.azure azure-core-experimental - 1.0.0-beta.56 + 1.0.0-beta.60 test com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.52 + 1.0.0-beta.56 test io.opentelemetry opentelemetry-api - 1.43.0 + 1.46.0 test io.opentelemetry opentelemetry-sdk - 1.43.0 + 1.46.0 test diff --git a/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/ServiceBusSessionReactorReceiver.java b/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/ServiceBusSessionReactorReceiver.java index f366799507fd..42cb50c79f8b 100644 --- a/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/ServiceBusSessionReactorReceiver.java +++ b/sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/ServiceBusSessionReactorReceiver.java @@ -90,7 +90,12 @@ public Flux getEndpointStates() { @Override public Flux receive() { if (hasIdleTimeout) { - return sessionLink.receive().doOnNext(m -> { + final Mono beginIdleTimer = Mono.defer(() -> { + nextItemIdleTimeoutSink.emitNext(true, Sinks.EmitFailureHandler.FAIL_FAST); + return Mono.empty(); + }); + final Flux messages = sessionLink.receive(); + return beginIdleTimer.thenMany(messages).doOnNext(m -> { nextItemIdleTimeoutSink.emitNext(true, Sinks.EmitFailureHandler.FAIL_FAST); }); } else { diff --git a/sdk/servicebus/azure-messaging-servicebus/src/samples/README.md b/sdk/servicebus/azure-messaging-servicebus/src/samples/README.md index 2ce0575d28c4..713a2d33b116 100644 --- a/sdk/servicebus/azure-messaging-servicebus/src/samples/README.md +++ b/sdk/servicebus/azure-messaging-servicebus/src/samples/README.md @@ -99,4 +99,4 @@ Guidelines](https://github.com/Azure/azure-sdk-for-java/blob/main/CONTRIBUTING.m [ReceiveMessageAsyncUsingSasSample]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/servicebus/azure-messaging-servicebus/src/samples/java/com/azure/messaging/servicebus/ReceiveMessageUsingSasSample.java [AdvancedConfigurationSample]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/servicebus/azure-messaging-servicebus/src/samples/java/com/azure/messaging/servicebus/AdvancedConfigurationSample.java -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fservicebus%2Fazure-messaging-servicebus%2Fsrc%2Fsamples%2FREADME.png) + diff --git a/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ServiceBusSessionReactorReceiverTest.java b/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ServiceBusSessionReactorReceiverTest.java index 9433f4005607..05ebdfc4c576 100644 --- a/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ServiceBusSessionReactorReceiverTest.java +++ b/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ServiceBusSessionReactorReceiverTest.java @@ -170,4 +170,28 @@ public void completesOnIdleTimeout() { receiver.dispose(); } } + + @Test + public void completesOnNoMessagesIdleTimeout() { + // Arrange + final Duration idleTimeout = Duration.ofSeconds(3); + doNothing().when(sessionLink).dispose(); + final ServiceBusSessionAcquirer.Session session = mock(ServiceBusSessionAcquirer.Session.class); + when(session.getId()).thenReturn(SESSION_ID); + when(session.getLink()).thenReturn(sessionLink); + when(session.beginLockRenew(any(ServiceBusTracer.class), any(Duration.class))).thenReturn(Disposables.single()); + final ServiceBusSessionReactorReceiver receiver = new ServiceBusSessionReactorReceiver(LOGGER, + mock(ServiceBusTracer.class), session, idleTimeout, Duration.ofSeconds(1)); + + // Act and assert + try { + // Since there are no messages arrives at 'messages' Flux, the endpoint 'states' Flux should terminate after + // the idle timeout of 1 second. + final Flux messages = receiver.receive(); + final Flux states = receiver.getEndpointStates(); + StepVerifier.create(messages.takeUntilOther(states.then())).expectComplete().verify(Duration.ofSeconds(15)); + } finally { + receiver.dispose(); + } + } } 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 301ff465caaf..d015828e8121 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 @@ -6,6 +6,10 @@ import com.azure.core.amqp.exception.AmqpResponseCode; import com.azure.core.amqp.implementation.ConnectionStringProperties; import com.azure.core.credential.TokenCredential; +import com.azure.core.test.models.CustomMatcher; +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.util.BinaryData; import com.azure.core.util.Configuration; import com.azure.core.util.CoreUtils; @@ -33,6 +37,7 @@ import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; +import java.util.Arrays; import java.util.Base64; import java.util.Collections; import java.util.Date; @@ -101,16 +106,32 @@ public class TestUtils { // An application property key to identify where in the stream this message was created. static final String MESSAGE_POSITION_ID = "message-position"; + /** + * Sanitizer to remove header values for ServiceBusDlqSupplementaryAuthorization and + * ServiceBusSupplementaryAuthorization. + */ + public static final TestProxySanitizer AUTHORIZATION_HEADER; + + public static final List TEST_PROXY_SANITIZERS; + + public static final List TEST_PROXY_REQUEST_MATCHERS; + static { APPLICATION_PROPERTIES.put("test-name", ServiceBusMessage.class.getName()); APPLICATION_PROPERTIES.put("a-number", 10L); APPLICATION_PROPERTIES.put("status-code", AmqpResponseCode.OK.getValue()); - } - /** - * Namespace used to record tests. - */ - public static final String TEST_NAMESPACE = "sb-java-conniey-sb1"; + AUTHORIZATION_HEADER = new TestProxySanitizer("SupplementaryAuthorization", null, + "SharedAccessSignature sr=https%3A%2F%2Ffoo.servicebus.windows.net&sig=dummyValue%3D&se=1687267490&skn=dummyKey", + TestProxySanitizerType.HEADER); + TEST_PROXY_SANITIZERS = Collections.singletonList(AUTHORIZATION_HEADER); + + final List skippedHeaders + = Arrays.asList("ServiceBusDlqSupplementaryAuthorization", "ServiceBusSupplementaryAuthorization"); + final CustomMatcher customMatcher = new CustomMatcher().setExcludedHeaders(skippedHeaders); + + TEST_PROXY_REQUEST_MATCHERS = Collections.singletonList(customMatcher); + } /** * Gets the namespace connection string. diff --git a/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/administration/ServiceBusAdministrationAsyncClientIntegrationTest.java b/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/administration/ServiceBusAdministrationAsyncClientIntegrationTest.java index a34e867db56f..41ba69b1a2ea 100644 --- a/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/administration/ServiceBusAdministrationAsyncClientIntegrationTest.java +++ b/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/administration/ServiceBusAdministrationAsyncClientIntegrationTest.java @@ -15,10 +15,6 @@ import com.azure.core.http.policy.HttpLogOptions; import com.azure.core.test.InterceptorManager; import com.azure.core.test.TestProxyTestBase; -import com.azure.core.test.models.CustomMatcher; -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.utils.MockTokenCredential; import com.azure.core.util.CoreUtils; import com.azure.identity.DefaultAzureCredentialBuilder; @@ -52,12 +48,13 @@ import java.time.Clock; import java.time.Duration; import java.time.OffsetDateTime; -import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Stream; +import static com.azure.messaging.servicebus.TestUtils.TEST_PROXY_REQUEST_MATCHERS; +import static com.azure.messaging.servicebus.TestUtils.TEST_PROXY_SANITIZERS; import static com.azure.messaging.servicebus.TestUtils.assertAuthorizationRules; import static com.azure.messaging.servicebus.TestUtils.getEntityName; import static com.azure.messaging.servicebus.TestUtils.getSessionSubscriptionBaseName; @@ -78,29 +75,6 @@ class ServiceBusAdministrationAsyncClientIntegrationTest extends TestProxyTestBa private static final Duration TIMEOUT = Duration.ofSeconds(20); private static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(10); - /** - * Sanitizer to remove header values for ServiceBusDlqSupplementaryAuthorization and - * ServiceBusSupplementaryAuthorization. - */ - static final TestProxySanitizer AUTHORIZATION_HEADER; - - static final List TEST_PROXY_SANITIZERS; - - static final List TEST_PROXY_REQUEST_MATCHERS; - - static { - AUTHORIZATION_HEADER = new TestProxySanitizer("SupplementaryAuthorization", null, - "SharedAccessSignature sr=https%3A%2F%2Ffoo.servicebus.windows.net&sig=dummyValue%3D&se=1687267490&skn=dummyKey", - TestProxySanitizerType.HEADER); - TEST_PROXY_SANITIZERS = Collections.singletonList(AUTHORIZATION_HEADER); - - final List skippedHeaders - = Arrays.asList("ServiceBusDlqSupplementaryAuthorization", "ServiceBusSupplementaryAuthorization"); - final CustomMatcher customMatcher = new CustomMatcher().setExcludedHeaders(skippedHeaders); - - TEST_PROXY_REQUEST_MATCHERS = Collections.singletonList(customMatcher); - } - private final AtomicReference credentialCached = new AtomicReference<>(); public static Stream createHttpClients() { diff --git a/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/implementation/ServiceBusAdministrationClientImplIntegrationTests.java b/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/implementation/ServiceBusAdministrationClientImplIntegrationTests.java index 559f38d08d58..306c4dda80a6 100644 --- a/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/implementation/ServiceBusAdministrationClientImplIntegrationTests.java +++ b/sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/implementation/ServiceBusAdministrationClientImplIntegrationTests.java @@ -4,9 +4,11 @@ package com.azure.messaging.servicebus.implementation; import com.azure.core.amqp.implementation.ConnectionStringProperties; +import com.azure.core.credential.TokenCredential; import com.azure.core.http.HttpClient; import com.azure.core.http.HttpPipeline; import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.policy.AddHeadersFromContextPolicy; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.policy.HttpLogOptions; import com.azure.core.http.policy.HttpLoggingPolicy; @@ -14,10 +16,14 @@ import com.azure.core.http.policy.UserAgentPolicy; import com.azure.core.http.rest.Response; import com.azure.core.test.TestProxyTestBase; +import com.azure.core.test.utils.MockTokenCredential; import com.azure.core.util.Context; +import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; +import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.messaging.servicebus.ServiceBusServiceVersion; import com.azure.messaging.servicebus.TestUtils; +import com.azure.messaging.servicebus.administration.ServiceBusSupplementaryAuthHeaderPolicy; import com.azure.messaging.servicebus.administration.implementation.EntitiesImpl; import com.azure.messaging.servicebus.administration.implementation.EntityHelper; import com.azure.messaging.servicebus.administration.implementation.ServiceBusManagementClientImpl; @@ -36,11 +42,13 @@ import java.time.Duration; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.atomic.AtomicReference; 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.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * Integration tests for {@link ServiceBusManagementClientImpl}. @@ -50,7 +58,9 @@ class ServiceBusAdministrationClientImplIntegrationTests extends TestProxyTestBa = new ClientLogger(ServiceBusAdministrationClientImplIntegrationTests.class); private static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(30); private static final ServiceBusManagementSerializer SERIALIZER = new ServiceBusManagementSerializer(); + private final Duration timeout = Duration.ofSeconds(30); + private final AtomicReference credentialCached = new AtomicReference<>(); /** * Verifies we can get queue information. @@ -205,33 +215,59 @@ void listQueuesImplementation(HttpClient httpClient) { } private ServiceBusManagementClientImpl createClient(HttpClient httpClient) { - final String connectionString = interceptorManager.isPlaybackMode() - ? "Endpoint=sb://foo" + TestUtils.getEndpoint() - + ";SharedAccessKeyName=dummyKey;SharedAccessKey=dummyAccessKey" - : TestUtils.getConnectionString(false); - final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); - final ServiceBusSharedKeyCredential credential - = new ServiceBusSharedKeyCredential(properties.getSharedAccessKeyName(), properties.getSharedAccessKey()); final List policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); - policies.add(new ServiceBusTokenCredentialHttpPolicy(credential)); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); + final TokenCredential tokenCredential; final HttpClient httpClientToUse; + final String fullyQualifiedNamespace; if (interceptorManager.isPlaybackMode()) { + fullyQualifiedNamespace = TestUtils.getFullyQualifiedDomainName(true); + httpClientToUse = interceptorManager.getPlaybackClient(); + tokenCredential = new MockTokenCredential(); } else if (interceptorManager.isLiveMode()) { + fullyQualifiedNamespace = TestUtils.getFullyQualifiedDomainName(false); + assumeTrue(!CoreUtils.isNullOrEmpty(fullyQualifiedNamespace), "FullyQualifiedDomainName is not set."); + httpClientToUse = httpClient; - } else { + tokenCredential = TestUtils.getPipelineCredential(credentialCached); + } else if (interceptorManager.isRecordMode()) { + // Record Mode. + final String connectionString = TestUtils.getConnectionString(false); + if (CoreUtils.isNullOrEmpty(connectionString)) { + fullyQualifiedNamespace = TestUtils.getFullyQualifiedDomainName(false); + assumeTrue(!CoreUtils.isNullOrEmpty(fullyQualifiedNamespace), "fullyQualifiedNamespace is not set."); + + tokenCredential = new DefaultAzureCredentialBuilder().build(); + } else { + tokenCredential = new ServiceBusSharedKeyCredential(connectionString); + + ConnectionStringProperties properties = new ConnectionStringProperties(connectionString); + fullyQualifiedNamespace = properties.getEndpoint().getHost(); + } + httpClientToUse = httpClient; policies.add(interceptorManager.getRecordPolicy()); + } else { + throw new UnsupportedOperationException("Test mode is not supported: " + getTestMode()); + } + + if (!interceptorManager.isLiveMode()) { + interceptorManager.addSanitizers(TestUtils.TEST_PROXY_SANITIZERS); + interceptorManager.addMatchers(TestUtils.TEST_PROXY_REQUEST_MATCHERS); } + policies.add(new ServiceBusTokenCredentialHttpPolicy(tokenCredential)); + policies.add(new AddHeadersFromContextPolicy()); + policies.add(new ServiceBusSupplementaryAuthHeaderPolicy(tokenCredential)); + final HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(httpClientToUse) .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); - return new ServiceBusManagementClientImpl(pipeline, SERIALIZER, properties.getEndpoint().getHost(), + return new ServiceBusManagementClientImpl(pipeline, SERIALIZER, fullyQualifiedNamespace, ServiceBusServiceVersion.getLatest().getVersion()); } diff --git a/sdk/servicebus/microsoft-azure-servicebus/README.md b/sdk/servicebus/microsoft-azure-servicebus/README.md index 3883c5d9b10d..87b90b02b846 100644 --- a/sdk/servicebus/microsoft-azure-servicebus/README.md +++ b/sdk/servicebus/microsoft-azure-servicebus/README.md @@ -85,4 +85,4 @@ To use a proxy for unit tests, set an environment variable `RUN_WITH_PROXY` to ` 9. Click "Apply" and then "Run" 10. You should have a new view next to the package explorer called JUnit showing the running tests and see Console outputs depending on which test currently runs. If you do not see the JUnit tab go to Window > Show view > Other... > Java > JUnit -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fservicebus%2FREADME.png) + diff --git a/sdk/servicebus/microsoft-azure-servicebus/pom.xml b/sdk/servicebus/microsoft-azure-servicebus/pom.xml index a398ee43126f..c4880c62bde6 100644 --- a/sdk/servicebus/microsoft-azure-servicebus/pom.xml +++ b/sdk/servicebus/microsoft-azure-servicebus/pom.xml @@ -45,7 +45,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 15 true diff --git a/sdk/servicebus/test-resources.json b/sdk/servicebus/test-resources.json index 717792dfa590..0e8ab3e18f0d 100644 --- a/sdk/servicebus/test-resources.json +++ b/sdk/servicebus/test-resources.json @@ -71,7 +71,9 @@ "sku": { "name": "Premium" }, - "properties": {}, + "properties": { + "disableLocalAuth": true + }, "resources": [ { "apiVersion": "2021-01-01-preview", diff --git a/sdk/servicefabric/azure-resourcemanager-servicefabric/README.md b/sdk/servicefabric/azure-resourcemanager-servicefabric/README.md index 18b6a32de682..7256b0126114 100644 --- a/sdk/servicefabric/azure-resourcemanager-servicefabric/README.md +++ b/sdk/servicefabric/azure-resourcemanager-servicefabric/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-servicefabric - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fservicefabric%2Fazure-resourcemanager-servicefabric%2FREADME.png) + diff --git a/sdk/servicefabric/azure-resourcemanager-servicefabric/pom.xml b/sdk/servicefabric/azure-resourcemanager-servicefabric/pom.xml index 0bdff9887adf..1f30cfca9b94 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.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/servicefabricmanagedclusters/azure-resourcemanager-servicefabricmanagedclusters/README.md b/sdk/servicefabricmanagedclusters/azure-resourcemanager-servicefabricmanagedclusters/README.md index 185e4356a2b1..d994bbd5e9e2 100644 --- a/sdk/servicefabricmanagedclusters/azure-resourcemanager-servicefabricmanagedclusters/README.md +++ b/sdk/servicefabricmanagedclusters/azure-resourcemanager-servicefabricmanagedclusters/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-servicefabricmanagedclusters - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -114,4 +114,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fservicefabricmanagedclusters%2Fazure-resourcemanager-servicefabricmanagedclusters%2FREADME.png) + diff --git a/sdk/servicefabricmanagedclusters/azure-resourcemanager-servicefabricmanagedclusters/pom.xml b/sdk/servicefabricmanagedclusters/azure-resourcemanager-servicefabricmanagedclusters/pom.xml index edb8141dcda9..95c1a9cbd257 100644 --- a/sdk/servicefabricmanagedclusters/azure-resourcemanager-servicefabricmanagedclusters/pom.xml +++ b/sdk/servicefabricmanagedclusters/azure-resourcemanager-servicefabricmanagedclusters/pom.xml @@ -51,34 +51,34 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-json - 1.3.0 + 1.5.0 com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/servicelinker/azure-resourcemanager-servicelinker/README.md b/sdk/servicelinker/azure-resourcemanager-servicelinker/README.md index febe99d4091d..cffab9cb503f 100644 --- a/sdk/servicelinker/azure-resourcemanager-servicelinker/README.md +++ b/sdk/servicelinker/azure-resourcemanager-servicelinker/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-servicelinker - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fservicelinker%2Fazure-resourcemanager-servicelinker%2FREADME.png) + diff --git a/sdk/servicelinker/azure-resourcemanager-servicelinker/pom.xml b/sdk/servicelinker/azure-resourcemanager-servicelinker/pom.xml index e9fc7bc92d76..ad7f743e0d02 100644 --- a/sdk/servicelinker/azure-resourcemanager-servicelinker/pom.xml +++ b/sdk/servicelinker/azure-resourcemanager-servicelinker/pom.xml @@ -51,29 +51,29 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager - 2.46.0 + 2.48.0 test diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/CHANGELOG.md b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/CHANGELOG.md index 9185626764f3..ed7455771113 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/CHANGELOG.md +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.1.0-beta.2 (Unreleased) +## 1.2.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,24 @@ ### Other Changes +## 1.1.0 (2025-02-06) + +- Azure Resource Manager Traffic Controller client library for Java. This package contains Microsoft Azure SDK for Traffic Controller Management SDK. Traffic Controller Provider management API. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). + +### Breaking Changes + +#### `models.FrontendListResult` was removed + +#### `models.OperationListResult` was removed + +#### `models.AssociationListResult` was removed + +#### `models.TrafficControllerListResult` was removed + +#### `models.ResourceId` was modified + +* `withId(java.lang.String)` was removed + ## 1.1.0-beta.1 (2024-09-30) - Azure Resource Manager TrafficController client library for Java. This package contains Microsoft Azure SDK for TrafficController Management SDK. Traffic Controller Provider management API. Package tag 2024-05-01-preview. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/README.md b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/README.md index c2472b49b1bb..6f344d4365db 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/README.md +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/README.md @@ -1,8 +1,8 @@ -# Azure Resource Manager TrafficController client library for Java +# Azure Resource Manager Traffic Controller client library for Java -Azure Resource Manager TrafficController client library for Java. +Azure Resource Manager Traffic Controller client library for Java. -This package contains Microsoft Azure SDK for TrafficController Management SDK. Traffic Controller Provider management API. Package tag 2024-05-01-preview. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). +This package contains Microsoft Azure SDK for Traffic Controller Management SDK. Traffic Controller Provider management API. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt). ## We'd love to hear your feedback @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-servicenetworking - 1.1.0-beta.1 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -70,6 +70,13 @@ See [API design][design] for general introduction on design and key concepts on ## Examples +```java +trafficController = trafficControllerManager.trafficControllerInterfaces() + .define(interfaceName) + .withRegion(REGION) + .withExistingResourceGroup(resourceGroupName) + .create(); +``` [Code snippets and samples](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/servicenetworking/azure-resourcemanager-servicenetworking/SAMPLE.md) @@ -101,4 +108,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fservicenetworking%2Fazure-resourcemanager-servicenetworking%2FREADME.png) + diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/SAMPLE.md b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/SAMPLE.md index d1e19dde43e3..21eaf2ca2f36 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/SAMPLE.md +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/SAMPLE.md @@ -49,9 +49,7 @@ import com.azure.resourcemanager.servicenetworking.models.AssociationType; */ public final class AssociationsInterfaceCreateOrUpdateSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * AssociationPut.json + * x-ms-original-file: 2025-01-01/AssociationPut.json */ /** * Sample code: Put Association. @@ -79,9 +77,7 @@ public final class AssociationsInterfaceCreateOrUpdateSamples { */ public final class AssociationsInterfaceDeleteSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * AssociationDelete.json + * x-ms-original-file: 2025-01-01/AssociationDelete.json */ /** * Sample code: Delete Association. @@ -102,9 +98,7 @@ public final class AssociationsInterfaceDeleteSamples { */ public final class AssociationsInterfaceGetSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * AssociationGet.json + * x-ms-original-file: 2025-01-01/AssociationGet.json */ /** * Sample code: Get Association. @@ -125,9 +119,7 @@ public final class AssociationsInterfaceGetSamples { */ public final class AssociationsInterfaceListByTrafficControllerSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * AssociationsGet.json + * x-ms-original-file: 2025-01-01/AssociationsGet.json */ /** * Sample code: Get Associations. @@ -153,9 +145,7 @@ import com.azure.resourcemanager.servicenetworking.models.AssociationUpdatePrope */ public final class AssociationsInterfaceUpdateSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * AssociationPatch.json + * x-ms-original-file: 2025-01-01/AssociationPatch.json */ /** * Sample code: Update Association. @@ -185,9 +175,7 @@ import com.azure.resourcemanager.servicenetworking.models.FrontendProperties; */ public final class FrontendsInterfaceCreateOrUpdateSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * FrontendPut.json + * x-ms-original-file: 2025-01-01/FrontendPut.json */ /** * Sample code: Put Frontend. @@ -213,9 +201,7 @@ public final class FrontendsInterfaceCreateOrUpdateSamples { */ public final class FrontendsInterfaceDeleteSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * FrontendDelete.json + * x-ms-original-file: 2025-01-01/FrontendDelete.json */ /** * Sample code: Delete Frontend. @@ -236,9 +222,7 @@ public final class FrontendsInterfaceDeleteSamples { */ public final class FrontendsInterfaceGetSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * FrontendGet.json + * x-ms-original-file: 2025-01-01/FrontendGet.json */ /** * Sample code: Get Frontend. @@ -259,9 +243,7 @@ public final class FrontendsInterfaceGetSamples { */ public final class FrontendsInterfaceListByTrafficControllerSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * FrontendsGet.json + * x-ms-original-file: 2025-01-01/FrontendsGet.json */ /** * Sample code: Get Frontends. @@ -284,9 +266,7 @@ import com.azure.resourcemanager.servicenetworking.models.Frontend; */ public final class FrontendsInterfaceUpdateSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * FrontendPatch.json + * x-ms-original-file: 2025-01-01/FrontendPatch.json */ /** * Sample code: Update Frontend. @@ -310,9 +290,7 @@ public final class FrontendsInterfaceUpdateSamples { */ public final class OperationsListSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * OperationsList.json + * x-ms-original-file: 2025-01-01/OperationsList.json */ /** * Sample code: Get Operations List. @@ -336,9 +314,7 @@ import com.azure.resourcemanager.servicenetworking.models.WafPolicy; */ public final class SecurityPoliciesInterfaceCreateOrUpdateSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * SecurityPolicyPut.json + * x-ms-original-file: 2025-01-01/SecurityPolicyPut.json */ /** * Sample code: Put SecurityPolicy. @@ -365,9 +341,7 @@ public final class SecurityPoliciesInterfaceCreateOrUpdateSamples { */ public final class SecurityPoliciesInterfaceDeleteSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * SecurityPolicyDelete.json + * x-ms-original-file: 2025-01-01/SecurityPolicyDelete.json */ /** * Sample code: Delete SecurityPolicy. @@ -389,9 +363,7 @@ public final class SecurityPoliciesInterfaceDeleteSamples { */ public final class SecurityPoliciesInterfaceGetSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * SecurityPolicyGet.json + * x-ms-original-file: 2025-01-01/SecurityPolicyGet.json */ /** * Sample code: Get SecurityPolicy. @@ -412,9 +384,7 @@ public final class SecurityPoliciesInterfaceGetSamples { */ public final class SecurityPoliciesInterfaceListByTrafficControllerSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * SecurityPoliciesGetList.json + * x-ms-original-file: 2025-01-01/SecurityPoliciesGetList.json */ /** * Sample code: Get SecurityPolicies. @@ -433,16 +403,14 @@ public final class SecurityPoliciesInterfaceListByTrafficControllerSamples { ```java import com.azure.resourcemanager.servicenetworking.models.SecurityPolicy; import com.azure.resourcemanager.servicenetworking.models.SecurityPolicyUpdateProperties; -import com.azure.resourcemanager.servicenetworking.models.WafPolicyUpdate; +import com.azure.resourcemanager.servicenetworking.models.WafPolicy; /** * Samples for SecurityPoliciesInterface Update. */ public final class SecurityPoliciesInterfaceUpdateSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * SecurityPolicyPatch.json + * x-ms-original-file: 2025-01-01/SecurityPolicyPatch.json */ /** * Sample code: Update SecurityPolicy. @@ -455,7 +423,7 @@ public final class SecurityPoliciesInterfaceUpdateSamples { .getWithResponse("rg1", "tc1", "sp1", com.azure.core.util.Context.NONE) .getValue(); resource.update() - .withProperties(new SecurityPolicyUpdateProperties().withWafPolicy(new WafPolicyUpdate().withId( + .withProperties(new SecurityPolicyUpdateProperties().withWafPolicy(new WafPolicy().withId( "/subscriptions/subid/resourcegroups/rg1/providers/Microsoft.Networking/applicationGatewayWebApplicationFirewallPolicies/wp-0"))) .apply(); } @@ -473,9 +441,7 @@ import java.util.Map; */ public final class TrafficControllerInterfaceCreateOrUpdateSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * TrafficControllerPut.json + * x-ms-original-file: 2025-01-01/TrafficControllerPut.json */ /** * Sample code: Put Traffic Controller. @@ -514,9 +480,7 @@ public final class TrafficControllerInterfaceCreateOrUpdateSamples { */ public final class TrafficControllerInterfaceDeleteSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * TrafficControllerDelete.json + * x-ms-original-file: 2025-01-01/TrafficControllerDelete.json */ /** * Sample code: Delete Traffic Controller. @@ -538,9 +502,7 @@ public final class TrafficControllerInterfaceDeleteSamples { */ public final class TrafficControllerInterfaceGetByResourceGroupSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * TrafficControllerGet.json + * x-ms-original-file: 2025-01-01/TrafficControllerGet.json */ /** * Sample code: Get Traffic Controller. @@ -563,9 +525,7 @@ public final class TrafficControllerInterfaceGetByResourceGroupSamples { */ public final class TrafficControllerInterfaceListSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * TrafficControllersGetList.json + * x-ms-original-file: 2025-01-01/TrafficControllersGetList.json */ /** * Sample code: Get Traffic Controllers List. @@ -587,9 +547,7 @@ public final class TrafficControllerInterfaceListSamples { */ public final class TrafficControllerInterfaceListByResourceGroupSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * TrafficControllersGet.json + * x-ms-original-file: 2025-01-01/TrafficControllersGet.json */ /** * Sample code: Get Traffic Controllers. @@ -615,9 +573,7 @@ import java.util.Map; */ public final class TrafficControllerInterfaceUpdateSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * TrafficControllerPatch.json + * x-ms-original-file: 2025-01-01/TrafficControllerPatch.json */ /** * Sample code: Patch Traffic Controller. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/pom.xml b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/pom.xml index a38b83aaee8a..b701931096aa 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/pom.xml +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/pom.xml @@ -1,7 +1,7 @@ 4.0.0 @@ -14,11 +14,11 @@ com.azure.resourcemanager azure-resourcemanager-servicenetworking - 1.1.0-beta.2 + 1.2.0-beta.1 jar - Microsoft Azure SDK for TrafficController Management - This package contains Microsoft Azure SDK for TrafficController Management SDK. For documentation on how to use this package, please see https://aka.ms/azsdk/java/mgmt. Traffic Controller Provider management API. Package tag 2024-05-01-preview. + Microsoft Azure SDK for Traffic Controller Management + This package contains Microsoft Azure SDK for Traffic Controller Management SDK. For documentation on how to use this package, please see https://aka.ms/azsdk/java/mgmt. Traffic Controller Provider management API. https://github.com/Azure/azure-sdk-for-java @@ -45,35 +45,36 @@ UTF-8 0 0 + false true com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/TrafficControllerManager.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/TrafficControllerManager.java index a69da110ab2e..ad4672f26832 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/TrafficControllerManager.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/TrafficControllerManager.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking; @@ -11,6 +11,7 @@ import com.azure.core.http.HttpPipelinePosition; import com.azure.core.http.policy.AddDatePolicy; import com.azure.core.http.policy.AddHeadersFromContextPolicy; +import com.azure.core.http.policy.BearerTokenAuthenticationPolicy; import com.azure.core.http.policy.HttpLogOptions; import com.azure.core.http.policy.HttpLoggingPolicy; import com.azure.core.http.policy.HttpPipelinePolicy; @@ -19,9 +20,9 @@ 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.management.http.policy.ArmChallengeAuthenticationPolicy; import com.azure.core.management.profile.AzureProfile; import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.servicenetworking.fluent.TrafficControllerManagementClient; import com.azure.resourcemanager.servicenetworking.implementation.AssociationsInterfacesImpl; @@ -39,6 +40,7 @@ import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; @@ -47,16 +49,16 @@ * Traffic Controller Provider management API. */ public final class TrafficControllerManager { - private Operations operations; - - private TrafficControllerInterfaces trafficControllerInterfaces; - private AssociationsInterfaces associationsInterfaces; private FrontendsInterfaces frontendsInterfaces; private SecurityPoliciesInterfaces securityPoliciesInterfaces; + private TrafficControllerInterfaces trafficControllerInterfaces; + + private Operations operations; + private final TrafficControllerManagementClient clientObject; private TrafficControllerManager(HttpPipeline httpPipeline, AzureProfile profile, Duration defaultPollInterval) { @@ -70,11 +72,11 @@ private TrafficControllerManager(HttpPipeline httpPipeline, AzureProfile profile } /** - * Creates an instance of TrafficController service API entry point. + * Creates an instance of Traffic Controller service API entry point. * * @param credential the credential to use. * @param profile the Azure profile for client. - * @return the TrafficController service API instance. + * @return the Traffic Controller service API instance. */ public static TrafficControllerManager authenticate(TokenCredential credential, AzureProfile profile) { Objects.requireNonNull(credential, "'credential' cannot be null."); @@ -83,11 +85,11 @@ public static TrafficControllerManager authenticate(TokenCredential credential, } /** - * Creates an instance of TrafficController service API entry point. + * Creates an instance of Traffic Controller service API entry point. * * @param httpPipeline the {@link HttpPipeline} configured with Azure authentication credential. * @param profile the Azure profile for client. - * @return the TrafficController service API instance. + * @return the Traffic Controller service API instance. */ public static TrafficControllerManager authenticate(HttpPipeline httpPipeline, AzureProfile profile) { Objects.requireNonNull(httpPipeline, "'httpPipeline' cannot be null."); @@ -109,6 +111,9 @@ public static Configurable configure() { */ public static final class Configurable { private static final ClientLogger LOGGER = new ClientLogger(Configurable.class); + private static final String SDK_VERSION = "version"; + private static final Map PROPERTIES + = CoreUtils.getProperties("azure-resourcemanager-servicenetworking.properties"); private HttpClient httpClient; private HttpLogOptions httpLogOptions; @@ -206,22 +211,24 @@ public Configurable withDefaultPollInterval(Duration defaultPollInterval) { } /** - * Creates an instance of TrafficController service API entry point. + * Creates an instance of Traffic Controller service API entry point. * * @param credential the credential to use. * @param profile the Azure profile for client. - * @return the TrafficController service API instance. + * @return the Traffic Controller service API instance. */ public TrafficControllerManager authenticate(TokenCredential credential, AzureProfile profile) { Objects.requireNonNull(credential, "'credential' cannot be null."); Objects.requireNonNull(profile, "'profile' cannot be null."); + String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); + StringBuilder userAgentBuilder = new StringBuilder(); userAgentBuilder.append("azsdk-java") .append("-") .append("com.azure.resourcemanager.servicenetworking") .append("/") - .append("1.1.0-beta.1"); + .append(clientVersion); if (!Configuration.getGlobalConfiguration().get("AZURE_TELEMETRY_DISABLED", false)) { userAgentBuilder.append(" (") .append(Configuration.getGlobalConfiguration().get("java.version")) @@ -254,7 +261,7 @@ public TrafficControllerManager authenticate(TokenCredential credential, AzurePr HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy); policies.add(new AddDatePolicy()); - policies.add(new ArmChallengeAuthenticationPolicy(credential, scopes.toArray(new String[0]))); + policies.add(new BearerTokenAuthenticationPolicy(credential, scopes.toArray(new String[0]))); policies.addAll(this.policies.stream() .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) .collect(Collectors.toList())); @@ -267,31 +274,6 @@ public TrafficControllerManager authenticate(TokenCredential credential, AzurePr } } - /** - * Gets the resource collection API of Operations. - * - * @return Resource collection API of Operations. - */ - public Operations operations() { - if (this.operations == null) { - this.operations = new OperationsImpl(clientObject.getOperations(), this); - } - return operations; - } - - /** - * Gets the resource collection API of TrafficControllerInterfaces. It manages TrafficController. - * - * @return Resource collection API of TrafficControllerInterfaces. - */ - public TrafficControllerInterfaces trafficControllerInterfaces() { - if (this.trafficControllerInterfaces == null) { - this.trafficControllerInterfaces - = new TrafficControllerInterfacesImpl(clientObject.getTrafficControllerInterfaces(), this); - } - return trafficControllerInterfaces; - } - /** * Gets the resource collection API of AssociationsInterfaces. It manages Association. * @@ -330,6 +312,31 @@ public SecurityPoliciesInterfaces securityPoliciesInterfaces() { return securityPoliciesInterfaces; } + /** + * Gets the resource collection API of TrafficControllerInterfaces. It manages TrafficController. + * + * @return Resource collection API of TrafficControllerInterfaces. + */ + public TrafficControllerInterfaces trafficControllerInterfaces() { + if (this.trafficControllerInterfaces == null) { + this.trafficControllerInterfaces + = new TrafficControllerInterfacesImpl(clientObject.getTrafficControllerInterfaces(), this); + } + return trafficControllerInterfaces; + } + + /** + * Gets the resource collection API of Operations. + * + * @return Resource collection API of Operations. + */ + public Operations operations() { + if (this.operations == null) { + this.operations = new OperationsImpl(clientObject.getOperations(), this); + } + return operations; + } + /** * Gets wrapped service client TrafficControllerManagementClient providing direct access to the underlying * auto-generated API implementation, based on Azure REST API. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/AssociationsInterfacesClient.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/AssociationsInterfacesClient.java index 652196137f93..59f423c733a3 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/AssociationsInterfacesClient.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/AssociationsInterfacesClient.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.fluent; @@ -18,34 +18,6 @@ * An instance of this class provides access to all the operations defined in AssociationsInterfacesClient. */ public interface AssociationsInterfacesClient { - /** - * List Association resources by TrafficController. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param trafficControllerName traffic controller name for path. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Association list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName); - - /** - * List Association resources by TrafficController. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param trafficControllerName traffic controller name for path. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Association list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName, - Context context); - /** * Get a Association. * @@ -232,4 +204,32 @@ SyncPoller, Void> beginDelete(String resourceGroupName, String */ @ServiceMethod(returns = ReturnType.SINGLE) void delete(String resourceGroupName, String trafficControllerName, String associationName, Context context); + + /** + * List Association resources by TrafficController. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param trafficControllerName traffic controller name for path. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Association list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName); + + /** + * List Association resources by TrafficController. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param trafficControllerName traffic controller name for path. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Association list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName, + Context context); } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/FrontendsInterfacesClient.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/FrontendsInterfacesClient.java index 2228a5c811c4..b051c9ff4540 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/FrontendsInterfacesClient.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/FrontendsInterfacesClient.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.fluent; @@ -18,34 +18,6 @@ * An instance of this class provides access to all the operations defined in FrontendsInterfacesClient. */ public interface FrontendsInterfacesClient { - /** - * List Frontend resources by TrafficController. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param trafficControllerName traffic controller name for path. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Frontend list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName); - - /** - * List Frontend resources by TrafficController. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param trafficControllerName traffic controller name for path. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Frontend list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName, - Context context); - /** * Get a Frontend. * @@ -232,4 +204,32 @@ SyncPoller, Void> beginDelete(String resourceGroupName, String */ @ServiceMethod(returns = ReturnType.SINGLE) void delete(String resourceGroupName, String trafficControllerName, String frontendName, Context context); + + /** + * List Frontend resources by TrafficController. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param trafficControllerName traffic controller name for path. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Frontend list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName); + + /** + * List Frontend resources by TrafficController. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param trafficControllerName traffic controller name for path. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Frontend list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName, + Context context); } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/OperationsClient.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/OperationsClient.java index 7bd4928b414e..c556fe9d93f7 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/OperationsClient.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/OperationsClient.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.fluent; diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/SecurityPoliciesInterfacesClient.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/SecurityPoliciesInterfacesClient.java index abc926afd38e..e5fac96da745 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/SecurityPoliciesInterfacesClient.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/SecurityPoliciesInterfacesClient.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.fluent; @@ -18,34 +18,6 @@ * An instance of this class provides access to all the operations defined in SecurityPoliciesInterfacesClient. */ public interface SecurityPoliciesInterfacesClient { - /** - * List SecurityPolicy resources by TrafficController. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param trafficControllerName traffic controller name for path. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SecurityPolicy list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName); - - /** - * List SecurityPolicy resources by TrafficController. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param trafficControllerName traffic controller name for path. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SecurityPolicy list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName, - Context context); - /** * Get a SecurityPolicy. * @@ -232,4 +204,32 @@ SyncPoller, Void> beginDelete(String resourceGroupName, String */ @ServiceMethod(returns = ReturnType.SINGLE) void delete(String resourceGroupName, String trafficControllerName, String securityPolicyName, Context context); + + /** + * List SecurityPolicy resources by TrafficController. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param trafficControllerName traffic controller name for path. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SecurityPolicy list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName); + + /** + * List SecurityPolicy resources by TrafficController. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param trafficControllerName traffic controller name for path. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SecurityPolicy list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName, + Context context); } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/TrafficControllerInterfacesClient.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/TrafficControllerInterfacesClient.java index 763962edf173..18d04562422c 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/TrafficControllerInterfacesClient.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/TrafficControllerInterfacesClient.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.fluent; @@ -18,53 +18,6 @@ * An instance of this class provides access to all the operations defined in TrafficControllerInterfacesClient. */ public interface TrafficControllerInterfacesClient { - /** - * List TrafficController resources by subscription ID. - * - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a TrafficController list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable list(); - - /** - * List TrafficController resources by subscription ID. - * - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a TrafficController list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable list(Context context); - - /** - * List TrafficController resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a TrafficController list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable listByResourceGroup(String resourceGroupName); - - /** - * List TrafficController resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a TrafficController list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - PagedIterable listByResourceGroup(String resourceGroupName, Context context); - /** * Get a TrafficController. * @@ -241,4 +194,51 @@ SyncPoller, Void> beginDelete(String resourceGroupName, String */ @ServiceMethod(returns = ReturnType.SINGLE) void delete(String resourceGroupName, String trafficControllerName, Context context); + + /** + * List TrafficController resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a TrafficController list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByResourceGroup(String resourceGroupName); + + /** + * List TrafficController resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a TrafficController list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable listByResourceGroup(String resourceGroupName, Context context); + + /** + * List TrafficController resources by subscription ID. + * + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a TrafficController list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(); + + /** + * List TrafficController resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a TrafficController list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + PagedIterable list(Context context); } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/TrafficControllerManagementClient.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/TrafficControllerManagementClient.java index 769ca8b96cfe..2589b6666a6e 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/TrafficControllerManagementClient.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/TrafficControllerManagementClient.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.fluent; @@ -12,26 +12,26 @@ */ public interface TrafficControllerManagementClient { /** - * Gets The ID of the target subscription. - * - * @return the subscriptionId value. - */ - String getSubscriptionId(); - - /** - * Gets server parameter. + * Gets Service host. * * @return the endpoint value. */ String getEndpoint(); /** - * Gets Api Version. + * Gets Version parameter. * * @return the apiVersion value. */ String getApiVersion(); + /** + * Gets The ID of the target subscription. The value must be an UUID. + * + * @return the subscriptionId value. + */ + String getSubscriptionId(); + /** * Gets The HTTP pipeline to send requests through. * @@ -46,20 +46,6 @@ public interface TrafficControllerManagementClient { */ Duration getDefaultPollInterval(); - /** - * Gets the OperationsClient object to access its operations. - * - * @return the OperationsClient object. - */ - OperationsClient getOperations(); - - /** - * Gets the TrafficControllerInterfacesClient object to access its operations. - * - * @return the TrafficControllerInterfacesClient object. - */ - TrafficControllerInterfacesClient getTrafficControllerInterfaces(); - /** * Gets the AssociationsInterfacesClient object to access its operations. * @@ -80,4 +66,18 @@ public interface TrafficControllerManagementClient { * @return the SecurityPoliciesInterfacesClient object. */ SecurityPoliciesInterfacesClient getSecurityPoliciesInterfaces(); + + /** + * Gets the TrafficControllerInterfacesClient object to access its operations. + * + * @return the TrafficControllerInterfacesClient object. + */ + TrafficControllerInterfacesClient getTrafficControllerInterfaces(); + + /** + * Gets the OperationsClient object to access its operations. + * + * @return the OperationsClient object. + */ + OperationsClient getOperations(); } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/models/AssociationInner.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/models/AssociationInner.java index 346dd4adfaa5..ae2c199e518b 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/models/AssociationInner.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/models/AssociationInner.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.fluent.models; diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/models/FrontendInner.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/models/FrontendInner.java index 076871395fa9..69b1bea1feb3 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/models/FrontendInner.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/models/FrontendInner.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.fluent.models; diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/models/OperationInner.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/models/OperationInner.java index a9a934f716b7..e677dfa283ff 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/models/OperationInner.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/models/OperationInner.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.fluent.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -15,11 +15,9 @@ import java.io.IOException; /** - * REST API Operation - * * Details of a REST API operation, returned from the Resource Provider Operations API. */ -@Fluent +@Immutable public final class OperationInner implements JsonSerializable { /* * The name of the operation, as per Resource-Based Access Control (RBAC). Examples: @@ -28,8 +26,8 @@ public final class OperationInner implements JsonSerializable { private String name; /* - * Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for - * ARM/control-plane operations. + * Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure + * Resource Manager/control-plane operations. */ private Boolean isDataAction; @@ -45,14 +43,14 @@ public final class OperationInner implements JsonSerializable { private Origin origin; /* - * Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + * Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. */ private ActionType actionType; /** * Creates an instance of OperationInner class. */ - public OperationInner() { + private OperationInner() { } /** @@ -67,7 +65,7 @@ public String name() { /** * Get the isDataAction property: Whether the operation applies to data-plane. This is "true" for data-plane - * operations and "false" for ARM/control-plane operations. + * operations and "false" for Azure Resource Manager/control-plane operations. * * @return the isDataAction value. */ @@ -84,17 +82,6 @@ public OperationDisplay display() { return this.display; } - /** - * Set the display property: Localized display information for this particular operation. - * - * @param display the display value to set. - * @return the OperationInner object itself. - */ - public OperationInner withDisplay(OperationDisplay display) { - this.display = display; - return this; - } - /** * Get the origin property: The intended executor of the operation; as in Resource Based Access Control (RBAC) and * audit logs UX. Default value is "user,system". @@ -106,8 +93,8 @@ public Origin origin() { } /** - * Get the actionType property: Enum. Indicates the action type. "Internal" refers to actions that are for internal - * only APIs. + * Get the actionType property: Extensible enum. Indicates the action type. "Internal" refers to actions that are + * for internal only APIs. * * @return the actionType value. */ diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/models/SecurityPolicyInner.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/models/SecurityPolicyInner.java index ef8ec2eea16c..c40b8e2d3bcd 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/models/SecurityPolicyInner.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/models/SecurityPolicyInner.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.fluent.models; diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/models/TrafficControllerInner.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/models/TrafficControllerInner.java index ff589bcd1f57..0c817cb50024 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/models/TrafficControllerInner.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/models/TrafficControllerInner.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.fluent.models; diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/models/package-info.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/models/package-info.java index 53ec06af5a7c..733a6b96ea59 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/models/package-info.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/models/package-info.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. /** * Package containing the inner data models for TrafficControllerManagementClient. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/package-info.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/package-info.java index b033de116256..f82c1f9dbdf7 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/package-info.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/fluent/package-info.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. /** * Package containing the service clients for TrafficControllerManagementClient. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/AssociationImpl.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/AssociationImpl.java index 9e5797c5bc5d..559e6888a7f1 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/AssociationImpl.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/AssociationImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.implementation; diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/AssociationsInterfacesClientImpl.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/AssociationsInterfacesClientImpl.java index ff219e01ec75..2c5522ec6e1b 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/AssociationsInterfacesClientImpl.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/AssociationsInterfacesClientImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.implementation; @@ -34,7 +34,7 @@ import com.azure.core.util.polling.SyncPoller; import com.azure.resourcemanager.servicenetworking.fluent.AssociationsInterfacesClient; import com.azure.resourcemanager.servicenetworking.fluent.models.AssociationInner; -import com.azure.resourcemanager.servicenetworking.models.AssociationListResult; +import com.azure.resourcemanager.servicenetworking.implementation.models.AssociationListResult; import com.azure.resourcemanager.servicenetworking.models.AssociationUpdate; import java.nio.ByteBuffer; import reactor.core.publisher.Flux; @@ -69,223 +69,72 @@ public final class AssociationsInterfacesClientImpl implements AssociationsInter * The interface defining all the services for TrafficControllerManagementClientAssociationsInterfaces to be used by * the proxy service to perform REST calls. */ - @Host("{$host}") + @Host("{endpoint}") @ServiceInterface(name = "TrafficControllerMan") public interface AssociationsInterfacesService { - @Headers({ "Content-Type: application/json" }) - @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceNetworking/trafficControllers/{trafficControllerName}/associations") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> listByTrafficController(@HostParam("$host") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, - @PathParam("trafficControllerName") String trafficControllerName, @HeaderParam("Accept") String accept, - Context context); - @Headers({ "Content-Type: application/json" }) @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceNetworking/trafficControllers/{trafficControllerName}/associations/{associationName}") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono> get(@HostParam("$host") String endpoint, + Mono> get(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("trafficControllerName") String trafficControllerName, @PathParam("associationName") String associationName, @HeaderParam("Accept") String accept, Context context); - @Headers({ "Content-Type: application/json" }) @Put("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceNetworking/trafficControllers/{trafficControllerName}/associations/{associationName}") @ExpectedResponses({ 200, 201 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono>> createOrUpdate(@HostParam("$host") String endpoint, + Mono>> createOrUpdate(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("trafficControllerName") String trafficControllerName, - @PathParam("associationName") String associationName, - @BodyParam("application/json") AssociationInner resource, @HeaderParam("Accept") String accept, + @PathParam("associationName") String associationName, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") AssociationInner resource, Context context); - @Headers({ "Content-Type: application/json" }) @Patch("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceNetworking/trafficControllers/{trafficControllerName}/associations/{associationName}") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono> update(@HostParam("$host") String endpoint, + Mono> update(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("trafficControllerName") String trafficControllerName, - @PathParam("associationName") String associationName, - @BodyParam("application/json") AssociationUpdate properties, @HeaderParam("Accept") String accept, + @PathParam("associationName") String associationName, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") AssociationUpdate properties, Context context); @Headers({ "Content-Type: application/json" }) @Delete("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceNetworking/trafficControllers/{trafficControllerName}/associations/{associationName}") @ExpectedResponses({ 202, 204 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono>> delete(@HostParam("$host") String endpoint, + Mono>> delete(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("trafficControllerName") String trafficControllerName, @PathParam("associationName") String associationName, @HeaderParam("Accept") String accept, Context context); + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceNetworking/trafficControllers/{trafficControllerName}/associations") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByTrafficController(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, + @PathParam("trafficControllerName") String trafficControllerName, @HeaderParam("Accept") String accept, + Context context); + @Headers({ "Content-Type: application/json" }) @Get("{nextLink}") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) Mono> listByTrafficControllerNext( - @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, @HeaderParam("Accept") String accept, Context context); } - /** - * List Association resources by TrafficController. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param trafficControllerName traffic controller name for path. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Association list operation along with {@link PagedResponse} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listByTrafficControllerSinglePageAsync(String resourceGroupName, - String trafficControllerName) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (trafficControllerName == null) { - return Mono - .error(new IllegalArgumentException("Parameter trafficControllerName is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext( - context -> service.listByTrafficController(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), - res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * List Association resources by TrafficController. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param trafficControllerName traffic controller name for path. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Association list operation along with {@link PagedResponse} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listByTrafficControllerSinglePageAsync(String resourceGroupName, - String trafficControllerName, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (trafficControllerName == null) { - return Mono - .error(new IllegalArgumentException("Parameter trafficControllerName is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service - .listByTrafficController(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } - - /** - * List Association resources by TrafficController. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param trafficControllerName traffic controller name for path. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Association list operation as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listByTrafficControllerAsync(String resourceGroupName, - String trafficControllerName) { - return new PagedFlux<>(() -> listByTrafficControllerSinglePageAsync(resourceGroupName, trafficControllerName), - nextLink -> listByTrafficControllerNextSinglePageAsync(nextLink)); - } - - /** - * List Association resources by TrafficController. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param trafficControllerName traffic controller name for path. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Association list operation as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listByTrafficControllerAsync(String resourceGroupName, - String trafficControllerName, Context context) { - return new PagedFlux<>( - () -> listByTrafficControllerSinglePageAsync(resourceGroupName, trafficControllerName, context), - nextLink -> listByTrafficControllerNextSinglePageAsync(nextLink, context)); - } - - /** - * List Association resources by TrafficController. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param trafficControllerName traffic controller name for path. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Association list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listByTrafficController(String resourceGroupName, - String trafficControllerName) { - return new PagedIterable<>(listByTrafficControllerAsync(resourceGroupName, trafficControllerName)); - } - - /** - * List Association resources by TrafficController. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param trafficControllerName traffic controller name for path. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Association list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listByTrafficController(String resourceGroupName, - String trafficControllerName, Context context) { - return new PagedIterable<>(listByTrafficControllerAsync(resourceGroupName, trafficControllerName, context)); - } - /** * Get a Association. * @@ -462,11 +311,12 @@ private Mono>> createOrUpdateWithResponseAsync(String } else { resource.validate(); } + final String contentType = "application/json"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.createOrUpdate(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, associationName, resource, - accept, context)) + this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, associationName, contentType, + accept, resource, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } @@ -512,11 +362,12 @@ private Mono>> createOrUpdateWithResponseAsync(String } else { resource.validate(); } + final String contentType = "application/json"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.createOrUpdate(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, associationName, resource, - accept, context); + this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, associationName, contentType, + accept, resource, context); } /** @@ -723,11 +574,12 @@ private Mono> updateWithResponseAsync(String resource } else { properties.validate(); } + final String contentType = "application/json"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.update(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, associationName, properties, - accept, context)) + this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, associationName, contentType, + accept, properties, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } @@ -773,10 +625,11 @@ private Mono> updateWithResponseAsync(String resource } else { properties.validate(); } + final String contentType = "application/json"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.update(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), - resourceGroupName, trafficControllerName, associationName, properties, accept, context); + resourceGroupName, trafficControllerName, associationName, contentType, accept, properties, context); } /** @@ -1066,6 +919,155 @@ public void delete(String resourceGroupName, String trafficControllerName, Strin deleteAsync(resourceGroupName, trafficControllerName, associationName, context).block(); } + /** + * List Association resources by TrafficController. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param trafficControllerName traffic controller name for path. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Association list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByTrafficControllerSinglePageAsync(String resourceGroupName, + String trafficControllerName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (trafficControllerName == null) { + return Mono + .error(new IllegalArgumentException("Parameter trafficControllerName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByTrafficController(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), + res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List Association resources by TrafficController. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param trafficControllerName traffic controller name for path. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Association list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByTrafficControllerSinglePageAsync(String resourceGroupName, + String trafficControllerName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (trafficControllerName == null) { + return Mono + .error(new IllegalArgumentException("Parameter trafficControllerName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByTrafficController(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List Association resources by TrafficController. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param trafficControllerName traffic controller name for path. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Association list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByTrafficControllerAsync(String resourceGroupName, + String trafficControllerName) { + return new PagedFlux<>(() -> listByTrafficControllerSinglePageAsync(resourceGroupName, trafficControllerName), + nextLink -> listByTrafficControllerNextSinglePageAsync(nextLink)); + } + + /** + * List Association resources by TrafficController. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param trafficControllerName traffic controller name for path. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Association list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByTrafficControllerAsync(String resourceGroupName, + String trafficControllerName, Context context) { + return new PagedFlux<>( + () -> listByTrafficControllerSinglePageAsync(resourceGroupName, trafficControllerName, context), + nextLink -> listByTrafficControllerNextSinglePageAsync(nextLink, context)); + } + + /** + * List Association resources by TrafficController. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param trafficControllerName traffic controller name for path. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Association list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByTrafficController(String resourceGroupName, + String trafficControllerName) { + return new PagedIterable<>(listByTrafficControllerAsync(resourceGroupName, trafficControllerName)); + } + + /** + * List Association resources by TrafficController. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param trafficControllerName traffic controller name for path. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Association list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByTrafficController(String resourceGroupName, + String trafficControllerName, Context context) { + return new PagedIterable<>(listByTrafficControllerAsync(resourceGroupName, trafficControllerName, context)); + } + /** * Get the next page of items. * diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/AssociationsInterfacesImpl.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/AssociationsInterfacesImpl.java index 3ec4c80e5625..415e11b1416e 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/AssociationsInterfacesImpl.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/AssociationsInterfacesImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.implementation; @@ -27,19 +27,6 @@ public AssociationsInterfacesImpl(AssociationsInterfacesClient innerClient, this.serviceManager = serviceManager; } - public PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName) { - PagedIterable inner - = this.serviceClient().listByTrafficController(resourceGroupName, trafficControllerName); - return ResourceManagerUtils.mapPage(inner, inner1 -> new AssociationImpl(inner1, this.manager())); - } - - public PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName, - Context context) { - PagedIterable inner - = this.serviceClient().listByTrafficController(resourceGroupName, trafficControllerName, context); - return ResourceManagerUtils.mapPage(inner, inner1 -> new AssociationImpl(inner1, this.manager())); - } - public Response getWithResponse(String resourceGroupName, String trafficControllerName, String associationName, Context context) { Response inner @@ -70,6 +57,19 @@ public void delete(String resourceGroupName, String trafficControllerName, Strin this.serviceClient().delete(resourceGroupName, trafficControllerName, associationName, context); } + public PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName) { + PagedIterable inner + = this.serviceClient().listByTrafficController(resourceGroupName, trafficControllerName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new AssociationImpl(inner1, this.manager())); + } + + public PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName, + Context context) { + PagedIterable inner + = this.serviceClient().listByTrafficController(resourceGroupName, trafficControllerName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new AssociationImpl(inner1, this.manager())); + } + public Association getById(String id) { String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); if (resourceGroupName == null) { diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/FrontendImpl.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/FrontendImpl.java index fcd726bc97b8..20ab5205611d 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/FrontendImpl.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/FrontendImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.implementation; diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/FrontendsInterfacesClientImpl.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/FrontendsInterfacesClientImpl.java index 784749e456e9..c4ff91860b05 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/FrontendsInterfacesClientImpl.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/FrontendsInterfacesClientImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.implementation; @@ -34,7 +34,7 @@ import com.azure.core.util.polling.SyncPoller; import com.azure.resourcemanager.servicenetworking.fluent.FrontendsInterfacesClient; import com.azure.resourcemanager.servicenetworking.fluent.models.FrontendInner; -import com.azure.resourcemanager.servicenetworking.models.FrontendListResult; +import com.azure.resourcemanager.servicenetworking.implementation.models.FrontendListResult; import com.azure.resourcemanager.servicenetworking.models.FrontendUpdate; import java.nio.ByteBuffer; import reactor.core.publisher.Flux; @@ -69,219 +69,70 @@ public final class FrontendsInterfacesClientImpl implements FrontendsInterfacesC * The interface defining all the services for TrafficControllerManagementClientFrontendsInterfaces to be used by * the proxy service to perform REST calls. */ - @Host("{$host}") + @Host("{endpoint}") @ServiceInterface(name = "TrafficControllerMan") public interface FrontendsInterfacesService { - @Headers({ "Content-Type: application/json" }) - @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceNetworking/trafficControllers/{trafficControllerName}/frontends") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> listByTrafficController(@HostParam("$host") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, - @PathParam("trafficControllerName") String trafficControllerName, @HeaderParam("Accept") String accept, - Context context); - @Headers({ "Content-Type: application/json" }) @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceNetworking/trafficControllers/{trafficControllerName}/frontends/{frontendName}") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono> get(@HostParam("$host") String endpoint, + Mono> get(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("trafficControllerName") String trafficControllerName, @PathParam("frontendName") String frontendName, @HeaderParam("Accept") String accept, Context context); - @Headers({ "Content-Type: application/json" }) @Put("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceNetworking/trafficControllers/{trafficControllerName}/frontends/{frontendName}") @ExpectedResponses({ 200, 201 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono>> createOrUpdate(@HostParam("$host") String endpoint, + Mono>> createOrUpdate(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("trafficControllerName") String trafficControllerName, - @PathParam("frontendName") String frontendName, @BodyParam("application/json") FrontendInner resource, - @HeaderParam("Accept") String accept, Context context); + @PathParam("frontendName") String frontendName, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") FrontendInner resource, + Context context); - @Headers({ "Content-Type: application/json" }) @Patch("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceNetworking/trafficControllers/{trafficControllerName}/frontends/{frontendName}") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono> update(@HostParam("$host") String endpoint, + Mono> update(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("trafficControllerName") String trafficControllerName, - @PathParam("frontendName") String frontendName, @BodyParam("application/json") FrontendUpdate properties, - @HeaderParam("Accept") String accept, Context context); + @PathParam("frontendName") String frontendName, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") FrontendUpdate properties, + Context context); @Headers({ "Content-Type: application/json" }) @Delete("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceNetworking/trafficControllers/{trafficControllerName}/frontends/{frontendName}") @ExpectedResponses({ 202, 204 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono>> delete(@HostParam("$host") String endpoint, + Mono>> delete(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("trafficControllerName") String trafficControllerName, @PathParam("frontendName") String frontendName, @HeaderParam("Accept") String accept, Context context); + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceNetworking/trafficControllers/{trafficControllerName}/frontends") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByTrafficController(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, + @PathParam("trafficControllerName") String trafficControllerName, @HeaderParam("Accept") String accept, + Context context); + @Headers({ "Content-Type: application/json" }) @Get("{nextLink}") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) Mono> listByTrafficControllerNext( - @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, @HeaderParam("Accept") String accept, Context context); } - /** - * List Frontend resources by TrafficController. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param trafficControllerName traffic controller name for path. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Frontend list operation along with {@link PagedResponse} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listByTrafficControllerSinglePageAsync(String resourceGroupName, - String trafficControllerName) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (trafficControllerName == null) { - return Mono - .error(new IllegalArgumentException("Parameter trafficControllerName is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext( - context -> service.listByTrafficController(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), - res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * List Frontend resources by TrafficController. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param trafficControllerName traffic controller name for path. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Frontend list operation along with {@link PagedResponse} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listByTrafficControllerSinglePageAsync(String resourceGroupName, - String trafficControllerName, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (trafficControllerName == null) { - return Mono - .error(new IllegalArgumentException("Parameter trafficControllerName is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service - .listByTrafficController(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } - - /** - * List Frontend resources by TrafficController. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param trafficControllerName traffic controller name for path. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Frontend list operation as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listByTrafficControllerAsync(String resourceGroupName, - String trafficControllerName) { - return new PagedFlux<>(() -> listByTrafficControllerSinglePageAsync(resourceGroupName, trafficControllerName), - nextLink -> listByTrafficControllerNextSinglePageAsync(nextLink)); - } - - /** - * List Frontend resources by TrafficController. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param trafficControllerName traffic controller name for path. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Frontend list operation as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listByTrafficControllerAsync(String resourceGroupName, - String trafficControllerName, Context context) { - return new PagedFlux<>( - () -> listByTrafficControllerSinglePageAsync(resourceGroupName, trafficControllerName, context), - nextLink -> listByTrafficControllerNextSinglePageAsync(nextLink, context)); - } - - /** - * List Frontend resources by TrafficController. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param trafficControllerName traffic controller name for path. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Frontend list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listByTrafficController(String resourceGroupName, - String trafficControllerName) { - return new PagedIterable<>(listByTrafficControllerAsync(resourceGroupName, trafficControllerName)); - } - - /** - * List Frontend resources by TrafficController. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param trafficControllerName traffic controller name for path. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Frontend list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName, - Context context) { - return new PagedIterable<>(listByTrafficControllerAsync(resourceGroupName, trafficControllerName, context)); - } - /** * Get a Frontend. * @@ -452,11 +303,12 @@ private Mono>> createOrUpdateWithResponseAsync(String } else { resource.validate(); } + final String contentType = "application/json"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.createOrUpdate(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, frontendName, resource, - accept, context)) + this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, frontendName, contentType, + accept, resource, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } @@ -501,11 +353,12 @@ private Mono>> createOrUpdateWithResponseAsync(String } else { resource.validate(); } + final String contentType = "application/json"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.createOrUpdate(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, frontendName, resource, accept, - context); + this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, frontendName, contentType, + accept, resource, context); } /** @@ -708,11 +561,12 @@ private Mono> updateWithResponseAsync(String resourceGro } else { properties.validate(); } + final String contentType = "application/json"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.update(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, frontendName, properties, - accept, context)) + this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, frontendName, contentType, + accept, properties, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } @@ -757,10 +611,11 @@ private Mono> updateWithResponseAsync(String resourceGro } else { properties.validate(); } + final String contentType = "application/json"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.update(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), - resourceGroupName, trafficControllerName, frontendName, properties, accept, context); + resourceGroupName, trafficControllerName, frontendName, contentType, accept, properties, context); } /** @@ -1044,6 +899,155 @@ public void delete(String resourceGroupName, String trafficControllerName, Strin deleteAsync(resourceGroupName, trafficControllerName, frontendName, context).block(); } + /** + * List Frontend resources by TrafficController. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param trafficControllerName traffic controller name for path. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Frontend list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByTrafficControllerSinglePageAsync(String resourceGroupName, + String trafficControllerName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (trafficControllerName == null) { + return Mono + .error(new IllegalArgumentException("Parameter trafficControllerName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByTrafficController(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), + res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List Frontend resources by TrafficController. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param trafficControllerName traffic controller name for path. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Frontend list operation along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByTrafficControllerSinglePageAsync(String resourceGroupName, + String trafficControllerName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (trafficControllerName == null) { + return Mono + .error(new IllegalArgumentException("Parameter trafficControllerName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByTrafficController(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List Frontend resources by TrafficController. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param trafficControllerName traffic controller name for path. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Frontend list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByTrafficControllerAsync(String resourceGroupName, + String trafficControllerName) { + return new PagedFlux<>(() -> listByTrafficControllerSinglePageAsync(resourceGroupName, trafficControllerName), + nextLink -> listByTrafficControllerNextSinglePageAsync(nextLink)); + } + + /** + * List Frontend resources by TrafficController. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param trafficControllerName traffic controller name for path. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Frontend list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByTrafficControllerAsync(String resourceGroupName, + String trafficControllerName, Context context) { + return new PagedFlux<>( + () -> listByTrafficControllerSinglePageAsync(resourceGroupName, trafficControllerName, context), + nextLink -> listByTrafficControllerNextSinglePageAsync(nextLink, context)); + } + + /** + * List Frontend resources by TrafficController. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param trafficControllerName traffic controller name for path. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Frontend list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByTrafficController(String resourceGroupName, + String trafficControllerName) { + return new PagedIterable<>(listByTrafficControllerAsync(resourceGroupName, trafficControllerName)); + } + + /** + * List Frontend resources by TrafficController. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param trafficControllerName traffic controller name for path. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Frontend list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName, + Context context) { + return new PagedIterable<>(listByTrafficControllerAsync(resourceGroupName, trafficControllerName, context)); + } + /** * Get the next page of items. * diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/FrontendsInterfacesImpl.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/FrontendsInterfacesImpl.java index fd65c03dad9a..9a2f7c7d814f 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/FrontendsInterfacesImpl.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/FrontendsInterfacesImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.implementation; @@ -27,19 +27,6 @@ public FrontendsInterfacesImpl(FrontendsInterfacesClient innerClient, this.serviceManager = serviceManager; } - public PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName) { - PagedIterable inner - = this.serviceClient().listByTrafficController(resourceGroupName, trafficControllerName); - return ResourceManagerUtils.mapPage(inner, inner1 -> new FrontendImpl(inner1, this.manager())); - } - - public PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName, - Context context) { - PagedIterable inner - = this.serviceClient().listByTrafficController(resourceGroupName, trafficControllerName, context); - return ResourceManagerUtils.mapPage(inner, inner1 -> new FrontendImpl(inner1, this.manager())); - } - public Response getWithResponse(String resourceGroupName, String trafficControllerName, String frontendName, Context context) { Response inner @@ -69,6 +56,19 @@ public void delete(String resourceGroupName, String trafficControllerName, Strin this.serviceClient().delete(resourceGroupName, trafficControllerName, frontendName, context); } + public PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName) { + PagedIterable inner + = this.serviceClient().listByTrafficController(resourceGroupName, trafficControllerName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new FrontendImpl(inner1, this.manager())); + } + + public PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName, + Context context) { + PagedIterable inner + = this.serviceClient().listByTrafficController(resourceGroupName, trafficControllerName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new FrontendImpl(inner1, this.manager())); + } + public Frontend getById(String id) { String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); if (resourceGroupName == null) { diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/OperationImpl.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/OperationImpl.java index 398d79167831..2d6b9866fbee 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/OperationImpl.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/OperationImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.implementation; diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/OperationsClientImpl.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/OperationsClientImpl.java index 5cf787c6177f..5615911898f5 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/OperationsClientImpl.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/OperationsClientImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.implementation; @@ -27,7 +27,7 @@ import com.azure.core.util.FluxUtil; import com.azure.resourcemanager.servicenetworking.fluent.OperationsClient; import com.azure.resourcemanager.servicenetworking.fluent.models.OperationInner; -import com.azure.resourcemanager.servicenetworking.models.OperationListResult; +import com.azure.resourcemanager.servicenetworking.implementation.models.OperationListResult; import reactor.core.publisher.Mono; /** @@ -59,14 +59,14 @@ public final class OperationsClientImpl implements OperationsClient { * The interface defining all the services for TrafficControllerManagementClientOperations to be used by the proxy * service to perform REST calls. */ - @Host("{$host}") + @Host("{endpoint}") @ServiceInterface(name = "TrafficControllerMan") public interface OperationsService { @Headers({ "Content-Type: application/json" }) @Get("/providers/Microsoft.ServiceNetworking/operations") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono> list(@HostParam("$host") String endpoint, + Mono> list(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); @Headers({ "Content-Type: application/json" }) @@ -74,7 +74,7 @@ Mono> list(@HostParam("$host") String endpoint, @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) Mono> listNext(@PathParam(value = "nextLink", encoded = true) String nextLink, - @HostParam("$host") String endpoint, @HeaderParam("Accept") String accept, Context context); + @HostParam("endpoint") String endpoint, @HeaderParam("Accept") String accept, Context context); } /** diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/OperationsImpl.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/OperationsImpl.java index df8814fb1892..a1161d250791 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/OperationsImpl.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/OperationsImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.implementation; diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/ResourceManagerUtils.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/ResourceManagerUtils.java index 25fb1934c1cf..46c47141f528 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/ResourceManagerUtils.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/ResourceManagerUtils.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.implementation; diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/SecurityPoliciesInterfacesClientImpl.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/SecurityPoliciesInterfacesClientImpl.java index 85dcc4875e0c..0dc40584e741 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/SecurityPoliciesInterfacesClientImpl.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/SecurityPoliciesInterfacesClientImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.implementation; @@ -34,7 +34,7 @@ import com.azure.core.util.polling.SyncPoller; import com.azure.resourcemanager.servicenetworking.fluent.SecurityPoliciesInterfacesClient; import com.azure.resourcemanager.servicenetworking.fluent.models.SecurityPolicyInner; -import com.azure.resourcemanager.servicenetworking.models.SecurityPolicyListResult; +import com.azure.resourcemanager.servicenetworking.implementation.models.SecurityPolicyListResult; import com.azure.resourcemanager.servicenetworking.models.SecurityPolicyUpdate; import java.nio.ByteBuffer; import reactor.core.publisher.Flux; @@ -69,223 +69,72 @@ public final class SecurityPoliciesInterfacesClientImpl implements SecurityPolic * The interface defining all the services for TrafficControllerManagementClientSecurityPoliciesInterfaces to be * used by the proxy service to perform REST calls. */ - @Host("{$host}") + @Host("{endpoint}") @ServiceInterface(name = "TrafficControllerMan") public interface SecurityPoliciesInterfacesService { - @Headers({ "Content-Type: application/json" }) - @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceNetworking/trafficControllers/{trafficControllerName}/securityPolicies") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> listByTrafficController(@HostParam("$host") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, - @PathParam("trafficControllerName") String trafficControllerName, @HeaderParam("Accept") String accept, - Context context); - @Headers({ "Content-Type: application/json" }) @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceNetworking/trafficControllers/{trafficControllerName}/securityPolicies/{securityPolicyName}") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono> get(@HostParam("$host") String endpoint, + Mono> get(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("trafficControllerName") String trafficControllerName, @PathParam("securityPolicyName") String securityPolicyName, @HeaderParam("Accept") String accept, Context context); - @Headers({ "Content-Type: application/json" }) @Put("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceNetworking/trafficControllers/{trafficControllerName}/securityPolicies/{securityPolicyName}") @ExpectedResponses({ 200, 201 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono>> createOrUpdate(@HostParam("$host") String endpoint, + Mono>> createOrUpdate(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("trafficControllerName") String trafficControllerName, - @PathParam("securityPolicyName") String securityPolicyName, - @BodyParam("application/json") SecurityPolicyInner resource, @HeaderParam("Accept") String accept, + @PathParam("securityPolicyName") String securityPolicyName, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") SecurityPolicyInner resource, Context context); - @Headers({ "Content-Type: application/json" }) @Patch("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceNetworking/trafficControllers/{trafficControllerName}/securityPolicies/{securityPolicyName}") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono> update(@HostParam("$host") String endpoint, + Mono> update(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("trafficControllerName") String trafficControllerName, - @PathParam("securityPolicyName") String securityPolicyName, - @BodyParam("application/json") SecurityPolicyUpdate properties, @HeaderParam("Accept") String accept, + @PathParam("securityPolicyName") String securityPolicyName, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") SecurityPolicyUpdate properties, Context context); @Headers({ "Content-Type: application/json" }) @Delete("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceNetworking/trafficControllers/{trafficControllerName}/securityPolicies/{securityPolicyName}") @ExpectedResponses({ 202, 204 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono>> delete(@HostParam("$host") String endpoint, + Mono>> delete(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("trafficControllerName") String trafficControllerName, @PathParam("securityPolicyName") String securityPolicyName, @HeaderParam("Accept") String accept, Context context); + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceNetworking/trafficControllers/{trafficControllerName}/securityPolicies") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listByTrafficController(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, + @PathParam("trafficControllerName") String trafficControllerName, @HeaderParam("Accept") String accept, + Context context); + @Headers({ "Content-Type: application/json" }) @Get("{nextLink}") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) Mono> listByTrafficControllerNext( - @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, @HeaderParam("Accept") String accept, Context context); } - /** - * List SecurityPolicy resources by TrafficController. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param trafficControllerName traffic controller name for path. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SecurityPolicy list operation along with {@link PagedResponse} on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listByTrafficControllerSinglePageAsync(String resourceGroupName, - String trafficControllerName) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (trafficControllerName == null) { - return Mono - .error(new IllegalArgumentException("Parameter trafficControllerName is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext( - context -> service.listByTrafficController(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), - res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * List SecurityPolicy resources by TrafficController. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param trafficControllerName traffic controller name for path. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SecurityPolicy list operation along with {@link PagedResponse} on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listByTrafficControllerSinglePageAsync(String resourceGroupName, - String trafficControllerName, Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - if (trafficControllerName == null) { - return Mono - .error(new IllegalArgumentException("Parameter trafficControllerName is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service - .listByTrafficController(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } - - /** - * List SecurityPolicy resources by TrafficController. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param trafficControllerName traffic controller name for path. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SecurityPolicy list operation as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listByTrafficControllerAsync(String resourceGroupName, - String trafficControllerName) { - return new PagedFlux<>(() -> listByTrafficControllerSinglePageAsync(resourceGroupName, trafficControllerName), - nextLink -> listByTrafficControllerNextSinglePageAsync(nextLink)); - } - - /** - * List SecurityPolicy resources by TrafficController. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param trafficControllerName traffic controller name for path. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SecurityPolicy list operation as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listByTrafficControllerAsync(String resourceGroupName, - String trafficControllerName, Context context) { - return new PagedFlux<>( - () -> listByTrafficControllerSinglePageAsync(resourceGroupName, trafficControllerName, context), - nextLink -> listByTrafficControllerNextSinglePageAsync(nextLink, context)); - } - - /** - * List SecurityPolicy resources by TrafficController. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param trafficControllerName traffic controller name for path. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SecurityPolicy list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listByTrafficController(String resourceGroupName, - String trafficControllerName) { - return new PagedIterable<>(listByTrafficControllerAsync(resourceGroupName, trafficControllerName)); - } - - /** - * List SecurityPolicy resources by TrafficController. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param trafficControllerName traffic controller name for path. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SecurityPolicy list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listByTrafficController(String resourceGroupName, - String trafficControllerName, Context context) { - return new PagedIterable<>(listByTrafficControllerAsync(resourceGroupName, trafficControllerName, context)); - } - /** * Get a SecurityPolicy. * @@ -462,11 +311,12 @@ private Mono>> createOrUpdateWithResponseAsync(String } else { resource.validate(); } + final String contentType = "application/json"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.createOrUpdate(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, securityPolicyName, resource, - accept, context)) + this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, securityPolicyName, + contentType, accept, resource, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } @@ -512,11 +362,12 @@ private Mono>> createOrUpdateWithResponseAsync(String } else { resource.validate(); } + final String contentType = "application/json"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.createOrUpdate(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, securityPolicyName, resource, - accept, context); + this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, securityPolicyName, contentType, + accept, resource, context); } /** @@ -726,11 +577,12 @@ private Mono> updateWithResponseAsync(String resou } else { properties.validate(); } + final String contentType = "application/json"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.update(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, securityPolicyName, - properties, accept, context)) + contentType, accept, properties, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } @@ -776,10 +628,11 @@ private Mono> updateWithResponseAsync(String resou } else { properties.validate(); } + final String contentType = "application/json"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.update(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), - resourceGroupName, trafficControllerName, securityPolicyName, properties, accept, context); + resourceGroupName, trafficControllerName, securityPolicyName, contentType, accept, properties, context); } /** @@ -1069,6 +922,155 @@ public void delete(String resourceGroupName, String trafficControllerName, Strin deleteAsync(resourceGroupName, trafficControllerName, securityPolicyName, context).block(); } + /** + * List SecurityPolicy resources by TrafficController. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param trafficControllerName traffic controller name for path. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SecurityPolicy list operation along with {@link PagedResponse} on successful completion + * of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByTrafficControllerSinglePageAsync(String resourceGroupName, + String trafficControllerName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (trafficControllerName == null) { + return Mono + .error(new IllegalArgumentException("Parameter trafficControllerName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext( + context -> service.listByTrafficController(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List SecurityPolicy resources by TrafficController. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param trafficControllerName traffic controller name for path. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SecurityPolicy list operation along with {@link PagedResponse} on successful completion + * of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByTrafficControllerSinglePageAsync(String resourceGroupName, + String trafficControllerName, Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + if (trafficControllerName == null) { + return Mono + .error(new IllegalArgumentException("Parameter trafficControllerName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByTrafficController(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List SecurityPolicy resources by TrafficController. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param trafficControllerName traffic controller name for path. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SecurityPolicy list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByTrafficControllerAsync(String resourceGroupName, + String trafficControllerName) { + return new PagedFlux<>(() -> listByTrafficControllerSinglePageAsync(resourceGroupName, trafficControllerName), + nextLink -> listByTrafficControllerNextSinglePageAsync(nextLink)); + } + + /** + * List SecurityPolicy resources by TrafficController. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param trafficControllerName traffic controller name for path. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SecurityPolicy list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByTrafficControllerAsync(String resourceGroupName, + String trafficControllerName, Context context) { + return new PagedFlux<>( + () -> listByTrafficControllerSinglePageAsync(resourceGroupName, trafficControllerName, context), + nextLink -> listByTrafficControllerNextSinglePageAsync(nextLink, context)); + } + + /** + * List SecurityPolicy resources by TrafficController. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param trafficControllerName traffic controller name for path. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SecurityPolicy list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByTrafficController(String resourceGroupName, + String trafficControllerName) { + return new PagedIterable<>(listByTrafficControllerAsync(resourceGroupName, trafficControllerName)); + } + + /** + * List SecurityPolicy resources by TrafficController. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param trafficControllerName traffic controller name for path. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SecurityPolicy list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByTrafficController(String resourceGroupName, + String trafficControllerName, Context context) { + return new PagedIterable<>(listByTrafficControllerAsync(resourceGroupName, trafficControllerName, context)); + } + /** * Get the next page of items. * diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/SecurityPoliciesInterfacesImpl.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/SecurityPoliciesInterfacesImpl.java index 673a5fdb7d28..7562bc7b84d9 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/SecurityPoliciesInterfacesImpl.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/SecurityPoliciesInterfacesImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.implementation; @@ -27,20 +27,6 @@ public SecurityPoliciesInterfacesImpl(SecurityPoliciesInterfacesClient innerClie this.serviceManager = serviceManager; } - public PagedIterable listByTrafficController(String resourceGroupName, - String trafficControllerName) { - PagedIterable inner - = this.serviceClient().listByTrafficController(resourceGroupName, trafficControllerName); - return ResourceManagerUtils.mapPage(inner, inner1 -> new SecurityPolicyImpl(inner1, this.manager())); - } - - public PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName, - Context context) { - PagedIterable inner - = this.serviceClient().listByTrafficController(resourceGroupName, trafficControllerName, context); - return ResourceManagerUtils.mapPage(inner, inner1 -> new SecurityPolicyImpl(inner1, this.manager())); - } - public Response getWithResponse(String resourceGroupName, String trafficControllerName, String securityPolicyName, Context context) { Response inner = this.serviceClient() @@ -72,6 +58,20 @@ public void delete(String resourceGroupName, String trafficControllerName, Strin this.serviceClient().delete(resourceGroupName, trafficControllerName, securityPolicyName, context); } + public PagedIterable listByTrafficController(String resourceGroupName, + String trafficControllerName) { + PagedIterable inner + = this.serviceClient().listByTrafficController(resourceGroupName, trafficControllerName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new SecurityPolicyImpl(inner1, this.manager())); + } + + public PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName, + Context context) { + PagedIterable inner + = this.serviceClient().listByTrafficController(resourceGroupName, trafficControllerName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new SecurityPolicyImpl(inner1, this.manager())); + } + public SecurityPolicy getById(String id) { String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); if (resourceGroupName == null) { diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/SecurityPolicyImpl.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/SecurityPolicyImpl.java index 527b0bd4c85c..af5ad900c6cc 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/SecurityPolicyImpl.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/SecurityPolicyImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.implementation; diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/TrafficControllerImpl.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/TrafficControllerImpl.java index b18bd813e559..86f6bd7738c6 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/TrafficControllerImpl.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/TrafficControllerImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.implementation; diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/TrafficControllerInterfacesClientImpl.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/TrafficControllerInterfacesClientImpl.java index 0440d7d88dee..9ddd13f57cb6 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/TrafficControllerInterfacesClientImpl.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/TrafficControllerInterfacesClientImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.implementation; @@ -34,7 +34,7 @@ import com.azure.core.util.polling.SyncPoller; import com.azure.resourcemanager.servicenetworking.fluent.TrafficControllerInterfacesClient; import com.azure.resourcemanager.servicenetworking.fluent.models.TrafficControllerInner; -import com.azure.resourcemanager.servicenetworking.models.TrafficControllerListResult; +import com.azure.resourcemanager.servicenetworking.implementation.models.TrafficControllerListResult; import com.azure.resourcemanager.servicenetworking.models.TrafficControllerUpdate; import java.nio.ByteBuffer; import reactor.core.publisher.Flux; @@ -69,74 +69,64 @@ public final class TrafficControllerInterfacesClientImpl implements TrafficContr * The interface defining all the services for TrafficControllerManagementClientTrafficControllerInterfaces to be * used by the proxy service to perform REST calls. */ - @Host("{$host}") + @Host("{endpoint}") @ServiceInterface(name = "TrafficControllerMan") public interface TrafficControllerInterfacesService { - @Headers({ "Content-Type: application/json" }) - @Get("/subscriptions/{subscriptionId}/providers/Microsoft.ServiceNetworking/trafficControllers") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> list(@HostParam("$host") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @HeaderParam("Accept") String accept, Context context); - - @Headers({ "Content-Type: application/json" }) - @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceNetworking/trafficControllers") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ManagementException.class) - Mono> listByResourceGroup(@HostParam("$host") String endpoint, - @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, - @PathParam("resourceGroupName") String resourceGroupName, @HeaderParam("Accept") String accept, - Context context); - @Headers({ "Content-Type: application/json" }) @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceNetworking/trafficControllers/{trafficControllerName}") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono> getByResourceGroup(@HostParam("$host") String endpoint, + Mono> getByResourceGroup(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("trafficControllerName") String trafficControllerName, @HeaderParam("Accept") String accept, Context context); - @Headers({ "Content-Type: application/json" }) @Put("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceNetworking/trafficControllers/{trafficControllerName}") @ExpectedResponses({ 200, 201 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono>> createOrUpdate(@HostParam("$host") String endpoint, + Mono>> createOrUpdate(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("trafficControllerName") String trafficControllerName, - @BodyParam("application/json") TrafficControllerInner resource, @HeaderParam("Accept") String accept, - Context context); + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") TrafficControllerInner resource, Context context); - @Headers({ "Content-Type: application/json" }) @Patch("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceNetworking/trafficControllers/{trafficControllerName}") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono> update(@HostParam("$host") String endpoint, + Mono> update(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("trafficControllerName") String trafficControllerName, - @BodyParam("application/json") TrafficControllerUpdate properties, @HeaderParam("Accept") String accept, - Context context); + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") TrafficControllerUpdate properties, Context context); @Headers({ "Content-Type: application/json" }) @Delete("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceNetworking/trafficControllers/{trafficControllerName}") @ExpectedResponses({ 202, 204 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono>> delete(@HostParam("$host") String endpoint, + Mono>> delete(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("trafficControllerName") String trafficControllerName, @HeaderParam("Accept") String accept, Context context); @Headers({ "Content-Type: application/json" }) - @Get("{nextLink}") + @Get("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceNetworking/trafficControllers") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) - Mono> listBySubscriptionNext( - @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + Mono> listByResourceGroup(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, + @PathParam("resourceGroupName") String resourceGroupName, @HeaderParam("Accept") String accept, + Context context); + + @Headers({ "Content-Type: application/json" }) + @Get("/subscriptions/{subscriptionId}/providers/Microsoft.ServiceNetworking/trafficControllers") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> list(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, @HeaderParam("Accept") String accept, Context context); @Headers({ "Content-Type: application/json" }) @@ -144,246 +134,16 @@ Mono> listBySubscriptionNext( @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(ManagementException.class) Mono> listByResourceGroupNext( - @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, @HeaderParam("Accept") String accept, Context context); - } - /** - * List TrafficController resources by subscription ID. - * - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a TrafficController list operation along with {@link PagedResponse} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listSinglePageAsync() { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.list(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), - res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * List TrafficController resources by subscription ID. - * - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a TrafficController list operation along with {@link PagedResponse} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listSinglePageAsync(Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service - .list(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), accept, - context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } - - /** - * List TrafficController resources by subscription ID. - * - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a TrafficController list operation as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listAsync() { - return new PagedFlux<>(() -> listSinglePageAsync(), - nextLink -> listBySubscriptionNextSinglePageAsync(nextLink)); - } - - /** - * List TrafficController resources by subscription ID. - * - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a TrafficController list operation as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listAsync(Context context) { - return new PagedFlux<>(() -> listSinglePageAsync(context), - nextLink -> listBySubscriptionNextSinglePageAsync(nextLink, context)); - } - - /** - * List TrafficController resources by subscription ID. - * - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a TrafficController list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list() { - return new PagedIterable<>(listAsync()); - } - - /** - * List TrafficController resources by subscription ID. - * - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a TrafficController list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list(Context context) { - return new PagedIterable<>(listAsync(context)); - } - - /** - * List TrafficController resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a TrafficController list operation along with {@link PagedResponse} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listByResourceGroupSinglePageAsync(String resourceGroupName) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - final String accept = "application/json"; - return FluxUtil - .withContext(context -> service.listByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, accept, context)) - .>map(res -> new PagedResponseBase<>(res.getRequest(), - res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) - .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); - } - - /** - * List TrafficController resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a TrafficController list operation along with {@link PagedResponse} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listByResourceGroupSinglePageAsync(String resourceGroupName, - Context context) { - if (this.client.getEndpoint() == null) { - return Mono.error( - new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); - } - if (this.client.getSubscriptionId() == null) { - return Mono.error(new IllegalArgumentException( - "Parameter this.client.getSubscriptionId() is required and cannot be null.")); - } - if (resourceGroupName == null) { - return Mono - .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - } - final String accept = "application/json"; - context = this.client.mergeContext(context); - return service - .listByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().value(), res.getValue().nextLink(), null)); - } - - /** - * List TrafficController resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a TrafficController list operation as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listByResourceGroupAsync(String resourceGroupName) { - return new PagedFlux<>(() -> listByResourceGroupSinglePageAsync(resourceGroupName), - nextLink -> listByResourceGroupNextSinglePageAsync(nextLink)); - } - - /** - * List TrafficController resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a TrafficController list operation as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - private PagedFlux listByResourceGroupAsync(String resourceGroupName, Context context) { - return new PagedFlux<>(() -> listByResourceGroupSinglePageAsync(resourceGroupName, context), - nextLink -> listByResourceGroupNextSinglePageAsync(nextLink, context)); - } - - /** - * List TrafficController resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a TrafficController list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listByResourceGroup(String resourceGroupName) { - return new PagedIterable<>(listByResourceGroupAsync(resourceGroupName)); - } - - /** - * List TrafficController resources by resource group. - * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ManagementException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a TrafficController list operation as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listByResourceGroup(String resourceGroupName, Context context) { - return new PagedIterable<>(listByResourceGroupAsync(resourceGroupName, context)); + @Headers({ "Content-Type: application/json" }) + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ManagementException.class) + Mono> listBySubscriptionNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, + @HeaderParam("Accept") String accept, Context context); } /** @@ -543,10 +303,12 @@ private Mono>> createOrUpdateWithResponseAsync(String } else { resource.validate(); } + final String contentType = "application/json"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.createOrUpdate(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, resource, accept, context)) + this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, contentType, accept, + resource, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } @@ -587,10 +349,12 @@ private Mono>> createOrUpdateWithResponseAsync(String } else { resource.validate(); } + final String contentType = "application/json"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.createOrUpdate(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, resource, accept, context); + this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, contentType, accept, resource, + context); } /** @@ -786,10 +550,12 @@ private Mono> updateWithResponseAsync(String re } else { properties.validate(); } + final String contentType = "application/json"; final String accept = "application/json"; return FluxUtil .withContext(context -> service.update(this.client.getEndpoint(), this.client.getApiVersion(), - this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, properties, accept, context)) + this.client.getSubscriptionId(), resourceGroupName, trafficControllerName, contentType, accept, + properties, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } @@ -830,10 +596,11 @@ private Mono> updateWithResponseAsync(String re } else { properties.validate(); } + final String contentType = "application/json"; final String accept = "application/json"; context = this.client.mergeContext(context); return service.update(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), - resourceGroupName, trafficControllerName, properties, accept, context); + resourceGroupName, trafficControllerName, contentType, accept, properties, context); } /** @@ -1096,6 +863,244 @@ public void delete(String resourceGroupName, String trafficControllerName, Conte deleteAsync(resourceGroupName, trafficControllerName, context).block(); } + /** + * List TrafficController resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a TrafficController list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByResourceGroupSinglePageAsync(String resourceGroupName) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List TrafficController resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a TrafficController list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listByResourceGroupSinglePageAsync(String resourceGroupName, + Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + if (resourceGroupName == null) { + return Mono + .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .listByResourceGroup(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), resourceGroupName, accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List TrafficController resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a TrafficController list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByResourceGroupAsync(String resourceGroupName) { + return new PagedFlux<>(() -> listByResourceGroupSinglePageAsync(resourceGroupName), + nextLink -> listByResourceGroupNextSinglePageAsync(nextLink)); + } + + /** + * List TrafficController resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a TrafficController list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listByResourceGroupAsync(String resourceGroupName, Context context) { + return new PagedFlux<>(() -> listByResourceGroupSinglePageAsync(resourceGroupName, context), + nextLink -> listByResourceGroupNextSinglePageAsync(nextLink, context)); + } + + /** + * List TrafficController resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a TrafficController list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByResourceGroup(String resourceGroupName) { + return new PagedIterable<>(listByResourceGroupAsync(resourceGroupName)); + } + + /** + * List TrafficController resources by resource group. + * + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a TrafficController list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listByResourceGroup(String resourceGroupName, Context context) { + return new PagedIterable<>(listByResourceGroupAsync(resourceGroupName, context)); + } + + /** + * List TrafficController resources by subscription ID. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a TrafficController list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync() { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.list(this.client.getEndpoint(), this.client.getApiVersion(), + this.client.getSubscriptionId(), accept, context)) + .>map(res -> new PagedResponseBase<>(res.getRequest(), + res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) + .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); + } + + /** + * List TrafficController resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a TrafficController list operation along with {@link PagedResponse} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync(Context context) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (this.client.getSubscriptionId() == null) { + return Mono.error(new IllegalArgumentException( + "Parameter this.client.getSubscriptionId() is required and cannot be null.")); + } + final String accept = "application/json"; + context = this.client.mergeContext(context); + return service + .list(this.client.getEndpoint(), this.client.getApiVersion(), this.client.getSubscriptionId(), accept, + context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().value(), res.getValue().nextLink(), null)); + } + + /** + * List TrafficController resources by subscription ID. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a TrafficController list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync() { + return new PagedFlux<>(() -> listSinglePageAsync(), + nextLink -> listBySubscriptionNextSinglePageAsync(nextLink)); + } + + /** + * List TrafficController resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a TrafficController list operation as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + private PagedFlux listAsync(Context context) { + return new PagedFlux<>(() -> listSinglePageAsync(context), + nextLink -> listBySubscriptionNextSinglePageAsync(nextLink, context)); + } + + /** + * List TrafficController resources by subscription ID. + * + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a TrafficController list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list() { + return new PagedIterable<>(listAsync()); + } + + /** + * List TrafficController resources by subscription ID. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ManagementException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a TrafficController list operation as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(Context context) { + return new PagedIterable<>(listAsync(context)); + } + /** * Get the next page of items. * @@ -1107,7 +1112,7 @@ public void delete(String resourceGroupName, String trafficControllerName, Conte * completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listBySubscriptionNextSinglePageAsync(String nextLink) { + private Mono> listByResourceGroupNextSinglePageAsync(String nextLink) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); } @@ -1118,7 +1123,7 @@ private Mono> listBySubscriptionNextSingle final String accept = "application/json"; return FluxUtil .withContext( - context -> service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context)) + context -> service.listByResourceGroupNext(nextLink, this.client.getEndpoint(), accept, context)) .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); @@ -1136,7 +1141,7 @@ private Mono> listBySubscriptionNextSingle * completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listBySubscriptionNextSinglePageAsync(String nextLink, + private Mono> listByResourceGroupNextSinglePageAsync(String nextLink, Context context) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); @@ -1147,7 +1152,7 @@ private Mono> listBySubscriptionNextSingle } final String accept = "application/json"; context = this.client.mergeContext(context); - return service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context) + return service.listByResourceGroupNext(nextLink, this.client.getEndpoint(), accept, context) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)); } @@ -1163,7 +1168,7 @@ private Mono> listBySubscriptionNextSingle * completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listByResourceGroupNextSinglePageAsync(String nextLink) { + private Mono> listBySubscriptionNextSinglePageAsync(String nextLink) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); } @@ -1174,7 +1179,7 @@ private Mono> listByResourceGroupNextSingl final String accept = "application/json"; return FluxUtil .withContext( - context -> service.listByResourceGroupNext(nextLink, this.client.getEndpoint(), accept, context)) + context -> service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context)) .>map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); @@ -1192,7 +1197,7 @@ private Mono> listByResourceGroupNextSingl * completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - private Mono> listByResourceGroupNextSinglePageAsync(String nextLink, + private Mono> listBySubscriptionNextSinglePageAsync(String nextLink, Context context) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); @@ -1203,7 +1208,7 @@ private Mono> listByResourceGroupNextSingl } final String accept = "application/json"; context = this.client.mergeContext(context); - return service.listByResourceGroupNext(nextLink, this.client.getEndpoint(), accept, context) + return service.listBySubscriptionNext(nextLink, this.client.getEndpoint(), accept, context) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)); } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/TrafficControllerInterfacesImpl.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/TrafficControllerInterfacesImpl.java index 347a9b901697..b5d2f694d633 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/TrafficControllerInterfacesImpl.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/TrafficControllerInterfacesImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.implementation; @@ -27,27 +27,6 @@ public TrafficControllerInterfacesImpl(TrafficControllerInterfacesClient innerCl this.serviceManager = serviceManager; } - public PagedIterable list() { - PagedIterable inner = this.serviceClient().list(); - return ResourceManagerUtils.mapPage(inner, inner1 -> new TrafficControllerImpl(inner1, this.manager())); - } - - public PagedIterable list(Context context) { - PagedIterable inner = this.serviceClient().list(context); - return ResourceManagerUtils.mapPage(inner, inner1 -> new TrafficControllerImpl(inner1, this.manager())); - } - - public PagedIterable listByResourceGroup(String resourceGroupName) { - PagedIterable inner = this.serviceClient().listByResourceGroup(resourceGroupName); - return ResourceManagerUtils.mapPage(inner, inner1 -> new TrafficControllerImpl(inner1, this.manager())); - } - - public PagedIterable listByResourceGroup(String resourceGroupName, Context context) { - PagedIterable inner - = this.serviceClient().listByResourceGroup(resourceGroupName, context); - return ResourceManagerUtils.mapPage(inner, inner1 -> new TrafficControllerImpl(inner1, this.manager())); - } - public Response getByResourceGroupWithResponse(String resourceGroupName, String trafficControllerName, Context context) { Response inner @@ -78,6 +57,27 @@ public void delete(String resourceGroupName, String trafficControllerName, Conte this.serviceClient().delete(resourceGroupName, trafficControllerName, context); } + public PagedIterable listByResourceGroup(String resourceGroupName) { + PagedIterable inner = this.serviceClient().listByResourceGroup(resourceGroupName); + return ResourceManagerUtils.mapPage(inner, inner1 -> new TrafficControllerImpl(inner1, this.manager())); + } + + public PagedIterable listByResourceGroup(String resourceGroupName, Context context) { + PagedIterable inner + = this.serviceClient().listByResourceGroup(resourceGroupName, context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new TrafficControllerImpl(inner1, this.manager())); + } + + public PagedIterable list() { + PagedIterable inner = this.serviceClient().list(); + return ResourceManagerUtils.mapPage(inner, inner1 -> new TrafficControllerImpl(inner1, this.manager())); + } + + public PagedIterable list(Context context) { + PagedIterable inner = this.serviceClient().list(context); + return ResourceManagerUtils.mapPage(inner, inner1 -> new TrafficControllerImpl(inner1, this.manager())); + } + public TrafficController getById(String id) { String resourceGroupName = ResourceManagerUtils.getValueFromIdByName(id, "resourceGroups"); if (resourceGroupName == null) { diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/TrafficControllerManagementClientBuilder.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/TrafficControllerManagementClientBuilder.java index 308b1d31515c..a90bfbfdd0c2 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/TrafficControllerManagementClientBuilder.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/TrafficControllerManagementClientBuilder.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.implementation; @@ -20,34 +20,34 @@ @ServiceClientBuilder(serviceClients = { TrafficControllerManagementClientImpl.class }) public final class TrafficControllerManagementClientBuilder { /* - * The ID of the target subscription. + * Service host */ - private String subscriptionId; + private String endpoint; /** - * Sets The ID of the target subscription. + * Sets Service host. * - * @param subscriptionId the subscriptionId value. + * @param endpoint the endpoint value. * @return the TrafficControllerManagementClientBuilder. */ - public TrafficControllerManagementClientBuilder subscriptionId(String subscriptionId) { - this.subscriptionId = subscriptionId; + public TrafficControllerManagementClientBuilder endpoint(String endpoint) { + this.endpoint = endpoint; return this; } /* - * server parameter + * The ID of the target subscription. The value must be an UUID. */ - private String endpoint; + private String subscriptionId; /** - * Sets server parameter. + * Sets The ID of the target subscription. The value must be an UUID. * - * @param endpoint the endpoint value. + * @param subscriptionId the subscriptionId value. * @return the TrafficControllerManagementClientBuilder. */ - public TrafficControllerManagementClientBuilder endpoint(String endpoint) { - this.endpoint = endpoint; + public TrafficControllerManagementClientBuilder subscriptionId(String subscriptionId) { + this.subscriptionId = subscriptionId; return this; } @@ -132,7 +132,7 @@ public TrafficControllerManagementClientImpl buildClient() { ? serializerAdapter : SerializerFactory.createDefaultManagementSerializerAdapter(); TrafficControllerManagementClientImpl client = new TrafficControllerManagementClientImpl(localPipeline, - localSerializerAdapter, localDefaultPollInterval, localEnvironment, this.subscriptionId, localEndpoint); + localSerializerAdapter, localDefaultPollInterval, localEnvironment, localEndpoint, this.subscriptionId); return client; } } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/TrafficControllerManagementClientImpl.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/TrafficControllerManagementClientImpl.java index ea96cee55c96..c7b1eb5665a0 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/TrafficControllerManagementClientImpl.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/TrafficControllerManagementClientImpl.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.implementation; @@ -44,26 +44,12 @@ @ServiceClient(builder = TrafficControllerManagementClientBuilder.class) public final class TrafficControllerManagementClientImpl implements TrafficControllerManagementClient { /** - * The ID of the target subscription. - */ - private final String subscriptionId; - - /** - * Gets The ID of the target subscription. - * - * @return the subscriptionId value. - */ - public String getSubscriptionId() { - return this.subscriptionId; - } - - /** - * server parameter. + * Service host. */ private final String endpoint; /** - * Gets server parameter. + * Gets Service host. * * @return the endpoint value. */ @@ -72,12 +58,12 @@ public String getEndpoint() { } /** - * Api Version. + * Version parameter. */ private final String apiVersion; /** - * Gets Api Version. + * Gets Version parameter. * * @return the apiVersion value. */ @@ -85,6 +71,20 @@ public String getApiVersion() { return this.apiVersion; } + /** + * The ID of the target subscription. The value must be an UUID. + */ + private final String subscriptionId; + + /** + * Gets The ID of the target subscription. The value must be an UUID. + * + * @return the subscriptionId value. + */ + public String getSubscriptionId() { + return this.subscriptionId; + } + /** * The HTTP pipeline to send requests through. */ @@ -127,34 +127,6 @@ public Duration getDefaultPollInterval() { return this.defaultPollInterval; } - /** - * The OperationsClient object to access its operations. - */ - private final OperationsClient operations; - - /** - * Gets the OperationsClient object to access its operations. - * - * @return the OperationsClient object. - */ - public OperationsClient getOperations() { - return this.operations; - } - - /** - * The TrafficControllerInterfacesClient object to access its operations. - */ - private final TrafficControllerInterfacesClient trafficControllerInterfaces; - - /** - * Gets the TrafficControllerInterfacesClient object to access its operations. - * - * @return the TrafficControllerInterfacesClient object. - */ - public TrafficControllerInterfacesClient getTrafficControllerInterfaces() { - return this.trafficControllerInterfaces; - } - /** * The AssociationsInterfacesClient object to access its operations. */ @@ -197,6 +169,34 @@ public SecurityPoliciesInterfacesClient getSecurityPoliciesInterfaces() { return this.securityPoliciesInterfaces; } + /** + * The TrafficControllerInterfacesClient object to access its operations. + */ + private final TrafficControllerInterfacesClient trafficControllerInterfaces; + + /** + * Gets the TrafficControllerInterfacesClient object to access its operations. + * + * @return the TrafficControllerInterfacesClient object. + */ + public TrafficControllerInterfacesClient getTrafficControllerInterfaces() { + return this.trafficControllerInterfaces; + } + + /** + * The OperationsClient object to access its operations. + */ + private final OperationsClient operations; + + /** + * Gets the OperationsClient object to access its operations. + * + * @return the OperationsClient object. + */ + public OperationsClient getOperations() { + return this.operations; + } + /** * Initializes an instance of TrafficControllerManagementClient client. * @@ -204,22 +204,22 @@ public SecurityPoliciesInterfacesClient getSecurityPoliciesInterfaces() { * @param serializerAdapter The serializer to serialize an object into a string. * @param defaultPollInterval The default poll interval for long-running operation. * @param environment The Azure environment. - * @param subscriptionId The ID of the target subscription. - * @param endpoint server parameter. + * @param endpoint Service host. + * @param subscriptionId The ID of the target subscription. The value must be an UUID. */ TrafficControllerManagementClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, - Duration defaultPollInterval, AzureEnvironment environment, String subscriptionId, String endpoint) { + Duration defaultPollInterval, AzureEnvironment environment, String endpoint, String subscriptionId) { this.httpPipeline = httpPipeline; this.serializerAdapter = serializerAdapter; this.defaultPollInterval = defaultPollInterval; - this.subscriptionId = subscriptionId; this.endpoint = endpoint; - this.apiVersion = "2024-05-01-preview"; - this.operations = new OperationsClientImpl(this); - this.trafficControllerInterfaces = new TrafficControllerInterfacesClientImpl(this); + this.subscriptionId = subscriptionId; + this.apiVersion = "2025-01-01"; this.associationsInterfaces = new AssociationsInterfacesClientImpl(this); this.frontendsInterfaces = new FrontendsInterfacesClientImpl(this); this.securityPoliciesInterfaces = new SecurityPoliciesInterfacesClientImpl(this); + this.trafficControllerInterfaces = new TrafficControllerInterfacesClientImpl(this); + this.operations = new OperationsClientImpl(this); } /** diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationListResult.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/models/AssociationListResult.java similarity index 80% rename from sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationListResult.java rename to sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/models/AssociationListResult.java index cf26ee1d49bf..0e7c7562bbae 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationListResult.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/models/AssociationListResult.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.resourcemanager.servicenetworking.models; +package com.azure.resourcemanager.servicenetworking.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Immutable; import com.azure.core.util.logging.ClientLogger; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -17,7 +17,7 @@ /** * The response of a Association list operation. */ -@Fluent +@Immutable public final class AssociationListResult implements JsonSerializable { /* * The Association items on this page @@ -32,7 +32,7 @@ public final class AssociationListResult implements JsonSerializable value() { return this.value; } - /** - * Set the value property: The Association items on this page. - * - * @param value the value value to set. - * @return the AssociationListResult object itself. - */ - public AssociationListResult withValue(List value) { - this.value = value; - return this; - } - /** * Get the nextLink property: The link to the next page of items. * @@ -64,17 +53,6 @@ public String nextLink() { return this.nextLink; } - /** - * Set the nextLink property: The link to the next page of items. - * - * @param nextLink the nextLink value to set. - * @return the AssociationListResult object itself. - */ - public AssociationListResult withNextLink(String nextLink) { - this.nextLink = nextLink; - return this; - } - /** * Validates the instance. * diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/FrontendListResult.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/models/FrontendListResult.java similarity index 80% rename from sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/FrontendListResult.java rename to sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/models/FrontendListResult.java index 6cbea3c7ad7a..db188db70260 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/FrontendListResult.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/models/FrontendListResult.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.resourcemanager.servicenetworking.models; +package com.azure.resourcemanager.servicenetworking.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Immutable; import com.azure.core.util.logging.ClientLogger; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -17,7 +17,7 @@ /** * The response of a Frontend list operation. */ -@Fluent +@Immutable public final class FrontendListResult implements JsonSerializable { /* * The Frontend items on this page @@ -32,7 +32,7 @@ public final class FrontendListResult implements JsonSerializable value() { return this.value; } - /** - * Set the value property: The Frontend items on this page. - * - * @param value the value value to set. - * @return the FrontendListResult object itself. - */ - public FrontendListResult withValue(List value) { - this.value = value; - return this; - } - /** * Get the nextLink property: The link to the next page of items. * @@ -64,17 +53,6 @@ public String nextLink() { return this.nextLink; } - /** - * Set the nextLink property: The link to the next page of items. - * - * @param nextLink the nextLink value to set. - * @return the FrontendListResult object itself. - */ - public FrontendListResult withNextLink(String nextLink) { - this.nextLink = nextLink; - return this; - } - /** * Validates the instance. * diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/models/OperationListResult.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/models/OperationListResult.java new file mode 100644 index 000000000000..26fa2f803080 --- /dev/null +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/models/OperationListResult.java @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.resourcemanager.servicenetworking.implementation.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.logging.ClientLogger; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import com.azure.resourcemanager.servicenetworking.fluent.models.OperationInner; +import java.io.IOException; +import java.util.List; + +/** + * A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + * results. + */ +@Immutable +public final class OperationListResult implements JsonSerializable { + /* + * The Operation items on this page + */ + private List value; + + /* + * The link to the next page of items + */ + private String nextLink; + + /** + * Creates an instance of OperationListResult class. + */ + private OperationListResult() { + } + + /** + * Get the value property: The Operation items on this page. + * + * @return the value value. + */ + public List value() { + return this.value; + } + + /** + * Get the nextLink property: The link to the next page of items. + * + * @return the nextLink value. + */ + public String nextLink() { + return this.nextLink; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + if (value() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property value in model OperationListResult")); + } else { + value().forEach(e -> e.validate()); + } + } + + private static final ClientLogger LOGGER = new ClientLogger(OperationListResult.class); + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.value, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("nextLink", this.nextLink); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of OperationListResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of OperationListResult 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 OperationListResult. + */ + public static OperationListResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + OperationListResult deserializedOperationListResult = new OperationListResult(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + List value = reader.readArray(reader1 -> OperationInner.fromJson(reader1)); + deserializedOperationListResult.value = value; + } else if ("nextLink".equals(fieldName)) { + deserializedOperationListResult.nextLink = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedOperationListResult; + }); + } +} diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPolicyListResult.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/models/SecurityPolicyListResult.java similarity index 80% rename from sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPolicyListResult.java rename to sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/models/SecurityPolicyListResult.java index 982e1e961f62..813ee826d08d 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPolicyListResult.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/models/SecurityPolicyListResult.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.resourcemanager.servicenetworking.models; +package com.azure.resourcemanager.servicenetworking.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Immutable; import com.azure.core.util.logging.ClientLogger; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -17,7 +17,7 @@ /** * The response of a SecurityPolicy list operation. */ -@Fluent +@Immutable public final class SecurityPolicyListResult implements JsonSerializable { /* * The SecurityPolicy items on this page @@ -32,7 +32,7 @@ public final class SecurityPolicyListResult implements JsonSerializable value() { return this.value; } - /** - * Set the value property: The SecurityPolicy items on this page. - * - * @param value the value value to set. - * @return the SecurityPolicyListResult object itself. - */ - public SecurityPolicyListResult withValue(List value) { - this.value = value; - return this; - } - /** * Get the nextLink property: The link to the next page of items. * @@ -64,17 +53,6 @@ public String nextLink() { return this.nextLink; } - /** - * Set the nextLink property: The link to the next page of items. - * - * @param nextLink the nextLink value to set. - * @return the SecurityPolicyListResult object itself. - */ - public SecurityPolicyListResult withNextLink(String nextLink) { - this.nextLink = nextLink; - return this; - } - /** * Validates the instance. * diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/TrafficControllerListResult.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/models/TrafficControllerListResult.java similarity index 80% rename from sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/TrafficControllerListResult.java rename to sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/models/TrafficControllerListResult.java index 56b1ccb93b5a..c271862ef665 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/TrafficControllerListResult.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/models/TrafficControllerListResult.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.resourcemanager.servicenetworking.models; +package com.azure.resourcemanager.servicenetworking.implementation.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Immutable; import com.azure.core.util.logging.ClientLogger; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -17,7 +17,7 @@ /** * The response of a TrafficController list operation. */ -@Fluent +@Immutable public final class TrafficControllerListResult implements JsonSerializable { /* * The TrafficController items on this page @@ -32,7 +32,7 @@ public final class TrafficControllerListResult implements JsonSerializable value() { return this.value; } - /** - * Set the value property: The TrafficController items on this page. - * - * @param value the value value to set. - * @return the TrafficControllerListResult object itself. - */ - public TrafficControllerListResult withValue(List value) { - this.value = value; - return this; - } - /** * Get the nextLink property: The link to the next page of items. * @@ -64,17 +53,6 @@ public String nextLink() { return this.nextLink; } - /** - * Set the nextLink property: The link to the next page of items. - * - * @param nextLink the nextLink value to set. - * @return the TrafficControllerListResult object itself. - */ - public TrafficControllerListResult withNextLink(String nextLink) { - this.nextLink = nextLink; - return this; - } - /** * Validates the instance. * diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/package-info.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/package-info.java index d7f0ba9478aa..cc72e10a9c0d 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/package-info.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/implementation/package-info.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. /** * Package containing the implementations for TrafficControllerManagementClient. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/ActionType.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/ActionType.java index 33569a9e30c5..09eede17632a 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/ActionType.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/ActionType.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; @@ -8,11 +8,11 @@ import java.util.Collection; /** - * Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + * Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. */ public final class ActionType extends ExpandableStringEnum { /** - * Static value Internal for ActionType. + * Actions are for internal-only APIs. */ public static final ActionType INTERNAL = fromString("Internal"); diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/Association.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/Association.java index 2436e88d9b82..ae249f116888 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/Association.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/Association.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationProperties.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationProperties.java index 47fe83b74b16..5c58cf24054c 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationProperties.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationProperties.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationSubnet.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationSubnet.java index 163b2dd1486d..a4129acb6a18 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationSubnet.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationSubnet.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationSubnetUpdate.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationSubnetUpdate.java index 151e55fb2b63..e34090491db5 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationSubnetUpdate.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationSubnetUpdate.java @@ -1,10 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; import com.azure.core.annotation.Fluent; +import com.azure.core.util.logging.ClientLogger; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -53,8 +54,14 @@ public AssociationSubnetUpdate withId(String id) { * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { + if (id() == null) { + throw LOGGER.atError() + .log(new IllegalArgumentException("Missing required property id in model AssociationSubnetUpdate")); + } } + private static final ClientLogger LOGGER = new ClientLogger(AssociationSubnetUpdate.class); + /** * {@inheritDoc} */ @@ -71,6 +78,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @param jsonReader The JsonReader being read. * @return An instance of AssociationSubnetUpdate 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 AssociationSubnetUpdate. */ public static AssociationSubnetUpdate fromJson(JsonReader jsonReader) throws IOException { diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationType.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationType.java index 57b0fa80882e..491c78fea9a2 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationType.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationType.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; @@ -12,7 +12,7 @@ */ public final class AssociationType extends ExpandableStringEnum { /** - * Static value subnets for AssociationType. + * Association of Type Subnet. */ public static final AssociationType SUBNETS = fromString("subnets"); diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationUpdate.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationUpdate.java index 6a00904a7293..27b3bedae2aa 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationUpdate.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationUpdate.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationUpdateProperties.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationUpdateProperties.java index deeceed87755..3beaa677dda0 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationUpdateProperties.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationUpdateProperties.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationsInterfaces.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationsInterfaces.java index f8200b7961d2..3d3c5c827eec 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationsInterfaces.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/AssociationsInterfaces.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; @@ -13,83 +13,83 @@ */ public interface AssociationsInterfaces { /** - * List Association resources by TrafficController. + * Get a Association. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param trafficControllerName traffic controller name for path. + * @param associationName Name of Association. + * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Association list operation as paginated response with {@link PagedIterable}. + * @return a Association along with {@link Response}. */ - PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName); + Response getWithResponse(String resourceGroupName, String trafficControllerName, + String associationName, Context context); /** - * List Association resources by TrafficController. + * Get a Association. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param trafficControllerName traffic controller name for path. - * @param context The context to associate with this operation. + * @param associationName Name of Association. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Association list operation as paginated response with {@link PagedIterable}. + * @return a Association. */ - PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName, - Context context); + Association get(String resourceGroupName, String trafficControllerName, String associationName); /** - * Get a Association. + * Delete a Association. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param trafficControllerName traffic controller name for path. * @param associationName Name of Association. - * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Association along with {@link Response}. */ - Response getWithResponse(String resourceGroupName, String trafficControllerName, - String associationName, Context context); + void delete(String resourceGroupName, String trafficControllerName, String associationName); /** - * Get a Association. + * Delete a Association. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param trafficControllerName traffic controller name for path. * @param associationName Name of Association. + * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Association. */ - Association get(String resourceGroupName, String trafficControllerName, String associationName); + void delete(String resourceGroupName, String trafficControllerName, String associationName, Context context); /** - * Delete a Association. + * List Association resources by TrafficController. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param trafficControllerName traffic controller name for path. - * @param associationName Name of Association. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Association list operation as paginated response with {@link PagedIterable}. */ - void delete(String resourceGroupName, String trafficControllerName, String associationName); + PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName); /** - * Delete a Association. + * List Association resources by TrafficController. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param trafficControllerName traffic controller name for path. - * @param associationName Name of Association. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Association list operation as paginated response with {@link PagedIterable}. */ - void delete(String resourceGroupName, String trafficControllerName, String associationName, Context context); + PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName, + Context context); /** * Get a Association. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/Frontend.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/Frontend.java index c1b551f5745d..47c97e09248e 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/Frontend.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/Frontend.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/FrontendProperties.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/FrontendProperties.java index f0280800d919..85e68237ba59 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/FrontendProperties.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/FrontendProperties.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/FrontendUpdate.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/FrontendUpdate.java index 26cf13c246d8..b4c269700317 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/FrontendUpdate.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/FrontendUpdate.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/FrontendsInterfaces.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/FrontendsInterfaces.java index 35f20ea28067..5ee48e3e74a4 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/FrontendsInterfaces.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/FrontendsInterfaces.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; @@ -13,83 +13,83 @@ */ public interface FrontendsInterfaces { /** - * List Frontend resources by TrafficController. + * Get a Frontend. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param trafficControllerName traffic controller name for path. + * @param frontendName Frontends. + * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Frontend list operation as paginated response with {@link PagedIterable}. + * @return a Frontend along with {@link Response}. */ - PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName); + Response getWithResponse(String resourceGroupName, String trafficControllerName, String frontendName, + Context context); /** - * List Frontend resources by TrafficController. + * Get a Frontend. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param trafficControllerName traffic controller name for path. - * @param context The context to associate with this operation. + * @param frontendName Frontends. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a Frontend list operation as paginated response with {@link PagedIterable}. + * @return a Frontend. */ - PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName, - Context context); + Frontend get(String resourceGroupName, String trafficControllerName, String frontendName); /** - * Get a Frontend. + * Delete a Frontend. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param trafficControllerName traffic controller name for path. * @param frontendName Frontends. - * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Frontend along with {@link Response}. */ - Response getWithResponse(String resourceGroupName, String trafficControllerName, String frontendName, - Context context); + void delete(String resourceGroupName, String trafficControllerName, String frontendName); /** - * Get a Frontend. + * Delete a Frontend. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param trafficControllerName traffic controller name for path. * @param frontendName Frontends. + * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a Frontend. */ - Frontend get(String resourceGroupName, String trafficControllerName, String frontendName); + void delete(String resourceGroupName, String trafficControllerName, String frontendName, Context context); /** - * Delete a Frontend. + * List Frontend resources by TrafficController. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param trafficControllerName traffic controller name for path. - * @param frontendName Frontends. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Frontend list operation as paginated response with {@link PagedIterable}. */ - void delete(String resourceGroupName, String trafficControllerName, String frontendName); + PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName); /** - * Delete a Frontend. + * List Frontend resources by TrafficController. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param trafficControllerName traffic controller name for path. - * @param frontendName Frontends. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a Frontend list operation as paginated response with {@link PagedIterable}. */ - void delete(String resourceGroupName, String trafficControllerName, String frontendName, Context context); + PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName, + Context context); /** * Get a Frontend. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/Operation.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/Operation.java index 52934f6cfbf3..01e80254ce9b 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/Operation.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/Operation.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; @@ -20,7 +20,7 @@ public interface Operation { /** * Gets the isDataAction property: Whether the operation applies to data-plane. This is "true" for data-plane - * operations and "false" for ARM/control-plane operations. + * operations and "false" for Azure Resource Manager/control-plane operations. * * @return the isDataAction value. */ @@ -42,8 +42,8 @@ public interface Operation { Origin origin(); /** - * Gets the actionType property: Enum. Indicates the action type. "Internal" refers to actions that are for internal - * only APIs. + * Gets the actionType property: Extensible enum. Indicates the action type. "Internal" refers to actions that are + * for internal only APIs. * * @return the actionType value. */ diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/OperationDisplay.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/OperationDisplay.java index fcd07604337d..6ab2c6e98f9b 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/OperationDisplay.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/OperationDisplay.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; @@ -12,7 +12,7 @@ import java.io.IOException; /** - * Localized display information for this particular operation. + * Localized display information for and operation. */ @Immutable public final class OperationDisplay implements JsonSerializable { @@ -42,7 +42,7 @@ public final class OperationDisplay implements JsonSerializable { - /* - * List of operations supported by the resource provider - */ - private List value; - - /* - * URL to get the next set of operation list results (if there are any). - */ - private String nextLink; - - /** - * Creates an instance of OperationListResult class. - */ - public OperationListResult() { - } - - /** - * Get the value property: List of operations supported by the resource provider. - * - * @return the value value. - */ - public List value() { - return this.value; - } - - /** - * Get the nextLink property: URL to get the next set of operation list results (if there are any). - * - * @return the nextLink value. - */ - public String nextLink() { - return this.nextLink; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (value() != null) { - value().forEach(e -> e.validate()); - } - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of OperationListResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of OperationListResult 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 OperationListResult. - */ - public static OperationListResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - OperationListResult deserializedOperationListResult = new OperationListResult(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - List value = reader.readArray(reader1 -> OperationInner.fromJson(reader1)); - deserializedOperationListResult.value = value; - } else if ("nextLink".equals(fieldName)) { - deserializedOperationListResult.nextLink = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedOperationListResult; - }); - } -} diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/Operations.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/Operations.java index 93b528aaaa37..9edaea21fad6 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/Operations.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/Operations.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/Origin.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/Origin.java index de3d85a19d09..ad9a97c89aff 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/Origin.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/Origin.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; @@ -13,17 +13,17 @@ */ public final class Origin extends ExpandableStringEnum { /** - * Static value user for Origin. + * Indicates the operation is initiated by a user. */ public static final Origin USER = fromString("user"); /** - * Static value system for Origin. + * Indicates the operation is initiated by a system. */ public static final Origin SYSTEM = fromString("system"); /** - * Static value user,system for Origin. + * Indicates the operation is initiated by a user or system. */ public static final Origin USER_SYSTEM = fromString("user,system"); diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/PolicyType.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/PolicyType.java index 454fe62bb988..1eb6df9b9b01 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/PolicyType.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/PolicyType.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; @@ -12,7 +12,7 @@ */ public final class PolicyType extends ExpandableStringEnum { /** - * Static value waf for PolicyType. + * Policy of Type WAF. */ public static final PolicyType WAF = fromString("waf"); diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/ProvisioningState.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/ProvisioningState.java index b8bc32c69804..d35e23fe76a6 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/ProvisioningState.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/ProvisioningState.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; @@ -12,37 +12,37 @@ */ public final class ProvisioningState extends ExpandableStringEnum { /** - * Static value Provisioning for ProvisioningState. + * Resource in Provisioning State. */ public static final ProvisioningState PROVISIONING = fromString("Provisioning"); /** - * Static value Updating for ProvisioningState. + * Resource in Updating State. */ public static final ProvisioningState UPDATING = fromString("Updating"); /** - * Static value Deleting for ProvisioningState. + * Resource in Deleting State. */ public static final ProvisioningState DELETING = fromString("Deleting"); /** - * Static value Accepted for ProvisioningState. + * Resource in Accepted State. */ public static final ProvisioningState ACCEPTED = fromString("Accepted"); /** - * Static value Succeeded for ProvisioningState. + * Resource in Succeeded State. */ public static final ProvisioningState SUCCEEDED = fromString("Succeeded"); /** - * Static value Failed for ProvisioningState. + * Resource in Failed State. */ public static final ProvisioningState FAILED = fromString("Failed"); /** - * Static value Canceled for ProvisioningState. + * Resource in Canceled State. */ public static final ProvisioningState CANCELED = fromString("Canceled"); diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/ResourceId.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/ResourceId.java index e9c855efc9f9..ab8af5bf4d44 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/ResourceId.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/ResourceId.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Immutable; import com.azure.core.util.logging.ClientLogger; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -15,7 +15,7 @@ /** * Resource ID definition used by parent to reference child resources. */ -@Fluent +@Immutable public final class ResourceId implements JsonSerializable { /* * Resource ID of child resource. @@ -25,7 +25,7 @@ public final class ResourceId implements JsonSerializable { /** * Creates an instance of ResourceId class. */ - public ResourceId() { + private ResourceId() { } /** @@ -37,17 +37,6 @@ public String id() { return this.id; } - /** - * Set the id property: Resource ID of child resource. - * - * @param id the id value to set. - * @return the ResourceId object itself. - */ - public ResourceId withId(String id) { - this.id = id; - return this; - } - /** * Validates the instance. * diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPoliciesInterfaces.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPoliciesInterfaces.java index ba36491f4dc8..52bb45821ca7 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPoliciesInterfaces.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPoliciesInterfaces.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; @@ -13,83 +13,83 @@ */ public interface SecurityPoliciesInterfaces { /** - * List SecurityPolicy resources by TrafficController. + * Get a SecurityPolicy. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param trafficControllerName traffic controller name for path. + * @param securityPolicyName SecurityPolicy. + * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SecurityPolicy list operation as paginated response with {@link PagedIterable}. + * @return a SecurityPolicy along with {@link Response}. */ - PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName); + Response getWithResponse(String resourceGroupName, String trafficControllerName, + String securityPolicyName, Context context); /** - * List SecurityPolicy resources by TrafficController. + * Get a SecurityPolicy. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param trafficControllerName traffic controller name for path. - * @param context The context to associate with this operation. + * @param securityPolicyName SecurityPolicy. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a SecurityPolicy list operation as paginated response with {@link PagedIterable}. + * @return a SecurityPolicy. */ - PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName, - Context context); + SecurityPolicy get(String resourceGroupName, String trafficControllerName, String securityPolicyName); /** - * Get a SecurityPolicy. + * Delete a SecurityPolicy. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param trafficControllerName traffic controller name for path. * @param securityPolicyName SecurityPolicy. - * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a SecurityPolicy along with {@link Response}. */ - Response getWithResponse(String resourceGroupName, String trafficControllerName, - String securityPolicyName, Context context); + void delete(String resourceGroupName, String trafficControllerName, String securityPolicyName); /** - * Get a SecurityPolicy. + * Delete a SecurityPolicy. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param trafficControllerName traffic controller name for path. * @param securityPolicyName SecurityPolicy. + * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a SecurityPolicy. */ - SecurityPolicy get(String resourceGroupName, String trafficControllerName, String securityPolicyName); + void delete(String resourceGroupName, String trafficControllerName, String securityPolicyName, Context context); /** - * Delete a SecurityPolicy. + * List SecurityPolicy resources by TrafficController. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param trafficControllerName traffic controller name for path. - * @param securityPolicyName SecurityPolicy. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SecurityPolicy list operation as paginated response with {@link PagedIterable}. */ - void delete(String resourceGroupName, String trafficControllerName, String securityPolicyName); + PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName); /** - * Delete a SecurityPolicy. + * List SecurityPolicy resources by TrafficController. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param trafficControllerName traffic controller name for path. - * @param securityPolicyName SecurityPolicy. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a SecurityPolicy list operation as paginated response with {@link PagedIterable}. */ - void delete(String resourceGroupName, String trafficControllerName, String securityPolicyName, Context context); + PagedIterable listByTrafficController(String resourceGroupName, String trafficControllerName, + Context context); /** * Get a SecurityPolicy. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPolicy.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPolicy.java index 9365a75f864f..339d796f588c 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPolicy.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPolicy.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPolicyConfigurations.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPolicyConfigurations.java index 5b822911c942..7cb469dcf8ce 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPolicyConfigurations.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPolicyConfigurations.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPolicyConfigurationsUpdate.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPolicyConfigurationsUpdate.java deleted file mode 100644 index 3d42fc617140..000000000000 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPolicyConfigurationsUpdate.java +++ /dev/null @@ -1,100 +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.resourcemanager.servicenetworking.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; - -/** - * SecurityPolicyConfigurations Subresource of Traffic Controller. - */ -@Fluent -public final class SecurityPolicyConfigurationsUpdate implements JsonSerializable { - /* - * Contains reference to a WAF-type security policy that is applied at the Traffic Controller level. - */ - private WafSecurityPolicyUpdate wafSecurityPolicy; - - /** - * Creates an instance of SecurityPolicyConfigurationsUpdate class. - */ - public SecurityPolicyConfigurationsUpdate() { - } - - /** - * Get the wafSecurityPolicy property: Contains reference to a WAF-type security policy that is applied at the - * Traffic Controller level. - * - * @return the wafSecurityPolicy value. - */ - public WafSecurityPolicyUpdate wafSecurityPolicy() { - return this.wafSecurityPolicy; - } - - /** - * Set the wafSecurityPolicy property: Contains reference to a WAF-type security policy that is applied at the - * Traffic Controller level. - * - * @param wafSecurityPolicy the wafSecurityPolicy value to set. - * @return the SecurityPolicyConfigurationsUpdate object itself. - */ - public SecurityPolicyConfigurationsUpdate withWafSecurityPolicy(WafSecurityPolicyUpdate wafSecurityPolicy) { - this.wafSecurityPolicy = wafSecurityPolicy; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - if (wafSecurityPolicy() != null) { - wafSecurityPolicy().validate(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeJsonField("wafSecurityPolicy", this.wafSecurityPolicy); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SecurityPolicyConfigurationsUpdate from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SecurityPolicyConfigurationsUpdate 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 SecurityPolicyConfigurationsUpdate. - */ - public static SecurityPolicyConfigurationsUpdate fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SecurityPolicyConfigurationsUpdate deserializedSecurityPolicyConfigurationsUpdate - = new SecurityPolicyConfigurationsUpdate(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("wafSecurityPolicy".equals(fieldName)) { - deserializedSecurityPolicyConfigurationsUpdate.wafSecurityPolicy - = WafSecurityPolicyUpdate.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedSecurityPolicyConfigurationsUpdate; - }); - } -} diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPolicyProperties.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPolicyProperties.java index 1afe95a42b2a..62b542d40410 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPolicyProperties.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPolicyProperties.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPolicyUpdate.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPolicyUpdate.java index 8349f5e83344..448e9cf21c52 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPolicyUpdate.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPolicyUpdate.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPolicyUpdateProperties.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPolicyUpdateProperties.java index 162901ceb5f2..9555edf56325 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPolicyUpdateProperties.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/SecurityPolicyUpdateProperties.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; @@ -19,7 +19,7 @@ public final class SecurityPolicyUpdateProperties implements JsonSerializable list(); + Response getByResourceGroupWithResponse(String resourceGroupName, String trafficControllerName, + Context context); /** - * List TrafficController resources by subscription ID. + * Get a TrafficController. * - * @param context The context to associate with this operation. + * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param trafficControllerName traffic controller name for path. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a TrafficController list operation as paginated response with {@link PagedIterable}. + * @return a TrafficController. */ - PagedIterable list(Context context); + TrafficController getByResourceGroup(String resourceGroupName, String trafficControllerName); /** - * List TrafficController resources by resource group. + * Delete a TrafficController. * * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param trafficControllerName traffic controller name for path. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a TrafficController list operation as paginated response with {@link PagedIterable}. */ - PagedIterable listByResourceGroup(String resourceGroupName); + void deleteByResourceGroup(String resourceGroupName, String trafficControllerName); /** - * List TrafficController resources by resource group. + * Delete a TrafficController. * * @param resourceGroupName The name of the resource group. The name is case insensitive. + * @param trafficControllerName traffic controller name for path. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response of a TrafficController list operation as paginated response with {@link PagedIterable}. */ - PagedIterable listByResourceGroup(String resourceGroupName, Context context); + void delete(String resourceGroupName, String trafficControllerName, Context context); /** - * Get a TrafficController. + * List TrafficController resources by resource group. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param trafficControllerName traffic controller name for path. - * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a TrafficController along with {@link Response}. + * @return the response of a TrafficController list operation as paginated response with {@link PagedIterable}. */ - Response getByResourceGroupWithResponse(String resourceGroupName, String trafficControllerName, - Context context); + PagedIterable listByResourceGroup(String resourceGroupName); /** - * Get a TrafficController. + * List TrafficController resources by resource group. * * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param trafficControllerName traffic controller name for path. + * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a TrafficController. + * @return the response of a TrafficController list operation as paginated response with {@link PagedIterable}. */ - TrafficController getByResourceGroup(String resourceGroupName, String trafficControllerName); + PagedIterable listByResourceGroup(String resourceGroupName, Context context); /** - * Delete a TrafficController. + * List TrafficController resources by subscription ID. * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param trafficControllerName traffic controller name for path. - * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a TrafficController list operation as paginated response with {@link PagedIterable}. */ - void deleteByResourceGroup(String resourceGroupName, String trafficControllerName); + PagedIterable list(); /** - * Delete a TrafficController. + * List TrafficController resources by subscription ID. * - * @param resourceGroupName The name of the resource group. The name is case insensitive. - * @param trafficControllerName traffic controller name for path. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response of a TrafficController list operation as paginated response with {@link PagedIterable}. */ - void delete(String resourceGroupName, String trafficControllerName, Context context); + PagedIterable list(Context context); /** * Get a TrafficController. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/TrafficControllerProperties.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/TrafficControllerProperties.java index 17faaa2028e0..026b04e45949 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/TrafficControllerProperties.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/TrafficControllerProperties.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/TrafficControllerUpdate.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/TrafficControllerUpdate.java index bb17bda735cb..55abec76d5d1 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/TrafficControllerUpdate.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/TrafficControllerUpdate.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/TrafficControllerUpdateProperties.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/TrafficControllerUpdateProperties.java index 73a4af599882..540f5f74d8aa 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/TrafficControllerUpdateProperties.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/TrafficControllerUpdateProperties.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; @@ -19,7 +19,7 @@ public final class TrafficControllerUpdateProperties implements JsonSerializable /* * Security Policy Configuration */ - private SecurityPolicyConfigurationsUpdate securityPolicyConfigurations; + private SecurityPolicyConfigurations securityPolicyConfigurations; /** * Creates an instance of TrafficControllerUpdateProperties class. @@ -32,7 +32,7 @@ public TrafficControllerUpdateProperties() { * * @return the securityPolicyConfigurations value. */ - public SecurityPolicyConfigurationsUpdate securityPolicyConfigurations() { + public SecurityPolicyConfigurations securityPolicyConfigurations() { return this.securityPolicyConfigurations; } @@ -43,7 +43,7 @@ public SecurityPolicyConfigurationsUpdate securityPolicyConfigurations() { * @return the TrafficControllerUpdateProperties object itself. */ public TrafficControllerUpdateProperties - withSecurityPolicyConfigurations(SecurityPolicyConfigurationsUpdate securityPolicyConfigurations) { + withSecurityPolicyConfigurations(SecurityPolicyConfigurations securityPolicyConfigurations) { this.securityPolicyConfigurations = securityPolicyConfigurations; return this; } @@ -87,7 +87,7 @@ public static TrafficControllerUpdateProperties fromJson(JsonReader jsonReader) if ("securityPolicyConfigurations".equals(fieldName)) { deserializedTrafficControllerUpdateProperties.securityPolicyConfigurations - = SecurityPolicyConfigurationsUpdate.fromJson(reader); + = SecurityPolicyConfigurations.fromJson(reader); } else { reader.skipChildren(); } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/WafPolicy.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/WafPolicy.java index a4da2b9a1907..4a7af2cd7c8d 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/WafPolicy.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/WafPolicy.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/WafPolicyUpdate.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/WafPolicyUpdate.java deleted file mode 100644 index 971eaafc3906..000000000000 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/WafPolicyUpdate.java +++ /dev/null @@ -1,93 +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.resourcemanager.servicenetworking.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; - -/** - * Web Application Firewall Policy. - */ -@Fluent -public final class WafPolicyUpdate implements JsonSerializable { - /* - * Resource ID of the WAF - */ - private String id; - - /** - * Creates an instance of WafPolicyUpdate class. - */ - public WafPolicyUpdate() { - } - - /** - * Get the id property: Resource ID of the WAF. - * - * @return the id value. - */ - public String id() { - return this.id; - } - - /** - * Set the id property: Resource ID of the WAF. - * - * @param id the id value to set. - * @return the WafPolicyUpdate object itself. - */ - public WafPolicyUpdate withId(String id) { - this.id = id; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("id", this.id); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of WafPolicyUpdate from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of WafPolicyUpdate 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 WafPolicyUpdate. - */ - public static WafPolicyUpdate fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - WafPolicyUpdate deserializedWafPolicyUpdate = new WafPolicyUpdate(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("id".equals(fieldName)) { - deserializedWafPolicyUpdate.id = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedWafPolicyUpdate; - }); - } -} diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/WafSecurityPolicy.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/WafSecurityPolicy.java index 25a8b712e41e..b70b16a2ff9b 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/WafSecurityPolicy.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/WafSecurityPolicy.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.models; diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/WafSecurityPolicyUpdate.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/WafSecurityPolicyUpdate.java deleted file mode 100644 index 8e431666961e..000000000000 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/WafSecurityPolicyUpdate.java +++ /dev/null @@ -1,93 +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.resourcemanager.servicenetworking.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; - -/** - * Web Application Firewall Security Policy. - */ -@Fluent -public final class WafSecurityPolicyUpdate implements JsonSerializable { - /* - * Resource ID of the Waf Security Policy - */ - private String id; - - /** - * Creates an instance of WafSecurityPolicyUpdate class. - */ - public WafSecurityPolicyUpdate() { - } - - /** - * Get the id property: Resource ID of the Waf Security Policy. - * - * @return the id value. - */ - public String id() { - return this.id; - } - - /** - * Set the id property: Resource ID of the Waf Security Policy. - * - * @param id the id value to set. - * @return the WafSecurityPolicyUpdate object itself. - */ - public WafSecurityPolicyUpdate withId(String id) { - this.id = id; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("id", this.id); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of WafSecurityPolicyUpdate from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of WafSecurityPolicyUpdate 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 WafSecurityPolicyUpdate. - */ - public static WafSecurityPolicyUpdate fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - WafSecurityPolicyUpdate deserializedWafSecurityPolicyUpdate = new WafSecurityPolicyUpdate(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("id".equals(fieldName)) { - deserializedWafSecurityPolicyUpdate.id = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedWafSecurityPolicyUpdate; - }); - } -} diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/package-info.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/package-info.java index 28042ec00208..6dfe7097ddbf 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/package-info.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/models/package-info.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. /** * Package containing the data models for TrafficControllerManagementClient. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/package-info.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/package-info.java index b0363c4baa6d..f8caabb10462 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/package-info.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/com/azure/resourcemanager/servicenetworking/package-info.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. /** * Package containing the classes for TrafficControllerManagementClient. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/module-info.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/module-info.java index e2c2a4c2af40..4e112e96d1a3 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/module-info.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/java/module-info.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. module com.azure.resourcemanager.servicenetworking { requires transitive com.azure.core.management; @@ -12,4 +12,5 @@ opens com.azure.resourcemanager.servicenetworking.fluent.models to com.azure.core; opens com.azure.resourcemanager.servicenetworking.models to com.azure.core; + opens com.azure.resourcemanager.servicenetworking.implementation.models to com.azure.core; } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/resources/azure-resourcemanager-servicenetworking.properties b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/resources/azure-resourcemanager-servicenetworking.properties new file mode 100644 index 000000000000..defbd48204e4 --- /dev/null +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/main/resources/azure-resourcemanager-servicenetworking.properties @@ -0,0 +1 @@ +version=${project.version} diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfaceCreateOrUpdateSamples.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfaceCreateOrUpdateSamples.java index 6510989327bc..ab944c91693e 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfaceCreateOrUpdateSamples.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfaceCreateOrUpdateSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -13,9 +13,7 @@ */ public final class AssociationsInterfaceCreateOrUpdateSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * AssociationPut.json + * x-ms-original-file: 2025-01-01/AssociationPut.json */ /** * Sample code: Put Association. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfaceDeleteSamples.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfaceDeleteSamples.java index ca57fa0bd57a..46eb3a96f1fc 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfaceDeleteSamples.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfaceDeleteSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -9,9 +9,7 @@ */ public final class AssociationsInterfaceDeleteSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * AssociationDelete.json + * x-ms-original-file: 2025-01-01/AssociationDelete.json */ /** * Sample code: Delete Association. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfaceGetSamples.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfaceGetSamples.java index bca32f140fff..6b7a83b4c8da 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfaceGetSamples.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfaceGetSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -9,9 +9,7 @@ */ public final class AssociationsInterfaceGetSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * AssociationGet.json + * x-ms-original-file: 2025-01-01/AssociationGet.json */ /** * Sample code: Get Association. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfaceListByTrafficControllerSamples.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfaceListByTrafficControllerSamples.java index d4442c0beebd..a11af15c14ee 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfaceListByTrafficControllerSamples.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfaceListByTrafficControllerSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -9,9 +9,7 @@ */ public final class AssociationsInterfaceListByTrafficControllerSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * AssociationsGet.json + * x-ms-original-file: 2025-01-01/AssociationsGet.json */ /** * Sample code: Get Associations. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfaceUpdateSamples.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfaceUpdateSamples.java index 0331c6dbc139..be32fc4fad81 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfaceUpdateSamples.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfaceUpdateSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -14,9 +14,7 @@ */ public final class AssociationsInterfaceUpdateSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * AssociationPatch.json + * x-ms-original-file: 2025-01-01/AssociationPatch.json */ /** * Sample code: Update Association. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfaceCreateOrUpdateSamples.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfaceCreateOrUpdateSamples.java index 105f54334c6a..868ed14117a8 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfaceCreateOrUpdateSamples.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfaceCreateOrUpdateSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -11,9 +11,7 @@ */ public final class FrontendsInterfaceCreateOrUpdateSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * FrontendPut.json + * x-ms-original-file: 2025-01-01/FrontendPut.json */ /** * Sample code: Put Frontend. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfaceDeleteSamples.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfaceDeleteSamples.java index 08580dcf52e3..aa1e87e3c9ed 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfaceDeleteSamples.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfaceDeleteSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -9,9 +9,7 @@ */ public final class FrontendsInterfaceDeleteSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * FrontendDelete.json + * x-ms-original-file: 2025-01-01/FrontendDelete.json */ /** * Sample code: Delete Frontend. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfaceGetSamples.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfaceGetSamples.java index a00dffca8437..b41195ed666f 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfaceGetSamples.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfaceGetSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -9,9 +9,7 @@ */ public final class FrontendsInterfaceGetSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * FrontendGet.json + * x-ms-original-file: 2025-01-01/FrontendGet.json */ /** * Sample code: Get Frontend. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfaceListByTrafficControllerSamples.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfaceListByTrafficControllerSamples.java index 6a54d7730545..14253752f46c 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfaceListByTrafficControllerSamples.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfaceListByTrafficControllerSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -9,9 +9,7 @@ */ public final class FrontendsInterfaceListByTrafficControllerSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * FrontendsGet.json + * x-ms-original-file: 2025-01-01/FrontendsGet.json */ /** * Sample code: Get Frontends. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfaceUpdateSamples.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfaceUpdateSamples.java index 330f0c996796..4f0c3068c5b6 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfaceUpdateSamples.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfaceUpdateSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -11,9 +11,7 @@ */ public final class FrontendsInterfaceUpdateSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * FrontendPatch.json + * x-ms-original-file: 2025-01-01/FrontendPatch.json */ /** * Sample code: Update Frontend. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/OperationsListSamples.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/OperationsListSamples.java index cfb9e91b50a3..1861b77c5a0d 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/OperationsListSamples.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/OperationsListSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -9,9 +9,7 @@ */ public final class OperationsListSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * OperationsList.json + * x-ms-original-file: 2025-01-01/OperationsList.json */ /** * Sample code: Get Operations List. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfaceCreateOrUpdateSamples.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfaceCreateOrUpdateSamples.java index 54373a08e58e..2b5741f872a7 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfaceCreateOrUpdateSamples.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfaceCreateOrUpdateSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -12,9 +12,7 @@ */ public final class SecurityPoliciesInterfaceCreateOrUpdateSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * SecurityPolicyPut.json + * x-ms-original-file: 2025-01-01/SecurityPolicyPut.json */ /** * Sample code: Put SecurityPolicy. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfaceDeleteSamples.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfaceDeleteSamples.java index 89204de3a0fe..f2374819aab3 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfaceDeleteSamples.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfaceDeleteSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -9,9 +9,7 @@ */ public final class SecurityPoliciesInterfaceDeleteSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * SecurityPolicyDelete.json + * x-ms-original-file: 2025-01-01/SecurityPolicyDelete.json */ /** * Sample code: Delete SecurityPolicy. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfaceGetSamples.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfaceGetSamples.java index 76da22b5fedb..7c2ea512e0b1 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfaceGetSamples.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfaceGetSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -9,9 +9,7 @@ */ public final class SecurityPoliciesInterfaceGetSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * SecurityPolicyGet.json + * x-ms-original-file: 2025-01-01/SecurityPolicyGet.json */ /** * Sample code: Get SecurityPolicy. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfaceListByTrafficControllerSamples.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfaceListByTrafficControllerSamples.java index ee2949b53779..29ea5a62bc34 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfaceListByTrafficControllerSamples.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfaceListByTrafficControllerSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -9,9 +9,7 @@ */ public final class SecurityPoliciesInterfaceListByTrafficControllerSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * SecurityPoliciesGetList.json + * x-ms-original-file: 2025-01-01/SecurityPoliciesGetList.json */ /** * Sample code: Get SecurityPolicies. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfaceUpdateSamples.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfaceUpdateSamples.java index 90f31edd8b63..5d1ef468fcb4 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfaceUpdateSamples.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfaceUpdateSamples.java @@ -1,21 +1,19 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; import com.azure.resourcemanager.servicenetworking.models.SecurityPolicy; import com.azure.resourcemanager.servicenetworking.models.SecurityPolicyUpdateProperties; -import com.azure.resourcemanager.servicenetworking.models.WafPolicyUpdate; +import com.azure.resourcemanager.servicenetworking.models.WafPolicy; /** * Samples for SecurityPoliciesInterface Update. */ public final class SecurityPoliciesInterfaceUpdateSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * SecurityPolicyPatch.json + * x-ms-original-file: 2025-01-01/SecurityPolicyPatch.json */ /** * Sample code: Update SecurityPolicy. @@ -28,7 +26,7 @@ public final class SecurityPoliciesInterfaceUpdateSamples { .getWithResponse("rg1", "tc1", "sp1", com.azure.core.util.Context.NONE) .getValue(); resource.update() - .withProperties(new SecurityPolicyUpdateProperties().withWafPolicy(new WafPolicyUpdate().withId( + .withProperties(new SecurityPolicyUpdateProperties().withWafPolicy(new WafPolicy().withId( "/subscriptions/subid/resourcegroups/rg1/providers/Microsoft.Networking/applicationGatewayWebApplicationFirewallPolicies/wp-0"))) .apply(); } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfaceCreateOrUpdateSamples.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfaceCreateOrUpdateSamples.java index 55e920e4ef9f..f1281458a915 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfaceCreateOrUpdateSamples.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfaceCreateOrUpdateSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -12,9 +12,7 @@ */ public final class TrafficControllerInterfaceCreateOrUpdateSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * TrafficControllerPut.json + * x-ms-original-file: 2025-01-01/TrafficControllerPut.json */ /** * Sample code: Put Traffic Controller. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfaceDeleteSamples.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfaceDeleteSamples.java index 2c653c2007b1..38eaaa20b15e 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfaceDeleteSamples.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfaceDeleteSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -9,9 +9,7 @@ */ public final class TrafficControllerInterfaceDeleteSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * TrafficControllerDelete.json + * x-ms-original-file: 2025-01-01/TrafficControllerDelete.json */ /** * Sample code: Delete Traffic Controller. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfaceGetByResourceGroupSamples.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfaceGetByResourceGroupSamples.java index 261072b88777..d88be41a0bc4 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfaceGetByResourceGroupSamples.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfaceGetByResourceGroupSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -9,9 +9,7 @@ */ public final class TrafficControllerInterfaceGetByResourceGroupSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * TrafficControllerGet.json + * x-ms-original-file: 2025-01-01/TrafficControllerGet.json */ /** * Sample code: Get Traffic Controller. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfaceListByResourceGroupSamples.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfaceListByResourceGroupSamples.java index 275286f19ed0..752e0454eb2e 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfaceListByResourceGroupSamples.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfaceListByResourceGroupSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -9,9 +9,7 @@ */ public final class TrafficControllerInterfaceListByResourceGroupSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * TrafficControllersGet.json + * x-ms-original-file: 2025-01-01/TrafficControllersGet.json */ /** * Sample code: Get Traffic Controllers. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfaceListSamples.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfaceListSamples.java index 7f0d08efe069..3f696918d191 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfaceListSamples.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfaceListSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -9,9 +9,7 @@ */ public final class TrafficControllerInterfaceListSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * TrafficControllersGetList.json + * x-ms-original-file: 2025-01-01/TrafficControllersGetList.json */ /** * Sample code: Get Traffic Controllers List. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfaceUpdateSamples.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfaceUpdateSamples.java index 4a4dfbe20bc5..bf73e4f3d9b4 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfaceUpdateSamples.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/samples/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfaceUpdateSamples.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -13,9 +13,7 @@ */ public final class TrafficControllerInterfaceUpdateSamples { /* - * x-ms-original-file: - * specification/servicenetworking/resource-manager/Microsoft.ServiceNetworking/preview/2024-05-01-preview/examples/ - * TrafficControllerPatch.json + * x-ms-original-file: 2025-01-01/TrafficControllerPatch.json */ /** * Sample code: Patch Traffic Controller. diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationInnerTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationInnerTests.java index 8c58e614761e..f5c513073e38 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationInnerTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationInnerTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -17,25 +17,25 @@ public final class AssociationInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { AssociationInner model = BinaryData.fromString( - "{\"properties\":{\"associationType\":\"subnets\",\"subnet\":{\"id\":\"xgjvtbv\"},\"provisioningState\":\"Deleting\"},\"location\":\"zdn\",\"tags\":{\"qfprwzwbn\":\"qguhmuo\"},\"id\":\"uitnwuiz\",\"name\":\"a\",\"type\":\"x\"}") + "{\"properties\":{\"associationType\":\"subnets\",\"subnet\":{\"id\":\"quvgjxpybczme\"},\"provisioningState\":\"Failed\"},\"location\":\"opb\",\"tags\":{\"ejhphoyc\":\"rupidgsyb\"},\"id\":\"sx\",\"name\":\"obhdxbmtqioqjze\",\"type\":\"tbmufpo\"}") .toObject(AssociationInner.class); - Assertions.assertEquals("zdn", model.location()); - Assertions.assertEquals("qguhmuo", model.tags().get("qfprwzwbn")); + Assertions.assertEquals("opb", model.location()); + Assertions.assertEquals("rupidgsyb", model.tags().get("ejhphoyc")); Assertions.assertEquals(AssociationType.SUBNETS, model.properties().associationType()); - Assertions.assertEquals("xgjvtbv", model.properties().subnet().id()); + Assertions.assertEquals("quvgjxpybczme", model.properties().subnet().id()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - AssociationInner model = new AssociationInner().withLocation("zdn") - .withTags(mapOf("qfprwzwbn", "qguhmuo")) + AssociationInner model = new AssociationInner().withLocation("opb") + .withTags(mapOf("ejhphoyc", "rupidgsyb")) .withProperties(new AssociationProperties().withAssociationType(AssociationType.SUBNETS) - .withSubnet(new AssociationSubnet().withId("xgjvtbv"))); + .withSubnet(new AssociationSubnet().withId("quvgjxpybczme"))); model = BinaryData.fromObject(model).toObject(AssociationInner.class); - Assertions.assertEquals("zdn", model.location()); - Assertions.assertEquals("qguhmuo", model.tags().get("qfprwzwbn")); + Assertions.assertEquals("opb", model.location()); + Assertions.assertEquals("rupidgsyb", model.tags().get("ejhphoyc")); Assertions.assertEquals(AssociationType.SUBNETS, model.properties().associationType()); - Assertions.assertEquals("xgjvtbv", model.properties().subnet().id()); + Assertions.assertEquals("quvgjxpybczme", model.properties().subnet().id()); } // Use "Map.of" if available diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationListResultTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationListResultTests.java index 04bb06025bc2..0f67d464cfae 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationListResultTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationListResultTests.java @@ -1,62 +1,24 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.servicenetworking.fluent.models.AssociationInner; -import com.azure.resourcemanager.servicenetworking.models.AssociationListResult; -import com.azure.resourcemanager.servicenetworking.models.AssociationProperties; -import com.azure.resourcemanager.servicenetworking.models.AssociationSubnet; +import com.azure.resourcemanager.servicenetworking.implementation.models.AssociationListResult; import com.azure.resourcemanager.servicenetworking.models.AssociationType; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; import org.junit.jupiter.api.Assertions; public final class AssociationListResultTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { AssociationListResult model = BinaryData.fromString( - "{\"value\":[{\"properties\":{\"associationType\":\"subnets\",\"subnet\":{\"id\":\"fgibmadgakeq\"},\"provisioningState\":\"Provisioning\"},\"location\":\"bzqqedqytbciq\",\"tags\":{\"smodmgloug\":\"flmmnk\",\"wtmutduq\":\"b\"},\"id\":\"ta\",\"name\":\"spwgcuertumkdosv\",\"type\":\"whbmd\"},{\"properties\":{\"associationType\":\"subnets\",\"subnet\":{\"id\":\"f\"},\"provisioningState\":\"Failed\"},\"location\":\"bmbexppbhtqqro\",\"tags\":{\"igjyjg\":\"fpsalgbqu\"},\"id\":\"jaoyfhrtx\",\"name\":\"lnerkujysvleju\",\"type\":\"fqawrlyxw\"}],\"nextLink\":\"cpr\"}") + "{\"value\":[{\"properties\":{\"associationType\":\"subnets\",\"subnet\":{\"id\":\"esaagdfm\"},\"provisioningState\":\"Provisioning\"},\"location\":\"hjxri\",\"tags\":{\"pa\":\"mrvktsizntoc\",\"poyfdkfogkn\":\"uajpsquc\",\"eqsrdeupewnwreit\":\"gjofjd\",\"usarhmofc\":\"zyf\"},\"id\":\"hs\",\"name\":\"yurkdtmlxhekuksj\",\"type\":\"xukcdmpar\"},{\"properties\":{\"associationType\":\"subnets\",\"subnet\":{\"id\":\"anzwuxzdxta\"},\"provisioningState\":\"Accepted\"},\"location\":\"m\",\"tags\":{\"u\":\"pmrqobm\"},\"id\":\"knryrtihfxtij\",\"name\":\"pzvgnwzsymglzufc\",\"type\":\"zk\"},{\"properties\":{\"associationType\":\"subnets\",\"subnet\":{\"id\":\"ihanuf\"},\"provisioningState\":\"Canceled\"},\"location\":\"jysagith\",\"tags\":{\"npqxuh\":\"abifpikxwczbys\"},\"id\":\"vyq\",\"name\":\"iwbybrkxvdumjg\",\"type\":\"tfwvukxgaudc\"},{\"properties\":{\"associationType\":\"subnets\",\"subnet\":{\"id\":\"s\"},\"provisioningState\":\"Updating\"},\"location\":\"ejhkry\",\"tags\":{\"lokjyemkk\":\"apcz\",\"joxzjnchgejspodm\":\"ni\",\"h\":\"ilzyd\"},\"id\":\"jwyahuxinpmqnja\",\"name\":\"wixjsprozvcp\",\"type\":\"tegjvwmf\"}],\"nextLink\":\"t\"}") .toObject(AssociationListResult.class); - Assertions.assertEquals("bzqqedqytbciq", model.value().get(0).location()); - Assertions.assertEquals("flmmnk", model.value().get(0).tags().get("smodmgloug")); + Assertions.assertEquals("hjxri", model.value().get(0).location()); + Assertions.assertEquals("mrvktsizntoc", model.value().get(0).tags().get("pa")); Assertions.assertEquals(AssociationType.SUBNETS, model.value().get(0).properties().associationType()); - Assertions.assertEquals("fgibmadgakeq", model.value().get(0).properties().subnet().id()); - Assertions.assertEquals("cpr", model.nextLink()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - AssociationListResult model = new AssociationListResult().withValue(Arrays.asList( - new AssociationInner().withLocation("bzqqedqytbciq") - .withTags(mapOf("smodmgloug", "flmmnk", "wtmutduq", "b")) - .withProperties(new AssociationProperties().withAssociationType(AssociationType.SUBNETS) - .withSubnet(new AssociationSubnet().withId("fgibmadgakeq"))), - new AssociationInner().withLocation("bmbexppbhtqqro") - .withTags(mapOf("igjyjg", "fpsalgbqu")) - .withProperties(new AssociationProperties().withAssociationType(AssociationType.SUBNETS) - .withSubnet(new AssociationSubnet().withId("f"))))) - .withNextLink("cpr"); - model = BinaryData.fromObject(model).toObject(AssociationListResult.class); - Assertions.assertEquals("bzqqedqytbciq", model.value().get(0).location()); - Assertions.assertEquals("flmmnk", model.value().get(0).tags().get("smodmgloug")); - Assertions.assertEquals(AssociationType.SUBNETS, model.value().get(0).properties().associationType()); - Assertions.assertEquals("fgibmadgakeq", model.value().get(0).properties().subnet().id()); - Assertions.assertEquals("cpr", model.nextLink()); - } - - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; + Assertions.assertEquals("esaagdfm", model.value().get(0).properties().subnet().id()); + Assertions.assertEquals("t", model.nextLink()); } } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationPropertiesTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationPropertiesTests.java index caa2dc9d5a47..33f18f2a859c 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationPropertiesTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationPropertiesTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -15,18 +15,18 @@ public final class AssociationPropertiesTests { public void testDeserialize() throws Exception { AssociationProperties model = BinaryData .fromString( - "{\"associationType\":\"subnets\",\"subnet\":{\"id\":\"zuckyfi\"},\"provisioningState\":\"Succeeded\"}") + "{\"associationType\":\"subnets\",\"subnet\":{\"id\":\"izhwlrxy\"},\"provisioningState\":\"Accepted\"}") .toObject(AssociationProperties.class); Assertions.assertEquals(AssociationType.SUBNETS, model.associationType()); - Assertions.assertEquals("zuckyfi", model.subnet().id()); + Assertions.assertEquals("izhwlrxy", model.subnet().id()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { AssociationProperties model = new AssociationProperties().withAssociationType(AssociationType.SUBNETS) - .withSubnet(new AssociationSubnet().withId("zuckyfi")); + .withSubnet(new AssociationSubnet().withId("izhwlrxy")); model = BinaryData.fromObject(model).toObject(AssociationProperties.class); Assertions.assertEquals(AssociationType.SUBNETS, model.associationType()); - Assertions.assertEquals("zuckyfi", model.subnet().id()); + Assertions.assertEquals("izhwlrxy", model.subnet().id()); } } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationSubnetTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationSubnetTests.java index cd2ad825148e..e7c249d12378 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationSubnetTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationSubnetTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -11,14 +11,14 @@ public final class AssociationSubnetTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - AssociationSubnet model = BinaryData.fromString("{\"id\":\"idf\"}").toObject(AssociationSubnet.class); - Assertions.assertEquals("idf", model.id()); + AssociationSubnet model = BinaryData.fromString("{\"id\":\"oqijgkdmbpaz\"}").toObject(AssociationSubnet.class); + Assertions.assertEquals("oqijgkdmbpaz", model.id()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - AssociationSubnet model = new AssociationSubnet().withId("idf"); + AssociationSubnet model = new AssociationSubnet().withId("oqijgkdmbpaz"); model = BinaryData.fromObject(model).toObject(AssociationSubnet.class); - Assertions.assertEquals("idf", model.id()); + Assertions.assertEquals("oqijgkdmbpaz", model.id()); } } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationSubnetUpdateTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationSubnetUpdateTests.java index 4164b85b9d81..ace6cb2fe0c5 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationSubnetUpdateTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationSubnetUpdateTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -12,14 +12,14 @@ public final class AssociationSubnetUpdateTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { AssociationSubnetUpdate model - = BinaryData.fromString("{\"id\":\"newmdwzjeiachbo\"}").toObject(AssociationSubnetUpdate.class); - Assertions.assertEquals("newmdwzjeiachbo", model.id()); + = BinaryData.fromString("{\"id\":\"lhqgnufooojy\"}").toObject(AssociationSubnetUpdate.class); + Assertions.assertEquals("lhqgnufooojy", model.id()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - AssociationSubnetUpdate model = new AssociationSubnetUpdate().withId("newmdwzjeiachbo"); + AssociationSubnetUpdate model = new AssociationSubnetUpdate().withId("lhqgnufooojy"); model = BinaryData.fromObject(model).toObject(AssociationSubnetUpdate.class); - Assertions.assertEquals("newmdwzjeiachbo", model.id()); + Assertions.assertEquals("lhqgnufooojy", model.id()); } } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationUpdatePropertiesTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationUpdatePropertiesTests.java index 4be1c92d2b02..800cda8e6b30 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationUpdatePropertiesTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationUpdatePropertiesTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -14,19 +14,19 @@ public final class AssociationUpdatePropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { AssociationUpdateProperties model - = BinaryData.fromString("{\"associationType\":\"subnets\",\"subnet\":{\"id\":\"c\"}}") + = BinaryData.fromString("{\"associationType\":\"subnets\",\"subnet\":{\"id\":\"nq\"}}") .toObject(AssociationUpdateProperties.class); Assertions.assertEquals(AssociationType.SUBNETS, model.associationType()); - Assertions.assertEquals("c", model.subnet().id()); + Assertions.assertEquals("nq", model.subnet().id()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { AssociationUpdateProperties model = new AssociationUpdateProperties().withAssociationType(AssociationType.SUBNETS) - .withSubnet(new AssociationSubnetUpdate().withId("c")); + .withSubnet(new AssociationSubnetUpdate().withId("nq")); model = BinaryData.fromObject(model).toObject(AssociationUpdateProperties.class); Assertions.assertEquals(AssociationType.SUBNETS, model.associationType()); - Assertions.assertEquals("c", model.subnet().id()); + Assertions.assertEquals("nq", model.subnet().id()); } } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationUpdateTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationUpdateTests.java index 1d11d5da9fdc..c86fe9e2353e 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationUpdateTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationUpdateTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -16,24 +16,24 @@ public final class AssociationUpdateTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - AssociationUpdate model = BinaryData.fromString( - "{\"tags\":{\"dkfthwxmnt\":\"dzuhtymwi\",\"aop\":\"i\",\"jcmmxdcufufsrp\":\"km\"},\"properties\":{\"associationType\":\"subnets\",\"subnet\":{\"id\":\"sezcxtb\"}}}") + AssociationUpdate model = BinaryData + .fromString( + "{\"tags\":{\"fp\":\"c\"},\"properties\":{\"associationType\":\"subnets\",\"subnet\":{\"id\":\"t\"}}}") .toObject(AssociationUpdate.class); - Assertions.assertEquals("dzuhtymwi", model.tags().get("dkfthwxmnt")); + Assertions.assertEquals("c", model.tags().get("fp")); Assertions.assertEquals(AssociationType.SUBNETS, model.properties().associationType()); - Assertions.assertEquals("sezcxtb", model.properties().subnet().id()); + Assertions.assertEquals("t", model.properties().subnet().id()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - AssociationUpdate model - = new AssociationUpdate().withTags(mapOf("dkfthwxmnt", "dzuhtymwi", "aop", "i", "jcmmxdcufufsrp", "km")) - .withProperties(new AssociationUpdateProperties().withAssociationType(AssociationType.SUBNETS) - .withSubnet(new AssociationSubnetUpdate().withId("sezcxtb"))); + AssociationUpdate model = new AssociationUpdate().withTags(mapOf("fp", "c")) + .withProperties(new AssociationUpdateProperties().withAssociationType(AssociationType.SUBNETS) + .withSubnet(new AssociationSubnetUpdate().withId("t"))); model = BinaryData.fromObject(model).toObject(AssociationUpdate.class); - Assertions.assertEquals("dzuhtymwi", model.tags().get("dkfthwxmnt")); + Assertions.assertEquals("c", model.tags().get("fp")); Assertions.assertEquals(AssociationType.SUBNETS, model.properties().associationType()); - Assertions.assertEquals("sezcxtb", model.properties().subnet().id()); + Assertions.assertEquals("t", model.properties().subnet().id()); } // Use "Map.of" if available diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfacesCreateOrUpdateMockTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfacesCreateOrUpdateMockTests.java index 98d64705d151..d0b29e7d9e7f 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfacesCreateOrUpdateMockTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfacesCreateOrUpdateMockTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -26,7 +26,7 @@ public final class AssociationsInterfacesCreateOrUpdateMockTests { @Test public void testCreateOrUpdate() throws Exception { String responseStr - = "{\"properties\":{\"associationType\":\"subnets\",\"subnet\":{\"id\":\"dxyt\"},\"provisioningState\":\"Succeeded\"},\"location\":\"rxv\",\"tags\":{\"zntxhdz\":\"dw\"},\"id\":\"lrqjbhckfr\",\"name\":\"hrxsbk\",\"type\":\"vpycanuzbp\"}"; + = "{\"properties\":{\"associationType\":\"subnets\",\"subnet\":{\"id\":\"kt\"},\"provisioningState\":\"Succeeded\"},\"location\":\"nhwlrsffrzpwvl\",\"tags\":{\"kt\":\"gbiqylihkaet\"},\"id\":\"fcivfsnkym\",\"name\":\"ctq\",\"type\":\"jf\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -36,18 +36,19 @@ public void testCreateOrUpdate() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); Association response = manager.associationsInterfaces() - .define("nmic") - .withRegion("jbkcnxdhbttkph") - .withExistingTrafficController("svlxotogtwrup", "sx") - .withTags(mapOf("t", "nv", "crpab", "qnermclfplphoxu", "sbj", "ye", "wfqkquj", "azqugxywpmueefj")) + .define("jdeyeamdpha") + .withRegion("ow") + .withExistingTrafficController("sjttgzfbish", "bkh") + .withTags(mapOf("tmryw", "hwankixzbinjepu", "yqzrnkcqvyxlw", "uzoqft", "oqqnwvlryav", "zlsico", "konocu", + "hheunmmqhgyx")) .withProperties(new AssociationProperties().withAssociationType(AssociationType.SUBNETS) - .withSubnet(new AssociationSubnet().withId("eoveilovnotyf"))) + .withSubnet(new AssociationSubnet().withId("buxwgip"))) .create(); - Assertions.assertEquals("rxv", response.location()); - Assertions.assertEquals("dw", response.tags().get("zntxhdz")); + Assertions.assertEquals("nhwlrsffrzpwvl", response.location()); + Assertions.assertEquals("gbiqylihkaet", response.tags().get("kt")); Assertions.assertEquals(AssociationType.SUBNETS, response.properties().associationType()); - Assertions.assertEquals("dxyt", response.properties().subnet().id()); + Assertions.assertEquals("kt", response.properties().subnet().id()); } // Use "Map.of" if available diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfacesGetWithResponseMockTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfacesGetWithResponseMockTests.java index 7e9deccdfd80..fd38c926fd88 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfacesGetWithResponseMockTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfacesGetWithResponseMockTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -22,7 +22,7 @@ public final class AssociationsInterfacesGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"associationType\":\"subnets\",\"subnet\":{\"id\":\"xnkjzkdesl\"},\"provisioningState\":\"Failed\"},\"location\":\"pwiyig\",\"tags\":{\"upedeojnabckhs\":\"kdwzbaiuebbaumny\",\"ie\":\"txp\"},\"id\":\"tfhvpesapskrdqmh\",\"name\":\"jdhtldwkyzxu\",\"type\":\"tkncwsc\"}"; + = "{\"properties\":{\"associationType\":\"subnets\",\"subnet\":{\"id\":\"ruwiqzbqjvsov\"},\"provisioningState\":\"Provisioning\"},\"location\":\"acspkwl\",\"tags\":{\"hrk\":\"obpxjmflbvvn\",\"ajiwkuo\":\"ciwwzjuqkhr\",\"sauuimj\":\"oskg\",\"rfbyaosvexcso\":\"vxieduugidyj\"},\"id\":\"pclhocohslk\",\"name\":\"vleggzfbuhfmvfax\",\"type\":\"ffeii\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -32,12 +32,12 @@ public void testGetWithResponse() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); Association response = manager.associationsInterfaces() - .getWithResponse("gu", "svmkfssxquk", "fpl", com.azure.core.util.Context.NONE) + .getWithResponse("oczvy", "fqrvkdvjsllrmvvd", "watkpnpulexxb", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("pwiyig", response.location()); - Assertions.assertEquals("kdwzbaiuebbaumny", response.tags().get("upedeojnabckhs")); + Assertions.assertEquals("acspkwl", response.location()); + Assertions.assertEquals("obpxjmflbvvn", response.tags().get("hrk")); Assertions.assertEquals(AssociationType.SUBNETS, response.properties().associationType()); - Assertions.assertEquals("xnkjzkdesl", response.properties().subnet().id()); + Assertions.assertEquals("ruwiqzbqjvsov", response.properties().subnet().id()); } } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfacesListByTrafficControllerMockTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfacesListByTrafficControllerMockTests.java index 800d02edf4ac..5af9ec400cc5 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfacesListByTrafficControllerMockTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/AssociationsInterfacesListByTrafficControllerMockTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -23,7 +23,7 @@ public final class AssociationsInterfacesListByTrafficControllerMockTests { @Test public void testListByTrafficController() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"associationType\":\"subnets\",\"subnet\":{\"id\":\"babphlwrqlfk\"},\"provisioningState\":\"Deleting\"},\"location\":\"sucocmnyyazttbtw\",\"tags\":{\"yueaxibxujwb\":\"puedckzywbiexzf\",\"zjancuxr\":\"qwalmuzyoxaepd\",\"bavxbniwdjswzt\":\"d\",\"xbzpfzab\":\"dbpgnxytxhp\"},\"id\":\"lcuhxwtctyqiklb\",\"name\":\"ovplw\",\"type\":\"bhvgy\"}]}"; + = "{\"value\":[{\"properties\":{\"associationType\":\"subnets\",\"subnet\":{\"id\":\"shxmzsbbzoggigrx\"},\"provisioningState\":\"Updating\"},\"location\":\"vjxxjnsp\",\"tags\":{\"nkoukn\":\"tko\",\"ngkpocipazy\":\"udwtiukbl\",\"gukgjnpiucgygevq\":\"o\"},\"id\":\"ntypmrbpizcdrqj\",\"name\":\"dpydn\",\"type\":\"yhxdeoejzicwi\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -32,12 +32,12 @@ public void testListByTrafficController() throws Exception { .authenticate(tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), new AzureProfile("", "", AzureEnvironment.AZURE)); - PagedIterable response = manager.associationsInterfaces() - .listByTrafficController("xywnytnrsynlqidy", "yxczfclh", com.azure.core.util.Context.NONE); + PagedIterable response + = manager.associationsInterfaces().listByTrafficController("hl", "m", com.azure.core.util.Context.NONE); - Assertions.assertEquals("sucocmnyyazttbtw", response.iterator().next().location()); - Assertions.assertEquals("puedckzywbiexzf", response.iterator().next().tags().get("yueaxibxujwb")); + Assertions.assertEquals("vjxxjnsp", response.iterator().next().location()); + Assertions.assertEquals("tko", response.iterator().next().tags().get("nkoukn")); Assertions.assertEquals(AssociationType.SUBNETS, response.iterator().next().properties().associationType()); - Assertions.assertEquals("babphlwrqlfk", response.iterator().next().properties().subnet().id()); + Assertions.assertEquals("shxmzsbbzoggigrx", response.iterator().next().properties().subnet().id()); } } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/FrontendInnerTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/FrontendInnerTests.java index 97d6915da9ea..db5da72de430 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/FrontendInnerTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/FrontendInnerTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -15,20 +15,20 @@ public final class FrontendInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { FrontendInner model = BinaryData.fromString( - "{\"properties\":{\"fqdn\":\"exhd\",\"provisioningState\":\"Provisioning\"},\"location\":\"qeojnxqbzvddntw\",\"tags\":{\"vuhrhcffcyddgl\":\"icbtwnpzao\"},\"id\":\"jthjqkwpyei\",\"name\":\"xmqci\",\"type\":\"q\"}") + "{\"properties\":{\"fqdn\":\"dvpjhulsuuvmk\",\"provisioningState\":\"Provisioning\"},\"location\":\"rwfndiod\",\"tags\":{\"ryo\":\"lwejdpv\",\"hbcryffdfdosyge\":\"psoacctazakljl\",\"rzevdphlxaol\":\"paojakhmsbzjh\"},\"id\":\"hqtrgqjbpf\",\"name\":\"fsinzgvfcjrwzoxx\",\"type\":\"tfell\"}") .toObject(FrontendInner.class); - Assertions.assertEquals("qeojnxqbzvddntw", model.location()); - Assertions.assertEquals("icbtwnpzao", model.tags().get("vuhrhcffcyddgl")); + Assertions.assertEquals("rwfndiod", model.location()); + Assertions.assertEquals("lwejdpv", model.tags().get("ryo")); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - FrontendInner model = new FrontendInner().withLocation("qeojnxqbzvddntw") - .withTags(mapOf("vuhrhcffcyddgl", "icbtwnpzao")) + FrontendInner model = new FrontendInner().withLocation("rwfndiod") + .withTags(mapOf("ryo", "lwejdpv", "hbcryffdfdosyge", "psoacctazakljl", "rzevdphlxaol", "paojakhmsbzjh")) .withProperties(new FrontendProperties()); model = BinaryData.fromObject(model).toObject(FrontendInner.class); - Assertions.assertEquals("qeojnxqbzvddntw", model.location()); - Assertions.assertEquals("icbtwnpzao", model.tags().get("vuhrhcffcyddgl")); + Assertions.assertEquals("rwfndiod", model.location()); + Assertions.assertEquals("lwejdpv", model.tags().get("ryo")); } // Use "Map.of" if available diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/FrontendListResultTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/FrontendListResultTests.java index 6924b1112fab..bd572a83e736 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/FrontendListResultTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/FrontendListResultTests.java @@ -1,62 +1,21 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.servicenetworking.fluent.models.FrontendInner; -import com.azure.resourcemanager.servicenetworking.models.FrontendListResult; -import com.azure.resourcemanager.servicenetworking.models.FrontendProperties; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; +import com.azure.resourcemanager.servicenetworking.implementation.models.FrontendListResult; import org.junit.jupiter.api.Assertions; public final class FrontendListResultTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { FrontendListResult model = BinaryData.fromString( - "{\"value\":[{\"properties\":{\"fqdn\":\"nrosfqpte\",\"provisioningState\":\"Canceled\"},\"location\":\"vypyqrimzinpv\",\"tags\":{\"nohjt\":\"dkirsoodqxhcr\",\"soifiyipjxsqw\":\"kwh\",\"bznorcjxvsnby\":\"gr\"},\"id\":\"qabnmoc\",\"name\":\"cyshurzafbljjgp\",\"type\":\"toqcjmklja\"},{\"properties\":{\"fqdn\":\"idtqajzyu\",\"provisioningState\":\"Deleting\"},\"location\":\"dj\",\"tags\":{\"e\":\"khbzhfepgzg\",\"scpai\":\"zloc\"},\"id\":\"rhhbcs\",\"name\":\"l\",\"type\":\"mmajtjaodx\"},{\"properties\":{\"fqdn\":\"bdxkqpxokaj\",\"provisioningState\":\"Canceled\"},\"location\":\"imexgstxgcpodgma\",\"tags\":{\"whijcoejctbza\":\"mvdjwzrlovmc\"},\"id\":\"s\",\"name\":\"sycbkbfk\",\"type\":\"ukdkexxppofmxa\"}],\"nextLink\":\"fjpgddtocjjxhvp\"}") + "{\"value\":[{\"properties\":{\"fqdn\":\"v\",\"provisioningState\":\"Deleting\"},\"location\":\"ihnhun\",\"tags\":{\"gxg\":\"jzrnf\",\"fublj\":\"spemvtzfk\",\"aeqjhqjbasvms\":\"fxqeof\",\"gsntnbybkzgcwr\":\"jqul\"},\"id\":\"clxxwrljdo\",\"name\":\"skcqvkocrcjd\",\"type\":\"wtnhxbnjbiksqr\"},{\"properties\":{\"fqdn\":\"sainqpjwnzl\",\"provisioningState\":\"Deleting\"},\"location\":\"ppeebvmgxsab\",\"tags\":{\"c\":\"duuji\",\"dhkrwpdappdsbdk\":\"czdzev\",\"nhutjeltmrldhugj\":\"wrwjfeu\",\"ablgphuticndvk\":\"zdatqxhocdg\"},\"id\":\"ozwyiftyhxhuro\",\"name\":\"ftyxolniw\",\"type\":\"wcukjfkgiawxk\"},{\"properties\":{\"fqdn\":\"plwckbas\",\"provisioningState\":\"Deleting\"},\"location\":\"ddhsgcbacphe\",\"tags\":{\"ndlik\":\"tynqgoul\"},\"id\":\"yqkgfg\",\"name\":\"bmadgak\",\"type\":\"qsrxybzqqed\"}],\"nextLink\":\"tbciqfouflmm\"}") .toObject(FrontendListResult.class); - Assertions.assertEquals("vypyqrimzinpv", model.value().get(0).location()); - Assertions.assertEquals("dkirsoodqxhcr", model.value().get(0).tags().get("nohjt")); - Assertions.assertEquals("fjpgddtocjjxhvp", model.nextLink()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - FrontendListResult model - = new FrontendListResult() - .withValue( - Arrays - .asList( - new FrontendInner().withLocation("vypyqrimzinpv") - .withTags( - mapOf("nohjt", "dkirsoodqxhcr", "soifiyipjxsqw", "kwh", "bznorcjxvsnby", "gr")) - .withProperties(new FrontendProperties()), - new FrontendInner().withLocation("dj") - .withTags(mapOf("e", "khbzhfepgzg", "scpai", "zloc")) - .withProperties(new FrontendProperties()), - new FrontendInner().withLocation("imexgstxgcpodgma") - .withTags(mapOf("whijcoejctbza", "mvdjwzrlovmc")) - .withProperties(new FrontendProperties()))) - .withNextLink("fjpgddtocjjxhvp"); - model = BinaryData.fromObject(model).toObject(FrontendListResult.class); - Assertions.assertEquals("vypyqrimzinpv", model.value().get(0).location()); - Assertions.assertEquals("dkirsoodqxhcr", model.value().get(0).tags().get("nohjt")); - Assertions.assertEquals("fjpgddtocjjxhvp", model.nextLink()); - } - - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; + Assertions.assertEquals("ihnhun", model.value().get(0).location()); + Assertions.assertEquals("jzrnf", model.value().get(0).tags().get("gxg")); + Assertions.assertEquals("tbciqfouflmm", model.nextLink()); } } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/FrontendPropertiesTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/FrontendPropertiesTests.java index 4667bd72bae5..68194b508821 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/FrontendPropertiesTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/FrontendPropertiesTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -10,9 +10,8 @@ public final class FrontendPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - FrontendProperties model - = BinaryData.fromString("{\"fqdn\":\"khixuigdtopbo\",\"provisioningState\":\"Failed\"}") - .toObject(FrontendProperties.class); + FrontendProperties model = BinaryData.fromString("{\"fqdn\":\"fziton\",\"provisioningState\":\"Updating\"}") + .toObject(FrontendProperties.class); } @org.junit.jupiter.api.Test diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/FrontendUpdateTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/FrontendUpdateTests.java index c8b8ef7ed239..42e38eeff20a 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/FrontendUpdateTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/FrontendUpdateTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -13,15 +13,19 @@ public final class FrontendUpdateTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - FrontendUpdate model = BinaryData.fromString("{\"tags\":{\"w\":\"m\"}}").toObject(FrontendUpdate.class); - Assertions.assertEquals("m", model.tags().get("w")); + FrontendUpdate model = BinaryData + .fromString( + "{\"tags\":{\"ypininm\":\"jkjlxofpdvhpfx\",\"po\":\"yhuybbkpod\",\"ognarxzxtheotus\":\"ginuvamih\"}}") + .toObject(FrontendUpdate.class); + Assertions.assertEquals("jkjlxofpdvhpfx", model.tags().get("ypininm")); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - FrontendUpdate model = new FrontendUpdate().withTags(mapOf("w", "m")); + FrontendUpdate model = new FrontendUpdate() + .withTags(mapOf("ypininm", "jkjlxofpdvhpfx", "po", "yhuybbkpod", "ognarxzxtheotus", "ginuvamih")); model = BinaryData.fromObject(model).toObject(FrontendUpdate.class); - Assertions.assertEquals("m", model.tags().get("w")); + Assertions.assertEquals("jkjlxofpdvhpfx", model.tags().get("ypininm")); } // Use "Map.of" if available diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfacesCreateOrUpdateMockTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfacesCreateOrUpdateMockTests.java index 5a6b182c3850..d0417343ed76 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfacesCreateOrUpdateMockTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfacesCreateOrUpdateMockTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -24,7 +24,7 @@ public final class FrontendsInterfacesCreateOrUpdateMockTests { @Test public void testCreateOrUpdate() throws Exception { String responseStr - = "{\"properties\":{\"fqdn\":\"cnojvknmefqsg\",\"provisioningState\":\"Succeeded\"},\"location\":\"apj\",\"tags\":{\"lxkvu\":\"pvgqzcjrvxdjzlm\",\"n\":\"fhzovawjvzunluth\"},\"id\":\"rnxipei\",\"name\":\"pjzu\",\"type\":\"e\"}"; + = "{\"properties\":{\"fqdn\":\"iwdjswztsdbpgn\",\"provisioningState\":\"Succeeded\"},\"location\":\"hpzxbzpfzab\",\"tags\":{\"lwzbhvgyugu\":\"uhxwtctyqiklbbov\"},\"id\":\"svmkfssxquk\",\"name\":\"fpl\",\"type\":\"mg\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -34,16 +34,15 @@ public void testCreateOrUpdate() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); Frontend response = manager.frontendsInterfaces() - .define("veual") - .withRegion("bcswsrt") - .withExistingTrafficController("vylwzbtdhxuj", "nbmpowuwprzq") - .withTags(mapOf("blcg", "plrbpbewtghf", "nmxiebwwaloayqc", "xzvlvqhjkbegib", "uzgwyzmhtx", "wrtz", - "wxqpsrknftguvri", "ngmtsavjcb")) + .define("axdbabph") + .withRegion("mnyyazt") + .withExistingTrafficController("xywnytnrsynlqidy", "yxczfclh") + .withTags(mapOf("uedck", "wwrq", "bxu", "ywbiexzfeyueax")) .withProperties(new FrontendProperties()) .create(); - Assertions.assertEquals("apj", response.location()); - Assertions.assertEquals("pvgqzcjrvxdjzlm", response.tags().get("lxkvu")); + Assertions.assertEquals("hpzxbzpfzab", response.location()); + Assertions.assertEquals("uhxwtctyqiklbbov", response.tags().get("lwzbhvgyugu")); } // Use "Map.of" if available diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfacesGetWithResponseMockTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfacesGetWithResponseMockTests.java index 869424028f6d..d7ee7f472e60 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfacesGetWithResponseMockTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfacesGetWithResponseMockTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -21,7 +21,7 @@ public final class FrontendsInterfacesGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"fqdn\":\"wmcdytdxwi\",\"provisioningState\":\"Canceled\"},\"location\":\"jawgqwg\",\"tags\":{\"fbkp\":\"isk\"},\"id\":\"cg\",\"name\":\"lwn\",\"type\":\"nhjdauw\"}"; + = "{\"properties\":{\"fqdn\":\"nljky\",\"provisioningState\":\"Failed\"},\"location\":\"uujqgidokgjljyo\",\"tags\":{\"hbijhtxfvgxb\":\"cltbgsncghkjesz\",\"eh\":\"smx\",\"qkkrb\":\"pvecxgodeb\"},\"id\":\"pukgriwflzlfb\",\"name\":\"zpuzycisp\",\"type\":\"qzahmgkbrp\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -31,10 +31,10 @@ public void testGetWithResponse() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); Frontend response = manager.frontendsInterfaces() - .getWithResponse("cjooxdjebwpucwwf", "ovbvmeueciv", "hzceuojgjrwjue", com.azure.core.util.Context.NONE) + .getWithResponse("ebrjcxe", "fuwutttxf", "jrbirphxepcyv", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("jawgqwg", response.location()); - Assertions.assertEquals("isk", response.tags().get("fbkp")); + Assertions.assertEquals("uujqgidokgjljyo", response.location()); + Assertions.assertEquals("cltbgsncghkjesz", response.tags().get("hbijhtxfvgxb")); } } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfacesListByTrafficControllerMockTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfacesListByTrafficControllerMockTests.java index 15c8b9ded396..01d683f1922e 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfacesListByTrafficControllerMockTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/FrontendsInterfacesListByTrafficControllerMockTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -22,7 +22,7 @@ public final class FrontendsInterfacesListByTrafficControllerMockTests { @Test public void testListByTrafficController() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"fqdn\":\"rts\",\"provisioningState\":\"Updating\"},\"location\":\"kdeemaofmxagkvtm\",\"tags\":{\"aquhcdhm\":\"qkrhahvljua\",\"rcrgvx\":\"ualaexqpvfadmw\",\"fmisg\":\"vgomz\",\"ali\":\"bnbbeldawkz\"},\"id\":\"urqhaka\",\"name\":\"hashsfwxosow\",\"type\":\"xcug\"}]}"; + = "{\"value\":[{\"properties\":{\"fqdn\":\"vtq\",\"provisioningState\":\"Deleting\"},\"location\":\"uynhijg\",\"tags\":{\"arbu\":\"bfs\"},\"id\":\"rcvpnazzmhjrunmp\",\"name\":\"ttdbhrbnl\",\"type\":\"nkxmyskpbhenbtk\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -32,9 +32,9 @@ public void testListByTrafficController() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); PagedIterable response = manager.frontendsInterfaces() - .listByTrafficController("kafkuwbcrnwbm", "hhseyv", com.azure.core.util.Context.NONE); + .listByTrafficController("y", "hibnuqqkpika", com.azure.core.util.Context.NONE); - Assertions.assertEquals("kdeemaofmxagkvtm", response.iterator().next().location()); - Assertions.assertEquals("qkrhahvljua", response.iterator().next().tags().get("aquhcdhm")); + Assertions.assertEquals("uynhijg", response.iterator().next().location()); + Assertions.assertEquals("bfs", response.iterator().next().tags().get("arbu")); } } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/OperationDisplayTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/OperationDisplayTests.java index 1b34f4837fac..64e6e67c1d9e 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/OperationDisplayTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/OperationDisplayTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -11,13 +11,7 @@ public final class OperationDisplayTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { OperationDisplay model = BinaryData.fromString( - "{\"provider\":\"yrtih\",\"resource\":\"tijbpzvgnwzsymgl\",\"operation\":\"fcyzkohdbihanufh\",\"description\":\"bj\"}") + "{\"provider\":\"dxwzywqsmbsurexi\",\"resource\":\"ryocfsfksymdd\",\"operation\":\"tki\",\"description\":\"xhqyudxorrqnb\"}") .toObject(OperationDisplay.class); } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - OperationDisplay model = new OperationDisplay(); - model = BinaryData.fromObject(model).toObject(OperationDisplay.class); - } } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/OperationInnerTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/OperationInnerTests.java index b6ba21eb1f7d..3344658f554d 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/OperationInnerTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/OperationInnerTests.java @@ -1,24 +1,17 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; import com.azure.core.util.BinaryData; import com.azure.resourcemanager.servicenetworking.fluent.models.OperationInner; -import com.azure.resourcemanager.servicenetworking.models.OperationDisplay; public final class OperationInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { OperationInner model = BinaryData.fromString( - "{\"name\":\"usarhmofc\",\"isDataAction\":false,\"display\":{\"provider\":\"urkdtmlx\",\"resource\":\"kuksjtxukcdm\",\"operation\":\"rcryuanzwuxzdxta\",\"description\":\"lhmwhfpmrqobm\"},\"origin\":\"user,system\",\"actionType\":\"Internal\"}") + "{\"name\":\"ltrpmopj\",\"isDataAction\":false,\"display\":{\"provider\":\"u\",\"resource\":\"thfuiuaodsfcpkvx\",\"operation\":\"puozmyzydag\",\"description\":\"axbezyiuo\"},\"origin\":\"user,system\",\"actionType\":\"Internal\"}") .toObject(OperationInner.class); } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - OperationInner model = new OperationInner().withDisplay(new OperationDisplay()); - model = BinaryData.fromObject(model).toObject(OperationInner.class); - } } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/OperationListResultTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/OperationListResultTests.java index 790882e7d182..3f299064b461 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/OperationListResultTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/OperationListResultTests.java @@ -1,23 +1,19 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.servicenetworking.models.OperationListResult; +import com.azure.resourcemanager.servicenetworking.implementation.models.OperationListResult; +import org.junit.jupiter.api.Assertions; public final class OperationListResultTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { OperationListResult model = BinaryData.fromString( - "{\"value\":[{\"name\":\"quvgjxpybczme\",\"isDataAction\":true,\"display\":{\"provider\":\"pbsphrupidgs\",\"resource\":\"bejhphoycmsxa\",\"operation\":\"hdxbmtqio\",\"description\":\"zehtbmu\"},\"origin\":\"user,system\",\"actionType\":\"Internal\"},{\"name\":\"izhwlrxy\",\"isDataAction\":false,\"display\":{\"provider\":\"ijgkdm\",\"resource\":\"azlobcufpdznrbt\",\"operation\":\"qjnqglhqgnufoooj\",\"description\":\"ifsqesaagdfmg\"},\"origin\":\"user,system\",\"actionType\":\"Internal\"},{\"name\":\"rifkwm\",\"isDataAction\":true,\"display\":{\"provider\":\"izntocipao\",\"resource\":\"jpsq\",\"operation\":\"mpoyfd\",\"description\":\"ogknygjofjdd\"},\"origin\":\"user,system\",\"actionType\":\"Internal\"}],\"nextLink\":\"upewnwreitjzy\"}") + "{\"value\":[{\"name\":\"xhbkuofq\",\"isDataAction\":false,\"display\":{\"provider\":\"menevfyexfwh\",\"resource\":\"cibvyvdcsitynn\",\"operation\":\"mdectehfiqscjey\",\"description\":\"hezrkgq\"},\"origin\":\"user\",\"actionType\":\"Internal\"},{\"name\":\"o\",\"isDataAction\":true,\"display\":{\"provider\":\"sle\",\"resource\":\"vxyqjpkcattpngjc\",\"operation\":\"czsqpjhvm\",\"description\":\"jvnysounqe\"},\"origin\":\"user,system\",\"actionType\":\"Internal\"}],\"nextLink\":\"upfh\"}") .toObject(OperationListResult.class); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - OperationListResult model = new OperationListResult(); - model = BinaryData.fromObject(model).toObject(OperationListResult.class); + Assertions.assertEquals("upfh", model.nextLink()); } } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/OperationsListMockTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/OperationsListMockTests.java index 00a4911a0ae6..4d1c0ae9c4a0 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/OperationsListMockTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/OperationsListMockTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -21,7 +21,7 @@ public final class OperationsListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"name\":\"w\",\"isDataAction\":true,\"display\":{\"provider\":\"gwdkcglhsl\",\"resource\":\"jdyggdtji\",\"operation\":\"b\",\"description\":\"ofqweykhmenevfye\"},\"origin\":\"user,system\",\"actionType\":\"Internal\"}]}"; + = "{\"value\":[{\"name\":\"mwabnetshhszhedp\",\"isDataAction\":false,\"display\":{\"provider\":\"ubmwmbesld\",\"resource\":\"wwtppj\",\"operation\":\"cxogaokonzm\",\"description\":\"ikvmkqzeqqk\"},\"origin\":\"system\",\"actionType\":\"Internal\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/ResourceIdTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/ResourceIdTests.java index febc50db2101..524dbb6f65e5 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/ResourceIdTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/ResourceIdTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -11,14 +11,7 @@ public final class ResourceIdTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - ResourceId model = BinaryData.fromString("{\"id\":\"pdappds\"}").toObject(ResourceId.class); - Assertions.assertEquals("pdappds", model.id()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - ResourceId model = new ResourceId().withId("pdappds"); - model = BinaryData.fromObject(model).toObject(ResourceId.class); - Assertions.assertEquals("pdappds", model.id()); + ResourceId model = BinaryData.fromString("{\"id\":\"eojnxqbzvddn\"}").toObject(ResourceId.class); + Assertions.assertEquals("eojnxqbzvddn", model.id()); } } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfacesCreateOrUpdateMockTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfacesCreateOrUpdateMockTests.java index 289ca67aa51e..4c15edcae551 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfacesCreateOrUpdateMockTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfacesCreateOrUpdateMockTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -25,7 +25,7 @@ public final class SecurityPoliciesInterfacesCreateOrUpdateMockTests { @Test public void testCreateOrUpdate() throws Exception { String responseStr - = "{\"properties\":{\"policyType\":\"waf\",\"wafPolicy\":{\"id\":\"aqtdoqmcbx\"},\"provisioningState\":\"Succeeded\"},\"location\":\"yslqbhsfx\",\"tags\":{\"wfbkrvrns\":\"ytkblmpew\"},\"id\":\"shqjohxcrsbf\",\"name\":\"vasrruvwb\",\"type\":\"sqfsubcgjbirxb\"}"; + = "{\"properties\":{\"policyType\":\"waf\",\"wafPolicy\":{\"id\":\"e\"},\"provisioningState\":\"Succeeded\"},\"location\":\"k\",\"tags\":{\"uhashsfwx\":\"liourqhak\"},\"id\":\"sowzxcugi\",\"name\":\"jooxdjebw\",\"type\":\"ucww\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -35,16 +35,17 @@ public void testCreateOrUpdate() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); SecurityPolicy response = manager.securityPoliciesInterfaces() - .define("rhhuaopppcqeqx") - .withRegion("kdmoi") - .withExistingTrafficController("llwptfdy", "pfqbuaceopzf") - .withTags(mapOf("kxbpvj", "stmgrcfbunrmfqjh", "xjyngudivk", "mjh")) - .withProperties(new SecurityPolicyProperties().withWafPolicy(new WafPolicy().withId("hzxct"))) + .define("qj") + .withRegion("pycanuzbpz") + .withExistingTrafficController("udxytlmoyrx", "wfudwpzntxhdzhl") + .withTags(mapOf("ehhseyvjusrts", "kuwbcrnwb", "mx", "hspkdeemao", "ljuahaquhcdh", "gkvtmelmqkrhah", + "xqpvfadmw", "duala")) + .withProperties(new SecurityPolicyProperties().withWafPolicy(new WafPolicy().withId("rlhrxs"))) .create(); - Assertions.assertEquals("yslqbhsfx", response.location()); - Assertions.assertEquals("ytkblmpew", response.tags().get("wfbkrvrns")); - Assertions.assertEquals("aqtdoqmcbx", response.properties().wafPolicy().id()); + Assertions.assertEquals("k", response.location()); + Assertions.assertEquals("liourqhak", response.tags().get("uhashsfwx")); + Assertions.assertEquals("e", response.properties().wafPolicy().id()); } // Use "Map.of" if available diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfacesGetWithResponseMockTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfacesGetWithResponseMockTests.java index fc33dd7104e8..fbeef5ac5528 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfacesGetWithResponseMockTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfacesGetWithResponseMockTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -21,7 +21,7 @@ public final class SecurityPoliciesInterfacesGetWithResponseMockTests { @Test public void testGetWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"policyType\":\"waf\",\"wafPolicy\":{\"id\":\"eli\"},\"provisioningState\":\"Canceled\"},\"location\":\"ztfolhbnxk\",\"tags\":{\"pnapnyiropuh\":\"aulppggd\",\"git\":\"igvpgylg\"},\"id\":\"medjvcslynqwwncw\",\"name\":\"zhxgktrmgucn\",\"type\":\"pkteo\"}"; + = "{\"properties\":{\"policyType\":\"waf\",\"wafPolicy\":{\"id\":\"eojnabc\"},\"provisioningState\":\"Canceled\"},\"location\":\"txp\",\"tags\":{\"rdqmhjjdhtldwkyz\":\"btfhvpesaps\",\"cwsvlxotog\":\"uutkncw\",\"o\":\"wrupqsxvnmicykvc\"},\"id\":\"eil\",\"name\":\"vnotyfjfcnj\",\"type\":\"k\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -31,11 +31,11 @@ public void testGetWithResponse() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); SecurityPolicy response = manager.securityPoliciesInterfaces() - .getWithResponse("aalnjixi", "xyawj", "yaqcslyjpkiidz", com.azure.core.util.Context.NONE) + .getWithResponse("xnkjzkdesl", "vlopwiyighx", "kdwzbaiuebbaumny", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("ztfolhbnxk", response.location()); - Assertions.assertEquals("aulppggd", response.tags().get("pnapnyiropuh")); - Assertions.assertEquals("eli", response.properties().wafPolicy().id()); + Assertions.assertEquals("txp", response.location()); + Assertions.assertEquals("btfhvpesaps", response.tags().get("rdqmhjjdhtldwkyz")); + Assertions.assertEquals("eojnabc", response.properties().wafPolicy().id()); } } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfacesListByTrafficControllerMockTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfacesListByTrafficControllerMockTests.java index 8dae1f02e5ae..02c505ca0200 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfacesListByTrafficControllerMockTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPoliciesInterfacesListByTrafficControllerMockTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -22,7 +22,7 @@ public final class SecurityPoliciesInterfacesListByTrafficControllerMockTests { @Test public void testListByTrafficController() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"policyType\":\"waf\",\"wafPolicy\":{\"id\":\"ekg\"},\"provisioningState\":\"Deleting\"},\"location\":\"uh\",\"tags\":{\"uusdttouwa\":\"bsjyofdx\"},\"id\":\"oekqvk\",\"name\":\"lns\",\"type\":\"vbxwyjsflhh\"}]}"; + = "{\"value\":[{\"properties\":{\"policyType\":\"waf\",\"wafPolicy\":{\"id\":\"clfp\"},\"provisioningState\":\"Deleting\"},\"location\":\"xus\",\"tags\":{\"psbjta\":\"abgy\",\"kqujidsuyono\":\"qugxywpmueefjzwf\"},\"id\":\"glaocq\",\"name\":\"tcc\",\"type\":\"g\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -32,10 +32,10 @@ public void testListByTrafficController() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); PagedIterable response = manager.securityPoliciesInterfaces() - .listByTrafficController("xdult", "kzbbtd", com.azure.core.util.Context.NONE); + .listByTrafficController("nxdhbt", "kphywpnvjto", com.azure.core.util.Context.NONE); - Assertions.assertEquals("uh", response.iterator().next().location()); - Assertions.assertEquals("bsjyofdx", response.iterator().next().tags().get("uusdttouwa")); - Assertions.assertEquals("ekg", response.iterator().next().properties().wafPolicy().id()); + Assertions.assertEquals("xus", response.iterator().next().location()); + Assertions.assertEquals("abgy", response.iterator().next().tags().get("psbjta")); + Assertions.assertEquals("clfp", response.iterator().next().properties().wafPolicy().id()); } } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPolicyConfigurationsTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPolicyConfigurationsTests.java index 07040429f53a..32de163920e4 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPolicyConfigurationsTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPolicyConfigurationsTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -12,16 +12,16 @@ public final class SecurityPolicyConfigurationsTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - SecurityPolicyConfigurations model = BinaryData.fromString("{\"wafSecurityPolicy\":{\"id\":\"kvwrwjfeu\"}}") + SecurityPolicyConfigurations model = BinaryData.fromString("{\"wafSecurityPolicy\":{\"id\":\"ndei\"}}") .toObject(SecurityPolicyConfigurations.class); - Assertions.assertEquals("kvwrwjfeu", model.wafSecurityPolicy().id()); + Assertions.assertEquals("ndei", model.wafSecurityPolicy().id()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { SecurityPolicyConfigurations model - = new SecurityPolicyConfigurations().withWafSecurityPolicy(new WafSecurityPolicy().withId("kvwrwjfeu")); + = new SecurityPolicyConfigurations().withWafSecurityPolicy(new WafSecurityPolicy().withId("ndei")); model = BinaryData.fromObject(model).toObject(SecurityPolicyConfigurations.class); - Assertions.assertEquals("kvwrwjfeu", model.wafSecurityPolicy().id()); + Assertions.assertEquals("ndei", model.wafSecurityPolicy().id()); } } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPolicyConfigurationsUpdateTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPolicyConfigurationsUpdateTests.java deleted file mode 100644 index 1d406476911e..000000000000 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPolicyConfigurationsUpdateTests.java +++ /dev/null @@ -1,27 +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.resourcemanager.servicenetworking.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.servicenetworking.models.SecurityPolicyConfigurationsUpdate; -import com.azure.resourcemanager.servicenetworking.models.WafSecurityPolicyUpdate; -import org.junit.jupiter.api.Assertions; - -public final class SecurityPolicyConfigurationsUpdateTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - SecurityPolicyConfigurationsUpdate model = BinaryData.fromString("{\"wafSecurityPolicy\":{\"id\":\"gou\"}}") - .toObject(SecurityPolicyConfigurationsUpdate.class); - Assertions.assertEquals("gou", model.wafSecurityPolicy().id()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - SecurityPolicyConfigurationsUpdate model = new SecurityPolicyConfigurationsUpdate() - .withWafSecurityPolicy(new WafSecurityPolicyUpdate().withId("gou")); - model = BinaryData.fromObject(model).toObject(SecurityPolicyConfigurationsUpdate.class); - Assertions.assertEquals("gou", model.wafSecurityPolicy().id()); - } -} diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPolicyInnerTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPolicyInnerTests.java index 1ad078808b5b..bae627430252 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPolicyInnerTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPolicyInnerTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -16,23 +16,22 @@ public final class SecurityPolicyInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { SecurityPolicyInner model = BinaryData.fromString( - "{\"properties\":{\"policyType\":\"waf\",\"wafPolicy\":{\"id\":\"nc\"},\"provisioningState\":\"Updating\"},\"location\":\"cfvmmco\",\"tags\":{\"mivkwlzuvcc\":\"xlzevgbmqjqabcy\",\"onlebxetqgtzxdpn\":\"wnfnbacf\",\"eallnwsubisnj\":\"bqqwxrj\"},\"id\":\"mpmngnzscxaqwoo\",\"name\":\"hcbonqvpkvlr\",\"type\":\"njeaseipheofloke\"}") + "{\"properties\":{\"policyType\":\"waf\",\"wafPolicy\":{\"id\":\"odmgl\"},\"provisioningState\":\"Canceled\"},\"location\":\"b\",\"tags\":{\"wgcu\":\"mutduqktaps\"},\"id\":\"rtumkdosvq\",\"name\":\"hbmdgbbjfdd\",\"type\":\"mbmbexppbh\"}") .toObject(SecurityPolicyInner.class); - Assertions.assertEquals("cfvmmco", model.location()); - Assertions.assertEquals("xlzevgbmqjqabcy", model.tags().get("mivkwlzuvcc")); - Assertions.assertEquals("nc", model.properties().wafPolicy().id()); + Assertions.assertEquals("b", model.location()); + Assertions.assertEquals("mutduqktaps", model.tags().get("wgcu")); + Assertions.assertEquals("odmgl", model.properties().wafPolicy().id()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - SecurityPolicyInner model = new SecurityPolicyInner().withLocation("cfvmmco") - .withTags( - mapOf("mivkwlzuvcc", "xlzevgbmqjqabcy", "onlebxetqgtzxdpn", "wnfnbacf", "eallnwsubisnj", "bqqwxrj")) - .withProperties(new SecurityPolicyProperties().withWafPolicy(new WafPolicy().withId("nc"))); + SecurityPolicyInner model = new SecurityPolicyInner().withLocation("b") + .withTags(mapOf("wgcu", "mutduqktaps")) + .withProperties(new SecurityPolicyProperties().withWafPolicy(new WafPolicy().withId("odmgl"))); model = BinaryData.fromObject(model).toObject(SecurityPolicyInner.class); - Assertions.assertEquals("cfvmmco", model.location()); - Assertions.assertEquals("xlzevgbmqjqabcy", model.tags().get("mivkwlzuvcc")); - Assertions.assertEquals("nc", model.properties().wafPolicy().id()); + Assertions.assertEquals("b", model.location()); + Assertions.assertEquals("mutduqktaps", model.tags().get("wgcu")); + Assertions.assertEquals("odmgl", model.properties().wafPolicy().id()); } // Use "Map.of" if available diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPolicyListResultTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPolicyListResultTests.java index dbd2a938f918..d84727976a27 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPolicyListResultTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPolicyListResultTests.java @@ -1,54 +1,22 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.servicenetworking.fluent.models.SecurityPolicyInner; -import com.azure.resourcemanager.servicenetworking.models.SecurityPolicyListResult; -import com.azure.resourcemanager.servicenetworking.models.SecurityPolicyProperties; -import com.azure.resourcemanager.servicenetworking.models.WafPolicy; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; +import com.azure.resourcemanager.servicenetworking.implementation.models.SecurityPolicyListResult; import org.junit.jupiter.api.Assertions; public final class SecurityPolicyListResultTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { SecurityPolicyListResult model = BinaryData.fromString( - "{\"value\":[{\"properties\":{\"policyType\":\"waf\",\"wafPolicy\":{\"id\":\"rzayv\"},\"provisioningState\":\"Succeeded\"},\"location\":\"vdfgiotk\",\"tags\":{\"xlefgugnxkrx\":\"tqxln\",\"tthzrvqd\":\"qmi\"},\"id\":\"abhjybi\",\"name\":\"ehoqfbowskan\",\"type\":\"ktzlcuiywg\"}],\"nextLink\":\"wgndrvynhzgpp\"}") + "{\"value\":[{\"properties\":{\"policyType\":\"waf\",\"wafPolicy\":{\"id\":\"wbxgjvt\"},\"provisioningState\":\"Provisioning\"},\"location\":\"sszdnru\",\"tags\":{\"uitnwuiz\":\"uhmuouqfprwzwbn\",\"x\":\"a\",\"hr\":\"fizuckyf\"},\"id\":\"idf\",\"name\":\"zwdzuh\",\"type\":\"ymwisdkft\"}],\"nextLink\":\"xmnteiwaop\"}") .toObject(SecurityPolicyListResult.class); - Assertions.assertEquals("vdfgiotk", model.value().get(0).location()); - Assertions.assertEquals("tqxln", model.value().get(0).tags().get("xlefgugnxkrx")); - Assertions.assertEquals("rzayv", model.value().get(0).properties().wafPolicy().id()); - Assertions.assertEquals("wgndrvynhzgpp", model.nextLink()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - SecurityPolicyListResult model = new SecurityPolicyListResult() - .withValue(Arrays.asList(new SecurityPolicyInner().withLocation("vdfgiotk") - .withTags(mapOf("xlefgugnxkrx", "tqxln", "tthzrvqd", "qmi")) - .withProperties(new SecurityPolicyProperties().withWafPolicy(new WafPolicy().withId("rzayv"))))) - .withNextLink("wgndrvynhzgpp"); - model = BinaryData.fromObject(model).toObject(SecurityPolicyListResult.class); - Assertions.assertEquals("vdfgiotk", model.value().get(0).location()); - Assertions.assertEquals("tqxln", model.value().get(0).tags().get("xlefgugnxkrx")); - Assertions.assertEquals("rzayv", model.value().get(0).properties().wafPolicy().id()); - Assertions.assertEquals("wgndrvynhzgpp", model.nextLink()); - } - - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; + Assertions.assertEquals("sszdnru", model.value().get(0).location()); + Assertions.assertEquals("uhmuouqfprwzwbn", model.value().get(0).tags().get("uitnwuiz")); + Assertions.assertEquals("wbxgjvt", model.value().get(0).properties().wafPolicy().id()); + Assertions.assertEquals("xmnteiwaop", model.nextLink()); } } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPolicyPropertiesTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPolicyPropertiesTests.java index 643ac0f540a6..2f730c8f050e 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPolicyPropertiesTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPolicyPropertiesTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -13,15 +13,15 @@ public final class SecurityPolicyPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { SecurityPolicyProperties model = BinaryData - .fromString("{\"policyType\":\"waf\",\"wafPolicy\":{\"id\":\"nj\"},\"provisioningState\":\"Canceled\"}") + .fromString("{\"policyType\":\"waf\",\"wafPolicy\":{\"id\":\"ol\"},\"provisioningState\":\"Failed\"}") .toObject(SecurityPolicyProperties.class); - Assertions.assertEquals("nj", model.wafPolicy().id()); + Assertions.assertEquals("ol", model.wafPolicy().id()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - SecurityPolicyProperties model = new SecurityPolicyProperties().withWafPolicy(new WafPolicy().withId("nj")); + SecurityPolicyProperties model = new SecurityPolicyProperties().withWafPolicy(new WafPolicy().withId("ol")); model = BinaryData.fromObject(model).toObject(SecurityPolicyProperties.class); - Assertions.assertEquals("nj", model.wafPolicy().id()); + Assertions.assertEquals("ol", model.wafPolicy().id()); } } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPolicyUpdatePropertiesTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPolicyUpdatePropertiesTests.java index e15be67f410b..5065edee186c 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPolicyUpdatePropertiesTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPolicyUpdatePropertiesTests.java @@ -1,27 +1,27 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; import com.azure.core.util.BinaryData; import com.azure.resourcemanager.servicenetworking.models.SecurityPolicyUpdateProperties; -import com.azure.resourcemanager.servicenetworking.models.WafPolicyUpdate; +import com.azure.resourcemanager.servicenetworking.models.WafPolicy; import org.junit.jupiter.api.Assertions; public final class SecurityPolicyUpdatePropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - SecurityPolicyUpdateProperties model - = BinaryData.fromString("{\"wafPolicy\":{\"id\":\"dmoh\"}}").toObject(SecurityPolicyUpdateProperties.class); - Assertions.assertEquals("dmoh", model.wafPolicy().id()); + SecurityPolicyUpdateProperties model = BinaryData.fromString("{\"wafPolicy\":{\"id\":\"qawrlyxwj\"}}") + .toObject(SecurityPolicyUpdateProperties.class); + Assertions.assertEquals("qawrlyxwj", model.wafPolicy().id()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { SecurityPolicyUpdateProperties model - = new SecurityPolicyUpdateProperties().withWafPolicy(new WafPolicyUpdate().withId("dmoh")); + = new SecurityPolicyUpdateProperties().withWafPolicy(new WafPolicy().withId("qawrlyxwj")); model = BinaryData.fromObject(model).toObject(SecurityPolicyUpdateProperties.class); - Assertions.assertEquals("dmoh", model.wafPolicy().id()); + Assertions.assertEquals("qawrlyxwj", model.wafPolicy().id()); } } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPolicyUpdateTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPolicyUpdateTests.java index aadeead01abf..456762aa7b16 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPolicyUpdateTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/SecurityPolicyUpdateTests.java @@ -1,13 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; import com.azure.core.util.BinaryData; import com.azure.resourcemanager.servicenetworking.models.SecurityPolicyUpdate; import com.azure.resourcemanager.servicenetworking.models.SecurityPolicyUpdateProperties; -import com.azure.resourcemanager.servicenetworking.models.WafPolicyUpdate; +import com.azure.resourcemanager.servicenetworking.models.WafPolicy; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; @@ -15,23 +15,20 @@ public final class SecurityPolicyUpdateTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - SecurityPolicyUpdate model = BinaryData.fromString( - "{\"tags\":{\"e\":\"sxazjpq\",\"zvdudgwdslfhotwm\":\"ualhbxxhejj\",\"pgacftadehxnlty\":\"ynpwlbj\",\"usue\":\"sop\"},\"properties\":{\"wafPolicy\":{\"id\":\"dejbavo\"}}}") + SecurityPolicyUpdate model = BinaryData + .fromString("{\"tags\":{\"rkujy\":\"yjgzjaoyfhrtxiln\"},\"properties\":{\"wafPolicy\":{\"id\":\"eju\"}}}") .toObject(SecurityPolicyUpdate.class); - Assertions.assertEquals("sxazjpq", model.tags().get("e")); - Assertions.assertEquals("dejbavo", model.properties().wafPolicy().id()); + Assertions.assertEquals("yjgzjaoyfhrtxiln", model.tags().get("rkujy")); + Assertions.assertEquals("eju", model.properties().wafPolicy().id()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - SecurityPolicyUpdate model = new SecurityPolicyUpdate() - .withTags( - mapOf("e", "sxazjpq", "zvdudgwdslfhotwm", "ualhbxxhejj", "pgacftadehxnlty", "ynpwlbj", "usue", "sop")) - .withProperties( - new SecurityPolicyUpdateProperties().withWafPolicy(new WafPolicyUpdate().withId("dejbavo"))); + SecurityPolicyUpdate model = new SecurityPolicyUpdate().withTags(mapOf("rkujy", "yjgzjaoyfhrtxiln")) + .withProperties(new SecurityPolicyUpdateProperties().withWafPolicy(new WafPolicy().withId("eju"))); model = BinaryData.fromObject(model).toObject(SecurityPolicyUpdate.class); - Assertions.assertEquals("sxazjpq", model.tags().get("e")); - Assertions.assertEquals("dejbavo", model.properties().wafPolicy().id()); + Assertions.assertEquals("yjgzjaoyfhrtxiln", model.tags().get("rkujy")); + Assertions.assertEquals("eju", model.properties().wafPolicy().id()); } // Use "Map.of" if available diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInnerTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInnerTests.java index 8dcacf7bfd8d..204fc560fa9a 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInnerTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInnerTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -17,27 +17,24 @@ public final class TrafficControllerInnerTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { TrafficControllerInner model = BinaryData.fromString( - "{\"properties\":{\"configurationEndpoints\":[\"hmsbzjhcrzevdp\",\"lxaolthqtrgqjbp\"],\"frontends\":[{\"id\":\"s\"},{\"id\":\"n\"},{\"id\":\"gvfcj\"},{\"id\":\"wzo\"}],\"associations\":[{\"id\":\"tfell\"}],\"securityPolicies\":[{\"id\":\"zitonpeqfpjkjl\"},{\"id\":\"ofpdvh\"}],\"securityPolicyConfigurations\":{\"wafSecurityPolicy\":{\"id\":\"xypininmayhuybbk\"}},\"provisioningState\":\"Canceled\"},\"location\":\"po\",\"tags\":{\"xzxtheo\":\"nuvamiheogna\",\"cciqihnhungbwjz\":\"usivye\",\"kufubljo\":\"nfygxgispemvtz\"},\"id\":\"xqeofjaeqjhqjba\",\"name\":\"v\",\"type\":\"smjqulngsntnbyb\"}") + "{\"properties\":{\"configurationEndpoints\":[\"jcmmxdcufufsrp\",\"mzidnsezcxtb\"],\"frontends\":[{\"id\":\"fycc\"},{\"id\":\"newmdwzjeiachbo\"}],\"associations\":[{\"id\":\"lnrosfqp\"},{\"id\":\"eeh\"},{\"id\":\"zvypyqrimzinp\"},{\"id\":\"swjdkirso\"}],\"securityPolicies\":[{\"id\":\"xhcr\"},{\"id\":\"nohjt\"}],\"securityPolicyConfigurations\":{\"wafSecurityPolicy\":{\"id\":\"h\"}},\"provisioningState\":\"Succeeded\"},\"location\":\"fiyipjxsqwpgrj\",\"tags\":{\"qabnmoc\":\"orcjxvsnby\",\"toqcjmklja\":\"cyshurzafbljjgp\",\"yulpkudjkr\":\"bqidtqaj\",\"e\":\"khbzhfepgzg\"},\"id\":\"zloc\",\"name\":\"scpai\",\"type\":\"rhhbcs\"}") .toObject(TrafficControllerInner.class); - Assertions.assertEquals("po", model.location()); - Assertions.assertEquals("nuvamiheogna", model.tags().get("xzxtheo")); - Assertions.assertEquals("xypininmayhuybbk", - model.properties().securityPolicyConfigurations().wafSecurityPolicy().id()); + Assertions.assertEquals("fiyipjxsqwpgrj", model.location()); + Assertions.assertEquals("orcjxvsnby", model.tags().get("qabnmoc")); + Assertions.assertEquals("h", model.properties().securityPolicyConfigurations().wafSecurityPolicy().id()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - TrafficControllerInner model - = new TrafficControllerInner().withLocation("po") - .withTags(mapOf("xzxtheo", "nuvamiheogna", "cciqihnhungbwjz", "usivye", "kufubljo", "nfygxgispemvtz")) - .withProperties(new TrafficControllerProperties() - .withSecurityPolicyConfigurations(new SecurityPolicyConfigurations() - .withWafSecurityPolicy(new WafSecurityPolicy().withId("xypininmayhuybbk")))); + TrafficControllerInner model = new TrafficControllerInner().withLocation("fiyipjxsqwpgrj") + .withTags(mapOf("qabnmoc", "orcjxvsnby", "toqcjmklja", "cyshurzafbljjgp", "yulpkudjkr", "bqidtqaj", "e", + "khbzhfepgzg")) + .withProperties(new TrafficControllerProperties().withSecurityPolicyConfigurations( + new SecurityPolicyConfigurations().withWafSecurityPolicy(new WafSecurityPolicy().withId("h")))); model = BinaryData.fromObject(model).toObject(TrafficControllerInner.class); - Assertions.assertEquals("po", model.location()); - Assertions.assertEquals("nuvamiheogna", model.tags().get("xzxtheo")); - Assertions.assertEquals("xypininmayhuybbk", - model.properties().securityPolicyConfigurations().wafSecurityPolicy().id()); + Assertions.assertEquals("fiyipjxsqwpgrj", model.location()); + Assertions.assertEquals("orcjxvsnby", model.tags().get("qabnmoc")); + Assertions.assertEquals("h", model.properties().securityPolicyConfigurations().wafSecurityPolicy().id()); } // Use "Map.of" if available diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfacesCreateOrUpdateMockTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfacesCreateOrUpdateMockTests.java index 952856789ba6..7bd3246c45c2 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfacesCreateOrUpdateMockTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfacesCreateOrUpdateMockTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -26,7 +26,7 @@ public final class TrafficControllerInterfacesCreateOrUpdateMockTests { @Test public void testCreateOrUpdate() throws Exception { String responseStr - = "{\"properties\":{\"configurationEndpoints\":[\"vf\",\"nkymuctqhjfbebrj\"],\"frontends\":[{\"id\":\"rfuwutt\"},{\"id\":\"xfvjrbirp\"},{\"id\":\"xepcyvahfn\"}],\"associations\":[{\"id\":\"yq\"},{\"id\":\"j\"},{\"id\":\"uujqgidokgjljyo\"},{\"id\":\"gvcl\"}],\"securityPolicies\":[{\"id\":\"sncghkjeszz\"},{\"id\":\"bijhtxfvgxbf\"},{\"id\":\"mxnehmp\"}],\"securityPolicyConfigurations\":{\"wafSecurityPolicy\":{\"id\":\"xgodebfqkkrbmp\"}},\"provisioningState\":\"Succeeded\"},\"location\":\"iw\",\"tags\":{\"qzahmgkbrp\":\"lfbxzpuzycisp\",\"hibnuqqkpika\":\"y\",\"buynhijggm\":\"rgvtqag\",\"arbu\":\"bfs\"},\"id\":\"rcvpnazzmhjrunmp\",\"name\":\"ttdbhrbnl\",\"type\":\"nkxmyskpbhenbtk\"}"; + = "{\"properties\":{\"configurationEndpoints\":[\"nayqi\",\"ynduha\",\"hqlkthumaqo\"],\"frontends\":[{\"id\":\"ycduier\"},{\"id\":\"gccymvaolpssl\"}],\"associations\":[{\"id\":\"mmdnbbglzps\"},{\"id\":\"iydmcwyhzdxs\"}],\"securityPolicies\":[{\"id\":\"bzmnvdfznud\"}],\"securityPolicyConfigurations\":{\"wafSecurityPolicy\":{\"id\":\"vxzbncb\"}},\"provisioningState\":\"Succeeded\"},\"location\":\"stdbhhxsrzdzu\",\"tags\":{\"wjmy\":\"scdntnevf\"},\"id\":\"tdss\",\"name\":\"s\",\"type\":\"tmweriofzpyq\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -36,17 +36,17 @@ public void testCreateOrUpdate() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); TrafficController response = manager.trafficControllerInterfaces() - .define("wkgshwa") - .withRegion("xuconu") - .withExistingResourceGroup("alpbuxwgipwhon") - .withTags(mapOf("ewrmjmwvvjektc", "fkbey")) + .define("tswb") + .withRegion("ftpvjzbexil") + .withExistingResourceGroup("xjyngudivk") + .withTags(mapOf("jmkcjhwqytj", "fqqnvwpmqtaruo", "jewgdrjerv", "ybn")) .withProperties(new TrafficControllerProperties().withSecurityPolicyConfigurations( - new SecurityPolicyConfigurations().withWafSecurityPolicy(new WafSecurityPolicy().withId("uko")))) + new SecurityPolicyConfigurations().withWafSecurityPolicy(new WafSecurityPolicy().withId("w")))) .create(); - Assertions.assertEquals("iw", response.location()); - Assertions.assertEquals("lfbxzpuzycisp", response.tags().get("qzahmgkbrp")); - Assertions.assertEquals("xgodebfqkkrbmp", + Assertions.assertEquals("stdbhhxsrzdzu", response.location()); + Assertions.assertEquals("scdntnevf", response.tags().get("wjmy")); + Assertions.assertEquals("vxzbncb", response.properties().securityPolicyConfigurations().wafSecurityPolicy().id()); } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfacesGetByResourceGroupWithResponseMockTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfacesGetByResourceGroupWithResponseMockTests.java index 23e2691ac7c7..fd9b365f9018 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfacesGetByResourceGroupWithResponseMockTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfacesGetByResourceGroupWithResponseMockTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -21,7 +21,7 @@ public final class TrafficControllerInterfacesGetByResourceGroupWithResponseMock @Test public void testGetByResourceGroupWithResponse() throws Exception { String responseStr - = "{\"properties\":{\"configurationEndpoints\":[\"onpc\",\"hocohslkev\",\"eggzfb\"],\"frontends\":[{\"id\":\"mvfaxkffeiith\"},{\"id\":\"vmezy\"},{\"id\":\"shxmzsbbzoggigrx\"},{\"id\":\"burvjxxjnspy\"}],\"associations\":[{\"id\":\"koen\"}],\"securityPolicies\":[{\"id\":\"knvudwtiukb\"},{\"id\":\"dng\"},{\"id\":\"pocipazyxoegu\"}],\"securityPolicyConfigurations\":{\"wafSecurityPolicy\":{\"id\":\"npiucgygevqznty\"}},\"provisioningState\":\"Canceled\"},\"location\":\"p\",\"tags\":{\"nfyhx\":\"drqjsdpy\"},\"id\":\"eoejzic\",\"name\":\"ifsjttgzfbishcb\",\"type\":\"hajdeyeamdpha\"}"; + = "{\"properties\":{\"configurationEndpoints\":[\"uojgj\",\"wjue\",\"otwmcdyt\"],\"frontends\":[{\"id\":\"it\"}],\"associations\":[{\"id\":\"jawgqwg\"}],\"securityPolicies\":[{\"id\":\"isk\"}],\"securityPolicyConfigurations\":{\"wafSecurityPolicy\":{\"id\":\"kpycgklwndnhjd\"}},\"provisioningState\":\"Deleting\"},\"location\":\"vylwzbtdhxuj\",\"tags\":{\"qlveualupjmkh\":\"mpowuwpr\"},\"id\":\"xobbcswsrt\",\"name\":\"riplrbpbewtg\",\"type\":\"fgb\"}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -31,12 +31,12 @@ public void testGetByResourceGroupWithResponse() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); TrafficController response = manager.trafficControllerInterfaces() - .getByResourceGroupWithResponse("byao", "v", com.azure.core.util.Context.NONE) + .getByResourceGroupWithResponse("vo", "bvmeuecivy", com.azure.core.util.Context.NONE) .getValue(); - Assertions.assertEquals("p", response.location()); - Assertions.assertEquals("drqjsdpy", response.tags().get("nfyhx")); - Assertions.assertEquals("npiucgygevqznty", + Assertions.assertEquals("vylwzbtdhxuj", response.location()); + Assertions.assertEquals("mpowuwpr", response.tags().get("qlveualupjmkh")); + Assertions.assertEquals("kpycgklwndnhjd", response.properties().securityPolicyConfigurations().wafSecurityPolicy().id()); } } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfacesListByResourceGroupMockTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfacesListByResourceGroupMockTests.java index d83366877203..c298588bab5d 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfacesListByResourceGroupMockTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfacesListByResourceGroupMockTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -22,7 +22,7 @@ public final class TrafficControllerInterfacesListByResourceGroupMockTests { @Test public void testListByResourceGroup() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"configurationEndpoints\":[\"puozmyzydag\",\"uaxbezyiuokkt\"],\"frontends\":[{\"id\":\"dxwzywqsmbsurexi\"},{\"id\":\"o\"},{\"id\":\"yocf\"}],\"associations\":[{\"id\":\"s\"},{\"id\":\"mddystkiiux\"}],\"securityPolicies\":[{\"id\":\"udxorrqn\"},{\"id\":\"poczvyifqrvkdvjs\"},{\"id\":\"lrmv\"}],\"securityPolicyConfigurations\":{\"wafSecurityPolicy\":{\"id\":\"watkpnpulexxb\"}},\"provisioningState\":\"Updating\"},\"location\":\"ruwiqzbqjvsov\",\"tags\":{\"hzdobpxjmflbvvnc\":\"kacspkw\",\"rsa\":\"rkcciwwzjuqk\"},\"id\":\"iwkuofos\",\"name\":\"ghsauuimjmvxied\",\"type\":\"ugidyjrr\"}]}"; + = "{\"value\":[{\"properties\":{\"configurationEndpoints\":[\"vlvqhjkbegi\",\"t\",\"mxiebw\",\"aloayqcgwrtzju\"],\"frontends\":[{\"id\":\"yzm\"},{\"id\":\"txon\"},{\"id\":\"mtsavjcbpwxqp\"}],\"associations\":[{\"id\":\"nftguvriuhpr\"},{\"id\":\"mdyvxqtayriw\"},{\"id\":\"ro\"}],\"securityPolicies\":[{\"id\":\"exrmcqibycnojvk\"},{\"id\":\"mefqsgzvahapjyzh\"}],\"securityPolicyConfigurations\":{\"wafSecurityPolicy\":{\"id\":\"qzcjrvxdj\"}},\"provisioningState\":\"Updating\"},\"location\":\"lxkvu\",\"tags\":{\"nluthnnp\":\"zovawjvz\",\"jzuaejxdultskzbb\":\"nxipeil\",\"wozuhkf\":\"dzumveekg\",\"uusdttouwa\":\"bsjyofdx\"},\"id\":\"oekqvk\",\"name\":\"lns\",\"type\":\"vbxwyjsflhh\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -32,11 +32,11 @@ public void testListByResourceGroup() throws Exception { new AzureProfile("", "", AzureEnvironment.AZURE)); PagedIterable response - = manager.trafficControllerInterfaces().listByResourceGroup("uaodsfcpk", com.azure.core.util.Context.NONE); + = manager.trafficControllerInterfaces().listByResourceGroup("c", com.azure.core.util.Context.NONE); - Assertions.assertEquals("ruwiqzbqjvsov", response.iterator().next().location()); - Assertions.assertEquals("kacspkw", response.iterator().next().tags().get("hzdobpxjmflbvvnc")); - Assertions.assertEquals("watkpnpulexxb", + Assertions.assertEquals("lxkvu", response.iterator().next().location()); + Assertions.assertEquals("zovawjvz", response.iterator().next().tags().get("nluthnnp")); + Assertions.assertEquals("qzcjrvxdj", response.iterator().next().properties().securityPolicyConfigurations().wafSecurityPolicy().id()); } } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfacesListMockTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfacesListMockTests.java index a1c97c53d7f8..5c4de0445747 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfacesListMockTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerInterfacesListMockTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -22,7 +22,7 @@ public final class TrafficControllerInterfacesListMockTests { @Test public void testList() throws Exception { String responseStr - = "{\"value\":[{\"properties\":{\"configurationEndpoints\":[\"bvyvdcsity\"],\"frontends\":[{\"id\":\"amdecte\"},{\"id\":\"f\"}],\"associations\":[{\"id\":\"cj\"},{\"id\":\"ypvhezrkg\"}],\"securityPolicies\":[{\"id\":\"jrefovgmkqsle\"}],\"securityPolicyConfigurations\":{\"wafSecurityPolicy\":{\"id\":\"xyqj\"}},\"provisioningState\":\"Provisioning\"},\"location\":\"t\",\"tags\":{\"ajvnysounqe\":\"gjcrcczsqpjhvm\"},\"id\":\"a\",\"name\":\"oaeupfhyhltrpmo\",\"type\":\"jmcmatuokthfu\"}]}"; + = "{\"value\":[{\"properties\":{\"configurationEndpoints\":[\"n\",\"ixisxyawjoy\",\"qcslyjpkiid\"],\"frontends\":[{\"id\":\"xznelixhnrztf\"},{\"id\":\"lhbnxkna\"},{\"id\":\"aulppggd\"}],\"associations\":[{\"id\":\"apnyiropuhpig\"},{\"id\":\"pgylg\"},{\"id\":\"git\"},{\"id\":\"medjvcslynqwwncw\"}],\"securityPolicies\":[{\"id\":\"xgk\"}],\"securityPolicyConfigurations\":{\"wafSecurityPolicy\":{\"id\":\"gucnapkte\"}},\"provisioningState\":\"Succeeded\"},\"location\":\"wptfdy\",\"tags\":{\"huaoppp\":\"qbuaceopzfqr\",\"z\":\"qeqxo\",\"moizpos\":\"ahzxctobgbk\"},\"id\":\"mgrcfbu\",\"name\":\"rmfqjhhkxbpvj\",\"type\":\"mjh\"}]}"; HttpClient httpClient = response -> Mono.just(new MockHttpResponse(response, 200, responseStr.getBytes(StandardCharsets.UTF_8))); @@ -34,9 +34,9 @@ public void testList() throws Exception { PagedIterable response = manager.trafficControllerInterfaces().list(com.azure.core.util.Context.NONE); - Assertions.assertEquals("t", response.iterator().next().location()); - Assertions.assertEquals("gjcrcczsqpjhvm", response.iterator().next().tags().get("ajvnysounqe")); - Assertions.assertEquals("xyqj", + Assertions.assertEquals("wptfdy", response.iterator().next().location()); + Assertions.assertEquals("qbuaceopzfqr", response.iterator().next().tags().get("huaoppp")); + Assertions.assertEquals("gucnapkte", response.iterator().next().properties().securityPolicyConfigurations().wafSecurityPolicy().id()); } } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerListResultTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerListResultTests.java index 8634f4aba0a6..41dae233b0e3 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerListResultTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerListResultTests.java @@ -1,60 +1,23 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.servicenetworking.fluent.models.TrafficControllerInner; -import com.azure.resourcemanager.servicenetworking.models.SecurityPolicyConfigurations; -import com.azure.resourcemanager.servicenetworking.models.TrafficControllerListResult; -import com.azure.resourcemanager.servicenetworking.models.TrafficControllerProperties; -import com.azure.resourcemanager.servicenetworking.models.WafSecurityPolicy; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; +import com.azure.resourcemanager.servicenetworking.implementation.models.TrafficControllerListResult; import org.junit.jupiter.api.Assertions; public final class TrafficControllerListResultTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { TrafficControllerListResult model = BinaryData.fromString( - "{\"value\":[{\"properties\":{\"configurationEndpoints\":[\"th\",\"qhabifpikxwcz\",\"yscnpqxu\"],\"frontends\":[{\"id\":\"y\"}],\"associations\":[{\"id\":\"wby\"},{\"id\":\"rkxvdum\"},{\"id\":\"grtfwvu\"},{\"id\":\"xgaudccs\"}],\"securityPolicies\":[{\"id\":\"jcny\"}],\"securityPolicyConfigurations\":{\"wafSecurityPolicy\":{\"id\":\"kryhtnapczwlokj\"}},\"provisioningState\":\"Accepted\"},\"location\":\"kvnipjoxz\",\"tags\":{\"lzydehojwyahux\":\"hgejspodma\",\"vcputegj\":\"npmqnjaqwixjspro\",\"uuvmkjozkrwfnd\":\"wmfdatscmdvpjhul\"},\"id\":\"odjpslwejd\",\"name\":\"vwryoqpso\",\"type\":\"cctazakljlahbc\"}],\"nextLink\":\"ffdfdosygexpa\"}") + "{\"value\":[{\"properties\":{\"configurationEndpoints\":[\"w\"],\"frontends\":[{\"id\":\"a\"}],\"associations\":[{\"id\":\"z\"},{\"id\":\"yvvtpgvdfgio\"}],\"securityPolicies\":[{\"id\":\"tutqxlngxlefgug\"},{\"id\":\"xkrxdqmi\"},{\"id\":\"tthzrvqd\"},{\"id\":\"abhjybi\"}],\"securityPolicyConfigurations\":{\"wafSecurityPolicy\":{\"id\":\"oqfbowskanyk\"}},\"provisioningState\":\"Provisioning\"},\"location\":\"u\",\"tags\":{\"nhzgpphrcgyn\":\"gqywgndrv\",\"fsxlzevgbmqjqa\":\"ocpecfvmmco\"},\"id\":\"c\",\"name\":\"pmivkwlzu\",\"type\":\"ccfwnfnbacfion\"},{\"properties\":{\"configurationEndpoints\":[\"etqgtzxdpnq\"],\"frontends\":[{\"id\":\"wxrjfeallnwsub\"},{\"id\":\"snjampmng\"},{\"id\":\"zscxaqwo\"}],\"associations\":[{\"id\":\"cbonqvpk\"},{\"id\":\"lrxnjeaseiphe\"},{\"id\":\"f\"}],\"securityPolicies\":[{\"id\":\"eyy\"},{\"id\":\"enjbdlwtgrhp\"}],\"securityPolicyConfigurations\":{\"wafSecurityPolicy\":{\"id\":\"jumasx\"}},\"provisioningState\":\"Succeeded\"},\"location\":\"qyeg\",\"tags\":{\"xhejjzzvdud\":\"hb\",\"pwlbjnpg\":\"wdslfhotwmcy\",\"nltyfsoppusuesnz\":\"cftadeh\",\"xzdmohctb\":\"dejbavo\"},\"id\":\"vudwx\",\"name\":\"ndnvo\",\"type\":\"gujjugwdkcglh\"}],\"nextLink\":\"azjdyggd\"}") .toObject(TrafficControllerListResult.class); - Assertions.assertEquals("kvnipjoxz", model.value().get(0).location()); - Assertions.assertEquals("hgejspodma", model.value().get(0).tags().get("lzydehojwyahux")); - Assertions.assertEquals("kryhtnapczwlokj", + Assertions.assertEquals("u", model.value().get(0).location()); + Assertions.assertEquals("gqywgndrv", model.value().get(0).tags().get("nhzgpphrcgyn")); + Assertions.assertEquals("oqfbowskanyk", model.value().get(0).properties().securityPolicyConfigurations().wafSecurityPolicy().id()); - Assertions.assertEquals("ffdfdosygexpa", model.nextLink()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - TrafficControllerListResult model = new TrafficControllerListResult() - .withValue(Arrays.asList(new TrafficControllerInner().withLocation("kvnipjoxz") - .withTags(mapOf("lzydehojwyahux", "hgejspodma", "vcputegj", "npmqnjaqwixjspro", "uuvmkjozkrwfnd", - "wmfdatscmdvpjhul")) - .withProperties(new TrafficControllerProperties() - .withSecurityPolicyConfigurations(new SecurityPolicyConfigurations() - .withWafSecurityPolicy(new WafSecurityPolicy().withId("kryhtnapczwlokj")))))) - .withNextLink("ffdfdosygexpa"); - model = BinaryData.fromObject(model).toObject(TrafficControllerListResult.class); - Assertions.assertEquals("kvnipjoxz", model.value().get(0).location()); - Assertions.assertEquals("hgejspodma", model.value().get(0).tags().get("lzydehojwyahux")); - Assertions.assertEquals("kryhtnapczwlokj", - model.value().get(0).properties().securityPolicyConfigurations().wafSecurityPolicy().id()); - Assertions.assertEquals("ffdfdosygexpa", model.nextLink()); - } - - // Use "Map.of" if available - @SuppressWarnings("unchecked") - private static Map mapOf(Object... inputs) { - Map map = new HashMap<>(); - for (int i = 0; i < inputs.length; i += 2) { - String key = (String) inputs[i]; - T value = (T) inputs[i + 1]; - map.put(key, value); - } - return map; + Assertions.assertEquals("azjdyggd", model.nextLink()); } } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerPropertiesTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerPropertiesTests.java index 3a9350e61fc6..5b57e9021c77 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerPropertiesTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerPropertiesTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -14,16 +14,16 @@ public final class TrafficControllerPropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { TrafficControllerProperties model = BinaryData.fromString( - "{\"configurationEndpoints\":[\"cwrwclxxwrljdous\"],\"frontends\":[{\"id\":\"vkocrcjdkwtn\"},{\"id\":\"xbnjbiksq\"}],\"associations\":[{\"id\":\"ssainqpjwnzll\"},{\"id\":\"fmppe\"}],\"securityPolicies\":[{\"id\":\"mgxsab\"},{\"id\":\"yqduujit\"}],\"securityPolicyConfigurations\":{\"wafSecurityPolicy\":{\"id\":\"zdzevndh\"}},\"provisioningState\":\"Accepted\"}") + "{\"configurationEndpoints\":[\"mmajtjaodx\",\"bnbdxkqpxokajion\",\"imexgstxgcpodgma\"],\"frontends\":[{\"id\":\"mvdjwzrlovmc\"}],\"associations\":[{\"id\":\"ijcoejctb\"},{\"id\":\"aqsqsycbkbfk\"}],\"securityPolicies\":[{\"id\":\"dkexxppofm\"},{\"id\":\"axcfjpgddtocjjx\"}],\"securityPolicyConfigurations\":{\"wafSecurityPolicy\":{\"id\":\"mouexhdzx\"}},\"provisioningState\":\"Succeeded\"}") .toObject(TrafficControllerProperties.class); - Assertions.assertEquals("zdzevndh", model.securityPolicyConfigurations().wafSecurityPolicy().id()); + Assertions.assertEquals("mouexhdzx", model.securityPolicyConfigurations().wafSecurityPolicy().id()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { TrafficControllerProperties model = new TrafficControllerProperties().withSecurityPolicyConfigurations( - new SecurityPolicyConfigurations().withWafSecurityPolicy(new WafSecurityPolicy().withId("zdzevndh"))); + new SecurityPolicyConfigurations().withWafSecurityPolicy(new WafSecurityPolicy().withId("mouexhdzx"))); model = BinaryData.fromObject(model).toObject(TrafficControllerProperties.class); - Assertions.assertEquals("zdzevndh", model.securityPolicyConfigurations().wafSecurityPolicy().id()); + Assertions.assertEquals("mouexhdzx", model.securityPolicyConfigurations().wafSecurityPolicy().id()); } } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerUpdatePropertiesTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerUpdatePropertiesTests.java index 4899a433fb2f..a8a5a8c0e2c4 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerUpdatePropertiesTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerUpdatePropertiesTests.java @@ -1,30 +1,30 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.servicenetworking.models.SecurityPolicyConfigurationsUpdate; +import com.azure.resourcemanager.servicenetworking.models.SecurityPolicyConfigurations; import com.azure.resourcemanager.servicenetworking.models.TrafficControllerUpdateProperties; -import com.azure.resourcemanager.servicenetworking.models.WafSecurityPolicyUpdate; +import com.azure.resourcemanager.servicenetworking.models.WafSecurityPolicy; import org.junit.jupiter.api.Assertions; public final class TrafficControllerUpdatePropertiesTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - TrafficControllerUpdateProperties model - = BinaryData.fromString("{\"securityPolicyConfigurations\":{\"wafSecurityPolicy\":{\"id\":\"jkot\"}}}") - .toObject(TrafficControllerUpdateProperties.class); - Assertions.assertEquals("jkot", model.securityPolicyConfigurations().wafSecurityPolicy().id()); + TrafficControllerUpdateProperties model = BinaryData + .fromString("{\"securityPolicyConfigurations\":{\"wafSecurityPolicy\":{\"id\":\"xuigdtopbobj\"}}}") + .toObject(TrafficControllerUpdateProperties.class); + Assertions.assertEquals("xuigdtopbobj", model.securityPolicyConfigurations().wafSecurityPolicy().id()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { TrafficControllerUpdateProperties model = new TrafficControllerUpdateProperties() - .withSecurityPolicyConfigurations(new SecurityPolicyConfigurationsUpdate() - .withWafSecurityPolicy(new WafSecurityPolicyUpdate().withId("jkot"))); + .withSecurityPolicyConfigurations(new SecurityPolicyConfigurations() + .withWafSecurityPolicy(new WafSecurityPolicy().withId("xuigdtopbobj"))); model = BinaryData.fromObject(model).toObject(TrafficControllerUpdateProperties.class); - Assertions.assertEquals("jkot", model.securityPolicyConfigurations().wafSecurityPolicy().id()); + Assertions.assertEquals("xuigdtopbobj", model.securityPolicyConfigurations().wafSecurityPolicy().id()); } } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerUpdateTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerUpdateTests.java index 8e7f3e697521..17341013dacd 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerUpdateTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/TrafficControllerUpdateTests.java @@ -1,14 +1,14 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.servicenetworking.models.SecurityPolicyConfigurationsUpdate; +import com.azure.resourcemanager.servicenetworking.models.SecurityPolicyConfigurations; import com.azure.resourcemanager.servicenetworking.models.TrafficControllerUpdate; import com.azure.resourcemanager.servicenetworking.models.TrafficControllerUpdateProperties; -import com.azure.resourcemanager.servicenetworking.models.WafSecurityPolicyUpdate; +import com.azure.resourcemanager.servicenetworking.models.WafSecurityPolicy; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; @@ -17,23 +17,23 @@ public final class TrafficControllerUpdateTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { TrafficControllerUpdate model = BinaryData.fromString( - "{\"tags\":{\"dgeablgphu\":\"atqxho\",\"xhurok\":\"icndvkaozwyifty\",\"kjfkg\":\"tyxolniwpwc\",\"plwckbas\":\"awxklr\"},\"properties\":{\"securityPolicyConfigurations\":{\"wafSecurityPolicy\":{\"id\":\"dhsgcba\"}}}}") + "{\"tags\":{\"t\":\"ddglm\"},\"properties\":{\"securityPolicyConfigurations\":{\"wafSecurityPolicy\":{\"id\":\"wpyeicxmqciwqvh\"}}}}") .toObject(TrafficControllerUpdate.class); - Assertions.assertEquals("atqxho", model.tags().get("dgeablgphu")); - Assertions.assertEquals("dhsgcba", model.properties().securityPolicyConfigurations().wafSecurityPolicy().id()); + Assertions.assertEquals("ddglm", model.tags().get("t")); + Assertions.assertEquals("wpyeicxmqciwqvh", + model.properties().securityPolicyConfigurations().wafSecurityPolicy().id()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - TrafficControllerUpdate model = new TrafficControllerUpdate() - .withTags(mapOf("dgeablgphu", "atqxho", "xhurok", "icndvkaozwyifty", "kjfkg", "tyxolniwpwc", "plwckbas", - "awxklr")) + TrafficControllerUpdate model = new TrafficControllerUpdate().withTags(mapOf("t", "ddglm")) .withProperties(new TrafficControllerUpdateProperties() - .withSecurityPolicyConfigurations(new SecurityPolicyConfigurationsUpdate() - .withWafSecurityPolicy(new WafSecurityPolicyUpdate().withId("dhsgcba")))); + .withSecurityPolicyConfigurations(new SecurityPolicyConfigurations() + .withWafSecurityPolicy(new WafSecurityPolicy().withId("wpyeicxmqciwqvh")))); model = BinaryData.fromObject(model).toObject(TrafficControllerUpdate.class); - Assertions.assertEquals("atqxho", model.tags().get("dgeablgphu")); - Assertions.assertEquals("dhsgcba", model.properties().securityPolicyConfigurations().wafSecurityPolicy().id()); + Assertions.assertEquals("ddglm", model.tags().get("t")); + Assertions.assertEquals("wpyeicxmqciwqvh", + model.properties().securityPolicyConfigurations().wafSecurityPolicy().id()); } // Use "Map.of" if available diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/WafPolicyTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/WafPolicyTests.java index 23dc9d662b94..b80c16f825d0 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/WafPolicyTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/WafPolicyTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -11,14 +11,14 @@ public final class WafPolicyTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { - WafPolicy model = BinaryData.fromString("{\"id\":\"wtgrhpdjpj\"}").toObject(WafPolicy.class); - Assertions.assertEquals("wtgrhpdjpj", model.id()); + WafPolicy model = BinaryData.fromString("{\"id\":\"psalgbqux\"}").toObject(WafPolicy.class); + Assertions.assertEquals("psalgbqux", model.id()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - WafPolicy model = new WafPolicy().withId("wtgrhpdjpj"); + WafPolicy model = new WafPolicy().withId("psalgbqux"); model = BinaryData.fromObject(model).toObject(WafPolicy.class); - Assertions.assertEquals("wtgrhpdjpj", model.id()); + Assertions.assertEquals("psalgbqux", model.id()); } } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/WafPolicyUpdateTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/WafPolicyUpdateTests.java deleted file mode 100644 index 1e90ed6deab6..000000000000 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/WafPolicyUpdateTests.java +++ /dev/null @@ -1,24 +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.resourcemanager.servicenetworking.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.servicenetworking.models.WafPolicyUpdate; -import org.junit.jupiter.api.Assertions; - -public final class WafPolicyUpdateTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - WafPolicyUpdate model = BinaryData.fromString("{\"id\":\"bqvudwxdndn\"}").toObject(WafPolicyUpdate.class); - Assertions.assertEquals("bqvudwxdndn", model.id()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - WafPolicyUpdate model = new WafPolicyUpdate().withId("bqvudwxdndn"); - model = BinaryData.fromObject(model).toObject(WafPolicyUpdate.class); - Assertions.assertEquals("bqvudwxdndn", model.id()); - } -} diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/WafSecurityPolicyTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/WafSecurityPolicyTests.java index 568a8f13325f..7d5bc149385d 100644 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/WafSecurityPolicyTests.java +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/WafSecurityPolicyTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.resourcemanager.servicenetworking.generated; @@ -12,14 +12,14 @@ public final class WafSecurityPolicyTests { @org.junit.jupiter.api.Test public void testDeserialize() throws Exception { WafSecurityPolicy model - = BinaryData.fromString("{\"id\":\"nhutjeltmrldhugj\"}").toObject(WafSecurityPolicy.class); - Assertions.assertEquals("nhutjeltmrldhugj", model.id()); + = BinaryData.fromString("{\"id\":\"btwnpzaoqvuhrhcf\"}").toObject(WafSecurityPolicy.class); + Assertions.assertEquals("btwnpzaoqvuhrhcf", model.id()); } @org.junit.jupiter.api.Test public void testSerialize() throws Exception { - WafSecurityPolicy model = new WafSecurityPolicy().withId("nhutjeltmrldhugj"); + WafSecurityPolicy model = new WafSecurityPolicy().withId("btwnpzaoqvuhrhcf"); model = BinaryData.fromObject(model).toObject(WafSecurityPolicy.class); - Assertions.assertEquals("nhutjeltmrldhugj", model.id()); + Assertions.assertEquals("btwnpzaoqvuhrhcf", model.id()); } } diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/WafSecurityPolicyUpdateTests.java b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/WafSecurityPolicyUpdateTests.java deleted file mode 100644 index fa44faa98441..000000000000 --- a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/src/test/java/com/azure/resourcemanager/servicenetworking/generated/WafSecurityPolicyUpdateTests.java +++ /dev/null @@ -1,25 +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.resourcemanager.servicenetworking.generated; - -import com.azure.core.util.BinaryData; -import com.azure.resourcemanager.servicenetworking.models.WafSecurityPolicyUpdate; -import org.junit.jupiter.api.Assertions; - -public final class WafSecurityPolicyUpdateTests { - @org.junit.jupiter.api.Test - public void testDeserialize() throws Exception { - WafSecurityPolicyUpdate model - = BinaryData.fromString("{\"id\":\"ndlik\"}").toObject(WafSecurityPolicyUpdate.class); - Assertions.assertEquals("ndlik", model.id()); - } - - @org.junit.jupiter.api.Test - public void testSerialize() throws Exception { - WafSecurityPolicyUpdate model = new WafSecurityPolicyUpdate().withId("ndlik"); - model = BinaryData.fromObject(model).toObject(WafSecurityPolicyUpdate.class); - Assertions.assertEquals("ndlik", model.id()); - } -} diff --git a/sdk/servicenetworking/azure-resourcemanager-servicenetworking/tsp-location.yaml b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/tsp-location.yaml new file mode 100644 index 000000000000..3e38b59b745b --- /dev/null +++ b/sdk/servicenetworking/azure-resourcemanager-servicenetworking/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/servicenetworking/ServiceNetworking.Management +commit: 05b150757bd72ad78bd27216e5e662beaa49bd6c +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/signalr/azure-resourcemanager-signalr/README.md b/sdk/signalr/azure-resourcemanager-signalr/README.md index cb0bb2247bcb..519d3ca60651 100644 --- a/sdk/signalr/azure-resourcemanager-signalr/README.md +++ b/sdk/signalr/azure-resourcemanager-signalr/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-signalr - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fsignalr%2Fazure-resourcemanager-signalr%2FREADME.png) + diff --git a/sdk/signalr/azure-resourcemanager-signalr/pom.xml b/sdk/signalr/azure-resourcemanager-signalr/pom.xml index 62606447f4d6..2e6ab58f8dae 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.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/sphere/azure-resourcemanager-sphere/README.md b/sdk/sphere/azure-resourcemanager-sphere/README.md index 7041a19d3c92..c83cb85ce457 100644 --- a/sdk/sphere/azure-resourcemanager-sphere/README.md +++ b/sdk/sphere/azure-resourcemanager-sphere/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-sphere - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -108,4 +108,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fsphere%2Fazure-resourcemanager-sphere%2FREADME.png) + diff --git a/sdk/sphere/azure-resourcemanager-sphere/pom.xml b/sdk/sphere/azure-resourcemanager-sphere/pom.xml index f52fcaea949a..df96221e349a 100644 --- a/sdk/sphere/azure-resourcemanager-sphere/pom.xml +++ b/sdk/sphere/azure-resourcemanager-sphere/pom.xml @@ -51,29 +51,29 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/spring/CHANGELOG.md b/sdk/spring/CHANGELOG.md index e170dc897681..768b5b7d510c 100644 --- a/sdk/spring/CHANGELOG.md +++ b/sdk/spring/CHANGELOG.md @@ -1,13 +1,50 @@ # Release History -## 5.20.0-beta.1 (Unreleased) -Upgrade Spring Boot dependencies version to 3.4.1 and Spring Cloud dependencies version to 2024.0.0 +## 5.21.0-beta.1 (Unreleased) + +#### Features Added +- Add the `spring-cloud-azure-starter-keyvault-jca`. This starter supports SSL Bundle with Azure Key Vault certificates. [#35782](https://github.com/Azure/azure-sdk-for-java/issues/35782). + +### Spring Cloud Azure Dependencies (BOM) + +#### Dependency Updates +- Add dependency `com.azure.spring:spring-cloud-azure-starter-keyvault-jca`. + +### Spring Cloud Azure Autoconfigure +This section includes changes in `spring-cloud-azure-autoconfigure` module. + +#### Bugs Fixed +- Custom `ObjectMapper` bean does not work for received messages. [#37796](https://github.com/Azure/azure-sdk-for-java/issues/37796). + +### Spring Cloud Azure Starter Key Vault +This section includes changes in `spring-cloud-azure-starter-keyvault` module. + +#### Features Added +- Support SSL Bundle with Azure Key Vault certificates [#44259](https://github.com/Azure/azure-sdk-for-java/pull/44259). + +## 5.20.1 (2025-03-03) +- This release is compatible with Spring Boot 3.4.0-3.4.2, 3.3.0-3.3.6, 3.2.0-3.2.12, 3.1.0-3.1.12, 3.0.0-3.0.13. (Note: 3.4.x (x>2), 3.3.y (y>6) and 3.2.z (z>12) should be supported, but they aren't tested with this release.) +- This release is compatible with Spring Cloud 2024.0.0, 2023.0.0-2023.0.4, 2022.0.0-2022.0.5. (Note: 2024.0.x(x>0) and 2023.0.y (y>4) should be supported, but they aren't tested with this release.) + +### Spring Cloud Azure Dependencies (BOM) + +#### Dependency Updates +- Upgrade `azure-sdk-bom` to 1.2.31. + +### Azure Spring Data Cosmos +This section includes changes in `azure-spring-data-cosmos` module. +Please refer to [azure-spring-data-cosmos/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/spring/azure-spring-data-cosmos/CHANGELOG.md#5201-2025-03-03) for more details. + +## 5.20.0 (2025-02-12) +- This release is compatible with Spring Boot 3.4.0-3.4.2, 3.3.0-3.3.6, 3.2.0-3.2.12, 3.1.0-3.1.12, 3.0.0-3.0.13. (Note: 3.4.x (x>2), 3.3.y (y>6) and 3.2.z (z>12) should be supported, but they aren't tested with this release.) +- This release is compatible with Spring Cloud 2024.0.0, 2023.0.0-2023.0.4, 2022.0.0-2022.0.5. (Note: 2024.0.x(x>0) and 2023.0.y (y>4) should be supported, but they aren't tested with this release.) ### Spring Cloud Azure Autoconfigure This section includes changes in `spring-cloud-azure-autoconfigure` module. #### Bugs Fixed - Fix bug: Registered the empty value for ineligible definition, it causes NPE when sending message via bean `StreamBridge`. [#43366](https://github.com/Azure/azure-sdk-for-java/issues/43366). +- Fix bug: Not working when using Spring Kafka and Kafka Binder via connection string auth [#43853](https://github.com/Azure/azure-sdk-for-java/issues/43853). ### Spring Messaging Azure Service Bus This section includes changes in the `spring-messaging-azure-servicebus` module. @@ -15,6 +52,10 @@ This section includes changes in the `spring-messaging-azure-servicebus` module. #### Bugs Fixed - Fix bug: The `PropertiesMerger` implementation not handling property `CustomEndpointAddress`. [#43555](https://github.com/Azure/azure-sdk-for-java/issues/43555). +### Azure Spring Data Cosmos +This section includes changes in `azure-spring-data-cosmos` module. +Please refer to [azure-spring-data-cosmos/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/spring/azure-spring-data-cosmos/CHANGELOG.md#5200-2025-02-12) for more details. + ## 5.19.0 (2024-12-17) - This release is compatible with Spring Boot 3.4.0, 3.3.0-3.3.6, 3.2.0-3.2.12, 3.1.0-3.1.12, 3.0.0-3.0.13. (Note: 3.4.x (x>0), 3.3.y (y>6) and 3.2.z (z>12) should be supported, but they aren't tested with this release.) - This release is compatible with Spring Cloud 2024.0.0, 2023.0.0-2023.0.4, 2022.0.0-2022.0.5. (Note: 2024.0.x(x>0) and 2023.0.y (y>4) should be supported, but they aren't tested with this release.) diff --git a/sdk/spring/README.md b/sdk/spring/README.md index 5b24d565d803..48b30ebc117f 100644 --- a/sdk/spring/README.md +++ b/sdk/spring/README.md @@ -146,7 +146,7 @@ If you’re a Maven user, add our BOM to your pom.xml `` s com.azure.spring spring-cloud-azure-dependencies - 5.19.0 + 5.21.0-beta.1 pom import diff --git a/sdk/spring/azure-spring-data-cosmos/CHANGELOG.md b/sdk/spring/azure-spring-data-cosmos/CHANGELOG.md index 53e5b062b7fd..68cefff2ed5b 100644 --- a/sdk/spring/azure-spring-data-cosmos/CHANGELOG.md +++ b/sdk/spring/azure-spring-data-cosmos/CHANGELOG.md @@ -1,10 +1,9 @@ ## Release History -### 5.20.0-beta.1 (Unreleased) +### 5.21.0-beta.1 (Unreleased) #### Features Added -* Improved the Exception Handling of 'azure-spring-data-cosmos' to throw more detailed exceptions and not always the same exception - See [PR 42902](https://github.com/Azure/azure-sdk-for-java/pull/42902). -* Implemented sum() support for annotated queries - See [PR 43239](https://github.com/Azure/azure-sdk-for-java/pull/43239). +* Added `readMany()` API support to `findAllByIds()` - See [PR 43759](https://github.com/Azure/azure-sdk-for-java/pull/43759). #### Breaking Changes @@ -12,6 +11,20 @@ #### Other Changes +### 5.20.1 (2025-03-03) + +#### Other Changes +* Upgrade `azure-sdk-bom` to 1.2.31. + +### 5.20.0 (2025-02-12) + +#### Features Added +* Improved the Exception Handling of 'azure-spring-data-cosmos' to throw more detailed exceptions and not always the same exception - See [PR 42902](https://github.com/Azure/azure-sdk-for-java/pull/42902). +* Implemented sum() support for annotated queries - See [PR 43239](https://github.com/Azure/azure-sdk-for-java/pull/43239). + +#### Other Changes +* Updated `azure-cosmos` to version `4.66.0`. + ### 5.19.0 (2024-12-17) #### Bugs Fixed diff --git a/sdk/spring/azure-spring-data-cosmos/README.md b/sdk/spring/azure-spring-data-cosmos/README.md index 23169142b2f4..b978b097bbf8 100644 --- a/sdk/spring/azure-spring-data-cosmos/README.md +++ b/sdk/spring/azure-spring-data-cosmos/README.md @@ -100,7 +100,7 @@ If you are using Maven, add the following dependency. com.azure azure-spring-data-cosmos - 5.19.0 + 5.21.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -1167,4 +1167,4 @@ or contact [opencode@microsoft.com][coc_contact] with any additional questions o [spring_boot_supported_versions]: https://github.com/spring-projects/spring-boot/wiki/Supported-Versions [azure_cosmos_db_java_sdk_samples]: https://github.com/Azure-Samples/azure-cosmos-java-sql-api-samples -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcosmos%2F%2Fazure-spring-data-cosmos%2FREADME.png) + diff --git a/sdk/spring/azure-spring-data-cosmos/pom.xml b/sdk/spring/azure-spring-data-cosmos/pom.xml index 5e247f52619a..af44ce73c16d 100644 --- a/sdk/spring/azure-spring-data-cosmos/pom.xml +++ b/sdk/spring/azure-spring-data-cosmos/pom.xml @@ -12,7 +12,7 @@ com.azure azure-spring-data-cosmos - 5.20.0-beta.1 + 5.21.0-beta.1 jar Spring Data for Azure Cosmos DB SQL API Spring Data for Azure Cosmos DB SQL API @@ -53,7 +53,7 @@ org.springframework spring-core - 6.2.1 + 6.2.2 commons-logging @@ -64,27 +64,27 @@ org.springframework spring-web - 6.2.1 + 6.2.2 org.springframework spring-beans - 6.2.1 + 6.2.2 org.springframework spring-context - 6.2.1 + 6.2.2 org.springframework spring-tx - 6.2.1 + 6.2.2 org.springframework.data spring-data-commons - 3.4.1 + 3.4.2 org.slf4j @@ -95,12 +95,12 @@ org.springframework spring-expression - 6.2.1 + 6.2.2 com.azure azure-cosmos - 4.66.0 + 4.67.0 com.fasterxml.jackson.module @@ -163,7 +163,7 @@ org.springframework.boot spring-boot-starter-test - 3.4.1 + 3.4.2 test @@ -175,7 +175,7 @@ io.projectreactor reactor-test - 3.7.1 + 3.7.2 test @@ -273,13 +273,13 @@ - org.springframework:spring-beans:[6.2.1] - org.springframework:spring-web:[6.2.1] - org.springframework:spring-tx:[6.2.1] - org.springframework:spring-expression:[6.2.1] - org.springframework:spring-core:[6.2.1] - org.springframework:spring-context:[6.2.1] - org.springframework.data:spring-data-commons:[3.4.1] + org.springframework:spring-beans:[6.2.2] + org.springframework:spring-web:[6.2.2] + org.springframework:spring-tx:[6.2.2] + org.springframework:spring-expression:[6.2.2] + org.springframework:spring-core:[6.2.2] + org.springframework:spring-context:[6.2.2] + org.springframework.data:spring-data-commons:[3.4.2] org.javatuples:javatuples:[1.2] com.fasterxml.jackson.core:jackson-annotations:[2.18.2] com.fasterxml.jackson.datatype:jackson-datatype-jdk8:[2.18.2] diff --git a/sdk/spring/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/Constants.java b/sdk/spring/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/Constants.java index 3f459d73b884..99c751bf8bf0 100644 --- a/sdk/spring/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/Constants.java +++ b/sdk/spring/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/Constants.java @@ -91,107 +91,6 @@ public final class Constants { */ public static final String ISO_8601_COMPATIBLE_DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ss:SSSXXX"; - /** - * Cosmos Exception Status Codes. - */ - public static final class CosmosExceptionStatusCodes { - /** - * Default constructor. - */ - private CosmosExceptionStatusCodes() { - } - /** - * Bad Request Status Code. - */ - public static final int BADREQUEST = 400; - /** - * Conflict Status Code. - */ - public static final int CONFLICT = 409; - /** - * Forbidden Status Code. - */ - public static final int FORBIDDEN = 403; - /** - * Gone Status Code. - */ - public static final int GONE = 410; - /** - * Internal Server Error Status Code. - */ - public static final int INTERNAL_SERVER_ERROR = 500; - /** - * Method Not Allowed Status Code. - */ - public static final int METHOD_NOT_ALLOWED = 405; - /** - * Not Found Status Code. - */ - public static final int NOTFOUND = 404; - /** - * Request Timeout Status Code. - */ - public static final int REQUEST_TIMEOUT = 408; - /** - * Precondition Failed Status Code. - */ - public static final int PRECONDITION_FAILED = 412; - /** - * Request Entity Too Large Status Code. - */ - public static final int REQUEST_ENTITY_TOO_LARGE = 413; - /** - * Too Many Requests Status Code. - */ - public static final int TOO_MANY_REQUESTS = 429; - /** - * Retry With Status Code. - */ - public static final int RETRY_WITH = 449; - /** - * Service Unavailable Status Code. - */ - public static final int SERVICE_UNAVAILABLE = 503; - /** - * Unauthorized Status Code. - */ - public static final int UNAUTHORIZED = 401; - } - - /** - * Cosmos Exception Sub Status Codes. - */ - public static final class CosmosExceptionSubStatusCodes { - /** - * Default constructor. - */ - private CosmosExceptionSubStatusCodes() { - } - // For 410 GONE - /** - * Name Cache Is Stale Sub Status Code. - */ - public static final int NAME_CACHE_IS_STALE = 1000; - /** - * Partition Key Range Gone Sub Status Code. - */ - public static final int PARTITION_KEY_RANGE_GONE = 1002; - /** - * Completing Split or Merge Sub Status Code. - */ - public static final int COMPLETING_SPLIT_OR_MERGE = 1007; - /** - * Completing Partition Migration Sub Status Code. - */ - public static final int COMPLETING_PARTITION_MIGRATION = 1008; - - // For 408 REQUEST_TIMEOUT - /** - * Client Operation Timeout Sub Status Code. - */ - public static final int CLIENT_OPERATION_TIMEOUT = 20008; - } - private Constants() { } } diff --git a/sdk/spring/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/CosmosOperations.java b/sdk/spring/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/CosmosOperations.java index 0c1681b61670..fb4ccc9a6652 100644 --- a/sdk/spring/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/CosmosOperations.java +++ b/sdk/spring/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/CosmosOperations.java @@ -372,10 +372,9 @@ public interface CosmosOperations { * * @param querySpec the document query spec * @param containerName the container name - * @param type class of domainType * @return sum result */ - long sum(SqlQuerySpec querySpec, String containerName); + long sum(SqlQuerySpec querySpec, String containerName); /** * To get converter diff --git a/sdk/spring/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/CosmosTemplate.java b/sdk/spring/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/CosmosTemplate.java index c3ab71dc3801..9bea4d7322a0 100644 --- a/sdk/spring/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/CosmosTemplate.java +++ b/sdk/spring/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/CosmosTemplate.java @@ -12,12 +12,14 @@ import com.azure.cosmos.models.CosmosContainerProperties; import com.azure.cosmos.models.CosmosContainerResponse; import com.azure.cosmos.models.CosmosDatabaseResponse; +import com.azure.cosmos.models.CosmosItemIdentity; import com.azure.cosmos.models.CosmosItemOperation; import com.azure.cosmos.models.CosmosItemRequestOptions; import com.azure.cosmos.models.CosmosItemResponse; import com.azure.cosmos.models.CosmosPatchItemRequestOptions; import com.azure.cosmos.models.CosmosPatchOperations; import com.azure.cosmos.models.CosmosQueryRequestOptions; +import com.azure.cosmos.models.CosmosReadManyRequestOptions; import com.azure.cosmos.models.FeedResponse; import com.azure.cosmos.models.PartitionKey; import com.azure.cosmos.models.PartitionKeyDefinition; @@ -856,13 +858,40 @@ public Iterable findByIds(Iterable ids, Class domainType, Stri Assert.notNull(ids, "Id list should not be null"); Assert.notNull(domainType, "domainType should not be null."); Assert.hasText(containerName, "container should not be null, empty or only whitespaces"); - final List idList = new ArrayList<>(); - for (ID id : ids) { - idList.add(CosmosUtils.getStringIDValue(id)); + + CosmosEntityInformation cosmosEntityInformation = CosmosEntityInformation.getInstance(domainType); + String containerPartitionKey = cosmosEntityInformation.getPartitionKeyFieldName(); + if ("id".equals(containerPartitionKey) && ids.iterator().next() != null) { + List idList = new ArrayList<>(); + for (ID id : ids) { + idList.add(new CosmosItemIdentity(new PartitionKey(id), String.valueOf(id))); + } + + final CosmosReadManyRequestOptions cosmosReadManyRequestOptions = new CosmosReadManyRequestOptions(); + containerName = getContainerNameOverride(containerName); + cosmosReadManyRequestOptions.setQueryMetricsEnabled(this.queryMetricsEnabled); + cosmosReadManyRequestOptions.setIndexMetricsEnabled(this.indexMetricsEnabled); + cosmosReadManyRequestOptions.setResponseContinuationTokenLimitInKb(this.responseContinuationTokenLimitInKb); + + return this.getCosmosAsyncClient() + .getDatabase(this.getDatabaseName()) + .getContainer(containerName) + .readMany(idList, cosmosReadManyRequestOptions, domainType) + .publishOn(CosmosSchedulers.SPRING_DATA_COSMOS_PARALLEL) + .onErrorResume(throwable -> + CosmosExceptionUtils.exceptionHandler("Failed to find items", throwable, + this.responseDiagnosticsProcessor)) + .block().getResults(); + } else { + final List idList = new ArrayList<>(); + for (ID id : ids) { + idList.add(CosmosUtils.getStringIDValue(id)); + } + final CosmosQuery query = new CosmosQuery(Criteria.getInstance(CriteriaType.IN, "id", + Collections.singletonList(idList), Part.IgnoreCaseType.NEVER)); + return find(query, domainType, containerName); } - final CosmosQuery query = new CosmosQuery(Criteria.getInstance(CriteriaType.IN, "id", - Collections.singletonList(idList), Part.IgnoreCaseType.NEVER)); - return find(query, domainType, containerName); + } /** @@ -1136,7 +1165,7 @@ public long count(SqlQuerySpec querySpec, String containerName) { } @Override - public long sum(SqlQuerySpec querySpec, String containerName) { + public long sum(SqlQuerySpec querySpec, String containerName) { return this.numeric(querySpec, containerName); } diff --git a/sdk/spring/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/CosmosExceptionUtils.java b/sdk/spring/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/CosmosExceptionUtils.java index 2c4f448191ac..d0f1fa090de3 100644 --- a/sdk/spring/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/CosmosExceptionUtils.java +++ b/sdk/spring/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/CosmosExceptionUtils.java @@ -3,9 +3,9 @@ package com.azure.spring.data.cosmos.exception; import com.azure.cosmos.CosmosException; -import com.azure.spring.data.cosmos.Constants; import com.azure.spring.data.cosmos.common.CosmosUtils; import com.azure.spring.data.cosmos.core.ResponseDiagnosticsProcessor; +import org.springframework.http.HttpStatus; import org.springframework.util.ObjectUtils; import reactor.core.Exceptions; import reactor.core.publisher.Mono; @@ -43,66 +43,52 @@ public static Mono exceptionHandler(String message, Throwable throwable, CosmosException cosmosException = (CosmosException) unwrappedThrowable; CosmosUtils.fillAndProcessCosmosExceptionDiagnostics(responseDiagnosticsProcessor, cosmosException); - switch (cosmosException.getStatusCode()) { - case Constants.CosmosExceptionStatusCodes.BADREQUEST: - cosmosAccessException = new CosmosBadRequestException(message, cosmosException); - break; - case Constants.CosmosExceptionStatusCodes.CONFLICT: - cosmosAccessException = new CosmosConflictException(message, cosmosException); - break; - case Constants.CosmosExceptionStatusCodes.FORBIDDEN: - cosmosAccessException = new CosmosForbiddenException(message, cosmosException); - break; - case Constants.CosmosExceptionStatusCodes.GONE: - if (cosmosException.getSubStatusCode() == Constants.CosmosExceptionSubStatusCodes.NAME_CACHE_IS_STALE) { - cosmosAccessException = new CosmosInvalidPartitionException(message, cosmosException); - } else if (cosmosException.getSubStatusCode() == Constants.CosmosExceptionSubStatusCodes.COMPLETING_PARTITION_MIGRATION) { - cosmosAccessException = new CosmosPartitionIsMigratingException(message, cosmosException); - } else if (cosmosException.getSubStatusCode() == Constants.CosmosExceptionSubStatusCodes.PARTITION_KEY_RANGE_GONE) { - cosmosAccessException = new CosmosPartitionKeyRangeGoneException(message, cosmosException); - } else if (cosmosException.getSubStatusCode() == Constants.CosmosExceptionSubStatusCodes.COMPLETING_SPLIT_OR_MERGE) { - cosmosAccessException = new CosmosPartitionKeyRangeIsSplittingException(message, cosmosException); - } else { - cosmosAccessException = new CosmosGoneException(message, cosmosException); - } - break; - case Constants.CosmosExceptionStatusCodes.INTERNAL_SERVER_ERROR: - cosmosAccessException = new CosmosInternalServerErrorException(message, cosmosException); - break; - case Constants.CosmosExceptionStatusCodes.METHOD_NOT_ALLOWED: - cosmosAccessException = new CosmosMethodNotAllowedException(message, cosmosException); - break; - case Constants.CosmosExceptionStatusCodes.NOTFOUND: - cosmosAccessException = new CosmosNotFoundException(message, cosmosException); - break; - case Constants.CosmosExceptionStatusCodes.REQUEST_TIMEOUT: - if (((CosmosException) unwrappedThrowable).getSubStatusCode() == Constants.CosmosExceptionSubStatusCodes.CLIENT_OPERATION_TIMEOUT) { - cosmosAccessException = new CosmosOperationCancelledException(message, cosmosException); - } else { - cosmosAccessException = new CosmosRequestTimeoutException(message, cosmosException); - } - break; - case Constants.CosmosExceptionStatusCodes.PRECONDITION_FAILED: - cosmosAccessException = new CosmosPreconditionFailedException(message, cosmosException); - break; - case Constants.CosmosExceptionStatusCodes.REQUEST_ENTITY_TOO_LARGE: - cosmosAccessException = new CosmosRequestEntityTooLargeException(message, cosmosException); - break; - case Constants.CosmosExceptionStatusCodes.TOO_MANY_REQUESTS: - cosmosAccessException = new CosmosRequestRateTooLargeException(message, cosmosException); - break; - case Constants.CosmosExceptionStatusCodes.RETRY_WITH: - cosmosAccessException = new CosmosRetryWithException(message, cosmosException); - break; - case Constants.CosmosExceptionStatusCodes.SERVICE_UNAVAILABLE: - cosmosAccessException = new CosmosServiceUnavailableException(message, cosmosException); - break; - case Constants.CosmosExceptionStatusCodes.UNAUTHORIZED: - cosmosAccessException = new CosmosUnauthorizedException(message, cosmosException); - break; - default: - cosmosAccessException = new CosmosAccessException(message, cosmosException); - break; + int statusCode = cosmosException.getStatusCode(); + int subStatusCode = ((CosmosException) unwrappedThrowable).getSubStatusCode(); + if (statusCode == HttpStatus.BAD_REQUEST.value()) { + cosmosAccessException = new CosmosBadRequestException(message, cosmosException); + } else if (statusCode == HttpStatus.CONFLICT.value()) { + cosmosAccessException = new CosmosConflictException(message, cosmosException); + } else if (statusCode == HttpStatus.FORBIDDEN.value()) { + cosmosAccessException = new CosmosForbiddenException(message, cosmosException); + } else if (statusCode == HttpStatus.GONE.value()) { + if (subStatusCode == HttpConstants.CosmosExceptionSubStatusCodes.NAME_CACHE_IS_STALE) { + cosmosAccessException = new CosmosInvalidPartitionException(message, cosmosException); + } else if (subStatusCode == HttpConstants.CosmosExceptionSubStatusCodes.COMPLETING_PARTITION_MIGRATION) { + cosmosAccessException = new CosmosPartitionIsMigratingException(message, cosmosException); + } else if (subStatusCode == HttpConstants.CosmosExceptionSubStatusCodes.PARTITION_KEY_RANGE_GONE) { + cosmosAccessException = new CosmosPartitionKeyRangeGoneException(message, cosmosException); + } else if (subStatusCode == HttpConstants.CosmosExceptionSubStatusCodes.COMPLETING_SPLIT_OR_MERGE) { + cosmosAccessException = new CosmosPartitionKeyRangeIsSplittingException(message, cosmosException); + } else { + cosmosAccessException = new CosmosGoneException(message, cosmosException); + } + } else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) { + cosmosAccessException = new CosmosInternalServerErrorException(message, cosmosException); + } else if (statusCode == HttpStatus.METHOD_NOT_ALLOWED.value()) { + cosmosAccessException = new CosmosMethodNotAllowedException(message, cosmosException); + } else if (statusCode == HttpStatus.NOT_FOUND.value()) { + cosmosAccessException = new CosmosNotFoundException(message, cosmosException); + } else if (statusCode == HttpStatus.REQUEST_TIMEOUT.value()) { + if (subStatusCode == HttpConstants.CosmosExceptionSubStatusCodes.CLIENT_OPERATION_TIMEOUT) { + cosmosAccessException = new CosmosOperationCancelledException(message, cosmosException); + } else { + cosmosAccessException = new CosmosRequestTimeoutException(message, cosmosException); + } + } else if (statusCode == HttpStatus.PRECONDITION_FAILED.value()) { + cosmosAccessException = new CosmosPreconditionFailedException(message, cosmosException); + } else if (statusCode == HttpStatus.PAYLOAD_TOO_LARGE.value()) { + cosmosAccessException = new CosmosRequestEntityTooLargeException(message, cosmosException); + } else if (statusCode == HttpStatus.TOO_MANY_REQUESTS.value()) { + cosmosAccessException = new CosmosRequestRateTooLargeException(message, cosmosException); + } else if (statusCode == HttpConstants.CosmosExceptionStatusCodes.RETRY_WITH) { + cosmosAccessException = new CosmosRetryWithException(message, cosmosException); + } else if (statusCode == HttpStatus.SERVICE_UNAVAILABLE.value()) { + cosmosAccessException = new CosmosServiceUnavailableException(message, cosmosException); + } else if (statusCode == HttpStatus.UNAUTHORIZED.value()) { + cosmosAccessException = new CosmosUnauthorizedException(message, cosmosException); + } else { + cosmosAccessException = new CosmosAccessException(message, cosmosException); } } else { cosmosAccessException = new CosmosAccessException(message, unwrappedThrowable); diff --git a/sdk/spring/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/HttpConstants.java b/sdk/spring/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/HttpConstants.java new file mode 100644 index 000000000000..90bc3b8605cb --- /dev/null +++ b/sdk/spring/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/HttpConstants.java @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.spring.data.cosmos.exception; + + +/** + * Http Constants. + */ +final class HttpConstants { + + /** + * Cosmos Exception Status Codes. + */ + static final class CosmosExceptionStatusCodes { + /** + * Default constructor. + */ + private CosmosExceptionStatusCodes() { + } + /** + * Retry With Status Code. + */ + static final int RETRY_WITH = 449; + } + + /** + * Cosmos Exception Sub Status Codes. + */ + static final class CosmosExceptionSubStatusCodes { + /** + * Default constructor. + */ + private CosmosExceptionSubStatusCodes() { + } + // For 410 GONE + /** + * Name Cache Is Stale Sub Status Code. + */ + static final int NAME_CACHE_IS_STALE = 1000; + /** + * Partition Key Range Gone Sub Status Code. + */ + static final int PARTITION_KEY_RANGE_GONE = 1002; + /** + * Completing Split or Merge Sub Status Code. + */ + static final int COMPLETING_SPLIT_OR_MERGE = 1007; + /** + * Completing Partition Migration Sub Status Code. + */ + static final int COMPLETING_PARTITION_MIGRATION = 1008; + + // For 408 REQUEST_TIMEOUT + /** + * Client Operation Timeout Sub Status Code. + */ + static final int CLIENT_OPERATION_TIMEOUT = 20008; + } + + /** + * Default constructor. + */ + private HttpConstants() { + } + +} diff --git a/sdk/spring/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/StringBasedCosmosQuery.java b/sdk/spring/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/StringBasedCosmosQuery.java index 6a5aea2021d2..713a7bf1a486 100644 --- a/sdk/spring/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/StringBasedCosmosQuery.java +++ b/sdk/spring/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/StringBasedCosmosQuery.java @@ -137,7 +137,7 @@ protected boolean isCountQuery() { * This method is used to determine if the query is a sum query. * @return boolean if the query is a sum query */ - protected boolean isSumQuery() { + boolean isSumQuery() { return isSumQuery(query, getQueryMethod().getReturnedObjectType()); } diff --git a/sdk/spring/azure-spring-data-cosmos/src/main/java/module-info.java b/sdk/spring/azure-spring-data-cosmos/src/main/java/module-info.java index 6a12a4355d20..438db3d8906d 100644 --- a/sdk/spring/azure-spring-data-cosmos/src/main/java/module-info.java +++ b/sdk/spring/azure-spring-data-cosmos/src/main/java/module-info.java @@ -15,6 +15,7 @@ requires spring.data.commons; requires spring.expression; requires spring.tx; + requires spring.web; exports com.azure.spring.data.cosmos; exports com.azure.spring.data.cosmos.common; diff --git a/sdk/spring/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/exception/CosmosExceptionUtilsTest.java b/sdk/spring/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/exception/CosmosExceptionUtilsTest.java index 0cf1aad1f053..334e3a2a7b54 100644 --- a/sdk/spring/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/exception/CosmosExceptionUtilsTest.java +++ b/sdk/spring/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/exception/CosmosExceptionUtilsTest.java @@ -4,10 +4,10 @@ import com.azure.cosmos.BridgeInternal; import com.azure.cosmos.CosmosException; -import com.azure.spring.data.cosmos.Constants; import com.azure.spring.data.cosmos.core.ResponseDiagnosticsProcessor; import org.junit.Test; import org.mockito.Mockito; +import org.springframework.http.HttpStatus; import static org.junit.Assert.assertThrows; @@ -17,7 +17,7 @@ public class CosmosExceptionUtilsTest { @Test public void testBadRequestException() { - CosmosException cosmosException = BridgeInternal.createCosmosException(Constants.CosmosExceptionStatusCodes.BADREQUEST, "Bad Request"); + CosmosException cosmosException = BridgeInternal.createCosmosException(HttpStatus.BAD_REQUEST.value(), "Bad Request"); assertThrows(CosmosBadRequestException.class, () -> { CosmosExceptionUtils.exceptionHandler("Bad Request", cosmosException, responseDiagnosticsProcessor).block(); }); @@ -25,7 +25,7 @@ public void testBadRequestException() { @Test public void testConflictException() { - CosmosException cosmosException = BridgeInternal.createCosmosException(Constants.CosmosExceptionStatusCodes.CONFLICT, "Conflict Exception"); + CosmosException cosmosException = BridgeInternal.createCosmosException(HttpStatus.CONFLICT.value(), "Conflict Exception"); assertThrows(CosmosConflictException.class, () -> { CosmosExceptionUtils.exceptionHandler("Conflict", cosmosException, responseDiagnosticsProcessor).block(); }); @@ -33,7 +33,7 @@ public void testConflictException() { @Test public void testForbiddenException() { - CosmosException cosmosException = BridgeInternal.createCosmosException(Constants.CosmosExceptionStatusCodes.FORBIDDEN, "Forbidden Exception"); + CosmosException cosmosException = BridgeInternal.createCosmosException(HttpStatus.FORBIDDEN.value(), "Forbidden Exception"); assertThrows(CosmosForbiddenException.class, () -> { CosmosExceptionUtils.exceptionHandler("Frobidden", cosmosException, responseDiagnosticsProcessor).block(); }); @@ -41,7 +41,7 @@ public void testForbiddenException() { @Test public void testGoneException() { - CosmosException cosmosException = BridgeInternal.createCosmosException(Constants.CosmosExceptionStatusCodes.GONE, "Gone Exception"); + CosmosException cosmosException = BridgeInternal.createCosmosException(HttpStatus.GONE.value(), "Gone Exception"); assertThrows(CosmosGoneException.class, () -> { CosmosExceptionUtils.exceptionHandler("Gone", cosmosException, responseDiagnosticsProcessor).block(); }); @@ -49,8 +49,8 @@ public void testGoneException() { @Test public void testInvalidPartitionException() { - CosmosException cosmosException = BridgeInternal.createCosmosException(Constants.CosmosExceptionStatusCodes.GONE, "Invalid Partition Exception"); - BridgeInternal.setSubStatusCode(cosmosException, Constants.CosmosExceptionSubStatusCodes.NAME_CACHE_IS_STALE); + CosmosException cosmosException = BridgeInternal.createCosmosException(HttpStatus.GONE.value(), "Invalid Partition Exception"); + BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.CosmosExceptionSubStatusCodes.NAME_CACHE_IS_STALE); assertThrows(CosmosInvalidPartitionException.class, () -> { CosmosExceptionUtils.exceptionHandler("Invalid Partition", cosmosException, responseDiagnosticsProcessor).block(); }); @@ -58,8 +58,8 @@ public void testInvalidPartitionException() { @Test public void testPartitionIsMigratingException() { - CosmosException cosmosException = BridgeInternal.createCosmosException(Constants.CosmosExceptionStatusCodes.GONE, "Partition is Migrating Exception"); - BridgeInternal.setSubStatusCode(cosmosException, Constants.CosmosExceptionSubStatusCodes.COMPLETING_PARTITION_MIGRATION); + CosmosException cosmosException = BridgeInternal.createCosmosException(HttpStatus.GONE.value(), "Partition is Migrating Exception"); + BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.CosmosExceptionSubStatusCodes.COMPLETING_PARTITION_MIGRATION); assertThrows(CosmosPartitionIsMigratingException.class, () -> { CosmosExceptionUtils.exceptionHandler("Partition is Migrating", cosmosException, responseDiagnosticsProcessor).block(); }); @@ -67,8 +67,8 @@ public void testPartitionIsMigratingException() { @Test public void testPartitionKeyRangeGoneException() { - CosmosException cosmosException = BridgeInternal.createCosmosException(Constants.CosmosExceptionStatusCodes.GONE, "Partition Key Range Gone Exception"); - BridgeInternal.setSubStatusCode(cosmosException, Constants.CosmosExceptionSubStatusCodes.PARTITION_KEY_RANGE_GONE); + CosmosException cosmosException = BridgeInternal.createCosmosException(HttpStatus.GONE.value(), "Partition Key Range Gone Exception"); + BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.CosmosExceptionSubStatusCodes.PARTITION_KEY_RANGE_GONE); assertThrows(CosmosPartitionKeyRangeGoneException.class, () -> { CosmosExceptionUtils.exceptionHandler("Partition Key Range Gone", cosmosException, responseDiagnosticsProcessor).block(); }); @@ -76,8 +76,8 @@ public void testPartitionKeyRangeGoneException() { @Test public void testPartitionKeyRangeIsSplittingException() { - CosmosException cosmosException = BridgeInternal.createCosmosException(Constants.CosmosExceptionStatusCodes.GONE, "Partition Key Range is Splitting Exception"); - BridgeInternal.setSubStatusCode(cosmosException, Constants.CosmosExceptionSubStatusCodes.COMPLETING_SPLIT_OR_MERGE); + CosmosException cosmosException = BridgeInternal.createCosmosException(HttpStatus.GONE.value(), "Partition Key Range is Splitting Exception"); + BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.CosmosExceptionSubStatusCodes.COMPLETING_SPLIT_OR_MERGE); assertThrows(CosmosPartitionKeyRangeIsSplittingException.class, () -> { CosmosExceptionUtils.exceptionHandler("Partition Key Range is Splitting", cosmosException, responseDiagnosticsProcessor).block(); }); @@ -85,7 +85,7 @@ public void testPartitionKeyRangeIsSplittingException() { @Test public void testInternalServerErrorException() { - CosmosException cosmosException = BridgeInternal.createCosmosException(Constants.CosmosExceptionStatusCodes.INTERNAL_SERVER_ERROR, "Internal Server Error Exception"); + CosmosException cosmosException = BridgeInternal.createCosmosException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Internal Server Error Exception"); assertThrows(CosmosInternalServerErrorException.class, () -> { CosmosExceptionUtils.exceptionHandler("Internal Server Error", cosmosException, responseDiagnosticsProcessor).block(); }); @@ -93,7 +93,7 @@ public void testInternalServerErrorException() { @Test public void testMethodNotAllowedException() { - CosmosException cosmosException = BridgeInternal.createCosmosException(Constants.CosmosExceptionStatusCodes.METHOD_NOT_ALLOWED, "Method Not Allowed Exception"); + CosmosException cosmosException = BridgeInternal.createCosmosException(HttpStatus.METHOD_NOT_ALLOWED.value(), "Method Not Allowed Exception"); assertThrows(CosmosMethodNotAllowedException.class, () -> { CosmosExceptionUtils.exceptionHandler("Method Not Allowed", cosmosException, responseDiagnosticsProcessor).block(); }); @@ -101,7 +101,7 @@ public void testMethodNotAllowedException() { @Test public void testNotFoundException() { - CosmosException cosmosException = BridgeInternal.createCosmosException(Constants.CosmosExceptionStatusCodes.NOTFOUND, "Not Found Exception"); + CosmosException cosmosException = BridgeInternal.createCosmosException(HttpStatus.NOT_FOUND.value(), "Not Found Exception"); assertThrows(CosmosNotFoundException.class, () -> { CosmosExceptionUtils.exceptionHandler("Not Found Allowed", cosmosException, responseDiagnosticsProcessor).block(); }); @@ -109,7 +109,7 @@ public void testNotFoundException() { @Test public void testRequestTimeoutException() { - CosmosException cosmosException = BridgeInternal.createCosmosException(Constants.CosmosExceptionStatusCodes.REQUEST_TIMEOUT, "Request Timeout Exception"); + CosmosException cosmosException = BridgeInternal.createCosmosException(HttpStatus.REQUEST_TIMEOUT.value(), "Request Timeout Exception"); assertThrows(CosmosRequestTimeoutException.class, () -> { CosmosExceptionUtils.exceptionHandler("Request Timeout", cosmosException, responseDiagnosticsProcessor).block(); }); @@ -117,8 +117,8 @@ public void testRequestTimeoutException() { @Test public void testOperationCancelledException() { - CosmosException cosmosException = BridgeInternal.createCosmosException(Constants.CosmosExceptionStatusCodes.REQUEST_TIMEOUT, "Request Timeout Exception"); - BridgeInternal.setSubStatusCode(cosmosException, Constants.CosmosExceptionSubStatusCodes.CLIENT_OPERATION_TIMEOUT); + CosmosException cosmosException = BridgeInternal.createCosmosException(HttpStatus.REQUEST_TIMEOUT.value(), "Request Timeout Exception"); + BridgeInternal.setSubStatusCode(cosmosException, HttpConstants.CosmosExceptionSubStatusCodes.CLIENT_OPERATION_TIMEOUT); assertThrows(CosmosOperationCancelledException.class, () -> { CosmosExceptionUtils.exceptionHandler("Operation Cancelled", cosmosException, responseDiagnosticsProcessor).block(); }); @@ -126,7 +126,7 @@ public void testOperationCancelledException() { @Test public void testPreconditionFailedException() { - CosmosException cosmosException = BridgeInternal.createCosmosException(Constants.CosmosExceptionStatusCodes.PRECONDITION_FAILED, "Precondition Failed Exception"); + CosmosException cosmosException = BridgeInternal.createCosmosException(HttpStatus.PRECONDITION_FAILED.value(), "Precondition Failed Exception"); assertThrows(CosmosPreconditionFailedException.class, () -> { CosmosExceptionUtils.exceptionHandler("Precondition Failed", cosmosException, responseDiagnosticsProcessor).block(); }); @@ -134,7 +134,7 @@ public void testPreconditionFailedException() { @Test public void testRequestEntityTooLargeException() { - CosmosException cosmosException = BridgeInternal.createCosmosException(Constants.CosmosExceptionStatusCodes.REQUEST_ENTITY_TOO_LARGE, "Request Entity Too Large Exception"); + CosmosException cosmosException = BridgeInternal.createCosmosException(HttpStatus.PAYLOAD_TOO_LARGE.value(), "Request Entity Too Large Exception"); assertThrows(CosmosRequestEntityTooLargeException.class, () -> { CosmosExceptionUtils.exceptionHandler("Request Entity Too Large", cosmosException, responseDiagnosticsProcessor).block(); }); @@ -142,7 +142,7 @@ public void testRequestEntityTooLargeException() { @Test public void testRequestRateTooLargeException() { - CosmosException cosmosException = BridgeInternal.createCosmosException(Constants.CosmosExceptionStatusCodes.TOO_MANY_REQUESTS, "Request Rate Too Large Exception"); + CosmosException cosmosException = BridgeInternal.createCosmosException(HttpStatus.TOO_MANY_REQUESTS.value(), "Request Rate Too Large Exception"); assertThrows(CosmosRequestRateTooLargeException.class, () -> { CosmosExceptionUtils.exceptionHandler("Request Rate Too Large", cosmosException, responseDiagnosticsProcessor).block(); }); @@ -150,7 +150,7 @@ public void testRequestRateTooLargeException() { @Test public void testRetryWithException() { - CosmosException cosmosException = BridgeInternal.createCosmosException(Constants.CosmosExceptionStatusCodes.RETRY_WITH, "Retry With Exception"); + CosmosException cosmosException = BridgeInternal.createCosmosException(HttpConstants.CosmosExceptionStatusCodes.RETRY_WITH, "Retry With Exception"); assertThrows(CosmosRetryWithException.class, () -> { CosmosExceptionUtils.exceptionHandler("Retry With", cosmosException, responseDiagnosticsProcessor).block(); }); @@ -158,7 +158,7 @@ public void testRetryWithException() { @Test public void testServiceUnavailableException() { - CosmosException cosmosException = BridgeInternal.createCosmosException(Constants.CosmosExceptionStatusCodes.SERVICE_UNAVAILABLE, "Service Unavailable Exception"); + CosmosException cosmosException = BridgeInternal.createCosmosException(HttpStatus.SERVICE_UNAVAILABLE.value(), "Service Unavailable Exception"); assertThrows(CosmosServiceUnavailableException.class, () -> { CosmosExceptionUtils.exceptionHandler("Service Unavailable", cosmosException, responseDiagnosticsProcessor).block(); }); @@ -166,7 +166,7 @@ public void testServiceUnavailableException() { @Test public void testUnauthorizedException() { - CosmosException cosmosException = BridgeInternal.createCosmosException(Constants.CosmosExceptionStatusCodes.UNAUTHORIZED, "Unauthorized Exception"); + CosmosException cosmosException = BridgeInternal.createCosmosException(HttpStatus.UNAUTHORIZED.value(), "Unauthorized Exception"); assertThrows(CosmosUnauthorizedException.class, () -> { CosmosExceptionUtils.exceptionHandler("Unauthorized", cosmosException, responseDiagnosticsProcessor).block(); }); diff --git a/sdk/spring/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/BasicItemRepositoryIT.java b/sdk/spring/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/BasicItemRepositoryIT.java new file mode 100644 index 000000000000..583f9f7b6a20 --- /dev/null +++ b/sdk/spring/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/BasicItemRepositoryIT.java @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.spring.data.cosmos.repository.integration; + +import com.azure.spring.data.cosmos.IntegrationTestCollectionManager; +import com.azure.spring.data.cosmos.common.ResponseDiagnosticsTestUtils; +import com.azure.spring.data.cosmos.common.TestUtils; +import com.azure.spring.data.cosmos.config.CosmosConfig; +import com.azure.spring.data.cosmos.core.CosmosTemplate; +import com.azure.spring.data.cosmos.domain.Address; +import com.azure.spring.data.cosmos.domain.BasicItem; +import com.azure.spring.data.cosmos.repository.TestRepositoryConfig; +import com.azure.spring.data.cosmos.repository.repository.BasicItemRepository; +import org.assertj.core.util.Lists; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; + +import static com.azure.spring.data.cosmos.common.TestConstants.ID_1; +import static com.azure.spring.data.cosmos.common.TestConstants.ID_2; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = TestRepositoryConfig.class) +public class BasicItemRepositoryIT { + + @ClassRule + public static final IntegrationTestCollectionManager collectionManager = new IntegrationTestCollectionManager(); + + @Autowired + BasicItemRepository repository; + + @Autowired + CosmosConfig cosmosConfig; + + @Autowired + private CosmosTemplate template; + + @Autowired + private ResponseDiagnosticsTestUtils responseDiagnosticsTestUtils; + + private static final BasicItem BASIC_ITEM_1 = new BasicItem(ID_1); + + private static final BasicItem BASIC_ITEM_2 = new BasicItem(ID_2); + + @Before + public void setUp() { + collectionManager.ensureContainersCreatedAndEmpty(template, Address.class); + repository.saveAll(Lists.newArrayList(BASIC_ITEM_1, BASIC_ITEM_2)); + } + + @Test + public void testFindAllById() { + final Iterable allById = + TestUtils.toList(this.repository.findAllById(Arrays.asList(BASIC_ITEM_1.getId(), BASIC_ITEM_2.getId()))); + Assert.assertTrue(((ArrayList) allById).size() == 2); + Iterator it = allById.iterator(); + Assert.assertEquals(BASIC_ITEM_1, it.next()); + Assert.assertEquals(BASIC_ITEM_2, it.next()); + } +} diff --git a/sdk/spring/ci.yml b/sdk/spring/ci.yml index c125c32bb5ec..43fd66dcefda 100644 --- a/sdk/spring/ci.yml +++ b/sdk/spring/ci.yml @@ -146,6 +146,10 @@ parameters: displayName: 'spring-cloud-azure-starter-keyvault-certificates' type: boolean default: true +- name: release_springcloudazurestarterkeyvaultjca + displayName: 'spring-cloud-azure-starter-keyvault-jca' + type: boolean + default: true - name: release_springcloudazurestarterkeyvaultsecrets displayName: 'spring-cloud-azure-starter-keyvault-secrets' type: boolean @@ -427,6 +431,13 @@ extends: skipPublishDocMs: true skipVerifyChangelog: true releaseInBatch: ${{ parameters.release_springcloudazurestarterkeyvaultcertificates }} + - name: spring-cloud-azure-starter-keyvault-jca + groupId: com.azure.spring + safeName: springcloudazurestarterkeyvaultjca + skipPublishDocGithubIo: true + skipPublishDocMs: true + skipVerifyChangelog: true + releaseInBatch: ${{ parameters.release_springcloudazurestarterkeyvaultjca }} - name: spring-cloud-azure-starter-keyvault-secrets groupId: com.azure.spring safeName: springcloudazurestarterkeyvaultsecrets diff --git a/sdk/spring/pipeline/ClientFromSourcePom.xml b/sdk/spring/pipeline/ClientFromSourcePom.xml index 3d9d26abf931..f1c693d1c33d 100644 --- a/sdk/spring/pipeline/ClientFromSourcePom.xml +++ b/sdk/spring/pipeline/ClientFromSourcePom.xml @@ -15,7 +15,7 @@ ../../eventhubs/azure-messaging-eventhubs-stress/pom.xml ../../eventhubs/azure-messaging-eventhubs-track2-perf/pom.xml ../../eventhubs/azure-messaging-eventhubs/pom.xml - ../../monitor/azure-monitor-opentelemetry-exporter/pom.xml + ../../monitor/azure-monitor-opentelemetry-autoconfigure/pom.xml ../../parents/azure-perf-test-parent/pom.xml ../../parents/azure-sdk-parent/pom.xml ../../servicebus/azure-messaging-servicebus-stress/pom.xml diff --git a/sdk/spring/pipeline/compatibility-tests-job.yml b/sdk/spring/pipeline/compatibility-tests-job.yml index bddd751aab1e..3b21a347f9c2 100644 --- a/sdk/spring/pipeline/compatibility-tests-job.yml +++ b/sdk/spring/pipeline/compatibility-tests-job.yml @@ -30,7 +30,7 @@ jobs: - 'sdk/servicebus' - 'sdk/eventhubs' - 'common/perf-test-core' - - 'sdk/monitor/azure-monitor-opentelemetry-exporter' + - 'sdk/monitor/azure-monitor-opentelemetry-autoconfigure' - 'sdk/parents/azure-perf-test-parent' - 'sdk/parents/azure-sdk-parent' - 'eng/code-quality-reports' diff --git a/sdk/spring/pipeline/spring-cloud-azure-supported-spring.json b/sdk/spring/pipeline/spring-cloud-azure-supported-spring.json index 10c7eb6b9031..d3b061dc4cd4 100644 --- a/sdk/spring/pipeline/spring-cloud-azure-supported-spring.json +++ b/sdk/spring/pipeline/spring-cloud-azure-supported-spring.json @@ -4,6 +4,14 @@ "releaseStatus" : "GENERAL_AVAILABILITY", "snapshot" : false, "supportStatus" : "SUPPORTED", + "spring-boot-version" : "3.4.2", + "spring-cloud-version" : "2024.0.0" + }, + { + "current" : false, + "releaseStatus" : "GENERAL_AVAILABILITY", + "snapshot" : false, + "supportStatus" : "END_OF_LIFE", "spring-boot-version" : "3.4.1", "spring-cloud-version" : "2024.0.0" }, @@ -20,6 +28,14 @@ "releaseStatus" : "GENERAL_AVAILABILITY", "snapshot" : false, "supportStatus" : "SUPPORTED", + "spring-boot-version" : "3.3.8", + "spring-cloud-version" : "2023.0.5" + }, + { + "current" : false, + "releaseStatus" : "GENERAL_AVAILABILITY", + "snapshot" : false, + "supportStatus" : "END_OF_LIFE", "spring-boot-version" : "3.3.7", "spring-cloud-version" : "2023.0.5" }, diff --git a/sdk/spring/pom.xml b/sdk/spring/pom.xml index c04281714cde..bd9835f7579f 100644 --- a/sdk/spring/pom.xml +++ b/sdk/spring/pom.xml @@ -40,6 +40,7 @@ spring-cloud-azure-starter-eventgrid spring-cloud-azure-starter-keyvault spring-cloud-azure-starter-keyvault-certificates + spring-cloud-azure-starter-keyvault-jca spring-cloud-azure-starter-keyvault-secrets spring-cloud-azure-starter-servicebus-jms spring-cloud-azure-starter-servicebus @@ -104,6 +105,7 @@ spring-cloud-azure-starter-eventgrid spring-cloud-azure-starter-keyvault spring-cloud-azure-starter-keyvault-certificates + spring-cloud-azure-starter-keyvault-jca spring-cloud-azure-starter-keyvault-secrets spring-cloud-azure-starter-servicebus-jms spring-cloud-azure-starter-servicebus diff --git a/sdk/spring/scripts/spring_boot_3.4.1_managed_external_dependencies.txt b/sdk/spring/scripts/spring_boot_3.4.1_managed_external_dependencies.txt deleted file mode 100644 index d0a742be0d9e..000000000000 --- a/sdk/spring/scripts/spring_boot_3.4.1_managed_external_dependencies.txt +++ /dev/null @@ -1,1885 +0,0 @@ -ch.qos.logback:logback-classic;1.5.12 -ch.qos.logback:logback-core;1.5.12 -co.elastic.clients:elasticsearch-java;8.15.5 -com.couchbase.client:java-client;3.7.6 -com.datastax.oss:java-driver-shaded-guava;25.1-jre-graal-sub-1 -com.datastax.oss:native-protocol;1.5.1 -com.ecwid.consul:consul-api;1.4.5 -com.fasterxml.jackson.core:jackson-annotations;2.18.2 -com.fasterxml.jackson.core:jackson-core;2.18.2 -com.fasterxml.jackson.core:jackson-databind;2.18.2 -com.fasterxml.jackson.dataformat:jackson-dataformat-avro;2.18.2 -com.fasterxml.jackson.dataformat:jackson-dataformat-cbor;2.18.2 -com.fasterxml.jackson.dataformat:jackson-dataformat-csv;2.18.2 -com.fasterxml.jackson.dataformat:jackson-dataformat-ion;2.18.2 -com.fasterxml.jackson.dataformat:jackson-dataformat-properties;2.18.2 -com.fasterxml.jackson.dataformat:jackson-dataformat-protobuf;2.18.2 -com.fasterxml.jackson.dataformat:jackson-dataformat-smile;2.18.2 -com.fasterxml.jackson.dataformat:jackson-dataformat-toml;2.18.2 -com.fasterxml.jackson.dataformat:jackson-dataformat-xml;2.18.2 -com.fasterxml.jackson.dataformat:jackson-dataformat-yaml;2.18.2 -com.fasterxml.jackson.datatype:jackson-datatype-eclipse-collections;2.18.2 -com.fasterxml.jackson.datatype:jackson-datatype-guava;2.18.2 -com.fasterxml.jackson.datatype:jackson-datatype-hibernate4;2.18.2 -com.fasterxml.jackson.datatype:jackson-datatype-hibernate5;2.18.2 -com.fasterxml.jackson.datatype:jackson-datatype-hibernate5-jakarta;2.18.2 -com.fasterxml.jackson.datatype:jackson-datatype-hibernate6;2.18.2 -com.fasterxml.jackson.datatype:jackson-datatype-hppc;2.18.2 -com.fasterxml.jackson.datatype:jackson-datatype-jakarta-jsonp;2.18.2 -com.fasterxml.jackson.datatype:jackson-datatype-jaxrs;2.18.2 -com.fasterxml.jackson.datatype:jackson-datatype-jdk8;2.18.2 -com.fasterxml.jackson.datatype:jackson-datatype-joda;2.18.2 -com.fasterxml.jackson.datatype:jackson-datatype-joda-money;2.18.2 -com.fasterxml.jackson.datatype:jackson-datatype-json-org;2.18.2 -com.fasterxml.jackson.datatype:jackson-datatype-jsr310;2.18.2 -com.fasterxml.jackson.datatype:jackson-datatype-jsr353;2.18.2 -com.fasterxml.jackson.datatype:jackson-datatype-pcollections;2.18.2 -com.fasterxml.jackson.jakarta.rs:jackson-jakarta-rs-base;2.18.2 -com.fasterxml.jackson.jakarta.rs:jackson-jakarta-rs-cbor-provider;2.18.2 -com.fasterxml.jackson.jakarta.rs:jackson-jakarta-rs-json-provider;2.18.2 -com.fasterxml.jackson.jakarta.rs:jackson-jakarta-rs-smile-provider;2.18.2 -com.fasterxml.jackson.jakarta.rs:jackson-jakarta-rs-xml-provider;2.18.2 -com.fasterxml.jackson.jakarta.rs:jackson-jakarta-rs-yaml-provider;2.18.2 -com.fasterxml.jackson.jaxrs:jackson-jaxrs-base;2.18.2 -com.fasterxml.jackson.jaxrs:jackson-jaxrs-cbor-provider;2.18.2 -com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider;2.18.2 -com.fasterxml.jackson.jaxrs:jackson-jaxrs-smile-provider;2.18.2 -com.fasterxml.jackson.jaxrs:jackson-jaxrs-xml-provider;2.18.2 -com.fasterxml.jackson.jaxrs:jackson-jaxrs-yaml-provider;2.18.2 -com.fasterxml.jackson.jr:jackson-jr-all;2.18.2 -com.fasterxml.jackson.jr:jackson-jr-annotation-support;2.18.2 -com.fasterxml.jackson.jr:jackson-jr-extension-javatime;2.18.2 -com.fasterxml.jackson.jr:jackson-jr-objects;2.18.2 -com.fasterxml.jackson.jr:jackson-jr-retrofit2;2.18.2 -com.fasterxml.jackson.jr:jackson-jr-stree;2.18.2 -com.fasterxml.jackson.module:jackson-module-afterburner;2.18.2 -com.fasterxml.jackson.module:jackson-module-android-record;2.18.2 -com.fasterxml.jackson.module:jackson-module-blackbird;2.18.2 -com.fasterxml.jackson.module:jackson-module-guice;2.18.2 -com.fasterxml.jackson.module:jackson-module-guice7;2.18.2 -com.fasterxml.jackson.module:jackson-module-jakarta-xmlbind-annotations;2.18.2 -com.fasterxml.jackson.module:jackson-module-jaxb-annotations;2.18.2 -com.fasterxml.jackson.module:jackson-module-jsonSchema;2.18.2 -com.fasterxml.jackson.module:jackson-module-jsonSchema-jakarta;2.18.2 -com.fasterxml.jackson.module:jackson-module-kotlin;2.18.2 -com.fasterxml.jackson.module:jackson-module-mrbean;2.18.2 -com.fasterxml.jackson.module:jackson-module-no-ctor-deser;2.18.2 -com.fasterxml.jackson.module:jackson-module-osgi;2.18.2 -com.fasterxml.jackson.module:jackson-module-parameter-names;2.18.2 -com.fasterxml.jackson.module:jackson-module-paranamer;2.18.2 -com.fasterxml.jackson.module:jackson-module-scala_2.11;2.18.2 -com.fasterxml.jackson.module:jackson-module-scala_2.12;2.18.2 -com.fasterxml.jackson.module:jackson-module-scala_2.13;2.18.2 -com.fasterxml.jackson.module:jackson-module-scala_3;2.18.2 -com.fasterxml.jackson:jackson-bom;2.18.2 -com.fasterxml:classmate;1.7.0 -com.github.ben-manes.caffeine:caffeine;3.1.8 -com.github.ben-manes.caffeine:guava;3.1.8 -com.github.ben-manes.caffeine:jcache;3.1.8 -com.github.ben-manes.caffeine:simulator;3.1.8 -com.github.mxab.thymeleaf.extras:thymeleaf-extras-data-attribute;2.0.1 -com.github.tomakehurst:wiremock-jre8-standalone;2.35.1 -com.google.code.gson:gson;2.11.0 -com.graphql-java:graphql-java;22.3 -com.h2database:h2;2.3.232 -com.hazelcast:hazelcast;5.5.0 -com.hazelcast:hazelcast-spring;5.5.0 -com.ibm.db2:jcc;11.5.9.0 -com.jayway.jsonpath:json-path;2.9.0 -com.jayway.jsonpath:json-path-assert;2.9.0 -com.microsoft.sqlserver:mssql-jdbc;12.8.1.jre11 -com.mysql:mysql-connector-j;9.1.0 -com.netflix.eureka:eureka-client;2.0.4 -com.netflix.eureka:eureka-client-jersey3;2.0.4 -com.netflix.eureka:eureka-core;2.0.4 -com.netflix.eureka:eureka-core-jersey3;2.0.4 -com.oracle.database.ha:ons;23.5.0.24.07 -com.oracle.database.ha:simplefan;23.5.0.24.07 -com.oracle.database.jdbc:ojdbc11;23.5.0.24.07 -com.oracle.database.jdbc:ojdbc11-production;23.5.0.24.07 -com.oracle.database.jdbc:ojdbc8;23.5.0.24.07 -com.oracle.database.jdbc:ojdbc8-production;23.5.0.24.07 -com.oracle.database.jdbc:rsi;23.5.0.24.07 -com.oracle.database.jdbc:ucp;23.5.0.24.07 -com.oracle.database.jdbc:ucp11;23.5.0.24.07 -com.oracle.database.nls:orai18n;23.5.0.24.07 -com.oracle.database.r2dbc:oracle-r2dbc;1.2.0 -com.oracle.database.security:oraclepki;23.5.0.24.07 -com.oracle.database.xml:xdb;23.5.0.24.07 -com.oracle.database.xml:xmlparserv2;23.5.0.24.07 -com.querydsl:codegen-utils;5.1.0 -com.querydsl:querydsl-apt;5.1.0 -com.querydsl:querydsl-bom;5.1.0 -com.querydsl:querydsl-codegen;5.1.0 -com.querydsl:querydsl-collections;5.1.0 -com.querydsl:querydsl-core;5.1.0 -com.querydsl:querydsl-guava;5.1.0 -com.querydsl:querydsl-hibernate-search;5.1.0 -com.querydsl:querydsl-jdo;5.1.0 -com.querydsl:querydsl-jpa;5.1.0 -com.querydsl:querydsl-jpa-codegen;5.1.0 -com.querydsl:querydsl-kotlin;5.1.0 -com.querydsl:querydsl-kotlin-codegen;5.1.0 -com.querydsl:querydsl-lucene3;5.1.0 -com.querydsl:querydsl-lucene4;5.1.0 -com.querydsl:querydsl-lucene5;5.1.0 -com.querydsl:querydsl-mongodb;5.1.0 -com.querydsl:querydsl-scala;5.1.0 -com.querydsl:querydsl-spatial;5.1.0 -com.querydsl:querydsl-sql;5.1.0 -com.querydsl:querydsl-sql-codegen;5.1.0 -com.querydsl:querydsl-sql-spatial;5.1.0 -com.querydsl:querydsl-sql-spring;5.1.0 -com.rabbitmq:amqp-client;5.22.0 -com.rabbitmq:stream-client;0.18.0 -com.redis:testcontainers-redis;2.2.2 -com.samskivert:jmustache;1.16 -com.sendgrid:sendgrid-java;4.10.3 -com.sun.istack:istack-commons-runtime;4.1.2 -com.sun.xml.bind:jaxb-core;4.0.5 -com.sun.xml.bind:jaxb-impl;4.0.5 -com.sun.xml.bind:jaxb-jxc;4.0.5 -com.sun.xml.bind:jaxb-osgi;4.0.5 -com.sun.xml.bind:jaxb-xjc;4.0.5 -com.sun.xml.fastinfoset:FastInfoset;2.1.1 -com.sun.xml.messaging.saaj:saaj-impl;3.0.4 -com.toomuchcoding.jsonassert:jsonassert;0.8.0 -com.toomuchcoding.jsonassert:jsonassert-shade;0.8.0 -com.unboundid:unboundid-ldapsdk;6.0.11 -com.zaxxer:HikariCP;5.1.0 -commons-codec:commons-codec;1.17.1 -commons-pool:commons-pool;1.6 -io.asyncer:r2dbc-mysql;1.3.0 -io.fabric8.java-generator:io.fabric8.java-generator.gradle.plugin;6.13.4 -io.fabric8.kubernetes:kubernetes-karaf;6.13.4 -io.fabric8.kubernetes:kubernetes-karaf-itests;6.13.4 -io.fabric8:certmanager-client;6.13.4 -io.fabric8:certmanager-examples;6.13.4 -io.fabric8:certmanager-model-v1;6.13.4 -io.fabric8:certmanager-model-v1alpha2;6.13.4 -io.fabric8:certmanager-model-v1alpha3;6.13.4 -io.fabric8:certmanager-model-v1beta1;6.13.4 -io.fabric8:certmanager-tests;6.13.4 -io.fabric8:chaosmesh-client;6.13.4 -io.fabric8:chaosmesh-examples;6.13.4 -io.fabric8:chaosmesh-model;6.13.4 -io.fabric8:chaosmesh-tests;6.13.4 -io.fabric8:crd-generator-api;6.13.4 -io.fabric8:crd-generator-api-v2;6.13.4 -io.fabric8:crd-generator-apt;6.13.4 -io.fabric8:crd-generator-test;6.13.4 -io.fabric8:crd-generator-test-apt;6.13.4 -io.fabric8:generator-annotations;6.13.4 -io.fabric8:istio-client;6.13.4 -io.fabric8:istio-examples;6.13.4 -io.fabric8:istio-model-v1alpha3;6.13.4 -io.fabric8:istio-model-v1beta1;6.13.4 -io.fabric8:istio-tests;6.13.4 -io.fabric8:java-generator-benchmark;6.13.4 -io.fabric8:java-generator-cli;6.13.4 -io.fabric8:java-generator-core;6.13.4 -io.fabric8:java-generator-integration-tests;6.13.4 -io.fabric8:java-generator-maven-plugin;6.13.4 -io.fabric8:knative-client;6.13.4 -io.fabric8:knative-examples;6.13.4 -io.fabric8:knative-model;6.13.4 -io.fabric8:knative-tests;6.13.4 -io.fabric8:kube-api-test;6.13.4 -io.fabric8:kube-api-test-client-inject;6.13.4 -io.fabric8:kubernetes-client;6.13.4 -io.fabric8:kubernetes-client-api;6.13.4 -io.fabric8:kubernetes-client-bom;6.13.4 -io.fabric8:kubernetes-client-init-bc-fips;6.13.4 -io.fabric8:kubernetes-examples;6.13.4 -io.fabric8:kubernetes-httpclient-jdk;6.13.4 -io.fabric8:kubernetes-httpclient-jetty;6.13.4 -io.fabric8:kubernetes-httpclient-okhttp;6.13.4 -io.fabric8:kubernetes-httpclient-tests;6.13.4 -io.fabric8:kubernetes-httpclient-vertx;6.13.4 -io.fabric8:kubernetes-junit-jupiter;6.13.4 -io.fabric8:kubernetes-junit-jupiter-autodetected;6.13.4 -io.fabric8:kubernetes-log4j;6.13.4 -io.fabric8:kubernetes-model;6.13.4 -io.fabric8:kubernetes-model-admissionregistration;6.13.4 -io.fabric8:kubernetes-model-apiextensions;6.13.4 -io.fabric8:kubernetes-model-apps;6.13.4 -io.fabric8:kubernetes-model-autoscaling;6.13.4 -io.fabric8:kubernetes-model-batch;6.13.4 -io.fabric8:kubernetes-model-certificates;6.13.4 -io.fabric8:kubernetes-model-common;6.13.4 -io.fabric8:kubernetes-model-coordination;6.13.4 -io.fabric8:kubernetes-model-core;6.13.4 -io.fabric8:kubernetes-model-discovery;6.13.4 -io.fabric8:kubernetes-model-events;6.13.4 -io.fabric8:kubernetes-model-extensions;6.13.4 -io.fabric8:kubernetes-model-flowcontrol;6.13.4 -io.fabric8:kubernetes-model-gatewayapi;6.13.4 -io.fabric8:kubernetes-model-jsonschema2pojo;6.13.4 -io.fabric8:kubernetes-model-kustomize;6.13.4 -io.fabric8:kubernetes-model-metrics;6.13.4 -io.fabric8:kubernetes-model-networking;6.13.4 -io.fabric8:kubernetes-model-node;6.13.4 -io.fabric8:kubernetes-model-policy;6.13.4 -io.fabric8:kubernetes-model-rbac;6.13.4 -io.fabric8:kubernetes-model-resource;6.13.4 -io.fabric8:kubernetes-model-scheduling;6.13.4 -io.fabric8:kubernetes-model-storageclass;6.13.4 -io.fabric8:kubernetes-openshift-uberjar;6.13.4 -io.fabric8:kubernetes-server-mock;6.13.4 -io.fabric8:kubernetes-test;6.13.4 -io.fabric8:mockwebserver;6.13.4 -io.fabric8:open-cluster-management-agent-model;6.13.4 -io.fabric8:open-cluster-management-apps-model;6.13.4 -io.fabric8:open-cluster-management-client;6.13.4 -io.fabric8:open-cluster-management-cluster-model;6.13.4 -io.fabric8:open-cluster-management-discovery-model;6.13.4 -io.fabric8:open-cluster-management-observability-model;6.13.4 -io.fabric8:open-cluster-management-operator-model;6.13.4 -io.fabric8:open-cluster-management-placementruleapps-model;6.13.4 -io.fabric8:open-cluster-management-policy-model;6.13.4 -io.fabric8:open-cluster-management-search-model;6.13.4 -io.fabric8:open-cluster-management-tests;6.13.4 -io.fabric8:open-virtual-networking-client;6.13.4 -io.fabric8:open-virtual-networking-model-v1;6.13.4 -io.fabric8:open-virtual-networking-tests;6.13.4 -io.fabric8:openclustermanagement-examples;6.13.4 -io.fabric8:openshift-client;6.13.4 -io.fabric8:openshift-client-api;6.13.4 -io.fabric8:openshift-model;6.13.4 -io.fabric8:openshift-model-clusterautoscaling;6.13.4 -io.fabric8:openshift-model-config;6.13.4 -io.fabric8:openshift-model-console;6.13.4 -io.fabric8:openshift-model-hive;6.13.4 -io.fabric8:openshift-model-installer;6.13.4 -io.fabric8:openshift-model-machine;6.13.4 -io.fabric8:openshift-model-machineconfig;6.13.4 -io.fabric8:openshift-model-miscellaneous;6.13.4 -io.fabric8:openshift-model-monitoring;6.13.4 -io.fabric8:openshift-model-operator;6.13.4 -io.fabric8:openshift-model-operatorhub;6.13.4 -io.fabric8:openshift-model-storageversionmigrator;6.13.4 -io.fabric8:openshift-model-tuned;6.13.4 -io.fabric8:openshift-model-whereabouts;6.13.4 -io.fabric8:openshift-server-mock;6.13.4 -io.fabric8:service-catalog-examples;6.13.4 -io.fabric8:servicecatalog-client;6.13.4 -io.fabric8:servicecatalog-model;6.13.4 -io.fabric8:servicecatalog-tests;6.13.4 -io.fabric8:tekton-client;6.13.4 -io.fabric8:tekton-examples;6.13.4 -io.fabric8:tekton-model-triggers-v1alpha1;6.13.4 -io.fabric8:tekton-model-triggers-v1beta1;6.13.4 -io.fabric8:tekton-model-v1;6.13.4 -io.fabric8:tekton-model-v1alpha1;6.13.4 -io.fabric8:tekton-model-v1beta1;6.13.4 -io.fabric8:tekton-tests;6.13.4 -io.fabric8:verticalpodautoscaler-client;6.13.4 -io.fabric8:verticalpodautoscaler-examples;6.13.4 -io.fabric8:verticalpodautoscaler-model-v1;6.13.4 -io.fabric8:verticalpodautoscaler-tests;6.13.4 -io.fabric8:volcano-client;6.13.4 -io.fabric8:volcano-examples;6.13.4 -io.fabric8:volcano-model-v1beta1;6.13.4 -io.fabric8:volcano-tests;6.13.4 -io.fabric8:volumesnapshot-client;6.13.4 -io.fabric8:volumesnapshot-examples;6.13.4 -io.fabric8:volumesnapshot-model;6.13.4 -io.fabric8:volumesnapshot-tests;6.13.4 -io.github.git-commit-id:git-commit-id-maven-plugin;9.0.1 -io.github.openfeign:feign-annotation-error-decoder;13.5 -io.github.openfeign:feign-bom;13.5 -io.github.openfeign:feign-core;13.5 -io.github.openfeign:feign-dropwizard-metrics4;13.5 -io.github.openfeign:feign-dropwizard-metrics5;13.5 -io.github.openfeign:feign-fastjson2;13.5 -io.github.openfeign:feign-form;13.5 -io.github.openfeign:feign-form-spring;13.5 -io.github.openfeign:feign-googlehttpclient;13.5 -io.github.openfeign:feign-gson;13.5 -io.github.openfeign:feign-hc5;13.5 -io.github.openfeign:feign-httpclient;13.5 -io.github.openfeign:feign-hystrix;13.5 -io.github.openfeign:feign-jackson;13.5 -io.github.openfeign:feign-jackson-jaxb;13.5 -io.github.openfeign:feign-jackson-jr;13.5 -io.github.openfeign:feign-jakarta;13.5 -io.github.openfeign:feign-java11;13.5 -io.github.openfeign:feign-jaxb;13.5 -io.github.openfeign:feign-jaxb-jakarta;13.5 -io.github.openfeign:feign-jaxrs;13.5 -io.github.openfeign:feign-jaxrs2;13.5 -io.github.openfeign:feign-jaxrs3;13.5 -io.github.openfeign:feign-jaxrs4;13.5 -io.github.openfeign:feign-json;13.5 -io.github.openfeign:feign-kotlin;13.5 -io.github.openfeign:feign-micrometer;13.5 -io.github.openfeign:feign-mock;13.5 -io.github.openfeign:feign-moshi;13.5 -io.github.openfeign:feign-okhttp;13.5 -io.github.openfeign:feign-reactive-wrappers;13.5 -io.github.openfeign:feign-ribbon;13.5 -io.github.openfeign:feign-sax;13.5 -io.github.openfeign:feign-slf4j;13.5 -io.github.openfeign:feign-soap;13.5 -io.github.openfeign:feign-soap-jakarta;13.5 -io.github.openfeign:feign-spring;13.5 -io.github.resilience4j:resilience4j-all;2.2.0 -io.github.resilience4j:resilience4j-annotations;2.2.0 -io.github.resilience4j:resilience4j-bom;2.2.0 -io.github.resilience4j:resilience4j-bulkhead;2.2.0 -io.github.resilience4j:resilience4j-cache;2.2.0 -io.github.resilience4j:resilience4j-circuitbreaker;2.2.0 -io.github.resilience4j:resilience4j-circularbuffer;2.2.0 -io.github.resilience4j:resilience4j-consumer;2.2.0 -io.github.resilience4j:resilience4j-core;2.2.0 -io.github.resilience4j:resilience4j-feign;2.2.0 -io.github.resilience4j:resilience4j-kotlin;2.2.0 -io.github.resilience4j:resilience4j-metrics;2.2.0 -io.github.resilience4j:resilience4j-micrometer;2.2.0 -io.github.resilience4j:resilience4j-ratelimiter;2.2.0 -io.github.resilience4j:resilience4j-reactor;2.2.0 -io.github.resilience4j:resilience4j-retry;2.2.0 -io.github.resilience4j:resilience4j-rxjava2;2.2.0 -io.github.resilience4j:resilience4j-rxjava3;2.2.0 -io.github.resilience4j:resilience4j-spring;2.2.0 -io.github.resilience4j:resilience4j-spring-boot2;2.2.0 -io.github.resilience4j:resilience4j-spring-boot3;2.2.0 -io.github.resilience4j:resilience4j-spring-cloud2;2.2.0 -io.github.resilience4j:resilience4j-spring6;2.2.0 -io.github.resilience4j:resilience4j-timelimiter;2.2.0 -io.github.resilience4j:resilience4j-vavr;2.2.0 -io.kubernetes:client-java;19.0.1 -io.kubernetes:client-java-extended;19.0.1 -io.kubernetes:client-java-spring-integration;19.0.1 -io.lettuce:lettuce-core;6.4.1.RELEASE -io.micrometer:context-propagation;1.1.2 -io.micrometer:docs;1.4.1 -io.micrometer:micrometer-bom;1.14.2 -io.micrometer:micrometer-commons;1.14.2 -io.micrometer:micrometer-core;1.14.2 -io.micrometer:micrometer-jakarta9;1.14.2 -io.micrometer:micrometer-java11;1.14.2 -io.micrometer:micrometer-java21;1.14.2 -io.micrometer:micrometer-jetty11;1.14.2 -io.micrometer:micrometer-jetty12;1.14.2 -io.micrometer:micrometer-observation;1.14.2 -io.micrometer:micrometer-observation-test;1.14.2 -io.micrometer:micrometer-registry-appoptics;1.14.2 -io.micrometer:micrometer-registry-atlas;1.14.2 -io.micrometer:micrometer-registry-azure-monitor;1.14.2 -io.micrometer:micrometer-registry-cloudwatch2;1.14.2 -io.micrometer:micrometer-registry-datadog;1.14.2 -io.micrometer:micrometer-registry-dynatrace;1.14.2 -io.micrometer:micrometer-registry-elastic;1.14.2 -io.micrometer:micrometer-registry-ganglia;1.14.2 -io.micrometer:micrometer-registry-graphite;1.14.2 -io.micrometer:micrometer-registry-health;1.14.2 -io.micrometer:micrometer-registry-humio;1.14.2 -io.micrometer:micrometer-registry-influx;1.14.2 -io.micrometer:micrometer-registry-jmx;1.14.2 -io.micrometer:micrometer-registry-kairos;1.14.2 -io.micrometer:micrometer-registry-new-relic;1.14.2 -io.micrometer:micrometer-registry-opentsdb;1.14.2 -io.micrometer:micrometer-registry-otlp;1.14.2 -io.micrometer:micrometer-registry-prometheus;1.14.2 -io.micrometer:micrometer-registry-prometheus-simpleclient;1.14.2 -io.micrometer:micrometer-registry-signalfx;1.14.2 -io.micrometer:micrometer-registry-stackdriver;1.14.2 -io.micrometer:micrometer-registry-statsd;1.14.2 -io.micrometer:micrometer-registry-wavefront;1.14.2 -io.micrometer:micrometer-test;1.14.2 -io.micrometer:micrometer-tracing;1.4.1 -io.micrometer:micrometer-tracing-bom;1.4.1 -io.micrometer:micrometer-tracing-bridge-brave;1.4.1 -io.micrometer:micrometer-tracing-bridge-otel;1.4.1 -io.micrometer:micrometer-tracing-integration-test;1.4.1 -io.micrometer:micrometer-tracing-reporter-wavefront;1.4.1 -io.micrometer:micrometer-tracing-test;1.4.1 -io.netty:netty-all;4.1.116.Final -io.netty:netty-bom;4.1.116.Final -io.netty:netty-buffer;4.1.116.Final -io.netty:netty-codec;4.1.116.Final -io.netty:netty-codec-dns;4.1.116.Final -io.netty:netty-codec-haproxy;4.1.116.Final -io.netty:netty-codec-http;4.1.116.Final -io.netty:netty-codec-http2;4.1.116.Final -io.netty:netty-codec-memcache;4.1.116.Final -io.netty:netty-codec-mqtt;4.1.116.Final -io.netty:netty-codec-redis;4.1.116.Final -io.netty:netty-codec-smtp;4.1.116.Final -io.netty:netty-codec-socks;4.1.116.Final -io.netty:netty-codec-stomp;4.1.116.Final -io.netty:netty-codec-xml;4.1.116.Final -io.netty:netty-common;4.1.116.Final -io.netty:netty-dev-tools;4.1.116.Final -io.netty:netty-example;4.1.116.Final -io.netty:netty-handler;4.1.116.Final -io.netty:netty-handler-proxy;4.1.116.Final -io.netty:netty-handler-ssl-ocsp;4.1.116.Final -io.netty:netty-resolver;4.1.116.Final -io.netty:netty-resolver-dns;4.1.116.Final -io.netty:netty-resolver-dns-classes-macos;4.1.116.Final -io.netty:netty-resolver-dns-native-macos;4.1.116.Final -io.netty:netty-tcnative;2.0.69.Final -io.netty:netty-tcnative-boringssl-static;2.0.69.Final -io.netty:netty-tcnative-classes;2.0.69.Final -io.netty:netty-transport;4.1.116.Final -io.netty:netty-transport-classes-epoll;4.1.116.Final -io.netty:netty-transport-classes-kqueue;4.1.116.Final -io.netty:netty-transport-native-epoll;4.1.116.Final -io.netty:netty-transport-native-kqueue;4.1.116.Final -io.netty:netty-transport-native-unix-common;4.1.116.Final -io.netty:netty-transport-rxtx;4.1.116.Final -io.netty:netty-transport-sctp;4.1.116.Final -io.netty:netty-transport-udt;4.1.116.Final -io.opentelemetry:opentelemetry-api;1.43.0 -io.opentelemetry:opentelemetry-bom;1.43.0 -io.opentelemetry:opentelemetry-context;1.43.0 -io.opentelemetry:opentelemetry-exporter-common;1.43.0 -io.opentelemetry:opentelemetry-exporter-logging;1.43.0 -io.opentelemetry:opentelemetry-exporter-logging-otlp;1.43.0 -io.opentelemetry:opentelemetry-exporter-otlp;1.43.0 -io.opentelemetry:opentelemetry-exporter-otlp-common;1.43.0 -io.opentelemetry:opentelemetry-exporter-sender-grpc-managed-channel;1.43.0 -io.opentelemetry:opentelemetry-exporter-sender-jdk;1.43.0 -io.opentelemetry:opentelemetry-exporter-sender-okhttp;1.43.0 -io.opentelemetry:opentelemetry-exporter-zipkin;1.43.0 -io.opentelemetry:opentelemetry-extension-kotlin;1.43.0 -io.opentelemetry:opentelemetry-extension-trace-propagators;1.43.0 -io.opentelemetry:opentelemetry-opentracing-shim;1.43.0 -io.opentelemetry:opentelemetry-sdk;1.43.0 -io.opentelemetry:opentelemetry-sdk-common;1.43.0 -io.opentelemetry:opentelemetry-sdk-extension-autoconfigure;1.43.0 -io.opentelemetry:opentelemetry-sdk-extension-autoconfigure-spi;1.43.0 -io.opentelemetry:opentelemetry-sdk-extension-jaeger-remote-sampler;1.43.0 -io.opentelemetry:opentelemetry-sdk-logs;1.43.0 -io.opentelemetry:opentelemetry-sdk-metrics;1.43.0 -io.opentelemetry:opentelemetry-sdk-testing;1.43.0 -io.opentelemetry:opentelemetry-sdk-trace;1.43.0 -io.projectreactor.addons:reactor-adapter;3.5.2 -io.projectreactor.addons:reactor-extra;3.5.2 -io.projectreactor.addons:reactor-pool;1.1.0 -io.projectreactor.addons:reactor-pool-micrometer;0.2.0 -io.projectreactor.kafka:reactor-kafka;1.3.23 -io.projectreactor.kotlin:reactor-kotlin-extensions;1.2.3 -io.projectreactor.netty:reactor-netty;1.2.1 -io.projectreactor.netty:reactor-netty-core;1.2.1 -io.projectreactor.netty:reactor-netty-http;1.2.1 -io.projectreactor.netty:reactor-netty-http-brave;1.2.1 -io.projectreactor:reactor-bom;2024.0.1 -io.projectreactor:reactor-core;3.7.1 -io.projectreactor:reactor-core-micrometer;1.2.1 -io.projectreactor:reactor-test;3.7.1 -io.projectreactor:reactor-tools;3.7.1 -io.prometheus:prometheus-metrics-bom;1.3.5 -io.prometheus:prometheus-metrics-config;1.3.5 -io.prometheus:prometheus-metrics-core;1.3.5 -io.prometheus:prometheus-metrics-exporter-common;1.3.5 -io.prometheus:prometheus-metrics-exporter-httpserver;1.3.5 -io.prometheus:prometheus-metrics-exporter-opentelemetry;1.3.5 -io.prometheus:prometheus-metrics-exporter-pushgateway;1.3.5 -io.prometheus:prometheus-metrics-exporter-servlet-jakarta;1.3.5 -io.prometheus:prometheus-metrics-exporter-servlet-javax;1.3.5 -io.prometheus:prometheus-metrics-exposition-formats;1.3.5 -io.prometheus:prometheus-metrics-instrumentation-caffeine;1.3.5 -io.prometheus:prometheus-metrics-instrumentation-dropwizard5;1.3.5 -io.prometheus:prometheus-metrics-instrumentation-guava;1.3.5 -io.prometheus:prometheus-metrics-instrumentation-jvm;1.3.5 -io.prometheus:prometheus-metrics-model;1.3.5 -io.prometheus:prometheus-metrics-simpleclient-bridge;1.3.5 -io.prometheus:prometheus-metrics-tracer;1.3.5 -io.prometheus:prometheus-metrics-tracer-common;1.3.5 -io.prometheus:prometheus-metrics-tracer-initializer;1.3.5 -io.prometheus:prometheus-metrics-tracer-otel;1.3.5 -io.prometheus:prometheus-metrics-tracer-otel-agent;1.3.5 -io.prometheus:simpleclient;0.16.0 -io.prometheus:simpleclient_bom;0.16.0 -io.prometheus:simpleclient_caffeine;0.16.0 -io.prometheus:simpleclient_common;0.16.0 -io.prometheus:simpleclient_dropwizard;0.16.0 -io.prometheus:simpleclient_graphite_bridge;0.16.0 -io.prometheus:simpleclient_guava;0.16.0 -io.prometheus:simpleclient_hibernate;0.16.0 -io.prometheus:simpleclient_hotspot;0.16.0 -io.prometheus:simpleclient_httpserver;0.16.0 -io.prometheus:simpleclient_jetty;0.16.0 -io.prometheus:simpleclient_jetty_jdk8;0.16.0 -io.prometheus:simpleclient_log4j;0.16.0 -io.prometheus:simpleclient_log4j2;0.16.0 -io.prometheus:simpleclient_logback;0.16.0 -io.prometheus:simpleclient_pushgateway;0.16.0 -io.prometheus:simpleclient_servlet;0.16.0 -io.prometheus:simpleclient_servlet_jakarta;0.16.0 -io.prometheus:simpleclient_spring_boot;0.16.0 -io.prometheus:simpleclient_spring_web;0.16.0 -io.prometheus:simpleclient_tracer_common;0.16.0 -io.prometheus:simpleclient_tracer_otel;0.16.0 -io.prometheus:simpleclient_tracer_otel_agent;0.16.0 -io.prometheus:simpleclient_vertx;0.16.0 -io.r2dbc:r2dbc-h2;1.0.0.RELEASE -io.r2dbc:r2dbc-mssql;1.0.2.RELEASE -io.r2dbc:r2dbc-pool;1.0.2.RELEASE -io.r2dbc:r2dbc-proxy;1.1.5.RELEASE -io.r2dbc:r2dbc-spi;1.0.0.RELEASE -io.reactivex.rxjava3:rxjava;3.1.10 -io.rest-assured:json-path;5.5.0 -io.rest-assured:json-schema-validator;5.5.0 -io.rest-assured:kotlin-extensions;5.5.0 -io.rest-assured:rest-assured;5.5.0 -io.rest-assured:rest-assured-all;5.5.0 -io.rest-assured:rest-assured-bom;5.5.0 -io.rest-assured:rest-assured-common;5.5.0 -io.rest-assured:scala-extensions;5.5.0 -io.rest-assured:scala-support;5.5.0 -io.rest-assured:spring-commons;5.5.0 -io.rest-assured:spring-mock-mvc;5.5.0 -io.rest-assured:spring-mock-mvc-kotlin-extensions;5.5.0 -io.rest-assured:spring-web-test-client;5.5.0 -io.rest-assured:spring-web-test-client-kotlin-extensions;5.5.0 -io.rest-assured:xml-path;5.5.0 -io.rsocket:rsocket-bom;1.1.3 -io.rsocket:rsocket-core;1.1.3 -io.rsocket:rsocket-load-balancer;1.1.3 -io.rsocket:rsocket-micrometer;1.1.3 -io.rsocket:rsocket-test;1.1.3 -io.rsocket:rsocket-transport-local;1.1.3 -io.rsocket:rsocket-transport-netty;1.1.3 -io.spring.gradle:dependency-management-plugin;1.1.7 -io.undertow:undertow-core;2.3.18.Final -io.undertow:undertow-servlet;2.3.18.Final -io.undertow:undertow-websockets-jsr;2.3.18.Final -io.zipkin.brave:brave;6.0.3 -io.zipkin.brave:brave-bom;6.0.3 -io.zipkin.brave:brave-context-jfr;6.0.3 -io.zipkin.brave:brave-context-log4j12;6.0.3 -io.zipkin.brave:brave-context-log4j2;6.0.3 -io.zipkin.brave:brave-context-slf4j;6.0.3 -io.zipkin.brave:brave-instrumentation-benchmarks;6.0.3 -io.zipkin.brave:brave-instrumentation-dubbo;6.0.3 -io.zipkin.brave:brave-instrumentation-grpc;6.0.3 -io.zipkin.brave:brave-instrumentation-http;6.0.3 -io.zipkin.brave:brave-instrumentation-http-tests;6.0.3 -io.zipkin.brave:brave-instrumentation-http-tests-jakarta;6.0.3 -io.zipkin.brave:brave-instrumentation-httpasyncclient;6.0.3 -io.zipkin.brave:brave-instrumentation-httpclient;6.0.3 -io.zipkin.brave:brave-instrumentation-httpclient5;6.0.3 -io.zipkin.brave:brave-instrumentation-jakarta-jms;6.0.3 -io.zipkin.brave:brave-instrumentation-jaxrs2;6.0.3 -io.zipkin.brave:brave-instrumentation-jersey-server;6.0.3 -io.zipkin.brave:brave-instrumentation-jms;6.0.3 -io.zipkin.brave:brave-instrumentation-jms-jakarta;6.0.3 -io.zipkin.brave:brave-instrumentation-kafka-clients;6.0.3 -io.zipkin.brave:brave-instrumentation-kafka-streams;6.0.3 -io.zipkin.brave:brave-instrumentation-messaging;6.0.3 -io.zipkin.brave:brave-instrumentation-mongodb;6.0.3 -io.zipkin.brave:brave-instrumentation-mysql;6.0.3 -io.zipkin.brave:brave-instrumentation-mysql6;6.0.3 -io.zipkin.brave:brave-instrumentation-mysql8;6.0.3 -io.zipkin.brave:brave-instrumentation-netty-codec-http;6.0.3 -io.zipkin.brave:brave-instrumentation-okhttp3;6.0.3 -io.zipkin.brave:brave-instrumentation-rpc;6.0.3 -io.zipkin.brave:brave-instrumentation-servlet;6.0.3 -io.zipkin.brave:brave-instrumentation-servlet-jakarta;6.0.3 -io.zipkin.brave:brave-instrumentation-spring-rabbit;6.0.3 -io.zipkin.brave:brave-instrumentation-spring-web;6.0.3 -io.zipkin.brave:brave-instrumentation-spring-webmvc;6.0.3 -io.zipkin.brave:brave-instrumentation-vertx-web;6.0.3 -io.zipkin.brave:brave-spring-beans;6.0.3 -io.zipkin.brave:brave-tests;6.0.3 -io.zipkin.reporter2:zipkin-reporter;3.4.3 -io.zipkin.reporter2:zipkin-reporter-bom;3.4.3 -io.zipkin.reporter2:zipkin-reporter-brave;3.4.3 -io.zipkin.reporter2:zipkin-reporter-metrics-micrometer;3.4.3 -io.zipkin.reporter2:zipkin-reporter-spring-beans;3.4.3 -io.zipkin.reporter2:zipkin-sender-activemq-client;3.4.3 -io.zipkin.reporter2:zipkin-sender-amqp-client;3.4.3 -io.zipkin.reporter2:zipkin-sender-kafka;3.4.3 -io.zipkin.reporter2:zipkin-sender-libthrift;3.4.3 -io.zipkin.reporter2:zipkin-sender-okhttp3;3.4.3 -io.zipkin.reporter2:zipkin-sender-urlconnection;3.4.3 -io.zipkin.zipkin2:zipkin;2.27.1 -jakarta.activation:jakarta.activation-api;2.1.3 -jakarta.annotation:jakarta.annotation-api;2.1.1 -jakarta.inject:jakarta.inject-api;2.0.1 -jakarta.jms:jakarta.jms-api;3.1.0 -jakarta.json.bind:jakarta.json.bind-api;3.0.1 -jakarta.json:jakarta.json-api;2.1.3 -jakarta.mail:jakarta.mail-api;2.1.3 -jakarta.management.j2ee:jakarta.management.j2ee-api;1.1.4 -jakarta.persistence:jakarta.persistence-api;3.1.0 -jakarta.servlet.jsp.jstl:jakarta.servlet.jsp.jstl-api;3.0.2 -jakarta.servlet:jakarta.servlet-api;6.0.0 -jakarta.transaction:jakarta.transaction-api;2.0.1 -jakarta.validation:jakarta.validation-api;3.0.2 -jakarta.websocket:jakarta.websocket-api;2.1.1 -jakarta.websocket:jakarta.websocket-client-api;2.1.1 -jakarta.ws.rs:jakarta.ws.rs-api;3.1.0 -jakarta.xml.bind:jakarta.xml.bind-api;4.0.2 -jakarta.xml.soap:jakarta.xml.soap-api;3.0.2 -jakarta.xml.ws:jakarta.xml.ws-api;4.0.2 -javax.cache:cache-api;1.1.1 -javax.money:money-api;1.1 -jaxen:jaxen;2.0.0 -junit:junit;4.13.2 -net.bytebuddy:byte-buddy;1.15.11 -net.bytebuddy:byte-buddy-agent;1.15.11 -net.minidev:json-smart;2.5.1 -net.sourceforge.jtds:jtds;1.3.1 -net.sourceforge.nekohtml:nekohtml;1.9.22 -nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect;3.3.0 -org.apache.activemq:activemq-all;6.1.4 -org.apache.activemq:activemq-amqp;6.1.4 -org.apache.activemq:activemq-blueprint;6.1.4 -org.apache.activemq:activemq-bom;6.1.4 -org.apache.activemq:activemq-branding;2.37.0 -org.apache.activemq:activemq-broker;6.1.4 -org.apache.activemq:activemq-client;6.1.4 -org.apache.activemq:activemq-console;6.1.4 -org.apache.activemq:activemq-http;6.1.4 -org.apache.activemq:activemq-jaas;6.1.4 -org.apache.activemq:activemq-jdbc-store;6.1.4 -org.apache.activemq:activemq-jms-pool;6.1.4 -org.apache.activemq:activemq-kahadb-store;6.1.4 -org.apache.activemq:activemq-karaf;6.1.4 -org.apache.activemq:activemq-log4j-appender;6.1.4 -org.apache.activemq:activemq-mqtt;6.1.4 -org.apache.activemq:activemq-openwire-generator;6.1.4 -org.apache.activemq:activemq-openwire-legacy;6.1.4 -org.apache.activemq:activemq-osgi;6.1.4 -org.apache.activemq:activemq-pool;6.1.4 -org.apache.activemq:activemq-ra;6.1.4 -org.apache.activemq:activemq-rar;6.1.4 -org.apache.activemq:activemq-run;6.1.4 -org.apache.activemq:activemq-runtime-config;6.1.4 -org.apache.activemq:activemq-shiro;6.1.4 -org.apache.activemq:activemq-spring;6.1.4 -org.apache.activemq:activemq-stomp;6.1.4 -org.apache.activemq:activemq-web;6.1.4 -org.apache.activemq:activemq-web-console;6.1.4 -org.apache.activemq:activemq-web-demo;6.1.4 -org.apache.activemq:artemis-amqp-protocol;2.37.0 -org.apache.activemq:artemis-bom;2.37.0 -org.apache.activemq:artemis-boot;2.37.0 -org.apache.activemq:artemis-cdi-client;2.37.0 -org.apache.activemq:artemis-cli;2.37.0 -org.apache.activemq:artemis-commons;2.37.0 -org.apache.activemq:artemis-console;2.37.0 -org.apache.activemq:artemis-core-client;2.37.0 -org.apache.activemq:artemis-core-client-all;2.37.0 -org.apache.activemq:artemis-core-client-osgi;2.37.0 -org.apache.activemq:artemis-dto;2.37.0 -org.apache.activemq:artemis-features;2.37.0 -org.apache.activemq:artemis-hornetq-protocol;2.37.0 -org.apache.activemq:artemis-hqclient-protocol;2.37.0 -org.apache.activemq:artemis-jakarta-client;2.37.0 -org.apache.activemq:artemis-jakarta-client-all;2.37.0 -org.apache.activemq:artemis-jakarta-openwire-protocol;2.37.0 -org.apache.activemq:artemis-jakarta-ra;2.37.0 -org.apache.activemq:artemis-jakarta-server;2.37.0 -org.apache.activemq:artemis-jakarta-service-extensions;2.37.0 -org.apache.activemq:artemis-jdbc-store;2.37.0 -org.apache.activemq:artemis-jms-client;2.37.0 -org.apache.activemq:artemis-jms-client-all;2.37.0 -org.apache.activemq:artemis-jms-client-osgi;2.37.0 -org.apache.activemq:artemis-jms-server;2.37.0 -org.apache.activemq:artemis-journal;2.37.0 -org.apache.activemq:artemis-lockmanager-api;2.37.0 -org.apache.activemq:artemis-lockmanager-ri;2.37.0 -org.apache.activemq:artemis-mqtt-protocol;2.37.0 -org.apache.activemq:artemis-openwire-protocol;2.37.0 -org.apache.activemq:artemis-plugin;2.37.0 -org.apache.activemq:artemis-ra;2.37.0 -org.apache.activemq:artemis-selector;2.37.0 -org.apache.activemq:artemis-server;2.37.0 -org.apache.activemq:artemis-server-osgi;2.37.0 -org.apache.activemq:artemis-service-extensions;2.37.0 -org.apache.activemq:artemis-stomp-protocol;2.37.0 -org.apache.activemq:artemis-web;2.37.0 -org.apache.activemq:artemis-website;2.37.0 -org.apache.cassandra:java-driver-bom;4.18.1 -org.apache.cassandra:java-driver-core;4.18.1 -org.apache.cassandra:java-driver-core-shaded;4.18.1 -org.apache.cassandra:java-driver-mapper-processor;4.18.1 -org.apache.cassandra:java-driver-mapper-runtime;4.18.1 -org.apache.cassandra:java-driver-metrics-micrometer;4.18.1 -org.apache.cassandra:java-driver-metrics-microprofile;4.18.1 -org.apache.cassandra:java-driver-query-builder;4.18.1 -org.apache.cassandra:java-driver-test-infra;4.18.1 -org.apache.commons:commons-dbcp2;2.12.0 -org.apache.commons:commons-lang3;3.17.0 -org.apache.commons:commons-pool2;2.12.0 -org.apache.curator:curator-framework;5.7.1 -org.apache.curator:curator-recipes;5.7.1 -org.apache.curator:curator-test;5.7.1 -org.apache.curator:curator-x-discovery;5.7.1 -org.apache.derby:derby;10.16.1.1 -org.apache.derby:derbyclient;10.16.1.1 -org.apache.derby:derbynet;10.16.1.1 -org.apache.derby:derbyoptionaltools;10.16.1.1 -org.apache.derby:derbyshared;10.16.1.1 -org.apache.derby:derbytools;10.16.1.1 -org.apache.groovy:groovy;4.0.24 -org.apache.groovy:groovy-ant;4.0.24 -org.apache.groovy:groovy-astbuilder;4.0.24 -org.apache.groovy:groovy-bom;4.0.24 -org.apache.groovy:groovy-cli-commons;4.0.24 -org.apache.groovy:groovy-cli-picocli;4.0.24 -org.apache.groovy:groovy-console;4.0.24 -org.apache.groovy:groovy-contracts;4.0.24 -org.apache.groovy:groovy-datetime;4.0.24 -org.apache.groovy:groovy-dateutil;4.0.24 -org.apache.groovy:groovy-docgenerator;4.0.24 -org.apache.groovy:groovy-ginq;4.0.24 -org.apache.groovy:groovy-groovydoc;4.0.24 -org.apache.groovy:groovy-groovysh;4.0.24 -org.apache.groovy:groovy-jmx;4.0.24 -org.apache.groovy:groovy-json;4.0.24 -org.apache.groovy:groovy-jsr223;4.0.24 -org.apache.groovy:groovy-macro;4.0.24 -org.apache.groovy:groovy-macro-library;4.0.24 -org.apache.groovy:groovy-nio;4.0.24 -org.apache.groovy:groovy-servlet;4.0.24 -org.apache.groovy:groovy-sql;4.0.24 -org.apache.groovy:groovy-swing;4.0.24 -org.apache.groovy:groovy-templates;4.0.24 -org.apache.groovy:groovy-test;4.0.24 -org.apache.groovy:groovy-test-junit5;4.0.24 -org.apache.groovy:groovy-testng;4.0.24 -org.apache.groovy:groovy-toml;4.0.24 -org.apache.groovy:groovy-typecheckers;4.0.24 -org.apache.groovy:groovy-xml;4.0.24 -org.apache.groovy:groovy-yaml;4.0.24 -org.apache.httpcomponents.client5:httpclient5;5.4.1 -org.apache.httpcomponents.client5:httpclient5-cache;5.4.1 -org.apache.httpcomponents.client5:httpclient5-fluent;5.4.1 -org.apache.httpcomponents.core5:httpcore5;5.3.1 -org.apache.httpcomponents.core5:httpcore5-h2;5.3.1 -org.apache.httpcomponents.core5:httpcore5-reactive;5.3.1 -org.apache.httpcomponents:httpasyncclient;4.1.5 -org.apache.httpcomponents:httpcore;4.4.16 -org.apache.httpcomponents:httpcore-nio;4.4.16 -org.apache.kafka:connect;3.8.1 -org.apache.kafka:connect-api;3.8.1 -org.apache.kafka:connect-basic-auth-extension;3.8.1 -org.apache.kafka:connect-file;3.8.1 -org.apache.kafka:connect-json;3.8.1 -org.apache.kafka:connect-mirror;3.8.1 -org.apache.kafka:connect-mirror-client;3.8.1 -org.apache.kafka:connect-runtime;3.8.1 -org.apache.kafka:connect-transforms;3.8.1 -org.apache.kafka:generator;3.8.1 -org.apache.kafka:kafka-clients;3.8.1 -org.apache.kafka:kafka-log4j-appender;3.8.1 -org.apache.kafka:kafka-metadata;3.8.1 -org.apache.kafka:kafka-raft;3.8.1 -org.apache.kafka:kafka-server;3.8.1 -org.apache.kafka:kafka-server-common;3.8.1 -org.apache.kafka:kafka-shell;3.8.1 -org.apache.kafka:kafka-storage;3.8.1 -org.apache.kafka:kafka-storage-api;3.8.1 -org.apache.kafka:kafka-streams;3.8.1 -org.apache.kafka:kafka-streams-scala_2.12;3.8.1 -org.apache.kafka:kafka-streams-scala_2.13;3.8.1 -org.apache.kafka:kafka-streams-test-utils;3.8.1 -org.apache.kafka:kafka-tools;3.8.1 -org.apache.kafka:kafka_2.12;3.8.1 -org.apache.kafka:kafka_2.13;3.8.1 -org.apache.kafka:trogdor;3.8.1 -org.apache.logging.log4j:log4j-1.2-api;2.24.3 -org.apache.logging.log4j:log4j-api;2.24.3 -org.apache.logging.log4j:log4j-api-test;2.24.3 -org.apache.logging.log4j:log4j-appserver;2.24.3 -org.apache.logging.log4j:log4j-bom;2.24.3 -org.apache.logging.log4j:log4j-cassandra;2.24.3 -org.apache.logging.log4j:log4j-core;2.24.3 -org.apache.logging.log4j:log4j-core-test;2.24.3 -org.apache.logging.log4j:log4j-couchdb;2.24.3 -org.apache.logging.log4j:log4j-docker;2.24.3 -org.apache.logging.log4j:log4j-flume-ng;2.23.1 -org.apache.logging.log4j:log4j-iostreams;2.24.3 -org.apache.logging.log4j:log4j-jakarta-smtp;2.24.3 -org.apache.logging.log4j:log4j-jakarta-web;2.24.3 -org.apache.logging.log4j:log4j-jcl;2.24.3 -org.apache.logging.log4j:log4j-jpa;2.24.3 -org.apache.logging.log4j:log4j-jpl;2.24.3 -org.apache.logging.log4j:log4j-jul;2.24.3 -org.apache.logging.log4j:log4j-layout-template-json;2.24.3 -org.apache.logging.log4j:log4j-mongodb;2.24.3 -org.apache.logging.log4j:log4j-mongodb4;2.24.3 -org.apache.logging.log4j:log4j-slf4j-impl;2.24.3 -org.apache.logging.log4j:log4j-slf4j2-impl;2.24.3 -org.apache.logging.log4j:log4j-spring-boot;2.24.3 -org.apache.logging.log4j:log4j-spring-cloud-config-client;2.24.3 -org.apache.logging.log4j:log4j-taglib;2.24.3 -org.apache.logging.log4j:log4j-to-jul;2.24.3 -org.apache.logging.log4j:log4j-to-slf4j;2.24.3 -org.apache.logging.log4j:log4j-web;2.24.3 -org.apache.maven.plugins:maven-antrun-plugin;3.1.0 -org.apache.maven.plugins:maven-assembly-plugin;3.7.1 -org.apache.maven.plugins:maven-clean-plugin;3.4.0 -org.apache.maven.plugins:maven-compiler-plugin;3.13.0 -org.apache.maven.plugins:maven-dependency-plugin;3.8.1 -org.apache.maven.plugins:maven-deploy-plugin;3.1.3 -org.apache.maven.plugins:maven-enforcer-plugin;3.5.0 -org.apache.maven.plugins:maven-failsafe-plugin;3.5.2 -org.apache.maven.plugins:maven-gpg-plugin;3.1.0 -org.apache.maven.plugins:maven-help-plugin;3.5.1 -org.apache.maven.plugins:maven-install-plugin;3.1.3 -org.apache.maven.plugins:maven-invoker-plugin;3.8.1 -org.apache.maven.plugins:maven-jar-plugin;3.4.2 -org.apache.maven.plugins:maven-javadoc-plugin;3.10.1 -org.apache.maven.plugins:maven-release-plugin;2.5.3 -org.apache.maven.plugins:maven-resources-plugin;3.3.1 -org.apache.maven.plugins:maven-shade-plugin;3.6.0 -org.apache.maven.plugins:maven-source-plugin;3.3.1 -org.apache.maven.plugins:maven-surefire-plugin;3.5.2 -org.apache.maven.plugins:maven-war-plugin;3.4.0 -org.apache.pulsar:bouncy-castle-bc;3.3.3 -org.apache.pulsar:bouncy-castle-bcfips;3.3.3 -org.apache.pulsar:bouncy-castle-parent;3.3.3 -org.apache.pulsar:buildtools;3.3.3 -org.apache.pulsar:distribution;3.3.3 -org.apache.pulsar:docker-images;3.3.3 -org.apache.pulsar:jclouds-shaded;3.3.3 -org.apache.pulsar:managed-ledger;3.3.3 -org.apache.pulsar:pulsar;3.3.3 -org.apache.pulsar:pulsar-all-docker-image;3.3.3 -org.apache.pulsar:pulsar-bom;3.3.3 -org.apache.pulsar:pulsar-broker;3.3.3 -org.apache.pulsar:pulsar-broker-auth-athenz;3.3.3 -org.apache.pulsar:pulsar-broker-auth-oidc;3.3.3 -org.apache.pulsar:pulsar-broker-auth-sasl;3.3.3 -org.apache.pulsar:pulsar-broker-common;3.3.3 -org.apache.pulsar:pulsar-cli-utils;3.3.3 -org.apache.pulsar:pulsar-client;3.3.3 -org.apache.pulsar:pulsar-client-1x;3.3.3 -org.apache.pulsar:pulsar-client-1x-base;3.3.3 -org.apache.pulsar:pulsar-client-2x-shaded;3.3.3 -org.apache.pulsar:pulsar-client-admin;3.3.3 -org.apache.pulsar:pulsar-client-admin-api;3.3.3 -org.apache.pulsar:pulsar-client-admin-original;3.3.3 -org.apache.pulsar:pulsar-client-all;3.3.3 -org.apache.pulsar:pulsar-client-api;3.3.3 -org.apache.pulsar:pulsar-client-auth-athenz;3.3.3 -org.apache.pulsar:pulsar-client-auth-sasl;3.3.3 -org.apache.pulsar:pulsar-client-messagecrypto-bc;3.3.3 -org.apache.pulsar:pulsar-client-original;3.3.3 -org.apache.pulsar:pulsar-client-reactive-adapter;0.5.10 -org.apache.pulsar:pulsar-client-reactive-api;0.5.10 -org.apache.pulsar:pulsar-client-reactive-jackson;0.5.10 -org.apache.pulsar:pulsar-client-reactive-producer-cache-caffeine;0.5.10 -org.apache.pulsar:pulsar-client-reactive-producer-cache-caffeine-shaded;0.5.10 -org.apache.pulsar:pulsar-client-tools;3.3.3 -org.apache.pulsar:pulsar-client-tools-api;3.3.3 -org.apache.pulsar:pulsar-common;3.3.3 -org.apache.pulsar:pulsar-config-validation;3.3.3 -org.apache.pulsar:pulsar-docker-image;3.3.3 -org.apache.pulsar:pulsar-docs-tools;3.3.3 -org.apache.pulsar:pulsar-functions;3.3.3 -org.apache.pulsar:pulsar-functions-api;3.3.3 -org.apache.pulsar:pulsar-functions-api-examples;3.3.3 -org.apache.pulsar:pulsar-functions-api-examples-builtin;3.3.3 -org.apache.pulsar:pulsar-functions-instance;3.3.3 -org.apache.pulsar:pulsar-functions-local-runner;3.3.3 -org.apache.pulsar:pulsar-functions-local-runner-original;3.3.3 -org.apache.pulsar:pulsar-functions-proto;3.3.3 -org.apache.pulsar:pulsar-functions-runtime;3.3.3 -org.apache.pulsar:pulsar-functions-runtime-all;3.3.3 -org.apache.pulsar:pulsar-functions-secrets;3.3.3 -org.apache.pulsar:pulsar-functions-utils;3.3.3 -org.apache.pulsar:pulsar-functions-worker;3.3.3 -org.apache.pulsar:pulsar-io;3.3.3 -org.apache.pulsar:pulsar-io-aerospike;3.3.3 -org.apache.pulsar:pulsar-io-alluxio;3.3.3 -org.apache.pulsar:pulsar-io-aws;3.3.3 -org.apache.pulsar:pulsar-io-batch-data-generator;3.3.3 -org.apache.pulsar:pulsar-io-batch-discovery-triggerers;3.3.3 -org.apache.pulsar:pulsar-io-canal;3.3.3 -org.apache.pulsar:pulsar-io-cassandra;3.3.3 -org.apache.pulsar:pulsar-io-common;3.3.3 -org.apache.pulsar:pulsar-io-core;3.3.3 -org.apache.pulsar:pulsar-io-data-generator;3.3.3 -org.apache.pulsar:pulsar-io-debezium;3.3.3 -org.apache.pulsar:pulsar-io-debezium-core;3.3.3 -org.apache.pulsar:pulsar-io-debezium-mongodb;3.3.3 -org.apache.pulsar:pulsar-io-debezium-mssql;3.3.3 -org.apache.pulsar:pulsar-io-debezium-mysql;3.3.3 -org.apache.pulsar:pulsar-io-debezium-oracle;3.3.3 -org.apache.pulsar:pulsar-io-debezium-postgres;3.3.3 -org.apache.pulsar:pulsar-io-distribution;3.3.3 -org.apache.pulsar:pulsar-io-docs;3.3.3 -org.apache.pulsar:pulsar-io-dynamodb;3.3.3 -org.apache.pulsar:pulsar-io-elastic-search;3.3.3 -org.apache.pulsar:pulsar-io-file;3.3.3 -org.apache.pulsar:pulsar-io-flume;3.3.3 -org.apache.pulsar:pulsar-io-hbase;3.3.3 -org.apache.pulsar:pulsar-io-hdfs3;3.3.3 -org.apache.pulsar:pulsar-io-http;3.3.3 -org.apache.pulsar:pulsar-io-influxdb;3.3.3 -org.apache.pulsar:pulsar-io-jdbc;3.3.3 -org.apache.pulsar:pulsar-io-jdbc-clickhouse;3.3.3 -org.apache.pulsar:pulsar-io-jdbc-core;3.3.3 -org.apache.pulsar:pulsar-io-jdbc-mariadb;3.3.3 -org.apache.pulsar:pulsar-io-jdbc-openmldb;3.3.3 -org.apache.pulsar:pulsar-io-jdbc-postgres;3.3.3 -org.apache.pulsar:pulsar-io-jdbc-sqlite;3.3.3 -org.apache.pulsar:pulsar-io-kafka;3.3.3 -org.apache.pulsar:pulsar-io-kafka-connect-adaptor;3.3.3 -org.apache.pulsar:pulsar-io-kafka-connect-adaptor-nar;3.3.3 -org.apache.pulsar:pulsar-io-kinesis;3.3.3 -org.apache.pulsar:pulsar-io-mongo;3.3.3 -org.apache.pulsar:pulsar-io-netty;3.3.3 -org.apache.pulsar:pulsar-io-nsq;3.3.3 -org.apache.pulsar:pulsar-io-rabbitmq;3.3.3 -org.apache.pulsar:pulsar-io-redis;3.3.3 -org.apache.pulsar:pulsar-io-solr;3.3.3 -org.apache.pulsar:pulsar-io-twitter;3.3.3 -org.apache.pulsar:pulsar-metadata;3.3.3 -org.apache.pulsar:pulsar-offloader-distribution;3.3.3 -org.apache.pulsar:pulsar-package-bookkeeper-storage;3.3.3 -org.apache.pulsar:pulsar-package-core;3.3.3 -org.apache.pulsar:pulsar-package-filesystem-storage;3.3.3 -org.apache.pulsar:pulsar-package-management;3.3.3 -org.apache.pulsar:pulsar-proxy;3.3.3 -org.apache.pulsar:pulsar-server-distribution;3.3.3 -org.apache.pulsar:pulsar-shell-distribution;3.3.3 -org.apache.pulsar:pulsar-testclient;3.3.3 -org.apache.pulsar:pulsar-transaction-common;3.3.3 -org.apache.pulsar:pulsar-transaction-coordinator;3.3.3 -org.apache.pulsar:pulsar-transaction-parent;3.3.3 -org.apache.pulsar:pulsar-websocket;3.3.3 -org.apache.pulsar:structured-event-log;3.3.3 -org.apache.pulsar:testmocks;3.3.3 -org.apache.pulsar:tiered-storage-file-system;3.3.3 -org.apache.pulsar:tiered-storage-jcloud;3.3.3 -org.apache.pulsar:tiered-storage-parent;3.3.3 -org.apache.tomcat.embed:tomcat-embed-core;10.1.34 -org.apache.tomcat.embed:tomcat-embed-el;10.1.34 -org.apache.tomcat.embed:tomcat-embed-jasper;10.1.34 -org.apache.tomcat.embed:tomcat-embed-websocket;10.1.34 -org.apache.tomcat:tomcat-annotations-api;10.1.34 -org.apache.tomcat:tomcat-jdbc;10.1.34 -org.apache.tomcat:tomcat-jsp-api;10.1.34 -org.aspectj:aspectjrt;1.9.22.1 -org.aspectj:aspectjtools;1.9.22.1 -org.aspectj:aspectjweaver;1.9.22.1 -org.assertj:assertj-bom;3.26.3 -org.assertj:assertj-core;3.26.3 -org.assertj:assertj-guava;3.26.3 -org.awaitility:awaitility;4.2.2 -org.awaitility:awaitility-groovy;4.2.2 -org.awaitility:awaitility-kotlin;4.2.2 -org.awaitility:awaitility-scala;4.2.2 -org.cache2k:cache2k-api;2.6.1.Final -org.cache2k:cache2k-config;2.6.1.Final -org.cache2k:cache2k-core;2.6.1.Final -org.cache2k:cache2k-jcache;2.6.1.Final -org.cache2k:cache2k-micrometer;2.6.1.Final -org.cache2k:cache2k-spring;2.6.1.Final -org.codehaus.janino:commons-compiler;3.1.12 -org.codehaus.janino:commons-compiler-jdk;3.1.12 -org.codehaus.janino:janino;3.1.12 -org.codehaus.mojo:build-helper-maven-plugin;3.6.0 -org.codehaus.mojo:versions-maven-plugin;2.17.1 -org.codehaus.mojo:xml-maven-plugin;1.1.0 -org.crac:crac;1.5.0 -org.cyclonedx:cyclonedx-maven-plugin;2.9.1 -org.eclipse.angus:angus-activation;2.0.2 -org.eclipse.angus:angus-core;2.0.3 -org.eclipse.angus:angus-mail;2.0.3 -org.eclipse.angus:dsn;2.0.3 -org.eclipse.angus:gimap;2.0.3 -org.eclipse.angus:imap;2.0.3 -org.eclipse.angus:jakarta.mail;2.0.3 -org.eclipse.angus:logging-mailhandler;2.0.3 -org.eclipse.angus:pop3;2.0.3 -org.eclipse.angus:smtp;2.0.3 -org.eclipse.jetty.demos:jetty-demo-handler;12.0.16 -org.eclipse.jetty.ee10.osgi:jetty-ee10-osgi-alpn;12.0.16 -org.eclipse.jetty.ee10.osgi:jetty-ee10-osgi-boot;12.0.16 -org.eclipse.jetty.ee10.osgi:jetty-ee10-osgi-boot-jsp;12.0.16 -org.eclipse.jetty.ee10.websocket:jetty-ee10-websocket-jakarta-client;12.0.16 -org.eclipse.jetty.ee10.websocket:jetty-ee10-websocket-jakarta-client-webapp;12.0.16 -org.eclipse.jetty.ee10.websocket:jetty-ee10-websocket-jakarta-common;12.0.16 -org.eclipse.jetty.ee10.websocket:jetty-ee10-websocket-jakarta-server;12.0.16 -org.eclipse.jetty.ee10.websocket:jetty-ee10-websocket-jetty-client-webapp;12.0.16 -org.eclipse.jetty.ee10.websocket:jetty-ee10-websocket-jetty-server;12.0.16 -org.eclipse.jetty.ee10.websocket:jetty-ee10-websocket-servlet;12.0.16 -org.eclipse.jetty.ee10:jetty-ee10-annotations;12.0.16 -org.eclipse.jetty.ee10:jetty-ee10-apache-jsp;12.0.16 -org.eclipse.jetty.ee10:jetty-ee10-bom;12.0.16 -org.eclipse.jetty.ee10:jetty-ee10-cdi;12.0.16 -org.eclipse.jetty.ee10:jetty-ee10-fcgi-proxy;12.0.16 -org.eclipse.jetty.ee10:jetty-ee10-glassfish-jstl;12.0.16 -org.eclipse.jetty.ee10:jetty-ee10-jaspi;12.0.16 -org.eclipse.jetty.ee10:jetty-ee10-jndi;12.0.16 -org.eclipse.jetty.ee10:jetty-ee10-jspc-maven-plugin;12.0.16 -org.eclipse.jetty.ee10:jetty-ee10-maven-plugin;12.0.16 -org.eclipse.jetty.ee10:jetty-ee10-plus;12.0.16 -org.eclipse.jetty.ee10:jetty-ee10-proxy;12.0.16 -org.eclipse.jetty.ee10:jetty-ee10-quickstart;12.0.16 -org.eclipse.jetty.ee10:jetty-ee10-runner;12.0.16 -org.eclipse.jetty.ee10:jetty-ee10-servlet;12.0.16 -org.eclipse.jetty.ee10:jetty-ee10-servlets;12.0.16 -org.eclipse.jetty.ee10:jetty-ee10-webapp;12.0.16 -org.eclipse.jetty.fcgi:jetty-fcgi-client;12.0.16 -org.eclipse.jetty.fcgi:jetty-fcgi-proxy;12.0.16 -org.eclipse.jetty.fcgi:jetty-fcgi-server;12.0.16 -org.eclipse.jetty.http2:jetty-http2-client;12.0.16 -org.eclipse.jetty.http2:jetty-http2-client-transport;12.0.16 -org.eclipse.jetty.http2:jetty-http2-common;12.0.16 -org.eclipse.jetty.http2:jetty-http2-hpack;12.0.16 -org.eclipse.jetty.http2:jetty-http2-server;12.0.16 -org.eclipse.jetty.http3:jetty-http3-client;12.0.16 -org.eclipse.jetty.http3:jetty-http3-client-transport;12.0.16 -org.eclipse.jetty.http3:jetty-http3-common;12.0.16 -org.eclipse.jetty.http3:jetty-http3-qpack;12.0.16 -org.eclipse.jetty.http3:jetty-http3-server;12.0.16 -org.eclipse.jetty.quic:jetty-quic-client;12.0.16 -org.eclipse.jetty.quic:jetty-quic-common;12.0.16 -org.eclipse.jetty.quic:jetty-quic-quiche-common;12.0.16 -org.eclipse.jetty.quic:jetty-quic-quiche-foreign;12.0.16 -org.eclipse.jetty.quic:jetty-quic-quiche-jna;12.0.16 -org.eclipse.jetty.quic:jetty-quic-server;12.0.16 -org.eclipse.jetty.websocket:jetty-websocket-core-client;12.0.16 -org.eclipse.jetty.websocket:jetty-websocket-core-common;12.0.16 -org.eclipse.jetty.websocket:jetty-websocket-core-server;12.0.16 -org.eclipse.jetty.websocket:jetty-websocket-jetty-api;12.0.16 -org.eclipse.jetty.websocket:jetty-websocket-jetty-client;12.0.16 -org.eclipse.jetty.websocket:jetty-websocket-jetty-common;12.0.16 -org.eclipse.jetty.websocket:jetty-websocket-jetty-server;12.0.16 -org.eclipse.jetty:jetty-alpn-client;12.0.16 -org.eclipse.jetty:jetty-alpn-conscrypt-client;12.0.16 -org.eclipse.jetty:jetty-alpn-conscrypt-server;12.0.16 -org.eclipse.jetty:jetty-alpn-java-client;12.0.16 -org.eclipse.jetty:jetty-alpn-java-server;12.0.16 -org.eclipse.jetty:jetty-alpn-server;12.0.16 -org.eclipse.jetty:jetty-bom;12.0.16 -org.eclipse.jetty:jetty-client;12.0.16 -org.eclipse.jetty:jetty-deploy;12.0.16 -org.eclipse.jetty:jetty-http;12.0.16 -org.eclipse.jetty:jetty-http-spi;12.0.16 -org.eclipse.jetty:jetty-http-tools;12.0.16 -org.eclipse.jetty:jetty-io;12.0.16 -org.eclipse.jetty:jetty-jmx;12.0.16 -org.eclipse.jetty:jetty-jndi;12.0.16 -org.eclipse.jetty:jetty-keystore;12.0.16 -org.eclipse.jetty:jetty-openid;12.0.16 -org.eclipse.jetty:jetty-osgi;12.0.16 -org.eclipse.jetty:jetty-plus;12.0.16 -org.eclipse.jetty:jetty-proxy;12.0.16 -org.eclipse.jetty:jetty-reactive-httpclient;4.0.8 -org.eclipse.jetty:jetty-rewrite;12.0.16 -org.eclipse.jetty:jetty-security;12.0.16 -org.eclipse.jetty:jetty-server;12.0.16 -org.eclipse.jetty:jetty-session;12.0.16 -org.eclipse.jetty:jetty-slf4j-impl;12.0.16 -org.eclipse.jetty:jetty-start;12.0.16 -org.eclipse.jetty:jetty-unixdomain-server;12.0.16 -org.eclipse.jetty:jetty-util;12.0.16 -org.eclipse.jetty:jetty-util-ajax;12.0.16 -org.eclipse.jetty:jetty-xml;12.0.16 -org.eclipse.jgit:org.eclipse.jgit;6.10.0.202406032230-r -org.eclipse.jgit:org.eclipse.jgit.http.apache;6.10.0.202406032230-r -org.eclipse.jgit:org.eclipse.jgit.junit.http;6.10.0.202406032230-r -org.eclipse.jgit:org.eclipse.jgit.ssh.apache;6.10.0.202406032230-r -org.eclipse:yasson;3.0.4 -org.ehcache:ehcache;3.10.8 -org.ehcache:ehcache-clustered;3.10.8 -org.ehcache:ehcache-transactions;3.10.8 -org.elasticsearch.client:elasticsearch-rest-client;8.15.5 -org.elasticsearch.client:elasticsearch-rest-client-sniffer;8.15.5 -org.firebirdsql.jdbc:jaybird;5.0.6.java11 -org.flywaydb:flyway-commandline;10.20.1 -org.flywaydb:flyway-core;10.20.1 -org.flywaydb:flyway-database-cassandra;10.20.1 -org.flywaydb:flyway-database-db2;10.20.1 -org.flywaydb:flyway-database-derby;10.20.1 -org.flywaydb:flyway-database-hsqldb;10.20.1 -org.flywaydb:flyway-database-informix;10.20.1 -org.flywaydb:flyway-database-mongodb;10.20.1 -org.flywaydb:flyway-database-oracle;10.20.1 -org.flywaydb:flyway-database-postgresql;10.20.1 -org.flywaydb:flyway-database-redshift;10.20.1 -org.flywaydb:flyway-database-saphana;10.20.1 -org.flywaydb:flyway-database-snowflake;10.20.1 -org.flywaydb:flyway-database-sybasease;10.20.1 -org.flywaydb:flyway-firebird;10.20.1 -org.flywaydb:flyway-gcp-bigquery;10.20.1 -org.flywaydb:flyway-gcp-spanner;10.20.1 -org.flywaydb:flyway-maven-plugin;10.20.1 -org.flywaydb:flyway-mysql;10.20.1 -org.flywaydb:flyway-singlestore;10.20.1 -org.flywaydb:flyway-sqlserver;10.20.1 -org.freemarker:freemarker;2.3.33 -org.glassfish.jaxb:codemodel;4.0.5 -org.glassfish.jaxb:jaxb-bom;4.0.5 -org.glassfish.jaxb:jaxb-core;4.0.5 -org.glassfish.jaxb:jaxb-jxc;4.0.5 -org.glassfish.jaxb:jaxb-runtime;4.0.5 -org.glassfish.jaxb:jaxb-xjc;4.0.5 -org.glassfish.jaxb:txw2;4.0.5 -org.glassfish.jaxb:xsom;4.0.5 -org.glassfish.jersey.bundles:jaxrs-ri;3.1.9 -org.glassfish.jersey.connectors:jersey-apache-connector;3.1.9 -org.glassfish.jersey.connectors:jersey-apache5-connector;3.1.9 -org.glassfish.jersey.connectors:jersey-grizzly-connector;3.1.9 -org.glassfish.jersey.connectors:jersey-helidon-connector;3.1.9 -org.glassfish.jersey.connectors:jersey-jdk-connector;3.1.9 -org.glassfish.jersey.connectors:jersey-jetty-connector;3.1.9 -org.glassfish.jersey.connectors:jersey-jetty-http2-connector;3.1.9 -org.glassfish.jersey.connectors:jersey-jetty11-connector;3.1.9 -org.glassfish.jersey.connectors:jersey-jnh-connector;3.1.9 -org.glassfish.jersey.connectors:jersey-netty-connector;3.1.9 -org.glassfish.jersey.containers.glassfish:jersey-gf-ejb;3.1.9 -org.glassfish.jersey.containers:jersey-container-grizzly2-http;3.1.9 -org.glassfish.jersey.containers:jersey-container-grizzly2-servlet;3.1.9 -org.glassfish.jersey.containers:jersey-container-jdk-http;3.1.9 -org.glassfish.jersey.containers:jersey-container-jetty-http;3.1.9 -org.glassfish.jersey.containers:jersey-container-jetty-http2;3.1.9 -org.glassfish.jersey.containers:jersey-container-jetty-servlet;3.1.9 -org.glassfish.jersey.containers:jersey-container-jetty11-http;3.1.9 -org.glassfish.jersey.containers:jersey-container-netty-http;3.1.9 -org.glassfish.jersey.containers:jersey-container-servlet;3.1.9 -org.glassfish.jersey.containers:jersey-container-servlet-core;3.1.9 -org.glassfish.jersey.containers:jersey-container-simple-http;3.1.9 -org.glassfish.jersey.core:jersey-client;3.1.9 -org.glassfish.jersey.core:jersey-common;3.1.9 -org.glassfish.jersey.core:jersey-server;3.1.9 -org.glassfish.jersey.ext.cdi:jersey-cdi-rs-inject;3.1.9 -org.glassfish.jersey.ext.cdi:jersey-cdi1x;3.1.9 -org.glassfish.jersey.ext.cdi:jersey-cdi1x-ban-custom-hk2-binding;3.1.9 -org.glassfish.jersey.ext.cdi:jersey-cdi1x-servlet;3.1.9 -org.glassfish.jersey.ext.cdi:jersey-cdi1x-transaction;3.1.9 -org.glassfish.jersey.ext.cdi:jersey-cdi1x-validation;3.1.9 -org.glassfish.jersey.ext.cdi:jersey-weld2-se;3.1.9 -org.glassfish.jersey.ext.microprofile:jersey-mp-config;3.1.9 -org.glassfish.jersey.ext.microprofile:jersey-mp-rest-client;3.1.9 -org.glassfish.jersey.ext.rx:jersey-rx-client-guava;3.1.9 -org.glassfish.jersey.ext.rx:jersey-rx-client-rxjava;3.1.9 -org.glassfish.jersey.ext.rx:jersey-rx-client-rxjava2;3.1.9 -org.glassfish.jersey.ext:jersey-bean-validation;3.1.9 -org.glassfish.jersey.ext:jersey-declarative-linking;3.1.9 -org.glassfish.jersey.ext:jersey-entity-filtering;3.1.9 -org.glassfish.jersey.ext:jersey-metainf-services;3.1.9 -org.glassfish.jersey.ext:jersey-micrometer;3.1.9 -org.glassfish.jersey.ext:jersey-mvc;3.1.9 -org.glassfish.jersey.ext:jersey-mvc-bean-validation;3.1.9 -org.glassfish.jersey.ext:jersey-mvc-freemarker;3.1.9 -org.glassfish.jersey.ext:jersey-mvc-jsp;3.1.9 -org.glassfish.jersey.ext:jersey-mvc-mustache;3.1.9 -org.glassfish.jersey.ext:jersey-proxy-client;3.1.9 -org.glassfish.jersey.ext:jersey-spring6;3.1.9 -org.glassfish.jersey.ext:jersey-wadl-doclet;3.1.9 -org.glassfish.jersey.inject:jersey-cdi2-se;3.1.9 -org.glassfish.jersey.inject:jersey-hk2;3.1.9 -org.glassfish.jersey.media:jersey-media-jaxb;3.1.9 -org.glassfish.jersey.media:jersey-media-json-binding;3.1.9 -org.glassfish.jersey.media:jersey-media-json-gson;3.1.9 -org.glassfish.jersey.media:jersey-media-json-jackson;3.1.9 -org.glassfish.jersey.media:jersey-media-json-jettison;3.1.9 -org.glassfish.jersey.media:jersey-media-json-processing;3.1.9 -org.glassfish.jersey.media:jersey-media-kryo;3.1.9 -org.glassfish.jersey.media:jersey-media-moxy;3.1.9 -org.glassfish.jersey.media:jersey-media-multipart;3.1.9 -org.glassfish.jersey.media:jersey-media-sse;3.1.9 -org.glassfish.jersey.security:oauth1-client;3.1.9 -org.glassfish.jersey.security:oauth1-server;3.1.9 -org.glassfish.jersey.security:oauth1-signature;3.1.9 -org.glassfish.jersey.security:oauth2-client;3.1.9 -org.glassfish.jersey.test-framework.providers:jersey-test-framework-provider-bundle;3.1.9 -org.glassfish.jersey.test-framework.providers:jersey-test-framework-provider-external;3.1.9 -org.glassfish.jersey.test-framework.providers:jersey-test-framework-provider-grizzly2;3.1.9 -org.glassfish.jersey.test-framework.providers:jersey-test-framework-provider-inmemory;3.1.9 -org.glassfish.jersey.test-framework.providers:jersey-test-framework-provider-jdk-http;3.1.9 -org.glassfish.jersey.test-framework.providers:jersey-test-framework-provider-jetty;3.1.9 -org.glassfish.jersey.test-framework.providers:jersey-test-framework-provider-jetty-http2;3.1.9 -org.glassfish.jersey.test-framework.providers:jersey-test-framework-provider-netty;3.1.9 -org.glassfish.jersey.test-framework.providers:jersey-test-framework-provider-simple;3.1.9 -org.glassfish.jersey.test-framework:jersey-test-framework-core;3.1.9 -org.glassfish.jersey.test-framework:jersey-test-framework-util;3.1.9 -org.glassfish.jersey:jersey-bom;3.1.9 -org.glassfish.web:jakarta.servlet.jsp.jstl;3.0.1 -org.graalvm.buildtools:native-maven-plugin;0.10.4 -org.hamcrest:hamcrest;2.2 -org.hamcrest:hamcrest-core;2.2 -org.hamcrest:hamcrest-library;2.2 -org.hibernate.orm:hibernate-agroal;6.6.4.Final -org.hibernate.orm:hibernate-ant;6.6.4.Final -org.hibernate.orm:hibernate-c3p0;6.6.4.Final -org.hibernate.orm:hibernate-community-dialects;6.6.4.Final -org.hibernate.orm:hibernate-core;6.6.4.Final -org.hibernate.orm:hibernate-envers;6.6.4.Final -org.hibernate.orm:hibernate-graalvm;6.6.4.Final -org.hibernate.orm:hibernate-hikaricp;6.6.4.Final -org.hibernate.orm:hibernate-jcache;6.6.4.Final -org.hibernate.orm:hibernate-jpamodelgen;6.6.4.Final -org.hibernate.orm:hibernate-micrometer;6.6.4.Final -org.hibernate.orm:hibernate-proxool;6.6.4.Final -org.hibernate.orm:hibernate-spatial;6.6.4.Final -org.hibernate.orm:hibernate-testing;6.6.4.Final -org.hibernate.orm:hibernate-vibur;6.6.4.Final -org.hibernate.validator:hibernate-validator;8.0.2.Final -org.hibernate.validator:hibernate-validator-annotation-processor;8.0.2.Final -org.hsqldb:hsqldb;2.7.3 -org.htmlunit:htmlunit;4.5.0 -org.infinispan.protostream:protostream;5.0.10.Final -org.infinispan.protostream:protostream-processor;5.0.10.Final -org.infinispan.protostream:protostream-types;5.0.10.Final -org.infinispan:infinispan-anchored-keys;15.0.11.Final -org.infinispan:infinispan-api;15.0.11.Final -org.infinispan:infinispan-bom;15.0.11.Final -org.infinispan:infinispan-cachestore-jdbc;15.0.11.Final -org.infinispan:infinispan-cachestore-jdbc-common;15.0.11.Final -org.infinispan:infinispan-cachestore-remote;15.0.11.Final -org.infinispan:infinispan-cachestore-rocksdb;15.0.11.Final -org.infinispan:infinispan-cachestore-sql;15.0.11.Final -org.infinispan:infinispan-cdi-common;15.0.11.Final -org.infinispan:infinispan-cdi-embedded;15.0.11.Final -org.infinispan:infinispan-cdi-remote;15.0.11.Final -org.infinispan:infinispan-checkstyle;15.0.11.Final -org.infinispan:infinispan-cli-client;15.0.11.Final -org.infinispan:infinispan-client-hotrod;15.0.11.Final -org.infinispan:infinispan-client-rest;15.0.11.Final -org.infinispan:infinispan-clustered-counter;15.0.11.Final -org.infinispan:infinispan-clustered-lock;15.0.11.Final -org.infinispan:infinispan-commons;15.0.11.Final -org.infinispan:infinispan-commons-graalvm;15.0.11.Final -org.infinispan:infinispan-commons-test;15.0.11.Final -org.infinispan:infinispan-component-annotations;15.0.11.Final -org.infinispan:infinispan-component-processor;15.0.11.Final -org.infinispan:infinispan-console;15.0.10.Final -org.infinispan:infinispan-core;15.0.11.Final -org.infinispan:infinispan-core-graalvm;15.0.11.Final -org.infinispan:infinispan-hibernate-cache-commons;15.0.11.Final -org.infinispan:infinispan-hibernate-cache-spi;15.0.11.Final -org.infinispan:infinispan-hibernate-cache-v62;15.0.11.Final -org.infinispan:infinispan-hotrod;15.0.11.Final -org.infinispan:infinispan-jboss-marshalling;15.0.11.Final -org.infinispan:infinispan-jcache;15.0.11.Final -org.infinispan:infinispan-jcache-commons;15.0.11.Final -org.infinispan:infinispan-jcache-remote;15.0.11.Final -org.infinispan:infinispan-key-value-store-client;15.0.11.Final -org.infinispan:infinispan-logging-annotations;15.0.11.Final -org.infinispan:infinispan-logging-processor;15.0.11.Final -org.infinispan:infinispan-multimap;15.0.11.Final -org.infinispan:infinispan-objectfilter;15.0.11.Final -org.infinispan:infinispan-quarkus-embedded;15.0.11.Final -org.infinispan:infinispan-query;15.0.11.Final -org.infinispan:infinispan-query-core;15.0.11.Final -org.infinispan:infinispan-query-dsl;15.0.11.Final -org.infinispan:infinispan-remote-query-client;15.0.11.Final -org.infinispan:infinispan-remote-query-server;15.0.11.Final -org.infinispan:infinispan-scripting;15.0.11.Final -org.infinispan:infinispan-server-core;15.0.11.Final -org.infinispan:infinispan-server-hotrod;15.0.11.Final -org.infinispan:infinispan-server-memcached;15.0.11.Final -org.infinispan:infinispan-server-resp;15.0.11.Final -org.infinispan:infinispan-server-rest;15.0.11.Final -org.infinispan:infinispan-server-router;15.0.11.Final -org.infinispan:infinispan-server-runtime;15.0.11.Final -org.infinispan:infinispan-server-testdriver-core;15.0.11.Final -org.infinispan:infinispan-server-testdriver-junit4;15.0.11.Final -org.infinispan:infinispan-server-testdriver-junit5;15.0.11.Final -org.infinispan:infinispan-spring-boot3-starter-embedded;15.0.11.Final -org.infinispan:infinispan-spring-boot3-starter-remote;15.0.11.Final -org.infinispan:infinispan-spring6-common;15.0.11.Final -org.infinispan:infinispan-spring6-embedded;15.0.11.Final -org.infinispan:infinispan-spring6-remote;15.0.11.Final -org.infinispan:infinispan-tasks;15.0.11.Final -org.infinispan:infinispan-tasks-api;15.0.11.Final -org.infinispan:infinispan-tools;15.0.11.Final -org.influxdb:influxdb-java;2.24 -org.jboss.logging:jboss-logging;3.6.1.Final -org.jdom:jdom2;2.0.6.1 -org.jetbrains.kotlin:kotlin-bom;1.9.25 -org.jetbrains.kotlin:kotlin-compiler;1.9.25 -org.jetbrains.kotlin:kotlin-compiler-embeddable;1.9.25 -org.jetbrains.kotlin:kotlin-daemon-client;1.9.25 -org.jetbrains.kotlin:kotlin-main-kts;1.9.25 -org.jetbrains.kotlin:kotlin-maven-plugin;1.9.25 -org.jetbrains.kotlin:kotlin-osgi-bundle;1.9.25 -org.jetbrains.kotlin:kotlin-reflect;1.9.25 -org.jetbrains.kotlin:kotlin-script-runtime;1.9.25 -org.jetbrains.kotlin:kotlin-scripting-common;1.9.25 -org.jetbrains.kotlin:kotlin-scripting-ide-services;1.9.25 -org.jetbrains.kotlin:kotlin-scripting-jvm;1.9.25 -org.jetbrains.kotlin:kotlin-scripting-jvm-host;1.9.25 -org.jetbrains.kotlin:kotlin-stdlib;1.9.25 -org.jetbrains.kotlin:kotlin-stdlib-common;1.9.25 -org.jetbrains.kotlin:kotlin-stdlib-jdk7;1.9.25 -org.jetbrains.kotlin:kotlin-stdlib-jdk8;1.9.25 -org.jetbrains.kotlin:kotlin-stdlib-js;1.9.25 -org.jetbrains.kotlin:kotlin-test;1.9.25 -org.jetbrains.kotlin:kotlin-test-annotations-common;1.9.25 -org.jetbrains.kotlin:kotlin-test-common;1.9.25 -org.jetbrains.kotlin:kotlin-test-js;1.9.25 -org.jetbrains.kotlin:kotlin-test-junit;1.9.25 -org.jetbrains.kotlin:kotlin-test-junit5;1.9.25 -org.jetbrains.kotlin:kotlin-test-testng;1.9.25 -org.jetbrains.kotlinx:kotlinx-coroutines-android;1.8.1 -org.jetbrains.kotlinx:kotlinx-coroutines-bom;1.8.1 -org.jetbrains.kotlinx:kotlinx-coroutines-core;1.8.1 -org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm;1.8.1 -org.jetbrains.kotlinx:kotlinx-coroutines-debug;1.8.1 -org.jetbrains.kotlinx:kotlinx-coroutines-guava;1.8.1 -org.jetbrains.kotlinx:kotlinx-coroutines-javafx;1.8.1 -org.jetbrains.kotlinx:kotlinx-coroutines-jdk8;1.8.1 -org.jetbrains.kotlinx:kotlinx-coroutines-jdk9;1.8.1 -org.jetbrains.kotlinx:kotlinx-coroutines-play-services;1.8.1 -org.jetbrains.kotlinx:kotlinx-coroutines-reactive;1.8.1 -org.jetbrains.kotlinx:kotlinx-coroutines-reactor;1.8.1 -org.jetbrains.kotlinx:kotlinx-coroutines-rx2;1.8.1 -org.jetbrains.kotlinx:kotlinx-coroutines-rx3;1.8.1 -org.jetbrains.kotlinx:kotlinx-coroutines-slf4j;1.8.1 -org.jetbrains.kotlinx:kotlinx-coroutines-swing;1.8.1 -org.jetbrains.kotlinx:kotlinx-coroutines-test;1.8.1 -org.jetbrains.kotlinx:kotlinx-coroutines-test-jvm;1.8.1 -org.jetbrains.kotlinx:kotlinx-serialization-bom;1.6.3 -org.jetbrains.kotlinx:kotlinx-serialization-cbor;1.6.3 -org.jetbrains.kotlinx:kotlinx-serialization-cbor-jvm;1.6.3 -org.jetbrains.kotlinx:kotlinx-serialization-core;1.6.3 -org.jetbrains.kotlinx:kotlinx-serialization-core-jvm;1.6.3 -org.jetbrains.kotlinx:kotlinx-serialization-hocon;1.6.3 -org.jetbrains.kotlinx:kotlinx-serialization-json;1.6.3 -org.jetbrains.kotlinx:kotlinx-serialization-json-jvm;1.6.3 -org.jetbrains.kotlinx:kotlinx-serialization-json-okio;1.6.3 -org.jetbrains.kotlinx:kotlinx-serialization-json-okio-jvm;1.6.3 -org.jetbrains.kotlinx:kotlinx-serialization-properties;1.6.3 -org.jetbrains.kotlinx:kotlinx-serialization-properties-jvm;1.6.3 -org.jetbrains.kotlinx:kotlinx-serialization-protobuf;1.6.3 -org.jetbrains.kotlinx:kotlinx-serialization-protobuf-jvm;1.6.3 -org.jooq:jooq;3.19.16 -org.jooq:jooq-codegen;3.19.16 -org.jooq:jooq-codegen-maven;3.19.16 -org.jooq:jooq-kotlin;3.19.16 -org.jooq:jooq-meta;3.19.16 -org.junit.jupiter:junit-jupiter;5.11.4 -org.junit.jupiter:junit-jupiter-api;5.11.4 -org.junit.jupiter:junit-jupiter-engine;5.11.4 -org.junit.jupiter:junit-jupiter-migrationsupport;5.11.4 -org.junit.jupiter:junit-jupiter-params;5.11.4 -org.junit.platform:junit-platform-commons;1.11.4 -org.junit.platform:junit-platform-console;1.11.4 -org.junit.platform:junit-platform-engine;1.11.4 -org.junit.platform:junit-platform-jfr;1.11.4 -org.junit.platform:junit-platform-launcher;1.11.4 -org.junit.platform:junit-platform-reporting;1.11.4 -org.junit.platform:junit-platform-runner;1.11.4 -org.junit.platform:junit-platform-suite;1.11.4 -org.junit.platform:junit-platform-suite-api;1.11.4 -org.junit.platform:junit-platform-suite-commons;1.11.4 -org.junit.platform:junit-platform-suite-engine;1.11.4 -org.junit.platform:junit-platform-testkit;1.11.4 -org.junit.vintage:junit-vintage-engine;5.11.4 -org.junit:junit-bom;5.11.4 -org.jvnet.staxex:stax-ex;2.1.0 -org.liquibase:liquibase-cdi;4.29.2 -org.liquibase:liquibase-core;4.29.2 -org.liquibase:liquibase-maven-plugin;4.29.2 -org.mariadb.jdbc:mariadb-java-client;3.4.1 -org.mariadb:r2dbc-mariadb;1.2.2 -org.messaginghub:pooled-jms;3.1.7 -org.mockito:mockito-android;5.14.2 -org.mockito:mockito-bom;5.14.2 -org.mockito:mockito-core;5.14.2 -org.mockito:mockito-errorprone;5.14.2 -org.mockito:mockito-junit-jupiter;5.14.2 -org.mockito:mockito-proxy;5.14.2 -org.mockito:mockito-subclass;5.14.2 -org.mongodb:bson;5.2.1 -org.mongodb:bson-record-codec;5.2.1 -org.mongodb:mongodb-driver-core;5.2.1 -org.mongodb:mongodb-driver-legacy;5.2.1 -org.mongodb:mongodb-driver-reactivestreams;5.2.1 -org.mongodb:mongodb-driver-sync;5.2.1 -org.neo4j.driver:neo4j-java-driver;5.25.0 -org.postgresql:postgresql;42.7.4 -org.postgresql:r2dbc-postgresql;1.0.7.RELEASE -org.projectlombok:lombok;1.18.36 -org.quartz-scheduler:quartz;2.3.2 -org.quartz-scheduler:quartz-jobs;2.3.2 -org.reactivestreams:reactive-streams;1.0.4 -org.seleniumhq.selenium:htmlunit3-driver;4.25.0 -org.seleniumhq.selenium:selenium-api;4.25.0 -org.seleniumhq.selenium:selenium-bom;4.25.0 -org.seleniumhq.selenium:selenium-chrome-driver;4.25.0 -org.seleniumhq.selenium:selenium-chromium-driver;4.25.0 -org.seleniumhq.selenium:selenium-devtools-v127;4.25.0 -org.seleniumhq.selenium:selenium-devtools-v128;4.25.0 -org.seleniumhq.selenium:selenium-devtools-v129;4.25.0 -org.seleniumhq.selenium:selenium-devtools-v85;4.25.0 -org.seleniumhq.selenium:selenium-edge-driver;4.25.0 -org.seleniumhq.selenium:selenium-firefox-driver;4.25.0 -org.seleniumhq.selenium:selenium-grid;4.25.0 -org.seleniumhq.selenium:selenium-http;4.25.0 -org.seleniumhq.selenium:selenium-ie-driver;4.25.0 -org.seleniumhq.selenium:selenium-java;4.25.0 -org.seleniumhq.selenium:selenium-json;4.25.0 -org.seleniumhq.selenium:selenium-manager;4.25.0 -org.seleniumhq.selenium:selenium-remote-driver;4.25.0 -org.seleniumhq.selenium:selenium-safari-driver;4.25.0 -org.seleniumhq.selenium:selenium-session-map-jdbc;4.25.0 -org.seleniumhq.selenium:selenium-session-map-redis;4.25.0 -org.seleniumhq.selenium:selenium-support;4.25.0 -org.skyscreamer:jsonassert;1.5.3 -org.slf4j:jcl-over-slf4j;2.0.16 -org.slf4j:jul-to-slf4j;2.0.16 -org.slf4j:log4j-over-slf4j;2.0.16 -org.slf4j:slf4j-api;2.0.16 -org.slf4j:slf4j-ext;2.0.16 -org.slf4j:slf4j-jdk-platform-logging;2.0.16 -org.slf4j:slf4j-jdk14;2.0.16 -org.slf4j:slf4j-log4j12;2.0.16 -org.slf4j:slf4j-nop;2.0.16 -org.slf4j:slf4j-reload4j;2.0.16 -org.slf4j:slf4j-simple;2.0.16 -org.springframework.amqp:spring-amqp;3.2.1 -org.springframework.amqp:spring-amqp-bom;3.2.1 -org.springframework.amqp:spring-rabbit;3.2.1 -org.springframework.amqp:spring-rabbit-junit;3.2.1 -org.springframework.amqp:spring-rabbit-stream;3.2.1 -org.springframework.amqp:spring-rabbit-test;3.2.1 -org.springframework.batch:spring-batch-bom;5.2.1 -org.springframework.batch:spring-batch-core;5.2.1 -org.springframework.batch:spring-batch-infrastructure;5.2.1 -org.springframework.batch:spring-batch-integration;5.2.1 -org.springframework.batch:spring-batch-test;5.2.1 -org.springframework.boot:spring-boot;3.4.1 -org.springframework.boot:spring-boot-actuator;3.4.1 -org.springframework.boot:spring-boot-actuator-autoconfigure;3.4.1 -org.springframework.boot:spring-boot-autoconfigure;3.4.1 -org.springframework.boot:spring-boot-autoconfigure-processor;3.4.1 -org.springframework.boot:spring-boot-buildpack-platform;3.4.1 -org.springframework.boot:spring-boot-configuration-metadata;3.4.1 -org.springframework.boot:spring-boot-configuration-processor;3.4.1 -org.springframework.boot:spring-boot-dependencies;3.4.1 -org.springframework.boot:spring-boot-devtools;3.4.1 -org.springframework.boot:spring-boot-docker-compose;3.4.1 -org.springframework.boot:spring-boot-jarmode-tools;3.4.1 -org.springframework.boot:spring-boot-loader;3.4.1 -org.springframework.boot:spring-boot-loader-classic;3.4.1 -org.springframework.boot:spring-boot-loader-tools;3.4.1 -org.springframework.boot:spring-boot-maven-plugin;3.4.1 -org.springframework.boot:spring-boot-properties-migrator;3.4.1 -org.springframework.boot:spring-boot-starter;3.4.1 -org.springframework.boot:spring-boot-starter-activemq;3.4.1 -org.springframework.boot:spring-boot-starter-actuator;3.4.1 -org.springframework.boot:spring-boot-starter-amqp;3.4.1 -org.springframework.boot:spring-boot-starter-aop;3.4.1 -org.springframework.boot:spring-boot-starter-artemis;3.4.1 -org.springframework.boot:spring-boot-starter-batch;3.4.1 -org.springframework.boot:spring-boot-starter-cache;3.4.1 -org.springframework.boot:spring-boot-starter-data-cassandra;3.4.1 -org.springframework.boot:spring-boot-starter-data-cassandra-reactive;3.4.1 -org.springframework.boot:spring-boot-starter-data-couchbase;3.4.1 -org.springframework.boot:spring-boot-starter-data-couchbase-reactive;3.4.1 -org.springframework.boot:spring-boot-starter-data-elasticsearch;3.4.1 -org.springframework.boot:spring-boot-starter-data-jdbc;3.4.1 -org.springframework.boot:spring-boot-starter-data-jpa;3.4.1 -org.springframework.boot:spring-boot-starter-data-ldap;3.4.1 -org.springframework.boot:spring-boot-starter-data-mongodb;3.4.1 -org.springframework.boot:spring-boot-starter-data-mongodb-reactive;3.4.1 -org.springframework.boot:spring-boot-starter-data-neo4j;3.4.1 -org.springframework.boot:spring-boot-starter-data-r2dbc;3.4.1 -org.springframework.boot:spring-boot-starter-data-redis;3.4.1 -org.springframework.boot:spring-boot-starter-data-redis-reactive;3.4.1 -org.springframework.boot:spring-boot-starter-data-rest;3.4.1 -org.springframework.boot:spring-boot-starter-freemarker;3.4.1 -org.springframework.boot:spring-boot-starter-graphql;3.4.1 -org.springframework.boot:spring-boot-starter-groovy-templates;3.4.1 -org.springframework.boot:spring-boot-starter-hateoas;3.4.1 -org.springframework.boot:spring-boot-starter-integration;3.4.1 -org.springframework.boot:spring-boot-starter-jdbc;3.4.1 -org.springframework.boot:spring-boot-starter-jersey;3.4.1 -org.springframework.boot:spring-boot-starter-jetty;3.4.1 -org.springframework.boot:spring-boot-starter-jooq;3.4.1 -org.springframework.boot:spring-boot-starter-json;3.4.1 -org.springframework.boot:spring-boot-starter-log4j2;3.4.1 -org.springframework.boot:spring-boot-starter-logging;3.4.1 -org.springframework.boot:spring-boot-starter-mail;3.4.1 -org.springframework.boot:spring-boot-starter-mustache;3.4.1 -org.springframework.boot:spring-boot-starter-oauth2-authorization-server;3.4.1 -org.springframework.boot:spring-boot-starter-oauth2-client;3.4.1 -org.springframework.boot:spring-boot-starter-oauth2-resource-server;3.4.1 -org.springframework.boot:spring-boot-starter-parent;3.4.1 -org.springframework.boot:spring-boot-starter-pulsar;3.4.1 -org.springframework.boot:spring-boot-starter-pulsar-reactive;3.4.1 -org.springframework.boot:spring-boot-starter-quartz;3.4.1 -org.springframework.boot:spring-boot-starter-reactor-netty;3.4.1 -org.springframework.boot:spring-boot-starter-rsocket;3.4.1 -org.springframework.boot:spring-boot-starter-security;3.4.1 -org.springframework.boot:spring-boot-starter-test;3.4.1 -org.springframework.boot:spring-boot-starter-thymeleaf;3.4.1 -org.springframework.boot:spring-boot-starter-tomcat;3.4.1 -org.springframework.boot:spring-boot-starter-undertow;3.4.1 -org.springframework.boot:spring-boot-starter-validation;3.4.1 -org.springframework.boot:spring-boot-starter-web;3.4.1 -org.springframework.boot:spring-boot-starter-web-services;3.4.1 -org.springframework.boot:spring-boot-starter-webflux;3.4.1 -org.springframework.boot:spring-boot-starter-websocket;3.4.1 -org.springframework.boot:spring-boot-test;3.4.1 -org.springframework.boot:spring-boot-test-autoconfigure;3.4.1 -org.springframework.boot:spring-boot-testcontainers;3.4.1 -org.springframework.cloud:spring-cloud-bus;4.2.0 -org.springframework.cloud:spring-cloud-bus-dependencies;4.2.0 -org.springframework.cloud:spring-cloud-bus-rsocket;4.2.0 -org.springframework.cloud:spring-cloud-circuitbreaker-dependencies;3.2.0 -org.springframework.cloud:spring-cloud-circuitbreaker-resilience4j;3.2.0 -org.springframework.cloud:spring-cloud-circuitbreaker-spring-retry;3.2.0 -org.springframework.cloud:spring-cloud-commons;4.2.0 -org.springframework.cloud:spring-cloud-commons-dependencies;4.2.0 -org.springframework.cloud:spring-cloud-config-client;4.2.0 -org.springframework.cloud:spring-cloud-config-dependencies;4.2.0 -org.springframework.cloud:spring-cloud-config-monitor;4.2.0 -org.springframework.cloud:spring-cloud-config-server;4.2.0 -org.springframework.cloud:spring-cloud-consul-binder;4.2.0 -org.springframework.cloud:spring-cloud-consul-config;4.2.0 -org.springframework.cloud:spring-cloud-consul-core;4.2.0 -org.springframework.cloud:spring-cloud-consul-dependencies;4.2.0 -org.springframework.cloud:spring-cloud-consul-discovery;4.2.0 -org.springframework.cloud:spring-cloud-context;4.2.0 -org.springframework.cloud:spring-cloud-contract-converters;4.2.0 -org.springframework.cloud:spring-cloud-contract-dependencies;4.2.0 -org.springframework.cloud:spring-cloud-contract-gradle-plugin;4.2.0 -org.springframework.cloud:spring-cloud-contract-maven-plugin;4.2.0 -org.springframework.cloud:spring-cloud-contract-shade;4.2.0 -org.springframework.cloud:spring-cloud-contract-spec;4.2.0 -org.springframework.cloud:spring-cloud-contract-spec-groovy;4.2.0 -org.springframework.cloud:spring-cloud-contract-spec-java;4.2.0 -org.springframework.cloud:spring-cloud-contract-spec-kotlin;4.2.0 -org.springframework.cloud:spring-cloud-contract-stub-runner;4.2.0 -org.springframework.cloud:spring-cloud-contract-stub-runner-boot;4.2.0 -org.springframework.cloud:spring-cloud-contract-verifier;4.2.0 -org.springframework.cloud:spring-cloud-contract-wiremock;4.2.0 -org.springframework.cloud:spring-cloud-dependencies;2024.0.0 -org.springframework.cloud:spring-cloud-function-adapter-aws;4.2.0 -org.springframework.cloud:spring-cloud-function-adapter-azure;4.2.0 -org.springframework.cloud:spring-cloud-function-adapter-gcp;4.2.0 -org.springframework.cloud:spring-cloud-function-context;4.2.0 -org.springframework.cloud:spring-cloud-function-core;4.2.0 -org.springframework.cloud:spring-cloud-function-dependencies;4.2.0 -org.springframework.cloud:spring-cloud-function-deployer;4.2.0 -org.springframework.cloud:spring-cloud-function-grpc;4.2.0 -org.springframework.cloud:spring-cloud-function-grpc-cloudevent-ext;4.2.0 -org.springframework.cloud:spring-cloud-function-integration;4.2.0 -org.springframework.cloud:spring-cloud-function-kotlin;4.2.0 -org.springframework.cloud:spring-cloud-function-rsocket;4.2.0 -org.springframework.cloud:spring-cloud-function-serverless-web;4.2.0 -org.springframework.cloud:spring-cloud-function-web;4.2.0 -org.springframework.cloud:spring-cloud-gateway-dependencies;4.2.0 -org.springframework.cloud:spring-cloud-gateway-mvc;4.2.0 -org.springframework.cloud:spring-cloud-gateway-server;4.2.0 -org.springframework.cloud:spring-cloud-gateway-server-mvc;4.2.0 -org.springframework.cloud:spring-cloud-gateway-webflux;4.2.0 -org.springframework.cloud:spring-cloud-kubernetes-client-autoconfig;3.2.0 -org.springframework.cloud:spring-cloud-kubernetes-client-config;3.2.0 -org.springframework.cloud:spring-cloud-kubernetes-client-discovery;3.2.0 -org.springframework.cloud:spring-cloud-kubernetes-client-loadbalancer;3.2.0 -org.springframework.cloud:spring-cloud-kubernetes-commons;3.2.0 -org.springframework.cloud:spring-cloud-kubernetes-dependencies;3.2.0 -org.springframework.cloud:spring-cloud-kubernetes-discovery;3.2.0 -org.springframework.cloud:spring-cloud-kubernetes-fabric8-autoconfig;3.2.0 -org.springframework.cloud:spring-cloud-kubernetes-fabric8-config;3.2.0 -org.springframework.cloud:spring-cloud-kubernetes-fabric8-discovery;3.2.0 -org.springframework.cloud:spring-cloud-kubernetes-fabric8-istio;3.2.0 -org.springframework.cloud:spring-cloud-kubernetes-fabric8-leader;3.2.0 -org.springframework.cloud:spring-cloud-kubernetes-fabric8-loadbalancer;3.2.0 -org.springframework.cloud:spring-cloud-kubernetes-test-support;3.2.0 -org.springframework.cloud:spring-cloud-loadbalancer;4.2.0 -org.springframework.cloud:spring-cloud-netflix-dependencies;4.2.0 -org.springframework.cloud:spring-cloud-netflix-eureka-client;4.2.0 -org.springframework.cloud:spring-cloud-netflix-eureka-server;4.2.0 -org.springframework.cloud:spring-cloud-openfeign-core;4.2.0 -org.springframework.cloud:spring-cloud-openfeign-dependencies;4.2.0 -org.springframework.cloud:spring-cloud-starter;4.2.0 -org.springframework.cloud:spring-cloud-starter-bootstrap;4.2.0 -org.springframework.cloud:spring-cloud-starter-bus-amqp;4.2.0 -org.springframework.cloud:spring-cloud-starter-bus-kafka;4.2.0 -org.springframework.cloud:spring-cloud-starter-bus-stream;4.2.0 -org.springframework.cloud:spring-cloud-starter-circuitbreaker-reactor-resilience4j;3.2.0 -org.springframework.cloud:spring-cloud-starter-circuitbreaker-resilience4j;3.2.0 -org.springframework.cloud:spring-cloud-starter-circuitbreaker-spring-retry;3.2.0 -org.springframework.cloud:spring-cloud-starter-config;4.2.0 -org.springframework.cloud:spring-cloud-starter-consul;4.2.0 -org.springframework.cloud:spring-cloud-starter-consul-all;4.2.0 -org.springframework.cloud:spring-cloud-starter-consul-bus;4.2.0 -org.springframework.cloud:spring-cloud-starter-consul-config;4.2.0 -org.springframework.cloud:spring-cloud-starter-consul-discovery;4.2.0 -org.springframework.cloud:spring-cloud-starter-contract-stub-runner;4.2.0 -org.springframework.cloud:spring-cloud-starter-contract-stub-runner-jetty;4.2.0 -org.springframework.cloud:spring-cloud-starter-contract-verifier;4.2.0 -org.springframework.cloud:spring-cloud-starter-function-web;4.2.0 -org.springframework.cloud:spring-cloud-starter-function-webflux;4.2.0 -org.springframework.cloud:spring-cloud-starter-gateway;4.2.0 -org.springframework.cloud:spring-cloud-starter-gateway-mvc;4.2.0 -org.springframework.cloud:spring-cloud-starter-kubernetes-client;3.2.0 -org.springframework.cloud:spring-cloud-starter-kubernetes-client-all;3.2.0 -org.springframework.cloud:spring-cloud-starter-kubernetes-client-config;3.2.0 -org.springframework.cloud:spring-cloud-starter-kubernetes-client-loadbalancer;3.2.0 -org.springframework.cloud:spring-cloud-starter-kubernetes-discoveryclient;3.2.0 -org.springframework.cloud:spring-cloud-starter-kubernetes-fabric8;3.2.0 -org.springframework.cloud:spring-cloud-starter-kubernetes-fabric8-all;3.2.0 -org.springframework.cloud:spring-cloud-starter-kubernetes-fabric8-config;3.2.0 -org.springframework.cloud:spring-cloud-starter-kubernetes-fabric8-loadbalancer;3.2.0 -org.springframework.cloud:spring-cloud-starter-loadbalancer;4.2.0 -org.springframework.cloud:spring-cloud-starter-netflix-eureka-client;4.2.0 -org.springframework.cloud:spring-cloud-starter-netflix-eureka-server;4.2.0 -org.springframework.cloud:spring-cloud-starter-openfeign;4.2.0 -org.springframework.cloud:spring-cloud-starter-stream-kafka;4.2.0 -org.springframework.cloud:spring-cloud-starter-stream-rabbit;4.2.0 -org.springframework.cloud:spring-cloud-starter-task;3.2.0 -org.springframework.cloud:spring-cloud-starter-vault-config;4.2.0 -org.springframework.cloud:spring-cloud-starter-zookeeper;4.2.0 -org.springframework.cloud:spring-cloud-starter-zookeeper-all;4.2.0 -org.springframework.cloud:spring-cloud-starter-zookeeper-config;4.2.0 -org.springframework.cloud:spring-cloud-starter-zookeeper-discovery;4.2.0 -org.springframework.cloud:spring-cloud-stream;4.2.0 -org.springframework.cloud:spring-cloud-stream-binder-kafka;4.2.0 -org.springframework.cloud:spring-cloud-stream-binder-kafka-core;4.2.0 -org.springframework.cloud:spring-cloud-stream-binder-kafka-reactive;4.2.0 -org.springframework.cloud:spring-cloud-stream-binder-kafka-streams;4.2.0 -org.springframework.cloud:spring-cloud-stream-binder-pulsar;4.2.0 -org.springframework.cloud:spring-cloud-stream-binder-rabbit;4.2.0 -org.springframework.cloud:spring-cloud-stream-binder-rabbit-core;4.2.0 -org.springframework.cloud:spring-cloud-stream-binder-rabbit-test-support;4.2.0 -org.springframework.cloud:spring-cloud-stream-dependencies;4.2.0 -org.springframework.cloud:spring-cloud-stream-schema-registry-client;4.2.0 -org.springframework.cloud:spring-cloud-stream-schema-registry-core;4.2.0 -org.springframework.cloud:spring-cloud-stream-schema-registry-server;4.2.0 -org.springframework.cloud:spring-cloud-stream-test-binder;4.2.0 -org.springframework.cloud:spring-cloud-stream-test-support;4.2.0 -org.springframework.cloud:spring-cloud-task-batch;3.2.0 -org.springframework.cloud:spring-cloud-task-core;3.2.0 -org.springframework.cloud:spring-cloud-task-dependencies;3.2.0 -org.springframework.cloud:spring-cloud-task-stream;3.2.0 -org.springframework.cloud:spring-cloud-test-support;4.2.0 -org.springframework.cloud:spring-cloud-vault-config;4.2.0 -org.springframework.cloud:spring-cloud-vault-config-aws;4.2.0 -org.springframework.cloud:spring-cloud-vault-config-consul;4.2.0 -org.springframework.cloud:spring-cloud-vault-config-databases;4.2.0 -org.springframework.cloud:spring-cloud-vault-config-rabbitmq;4.2.0 -org.springframework.cloud:spring-cloud-vault-dependencies;4.2.0 -org.springframework.cloud:spring-cloud-zookeeper-config;4.2.0 -org.springframework.cloud:spring-cloud-zookeeper-core;4.2.0 -org.springframework.cloud:spring-cloud-zookeeper-dependencies;4.2.0 -org.springframework.cloud:spring-cloud-zookeeper-discovery;4.2.0 -org.springframework.credhub:spring-credhub-core;2.1.1.RELEASE -org.springframework.data:spring-data-bom;2024.1.1 -org.springframework.data:spring-data-cassandra;4.4.1 -org.springframework.data:spring-data-commons;3.4.1 -org.springframework.data:spring-data-couchbase;5.4.1 -org.springframework.data:spring-data-elasticsearch;5.4.1 -org.springframework.data:spring-data-envers;3.4.1 -org.springframework.data:spring-data-jdbc;3.4.1 -org.springframework.data:spring-data-jpa;3.4.1 -org.springframework.data:spring-data-keyvalue;3.4.1 -org.springframework.data:spring-data-ldap;3.4.1 -org.springframework.data:spring-data-mongodb;4.4.1 -org.springframework.data:spring-data-neo4j;7.4.1 -org.springframework.data:spring-data-r2dbc;3.4.1 -org.springframework.data:spring-data-redis;3.4.1 -org.springframework.data:spring-data-relational;3.4.1 -org.springframework.data:spring-data-rest-core;4.4.1 -org.springframework.data:spring-data-rest-hal-explorer;4.4.1 -org.springframework.data:spring-data-rest-webmvc;4.4.1 -org.springframework.graphql:spring-graphql;1.3.3 -org.springframework.graphql:spring-graphql-test;1.3.3 -org.springframework.hateoas:spring-hateoas;2.4.1 -org.springframework.integration:spring-integration-amqp;6.4.1 -org.springframework.integration:spring-integration-bom;6.4.1 -org.springframework.integration:spring-integration-camel;6.4.1 -org.springframework.integration:spring-integration-cassandra;6.4.1 -org.springframework.integration:spring-integration-core;6.4.1 -org.springframework.integration:spring-integration-debezium;6.4.1 -org.springframework.integration:spring-integration-event;6.4.1 -org.springframework.integration:spring-integration-feed;6.4.1 -org.springframework.integration:spring-integration-file;6.4.1 -org.springframework.integration:spring-integration-ftp;6.4.1 -org.springframework.integration:spring-integration-graphql;6.4.1 -org.springframework.integration:spring-integration-groovy;6.4.1 -org.springframework.integration:spring-integration-hazelcast;6.4.1 -org.springframework.integration:spring-integration-http;6.4.1 -org.springframework.integration:spring-integration-ip;6.4.1 -org.springframework.integration:spring-integration-jdbc;6.4.1 -org.springframework.integration:spring-integration-jms;6.4.1 -org.springframework.integration:spring-integration-jmx;6.4.1 -org.springframework.integration:spring-integration-jpa;6.4.1 -org.springframework.integration:spring-integration-kafka;6.4.1 -org.springframework.integration:spring-integration-mail;6.4.1 -org.springframework.integration:spring-integration-mongodb;6.4.1 -org.springframework.integration:spring-integration-mqtt;6.4.1 -org.springframework.integration:spring-integration-r2dbc;6.4.1 -org.springframework.integration:spring-integration-redis;6.4.1 -org.springframework.integration:spring-integration-rsocket;6.4.1 -org.springframework.integration:spring-integration-scripting;6.4.1 -org.springframework.integration:spring-integration-sftp;6.4.1 -org.springframework.integration:spring-integration-smb;6.4.1 -org.springframework.integration:spring-integration-stomp;6.4.1 -org.springframework.integration:spring-integration-stream;6.4.1 -org.springframework.integration:spring-integration-syslog;6.4.1 -org.springframework.integration:spring-integration-test;6.4.1 -org.springframework.integration:spring-integration-test-support;6.4.1 -org.springframework.integration:spring-integration-webflux;6.4.1 -org.springframework.integration:spring-integration-websocket;6.4.1 -org.springframework.integration:spring-integration-ws;6.4.1 -org.springframework.integration:spring-integration-xml;6.4.1 -org.springframework.integration:spring-integration-xmpp;6.4.1 -org.springframework.integration:spring-integration-zeromq;6.4.1 -org.springframework.integration:spring-integration-zip;6.4.1 -org.springframework.integration:spring-integration-zookeeper;6.4.1 -org.springframework.kafka:spring-kafka;3.3.1 -org.springframework.kafka:spring-kafka-test;3.3.1 -org.springframework.ldap:spring-ldap-core;3.2.10 -org.springframework.ldap:spring-ldap-ldif-core;3.2.10 -org.springframework.ldap:spring-ldap-odm;3.2.10 -org.springframework.ldap:spring-ldap-test;3.2.10 -org.springframework.pulsar:spring-pulsar;1.2.1 -org.springframework.pulsar:spring-pulsar-bom;1.2.1 -org.springframework.pulsar:spring-pulsar-cache-provider;1.2.1 -org.springframework.pulsar:spring-pulsar-cache-provider-caffeine;1.2.1 -org.springframework.pulsar:spring-pulsar-reactive;1.2.1 -org.springframework.pulsar:spring-pulsar-test;1.2.1 -org.springframework.restdocs:spring-restdocs-asciidoctor;3.0.3 -org.springframework.restdocs:spring-restdocs-bom;3.0.3 -org.springframework.restdocs:spring-restdocs-core;3.0.3 -org.springframework.restdocs:spring-restdocs-mockmvc;3.0.3 -org.springframework.restdocs:spring-restdocs-restassured;3.0.3 -org.springframework.restdocs:spring-restdocs-webtestclient;3.0.3 -org.springframework.retry:spring-retry;2.0.11 -org.springframework.security:spring-security-acl;6.4.2 -org.springframework.security:spring-security-aspects;6.4.2 -org.springframework.security:spring-security-bom;6.4.2 -org.springframework.security:spring-security-cas;6.4.2 -org.springframework.security:spring-security-config;6.4.2 -org.springframework.security:spring-security-core;6.4.2 -org.springframework.security:spring-security-crypto;6.4.2 -org.springframework.security:spring-security-data;6.4.2 -org.springframework.security:spring-security-ldap;6.4.2 -org.springframework.security:spring-security-messaging;6.4.2 -org.springframework.security:spring-security-oauth2-authorization-server;1.4.1 -org.springframework.security:spring-security-oauth2-client;6.4.2 -org.springframework.security:spring-security-oauth2-core;6.4.2 -org.springframework.security:spring-security-oauth2-jose;6.4.2 -org.springframework.security:spring-security-oauth2-resource-server;6.4.2 -org.springframework.security:spring-security-rsocket;6.4.2 -org.springframework.security:spring-security-saml2-service-provider;6.4.2 -org.springframework.security:spring-security-taglibs;6.4.2 -org.springframework.security:spring-security-test;6.4.2 -org.springframework.security:spring-security-web;6.4.2 -org.springframework.session:spring-session-bom;3.4.1 -org.springframework.session:spring-session-core;3.4.1 -org.springframework.session:spring-session-data-mongodb;3.4.1 -org.springframework.session:spring-session-data-redis;3.4.1 -org.springframework.session:spring-session-hazelcast;3.4.1 -org.springframework.session:spring-session-jdbc;3.4.1 -org.springframework.vault:spring-vault-core;3.1.2 -org.springframework.ws:spring-ws-bom;4.0.11 -org.springframework.ws:spring-ws-core;4.0.11 -org.springframework.ws:spring-ws-security;4.0.11 -org.springframework.ws:spring-ws-support;4.0.11 -org.springframework.ws:spring-ws-test;4.0.11 -org.springframework.ws:spring-xml;4.0.11 -org.springframework:spring-aop;6.2.1 -org.springframework:spring-aspects;6.2.1 -org.springframework:spring-beans;6.2.1 -org.springframework:spring-context;6.2.1 -org.springframework:spring-context-indexer;6.2.1 -org.springframework:spring-context-support;6.2.1 -org.springframework:spring-core;6.2.1 -org.springframework:spring-core-test;6.2.1 -org.springframework:spring-expression;6.2.1 -org.springframework:spring-framework-bom;6.2.1 -org.springframework:spring-instrument;6.2.1 -org.springframework:spring-jcl;6.2.1 -org.springframework:spring-jdbc;6.2.1 -org.springframework:spring-jms;6.2.1 -org.springframework:spring-messaging;6.2.1 -org.springframework:spring-orm;6.2.1 -org.springframework:spring-oxm;6.2.1 -org.springframework:spring-r2dbc;6.2.1 -org.springframework:spring-test;6.2.1 -org.springframework:spring-tx;6.2.1 -org.springframework:spring-web;6.2.1 -org.springframework:spring-webflux;6.2.1 -org.springframework:spring-webmvc;6.2.1 -org.springframework:spring-websocket;6.2.1 -org.testcontainers:activemq;1.20.4 -org.testcontainers:azure;1.20.4 -org.testcontainers:cassandra;1.20.4 -org.testcontainers:chromadb;1.20.4 -org.testcontainers:clickhouse;1.20.4 -org.testcontainers:cockroachdb;1.20.4 -org.testcontainers:consul;1.20.4 -org.testcontainers:couchbase;1.20.4 -org.testcontainers:cratedb;1.20.4 -org.testcontainers:database-commons;1.20.4 -org.testcontainers:databend;1.20.4 -org.testcontainers:db2;1.20.4 -org.testcontainers:dynalite;1.20.4 -org.testcontainers:elasticsearch;1.20.4 -org.testcontainers:gcloud;1.20.4 -org.testcontainers:grafana;1.20.4 -org.testcontainers:hivemq;1.20.4 -org.testcontainers:influxdb;1.20.4 -org.testcontainers:jdbc;1.20.4 -org.testcontainers:junit-jupiter;1.20.4 -org.testcontainers:k3s;1.20.4 -org.testcontainers:k6;1.20.4 -org.testcontainers:kafka;1.20.4 -org.testcontainers:localstack;1.20.4 -org.testcontainers:mariadb;1.20.4 -org.testcontainers:milvus;1.20.4 -org.testcontainers:minio;1.20.4 -org.testcontainers:mockserver;1.20.4 -org.testcontainers:mongodb;1.20.4 -org.testcontainers:mssqlserver;1.20.4 -org.testcontainers:mysql;1.20.4 -org.testcontainers:neo4j;1.20.4 -org.testcontainers:nginx;1.20.4 -org.testcontainers:oceanbase;1.20.4 -org.testcontainers:ollama;1.20.4 -org.testcontainers:openfga;1.20.4 -org.testcontainers:oracle-free;1.20.4 -org.testcontainers:oracle-xe;1.20.4 -org.testcontainers:orientdb;1.20.4 -org.testcontainers:postgresql;1.20.4 -org.testcontainers:presto;1.20.4 -org.testcontainers:pulsar;1.20.4 -org.testcontainers:qdrant;1.20.4 -org.testcontainers:questdb;1.20.4 -org.testcontainers:r2dbc;1.20.4 -org.testcontainers:rabbitmq;1.20.4 -org.testcontainers:redpanda;1.20.4 -org.testcontainers:selenium;1.20.4 -org.testcontainers:solace;1.20.4 -org.testcontainers:solr;1.20.4 -org.testcontainers:spock;1.20.4 -org.testcontainers:testcontainers;1.20.4 -org.testcontainers:testcontainers-bom;1.20.4 -org.testcontainers:tidb;1.20.4 -org.testcontainers:timeplus;1.20.4 -org.testcontainers:toxiproxy;1.20.4 -org.testcontainers:trino;1.20.4 -org.testcontainers:typesense;1.20.4 -org.testcontainers:vault;1.20.4 -org.testcontainers:weaviate;1.20.4 -org.testcontainers:yugabytedb;1.20.4 -org.thymeleaf.extras:thymeleaf-extras-springsecurity6;3.1.3.RELEASE -org.thymeleaf:thymeleaf;3.1.3.RELEASE -org.thymeleaf:thymeleaf-spring6;3.1.3.RELEASE -org.tmatesoft.svnkit:svnkit;1.10.11 -org.webjars:webjars-locator-core;0.59 -org.webjars:webjars-locator-lite;1.0.1 -org.wiremock:wiremock-standalone;3.4.2 -org.xerial:sqlite-jdbc;3.47.1.0 -org.xmlunit:xmlunit-assertj;2.10.0 -org.xmlunit:xmlunit-assertj3;2.10.0 -org.xmlunit:xmlunit-core;2.10.0 -org.xmlunit:xmlunit-jakarta-jaxb-impl;2.10.0 -org.xmlunit:xmlunit-legacy;2.10.0 -org.xmlunit:xmlunit-matchers;2.10.0 -org.xmlunit:xmlunit-placeholders;2.10.0 -org.yaml:snakeyaml;2.3 -redis.clients:jedis;5.2.0 -wsdl4j:wsdl4j;1.6.3 diff --git a/sdk/spring/scripts/spring_boot_3.4.2_managed_external_dependencies.txt b/sdk/spring/scripts/spring_boot_3.4.2_managed_external_dependencies.txt new file mode 100644 index 000000000000..061f7dadda58 --- /dev/null +++ b/sdk/spring/scripts/spring_boot_3.4.2_managed_external_dependencies.txt @@ -0,0 +1,1885 @@ +ch.qos.logback:logback-classic;1.5.16 +ch.qos.logback:logback-core;1.5.16 +co.elastic.clients:elasticsearch-java;8.15.5 +com.couchbase.client:java-client;3.7.7 +com.datastax.oss:java-driver-shaded-guava;25.1-jre-graal-sub-1 +com.datastax.oss:native-protocol;1.5.1 +com.ecwid.consul:consul-api;1.4.5 +com.fasterxml.jackson.core:jackson-annotations;2.18.2 +com.fasterxml.jackson.core:jackson-core;2.18.2 +com.fasterxml.jackson.core:jackson-databind;2.18.2 +com.fasterxml.jackson.dataformat:jackson-dataformat-avro;2.18.2 +com.fasterxml.jackson.dataformat:jackson-dataformat-cbor;2.18.2 +com.fasterxml.jackson.dataformat:jackson-dataformat-csv;2.18.2 +com.fasterxml.jackson.dataformat:jackson-dataformat-ion;2.18.2 +com.fasterxml.jackson.dataformat:jackson-dataformat-properties;2.18.2 +com.fasterxml.jackson.dataformat:jackson-dataformat-protobuf;2.18.2 +com.fasterxml.jackson.dataformat:jackson-dataformat-smile;2.18.2 +com.fasterxml.jackson.dataformat:jackson-dataformat-toml;2.18.2 +com.fasterxml.jackson.dataformat:jackson-dataformat-xml;2.18.2 +com.fasterxml.jackson.dataformat:jackson-dataformat-yaml;2.18.2 +com.fasterxml.jackson.datatype:jackson-datatype-eclipse-collections;2.18.2 +com.fasterxml.jackson.datatype:jackson-datatype-guava;2.18.2 +com.fasterxml.jackson.datatype:jackson-datatype-hibernate4;2.18.2 +com.fasterxml.jackson.datatype:jackson-datatype-hibernate5;2.18.2 +com.fasterxml.jackson.datatype:jackson-datatype-hibernate5-jakarta;2.18.2 +com.fasterxml.jackson.datatype:jackson-datatype-hibernate6;2.18.2 +com.fasterxml.jackson.datatype:jackson-datatype-hppc;2.18.2 +com.fasterxml.jackson.datatype:jackson-datatype-jakarta-jsonp;2.18.2 +com.fasterxml.jackson.datatype:jackson-datatype-jaxrs;2.18.2 +com.fasterxml.jackson.datatype:jackson-datatype-jdk8;2.18.2 +com.fasterxml.jackson.datatype:jackson-datatype-joda;2.18.2 +com.fasterxml.jackson.datatype:jackson-datatype-joda-money;2.18.2 +com.fasterxml.jackson.datatype:jackson-datatype-json-org;2.18.2 +com.fasterxml.jackson.datatype:jackson-datatype-jsr310;2.18.2 +com.fasterxml.jackson.datatype:jackson-datatype-jsr353;2.18.2 +com.fasterxml.jackson.datatype:jackson-datatype-pcollections;2.18.2 +com.fasterxml.jackson.jakarta.rs:jackson-jakarta-rs-base;2.18.2 +com.fasterxml.jackson.jakarta.rs:jackson-jakarta-rs-cbor-provider;2.18.2 +com.fasterxml.jackson.jakarta.rs:jackson-jakarta-rs-json-provider;2.18.2 +com.fasterxml.jackson.jakarta.rs:jackson-jakarta-rs-smile-provider;2.18.2 +com.fasterxml.jackson.jakarta.rs:jackson-jakarta-rs-xml-provider;2.18.2 +com.fasterxml.jackson.jakarta.rs:jackson-jakarta-rs-yaml-provider;2.18.2 +com.fasterxml.jackson.jaxrs:jackson-jaxrs-base;2.18.2 +com.fasterxml.jackson.jaxrs:jackson-jaxrs-cbor-provider;2.18.2 +com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider;2.18.2 +com.fasterxml.jackson.jaxrs:jackson-jaxrs-smile-provider;2.18.2 +com.fasterxml.jackson.jaxrs:jackson-jaxrs-xml-provider;2.18.2 +com.fasterxml.jackson.jaxrs:jackson-jaxrs-yaml-provider;2.18.2 +com.fasterxml.jackson.jr:jackson-jr-all;2.18.2 +com.fasterxml.jackson.jr:jackson-jr-annotation-support;2.18.2 +com.fasterxml.jackson.jr:jackson-jr-extension-javatime;2.18.2 +com.fasterxml.jackson.jr:jackson-jr-objects;2.18.2 +com.fasterxml.jackson.jr:jackson-jr-retrofit2;2.18.2 +com.fasterxml.jackson.jr:jackson-jr-stree;2.18.2 +com.fasterxml.jackson.module:jackson-module-afterburner;2.18.2 +com.fasterxml.jackson.module:jackson-module-android-record;2.18.2 +com.fasterxml.jackson.module:jackson-module-blackbird;2.18.2 +com.fasterxml.jackson.module:jackson-module-guice;2.18.2 +com.fasterxml.jackson.module:jackson-module-guice7;2.18.2 +com.fasterxml.jackson.module:jackson-module-jakarta-xmlbind-annotations;2.18.2 +com.fasterxml.jackson.module:jackson-module-jaxb-annotations;2.18.2 +com.fasterxml.jackson.module:jackson-module-jsonSchema;2.18.2 +com.fasterxml.jackson.module:jackson-module-jsonSchema-jakarta;2.18.2 +com.fasterxml.jackson.module:jackson-module-kotlin;2.18.2 +com.fasterxml.jackson.module:jackson-module-mrbean;2.18.2 +com.fasterxml.jackson.module:jackson-module-no-ctor-deser;2.18.2 +com.fasterxml.jackson.module:jackson-module-osgi;2.18.2 +com.fasterxml.jackson.module:jackson-module-parameter-names;2.18.2 +com.fasterxml.jackson.module:jackson-module-paranamer;2.18.2 +com.fasterxml.jackson.module:jackson-module-scala_2.11;2.18.2 +com.fasterxml.jackson.module:jackson-module-scala_2.12;2.18.2 +com.fasterxml.jackson.module:jackson-module-scala_2.13;2.18.2 +com.fasterxml.jackson.module:jackson-module-scala_3;2.18.2 +com.fasterxml.jackson:jackson-bom;2.18.2 +com.fasterxml:classmate;1.7.0 +com.github.ben-manes.caffeine:caffeine;3.1.8 +com.github.ben-manes.caffeine:guava;3.1.8 +com.github.ben-manes.caffeine:jcache;3.1.8 +com.github.ben-manes.caffeine:simulator;3.1.8 +com.github.mxab.thymeleaf.extras:thymeleaf-extras-data-attribute;2.0.1 +com.github.tomakehurst:wiremock-jre8-standalone;2.35.1 +com.google.code.gson:gson;2.11.0 +com.graphql-java:graphql-java;22.3 +com.h2database:h2;2.3.232 +com.hazelcast:hazelcast;5.5.0 +com.hazelcast:hazelcast-spring;5.5.0 +com.ibm.db2:jcc;11.5.9.0 +com.jayway.jsonpath:json-path;2.9.0 +com.jayway.jsonpath:json-path-assert;2.9.0 +com.microsoft.sqlserver:mssql-jdbc;12.8.1.jre11 +com.mysql:mysql-connector-j;9.1.0 +com.netflix.eureka:eureka-client;2.0.4 +com.netflix.eureka:eureka-client-jersey3;2.0.4 +com.netflix.eureka:eureka-core;2.0.4 +com.netflix.eureka:eureka-core-jersey3;2.0.4 +com.oracle.database.ha:ons;23.5.0.24.07 +com.oracle.database.ha:simplefan;23.5.0.24.07 +com.oracle.database.jdbc:ojdbc11;23.5.0.24.07 +com.oracle.database.jdbc:ojdbc11-production;23.5.0.24.07 +com.oracle.database.jdbc:ojdbc8;23.5.0.24.07 +com.oracle.database.jdbc:ojdbc8-production;23.5.0.24.07 +com.oracle.database.jdbc:rsi;23.5.0.24.07 +com.oracle.database.jdbc:ucp;23.5.0.24.07 +com.oracle.database.jdbc:ucp11;23.5.0.24.07 +com.oracle.database.nls:orai18n;23.5.0.24.07 +com.oracle.database.r2dbc:oracle-r2dbc;1.2.0 +com.oracle.database.security:oraclepki;23.5.0.24.07 +com.oracle.database.xml:xdb;23.5.0.24.07 +com.oracle.database.xml:xmlparserv2;23.5.0.24.07 +com.querydsl:codegen-utils;5.1.0 +com.querydsl:querydsl-apt;5.1.0 +com.querydsl:querydsl-bom;5.1.0 +com.querydsl:querydsl-codegen;5.1.0 +com.querydsl:querydsl-collections;5.1.0 +com.querydsl:querydsl-core;5.1.0 +com.querydsl:querydsl-guava;5.1.0 +com.querydsl:querydsl-hibernate-search;5.1.0 +com.querydsl:querydsl-jdo;5.1.0 +com.querydsl:querydsl-jpa;5.1.0 +com.querydsl:querydsl-jpa-codegen;5.1.0 +com.querydsl:querydsl-kotlin;5.1.0 +com.querydsl:querydsl-kotlin-codegen;5.1.0 +com.querydsl:querydsl-lucene3;5.1.0 +com.querydsl:querydsl-lucene4;5.1.0 +com.querydsl:querydsl-lucene5;5.1.0 +com.querydsl:querydsl-mongodb;5.1.0 +com.querydsl:querydsl-scala;5.1.0 +com.querydsl:querydsl-spatial;5.1.0 +com.querydsl:querydsl-sql;5.1.0 +com.querydsl:querydsl-sql-codegen;5.1.0 +com.querydsl:querydsl-sql-spatial;5.1.0 +com.querydsl:querydsl-sql-spring;5.1.0 +com.rabbitmq:amqp-client;5.22.0 +com.rabbitmq:stream-client;0.18.0 +com.redis:testcontainers-redis;2.2.2 +com.samskivert:jmustache;1.16 +com.sendgrid:sendgrid-java;4.10.3 +com.sun.istack:istack-commons-runtime;4.1.2 +com.sun.xml.bind:jaxb-core;4.0.5 +com.sun.xml.bind:jaxb-impl;4.0.5 +com.sun.xml.bind:jaxb-jxc;4.0.5 +com.sun.xml.bind:jaxb-osgi;4.0.5 +com.sun.xml.bind:jaxb-xjc;4.0.5 +com.sun.xml.fastinfoset:FastInfoset;2.1.1 +com.sun.xml.messaging.saaj:saaj-impl;3.0.4 +com.toomuchcoding.jsonassert:jsonassert;0.8.0 +com.toomuchcoding.jsonassert:jsonassert-shade;0.8.0 +com.unboundid:unboundid-ldapsdk;6.0.11 +com.zaxxer:HikariCP;5.1.0 +commons-codec:commons-codec;1.17.2 +commons-pool:commons-pool;1.6 +io.asyncer:r2dbc-mysql;1.3.1 +io.fabric8.java-generator:io.fabric8.java-generator.gradle.plugin;6.13.4 +io.fabric8.kubernetes:kubernetes-karaf;6.13.4 +io.fabric8.kubernetes:kubernetes-karaf-itests;6.13.4 +io.fabric8:certmanager-client;6.13.4 +io.fabric8:certmanager-examples;6.13.4 +io.fabric8:certmanager-model-v1;6.13.4 +io.fabric8:certmanager-model-v1alpha2;6.13.4 +io.fabric8:certmanager-model-v1alpha3;6.13.4 +io.fabric8:certmanager-model-v1beta1;6.13.4 +io.fabric8:certmanager-tests;6.13.4 +io.fabric8:chaosmesh-client;6.13.4 +io.fabric8:chaosmesh-examples;6.13.4 +io.fabric8:chaosmesh-model;6.13.4 +io.fabric8:chaosmesh-tests;6.13.4 +io.fabric8:crd-generator-api;6.13.4 +io.fabric8:crd-generator-api-v2;6.13.4 +io.fabric8:crd-generator-apt;6.13.4 +io.fabric8:crd-generator-test;6.13.4 +io.fabric8:crd-generator-test-apt;6.13.4 +io.fabric8:generator-annotations;6.13.4 +io.fabric8:istio-client;6.13.4 +io.fabric8:istio-examples;6.13.4 +io.fabric8:istio-model-v1alpha3;6.13.4 +io.fabric8:istio-model-v1beta1;6.13.4 +io.fabric8:istio-tests;6.13.4 +io.fabric8:java-generator-benchmark;6.13.4 +io.fabric8:java-generator-cli;6.13.4 +io.fabric8:java-generator-core;6.13.4 +io.fabric8:java-generator-integration-tests;6.13.4 +io.fabric8:java-generator-maven-plugin;6.13.4 +io.fabric8:knative-client;6.13.4 +io.fabric8:knative-examples;6.13.4 +io.fabric8:knative-model;6.13.4 +io.fabric8:knative-tests;6.13.4 +io.fabric8:kube-api-test;6.13.4 +io.fabric8:kube-api-test-client-inject;6.13.4 +io.fabric8:kubernetes-client;6.13.4 +io.fabric8:kubernetes-client-api;6.13.4 +io.fabric8:kubernetes-client-bom;6.13.4 +io.fabric8:kubernetes-client-init-bc-fips;6.13.4 +io.fabric8:kubernetes-examples;6.13.4 +io.fabric8:kubernetes-httpclient-jdk;6.13.4 +io.fabric8:kubernetes-httpclient-jetty;6.13.4 +io.fabric8:kubernetes-httpclient-okhttp;6.13.4 +io.fabric8:kubernetes-httpclient-tests;6.13.4 +io.fabric8:kubernetes-httpclient-vertx;6.13.4 +io.fabric8:kubernetes-junit-jupiter;6.13.4 +io.fabric8:kubernetes-junit-jupiter-autodetected;6.13.4 +io.fabric8:kubernetes-log4j;6.13.4 +io.fabric8:kubernetes-model;6.13.4 +io.fabric8:kubernetes-model-admissionregistration;6.13.4 +io.fabric8:kubernetes-model-apiextensions;6.13.4 +io.fabric8:kubernetes-model-apps;6.13.4 +io.fabric8:kubernetes-model-autoscaling;6.13.4 +io.fabric8:kubernetes-model-batch;6.13.4 +io.fabric8:kubernetes-model-certificates;6.13.4 +io.fabric8:kubernetes-model-common;6.13.4 +io.fabric8:kubernetes-model-coordination;6.13.4 +io.fabric8:kubernetes-model-core;6.13.4 +io.fabric8:kubernetes-model-discovery;6.13.4 +io.fabric8:kubernetes-model-events;6.13.4 +io.fabric8:kubernetes-model-extensions;6.13.4 +io.fabric8:kubernetes-model-flowcontrol;6.13.4 +io.fabric8:kubernetes-model-gatewayapi;6.13.4 +io.fabric8:kubernetes-model-jsonschema2pojo;6.13.4 +io.fabric8:kubernetes-model-kustomize;6.13.4 +io.fabric8:kubernetes-model-metrics;6.13.4 +io.fabric8:kubernetes-model-networking;6.13.4 +io.fabric8:kubernetes-model-node;6.13.4 +io.fabric8:kubernetes-model-policy;6.13.4 +io.fabric8:kubernetes-model-rbac;6.13.4 +io.fabric8:kubernetes-model-resource;6.13.4 +io.fabric8:kubernetes-model-scheduling;6.13.4 +io.fabric8:kubernetes-model-storageclass;6.13.4 +io.fabric8:kubernetes-openshift-uberjar;6.13.4 +io.fabric8:kubernetes-server-mock;6.13.4 +io.fabric8:kubernetes-test;6.13.4 +io.fabric8:mockwebserver;6.13.4 +io.fabric8:open-cluster-management-agent-model;6.13.4 +io.fabric8:open-cluster-management-apps-model;6.13.4 +io.fabric8:open-cluster-management-client;6.13.4 +io.fabric8:open-cluster-management-cluster-model;6.13.4 +io.fabric8:open-cluster-management-discovery-model;6.13.4 +io.fabric8:open-cluster-management-observability-model;6.13.4 +io.fabric8:open-cluster-management-operator-model;6.13.4 +io.fabric8:open-cluster-management-placementruleapps-model;6.13.4 +io.fabric8:open-cluster-management-policy-model;6.13.4 +io.fabric8:open-cluster-management-search-model;6.13.4 +io.fabric8:open-cluster-management-tests;6.13.4 +io.fabric8:open-virtual-networking-client;6.13.4 +io.fabric8:open-virtual-networking-model-v1;6.13.4 +io.fabric8:open-virtual-networking-tests;6.13.4 +io.fabric8:openclustermanagement-examples;6.13.4 +io.fabric8:openshift-client;6.13.4 +io.fabric8:openshift-client-api;6.13.4 +io.fabric8:openshift-model;6.13.4 +io.fabric8:openshift-model-clusterautoscaling;6.13.4 +io.fabric8:openshift-model-config;6.13.4 +io.fabric8:openshift-model-console;6.13.4 +io.fabric8:openshift-model-hive;6.13.4 +io.fabric8:openshift-model-installer;6.13.4 +io.fabric8:openshift-model-machine;6.13.4 +io.fabric8:openshift-model-machineconfig;6.13.4 +io.fabric8:openshift-model-miscellaneous;6.13.4 +io.fabric8:openshift-model-monitoring;6.13.4 +io.fabric8:openshift-model-operator;6.13.4 +io.fabric8:openshift-model-operatorhub;6.13.4 +io.fabric8:openshift-model-storageversionmigrator;6.13.4 +io.fabric8:openshift-model-tuned;6.13.4 +io.fabric8:openshift-model-whereabouts;6.13.4 +io.fabric8:openshift-server-mock;6.13.4 +io.fabric8:service-catalog-examples;6.13.4 +io.fabric8:servicecatalog-client;6.13.4 +io.fabric8:servicecatalog-model;6.13.4 +io.fabric8:servicecatalog-tests;6.13.4 +io.fabric8:tekton-client;6.13.4 +io.fabric8:tekton-examples;6.13.4 +io.fabric8:tekton-model-triggers-v1alpha1;6.13.4 +io.fabric8:tekton-model-triggers-v1beta1;6.13.4 +io.fabric8:tekton-model-v1;6.13.4 +io.fabric8:tekton-model-v1alpha1;6.13.4 +io.fabric8:tekton-model-v1beta1;6.13.4 +io.fabric8:tekton-tests;6.13.4 +io.fabric8:verticalpodautoscaler-client;6.13.4 +io.fabric8:verticalpodautoscaler-examples;6.13.4 +io.fabric8:verticalpodautoscaler-model-v1;6.13.4 +io.fabric8:verticalpodautoscaler-tests;6.13.4 +io.fabric8:volcano-client;6.13.4 +io.fabric8:volcano-examples;6.13.4 +io.fabric8:volcano-model-v1beta1;6.13.4 +io.fabric8:volcano-tests;6.13.4 +io.fabric8:volumesnapshot-client;6.13.4 +io.fabric8:volumesnapshot-examples;6.13.4 +io.fabric8:volumesnapshot-model;6.13.4 +io.fabric8:volumesnapshot-tests;6.13.4 +io.github.git-commit-id:git-commit-id-maven-plugin;9.0.1 +io.github.openfeign:feign-annotation-error-decoder;13.5 +io.github.openfeign:feign-bom;13.5 +io.github.openfeign:feign-core;13.5 +io.github.openfeign:feign-dropwizard-metrics4;13.5 +io.github.openfeign:feign-dropwizard-metrics5;13.5 +io.github.openfeign:feign-fastjson2;13.5 +io.github.openfeign:feign-form;13.5 +io.github.openfeign:feign-form-spring;13.5 +io.github.openfeign:feign-googlehttpclient;13.5 +io.github.openfeign:feign-gson;13.5 +io.github.openfeign:feign-hc5;13.5 +io.github.openfeign:feign-httpclient;13.5 +io.github.openfeign:feign-hystrix;13.5 +io.github.openfeign:feign-jackson;13.5 +io.github.openfeign:feign-jackson-jaxb;13.5 +io.github.openfeign:feign-jackson-jr;13.5 +io.github.openfeign:feign-jakarta;13.5 +io.github.openfeign:feign-java11;13.5 +io.github.openfeign:feign-jaxb;13.5 +io.github.openfeign:feign-jaxb-jakarta;13.5 +io.github.openfeign:feign-jaxrs;13.5 +io.github.openfeign:feign-jaxrs2;13.5 +io.github.openfeign:feign-jaxrs3;13.5 +io.github.openfeign:feign-jaxrs4;13.5 +io.github.openfeign:feign-json;13.5 +io.github.openfeign:feign-kotlin;13.5 +io.github.openfeign:feign-micrometer;13.5 +io.github.openfeign:feign-mock;13.5 +io.github.openfeign:feign-moshi;13.5 +io.github.openfeign:feign-okhttp;13.5 +io.github.openfeign:feign-reactive-wrappers;13.5 +io.github.openfeign:feign-ribbon;13.5 +io.github.openfeign:feign-sax;13.5 +io.github.openfeign:feign-slf4j;13.5 +io.github.openfeign:feign-soap;13.5 +io.github.openfeign:feign-soap-jakarta;13.5 +io.github.openfeign:feign-spring;13.5 +io.github.resilience4j:resilience4j-all;2.2.0 +io.github.resilience4j:resilience4j-annotations;2.2.0 +io.github.resilience4j:resilience4j-bom;2.2.0 +io.github.resilience4j:resilience4j-bulkhead;2.2.0 +io.github.resilience4j:resilience4j-cache;2.2.0 +io.github.resilience4j:resilience4j-circuitbreaker;2.2.0 +io.github.resilience4j:resilience4j-circularbuffer;2.2.0 +io.github.resilience4j:resilience4j-consumer;2.2.0 +io.github.resilience4j:resilience4j-core;2.2.0 +io.github.resilience4j:resilience4j-feign;2.2.0 +io.github.resilience4j:resilience4j-kotlin;2.2.0 +io.github.resilience4j:resilience4j-metrics;2.2.0 +io.github.resilience4j:resilience4j-micrometer;2.2.0 +io.github.resilience4j:resilience4j-ratelimiter;2.2.0 +io.github.resilience4j:resilience4j-reactor;2.2.0 +io.github.resilience4j:resilience4j-retry;2.2.0 +io.github.resilience4j:resilience4j-rxjava2;2.2.0 +io.github.resilience4j:resilience4j-rxjava3;2.2.0 +io.github.resilience4j:resilience4j-spring;2.2.0 +io.github.resilience4j:resilience4j-spring-boot2;2.2.0 +io.github.resilience4j:resilience4j-spring-boot3;2.2.0 +io.github.resilience4j:resilience4j-spring-cloud2;2.2.0 +io.github.resilience4j:resilience4j-spring6;2.2.0 +io.github.resilience4j:resilience4j-timelimiter;2.2.0 +io.github.resilience4j:resilience4j-vavr;2.2.0 +io.kubernetes:client-java;19.0.1 +io.kubernetes:client-java-extended;19.0.1 +io.kubernetes:client-java-spring-integration;19.0.1 +io.lettuce:lettuce-core;6.4.2.RELEASE +io.micrometer:context-propagation;1.1.2 +io.micrometer:docs;1.4.2 +io.micrometer:micrometer-bom;1.14.3 +io.micrometer:micrometer-commons;1.14.3 +io.micrometer:micrometer-core;1.14.3 +io.micrometer:micrometer-jakarta9;1.14.3 +io.micrometer:micrometer-java11;1.14.3 +io.micrometer:micrometer-java21;1.14.3 +io.micrometer:micrometer-jetty11;1.14.3 +io.micrometer:micrometer-jetty12;1.14.3 +io.micrometer:micrometer-observation;1.14.3 +io.micrometer:micrometer-observation-test;1.14.3 +io.micrometer:micrometer-registry-appoptics;1.14.3 +io.micrometer:micrometer-registry-atlas;1.14.3 +io.micrometer:micrometer-registry-azure-monitor;1.14.3 +io.micrometer:micrometer-registry-cloudwatch2;1.14.3 +io.micrometer:micrometer-registry-datadog;1.14.3 +io.micrometer:micrometer-registry-dynatrace;1.14.3 +io.micrometer:micrometer-registry-elastic;1.14.3 +io.micrometer:micrometer-registry-ganglia;1.14.3 +io.micrometer:micrometer-registry-graphite;1.14.3 +io.micrometer:micrometer-registry-health;1.14.3 +io.micrometer:micrometer-registry-humio;1.14.3 +io.micrometer:micrometer-registry-influx;1.14.3 +io.micrometer:micrometer-registry-jmx;1.14.3 +io.micrometer:micrometer-registry-kairos;1.14.3 +io.micrometer:micrometer-registry-new-relic;1.14.3 +io.micrometer:micrometer-registry-opentsdb;1.14.3 +io.micrometer:micrometer-registry-otlp;1.14.3 +io.micrometer:micrometer-registry-prometheus;1.14.3 +io.micrometer:micrometer-registry-prometheus-simpleclient;1.14.3 +io.micrometer:micrometer-registry-signalfx;1.14.3 +io.micrometer:micrometer-registry-stackdriver;1.14.3 +io.micrometer:micrometer-registry-statsd;1.14.3 +io.micrometer:micrometer-registry-wavefront;1.14.3 +io.micrometer:micrometer-test;1.14.3 +io.micrometer:micrometer-tracing;1.4.2 +io.micrometer:micrometer-tracing-bom;1.4.2 +io.micrometer:micrometer-tracing-bridge-brave;1.4.2 +io.micrometer:micrometer-tracing-bridge-otel;1.4.2 +io.micrometer:micrometer-tracing-integration-test;1.4.2 +io.micrometer:micrometer-tracing-reporter-wavefront;1.4.2 +io.micrometer:micrometer-tracing-test;1.4.2 +io.netty:netty-all;4.1.117.Final +io.netty:netty-bom;4.1.117.Final +io.netty:netty-buffer;4.1.117.Final +io.netty:netty-codec;4.1.117.Final +io.netty:netty-codec-dns;4.1.117.Final +io.netty:netty-codec-haproxy;4.1.117.Final +io.netty:netty-codec-http;4.1.117.Final +io.netty:netty-codec-http2;4.1.117.Final +io.netty:netty-codec-memcache;4.1.117.Final +io.netty:netty-codec-mqtt;4.1.117.Final +io.netty:netty-codec-redis;4.1.117.Final +io.netty:netty-codec-smtp;4.1.117.Final +io.netty:netty-codec-socks;4.1.117.Final +io.netty:netty-codec-stomp;4.1.117.Final +io.netty:netty-codec-xml;4.1.117.Final +io.netty:netty-common;4.1.117.Final +io.netty:netty-dev-tools;4.1.117.Final +io.netty:netty-example;4.1.117.Final +io.netty:netty-handler;4.1.117.Final +io.netty:netty-handler-proxy;4.1.117.Final +io.netty:netty-handler-ssl-ocsp;4.1.117.Final +io.netty:netty-resolver;4.1.117.Final +io.netty:netty-resolver-dns;4.1.117.Final +io.netty:netty-resolver-dns-classes-macos;4.1.117.Final +io.netty:netty-resolver-dns-native-macos;4.1.117.Final +io.netty:netty-tcnative;2.0.69.Final +io.netty:netty-tcnative-boringssl-static;2.0.69.Final +io.netty:netty-tcnative-classes;2.0.69.Final +io.netty:netty-transport;4.1.117.Final +io.netty:netty-transport-classes-epoll;4.1.117.Final +io.netty:netty-transport-classes-kqueue;4.1.117.Final +io.netty:netty-transport-native-epoll;4.1.117.Final +io.netty:netty-transport-native-kqueue;4.1.117.Final +io.netty:netty-transport-native-unix-common;4.1.117.Final +io.netty:netty-transport-rxtx;4.1.117.Final +io.netty:netty-transport-sctp;4.1.117.Final +io.netty:netty-transport-udt;4.1.117.Final +io.opentelemetry:opentelemetry-api;1.43.0 +io.opentelemetry:opentelemetry-bom;1.43.0 +io.opentelemetry:opentelemetry-context;1.43.0 +io.opentelemetry:opentelemetry-exporter-common;1.43.0 +io.opentelemetry:opentelemetry-exporter-logging;1.43.0 +io.opentelemetry:opentelemetry-exporter-logging-otlp;1.43.0 +io.opentelemetry:opentelemetry-exporter-otlp;1.43.0 +io.opentelemetry:opentelemetry-exporter-otlp-common;1.43.0 +io.opentelemetry:opentelemetry-exporter-sender-grpc-managed-channel;1.43.0 +io.opentelemetry:opentelemetry-exporter-sender-jdk;1.43.0 +io.opentelemetry:opentelemetry-exporter-sender-okhttp;1.43.0 +io.opentelemetry:opentelemetry-exporter-zipkin;1.43.0 +io.opentelemetry:opentelemetry-extension-kotlin;1.43.0 +io.opentelemetry:opentelemetry-extension-trace-propagators;1.43.0 +io.opentelemetry:opentelemetry-opentracing-shim;1.43.0 +io.opentelemetry:opentelemetry-sdk;1.43.0 +io.opentelemetry:opentelemetry-sdk-common;1.43.0 +io.opentelemetry:opentelemetry-sdk-extension-autoconfigure;1.43.0 +io.opentelemetry:opentelemetry-sdk-extension-autoconfigure-spi;1.43.0 +io.opentelemetry:opentelemetry-sdk-extension-jaeger-remote-sampler;1.43.0 +io.opentelemetry:opentelemetry-sdk-logs;1.43.0 +io.opentelemetry:opentelemetry-sdk-metrics;1.43.0 +io.opentelemetry:opentelemetry-sdk-testing;1.43.0 +io.opentelemetry:opentelemetry-sdk-trace;1.43.0 +io.projectreactor.addons:reactor-adapter;3.5.2 +io.projectreactor.addons:reactor-extra;3.5.2 +io.projectreactor.addons:reactor-pool;1.1.1 +io.projectreactor.addons:reactor-pool-micrometer;0.2.1 +io.projectreactor.kafka:reactor-kafka;1.3.23 +io.projectreactor.kotlin:reactor-kotlin-extensions;1.2.3 +io.projectreactor.netty:reactor-netty;1.2.2 +io.projectreactor.netty:reactor-netty-core;1.2.2 +io.projectreactor.netty:reactor-netty-http;1.2.2 +io.projectreactor.netty:reactor-netty-http-brave;1.2.2 +io.projectreactor:reactor-bom;2024.0.2 +io.projectreactor:reactor-core;3.7.2 +io.projectreactor:reactor-core-micrometer;1.2.2 +io.projectreactor:reactor-test;3.7.2 +io.projectreactor:reactor-tools;3.7.2 +io.prometheus:prometheus-metrics-bom;1.3.5 +io.prometheus:prometheus-metrics-config;1.3.5 +io.prometheus:prometheus-metrics-core;1.3.5 +io.prometheus:prometheus-metrics-exporter-common;1.3.5 +io.prometheus:prometheus-metrics-exporter-httpserver;1.3.5 +io.prometheus:prometheus-metrics-exporter-opentelemetry;1.3.5 +io.prometheus:prometheus-metrics-exporter-pushgateway;1.3.5 +io.prometheus:prometheus-metrics-exporter-servlet-jakarta;1.3.5 +io.prometheus:prometheus-metrics-exporter-servlet-javax;1.3.5 +io.prometheus:prometheus-metrics-exposition-formats;1.3.5 +io.prometheus:prometheus-metrics-instrumentation-caffeine;1.3.5 +io.prometheus:prometheus-metrics-instrumentation-dropwizard5;1.3.5 +io.prometheus:prometheus-metrics-instrumentation-guava;1.3.5 +io.prometheus:prometheus-metrics-instrumentation-jvm;1.3.5 +io.prometheus:prometheus-metrics-model;1.3.5 +io.prometheus:prometheus-metrics-simpleclient-bridge;1.3.5 +io.prometheus:prometheus-metrics-tracer;1.3.5 +io.prometheus:prometheus-metrics-tracer-common;1.3.5 +io.prometheus:prometheus-metrics-tracer-initializer;1.3.5 +io.prometheus:prometheus-metrics-tracer-otel;1.3.5 +io.prometheus:prometheus-metrics-tracer-otel-agent;1.3.5 +io.prometheus:simpleclient;0.16.0 +io.prometheus:simpleclient_bom;0.16.0 +io.prometheus:simpleclient_caffeine;0.16.0 +io.prometheus:simpleclient_common;0.16.0 +io.prometheus:simpleclient_dropwizard;0.16.0 +io.prometheus:simpleclient_graphite_bridge;0.16.0 +io.prometheus:simpleclient_guava;0.16.0 +io.prometheus:simpleclient_hibernate;0.16.0 +io.prometheus:simpleclient_hotspot;0.16.0 +io.prometheus:simpleclient_httpserver;0.16.0 +io.prometheus:simpleclient_jetty;0.16.0 +io.prometheus:simpleclient_jetty_jdk8;0.16.0 +io.prometheus:simpleclient_log4j;0.16.0 +io.prometheus:simpleclient_log4j2;0.16.0 +io.prometheus:simpleclient_logback;0.16.0 +io.prometheus:simpleclient_pushgateway;0.16.0 +io.prometheus:simpleclient_servlet;0.16.0 +io.prometheus:simpleclient_servlet_jakarta;0.16.0 +io.prometheus:simpleclient_spring_boot;0.16.0 +io.prometheus:simpleclient_spring_web;0.16.0 +io.prometheus:simpleclient_tracer_common;0.16.0 +io.prometheus:simpleclient_tracer_otel;0.16.0 +io.prometheus:simpleclient_tracer_otel_agent;0.16.0 +io.prometheus:simpleclient_vertx;0.16.0 +io.r2dbc:r2dbc-h2;1.0.0.RELEASE +io.r2dbc:r2dbc-mssql;1.0.2.RELEASE +io.r2dbc:r2dbc-pool;1.0.2.RELEASE +io.r2dbc:r2dbc-proxy;1.1.5.RELEASE +io.r2dbc:r2dbc-spi;1.0.0.RELEASE +io.reactivex.rxjava3:rxjava;3.1.10 +io.rest-assured:json-path;5.5.0 +io.rest-assured:json-schema-validator;5.5.0 +io.rest-assured:kotlin-extensions;5.5.0 +io.rest-assured:rest-assured;5.5.0 +io.rest-assured:rest-assured-all;5.5.0 +io.rest-assured:rest-assured-bom;5.5.0 +io.rest-assured:rest-assured-common;5.5.0 +io.rest-assured:scala-extensions;5.5.0 +io.rest-assured:scala-support;5.5.0 +io.rest-assured:spring-commons;5.5.0 +io.rest-assured:spring-mock-mvc;5.5.0 +io.rest-assured:spring-mock-mvc-kotlin-extensions;5.5.0 +io.rest-assured:spring-web-test-client;5.5.0 +io.rest-assured:spring-web-test-client-kotlin-extensions;5.5.0 +io.rest-assured:xml-path;5.5.0 +io.rsocket:rsocket-bom;1.1.3 +io.rsocket:rsocket-core;1.1.3 +io.rsocket:rsocket-load-balancer;1.1.3 +io.rsocket:rsocket-micrometer;1.1.3 +io.rsocket:rsocket-test;1.1.3 +io.rsocket:rsocket-transport-local;1.1.3 +io.rsocket:rsocket-transport-netty;1.1.3 +io.spring.gradle:dependency-management-plugin;1.1.7 +io.undertow:undertow-core;2.3.18.Final +io.undertow:undertow-servlet;2.3.18.Final +io.undertow:undertow-websockets-jsr;2.3.18.Final +io.zipkin.brave:brave;6.0.3 +io.zipkin.brave:brave-bom;6.0.3 +io.zipkin.brave:brave-context-jfr;6.0.3 +io.zipkin.brave:brave-context-log4j12;6.0.3 +io.zipkin.brave:brave-context-log4j2;6.0.3 +io.zipkin.brave:brave-context-slf4j;6.0.3 +io.zipkin.brave:brave-instrumentation-benchmarks;6.0.3 +io.zipkin.brave:brave-instrumentation-dubbo;6.0.3 +io.zipkin.brave:brave-instrumentation-grpc;6.0.3 +io.zipkin.brave:brave-instrumentation-http;6.0.3 +io.zipkin.brave:brave-instrumentation-http-tests;6.0.3 +io.zipkin.brave:brave-instrumentation-http-tests-jakarta;6.0.3 +io.zipkin.brave:brave-instrumentation-httpasyncclient;6.0.3 +io.zipkin.brave:brave-instrumentation-httpclient;6.0.3 +io.zipkin.brave:brave-instrumentation-httpclient5;6.0.3 +io.zipkin.brave:brave-instrumentation-jakarta-jms;6.0.3 +io.zipkin.brave:brave-instrumentation-jaxrs2;6.0.3 +io.zipkin.brave:brave-instrumentation-jersey-server;6.0.3 +io.zipkin.brave:brave-instrumentation-jms;6.0.3 +io.zipkin.brave:brave-instrumentation-jms-jakarta;6.0.3 +io.zipkin.brave:brave-instrumentation-kafka-clients;6.0.3 +io.zipkin.brave:brave-instrumentation-kafka-streams;6.0.3 +io.zipkin.brave:brave-instrumentation-messaging;6.0.3 +io.zipkin.brave:brave-instrumentation-mongodb;6.0.3 +io.zipkin.brave:brave-instrumentation-mysql;6.0.3 +io.zipkin.brave:brave-instrumentation-mysql6;6.0.3 +io.zipkin.brave:brave-instrumentation-mysql8;6.0.3 +io.zipkin.brave:brave-instrumentation-netty-codec-http;6.0.3 +io.zipkin.brave:brave-instrumentation-okhttp3;6.0.3 +io.zipkin.brave:brave-instrumentation-rpc;6.0.3 +io.zipkin.brave:brave-instrumentation-servlet;6.0.3 +io.zipkin.brave:brave-instrumentation-servlet-jakarta;6.0.3 +io.zipkin.brave:brave-instrumentation-spring-rabbit;6.0.3 +io.zipkin.brave:brave-instrumentation-spring-web;6.0.3 +io.zipkin.brave:brave-instrumentation-spring-webmvc;6.0.3 +io.zipkin.brave:brave-instrumentation-vertx-web;6.0.3 +io.zipkin.brave:brave-spring-beans;6.0.3 +io.zipkin.brave:brave-tests;6.0.3 +io.zipkin.reporter2:zipkin-reporter;3.4.3 +io.zipkin.reporter2:zipkin-reporter-bom;3.4.3 +io.zipkin.reporter2:zipkin-reporter-brave;3.4.3 +io.zipkin.reporter2:zipkin-reporter-metrics-micrometer;3.4.3 +io.zipkin.reporter2:zipkin-reporter-spring-beans;3.4.3 +io.zipkin.reporter2:zipkin-sender-activemq-client;3.4.3 +io.zipkin.reporter2:zipkin-sender-amqp-client;3.4.3 +io.zipkin.reporter2:zipkin-sender-kafka;3.4.3 +io.zipkin.reporter2:zipkin-sender-libthrift;3.4.3 +io.zipkin.reporter2:zipkin-sender-okhttp3;3.4.3 +io.zipkin.reporter2:zipkin-sender-urlconnection;3.4.3 +io.zipkin.zipkin2:zipkin;2.27.1 +jakarta.activation:jakarta.activation-api;2.1.3 +jakarta.annotation:jakarta.annotation-api;2.1.1 +jakarta.inject:jakarta.inject-api;2.0.1 +jakarta.jms:jakarta.jms-api;3.1.0 +jakarta.json.bind:jakarta.json.bind-api;3.0.1 +jakarta.json:jakarta.json-api;2.1.3 +jakarta.mail:jakarta.mail-api;2.1.3 +jakarta.management.j2ee:jakarta.management.j2ee-api;1.1.4 +jakarta.persistence:jakarta.persistence-api;3.1.0 +jakarta.servlet.jsp.jstl:jakarta.servlet.jsp.jstl-api;3.0.2 +jakarta.servlet:jakarta.servlet-api;6.0.0 +jakarta.transaction:jakarta.transaction-api;2.0.1 +jakarta.validation:jakarta.validation-api;3.0.2 +jakarta.websocket:jakarta.websocket-api;2.1.1 +jakarta.websocket:jakarta.websocket-client-api;2.1.1 +jakarta.ws.rs:jakarta.ws.rs-api;3.1.0 +jakarta.xml.bind:jakarta.xml.bind-api;4.0.2 +jakarta.xml.soap:jakarta.xml.soap-api;3.0.2 +jakarta.xml.ws:jakarta.xml.ws-api;4.0.2 +javax.cache:cache-api;1.1.1 +javax.money:money-api;1.1 +jaxen:jaxen;2.0.0 +junit:junit;4.13.2 +net.bytebuddy:byte-buddy;1.15.11 +net.bytebuddy:byte-buddy-agent;1.15.11 +net.minidev:json-smart;2.5.1 +net.sourceforge.jtds:jtds;1.3.1 +net.sourceforge.nekohtml:nekohtml;1.9.22 +nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect;3.3.0 +org.apache.activemq:activemq-all;6.1.5 +org.apache.activemq:activemq-amqp;6.1.5 +org.apache.activemq:activemq-blueprint;6.1.5 +org.apache.activemq:activemq-bom;6.1.5 +org.apache.activemq:activemq-branding;2.37.0 +org.apache.activemq:activemq-broker;6.1.5 +org.apache.activemq:activemq-client;6.1.5 +org.apache.activemq:activemq-console;6.1.5 +org.apache.activemq:activemq-http;6.1.5 +org.apache.activemq:activemq-jaas;6.1.5 +org.apache.activemq:activemq-jdbc-store;6.1.5 +org.apache.activemq:activemq-jms-pool;6.1.5 +org.apache.activemq:activemq-kahadb-store;6.1.5 +org.apache.activemq:activemq-karaf;6.1.5 +org.apache.activemq:activemq-log4j-appender;6.1.5 +org.apache.activemq:activemq-mqtt;6.1.5 +org.apache.activemq:activemq-openwire-generator;6.1.5 +org.apache.activemq:activemq-openwire-legacy;6.1.5 +org.apache.activemq:activemq-osgi;6.1.5 +org.apache.activemq:activemq-pool;6.1.5 +org.apache.activemq:activemq-ra;6.1.5 +org.apache.activemq:activemq-rar;6.1.5 +org.apache.activemq:activemq-run;6.1.5 +org.apache.activemq:activemq-runtime-config;6.1.5 +org.apache.activemq:activemq-shiro;6.1.5 +org.apache.activemq:activemq-spring;6.1.5 +org.apache.activemq:activemq-stomp;6.1.5 +org.apache.activemq:activemq-web;6.1.5 +org.apache.activemq:activemq-web-console;6.1.5 +org.apache.activemq:activemq-web-demo;6.1.5 +org.apache.activemq:artemis-amqp-protocol;2.37.0 +org.apache.activemq:artemis-bom;2.37.0 +org.apache.activemq:artemis-boot;2.37.0 +org.apache.activemq:artemis-cdi-client;2.37.0 +org.apache.activemq:artemis-cli;2.37.0 +org.apache.activemq:artemis-commons;2.37.0 +org.apache.activemq:artemis-console;2.37.0 +org.apache.activemq:artemis-core-client;2.37.0 +org.apache.activemq:artemis-core-client-all;2.37.0 +org.apache.activemq:artemis-core-client-osgi;2.37.0 +org.apache.activemq:artemis-dto;2.37.0 +org.apache.activemq:artemis-features;2.37.0 +org.apache.activemq:artemis-hornetq-protocol;2.37.0 +org.apache.activemq:artemis-hqclient-protocol;2.37.0 +org.apache.activemq:artemis-jakarta-client;2.37.0 +org.apache.activemq:artemis-jakarta-client-all;2.37.0 +org.apache.activemq:artemis-jakarta-openwire-protocol;2.37.0 +org.apache.activemq:artemis-jakarta-ra;2.37.0 +org.apache.activemq:artemis-jakarta-server;2.37.0 +org.apache.activemq:artemis-jakarta-service-extensions;2.37.0 +org.apache.activemq:artemis-jdbc-store;2.37.0 +org.apache.activemq:artemis-jms-client;2.37.0 +org.apache.activemq:artemis-jms-client-all;2.37.0 +org.apache.activemq:artemis-jms-client-osgi;2.37.0 +org.apache.activemq:artemis-jms-server;2.37.0 +org.apache.activemq:artemis-journal;2.37.0 +org.apache.activemq:artemis-lockmanager-api;2.37.0 +org.apache.activemq:artemis-lockmanager-ri;2.37.0 +org.apache.activemq:artemis-mqtt-protocol;2.37.0 +org.apache.activemq:artemis-openwire-protocol;2.37.0 +org.apache.activemq:artemis-plugin;2.37.0 +org.apache.activemq:artemis-ra;2.37.0 +org.apache.activemq:artemis-selector;2.37.0 +org.apache.activemq:artemis-server;2.37.0 +org.apache.activemq:artemis-server-osgi;2.37.0 +org.apache.activemq:artemis-service-extensions;2.37.0 +org.apache.activemq:artemis-stomp-protocol;2.37.0 +org.apache.activemq:artemis-web;2.37.0 +org.apache.activemq:artemis-website;2.37.0 +org.apache.cassandra:java-driver-bom;4.18.1 +org.apache.cassandra:java-driver-core;4.18.1 +org.apache.cassandra:java-driver-core-shaded;4.18.1 +org.apache.cassandra:java-driver-mapper-processor;4.18.1 +org.apache.cassandra:java-driver-mapper-runtime;4.18.1 +org.apache.cassandra:java-driver-metrics-micrometer;4.18.1 +org.apache.cassandra:java-driver-metrics-microprofile;4.18.1 +org.apache.cassandra:java-driver-query-builder;4.18.1 +org.apache.cassandra:java-driver-test-infra;4.18.1 +org.apache.commons:commons-dbcp2;2.12.0 +org.apache.commons:commons-lang3;3.17.0 +org.apache.commons:commons-pool2;2.12.0 +org.apache.curator:curator-framework;5.7.1 +org.apache.curator:curator-recipes;5.7.1 +org.apache.curator:curator-test;5.7.1 +org.apache.curator:curator-x-discovery;5.7.1 +org.apache.derby:derby;10.16.1.1 +org.apache.derby:derbyclient;10.16.1.1 +org.apache.derby:derbynet;10.16.1.1 +org.apache.derby:derbyoptionaltools;10.16.1.1 +org.apache.derby:derbyshared;10.16.1.1 +org.apache.derby:derbytools;10.16.1.1 +org.apache.groovy:groovy;4.0.24 +org.apache.groovy:groovy-ant;4.0.24 +org.apache.groovy:groovy-astbuilder;4.0.24 +org.apache.groovy:groovy-bom;4.0.24 +org.apache.groovy:groovy-cli-commons;4.0.24 +org.apache.groovy:groovy-cli-picocli;4.0.24 +org.apache.groovy:groovy-console;4.0.24 +org.apache.groovy:groovy-contracts;4.0.24 +org.apache.groovy:groovy-datetime;4.0.24 +org.apache.groovy:groovy-dateutil;4.0.24 +org.apache.groovy:groovy-docgenerator;4.0.24 +org.apache.groovy:groovy-ginq;4.0.24 +org.apache.groovy:groovy-groovydoc;4.0.24 +org.apache.groovy:groovy-groovysh;4.0.24 +org.apache.groovy:groovy-jmx;4.0.24 +org.apache.groovy:groovy-json;4.0.24 +org.apache.groovy:groovy-jsr223;4.0.24 +org.apache.groovy:groovy-macro;4.0.24 +org.apache.groovy:groovy-macro-library;4.0.24 +org.apache.groovy:groovy-nio;4.0.24 +org.apache.groovy:groovy-servlet;4.0.24 +org.apache.groovy:groovy-sql;4.0.24 +org.apache.groovy:groovy-swing;4.0.24 +org.apache.groovy:groovy-templates;4.0.24 +org.apache.groovy:groovy-test;4.0.24 +org.apache.groovy:groovy-test-junit5;4.0.24 +org.apache.groovy:groovy-testng;4.0.24 +org.apache.groovy:groovy-toml;4.0.24 +org.apache.groovy:groovy-typecheckers;4.0.24 +org.apache.groovy:groovy-xml;4.0.24 +org.apache.groovy:groovy-yaml;4.0.24 +org.apache.httpcomponents.client5:httpclient5;5.4.1 +org.apache.httpcomponents.client5:httpclient5-cache;5.4.1 +org.apache.httpcomponents.client5:httpclient5-fluent;5.4.1 +org.apache.httpcomponents.core5:httpcore5;5.3.2 +org.apache.httpcomponents.core5:httpcore5-h2;5.3.2 +org.apache.httpcomponents.core5:httpcore5-reactive;5.3.2 +org.apache.httpcomponents:httpasyncclient;4.1.5 +org.apache.httpcomponents:httpcore;4.4.16 +org.apache.httpcomponents:httpcore-nio;4.4.16 +org.apache.kafka:connect;3.8.1 +org.apache.kafka:connect-api;3.8.1 +org.apache.kafka:connect-basic-auth-extension;3.8.1 +org.apache.kafka:connect-file;3.8.1 +org.apache.kafka:connect-json;3.8.1 +org.apache.kafka:connect-mirror;3.8.1 +org.apache.kafka:connect-mirror-client;3.8.1 +org.apache.kafka:connect-runtime;3.8.1 +org.apache.kafka:connect-transforms;3.8.1 +org.apache.kafka:generator;3.8.1 +org.apache.kafka:kafka-clients;3.8.1 +org.apache.kafka:kafka-log4j-appender;3.8.1 +org.apache.kafka:kafka-metadata;3.8.1 +org.apache.kafka:kafka-raft;3.8.1 +org.apache.kafka:kafka-server;3.8.1 +org.apache.kafka:kafka-server-common;3.8.1 +org.apache.kafka:kafka-shell;3.8.1 +org.apache.kafka:kafka-storage;3.8.1 +org.apache.kafka:kafka-storage-api;3.8.1 +org.apache.kafka:kafka-streams;3.8.1 +org.apache.kafka:kafka-streams-scala_2.12;3.8.1 +org.apache.kafka:kafka-streams-scala_2.13;3.8.1 +org.apache.kafka:kafka-streams-test-utils;3.8.1 +org.apache.kafka:kafka-tools;3.8.1 +org.apache.kafka:kafka_2.12;3.8.1 +org.apache.kafka:kafka_2.13;3.8.1 +org.apache.kafka:trogdor;3.8.1 +org.apache.logging.log4j:log4j-1.2-api;2.24.3 +org.apache.logging.log4j:log4j-api;2.24.3 +org.apache.logging.log4j:log4j-api-test;2.24.3 +org.apache.logging.log4j:log4j-appserver;2.24.3 +org.apache.logging.log4j:log4j-bom;2.24.3 +org.apache.logging.log4j:log4j-cassandra;2.24.3 +org.apache.logging.log4j:log4j-core;2.24.3 +org.apache.logging.log4j:log4j-core-test;2.24.3 +org.apache.logging.log4j:log4j-couchdb;2.24.3 +org.apache.logging.log4j:log4j-docker;2.24.3 +org.apache.logging.log4j:log4j-flume-ng;2.23.1 +org.apache.logging.log4j:log4j-iostreams;2.24.3 +org.apache.logging.log4j:log4j-jakarta-smtp;2.24.3 +org.apache.logging.log4j:log4j-jakarta-web;2.24.3 +org.apache.logging.log4j:log4j-jcl;2.24.3 +org.apache.logging.log4j:log4j-jpa;2.24.3 +org.apache.logging.log4j:log4j-jpl;2.24.3 +org.apache.logging.log4j:log4j-jul;2.24.3 +org.apache.logging.log4j:log4j-layout-template-json;2.24.3 +org.apache.logging.log4j:log4j-mongodb;2.24.3 +org.apache.logging.log4j:log4j-mongodb4;2.24.3 +org.apache.logging.log4j:log4j-slf4j-impl;2.24.3 +org.apache.logging.log4j:log4j-slf4j2-impl;2.24.3 +org.apache.logging.log4j:log4j-spring-boot;2.24.3 +org.apache.logging.log4j:log4j-spring-cloud-config-client;2.24.3 +org.apache.logging.log4j:log4j-taglib;2.24.3 +org.apache.logging.log4j:log4j-to-jul;2.24.3 +org.apache.logging.log4j:log4j-to-slf4j;2.24.3 +org.apache.logging.log4j:log4j-web;2.24.3 +org.apache.maven.plugins:maven-antrun-plugin;3.1.0 +org.apache.maven.plugins:maven-assembly-plugin;3.7.1 +org.apache.maven.plugins:maven-clean-plugin;3.4.0 +org.apache.maven.plugins:maven-compiler-plugin;3.13.0 +org.apache.maven.plugins:maven-dependency-plugin;3.8.1 +org.apache.maven.plugins:maven-deploy-plugin;3.1.3 +org.apache.maven.plugins:maven-enforcer-plugin;3.5.0 +org.apache.maven.plugins:maven-failsafe-plugin;3.5.2 +org.apache.maven.plugins:maven-gpg-plugin;3.1.0 +org.apache.maven.plugins:maven-help-plugin;3.5.1 +org.apache.maven.plugins:maven-install-plugin;3.1.3 +org.apache.maven.plugins:maven-invoker-plugin;3.8.1 +org.apache.maven.plugins:maven-jar-plugin;3.4.2 +org.apache.maven.plugins:maven-javadoc-plugin;3.10.1 +org.apache.maven.plugins:maven-release-plugin;2.5.3 +org.apache.maven.plugins:maven-resources-plugin;3.3.1 +org.apache.maven.plugins:maven-shade-plugin;3.6.0 +org.apache.maven.plugins:maven-source-plugin;3.3.1 +org.apache.maven.plugins:maven-surefire-plugin;3.5.2 +org.apache.maven.plugins:maven-war-plugin;3.4.0 +org.apache.pulsar:bouncy-castle-bc;3.3.4 +org.apache.pulsar:bouncy-castle-bcfips;3.3.4 +org.apache.pulsar:bouncy-castle-parent;3.3.4 +org.apache.pulsar:buildtools;3.3.4 +org.apache.pulsar:distribution;3.3.4 +org.apache.pulsar:docker-images;3.3.4 +org.apache.pulsar:jclouds-shaded;3.3.4 +org.apache.pulsar:managed-ledger;3.3.4 +org.apache.pulsar:pulsar;3.3.4 +org.apache.pulsar:pulsar-all-docker-image;3.3.4 +org.apache.pulsar:pulsar-bom;3.3.4 +org.apache.pulsar:pulsar-broker;3.3.4 +org.apache.pulsar:pulsar-broker-auth-athenz;3.3.4 +org.apache.pulsar:pulsar-broker-auth-oidc;3.3.4 +org.apache.pulsar:pulsar-broker-auth-sasl;3.3.4 +org.apache.pulsar:pulsar-broker-common;3.3.4 +org.apache.pulsar:pulsar-cli-utils;3.3.4 +org.apache.pulsar:pulsar-client;3.3.4 +org.apache.pulsar:pulsar-client-1x;3.3.4 +org.apache.pulsar:pulsar-client-1x-base;3.3.4 +org.apache.pulsar:pulsar-client-2x-shaded;3.3.4 +org.apache.pulsar:pulsar-client-admin;3.3.4 +org.apache.pulsar:pulsar-client-admin-api;3.3.4 +org.apache.pulsar:pulsar-client-admin-original;3.3.4 +org.apache.pulsar:pulsar-client-all;3.3.4 +org.apache.pulsar:pulsar-client-api;3.3.4 +org.apache.pulsar:pulsar-client-auth-athenz;3.3.4 +org.apache.pulsar:pulsar-client-auth-sasl;3.3.4 +org.apache.pulsar:pulsar-client-messagecrypto-bc;3.3.4 +org.apache.pulsar:pulsar-client-original;3.3.4 +org.apache.pulsar:pulsar-client-reactive-adapter;0.5.10 +org.apache.pulsar:pulsar-client-reactive-api;0.5.10 +org.apache.pulsar:pulsar-client-reactive-jackson;0.5.10 +org.apache.pulsar:pulsar-client-reactive-producer-cache-caffeine;0.5.10 +org.apache.pulsar:pulsar-client-reactive-producer-cache-caffeine-shaded;0.5.10 +org.apache.pulsar:pulsar-client-tools;3.3.4 +org.apache.pulsar:pulsar-client-tools-api;3.3.4 +org.apache.pulsar:pulsar-common;3.3.4 +org.apache.pulsar:pulsar-config-validation;3.3.4 +org.apache.pulsar:pulsar-docker-image;3.3.4 +org.apache.pulsar:pulsar-docs-tools;3.3.4 +org.apache.pulsar:pulsar-functions;3.3.4 +org.apache.pulsar:pulsar-functions-api;3.3.4 +org.apache.pulsar:pulsar-functions-api-examples;3.3.4 +org.apache.pulsar:pulsar-functions-api-examples-builtin;3.3.4 +org.apache.pulsar:pulsar-functions-instance;3.3.4 +org.apache.pulsar:pulsar-functions-local-runner;3.3.4 +org.apache.pulsar:pulsar-functions-local-runner-original;3.3.4 +org.apache.pulsar:pulsar-functions-proto;3.3.4 +org.apache.pulsar:pulsar-functions-runtime;3.3.4 +org.apache.pulsar:pulsar-functions-runtime-all;3.3.4 +org.apache.pulsar:pulsar-functions-secrets;3.3.4 +org.apache.pulsar:pulsar-functions-utils;3.3.4 +org.apache.pulsar:pulsar-functions-worker;3.3.4 +org.apache.pulsar:pulsar-io;3.3.4 +org.apache.pulsar:pulsar-io-aerospike;3.3.4 +org.apache.pulsar:pulsar-io-alluxio;3.3.4 +org.apache.pulsar:pulsar-io-aws;3.3.4 +org.apache.pulsar:pulsar-io-batch-data-generator;3.3.4 +org.apache.pulsar:pulsar-io-batch-discovery-triggerers;3.3.4 +org.apache.pulsar:pulsar-io-canal;3.3.4 +org.apache.pulsar:pulsar-io-cassandra;3.3.4 +org.apache.pulsar:pulsar-io-common;3.3.4 +org.apache.pulsar:pulsar-io-core;3.3.4 +org.apache.pulsar:pulsar-io-data-generator;3.3.4 +org.apache.pulsar:pulsar-io-debezium;3.3.4 +org.apache.pulsar:pulsar-io-debezium-core;3.3.4 +org.apache.pulsar:pulsar-io-debezium-mongodb;3.3.4 +org.apache.pulsar:pulsar-io-debezium-mssql;3.3.4 +org.apache.pulsar:pulsar-io-debezium-mysql;3.3.4 +org.apache.pulsar:pulsar-io-debezium-oracle;3.3.4 +org.apache.pulsar:pulsar-io-debezium-postgres;3.3.4 +org.apache.pulsar:pulsar-io-distribution;3.3.4 +org.apache.pulsar:pulsar-io-docs;3.3.4 +org.apache.pulsar:pulsar-io-dynamodb;3.3.4 +org.apache.pulsar:pulsar-io-elastic-search;3.3.4 +org.apache.pulsar:pulsar-io-file;3.3.4 +org.apache.pulsar:pulsar-io-flume;3.3.4 +org.apache.pulsar:pulsar-io-hbase;3.3.4 +org.apache.pulsar:pulsar-io-hdfs3;3.3.4 +org.apache.pulsar:pulsar-io-http;3.3.4 +org.apache.pulsar:pulsar-io-influxdb;3.3.4 +org.apache.pulsar:pulsar-io-jdbc;3.3.4 +org.apache.pulsar:pulsar-io-jdbc-clickhouse;3.3.4 +org.apache.pulsar:pulsar-io-jdbc-core;3.3.4 +org.apache.pulsar:pulsar-io-jdbc-mariadb;3.3.4 +org.apache.pulsar:pulsar-io-jdbc-openmldb;3.3.4 +org.apache.pulsar:pulsar-io-jdbc-postgres;3.3.4 +org.apache.pulsar:pulsar-io-jdbc-sqlite;3.3.4 +org.apache.pulsar:pulsar-io-kafka;3.3.4 +org.apache.pulsar:pulsar-io-kafka-connect-adaptor;3.3.4 +org.apache.pulsar:pulsar-io-kafka-connect-adaptor-nar;3.3.4 +org.apache.pulsar:pulsar-io-kinesis;3.3.4 +org.apache.pulsar:pulsar-io-mongo;3.3.4 +org.apache.pulsar:pulsar-io-netty;3.3.4 +org.apache.pulsar:pulsar-io-nsq;3.3.4 +org.apache.pulsar:pulsar-io-rabbitmq;3.3.4 +org.apache.pulsar:pulsar-io-redis;3.3.4 +org.apache.pulsar:pulsar-io-solr;3.3.4 +org.apache.pulsar:pulsar-io-twitter;3.3.4 +org.apache.pulsar:pulsar-metadata;3.3.4 +org.apache.pulsar:pulsar-offloader-distribution;3.3.4 +org.apache.pulsar:pulsar-package-bookkeeper-storage;3.3.4 +org.apache.pulsar:pulsar-package-core;3.3.4 +org.apache.pulsar:pulsar-package-filesystem-storage;3.3.4 +org.apache.pulsar:pulsar-package-management;3.3.4 +org.apache.pulsar:pulsar-proxy;3.3.4 +org.apache.pulsar:pulsar-server-distribution;3.3.4 +org.apache.pulsar:pulsar-shell-distribution;3.3.4 +org.apache.pulsar:pulsar-testclient;3.3.4 +org.apache.pulsar:pulsar-transaction-common;3.3.4 +org.apache.pulsar:pulsar-transaction-coordinator;3.3.4 +org.apache.pulsar:pulsar-transaction-parent;3.3.4 +org.apache.pulsar:pulsar-websocket;3.3.4 +org.apache.pulsar:structured-event-log;3.3.4 +org.apache.pulsar:testmocks;3.3.4 +org.apache.pulsar:tiered-storage-file-system;3.3.4 +org.apache.pulsar:tiered-storage-jcloud;3.3.4 +org.apache.pulsar:tiered-storage-parent;3.3.4 +org.apache.tomcat.embed:tomcat-embed-core;10.1.34 +org.apache.tomcat.embed:tomcat-embed-el;10.1.34 +org.apache.tomcat.embed:tomcat-embed-jasper;10.1.34 +org.apache.tomcat.embed:tomcat-embed-websocket;10.1.34 +org.apache.tomcat:tomcat-annotations-api;10.1.34 +org.apache.tomcat:tomcat-jdbc;10.1.34 +org.apache.tomcat:tomcat-jsp-api;10.1.34 +org.aspectj:aspectjrt;1.9.22.1 +org.aspectj:aspectjtools;1.9.22.1 +org.aspectj:aspectjweaver;1.9.22.1 +org.assertj:assertj-bom;3.26.3 +org.assertj:assertj-core;3.26.3 +org.assertj:assertj-guava;3.26.3 +org.awaitility:awaitility;4.2.2 +org.awaitility:awaitility-groovy;4.2.2 +org.awaitility:awaitility-kotlin;4.2.2 +org.awaitility:awaitility-scala;4.2.2 +org.cache2k:cache2k-api;2.6.1.Final +org.cache2k:cache2k-config;2.6.1.Final +org.cache2k:cache2k-core;2.6.1.Final +org.cache2k:cache2k-jcache;2.6.1.Final +org.cache2k:cache2k-micrometer;2.6.1.Final +org.cache2k:cache2k-spring;2.6.1.Final +org.codehaus.janino:commons-compiler;3.1.12 +org.codehaus.janino:commons-compiler-jdk;3.1.12 +org.codehaus.janino:janino;3.1.12 +org.codehaus.mojo:build-helper-maven-plugin;3.6.0 +org.codehaus.mojo:versions-maven-plugin;2.17.1 +org.codehaus.mojo:xml-maven-plugin;1.1.0 +org.crac:crac;1.5.0 +org.cyclonedx:cyclonedx-maven-plugin;2.9.1 +org.eclipse.angus:angus-activation;2.0.2 +org.eclipse.angus:angus-core;2.0.3 +org.eclipse.angus:angus-mail;2.0.3 +org.eclipse.angus:dsn;2.0.3 +org.eclipse.angus:gimap;2.0.3 +org.eclipse.angus:imap;2.0.3 +org.eclipse.angus:jakarta.mail;2.0.3 +org.eclipse.angus:logging-mailhandler;2.0.3 +org.eclipse.angus:pop3;2.0.3 +org.eclipse.angus:smtp;2.0.3 +org.eclipse.jetty.demos:jetty-demo-handler;12.0.16 +org.eclipse.jetty.ee10.osgi:jetty-ee10-osgi-alpn;12.0.16 +org.eclipse.jetty.ee10.osgi:jetty-ee10-osgi-boot;12.0.16 +org.eclipse.jetty.ee10.osgi:jetty-ee10-osgi-boot-jsp;12.0.16 +org.eclipse.jetty.ee10.websocket:jetty-ee10-websocket-jakarta-client;12.0.16 +org.eclipse.jetty.ee10.websocket:jetty-ee10-websocket-jakarta-client-webapp;12.0.16 +org.eclipse.jetty.ee10.websocket:jetty-ee10-websocket-jakarta-common;12.0.16 +org.eclipse.jetty.ee10.websocket:jetty-ee10-websocket-jakarta-server;12.0.16 +org.eclipse.jetty.ee10.websocket:jetty-ee10-websocket-jetty-client-webapp;12.0.16 +org.eclipse.jetty.ee10.websocket:jetty-ee10-websocket-jetty-server;12.0.16 +org.eclipse.jetty.ee10.websocket:jetty-ee10-websocket-servlet;12.0.16 +org.eclipse.jetty.ee10:jetty-ee10-annotations;12.0.16 +org.eclipse.jetty.ee10:jetty-ee10-apache-jsp;12.0.16 +org.eclipse.jetty.ee10:jetty-ee10-bom;12.0.16 +org.eclipse.jetty.ee10:jetty-ee10-cdi;12.0.16 +org.eclipse.jetty.ee10:jetty-ee10-fcgi-proxy;12.0.16 +org.eclipse.jetty.ee10:jetty-ee10-glassfish-jstl;12.0.16 +org.eclipse.jetty.ee10:jetty-ee10-jaspi;12.0.16 +org.eclipse.jetty.ee10:jetty-ee10-jndi;12.0.16 +org.eclipse.jetty.ee10:jetty-ee10-jspc-maven-plugin;12.0.16 +org.eclipse.jetty.ee10:jetty-ee10-maven-plugin;12.0.16 +org.eclipse.jetty.ee10:jetty-ee10-plus;12.0.16 +org.eclipse.jetty.ee10:jetty-ee10-proxy;12.0.16 +org.eclipse.jetty.ee10:jetty-ee10-quickstart;12.0.16 +org.eclipse.jetty.ee10:jetty-ee10-runner;12.0.16 +org.eclipse.jetty.ee10:jetty-ee10-servlet;12.0.16 +org.eclipse.jetty.ee10:jetty-ee10-servlets;12.0.16 +org.eclipse.jetty.ee10:jetty-ee10-webapp;12.0.16 +org.eclipse.jetty.fcgi:jetty-fcgi-client;12.0.16 +org.eclipse.jetty.fcgi:jetty-fcgi-proxy;12.0.16 +org.eclipse.jetty.fcgi:jetty-fcgi-server;12.0.16 +org.eclipse.jetty.http2:jetty-http2-client;12.0.16 +org.eclipse.jetty.http2:jetty-http2-client-transport;12.0.16 +org.eclipse.jetty.http2:jetty-http2-common;12.0.16 +org.eclipse.jetty.http2:jetty-http2-hpack;12.0.16 +org.eclipse.jetty.http2:jetty-http2-server;12.0.16 +org.eclipse.jetty.http3:jetty-http3-client;12.0.16 +org.eclipse.jetty.http3:jetty-http3-client-transport;12.0.16 +org.eclipse.jetty.http3:jetty-http3-common;12.0.16 +org.eclipse.jetty.http3:jetty-http3-qpack;12.0.16 +org.eclipse.jetty.http3:jetty-http3-server;12.0.16 +org.eclipse.jetty.quic:jetty-quic-client;12.0.16 +org.eclipse.jetty.quic:jetty-quic-common;12.0.16 +org.eclipse.jetty.quic:jetty-quic-quiche-common;12.0.16 +org.eclipse.jetty.quic:jetty-quic-quiche-foreign;12.0.16 +org.eclipse.jetty.quic:jetty-quic-quiche-jna;12.0.16 +org.eclipse.jetty.quic:jetty-quic-server;12.0.16 +org.eclipse.jetty.websocket:jetty-websocket-core-client;12.0.16 +org.eclipse.jetty.websocket:jetty-websocket-core-common;12.0.16 +org.eclipse.jetty.websocket:jetty-websocket-core-server;12.0.16 +org.eclipse.jetty.websocket:jetty-websocket-jetty-api;12.0.16 +org.eclipse.jetty.websocket:jetty-websocket-jetty-client;12.0.16 +org.eclipse.jetty.websocket:jetty-websocket-jetty-common;12.0.16 +org.eclipse.jetty.websocket:jetty-websocket-jetty-server;12.0.16 +org.eclipse.jetty:jetty-alpn-client;12.0.16 +org.eclipse.jetty:jetty-alpn-conscrypt-client;12.0.16 +org.eclipse.jetty:jetty-alpn-conscrypt-server;12.0.16 +org.eclipse.jetty:jetty-alpn-java-client;12.0.16 +org.eclipse.jetty:jetty-alpn-java-server;12.0.16 +org.eclipse.jetty:jetty-alpn-server;12.0.16 +org.eclipse.jetty:jetty-bom;12.0.16 +org.eclipse.jetty:jetty-client;12.0.16 +org.eclipse.jetty:jetty-deploy;12.0.16 +org.eclipse.jetty:jetty-http;12.0.16 +org.eclipse.jetty:jetty-http-spi;12.0.16 +org.eclipse.jetty:jetty-http-tools;12.0.16 +org.eclipse.jetty:jetty-io;12.0.16 +org.eclipse.jetty:jetty-jmx;12.0.16 +org.eclipse.jetty:jetty-jndi;12.0.16 +org.eclipse.jetty:jetty-keystore;12.0.16 +org.eclipse.jetty:jetty-openid;12.0.16 +org.eclipse.jetty:jetty-osgi;12.0.16 +org.eclipse.jetty:jetty-plus;12.0.16 +org.eclipse.jetty:jetty-proxy;12.0.16 +org.eclipse.jetty:jetty-reactive-httpclient;4.0.8 +org.eclipse.jetty:jetty-rewrite;12.0.16 +org.eclipse.jetty:jetty-security;12.0.16 +org.eclipse.jetty:jetty-server;12.0.16 +org.eclipse.jetty:jetty-session;12.0.16 +org.eclipse.jetty:jetty-slf4j-impl;12.0.16 +org.eclipse.jetty:jetty-start;12.0.16 +org.eclipse.jetty:jetty-unixdomain-server;12.0.16 +org.eclipse.jetty:jetty-util;12.0.16 +org.eclipse.jetty:jetty-util-ajax;12.0.16 +org.eclipse.jetty:jetty-xml;12.0.16 +org.eclipse.jgit:org.eclipse.jgit;6.10.0.202406032230-r +org.eclipse.jgit:org.eclipse.jgit.http.apache;6.10.0.202406032230-r +org.eclipse.jgit:org.eclipse.jgit.junit.http;6.10.0.202406032230-r +org.eclipse.jgit:org.eclipse.jgit.ssh.apache;6.10.0.202406032230-r +org.eclipse:yasson;3.0.4 +org.ehcache:ehcache;3.10.8 +org.ehcache:ehcache-clustered;3.10.8 +org.ehcache:ehcache-transactions;3.10.8 +org.elasticsearch.client:elasticsearch-rest-client;8.15.5 +org.elasticsearch.client:elasticsearch-rest-client-sniffer;8.15.5 +org.firebirdsql.jdbc:jaybird;5.0.6.java11 +org.flywaydb:flyway-commandline;10.20.1 +org.flywaydb:flyway-core;10.20.1 +org.flywaydb:flyway-database-cassandra;10.20.1 +org.flywaydb:flyway-database-db2;10.20.1 +org.flywaydb:flyway-database-derby;10.20.1 +org.flywaydb:flyway-database-hsqldb;10.20.1 +org.flywaydb:flyway-database-informix;10.20.1 +org.flywaydb:flyway-database-mongodb;10.20.1 +org.flywaydb:flyway-database-oracle;10.20.1 +org.flywaydb:flyway-database-postgresql;10.20.1 +org.flywaydb:flyway-database-redshift;10.20.1 +org.flywaydb:flyway-database-saphana;10.20.1 +org.flywaydb:flyway-database-snowflake;10.20.1 +org.flywaydb:flyway-database-sybasease;10.20.1 +org.flywaydb:flyway-firebird;10.20.1 +org.flywaydb:flyway-gcp-bigquery;10.20.1 +org.flywaydb:flyway-gcp-spanner;10.20.1 +org.flywaydb:flyway-maven-plugin;10.20.1 +org.flywaydb:flyway-mysql;10.20.1 +org.flywaydb:flyway-singlestore;10.20.1 +org.flywaydb:flyway-sqlserver;10.20.1 +org.freemarker:freemarker;2.3.34 +org.glassfish.jaxb:codemodel;4.0.5 +org.glassfish.jaxb:jaxb-bom;4.0.5 +org.glassfish.jaxb:jaxb-core;4.0.5 +org.glassfish.jaxb:jaxb-jxc;4.0.5 +org.glassfish.jaxb:jaxb-runtime;4.0.5 +org.glassfish.jaxb:jaxb-xjc;4.0.5 +org.glassfish.jaxb:txw2;4.0.5 +org.glassfish.jaxb:xsom;4.0.5 +org.glassfish.jersey.bundles:jaxrs-ri;3.1.10 +org.glassfish.jersey.connectors:jersey-apache-connector;3.1.10 +org.glassfish.jersey.connectors:jersey-apache5-connector;3.1.10 +org.glassfish.jersey.connectors:jersey-grizzly-connector;3.1.10 +org.glassfish.jersey.connectors:jersey-helidon-connector;3.1.10 +org.glassfish.jersey.connectors:jersey-jdk-connector;3.1.10 +org.glassfish.jersey.connectors:jersey-jetty-connector;3.1.10 +org.glassfish.jersey.connectors:jersey-jetty-http2-connector;3.1.10 +org.glassfish.jersey.connectors:jersey-jetty11-connector;3.1.10 +org.glassfish.jersey.connectors:jersey-jnh-connector;3.1.10 +org.glassfish.jersey.connectors:jersey-netty-connector;3.1.10 +org.glassfish.jersey.containers.glassfish:jersey-gf-ejb;3.1.10 +org.glassfish.jersey.containers:jersey-container-grizzly2-http;3.1.10 +org.glassfish.jersey.containers:jersey-container-grizzly2-servlet;3.1.10 +org.glassfish.jersey.containers:jersey-container-jdk-http;3.1.10 +org.glassfish.jersey.containers:jersey-container-jetty-http;3.1.10 +org.glassfish.jersey.containers:jersey-container-jetty-http2;3.1.10 +org.glassfish.jersey.containers:jersey-container-jetty-servlet;3.1.10 +org.glassfish.jersey.containers:jersey-container-jetty11-http;3.1.10 +org.glassfish.jersey.containers:jersey-container-netty-http;3.1.10 +org.glassfish.jersey.containers:jersey-container-servlet;3.1.10 +org.glassfish.jersey.containers:jersey-container-servlet-core;3.1.10 +org.glassfish.jersey.containers:jersey-container-simple-http;3.1.10 +org.glassfish.jersey.core:jersey-client;3.1.10 +org.glassfish.jersey.core:jersey-common;3.1.10 +org.glassfish.jersey.core:jersey-server;3.1.10 +org.glassfish.jersey.ext.cdi:jersey-cdi-rs-inject;3.1.10 +org.glassfish.jersey.ext.cdi:jersey-cdi1x;3.1.10 +org.glassfish.jersey.ext.cdi:jersey-cdi1x-ban-custom-hk2-binding;3.1.10 +org.glassfish.jersey.ext.cdi:jersey-cdi1x-servlet;3.1.10 +org.glassfish.jersey.ext.cdi:jersey-cdi1x-transaction;3.1.10 +org.glassfish.jersey.ext.cdi:jersey-cdi1x-validation;3.1.10 +org.glassfish.jersey.ext.cdi:jersey-weld2-se;3.1.10 +org.glassfish.jersey.ext.microprofile:jersey-mp-config;3.1.10 +org.glassfish.jersey.ext.microprofile:jersey-mp-rest-client;3.1.10 +org.glassfish.jersey.ext.rx:jersey-rx-client-guava;3.1.10 +org.glassfish.jersey.ext.rx:jersey-rx-client-rxjava;3.1.10 +org.glassfish.jersey.ext.rx:jersey-rx-client-rxjava2;3.1.10 +org.glassfish.jersey.ext:jersey-bean-validation;3.1.10 +org.glassfish.jersey.ext:jersey-declarative-linking;3.1.10 +org.glassfish.jersey.ext:jersey-entity-filtering;3.1.10 +org.glassfish.jersey.ext:jersey-metainf-services;3.1.10 +org.glassfish.jersey.ext:jersey-micrometer;3.1.10 +org.glassfish.jersey.ext:jersey-mvc;3.1.10 +org.glassfish.jersey.ext:jersey-mvc-bean-validation;3.1.10 +org.glassfish.jersey.ext:jersey-mvc-freemarker;3.1.10 +org.glassfish.jersey.ext:jersey-mvc-jsp;3.1.10 +org.glassfish.jersey.ext:jersey-mvc-mustache;3.1.10 +org.glassfish.jersey.ext:jersey-proxy-client;3.1.10 +org.glassfish.jersey.ext:jersey-spring6;3.1.10 +org.glassfish.jersey.ext:jersey-wadl-doclet;3.1.10 +org.glassfish.jersey.inject:jersey-cdi2-se;3.1.10 +org.glassfish.jersey.inject:jersey-hk2;3.1.10 +org.glassfish.jersey.media:jersey-media-jaxb;3.1.10 +org.glassfish.jersey.media:jersey-media-json-binding;3.1.10 +org.glassfish.jersey.media:jersey-media-json-gson;3.1.10 +org.glassfish.jersey.media:jersey-media-json-jackson;3.1.10 +org.glassfish.jersey.media:jersey-media-json-jettison;3.1.10 +org.glassfish.jersey.media:jersey-media-json-processing;3.1.10 +org.glassfish.jersey.media:jersey-media-kryo;3.1.10 +org.glassfish.jersey.media:jersey-media-moxy;3.1.10 +org.glassfish.jersey.media:jersey-media-multipart;3.1.10 +org.glassfish.jersey.media:jersey-media-sse;3.1.10 +org.glassfish.jersey.security:oauth1-client;3.1.10 +org.glassfish.jersey.security:oauth1-server;3.1.10 +org.glassfish.jersey.security:oauth1-signature;3.1.10 +org.glassfish.jersey.security:oauth2-client;3.1.10 +org.glassfish.jersey.test-framework.providers:jersey-test-framework-provider-bundle;3.1.10 +org.glassfish.jersey.test-framework.providers:jersey-test-framework-provider-external;3.1.10 +org.glassfish.jersey.test-framework.providers:jersey-test-framework-provider-grizzly2;3.1.10 +org.glassfish.jersey.test-framework.providers:jersey-test-framework-provider-inmemory;3.1.10 +org.glassfish.jersey.test-framework.providers:jersey-test-framework-provider-jdk-http;3.1.10 +org.glassfish.jersey.test-framework.providers:jersey-test-framework-provider-jetty;3.1.10 +org.glassfish.jersey.test-framework.providers:jersey-test-framework-provider-jetty-http2;3.1.10 +org.glassfish.jersey.test-framework.providers:jersey-test-framework-provider-netty;3.1.10 +org.glassfish.jersey.test-framework.providers:jersey-test-framework-provider-simple;3.1.10 +org.glassfish.jersey.test-framework:jersey-test-framework-core;3.1.10 +org.glassfish.jersey.test-framework:jersey-test-framework-util;3.1.10 +org.glassfish.jersey:jersey-bom;3.1.10 +org.glassfish.web:jakarta.servlet.jsp.jstl;3.0.1 +org.graalvm.buildtools:native-maven-plugin;0.10.4 +org.hamcrest:hamcrest;2.2 +org.hamcrest:hamcrest-core;2.2 +org.hamcrest:hamcrest-library;2.2 +org.hibernate.orm:hibernate-agroal;6.6.5.Final +org.hibernate.orm:hibernate-ant;6.6.5.Final +org.hibernate.orm:hibernate-c3p0;6.6.5.Final +org.hibernate.orm:hibernate-community-dialects;6.6.5.Final +org.hibernate.orm:hibernate-core;6.6.5.Final +org.hibernate.orm:hibernate-envers;6.6.5.Final +org.hibernate.orm:hibernate-graalvm;6.6.5.Final +org.hibernate.orm:hibernate-hikaricp;6.6.5.Final +org.hibernate.orm:hibernate-jcache;6.6.5.Final +org.hibernate.orm:hibernate-jpamodelgen;6.6.5.Final +org.hibernate.orm:hibernate-micrometer;6.6.5.Final +org.hibernate.orm:hibernate-proxool;6.6.5.Final +org.hibernate.orm:hibernate-spatial;6.6.5.Final +org.hibernate.orm:hibernate-testing;6.6.5.Final +org.hibernate.orm:hibernate-vibur;6.6.5.Final +org.hibernate.validator:hibernate-validator;8.0.2.Final +org.hibernate.validator:hibernate-validator-annotation-processor;8.0.2.Final +org.hsqldb:hsqldb;2.7.3 +org.htmlunit:htmlunit;4.5.0 +org.infinispan.protostream:protostream;5.0.12.Final +org.infinispan.protostream:protostream-processor;5.0.12.Final +org.infinispan.protostream:protostream-types;5.0.12.Final +org.infinispan:infinispan-anchored-keys;15.0.12.Final +org.infinispan:infinispan-api;15.0.12.Final +org.infinispan:infinispan-bom;15.0.12.Final +org.infinispan:infinispan-cachestore-jdbc;15.0.12.Final +org.infinispan:infinispan-cachestore-jdbc-common;15.0.12.Final +org.infinispan:infinispan-cachestore-remote;15.0.12.Final +org.infinispan:infinispan-cachestore-rocksdb;15.0.12.Final +org.infinispan:infinispan-cachestore-sql;15.0.12.Final +org.infinispan:infinispan-cdi-common;15.0.12.Final +org.infinispan:infinispan-cdi-embedded;15.0.12.Final +org.infinispan:infinispan-cdi-remote;15.0.12.Final +org.infinispan:infinispan-checkstyle;15.0.12.Final +org.infinispan:infinispan-cli-client;15.0.12.Final +org.infinispan:infinispan-client-hotrod;15.0.12.Final +org.infinispan:infinispan-client-rest;15.0.12.Final +org.infinispan:infinispan-clustered-counter;15.0.12.Final +org.infinispan:infinispan-clustered-lock;15.0.12.Final +org.infinispan:infinispan-commons;15.0.12.Final +org.infinispan:infinispan-commons-graalvm;15.0.12.Final +org.infinispan:infinispan-commons-test;15.0.12.Final +org.infinispan:infinispan-component-annotations;15.0.12.Final +org.infinispan:infinispan-component-processor;15.0.12.Final +org.infinispan:infinispan-console;15.0.11.Final +org.infinispan:infinispan-core;15.0.12.Final +org.infinispan:infinispan-core-graalvm;15.0.12.Final +org.infinispan:infinispan-hibernate-cache-commons;15.0.12.Final +org.infinispan:infinispan-hibernate-cache-spi;15.0.12.Final +org.infinispan:infinispan-hibernate-cache-v62;15.0.12.Final +org.infinispan:infinispan-hotrod;15.0.12.Final +org.infinispan:infinispan-jboss-marshalling;15.0.12.Final +org.infinispan:infinispan-jcache;15.0.12.Final +org.infinispan:infinispan-jcache-commons;15.0.12.Final +org.infinispan:infinispan-jcache-remote;15.0.12.Final +org.infinispan:infinispan-key-value-store-client;15.0.12.Final +org.infinispan:infinispan-logging-annotations;15.0.12.Final +org.infinispan:infinispan-logging-processor;15.0.12.Final +org.infinispan:infinispan-multimap;15.0.12.Final +org.infinispan:infinispan-objectfilter;15.0.12.Final +org.infinispan:infinispan-quarkus-embedded;15.0.12.Final +org.infinispan:infinispan-query;15.0.12.Final +org.infinispan:infinispan-query-core;15.0.12.Final +org.infinispan:infinispan-query-dsl;15.0.12.Final +org.infinispan:infinispan-remote-query-client;15.0.12.Final +org.infinispan:infinispan-remote-query-server;15.0.12.Final +org.infinispan:infinispan-scripting;15.0.12.Final +org.infinispan:infinispan-server-core;15.0.12.Final +org.infinispan:infinispan-server-hotrod;15.0.12.Final +org.infinispan:infinispan-server-memcached;15.0.12.Final +org.infinispan:infinispan-server-resp;15.0.12.Final +org.infinispan:infinispan-server-rest;15.0.12.Final +org.infinispan:infinispan-server-router;15.0.12.Final +org.infinispan:infinispan-server-runtime;15.0.12.Final +org.infinispan:infinispan-server-testdriver-core;15.0.12.Final +org.infinispan:infinispan-server-testdriver-junit4;15.0.12.Final +org.infinispan:infinispan-server-testdriver-junit5;15.0.12.Final +org.infinispan:infinispan-spring-boot3-starter-embedded;15.0.12.Final +org.infinispan:infinispan-spring-boot3-starter-remote;15.0.12.Final +org.infinispan:infinispan-spring6-common;15.0.12.Final +org.infinispan:infinispan-spring6-embedded;15.0.12.Final +org.infinispan:infinispan-spring6-remote;15.0.12.Final +org.infinispan:infinispan-tasks;15.0.12.Final +org.infinispan:infinispan-tasks-api;15.0.12.Final +org.infinispan:infinispan-tools;15.0.12.Final +org.influxdb:influxdb-java;2.24 +org.jboss.logging:jboss-logging;3.6.1.Final +org.jdom:jdom2;2.0.6.1 +org.jetbrains.kotlin:kotlin-bom;1.9.25 +org.jetbrains.kotlin:kotlin-compiler;1.9.25 +org.jetbrains.kotlin:kotlin-compiler-embeddable;1.9.25 +org.jetbrains.kotlin:kotlin-daemon-client;1.9.25 +org.jetbrains.kotlin:kotlin-main-kts;1.9.25 +org.jetbrains.kotlin:kotlin-maven-plugin;1.9.25 +org.jetbrains.kotlin:kotlin-osgi-bundle;1.9.25 +org.jetbrains.kotlin:kotlin-reflect;1.9.25 +org.jetbrains.kotlin:kotlin-script-runtime;1.9.25 +org.jetbrains.kotlin:kotlin-scripting-common;1.9.25 +org.jetbrains.kotlin:kotlin-scripting-ide-services;1.9.25 +org.jetbrains.kotlin:kotlin-scripting-jvm;1.9.25 +org.jetbrains.kotlin:kotlin-scripting-jvm-host;1.9.25 +org.jetbrains.kotlin:kotlin-stdlib;1.9.25 +org.jetbrains.kotlin:kotlin-stdlib-common;1.9.25 +org.jetbrains.kotlin:kotlin-stdlib-jdk7;1.9.25 +org.jetbrains.kotlin:kotlin-stdlib-jdk8;1.9.25 +org.jetbrains.kotlin:kotlin-stdlib-js;1.9.25 +org.jetbrains.kotlin:kotlin-test;1.9.25 +org.jetbrains.kotlin:kotlin-test-annotations-common;1.9.25 +org.jetbrains.kotlin:kotlin-test-common;1.9.25 +org.jetbrains.kotlin:kotlin-test-js;1.9.25 +org.jetbrains.kotlin:kotlin-test-junit;1.9.25 +org.jetbrains.kotlin:kotlin-test-junit5;1.9.25 +org.jetbrains.kotlin:kotlin-test-testng;1.9.25 +org.jetbrains.kotlinx:kotlinx-coroutines-android;1.8.1 +org.jetbrains.kotlinx:kotlinx-coroutines-bom;1.8.1 +org.jetbrains.kotlinx:kotlinx-coroutines-core;1.8.1 +org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm;1.8.1 +org.jetbrains.kotlinx:kotlinx-coroutines-debug;1.8.1 +org.jetbrains.kotlinx:kotlinx-coroutines-guava;1.8.1 +org.jetbrains.kotlinx:kotlinx-coroutines-javafx;1.8.1 +org.jetbrains.kotlinx:kotlinx-coroutines-jdk8;1.8.1 +org.jetbrains.kotlinx:kotlinx-coroutines-jdk9;1.8.1 +org.jetbrains.kotlinx:kotlinx-coroutines-play-services;1.8.1 +org.jetbrains.kotlinx:kotlinx-coroutines-reactive;1.8.1 +org.jetbrains.kotlinx:kotlinx-coroutines-reactor;1.8.1 +org.jetbrains.kotlinx:kotlinx-coroutines-rx2;1.8.1 +org.jetbrains.kotlinx:kotlinx-coroutines-rx3;1.8.1 +org.jetbrains.kotlinx:kotlinx-coroutines-slf4j;1.8.1 +org.jetbrains.kotlinx:kotlinx-coroutines-swing;1.8.1 +org.jetbrains.kotlinx:kotlinx-coroutines-test;1.8.1 +org.jetbrains.kotlinx:kotlinx-coroutines-test-jvm;1.8.1 +org.jetbrains.kotlinx:kotlinx-serialization-bom;1.6.3 +org.jetbrains.kotlinx:kotlinx-serialization-cbor;1.6.3 +org.jetbrains.kotlinx:kotlinx-serialization-cbor-jvm;1.6.3 +org.jetbrains.kotlinx:kotlinx-serialization-core;1.6.3 +org.jetbrains.kotlinx:kotlinx-serialization-core-jvm;1.6.3 +org.jetbrains.kotlinx:kotlinx-serialization-hocon;1.6.3 +org.jetbrains.kotlinx:kotlinx-serialization-json;1.6.3 +org.jetbrains.kotlinx:kotlinx-serialization-json-jvm;1.6.3 +org.jetbrains.kotlinx:kotlinx-serialization-json-okio;1.6.3 +org.jetbrains.kotlinx:kotlinx-serialization-json-okio-jvm;1.6.3 +org.jetbrains.kotlinx:kotlinx-serialization-properties;1.6.3 +org.jetbrains.kotlinx:kotlinx-serialization-properties-jvm;1.6.3 +org.jetbrains.kotlinx:kotlinx-serialization-protobuf;1.6.3 +org.jetbrains.kotlinx:kotlinx-serialization-protobuf-jvm;1.6.3 +org.jooq:jooq;3.19.18 +org.jooq:jooq-codegen;3.19.18 +org.jooq:jooq-codegen-maven;3.19.18 +org.jooq:jooq-kotlin;3.19.18 +org.jooq:jooq-meta;3.19.18 +org.junit.jupiter:junit-jupiter;5.11.4 +org.junit.jupiter:junit-jupiter-api;5.11.4 +org.junit.jupiter:junit-jupiter-engine;5.11.4 +org.junit.jupiter:junit-jupiter-migrationsupport;5.11.4 +org.junit.jupiter:junit-jupiter-params;5.11.4 +org.junit.platform:junit-platform-commons;1.11.4 +org.junit.platform:junit-platform-console;1.11.4 +org.junit.platform:junit-platform-engine;1.11.4 +org.junit.platform:junit-platform-jfr;1.11.4 +org.junit.platform:junit-platform-launcher;1.11.4 +org.junit.platform:junit-platform-reporting;1.11.4 +org.junit.platform:junit-platform-runner;1.11.4 +org.junit.platform:junit-platform-suite;1.11.4 +org.junit.platform:junit-platform-suite-api;1.11.4 +org.junit.platform:junit-platform-suite-commons;1.11.4 +org.junit.platform:junit-platform-suite-engine;1.11.4 +org.junit.platform:junit-platform-testkit;1.11.4 +org.junit.vintage:junit-vintage-engine;5.11.4 +org.junit:junit-bom;5.11.4 +org.jvnet.staxex:stax-ex;2.1.0 +org.liquibase:liquibase-cdi;4.29.2 +org.liquibase:liquibase-core;4.29.2 +org.liquibase:liquibase-maven-plugin;4.29.2 +org.mariadb.jdbc:mariadb-java-client;3.4.1 +org.mariadb:r2dbc-mariadb;1.2.2 +org.messaginghub:pooled-jms;3.1.7 +org.mockito:mockito-android;5.14.2 +org.mockito:mockito-bom;5.14.2 +org.mockito:mockito-core;5.14.2 +org.mockito:mockito-errorprone;5.14.2 +org.mockito:mockito-junit-jupiter;5.14.2 +org.mockito:mockito-proxy;5.14.2 +org.mockito:mockito-subclass;5.14.2 +org.mongodb:bson;5.2.1 +org.mongodb:bson-record-codec;5.2.1 +org.mongodb:mongodb-driver-core;5.2.1 +org.mongodb:mongodb-driver-legacy;5.2.1 +org.mongodb:mongodb-driver-reactivestreams;5.2.1 +org.mongodb:mongodb-driver-sync;5.2.1 +org.neo4j.driver:neo4j-java-driver;5.25.0 +org.postgresql:postgresql;42.7.5 +org.postgresql:r2dbc-postgresql;1.0.7.RELEASE +org.projectlombok:lombok;1.18.36 +org.quartz-scheduler:quartz;2.3.2 +org.quartz-scheduler:quartz-jobs;2.3.2 +org.reactivestreams:reactive-streams;1.0.4 +org.seleniumhq.selenium:htmlunit3-driver;4.25.0 +org.seleniumhq.selenium:selenium-api;4.25.0 +org.seleniumhq.selenium:selenium-bom;4.25.0 +org.seleniumhq.selenium:selenium-chrome-driver;4.25.0 +org.seleniumhq.selenium:selenium-chromium-driver;4.25.0 +org.seleniumhq.selenium:selenium-devtools-v127;4.25.0 +org.seleniumhq.selenium:selenium-devtools-v128;4.25.0 +org.seleniumhq.selenium:selenium-devtools-v129;4.25.0 +org.seleniumhq.selenium:selenium-devtools-v85;4.25.0 +org.seleniumhq.selenium:selenium-edge-driver;4.25.0 +org.seleniumhq.selenium:selenium-firefox-driver;4.25.0 +org.seleniumhq.selenium:selenium-grid;4.25.0 +org.seleniumhq.selenium:selenium-http;4.25.0 +org.seleniumhq.selenium:selenium-ie-driver;4.25.0 +org.seleniumhq.selenium:selenium-java;4.25.0 +org.seleniumhq.selenium:selenium-json;4.25.0 +org.seleniumhq.selenium:selenium-manager;4.25.0 +org.seleniumhq.selenium:selenium-remote-driver;4.25.0 +org.seleniumhq.selenium:selenium-safari-driver;4.25.0 +org.seleniumhq.selenium:selenium-session-map-jdbc;4.25.0 +org.seleniumhq.selenium:selenium-session-map-redis;4.25.0 +org.seleniumhq.selenium:selenium-support;4.25.0 +org.skyscreamer:jsonassert;1.5.3 +org.slf4j:jcl-over-slf4j;2.0.16 +org.slf4j:jul-to-slf4j;2.0.16 +org.slf4j:log4j-over-slf4j;2.0.16 +org.slf4j:slf4j-api;2.0.16 +org.slf4j:slf4j-ext;2.0.16 +org.slf4j:slf4j-jdk-platform-logging;2.0.16 +org.slf4j:slf4j-jdk14;2.0.16 +org.slf4j:slf4j-log4j12;2.0.16 +org.slf4j:slf4j-nop;2.0.16 +org.slf4j:slf4j-reload4j;2.0.16 +org.slf4j:slf4j-simple;2.0.16 +org.springframework.amqp:spring-amqp;3.2.2 +org.springframework.amqp:spring-amqp-bom;3.2.2 +org.springframework.amqp:spring-rabbit;3.2.2 +org.springframework.amqp:spring-rabbit-junit;3.2.2 +org.springframework.amqp:spring-rabbit-stream;3.2.2 +org.springframework.amqp:spring-rabbit-test;3.2.2 +org.springframework.batch:spring-batch-bom;5.2.1 +org.springframework.batch:spring-batch-core;5.2.1 +org.springframework.batch:spring-batch-infrastructure;5.2.1 +org.springframework.batch:spring-batch-integration;5.2.1 +org.springframework.batch:spring-batch-test;5.2.1 +org.springframework.boot:spring-boot;3.4.2 +org.springframework.boot:spring-boot-actuator;3.4.2 +org.springframework.boot:spring-boot-actuator-autoconfigure;3.4.2 +org.springframework.boot:spring-boot-autoconfigure;3.4.2 +org.springframework.boot:spring-boot-autoconfigure-processor;3.4.2 +org.springframework.boot:spring-boot-buildpack-platform;3.4.2 +org.springframework.boot:spring-boot-configuration-metadata;3.4.2 +org.springframework.boot:spring-boot-configuration-processor;3.4.2 +org.springframework.boot:spring-boot-dependencies;3.4.2 +org.springframework.boot:spring-boot-devtools;3.4.2 +org.springframework.boot:spring-boot-docker-compose;3.4.2 +org.springframework.boot:spring-boot-jarmode-tools;3.4.2 +org.springframework.boot:spring-boot-loader;3.4.2 +org.springframework.boot:spring-boot-loader-classic;3.4.2 +org.springframework.boot:spring-boot-loader-tools;3.4.2 +org.springframework.boot:spring-boot-maven-plugin;3.4.2 +org.springframework.boot:spring-boot-properties-migrator;3.4.2 +org.springframework.boot:spring-boot-starter;3.4.2 +org.springframework.boot:spring-boot-starter-activemq;3.4.2 +org.springframework.boot:spring-boot-starter-actuator;3.4.2 +org.springframework.boot:spring-boot-starter-amqp;3.4.2 +org.springframework.boot:spring-boot-starter-aop;3.4.2 +org.springframework.boot:spring-boot-starter-artemis;3.4.2 +org.springframework.boot:spring-boot-starter-batch;3.4.2 +org.springframework.boot:spring-boot-starter-cache;3.4.2 +org.springframework.boot:spring-boot-starter-data-cassandra;3.4.2 +org.springframework.boot:spring-boot-starter-data-cassandra-reactive;3.4.2 +org.springframework.boot:spring-boot-starter-data-couchbase;3.4.2 +org.springframework.boot:spring-boot-starter-data-couchbase-reactive;3.4.2 +org.springframework.boot:spring-boot-starter-data-elasticsearch;3.4.2 +org.springframework.boot:spring-boot-starter-data-jdbc;3.4.2 +org.springframework.boot:spring-boot-starter-data-jpa;3.4.2 +org.springframework.boot:spring-boot-starter-data-ldap;3.4.2 +org.springframework.boot:spring-boot-starter-data-mongodb;3.4.2 +org.springframework.boot:spring-boot-starter-data-mongodb-reactive;3.4.2 +org.springframework.boot:spring-boot-starter-data-neo4j;3.4.2 +org.springframework.boot:spring-boot-starter-data-r2dbc;3.4.2 +org.springframework.boot:spring-boot-starter-data-redis;3.4.2 +org.springframework.boot:spring-boot-starter-data-redis-reactive;3.4.2 +org.springframework.boot:spring-boot-starter-data-rest;3.4.2 +org.springframework.boot:spring-boot-starter-freemarker;3.4.2 +org.springframework.boot:spring-boot-starter-graphql;3.4.2 +org.springframework.boot:spring-boot-starter-groovy-templates;3.4.2 +org.springframework.boot:spring-boot-starter-hateoas;3.4.2 +org.springframework.boot:spring-boot-starter-integration;3.4.2 +org.springframework.boot:spring-boot-starter-jdbc;3.4.2 +org.springframework.boot:spring-boot-starter-jersey;3.4.2 +org.springframework.boot:spring-boot-starter-jetty;3.4.2 +org.springframework.boot:spring-boot-starter-jooq;3.4.2 +org.springframework.boot:spring-boot-starter-json;3.4.2 +org.springframework.boot:spring-boot-starter-log4j2;3.4.2 +org.springframework.boot:spring-boot-starter-logging;3.4.2 +org.springframework.boot:spring-boot-starter-mail;3.4.2 +org.springframework.boot:spring-boot-starter-mustache;3.4.2 +org.springframework.boot:spring-boot-starter-oauth2-authorization-server;3.4.2 +org.springframework.boot:spring-boot-starter-oauth2-client;3.4.2 +org.springframework.boot:spring-boot-starter-oauth2-resource-server;3.4.2 +org.springframework.boot:spring-boot-starter-parent;3.4.2 +org.springframework.boot:spring-boot-starter-pulsar;3.4.2 +org.springframework.boot:spring-boot-starter-pulsar-reactive;3.4.2 +org.springframework.boot:spring-boot-starter-quartz;3.4.2 +org.springframework.boot:spring-boot-starter-reactor-netty;3.4.2 +org.springframework.boot:spring-boot-starter-rsocket;3.4.2 +org.springframework.boot:spring-boot-starter-security;3.4.2 +org.springframework.boot:spring-boot-starter-test;3.4.2 +org.springframework.boot:spring-boot-starter-thymeleaf;3.4.2 +org.springframework.boot:spring-boot-starter-tomcat;3.4.2 +org.springframework.boot:spring-boot-starter-undertow;3.4.2 +org.springframework.boot:spring-boot-starter-validation;3.4.2 +org.springframework.boot:spring-boot-starter-web;3.4.2 +org.springframework.boot:spring-boot-starter-web-services;3.4.2 +org.springframework.boot:spring-boot-starter-webflux;3.4.2 +org.springframework.boot:spring-boot-starter-websocket;3.4.2 +org.springframework.boot:spring-boot-test;3.4.2 +org.springframework.boot:spring-boot-test-autoconfigure;3.4.2 +org.springframework.boot:spring-boot-testcontainers;3.4.2 +org.springframework.cloud:spring-cloud-bus;4.2.0 +org.springframework.cloud:spring-cloud-bus-dependencies;4.2.0 +org.springframework.cloud:spring-cloud-bus-rsocket;4.2.0 +org.springframework.cloud:spring-cloud-circuitbreaker-dependencies;3.2.0 +org.springframework.cloud:spring-cloud-circuitbreaker-resilience4j;3.2.0 +org.springframework.cloud:spring-cloud-circuitbreaker-spring-retry;3.2.0 +org.springframework.cloud:spring-cloud-commons;4.2.0 +org.springframework.cloud:spring-cloud-commons-dependencies;4.2.0 +org.springframework.cloud:spring-cloud-config-client;4.2.0 +org.springframework.cloud:spring-cloud-config-dependencies;4.2.0 +org.springframework.cloud:spring-cloud-config-monitor;4.2.0 +org.springframework.cloud:spring-cloud-config-server;4.2.0 +org.springframework.cloud:spring-cloud-consul-binder;4.2.0 +org.springframework.cloud:spring-cloud-consul-config;4.2.0 +org.springframework.cloud:spring-cloud-consul-core;4.2.0 +org.springframework.cloud:spring-cloud-consul-dependencies;4.2.0 +org.springframework.cloud:spring-cloud-consul-discovery;4.2.0 +org.springframework.cloud:spring-cloud-context;4.2.0 +org.springframework.cloud:spring-cloud-contract-converters;4.2.0 +org.springframework.cloud:spring-cloud-contract-dependencies;4.2.0 +org.springframework.cloud:spring-cloud-contract-gradle-plugin;4.2.0 +org.springframework.cloud:spring-cloud-contract-maven-plugin;4.2.0 +org.springframework.cloud:spring-cloud-contract-shade;4.2.0 +org.springframework.cloud:spring-cloud-contract-spec;4.2.0 +org.springframework.cloud:spring-cloud-contract-spec-groovy;4.2.0 +org.springframework.cloud:spring-cloud-contract-spec-java;4.2.0 +org.springframework.cloud:spring-cloud-contract-spec-kotlin;4.2.0 +org.springframework.cloud:spring-cloud-contract-stub-runner;4.2.0 +org.springframework.cloud:spring-cloud-contract-stub-runner-boot;4.2.0 +org.springframework.cloud:spring-cloud-contract-verifier;4.2.0 +org.springframework.cloud:spring-cloud-contract-wiremock;4.2.0 +org.springframework.cloud:spring-cloud-dependencies;2024.0.0 +org.springframework.cloud:spring-cloud-function-adapter-aws;4.2.0 +org.springframework.cloud:spring-cloud-function-adapter-azure;4.2.0 +org.springframework.cloud:spring-cloud-function-adapter-gcp;4.2.0 +org.springframework.cloud:spring-cloud-function-context;4.2.0 +org.springframework.cloud:spring-cloud-function-core;4.2.0 +org.springframework.cloud:spring-cloud-function-dependencies;4.2.0 +org.springframework.cloud:spring-cloud-function-deployer;4.2.0 +org.springframework.cloud:spring-cloud-function-grpc;4.2.0 +org.springframework.cloud:spring-cloud-function-grpc-cloudevent-ext;4.2.0 +org.springframework.cloud:spring-cloud-function-integration;4.2.0 +org.springframework.cloud:spring-cloud-function-kotlin;4.2.0 +org.springframework.cloud:spring-cloud-function-rsocket;4.2.0 +org.springframework.cloud:spring-cloud-function-serverless-web;4.2.0 +org.springframework.cloud:spring-cloud-function-web;4.2.0 +org.springframework.cloud:spring-cloud-gateway-dependencies;4.2.0 +org.springframework.cloud:spring-cloud-gateway-mvc;4.2.0 +org.springframework.cloud:spring-cloud-gateway-server;4.2.0 +org.springframework.cloud:spring-cloud-gateway-server-mvc;4.2.0 +org.springframework.cloud:spring-cloud-gateway-webflux;4.2.0 +org.springframework.cloud:spring-cloud-kubernetes-client-autoconfig;3.2.0 +org.springframework.cloud:spring-cloud-kubernetes-client-config;3.2.0 +org.springframework.cloud:spring-cloud-kubernetes-client-discovery;3.2.0 +org.springframework.cloud:spring-cloud-kubernetes-client-loadbalancer;3.2.0 +org.springframework.cloud:spring-cloud-kubernetes-commons;3.2.0 +org.springframework.cloud:spring-cloud-kubernetes-dependencies;3.2.0 +org.springframework.cloud:spring-cloud-kubernetes-discovery;3.2.0 +org.springframework.cloud:spring-cloud-kubernetes-fabric8-autoconfig;3.2.0 +org.springframework.cloud:spring-cloud-kubernetes-fabric8-config;3.2.0 +org.springframework.cloud:spring-cloud-kubernetes-fabric8-discovery;3.2.0 +org.springframework.cloud:spring-cloud-kubernetes-fabric8-istio;3.2.0 +org.springframework.cloud:spring-cloud-kubernetes-fabric8-leader;3.2.0 +org.springframework.cloud:spring-cloud-kubernetes-fabric8-loadbalancer;3.2.0 +org.springframework.cloud:spring-cloud-kubernetes-test-support;3.2.0 +org.springframework.cloud:spring-cloud-loadbalancer;4.2.0 +org.springframework.cloud:spring-cloud-netflix-dependencies;4.2.0 +org.springframework.cloud:spring-cloud-netflix-eureka-client;4.2.0 +org.springframework.cloud:spring-cloud-netflix-eureka-server;4.2.0 +org.springframework.cloud:spring-cloud-openfeign-core;4.2.0 +org.springframework.cloud:spring-cloud-openfeign-dependencies;4.2.0 +org.springframework.cloud:spring-cloud-starter;4.2.0 +org.springframework.cloud:spring-cloud-starter-bootstrap;4.2.0 +org.springframework.cloud:spring-cloud-starter-bus-amqp;4.2.0 +org.springframework.cloud:spring-cloud-starter-bus-kafka;4.2.0 +org.springframework.cloud:spring-cloud-starter-bus-stream;4.2.0 +org.springframework.cloud:spring-cloud-starter-circuitbreaker-reactor-resilience4j;3.2.0 +org.springframework.cloud:spring-cloud-starter-circuitbreaker-resilience4j;3.2.0 +org.springframework.cloud:spring-cloud-starter-circuitbreaker-spring-retry;3.2.0 +org.springframework.cloud:spring-cloud-starter-config;4.2.0 +org.springframework.cloud:spring-cloud-starter-consul;4.2.0 +org.springframework.cloud:spring-cloud-starter-consul-all;4.2.0 +org.springframework.cloud:spring-cloud-starter-consul-bus;4.2.0 +org.springframework.cloud:spring-cloud-starter-consul-config;4.2.0 +org.springframework.cloud:spring-cloud-starter-consul-discovery;4.2.0 +org.springframework.cloud:spring-cloud-starter-contract-stub-runner;4.2.0 +org.springframework.cloud:spring-cloud-starter-contract-stub-runner-jetty;4.2.0 +org.springframework.cloud:spring-cloud-starter-contract-verifier;4.2.0 +org.springframework.cloud:spring-cloud-starter-function-web;4.2.0 +org.springframework.cloud:spring-cloud-starter-function-webflux;4.2.0 +org.springframework.cloud:spring-cloud-starter-gateway;4.2.0 +org.springframework.cloud:spring-cloud-starter-gateway-mvc;4.2.0 +org.springframework.cloud:spring-cloud-starter-kubernetes-client;3.2.0 +org.springframework.cloud:spring-cloud-starter-kubernetes-client-all;3.2.0 +org.springframework.cloud:spring-cloud-starter-kubernetes-client-config;3.2.0 +org.springframework.cloud:spring-cloud-starter-kubernetes-client-loadbalancer;3.2.0 +org.springframework.cloud:spring-cloud-starter-kubernetes-discoveryclient;3.2.0 +org.springframework.cloud:spring-cloud-starter-kubernetes-fabric8;3.2.0 +org.springframework.cloud:spring-cloud-starter-kubernetes-fabric8-all;3.2.0 +org.springframework.cloud:spring-cloud-starter-kubernetes-fabric8-config;3.2.0 +org.springframework.cloud:spring-cloud-starter-kubernetes-fabric8-loadbalancer;3.2.0 +org.springframework.cloud:spring-cloud-starter-loadbalancer;4.2.0 +org.springframework.cloud:spring-cloud-starter-netflix-eureka-client;4.2.0 +org.springframework.cloud:spring-cloud-starter-netflix-eureka-server;4.2.0 +org.springframework.cloud:spring-cloud-starter-openfeign;4.2.0 +org.springframework.cloud:spring-cloud-starter-stream-kafka;4.2.0 +org.springframework.cloud:spring-cloud-starter-stream-rabbit;4.2.0 +org.springframework.cloud:spring-cloud-starter-task;3.2.0 +org.springframework.cloud:spring-cloud-starter-vault-config;4.2.0 +org.springframework.cloud:spring-cloud-starter-zookeeper;4.2.0 +org.springframework.cloud:spring-cloud-starter-zookeeper-all;4.2.0 +org.springframework.cloud:spring-cloud-starter-zookeeper-config;4.2.0 +org.springframework.cloud:spring-cloud-starter-zookeeper-discovery;4.2.0 +org.springframework.cloud:spring-cloud-stream;4.2.0 +org.springframework.cloud:spring-cloud-stream-binder-kafka;4.2.0 +org.springframework.cloud:spring-cloud-stream-binder-kafka-core;4.2.0 +org.springframework.cloud:spring-cloud-stream-binder-kafka-reactive;4.2.0 +org.springframework.cloud:spring-cloud-stream-binder-kafka-streams;4.2.0 +org.springframework.cloud:spring-cloud-stream-binder-pulsar;4.2.0 +org.springframework.cloud:spring-cloud-stream-binder-rabbit;4.2.0 +org.springframework.cloud:spring-cloud-stream-binder-rabbit-core;4.2.0 +org.springframework.cloud:spring-cloud-stream-binder-rabbit-test-support;4.2.0 +org.springframework.cloud:spring-cloud-stream-dependencies;4.2.0 +org.springframework.cloud:spring-cloud-stream-schema-registry-client;4.2.0 +org.springframework.cloud:spring-cloud-stream-schema-registry-core;4.2.0 +org.springframework.cloud:spring-cloud-stream-schema-registry-server;4.2.0 +org.springframework.cloud:spring-cloud-stream-test-binder;4.2.0 +org.springframework.cloud:spring-cloud-stream-test-support;4.2.0 +org.springframework.cloud:spring-cloud-task-batch;3.2.0 +org.springframework.cloud:spring-cloud-task-core;3.2.0 +org.springframework.cloud:spring-cloud-task-dependencies;3.2.0 +org.springframework.cloud:spring-cloud-task-stream;3.2.0 +org.springframework.cloud:spring-cloud-test-support;4.2.0 +org.springframework.cloud:spring-cloud-vault-config;4.2.0 +org.springframework.cloud:spring-cloud-vault-config-aws;4.2.0 +org.springframework.cloud:spring-cloud-vault-config-consul;4.2.0 +org.springframework.cloud:spring-cloud-vault-config-databases;4.2.0 +org.springframework.cloud:spring-cloud-vault-config-rabbitmq;4.2.0 +org.springframework.cloud:spring-cloud-vault-dependencies;4.2.0 +org.springframework.cloud:spring-cloud-zookeeper-config;4.2.0 +org.springframework.cloud:spring-cloud-zookeeper-core;4.2.0 +org.springframework.cloud:spring-cloud-zookeeper-dependencies;4.2.0 +org.springframework.cloud:spring-cloud-zookeeper-discovery;4.2.0 +org.springframework.credhub:spring-credhub-core;2.1.1.RELEASE +org.springframework.data:spring-data-bom;2024.1.2 +org.springframework.data:spring-data-cassandra;4.4.2 +org.springframework.data:spring-data-commons;3.4.2 +org.springframework.data:spring-data-couchbase;5.4.2 +org.springframework.data:spring-data-elasticsearch;5.4.2 +org.springframework.data:spring-data-envers;3.4.2 +org.springframework.data:spring-data-jdbc;3.4.2 +org.springframework.data:spring-data-jpa;3.4.2 +org.springframework.data:spring-data-keyvalue;3.4.2 +org.springframework.data:spring-data-ldap;3.4.2 +org.springframework.data:spring-data-mongodb;4.4.2 +org.springframework.data:spring-data-neo4j;7.4.2 +org.springframework.data:spring-data-r2dbc;3.4.2 +org.springframework.data:spring-data-redis;3.4.2 +org.springframework.data:spring-data-relational;3.4.2 +org.springframework.data:spring-data-rest-core;4.4.2 +org.springframework.data:spring-data-rest-hal-explorer;4.4.2 +org.springframework.data:spring-data-rest-webmvc;4.4.2 +org.springframework.graphql:spring-graphql;1.3.3 +org.springframework.graphql:spring-graphql-test;1.3.3 +org.springframework.hateoas:spring-hateoas;2.4.1 +org.springframework.integration:spring-integration-amqp;6.4.1 +org.springframework.integration:spring-integration-bom;6.4.1 +org.springframework.integration:spring-integration-camel;6.4.1 +org.springframework.integration:spring-integration-cassandra;6.4.1 +org.springframework.integration:spring-integration-core;6.4.1 +org.springframework.integration:spring-integration-debezium;6.4.1 +org.springframework.integration:spring-integration-event;6.4.1 +org.springframework.integration:spring-integration-feed;6.4.1 +org.springframework.integration:spring-integration-file;6.4.1 +org.springframework.integration:spring-integration-ftp;6.4.1 +org.springframework.integration:spring-integration-graphql;6.4.1 +org.springframework.integration:spring-integration-groovy;6.4.1 +org.springframework.integration:spring-integration-hazelcast;6.4.1 +org.springframework.integration:spring-integration-http;6.4.1 +org.springframework.integration:spring-integration-ip;6.4.1 +org.springframework.integration:spring-integration-jdbc;6.4.1 +org.springframework.integration:spring-integration-jms;6.4.1 +org.springframework.integration:spring-integration-jmx;6.4.1 +org.springframework.integration:spring-integration-jpa;6.4.1 +org.springframework.integration:spring-integration-kafka;6.4.1 +org.springframework.integration:spring-integration-mail;6.4.1 +org.springframework.integration:spring-integration-mongodb;6.4.1 +org.springframework.integration:spring-integration-mqtt;6.4.1 +org.springframework.integration:spring-integration-r2dbc;6.4.1 +org.springframework.integration:spring-integration-redis;6.4.1 +org.springframework.integration:spring-integration-rsocket;6.4.1 +org.springframework.integration:spring-integration-scripting;6.4.1 +org.springframework.integration:spring-integration-sftp;6.4.1 +org.springframework.integration:spring-integration-smb;6.4.1 +org.springframework.integration:spring-integration-stomp;6.4.1 +org.springframework.integration:spring-integration-stream;6.4.1 +org.springframework.integration:spring-integration-syslog;6.4.1 +org.springframework.integration:spring-integration-test;6.4.1 +org.springframework.integration:spring-integration-test-support;6.4.1 +org.springframework.integration:spring-integration-webflux;6.4.1 +org.springframework.integration:spring-integration-websocket;6.4.1 +org.springframework.integration:spring-integration-ws;6.4.1 +org.springframework.integration:spring-integration-xml;6.4.1 +org.springframework.integration:spring-integration-xmpp;6.4.1 +org.springframework.integration:spring-integration-zeromq;6.4.1 +org.springframework.integration:spring-integration-zip;6.4.1 +org.springframework.integration:spring-integration-zookeeper;6.4.1 +org.springframework.kafka:spring-kafka;3.3.2 +org.springframework.kafka:spring-kafka-test;3.3.2 +org.springframework.ldap:spring-ldap-core;3.2.10 +org.springframework.ldap:spring-ldap-ldif-core;3.2.10 +org.springframework.ldap:spring-ldap-odm;3.2.10 +org.springframework.ldap:spring-ldap-test;3.2.10 +org.springframework.pulsar:spring-pulsar;1.2.2 +org.springframework.pulsar:spring-pulsar-bom;1.2.2 +org.springframework.pulsar:spring-pulsar-cache-provider;1.2.2 +org.springframework.pulsar:spring-pulsar-cache-provider-caffeine;1.2.2 +org.springframework.pulsar:spring-pulsar-reactive;1.2.2 +org.springframework.pulsar:spring-pulsar-test;1.2.2 +org.springframework.restdocs:spring-restdocs-asciidoctor;3.0.3 +org.springframework.restdocs:spring-restdocs-bom;3.0.3 +org.springframework.restdocs:spring-restdocs-core;3.0.3 +org.springframework.restdocs:spring-restdocs-mockmvc;3.0.3 +org.springframework.restdocs:spring-restdocs-restassured;3.0.3 +org.springframework.restdocs:spring-restdocs-webtestclient;3.0.3 +org.springframework.retry:spring-retry;2.0.11 +org.springframework.security:spring-security-acl;6.4.2 +org.springframework.security:spring-security-aspects;6.4.2 +org.springframework.security:spring-security-bom;6.4.2 +org.springframework.security:spring-security-cas;6.4.2 +org.springframework.security:spring-security-config;6.4.2 +org.springframework.security:spring-security-core;6.4.2 +org.springframework.security:spring-security-crypto;6.4.2 +org.springframework.security:spring-security-data;6.4.2 +org.springframework.security:spring-security-ldap;6.4.2 +org.springframework.security:spring-security-messaging;6.4.2 +org.springframework.security:spring-security-oauth2-authorization-server;1.4.1 +org.springframework.security:spring-security-oauth2-client;6.4.2 +org.springframework.security:spring-security-oauth2-core;6.4.2 +org.springframework.security:spring-security-oauth2-jose;6.4.2 +org.springframework.security:spring-security-oauth2-resource-server;6.4.2 +org.springframework.security:spring-security-rsocket;6.4.2 +org.springframework.security:spring-security-saml2-service-provider;6.4.2 +org.springframework.security:spring-security-taglibs;6.4.2 +org.springframework.security:spring-security-test;6.4.2 +org.springframework.security:spring-security-web;6.4.2 +org.springframework.session:spring-session-bom;3.4.1 +org.springframework.session:spring-session-core;3.4.1 +org.springframework.session:spring-session-data-mongodb;3.4.1 +org.springframework.session:spring-session-data-redis;3.4.1 +org.springframework.session:spring-session-hazelcast;3.4.1 +org.springframework.session:spring-session-jdbc;3.4.1 +org.springframework.vault:spring-vault-core;3.1.2 +org.springframework.ws:spring-ws-bom;4.0.11 +org.springframework.ws:spring-ws-core;4.0.11 +org.springframework.ws:spring-ws-security;4.0.11 +org.springframework.ws:spring-ws-support;4.0.11 +org.springframework.ws:spring-ws-test;4.0.11 +org.springframework.ws:spring-xml;4.0.11 +org.springframework:spring-aop;6.2.2 +org.springframework:spring-aspects;6.2.2 +org.springframework:spring-beans;6.2.2 +org.springframework:spring-context;6.2.2 +org.springframework:spring-context-indexer;6.2.2 +org.springframework:spring-context-support;6.2.2 +org.springframework:spring-core;6.2.2 +org.springframework:spring-core-test;6.2.2 +org.springframework:spring-expression;6.2.2 +org.springframework:spring-framework-bom;6.2.2 +org.springframework:spring-instrument;6.2.2 +org.springframework:spring-jcl;6.2.2 +org.springframework:spring-jdbc;6.2.2 +org.springframework:spring-jms;6.2.2 +org.springframework:spring-messaging;6.2.2 +org.springframework:spring-orm;6.2.2 +org.springframework:spring-oxm;6.2.2 +org.springframework:spring-r2dbc;6.2.2 +org.springframework:spring-test;6.2.2 +org.springframework:spring-tx;6.2.2 +org.springframework:spring-web;6.2.2 +org.springframework:spring-webflux;6.2.2 +org.springframework:spring-webmvc;6.2.2 +org.springframework:spring-websocket;6.2.2 +org.testcontainers:activemq;1.20.4 +org.testcontainers:azure;1.20.4 +org.testcontainers:cassandra;1.20.4 +org.testcontainers:chromadb;1.20.4 +org.testcontainers:clickhouse;1.20.4 +org.testcontainers:cockroachdb;1.20.4 +org.testcontainers:consul;1.20.4 +org.testcontainers:couchbase;1.20.4 +org.testcontainers:cratedb;1.20.4 +org.testcontainers:database-commons;1.20.4 +org.testcontainers:databend;1.20.4 +org.testcontainers:db2;1.20.4 +org.testcontainers:dynalite;1.20.4 +org.testcontainers:elasticsearch;1.20.4 +org.testcontainers:gcloud;1.20.4 +org.testcontainers:grafana;1.20.4 +org.testcontainers:hivemq;1.20.4 +org.testcontainers:influxdb;1.20.4 +org.testcontainers:jdbc;1.20.4 +org.testcontainers:junit-jupiter;1.20.4 +org.testcontainers:k3s;1.20.4 +org.testcontainers:k6;1.20.4 +org.testcontainers:kafka;1.20.4 +org.testcontainers:localstack;1.20.4 +org.testcontainers:mariadb;1.20.4 +org.testcontainers:milvus;1.20.4 +org.testcontainers:minio;1.20.4 +org.testcontainers:mockserver;1.20.4 +org.testcontainers:mongodb;1.20.4 +org.testcontainers:mssqlserver;1.20.4 +org.testcontainers:mysql;1.20.4 +org.testcontainers:neo4j;1.20.4 +org.testcontainers:nginx;1.20.4 +org.testcontainers:oceanbase;1.20.4 +org.testcontainers:ollama;1.20.4 +org.testcontainers:openfga;1.20.4 +org.testcontainers:oracle-free;1.20.4 +org.testcontainers:oracle-xe;1.20.4 +org.testcontainers:orientdb;1.20.4 +org.testcontainers:postgresql;1.20.4 +org.testcontainers:presto;1.20.4 +org.testcontainers:pulsar;1.20.4 +org.testcontainers:qdrant;1.20.4 +org.testcontainers:questdb;1.20.4 +org.testcontainers:r2dbc;1.20.4 +org.testcontainers:rabbitmq;1.20.4 +org.testcontainers:redpanda;1.20.4 +org.testcontainers:selenium;1.20.4 +org.testcontainers:solace;1.20.4 +org.testcontainers:solr;1.20.4 +org.testcontainers:spock;1.20.4 +org.testcontainers:testcontainers;1.20.4 +org.testcontainers:testcontainers-bom;1.20.4 +org.testcontainers:tidb;1.20.4 +org.testcontainers:timeplus;1.20.4 +org.testcontainers:toxiproxy;1.20.4 +org.testcontainers:trino;1.20.4 +org.testcontainers:typesense;1.20.4 +org.testcontainers:vault;1.20.4 +org.testcontainers:weaviate;1.20.4 +org.testcontainers:yugabytedb;1.20.4 +org.thymeleaf.extras:thymeleaf-extras-springsecurity6;3.1.3.RELEASE +org.thymeleaf:thymeleaf;3.1.3.RELEASE +org.thymeleaf:thymeleaf-spring6;3.1.3.RELEASE +org.tmatesoft.svnkit:svnkit;1.10.11 +org.webjars:webjars-locator-core;0.59 +org.webjars:webjars-locator-lite;1.0.1 +org.wiremock:wiremock-standalone;3.4.2 +org.xerial:sqlite-jdbc;3.47.2.0 +org.xmlunit:xmlunit-assertj;2.10.0 +org.xmlunit:xmlunit-assertj3;2.10.0 +org.xmlunit:xmlunit-core;2.10.0 +org.xmlunit:xmlunit-jakarta-jaxb-impl;2.10.0 +org.xmlunit:xmlunit-legacy;2.10.0 +org.xmlunit:xmlunit-matchers;2.10.0 +org.xmlunit:xmlunit-placeholders;2.10.0 +org.yaml:snakeyaml;2.3 +redis.clients:jedis;5.2.0 +wsdl4j:wsdl4j;1.6.3 diff --git a/sdk/spring/spring-cloud-azure-actuator-autoconfigure/CHANGELOG.md b/sdk/spring/spring-cloud-azure-actuator-autoconfigure/CHANGELOG.md index edb5e88a52c4..a57cc1805451 100644 --- a/sdk/spring/spring-cloud-azure-actuator-autoconfigure/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-actuator-autoconfigure/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 5.20.0-beta.1 (Unreleased) +## 5.21.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 5.20.1 (2025-03-03) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5201-2025-03-03) for more details. + +## 5.20.0 (2025-02-12) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5200-2025-02-12) for more details. + ## 5.19.0 (2024-12-17) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5190-2024-12-17) for more details. diff --git a/sdk/spring/spring-cloud-azure-actuator-autoconfigure/README.md b/sdk/spring/spring-cloud-azure-actuator-autoconfigure/README.md index e69de29bb2d1..bbaecbaa3de8 100644 --- a/sdk/spring/spring-cloud-azure-actuator-autoconfigure/README.md +++ b/sdk/spring/spring-cloud-azure-actuator-autoconfigure/README.md @@ -0,0 +1 @@ +Please refer to [spring/README.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/README.md) for more details. diff --git a/sdk/spring/spring-cloud-azure-actuator-autoconfigure/pom.xml b/sdk/spring/spring-cloud-azure-actuator-autoconfigure/pom.xml index a4a486da9d1d..2a29adc7a60f 100644 --- a/sdk/spring/spring-cloud-azure-actuator-autoconfigure/pom.xml +++ b/sdk/spring/spring-cloud-azure-actuator-autoconfigure/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-cloud-azure-actuator-autoconfigure - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Actuator AutoConfigure Spring Cloud Azure Starter Actuator AutoConfigure @@ -41,7 +41,7 @@ org.springframework.boot spring-boot-actuator-autoconfigure - 3.4.1 + 3.4.2 compile @@ -52,17 +52,17 @@ com.azure.spring spring-cloud-azure-actuator - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure.spring spring-cloud-azure-autoconfigure - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure.spring spring-cloud-azure-appconfiguration-config-web - 5.20.0-beta.1 + 5.21.0-beta.1 true @@ -72,55 +72,55 @@ com.azure azure-core - 1.54.1 + 1.55.3 true com.azure azure-cosmos - 4.66.0 + 4.67.0 true com.azure azure-data-appconfiguration - 1.7.3 + 1.7.4 true com.azure azure-messaging-eventhubs - 5.19.2 + 5.20.1 true com.azure azure-security-keyvault-certificates - 4.7.1 + 4.7.3 true com.azure azure-security-keyvault-secrets - 4.9.1 + 4.9.3 true com.azure azure-storage-blob - 12.29.0 + 12.29.1 true com.azure azure-storage-file-share - 12.25.1 + 12.25.2 true com.azure azure-storage-queue - 12.24.0 + 12.24.1 true @@ -128,7 +128,7 @@ org.springframework.boot spring-boot-starter-test - 3.4.1 + 3.4.2 test @@ -200,8 +200,8 @@ com.fasterxml.jackson.core:jackson-databind:[2.18.2] - org.springframework.boot:spring-boot-actuator:[3.4.1] - org.springframework.boot:spring-boot-actuator-autoconfigure:[3.4.1] + org.springframework.boot:spring-boot-actuator:[3.4.2] + org.springframework.boot:spring-boot-actuator-autoconfigure:[3.4.2] diff --git a/sdk/spring/spring-cloud-azure-actuator/CHANGELOG.md b/sdk/spring/spring-cloud-azure-actuator/CHANGELOG.md index edb5e88a52c4..a57cc1805451 100644 --- a/sdk/spring/spring-cloud-azure-actuator/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-actuator/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 5.20.0-beta.1 (Unreleased) +## 5.21.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 5.20.1 (2025-03-03) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5201-2025-03-03) for more details. + +## 5.20.0 (2025-02-12) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5200-2025-02-12) for more details. + ## 5.19.0 (2024-12-17) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5190-2024-12-17) for more details. diff --git a/sdk/spring/spring-cloud-azure-actuator/README.md b/sdk/spring/spring-cloud-azure-actuator/README.md index e69de29bb2d1..bbaecbaa3de8 100644 --- a/sdk/spring/spring-cloud-azure-actuator/README.md +++ b/sdk/spring/spring-cloud-azure-actuator/README.md @@ -0,0 +1 @@ +Please refer to [spring/README.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/README.md) for more details. diff --git a/sdk/spring/spring-cloud-azure-actuator/pom.xml b/sdk/spring/spring-cloud-azure-actuator/pom.xml index d763033ac0da..602aff7432d4 100644 --- a/sdk/spring/spring-cloud-azure-actuator/pom.xml +++ b/sdk/spring/spring-cloud-azure-actuator/pom.xml @@ -17,7 +17,7 @@ com.azure.spring spring-cloud-azure-actuator - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Actuator https://microsoft.github.io/spring-cloud-azure @@ -45,7 +45,7 @@ org.springframework.boot spring-boot-actuator - 3.4.1 + 3.4.2 compile @@ -55,68 +55,68 @@ com.azure azure-core - 1.54.1 + 1.55.3 true com.azure azure-cosmos - 4.66.0 + 4.67.0 true com.azure azure-data-appconfiguration - 1.7.3 + 1.7.4 true com.azure azure-messaging-eventhubs - 5.19.2 + 5.20.1 true com.azure azure-security-keyvault-certificates - 4.7.1 + 4.7.3 true com.azure azure-security-keyvault-secrets - 4.9.1 + 4.9.3 true com.azure azure-storage-blob - 12.29.0 + 12.29.1 true com.azure azure-storage-file-share - 12.25.1 + 12.25.2 true com.azure azure-storage-queue - 12.24.0 + 12.24.1 true com.azure.spring spring-cloud-azure-appconfiguration-config-web - 5.20.0-beta.1 + 5.21.0-beta.1 true org.springframework.boot spring-boot-starter-test - 3.4.1 + 3.4.2 test @@ -184,7 +184,7 @@ - org.springframework.boot:spring-boot-actuator:[3.4.1] + org.springframework.boot:spring-boot-actuator:[3.4.2] diff --git a/sdk/spring/spring-cloud-azure-appconfiguration-config-web/CHANGELOG.md b/sdk/spring/spring-cloud-azure-appconfiguration-config-web/CHANGELOG.md index d97cb168e6ab..5492e1b2c976 100644 --- a/sdk/spring/spring-cloud-azure-appconfiguration-config-web/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-appconfiguration-config-web/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 5.20.0-beta.1 (Unreleased) +## 5.21.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 5.20.1 (2025-03-03) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5201-2025-03-03) for more details. + +## 5.20.0 (2025-02-12) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5200-2025-02-12) for more details. + ## 5.19.0 (2024-12-17) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5190-2024-12-17) for more details. diff --git a/sdk/spring/spring-cloud-azure-appconfiguration-config-web/pom.xml b/sdk/spring/spring-cloud-azure-appconfiguration-config-web/pom.xml index 4935d03fefdd..946eccb46dab 100644 --- a/sdk/spring/spring-cloud-azure-appconfiguration-config-web/pom.xml +++ b/sdk/spring/spring-cloud-azure-appconfiguration-config-web/pom.xml @@ -9,7 +9,7 @@ 4.0.0 com.azure.spring spring-cloud-azure-appconfiguration-config-web - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure App Configuration Config Web Integration of Spring Cloud Config and Azure App Configuration Service @@ -21,17 +21,17 @@ com.azure.spring spring-cloud-azure-appconfiguration-config - 5.20.0-beta.1 + 5.21.0-beta.1 org.springframework.boot spring-boot-starter-web - 3.4.1 + 3.4.2 org.springframework.boot spring-boot-starter-actuator - 3.4.1 + 3.4.2 true @@ -43,7 +43,7 @@ org.springframework.boot spring-boot-starter-test - 3.4.1 + 3.4.2 test @@ -118,8 +118,8 @@ - org.springframework.boot:spring-boot-starter-actuator:[3.4.1] - org.springframework.boot:spring-boot-starter-web:[3.4.1] + org.springframework.boot:spring-boot-starter-actuator:[3.4.2] + org.springframework.boot:spring-boot-starter-web:[3.4.2] org.springframework.cloud:spring-cloud-bus:[4.2.0] diff --git a/sdk/spring/spring-cloud-azure-appconfiguration-config/CHANGELOG.md b/sdk/spring/spring-cloud-azure-appconfiguration-config/CHANGELOG.md index 765f9fc9a16e..0bfcc04e67da 100644 --- a/sdk/spring/spring-cloud-azure-appconfiguration-config/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-appconfiguration-config/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 5.20.0-beta.1 (Unreleased) +## 5.21.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 5.20.1 (2025-03-03) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5201-2025-03-03) for more details. + +## 5.20.0 (2025-02-12) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5200-2025-02-12) for more details. + ## 5.19.0 (2024-12-17) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5190-2024-12-17) for more details. diff --git a/sdk/spring/spring-cloud-azure-appconfiguration-config/pom.xml b/sdk/spring/spring-cloud-azure-appconfiguration-config/pom.xml index ca003da589e4..b91bb4f179f3 100644 --- a/sdk/spring/spring-cloud-azure-appconfiguration-config/pom.xml +++ b/sdk/spring/spring-cloud-azure-appconfiguration-config/pom.xml @@ -9,7 +9,7 @@ 4.0.0 com.azure.spring spring-cloud-azure-appconfiguration-config - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure App Configuration Config Integration of Spring Cloud Config and Azure App Configuration Service @@ -21,12 +21,12 @@ org.springframework.boot spring-boot-autoconfigure - 3.4.1 + 3.4.2 org.springframework.boot spring-boot-configuration-processor - 3.4.1 + 3.4.2 true @@ -42,45 +42,45 @@ org.springframework.boot spring-boot-actuator - 3.4.1 + 3.4.2 compile com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-data-appconfiguration - 1.7.3 + 1.7.4 com.azure azure-identity - 1.15.0 + 1.15.4 com.azure azure-security-keyvault-secrets - 4.9.1 + 4.9.3 com.azure.spring spring-cloud-azure-service - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure.spring spring-cloud-azure-autoconfigure - 5.20.0-beta.1 + 5.21.0-beta.1 org.springframework.boot spring-boot-starter-test - 3.4.1 + 3.4.2 test @@ -179,10 +179,10 @@ com.fasterxml.jackson.core:jackson-annotations:[2.18.2] com.fasterxml.jackson.core:jackson-databind:[2.18.2] - org.springframework.boot:spring-boot-actuator:[3.4.1] - org.springframework.boot:spring-boot-autoconfigure:[3.4.1] + org.springframework.boot:spring-boot-actuator:[3.4.2] + org.springframework.boot:spring-boot-autoconfigure:[3.4.2] org.springframework.cloud:spring-cloud-context:[4.2.0] - org.springframework.boot:spring-boot-configuration-processor:[3.4.1] + org.springframework.boot:spring-boot-configuration-processor:[3.4.2] org.springframework.cloud:spring-cloud-starter-bootstrap:[4.2.0] diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/CHANGELOG.md b/sdk/spring/spring-cloud-azure-autoconfigure/CHANGELOG.md index edb5e88a52c4..a57cc1805451 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-autoconfigure/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 5.20.0-beta.1 (Unreleased) +## 5.21.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 5.20.1 (2025-03-03) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5201-2025-03-03) for more details. + +## 5.20.0 (2025-02-12) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5200-2025-02-12) for more details. + ## 5.19.0 (2024-12-17) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5190-2024-12-17) for more details. diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/README.md b/sdk/spring/spring-cloud-azure-autoconfigure/README.md index e69de29bb2d1..bbaecbaa3de8 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/README.md +++ b/sdk/spring/spring-cloud-azure-autoconfigure/README.md @@ -0,0 +1 @@ +Please refer to [spring/README.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/README.md) for more details. diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/pom.xml b/sdk/spring/spring-cloud-azure-autoconfigure/pom.xml index 75524353cb99..30e6dd99a029 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/pom.xml +++ b/sdk/spring/spring-cloud-azure-autoconfigure/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-cloud-azure-autoconfigure - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure AutoConfigure Spring Cloud Azure AutoConfigure @@ -41,13 +41,13 @@ com.azure.spring spring-cloud-azure-service - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure.spring spring-cloud-azure-resourcemanager - 5.20.0-beta.1 + 5.21.0-beta.1 true @@ -56,13 +56,13 @@ com.azure.spring spring-integration-azure-eventhubs - 5.20.0-beta.1 + 5.21.0-beta.1 true com.azure azure-messaging-eventhubs-checkpointstore-blob - 1.20.2 + 1.20.5 true @@ -70,7 +70,7 @@ com.azure.spring spring-integration-azure-servicebus - 5.20.0-beta.1 + 5.21.0-beta.1 true @@ -78,7 +78,7 @@ com.azure.spring spring-integration-azure-storage-queue - 5.20.0-beta.1 + 5.21.0-beta.1 true @@ -86,7 +86,7 @@ org.springframework.kafka spring-kafka - 3.3.1 + 3.3.2 true @@ -100,19 +100,19 @@ io.lettuce lettuce-core - 6.4.1.RELEASE + 6.4.2.RELEASE true org.springframework.data spring-data-redis - 3.4.1 + 3.4.2 true org.springframework spring-tx - 6.2.1 + 6.2.2 true @@ -120,7 +120,7 @@ com.azure azure-spring-data-cosmos - 5.20.0-beta.1 + 5.21.0-beta.1 true @@ -128,7 +128,7 @@ org.springframework spring-jms - 6.2.1 + 6.2.2 true @@ -160,7 +160,7 @@ com.azure azure-core - 1.54.1 + 1.55.3 true @@ -184,13 +184,13 @@ com.azure azure-core-amqp - 2.9.12 + 2.9.16 true com.azure azure-identity - 1.15.0 + 1.15.4 true @@ -202,7 +202,7 @@ com.azure azure-cosmos - 4.66.0 + 4.67.0 true @@ -214,13 +214,13 @@ com.azure azure-data-appconfiguration - 1.7.3 + 1.7.4 true com.azure azure-messaging-servicebus - 7.17.8 + 7.17.9 true @@ -232,31 +232,37 @@ com.azure azure-messaging-eventhubs - 5.19.2 + 5.20.1 true com.azure azure-messaging-eventgrid - 4.27.0 + 4.29.0 true com.azure azure-security-keyvault-certificates - 4.7.1 + 4.7.3 + true + + + com.azure + azure-security-keyvault-jca + 2.10.0 true com.azure azure-security-keyvault-secrets - 4.9.1 + 4.9.3 true com.azure azure-storage-blob - 12.29.0 + 12.29.1 true @@ -268,7 +274,7 @@ com.azure azure-storage-file-share - 12.25.1 + 12.25.2 true @@ -280,7 +286,7 @@ com.azure azure-storage-queue - 12.24.0 + 12.24.1 true @@ -294,25 +300,25 @@ org.springframework.boot spring-boot-autoconfigure - 3.4.1 + 3.4.2 org.springframework spring-context-support - 6.2.1 + 6.2.2 true org.springframework.boot spring-boot-actuator-autoconfigure - 3.4.1 + 3.4.2 true org.springframework.boot spring-boot-configuration-processor - 3.4.1 + 3.4.2 true @@ -373,7 +379,7 @@ com.azure azure-identity-extensions - 1.2.0 + 1.2.1 true @@ -419,19 +425,19 @@ org.springframework.boot spring-boot-starter-test - 3.4.1 + 3.4.2 test org.springframework spring-core-test - 6.2.1 + 6.2.2 test org.springframework.boot spring-boot-configuration-metadata - 3.4.1 + 3.4.2 test @@ -467,14 +473,14 @@ org.postgresql postgresql - 42.7.4 + 42.7.5 test org.springframework spring-jdbc - 6.2.1 + 6.2.2 test @@ -544,26 +550,26 @@ com.fasterxml.jackson.dataformat:jackson-dataformat-xml:[2.18.2] com.fasterxml.jackson.datatype:jackson-datatype-jsr310:[2.18.2] com.fasterxml.jackson.module:jackson-module-afterburner:[2.18.2] - io.lettuce:lettuce-core:[6.4.1.RELEASE] + io.lettuce:lettuce-core:[6.4.2.RELEASE] jakarta.servlet:jakarta.servlet-api:[6.0.0] jakarta.validation:jakarta.validation-api:[3.0.2] org.hibernate.validator:hibernate-validator:[8.0.2.Final] org.messaginghub:pooled-jms:[3.1.7] - org.postgresql:postgresql:[42.7.4] - org.springframework.boot:spring-boot-actuator-autoconfigure:[3.4.1] - org.springframework.boot:spring-boot-autoconfigure:[3.4.1] - org.springframework.boot:spring-boot-configuration-processor:[3.4.1] + org.postgresql:postgresql:[42.7.5] + org.springframework.boot:spring-boot-actuator-autoconfigure:[3.4.2] + org.springframework.boot:spring-boot-autoconfigure:[3.4.2] + org.springframework.boot:spring-boot-configuration-processor:[3.4.2] org.springframework.cloud:spring-cloud-starter-stream-kafka:[4.2.0] - org.springframework.data:spring-data-redis:[3.4.1] - org.springframework.kafka:spring-kafka:[3.3.1] + org.springframework.data:spring-data-redis:[3.4.2] + org.springframework.kafka:spring-kafka:[3.3.2] org.springframework.security:spring-security-config:[6.4.2] org.springframework.security:spring-security-oauth2-client:[6.4.2] org.springframework.security:spring-security-oauth2-jose:[6.4.2] org.springframework.security:spring-security-oauth2-resource-server:[6.4.2] - org.springframework:spring-context-support:[6.2.1] - org.springframework:spring-jdbc:[6.2.1] - org.springframework:spring-jms:[6.2.1] - org.springframework:spring-tx:[6.2.1] + org.springframework:spring-context-support:[6.2.2] + org.springframework:spring-jdbc:[6.2.2] + org.springframework:spring-jms:[6.2.2] + org.springframework:spring-tx:[6.2.2] diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/context/AzureServiceClientBuilderFactoryConfiguration.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/context/AzureServiceClientBuilderFactoryConfiguration.java index 599d3f6c1e6a..83ba863cb840 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/context/AzureServiceClientBuilderFactoryConfiguration.java +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/context/AzureServiceClientBuilderFactoryConfiguration.java @@ -4,10 +4,8 @@ package com.azure.spring.cloud.autoconfigure.implementation.context; import com.azure.spring.cloud.core.implementation.factory.AbstractAzureServiceClientBuilderFactory; -import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Role; /** * {@code @Configuration} class that registers a {@link AzureServiceClientBuilderFactoryPostProcessor} @@ -16,7 +14,6 @@ * @since 5.19.0 */ @Configuration(proxyBeanMethods = false) -@Role(BeanDefinition.ROLE_INFRASTRUCTURE) class AzureServiceClientBuilderFactoryConfiguration { /** @@ -24,7 +21,6 @@ class AzureServiceClientBuilderFactoryConfiguration { * @return the BPP. */ @Bean - @Role(BeanDefinition.ROLE_INFRASTRUCTURE) static AzureServiceClientBuilderFactoryPostProcessor builderFactoryBeanPostProcessor() { return new AzureServiceClientBuilderFactoryPostProcessor(); } diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/context/AzureTokenCredentialAutoConfiguration.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/context/AzureTokenCredentialAutoConfiguration.java index 8d672810f2aa..88d4359e8007 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/context/AzureTokenCredentialAutoConfiguration.java +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/context/AzureTokenCredentialAutoConfiguration.java @@ -48,6 +48,7 @@ @Configuration(proxyBeanMethods = false) @AutoConfigureAfter(TaskExecutionAutoConfiguration.class) @Import(AzureServiceClientBuilderFactoryConfiguration.class) +@SuppressWarnings("deprecation") public class AzureTokenCredentialAutoConfiguration extends AzureServiceConfigurationBase { private static final Logger LOGGER = LoggerFactory.getLogger(AzureTokenCredentialAutoConfiguration.class); diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/eventhubs/kafka/AzureEventHubsKafkaAutoConfiguration.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/eventhubs/kafka/AzureEventHubsKafkaAutoConfiguration.java index b2bbf55eacfa..ed73cf8d4337 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/eventhubs/kafka/AzureEventHubsKafkaAutoConfiguration.java +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/eventhubs/kafka/AzureEventHubsKafkaAutoConfiguration.java @@ -14,13 +14,13 @@ import org.slf4j.LoggerFactory; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; import org.springframework.core.env.Environment; import org.springframework.kafka.core.KafkaTemplate; @@ -36,7 +36,6 @@ @ConditionalOnClass(KafkaTemplate.class) @ConditionalOnProperty(value = "spring.cloud.azure.eventhubs.kafka.enabled", havingValue = "true", matchIfMissing = true) @AutoConfigureAfter({ AzureEventHubsAutoConfiguration.class, AzureEventHubsResourceManagerAutoConfiguration.class }) -@Import(KafkaPropertiesConfiguration.class) public class AzureEventHubsKafkaAutoConfiguration { private static final Logger LOGGER = LoggerFactory.getLogger(AzureEventHubsKafkaAutoConfiguration.class); @@ -56,4 +55,10 @@ StaticConnectionStringProvider eventHubsKafkaConnect return new StaticConnectionStringProvider<>(AzureServiceType.EVENT_HUBS, connectionString); } + + @Bean + @ConditionalOnBean(value = AzureServiceType.EventHubs.class, parameterizedContainer = ServiceConnectionStringProvider.class) + static KafkaPropertiesBeanPostProcessor kafkaPropertiesBeanPostProcessor() { + return new KafkaPropertiesBeanPostProcessor(); + } } diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/eventhubs/kafka/KafkaPropertiesBeanPostProcessor.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/eventhubs/kafka/KafkaPropertiesBeanPostProcessor.java index b55ce88e8897..b8e0e0fef93e 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/eventhubs/kafka/KafkaPropertiesBeanPostProcessor.java +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/eventhubs/kafka/KafkaPropertiesBeanPostProcessor.java @@ -8,8 +8,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; +import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.boot.autoconfigure.kafka.KafkaProperties; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.core.ResolvableType; import java.util.ArrayList; import java.util.Collections; @@ -22,16 +26,12 @@ /** * {@link BeanPostProcessor} for {@link KafkaProperties} to configure connection string credentials. */ -class KafkaPropertiesBeanPostProcessor implements BeanPostProcessor { +class KafkaPropertiesBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware { private static final Logger LOGGER = LoggerFactory.getLogger(KafkaPropertiesBeanPostProcessor.class); private static final String SASL_CONFIG_VALUE = "org.apache.kafka.common.security.plain.PlainLoginModule required username=\"$ConnectionString\" password=\"%s\";%s"; - private final ServiceConnectionStringProvider connectionStringProvider; - - KafkaPropertiesBeanPostProcessor(ServiceConnectionStringProvider connectionStringProvider) { - this.connectionStringProvider = connectionStringProvider; - } + private ApplicationContext applicationContext; @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { @@ -43,8 +43,17 @@ public Object postProcessAfterInitialization(Object bean, String beanName) throw + " instead, which can be set as spring.kafka.boostrap-servers=EventHubsNamespacesFQDN:9093."); KafkaProperties kafkaProperties = (KafkaProperties) bean; - String connectionString = connectionStringProvider.getConnectionString(); + ResolvableType provider = ResolvableType.forClassWithGenerics(ServiceConnectionStringProvider.class, AzureServiceType.EventHubs.class); + ObjectProvider> beanProvider = applicationContext.getBeanProvider(provider); + + ServiceConnectionStringProvider connectionStringProvider = beanProvider.getIfAvailable(); + if (connectionStringProvider == null) { + LOGGER.debug("Cannot find a bean of type ServiceConnectionStringProvider, " + + "Spring Cloud Azure will skip performing JAAS enhancements on the KafkaProperties bean."); + return bean; + } + String connectionString = connectionStringProvider.getConnectionString(); String bootstrapServer = new EventHubsConnectionString(connectionString).getFullyQualifiedNamespace() + ":9093"; kafkaProperties.setBootstrapServers(new ArrayList<>(Collections.singletonList(bootstrapServer))); kafkaProperties.getProperties().put(SECURITY_PROTOCOL_CONFIG, SASL_SSL.name()); @@ -55,4 +64,8 @@ public Object postProcessAfterInitialization(Object bean, String beanName) throw return bean; } + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + this.applicationContext = applicationContext; + } } diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/eventhubs/kafka/KafkaPropertiesConfiguration.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/eventhubs/kafka/KafkaPropertiesConfiguration.java deleted file mode 100644 index e8c882df3b70..000000000000 --- a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/eventhubs/kafka/KafkaPropertiesConfiguration.java +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.spring.cloud.autoconfigure.implementation.eventhubs.kafka; - -import com.azure.spring.cloud.autoconfigure.implementation.kafka.AzureEventHubsKafkaOAuth2AutoConfiguration; -import com.azure.spring.cloud.core.provider.connectionstring.ServiceConnectionStringProvider; -import com.azure.spring.cloud.core.service.AzureServiceType; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; -import org.springframework.boot.autoconfigure.kafka.KafkaProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Role; - -/** - * {@code @Configuration} class that registers a {@link KafkaPropertiesBeanPostProcessor} - * bean capable of processing Kafka properties @{@link KafkaProperties}. - * - * @since 5.19.0 - * @deprecated 4.3.0 in favor of {@link AzureEventHubsKafkaOAuth2AutoConfiguration}. - */ -@Deprecated -@Configuration(proxyBeanMethods = false) -@Role(BeanDefinition.ROLE_INFRASTRUCTURE) -class KafkaPropertiesConfiguration { - - @Bean - @Role(BeanDefinition.ROLE_INFRASTRUCTURE) - @ConditionalOnBean(value = AzureServiceType.EventHubs.class, parameterizedContainer = ServiceConnectionStringProvider.class) - static KafkaPropertiesBeanPostProcessor kafkaPropertiesBeanPostProcessor( - ServiceConnectionStringProvider connectionStringProvider) { - return new KafkaPropertiesBeanPostProcessor(connectionStringProvider); - } -} diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/jdbc/AzureJdbcAutoConfiguration.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/jdbc/AzureJdbcAutoConfiguration.java index 38a987fc74f0..ac381ec55213 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/jdbc/AzureJdbcAutoConfiguration.java +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/jdbc/AzureJdbcAutoConfiguration.java @@ -3,7 +3,6 @@ package com.azure.spring.cloud.autoconfigure.implementation.jdbc; import com.azure.identity.extensions.implementation.template.AzureAuthenticationTemplate; -import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; @@ -13,7 +12,6 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Role; /** @@ -23,7 +21,6 @@ * @since 4.5.0 */ @Configuration(proxyBeanMethods = false) -@Role(BeanDefinition.ROLE_INFRASTRUCTURE) @ConditionalOnBean(DataSourceProperties.class) @ConditionalOnClass(AzureAuthenticationTemplate.class) @AutoConfigureAfter(DataSourceAutoConfiguration.class) @@ -31,7 +28,6 @@ public class AzureJdbcAutoConfiguration { @Bean @ConditionalOnMissingBean - @Role(BeanDefinition.ROLE_INFRASTRUCTURE) static JdbcPropertiesBeanPostProcessor jdbcConfigurationPropertiesBeanPostProcessor() { return new JdbcPropertiesBeanPostProcessor(); } diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/jms/AzureServiceBusJmsPropertiesBeanPostProcessor.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/jms/AzureServiceBusJmsPropertiesBeanPostProcessor.java index 4db04c3dca82..4c600055bba6 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/jms/AzureServiceBusJmsPropertiesBeanPostProcessor.java +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/jms/AzureServiceBusJmsPropertiesBeanPostProcessor.java @@ -9,14 +9,18 @@ import org.springframework.beans.BeansException; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.core.ResolvableType; import org.springframework.util.StringUtils; -class AzureServiceBusJmsPropertiesBeanPostProcessor implements BeanPostProcessor { +class AzureServiceBusJmsPropertiesBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware { - private final ObjectProvider> connectionStringProviders; + private ApplicationContext applicationContext; - AzureServiceBusJmsPropertiesBeanPostProcessor(ObjectProvider> connectionStringProviders) { - this.connectionStringProviders = connectionStringProviders; + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + this.applicationContext = applicationContext; } @Override @@ -24,6 +28,8 @@ public Object postProcessBeforeInitialization(Object bean, String beanName) thro if (bean instanceof AzureServiceBusJmsProperties) { AzureServiceBusJmsProperties jmsProperties = (AzureServiceBusJmsProperties) bean; if (!StringUtils.hasText(jmsProperties.getConnectionString())) { + ResolvableType providerType = ResolvableType.forClassWithGenerics(ServiceConnectionStringProvider.class, AzureServiceType.ServiceBus.class); + ObjectProvider> connectionStringProviders = applicationContext.getBeanProvider(providerType); connectionStringProviders.ifAvailable(provider -> jmsProperties.setConnectionString(provider.getConnectionString())); } } diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/jms/ServiceBusJmsPropertiesConfiguration.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/jms/ServiceBusJmsPropertiesConfiguration.java index 9097b83924b2..a73e20636a0e 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/jms/ServiceBusJmsPropertiesConfiguration.java +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/jms/ServiceBusJmsPropertiesConfiguration.java @@ -5,14 +5,9 @@ import com.azure.spring.cloud.autoconfigure.implementation.condition.ConditionalOnMissingProperty; import com.azure.spring.cloud.autoconfigure.implementation.jms.properties.AzureServiceBusJmsProperties; -import com.azure.spring.cloud.core.provider.connectionstring.ServiceConnectionStringProvider; -import com.azure.spring.cloud.core.service.AzureServiceType; -import org.springframework.beans.factory.ObjectProvider; -import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Role; /** * {@code @Configuration} class that registers a {@link AzureServiceBusJmsPropertiesBeanPostProcessor} @@ -21,15 +16,12 @@ * @since 5.19.0 */ @Configuration(proxyBeanMethods = false) -@Role(BeanDefinition.ROLE_INFRASTRUCTURE) class ServiceBusJmsPropertiesConfiguration { @Bean @ConditionalOnMissingBean - @Role(BeanDefinition.ROLE_INFRASTRUCTURE) @ConditionalOnMissingProperty(prefix = "spring.jms.servicebus", name = "connection-string") - static AzureServiceBusJmsPropertiesBeanPostProcessor azureServiceBusJmsPropertiesBeanPostProcessor( - ObjectProvider> connectionStringProviders) { - return new AzureServiceBusJmsPropertiesBeanPostProcessor(connectionStringProviders); + static AzureServiceBusJmsPropertiesBeanPostProcessor azureServiceBusJmsPropertiesBeanPostProcessor() { + return new AzureServiceBusJmsPropertiesBeanPostProcessor(); } } diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/AbstractKafkaPropertiesBeanPostProcessor.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/AbstractKafkaPropertiesBeanPostProcessor.java index cf9147764a69..5e3410441501 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/AbstractKafkaPropertiesBeanPostProcessor.java +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/AbstractKafkaPropertiesBeanPostProcessor.java @@ -13,9 +13,13 @@ import org.apache.kafka.common.requests.ApiVersionsRequest; import org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule; import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; +import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.boot.autoconfigure.kafka.KafkaProperties; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; import org.springframework.util.ReflectionUtils; import java.lang.reflect.InvocationTargetException; @@ -39,14 +43,16 @@ import static org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule.OAUTHBEARER_MECHANISM; import static org.springframework.util.StringUtils.delimitedListToStringArray; -abstract class AbstractKafkaPropertiesBeanPostProcessor implements BeanPostProcessor { +abstract class AbstractKafkaPropertiesBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware { + private static final Logger LOGGER = LoggerFactory.getLogger(AbstractKafkaPropertiesBeanPostProcessor.class); static final String SECURITY_PROTOCOL_CONFIG_SASL = SASL_SSL.name(); static final String SASL_MECHANISM_OAUTH = OAUTHBEARER_MECHANISM; static final String AZURE_CONFIGURED_JAAS_OPTIONS_KEY = "azure.configured"; static final String AZURE_CONFIGURED_JAAS_OPTIONS_VALUE = "true"; static final String SASL_LOGIN_CALLBACK_HANDLER_CLASS_OAUTH = KafkaOAuth2AuthenticateCallbackHandler.class.getName(); + protected ApplicationContext applicationContext; protected static final PropertyMapper PROPERTY_MAPPER = new PropertyMapper(); private static final Map KAFKA_OAUTH_CONFIGS; private static final String LOG_OAUTH_DETAILED_PROPERTY_CONFIGURE = "OAUTHBEARER authentication property {} will be configured as {} to support Azure Identity credentials."; @@ -63,18 +69,21 @@ abstract class AbstractKafkaPropertiesBeanPostProcessor implements BeanPostPr KAFKA_OAUTH_CONFIGS = Collections.unmodifiableMap(configs); } - private final AzureGlobalProperties azureGlobalProperties; - - AbstractKafkaPropertiesBeanPostProcessor(AzureGlobalProperties azureGlobalProperties) { - this.azureGlobalProperties = azureGlobalProperties; - } + private AzureGlobalProperties azureGlobalProperties; @SuppressWarnings("unchecked") @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (needsPostProcess(bean)) { - T properties = (T) bean; + ObjectProvider beanProvider = applicationContext.getBeanProvider(AzureGlobalProperties.class); + azureGlobalProperties = beanProvider.getIfAvailable(); + if (azureGlobalProperties == null) { + LOGGER.debug("Cannot find a bean of type AzureGlobalProperties, " + + "Spring Cloud Azure will skip performing JAAS enhancements on the {} bean.", beanName); + return bean; + } + T properties = (T) bean; replaceAzurePropertiesWithJaas(getMergedProducerProperties(properties), getRawProducerProperties(properties)); replaceAzurePropertiesWithJaas(getMergedConsumerProperties(properties), getRawConsumerProperties(properties)); replaceAzurePropertiesWithJaas(getMergedAdminProperties(properties), getRawAdminProperties(properties)); @@ -129,6 +138,11 @@ public Object postProcessBeforeInitialization(Object bean, String beanName) thro protected abstract Logger getLogger(); + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + this.applicationContext = applicationContext; + } + /** * Process Kafka Spring properties for any customized operations. * @param properties the Kafka Spring properties diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/AzureEventHubsKafkaOAuth2AutoConfiguration.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/AzureEventHubsKafkaOAuth2AutoConfiguration.java index aa5a62787c0e..cd86a70cc667 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/AzureEventHubsKafkaOAuth2AutoConfiguration.java +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/AzureEventHubsKafkaOAuth2AutoConfiguration.java @@ -2,15 +2,12 @@ // Licensed under the MIT License. package com.azure.spring.cloud.autoconfigure.implementation.kafka; -import com.azure.spring.cloud.autoconfigure.implementation.context.properties.AzureGlobalProperties; -import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Role; import org.springframework.kafka.core.KafkaTemplate; import static com.azure.spring.cloud.autoconfigure.implementation.context.AzureContextUtils.PASSWORDLESS_KAFKA_PROPERTIES_BEAN_POST_PROCESSOR_BEAN_NAME; @@ -22,14 +19,12 @@ * @since 4.3.0 */ @Configuration(proxyBeanMethods = false) -@Role(BeanDefinition.ROLE_INFRASTRUCTURE) @ConditionalOnClass(KafkaTemplate.class) @ConditionalOnProperty(value = "spring.cloud.azure.eventhubs.kafka.enabled", havingValue = "true", matchIfMissing = true) public class AzureEventHubsKafkaOAuth2AutoConfiguration { @Bean(PASSWORDLESS_KAFKA_PROPERTIES_BEAN_POST_PROCESSOR_BEAN_NAME) - @Role(BeanDefinition.ROLE_INFRASTRUCTURE) - static BeanPostProcessor kafkaPropertiesBeanPostProcessor(AzureGlobalProperties properties) { - return new KafkaPropertiesBeanPostProcessor(properties); + static BeanPostProcessor kafkaPropertiesBeanPostProcessor() { + return new KafkaPropertiesBeanPostProcessor(); } } diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/AzureKafkaSpringCloudStreamConfiguration.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/AzureKafkaSpringCloudStreamConfiguration.java index 44d9b60d1016..b0eeff8eab50 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/AzureKafkaSpringCloudStreamConfiguration.java +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/AzureKafkaSpringCloudStreamConfiguration.java @@ -3,14 +3,11 @@ package com.azure.spring.cloud.autoconfigure.implementation.kafka; import com.azure.spring.cloud.autoconfigure.implementation.context.AzureGlobalPropertiesAutoConfiguration; -import com.azure.spring.cloud.autoconfigure.implementation.context.properties.AzureGlobalProperties; -import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.cloud.stream.binder.kafka.KafkaMessageChannelBinder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; -import org.springframework.context.annotation.Role; /** * Configuration for OAuth2 support on Spring Cloud Stream Kafka Binder. Provide Azure Identity-based @@ -19,15 +16,12 @@ * @since 4.3.0 */ @Configuration(proxyBeanMethods = false) -@Role(BeanDefinition.ROLE_INFRASTRUCTURE) @ConditionalOnClass(KafkaMessageChannelBinder.class) @Import(AzureGlobalPropertiesAutoConfiguration.class) public class AzureKafkaSpringCloudStreamConfiguration { @Bean - @Role(BeanDefinition.ROLE_INFRASTRUCTURE) - static KafkaBinderConfigurationPropertiesBeanPostProcessor kafkaBinderConfigurationPropertiesBeanPostProcessor( - AzureGlobalProperties azureGlobalProperties) { - return new KafkaBinderConfigurationPropertiesBeanPostProcessor(azureGlobalProperties); + static KafkaBinderConfigurationPropertiesBeanPostProcessor kafkaBinderConfigurationPropertiesBeanPostProcessor() { + return new KafkaBinderConfigurationPropertiesBeanPostProcessor(); } } diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/KafkaBinderConfigurationPropertiesBeanPostProcessor.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/KafkaBinderConfigurationPropertiesBeanPostProcessor.java index 6db44fb776ca..c93ad1aa1016 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/KafkaBinderConfigurationPropertiesBeanPostProcessor.java +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/KafkaBinderConfigurationPropertiesBeanPostProcessor.java @@ -23,10 +23,6 @@ class KafkaBinderConfigurationPropertiesBeanPostProcessor extends AbstractKafkaP private static final Logger LOGGER = LoggerFactory.getLogger(KafkaBinderConfigurationPropertiesBeanPostProcessor.class); - KafkaBinderConfigurationPropertiesBeanPostProcessor(AzureGlobalProperties azureGlobalProperties) { - super(azureGlobalProperties); - } - @Override protected Map getMergedProducerProperties(KafkaBinderConfigurationProperties properties) { return mergeNonAdminProperties(properties.mergedProducerConfiguration(), properties.getConfiguration()); diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/KafkaPropertiesBeanPostProcessor.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/KafkaPropertiesBeanPostProcessor.java index 3d5d4beee9cc..fffbd5885a18 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/KafkaPropertiesBeanPostProcessor.java +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/KafkaPropertiesBeanPostProcessor.java @@ -2,7 +2,6 @@ // Licensed under the MIT License. package com.azure.spring.cloud.autoconfigure.implementation.kafka; -import com.azure.spring.cloud.autoconfigure.implementation.context.properties.AzureGlobalProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.autoconfigure.kafka.KafkaProperties; @@ -13,10 +12,6 @@ class KafkaPropertiesBeanPostProcessor extends AbstractKafkaPropertiesBeanPostPr private static final Logger LOGGER = LoggerFactory.getLogger(KafkaPropertiesBeanPostProcessor.class); - KafkaPropertiesBeanPostProcessor(AzureGlobalProperties azureGlobalProperties) { - super(azureGlobalProperties); - } - @Override protected Map getMergedProducerProperties(KafkaProperties properties) { return invokeBuildKafkaProperties(properties, "buildProducerProperties"); diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/keyvault/jca/AzureKeyVaultJcaAutoConfiguration.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/keyvault/jca/AzureKeyVaultJcaAutoConfiguration.java new file mode 100644 index 000000000000..f2b30f065c07 --- /dev/null +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/keyvault/jca/AzureKeyVaultJcaAutoConfiguration.java @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.spring.cloud.autoconfigure.implementation.keyvault.jca; + +import com.azure.security.keyvault.jca.KeyVaultJcaProvider; +import com.azure.spring.cloud.autoconfigure.implementation.keyvault.jca.properties.AzureKeyVaultJcaProperties; +import com.azure.spring.cloud.autoconfigure.implementation.keyvault.jca.properties.AzureKeyVaultSslBundleProperties; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.boot.ssl.SslBundle; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * {@link EnableAutoConfiguration Auto-configuration} for Azure Key Vault JCA support. + * @since 5.21.0 + */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnClass({ KeyVaultJcaProvider.class, SslBundle.class }) +@EnableConfigurationProperties({AzureKeyVaultJcaProperties.class, AzureKeyVaultSslBundleProperties.class}) +@ConditionalOnProperty(value = "spring.cloud.azure.keyvault.jca.enabled", havingValue = "true", matchIfMissing = true) +public class AzureKeyVaultJcaAutoConfiguration { + + @Bean + @ConditionalOnMissingBean + AzureKeyVaultSslBundleRegistrar azureKeyVaultSslBundleRegistrar(AzureKeyVaultJcaProperties jcaProperties, + AzureKeyVaultSslBundleProperties sslBundlesProperties) { + return new AzureKeyVaultSslBundleRegistrar(jcaProperties, sslBundlesProperties); + } +} diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/keyvault/jca/AzureKeyVaultSslBundleRegistrar.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/keyvault/jca/AzureKeyVaultSslBundleRegistrar.java new file mode 100644 index 000000000000..be5a3e9a6427 --- /dev/null +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/keyvault/jca/AzureKeyVaultSslBundleRegistrar.java @@ -0,0 +1,243 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.spring.cloud.autoconfigure.implementation.keyvault.jca; + +import com.azure.security.keyvault.jca.KeyVaultJcaProvider; +import com.azure.spring.cloud.autoconfigure.implementation.keyvault.jca.properties.AzureKeyVaultJcaProperties; +import com.azure.spring.cloud.autoconfigure.implementation.keyvault.jca.properties.AzureKeyVaultSslBundleProperties; +import com.azure.spring.cloud.core.implementation.properties.PropertyMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.autoconfigure.ssl.SslBundleRegistrar; +import org.springframework.boot.ssl.SslBundle; +import org.springframework.boot.ssl.SslBundleKey; +import org.springframework.boot.ssl.SslBundleRegistry; +import org.springframework.boot.ssl.SslOptions; +import org.springframework.boot.ssl.SslStoreBundle; +import org.springframework.context.ResourceLoaderAware; +import org.springframework.core.io.ResourceLoader; +import org.springframework.util.ClassUtils; +import org.springframework.util.StringUtils; + +import java.io.IOException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.Security; +import java.security.cert.CertificateException; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * Azure Key Vault SslBundleRegistrar that registers SSL bundles based Key Vault JCA properties and Key Vault SSL bundle properties. + * + * @since 5.21.0 + */ +public class AzureKeyVaultSslBundleRegistrar implements SslBundleRegistrar, ResourceLoaderAware { + + private static final Logger LOGGER = LoggerFactory.getLogger(AzureKeyVaultSslBundleRegistrar.class); + private ResourceLoader resourceLoader; + private final Map jcaVaults; + private final Map sslBundles; + private static final String[] JCA_SYSTEM_PROPERTY_KEYS = new String[]{ + "azure.keyvault.uri", + "azure.keyvault.tenant-id", + "azure.keyvault.client-id", + "azure.keyvault.client-secret", + "azure.keyvault.managed-identity", + "azure.keyvault.jca.certificates-refresh-interval", + "azure.keyvault.jca.refresh-certificates-when-have-un-trust-certificate", + "azure.cert-path.well-known", + "azure.cert-path.custom" + }; + + public AzureKeyVaultSslBundleRegistrar(AzureKeyVaultJcaProperties azureKeyVaultJcaProperties, + AzureKeyVaultSslBundleProperties azureKeyVaultSslBundleProperties) { + this.jcaVaults = azureKeyVaultJcaProperties.getVaults(); + this.sslBundles = azureKeyVaultSslBundleProperties.getKeyvault(); + } + + @Override + public void registerBundles(SslBundleRegistry registry) { + if (!hasKeyVaultJcaOnClasspath()) { + LOGGER.debug("Skip configuring Key Vault SSL bundles because {}", "'com.azure:azure-security-keyvault-jca' " + + "doesn't exist in classpath."); + return; + } + + if (sslBundles.isEmpty()) { + LOGGER.debug("Skip configuring Key Vault SSL bundles because {}", "'spring.ssl.bundle.azure-keyvault' " + + "is empty."); + return; + } + + final AtomicBoolean providerConfigured = new AtomicBoolean(false); + sslBundles.forEach((bundleName, bundle) -> { + boolean hasAnyCertConfiguredForTruststore = hasAnyCertConfigured(jcaVaults, bundle.getTruststore()); + boolean hasAnyCertConfiguredForKeyStore = hasAnyCertConfigured(jcaVaults, bundle.getKeystore()); + boolean anyCertConfigured = hasAnyCertConfiguredForTruststore || hasAnyCertConfiguredForKeyStore; + if (!anyCertConfigured) { + LOGGER.debug("Skip configuring Key Vault SSL bundle '{}'. Consider configuring 'keyvault-ref', " + + "'certificate-paths.custom' or 'certificate-paths.well-known' properties of the keystore or " + + "truststore.", bundleName); + return; + } + + KeyStore keyVaultKeyStore = initilizeKeyVaultKeyStore("keystore", + bundleName, + hasAnyCertConfiguredForKeyStore, + providerConfigured, + jcaVaults.get(bundle.getKeystore().getKeyvaultRef()), + bundle.getKeystore()); + + KeyStore keyVaultTruststore = initilizeKeyVaultKeyStore("truststore", + bundleName, + hasAnyCertConfiguredForTruststore, + providerConfigured, + jcaVaults.get(bundle.getTruststore().getKeyvaultRef()), + bundle.getTruststore()); + + SslStoreBundle sslStoreBundle = SslStoreBundle.of(keyVaultKeyStore, null, keyVaultTruststore); + + SslBundleKey sslBundleKey = Optional.ofNullable(bundle.getKey()) + .map(k -> SslBundleKey.of(k.getPassword(), k.getAlias())) + .orElse(SslBundleKey.NONE); + + SslOptions sslOptions = Optional.ofNullable(bundle.getOptions()) + .map(o -> SslOptions.of(o.getCiphers(), o.getEnabledProtocols())) + .orElse(SslOptions.NONE); + + SslBundle sslBundle = SslBundle.of(sslStoreBundle, sslBundleKey, + sslOptions, + bundle.getProtocol(), + new KeyVaultSslManagerBundle(sslStoreBundle, sslBundleKey, bundle.isForClientAuth())); + + registry.registerBundle(bundleName, sslBundle); + + LOGGER.debug("Registered Azure Key Vault SSL bundle '{}'.", bundleName); + }); + } + + private KeyStore initilizeKeyVaultKeyStore(String storeName, + String bundleName, + boolean anyCertConfigured, + AtomicBoolean providerConfigured, + AzureKeyVaultJcaProperties.JcaVaultProperties jcaVaultProperties, + AzureKeyVaultSslBundleProperties.KeyStoreProperties keyStoreProperties) { + if (!anyCertConfigured) { + LOGGER.debug("The {} parameter of Key Vault SSL bundle '{}' is null.", storeName, bundleName); + return null; + } + + configureJcaKeyStoreSystemProperties(jcaVaultProperties, keyStoreProperties, resourceLoader); + if (providerConfigured.compareAndSet(false, true)) { + Security.removeProvider(KeyVaultJcaProvider.PROVIDER_NAME); + Security.insertProviderAt(new KeyVaultJcaProvider(), 1); + } + KeyStore azureKeyVaultKeyStore; + try { + if (hasEmbeddedTomcat()) { + // DKS (Domain Key Store) type key store can act as a single logical key store and support key stores of various + // types (JKS - Java Key Store, pkcs12) within a single domain. When configuring the Tomcat SSL context, if the + // KeyStore is not of type DKS, the final key store will be reinitialized and loaded, see source code from + // https://github.com/apache/tomcat/blob/cab38e5b9c4f498336f716afd1bf4161adedd71d/java/org/apache/tomcat/util/net/SSLUtilBase.java#L393~L403, + // which will result in the KeyManager being used not being wrapped by the JSSEKeyManager provided by Tomcat, see source code from + // https://github.com/apache/tomcat/blob/cab38e5b9c4f498336f716afd1bf4161adedd71d/java/org/apache/tomcat/util/net/SSLUtilBase.java#L424, + // so JSSEKeyManager#chooseEngineServerAlias does not delegate KeyVaultKeyManager.chooseEngineServerAlias, resulting in a null return value. + azureKeyVaultKeyStore = KeyStore.getInstance("DKS", KeyVaultJcaProvider.PROVIDER_NAME); + } else { + azureKeyVaultKeyStore = KeyStore.getInstance(KeyVaultJcaProvider.PROVIDER_NAME); + } + azureKeyVaultKeyStore.load(null); + } catch (CertificateException | KeyStoreException | IOException | NoSuchAlgorithmException | NoSuchProviderException e) { + throw new RuntimeException("Failed to load Key Vault " + storeName + " for SSL bundle '" + bundleName + "'", e); + } + return azureKeyVaultKeyStore; + } + + private static boolean hasKeyVaultJcaOnClasspath() { + return ClassUtils.isPresent("com.azure.security.keyvault.jca.KeyVaultJcaProvider", + AzureKeyVaultSslBundleRegistrar.class.getClassLoader()); + } + + private static boolean hasAnyCertConfigured(Map jcaVaults, + AzureKeyVaultSslBundleProperties.KeyStoreProperties keyStoreProperties) { + AzureKeyVaultSslBundleProperties.CertificatePathsProperties certificatePaths = keyStoreProperties.getCertificatePaths(); + String keyvaultRef = keyStoreProperties.getKeyvaultRef(); + boolean localCertConfigured = StringUtils.hasText(certificatePaths.getWellKnown()) || StringUtils.hasText(certificatePaths.getCustom()); + boolean keyVaultRefConfigured = StringUtils.hasText(keyvaultRef) && jcaVaults.get(keyvaultRef) != null; + return localCertConfigured || keyVaultRefConfigured; + } + + private static boolean hasEmbeddedTomcat() { + try { + Class.forName("org.apache.tomcat.InstanceManager"); + return true; + } catch (ClassNotFoundException ex) { + return false; + } + } + + private static void configureJcaKeyStoreSystemProperties(AzureKeyVaultJcaProperties.JcaVaultProperties jcaVaultProperties, + AzureKeyVaultSslBundleProperties.KeyStoreProperties keyStoreProperties, + ResourceLoader resourceLoader) { + PropertyMapper pm = new PropertyMapper(); + clearJcaSystemProperties(); + if (jcaVaultProperties != null) { + pm.from(jcaVaultProperties.getEndpoint()) + .when(StringUtils::hasText) + .to(v -> System.setProperty("azure.keyvault.uri", v)); + pm.from(jcaVaultProperties.getProfile().getTenantId()) + .when(StringUtils::hasText) + .to(v -> System.setProperty("azure.keyvault.tenant-id", v)); + pm.from(jcaVaultProperties.getCredential().getClientId()) + .when(StringUtils::hasText) + .to(v -> System.setProperty("azure.keyvault.client-id", v)); + pm.from(jcaVaultProperties.getCredential().getClientSecret()) + .when(StringUtils::hasText) + .to(v -> System.setProperty("azure.keyvault.client-secret", v)); + pm.from(jcaVaultProperties.getCredential().isManagedIdentityEnabled()) + .whenTrue() + // should put the client id to the managed-identity property + .to(v -> System.setProperty("azure.keyvault.managed-identity", jcaVaultProperties.getCredential().getClientId())); + } + + pm.from(keyStoreProperties.getCertificatesRefreshInterval()) + .when(Objects::nonNull) + .to(v -> System.setProperty("azure.keyvault.jca.certificates-refresh-interval", String.valueOf(v.toMillis()))); + pm.from(keyStoreProperties.isRefreshCertificatesWhenHaveUntrustedCertificate()) + .to(v -> System.setProperty("azure.keyvault.jca.refresh-certificates-when-have-un-trust-certificate", Boolean.toString(v))); + + pm.from(keyStoreProperties.getCertificatePaths().getWellKnown()) + .to(v -> resolvePath(resourceLoader, v).ifPresent(path -> System.setProperty("azure.cert-path.well-known", path))); + pm.from(keyStoreProperties.getCertificatePaths().getCustom()) + .to(v -> resolvePath(resourceLoader, v).ifPresent(path -> System.setProperty("azure.cert-path.custom", path))); + } + + private static void clearJcaSystemProperties() { + Arrays.stream(JCA_SYSTEM_PROPERTY_KEYS).forEach(System::clearProperty); + } + + private static Optional resolvePath(ResourceLoader resourceLoader, String path) { + return Optional.ofNullable(path) + .filter(p -> p.startsWith("classpath:") || p.startsWith("file:")) + .map(resourceLoader::getResource) + .map(res -> { + try { + return res.getFile().getAbsolutePath(); + } catch (IOException e) { + throw new RuntimeException("Failed to load the certificate path '" + path + "'", e); + } + }); + } + + @Override + public void setResourceLoader(ResourceLoader resourceLoader) { + this.resourceLoader = resourceLoader; + } +} diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/keyvault/jca/KeyVaultAliasKeyManagerFactory.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/keyvault/jca/KeyVaultAliasKeyManagerFactory.java new file mode 100644 index 000000000000..11632d79338f --- /dev/null +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/keyvault/jca/KeyVaultAliasKeyManagerFactory.java @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.spring.cloud.autoconfigure.implementation.keyvault.jca; + +import javax.net.ssl.KeyManager; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.KeyManagerFactorySpi; +import javax.net.ssl.ManagerFactoryParameters; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.X509ExtendedKeyManager; +import java.net.Socket; +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.Principal; +import java.security.PrivateKey; +import java.security.UnrecoverableKeyException; +import java.security.cert.X509Certificate; +import java.util.Arrays; + +final class KeyVaultAliasKeyManagerFactory extends KeyManagerFactory { + + KeyVaultAliasKeyManagerFactory(KeyManagerFactory delegate, String alias, String algorithm) { + super(new KeyVaultAliasKeyManagerFactorySpi(delegate, alias), delegate.getProvider(), algorithm); + } + + private static final class KeyVaultAliasKeyManagerFactorySpi extends KeyManagerFactorySpi { + + private final KeyManagerFactory delegate; + + private final String alias; + + private KeyVaultAliasKeyManagerFactorySpi(KeyManagerFactory delegate, String alias) { + this.delegate = delegate; + this.alias = alias; + } + + @Override + protected void engineInit(KeyStore keyStore, char[] chars) + throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException { + this.delegate.init(keyStore, chars); + } + + @Override + protected void engineInit(ManagerFactoryParameters managerFactoryParameters) + throws InvalidAlgorithmParameterException { + throw new InvalidAlgorithmParameterException("Unsupported ManagerFactoryParameters"); + } + + @Override + protected KeyManager[] engineGetKeyManagers() { + return Arrays.stream(this.delegate.getKeyManagers()) + .filter(X509ExtendedKeyManager.class::isInstance) + .map(X509ExtendedKeyManager.class::cast) + .map(this::wrap) + .toArray(KeyManager[]::new); + } + + private AliasKeyVaultClientKeyManager wrap(X509ExtendedKeyManager keyManager) { + return new AliasKeyVaultClientKeyManager(keyManager, this.alias); + } + + } + + /** + * {@link X509ExtendedKeyManager} that allows a configurable key alias to be used. + */ + static final class AliasKeyVaultClientKeyManager extends X509ExtendedKeyManager { + + private final X509ExtendedKeyManager delegate; + + private final String alias; + + private AliasKeyVaultClientKeyManager(X509ExtendedKeyManager keyManager, String alias) { + this.delegate = keyManager; + this.alias = alias; + } + + @Override + public String chooseEngineClientAlias(String[] strings, Principal[] principals, SSLEngine sslEngine) { + return this.alias; + } + + @Override + public String chooseEngineServerAlias(String s, Principal[] principals, SSLEngine sslEngine) { + return this.delegate.chooseEngineServerAlias(s, principals, sslEngine); + } + + @Override + public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) { + return this.delegate.chooseClientAlias(keyType, issuers, socket); + } + + @Override + public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { + return this.delegate.chooseServerAlias(keyType, issuers, socket); + } + + @Override + public X509Certificate[] getCertificateChain(String alias) { + return this.delegate.getCertificateChain(alias); + } + + @Override + public String[] getClientAliases(String keyType, Principal[] issuers) { + return this.delegate.getClientAliases(keyType, issuers); + } + + @Override + public PrivateKey getPrivateKey(String alias) { + return this.delegate.getPrivateKey(alias); + } + + @Override + public String[] getServerAliases(String keyType, Principal[] issuers) { + return this.delegate.getServerAliases(keyType, issuers); + } + + } + +} diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/keyvault/jca/KeyVaultSslManagerBundle.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/keyvault/jca/KeyVaultSslManagerBundle.java new file mode 100644 index 000000000000..0b3b73622fa2 --- /dev/null +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/keyvault/jca/KeyVaultSslManagerBundle.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.spring.cloud.autoconfigure.implementation.keyvault.jca; + +import org.springframework.boot.ssl.SslBundleKey; +import org.springframework.boot.ssl.SslManagerBundle; +import org.springframework.boot.ssl.SslStoreBundle; + +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.TrustManagerFactory; +import java.security.KeyStore; + +class KeyVaultSslManagerBundle implements SslManagerBundle { + + private final SslStoreBundle sslStoreBundle; + + private final SslBundleKey sslBundleKey; + + private final boolean forClientAuth; + + private final SslManagerBundle delegate; + + KeyVaultSslManagerBundle(SslStoreBundle sslStoreBundle, SslBundleKey sslBundleKey, boolean forClientAuth) { + this.sslStoreBundle = sslStoreBundle; + this.sslBundleKey = sslBundleKey; + this.delegate = SslManagerBundle.from(sslStoreBundle, sslBundleKey); + this.forClientAuth = forClientAuth; + } + + @Override + public KeyManagerFactory getKeyManagerFactory() { + if (!this.forClientAuth) { + return this.delegate.getKeyManagerFactory(); + } else { + try { + KeyStore store = this.sslStoreBundle.getKeyStore(); + this.sslBundleKey.assertContainsAlias(store); + String alias = this.sslBundleKey.getAlias(); + String algorithm = KeyManagerFactory.getDefaultAlgorithm(); + KeyManagerFactory factory = KeyManagerFactory.getInstance(algorithm); + factory = (alias != null) ? new KeyVaultAliasKeyManagerFactory(factory, alias, algorithm) : factory; + String password = this.sslBundleKey.getPassword(); + password = (password != null) ? password : this.sslStoreBundle.getKeyStorePassword(); + factory.init(store, (password != null) ? password.toCharArray() : null); + return factory; + } catch (RuntimeException ex) { + throw ex; + } catch (Exception ex) { + throw new IllegalStateException("Could not load key manager factory: " + ex.getMessage(), ex); + } + } + + } + + @Override + public TrustManagerFactory getTrustManagerFactory() { + return this.delegate.getTrustManagerFactory(); + } + +} diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/keyvault/jca/properties/AzureKeyVaultJcaProperties.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/keyvault/jca/properties/AzureKeyVaultJcaProperties.java new file mode 100644 index 000000000000..972727e4f6a4 --- /dev/null +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/keyvault/jca/properties/AzureKeyVaultJcaProperties.java @@ -0,0 +1,115 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.spring.cloud.autoconfigure.implementation.keyvault.jca.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.NestedConfigurationProperty; + +import java.util.HashMap; +import java.util.Map; + +/** + * Azure Key Vault JCA vault properties. + * + * @since 5.21.0 + */ +@ConfigurationProperties(AzureKeyVaultJcaProperties.PREFIX) +public class AzureKeyVaultJcaProperties { + + public static final String PREFIX = "spring.cloud.azure.keyvault.jca"; + + private final Map vaults = new HashMap<>(); + + public Map getVaults() { + return vaults; + } + + public static class JcaVaultProperties { + /** + * Azure Key Vault endpoint. + */ + private String endpoint; + + @NestedConfigurationProperty + private final TokenCredentialProperties credential = new TokenCredentialProperties(); + + @NestedConfigurationProperty + private final ProfileProperties profile = new ProfileProperties(); + + public String getEndpoint() { + return endpoint; + } + + public void setEndpoint(String endpoint) { + this.endpoint = endpoint; + } + + public TokenCredentialProperties getCredential() { + return credential; + } + + public ProfileProperties getProfile() { + return profile; + } + } + + public static class TokenCredentialProperties { + + /** + * Client ID to use when performing service principal authentication with Azure Key Vault. + */ + private String clientId; + + /** + * Client secret to use when performing service principal authentication with Azure Key Vault. + */ + private String clientSecret; + + /** + * Whether to enable managed identity to authenticate with Azure Key Vault. If true and the client-id is set, will + * use the client ID as user assigned managed identity client ID. + */ + private boolean managedIdentityEnabled = false; + + public String getClientId() { + return clientId; + } + + public void setClientId(String clientId) { + this.clientId = clientId; + } + + public String getClientSecret() { + return clientSecret; + } + + public void setClientSecret(String clientSecret) { + this.clientSecret = clientSecret; + } + + public boolean isManagedIdentityEnabled() { + return managedIdentityEnabled; + } + + public void setManagedIdentityEnabled(boolean managedIdentityEnabled) { + this.managedIdentityEnabled = managedIdentityEnabled; + } + } + + public static class ProfileProperties { + + /** + * Tenant ID to use when performing service principal authentication with Azure Key Vault. + */ + private String tenantId; + + public String getTenantId() { + return tenantId; + } + + public void setTenantId(String tenantId) { + this.tenantId = tenantId; + } + } +} diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/keyvault/jca/properties/AzureKeyVaultSslBundleProperties.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/keyvault/jca/properties/AzureKeyVaultSslBundleProperties.java new file mode 100644 index 000000000000..bf32fcd226b0 --- /dev/null +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/keyvault/jca/properties/AzureKeyVaultSslBundleProperties.java @@ -0,0 +1,141 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.spring.cloud.autoconfigure.implementation.keyvault.jca.properties; + +import org.springframework.boot.autoconfigure.ssl.SslBundleProperties; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.NestedConfigurationProperty; + +import java.time.Duration; +import java.util.HashMap; +import java.util.Map; + +/** + * Azure Key Vault SSL Bundle properties. + * + * @since 5.21.0 + */ +@ConfigurationProperties(AzureKeyVaultSslBundleProperties.PREFIX) +public class AzureKeyVaultSslBundleProperties { + + public static final String PREFIX = "spring.ssl.bundle"; + + private final Map keyvault = new HashMap<>(); + + public Map getKeyvault() { + return keyvault; + } + + public static class KeyVaultSslBundleProperties extends SslBundleProperties { + + /** + * Whether to use this ssl bundle for client authentication. + */ + private boolean forClientAuth; + /** + * Key Vault keystore properties. + */ + @NestedConfigurationProperty + private final KeyStoreProperties keystore = new KeyStoreProperties(); + + /** + * Key Vault truststore properties. + */ + @NestedConfigurationProperty + private final KeyStoreProperties truststore = new KeyStoreProperties(); + + public boolean isForClientAuth() { + return forClientAuth; + } + + public void setForClientAuth(boolean forClientAuth) { + this.forClientAuth = forClientAuth; + } + + public KeyStoreProperties getKeystore() { + return keystore; + } + + public KeyStoreProperties getTruststore() { + return truststore; + } + } + + public static class KeyStoreProperties { + + /** + * The key of Key Vault connection. + */ + private String keyvaultRef; + /** + * Whether to enable refresh certificate when get untrusted certificate. + */ + private boolean refreshCertificatesWhenHaveUntrustedCertificate; + /** + * Time interval to refresh all Key Vault certificate. + */ + private Duration certificatesRefreshInterval; + + @NestedConfigurationProperty + private final CertificatePathsProperties certificatePaths = new CertificatePathsProperties(); + + public String getKeyvaultRef() { + return keyvaultRef; + } + + public void setKeyvaultRef(String keyvaultRef) { + this.keyvaultRef = keyvaultRef; + } + + public boolean isRefreshCertificatesWhenHaveUntrustedCertificate() { + return refreshCertificatesWhenHaveUntrustedCertificate; + } + + public void setRefreshCertificatesWhenHaveUntrustedCertificate(boolean refreshCertificatesWhenHaveUntrustedCertificate) { + this.refreshCertificatesWhenHaveUntrustedCertificate = refreshCertificatesWhenHaveUntrustedCertificate; + } + + public Duration getCertificatesRefreshInterval() { + return certificatesRefreshInterval; + } + + public void setCertificatesRefreshInterval(Duration certificatesRefreshInterval) { + this.certificatesRefreshInterval = certificatesRefreshInterval; + } + + public CertificatePathsProperties getCertificatePaths() { + return certificatePaths; + } + } + + public static class CertificatePathsProperties { + + /** + * The path to put custom certificates. + */ + private String custom; + + /** + * The path to put well-known certificates. + */ + private String wellKnown; + + + public String getCustom() { + return custom; + } + + public void setCustom(String custom) { + this.custom = custom; + } + + public String getWellKnown() { + return wellKnown; + } + + public void setWellKnown(String wellKnown) { + this.wellKnown = wellKnown; + } + } +} diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/messaging/AzureMessagingListenerAutoConfiguration.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/messaging/AzureMessagingListenerAutoConfiguration.java index e341f523ffea..ae45faee7838 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/messaging/AzureMessagingListenerAutoConfiguration.java +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/messaging/AzureMessagingListenerAutoConfiguration.java @@ -3,8 +3,12 @@ package com.azure.spring.cloud.autoconfigure.implementation.messaging; +import com.azure.messaging.eventhubs.EventData; +import com.azure.messaging.servicebus.ServiceBusMessage; +import com.azure.messaging.servicebus.ServiceBusReceivedMessage; import com.azure.spring.cloud.autoconfigure.implementation.eventhubs.AzureEventHubsMessagingAutoConfiguration; import com.azure.spring.cloud.autoconfigure.implementation.servicebus.AzureServiceBusMessagingAutoConfiguration; +import com.azure.spring.messaging.converter.AzureMessageConverter; import com.azure.spring.messaging.eventhubs.core.EventHubsProcessorFactory; import com.azure.spring.messaging.eventhubs.core.listener.EventHubsMessageListenerContainer; import com.azure.spring.messaging.eventhubs.implementation.core.config.EventHubsMessageListenerContainerFactory; @@ -14,6 +18,7 @@ import com.azure.spring.messaging.servicebus.core.ServiceBusProcessorFactory; import com.azure.spring.messaging.servicebus.core.listener.ServiceBusMessageListenerContainer; import com.azure.spring.messaging.servicebus.implementation.core.config.ServiceBusMessageListenerContainerFactory; +import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.AnyNestedCondition; @@ -44,8 +49,11 @@ static class EventHubsConfiguration { @Bean(name = "azureEventHubsListenerContainerFactory") @ConditionalOnMissingBean(name = "azureEventHubsListenerContainerFactory") public MessageListenerContainerFactory azureEventHubsListenerContainerFactory( - EventHubsProcessorFactory eventHubsProcessorFactory) { - return new EventHubsMessageListenerContainerFactory(eventHubsProcessorFactory); + EventHubsProcessorFactory eventHubsProcessorFactory, + ObjectProvider> messageConverterProvider) { + EventHubsMessageListenerContainerFactory containerFactory = new EventHubsMessageListenerContainerFactory(eventHubsProcessorFactory); + messageConverterProvider.ifAvailable(containerFactory::setMessageConverter); + return containerFactory; } } @@ -56,8 +64,11 @@ static class ServiceBusConfiguration { @Bean(name = "azureServiceBusListenerContainerFactory") @ConditionalOnMissingBean(name = "azureServiceBusListenerContainerFactory") public MessageListenerContainerFactory azureServiceBusListenerContainerFactory( - ServiceBusProcessorFactory serviceBusProcessorFactory) { - return new ServiceBusMessageListenerContainerFactory(serviceBusProcessorFactory); + ServiceBusProcessorFactory serviceBusProcessorFactory, + ObjectProvider> messageConverterProvider) { + ServiceBusMessageListenerContainerFactory containerFactory = new ServiceBusMessageListenerContainerFactory(serviceBusProcessorFactory); + messageConverterProvider.ifAvailable(containerFactory::setMessageConverter); + return containerFactory; } } diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/properties/core/authentication/TokenCredentialConfigurationProperties.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/properties/core/authentication/TokenCredentialConfigurationProperties.java index 8672be1a4cbb..15fbb12eaac0 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/properties/core/authentication/TokenCredentialConfigurationProperties.java +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/properties/core/authentication/TokenCredentialConfigurationProperties.java @@ -48,7 +48,7 @@ public class TokenCredentialConfigurationProperties implements TokenCredentialOp private boolean managedIdentityEnabled = false; /** - * Custom Get the custom 'com.azure.core.credential.TokenCredential' bean name, it's used for Service builder factory or passwordless authentication. + * The bean name of type 'com.azure.core.credential.TokenCredential' to use when performing authentication with Azure. */ private String tokenCredentialBeanName; diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/servicebus/AzureServiceBusMessagingAutoConfiguration.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/servicebus/AzureServiceBusMessagingAutoConfiguration.java index 43c1be1b0ac2..74dd6b36c3d7 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/servicebus/AzureServiceBusMessagingAutoConfiguration.java +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/implementation/servicebus/AzureServiceBusMessagingAutoConfiguration.java @@ -5,6 +5,8 @@ import com.azure.core.credential.TokenCredential; import com.azure.messaging.servicebus.ServiceBusClientBuilder; +import com.azure.messaging.servicebus.ServiceBusMessage; +import com.azure.messaging.servicebus.ServiceBusReceivedMessage; import com.azure.spring.cloud.autoconfigure.implementation.condition.ConditionalOnAnyProperty; import com.azure.spring.cloud.autoconfigure.implementation.servicebus.properties.AzureServiceBusProperties; import com.azure.spring.cloud.core.customizer.AzureServiceClientBuilderCustomizer; @@ -13,6 +15,7 @@ import com.azure.spring.cloud.core.service.AzureServiceType; import com.azure.spring.messaging.ConsumerIdentifier; import com.azure.spring.messaging.PropertiesSupplier; +import com.azure.spring.messaging.converter.AzureMessageConverter; import com.azure.spring.messaging.implementation.converter.ObjectMapperHolder; import com.azure.spring.messaging.servicebus.core.DefaultServiceBusNamespaceProcessorFactory; import com.azure.spring.messaging.servicebus.core.DefaultServiceBusNamespaceProducerFactory; @@ -137,9 +140,9 @@ ServiceBusMessageConverter serviceBusMessageConverter(ObjectMapper objectMapper) @Bean @ConditionalOnMissingBean @ConditionalOnBean(ServiceBusProducerFactory.class) - ServiceBusTemplate serviceBusTemplate(ServiceBusProducerFactory senderClientfactory, - ServiceBusMessageConverter messageConverter) { - ServiceBusTemplate serviceBusTemplate = new ServiceBusTemplate(senderClientfactory); + ServiceBusTemplate serviceBusTemplate(ServiceBusProducerFactory senderClientFactory, + AzureMessageConverter messageConverter) { + ServiceBusTemplate serviceBusTemplate = new ServiceBusTemplate(senderClientFactory); serviceBusTemplate.setMessageConverter(messageConverter); return serviceBusTemplate; } diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports index c23b97895fc2..d639ede808f7 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -15,6 +15,7 @@ com.azure.spring.cloud.autoconfigure.implementation.kafka.AzureEventHubsKafkaOAu com.azure.spring.cloud.autoconfigure.implementation.kafka.AzureEventHubsKafkaBinderOAuth2AutoConfiguration com.azure.spring.cloud.autoconfigure.implementation.keyvault.secrets.AzureKeyVaultSecretAutoConfiguration com.azure.spring.cloud.autoconfigure.implementation.keyvault.certificates.AzureKeyVaultCertificateAutoConfiguration +com.azure.spring.cloud.autoconfigure.implementation.keyvault.jca.AzureKeyVaultJcaAutoConfiguration com.azure.spring.cloud.autoconfigure.implementation.messaging.AzureMessagingListenerAutoConfiguration com.azure.spring.cloud.autoconfigure.implementation.servicebus.AzureServiceBusAutoConfiguration com.azure.spring.cloud.autoconfigure.implementation.servicebus.AzureServiceBusMessagingAutoConfiguration diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/main/resources/azure-security-keyvault-jca-user-agent-value-prefix.txt b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/resources/azure-security-keyvault-jca-user-agent-value-prefix.txt new file mode 100644 index 000000000000..e7c6c1364ef1 --- /dev/null +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/main/resources/azure-security-keyvault-jca-user-agent-value-prefix.txt @@ -0,0 +1 @@ +az-sp-kv-jca/ diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/AbstractAzureServiceConfigurationTests.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/AbstractAzureServiceConfigurationTests.java index 9285faecaf06..6a669ac18f8b 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/AbstractAzureServiceConfigurationTests.java +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/AbstractAzureServiceConfigurationTests.java @@ -23,6 +23,7 @@ import static com.azure.spring.cloud.core.implementation.util.ReflectionUtils.getField; import static org.assertj.core.api.Assertions.assertThat; +@SuppressWarnings("deprecation") public abstract class AbstractAzureServiceConfigurationTests, P extends AzureProperties> { diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/context/AzureTokenCredentialAutoConfigurationTests.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/context/AzureTokenCredentialAutoConfigurationTests.java index 6b1ae3c7a3ad..2010a77416f3 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/context/AzureTokenCredentialAutoConfigurationTests.java +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/context/AzureTokenCredentialAutoConfigurationTests.java @@ -41,6 +41,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +@SuppressWarnings("deprecation") class AzureTokenCredentialAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/eventhubs/kafka/AzureEventHubsKafkaAutoConfigurationTests.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/eventhubs/kafka/AzureEventHubsKafkaAutoConfigurationTests.java index ce5c41189e19..8eb24d6d593e 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/eventhubs/kafka/AzureEventHubsKafkaAutoConfigurationTests.java +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/eventhubs/kafka/AzureEventHubsKafkaAutoConfigurationTests.java @@ -34,8 +34,7 @@ class AzureEventHubsKafkaAutoConfigurationTests { "Endpoint=sb://%s.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=key"; private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(AzureEventHubsKafkaAutoConfiguration.class, - KafkaPropertiesConfiguration.class, KafkaAutoConfiguration.class)); + .withConfiguration(AutoConfigurations.of(AzureEventHubsKafkaAutoConfiguration.class, KafkaAutoConfiguration.class)); @Test void shouldNotConfigureWhenAzureEventHubsKafkaDisabled() { this.contextRunner diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/eventhubs/kafka/AzureEventHubsKafkaConfigurationTests.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/eventhubs/kafka/AzureEventHubsKafkaConfigurationTests.java index 7cbe582e2066..cd4bb8a1e5ae 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/eventhubs/kafka/AzureEventHubsKafkaConfigurationTests.java +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/eventhubs/kafka/AzureEventHubsKafkaConfigurationTests.java @@ -36,8 +36,8 @@ class AzureEventHubsKafkaConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(AzureEventHubsKafkaOAuth2AutoConfiguration.class, AzureEventHubsKafkaAutoConfiguration.class, AzureGlobalPropertiesAutoConfiguration.class, - AzureTokenCredentialAutoConfiguration.class, KafkaPropertiesConfiguration.class, - KafkaAutoConfiguration.class, AzureKafkaSpringCloudStreamConfiguration.class, KafkaBinderConfiguration.class)); + AzureTokenCredentialAutoConfiguration.class, KafkaAutoConfiguration.class, + AzureKafkaSpringCloudStreamConfiguration.class, KafkaBinderConfiguration.class)); @Test diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/AzureKafkaOAuth2BinderConfigurationTests.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/AzureKafkaOAuth2BinderConfigurationTests.java index 2824636e5c97..14b9cbee0bce 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/AzureKafkaOAuth2BinderConfigurationTests.java +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/AzureKafkaOAuth2BinderConfigurationTests.java @@ -40,7 +40,7 @@ class AzureKafkaOAuth2BinderConfigurationTests extends AbstractAzureKafkaOAuth2AutoConfigurationTests { AzureKafkaOAuth2BinderConfigurationTests() { - super(new KafkaBinderConfigurationPropertiesBeanPostProcessor(new AzureGlobalProperties())); + super(new KafkaBinderConfigurationPropertiesBeanPostProcessor()); } private final ApplicationContextRunner contextRunnerWithoutEventHubsURL = new ApplicationContextRunner() diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/AzureKafkaOAuth2BootConfigurationTests.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/AzureKafkaOAuth2BootConfigurationTests.java index 0f018403653f..797e6dde7b20 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/AzureKafkaOAuth2BootConfigurationTests.java +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/AzureKafkaOAuth2BootConfigurationTests.java @@ -36,7 +36,7 @@ class AzureKafkaOAuth2BootConfigurationTests extends AbstractAzureKafkaOAuth2AutoConfigurationTests { AzureKafkaOAuth2BootConfigurationTests() { - super(new KafkaPropertiesBeanPostProcessor(new AzureGlobalProperties())); + super(new KafkaPropertiesBeanPostProcessor()); } private final ApplicationContextRunner contextRunnerWithoutEventHubsURL = new ApplicationContextRunner() diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/KafkaBinderConfigurationPropertiesBeanPostProcessorTest.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/KafkaBinderConfigurationPropertiesBeanPostProcessorTest.java index 54288875b0bc..94b25e481ba1 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/KafkaBinderConfigurationPropertiesBeanPostProcessorTest.java +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/KafkaBinderConfigurationPropertiesBeanPostProcessorTest.java @@ -2,13 +2,12 @@ // Licensed under the MIT License. package com.azure.spring.cloud.autoconfigure.implementation.kafka; -import com.azure.spring.cloud.autoconfigure.implementation.context.properties.AzureGlobalProperties; import org.springframework.cloud.stream.binder.kafka.properties.KafkaBinderConfigurationProperties; class KafkaBinderConfigurationPropertiesBeanPostProcessorTest extends AbstractKafkaPropertiesBeanPostProcessorTest { KafkaBinderConfigurationPropertiesBeanPostProcessorTest() { - super(new KafkaBinderConfigurationPropertiesBeanPostProcessor(new AzureGlobalProperties())); + super(new KafkaBinderConfigurationPropertiesBeanPostProcessor()); } } diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/KafkaPropertiesBeanPostProcessorTest.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/KafkaPropertiesBeanPostProcessorTest.java index da342aaca895..7f9838bf7014 100644 --- a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/KafkaPropertiesBeanPostProcessorTest.java +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/kafka/KafkaPropertiesBeanPostProcessorTest.java @@ -2,13 +2,12 @@ // Licensed under the MIT License. package com.azure.spring.cloud.autoconfigure.implementation.kafka; -import com.azure.spring.cloud.autoconfigure.implementation.context.properties.AzureGlobalProperties; import org.springframework.boot.autoconfigure.kafka.KafkaProperties; class KafkaPropertiesBeanPostProcessorTest extends AbstractKafkaPropertiesBeanPostProcessorTest { KafkaPropertiesBeanPostProcessorTest() { - super(new KafkaPropertiesBeanPostProcessor(new AzureGlobalProperties())); + super(new KafkaPropertiesBeanPostProcessor()); } } diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/keyvault/jca/AzureKeyVaultJcaAutoConfigurationTests.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/keyvault/jca/AzureKeyVaultJcaAutoConfigurationTests.java new file mode 100644 index 000000000000..f8567e42b5f4 --- /dev/null +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/keyvault/jca/AzureKeyVaultJcaAutoConfigurationTests.java @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.spring.cloud.autoconfigure.implementation.keyvault.jca; + +import com.azure.security.keyvault.jca.KeyVaultJcaProvider; +import com.azure.spring.cloud.autoconfigure.implementation.keyvault.jca.properties.AzureKeyVaultJcaProperties; +import com.azure.spring.cloud.autoconfigure.implementation.keyvault.jca.properties.AzureKeyVaultSslBundleProperties; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.ssl.SslBundle; +import org.springframework.boot.test.context.FilteredClassLoader; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +class AzureKeyVaultJcaAutoConfigurationTests { + private static final String ENDPOINT = "https:/%s.vault.azure.net/"; + + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(AzureKeyVaultJcaAutoConfiguration.class)); + + @Test + void noJcaProviderClass() { + this.contextRunner + .withClassLoader(new FilteredClassLoader(KeyVaultJcaProvider.class)) + .run(context -> assertThat(context).doesNotHaveBean(AzureKeyVaultJcaAutoConfiguration.class)); + } + + @Test + void noSslBundleClass() { + this.contextRunner + .withClassLoader(new FilteredClassLoader(SslBundle.class)) + .run(context -> assertThat(context).doesNotHaveBean(AzureKeyVaultJcaAutoConfiguration.class)); + } + + @Test + void disabledJca() { + this.contextRunner + .withPropertyValues( + "spring.cloud.azure.keyvault.jca.enabled=false" + ) + .run(context -> assertThat(context).doesNotHaveBean(AzureKeyVaultJcaAutoConfiguration.class)); + } + + @Test + void keyVaultJca() { + this.contextRunner + .withPropertyValues( + "spring.cloud.azure.keyvault.jca.vaults.kv1.endpoint=" + String.format(ENDPOINT, "test1"), + "spring.cloud.azure.keyvault.jca.vaults.kv1.credential.client-id=client-id", + "spring.cloud.azure.keyvault.jca.vaults.kv2.endpoint=" + String.format(ENDPOINT, "test2"), + "spring.ssl.bundle.keyvault.testBundle1.truststore.certificate-paths.custom=classpath:keyvault/certificate-paths/custom", + "spring.ssl.bundle.keyvault.testBundle2.truststore.keyvault-ref=kv2", + "spring.ssl.bundle.keyvault.testBundle3.truststore.keyvault-ref=kv1", + "spring.ssl.bundle.keyvault.testBundle3.keystore.keyvault-ref=kv2" + ) + .run(context -> { + assertThat(context).hasSingleBean(AzureKeyVaultJcaAutoConfiguration.class); + assertThat(context).hasSingleBean(AzureKeyVaultJcaProperties.class); + assertThat(context).hasSingleBean(AzureKeyVaultSslBundleProperties.class); + assertThat(context).hasSingleBean(AzureKeyVaultSslBundleRegistrar.class); + + AzureKeyVaultJcaProperties jcaProperties = context.getBean(AzureKeyVaultJcaProperties.class); + assertThat(jcaProperties.getVaults()).hasSize(2); + assertThat(jcaProperties.getVaults().get("kv1").getEndpoint()).isEqualTo(String.format(ENDPOINT, "test1")); + assertThat(jcaProperties.getVaults().get("kv1").getCredential().getClientId()).isEqualTo("client-id"); + assertThat(jcaProperties.getVaults().get("kv2").getEndpoint()).isEqualTo(String.format(ENDPOINT, "test2")); + + AzureKeyVaultSslBundleProperties sslBundlesProperties = context.getBean(AzureKeyVaultSslBundleProperties.class); + assertThat(sslBundlesProperties.getKeyvault()).hasSize(3); + assertThat(sslBundlesProperties.getKeyvault().get("testBundle1").getTruststore().getCertificatePaths().getCustom()).isEqualTo("classpath:keyvault/certificate-paths/custom"); + assertThat(sslBundlesProperties.getKeyvault().get("testBundle2").getTruststore().getKeyvaultRef()).isEqualTo("kv2"); + assertThat(sslBundlesProperties.getKeyvault().get("testBundle3").getTruststore().getKeyvaultRef()).isEqualTo("kv1"); + assertThat(sslBundlesProperties.getKeyvault().get("testBundle3").getKeystore().getKeyvaultRef()).isEqualTo("kv2"); + }); + } +} diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/keyvault/jca/AzureKeyVaultSslBundleRegistrarTests.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/keyvault/jca/AzureKeyVaultSslBundleRegistrarTests.java new file mode 100644 index 000000000000..757ce72ea54c --- /dev/null +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/keyvault/jca/AzureKeyVaultSslBundleRegistrarTests.java @@ -0,0 +1,165 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.spring.cloud.autoconfigure.implementation.keyvault.jca; + +import com.azure.spring.cloud.autoconfigure.implementation.keyvault.jca.properties.AzureKeyVaultJcaProperties; +import com.azure.spring.cloud.autoconfigure.implementation.keyvault.jca.properties.AzureKeyVaultSslBundleProperties; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Isolated; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.springframework.boot.ssl.SslBundleRegistry; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; +import org.springframework.core.io.DefaultResourceLoader; +import org.springframework.util.ClassUtils; + +import java.security.KeyStore; +import java.util.Arrays; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.then; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.times; + +@Isolated("Run this by itself as it captures System.out") +@ExtendWith({OutputCaptureExtension.class}) +class AzureKeyVaultSslBundleRegistrarTests { + + @Test + void noJcaProviderOnClassPath(CapturedOutput capturedOutput) { + AzureKeyVaultSslBundleRegistrar registrar = new AzureKeyVaultSslBundleRegistrar(new AzureKeyVaultJcaProperties(), new AzureKeyVaultSslBundleProperties()); + registrar.setResourceLoader(new DefaultResourceLoader()); + SslBundleRegistry registry = Mockito.mock(SslBundleRegistry.class); + + try (MockedStatic classUtils = mockStatic(ClassUtils.class)) { + classUtils.when(() -> ClassUtils.isPresent("com.azure.security.keyvault.jca.KeyVaultJcaProvider", + AzureKeyVaultSslBundleRegistrar.class.getClassLoader())) + .thenReturn(false); + registrar.registerBundles(registry); + then(registry).should(times(0)).registerBundle(anyString(), any()); + String allOutput = capturedOutput.getAll(); + String log = "Skip configuring Key Vault SSL bundles because 'com.azure:azure-security-keyvault-jca' " + + "doesn't exist in classpath."; + assertTrue(allOutput.contains(log)); + } + } + + @Test + void notConfigureSslBundlesAzureKeyvault(CapturedOutput capturedOutput) { + AzureKeyVaultSslBundleRegistrar registrar = new AzureKeyVaultSslBundleRegistrar(new AzureKeyVaultJcaProperties(), new AzureKeyVaultSslBundleProperties()); + registrar.setResourceLoader(new DefaultResourceLoader()); + SslBundleRegistry registry = Mockito.mock(SslBundleRegistry.class); + + registrar.registerBundles(registry); + then(registry).should(times(0)).registerBundle(anyString(), any()); + String allOutput = capturedOutput.getAll(); + String log = "Skip configuring Key Vault SSL bundles because 'spring.ssl.bundle.azure-keyvault' is empty."; + assertTrue(allOutput.contains(log)); + } + + @Test + void notConfigureEndpointOrSslBundleProperties(CapturedOutput capturedOutput) { + AzureKeyVaultSslBundleProperties sslBundleProperties = new AzureKeyVaultSslBundleProperties(); + AzureKeyVaultSslBundleRegistrar registrar = new AzureKeyVaultSslBundleRegistrar(new AzureKeyVaultJcaProperties(), sslBundleProperties); + registrar.setResourceLoader(new DefaultResourceLoader()); + SslBundleRegistry registry = Mockito.mock(SslBundleRegistry.class); + + sslBundleProperties.getKeyvault().put("testBundle", new AzureKeyVaultSslBundleProperties.KeyVaultSslBundleProperties()); + + registrar.registerBundles(registry); + then(registry).should(times(0)).registerBundle(anyString(), any()); + String allOutput = capturedOutput.getAll(); + String log = "Skip configuring Key Vault SSL bundle 'testBundle'. Consider configuring 'keyvault-ref', " + + "'certificate-paths.custom' or 'certificate-paths.well-known' properties of the keystore or " + + "truststore."; + assertTrue(allOutput.contains(log)); + } + + @Test + void registerKeyVaultSslBundle(CapturedOutput capturedOutput) { + AzureKeyVaultJcaProperties jcaProperties = new AzureKeyVaultJcaProperties(); + AzureKeyVaultSslBundleProperties sslBundleProperties = new AzureKeyVaultSslBundleProperties(); + AzureKeyVaultSslBundleRegistrar registrar = new AzureKeyVaultSslBundleRegistrar(jcaProperties, sslBundleProperties); + registrar.setResourceLoader(new DefaultResourceLoader()); + SslBundleRegistry registry = Mockito.mock(SslBundleRegistry.class); + + try (MockedStatic keyStoreMockedStatic = mockStatic(KeyStore.class)) { + String bundleName = "testBundle"; + KeyStore keyStore = Mockito.mock(KeyStore.class); + keyStoreMockedStatic.when(() -> KeyStore.getInstance("AzureKeyVault")).thenReturn(keyStore); + + String keyvaultName = "keyvault1"; + AzureKeyVaultJcaProperties.JcaVaultProperties jcaVaultProperties = new AzureKeyVaultJcaProperties.JcaVaultProperties(); + jcaVaultProperties.setEndpoint("https://test.vault.azure.net/"); + jcaProperties.getVaults().put(keyvaultName, jcaVaultProperties); + AzureKeyVaultSslBundleProperties.KeyVaultSslBundleProperties bundleProperties = new AzureKeyVaultSslBundleProperties.KeyVaultSslBundleProperties(); + bundleProperties.getTruststore().setKeyvaultRef(keyvaultName); + + sslBundleProperties.getKeyvault().put(bundleName, bundleProperties); + registrar.registerBundles(registry); + then(registry).should(times(1)).registerBundle(eq(bundleName), any()); + String allOutput = capturedOutput.getAll(); + String keystoreLog = "The keystore parameter of Key Vault SSL bundle 'testBundle' is null."; + String registerLog = "Registered Azure Key Vault SSL bundle '" + bundleName + "'."; + assertTrue(allOutput.contains(keystoreLog) || allOutput.contains(registerLog)); + } + } + + @Test + void registerMultipleSslBundles(CapturedOutput capturedOutput) { + AzureKeyVaultJcaProperties jcaProperties = new AzureKeyVaultJcaProperties(); + AzureKeyVaultSslBundleProperties sslBundleProperties = new AzureKeyVaultSslBundleProperties(); + AzureKeyVaultSslBundleRegistrar registrar = new AzureKeyVaultSslBundleRegistrar(jcaProperties, sslBundleProperties); + registrar.setResourceLoader(new DefaultResourceLoader()); + SslBundleRegistry registry = Mockito.mock(SslBundleRegistry.class); + + try (MockedStatic keyStoreMockedStatic = mockStatic(KeyStore.class)) { + KeyStore keyStore = Mockito.mock(KeyStore.class); + keyStoreMockedStatic.when(() -> KeyStore.getInstance("AzureKeyVault")).thenReturn(keyStore); + + AzureKeyVaultJcaProperties.JcaVaultProperties kv1 = new AzureKeyVaultJcaProperties.JcaVaultProperties(); + kv1.setEndpoint("https://test1.vault.azure.net/"); + jcaProperties.getVaults().put("keyvault1", kv1); + + AzureKeyVaultJcaProperties.JcaVaultProperties kv2 = new AzureKeyVaultJcaProperties.JcaVaultProperties(); + kv2.setEndpoint("https://test2.vault.azure.net/"); + jcaProperties.getVaults().put("keyvault2", kv2); + + // bundle for using kv1 for keystore + AzureKeyVaultSslBundleProperties.KeyVaultSslBundleProperties kvBundle1 = new AzureKeyVaultSslBundleProperties.KeyVaultSslBundleProperties(); + kvBundle1.getKeystore().setKeyvaultRef("keyvault1"); + sslBundleProperties.getKeyvault().put("kvBundle1", kvBundle1); + + + // bundle for using kv1 for keystore and kv2 for truststore + AzureKeyVaultSslBundleProperties.KeyVaultSslBundleProperties kvBundle2 = new AzureKeyVaultSslBundleProperties.KeyVaultSslBundleProperties(); + kvBundle2.getKeystore().setKeyvaultRef("keyvault1"); + kvBundle2.getTruststore().setKeyvaultRef("keyvault2"); + sslBundleProperties.getKeyvault().put("kvBundle2", kvBundle2); + + // bundle for local trust store with custom certs + AzureKeyVaultSslBundleProperties.KeyVaultSslBundleProperties localCustomTrustStoreBundle = new AzureKeyVaultSslBundleProperties.KeyVaultSslBundleProperties(); + localCustomTrustStoreBundle.getTruststore().getCertificatePaths().setCustom("classpath:keyvault/certificate-paths/custom"); + sslBundleProperties.getKeyvault().put("localCustom", localCustomTrustStoreBundle); + + // bundle for local trust store with well-known certs + AzureKeyVaultSslBundleProperties.KeyVaultSslBundleProperties localWellKnownBundle = new AzureKeyVaultSslBundleProperties.KeyVaultSslBundleProperties(); + localWellKnownBundle.getTruststore().getCertificatePaths().setWellKnown("classpath:keyvault/certificate-paths/well-known"); + sslBundleProperties.getKeyvault().put("localWellKnown", localWellKnownBundle); + + registrar.registerBundles(registry); + String allOutput = capturedOutput.getAll(); + Arrays.stream(sslBundleProperties.getKeyvault().keySet().toArray(new String[0])).forEach(bundleName -> { + then(registry).should(times(1)).registerBundle(eq(bundleName), any()); + String log = "Registered Azure Key Vault SSL bundle '" + bundleName + "'."; + assertTrue(allOutput.contains(log)); + }); + } + } +} diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/keyvault/jca/HttpUtilTest.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/keyvault/jca/HttpUtilTest.java new file mode 100644 index 000000000000..e8351b195e09 --- /dev/null +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/keyvault/jca/HttpUtilTest.java @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.spring.cloud.autoconfigure.implementation.keyvault.jca; + +import com.azure.security.keyvault.jca.implementation.utils.HttpUtil; +import org.junit.jupiter.api.Test; + +import static com.azure.security.keyvault.jca.implementation.utils.HttpUtil.USER_AGENT_VALUE; +import static com.azure.security.keyvault.jca.implementation.utils.HttpUtil.VERSION; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class HttpUtilTest { + + @Test + void userAgent() { + assertEquals("az-sp-kv-jca/", HttpUtil.getUserAgentPrefix()); + assertEquals("az-sp-kv-jca/" + VERSION, USER_AGENT_VALUE); + } +} diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/messaging/AzureMessagingListenerAutoConfigurationTests.java b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/messaging/AzureMessagingListenerAutoConfigurationTests.java new file mode 100644 index 000000000000..7ee4b88d0039 --- /dev/null +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/java/com/azure/spring/cloud/autoconfigure/implementation/messaging/AzureMessagingListenerAutoConfigurationTests.java @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.spring.cloud.autoconfigure.implementation.messaging; + +import com.azure.spring.cloud.autoconfigure.implementation.eventhubs.AzureEventHubsMessagingAutoConfiguration; +import com.azure.spring.cloud.autoconfigure.implementation.servicebus.AzureServiceBusMessagingAutoConfiguration; +import com.azure.spring.messaging.eventhubs.core.EventHubsProcessorFactory; +import com.azure.spring.messaging.eventhubs.core.listener.EventHubsMessageListenerContainer; +import com.azure.spring.messaging.eventhubs.implementation.core.config.EventHubsMessageListenerContainerFactory; +import com.azure.spring.messaging.eventhubs.implementation.support.converter.EventHubsMessageConverter; +import com.azure.spring.messaging.implementation.annotation.EnableAzureMessaging; +import com.azure.spring.messaging.servicebus.core.ServiceBusProcessorFactory; +import com.azure.spring.messaging.servicebus.core.listener.ServiceBusMessageListenerContainer; +import com.azure.spring.messaging.servicebus.implementation.core.config.ServiceBusMessageListenerContainerFactory; +import com.azure.spring.messaging.servicebus.implementation.support.converter.ServiceBusMessageConverter; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.FilteredClassLoader; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.mockito.Mockito.mock; + +public class AzureMessagingListenerAutoConfigurationTests { + + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of( + AzureEventHubsMessagingAutoConfiguration.class, + AzureServiceBusMessagingAutoConfiguration.class, + AzureMessagingListenerAutoConfiguration.class)); + + @Test + void withoutEnableAzureMessagingShouldNotConfigure() { + this.contextRunner + .withClassLoader(new FilteredClassLoader(EnableAzureMessaging.class)) + .run(context -> { + assertThat(context).doesNotHaveBean(AzureMessagingListenerAutoConfiguration.EventHubsConfiguration.class); + assertThat(context).doesNotHaveBean(AzureMessagingListenerAutoConfiguration.ServiceBusConfiguration.class); + }); + } + + @Test + void withoutEventHubsMessageListenerContainerShouldNotConfigure() { + this.contextRunner + .withClassLoader(new FilteredClassLoader(EventHubsMessageListenerContainer.class)) + .run(context -> { + assertThat(context).doesNotHaveBean(AzureMessagingListenerAutoConfiguration.EventHubsConfiguration.class); + }); + } + + @Test + void withoutServiceBusMessageListenerContainerShouldNotConfigure() { + this.contextRunner + .withClassLoader(new FilteredClassLoader(ServiceBusMessageListenerContainer.class)) + .run(context -> { + assertThat(context).doesNotHaveBean(AzureMessagingListenerAutoConfiguration.ServiceBusConfiguration.class); + }); + } + + @Test + void configureContainerFactories() { + this.contextRunner + .withBean(EventHubsMessageConverter.class, () -> mock(EventHubsMessageConverter.class)) + .withBean(EventHubsProcessorFactory.class, () -> mock(EventHubsProcessorFactory.class)) + .withBean(ServiceBusMessageConverter.class, () -> mock(ServiceBusMessageConverter.class)) + .withBean(ServiceBusProcessorFactory.class, () -> mock(ServiceBusProcessorFactory.class)) + .run(context -> { + assertThat(context).hasBean("azureEventHubsListenerContainerFactory"); + assertThat(context).hasBean("azureServiceBusListenerContainerFactory"); + + EventHubsMessageConverter eventHubsMessageConverter = context.getBean(EventHubsMessageConverter.class); + EventHubsMessageListenerContainerFactory eventHubsContainerFactory = (EventHubsMessageListenerContainerFactory) context.getBean("azureEventHubsListenerContainerFactory"); + assertSame(eventHubsMessageConverter, eventHubsContainerFactory.getMessageConverter()); + + ServiceBusMessageConverter messageConverter = context.getBean(ServiceBusMessageConverter.class); + ServiceBusMessageListenerContainerFactory serviceBusContainerFactory = (ServiceBusMessageListenerContainerFactory) context.getBean("azureServiceBusListenerContainerFactory"); + assertSame(messageConverter, serviceBusContainerFactory.getMessageConverter()); + }); + } +} diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/resources/keyvault/certificate-paths/custom/test-custom.pem b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/resources/keyvault/certificate-paths/custom/test-custom.pem new file mode 100644 index 000000000000..22146610cbf3 --- /dev/null +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/resources/keyvault/certificate-paths/custom/test-custom.pem @@ -0,0 +1,34 @@ +-----BEGIN CERTIFICATE----- +MIIF2TCCA8GgAwIBAgIUfC87AQplK322dHwB3EBUpDwcNkwwDQYJKoZIhvcNAQEL +BQAwfDELMAkGA1UEBhMCQ04xEDAOBgNVBAgMB1NIQU5OWEkxDTALBgNVBAcMBFhJ +QU4xDTALBgNVBAoMBERFTU8xDTALBgNVBAsMBERNRU8xEDAOBgNVBAMMBzIwMC5Q +VUIxHDAaBgkqhkiG9w0BCQEWDU1PQVJZQDEyNi5DT00wHhcNMjUwMjEwMDUzMjI5 +WhcNMjYwMjEwMDUzMjI5WjB8MQswCQYDVQQGEwJDTjEQMA4GA1UECAwHU0hBTk5Y +STENMAsGA1UEBwwEWElBTjENMAsGA1UECgwEREVNTzENMAsGA1UECwwERE1FTzEQ +MA4GA1UEAwwHMjAwLlBVQjEcMBoGCSqGSIb3DQEJARYNTU9BUllAMTI2LkNPTTCC +AiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBALKHlnjjqRJBG03vPNO4Qbch +fZF/LCK0lTVtwvee96pxsxd0CvvrEes9g8tph46HbaDmPRcBEI+QDjAmQjt9NhtV +Ztj7eajaDQccFXvWluM/2n6F1hWU9nx0y+blXfwPAZpYwHKhjq/GTlcE8a9hoafX +9guRMLy6prFVCnS/OzCxRo4u1j1zA9Q0t5KZChT39Z2EuJ47e1WqTSdq4AFXzItv +vgJx70A3LCMpWy2UU2pVYX9KkUzuKC8eD2GKznfznpfLWnvnnWmjoann5xfoOcBZ +UF/04+7ntnzAJu+02nP/8DwpaXNFJ+yFRgLZjqmu3ErXkZ0DjYiANOmamyOU0ipa +Hrdz7gYOM6k3J2mFKTg8JdE/YUhG/BUZOaN8LEkOLRbzmEwte/vAbiWS9I821ZZ2 +CxWF+cmhnYJ6qHp6eaC0fqLB3gLCt7hSziAR1iUBhnrcrSEm9iaTE2zMPsJ3yE3Z +L+PBKGYBA8SrnT997ivjS8geF0uw259XdoxjZqZEYatx5kSTznxUaqqbSuW0TeSW +zZdMQCJYSPzuj9iCD5nQmGdWAOBYvR2ml5PiWKRhLQm8lFOQQZ9wTH5WyzwN/a1g +aMvLrWmnL2j7qbEr1KNn6b14GdUnvFSr3Heb9B4aav8JZNZSKgc3x8Wy3QJfvZPU +WXvThJAdpMrhPkLUt+QTAgMBAAGjUzBRMB0GA1UdDgQWBBSChtt4VmCf9gqKoqhq +FAgJRabGyzAfBgNVHSMEGDAWgBSChtt4VmCf9gqKoqhqFAgJRabGyzAPBgNVHRMB +Af8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4ICAQA6prsKLeu0Ps10kd8yTrtPrbre +dK9k3qRoWoPwHMvl4hLATODrPBErWhayfPj2/WZyB2rNHOK8J/Pv+BHWkj2Dybqy +A8FwWVlfcNDZnVbS5xtQZQXHZntslRyBipOz+gTte8bPSN2E9IfWccqFGGmM97lr ++o8RN0Q2OvrvS/Bt31g3R1EwF1CIagRl8BQB8FuYS78EYezch8J61Jxo/PQeKWv5 +34qGq+QHk4NV8HBWIc+yYOGPHnQuqU5Dagfb8HTGBUw4RmG6+GQNHfcAsN1ruhW3 +tdXEPcCXbi4PoLp5xh5qComejGjwk9jNzKZb4EdGm17I2pn8c3Rs7WrTGiZAT22j +iFc7W3WwoX/5fOex8LBxN7m2k5rMfnJtv2yJClkuG3ivdCZiTYxeZUe4TaKIJ5os +xylVlZEU6xq4MzhNcYbdGTptXvU1SAXQoUbaHEUGumlNtTArV9tcmKFv7/DB6c8r +YUYrSciMt33DagIW7Cbiod2ywqB1KY4UvLNG1KCtxLfQzgEx+unw4jEuKryz3onh +2RSDTUfdxwVGUpdj8+BKPscvkNUHC1MsUWnhg/gNb51Ub98ZXGlV7vsyv0hq0xaA +rjayWKdQti2Fv8E+Y7VT5GLAZn5gsTnNYbSKK5oG+wGVVX2G3o6ZwGvabjF+cf9K +kbN0WZRMHX96pbQYEQ== +-----END CERTIFICATE----- diff --git a/sdk/spring/spring-cloud-azure-autoconfigure/src/test/resources/keyvault/certificate-paths/well-known/test-well-known.pem b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/resources/keyvault/certificate-paths/well-known/test-well-known.pem new file mode 100644 index 000000000000..22146610cbf3 --- /dev/null +++ b/sdk/spring/spring-cloud-azure-autoconfigure/src/test/resources/keyvault/certificate-paths/well-known/test-well-known.pem @@ -0,0 +1,34 @@ +-----BEGIN CERTIFICATE----- +MIIF2TCCA8GgAwIBAgIUfC87AQplK322dHwB3EBUpDwcNkwwDQYJKoZIhvcNAQEL +BQAwfDELMAkGA1UEBhMCQ04xEDAOBgNVBAgMB1NIQU5OWEkxDTALBgNVBAcMBFhJ +QU4xDTALBgNVBAoMBERFTU8xDTALBgNVBAsMBERNRU8xEDAOBgNVBAMMBzIwMC5Q +VUIxHDAaBgkqhkiG9w0BCQEWDU1PQVJZQDEyNi5DT00wHhcNMjUwMjEwMDUzMjI5 +WhcNMjYwMjEwMDUzMjI5WjB8MQswCQYDVQQGEwJDTjEQMA4GA1UECAwHU0hBTk5Y +STENMAsGA1UEBwwEWElBTjENMAsGA1UECgwEREVNTzENMAsGA1UECwwERE1FTzEQ +MA4GA1UEAwwHMjAwLlBVQjEcMBoGCSqGSIb3DQEJARYNTU9BUllAMTI2LkNPTTCC +AiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBALKHlnjjqRJBG03vPNO4Qbch +fZF/LCK0lTVtwvee96pxsxd0CvvrEes9g8tph46HbaDmPRcBEI+QDjAmQjt9NhtV +Ztj7eajaDQccFXvWluM/2n6F1hWU9nx0y+blXfwPAZpYwHKhjq/GTlcE8a9hoafX +9guRMLy6prFVCnS/OzCxRo4u1j1zA9Q0t5KZChT39Z2EuJ47e1WqTSdq4AFXzItv +vgJx70A3LCMpWy2UU2pVYX9KkUzuKC8eD2GKznfznpfLWnvnnWmjoann5xfoOcBZ +UF/04+7ntnzAJu+02nP/8DwpaXNFJ+yFRgLZjqmu3ErXkZ0DjYiANOmamyOU0ipa +Hrdz7gYOM6k3J2mFKTg8JdE/YUhG/BUZOaN8LEkOLRbzmEwte/vAbiWS9I821ZZ2 +CxWF+cmhnYJ6qHp6eaC0fqLB3gLCt7hSziAR1iUBhnrcrSEm9iaTE2zMPsJ3yE3Z +L+PBKGYBA8SrnT997ivjS8geF0uw259XdoxjZqZEYatx5kSTznxUaqqbSuW0TeSW +zZdMQCJYSPzuj9iCD5nQmGdWAOBYvR2ml5PiWKRhLQm8lFOQQZ9wTH5WyzwN/a1g +aMvLrWmnL2j7qbEr1KNn6b14GdUnvFSr3Heb9B4aav8JZNZSKgc3x8Wy3QJfvZPU +WXvThJAdpMrhPkLUt+QTAgMBAAGjUzBRMB0GA1UdDgQWBBSChtt4VmCf9gqKoqhq +FAgJRabGyzAfBgNVHSMEGDAWgBSChtt4VmCf9gqKoqhqFAgJRabGyzAPBgNVHRMB +Af8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4ICAQA6prsKLeu0Ps10kd8yTrtPrbre +dK9k3qRoWoPwHMvl4hLATODrPBErWhayfPj2/WZyB2rNHOK8J/Pv+BHWkj2Dybqy +A8FwWVlfcNDZnVbS5xtQZQXHZntslRyBipOz+gTte8bPSN2E9IfWccqFGGmM97lr ++o8RN0Q2OvrvS/Bt31g3R1EwF1CIagRl8BQB8FuYS78EYezch8J61Jxo/PQeKWv5 +34qGq+QHk4NV8HBWIc+yYOGPHnQuqU5Dagfb8HTGBUw4RmG6+GQNHfcAsN1ruhW3 +tdXEPcCXbi4PoLp5xh5qComejGjwk9jNzKZb4EdGm17I2pn8c3Rs7WrTGiZAT22j +iFc7W3WwoX/5fOex8LBxN7m2k5rMfnJtv2yJClkuG3ivdCZiTYxeZUe4TaKIJ5os +xylVlZEU6xq4MzhNcYbdGTptXvU1SAXQoUbaHEUGumlNtTArV9tcmKFv7/DB6c8r +YUYrSciMt33DagIW7Cbiod2ywqB1KY4UvLNG1KCtxLfQzgEx+unw4jEuKryz3onh +2RSDTUfdxwVGUpdj8+BKPscvkNUHC1MsUWnhg/gNb51Ub98ZXGlV7vsyv0hq0xaA +rjayWKdQti2Fv8E+Y7VT5GLAZn5gsTnNYbSKK5oG+wGVVX2G3o6ZwGvabjF+cf9K +kbN0WZRMHX96pbQYEQ== +-----END CERTIFICATE----- diff --git a/sdk/spring/spring-cloud-azure-core/CHANGELOG.md b/sdk/spring/spring-cloud-azure-core/CHANGELOG.md index edb5e88a52c4..a57cc1805451 100644 --- a/sdk/spring/spring-cloud-azure-core/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-core/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 5.20.0-beta.1 (Unreleased) +## 5.21.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 5.20.1 (2025-03-03) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5201-2025-03-03) for more details. + +## 5.20.0 (2025-02-12) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5200-2025-02-12) for more details. + ## 5.19.0 (2024-12-17) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5190-2024-12-17) for more details. diff --git a/sdk/spring/spring-cloud-azure-core/README.md b/sdk/spring/spring-cloud-azure-core/README.md index e69de29bb2d1..bbaecbaa3de8 100644 --- a/sdk/spring/spring-cloud-azure-core/README.md +++ b/sdk/spring/spring-cloud-azure-core/README.md @@ -0,0 +1 @@ +Please refer to [spring/README.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/README.md) for more details. diff --git a/sdk/spring/spring-cloud-azure-core/pom.xml b/sdk/spring/spring-cloud-azure-core/pom.xml index 8c4fff1af3bb..7dd765ce6b89 100644 --- a/sdk/spring/spring-cloud-azure-core/pom.xml +++ b/sdk/spring/spring-cloud-azure-core/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-cloud-azure-core - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Core https://microsoft.github.io/spring-cloud-azure @@ -40,40 +40,40 @@ org.springframework spring-context - 6.2.1 + 6.2.2 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-identity - 1.15.0 + 1.15.4 com.azure azure-core-amqp - 2.9.12 + 2.9.16 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-identity-extensions - 1.2.0 + 1.2.1 true com.azure azure-storage-blob - 12.29.0 + 12.29.1 true @@ -85,7 +85,7 @@ com.azure azure-storage-file-share - 12.25.1 + 12.25.2 true @@ -124,7 +124,7 @@ org.springframework spring-test - 6.2.1 + 6.2.2 test @@ -181,7 +181,7 @@ - org.springframework:spring-context:[6.2.1] + org.springframework:spring-context:[6.2.2] diff --git a/sdk/spring/spring-cloud-azure-core/src/main/java/com/azure/spring/cloud/core/implementation/factory/credential/UsernamePasswordCredentialBuilderFactory.java b/sdk/spring/spring-cloud-azure-core/src/main/java/com/azure/spring/cloud/core/implementation/factory/credential/UsernamePasswordCredentialBuilderFactory.java index 13a49f839eab..8af0e4d1dfb3 100644 --- a/sdk/spring/spring-cloud-azure-core/src/main/java/com/azure/spring/cloud/core/implementation/factory/credential/UsernamePasswordCredentialBuilderFactory.java +++ b/sdk/spring/spring-cloud-azure-core/src/main/java/com/azure/spring/cloud/core/implementation/factory/credential/UsernamePasswordCredentialBuilderFactory.java @@ -11,6 +11,7 @@ /** * A credential builder factory for the {@link UsernamePasswordCredentialBuilder}. */ +@SuppressWarnings("deprecation") public class UsernamePasswordCredentialBuilderFactory extends AzureAadCredentialBuilderFactory { /** diff --git a/sdk/spring/spring-cloud-azure-core/src/main/java/com/azure/spring/cloud/core/implementation/util/AzurePropertiesUtils.java b/sdk/spring/spring-cloud-azure-core/src/main/java/com/azure/spring/cloud/core/implementation/util/AzurePropertiesUtils.java index c5574e20a0ae..f11056901e5b 100644 --- a/sdk/spring/spring-cloud-azure-core/src/main/java/com/azure/spring/cloud/core/implementation/util/AzurePropertiesUtils.java +++ b/sdk/spring/spring-cloud-azure-core/src/main/java/com/azure/spring/cloud/core/implementation/util/AzurePropertiesUtils.java @@ -16,6 +16,7 @@ import java.util.Set; import java.util.function.BiFunction; +import static com.azure.spring.cloud.core.implementation.util.ClassUtils.isPrimitive; import static com.azure.spring.cloud.core.implementation.util.ClassUtils.isPrimitiveDefaultValue; import static com.azure.spring.cloud.core.implementation.util.ClassUtils.isPrimitiveNonDefaultValue; @@ -163,8 +164,9 @@ static String[] findNullPropertyNames(Object source) { Objects.isNull(srcValue) || isPrimitiveDefaultValue(propertyType, srcValue)); } - static String[] findNonNullPropertyNames(Object source) { + public static String[] findNonNullPropertyNames(Object source) { return findPropertyNames(source, (propertyType, srcValue) -> - Objects.nonNull(srcValue) && isPrimitiveNonDefaultValue(propertyType, srcValue)); + (!isPrimitive(propertyType) && Objects.nonNull(srcValue) && (propertyType != Class.class && srcValue != source.getClass())) + || (isPrimitive(propertyType) && isPrimitiveNonDefaultValue(propertyType, srcValue))); } } diff --git a/sdk/spring/spring-cloud-azure-core/src/main/java/com/azure/spring/cloud/core/implementation/util/AzureSpringIdentifier.java b/sdk/spring/spring-cloud-azure-core/src/main/java/com/azure/spring/cloud/core/implementation/util/AzureSpringIdentifier.java index 392c0fc91a3b..bfa21c7788c0 100644 --- a/sdk/spring/spring-cloud-azure-core/src/main/java/com/azure/spring/cloud/core/implementation/util/AzureSpringIdentifier.java +++ b/sdk/spring/spring-cloud-azure-core/src/main/java/com/azure/spring/cloud/core/implementation/util/AzureSpringIdentifier.java @@ -50,7 +50,7 @@ private AzureSpringIdentifier() { public static final String AZURE_SPRING_EVENT_HUBS_KAFKA_OAUTH = ".az-sp-kafka"; public static final String AZURE_SPRING_KEY_VAULT_SECRETS = "az-sp-kv/" + VERSION; public static final String AZURE_SPRING_KEY_VAULT_CERTIFICATES = "az-sp-kv-ct/" + VERSION; - + public static final String AZURE_SPRING_KEY_VAULT_JCA = "az-sp-kv-jca/" + VERSION; public static final String AZURE_SPRING_MYSQL_OAUTH = "az-sp-mysql/" + VERSION; public static final String AZURE_SPRING_POSTGRESQL_OAUTH = "az-sp-psql/" + VERSION; diff --git a/sdk/spring/spring-cloud-azure-core/src/main/java/com/azure/spring/cloud/core/implementation/util/ClassUtils.java b/sdk/spring/spring-cloud-azure-core/src/main/java/com/azure/spring/cloud/core/implementation/util/ClassUtils.java index 5c18926e2da0..ca4521200ece 100644 --- a/sdk/spring/spring-cloud-azure-core/src/main/java/com/azure/spring/cloud/core/implementation/util/ClassUtils.java +++ b/sdk/spring/spring-cloud-azure-core/src/main/java/com/azure/spring/cloud/core/implementation/util/ClassUtils.java @@ -48,4 +48,13 @@ public static boolean isPrimitiveNonDefaultValue(Class type, Object value) { && !PRIMITIVE_DEFAULT_VALUE_CHECKER.get(type).apply(value); } + /** + * Check if it's a primitive type property + * @param type Type class to be checked. + * @return True if it's a primitive type property + */ + public static boolean isPrimitive(Class type) { + return PRIMITIVE_DEFAULT_VALUE_CHECKER.containsKey(type); + } + } diff --git a/sdk/spring/spring-cloud-azure-core/src/main/java/com/azure/spring/cloud/core/properties/authentication/TokenCredentialProperties.java b/sdk/spring/spring-cloud-azure-core/src/main/java/com/azure/spring/cloud/core/properties/authentication/TokenCredentialProperties.java index 2f4fc156eee6..ec12b93d14db 100644 --- a/sdk/spring/spring-cloud-azure-core/src/main/java/com/azure/spring/cloud/core/properties/authentication/TokenCredentialProperties.java +++ b/sdk/spring/spring-cloud-azure-core/src/main/java/com/azure/spring/cloud/core/properties/authentication/TokenCredentialProperties.java @@ -54,7 +54,7 @@ public TokenCredentialProperties() { private boolean managedIdentityEnabled; /** - * Custom Get the custom 'com.azure.core.credential.TokenCredential' bean name, it's used for Service builder factory or passwordless authentication. + * The bean name of type 'com.azure.core.credential.TokenCredential' to use when performing authentication with Azure. */ private String tokenCredentialBeanName; diff --git a/sdk/spring/spring-cloud-azure-core/src/test/java/com/azure/spring/cloud/core/implementation/credential/resolver/AzureTokenCredentialResolverTests.java b/sdk/spring/spring-cloud-azure-core/src/test/java/com/azure/spring/cloud/core/implementation/credential/resolver/AzureTokenCredentialResolverTests.java index b0e34dcc5ca7..df783203dc2d 100644 --- a/sdk/spring/spring-cloud-azure-core/src/test/java/com/azure/spring/cloud/core/implementation/credential/resolver/AzureTokenCredentialResolverTests.java +++ b/sdk/spring/spring-cloud-azure-core/src/test/java/com/azure/spring/cloud/core/implementation/credential/resolver/AzureTokenCredentialResolverTests.java @@ -15,6 +15,7 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +@SuppressWarnings("deprecation") class AzureTokenCredentialResolverTests { diff --git a/sdk/spring/spring-cloud-azure-core/src/test/java/com/azure/spring/cloud/core/implementation/factory/credential/UsernamePasswordCredentialBuilderFactoryTest.java b/sdk/spring/spring-cloud-azure-core/src/test/java/com/azure/spring/cloud/core/implementation/factory/credential/UsernamePasswordCredentialBuilderFactoryTest.java index 84b4c043c0b5..de516d978735 100644 --- a/sdk/spring/spring-cloud-azure-core/src/test/java/com/azure/spring/cloud/core/implementation/factory/credential/UsernamePasswordCredentialBuilderFactoryTest.java +++ b/sdk/spring/spring-cloud-azure-core/src/test/java/com/azure/spring/cloud/core/implementation/factory/credential/UsernamePasswordCredentialBuilderFactoryTest.java @@ -6,6 +6,7 @@ import com.azure.identity.UsernamePasswordCredentialBuilder; import com.azure.spring.cloud.core.properties.AzureProperties; +@SuppressWarnings("deprecation") class UsernamePasswordCredentialBuilderFactoryTest extends AzureAadCredentialBuilderFactoryTest< UsernamePasswordCredentialBuilder, UsernamePasswordCredentialBuilderFactory> { diff --git a/sdk/spring/spring-cloud-azure-core/src/test/java/com/azure/spring/cloud/core/util/AzurePropertiesUtilsTests.java b/sdk/spring/spring-cloud-azure-core/src/test/java/com/azure/spring/cloud/core/util/AzurePropertiesUtilsTests.java index b14a69f9e7dd..c7ab6b3e455f 100644 --- a/sdk/spring/spring-cloud-azure-core/src/test/java/com/azure/spring/cloud/core/util/AzurePropertiesUtilsTests.java +++ b/sdk/spring/spring-cloud-azure-core/src/test/java/com/azure/spring/cloud/core/util/AzurePropertiesUtilsTests.java @@ -18,12 +18,15 @@ import com.azure.spring.cloud.core.properties.retry.RetryProperties; import com.azure.spring.cloud.core.provider.RetryOptionsProvider; import org.junit.jupiter.api.Test; +import org.mockito.internal.util.collections.Sets; import java.time.Duration; import java.util.Arrays; import java.util.HashSet; import java.util.Set; +import java.util.stream.Collectors; +import static com.azure.spring.cloud.core.implementation.util.AzurePropertiesUtils.findNonNullPropertyNames; import static com.azure.spring.cloud.core.provider.AzureProfileOptionsProvider.CloudType.AZURE; import static com.azure.spring.cloud.core.provider.AzureProfileOptionsProvider.CloudType.AZURE_CHINA; import static com.azure.spring.cloud.core.provider.AzureProfileOptionsProvider.CloudType.OTHER; @@ -532,6 +535,33 @@ void testCopyPropertiesIgnoreNullAmqpClientPropertiesShouldBeCopied() { assertEquals(AmqpTransportType.AMQP, target.getClient().getTransportType()); } + @Test + void noNonNullPropertyNames() { + TestProperties properties = new TestProperties(); + assertEquals(0, findNonNullPropertyNames(properties).length); + } + + @Test + void partNonNullPropertyNames() { + TestProperties properties = new TestProperties("test", 10, 10L, Boolean.FALSE); + Set assertNullNames = Sets.newSet("testString", "testWrapNumber", "testWrapLong", "testWrapBoolean"); + asertNonNullProperties(properties, assertNullNames); + } + + @Test + void allNonNullPropertyNames() { + TestProperties properties = new TestProperties("test", 10, 10, + 10L, 10, Boolean.TRUE, true); + Set assertNullNames = Sets.newSet("testString", "testWrapNumber", "testNumber", + "testWrapLong", "testLong", "testWrapBoolean", "testBoolean"); + asertNonNullProperties(properties, assertNullNames); + } + + private static void asertNonNullProperties(TestProperties properties, Set assertNullNames) { + Set result = Arrays.stream(findNonNullPropertyNames(properties)).collect(Collectors.toSet()); + assertEquals(assertNullNames, result); + } + static class AzureHttpClientProperties extends AzureHttpSdkProperties { } @@ -540,6 +570,92 @@ static class AzureAmqpClientProperties extends AzureAmqpSdkProperties { } + static class TestProperties { + private String testString; + private Integer testWrapNumber; + private int testNumber; + private Long testWrapLong; + private long testLong; + private Boolean testWrapBoolean; + private boolean testBoolean; + + TestProperties() { + } + + TestProperties(String testString, Integer testWrapNumber, Long testWrapLong, Boolean testWrapBoolean) { + this.testString = testString; + this.testWrapNumber = testWrapNumber; + this.testWrapLong = testWrapLong; + this.testWrapBoolean = testWrapBoolean; + } + + TestProperties(String testString, Integer testWrapNumber, int testNumber, Long testWrapLong, long testLong, Boolean testWrapBoolean, boolean testBoolean) { + this.testString = testString; + this.testWrapNumber = testWrapNumber; + this.testNumber = testNumber; + this.testWrapLong = testWrapLong; + this.testLong = testLong; + this.testWrapBoolean = testWrapBoolean; + this.testBoolean = testBoolean; + } + + public String getTestString() { + return testString; + } + + public void setTestString(String testString) { + this.testString = testString; + } + + public Integer getTestWrapNumber() { + return testWrapNumber; + } + + public void setTestWrapNumber(Integer testWrapNumber) { + this.testWrapNumber = testWrapNumber; + } + + public int getTestNumber() { + return testNumber; + } + + public void setTestNumber(int testNumber) { + this.testNumber = testNumber; + } + + public Long getTestWrapLong() { + return testWrapLong; + } + + public void setTestWrapLong(Long testWrapLong) { + this.testWrapLong = testWrapLong; + } + + public long getTestLong() { + return testLong; + } + + public void setTestLong(long testLong) { + this.testLong = testLong; + } + + public Boolean getTestWrapBoolean() { + return testWrapBoolean; + } + + public void setTestWrapBoolean(Boolean testWrapBoolean) { + this.testWrapBoolean = testWrapBoolean; + } + + public boolean isTestBoolean() { + return testBoolean; + } + + public void setTestBoolean(boolean testBoolean) { + this.testBoolean = testBoolean; + } + } + static class AzurePropertiesA implements AzureProperties, RetryOptionsProvider { private final ClientProperties client = new ClientProperties(); diff --git a/sdk/spring/spring-cloud-azure-docker-compose/CHANGELOG.md b/sdk/spring/spring-cloud-azure-docker-compose/CHANGELOG.md index 7f6269274cd2..d36b89dbb423 100644 --- a/sdk/spring/spring-cloud-azure-docker-compose/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-docker-compose/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 5.20.0-beta.1 (Unreleased) +## 5.21.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 5.20.1 (2025-03-03) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5201-2025-03-03) for more details. + +## 5.20.0 (2025-02-12) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5200-2025-02-12) for more details. + ## 5.19.0 (2024-12-17) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5190-2024-12-17) for more details. diff --git a/sdk/spring/spring-cloud-azure-docker-compose/README.md b/sdk/spring/spring-cloud-azure-docker-compose/README.md index e69de29bb2d1..bbaecbaa3de8 100644 --- a/sdk/spring/spring-cloud-azure-docker-compose/README.md +++ b/sdk/spring/spring-cloud-azure-docker-compose/README.md @@ -0,0 +1 @@ +Please refer to [spring/README.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/README.md) for more details. diff --git a/sdk/spring/spring-cloud-azure-docker-compose/pom.xml b/sdk/spring/spring-cloud-azure-docker-compose/pom.xml index cd3bd7ed66fe..9c87546bb5a7 100644 --- a/sdk/spring/spring-cloud-azure-docker-compose/pom.xml +++ b/sdk/spring/spring-cloud-azure-docker-compose/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-cloud-azure-docker-compose - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Docker Compose Spring Cloud Azure Docker Compose @@ -56,13 +56,13 @@ com.azure.spring spring-cloud-azure-autoconfigure - 5.20.0-beta.1 + 5.21.0-beta.1 true com.azure azure-storage-blob - 12.29.0 + 12.29.1 com.fasterxml.jackson.core @@ -74,14 +74,14 @@ com.azure azure-storage-queue - 12.24.0 + 12.24.1 true org.springframework.boot spring-boot-docker-compose - 3.4.1 + 3.4.2 + 3.4.2 test org.springframework spring-test - 6.2.1 + 6.2.2 test @@ -160,7 +160,7 @@ - org.springframework.boot:spring-boot-docker-compose:[3.4.1] + org.springframework.boot:spring-boot-docker-compose:[3.4.2] diff --git a/sdk/spring/spring-cloud-azure-feature-management-web/CHANGELOG.md b/sdk/spring/spring-cloud-azure-feature-management-web/CHANGELOG.md index 305fcea90874..97cdeab9108f 100644 --- a/sdk/spring/spring-cloud-azure-feature-management-web/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-feature-management-web/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 5.20.0-beta.1 (Unreleased) +## 5.21.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 5.20.1 (2025-03-03) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5201-2025-03-03) for more details. + +## 5.20.0 (2025-02-12) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5200-2025-02-12) for more details. + ## 5.19.0 (2024-12-17) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5190-2024-12-17) for more details. diff --git a/sdk/spring/spring-cloud-azure-feature-management-web/pom.xml b/sdk/spring/spring-cloud-azure-feature-management-web/pom.xml index b4f5ac25000f..9bec91bf3577 100644 --- a/sdk/spring/spring-cloud-azure-feature-management-web/pom.xml +++ b/sdk/spring/spring-cloud-azure-feature-management-web/pom.xml @@ -8,7 +8,7 @@ 4.0.0 com.azure.spring spring-cloud-azure-feature-management-web - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Feature Management Web Adds Feature Management into Spring Web @@ -29,17 +29,17 @@ org.springframework spring-web - 6.2.1 + 6.2.2 org.springframework spring-webmvc - 6.2.1 + 6.2.2 com.azure.spring spring-cloud-azure-feature-management - 5.20.0-beta.1 + 5.21.0-beta.1 jakarta.servlet @@ -50,7 +50,7 @@ org.springframework.boot spring-boot-starter-test - 3.4.1 + 3.4.2 test @@ -127,10 +127,10 @@ - com.azure.spring:spring-cloud-azure-feature-management:[5.20.0-beta.1] + com.azure.spring:spring-cloud-azure-feature-management:[5.21.0-beta.1] jakarta.servlet:jakarta.servlet-api:[6.0.0] - org.springframework:spring-web:[6.2.1] - org.springframework:spring-webmvc:[6.2.1] + org.springframework:spring-web:[6.2.2] + org.springframework:spring-webmvc:[6.2.2] diff --git a/sdk/spring/spring-cloud-azure-feature-management/CHANGELOG.md b/sdk/spring/spring-cloud-azure-feature-management/CHANGELOG.md index fc9d17031b5c..807ccde2d88f 100644 --- a/sdk/spring/spring-cloud-azure-feature-management/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-feature-management/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 5.20.0-beta.1 (Unreleased) +## 5.21.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 5.20.1 (2025-03-03) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5201-2025-03-03) for more details. + +## 5.20.0 (2025-02-12) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5200-2025-02-12) for more details. + ## 5.19.0 (2024-12-17) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5190-2024-12-17) for more details. diff --git a/sdk/spring/spring-cloud-azure-feature-management/pom.xml b/sdk/spring/spring-cloud-azure-feature-management/pom.xml index 6938a5d716ed..27f57dd498a1 100644 --- a/sdk/spring/spring-cloud-azure-feature-management/pom.xml +++ b/sdk/spring/spring-cloud-azure-feature-management/pom.xml @@ -8,7 +8,7 @@ 4.0.0 com.azure.spring spring-cloud-azure-feature-management - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Feature Management Adds Feature Management into Spring @@ -29,12 +29,12 @@ org.springframework spring-context - 6.2.1 + 6.2.2 org.springframework.boot spring-boot-starter - 3.4.1 + 3.4.2 ch.qos.logback @@ -45,7 +45,7 @@ org.springframework.boot spring-boot-configuration-processor - 3.4.1 + 3.4.2 true @@ -61,12 +61,12 @@ io.projectreactor.netty reactor-netty - 1.2.1 + 1.2.2 org.springframework.boot spring-boot-starter-test - 3.4.1 + 3.4.2 test @@ -162,10 +162,10 @@ com.fasterxml.jackson.core:jackson-annotations:[2.18.2] com.fasterxml.jackson.core:jackson-databind:[2.18.2] - io.projectreactor.netty:reactor-netty:[1.2.1] - org.springframework.boot:spring-boot-configuration-processor:[3.4.1] - org.springframework.boot:spring-boot-starter:[3.4.1] - org.springframework:spring-context:[6.2.1] + io.projectreactor.netty:reactor-netty:[1.2.2] + org.springframework.boot:spring-boot-configuration-processor:[3.4.2] + org.springframework.boot:spring-boot-starter:[3.4.2] + org.springframework:spring-context:[6.2.2] diff --git a/sdk/spring/spring-cloud-azure-integration-test-appconfiguration-config/pom.xml b/sdk/spring/spring-cloud-azure-integration-test-appconfiguration-config/pom.xml index ce572c123332..f2cf0a1a532e 100644 --- a/sdk/spring/spring-cloud-azure-integration-test-appconfiguration-config/pom.xml +++ b/sdk/spring/spring-cloud-azure-integration-test-appconfiguration-config/pom.xml @@ -6,7 +6,7 @@ org.springframework.boot spring-boot-starter-parent - 3.4.1 + 3.4.2 com.azure.spring @@ -21,7 +21,7 @@ com.azure.spring spring-cloud-azure-starter-appconfiguration-config - 5.20.0-beta.1 + 5.21.0-beta.1 org.springframework.boot @@ -30,7 +30,7 @@ org.springframework.boot spring-boot-starter-test - 3.4.1 + 3.4.2 test @@ -94,7 +94,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 true @@ -121,7 +121,7 @@ org.apache.maven.plugins maven-checkstyle-plugin - 3.5.0 + 3.6.0 true diff --git a/sdk/spring/spring-cloud-azure-integration-tests/pom.xml b/sdk/spring/spring-cloud-azure-integration-tests/pom.xml index 2d83a9f8e779..399a426a2a0c 100644 --- a/sdk/spring/spring-cloud-azure-integration-tests/pom.xml +++ b/sdk/spring/spring-cloud-azure-integration-tests/pom.xml @@ -7,7 +7,7 @@ org.springframework.boot spring-boot-starter-parent - 3.4.1 + 3.4.2 @@ -42,67 +42,72 @@ com.azure.spring spring-cloud-azure-starter-servicebus - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure.spring spring-cloud-azure-starter-servicebus-jms - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure.spring spring-cloud-azure-starter-eventhubs - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure.spring spring-cloud-azure-starter-keyvault-secrets - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure.spring spring-cloud-azure-starter-storage-blob - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure.spring spring-cloud-azure-starter-storage-file-share - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure.spring spring-cloud-azure-starter-storage-queue - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure.spring spring-cloud-azure-starter-appconfiguration - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure.spring spring-cloud-azure-starter-cosmos - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure.spring spring-cloud-azure-starter-data-cosmos - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure.spring spring-cloud-azure-stream-binder-eventhubs - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure.spring spring-cloud-azure-stream-binder-servicebus - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure.spring spring-cloud-azure-starter-jdbc-mysql - 5.20.0-beta.1 + 5.21.0-beta.1 + + + org.springframework.cloud + spring-cloud-starter-stream-kafka + 4.2.0 org.springframework.boot @@ -128,7 +133,7 @@ com.azure azure-identity - 1.15.0 + 1.15.4 @@ -184,7 +189,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 true @@ -211,7 +216,7 @@ org.apache.maven.plugins maven-checkstyle-plugin - 3.5.0 + 3.6.0 true diff --git a/sdk/spring/spring-cloud-azure-integration-tests/src/test/java/com/azure/spring/cloud/integration/tests/eventhubs/binder/EventHubsKafkaBinderIT.java b/sdk/spring/spring-cloud-azure-integration-tests/src/test/java/com/azure/spring/cloud/integration/tests/eventhubs/binder/EventHubsKafkaBinderIT.java new file mode 100644 index 000000000000..e234d2074ac8 --- /dev/null +++ b/sdk/spring/spring-cloud-azure-integration-tests/src/test/java/com/azure/spring/cloud/integration/tests/eventhubs/binder/EventHubsKafkaBinderIT.java @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.spring.cloud.integration.tests.eventhubs.binder; + +import io.micrometer.core.instrument.MeterRegistry; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.messaging.Message; +import org.springframework.messaging.support.GenericMessage; +import org.springframework.test.context.ActiveProfiles; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Sinks; + +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; +import java.util.function.Supplier; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) +@ActiveProfiles("eventhubs-kafka-binder") +class EventHubsKafkaBinderIT { + + private static final Logger LOGGER = LoggerFactory.getLogger(EventHubsKafkaBinderIT.class); + private static final String MESSAGE = UUID.randomUUID().toString(); + private static final CountDownLatch LATCH = new CountDownLatch(1); + + @Autowired + private Sinks.Many> many; + + @TestConfiguration + static class TestConfig { + + @Bean + public MeterRegistry meterRegistry() { + return new SimpleMeterRegistry(); + } + + @Bean + public Sinks.Many> many() { + return Sinks.many().unicast().onBackpressureBuffer(); + } + + @Bean + public Supplier>> supply(Sinks.Many> many) { + return () -> many.asFlux() + .doOnNext(m -> LOGGER.info("Manually sending message {}", m)) + .doOnError(t -> LOGGER.error("Error encountered", t)); + } + + @Bean + public Consumer> consume() { + return message -> { + LOGGER.info("New message received: '{}'", message.getPayload()); + LATCH.countDown(); + }; + } + } + + @Test + void testSendAndReceiveMessage() throws InterruptedException { + LOGGER.info("EventHubsKafkaBinderIT begin."); + // Wait for Kafka Binder initialization to complete + Thread.sleep(20000); + LOGGER.info("Send a message:" + MESSAGE + "."); + many.emitNext(new GenericMessage<>(MESSAGE), Sinks.EmitFailureHandler.FAIL_FAST); + assertThat(EventHubsKafkaBinderIT.LATCH.await(40, TimeUnit.SECONDS)).isTrue(); + LOGGER.info("EventHubsKafkaBinderIT end."); + } +} diff --git a/sdk/spring/spring-cloud-azure-integration-tests/src/test/resources/application-eventhubs-kafka-binder.yml b/sdk/spring/spring-cloud-azure-integration-tests/src/test/resources/application-eventhubs-kafka-binder.yml new file mode 100644 index 000000000000..b5bc76a1f527 --- /dev/null +++ b/sdk/spring/spring-cloud-azure-integration-tests/src/test/resources/application-eventhubs-kafka-binder.yml @@ -0,0 +1,20 @@ +spring: + cloud: + azure: + eventhubs: + connection-string: ${AZURE_EVENT_HUBS_CONNECTION_STRING} + function: + definition: consume;supply + stream: + bindings: + consume-in-0: + destination: connnection-string-auth + group: $Default + supply-out-0: + destination: connnection-string-auth + binders: + kafka: + environment: + spring: + main: + sources: com.azure.spring.cloud.autoconfigure.implementation.eventhubs.kafka.AzureEventHubsKafkaAutoConfiguration diff --git a/sdk/spring/spring-cloud-azure-integration-tests/src/test/resources/application-servicebus-jms-connection-string.yml b/sdk/spring/spring-cloud-azure-integration-tests/src/test/resources/application-servicebus-jms-connection-string.yml index c9d1b15743b4..0d715bfeab7a 100644 --- a/sdk/spring/spring-cloud-azure-integration-tests/src/test/resources/application-servicebus-jms-connection-string.yml +++ b/sdk/spring/spring-cloud-azure-integration-tests/src/test/resources/application-servicebus-jms-connection-string.yml @@ -1,8 +1,4 @@ spring: - cloud: - azure: - credential: - token-credential-bean-name: integrationTestTokenCredential jms: servicebus: connection-string: ${AZURE_SERVICE_BUS_JMS_CONNECTION_STRING} diff --git a/sdk/spring/spring-cloud-azure-integration-tests/test-resources/eventhubs/test-resources.json b/sdk/spring/spring-cloud-azure-integration-tests/test-resources/eventhubs/test-resources.json index a7f8ea582f88..eb38bb796aff 100644 --- a/sdk/spring/spring-cloud-azure-integration-tests/test-resources/eventhubs/test-resources.json +++ b/sdk/spring/spring-cloud-azure-integration-tests/test-resources/eventhubs/test-resources.json @@ -98,6 +98,31 @@ ], "properties": {} }, + { + "type": "Microsoft.EventHub/namespaces/eventhubs", + "apiVersion": "2022-01-01-preview", + "name": "[concat(variables('eventHubsNamespaceName'), '/connnection-string-auth')]", + "location": "[variables('location')]", + "dependsOn": [ + "[resourceId('Microsoft.EventHub/namespaces', variables('eventHubsNamespaceName'))]" + ], + "properties": { + "messageRetentionInDays": 1, + "partitionCount": 1, + "status": "Active" + } + }, + { + "type": "Microsoft.EventHub/namespaces/eventhubs/consumergroups", + "apiVersion": "2022-01-01-preview", + "name": "[concat(variables('eventHubsNamespaceName'), '/connnection-string-auth/$Default')]", + "location": "[variables('location')]", + "dependsOn": [ + "[resourceId('Microsoft.EventHub/namespaces/eventhubs', variables('eventHubsNamespaceName'), 'connnection-string-auth')]", + "[resourceId('Microsoft.EventHub/namespaces', variables('eventHubsNamespaceName'))]" + ], + "properties": {} + }, { "type": "Microsoft.EventHub/namespaces/eventhubs", "apiVersion": "2022-01-01-preview", @@ -465,6 +490,10 @@ "AZURE_EVENTHUB_NAME_FOR_BINDER_SYNC": { "type": "string", "value": "test-eventhub-sync" + }, + "AZURE_EVENT_HUBS_CONNECTION_STRING": { + "type": "string", + "value": "[listKeys(resourceId('Microsoft.EventHub/namespaces/authorizationRules', variables('eventHubsNamespaceName'), 'RootManageSharedAccessKey'), '2017-04-01').primaryConnectionString]" } } } diff --git a/sdk/spring/spring-cloud-azure-resourcemanager/CHANGELOG.md b/sdk/spring/spring-cloud-azure-resourcemanager/CHANGELOG.md index edb5e88a52c4..a57cc1805451 100644 --- a/sdk/spring/spring-cloud-azure-resourcemanager/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-resourcemanager/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 5.20.0-beta.1 (Unreleased) +## 5.21.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 5.20.1 (2025-03-03) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5201-2025-03-03) for more details. + +## 5.20.0 (2025-02-12) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5200-2025-02-12) for more details. + ## 5.19.0 (2024-12-17) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5190-2024-12-17) for more details. diff --git a/sdk/spring/spring-cloud-azure-resourcemanager/README.md b/sdk/spring/spring-cloud-azure-resourcemanager/README.md index e69de29bb2d1..bbaecbaa3de8 100644 --- a/sdk/spring/spring-cloud-azure-resourcemanager/README.md +++ b/sdk/spring/spring-cloud-azure-resourcemanager/README.md @@ -0,0 +1 @@ +Please refer to [spring/README.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/README.md) for more details. diff --git a/sdk/spring/spring-cloud-azure-resourcemanager/pom.xml b/sdk/spring/spring-cloud-azure-resourcemanager/pom.xml index 9afd6ad2e598..01b046fc5a44 100644 --- a/sdk/spring/spring-cloud-azure-resourcemanager/pom.xml +++ b/sdk/spring/spring-cloud-azure-resourcemanager/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-cloud-azure-resourcemanager - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Resource Manager Spring Cloud Azure Resource Manager @@ -41,13 +41,13 @@ com.azure.spring spring-cloud-azure-core - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure.resourcemanager azure-resourcemanager - 2.46.0 + 2.48.0 @@ -79,7 +79,7 @@ org.springframework spring-test - 6.2.1 + 6.2.2 test diff --git a/sdk/spring/spring-cloud-azure-service/CHANGELOG.md b/sdk/spring/spring-cloud-azure-service/CHANGELOG.md index e441b741757a..dee30c12d278 100644 --- a/sdk/spring/spring-cloud-azure-service/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-service/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 5.20.0-beta.1 (Unreleased) +## 5.21.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 5.20.1 (2025-03-03) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5201-2025-03-03) for more details. + +## 5.20.0 (2025-02-12) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5200-2025-02-12) for more details. + ## 5.19.0 (2024-12-17) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5190-2024-12-17) for more details. diff --git a/sdk/spring/spring-cloud-azure-service/README.md b/sdk/spring/spring-cloud-azure-service/README.md index e69de29bb2d1..bbaecbaa3de8 100644 --- a/sdk/spring/spring-cloud-azure-service/README.md +++ b/sdk/spring/spring-cloud-azure-service/README.md @@ -0,0 +1 @@ +Please refer to [spring/README.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/README.md) for more details. diff --git a/sdk/spring/spring-cloud-azure-service/pom.xml b/sdk/spring/spring-cloud-azure-service/pom.xml index 1f97d0749093..edcd0abdf2f7 100644 --- a/sdk/spring/spring-cloud-azure-service/pom.xml +++ b/sdk/spring/spring-cloud-azure-service/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-cloud-azure-service - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Service Spring Cloud Azure Service @@ -41,68 +41,68 @@ com.azure.spring spring-cloud-azure-core - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure azure-cosmos - 4.66.0 + 4.67.0 true com.azure azure-data-appconfiguration - 1.7.3 + 1.7.4 true com.azure azure-messaging-servicebus - 7.17.8 + 7.17.9 true com.azure azure-messaging-eventhubs - 5.19.2 + 5.20.1 true com.azure azure-messaging-eventgrid - 4.27.0 + 4.29.0 true com.azure azure-security-keyvault-certificates - 4.7.1 + 4.7.3 true com.azure azure-security-keyvault-secrets - 4.9.1 + 4.9.3 true com.azure azure-storage-blob - 12.29.0 + 12.29.1 true com.azure azure-storage-file-share - 12.25.1 + 12.25.2 true com.azure azure-storage-queue - 12.24.0 + 12.24.1 true @@ -118,7 +118,7 @@ com.azure azure-identity-extensions - 1.2.0 + 1.2.1 true @@ -151,7 +151,7 @@ org.springframework spring-test - 6.2.1 + 6.2.2 test @@ -209,7 +209,7 @@ org.apache.kafka:kafka-clients:[3.8.1] - org.postgresql:postgresql:[42.7.4] + org.postgresql:postgresql:[42.7.5] diff --git a/sdk/spring/spring-cloud-azure-service/src/test/java/com/azure/spring/cloud/service/implementation/AzureServiceClientBuilderFactoryBaseTests.java b/sdk/spring/spring-cloud-azure-service/src/test/java/com/azure/spring/cloud/service/implementation/AzureServiceClientBuilderFactoryBaseTests.java index 0b9f8d24416a..ce3963ec69a6 100644 --- a/sdk/spring/spring-cloud-azure-service/src/test/java/com/azure/spring/cloud/service/implementation/AzureServiceClientBuilderFactoryBaseTests.java +++ b/sdk/spring/spring-cloud-azure-service/src/test/java/com/azure/spring/cloud/service/implementation/AzureServiceClientBuilderFactoryBaseTests.java @@ -15,6 +15,7 @@ import static org.mockito.Mockito.times; +@SuppressWarnings("deprecation") public abstract class AzureServiceClientBuilderFactoryBaseTests> extends AzureGenericServiceClientBuilderFactoryBaseTests { diff --git a/sdk/spring/spring-cloud-azure-service/src/test/java/com/azure/spring/cloud/service/implementation/servicebus/factory/AbstractServiceBusSubClientBuilderFactoryTests.java b/sdk/spring/spring-cloud-azure-service/src/test/java/com/azure/spring/cloud/service/implementation/servicebus/factory/AbstractServiceBusSubClientBuilderFactoryTests.java index 9473abe8563d..2d9905cc98ce 100644 --- a/sdk/spring/spring-cloud-azure-service/src/test/java/com/azure/spring/cloud/service/implementation/servicebus/factory/AbstractServiceBusSubClientBuilderFactoryTests.java +++ b/sdk/spring/spring-cloud-azure-service/src/test/java/com/azure/spring/cloud/service/implementation/servicebus/factory/AbstractServiceBusSubClientBuilderFactoryTests.java @@ -28,6 +28,7 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +@SuppressWarnings("deprecation") abstract class AbstractServiceBusSubClientBuilderFactoryTests> extends AzureGenericServiceClientBuilderFactoryBaseTests { diff --git a/sdk/spring/spring-cloud-azure-starter-active-directory-b2c/pom.xml b/sdk/spring/spring-cloud-azure-starter-active-directory-b2c/pom.xml index 6777f06971b6..c260e42f46e5 100644 --- a/sdk/spring/spring-cloud-azure-starter-active-directory-b2c/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-active-directory-b2c/pom.xml @@ -7,7 +7,7 @@ com.azure.spring spring-cloud-azure-starter-active-directory-b2c - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Starter Active Directory B2C Spring Cloud Azure Starter Active Directory B2C @@ -90,7 +90,7 @@ com.azure.spring spring-cloud-azure-starter - 5.20.0-beta.1 + 5.21.0-beta.1 org.springframework.security diff --git a/sdk/spring/spring-cloud-azure-starter-active-directory/pom.xml b/sdk/spring/spring-cloud-azure-starter-active-directory/pom.xml index 929716653399..405c6b27ea43 100644 --- a/sdk/spring/spring-cloud-azure-starter-active-directory/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-active-directory/pom.xml @@ -7,7 +7,7 @@ com.azure.spring spring-cloud-azure-starter-active-directory - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Starter Active Directory Spring Cloud Azure Starter Active Directory @@ -89,7 +89,7 @@ com.azure.spring spring-cloud-azure-starter - 5.20.0-beta.1 + 5.21.0-beta.1 org.springframework.security diff --git a/sdk/spring/spring-cloud-azure-starter-actuator/pom.xml b/sdk/spring/spring-cloud-azure-starter-actuator/pom.xml index 49cdabdaa2e1..87e5be8c7e8e 100644 --- a/sdk/spring/spring-cloud-azure-starter-actuator/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-actuator/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter-actuator - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Starter Actuator Spring Cloud Azure Starter Actuator @@ -89,17 +89,17 @@ com.azure.spring spring-cloud-azure-starter - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure.spring spring-cloud-azure-actuator-autoconfigure - 5.20.0-beta.1 + 5.21.0-beta.1 org.springframework.boot spring-boot-starter-actuator - 3.4.1 + 3.4.2 diff --git a/sdk/spring/spring-cloud-azure-starter-appconfiguration-config/CHANGELOG.md b/sdk/spring/spring-cloud-azure-starter-appconfiguration-config/CHANGELOG.md index ff498ebcef83..537e26e0c1ee 100644 --- a/sdk/spring/spring-cloud-azure-starter-appconfiguration-config/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-starter-appconfiguration-config/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 5.20.0-beta.1 (Unreleased) +## 5.21.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 5.20.1 (2025-03-03) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5201-2025-03-03) for more details. + +## 5.20.0 (2025-02-12) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5200-2025-02-12) for more details. + ## 5.19.0 (2024-12-17) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5190-2024-12-17) for more details. diff --git a/sdk/spring/spring-cloud-azure-starter-appconfiguration-config/README.md b/sdk/spring/spring-cloud-azure-starter-appconfiguration-config/README.md index 8dccd7b6d642..9450b2858ed4 100644 --- a/sdk/spring/spring-cloud-azure-starter-appconfiguration-config/README.md +++ b/sdk/spring/spring-cloud-azure-starter-appconfiguration-config/README.md @@ -21,7 +21,7 @@ There are two libraries that can be used spring-cloud-azure-appconfiguration-con com.azure.spring spring-cloud-azure-appconfiguration-config - 5.19.0 + 5.21.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -33,7 +33,7 @@ or com.azure.spring spring-cloud-azure-appconfiguration-config-web - 5.19.0 + 5.21.0-beta.1 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/spring/spring-cloud-azure-starter-appconfiguration-config/pom.xml b/sdk/spring/spring-cloud-azure-starter-appconfiguration-config/pom.xml index 6cb8a638e660..bd0a4cc228c3 100644 --- a/sdk/spring/spring-cloud-azure-starter-appconfiguration-config/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-appconfiguration-config/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter-appconfiguration-config - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Starter App Configuration Config Spring Cloud Azure Starter App Configuration Config https://microsoft.github.io/spring-cloud-azure @@ -88,12 +88,12 @@ com.azure.spring spring-cloud-azure-appconfiguration-config-web - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure.spring spring-cloud-azure-feature-management-web - 5.20.0-beta.1 + 5.21.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-starter-appconfiguration/pom.xml b/sdk/spring/spring-cloud-azure-starter-appconfiguration/pom.xml index f14de9843487..106866f5fe7d 100644 --- a/sdk/spring/spring-cloud-azure-starter-appconfiguration/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-appconfiguration/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter-appconfiguration - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Starter App Configuration Spring Cloud Azure Starter App Configuration @@ -89,12 +89,12 @@ com.azure.spring spring-cloud-azure-starter - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure azure-data-appconfiguration - 1.7.3 + 1.7.4 diff --git a/sdk/spring/spring-cloud-azure-starter-cosmos/pom.xml b/sdk/spring/spring-cloud-azure-starter-cosmos/pom.xml index f74e7486f09d..4bd23a5a23a9 100644 --- a/sdk/spring/spring-cloud-azure-starter-cosmos/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-cosmos/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter-cosmos - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Starter Cosmos DB Spring Cloud Azure Starter Cosmos DB @@ -89,12 +89,12 @@ com.azure.spring spring-cloud-azure-starter - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure azure-cosmos - 4.66.0 + 4.67.0 diff --git a/sdk/spring/spring-cloud-azure-starter-data-cosmos/pom.xml b/sdk/spring/spring-cloud-azure-starter-data-cosmos/pom.xml index 71eb58053b57..3bb9b3f163e0 100644 --- a/sdk/spring/spring-cloud-azure-starter-data-cosmos/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-data-cosmos/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter-data-cosmos - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Starter Data Cosmos DB Spring Cloud Azure Starter Data Cosmos DB @@ -89,12 +89,12 @@ com.azure.spring spring-cloud-azure-starter - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure azure-spring-data-cosmos - 5.20.0-beta.1 + 5.21.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-starter-data-redis-lettuce/pom.xml b/sdk/spring/spring-cloud-azure-starter-data-redis-lettuce/pom.xml index 09dd75091b39..1bfb27b88599 100644 --- a/sdk/spring/spring-cloud-azure-starter-data-redis-lettuce/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-data-redis-lettuce/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter-data-redis-lettuce - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Starter Data Redis with Lettuce Spring Cloud Azure Starter Data Redis with Lettuce @@ -89,26 +89,26 @@ com.azure.spring spring-cloud-azure-starter - 5.20.0-beta.1 + 5.21.0-beta.1 org.springframework.data spring-data-redis - 3.4.1 + 3.4.2 io.lettuce lettuce-core - 6.4.1.RELEASE + 6.4.2.RELEASE true com.azure azure-identity-extensions - 1.2.0 + 1.2.1 diff --git a/sdk/spring/spring-cloud-azure-starter-eventgrid/pom.xml b/sdk/spring/spring-cloud-azure-starter-eventgrid/pom.xml index e58fb83ac401..6cce280b7090 100644 --- a/sdk/spring/spring-cloud-azure-starter-eventgrid/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-eventgrid/pom.xml @@ -7,7 +7,7 @@ com.azure.spring spring-cloud-azure-starter-eventgrid - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Starter Event Grid Spring Cloud Azure Starter Event Grid @@ -90,13 +90,13 @@ com.azure.spring spring-cloud-azure-starter - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure azure-messaging-eventgrid - 4.27.0 + 4.29.0 diff --git a/sdk/spring/spring-cloud-azure-starter-eventhubs/pom.xml b/sdk/spring/spring-cloud-azure-starter-eventhubs/pom.xml index fefeb9112c06..f395d33a8f4d 100644 --- a/sdk/spring/spring-cloud-azure-starter-eventhubs/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-eventhubs/pom.xml @@ -7,7 +7,7 @@ com.azure.spring spring-cloud-azure-starter-eventhubs - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Starter Event Hubs Spring Cloud Azure Starter Event Hubs @@ -90,19 +90,19 @@ com.azure.spring spring-cloud-azure-starter - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure azure-messaging-eventhubs - 5.19.2 + 5.20.1 com.azure azure-messaging-eventhubs-checkpointstore-blob - 1.20.2 + 1.20.5 diff --git a/sdk/spring/spring-cloud-azure-starter-integration-eventhubs/pom.xml b/sdk/spring/spring-cloud-azure-starter-integration-eventhubs/pom.xml index a151be34895b..ceff1ca03cdc 100644 --- a/sdk/spring/spring-cloud-azure-starter-integration-eventhubs/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-integration-eventhubs/pom.xml @@ -7,7 +7,7 @@ com.azure.spring spring-cloud-azure-starter-integration-eventhubs - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Starter Integration Event Hubs Spring Cloud Azure Starter Integration Event Hubs @@ -90,17 +90,17 @@ com.azure.spring spring-cloud-azure-starter - 5.20.0-beta.1 + 5.21.0-beta.1 org.springframework.boot spring-boot-starter-integration - 3.4.1 + 3.4.2 com.azure.spring spring-integration-azure-eventhubs - 5.20.0-beta.1 + 5.21.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-starter-integration-servicebus/pom.xml b/sdk/spring/spring-cloud-azure-starter-integration-servicebus/pom.xml index 0e8acc100cbc..53d2ba20b221 100644 --- a/sdk/spring/spring-cloud-azure-starter-integration-servicebus/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-integration-servicebus/pom.xml @@ -7,7 +7,7 @@ com.azure.spring spring-cloud-azure-starter-integration-servicebus - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Starter Integration Service Bus Spring Cloud Azure Starter Integration Service Bus @@ -90,17 +90,17 @@ com.azure.spring spring-cloud-azure-starter - 5.20.0-beta.1 + 5.21.0-beta.1 org.springframework.boot spring-boot-starter-integration - 3.4.1 + 3.4.2 com.azure.spring spring-integration-azure-servicebus - 5.20.0-beta.1 + 5.21.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-starter-integration-storage-queue/pom.xml b/sdk/spring/spring-cloud-azure-starter-integration-storage-queue/pom.xml index 5c0d01f7623d..ed1f51159821 100644 --- a/sdk/spring/spring-cloud-azure-starter-integration-storage-queue/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-integration-storage-queue/pom.xml @@ -10,7 +10,7 @@ com.azure.spring spring-cloud-azure-starter-integration-storage-queue - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Starter Integration Storage Queue Spring Cloud Azure Starter Integration Storage Queue @@ -93,17 +93,17 @@ com.azure.spring spring-cloud-azure-starter - 5.20.0-beta.1 + 5.21.0-beta.1 org.springframework.boot spring-boot-starter-integration - 3.4.1 + 3.4.2 com.azure.spring spring-integration-azure-storage-queue - 5.20.0-beta.1 + 5.21.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-starter-jdbc-mysql/pom.xml b/sdk/spring/spring-cloud-azure-starter-jdbc-mysql/pom.xml index a53b69f155c6..42ff880ca21d 100644 --- a/sdk/spring/spring-cloud-azure-starter-jdbc-mysql/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-jdbc-mysql/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter-jdbc-mysql - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Starter JDBC MySQL Spring Cloud Azure Starter for building applications with JDBC and Azure MySQL Services. Support authenticating with Azure AD. @@ -89,13 +89,13 @@ com.azure.spring spring-cloud-azure-starter - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure azure-identity-extensions - 1.2.0 + 1.2.1 diff --git a/sdk/spring/spring-cloud-azure-starter-jdbc-postgresql/pom.xml b/sdk/spring/spring-cloud-azure-starter-jdbc-postgresql/pom.xml index fb043dfc6f8c..6598f145a16d 100644 --- a/sdk/spring/spring-cloud-azure-starter-jdbc-postgresql/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-jdbc-postgresql/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter-jdbc-postgresql - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Starter JDBC PostgreSQL Spring Cloud Azure Starter for building applications with JDBC and Azure PostgreSQL Services. Support authenticating with Azure AD. @@ -89,19 +89,19 @@ com.azure.spring spring-cloud-azure-starter - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure azure-identity-extensions - 1.2.0 + 1.2.1 org.postgresql postgresql - 42.7.4 + 42.7.5 diff --git a/sdk/spring/spring-cloud-azure-starter-keyvault-certificates/pom.xml b/sdk/spring/spring-cloud-azure-starter-keyvault-certificates/pom.xml index ad6d394d327d..5391db1f2e80 100644 --- a/sdk/spring/spring-cloud-azure-starter-keyvault-certificates/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-keyvault-certificates/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter-keyvault-certificates - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Starter Key Vault Certificates Spring Cloud Azure Starter Key Vault Certificates @@ -89,12 +89,12 @@ com.azure.spring spring-cloud-azure-starter - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure azure-security-keyvault-certificates - 4.7.1 + 4.7.3 diff --git a/sdk/spring/spring-cloud-azure-starter-keyvault-jca/pom.xml b/sdk/spring/spring-cloud-azure-starter-keyvault-jca/pom.xml new file mode 100644 index 000000000000..089bc299b1f9 --- /dev/null +++ b/sdk/spring/spring-cloud-azure-starter-keyvault-jca/pom.xml @@ -0,0 +1,219 @@ + + + 4.0.0 + + com.azure.spring + spring-cloud-azure-starter-keyvault-jca + 5.21.0-beta.1 + + Spring Cloud Azure Starter Key Vault JCA + Spring Cloud Azure Starter Key Vault Java Crypto Architecture (JCA) Provider + https://learn.microsoft.com/azure/developer/java/spring-framework + + + Spring Cloud Azure + SpringIntegSupport@microsoft.com + + + + scm:git:git@github.com:Azure/azure-sdk-for-java.git + scm:git:ssh://git@github.com:Azure/azure-sdk-for-java.git + https://github.com/Azure/azure-sdk-for-java + + + GitHub + https://github.com/Azure/azure-sdk-for-java/issues + + + + 17 + 17 + + + https://azuresdkartifacts.blob.core.windows.net/azure-sdk-for-java + true + + + + + The MIT License (MIT) + http://opensource.org/licenses/MIT + repo + + + + + + + ossrh + Sonatype Snapshots + https://oss.sonatype.org/content/repositories/snapshots/ + default + + true + daily + + + + + + + ossrh + Sonatype Snapshots + https://oss.sonatype.org/content/repositories/snapshots/ + default + + true + always + + + + + + + ossrh + Sonatype Snapshots + https://oss.sonatype.org/content/repositories/snapshots/ + true + default + + + azure-java-build-docs + ${site.url}/site/ + + + + + + com.azure.spring + spring-cloud-azure-starter + 5.21.0-beta.1 + + + com.azure + azure-security-keyvault-jca + 2.10.0 + + + + + + + com.github.spotbugs + spotbugs-maven-plugin + 4.8.2.0 + + true + + + + com.diffplug.spotless + spotless-maven-plugin + 2.30.0 + + true + + + + org.revapi + revapi-maven-plugin + 0.14.6 + + true + + + + com.azure.tools + codesnippet-maven-plugin + 1.0.0-beta.10 + + true + + + + org.apache.maven.plugins + maven-jar-plugin + 3.4.2 + + + + com.azure.spring.cloud.starter.keyvault.certificates + + + true + + + + + + + + empty-javadoc-jar-with-readme + package + + jar + + + javadoc + ${project.basedir}/javadocTemp + + + + empty-source-jar-with-readme + package + + jar + + + sources + ${project.basedir}/sourceTemp + + + + + + org.apache.maven.plugins + maven-antrun-plugin + 3.1.0 + + + copy-readme-to-javadocTemp-and-sourceTemp + prepare-package + + + Deleting existing ${project.basedir}/javadocTemp and + ${project.basedir}/sourceTemp + + + + + Copying ${project.basedir}/../README.md to + ${project.basedir}/javadocTemp/README.md + + + Copying ${project.basedir}/../README.md to + ${project.basedir}/sourceTemp/README.md + + + + + + run + + + + + + + + + diff --git a/sdk/spring/spring-cloud-azure-starter-keyvault-secrets/pom.xml b/sdk/spring/spring-cloud-azure-starter-keyvault-secrets/pom.xml index cef722ebbc39..4082f10dc5e4 100644 --- a/sdk/spring/spring-cloud-azure-starter-keyvault-secrets/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-keyvault-secrets/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter-keyvault-secrets - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Starter Key Vault Secrets Spring Cloud Azure Starter Key Vault Secrets @@ -89,12 +89,12 @@ com.azure.spring spring-cloud-azure-starter - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure azure-security-keyvault-secrets - 4.9.1 + 4.9.3 diff --git a/sdk/spring/spring-cloud-azure-starter-keyvault/pom.xml b/sdk/spring/spring-cloud-azure-starter-keyvault/pom.xml index 7812a0f767ea..7b5481ea2dda 100644 --- a/sdk/spring/spring-cloud-azure-starter-keyvault/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-keyvault/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter-keyvault - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Starter Key Vault Spring Cloud Azure Starter Key Vault @@ -89,12 +89,17 @@ com.azure.spring spring-cloud-azure-starter-keyvault-secrets - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure.spring spring-cloud-azure-starter-keyvault-certificates - 5.20.0-beta.1 + 5.21.0-beta.1 + + + com.azure.spring + spring-cloud-azure-starter-keyvault-jca + 5.21.0-beta.1 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 c7b8e61b02c6..cca2c2221871 100644 --- a/sdk/spring/spring-cloud-azure-starter-monitor-test/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-monitor-test/pom.xml @@ -7,7 +7,7 @@ org.springframework.boot spring-boot-starter-parent - 3.4.1 + 3.4.2 @@ -31,7 +31,7 @@ io.opentelemetry opentelemetry-bom - 1.43.0 + 1.46.0 pom runtime @@ -48,23 +48,23 @@ org.springframework.boot spring-boot-starter-web - 3.4.1 + 3.4.2 org.springframework.boot spring-boot-starter-data-jdbc - 3.4.1 + 3.4.2 org.springframework.boot spring-boot-starter-test - 3.4.1 + 3.4.2 test com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test @@ -80,7 +80,7 @@ org.apache.maven.plugins maven-checkstyle-plugin - 3.5.0 + 3.6.0 true @@ -162,7 +162,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 true diff --git a/sdk/spring/spring-cloud-azure-starter-monitor-test/src/test/java/com/azure/spring/cloud/autoconfigure/monitor/SpringMonitorTest.java b/sdk/spring/spring-cloud-azure-starter-monitor-test/src/test/java/com/azure/spring/cloud/autoconfigure/monitor/SpringMonitorTest.java index d37513944c9d..9e31cb5db718 100644 --- a/sdk/spring/spring-cloud-azure-starter-monitor-test/src/test/java/com/azure/spring/cloud/autoconfigure/monitor/SpringMonitorTest.java +++ b/sdk/spring/spring-cloud-azure-starter-monitor-test/src/test/java/com/azure/spring/cloud/autoconfigure/monitor/SpringMonitorTest.java @@ -25,6 +25,7 @@ import java.net.MalformedURLException; import java.net.URL; import java.util.List; +import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.stream.Collectors; @@ -99,6 +100,7 @@ public void shouldMonitor() throws InterruptedException, MalformedURLException { // Log telemetry assertThat(logs.size()).isGreaterThan(0); TelemetryItem firstLogTelemetry = logs.get(0); + assertThat(sdkVersion(firstLogTelemetry)).contains("java").contains(":otel").contains(":dss"); MonitorDomain logBaseData = firstLogTelemetry.getData().getBaseData(); MessageData logData = toMessageData(logBaseData); assertThat(logData.getMessage()).startsWith("Starting SpringMonitorTest using"); @@ -124,6 +126,11 @@ public void shouldMonitor() throws InterruptedException, MalformedURLException { assertThat(requestData.getName()).isEqualTo("GET /controller-url"); } + private static String sdkVersion(TelemetryItem telemetryItem) { + Map tags = telemetryItem.getTags(); + return tags.get("ai.internal.sdkVersion"); + } + // Copied from com.azure.monitor.opentelemetry.exporter.implementation.utils.TestUtils.java // azure-json doesn't deserialize subtypes yet, so need to convert the abstract MonitorDomain to MessageData public static MessageData toMessageData(MonitorDomain baseData) { diff --git a/sdk/spring/spring-cloud-azure-starter-monitor/README.md b/sdk/spring/spring-cloud-azure-starter-monitor/README.md index 773a37703772..6ef0db9c4161 100644 --- a/sdk/spring/spring-cloud-azure-starter-monitor/README.md +++ b/sdk/spring/spring-cloud-azure-starter-monitor/README.md @@ -19,10 +19,9 @@ For more information, please read [introduction to Application Insights][applica ### Build update -#### OpenTelemetry configuration +#### OpenTelemetry dependency management -Import the OpenTelemetry Bills of Materials (BOM) -by [following the OpenTelemetry documentation](https://opentelemetry.io/docs/instrumentation/java/automatic/spring-boot/#dependency-management). +Follow these [OpenTelemetry instructions](https://opentelemetry.io/docs/zero-code/java/spring-boot-starter/getting-started/#dependency-management) on dependency management. #### Add monitoring dependency @@ -55,7 +54,7 @@ You can then configure the connection string in two different ways: The [Application Map](https://learn.microsoft.com/azure/azure-monitor/app/app-map?tabs=net#set-or-override-cloud-role-name) uses the cloud role name to identify components on the map. -You can set the cloud role name with the `spring.application.name` property. You have other options to set the cloud role role: see how to set the service name in the [OpenTelemetry documentation](https://opentelemetry.io/docs/languages/java/automatic/spring-boot/). +You can set the cloud role name with the `spring.application.name` property. You have other options to set the cloud role role: see how to set the service name in the [OpenTelemetry documentation](https://opentelemetry.io/docs/zero-code/java/spring-boot-starter/sdk-configuration/#service-name). ### Build your Spring native application At this step, you can build your Spring Boot native image application and start it: @@ -109,4 +108,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ [coc_contact]: mailto:opencode@microsoft.com -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%monitor%2Fazure-monitor-spring-native%2FREADME.png) + diff --git a/sdk/spring/spring-cloud-azure-starter-monitor/ci.yml b/sdk/spring/spring-cloud-azure-starter-monitor/ci.yml index da110e84b17d..cff5a479b4f3 100644 --- a/sdk/spring/spring-cloud-azure-starter-monitor/ci.yml +++ b/sdk/spring/spring-cloud-azure-starter-monitor/ci.yml @@ -38,3 +38,5 @@ extends: AdditionalModules: - name: spring-cloud-azure-starter-monitor-test groupId: com.azure.spring + MatrixFilters: + - JavaTestVersion=^(?!1.8|1.11).* diff --git a/sdk/spring/spring-cloud-azure-starter-monitor/pom.xml b/sdk/spring/spring-cloud-azure-starter-monitor/pom.xml index 2ca923f050b8..aa5d282e8bde 100644 --- a/sdk/spring/spring-cloud-azure-starter-monitor/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-monitor/pom.xml @@ -3,93 +3,138 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.azure azure-client-sdk-parent 1.7.0 ../../parents/azure-client-sdk-parent + + scm:git:git@github.com:Azure/azure-sdk-for-java.git + scm:git:ssh://git@github.com:Azure/azure-sdk-for-java.git + https://github.com/Azure/azure-sdk-for-java + + + GitHub + https://github.com/Azure/azure-sdk-for-java/issues + - 8 - 8 - - ${jdk.version} - ${jdk.version} - ${jdk-test.version} - ${jdk-test.version} - true + 17 + 17 + true true - com.azure.spring - spring-cloud-azure-starter-monitor - 1.0.0-beta.7 + + + The MIT License (MIT) + http://opensource.org/licenses/MIT + repo + + - Azure Monitor OpenTelemetry Distro / Application Insights in Spring native Java application - Spring Boot starter providing telemetry data to Azure Monitor for Spring Boot applications and GraalVM native images. + + + + ossrh + Sonatype Snapshots + https://oss.sonatype.org/content/repositories/snapshots/ + default + + true + daily + + + + + + + ossrh + Sonatype Snapshots + https://oss.sonatype.org/content/repositories/snapshots/ + default + + true + always + + + + + ossrh + Sonatype Snapshots + https://oss.sonatype.org/content/repositories/snapshots/ + true + default + azure-java-build-docs - ${site.url}/site/${project.artifactId} + ${site.url}/site/ - - https://github.com/Azure/azure-sdk-for-java - + com.azure.spring + spring-cloud-azure-starter-monitor + 1.0.0-beta.7 + + Azure Monitor OpenTelemetry Distro / Application Insights in Spring native Java application + Spring Boot starter providing telemetry data to Azure Monitor for Spring Boot applications and GraalVM native images. - + + org.springframework.boot + spring-boot-starter + 3.4.2 + provided + + io.opentelemetry.instrumentation opentelemetry-spring-boot-starter - 2.9.0 + 2.12.0 - - + io.opentelemetry opentelemetry-api - 1.43.0 + 1.46.0 io.opentelemetry opentelemetry-sdk - 1.43.0 + 1.46.0 io.opentelemetry opentelemetry-sdk-metrics - 1.43.0 + 1.46.0 io.opentelemetry opentelemetry-sdk-logs - 1.43.0 + 1.46.0 io.opentelemetry opentelemetry-sdk-extension-autoconfigure-spi - 1.43.0 + 1.46.0 - - - org.springframework.boot - spring-boot-starter - 2.7.18 - provided + io.opentelemetry + opentelemetry-sdk-extension-autoconfigure + 1.46.0 + + com.azure azure-monitor-opentelemetry-autoconfigure - 1.0.0-beta.1 + 1.0.0 @@ -111,19 +156,56 @@ 3.22.0 test + + + org.slf4j + slf4j-simple + 2.0.16 + test + org.springframework.boot spring-boot-starter-test - 2.7.18 + 3.4.2 test - + + org.apache.maven.plugins + maven-compiler-plugin + 3.13.0 + + + + base-modules-compile + none + + + + base-compile + none + + + + base-testCompile + none + + + + + compile + + + 17 + + + + org.apache.maven.plugins maven-enforcer-plugin @@ -132,15 +214,15 @@ - io.opentelemetry.instrumentation:opentelemetry-spring-boot-starter:[2.9.0] - io.opentelemetry:opentelemetry-sdk-extension-autoconfigure:[1.43.0] - io.opentelemetry.instrumentation:opentelemetry-runtime-telemetry-java8:[2.9.0-alpha] - io.opentelemetry:opentelemetry-api:[1.43.0] - io.opentelemetry:opentelemetry-sdk:[1.43.0] - io.opentelemetry:opentelemetry-sdk-metrics:[1.43.0] - io.opentelemetry:opentelemetry-sdk-logs:[1.43.0] - io.opentelemetry:opentelemetry-sdk-extension-autoconfigure-spi:[1.43.0] - org.springframework.boot:spring-boot-starter:[2.7.18] + io.opentelemetry.instrumentation:opentelemetry-spring-boot-starter:[2.12.0] + io.opentelemetry:opentelemetry-sdk-extension-autoconfigure:[1.46.0] + io.opentelemetry.instrumentation:opentelemetry-runtime-telemetry-java8:[2.12.0-alpha] + io.opentelemetry:opentelemetry-api:[1.46.0] + io.opentelemetry:opentelemetry-sdk:[1.46.0] + io.opentelemetry:opentelemetry-sdk-metrics:[1.46.0] + io.opentelemetry:opentelemetry-sdk-logs:[1.46.0] + io.opentelemetry:opentelemetry-sdk-extension-autoconfigure-spi:[1.46.0] + org.springframework.boot:spring-boot-starter:[3.4.2] diff --git a/sdk/spring/spring-cloud-azure-starter-monitor/src/main/java/com/azure/spring/cloud/autoconfigure/monitor/implementation/OpenTelemetryVersionCheckRunner.java b/sdk/spring/spring-cloud-azure-starter-monitor/src/main/java/com/azure/spring/cloud/autoconfigure/monitor/implementation/OpenTelemetryVersionCheckRunner.java index d24d76bd0612..6d01ac4a58ad 100644 --- a/sdk/spring/spring-cloud-azure-starter-monitor/src/main/java/com/azure/spring/cloud/autoconfigure/monitor/implementation/OpenTelemetryVersionCheckRunner.java +++ b/sdk/spring/spring-cloud-azure-starter-monitor/src/main/java/com/azure/spring/cloud/autoconfigure/monitor/implementation/OpenTelemetryVersionCheckRunner.java @@ -15,7 +15,7 @@ class OpenTelemetryVersionCheckRunner implements CommandLineRunner { /** * OpenTelemetry version of the starter */ - static final String STARTER_OTEL_VERSION = "1.43.0"; + static final String STARTER_OTEL_VERSION = "1.46.0"; @Override public void run(String... args) { 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 ec9ad5d9d541..55e02a94334c 100644 --- a/sdk/spring/spring-cloud-azure-starter-servicebus-jms/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-servicebus-jms/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter-servicebus-jms - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Starter Service Bus JMS Spring Cloud Azure Starter Service Bus JMS @@ -89,14 +89,14 @@ com.azure.spring spring-cloud-azure-starter - 5.20.0-beta.1 + 5.21.0-beta.1 org.springframework spring-jms - 6.2.1 + 6.2.2 org.messaginghub @@ -123,55 +123,55 @@ currently released version and a lower version is resolved. --> com.azure azure-core - 1.54.1 + 1.55.3 true com.azure azure-identity - 1.15.0 + 1.15.4 true io.netty netty-buffer - 4.1.116.Final + 4.1.117.Final io.netty netty-common - 4.1.116.Final + 4.1.117.Final io.netty netty-handler - 4.1.116.Final + 4.1.117.Final io.netty netty-transport - 4.1.116.Final + 4.1.117.Final io.netty netty-transport-native-epoll - 4.1.116.Final + 4.1.117.Final io.netty netty-transport-native-kqueue - 4.1.116.Final + 4.1.117.Final io.netty netty-codec-http - 4.1.116.Final + 4.1.117.Final com.azure azure-identity-extensions - 1.2.0 + 1.2.1 diff --git a/sdk/spring/spring-cloud-azure-starter-servicebus/pom.xml b/sdk/spring/spring-cloud-azure-starter-servicebus/pom.xml index 4895a29ecc52..1f59b496d0ac 100644 --- a/sdk/spring/spring-cloud-azure-starter-servicebus/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-servicebus/pom.xml @@ -7,7 +7,7 @@ com.azure.spring spring-cloud-azure-starter-servicebus - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Starter Service Bus Spring Cloud Azure Starter Service Bus @@ -90,12 +90,12 @@ com.azure.spring spring-cloud-azure-starter - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure azure-messaging-servicebus - 7.17.8 + 7.17.9 diff --git a/sdk/spring/spring-cloud-azure-starter-storage-blob/pom.xml b/sdk/spring/spring-cloud-azure-starter-storage-blob/pom.xml index cfd73f6374df..06ea89624b27 100644 --- a/sdk/spring/spring-cloud-azure-starter-storage-blob/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-storage-blob/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter-storage-blob - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Starter Storage Blob Spring Cloud Azure Starter Storage Blob @@ -89,13 +89,13 @@ com.azure.spring spring-cloud-azure-starter - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure azure-storage-blob - 12.29.0 + 12.29.1 diff --git a/sdk/spring/spring-cloud-azure-starter-storage-file-share/pom.xml b/sdk/spring/spring-cloud-azure-starter-storage-file-share/pom.xml index 67bfafe6eb63..f46d1b68e210 100644 --- a/sdk/spring/spring-cloud-azure-starter-storage-file-share/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-storage-file-share/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter-storage-file-share - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Starter Storage File Share Spring Cloud Azure Starter Storage File Share @@ -89,13 +89,13 @@ com.azure.spring spring-cloud-azure-starter - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure azure-storage-file-share - 12.25.1 + 12.25.2 diff --git a/sdk/spring/spring-cloud-azure-starter-storage-queue/pom.xml b/sdk/spring/spring-cloud-azure-starter-storage-queue/pom.xml index 4458925d368d..5146b4873b53 100644 --- a/sdk/spring/spring-cloud-azure-starter-storage-queue/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-storage-queue/pom.xml @@ -10,7 +10,7 @@ com.azure.spring spring-cloud-azure-starter-storage-queue - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Starter Storage Queue Spring Cloud Azure Starter Storage Queue @@ -93,12 +93,12 @@ com.azure.spring spring-cloud-azure-starter - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure azure-storage-queue - 12.24.0 + 12.24.1 diff --git a/sdk/spring/spring-cloud-azure-starter-storage/pom.xml b/sdk/spring/spring-cloud-azure-starter-storage/pom.xml index 0051676be048..0e957b0c382a 100644 --- a/sdk/spring/spring-cloud-azure-starter-storage/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-storage/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter-storage - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Starter Storage Spring Cloud Azure Starter Storage @@ -89,19 +89,19 @@ com.azure.spring spring-cloud-azure-starter-storage-blob - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure.spring spring-cloud-azure-starter-storage-file-share - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure.spring spring-cloud-azure-starter-storage-queue - 5.20.0-beta.1 + 5.21.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-starter-stream-eventhubs/pom.xml b/sdk/spring/spring-cloud-azure-starter-stream-eventhubs/pom.xml index b4c8ec692225..a8214bc0717c 100644 --- a/sdk/spring/spring-cloud-azure-starter-stream-eventhubs/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-stream-eventhubs/pom.xml @@ -7,7 +7,7 @@ com.azure.spring spring-cloud-azure-starter-stream-eventhubs - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Starter Stream Event Hubs Spring Cloud Azure Starter Stream Event Hubs @@ -90,7 +90,7 @@ com.azure.spring spring-cloud-azure-stream-binder-eventhubs - 5.20.0-beta.1 + 5.21.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-starter-stream-servicebus/pom.xml b/sdk/spring/spring-cloud-azure-starter-stream-servicebus/pom.xml index fc9322db56e3..6341e0bb2555 100644 --- a/sdk/spring/spring-cloud-azure-starter-stream-servicebus/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter-stream-servicebus/pom.xml @@ -7,7 +7,7 @@ com.azure.spring spring-cloud-azure-starter-stream-servicebus - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Starter Stream Service Bus Spring Cloud Azure Starter Stream Service Bus @@ -90,7 +90,7 @@ com.azure.spring spring-cloud-azure-stream-binder-servicebus - 5.20.0-beta.1 + 5.21.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-starter/pom.xml b/sdk/spring/spring-cloud-azure-starter/pom.xml index e383e1259a08..d0cfaccdcc0c 100644 --- a/sdk/spring/spring-cloud-azure-starter/pom.xml +++ b/sdk/spring/spring-cloud-azure-starter/pom.xml @@ -6,7 +6,7 @@ com.azure.spring spring-cloud-azure-starter - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Starter Core starter, including auto-configuration support @@ -89,12 +89,12 @@ org.springframework.boot spring-boot-starter - 3.4.1 + 3.4.2 com.azure.spring spring-cloud-azure-autoconfigure - 5.20.0-beta.1 + 5.21.0-beta.1 diff --git a/sdk/spring/spring-cloud-azure-stream-binder-eventhubs-core/CHANGELOG.md b/sdk/spring/spring-cloud-azure-stream-binder-eventhubs-core/CHANGELOG.md index edb5e88a52c4..a57cc1805451 100644 --- a/sdk/spring/spring-cloud-azure-stream-binder-eventhubs-core/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-stream-binder-eventhubs-core/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 5.20.0-beta.1 (Unreleased) +## 5.21.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 5.20.1 (2025-03-03) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5201-2025-03-03) for more details. + +## 5.20.0 (2025-02-12) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5200-2025-02-12) for more details. + ## 5.19.0 (2024-12-17) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5190-2024-12-17) for more details. diff --git a/sdk/spring/spring-cloud-azure-stream-binder-eventhubs-core/README.md b/sdk/spring/spring-cloud-azure-stream-binder-eventhubs-core/README.md index e69de29bb2d1..bbaecbaa3de8 100644 --- a/sdk/spring/spring-cloud-azure-stream-binder-eventhubs-core/README.md +++ b/sdk/spring/spring-cloud-azure-stream-binder-eventhubs-core/README.md @@ -0,0 +1 @@ +Please refer to [spring/README.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/README.md) for more details. diff --git a/sdk/spring/spring-cloud-azure-stream-binder-eventhubs-core/pom.xml b/sdk/spring/spring-cloud-azure-stream-binder-eventhubs-core/pom.xml index 7f4838f3779d..b72033a8a757 100644 --- a/sdk/spring/spring-cloud-azure-stream-binder-eventhubs-core/pom.xml +++ b/sdk/spring/spring-cloud-azure-stream-binder-eventhubs-core/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-cloud-azure-stream-binder-eventhubs-core - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Stream Binder Event Hubs Core Spring Cloud Azure Stream Binder Event Hubs Core @@ -53,13 +53,13 @@ com.azure.spring spring-integration-azure-eventhubs - 5.20.0-beta.1 + 5.21.0-beta.1 org.springframework.boot spring-boot-configuration-processor - 3.4.1 + 3.4.2 true @@ -92,7 +92,7 @@ org.springframework spring-test - 6.2.1 + 6.2.2 test @@ -108,7 +108,7 @@ org.springframework.boot spring-boot-test - 3.4.1 + 3.4.2 test @@ -171,7 +171,7 @@ - org.springframework.boot:spring-boot-configuration-processor:[3.4.1] + org.springframework.boot:spring-boot-configuration-processor:[3.4.2] org.springframework.cloud:spring-cloud-stream:[4.2.0] diff --git a/sdk/spring/spring-cloud-azure-stream-binder-eventhubs/CHANGELOG.md b/sdk/spring/spring-cloud-azure-stream-binder-eventhubs/CHANGELOG.md index edb5e88a52c4..a57cc1805451 100644 --- a/sdk/spring/spring-cloud-azure-stream-binder-eventhubs/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-stream-binder-eventhubs/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 5.20.0-beta.1 (Unreleased) +## 5.21.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 5.20.1 (2025-03-03) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5201-2025-03-03) for more details. + +## 5.20.0 (2025-02-12) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5200-2025-02-12) for more details. + ## 5.19.0 (2024-12-17) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5190-2024-12-17) for more details. diff --git a/sdk/spring/spring-cloud-azure-stream-binder-eventhubs/README.md b/sdk/spring/spring-cloud-azure-stream-binder-eventhubs/README.md index e69de29bb2d1..bbaecbaa3de8 100644 --- a/sdk/spring/spring-cloud-azure-stream-binder-eventhubs/README.md +++ b/sdk/spring/spring-cloud-azure-stream-binder-eventhubs/README.md @@ -0,0 +1 @@ +Please refer to [spring/README.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/README.md) for more details. diff --git a/sdk/spring/spring-cloud-azure-stream-binder-eventhubs/pom.xml b/sdk/spring/spring-cloud-azure-stream-binder-eventhubs/pom.xml index e9bc5a9c15c1..39e73fa622e5 100644 --- a/sdk/spring/spring-cloud-azure-stream-binder-eventhubs/pom.xml +++ b/sdk/spring/spring-cloud-azure-stream-binder-eventhubs/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-cloud-azure-stream-binder-eventhubs - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Stream Binder Event Hubs Spring Cloud Azure Stream Binder Event Hubs @@ -41,30 +41,30 @@ com.azure.spring spring-cloud-azure-autoconfigure - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure.spring spring-cloud-azure-stream-binder-eventhubs-core - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure azure-messaging-eventhubs-checkpointstore-blob - 1.20.2 + 1.20.5 org.springframework.boot spring-boot-starter-actuator - 3.4.1 + 3.4.2 true com.azure.spring spring-cloud-azure-resourcemanager - 5.20.0-beta.1 + 5.21.0-beta.1 @@ -82,7 +82,7 @@ org.springframework.boot spring-boot-starter-test - 3.4.1 + 3.4.2 test @@ -162,7 +162,7 @@ - org.springframework.boot:spring-boot-starter-actuator:[3.4.1] + org.springframework.boot:spring-boot-starter-actuator:[3.4.2] diff --git a/sdk/spring/spring-cloud-azure-stream-binder-servicebus-core/CHANGELOG.md b/sdk/spring/spring-cloud-azure-stream-binder-servicebus-core/CHANGELOG.md index e441b741757a..dee30c12d278 100644 --- a/sdk/spring/spring-cloud-azure-stream-binder-servicebus-core/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-stream-binder-servicebus-core/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 5.20.0-beta.1 (Unreleased) +## 5.21.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 5.20.1 (2025-03-03) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5201-2025-03-03) for more details. + +## 5.20.0 (2025-02-12) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5200-2025-02-12) for more details. + ## 5.19.0 (2024-12-17) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5190-2024-12-17) for more details. diff --git a/sdk/spring/spring-cloud-azure-stream-binder-servicebus-core/README.md b/sdk/spring/spring-cloud-azure-stream-binder-servicebus-core/README.md index e69de29bb2d1..bbaecbaa3de8 100644 --- a/sdk/spring/spring-cloud-azure-stream-binder-servicebus-core/README.md +++ b/sdk/spring/spring-cloud-azure-stream-binder-servicebus-core/README.md @@ -0,0 +1 @@ +Please refer to [spring/README.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/README.md) for more details. diff --git a/sdk/spring/spring-cloud-azure-stream-binder-servicebus-core/pom.xml b/sdk/spring/spring-cloud-azure-stream-binder-servicebus-core/pom.xml index fbf9aa5927d2..7292807628a2 100644 --- a/sdk/spring/spring-cloud-azure-stream-binder-servicebus-core/pom.xml +++ b/sdk/spring/spring-cloud-azure-stream-binder-servicebus-core/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-cloud-azure-stream-binder-servicebus-core - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Stream Binder Service Bus Core Spring Cloud Azure Stream Binder Service Bus Core @@ -47,17 +47,17 @@ com.azure.spring spring-integration-azure-servicebus - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure azure-messaging-servicebus - 7.17.8 + 7.17.9 org.springframework.boot spring-boot-configuration-processor - 3.4.1 + 3.4.2 true @@ -90,7 +90,7 @@ org.springframework spring-test - 6.2.1 + 6.2.2 test @@ -106,7 +106,7 @@ org.springframework.boot spring-boot-test - 3.4.1 + 3.4.2 test @@ -170,7 +170,7 @@ - org.springframework.boot:spring-boot-configuration-processor:[3.4.1] + org.springframework.boot:spring-boot-configuration-processor:[3.4.2] org.springframework.cloud:spring-cloud-stream:[4.2.0] diff --git a/sdk/spring/spring-cloud-azure-stream-binder-servicebus/CHANGELOG.md b/sdk/spring/spring-cloud-azure-stream-binder-servicebus/CHANGELOG.md index e441b741757a..dee30c12d278 100644 --- a/sdk/spring/spring-cloud-azure-stream-binder-servicebus/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-stream-binder-servicebus/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 5.20.0-beta.1 (Unreleased) +## 5.21.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 5.20.1 (2025-03-03) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5201-2025-03-03) for more details. + +## 5.20.0 (2025-02-12) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5200-2025-02-12) for more details. + ## 5.19.0 (2024-12-17) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5190-2024-12-17) for more details. diff --git a/sdk/spring/spring-cloud-azure-stream-binder-servicebus/README.md b/sdk/spring/spring-cloud-azure-stream-binder-servicebus/README.md index e69de29bb2d1..bbaecbaa3de8 100644 --- a/sdk/spring/spring-cloud-azure-stream-binder-servicebus/README.md +++ b/sdk/spring/spring-cloud-azure-stream-binder-servicebus/README.md @@ -0,0 +1 @@ +Please refer to [spring/README.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/README.md) for more details. diff --git a/sdk/spring/spring-cloud-azure-stream-binder-servicebus/pom.xml b/sdk/spring/spring-cloud-azure-stream-binder-servicebus/pom.xml index 13d4f31f435d..521a6951a3d5 100644 --- a/sdk/spring/spring-cloud-azure-stream-binder-servicebus/pom.xml +++ b/sdk/spring/spring-cloud-azure-stream-binder-servicebus/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-cloud-azure-stream-binder-servicebus - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Stream Binder Service Bus Spring Cloud Azure Stream Binder Service Bus @@ -41,22 +41,22 @@ com.azure.spring spring-cloud-azure-stream-binder-servicebus-core - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure.spring spring-cloud-azure-autoconfigure - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure.spring spring-cloud-azure-resourcemanager - 5.20.0-beta.1 + 5.21.0-beta.1 org.springframework.boot spring-boot-starter-actuator - 3.4.1 + 3.4.2 true + 3.4.2 test @@ -155,7 +155,7 @@ - org.springframework.boot:spring-boot-starter-actuator:[3.4.1] + org.springframework.boot:spring-boot-starter-actuator:[3.4.2] diff --git a/sdk/spring/spring-cloud-azure-testcontainers/CHANGELOG.md b/sdk/spring/spring-cloud-azure-testcontainers/CHANGELOG.md index b78315523599..ed62e6bd9696 100644 --- a/sdk/spring/spring-cloud-azure-testcontainers/CHANGELOG.md +++ b/sdk/spring/spring-cloud-azure-testcontainers/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 5.20.0-beta.1 (Unreleased) +## 5.21.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 5.20.1 (2025-03-03) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5201-2025-03-03) for more details. + +## 5.20.0 (2025-02-12) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5200-2025-02-12) for more details. + ## 5.19.0 (2024-12-17) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5190-2024-12-17) for more details. diff --git a/sdk/spring/spring-cloud-azure-testcontainers/README.md b/sdk/spring/spring-cloud-azure-testcontainers/README.md index e69de29bb2d1..bbaecbaa3de8 100644 --- a/sdk/spring/spring-cloud-azure-testcontainers/README.md +++ b/sdk/spring/spring-cloud-azure-testcontainers/README.md @@ -0,0 +1 @@ +Please refer to [spring/README.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/README.md) for more details. diff --git a/sdk/spring/spring-cloud-azure-testcontainers/pom.xml b/sdk/spring/spring-cloud-azure-testcontainers/pom.xml index 50553aa6db2d..8e12cef7c2b8 100644 --- a/sdk/spring/spring-cloud-azure-testcontainers/pom.xml +++ b/sdk/spring/spring-cloud-azure-testcontainers/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-cloud-azure-testcontainers - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Cloud Azure Testcontainers Spring Cloud Azure Testcontainers @@ -56,33 +56,33 @@ com.azure.spring spring-cloud-azure-autoconfigure - 5.20.0-beta.1 + 5.21.0-beta.1 true com.azure azure-spring-data-cosmos - 5.20.0-beta.1 + 5.21.0-beta.1 true com.azure azure-storage-blob - 12.29.0 + 12.29.1 true com.azure azure-storage-queue - 12.24.0 + 12.24.1 true org.springframework.boot spring-boot-testcontainers - 3.4.1 + 3.4.2 org.testcontainers @@ -103,7 +103,7 @@ org.springframework spring-test - 6.2.1 + 6.2.2 test @@ -167,7 +167,7 @@ - org.springframework.boot:spring-boot-testcontainers:[3.4.1] + org.springframework.boot:spring-boot-testcontainers:[3.4.2] org.testcontainers:azure:[1.20.4] diff --git a/sdk/spring/spring-integration-azure-core/CHANGELOG.md b/sdk/spring/spring-integration-azure-core/CHANGELOG.md index e441b741757a..dee30c12d278 100644 --- a/sdk/spring/spring-integration-azure-core/CHANGELOG.md +++ b/sdk/spring/spring-integration-azure-core/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 5.20.0-beta.1 (Unreleased) +## 5.21.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 5.20.1 (2025-03-03) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5201-2025-03-03) for more details. + +## 5.20.0 (2025-02-12) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5200-2025-02-12) for more details. + ## 5.19.0 (2024-12-17) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5190-2024-12-17) for more details. diff --git a/sdk/spring/spring-integration-azure-core/README.md b/sdk/spring/spring-integration-azure-core/README.md index e69de29bb2d1..bbaecbaa3de8 100644 --- a/sdk/spring/spring-integration-azure-core/README.md +++ b/sdk/spring/spring-integration-azure-core/README.md @@ -0,0 +1 @@ +Please refer to [spring/README.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/README.md) for more details. diff --git a/sdk/spring/spring-integration-azure-core/pom.xml b/sdk/spring/spring-integration-azure-core/pom.xml index 8d9185c116f6..9742a24f3c60 100644 --- a/sdk/spring/spring-integration-azure-core/pom.xml +++ b/sdk/spring/spring-integration-azure-core/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-integration-azure-core - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Integration Azure Core Spring Integration Azure Core @@ -43,7 +43,7 @@ com.azure.spring spring-messaging-azure - 5.20.0-beta.1 + 5.21.0-beta.1 org.springframework.integration @@ -83,7 +83,7 @@ org.springframework spring-test - 6.2.1 + 6.2.2 test diff --git a/sdk/spring/spring-integration-azure-eventhubs/CHANGELOG.md b/sdk/spring/spring-integration-azure-eventhubs/CHANGELOG.md index edb5e88a52c4..a57cc1805451 100644 --- a/sdk/spring/spring-integration-azure-eventhubs/CHANGELOG.md +++ b/sdk/spring/spring-integration-azure-eventhubs/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 5.20.0-beta.1 (Unreleased) +## 5.21.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 5.20.1 (2025-03-03) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5201-2025-03-03) for more details. + +## 5.20.0 (2025-02-12) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5200-2025-02-12) for more details. + ## 5.19.0 (2024-12-17) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5190-2024-12-17) for more details. diff --git a/sdk/spring/spring-integration-azure-eventhubs/README.md b/sdk/spring/spring-integration-azure-eventhubs/README.md index e69de29bb2d1..bbaecbaa3de8 100644 --- a/sdk/spring/spring-integration-azure-eventhubs/README.md +++ b/sdk/spring/spring-integration-azure-eventhubs/README.md @@ -0,0 +1 @@ +Please refer to [spring/README.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/README.md) for more details. diff --git a/sdk/spring/spring-integration-azure-eventhubs/pom.xml b/sdk/spring/spring-integration-azure-eventhubs/pom.xml index de0868cf5467..b705252b4ab3 100644 --- a/sdk/spring/spring-integration-azure-eventhubs/pom.xml +++ b/sdk/spring/spring-integration-azure-eventhubs/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-integration-azure-eventhubs - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Integration Azure Event Hubs Spring Integration Azure Event Hubs @@ -41,18 +41,18 @@ com.azure.spring spring-integration-azure-core - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure.spring spring-messaging-azure-eventhubs - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure azure-messaging-eventhubs-checkpointstore-blob - 1.20.2 + 1.20.5 + 6.2.2 test @@ -180,7 +180,7 @@ com.azure.spring spring-integration-azure-core - 5.20.0-beta.1 + 5.21.0-beta.1 test-jar test diff --git a/sdk/spring/spring-integration-azure-servicebus/CHANGELOG.md b/sdk/spring/spring-integration-azure-servicebus/CHANGELOG.md index e441b741757a..dee30c12d278 100644 --- a/sdk/spring/spring-integration-azure-servicebus/CHANGELOG.md +++ b/sdk/spring/spring-integration-azure-servicebus/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 5.20.0-beta.1 (Unreleased) +## 5.21.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 5.20.1 (2025-03-03) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5201-2025-03-03) for more details. + +## 5.20.0 (2025-02-12) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5200-2025-02-12) for more details. + ## 5.19.0 (2024-12-17) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5190-2024-12-17) for more details. diff --git a/sdk/spring/spring-integration-azure-servicebus/README.md b/sdk/spring/spring-integration-azure-servicebus/README.md index e69de29bb2d1..bbaecbaa3de8 100644 --- a/sdk/spring/spring-integration-azure-servicebus/README.md +++ b/sdk/spring/spring-integration-azure-servicebus/README.md @@ -0,0 +1 @@ +Please refer to [spring/README.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/README.md) for more details. diff --git a/sdk/spring/spring-integration-azure-servicebus/pom.xml b/sdk/spring/spring-integration-azure-servicebus/pom.xml index 4be32eae3857..20fec722514e 100644 --- a/sdk/spring/spring-integration-azure-servicebus/pom.xml +++ b/sdk/spring/spring-integration-azure-servicebus/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-integration-azure-servicebus - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Integration Azure Service Bus Spring Integration Azure Service Bus @@ -41,12 +41,12 @@ com.azure.spring spring-integration-azure-core - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure.spring spring-messaging-azure-servicebus - 5.20.0-beta.1 + 5.21.0-beta.1 + 1.5.8 test @@ -92,7 +92,7 @@ org.springframework spring-test - 6.2.1 + 6.2.2 test @@ -179,14 +179,14 @@ com.azure.spring spring-integration-azure-core - 5.20.0-beta.1 + 5.21.0-beta.1 test-jar test com.azure.spring spring-messaging-azure-servicebus - 5.20.0-beta.1 + 5.21.0-beta.1 test-jar test diff --git a/sdk/spring/spring-integration-azure-storage-queue/CHANGELOG.md b/sdk/spring/spring-integration-azure-storage-queue/CHANGELOG.md index e441b741757a..dee30c12d278 100644 --- a/sdk/spring/spring-integration-azure-storage-queue/CHANGELOG.md +++ b/sdk/spring/spring-integration-azure-storage-queue/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 5.20.0-beta.1 (Unreleased) +## 5.21.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 5.20.1 (2025-03-03) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5201-2025-03-03) for more details. + +## 5.20.0 (2025-02-12) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5200-2025-02-12) for more details. + ## 5.19.0 (2024-12-17) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5190-2024-12-17) for more details. diff --git a/sdk/spring/spring-integration-azure-storage-queue/README.md b/sdk/spring/spring-integration-azure-storage-queue/README.md index e69de29bb2d1..bbaecbaa3de8 100644 --- a/sdk/spring/spring-integration-azure-storage-queue/README.md +++ b/sdk/spring/spring-integration-azure-storage-queue/README.md @@ -0,0 +1 @@ +Please refer to [spring/README.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/README.md) for more details. diff --git a/sdk/spring/spring-integration-azure-storage-queue/pom.xml b/sdk/spring/spring-integration-azure-storage-queue/pom.xml index ef3185c10305..83e20d89a705 100644 --- a/sdk/spring/spring-integration-azure-storage-queue/pom.xml +++ b/sdk/spring/spring-integration-azure-storage-queue/pom.xml @@ -13,7 +13,7 @@ com.azure.spring spring-integration-azure-storage-queue - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Integration Azure Storage Queue Spring Integration Azure Storage Queue @@ -42,12 +42,12 @@ com.azure.spring spring-integration-azure-core - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure.spring spring-messaging-azure-storage-queue - 5.20.0-beta.1 + 5.21.0-beta.1 + 5.21.0-beta.1 Spring Messaging Azure Event Hubs Spring Messaging Azure Event Hubs @@ -41,25 +41,25 @@ com.azure.spring spring-messaging-azure - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure azure-messaging-eventhubs - 5.19.2 + 5.20.1 com.azure azure-messaging-eventhubs-checkpointstore-blob - 1.20.2 + 1.20.5 true org.springframework spring-tx - 6.2.1 + 6.2.2 true @@ -71,7 +71,7 @@ org.springframework.data spring-data-commons - 3.4.1 + 3.4.2 org.slf4j @@ -83,7 +83,7 @@ io.micrometer micrometer-core - 1.14.2 + 1.14.3 true @@ -97,7 +97,7 @@ org.springframework spring-test - 6.2.1 + 6.2.2 test @@ -129,7 +129,7 @@ io.projectreactor reactor-test - 3.7.1 + 3.7.2 test @@ -174,10 +174,10 @@ - io.micrometer:micrometer-core:[1.14.2] - org.springframework:spring-tx:[6.2.1] + io.micrometer:micrometer-core:[1.14.3] + org.springframework:spring-tx:[6.2.2] org.springframework.retry:spring-retry:[2.0.11] - org.springframework.data:spring-data-commons:[3.4.1] + org.springframework.data:spring-data-commons:[3.4.2] @@ -226,7 +226,7 @@ com.azure.spring spring-messaging-azure - 5.20.0-beta.1 + 5.21.0-beta.1 test-jar test diff --git a/sdk/spring/spring-messaging-azure-servicebus/CHANGELOG.md b/sdk/spring/spring-messaging-azure-servicebus/CHANGELOG.md index edb5e88a52c4..a57cc1805451 100644 --- a/sdk/spring/spring-messaging-azure-servicebus/CHANGELOG.md +++ b/sdk/spring/spring-messaging-azure-servicebus/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 5.20.0-beta.1 (Unreleased) +## 5.21.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 5.20.1 (2025-03-03) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5201-2025-03-03) for more details. + +## 5.20.0 (2025-02-12) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5200-2025-02-12) for more details. + ## 5.19.0 (2024-12-17) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5190-2024-12-17) for more details. diff --git a/sdk/spring/spring-messaging-azure-servicebus/README.md b/sdk/spring/spring-messaging-azure-servicebus/README.md index e69de29bb2d1..bbaecbaa3de8 100644 --- a/sdk/spring/spring-messaging-azure-servicebus/README.md +++ b/sdk/spring/spring-messaging-azure-servicebus/README.md @@ -0,0 +1 @@ +Please refer to [spring/README.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/README.md) for more details. diff --git a/sdk/spring/spring-messaging-azure-servicebus/pom.xml b/sdk/spring/spring-messaging-azure-servicebus/pom.xml index f26971732606..65706d7d2e83 100644 --- a/sdk/spring/spring-messaging-azure-servicebus/pom.xml +++ b/sdk/spring/spring-messaging-azure-servicebus/pom.xml @@ -13,7 +13,7 @@ com.azure.spring spring-messaging-azure-servicebus - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Messaging Azure Service Bus Spring Messaging Azure Service Bus @@ -42,17 +42,17 @@ com.azure.spring spring-messaging-azure - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure azure-messaging-servicebus - 7.17.8 + 7.17.9 org.springframework spring-tx - 6.2.1 + 6.2.2 true @@ -64,7 +64,7 @@ org.springframework.data spring-data-commons - 3.4.1 + 3.4.2 org.slf4j @@ -76,7 +76,7 @@ io.micrometer micrometer-core - 1.14.2 + 1.14.3 true @@ -114,7 +114,7 @@ com.azure azure-core-serializer-json-jackson - 1.5.4 + 1.5.8 test @@ -159,10 +159,10 @@ - io.micrometer:micrometer-core:[1.14.2] - org.springframework:spring-tx:[6.2.1] + io.micrometer:micrometer-core:[1.14.3] + org.springframework:spring-tx:[6.2.2] org.springframework.retry:spring-retry:[2.0.11] - org.springframework.data:spring-data-commons:[3.4.1] + org.springframework.data:spring-data-commons:[3.4.2] @@ -218,7 +218,7 @@ com.azure.spring spring-messaging-azure - 5.20.0-beta.1 + 5.21.0-beta.1 test-jar test diff --git a/sdk/spring/spring-messaging-azure-storage-queue/CHANGELOG.md b/sdk/spring/spring-messaging-azure-storage-queue/CHANGELOG.md index e441b741757a..dee30c12d278 100644 --- a/sdk/spring/spring-messaging-azure-storage-queue/CHANGELOG.md +++ b/sdk/spring/spring-messaging-azure-storage-queue/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 5.20.0-beta.1 (Unreleased) +## 5.21.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 5.20.1 (2025-03-03) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5201-2025-03-03) for more details. + +## 5.20.0 (2025-02-12) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5200-2025-02-12) for more details. + ## 5.19.0 (2024-12-17) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5190-2024-12-17) for more details. diff --git a/sdk/spring/spring-messaging-azure-storage-queue/README.md b/sdk/spring/spring-messaging-azure-storage-queue/README.md index e69de29bb2d1..bbaecbaa3de8 100644 --- a/sdk/spring/spring-messaging-azure-storage-queue/README.md +++ b/sdk/spring/spring-messaging-azure-storage-queue/README.md @@ -0,0 +1 @@ +Please refer to [spring/README.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/README.md) for more details. diff --git a/sdk/spring/spring-messaging-azure-storage-queue/pom.xml b/sdk/spring/spring-messaging-azure-storage-queue/pom.xml index e786290c49b2..c989973418ab 100644 --- a/sdk/spring/spring-messaging-azure-storage-queue/pom.xml +++ b/sdk/spring/spring-messaging-azure-storage-queue/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-messaging-azure-storage-queue - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Messaging Azure Storage Queue Spring Messaging Azure Storage Queue @@ -41,12 +41,12 @@ com.azure.spring spring-messaging-azure - 5.20.0-beta.1 + 5.21.0-beta.1 com.azure azure-storage-queue - 12.24.0 + 12.24.1 @@ -78,7 +78,7 @@ org.springframework.boot spring-boot-starter-test - 3.4.1 + 3.4.2 test @@ -90,7 +90,7 @@ com.azure azure-core-serializer-json-jackson - 1.5.4 + 1.5.8 test @@ -171,7 +171,7 @@ com.azure.spring spring-messaging-azure - 5.20.0-beta.1 + 5.21.0-beta.1 test-jar test diff --git a/sdk/spring/spring-messaging-azure/CHANGELOG.md b/sdk/spring/spring-messaging-azure/CHANGELOG.md index edb5e88a52c4..a57cc1805451 100644 --- a/sdk/spring/spring-messaging-azure/CHANGELOG.md +++ b/sdk/spring/spring-messaging-azure/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 5.20.0-beta.1 (Unreleased) +## 5.21.0-beta.1 (Unreleased) ### Features Added @@ -10,6 +10,14 @@ ### Other Changes +## 5.20.1 (2025-03-03) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5201-2025-03-03) for more details. + +## 5.20.0 (2025-02-12) + +Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5200-2025-02-12) for more details. + ## 5.19.0 (2024-12-17) Please refer to [spring/CHANGELOG.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/CHANGELOG.md#5190-2024-12-17) for more details. diff --git a/sdk/spring/spring-messaging-azure/README.md b/sdk/spring/spring-messaging-azure/README.md index e69de29bb2d1..bbaecbaa3de8 100644 --- a/sdk/spring/spring-messaging-azure/README.md +++ b/sdk/spring/spring-messaging-azure/README.md @@ -0,0 +1 @@ +Please refer to [spring/README.md](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/spring/README.md) for more details. diff --git a/sdk/spring/spring-messaging-azure/pom.xml b/sdk/spring/spring-messaging-azure/pom.xml index 70bf79fe676d..bd94e39e551a 100644 --- a/sdk/spring/spring-messaging-azure/pom.xml +++ b/sdk/spring/spring-messaging-azure/pom.xml @@ -12,7 +12,7 @@ com.azure.spring spring-messaging-azure - 5.20.0-beta.1 + 5.21.0-beta.1 Spring Messaging Azure Spring Messaging Azure @@ -41,17 +41,17 @@ com.azure.spring spring-cloud-azure-service - 5.20.0-beta.1 + 5.21.0-beta.1 org.springframework spring-messaging - 6.2.1 + 6.2.2 org.springframework spring-tx - 6.2.1 + 6.2.2 true @@ -63,7 +63,7 @@ org.springframework.data spring-data-commons - 3.4.1 + 3.4.2 org.slf4j @@ -75,7 +75,7 @@ io.micrometer micrometer-core - 1.14.2 + 1.14.3 true + 3.4.2 test @@ -159,10 +159,10 @@ - io.micrometer:micrometer-core:[1.14.2] - org.springframework.data:spring-data-commons:[3.4.1] - org.springframework:spring-messaging:[6.2.1] - org.springframework:spring-tx:[6.2.1] + io.micrometer:micrometer-core:[1.14.3] + org.springframework.data:spring-data-commons:[3.4.2] + org.springframework:spring-messaging:[6.2.2] + org.springframework:spring-tx:[6.2.2] org.springframework.retry:spring-retry:[2.0.11] diff --git a/sdk/spring/spring-messaging-azure/src/main/java/com/azure/spring/messaging/implementation/annotation/AzureListenerAnnotationBeanPostProcessorAdapter.java b/sdk/spring/spring-messaging-azure/src/main/java/com/azure/spring/messaging/implementation/annotation/AzureListenerAnnotationBeanPostProcessorAdapter.java index 713c4bf4eaed..2ccd3f16deff 100644 --- a/sdk/spring/spring-messaging-azure/src/main/java/com/azure/spring/messaging/implementation/annotation/AzureListenerAnnotationBeanPostProcessorAdapter.java +++ b/sdk/spring/spring-messaging-azure/src/main/java/com/azure/spring/messaging/implementation/annotation/AzureListenerAnnotationBeanPostProcessorAdapter.java @@ -45,7 +45,7 @@ /** * Bean post-processor that registers methods annotated with {@link T} - * to be invoked by a Azure message listener container created under the cover + * to be invoked by an Azure message listener container created under the cover * by a {@link MessageListenerContainerFactory} * according to the attributes of the annotation. * diff --git a/sdk/spring/spring-reference.yml b/sdk/spring/spring-reference.yml index 584da5a4706b..5c6974cdd323 100644 --- a/sdk/spring/spring-reference.yml +++ b/sdk/spring/spring-reference.yml @@ -8,11 +8,11 @@ artifacts: - artifactId: spring-cloud-azure-dependencies groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: Bill of Materials (BOM) for Spring Cloud Azure support. type: spring links: - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/boms/spring-cloud-azure-dependencies + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/boms/spring-cloud-azure-dependencies msdocs: https://docs.microsoft.com/azure/developer/java/spring-framework/spring-cloud-azure#bill-of-material-bom repopath: https://search.maven.org/artifact/com.azure.spring/spring-cloud-azure-dependencies dependencyPattern: @@ -36,7 +36,7 @@ springProperties: starter: false - compatibilityRange: "[2.5.0,3.3.6]" + compatibilityRange: "[2.5.0,3.4.2]" mappings: - compatibilityRange: "[2.5.0,2.5.15]" groupId: com.azure.spring @@ -53,23 +53,23 @@ - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-cloud-azure-dependencies - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-dependencies - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-dependencies - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-cloud-azure-dependencies - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-cloud-azure-dependencies - version: 5.19.0 + version: 5.20.1 - name: Active Directory content: - name: Active Directory @@ -80,7 +80,7 @@ artifacts: - artifactId: spring-cloud-azure-starter-active-directory groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: |- Microsoft's Spring Boot Starter provides the most optimal way to connect your Web application to an Azure Active Directory (AAD for short) tenant and protect resource @@ -88,14 +88,14 @@ servers. type: spring links: - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-cloud-azure-starter-active-directory + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-cloud-azure-starter-active-directory msdocs: https://docs.microsoft.com/azure/developer/java/spring-framework/configure-spring-boot-starter-java-app-with-azure-active-directory repopath: https://search.maven.org/artifact/com.azure.spring/spring-cloud-azure-starter-active-directory - sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.19.0/aad/spring-cloud-azure-starter-active-directory/ + sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.20.1/aad/spring-cloud-azure-starter-active-directory/ springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[2.5.0,3.3.6]" + compatibilityRange: "[2.5.0,3.4.2]" mappings: - compatibilityRange: "[2.5.0,2.5.15]" groupId: com.azure.spring @@ -112,23 +112,23 @@ - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-active-directory - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-active-directory - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-active-directory - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-active-directory - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-active-directory - version: 5.19.0 + version: 5.20.1 - name: Active Directory B2C content: - name: Active Directory B2C @@ -140,17 +140,17 @@ artifacts: - artifactId: spring-cloud-azure-starter-active-directory-b2c groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 type: spring links: - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-cloud-azure-starter-active-directory-b2c + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-cloud-azure-starter-active-directory-b2c msdocs: https://docs.microsoft.com/azure/developer/java/spring-framework/configure-spring-boot-starter-java-app-with-azure-active-directory-b2c-oidc repopath: https://search.maven.org/artifact/com.azure.spring/spring-cloud-azure-starter-active-directory-b2c - sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.19.0/aad/spring-cloud-azure-starter-active-directory-b2c/ + sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.20.1/aad/spring-cloud-azure-starter-active-directory-b2c/ springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[2.5.0,3.3.6]" + compatibilityRange: "[2.5.0,3.4.2]" mappings: - compatibilityRange: "[2.5.0,2.5.15]" groupId: com.azure.spring @@ -167,23 +167,23 @@ - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-active-directory-b2c - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-active-directory-b2c - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-active-directory-b2c - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-active-directory-b2c - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-active-directory-b2c - version: 5.19.0 + version: 5.20.1 - name: App Configuration content: - name: App Configuration @@ -198,20 +198,20 @@ artifacts: - artifactId: spring-cloud-azure-starter-appconfiguration groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: |- Microsoft's Spring Boot Starter helps developers to finish the auto-configuration of Azure App Configuration. type: spring links: - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-cloud-azure-starter-appconfiguration + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-cloud-azure-starter-appconfiguration msdocs: https://docs.microsoft.com/azure/developer/java/spring-framework/spring-cloud-azure#auto-configure-azure-sdk-clients repopath: https://search.maven.org/artifact/com.azure.spring/spring-cloud-azure-starter-appconfiguration - sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.19.0/appconfiguration/spring-cloud-azure-starter-appconfiguration/ + sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.20.1/appconfiguration/spring-cloud-azure-starter-appconfiguration/ springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[2.5.0,3.3.6]" + compatibilityRange: "[2.5.0,3.4.2]" mappings: - compatibilityRange: "[2.5.0,2.5.15]" groupId: com.azure.spring @@ -228,37 +228,37 @@ - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-appconfiguration - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-appconfiguration - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-appconfiguration - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-appconfiguration - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-appconfiguration - version: 5.19.0 + version: 5.20.1 - artifactId: spring-cloud-azure-starter-appconfiguration-config groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: Microsoft's Spring Boot Starter helps developers to load properties and manage features from Azure App Configuration service for Spring Application. type: spring links: - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-cloud-azure-starter-appconfiguration-config + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-cloud-azure-starter-appconfiguration-config repopath: https://search.maven.org/artifact/com.azure.spring/spring-cloud-azure-starter-appconfiguration-config - sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.19.0/appconfiguration/spring-cloud-azure-starter-appconfiguration-config/ + sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.20.1/appconfiguration/spring-cloud-azure-starter-appconfiguration-config/ springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[2.5.0,3.3.6]" + compatibilityRange: "[2.5.0,3.4.2]" mappings: - compatibilityRange: "[2.5.0,2.5.15]" groupId: com.azure.spring @@ -275,23 +275,23 @@ - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-appconfiguration-config - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-appconfiguration-config - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-appconfiguration-config - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-appconfiguration-config - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-appconfiguration-config - version: 5.19.0 + version: 5.20.1 - name: Cosmos DB content: - name: Spring Data Cosmos @@ -307,21 +307,21 @@ artifacts: - artifactId: spring-cloud-azure-starter-data-cosmos groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: |- Microsoft's Spring Boot Starter helps developers to finish the auto-configuration of Spring Data Azure Cosmos DB, which enables developers to easily integrate with Azure Cosmos DB SQL API using Spring Data. type: spring links: - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-cloud-azure-starter-data-cosmos + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-cloud-azure-starter-data-cosmos msdocs: https://docs.microsoft.com/azure/developer/java/spring-framework/configure-spring-boot-starter-java-app-with-cosmos-db repopath: https://search.maven.org/artifact/com.azure.spring/spring-cloud-azure-starter-data-cosmos - sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.19.0/cosmos/spring-cloud-azure-starter-data-cosmos/ + sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.20.1/cosmos/spring-cloud-azure-starter-data-cosmos/ springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[2.5.0,3.3.6]" + compatibilityRange: "[2.5.0,3.4.2]" mappings: - compatibilityRange: "[2.5.0,2.5.15]" groupId: com.azure.spring @@ -338,23 +338,23 @@ - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-data-cosmos - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-data-cosmos - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-data-cosmos - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-data-cosmos - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-data-cosmos - version: 5.19.0 + version: 5.20.1 - name: Cosmos DB description: |- Azure Cosmos DB is a fully managed NoSQL database for modern app development. @@ -365,20 +365,20 @@ artifacts: - artifactId: spring-cloud-azure-starter-cosmos groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: |- Microsoft's Spring Boot Starter helps developers to finish the auto-configuration of Azure Cosmos DB, which enables developers to easily integrate with Azure Cosmos DB SQL API. type: spring links: - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-cloud-azure-starter-cosmos + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-cloud-azure-starter-cosmos msdocs: https://docs.microsoft.com/azure/developer/java/spring-framework/spring-cloud-azure#auto-configure-azure-sdk-clients repopath: https://search.maven.org/artifact/com.azure.spring/spring-cloud-azure-starter-cosmos - sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.19.0/cosmos/spring-cloud-azure-starter-cosmos/ + sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.20.1/cosmos/spring-cloud-azure-starter-cosmos/ springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[2.5.0,3.3.6]" + compatibilityRange: "[2.5.0,3.4.2]" mappings: - compatibilityRange: "[2.5.0,2.5.15]" groupId: com.azure.spring @@ -395,23 +395,23 @@ - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-cosmos - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-cosmos - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-cosmos - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-cosmos - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-cosmos - version: 5.19.0 + version: 5.20.1 - name: Key Vault content: - name: Key Vault @@ -421,20 +421,20 @@ artifacts: - artifactId: spring-cloud-azure-starter-keyvault groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: |- Microsoft's Spring Boot Starter helps developers to finish the auto-configuration of Azure Key Vault. type: spring links: - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-cloud-azure-starter-keyvault + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-cloud-azure-starter-keyvault msdocs: https://learn.microsoft.com/azure/key-vault/ repopath: https://search.maven.org/artifact/com.azure.spring/spring-cloud-azure-starter-keyvault - sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.19.0/keyvault/spring-cloud-azure-starter-keyvault/ + sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.20.1/keyvault/spring-cloud-azure-starter-keyvault/ springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[2.5.0,3.3.6]" + compatibilityRange: "[2.5.0,3.4.2]" mappings: - compatibilityRange: "[2.5.0,2.5.15]" groupId: com.azure.spring @@ -451,23 +451,23 @@ - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-keyvault - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-keyvault - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-keyvault - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-keyvault - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-keyvault - version: 5.19.0 + version: 5.20.1 - name: Key Vault - Certificates description: |- Azure Key Vault enables Microsoft Azure applications and users to store and use certificates, which are @@ -479,19 +479,19 @@ artifacts: - artifactId: spring-cloud-azure-starter-keyvault-certificates groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: |- Microsoft's Spring Boot Starter helps developers to finish the auto-configuration of Azure Key Vault Certificates. type: spring links: - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-cloud-azure-starter-keyvault-certificates + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-cloud-azure-starter-keyvault-certificates msdocs: https://docs.microsoft.com/azure/developer/java/spring-framework/configure-spring-boot-starter-java-app-with-azure-key-vault-certificates repopath: https://search.maven.org/artifact/com.azure.spring/spring-cloud-azure-starter-keyvault-certificates springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[2.5.0,3.3.6]" + compatibilityRange: "[2.5.0,3.4.2]" mappings: - compatibilityRange: "[2.5.0,2.5.15]" groupId: com.azure.spring @@ -508,23 +508,23 @@ - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-keyvault-certificates - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-keyvault-certificates - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-keyvault-certificates - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-keyvault-certificates - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-keyvault-certificates - version: 5.19.0 + version: 5.20.1 - artifactId: azure-security-keyvault-jca groupId: com.azure versionGA: 2.10.0 @@ -548,7 +548,7 @@ artifacts: - artifactId: spring-cloud-azure-starter-keyvault-secrets groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: |- Microsoft's Spring Boot Starter helps developers to finish the auto-configuration of Azure Key Vault Secrets, and adds Azure Key Vault as one of Spring PropertySource. @@ -556,14 +556,14 @@ externalized configuration property. type: spring links: - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-cloud-azure-starter-keyvault-secrets + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-cloud-azure-starter-keyvault-secrets msdocs: https://docs.microsoft.com/azure/developer/java/spring-framework/configure-spring-boot-starter-java-app-with-azure-key-vault repopath: https://search.maven.org/artifact/com.azure.spring/spring-cloud-azure-starter-keyvault-secrets - sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.19.0/keyvault/spring-cloud-azure-starter-keyvault-secrets/ + sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.20.1/keyvault/spring-cloud-azure-starter-keyvault-secrets/ springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[2.5.0,3.3.6]" + compatibilityRange: "[2.5.0,3.4.2]" mappings: - compatibilityRange: "[2.5.0,2.5.15]" groupId: com.azure.spring @@ -580,23 +580,23 @@ - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-keyvault-secrets - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-keyvault-secrets - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-keyvault-secrets - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-keyvault-secrets - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-keyvault-secrets - version: 5.19.0 + version: 5.20.1 - name: Storage content: - name: Storage @@ -605,21 +605,21 @@ artifacts: - artifactId: spring-cloud-azure-starter-storage groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: |- Microsoft's Spring Boot Starter helps developers to finish the auto-configuration of Azure Storage, and implements Spring Resource abstraction for Azure Storage service which allows you to interact with Storage Account using Spring programming model. type: spring links: - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-cloud-azure-starter-storage + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-cloud-azure-starter-storage msdocs: https://docs.microsoft.com/azure/storage/ repopath: https://search.maven.org/artifact/com.azure.spring/spring-cloud-azure-starter-storage - sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.19.0/storage/spring-cloud-azure-starter-storage/ + sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.20.1/storage/spring-cloud-azure-starter-storage/ springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[2.5.0,3.3.6]" + compatibilityRange: "[2.5.0,3.4.2]" mappings: - compatibilityRange: "[2.5.0,2.5.15]" groupId: com.azure.spring @@ -636,23 +636,23 @@ - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-storage - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-storage - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-storage - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-storage - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-storage - version: 5.19.0 + version: 5.20.1 - name: Storage - Blobs description: |- Azure Blob Storage is Microsoft's object storage solution for the cloud. Blob Storage @@ -666,21 +666,21 @@ artifacts: - artifactId: spring-cloud-azure-starter-storage-blob groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: |- Microsoft's Spring Boot Starter helps developers to finish the auto-configuration of Azure Storage Blob, and implements Spring Resource abstraction for Azure Storage service which allows you to interact with Storage Blob using Spring programming model. type: spring links: - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-cloud-azure-starter-storage-blob + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-cloud-azure-starter-storage-blob msdocs: https://docs.microsoft.com/azure/developer/java/spring-framework/configure-spring-boot-starter-java-app-with-azure-storage repopath: https://search.maven.org/artifact/com.azure.spring/spring-cloud-azure-starter-storage-blob - sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.19.0/storage/spring-cloud-azure-starter-storage-blob/ + sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.20.1/storage/spring-cloud-azure-starter-storage-blob/ springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[2.5.0,3.3.6]" + compatibilityRange: "[2.5.0,3.4.2]" mappings: - compatibilityRange: "[2.5.0,2.5.15]" groupId: com.azure.spring @@ -697,23 +697,23 @@ - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-storage-blob - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-storage-blob - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-storage-blob - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-storage-blob - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-storage-blob - version: 5.19.0 + version: 5.20.1 - name: Storage - Files Shares description: |- Azure File Share storage offers fully managed file shares in the cloud that are @@ -728,21 +728,21 @@ artifacts: - artifactId: spring-cloud-azure-starter-storage-file-share groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: |- Microsoft's Spring Boot Starter helps developers to finish the auto-configuration of Azure Storage File Share, and implements Spring Resource abstraction for Azure Storage service which allows you to interact with Storage File Share using Spring programming model. type: spring links: - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-cloud-azure-starter-storage-file-share + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-cloud-azure-starter-storage-file-share msdocs: https://docs.microsoft.com/azure/developer/java/spring-framework/spring-cloud-azure#resource-handling repopath: https://search.maven.org/artifact/com.azure.spring/spring-cloud-azure-starter-storage-file-share - sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.19.0/storage/spring-cloud-azure-starter-storage-file-share/ + sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.20.1/storage/spring-cloud-azure-starter-storage-file-share/ springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[2.5.0,3.3.6]" + compatibilityRange: "[2.5.0,3.4.2]" mappings: - compatibilityRange: "[2.5.0,2.5.15]" groupId: com.azure.spring @@ -759,23 +759,23 @@ - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-storage-file-share - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-storage-file-share - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-storage-file-share - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-storage-file-share - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-storage-file-share - version: 5.19.0 + version: 5.20.1 - name: Storage - Queues description: |- Azure Queue Storage is a service for storing large numbers of messages. You access @@ -790,20 +790,20 @@ artifacts: - artifactId: spring-cloud-azure-starter-storage-queue groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: |- Microsoft's Spring Boot Starter helps developers to finish the auto-configuration of Azure Storage Queue. type: spring links: - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-cloud-azure-starter-storage-queue + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-cloud-azure-starter-storage-queue msdocs: https://docs.microsoft.com/azure/developer/java/spring-framework/spring-cloud-azure#auto-configure-azure-sdk-clients repopath: https://search.maven.org/artifact/com.azure.spring/spring-cloud-azure-starter-storage-queue - sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.19.0/storage/spring-cloud-azure-starter-storage-queue/ + sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.20.1/storage/spring-cloud-azure-starter-storage-queue/ springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[2.5.0,3.3.6]" + compatibilityRange: "[2.5.0,3.4.2]" mappings: - compatibilityRange: "[2.5.0,2.5.15]" groupId: com.azure.spring @@ -820,39 +820,39 @@ - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-storage-queue - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-storage-queue - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-storage-queue - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-storage-queue - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-storage-queue - version: 5.19.0 + version: 5.20.1 - artifactId: spring-cloud-azure-starter-integration-storage-queue groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: |- Microsoft's Spring Boot Starter helps developers to finish the auto-configuration of Spring Integration Azure Storage Queue. type: spring links: - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-cloud-azure-starter-integration-storage-queue + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-cloud-azure-starter-integration-storage-queue msdocs: https://docs.microsoft.com/azure/developer/java/spring-framework/configure-spring-boot-starter-java-app-with-azure-service-bus repopath: https://search.maven.org/artifact/com.azure.spring/spring-cloud-azure-starter-integration-storage-queue - sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.19.0/storage/spring-cloud-azure-starter-integration-storage-queue/ + sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.20.1/storage/spring-cloud-azure-starter-integration-storage-queue/ springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[2.5.0,3.3.6]" + compatibilityRange: "[2.5.0,3.4.2]" mappings: - compatibilityRange: "[2.5.0,2.5.15]" groupId: com.azure.spring @@ -869,40 +869,40 @@ - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-integration-storage-queue - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-integration-storage-queue - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-integration-storage-queue - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-integration-storage-queue - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-integration-storage-queue - version: 5.19.0 + version: 5.20.1 - artifactId: spring-integration-azure-storage-queue groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: |- Microsoft's Spring Integration extension for Azure Storage Queue. Spring Integration extends the Spring programming modoel to support well-known Enterprise Integration Patterns. type: spring links: - javadoc: https://azuresdkdocs.blob.core.windows.net/$web/java/spring-integration-azure-storage-queue/5.19.0/index.html - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-integration-azure-storage-queue + javadoc: https://azuresdkdocs.blob.core.windows.net/$web/java/spring-integration-azure-storage-queue/5.20.1/index.html + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-integration-azure-storage-queue msdocs: https://docs.microsoft.com/azure/developer/java/spring-framework/spring-cloud-azure#spring-integration-support repopath: https://search.maven.org/artifact/com.azure.spring/spring-integration-azure-storage-queue - sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.19.0/storage/spring-integration-azure-storage-queue/ + sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.20.1/storage/spring-integration-azure-storage-queue/ springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[2.5.0,3.3.6]" + compatibilityRange: "[2.5.0,3.4.2]" mappings: - compatibilityRange: "[2.5.0,2.5.15]" groupId: com.azure.spring @@ -919,23 +919,23 @@ - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-integration-azure-storage-queue - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-integration-azure-storage-queue - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-integration-azure-storage-queue - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-integration-azure-storage-queue - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-integration-azure-storage-queue - version: 5.19.0 + version: 5.20.1 - name: Service Bus content: - name: Service Bus @@ -951,20 +951,20 @@ artifacts: - artifactId: spring-cloud-azure-starter-servicebus groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: |- Microsoft's Spring Boot Starter helps developers to finish the auto-configuration of Azure Service Bus. type: spring links: - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-cloud-azure-starter-servicebus + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-cloud-azure-starter-servicebus msdocs: https://docs.microsoft.com/azure/developer/java/spring-framework/spring-cloud-azure#auto-configure-azure-sdk-clients repopath: https://search.maven.org/artifact/com.azure.spring/spring-cloud-azure-starter-servicebus - sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.19.0/servicebus/spring-cloud-azure-starter-servicebus/ + sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.20.1/servicebus/spring-cloud-azure-starter-servicebus/ springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[2.5.0,3.3.6]" + compatibilityRange: "[2.5.0,3.4.2]" mappings: - compatibilityRange: "[2.5.0,2.5.15]" groupId: com.azure.spring @@ -981,39 +981,39 @@ - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-servicebus - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-servicebus - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-servicebus - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-servicebus - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-servicebus - version: 5.19.0 + version: 5.20.1 - artifactId: spring-cloud-azure-starter-integration-servicebus groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: |- Microsoft's Spring Boot Starter helps developers to finish the auto-configuration of Spring Integration Azure Service Bus. type: spring links: - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-cloud-azure-starter-integration-servicebus + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-cloud-azure-starter-integration-servicebus msdocs: https://docs.microsoft.com/azure/developer/java/spring-framework/configure-spring-boot-starter-java-app-with-azure-service-bus repopath: https://search.maven.org/artifact/com.azure.spring/spring-cloud-azure-starter-integration-servicebus - sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.19.0/servicebus/spring-cloud-azure-starter-integration-servicebus/ + sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.20.1/servicebus/spring-cloud-azure-starter-integration-servicebus/ springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[2.5.0,3.3.6]" + compatibilityRange: "[2.5.0,3.4.2]" mappings: - compatibilityRange: "[2.5.0,2.5.15]" groupId: com.azure.spring @@ -1030,40 +1030,40 @@ - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-integration-servicebus - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-integration-servicebus - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-integration-servicebus - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-integration-servicebus - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-integration-servicebus - version: 5.19.0 + version: 5.20.1 - artifactId: spring-integration-azure-servicebus groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: |- Microsoft's Spring Integration extension for Azure Service Bus. Spring Integration extends the Spring programming modoel to support well-known Enterprise Integration Patterns. type: spring links: - javadoc: https://azuresdkdocs.blob.core.windows.net/$web/java/spring-integration-azure-servicebus/5.19.0/index.html - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-integration-azure-servicebus + javadoc: https://azuresdkdocs.blob.core.windows.net/$web/java/spring-integration-azure-servicebus/5.20.1/index.html + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-integration-azure-servicebus msdocs: https://docs.microsoft.com/azure/developer/java/spring-framework/spring-cloud-azure#spring-integration-support repopath: https://search.maven.org/artifact/com.azure.spring/spring-integration-azure-servicebus - sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.19.0/servicebus/spring-integration-azure-servicebus/ + sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.20.1/servicebus/spring-integration-azure-servicebus/ springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[2.5.0,3.3.6]" + compatibilityRange: "[2.5.0,3.4.2]" mappings: - compatibilityRange: "[2.5.0,2.5.15]" groupId: com.azure.spring @@ -1080,41 +1080,41 @@ - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-integration-azure-servicebus - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-integration-azure-servicebus - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-integration-azure-servicebus - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-integration-azure-servicebus - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-integration-azure-servicebus - version: 5.19.0 + version: 5.20.1 - artifactId: spring-cloud-azure-stream-binder-servicebus groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: |- Microsoft's Spring Cloud Stream Binder provides Spring Cloud Stream Binder for Azure Service Bus which allows you to build message-driven microservice using Spring Cloud Stream based on Azure Service Bus. type: spring links: - javadoc: https://azuresdkdocs.blob.core.windows.net/$web/java/spring-cloud-azure-stream-binder-servicebus/5.19.0/index.html - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-cloud-azure-stream-binder-servicebus + javadoc: https://azuresdkdocs.blob.core.windows.net/$web/java/spring-cloud-azure-stream-binder-servicebus/5.20.1/index.html + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-cloud-azure-stream-binder-servicebus msdocs: https://docs.microsoft.com/azure/developer/java/spring-framework/configure-spring-cloud-stream-binder-java-app-with-service-bus repopath: https://search.maven.org/artifact/com.azure.spring/spring-cloud-azure-stream-binder-servicebus - sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.19.0/servicebus/spring-cloud-azure-stream-binder-servicebus/ + sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.20.1/servicebus/spring-cloud-azure-stream-binder-servicebus/ springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[2.5.0,3.3.6]" + compatibilityRange: "[2.5.0,3.4.2]" mappings: - compatibilityRange: "[2.5.0,2.5.15]" groupId: com.azure.spring @@ -1131,23 +1131,23 @@ - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-cloud-azure-stream-binder-servicebus - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-stream-binder-servicebus - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-stream-binder-servicebus - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-cloud-azure-stream-binder-servicebus - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-cloud-azure-stream-binder-servicebus - version: 5.19.0 + version: 5.20.1 - name: Service Bus JMS description: |- Microsoft Azure Service Bus is a fully managed enterprise integration message broker. @@ -1158,20 +1158,20 @@ artifacts: - artifactId: spring-cloud-azure-starter-servicebus-jms groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: |- Microsoft's Spring Boot Starter helps developers to finish the auto-configuration of Spring JMS with Azure Service Bus Queue and Topic. type: spring links: - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-cloud-azure-starter-servicebus-jms + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-cloud-azure-starter-servicebus-jms msdocs: https://docs.microsoft.com/azure/developer/java/spring-framework/configure-spring-boot-starter-java-app-with-azure-service-bus repopath: https://search.maven.org/artifact/com.azure.spring/spring-cloud-azure-starter-servicebus-jms - sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.19.0/servicebus/spring-cloud-azure-starter-servicebus-jms/ + sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.20.1/servicebus/spring-cloud-azure-starter-servicebus-jms/ springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[2.5.0,3.3.6]" + compatibilityRange: "[2.5.0,3.4.2]" mappings: - compatibilityRange: "[2.5.0,2.5.15]" groupId: com.azure.spring @@ -1188,23 +1188,23 @@ - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-servicebus-jms - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-servicebus-jms - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-servicebus-jms - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-servicebus-jms - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-servicebus-jms - version: 5.19.0 + version: 5.20.1 - name: Event Grid content: - name: Event Grid @@ -1226,20 +1226,20 @@ artifacts: - artifactId: spring-cloud-azure-starter-eventgrid groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: |- Microsoft's Spring Boot Starter helps developers to finish the auto-configuration of Azure Event Grid. type: spring links: - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-cloud-azure-starter-eventgrid + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-cloud-azure-starter-eventgrid msdocs: https://learn.microsoft.com/azure/developer/java/spring-framework/configure-spring-boot-initializer-java-app-with-event-grid repopath: https://search.maven.org/artifact/com.azure.spring/spring-cloud-azure-starter-eventgrid - sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.19.0/eventgrid/spring-cloud-azure-starter-eventgrid/ + sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.20.1/eventgrid/spring-cloud-azure-starter-eventgrid/ springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[2.5.0,3.3.6]" + compatibilityRange: "[2.5.0,3.4.2]" mappings: - compatibilityRange: "[2.5.0,2.5.15]" groupId: com.azure.spring @@ -1256,23 +1256,23 @@ - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-eventgrid - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-eventgrid - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-eventgrid - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-eventgrid - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-eventgrid - version: 5.19.0 + version: 5.20.1 - name: Event Hubs content: - name: Event Hubs @@ -1288,20 +1288,20 @@ artifacts: - artifactId: spring-cloud-azure-starter-eventhubs groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: |- Microsoft's Spring Boot Starter helps developers to finish the auto-configuration of Azure Event Hubs. type: spring links: - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-cloud-azure-starter-eventhubs + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-cloud-azure-starter-eventhubs msdocs: https://docs.microsoft.com/azure/developer/java/spring-framework/spring-cloud-azure#auto-configure-azure-sdk-clients repopath: https://search.maven.org/artifact/com.azure.spring/spring-cloud-azure-starter-eventhubs - sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.19.0/eventhubs/spring-cloud-azure-starter-eventhubs/ + sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.20.1/eventhubs/spring-cloud-azure-starter-eventhubs/ springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[2.5.0,3.3.6]" + compatibilityRange: "[2.5.0,3.4.2]" mappings: - compatibilityRange: "[2.5.0,2.5.15]" groupId: com.azure.spring @@ -1318,39 +1318,39 @@ - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-eventhubs - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-eventhubs - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-eventhubs - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-eventhubs - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-eventhubs - version: 5.19.0 + version: 5.20.1 - artifactId: spring-cloud-azure-starter-integration-eventhubs groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: |- Microsoft's Spring Boot Starter helps developers to finish the auto-configuration of Spring Integration Azure Event Hubs. type: spring links: - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-cloud-azure-starter-integration-eventhubs + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-cloud-azure-starter-integration-eventhubs msdocs: https://docs.microsoft.com/azure/developer/java/spring-framework/configure-spring-boot-starter-java-app-with-azure-service-bus repopath: https://search.maven.org/artifact/com.azure.spring/spring-cloud-azure-starter-integration-eventhubs - sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.19.0/eventhubs/spring-cloud-azure-starter-integration-eventhubs/ + sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.20.1/eventhubs/spring-cloud-azure-starter-integration-eventhubs/ springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[2.5.0,3.3.6]" + compatibilityRange: "[2.5.0,3.4.2]" mappings: - compatibilityRange: "[2.5.0,2.5.15]" groupId: com.azure.spring @@ -1367,40 +1367,40 @@ - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-integration-eventhubs - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-integration-eventhubs - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-integration-eventhubs - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-integration-eventhubs - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-integration-eventhubs - version: 5.19.0 + version: 5.20.1 - artifactId: spring-integration-azure-eventhubs groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: |- Microsoft's Spring Integration extension for Azure Event Hubs. Spring Integration extends the Spring programming modoel to support well-known Enterprise Integration Patterns. type: spring links: - javadoc: https://azuresdkdocs.blob.core.windows.net/$web/java/spring-integration-azure-eventhubs/5.19.0/index.html - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-integration-azure-eventhubs + javadoc: https://azuresdkdocs.blob.core.windows.net/$web/java/spring-integration-azure-eventhubs/5.20.1/index.html + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-integration-azure-eventhubs msdocs: https://docs.microsoft.com/azure/developer/java/spring-framework/spring-cloud-azure#spring-integration-support repopath: https://search.maven.org/artifact/com.azure.spring/spring-integration-azure-eventhubs - sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.19.0/eventhubs/spring-integration-azure-eventhubs/ + sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.20.1/eventhubs/spring-integration-azure-eventhubs/ springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[2.5.0,3.3.6]" + compatibilityRange: "[2.5.0,3.4.2]" mappings: - compatibilityRange: "[2.5.0,2.5.15]" groupId: com.azure.spring @@ -1417,41 +1417,41 @@ - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-integration-azure-eventhubs - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-integration-azure-eventhubs - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-integration-azure-eventhubs - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-integration-azure-eventhubs - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-integration-azure-eventhubs - version: 5.19.0 + version: 5.20.1 - artifactId: spring-cloud-azure-stream-binder-eventhubs groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: |- Microsoft's Spring Cloud Stream Binder provides Spring Cloud Stream Binder for Azure Event Hubs which allows you to build message-driven microservice using Spring Cloud Stream based on Azure Event Hubs. type: spring links: - javadoc: https://azuresdkdocs.blob.core.windows.net/$web/java/spring-cloud-azure-stream-binder-eventhubs/5.19.0/index.html - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-cloud-azure-stream-binder-eventhubs + javadoc: https://azuresdkdocs.blob.core.windows.net/$web/java/spring-cloud-azure-stream-binder-eventhubs/5.20.1/index.html + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-cloud-azure-stream-binder-eventhubs msdocs: https://docs.microsoft.com/azure/developer/java/spring-framework/spring-cloud-azure#spring-cloud-stream-binder-for-azure-event-hubs repopath: https://search.maven.org/artifact/com.azure.spring/spring-cloud-azure-stream-binder-eventhubs - sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.19.0/eventhubs/spring-cloud-azure-stream-binder-eventhubs/ + sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.20.1/eventhubs/spring-cloud-azure-stream-binder-eventhubs/ springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[2.5.0,3.3.6]" + compatibilityRange: "[2.5.0,3.4.2]" mappings: - compatibilityRange: "[2.5.0,2.5.15]" groupId: com.azure.spring @@ -1468,23 +1468,23 @@ - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-cloud-azure-stream-binder-eventhubs - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-stream-binder-eventhubs - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-stream-binder-eventhubs - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-cloud-azure-stream-binder-eventhubs - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-cloud-azure-stream-binder-eventhubs - version: 5.19.0 + version: 5.20.1 - name: MySQL content: - name: Database for MySQL @@ -1496,20 +1496,20 @@ artifacts: - artifactId: spring-cloud-azure-starter-jdbc-mysql groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: |- Microsoft's Spring Boot Starter helps developers to finish the auto-configuration of Azure Database for MySQL. type: spring links: - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-cloud-azure-starter-jdbc-mysql + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-cloud-azure-starter-jdbc-mysql msdocs: https://docs.microsoft.com/azure/developer/java/spring-framework/spring-cloud-azure#auto-configure-azure-sdk-clients repopath: https://search.maven.org/artifact/com.azure.spring/spring-cloud-azure-starter-jdbc-mysql - sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.19.0/mysql/spring-cloud-azure-starter-jdbc-mysql/ + sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.20.1/mysql/spring-cloud-azure-starter-jdbc-mysql/ springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[2.5.0,3.3.6]" + compatibilityRange: "[2.5.0,3.4.2]" mappings: - compatibilityRange: "[2.5.0,2.5.15]" groupId: com.azure.spring @@ -1526,23 +1526,23 @@ - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-jdbc-mysql - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-jdbc-mysql - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-jdbc-mysql - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-jdbc-mysql - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-jdbc-mysql - version: 5.19.0 + version: 5.20.1 - name: PostgreSQL content: - name: Database for PostgreSQL @@ -1554,20 +1554,20 @@ artifacts: - artifactId: spring-cloud-azure-starter-jdbc-postgresql groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: |- Microsoft's Spring Boot Starter helps developers to finish the auto-configuration of Azure Database for PostgreSQL. type: spring links: - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-cloud-azure-starter-jdbc-postgresql + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-cloud-azure-starter-jdbc-postgresql msdocs: https://docs.microsoft.com/azure/developer/java/spring-framework/spring-cloud-azure#auto-configure-azure-sdk-clients repopath: https://search.maven.org/artifact/com.azure.spring/spring-cloud-azure-starter-jdbc-postgresql - sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.19.0/postgresql/spring-cloud-azure-starter-jdbc-postgresql/ + sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.20.1/postgresql/spring-cloud-azure-starter-jdbc-postgresql/ springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[2.5.0,3.3.6]" + compatibilityRange: "[2.5.0,3.4.2]" mappings: - compatibilityRange: "[2.5.0,2.5.15]" groupId: com.azure.spring @@ -1584,23 +1584,23 @@ - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-jdbc-postgresql - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-jdbc-postgresql - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-jdbc-postgresql - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-jdbc-postgresql - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-jdbc-postgresql - version: 5.19.0 + version: 5.20.1 - name: Redis content: - name: Azure Cache for Redis @@ -1615,41 +1615,41 @@ artifacts: - artifactId: spring-cloud-azure-starter-data-redis-lettuce groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: |- Microsoft's Spring Boot Starter helps developers to finish the auto-configuration of Azure Cache for Redis. type: spring links: - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-cloud-azure-starter-data-redis-lettuce + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-cloud-azure-starter-data-redis-lettuce msdocs: https://learn.microsoft.com/azure/developer/java/spring-framework/configure-spring-boot-initializer-java-app-with-redis-cache repopath: https://search.maven.org/artifact/com.azure.spring/spring-cloud-azure-starter-data-redis-lettuce - sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.19.0/redis/spring-cloud-azure-starter-data-redis-lettuce/ + sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.20.1/redis/spring-cloud-azure-starter-data-redis-lettuce/ springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[3.0.0,3.3.6]" + compatibilityRange: "[3.0.0,3.4.2]" mappings: - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-data-redis-lettuce - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-data-redis-lettuce - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-data-redis-lettuce - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-data-redis-lettuce - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-cloud-azure-starter-data-redis-lettuce - version: 5.19.0 + version: 5.20.1 - name: Testcontainers content: - name: Testcontainers @@ -1661,41 +1661,41 @@ artifacts: - artifactId: spring-cloud-azure-testcontainers groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: |- Microsoft's Spring Cloud Azure lib helps developers to use testcontainers to test Cosmos, Storage Blob, Storage Queue. type: spring links: - javadoc: https://azuresdkdocs.blob.core.windows.net/$web/java/spring-cloud-azure-testcontainers/5.19.0/index.html - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-cloud-azure-testcontainers + javadoc: https://azuresdkdocs.blob.core.windows.net/$web/java/spring-cloud-azure-testcontainers/5.20.1/index.html + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-cloud-azure-testcontainers repopath: https://search.maven.org/artifact/com.azure.spring/spring-cloud-azure-testcontainers - sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.19.0/testcontainers/spring-cloud-azure-testcontainers/ + sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.20.1/testcontainers/spring-cloud-azure-testcontainers/ springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[3.0.0,3.3.6]" + compatibilityRange: "[3.0.0,3.4.2]" mappings: - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-cloud-azure-testcontainers - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-testcontainers - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-testcontainers - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-cloud-azure-testcontainers - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-cloud-azure-testcontainers - version: 5.19.0 + version: 5.20.1 - name: Dockercompose content: - name: Dockercompose @@ -1708,38 +1708,38 @@ artifacts: - artifactId: spring-cloud-azure-docker-compose groupId: com.azure.spring - versionGA: 5.19.0 + versionGA: 5.20.1 description: |- Microsoft's Spring Cloud Azure lib helps developers to use Docker Compose, now it supports Azure Storage Blob and Azure Storage Queue. type: spring links: - javadoc: https://azuresdkdocs.blob.core.windows.net/$web/java/spring-cloud-azure-docker-compose/5.19.0/index.html - github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.19.0/sdk/spring/spring-cloud-azure-docker-compose + javadoc: https://azuresdkdocs.blob.core.windows.net/$web/java/spring-cloud-azure-docker-compose/5.20.1/index.html + github: https://github.com/Azure/azure-sdk-for-java/tree/spring-cloud-azure_5.20.1/sdk/spring/spring-cloud-azure-docker-compose repopath: https://search.maven.org/artifact/com.azure.spring/spring-cloud-azure-docker-compose - sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.19.0/dockercompose/spring-cloud-azure-docker-compose/ + sample: https://github.com/Azure-Samples/azure-spring-boot-samples/tree/spring-cloud-azure_5.20.1/dockercompose/spring-cloud-azure-docker-compose/ springProperties: starter: true bom: spring-cloud-azure-dependencies - compatibilityRange: "[3.0.0,3.3.6]" + compatibilityRange: "[3.0.0,3.4.2]" mappings: - compatibilityRange: "[3.0.0,3.0.13]" groupId: com.azure.spring artifactId: spring-cloud-azure-docker-compose - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.1.0,3.1.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-docker-compose - version: 5.19.0 + version: 5.20.1 - compatibilityRange: "[3.2.0,3.2.12]" groupId: com.azure.spring artifactId: spring-cloud-azure-docker-compose - version: 5.19.0 - - compatibilityRange: "[3.3.0,3.3.6]" + version: 5.20.1 + - compatibilityRange: "[3.3.0,3.3.8]" groupId: com.azure.spring artifactId: spring-cloud-azure-docker-compose - version: 5.19.0 - - compatibilityRange: "[3.4.0,3.4.0]" + version: 5.20.1 + - compatibilityRange: "[3.4.0,3.4.2]" groupId: com.azure.spring artifactId: spring-cloud-azure-docker-compose - version: 5.19.0 + version: 5.20.1 diff --git a/sdk/springappdiscovery/azure-resourcemanager-springappdiscovery/README.md b/sdk/springappdiscovery/azure-resourcemanager-springappdiscovery/README.md index 2209a1353e60..d570e5a59287 100644 --- a/sdk/springappdiscovery/azure-resourcemanager-springappdiscovery/README.md +++ b/sdk/springappdiscovery/azure-resourcemanager-springappdiscovery/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-springappdiscovery - 1.0.0-beta.2 + 1.0.0-beta.3 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fspringappdiscovery%2Fazure-resourcemanager-springappdiscovery%2FREADME.png) + diff --git a/sdk/springappdiscovery/azure-resourcemanager-springappdiscovery/pom.xml b/sdk/springappdiscovery/azure-resourcemanager-springappdiscovery/pom.xml index 9d841db06c8b..82034643dd8f 100644 --- a/sdk/springappdiscovery/azure-resourcemanager-springappdiscovery/pom.xml +++ b/sdk/springappdiscovery/azure-resourcemanager-springappdiscovery/pom.xml @@ -52,23 +52,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/sqlvirtualmachine/azure-resourcemanager-sqlvirtualmachine/README.md b/sdk/sqlvirtualmachine/azure-resourcemanager-sqlvirtualmachine/README.md index 00b3e46ecf17..0fb375352569 100644 --- a/sdk/sqlvirtualmachine/azure-resourcemanager-sqlvirtualmachine/README.md +++ b/sdk/sqlvirtualmachine/azure-resourcemanager-sqlvirtualmachine/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-sqlvirtualmachine - 1.0.0-beta.5 + 1.0.0-beta.6 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fsqlvirtualmachine%2Fazure-resourcemanager-sqlvirtualmachine%2FREADME.png) + diff --git a/sdk/sqlvirtualmachine/azure-resourcemanager-sqlvirtualmachine/pom.xml b/sdk/sqlvirtualmachine/azure-resourcemanager-sqlvirtualmachine/pom.xml index 3a6720f8641e..66c5a50dba96 100644 --- a/sdk/sqlvirtualmachine/azure-resourcemanager-sqlvirtualmachine/pom.xml +++ b/sdk/sqlvirtualmachine/azure-resourcemanager-sqlvirtualmachine/pom.xml @@ -52,23 +52,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/standbypool/azure-resourcemanager-standbypool/README.md b/sdk/standbypool/azure-resourcemanager-standbypool/README.md index b0288c241a33..f7b0a5f5ed75 100644 --- a/sdk/standbypool/azure-resourcemanager-standbypool/README.md +++ b/sdk/standbypool/azure-resourcemanager-standbypool/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-standbypool - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fstandbypool%2Fazure-resourcemanager-standbypool%2FREADME.png) + diff --git a/sdk/standbypool/azure-resourcemanager-standbypool/pom.xml b/sdk/standbypool/azure-resourcemanager-standbypool/pom.xml index de0a5e70d38d..0299784654d9 100644 --- a/sdk/standbypool/azure-resourcemanager-standbypool/pom.xml +++ b/sdk/standbypool/azure-resourcemanager-standbypool/pom.xml @@ -51,34 +51,34 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure.resourcemanager azure-resourcemanager-compute - 2.46.0 + 2.48.0 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/standbypool/azure-resourcemanager-standbypool/src/main/java/com/azure/resourcemanager/standbypool/StandbyPoolManager.java b/sdk/standbypool/azure-resourcemanager-standbypool/src/main/java/com/azure/resourcemanager/standbypool/StandbyPoolManager.java index 7879c25ef6aa..e214d76bcc47 100644 --- a/sdk/standbypool/azure-resourcemanager-standbypool/src/main/java/com/azure/resourcemanager/standbypool/StandbyPoolManager.java +++ b/sdk/standbypool/azure-resourcemanager-standbypool/src/main/java/com/azure/resourcemanager/standbypool/StandbyPoolManager.java @@ -22,6 +22,7 @@ import com.azure.core.http.policy.UserAgentPolicy; import com.azure.core.management.profile.AzureProfile; import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.standbypool.fluent.StandbyPoolClient; import com.azure.resourcemanager.standbypool.implementation.OperationsImpl; @@ -41,6 +42,7 @@ import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; @@ -112,6 +114,9 @@ public static Configurable configure() { */ public static final class Configurable { private static final ClientLogger LOGGER = new ClientLogger(Configurable.class); + private static final String SDK_VERSION = "version"; + private static final Map PROPERTIES + = CoreUtils.getProperties("azure-resourcemanager-standbypool.properties"); private HttpClient httpClient; private HttpLogOptions httpLogOptions; @@ -219,12 +224,14 @@ public StandbyPoolManager authenticate(TokenCredential credential, AzureProfile Objects.requireNonNull(credential, "'credential' cannot be null."); Objects.requireNonNull(profile, "'profile' cannot be null."); + String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); + StringBuilder userAgentBuilder = new StringBuilder(); userAgentBuilder.append("azsdk-java") .append("-") .append("com.azure.resourcemanager.standbypool") .append("/") - .append("1.0.0-beta.1"); + .append(clientVersion); if (!Configuration.getGlobalConfiguration().get("AZURE_TELEMETRY_DISABLED", false)) { userAgentBuilder.append(" (") .append(Configuration.getGlobalConfiguration().get("java.version")) diff --git a/sdk/standbypool/azure-resourcemanager-standbypool/src/main/resources/azure-resourcemanager-standbypool.properties b/sdk/standbypool/azure-resourcemanager-standbypool/src/main/resources/azure-resourcemanager-standbypool.properties new file mode 100644 index 000000000000..defbd48204e4 --- /dev/null +++ b/sdk/standbypool/azure-resourcemanager-standbypool/src/main/resources/azure-resourcemanager-standbypool.properties @@ -0,0 +1 @@ +version=${project.version} diff --git a/sdk/storage/README.md b/sdk/storage/README.md index e865711a4640..3b461cbf76be 100644 --- a/sdk/storage/README.md +++ b/sdk/storage/README.md @@ -16,4 +16,4 @@ To get started with a specific library, see the **README.md** file located in th - [Azure Storage File Datalake](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/storage/azure-storage-file-datalake/README.md) is Microsoft's optimized storage solution for for big data analytics workloads. A fundamental part of Data Lake Storage Gen2 is the addition of a hierarchical namespace to Blob storage. The hierarchical namespace organizes objects/files into a hierarchy of directories for efficient data access. -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fstorage%2FREADME.png) + diff --git a/sdk/storage/azure-storage-blob-batch/CHANGELOG.md b/sdk/storage/azure-storage-blob-batch/CHANGELOG.md index 0d2957413929..8559c402b8ae 100644 --- a/sdk/storage/azure-storage-blob-batch/CHANGELOG.md +++ b/sdk/storage/azure-storage-blob-batch/CHANGELOG.md @@ -1,15 +1,30 @@ # Release History -## 12.26.0-beta.1 (Unreleased) +## 12.26.0 (2025-03-11) ### Features Added +- Added support for service version 2025-05-05. -### Breaking Changes +### Other Changes + +#### Dependency Updates +- Upgraded `azure-storage-blob` from `12.29.1` to version `12.30.0`. -### Bugs Fixed +## 12.25.1 (2025-03-03) ### Other Changes +#### Dependency Updates +- Upgraded `azure-xml` from `1.1.0` to version `1.2.0`. +- Upgraded `azure-storage-blob` from `12.29.0` to version `12.29.1`. +- Upgraded `azure-core` from `1.54.0` to version `1.55.2`. +- Upgraded `azure-core-http-netty` from `1.15.6` to version `1.15.10`. + +## 12.26.0-beta.1 (2025-02-11) + +### Features Added +- Added support for service version 2025-05-05. + ## 12.25.0 (2024-11-13) ### Features Added diff --git a/sdk/storage/azure-storage-blob-batch/README.md b/sdk/storage/azure-storage-blob-batch/README.md index f8d651b9d385..ce619663be18 100644 --- a/sdk/storage/azure-storage-blob-batch/README.md +++ b/sdk/storage/azure-storage-blob-batch/README.md @@ -56,7 +56,7 @@ add the direct dependency to your project as follows. com.azure azure-storage-blob-batch - 12.25.0 + 12.26.0 ``` [//]: # ({x-version-update-end}) @@ -213,4 +213,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct](https://ope [coc_contact]: mailto:opencode@microsoft.com [performance_tuning]: https://github.com/Azure/azure-sdk-for-java/wiki/Performance-Tuning -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fstorage%2Fazure-storage-blob-batch%2FREADME.png) + diff --git a/sdk/storage/azure-storage-blob-batch/pom.xml b/sdk/storage/azure-storage-blob-batch/pom.xml index a5b1d8cf6a28..dd6fbd29d33e 100644 --- a/sdk/storage/azure-storage-blob-batch/pom.xml +++ b/sdk/storage/azure-storage-blob-batch/pom.xml @@ -13,7 +13,7 @@ com.azure azure-storage-blob-batch - 12.26.0-beta.1 + 12.26.0 Microsoft Azure client library for Blob Storage batching This module contains client library for Microsoft Azure Blob Storage batching. @@ -55,22 +55,22 @@ com.azure azure-xml - 1.1.0 + 1.2.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-storage-blob - 12.30.0-beta.1 + 12.30.0 + 12.29.0 tests test-jar test @@ -94,13 +94,13 @@ com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/storage/azure-storage-blob-batch/src/samples/README.md b/sdk/storage/azure-storage-blob-batch/src/samples/README.md index ca869dca1ee9..ab13fd3823a1 100644 --- a/sdk/storage/azure-storage-blob-batch/src/samples/README.md +++ b/sdk/storage/azure-storage-blob-batch/src/samples/README.md @@ -51,4 +51,4 @@ This project welcomes contributions and suggestions. Find [more contributing][SD [storageblob_rest]: https://learn.microsoft.com/rest/api/storageservices/blob-service-rest-api [error_codes]: https://learn.microsoft.com/rest/api/storageservices/blob-service-error-codes -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fstorage%2Fazure-storage-blob-batch%2Fsrc%2Fsamples%2FREADME.png) + diff --git a/sdk/storage/azure-storage-blob-changefeed/CHANGELOG.md b/sdk/storage/azure-storage-blob-changefeed/CHANGELOG.md index 7ee9ff8d86cc..134385104b4b 100644 --- a/sdk/storage/azure-storage-blob-changefeed/CHANGELOG.md +++ b/sdk/storage/azure-storage-blob-changefeed/CHANGELOG.md @@ -1,14 +1,14 @@ # Release History -## 12.0.0-beta.28 (Unreleased) +## 12.0.0-beta.29 (2025-03-11) ### Features Added +- Added support for service version 2025-05-05. -### Breaking Changes +## 12.0.0-beta.28 (2025-02-11) -### Bugs Fixed - -### Other Changes +### Features Added +- Added support for service version 2025-05-05. ## 12.0.0-beta.27 (2024-11-13) diff --git a/sdk/storage/azure-storage-blob-changefeed/README.md b/sdk/storage/azure-storage-blob-changefeed/README.md index f6fb20e2c733..91fa45ce7dff 100644 --- a/sdk/storage/azure-storage-blob-changefeed/README.md +++ b/sdk/storage/azure-storage-blob-changefeed/README.md @@ -21,7 +21,7 @@ process change events that occur in your Blob Storage account at a low cost. com.azure azure-storage-blob-changefeed - 12.0.0-beta.27 + 12.0.0-beta.29 ``` [//]: # ({x-version-update-end}) @@ -255,4 +255,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct](https://ope [coc_contact]: mailto:opencode@microsoft.com [performance_tuning]: https://github.com/Azure/azure-sdk-for-java/wiki/Performance-Tuning -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fstorage%2Fazure-storage-blob-changefeed%2FREADME.png) + diff --git a/sdk/storage/azure-storage-blob-changefeed/pom.xml b/sdk/storage/azure-storage-blob-changefeed/pom.xml index 7de70e9891a2..6b2218ecc62c 100644 --- a/sdk/storage/azure-storage-blob-changefeed/pom.xml +++ b/sdk/storage/azure-storage-blob-changefeed/pom.xml @@ -13,7 +13,7 @@ com.azure azure-storage-blob-changefeed - 12.0.0-beta.28 + 12.0.0-beta.29 Microsoft Azure client library for Blob Storage changefeed This module contains client library for Microsoft Azure Blob Storage changefeed. @@ -62,27 +62,27 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-xml - 1.1.0 + 1.2.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-storage-blob - 12.30.0-beta.1 + 12.30.0 + 12.29.0 tests test-jar test @@ -106,13 +106,13 @@ com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/storage/azure-storage-blob-changefeed/src/samples/README.md b/sdk/storage/azure-storage-blob-changefeed/src/samples/README.md index 6e0e4bd56034..436b940e3968 100644 --- a/sdk/storage/azure-storage-blob-changefeed/src/samples/README.md +++ b/sdk/storage/azure-storage-blob-changefeed/src/samples/README.md @@ -45,4 +45,4 @@ This project welcomes contributions and suggestions. Find [more contributing][SD [storageblob_rest]: https://learn.microsoft.com/rest/api/storageservices/blob-service-rest-api [error_codes]: https://learn.microsoft.com/rest/api/storageservices/blob-service-error-codes -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fstorage%2Fazure-storage-blob-changefeed%2Fsrc%2Fsamples%2FREADME.png) + diff --git a/sdk/storage/azure-storage-blob-cryptography/CHANGELOG.md b/sdk/storage/azure-storage-blob-cryptography/CHANGELOG.md index 04c3d7520adb..299a14ed52ac 100644 --- a/sdk/storage/azure-storage-blob-cryptography/CHANGELOG.md +++ b/sdk/storage/azure-storage-blob-cryptography/CHANGELOG.md @@ -1,15 +1,31 @@ # Release History -## 12.29.0-beta.1 (Unreleased) +## 12.29.0 (2025-03-11) ### Features Added +- Added support for service version 2025-05-05. -### Breaking Changes +### Other Changes -### Bugs Fixed +#### Dependency Updates +- Upgraded `azure-storage-blob` from `12.29.1` to version `12.30.0`. + +## 12.28.1 (2025-03-03) ### Other Changes +#### Dependency Updates +- Upgraded `azure-xml` from `1.1.0` to version `1.2.0`. +- Upgraded `azure-storage-blob` from `12.29.0` to version `12.29.1`. +- Upgraded `azure-json` from `1.3.0` to version `1.4.0`. +- Upgraded `azure-core` from `1.54.0` to version `1.55.2`. +- Upgraded `azure-core-http-netty` from `1.15.6` to version `1.15.10`. + +## 12.29.0-beta.1 (2025-02-11) + +### Features Added +- Added support for service version 2025-05-05. + ## 12.28.0 (2024-11-13) ### Features Added diff --git a/sdk/storage/azure-storage-blob-cryptography/README.md b/sdk/storage/azure-storage-blob-cryptography/README.md index 0567921c12d1..e1fb151454a4 100644 --- a/sdk/storage/azure-storage-blob-cryptography/README.md +++ b/sdk/storage/azure-storage-blob-cryptography/README.md @@ -58,7 +58,7 @@ add the direct dependency to your project as follows. com.azure azure-storage-blob-cryptography - 12.28.0 + 12.29.0 ``` [//]: # ({x-version-update-end}) @@ -245,7 +245,7 @@ When you submit a pull request, a CLA-bot will automatically determine whether y This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments. -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fstorage%2Fazure-storage-blob-cryptography%2FREADME.png) + [jdk]: https://learn.microsoft.com/java/azure/jdk/ [source]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/storage/azure-storage-blob-cryptography/src diff --git a/sdk/storage/azure-storage-blob-cryptography/pom.xml b/sdk/storage/azure-storage-blob-cryptography/pom.xml index 52d2dc430ec7..823e42dded69 100644 --- a/sdk/storage/azure-storage-blob-cryptography/pom.xml +++ b/sdk/storage/azure-storage-blob-cryptography/pom.xml @@ -13,7 +13,7 @@ com.azure azure-storage-blob-cryptography - 12.29.0-beta.1 + 12.29.0 Microsoft Azure client library for Blob Storage cryptography This module contains client library for Microsoft Azure Blob Storage cryptography. @@ -56,33 +56,33 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-xml - 1.1.0 + 1.2.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-storage-blob - 12.30.0-beta.1 + 12.30.0 com.azure azure-storage-common - 12.29.0-beta.1 + 12.29.0 tests test-jar test @@ -90,7 +90,7 @@ com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test @@ -130,13 +130,13 @@ com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-security-keyvault-keys - 4.9.1 + 4.9.3 test diff --git a/sdk/storage/azure-storage-blob-nio/CHANGELOG.md b/sdk/storage/azure-storage-blob-nio/CHANGELOG.md index 56ac5a869d6a..2c9f1723e4f8 100644 --- a/sdk/storage/azure-storage-blob-nio/CHANGELOG.md +++ b/sdk/storage/azure-storage-blob-nio/CHANGELOG.md @@ -1,14 +1,14 @@ # Release History -## 12.0.0-beta.29 (Unreleased) +## 12.0.0-beta.30 (2025-03-11) ### Features Added +- Added support for service version 2025-05-05. -### Breaking Changes - -### Bugs Fixed +## 12.0.0-beta.29 (2025-02-11) -### Other Changes +### Features Added +- Added support for service version 2025-05-05. ## 12.0.0-beta.28 (2024-11-13) diff --git a/sdk/storage/azure-storage-blob-nio/README.md b/sdk/storage/azure-storage-blob-nio/README.md index f02843d6baa4..7e529eeb48ff 100644 --- a/sdk/storage/azure-storage-blob-nio/README.md +++ b/sdk/storage/azure-storage-blob-nio/README.md @@ -20,7 +20,7 @@ This package allows you to interact with Azure Blob Storage through the standard com.azure azure-storage-blob-nio - 12.0.0-beta.28 + 12.0.0-beta.30 ``` [//]: # ({x-version-update-end}) @@ -331,4 +331,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [file_system]: https://docs.oracle.com/javase/7/docs/api/java/nio/file/FileSystem.html [file_systems]: https://docs.oracle.com/javase/7/docs/api/java/nio/file/FileSystems.html -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fstorage%2Fazure-storage-blob%2FREADME.png) + diff --git a/sdk/storage/azure-storage-blob-nio/pom.xml b/sdk/storage/azure-storage-blob-nio/pom.xml index 57f44b73fd7b..cc22c2f94833 100644 --- a/sdk/storage/azure-storage-blob-nio/pom.xml +++ b/sdk/storage/azure-storage-blob-nio/pom.xml @@ -13,7 +13,7 @@ com.azure azure-storage-blob-nio - 12.0.0-beta.29 + 12.0.0-beta.30 Microsoft Azure implementation of NIO on top of Azure Blob Storage This module contains an implementation of Java's NIO interface on top of Azure Blob Storage. https://github.com/Azure/azure-sdk-for-java @@ -53,28 +53,28 @@ com.azure azure-xml - 1.1.0 + 1.2.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-storage-blob - 12.30.0-beta.1 + 12.30.0 com.azure azure-storage-common - 12.29.0-beta.1 + 12.29.0 tests test-jar test @@ -82,7 +82,7 @@ com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test diff --git a/sdk/storage/azure-storage-blob-stress/pom.xml b/sdk/storage/azure-storage-blob-stress/pom.xml index 2a7d11f1cad0..15491576274c 100644 --- a/sdk/storage/azure-storage-blob-stress/pom.xml +++ b/sdk/storage/azure-storage-blob-stress/pom.xml @@ -30,17 +30,17 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-storage-blob - 12.30.0-beta.1 + 12.30.0 com.azure @@ -51,24 +51,24 @@ com.azure - azure-monitor-opentelemetry-exporter - 1.0.0-beta.31 + azure-monitor-opentelemetry-autoconfigure + 1.0.0 io.opentelemetry.instrumentation opentelemetry-runtime-telemetry-java8 - 2.9.0-alpha + 2.12.0-alpha io.opentelemetry.instrumentation opentelemetry-logback-appender-1.0 - 2.9.0-alpha + 2.12.0-alpha com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.52 + 1.0.0-beta.56 com.azure diff --git a/sdk/storage/azure-storage-blob/CHANGELOG.md b/sdk/storage/azure-storage-blob/CHANGELOG.md index 14c697cad9c8..0755f9d98dcf 100644 --- a/sdk/storage/azure-storage-blob/CHANGELOG.md +++ b/sdk/storage/azure-storage-blob/CHANGELOG.md @@ -1,15 +1,32 @@ # Release History -## 12.30.0-beta.1 (Unreleased) +## 12.30.0 (2025-03-11) ### Features Added +- Added support for service version 2025-05-05. -### Breaking Changes +### Other Changes -### Bugs Fixed +#### Dependency Updates +- Upgraded `azure-storage-common` from `12.28.1` to version `12.29.0`. +- Upgraded `azure-storage-internal-avro` from `12.14.0` to version `12.15.0`. + +## 12.29.1 (2025-03-03) ### Other Changes +#### Dependency Updates +- Upgraded `azure-storage-common` from `12.28.0` to version `12.29.0-beta.2`. +- Upgraded `azure-storage-internal-avro` from `12.14.0` to version `12.15.0-beta.2`. +- Upgraded `azure-xml` from `1.1.0` to version `1.2.0`. +- Upgraded `azure-core` from `1.54.0` to version `1.55.2`. +- Upgraded `azure-core-http-netty` from `1.15.6` to version `1.15.10`. + +## 12.30.0-beta.1 (2025-02-11) + +### Features Added +- Added support for service version 2025-05-05. + ## 12.29.0 (2024-11-13) ### Features Added diff --git a/sdk/storage/azure-storage-blob/README.md b/sdk/storage/azure-storage-blob/README.md index d81e456ebaaa..0f07a4309d78 100644 --- a/sdk/storage/azure-storage-blob/README.md +++ b/sdk/storage/azure-storage-blob/README.md @@ -56,7 +56,7 @@ add the direct dependency to your project as follows. com.azure azure-storage-blob - 12.29.0 + 12.30.0 ``` [//]: # ({x-version-update-end}) @@ -628,4 +628,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc_contact]: mailto:opencode@microsoft.com [performance_tuning]: https://github.com/Azure/azure-sdk-for-java/wiki/Performance-Tuning -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fstorage%2Fazure-storage-blob%2FREADME.png) + diff --git a/sdk/storage/azure-storage-blob/pom.xml b/sdk/storage/azure-storage-blob/pom.xml index b3b59fcea40b..8327aa4a0042 100644 --- a/sdk/storage/azure-storage-blob/pom.xml +++ b/sdk/storage/azure-storage-blob/pom.xml @@ -13,7 +13,7 @@ com.azure azure-storage-blob - 12.30.0-beta.1 + 12.30.0 Microsoft Azure client library for Blob Storage This module contains client library for Microsoft Azure Blob Storage. @@ -69,27 +69,27 @@ com.azure azure-xml - 1.1.0 + 1.2.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-storage-common - 12.29.0-beta.1 + 12.29.0 com.azure azure-storage-internal-avro - 12.15.0-beta.1 + 12.15.0 + 12.29.0 tests test-jar test @@ -112,13 +112,13 @@ com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test @@ -175,7 +175,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 ${AZURE_STORAGE_SAS_SERVICE_VERSION} diff --git a/sdk/storage/azure-storage-blob/src/main/java/com/azure/storage/blob/BlobServiceVersion.java b/sdk/storage/azure-storage-blob/src/main/java/com/azure/storage/blob/BlobServiceVersion.java index fba47b07e72b..ce390841d0a5 100644 --- a/sdk/storage/azure-storage-blob/src/main/java/com/azure/storage/blob/BlobServiceVersion.java +++ b/sdk/storage/azure-storage-blob/src/main/java/com/azure/storage/blob/BlobServiceVersion.java @@ -132,7 +132,12 @@ public enum BlobServiceVersion implements ServiceVersion { /** * Service version {@code 2025-01-05}. */ - V2025_01_05("2025-01-05"); + V2025_01_05("2025-01-05"), + + /** + * Service version {@code 2025-05-05}. + */ + V2025_05_05("2025-05-05"); private final String version; @@ -154,6 +159,6 @@ public String getVersion() { * @return the latest {@link BlobServiceVersion} */ public static BlobServiceVersion getLatest() { - return V2025_01_05; + return V2025_05_05; } } diff --git a/sdk/storage/azure-storage-blob/src/samples/README.md b/sdk/storage/azure-storage-blob/src/samples/README.md index dda895dff752..360af08a0069 100644 --- a/sdk/storage/azure-storage-blob/src/samples/README.md +++ b/sdk/storage/azure-storage-blob/src/samples/README.md @@ -61,4 +61,4 @@ This project welcomes contributions and suggestions. Find [more contributing][SD [storageblob_rest]: https://learn.microsoft.com/rest/api/storageservices/blob-service-rest-api [error_codes]: https://learn.microsoft.com/rest/api/storageservices/blob-service-error-codes -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fstorage%2Fazure-storage-blob%2Fsrc%2Fsamples%2FREADME.png) + diff --git a/sdk/storage/azure-storage-blob/swagger/README.md b/sdk/storage/azure-storage-blob/swagger/README.md index 0c0037216c7e..fe6f996233e8 100644 --- a/sdk/storage/azure-storage-blob/swagger/README.md +++ b/sdk/storage/azure-storage-blob/swagger/README.md @@ -679,4 +679,4 @@ directive: ]; ``` -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fstorage%2Fazure-storage-blob%2Fswagger%2FREADME.png) + diff --git a/sdk/storage/azure-storage-common/CHANGELOG.md b/sdk/storage/azure-storage-common/CHANGELOG.md index 6f869128a87b..bb20e91d6b6a 100644 --- a/sdk/storage/azure-storage-common/CHANGELOG.md +++ b/sdk/storage/azure-storage-common/CHANGELOG.md @@ -1,15 +1,27 @@ # Release History -## 12.29.0-beta.1 (Unreleased) +## 12.29.0 (2025-03-11) ### Features Added - -### Breaking Changes +- Added support for service version 2025-05-05. ### Bugs Fixed +- Fixed an issue where the tenant ID was not properly extracted from the authorization URI. + +## 12.28.1 (2025-03-03) ### Other Changes +#### Dependency Updates +- Upgraded `azure-xml` from `1.1.0` to version `1.2.0`. +- Upgraded `azure-core` from `1.54.0` to version `1.55.2`. +- Upgraded `azure-core-http-netty` from `1.15.6` to version `1.15.10`. + +## 12.29.0-beta.1 (2025-02-11) + +### Features Added +- Added support for service version 2025-05-05. + ## 12.28.0 (2024-11-13) ### Features Added diff --git a/sdk/storage/azure-storage-common/README.md b/sdk/storage/azure-storage-common/README.md index 7878ff143d1d..1de983ef163c 100644 --- a/sdk/storage/azure-storage-common/README.md +++ b/sdk/storage/azure-storage-common/README.md @@ -53,7 +53,7 @@ add the direct dependency to your project as follows. com.azure azure-storage-common - 12.28.0 + 12.29.0 ``` [//]: # ({x-version-update-end}) @@ -102,4 +102,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ [coc_contact]: mailto:opencode@microsoft.com -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fstorage%2Fazure-storage-common%2FREADME.png) + diff --git a/sdk/storage/azure-storage-common/ci.system.properties b/sdk/storage/azure-storage-common/ci.system.properties index 43ea5cd58847..7795686dafcf 100644 --- a/sdk/storage/azure-storage-common/ci.system.properties +++ b/sdk/storage/azure-storage-common/ci.system.properties @@ -1,2 +1,2 @@ -AZURE_LIVE_TEST_SERVICE_VERSION=V2025_01_05 -AZURE_STORAGE_SAS_SERVICE_VERSION=2025-01-05 +AZURE_LIVE_TEST_SERVICE_VERSION=V2025_05_05 +AZURE_STORAGE_SAS_SERVICE_VERSION=2025-05-05 diff --git a/sdk/storage/azure-storage-common/pom.xml b/sdk/storage/azure-storage-common/pom.xml index 1b8e609e1760..5f11bbab64e3 100644 --- a/sdk/storage/azure-storage-common/pom.xml +++ b/sdk/storage/azure-storage-common/pom.xml @@ -13,7 +13,7 @@ com.azure azure-storage-common - 12.29.0-beta.1 + 12.29.0 Microsoft Azure common module for Storage This module contains common code based for all Microsoft Azure Storage client libraries. @@ -58,17 +58,17 @@ com.azure azure-xml - 1.1.0 + 1.2.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test @@ -140,7 +140,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 ${settings.localRepository}/com/azure/${project.artifactId}/${project.version}/${project.artifactId}-${project.version}-tests.jar diff --git a/sdk/storage/azure-storage-common/src/main/java/com/azure/storage/common/implementation/Constants.java b/sdk/storage/azure-storage-common/src/main/java/com/azure/storage/common/implementation/Constants.java index 1a1d4cc1fee8..7a07e648d8ca 100644 --- a/sdk/storage/azure-storage-common/src/main/java/com/azure/storage/common/implementation/Constants.java +++ b/sdk/storage/azure-storage-common/src/main/java/com/azure/storage/common/implementation/Constants.java @@ -88,7 +88,7 @@ public final class Constants { public static final String PROPERTY_AZURE_STORAGE_SAS_SERVICE_VERSION = "AZURE_STORAGE_SAS_SERVICE_VERSION"; public static final String SAS_SERVICE_VERSION - = Configuration.getGlobalConfiguration().get(PROPERTY_AZURE_STORAGE_SAS_SERVICE_VERSION, "2025-01-05"); + = Configuration.getGlobalConfiguration().get(PROPERTY_AZURE_STORAGE_SAS_SERVICE_VERSION, "2025-05-05"); public static final String ADJUSTED_BLOB_LENGTH_KEY = "adjustedBlobLength"; @@ -218,7 +218,7 @@ public static final class HeaderConstants { * @deprecated For SAS Service Version use {@link Constants#SAS_SERVICE_VERSION}. */ @Deprecated - public static final String TARGET_STORAGE_VERSION = "2025-01-05"; + public static final String TARGET_STORAGE_VERSION = "2025-05-05"; /** * Error code returned from the service. diff --git a/sdk/storage/azure-storage-common/src/main/java/com/azure/storage/common/policy/StorageBearerTokenChallengeAuthorizationPolicy.java b/sdk/storage/azure-storage-common/src/main/java/com/azure/storage/common/policy/StorageBearerTokenChallengeAuthorizationPolicy.java index 1304665c3683..edc8323e0600 100644 --- a/sdk/storage/azure-storage-common/src/main/java/com/azure/storage/common/policy/StorageBearerTokenChallengeAuthorizationPolicy.java +++ b/sdk/storage/azure-storage-common/src/main/java/com/azure/storage/common/policy/StorageBearerTokenChallengeAuthorizationPolicy.java @@ -10,8 +10,11 @@ import com.azure.core.http.HttpResponse; import com.azure.core.http.policy.BearerTokenAuthenticationPolicy; import com.azure.core.util.CoreUtils; +import com.azure.core.util.logging.ClientLogger; import reactor.core.publisher.Mono; +import java.net.URI; +import java.net.URISyntaxException; import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -22,8 +25,10 @@ */ public class StorageBearerTokenChallengeAuthorizationPolicy extends BearerTokenAuthenticationPolicy { + private static final ClientLogger LOGGER = new ClientLogger(StorageBearerTokenChallengeAuthorizationPolicy.class); + private static final String DEFAULT_SCOPE = "/.default"; - private static final String BEARER_TOKEN_PREFIX = "Bearer "; + static final String BEARER_TOKEN_PREFIX = "Bearer "; private String[] scopes; @@ -64,29 +69,69 @@ public Mono authorizeRequestOnChallenge(HttpPipelineCallContext context String authHeader = response.getHeaderValue(HttpHeaderName.WWW_AUTHENTICATE); Map challenges = extractChallengeAttributes(authHeader, BEARER_TOKEN_PREFIX); - String scope = challenges.get("resource_id"); + String scope = getScopeFromChallenges(challenges); + String authorization = getAuthorizationFromChallenges(challenges); + if (scope != null) { scope += DEFAULT_SCOPE; scopes = new String[] { scope }; scopes = getScopes(context, scopes); - return setAuthorizationHeader(context, new TokenRequestContext().addScopes(scopes)).thenReturn(true); } + + if (authorization != null) { + String tenantId = extractTenantIdFromUri(authorization); + TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(scopes).setTenantId(tenantId); + return setAuthorizationHeader(context, tokenRequestContext).thenReturn(true); + } + + if (scope != null) { + TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(scopes); + return setAuthorizationHeader(context, tokenRequestContext).thenReturn(true); + } + return Mono.just(false); } + String extractTenantIdFromUri(String uri) { + try { + String[] segments = new URI(uri).getPath().split("/"); + if (segments.length > 1) { + return segments[1]; + } else { + throw LOGGER.logExceptionAsError(new RuntimeException("Invalid authorization URI: tenantId not found")); + } + } catch (URISyntaxException e) { + throw LOGGER.logExceptionAsError(new RuntimeException("Invalid authorization URI", e)); + } + } + @Override public boolean authorizeRequestOnChallengeSync(HttpPipelineCallContext context, HttpResponse response) { String authHeader = response.getHeaderValue(HttpHeaderName.WWW_AUTHENTICATE); Map challenges = extractChallengeAttributes(authHeader, BEARER_TOKEN_PREFIX); - String scope = challenges.get("resource_id"); + String scope = getScopeFromChallenges(challenges); + String authorization = getAuthorizationFromChallenges(challenges); + if (scope != null) { scope += DEFAULT_SCOPE; scopes = new String[] { scope }; scopes = getScopes(context, scopes); - setAuthorizationHeaderSync(context, new TokenRequestContext().addScopes(scopes)); + } + + if (authorization != null) { + String tenantId = extractTenantIdFromUri(authorization); + TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(scopes).setTenantId(tenantId); + setAuthorizationHeaderSync(context, tokenRequestContext); + return true; + } + + if (scope != null) { + TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(scopes); + setAuthorizationHeaderSync(context, tokenRequestContext); return true; } + return false; } @@ -117,4 +162,12 @@ static boolean isBearerChallenge(String authenticateHeader, String authChallenge return (!CoreUtils.isNullOrEmpty(authenticateHeader) && authenticateHeader.toLowerCase(Locale.ROOT).startsWith(authChallengePrefix.toLowerCase(Locale.ROOT))); } + + String getScopeFromChallenges(Map challenges) { + return challenges.get("resource_id"); + } + + String getAuthorizationFromChallenges(Map challenges) { + return challenges.get("authorization_uri"); + } } diff --git a/sdk/storage/azure-storage-common/src/test/java/com/azure/storage/common/policy/StorageBearerTokenChallengeAuthorizationPolicyTests.java b/sdk/storage/azure-storage-common/src/test/java/com/azure/storage/common/policy/StorageBearerTokenChallengeAuthorizationPolicyTests.java new file mode 100644 index 000000000000..3cee69ca1f50 --- /dev/null +++ b/sdk/storage/azure-storage-common/src/test/java/com/azure/storage/common/policy/StorageBearerTokenChallengeAuthorizationPolicyTests.java @@ -0,0 +1,211 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.common.policy; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.test.utils.MockTokenCredential; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.Map; + +import static com.azure.storage.common.policy.StorageBearerTokenChallengeAuthorizationPolicy.BEARER_TOKEN_PREFIX; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class StorageBearerTokenChallengeAuthorizationPolicyTests { + + private String[] scopes; + private TokenCredential mockCredential; + + @BeforeEach + public void setup() { + scopes = new String[] { "https://storage.azure.com/.default" }; + mockCredential = new MockTokenCredential(); + } + + @Test + public void testExtractChallengeAttributes() { + StorageBearerTokenChallengeAuthorizationPolicy policy + = new StorageBearerTokenChallengeAuthorizationPolicy(mockCredential, "https://storage.azure.com/.default"); + + String authHeader + = "Bearer authorization_uri=https://login.microsoftonline.com/tenantId/oauth2/authorize resource_id=https://storage.azure.com"; + Map challenges = policy.extractChallengeAttributes(authHeader, BEARER_TOKEN_PREFIX); + + assertNotNull(challenges); + assertEquals("https://login.microsoftonline.com/tenantid/oauth2/authorize", + challenges.get("authorization_uri")); + assertEquals("https://storage.azure.com", challenges.get("resource_id")); + } + + @Test + public void testGetScopeFromChallenges() { + StorageBearerTokenChallengeAuthorizationPolicy policy + = new StorageBearerTokenChallengeAuthorizationPolicy(mockCredential, "https://storage.azure.com/.default"); + + Map challenges = new HashMap<>(); + challenges.put("resource_id", "https://storage.azure.com"); + + String scope = policy.getScopeFromChallenges(challenges); + + assertEquals("https://storage.azure.com", scope); + } + + @Test + public void testGetAuthorizationFromChallenges() { + StorageBearerTokenChallengeAuthorizationPolicy policy + = new StorageBearerTokenChallengeAuthorizationPolicy(mockCredential, "https://storage.azure.com/.default"); + + Map challenges = new HashMap<>(); + challenges.put("authorization_uri", "https://login.microsoftonline.com/tenantId/oauth2/authorize"); + + String authorization = policy.getAuthorizationFromChallenges(challenges); + + assertEquals("https://login.microsoftonline.com/tenantId/oauth2/authorize", authorization); + } + + @Test + public void usesTokenProvidedByCredentials() { + StorageBearerTokenChallengeAuthorizationPolicy policy + = new StorageBearerTokenChallengeAuthorizationPolicy(mockCredential, scopes); + + Map challenges = policy.extractChallengeAttributes(null, BEARER_TOKEN_PREFIX); + + String scope = policy.getScopeFromChallenges(challenges); + String authorization = policy.getAuthorizationFromChallenges(challenges); + + assertNull(scope); + assertNull(authorization); + } + + @Test + public void doesNotSendUnauthorizedRequestWhenEnableTenantDiscoveryIsFalse() { + StorageBearerTokenChallengeAuthorizationPolicy policy + = new StorageBearerTokenChallengeAuthorizationPolicy(mockCredential, scopes); + + Map challenges = policy.extractChallengeAttributes(null, BEARER_TOKEN_PREFIX); + + String scope = policy.getScopeFromChallenges(challenges); + String authorization = policy.getAuthorizationFromChallenges(challenges); + + assertNull(scope); + assertNull(authorization); + } + + @Test + public void sendsUnauthorizedRequestWhenEnableTenantDiscoveryIsTrue() { + StorageBearerTokenChallengeAuthorizationPolicy policy + = new StorageBearerTokenChallengeAuthorizationPolicy(mockCredential, scopes); + + String expectedTenantId = "72f988bf-86f1-41af-91ab-2d7cd011db47"; + String authHeader = "Bearer authorization_uri=https://login.microsoftonline.com/" + expectedTenantId + + "/oauth2/authorize resource_id=https://storage.azure.com"; + Map challenges = policy.extractChallengeAttributes(authHeader, BEARER_TOKEN_PREFIX); + + String scope = policy.getScopeFromChallenges(challenges); + String authorization = policy.getAuthorizationFromChallenges(challenges); + + assertEquals("https://storage.azure.com", scope); + assertEquals("https://login.microsoftonline.com/" + expectedTenantId + "/oauth2/authorize", authorization); + } + + @Test + public void usesScopeFromBearerChallenge() { + StorageBearerTokenChallengeAuthorizationPolicy policy = new StorageBearerTokenChallengeAuthorizationPolicy( + mockCredential, "https://disk.compute.azure.com/.default"); + + String serviceChallengeResponseScope = "https://storage.azure.com"; + String authHeader + = "Bearer authorization_uri=https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2/authorize resource_id=" + + serviceChallengeResponseScope; + Map challenges = policy.extractChallengeAttributes(authHeader, BEARER_TOKEN_PREFIX); + + String scope = policy.getScopeFromChallenges(challenges); + String authorization = policy.getAuthorizationFromChallenges(challenges); + + assertEquals(serviceChallengeResponseScope, scope); + assertEquals("https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2/authorize", + authorization); + } + + @Test + public void testMultiTenantAuthentication() { + StorageBearerTokenChallengeAuthorizationPolicy policy + = new StorageBearerTokenChallengeAuthorizationPolicy(mockCredential, "https://storage.azure.com/.default"); + + String tenantId1 = "tenant1"; + String tenantId2 = "tenant2"; + + String authHeader1 = "Bearer authorization_uri=https://login.microsoftonline.com/" + tenantId1 + + "/oauth2/authorize resource_id=https://storage.azure.com"; + String authHeader2 = "Bearer authorization_uri=https://login.microsoftonline.com/" + tenantId2 + + "/oauth2/authorize resource_id=https://storage.azure.com"; + + Map challenges1 = policy.extractChallengeAttributes(authHeader1, BEARER_TOKEN_PREFIX); + Map challenges2 = policy.extractChallengeAttributes(authHeader2, BEARER_TOKEN_PREFIX); + + String scope1 = policy.getScopeFromChallenges(challenges1); + String authorization1 = policy.getAuthorizationFromChallenges(challenges1); + String scope2 = policy.getScopeFromChallenges(challenges2); + String authorization2 = policy.getAuthorizationFromChallenges(challenges2); + + assertEquals("https://storage.azure.com", scope1); + assertEquals("https://login.microsoftonline.com/" + tenantId1 + "/oauth2/authorize", authorization1); + assertEquals("https://storage.azure.com", scope2); + assertEquals("https://login.microsoftonline.com/" + tenantId2 + "/oauth2/authorize", authorization2); + } + + @Test + public void testExtractTenantIdFromUri() { + StorageBearerTokenChallengeAuthorizationPolicy policy + = new StorageBearerTokenChallengeAuthorizationPolicy(mockCredential, "https://storage.azure.com/.default"); + + String uri = "https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2/authorize"; + String expectedTenantId = "72f988bf-86f1-41af-91ab-2d7cd011db47"; + + String actualTenantId = policy.extractTenantIdFromUri(uri); + + assertEquals(expectedTenantId, actualTenantId); + } + + @Test + public void testExtractTenantIdFromUriInvalidUri() { + StorageBearerTokenChallengeAuthorizationPolicy policy + = new StorageBearerTokenChallengeAuthorizationPolicy(mockCredential, "https://storage.azure.com/.default"); + + String invalidUri = "https://login.microsoftonline.com/"; + + Exception exception = assertThrows(RuntimeException.class, () -> { + policy.extractTenantIdFromUri(invalidUri); + }); + + String expectedMessage = "Invalid authorization URI: tenantId not found"; + String actualMessage = exception.getMessage(); + + assertTrue(actualMessage.contains(expectedMessage)); + } + + @Test + public void testExtractTenantIdFromUriMalformedUri() { + StorageBearerTokenChallengeAuthorizationPolicy policy + = new StorageBearerTokenChallengeAuthorizationPolicy(mockCredential, "https://storage.azure.com/.default"); + + String malformedUri = "ht!tp://invalid-uri"; + + Exception exception = assertThrows(RuntimeException.class, () -> { + policy.extractTenantIdFromUri(malformedUri); + }); + + String expectedMessage = "Invalid authorization URI"; + String actualMessage = exception.getMessage(); + + assertTrue(actualMessage.contains(expectedMessage)); + } + +} diff --git a/sdk/storage/azure-storage-file-datalake-stress/pom.xml b/sdk/storage/azure-storage-file-datalake-stress/pom.xml index b151b34cca12..1052b82c2019 100644 --- a/sdk/storage/azure-storage-file-datalake-stress/pom.xml +++ b/sdk/storage/azure-storage-file-datalake-stress/pom.xml @@ -30,17 +30,17 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-storage-file-datalake - 12.23.0-beta.1 + 12.23.0 com.azure @@ -51,24 +51,24 @@ com.azure - azure-monitor-opentelemetry-exporter - 1.0.0-beta.31 + azure-monitor-opentelemetry-autoconfigure + 1.0.0 io.opentelemetry.instrumentation opentelemetry-runtime-telemetry-java8 - 2.9.0-alpha + 2.12.0-alpha io.opentelemetry.instrumentation opentelemetry-logback-appender-1.0 - 2.9.0-alpha + 2.12.0-alpha com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.52 + 1.0.0-beta.56 com.azure diff --git a/sdk/storage/azure-storage-file-datalake/CHANGELOG.md b/sdk/storage/azure-storage-file-datalake/CHANGELOG.md index a640d3b1c11b..20b5972657e1 100644 --- a/sdk/storage/azure-storage-file-datalake/CHANGELOG.md +++ b/sdk/storage/azure-storage-file-datalake/CHANGELOG.md @@ -1,15 +1,30 @@ # Release History -## 12.23.0-beta.1 (Unreleased) +## 12.23.0 (2025-03-11) ### Features Added +- Added support for service version 2025-05-05. -### Breaking Changes +### Other Changes -### Bugs Fixed +#### Dependency Updates +- Upgraded `azure-storage-blob` from `12.29.1` to version `12.30.0`. + +## 12.22.1 (2025-03-03) ### Other Changes +#### Dependency Updates +- Upgraded `azure-xml` from `1.1.0` to version `1.2.0`. +- Upgraded `azure-storage-blob` from `12.29.0` to version `12.29.1`. +- Upgraded `azure-core` from `1.54.0` to version `1.55.2`. +- Upgraded `azure-core-http-netty` from `1.15.6` to version `1.15.10`. + +## 12.23.0-beta.1 (2025-02-11) + +### Features Added +- Added support for service version 2025-05-05. + ## 12.22.0 (2024-11-13) ### Features Added diff --git a/sdk/storage/azure-storage-file-datalake/README.md b/sdk/storage/azure-storage-file-datalake/README.md index dcdc90ecde2b..9883e51d3919 100644 --- a/sdk/storage/azure-storage-file-datalake/README.md +++ b/sdk/storage/azure-storage-file-datalake/README.md @@ -57,7 +57,7 @@ add the direct dependency to your project as follows. com.azure azure-storage-file-datalake - 12.22.0 + 12.23.0 ``` [//]: # ({x-version-update-end}) @@ -447,4 +447,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc_contact]: mailto:opencode@microsoft.com [performance_tuning]: https://github.com/Azure/azure-sdk-for-java/wiki/Performance-Tuning -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fstorage%2Fazure-storage-file-datalake%2FREADME.png) + diff --git a/sdk/storage/azure-storage-file-datalake/pom.xml b/sdk/storage/azure-storage-file-datalake/pom.xml index 45fad0dd39dd..a7ea5d8aeb32 100644 --- a/sdk/storage/azure-storage-file-datalake/pom.xml +++ b/sdk/storage/azure-storage-file-datalake/pom.xml @@ -13,7 +13,7 @@ com.azure azure-storage-file-datalake - 12.23.0-beta.1 + 12.23.0 Microsoft Azure client library for File Storage Data Lake This module contains client library for Microsoft Azure File Storage Data Lake. @@ -66,22 +66,22 @@ com.azure azure-xml - 1.1.0 + 1.2.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-storage-blob - 12.30.0-beta.1 + 12.30.0 + 12.29.0 tests test-jar test @@ -105,13 +105,13 @@ com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test @@ -146,7 +146,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 ${AZURE_STORAGE_SAS_SERVICE_VERSION} diff --git a/sdk/storage/azure-storage-file-datalake/src/main/java/com/azure/storage/file/datalake/DataLakeServiceVersion.java b/sdk/storage/azure-storage-file-datalake/src/main/java/com/azure/storage/file/datalake/DataLakeServiceVersion.java index a4444194cad1..483bb0f936a0 100644 --- a/sdk/storage/azure-storage-file-datalake/src/main/java/com/azure/storage/file/datalake/DataLakeServiceVersion.java +++ b/sdk/storage/azure-storage-file-datalake/src/main/java/com/azure/storage/file/datalake/DataLakeServiceVersion.java @@ -132,7 +132,12 @@ public enum DataLakeServiceVersion implements ServiceVersion { /** * Service version {@code 2025-01-05}. */ - V2025_01_05("2025-01-05"); + V2025_01_05("2025-01-05"), + + /** + * Service version {@code 2025-05-05}. + */ + V2025_05_05("2025-05-05"); private final String version; @@ -154,6 +159,6 @@ public String getVersion() { * @return the latest {@link DataLakeServiceVersion} */ public static DataLakeServiceVersion getLatest() { - return V2025_01_05; + return V2025_05_05; } } diff --git a/sdk/storage/azure-storage-file-datalake/src/main/java/com/azure/storage/file/datalake/implementation/util/TransformUtils.java b/sdk/storage/azure-storage-file-datalake/src/main/java/com/azure/storage/file/datalake/implementation/util/TransformUtils.java index f3329bb5362b..0d9923aedde3 100644 --- a/sdk/storage/azure-storage-file-datalake/src/main/java/com/azure/storage/file/datalake/implementation/util/TransformUtils.java +++ b/sdk/storage/azure-storage-file-datalake/src/main/java/com/azure/storage/file/datalake/implementation/util/TransformUtils.java @@ -62,6 +62,8 @@ public static BlobServiceVersion toBlobServiceVersion(DataLakeServiceVersion ver return BlobServiceVersion.V2024_11_04; } else if (DataLakeServiceVersion.V2025_01_05.ordinal() == version.ordinal()) { return BlobServiceVersion.V2025_01_05; + } else if (DataLakeServiceVersion.V2025_05_05.ordinal() == version.ordinal()) { + return BlobServiceVersion.V2025_05_05; } return null; diff --git a/sdk/storage/azure-storage-file-datalake/swagger/README.md b/sdk/storage/azure-storage-file-datalake/swagger/README.md index 8fab00739a0f..ab6afd59a441 100644 --- a/sdk/storage/azure-storage-file-datalake/swagger/README.md +++ b/sdk/storage/azure-storage-file-datalake/swagger/README.md @@ -112,5 +112,5 @@ directive: ``` -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fstorage%2Fazure-storage-file-datalake%2Fswagger%2FREADME.png) + diff --git a/sdk/storage/azure-storage-file-share-stress/pom.xml b/sdk/storage/azure-storage-file-share-stress/pom.xml index a0fca7e750cc..da6776fcd092 100644 --- a/sdk/storage/azure-storage-file-share-stress/pom.xml +++ b/sdk/storage/azure-storage-file-share-stress/pom.xml @@ -30,17 +30,17 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-storage-file-share - 12.26.0-beta.1 + 12.26.0 com.azure @@ -51,24 +51,24 @@ com.azure - azure-monitor-opentelemetry-exporter - 1.0.0-beta.31 + azure-monitor-opentelemetry-autoconfigure + 1.0.0 io.opentelemetry.instrumentation opentelemetry-runtime-telemetry-java8 - 2.9.0-alpha + 2.12.0-alpha io.opentelemetry.instrumentation opentelemetry-logback-appender-1.0 - 2.9.0-alpha + 2.12.0-alpha com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.52 + 1.0.0-beta.56 com.azure diff --git a/sdk/storage/azure-storage-file-share/CHANGELOG.md b/sdk/storage/azure-storage-file-share/CHANGELOG.md index 5bfb166a9b9e..3636927c5362 100644 --- a/sdk/storage/azure-storage-file-share/CHANGELOG.md +++ b/sdk/storage/azure-storage-file-share/CHANGELOG.md @@ -1,15 +1,48 @@ # Release History -## 12.26.0-beta.1 (Unreleased) +## 12.26.0 (2025-03-11) ### Features Added +- Added support for NFS over REST. +- Added support for service version 2025-05-05. ### Breaking Changes +- The following APIs no longer send the x-ms-file-permission, x-ms-file-attributes, x-ms-file-creation-time, and x-ms-file-last-write-time request headers by default. These headers have been optional in the REST API since x-ms-version 2021-06-08: + - ShareDirectoryClient/ShareDirectoryAsyncClient.createWithResponse() + - ShareDirectoryClient/ShareDirectoryAsyncClient.setPropertiesWithResponse() + - ShareFileClient/ShareFileAsyncClient.createWithResponse() + - ShareFileClient/ShareFileAsyncClient.beginCopy() + - ShareFileClient/ShareFileAsyncClient.setPropertiesWithResponse() -### Bugs Fixed +### Other Changes + +#### Dependency Updates +- Upgraded `azure-storage-common` from `12.28.1` to version `12.29.0`. + +## 12.25.2 (2025-03-03) ### Other Changes +#### Dependency Updates +- Upgraded `azure-xml` from `1.1.0` to version `1.2.0`. +- Upgraded `azure-storage-common` from `12.28.0` to version `12.29.0-beta.2`. +- Upgraded `azure-core` from `1.54.0` to version `1.55.2`. +- Upgraded `azure-core-http-netty` from `1.15.6` to version `1.15.10`. + +## 12.26.0-beta.1 (2025-02-11) + +### Features Added +- Added support for NFS over REST. +- Added support for service version 2025-05-05. + +### Breaking Changes +- The following APIs no longer send the x-ms-file-permission, x-ms-file-attributes, x-ms-file-creation-time, and x-ms-file-last-write-time request headers by default. These headers have been optional in the REST API since x-ms-version 2021-06-08: + - ShareDirectoryClient/ShareDirectoryAsyncClient.createWithResponse() + - ShareDirectoryClient/ShareDirectoryAsyncClient.setPropertiesWithResponse() + - ShareFileClient/ShareFileAsyncClient.createWithResponse() + - ShareFileClient/ShareFileAsyncClient.beginCopy() + - ShareFileClient/ShareFileAsyncClient.setPropertiesWithResponse() + ## 12.25.1 (2024-12-04) ### Bugs Fixed diff --git a/sdk/storage/azure-storage-file-share/README.md b/sdk/storage/azure-storage-file-share/README.md index 51c3853570ef..e243337cf2bd 100644 --- a/sdk/storage/azure-storage-file-share/README.md +++ b/sdk/storage/azure-storage-file-share/README.md @@ -60,7 +60,7 @@ add the direct dependency to your project as follows. com.azure azure-storage-file-share - 12.25.1 + 12.26.0 ``` [//]: # ({x-version-update-end}) @@ -601,4 +601,4 @@ For details on contributing to this repository, see the [contributing guide](htt [samples]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/storage/azure-storage-file-share/src/samples [performance_tuning]: https://github.com/Azure/azure-sdk-for-java/wiki/Performance-Tuning -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fstorage%2Fazure-storage-file-share%2FREADME.png) + diff --git a/sdk/storage/azure-storage-file-share/assets.json b/sdk/storage/azure-storage-file-share/assets.json index f14509bcc830..fed144c90af2 100644 --- a/sdk/storage/azure-storage-file-share/assets.json +++ b/sdk/storage/azure-storage-file-share/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "java", "TagPrefix": "java/storage/azure-storage-file-share", - "Tag": "java/storage/azure-storage-file-share_1ec39c35ed" + "Tag": "java/storage/azure-storage-file-share_793c5e10e5" } diff --git a/sdk/storage/azure-storage-file-share/pom.xml b/sdk/storage/azure-storage-file-share/pom.xml index dd4d5eb7acb4..83e6e018cd85 100644 --- a/sdk/storage/azure-storage-file-share/pom.xml +++ b/sdk/storage/azure-storage-file-share/pom.xml @@ -13,7 +13,7 @@ com.azure azure-storage-file-share - 12.26.0-beta.1 + 12.26.0 Microsoft Azure client library for File Share Storage This module contains client library for Microsoft Azure File Share Storage. @@ -66,28 +66,28 @@ com.azure azure-xml - 1.1.0 + 1.2.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-storage-common - 12.29.0-beta.1 + 12.29.0 com.azure azure-storage-common - 12.29.0-beta.1 + 12.29.0 tests test-jar test @@ -106,19 +106,19 @@ com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-storage-blob - 12.30.0-beta.1 + 12.30.0 test @@ -173,7 +173,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 ${AZURE_STORAGE_SAS_SERVICE_VERSION} diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/FileSmbProperties.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/FileSmbProperties.java index 3ae99da78cb3..2be1ac93c972 100644 --- a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/FileSmbProperties.java +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/FileSmbProperties.java @@ -202,6 +202,33 @@ String getFileChangeTimeString() { return fileChangeTime == null ? null : parseFileSMBDate(fileChangeTime); } + /** + * Gets the string representation of the file's {@link NtfsFileAttributes} or null if no value is set. + * + * @return The value of the file's {@link NtfsFileAttributes}. + */ + String getNtfsFileAttributesString() { + return ntfsFileAttributes == null ? null : NtfsFileAttributes.toString(ntfsFileAttributes); + } + + /** + * Gets the string representation of the file's creation time or null if no value is set. + * + * @return The value of the file's creation time. + */ + String getFileCreationTimeString() { + return fileCreationTime == null ? null : parseFileSMBDate(fileCreationTime); + } + + /** + * Gets the string representation of the file's last write time or null if no value is set. + * + * @return The value of the file's last write time. + */ + String getFileLastWriteTimeString() { + return fileLastWriteTime == null ? null : parseFileSMBDate(fileLastWriteTime); + } + /** * Given an OffsetDateTime, generates a {@code String} representing a date in the format needed for * file SMB properties diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/ShareAsyncClient.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/ShareAsyncClient.java index 71f5ae2666c2..ca38096b84ac 100644 --- a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/ShareAsyncClient.java +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/ShareAsyncClient.java @@ -1693,8 +1693,8 @@ Mono> createFileWithResponse(String fileName, lon Map metadata, ShareRequestConditions requestConditions, Context context) { ShareFileAsyncClient shareFileAsyncClient = getFileClient(fileName); return shareFileAsyncClient - .createWithResponse(maxSize, httpHeaders, smbProperties, filePermission, null, metadata, requestConditions, - context) + .createWithResponse(maxSize, httpHeaders, smbProperties, filePermission, null, null, metadata, + requestConditions, context) .map(response -> new SimpleResponse<>(response, shareFileAsyncClient)); } diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/ShareDirectoryAsyncClient.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/ShareDirectoryAsyncClient.java index 756b149e8156..da1df0d1321a 100644 --- a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/ShareDirectoryAsyncClient.java +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/ShareDirectoryAsyncClient.java @@ -31,6 +31,7 @@ import com.azure.storage.file.share.implementation.util.ShareSasImplUtil; import com.azure.storage.file.share.models.CloseHandlesInfo; import com.azure.storage.file.share.models.FilePermissionFormat; +import com.azure.storage.file.share.models.FilePosixProperties; import com.azure.storage.file.share.models.HandleItem; import com.azure.storage.file.share.models.NtfsFileAttributes; import com.azure.storage.file.share.models.ShareDirectoryInfo; @@ -39,6 +40,7 @@ import com.azure.storage.file.share.models.ShareErrorCode; import com.azure.storage.file.share.models.ShareFileHttpHeaders; import com.azure.storage.file.share.models.ShareFileItem; +import com.azure.storage.file.share.models.ShareFilePermission; import com.azure.storage.file.share.models.ShareRequestConditions; import com.azure.storage.file.share.models.ShareStorageException; import com.azure.storage.file.share.options.ShareDirectoryCreateOptions; @@ -310,7 +312,8 @@ public Mono create() { public Mono> createWithResponse(FileSmbProperties smbProperties, String filePermission, Map metadata) { try { - return withContext(context -> createWithResponse(smbProperties, filePermission, null, metadata, context)); + return withContext( + context -> createWithResponse(smbProperties, filePermission, null, null, metadata, context)); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } @@ -350,32 +353,28 @@ public Mono> createWithResponse(FileSmbProperties s public Mono> createWithResponse(ShareDirectoryCreateOptions options) { try { return withContext(context -> createWithResponse(options.getSmbProperties(), options.getFilePermission(), - options.getFilePermissionFormat(), options.getMetadata(), context)); + options.getFilePermissionFormat(), options.getPosixProperties(), options.getMetadata(), context)); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } } Mono> createWithResponse(FileSmbProperties smbProperties, String filePermission, - FilePermissionFormat filePermissionFormat, Map metadata, Context context) { - FileSmbProperties properties = smbProperties == null ? new FileSmbProperties() : smbProperties; + FilePermissionFormat filePermissionFormat, FilePosixProperties posixProperties, Map metadata, + Context context) { + context = context == null ? Context.NONE : context; + smbProperties = smbProperties == null ? new FileSmbProperties() : smbProperties; + posixProperties = posixProperties == null ? new FilePosixProperties() : posixProperties; // Checks that file permission and file permission key are valid - ModelHelper.validateFilePermissionAndKey(filePermission, properties.getFilePermissionKey()); - - // If file permission and file permission key are both not set then set default value - filePermission = properties.setFilePermission(filePermission, FileConstants.FILE_PERMISSION_INHERIT); - String filePermissionKey = properties.getFilePermissionKey(); - - String fileAttributes = properties.setNtfsFileAttributes(FileConstants.FILE_ATTRIBUTES_NONE); - String fileCreationTime = properties.setFileCreationTime(FileConstants.FILE_TIME_NOW); - String fileLastWriteTime = properties.setFileLastWriteTime(FileConstants.FILE_TIME_NOW); - String fileChangeTime = properties.getFileChangeTimeString(); - context = context == null ? Context.NONE : context; + ModelHelper.validateFilePermissionAndKey(filePermission, smbProperties.getFilePermissionKey()); return azureFileStorageClient.getDirectories() - .createWithResponseAsync(shareName, directoryPath, fileAttributes, null, metadata, filePermission, - filePermissionFormat, filePermissionKey, fileCreationTime, fileLastWriteTime, fileChangeTime, context) + .createWithResponseAsync(shareName, directoryPath, null, metadata, filePermission, filePermissionFormat, + smbProperties.getFilePermissionKey(), smbProperties.getNtfsFileAttributesString(), + smbProperties.getFileCreationTimeString(), smbProperties.getFileLastWriteTimeString(), + smbProperties.getFileChangeTimeString(), posixProperties.getOwner(), posixProperties.getGroup(), + posixProperties.getFileMode(), context) .map(ModelHelper::mapShareDirectoryInfo); } @@ -455,14 +454,15 @@ Mono> createIfNotExistsWithResponse(ShareDirectoryC Context context) { try { options = options == null ? new ShareDirectoryCreateOptions() : options; - return createWithResponse(options.getSmbProperties(), options.getFilePermission(), null, - options.getMetadata(), context).onErrorResume( - t -> t instanceof ShareStorageException && ((ShareStorageException) t).getStatusCode() == 409, - t -> { - HttpResponse response = ((ShareStorageException) t).getResponse(); - return Mono.just(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), - response.getHeaders(), null)); - }); + return createWithResponse(options.getSmbProperties(), options.getFilePermission(), + options.getFilePermissionFormat(), options.getPosixProperties(), options.getMetadata(), context) + .onErrorResume( + t -> t instanceof ShareStorageException && ((ShareStorageException) t).getStatusCode() == 409, + t -> { + HttpResponse response = ((ShareStorageException) t).getResponse(); + return Mono.just(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), + response.getHeaders(), null)); + }); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } @@ -729,7 +729,8 @@ public Mono setProperties(FileSmbProperties smbProperties, S public Mono> setPropertiesWithResponse(FileSmbProperties smbProperties, String filePermission) { try { - return withContext(context -> setPropertiesWithResponse(smbProperties, filePermission, null, context)); + return withContext( + context -> setPropertiesWithResponse(smbProperties, filePermission, null, null, context)); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } @@ -763,35 +764,31 @@ public Mono> setPropertiesWithResponse(FileSmbPrope @ServiceMethod(returns = ReturnType.SINGLE) public Mono> setPropertiesWithResponse(ShareDirectorySetPropertiesOptions options) { try { - return withContext(context -> setPropertiesWithResponse(options.getSmbProperties(), - options.getFilePermissions().getPermission(), options.getFilePermissions().getPermissionFormat(), - context)); + ShareFilePermission filePermission + = options.getFilePermissions() == null ? new ShareFilePermission() : options.getFilePermissions(); + return withContext( + context -> setPropertiesWithResponse(options.getSmbProperties(), filePermission.getPermission(), + filePermission.getPermissionFormat(), options.getPosixProperties(), context)); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } } Mono> setPropertiesWithResponse(FileSmbProperties smbProperties, String filePermission, - FilePermissionFormat filePermissionFormat, Context context) { - - FileSmbProperties properties = smbProperties == null ? new FileSmbProperties() : smbProperties; + FilePermissionFormat filePermissionFormat, FilePosixProperties posixProperties, Context context) { + context = context == null ? Context.NONE : context; + smbProperties = smbProperties == null ? new FileSmbProperties() : smbProperties; + posixProperties = posixProperties == null ? new FilePosixProperties() : posixProperties; // Checks that file permission and file permission key are valid - ModelHelper.validateFilePermissionAndKey(filePermission, properties.getFilePermissionKey()); + ModelHelper.validateFilePermissionAndKey(filePermission, smbProperties.getFilePermissionKey()); - // If file permission and file permission key are both not set then set default value - filePermission = properties.setFilePermission(filePermission, FileConstants.PRESERVE); - String filePermissionKey = properties.getFilePermissionKey(); - - String fileAttributes = properties.setNtfsFileAttributes(FileConstants.PRESERVE); - String fileCreationTime = properties.setFileCreationTime(FileConstants.PRESERVE); - String fileLastWriteTime = properties.setFileLastWriteTime(FileConstants.PRESERVE); - String fileChangeTime = properties.getFileChangeTimeString(); - - context = context == null ? Context.NONE : context; return azureFileStorageClient.getDirectories() - .setPropertiesWithResponseAsync(shareName, directoryPath, fileAttributes, null, filePermission, - filePermissionFormat, filePermissionKey, fileCreationTime, fileLastWriteTime, fileChangeTime, context) + .setPropertiesWithResponseAsync(shareName, directoryPath, null, filePermission, filePermissionFormat, + smbProperties.getFilePermissionKey(), smbProperties.getNtfsFileAttributesString(), + smbProperties.getFileCreationTimeString(), smbProperties.getFileLastWriteTimeString(), + smbProperties.getFileChangeTimeString(), posixProperties.getOwner(), posixProperties.getGroup(), + posixProperties.getFileMode(), context) .map(ModelHelper::mapSetPropertiesResponse); } @@ -1388,7 +1385,7 @@ public Mono> createSubdirectoryWithResponse( Mono> createSubdirectoryWithResponse(String subdirectoryName, FileSmbProperties smbProperties, String filePermission, Map metadata, Context context) { ShareDirectoryAsyncClient createSubClient = getSubdirectoryClient(subdirectoryName); - return createSubClient.createWithResponse(smbProperties, filePermission, null, metadata, context) + return createSubClient.createWithResponse(smbProperties, filePermission, null, null, metadata, context) .map(response -> new SimpleResponse<>(response, createSubClient)); } @@ -1774,8 +1771,8 @@ Mono> createFileWithResponse(String fileName, lon Map metadata, ShareRequestConditions requestConditions, Context context) { ShareFileAsyncClient shareFileAsyncClient = getFileClient(fileName); return shareFileAsyncClient - .createWithResponse(maxSize, httpHeaders, smbProperties, filePermission, null, metadata, requestConditions, - context) + .createWithResponse(maxSize, httpHeaders, smbProperties, filePermission, null, null, metadata, + requestConditions, context) .map(response -> new SimpleResponse<>(response, shareFileAsyncClient)); } diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/ShareDirectoryClient.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/ShareDirectoryClient.java index 2d5eb714c9aa..fc24e6e8fe6d 100644 --- a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/ShareDirectoryClient.java +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/ShareDirectoryClient.java @@ -38,6 +38,7 @@ import com.azure.storage.file.share.implementation.util.ModelHelper; import com.azure.storage.file.share.implementation.util.ShareSasImplUtil; import com.azure.storage.file.share.models.CloseHandlesInfo; +import com.azure.storage.file.share.models.FilePosixProperties; import com.azure.storage.file.share.models.HandleItem; import com.azure.storage.file.share.models.NtfsFileAttributes; import com.azure.storage.file.share.models.ShareDirectoryInfo; @@ -47,6 +48,7 @@ import com.azure.storage.file.share.models.ShareFileHttpHeaders; import com.azure.storage.file.share.models.ShareFileInfo; import com.azure.storage.file.share.models.ShareFileItem; +import com.azure.storage.file.share.models.ShareFilePermission; import com.azure.storage.file.share.models.ShareRequestConditions; import com.azure.storage.file.share.models.ShareStorageException; import com.azure.storage.file.share.options.ShareDirectoryCreateOptions; @@ -342,26 +344,23 @@ public Response createWithResponse(ShareDirectoryCreateOptio Context context) { Context finalContext = context == null ? Context.NONE : context; ShareDirectoryCreateOptions finalOptions = options == null ? new ShareDirectoryCreateOptions() : options; - FileSmbProperties properties + + FileSmbProperties smbProperties = finalOptions.getSmbProperties() == null ? new FileSmbProperties() : finalOptions.getSmbProperties(); + FilePosixProperties fileposixProperties + = finalOptions.getPosixProperties() == null ? new FilePosixProperties() : finalOptions.getPosixProperties(); // Checks that file permission and file permission key are valid - ModelHelper.validateFilePermissionAndKey(finalOptions.getFilePermission(), properties.getFilePermissionKey()); - - // If file permission and file permission key are both not set then set default value - String finalFilePermission - = properties.setFilePermission(finalOptions.getFilePermission(), FileConstants.FILE_PERMISSION_INHERIT); - String filePermissionKey = properties.getFilePermissionKey(); - - String fileAttributes = properties.setNtfsFileAttributes(FileConstants.FILE_ATTRIBUTES_NONE); - String fileCreationTime = properties.setFileCreationTime(FileConstants.FILE_TIME_NOW); - String fileLastWriteTime = properties.setFileLastWriteTime(FileConstants.FILE_TIME_NOW); - String fileChangeTime = properties.getFileChangeTimeString(); + ModelHelper.validateFilePermissionAndKey(finalOptions.getFilePermission(), + smbProperties.getFilePermissionKey()); Callable> operation = () -> azureFileStorageClient.getDirectories() - .createWithResponse(shareName, directoryPath, fileAttributes, null, finalOptions.getMetadata(), - finalFilePermission, finalOptions.getFilePermissionFormat(), filePermissionKey, fileCreationTime, - fileLastWriteTime, fileChangeTime, finalContext); + .createWithResponse(shareName, directoryPath, null, finalOptions.getMetadata(), + finalOptions.getFilePermission(), finalOptions.getFilePermissionFormat(), + smbProperties.getFilePermissionKey(), smbProperties.getNtfsFileAttributesString(), + smbProperties.getFileCreationTimeString(), smbProperties.getFileLastWriteTimeString(), + smbProperties.getFileChangeTimeString(), fileposixProperties.getOwner(), fileposixProperties.getGroup(), + fileposixProperties.getFileMode(), finalContext); return ModelHelper.mapShareDirectoryInfo(sendRequest(operation, timeout, ShareStorageException.class)); } @@ -690,26 +689,8 @@ public ShareDirectoryInfo setProperties(FileSmbProperties smbProperties, String @ServiceMethod(returns = ReturnType.SINGLE) public Response setPropertiesWithResponse(FileSmbProperties smbProperties, String filePermission, Duration timeout, Context context) { - Context finalContext = context == null ? Context.NONE : context; - smbProperties = smbProperties == null ? new FileSmbProperties() : smbProperties; - - // Checks that file permission and file permission key are valid - ModelHelper.validateFilePermissionAndKey(filePermission, smbProperties.getFilePermissionKey()); - - // If file permission and file permission key are both not set then set default value - String finalFilePermission = smbProperties.setFilePermission(filePermission, FileConstants.PRESERVE); - String filePermissionKey = smbProperties.getFilePermissionKey(); - - String fileAttributes = smbProperties.setNtfsFileAttributes(FileConstants.PRESERVE); - String fileCreationTime = smbProperties.setFileCreationTime(FileConstants.PRESERVE); - String fileLastWriteTime = smbProperties.setFileLastWriteTime(FileConstants.PRESERVE); - String fileChangeTime = smbProperties.getFileChangeTimeString(); - Callable> operation - = () -> this.azureFileStorageClient.getDirectories() - .setPropertiesWithResponse(shareName, directoryPath, fileAttributes, null, finalFilePermission, null, - filePermissionKey, fileCreationTime, fileLastWriteTime, fileChangeTime, finalContext); - - return ModelHelper.mapSetPropertiesResponse(sendRequest(operation, timeout, ShareStorageException.class)); + return setPropertiesWithResponse(new ShareDirectorySetPropertiesOptions().setSmbProperties(smbProperties) + .setFilePermissions(new ShareFilePermission().setPermission(filePermission)), timeout, context); } /** @@ -744,27 +725,27 @@ public Response setPropertiesWithResponse(FileSmbProperties public Response setPropertiesWithResponse(ShareDirectorySetPropertiesOptions options, Duration timeout, Context context) { Context finalContext = context == null ? Context.NONE : context; - FileSmbProperties smbProperties = options.getSmbProperties(); - smbProperties = smbProperties == null ? new FileSmbProperties() : smbProperties; + ShareDirectorySetPropertiesOptions finalOptions + = options == null ? new ShareDirectorySetPropertiesOptions() : options; - // Checks that file permission and file permission key are valid - ModelHelper.validateFilePermissionAndKey(options.getFilePermissions().getPermission(), - smbProperties.getFilePermissionKey()); + FileSmbProperties smbProperties + = finalOptions.getSmbProperties() == null ? new FileSmbProperties() : finalOptions.getSmbProperties(); + FilePosixProperties fileposixProperties + = finalOptions.getPosixProperties() == null ? new FilePosixProperties() : finalOptions.getPosixProperties(); + ShareFilePermission filePermission + = finalOptions.getFilePermissions() == null ? new ShareFilePermission() : finalOptions.getFilePermissions(); - // If file permission and file permission key are both not set then set default value - String finalFilePermission - = smbProperties.setFilePermission(options.getFilePermissions().getPermission(), FileConstants.PRESERVE); - String filePermissionKey = smbProperties.getFilePermissionKey(); + // Checks that file permission and file permission key are valid + ModelHelper.validateFilePermissionAndKey(filePermission.getPermission(), smbProperties.getFilePermissionKey()); - String fileAttributes = smbProperties.setNtfsFileAttributes(FileConstants.PRESERVE); - String fileCreationTime = smbProperties.setFileCreationTime(FileConstants.PRESERVE); - String fileLastWriteTime = smbProperties.setFileLastWriteTime(FileConstants.PRESERVE); - String fileChangeTime = smbProperties.getFileChangeTimeString(); Callable> operation = () -> this.azureFileStorageClient.getDirectories() - .setPropertiesWithResponse(shareName, directoryPath, fileAttributes, null, finalFilePermission, - options.getFilePermissions().getPermissionFormat(), filePermissionKey, fileCreationTime, - fileLastWriteTime, fileChangeTime, finalContext); + .setPropertiesWithResponse(shareName, directoryPath, null, filePermission.getPermission(), + filePermission.getPermissionFormat(), smbProperties.getFilePermissionKey(), + smbProperties.getNtfsFileAttributesString(), smbProperties.getFileCreationTimeString(), + smbProperties.getFileLastWriteTimeString(), smbProperties.getFileChangeTimeString(), + fileposixProperties.getOwner(), fileposixProperties.getGroup(), fileposixProperties.getFileMode(), + finalContext); return ModelHelper.mapSetPropertiesResponse(sendRequest(operation, timeout, ShareStorageException.class)); } diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/ShareFileAsyncClient.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/ShareFileAsyncClient.java index ca612808fdc8..976d60a14306 100644 --- a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/ShareFileAsyncClient.java +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/ShareFileAsyncClient.java @@ -48,6 +48,7 @@ import com.azure.storage.file.share.models.CopyableFileSmbPropertiesList; import com.azure.storage.file.share.models.DownloadRetryOptions; import com.azure.storage.file.share.models.FilePermissionFormat; +import com.azure.storage.file.share.models.FilePosixProperties; import com.azure.storage.file.share.models.HandleItem; import com.azure.storage.file.share.models.NtfsFileAttributes; import com.azure.storage.file.share.models.PermissionCopyModeType; @@ -59,6 +60,7 @@ import com.azure.storage.file.share.models.ShareFileHttpHeaders; import com.azure.storage.file.share.models.ShareFileInfo; import com.azure.storage.file.share.models.ShareFileMetadataInfo; +import com.azure.storage.file.share.models.ShareFilePermission; import com.azure.storage.file.share.models.ShareFileProperties; import com.azure.storage.file.share.models.ShareFileRange; import com.azure.storage.file.share.models.ShareFileRangeList; @@ -69,6 +71,7 @@ import com.azure.storage.file.share.models.ShareRequestConditions; import com.azure.storage.file.share.models.ShareStorageException; import com.azure.storage.file.share.options.ShareFileCopyOptions; +import com.azure.storage.file.share.options.ShareFileCreateHardLinkOptions; import com.azure.storage.file.share.options.ShareFileCreateOptions; import com.azure.storage.file.share.options.ShareFileDownloadOptions; import com.azure.storage.file.share.options.ShareFileListRangesDiffOptions; @@ -408,7 +411,7 @@ public Mono> createWithResponse(long maxSize, ShareFileH ShareRequestConditions requestConditions) { try { return withContext(context -> createWithResponse(maxSize, httpHeaders, smbProperties, filePermission, null, - metadata, requestConditions, context)); + null, metadata, requestConditions, context)); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } @@ -458,9 +461,10 @@ public Mono> createWithResponse(long maxSize, ShareFileH @ServiceMethod(returns = ReturnType.SINGLE) public Mono> createWithResponse(ShareFileCreateOptions options) { try { + StorageImplUtils.assertNotNull("options", options); return withContext(context -> createWithResponse(options.getSize(), options.getShareFileHttpHeaders(), options.getSmbProperties(), options.getFilePermission(), options.getFilePermissionFormat(), - options.getMetadata(), options.getRequestConditions(), context)); + options.getPosixProperties(), options.getMetadata(), options.getRequestConditions(), context)); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } @@ -468,26 +472,23 @@ public Mono> createWithResponse(ShareFileCreateOptions o Mono> createWithResponse(long maxSize, ShareFileHttpHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission, FilePermissionFormat filePermissionFormat, - Map metadata, ShareRequestConditions requestConditions, Context context) { + FilePosixProperties fileposixProperties, Map metadata, ShareRequestConditions requestConditions, + Context context) { + context = context == null ? Context.NONE : context; requestConditions = requestConditions == null ? new ShareRequestConditions() : requestConditions; smbProperties = smbProperties == null ? new FileSmbProperties() : smbProperties; + fileposixProperties = fileposixProperties == null ? new FilePosixProperties() : fileposixProperties; // Checks that file permission and file permission key are valid ModelHelper.validateFilePermissionAndKey(filePermission, smbProperties.getFilePermissionKey()); - // If file permission and file permission key are both not set then set default value - filePermission = smbProperties.setFilePermission(filePermission, FileConstants.FILE_PERMISSION_INHERIT); - String filePermissionKey = smbProperties.getFilePermissionKey(); - - String fileAttributes = smbProperties.setNtfsFileAttributes(FileConstants.FILE_ATTRIBUTES_NONE); - String fileCreationTime = smbProperties.setFileCreationTime(FileConstants.FILE_TIME_NOW); - String fileLastWriteTime = smbProperties.setFileLastWriteTime(FileConstants.FILE_TIME_NOW); - String fileChangeTime = smbProperties.getFileChangeTimeString(); - return azureFileStorageClient.getFiles() - .createWithResponseAsync(shareName, filePath, maxSize, fileAttributes, null, metadata, filePermission, - filePermissionFormat, filePermissionKey, fileCreationTime, fileLastWriteTime, fileChangeTime, - requestConditions.getLeaseId(), httpHeaders, context) + .createWithResponseAsync(shareName, filePath, maxSize, null, metadata, filePermission, filePermissionFormat, + smbProperties.getFilePermissionKey(), smbProperties.getNtfsFileAttributesString(), + smbProperties.getFileCreationTimeString(), smbProperties.getFileLastWriteTimeString(), + smbProperties.getFileChangeTimeString(), requestConditions.getLeaseId(), fileposixProperties.getOwner(), + fileposixProperties.getGroup(), fileposixProperties.getFileMode(), fileposixProperties.getFileType(), + httpHeaders, context) .map(ModelHelper::createFileInfoResponse); } @@ -699,18 +700,15 @@ public PollerFlux beginCopy(String sourceUrl, ShareFile "Both CopyableFileSmbPropertiesList.isSetChangedOn and smbProperties.fileChangeTime cannot be set.")); } - String fileAttributes = list.isFileAttributes() - ? FileConstants.COPY_SOURCE - : NtfsFileAttributes.toString(tempSmbProperties.getNtfsFileAttributes()); - String fileCreationTime = list.isCreatedOn() - ? FileConstants.COPY_SOURCE - : FileSmbProperties.parseFileSMBDate(tempSmbProperties.getFileCreationTime()); + String fileAttributes + = list.isFileAttributes() ? null : NtfsFileAttributes.toString(tempSmbProperties.getNtfsFileAttributes()); + String fileCreationTime + = list.isCreatedOn() ? null : FileSmbProperties.parseFileSMBDate(tempSmbProperties.getFileCreationTime()); String fileLastWriteTime = list.isLastWrittenOn() - ? FileConstants.COPY_SOURCE + ? null : FileSmbProperties.parseFileSMBDate(tempSmbProperties.getFileLastWriteTime()); - String fileChangedOnTime = list.isChangedOn() - ? FileConstants.COPY_SOURCE - : FileSmbProperties.parseFileSMBDate(tempSmbProperties.getFileChangeTime()); + String fileChangedOnTime + = list.isChangedOn() ? null : FileSmbProperties.parseFileSMBDate(tempSmbProperties.getFileChangeTime()); final CopyFileSmbInfo copyFileSmbInfo = new CopyFileSmbInfo().setFilePermissionCopyMode(options.getPermissionCopyModeType()) @@ -723,13 +721,18 @@ public PollerFlux beginCopy(String sourceUrl, ShareFile final String copySource = Utility.encodeUrlPath(sourceUrl); + FilePosixProperties fileposixProperties + = options.getPosixProperties() == null ? new FilePosixProperties() : options.getPosixProperties(); + return new PollerFlux<>(interval, (pollingContext) -> { try { return withContext(context -> azureFileStorageClient.getFiles() .startCopyWithResponseAsync(shareName, filePath, copySource, null, options.getMetadata(), options.getFilePermission(), options.getFilePermissionFormat(), - tempSmbProperties.getFilePermissionKey(), finalRequestConditions.getLeaseId(), copyFileSmbInfo, - context)).map(response -> { + tempSmbProperties.getFilePermissionKey(), finalRequestConditions.getLeaseId(), + fileposixProperties.getOwner(), fileposixProperties.getGroup(), + fileposixProperties.getFileMode(), options.getModeCopyMode(), options.getOwnerCopyMode(), + copyFileSmbInfo, context)).map(response -> { final FilesStartCopyHeaders headers = response.getDeserializedHeaders(); copyId.set(headers.getXMsCopyId()); @@ -1706,7 +1709,7 @@ public Mono> setPropertiesWithResponse(long newFileSize, FileSmbProperties smbProperties, String filePermission, ShareRequestConditions requestConditions) { try { return withContext(context -> setPropertiesWithResponse(newFileSize, httpHeaders, smbProperties, - filePermission, null, requestConditions, context)); + filePermission, null, null, requestConditions, context)); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } @@ -1759,9 +1762,12 @@ public Mono> setPropertiesWithResponse(long newFileSize, @ServiceMethod(returns = ReturnType.SINGLE) public Mono> setPropertiesWithResponse(ShareFileSetPropertiesOptions options) { try { + StorageImplUtils.assertNotNull("options", options); + ShareFilePermission filePermission + = options.getFilePermissions() == null ? new ShareFilePermission() : options.getFilePermissions(); return withContext(context -> setPropertiesWithResponse(options.getSizeInBytes(), options.getHttpHeaders(), - options.getSmbProperties(), options.getFilePermissions().getPermission(), - options.getFilePermissions().getPermissionFormat(), options.getRequestConditions(), context)); + options.getSmbProperties(), filePermission.getPermission(), filePermission.getPermissionFormat(), + options.getPosixProperties(), options.getRequestConditions(), context)); } catch (RuntimeException ex) { return monoError(LOGGER, ex); } @@ -1769,27 +1775,21 @@ public Mono> setPropertiesWithResponse(ShareFileSetPrope Mono> setPropertiesWithResponse(long newFileSize, ShareFileHttpHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission, FilePermissionFormat filePermissionFormat, - ShareRequestConditions requestConditions, Context context) { + FilePosixProperties fileposixProperties, ShareRequestConditions requestConditions, Context context) { + context = context == null ? Context.NONE : context; requestConditions = requestConditions == null ? new ShareRequestConditions() : requestConditions; smbProperties = smbProperties == null ? new FileSmbProperties() : smbProperties; + fileposixProperties = fileposixProperties == null ? new FilePosixProperties() : fileposixProperties; // Checks that file permission and file permission key are valid ModelHelper.validateFilePermissionAndKey(filePermission, smbProperties.getFilePermissionKey()); - // If file permission and file permission key are both not set then set default value - filePermission = smbProperties.setFilePermission(filePermission, FileConstants.PRESERVE); - String filePermissionKey = smbProperties.getFilePermissionKey(); - - String fileAttributes = smbProperties.setNtfsFileAttributes(FileConstants.PRESERVE); - String fileCreationTime = smbProperties.setFileCreationTime(FileConstants.PRESERVE); - String fileLastWriteTime = smbProperties.setFileLastWriteTime(FileConstants.PRESERVE); - String fileChangeTime = smbProperties.getFileChangeTimeString(); - context = context == null ? Context.NONE : context; - return azureFileStorageClient.getFiles() - .setHttpHeadersWithResponseAsync(shareName, filePath, fileAttributes, null, newFileSize, filePermission, - filePermissionFormat, filePermissionKey, fileCreationTime, fileLastWriteTime, fileChangeTime, - requestConditions.getLeaseId(), httpHeaders, context) + .setHttpHeadersWithResponseAsync(shareName, filePath, null, newFileSize, filePermission, + filePermissionFormat, smbProperties.getFilePermissionKey(), smbProperties.getNtfsFileAttributesString(), + smbProperties.getFileCreationTimeString(), smbProperties.getFileLastWriteTimeString(), + smbProperties.getFileChangeTimeString(), requestConditions.getLeaseId(), fileposixProperties.getOwner(), + fileposixProperties.getGroup(), fileposixProperties.getFileMode(), httpHeaders, context) .map(ModelHelper::setPropertiesResponse); } @@ -3342,4 +3342,59 @@ public String generateSas(ShareServiceSasSignatureValues shareServiceSasSignatur return new ShareSasImplUtil(shareServiceSasSignatureValues, getShareName(), getFilePath()) .generateSas(SasImplUtils.extractSharedKeyCredential(getHttpPipeline()), stringToSignHandler, context); } + + /** + * NFS only. Creates a hard link to the file specified by path. + * + *
        +     * hardLinkClient.createHardLink(sourceClient.getFilePath())
        +     *     .subscribe(result -> System.out.printf("Link count is is %s.",
        +     *         result.getPosixProperties().getLinkCount()));
        +     * 
        + * + * + * @param targetFile Path of the file to create the hard link to, not including the share. For example, + * {@code targetDirectory/targetSubDirectory/.../targetFile} + * @return A {@link Mono} containing a {@link ShareFileInfo} describing the state of the hard link. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createHardLink(String targetFile) { + return createHardLinkWithResponse(new ShareFileCreateHardLinkOptions(targetFile)).flatMap(FluxUtil::toMono); + } + + /** + * NFS only. Creates a hard link to the file specified by path. + * + *
        +     * ShareFileCreateHardLinkOptions options = new ShareFileCreateHardLinkOptions(sourceClient.getFilePath());
        +     * hardLinkClient.createHardLinkWithResponse(options)
        +     *     .subscribe(result -> System.out.printf("Link count is is %s.",
        +     *         result.getValue().getPosixProperties().getLinkCount()));
        +     * 
        + * + * + * @param options {@link ShareFileCreateHardLinkOptions} + * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains + * {@link ShareFileInfo} describing the state of the hard link. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createHardLinkWithResponse(ShareFileCreateHardLinkOptions options) { + try { + StorageImplUtils.assertNotNull("options", options); + return withContext(context -> createHardLinkWithResponse(options.getTargetFile(), + options.getRequestConditions(), context)); + } catch (RuntimeException ex) { + return monoError(LOGGER, ex); + } + } + + Mono> createHardLinkWithResponse(String targetFile, + ShareRequestConditions requestConditions, Context context) { + context = context == null ? Context.NONE : context; + requestConditions = requestConditions == null ? new ShareRequestConditions() : requestConditions; + return this.azureFileStorageClient.getFiles() + .createHardLinkWithResponseAsync(shareName, filePath, targetFile, null, null, + requestConditions.getLeaseId(), context) + .map(ModelHelper::createHardLinkResponse); + } } diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/ShareFileClient.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/ShareFileClient.java index 3ec24b973673..ac3be58399d2 100644 --- a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/ShareFileClient.java +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/ShareFileClient.java @@ -34,6 +34,7 @@ import com.azure.storage.file.share.implementation.AzureFileStorageImpl; import com.azure.storage.file.share.implementation.models.CopyFileSmbInfo; import com.azure.storage.file.share.implementation.models.DestinationLeaseAccessConditions; +import com.azure.storage.file.share.implementation.models.FilesCreateHardLinkHeaders; import com.azure.storage.file.share.implementation.models.FilesCreateHeaders; import com.azure.storage.file.share.implementation.models.FilesForceCloseHandlesHeaders; import com.azure.storage.file.share.implementation.models.FilesGetPropertiesHeaders; @@ -52,6 +53,7 @@ import com.azure.storage.file.share.models.CloseHandlesInfo; import com.azure.storage.file.share.models.CopyStatusType; import com.azure.storage.file.share.models.CopyableFileSmbPropertiesList; +import com.azure.storage.file.share.models.FilePosixProperties; import com.azure.storage.file.share.models.HandleItem; import com.azure.storage.file.share.models.NtfsFileAttributes; import com.azure.storage.file.share.models.PermissionCopyModeType; @@ -62,6 +64,7 @@ import com.azure.storage.file.share.models.ShareFileHttpHeaders; import com.azure.storage.file.share.models.ShareFileInfo; import com.azure.storage.file.share.models.ShareFileMetadataInfo; +import com.azure.storage.file.share.models.ShareFilePermission; import com.azure.storage.file.share.models.ShareFileProperties; import com.azure.storage.file.share.models.ShareFileRange; import com.azure.storage.file.share.models.ShareFileRangeList; @@ -72,6 +75,7 @@ import com.azure.storage.file.share.models.ShareRequestConditions; import com.azure.storage.file.share.models.ShareStorageException; import com.azure.storage.file.share.options.ShareFileCopyOptions; +import com.azure.storage.file.share.options.ShareFileCreateHardLinkOptions; import com.azure.storage.file.share.options.ShareFileCreateOptions; import com.azure.storage.file.share.options.ShareFileDownloadOptions; import com.azure.storage.file.share.options.ShareFileListRangesDiffOptions; @@ -462,29 +466,11 @@ public Response createWithResponse(long maxSize, ShareFileHttpHea public Response createWithResponse(long maxSize, ShareFileHttpHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission, Map metadata, ShareRequestConditions requestConditions, Duration timeout, Context context) { - Context finalContext = context == null ? Context.NONE : context; - ShareRequestConditions finalRequestConditions - = requestConditions == null ? new ShareRequestConditions() : requestConditions; - smbProperties = smbProperties == null ? new FileSmbProperties() : smbProperties; - - // Checks that file permission and file permission key are valid - ModelHelper.validateFilePermissionAndKey(filePermission, smbProperties.getFilePermissionKey()); - - // If file permission and file permission key are both not set then set default value - String finalFilePermission - = smbProperties.setFilePermission(filePermission, FileConstants.FILE_PERMISSION_INHERIT); - String filePermissionKey = smbProperties.getFilePermissionKey(); - - String fileAttributes = smbProperties.setNtfsFileAttributes(FileConstants.FILE_ATTRIBUTES_NONE); - String fileCreationTime = smbProperties.setFileCreationTime(FileConstants.FILE_TIME_NOW); - String fileLastWriteTime = smbProperties.setFileLastWriteTime(FileConstants.FILE_TIME_NOW); - String fileChangeTime = smbProperties.getFileChangeTimeString(); - Callable> operation = () -> this.azureFileStorageClient.getFiles() - .createWithResponse(shareName, filePath, maxSize, fileAttributes, null, metadata, finalFilePermission, null, - filePermissionKey, fileCreationTime, fileLastWriteTime, fileChangeTime, - finalRequestConditions.getLeaseId(), httpHeaders, finalContext); - - return ModelHelper.createFileInfoResponse(sendRequest(operation, timeout, ShareStorageException.class)); + return createWithResponse(new ShareFileCreateOptions(maxSize).setShareFileHttpHeaders(httpHeaders) + .setSmbProperties(smbProperties) + .setFilePermission(filePermission) + .setMetadata(metadata) + .setRequestConditions(requestConditions), timeout, context); } /** @@ -536,30 +522,27 @@ public Response createWithResponse(long maxSize, ShareFileHttpHea @ServiceMethod(returns = ReturnType.SINGLE) public Response createWithResponse(ShareFileCreateOptions options, Duration timeout, Context context) { + StorageImplUtils.assertNotNull("options", options); Context finalContext = context == null ? Context.NONE : context; - ShareRequestConditions requestConditions = options.getRequestConditions(); - ShareRequestConditions finalRequestConditions - = requestConditions == null ? new ShareRequestConditions() : requestConditions; - FileSmbProperties smbProperties = options.getSmbProperties(); - smbProperties = smbProperties == null ? new FileSmbProperties() : smbProperties; + ShareRequestConditions requestConditions + = options.getRequestConditions() == null ? new ShareRequestConditions() : options.getRequestConditions(); + + FileSmbProperties smbProperties + = options.getSmbProperties() == null ? new FileSmbProperties() : options.getSmbProperties(); + FilePosixProperties fileposixProperties + = options.getPosixProperties() == null ? new FilePosixProperties() : options.getPosixProperties(); // Checks that file permission and file permission key are valid ModelHelper.validateFilePermissionAndKey(options.getFilePermission(), smbProperties.getFilePermissionKey()); - // If file permission and file permission key are both not set then set default value - String finalFilePermission - = smbProperties.setFilePermission(options.getFilePermission(), FileConstants.FILE_PERMISSION_INHERIT); - String filePermissionKey = smbProperties.getFilePermissionKey(); - - String fileAttributes = smbProperties.setNtfsFileAttributes(FileConstants.FILE_ATTRIBUTES_NONE); - String fileCreationTime = smbProperties.setFileCreationTime(FileConstants.FILE_TIME_NOW); - String fileLastWriteTime = smbProperties.setFileLastWriteTime(FileConstants.FILE_TIME_NOW); - String fileChangeTime = smbProperties.getFileChangeTimeString(); Callable> operation = () -> this.azureFileStorageClient.getFiles() - .createWithResponse(shareName, filePath, options.getSize(), fileAttributes, null, options.getMetadata(), - finalFilePermission, options.getFilePermissionFormat(), filePermissionKey, fileCreationTime, - fileLastWriteTime, fileChangeTime, finalRequestConditions.getLeaseId(), - options.getShareFileHttpHeaders(), finalContext); + .createWithResponse(shareName, filePath, options.getSize(), null, options.getMetadata(), + options.getFilePermission(), options.getFilePermissionFormat(), smbProperties.getFilePermissionKey(), + smbProperties.getNtfsFileAttributesString(), smbProperties.getFileCreationTimeString(), + smbProperties.getFileLastWriteTimeString(), smbProperties.getFileChangeTimeString(), + requestConditions.getLeaseId(), fileposixProperties.getOwner(), fileposixProperties.getGroup(), + fileposixProperties.getFileMode(), fileposixProperties.getFileType(), options.getShareFileHttpHeaders(), + finalContext); return ModelHelper.createFileInfoResponse(sendRequest(operation, timeout, ShareStorageException.class)); } @@ -756,18 +739,15 @@ public SyncPoller beginCopy(String sourceUrl, ShareFile throw LOGGER.logExceptionAsError(ex); } - String fileAttributes = list.isFileAttributes() - ? FileConstants.COPY_SOURCE - : NtfsFileAttributes.toString(tempSmbProperties.getNtfsFileAttributes()); - String fileCreationTime = list.isCreatedOn() - ? FileConstants.COPY_SOURCE - : FileSmbProperties.parseFileSMBDate(tempSmbProperties.getFileCreationTime()); + String fileAttributes + = list.isFileAttributes() ? null : NtfsFileAttributes.toString(tempSmbProperties.getNtfsFileAttributes()); + String fileCreationTime + = list.isCreatedOn() ? null : FileSmbProperties.parseFileSMBDate(tempSmbProperties.getFileCreationTime()); String fileLastWriteTime = list.isLastWrittenOn() - ? FileConstants.COPY_SOURCE + ? null : FileSmbProperties.parseFileSMBDate(tempSmbProperties.getFileLastWriteTime()); - String fileChangedOnTime = list.isChangedOn() - ? FileConstants.COPY_SOURCE - : FileSmbProperties.parseFileSMBDate(tempSmbProperties.getFileChangeTime()); + String fileChangedOnTime + = list.isChangedOn() ? null : FileSmbProperties.parseFileSMBDate(tempSmbProperties.getFileChangeTime()); final CopyFileSmbInfo copyFileSmbInfo = new CopyFileSmbInfo().setFilePermissionCopyMode(options.getPermissionCopyModeType()) @@ -780,13 +760,18 @@ public SyncPoller beginCopy(String sourceUrl, ShareFile final String copySource = Utility.encodeUrlPath(sourceUrl); + FilePosixProperties fileposixProperties + = options.getPosixProperties() == null ? new FilePosixProperties() : options.getPosixProperties(); + Function, PollResponse> syncActivationOperation = (pollingContext) -> { ResponseBase response = azureFileStorageClient.getFiles() .startCopyWithResponse(shareName, filePath, copySource, null, options.getMetadata(), options.getFilePermission(), options.getFilePermissionFormat(), - tempSmbProperties.getFilePermissionKey(), finalRequestConditions.getLeaseId(), copyFileSmbInfo, - null); + tempSmbProperties.getFilePermissionKey(), finalRequestConditions.getLeaseId(), + fileposixProperties.getOwner(), fileposixProperties.getGroup(), + fileposixProperties.getFileMode(), options.getModeCopyMode(), options.getOwnerCopyMode(), + copyFileSmbInfo, null); FilesStartCopyHeaders headers = response.getDeserializedHeaders(); copyId.set(headers.getXMsCopyId()); @@ -1659,28 +1644,10 @@ public Response setPropertiesWithResponse(long newFileSize, Share public Response setPropertiesWithResponse(long newFileSize, ShareFileHttpHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission, ShareRequestConditions requestConditions, Duration timeout, Context context) { - Context finalContext = context == null ? Context.NONE : context; - ShareRequestConditions finalRequestConditions - = requestConditions == null ? new ShareRequestConditions() : requestConditions; - smbProperties = smbProperties == null ? new FileSmbProperties() : smbProperties; - - // Checks that file permission and file permission key are valid - ModelHelper.validateFilePermissionAndKey(filePermission, smbProperties.getFilePermissionKey()); - - // If file permission and file permission key are both not set then set default value - String finalFilePermission = smbProperties.setFilePermission(filePermission, FileConstants.PRESERVE); - String filePermissionKey = smbProperties.getFilePermissionKey(); - - String fileAttributes = smbProperties.setNtfsFileAttributes(FileConstants.PRESERVE); - String fileCreationTime = smbProperties.setFileCreationTime(FileConstants.PRESERVE); - String fileLastWriteTime = smbProperties.setFileLastWriteTime(FileConstants.PRESERVE); - String fileChangeTime = smbProperties.getFileChangeTimeString(); - Callable> operation = () -> azureFileStorageClient.getFiles() - .setHttpHeadersWithResponse(shareName, filePath, fileAttributes, null, newFileSize, finalFilePermission, - null, filePermissionKey, fileCreationTime, fileLastWriteTime, fileChangeTime, - finalRequestConditions.getLeaseId(), httpHeaders, finalContext); - - return ModelHelper.setPropertiesResponse(sendRequest(operation, timeout, ShareStorageException.class)); + return setPropertiesWithResponse(new ShareFileSetPropertiesOptions(newFileSize).setHttpHeaders(httpHeaders) + .setSmbProperties(smbProperties) + .setFilePermissions(new ShareFilePermission().setPermission(filePermission)) + .setRequestConditions(requestConditions), timeout, context); } /** @@ -1729,30 +1696,28 @@ public Response setPropertiesWithResponse(long newFileSize, Share @ServiceMethod(returns = ReturnType.SINGLE) public Response setPropertiesWithResponse(ShareFileSetPropertiesOptions options, Duration timeout, Context context) { + StorageImplUtils.assertNotNull("options", options); Context finalContext = context == null ? Context.NONE : context; - ShareRequestConditions requestConditions = options.getRequestConditions(); ShareRequestConditions finalRequestConditions - = requestConditions == null ? new ShareRequestConditions() : requestConditions; - FileSmbProperties smbProperties = options.getSmbProperties(); - smbProperties = smbProperties == null ? new FileSmbProperties() : smbProperties; + = options.getRequestConditions() == null ? new ShareRequestConditions() : options.getRequestConditions(); + + FileSmbProperties smbProperties + = options.getSmbProperties() == null ? new FileSmbProperties() : options.getSmbProperties(); + FilePosixProperties fileposixProperties + = options.getPosixProperties() == null ? new FilePosixProperties() : options.getPosixProperties(); + ShareFilePermission filePermission + = options.getFilePermissions() == null ? new ShareFilePermission() : options.getFilePermissions(); // Checks that file permission and file permission key are valid - ModelHelper.validateFilePermissionAndKey(options.getFilePermissions().getPermission(), - smbProperties.getFilePermissionKey()); - - // If file permission and file permission key are both not set then set default value - String finalFilePermission - = smbProperties.setFilePermission(options.getFilePermissions().getPermission(), FileConstants.PRESERVE); - String filePermissionKey = smbProperties.getFilePermissionKey(); - - String fileAttributes = smbProperties.setNtfsFileAttributes(FileConstants.PRESERVE); - String fileCreationTime = smbProperties.setFileCreationTime(FileConstants.PRESERVE); - String fileLastWriteTime = smbProperties.setFileLastWriteTime(FileConstants.PRESERVE); - String fileChangeTime = smbProperties.getFileChangeTimeString(); + ModelHelper.validateFilePermissionAndKey(filePermission.getPermission(), smbProperties.getFilePermissionKey()); + Callable> operation = () -> azureFileStorageClient.getFiles() - .setHttpHeadersWithResponse(shareName, filePath, fileAttributes, null, options.getSizeInBytes(), - finalFilePermission, options.getFilePermissions().getPermissionFormat(), filePermissionKey, - fileCreationTime, fileLastWriteTime, fileChangeTime, finalRequestConditions.getLeaseId(), + .setHttpHeadersWithResponse(shareName, filePath, null, options.getSizeInBytes(), + filePermission.getPermission(), filePermission.getPermissionFormat(), + smbProperties.getFilePermissionKey(), smbProperties.getNtfsFileAttributesString(), + smbProperties.getFileCreationTimeString(), smbProperties.getFileLastWriteTimeString(), + smbProperties.getFileChangeTimeString(), finalRequestConditions.getLeaseId(), + fileposixProperties.getOwner(), fileposixProperties.getGroup(), fileposixProperties.getFileMode(), options.getHttpHeaders(), finalContext); return ModelHelper.setPropertiesResponse(sendRequest(operation, timeout, ShareStorageException.class)); @@ -3142,4 +3107,57 @@ public String generateSas(ShareServiceSasSignatureValues shareServiceSasSignatur return new ShareSasImplUtil(shareServiceSasSignatureValues, getShareName(), getFilePath()) .generateSas(SasImplUtils.extractSharedKeyCredential(getHttpPipeline()), stringToSignHandler, context); } + + /** + * NFS only. Creates a hard link to the file specified by path. + * + *
        +     * ShareFileInfo response = hardLinkClient.createHardLink(sourceClient.getFilePath());
        +     *
        +     * System.out.printf("Link count is is %s.", response.getPosixProperties().getLinkCount());
        +     * 
        + * + * + * @param targetFile Path of the file to create the hard link to, not including the share. For example, + * {@code targetDirectory/targetSubDirectory/.../targetFile} + * @return A {@link ShareFileInfo} describing the state of the hard link. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public ShareFileInfo createHardLink(String targetFile) { + return createHardLinkWithResponse(new ShareFileCreateHardLinkOptions(targetFile), null, Context.NONE) + .getValue(); + } + + /** + * NFS only. Creates a hard link to the file specified by path. + * + *
        +     * ShareFileCreateHardLinkOptions options = new ShareFileCreateHardLinkOptions(sourceClient.getFilePath());
        +     * ShareFileInfo response2 = hardLinkClient.createHardLinkWithResponse(options, null, null).getValue();
        +     *
        +     * System.out.printf("Link count is is %s.", response2.getPosixProperties().getLinkCount());
        +     * 
        + * + * + * @param options {@link ShareFileCreateHardLinkOptions} + * @param timeout An optional timeout applied to the operation. If a response is not returned before the timeout + * concludes a {@link RuntimeException} will be thrown. + * @param context Additional context that is passed through the Http pipeline during the service call. + * @return A {@link Response} whose {@link Response#getValue() value} contains {@link ShareFileInfo} describing the state of the hard link. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createHardLinkWithResponse(ShareFileCreateHardLinkOptions options, Duration timeout, + Context context) { + StorageImplUtils.assertNotNull("options", options); + Context finalContext = context == null ? Context.NONE : context; + ShareRequestConditions requestConditions + = options.getRequestConditions() == null ? new ShareRequestConditions() : options.getRequestConditions(); + + Callable> operation + = () -> this.azureFileStorageClient.getFiles() + .createHardLinkWithResponse(shareName, filePath, options.getTargetFile(), null, null, + requestConditions.getLeaseId(), finalContext); + + return ModelHelper.createHardLinkResponse(sendRequest(operation, timeout, ShareStorageException.class)); + } } diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/ShareServiceVersion.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/ShareServiceVersion.java index eeaf3fd96823..8372d19f461d 100644 --- a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/ShareServiceVersion.java +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/ShareServiceVersion.java @@ -132,7 +132,12 @@ public enum ShareServiceVersion implements ServiceVersion { /** * Service version {@code 2025-01-05}. */ - V2025_01_05("2025-01-05"); + V2025_01_05("2025-01-05"), + + /** + * Service version {@code 2025-05-05}. + */ + V2025_05_05("2025-05-05"); private final String version; @@ -154,6 +159,6 @@ public String getVersion() { * @return the latest {@link ShareServiceVersion} */ public static ShareServiceVersion getLatest() { - return V2025_01_05; + return V2025_05_05; } } diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/DirectoriesImpl.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/DirectoriesImpl.java index c76cf6d43d6e..177a6ce12ead 100644 --- a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/DirectoriesImpl.java +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/DirectoriesImpl.java @@ -95,7 +95,8 @@ Mono> create(@HostParam("url") Stri @HeaderParam("x-ms-file-last-write-time") String fileLastWriteTime, @HeaderParam("x-ms-file-change-time") String fileChangeTime, @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, - @HeaderParam("Accept") String accept, Context context); + @HeaderParam("x-ms-owner") String owner, @HeaderParam("x-ms-group") String group, + @HeaderParam("x-ms-mode") String fileMode, @HeaderParam("Accept") String accept, Context context); @Put("/{shareName}/{directory}") @ExpectedResponses({ 201 }) @@ -112,7 +113,8 @@ Mono> createNoCustomHeaders(@HostParam("url") String url, @HeaderParam("x-ms-file-last-write-time") String fileLastWriteTime, @HeaderParam("x-ms-file-change-time") String fileChangeTime, @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, - @HeaderParam("Accept") String accept, Context context); + @HeaderParam("x-ms-owner") String owner, @HeaderParam("x-ms-group") String group, + @HeaderParam("x-ms-mode") String fileMode, @HeaderParam("Accept") String accept, Context context); @Put("/{shareName}/{directory}") @ExpectedResponses({ 201 }) @@ -129,7 +131,8 @@ ResponseBase createSync(@HostParam("url") String @HeaderParam("x-ms-file-last-write-time") String fileLastWriteTime, @HeaderParam("x-ms-file-change-time") String fileChangeTime, @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, - @HeaderParam("Accept") String accept, Context context); + @HeaderParam("x-ms-owner") String owner, @HeaderParam("x-ms-group") String group, + @HeaderParam("x-ms-mode") String fileMode, @HeaderParam("Accept") String accept, Context context); @Put("/{shareName}/{directory}") @ExpectedResponses({ 201 }) @@ -146,7 +149,8 @@ Response createNoCustomHeadersSync(@HostParam("url") String url, @PathPara @HeaderParam("x-ms-file-last-write-time") String fileLastWriteTime, @HeaderParam("x-ms-file-change-time") String fileChangeTime, @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, - @HeaderParam("Accept") String accept, Context context); + @HeaderParam("x-ms-owner") String owner, @HeaderParam("x-ms-group") String group, + @HeaderParam("x-ms-mode") String fileMode, @HeaderParam("Accept") String accept, Context context); @Get("/{shareName}/{directory}") @ExpectedResponses({ 200 }) @@ -248,7 +252,8 @@ Mono> setProperties(@HostPar @HeaderParam("x-ms-file-change-time") String fileChangeTime, @HeaderParam("x-ms-allow-trailing-dot") Boolean allowTrailingDot, @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, - @HeaderParam("Accept") String accept, Context context); + @HeaderParam("x-ms-owner") String owner, @HeaderParam("x-ms-group") String group, + @HeaderParam("x-ms-mode") String fileMode, @HeaderParam("Accept") String accept, Context context); @Put("/{shareName}/{directory}") @ExpectedResponses({ 200 }) @@ -266,7 +271,8 @@ Mono> setPropertiesNoCustomHeaders(@HostParam("url") String url, @HeaderParam("x-ms-file-change-time") String fileChangeTime, @HeaderParam("x-ms-allow-trailing-dot") Boolean allowTrailingDot, @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, - @HeaderParam("Accept") String accept, Context context); + @HeaderParam("x-ms-owner") String owner, @HeaderParam("x-ms-group") String group, + @HeaderParam("x-ms-mode") String fileMode, @HeaderParam("Accept") String accept, Context context); @Put("/{shareName}/{directory}") @ExpectedResponses({ 200 }) @@ -284,7 +290,8 @@ ResponseBase setPropertiesSync(@HostParam @HeaderParam("x-ms-file-change-time") String fileChangeTime, @HeaderParam("x-ms-allow-trailing-dot") Boolean allowTrailingDot, @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, - @HeaderParam("Accept") String accept, Context context); + @HeaderParam("x-ms-owner") String owner, @HeaderParam("x-ms-group") String group, + @HeaderParam("x-ms-mode") String fileMode, @HeaderParam("Accept") String accept, Context context); @Put("/{shareName}/{directory}") @ExpectedResponses({ 200 }) @@ -302,7 +309,8 @@ Response setPropertiesNoCustomHeadersSync(@HostParam("url") String url, @HeaderParam("x-ms-file-change-time") String fileChangeTime, @HeaderParam("x-ms-allow-trailing-dot") Boolean allowTrailingDot, @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, - @HeaderParam("Accept") String accept, Context context); + @HeaderParam("x-ms-owner") String owner, @HeaderParam("x-ms-group") String group, + @HeaderParam("x-ms-mode") String fileMode, @HeaderParam("Accept") String accept, Context context); @Put("/{shareName}/{directory}") @ExpectedResponses({ 200 }) @@ -621,8 +629,6 @@ Response renameNoCustomHeadersSync(@HostParam("url") String url, @PathPara * * @param shareName The name of the target share. * @param directory The path of the target directory. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -638,9 +644,14 @@ Response renameNoCustomHeadersSync(@HostParam("url") String url, @PathPara * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -648,13 +659,14 @@ Response renameNoCustomHeadersSync(@HostParam("url") String url, @PathPara */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> createWithResponseAsync(String shareName, - String directory, String fileAttributes, Integer timeout, Map metadata, String filePermission, - FilePermissionFormat filePermissionFormat, String filePermissionKey, String fileCreationTime, - String fileLastWriteTime, String fileChangeTime) { + String directory, Integer timeout, Map metadata, String filePermission, + FilePermissionFormat filePermissionFormat, String filePermissionKey, String fileAttributes, + String fileCreationTime, String fileLastWriteTime, String fileChangeTime, String owner, String group, + String fileMode) { return FluxUtil - .withContext(context -> createWithResponseAsync(shareName, directory, fileAttributes, timeout, metadata, - filePermission, filePermissionFormat, filePermissionKey, fileCreationTime, fileLastWriteTime, - fileChangeTime, context)) + .withContext(context -> createWithResponseAsync(shareName, directory, timeout, metadata, filePermission, + filePermissionFormat, filePermissionKey, fileAttributes, fileCreationTime, fileLastWriteTime, + fileChangeTime, owner, group, fileMode, context)) .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); } @@ -663,8 +675,6 @@ public Mono> createWithResponseAsyn * * @param shareName The name of the target share. * @param directory The path of the target directory. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -680,9 +690,14 @@ public Mono> createWithResponseAsyn * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. @@ -691,16 +706,17 @@ public Mono> createWithResponseAsyn */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> createWithResponseAsync(String shareName, - String directory, String fileAttributes, Integer timeout, Map metadata, String filePermission, - FilePermissionFormat filePermissionFormat, String filePermissionKey, String fileCreationTime, - String fileLastWriteTime, String fileChangeTime, Context context) { + String directory, Integer timeout, Map metadata, String filePermission, + FilePermissionFormat filePermissionFormat, String filePermissionKey, String fileAttributes, + String fileCreationTime, String fileLastWriteTime, String fileChangeTime, String owner, String group, + String fileMode, Context context) { final String restype = "directory"; final String accept = "application/xml"; return service .create(this.client.getUrl(), shareName, directory, restype, this.client.isAllowTrailingDot(), timeout, metadata, this.client.getVersion(), filePermission, filePermissionFormat, filePermissionKey, fileAttributes, fileCreationTime, fileLastWriteTime, fileChangeTime, this.client.getFileRequestIntent(), - accept, context) + owner, group, fileMode, accept, context) .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); } @@ -709,8 +725,6 @@ public Mono> createWithResponseAsyn * * @param shareName The name of the target share. * @param directory The path of the target directory. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -726,21 +740,27 @@ public Mono> createWithResponseAsyn * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return A {@link Mono} that completes when a successful response is received. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createAsync(String shareName, String directory, String fileAttributes, Integer timeout, - Map metadata, String filePermission, FilePermissionFormat filePermissionFormat, - String filePermissionKey, String fileCreationTime, String fileLastWriteTime, String fileChangeTime) { - return createWithResponseAsync(shareName, directory, fileAttributes, timeout, metadata, filePermission, - filePermissionFormat, filePermissionKey, fileCreationTime, fileLastWriteTime, fileChangeTime) - .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException) + public Mono createAsync(String shareName, String directory, Integer timeout, Map metadata, + String filePermission, FilePermissionFormat filePermissionFormat, String filePermissionKey, + String fileAttributes, String fileCreationTime, String fileLastWriteTime, String fileChangeTime, String owner, + String group, String fileMode) { + return createWithResponseAsync(shareName, directory, timeout, metadata, filePermission, filePermissionFormat, + filePermissionKey, fileAttributes, fileCreationTime, fileLastWriteTime, fileChangeTime, owner, group, + fileMode).onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException) .flatMap(ignored -> Mono.empty()); } @@ -749,8 +769,6 @@ public Mono createAsync(String shareName, String directory, String fileAtt * * @param shareName The name of the target share. * @param directory The path of the target directory. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -766,9 +784,14 @@ public Mono createAsync(String shareName, String directory, String fileAtt * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. @@ -776,13 +799,13 @@ public Mono createAsync(String shareName, String directory, String fileAtt * @return A {@link Mono} that completes when a successful response is received. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createAsync(String shareName, String directory, String fileAttributes, Integer timeout, - Map metadata, String filePermission, FilePermissionFormat filePermissionFormat, - String filePermissionKey, String fileCreationTime, String fileLastWriteTime, String fileChangeTime, - Context context) { - return createWithResponseAsync(shareName, directory, fileAttributes, timeout, metadata, filePermission, - filePermissionFormat, filePermissionKey, fileCreationTime, fileLastWriteTime, fileChangeTime, context) - .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException) + public Mono createAsync(String shareName, String directory, Integer timeout, Map metadata, + String filePermission, FilePermissionFormat filePermissionFormat, String filePermissionKey, + String fileAttributes, String fileCreationTime, String fileLastWriteTime, String fileChangeTime, String owner, + String group, String fileMode, Context context) { + return createWithResponseAsync(shareName, directory, timeout, metadata, filePermission, filePermissionFormat, + filePermissionKey, fileAttributes, fileCreationTime, fileLastWriteTime, fileChangeTime, owner, group, + fileMode, context).onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException) .flatMap(ignored -> Mono.empty()); } @@ -791,8 +814,6 @@ public Mono createAsync(String shareName, String directory, String fileAtt * * @param shareName The name of the target share. * @param directory The path of the target directory. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -808,9 +829,14 @@ public Mono createAsync(String shareName, String directory, String fileAtt * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -818,13 +844,13 @@ public Mono createAsync(String shareName, String directory, String fileAtt */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> createNoCustomHeadersWithResponseAsync(String shareName, String directory, - String fileAttributes, Integer timeout, Map metadata, String filePermission, - FilePermissionFormat filePermissionFormat, String filePermissionKey, String fileCreationTime, - String fileLastWriteTime, String fileChangeTime) { + Integer timeout, Map metadata, String filePermission, FilePermissionFormat filePermissionFormat, + String filePermissionKey, String fileAttributes, String fileCreationTime, String fileLastWriteTime, + String fileChangeTime, String owner, String group, String fileMode) { return FluxUtil - .withContext(context -> createNoCustomHeadersWithResponseAsync(shareName, directory, fileAttributes, - timeout, metadata, filePermission, filePermissionFormat, filePermissionKey, fileCreationTime, - fileLastWriteTime, fileChangeTime, context)) + .withContext(context -> createNoCustomHeadersWithResponseAsync(shareName, directory, timeout, metadata, + filePermission, filePermissionFormat, filePermissionKey, fileAttributes, fileCreationTime, + fileLastWriteTime, fileChangeTime, owner, group, fileMode, context)) .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); } @@ -833,8 +859,6 @@ public Mono> createNoCustomHeadersWithResponseAsync(String shareN * * @param shareName The name of the target share. * @param directory The path of the target directory. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -850,9 +874,14 @@ public Mono> createNoCustomHeadersWithResponseAsync(String shareN * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. @@ -861,16 +890,16 @@ public Mono> createNoCustomHeadersWithResponseAsync(String shareN */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> createNoCustomHeadersWithResponseAsync(String shareName, String directory, - String fileAttributes, Integer timeout, Map metadata, String filePermission, - FilePermissionFormat filePermissionFormat, String filePermissionKey, String fileCreationTime, - String fileLastWriteTime, String fileChangeTime, Context context) { + Integer timeout, Map metadata, String filePermission, FilePermissionFormat filePermissionFormat, + String filePermissionKey, String fileAttributes, String fileCreationTime, String fileLastWriteTime, + String fileChangeTime, String owner, String group, String fileMode, Context context) { final String restype = "directory"; final String accept = "application/xml"; return service .createNoCustomHeaders(this.client.getUrl(), shareName, directory, restype, this.client.isAllowTrailingDot(), timeout, metadata, this.client.getVersion(), filePermission, filePermissionFormat, filePermissionKey, fileAttributes, fileCreationTime, fileLastWriteTime, - fileChangeTime, this.client.getFileRequestIntent(), accept, context) + fileChangeTime, this.client.getFileRequestIntent(), owner, group, fileMode, accept, context) .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); } @@ -879,8 +908,6 @@ public Mono> createNoCustomHeadersWithResponseAsync(String shareN * * @param shareName The name of the target share. * @param directory The path of the target directory. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -896,9 +923,14 @@ public Mono> createNoCustomHeadersWithResponseAsync(String shareN * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. @@ -907,16 +939,16 @@ public Mono> createNoCustomHeadersWithResponseAsync(String shareN */ @ServiceMethod(returns = ReturnType.SINGLE) public ResponseBase createWithResponse(String shareName, String directory, - String fileAttributes, Integer timeout, Map metadata, String filePermission, - FilePermissionFormat filePermissionFormat, String filePermissionKey, String fileCreationTime, - String fileLastWriteTime, String fileChangeTime, Context context) { + Integer timeout, Map metadata, String filePermission, FilePermissionFormat filePermissionFormat, + String filePermissionKey, String fileAttributes, String fileCreationTime, String fileLastWriteTime, + String fileChangeTime, String owner, String group, String fileMode, Context context) { try { final String restype = "directory"; final String accept = "application/xml"; return service.createSync(this.client.getUrl(), shareName, directory, restype, this.client.isAllowTrailingDot(), timeout, metadata, this.client.getVersion(), filePermission, filePermissionFormat, filePermissionKey, fileAttributes, fileCreationTime, fileLastWriteTime, - fileChangeTime, this.client.getFileRequestIntent(), accept, context); + fileChangeTime, this.client.getFileRequestIntent(), owner, group, fileMode, accept, context); } catch (ShareStorageExceptionInternal internalException) { throw ModelHelper.mapToShareStorageException(internalException); } @@ -927,8 +959,6 @@ public ResponseBase createWithResponse(String sh * * @param shareName The name of the target share. * @param directory The path of the target directory. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -944,19 +974,26 @@ public ResponseBase createWithResponse(String sh * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) - public void create(String shareName, String directory, String fileAttributes, Integer timeout, - Map metadata, String filePermission, FilePermissionFormat filePermissionFormat, - String filePermissionKey, String fileCreationTime, String fileLastWriteTime, String fileChangeTime) { - createWithResponse(shareName, directory, fileAttributes, timeout, metadata, filePermission, - filePermissionFormat, filePermissionKey, fileCreationTime, fileLastWriteTime, fileChangeTime, Context.NONE); + public void create(String shareName, String directory, Integer timeout, Map metadata, + String filePermission, FilePermissionFormat filePermissionFormat, String filePermissionKey, + String fileAttributes, String fileCreationTime, String fileLastWriteTime, String fileChangeTime, String owner, + String group, String fileMode) { + createWithResponse(shareName, directory, timeout, metadata, filePermission, filePermissionFormat, + filePermissionKey, fileAttributes, fileCreationTime, fileLastWriteTime, fileChangeTime, owner, group, + fileMode, Context.NONE); } /** @@ -964,8 +1001,6 @@ public void create(String shareName, String directory, String fileAttributes, In * * @param shareName The name of the target share. * @param directory The path of the target directory. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -981,9 +1016,14 @@ public void create(String shareName, String directory, String fileAttributes, In * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. @@ -991,17 +1031,17 @@ public void create(String shareName, String directory, String fileAttributes, In * @return the {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response createNoCustomHeadersWithResponse(String shareName, String directory, String fileAttributes, - Integer timeout, Map metadata, String filePermission, FilePermissionFormat filePermissionFormat, - String filePermissionKey, String fileCreationTime, String fileLastWriteTime, String fileChangeTime, - Context context) { + public Response createNoCustomHeadersWithResponse(String shareName, String directory, Integer timeout, + Map metadata, String filePermission, FilePermissionFormat filePermissionFormat, + String filePermissionKey, String fileAttributes, String fileCreationTime, String fileLastWriteTime, + String fileChangeTime, String owner, String group, String fileMode, Context context) { try { final String restype = "directory"; final String accept = "application/xml"; return service.createNoCustomHeadersSync(this.client.getUrl(), shareName, directory, restype, this.client.isAllowTrailingDot(), timeout, metadata, this.client.getVersion(), filePermission, filePermissionFormat, filePermissionKey, fileAttributes, fileCreationTime, fileLastWriteTime, - fileChangeTime, this.client.getFileRequestIntent(), accept, context); + fileChangeTime, this.client.getFileRequestIntent(), owner, group, fileMode, accept, context); } catch (ShareStorageExceptionInternal internalException) { throw ModelHelper.mapToShareStorageException(internalException); } @@ -1455,8 +1495,6 @@ public Response deleteNoCustomHeadersWithResponse(String shareName, String * * @param shareName The name of the target share. * @param directory The path of the target directory. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -1471,9 +1509,14 @@ public Response deleteNoCustomHeadersWithResponse(String shareName, String * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -1481,13 +1524,13 @@ public Response deleteNoCustomHeadersWithResponse(String shareName, String */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> setPropertiesWithResponseAsync(String shareName, - String directory, String fileAttributes, Integer timeout, String filePermission, - FilePermissionFormat filePermissionFormat, String filePermissionKey, String fileCreationTime, - String fileLastWriteTime, String fileChangeTime) { + String directory, Integer timeout, String filePermission, FilePermissionFormat filePermissionFormat, + String filePermissionKey, String fileAttributes, String fileCreationTime, String fileLastWriteTime, + String fileChangeTime, String owner, String group, String fileMode) { return FluxUtil - .withContext(context -> setPropertiesWithResponseAsync(shareName, directory, fileAttributes, timeout, - filePermission, filePermissionFormat, filePermissionKey, fileCreationTime, fileLastWriteTime, - fileChangeTime, context)) + .withContext(context -> setPropertiesWithResponseAsync(shareName, directory, timeout, filePermission, + filePermissionFormat, filePermissionKey, fileAttributes, fileCreationTime, fileLastWriteTime, + fileChangeTime, owner, group, fileMode, context)) .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); } @@ -1496,8 +1539,6 @@ public Mono> setPropertiesWi * * @param shareName The name of the target share. * @param directory The path of the target directory. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -1512,9 +1553,14 @@ public Mono> setPropertiesWi * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. @@ -1523,9 +1569,9 @@ public Mono> setPropertiesWi */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> setPropertiesWithResponseAsync(String shareName, - String directory, String fileAttributes, Integer timeout, String filePermission, - FilePermissionFormat filePermissionFormat, String filePermissionKey, String fileCreationTime, - String fileLastWriteTime, String fileChangeTime, Context context) { + String directory, Integer timeout, String filePermission, FilePermissionFormat filePermissionFormat, + String filePermissionKey, String fileAttributes, String fileCreationTime, String fileLastWriteTime, + String fileChangeTime, String owner, String group, String fileMode, Context context) { final String restype = "directory"; final String comp = "properties"; final String accept = "application/xml"; @@ -1533,7 +1579,7 @@ public Mono> setPropertiesWi .setProperties(this.client.getUrl(), shareName, directory, restype, comp, timeout, this.client.getVersion(), filePermission, filePermissionFormat, filePermissionKey, fileAttributes, fileCreationTime, fileLastWriteTime, fileChangeTime, this.client.isAllowTrailingDot(), this.client.getFileRequestIntent(), - accept, context) + owner, group, fileMode, accept, context) .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); } @@ -1542,8 +1588,6 @@ public Mono> setPropertiesWi * * @param shareName The name of the target share. * @param directory The path of the target directory. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -1558,21 +1602,27 @@ public Mono> setPropertiesWi * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return A {@link Mono} that completes when a successful response is received. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono setPropertiesAsync(String shareName, String directory, String fileAttributes, Integer timeout, - String filePermission, FilePermissionFormat filePermissionFormat, String filePermissionKey, - String fileCreationTime, String fileLastWriteTime, String fileChangeTime) { - return setPropertiesWithResponseAsync(shareName, directory, fileAttributes, timeout, filePermission, - filePermissionFormat, filePermissionKey, fileCreationTime, fileLastWriteTime, fileChangeTime) - .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException) + public Mono setPropertiesAsync(String shareName, String directory, Integer timeout, String filePermission, + FilePermissionFormat filePermissionFormat, String filePermissionKey, String fileAttributes, + String fileCreationTime, String fileLastWriteTime, String fileChangeTime, String owner, String group, + String fileMode) { + return setPropertiesWithResponseAsync(shareName, directory, timeout, filePermission, filePermissionFormat, + filePermissionKey, fileAttributes, fileCreationTime, fileLastWriteTime, fileChangeTime, owner, group, + fileMode).onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException) .flatMap(ignored -> Mono.empty()); } @@ -1581,8 +1631,6 @@ public Mono setPropertiesAsync(String shareName, String directory, String * * @param shareName The name of the target share. * @param directory The path of the target directory. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -1597,9 +1645,14 @@ public Mono setPropertiesAsync(String shareName, String directory, String * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. @@ -1607,12 +1660,13 @@ public Mono setPropertiesAsync(String shareName, String directory, String * @return A {@link Mono} that completes when a successful response is received. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono setPropertiesAsync(String shareName, String directory, String fileAttributes, Integer timeout, - String filePermission, FilePermissionFormat filePermissionFormat, String filePermissionKey, - String fileCreationTime, String fileLastWriteTime, String fileChangeTime, Context context) { - return setPropertiesWithResponseAsync(shareName, directory, fileAttributes, timeout, filePermission, - filePermissionFormat, filePermissionKey, fileCreationTime, fileLastWriteTime, fileChangeTime, context) - .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException) + public Mono setPropertiesAsync(String shareName, String directory, Integer timeout, String filePermission, + FilePermissionFormat filePermissionFormat, String filePermissionKey, String fileAttributes, + String fileCreationTime, String fileLastWriteTime, String fileChangeTime, String owner, String group, + String fileMode, Context context) { + return setPropertiesWithResponseAsync(shareName, directory, timeout, filePermission, filePermissionFormat, + filePermissionKey, fileAttributes, fileCreationTime, fileLastWriteTime, fileChangeTime, owner, group, + fileMode, context).onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException) .flatMap(ignored -> Mono.empty()); } @@ -1621,8 +1675,6 @@ public Mono setPropertiesAsync(String shareName, String directory, String * * @param shareName The name of the target share. * @param directory The path of the target directory. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -1637,9 +1689,14 @@ public Mono setPropertiesAsync(String shareName, String directory, String * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -1647,12 +1704,13 @@ public Mono setPropertiesAsync(String shareName, String directory, String */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> setPropertiesNoCustomHeadersWithResponseAsync(String shareName, String directory, - String fileAttributes, Integer timeout, String filePermission, FilePermissionFormat filePermissionFormat, - String filePermissionKey, String fileCreationTime, String fileLastWriteTime, String fileChangeTime) { + Integer timeout, String filePermission, FilePermissionFormat filePermissionFormat, String filePermissionKey, + String fileAttributes, String fileCreationTime, String fileLastWriteTime, String fileChangeTime, String owner, + String group, String fileMode) { return FluxUtil - .withContext(context -> setPropertiesNoCustomHeadersWithResponseAsync(shareName, directory, fileAttributes, - timeout, filePermission, filePermissionFormat, filePermissionKey, fileCreationTime, fileLastWriteTime, - fileChangeTime, context)) + .withContext(context -> setPropertiesNoCustomHeadersWithResponseAsync(shareName, directory, timeout, + filePermission, filePermissionFormat, filePermissionKey, fileAttributes, fileCreationTime, + fileLastWriteTime, fileChangeTime, owner, group, fileMode, context)) .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); } @@ -1661,8 +1719,6 @@ public Mono> setPropertiesNoCustomHeadersWithResponseAsync(String * * @param shareName The name of the target share. * @param directory The path of the target directory. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -1677,9 +1733,14 @@ public Mono> setPropertiesNoCustomHeadersWithResponseAsync(String * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. @@ -1688,9 +1749,9 @@ public Mono> setPropertiesNoCustomHeadersWithResponseAsync(String */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> setPropertiesNoCustomHeadersWithResponseAsync(String shareName, String directory, - String fileAttributes, Integer timeout, String filePermission, FilePermissionFormat filePermissionFormat, - String filePermissionKey, String fileCreationTime, String fileLastWriteTime, String fileChangeTime, - Context context) { + Integer timeout, String filePermission, FilePermissionFormat filePermissionFormat, String filePermissionKey, + String fileAttributes, String fileCreationTime, String fileLastWriteTime, String fileChangeTime, String owner, + String group, String fileMode, Context context) { final String restype = "directory"; final String comp = "properties"; final String accept = "application/xml"; @@ -1698,7 +1759,7 @@ public Mono> setPropertiesNoCustomHeadersWithResponseAsync(String .setPropertiesNoCustomHeaders(this.client.getUrl(), shareName, directory, restype, comp, timeout, this.client.getVersion(), filePermission, filePermissionFormat, filePermissionKey, fileAttributes, fileCreationTime, fileLastWriteTime, fileChangeTime, this.client.isAllowTrailingDot(), - this.client.getFileRequestIntent(), accept, context) + this.client.getFileRequestIntent(), owner, group, fileMode, accept, context) .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); } @@ -1707,8 +1768,6 @@ public Mono> setPropertiesNoCustomHeadersWithResponseAsync(String * * @param shareName The name of the target share. * @param directory The path of the target directory. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -1723,9 +1782,14 @@ public Mono> setPropertiesNoCustomHeadersWithResponseAsync(String * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. @@ -1734,9 +1798,9 @@ public Mono> setPropertiesNoCustomHeadersWithResponseAsync(String */ @ServiceMethod(returns = ReturnType.SINGLE) public ResponseBase setPropertiesWithResponse(String shareName, - String directory, String fileAttributes, Integer timeout, String filePermission, - FilePermissionFormat filePermissionFormat, String filePermissionKey, String fileCreationTime, - String fileLastWriteTime, String fileChangeTime, Context context) { + String directory, Integer timeout, String filePermission, FilePermissionFormat filePermissionFormat, + String filePermissionKey, String fileAttributes, String fileCreationTime, String fileLastWriteTime, + String fileChangeTime, String owner, String group, String fileMode, Context context) { try { final String restype = "directory"; final String comp = "properties"; @@ -1744,7 +1808,7 @@ public ResponseBase setPropertiesWithResp return service.setPropertiesSync(this.client.getUrl(), shareName, directory, restype, comp, timeout, this.client.getVersion(), filePermission, filePermissionFormat, filePermissionKey, fileAttributes, fileCreationTime, fileLastWriteTime, fileChangeTime, this.client.isAllowTrailingDot(), - this.client.getFileRequestIntent(), accept, context); + this.client.getFileRequestIntent(), owner, group, fileMode, accept, context); } catch (ShareStorageExceptionInternal internalException) { throw ModelHelper.mapToShareStorageException(internalException); } @@ -1755,8 +1819,6 @@ public ResponseBase setPropertiesWithResp * * @param shareName The name of the target share. * @param directory The path of the target directory. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -1771,19 +1833,26 @@ public ResponseBase setPropertiesWithResp * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) - public void setProperties(String shareName, String directory, String fileAttributes, Integer timeout, - String filePermission, FilePermissionFormat filePermissionFormat, String filePermissionKey, - String fileCreationTime, String fileLastWriteTime, String fileChangeTime) { - setPropertiesWithResponse(shareName, directory, fileAttributes, timeout, filePermission, filePermissionFormat, - filePermissionKey, fileCreationTime, fileLastWriteTime, fileChangeTime, Context.NONE); + public void setProperties(String shareName, String directory, Integer timeout, String filePermission, + FilePermissionFormat filePermissionFormat, String filePermissionKey, String fileAttributes, + String fileCreationTime, String fileLastWriteTime, String fileChangeTime, String owner, String group, + String fileMode) { + setPropertiesWithResponse(shareName, directory, timeout, filePermission, filePermissionFormat, + filePermissionKey, fileAttributes, fileCreationTime, fileLastWriteTime, fileChangeTime, owner, group, + fileMode, Context.NONE); } /** @@ -1791,8 +1860,6 @@ public void setProperties(String shareName, String directory, String fileAttribu * * @param shareName The name of the target share. * @param directory The path of the target directory. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -1807,9 +1874,14 @@ public void setProperties(String shareName, String directory, String fileAttribu * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. @@ -1817,10 +1889,10 @@ public void setProperties(String shareName, String directory, String fileAttribu * @return the {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response setPropertiesNoCustomHeadersWithResponse(String shareName, String directory, - String fileAttributes, Integer timeout, String filePermission, FilePermissionFormat filePermissionFormat, - String filePermissionKey, String fileCreationTime, String fileLastWriteTime, String fileChangeTime, - Context context) { + public Response setPropertiesNoCustomHeadersWithResponse(String shareName, String directory, Integer timeout, + String filePermission, FilePermissionFormat filePermissionFormat, String filePermissionKey, + String fileAttributes, String fileCreationTime, String fileLastWriteTime, String fileChangeTime, String owner, + String group, String fileMode, Context context) { try { final String restype = "directory"; final String comp = "properties"; @@ -1828,7 +1900,7 @@ public Response setPropertiesNoCustomHeadersWithResponse(String shareName, return service.setPropertiesNoCustomHeadersSync(this.client.getUrl(), shareName, directory, restype, comp, timeout, this.client.getVersion(), filePermission, filePermissionFormat, filePermissionKey, fileAttributes, fileCreationTime, fileLastWriteTime, fileChangeTime, this.client.isAllowTrailingDot(), - this.client.getFileRequestIntent(), accept, context); + this.client.getFileRequestIntent(), owner, group, fileMode, accept, context); } catch (ShareStorageExceptionInternal internalException) { throw ModelHelper.mapToShareStorageException(internalException); } diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/FilesImpl.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/FilesImpl.java index 53d35f0197c6..b1629ad2e5d6 100644 --- a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/FilesImpl.java +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/FilesImpl.java @@ -32,12 +32,15 @@ import com.azure.storage.file.share.implementation.models.FilesAcquireLeaseHeaders; import com.azure.storage.file.share.implementation.models.FilesBreakLeaseHeaders; import com.azure.storage.file.share.implementation.models.FilesChangeLeaseHeaders; +import com.azure.storage.file.share.implementation.models.FilesCreateHardLinkHeaders; import com.azure.storage.file.share.implementation.models.FilesCreateHeaders; +import com.azure.storage.file.share.implementation.models.FilesCreateSymbolicLinkHeaders; import com.azure.storage.file.share.implementation.models.FilesDeleteHeaders; import com.azure.storage.file.share.implementation.models.FilesDownloadHeaders; import com.azure.storage.file.share.implementation.models.FilesForceCloseHandlesHeaders; import com.azure.storage.file.share.implementation.models.FilesGetPropertiesHeaders; import com.azure.storage.file.share.implementation.models.FilesGetRangeListHeaders; +import com.azure.storage.file.share.implementation.models.FilesGetSymbolicLinkHeaders; import com.azure.storage.file.share.implementation.models.FilesListHandlesHeaders; import com.azure.storage.file.share.implementation.models.FilesReleaseLeaseHeaders; import com.azure.storage.file.share.implementation.models.FilesRenameHeaders; @@ -53,6 +56,9 @@ import com.azure.storage.file.share.implementation.util.ModelHelper; import com.azure.storage.file.share.models.FileLastWrittenMode; import com.azure.storage.file.share.models.FilePermissionFormat; +import com.azure.storage.file.share.models.ModeCopyMode; +import com.azure.storage.file.share.models.NfsFileType; +import com.azure.storage.file.share.models.OwnerCopyMode; import com.azure.storage.file.share.models.PermissionCopyModeType; import com.azure.storage.file.share.models.ShareFileHttpHeaders; import com.azure.storage.file.share.models.ShareFileRangeList; @@ -118,6 +124,8 @@ Mono> create(@HostParam("url") String url @HeaderParam("x-ms-file-last-write-time") String fileLastWriteTime, @HeaderParam("x-ms-file-change-time") String fileChangeTime, @HeaderParam("x-ms-lease-id") String leaseId, @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, + @HeaderParam("x-ms-owner") String owner, @HeaderParam("x-ms-group") String group, + @HeaderParam("x-ms-mode") String fileMode, @HeaderParam("x-ms-file-file-type") NfsFileType nfsFileType, @HeaderParam("Accept") String accept, Context context); @Put("/{shareName}/{fileName}") @@ -141,6 +149,8 @@ Mono> createNoCustomHeaders(@HostParam("url") String url, @HeaderParam("x-ms-file-last-write-time") String fileLastWriteTime, @HeaderParam("x-ms-file-change-time") String fileChangeTime, @HeaderParam("x-ms-lease-id") String leaseId, @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, + @HeaderParam("x-ms-owner") String owner, @HeaderParam("x-ms-group") String group, + @HeaderParam("x-ms-mode") String fileMode, @HeaderParam("x-ms-file-file-type") NfsFileType nfsFileType, @HeaderParam("Accept") String accept, Context context); @Put("/{shareName}/{fileName}") @@ -164,6 +174,8 @@ ResponseBase createSync(@HostParam("url") String url, @HeaderParam("x-ms-file-last-write-time") String fileLastWriteTime, @HeaderParam("x-ms-file-change-time") String fileChangeTime, @HeaderParam("x-ms-lease-id") String leaseId, @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, + @HeaderParam("x-ms-owner") String owner, @HeaderParam("x-ms-group") String group, + @HeaderParam("x-ms-mode") String fileMode, @HeaderParam("x-ms-file-file-type") NfsFileType nfsFileType, @HeaderParam("Accept") String accept, Context context); @Put("/{shareName}/{fileName}") @@ -187,6 +199,8 @@ Response createNoCustomHeadersSync(@HostParam("url") String url, @PathPara @HeaderParam("x-ms-file-last-write-time") String fileLastWriteTime, @HeaderParam("x-ms-file-change-time") String fileChangeTime, @HeaderParam("x-ms-lease-id") String leaseId, @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, + @HeaderParam("x-ms-owner") String owner, @HeaderParam("x-ms-group") String group, + @HeaderParam("x-ms-mode") String fileMode, @HeaderParam("x-ms-file-file-type") NfsFileType nfsFileType, @HeaderParam("Accept") String accept, Context context); @Get("/{shareName}/{fileName}") @@ -346,7 +360,8 @@ Mono> setHttpHeaders(@HostParam(" @HeaderParam("x-ms-file-change-time") String fileChangeTime, @HeaderParam("x-ms-lease-id") String leaseId, @HeaderParam("x-ms-allow-trailing-dot") Boolean allowTrailingDot, @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, - @HeaderParam("Accept") String accept, Context context); + @HeaderParam("x-ms-owner") String owner, @HeaderParam("x-ms-group") String group, + @HeaderParam("x-ms-mode") String fileMode, @HeaderParam("Accept") String accept, Context context); @Put("/{shareName}/{fileName}") @ExpectedResponses({ 200 }) @@ -369,7 +384,8 @@ Mono> setHttpHeadersNoCustomHeaders(@HostParam("url") String url, @HeaderParam("x-ms-file-change-time") String fileChangeTime, @HeaderParam("x-ms-lease-id") String leaseId, @HeaderParam("x-ms-allow-trailing-dot") Boolean allowTrailingDot, @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, - @HeaderParam("Accept") String accept, Context context); + @HeaderParam("x-ms-owner") String owner, @HeaderParam("x-ms-group") String group, + @HeaderParam("x-ms-mode") String fileMode, @HeaderParam("Accept") String accept, Context context); @Put("/{shareName}/{fileName}") @ExpectedResponses({ 200 }) @@ -392,7 +408,8 @@ ResponseBase setHttpHeadersSync(@HostParam("ur @HeaderParam("x-ms-file-change-time") String fileChangeTime, @HeaderParam("x-ms-lease-id") String leaseId, @HeaderParam("x-ms-allow-trailing-dot") Boolean allowTrailingDot, @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, - @HeaderParam("Accept") String accept, Context context); + @HeaderParam("x-ms-owner") String owner, @HeaderParam("x-ms-group") String group, + @HeaderParam("x-ms-mode") String fileMode, @HeaderParam("Accept") String accept, Context context); @Put("/{shareName}/{fileName}") @ExpectedResponses({ 200 }) @@ -415,7 +432,8 @@ Response setHttpHeadersNoCustomHeadersSync(@HostParam("url") String url, @HeaderParam("x-ms-file-change-time") String fileChangeTime, @HeaderParam("x-ms-lease-id") String leaseId, @HeaderParam("x-ms-allow-trailing-dot") Boolean allowTrailingDot, @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, - @HeaderParam("Accept") String accept, Context context); + @HeaderParam("x-ms-owner") String owner, @HeaderParam("x-ms-group") String group, + @HeaderParam("x-ms-mode") String fileMode, @HeaderParam("Accept") String accept, Context context); @Put("/{shareName}/{fileName}") @ExpectedResponses({ 201 }) @@ -924,6 +942,10 @@ Mono> startCopy(@HostParam("url") Stri @HeaderParam("x-ms-allow-trailing-dot") Boolean allowTrailingDot, @HeaderParam("x-ms-source-allow-trailing-dot") Boolean allowSourceTrailingDot, @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, + @HeaderParam("x-ms-owner") String owner, @HeaderParam("x-ms-group") String group, + @HeaderParam("x-ms-mode") String fileMode, + @HeaderParam("x-ms-file-mode-copy-mode") ModeCopyMode fileModeCopyMode, + @HeaderParam("x-ms-file-owner-copy-mode") OwnerCopyMode fileOwnerCopyMode, @HeaderParam("Accept") String accept, Context context); @Put("/{shareName}/{fileName}") @@ -947,6 +969,10 @@ Mono> startCopyNoCustomHeaders(@HostParam("url") String url, @HeaderParam("x-ms-allow-trailing-dot") Boolean allowTrailingDot, @HeaderParam("x-ms-source-allow-trailing-dot") Boolean allowSourceTrailingDot, @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, + @HeaderParam("x-ms-owner") String owner, @HeaderParam("x-ms-group") String group, + @HeaderParam("x-ms-mode") String fileMode, + @HeaderParam("x-ms-file-mode-copy-mode") ModeCopyMode fileModeCopyMode, + @HeaderParam("x-ms-file-owner-copy-mode") OwnerCopyMode fileOwnerCopyMode, @HeaderParam("Accept") String accept, Context context); @Put("/{shareName}/{fileName}") @@ -970,6 +996,10 @@ ResponseBase startCopySync(@HostParam("url") String @HeaderParam("x-ms-allow-trailing-dot") Boolean allowTrailingDot, @HeaderParam("x-ms-source-allow-trailing-dot") Boolean allowSourceTrailingDot, @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, + @HeaderParam("x-ms-owner") String owner, @HeaderParam("x-ms-group") String group, + @HeaderParam("x-ms-mode") String fileMode, + @HeaderParam("x-ms-file-mode-copy-mode") ModeCopyMode fileModeCopyMode, + @HeaderParam("x-ms-file-owner-copy-mode") OwnerCopyMode fileOwnerCopyMode, @HeaderParam("Accept") String accept, Context context); @Put("/{shareName}/{fileName}") @@ -993,6 +1023,10 @@ Response startCopyNoCustomHeadersSync(@HostParam("url") String url, @HeaderParam("x-ms-allow-trailing-dot") Boolean allowTrailingDot, @HeaderParam("x-ms-source-allow-trailing-dot") Boolean allowSourceTrailingDot, @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, + @HeaderParam("x-ms-owner") String owner, @HeaderParam("x-ms-group") String group, + @HeaderParam("x-ms-mode") String fileMode, + @HeaderParam("x-ms-file-mode-copy-mode") ModeCopyMode fileModeCopyMode, + @HeaderParam("x-ms-file-owner-copy-mode") OwnerCopyMode fileOwnerCopyMode, @HeaderParam("Accept") String accept, Context context); @Put("/{shareName}/{fileName}") @@ -1238,6 +1272,158 @@ Response renameNoCustomHeadersSync(@HostParam("url") String url, @PathPara @HeaderParam("x-ms-source-allow-trailing-dot") Boolean allowSourceTrailingDot, @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, @HeaderParam("Accept") String accept, Context context); + + @Put("/{shareName}/{fileName}") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(ShareStorageExceptionInternal.class) + Mono> createSymbolicLink(@HostParam("url") String url, + @PathParam("shareName") String shareName, @PathParam("fileName") String fileName, + @QueryParam("restype") String restype, @QueryParam("timeout") Integer timeout, + @HeaderParam("x-ms-version") String version, @HeaderParam("x-ms-meta-") Map metadata, + @HeaderParam("x-ms-file-creation-time") String fileCreationTime, + @HeaderParam("x-ms-file-last-write-time") String fileLastWriteTime, + @HeaderParam("x-ms-client-request-id") String requestId, @HeaderParam("x-ms-lease-id") String leaseId, + @HeaderParam("x-ms-owner") String owner, @HeaderParam("x-ms-group") String group, + @HeaderParam("x-ms-link-text") String linkText, + @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, + @HeaderParam("Accept") String accept, Context context); + + @Put("/{shareName}/{fileName}") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(ShareStorageExceptionInternal.class) + Mono> createSymbolicLinkNoCustomHeaders(@HostParam("url") String url, + @PathParam("shareName") String shareName, @PathParam("fileName") String fileName, + @QueryParam("restype") String restype, @QueryParam("timeout") Integer timeout, + @HeaderParam("x-ms-version") String version, @HeaderParam("x-ms-meta-") Map metadata, + @HeaderParam("x-ms-file-creation-time") String fileCreationTime, + @HeaderParam("x-ms-file-last-write-time") String fileLastWriteTime, + @HeaderParam("x-ms-client-request-id") String requestId, @HeaderParam("x-ms-lease-id") String leaseId, + @HeaderParam("x-ms-owner") String owner, @HeaderParam("x-ms-group") String group, + @HeaderParam("x-ms-link-text") String linkText, + @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, + @HeaderParam("Accept") String accept, Context context); + + @Put("/{shareName}/{fileName}") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(ShareStorageExceptionInternal.class) + ResponseBase createSymbolicLinkSync(@HostParam("url") String url, + @PathParam("shareName") String shareName, @PathParam("fileName") String fileName, + @QueryParam("restype") String restype, @QueryParam("timeout") Integer timeout, + @HeaderParam("x-ms-version") String version, @HeaderParam("x-ms-meta-") Map metadata, + @HeaderParam("x-ms-file-creation-time") String fileCreationTime, + @HeaderParam("x-ms-file-last-write-time") String fileLastWriteTime, + @HeaderParam("x-ms-client-request-id") String requestId, @HeaderParam("x-ms-lease-id") String leaseId, + @HeaderParam("x-ms-owner") String owner, @HeaderParam("x-ms-group") String group, + @HeaderParam("x-ms-link-text") String linkText, + @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, + @HeaderParam("Accept") String accept, Context context); + + @Put("/{shareName}/{fileName}") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(ShareStorageExceptionInternal.class) + Response createSymbolicLinkNoCustomHeadersSync(@HostParam("url") String url, + @PathParam("shareName") String shareName, @PathParam("fileName") String fileName, + @QueryParam("restype") String restype, @QueryParam("timeout") Integer timeout, + @HeaderParam("x-ms-version") String version, @HeaderParam("x-ms-meta-") Map metadata, + @HeaderParam("x-ms-file-creation-time") String fileCreationTime, + @HeaderParam("x-ms-file-last-write-time") String fileLastWriteTime, + @HeaderParam("x-ms-client-request-id") String requestId, @HeaderParam("x-ms-lease-id") String leaseId, + @HeaderParam("x-ms-owner") String owner, @HeaderParam("x-ms-group") String group, + @HeaderParam("x-ms-link-text") String linkText, + @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, + @HeaderParam("Accept") String accept, Context context); + + @Get("/{shareName}/{fileName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ShareStorageExceptionInternal.class) + Mono> getSymbolicLink(@HostParam("url") String url, + @PathParam("shareName") String shareName, @PathParam("fileName") String fileName, + @QueryParam("restype") String restype, @QueryParam("timeout") Integer timeout, + @QueryParam("sharesnapshot") String sharesnapshot, @HeaderParam("x-ms-version") String version, + @HeaderParam("x-ms-client-request-id") String requestId, + @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, + @HeaderParam("Accept") String accept, Context context); + + @Get("/{shareName}/{fileName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ShareStorageExceptionInternal.class) + Mono> getSymbolicLinkNoCustomHeaders(@HostParam("url") String url, + @PathParam("shareName") String shareName, @PathParam("fileName") String fileName, + @QueryParam("restype") String restype, @QueryParam("timeout") Integer timeout, + @QueryParam("sharesnapshot") String sharesnapshot, @HeaderParam("x-ms-version") String version, + @HeaderParam("x-ms-client-request-id") String requestId, + @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, + @HeaderParam("Accept") String accept, Context context); + + @Get("/{shareName}/{fileName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ShareStorageExceptionInternal.class) + ResponseBase getSymbolicLinkSync(@HostParam("url") String url, + @PathParam("shareName") String shareName, @PathParam("fileName") String fileName, + @QueryParam("restype") String restype, @QueryParam("timeout") Integer timeout, + @QueryParam("sharesnapshot") String sharesnapshot, @HeaderParam("x-ms-version") String version, + @HeaderParam("x-ms-client-request-id") String requestId, + @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, + @HeaderParam("Accept") String accept, Context context); + + @Get("/{shareName}/{fileName}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ShareStorageExceptionInternal.class) + Response getSymbolicLinkNoCustomHeadersSync(@HostParam("url") String url, + @PathParam("shareName") String shareName, @PathParam("fileName") String fileName, + @QueryParam("restype") String restype, @QueryParam("timeout") Integer timeout, + @QueryParam("sharesnapshot") String sharesnapshot, @HeaderParam("x-ms-version") String version, + @HeaderParam("x-ms-client-request-id") String requestId, + @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, + @HeaderParam("Accept") String accept, Context context); + + @Put("/{shareName}/{fileName}") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(ShareStorageExceptionInternal.class) + Mono> createHardLink(@HostParam("url") String url, + @PathParam("shareName") String shareName, @PathParam("fileName") String fileName, + @QueryParam("restype") String restype, @QueryParam("timeout") Integer timeout, + @HeaderParam("x-ms-version") String version, @HeaderParam("x-ms-type") String fileTypeConstant, + @HeaderParam("x-ms-client-request-id") String requestId, @HeaderParam("x-ms-lease-id") String leaseId, + @HeaderParam("x-ms-file-target-file") String targetFile, + @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, + @HeaderParam("Accept") String accept, Context context); + + @Put("/{shareName}/{fileName}") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(ShareStorageExceptionInternal.class) + Mono> createHardLinkNoCustomHeaders(@HostParam("url") String url, + @PathParam("shareName") String shareName, @PathParam("fileName") String fileName, + @QueryParam("restype") String restype, @QueryParam("timeout") Integer timeout, + @HeaderParam("x-ms-version") String version, @HeaderParam("x-ms-type") String fileTypeConstant, + @HeaderParam("x-ms-client-request-id") String requestId, @HeaderParam("x-ms-lease-id") String leaseId, + @HeaderParam("x-ms-file-target-file") String targetFile, + @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, + @HeaderParam("Accept") String accept, Context context); + + @Put("/{shareName}/{fileName}") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(ShareStorageExceptionInternal.class) + ResponseBase createHardLinkSync(@HostParam("url") String url, + @PathParam("shareName") String shareName, @PathParam("fileName") String fileName, + @QueryParam("restype") String restype, @QueryParam("timeout") Integer timeout, + @HeaderParam("x-ms-version") String version, @HeaderParam("x-ms-type") String fileTypeConstant, + @HeaderParam("x-ms-client-request-id") String requestId, @HeaderParam("x-ms-lease-id") String leaseId, + @HeaderParam("x-ms-file-target-file") String targetFile, + @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, + @HeaderParam("Accept") String accept, Context context); + + @Put("/{shareName}/{fileName}") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(ShareStorageExceptionInternal.class) + Response createHardLinkNoCustomHeadersSync(@HostParam("url") String url, + @PathParam("shareName") String shareName, @PathParam("fileName") String fileName, + @QueryParam("restype") String restype, @QueryParam("timeout") Integer timeout, + @HeaderParam("x-ms-version") String version, @HeaderParam("x-ms-type") String fileTypeConstant, + @HeaderParam("x-ms-client-request-id") String requestId, @HeaderParam("x-ms-lease-id") String leaseId, + @HeaderParam("x-ms-file-target-file") String targetFile, + @HeaderParam("x-ms-file-request-intent") ShareTokenIntent fileRequestIntent, + @HeaderParam("Accept") String accept, Context context); } /** @@ -1246,8 +1432,6 @@ Response renameNoCustomHeadersSync(@HostParam("url") String url, @PathPara * @param shareName The name of the target share. * @param fileName The path of the target file. * @param fileContentLength Specifies the maximum size for the file, up to 4 TB. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -1263,10 +1447,16 @@ Response renameNoCustomHeadersSync(@HostParam("url") String url, @PathPara * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. + * @param nfsFileType Optional, NFS only. Type of the file or directory. * @param shareFileHttpHeaders Parameter group. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. @@ -1275,15 +1465,14 @@ Response renameNoCustomHeadersSync(@HostParam("url") String url, @PathPara */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> createWithResponseAsync(String shareName, String fileName, - long fileContentLength, String fileAttributes, Integer timeout, Map metadata, - String filePermission, FilePermissionFormat filePermissionFormat, String filePermissionKey, - String fileCreationTime, String fileLastWriteTime, String fileChangeTime, String leaseId, - ShareFileHttpHeaders shareFileHttpHeaders) { - return FluxUtil - .withContext(context -> createWithResponseAsync(shareName, fileName, fileContentLength, fileAttributes, - timeout, metadata, filePermission, filePermissionFormat, filePermissionKey, fileCreationTime, - fileLastWriteTime, fileChangeTime, leaseId, shareFileHttpHeaders, context)) - .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); + long fileContentLength, Integer timeout, Map metadata, String filePermission, + FilePermissionFormat filePermissionFormat, String filePermissionKey, String fileAttributes, + String fileCreationTime, String fileLastWriteTime, String fileChangeTime, String leaseId, String owner, + String group, String fileMode, NfsFileType nfsFileType, ShareFileHttpHeaders shareFileHttpHeaders) { + return FluxUtil.withContext(context -> createWithResponseAsync(shareName, fileName, fileContentLength, timeout, + metadata, filePermission, filePermissionFormat, filePermissionKey, fileAttributes, fileCreationTime, + fileLastWriteTime, fileChangeTime, leaseId, owner, group, fileMode, nfsFileType, shareFileHttpHeaders, + context)).onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); } /** @@ -1292,8 +1481,6 @@ public Mono> createWithResponseAsync(Stri * @param shareName The name of the target share. * @param fileName The path of the target file. * @param fileContentLength Specifies the maximum size for the file, up to 4 TB. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -1309,10 +1496,16 @@ public Mono> createWithResponseAsync(Stri * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. + * @param nfsFileType Optional, NFS only. Type of the file or directory. * @param shareFileHttpHeaders Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -1322,10 +1515,11 @@ public Mono> createWithResponseAsync(Stri */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> createWithResponseAsync(String shareName, String fileName, - long fileContentLength, String fileAttributes, Integer timeout, Map metadata, - String filePermission, FilePermissionFormat filePermissionFormat, String filePermissionKey, - String fileCreationTime, String fileLastWriteTime, String fileChangeTime, String leaseId, - ShareFileHttpHeaders shareFileHttpHeaders, Context context) { + long fileContentLength, Integer timeout, Map metadata, String filePermission, + FilePermissionFormat filePermissionFormat, String filePermissionKey, String fileAttributes, + String fileCreationTime, String fileLastWriteTime, String fileChangeTime, String leaseId, String owner, + String group, String fileMode, NfsFileType nfsFileType, ShareFileHttpHeaders shareFileHttpHeaders, + Context context) { final String fileTypeConstant = "file"; final String accept = "application/xml"; String contentTypeInternal = null; @@ -1364,7 +1558,8 @@ public Mono> createWithResponseAsync(Stri this.client.getVersion(), fileContentLength, fileTypeConstant, contentType, contentEncoding, contentLanguage, cacheControl, contentMd5Converted, contentDisposition, metadata, filePermission, filePermissionFormat, filePermissionKey, fileAttributes, fileCreationTime, fileLastWriteTime, - fileChangeTime, leaseId, this.client.getFileRequestIntent(), accept, context) + fileChangeTime, leaseId, this.client.getFileRequestIntent(), owner, group, fileMode, nfsFileType, + accept, context) .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); } @@ -1374,8 +1569,6 @@ public Mono> createWithResponseAsync(Stri * @param shareName The name of the target share. * @param fileName The path of the target file. * @param fileContentLength Specifies the maximum size for the file, up to 4 TB. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -1391,10 +1584,16 @@ public Mono> createWithResponseAsync(Stri * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. + * @param nfsFileType Optional, NFS only. Type of the file or directory. * @param shareFileHttpHeaders Parameter group. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. @@ -1402,13 +1601,14 @@ public Mono> createWithResponseAsync(Stri * @return A {@link Mono} that completes when a successful response is received. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createAsync(String shareName, String fileName, long fileContentLength, String fileAttributes, - Integer timeout, Map metadata, String filePermission, FilePermissionFormat filePermissionFormat, - String filePermissionKey, String fileCreationTime, String fileLastWriteTime, String fileChangeTime, - String leaseId, ShareFileHttpHeaders shareFileHttpHeaders) { - return createWithResponseAsync(shareName, fileName, fileContentLength, fileAttributes, timeout, metadata, - filePermission, filePermissionFormat, filePermissionKey, fileCreationTime, fileLastWriteTime, - fileChangeTime, leaseId, shareFileHttpHeaders) + public Mono createAsync(String shareName, String fileName, long fileContentLength, Integer timeout, + Map metadata, String filePermission, FilePermissionFormat filePermissionFormat, + String filePermissionKey, String fileAttributes, String fileCreationTime, String fileLastWriteTime, + String fileChangeTime, String leaseId, String owner, String group, String fileMode, NfsFileType nfsFileType, + ShareFileHttpHeaders shareFileHttpHeaders) { + return createWithResponseAsync(shareName, fileName, fileContentLength, timeout, metadata, filePermission, + filePermissionFormat, filePermissionKey, fileAttributes, fileCreationTime, fileLastWriteTime, + fileChangeTime, leaseId, owner, group, fileMode, nfsFileType, shareFileHttpHeaders) .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException) .flatMap(ignored -> Mono.empty()); } @@ -1419,8 +1619,6 @@ public Mono createAsync(String shareName, String fileName, long fileConten * @param shareName The name of the target share. * @param fileName The path of the target file. * @param fileContentLength Specifies the maximum size for the file, up to 4 TB. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -1436,10 +1634,16 @@ public Mono createAsync(String shareName, String fileName, long fileConten * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. + * @param nfsFileType Optional, NFS only. Type of the file or directory. * @param shareFileHttpHeaders Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -1448,13 +1652,14 @@ public Mono createAsync(String shareName, String fileName, long fileConten * @return A {@link Mono} that completes when a successful response is received. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createAsync(String shareName, String fileName, long fileContentLength, String fileAttributes, - Integer timeout, Map metadata, String filePermission, FilePermissionFormat filePermissionFormat, - String filePermissionKey, String fileCreationTime, String fileLastWriteTime, String fileChangeTime, - String leaseId, ShareFileHttpHeaders shareFileHttpHeaders, Context context) { - return createWithResponseAsync(shareName, fileName, fileContentLength, fileAttributes, timeout, metadata, - filePermission, filePermissionFormat, filePermissionKey, fileCreationTime, fileLastWriteTime, - fileChangeTime, leaseId, shareFileHttpHeaders, context) + public Mono createAsync(String shareName, String fileName, long fileContentLength, Integer timeout, + Map metadata, String filePermission, FilePermissionFormat filePermissionFormat, + String filePermissionKey, String fileAttributes, String fileCreationTime, String fileLastWriteTime, + String fileChangeTime, String leaseId, String owner, String group, String fileMode, NfsFileType nfsFileType, + ShareFileHttpHeaders shareFileHttpHeaders, Context context) { + return createWithResponseAsync(shareName, fileName, fileContentLength, timeout, metadata, filePermission, + filePermissionFormat, filePermissionKey, fileAttributes, fileCreationTime, fileLastWriteTime, + fileChangeTime, leaseId, owner, group, fileMode, nfsFileType, shareFileHttpHeaders, context) .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException) .flatMap(ignored -> Mono.empty()); } @@ -1465,8 +1670,6 @@ public Mono createAsync(String shareName, String fileName, long fileConten * @param shareName The name of the target share. * @param fileName The path of the target file. * @param fileContentLength Specifies the maximum size for the file, up to 4 TB. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -1482,10 +1685,16 @@ public Mono createAsync(String shareName, String fileName, long fileConten * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. + * @param nfsFileType Optional, NFS only. Type of the file or directory. * @param shareFileHttpHeaders Parameter group. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. @@ -1494,14 +1703,15 @@ public Mono createAsync(String shareName, String fileName, long fileConten */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> createNoCustomHeadersWithResponseAsync(String shareName, String fileName, - long fileContentLength, String fileAttributes, Integer timeout, Map metadata, - String filePermission, FilePermissionFormat filePermissionFormat, String filePermissionKey, - String fileCreationTime, String fileLastWriteTime, String fileChangeTime, String leaseId, - ShareFileHttpHeaders shareFileHttpHeaders) { + long fileContentLength, Integer timeout, Map metadata, String filePermission, + FilePermissionFormat filePermissionFormat, String filePermissionKey, String fileAttributes, + String fileCreationTime, String fileLastWriteTime, String fileChangeTime, String leaseId, String owner, + String group, String fileMode, NfsFileType nfsFileType, ShareFileHttpHeaders shareFileHttpHeaders) { return FluxUtil .withContext(context -> createNoCustomHeadersWithResponseAsync(shareName, fileName, fileContentLength, - fileAttributes, timeout, metadata, filePermission, filePermissionFormat, filePermissionKey, - fileCreationTime, fileLastWriteTime, fileChangeTime, leaseId, shareFileHttpHeaders, context)) + timeout, metadata, filePermission, filePermissionFormat, filePermissionKey, fileAttributes, + fileCreationTime, fileLastWriteTime, fileChangeTime, leaseId, owner, group, fileMode, nfsFileType, + shareFileHttpHeaders, context)) .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); } @@ -1511,8 +1721,6 @@ public Mono> createNoCustomHeadersWithResponseAsync(String shareN * @param shareName The name of the target share. * @param fileName The path of the target file. * @param fileContentLength Specifies the maximum size for the file, up to 4 TB. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -1528,10 +1736,16 @@ public Mono> createNoCustomHeadersWithResponseAsync(String shareN * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. + * @param nfsFileType Optional, NFS only. Type of the file or directory. * @param shareFileHttpHeaders Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -1541,10 +1755,11 @@ public Mono> createNoCustomHeadersWithResponseAsync(String shareN */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> createNoCustomHeadersWithResponseAsync(String shareName, String fileName, - long fileContentLength, String fileAttributes, Integer timeout, Map metadata, - String filePermission, FilePermissionFormat filePermissionFormat, String filePermissionKey, - String fileCreationTime, String fileLastWriteTime, String fileChangeTime, String leaseId, - ShareFileHttpHeaders shareFileHttpHeaders, Context context) { + long fileContentLength, Integer timeout, Map metadata, String filePermission, + FilePermissionFormat filePermissionFormat, String filePermissionKey, String fileAttributes, + String fileCreationTime, String fileLastWriteTime, String fileChangeTime, String leaseId, String owner, + String group, String fileMode, NfsFileType nfsFileType, ShareFileHttpHeaders shareFileHttpHeaders, + Context context) { final String fileTypeConstant = "file"; final String accept = "application/xml"; String contentTypeInternal = null; @@ -1583,7 +1798,8 @@ public Mono> createNoCustomHeadersWithResponseAsync(String shareN this.client.getVersion(), fileContentLength, fileTypeConstant, contentType, contentEncoding, contentLanguage, cacheControl, contentMd5Converted, contentDisposition, metadata, filePermission, filePermissionFormat, filePermissionKey, fileAttributes, fileCreationTime, fileLastWriteTime, - fileChangeTime, leaseId, this.client.getFileRequestIntent(), accept, context) + fileChangeTime, leaseId, this.client.getFileRequestIntent(), owner, group, fileMode, nfsFileType, + accept, context) .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); } @@ -1593,8 +1809,6 @@ public Mono> createNoCustomHeadersWithResponseAsync(String shareN * @param shareName The name of the target share. * @param fileName The path of the target file. * @param fileContentLength Specifies the maximum size for the file, up to 4 TB. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -1610,10 +1824,16 @@ public Mono> createNoCustomHeadersWithResponseAsync(String shareN * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. + * @param nfsFileType Optional, NFS only. Type of the file or directory. * @param shareFileHttpHeaders Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -1623,10 +1843,11 @@ public Mono> createNoCustomHeadersWithResponseAsync(String shareN */ @ServiceMethod(returns = ReturnType.SINGLE) public ResponseBase createWithResponse(String shareName, String fileName, - long fileContentLength, String fileAttributes, Integer timeout, Map metadata, - String filePermission, FilePermissionFormat filePermissionFormat, String filePermissionKey, - String fileCreationTime, String fileLastWriteTime, String fileChangeTime, String leaseId, - ShareFileHttpHeaders shareFileHttpHeaders, Context context) { + long fileContentLength, Integer timeout, Map metadata, String filePermission, + FilePermissionFormat filePermissionFormat, String filePermissionKey, String fileAttributes, + String fileCreationTime, String fileLastWriteTime, String fileChangeTime, String leaseId, String owner, + String group, String fileMode, NfsFileType nfsFileType, ShareFileHttpHeaders shareFileHttpHeaders, + Context context) { try { final String fileTypeConstant = "file"; final String accept = "application/xml"; @@ -1665,7 +1886,8 @@ public ResponseBase createWithResponse(String shareNam timeout, this.client.getVersion(), fileContentLength, fileTypeConstant, contentType, contentEncoding, contentLanguage, cacheControl, contentMd5Converted, contentDisposition, metadata, filePermission, filePermissionFormat, filePermissionKey, fileAttributes, fileCreationTime, fileLastWriteTime, - fileChangeTime, leaseId, this.client.getFileRequestIntent(), accept, context); + fileChangeTime, leaseId, this.client.getFileRequestIntent(), owner, group, fileMode, nfsFileType, + accept, context); } catch (ShareStorageExceptionInternal internalException) { throw ModelHelper.mapToShareStorageException(internalException); } @@ -1677,8 +1899,6 @@ public ResponseBase createWithResponse(String shareNam * @param shareName The name of the target share. * @param fileName The path of the target file. * @param fileContentLength Specifies the maximum size for the file, up to 4 TB. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -1694,23 +1914,30 @@ public ResponseBase createWithResponse(String shareNam * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. + * @param nfsFileType Optional, NFS only. Type of the file or directory. * @param shareFileHttpHeaders Parameter group. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) - public void create(String shareName, String fileName, long fileContentLength, String fileAttributes, - Integer timeout, Map metadata, String filePermission, FilePermissionFormat filePermissionFormat, - String filePermissionKey, String fileCreationTime, String fileLastWriteTime, String fileChangeTime, - String leaseId, ShareFileHttpHeaders shareFileHttpHeaders) { - createWithResponse(shareName, fileName, fileContentLength, fileAttributes, timeout, metadata, filePermission, - filePermissionFormat, filePermissionKey, fileCreationTime, fileLastWriteTime, fileChangeTime, leaseId, - shareFileHttpHeaders, Context.NONE); + public void create(String shareName, String fileName, long fileContentLength, Integer timeout, + Map metadata, String filePermission, FilePermissionFormat filePermissionFormat, + String filePermissionKey, String fileAttributes, String fileCreationTime, String fileLastWriteTime, + String fileChangeTime, String leaseId, String owner, String group, String fileMode, NfsFileType nfsFileType, + ShareFileHttpHeaders shareFileHttpHeaders) { + createWithResponse(shareName, fileName, fileContentLength, timeout, metadata, filePermission, + filePermissionFormat, filePermissionKey, fileAttributes, fileCreationTime, fileLastWriteTime, + fileChangeTime, leaseId, owner, group, fileMode, nfsFileType, shareFileHttpHeaders, Context.NONE); } /** @@ -1719,8 +1946,6 @@ public void create(String shareName, String fileName, long fileContentLength, St * @param shareName The name of the target share. * @param fileName The path of the target file. * @param fileContentLength Specifies the maximum size for the file, up to 4 TB. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -1736,10 +1961,16 @@ public void create(String shareName, String fileName, long fileContentLength, St * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. + * @param nfsFileType Optional, NFS only. Type of the file or directory. * @param shareFileHttpHeaders Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -1749,10 +1980,10 @@ public void create(String shareName, String fileName, long fileContentLength, St */ @ServiceMethod(returns = ReturnType.SINGLE) public Response createNoCustomHeadersWithResponse(String shareName, String fileName, long fileContentLength, - String fileAttributes, Integer timeout, Map metadata, String filePermission, - FilePermissionFormat filePermissionFormat, String filePermissionKey, String fileCreationTime, - String fileLastWriteTime, String fileChangeTime, String leaseId, ShareFileHttpHeaders shareFileHttpHeaders, - Context context) { + Integer timeout, Map metadata, String filePermission, FilePermissionFormat filePermissionFormat, + String filePermissionKey, String fileAttributes, String fileCreationTime, String fileLastWriteTime, + String fileChangeTime, String leaseId, String owner, String group, String fileMode, NfsFileType nfsFileType, + ShareFileHttpHeaders shareFileHttpHeaders, Context context) { try { final String fileTypeConstant = "file"; final String accept = "application/xml"; @@ -1791,8 +2022,8 @@ public Response createNoCustomHeadersWithResponse(String shareName, String this.client.isAllowTrailingDot(), timeout, this.client.getVersion(), fileContentLength, fileTypeConstant, contentType, contentEncoding, contentLanguage, cacheControl, contentMd5Converted, contentDisposition, metadata, filePermission, filePermissionFormat, filePermissionKey, fileAttributes, - fileCreationTime, fileLastWriteTime, fileChangeTime, leaseId, this.client.getFileRequestIntent(), - accept, context); + fileCreationTime, fileLastWriteTime, fileChangeTime, leaseId, this.client.getFileRequestIntent(), owner, + group, fileMode, nfsFileType, accept, context); } catch (ShareStorageExceptionInternal internalException) { throw ModelHelper.mapToShareStorageException(internalException); } @@ -2529,8 +2760,6 @@ public Response deleteNoCustomHeadersWithResponse(String shareName, String * * @param shareName The name of the target share. * @param fileName The path of the target file. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -2547,10 +2776,15 @@ public Response deleteNoCustomHeadersWithResponse(String shareName, String * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. * @param shareFileHttpHeaders Parameter group. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. @@ -2559,13 +2793,14 @@ public Response deleteNoCustomHeadersWithResponse(String shareName, String */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> setHttpHeadersWithResponseAsync(String shareName, - String fileName, String fileAttributes, Integer timeout, Long fileContentLength, String filePermission, - FilePermissionFormat filePermissionFormat, String filePermissionKey, String fileCreationTime, - String fileLastWriteTime, String fileChangeTime, String leaseId, ShareFileHttpHeaders shareFileHttpHeaders) { + String fileName, Integer timeout, Long fileContentLength, String filePermission, + FilePermissionFormat filePermissionFormat, String filePermissionKey, String fileAttributes, + String fileCreationTime, String fileLastWriteTime, String fileChangeTime, String leaseId, String owner, + String group, String fileMode, ShareFileHttpHeaders shareFileHttpHeaders) { return FluxUtil - .withContext(context -> setHttpHeadersWithResponseAsync(shareName, fileName, fileAttributes, timeout, - fileContentLength, filePermission, filePermissionFormat, filePermissionKey, fileCreationTime, - fileLastWriteTime, fileChangeTime, leaseId, shareFileHttpHeaders, context)) + .withContext(context -> setHttpHeadersWithResponseAsync(shareName, fileName, timeout, fileContentLength, + filePermission, filePermissionFormat, filePermissionKey, fileAttributes, fileCreationTime, + fileLastWriteTime, fileChangeTime, leaseId, owner, group, fileMode, shareFileHttpHeaders, context)) .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); } @@ -2574,8 +2809,6 @@ public Mono> setHttpHeadersWithRe * * @param shareName The name of the target share. * @param fileName The path of the target file. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -2592,10 +2825,15 @@ public Mono> setHttpHeadersWithRe * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. * @param shareFileHttpHeaders Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -2605,10 +2843,10 @@ public Mono> setHttpHeadersWithRe */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> setHttpHeadersWithResponseAsync(String shareName, - String fileName, String fileAttributes, Integer timeout, Long fileContentLength, String filePermission, - FilePermissionFormat filePermissionFormat, String filePermissionKey, String fileCreationTime, - String fileLastWriteTime, String fileChangeTime, String leaseId, ShareFileHttpHeaders shareFileHttpHeaders, - Context context) { + String fileName, Integer timeout, Long fileContentLength, String filePermission, + FilePermissionFormat filePermissionFormat, String filePermissionKey, String fileAttributes, + String fileCreationTime, String fileLastWriteTime, String fileChangeTime, String leaseId, String owner, + String group, String fileMode, ShareFileHttpHeaders shareFileHttpHeaders, Context context) { final String comp = "properties"; final String accept = "application/xml"; String contentTypeInternal = null; @@ -2647,7 +2885,7 @@ public Mono> setHttpHeadersWithRe fileContentLength, contentType, contentEncoding, contentLanguage, cacheControl, contentMd5Converted, contentDisposition, filePermission, filePermissionFormat, filePermissionKey, fileAttributes, fileCreationTime, fileLastWriteTime, fileChangeTime, leaseId, this.client.isAllowTrailingDot(), - this.client.getFileRequestIntent(), accept, context) + this.client.getFileRequestIntent(), owner, group, fileMode, accept, context) .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); } @@ -2656,8 +2894,6 @@ public Mono> setHttpHeadersWithRe * * @param shareName The name of the target share. * @param fileName The path of the target file. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -2674,10 +2910,15 @@ public Mono> setHttpHeadersWithRe * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. * @param shareFileHttpHeaders Parameter group. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. @@ -2685,13 +2926,13 @@ public Mono> setHttpHeadersWithRe * @return A {@link Mono} that completes when a successful response is received. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono setHttpHeadersAsync(String shareName, String fileName, String fileAttributes, Integer timeout, - Long fileContentLength, String filePermission, FilePermissionFormat filePermissionFormat, - String filePermissionKey, String fileCreationTime, String fileLastWriteTime, String fileChangeTime, - String leaseId, ShareFileHttpHeaders shareFileHttpHeaders) { - return setHttpHeadersWithResponseAsync(shareName, fileName, fileAttributes, timeout, fileContentLength, - filePermission, filePermissionFormat, filePermissionKey, fileCreationTime, fileLastWriteTime, - fileChangeTime, leaseId, shareFileHttpHeaders) + public Mono setHttpHeadersAsync(String shareName, String fileName, Integer timeout, Long fileContentLength, + String filePermission, FilePermissionFormat filePermissionFormat, String filePermissionKey, + String fileAttributes, String fileCreationTime, String fileLastWriteTime, String fileChangeTime, String leaseId, + String owner, String group, String fileMode, ShareFileHttpHeaders shareFileHttpHeaders) { + return setHttpHeadersWithResponseAsync(shareName, fileName, timeout, fileContentLength, filePermission, + filePermissionFormat, filePermissionKey, fileAttributes, fileCreationTime, fileLastWriteTime, + fileChangeTime, leaseId, owner, group, fileMode, shareFileHttpHeaders) .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException) .flatMap(ignored -> Mono.empty()); } @@ -2701,8 +2942,6 @@ public Mono setHttpHeadersAsync(String shareName, String fileName, String * * @param shareName The name of the target share. * @param fileName The path of the target file. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -2719,10 +2958,15 @@ public Mono setHttpHeadersAsync(String shareName, String fileName, String * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. * @param shareFileHttpHeaders Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -2731,13 +2975,13 @@ public Mono setHttpHeadersAsync(String shareName, String fileName, String * @return A {@link Mono} that completes when a successful response is received. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono setHttpHeadersAsync(String shareName, String fileName, String fileAttributes, Integer timeout, - Long fileContentLength, String filePermission, FilePermissionFormat filePermissionFormat, - String filePermissionKey, String fileCreationTime, String fileLastWriteTime, String fileChangeTime, - String leaseId, ShareFileHttpHeaders shareFileHttpHeaders, Context context) { - return setHttpHeadersWithResponseAsync(shareName, fileName, fileAttributes, timeout, fileContentLength, - filePermission, filePermissionFormat, filePermissionKey, fileCreationTime, fileLastWriteTime, - fileChangeTime, leaseId, shareFileHttpHeaders, context) + public Mono setHttpHeadersAsync(String shareName, String fileName, Integer timeout, Long fileContentLength, + String filePermission, FilePermissionFormat filePermissionFormat, String filePermissionKey, + String fileAttributes, String fileCreationTime, String fileLastWriteTime, String fileChangeTime, String leaseId, + String owner, String group, String fileMode, ShareFileHttpHeaders shareFileHttpHeaders, Context context) { + return setHttpHeadersWithResponseAsync(shareName, fileName, timeout, fileContentLength, filePermission, + filePermissionFormat, filePermissionKey, fileAttributes, fileCreationTime, fileLastWriteTime, + fileChangeTime, leaseId, owner, group, fileMode, shareFileHttpHeaders, context) .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException) .flatMap(ignored -> Mono.empty()); } @@ -2747,8 +2991,6 @@ public Mono setHttpHeadersAsync(String shareName, String fileName, String * * @param shareName The name of the target share. * @param fileName The path of the target file. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -2765,10 +3007,15 @@ public Mono setHttpHeadersAsync(String shareName, String fileName, String * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. * @param shareFileHttpHeaders Parameter group. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. @@ -2777,13 +3024,15 @@ public Mono setHttpHeadersAsync(String shareName, String fileName, String */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> setHttpHeadersNoCustomHeadersWithResponseAsync(String shareName, String fileName, - String fileAttributes, Integer timeout, Long fileContentLength, String filePermission, - FilePermissionFormat filePermissionFormat, String filePermissionKey, String fileCreationTime, - String fileLastWriteTime, String fileChangeTime, String leaseId, ShareFileHttpHeaders shareFileHttpHeaders) { + Integer timeout, Long fileContentLength, String filePermission, FilePermissionFormat filePermissionFormat, + String filePermissionKey, String fileAttributes, String fileCreationTime, String fileLastWriteTime, + String fileChangeTime, String leaseId, String owner, String group, String fileMode, + ShareFileHttpHeaders shareFileHttpHeaders) { return FluxUtil - .withContext(context -> setHttpHeadersNoCustomHeadersWithResponseAsync(shareName, fileName, fileAttributes, - timeout, fileContentLength, filePermission, filePermissionFormat, filePermissionKey, fileCreationTime, - fileLastWriteTime, fileChangeTime, leaseId, shareFileHttpHeaders, context)) + .withContext(context -> setHttpHeadersNoCustomHeadersWithResponseAsync(shareName, fileName, timeout, + fileContentLength, filePermission, filePermissionFormat, filePermissionKey, fileAttributes, + fileCreationTime, fileLastWriteTime, fileChangeTime, leaseId, owner, group, fileMode, + shareFileHttpHeaders, context)) .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); } @@ -2792,8 +3041,6 @@ public Mono> setHttpHeadersNoCustomHeadersWithResponseAsync(Strin * * @param shareName The name of the target share. * @param fileName The path of the target file. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -2810,10 +3057,15 @@ public Mono> setHttpHeadersNoCustomHeadersWithResponseAsync(Strin * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. * @param shareFileHttpHeaders Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -2823,10 +3075,10 @@ public Mono> setHttpHeadersNoCustomHeadersWithResponseAsync(Strin */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> setHttpHeadersNoCustomHeadersWithResponseAsync(String shareName, String fileName, - String fileAttributes, Integer timeout, Long fileContentLength, String filePermission, - FilePermissionFormat filePermissionFormat, String filePermissionKey, String fileCreationTime, - String fileLastWriteTime, String fileChangeTime, String leaseId, ShareFileHttpHeaders shareFileHttpHeaders, - Context context) { + Integer timeout, Long fileContentLength, String filePermission, FilePermissionFormat filePermissionFormat, + String filePermissionKey, String fileAttributes, String fileCreationTime, String fileLastWriteTime, + String fileChangeTime, String leaseId, String owner, String group, String fileMode, + ShareFileHttpHeaders shareFileHttpHeaders, Context context) { final String comp = "properties"; final String accept = "application/xml"; String contentTypeInternal = null; @@ -2865,7 +3117,8 @@ public Mono> setHttpHeadersNoCustomHeadersWithResponseAsync(Strin this.client.getVersion(), fileContentLength, contentType, contentEncoding, contentLanguage, cacheControl, contentMd5Converted, contentDisposition, filePermission, filePermissionFormat, filePermissionKey, fileAttributes, fileCreationTime, fileLastWriteTime, fileChangeTime, leaseId, - this.client.isAllowTrailingDot(), this.client.getFileRequestIntent(), accept, context) + this.client.isAllowTrailingDot(), this.client.getFileRequestIntent(), owner, group, fileMode, accept, + context) .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); } @@ -2874,8 +3127,6 @@ public Mono> setHttpHeadersNoCustomHeadersWithResponseAsync(Strin * * @param shareName The name of the target share. * @param fileName The path of the target file. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -2892,10 +3143,15 @@ public Mono> setHttpHeadersNoCustomHeadersWithResponseAsync(Strin * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. * @param shareFileHttpHeaders Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -2905,10 +3161,10 @@ public Mono> setHttpHeadersNoCustomHeadersWithResponseAsync(Strin */ @ServiceMethod(returns = ReturnType.SINGLE) public ResponseBase setHttpHeadersWithResponse(String shareName, String fileName, - String fileAttributes, Integer timeout, Long fileContentLength, String filePermission, - FilePermissionFormat filePermissionFormat, String filePermissionKey, String fileCreationTime, - String fileLastWriteTime, String fileChangeTime, String leaseId, ShareFileHttpHeaders shareFileHttpHeaders, - Context context) { + Integer timeout, Long fileContentLength, String filePermission, FilePermissionFormat filePermissionFormat, + String filePermissionKey, String fileAttributes, String fileCreationTime, String fileLastWriteTime, + String fileChangeTime, String leaseId, String owner, String group, String fileMode, + ShareFileHttpHeaders shareFileHttpHeaders, Context context) { try { final String comp = "properties"; final String accept = "application/xml"; @@ -2947,7 +3203,8 @@ public ResponseBase setHttpHeadersWithResponse this.client.getVersion(), fileContentLength, contentType, contentEncoding, contentLanguage, cacheControl, contentMd5Converted, contentDisposition, filePermission, filePermissionFormat, filePermissionKey, fileAttributes, fileCreationTime, fileLastWriteTime, fileChangeTime, leaseId, - this.client.isAllowTrailingDot(), this.client.getFileRequestIntent(), accept, context); + this.client.isAllowTrailingDot(), this.client.getFileRequestIntent(), owner, group, fileMode, accept, + context); } catch (ShareStorageExceptionInternal internalException) { throw ModelHelper.mapToShareStorageException(internalException); } @@ -2958,8 +3215,6 @@ public ResponseBase setHttpHeadersWithResponse * * @param shareName The name of the target share. * @param fileName The path of the target file. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -2976,23 +3231,28 @@ public ResponseBase setHttpHeadersWithResponse * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. * @param shareFileHttpHeaders Parameter group. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) - public void setHttpHeaders(String shareName, String fileName, String fileAttributes, Integer timeout, - Long fileContentLength, String filePermission, FilePermissionFormat filePermissionFormat, - String filePermissionKey, String fileCreationTime, String fileLastWriteTime, String fileChangeTime, - String leaseId, ShareFileHttpHeaders shareFileHttpHeaders) { - setHttpHeadersWithResponse(shareName, fileName, fileAttributes, timeout, fileContentLength, filePermission, - filePermissionFormat, filePermissionKey, fileCreationTime, fileLastWriteTime, fileChangeTime, leaseId, - shareFileHttpHeaders, Context.NONE); + public void setHttpHeaders(String shareName, String fileName, Integer timeout, Long fileContentLength, + String filePermission, FilePermissionFormat filePermissionFormat, String filePermissionKey, + String fileAttributes, String fileCreationTime, String fileLastWriteTime, String fileChangeTime, String leaseId, + String owner, String group, String fileMode, ShareFileHttpHeaders shareFileHttpHeaders) { + setHttpHeadersWithResponse(shareName, fileName, timeout, fileContentLength, filePermission, + filePermissionFormat, filePermissionKey, fileAttributes, fileCreationTime, fileLastWriteTime, + fileChangeTime, leaseId, owner, group, fileMode, shareFileHttpHeaders, Context.NONE); } /** @@ -3000,8 +3260,6 @@ public void setHttpHeaders(String shareName, String fileName, String fileAttribu * * @param shareName The name of the target share. * @param fileName The path of the target file. - * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file - * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param timeout The timeout parameter is expressed in seconds. For more information, see <a * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting * Timeouts for File Service Operations.</a>. @@ -3018,10 +3276,15 @@ public void setHttpHeaders(String shareName, String fileName, String fileAttribu * permission. * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. + * @param fileAttributes If specified, the provided file attributes shall be set. Default value: ‘Archive’ for file + * and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreationTime Creation time for the file/directory. Default value: Now. * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. * @param fileChangeTime Change time for the file/directory. Default value: Now. * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. * @param shareFileHttpHeaders Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -3030,11 +3293,11 @@ public void setHttpHeaders(String shareName, String fileName, String fileAttribu * @return the {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response setHttpHeadersNoCustomHeadersWithResponse(String shareName, String fileName, - String fileAttributes, Integer timeout, Long fileContentLength, String filePermission, - FilePermissionFormat filePermissionFormat, String filePermissionKey, String fileCreationTime, - String fileLastWriteTime, String fileChangeTime, String leaseId, ShareFileHttpHeaders shareFileHttpHeaders, - Context context) { + public Response setHttpHeadersNoCustomHeadersWithResponse(String shareName, String fileName, Integer timeout, + Long fileContentLength, String filePermission, FilePermissionFormat filePermissionFormat, + String filePermissionKey, String fileAttributes, String fileCreationTime, String fileLastWriteTime, + String fileChangeTime, String leaseId, String owner, String group, String fileMode, + ShareFileHttpHeaders shareFileHttpHeaders, Context context) { try { final String comp = "properties"; final String accept = "application/xml"; @@ -3073,7 +3336,8 @@ public Response setHttpHeadersNoCustomHeadersWithResponse(String shareName this.client.getVersion(), fileContentLength, contentType, contentEncoding, contentLanguage, cacheControl, contentMd5Converted, contentDisposition, filePermission, filePermissionFormat, filePermissionKey, fileAttributes, fileCreationTime, fileLastWriteTime, fileChangeTime, leaseId, - this.client.isAllowTrailingDot(), this.client.getFileRequestIntent(), accept, context); + this.client.isAllowTrailingDot(), this.client.getFileRequestIntent(), owner, group, fileMode, accept, + context); } catch (ShareStorageExceptionInternal internalException) { throw ModelHelper.mapToShareStorageException(internalException); } @@ -5901,6 +6165,16 @@ public Response getRangeListNoCustomHeadersWithResponse(Stri * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. + * @param fileModeCopyMode NFS only. Applicable only when the copy source is a File. Determines the copy behavior of + * the mode bits of the file. source: The mode on the destination file is copied from the source file. override: The + * mode on the destination file is determined via the x-ms-mode header. + * @param fileOwnerCopyMode NFS only. Determines the copy behavior of the owner user identifier (UID) and group + * identifier (GID) of the file. source: The owner user identifier (UID) and group identifier (GID) on the + * destination file is copied from the source file. override: The owner user identifier (UID) and group identifier + * (GID) on the destination file is determined via the x-ms-owner and x-ms-group headers. * @param copyFileSmbInfo Parameter group. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. @@ -5910,11 +6184,13 @@ public Response getRangeListNoCustomHeadersWithResponse(Stri @ServiceMethod(returns = ReturnType.SINGLE) public Mono> startCopyWithResponseAsync(String shareName, String fileName, String copySource, Integer timeout, Map metadata, String filePermission, - FilePermissionFormat filePermissionFormat, String filePermissionKey, String leaseId, + FilePermissionFormat filePermissionFormat, String filePermissionKey, String leaseId, String owner, String group, + String fileMode, ModeCopyMode fileModeCopyMode, OwnerCopyMode fileOwnerCopyMode, CopyFileSmbInfo copyFileSmbInfo) { return FluxUtil .withContext(context -> startCopyWithResponseAsync(shareName, fileName, copySource, timeout, metadata, - filePermission, filePermissionFormat, filePermissionKey, leaseId, copyFileSmbInfo, context)) + filePermission, filePermissionFormat, filePermissionKey, leaseId, owner, group, fileMode, + fileModeCopyMode, fileOwnerCopyMode, copyFileSmbInfo, context)) .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); } @@ -5945,6 +6221,16 @@ public Mono> startCopyWithResponseAsyn * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. + * @param fileModeCopyMode NFS only. Applicable only when the copy source is a File. Determines the copy behavior of + * the mode bits of the file. source: The mode on the destination file is copied from the source file. override: The + * mode on the destination file is determined via the x-ms-mode header. + * @param fileOwnerCopyMode NFS only. Determines the copy behavior of the owner user identifier (UID) and group + * identifier (GID) of the file. source: The owner user identifier (UID) and group identifier (GID) on the + * destination file is copied from the source file. override: The owner user identifier (UID) and group identifier + * (GID) on the destination file is determined via the x-ms-owner and x-ms-group headers. * @param copyFileSmbInfo Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -5955,7 +6241,8 @@ public Mono> startCopyWithResponseAsyn @ServiceMethod(returns = ReturnType.SINGLE) public Mono> startCopyWithResponseAsync(String shareName, String fileName, String copySource, Integer timeout, Map metadata, String filePermission, - FilePermissionFormat filePermissionFormat, String filePermissionKey, String leaseId, + FilePermissionFormat filePermissionFormat, String filePermissionKey, String leaseId, String owner, String group, + String fileMode, ModeCopyMode fileModeCopyMode, OwnerCopyMode fileOwnerCopyMode, CopyFileSmbInfo copyFileSmbInfo, Context context) { final String accept = "application/xml"; PermissionCopyModeType filePermissionCopyModeInternal = null; @@ -5998,7 +6285,8 @@ public Mono> startCopyWithResponseAsyn copySource, filePermission, filePermissionFormat, filePermissionKey, filePermissionCopyMode, ignoreReadOnly, fileAttributes, fileCreationTime, fileLastWriteTime, fileChangeTime, setArchiveAttribute, leaseId, this.client.isAllowTrailingDot(), this.client.isAllowSourceTrailingDot(), - this.client.getFileRequestIntent(), accept, context) + this.client.getFileRequestIntent(), owner, group, fileMode, fileModeCopyMode, fileOwnerCopyMode, accept, + context) .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); } @@ -6029,6 +6317,16 @@ public Mono> startCopyWithResponseAsyn * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. + * @param fileModeCopyMode NFS only. Applicable only when the copy source is a File. Determines the copy behavior of + * the mode bits of the file. source: The mode on the destination file is copied from the source file. override: The + * mode on the destination file is determined via the x-ms-mode header. + * @param fileOwnerCopyMode NFS only. Determines the copy behavior of the owner user identifier (UID) and group + * identifier (GID) of the file. source: The owner user identifier (UID) and group identifier (GID) on the + * destination file is copied from the source file. override: The owner user identifier (UID) and group identifier + * (GID) on the destination file is determined via the x-ms-owner and x-ms-group headers. * @param copyFileSmbInfo Parameter group. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. @@ -6038,9 +6336,11 @@ public Mono> startCopyWithResponseAsyn @ServiceMethod(returns = ReturnType.SINGLE) public Mono startCopyAsync(String shareName, String fileName, String copySource, Integer timeout, Map metadata, String filePermission, FilePermissionFormat filePermissionFormat, - String filePermissionKey, String leaseId, CopyFileSmbInfo copyFileSmbInfo) { + String filePermissionKey, String leaseId, String owner, String group, String fileMode, + ModeCopyMode fileModeCopyMode, OwnerCopyMode fileOwnerCopyMode, CopyFileSmbInfo copyFileSmbInfo) { return startCopyWithResponseAsync(shareName, fileName, copySource, timeout, metadata, filePermission, - filePermissionFormat, filePermissionKey, leaseId, copyFileSmbInfo) + filePermissionFormat, filePermissionKey, leaseId, owner, group, fileMode, fileModeCopyMode, + fileOwnerCopyMode, copyFileSmbInfo) .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException) .flatMap(ignored -> Mono.empty()); } @@ -6072,6 +6372,16 @@ public Mono startCopyAsync(String shareName, String fileName, String copyS * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. + * @param fileModeCopyMode NFS only. Applicable only when the copy source is a File. Determines the copy behavior of + * the mode bits of the file. source: The mode on the destination file is copied from the source file. override: The + * mode on the destination file is determined via the x-ms-mode header. + * @param fileOwnerCopyMode NFS only. Determines the copy behavior of the owner user identifier (UID) and group + * identifier (GID) of the file. source: The owner user identifier (UID) and group identifier (GID) on the + * destination file is copied from the source file. override: The owner user identifier (UID) and group identifier + * (GID) on the destination file is determined via the x-ms-owner and x-ms-group headers. * @param copyFileSmbInfo Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -6082,9 +6392,12 @@ public Mono startCopyAsync(String shareName, String fileName, String copyS @ServiceMethod(returns = ReturnType.SINGLE) public Mono startCopyAsync(String shareName, String fileName, String copySource, Integer timeout, Map metadata, String filePermission, FilePermissionFormat filePermissionFormat, - String filePermissionKey, String leaseId, CopyFileSmbInfo copyFileSmbInfo, Context context) { + String filePermissionKey, String leaseId, String owner, String group, String fileMode, + ModeCopyMode fileModeCopyMode, OwnerCopyMode fileOwnerCopyMode, CopyFileSmbInfo copyFileSmbInfo, + Context context) { return startCopyWithResponseAsync(shareName, fileName, copySource, timeout, metadata, filePermission, - filePermissionFormat, filePermissionKey, leaseId, copyFileSmbInfo, context) + filePermissionFormat, filePermissionKey, leaseId, owner, group, fileMode, fileModeCopyMode, + fileOwnerCopyMode, copyFileSmbInfo, context) .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException) .flatMap(ignored -> Mono.empty()); } @@ -6116,6 +6429,16 @@ public Mono startCopyAsync(String shareName, String fileName, String copyS * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. + * @param fileModeCopyMode NFS only. Applicable only when the copy source is a File. Determines the copy behavior of + * the mode bits of the file. source: The mode on the destination file is copied from the source file. override: The + * mode on the destination file is determined via the x-ms-mode header. + * @param fileOwnerCopyMode NFS only. Determines the copy behavior of the owner user identifier (UID) and group + * identifier (GID) of the file. source: The owner user identifier (UID) and group identifier (GID) on the + * destination file is copied from the source file. override: The owner user identifier (UID) and group identifier + * (GID) on the destination file is determined via the x-ms-owner and x-ms-group headers. * @param copyFileSmbInfo Parameter group. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. @@ -6125,11 +6448,13 @@ public Mono startCopyAsync(String shareName, String fileName, String copyS @ServiceMethod(returns = ReturnType.SINGLE) public Mono> startCopyNoCustomHeadersWithResponseAsync(String shareName, String fileName, String copySource, Integer timeout, Map metadata, String filePermission, - FilePermissionFormat filePermissionFormat, String filePermissionKey, String leaseId, + FilePermissionFormat filePermissionFormat, String filePermissionKey, String leaseId, String owner, String group, + String fileMode, ModeCopyMode fileModeCopyMode, OwnerCopyMode fileOwnerCopyMode, CopyFileSmbInfo copyFileSmbInfo) { return FluxUtil .withContext(context -> startCopyNoCustomHeadersWithResponseAsync(shareName, fileName, copySource, timeout, - metadata, filePermission, filePermissionFormat, filePermissionKey, leaseId, copyFileSmbInfo, context)) + metadata, filePermission, filePermissionFormat, filePermissionKey, leaseId, owner, group, fileMode, + fileModeCopyMode, fileOwnerCopyMode, copyFileSmbInfo, context)) .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); } @@ -6160,6 +6485,16 @@ public Mono> startCopyNoCustomHeadersWithResponseAsync(String sha * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. + * @param fileModeCopyMode NFS only. Applicable only when the copy source is a File. Determines the copy behavior of + * the mode bits of the file. source: The mode on the destination file is copied from the source file. override: The + * mode on the destination file is determined via the x-ms-mode header. + * @param fileOwnerCopyMode NFS only. Determines the copy behavior of the owner user identifier (UID) and group + * identifier (GID) of the file. source: The owner user identifier (UID) and group identifier (GID) on the + * destination file is copied from the source file. override: The owner user identifier (UID) and group identifier + * (GID) on the destination file is determined via the x-ms-owner and x-ms-group headers. * @param copyFileSmbInfo Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -6170,7 +6505,8 @@ public Mono> startCopyNoCustomHeadersWithResponseAsync(String sha @ServiceMethod(returns = ReturnType.SINGLE) public Mono> startCopyNoCustomHeadersWithResponseAsync(String shareName, String fileName, String copySource, Integer timeout, Map metadata, String filePermission, - FilePermissionFormat filePermissionFormat, String filePermissionKey, String leaseId, + FilePermissionFormat filePermissionFormat, String filePermissionKey, String leaseId, String owner, String group, + String fileMode, ModeCopyMode fileModeCopyMode, OwnerCopyMode fileOwnerCopyMode, CopyFileSmbInfo copyFileSmbInfo, Context context) { final String accept = "application/xml"; PermissionCopyModeType filePermissionCopyModeInternal = null; @@ -6213,7 +6549,8 @@ public Mono> startCopyNoCustomHeadersWithResponseAsync(String sha metadata, copySource, filePermission, filePermissionFormat, filePermissionKey, filePermissionCopyMode, ignoreReadOnly, fileAttributes, fileCreationTime, fileLastWriteTime, fileChangeTime, setArchiveAttribute, leaseId, this.client.isAllowTrailingDot(), this.client.isAllowSourceTrailingDot(), - this.client.getFileRequestIntent(), accept, context) + this.client.getFileRequestIntent(), owner, group, fileMode, fileModeCopyMode, fileOwnerCopyMode, accept, + context) .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); } @@ -6244,6 +6581,16 @@ public Mono> startCopyNoCustomHeadersWithResponseAsync(String sha * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. + * @param fileModeCopyMode NFS only. Applicable only when the copy source is a File. Determines the copy behavior of + * the mode bits of the file. source: The mode on the destination file is copied from the source file. override: The + * mode on the destination file is determined via the x-ms-mode header. + * @param fileOwnerCopyMode NFS only. Determines the copy behavior of the owner user identifier (UID) and group + * identifier (GID) of the file. source: The owner user identifier (UID) and group identifier (GID) on the + * destination file is copied from the source file. override: The owner user identifier (UID) and group identifier + * (GID) on the destination file is determined via the x-ms-owner and x-ms-group headers. * @param copyFileSmbInfo Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -6254,7 +6601,8 @@ public Mono> startCopyNoCustomHeadersWithResponseAsync(String sha @ServiceMethod(returns = ReturnType.SINGLE) public ResponseBase startCopyWithResponse(String shareName, String fileName, String copySource, Integer timeout, Map metadata, String filePermission, - FilePermissionFormat filePermissionFormat, String filePermissionKey, String leaseId, + FilePermissionFormat filePermissionFormat, String filePermissionKey, String leaseId, String owner, String group, + String fileMode, ModeCopyMode fileModeCopyMode, OwnerCopyMode fileOwnerCopyMode, CopyFileSmbInfo copyFileSmbInfo, Context context) { try { final String accept = "application/xml"; @@ -6297,7 +6645,8 @@ public ResponseBase startCopyWithResponse(String sh metadata, copySource, filePermission, filePermissionFormat, filePermissionKey, filePermissionCopyMode, ignoreReadOnly, fileAttributes, fileCreationTime, fileLastWriteTime, fileChangeTime, setArchiveAttribute, leaseId, this.client.isAllowTrailingDot(), this.client.isAllowSourceTrailingDot(), - this.client.getFileRequestIntent(), accept, context); + this.client.getFileRequestIntent(), owner, group, fileMode, fileModeCopyMode, fileOwnerCopyMode, accept, + context); } catch (ShareStorageExceptionInternal internalException) { throw ModelHelper.mapToShareStorageException(internalException); } @@ -6330,6 +6679,16 @@ public ResponseBase startCopyWithResponse(String sh * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. + * @param fileModeCopyMode NFS only. Applicable only when the copy source is a File. Determines the copy behavior of + * the mode bits of the file. source: The mode on the destination file is copied from the source file. override: The + * mode on the destination file is determined via the x-ms-mode header. + * @param fileOwnerCopyMode NFS only. Determines the copy behavior of the owner user identifier (UID) and group + * identifier (GID) of the file. source: The owner user identifier (UID) and group identifier (GID) on the + * destination file is copied from the source file. override: The owner user identifier (UID) and group identifier + * (GID) on the destination file is determined via the x-ms-owner and x-ms-group headers. * @param copyFileSmbInfo Parameter group. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. @@ -6338,9 +6697,11 @@ public ResponseBase startCopyWithResponse(String sh @ServiceMethod(returns = ReturnType.SINGLE) public void startCopy(String shareName, String fileName, String copySource, Integer timeout, Map metadata, String filePermission, FilePermissionFormat filePermissionFormat, - String filePermissionKey, String leaseId, CopyFileSmbInfo copyFileSmbInfo) { + String filePermissionKey, String leaseId, String owner, String group, String fileMode, + ModeCopyMode fileModeCopyMode, OwnerCopyMode fileOwnerCopyMode, CopyFileSmbInfo copyFileSmbInfo) { startCopyWithResponse(shareName, fileName, copySource, timeout, metadata, filePermission, filePermissionFormat, - filePermissionKey, leaseId, copyFileSmbInfo, Context.NONE); + filePermissionKey, leaseId, owner, group, fileMode, fileModeCopyMode, fileOwnerCopyMode, copyFileSmbInfo, + Context.NONE); } /** @@ -6370,6 +6731,16 @@ public void startCopy(String shareName, String fileName, String copySource, Inte * @param filePermissionKey Key of the permission to be set for the directory/file. Note: Only one of the * x-ms-file-permission or x-ms-file-permission-key should be specified. * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param fileMode Optional, NFS only. The file mode of the file or directory. + * @param fileModeCopyMode NFS only. Applicable only when the copy source is a File. Determines the copy behavior of + * the mode bits of the file. source: The mode on the destination file is copied from the source file. override: The + * mode on the destination file is determined via the x-ms-mode header. + * @param fileOwnerCopyMode NFS only. Determines the copy behavior of the owner user identifier (UID) and group + * identifier (GID) of the file. source: The owner user identifier (UID) and group identifier (GID) on the + * destination file is copied from the source file. override: The owner user identifier (UID) and group identifier + * (GID) on the destination file is determined via the x-ms-owner and x-ms-group headers. * @param copyFileSmbInfo Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -6380,7 +6751,9 @@ public void startCopy(String shareName, String fileName, String copySource, Inte @ServiceMethod(returns = ReturnType.SINGLE) public Response startCopyNoCustomHeadersWithResponse(String shareName, String fileName, String copySource, Integer timeout, Map metadata, String filePermission, FilePermissionFormat filePermissionFormat, - String filePermissionKey, String leaseId, CopyFileSmbInfo copyFileSmbInfo, Context context) { + String filePermissionKey, String leaseId, String owner, String group, String fileMode, + ModeCopyMode fileModeCopyMode, OwnerCopyMode fileOwnerCopyMode, CopyFileSmbInfo copyFileSmbInfo, + Context context) { try { final String accept = "application/xml"; PermissionCopyModeType filePermissionCopyModeInternal = null; @@ -6422,7 +6795,8 @@ public Response startCopyNoCustomHeadersWithResponse(String shareName, Str this.client.getVersion(), metadata, copySource, filePermission, filePermissionFormat, filePermissionKey, filePermissionCopyMode, ignoreReadOnly, fileAttributes, fileCreationTime, fileLastWriteTime, fileChangeTime, setArchiveAttribute, leaseId, this.client.isAllowTrailingDot(), - this.client.isAllowSourceTrailingDot(), this.client.getFileRequestIntent(), accept, context); + this.client.isAllowSourceTrailingDot(), this.client.getFileRequestIntent(), owner, group, fileMode, + fileModeCopyMode, fileOwnerCopyMode, accept, context); } catch (ShareStorageExceptionInternal internalException) { throw ModelHelper.mapToShareStorageException(internalException); } @@ -7864,4 +8238,847 @@ public Response renameNoCustomHeadersWithResponse(String shareName, String throw ModelHelper.mapToShareStorageException(internalException); } } + + /** + * Creates a symbolic link. + * + * @param shareName The name of the target share. + * @param fileName The path of the target file. + * @param linkText NFS only. Required. The path to the original file, the symbolic link is pointing to. The path is + * of type string which is not resolved and is stored as is. The path can be absolute path or the relative path + * depending on the content stored in the symbolic link file. + * @param timeout The timeout parameter is expressed in seconds. For more information, see <a + * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting + * Timeouts for File Service Operations.</a>. + * @param metadata A name-value pair to associate with a file storage object. + * @param fileCreationTime Creation time for the file/directory. Default value: Now. + * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. + * @param requestId Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the + * analytics logs when storage analytics logging is enabled. + * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link ResponseBase} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createSymbolicLinkWithResponseAsync( + String shareName, String fileName, String linkText, Integer timeout, Map metadata, + String fileCreationTime, String fileLastWriteTime, String requestId, String leaseId, String owner, + String group) { + return FluxUtil + .withContext(context -> createSymbolicLinkWithResponseAsync(shareName, fileName, linkText, timeout, + metadata, fileCreationTime, fileLastWriteTime, requestId, leaseId, owner, group, context)) + .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); + } + + /** + * Creates a symbolic link. + * + * @param shareName The name of the target share. + * @param fileName The path of the target file. + * @param linkText NFS only. Required. The path to the original file, the symbolic link is pointing to. The path is + * of type string which is not resolved and is stored as is. The path can be absolute path or the relative path + * depending on the content stored in the symbolic link file. + * @param timeout The timeout parameter is expressed in seconds. For more information, see <a + * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting + * Timeouts for File Service Operations.</a>. + * @param metadata A name-value pair to associate with a file storage object. + * @param fileCreationTime Creation time for the file/directory. Default value: Now. + * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. + * @param requestId Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the + * analytics logs when storage analytics logging is enabled. + * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link ResponseBase} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createSymbolicLinkWithResponseAsync( + String shareName, String fileName, String linkText, Integer timeout, Map metadata, + String fileCreationTime, String fileLastWriteTime, String requestId, String leaseId, String owner, String group, + Context context) { + final String restype = "symboliclink"; + final String accept = "application/xml"; + return service + .createSymbolicLink(this.client.getUrl(), shareName, fileName, restype, timeout, this.client.getVersion(), + metadata, fileCreationTime, fileLastWriteTime, requestId, leaseId, owner, group, linkText, + this.client.getFileRequestIntent(), accept, context) + .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); + } + + /** + * Creates a symbolic link. + * + * @param shareName The name of the target share. + * @param fileName The path of the target file. + * @param linkText NFS only. Required. The path to the original file, the symbolic link is pointing to. The path is + * of type string which is not resolved and is stored as is. The path can be absolute path or the relative path + * depending on the content stored in the symbolic link file. + * @param timeout The timeout parameter is expressed in seconds. For more information, see <a + * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting + * Timeouts for File Service Operations.</a>. + * @param metadata A name-value pair to associate with a file storage object. + * @param fileCreationTime Creation time for the file/directory. Default value: Now. + * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. + * @param requestId Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the + * analytics logs when storage analytics logging is enabled. + * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createSymbolicLinkAsync(String shareName, String fileName, String linkText, Integer timeout, + Map metadata, String fileCreationTime, String fileLastWriteTime, String requestId, + String leaseId, String owner, String group) { + return createSymbolicLinkWithResponseAsync(shareName, fileName, linkText, timeout, metadata, fileCreationTime, + fileLastWriteTime, requestId, leaseId, owner, group) + .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException) + .flatMap(ignored -> Mono.empty()); + } + + /** + * Creates a symbolic link. + * + * @param shareName The name of the target share. + * @param fileName The path of the target file. + * @param linkText NFS only. Required. The path to the original file, the symbolic link is pointing to. The path is + * of type string which is not resolved and is stored as is. The path can be absolute path or the relative path + * depending on the content stored in the symbolic link file. + * @param timeout The timeout parameter is expressed in seconds. For more information, see <a + * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting + * Timeouts for File Service Operations.</a>. + * @param metadata A name-value pair to associate with a file storage object. + * @param fileCreationTime Creation time for the file/directory. Default value: Now. + * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. + * @param requestId Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the + * analytics logs when storage analytics logging is enabled. + * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createSymbolicLinkAsync(String shareName, String fileName, String linkText, Integer timeout, + Map metadata, String fileCreationTime, String fileLastWriteTime, String requestId, + String leaseId, String owner, String group, Context context) { + return createSymbolicLinkWithResponseAsync(shareName, fileName, linkText, timeout, metadata, fileCreationTime, + fileLastWriteTime, requestId, leaseId, owner, group, context) + .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException) + .flatMap(ignored -> Mono.empty()); + } + + /** + * Creates a symbolic link. + * + * @param shareName The name of the target share. + * @param fileName The path of the target file. + * @param linkText NFS only. Required. The path to the original file, the symbolic link is pointing to. The path is + * of type string which is not resolved and is stored as is. The path can be absolute path or the relative path + * depending on the content stored in the symbolic link file. + * @param timeout The timeout parameter is expressed in seconds. For more information, see <a + * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting + * Timeouts for File Service Operations.</a>. + * @param metadata A name-value pair to associate with a file storage object. + * @param fileCreationTime Creation time for the file/directory. Default value: Now. + * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. + * @param requestId Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the + * analytics logs when storage analytics logging is enabled. + * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createSymbolicLinkNoCustomHeadersWithResponseAsync(String shareName, String fileName, + String linkText, Integer timeout, Map metadata, String fileCreationTime, + String fileLastWriteTime, String requestId, String leaseId, String owner, String group) { + return FluxUtil + .withContext(context -> createSymbolicLinkNoCustomHeadersWithResponseAsync(shareName, fileName, linkText, + timeout, metadata, fileCreationTime, fileLastWriteTime, requestId, leaseId, owner, group, context)) + .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); + } + + /** + * Creates a symbolic link. + * + * @param shareName The name of the target share. + * @param fileName The path of the target file. + * @param linkText NFS only. Required. The path to the original file, the symbolic link is pointing to. The path is + * of type string which is not resolved and is stored as is. The path can be absolute path or the relative path + * depending on the content stored in the symbolic link file. + * @param timeout The timeout parameter is expressed in seconds. For more information, see <a + * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting + * Timeouts for File Service Operations.</a>. + * @param metadata A name-value pair to associate with a file storage object. + * @param fileCreationTime Creation time for the file/directory. Default value: Now. + * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. + * @param requestId Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the + * analytics logs when storage analytics logging is enabled. + * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createSymbolicLinkNoCustomHeadersWithResponseAsync(String shareName, String fileName, + String linkText, Integer timeout, Map metadata, String fileCreationTime, + String fileLastWriteTime, String requestId, String leaseId, String owner, String group, Context context) { + final String restype = "symboliclink"; + final String accept = "application/xml"; + return service + .createSymbolicLinkNoCustomHeaders(this.client.getUrl(), shareName, fileName, restype, timeout, + this.client.getVersion(), metadata, fileCreationTime, fileLastWriteTime, requestId, leaseId, owner, + group, linkText, this.client.getFileRequestIntent(), accept, context) + .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); + } + + /** + * Creates a symbolic link. + * + * @param shareName The name of the target share. + * @param fileName The path of the target file. + * @param linkText NFS only. Required. The path to the original file, the symbolic link is pointing to. The path is + * of type string which is not resolved and is stored as is. The path can be absolute path or the relative path + * depending on the content stored in the symbolic link file. + * @param timeout The timeout parameter is expressed in seconds. For more information, see <a + * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting + * Timeouts for File Service Operations.</a>. + * @param metadata A name-value pair to associate with a file storage object. + * @param fileCreationTime Creation time for the file/directory. Default value: Now. + * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. + * @param requestId Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the + * analytics logs when storage analytics logging is enabled. + * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link ResponseBase}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public ResponseBase createSymbolicLinkWithResponse(String shareName, + String fileName, String linkText, Integer timeout, Map metadata, String fileCreationTime, + String fileLastWriteTime, String requestId, String leaseId, String owner, String group, Context context) { + try { + final String restype = "symboliclink"; + final String accept = "application/xml"; + return service.createSymbolicLinkSync(this.client.getUrl(), shareName, fileName, restype, timeout, + this.client.getVersion(), metadata, fileCreationTime, fileLastWriteTime, requestId, leaseId, owner, + group, linkText, this.client.getFileRequestIntent(), accept, context); + } catch (ShareStorageExceptionInternal internalException) { + throw ModelHelper.mapToShareStorageException(internalException); + } + } + + /** + * Creates a symbolic link. + * + * @param shareName The name of the target share. + * @param fileName The path of the target file. + * @param linkText NFS only. Required. The path to the original file, the symbolic link is pointing to. The path is + * of type string which is not resolved and is stored as is. The path can be absolute path or the relative path + * depending on the content stored in the symbolic link file. + * @param timeout The timeout parameter is expressed in seconds. For more information, see <a + * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting + * Timeouts for File Service Operations.</a>. + * @param metadata A name-value pair to associate with a file storage object. + * @param fileCreationTime Creation time for the file/directory. Default value: Now. + * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. + * @param requestId Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the + * analytics logs when storage analytics logging is enabled. + * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void createSymbolicLink(String shareName, String fileName, String linkText, Integer timeout, + Map metadata, String fileCreationTime, String fileLastWriteTime, String requestId, + String leaseId, String owner, String group) { + createSymbolicLinkWithResponse(shareName, fileName, linkText, timeout, metadata, fileCreationTime, + fileLastWriteTime, requestId, leaseId, owner, group, Context.NONE); + } + + /** + * Creates a symbolic link. + * + * @param shareName The name of the target share. + * @param fileName The path of the target file. + * @param linkText NFS only. Required. The path to the original file, the symbolic link is pointing to. The path is + * of type string which is not resolved and is stored as is. The path can be absolute path or the relative path + * depending on the content stored in the symbolic link file. + * @param timeout The timeout parameter is expressed in seconds. For more information, see <a + * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting + * Timeouts for File Service Operations.</a>. + * @param metadata A name-value pair to associate with a file storage object. + * @param fileCreationTime Creation time for the file/directory. Default value: Now. + * @param fileLastWriteTime Last write time for the file/directory. Default value: Now. + * @param requestId Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the + * analytics logs when storage analytics logging is enabled. + * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param owner Optional, NFS only. The owner of the file or directory. + * @param group Optional, NFS only. The owning group of the file or directory. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createSymbolicLinkNoCustomHeadersWithResponse(String shareName, String fileName, + String linkText, Integer timeout, Map metadata, String fileCreationTime, + String fileLastWriteTime, String requestId, String leaseId, String owner, String group, Context context) { + try { + final String restype = "symboliclink"; + final String accept = "application/xml"; + return service.createSymbolicLinkNoCustomHeadersSync(this.client.getUrl(), shareName, fileName, restype, + timeout, this.client.getVersion(), metadata, fileCreationTime, fileLastWriteTime, requestId, leaseId, + owner, group, linkText, this.client.getFileRequestIntent(), accept, context); + } catch (ShareStorageExceptionInternal internalException) { + throw ModelHelper.mapToShareStorageException(internalException); + } + } + + /** + * The getSymbolicLink operation. + * + * @param shareName The name of the target share. + * @param fileName The path of the target file. + * @param timeout The timeout parameter is expressed in seconds. For more information, see <a + * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting + * Timeouts for File Service Operations.</a>. + * @param sharesnapshot The snapshot parameter is an opaque DateTime value that, when present, specifies the share + * snapshot to query. + * @param requestId Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the + * analytics logs when storage analytics logging is enabled. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link ResponseBase} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getSymbolicLinkWithResponseAsync(String shareName, + String fileName, Integer timeout, String sharesnapshot, String requestId) { + return FluxUtil + .withContext(context -> getSymbolicLinkWithResponseAsync(shareName, fileName, timeout, sharesnapshot, + requestId, context)) + .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); + } + + /** + * The getSymbolicLink operation. + * + * @param shareName The name of the target share. + * @param fileName The path of the target file. + * @param timeout The timeout parameter is expressed in seconds. For more information, see <a + * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting + * Timeouts for File Service Operations.</a>. + * @param sharesnapshot The snapshot parameter is an opaque DateTime value that, when present, specifies the share + * snapshot to query. + * @param requestId Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the + * analytics logs when storage analytics logging is enabled. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link ResponseBase} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getSymbolicLinkWithResponseAsync(String shareName, + String fileName, Integer timeout, String sharesnapshot, String requestId, Context context) { + final String restype = "symboliclink"; + final String accept = "application/xml"; + return service + .getSymbolicLink(this.client.getUrl(), shareName, fileName, restype, timeout, sharesnapshot, + this.client.getVersion(), requestId, this.client.getFileRequestIntent(), accept, context) + .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); + } + + /** + * The getSymbolicLink operation. + * + * @param shareName The name of the target share. + * @param fileName The path of the target file. + * @param timeout The timeout parameter is expressed in seconds. For more information, see <a + * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting + * Timeouts for File Service Operations.</a>. + * @param sharesnapshot The snapshot parameter is an opaque DateTime value that, when present, specifies the share + * snapshot to query. + * @param requestId Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the + * analytics logs when storage analytics logging is enabled. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getSymbolicLinkAsync(String shareName, String fileName, Integer timeout, String sharesnapshot, + String requestId) { + return getSymbolicLinkWithResponseAsync(shareName, fileName, timeout, sharesnapshot, requestId) + .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException) + .flatMap(ignored -> Mono.empty()); + } + + /** + * The getSymbolicLink operation. + * + * @param shareName The name of the target share. + * @param fileName The path of the target file. + * @param timeout The timeout parameter is expressed in seconds. For more information, see <a + * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting + * Timeouts for File Service Operations.</a>. + * @param sharesnapshot The snapshot parameter is an opaque DateTime value that, when present, specifies the share + * snapshot to query. + * @param requestId Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the + * analytics logs when storage analytics logging is enabled. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getSymbolicLinkAsync(String shareName, String fileName, Integer timeout, String sharesnapshot, + String requestId, Context context) { + return getSymbolicLinkWithResponseAsync(shareName, fileName, timeout, sharesnapshot, requestId, context) + .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException) + .flatMap(ignored -> Mono.empty()); + } + + /** + * The getSymbolicLink operation. + * + * @param shareName The name of the target share. + * @param fileName The path of the target file. + * @param timeout The timeout parameter is expressed in seconds. For more information, see <a + * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting + * Timeouts for File Service Operations.</a>. + * @param sharesnapshot The snapshot parameter is an opaque DateTime value that, when present, specifies the share + * snapshot to query. + * @param requestId Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the + * analytics logs when storage analytics logging is enabled. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getSymbolicLinkNoCustomHeadersWithResponseAsync(String shareName, String fileName, + Integer timeout, String sharesnapshot, String requestId) { + return FluxUtil + .withContext(context -> getSymbolicLinkNoCustomHeadersWithResponseAsync(shareName, fileName, timeout, + sharesnapshot, requestId, context)) + .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); + } + + /** + * The getSymbolicLink operation. + * + * @param shareName The name of the target share. + * @param fileName The path of the target file. + * @param timeout The timeout parameter is expressed in seconds. For more information, see <a + * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting + * Timeouts for File Service Operations.</a>. + * @param sharesnapshot The snapshot parameter is an opaque DateTime value that, when present, specifies the share + * snapshot to query. + * @param requestId Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the + * analytics logs when storage analytics logging is enabled. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getSymbolicLinkNoCustomHeadersWithResponseAsync(String shareName, String fileName, + Integer timeout, String sharesnapshot, String requestId, Context context) { + final String restype = "symboliclink"; + final String accept = "application/xml"; + return service + .getSymbolicLinkNoCustomHeaders(this.client.getUrl(), shareName, fileName, restype, timeout, sharesnapshot, + this.client.getVersion(), requestId, this.client.getFileRequestIntent(), accept, context) + .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); + } + + /** + * The getSymbolicLink operation. + * + * @param shareName The name of the target share. + * @param fileName The path of the target file. + * @param timeout The timeout parameter is expressed in seconds. For more information, see <a + * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting + * Timeouts for File Service Operations.</a>. + * @param sharesnapshot The snapshot parameter is an opaque DateTime value that, when present, specifies the share + * snapshot to query. + * @param requestId Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the + * analytics logs when storage analytics logging is enabled. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link ResponseBase}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public ResponseBase getSymbolicLinkWithResponse(String shareName, + String fileName, Integer timeout, String sharesnapshot, String requestId, Context context) { + try { + final String restype = "symboliclink"; + final String accept = "application/xml"; + return service.getSymbolicLinkSync(this.client.getUrl(), shareName, fileName, restype, timeout, + sharesnapshot, this.client.getVersion(), requestId, this.client.getFileRequestIntent(), accept, + context); + } catch (ShareStorageExceptionInternal internalException) { + throw ModelHelper.mapToShareStorageException(internalException); + } + } + + /** + * The getSymbolicLink operation. + * + * @param shareName The name of the target share. + * @param fileName The path of the target file. + * @param timeout The timeout parameter is expressed in seconds. For more information, see <a + * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting + * Timeouts for File Service Operations.</a>. + * @param sharesnapshot The snapshot parameter is an opaque DateTime value that, when present, specifies the share + * snapshot to query. + * @param requestId Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the + * analytics logs when storage analytics logging is enabled. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void getSymbolicLink(String shareName, String fileName, Integer timeout, String sharesnapshot, + String requestId) { + getSymbolicLinkWithResponse(shareName, fileName, timeout, sharesnapshot, requestId, Context.NONE); + } + + /** + * The getSymbolicLink operation. + * + * @param shareName The name of the target share. + * @param fileName The path of the target file. + * @param timeout The timeout parameter is expressed in seconds. For more information, see <a + * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting + * Timeouts for File Service Operations.</a>. + * @param sharesnapshot The snapshot parameter is an opaque DateTime value that, when present, specifies the share + * snapshot to query. + * @param requestId Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the + * analytics logs when storage analytics logging is enabled. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getSymbolicLinkNoCustomHeadersWithResponse(String shareName, String fileName, Integer timeout, + String sharesnapshot, String requestId, Context context) { + try { + final String restype = "symboliclink"; + final String accept = "application/xml"; + return service.getSymbolicLinkNoCustomHeadersSync(this.client.getUrl(), shareName, fileName, restype, + timeout, sharesnapshot, this.client.getVersion(), requestId, this.client.getFileRequestIntent(), accept, + context); + } catch (ShareStorageExceptionInternal internalException) { + throw ModelHelper.mapToShareStorageException(internalException); + } + } + + /** + * Creates a hard link. + * + * @param shareName The name of the target share. + * @param fileName The path of the target file. + * @param targetFile NFS only. Required. Specifies the path of the target file to which the link will be created, up + * to 2 KiB in length. It should be full path of the target from the root.The target file must be in the same share + * and hence the same storage account. + * @param timeout The timeout parameter is expressed in seconds. For more information, see <a + * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting + * Timeouts for File Service Operations.</a>. + * @param requestId Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the + * analytics logs when storage analytics logging is enabled. + * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link ResponseBase} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createHardLinkWithResponseAsync(String shareName, + String fileName, String targetFile, Integer timeout, String requestId, String leaseId) { + return FluxUtil + .withContext(context -> createHardLinkWithResponseAsync(shareName, fileName, targetFile, timeout, requestId, + leaseId, context)) + .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); + } + + /** + * Creates a hard link. + * + * @param shareName The name of the target share. + * @param fileName The path of the target file. + * @param targetFile NFS only. Required. Specifies the path of the target file to which the link will be created, up + * to 2 KiB in length. It should be full path of the target from the root.The target file must be in the same share + * and hence the same storage account. + * @param timeout The timeout parameter is expressed in seconds. For more information, see <a + * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting + * Timeouts for File Service Operations.</a>. + * @param requestId Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the + * analytics logs when storage analytics logging is enabled. + * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link ResponseBase} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createHardLinkWithResponseAsync(String shareName, + String fileName, String targetFile, Integer timeout, String requestId, String leaseId, Context context) { + final String restype = "hardlink"; + final String fileTypeConstant = "file"; + final String accept = "application/xml"; + return service + .createHardLink(this.client.getUrl(), shareName, fileName, restype, timeout, this.client.getVersion(), + fileTypeConstant, requestId, leaseId, targetFile, this.client.getFileRequestIntent(), accept, context) + .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); + } + + /** + * Creates a hard link. + * + * @param shareName The name of the target share. + * @param fileName The path of the target file. + * @param targetFile NFS only. Required. Specifies the path of the target file to which the link will be created, up + * to 2 KiB in length. It should be full path of the target from the root.The target file must be in the same share + * and hence the same storage account. + * @param timeout The timeout parameter is expressed in seconds. For more information, see <a + * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting + * Timeouts for File Service Operations.</a>. + * @param requestId Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the + * analytics logs when storage analytics logging is enabled. + * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createHardLinkAsync(String shareName, String fileName, String targetFile, Integer timeout, + String requestId, String leaseId) { + return createHardLinkWithResponseAsync(shareName, fileName, targetFile, timeout, requestId, leaseId) + .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException) + .flatMap(ignored -> Mono.empty()); + } + + /** + * Creates a hard link. + * + * @param shareName The name of the target share. + * @param fileName The path of the target file. + * @param targetFile NFS only. Required. Specifies the path of the target file to which the link will be created, up + * to 2 KiB in length. It should be full path of the target from the root.The target file must be in the same share + * and hence the same storage account. + * @param timeout The timeout parameter is expressed in seconds. For more information, see <a + * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting + * Timeouts for File Service Operations.</a>. + * @param requestId Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the + * analytics logs when storage analytics logging is enabled. + * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createHardLinkAsync(String shareName, String fileName, String targetFile, Integer timeout, + String requestId, String leaseId, Context context) { + return createHardLinkWithResponseAsync(shareName, fileName, targetFile, timeout, requestId, leaseId, context) + .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException) + .flatMap(ignored -> Mono.empty()); + } + + /** + * Creates a hard link. + * + * @param shareName The name of the target share. + * @param fileName The path of the target file. + * @param targetFile NFS only. Required. Specifies the path of the target file to which the link will be created, up + * to 2 KiB in length. It should be full path of the target from the root.The target file must be in the same share + * and hence the same storage account. + * @param timeout The timeout parameter is expressed in seconds. For more information, see <a + * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting + * Timeouts for File Service Operations.</a>. + * @param requestId Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the + * analytics logs when storage analytics logging is enabled. + * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createHardLinkNoCustomHeadersWithResponseAsync(String shareName, String fileName, + String targetFile, Integer timeout, String requestId, String leaseId) { + return FluxUtil + .withContext(context -> createHardLinkNoCustomHeadersWithResponseAsync(shareName, fileName, targetFile, + timeout, requestId, leaseId, context)) + .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); + } + + /** + * Creates a hard link. + * + * @param shareName The name of the target share. + * @param fileName The path of the target file. + * @param targetFile NFS only. Required. Specifies the path of the target file to which the link will be created, up + * to 2 KiB in length. It should be full path of the target from the root.The target file must be in the same share + * and hence the same storage account. + * @param timeout The timeout parameter is expressed in seconds. For more information, see <a + * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting + * Timeouts for File Service Operations.</a>. + * @param requestId Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the + * analytics logs when storage analytics logging is enabled. + * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createHardLinkNoCustomHeadersWithResponseAsync(String shareName, String fileName, + String targetFile, Integer timeout, String requestId, String leaseId, Context context) { + final String restype = "hardlink"; + final String fileTypeConstant = "file"; + final String accept = "application/xml"; + return service + .createHardLinkNoCustomHeaders(this.client.getUrl(), shareName, fileName, restype, timeout, + this.client.getVersion(), fileTypeConstant, requestId, leaseId, targetFile, + this.client.getFileRequestIntent(), accept, context) + .onErrorMap(ShareStorageExceptionInternal.class, ModelHelper::mapToShareStorageException); + } + + /** + * Creates a hard link. + * + * @param shareName The name of the target share. + * @param fileName The path of the target file. + * @param targetFile NFS only. Required. Specifies the path of the target file to which the link will be created, up + * to 2 KiB in length. It should be full path of the target from the root.The target file must be in the same share + * and hence the same storage account. + * @param timeout The timeout parameter is expressed in seconds. For more information, see <a + * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting + * Timeouts for File Service Operations.</a>. + * @param requestId Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the + * analytics logs when storage analytics logging is enabled. + * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link ResponseBase}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public ResponseBase createHardLinkWithResponse(String shareName, String fileName, + String targetFile, Integer timeout, String requestId, String leaseId, Context context) { + try { + final String restype = "hardlink"; + final String fileTypeConstant = "file"; + final String accept = "application/xml"; + return service.createHardLinkSync(this.client.getUrl(), shareName, fileName, restype, timeout, + this.client.getVersion(), fileTypeConstant, requestId, leaseId, targetFile, + this.client.getFileRequestIntent(), accept, context); + } catch (ShareStorageExceptionInternal internalException) { + throw ModelHelper.mapToShareStorageException(internalException); + } + } + + /** + * Creates a hard link. + * + * @param shareName The name of the target share. + * @param fileName The path of the target file. + * @param targetFile NFS only. Required. Specifies the path of the target file to which the link will be created, up + * to 2 KiB in length. It should be full path of the target from the root.The target file must be in the same share + * and hence the same storage account. + * @param timeout The timeout parameter is expressed in seconds. For more information, see <a + * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting + * Timeouts for File Service Operations.</a>. + * @param requestId Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the + * analytics logs when storage analytics logging is enabled. + * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void createHardLink(String shareName, String fileName, String targetFile, Integer timeout, String requestId, + String leaseId) { + createHardLinkWithResponse(shareName, fileName, targetFile, timeout, requestId, leaseId, Context.NONE); + } + + /** + * Creates a hard link. + * + * @param shareName The name of the target share. + * @param fileName The path of the target file. + * @param targetFile NFS only. Required. Specifies the path of the target file to which the link will be created, up + * to 2 KiB in length. It should be full path of the target from the root.The target file must be in the same share + * and hence the same storage account. + * @param timeout The timeout parameter is expressed in seconds. For more information, see <a + * href="https://docs.microsoft.com/en-us/rest/api/storageservices/Setting-Timeouts-for-File-Service-Operations?redirectedfrom=MSDN">Setting + * Timeouts for File Service Operations.</a>. + * @param requestId Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the + * analytics logs when storage analytics logging is enabled. + * @param leaseId If specified, the operation only succeeds if the resource's lease is active and matches this ID. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ShareStorageExceptionInternal thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createHardLinkNoCustomHeadersWithResponse(String shareName, String fileName, + String targetFile, Integer timeout, String requestId, String leaseId, Context context) { + try { + final String restype = "hardlink"; + final String fileTypeConstant = "file"; + final String accept = "application/xml"; + return service.createHardLinkNoCustomHeadersSync(this.client.getUrl(), shareName, fileName, restype, + timeout, this.client.getVersion(), fileTypeConstant, requestId, leaseId, targetFile, + this.client.getFileRequestIntent(), accept, context); + } catch (ShareStorageExceptionInternal internalException) { + throw ModelHelper.mapToShareStorageException(internalException); + } + } } diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/accesshelpers/FilePosixPropertiesHelper.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/accesshelpers/FilePosixPropertiesHelper.java new file mode 100644 index 000000000000..847b040e240d --- /dev/null +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/accesshelpers/FilePosixPropertiesHelper.java @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.file.share.implementation.accesshelpers; + +import com.azure.core.http.HttpHeaders; +import com.azure.storage.file.share.models.FilePosixProperties; + +/** + * Helper class to access private values of {@link FilePosixProperties} across package boundaries. + */ +public final class FilePosixPropertiesHelper { + + private static FilePosixPropertiesAccessor accessor; + + private FilePosixPropertiesHelper() { + } + + /** + * Type defining the methods to set the non-public properties of a {@link FilePosixProperties} instance. + */ + public interface FilePosixPropertiesAccessor { + /** + * Creates a new instance of {@link FilePosixProperties}. + * + * @param httpHeaders The internal headers. + * @return A new instance of {@link FilePosixProperties}. + */ + FilePosixProperties create(HttpHeaders httpHeaders); + } + + /** + * The method called from {@link FilePosixProperties} to set it's accessor. + * + * @param accessor The accessor. + */ + public static void setAccessor(final FilePosixPropertiesAccessor accessor) { + FilePosixPropertiesHelper.accessor = accessor; + } + + /** + * Creates a new instance of {@link FilePosixProperties}. + * + * @param httpHeaders The internal headers. + * @return A new instance of {@link FilePosixProperties}. + */ + public static FilePosixProperties create(HttpHeaders httpHeaders) { + // This looks odd but is necessary, it is possible to engage the access helper before anywhere else in the + // application accesses FilePosixProperties which triggers the accessor to be configured. So, if the accessor + // is null this effectively pokes the class to set up the accessor. + if (accessor == null) { + new FilePosixProperties(); + } + + assert accessor != null; + return accessor.create(httpHeaders); + } +} diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/accesshelpers/FileSmbPropertiesHelper.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/accesshelpers/FileSmbPropertiesHelper.java index cfb7e6673272..950e9e4c8934 100644 --- a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/accesshelpers/FileSmbPropertiesHelper.java +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/accesshelpers/FileSmbPropertiesHelper.java @@ -21,8 +21,7 @@ private FileSmbPropertiesHelper() { */ public interface FileSmbPropertiesAccessor { /** - * Creates a new instance of {@link FileSmbProperties} backed by an internal instance of - * {@link FileSmbProperties}. + * Creates a new instance of {@link FileSmbProperties}. * * @param httpHeaders The internal headers. * @return A new instance of {@link FileSmbProperties}. @@ -40,13 +39,15 @@ public static void setAccessor(final FileSmbPropertiesAccessor accessor) { } /** - * Creates a new instance of {@link FileSmbProperties} backed by an internal instance of - * {@link FileSmbProperties}. + * Creates a new instance of {@link FileSmbProperties}. * * @param httpHeaders The internal headers. * @return A new instance of {@link FileSmbProperties}. */ public static FileSmbProperties create(HttpHeaders httpHeaders) { + // This looks odd but is necessary, it is possible to engage the access helper before anywhere else in the + // application accesses FileSmbProperties which triggers the accessor to be configured. So, if the accessor + // is null this effectively pokes the class to set up the accessor. if (accessor == null) { new FileSmbProperties(); } diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/accesshelpers/ShareDirectoryInfoHelper.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/accesshelpers/ShareDirectoryInfoHelper.java new file mode 100644 index 000000000000..033dcddab865 --- /dev/null +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/accesshelpers/ShareDirectoryInfoHelper.java @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.file.share.implementation.accesshelpers; + +import com.azure.storage.file.share.FileSmbProperties; +import com.azure.storage.file.share.models.FilePosixProperties; +import com.azure.storage.file.share.models.ShareDirectoryInfo; + +import java.time.OffsetDateTime; + +/** + * Helper class to access private values of {@link ShareDirectoryInfo} across package boundaries. + */ +public final class ShareDirectoryInfoHelper { + + private static ShareDirectoryInfoAccessor accessor; + + private ShareDirectoryInfoHelper() { + } + + /** + * Type defining the methods to set the non-public properties of a {@link ShareDirectoryInfo} instance. + */ + public interface ShareDirectoryInfoAccessor { + /** + * Creates a new instance of {@link ShareDirectoryInfo}. + * + * @param eTag Entity tag that corresponds to the directory. + * @param lastModified Last time the directory was modified. + * @param smbProperties The SMB properties of the directory. + * @param posixProperties The NFS properties of the directory. + * @return A new instance of {@link ShareDirectoryInfo}. + */ + ShareDirectoryInfo create(String eTag, OffsetDateTime lastModified, FileSmbProperties smbProperties, + FilePosixProperties posixProperties); + } + + /** + * The method called from {@link ShareDirectoryInfo} to set it's accessor. + * + * @param accessor The accessor. + */ + public static void setAccessor(final ShareDirectoryInfoAccessor accessor) { + ShareDirectoryInfoHelper.accessor = accessor; + } + + /** + * Creates a new instance of {@link ShareDirectoryInfo}. + * + * @param eTag Entity tag that corresponds to the directory. + * @param lastModified Last time the directory was modified. + * @param smbProperties The SMB properties of the directory. + * @param posixProperties the NFS properties of the directory. + * @return A new instance of {@link ShareDirectoryInfo}. + */ + public static ShareDirectoryInfo create(String eTag, OffsetDateTime lastModified, FileSmbProperties smbProperties, + FilePosixProperties posixProperties) { + // This looks odd but is necessary, it is possible to engage the access helper before anywhere else in the + // application accesses ShareDirectoryInfo which triggers the accessor to be configured. So, if the accessor + // is null this effectively pokes the class to set up the accessor. + if (accessor == null) { + new ShareDirectoryInfo(null, null, null); + } + + assert accessor != null; + return accessor.create(eTag, lastModified, smbProperties, posixProperties); + } +} diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/accesshelpers/ShareDirectoryPropertiesHelper.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/accesshelpers/ShareDirectoryPropertiesHelper.java new file mode 100644 index 000000000000..7dd95ad83c29 --- /dev/null +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/accesshelpers/ShareDirectoryPropertiesHelper.java @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.file.share.implementation.accesshelpers; + +import com.azure.storage.file.share.FileSmbProperties; +import com.azure.storage.file.share.models.FilePosixProperties; +import com.azure.storage.file.share.models.ShareDirectoryProperties; + +import java.time.OffsetDateTime; +import java.util.Map; + +/** + * Helper class to access private values of {@link ShareDirectoryProperties} across package boundaries. + */ +public final class ShareDirectoryPropertiesHelper { + + private static ShareDirectoryPropertiesAccessor accessor; + + private ShareDirectoryPropertiesHelper() { + } + + /** + * Type defining the methods to set the non-public properties of a {@link ShareDirectoryProperties} instance. + */ + public interface ShareDirectoryPropertiesAccessor { + /** + * Creates a new instance of {@link ShareDirectoryProperties}. + * + * @param metadata A set of name-value pairs that contain metadata for the directory. + * @param eTag Entity tag that corresponds to the directory. + * @param lastModified Last time the directory was modified. + * @param isServerEncrypted The value of this header is set to true if the directory metadata is completely + * encrypted using the specified algorithm. Otherwise, the value is set to false. + * @param smbProperties The SMB properties of the directory. + * @param posixProperties the NFS properties of the directory. + * @return A new instance of {@link ShareDirectoryProperties}. + */ + ShareDirectoryProperties create(Map metadata, String eTag, OffsetDateTime lastModified, + boolean isServerEncrypted, FileSmbProperties smbProperties, FilePosixProperties posixProperties); + } + + /** + * The method called from {@link ShareDirectoryProperties} to set it's accessor. + * + * @param accessor The accessor. + */ + public static void setAccessor(ShareDirectoryPropertiesAccessor accessor) { + ShareDirectoryPropertiesHelper.accessor = accessor; + } + + /** + * Creates a new instance of {@link ShareDirectoryProperties}. + * + * @param metadata A set of name-value pairs that contain metadata for the directory. + * @param eTag Entity tag that corresponds to the directory. + * @param lastModified Last time the directory was modified. + * @param isServerEncrypted The value of this header is set to true if the directory metadata is completely + * encrypted using the specified algorithm. Otherwise, the value is set to false. + * @param smbProperties The SMB properties of the directory. + * @param posixProperties the NFS properties of the directory. + * @return A new instance of {@link ShareDirectoryProperties}. + */ + public static ShareDirectoryProperties create(Map metadata, String eTag, + OffsetDateTime lastModified, boolean isServerEncrypted, FileSmbProperties smbProperties, + FilePosixProperties posixProperties) { + // This looks odd but is necessary, it is possible to engage the access helper before anywhere else in the + // application accesses ShareDirectoryProperties which triggers the accessor to be configured. So, if the accessor + // is null this effectively pokes the class to set up the accessor. + if (accessor == null) { + new ShareDirectoryProperties(null, null, null, false, null); + } + + assert accessor != null; + return accessor.create(metadata, eTag, lastModified, isServerEncrypted, smbProperties, posixProperties); + } +} diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/accesshelpers/ShareFileInfoHelper.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/accesshelpers/ShareFileInfoHelper.java new file mode 100644 index 000000000000..356612855b62 --- /dev/null +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/accesshelpers/ShareFileInfoHelper.java @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.file.share.implementation.accesshelpers; + +import com.azure.storage.file.share.FileSmbProperties; +import com.azure.storage.file.share.models.FilePosixProperties; +import com.azure.storage.file.share.models.ShareFileInfo; + +import java.time.OffsetDateTime; + +/** + * Helper class to access private values of {@link ShareFileInfo} across package boundaries. + */ +public final class ShareFileInfoHelper { + + private static ShareFileInfoAccessor accessor; + + private ShareFileInfoHelper() { + } + + /** + * Type defining the methods to set the non-public properties of a {@link ShareFileInfo} instance. + */ + public interface ShareFileInfoAccessor { + /** + * Creates a new instance of {@link ShareFileInfo}. + * + * @param eTag Entity tag that corresponds to the directory. + * @param lastModified Last time the directory was modified. + * @param isServerEncrypted The value of this header is set to true if the directory metadata is completely + * encrypted using the specified algorithm. Otherwise, the value is set to false. + * @param smbProperties The SMB properties of the file. + * @param posixProperties The NFS properties of the file. + * @return A new instance of {@link ShareFileInfo}. + */ + ShareFileInfo create(String eTag, OffsetDateTime lastModified, Boolean isServerEncrypted, + FileSmbProperties smbProperties, FilePosixProperties posixProperties); + } + + /** + * The method called from {@link ShareFileInfo} to set it's accessor. + * + * @param accessor The accessor. + */ + public static void setAccessor(ShareFileInfoAccessor accessor) { + ShareFileInfoHelper.accessor = accessor; + } + + /** + * Creates a new instance of {@link ShareFileInfo}. + * + * @param eTag Entity tag that corresponds to the directory. + * @param lastModified Last time the directory was modified. + * @param isServerEncrypted The value of this header is set to true if the directory metadata is completely + * encrypted using the specified algorithm. Otherwise, the value is set to false. + * @param smbProperties The SMB properties of the file. + * @param posixProperties The NFS properties of the file. + * @return A new instance of {@link ShareFileInfo}. + */ + public static ShareFileInfo create(String eTag, OffsetDateTime lastModified, Boolean isServerEncrypted, + FileSmbProperties smbProperties, FilePosixProperties posixProperties) { + // This looks odd but is necessary, it is possible to engage the access helper before anywhere else in the + // application accesses ShareFileInfo which triggers the accessor to be configured. So, if the accessor + // is null this effectively pokes the class to set up the accessor. + if (accessor == null) { + new ShareFileInfo(null, null, false, null); + } + + assert accessor != null; + return accessor.create(eTag, lastModified, isServerEncrypted, smbProperties, posixProperties); + } +} diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/accesshelpers/ShareFilePropertiesHelper.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/accesshelpers/ShareFilePropertiesHelper.java new file mode 100644 index 000000000000..7e6c151276cc --- /dev/null +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/accesshelpers/ShareFilePropertiesHelper.java @@ -0,0 +1,152 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.file.share.implementation.accesshelpers; + +import com.azure.storage.file.share.FileSmbProperties; +import com.azure.storage.file.share.models.CopyStatusType; +import com.azure.storage.file.share.models.FilePosixProperties; +import com.azure.storage.file.share.models.LeaseDurationType; +import com.azure.storage.file.share.models.LeaseStateType; +import com.azure.storage.file.share.models.LeaseStatusType; +import com.azure.storage.file.share.models.ShareFileProperties; + +import java.time.OffsetDateTime; +import java.util.Map; + +/** + * Helper class to access private values of {@link ShareFileProperties} across package boundaries. + */ +public final class ShareFilePropertiesHelper { + private static ShareFilePropertiesAccessor accessor; + + private ShareFilePropertiesHelper() { + } + + /** + * Type defining the methods to set the non-public properties of a {@link ShareFileProperties} instance. + */ + public interface ShareFilePropertiesAccessor { + /** + * Creates a new instance of {@link ShareFileProperties}. + * + * @param eTag Entity tag that corresponds to the directory. + * @param lastModified Last time the directory was modified. + * @param metadata A set of name-value pairs associated with this file as user-defined metadata. + * @param fileType Type of the file. + * @param contentLength The number of bytes present in the response body. + * @param contentType The content type specified for the file. The default content type is + * application/octet-stream. + * @param contentMd5 The MD5 hash of the file to check the message content integrity. + * @param contentEncoding This header returns the value that was specified for the Content-Encoding request header. + * @param cacheControl This header is returned if it was previously specified for the file. + * @param contentDisposition The value that was specified for the x-ms-content-disposition header and specifies how + * to process the response. + * @param leaseStatusType Status of the lease. + * @param leaseStateType State of the lease. + * @param leaseDurationType How long the lease has left. + * @param copyCompletionTime Conclusion time of the last attempted Copy File operation where this file was the + * destination file. + * @param copyStatusDescription Appears when x-ms-copy-status is failed or pending. Describes cause of fatal or + * non-fatal copy operation failure. + * @param copyId String identifier for the last attempted Copy File operation where this file was the destination + * file. + * @param copyProgress Contains the number of bytes copied and the total bytes in the source in the last attempted + * Copy File operation where this file was the destination file. + * @param copySource URL up to 2KB in length that specifies the source file used in the last attempted Copy File + * operation where this file was the destination file. + * @param copyStatus State of the copy operation identified by x-ms-copy-id, with these values: + *
          + *
        • success: Copy completed successfully
        • + *
        • pending: Copy is in progress. Check x-ms-copy-status-description if intermittent, non-fatal errors impede + * copy progress but don't cause failure.
        • + *
        • aborted: Copy was ended by Abort Copy File.
        • + *
        • failed: Copy failed. See x-ms-copy-status-description for failure details.
        • + *
        + * @param isServerEncrypted The value of this header is set to true if the file data and application metadata are + * completely encrypted using the specified algorithm. Otherwise, the value is set to false. + * @param smbProperties The SMB properties of the file. + * @param posixProperties The NFS properties of the file. + * @return A new instance of {@link ShareFileProperties}. + */ + ShareFileProperties create(String eTag, OffsetDateTime lastModified, Map metadata, + String fileType, Long contentLength, String contentType, byte[] contentMd5, String contentEncoding, + String cacheControl, String contentDisposition, LeaseStatusType leaseStatusType, + LeaseStateType leaseStateType, LeaseDurationType leaseDurationType, OffsetDateTime copyCompletionTime, + String copyStatusDescription, String copyId, String copyProgress, String copySource, + CopyStatusType copyStatus, Boolean isServerEncrypted, FileSmbProperties smbProperties, + FilePosixProperties posixProperties); + } + + /** + * The method called from {@link ShareFileProperties} to set it's accessor. + * + * @param accessor The accessor. + */ + public static void setAccessor(ShareFilePropertiesAccessor accessor) { + ShareFilePropertiesHelper.accessor = accessor; + } + + /** + * Creates a new instance of {@link ShareFileProperties}. + * + * @param eTag Entity tag that corresponds to the directory. + * @param lastModified Last time the directory was modified. + * @param metadata A set of name-value pairs associated with this file as user-defined metadata. + * @param fileType Type of the file. + * @param contentLength The number of bytes present in the response body. + * @param contentType The content type specified for the file. The default content type is + * application/octet-stream. + * @param contentMd5 The MD5 hash of the file to check the message content integrity. + * @param contentEncoding This header returns the value that was specified for the Content-Encoding request header. + * @param cacheControl This header is returned if it was previously specified for the file. + * @param contentDisposition The value that was specified for the x-ms-content-disposition header and specifies how + * to process the response. + * @param leaseStatusType Status of the lease. + * @param leaseStateType State of the lease. + * @param leaseDurationType How long the lease has left. + * @param copyCompletionTime Conclusion time of the last attempted Copy File operation where this file was the + * destination file. + * @param copyStatusDescription Appears when x-ms-copy-status is failed or pending. Describes cause of fatal or + * non-fatal copy operation failure. + * @param copyId String identifier for the last attempted Copy File operation where this file was the destination + * file. + * @param copyProgress Contains the number of bytes copied and the total bytes in the source in the last attempted + * Copy File operation where this file was the destination file. + * @param copySource URL up to 2KB in length that specifies the source file used in the last attempted Copy File + * operation where this file was the destination file. + * @param copyStatus State of the copy operation identified by x-ms-copy-id, with these values: + *
          + *
        • success: Copy completed successfully
        • + *
        • pending: Copy is in progress. Check x-ms-copy-status-description if intermittent, non-fatal errors impede + * copy progress but don't cause failure.
        • + *
        • aborted: Copy was ended by Abort Copy File.
        • + *
        • failed: Copy failed. See x-ms-copy-status-description for failure details.
        • + *
        + * @param isServerEncrypted The value of this header is set to true if the file data and application metadata are + * completely encrypted using the specified algorithm. Otherwise, the value is set to false. + * @param smbProperties The SMB properties of the file. + * @param posixProperties The NFS properties of the file. + * @return A new instance of {@link ShareFileProperties}. + */ + public static ShareFileProperties create(String eTag, OffsetDateTime lastModified, Map metadata, + String fileType, Long contentLength, String contentType, byte[] contentMd5, String contentEncoding, + String cacheControl, String contentDisposition, LeaseStatusType leaseStatusType, LeaseStateType leaseStateType, + LeaseDurationType leaseDurationType, OffsetDateTime copyCompletionTime, String copyStatusDescription, + String copyId, String copyProgress, String copySource, CopyStatusType copyStatus, Boolean isServerEncrypted, + FileSmbProperties smbProperties, FilePosixProperties posixProperties) { + // This looks odd but is necessary, it is possible to engage the access helper before anywhere else in the + // application accesses ShareFileProperties which triggers the accessor to be configured. So, if the accessor + // is null this effectively pokes the class to set up the accessor. + if (accessor == null) { + new ShareFileProperties(null, null, null, null, null, null, null, null, null, null, null, null, null, null, + null, null, null, null, null, false, null); + } + + assert accessor != null; + return accessor.create(eTag, lastModified, metadata, fileType, contentLength, contentType, contentMd5, + contentEncoding, cacheControl, contentDisposition, leaseStatusType, leaseStateType, leaseDurationType, + copyCompletionTime, copyStatusDescription, copyId, copyProgress, copySource, copyStatus, isServerEncrypted, + smbProperties, posixProperties); + } +} diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/DirectoriesCreateHeaders.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/DirectoriesCreateHeaders.java index eb2297c000ff..70970048f3fd 100644 --- a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/DirectoriesCreateHeaders.java +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/DirectoriesCreateHeaders.java @@ -8,6 +8,7 @@ import com.azure.core.http.HttpHeaderName; import com.azure.core.http.HttpHeaders; import com.azure.core.util.DateTimeRfc1123; +import com.azure.storage.file.share.models.NfsFileType; import java.time.OffsetDateTime; /** @@ -15,6 +16,11 @@ */ @Fluent public final class DirectoriesCreateHeaders { + /* + * The x-ms-group property. + */ + private String xMsGroup; + /* * The x-ms-version property. */ @@ -35,6 +41,11 @@ public final class DirectoriesCreateHeaders { */ private OffsetDateTime xMsFileCreationTime; + /* + * The x-ms-file-file-type property. + */ + private NfsFileType xMsFileFileType; + /* * The Last-Modified property. */ @@ -50,6 +61,11 @@ public final class DirectoriesCreateHeaders { */ private DateTimeRfc1123 date; + /* + * The x-ms-mode property. + */ + private String xMsMode; + /* * The ETag property. */ @@ -80,6 +96,13 @@ public final class DirectoriesCreateHeaders { */ private OffsetDateTime xMsFileLastWriteTime; + /* + * The x-ms-owner property. + */ + private String xMsOwner; + + private static final HttpHeaderName X_MS_GROUP = HttpHeaderName.fromString("x-ms-group"); + private static final HttpHeaderName X_MS_VERSION = HttpHeaderName.fromString("x-ms-version"); private static final HttpHeaderName X_MS_FILE_PERMISSION_KEY @@ -89,9 +112,13 @@ public final class DirectoriesCreateHeaders { private static final HttpHeaderName X_MS_FILE_CREATION_TIME = HttpHeaderName.fromString("x-ms-file-creation-time"); + private static final HttpHeaderName X_MS_FILE_FILE_TYPE = HttpHeaderName.fromString("x-ms-file-file-type"); + private static final HttpHeaderName X_MS_REQUEST_SERVER_ENCRYPTED = HttpHeaderName.fromString("x-ms-request-server-encrypted"); + private static final HttpHeaderName X_MS_MODE = HttpHeaderName.fromString("x-ms-mode"); + private static final HttpHeaderName X_MS_FILE_ATTRIBUTES = HttpHeaderName.fromString("x-ms-file-attributes"); private static final HttpHeaderName X_MS_FILE_CHANGE_TIME = HttpHeaderName.fromString("x-ms-file-change-time"); @@ -101,6 +128,8 @@ public final class DirectoriesCreateHeaders { private static final HttpHeaderName X_MS_FILE_LAST_WRITE_TIME = HttpHeaderName.fromString("x-ms-file-last-write-time"); + private static final HttpHeaderName X_MS_OWNER = HttpHeaderName.fromString("x-ms-owner"); + // HttpHeaders containing the raw property values. /** * Creates an instance of DirectoriesCreateHeaders class. @@ -108,6 +137,7 @@ public final class DirectoriesCreateHeaders { * @param rawHeaders The raw HttpHeaders that will be used to create the property values. */ public DirectoriesCreateHeaders(HttpHeaders rawHeaders) { + this.xMsGroup = rawHeaders.getValue(X_MS_GROUP); this.xMsVersion = rawHeaders.getValue(X_MS_VERSION); this.xMsFilePermissionKey = rawHeaders.getValue(X_MS_FILE_PERMISSION_KEY); this.xMsFileId = rawHeaders.getValue(X_MS_FILE_ID); @@ -115,6 +145,10 @@ public DirectoriesCreateHeaders(HttpHeaders rawHeaders) { if (xMsFileCreationTime != null) { this.xMsFileCreationTime = OffsetDateTime.parse(xMsFileCreationTime); } + String xMsFileFileType = rawHeaders.getValue(X_MS_FILE_FILE_TYPE); + if (xMsFileFileType != null) { + this.xMsFileFileType = NfsFileType.fromString(xMsFileFileType); + } String lastModified = rawHeaders.getValue(HttpHeaderName.LAST_MODIFIED); if (lastModified != null) { this.lastModified = new DateTimeRfc1123(lastModified); @@ -127,6 +161,7 @@ public DirectoriesCreateHeaders(HttpHeaders rawHeaders) { if (date != null) { this.date = new DateTimeRfc1123(date); } + this.xMsMode = rawHeaders.getValue(X_MS_MODE); this.eTag = rawHeaders.getValue(HttpHeaderName.ETAG); this.xMsFileAttributes = rawHeaders.getValue(X_MS_FILE_ATTRIBUTES); String xMsFileChangeTime = rawHeaders.getValue(X_MS_FILE_CHANGE_TIME); @@ -139,6 +174,27 @@ public DirectoriesCreateHeaders(HttpHeaders rawHeaders) { if (xMsFileLastWriteTime != null) { this.xMsFileLastWriteTime = OffsetDateTime.parse(xMsFileLastWriteTime); } + this.xMsOwner = rawHeaders.getValue(X_MS_OWNER); + } + + /** + * Get the xMsGroup property: The x-ms-group property. + * + * @return the xMsGroup value. + */ + public String getXMsGroup() { + return this.xMsGroup; + } + + /** + * Set the xMsGroup property: The x-ms-group property. + * + * @param xMsGroup the xMsGroup value to set. + * @return the DirectoriesCreateHeaders object itself. + */ + public DirectoriesCreateHeaders setXMsGroup(String xMsGroup) { + this.xMsGroup = xMsGroup; + return this; } /** @@ -221,6 +277,26 @@ public DirectoriesCreateHeaders setXMsFileCreationTime(OffsetDateTime xMsFileCre return this; } + /** + * Get the xMsFileFileType property: The x-ms-file-file-type property. + * + * @return the xMsFileFileType value. + */ + public NfsFileType getXMsFileFileType() { + return this.xMsFileFileType; + } + + /** + * Set the xMsFileFileType property: The x-ms-file-file-type property. + * + * @param xMsFileFileType the xMsFileFileType value to set. + * @return the DirectoriesCreateHeaders object itself. + */ + public DirectoriesCreateHeaders setXMsFileFileType(NfsFileType xMsFileFileType) { + this.xMsFileFileType = xMsFileFileType; + return this; + } + /** * Get the lastModified property: The Last-Modified property. * @@ -295,6 +371,26 @@ public DirectoriesCreateHeaders setDate(OffsetDateTime date) { return this; } + /** + * Get the xMsMode property: The x-ms-mode property. + * + * @return the xMsMode value. + */ + public String getXMsMode() { + return this.xMsMode; + } + + /** + * Set the xMsMode property: The x-ms-mode property. + * + * @param xMsMode the xMsMode value to set. + * @return the DirectoriesCreateHeaders object itself. + */ + public DirectoriesCreateHeaders setXMsMode(String xMsMode) { + this.xMsMode = xMsMode; + return this; + } + /** * Get the eTag property: The ETag property. * @@ -414,4 +510,24 @@ public DirectoriesCreateHeaders setXMsFileLastWriteTime(OffsetDateTime xMsFileLa this.xMsFileLastWriteTime = xMsFileLastWriteTime; return this; } + + /** + * Get the xMsOwner property: The x-ms-owner property. + * + * @return the xMsOwner value. + */ + public String getXMsOwner() { + return this.xMsOwner; + } + + /** + * Set the xMsOwner property: The x-ms-owner property. + * + * @param xMsOwner the xMsOwner value to set. + * @return the DirectoriesCreateHeaders object itself. + */ + public DirectoriesCreateHeaders setXMsOwner(String xMsOwner) { + this.xMsOwner = xMsOwner; + return this; + } } diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/DirectoriesGetPropertiesHeaders.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/DirectoriesGetPropertiesHeaders.java index 54bb3b21b808..028c74a228b5 100644 --- a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/DirectoriesGetPropertiesHeaders.java +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/DirectoriesGetPropertiesHeaders.java @@ -9,6 +9,7 @@ import com.azure.core.http.HttpHeaderName; import com.azure.core.http.HttpHeaders; import com.azure.core.util.DateTimeRfc1123; +import com.azure.storage.file.share.models.NfsFileType; import java.time.OffsetDateTime; import java.util.LinkedHashMap; import java.util.Map; @@ -18,6 +19,11 @@ */ @Fluent public final class DirectoriesGetPropertiesHeaders { + /* + * The x-ms-group property. + */ + private String xMsGroup; + /* * The x-ms-version property. */ @@ -38,6 +44,11 @@ public final class DirectoriesGetPropertiesHeaders { */ private OffsetDateTime xMsFileCreationTime; + /* + * The x-ms-file-file-type property. + */ + private NfsFileType xMsFileFileType; + /* * The Last-Modified property. */ @@ -53,6 +64,11 @@ public final class DirectoriesGetPropertiesHeaders { */ private DateTimeRfc1123 date; + /* + * The x-ms-mode property. + */ + private String xMsMode; + /* * The x-ms-server-encrypted property. */ @@ -88,6 +104,13 @@ public final class DirectoriesGetPropertiesHeaders { */ private OffsetDateTime xMsFileLastWriteTime; + /* + * The x-ms-owner property. + */ + private String xMsOwner; + + private static final HttpHeaderName X_MS_GROUP = HttpHeaderName.fromString("x-ms-group"); + private static final HttpHeaderName X_MS_VERSION = HttpHeaderName.fromString("x-ms-version"); private static final HttpHeaderName X_MS_FILE_PERMISSION_KEY @@ -97,6 +120,10 @@ public final class DirectoriesGetPropertiesHeaders { private static final HttpHeaderName X_MS_FILE_CREATION_TIME = HttpHeaderName.fromString("x-ms-file-creation-time"); + private static final HttpHeaderName X_MS_FILE_FILE_TYPE = HttpHeaderName.fromString("x-ms-file-file-type"); + + private static final HttpHeaderName X_MS_MODE = HttpHeaderName.fromString("x-ms-mode"); + private static final HttpHeaderName X_MS_SERVER_ENCRYPTED = HttpHeaderName.fromString("x-ms-server-encrypted"); private static final HttpHeaderName X_MS_FILE_ATTRIBUTES = HttpHeaderName.fromString("x-ms-file-attributes"); @@ -108,6 +135,8 @@ public final class DirectoriesGetPropertiesHeaders { private static final HttpHeaderName X_MS_FILE_LAST_WRITE_TIME = HttpHeaderName.fromString("x-ms-file-last-write-time"); + private static final HttpHeaderName X_MS_OWNER = HttpHeaderName.fromString("x-ms-owner"); + // HttpHeaders containing the raw property values. /** * Creates an instance of DirectoriesGetPropertiesHeaders class. @@ -115,6 +144,7 @@ public final class DirectoriesGetPropertiesHeaders { * @param rawHeaders The raw HttpHeaders that will be used to create the property values. */ public DirectoriesGetPropertiesHeaders(HttpHeaders rawHeaders) { + this.xMsGroup = rawHeaders.getValue(X_MS_GROUP); this.xMsVersion = rawHeaders.getValue(X_MS_VERSION); this.xMsFilePermissionKey = rawHeaders.getValue(X_MS_FILE_PERMISSION_KEY); this.xMsFileId = rawHeaders.getValue(X_MS_FILE_ID); @@ -122,6 +152,10 @@ public DirectoriesGetPropertiesHeaders(HttpHeaders rawHeaders) { if (xMsFileCreationTime != null) { this.xMsFileCreationTime = OffsetDateTime.parse(xMsFileCreationTime); } + String xMsFileFileType = rawHeaders.getValue(X_MS_FILE_FILE_TYPE); + if (xMsFileFileType != null) { + this.xMsFileFileType = NfsFileType.fromString(xMsFileFileType); + } String lastModified = rawHeaders.getValue(HttpHeaderName.LAST_MODIFIED); if (lastModified != null) { this.lastModified = new DateTimeRfc1123(lastModified); @@ -130,6 +164,7 @@ public DirectoriesGetPropertiesHeaders(HttpHeaders rawHeaders) { if (date != null) { this.date = new DateTimeRfc1123(date); } + this.xMsMode = rawHeaders.getValue(X_MS_MODE); String xMsServerEncrypted = rawHeaders.getValue(X_MS_SERVER_ENCRYPTED); if (xMsServerEncrypted != null) { this.xMsServerEncrypted = Boolean.parseBoolean(xMsServerEncrypted); @@ -146,6 +181,7 @@ public DirectoriesGetPropertiesHeaders(HttpHeaders rawHeaders) { if (xMsFileLastWriteTime != null) { this.xMsFileLastWriteTime = OffsetDateTime.parse(xMsFileLastWriteTime); } + this.xMsOwner = rawHeaders.getValue(X_MS_OWNER); Map xMsMetaHeaderCollection = new LinkedHashMap<>(); for (HttpHeader header : rawHeaders) { @@ -158,6 +194,26 @@ public DirectoriesGetPropertiesHeaders(HttpHeaders rawHeaders) { this.xMsMeta = xMsMetaHeaderCollection; } + /** + * Get the xMsGroup property: The x-ms-group property. + * + * @return the xMsGroup value. + */ + public String getXMsGroup() { + return this.xMsGroup; + } + + /** + * Set the xMsGroup property: The x-ms-group property. + * + * @param xMsGroup the xMsGroup value to set. + * @return the DirectoriesGetPropertiesHeaders object itself. + */ + public DirectoriesGetPropertiesHeaders setXMsGroup(String xMsGroup) { + this.xMsGroup = xMsGroup; + return this; + } + /** * Get the xMsVersion property: The x-ms-version property. * @@ -238,6 +294,26 @@ public DirectoriesGetPropertiesHeaders setXMsFileCreationTime(OffsetDateTime xMs return this; } + /** + * Get the xMsFileFileType property: The x-ms-file-file-type property. + * + * @return the xMsFileFileType value. + */ + public NfsFileType getXMsFileFileType() { + return this.xMsFileFileType; + } + + /** + * Set the xMsFileFileType property: The x-ms-file-file-type property. + * + * @param xMsFileFileType the xMsFileFileType value to set. + * @return the DirectoriesGetPropertiesHeaders object itself. + */ + public DirectoriesGetPropertiesHeaders setXMsFileFileType(NfsFileType xMsFileFileType) { + this.xMsFileFileType = xMsFileFileType; + return this; + } + /** * Get the lastModified property: The Last-Modified property. * @@ -312,6 +388,26 @@ public DirectoriesGetPropertiesHeaders setDate(OffsetDateTime date) { return this; } + /** + * Get the xMsMode property: The x-ms-mode property. + * + * @return the xMsMode value. + */ + public String getXMsMode() { + return this.xMsMode; + } + + /** + * Set the xMsMode property: The x-ms-mode property. + * + * @param xMsMode the xMsMode value to set. + * @return the DirectoriesGetPropertiesHeaders object itself. + */ + public DirectoriesGetPropertiesHeaders setXMsMode(String xMsMode) { + this.xMsMode = xMsMode; + return this; + } + /** * Get the xMsServerEncrypted property: The x-ms-server-encrypted property. * @@ -451,4 +547,24 @@ public DirectoriesGetPropertiesHeaders setXMsFileLastWriteTime(OffsetDateTime xM this.xMsFileLastWriteTime = xMsFileLastWriteTime; return this; } + + /** + * Get the xMsOwner property: The x-ms-owner property. + * + * @return the xMsOwner value. + */ + public String getXMsOwner() { + return this.xMsOwner; + } + + /** + * Set the xMsOwner property: The x-ms-owner property. + * + * @param xMsOwner the xMsOwner value to set. + * @return the DirectoriesGetPropertiesHeaders object itself. + */ + public DirectoriesGetPropertiesHeaders setXMsOwner(String xMsOwner) { + this.xMsOwner = xMsOwner; + return this; + } } diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/DirectoriesSetPropertiesHeaders.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/DirectoriesSetPropertiesHeaders.java index 47946157b5ac..1796d92cebb0 100644 --- a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/DirectoriesSetPropertiesHeaders.java +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/DirectoriesSetPropertiesHeaders.java @@ -15,6 +15,11 @@ */ @Fluent public final class DirectoriesSetPropertiesHeaders { + /* + * The x-ms-group property. + */ + private String xMsGroup; + /* * The x-ms-version property. */ @@ -50,6 +55,11 @@ public final class DirectoriesSetPropertiesHeaders { */ private DateTimeRfc1123 date; + /* + * The x-ms-mode property. + */ + private String xMsMode; + /* * The ETag property. */ @@ -80,6 +90,13 @@ public final class DirectoriesSetPropertiesHeaders { */ private OffsetDateTime xMsFileLastWriteTime; + /* + * The x-ms-owner property. + */ + private String xMsOwner; + + private static final HttpHeaderName X_MS_GROUP = HttpHeaderName.fromString("x-ms-group"); + private static final HttpHeaderName X_MS_VERSION = HttpHeaderName.fromString("x-ms-version"); private static final HttpHeaderName X_MS_FILE_PERMISSION_KEY @@ -92,6 +109,8 @@ public final class DirectoriesSetPropertiesHeaders { private static final HttpHeaderName X_MS_REQUEST_SERVER_ENCRYPTED = HttpHeaderName.fromString("x-ms-request-server-encrypted"); + private static final HttpHeaderName X_MS_MODE = HttpHeaderName.fromString("x-ms-mode"); + private static final HttpHeaderName X_MS_FILE_ATTRIBUTES = HttpHeaderName.fromString("x-ms-file-attributes"); private static final HttpHeaderName X_MS_FILE_CHANGE_TIME = HttpHeaderName.fromString("x-ms-file-change-time"); @@ -101,6 +120,8 @@ public final class DirectoriesSetPropertiesHeaders { private static final HttpHeaderName X_MS_FILE_LAST_WRITE_TIME = HttpHeaderName.fromString("x-ms-file-last-write-time"); + private static final HttpHeaderName X_MS_OWNER = HttpHeaderName.fromString("x-ms-owner"); + // HttpHeaders containing the raw property values. /** * Creates an instance of DirectoriesSetPropertiesHeaders class. @@ -108,6 +129,7 @@ public final class DirectoriesSetPropertiesHeaders { * @param rawHeaders The raw HttpHeaders that will be used to create the property values. */ public DirectoriesSetPropertiesHeaders(HttpHeaders rawHeaders) { + this.xMsGroup = rawHeaders.getValue(X_MS_GROUP); this.xMsVersion = rawHeaders.getValue(X_MS_VERSION); this.xMsFilePermissionKey = rawHeaders.getValue(X_MS_FILE_PERMISSION_KEY); this.xMsFileId = rawHeaders.getValue(X_MS_FILE_ID); @@ -127,6 +149,7 @@ public DirectoriesSetPropertiesHeaders(HttpHeaders rawHeaders) { if (date != null) { this.date = new DateTimeRfc1123(date); } + this.xMsMode = rawHeaders.getValue(X_MS_MODE); this.eTag = rawHeaders.getValue(HttpHeaderName.ETAG); this.xMsFileAttributes = rawHeaders.getValue(X_MS_FILE_ATTRIBUTES); String xMsFileChangeTime = rawHeaders.getValue(X_MS_FILE_CHANGE_TIME); @@ -139,6 +162,27 @@ public DirectoriesSetPropertiesHeaders(HttpHeaders rawHeaders) { if (xMsFileLastWriteTime != null) { this.xMsFileLastWriteTime = OffsetDateTime.parse(xMsFileLastWriteTime); } + this.xMsOwner = rawHeaders.getValue(X_MS_OWNER); + } + + /** + * Get the xMsGroup property: The x-ms-group property. + * + * @return the xMsGroup value. + */ + public String getXMsGroup() { + return this.xMsGroup; + } + + /** + * Set the xMsGroup property: The x-ms-group property. + * + * @param xMsGroup the xMsGroup value to set. + * @return the DirectoriesSetPropertiesHeaders object itself. + */ + public DirectoriesSetPropertiesHeaders setXMsGroup(String xMsGroup) { + this.xMsGroup = xMsGroup; + return this; } /** @@ -295,6 +339,26 @@ public DirectoriesSetPropertiesHeaders setDate(OffsetDateTime date) { return this; } + /** + * Get the xMsMode property: The x-ms-mode property. + * + * @return the xMsMode value. + */ + public String getXMsMode() { + return this.xMsMode; + } + + /** + * Set the xMsMode property: The x-ms-mode property. + * + * @param xMsMode the xMsMode value to set. + * @return the DirectoriesSetPropertiesHeaders object itself. + */ + public DirectoriesSetPropertiesHeaders setXMsMode(String xMsMode) { + this.xMsMode = xMsMode; + return this; + } + /** * Get the eTag property: The ETag property. * @@ -414,4 +478,24 @@ public DirectoriesSetPropertiesHeaders setXMsFileLastWriteTime(OffsetDateTime xM this.xMsFileLastWriteTime = xMsFileLastWriteTime; return this; } + + /** + * Get the xMsOwner property: The x-ms-owner property. + * + * @return the xMsOwner value. + */ + public String getXMsOwner() { + return this.xMsOwner; + } + + /** + * Set the xMsOwner property: The x-ms-owner property. + * + * @param xMsOwner the xMsOwner value to set. + * @return the DirectoriesSetPropertiesHeaders object itself. + */ + public DirectoriesSetPropertiesHeaders setXMsOwner(String xMsOwner) { + this.xMsOwner = xMsOwner; + return this; + } } diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/FilesCreateHardLinkHeaders.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/FilesCreateHardLinkHeaders.java new file mode 100644 index 000000000000..ce9ab4bff005 --- /dev/null +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/FilesCreateHardLinkHeaders.java @@ -0,0 +1,501 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.storage.file.share.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.HttpHeaders; +import com.azure.core.util.DateTimeRfc1123; +import com.azure.storage.file.share.models.NfsFileType; +import java.time.OffsetDateTime; + +/** + * The FilesCreateHardLinkHeaders model. + */ +@Fluent +public final class FilesCreateHardLinkHeaders { + /* + * The x-ms-group property. + */ + private String xMsGroup; + + /* + * The x-ms-version property. + */ + private String xMsVersion; + + /* + * The x-ms-file-id property. + */ + private String xMsFileId; + + /* + * The x-ms-file-creation-time property. + */ + private OffsetDateTime xMsFileCreationTime; + + /* + * The x-ms-file-file-type property. + */ + private NfsFileType xMsFileFileType; + + /* + * The Last-Modified property. + */ + private DateTimeRfc1123 lastModified; + + /* + * The Date property. + */ + private DateTimeRfc1123 date; + + /* + * The x-ms-mode property. + */ + private String xMsMode; + + /* + * The ETag property. + */ + private String eTag; + + /* + * The x-ms-link-count property. + */ + private Long xMsLinkCount; + + /* + * The x-ms-file-change-time property. + */ + private OffsetDateTime xMsFileChangeTime; + + /* + * The x-ms-file-parent-id property. + */ + private String xMsFileParentId; + + /* + * The x-ms-request-id property. + */ + private String xMsRequestId; + + /* + * The x-ms-file-last-write-time property. + */ + private OffsetDateTime xMsFileLastWriteTime; + + /* + * The x-ms-client-request-id property. + */ + private String xMsClientRequestId; + + /* + * The x-ms-owner property. + */ + private String xMsOwner; + + private static final HttpHeaderName X_MS_GROUP = HttpHeaderName.fromString("x-ms-group"); + + private static final HttpHeaderName X_MS_VERSION = HttpHeaderName.fromString("x-ms-version"); + + private static final HttpHeaderName X_MS_FILE_ID = HttpHeaderName.fromString("x-ms-file-id"); + + private static final HttpHeaderName X_MS_FILE_CREATION_TIME = HttpHeaderName.fromString("x-ms-file-creation-time"); + + private static final HttpHeaderName X_MS_FILE_FILE_TYPE = HttpHeaderName.fromString("x-ms-file-file-type"); + + private static final HttpHeaderName X_MS_MODE = HttpHeaderName.fromString("x-ms-mode"); + + private static final HttpHeaderName X_MS_LINK_COUNT = HttpHeaderName.fromString("x-ms-link-count"); + + private static final HttpHeaderName X_MS_FILE_CHANGE_TIME = HttpHeaderName.fromString("x-ms-file-change-time"); + + private static final HttpHeaderName X_MS_FILE_PARENT_ID = HttpHeaderName.fromString("x-ms-file-parent-id"); + + private static final HttpHeaderName X_MS_FILE_LAST_WRITE_TIME + = HttpHeaderName.fromString("x-ms-file-last-write-time"); + + private static final HttpHeaderName X_MS_OWNER = HttpHeaderName.fromString("x-ms-owner"); + + // HttpHeaders containing the raw property values. + /** + * Creates an instance of FilesCreateHardLinkHeaders class. + * + * @param rawHeaders The raw HttpHeaders that will be used to create the property values. + */ + public FilesCreateHardLinkHeaders(HttpHeaders rawHeaders) { + this.xMsGroup = rawHeaders.getValue(X_MS_GROUP); + this.xMsVersion = rawHeaders.getValue(X_MS_VERSION); + this.xMsFileId = rawHeaders.getValue(X_MS_FILE_ID); + String xMsFileCreationTime = rawHeaders.getValue(X_MS_FILE_CREATION_TIME); + if (xMsFileCreationTime != null) { + this.xMsFileCreationTime = OffsetDateTime.parse(xMsFileCreationTime); + } + String xMsFileFileType = rawHeaders.getValue(X_MS_FILE_FILE_TYPE); + if (xMsFileFileType != null) { + this.xMsFileFileType = NfsFileType.fromString(xMsFileFileType); + } + String lastModified = rawHeaders.getValue(HttpHeaderName.LAST_MODIFIED); + if (lastModified != null) { + this.lastModified = new DateTimeRfc1123(lastModified); + } + String date = rawHeaders.getValue(HttpHeaderName.DATE); + if (date != null) { + this.date = new DateTimeRfc1123(date); + } + this.xMsMode = rawHeaders.getValue(X_MS_MODE); + this.eTag = rawHeaders.getValue(HttpHeaderName.ETAG); + String xMsLinkCount = rawHeaders.getValue(X_MS_LINK_COUNT); + if (xMsLinkCount != null) { + this.xMsLinkCount = Long.parseLong(xMsLinkCount); + } + String xMsFileChangeTime = rawHeaders.getValue(X_MS_FILE_CHANGE_TIME); + if (xMsFileChangeTime != null) { + this.xMsFileChangeTime = OffsetDateTime.parse(xMsFileChangeTime); + } + this.xMsFileParentId = rawHeaders.getValue(X_MS_FILE_PARENT_ID); + this.xMsRequestId = rawHeaders.getValue(HttpHeaderName.X_MS_REQUEST_ID); + String xMsFileLastWriteTime = rawHeaders.getValue(X_MS_FILE_LAST_WRITE_TIME); + if (xMsFileLastWriteTime != null) { + this.xMsFileLastWriteTime = OffsetDateTime.parse(xMsFileLastWriteTime); + } + this.xMsClientRequestId = rawHeaders.getValue(HttpHeaderName.X_MS_CLIENT_REQUEST_ID); + this.xMsOwner = rawHeaders.getValue(X_MS_OWNER); + } + + /** + * Get the xMsGroup property: The x-ms-group property. + * + * @return the xMsGroup value. + */ + public String getXMsGroup() { + return this.xMsGroup; + } + + /** + * Set the xMsGroup property: The x-ms-group property. + * + * @param xMsGroup the xMsGroup value to set. + * @return the FilesCreateHardLinkHeaders object itself. + */ + public FilesCreateHardLinkHeaders setXMsGroup(String xMsGroup) { + this.xMsGroup = xMsGroup; + return this; + } + + /** + * Get the xMsVersion property: The x-ms-version property. + * + * @return the xMsVersion value. + */ + public String getXMsVersion() { + return this.xMsVersion; + } + + /** + * Set the xMsVersion property: The x-ms-version property. + * + * @param xMsVersion the xMsVersion value to set. + * @return the FilesCreateHardLinkHeaders object itself. + */ + public FilesCreateHardLinkHeaders setXMsVersion(String xMsVersion) { + this.xMsVersion = xMsVersion; + return this; + } + + /** + * Get the xMsFileId property: The x-ms-file-id property. + * + * @return the xMsFileId value. + */ + public String getXMsFileId() { + return this.xMsFileId; + } + + /** + * Set the xMsFileId property: The x-ms-file-id property. + * + * @param xMsFileId the xMsFileId value to set. + * @return the FilesCreateHardLinkHeaders object itself. + */ + public FilesCreateHardLinkHeaders setXMsFileId(String xMsFileId) { + this.xMsFileId = xMsFileId; + return this; + } + + /** + * Get the xMsFileCreationTime property: The x-ms-file-creation-time property. + * + * @return the xMsFileCreationTime value. + */ + public OffsetDateTime getXMsFileCreationTime() { + return this.xMsFileCreationTime; + } + + /** + * Set the xMsFileCreationTime property: The x-ms-file-creation-time property. + * + * @param xMsFileCreationTime the xMsFileCreationTime value to set. + * @return the FilesCreateHardLinkHeaders object itself. + */ + public FilesCreateHardLinkHeaders setXMsFileCreationTime(OffsetDateTime xMsFileCreationTime) { + this.xMsFileCreationTime = xMsFileCreationTime; + return this; + } + + /** + * Get the xMsFileFileType property: The x-ms-file-file-type property. + * + * @return the xMsFileFileType value. + */ + public NfsFileType getXMsFileFileType() { + return this.xMsFileFileType; + } + + /** + * Set the xMsFileFileType property: The x-ms-file-file-type property. + * + * @param xMsFileFileType the xMsFileFileType value to set. + * @return the FilesCreateHardLinkHeaders object itself. + */ + public FilesCreateHardLinkHeaders setXMsFileFileType(NfsFileType xMsFileFileType) { + this.xMsFileFileType = xMsFileFileType; + return this; + } + + /** + * Get the lastModified property: The Last-Modified property. + * + * @return the lastModified value. + */ + public OffsetDateTime getLastModified() { + if (this.lastModified == null) { + return null; + } + return this.lastModified.getDateTime(); + } + + /** + * Set the lastModified property: The Last-Modified property. + * + * @param lastModified the lastModified value to set. + * @return the FilesCreateHardLinkHeaders object itself. + */ + public FilesCreateHardLinkHeaders setLastModified(OffsetDateTime lastModified) { + if (lastModified == null) { + this.lastModified = null; + } else { + this.lastModified = new DateTimeRfc1123(lastModified); + } + return this; + } + + /** + * Get the date property: The Date property. + * + * @return the date value. + */ + public OffsetDateTime getDate() { + if (this.date == null) { + return null; + } + return this.date.getDateTime(); + } + + /** + * Set the date property: The Date property. + * + * @param date the date value to set. + * @return the FilesCreateHardLinkHeaders object itself. + */ + public FilesCreateHardLinkHeaders setDate(OffsetDateTime date) { + if (date == null) { + this.date = null; + } else { + this.date = new DateTimeRfc1123(date); + } + return this; + } + + /** + * Get the xMsMode property: The x-ms-mode property. + * + * @return the xMsMode value. + */ + public String getXMsMode() { + return this.xMsMode; + } + + /** + * Set the xMsMode property: The x-ms-mode property. + * + * @param xMsMode the xMsMode value to set. + * @return the FilesCreateHardLinkHeaders object itself. + */ + public FilesCreateHardLinkHeaders setXMsMode(String xMsMode) { + this.xMsMode = xMsMode; + return this; + } + + /** + * Get the eTag property: The ETag property. + * + * @return the eTag value. + */ + public String getETag() { + return this.eTag; + } + + /** + * Set the eTag property: The ETag property. + * + * @param eTag the eTag value to set. + * @return the FilesCreateHardLinkHeaders object itself. + */ + public FilesCreateHardLinkHeaders setETag(String eTag) { + this.eTag = eTag; + return this; + } + + /** + * Get the xMsLinkCount property: The x-ms-link-count property. + * + * @return the xMsLinkCount value. + */ + public Long getXMsLinkCount() { + return this.xMsLinkCount; + } + + /** + * Set the xMsLinkCount property: The x-ms-link-count property. + * + * @param xMsLinkCount the xMsLinkCount value to set. + * @return the FilesCreateHardLinkHeaders object itself. + */ + public FilesCreateHardLinkHeaders setXMsLinkCount(Long xMsLinkCount) { + this.xMsLinkCount = xMsLinkCount; + return this; + } + + /** + * Get the xMsFileChangeTime property: The x-ms-file-change-time property. + * + * @return the xMsFileChangeTime value. + */ + public OffsetDateTime getXMsFileChangeTime() { + return this.xMsFileChangeTime; + } + + /** + * Set the xMsFileChangeTime property: The x-ms-file-change-time property. + * + * @param xMsFileChangeTime the xMsFileChangeTime value to set. + * @return the FilesCreateHardLinkHeaders object itself. + */ + public FilesCreateHardLinkHeaders setXMsFileChangeTime(OffsetDateTime xMsFileChangeTime) { + this.xMsFileChangeTime = xMsFileChangeTime; + return this; + } + + /** + * Get the xMsFileParentId property: The x-ms-file-parent-id property. + * + * @return the xMsFileParentId value. + */ + public String getXMsFileParentId() { + return this.xMsFileParentId; + } + + /** + * Set the xMsFileParentId property: The x-ms-file-parent-id property. + * + * @param xMsFileParentId the xMsFileParentId value to set. + * @return the FilesCreateHardLinkHeaders object itself. + */ + public FilesCreateHardLinkHeaders setXMsFileParentId(String xMsFileParentId) { + this.xMsFileParentId = xMsFileParentId; + return this; + } + + /** + * Get the xMsRequestId property: The x-ms-request-id property. + * + * @return the xMsRequestId value. + */ + public String getXMsRequestId() { + return this.xMsRequestId; + } + + /** + * Set the xMsRequestId property: The x-ms-request-id property. + * + * @param xMsRequestId the xMsRequestId value to set. + * @return the FilesCreateHardLinkHeaders object itself. + */ + public FilesCreateHardLinkHeaders setXMsRequestId(String xMsRequestId) { + this.xMsRequestId = xMsRequestId; + return this; + } + + /** + * Get the xMsFileLastWriteTime property: The x-ms-file-last-write-time property. + * + * @return the xMsFileLastWriteTime value. + */ + public OffsetDateTime getXMsFileLastWriteTime() { + return this.xMsFileLastWriteTime; + } + + /** + * Set the xMsFileLastWriteTime property: The x-ms-file-last-write-time property. + * + * @param xMsFileLastWriteTime the xMsFileLastWriteTime value to set. + * @return the FilesCreateHardLinkHeaders object itself. + */ + public FilesCreateHardLinkHeaders setXMsFileLastWriteTime(OffsetDateTime xMsFileLastWriteTime) { + this.xMsFileLastWriteTime = xMsFileLastWriteTime; + return this; + } + + /** + * Get the xMsClientRequestId property: The x-ms-client-request-id property. + * + * @return the xMsClientRequestId value. + */ + public String getXMsClientRequestId() { + return this.xMsClientRequestId; + } + + /** + * Set the xMsClientRequestId property: The x-ms-client-request-id property. + * + * @param xMsClientRequestId the xMsClientRequestId value to set. + * @return the FilesCreateHardLinkHeaders object itself. + */ + public FilesCreateHardLinkHeaders setXMsClientRequestId(String xMsClientRequestId) { + this.xMsClientRequestId = xMsClientRequestId; + return this; + } + + /** + * Get the xMsOwner property: The x-ms-owner property. + * + * @return the xMsOwner value. + */ + public String getXMsOwner() { + return this.xMsOwner; + } + + /** + * Set the xMsOwner property: The x-ms-owner property. + * + * @param xMsOwner the xMsOwner value to set. + * @return the FilesCreateHardLinkHeaders object itself. + */ + public FilesCreateHardLinkHeaders setXMsOwner(String xMsOwner) { + this.xMsOwner = xMsOwner; + return this; + } +} diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/FilesCreateHeaders.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/FilesCreateHeaders.java index ed893f6355ad..4e0c05354787 100644 --- a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/FilesCreateHeaders.java +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/FilesCreateHeaders.java @@ -8,6 +8,7 @@ import com.azure.core.http.HttpHeaderName; import com.azure.core.http.HttpHeaders; import com.azure.core.util.DateTimeRfc1123; +import com.azure.storage.file.share.models.NfsFileType; import java.time.OffsetDateTime; /** @@ -15,6 +16,11 @@ */ @Fluent public final class FilesCreateHeaders { + /* + * The x-ms-group property. + */ + private String xMsGroup; + /* * The x-ms-version property. */ @@ -35,6 +41,11 @@ public final class FilesCreateHeaders { */ private OffsetDateTime xMsFileCreationTime; + /* + * The x-ms-file-file-type property. + */ + private NfsFileType xMsFileFileType; + /* * The Last-Modified property. */ @@ -50,6 +61,11 @@ public final class FilesCreateHeaders { */ private DateTimeRfc1123 date; + /* + * The x-ms-mode property. + */ + private String xMsMode; + /* * The ETag property. */ @@ -80,6 +96,13 @@ public final class FilesCreateHeaders { */ private OffsetDateTime xMsFileLastWriteTime; + /* + * The x-ms-owner property. + */ + private String xMsOwner; + + private static final HttpHeaderName X_MS_GROUP = HttpHeaderName.fromString("x-ms-group"); + private static final HttpHeaderName X_MS_VERSION = HttpHeaderName.fromString("x-ms-version"); private static final HttpHeaderName X_MS_FILE_PERMISSION_KEY @@ -89,9 +112,13 @@ public final class FilesCreateHeaders { private static final HttpHeaderName X_MS_FILE_CREATION_TIME = HttpHeaderName.fromString("x-ms-file-creation-time"); + private static final HttpHeaderName X_MS_FILE_FILE_TYPE = HttpHeaderName.fromString("x-ms-file-file-type"); + private static final HttpHeaderName X_MS_REQUEST_SERVER_ENCRYPTED = HttpHeaderName.fromString("x-ms-request-server-encrypted"); + private static final HttpHeaderName X_MS_MODE = HttpHeaderName.fromString("x-ms-mode"); + private static final HttpHeaderName X_MS_FILE_ATTRIBUTES = HttpHeaderName.fromString("x-ms-file-attributes"); private static final HttpHeaderName X_MS_FILE_CHANGE_TIME = HttpHeaderName.fromString("x-ms-file-change-time"); @@ -101,6 +128,8 @@ public final class FilesCreateHeaders { private static final HttpHeaderName X_MS_FILE_LAST_WRITE_TIME = HttpHeaderName.fromString("x-ms-file-last-write-time"); + private static final HttpHeaderName X_MS_OWNER = HttpHeaderName.fromString("x-ms-owner"); + // HttpHeaders containing the raw property values. /** * Creates an instance of FilesCreateHeaders class. @@ -108,6 +137,7 @@ public final class FilesCreateHeaders { * @param rawHeaders The raw HttpHeaders that will be used to create the property values. */ public FilesCreateHeaders(HttpHeaders rawHeaders) { + this.xMsGroup = rawHeaders.getValue(X_MS_GROUP); this.xMsVersion = rawHeaders.getValue(X_MS_VERSION); this.xMsFilePermissionKey = rawHeaders.getValue(X_MS_FILE_PERMISSION_KEY); this.xMsFileId = rawHeaders.getValue(X_MS_FILE_ID); @@ -115,6 +145,10 @@ public FilesCreateHeaders(HttpHeaders rawHeaders) { if (xMsFileCreationTime != null) { this.xMsFileCreationTime = OffsetDateTime.parse(xMsFileCreationTime); } + String xMsFileFileType = rawHeaders.getValue(X_MS_FILE_FILE_TYPE); + if (xMsFileFileType != null) { + this.xMsFileFileType = NfsFileType.fromString(xMsFileFileType); + } String lastModified = rawHeaders.getValue(HttpHeaderName.LAST_MODIFIED); if (lastModified != null) { this.lastModified = new DateTimeRfc1123(lastModified); @@ -127,6 +161,7 @@ public FilesCreateHeaders(HttpHeaders rawHeaders) { if (date != null) { this.date = new DateTimeRfc1123(date); } + this.xMsMode = rawHeaders.getValue(X_MS_MODE); this.eTag = rawHeaders.getValue(HttpHeaderName.ETAG); this.xMsFileAttributes = rawHeaders.getValue(X_MS_FILE_ATTRIBUTES); String xMsFileChangeTime = rawHeaders.getValue(X_MS_FILE_CHANGE_TIME); @@ -139,6 +174,27 @@ public FilesCreateHeaders(HttpHeaders rawHeaders) { if (xMsFileLastWriteTime != null) { this.xMsFileLastWriteTime = OffsetDateTime.parse(xMsFileLastWriteTime); } + this.xMsOwner = rawHeaders.getValue(X_MS_OWNER); + } + + /** + * Get the xMsGroup property: The x-ms-group property. + * + * @return the xMsGroup value. + */ + public String getXMsGroup() { + return this.xMsGroup; + } + + /** + * Set the xMsGroup property: The x-ms-group property. + * + * @param xMsGroup the xMsGroup value to set. + * @return the FilesCreateHeaders object itself. + */ + public FilesCreateHeaders setXMsGroup(String xMsGroup) { + this.xMsGroup = xMsGroup; + return this; } /** @@ -221,6 +277,26 @@ public FilesCreateHeaders setXMsFileCreationTime(OffsetDateTime xMsFileCreationT return this; } + /** + * Get the xMsFileFileType property: The x-ms-file-file-type property. + * + * @return the xMsFileFileType value. + */ + public NfsFileType getXMsFileFileType() { + return this.xMsFileFileType; + } + + /** + * Set the xMsFileFileType property: The x-ms-file-file-type property. + * + * @param xMsFileFileType the xMsFileFileType value to set. + * @return the FilesCreateHeaders object itself. + */ + public FilesCreateHeaders setXMsFileFileType(NfsFileType xMsFileFileType) { + this.xMsFileFileType = xMsFileFileType; + return this; + } + /** * Get the lastModified property: The Last-Modified property. * @@ -295,6 +371,26 @@ public FilesCreateHeaders setDate(OffsetDateTime date) { return this; } + /** + * Get the xMsMode property: The x-ms-mode property. + * + * @return the xMsMode value. + */ + public String getXMsMode() { + return this.xMsMode; + } + + /** + * Set the xMsMode property: The x-ms-mode property. + * + * @param xMsMode the xMsMode value to set. + * @return the FilesCreateHeaders object itself. + */ + public FilesCreateHeaders setXMsMode(String xMsMode) { + this.xMsMode = xMsMode; + return this; + } + /** * Get the eTag property: The ETag property. * @@ -414,4 +510,24 @@ public FilesCreateHeaders setXMsFileLastWriteTime(OffsetDateTime xMsFileLastWrit this.xMsFileLastWriteTime = xMsFileLastWriteTime; return this; } + + /** + * Get the xMsOwner property: The x-ms-owner property. + * + * @return the xMsOwner value. + */ + public String getXMsOwner() { + return this.xMsOwner; + } + + /** + * Set the xMsOwner property: The x-ms-owner property. + * + * @param xMsOwner the xMsOwner value to set. + * @return the FilesCreateHeaders object itself. + */ + public FilesCreateHeaders setXMsOwner(String xMsOwner) { + this.xMsOwner = xMsOwner; + return this; + } } diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/FilesCreateSymbolicLinkHeaders.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/FilesCreateSymbolicLinkHeaders.java new file mode 100644 index 000000000000..6e8edec06515 --- /dev/null +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/FilesCreateSymbolicLinkHeaders.java @@ -0,0 +1,491 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.storage.file.share.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.HttpHeaders; +import com.azure.core.util.DateTimeRfc1123; +import com.azure.storage.file.share.models.NfsFileType; +import java.time.OffsetDateTime; + +/** + * The FilesCreateSymbolicLinkHeaders model. + */ +@Fluent +public final class FilesCreateSymbolicLinkHeaders { + /* + * The x-ms-group property. + */ + private String xMsGroup; + + /* + * The x-ms-version property. + */ + private String xMsVersion; + + /* + * The x-ms-file-id property. + */ + private String xMsFileId; + + /* + * The x-ms-file-creation-time property. + */ + private DateTimeRfc1123 xMsFileCreationTime; + + /* + * The x-ms-file-file-type property. + */ + private NfsFileType xMsFileFileType; + + /* + * The Last-Modified property. + */ + private DateTimeRfc1123 lastModified; + + /* + * The Date property. + */ + private DateTimeRfc1123 date; + + /* + * The x-ms-mode property. + */ + private String xMsMode; + + /* + * The ETag property. + */ + private String eTag; + + /* + * The x-ms-file-change-time property. + */ + private DateTimeRfc1123 xMsFileChangeTime; + + /* + * The x-ms-file-parent-id property. + */ + private String xMsFileParentId; + + /* + * The x-ms-request-id property. + */ + private String xMsRequestId; + + /* + * The x-ms-file-last-write-time property. + */ + private DateTimeRfc1123 xMsFileLastWriteTime; + + /* + * The x-ms-client-request-id property. + */ + private String xMsClientRequestId; + + /* + * The x-ms-owner property. + */ + private String xMsOwner; + + private static final HttpHeaderName X_MS_GROUP = HttpHeaderName.fromString("x-ms-group"); + + private static final HttpHeaderName X_MS_VERSION = HttpHeaderName.fromString("x-ms-version"); + + private static final HttpHeaderName X_MS_FILE_ID = HttpHeaderName.fromString("x-ms-file-id"); + + private static final HttpHeaderName X_MS_FILE_CREATION_TIME = HttpHeaderName.fromString("x-ms-file-creation-time"); + + private static final HttpHeaderName X_MS_FILE_FILE_TYPE = HttpHeaderName.fromString("x-ms-file-file-type"); + + private static final HttpHeaderName X_MS_MODE = HttpHeaderName.fromString("x-ms-mode"); + + private static final HttpHeaderName X_MS_FILE_CHANGE_TIME = HttpHeaderName.fromString("x-ms-file-change-time"); + + private static final HttpHeaderName X_MS_FILE_PARENT_ID = HttpHeaderName.fromString("x-ms-file-parent-id"); + + private static final HttpHeaderName X_MS_FILE_LAST_WRITE_TIME + = HttpHeaderName.fromString("x-ms-file-last-write-time"); + + private static final HttpHeaderName X_MS_OWNER = HttpHeaderName.fromString("x-ms-owner"); + + // HttpHeaders containing the raw property values. + /** + * Creates an instance of FilesCreateSymbolicLinkHeaders class. + * + * @param rawHeaders The raw HttpHeaders that will be used to create the property values. + */ + public FilesCreateSymbolicLinkHeaders(HttpHeaders rawHeaders) { + this.xMsGroup = rawHeaders.getValue(X_MS_GROUP); + this.xMsVersion = rawHeaders.getValue(X_MS_VERSION); + this.xMsFileId = rawHeaders.getValue(X_MS_FILE_ID); + String xMsFileCreationTime = rawHeaders.getValue(X_MS_FILE_CREATION_TIME); + if (xMsFileCreationTime != null) { + this.xMsFileCreationTime = new DateTimeRfc1123(xMsFileCreationTime); + } + String xMsFileFileType = rawHeaders.getValue(X_MS_FILE_FILE_TYPE); + if (xMsFileFileType != null) { + this.xMsFileFileType = NfsFileType.fromString(xMsFileFileType); + } + String lastModified = rawHeaders.getValue(HttpHeaderName.LAST_MODIFIED); + if (lastModified != null) { + this.lastModified = new DateTimeRfc1123(lastModified); + } + String date = rawHeaders.getValue(HttpHeaderName.DATE); + if (date != null) { + this.date = new DateTimeRfc1123(date); + } + this.xMsMode = rawHeaders.getValue(X_MS_MODE); + this.eTag = rawHeaders.getValue(HttpHeaderName.ETAG); + String xMsFileChangeTime = rawHeaders.getValue(X_MS_FILE_CHANGE_TIME); + if (xMsFileChangeTime != null) { + this.xMsFileChangeTime = new DateTimeRfc1123(xMsFileChangeTime); + } + this.xMsFileParentId = rawHeaders.getValue(X_MS_FILE_PARENT_ID); + this.xMsRequestId = rawHeaders.getValue(HttpHeaderName.X_MS_REQUEST_ID); + String xMsFileLastWriteTime = rawHeaders.getValue(X_MS_FILE_LAST_WRITE_TIME); + if (xMsFileLastWriteTime != null) { + this.xMsFileLastWriteTime = new DateTimeRfc1123(xMsFileLastWriteTime); + } + this.xMsClientRequestId = rawHeaders.getValue(HttpHeaderName.X_MS_CLIENT_REQUEST_ID); + this.xMsOwner = rawHeaders.getValue(X_MS_OWNER); + } + + /** + * Get the xMsGroup property: The x-ms-group property. + * + * @return the xMsGroup value. + */ + public String getXMsGroup() { + return this.xMsGroup; + } + + /** + * Set the xMsGroup property: The x-ms-group property. + * + * @param xMsGroup the xMsGroup value to set. + * @return the FilesCreateSymbolicLinkHeaders object itself. + */ + public FilesCreateSymbolicLinkHeaders setXMsGroup(String xMsGroup) { + this.xMsGroup = xMsGroup; + return this; + } + + /** + * Get the xMsVersion property: The x-ms-version property. + * + * @return the xMsVersion value. + */ + public String getXMsVersion() { + return this.xMsVersion; + } + + /** + * Set the xMsVersion property: The x-ms-version property. + * + * @param xMsVersion the xMsVersion value to set. + * @return the FilesCreateSymbolicLinkHeaders object itself. + */ + public FilesCreateSymbolicLinkHeaders setXMsVersion(String xMsVersion) { + this.xMsVersion = xMsVersion; + return this; + } + + /** + * Get the xMsFileId property: The x-ms-file-id property. + * + * @return the xMsFileId value. + */ + public String getXMsFileId() { + return this.xMsFileId; + } + + /** + * Set the xMsFileId property: The x-ms-file-id property. + * + * @param xMsFileId the xMsFileId value to set. + * @return the FilesCreateSymbolicLinkHeaders object itself. + */ + public FilesCreateSymbolicLinkHeaders setXMsFileId(String xMsFileId) { + this.xMsFileId = xMsFileId; + return this; + } + + /** + * Get the xMsFileCreationTime property: The x-ms-file-creation-time property. + * + * @return the xMsFileCreationTime value. + */ + public OffsetDateTime getXMsFileCreationTime() { + if (this.xMsFileCreationTime == null) { + return null; + } + return this.xMsFileCreationTime.getDateTime(); + } + + /** + * Set the xMsFileCreationTime property: The x-ms-file-creation-time property. + * + * @param xMsFileCreationTime the xMsFileCreationTime value to set. + * @return the FilesCreateSymbolicLinkHeaders object itself. + */ + public FilesCreateSymbolicLinkHeaders setXMsFileCreationTime(OffsetDateTime xMsFileCreationTime) { + if (xMsFileCreationTime == null) { + this.xMsFileCreationTime = null; + } else { + this.xMsFileCreationTime = new DateTimeRfc1123(xMsFileCreationTime); + } + return this; + } + + /** + * Get the xMsFileFileType property: The x-ms-file-file-type property. + * + * @return the xMsFileFileType value. + */ + public NfsFileType getXMsFileFileType() { + return this.xMsFileFileType; + } + + /** + * Set the xMsFileFileType property: The x-ms-file-file-type property. + * + * @param xMsFileFileType the xMsFileFileType value to set. + * @return the FilesCreateSymbolicLinkHeaders object itself. + */ + public FilesCreateSymbolicLinkHeaders setXMsFileFileType(NfsFileType xMsFileFileType) { + this.xMsFileFileType = xMsFileFileType; + return this; + } + + /** + * Get the lastModified property: The Last-Modified property. + * + * @return the lastModified value. + */ + public OffsetDateTime getLastModified() { + if (this.lastModified == null) { + return null; + } + return this.lastModified.getDateTime(); + } + + /** + * Set the lastModified property: The Last-Modified property. + * + * @param lastModified the lastModified value to set. + * @return the FilesCreateSymbolicLinkHeaders object itself. + */ + public FilesCreateSymbolicLinkHeaders setLastModified(OffsetDateTime lastModified) { + if (lastModified == null) { + this.lastModified = null; + } else { + this.lastModified = new DateTimeRfc1123(lastModified); + } + return this; + } + + /** + * Get the date property: The Date property. + * + * @return the date value. + */ + public OffsetDateTime getDate() { + if (this.date == null) { + return null; + } + return this.date.getDateTime(); + } + + /** + * Set the date property: The Date property. + * + * @param date the date value to set. + * @return the FilesCreateSymbolicLinkHeaders object itself. + */ + public FilesCreateSymbolicLinkHeaders setDate(OffsetDateTime date) { + if (date == null) { + this.date = null; + } else { + this.date = new DateTimeRfc1123(date); + } + return this; + } + + /** + * Get the xMsMode property: The x-ms-mode property. + * + * @return the xMsMode value. + */ + public String getXMsMode() { + return this.xMsMode; + } + + /** + * Set the xMsMode property: The x-ms-mode property. + * + * @param xMsMode the xMsMode value to set. + * @return the FilesCreateSymbolicLinkHeaders object itself. + */ + public FilesCreateSymbolicLinkHeaders setXMsMode(String xMsMode) { + this.xMsMode = xMsMode; + return this; + } + + /** + * Get the eTag property: The ETag property. + * + * @return the eTag value. + */ + public String getETag() { + return this.eTag; + } + + /** + * Set the eTag property: The ETag property. + * + * @param eTag the eTag value to set. + * @return the FilesCreateSymbolicLinkHeaders object itself. + */ + public FilesCreateSymbolicLinkHeaders setETag(String eTag) { + this.eTag = eTag; + return this; + } + + /** + * Get the xMsFileChangeTime property: The x-ms-file-change-time property. + * + * @return the xMsFileChangeTime value. + */ + public OffsetDateTime getXMsFileChangeTime() { + if (this.xMsFileChangeTime == null) { + return null; + } + return this.xMsFileChangeTime.getDateTime(); + } + + /** + * Set the xMsFileChangeTime property: The x-ms-file-change-time property. + * + * @param xMsFileChangeTime the xMsFileChangeTime value to set. + * @return the FilesCreateSymbolicLinkHeaders object itself. + */ + public FilesCreateSymbolicLinkHeaders setXMsFileChangeTime(OffsetDateTime xMsFileChangeTime) { + if (xMsFileChangeTime == null) { + this.xMsFileChangeTime = null; + } else { + this.xMsFileChangeTime = new DateTimeRfc1123(xMsFileChangeTime); + } + return this; + } + + /** + * Get the xMsFileParentId property: The x-ms-file-parent-id property. + * + * @return the xMsFileParentId value. + */ + public String getXMsFileParentId() { + return this.xMsFileParentId; + } + + /** + * Set the xMsFileParentId property: The x-ms-file-parent-id property. + * + * @param xMsFileParentId the xMsFileParentId value to set. + * @return the FilesCreateSymbolicLinkHeaders object itself. + */ + public FilesCreateSymbolicLinkHeaders setXMsFileParentId(String xMsFileParentId) { + this.xMsFileParentId = xMsFileParentId; + return this; + } + + /** + * Get the xMsRequestId property: The x-ms-request-id property. + * + * @return the xMsRequestId value. + */ + public String getXMsRequestId() { + return this.xMsRequestId; + } + + /** + * Set the xMsRequestId property: The x-ms-request-id property. + * + * @param xMsRequestId the xMsRequestId value to set. + * @return the FilesCreateSymbolicLinkHeaders object itself. + */ + public FilesCreateSymbolicLinkHeaders setXMsRequestId(String xMsRequestId) { + this.xMsRequestId = xMsRequestId; + return this; + } + + /** + * Get the xMsFileLastWriteTime property: The x-ms-file-last-write-time property. + * + * @return the xMsFileLastWriteTime value. + */ + public OffsetDateTime getXMsFileLastWriteTime() { + if (this.xMsFileLastWriteTime == null) { + return null; + } + return this.xMsFileLastWriteTime.getDateTime(); + } + + /** + * Set the xMsFileLastWriteTime property: The x-ms-file-last-write-time property. + * + * @param xMsFileLastWriteTime the xMsFileLastWriteTime value to set. + * @return the FilesCreateSymbolicLinkHeaders object itself. + */ + public FilesCreateSymbolicLinkHeaders setXMsFileLastWriteTime(OffsetDateTime xMsFileLastWriteTime) { + if (xMsFileLastWriteTime == null) { + this.xMsFileLastWriteTime = null; + } else { + this.xMsFileLastWriteTime = new DateTimeRfc1123(xMsFileLastWriteTime); + } + return this; + } + + /** + * Get the xMsClientRequestId property: The x-ms-client-request-id property. + * + * @return the xMsClientRequestId value. + */ + public String getXMsClientRequestId() { + return this.xMsClientRequestId; + } + + /** + * Set the xMsClientRequestId property: The x-ms-client-request-id property. + * + * @param xMsClientRequestId the xMsClientRequestId value to set. + * @return the FilesCreateSymbolicLinkHeaders object itself. + */ + public FilesCreateSymbolicLinkHeaders setXMsClientRequestId(String xMsClientRequestId) { + this.xMsClientRequestId = xMsClientRequestId; + return this; + } + + /** + * Get the xMsOwner property: The x-ms-owner property. + * + * @return the xMsOwner value. + */ + public String getXMsOwner() { + return this.xMsOwner; + } + + /** + * Set the xMsOwner property: The x-ms-owner property. + * + * @param xMsOwner the xMsOwner value to set. + * @return the FilesCreateSymbolicLinkHeaders object itself. + */ + public FilesCreateSymbolicLinkHeaders setXMsOwner(String xMsOwner) { + this.xMsOwner = xMsOwner; + return this; + } +} diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/FilesDeleteHeaders.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/FilesDeleteHeaders.java index 78446c1ac002..1f88c645a408 100644 --- a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/FilesDeleteHeaders.java +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/FilesDeleteHeaders.java @@ -20,6 +20,11 @@ public final class FilesDeleteHeaders { */ private String xMsVersion; + /* + * The x-ms-link-count property. + */ + private Long xMsLinkCount; + /* * The x-ms-request-id property. */ @@ -32,6 +37,8 @@ public final class FilesDeleteHeaders { private static final HttpHeaderName X_MS_VERSION = HttpHeaderName.fromString("x-ms-version"); + private static final HttpHeaderName X_MS_LINK_COUNT = HttpHeaderName.fromString("x-ms-link-count"); + // HttpHeaders containing the raw property values. /** * Creates an instance of FilesDeleteHeaders class. @@ -40,6 +47,10 @@ public final class FilesDeleteHeaders { */ public FilesDeleteHeaders(HttpHeaders rawHeaders) { this.xMsVersion = rawHeaders.getValue(X_MS_VERSION); + String xMsLinkCount = rawHeaders.getValue(X_MS_LINK_COUNT); + if (xMsLinkCount != null) { + this.xMsLinkCount = Long.parseLong(xMsLinkCount); + } this.xMsRequestId = rawHeaders.getValue(HttpHeaderName.X_MS_REQUEST_ID); String date = rawHeaders.getValue(HttpHeaderName.DATE); if (date != null) { @@ -67,6 +78,26 @@ public FilesDeleteHeaders setXMsVersion(String xMsVersion) { return this; } + /** + * Get the xMsLinkCount property: The x-ms-link-count property. + * + * @return the xMsLinkCount value. + */ + public Long getXMsLinkCount() { + return this.xMsLinkCount; + } + + /** + * Set the xMsLinkCount property: The x-ms-link-count property. + * + * @param xMsLinkCount the xMsLinkCount value to set. + * @return the FilesDeleteHeaders object itself. + */ + public FilesDeleteHeaders setXMsLinkCount(Long xMsLinkCount) { + this.xMsLinkCount = xMsLinkCount; + return this; + } + /** * Get the xMsRequestId property: The x-ms-request-id property. * diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/FilesDownloadHeaders.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/FilesDownloadHeaders.java index 5ead3f5728bf..edc56f5ed748 100644 --- a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/FilesDownloadHeaders.java +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/FilesDownloadHeaders.java @@ -64,6 +64,11 @@ public final class FilesDownloadHeaders { */ private String xMsStructuredBody; + /* + * The x-ms-mode property. + */ + private String xMsMode; + /* * The x-ms-file-attributes property. */ @@ -99,11 +104,21 @@ public final class FilesDownloadHeaders { */ private String xMsRequestId; + /* + * The x-ms-owner property. + */ + private String xMsOwner; + /* * The Content-Type property. */ private String contentType; + /* + * The x-ms-group property. + */ + private String xMsGroup; + /* * The x-ms-version property. */ @@ -169,6 +184,11 @@ public final class FilesDownloadHeaders { */ private String eTag; + /* + * The x-ms-link-count property. + */ + private Long xMsLinkCount; + /* * The Content-Disposition property. */ @@ -211,6 +231,8 @@ public final class FilesDownloadHeaders { private static final HttpHeaderName X_MS_STRUCTURED_BODY = HttpHeaderName.fromString("x-ms-structured-body"); + private static final HttpHeaderName X_MS_MODE = HttpHeaderName.fromString("x-ms-mode"); + private static final HttpHeaderName X_MS_FILE_ATTRIBUTES = HttpHeaderName.fromString("x-ms-file-attributes"); private static final HttpHeaderName X_MS_STRUCTURED_CONTENT_LENGTH @@ -221,6 +243,10 @@ public final class FilesDownloadHeaders { private static final HttpHeaderName X_MS_LEASE_DURATION = HttpHeaderName.fromString("x-ms-lease-duration"); + private static final HttpHeaderName X_MS_OWNER = HttpHeaderName.fromString("x-ms-owner"); + + private static final HttpHeaderName X_MS_GROUP = HttpHeaderName.fromString("x-ms-group"); + private static final HttpHeaderName X_MS_VERSION = HttpHeaderName.fromString("x-ms-version"); private static final HttpHeaderName X_MS_FILE_PERMISSION_KEY @@ -237,6 +263,8 @@ public final class FilesDownloadHeaders { private static final HttpHeaderName X_MS_SERVER_ENCRYPTED = HttpHeaderName.fromString("x-ms-server-encrypted"); + private static final HttpHeaderName X_MS_LINK_COUNT = HttpHeaderName.fromString("x-ms-link-count"); + private static final HttpHeaderName X_MS_FILE_CHANGE_TIME = HttpHeaderName.fromString("x-ms-file-change-time"); private static final HttpHeaderName X_MS_FILE_PARENT_ID = HttpHeaderName.fromString("x-ms-file-parent-id"); @@ -276,6 +304,7 @@ public FilesDownloadHeaders(HttpHeaders rawHeaders) { this.lastModified = new DateTimeRfc1123(lastModified); } this.xMsStructuredBody = rawHeaders.getValue(X_MS_STRUCTURED_BODY); + this.xMsMode = rawHeaders.getValue(X_MS_MODE); this.xMsFileAttributes = rawHeaders.getValue(X_MS_FILE_ATTRIBUTES); String xMsStructuredContentLength = rawHeaders.getValue(X_MS_STRUCTURED_CONTENT_LENGTH); if (xMsStructuredContentLength != null) { @@ -292,7 +321,9 @@ public FilesDownloadHeaders(HttpHeaders rawHeaders) { this.contentLength = Long.parseLong(contentLength); } this.xMsRequestId = rawHeaders.getValue(HttpHeaderName.X_MS_REQUEST_ID); + this.xMsOwner = rawHeaders.getValue(X_MS_OWNER); this.contentType = rawHeaders.getValue(HttpHeaderName.CONTENT_TYPE); + this.xMsGroup = rawHeaders.getValue(X_MS_GROUP); this.xMsVersion = rawHeaders.getValue(X_MS_VERSION); this.xMsFilePermissionKey = rawHeaders.getValue(X_MS_FILE_PERMISSION_KEY); this.xMsCopyId = rawHeaders.getValue(X_MS_COPY_ID); @@ -317,6 +348,10 @@ public FilesDownloadHeaders(HttpHeaders rawHeaders) { } this.cacheControl = rawHeaders.getValue(HttpHeaderName.CACHE_CONTROL); this.eTag = rawHeaders.getValue(HttpHeaderName.ETAG); + String xMsLinkCount = rawHeaders.getValue(X_MS_LINK_COUNT); + if (xMsLinkCount != null) { + this.xMsLinkCount = Long.parseLong(xMsLinkCount); + } this.contentDisposition = rawHeaders.getValue(HttpHeaderName.CONTENT_DISPOSITION); String xMsFileChangeTime = rawHeaders.getValue(X_MS_FILE_CHANGE_TIME); if (xMsFileChangeTime != null) { @@ -511,6 +546,26 @@ public FilesDownloadHeaders setXMsStructuredBody(String xMsStructuredBody) { return this; } + /** + * Get the xMsMode property: The x-ms-mode property. + * + * @return the xMsMode value. + */ + public String getXMsMode() { + return this.xMsMode; + } + + /** + * Set the xMsMode property: The x-ms-mode property. + * + * @param xMsMode the xMsMode value to set. + * @return the FilesDownloadHeaders object itself. + */ + public FilesDownloadHeaders setXMsMode(String xMsMode) { + this.xMsMode = xMsMode; + return this; + } + /** * Get the xMsFileAttributes property: The x-ms-file-attributes property. * @@ -651,6 +706,26 @@ public FilesDownloadHeaders setXMsRequestId(String xMsRequestId) { return this; } + /** + * Get the xMsOwner property: The x-ms-owner property. + * + * @return the xMsOwner value. + */ + public String getXMsOwner() { + return this.xMsOwner; + } + + /** + * Set the xMsOwner property: The x-ms-owner property. + * + * @param xMsOwner the xMsOwner value to set. + * @return the FilesDownloadHeaders object itself. + */ + public FilesDownloadHeaders setXMsOwner(String xMsOwner) { + this.xMsOwner = xMsOwner; + return this; + } + /** * Get the contentType property: The Content-Type property. * @@ -671,6 +746,26 @@ public FilesDownloadHeaders setContentType(String contentType) { return this; } + /** + * Get the xMsGroup property: The x-ms-group property. + * + * @return the xMsGroup value. + */ + public String getXMsGroup() { + return this.xMsGroup; + } + + /** + * Set the xMsGroup property: The x-ms-group property. + * + * @param xMsGroup the xMsGroup value to set. + * @return the FilesDownloadHeaders object itself. + */ + public FilesDownloadHeaders setXMsGroup(String xMsGroup) { + this.xMsGroup = xMsGroup; + return this; + } + /** * Get the xMsVersion property: The x-ms-version property. * @@ -945,6 +1040,26 @@ public FilesDownloadHeaders setETag(String eTag) { return this; } + /** + * Get the xMsLinkCount property: The x-ms-link-count property. + * + * @return the xMsLinkCount value. + */ + public Long getXMsLinkCount() { + return this.xMsLinkCount; + } + + /** + * Set the xMsLinkCount property: The x-ms-link-count property. + * + * @param xMsLinkCount the xMsLinkCount value to set. + * @return the FilesDownloadHeaders object itself. + */ + public FilesDownloadHeaders setXMsLinkCount(Long xMsLinkCount) { + this.xMsLinkCount = xMsLinkCount; + return this; + } + /** * Get the contentDisposition property: The Content-Disposition property. * diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/FilesGetPropertiesHeaders.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/FilesGetPropertiesHeaders.java index 78ab0071595b..b748b4b85025 100644 --- a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/FilesGetPropertiesHeaders.java +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/FilesGetPropertiesHeaders.java @@ -14,6 +14,7 @@ import com.azure.storage.file.share.models.LeaseDurationType; import com.azure.storage.file.share.models.LeaseStateType; import com.azure.storage.file.share.models.LeaseStatusType; +import com.azure.storage.file.share.models.NfsFileType; import java.time.OffsetDateTime; import java.util.Base64; import java.util.LinkedHashMap; @@ -49,6 +50,11 @@ public final class FilesGetPropertiesHeaders { */ private DateTimeRfc1123 lastModified; + /* + * The x-ms-mode property. + */ + private String xMsMode; + /* * The x-ms-file-attributes property. */ @@ -79,11 +85,21 @@ public final class FilesGetPropertiesHeaders { */ private String xMsRequestId; + /* + * The x-ms-owner property. + */ + private String xMsOwner; + /* * The Content-Type property. */ private String contentType; + /* + * The x-ms-group property. + */ + private String xMsGroup; + /* * The x-ms-version property. */ @@ -104,6 +120,11 @@ public final class FilesGetPropertiesHeaders { */ private String xMsCopySource; + /* + * The x-ms-file-file-type property. + */ + private NfsFileType xMsFileFileType; + /* * The x-ms-copy-progress property. */ @@ -149,6 +170,11 @@ public final class FilesGetPropertiesHeaders { */ private String eTag; + /* + * The x-ms-link-count property. + */ + private Long xMsLinkCount; + /* * The Content-Disposition property. */ @@ -187,6 +213,8 @@ public final class FilesGetPropertiesHeaders { private static final HttpHeaderName X_MS_LEASE_STATE = HttpHeaderName.fromString("x-ms-lease-state"); + private static final HttpHeaderName X_MS_MODE = HttpHeaderName.fromString("x-ms-mode"); + private static final HttpHeaderName X_MS_FILE_ATTRIBUTES = HttpHeaderName.fromString("x-ms-file-attributes"); private static final HttpHeaderName X_MS_COPY_STATUS_DESCRIPTION @@ -194,6 +222,10 @@ public final class FilesGetPropertiesHeaders { private static final HttpHeaderName X_MS_LEASE_DURATION = HttpHeaderName.fromString("x-ms-lease-duration"); + private static final HttpHeaderName X_MS_OWNER = HttpHeaderName.fromString("x-ms-owner"); + + private static final HttpHeaderName X_MS_GROUP = HttpHeaderName.fromString("x-ms-group"); + private static final HttpHeaderName X_MS_VERSION = HttpHeaderName.fromString("x-ms-version"); private static final HttpHeaderName X_MS_FILE_PERMISSION_KEY @@ -203,6 +235,8 @@ public final class FilesGetPropertiesHeaders { private static final HttpHeaderName X_MS_COPY_SOURCE = HttpHeaderName.fromString("x-ms-copy-source"); + private static final HttpHeaderName X_MS_FILE_FILE_TYPE = HttpHeaderName.fromString("x-ms-file-file-type"); + private static final HttpHeaderName X_MS_COPY_PROGRESS = HttpHeaderName.fromString("x-ms-copy-progress"); private static final HttpHeaderName X_MS_COPY_COMPLETION_TIME @@ -212,6 +246,8 @@ public final class FilesGetPropertiesHeaders { private static final HttpHeaderName X_MS_TYPE = HttpHeaderName.fromString("x-ms-type"); + private static final HttpHeaderName X_MS_LINK_COUNT = HttpHeaderName.fromString("x-ms-link-count"); + private static final HttpHeaderName X_MS_FILE_CHANGE_TIME = HttpHeaderName.fromString("x-ms-file-change-time"); private static final HttpHeaderName X_MS_FILE_PARENT_ID = HttpHeaderName.fromString("x-ms-file-parent-id"); @@ -245,6 +281,7 @@ public FilesGetPropertiesHeaders(HttpHeaders rawHeaders) { if (lastModified != null) { this.lastModified = new DateTimeRfc1123(lastModified); } + this.xMsMode = rawHeaders.getValue(X_MS_MODE); this.xMsFileAttributes = rawHeaders.getValue(X_MS_FILE_ATTRIBUTES); this.contentEncoding = rawHeaders.getValue(HttpHeaderName.CONTENT_ENCODING); this.xMsCopyStatusDescription = rawHeaders.getValue(X_MS_COPY_STATUS_DESCRIPTION); @@ -257,11 +294,17 @@ public FilesGetPropertiesHeaders(HttpHeaders rawHeaders) { this.contentLength = Long.parseLong(contentLength); } this.xMsRequestId = rawHeaders.getValue(HttpHeaderName.X_MS_REQUEST_ID); + this.xMsOwner = rawHeaders.getValue(X_MS_OWNER); this.contentType = rawHeaders.getValue(HttpHeaderName.CONTENT_TYPE); + this.xMsGroup = rawHeaders.getValue(X_MS_GROUP); this.xMsVersion = rawHeaders.getValue(X_MS_VERSION); this.xMsFilePermissionKey = rawHeaders.getValue(X_MS_FILE_PERMISSION_KEY); this.xMsCopyId = rawHeaders.getValue(X_MS_COPY_ID); this.xMsCopySource = rawHeaders.getValue(X_MS_COPY_SOURCE); + String xMsFileFileType = rawHeaders.getValue(X_MS_FILE_FILE_TYPE); + if (xMsFileFileType != null) { + this.xMsFileFileType = NfsFileType.fromString(xMsFileFileType); + } this.xMsCopyProgress = rawHeaders.getValue(X_MS_COPY_PROGRESS); String date = rawHeaders.getValue(HttpHeaderName.DATE); if (date != null) { @@ -282,6 +325,10 @@ public FilesGetPropertiesHeaders(HttpHeaders rawHeaders) { this.xMsType = rawHeaders.getValue(X_MS_TYPE); this.cacheControl = rawHeaders.getValue(HttpHeaderName.CACHE_CONTROL); this.eTag = rawHeaders.getValue(HttpHeaderName.ETAG); + String xMsLinkCount = rawHeaders.getValue(X_MS_LINK_COUNT); + if (xMsLinkCount != null) { + this.xMsLinkCount = Long.parseLong(xMsLinkCount); + } this.contentDisposition = rawHeaders.getValue(HttpHeaderName.CONTENT_DISPOSITION); String xMsFileChangeTime = rawHeaders.getValue(X_MS_FILE_CHANGE_TIME); if (xMsFileChangeTime != null) { @@ -416,6 +463,26 @@ public FilesGetPropertiesHeaders setLastModified(OffsetDateTime lastModified) { return this; } + /** + * Get the xMsMode property: The x-ms-mode property. + * + * @return the xMsMode value. + */ + public String getXMsMode() { + return this.xMsMode; + } + + /** + * Set the xMsMode property: The x-ms-mode property. + * + * @param xMsMode the xMsMode value to set. + * @return the FilesGetPropertiesHeaders object itself. + */ + public FilesGetPropertiesHeaders setXMsMode(String xMsMode) { + this.xMsMode = xMsMode; + return this; + } + /** * Get the xMsFileAttributes property: The x-ms-file-attributes property. * @@ -536,6 +603,26 @@ public FilesGetPropertiesHeaders setXMsRequestId(String xMsRequestId) { return this; } + /** + * Get the xMsOwner property: The x-ms-owner property. + * + * @return the xMsOwner value. + */ + public String getXMsOwner() { + return this.xMsOwner; + } + + /** + * Set the xMsOwner property: The x-ms-owner property. + * + * @param xMsOwner the xMsOwner value to set. + * @return the FilesGetPropertiesHeaders object itself. + */ + public FilesGetPropertiesHeaders setXMsOwner(String xMsOwner) { + this.xMsOwner = xMsOwner; + return this; + } + /** * Get the contentType property: The Content-Type property. * @@ -556,6 +643,26 @@ public FilesGetPropertiesHeaders setContentType(String contentType) { return this; } + /** + * Get the xMsGroup property: The x-ms-group property. + * + * @return the xMsGroup value. + */ + public String getXMsGroup() { + return this.xMsGroup; + } + + /** + * Set the xMsGroup property: The x-ms-group property. + * + * @param xMsGroup the xMsGroup value to set. + * @return the FilesGetPropertiesHeaders object itself. + */ + public FilesGetPropertiesHeaders setXMsGroup(String xMsGroup) { + this.xMsGroup = xMsGroup; + return this; + } + /** * Get the xMsVersion property: The x-ms-version property. * @@ -636,6 +743,26 @@ public FilesGetPropertiesHeaders setXMsCopySource(String xMsCopySource) { return this; } + /** + * Get the xMsFileFileType property: The x-ms-file-file-type property. + * + * @return the xMsFileFileType value. + */ + public NfsFileType getXMsFileFileType() { + return this.xMsFileFileType; + } + + /** + * Set the xMsFileFileType property: The x-ms-file-file-type property. + * + * @param xMsFileFileType the xMsFileFileType value to set. + * @return the FilesGetPropertiesHeaders object itself. + */ + public FilesGetPropertiesHeaders setXMsFileFileType(NfsFileType xMsFileFileType) { + this.xMsFileFileType = xMsFileFileType; + return this; + } + /** * Get the xMsCopyProgress property: The x-ms-copy-progress property. * @@ -830,6 +957,26 @@ public FilesGetPropertiesHeaders setETag(String eTag) { return this; } + /** + * Get the xMsLinkCount property: The x-ms-link-count property. + * + * @return the xMsLinkCount value. + */ + public Long getXMsLinkCount() { + return this.xMsLinkCount; + } + + /** + * Set the xMsLinkCount property: The x-ms-link-count property. + * + * @param xMsLinkCount the xMsLinkCount value to set. + * @return the FilesGetPropertiesHeaders object itself. + */ + public FilesGetPropertiesHeaders setXMsLinkCount(Long xMsLinkCount) { + this.xMsLinkCount = xMsLinkCount; + return this; + } + /** * Get the contentDisposition property: The Content-Disposition property. * diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/FilesGetSymbolicLinkHeaders.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/FilesGetSymbolicLinkHeaders.java new file mode 100644 index 000000000000..fbe8e432ad64 --- /dev/null +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/FilesGetSymbolicLinkHeaders.java @@ -0,0 +1,232 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.storage.file.share.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.HttpHeaders; +import com.azure.core.util.DateTimeRfc1123; +import java.time.OffsetDateTime; + +/** + * The FilesGetSymbolicLinkHeaders model. + */ +@Fluent +public final class FilesGetSymbolicLinkHeaders { + /* + * The x-ms-version property. + */ + private String xMsVersion; + + /* + * The ETag property. + */ + private String eTag; + + /* + * The Last-Modified property. + */ + private DateTimeRfc1123 lastModified; + + /* + * The x-ms-link-text property. + */ + private String xMsLinkText; + + /* + * The x-ms-request-id property. + */ + private String xMsRequestId; + + /* + * The Date property. + */ + private DateTimeRfc1123 date; + + /* + * The x-ms-client-request-id property. + */ + private String xMsClientRequestId; + + private static final HttpHeaderName X_MS_VERSION = HttpHeaderName.fromString("x-ms-version"); + + private static final HttpHeaderName X_MS_LINK_TEXT = HttpHeaderName.fromString("x-ms-link-text"); + + // HttpHeaders containing the raw property values. + /** + * Creates an instance of FilesGetSymbolicLinkHeaders class. + * + * @param rawHeaders The raw HttpHeaders that will be used to create the property values. + */ + public FilesGetSymbolicLinkHeaders(HttpHeaders rawHeaders) { + this.xMsVersion = rawHeaders.getValue(X_MS_VERSION); + this.eTag = rawHeaders.getValue(HttpHeaderName.ETAG); + String lastModified = rawHeaders.getValue(HttpHeaderName.LAST_MODIFIED); + if (lastModified != null) { + this.lastModified = new DateTimeRfc1123(lastModified); + } + this.xMsLinkText = rawHeaders.getValue(X_MS_LINK_TEXT); + this.xMsRequestId = rawHeaders.getValue(HttpHeaderName.X_MS_REQUEST_ID); + String date = rawHeaders.getValue(HttpHeaderName.DATE); + if (date != null) { + this.date = new DateTimeRfc1123(date); + } + this.xMsClientRequestId = rawHeaders.getValue(HttpHeaderName.X_MS_CLIENT_REQUEST_ID); + } + + /** + * Get the xMsVersion property: The x-ms-version property. + * + * @return the xMsVersion value. + */ + public String getXMsVersion() { + return this.xMsVersion; + } + + /** + * Set the xMsVersion property: The x-ms-version property. + * + * @param xMsVersion the xMsVersion value to set. + * @return the FilesGetSymbolicLinkHeaders object itself. + */ + public FilesGetSymbolicLinkHeaders setXMsVersion(String xMsVersion) { + this.xMsVersion = xMsVersion; + return this; + } + + /** + * Get the eTag property: The ETag property. + * + * @return the eTag value. + */ + public String getETag() { + return this.eTag; + } + + /** + * Set the eTag property: The ETag property. + * + * @param eTag the eTag value to set. + * @return the FilesGetSymbolicLinkHeaders object itself. + */ + public FilesGetSymbolicLinkHeaders setETag(String eTag) { + this.eTag = eTag; + return this; + } + + /** + * Get the lastModified property: The Last-Modified property. + * + * @return the lastModified value. + */ + public OffsetDateTime getLastModified() { + if (this.lastModified == null) { + return null; + } + return this.lastModified.getDateTime(); + } + + /** + * Set the lastModified property: The Last-Modified property. + * + * @param lastModified the lastModified value to set. + * @return the FilesGetSymbolicLinkHeaders object itself. + */ + public FilesGetSymbolicLinkHeaders setLastModified(OffsetDateTime lastModified) { + if (lastModified == null) { + this.lastModified = null; + } else { + this.lastModified = new DateTimeRfc1123(lastModified); + } + return this; + } + + /** + * Get the xMsLinkText property: The x-ms-link-text property. + * + * @return the xMsLinkText value. + */ + public String getXMsLinkText() { + return this.xMsLinkText; + } + + /** + * Set the xMsLinkText property: The x-ms-link-text property. + * + * @param xMsLinkText the xMsLinkText value to set. + * @return the FilesGetSymbolicLinkHeaders object itself. + */ + public FilesGetSymbolicLinkHeaders setXMsLinkText(String xMsLinkText) { + this.xMsLinkText = xMsLinkText; + return this; + } + + /** + * Get the xMsRequestId property: The x-ms-request-id property. + * + * @return the xMsRequestId value. + */ + public String getXMsRequestId() { + return this.xMsRequestId; + } + + /** + * Set the xMsRequestId property: The x-ms-request-id property. + * + * @param xMsRequestId the xMsRequestId value to set. + * @return the FilesGetSymbolicLinkHeaders object itself. + */ + public FilesGetSymbolicLinkHeaders setXMsRequestId(String xMsRequestId) { + this.xMsRequestId = xMsRequestId; + return this; + } + + /** + * Get the date property: The Date property. + * + * @return the date value. + */ + public OffsetDateTime getDate() { + if (this.date == null) { + return null; + } + return this.date.getDateTime(); + } + + /** + * Set the date property: The Date property. + * + * @param date the date value to set. + * @return the FilesGetSymbolicLinkHeaders object itself. + */ + public FilesGetSymbolicLinkHeaders setDate(OffsetDateTime date) { + if (date == null) { + this.date = null; + } else { + this.date = new DateTimeRfc1123(date); + } + return this; + } + + /** + * Get the xMsClientRequestId property: The x-ms-client-request-id property. + * + * @return the xMsClientRequestId value. + */ + public String getXMsClientRequestId() { + return this.xMsClientRequestId; + } + + /** + * Set the xMsClientRequestId property: The x-ms-client-request-id property. + * + * @param xMsClientRequestId the xMsClientRequestId value to set. + * @return the FilesGetSymbolicLinkHeaders object itself. + */ + public FilesGetSymbolicLinkHeaders setXMsClientRequestId(String xMsClientRequestId) { + this.xMsClientRequestId = xMsClientRequestId; + return this; + } +} diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/FilesSetHttpHeadersHeaders.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/FilesSetHttpHeadersHeaders.java index b027ca0e44c8..5046cd4485a7 100644 --- a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/FilesSetHttpHeadersHeaders.java +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/models/FilesSetHttpHeadersHeaders.java @@ -15,6 +15,11 @@ */ @Fluent public final class FilesSetHttpHeadersHeaders { + /* + * The x-ms-group property. + */ + private String xMsGroup; + /* * The x-ms-version property. */ @@ -50,11 +55,21 @@ public final class FilesSetHttpHeadersHeaders { */ private DateTimeRfc1123 date; + /* + * The x-ms-mode property. + */ + private String xMsMode; + /* * The ETag property. */ private String eTag; + /* + * The x-ms-link-count property. + */ + private Long xMsLinkCount; + /* * The x-ms-file-attributes property. */ @@ -80,6 +95,13 @@ public final class FilesSetHttpHeadersHeaders { */ private OffsetDateTime xMsFileLastWriteTime; + /* + * The x-ms-owner property. + */ + private String xMsOwner; + + private static final HttpHeaderName X_MS_GROUP = HttpHeaderName.fromString("x-ms-group"); + private static final HttpHeaderName X_MS_VERSION = HttpHeaderName.fromString("x-ms-version"); private static final HttpHeaderName X_MS_FILE_PERMISSION_KEY @@ -92,6 +114,10 @@ public final class FilesSetHttpHeadersHeaders { private static final HttpHeaderName X_MS_REQUEST_SERVER_ENCRYPTED = HttpHeaderName.fromString("x-ms-request-server-encrypted"); + private static final HttpHeaderName X_MS_MODE = HttpHeaderName.fromString("x-ms-mode"); + + private static final HttpHeaderName X_MS_LINK_COUNT = HttpHeaderName.fromString("x-ms-link-count"); + private static final HttpHeaderName X_MS_FILE_ATTRIBUTES = HttpHeaderName.fromString("x-ms-file-attributes"); private static final HttpHeaderName X_MS_FILE_CHANGE_TIME = HttpHeaderName.fromString("x-ms-file-change-time"); @@ -101,6 +127,8 @@ public final class FilesSetHttpHeadersHeaders { private static final HttpHeaderName X_MS_FILE_LAST_WRITE_TIME = HttpHeaderName.fromString("x-ms-file-last-write-time"); + private static final HttpHeaderName X_MS_OWNER = HttpHeaderName.fromString("x-ms-owner"); + // HttpHeaders containing the raw property values. /** * Creates an instance of FilesSetHttpHeadersHeaders class. @@ -108,6 +136,7 @@ public final class FilesSetHttpHeadersHeaders { * @param rawHeaders The raw HttpHeaders that will be used to create the property values. */ public FilesSetHttpHeadersHeaders(HttpHeaders rawHeaders) { + this.xMsGroup = rawHeaders.getValue(X_MS_GROUP); this.xMsVersion = rawHeaders.getValue(X_MS_VERSION); this.xMsFilePermissionKey = rawHeaders.getValue(X_MS_FILE_PERMISSION_KEY); this.xMsFileId = rawHeaders.getValue(X_MS_FILE_ID); @@ -127,7 +156,12 @@ public FilesSetHttpHeadersHeaders(HttpHeaders rawHeaders) { if (date != null) { this.date = new DateTimeRfc1123(date); } + this.xMsMode = rawHeaders.getValue(X_MS_MODE); this.eTag = rawHeaders.getValue(HttpHeaderName.ETAG); + String xMsLinkCount = rawHeaders.getValue(X_MS_LINK_COUNT); + if (xMsLinkCount != null) { + this.xMsLinkCount = Long.parseLong(xMsLinkCount); + } this.xMsFileAttributes = rawHeaders.getValue(X_MS_FILE_ATTRIBUTES); String xMsFileChangeTime = rawHeaders.getValue(X_MS_FILE_CHANGE_TIME); if (xMsFileChangeTime != null) { @@ -139,6 +173,27 @@ public FilesSetHttpHeadersHeaders(HttpHeaders rawHeaders) { if (xMsFileLastWriteTime != null) { this.xMsFileLastWriteTime = OffsetDateTime.parse(xMsFileLastWriteTime); } + this.xMsOwner = rawHeaders.getValue(X_MS_OWNER); + } + + /** + * Get the xMsGroup property: The x-ms-group property. + * + * @return the xMsGroup value. + */ + public String getXMsGroup() { + return this.xMsGroup; + } + + /** + * Set the xMsGroup property: The x-ms-group property. + * + * @param xMsGroup the xMsGroup value to set. + * @return the FilesSetHttpHeadersHeaders object itself. + */ + public FilesSetHttpHeadersHeaders setXMsGroup(String xMsGroup) { + this.xMsGroup = xMsGroup; + return this; } /** @@ -295,6 +350,26 @@ public FilesSetHttpHeadersHeaders setDate(OffsetDateTime date) { return this; } + /** + * Get the xMsMode property: The x-ms-mode property. + * + * @return the xMsMode value. + */ + public String getXMsMode() { + return this.xMsMode; + } + + /** + * Set the xMsMode property: The x-ms-mode property. + * + * @param xMsMode the xMsMode value to set. + * @return the FilesSetHttpHeadersHeaders object itself. + */ + public FilesSetHttpHeadersHeaders setXMsMode(String xMsMode) { + this.xMsMode = xMsMode; + return this; + } + /** * Get the eTag property: The ETag property. * @@ -315,6 +390,26 @@ public FilesSetHttpHeadersHeaders setETag(String eTag) { return this; } + /** + * Get the xMsLinkCount property: The x-ms-link-count property. + * + * @return the xMsLinkCount value. + */ + public Long getXMsLinkCount() { + return this.xMsLinkCount; + } + + /** + * Set the xMsLinkCount property: The x-ms-link-count property. + * + * @param xMsLinkCount the xMsLinkCount value to set. + * @return the FilesSetHttpHeadersHeaders object itself. + */ + public FilesSetHttpHeadersHeaders setXMsLinkCount(Long xMsLinkCount) { + this.xMsLinkCount = xMsLinkCount; + return this; + } + /** * Get the xMsFileAttributes property: The x-ms-file-attributes property. * @@ -414,4 +509,24 @@ public FilesSetHttpHeadersHeaders setXMsFileLastWriteTime(OffsetDateTime xMsFile this.xMsFileLastWriteTime = xMsFileLastWriteTime; return this; } + + /** + * Get the xMsOwner property: The x-ms-owner property. + * + * @return the xMsOwner value. + */ + public String getXMsOwner() { + return this.xMsOwner; + } + + /** + * Set the xMsOwner property: The x-ms-owner property. + * + * @param xMsOwner the xMsOwner value to set. + * @return the FilesSetHttpHeadersHeaders object itself. + */ + public FilesSetHttpHeadersHeaders setXMsOwner(String xMsOwner) { + this.xMsOwner = xMsOwner; + return this; + } } diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/util/ModelHelper.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/util/ModelHelper.java index 0c3f29175c80..fd61a7dc2f2e 100644 --- a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/util/ModelHelper.java +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/implementation/util/ModelHelper.java @@ -17,14 +17,20 @@ import com.azure.storage.common.implementation.StorageImplUtils; import com.azure.storage.file.share.FileSmbProperties; import com.azure.storage.file.share.implementation.MessageConstants; +import com.azure.storage.file.share.implementation.accesshelpers.FilePosixPropertiesHelper; import com.azure.storage.file.share.implementation.accesshelpers.FileSmbPropertiesHelper; +import com.azure.storage.file.share.implementation.accesshelpers.ShareDirectoryInfoHelper; +import com.azure.storage.file.share.implementation.accesshelpers.ShareDirectoryPropertiesHelper; import com.azure.storage.file.share.implementation.accesshelpers.ShareFileDownloadHeadersConstructorProxy; +import com.azure.storage.file.share.implementation.accesshelpers.ShareFileInfoHelper; +import com.azure.storage.file.share.implementation.accesshelpers.ShareFilePropertiesHelper; import com.azure.storage.file.share.implementation.models.DeleteSnapshotsOptionType; import com.azure.storage.file.share.implementation.models.DirectoriesCreateHeaders; import com.azure.storage.file.share.implementation.models.DirectoriesGetPropertiesHeaders; import com.azure.storage.file.share.implementation.models.DirectoriesSetMetadataHeaders; import com.azure.storage.file.share.implementation.models.DirectoriesSetPropertiesHeaders; import com.azure.storage.file.share.implementation.models.FileProperty; +import com.azure.storage.file.share.implementation.models.FilesCreateHardLinkHeaders; import com.azure.storage.file.share.implementation.models.FilesCreateHeaders; import com.azure.storage.file.share.implementation.models.FilesDownloadHeaders; import com.azure.storage.file.share.implementation.models.FilesGetPropertiesHeaders; @@ -44,6 +50,7 @@ import com.azure.storage.file.share.implementation.models.StringEncoded; import com.azure.storage.file.share.models.CopyStatusType; import com.azure.storage.file.share.models.CopyableFileSmbPropertiesList; +import com.azure.storage.file.share.models.FilePosixProperties; import com.azure.storage.file.share.models.HandleItem; import com.azure.storage.file.share.models.LeaseDurationType; import com.azure.storage.file.share.models.LeaseStateType; @@ -356,7 +363,9 @@ public static Response createFileInfoResponse(ResponseBase(response, shareFileInfo); } @@ -389,10 +398,11 @@ public static Response createFileInfoResponse(ResponseBase(response, shareFileProperties); } @@ -402,7 +412,9 @@ public static Response createFileInfoResponse(ResponseBase(response, shareFileInfo); } @@ -541,7 +553,9 @@ public static Response mapGetStatisticsResponse(Response(response, shareDirectoryInfo); } @@ -552,8 +566,9 @@ public static Response mapGetStatisticsResponse(Response(response, shareDirectoryProperties); } @@ -562,7 +577,9 @@ public static Response mapGetStatisticsResponse(Response(response, shareDirectoryInfo); } @@ -601,6 +618,17 @@ public static Response mapGetStatisticsResponse(Response(shareFileItems); } + public static Response + createHardLinkResponse(final ResponseBase response) { + String eTag = response.getDeserializedHeaders().getETag(); + OffsetDateTime lastModified = response.getDeserializedHeaders().getLastModified(); + FileSmbProperties smbProperties = FileSmbPropertiesHelper.create(response.getHeaders()); + FilePosixProperties posixProperties = FilePosixPropertiesHelper.create(response.getHeaders()); + ShareFileInfo shareFileInfo + = ShareFileInfoHelper.create(eTag, lastModified, null, smbProperties, posixProperties); + return new SimpleResponse<>(response, shareFileInfo); + } + public static List truncateAccessPolicyPermissionsToSeconds(List permissions) { /* diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/models/FilePosixProperties.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/models/FilePosixProperties.java new file mode 100644 index 000000000000..3f58bfcaac63 --- /dev/null +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/models/FilePosixProperties.java @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.file.share.models; + +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.HttpHeaders; +import com.azure.storage.file.share.implementation.accesshelpers.FilePosixPropertiesHelper; + +/** + * NFS properties. + * Note that these properties only apply to files or directories in premium NFS file accounts. + */ +public final class FilePosixProperties { + + private String fileMode; + private String owner; + private String group; + private final NfsFileType fileType; + private final Long linkCount; + + /** + * Default constructor + */ + public FilePosixProperties() { + // Non user-settable properties + fileType = null; + linkCount = null; + } + + /** + * Gets the file mode permissions. + * + * @return the file mode permissions. + */ + public String getFileMode() { + return fileMode; + } + + /** + * Gets the owner user identifier (UID). + * + * @return the owner user identifier (UID). + */ + public String getOwner() { + return owner; + } + + /** + * Gets the owner group identifier (GID). + * + * @return the owner group identifier (GID). + */ + public String getGroup() { + return group; + } + + /** + * Gets the file type. + * + * @return the file type. + */ + public NfsFileType getFileType() { + return fileType; + } + + /** + * Gets the link count of the file or directory. + * + * @return the link count of the file or directory. + */ + public Long getLinkCount() { + return linkCount; + } + + /** + * Optional. Version 2025-05-05 and newer. + * The mode permissions to be set on the file or directory. This can be in either symbolic or octal notation. + * + *

        For more information, see this + * Wikipedia page.

        + * + * @param fileMode The mode permissions to be set on the file or directory. + * @return the FilePosixProperties object itself. + */ + public FilePosixProperties setFileMode(String fileMode) { + this.fileMode = fileMode; + return this; + } + + /** + * Optional. The owner user identifier (UID) to be set on the file or directory. The default value is 0 (root). + * + * @param owner the owner user identifier (UID) to set. + * @return the FilePosixProperties object itself. + */ + public FilePosixProperties setOwner(String owner) { + this.owner = owner; + return this; + } + + /** + * Optional. The owner group identifier (GID) to be set on the file or directory. The default value is 0 (root group). + * + * @param group the owner group identifier (GID) to set. + * @return the FilePosixProperties object itself. + */ + public FilePosixProperties setGroup(String group) { + this.group = group; + return this; + } + + /** + * Creates a new FilePosixProperties object from HttpHeaders. + * + * @param httpHeaders The headers to construct FilePosixProperties from. + */ + FilePosixProperties(HttpHeaders httpHeaders) { + String tempFileMode = httpHeaders.getValue(HttpHeaderName.fromString("x-ms-mode")); + String tempOwner = httpHeaders.getValue(HttpHeaderName.fromString("x-ms-owner")); + String tempGroup = httpHeaders.getValue(HttpHeaderName.fromString("x-ms-group")); + String tempFileType = httpHeaders.getValue(HttpHeaderName.fromString("x-ms-file-file-type")); + String tempLinkCount = httpHeaders.getValue(HttpHeaderName.fromString("x-ms-link-count")); + + Long linkCountValue; + try { + linkCountValue = tempLinkCount == null ? null : Long.valueOf(tempLinkCount); + } catch (NumberFormatException e) { + throw new IllegalArgumentException( + "Unable to convert value of header x-ms-link-count \"" + tempLinkCount + "\" to Long. ", e); + } + + this.fileMode = tempFileMode; + this.owner = tempOwner; + this.group = tempGroup; + this.fileType = NfsFileType.fromString(tempFileType); + this.linkCount = linkCountValue; + } + + static { + FilePosixPropertiesHelper.setAccessor(FilePosixProperties::new); + } +} diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/models/ModeCopyMode.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/models/ModeCopyMode.java new file mode 100644 index 000000000000..e9908d9bdc1b --- /dev/null +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/models/ModeCopyMode.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. + +package com.azure.storage.file.share.models; + +/** + * Defines values for ModeCopyMode. + */ +public enum ModeCopyMode { + /** + * Enum value source. + */ + SOURCE("source"), + + /** + * Enum value override. + */ + OVERRIDE("override"); + + /** + * The actual serialized value for a ModeCopyMode instance. + */ + private final String value; + + ModeCopyMode(String value) { + this.value = value; + } + + /** + * Parses a serialized value to a ModeCopyMode instance. + * + * @param value the serialized value to parse. + * @return the parsed ModeCopyMode object, or null if unable to parse. + */ + public static ModeCopyMode fromString(String value) { + if (value == null) { + return null; + } + ModeCopyMode[] items = ModeCopyMode.values(); + for (ModeCopyMode item : items) { + if (item.toString().equalsIgnoreCase(value)) { + return item; + } + } + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return this.value; + } +} diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/models/NfsFileType.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/models/NfsFileType.java new file mode 100644 index 000000000000..743de246f477 --- /dev/null +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/models/NfsFileType.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. + +package com.azure.storage.file.share.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for NfsFileType. + */ +public final class NfsFileType extends ExpandableStringEnum { + /** + * Static value Regular for NfsFileType. + */ + public static final NfsFileType REGULAR = fromString("Regular"); + + /** + * Static value Directory for NfsFileType. + */ + public static final NfsFileType DIRECTORY = fromString("Directory"); + + /** + * Static value SymLink for NfsFileType. + */ + public static final NfsFileType SYM_LINK = fromString("SymLink"); + + /** + * Creates a new instance of NfsFileType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public NfsFileType() { + } + + /** + * Creates or finds a NfsFileType from its string representation. + * + * @param name a name to look for. + * @return the corresponding NfsFileType. + */ + public static NfsFileType fromString(String name) { + return fromString(name, NfsFileType.class); + } + + /** + * Gets known NfsFileType values. + * + * @return known NfsFileType values. + */ + public static Collection values() { + return values(NfsFileType.class); + } +} diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/models/OwnerCopyMode.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/models/OwnerCopyMode.java new file mode 100644 index 000000000000..657a96030d45 --- /dev/null +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/models/OwnerCopyMode.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. + +package com.azure.storage.file.share.models; + +/** + * Defines values for OwnerCopyMode. + */ +public enum OwnerCopyMode { + /** + * Enum value source. + */ + SOURCE("source"), + + /** + * Enum value override. + */ + OVERRIDE("override"); + + /** + * The actual serialized value for a OwnerCopyMode instance. + */ + private final String value; + + OwnerCopyMode(String value) { + this.value = value; + } + + /** + * Parses a serialized value to a OwnerCopyMode instance. + * + * @param value the serialized value to parse. + * @return the parsed OwnerCopyMode object, or null if unable to parse. + */ + public static OwnerCopyMode fromString(String value) { + if (value == null) { + return null; + } + OwnerCopyMode[] items = OwnerCopyMode.values(); + for (OwnerCopyMode item : items) { + if (item.toString().equalsIgnoreCase(value)) { + return item; + } + } + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return this.value; + } +} diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/models/ShareDirectoryInfo.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/models/ShareDirectoryInfo.java index 360c61665d61..c6fc93183cce 100644 --- a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/models/ShareDirectoryInfo.java +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/models/ShareDirectoryInfo.java @@ -5,6 +5,7 @@ import com.azure.core.annotation.Immutable; import com.azure.storage.file.share.FileSmbProperties; +import com.azure.storage.file.share.implementation.accesshelpers.ShareDirectoryInfoHelper; import java.time.OffsetDateTime; @@ -16,6 +17,7 @@ public final class ShareDirectoryInfo { private final String eTag; private final OffsetDateTime lastModified; private final FileSmbProperties smbProperties; + private final FilePosixProperties posixProperties; /** * Creates an instance of information about a specific Directory. @@ -28,6 +30,20 @@ public ShareDirectoryInfo(String eTag, OffsetDateTime lastModified, FileSmbPrope this.eTag = eTag; this.lastModified = lastModified; this.smbProperties = smbProperties; + this.posixProperties = null; + } + + //Internal constructor to support FilePosixProperties class. + private ShareDirectoryInfo(String eTag, OffsetDateTime lastModified, FileSmbProperties smbProperties, + FilePosixProperties posixProperties) { + this.eTag = eTag; + this.lastModified = lastModified; + this.smbProperties = smbProperties; + this.posixProperties = posixProperties; + } + + static { + ShareDirectoryInfoHelper.setAccessor(ShareDirectoryInfo::new); } /** @@ -56,4 +72,14 @@ public OffsetDateTime getLastModified() { public FileSmbProperties getSmbProperties() { return smbProperties; } + + /** + * Gets the directory's NFS properties. + * Only applicable to directories in a NFS share. + * + * @return The NFS Properties of the directory. + */ + public FilePosixProperties getPosixProperties() { + return posixProperties; + } } diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/models/ShareDirectoryProperties.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/models/ShareDirectoryProperties.java index 7ad2c823fe03..b70915b26937 100644 --- a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/models/ShareDirectoryProperties.java +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/models/ShareDirectoryProperties.java @@ -5,6 +5,7 @@ import com.azure.core.annotation.Immutable; import com.azure.storage.file.share.FileSmbProperties; +import com.azure.storage.file.share.implementation.accesshelpers.ShareDirectoryPropertiesHelper; import java.time.OffsetDateTime; import java.util.Map; @@ -19,6 +20,7 @@ public final class ShareDirectoryProperties { private final OffsetDateTime lastModified; private final boolean isServerEncrypted; private final FileSmbProperties smbProperties; + private final FilePosixProperties posixProperties; /** * Creates an instance of properties information about a specific Directory. @@ -37,6 +39,22 @@ public ShareDirectoryProperties(Map metadata, String eTag, Offse this.lastModified = lastModified; this.isServerEncrypted = isServerEncrypted; this.smbProperties = smbProperties; + this.posixProperties = null; + } + + //Internal constructor to support FilePosixProperties class. + private ShareDirectoryProperties(Map metadata, String eTag, OffsetDateTime lastModified, + boolean isServerEncrypted, FileSmbProperties smbProperties, FilePosixProperties posixProperties) { + this.metadata = metadata; + this.eTag = eTag; + this.lastModified = lastModified; + this.isServerEncrypted = isServerEncrypted; + this.smbProperties = smbProperties; + this.posixProperties = posixProperties; + } + + static { + ShareDirectoryPropertiesHelper.setAccessor(ShareDirectoryProperties::new); } /** @@ -85,4 +103,14 @@ public boolean isServerEncrypted() { public FileSmbProperties getSmbProperties() { return smbProperties; } + + /** + * Gets the directory's NFS properties. + * Only applicable to directories in a NFS share. + * + * @return The NFS Properties of the directory. + */ + public FilePosixProperties getPosixProperties() { + return posixProperties; + } } diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/models/ShareFileInfo.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/models/ShareFileInfo.java index 4fdf8bcefe25..18e26395b25c 100644 --- a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/models/ShareFileInfo.java +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/models/ShareFileInfo.java @@ -5,6 +5,7 @@ import com.azure.core.annotation.Immutable; import com.azure.storage.file.share.FileSmbProperties; +import com.azure.storage.file.share.implementation.accesshelpers.ShareFileInfoHelper; import java.time.OffsetDateTime; @@ -17,6 +18,7 @@ public final class ShareFileInfo { private final OffsetDateTime lastModified; private final Boolean isServerEncrypted; private final FileSmbProperties smbProperties; + private final FilePosixProperties posixProperties; /** * Creates an instance of information about a specific Directory. @@ -33,6 +35,21 @@ public ShareFileInfo(String eTag, OffsetDateTime lastModified, Boolean isServerE this.lastModified = lastModified; this.isServerEncrypted = isServerEncrypted; this.smbProperties = smbProperties; + this.posixProperties = null; + } + + //Internal constructor to support FilePosixProperties class. + private ShareFileInfo(String eTag, OffsetDateTime lastModified, Boolean isServerEncrypted, + FileSmbProperties smbProperties, FilePosixProperties posixProperties) { + this.eTag = eTag; + this.lastModified = lastModified; + this.isServerEncrypted = isServerEncrypted; + this.smbProperties = smbProperties; + this.posixProperties = posixProperties; + } + + static { + ShareFileInfoHelper.setAccessor(ShareFileInfo::new); } /** @@ -72,4 +89,14 @@ public Boolean isServerEncrypted() { public FileSmbProperties getSmbProperties() { return smbProperties; } + + /** + * Gets the file's NFS properties. + * Only applicable to files in a NFS share. + * + * @return The NFS Properties of the file. + */ + public FilePosixProperties getPosixProperties() { + return posixProperties; + } } diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/models/ShareFileProperties.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/models/ShareFileProperties.java index 100074265774..740d480e88b3 100644 --- a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/models/ShareFileProperties.java +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/models/ShareFileProperties.java @@ -6,6 +6,7 @@ import com.azure.core.annotation.Immutable; import com.azure.core.util.CoreUtils; import com.azure.storage.file.share.FileSmbProperties; +import com.azure.storage.file.share.implementation.accesshelpers.ShareFilePropertiesHelper; import java.time.OffsetDateTime; import java.util.Map; @@ -36,6 +37,7 @@ public final class ShareFileProperties { private final CopyStatusType copyStatus; private final Boolean isServerEncrypted; private final FileSmbProperties smbProperties; + private final FilePosixProperties posixProperties; /** * Creates an instance of property information about a specific File. @@ -151,6 +153,42 @@ public ShareFileProperties(String eTag, OffsetDateTime lastModified, Map metadata, String fileType, + Long contentLength, String contentType, byte[] contentMd5, String contentEncoding, String cacheControl, + String contentDisposition, LeaseStatusType leaseStatusType, LeaseStateType leaseStateType, + LeaseDurationType leaseDurationType, OffsetDateTime copyCompletionTime, String copyStatusDescription, + String copyId, String copyProgress, String copySource, CopyStatusType copyStatus, Boolean isServerEncrypted, + FileSmbProperties smbProperties, FilePosixProperties posixProperties) { + this.eTag = eTag; + this.lastModified = lastModified; + this.metadata = metadata; + this.fileType = fileType; + this.contentLength = contentLength; + this.contentType = contentType; + this.contentMd5 = CoreUtils.clone(contentMd5); + this.contentEncoding = contentEncoding; + this.cacheControl = cacheControl; + this.contentDisposition = contentDisposition; + this.leaseStatus = leaseStatusType; + this.leaseState = leaseStateType; + this.leaseDuration = leaseDurationType; + this.copyCompletionTime = copyCompletionTime; + this.copyStatusDescription = copyStatusDescription; + this.copyId = copyId; + this.copyProgress = copyProgress; + this.copySource = copySource; + this.copyStatus = copyStatus; + this.isServerEncrypted = isServerEncrypted; + this.smbProperties = smbProperties; + this.posixProperties = posixProperties; + } + + static { + ShareFilePropertiesHelper.setAccessor(ShareFileProperties::new); } /** @@ -350,4 +388,14 @@ public Boolean isServerEncrypted() { public FileSmbProperties getSmbProperties() { return smbProperties; } + + /** + * Gets the file's NFS properties. + * Only applicable to files in a NFS share. + * + * @return The NFS Properties of the file. + */ + public FilePosixProperties getPosixProperties() { + return posixProperties; + } } diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/options/ShareDirectoryCreateOptions.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/options/ShareDirectoryCreateOptions.java index 13f784fe23de..86163d82a656 100644 --- a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/options/ShareDirectoryCreateOptions.java +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/options/ShareDirectoryCreateOptions.java @@ -6,6 +6,7 @@ import com.azure.core.annotation.Fluent; import com.azure.storage.file.share.FileSmbProperties; import com.azure.storage.file.share.models.FilePermissionFormat; +import com.azure.storage.file.share.models.FilePosixProperties; import java.util.Map; @@ -18,6 +19,7 @@ public class ShareDirectoryCreateOptions { private String filePermission; private FilePermissionFormat filePermissionFormat; private Map metadata; + private FilePosixProperties posixProperties; /** * Creates a new instance of {@link ShareDirectoryCreateOptions}. @@ -109,4 +111,26 @@ public ShareDirectoryCreateOptions setFilePermissionFormat(FilePermissionFormat this.filePermissionFormat = filePermissionFormat; return this; } + + /** + * Optional properties to set on NFS directories. + * Note that this property is only applicable to directories created in NFS shares. + * + * @return {@link FilePosixProperties} + */ + public FilePosixProperties getPosixProperties() { + return posixProperties; + } + + /** + * Optional properties to set on NFS directories. + * Note that this property is only applicable to directories created in NFS shares. + * + * @param posixProperties {@link FilePosixProperties} + * @return The updated options. + */ + public ShareDirectoryCreateOptions setPosixProperties(FilePosixProperties posixProperties) { + this.posixProperties = posixProperties; + return this; + } } diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/options/ShareDirectorySetPropertiesOptions.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/options/ShareDirectorySetPropertiesOptions.java index d3d5eac2b25d..762c02dce902 100644 --- a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/options/ShareDirectorySetPropertiesOptions.java +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/options/ShareDirectorySetPropertiesOptions.java @@ -4,6 +4,7 @@ import com.azure.core.annotation.Fluent; import com.azure.storage.file.share.FileSmbProperties; +import com.azure.storage.file.share.models.FilePosixProperties; import com.azure.storage.file.share.models.ShareFilePermission; /** @@ -13,6 +14,7 @@ public class ShareDirectorySetPropertiesOptions { private FileSmbProperties smbProperties; private ShareFilePermission filePermissions; + private FilePosixProperties posixProperties; /** * Creates a new instance of {@link ShareDirectorySetPropertiesOptions}. @@ -64,4 +66,26 @@ public ShareDirectorySetPropertiesOptions setFilePermissions(ShareFilePermission return this; } + /** + * Optional properties to set on NFS directories. + * Note that this property is only applicable to directories created in NFS shares. + * + * @return {@link FilePosixProperties} + */ + public FilePosixProperties getPosixProperties() { + return posixProperties; + } + + /** + * Optional properties to set on NFS directories. + * Note that this property is only applicable to directories created in NFS shares. + * + * @param posixProperties {@link FilePosixProperties} + * @return The updated options. + */ + public ShareDirectorySetPropertiesOptions setPosixProperties(FilePosixProperties posixProperties) { + this.posixProperties = posixProperties; + return this; + } + } diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/options/ShareFileCopyOptions.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/options/ShareFileCopyOptions.java index 0d581ee571c8..2ec3d6c4410b 100644 --- a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/options/ShareFileCopyOptions.java +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/options/ShareFileCopyOptions.java @@ -5,8 +5,11 @@ import com.azure.core.annotation.Fluent; import com.azure.storage.file.share.FileSmbProperties; +import com.azure.storage.file.share.models.ModeCopyMode; +import com.azure.storage.file.share.models.OwnerCopyMode; import com.azure.storage.file.share.models.CopyableFileSmbPropertiesList; import com.azure.storage.file.share.models.FilePermissionFormat; +import com.azure.storage.file.share.models.FilePosixProperties; import com.azure.storage.file.share.models.PermissionCopyModeType; import com.azure.storage.file.share.models.ShareRequestConditions; @@ -26,6 +29,9 @@ public final class ShareFileCopyOptions { private Map metadata; private ShareRequestConditions destinationRequestConditions; private CopyableFileSmbPropertiesList smbPropertiesToCopy; + private FilePosixProperties posixProperties; + private ModeCopyMode modeCopyMode; + private OwnerCopyMode ownerCopyMode; /** * Creates a new instance of {@link ShareFileCopyOptions}. @@ -229,4 +235,74 @@ public ShareFileCopyOptions setFilePermissionFormat(FilePermissionFormat filePer this.filePermissionFormat = filePermissionFormat; return this; } + + /** + * Optional properties to set on NFS files. + * Note that this property is only applicable to files created in NFS shares. + * + * @return {@link FilePosixProperties} + */ + public FilePosixProperties getPosixProperties() { + return posixProperties; + } + + /** + * Optional properties to set on NFS files. + * Note that this property is only applicable to files created in NFS shares. + * + * @param posixProperties {@link FilePosixProperties} + * @return The updated options. + */ + public ShareFileCopyOptions setPosixProperties(FilePosixProperties posixProperties) { + this.posixProperties = posixProperties; + return this; + } + + /** + * Optional properties to set on NFS files. + * Note that this property is only applicable to files created in NFS shares. + * If not populated, the destination file will have the default File Mode. + * + * @return The destination file's FileMode. + */ + public ModeCopyMode getModeCopyMode() { + return modeCopyMode; + } + + /** + * Optional properties to set on NFS files. + * Note that this property is only applicable to files created in NFS shares. + * If not populated, the destination file will have the default File Mode. + * + * @param modeCopyMode The destination file's FileMode. + * @return The updated options. + */ + public ShareFileCopyOptions setModeCopyMode(ModeCopyMode modeCopyMode) { + this.modeCopyMode = modeCopyMode; + return this; + } + + /** + * Optional properties to set on NFS files. + * Note that this property is only applicable to files created in NFS shares. + * If not populated,the destination file will have the default Owner and Group. + * + * @return The destination file's Owner and Group. + */ + public OwnerCopyMode getOwnerCopyMode() { + return ownerCopyMode; + } + + /** + * Optional properties to set on NFS files. + * Note that this property is only applicable to files created in NFS shares. + * If not populated,the destination file will have the default Owner and Group. + * + * @param ownerCopyMode The destination file's Owner and Group. + * @return The updated options. + */ + public ShareFileCopyOptions setOwnerCopyMode(OwnerCopyMode ownerCopyMode) { + this.ownerCopyMode = ownerCopyMode; + return this; + } } diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/options/ShareFileCreateHardLinkOptions.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/options/ShareFileCreateHardLinkOptions.java new file mode 100644 index 000000000000..76de90c30261 --- /dev/null +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/options/ShareFileCreateHardLinkOptions.java @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.file.share.options; + +import com.azure.storage.file.share.models.ShareRequestConditions; + +/** + * Options that may be passed when creating a hard link for a file. + */ +public final class ShareFileCreateHardLinkOptions { + private final String targetFile; + private ShareRequestConditions requestConditions; + + /** + * Creates a new instance of {@link ShareFileCreateHardLinkOptions}. + * @param targetFile Path of the file to create the hard link to, not including the share. For example, + * {@code targetDirectory/targetSubDirectory/.../targetFile} + */ + public ShareFileCreateHardLinkOptions(String targetFile) { + this.targetFile = targetFile; + } + + /** + * Gets the path of the target file to create the hard link to, not including the share. + * + * @return the path of the target file to create the hard link to, not including the share. For example, + * {@code targetDirectory/targetSubDirectory/.../targetFile} + */ + public String getTargetFile() { + return targetFile; + } + + /** + * Optional {@link ShareRequestConditions} to add conditions on creating the hard link. + * + * @return the {@link ShareRequestConditions} for the creation of the hard link. + */ + public ShareRequestConditions getRequestConditions() { + return requestConditions; + } + + /** + * Optional {@link ShareRequestConditions} to add conditions on creating the hard link. + * + * @param requestConditions {@link ShareRequestConditions} + * @return the updated options. + */ + public ShareFileCreateHardLinkOptions setRequestConditions(ShareRequestConditions requestConditions) { + this.requestConditions = requestConditions; + return this; + } +} diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/options/ShareFileCreateOptions.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/options/ShareFileCreateOptions.java index bddc32347af4..89ad4f2298e3 100644 --- a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/options/ShareFileCreateOptions.java +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/options/ShareFileCreateOptions.java @@ -6,6 +6,7 @@ import com.azure.core.annotation.Fluent; import com.azure.storage.file.share.FileSmbProperties; import com.azure.storage.file.share.models.FilePermissionFormat; +import com.azure.storage.file.share.models.FilePosixProperties; import com.azure.storage.file.share.models.ShareFileHttpHeaders; import com.azure.storage.file.share.models.ShareRequestConditions; import java.util.Map; @@ -23,6 +24,7 @@ public class ShareFileCreateOptions { private FilePermissionFormat filePermissionFormat; private Map metadata; private ShareRequestConditions requestConditions; + private FilePosixProperties posixProperties; /** * Creates a new instance of {@link ShareFileCreateOptions}. @@ -166,4 +168,26 @@ public ShareFileCreateOptions setFilePermissionFormat(FilePermissionFormat fileP this.filePermissionFormat = filePermissionFormat; return this; } + + /** + * Optional properties to set on NFS files. + * Note that this property is only applicable to files created in NFS shares. + * + * @return {@link FilePosixProperties} + */ + public FilePosixProperties getPosixProperties() { + return posixProperties; + } + + /** + * Optional properties to set on NFS files. + * Note that this property is only applicable to files created in NFS shares. + * + * @param posixProperties {@link FilePosixProperties} + * @return The updated options. + */ + public ShareFileCreateOptions setPosixProperties(FilePosixProperties posixProperties) { + this.posixProperties = posixProperties; + return this; + } } diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/options/ShareFileSetPropertiesOptions.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/options/ShareFileSetPropertiesOptions.java index 463bdc5588c9..d94f791b8ab0 100644 --- a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/options/ShareFileSetPropertiesOptions.java +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/options/ShareFileSetPropertiesOptions.java @@ -4,6 +4,7 @@ import com.azure.core.annotation.Fluent; import com.azure.storage.file.share.FileSmbProperties; +import com.azure.storage.file.share.models.FilePosixProperties; import com.azure.storage.file.share.models.ShareFileHttpHeaders; import com.azure.storage.file.share.models.ShareFilePermission; import com.azure.storage.file.share.models.ShareRequestConditions; @@ -18,6 +19,7 @@ public class ShareFileSetPropertiesOptions { private FileSmbProperties smbProperties; private ShareFilePermission filePermissions; private ShareRequestConditions requestConditions; + private FilePosixProperties posixProperties; /** * Creates a new instance of {@link ShareFileSetPropertiesOptions}. @@ -120,4 +122,26 @@ public ShareFileSetPropertiesOptions setRequestConditions(ShareRequestConditions this.requestConditions = requestConditions; return this; } + + /** + * Optional properties to set on NFS files. + * Note that this property is only applicable to files created in NFS shares. + * + * @return {@link FilePosixProperties} + */ + public FilePosixProperties getPosixProperties() { + return posixProperties; + } + + /** + * Optional properties to set on NFS files. + * Note that this property is only applicable to files created in NFS shares. + * + * @param posixProperties {@link FilePosixProperties} + * @return The updated options. + */ + public ShareFileSetPropertiesOptions setPosixProperties(FilePosixProperties posixProperties) { + this.posixProperties = posixProperties; + return this; + } } diff --git a/sdk/storage/azure-storage-file-share/src/samples/README.md b/sdk/storage/azure-storage-file-share/src/samples/README.md index b6a7685d818d..ee2991f11f88 100644 --- a/sdk/storage/azure-storage-file-share/src/samples/README.md +++ b/sdk/storage/azure-storage-file-share/src/samples/README.md @@ -58,4 +58,4 @@ This project welcomes contributions and suggestions. Find [more contributing][SD [SDK_README_GETTING_STARTDED]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/storage/azure-storage-file-share/README.md#getting-started [SDK_README_TROUBLESHOOTING]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/storage/azure-storage-file-share/README.md#troubleshooting -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fstorage%2Fazure-storage-file-share%2Fsrc%2Fsamples%2FREADME.png) + diff --git a/sdk/storage/azure-storage-file-share/src/samples/java/com/azure/storage/file/share/ShareFileAsyncJavaDocCodeSamples.java b/sdk/storage/azure-storage-file-share/src/samples/java/com/azure/storage/file/share/ShareFileAsyncJavaDocCodeSamples.java index 98335e1efba5..1afbfd4980b1 100644 --- a/sdk/storage/azure-storage-file-share/src/samples/java/com/azure/storage/file/share/ShareFileAsyncJavaDocCodeSamples.java +++ b/sdk/storage/azure-storage-file-share/src/samples/java/com/azure/storage/file/share/ShareFileAsyncJavaDocCodeSamples.java @@ -20,6 +20,7 @@ import com.azure.storage.file.share.models.ShareFileUploadRangeOptions; import com.azure.storage.file.share.models.ShareRequestConditions; import com.azure.storage.file.share.options.ShareFileCopyOptions; +import com.azure.storage.file.share.options.ShareFileCreateHardLinkOptions; import com.azure.storage.file.share.options.ShareFileCreateOptions; import com.azure.storage.file.share.options.ShareFileDownloadOptions; import com.azure.storage.file.share.options.ShareFileListRangesDiffOptions; @@ -1268,4 +1269,25 @@ public void deleteFileIfExistsCodeSnippets() { }); // END: com.azure.storage.file.share.ShareFileAsyncClient.deleteIfExistsWithResponse#ShareRequestConditions } + + /** + * Generates a code sample for using {@link ShareFileAsyncClient#createHardLink(String)}, + * {@link ShareFileAsyncClient#createHardLinkWithResponse(ShareFileCreateHardLinkOptions)} + */ + public void createHardLink() { + ShareFileAsyncClient sourceClient = createAsyncClientWithSASToken(); + ShareFileAsyncClient hardLinkClient = createAsyncClientWithSASToken(); + // BEGIN: com.azure.storage.file.share.ShareFileAsyncClient.createHardLink#String + hardLinkClient.createHardLink(sourceClient.getFilePath()) + .subscribe(result -> System.out.printf("Link count is is %s.", + result.getPosixProperties().getLinkCount())); + // END: com.azure.storage.file.share.ShareFileAsyncClient.createHardLink#String + + // BEGIN: com.azure.storage.file.share.ShareFileAsyncClient.createHardLink#ShareFileCreateHardLinkOptions + ShareFileCreateHardLinkOptions options = new ShareFileCreateHardLinkOptions(sourceClient.getFilePath()); + hardLinkClient.createHardLinkWithResponse(options) + .subscribe(result -> System.out.printf("Link count is is %s.", + result.getValue().getPosixProperties().getLinkCount())); + // END: com.azure.storage.file.share.ShareFileAsyncClient.createHardLink#ShareFileCreateHardLinkOptions + } } diff --git a/sdk/storage/azure-storage-file-share/src/samples/java/com/azure/storage/file/share/ShareFileJavaDocCodeSamples.java b/sdk/storage/azure-storage-file-share/src/samples/java/com/azure/storage/file/share/ShareFileJavaDocCodeSamples.java index 6098fcfa37e4..bd5f6889ecd4 100644 --- a/sdk/storage/azure-storage-file-share/src/samples/java/com/azure/storage/file/share/ShareFileJavaDocCodeSamples.java +++ b/sdk/storage/azure-storage-file-share/src/samples/java/com/azure/storage/file/share/ShareFileJavaDocCodeSamples.java @@ -28,6 +28,7 @@ import com.azure.storage.file.share.models.ShareFileUploadRangeOptions; import com.azure.storage.file.share.models.ShareRequestConditions; import com.azure.storage.file.share.options.ShareFileCopyOptions; +import com.azure.storage.file.share.options.ShareFileCreateHardLinkOptions; import com.azure.storage.file.share.options.ShareFileCreateOptions; import com.azure.storage.file.share.options.ShareFileDownloadOptions; import com.azure.storage.file.share.options.ShareFileListRangesDiffOptions; @@ -1249,4 +1250,25 @@ public void deleteFileIfExistsCodeSnippets() { } // END: com.azure.storage.file.share.ShareFileClient.deleteIfExistsWithResponse#ShareRequestConditions-duration-context } + + /** + * Generates a code sample for using {@link ShareFileClient#createHardLink(String)}, + * {@link ShareFileClient#createHardLinkWithResponse(ShareFileCreateHardLinkOptions, Duration, Context)} + */ + public void createHardLink() { + ShareFileClient sourceClient = createClientWithSASToken(); + ShareFileClient hardLinkClient = createClientWithSASToken(); + // BEGIN: com.azure.storage.file.share.ShareFileClient.createHardLink#String + ShareFileInfo response = hardLinkClient.createHardLink(sourceClient.getFilePath()); + + System.out.printf("Link count is is %s.", response.getPosixProperties().getLinkCount()); + // END: com.azure.storage.file.share.ShareFileClient.createHardLink#String + + // BEGIN: com.azure.storage.file.share.ShareFileClient.createHardLink#ShareFileCreateHardLinkOptions-Duration-Context + ShareFileCreateHardLinkOptions options = new ShareFileCreateHardLinkOptions(sourceClient.getFilePath()); + ShareFileInfo response2 = hardLinkClient.createHardLinkWithResponse(options, null, null).getValue(); + + System.out.printf("Link count is is %s.", response2.getPosixProperties().getLinkCount()); + // END: com.azure.storage.file.share.ShareFileClient.createHardLink#ShareFileCreateHardLinkOptions-Duration-Context + } } 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 f3cc49ec2ff7..28ebb3097cb2 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 @@ -11,8 +11,10 @@ import com.azure.storage.common.implementation.Constants; import com.azure.storage.common.policy.RequestRetryOptions; import com.azure.storage.common.test.shared.extensions.RequiredServiceVersion; +import com.azure.storage.file.share.models.NfsFileType; import com.azure.storage.file.share.models.CloseHandlesInfo; import com.azure.storage.file.share.models.FilePermissionFormat; +import com.azure.storage.file.share.models.FilePosixProperties; import com.azure.storage.file.share.models.HandleItem; import com.azure.storage.file.share.models.NtfsFileAttributes; import com.azure.storage.file.share.models.ShareAudience; @@ -1745,4 +1747,70 @@ public void audienceFromString() { ShareDirectoryClient aadDirClient = oAuthServiceClient.getShareClient(shareName).getDirectoryClient(dirName); assertTrue(aadDirClient.exists()); } + + @RequiredServiceVersion(clazz = ShareServiceVersion.class, min = "2025-05-05") + @Test + public void createNFS() { + ShareClient premiumShareClient = getPremiumNFSShareClient(generateShareName()); + + ShareDirectoryClient premiumDirectoryClient = premiumShareClient.getDirectoryClient(generatePathName()); + + ShareDirectoryCreateOptions options = new ShareDirectoryCreateOptions() + .setPosixProperties(new FilePosixProperties().setOwner("345").setGroup("123").setFileMode("7777")); + ShareDirectoryInfo response = premiumDirectoryClient.createWithResponse(options, null, null).getValue(); + + assertEquals(NfsFileType.DIRECTORY, response.getPosixProperties().getFileType()); + assertEquals("345", response.getPosixProperties().getOwner()); + assertEquals("123", response.getPosixProperties().getGroup()); + assertEquals("7777", response.getPosixProperties().getFileMode()); + + FileShareTestHelper.assertSmbPropertiesNull(response.getSmbProperties()); + + //cleanup + premiumShareClient.delete(); + } + + @RequiredServiceVersion(clazz = ShareServiceVersion.class, min = "2025-05-05") + @Test + public void setPropertiesNFS() { + ShareClient premiumShareClient = getPremiumNFSShareClient(generateShareName()); + + ShareDirectoryClient premiumDirectoryClient = premiumShareClient.getDirectoryClient(generatePathName()); + premiumDirectoryClient.create(); + + ShareDirectorySetPropertiesOptions options = new ShareDirectorySetPropertiesOptions() + .setPosixProperties(new FilePosixProperties().setOwner("345").setGroup("123").setFileMode("7777")); + + ShareDirectoryInfo response = premiumDirectoryClient.setPropertiesWithResponse(options, null, null).getValue(); + + assertEquals("345", response.getPosixProperties().getOwner()); + assertEquals("123", response.getPosixProperties().getGroup()); + assertEquals("7777", response.getPosixProperties().getFileMode()); + + FileShareTestHelper.assertSmbPropertiesNull(response.getSmbProperties()); + + //cleanup + premiumShareClient.delete(); + } + + @RequiredServiceVersion(clazz = ShareServiceVersion.class, min = "2025-05-05") + @Test + public void getPropertiesNFS() { + ShareClient premiumShareClient = getPremiumNFSShareClient(generateShareName()); + + ShareDirectoryClient premiumDirectoryClient = premiumShareClient.getDirectoryClient(generatePathName()); + premiumDirectoryClient.create(); + + ShareDirectoryProperties response = premiumDirectoryClient.getPropertiesWithResponse(null, null).getValue(); + + assertEquals(NfsFileType.DIRECTORY, response.getPosixProperties().getFileType()); + assertEquals("0", response.getPosixProperties().getOwner()); + assertEquals("0", response.getPosixProperties().getGroup()); + assertEquals("0755", response.getPosixProperties().getFileMode()); + + FileShareTestHelper.assertSmbPropertiesNull(response.getSmbProperties()); + + //cleanup + premiumShareClient.delete(); + } } diff --git a/sdk/storage/azure-storage-file-share/src/test/java/com/azure/storage/file/share/DirectoryAsyncApiTests.java b/sdk/storage/azure-storage-file-share/src/test/java/com/azure/storage/file/share/DirectoryAsyncApiTests.java index a8b2c05922d5..0c6f6db99370 100644 --- a/sdk/storage/azure-storage-file-share/src/test/java/com/azure/storage/file/share/DirectoryAsyncApiTests.java +++ b/sdk/storage/azure-storage-file-share/src/test/java/com/azure/storage/file/share/DirectoryAsyncApiTests.java @@ -7,7 +7,9 @@ import com.azure.storage.common.StorageSharedKeyCredential; import com.azure.storage.common.implementation.Constants; import com.azure.storage.common.test.shared.extensions.RequiredServiceVersion; +import com.azure.storage.file.share.models.NfsFileType; import com.azure.storage.file.share.models.FilePermissionFormat; +import com.azure.storage.file.share.models.FilePosixProperties; import com.azure.storage.file.share.models.NtfsFileAttributes; import com.azure.storage.file.share.models.ShareAudience; import com.azure.storage.file.share.models.ShareDirectoryInfo; @@ -1054,4 +1056,85 @@ public void audienceFromString() { StepVerifier.create(createDirMono.then(aadDirClient.exists())).expectNext(true).verifyComplete(); } + + @RequiredServiceVersion(clazz = ShareServiceVersion.class, min = "2025-05-05") + @Test + public void createNFS() { + ShareDirectoryCreateOptions options = new ShareDirectoryCreateOptions() + .setPosixProperties(new FilePosixProperties().setOwner("345").setGroup("123").setFileMode("7777")); + + String shareName = generateShareName(); + Mono> create + = getPremiumNFSShareAsyncClient(shareName).flatMap(premiumShareClient -> { + ShareDirectoryAsyncClient premiumDirectoryClient + = premiumShareClient.getDirectoryClient(generatePathName()); + return premiumDirectoryClient.createWithResponse(options); + }); + + StepVerifier.create(create).assertNext(r -> { + ShareDirectoryInfo response = r.getValue(); + assertEquals(NfsFileType.DIRECTORY, response.getPosixProperties().getFileType()); + assertEquals("345", response.getPosixProperties().getOwner()); + assertEquals("123", response.getPosixProperties().getGroup()); + assertEquals("7777", response.getPosixProperties().getFileMode()); + + FileShareTestHelper.assertSmbPropertiesNull(response.getSmbProperties()); + }).verifyComplete(); + + //cleanup + premiumFileServiceAsyncClient.getShareAsyncClient(shareName).delete().block(); + } + + @RequiredServiceVersion(clazz = ShareServiceVersion.class, min = "2025-05-05") + @Test + public void setPropertiesNFS() { + ShareDirectorySetPropertiesOptions options = new ShareDirectorySetPropertiesOptions() + .setPosixProperties(new FilePosixProperties().setOwner("345").setGroup("123").setFileMode("7777")); + + String shareName = generateShareName(); + Mono> create + = getPremiumNFSShareAsyncClient(shareName).flatMap(premiumShareClient -> { + ShareDirectoryAsyncClient premiumDirectoryClient + = premiumShareClient.getDirectoryClient(generatePathName()); + return premiumDirectoryClient.create().then(premiumDirectoryClient.setPropertiesWithResponse(options)); + }); + + StepVerifier.create(create).assertNext(r -> { + ShareDirectoryInfo response = r.getValue(); + assertEquals("345", response.getPosixProperties().getOwner()); + assertEquals("123", response.getPosixProperties().getGroup()); + assertEquals("7777", response.getPosixProperties().getFileMode()); + + FileShareTestHelper.assertSmbPropertiesNull(response.getSmbProperties()); + }).verifyComplete(); + + //cleanup + premiumFileServiceAsyncClient.getShareAsyncClient(shareName).delete().block(); + } + + @RequiredServiceVersion(clazz = ShareServiceVersion.class, min = "2025-05-05") + @Test + public void getPropertiesNFS() { + String shareName = generateShareName(); + Mono> create + = getPremiumNFSShareAsyncClient(shareName).flatMap(premiumShareClient -> { + ShareDirectoryAsyncClient premiumDirectoryClient + = premiumShareClient.getDirectoryClient(generatePathName()); + return premiumDirectoryClient.create().then(premiumDirectoryClient.getPropertiesWithResponse()); + }); + + StepVerifier.create(create).assertNext(r -> { + ShareDirectoryProperties response = r.getValue(); + + assertEquals(NfsFileType.DIRECTORY, response.getPosixProperties().getFileType()); + assertEquals("0", response.getPosixProperties().getOwner()); + assertEquals("0", response.getPosixProperties().getGroup()); + assertEquals("0755", response.getPosixProperties().getFileMode()); + + FileShareTestHelper.assertSmbPropertiesNull(response.getSmbProperties()); + }).verifyComplete(); + + //cleanup + premiumFileServiceAsyncClient.getShareAsyncClient(shareName).delete().block(); + } } diff --git a/sdk/storage/azure-storage-file-share/src/test/java/com/azure/storage/file/share/FileApiTests.java b/sdk/storage/azure-storage-file-share/src/test/java/com/azure/storage/file/share/FileApiTests.java index 931442c3ac94..f4fdc99e58fa 100644 --- a/sdk/storage/azure-storage-file-share/src/test/java/com/azure/storage/file/share/FileApiTests.java +++ b/sdk/storage/azure-storage-file-share/src/test/java/com/azure/storage/file/share/FileApiTests.java @@ -22,15 +22,19 @@ import com.azure.storage.common.test.shared.policy.MockPartialResponsePolicy; import com.azure.storage.common.test.shared.policy.MockRetryRangeResponsePolicy; import com.azure.storage.common.test.shared.policy.TransientFailureInjectingHttpPipelinePolicy; +import com.azure.storage.file.share.models.ModeCopyMode; +import com.azure.storage.file.share.models.NfsFileType; import com.azure.storage.file.share.models.ClearRange; import com.azure.storage.file.share.models.CloseHandlesInfo; import com.azure.storage.file.share.models.CopyableFileSmbPropertiesList; import com.azure.storage.file.share.models.DownloadRetryOptions; import com.azure.storage.file.share.models.FileLastWrittenMode; import com.azure.storage.file.share.models.FilePermissionFormat; +import com.azure.storage.file.share.models.FilePosixProperties; import com.azure.storage.file.share.models.FileRange; import com.azure.storage.file.share.models.HandleItem; import com.azure.storage.file.share.models.NtfsFileAttributes; +import com.azure.storage.file.share.models.OwnerCopyMode; import com.azure.storage.file.share.models.PermissionCopyModeType; import com.azure.storage.file.share.models.ShareAudience; import com.azure.storage.file.share.models.ShareErrorCode; @@ -55,6 +59,7 @@ import com.azure.storage.file.share.models.ShareStorageException; import com.azure.storage.file.share.models.ShareTokenIntent; import com.azure.storage.file.share.options.ShareFileCopyOptions; +import com.azure.storage.file.share.options.ShareFileCreateHardLinkOptions; import com.azure.storage.file.share.options.ShareFileCreateOptions; import com.azure.storage.file.share.options.ShareFileDownloadOptions; import com.azure.storage.file.share.options.ShareFileListRangesDiffOptions; @@ -63,6 +68,7 @@ import com.azure.storage.file.share.options.ShareFileUploadRangeFromUrlOptions; import com.azure.storage.file.share.sas.ShareFileSasPermission; import com.azure.storage.file.share.sas.ShareServiceSasSignatureValues; +import com.azure.storage.file.share.specialized.ShareLeaseClient; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; @@ -1198,20 +1204,20 @@ public void uploadRangeFromURL(String pathSuffix) { } } - /*@RequiredServiceVersion(clazz = ShareServiceVersion.class, min = "2024-08-04") - @Test - public void uploadRangeFromURLSourceErrorAndStatusCode() { - primaryFileClient.create(1024); - ShareFileClient destinationClient = shareClient.getFileClient(generatePathName()); - destinationClient.create(1024); - - ShareStorageException e = assertThrows(ShareStorageException.class, - () -> destinationClient.uploadRangeFromUrl(5, 0, 0, primaryFileClient.getFileUrl())); - - assertTrue(e.getStatusCode() == 401); - assertTrue(e.getServiceMessage().contains("NoAuthenticationInformation")); - assertTrue(e.getServiceMessage().contains("Server failed to authenticate the request. Please refer to the information in the www-authenticate header.")); - }*/ + // @RequiredServiceVersion(clazz = ShareServiceVersion.class, min = "2024-08-04") + // @Test + // public void uploadRangeFromURLSourceErrorAndStatusCode() { + // primaryFileClient.create(1024); + // ShareFileClient destinationClient = shareClient.getFileClient(generatePathName()); + // destinationClient.create(1024); + // + // ShareStorageException e = assertThrows(ShareStorageException.class, + // () -> destinationClient.uploadRangeFromUrl(5, 0, 0, primaryFileClient.getFileUrl())); + // + // assertTrue(e.getStatusCode() == 401); + // assertTrue(e.getServiceMessage().contains("NoAuthenticationInformation")); + // assertTrue(e.getServiceMessage().contains("Server failed to authenticate the request. Please refer to the information in the www-authenticate header.")); + // } @RequiredServiceVersion(clazz = ShareServiceVersion.class, min = "2021-04-10") @Test @@ -1455,20 +1461,20 @@ public void startCopyError() { FileShareTestHelper.assertExceptionStatusCodeAndMessage(e, 400, ShareErrorCode.INVALID_HEADER_VALUE); } - /*@RequiredServiceVersion(clazz = ShareServiceVersion.class, min = "2024-08-04") - @Test - public void startCopySourceErrorAndStatusCode() { - primaryFileClient.create(1024); - - ShareStorageException e = assertThrows(ShareStorageException.class, () -> { - SyncPoller poller = primaryFileClient.beginCopy("https://error.file.core.windows.net/garbage", testMetadata, null); - poller.waitForCompletion(); - }); - - assertTrue(e.getStatusCode() == 400); - assertTrue(e.getServiceMessage().contains("InvalidUri")); - assertTrue(e.getServiceMessage().contains("The requested URI does not represent any resource on the server.")); - }*/ + // @RequiredServiceVersion(clazz = ShareServiceVersion.class, min = "2024-08-04") + // @Test + // public void startCopySourceErrorAndStatusCode() { + // primaryFileClient.create(1024); + // + // ShareStorageException e = assertThrows(ShareStorageException.class, () -> { + // SyncPoller poller = primaryFileClient.beginCopy("https://error.file.core.windows.net/garbage", testMetadata, null); + // poller.waitForCompletion(); + // }); + // + // assertTrue(e.getStatusCode() == 400); + // assertTrue(e.getServiceMessage().contains("InvalidUri")); + // assertTrue(e.getServiceMessage().contains("The requested URI does not represent any resource on the server.")); + // } @ParameterizedTest @MethodSource("com.azure.storage.file.share.FileShareTestHelper#startCopyArgumentsSupplier") @@ -3046,4 +3052,179 @@ public void listHandlesClientName() { List list = fileClient.listHandles().stream().collect(Collectors.toList()); assertNotNull(list.get(0).getClientName()); } + + @RequiredServiceVersion(clazz = ShareServiceVersion.class, min = "2025-05-05") + @Test + public void createNFS() { + ShareClient premiumShareClient = getPremiumNFSShareClient(generateShareName()); + + ShareFileClient premiumFileClient = premiumShareClient.getFileClient(generatePathName()); + + ShareFileCreateOptions options = new ShareFileCreateOptions(1024) + .setPosixProperties(new FilePosixProperties().setOwner("345").setGroup("123").setFileMode("7777")); + ShareFileInfo response = premiumFileClient.createWithResponse(options, null, null).getValue(); + + assertEquals(NfsFileType.REGULAR, response.getPosixProperties().getFileType()); + assertEquals("345", response.getPosixProperties().getOwner()); + assertEquals("123", response.getPosixProperties().getGroup()); + assertEquals("7777", response.getPosixProperties().getFileMode()); + + FileShareTestHelper.assertSmbPropertiesNull(response.getSmbProperties()); + + //cleanup + premiumShareClient.delete(); + } + + @RequiredServiceVersion(clazz = ShareServiceVersion.class, min = "2025-05-05") + @Test + public void setPropertiesNFS() { + ShareClient premiumShareClient = getPremiumNFSShareClient(generateShareName()); + + ShareFileClient premiumFileClient = premiumShareClient.getFileClient(generatePathName()); + premiumFileClient.create(1024); + + ShareFileSetPropertiesOptions options = new ShareFileSetPropertiesOptions(1024) + .setPosixProperties(new FilePosixProperties().setOwner("345").setGroup("123").setFileMode("7777")); + + ShareFileInfo response = premiumFileClient.setPropertiesWithResponse(options, null, null).getValue(); + + assertEquals("345", response.getPosixProperties().getOwner()); + assertEquals("123", response.getPosixProperties().getGroup()); + assertEquals("7777", response.getPosixProperties().getFileMode()); + assertNotNull(response.getPosixProperties().getLinkCount()); + + FileShareTestHelper.assertSmbPropertiesNull(response.getSmbProperties()); + + //cleanup + premiumShareClient.delete(); + } + + @RequiredServiceVersion(clazz = ShareServiceVersion.class, min = "2025-05-05") + @Test + public void getPropertiesNFS() { + ShareClient premiumShareClient = getPremiumNFSShareClient(generateShareName()); + + ShareFileClient premiumFileClient = premiumShareClient.getFileClient(generatePathName()); + premiumFileClient.create(1024); + + ShareFileProperties response = premiumFileClient.getPropertiesWithResponse(null, null).getValue(); + + assertEquals(NfsFileType.REGULAR, response.getPosixProperties().getFileType()); + assertEquals("0", response.getPosixProperties().getOwner()); + assertEquals("0", response.getPosixProperties().getGroup()); + assertEquals("0664", response.getPosixProperties().getFileMode()); + assertEquals(1, response.getPosixProperties().getLinkCount()); + + FileShareTestHelper.assertSmbPropertiesNull(response.getSmbProperties()); + + //cleanup + premiumShareClient.delete(); + } + + private static Stream beginCopyNFSSupplier() { + return Stream.of(Arguments.of(ModeCopyMode.SOURCE), Arguments.of(ModeCopyMode.OVERRIDE), + Arguments.of((ModeCopyMode) null)); + } + + @RequiredServiceVersion(clazz = ShareServiceVersion.class, min = "2025-05-05") + @ParameterizedTest + @MethodSource("beginCopyNFSSupplier") + public void beginCopyNFS(ModeCopyMode modeAndOwnerCopyMode) { + ShareClient premiumShareClient = getPremiumNFSShareClient(generateShareName()); + + String sourcePath = generatePathName() + "source"; + ShareFileClient premiumFileClientSource = premiumShareClient.getFileClient(sourcePath); + premiumFileClientSource.create(1024); + premiumFileClientSource.uploadRange(DATA.getDefaultInputStream(), DATA.getDefaultDataSizeLong()); + + premiumFileClientSource.setPropertiesWithResponse(new ShareFileSetPropertiesOptions(1024).setPosixProperties( + new FilePosixProperties().setOwner("999").setGroup("888").setFileMode("0111")), null, null); + + String destPath = generatePathName() + "dest"; + ShareFileClient premiumFileClientDest = premiumShareClient.getFileClient(destPath); + premiumFileClientDest.create(1024); + + ShareFileProperties sourceProperties = premiumFileClientSource.getProperties(); + + String owner; + String group; + String mode; + + ShareFileCopyOptions options = new ShareFileCopyOptions().setPosixProperties(new FilePosixProperties()); + + if (modeAndOwnerCopyMode == ModeCopyMode.OVERRIDE) { + owner = "54321"; + group = "12345"; + mode = "7777"; + options.setModeCopyMode(ModeCopyMode.OVERRIDE); + options.setOwnerCopyMode(OwnerCopyMode.OVERRIDE); + options.getPosixProperties().setOwner(owner); + options.getPosixProperties().setGroup(group); + options.getPosixProperties().setFileMode(mode); + } else if (modeAndOwnerCopyMode == ModeCopyMode.SOURCE) { + options.setModeCopyMode(ModeCopyMode.SOURCE); + options.setOwnerCopyMode(OwnerCopyMode.SOURCE); + owner = sourceProperties.getPosixProperties().getOwner(); + group = sourceProperties.getPosixProperties().getGroup(); + mode = sourceProperties.getPosixProperties().getFileMode(); + } else { + owner = "0"; + group = "0"; + mode = "0664"; + } + + SyncPoller poller + = premiumFileClientDest.beginCopy(premiumFileClientSource.getFileUrl(), options, null); + PollResponse pollResponse = poller.poll(); + + ShareFileProperties resultProperties = premiumFileClientDest.getProperties(); + + assertNotNull(pollResponse.getValue().getCopyId()); + assertEquals(pollResponse.getStatus(), LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); + + assertEquals(owner, resultProperties.getPosixProperties().getOwner()); + assertEquals(group, resultProperties.getPosixProperties().getGroup()); + assertEquals(mode, resultProperties.getPosixProperties().getFileMode()); + FileShareTestHelper.assertSmbPropertiesNull(resultProperties.getSmbProperties()); + + //cleanup + premiumShareClient.delete(); + } + + @RequiredServiceVersion(clazz = ShareServiceVersion.class, min = "2025-05-05") + @Test + public void createHardLink() { + ShareClient premiumShareClient = getPremiumNFSShareClient(generateShareName()); + + ShareFileClient source = premiumShareClient.getFileClient(generatePathName()); + source.create(1024); + + String leaseId = testResourceNamer.randomUuid(); + ShareLeaseClient leaseClient = createLeaseClient(premiumShareClient, leaseId); + String lease = leaseClient.acquireLease(); + + ShareFileClient hardLink = premiumShareClient.getFileClient(generatePathName() + "hardlink"); + ShareFileCreateHardLinkOptions options = new ShareFileCreateHardLinkOptions(source.getFilePath()) + .setRequestConditions(new ShareRequestConditions().setLeaseId(lease)); + + ShareFileInfo response = hardLink.createHardLinkWithResponse(options, null, null).getValue(); + + assertEquals(NfsFileType.REGULAR, response.getPosixProperties().getFileType()); + assertEquals("0", response.getPosixProperties().getOwner()); + assertEquals("0", response.getPosixProperties().getGroup()); + assertEquals("0664", response.getPosixProperties().getFileMode()); + assertEquals(2, response.getPosixProperties().getLinkCount()); + + assertNotNull(response.getSmbProperties().getFileCreationTime()); + assertNotNull(response.getSmbProperties().getFileLastWriteTime()); + assertNotNull(response.getSmbProperties().getFileChangeTime()); + assertNotNull(response.getSmbProperties().getFileId()); + assertNotNull(response.getSmbProperties().getParentId()); + + FileShareTestHelper.assertSmbPropertiesNull(response.getSmbProperties()); + + //cleanup + leaseClient.releaseLease(); + premiumShareClient.delete(); + } } diff --git a/sdk/storage/azure-storage-file-share/src/test/java/com/azure/storage/file/share/FileAsyncApiTests.java b/sdk/storage/azure-storage-file-share/src/test/java/com/azure/storage/file/share/FileAsyncApiTests.java index e1a8025e184a..a13c4a9b1f79 100644 --- a/sdk/storage/azure-storage-file-share/src/test/java/com/azure/storage/file/share/FileAsyncApiTests.java +++ b/sdk/storage/azure-storage-file-share/src/test/java/com/azure/storage/file/share/FileAsyncApiTests.java @@ -4,6 +4,7 @@ package com.azure.storage.file.share; import com.azure.core.exception.UnexpectedLengthException; +import com.azure.core.http.rest.Response; import com.azure.core.util.CoreUtils; import com.azure.core.util.FluxUtil; import com.azure.core.util.polling.LongRunningOperationStatus; @@ -13,12 +14,16 @@ import com.azure.storage.common.test.shared.extensions.LiveOnly; import com.azure.storage.common.test.shared.extensions.PlaybackOnly; import com.azure.storage.common.test.shared.extensions.RequiredServiceVersion; +import com.azure.storage.file.share.models.ModeCopyMode; +import com.azure.storage.file.share.models.NfsFileType; import com.azure.storage.common.test.shared.policy.MockPartialResponsePolicy; import com.azure.storage.file.share.models.ClearRange; import com.azure.storage.file.share.models.CopyableFileSmbPropertiesList; import com.azure.storage.file.share.models.FilePermissionFormat; +import com.azure.storage.file.share.models.FilePosixProperties; import com.azure.storage.file.share.models.FileRange; import com.azure.storage.file.share.models.NtfsFileAttributes; +import com.azure.storage.file.share.models.OwnerCopyMode; import com.azure.storage.file.share.models.PermissionCopyModeType; import com.azure.storage.file.share.models.ShareAudience; import com.azure.storage.file.share.models.ShareErrorCode; @@ -36,12 +41,14 @@ import com.azure.storage.file.share.models.ShareStorageException; import com.azure.storage.file.share.models.ShareTokenIntent; import com.azure.storage.file.share.options.ShareFileCopyOptions; +import com.azure.storage.file.share.options.ShareFileCreateHardLinkOptions; import com.azure.storage.file.share.options.ShareFileCreateOptions; import com.azure.storage.file.share.options.ShareFileListRangesDiffOptions; import com.azure.storage.file.share.options.ShareFileRenameOptions; import com.azure.storage.file.share.options.ShareFileSetPropertiesOptions; import com.azure.storage.file.share.sas.ShareFileSasPermission; import com.azure.storage.file.share.sas.ShareServiceSasSignatureValues; +import com.azure.storage.file.share.specialized.ShareLeaseAsyncClient; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; @@ -53,6 +60,7 @@ import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; +import reactor.util.function.Tuple4; import java.io.File; import java.io.FileNotFoundException; @@ -1823,4 +1831,198 @@ public void listHandlesClientName() { .listHandles() .collectList()).assertNext(list -> assertNotNull(list.get(0).getClientName())).verifyComplete(); } + + @RequiredServiceVersion(clazz = ShareServiceVersion.class, min = "2025-05-05") + @Test + public void createNFS() { + ShareFileCreateOptions options = new ShareFileCreateOptions(1024) + .setPosixProperties(new FilePosixProperties().setOwner("345").setGroup("123").setFileMode("7777")); + + String shareName = generateShareName(); + Mono> create = getPremiumNFSShareAsyncClient(shareName).flatMap(premiumShareClient -> { + ShareFileAsyncClient premiumFileClient = premiumShareClient.getFileClient(generatePathName()); + return premiumFileClient.createWithResponse(options); + }); + + StepVerifier.create(create).assertNext(r -> { + ShareFileInfo response = r.getValue(); + assertEquals(NfsFileType.REGULAR, response.getPosixProperties().getFileType()); + assertEquals("345", response.getPosixProperties().getOwner()); + assertEquals("123", response.getPosixProperties().getGroup()); + assertEquals("7777", response.getPosixProperties().getFileMode()); + + FileShareTestHelper.assertSmbPropertiesNull(response.getSmbProperties()); + }).verifyComplete(); + + //cleanup + premiumFileServiceAsyncClient.getShareAsyncClient(shareName).delete().block(); + } + + @RequiredServiceVersion(clazz = ShareServiceVersion.class, min = "2025-05-05") + @Test + public void setPropertiesNFS() { + ShareFileSetPropertiesOptions options = new ShareFileSetPropertiesOptions(1024) + .setPosixProperties(new FilePosixProperties().setOwner("345").setGroup("123").setFileMode("7777")); + + String shareName = generateShareName(); + Mono> create = getPremiumNFSShareAsyncClient(shareName).flatMap(premiumShareClient -> { + ShareFileAsyncClient premiumFileClient = premiumShareClient.getFileClient(generatePathName()); + return premiumFileClient.create(1024).then(premiumFileClient.setPropertiesWithResponse(options)); + }); + + StepVerifier.create(create).assertNext(r -> { + ShareFileInfo response = r.getValue(); + assertEquals("345", response.getPosixProperties().getOwner()); + assertEquals("123", response.getPosixProperties().getGroup()); + assertEquals("7777", response.getPosixProperties().getFileMode()); + assertNotNull(response.getPosixProperties().getLinkCount()); + + FileShareTestHelper.assertSmbPropertiesNull(response.getSmbProperties()); + }).verifyComplete(); + + //cleanup + premiumFileServiceAsyncClient.getShareAsyncClient(shareName).delete().block(); + } + + @RequiredServiceVersion(clazz = ShareServiceVersion.class, min = "2025-05-05") + @Test + public void getPropertiesNFS() { + String shareName = generateShareName(); + Mono> create + = getPremiumNFSShareAsyncClient(shareName).flatMap(premiumShareClient -> { + ShareFileAsyncClient premiumFileClient = premiumShareClient.getFileClient(generatePathName()); + return premiumFileClient.create(1024).then(premiumFileClient.getPropertiesWithResponse()); + }); + + StepVerifier.create(create).assertNext(r -> { + ShareFileProperties response = r.getValue(); + + assertEquals(NfsFileType.REGULAR, response.getPosixProperties().getFileType()); + assertEquals("0", response.getPosixProperties().getOwner()); + assertEquals("0", response.getPosixProperties().getGroup()); + assertEquals("0664", response.getPosixProperties().getFileMode()); + assertEquals(1, response.getPosixProperties().getLinkCount()); + + FileShareTestHelper.assertSmbPropertiesNull(response.getSmbProperties()); + }).verifyComplete(); + + //cleanup + premiumFileServiceAsyncClient.getShareAsyncClient(shareName).delete().block(); + } + + private static Stream beginCopyNFSSupplier() { + return Stream.of(Arguments.of(ModeCopyMode.SOURCE), Arguments.of(ModeCopyMode.OVERRIDE), + Arguments.of((ModeCopyMode) null)); + } + + @RequiredServiceVersion(clazz = ShareServiceVersion.class, min = "2025-05-05") + @ParameterizedTest + @MethodSource("beginCopyNFSSupplier") + public void beginCopyNFS(ModeCopyMode modeAndOwnerCopyMode) { + String shareName = generateShareName(); + + String sourcePath = generatePathName() + "source"; + String destPath = generatePathName() + "dest"; + + Mono> setup + = getPremiumNFSShareAsyncClient(shareName).flatMap(premiumShareClient -> { + ShareFileAsyncClient premiumFileClientSource = premiumShareClient.getFileClient(sourcePath); + ShareFileAsyncClient premiumFileClientDest = premiumShareClient.getFileClient(destPath); + + return premiumFileClientSource.create(1024) + .then(premiumFileClientSource.uploadRange(DATA.getDefaultFlux(), DATA.getDefaultDataSizeLong())) + .then(premiumFileClientSource + .setPropertiesWithResponse(new ShareFileSetPropertiesOptions(1024).setPosixProperties( + new FilePosixProperties().setOwner("999").setGroup("888").setFileMode("0111")))) + .then(premiumFileClientDest.create(1024)) + .then(premiumFileClientSource.getProperties()) + .flatMap(sourceProperties -> { + String owner; + String group; + String mode; + + ShareFileCopyOptions options + = new ShareFileCopyOptions().setPosixProperties(new FilePosixProperties()); + + if (modeAndOwnerCopyMode == ModeCopyMode.OVERRIDE) { + owner = "54321"; + group = "12345"; + mode = "7777"; + options.setModeCopyMode(ModeCopyMode.OVERRIDE); + options.setOwnerCopyMode(OwnerCopyMode.OVERRIDE); + options.getPosixProperties().setOwner(owner); + options.getPosixProperties().setGroup(group); + options.getPosixProperties().setFileMode(mode); + } else if (modeAndOwnerCopyMode == ModeCopyMode.SOURCE) { + options.setModeCopyMode(ModeCopyMode.SOURCE); + options.setOwnerCopyMode(OwnerCopyMode.SOURCE); + owner = sourceProperties.getPosixProperties().getOwner(); + group = sourceProperties.getPosixProperties().getGroup(); + mode = sourceProperties.getPosixProperties().getFileMode(); + } else { + owner = "0"; + group = "0"; + mode = "0664"; + } + + return setPlaybackPollerFluxPollInterval( + premiumFileClientDest.beginCopy(premiumFileClientSource.getFileUrl(), options, null)).last() + .flatMap(ignore -> premiumFileClientDest.getProperties()) + .flatMap(properties -> Mono.zip(Mono.just(properties), Mono.just(owner), + Mono.just(group), Mono.just(mode))); + }); + }); + + StepVerifier.create(setup).assertNext(r -> { + assertEquals(r.getT2(), r.getT1().getPosixProperties().getOwner()); + assertEquals(r.getT3(), r.getT1().getPosixProperties().getGroup()); + assertEquals(r.getT4(), r.getT1().getPosixProperties().getFileMode()); + FileShareTestHelper.assertSmbPropertiesNull(r.getT1().getSmbProperties()); + }).verifyComplete(); + + //cleanup + premiumFileServiceAsyncClient.getShareAsyncClient(shareName).delete().block(); + } + + @RequiredServiceVersion(clazz = ShareServiceVersion.class, min = "2025-05-05") + @Test + public void createHardLink() { + String shareName = generateShareName(); + + Mono response = getPremiumNFSShareAsyncClient(shareName).flatMap(premiumShareClient -> { + ShareFileAsyncClient source = premiumShareClient.getFileClient(generatePathName()); + + String leaseId = testResourceNamer.randomUuid(); + ShareLeaseAsyncClient leaseClient = createLeaseClient(premiumShareClient, leaseId); + + return source.create(1024).then(leaseClient.acquireLease()).flatMap(lease -> { + ShareFileAsyncClient hardLink = premiumShareClient.getFileClient(generatePathName() + "hardlink"); + ShareFileCreateHardLinkOptions options = new ShareFileCreateHardLinkOptions(source.getFilePath()) + .setRequestConditions(new ShareRequestConditions().setLeaseId(lease)); + return hardLink.createHardLinkWithResponse(options).flatMap(res -> { + ShareFileInfo info = res.getValue(); + assertEquals(NfsFileType.REGULAR, info.getPosixProperties().getFileType()); + assertEquals("0", info.getPosixProperties().getOwner()); + assertEquals("0", info.getPosixProperties().getGroup()); + assertEquals("0664", info.getPosixProperties().getFileMode()); + assertEquals(2, info.getPosixProperties().getLinkCount()); + + assertNotNull(info.getSmbProperties().getFileCreationTime()); + assertNotNull(info.getSmbProperties().getFileLastWriteTime()); + assertNotNull(info.getSmbProperties().getFileChangeTime()); + assertNotNull(info.getSmbProperties().getFileId()); + assertNotNull(info.getSmbProperties().getParentId()); + + FileShareTestHelper.assertSmbPropertiesNull(info.getSmbProperties()); + //cleanup + return leaseClient.releaseLease(); + }); + }); + }); + + StepVerifier.create(response).verifyComplete(); + + //cleanup + premiumFileServiceAsyncClient.getShareAsyncClient(shareName).delete().block(); + } } diff --git a/sdk/storage/azure-storage-file-share/src/test/java/com/azure/storage/file/share/FileShareTestBase.java b/sdk/storage/azure-storage-file-share/src/test/java/com/azure/storage/file/share/FileShareTestBase.java index 4b812e4d8455..3696461349b3 100644 --- a/sdk/storage/azure-storage-file-share/src/test/java/com/azure/storage/file/share/FileShareTestBase.java +++ b/sdk/storage/azure-storage-file-share/src/test/java/com/azure/storage/file/share/FileShareTestBase.java @@ -25,13 +25,16 @@ import com.azure.storage.common.test.shared.TestDataFactory; import com.azure.storage.common.test.shared.TestEnvironment; import com.azure.storage.common.test.shared.policy.PerCallVersionPolicy; +import com.azure.storage.file.share.implementation.util.ModelHelper; import com.azure.storage.file.share.models.LeaseStateType; import com.azure.storage.file.share.models.ListSharesOptions; import com.azure.storage.file.share.models.ShareItem; +import com.azure.storage.file.share.models.ShareProtocols; import com.azure.storage.file.share.models.ShareSnapshotsDeleteOptionType; import com.azure.storage.file.share.models.ShareStorageException; import com.azure.storage.file.share.options.ShareAcquireLeaseOptions; import com.azure.storage.file.share.options.ShareBreakLeaseOptions; +import com.azure.storage.file.share.options.ShareCreateOptions; import com.azure.storage.file.share.options.ShareDeleteOptions; import com.azure.storage.file.share.specialized.ShareLeaseAsyncClient; import com.azure.storage.file.share.specialized.ShareLeaseClient; @@ -413,6 +416,20 @@ protected HttpClient getHttpClient() { return StorageCommonTestUtils.getHttpClient(interceptorManager); } + protected ShareClient getPremiumNFSShareClient(String shareName) { + ShareProtocols enabledProtocol = ModelHelper.parseShareProtocols("NFS"); + return premiumFileServiceClient + .createShareWithResponse(shareName, new ShareCreateOptions().setProtocols(enabledProtocol), null, null) + .getValue(); + } + + protected Mono getPremiumNFSShareAsyncClient(String shareName) { + ShareProtocols enabledProtocol = ModelHelper.parseShareProtocols("NFS"); + return premiumFileServiceAsyncClient + .createShareWithResponse(shareName, new ShareCreateOptions().setProtocols(enabledProtocol)) + .flatMap(r -> Mono.just(r.getValue())); + } + protected String getPrimaryConnectionString() { return ENVIRONMENT.getPrimaryAccount().getConnectionString(); } diff --git a/sdk/storage/azure-storage-file-share/src/test/java/com/azure/storage/file/share/FileShareTestHelper.java b/sdk/storage/azure-storage-file-share/src/test/java/com/azure/storage/file/share/FileShareTestHelper.java index 37caf69d45bb..10a73f52ad8d 100644 --- a/sdk/storage/azure-storage-file-share/src/test/java/com/azure/storage/file/share/FileShareTestHelper.java +++ b/sdk/storage/azure-storage-file-share/src/test/java/com/azure/storage/file/share/FileShareTestHelper.java @@ -43,6 +43,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNull; public class FileShareTestHelper { private static final ClientLogger LOGGER = new ClientLogger(FileShareTestHelper.class); @@ -376,4 +377,9 @@ protected static Stream filePermissionFormatSupplier() { return Stream.of(Arguments.of(FilePermissionFormat.SDDL), Arguments.of(FilePermissionFormat.BINARY), Arguments.of((Object) null)); } + + protected static void assertSmbPropertiesNull(FileSmbProperties smbProperties) { + assertNull(smbProperties.getFilePermissionKey()); + assertNull(smbProperties.getNtfsFileAttributes()); + } } diff --git a/sdk/storage/azure-storage-file-share/swagger/README.md b/sdk/storage/azure-storage-file-share/swagger/README.md index fc1f72a4be8b..5392db0e4931 100644 --- a/sdk/storage/azure-storage-file-share/swagger/README.md +++ b/sdk/storage/azure-storage-file-share/swagger/README.md @@ -16,7 +16,7 @@ autorest ### Code generation settings ``` yaml use: '@autorest/java@4.1.42' -input-file: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/refs/heads/main/specification/storage/data-plane/Microsoft.FileStorage/stable/2025-01-05/file.json +input-file: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/d18a495685ccec837b72891b4deea017f62e8190/specification/storage/data-plane/Microsoft.FileStorage/stable/2025-05-05/file.json java: true output-folder: ../ namespace: com.azure.storage.file.share @@ -26,7 +26,7 @@ enable-sync-stack: true default-http-exception-type: com.azure.storage.file.share.implementation.models.ShareStorageExceptionInternal models-subpackage: implementation.models custom-types-subpackage: models -custom-types: ShareFileHttpHeaders,ShareServiceProperties,ShareCorsRule,Range,FileRange,ClearRange,ShareFileRangeList,CopyStatusType,ShareSignedIdentifier,SourceModifiedAccessConditions,ShareErrorCode,StorageServiceProperties,ShareMetrics,ShareAccessPolicy,ShareFileDownloadHeaders,LeaseDurationType,LeaseStateType,LeaseStatusType,PermissionCopyModeType,ShareAccessTier,ShareRootSquash,ShareRetentionPolicy,ShareProtocolSettings,ShareSmbSettings,SmbMultichannel,FileLastWrittenMode,ShareTokenIntent,AccessRight,FilePermissionFormat +custom-types: ShareFileHttpHeaders,ShareServiceProperties,ShareCorsRule,Range,FileRange,ClearRange,ShareFileRangeList,CopyStatusType,ShareSignedIdentifier,SourceModifiedAccessConditions,ShareErrorCode,StorageServiceProperties,ShareMetrics,ShareAccessPolicy,ShareFileDownloadHeaders,LeaseDurationType,LeaseStateType,LeaseStatusType,PermissionCopyModeType,ShareAccessTier,ShareRootSquash,ShareRetentionPolicy,ShareProtocolSettings,ShareSmbSettings,SmbMultichannel,FileLastWrittenMode,ShareTokenIntent,AccessRight,FilePermissionFormat,NfsFileType,ModeCopyMode,OwnerCopyMode customization-class: src/main/java/ShareStorageCustomization.java use-input-stream-for-binary: true disable-client-builder: true @@ -114,6 +114,18 @@ directive: op.put.responses["200"].headers["x-ms-file-change-time"].format = "date-time"; ``` +### /{shareName}/{directory}/{fileName}?restype=hardlink +``` yaml +directive: +- from: swagger-document + where: $["x-ms-paths"] + transform: > + const op = $["/{shareName}/{directory}/{fileName}?restype=hardlink"]; + op.put.responses["201"].headers["x-ms-file-creation-time"].format = "date-time"; + op.put.responses["201"].headers["x-ms-file-last-write-time"].format = "date-time"; + op.put.responses["201"].headers["x-ms-file-change-time"].format = "date-time"; +``` + ### /{shareName}/{directory}/{fileName}?comp=rename ``` yaml directive: @@ -406,5 +418,5 @@ directive: $.xml = {"name": "Ranges"}; ``` -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fstorage%2Fazure-storage-file-share%2Fswagger%2FREADME.png) + diff --git a/sdk/storage/azure-storage-internal-avro/CHANGELOG.md b/sdk/storage/azure-storage-internal-avro/CHANGELOG.md index 82389ac831e8..29e6deaac2b7 100644 --- a/sdk/storage/azure-storage-internal-avro/CHANGELOG.md +++ b/sdk/storage/azure-storage-internal-avro/CHANGELOG.md @@ -1,15 +1,29 @@ # Release History -## 12.15.0-beta.1 (Unreleased) +## 12.15.0 (2025-03-11) ### Features Added +- Added support for service version 2025-05-05. -### Breaking Changes +### Other Changes + +#### Dependency Updates +- Upgraded `azure-storage-common` from `12.28.1` to version `12.29.0`. -### Bugs Fixed +## 12.14.1 (2025-03-03) ### Other Changes +#### Dependency Updates +- Upgraded `azure-xml` from `1.1.0` to version `1.2.0`. +- Upgraded `azure-storage-common` from `12.28.0` to version `12.29.0-beta.2`. +- Upgraded `azure-core` from `1.54.0` to version `1.55.2`. + +## 12.15.0-beta.1 (2025-02-11) + +### Features Added +- Added support for service version 2025-05-05. + ## 12.14.0 (2024-11-13) ### Features Added diff --git a/sdk/storage/azure-storage-internal-avro/pom.xml b/sdk/storage/azure-storage-internal-avro/pom.xml index d9b1e5bbf65f..832dc44bce98 100644 --- a/sdk/storage/azure-storage-internal-avro/pom.xml +++ b/sdk/storage/azure-storage-internal-avro/pom.xml @@ -13,7 +13,7 @@ com.azure azure-storage-internal-avro - 12.15.0-beta.1 + 12.15.0 Microsoft Azure internal Avro module for Storage This module contains internal use only avro parser code based for Microsoft Azure Storage client libraries. @@ -53,29 +53,29 @@ com.azure azure-xml - 1.1.0 + 1.2.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-storage-common - 12.29.0-beta.1 + 12.29.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-storage-common - 12.29.0-beta.1 + 12.29.0 tests test-jar test diff --git a/sdk/storage/azure-storage-perf/README.md b/sdk/storage/azure-storage-perf/README.md index 6ce2200a9a2e..b9cc367e64f6 100644 --- a/sdk/storage/azure-storage-perf/README.md +++ b/sdk/storage/azure-storage-perf/README.md @@ -30,4 +30,4 @@ For details on contributing to this repository, see the [contributing guide](htt 1. Push to the branch (`git push origin my-new-feature`) 1. Create new Pull Request -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fstorage%2Fperf-test-core%2FREADME.png) + diff --git a/sdk/storage/azure-storage-perf/pom.xml b/sdk/storage/azure-storage-perf/pom.xml index aa9c0bd60e00..413650c5d3bd 100644 --- a/sdk/storage/azure-storage-perf/pom.xml +++ b/sdk/storage/azure-storage-perf/pom.xml @@ -25,25 +25,25 @@ com.azure azure-storage-blob - 12.30.0-beta.1 + 12.30.0 com.azure azure-storage-blob-cryptography - 12.29.0-beta.1 + 12.29.0 com.azure azure-storage-file-datalake - 12.23.0-beta.1 + 12.23.0 com.azure azure-storage-file-share - 12.26.0-beta.1 + 12.26.0 @@ -55,28 +55,28 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-xml - 1.1.0 + 1.2.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-security-keyvault-keys - 4.9.1 + 4.9.3 diff --git a/sdk/storage/azure-storage-queue/CHANGELOG.md b/sdk/storage/azure-storage-queue/CHANGELOG.md index 108eafd58256..43137f22b75f 100644 --- a/sdk/storage/azure-storage-queue/CHANGELOG.md +++ b/sdk/storage/azure-storage-queue/CHANGELOG.md @@ -1,15 +1,30 @@ # Release History -## 12.25.0-beta.1 (Unreleased) +## 12.25.0 (2025-03-11) ### Features Added +- Added support for service version 2025-05-05. -### Breaking Changes +### Other Changes -### Bugs Fixed +#### Dependency Updates +- Upgraded `azure-storage-common` from `12.28.1` to version `12.29.0`. + +## 12.24.1 (2025-03-03) ### Other Changes +#### Dependency Updates +- Upgraded `azure-xml` from `1.1.0` to version `1.2.0`. +- Upgraded `azure-storage-common` from `12.28.0` to version `12.29.0-beta.2`. +- Upgraded `azure-core` from `1.54.0` to version `1.55.2`. +- Upgraded `azure-core-http-netty` from `1.15.6` to version `1.15.10`. + +## 12.25.0-beta.1 (2025-02-11) + +### Features Added +- Added support for service version 2025-05-05. + ## 12.24.0 (2024-11-13) ### Features Added diff --git a/sdk/storage/azure-storage-queue/README.md b/sdk/storage/azure-storage-queue/README.md index 3bd80038a7cb..f54c3be01931 100644 --- a/sdk/storage/azure-storage-queue/README.md +++ b/sdk/storage/azure-storage-queue/README.md @@ -54,7 +54,7 @@ add the direct dependency to your project as follows. com.azure azure-storage-queue - 12.24.0 + 12.25.0 ``` [//]: # ({x-version-update-end}) @@ -499,4 +499,4 @@ For details on contributing to this repository, see the [contributing guide](htt [samples]: https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/storage/azure-storage-queue/src/samples [performance_tuning]: https://github.com/Azure/azure-sdk-for-java/wiki/Performance-Tuning -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fstorage%2Fazure-storage-queue%2FREADME.png) + diff --git a/sdk/storage/azure-storage-queue/pom.xml b/sdk/storage/azure-storage-queue/pom.xml index ee420d8d72fd..86323252278a 100644 --- a/sdk/storage/azure-storage-queue/pom.xml +++ b/sdk/storage/azure-storage-queue/pom.xml @@ -13,7 +13,7 @@ com.azure azure-storage-queue - 12.25.0-beta.1 + 12.25.0 Microsoft Azure client library for Queue Storage This module contains client library for Microsoft Azure Queue Storage. @@ -61,28 +61,28 @@ com.azure azure-xml - 1.1.0 + 1.2.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-storage-common - 12.29.0-beta.1 + 12.29.0 com.azure azure-storage-common - 12.29.0-beta.1 + 12.29.0 tests test-jar test @@ -90,13 +90,13 @@ com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test @@ -131,7 +131,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 ${AZURE_STORAGE_SAS_SERVICE_VERSION} diff --git a/sdk/storage/azure-storage-queue/src/main/java/com/azure/storage/queue/QueueServiceVersion.java b/sdk/storage/azure-storage-queue/src/main/java/com/azure/storage/queue/QueueServiceVersion.java index e4df86902ca9..08b8f3203cfc 100644 --- a/sdk/storage/azure-storage-queue/src/main/java/com/azure/storage/queue/QueueServiceVersion.java +++ b/sdk/storage/azure-storage-queue/src/main/java/com/azure/storage/queue/QueueServiceVersion.java @@ -132,7 +132,12 @@ public enum QueueServiceVersion implements ServiceVersion { /** * Service version {@code 2025-01-05}. */ - V2025_01_05("2025-01-05"); + V2025_01_05("2025-01-05"), + + /** + * Service version {@code 2025-05-05}. + */ + V2025_05_05("2025-05-05"); private final String version; @@ -154,6 +159,6 @@ public String getVersion() { * @return the latest {@link QueueServiceVersion} */ public static QueueServiceVersion getLatest() { - return V2025_01_05; + return V2025_05_05; } } diff --git a/sdk/storage/azure-storage-queue/src/samples/README.md b/sdk/storage/azure-storage-queue/src/samples/README.md index 38a450431f6f..d79c63a8dd10 100644 --- a/sdk/storage/azure-storage-queue/src/samples/README.md +++ b/sdk/storage/azure-storage-queue/src/samples/README.md @@ -55,4 +55,4 @@ This project welcomes contributions and suggestions. Find [more contributing][SD [queue_key_concept]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/storage/azure-storage-queue/README.md#key-concepts [samples]: java/samples/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fstorage%2Fazure-storage-queue%2Fsrc%2Fsamples%2FREADME.png) + diff --git a/sdk/storage/azure-storage-queue/swagger/README.md b/sdk/storage/azure-storage-queue/swagger/README.md index 4e08626e8b40..7c368e9c10d2 100644 --- a/sdk/storage/azure-storage-queue/swagger/README.md +++ b/sdk/storage/azure-storage-queue/swagger/README.md @@ -141,4 +141,4 @@ directive: $["x-ms-pageable"].itemName = "QueueItems"; ``` -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fstorage%2Fazure-storage-queue%2Fswagger%2FREADME.png) + diff --git a/sdk/storage/azure-storage-stress/pom.xml b/sdk/storage/azure-storage-stress/pom.xml index 31c2ba8eed2a..90ebc4c06953 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.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure @@ -46,29 +46,29 @@ com.azure - azure-monitor-opentelemetry-exporter - 1.0.0-beta.31 + azure-monitor-opentelemetry-autoconfigure + 1.0.0 io.opentelemetry.instrumentation opentelemetry-runtime-telemetry-java8 - 2.9.0-alpha + 2.12.0-alpha io.opentelemetry.instrumentation opentelemetry-logback-appender-1.0 - 2.9.0-alpha + 2.12.0-alpha com.azure azure-core-metrics-opentelemetry - 1.0.0-beta.25 + 1.0.0-beta.29 com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.52 + 1.0.0-beta.56 diff --git a/sdk/storage/azure-storage-stress/src/main/java/com/azure/storage/stress/TelemetryHelper.java b/sdk/storage/azure-storage-stress/src/main/java/com/azure/storage/stress/TelemetryHelper.java index a9a7c7fa1d93..135ff4e9073b 100644 --- a/sdk/storage/azure-storage-stress/src/main/java/com/azure/storage/stress/TelemetryHelper.java +++ b/sdk/storage/azure-storage-stress/src/main/java/com/azure/storage/stress/TelemetryHelper.java @@ -5,7 +5,7 @@ import com.azure.core.util.logging.ClientLogger; import com.azure.core.util.logging.LogLevel; -import com.azure.monitor.opentelemetry.exporter.AzureMonitorExporter; +import com.azure.monitor.opentelemetry.autoconfigure.AzureMonitorAutoConfigure; import io.netty.channel.unix.Errors; import io.opentelemetry.api.OpenTelemetry; import io.opentelemetry.api.common.AttributeKey; @@ -99,7 +99,7 @@ public static OpenTelemetry init() { System.setProperty("otel.metrics.exporter", "none"); System.setProperty("otel.logs.exporter", "none"); } else { - AzureMonitorExporter.customize(sdkBuilder, applicationInsightsConnectionString); + AzureMonitorAutoConfigure.customize(sdkBuilder, applicationInsightsConnectionString); } OpenTelemetry otel = sdkBuilder diff --git a/sdk/storageactions/azure-resourcemanager-storageactions/README.md b/sdk/storageactions/azure-resourcemanager-storageactions/README.md index 49786453d202..b338518a8990 100644 --- a/sdk/storageactions/azure-resourcemanager-storageactions/README.md +++ b/sdk/storageactions/azure-resourcemanager-storageactions/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-storageactions - 1.0.0-beta.2 + 1.0.0-beta.3 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fstorageactions%2Fazure-resourcemanager-storageactions%2FREADME.png) + diff --git a/sdk/storageactions/azure-resourcemanager-storageactions/pom.xml b/sdk/storageactions/azure-resourcemanager-storageactions/pom.xml index c4281eda6fe8..d97512568449 100644 --- a/sdk/storageactions/azure-resourcemanager-storageactions/pom.xml +++ b/sdk/storageactions/azure-resourcemanager-storageactions/pom.xml @@ -52,23 +52,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/storagecache/azure-resourcemanager-storagecache/README.md b/sdk/storagecache/azure-resourcemanager-storagecache/README.md index 7daf0fbd0a5f..71ff6cd3b6d0 100644 --- a/sdk/storagecache/azure-resourcemanager-storagecache/README.md +++ b/sdk/storagecache/azure-resourcemanager-storagecache/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-storagecache - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fstoragecache%2Fazure-resourcemanager-storagecache%2FREADME.png) + diff --git a/sdk/storagecache/azure-resourcemanager-storagecache/pom.xml b/sdk/storagecache/azure-resourcemanager-storagecache/pom.xml index c73e1567e85c..0e7d83aa13d8 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.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/storagemover/azure-resourcemanager-storagemover/README.md b/sdk/storagemover/azure-resourcemanager-storagemover/README.md index 7e98289756b1..0e1ce683d9ce 100644 --- a/sdk/storagemover/azure-resourcemanager-storagemover/README.md +++ b/sdk/storagemover/azure-resourcemanager-storagemover/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-storagemover - 1.3.0 + 1.4.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -108,4 +108,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fstoragemover%2Fazure-resourcemanager-storagemover%2FREADME.png) + diff --git a/sdk/storagemover/azure-resourcemanager-storagemover/pom.xml b/sdk/storagemover/azure-resourcemanager-storagemover/pom.xml index 0dbd79d781bb..9daa149b8c08 100644 --- a/sdk/storagemover/azure-resourcemanager-storagemover/pom.xml +++ b/sdk/storagemover/azure-resourcemanager-storagemover/pom.xml @@ -52,29 +52,29 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/storagepool/azure-resourcemanager-storagepool/README.md b/sdk/storagepool/azure-resourcemanager-storagepool/README.md index 73f753219d1f..688e7a797864 100644 --- a/sdk/storagepool/azure-resourcemanager-storagepool/README.md +++ b/sdk/storagepool/azure-resourcemanager-storagepool/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-storagepool - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fstoragepool%2Fazure-resourcemanager-storagepool%2FREADME.png) + diff --git a/sdk/storagepool/azure-resourcemanager-storagepool/pom.xml b/sdk/storagepool/azure-resourcemanager-storagepool/pom.xml index d3017d64da31..8d5b08714fde 100644 --- a/sdk/storagepool/azure-resourcemanager-storagepool/pom.xml +++ b/sdk/storagepool/azure-resourcemanager-storagepool/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/streamanalytics/azure-resourcemanager-streamanalytics/README.md b/sdk/streamanalytics/azure-resourcemanager-streamanalytics/README.md index 59d13a19bc18..0d3203c3c11a 100644 --- a/sdk/streamanalytics/azure-resourcemanager-streamanalytics/README.md +++ b/sdk/streamanalytics/azure-resourcemanager-streamanalytics/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-streamanalytics - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fstreamanalytics%2Fazure-resourcemanager-streamanalytics%2FREADME.png) + diff --git a/sdk/streamanalytics/azure-resourcemanager-streamanalytics/pom.xml b/sdk/streamanalytics/azure-resourcemanager-streamanalytics/pom.xml index f2c69264ec0c..2f5feb095e31 100644 --- a/sdk/streamanalytics/azure-resourcemanager-streamanalytics/pom.xml +++ b/sdk/streamanalytics/azure-resourcemanager-streamanalytics/pom.xml @@ -51,23 +51,23 @@ Code generated by Microsoft (R) AutoRest Code Generator. com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/subscription/azure-resourcemanager-subscription/README.md b/sdk/subscription/azure-resourcemanager-subscription/README.md index be9133521515..9737d6f43586 100644 --- a/sdk/subscription/azure-resourcemanager-subscription/README.md +++ b/sdk/subscription/azure-resourcemanager-subscription/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-subscription - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fsubscription%2Fazure-resourcemanager-subscription%2FREADME.png) + diff --git a/sdk/subscription/azure-resourcemanager-subscription/pom.xml b/sdk/subscription/azure-resourcemanager-subscription/pom.xml index 6c10e142a37f..dc7ba3886a05 100644 --- a/sdk/subscription/azure-resourcemanager-subscription/pom.xml +++ b/sdk/subscription/azure-resourcemanager-subscription/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/support/azure-resourcemanager-support/README.md b/sdk/support/azure-resourcemanager-support/README.md index da8ed713e929..f58b58a8a719 100644 --- a/sdk/support/azure-resourcemanager-support/README.md +++ b/sdk/support/azure-resourcemanager-support/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-support - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fsupport%2Fazure-resourcemanager-support%2FREADME.png) + diff --git a/sdk/support/azure-resourcemanager-support/pom.xml b/sdk/support/azure-resourcemanager-support/pom.xml index 38319f1839e4..6c3bf633b205 100644 --- a/sdk/support/azure-resourcemanager-support/pom.xml +++ b/sdk/support/azure-resourcemanager-support/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/synapse/azure-analytics-synapse-accesscontrol/README.md b/sdk/synapse/azure-analytics-synapse-accesscontrol/README.md index 047ef9739850..26f9ff1a4e07 100644 --- a/sdk/synapse/azure-analytics-synapse-accesscontrol/README.md +++ b/sdk/synapse/azure-analytics-synapse-accesscontrol/README.md @@ -14,7 +14,7 @@ Maven dependency for the Azure Synapse Access Control client library. Add it to com.azure azure-analytics-synapse-accesscontrol - 1.0.0-beta.4 + 1.0.0-beta.5 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/synapse/azure-analytics-synapse-accesscontrol/pom.xml b/sdk/synapse/azure-analytics-synapse-accesscontrol/pom.xml index 74beb590fae9..1d4e1449549a 100644 --- a/sdk/synapse/azure-analytics-synapse-accesscontrol/pom.xml +++ b/sdk/synapse/azure-analytics-synapse-accesscontrol/pom.xml @@ -45,30 +45,30 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/CHANGELOG.md b/sdk/synapse/azure-analytics-synapse-artifacts/CHANGELOG.md index 0129c79efaaa..cf51a755a4d0 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/CHANGELOG.md +++ b/sdk/synapse/azure-analytics-synapse-artifacts/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.0.0-beta.16 (Unreleased) +## 1.0.0-beta.17 (Unreleased) ### Features Added @@ -10,6 +10,47 @@ ### Other Changes +## 1.0.0-beta.16 (2025-03-07) + +### Features Added + + - Model Dataset has a new parameter schema + - Model LinkedService parameter AzureFileStorageLinkedService support MI auth + - Model LinkedService parameter AzureTableStorageLinkedService support MI auth + - Model LinkedService parameter DynamicsCrmLinkedService has a new properties credential + - Model LinkedService parameter DynamicsLinkedService has a new properties domain + - Model LinkedService parameter GreenplumLinkedService has some new connection properties + - Model LinkedService parameter MySqlLinkedService has some new properties + - Model LinkedService parameter OracleLinkedService update properties + - Model LinkedService parameter RestService and SharePointOnlineList support ServicePrincipalCert auth + - Model LinkedService parameter SAP ODP update properties sncMode + - Model LinkedService parameter SnowflakeV2LinkedService has a new properties host + - Model LinkedService parameter SqlServerLinkedService add authenticationType UserAssignedManagedIdentity + - Model LinkedService parameter TeradataLinkedService has some new Teradata connection properties + - Model LinkedService parameter VerticaLinkedService support Vertica V2 + - Model LinkedService has a new parameter version + - Model Pipeline Add credential reference in notebook and spark job definition activity + - Model Pipeline feature snowflake support multi-resultset + - Model Pipeline feature snowflake support storage integration + - Model Pipeline parameter ExecuteDataFlowActivity has a new properties continuationSettings + - Model Pipeline parameter ExpressionV2 has a new properties page_size + - Model Pipeline parameter SalesforceV2Source has a new properties page_size + - Model Pipeline support Iceberg Format As Sink + - Model Pipeline support TeradataSink + - Model Dataset support Iceberg Format As Sink + - Model runNotebook parameter runId update description + - Model LinkedService support sslMode and useSystemTrustStore for MariaDB + +### Breaking Changes + + - Model LinkedService parameter PostgreSqlV2LinkedService has a new required properties authentication_type + - Model LinkedService parameter SapOdpLinkedService update properties sncMode + - Model LinkedService parameter AzureSqlDWLinkedService update required properties + - Model LinkedService parameter SqlServerLinkedService update required properties + - Model LinkedService parameter AmazonRdsForSqlServerLinkedService update required properties + - Model LinkedService parameter AzureSqlDatabaseLinkedService update required properties + - Model LinkedService parameter AzureSqlMILinkedService update required properties + ## 1.0.0-beta.15 (2024-06-11) ### Features Added diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/README.md b/sdk/synapse/azure-analytics-synapse-artifacts/README.md index 123e483750b1..82d70c04acad 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/README.md +++ b/sdk/synapse/azure-analytics-synapse-artifacts/README.md @@ -14,7 +14,7 @@ Maven dependency for the Azure Synapse Artifacts client library. Add it to your com.azure azure-analytics-synapse-artifacts - 1.0.0-beta.15 + 1.0.0-beta.17 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/pom.xml b/sdk/synapse/azure-analytics-synapse-artifacts/pom.xml index 3cb206d334b9..9509d38e722b 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/pom.xml +++ b/sdk/synapse/azure-analytics-synapse-artifacts/pom.xml @@ -13,7 +13,7 @@ com.azure azure-analytics-synapse-artifacts - 1.0.0-beta.16 + 1.0.0-beta.17 Microsoft Azure client library for Synapse artifacts service This package contains the Microsoft Azure Synapse Analytics artifacts related features. @@ -45,25 +45,25 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/RunNotebookAsyncClient.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/RunNotebookAsyncClient.java index 021ffb553f54..4d1009084e20 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/RunNotebookAsyncClient.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/RunNotebookAsyncClient.java @@ -39,7 +39,8 @@ public final class RunNotebookAsyncClient { /** * Run notebook. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @param runNotebookRequest Run notebook request payload. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. @@ -56,7 +57,8 @@ public Mono> cre /** * Run notebook. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @param runNotebookRequest Run notebook request payload. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. @@ -72,7 +74,8 @@ public Mono createRun(String runId, RunNotebookRequest runN /** * Run notebook. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @param runNotebookRequest Run notebook request payload. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. @@ -89,7 +92,8 @@ public Mono> createRunNoCustomHeadersWithResponse( /** * Get RunNotebook Status for run id. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -104,7 +108,8 @@ public Mono> getStatusWithResponse(String runId) { /** * Get RunNotebook Status for run id. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -119,7 +124,8 @@ public Mono getStatus(String runId) { /** * Cancel notebook run. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -134,7 +140,8 @@ public Mono> cancelRunWithResponse(String runId) { /** * Cancel notebook run. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -149,7 +156,8 @@ public Mono cancelRun(String runId) { /** * Get RunNotebook Snapshot for run id. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -164,7 +172,8 @@ public Mono> getSnapshotWithResponse(Strin /** * Get RunNotebook Snapshot for run id. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/RunNotebookClient.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/RunNotebookClient.java index f2aa03a98fbf..7ca3a03048e9 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/RunNotebookClient.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/RunNotebookClient.java @@ -39,7 +39,8 @@ public final class RunNotebookClient { /** * Run notebook. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @param runNotebookRequest Run notebook request payload. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -57,7 +58,8 @@ public ResponseBase createRun /** * Run notebook. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @param runNotebookRequest Run notebook request payload. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. @@ -73,7 +75,8 @@ public RunNotebookResponse createRun(String runId, RunNotebookRequest runNoteboo /** * Run notebook. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @param runNotebookRequest Run notebook request payload. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -91,7 +94,8 @@ public Response createRunNoCustomHeadersWithResponse(String /** * Get RunNotebook Status for run id. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. @@ -107,7 +111,8 @@ public Response getStatusWithResponse(String runId, Context /** * Get RunNotebook Status for run id. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -122,7 +127,8 @@ public RunNotebookResponse getStatus(String runId) { /** * Cancel notebook run. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. @@ -138,7 +144,8 @@ public Response cancelRunWithResponse(String runId, Context /** * Cancel notebook run. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -153,7 +160,8 @@ public RunNotebookResponse cancelRun(String runId) { /** * Get RunNotebook Snapshot for run id. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. @@ -169,7 +177,8 @@ public Response getSnapshotWithResponse(String runI /** * Get RunNotebook Snapshot for run id. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/implementation/RunNotebooksImpl.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/implementation/RunNotebooksImpl.java index 515af7645bdd..f96fc20ad922 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/implementation/RunNotebooksImpl.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/implementation/RunNotebooksImpl.java @@ -105,7 +105,8 @@ Mono> getSnapshot(@HostParam("endpoint") S /** * Run notebook. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @param runNotebookRequest Run notebook request payload. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. @@ -121,7 +122,8 @@ Mono> getSnapshot(@HostParam("endpoint") S /** * Run notebook. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @param runNotebookRequest Run notebook request payload. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -140,7 +142,8 @@ Mono> getSnapshot(@HostParam("endpoint") S /** * Run notebook. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @param runNotebookRequest Run notebook request payload. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. @@ -155,7 +158,8 @@ public Mono createRunAsync(String runId, RunNotebookRequest /** * Run notebook. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @param runNotebookRequest Run notebook request payload. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -173,7 +177,8 @@ public Mono createRunAsync(String runId, RunNotebookRequest /** * Run notebook. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @param runNotebookRequest Run notebook request payload. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -190,7 +195,8 @@ public ResponseBase createRun /** * Run notebook. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @param runNotebookRequest Run notebook request payload. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. @@ -205,7 +211,8 @@ public RunNotebookResponse createRun(String runId, RunNotebookRequest runNoteboo /** * Run notebook. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @param runNotebookRequest Run notebook request payload. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. @@ -222,7 +229,8 @@ public Mono> createRunNoCustomHeadersWithResponseA /** * Run notebook. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @param runNotebookRequest Run notebook request payload. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -242,7 +250,8 @@ public Mono> createRunNoCustomHeadersWithResponseA /** * Run notebook. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @param runNotebookRequest Run notebook request payload. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -259,7 +268,8 @@ public Response createRunNoCustomHeadersWithResponse(String /** * Get RunNotebook Status for run id. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -273,7 +283,8 @@ public Mono> getStatusWithResponseAsync(String run /** * Get RunNotebook Status for run id. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. @@ -290,7 +301,8 @@ public Mono> getStatusWithResponseAsync(String run /** * Get RunNotebook Status for run id. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -304,7 +316,8 @@ public Mono getStatusAsync(String runId) { /** * Get RunNotebook Status for run id. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. @@ -319,7 +332,8 @@ public Mono getStatusAsync(String runId, Context context) { /** * Get RunNotebook Status for run id. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. @@ -334,7 +348,8 @@ public Response getStatusWithResponse(String runId, Context /** * Get RunNotebook Status for run id. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -348,7 +363,8 @@ public RunNotebookResponse getStatus(String runId) { /** * Cancel notebook run. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. * @throws RunNotebookResponseException thrown if the request is rejected by server on status code 409. @@ -363,7 +379,8 @@ public Mono> cancelRunWithResponseAsync(String run /** * Cancel notebook run. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. @@ -381,7 +398,8 @@ public Mono> cancelRunWithResponseAsync(String run /** * Cancel notebook run. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. * @throws RunNotebookResponseException thrown if the request is rejected by server on status code 409. @@ -396,7 +414,8 @@ public Mono cancelRunAsync(String runId) { /** * Cancel notebook run. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. @@ -412,7 +431,8 @@ public Mono cancelRunAsync(String runId, Context context) { /** * Cancel notebook run. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. @@ -428,7 +448,8 @@ public Response cancelRunWithResponse(String runId, Context /** * Cancel notebook run. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. * @throws RunNotebookResponseException thrown if the request is rejected by server on status code 409. @@ -443,7 +464,8 @@ public RunNotebookResponse cancelRun(String runId) { /** * Get RunNotebook Snapshot for run id. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -457,7 +479,8 @@ public Mono> getSnapshotWithResponseAsync( /** * Get RunNotebook Snapshot for run id. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. @@ -474,7 +497,8 @@ public Mono> getSnapshotWithResponseAsync( /** * Get RunNotebook Snapshot for run id. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. @@ -488,7 +512,8 @@ public Mono getSnapshotAsync(String runId) { /** * Get RunNotebook Snapshot for run id. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. @@ -503,7 +528,8 @@ public Mono getSnapshotAsync(String runId, Context /** * Get RunNotebook Snapshot for run id. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. @@ -518,7 +544,8 @@ public Response getSnapshotWithResponse(String runI /** * Get RunNotebook Snapshot for run id. * - * @param runId Notebook run id. + * @param runId Notebook run id. For Create Run, you can generate a new GUID and use it here. For other actions, + * this is the same ID used in Create Run. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws CloudErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AmazonMWSLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AmazonMWSLinkedService.java index cdc3ba8d6df0..daa36781fba9 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AmazonMWSLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AmazonMWSLinkedService.java @@ -302,6 +302,15 @@ public AmazonMWSLinkedService setEncryptedCredential(Object encryptedCredential) return this; } + /** + * {@inheritDoc} + */ + @Override + public AmazonMWSLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -344,6 +353,7 @@ public AmazonMWSLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -397,7 +407,9 @@ public static AmazonMWSLinkedService fromJson(JsonReader jsonReader) throws IOEx String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAmazonMWSLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAmazonMWSLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedAmazonMWSLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AmazonRdsForOracleLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AmazonRdsForOracleLinkedService.java index 5746a3bf4fa4..af8a4baaaa24 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AmazonRdsForOracleLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AmazonRdsForOracleLinkedService.java @@ -119,6 +119,15 @@ public AmazonRdsForOracleLinkedService setEncryptedCredential(Object encryptedCr return this; } + /** + * {@inheritDoc} + */ + @Override + public AmazonRdsForOracleLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -161,6 +170,7 @@ public AmazonRdsForOracleLinkedService setAnnotations(List annotations) @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -199,7 +209,9 @@ public static AmazonRdsForOracleLinkedService fromJson(JsonReader jsonReader) th String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAmazonRdsForOracleLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAmazonRdsForOracleLinkedService .setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AmazonRdsForSqlServerAuthenticationType.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AmazonRdsForSqlServerAuthenticationType.java new file mode 100644 index 000000000000..bce52b37a1b4 --- /dev/null +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AmazonRdsForSqlServerAuthenticationType.java @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.analytics.synapse.artifacts.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The type used for authentication. Type: string. + */ +public final class AmazonRdsForSqlServerAuthenticationType + extends ExpandableStringEnum { + /** + * Static value SQL for AmazonRdsForSqlServerAuthenticationType. + */ + public static final AmazonRdsForSqlServerAuthenticationType SQL = fromString("SQL"); + + /** + * Static value Windows for AmazonRdsForSqlServerAuthenticationType. + */ + public static final AmazonRdsForSqlServerAuthenticationType WINDOWS = fromString("Windows"); + + /** + * Creates a new instance of AmazonRdsForSqlServerAuthenticationType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AmazonRdsForSqlServerAuthenticationType() { + } + + /** + * Creates or finds a AmazonRdsForSqlServerAuthenticationType from its string representation. + * + * @param name a name to look for. + * @return the corresponding AmazonRdsForSqlServerAuthenticationType. + */ + public static AmazonRdsForSqlServerAuthenticationType fromString(String name) { + return fromString(name, AmazonRdsForSqlServerAuthenticationType.class); + } + + /** + * Gets known AmazonRdsForSqlServerAuthenticationType values. + * + * @return known AmazonRdsForSqlServerAuthenticationType values. + */ + public static Collection values() { + return values(AmazonRdsForSqlServerAuthenticationType.class); + } +} diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AmazonRdsForSqlServerLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AmazonRdsForSqlServerLinkedService.java index e2fbc6ec0c90..ccf0fca63402 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AmazonRdsForSqlServerLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AmazonRdsForSqlServerLinkedService.java @@ -23,11 +23,136 @@ public class AmazonRdsForSqlServerLinkedService extends LinkedService { */ private String type = "AmazonRdsForSqlServer"; + /* + * The name or network address of the instance of SQL Server to which to connect, used by recommended version. Type: + * string (or Expression with resultType string). + */ + private Object server; + + /* + * The name of the database, used by recommended version. Type: string (or Expression with resultType string). + */ + private Object database; + + /* + * Indicate whether TLS encryption is required for all data sent between the client and server, used by recommended + * version. Possible values are true/yes/mandatory, false/no/optional and strict. Type: string (or Expression with + * resultType string). + */ + private Object encrypt; + + /* + * Indicate whether the channel will be encrypted while bypassing walking the certificate chain to validate trust, + * used by recommended version. Type: Boolean (or Expression with resultType boolean). + */ + private Object trustServerCertificate; + + /* + * The host name to use when validating the server certificate for the connection. When not specified, the server + * name from the Data Source is used for certificate validation, used by recommended version. Type: string (or + * Expression with resultType string). + */ + private Object hostNameInCertificate; + + /* + * The application workload type when connecting to a server, used by recommended version. Possible values are + * ReadOnly and ReadWrite. Type: string (or Expression with resultType string). + */ + private Object applicationIntent; + + /* + * The length of time (in seconds) to wait for a connection to the server before terminating the attempt and + * generating an error, used by recommended version. Type: integer (or Expression with resultType integer). + */ + private Object connectTimeout; + + /* + * The number of re-connections attempted after identifying that there was an idle connection failure, used by + * recommended version. This must be an integer between 0 and 255. Type: integer (or Expression with resultType + * integer). + */ + private Object connectRetryCount; + + /* + * The amount of time (in seconds) between each re-connection attempt after identifying that there was an idle + * connection failure, used by recommended version. This must be an integer between 1 and 60. Type: integer (or + * Expression with resultType integer). + */ + private Object connectRetryInterval; + + /* + * The minimum time, in seconds, for the connection to live in the connection pool before being destroyed, used by + * recommended version. Type: integer (or Expression with resultType integer). + */ + private Object loadBalanceTimeout; + + /* + * The default wait time (in seconds) before terminating the attempt to execute a command and generating an error, + * used by recommended version. Type: integer (or Expression with resultType integer). + */ + private Object commandTimeout; + + /* + * Indicate whether User ID and Password are specified in the connection (when false) or whether the current Windows + * account credentials are used for authentication (when true), used by recommended version. Type: Boolean (or + * Expression with resultType boolean). + */ + private Object integratedSecurity; + + /* + * The name or address of the partner server to connect to if the primary server is down, used by recommended + * version. Type: string (or Expression with resultType string). + */ + private Object failoverPartner; + + /* + * The maximum number of connections allowed in the connection pool for this specific connection string, used by + * recommended version. Type: integer (or Expression with resultType integer). + */ + private Object maxPoolSize; + + /* + * The minimum number of connections allowed in the connection pool for this specific connection string, used by + * recommended version. Type: integer (or Expression with resultType integer). + */ + private Object minPoolSize; + + /* + * When true, an application can maintain multiple active result sets (MARS). When false, an application must + * process or cancel all result sets from one batch before it can execute any other batch on that connection. Type: + * Boolean (or Expression with resultType boolean). + */ + private Object multipleActiveResultSets; + + /* + * If your application is connecting to an AlwaysOn availability group (AG) on different subnets, setting + * MultiSubnetFailover=true provides faster detection of and connection to the (currently) active server, used by + * recommended version. Type: Boolean (or Expression with resultType boolean). + */ + private Object multiSubnetFailover; + + /* + * The size in bytes of the network packets used to communicate with an instance of server, used by recommended + * version. Type: integer (or Expression with resultType integer). + */ + private Object packetSize; + + /* + * Indicate whether the connection will be pooled or explicitly opened every time that the connection is requested, + * used by recommended version. Type: Boolean (or Expression with resultType boolean). + */ + private Object pooling; + /* * The connection string. Type: string, SecureString or AzureKeyVaultSecretReference. */ private Object connectionString; + /* + * The type used for authentication. Type: string. + */ + private AmazonRdsForSqlServerAuthenticationType authenticationType; + /* * The on-premises Windows authentication user name. Type: string (or Expression with resultType string). */ @@ -65,6 +190,446 @@ public String getType() { return this.type; } + /** + * Get the server property: The name or network address of the instance of SQL Server to which to connect, used by + * recommended version. Type: string (or Expression with resultType string). + * + * @return the server value. + */ + public Object getServer() { + return this.server; + } + + /** + * Set the server property: The name or network address of the instance of SQL Server to which to connect, used by + * recommended version. Type: string (or Expression with resultType string). + * + * @param server the server value to set. + * @return the AmazonRdsForSqlServerLinkedService object itself. + */ + public AmazonRdsForSqlServerLinkedService setServer(Object server) { + this.server = server; + return this; + } + + /** + * Get the database property: The name of the database, used by recommended version. Type: string (or Expression + * with resultType string). + * + * @return the database value. + */ + public Object getDatabase() { + return this.database; + } + + /** + * Set the database property: The name of the database, used by recommended version. Type: string (or Expression + * with resultType string). + * + * @param database the database value to set. + * @return the AmazonRdsForSqlServerLinkedService object itself. + */ + public AmazonRdsForSqlServerLinkedService setDatabase(Object database) { + this.database = database; + return this; + } + + /** + * Get the encrypt property: Indicate whether TLS encryption is required for all data sent between the client and + * server, used by recommended version. Possible values are true/yes/mandatory, false/no/optional and strict. Type: + * string (or Expression with resultType string). + * + * @return the encrypt value. + */ + public Object getEncrypt() { + return this.encrypt; + } + + /** + * Set the encrypt property: Indicate whether TLS encryption is required for all data sent between the client and + * server, used by recommended version. Possible values are true/yes/mandatory, false/no/optional and strict. Type: + * string (or Expression with resultType string). + * + * @param encrypt the encrypt value to set. + * @return the AmazonRdsForSqlServerLinkedService object itself. + */ + public AmazonRdsForSqlServerLinkedService setEncrypt(Object encrypt) { + this.encrypt = encrypt; + return this; + } + + /** + * Get the trustServerCertificate property: Indicate whether the channel will be encrypted while bypassing walking + * the certificate chain to validate trust, used by recommended version. Type: Boolean (or Expression with + * resultType boolean). + * + * @return the trustServerCertificate value. + */ + public Object getTrustServerCertificate() { + return this.trustServerCertificate; + } + + /** + * Set the trustServerCertificate property: Indicate whether the channel will be encrypted while bypassing walking + * the certificate chain to validate trust, used by recommended version. Type: Boolean (or Expression with + * resultType boolean). + * + * @param trustServerCertificate the trustServerCertificate value to set. + * @return the AmazonRdsForSqlServerLinkedService object itself. + */ + public AmazonRdsForSqlServerLinkedService setTrustServerCertificate(Object trustServerCertificate) { + this.trustServerCertificate = trustServerCertificate; + return this; + } + + /** + * Get the hostNameInCertificate property: The host name to use when validating the server certificate for the + * connection. When not specified, the server name from the Data Source is used for certificate validation, used by + * recommended version. Type: string (or Expression with resultType string). + * + * @return the hostNameInCertificate value. + */ + public Object getHostNameInCertificate() { + return this.hostNameInCertificate; + } + + /** + * Set the hostNameInCertificate property: The host name to use when validating the server certificate for the + * connection. When not specified, the server name from the Data Source is used for certificate validation, used by + * recommended version. Type: string (or Expression with resultType string). + * + * @param hostNameInCertificate the hostNameInCertificate value to set. + * @return the AmazonRdsForSqlServerLinkedService object itself. + */ + public AmazonRdsForSqlServerLinkedService setHostNameInCertificate(Object hostNameInCertificate) { + this.hostNameInCertificate = hostNameInCertificate; + return this; + } + + /** + * Get the applicationIntent property: The application workload type when connecting to a server, used by + * recommended version. Possible values are ReadOnly and ReadWrite. Type: string (or Expression with resultType + * string). + * + * @return the applicationIntent value. + */ + public Object getApplicationIntent() { + return this.applicationIntent; + } + + /** + * Set the applicationIntent property: The application workload type when connecting to a server, used by + * recommended version. Possible values are ReadOnly and ReadWrite. Type: string (or Expression with resultType + * string). + * + * @param applicationIntent the applicationIntent value to set. + * @return the AmazonRdsForSqlServerLinkedService object itself. + */ + public AmazonRdsForSqlServerLinkedService setApplicationIntent(Object applicationIntent) { + this.applicationIntent = applicationIntent; + return this; + } + + /** + * Get the connectTimeout property: The length of time (in seconds) to wait for a connection to the server before + * terminating the attempt and generating an error, used by recommended version. Type: integer (or Expression with + * resultType integer). + * + * @return the connectTimeout value. + */ + public Object getConnectTimeout() { + return this.connectTimeout; + } + + /** + * Set the connectTimeout property: The length of time (in seconds) to wait for a connection to the server before + * terminating the attempt and generating an error, used by recommended version. Type: integer (or Expression with + * resultType integer). + * + * @param connectTimeout the connectTimeout value to set. + * @return the AmazonRdsForSqlServerLinkedService object itself. + */ + public AmazonRdsForSqlServerLinkedService setConnectTimeout(Object connectTimeout) { + this.connectTimeout = connectTimeout; + return this; + } + + /** + * Get the connectRetryCount property: The number of re-connections attempted after identifying that there was an + * idle connection failure, used by recommended version. This must be an integer between 0 and 255. Type: integer + * (or Expression with resultType integer). + * + * @return the connectRetryCount value. + */ + public Object getConnectRetryCount() { + return this.connectRetryCount; + } + + /** + * Set the connectRetryCount property: The number of re-connections attempted after identifying that there was an + * idle connection failure, used by recommended version. This must be an integer between 0 and 255. Type: integer + * (or Expression with resultType integer). + * + * @param connectRetryCount the connectRetryCount value to set. + * @return the AmazonRdsForSqlServerLinkedService object itself. + */ + public AmazonRdsForSqlServerLinkedService setConnectRetryCount(Object connectRetryCount) { + this.connectRetryCount = connectRetryCount; + return this; + } + + /** + * Get the connectRetryInterval property: The amount of time (in seconds) between each re-connection attempt after + * identifying that there was an idle connection failure, used by recommended version. This must be an integer + * between 1 and 60. Type: integer (or Expression with resultType integer). + * + * @return the connectRetryInterval value. + */ + public Object getConnectRetryInterval() { + return this.connectRetryInterval; + } + + /** + * Set the connectRetryInterval property: The amount of time (in seconds) between each re-connection attempt after + * identifying that there was an idle connection failure, used by recommended version. This must be an integer + * between 1 and 60. Type: integer (or Expression with resultType integer). + * + * @param connectRetryInterval the connectRetryInterval value to set. + * @return the AmazonRdsForSqlServerLinkedService object itself. + */ + public AmazonRdsForSqlServerLinkedService setConnectRetryInterval(Object connectRetryInterval) { + this.connectRetryInterval = connectRetryInterval; + return this; + } + + /** + * Get the loadBalanceTimeout property: The minimum time, in seconds, for the connection to live in the connection + * pool before being destroyed, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @return the loadBalanceTimeout value. + */ + public Object getLoadBalanceTimeout() { + return this.loadBalanceTimeout; + } + + /** + * Set the loadBalanceTimeout property: The minimum time, in seconds, for the connection to live in the connection + * pool before being destroyed, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @param loadBalanceTimeout the loadBalanceTimeout value to set. + * @return the AmazonRdsForSqlServerLinkedService object itself. + */ + public AmazonRdsForSqlServerLinkedService setLoadBalanceTimeout(Object loadBalanceTimeout) { + this.loadBalanceTimeout = loadBalanceTimeout; + return this; + } + + /** + * Get the commandTimeout property: The default wait time (in seconds) before terminating the attempt to execute a + * command and generating an error, used by recommended version. Type: integer (or Expression with resultType + * integer). + * + * @return the commandTimeout value. + */ + public Object getCommandTimeout() { + return this.commandTimeout; + } + + /** + * Set the commandTimeout property: The default wait time (in seconds) before terminating the attempt to execute a + * command and generating an error, used by recommended version. Type: integer (or Expression with resultType + * integer). + * + * @param commandTimeout the commandTimeout value to set. + * @return the AmazonRdsForSqlServerLinkedService object itself. + */ + public AmazonRdsForSqlServerLinkedService setCommandTimeout(Object commandTimeout) { + this.commandTimeout = commandTimeout; + return this; + } + + /** + * Get the integratedSecurity property: Indicate whether User ID and Password are specified in the connection (when + * false) or whether the current Windows account credentials are used for authentication (when true), used by + * recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @return the integratedSecurity value. + */ + public Object getIntegratedSecurity() { + return this.integratedSecurity; + } + + /** + * Set the integratedSecurity property: Indicate whether User ID and Password are specified in the connection (when + * false) or whether the current Windows account credentials are used for authentication (when true), used by + * recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @param integratedSecurity the integratedSecurity value to set. + * @return the AmazonRdsForSqlServerLinkedService object itself. + */ + public AmazonRdsForSqlServerLinkedService setIntegratedSecurity(Object integratedSecurity) { + this.integratedSecurity = integratedSecurity; + return this; + } + + /** + * Get the failoverPartner property: The name or address of the partner server to connect to if the primary server + * is down, used by recommended version. Type: string (or Expression with resultType string). + * + * @return the failoverPartner value. + */ + public Object getFailoverPartner() { + return this.failoverPartner; + } + + /** + * Set the failoverPartner property: The name or address of the partner server to connect to if the primary server + * is down, used by recommended version. Type: string (or Expression with resultType string). + * + * @param failoverPartner the failoverPartner value to set. + * @return the AmazonRdsForSqlServerLinkedService object itself. + */ + public AmazonRdsForSqlServerLinkedService setFailoverPartner(Object failoverPartner) { + this.failoverPartner = failoverPartner; + return this; + } + + /** + * Get the maxPoolSize property: The maximum number of connections allowed in the connection pool for this specific + * connection string, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @return the maxPoolSize value. + */ + public Object getMaxPoolSize() { + return this.maxPoolSize; + } + + /** + * Set the maxPoolSize property: The maximum number of connections allowed in the connection pool for this specific + * connection string, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @param maxPoolSize the maxPoolSize value to set. + * @return the AmazonRdsForSqlServerLinkedService object itself. + */ + public AmazonRdsForSqlServerLinkedService setMaxPoolSize(Object maxPoolSize) { + this.maxPoolSize = maxPoolSize; + return this; + } + + /** + * Get the minPoolSize property: The minimum number of connections allowed in the connection pool for this specific + * connection string, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @return the minPoolSize value. + */ + public Object getMinPoolSize() { + return this.minPoolSize; + } + + /** + * Set the minPoolSize property: The minimum number of connections allowed in the connection pool for this specific + * connection string, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @param minPoolSize the minPoolSize value to set. + * @return the AmazonRdsForSqlServerLinkedService object itself. + */ + public AmazonRdsForSqlServerLinkedService setMinPoolSize(Object minPoolSize) { + this.minPoolSize = minPoolSize; + return this; + } + + /** + * Get the multipleActiveResultSets property: When true, an application can maintain multiple active result sets + * (MARS). When false, an application must process or cancel all result sets from one batch before it can execute + * any other batch on that connection. Type: Boolean (or Expression with resultType boolean). + * + * @return the multipleActiveResultSets value. + */ + public Object getMultipleActiveResultSets() { + return this.multipleActiveResultSets; + } + + /** + * Set the multipleActiveResultSets property: When true, an application can maintain multiple active result sets + * (MARS). When false, an application must process or cancel all result sets from one batch before it can execute + * any other batch on that connection. Type: Boolean (or Expression with resultType boolean). + * + * @param multipleActiveResultSets the multipleActiveResultSets value to set. + * @return the AmazonRdsForSqlServerLinkedService object itself. + */ + public AmazonRdsForSqlServerLinkedService setMultipleActiveResultSets(Object multipleActiveResultSets) { + this.multipleActiveResultSets = multipleActiveResultSets; + return this; + } + + /** + * Get the multiSubnetFailover property: If your application is connecting to an AlwaysOn availability group (AG) on + * different subnets, setting MultiSubnetFailover=true provides faster detection of and connection to the + * (currently) active server, used by recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @return the multiSubnetFailover value. + */ + public Object getMultiSubnetFailover() { + return this.multiSubnetFailover; + } + + /** + * Set the multiSubnetFailover property: If your application is connecting to an AlwaysOn availability group (AG) on + * different subnets, setting MultiSubnetFailover=true provides faster detection of and connection to the + * (currently) active server, used by recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @param multiSubnetFailover the multiSubnetFailover value to set. + * @return the AmazonRdsForSqlServerLinkedService object itself. + */ + public AmazonRdsForSqlServerLinkedService setMultiSubnetFailover(Object multiSubnetFailover) { + this.multiSubnetFailover = multiSubnetFailover; + return this; + } + + /** + * Get the packetSize property: The size in bytes of the network packets used to communicate with an instance of + * server, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @return the packetSize value. + */ + public Object getPacketSize() { + return this.packetSize; + } + + /** + * Set the packetSize property: The size in bytes of the network packets used to communicate with an instance of + * server, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @param packetSize the packetSize value to set. + * @return the AmazonRdsForSqlServerLinkedService object itself. + */ + public AmazonRdsForSqlServerLinkedService setPacketSize(Object packetSize) { + this.packetSize = packetSize; + return this; + } + + /** + * Get the pooling property: Indicate whether the connection will be pooled or explicitly opened every time that the + * connection is requested, used by recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @return the pooling value. + */ + public Object getPooling() { + return this.pooling; + } + + /** + * Set the pooling property: Indicate whether the connection will be pooled or explicitly opened every time that the + * connection is requested, used by recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @param pooling the pooling value to set. + * @return the AmazonRdsForSqlServerLinkedService object itself. + */ + public AmazonRdsForSqlServerLinkedService setPooling(Object pooling) { + this.pooling = pooling; + return this; + } + /** * Get the connectionString property: The connection string. Type: string, SecureString or * AzureKeyVaultSecretReference. @@ -87,6 +652,27 @@ public AmazonRdsForSqlServerLinkedService setConnectionString(Object connectionS return this; } + /** + * Get the authenticationType property: The type used for authentication. Type: string. + * + * @return the authenticationType value. + */ + public AmazonRdsForSqlServerAuthenticationType getAuthenticationType() { + return this.authenticationType; + } + + /** + * Set the authenticationType property: The type used for authentication. Type: string. + * + * @param authenticationType the authenticationType value to set. + * @return the AmazonRdsForSqlServerLinkedService object itself. + */ + public AmazonRdsForSqlServerLinkedService + setAuthenticationType(AmazonRdsForSqlServerAuthenticationType authenticationType) { + this.authenticationType = authenticationType; + return this; + } + /** * Get the userName property: The on-premises Windows authentication user name. Type: string (or Expression with * resultType string). @@ -172,6 +758,15 @@ public SqlAlwaysEncryptedProperties getAlwaysEncryptedSettings() { return this; } + /** + * {@inheritDoc} + */ + @Override + public AmazonRdsForSqlServerLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -214,18 +809,60 @@ public AmazonRdsForSqlServerLinkedService setAnnotations(List annotation @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); jsonWriter.writeArrayField("annotations", getAnnotations(), (writer, element) -> writer.writeUntyped(element)); jsonWriter.writeStringField("type", this.type); - if (connectionString != null + if (server != null + || database != null + || encrypt != null + || trustServerCertificate != null + || hostNameInCertificate != null + || applicationIntent != null + || connectTimeout != null + || connectRetryCount != null + || connectRetryInterval != null + || loadBalanceTimeout != null + || commandTimeout != null + || integratedSecurity != null + || failoverPartner != null + || maxPoolSize != null + || minPoolSize != null + || multipleActiveResultSets != null + || multiSubnetFailover != null + || packetSize != null + || pooling != null + || connectionString != null + || authenticationType != null || userName != null || password != null || encryptedCredential != null || alwaysEncryptedSettings != null) { jsonWriter.writeStartObject("typeProperties"); + jsonWriter.writeUntypedField("server", this.server); + jsonWriter.writeUntypedField("database", this.database); + jsonWriter.writeUntypedField("encrypt", this.encrypt); + jsonWriter.writeUntypedField("trustServerCertificate", this.trustServerCertificate); + jsonWriter.writeUntypedField("hostNameInCertificate", this.hostNameInCertificate); + jsonWriter.writeUntypedField("applicationIntent", this.applicationIntent); + jsonWriter.writeUntypedField("connectTimeout", this.connectTimeout); + jsonWriter.writeUntypedField("connectRetryCount", this.connectRetryCount); + jsonWriter.writeUntypedField("connectRetryInterval", this.connectRetryInterval); + jsonWriter.writeUntypedField("loadBalanceTimeout", this.loadBalanceTimeout); + jsonWriter.writeUntypedField("commandTimeout", this.commandTimeout); + jsonWriter.writeUntypedField("integratedSecurity", this.integratedSecurity); + jsonWriter.writeUntypedField("failoverPartner", this.failoverPartner); + jsonWriter.writeUntypedField("maxPoolSize", this.maxPoolSize); + jsonWriter.writeUntypedField("minPoolSize", this.minPoolSize); + jsonWriter.writeUntypedField("multipleActiveResultSets", this.multipleActiveResultSets); + jsonWriter.writeUntypedField("multiSubnetFailover", this.multiSubnetFailover); + jsonWriter.writeUntypedField("packetSize", this.packetSize); + jsonWriter.writeUntypedField("pooling", this.pooling); jsonWriter.writeUntypedField("connectionString", this.connectionString); + jsonWriter.writeStringField("authenticationType", + this.authenticationType == null ? null : this.authenticationType.toString()); jsonWriter.writeUntypedField("userName", this.userName); jsonWriter.writeJsonField("password", this.password); jsonWriter.writeUntypedField("encryptedCredential", this.encryptedCredential); @@ -246,7 +883,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @param jsonReader The JsonReader being read. * @return An instance of AmazonRdsForSqlServerLinkedService 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 AmazonRdsForSqlServerLinkedService. */ public static AmazonRdsForSqlServerLinkedService fromJson(JsonReader jsonReader) throws IOException { @@ -258,7 +894,9 @@ public static AmazonRdsForSqlServerLinkedService fromJson(JsonReader jsonReader) String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAmazonRdsForSqlServerLinkedService .setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { @@ -277,8 +915,51 @@ public static AmazonRdsForSqlServerLinkedService fromJson(JsonReader jsonReader) fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectionString".equals(fieldName)) { + if ("server".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedService.server = reader.readUntyped(); + } else if ("database".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedService.database = reader.readUntyped(); + } else if ("encrypt".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedService.encrypt = reader.readUntyped(); + } else if ("trustServerCertificate".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedService.trustServerCertificate + = reader.readUntyped(); + } else if ("hostNameInCertificate".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedService.hostNameInCertificate = reader.readUntyped(); + } else if ("applicationIntent".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedService.applicationIntent = reader.readUntyped(); + } else if ("connectTimeout".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedService.connectTimeout = reader.readUntyped(); + } else if ("connectRetryCount".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedService.connectRetryCount = reader.readUntyped(); + } else if ("connectRetryInterval".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedService.connectRetryInterval = reader.readUntyped(); + } else if ("loadBalanceTimeout".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedService.loadBalanceTimeout = reader.readUntyped(); + } else if ("commandTimeout".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedService.commandTimeout = reader.readUntyped(); + } else if ("integratedSecurity".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedService.integratedSecurity = reader.readUntyped(); + } else if ("failoverPartner".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedService.failoverPartner = reader.readUntyped(); + } else if ("maxPoolSize".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedService.maxPoolSize = reader.readUntyped(); + } else if ("minPoolSize".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedService.minPoolSize = reader.readUntyped(); + } else if ("multipleActiveResultSets".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedService.multipleActiveResultSets + = reader.readUntyped(); + } else if ("multiSubnetFailover".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedService.multiSubnetFailover = reader.readUntyped(); + } else if ("packetSize".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedService.packetSize = reader.readUntyped(); + } else if ("pooling".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedService.pooling = reader.readUntyped(); + } else if ("connectionString".equals(fieldName)) { deserializedAmazonRdsForSqlServerLinkedService.connectionString = reader.readUntyped(); + } else if ("authenticationType".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedService.authenticationType + = AmazonRdsForSqlServerAuthenticationType.fromString(reader.getString()); } else if ("userName".equals(fieldName)) { deserializedAmazonRdsForSqlServerLinkedService.userName = reader.readUntyped(); } else if ("password".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AmazonRdsForSqlServerLinkedServiceTypeProperties.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AmazonRdsForSqlServerLinkedServiceTypeProperties.java new file mode 100644 index 000000000000..88e624be80b5 --- /dev/null +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AmazonRdsForSqlServerLinkedServiceTypeProperties.java @@ -0,0 +1,480 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.analytics.synapse.artifacts.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; + +/** + * SQL Server linked service properties. + */ +@Fluent +public final class AmazonRdsForSqlServerLinkedServiceTypeProperties extends SqlServerBaseLinkedServiceTypeProperties { + /* + * The connection string. Type: string, SecureString or AzureKeyVaultSecretReference. + */ + private Object connectionString; + + /* + * The type used for authentication. Type: string. + */ + private AmazonRdsForSqlServerAuthenticationType authenticationType; + + /* + * The on-premises Windows authentication user name. Type: string (or Expression with resultType string). + */ + private Object userName; + + /* + * The on-premises Windows authentication password. + */ + private SecretBase password; + + /* + * The encrypted credential used for authentication. Credentials are encrypted using the integration runtime + * credential manager. Type: string (or Expression with resultType string). + */ + private Object encryptedCredential; + + /* + * Sql always encrypted properties. + */ + private SqlAlwaysEncryptedProperties alwaysEncryptedSettings; + + /** + * Creates an instance of AmazonRdsForSqlServerLinkedServiceTypeProperties class. + */ + public AmazonRdsForSqlServerLinkedServiceTypeProperties() { + } + + /** + * Get the connectionString property: The connection string. Type: string, SecureString or + * AzureKeyVaultSecretReference. + * + * @return the connectionString value. + */ + public Object getConnectionString() { + return this.connectionString; + } + + /** + * Set the connectionString property: The connection string. Type: string, SecureString or + * AzureKeyVaultSecretReference. + * + * @param connectionString the connectionString value to set. + * @return the AmazonRdsForSqlServerLinkedServiceTypeProperties object itself. + */ + public AmazonRdsForSqlServerLinkedServiceTypeProperties setConnectionString(Object connectionString) { + this.connectionString = connectionString; + return this; + } + + /** + * Get the authenticationType property: The type used for authentication. Type: string. + * + * @return the authenticationType value. + */ + public AmazonRdsForSqlServerAuthenticationType getAuthenticationType() { + return this.authenticationType; + } + + /** + * Set the authenticationType property: The type used for authentication. Type: string. + * + * @param authenticationType the authenticationType value to set. + * @return the AmazonRdsForSqlServerLinkedServiceTypeProperties object itself. + */ + public AmazonRdsForSqlServerLinkedServiceTypeProperties + setAuthenticationType(AmazonRdsForSqlServerAuthenticationType authenticationType) { + this.authenticationType = authenticationType; + return this; + } + + /** + * Get the userName property: The on-premises Windows authentication user name. Type: string (or Expression with + * resultType string). + * + * @return the userName value. + */ + public Object getUserName() { + return this.userName; + } + + /** + * Set the userName property: The on-premises Windows authentication user name. Type: string (or Expression with + * resultType string). + * + * @param userName the userName value to set. + * @return the AmazonRdsForSqlServerLinkedServiceTypeProperties object itself. + */ + public AmazonRdsForSqlServerLinkedServiceTypeProperties setUserName(Object userName) { + this.userName = userName; + return this; + } + + /** + * Get the password property: The on-premises Windows authentication password. + * + * @return the password value. + */ + public SecretBase getPassword() { + return this.password; + } + + /** + * Set the password property: The on-premises Windows authentication password. + * + * @param password the password value to set. + * @return the AmazonRdsForSqlServerLinkedServiceTypeProperties object itself. + */ + public AmazonRdsForSqlServerLinkedServiceTypeProperties setPassword(SecretBase password) { + this.password = password; + return this; + } + + /** + * Get the encryptedCredential property: The encrypted credential used for authentication. Credentials are encrypted + * using the integration runtime credential manager. Type: string (or Expression with resultType string). + * + * @return the encryptedCredential value. + */ + public Object getEncryptedCredential() { + return this.encryptedCredential; + } + + /** + * Set the encryptedCredential property: The encrypted credential used for authentication. Credentials are encrypted + * using the integration runtime credential manager. Type: string (or Expression with resultType string). + * + * @param encryptedCredential the encryptedCredential value to set. + * @return the AmazonRdsForSqlServerLinkedServiceTypeProperties object itself. + */ + public AmazonRdsForSqlServerLinkedServiceTypeProperties setEncryptedCredential(Object encryptedCredential) { + this.encryptedCredential = encryptedCredential; + return this; + } + + /** + * Get the alwaysEncryptedSettings property: Sql always encrypted properties. + * + * @return the alwaysEncryptedSettings value. + */ + public SqlAlwaysEncryptedProperties getAlwaysEncryptedSettings() { + return this.alwaysEncryptedSettings; + } + + /** + * Set the alwaysEncryptedSettings property: Sql always encrypted properties. + * + * @param alwaysEncryptedSettings the alwaysEncryptedSettings value to set. + * @return the AmazonRdsForSqlServerLinkedServiceTypeProperties object itself. + */ + public AmazonRdsForSqlServerLinkedServiceTypeProperties + setAlwaysEncryptedSettings(SqlAlwaysEncryptedProperties alwaysEncryptedSettings) { + this.alwaysEncryptedSettings = alwaysEncryptedSettings; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AmazonRdsForSqlServerLinkedServiceTypeProperties setServer(Object server) { + super.setServer(server); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AmazonRdsForSqlServerLinkedServiceTypeProperties setDatabase(Object database) { + super.setDatabase(database); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AmazonRdsForSqlServerLinkedServiceTypeProperties setEncrypt(Object encrypt) { + super.setEncrypt(encrypt); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AmazonRdsForSqlServerLinkedServiceTypeProperties setTrustServerCertificate(Object trustServerCertificate) { + super.setTrustServerCertificate(trustServerCertificate); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AmazonRdsForSqlServerLinkedServiceTypeProperties setHostNameInCertificate(Object hostNameInCertificate) { + super.setHostNameInCertificate(hostNameInCertificate); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AmazonRdsForSqlServerLinkedServiceTypeProperties setApplicationIntent(Object applicationIntent) { + super.setApplicationIntent(applicationIntent); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AmazonRdsForSqlServerLinkedServiceTypeProperties setConnectTimeout(Object connectTimeout) { + super.setConnectTimeout(connectTimeout); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AmazonRdsForSqlServerLinkedServiceTypeProperties setConnectRetryCount(Object connectRetryCount) { + super.setConnectRetryCount(connectRetryCount); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AmazonRdsForSqlServerLinkedServiceTypeProperties setConnectRetryInterval(Object connectRetryInterval) { + super.setConnectRetryInterval(connectRetryInterval); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AmazonRdsForSqlServerLinkedServiceTypeProperties setLoadBalanceTimeout(Object loadBalanceTimeout) { + super.setLoadBalanceTimeout(loadBalanceTimeout); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AmazonRdsForSqlServerLinkedServiceTypeProperties setCommandTimeout(Object commandTimeout) { + super.setCommandTimeout(commandTimeout); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AmazonRdsForSqlServerLinkedServiceTypeProperties setIntegratedSecurity(Object integratedSecurity) { + super.setIntegratedSecurity(integratedSecurity); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AmazonRdsForSqlServerLinkedServiceTypeProperties setFailoverPartner(Object failoverPartner) { + super.setFailoverPartner(failoverPartner); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AmazonRdsForSqlServerLinkedServiceTypeProperties setMaxPoolSize(Object maxPoolSize) { + super.setMaxPoolSize(maxPoolSize); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AmazonRdsForSqlServerLinkedServiceTypeProperties setMinPoolSize(Object minPoolSize) { + super.setMinPoolSize(minPoolSize); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AmazonRdsForSqlServerLinkedServiceTypeProperties + setMultipleActiveResultSets(Object multipleActiveResultSets) { + super.setMultipleActiveResultSets(multipleActiveResultSets); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AmazonRdsForSqlServerLinkedServiceTypeProperties setMultiSubnetFailover(Object multiSubnetFailover) { + super.setMultiSubnetFailover(multiSubnetFailover); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AmazonRdsForSqlServerLinkedServiceTypeProperties setPacketSize(Object packetSize) { + super.setPacketSize(packetSize); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AmazonRdsForSqlServerLinkedServiceTypeProperties setPooling(Object pooling) { + super.setPooling(pooling); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeUntypedField("server", getServer()); + jsonWriter.writeUntypedField("database", getDatabase()); + jsonWriter.writeUntypedField("encrypt", getEncrypt()); + jsonWriter.writeUntypedField("trustServerCertificate", getTrustServerCertificate()); + jsonWriter.writeUntypedField("hostNameInCertificate", getHostNameInCertificate()); + jsonWriter.writeUntypedField("applicationIntent", getApplicationIntent()); + jsonWriter.writeUntypedField("connectTimeout", getConnectTimeout()); + jsonWriter.writeUntypedField("connectRetryCount", getConnectRetryCount()); + jsonWriter.writeUntypedField("connectRetryInterval", getConnectRetryInterval()); + jsonWriter.writeUntypedField("loadBalanceTimeout", getLoadBalanceTimeout()); + jsonWriter.writeUntypedField("commandTimeout", getCommandTimeout()); + jsonWriter.writeUntypedField("integratedSecurity", getIntegratedSecurity()); + jsonWriter.writeUntypedField("failoverPartner", getFailoverPartner()); + jsonWriter.writeUntypedField("maxPoolSize", getMaxPoolSize()); + jsonWriter.writeUntypedField("minPoolSize", getMinPoolSize()); + jsonWriter.writeUntypedField("multipleActiveResultSets", getMultipleActiveResultSets()); + jsonWriter.writeUntypedField("multiSubnetFailover", getMultiSubnetFailover()); + jsonWriter.writeUntypedField("packetSize", getPacketSize()); + jsonWriter.writeUntypedField("pooling", getPooling()); + jsonWriter.writeUntypedField("connectionString", this.connectionString); + jsonWriter.writeStringField("authenticationType", + this.authenticationType == null ? null : this.authenticationType.toString()); + jsonWriter.writeUntypedField("userName", this.userName); + jsonWriter.writeJsonField("password", this.password); + jsonWriter.writeUntypedField("encryptedCredential", this.encryptedCredential); + jsonWriter.writeJsonField("alwaysEncryptedSettings", this.alwaysEncryptedSettings); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AmazonRdsForSqlServerLinkedServiceTypeProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AmazonRdsForSqlServerLinkedServiceTypeProperties 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 AmazonRdsForSqlServerLinkedServiceTypeProperties. + */ + public static AmazonRdsForSqlServerLinkedServiceTypeProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AmazonRdsForSqlServerLinkedServiceTypeProperties deserializedAmazonRdsForSqlServerLinkedServiceTypeProperties + = new AmazonRdsForSqlServerLinkedServiceTypeProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("server".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedServiceTypeProperties.setServer(reader.readUntyped()); + } else if ("database".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedServiceTypeProperties.setDatabase(reader.readUntyped()); + } else if ("encrypt".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedServiceTypeProperties.setEncrypt(reader.readUntyped()); + } else if ("trustServerCertificate".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedServiceTypeProperties + .setTrustServerCertificate(reader.readUntyped()); + } else if ("hostNameInCertificate".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedServiceTypeProperties + .setHostNameInCertificate(reader.readUntyped()); + } else if ("applicationIntent".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedServiceTypeProperties + .setApplicationIntent(reader.readUntyped()); + } else if ("connectTimeout".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedServiceTypeProperties + .setConnectTimeout(reader.readUntyped()); + } else if ("connectRetryCount".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedServiceTypeProperties + .setConnectRetryCount(reader.readUntyped()); + } else if ("connectRetryInterval".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedServiceTypeProperties + .setConnectRetryInterval(reader.readUntyped()); + } else if ("loadBalanceTimeout".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedServiceTypeProperties + .setLoadBalanceTimeout(reader.readUntyped()); + } else if ("commandTimeout".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedServiceTypeProperties + .setCommandTimeout(reader.readUntyped()); + } else if ("integratedSecurity".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedServiceTypeProperties + .setIntegratedSecurity(reader.readUntyped()); + } else if ("failoverPartner".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedServiceTypeProperties + .setFailoverPartner(reader.readUntyped()); + } else if ("maxPoolSize".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedServiceTypeProperties.setMaxPoolSize(reader.readUntyped()); + } else if ("minPoolSize".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedServiceTypeProperties.setMinPoolSize(reader.readUntyped()); + } else if ("multipleActiveResultSets".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedServiceTypeProperties + .setMultipleActiveResultSets(reader.readUntyped()); + } else if ("multiSubnetFailover".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedServiceTypeProperties + .setMultiSubnetFailover(reader.readUntyped()); + } else if ("packetSize".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedServiceTypeProperties.setPacketSize(reader.readUntyped()); + } else if ("pooling".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedServiceTypeProperties.setPooling(reader.readUntyped()); + } else if ("connectionString".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedServiceTypeProperties.connectionString + = reader.readUntyped(); + } else if ("authenticationType".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedServiceTypeProperties.authenticationType + = AmazonRdsForSqlServerAuthenticationType.fromString(reader.getString()); + } else if ("userName".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedServiceTypeProperties.userName = reader.readUntyped(); + } else if ("password".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedServiceTypeProperties.password = SecretBase.fromJson(reader); + } else if ("encryptedCredential".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedServiceTypeProperties.encryptedCredential + = reader.readUntyped(); + } else if ("alwaysEncryptedSettings".equals(fieldName)) { + deserializedAmazonRdsForSqlServerLinkedServiceTypeProperties.alwaysEncryptedSettings + = SqlAlwaysEncryptedProperties.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedAmazonRdsForSqlServerLinkedServiceTypeProperties; + }); + } +} diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AmazonRedshiftLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AmazonRedshiftLinkedService.java index 7e43c5491559..c4c87c8fa7b3 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AmazonRedshiftLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AmazonRedshiftLinkedService.java @@ -201,6 +201,15 @@ public AmazonRedshiftLinkedService setEncryptedCredential(Object encryptedCreden return this; } + /** + * {@inheritDoc} + */ + @Override + public AmazonRedshiftLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -243,6 +252,7 @@ public AmazonRedshiftLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -288,7 +298,9 @@ public static AmazonRedshiftLinkedService fromJson(JsonReader jsonReader) throws String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAmazonRedshiftLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAmazonRedshiftLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedAmazonRedshiftLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AmazonS3LinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AmazonS3LinkedService.java index f0b02fcd9db6..e80259948055 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AmazonS3LinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AmazonS3LinkedService.java @@ -206,6 +206,15 @@ public AmazonS3LinkedService setEncryptedCredential(Object encryptedCredential) return this; } + /** + * {@inheritDoc} + */ + @Override + public AmazonS3LinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -248,6 +257,7 @@ public AmazonS3LinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -292,7 +302,9 @@ public static AmazonS3LinkedService fromJson(JsonReader jsonReader) throws IOExc String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAmazonS3LinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAmazonS3LinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedAmazonS3LinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AppFiguresLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AppFiguresLinkedService.java index e38cd5243d5c..f0bcbc13fb48 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AppFiguresLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AppFiguresLinkedService.java @@ -114,6 +114,15 @@ public AppFiguresLinkedService setClientKey(SecretBase clientKey) { return this; } + /** + * {@inheritDoc} + */ + @Override + public AppFiguresLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -156,6 +165,7 @@ public AppFiguresLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -193,7 +203,9 @@ public static AppFiguresLinkedService fromJson(JsonReader jsonReader) throws IOE String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAppFiguresLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAppFiguresLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedAppFiguresLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AsanaLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AsanaLinkedService.java index b53c7c358184..c7a6de76e760 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AsanaLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AsanaLinkedService.java @@ -92,6 +92,15 @@ public AsanaLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public AsanaLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -134,6 +143,7 @@ public AsanaLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -170,7 +180,9 @@ public static AsanaLinkedService fromJson(JsonReader jsonReader) throws IOExcept String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAsanaLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAsanaLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedAsanaLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureBatchLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureBatchLinkedService.java index a306dd194b41..ca3519b65fa6 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureBatchLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureBatchLinkedService.java @@ -217,6 +217,15 @@ public AzureBatchLinkedService setCredential(CredentialReference credential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public AzureBatchLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -259,6 +268,7 @@ public AzureBatchLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -306,7 +316,9 @@ public static AzureBatchLinkedService fromJson(JsonReader jsonReader) throws IOE String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAzureBatchLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAzureBatchLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedAzureBatchLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureBlobFSLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureBlobFSLinkedService.java index 47d511e7fa22..6cb9ee20c86e 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureBlobFSLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureBlobFSLinkedService.java @@ -376,6 +376,15 @@ public AzureBlobFSLinkedService setCredential(CredentialReference credential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public AzureBlobFSLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -418,6 +427,7 @@ public AzureBlobFSLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -474,7 +484,9 @@ public static AzureBlobFSLinkedService fromJson(JsonReader jsonReader) throws IO String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAzureBlobFSLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAzureBlobFSLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedAzureBlobFSLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureBlobStorageLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureBlobStorageLinkedService.java index 0b55269d433e..5f6f13bde41c 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureBlobStorageLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureBlobStorageLinkedService.java @@ -423,6 +423,15 @@ public AzureBlobStorageLinkedService setContainerUri(Object containerUri) { return this; } + /** + * {@inheritDoc} + */ + @Override + public AzureBlobStorageLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -465,6 +474,7 @@ public AzureBlobStorageLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -527,7 +537,9 @@ public static AzureBlobStorageLinkedService fromJson(JsonReader jsonReader) thro String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAzureBlobStorageLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAzureBlobStorageLinkedService .setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureDataExplorerLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureDataExplorerLinkedService.java index 158b83ca3bc0..b87c2f30c017 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureDataExplorerLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureDataExplorerLinkedService.java @@ -200,6 +200,15 @@ public AzureDataExplorerLinkedService setCredential(CredentialReference credenti return this; } + /** + * {@inheritDoc} + */ + @Override + public AzureDataExplorerLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -242,6 +251,7 @@ public AzureDataExplorerLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -288,7 +298,9 @@ public static AzureDataExplorerLinkedService fromJson(JsonReader jsonReader) thr String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAzureDataExplorerLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAzureDataExplorerLinkedService .setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureDataLakeAnalyticsLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureDataLakeAnalyticsLinkedService.java index 01ac7a209ee5..22f71b483c8f 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureDataLakeAnalyticsLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureDataLakeAnalyticsLinkedService.java @@ -260,6 +260,15 @@ public AzureDataLakeAnalyticsLinkedService setEncryptedCredential(Object encrypt return this; } + /** + * {@inheritDoc} + */ + @Override + public AzureDataLakeAnalyticsLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -302,6 +311,7 @@ public AzureDataLakeAnalyticsLinkedService setAnnotations(List annotatio @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -352,7 +362,9 @@ public static AzureDataLakeAnalyticsLinkedService fromJson(JsonReader jsonReader String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAzureDataLakeAnalyticsLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAzureDataLakeAnalyticsLinkedService .setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureDataLakeStoreLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureDataLakeStoreLinkedService.java index 8c9e2a55f26b..de2f876f8d51 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureDataLakeStoreLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureDataLakeStoreLinkedService.java @@ -314,6 +314,15 @@ public AzureDataLakeStoreLinkedService setCredential(CredentialReference credent return this; } + /** + * {@inheritDoc} + */ + @Override + public AzureDataLakeStoreLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -356,6 +365,7 @@ public AzureDataLakeStoreLinkedService setAnnotations(List annotations) @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -410,7 +420,9 @@ public static AzureDataLakeStoreLinkedService fromJson(JsonReader jsonReader) th String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAzureDataLakeStoreLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAzureDataLakeStoreLinkedService .setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureDatabricksDeltaLakeLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureDatabricksDeltaLakeLinkedService.java index 698daec6e6b7..700ba96a6f8a 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureDatabricksDeltaLakeLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureDatabricksDeltaLakeLinkedService.java @@ -178,6 +178,15 @@ public AzureDatabricksDeltaLakeLinkedService setCredential(CredentialReference c return this; } + /** + * {@inheritDoc} + */ + @Override + public AzureDatabricksDeltaLakeLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -220,6 +229,7 @@ public AzureDatabricksDeltaLakeLinkedService setAnnotations(List annotat @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -264,7 +274,9 @@ public static AzureDatabricksDeltaLakeLinkedService fromJson(JsonReader jsonRead String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAzureDatabricksDeltaLakeLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAzureDatabricksDeltaLakeLinkedService .setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureDatabricksLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureDatabricksLinkedService.java index 3771f64b2f5c..f928819f7db6 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureDatabricksLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureDatabricksLinkedService.java @@ -581,6 +581,15 @@ public AzureDatabricksLinkedService setCredential(CredentialReference credential return this; } + /** + * {@inheritDoc} + */ + @Override + public AzureDatabricksLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -623,6 +632,7 @@ public AzureDatabricksLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -697,7 +707,9 @@ public static AzureDatabricksLinkedService fromJson(JsonReader jsonReader) throw String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAzureDatabricksLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAzureDatabricksLinkedService .setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureFileStorageLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureFileStorageLinkedService.java index 6cd0c66cf637..bcbfa1984d94 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureFileStorageLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureFileStorageLinkedService.java @@ -77,6 +77,17 @@ public class AzureFileStorageLinkedService extends LinkedService { */ private Object encryptedCredential; + /* + * File service endpoint of the Azure File Storage resource. It is mutually exclusive with connectionString, sasUri + * property. + */ + private Object serviceEndpoint; + + /* + * The credential reference containing authentication information. + */ + private CredentialReference credential; + /** * Creates an instance of AzureFileStorageLinkedService class. */ @@ -303,6 +314,57 @@ public AzureFileStorageLinkedService setEncryptedCredential(Object encryptedCred return this; } + /** + * Get the serviceEndpoint property: File service endpoint of the Azure File Storage resource. It is mutually + * exclusive with connectionString, sasUri property. + * + * @return the serviceEndpoint value. + */ + public Object getServiceEndpoint() { + return this.serviceEndpoint; + } + + /** + * Set the serviceEndpoint property: File service endpoint of the Azure File Storage resource. It is mutually + * exclusive with connectionString, sasUri property. + * + * @param serviceEndpoint the serviceEndpoint value to set. + * @return the AzureFileStorageLinkedService object itself. + */ + public AzureFileStorageLinkedService setServiceEndpoint(Object serviceEndpoint) { + this.serviceEndpoint = serviceEndpoint; + return this; + } + + /** + * Get the credential property: The credential reference containing authentication information. + * + * @return the credential value. + */ + public CredentialReference getCredential() { + return this.credential; + } + + /** + * Set the credential property: The credential reference containing authentication information. + * + * @param credential the credential value to set. + * @return the AzureFileStorageLinkedService object itself. + */ + public AzureFileStorageLinkedService setCredential(CredentialReference credential) { + this.credential = credential; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureFileStorageLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -345,6 +407,7 @@ public AzureFileStorageLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -359,7 +422,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { || sasToken != null || fileShare != null || snapshot != null - || encryptedCredential != null) { + || encryptedCredential != null + || serviceEndpoint != null + || credential != null) { jsonWriter.writeStartObject("typeProperties"); jsonWriter.writeUntypedField("host", this.host); jsonWriter.writeUntypedField("userId", this.userId); @@ -371,6 +436,8 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeUntypedField("fileShare", this.fileShare); jsonWriter.writeUntypedField("snapshot", this.snapshot); jsonWriter.writeUntypedField("encryptedCredential", this.encryptedCredential); + jsonWriter.writeUntypedField("serviceEndpoint", this.serviceEndpoint); + jsonWriter.writeJsonField("credential", this.credential); jsonWriter.writeEndObject(); } if (getAdditionalProperties() != null) { @@ -399,7 +466,9 @@ public static AzureFileStorageLinkedService fromJson(JsonReader jsonReader) thro String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAzureFileStorageLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAzureFileStorageLinkedService .setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { @@ -440,6 +509,10 @@ public static AzureFileStorageLinkedService fromJson(JsonReader jsonReader) thro deserializedAzureFileStorageLinkedService.snapshot = reader.readUntyped(); } else if ("encryptedCredential".equals(fieldName)) { deserializedAzureFileStorageLinkedService.encryptedCredential = reader.readUntyped(); + } else if ("serviceEndpoint".equals(fieldName)) { + deserializedAzureFileStorageLinkedService.serviceEndpoint = reader.readUntyped(); + } else if ("credential".equals(fieldName)) { + deserializedAzureFileStorageLinkedService.credential = CredentialReference.fromJson(reader); } else { reader.skipChildren(); } diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureFunctionLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureFunctionLinkedService.java index 4f88020be7c7..0d0a1a650ca9 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureFunctionLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureFunctionLinkedService.java @@ -197,6 +197,15 @@ public AzureFunctionLinkedService setAuthentication(Object authentication) { return this; } + /** + * {@inheritDoc} + */ + @Override + public AzureFunctionLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -239,6 +248,7 @@ public AzureFunctionLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -284,7 +294,9 @@ public static AzureFunctionLinkedService fromJson(JsonReader jsonReader) throws String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAzureFunctionLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAzureFunctionLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedAzureFunctionLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureKeyVaultLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureKeyVaultLinkedService.java index 6c3882a22d7e..02e1dfd53af1 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureKeyVaultLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureKeyVaultLinkedService.java @@ -92,6 +92,15 @@ public AzureKeyVaultLinkedService setCredential(CredentialReference credential) return this; } + /** + * {@inheritDoc} + */ + @Override + public AzureKeyVaultLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -134,6 +143,7 @@ public AzureKeyVaultLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -170,7 +180,9 @@ public static AzureKeyVaultLinkedService fromJson(JsonReader jsonReader) throws String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAzureKeyVaultLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAzureKeyVaultLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedAzureKeyVaultLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureMLLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureMLLinkedService.java index 872bb9e2c7de..89ec05869d22 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureMLLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureMLLinkedService.java @@ -260,6 +260,15 @@ public AzureMLLinkedService setAuthentication(Object authentication) { return this; } + /** + * {@inheritDoc} + */ + @Override + public AzureMLLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -302,6 +311,7 @@ public AzureMLLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -351,7 +361,9 @@ public static AzureMLLinkedService fromJson(JsonReader jsonReader) throws IOExce String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAzureMLLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAzureMLLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedAzureMLLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureMLServiceLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureMLServiceLinkedService.java index 52c665d97869..ac60ec277f64 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureMLServiceLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureMLServiceLinkedService.java @@ -260,6 +260,15 @@ public AzureMLServiceLinkedService setEncryptedCredential(Object encryptedCreden return this; } + /** + * {@inheritDoc} + */ + @Override + public AzureMLServiceLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -302,6 +311,7 @@ public AzureMLServiceLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -351,7 +361,9 @@ public static AzureMLServiceLinkedService fromJson(JsonReader jsonReader) throws String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAzureMLServiceLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAzureMLServiceLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedAzureMLServiceLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureMariaDBLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureMariaDBLinkedService.java index 778c07835d92..7a7b2f871977 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureMariaDBLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureMariaDBLinkedService.java @@ -119,6 +119,15 @@ public AzureMariaDBLinkedService setEncryptedCredential(Object encryptedCredenti return this; } + /** + * {@inheritDoc} + */ + @Override + public AzureMariaDBLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -161,6 +170,7 @@ public AzureMariaDBLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -197,7 +207,9 @@ public static AzureMariaDBLinkedService fromJson(JsonReader jsonReader) throws I String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAzureMariaDBLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAzureMariaDBLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedAzureMariaDBLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureMySqlLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureMySqlLinkedService.java index fd9aceab2c5d..bcf2103d4cb6 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureMySqlLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureMySqlLinkedService.java @@ -119,6 +119,15 @@ public AzureMySqlLinkedService setEncryptedCredential(Object encryptedCredential return this; } + /** + * {@inheritDoc} + */ + @Override + public AzureMySqlLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -161,6 +170,7 @@ public AzureMySqlLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -198,7 +208,9 @@ public static AzureMySqlLinkedService fromJson(JsonReader jsonReader) throws IOE String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAzureMySqlLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAzureMySqlLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedAzureMySqlLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzurePostgreSqlLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzurePostgreSqlLinkedService.java index 76b06d096d88..0afc445527ef 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzurePostgreSqlLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzurePostgreSqlLinkedService.java @@ -28,6 +28,65 @@ public class AzurePostgreSqlLinkedService extends LinkedService { */ private Object connectionString; + /* + * Server name for connection. Type: string. + */ + private Object server; + + /* + * The port for the connection. Type: integer. + */ + private Object port; + + /* + * Username for authentication. Type: string. + */ + private Object username; + + /* + * Database name for connection. Type: string. + */ + private Object database; + + /* + * SSL mode for connection. Type: integer. 0: disable, 1:allow, 2: prefer, 3: require, 4: verify-ca, 5: verify-full. + * Type: integer. + */ + private Object sslMode; + + /* + * The time to wait (in seconds) while trying to establish a connection before terminating the attempt and + * generating an error. Type: integer. + */ + private Object timeout; + + /* + * The time to wait (in seconds) while trying to execute a command before terminating the attempt and generating an + * error. Set to zero for infinity. Type: integer. + */ + private Object commandTimeout; + + /* + * Whether to trust the server certificate without validating it. Type: boolean. + */ + private Object trustServerCertificate; + + /* + * Determines the size of the internal buffer uses when reading. Increasing may improve performance if transferring + * large values from the database. Type: integer. + */ + private Object readBufferSize; + + /* + * Gets or sets the session timezone. Type: string. + */ + private Object timezone; + + /* + * Gets or sets the .NET encoding that will be used to encode/decode PostgreSQL string data. Type: string + */ + private Object encoding; + /* * The Azure key vault secret reference of password in connection string. */ @@ -39,6 +98,53 @@ public class AzurePostgreSqlLinkedService extends LinkedService { */ private Object encryptedCredential; + /* + * The ID of the service principal used to authenticate against Azure Database for PostgreSQL Flexible server. Type: + * string (or Expression with resultType string). + */ + private Object servicePrincipalId; + + /* + * The key of the service principal used to authenticate against Azure Database for PostgreSQL Flexible server. + */ + private SecretBase servicePrincipalKey; + + /* + * The service principal credential type to use in Server-To-Server authentication. 'ServicePrincipalKey' for + * key/secret, 'ServicePrincipalCert' for certificate. Type: string (or Expression with resultType string). + */ + private Object servicePrincipalCredentialType; + + /* + * Specify the base64 encoded certificate of your application registered in Azure Active Directory. Type: string (or + * Expression with resultType string). + */ + private SecretBase servicePrincipalEmbeddedCert; + + /* + * Specify the password of your certificate if your certificate has a password and you are using AadServicePrincipal + * authentication. Type: string (or Expression with resultType string). + */ + private SecretBase servicePrincipalEmbeddedCertPassword; + + /* + * The name or ID of the tenant to which the service principal belongs. Type: string (or Expression with resultType + * string). + */ + private Object tenant; + + /* + * Indicates the azure cloud type of the service principle auth. Allowed values are AzurePublic, AzureChina, + * AzureUsGovernment, AzureGermany. Default value is the data factory regions’ cloud type. Type: string (or + * Expression with resultType string). + */ + private Object azureCloudType; + + /* + * The credential reference containing authentication information. + */ + private CredentialReference credential; + /** * Creates an instance of AzurePostgreSqlLinkedService class. */ @@ -77,6 +183,238 @@ public AzurePostgreSqlLinkedService setConnectionString(Object connectionString) return this; } + /** + * Get the server property: Server name for connection. Type: string. + * + * @return the server value. + */ + public Object getServer() { + return this.server; + } + + /** + * Set the server property: Server name for connection. Type: string. + * + * @param server the server value to set. + * @return the AzurePostgreSqlLinkedService object itself. + */ + public AzurePostgreSqlLinkedService setServer(Object server) { + this.server = server; + return this; + } + + /** + * Get the port property: The port for the connection. Type: integer. + * + * @return the port value. + */ + public Object getPort() { + return this.port; + } + + /** + * Set the port property: The port for the connection. Type: integer. + * + * @param port the port value to set. + * @return the AzurePostgreSqlLinkedService object itself. + */ + public AzurePostgreSqlLinkedService setPort(Object port) { + this.port = port; + return this; + } + + /** + * Get the username property: Username for authentication. Type: string. + * + * @return the username value. + */ + public Object getUsername() { + return this.username; + } + + /** + * Set the username property: Username for authentication. Type: string. + * + * @param username the username value to set. + * @return the AzurePostgreSqlLinkedService object itself. + */ + public AzurePostgreSqlLinkedService setUsername(Object username) { + this.username = username; + return this; + } + + /** + * Get the database property: Database name for connection. Type: string. + * + * @return the database value. + */ + public Object getDatabase() { + return this.database; + } + + /** + * Set the database property: Database name for connection. Type: string. + * + * @param database the database value to set. + * @return the AzurePostgreSqlLinkedService object itself. + */ + public AzurePostgreSqlLinkedService setDatabase(Object database) { + this.database = database; + return this; + } + + /** + * Get the sslMode property: SSL mode for connection. Type: integer. 0: disable, 1:allow, 2: prefer, 3: require, 4: + * verify-ca, 5: verify-full. Type: integer. + * + * @return the sslMode value. + */ + public Object getSslMode() { + return this.sslMode; + } + + /** + * Set the sslMode property: SSL mode for connection. Type: integer. 0: disable, 1:allow, 2: prefer, 3: require, 4: + * verify-ca, 5: verify-full. Type: integer. + * + * @param sslMode the sslMode value to set. + * @return the AzurePostgreSqlLinkedService object itself. + */ + public AzurePostgreSqlLinkedService setSslMode(Object sslMode) { + this.sslMode = sslMode; + return this; + } + + /** + * Get the timeout property: The time to wait (in seconds) while trying to establish a connection before terminating + * the attempt and generating an error. Type: integer. + * + * @return the timeout value. + */ + public Object getTimeout() { + return this.timeout; + } + + /** + * Set the timeout property: The time to wait (in seconds) while trying to establish a connection before terminating + * the attempt and generating an error. Type: integer. + * + * @param timeout the timeout value to set. + * @return the AzurePostgreSqlLinkedService object itself. + */ + public AzurePostgreSqlLinkedService setTimeout(Object timeout) { + this.timeout = timeout; + return this; + } + + /** + * Get the commandTimeout property: The time to wait (in seconds) while trying to execute a command before + * terminating the attempt and generating an error. Set to zero for infinity. Type: integer. + * + * @return the commandTimeout value. + */ + public Object getCommandTimeout() { + return this.commandTimeout; + } + + /** + * Set the commandTimeout property: The time to wait (in seconds) while trying to execute a command before + * terminating the attempt and generating an error. Set to zero for infinity. Type: integer. + * + * @param commandTimeout the commandTimeout value to set. + * @return the AzurePostgreSqlLinkedService object itself. + */ + public AzurePostgreSqlLinkedService setCommandTimeout(Object commandTimeout) { + this.commandTimeout = commandTimeout; + return this; + } + + /** + * Get the trustServerCertificate property: Whether to trust the server certificate without validating it. Type: + * boolean. + * + * @return the trustServerCertificate value. + */ + public Object getTrustServerCertificate() { + return this.trustServerCertificate; + } + + /** + * Set the trustServerCertificate property: Whether to trust the server certificate without validating it. Type: + * boolean. + * + * @param trustServerCertificate the trustServerCertificate value to set. + * @return the AzurePostgreSqlLinkedService object itself. + */ + public AzurePostgreSqlLinkedService setTrustServerCertificate(Object trustServerCertificate) { + this.trustServerCertificate = trustServerCertificate; + return this; + } + + /** + * Get the readBufferSize property: Determines the size of the internal buffer uses when reading. Increasing may + * improve performance if transferring large values from the database. Type: integer. + * + * @return the readBufferSize value. + */ + public Object getReadBufferSize() { + return this.readBufferSize; + } + + /** + * Set the readBufferSize property: Determines the size of the internal buffer uses when reading. Increasing may + * improve performance if transferring large values from the database. Type: integer. + * + * @param readBufferSize the readBufferSize value to set. + * @return the AzurePostgreSqlLinkedService object itself. + */ + public AzurePostgreSqlLinkedService setReadBufferSize(Object readBufferSize) { + this.readBufferSize = readBufferSize; + return this; + } + + /** + * Get the timezone property: Gets or sets the session timezone. Type: string. + * + * @return the timezone value. + */ + public Object getTimezone() { + return this.timezone; + } + + /** + * Set the timezone property: Gets or sets the session timezone. Type: string. + * + * @param timezone the timezone value to set. + * @return the AzurePostgreSqlLinkedService object itself. + */ + public AzurePostgreSqlLinkedService setTimezone(Object timezone) { + this.timezone = timezone; + return this; + } + + /** + * Get the encoding property: Gets or sets the .NET encoding that will be used to encode/decode PostgreSQL string + * data. Type: string. + * + * @return the encoding value. + */ + public Object getEncoding() { + return this.encoding; + } + + /** + * Set the encoding property: Gets or sets the .NET encoding that will be used to encode/decode PostgreSQL string + * data. Type: string. + * + * @param encoding the encoding value to set. + * @return the AzurePostgreSqlLinkedService object itself. + */ + public AzurePostgreSqlLinkedService setEncoding(Object encoding) { + this.encoding = encoding; + return this; + } + /** * Get the password property: The Azure key vault secret reference of password in connection string. * @@ -119,6 +457,196 @@ public AzurePostgreSqlLinkedService setEncryptedCredential(Object encryptedCrede return this; } + /** + * Get the servicePrincipalId property: The ID of the service principal used to authenticate against Azure Database + * for PostgreSQL Flexible server. Type: string (or Expression with resultType string). + * + * @return the servicePrincipalId value. + */ + public Object getServicePrincipalId() { + return this.servicePrincipalId; + } + + /** + * Set the servicePrincipalId property: The ID of the service principal used to authenticate against Azure Database + * for PostgreSQL Flexible server. Type: string (or Expression with resultType string). + * + * @param servicePrincipalId the servicePrincipalId value to set. + * @return the AzurePostgreSqlLinkedService object itself. + */ + public AzurePostgreSqlLinkedService setServicePrincipalId(Object servicePrincipalId) { + this.servicePrincipalId = servicePrincipalId; + return this; + } + + /** + * Get the servicePrincipalKey property: The key of the service principal used to authenticate against Azure + * Database for PostgreSQL Flexible server. + * + * @return the servicePrincipalKey value. + */ + public SecretBase getServicePrincipalKey() { + return this.servicePrincipalKey; + } + + /** + * Set the servicePrincipalKey property: The key of the service principal used to authenticate against Azure + * Database for PostgreSQL Flexible server. + * + * @param servicePrincipalKey the servicePrincipalKey value to set. + * @return the AzurePostgreSqlLinkedService object itself. + */ + public AzurePostgreSqlLinkedService setServicePrincipalKey(SecretBase servicePrincipalKey) { + this.servicePrincipalKey = servicePrincipalKey; + return this; + } + + /** + * Get the servicePrincipalCredentialType property: The service principal credential type to use in Server-To-Server + * authentication. 'ServicePrincipalKey' for key/secret, 'ServicePrincipalCert' for certificate. Type: string (or + * Expression with resultType string). + * + * @return the servicePrincipalCredentialType value. + */ + public Object getServicePrincipalCredentialType() { + return this.servicePrincipalCredentialType; + } + + /** + * Set the servicePrincipalCredentialType property: The service principal credential type to use in Server-To-Server + * authentication. 'ServicePrincipalKey' for key/secret, 'ServicePrincipalCert' for certificate. Type: string (or + * Expression with resultType string). + * + * @param servicePrincipalCredentialType the servicePrincipalCredentialType value to set. + * @return the AzurePostgreSqlLinkedService object itself. + */ + public AzurePostgreSqlLinkedService setServicePrincipalCredentialType(Object servicePrincipalCredentialType) { + this.servicePrincipalCredentialType = servicePrincipalCredentialType; + return this; + } + + /** + * Get the servicePrincipalEmbeddedCert property: Specify the base64 encoded certificate of your application + * registered in Azure Active Directory. Type: string (or Expression with resultType string). + * + * @return the servicePrincipalEmbeddedCert value. + */ + public SecretBase getServicePrincipalEmbeddedCert() { + return this.servicePrincipalEmbeddedCert; + } + + /** + * Set the servicePrincipalEmbeddedCert property: Specify the base64 encoded certificate of your application + * registered in Azure Active Directory. Type: string (or Expression with resultType string). + * + * @param servicePrincipalEmbeddedCert the servicePrincipalEmbeddedCert value to set. + * @return the AzurePostgreSqlLinkedService object itself. + */ + public AzurePostgreSqlLinkedService setServicePrincipalEmbeddedCert(SecretBase servicePrincipalEmbeddedCert) { + this.servicePrincipalEmbeddedCert = servicePrincipalEmbeddedCert; + return this; + } + + /** + * Get the servicePrincipalEmbeddedCertPassword property: Specify the password of your certificate if your + * certificate has a password and you are using AadServicePrincipal authentication. Type: string (or Expression with + * resultType string). + * + * @return the servicePrincipalEmbeddedCertPassword value. + */ + public SecretBase getServicePrincipalEmbeddedCertPassword() { + return this.servicePrincipalEmbeddedCertPassword; + } + + /** + * Set the servicePrincipalEmbeddedCertPassword property: Specify the password of your certificate if your + * certificate has a password and you are using AadServicePrincipal authentication. Type: string (or Expression with + * resultType string). + * + * @param servicePrincipalEmbeddedCertPassword the servicePrincipalEmbeddedCertPassword value to set. + * @return the AzurePostgreSqlLinkedService object itself. + */ + public AzurePostgreSqlLinkedService + setServicePrincipalEmbeddedCertPassword(SecretBase servicePrincipalEmbeddedCertPassword) { + this.servicePrincipalEmbeddedCertPassword = servicePrincipalEmbeddedCertPassword; + return this; + } + + /** + * Get the tenant property: The name or ID of the tenant to which the service principal belongs. Type: string (or + * Expression with resultType string). + * + * @return the tenant value. + */ + public Object getTenant() { + return this.tenant; + } + + /** + * Set the tenant property: The name or ID of the tenant to which the service principal belongs. Type: string (or + * Expression with resultType string). + * + * @param tenant the tenant value to set. + * @return the AzurePostgreSqlLinkedService object itself. + */ + public AzurePostgreSqlLinkedService setTenant(Object tenant) { + this.tenant = tenant; + return this; + } + + /** + * Get the azureCloudType property: Indicates the azure cloud type of the service principle auth. Allowed values are + * AzurePublic, AzureChina, AzureUsGovernment, AzureGermany. Default value is the data factory regions’ cloud type. + * Type: string (or Expression with resultType string). + * + * @return the azureCloudType value. + */ + public Object getAzureCloudType() { + return this.azureCloudType; + } + + /** + * Set the azureCloudType property: Indicates the azure cloud type of the service principle auth. Allowed values are + * AzurePublic, AzureChina, AzureUsGovernment, AzureGermany. Default value is the data factory regions’ cloud type. + * Type: string (or Expression with resultType string). + * + * @param azureCloudType the azureCloudType value to set. + * @return the AzurePostgreSqlLinkedService object itself. + */ + public AzurePostgreSqlLinkedService setAzureCloudType(Object azureCloudType) { + this.azureCloudType = azureCloudType; + return this; + } + + /** + * Get the credential property: The credential reference containing authentication information. + * + * @return the credential value. + */ + public CredentialReference getCredential() { + return this.credential; + } + + /** + * Set the credential property: The credential reference containing authentication information. + * + * @param credential the credential value to set. + * @return the AzurePostgreSqlLinkedService object itself. + */ + public AzurePostgreSqlLinkedService setCredential(CredentialReference credential) { + this.credential = credential; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzurePostgreSqlLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -161,16 +689,58 @@ public AzurePostgreSqlLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); jsonWriter.writeArrayField("annotations", getAnnotations(), (writer, element) -> writer.writeUntyped(element)); jsonWriter.writeStringField("type", this.type); - if (connectionString != null || password != null || encryptedCredential != null) { + if (connectionString != null + || server != null + || port != null + || username != null + || database != null + || sslMode != null + || timeout != null + || commandTimeout != null + || trustServerCertificate != null + || readBufferSize != null + || timezone != null + || encoding != null + || password != null + || encryptedCredential != null + || servicePrincipalId != null + || servicePrincipalKey != null + || servicePrincipalCredentialType != null + || servicePrincipalEmbeddedCert != null + || servicePrincipalEmbeddedCertPassword != null + || tenant != null + || azureCloudType != null + || credential != null) { jsonWriter.writeStartObject("typeProperties"); jsonWriter.writeUntypedField("connectionString", this.connectionString); + jsonWriter.writeUntypedField("server", this.server); + jsonWriter.writeUntypedField("port", this.port); + jsonWriter.writeUntypedField("username", this.username); + jsonWriter.writeUntypedField("database", this.database); + jsonWriter.writeUntypedField("sslMode", this.sslMode); + jsonWriter.writeUntypedField("timeout", this.timeout); + jsonWriter.writeUntypedField("commandTimeout", this.commandTimeout); + jsonWriter.writeUntypedField("trustServerCertificate", this.trustServerCertificate); + jsonWriter.writeUntypedField("readBufferSize", this.readBufferSize); + jsonWriter.writeUntypedField("timezone", this.timezone); + jsonWriter.writeUntypedField("encoding", this.encoding); jsonWriter.writeJsonField("password", this.password); jsonWriter.writeUntypedField("encryptedCredential", this.encryptedCredential); + jsonWriter.writeUntypedField("servicePrincipalId", this.servicePrincipalId); + jsonWriter.writeJsonField("servicePrincipalKey", this.servicePrincipalKey); + jsonWriter.writeUntypedField("servicePrincipalCredentialType", this.servicePrincipalCredentialType); + jsonWriter.writeJsonField("servicePrincipalEmbeddedCert", this.servicePrincipalEmbeddedCert); + jsonWriter.writeJsonField("servicePrincipalEmbeddedCertPassword", + this.servicePrincipalEmbeddedCertPassword); + jsonWriter.writeUntypedField("tenant", this.tenant); + jsonWriter.writeUntypedField("azureCloudType", this.azureCloudType); + jsonWriter.writeJsonField("credential", this.credential); jsonWriter.writeEndObject(); } if (getAdditionalProperties() != null) { @@ -197,7 +767,9 @@ public static AzurePostgreSqlLinkedService fromJson(JsonReader jsonReader) throw String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAzurePostgreSqlLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAzurePostgreSqlLinkedService .setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { @@ -218,11 +790,52 @@ public static AzurePostgreSqlLinkedService fromJson(JsonReader jsonReader) throw if ("connectionString".equals(fieldName)) { deserializedAzurePostgreSqlLinkedService.connectionString = reader.readUntyped(); + } else if ("server".equals(fieldName)) { + deserializedAzurePostgreSqlLinkedService.server = reader.readUntyped(); + } else if ("port".equals(fieldName)) { + deserializedAzurePostgreSqlLinkedService.port = reader.readUntyped(); + } else if ("username".equals(fieldName)) { + deserializedAzurePostgreSqlLinkedService.username = reader.readUntyped(); + } else if ("database".equals(fieldName)) { + deserializedAzurePostgreSqlLinkedService.database = reader.readUntyped(); + } else if ("sslMode".equals(fieldName)) { + deserializedAzurePostgreSqlLinkedService.sslMode = reader.readUntyped(); + } else if ("timeout".equals(fieldName)) { + deserializedAzurePostgreSqlLinkedService.timeout = reader.readUntyped(); + } else if ("commandTimeout".equals(fieldName)) { + deserializedAzurePostgreSqlLinkedService.commandTimeout = reader.readUntyped(); + } else if ("trustServerCertificate".equals(fieldName)) { + deserializedAzurePostgreSqlLinkedService.trustServerCertificate = reader.readUntyped(); + } else if ("readBufferSize".equals(fieldName)) { + deserializedAzurePostgreSqlLinkedService.readBufferSize = reader.readUntyped(); + } else if ("timezone".equals(fieldName)) { + deserializedAzurePostgreSqlLinkedService.timezone = reader.readUntyped(); + } else if ("encoding".equals(fieldName)) { + deserializedAzurePostgreSqlLinkedService.encoding = reader.readUntyped(); } else if ("password".equals(fieldName)) { deserializedAzurePostgreSqlLinkedService.password = AzureKeyVaultSecretReference.fromJson(reader); } else if ("encryptedCredential".equals(fieldName)) { deserializedAzurePostgreSqlLinkedService.encryptedCredential = reader.readUntyped(); + } else if ("servicePrincipalId".equals(fieldName)) { + deserializedAzurePostgreSqlLinkedService.servicePrincipalId = reader.readUntyped(); + } else if ("servicePrincipalKey".equals(fieldName)) { + deserializedAzurePostgreSqlLinkedService.servicePrincipalKey = SecretBase.fromJson(reader); + } else if ("servicePrincipalCredentialType".equals(fieldName)) { + deserializedAzurePostgreSqlLinkedService.servicePrincipalCredentialType + = reader.readUntyped(); + } else if ("servicePrincipalEmbeddedCert".equals(fieldName)) { + deserializedAzurePostgreSqlLinkedService.servicePrincipalEmbeddedCert + = SecretBase.fromJson(reader); + } else if ("servicePrincipalEmbeddedCertPassword".equals(fieldName)) { + deserializedAzurePostgreSqlLinkedService.servicePrincipalEmbeddedCertPassword + = SecretBase.fromJson(reader); + } else if ("tenant".equals(fieldName)) { + deserializedAzurePostgreSqlLinkedService.tenant = reader.readUntyped(); + } else if ("azureCloudType".equals(fieldName)) { + deserializedAzurePostgreSqlLinkedService.azureCloudType = reader.readUntyped(); + } else if ("credential".equals(fieldName)) { + deserializedAzurePostgreSqlLinkedService.credential = CredentialReference.fromJson(reader); } else { reader.skipChildren(); } diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSearchLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSearchLinkedService.java index 413348e17f7b..c58c3146d2d3 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSearchLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSearchLinkedService.java @@ -117,6 +117,15 @@ public AzureSearchLinkedService setEncryptedCredential(Object encryptedCredentia return this; } + /** + * {@inheritDoc} + */ + @Override + public AzureSearchLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -159,6 +168,7 @@ public AzureSearchLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -196,7 +206,9 @@ public static AzureSearchLinkedService fromJson(JsonReader jsonReader) throws IO String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAzureSearchLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAzureSearchLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedAzureSearchLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlDWAuthenticationType.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlDWAuthenticationType.java new file mode 100644 index 000000000000..08580a777b68 --- /dev/null +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlDWAuthenticationType.java @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.analytics.synapse.artifacts.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The type used for authentication. Type: string. + */ +public final class AzureSqlDWAuthenticationType extends ExpandableStringEnum { + /** + * Static value SQL for AzureSqlDWAuthenticationType. + */ + public static final AzureSqlDWAuthenticationType SQL = fromString("SQL"); + + /** + * Static value ServicePrincipal for AzureSqlDWAuthenticationType. + */ + public static final AzureSqlDWAuthenticationType SERVICE_PRINCIPAL = fromString("ServicePrincipal"); + + /** + * Static value SystemAssignedManagedIdentity for AzureSqlDWAuthenticationType. + */ + public static final AzureSqlDWAuthenticationType SYSTEM_ASSIGNED_MANAGED_IDENTITY + = fromString("SystemAssignedManagedIdentity"); + + /** + * Static value UserAssignedManagedIdentity for AzureSqlDWAuthenticationType. + */ + public static final AzureSqlDWAuthenticationType USER_ASSIGNED_MANAGED_IDENTITY + = fromString("UserAssignedManagedIdentity"); + + /** + * Creates a new instance of AzureSqlDWAuthenticationType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureSqlDWAuthenticationType() { + } + + /** + * Creates or finds a AzureSqlDWAuthenticationType from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureSqlDWAuthenticationType. + */ + public static AzureSqlDWAuthenticationType fromString(String name) { + return fromString(name, AzureSqlDWAuthenticationType.class); + } + + /** + * Gets known AzureSqlDWAuthenticationType values. + * + * @return known AzureSqlDWAuthenticationType values. + */ + public static Collection values() { + return values(AzureSqlDWAuthenticationType.class); + } +} diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlDWLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlDWLinkedService.java index 519604bb3cec..d6f7a5a0f183 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlDWLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlDWLinkedService.java @@ -23,12 +23,142 @@ public class AzureSqlDWLinkedService extends LinkedService { */ private String type = "AzureSqlDW"; + /* + * The name or network address of the instance of SQL Server to which to connect, used by recommended version. Type: + * string (or Expression with resultType string). + */ + private Object server; + + /* + * The name of the database, used by recommended version. Type: string (or Expression with resultType string). + */ + private Object database; + + /* + * Indicate whether TLS encryption is required for all data sent between the client and server, used by recommended + * version. Possible values are true/yes/mandatory, false/no/optional and strict. Type: string (or Expression with + * resultType string). + */ + private Object encrypt; + + /* + * Indicate whether the channel will be encrypted while bypassing walking the certificate chain to validate trust, + * used by recommended version. Type: Boolean (or Expression with resultType boolean). + */ + private Object trustServerCertificate; + + /* + * The host name to use when validating the server certificate for the connection. When not specified, the server + * name from the Data Source is used for certificate validation, used by recommended version. Type: string (or + * Expression with resultType string). + */ + private Object hostNameInCertificate; + + /* + * The application workload type when connecting to a server, used by recommended version. Possible values are + * ReadOnly and ReadWrite. Type: string (or Expression with resultType string). + */ + private Object applicationIntent; + + /* + * The length of time (in seconds) to wait for a connection to the server before terminating the attempt and + * generating an error, used by recommended version. Type: integer (or Expression with resultType integer). + */ + private Object connectTimeout; + + /* + * The number of re-connections attempted after identifying that there was an idle connection failure, used by + * recommended version. This must be an integer between 0 and 255. Type: integer (or Expression with resultType + * integer). + */ + private Object connectRetryCount; + + /* + * The amount of time (in seconds) between each re-connection attempt after identifying that there was an idle + * connection failure, used by recommended version. This must be an integer between 1 and 60. Type: integer (or + * Expression with resultType integer). + */ + private Object connectRetryInterval; + + /* + * The minimum time, in seconds, for the connection to live in the connection pool before being destroyed, used by + * recommended version. Type: integer (or Expression with resultType integer). + */ + private Object loadBalanceTimeout; + + /* + * The default wait time (in seconds) before terminating the attempt to execute a command and generating an error, + * used by recommended version. Type: integer (or Expression with resultType integer). + */ + private Object commandTimeout; + + /* + * Indicate whether User ID and Password are specified in the connection (when false) or whether the current Windows + * account credentials are used for authentication (when true), used by recommended version. Type: Boolean (or + * Expression with resultType boolean). + */ + private Object integratedSecurity; + + /* + * The name or address of the partner server to connect to if the primary server is down, used by recommended + * version. Type: string (or Expression with resultType string). + */ + private Object failoverPartner; + + /* + * The maximum number of connections allowed in the connection pool for this specific connection string, used by + * recommended version. Type: integer (or Expression with resultType integer). + */ + private Object maxPoolSize; + + /* + * The minimum number of connections allowed in the connection pool for this specific connection string, used by + * recommended version. Type: integer (or Expression with resultType integer). + */ + private Object minPoolSize; + + /* + * When true, an application can maintain multiple active result sets (MARS). When false, an application must + * process or cancel all result sets from one batch before it can execute any other batch on that connection. Type: + * Boolean (or Expression with resultType boolean). + */ + private Object multipleActiveResultSets; + + /* + * If your application is connecting to an AlwaysOn availability group (AG) on different subnets, setting + * MultiSubnetFailover=true provides faster detection of and connection to the (currently) active server, used by + * recommended version. Type: Boolean (or Expression with resultType boolean). + */ + private Object multiSubnetFailover; + + /* + * The size in bytes of the network packets used to communicate with an instance of server, used by recommended + * version. Type: integer (or Expression with resultType integer). + */ + private Object packetSize; + + /* + * Indicate whether the connection will be pooled or explicitly opened every time that the connection is requested, + * used by recommended version. Type: Boolean (or Expression with resultType boolean). + */ + private Object pooling; + /* * The connection string. Type: string, SecureString or AzureKeyVaultSecretReference. Type: string, SecureString or * AzureKeyVaultSecretReference. */ private Object connectionString; + /* + * The type used for authentication. Type: string. + */ + private AzureSqlDWAuthenticationType authenticationType; + + /* + * The user name to be used when connecting to server. Type: string (or Expression with resultType string). + */ + private Object userName; + /* * The Azure key vault secret reference of password in connection string. */ @@ -45,6 +175,20 @@ public class AzureSqlDWLinkedService extends LinkedService { */ private SecretBase servicePrincipalKey; + /* + * The service principal credential type to use in Server-To-Server authentication. 'ServicePrincipalKey' for + * key/secret, 'ServicePrincipalCert' for certificate. Type: string (or Expression with resultType string). + */ + private Object servicePrincipalCredentialType; + + /* + * The credential of the service principal object in Azure Active Directory. If servicePrincipalCredentialType is + * 'ServicePrincipalKey', servicePrincipalCredential can be SecureString or AzureKeyVaultSecretReference. If + * servicePrincipalCredentialType is 'ServicePrincipalCert', servicePrincipalCredential can only be + * AzureKeyVaultSecretReference. + */ + private SecretBase servicePrincipalCredential; + /* * The name or ID of the tenant to which the service principal belongs. Type: string (or Expression with resultType * string). @@ -85,6 +229,446 @@ public String getType() { return this.type; } + /** + * Get the server property: The name or network address of the instance of SQL Server to which to connect, used by + * recommended version. Type: string (or Expression with resultType string). + * + * @return the server value. + */ + public Object getServer() { + return this.server; + } + + /** + * Set the server property: The name or network address of the instance of SQL Server to which to connect, used by + * recommended version. Type: string (or Expression with resultType string). + * + * @param server the server value to set. + * @return the AzureSqlDWLinkedService object itself. + */ + public AzureSqlDWLinkedService setServer(Object server) { + this.server = server; + return this; + } + + /** + * Get the database property: The name of the database, used by recommended version. Type: string (or Expression + * with resultType string). + * + * @return the database value. + */ + public Object getDatabase() { + return this.database; + } + + /** + * Set the database property: The name of the database, used by recommended version. Type: string (or Expression + * with resultType string). + * + * @param database the database value to set. + * @return the AzureSqlDWLinkedService object itself. + */ + public AzureSqlDWLinkedService setDatabase(Object database) { + this.database = database; + return this; + } + + /** + * Get the encrypt property: Indicate whether TLS encryption is required for all data sent between the client and + * server, used by recommended version. Possible values are true/yes/mandatory, false/no/optional and strict. Type: + * string (or Expression with resultType string). + * + * @return the encrypt value. + */ + public Object getEncrypt() { + return this.encrypt; + } + + /** + * Set the encrypt property: Indicate whether TLS encryption is required for all data sent between the client and + * server, used by recommended version. Possible values are true/yes/mandatory, false/no/optional and strict. Type: + * string (or Expression with resultType string). + * + * @param encrypt the encrypt value to set. + * @return the AzureSqlDWLinkedService object itself. + */ + public AzureSqlDWLinkedService setEncrypt(Object encrypt) { + this.encrypt = encrypt; + return this; + } + + /** + * Get the trustServerCertificate property: Indicate whether the channel will be encrypted while bypassing walking + * the certificate chain to validate trust, used by recommended version. Type: Boolean (or Expression with + * resultType boolean). + * + * @return the trustServerCertificate value. + */ + public Object getTrustServerCertificate() { + return this.trustServerCertificate; + } + + /** + * Set the trustServerCertificate property: Indicate whether the channel will be encrypted while bypassing walking + * the certificate chain to validate trust, used by recommended version. Type: Boolean (or Expression with + * resultType boolean). + * + * @param trustServerCertificate the trustServerCertificate value to set. + * @return the AzureSqlDWLinkedService object itself. + */ + public AzureSqlDWLinkedService setTrustServerCertificate(Object trustServerCertificate) { + this.trustServerCertificate = trustServerCertificate; + return this; + } + + /** + * Get the hostNameInCertificate property: The host name to use when validating the server certificate for the + * connection. When not specified, the server name from the Data Source is used for certificate validation, used by + * recommended version. Type: string (or Expression with resultType string). + * + * @return the hostNameInCertificate value. + */ + public Object getHostNameInCertificate() { + return this.hostNameInCertificate; + } + + /** + * Set the hostNameInCertificate property: The host name to use when validating the server certificate for the + * connection. When not specified, the server name from the Data Source is used for certificate validation, used by + * recommended version. Type: string (or Expression with resultType string). + * + * @param hostNameInCertificate the hostNameInCertificate value to set. + * @return the AzureSqlDWLinkedService object itself. + */ + public AzureSqlDWLinkedService setHostNameInCertificate(Object hostNameInCertificate) { + this.hostNameInCertificate = hostNameInCertificate; + return this; + } + + /** + * Get the applicationIntent property: The application workload type when connecting to a server, used by + * recommended version. Possible values are ReadOnly and ReadWrite. Type: string (or Expression with resultType + * string). + * + * @return the applicationIntent value. + */ + public Object getApplicationIntent() { + return this.applicationIntent; + } + + /** + * Set the applicationIntent property: The application workload type when connecting to a server, used by + * recommended version. Possible values are ReadOnly and ReadWrite. Type: string (or Expression with resultType + * string). + * + * @param applicationIntent the applicationIntent value to set. + * @return the AzureSqlDWLinkedService object itself. + */ + public AzureSqlDWLinkedService setApplicationIntent(Object applicationIntent) { + this.applicationIntent = applicationIntent; + return this; + } + + /** + * Get the connectTimeout property: The length of time (in seconds) to wait for a connection to the server before + * terminating the attempt and generating an error, used by recommended version. Type: integer (or Expression with + * resultType integer). + * + * @return the connectTimeout value. + */ + public Object getConnectTimeout() { + return this.connectTimeout; + } + + /** + * Set the connectTimeout property: The length of time (in seconds) to wait for a connection to the server before + * terminating the attempt and generating an error, used by recommended version. Type: integer (or Expression with + * resultType integer). + * + * @param connectTimeout the connectTimeout value to set. + * @return the AzureSqlDWLinkedService object itself. + */ + public AzureSqlDWLinkedService setConnectTimeout(Object connectTimeout) { + this.connectTimeout = connectTimeout; + return this; + } + + /** + * Get the connectRetryCount property: The number of re-connections attempted after identifying that there was an + * idle connection failure, used by recommended version. This must be an integer between 0 and 255. Type: integer + * (or Expression with resultType integer). + * + * @return the connectRetryCount value. + */ + public Object getConnectRetryCount() { + return this.connectRetryCount; + } + + /** + * Set the connectRetryCount property: The number of re-connections attempted after identifying that there was an + * idle connection failure, used by recommended version. This must be an integer between 0 and 255. Type: integer + * (or Expression with resultType integer). + * + * @param connectRetryCount the connectRetryCount value to set. + * @return the AzureSqlDWLinkedService object itself. + */ + public AzureSqlDWLinkedService setConnectRetryCount(Object connectRetryCount) { + this.connectRetryCount = connectRetryCount; + return this; + } + + /** + * Get the connectRetryInterval property: The amount of time (in seconds) between each re-connection attempt after + * identifying that there was an idle connection failure, used by recommended version. This must be an integer + * between 1 and 60. Type: integer (or Expression with resultType integer). + * + * @return the connectRetryInterval value. + */ + public Object getConnectRetryInterval() { + return this.connectRetryInterval; + } + + /** + * Set the connectRetryInterval property: The amount of time (in seconds) between each re-connection attempt after + * identifying that there was an idle connection failure, used by recommended version. This must be an integer + * between 1 and 60. Type: integer (or Expression with resultType integer). + * + * @param connectRetryInterval the connectRetryInterval value to set. + * @return the AzureSqlDWLinkedService object itself. + */ + public AzureSqlDWLinkedService setConnectRetryInterval(Object connectRetryInterval) { + this.connectRetryInterval = connectRetryInterval; + return this; + } + + /** + * Get the loadBalanceTimeout property: The minimum time, in seconds, for the connection to live in the connection + * pool before being destroyed, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @return the loadBalanceTimeout value. + */ + public Object getLoadBalanceTimeout() { + return this.loadBalanceTimeout; + } + + /** + * Set the loadBalanceTimeout property: The minimum time, in seconds, for the connection to live in the connection + * pool before being destroyed, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @param loadBalanceTimeout the loadBalanceTimeout value to set. + * @return the AzureSqlDWLinkedService object itself. + */ + public AzureSqlDWLinkedService setLoadBalanceTimeout(Object loadBalanceTimeout) { + this.loadBalanceTimeout = loadBalanceTimeout; + return this; + } + + /** + * Get the commandTimeout property: The default wait time (in seconds) before terminating the attempt to execute a + * command and generating an error, used by recommended version. Type: integer (or Expression with resultType + * integer). + * + * @return the commandTimeout value. + */ + public Object getCommandTimeout() { + return this.commandTimeout; + } + + /** + * Set the commandTimeout property: The default wait time (in seconds) before terminating the attempt to execute a + * command and generating an error, used by recommended version. Type: integer (or Expression with resultType + * integer). + * + * @param commandTimeout the commandTimeout value to set. + * @return the AzureSqlDWLinkedService object itself. + */ + public AzureSqlDWLinkedService setCommandTimeout(Object commandTimeout) { + this.commandTimeout = commandTimeout; + return this; + } + + /** + * Get the integratedSecurity property: Indicate whether User ID and Password are specified in the connection (when + * false) or whether the current Windows account credentials are used for authentication (when true), used by + * recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @return the integratedSecurity value. + */ + public Object getIntegratedSecurity() { + return this.integratedSecurity; + } + + /** + * Set the integratedSecurity property: Indicate whether User ID and Password are specified in the connection (when + * false) or whether the current Windows account credentials are used for authentication (when true), used by + * recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @param integratedSecurity the integratedSecurity value to set. + * @return the AzureSqlDWLinkedService object itself. + */ + public AzureSqlDWLinkedService setIntegratedSecurity(Object integratedSecurity) { + this.integratedSecurity = integratedSecurity; + return this; + } + + /** + * Get the failoverPartner property: The name or address of the partner server to connect to if the primary server + * is down, used by recommended version. Type: string (or Expression with resultType string). + * + * @return the failoverPartner value. + */ + public Object getFailoverPartner() { + return this.failoverPartner; + } + + /** + * Set the failoverPartner property: The name or address of the partner server to connect to if the primary server + * is down, used by recommended version. Type: string (or Expression with resultType string). + * + * @param failoverPartner the failoverPartner value to set. + * @return the AzureSqlDWLinkedService object itself. + */ + public AzureSqlDWLinkedService setFailoverPartner(Object failoverPartner) { + this.failoverPartner = failoverPartner; + return this; + } + + /** + * Get the maxPoolSize property: The maximum number of connections allowed in the connection pool for this specific + * connection string, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @return the maxPoolSize value. + */ + public Object getMaxPoolSize() { + return this.maxPoolSize; + } + + /** + * Set the maxPoolSize property: The maximum number of connections allowed in the connection pool for this specific + * connection string, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @param maxPoolSize the maxPoolSize value to set. + * @return the AzureSqlDWLinkedService object itself. + */ + public AzureSqlDWLinkedService setMaxPoolSize(Object maxPoolSize) { + this.maxPoolSize = maxPoolSize; + return this; + } + + /** + * Get the minPoolSize property: The minimum number of connections allowed in the connection pool for this specific + * connection string, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @return the minPoolSize value. + */ + public Object getMinPoolSize() { + return this.minPoolSize; + } + + /** + * Set the minPoolSize property: The minimum number of connections allowed in the connection pool for this specific + * connection string, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @param minPoolSize the minPoolSize value to set. + * @return the AzureSqlDWLinkedService object itself. + */ + public AzureSqlDWLinkedService setMinPoolSize(Object minPoolSize) { + this.minPoolSize = minPoolSize; + return this; + } + + /** + * Get the multipleActiveResultSets property: When true, an application can maintain multiple active result sets + * (MARS). When false, an application must process or cancel all result sets from one batch before it can execute + * any other batch on that connection. Type: Boolean (or Expression with resultType boolean). + * + * @return the multipleActiveResultSets value. + */ + public Object getMultipleActiveResultSets() { + return this.multipleActiveResultSets; + } + + /** + * Set the multipleActiveResultSets property: When true, an application can maintain multiple active result sets + * (MARS). When false, an application must process or cancel all result sets from one batch before it can execute + * any other batch on that connection. Type: Boolean (or Expression with resultType boolean). + * + * @param multipleActiveResultSets the multipleActiveResultSets value to set. + * @return the AzureSqlDWLinkedService object itself. + */ + public AzureSqlDWLinkedService setMultipleActiveResultSets(Object multipleActiveResultSets) { + this.multipleActiveResultSets = multipleActiveResultSets; + return this; + } + + /** + * Get the multiSubnetFailover property: If your application is connecting to an AlwaysOn availability group (AG) on + * different subnets, setting MultiSubnetFailover=true provides faster detection of and connection to the + * (currently) active server, used by recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @return the multiSubnetFailover value. + */ + public Object getMultiSubnetFailover() { + return this.multiSubnetFailover; + } + + /** + * Set the multiSubnetFailover property: If your application is connecting to an AlwaysOn availability group (AG) on + * different subnets, setting MultiSubnetFailover=true provides faster detection of and connection to the + * (currently) active server, used by recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @param multiSubnetFailover the multiSubnetFailover value to set. + * @return the AzureSqlDWLinkedService object itself. + */ + public AzureSqlDWLinkedService setMultiSubnetFailover(Object multiSubnetFailover) { + this.multiSubnetFailover = multiSubnetFailover; + return this; + } + + /** + * Get the packetSize property: The size in bytes of the network packets used to communicate with an instance of + * server, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @return the packetSize value. + */ + public Object getPacketSize() { + return this.packetSize; + } + + /** + * Set the packetSize property: The size in bytes of the network packets used to communicate with an instance of + * server, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @param packetSize the packetSize value to set. + * @return the AzureSqlDWLinkedService object itself. + */ + public AzureSqlDWLinkedService setPacketSize(Object packetSize) { + this.packetSize = packetSize; + return this; + } + + /** + * Get the pooling property: Indicate whether the connection will be pooled or explicitly opened every time that the + * connection is requested, used by recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @return the pooling value. + */ + public Object getPooling() { + return this.pooling; + } + + /** + * Set the pooling property: Indicate whether the connection will be pooled or explicitly opened every time that the + * connection is requested, used by recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @param pooling the pooling value to set. + * @return the AzureSqlDWLinkedService object itself. + */ + public AzureSqlDWLinkedService setPooling(Object pooling) { + this.pooling = pooling; + return this; + } + /** * Get the connectionString property: The connection string. Type: string, SecureString or * AzureKeyVaultSecretReference. Type: string, SecureString or AzureKeyVaultSecretReference. @@ -107,6 +691,48 @@ public AzureSqlDWLinkedService setConnectionString(Object connectionString) { return this; } + /** + * Get the authenticationType property: The type used for authentication. Type: string. + * + * @return the authenticationType value. + */ + public AzureSqlDWAuthenticationType getAuthenticationType() { + return this.authenticationType; + } + + /** + * Set the authenticationType property: The type used for authentication. Type: string. + * + * @param authenticationType the authenticationType value to set. + * @return the AzureSqlDWLinkedService object itself. + */ + public AzureSqlDWLinkedService setAuthenticationType(AzureSqlDWAuthenticationType authenticationType) { + this.authenticationType = authenticationType; + return this; + } + + /** + * Get the userName property: The user name to be used when connecting to server. Type: string (or Expression with + * resultType string). + * + * @return the userName value. + */ + public Object getUserName() { + return this.userName; + } + + /** + * Set the userName property: The user name to be used when connecting to server. Type: string (or Expression with + * resultType string). + * + * @param userName the userName value to set. + * @return the AzureSqlDWLinkedService object itself. + */ + public AzureSqlDWLinkedService setUserName(Object userName) { + this.userName = userName; + return this; + } + /** * Get the password property: The Azure key vault secret reference of password in connection string. * @@ -171,6 +797,56 @@ public AzureSqlDWLinkedService setServicePrincipalKey(SecretBase servicePrincipa return this; } + /** + * Get the servicePrincipalCredentialType property: The service principal credential type to use in Server-To-Server + * authentication. 'ServicePrincipalKey' for key/secret, 'ServicePrincipalCert' for certificate. Type: string (or + * Expression with resultType string). + * + * @return the servicePrincipalCredentialType value. + */ + public Object getServicePrincipalCredentialType() { + return this.servicePrincipalCredentialType; + } + + /** + * Set the servicePrincipalCredentialType property: The service principal credential type to use in Server-To-Server + * authentication. 'ServicePrincipalKey' for key/secret, 'ServicePrincipalCert' for certificate. Type: string (or + * Expression with resultType string). + * + * @param servicePrincipalCredentialType the servicePrincipalCredentialType value to set. + * @return the AzureSqlDWLinkedService object itself. + */ + public AzureSqlDWLinkedService setServicePrincipalCredentialType(Object servicePrincipalCredentialType) { + this.servicePrincipalCredentialType = servicePrincipalCredentialType; + return this; + } + + /** + * Get the servicePrincipalCredential property: The credential of the service principal object in Azure Active + * Directory. If servicePrincipalCredentialType is 'ServicePrincipalKey', servicePrincipalCredential can be + * SecureString or AzureKeyVaultSecretReference. If servicePrincipalCredentialType is 'ServicePrincipalCert', + * servicePrincipalCredential can only be AzureKeyVaultSecretReference. + * + * @return the servicePrincipalCredential value. + */ + public SecretBase getServicePrincipalCredential() { + return this.servicePrincipalCredential; + } + + /** + * Set the servicePrincipalCredential property: The credential of the service principal object in Azure Active + * Directory. If servicePrincipalCredentialType is 'ServicePrincipalKey', servicePrincipalCredential can be + * SecureString or AzureKeyVaultSecretReference. If servicePrincipalCredentialType is 'ServicePrincipalCert', + * servicePrincipalCredential can only be AzureKeyVaultSecretReference. + * + * @param servicePrincipalCredential the servicePrincipalCredential value to set. + * @return the AzureSqlDWLinkedService object itself. + */ + public AzureSqlDWLinkedService setServicePrincipalCredential(SecretBase servicePrincipalCredential) { + this.servicePrincipalCredential = servicePrincipalCredential; + return this; + } + /** * Get the tenant property: The name or ID of the tenant to which the service principal belongs. Type: string (or * Expression with resultType string). @@ -259,6 +935,15 @@ public AzureSqlDWLinkedService setCredential(CredentialReference credential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDWLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -301,24 +986,72 @@ public AzureSqlDWLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); jsonWriter.writeArrayField("annotations", getAnnotations(), (writer, element) -> writer.writeUntyped(element)); jsonWriter.writeStringField("type", this.type); - if (connectionString != null + if (server != null + || database != null + || encrypt != null + || trustServerCertificate != null + || hostNameInCertificate != null + || applicationIntent != null + || connectTimeout != null + || connectRetryCount != null + || connectRetryInterval != null + || loadBalanceTimeout != null + || commandTimeout != null + || integratedSecurity != null + || failoverPartner != null + || maxPoolSize != null + || minPoolSize != null + || multipleActiveResultSets != null + || multiSubnetFailover != null + || packetSize != null + || pooling != null + || connectionString != null + || authenticationType != null + || userName != null || password != null || servicePrincipalId != null || servicePrincipalKey != null + || servicePrincipalCredentialType != null + || servicePrincipalCredential != null || tenant != null || azureCloudType != null || encryptedCredential != null || credential != null) { jsonWriter.writeStartObject("typeProperties"); + jsonWriter.writeUntypedField("server", this.server); + jsonWriter.writeUntypedField("database", this.database); + jsonWriter.writeUntypedField("encrypt", this.encrypt); + jsonWriter.writeUntypedField("trustServerCertificate", this.trustServerCertificate); + jsonWriter.writeUntypedField("hostNameInCertificate", this.hostNameInCertificate); + jsonWriter.writeUntypedField("applicationIntent", this.applicationIntent); + jsonWriter.writeUntypedField("connectTimeout", this.connectTimeout); + jsonWriter.writeUntypedField("connectRetryCount", this.connectRetryCount); + jsonWriter.writeUntypedField("connectRetryInterval", this.connectRetryInterval); + jsonWriter.writeUntypedField("loadBalanceTimeout", this.loadBalanceTimeout); + jsonWriter.writeUntypedField("commandTimeout", this.commandTimeout); + jsonWriter.writeUntypedField("integratedSecurity", this.integratedSecurity); + jsonWriter.writeUntypedField("failoverPartner", this.failoverPartner); + jsonWriter.writeUntypedField("maxPoolSize", this.maxPoolSize); + jsonWriter.writeUntypedField("minPoolSize", this.minPoolSize); + jsonWriter.writeUntypedField("multipleActiveResultSets", this.multipleActiveResultSets); + jsonWriter.writeUntypedField("multiSubnetFailover", this.multiSubnetFailover); + jsonWriter.writeUntypedField("packetSize", this.packetSize); + jsonWriter.writeUntypedField("pooling", this.pooling); jsonWriter.writeUntypedField("connectionString", this.connectionString); + jsonWriter.writeStringField("authenticationType", + this.authenticationType == null ? null : this.authenticationType.toString()); + jsonWriter.writeUntypedField("userName", this.userName); jsonWriter.writeJsonField("password", this.password); jsonWriter.writeUntypedField("servicePrincipalId", this.servicePrincipalId); jsonWriter.writeJsonField("servicePrincipalKey", this.servicePrincipalKey); + jsonWriter.writeUntypedField("servicePrincipalCredentialType", this.servicePrincipalCredentialType); + jsonWriter.writeJsonField("servicePrincipalCredential", this.servicePrincipalCredential); jsonWriter.writeUntypedField("tenant", this.tenant); jsonWriter.writeUntypedField("azureCloudType", this.azureCloudType); jsonWriter.writeUntypedField("encryptedCredential", this.encryptedCredential); @@ -339,7 +1072,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @param jsonReader The JsonReader being read. * @return An instance of AzureSqlDWLinkedService 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 AzureSqlDWLinkedService. */ public static AzureSqlDWLinkedService fromJson(JsonReader jsonReader) throws IOException { @@ -350,7 +1082,9 @@ public static AzureSqlDWLinkedService fromJson(JsonReader jsonReader) throws IOE String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAzureSqlDWLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAzureSqlDWLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedAzureSqlDWLinkedService.setDescription(reader.getString()); @@ -368,8 +1102,51 @@ public static AzureSqlDWLinkedService fromJson(JsonReader jsonReader) throws IOE fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectionString".equals(fieldName)) { + if ("server".equals(fieldName)) { + deserializedAzureSqlDWLinkedService.server = reader.readUntyped(); + } else if ("database".equals(fieldName)) { + deserializedAzureSqlDWLinkedService.database = reader.readUntyped(); + } else if ("encrypt".equals(fieldName)) { + deserializedAzureSqlDWLinkedService.encrypt = reader.readUntyped(); + } else if ("trustServerCertificate".equals(fieldName)) { + deserializedAzureSqlDWLinkedService.trustServerCertificate = reader.readUntyped(); + } else if ("hostNameInCertificate".equals(fieldName)) { + deserializedAzureSqlDWLinkedService.hostNameInCertificate = reader.readUntyped(); + } else if ("applicationIntent".equals(fieldName)) { + deserializedAzureSqlDWLinkedService.applicationIntent = reader.readUntyped(); + } else if ("connectTimeout".equals(fieldName)) { + deserializedAzureSqlDWLinkedService.connectTimeout = reader.readUntyped(); + } else if ("connectRetryCount".equals(fieldName)) { + deserializedAzureSqlDWLinkedService.connectRetryCount = reader.readUntyped(); + } else if ("connectRetryInterval".equals(fieldName)) { + deserializedAzureSqlDWLinkedService.connectRetryInterval = reader.readUntyped(); + } else if ("loadBalanceTimeout".equals(fieldName)) { + deserializedAzureSqlDWLinkedService.loadBalanceTimeout = reader.readUntyped(); + } else if ("commandTimeout".equals(fieldName)) { + deserializedAzureSqlDWLinkedService.commandTimeout = reader.readUntyped(); + } else if ("integratedSecurity".equals(fieldName)) { + deserializedAzureSqlDWLinkedService.integratedSecurity = reader.readUntyped(); + } else if ("failoverPartner".equals(fieldName)) { + deserializedAzureSqlDWLinkedService.failoverPartner = reader.readUntyped(); + } else if ("maxPoolSize".equals(fieldName)) { + deserializedAzureSqlDWLinkedService.maxPoolSize = reader.readUntyped(); + } else if ("minPoolSize".equals(fieldName)) { + deserializedAzureSqlDWLinkedService.minPoolSize = reader.readUntyped(); + } else if ("multipleActiveResultSets".equals(fieldName)) { + deserializedAzureSqlDWLinkedService.multipleActiveResultSets = reader.readUntyped(); + } else if ("multiSubnetFailover".equals(fieldName)) { + deserializedAzureSqlDWLinkedService.multiSubnetFailover = reader.readUntyped(); + } else if ("packetSize".equals(fieldName)) { + deserializedAzureSqlDWLinkedService.packetSize = reader.readUntyped(); + } else if ("pooling".equals(fieldName)) { + deserializedAzureSqlDWLinkedService.pooling = reader.readUntyped(); + } else if ("connectionString".equals(fieldName)) { deserializedAzureSqlDWLinkedService.connectionString = reader.readUntyped(); + } else if ("authenticationType".equals(fieldName)) { + deserializedAzureSqlDWLinkedService.authenticationType + = AzureSqlDWAuthenticationType.fromString(reader.getString()); + } else if ("userName".equals(fieldName)) { + deserializedAzureSqlDWLinkedService.userName = reader.readUntyped(); } else if ("password".equals(fieldName)) { deserializedAzureSqlDWLinkedService.password = AzureKeyVaultSecretReference.fromJson(reader); @@ -377,6 +1154,11 @@ public static AzureSqlDWLinkedService fromJson(JsonReader jsonReader) throws IOE deserializedAzureSqlDWLinkedService.servicePrincipalId = reader.readUntyped(); } else if ("servicePrincipalKey".equals(fieldName)) { deserializedAzureSqlDWLinkedService.servicePrincipalKey = SecretBase.fromJson(reader); + } else if ("servicePrincipalCredentialType".equals(fieldName)) { + deserializedAzureSqlDWLinkedService.servicePrincipalCredentialType = reader.readUntyped(); + } else if ("servicePrincipalCredential".equals(fieldName)) { + deserializedAzureSqlDWLinkedService.servicePrincipalCredential + = SecretBase.fromJson(reader); } else if ("tenant".equals(fieldName)) { deserializedAzureSqlDWLinkedService.tenant = reader.readUntyped(); } else if ("azureCloudType".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlDWLinkedServiceTypeProperties.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlDWLinkedServiceTypeProperties.java new file mode 100644 index 000000000000..b739124d9126 --- /dev/null +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlDWLinkedServiceTypeProperties.java @@ -0,0 +1,664 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.analytics.synapse.artifacts.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; + +/** + * Azure SQL Data Warehouse linked service properties. + */ +@Fluent +public final class AzureSqlDWLinkedServiceTypeProperties extends SqlServerBaseLinkedServiceTypeProperties { + /* + * The connection string. Type: string, SecureString or AzureKeyVaultSecretReference. Type: string, SecureString or + * AzureKeyVaultSecretReference. + */ + private Object connectionString; + + /* + * The type used for authentication. Type: string. + */ + private AzureSqlDWAuthenticationType authenticationType; + + /* + * The user name to be used when connecting to server. Type: string (or Expression with resultType string). + */ + private Object userName; + + /* + * The Azure key vault secret reference of password in connection string. + */ + private AzureKeyVaultSecretReference password; + + /* + * The ID of the service principal used to authenticate against Azure SQL Data Warehouse. Type: string (or + * Expression with resultType string). + */ + private Object servicePrincipalId; + + /* + * The key of the service principal used to authenticate against Azure SQL Data Warehouse. + */ + private SecretBase servicePrincipalKey; + + /* + * The service principal credential type to use in Server-To-Server authentication. 'ServicePrincipalKey' for + * key/secret, 'ServicePrincipalCert' for certificate. Type: string (or Expression with resultType string). + */ + private Object servicePrincipalCredentialType; + + /* + * The credential of the service principal object in Azure Active Directory. If servicePrincipalCredentialType is + * 'ServicePrincipalKey', servicePrincipalCredential can be SecureString or AzureKeyVaultSecretReference. If + * servicePrincipalCredentialType is 'ServicePrincipalCert', servicePrincipalCredential can only be + * AzureKeyVaultSecretReference. + */ + private SecretBase servicePrincipalCredential; + + /* + * The name or ID of the tenant to which the service principal belongs. Type: string (or Expression with resultType + * string). + */ + private Object tenant; + + /* + * Indicates the azure cloud type of the service principle auth. Allowed values are AzurePublic, AzureChina, + * AzureUsGovernment, AzureGermany. Default value is the data factory regions’ cloud type. Type: string (or + * Expression with resultType string). + */ + private Object azureCloudType; + + /* + * The encrypted credential used for authentication. Credentials are encrypted using the integration runtime + * credential manager. Type: string (or Expression with resultType string). + */ + private Object encryptedCredential; + + /* + * The credential reference containing authentication information. + */ + private CredentialReference credential; + + /** + * Creates an instance of AzureSqlDWLinkedServiceTypeProperties class. + */ + public AzureSqlDWLinkedServiceTypeProperties() { + } + + /** + * Get the connectionString property: The connection string. Type: string, SecureString or + * AzureKeyVaultSecretReference. Type: string, SecureString or AzureKeyVaultSecretReference. + * + * @return the connectionString value. + */ + public Object getConnectionString() { + return this.connectionString; + } + + /** + * Set the connectionString property: The connection string. Type: string, SecureString or + * AzureKeyVaultSecretReference. Type: string, SecureString or AzureKeyVaultSecretReference. + * + * @param connectionString the connectionString value to set. + * @return the AzureSqlDWLinkedServiceTypeProperties object itself. + */ + public AzureSqlDWLinkedServiceTypeProperties setConnectionString(Object connectionString) { + this.connectionString = connectionString; + return this; + } + + /** + * Get the authenticationType property: The type used for authentication. Type: string. + * + * @return the authenticationType value. + */ + public AzureSqlDWAuthenticationType getAuthenticationType() { + return this.authenticationType; + } + + /** + * Set the authenticationType property: The type used for authentication. Type: string. + * + * @param authenticationType the authenticationType value to set. + * @return the AzureSqlDWLinkedServiceTypeProperties object itself. + */ + public AzureSqlDWLinkedServiceTypeProperties + setAuthenticationType(AzureSqlDWAuthenticationType authenticationType) { + this.authenticationType = authenticationType; + return this; + } + + /** + * Get the userName property: The user name to be used when connecting to server. Type: string (or Expression with + * resultType string). + * + * @return the userName value. + */ + public Object getUserName() { + return this.userName; + } + + /** + * Set the userName property: The user name to be used when connecting to server. Type: string (or Expression with + * resultType string). + * + * @param userName the userName value to set. + * @return the AzureSqlDWLinkedServiceTypeProperties object itself. + */ + public AzureSqlDWLinkedServiceTypeProperties setUserName(Object userName) { + this.userName = userName; + return this; + } + + /** + * Get the password property: The Azure key vault secret reference of password in connection string. + * + * @return the password value. + */ + public AzureKeyVaultSecretReference getPassword() { + return this.password; + } + + /** + * Set the password property: The Azure key vault secret reference of password in connection string. + * + * @param password the password value to set. + * @return the AzureSqlDWLinkedServiceTypeProperties object itself. + */ + public AzureSqlDWLinkedServiceTypeProperties setPassword(AzureKeyVaultSecretReference password) { + this.password = password; + return this; + } + + /** + * Get the servicePrincipalId property: The ID of the service principal used to authenticate against Azure SQL Data + * Warehouse. Type: string (or Expression with resultType string). + * + * @return the servicePrincipalId value. + */ + public Object getServicePrincipalId() { + return this.servicePrincipalId; + } + + /** + * Set the servicePrincipalId property: The ID of the service principal used to authenticate against Azure SQL Data + * Warehouse. Type: string (or Expression with resultType string). + * + * @param servicePrincipalId the servicePrincipalId value to set. + * @return the AzureSqlDWLinkedServiceTypeProperties object itself. + */ + public AzureSqlDWLinkedServiceTypeProperties setServicePrincipalId(Object servicePrincipalId) { + this.servicePrincipalId = servicePrincipalId; + return this; + } + + /** + * Get the servicePrincipalKey property: The key of the service principal used to authenticate against Azure SQL + * Data Warehouse. + * + * @return the servicePrincipalKey value. + */ + public SecretBase getServicePrincipalKey() { + return this.servicePrincipalKey; + } + + /** + * Set the servicePrincipalKey property: The key of the service principal used to authenticate against Azure SQL + * Data Warehouse. + * + * @param servicePrincipalKey the servicePrincipalKey value to set. + * @return the AzureSqlDWLinkedServiceTypeProperties object itself. + */ + public AzureSqlDWLinkedServiceTypeProperties setServicePrincipalKey(SecretBase servicePrincipalKey) { + this.servicePrincipalKey = servicePrincipalKey; + return this; + } + + /** + * Get the servicePrincipalCredentialType property: The service principal credential type to use in Server-To-Server + * authentication. 'ServicePrincipalKey' for key/secret, 'ServicePrincipalCert' for certificate. Type: string (or + * Expression with resultType string). + * + * @return the servicePrincipalCredentialType value. + */ + public Object getServicePrincipalCredentialType() { + return this.servicePrincipalCredentialType; + } + + /** + * Set the servicePrincipalCredentialType property: The service principal credential type to use in Server-To-Server + * authentication. 'ServicePrincipalKey' for key/secret, 'ServicePrincipalCert' for certificate. Type: string (or + * Expression with resultType string). + * + * @param servicePrincipalCredentialType the servicePrincipalCredentialType value to set. + * @return the AzureSqlDWLinkedServiceTypeProperties object itself. + */ + public AzureSqlDWLinkedServiceTypeProperties + setServicePrincipalCredentialType(Object servicePrincipalCredentialType) { + this.servicePrincipalCredentialType = servicePrincipalCredentialType; + return this; + } + + /** + * Get the servicePrincipalCredential property: The credential of the service principal object in Azure Active + * Directory. If servicePrincipalCredentialType is 'ServicePrincipalKey', servicePrincipalCredential can be + * SecureString or AzureKeyVaultSecretReference. If servicePrincipalCredentialType is 'ServicePrincipalCert', + * servicePrincipalCredential can only be AzureKeyVaultSecretReference. + * + * @return the servicePrincipalCredential value. + */ + public SecretBase getServicePrincipalCredential() { + return this.servicePrincipalCredential; + } + + /** + * Set the servicePrincipalCredential property: The credential of the service principal object in Azure Active + * Directory. If servicePrincipalCredentialType is 'ServicePrincipalKey', servicePrincipalCredential can be + * SecureString or AzureKeyVaultSecretReference. If servicePrincipalCredentialType is 'ServicePrincipalCert', + * servicePrincipalCredential can only be AzureKeyVaultSecretReference. + * + * @param servicePrincipalCredential the servicePrincipalCredential value to set. + * @return the AzureSqlDWLinkedServiceTypeProperties object itself. + */ + public AzureSqlDWLinkedServiceTypeProperties setServicePrincipalCredential(SecretBase servicePrincipalCredential) { + this.servicePrincipalCredential = servicePrincipalCredential; + return this; + } + + /** + * Get the tenant property: The name or ID of the tenant to which the service principal belongs. Type: string (or + * Expression with resultType string). + * + * @return the tenant value. + */ + public Object getTenant() { + return this.tenant; + } + + /** + * Set the tenant property: The name or ID of the tenant to which the service principal belongs. Type: string (or + * Expression with resultType string). + * + * @param tenant the tenant value to set. + * @return the AzureSqlDWLinkedServiceTypeProperties object itself. + */ + public AzureSqlDWLinkedServiceTypeProperties setTenant(Object tenant) { + this.tenant = tenant; + return this; + } + + /** + * Get the azureCloudType property: Indicates the azure cloud type of the service principle auth. Allowed values are + * AzurePublic, AzureChina, AzureUsGovernment, AzureGermany. Default value is the data factory regions’ cloud type. + * Type: string (or Expression with resultType string). + * + * @return the azureCloudType value. + */ + public Object getAzureCloudType() { + return this.azureCloudType; + } + + /** + * Set the azureCloudType property: Indicates the azure cloud type of the service principle auth. Allowed values are + * AzurePublic, AzureChina, AzureUsGovernment, AzureGermany. Default value is the data factory regions’ cloud type. + * Type: string (or Expression with resultType string). + * + * @param azureCloudType the azureCloudType value to set. + * @return the AzureSqlDWLinkedServiceTypeProperties object itself. + */ + public AzureSqlDWLinkedServiceTypeProperties setAzureCloudType(Object azureCloudType) { + this.azureCloudType = azureCloudType; + return this; + } + + /** + * Get the encryptedCredential property: The encrypted credential used for authentication. Credentials are encrypted + * using the integration runtime credential manager. Type: string (or Expression with resultType string). + * + * @return the encryptedCredential value. + */ + public Object getEncryptedCredential() { + return this.encryptedCredential; + } + + /** + * Set the encryptedCredential property: The encrypted credential used for authentication. Credentials are encrypted + * using the integration runtime credential manager. Type: string (or Expression with resultType string). + * + * @param encryptedCredential the encryptedCredential value to set. + * @return the AzureSqlDWLinkedServiceTypeProperties object itself. + */ + public AzureSqlDWLinkedServiceTypeProperties setEncryptedCredential(Object encryptedCredential) { + this.encryptedCredential = encryptedCredential; + return this; + } + + /** + * Get the credential property: The credential reference containing authentication information. + * + * @return the credential value. + */ + public CredentialReference getCredential() { + return this.credential; + } + + /** + * Set the credential property: The credential reference containing authentication information. + * + * @param credential the credential value to set. + * @return the AzureSqlDWLinkedServiceTypeProperties object itself. + */ + public AzureSqlDWLinkedServiceTypeProperties setCredential(CredentialReference credential) { + this.credential = credential; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDWLinkedServiceTypeProperties setServer(Object server) { + super.setServer(server); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDWLinkedServiceTypeProperties setDatabase(Object database) { + super.setDatabase(database); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDWLinkedServiceTypeProperties setEncrypt(Object encrypt) { + super.setEncrypt(encrypt); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDWLinkedServiceTypeProperties setTrustServerCertificate(Object trustServerCertificate) { + super.setTrustServerCertificate(trustServerCertificate); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDWLinkedServiceTypeProperties setHostNameInCertificate(Object hostNameInCertificate) { + super.setHostNameInCertificate(hostNameInCertificate); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDWLinkedServiceTypeProperties setApplicationIntent(Object applicationIntent) { + super.setApplicationIntent(applicationIntent); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDWLinkedServiceTypeProperties setConnectTimeout(Object connectTimeout) { + super.setConnectTimeout(connectTimeout); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDWLinkedServiceTypeProperties setConnectRetryCount(Object connectRetryCount) { + super.setConnectRetryCount(connectRetryCount); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDWLinkedServiceTypeProperties setConnectRetryInterval(Object connectRetryInterval) { + super.setConnectRetryInterval(connectRetryInterval); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDWLinkedServiceTypeProperties setLoadBalanceTimeout(Object loadBalanceTimeout) { + super.setLoadBalanceTimeout(loadBalanceTimeout); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDWLinkedServiceTypeProperties setCommandTimeout(Object commandTimeout) { + super.setCommandTimeout(commandTimeout); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDWLinkedServiceTypeProperties setIntegratedSecurity(Object integratedSecurity) { + super.setIntegratedSecurity(integratedSecurity); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDWLinkedServiceTypeProperties setFailoverPartner(Object failoverPartner) { + super.setFailoverPartner(failoverPartner); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDWLinkedServiceTypeProperties setMaxPoolSize(Object maxPoolSize) { + super.setMaxPoolSize(maxPoolSize); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDWLinkedServiceTypeProperties setMinPoolSize(Object minPoolSize) { + super.setMinPoolSize(minPoolSize); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDWLinkedServiceTypeProperties setMultipleActiveResultSets(Object multipleActiveResultSets) { + super.setMultipleActiveResultSets(multipleActiveResultSets); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDWLinkedServiceTypeProperties setMultiSubnetFailover(Object multiSubnetFailover) { + super.setMultiSubnetFailover(multiSubnetFailover); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDWLinkedServiceTypeProperties setPacketSize(Object packetSize) { + super.setPacketSize(packetSize); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDWLinkedServiceTypeProperties setPooling(Object pooling) { + super.setPooling(pooling); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeUntypedField("server", getServer()); + jsonWriter.writeUntypedField("database", getDatabase()); + jsonWriter.writeUntypedField("encrypt", getEncrypt()); + jsonWriter.writeUntypedField("trustServerCertificate", getTrustServerCertificate()); + jsonWriter.writeUntypedField("hostNameInCertificate", getHostNameInCertificate()); + jsonWriter.writeUntypedField("applicationIntent", getApplicationIntent()); + jsonWriter.writeUntypedField("connectTimeout", getConnectTimeout()); + jsonWriter.writeUntypedField("connectRetryCount", getConnectRetryCount()); + jsonWriter.writeUntypedField("connectRetryInterval", getConnectRetryInterval()); + jsonWriter.writeUntypedField("loadBalanceTimeout", getLoadBalanceTimeout()); + jsonWriter.writeUntypedField("commandTimeout", getCommandTimeout()); + jsonWriter.writeUntypedField("integratedSecurity", getIntegratedSecurity()); + jsonWriter.writeUntypedField("failoverPartner", getFailoverPartner()); + jsonWriter.writeUntypedField("maxPoolSize", getMaxPoolSize()); + jsonWriter.writeUntypedField("minPoolSize", getMinPoolSize()); + jsonWriter.writeUntypedField("multipleActiveResultSets", getMultipleActiveResultSets()); + jsonWriter.writeUntypedField("multiSubnetFailover", getMultiSubnetFailover()); + jsonWriter.writeUntypedField("packetSize", getPacketSize()); + jsonWriter.writeUntypedField("pooling", getPooling()); + jsonWriter.writeUntypedField("connectionString", this.connectionString); + jsonWriter.writeStringField("authenticationType", + this.authenticationType == null ? null : this.authenticationType.toString()); + jsonWriter.writeUntypedField("userName", this.userName); + jsonWriter.writeJsonField("password", this.password); + jsonWriter.writeUntypedField("servicePrincipalId", this.servicePrincipalId); + jsonWriter.writeJsonField("servicePrincipalKey", this.servicePrincipalKey); + jsonWriter.writeUntypedField("servicePrincipalCredentialType", this.servicePrincipalCredentialType); + jsonWriter.writeJsonField("servicePrincipalCredential", this.servicePrincipalCredential); + jsonWriter.writeUntypedField("tenant", this.tenant); + jsonWriter.writeUntypedField("azureCloudType", this.azureCloudType); + jsonWriter.writeUntypedField("encryptedCredential", this.encryptedCredential); + jsonWriter.writeJsonField("credential", this.credential); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureSqlDWLinkedServiceTypeProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureSqlDWLinkedServiceTypeProperties 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 AzureSqlDWLinkedServiceTypeProperties. + */ + public static AzureSqlDWLinkedServiceTypeProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AzureSqlDWLinkedServiceTypeProperties deserializedAzureSqlDWLinkedServiceTypeProperties + = new AzureSqlDWLinkedServiceTypeProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("server".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.setServer(reader.readUntyped()); + } else if ("database".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.setDatabase(reader.readUntyped()); + } else if ("encrypt".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.setEncrypt(reader.readUntyped()); + } else if ("trustServerCertificate".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.setTrustServerCertificate(reader.readUntyped()); + } else if ("hostNameInCertificate".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.setHostNameInCertificate(reader.readUntyped()); + } else if ("applicationIntent".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.setApplicationIntent(reader.readUntyped()); + } else if ("connectTimeout".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.setConnectTimeout(reader.readUntyped()); + } else if ("connectRetryCount".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.setConnectRetryCount(reader.readUntyped()); + } else if ("connectRetryInterval".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.setConnectRetryInterval(reader.readUntyped()); + } else if ("loadBalanceTimeout".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.setLoadBalanceTimeout(reader.readUntyped()); + } else if ("commandTimeout".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.setCommandTimeout(reader.readUntyped()); + } else if ("integratedSecurity".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.setIntegratedSecurity(reader.readUntyped()); + } else if ("failoverPartner".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.setFailoverPartner(reader.readUntyped()); + } else if ("maxPoolSize".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.setMaxPoolSize(reader.readUntyped()); + } else if ("minPoolSize".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.setMinPoolSize(reader.readUntyped()); + } else if ("multipleActiveResultSets".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.setMultipleActiveResultSets(reader.readUntyped()); + } else if ("multiSubnetFailover".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.setMultiSubnetFailover(reader.readUntyped()); + } else if ("packetSize".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.setPacketSize(reader.readUntyped()); + } else if ("pooling".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.setPooling(reader.readUntyped()); + } else if ("connectionString".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.connectionString = reader.readUntyped(); + } else if ("authenticationType".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.authenticationType + = AzureSqlDWAuthenticationType.fromString(reader.getString()); + } else if ("userName".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.userName = reader.readUntyped(); + } else if ("password".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.password + = AzureKeyVaultSecretReference.fromJson(reader); + } else if ("servicePrincipalId".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.servicePrincipalId = reader.readUntyped(); + } else if ("servicePrincipalKey".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.servicePrincipalKey = SecretBase.fromJson(reader); + } else if ("servicePrincipalCredentialType".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.servicePrincipalCredentialType + = reader.readUntyped(); + } else if ("servicePrincipalCredential".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.servicePrincipalCredential + = SecretBase.fromJson(reader); + } else if ("tenant".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.tenant = reader.readUntyped(); + } else if ("azureCloudType".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.azureCloudType = reader.readUntyped(); + } else if ("encryptedCredential".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.encryptedCredential = reader.readUntyped(); + } else if ("credential".equals(fieldName)) { + deserializedAzureSqlDWLinkedServiceTypeProperties.credential = CredentialReference.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedAzureSqlDWLinkedServiceTypeProperties; + }); + } +} diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlDatabaseAuthenticationType.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlDatabaseAuthenticationType.java new file mode 100644 index 000000000000..05c5947b897d --- /dev/null +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlDatabaseAuthenticationType.java @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.analytics.synapse.artifacts.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The type used for authentication. Type: string. + */ +public final class AzureSqlDatabaseAuthenticationType extends ExpandableStringEnum { + /** + * Static value SQL for AzureSqlDatabaseAuthenticationType. + */ + public static final AzureSqlDatabaseAuthenticationType SQL = fromString("SQL"); + + /** + * Static value ServicePrincipal for AzureSqlDatabaseAuthenticationType. + */ + public static final AzureSqlDatabaseAuthenticationType SERVICE_PRINCIPAL = fromString("ServicePrincipal"); + + /** + * Static value SystemAssignedManagedIdentity for AzureSqlDatabaseAuthenticationType. + */ + public static final AzureSqlDatabaseAuthenticationType SYSTEM_ASSIGNED_MANAGED_IDENTITY + = fromString("SystemAssignedManagedIdentity"); + + /** + * Static value UserAssignedManagedIdentity for AzureSqlDatabaseAuthenticationType. + */ + public static final AzureSqlDatabaseAuthenticationType USER_ASSIGNED_MANAGED_IDENTITY + = fromString("UserAssignedManagedIdentity"); + + /** + * Creates a new instance of AzureSqlDatabaseAuthenticationType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureSqlDatabaseAuthenticationType() { + } + + /** + * Creates or finds a AzureSqlDatabaseAuthenticationType from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureSqlDatabaseAuthenticationType. + */ + public static AzureSqlDatabaseAuthenticationType fromString(String name) { + return fromString(name, AzureSqlDatabaseAuthenticationType.class); + } + + /** + * Gets known AzureSqlDatabaseAuthenticationType values. + * + * @return known AzureSqlDatabaseAuthenticationType values. + */ + public static Collection values() { + return values(AzureSqlDatabaseAuthenticationType.class); + } +} diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlDatabaseLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlDatabaseLinkedService.java index c0e0ab3dab18..7a559037af3d 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlDatabaseLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlDatabaseLinkedService.java @@ -23,11 +23,141 @@ public class AzureSqlDatabaseLinkedService extends LinkedService { */ private String type = "AzureSqlDatabase"; + /* + * The name or network address of the instance of SQL Server to which to connect, used by recommended version. Type: + * string (or Expression with resultType string). + */ + private Object server; + + /* + * The name of the database, used by recommended version. Type: string (or Expression with resultType string). + */ + private Object database; + + /* + * Indicate whether TLS encryption is required for all data sent between the client and server, used by recommended + * version. Possible values are true/yes/mandatory, false/no/optional and strict. Type: string (or Expression with + * resultType string). + */ + private Object encrypt; + + /* + * Indicate whether the channel will be encrypted while bypassing walking the certificate chain to validate trust, + * used by recommended version. Type: Boolean (or Expression with resultType boolean). + */ + private Object trustServerCertificate; + + /* + * The host name to use when validating the server certificate for the connection. When not specified, the server + * name from the Data Source is used for certificate validation, used by recommended version. Type: string (or + * Expression with resultType string). + */ + private Object hostNameInCertificate; + + /* + * The application workload type when connecting to a server, used by recommended version. Possible values are + * ReadOnly and ReadWrite. Type: string (or Expression with resultType string). + */ + private Object applicationIntent; + + /* + * The length of time (in seconds) to wait for a connection to the server before terminating the attempt and + * generating an error, used by recommended version. Type: integer (or Expression with resultType integer). + */ + private Object connectTimeout; + + /* + * The number of re-connections attempted after identifying that there was an idle connection failure, used by + * recommended version. This must be an integer between 0 and 255. Type: integer (or Expression with resultType + * integer). + */ + private Object connectRetryCount; + + /* + * The amount of time (in seconds) between each re-connection attempt after identifying that there was an idle + * connection failure, used by recommended version. This must be an integer between 1 and 60. Type: integer (or + * Expression with resultType integer). + */ + private Object connectRetryInterval; + + /* + * The minimum time, in seconds, for the connection to live in the connection pool before being destroyed, used by + * recommended version. Type: integer (or Expression with resultType integer). + */ + private Object loadBalanceTimeout; + + /* + * The default wait time (in seconds) before terminating the attempt to execute a command and generating an error, + * used by recommended version. Type: integer (or Expression with resultType integer). + */ + private Object commandTimeout; + + /* + * Indicate whether User ID and Password are specified in the connection (when false) or whether the current Windows + * account credentials are used for authentication (when true), used by recommended version. Type: Boolean (or + * Expression with resultType boolean). + */ + private Object integratedSecurity; + + /* + * The name or address of the partner server to connect to if the primary server is down, used by recommended + * version. Type: string (or Expression with resultType string). + */ + private Object failoverPartner; + + /* + * The maximum number of connections allowed in the connection pool for this specific connection string, used by + * recommended version. Type: integer (or Expression with resultType integer). + */ + private Object maxPoolSize; + + /* + * The minimum number of connections allowed in the connection pool for this specific connection string, used by + * recommended version. Type: integer (or Expression with resultType integer). + */ + private Object minPoolSize; + + /* + * When true, an application can maintain multiple active result sets (MARS). When false, an application must + * process or cancel all result sets from one batch before it can execute any other batch on that connection. Type: + * Boolean (or Expression with resultType boolean). + */ + private Object multipleActiveResultSets; + + /* + * If your application is connecting to an AlwaysOn availability group (AG) on different subnets, setting + * MultiSubnetFailover=true provides faster detection of and connection to the (currently) active server, used by + * recommended version. Type: Boolean (or Expression with resultType boolean). + */ + private Object multiSubnetFailover; + + /* + * The size in bytes of the network packets used to communicate with an instance of server, used by recommended + * version. Type: integer (or Expression with resultType integer). + */ + private Object packetSize; + + /* + * Indicate whether the connection will be pooled or explicitly opened every time that the connection is requested, + * used by recommended version. Type: Boolean (or Expression with resultType boolean). + */ + private Object pooling; + /* * The connection string. Type: string, SecureString or AzureKeyVaultSecretReference. */ private Object connectionString; + /* + * The type used for authentication. Type: string. + */ + private AzureSqlDatabaseAuthenticationType authenticationType; + + /* + * The user name to be used when connecting to server. Type: string (or Expression with resultType string). + */ + private Object userName; + /* * The Azure key vault secret reference of password in connection string. */ @@ -44,6 +174,20 @@ public class AzureSqlDatabaseLinkedService extends LinkedService { */ private SecretBase servicePrincipalKey; + /* + * The service principal credential type to use in Server-To-Server authentication. 'ServicePrincipalKey' for + * key/secret, 'ServicePrincipalCert' for certificate. Type: string (or Expression with resultType string). + */ + private Object servicePrincipalCredentialType; + + /* + * The credential of the service principal object in Azure Active Directory. If servicePrincipalCredentialType is + * 'ServicePrincipalKey', servicePrincipalCredential can be SecureString or AzureKeyVaultSecretReference. If + * servicePrincipalCredentialType is 'ServicePrincipalCert', servicePrincipalCredential can only be + * AzureKeyVaultSecretReference. + */ + private SecretBase servicePrincipalCredential; + /* * The name or ID of the tenant to which the service principal belongs. Type: string (or Expression with resultType * string). @@ -89,6 +233,446 @@ public String getType() { return this.type; } + /** + * Get the server property: The name or network address of the instance of SQL Server to which to connect, used by + * recommended version. Type: string (or Expression with resultType string). + * + * @return the server value. + */ + public Object getServer() { + return this.server; + } + + /** + * Set the server property: The name or network address of the instance of SQL Server to which to connect, used by + * recommended version. Type: string (or Expression with resultType string). + * + * @param server the server value to set. + * @return the AzureSqlDatabaseLinkedService object itself. + */ + public AzureSqlDatabaseLinkedService setServer(Object server) { + this.server = server; + return this; + } + + /** + * Get the database property: The name of the database, used by recommended version. Type: string (or Expression + * with resultType string). + * + * @return the database value. + */ + public Object getDatabase() { + return this.database; + } + + /** + * Set the database property: The name of the database, used by recommended version. Type: string (or Expression + * with resultType string). + * + * @param database the database value to set. + * @return the AzureSqlDatabaseLinkedService object itself. + */ + public AzureSqlDatabaseLinkedService setDatabase(Object database) { + this.database = database; + return this; + } + + /** + * Get the encrypt property: Indicate whether TLS encryption is required for all data sent between the client and + * server, used by recommended version. Possible values are true/yes/mandatory, false/no/optional and strict. Type: + * string (or Expression with resultType string). + * + * @return the encrypt value. + */ + public Object getEncrypt() { + return this.encrypt; + } + + /** + * Set the encrypt property: Indicate whether TLS encryption is required for all data sent between the client and + * server, used by recommended version. Possible values are true/yes/mandatory, false/no/optional and strict. Type: + * string (or Expression with resultType string). + * + * @param encrypt the encrypt value to set. + * @return the AzureSqlDatabaseLinkedService object itself. + */ + public AzureSqlDatabaseLinkedService setEncrypt(Object encrypt) { + this.encrypt = encrypt; + return this; + } + + /** + * Get the trustServerCertificate property: Indicate whether the channel will be encrypted while bypassing walking + * the certificate chain to validate trust, used by recommended version. Type: Boolean (or Expression with + * resultType boolean). + * + * @return the trustServerCertificate value. + */ + public Object getTrustServerCertificate() { + return this.trustServerCertificate; + } + + /** + * Set the trustServerCertificate property: Indicate whether the channel will be encrypted while bypassing walking + * the certificate chain to validate trust, used by recommended version. Type: Boolean (or Expression with + * resultType boolean). + * + * @param trustServerCertificate the trustServerCertificate value to set. + * @return the AzureSqlDatabaseLinkedService object itself. + */ + public AzureSqlDatabaseLinkedService setTrustServerCertificate(Object trustServerCertificate) { + this.trustServerCertificate = trustServerCertificate; + return this; + } + + /** + * Get the hostNameInCertificate property: The host name to use when validating the server certificate for the + * connection. When not specified, the server name from the Data Source is used for certificate validation, used by + * recommended version. Type: string (or Expression with resultType string). + * + * @return the hostNameInCertificate value. + */ + public Object getHostNameInCertificate() { + return this.hostNameInCertificate; + } + + /** + * Set the hostNameInCertificate property: The host name to use when validating the server certificate for the + * connection. When not specified, the server name from the Data Source is used for certificate validation, used by + * recommended version. Type: string (or Expression with resultType string). + * + * @param hostNameInCertificate the hostNameInCertificate value to set. + * @return the AzureSqlDatabaseLinkedService object itself. + */ + public AzureSqlDatabaseLinkedService setHostNameInCertificate(Object hostNameInCertificate) { + this.hostNameInCertificate = hostNameInCertificate; + return this; + } + + /** + * Get the applicationIntent property: The application workload type when connecting to a server, used by + * recommended version. Possible values are ReadOnly and ReadWrite. Type: string (or Expression with resultType + * string). + * + * @return the applicationIntent value. + */ + public Object getApplicationIntent() { + return this.applicationIntent; + } + + /** + * Set the applicationIntent property: The application workload type when connecting to a server, used by + * recommended version. Possible values are ReadOnly and ReadWrite. Type: string (or Expression with resultType + * string). + * + * @param applicationIntent the applicationIntent value to set. + * @return the AzureSqlDatabaseLinkedService object itself. + */ + public AzureSqlDatabaseLinkedService setApplicationIntent(Object applicationIntent) { + this.applicationIntent = applicationIntent; + return this; + } + + /** + * Get the connectTimeout property: The length of time (in seconds) to wait for a connection to the server before + * terminating the attempt and generating an error, used by recommended version. Type: integer (or Expression with + * resultType integer). + * + * @return the connectTimeout value. + */ + public Object getConnectTimeout() { + return this.connectTimeout; + } + + /** + * Set the connectTimeout property: The length of time (in seconds) to wait for a connection to the server before + * terminating the attempt and generating an error, used by recommended version. Type: integer (or Expression with + * resultType integer). + * + * @param connectTimeout the connectTimeout value to set. + * @return the AzureSqlDatabaseLinkedService object itself. + */ + public AzureSqlDatabaseLinkedService setConnectTimeout(Object connectTimeout) { + this.connectTimeout = connectTimeout; + return this; + } + + /** + * Get the connectRetryCount property: The number of re-connections attempted after identifying that there was an + * idle connection failure, used by recommended version. This must be an integer between 0 and 255. Type: integer + * (or Expression with resultType integer). + * + * @return the connectRetryCount value. + */ + public Object getConnectRetryCount() { + return this.connectRetryCount; + } + + /** + * Set the connectRetryCount property: The number of re-connections attempted after identifying that there was an + * idle connection failure, used by recommended version. This must be an integer between 0 and 255. Type: integer + * (or Expression with resultType integer). + * + * @param connectRetryCount the connectRetryCount value to set. + * @return the AzureSqlDatabaseLinkedService object itself. + */ + public AzureSqlDatabaseLinkedService setConnectRetryCount(Object connectRetryCount) { + this.connectRetryCount = connectRetryCount; + return this; + } + + /** + * Get the connectRetryInterval property: The amount of time (in seconds) between each re-connection attempt after + * identifying that there was an idle connection failure, used by recommended version. This must be an integer + * between 1 and 60. Type: integer (or Expression with resultType integer). + * + * @return the connectRetryInterval value. + */ + public Object getConnectRetryInterval() { + return this.connectRetryInterval; + } + + /** + * Set the connectRetryInterval property: The amount of time (in seconds) between each re-connection attempt after + * identifying that there was an idle connection failure, used by recommended version. This must be an integer + * between 1 and 60. Type: integer (or Expression with resultType integer). + * + * @param connectRetryInterval the connectRetryInterval value to set. + * @return the AzureSqlDatabaseLinkedService object itself. + */ + public AzureSqlDatabaseLinkedService setConnectRetryInterval(Object connectRetryInterval) { + this.connectRetryInterval = connectRetryInterval; + return this; + } + + /** + * Get the loadBalanceTimeout property: The minimum time, in seconds, for the connection to live in the connection + * pool before being destroyed, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @return the loadBalanceTimeout value. + */ + public Object getLoadBalanceTimeout() { + return this.loadBalanceTimeout; + } + + /** + * Set the loadBalanceTimeout property: The minimum time, in seconds, for the connection to live in the connection + * pool before being destroyed, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @param loadBalanceTimeout the loadBalanceTimeout value to set. + * @return the AzureSqlDatabaseLinkedService object itself. + */ + public AzureSqlDatabaseLinkedService setLoadBalanceTimeout(Object loadBalanceTimeout) { + this.loadBalanceTimeout = loadBalanceTimeout; + return this; + } + + /** + * Get the commandTimeout property: The default wait time (in seconds) before terminating the attempt to execute a + * command and generating an error, used by recommended version. Type: integer (or Expression with resultType + * integer). + * + * @return the commandTimeout value. + */ + public Object getCommandTimeout() { + return this.commandTimeout; + } + + /** + * Set the commandTimeout property: The default wait time (in seconds) before terminating the attempt to execute a + * command and generating an error, used by recommended version. Type: integer (or Expression with resultType + * integer). + * + * @param commandTimeout the commandTimeout value to set. + * @return the AzureSqlDatabaseLinkedService object itself. + */ + public AzureSqlDatabaseLinkedService setCommandTimeout(Object commandTimeout) { + this.commandTimeout = commandTimeout; + return this; + } + + /** + * Get the integratedSecurity property: Indicate whether User ID and Password are specified in the connection (when + * false) or whether the current Windows account credentials are used for authentication (when true), used by + * recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @return the integratedSecurity value. + */ + public Object getIntegratedSecurity() { + return this.integratedSecurity; + } + + /** + * Set the integratedSecurity property: Indicate whether User ID and Password are specified in the connection (when + * false) or whether the current Windows account credentials are used for authentication (when true), used by + * recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @param integratedSecurity the integratedSecurity value to set. + * @return the AzureSqlDatabaseLinkedService object itself. + */ + public AzureSqlDatabaseLinkedService setIntegratedSecurity(Object integratedSecurity) { + this.integratedSecurity = integratedSecurity; + return this; + } + + /** + * Get the failoverPartner property: The name or address of the partner server to connect to if the primary server + * is down, used by recommended version. Type: string (or Expression with resultType string). + * + * @return the failoverPartner value. + */ + public Object getFailoverPartner() { + return this.failoverPartner; + } + + /** + * Set the failoverPartner property: The name or address of the partner server to connect to if the primary server + * is down, used by recommended version. Type: string (or Expression with resultType string). + * + * @param failoverPartner the failoverPartner value to set. + * @return the AzureSqlDatabaseLinkedService object itself. + */ + public AzureSqlDatabaseLinkedService setFailoverPartner(Object failoverPartner) { + this.failoverPartner = failoverPartner; + return this; + } + + /** + * Get the maxPoolSize property: The maximum number of connections allowed in the connection pool for this specific + * connection string, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @return the maxPoolSize value. + */ + public Object getMaxPoolSize() { + return this.maxPoolSize; + } + + /** + * Set the maxPoolSize property: The maximum number of connections allowed in the connection pool for this specific + * connection string, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @param maxPoolSize the maxPoolSize value to set. + * @return the AzureSqlDatabaseLinkedService object itself. + */ + public AzureSqlDatabaseLinkedService setMaxPoolSize(Object maxPoolSize) { + this.maxPoolSize = maxPoolSize; + return this; + } + + /** + * Get the minPoolSize property: The minimum number of connections allowed in the connection pool for this specific + * connection string, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @return the minPoolSize value. + */ + public Object getMinPoolSize() { + return this.minPoolSize; + } + + /** + * Set the minPoolSize property: The minimum number of connections allowed in the connection pool for this specific + * connection string, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @param minPoolSize the minPoolSize value to set. + * @return the AzureSqlDatabaseLinkedService object itself. + */ + public AzureSqlDatabaseLinkedService setMinPoolSize(Object minPoolSize) { + this.minPoolSize = minPoolSize; + return this; + } + + /** + * Get the multipleActiveResultSets property: When true, an application can maintain multiple active result sets + * (MARS). When false, an application must process or cancel all result sets from one batch before it can execute + * any other batch on that connection. Type: Boolean (or Expression with resultType boolean). + * + * @return the multipleActiveResultSets value. + */ + public Object getMultipleActiveResultSets() { + return this.multipleActiveResultSets; + } + + /** + * Set the multipleActiveResultSets property: When true, an application can maintain multiple active result sets + * (MARS). When false, an application must process or cancel all result sets from one batch before it can execute + * any other batch on that connection. Type: Boolean (or Expression with resultType boolean). + * + * @param multipleActiveResultSets the multipleActiveResultSets value to set. + * @return the AzureSqlDatabaseLinkedService object itself. + */ + public AzureSqlDatabaseLinkedService setMultipleActiveResultSets(Object multipleActiveResultSets) { + this.multipleActiveResultSets = multipleActiveResultSets; + return this; + } + + /** + * Get the multiSubnetFailover property: If your application is connecting to an AlwaysOn availability group (AG) on + * different subnets, setting MultiSubnetFailover=true provides faster detection of and connection to the + * (currently) active server, used by recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @return the multiSubnetFailover value. + */ + public Object getMultiSubnetFailover() { + return this.multiSubnetFailover; + } + + /** + * Set the multiSubnetFailover property: If your application is connecting to an AlwaysOn availability group (AG) on + * different subnets, setting MultiSubnetFailover=true provides faster detection of and connection to the + * (currently) active server, used by recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @param multiSubnetFailover the multiSubnetFailover value to set. + * @return the AzureSqlDatabaseLinkedService object itself. + */ + public AzureSqlDatabaseLinkedService setMultiSubnetFailover(Object multiSubnetFailover) { + this.multiSubnetFailover = multiSubnetFailover; + return this; + } + + /** + * Get the packetSize property: The size in bytes of the network packets used to communicate with an instance of + * server, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @return the packetSize value. + */ + public Object getPacketSize() { + return this.packetSize; + } + + /** + * Set the packetSize property: The size in bytes of the network packets used to communicate with an instance of + * server, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @param packetSize the packetSize value to set. + * @return the AzureSqlDatabaseLinkedService object itself. + */ + public AzureSqlDatabaseLinkedService setPacketSize(Object packetSize) { + this.packetSize = packetSize; + return this; + } + + /** + * Get the pooling property: Indicate whether the connection will be pooled or explicitly opened every time that the + * connection is requested, used by recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @return the pooling value. + */ + public Object getPooling() { + return this.pooling; + } + + /** + * Set the pooling property: Indicate whether the connection will be pooled or explicitly opened every time that the + * connection is requested, used by recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @param pooling the pooling value to set. + * @return the AzureSqlDatabaseLinkedService object itself. + */ + public AzureSqlDatabaseLinkedService setPooling(Object pooling) { + this.pooling = pooling; + return this; + } + /** * Get the connectionString property: The connection string. Type: string, SecureString or * AzureKeyVaultSecretReference. @@ -111,6 +695,48 @@ public AzureSqlDatabaseLinkedService setConnectionString(Object connectionString return this; } + /** + * Get the authenticationType property: The type used for authentication. Type: string. + * + * @return the authenticationType value. + */ + public AzureSqlDatabaseAuthenticationType getAuthenticationType() { + return this.authenticationType; + } + + /** + * Set the authenticationType property: The type used for authentication. Type: string. + * + * @param authenticationType the authenticationType value to set. + * @return the AzureSqlDatabaseLinkedService object itself. + */ + public AzureSqlDatabaseLinkedService setAuthenticationType(AzureSqlDatabaseAuthenticationType authenticationType) { + this.authenticationType = authenticationType; + return this; + } + + /** + * Get the userName property: The user name to be used when connecting to server. Type: string (or Expression with + * resultType string). + * + * @return the userName value. + */ + public Object getUserName() { + return this.userName; + } + + /** + * Set the userName property: The user name to be used when connecting to server. Type: string (or Expression with + * resultType string). + * + * @param userName the userName value to set. + * @return the AzureSqlDatabaseLinkedService object itself. + */ + public AzureSqlDatabaseLinkedService setUserName(Object userName) { + this.userName = userName; + return this; + } + /** * Get the password property: The Azure key vault secret reference of password in connection string. * @@ -175,6 +801,56 @@ public AzureSqlDatabaseLinkedService setServicePrincipalKey(SecretBase servicePr return this; } + /** + * Get the servicePrincipalCredentialType property: The service principal credential type to use in Server-To-Server + * authentication. 'ServicePrincipalKey' for key/secret, 'ServicePrincipalCert' for certificate. Type: string (or + * Expression with resultType string). + * + * @return the servicePrincipalCredentialType value. + */ + public Object getServicePrincipalCredentialType() { + return this.servicePrincipalCredentialType; + } + + /** + * Set the servicePrincipalCredentialType property: The service principal credential type to use in Server-To-Server + * authentication. 'ServicePrincipalKey' for key/secret, 'ServicePrincipalCert' for certificate. Type: string (or + * Expression with resultType string). + * + * @param servicePrincipalCredentialType the servicePrincipalCredentialType value to set. + * @return the AzureSqlDatabaseLinkedService object itself. + */ + public AzureSqlDatabaseLinkedService setServicePrincipalCredentialType(Object servicePrincipalCredentialType) { + this.servicePrincipalCredentialType = servicePrincipalCredentialType; + return this; + } + + /** + * Get the servicePrincipalCredential property: The credential of the service principal object in Azure Active + * Directory. If servicePrincipalCredentialType is 'ServicePrincipalKey', servicePrincipalCredential can be + * SecureString or AzureKeyVaultSecretReference. If servicePrincipalCredentialType is 'ServicePrincipalCert', + * servicePrincipalCredential can only be AzureKeyVaultSecretReference. + * + * @return the servicePrincipalCredential value. + */ + public SecretBase getServicePrincipalCredential() { + return this.servicePrincipalCredential; + } + + /** + * Set the servicePrincipalCredential property: The credential of the service principal object in Azure Active + * Directory. If servicePrincipalCredentialType is 'ServicePrincipalKey', servicePrincipalCredential can be + * SecureString or AzureKeyVaultSecretReference. If servicePrincipalCredentialType is 'ServicePrincipalCert', + * servicePrincipalCredential can only be AzureKeyVaultSecretReference. + * + * @param servicePrincipalCredential the servicePrincipalCredential value to set. + * @return the AzureSqlDatabaseLinkedService object itself. + */ + public AzureSqlDatabaseLinkedService setServicePrincipalCredential(SecretBase servicePrincipalCredential) { + this.servicePrincipalCredential = servicePrincipalCredential; + return this; + } + /** * Get the tenant property: The name or ID of the tenant to which the service principal belongs. Type: string (or * Expression with resultType string). @@ -284,6 +960,15 @@ public AzureSqlDatabaseLinkedService setCredential(CredentialReference credentia return this; } + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDatabaseLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -326,25 +1011,73 @@ public AzureSqlDatabaseLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); jsonWriter.writeArrayField("annotations", getAnnotations(), (writer, element) -> writer.writeUntyped(element)); jsonWriter.writeStringField("type", this.type); - if (connectionString != null + if (server != null + || database != null + || encrypt != null + || trustServerCertificate != null + || hostNameInCertificate != null + || applicationIntent != null + || connectTimeout != null + || connectRetryCount != null + || connectRetryInterval != null + || loadBalanceTimeout != null + || commandTimeout != null + || integratedSecurity != null + || failoverPartner != null + || maxPoolSize != null + || minPoolSize != null + || multipleActiveResultSets != null + || multiSubnetFailover != null + || packetSize != null + || pooling != null + || connectionString != null + || authenticationType != null + || userName != null || password != null || servicePrincipalId != null || servicePrincipalKey != null + || servicePrincipalCredentialType != null + || servicePrincipalCredential != null || tenant != null || azureCloudType != null || alwaysEncryptedSettings != null || encryptedCredential != null || credential != null) { jsonWriter.writeStartObject("typeProperties"); + jsonWriter.writeUntypedField("server", this.server); + jsonWriter.writeUntypedField("database", this.database); + jsonWriter.writeUntypedField("encrypt", this.encrypt); + jsonWriter.writeUntypedField("trustServerCertificate", this.trustServerCertificate); + jsonWriter.writeUntypedField("hostNameInCertificate", this.hostNameInCertificate); + jsonWriter.writeUntypedField("applicationIntent", this.applicationIntent); + jsonWriter.writeUntypedField("connectTimeout", this.connectTimeout); + jsonWriter.writeUntypedField("connectRetryCount", this.connectRetryCount); + jsonWriter.writeUntypedField("connectRetryInterval", this.connectRetryInterval); + jsonWriter.writeUntypedField("loadBalanceTimeout", this.loadBalanceTimeout); + jsonWriter.writeUntypedField("commandTimeout", this.commandTimeout); + jsonWriter.writeUntypedField("integratedSecurity", this.integratedSecurity); + jsonWriter.writeUntypedField("failoverPartner", this.failoverPartner); + jsonWriter.writeUntypedField("maxPoolSize", this.maxPoolSize); + jsonWriter.writeUntypedField("minPoolSize", this.minPoolSize); + jsonWriter.writeUntypedField("multipleActiveResultSets", this.multipleActiveResultSets); + jsonWriter.writeUntypedField("multiSubnetFailover", this.multiSubnetFailover); + jsonWriter.writeUntypedField("packetSize", this.packetSize); + jsonWriter.writeUntypedField("pooling", this.pooling); jsonWriter.writeUntypedField("connectionString", this.connectionString); + jsonWriter.writeStringField("authenticationType", + this.authenticationType == null ? null : this.authenticationType.toString()); + jsonWriter.writeUntypedField("userName", this.userName); jsonWriter.writeJsonField("password", this.password); jsonWriter.writeUntypedField("servicePrincipalId", this.servicePrincipalId); jsonWriter.writeJsonField("servicePrincipalKey", this.servicePrincipalKey); + jsonWriter.writeUntypedField("servicePrincipalCredentialType", this.servicePrincipalCredentialType); + jsonWriter.writeJsonField("servicePrincipalCredential", this.servicePrincipalCredential); jsonWriter.writeUntypedField("tenant", this.tenant); jsonWriter.writeUntypedField("azureCloudType", this.azureCloudType); jsonWriter.writeJsonField("alwaysEncryptedSettings", this.alwaysEncryptedSettings); @@ -366,7 +1099,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @param jsonReader The JsonReader being read. * @return An instance of AzureSqlDatabaseLinkedService 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 AzureSqlDatabaseLinkedService. */ public static AzureSqlDatabaseLinkedService fromJson(JsonReader jsonReader) throws IOException { @@ -378,7 +1110,9 @@ public static AzureSqlDatabaseLinkedService fromJson(JsonReader jsonReader) thro String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAzureSqlDatabaseLinkedService .setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { @@ -397,8 +1131,51 @@ public static AzureSqlDatabaseLinkedService fromJson(JsonReader jsonReader) thro fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectionString".equals(fieldName)) { + if ("server".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedService.server = reader.readUntyped(); + } else if ("database".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedService.database = reader.readUntyped(); + } else if ("encrypt".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedService.encrypt = reader.readUntyped(); + } else if ("trustServerCertificate".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedService.trustServerCertificate = reader.readUntyped(); + } else if ("hostNameInCertificate".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedService.hostNameInCertificate = reader.readUntyped(); + } else if ("applicationIntent".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedService.applicationIntent = reader.readUntyped(); + } else if ("connectTimeout".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedService.connectTimeout = reader.readUntyped(); + } else if ("connectRetryCount".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedService.connectRetryCount = reader.readUntyped(); + } else if ("connectRetryInterval".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedService.connectRetryInterval = reader.readUntyped(); + } else if ("loadBalanceTimeout".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedService.loadBalanceTimeout = reader.readUntyped(); + } else if ("commandTimeout".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedService.commandTimeout = reader.readUntyped(); + } else if ("integratedSecurity".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedService.integratedSecurity = reader.readUntyped(); + } else if ("failoverPartner".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedService.failoverPartner = reader.readUntyped(); + } else if ("maxPoolSize".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedService.maxPoolSize = reader.readUntyped(); + } else if ("minPoolSize".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedService.minPoolSize = reader.readUntyped(); + } else if ("multipleActiveResultSets".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedService.multipleActiveResultSets = reader.readUntyped(); + } else if ("multiSubnetFailover".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedService.multiSubnetFailover = reader.readUntyped(); + } else if ("packetSize".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedService.packetSize = reader.readUntyped(); + } else if ("pooling".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedService.pooling = reader.readUntyped(); + } else if ("connectionString".equals(fieldName)) { deserializedAzureSqlDatabaseLinkedService.connectionString = reader.readUntyped(); + } else if ("authenticationType".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedService.authenticationType + = AzureSqlDatabaseAuthenticationType.fromString(reader.getString()); + } else if ("userName".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedService.userName = reader.readUntyped(); } else if ("password".equals(fieldName)) { deserializedAzureSqlDatabaseLinkedService.password = AzureKeyVaultSecretReference.fromJson(reader); @@ -406,6 +1183,12 @@ public static AzureSqlDatabaseLinkedService fromJson(JsonReader jsonReader) thro deserializedAzureSqlDatabaseLinkedService.servicePrincipalId = reader.readUntyped(); } else if ("servicePrincipalKey".equals(fieldName)) { deserializedAzureSqlDatabaseLinkedService.servicePrincipalKey = SecretBase.fromJson(reader); + } else if ("servicePrincipalCredentialType".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedService.servicePrincipalCredentialType + = reader.readUntyped(); + } else if ("servicePrincipalCredential".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedService.servicePrincipalCredential + = SecretBase.fromJson(reader); } else if ("tenant".equals(fieldName)) { deserializedAzureSqlDatabaseLinkedService.tenant = reader.readUntyped(); } else if ("azureCloudType".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlDatabaseLinkedServiceTypeProperties.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlDatabaseLinkedServiceTypeProperties.java new file mode 100644 index 000000000000..11fcf8f0bd8b --- /dev/null +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlDatabaseLinkedServiceTypeProperties.java @@ -0,0 +1,701 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.analytics.synapse.artifacts.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; + +/** + * Azure SQL Database linked service properties. + */ +@Fluent +public final class AzureSqlDatabaseLinkedServiceTypeProperties extends SqlServerBaseLinkedServiceTypeProperties { + /* + * The connection string. Type: string, SecureString or AzureKeyVaultSecretReference. + */ + private Object connectionString; + + /* + * The type used for authentication. Type: string. + */ + private AzureSqlDatabaseAuthenticationType authenticationType; + + /* + * The user name to be used when connecting to server. Type: string (or Expression with resultType string). + */ + private Object userName; + + /* + * The Azure key vault secret reference of password in connection string. + */ + private AzureKeyVaultSecretReference password; + + /* + * The ID of the service principal used to authenticate against Azure SQL Database. Type: string (or Expression with + * resultType string). + */ + private Object servicePrincipalId; + + /* + * The key of the service principal used to authenticate against Azure SQL Database. + */ + private SecretBase servicePrincipalKey; + + /* + * The service principal credential type to use in Server-To-Server authentication. 'ServicePrincipalKey' for + * key/secret, 'ServicePrincipalCert' for certificate. Type: string (or Expression with resultType string). + */ + private Object servicePrincipalCredentialType; + + /* + * The credential of the service principal object in Azure Active Directory. If servicePrincipalCredentialType is + * 'ServicePrincipalKey', servicePrincipalCredential can be SecureString or AzureKeyVaultSecretReference. If + * servicePrincipalCredentialType is 'ServicePrincipalCert', servicePrincipalCredential can only be + * AzureKeyVaultSecretReference. + */ + private SecretBase servicePrincipalCredential; + + /* + * The name or ID of the tenant to which the service principal belongs. Type: string (or Expression with resultType + * string). + */ + private Object tenant; + + /* + * Indicates the azure cloud type of the service principle auth. Allowed values are AzurePublic, AzureChina, + * AzureUsGovernment, AzureGermany. Default value is the data factory regions’ cloud type. Type: string (or + * Expression with resultType string). + */ + private Object azureCloudType; + + /* + * Sql always encrypted properties. + */ + private SqlAlwaysEncryptedProperties alwaysEncryptedSettings; + + /* + * The encrypted credential used for authentication. Credentials are encrypted using the integration runtime + * credential manager. Type: string (or Expression with resultType string). + */ + private Object encryptedCredential; + + /* + * The credential reference containing authentication information. + */ + private CredentialReference credential; + + /** + * Creates an instance of AzureSqlDatabaseLinkedServiceTypeProperties class. + */ + public AzureSqlDatabaseLinkedServiceTypeProperties() { + } + + /** + * Get the connectionString property: The connection string. Type: string, SecureString or + * AzureKeyVaultSecretReference. + * + * @return the connectionString value. + */ + public Object getConnectionString() { + return this.connectionString; + } + + /** + * Set the connectionString property: The connection string. Type: string, SecureString or + * AzureKeyVaultSecretReference. + * + * @param connectionString the connectionString value to set. + * @return the AzureSqlDatabaseLinkedServiceTypeProperties object itself. + */ + public AzureSqlDatabaseLinkedServiceTypeProperties setConnectionString(Object connectionString) { + this.connectionString = connectionString; + return this; + } + + /** + * Get the authenticationType property: The type used for authentication. Type: string. + * + * @return the authenticationType value. + */ + public AzureSqlDatabaseAuthenticationType getAuthenticationType() { + return this.authenticationType; + } + + /** + * Set the authenticationType property: The type used for authentication. Type: string. + * + * @param authenticationType the authenticationType value to set. + * @return the AzureSqlDatabaseLinkedServiceTypeProperties object itself. + */ + public AzureSqlDatabaseLinkedServiceTypeProperties + setAuthenticationType(AzureSqlDatabaseAuthenticationType authenticationType) { + this.authenticationType = authenticationType; + return this; + } + + /** + * Get the userName property: The user name to be used when connecting to server. Type: string (or Expression with + * resultType string). + * + * @return the userName value. + */ + public Object getUserName() { + return this.userName; + } + + /** + * Set the userName property: The user name to be used when connecting to server. Type: string (or Expression with + * resultType string). + * + * @param userName the userName value to set. + * @return the AzureSqlDatabaseLinkedServiceTypeProperties object itself. + */ + public AzureSqlDatabaseLinkedServiceTypeProperties setUserName(Object userName) { + this.userName = userName; + return this; + } + + /** + * Get the password property: The Azure key vault secret reference of password in connection string. + * + * @return the password value. + */ + public AzureKeyVaultSecretReference getPassword() { + return this.password; + } + + /** + * Set the password property: The Azure key vault secret reference of password in connection string. + * + * @param password the password value to set. + * @return the AzureSqlDatabaseLinkedServiceTypeProperties object itself. + */ + public AzureSqlDatabaseLinkedServiceTypeProperties setPassword(AzureKeyVaultSecretReference password) { + this.password = password; + return this; + } + + /** + * Get the servicePrincipalId property: The ID of the service principal used to authenticate against Azure SQL + * Database. Type: string (or Expression with resultType string). + * + * @return the servicePrincipalId value. + */ + public Object getServicePrincipalId() { + return this.servicePrincipalId; + } + + /** + * Set the servicePrincipalId property: The ID of the service principal used to authenticate against Azure SQL + * Database. Type: string (or Expression with resultType string). + * + * @param servicePrincipalId the servicePrincipalId value to set. + * @return the AzureSqlDatabaseLinkedServiceTypeProperties object itself. + */ + public AzureSqlDatabaseLinkedServiceTypeProperties setServicePrincipalId(Object servicePrincipalId) { + this.servicePrincipalId = servicePrincipalId; + return this; + } + + /** + * Get the servicePrincipalKey property: The key of the service principal used to authenticate against Azure SQL + * Database. + * + * @return the servicePrincipalKey value. + */ + public SecretBase getServicePrincipalKey() { + return this.servicePrincipalKey; + } + + /** + * Set the servicePrincipalKey property: The key of the service principal used to authenticate against Azure SQL + * Database. + * + * @param servicePrincipalKey the servicePrincipalKey value to set. + * @return the AzureSqlDatabaseLinkedServiceTypeProperties object itself. + */ + public AzureSqlDatabaseLinkedServiceTypeProperties setServicePrincipalKey(SecretBase servicePrincipalKey) { + this.servicePrincipalKey = servicePrincipalKey; + return this; + } + + /** + * Get the servicePrincipalCredentialType property: The service principal credential type to use in Server-To-Server + * authentication. 'ServicePrincipalKey' for key/secret, 'ServicePrincipalCert' for certificate. Type: string (or + * Expression with resultType string). + * + * @return the servicePrincipalCredentialType value. + */ + public Object getServicePrincipalCredentialType() { + return this.servicePrincipalCredentialType; + } + + /** + * Set the servicePrincipalCredentialType property: The service principal credential type to use in Server-To-Server + * authentication. 'ServicePrincipalKey' for key/secret, 'ServicePrincipalCert' for certificate. Type: string (or + * Expression with resultType string). + * + * @param servicePrincipalCredentialType the servicePrincipalCredentialType value to set. + * @return the AzureSqlDatabaseLinkedServiceTypeProperties object itself. + */ + public AzureSqlDatabaseLinkedServiceTypeProperties + setServicePrincipalCredentialType(Object servicePrincipalCredentialType) { + this.servicePrincipalCredentialType = servicePrincipalCredentialType; + return this; + } + + /** + * Get the servicePrincipalCredential property: The credential of the service principal object in Azure Active + * Directory. If servicePrincipalCredentialType is 'ServicePrincipalKey', servicePrincipalCredential can be + * SecureString or AzureKeyVaultSecretReference. If servicePrincipalCredentialType is 'ServicePrincipalCert', + * servicePrincipalCredential can only be AzureKeyVaultSecretReference. + * + * @return the servicePrincipalCredential value. + */ + public SecretBase getServicePrincipalCredential() { + return this.servicePrincipalCredential; + } + + /** + * Set the servicePrincipalCredential property: The credential of the service principal object in Azure Active + * Directory. If servicePrincipalCredentialType is 'ServicePrincipalKey', servicePrincipalCredential can be + * SecureString or AzureKeyVaultSecretReference. If servicePrincipalCredentialType is 'ServicePrincipalCert', + * servicePrincipalCredential can only be AzureKeyVaultSecretReference. + * + * @param servicePrincipalCredential the servicePrincipalCredential value to set. + * @return the AzureSqlDatabaseLinkedServiceTypeProperties object itself. + */ + public AzureSqlDatabaseLinkedServiceTypeProperties + setServicePrincipalCredential(SecretBase servicePrincipalCredential) { + this.servicePrincipalCredential = servicePrincipalCredential; + return this; + } + + /** + * Get the tenant property: The name or ID of the tenant to which the service principal belongs. Type: string (or + * Expression with resultType string). + * + * @return the tenant value. + */ + public Object getTenant() { + return this.tenant; + } + + /** + * Set the tenant property: The name or ID of the tenant to which the service principal belongs. Type: string (or + * Expression with resultType string). + * + * @param tenant the tenant value to set. + * @return the AzureSqlDatabaseLinkedServiceTypeProperties object itself. + */ + public AzureSqlDatabaseLinkedServiceTypeProperties setTenant(Object tenant) { + this.tenant = tenant; + return this; + } + + /** + * Get the azureCloudType property: Indicates the azure cloud type of the service principle auth. Allowed values are + * AzurePublic, AzureChina, AzureUsGovernment, AzureGermany. Default value is the data factory regions’ cloud type. + * Type: string (or Expression with resultType string). + * + * @return the azureCloudType value. + */ + public Object getAzureCloudType() { + return this.azureCloudType; + } + + /** + * Set the azureCloudType property: Indicates the azure cloud type of the service principle auth. Allowed values are + * AzurePublic, AzureChina, AzureUsGovernment, AzureGermany. Default value is the data factory regions’ cloud type. + * Type: string (or Expression with resultType string). + * + * @param azureCloudType the azureCloudType value to set. + * @return the AzureSqlDatabaseLinkedServiceTypeProperties object itself. + */ + public AzureSqlDatabaseLinkedServiceTypeProperties setAzureCloudType(Object azureCloudType) { + this.azureCloudType = azureCloudType; + return this; + } + + /** + * Get the alwaysEncryptedSettings property: Sql always encrypted properties. + * + * @return the alwaysEncryptedSettings value. + */ + public SqlAlwaysEncryptedProperties getAlwaysEncryptedSettings() { + return this.alwaysEncryptedSettings; + } + + /** + * Set the alwaysEncryptedSettings property: Sql always encrypted properties. + * + * @param alwaysEncryptedSettings the alwaysEncryptedSettings value to set. + * @return the AzureSqlDatabaseLinkedServiceTypeProperties object itself. + */ + public AzureSqlDatabaseLinkedServiceTypeProperties + setAlwaysEncryptedSettings(SqlAlwaysEncryptedProperties alwaysEncryptedSettings) { + this.alwaysEncryptedSettings = alwaysEncryptedSettings; + return this; + } + + /** + * Get the encryptedCredential property: The encrypted credential used for authentication. Credentials are encrypted + * using the integration runtime credential manager. Type: string (or Expression with resultType string). + * + * @return the encryptedCredential value. + */ + public Object getEncryptedCredential() { + return this.encryptedCredential; + } + + /** + * Set the encryptedCredential property: The encrypted credential used for authentication. Credentials are encrypted + * using the integration runtime credential manager. Type: string (or Expression with resultType string). + * + * @param encryptedCredential the encryptedCredential value to set. + * @return the AzureSqlDatabaseLinkedServiceTypeProperties object itself. + */ + public AzureSqlDatabaseLinkedServiceTypeProperties setEncryptedCredential(Object encryptedCredential) { + this.encryptedCredential = encryptedCredential; + return this; + } + + /** + * Get the credential property: The credential reference containing authentication information. + * + * @return the credential value. + */ + public CredentialReference getCredential() { + return this.credential; + } + + /** + * Set the credential property: The credential reference containing authentication information. + * + * @param credential the credential value to set. + * @return the AzureSqlDatabaseLinkedServiceTypeProperties object itself. + */ + public AzureSqlDatabaseLinkedServiceTypeProperties setCredential(CredentialReference credential) { + this.credential = credential; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDatabaseLinkedServiceTypeProperties setServer(Object server) { + super.setServer(server); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDatabaseLinkedServiceTypeProperties setDatabase(Object database) { + super.setDatabase(database); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDatabaseLinkedServiceTypeProperties setEncrypt(Object encrypt) { + super.setEncrypt(encrypt); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDatabaseLinkedServiceTypeProperties setTrustServerCertificate(Object trustServerCertificate) { + super.setTrustServerCertificate(trustServerCertificate); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDatabaseLinkedServiceTypeProperties setHostNameInCertificate(Object hostNameInCertificate) { + super.setHostNameInCertificate(hostNameInCertificate); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDatabaseLinkedServiceTypeProperties setApplicationIntent(Object applicationIntent) { + super.setApplicationIntent(applicationIntent); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDatabaseLinkedServiceTypeProperties setConnectTimeout(Object connectTimeout) { + super.setConnectTimeout(connectTimeout); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDatabaseLinkedServiceTypeProperties setConnectRetryCount(Object connectRetryCount) { + super.setConnectRetryCount(connectRetryCount); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDatabaseLinkedServiceTypeProperties setConnectRetryInterval(Object connectRetryInterval) { + super.setConnectRetryInterval(connectRetryInterval); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDatabaseLinkedServiceTypeProperties setLoadBalanceTimeout(Object loadBalanceTimeout) { + super.setLoadBalanceTimeout(loadBalanceTimeout); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDatabaseLinkedServiceTypeProperties setCommandTimeout(Object commandTimeout) { + super.setCommandTimeout(commandTimeout); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDatabaseLinkedServiceTypeProperties setIntegratedSecurity(Object integratedSecurity) { + super.setIntegratedSecurity(integratedSecurity); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDatabaseLinkedServiceTypeProperties setFailoverPartner(Object failoverPartner) { + super.setFailoverPartner(failoverPartner); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDatabaseLinkedServiceTypeProperties setMaxPoolSize(Object maxPoolSize) { + super.setMaxPoolSize(maxPoolSize); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDatabaseLinkedServiceTypeProperties setMinPoolSize(Object minPoolSize) { + super.setMinPoolSize(minPoolSize); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDatabaseLinkedServiceTypeProperties setMultipleActiveResultSets(Object multipleActiveResultSets) { + super.setMultipleActiveResultSets(multipleActiveResultSets); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDatabaseLinkedServiceTypeProperties setMultiSubnetFailover(Object multiSubnetFailover) { + super.setMultiSubnetFailover(multiSubnetFailover); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDatabaseLinkedServiceTypeProperties setPacketSize(Object packetSize) { + super.setPacketSize(packetSize); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlDatabaseLinkedServiceTypeProperties setPooling(Object pooling) { + super.setPooling(pooling); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeUntypedField("server", getServer()); + jsonWriter.writeUntypedField("database", getDatabase()); + jsonWriter.writeUntypedField("encrypt", getEncrypt()); + jsonWriter.writeUntypedField("trustServerCertificate", getTrustServerCertificate()); + jsonWriter.writeUntypedField("hostNameInCertificate", getHostNameInCertificate()); + jsonWriter.writeUntypedField("applicationIntent", getApplicationIntent()); + jsonWriter.writeUntypedField("connectTimeout", getConnectTimeout()); + jsonWriter.writeUntypedField("connectRetryCount", getConnectRetryCount()); + jsonWriter.writeUntypedField("connectRetryInterval", getConnectRetryInterval()); + jsonWriter.writeUntypedField("loadBalanceTimeout", getLoadBalanceTimeout()); + jsonWriter.writeUntypedField("commandTimeout", getCommandTimeout()); + jsonWriter.writeUntypedField("integratedSecurity", getIntegratedSecurity()); + jsonWriter.writeUntypedField("failoverPartner", getFailoverPartner()); + jsonWriter.writeUntypedField("maxPoolSize", getMaxPoolSize()); + jsonWriter.writeUntypedField("minPoolSize", getMinPoolSize()); + jsonWriter.writeUntypedField("multipleActiveResultSets", getMultipleActiveResultSets()); + jsonWriter.writeUntypedField("multiSubnetFailover", getMultiSubnetFailover()); + jsonWriter.writeUntypedField("packetSize", getPacketSize()); + jsonWriter.writeUntypedField("pooling", getPooling()); + jsonWriter.writeUntypedField("connectionString", this.connectionString); + jsonWriter.writeStringField("authenticationType", + this.authenticationType == null ? null : this.authenticationType.toString()); + jsonWriter.writeUntypedField("userName", this.userName); + jsonWriter.writeJsonField("password", this.password); + jsonWriter.writeUntypedField("servicePrincipalId", this.servicePrincipalId); + jsonWriter.writeJsonField("servicePrincipalKey", this.servicePrincipalKey); + jsonWriter.writeUntypedField("servicePrincipalCredentialType", this.servicePrincipalCredentialType); + jsonWriter.writeJsonField("servicePrincipalCredential", this.servicePrincipalCredential); + jsonWriter.writeUntypedField("tenant", this.tenant); + jsonWriter.writeUntypedField("azureCloudType", this.azureCloudType); + jsonWriter.writeJsonField("alwaysEncryptedSettings", this.alwaysEncryptedSettings); + jsonWriter.writeUntypedField("encryptedCredential", this.encryptedCredential); + jsonWriter.writeJsonField("credential", this.credential); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureSqlDatabaseLinkedServiceTypeProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureSqlDatabaseLinkedServiceTypeProperties 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 AzureSqlDatabaseLinkedServiceTypeProperties. + */ + public static AzureSqlDatabaseLinkedServiceTypeProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AzureSqlDatabaseLinkedServiceTypeProperties deserializedAzureSqlDatabaseLinkedServiceTypeProperties + = new AzureSqlDatabaseLinkedServiceTypeProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("server".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties.setServer(reader.readUntyped()); + } else if ("database".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties.setDatabase(reader.readUntyped()); + } else if ("encrypt".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties.setEncrypt(reader.readUntyped()); + } else if ("trustServerCertificate".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties + .setTrustServerCertificate(reader.readUntyped()); + } else if ("hostNameInCertificate".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties + .setHostNameInCertificate(reader.readUntyped()); + } else if ("applicationIntent".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties.setApplicationIntent(reader.readUntyped()); + } else if ("connectTimeout".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties.setConnectTimeout(reader.readUntyped()); + } else if ("connectRetryCount".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties.setConnectRetryCount(reader.readUntyped()); + } else if ("connectRetryInterval".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties + .setConnectRetryInterval(reader.readUntyped()); + } else if ("loadBalanceTimeout".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties.setLoadBalanceTimeout(reader.readUntyped()); + } else if ("commandTimeout".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties.setCommandTimeout(reader.readUntyped()); + } else if ("integratedSecurity".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties.setIntegratedSecurity(reader.readUntyped()); + } else if ("failoverPartner".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties.setFailoverPartner(reader.readUntyped()); + } else if ("maxPoolSize".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties.setMaxPoolSize(reader.readUntyped()); + } else if ("minPoolSize".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties.setMinPoolSize(reader.readUntyped()); + } else if ("multipleActiveResultSets".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties + .setMultipleActiveResultSets(reader.readUntyped()); + } else if ("multiSubnetFailover".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties + .setMultiSubnetFailover(reader.readUntyped()); + } else if ("packetSize".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties.setPacketSize(reader.readUntyped()); + } else if ("pooling".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties.setPooling(reader.readUntyped()); + } else if ("connectionString".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties.connectionString = reader.readUntyped(); + } else if ("authenticationType".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties.authenticationType + = AzureSqlDatabaseAuthenticationType.fromString(reader.getString()); + } else if ("userName".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties.userName = reader.readUntyped(); + } else if ("password".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties.password + = AzureKeyVaultSecretReference.fromJson(reader); + } else if ("servicePrincipalId".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties.servicePrincipalId = reader.readUntyped(); + } else if ("servicePrincipalKey".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties.servicePrincipalKey + = SecretBase.fromJson(reader); + } else if ("servicePrincipalCredentialType".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties.servicePrincipalCredentialType + = reader.readUntyped(); + } else if ("servicePrincipalCredential".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties.servicePrincipalCredential + = SecretBase.fromJson(reader); + } else if ("tenant".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties.tenant = reader.readUntyped(); + } else if ("azureCloudType".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties.azureCloudType = reader.readUntyped(); + } else if ("alwaysEncryptedSettings".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties.alwaysEncryptedSettings + = SqlAlwaysEncryptedProperties.fromJson(reader); + } else if ("encryptedCredential".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties.encryptedCredential = reader.readUntyped(); + } else if ("credential".equals(fieldName)) { + deserializedAzureSqlDatabaseLinkedServiceTypeProperties.credential + = CredentialReference.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedAzureSqlDatabaseLinkedServiceTypeProperties; + }); + } +} diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlMIAuthenticationType.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlMIAuthenticationType.java new file mode 100644 index 000000000000..12d316a5a5f9 --- /dev/null +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlMIAuthenticationType.java @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.analytics.synapse.artifacts.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The type used for authentication. Type: string. + */ +public final class AzureSqlMIAuthenticationType extends ExpandableStringEnum { + /** + * Static value SQL for AzureSqlMIAuthenticationType. + */ + public static final AzureSqlMIAuthenticationType SQL = fromString("SQL"); + + /** + * Static value ServicePrincipal for AzureSqlMIAuthenticationType. + */ + public static final AzureSqlMIAuthenticationType SERVICE_PRINCIPAL = fromString("ServicePrincipal"); + + /** + * Static value SystemAssignedManagedIdentity for AzureSqlMIAuthenticationType. + */ + public static final AzureSqlMIAuthenticationType SYSTEM_ASSIGNED_MANAGED_IDENTITY + = fromString("SystemAssignedManagedIdentity"); + + /** + * Static value UserAssignedManagedIdentity for AzureSqlMIAuthenticationType. + */ + public static final AzureSqlMIAuthenticationType USER_ASSIGNED_MANAGED_IDENTITY + = fromString("UserAssignedManagedIdentity"); + + /** + * Creates a new instance of AzureSqlMIAuthenticationType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public AzureSqlMIAuthenticationType() { + } + + /** + * Creates or finds a AzureSqlMIAuthenticationType from its string representation. + * + * @param name a name to look for. + * @return the corresponding AzureSqlMIAuthenticationType. + */ + public static AzureSqlMIAuthenticationType fromString(String name) { + return fromString(name, AzureSqlMIAuthenticationType.class); + } + + /** + * Gets known AzureSqlMIAuthenticationType values. + * + * @return known AzureSqlMIAuthenticationType values. + */ + public static Collection values() { + return values(AzureSqlMIAuthenticationType.class); + } +} diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlMILinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlMILinkedService.java index 06c8519a579b..834518c8eab6 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlMILinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlMILinkedService.java @@ -23,11 +23,141 @@ public class AzureSqlMILinkedService extends LinkedService { */ private String type = "AzureSqlMI"; + /* + * The name or network address of the instance of SQL Server to which to connect, used by recommended version. Type: + * string (or Expression with resultType string). + */ + private Object server; + + /* + * The name of the database, used by recommended version. Type: string (or Expression with resultType string). + */ + private Object database; + + /* + * Indicate whether TLS encryption is required for all data sent between the client and server, used by recommended + * version. Possible values are true/yes/mandatory, false/no/optional and strict. Type: string (or Expression with + * resultType string). + */ + private Object encrypt; + + /* + * Indicate whether the channel will be encrypted while bypassing walking the certificate chain to validate trust, + * used by recommended version. Type: Boolean (or Expression with resultType boolean). + */ + private Object trustServerCertificate; + + /* + * The host name to use when validating the server certificate for the connection. When not specified, the server + * name from the Data Source is used for certificate validation, used by recommended version. Type: string (or + * Expression with resultType string). + */ + private Object hostNameInCertificate; + + /* + * The application workload type when connecting to a server, used by recommended version. Possible values are + * ReadOnly and ReadWrite. Type: string (or Expression with resultType string). + */ + private Object applicationIntent; + + /* + * The length of time (in seconds) to wait for a connection to the server before terminating the attempt and + * generating an error, used by recommended version. Type: integer (or Expression with resultType integer). + */ + private Object connectTimeout; + + /* + * The number of re-connections attempted after identifying that there was an idle connection failure, used by + * recommended version. This must be an integer between 0 and 255. Type: integer (or Expression with resultType + * integer). + */ + private Object connectRetryCount; + + /* + * The amount of time (in seconds) between each re-connection attempt after identifying that there was an idle + * connection failure, used by recommended version. This must be an integer between 1 and 60. Type: integer (or + * Expression with resultType integer). + */ + private Object connectRetryInterval; + + /* + * The minimum time, in seconds, for the connection to live in the connection pool before being destroyed, used by + * recommended version. Type: integer (or Expression with resultType integer). + */ + private Object loadBalanceTimeout; + + /* + * The default wait time (in seconds) before terminating the attempt to execute a command and generating an error, + * used by recommended version. Type: integer (or Expression with resultType integer). + */ + private Object commandTimeout; + + /* + * Indicate whether User ID and Password are specified in the connection (when false) or whether the current Windows + * account credentials are used for authentication (when true), used by recommended version. Type: Boolean (or + * Expression with resultType boolean). + */ + private Object integratedSecurity; + + /* + * The name or address of the partner server to connect to if the primary server is down, used by recommended + * version. Type: string (or Expression with resultType string). + */ + private Object failoverPartner; + + /* + * The maximum number of connections allowed in the connection pool for this specific connection string, used by + * recommended version. Type: integer (or Expression with resultType integer). + */ + private Object maxPoolSize; + + /* + * The minimum number of connections allowed in the connection pool for this specific connection string, used by + * recommended version. Type: integer (or Expression with resultType integer). + */ + private Object minPoolSize; + + /* + * When true, an application can maintain multiple active result sets (MARS). When false, an application must + * process or cancel all result sets from one batch before it can execute any other batch on that connection. Type: + * Boolean (or Expression with resultType boolean). + */ + private Object multipleActiveResultSets; + + /* + * If your application is connecting to an AlwaysOn availability group (AG) on different subnets, setting + * MultiSubnetFailover=true provides faster detection of and connection to the (currently) active server, used by + * recommended version. Type: Boolean (or Expression with resultType boolean). + */ + private Object multiSubnetFailover; + + /* + * The size in bytes of the network packets used to communicate with an instance of server, used by recommended + * version. Type: integer (or Expression with resultType integer). + */ + private Object packetSize; + + /* + * Indicate whether the connection will be pooled or explicitly opened every time that the connection is requested, + * used by recommended version. Type: Boolean (or Expression with resultType boolean). + */ + private Object pooling; + /* * The connection string. Type: string, SecureString or AzureKeyVaultSecretReference. */ private Object connectionString; + /* + * The type used for authentication. Type: string. + */ + private AzureSqlMIAuthenticationType authenticationType; + + /* + * The user name to be used when connecting to server. Type: string (or Expression with resultType string). + */ + private Object userName; + /* * The Azure key vault secret reference of password in connection string. */ @@ -44,6 +174,20 @@ public class AzureSqlMILinkedService extends LinkedService { */ private SecretBase servicePrincipalKey; + /* + * The service principal credential type to use in Server-To-Server authentication. 'ServicePrincipalKey' for + * key/secret, 'ServicePrincipalCert' for certificate. Type: string (or Expression with resultType string). + */ + private Object servicePrincipalCredentialType; + + /* + * The credential of the service principal object in Azure Active Directory. If servicePrincipalCredentialType is + * 'ServicePrincipalKey', servicePrincipalCredential can be SecureString or AzureKeyVaultSecretReference. If + * servicePrincipalCredentialType is 'ServicePrincipalCert', servicePrincipalCredential can only be + * AzureKeyVaultSecretReference. + */ + private SecretBase servicePrincipalCredential; + /* * The name or ID of the tenant to which the service principal belongs. Type: string (or Expression with resultType * string). @@ -89,6 +233,446 @@ public String getType() { return this.type; } + /** + * Get the server property: The name or network address of the instance of SQL Server to which to connect, used by + * recommended version. Type: string (or Expression with resultType string). + * + * @return the server value. + */ + public Object getServer() { + return this.server; + } + + /** + * Set the server property: The name or network address of the instance of SQL Server to which to connect, used by + * recommended version. Type: string (or Expression with resultType string). + * + * @param server the server value to set. + * @return the AzureSqlMILinkedService object itself. + */ + public AzureSqlMILinkedService setServer(Object server) { + this.server = server; + return this; + } + + /** + * Get the database property: The name of the database, used by recommended version. Type: string (or Expression + * with resultType string). + * + * @return the database value. + */ + public Object getDatabase() { + return this.database; + } + + /** + * Set the database property: The name of the database, used by recommended version. Type: string (or Expression + * with resultType string). + * + * @param database the database value to set. + * @return the AzureSqlMILinkedService object itself. + */ + public AzureSqlMILinkedService setDatabase(Object database) { + this.database = database; + return this; + } + + /** + * Get the encrypt property: Indicate whether TLS encryption is required for all data sent between the client and + * server, used by recommended version. Possible values are true/yes/mandatory, false/no/optional and strict. Type: + * string (or Expression with resultType string). + * + * @return the encrypt value. + */ + public Object getEncrypt() { + return this.encrypt; + } + + /** + * Set the encrypt property: Indicate whether TLS encryption is required for all data sent between the client and + * server, used by recommended version. Possible values are true/yes/mandatory, false/no/optional and strict. Type: + * string (or Expression with resultType string). + * + * @param encrypt the encrypt value to set. + * @return the AzureSqlMILinkedService object itself. + */ + public AzureSqlMILinkedService setEncrypt(Object encrypt) { + this.encrypt = encrypt; + return this; + } + + /** + * Get the trustServerCertificate property: Indicate whether the channel will be encrypted while bypassing walking + * the certificate chain to validate trust, used by recommended version. Type: Boolean (or Expression with + * resultType boolean). + * + * @return the trustServerCertificate value. + */ + public Object getTrustServerCertificate() { + return this.trustServerCertificate; + } + + /** + * Set the trustServerCertificate property: Indicate whether the channel will be encrypted while bypassing walking + * the certificate chain to validate trust, used by recommended version. Type: Boolean (or Expression with + * resultType boolean). + * + * @param trustServerCertificate the trustServerCertificate value to set. + * @return the AzureSqlMILinkedService object itself. + */ + public AzureSqlMILinkedService setTrustServerCertificate(Object trustServerCertificate) { + this.trustServerCertificate = trustServerCertificate; + return this; + } + + /** + * Get the hostNameInCertificate property: The host name to use when validating the server certificate for the + * connection. When not specified, the server name from the Data Source is used for certificate validation, used by + * recommended version. Type: string (or Expression with resultType string). + * + * @return the hostNameInCertificate value. + */ + public Object getHostNameInCertificate() { + return this.hostNameInCertificate; + } + + /** + * Set the hostNameInCertificate property: The host name to use when validating the server certificate for the + * connection. When not specified, the server name from the Data Source is used for certificate validation, used by + * recommended version. Type: string (or Expression with resultType string). + * + * @param hostNameInCertificate the hostNameInCertificate value to set. + * @return the AzureSqlMILinkedService object itself. + */ + public AzureSqlMILinkedService setHostNameInCertificate(Object hostNameInCertificate) { + this.hostNameInCertificate = hostNameInCertificate; + return this; + } + + /** + * Get the applicationIntent property: The application workload type when connecting to a server, used by + * recommended version. Possible values are ReadOnly and ReadWrite. Type: string (or Expression with resultType + * string). + * + * @return the applicationIntent value. + */ + public Object getApplicationIntent() { + return this.applicationIntent; + } + + /** + * Set the applicationIntent property: The application workload type when connecting to a server, used by + * recommended version. Possible values are ReadOnly and ReadWrite. Type: string (or Expression with resultType + * string). + * + * @param applicationIntent the applicationIntent value to set. + * @return the AzureSqlMILinkedService object itself. + */ + public AzureSqlMILinkedService setApplicationIntent(Object applicationIntent) { + this.applicationIntent = applicationIntent; + return this; + } + + /** + * Get the connectTimeout property: The length of time (in seconds) to wait for a connection to the server before + * terminating the attempt and generating an error, used by recommended version. Type: integer (or Expression with + * resultType integer). + * + * @return the connectTimeout value. + */ + public Object getConnectTimeout() { + return this.connectTimeout; + } + + /** + * Set the connectTimeout property: The length of time (in seconds) to wait for a connection to the server before + * terminating the attempt and generating an error, used by recommended version. Type: integer (or Expression with + * resultType integer). + * + * @param connectTimeout the connectTimeout value to set. + * @return the AzureSqlMILinkedService object itself. + */ + public AzureSqlMILinkedService setConnectTimeout(Object connectTimeout) { + this.connectTimeout = connectTimeout; + return this; + } + + /** + * Get the connectRetryCount property: The number of re-connections attempted after identifying that there was an + * idle connection failure, used by recommended version. This must be an integer between 0 and 255. Type: integer + * (or Expression with resultType integer). + * + * @return the connectRetryCount value. + */ + public Object getConnectRetryCount() { + return this.connectRetryCount; + } + + /** + * Set the connectRetryCount property: The number of re-connections attempted after identifying that there was an + * idle connection failure, used by recommended version. This must be an integer between 0 and 255. Type: integer + * (or Expression with resultType integer). + * + * @param connectRetryCount the connectRetryCount value to set. + * @return the AzureSqlMILinkedService object itself. + */ + public AzureSqlMILinkedService setConnectRetryCount(Object connectRetryCount) { + this.connectRetryCount = connectRetryCount; + return this; + } + + /** + * Get the connectRetryInterval property: The amount of time (in seconds) between each re-connection attempt after + * identifying that there was an idle connection failure, used by recommended version. This must be an integer + * between 1 and 60. Type: integer (or Expression with resultType integer). + * + * @return the connectRetryInterval value. + */ + public Object getConnectRetryInterval() { + return this.connectRetryInterval; + } + + /** + * Set the connectRetryInterval property: The amount of time (in seconds) between each re-connection attempt after + * identifying that there was an idle connection failure, used by recommended version. This must be an integer + * between 1 and 60. Type: integer (or Expression with resultType integer). + * + * @param connectRetryInterval the connectRetryInterval value to set. + * @return the AzureSqlMILinkedService object itself. + */ + public AzureSqlMILinkedService setConnectRetryInterval(Object connectRetryInterval) { + this.connectRetryInterval = connectRetryInterval; + return this; + } + + /** + * Get the loadBalanceTimeout property: The minimum time, in seconds, for the connection to live in the connection + * pool before being destroyed, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @return the loadBalanceTimeout value. + */ + public Object getLoadBalanceTimeout() { + return this.loadBalanceTimeout; + } + + /** + * Set the loadBalanceTimeout property: The minimum time, in seconds, for the connection to live in the connection + * pool before being destroyed, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @param loadBalanceTimeout the loadBalanceTimeout value to set. + * @return the AzureSqlMILinkedService object itself. + */ + public AzureSqlMILinkedService setLoadBalanceTimeout(Object loadBalanceTimeout) { + this.loadBalanceTimeout = loadBalanceTimeout; + return this; + } + + /** + * Get the commandTimeout property: The default wait time (in seconds) before terminating the attempt to execute a + * command and generating an error, used by recommended version. Type: integer (or Expression with resultType + * integer). + * + * @return the commandTimeout value. + */ + public Object getCommandTimeout() { + return this.commandTimeout; + } + + /** + * Set the commandTimeout property: The default wait time (in seconds) before terminating the attempt to execute a + * command and generating an error, used by recommended version. Type: integer (or Expression with resultType + * integer). + * + * @param commandTimeout the commandTimeout value to set. + * @return the AzureSqlMILinkedService object itself. + */ + public AzureSqlMILinkedService setCommandTimeout(Object commandTimeout) { + this.commandTimeout = commandTimeout; + return this; + } + + /** + * Get the integratedSecurity property: Indicate whether User ID and Password are specified in the connection (when + * false) or whether the current Windows account credentials are used for authentication (when true), used by + * recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @return the integratedSecurity value. + */ + public Object getIntegratedSecurity() { + return this.integratedSecurity; + } + + /** + * Set the integratedSecurity property: Indicate whether User ID and Password are specified in the connection (when + * false) or whether the current Windows account credentials are used for authentication (when true), used by + * recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @param integratedSecurity the integratedSecurity value to set. + * @return the AzureSqlMILinkedService object itself. + */ + public AzureSqlMILinkedService setIntegratedSecurity(Object integratedSecurity) { + this.integratedSecurity = integratedSecurity; + return this; + } + + /** + * Get the failoverPartner property: The name or address of the partner server to connect to if the primary server + * is down, used by recommended version. Type: string (or Expression with resultType string). + * + * @return the failoverPartner value. + */ + public Object getFailoverPartner() { + return this.failoverPartner; + } + + /** + * Set the failoverPartner property: The name or address of the partner server to connect to if the primary server + * is down, used by recommended version. Type: string (or Expression with resultType string). + * + * @param failoverPartner the failoverPartner value to set. + * @return the AzureSqlMILinkedService object itself. + */ + public AzureSqlMILinkedService setFailoverPartner(Object failoverPartner) { + this.failoverPartner = failoverPartner; + return this; + } + + /** + * Get the maxPoolSize property: The maximum number of connections allowed in the connection pool for this specific + * connection string, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @return the maxPoolSize value. + */ + public Object getMaxPoolSize() { + return this.maxPoolSize; + } + + /** + * Set the maxPoolSize property: The maximum number of connections allowed in the connection pool for this specific + * connection string, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @param maxPoolSize the maxPoolSize value to set. + * @return the AzureSqlMILinkedService object itself. + */ + public AzureSqlMILinkedService setMaxPoolSize(Object maxPoolSize) { + this.maxPoolSize = maxPoolSize; + return this; + } + + /** + * Get the minPoolSize property: The minimum number of connections allowed in the connection pool for this specific + * connection string, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @return the minPoolSize value. + */ + public Object getMinPoolSize() { + return this.minPoolSize; + } + + /** + * Set the minPoolSize property: The minimum number of connections allowed in the connection pool for this specific + * connection string, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @param minPoolSize the minPoolSize value to set. + * @return the AzureSqlMILinkedService object itself. + */ + public AzureSqlMILinkedService setMinPoolSize(Object minPoolSize) { + this.minPoolSize = minPoolSize; + return this; + } + + /** + * Get the multipleActiveResultSets property: When true, an application can maintain multiple active result sets + * (MARS). When false, an application must process or cancel all result sets from one batch before it can execute + * any other batch on that connection. Type: Boolean (or Expression with resultType boolean). + * + * @return the multipleActiveResultSets value. + */ + public Object getMultipleActiveResultSets() { + return this.multipleActiveResultSets; + } + + /** + * Set the multipleActiveResultSets property: When true, an application can maintain multiple active result sets + * (MARS). When false, an application must process or cancel all result sets from one batch before it can execute + * any other batch on that connection. Type: Boolean (or Expression with resultType boolean). + * + * @param multipleActiveResultSets the multipleActiveResultSets value to set. + * @return the AzureSqlMILinkedService object itself. + */ + public AzureSqlMILinkedService setMultipleActiveResultSets(Object multipleActiveResultSets) { + this.multipleActiveResultSets = multipleActiveResultSets; + return this; + } + + /** + * Get the multiSubnetFailover property: If your application is connecting to an AlwaysOn availability group (AG) on + * different subnets, setting MultiSubnetFailover=true provides faster detection of and connection to the + * (currently) active server, used by recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @return the multiSubnetFailover value. + */ + public Object getMultiSubnetFailover() { + return this.multiSubnetFailover; + } + + /** + * Set the multiSubnetFailover property: If your application is connecting to an AlwaysOn availability group (AG) on + * different subnets, setting MultiSubnetFailover=true provides faster detection of and connection to the + * (currently) active server, used by recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @param multiSubnetFailover the multiSubnetFailover value to set. + * @return the AzureSqlMILinkedService object itself. + */ + public AzureSqlMILinkedService setMultiSubnetFailover(Object multiSubnetFailover) { + this.multiSubnetFailover = multiSubnetFailover; + return this; + } + + /** + * Get the packetSize property: The size in bytes of the network packets used to communicate with an instance of + * server, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @return the packetSize value. + */ + public Object getPacketSize() { + return this.packetSize; + } + + /** + * Set the packetSize property: The size in bytes of the network packets used to communicate with an instance of + * server, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @param packetSize the packetSize value to set. + * @return the AzureSqlMILinkedService object itself. + */ + public AzureSqlMILinkedService setPacketSize(Object packetSize) { + this.packetSize = packetSize; + return this; + } + + /** + * Get the pooling property: Indicate whether the connection will be pooled or explicitly opened every time that the + * connection is requested, used by recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @return the pooling value. + */ + public Object getPooling() { + return this.pooling; + } + + /** + * Set the pooling property: Indicate whether the connection will be pooled or explicitly opened every time that the + * connection is requested, used by recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @param pooling the pooling value to set. + * @return the AzureSqlMILinkedService object itself. + */ + public AzureSqlMILinkedService setPooling(Object pooling) { + this.pooling = pooling; + return this; + } + /** * Get the connectionString property: The connection string. Type: string, SecureString or * AzureKeyVaultSecretReference. @@ -111,6 +695,48 @@ public AzureSqlMILinkedService setConnectionString(Object connectionString) { return this; } + /** + * Get the authenticationType property: The type used for authentication. Type: string. + * + * @return the authenticationType value. + */ + public AzureSqlMIAuthenticationType getAuthenticationType() { + return this.authenticationType; + } + + /** + * Set the authenticationType property: The type used for authentication. Type: string. + * + * @param authenticationType the authenticationType value to set. + * @return the AzureSqlMILinkedService object itself. + */ + public AzureSqlMILinkedService setAuthenticationType(AzureSqlMIAuthenticationType authenticationType) { + this.authenticationType = authenticationType; + return this; + } + + /** + * Get the userName property: The user name to be used when connecting to server. Type: string (or Expression with + * resultType string). + * + * @return the userName value. + */ + public Object getUserName() { + return this.userName; + } + + /** + * Set the userName property: The user name to be used when connecting to server. Type: string (or Expression with + * resultType string). + * + * @param userName the userName value to set. + * @return the AzureSqlMILinkedService object itself. + */ + public AzureSqlMILinkedService setUserName(Object userName) { + this.userName = userName; + return this; + } + /** * Get the password property: The Azure key vault secret reference of password in connection string. * @@ -175,6 +801,56 @@ public AzureSqlMILinkedService setServicePrincipalKey(SecretBase servicePrincipa return this; } + /** + * Get the servicePrincipalCredentialType property: The service principal credential type to use in Server-To-Server + * authentication. 'ServicePrincipalKey' for key/secret, 'ServicePrincipalCert' for certificate. Type: string (or + * Expression with resultType string). + * + * @return the servicePrincipalCredentialType value. + */ + public Object getServicePrincipalCredentialType() { + return this.servicePrincipalCredentialType; + } + + /** + * Set the servicePrincipalCredentialType property: The service principal credential type to use in Server-To-Server + * authentication. 'ServicePrincipalKey' for key/secret, 'ServicePrincipalCert' for certificate. Type: string (or + * Expression with resultType string). + * + * @param servicePrincipalCredentialType the servicePrincipalCredentialType value to set. + * @return the AzureSqlMILinkedService object itself. + */ + public AzureSqlMILinkedService setServicePrincipalCredentialType(Object servicePrincipalCredentialType) { + this.servicePrincipalCredentialType = servicePrincipalCredentialType; + return this; + } + + /** + * Get the servicePrincipalCredential property: The credential of the service principal object in Azure Active + * Directory. If servicePrincipalCredentialType is 'ServicePrincipalKey', servicePrincipalCredential can be + * SecureString or AzureKeyVaultSecretReference. If servicePrincipalCredentialType is 'ServicePrincipalCert', + * servicePrincipalCredential can only be AzureKeyVaultSecretReference. + * + * @return the servicePrincipalCredential value. + */ + public SecretBase getServicePrincipalCredential() { + return this.servicePrincipalCredential; + } + + /** + * Set the servicePrincipalCredential property: The credential of the service principal object in Azure Active + * Directory. If servicePrincipalCredentialType is 'ServicePrincipalKey', servicePrincipalCredential can be + * SecureString or AzureKeyVaultSecretReference. If servicePrincipalCredentialType is 'ServicePrincipalCert', + * servicePrincipalCredential can only be AzureKeyVaultSecretReference. + * + * @param servicePrincipalCredential the servicePrincipalCredential value to set. + * @return the AzureSqlMILinkedService object itself. + */ + public AzureSqlMILinkedService setServicePrincipalCredential(SecretBase servicePrincipalCredential) { + this.servicePrincipalCredential = servicePrincipalCredential; + return this; + } + /** * Get the tenant property: The name or ID of the tenant to which the service principal belongs. Type: string (or * Expression with resultType string). @@ -283,6 +959,15 @@ public AzureSqlMILinkedService setCredential(CredentialReference credential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public AzureSqlMILinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -325,25 +1010,73 @@ public AzureSqlMILinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); jsonWriter.writeArrayField("annotations", getAnnotations(), (writer, element) -> writer.writeUntyped(element)); jsonWriter.writeStringField("type", this.type); - if (connectionString != null + if (server != null + || database != null + || encrypt != null + || trustServerCertificate != null + || hostNameInCertificate != null + || applicationIntent != null + || connectTimeout != null + || connectRetryCount != null + || connectRetryInterval != null + || loadBalanceTimeout != null + || commandTimeout != null + || integratedSecurity != null + || failoverPartner != null + || maxPoolSize != null + || minPoolSize != null + || multipleActiveResultSets != null + || multiSubnetFailover != null + || packetSize != null + || pooling != null + || connectionString != null + || authenticationType != null + || userName != null || password != null || servicePrincipalId != null || servicePrincipalKey != null + || servicePrincipalCredentialType != null + || servicePrincipalCredential != null || tenant != null || azureCloudType != null || alwaysEncryptedSettings != null || encryptedCredential != null || credential != null) { jsonWriter.writeStartObject("typeProperties"); + jsonWriter.writeUntypedField("server", this.server); + jsonWriter.writeUntypedField("database", this.database); + jsonWriter.writeUntypedField("encrypt", this.encrypt); + jsonWriter.writeUntypedField("trustServerCertificate", this.trustServerCertificate); + jsonWriter.writeUntypedField("hostNameInCertificate", this.hostNameInCertificate); + jsonWriter.writeUntypedField("applicationIntent", this.applicationIntent); + jsonWriter.writeUntypedField("connectTimeout", this.connectTimeout); + jsonWriter.writeUntypedField("connectRetryCount", this.connectRetryCount); + jsonWriter.writeUntypedField("connectRetryInterval", this.connectRetryInterval); + jsonWriter.writeUntypedField("loadBalanceTimeout", this.loadBalanceTimeout); + jsonWriter.writeUntypedField("commandTimeout", this.commandTimeout); + jsonWriter.writeUntypedField("integratedSecurity", this.integratedSecurity); + jsonWriter.writeUntypedField("failoverPartner", this.failoverPartner); + jsonWriter.writeUntypedField("maxPoolSize", this.maxPoolSize); + jsonWriter.writeUntypedField("minPoolSize", this.minPoolSize); + jsonWriter.writeUntypedField("multipleActiveResultSets", this.multipleActiveResultSets); + jsonWriter.writeUntypedField("multiSubnetFailover", this.multiSubnetFailover); + jsonWriter.writeUntypedField("packetSize", this.packetSize); + jsonWriter.writeUntypedField("pooling", this.pooling); jsonWriter.writeUntypedField("connectionString", this.connectionString); + jsonWriter.writeStringField("authenticationType", + this.authenticationType == null ? null : this.authenticationType.toString()); + jsonWriter.writeUntypedField("userName", this.userName); jsonWriter.writeJsonField("password", this.password); jsonWriter.writeUntypedField("servicePrincipalId", this.servicePrincipalId); jsonWriter.writeJsonField("servicePrincipalKey", this.servicePrincipalKey); + jsonWriter.writeUntypedField("servicePrincipalCredentialType", this.servicePrincipalCredentialType); + jsonWriter.writeJsonField("servicePrincipalCredential", this.servicePrincipalCredential); jsonWriter.writeUntypedField("tenant", this.tenant); jsonWriter.writeUntypedField("azureCloudType", this.azureCloudType); jsonWriter.writeJsonField("alwaysEncryptedSettings", this.alwaysEncryptedSettings); @@ -365,7 +1098,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @param jsonReader The JsonReader being read. * @return An instance of AzureSqlMILinkedService 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 AzureSqlMILinkedService. */ public static AzureSqlMILinkedService fromJson(JsonReader jsonReader) throws IOException { @@ -376,7 +1108,9 @@ public static AzureSqlMILinkedService fromJson(JsonReader jsonReader) throws IOE String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAzureSqlMILinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAzureSqlMILinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedAzureSqlMILinkedService.setDescription(reader.getString()); @@ -394,8 +1128,51 @@ public static AzureSqlMILinkedService fromJson(JsonReader jsonReader) throws IOE fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectionString".equals(fieldName)) { + if ("server".equals(fieldName)) { + deserializedAzureSqlMILinkedService.server = reader.readUntyped(); + } else if ("database".equals(fieldName)) { + deserializedAzureSqlMILinkedService.database = reader.readUntyped(); + } else if ("encrypt".equals(fieldName)) { + deserializedAzureSqlMILinkedService.encrypt = reader.readUntyped(); + } else if ("trustServerCertificate".equals(fieldName)) { + deserializedAzureSqlMILinkedService.trustServerCertificate = reader.readUntyped(); + } else if ("hostNameInCertificate".equals(fieldName)) { + deserializedAzureSqlMILinkedService.hostNameInCertificate = reader.readUntyped(); + } else if ("applicationIntent".equals(fieldName)) { + deserializedAzureSqlMILinkedService.applicationIntent = reader.readUntyped(); + } else if ("connectTimeout".equals(fieldName)) { + deserializedAzureSqlMILinkedService.connectTimeout = reader.readUntyped(); + } else if ("connectRetryCount".equals(fieldName)) { + deserializedAzureSqlMILinkedService.connectRetryCount = reader.readUntyped(); + } else if ("connectRetryInterval".equals(fieldName)) { + deserializedAzureSqlMILinkedService.connectRetryInterval = reader.readUntyped(); + } else if ("loadBalanceTimeout".equals(fieldName)) { + deserializedAzureSqlMILinkedService.loadBalanceTimeout = reader.readUntyped(); + } else if ("commandTimeout".equals(fieldName)) { + deserializedAzureSqlMILinkedService.commandTimeout = reader.readUntyped(); + } else if ("integratedSecurity".equals(fieldName)) { + deserializedAzureSqlMILinkedService.integratedSecurity = reader.readUntyped(); + } else if ("failoverPartner".equals(fieldName)) { + deserializedAzureSqlMILinkedService.failoverPartner = reader.readUntyped(); + } else if ("maxPoolSize".equals(fieldName)) { + deserializedAzureSqlMILinkedService.maxPoolSize = reader.readUntyped(); + } else if ("minPoolSize".equals(fieldName)) { + deserializedAzureSqlMILinkedService.minPoolSize = reader.readUntyped(); + } else if ("multipleActiveResultSets".equals(fieldName)) { + deserializedAzureSqlMILinkedService.multipleActiveResultSets = reader.readUntyped(); + } else if ("multiSubnetFailover".equals(fieldName)) { + deserializedAzureSqlMILinkedService.multiSubnetFailover = reader.readUntyped(); + } else if ("packetSize".equals(fieldName)) { + deserializedAzureSqlMILinkedService.packetSize = reader.readUntyped(); + } else if ("pooling".equals(fieldName)) { + deserializedAzureSqlMILinkedService.pooling = reader.readUntyped(); + } else if ("connectionString".equals(fieldName)) { deserializedAzureSqlMILinkedService.connectionString = reader.readUntyped(); + } else if ("authenticationType".equals(fieldName)) { + deserializedAzureSqlMILinkedService.authenticationType + = AzureSqlMIAuthenticationType.fromString(reader.getString()); + } else if ("userName".equals(fieldName)) { + deserializedAzureSqlMILinkedService.userName = reader.readUntyped(); } else if ("password".equals(fieldName)) { deserializedAzureSqlMILinkedService.password = AzureKeyVaultSecretReference.fromJson(reader); @@ -403,6 +1180,11 @@ public static AzureSqlMILinkedService fromJson(JsonReader jsonReader) throws IOE deserializedAzureSqlMILinkedService.servicePrincipalId = reader.readUntyped(); } else if ("servicePrincipalKey".equals(fieldName)) { deserializedAzureSqlMILinkedService.servicePrincipalKey = SecretBase.fromJson(reader); + } else if ("servicePrincipalCredentialType".equals(fieldName)) { + deserializedAzureSqlMILinkedService.servicePrincipalCredentialType = reader.readUntyped(); + } else if ("servicePrincipalCredential".equals(fieldName)) { + deserializedAzureSqlMILinkedService.servicePrincipalCredential + = SecretBase.fromJson(reader); } else if ("tenant".equals(fieldName)) { deserializedAzureSqlMILinkedService.tenant = reader.readUntyped(); } else if ("azureCloudType".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlMILinkedServiceTypeProperties.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlMILinkedServiceTypeProperties.java new file mode 100644 index 000000000000..5551e3612d0c --- /dev/null +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSqlMILinkedServiceTypeProperties.java @@ -0,0 +1,693 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.analytics.synapse.artifacts.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; + +/** + * Azure SQL Managed Instance linked service properties. + */ +@Fluent +public final class AzureSqlMILinkedServiceTypeProperties extends SqlServerBaseLinkedServiceTypeProperties { + /* + * The connection string. Type: string, SecureString or AzureKeyVaultSecretReference. + */ + private Object connectionString; + + /* + * The type used for authentication. Type: string. + */ + private AzureSqlMIAuthenticationType authenticationType; + + /* + * The user name to be used when connecting to server. Type: string (or Expression with resultType string). + */ + private Object userName; + + /* + * The Azure key vault secret reference of password in connection string. + */ + private AzureKeyVaultSecretReference password; + + /* + * The ID of the service principal used to authenticate against Azure SQL Managed Instance. Type: string (or + * Expression with resultType string). + */ + private Object servicePrincipalId; + + /* + * The key of the service principal used to authenticate against Azure SQL Managed Instance. + */ + private SecretBase servicePrincipalKey; + + /* + * The service principal credential type to use in Server-To-Server authentication. 'ServicePrincipalKey' for + * key/secret, 'ServicePrincipalCert' for certificate. Type: string (or Expression with resultType string). + */ + private Object servicePrincipalCredentialType; + + /* + * The credential of the service principal object in Azure Active Directory. If servicePrincipalCredentialType is + * 'ServicePrincipalKey', servicePrincipalCredential can be SecureString or AzureKeyVaultSecretReference. If + * servicePrincipalCredentialType is 'ServicePrincipalCert', servicePrincipalCredential can only be + * AzureKeyVaultSecretReference. + */ + private SecretBase servicePrincipalCredential; + + /* + * The name or ID of the tenant to which the service principal belongs. Type: string (or Expression with resultType + * string). + */ + private Object tenant; + + /* + * Indicates the azure cloud type of the service principle auth. Allowed values are AzurePublic, AzureChina, + * AzureUsGovernment, AzureGermany. Default value is the data factory regions’ cloud type. Type: string (or + * Expression with resultType string). + */ + private Object azureCloudType; + + /* + * Sql always encrypted properties. + */ + private SqlAlwaysEncryptedProperties alwaysEncryptedSettings; + + /* + * The encrypted credential used for authentication. Credentials are encrypted using the integration runtime + * credential manager. Type: string (or Expression with resultType string). + */ + private Object encryptedCredential; + + /* + * The credential reference containing authentication information. + */ + private CredentialReference credential; + + /** + * Creates an instance of AzureSqlMILinkedServiceTypeProperties class. + */ + public AzureSqlMILinkedServiceTypeProperties() { + } + + /** + * Get the connectionString property: The connection string. Type: string, SecureString or + * AzureKeyVaultSecretReference. + * + * @return the connectionString value. + */ + public Object getConnectionString() { + return this.connectionString; + } + + /** + * Set the connectionString property: The connection string. Type: string, SecureString or + * AzureKeyVaultSecretReference. + * + * @param connectionString the connectionString value to set. + * @return the AzureSqlMILinkedServiceTypeProperties object itself. + */ + public AzureSqlMILinkedServiceTypeProperties setConnectionString(Object connectionString) { + this.connectionString = connectionString; + return this; + } + + /** + * Get the authenticationType property: The type used for authentication. Type: string. + * + * @return the authenticationType value. + */ + public AzureSqlMIAuthenticationType getAuthenticationType() { + return this.authenticationType; + } + + /** + * Set the authenticationType property: The type used for authentication. Type: string. + * + * @param authenticationType the authenticationType value to set. + * @return the AzureSqlMILinkedServiceTypeProperties object itself. + */ + public AzureSqlMILinkedServiceTypeProperties + setAuthenticationType(AzureSqlMIAuthenticationType authenticationType) { + this.authenticationType = authenticationType; + return this; + } + + /** + * Get the userName property: The user name to be used when connecting to server. Type: string (or Expression with + * resultType string). + * + * @return the userName value. + */ + public Object getUserName() { + return this.userName; + } + + /** + * Set the userName property: The user name to be used when connecting to server. Type: string (or Expression with + * resultType string). + * + * @param userName the userName value to set. + * @return the AzureSqlMILinkedServiceTypeProperties object itself. + */ + public AzureSqlMILinkedServiceTypeProperties setUserName(Object userName) { + this.userName = userName; + return this; + } + + /** + * Get the password property: The Azure key vault secret reference of password in connection string. + * + * @return the password value. + */ + public AzureKeyVaultSecretReference getPassword() { + return this.password; + } + + /** + * Set the password property: The Azure key vault secret reference of password in connection string. + * + * @param password the password value to set. + * @return the AzureSqlMILinkedServiceTypeProperties object itself. + */ + public AzureSqlMILinkedServiceTypeProperties setPassword(AzureKeyVaultSecretReference password) { + this.password = password; + return this; + } + + /** + * Get the servicePrincipalId property: The ID of the service principal used to authenticate against Azure SQL + * Managed Instance. Type: string (or Expression with resultType string). + * + * @return the servicePrincipalId value. + */ + public Object getServicePrincipalId() { + return this.servicePrincipalId; + } + + /** + * Set the servicePrincipalId property: The ID of the service principal used to authenticate against Azure SQL + * Managed Instance. Type: string (or Expression with resultType string). + * + * @param servicePrincipalId the servicePrincipalId value to set. + * @return the AzureSqlMILinkedServiceTypeProperties object itself. + */ + public AzureSqlMILinkedServiceTypeProperties setServicePrincipalId(Object servicePrincipalId) { + this.servicePrincipalId = servicePrincipalId; + return this; + } + + /** + * Get the servicePrincipalKey property: The key of the service principal used to authenticate against Azure SQL + * Managed Instance. + * + * @return the servicePrincipalKey value. + */ + public SecretBase getServicePrincipalKey() { + return this.servicePrincipalKey; + } + + /** + * Set the servicePrincipalKey property: The key of the service principal used to authenticate against Azure SQL + * Managed Instance. + * + * @param servicePrincipalKey the servicePrincipalKey value to set. + * @return the AzureSqlMILinkedServiceTypeProperties object itself. + */ + public AzureSqlMILinkedServiceTypeProperties setServicePrincipalKey(SecretBase servicePrincipalKey) { + this.servicePrincipalKey = servicePrincipalKey; + return this; + } + + /** + * Get the servicePrincipalCredentialType property: The service principal credential type to use in Server-To-Server + * authentication. 'ServicePrincipalKey' for key/secret, 'ServicePrincipalCert' for certificate. Type: string (or + * Expression with resultType string). + * + * @return the servicePrincipalCredentialType value. + */ + public Object getServicePrincipalCredentialType() { + return this.servicePrincipalCredentialType; + } + + /** + * Set the servicePrincipalCredentialType property: The service principal credential type to use in Server-To-Server + * authentication. 'ServicePrincipalKey' for key/secret, 'ServicePrincipalCert' for certificate. Type: string (or + * Expression with resultType string). + * + * @param servicePrincipalCredentialType the servicePrincipalCredentialType value to set. + * @return the AzureSqlMILinkedServiceTypeProperties object itself. + */ + public AzureSqlMILinkedServiceTypeProperties + setServicePrincipalCredentialType(Object servicePrincipalCredentialType) { + this.servicePrincipalCredentialType = servicePrincipalCredentialType; + return this; + } + + /** + * Get the servicePrincipalCredential property: The credential of the service principal object in Azure Active + * Directory. If servicePrincipalCredentialType is 'ServicePrincipalKey', servicePrincipalCredential can be + * SecureString or AzureKeyVaultSecretReference. If servicePrincipalCredentialType is 'ServicePrincipalCert', + * servicePrincipalCredential can only be AzureKeyVaultSecretReference. + * + * @return the servicePrincipalCredential value. + */ + public SecretBase getServicePrincipalCredential() { + return this.servicePrincipalCredential; + } + + /** + * Set the servicePrincipalCredential property: The credential of the service principal object in Azure Active + * Directory. If servicePrincipalCredentialType is 'ServicePrincipalKey', servicePrincipalCredential can be + * SecureString or AzureKeyVaultSecretReference. If servicePrincipalCredentialType is 'ServicePrincipalCert', + * servicePrincipalCredential can only be AzureKeyVaultSecretReference. + * + * @param servicePrincipalCredential the servicePrincipalCredential value to set. + * @return the AzureSqlMILinkedServiceTypeProperties object itself. + */ + public AzureSqlMILinkedServiceTypeProperties setServicePrincipalCredential(SecretBase servicePrincipalCredential) { + this.servicePrincipalCredential = servicePrincipalCredential; + return this; + } + + /** + * Get the tenant property: The name or ID of the tenant to which the service principal belongs. Type: string (or + * Expression with resultType string). + * + * @return the tenant value. + */ + public Object getTenant() { + return this.tenant; + } + + /** + * Set the tenant property: The name or ID of the tenant to which the service principal belongs. Type: string (or + * Expression with resultType string). + * + * @param tenant the tenant value to set. + * @return the AzureSqlMILinkedServiceTypeProperties object itself. + */ + public AzureSqlMILinkedServiceTypeProperties setTenant(Object tenant) { + this.tenant = tenant; + return this; + } + + /** + * Get the azureCloudType property: Indicates the azure cloud type of the service principle auth. Allowed values are + * AzurePublic, AzureChina, AzureUsGovernment, AzureGermany. Default value is the data factory regions’ cloud type. + * Type: string (or Expression with resultType string). + * + * @return the azureCloudType value. + */ + public Object getAzureCloudType() { + return this.azureCloudType; + } + + /** + * Set the azureCloudType property: Indicates the azure cloud type of the service principle auth. Allowed values are + * AzurePublic, AzureChina, AzureUsGovernment, AzureGermany. Default value is the data factory regions’ cloud type. + * Type: string (or Expression with resultType string). + * + * @param azureCloudType the azureCloudType value to set. + * @return the AzureSqlMILinkedServiceTypeProperties object itself. + */ + public AzureSqlMILinkedServiceTypeProperties setAzureCloudType(Object azureCloudType) { + this.azureCloudType = azureCloudType; + return this; + } + + /** + * Get the alwaysEncryptedSettings property: Sql always encrypted properties. + * + * @return the alwaysEncryptedSettings value. + */ + public SqlAlwaysEncryptedProperties getAlwaysEncryptedSettings() { + return this.alwaysEncryptedSettings; + } + + /** + * Set the alwaysEncryptedSettings property: Sql always encrypted properties. + * + * @param alwaysEncryptedSettings the alwaysEncryptedSettings value to set. + * @return the AzureSqlMILinkedServiceTypeProperties object itself. + */ + public AzureSqlMILinkedServiceTypeProperties + setAlwaysEncryptedSettings(SqlAlwaysEncryptedProperties alwaysEncryptedSettings) { + this.alwaysEncryptedSettings = alwaysEncryptedSettings; + return this; + } + + /** + * Get the encryptedCredential property: The encrypted credential used for authentication. Credentials are encrypted + * using the integration runtime credential manager. Type: string (or Expression with resultType string). + * + * @return the encryptedCredential value. + */ + public Object getEncryptedCredential() { + return this.encryptedCredential; + } + + /** + * Set the encryptedCredential property: The encrypted credential used for authentication. Credentials are encrypted + * using the integration runtime credential manager. Type: string (or Expression with resultType string). + * + * @param encryptedCredential the encryptedCredential value to set. + * @return the AzureSqlMILinkedServiceTypeProperties object itself. + */ + public AzureSqlMILinkedServiceTypeProperties setEncryptedCredential(Object encryptedCredential) { + this.encryptedCredential = encryptedCredential; + return this; + } + + /** + * Get the credential property: The credential reference containing authentication information. + * + * @return the credential value. + */ + public CredentialReference getCredential() { + return this.credential; + } + + /** + * Set the credential property: The credential reference containing authentication information. + * + * @param credential the credential value to set. + * @return the AzureSqlMILinkedServiceTypeProperties object itself. + */ + public AzureSqlMILinkedServiceTypeProperties setCredential(CredentialReference credential) { + this.credential = credential; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlMILinkedServiceTypeProperties setServer(Object server) { + super.setServer(server); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlMILinkedServiceTypeProperties setDatabase(Object database) { + super.setDatabase(database); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlMILinkedServiceTypeProperties setEncrypt(Object encrypt) { + super.setEncrypt(encrypt); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlMILinkedServiceTypeProperties setTrustServerCertificate(Object trustServerCertificate) { + super.setTrustServerCertificate(trustServerCertificate); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlMILinkedServiceTypeProperties setHostNameInCertificate(Object hostNameInCertificate) { + super.setHostNameInCertificate(hostNameInCertificate); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlMILinkedServiceTypeProperties setApplicationIntent(Object applicationIntent) { + super.setApplicationIntent(applicationIntent); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlMILinkedServiceTypeProperties setConnectTimeout(Object connectTimeout) { + super.setConnectTimeout(connectTimeout); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlMILinkedServiceTypeProperties setConnectRetryCount(Object connectRetryCount) { + super.setConnectRetryCount(connectRetryCount); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlMILinkedServiceTypeProperties setConnectRetryInterval(Object connectRetryInterval) { + super.setConnectRetryInterval(connectRetryInterval); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlMILinkedServiceTypeProperties setLoadBalanceTimeout(Object loadBalanceTimeout) { + super.setLoadBalanceTimeout(loadBalanceTimeout); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlMILinkedServiceTypeProperties setCommandTimeout(Object commandTimeout) { + super.setCommandTimeout(commandTimeout); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlMILinkedServiceTypeProperties setIntegratedSecurity(Object integratedSecurity) { + super.setIntegratedSecurity(integratedSecurity); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlMILinkedServiceTypeProperties setFailoverPartner(Object failoverPartner) { + super.setFailoverPartner(failoverPartner); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlMILinkedServiceTypeProperties setMaxPoolSize(Object maxPoolSize) { + super.setMaxPoolSize(maxPoolSize); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlMILinkedServiceTypeProperties setMinPoolSize(Object minPoolSize) { + super.setMinPoolSize(minPoolSize); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlMILinkedServiceTypeProperties setMultipleActiveResultSets(Object multipleActiveResultSets) { + super.setMultipleActiveResultSets(multipleActiveResultSets); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlMILinkedServiceTypeProperties setMultiSubnetFailover(Object multiSubnetFailover) { + super.setMultiSubnetFailover(multiSubnetFailover); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlMILinkedServiceTypeProperties setPacketSize(Object packetSize) { + super.setPacketSize(packetSize); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureSqlMILinkedServiceTypeProperties setPooling(Object pooling) { + super.setPooling(pooling); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeUntypedField("server", getServer()); + jsonWriter.writeUntypedField("database", getDatabase()); + jsonWriter.writeUntypedField("encrypt", getEncrypt()); + jsonWriter.writeUntypedField("trustServerCertificate", getTrustServerCertificate()); + jsonWriter.writeUntypedField("hostNameInCertificate", getHostNameInCertificate()); + jsonWriter.writeUntypedField("applicationIntent", getApplicationIntent()); + jsonWriter.writeUntypedField("connectTimeout", getConnectTimeout()); + jsonWriter.writeUntypedField("connectRetryCount", getConnectRetryCount()); + jsonWriter.writeUntypedField("connectRetryInterval", getConnectRetryInterval()); + jsonWriter.writeUntypedField("loadBalanceTimeout", getLoadBalanceTimeout()); + jsonWriter.writeUntypedField("commandTimeout", getCommandTimeout()); + jsonWriter.writeUntypedField("integratedSecurity", getIntegratedSecurity()); + jsonWriter.writeUntypedField("failoverPartner", getFailoverPartner()); + jsonWriter.writeUntypedField("maxPoolSize", getMaxPoolSize()); + jsonWriter.writeUntypedField("minPoolSize", getMinPoolSize()); + jsonWriter.writeUntypedField("multipleActiveResultSets", getMultipleActiveResultSets()); + jsonWriter.writeUntypedField("multiSubnetFailover", getMultiSubnetFailover()); + jsonWriter.writeUntypedField("packetSize", getPacketSize()); + jsonWriter.writeUntypedField("pooling", getPooling()); + jsonWriter.writeUntypedField("connectionString", this.connectionString); + jsonWriter.writeStringField("authenticationType", + this.authenticationType == null ? null : this.authenticationType.toString()); + jsonWriter.writeUntypedField("userName", this.userName); + jsonWriter.writeJsonField("password", this.password); + jsonWriter.writeUntypedField("servicePrincipalId", this.servicePrincipalId); + jsonWriter.writeJsonField("servicePrincipalKey", this.servicePrincipalKey); + jsonWriter.writeUntypedField("servicePrincipalCredentialType", this.servicePrincipalCredentialType); + jsonWriter.writeJsonField("servicePrincipalCredential", this.servicePrincipalCredential); + jsonWriter.writeUntypedField("tenant", this.tenant); + jsonWriter.writeUntypedField("azureCloudType", this.azureCloudType); + jsonWriter.writeJsonField("alwaysEncryptedSettings", this.alwaysEncryptedSettings); + jsonWriter.writeUntypedField("encryptedCredential", this.encryptedCredential); + jsonWriter.writeJsonField("credential", this.credential); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureSqlMILinkedServiceTypeProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureSqlMILinkedServiceTypeProperties 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 AzureSqlMILinkedServiceTypeProperties. + */ + public static AzureSqlMILinkedServiceTypeProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AzureSqlMILinkedServiceTypeProperties deserializedAzureSqlMILinkedServiceTypeProperties + = new AzureSqlMILinkedServiceTypeProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("server".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.setServer(reader.readUntyped()); + } else if ("database".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.setDatabase(reader.readUntyped()); + } else if ("encrypt".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.setEncrypt(reader.readUntyped()); + } else if ("trustServerCertificate".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.setTrustServerCertificate(reader.readUntyped()); + } else if ("hostNameInCertificate".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.setHostNameInCertificate(reader.readUntyped()); + } else if ("applicationIntent".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.setApplicationIntent(reader.readUntyped()); + } else if ("connectTimeout".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.setConnectTimeout(reader.readUntyped()); + } else if ("connectRetryCount".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.setConnectRetryCount(reader.readUntyped()); + } else if ("connectRetryInterval".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.setConnectRetryInterval(reader.readUntyped()); + } else if ("loadBalanceTimeout".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.setLoadBalanceTimeout(reader.readUntyped()); + } else if ("commandTimeout".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.setCommandTimeout(reader.readUntyped()); + } else if ("integratedSecurity".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.setIntegratedSecurity(reader.readUntyped()); + } else if ("failoverPartner".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.setFailoverPartner(reader.readUntyped()); + } else if ("maxPoolSize".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.setMaxPoolSize(reader.readUntyped()); + } else if ("minPoolSize".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.setMinPoolSize(reader.readUntyped()); + } else if ("multipleActiveResultSets".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.setMultipleActiveResultSets(reader.readUntyped()); + } else if ("multiSubnetFailover".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.setMultiSubnetFailover(reader.readUntyped()); + } else if ("packetSize".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.setPacketSize(reader.readUntyped()); + } else if ("pooling".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.setPooling(reader.readUntyped()); + } else if ("connectionString".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.connectionString = reader.readUntyped(); + } else if ("authenticationType".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.authenticationType + = AzureSqlMIAuthenticationType.fromString(reader.getString()); + } else if ("userName".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.userName = reader.readUntyped(); + } else if ("password".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.password + = AzureKeyVaultSecretReference.fromJson(reader); + } else if ("servicePrincipalId".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.servicePrincipalId = reader.readUntyped(); + } else if ("servicePrincipalKey".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.servicePrincipalKey = SecretBase.fromJson(reader); + } else if ("servicePrincipalCredentialType".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.servicePrincipalCredentialType + = reader.readUntyped(); + } else if ("servicePrincipalCredential".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.servicePrincipalCredential + = SecretBase.fromJson(reader); + } else if ("tenant".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.tenant = reader.readUntyped(); + } else if ("azureCloudType".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.azureCloudType = reader.readUntyped(); + } else if ("alwaysEncryptedSettings".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.alwaysEncryptedSettings + = SqlAlwaysEncryptedProperties.fromJson(reader); + } else if ("encryptedCredential".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.encryptedCredential = reader.readUntyped(); + } else if ("credential".equals(fieldName)) { + deserializedAzureSqlMILinkedServiceTypeProperties.credential = CredentialReference.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedAzureSqlMILinkedServiceTypeProperties; + }); + } +} diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureStorageLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureStorageLinkedService.java index d58b33b48dda..d5bb765c9fb5 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureStorageLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureStorageLinkedService.java @@ -173,6 +173,15 @@ public AzureStorageLinkedService setEncryptedCredential(String encryptedCredenti return this; } + /** + * {@inheritDoc} + */ + @Override + public AzureStorageLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -215,6 +224,7 @@ public AzureStorageLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -257,7 +267,9 @@ public static AzureStorageLinkedService fromJson(JsonReader jsonReader) throws I String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAzureStorageLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAzureStorageLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedAzureStorageLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureStorageLinkedServiceTypeProperties.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureStorageLinkedServiceTypeProperties.java new file mode 100644 index 000000000000..06b93b70def8 --- /dev/null +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureStorageLinkedServiceTypeProperties.java @@ -0,0 +1,210 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.analytics.synapse.artifacts.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; + +/** + * Azure Storage linked service properties. + */ +@Fluent +public class AzureStorageLinkedServiceTypeProperties + implements JsonSerializable { + /* + * The connection string. It is mutually exclusive with sasUri property. Type: string, SecureString or + * AzureKeyVaultSecretReference. + */ + private Object connectionString; + + /* + * The Azure key vault secret reference of accountKey in connection string. + */ + private AzureKeyVaultSecretReference accountKey; + + /* + * SAS URI of the Azure Storage resource. It is mutually exclusive with connectionString property. Type: string, + * SecureString or AzureKeyVaultSecretReference. + */ + private Object sasUri; + + /* + * The Azure key vault secret reference of sasToken in sas uri. + */ + private AzureKeyVaultSecretReference sasToken; + + /* + * The encrypted credential used for authentication. Credentials are encrypted using the integration runtime + * credential manager. Type: string (or Expression with resultType string). + */ + private String encryptedCredential; + + /** + * Creates an instance of AzureStorageLinkedServiceTypeProperties class. + */ + public AzureStorageLinkedServiceTypeProperties() { + } + + /** + * Get the connectionString property: The connection string. It is mutually exclusive with sasUri property. Type: + * string, SecureString or AzureKeyVaultSecretReference. + * + * @return the connectionString value. + */ + public Object getConnectionString() { + return this.connectionString; + } + + /** + * Set the connectionString property: The connection string. It is mutually exclusive with sasUri property. Type: + * string, SecureString or AzureKeyVaultSecretReference. + * + * @param connectionString the connectionString value to set. + * @return the AzureStorageLinkedServiceTypeProperties object itself. + */ + public AzureStorageLinkedServiceTypeProperties setConnectionString(Object connectionString) { + this.connectionString = connectionString; + return this; + } + + /** + * Get the accountKey property: The Azure key vault secret reference of accountKey in connection string. + * + * @return the accountKey value. + */ + public AzureKeyVaultSecretReference getAccountKey() { + return this.accountKey; + } + + /** + * Set the accountKey property: The Azure key vault secret reference of accountKey in connection string. + * + * @param accountKey the accountKey value to set. + * @return the AzureStorageLinkedServiceTypeProperties object itself. + */ + public AzureStorageLinkedServiceTypeProperties setAccountKey(AzureKeyVaultSecretReference accountKey) { + this.accountKey = accountKey; + return this; + } + + /** + * Get the sasUri property: SAS URI of the Azure Storage resource. It is mutually exclusive with connectionString + * property. Type: string, SecureString or AzureKeyVaultSecretReference. + * + * @return the sasUri value. + */ + public Object getSasUri() { + return this.sasUri; + } + + /** + * Set the sasUri property: SAS URI of the Azure Storage resource. It is mutually exclusive with connectionString + * property. Type: string, SecureString or AzureKeyVaultSecretReference. + * + * @param sasUri the sasUri value to set. + * @return the AzureStorageLinkedServiceTypeProperties object itself. + */ + public AzureStorageLinkedServiceTypeProperties setSasUri(Object sasUri) { + this.sasUri = sasUri; + return this; + } + + /** + * Get the sasToken property: The Azure key vault secret reference of sasToken in sas uri. + * + * @return the sasToken value. + */ + public AzureKeyVaultSecretReference getSasToken() { + return this.sasToken; + } + + /** + * Set the sasToken property: The Azure key vault secret reference of sasToken in sas uri. + * + * @param sasToken the sasToken value to set. + * @return the AzureStorageLinkedServiceTypeProperties object itself. + */ + public AzureStorageLinkedServiceTypeProperties setSasToken(AzureKeyVaultSecretReference sasToken) { + this.sasToken = sasToken; + return this; + } + + /** + * Get the encryptedCredential property: The encrypted credential used for authentication. Credentials are encrypted + * using the integration runtime credential manager. Type: string (or Expression with resultType string). + * + * @return the encryptedCredential value. + */ + public String getEncryptedCredential() { + return this.encryptedCredential; + } + + /** + * Set the encryptedCredential property: The encrypted credential used for authentication. Credentials are encrypted + * using the integration runtime credential manager. Type: string (or Expression with resultType string). + * + * @param encryptedCredential the encryptedCredential value to set. + * @return the AzureStorageLinkedServiceTypeProperties object itself. + */ + public AzureStorageLinkedServiceTypeProperties setEncryptedCredential(String encryptedCredential) { + this.encryptedCredential = encryptedCredential; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeUntypedField("connectionString", this.connectionString); + jsonWriter.writeJsonField("accountKey", this.accountKey); + jsonWriter.writeUntypedField("sasUri", this.sasUri); + jsonWriter.writeJsonField("sasToken", this.sasToken); + jsonWriter.writeStringField("encryptedCredential", this.encryptedCredential); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureStorageLinkedServiceTypeProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureStorageLinkedServiceTypeProperties 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 AzureStorageLinkedServiceTypeProperties. + */ + public static AzureStorageLinkedServiceTypeProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AzureStorageLinkedServiceTypeProperties deserializedAzureStorageLinkedServiceTypeProperties + = new AzureStorageLinkedServiceTypeProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("connectionString".equals(fieldName)) { + deserializedAzureStorageLinkedServiceTypeProperties.connectionString = reader.readUntyped(); + } else if ("accountKey".equals(fieldName)) { + deserializedAzureStorageLinkedServiceTypeProperties.accountKey + = AzureKeyVaultSecretReference.fromJson(reader); + } else if ("sasUri".equals(fieldName)) { + deserializedAzureStorageLinkedServiceTypeProperties.sasUri = reader.readUntyped(); + } else if ("sasToken".equals(fieldName)) { + deserializedAzureStorageLinkedServiceTypeProperties.sasToken + = AzureKeyVaultSecretReference.fromJson(reader); + } else if ("encryptedCredential".equals(fieldName)) { + deserializedAzureStorageLinkedServiceTypeProperties.encryptedCredential = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedAzureStorageLinkedServiceTypeProperties; + }); + } +} diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSynapseArtifactsLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSynapseArtifactsLinkedService.java index 0e8ac64a82ec..575a2a705114 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSynapseArtifactsLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureSynapseArtifactsLinkedService.java @@ -126,6 +126,15 @@ public AzureSynapseArtifactsLinkedService setWorkspaceResourceId(Object workspac return this; } + /** + * {@inheritDoc} + */ + @Override + public AzureSynapseArtifactsLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -168,6 +177,7 @@ public AzureSynapseArtifactsLinkedService setAnnotations(List annotation @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -206,7 +216,9 @@ public static AzureSynapseArtifactsLinkedService fromJson(JsonReader jsonReader) String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAzureSynapseArtifactsLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAzureSynapseArtifactsLinkedService .setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureTableStorageLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureTableStorageLinkedService.java index 383268fd6952..22cf4635eec4 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureTableStorageLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureTableStorageLinkedService.java @@ -51,6 +51,17 @@ public class AzureTableStorageLinkedService extends LinkedService { */ private String encryptedCredential; + /* + * Table service endpoint of the Azure Table Storage resource. It is mutually exclusive with connectionString, + * sasUri property. + */ + private Object serviceEndpoint; + + /* + * The credential reference containing authentication information. + */ + private CredentialReference credential; + /** * Creates an instance of AzureTableStorageLinkedService class. */ @@ -173,6 +184,57 @@ public AzureTableStorageLinkedService setEncryptedCredential(String encryptedCre return this; } + /** + * Get the serviceEndpoint property: Table service endpoint of the Azure Table Storage resource. It is mutually + * exclusive with connectionString, sasUri property. + * + * @return the serviceEndpoint value. + */ + public Object getServiceEndpoint() { + return this.serviceEndpoint; + } + + /** + * Set the serviceEndpoint property: Table service endpoint of the Azure Table Storage resource. It is mutually + * exclusive with connectionString, sasUri property. + * + * @param serviceEndpoint the serviceEndpoint value to set. + * @return the AzureTableStorageLinkedService object itself. + */ + public AzureTableStorageLinkedService setServiceEndpoint(Object serviceEndpoint) { + this.serviceEndpoint = serviceEndpoint; + return this; + } + + /** + * Get the credential property: The credential reference containing authentication information. + * + * @return the credential value. + */ + public CredentialReference getCredential() { + return this.credential; + } + + /** + * Set the credential property: The credential reference containing authentication information. + * + * @param credential the credential value to set. + * @return the AzureTableStorageLinkedService object itself. + */ + public AzureTableStorageLinkedService setCredential(CredentialReference credential) { + this.credential = credential; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureTableStorageLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -215,6 +277,7 @@ public AzureTableStorageLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -224,13 +287,17 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { || accountKey != null || sasUri != null || sasToken != null - || encryptedCredential != null) { + || encryptedCredential != null + || serviceEndpoint != null + || credential != null) { jsonWriter.writeStartObject("typeProperties"); jsonWriter.writeUntypedField("connectionString", this.connectionString); jsonWriter.writeJsonField("accountKey", this.accountKey); jsonWriter.writeUntypedField("sasUri", this.sasUri); jsonWriter.writeJsonField("sasToken", this.sasToken); jsonWriter.writeStringField("encryptedCredential", this.encryptedCredential); + jsonWriter.writeUntypedField("serviceEndpoint", this.serviceEndpoint); + jsonWriter.writeJsonField("credential", this.credential); jsonWriter.writeEndObject(); } if (getAdditionalProperties() != null) { @@ -258,7 +325,9 @@ public static AzureTableStorageLinkedService fromJson(JsonReader jsonReader) thr String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedAzureTableStorageLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedAzureTableStorageLinkedService .setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { @@ -289,6 +358,11 @@ public static AzureTableStorageLinkedService fromJson(JsonReader jsonReader) thr = AzureKeyVaultSecretReference.fromJson(reader); } else if ("encryptedCredential".equals(fieldName)) { deserializedAzureTableStorageLinkedService.encryptedCredential = reader.getString(); + } else if ("serviceEndpoint".equals(fieldName)) { + deserializedAzureTableStorageLinkedService.serviceEndpoint = reader.readUntyped(); + } else if ("credential".equals(fieldName)) { + deserializedAzureTableStorageLinkedService.credential + = CredentialReference.fromJson(reader); } else { reader.skipChildren(); } diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureTableStorageLinkedServiceTypeProperties.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureTableStorageLinkedServiceTypeProperties.java new file mode 100644 index 000000000000..f7ca49e69ce2 --- /dev/null +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/AzureTableStorageLinkedServiceTypeProperties.java @@ -0,0 +1,179 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.analytics.synapse.artifacts.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; + +/** + * Azure Table Storage linked service properties. + */ +@Fluent +public final class AzureTableStorageLinkedServiceTypeProperties extends AzureStorageLinkedServiceTypeProperties { + /* + * Table service endpoint of the Azure Table Storage resource. It is mutually exclusive with connectionString, + * sasUri property. + */ + private Object serviceEndpoint; + + /* + * The credential reference containing authentication information. + */ + private CredentialReference credential; + + /** + * Creates an instance of AzureTableStorageLinkedServiceTypeProperties class. + */ + public AzureTableStorageLinkedServiceTypeProperties() { + } + + /** + * Get the serviceEndpoint property: Table service endpoint of the Azure Table Storage resource. It is mutually + * exclusive with connectionString, sasUri property. + * + * @return the serviceEndpoint value. + */ + public Object getServiceEndpoint() { + return this.serviceEndpoint; + } + + /** + * Set the serviceEndpoint property: Table service endpoint of the Azure Table Storage resource. It is mutually + * exclusive with connectionString, sasUri property. + * + * @param serviceEndpoint the serviceEndpoint value to set. + * @return the AzureTableStorageLinkedServiceTypeProperties object itself. + */ + public AzureTableStorageLinkedServiceTypeProperties setServiceEndpoint(Object serviceEndpoint) { + this.serviceEndpoint = serviceEndpoint; + return this; + } + + /** + * Get the credential property: The credential reference containing authentication information. + * + * @return the credential value. + */ + public CredentialReference getCredential() { + return this.credential; + } + + /** + * Set the credential property: The credential reference containing authentication information. + * + * @param credential the credential value to set. + * @return the AzureTableStorageLinkedServiceTypeProperties object itself. + */ + public AzureTableStorageLinkedServiceTypeProperties setCredential(CredentialReference credential) { + this.credential = credential; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureTableStorageLinkedServiceTypeProperties setConnectionString(Object connectionString) { + super.setConnectionString(connectionString); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureTableStorageLinkedServiceTypeProperties setAccountKey(AzureKeyVaultSecretReference accountKey) { + super.setAccountKey(accountKey); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureTableStorageLinkedServiceTypeProperties setSasUri(Object sasUri) { + super.setSasUri(sasUri); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureTableStorageLinkedServiceTypeProperties setSasToken(AzureKeyVaultSecretReference sasToken) { + super.setSasToken(sasToken); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public AzureTableStorageLinkedServiceTypeProperties setEncryptedCredential(String encryptedCredential) { + super.setEncryptedCredential(encryptedCredential); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeUntypedField("connectionString", getConnectionString()); + jsonWriter.writeJsonField("accountKey", getAccountKey()); + jsonWriter.writeUntypedField("sasUri", getSasUri()); + jsonWriter.writeJsonField("sasToken", getSasToken()); + jsonWriter.writeStringField("encryptedCredential", getEncryptedCredential()); + jsonWriter.writeUntypedField("serviceEndpoint", this.serviceEndpoint); + jsonWriter.writeJsonField("credential", this.credential); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureTableStorageLinkedServiceTypeProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureTableStorageLinkedServiceTypeProperties 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 AzureTableStorageLinkedServiceTypeProperties. + */ + public static AzureTableStorageLinkedServiceTypeProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AzureTableStorageLinkedServiceTypeProperties deserializedAzureTableStorageLinkedServiceTypeProperties + = new AzureTableStorageLinkedServiceTypeProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("connectionString".equals(fieldName)) { + deserializedAzureTableStorageLinkedServiceTypeProperties.setConnectionString(reader.readUntyped()); + } else if ("accountKey".equals(fieldName)) { + deserializedAzureTableStorageLinkedServiceTypeProperties + .setAccountKey(AzureKeyVaultSecretReference.fromJson(reader)); + } else if ("sasUri".equals(fieldName)) { + deserializedAzureTableStorageLinkedServiceTypeProperties.setSasUri(reader.readUntyped()); + } else if ("sasToken".equals(fieldName)) { + deserializedAzureTableStorageLinkedServiceTypeProperties + .setSasToken(AzureKeyVaultSecretReference.fromJson(reader)); + } else if ("encryptedCredential".equals(fieldName)) { + deserializedAzureTableStorageLinkedServiceTypeProperties.setEncryptedCredential(reader.getString()); + } else if ("serviceEndpoint".equals(fieldName)) { + deserializedAzureTableStorageLinkedServiceTypeProperties.serviceEndpoint = reader.readUntyped(); + } else if ("credential".equals(fieldName)) { + deserializedAzureTableStorageLinkedServiceTypeProperties.credential + = CredentialReference.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedAzureTableStorageLinkedServiceTypeProperties; + }); + } +} diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/BlobEventsTrigger.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/BlobEventsTrigger.java index d47b22dbf6c3..4a4549ed0d13 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/BlobEventsTrigger.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/BlobEventsTrigger.java @@ -52,11 +52,6 @@ public class BlobEventsTrigger extends MultiplePipelineTrigger { */ private String scope; - /* - * Indicates if trigger is running or not. Updated when Start/Stop APIs are called on the Trigger. - */ - private TriggerRuntimeState runtimeState; - /** * Creates an instance of BlobEventsTrigger class. */ @@ -181,17 +176,6 @@ public BlobEventsTrigger setScope(String scope) { return this; } - /** - * Get the runtimeState property: Indicates if trigger is running or not. Updated when Start/Stop APIs are called on - * the Trigger. - * - * @return the runtimeState value. - */ - @Override - public TriggerRuntimeState getRuntimeState() { - return this.runtimeState; - } - /** * {@inheritDoc} */ @@ -271,7 +255,7 @@ public static BlobEventsTrigger fromJson(JsonReader jsonReader) throws IOExcepti if ("description".equals(fieldName)) { deserializedBlobEventsTrigger.setDescription(reader.getString()); } else if ("runtimeState".equals(fieldName)) { - deserializedBlobEventsTrigger.runtimeState = TriggerRuntimeState.fromString(reader.getString()); + deserializedBlobEventsTrigger.setRuntimeState(TriggerRuntimeState.fromString(reader.getString())); } else if ("annotations".equals(fieldName)) { List annotations = reader.readArray(reader1 -> reader1.readUntyped()); deserializedBlobEventsTrigger.setAnnotations(annotations); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/BlobTrigger.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/BlobTrigger.java index 894d7489b700..683798f7c185 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/BlobTrigger.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/BlobTrigger.java @@ -38,11 +38,6 @@ public class BlobTrigger extends MultiplePipelineTrigger { */ private LinkedServiceReference linkedService; - /* - * Indicates if trigger is running or not. Updated when Start/Stop APIs are called on the Trigger. - */ - private TriggerRuntimeState runtimeState; - /** * Creates an instance of BlobTrigger class. */ @@ -119,17 +114,6 @@ public BlobTrigger setLinkedService(LinkedServiceReference linkedService) { return this; } - /** - * Get the runtimeState property: Indicates if trigger is running or not. Updated when Start/Stop APIs are called on - * the Trigger. - * - * @return the runtimeState value. - */ - @Override - public TriggerRuntimeState getRuntimeState() { - return this.runtimeState; - } - /** * {@inheritDoc} */ @@ -200,7 +184,7 @@ public static BlobTrigger fromJson(JsonReader jsonReader) throws IOException { if ("description".equals(fieldName)) { deserializedBlobTrigger.setDescription(reader.getString()); } else if ("runtimeState".equals(fieldName)) { - deserializedBlobTrigger.runtimeState = TriggerRuntimeState.fromString(reader.getString()); + deserializedBlobTrigger.setRuntimeState(TriggerRuntimeState.fromString(reader.getString())); } else if ("annotations".equals(fieldName)) { List annotations = reader.readArray(reader1 -> reader1.readUntyped()); deserializedBlobTrigger.setAnnotations(annotations); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CassandraLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CassandraLinkedService.java index 584be7e347dc..1687af5198a7 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CassandraLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CassandraLinkedService.java @@ -194,6 +194,15 @@ public CassandraLinkedService setEncryptedCredential(Object encryptedCredential) return this; } + /** + * {@inheritDoc} + */ + @Override + public CassandraLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -236,6 +245,7 @@ public CassandraLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -281,7 +291,9 @@ public static CassandraLinkedService fromJson(JsonReader jsonReader) throws IOEx String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedCassandraLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedCassandraLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedCassandraLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ChainingTrigger.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ChainingTrigger.java index 286a46011a1f..90d3b6681879 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ChainingTrigger.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ChainingTrigger.java @@ -41,11 +41,6 @@ public class ChainingTrigger extends Trigger { */ private String runDimension; - /* - * Indicates if trigger is running or not. Updated when Start/Stop APIs are called on the Trigger. - */ - private TriggerRuntimeState runtimeState; - /** * Creates an instance of ChainingTrigger class. */ @@ -122,17 +117,6 @@ public ChainingTrigger setRunDimension(String runDimension) { return this; } - /** - * Get the runtimeState property: Indicates if trigger is running or not. Updated when Start/Stop APIs are called on - * the Trigger. - * - * @return the runtimeState value. - */ - @Override - public TriggerRuntimeState getRuntimeState() { - return this.runtimeState; - } - /** * {@inheritDoc} */ @@ -195,7 +179,7 @@ public static ChainingTrigger fromJson(JsonReader jsonReader) throws IOException if ("description".equals(fieldName)) { deserializedChainingTrigger.setDescription(reader.getString()); } else if ("runtimeState".equals(fieldName)) { - deserializedChainingTrigger.runtimeState = TriggerRuntimeState.fromString(reader.getString()); + deserializedChainingTrigger.setRuntimeState(TriggerRuntimeState.fromString(reader.getString())); } else if ("annotations".equals(fieldName)) { List annotations = reader.readArray(reader1 -> reader1.readUntyped()); deserializedChainingTrigger.setAnnotations(annotations); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CommonDataServiceForAppsLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CommonDataServiceForAppsLinkedService.java index 5f023fe2d38f..0c378962a904 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CommonDataServiceForAppsLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CommonDataServiceForAppsLinkedService.java @@ -57,11 +57,17 @@ public class CommonDataServiceForAppsLinkedService extends LinkedService { /* * The authentication type to connect to Common Data Service for Apps server. 'Office365' for online scenario, 'Ifd' - * for on-premises with Ifd scenario. 'AADServicePrincipal' for Server-To-Server authentication in online scenario. - * Type: string (or Expression with resultType string). + * for on-premises with Ifd scenario. 'AADServicePrincipal' for Server-To-Server authentication in online scenario, + * 'Active Directory' for Dynamics on-premises with IFD. Type: string (or Expression with resultType string). */ private Object authenticationType; + /* + * The Active Directory domain that will verify user credentials. Type: string (or Expression with resultType + * string). + */ + private Object domain; + /* * User name to access the Common Data Service for Apps instance. Type: string (or Expression with resultType * string). @@ -233,7 +239,8 @@ public CommonDataServiceForAppsLinkedService setOrganizationName(Object organiza /** * Get the authenticationType property: The authentication type to connect to Common Data Service for Apps server. * 'Office365' for online scenario, 'Ifd' for on-premises with Ifd scenario. 'AADServicePrincipal' for - * Server-To-Server authentication in online scenario. Type: string (or Expression with resultType string). + * Server-To-Server authentication in online scenario, 'Active Directory' for Dynamics on-premises with IFD. Type: + * string (or Expression with resultType string). * * @return the authenticationType value. */ @@ -244,7 +251,8 @@ public Object getAuthenticationType() { /** * Set the authenticationType property: The authentication type to connect to Common Data Service for Apps server. * 'Office365' for online scenario, 'Ifd' for on-premises with Ifd scenario. 'AADServicePrincipal' for - * Server-To-Server authentication in online scenario. Type: string (or Expression with resultType string). + * Server-To-Server authentication in online scenario, 'Active Directory' for Dynamics on-premises with IFD. Type: + * string (or Expression with resultType string). * * @param authenticationType the authenticationType value to set. * @return the CommonDataServiceForAppsLinkedService object itself. @@ -254,6 +262,28 @@ public CommonDataServiceForAppsLinkedService setAuthenticationType(Object authen return this; } + /** + * Get the domain property: The Active Directory domain that will verify user credentials. Type: string (or + * Expression with resultType string). + * + * @return the domain value. + */ + public Object getDomain() { + return this.domain; + } + + /** + * Set the domain property: The Active Directory domain that will verify user credentials. Type: string (or + * Expression with resultType string). + * + * @param domain the domain value to set. + * @return the CommonDataServiceForAppsLinkedService object itself. + */ + public CommonDataServiceForAppsLinkedService setDomain(Object domain) { + this.domain = domain; + return this; + } + /** * Get the username property: User name to access the Common Data Service for Apps instance. Type: string (or * Expression with resultType string). @@ -387,6 +417,15 @@ public CommonDataServiceForAppsLinkedService setEncryptedCredential(Object encry return this; } + /** + * {@inheritDoc} + */ + @Override + public CommonDataServiceForAppsLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -429,6 +468,7 @@ public CommonDataServiceForAppsLinkedService setAnnotations(List annotat @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -440,6 +480,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { || serviceUri != null || organizationName != null || authenticationType != null + || domain != null || username != null || password != null || servicePrincipalId != null @@ -453,6 +494,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeUntypedField("serviceUri", this.serviceUri); jsonWriter.writeUntypedField("organizationName", this.organizationName); jsonWriter.writeUntypedField("authenticationType", this.authenticationType); + jsonWriter.writeUntypedField("domain", this.domain); jsonWriter.writeUntypedField("username", this.username); jsonWriter.writeJsonField("password", this.password); jsonWriter.writeUntypedField("servicePrincipalId", this.servicePrincipalId); @@ -487,7 +529,9 @@ public static CommonDataServiceForAppsLinkedService fromJson(JsonReader jsonRead String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedCommonDataServiceForAppsLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedCommonDataServiceForAppsLinkedService .setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { @@ -518,6 +562,8 @@ public static CommonDataServiceForAppsLinkedService fromJson(JsonReader jsonRead deserializedCommonDataServiceForAppsLinkedService.organizationName = reader.readUntyped(); } else if ("authenticationType".equals(fieldName)) { deserializedCommonDataServiceForAppsLinkedService.authenticationType = reader.readUntyped(); + } else if ("domain".equals(fieldName)) { + deserializedCommonDataServiceForAppsLinkedService.domain = reader.readUntyped(); } else if ("username".equals(fieldName)) { deserializedCommonDataServiceForAppsLinkedService.username = reader.readUntyped(); } else if ("password".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ConcurLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ConcurLinkedService.java index 15aaa87aca4a..20cbad3ac309 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ConcurLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ConcurLinkedService.java @@ -252,6 +252,15 @@ public ConcurLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public ConcurLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -294,6 +303,7 @@ public ConcurLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -343,7 +353,9 @@ public static ConcurLinkedService fromJson(JsonReader jsonReader) throws IOExcep String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedConcurLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedConcurLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedConcurLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ContinuationSettingsReference.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ContinuationSettingsReference.java new file mode 100644 index 000000000000..e3bdbc67eda0 --- /dev/null +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ContinuationSettingsReference.java @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.analytics.synapse.artifacts.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; + +/** + * Continuation settings for execute data flow activity. + */ +@Fluent +public final class ContinuationSettingsReference implements JsonSerializable { + /* + * Continuation TTL in minutes. + */ + private Object continuationTtlInMinutes; + + /* + * Idle condition. + */ + private Object idleCondition; + + /* + * Customized checkpoint key. + */ + private Object customizedCheckpointKey; + + /** + * Creates an instance of ContinuationSettingsReference class. + */ + public ContinuationSettingsReference() { + } + + /** + * Get the continuationTtlInMinutes property: Continuation TTL in minutes. + * + * @return the continuationTtlInMinutes value. + */ + public Object getContinuationTtlInMinutes() { + return this.continuationTtlInMinutes; + } + + /** + * Set the continuationTtlInMinutes property: Continuation TTL in minutes. + * + * @param continuationTtlInMinutes the continuationTtlInMinutes value to set. + * @return the ContinuationSettingsReference object itself. + */ + public ContinuationSettingsReference setContinuationTtlInMinutes(Object continuationTtlInMinutes) { + this.continuationTtlInMinutes = continuationTtlInMinutes; + return this; + } + + /** + * Get the idleCondition property: Idle condition. + * + * @return the idleCondition value. + */ + public Object getIdleCondition() { + return this.idleCondition; + } + + /** + * Set the idleCondition property: Idle condition. + * + * @param idleCondition the idleCondition value to set. + * @return the ContinuationSettingsReference object itself. + */ + public ContinuationSettingsReference setIdleCondition(Object idleCondition) { + this.idleCondition = idleCondition; + return this; + } + + /** + * Get the customizedCheckpointKey property: Customized checkpoint key. + * + * @return the customizedCheckpointKey value. + */ + public Object getCustomizedCheckpointKey() { + return this.customizedCheckpointKey; + } + + /** + * Set the customizedCheckpointKey property: Customized checkpoint key. + * + * @param customizedCheckpointKey the customizedCheckpointKey value to set. + * @return the ContinuationSettingsReference object itself. + */ + public ContinuationSettingsReference setCustomizedCheckpointKey(Object customizedCheckpointKey) { + this.customizedCheckpointKey = customizedCheckpointKey; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeUntypedField("continuationTtlInMinutes", this.continuationTtlInMinutes); + jsonWriter.writeUntypedField("idleCondition", this.idleCondition); + jsonWriter.writeUntypedField("customizedCheckpointKey", this.customizedCheckpointKey); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ContinuationSettingsReference from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ContinuationSettingsReference 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 ContinuationSettingsReference. + */ + public static ContinuationSettingsReference fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ContinuationSettingsReference deserializedContinuationSettingsReference + = new ContinuationSettingsReference(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("continuationTtlInMinutes".equals(fieldName)) { + deserializedContinuationSettingsReference.continuationTtlInMinutes = reader.readUntyped(); + } else if ("idleCondition".equals(fieldName)) { + deserializedContinuationSettingsReference.idleCondition = reader.readUntyped(); + } else if ("customizedCheckpointKey".equals(fieldName)) { + deserializedContinuationSettingsReference.customizedCheckpointKey = reader.readUntyped(); + } else { + reader.skipChildren(); + } + } + + return deserializedContinuationSettingsReference; + }); + } +} diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CopySink.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CopySink.java index b3c67c81f5b6..ffb69e0b24e0 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CopySink.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CopySink.java @@ -251,6 +251,8 @@ public static CopySink fromJson(JsonReader jsonReader) throws IOException { return OrcSink.fromJson(readerToUse.reset()); } else if ("RestSink".equals(discriminatorValue)) { return RestSink.fromJson(readerToUse.reset()); + } else if ("TeradataSink".equals(discriminatorValue)) { + return TeradataSink.fromJson(readerToUse.reset()); } else if ("AzurePostgreSqlSink".equals(discriminatorValue)) { return AzurePostgreSqlSink.fromJson(readerToUse.reset()); } else if ("AzureMySqlSink".equals(discriminatorValue)) { @@ -271,6 +273,8 @@ public static CopySink fromJson(JsonReader jsonReader) throws IOException { return ParquetSink.fromJson(readerToUse.reset()); } else if ("BinarySink".equals(discriminatorValue)) { return BinarySink.fromJson(readerToUse.reset()); + } else if ("IcebergSink".equals(discriminatorValue)) { + return IcebergSink.fromJson(readerToUse.reset()); } else if ("BlobSink".equals(discriminatorValue)) { return BlobSink.fromJson(readerToUse.reset()); } else if ("FileSystemSink".equals(discriminatorValue)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CosmosDbLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CosmosDbLinkedService.java index 449901a152ff..518b88c50c28 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CosmosDbLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CosmosDbLinkedService.java @@ -198,6 +198,15 @@ public CosmosDbLinkedService setCredential(CredentialReference credential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public CosmosDbLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -240,6 +249,7 @@ public CosmosDbLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -284,7 +294,9 @@ public static CosmosDbLinkedService fromJson(JsonReader jsonReader) throws IOExc String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedCosmosDbLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedCosmosDbLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedCosmosDbLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CosmosDbMongoDbApiLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CosmosDbMongoDbApiLinkedService.java index 8ad782ef1961..54083fcd0769 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CosmosDbMongoDbApiLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CosmosDbMongoDbApiLinkedService.java @@ -95,6 +95,15 @@ public CosmosDbMongoDbApiLinkedService setDatabase(Object database) { return this; } + /** + * {@inheritDoc} + */ + @Override + public CosmosDbMongoDbApiLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -137,6 +146,7 @@ public CosmosDbMongoDbApiLinkedService setAnnotations(List annotations) @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -174,7 +184,9 @@ public static CosmosDbMongoDbApiLinkedService fromJson(JsonReader jsonReader) th String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedCosmosDbMongoDbApiLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedCosmosDbMongoDbApiLinkedService .setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CouchbaseLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CouchbaseLinkedService.java index 8452daa7cd2d..2d63b2572fd7 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CouchbaseLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CouchbaseLinkedService.java @@ -119,6 +119,15 @@ public CouchbaseLinkedService setEncryptedCredential(Object encryptedCredential) return this; } + /** + * {@inheritDoc} + */ + @Override + public CouchbaseLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -161,6 +170,7 @@ public CouchbaseLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -197,7 +207,9 @@ public static CouchbaseLinkedService fromJson(JsonReader jsonReader) throws IOEx String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedCouchbaseLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedCouchbaseLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedCouchbaseLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CustomDataSourceLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CustomDataSourceLinkedService.java index 41307905666b..04ebd6fcf40e 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CustomDataSourceLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CustomDataSourceLinkedService.java @@ -64,6 +64,15 @@ public CustomDataSourceLinkedService setTypeProperties(Object typeProperties) { return this; } + /** + * {@inheritDoc} + */ + @Override + public CustomDataSourceLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -106,6 +115,7 @@ public CustomDataSourceLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -138,7 +148,9 @@ public static CustomDataSourceLinkedService fromJson(JsonReader jsonReader) thro String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedCustomDataSourceLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedCustomDataSourceLinkedService .setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CustomEventsTrigger.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CustomEventsTrigger.java index 316dbad7fb33..80a1441a88c1 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CustomEventsTrigger.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/CustomEventsTrigger.java @@ -45,11 +45,6 @@ public class CustomEventsTrigger extends MultiplePipelineTrigger { */ private String scope; - /* - * Indicates if trigger is running or not. Updated when Start/Stop APIs are called on the Trigger. - */ - private TriggerRuntimeState runtimeState; - /** * Creates an instance of CustomEventsTrigger class. */ @@ -150,17 +145,6 @@ public CustomEventsTrigger setScope(String scope) { return this; } - /** - * Get the runtimeState property: Indicates if trigger is running or not. Updated when Start/Stop APIs are called on - * the Trigger. - * - * @return the runtimeState value. - */ - @Override - public TriggerRuntimeState getRuntimeState() { - return this.runtimeState; - } - /** * {@inheritDoc} */ @@ -234,7 +218,7 @@ public static CustomEventsTrigger fromJson(JsonReader jsonReader) throws IOExcep if ("description".equals(fieldName)) { deserializedCustomEventsTrigger.setDescription(reader.getString()); } else if ("runtimeState".equals(fieldName)) { - deserializedCustomEventsTrigger.runtimeState = TriggerRuntimeState.fromString(reader.getString()); + deserializedCustomEventsTrigger.setRuntimeState(TriggerRuntimeState.fromString(reader.getString())); } else if ("annotations".equals(fieldName)) { List annotations = reader.readArray(reader1 -> reader1.readUntyped()); deserializedCustomEventsTrigger.setAnnotations(annotations); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/Dataset.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/Dataset.java index 21a536334f84..813fa3a99f0d 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/Dataset.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/Dataset.java @@ -316,6 +316,8 @@ public static Dataset fromJson(JsonReader jsonReader) throws IOException { return OrcDataset.fromJson(readerToUse.reset()); } else if ("Binary".equals(discriminatorValue)) { return BinaryDataset.fromJson(readerToUse.reset()); + } else if ("Iceberg".equals(discriminatorValue)) { + return IcebergDataset.fromJson(readerToUse.reset()); } else if ("AzureBlob".equals(discriminatorValue)) { return AzureBlobDataset.fromJson(readerToUse.reset()); } else if ("AzureTable".equals(discriminatorValue)) { @@ -496,7 +498,7 @@ public static Dataset fromJson(JsonReader jsonReader) throws IOException { return SharePointOnlineListResourceDataset.fromJson(readerToUse.reset()); } else if ("AzureDatabricksDeltaLakeDataset".equals(discriminatorValue)) { return AzureDatabricksDeltaLakeDataset.fromJson(readerToUse.reset()); - } else if ("LakeHouseTable".equals(discriminatorValue)) { + } else if ("LakehouseTable".equals(discriminatorValue)) { return LakeHouseTableDataset.fromJson(readerToUse.reset()); } else if ("SalesforceV2Object".equals(discriminatorValue)) { return SalesforceV2ObjectDataset.fromJson(readerToUse.reset()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/DataworldLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/DataworldLinkedService.java index ffa073b78067..a422e3b34448 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/DataworldLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/DataworldLinkedService.java @@ -92,6 +92,15 @@ public DataworldLinkedService setEncryptedCredential(Object encryptedCredential) return this; } + /** + * {@inheritDoc} + */ + @Override + public DataworldLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -134,6 +143,7 @@ public DataworldLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -170,7 +180,9 @@ public static DataworldLinkedService fromJson(JsonReader jsonReader) throws IOEx String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedDataworldLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedDataworldLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedDataworldLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/Db2LinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/Db2LinkedService.java index addbe37858cb..e36ac4593dce 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/Db2LinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/Db2LinkedService.java @@ -292,6 +292,15 @@ public Db2LinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public Db2LinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -334,6 +343,7 @@ public Db2LinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -386,7 +396,9 @@ public static Db2LinkedService fromJson(JsonReader jsonReader) throws IOExceptio String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedDb2LinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedDb2LinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedDb2LinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/DrillLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/DrillLinkedService.java index 5b43edf67a12..2a1ec79bcffd 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/DrillLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/DrillLinkedService.java @@ -119,6 +119,15 @@ public DrillLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public DrillLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -161,6 +170,7 @@ public DrillLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -197,7 +207,9 @@ public static DrillLinkedService fromJson(JsonReader jsonReader) throws IOExcept String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedDrillLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedDrillLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedDrillLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/DynamicsAXLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/DynamicsAXLinkedService.java index 6b026d57bb94..e0c20d57b7f1 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/DynamicsAXLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/DynamicsAXLinkedService.java @@ -207,6 +207,15 @@ public DynamicsAXLinkedService setEncryptedCredential(Object encryptedCredential return this; } + /** + * {@inheritDoc} + */ + @Override + public DynamicsAXLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -249,6 +258,7 @@ public DynamicsAXLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -294,7 +304,9 @@ public static DynamicsAXLinkedService fromJson(JsonReader jsonReader) throws IOE String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedDynamicsAXLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedDynamicsAXLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedDynamicsAXLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/DynamicsAuthenticationType.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/DynamicsAuthenticationType.java index dfc88af1a410..09ce57c3ee00 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/DynamicsAuthenticationType.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/DynamicsAuthenticationType.java @@ -26,6 +26,11 @@ public final class DynamicsAuthenticationType extends ExpandableStringEnum annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -435,11 +500,13 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { || serviceUri != null || organizationName != null || authenticationType != null + || domain != null || username != null || password != null || servicePrincipalId != null || servicePrincipalCredentialType != null || servicePrincipalCredential != null + || credential != null || encryptedCredential != null) { jsonWriter.writeStartObject("typeProperties"); jsonWriter.writeUntypedField("deploymentType", this.deploymentType); @@ -448,11 +515,13 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeUntypedField("serviceUri", this.serviceUri); jsonWriter.writeUntypedField("organizationName", this.organizationName); jsonWriter.writeUntypedField("authenticationType", this.authenticationType); + jsonWriter.writeUntypedField("domain", this.domain); jsonWriter.writeUntypedField("username", this.username); jsonWriter.writeJsonField("password", this.password); jsonWriter.writeUntypedField("servicePrincipalId", this.servicePrincipalId); jsonWriter.writeUntypedField("servicePrincipalCredentialType", this.servicePrincipalCredentialType); jsonWriter.writeJsonField("servicePrincipalCredential", this.servicePrincipalCredential); + jsonWriter.writeJsonField("credential", this.credential); jsonWriter.writeUntypedField("encryptedCredential", this.encryptedCredential); jsonWriter.writeEndObject(); } @@ -481,7 +550,9 @@ public static DynamicsCrmLinkedService fromJson(JsonReader jsonReader) throws IO String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedDynamicsCrmLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedDynamicsCrmLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedDynamicsCrmLinkedService.setDescription(reader.getString()); @@ -511,6 +582,8 @@ public static DynamicsCrmLinkedService fromJson(JsonReader jsonReader) throws IO deserializedDynamicsCrmLinkedService.organizationName = reader.readUntyped(); } else if ("authenticationType".equals(fieldName)) { deserializedDynamicsCrmLinkedService.authenticationType = reader.readUntyped(); + } else if ("domain".equals(fieldName)) { + deserializedDynamicsCrmLinkedService.domain = reader.readUntyped(); } else if ("username".equals(fieldName)) { deserializedDynamicsCrmLinkedService.username = reader.readUntyped(); } else if ("password".equals(fieldName)) { @@ -522,6 +595,8 @@ public static DynamicsCrmLinkedService fromJson(JsonReader jsonReader) throws IO } else if ("servicePrincipalCredential".equals(fieldName)) { deserializedDynamicsCrmLinkedService.servicePrincipalCredential = SecretBase.fromJson(reader); + } else if ("credential".equals(fieldName)) { + deserializedDynamicsCrmLinkedService.credential = SecretBase.fromJson(reader); } else if ("encryptedCredential".equals(fieldName)) { deserializedDynamicsCrmLinkedService.encryptedCredential = reader.readUntyped(); } else { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/DynamicsLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/DynamicsLinkedService.java index 3abf58475699..acfab4751eb6 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/DynamicsLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/DynamicsLinkedService.java @@ -56,11 +56,17 @@ public class DynamicsLinkedService extends LinkedService { /* * The authentication type to connect to Dynamics server. 'Office365' for online scenario, 'Ifd' for on-premises - * with Ifd scenario, 'AADServicePrincipal' for Server-To-Server authentication in online scenario. Type: string (or - * Expression with resultType string). + * with Ifd scenario, 'AADServicePrincipal' for Server-To-Server authentication in online scenario, 'Active + * Directory' for Dynamics on-premises with IFD. Type: string (or Expression with resultType string). */ private Object authenticationType; + /* + * The Active Directory domain that will verify user credentials. Type: string (or Expression with resultType + * string). + */ + private Object domain; + /* * User name to access the Dynamics instance. Type: string (or Expression with resultType string). */ @@ -233,7 +239,8 @@ public DynamicsLinkedService setOrganizationName(Object organizationName) { /** * Get the authenticationType property: The authentication type to connect to Dynamics server. 'Office365' for * online scenario, 'Ifd' for on-premises with Ifd scenario, 'AADServicePrincipal' for Server-To-Server - * authentication in online scenario. Type: string (or Expression with resultType string). + * authentication in online scenario, 'Active Directory' for Dynamics on-premises with IFD. Type: string (or + * Expression with resultType string). * * @return the authenticationType value. */ @@ -244,7 +251,8 @@ public Object getAuthenticationType() { /** * Set the authenticationType property: The authentication type to connect to Dynamics server. 'Office365' for * online scenario, 'Ifd' for on-premises with Ifd scenario, 'AADServicePrincipal' for Server-To-Server - * authentication in online scenario. Type: string (or Expression with resultType string). + * authentication in online scenario, 'Active Directory' for Dynamics on-premises with IFD. Type: string (or + * Expression with resultType string). * * @param authenticationType the authenticationType value to set. * @return the DynamicsLinkedService object itself. @@ -254,6 +262,28 @@ public DynamicsLinkedService setAuthenticationType(Object authenticationType) { return this; } + /** + * Get the domain property: The Active Directory domain that will verify user credentials. Type: string (or + * Expression with resultType string). + * + * @return the domain value. + */ + public Object getDomain() { + return this.domain; + } + + /** + * Set the domain property: The Active Directory domain that will verify user credentials. Type: string (or + * Expression with resultType string). + * + * @param domain the domain value to set. + * @return the DynamicsLinkedService object itself. + */ + public DynamicsLinkedService setDomain(Object domain) { + this.domain = domain; + return this; + } + /** * Get the username property: User name to access the Dynamics instance. Type: string (or Expression with resultType * string). @@ -410,6 +440,15 @@ public DynamicsLinkedService setCredential(CredentialReference credential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public DynamicsLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -452,6 +491,7 @@ public DynamicsLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -463,6 +503,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { || serviceUri != null || organizationName != null || authenticationType != null + || domain != null || username != null || password != null || servicePrincipalId != null @@ -477,6 +518,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeUntypedField("serviceUri", this.serviceUri); jsonWriter.writeUntypedField("organizationName", this.organizationName); jsonWriter.writeUntypedField("authenticationType", this.authenticationType); + jsonWriter.writeUntypedField("domain", this.domain); jsonWriter.writeUntypedField("username", this.username); jsonWriter.writeJsonField("password", this.password); jsonWriter.writeUntypedField("servicePrincipalId", this.servicePrincipalId); @@ -511,7 +553,9 @@ public static DynamicsLinkedService fromJson(JsonReader jsonReader) throws IOExc String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedDynamicsLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedDynamicsLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedDynamicsLinkedService.setDescription(reader.getString()); @@ -541,6 +585,8 @@ public static DynamicsLinkedService fromJson(JsonReader jsonReader) throws IOExc deserializedDynamicsLinkedService.organizationName = reader.readUntyped(); } else if ("authenticationType".equals(fieldName)) { deserializedDynamicsLinkedService.authenticationType = reader.readUntyped(); + } else if ("domain".equals(fieldName)) { + deserializedDynamicsLinkedService.domain = reader.readUntyped(); } else if ("username".equals(fieldName)) { deserializedDynamicsLinkedService.username = reader.readUntyped(); } else if ("password".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/EloquaLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/EloquaLinkedService.java index d83be5c7a622..5d8669b35f17 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/EloquaLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/EloquaLinkedService.java @@ -226,6 +226,15 @@ public EloquaLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public EloquaLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -268,6 +277,7 @@ public EloquaLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -315,7 +325,9 @@ public static EloquaLinkedService fromJson(JsonReader jsonReader) throws IOExcep String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedEloquaLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedEloquaLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedEloquaLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ExecuteDataFlowActivity.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ExecuteDataFlowActivity.java index 333798a6795b..00e5791e3963 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ExecuteDataFlowActivity.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ExecuteDataFlowActivity.java @@ -38,6 +38,11 @@ public class ExecuteDataFlowActivity extends ExecutionActivity { */ private IntegrationRuntimeReference integrationRuntime; + /* + * Continuation settings for execute data flow activity. + */ + private ContinuationSettingsReference continuationSettings; + /* * Compute properties for data flow activity. */ @@ -143,6 +148,26 @@ public ExecuteDataFlowActivity setIntegrationRuntime(IntegrationRuntimeReference return this; } + /** + * Get the continuationSettings property: Continuation settings for execute data flow activity. + * + * @return the continuationSettings value. + */ + public ContinuationSettingsReference getContinuationSettings() { + return this.continuationSettings; + } + + /** + * Set the continuationSettings property: Continuation settings for execute data flow activity. + * + * @param continuationSettings the continuationSettings value to set. + * @return the ExecuteDataFlowActivity object itself. + */ + public ExecuteDataFlowActivity setContinuationSettings(ContinuationSettingsReference continuationSettings) { + this.continuationSettings = continuationSettings; + return this; + } + /** * Get the compute property: Compute properties for data flow activity. * @@ -343,6 +368,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { if (dataflow != null || staging != null || integrationRuntime != null + || continuationSettings != null || compute != null || traceLevel != null || continueOnError != null @@ -352,6 +378,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeJsonField("dataflow", this.dataflow); jsonWriter.writeJsonField("staging", this.staging); jsonWriter.writeJsonField("integrationRuntime", this.integrationRuntime); + jsonWriter.writeJsonField("continuationSettings", this.continuationSettings); jsonWriter.writeJsonField("compute", this.compute); jsonWriter.writeUntypedField("traceLevel", this.traceLevel); jsonWriter.writeUntypedField("continueOnError", this.continueOnError); @@ -418,6 +445,9 @@ public static ExecuteDataFlowActivity fromJson(JsonReader jsonReader) throws IOE } else if ("integrationRuntime".equals(fieldName)) { deserializedExecuteDataFlowActivity.integrationRuntime = IntegrationRuntimeReference.fromJson(reader); + } else if ("continuationSettings".equals(fieldName)) { + deserializedExecuteDataFlowActivity.continuationSettings + = ContinuationSettingsReference.fromJson(reader); } else if ("compute".equals(fieldName)) { deserializedExecuteDataFlowActivity.compute = ExecuteDataFlowActivityTypePropertiesCompute.fromJson(reader); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ExpressionV2.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ExpressionV2.java index a4e60dc9774d..e39b7099301f 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ExpressionV2.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ExpressionV2.java @@ -28,9 +28,9 @@ public final class ExpressionV2 implements JsonSerializable { private String value; /* - * Expression operator value Type: string. + * Expression operator value Type: list of strings. */ - private String operator; + private List operators; /* * List of nested expressions. @@ -84,22 +84,22 @@ public ExpressionV2 setValue(String value) { } /** - * Get the operator property: Expression operator value Type: string. + * Get the operators property: Expression operator value Type: list of strings. * - * @return the operator value. + * @return the operators value. */ - public String getOperator() { - return this.operator; + public List getOperators() { + return this.operators; } /** - * Set the operator property: Expression operator value Type: string. + * Set the operators property: Expression operator value Type: list of strings. * - * @param operator the operator value to set. + * @param operators the operators value to set. * @return the ExpressionV2 object itself. */ - public ExpressionV2 setOperator(String operator) { - this.operator = operator; + public ExpressionV2 setOperators(List operators) { + this.operators = operators; return this; } @@ -131,7 +131,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); jsonWriter.writeStringField("value", this.value); - jsonWriter.writeStringField("operator", this.operator); + jsonWriter.writeArrayField("operators", this.operators, (writer, element) -> writer.writeString(element)); jsonWriter.writeArrayField("operands", this.operands, (writer, element) -> writer.writeJson(element)); return jsonWriter.writeEndObject(); } @@ -155,8 +155,9 @@ public static ExpressionV2 fromJson(JsonReader jsonReader) throws IOException { deserializedExpressionV2.type = ExpressionV2Type.fromString(reader.getString()); } else if ("value".equals(fieldName)) { deserializedExpressionV2.value = reader.getString(); - } else if ("operator".equals(fieldName)) { - deserializedExpressionV2.operator = reader.getString(); + } else if ("operators".equals(fieldName)) { + List operators = reader.readArray(reader1 -> reader1.getString()); + deserializedExpressionV2.operators = operators; } else if ("operands".equals(fieldName)) { List operands = reader.readArray(reader1 -> ExpressionV2.fromJson(reader1)); deserializedExpressionV2.operands = operands; diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ExpressionV2Type.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ExpressionV2Type.java index 2e8a3af7511e..a872f1394c09 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ExpressionV2Type.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ExpressionV2Type.java @@ -31,6 +31,11 @@ public final class ExpressionV2Type extends ExpandableStringEnum annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -222,7 +232,9 @@ public static FileServerLinkedService fromJson(JsonReader jsonReader) throws IOE String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedFileServerLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedFileServerLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedFileServerLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/FormatWriteSettings.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/FormatWriteSettings.java index 66eba64620c0..a6db38b5f229 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/FormatWriteSettings.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/FormatWriteSettings.java @@ -112,6 +112,8 @@ public static FormatWriteSettings fromJson(JsonReader jsonReader) throws IOExcep return DelimitedTextWriteSettings.fromJson(readerToUse.reset()); } else if ("JsonWriteSettings".equals(discriminatorValue)) { return JsonWriteSettings.fromJson(readerToUse.reset()); + } else if ("IcebergWriteSettings".equals(discriminatorValue)) { + return IcebergWriteSettings.fromJson(readerToUse.reset()); } else { return fromJsonKnownDiscriminator(readerToUse.reset()); } diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/FtpServerLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/FtpServerLinkedService.java index 5ec17a5aaaa6..494dc68eb06f 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/FtpServerLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/FtpServerLinkedService.java @@ -251,6 +251,15 @@ public FtpServerLinkedService setEnableServerCertificateValidation(Object enable return this; } + /** + * {@inheritDoc} + */ + @Override + public FtpServerLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -293,6 +302,7 @@ public FtpServerLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -343,7 +353,9 @@ public static FtpServerLinkedService fromJson(JsonReader jsonReader) throws IOEx String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedFtpServerLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedFtpServerLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedFtpServerLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/GoogleAdWordsLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/GoogleAdWordsLinkedService.java index 535ef1614058..489595ff8a3e 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/GoogleAdWordsLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/GoogleAdWordsLinkedService.java @@ -486,6 +486,15 @@ public GoogleAdWordsLinkedService setEncryptedCredential(Object encryptedCredent return this; } + /** + * {@inheritDoc} + */ + @Override + public GoogleAdWordsLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -528,6 +537,7 @@ public GoogleAdWordsLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -593,7 +603,9 @@ public static GoogleAdWordsLinkedService fromJson(JsonReader jsonReader) throws String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedGoogleAdWordsLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedGoogleAdWordsLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedGoogleAdWordsLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/GoogleBigQueryLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/GoogleBigQueryLinkedService.java index be635ec4f603..e7b8ce1350b3 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/GoogleBigQueryLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/GoogleBigQueryLinkedService.java @@ -369,6 +369,15 @@ public GoogleBigQueryLinkedService setEncryptedCredential(Object encryptedCreden return this; } + /** + * {@inheritDoc} + */ + @Override + public GoogleBigQueryLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -411,6 +420,7 @@ public GoogleBigQueryLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -469,7 +479,9 @@ public static GoogleBigQueryLinkedService fromJson(JsonReader jsonReader) throws String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedGoogleBigQueryLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedGoogleBigQueryLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedGoogleBigQueryLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/GoogleBigQueryV2LinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/GoogleBigQueryV2LinkedService.java index fb5721a3057a..4c22c877be02 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/GoogleBigQueryV2LinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/GoogleBigQueryV2LinkedService.java @@ -224,6 +224,15 @@ public GoogleBigQueryV2LinkedService setEncryptedCredential(String encryptedCred return this; } + /** + * {@inheritDoc} + */ + @Override + public GoogleBigQueryV2LinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -266,6 +275,7 @@ public GoogleBigQueryV2LinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -315,7 +325,9 @@ public static GoogleBigQueryV2LinkedService fromJson(JsonReader jsonReader) thro String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedGoogleBigQueryV2LinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedGoogleBigQueryV2LinkedService .setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/GoogleCloudStorageLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/GoogleCloudStorageLinkedService.java index 2be9de3e2889..748726f6b106 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/GoogleCloudStorageLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/GoogleCloudStorageLinkedService.java @@ -153,6 +153,15 @@ public GoogleCloudStorageLinkedService setEncryptedCredential(Object encryptedCr return this; } + /** + * {@inheritDoc} + */ + @Override + public GoogleCloudStorageLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -195,6 +204,7 @@ public GoogleCloudStorageLinkedService setAnnotations(List annotations) @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -233,7 +243,9 @@ public static GoogleCloudStorageLinkedService fromJson(JsonReader jsonReader) th String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedGoogleCloudStorageLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedGoogleCloudStorageLinkedService .setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/GoogleSheetsLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/GoogleSheetsLinkedService.java index 74a5a5ab4e08..2dc61c0da4a5 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/GoogleSheetsLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/GoogleSheetsLinkedService.java @@ -92,6 +92,15 @@ public GoogleSheetsLinkedService setEncryptedCredential(Object encryptedCredenti return this; } + /** + * {@inheritDoc} + */ + @Override + public GoogleSheetsLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -134,6 +143,7 @@ public GoogleSheetsLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -170,7 +180,9 @@ public static GoogleSheetsLinkedService fromJson(JsonReader jsonReader) throws I String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedGoogleSheetsLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedGoogleSheetsLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedGoogleSheetsLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/GreenplumAuthenticationType.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/GreenplumAuthenticationType.java new file mode 100644 index 000000000000..867674d2af60 --- /dev/null +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/GreenplumAuthenticationType.java @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.analytics.synapse.artifacts.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The authentication type to use. Type: string. Only used for V2. + */ +public final class GreenplumAuthenticationType extends ExpandableStringEnum { + /** + * Static value Basic for GreenplumAuthenticationType. + */ + public static final GreenplumAuthenticationType BASIC = fromString("Basic"); + + /** + * Creates a new instance of GreenplumAuthenticationType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public GreenplumAuthenticationType() { + } + + /** + * Creates or finds a GreenplumAuthenticationType from its string representation. + * + * @param name a name to look for. + * @return the corresponding GreenplumAuthenticationType. + */ + public static GreenplumAuthenticationType fromString(String name) { + return fromString(name, GreenplumAuthenticationType.class); + } + + /** + * Gets known GreenplumAuthenticationType values. + * + * @return known GreenplumAuthenticationType values. + */ + public static Collection values() { + return values(GreenplumAuthenticationType.class); + } +} diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/GreenplumLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/GreenplumLinkedService.java index c45307a31599..8da26c5b51c8 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/GreenplumLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/GreenplumLinkedService.java @@ -39,6 +39,54 @@ public class GreenplumLinkedService extends LinkedService { */ private Object encryptedCredential; + /* + * The authentication type to use. Type: string. Only used for V2. + */ + private GreenplumAuthenticationType authenticationType; + + /* + * Host name for connection. Type: string. Only used for V2. + */ + private Object host; + + /* + * The port for the connection. Type: integer. Only used for V2. + */ + private Object port; + + /* + * Username for authentication. Type: string. Only used for V2. + */ + private Object username; + + /* + * Database name for connection. Type: string. Only used for V2. + */ + private Object database; + + /* + * SSL mode for connection. Type: integer. 0: disable, 1:allow, 2: prefer, 3: require, 4: verify-ca, 5: verify-full. + * Type: integer. Only used for V2. + */ + private Object sslMode; + + /* + * The time to wait (in seconds) while trying to establish a connection before terminating the attempt and + * generating an error. Type: integer. Only used for V2. + */ + private Object connectionTimeout; + + /* + * The time to wait (in seconds) while trying to execute a command before terminating the attempt and generating an + * error. Set to zero for infinity. Type: integer. Only used for V2. + */ + private Object commandTimeout; + + /* + * The Azure key vault secret reference of password in connection string. Type: string. Only used for V2. + */ + private SecretBase password; + /** * Creates an instance of GreenplumLinkedService class. */ @@ -119,6 +167,203 @@ public GreenplumLinkedService setEncryptedCredential(Object encryptedCredential) return this; } + /** + * Get the authenticationType property: The authentication type to use. Type: string. Only used for V2. + * + * @return the authenticationType value. + */ + public GreenplumAuthenticationType getAuthenticationType() { + return this.authenticationType; + } + + /** + * Set the authenticationType property: The authentication type to use. Type: string. Only used for V2. + * + * @param authenticationType the authenticationType value to set. + * @return the GreenplumLinkedService object itself. + */ + public GreenplumLinkedService setAuthenticationType(GreenplumAuthenticationType authenticationType) { + this.authenticationType = authenticationType; + return this; + } + + /** + * Get the host property: Host name for connection. Type: string. Only used for V2. + * + * @return the host value. + */ + public Object getHost() { + return this.host; + } + + /** + * Set the host property: Host name for connection. Type: string. Only used for V2. + * + * @param host the host value to set. + * @return the GreenplumLinkedService object itself. + */ + public GreenplumLinkedService setHost(Object host) { + this.host = host; + return this; + } + + /** + * Get the port property: The port for the connection. Type: integer. Only used for V2. + * + * @return the port value. + */ + public Object getPort() { + return this.port; + } + + /** + * Set the port property: The port for the connection. Type: integer. Only used for V2. + * + * @param port the port value to set. + * @return the GreenplumLinkedService object itself. + */ + public GreenplumLinkedService setPort(Object port) { + this.port = port; + return this; + } + + /** + * Get the username property: Username for authentication. Type: string. Only used for V2. + * + * @return the username value. + */ + public Object getUsername() { + return this.username; + } + + /** + * Set the username property: Username for authentication. Type: string. Only used for V2. + * + * @param username the username value to set. + * @return the GreenplumLinkedService object itself. + */ + public GreenplumLinkedService setUsername(Object username) { + this.username = username; + return this; + } + + /** + * Get the database property: Database name for connection. Type: string. Only used for V2. + * + * @return the database value. + */ + public Object getDatabase() { + return this.database; + } + + /** + * Set the database property: Database name for connection. Type: string. Only used for V2. + * + * @param database the database value to set. + * @return the GreenplumLinkedService object itself. + */ + public GreenplumLinkedService setDatabase(Object database) { + this.database = database; + return this; + } + + /** + * Get the sslMode property: SSL mode for connection. Type: integer. 0: disable, 1:allow, 2: prefer, 3: require, 4: + * verify-ca, 5: verify-full. Type: integer. Only used for V2. + * + * @return the sslMode value. + */ + public Object getSslMode() { + return this.sslMode; + } + + /** + * Set the sslMode property: SSL mode for connection. Type: integer. 0: disable, 1:allow, 2: prefer, 3: require, 4: + * verify-ca, 5: verify-full. Type: integer. Only used for V2. + * + * @param sslMode the sslMode value to set. + * @return the GreenplumLinkedService object itself. + */ + public GreenplumLinkedService setSslMode(Object sslMode) { + this.sslMode = sslMode; + return this; + } + + /** + * Get the connectionTimeout property: The time to wait (in seconds) while trying to establish a connection before + * terminating the attempt and generating an error. Type: integer. Only used for V2. + * + * @return the connectionTimeout value. + */ + public Object getConnectionTimeout() { + return this.connectionTimeout; + } + + /** + * Set the connectionTimeout property: The time to wait (in seconds) while trying to establish a connection before + * terminating the attempt and generating an error. Type: integer. Only used for V2. + * + * @param connectionTimeout the connectionTimeout value to set. + * @return the GreenplumLinkedService object itself. + */ + public GreenplumLinkedService setConnectionTimeout(Object connectionTimeout) { + this.connectionTimeout = connectionTimeout; + return this; + } + + /** + * Get the commandTimeout property: The time to wait (in seconds) while trying to execute a command before + * terminating the attempt and generating an error. Set to zero for infinity. Type: integer. Only used for V2. + * + * @return the commandTimeout value. + */ + public Object getCommandTimeout() { + return this.commandTimeout; + } + + /** + * Set the commandTimeout property: The time to wait (in seconds) while trying to execute a command before + * terminating the attempt and generating an error. Set to zero for infinity. Type: integer. Only used for V2. + * + * @param commandTimeout the commandTimeout value to set. + * @return the GreenplumLinkedService object itself. + */ + public GreenplumLinkedService setCommandTimeout(Object commandTimeout) { + this.commandTimeout = commandTimeout; + return this; + } + + /** + * Get the password property: The Azure key vault secret reference of password in connection string. Type: string. + * Only used for V2. + * + * @return the password value. + */ + public SecretBase getPassword() { + return this.password; + } + + /** + * Set the password property: The Azure key vault secret reference of password in connection string. Type: string. + * Only used for V2. + * + * @param password the password value to set. + * @return the GreenplumLinkedService object itself. + */ + public GreenplumLinkedService setPassword(SecretBase password) { + this.password = password; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public GreenplumLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -161,16 +406,38 @@ public GreenplumLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); jsonWriter.writeArrayField("annotations", getAnnotations(), (writer, element) -> writer.writeUntyped(element)); jsonWriter.writeStringField("type", this.type); - if (connectionString != null || pwd != null || encryptedCredential != null) { + if (connectionString != null + || pwd != null + || encryptedCredential != null + || authenticationType != null + || host != null + || port != null + || username != null + || database != null + || sslMode != null + || connectionTimeout != null + || commandTimeout != null + || password != null) { jsonWriter.writeStartObject("typeProperties"); jsonWriter.writeUntypedField("connectionString", this.connectionString); jsonWriter.writeJsonField("pwd", this.pwd); jsonWriter.writeUntypedField("encryptedCredential", this.encryptedCredential); + jsonWriter.writeStringField("authenticationType", + this.authenticationType == null ? null : this.authenticationType.toString()); + jsonWriter.writeUntypedField("host", this.host); + jsonWriter.writeUntypedField("port", this.port); + jsonWriter.writeUntypedField("username", this.username); + jsonWriter.writeUntypedField("database", this.database); + jsonWriter.writeUntypedField("sslMode", this.sslMode); + jsonWriter.writeUntypedField("connectionTimeout", this.connectionTimeout); + jsonWriter.writeUntypedField("commandTimeout", this.commandTimeout); + jsonWriter.writeJsonField("password", this.password); jsonWriter.writeEndObject(); } if (getAdditionalProperties() != null) { @@ -197,7 +464,9 @@ public static GreenplumLinkedService fromJson(JsonReader jsonReader) throws IOEx String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedGreenplumLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedGreenplumLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedGreenplumLinkedService.setDescription(reader.getString()); @@ -221,6 +490,25 @@ public static GreenplumLinkedService fromJson(JsonReader jsonReader) throws IOEx deserializedGreenplumLinkedService.pwd = AzureKeyVaultSecretReference.fromJson(reader); } else if ("encryptedCredential".equals(fieldName)) { deserializedGreenplumLinkedService.encryptedCredential = reader.readUntyped(); + } else if ("authenticationType".equals(fieldName)) { + deserializedGreenplumLinkedService.authenticationType + = GreenplumAuthenticationType.fromString(reader.getString()); + } else if ("host".equals(fieldName)) { + deserializedGreenplumLinkedService.host = reader.readUntyped(); + } else if ("port".equals(fieldName)) { + deserializedGreenplumLinkedService.port = reader.readUntyped(); + } else if ("username".equals(fieldName)) { + deserializedGreenplumLinkedService.username = reader.readUntyped(); + } else if ("database".equals(fieldName)) { + deserializedGreenplumLinkedService.database = reader.readUntyped(); + } else if ("sslMode".equals(fieldName)) { + deserializedGreenplumLinkedService.sslMode = reader.readUntyped(); + } else if ("connectionTimeout".equals(fieldName)) { + deserializedGreenplumLinkedService.connectionTimeout = reader.readUntyped(); + } else if ("commandTimeout".equals(fieldName)) { + deserializedGreenplumLinkedService.commandTimeout = reader.readUntyped(); + } else if ("password".equals(fieldName)) { + deserializedGreenplumLinkedService.password = SecretBase.fromJson(reader); } else { reader.skipChildren(); } diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/HBaseLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/HBaseLinkedService.java index 1ef9771cff82..29e7a392b247 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/HBaseLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/HBaseLinkedService.java @@ -334,6 +334,15 @@ public HBaseLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public HBaseLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -376,6 +385,7 @@ public HBaseLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -432,7 +442,9 @@ public static HBaseLinkedService fromJson(JsonReader jsonReader) throws IOExcept String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedHBaseLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedHBaseLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedHBaseLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/HDInsightLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/HDInsightLinkedService.java index c1d4648421fb..3997575afd5b 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/HDInsightLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/HDInsightLinkedService.java @@ -249,6 +249,15 @@ public HDInsightLinkedService setFileSystem(Object fileSystem) { return this; } + /** + * {@inheritDoc} + */ + @Override + public HDInsightLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -291,6 +300,7 @@ public HDInsightLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -340,7 +350,9 @@ public static HDInsightLinkedService fromJson(JsonReader jsonReader) throws IOEx String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedHDInsightLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedHDInsightLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedHDInsightLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/HDInsightOnDemandLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/HDInsightOnDemandLinkedService.java index f4a5d453aeba..b978460a1ddd 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/HDInsightOnDemandLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/HDInsightOnDemandLinkedService.java @@ -39,7 +39,7 @@ public class HDInsightOnDemandLinkedService extends LinkedService { /* * Version of the HDInsight cluster.  Type: string (or Expression with resultType string). */ - private Object version; + private Object versionTypePropertiesVersion; /* * Azure Storage linked service to be used by the on-demand cluster for storing and processing data. @@ -268,22 +268,24 @@ public HDInsightOnDemandLinkedService setTimeToLive(Object timeToLive) { } /** - * Get the version property: Version of the HDInsight cluster.  Type: string (or Expression with resultType string). + * Get the versionTypePropertiesVersion property: Version of the HDInsight cluster.  Type: string (or Expression + * with resultType string). * - * @return the version value. + * @return the versionTypePropertiesVersion value. */ - public Object getVersion() { - return this.version; + public Object getVersionTypePropertiesVersion() { + return this.versionTypePropertiesVersion; } /** - * Set the version property: Version of the HDInsight cluster.  Type: string (or Expression with resultType string). + * Set the versionTypePropertiesVersion property: Version of the HDInsight cluster.  Type: string (or Expression + * with resultType string). * - * @param version the version value to set. + * @param versionTypePropertiesVersion the versionTypePropertiesVersion value to set. * @return the HDInsightOnDemandLinkedService object itself. */ - public HDInsightOnDemandLinkedService setVersion(Object version) { - this.version = version; + public HDInsightOnDemandLinkedService setVersionTypePropertiesVersion(Object versionTypePropertiesVersion) { + this.versionTypePropertiesVersion = versionTypePropertiesVersion; return this; } @@ -957,6 +959,15 @@ public HDInsightOnDemandLinkedService setCredential(CredentialReference credenti return this; } + /** + * {@inheritDoc} + */ + @Override + public HDInsightOnDemandLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -999,6 +1010,7 @@ public HDInsightOnDemandLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -1006,7 +1018,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStringField("type", this.type); if (clusterSize != null || timeToLive != null - || version != null + || versionTypePropertiesVersion != null || linkedServiceName != null || hostSubscriptionId != null || servicePrincipalId != null @@ -1041,7 +1053,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject("typeProperties"); jsonWriter.writeUntypedField("clusterSize", this.clusterSize); jsonWriter.writeUntypedField("timeToLive", this.timeToLive); - jsonWriter.writeUntypedField("version", this.version); + jsonWriter.writeUntypedField("version", this.versionTypePropertiesVersion); jsonWriter.writeJsonField("linkedServiceName", this.linkedServiceName); jsonWriter.writeUntypedField("hostSubscriptionId", this.hostSubscriptionId); jsonWriter.writeUntypedField("servicePrincipalId", this.servicePrincipalId); @@ -1103,7 +1115,9 @@ public static HDInsightOnDemandLinkedService fromJson(JsonReader jsonReader) thr String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedHDInsightOnDemandLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedHDInsightOnDemandLinkedService .setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { @@ -1127,7 +1141,8 @@ public static HDInsightOnDemandLinkedService fromJson(JsonReader jsonReader) thr } else if ("timeToLive".equals(fieldName)) { deserializedHDInsightOnDemandLinkedService.timeToLive = reader.readUntyped(); } else if ("version".equals(fieldName)) { - deserializedHDInsightOnDemandLinkedService.version = reader.readUntyped(); + deserializedHDInsightOnDemandLinkedService.versionTypePropertiesVersion + = reader.readUntyped(); } else if ("linkedServiceName".equals(fieldName)) { deserializedHDInsightOnDemandLinkedService.linkedServiceName = LinkedServiceReference.fromJson(reader); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/HdfsLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/HdfsLinkedService.java index 9f58c486a8b0..4f87988e7158 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/HdfsLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/HdfsLinkedService.java @@ -175,6 +175,15 @@ public HdfsLinkedService setPassword(SecretBase password) { return this; } + /** + * {@inheritDoc} + */ + @Override + public HdfsLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -217,6 +226,7 @@ public HdfsLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -260,7 +270,9 @@ public static HdfsLinkedService fromJson(JsonReader jsonReader) throws IOExcepti String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedHdfsLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedHdfsLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedHdfsLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/HiveLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/HiveLinkedService.java index fb0df7044674..75e7ec767439 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/HiveLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/HiveLinkedService.java @@ -488,6 +488,15 @@ public HiveLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public HiveLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -530,6 +539,7 @@ public HiveLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -599,7 +609,9 @@ public static HiveLinkedService fromJson(JsonReader jsonReader) throws IOExcepti String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedHiveLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedHiveLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedHiveLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/HttpLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/HttpLinkedService.java index ac9a6a51295d..4494435696da 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/HttpLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/HttpLinkedService.java @@ -264,6 +264,15 @@ public HttpLinkedService setEnableServerCertificateValidation(Object enableServe return this; } + /** + * {@inheritDoc} + */ + @Override + public HttpLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -306,6 +315,7 @@ public HttpLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -356,7 +366,9 @@ public static HttpLinkedService fromJson(JsonReader jsonReader) throws IOExcepti String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedHttpLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedHttpLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedHttpLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/HubspotLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/HubspotLinkedService.java index 301c3da2f5e6..44f8dfab1ec2 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/HubspotLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/HubspotLinkedService.java @@ -249,6 +249,15 @@ public HubspotLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public HubspotLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -291,6 +300,7 @@ public HubspotLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -340,7 +350,9 @@ public static HubspotLinkedService fromJson(JsonReader jsonReader) throws IOExce String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedHubspotLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedHubspotLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedHubspotLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/IcebergDataset.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/IcebergDataset.java new file mode 100644 index 000000000000..a33df77a7b89 --- /dev/null +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/IcebergDataset.java @@ -0,0 +1,219 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.analytics.synapse.artifacts.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; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Iceberg dataset. + */ +@Fluent +public class IcebergDataset extends Dataset { + /* + * Type of dataset. + */ + private String type = "Iceberg"; + + /* + * The location of the iceberg storage. Setting a file name is not allowed for iceberg format. + */ + private DatasetLocation location; + + /** + * Creates an instance of IcebergDataset class. + */ + public IcebergDataset() { + } + + /** + * Get the type property: Type of dataset. + * + * @return the type value. + */ + @Override + public String getType() { + return this.type; + } + + /** + * Get the location property: The location of the iceberg storage. Setting a file name is not allowed for iceberg + * format. + * + * @return the location value. + */ + public DatasetLocation getLocation() { + return this.location; + } + + /** + * Set the location property: The location of the iceberg storage. Setting a file name is not allowed for iceberg + * format. + * + * @param location the location value to set. + * @return the IcebergDataset object itself. + */ + public IcebergDataset setLocation(DatasetLocation location) { + this.location = location; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public IcebergDataset setDescription(String description) { + super.setDescription(description); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public IcebergDataset setStructure(Object structure) { + super.setStructure(structure); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public IcebergDataset setSchema(Object schema) { + super.setSchema(schema); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public IcebergDataset setLinkedServiceName(LinkedServiceReference linkedServiceName) { + super.setLinkedServiceName(linkedServiceName); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public IcebergDataset setParameters(Map parameters) { + super.setParameters(parameters); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public IcebergDataset setAnnotations(List annotations) { + super.setAnnotations(annotations); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public IcebergDataset setFolder(DatasetFolder folder) { + super.setFolder(folder); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("linkedServiceName", getLinkedServiceName()); + jsonWriter.writeStringField("description", getDescription()); + jsonWriter.writeUntypedField("structure", getStructure()); + jsonWriter.writeUntypedField("schema", getSchema()); + jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); + jsonWriter.writeArrayField("annotations", getAnnotations(), (writer, element) -> writer.writeUntyped(element)); + jsonWriter.writeJsonField("folder", getFolder()); + jsonWriter.writeStringField("type", this.type); + if (location != null) { + jsonWriter.writeStartObject("typeProperties"); + jsonWriter.writeJsonField("location", this.location); + jsonWriter.writeEndObject(); + } + if (getAdditionalProperties() != null) { + for (Map.Entry additionalProperty : getAdditionalProperties().entrySet()) { + jsonWriter.writeUntypedField(additionalProperty.getKey(), additionalProperty.getValue()); + } + } + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of IcebergDataset from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of IcebergDataset 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 IcebergDataset. + */ + public static IcebergDataset fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + IcebergDataset deserializedIcebergDataset = new IcebergDataset(); + Map additionalProperties = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("linkedServiceName".equals(fieldName)) { + deserializedIcebergDataset.setLinkedServiceName(LinkedServiceReference.fromJson(reader)); + } else if ("description".equals(fieldName)) { + deserializedIcebergDataset.setDescription(reader.getString()); + } else if ("structure".equals(fieldName)) { + deserializedIcebergDataset.setStructure(reader.readUntyped()); + } else if ("schema".equals(fieldName)) { + deserializedIcebergDataset.setSchema(reader.readUntyped()); + } else if ("parameters".equals(fieldName)) { + Map parameters + = reader.readMap(reader1 -> ParameterSpecification.fromJson(reader1)); + deserializedIcebergDataset.setParameters(parameters); + } else if ("annotations".equals(fieldName)) { + List annotations = reader.readArray(reader1 -> reader1.readUntyped()); + deserializedIcebergDataset.setAnnotations(annotations); + } else if ("folder".equals(fieldName)) { + deserializedIcebergDataset.setFolder(DatasetFolder.fromJson(reader)); + } else if ("type".equals(fieldName)) { + deserializedIcebergDataset.type = reader.getString(); + } else if ("typeProperties".equals(fieldName) && reader.currentToken() == JsonToken.START_OBJECT) { + while (reader.nextToken() != JsonToken.END_OBJECT) { + fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("location".equals(fieldName)) { + deserializedIcebergDataset.location = DatasetLocation.fromJson(reader); + } else { + reader.skipChildren(); + } + } + } else { + if (additionalProperties == null) { + additionalProperties = new LinkedHashMap<>(); + } + + additionalProperties.put(fieldName, reader.readUntyped()); + } + } + deserializedIcebergDataset.setAdditionalProperties(additionalProperties); + + return deserializedIcebergDataset; + }); + } +} diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/IcebergSink.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/IcebergSink.java new file mode 100644 index 000000000000..0bbdca779a13 --- /dev/null +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/IcebergSink.java @@ -0,0 +1,203 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.analytics.synapse.artifacts.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; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * A copy activity Iceberg sink. + */ +@Fluent +public final class IcebergSink extends CopySink { + /* + * Copy sink type. + */ + private String type = "IcebergSink"; + + /* + * Iceberg store settings. + */ + private StoreWriteSettings storeSettings; + + /* + * Iceberg format settings. + */ + private IcebergWriteSettings formatSettings; + + /** + * Creates an instance of IcebergSink class. + */ + public IcebergSink() { + } + + /** + * Get the type property: Copy sink type. + * + * @return the type value. + */ + @Override + public String getType() { + return this.type; + } + + /** + * Get the storeSettings property: Iceberg store settings. + * + * @return the storeSettings value. + */ + public StoreWriteSettings getStoreSettings() { + return this.storeSettings; + } + + /** + * Set the storeSettings property: Iceberg store settings. + * + * @param storeSettings the storeSettings value to set. + * @return the IcebergSink object itself. + */ + public IcebergSink setStoreSettings(StoreWriteSettings storeSettings) { + this.storeSettings = storeSettings; + return this; + } + + /** + * Get the formatSettings property: Iceberg format settings. + * + * @return the formatSettings value. + */ + public IcebergWriteSettings getFormatSettings() { + return this.formatSettings; + } + + /** + * Set the formatSettings property: Iceberg format settings. + * + * @param formatSettings the formatSettings value to set. + * @return the IcebergSink object itself. + */ + public IcebergSink setFormatSettings(IcebergWriteSettings formatSettings) { + this.formatSettings = formatSettings; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public IcebergSink setWriteBatchSize(Object writeBatchSize) { + super.setWriteBatchSize(writeBatchSize); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public IcebergSink setWriteBatchTimeout(Object writeBatchTimeout) { + super.setWriteBatchTimeout(writeBatchTimeout); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public IcebergSink setSinkRetryCount(Object sinkRetryCount) { + super.setSinkRetryCount(sinkRetryCount); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public IcebergSink setSinkRetryWait(Object sinkRetryWait) { + super.setSinkRetryWait(sinkRetryWait); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public IcebergSink setMaxConcurrentConnections(Object maxConcurrentConnections) { + super.setMaxConcurrentConnections(maxConcurrentConnections); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeUntypedField("writeBatchSize", getWriteBatchSize()); + jsonWriter.writeUntypedField("writeBatchTimeout", getWriteBatchTimeout()); + jsonWriter.writeUntypedField("sinkRetryCount", getSinkRetryCount()); + jsonWriter.writeUntypedField("sinkRetryWait", getSinkRetryWait()); + jsonWriter.writeUntypedField("maxConcurrentConnections", getMaxConcurrentConnections()); + jsonWriter.writeStringField("type", this.type); + jsonWriter.writeJsonField("storeSettings", this.storeSettings); + jsonWriter.writeJsonField("formatSettings", this.formatSettings); + if (getAdditionalProperties() != null) { + for (Map.Entry additionalProperty : getAdditionalProperties().entrySet()) { + jsonWriter.writeUntypedField(additionalProperty.getKey(), additionalProperty.getValue()); + } + } + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of IcebergSink from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of IcebergSink 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 IcebergSink. + */ + public static IcebergSink fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + IcebergSink deserializedIcebergSink = new IcebergSink(); + Map additionalProperties = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("writeBatchSize".equals(fieldName)) { + deserializedIcebergSink.setWriteBatchSize(reader.readUntyped()); + } else if ("writeBatchTimeout".equals(fieldName)) { + deserializedIcebergSink.setWriteBatchTimeout(reader.readUntyped()); + } else if ("sinkRetryCount".equals(fieldName)) { + deserializedIcebergSink.setSinkRetryCount(reader.readUntyped()); + } else if ("sinkRetryWait".equals(fieldName)) { + deserializedIcebergSink.setSinkRetryWait(reader.readUntyped()); + } else if ("maxConcurrentConnections".equals(fieldName)) { + deserializedIcebergSink.setMaxConcurrentConnections(reader.readUntyped()); + } else if ("type".equals(fieldName)) { + deserializedIcebergSink.type = reader.getString(); + } else if ("storeSettings".equals(fieldName)) { + deserializedIcebergSink.storeSettings = StoreWriteSettings.fromJson(reader); + } else if ("formatSettings".equals(fieldName)) { + deserializedIcebergSink.formatSettings = IcebergWriteSettings.fromJson(reader); + } else { + if (additionalProperties == null) { + additionalProperties = new LinkedHashMap<>(); + } + + additionalProperties.put(fieldName, reader.readUntyped()); + } + } + deserializedIcebergSink.setAdditionalProperties(additionalProperties); + + return deserializedIcebergSink; + }); + } +} diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/IcebergWriteSettings.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/IcebergWriteSettings.java new file mode 100644 index 000000000000..4af0a75616c4 --- /dev/null +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/IcebergWriteSettings.java @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.analytics.synapse.artifacts.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; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Iceberg write settings. + */ +@Immutable +public final class IcebergWriteSettings extends FormatWriteSettings { + /* + * The write setting type. + */ + private String type = "IcebergWriteSettings"; + + /** + * Creates an instance of IcebergWriteSettings class. + */ + public IcebergWriteSettings() { + } + + /** + * Get the type property: The write setting type. + * + * @return the type value. + */ + @Override + public String getType() { + return this.type; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type); + if (getAdditionalProperties() != null) { + for (Map.Entry additionalProperty : getAdditionalProperties().entrySet()) { + jsonWriter.writeUntypedField(additionalProperty.getKey(), additionalProperty.getValue()); + } + } + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of IcebergWriteSettings from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of IcebergWriteSettings 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 IcebergWriteSettings. + */ + public static IcebergWriteSettings fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + IcebergWriteSettings deserializedIcebergWriteSettings = new IcebergWriteSettings(); + Map additionalProperties = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("type".equals(fieldName)) { + deserializedIcebergWriteSettings.type = reader.getString(); + } else { + if (additionalProperties == null) { + additionalProperties = new LinkedHashMap<>(); + } + + additionalProperties.put(fieldName, reader.readUntyped()); + } + } + deserializedIcebergWriteSettings.setAdditionalProperties(additionalProperties); + + return deserializedIcebergWriteSettings; + }); + } +} diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ImpalaLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ImpalaLinkedService.java index ad8413cce70c..be05bbf848ce 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ImpalaLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ImpalaLinkedService.java @@ -337,6 +337,15 @@ public ImpalaLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public ImpalaLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -379,6 +388,7 @@ public ImpalaLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -435,7 +445,9 @@ public static ImpalaLinkedService fromJson(JsonReader jsonReader) throws IOExcep String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedImpalaLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedImpalaLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedImpalaLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ImportSettings.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ImportSettings.java index c0b3e0e233df..13ccb6b7c092 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ImportSettings.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ImportSettings.java @@ -102,7 +102,9 @@ public static ImportSettings fromJson(JsonReader jsonReader) throws IOException } } // Use the discriminator value to determine which subtype should be deserialized. - if ("AzureDatabricksDeltaLakeImportCommand".equals(discriminatorValue)) { + if ("TeradataImportCommand".equals(discriminatorValue)) { + return TeradataImportCommand.fromJson(readerToUse.reset()); + } else if ("AzureDatabricksDeltaLakeImportCommand".equals(discriminatorValue)) { return AzureDatabricksDeltaLakeImportCommand.fromJson(readerToUse.reset()); } else if ("SnowflakeImportCopyCommand".equals(discriminatorValue)) { return SnowflakeImportCopyCommand.fromJson(readerToUse.reset()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/InformixLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/InformixLinkedService.java index ff87789bd357..884e98687ddf 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/InformixLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/InformixLinkedService.java @@ -202,6 +202,15 @@ public InformixLinkedService setEncryptedCredential(Object encryptedCredential) return this; } + /** + * {@inheritDoc} + */ + @Override + public InformixLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -244,6 +253,7 @@ public InformixLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -289,7 +299,9 @@ public static InformixLinkedService fromJson(JsonReader jsonReader) throws IOExc String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedInformixLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedInformixLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedInformixLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/JiraLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/JiraLinkedService.java index caf582eefe54..b6be993498c1 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/JiraLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/JiraLinkedService.java @@ -252,6 +252,15 @@ public JiraLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public JiraLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -294,6 +303,7 @@ public JiraLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -343,7 +353,9 @@ public static JiraLinkedService fromJson(JsonReader jsonReader) throws IOExcepti String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedJiraLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedJiraLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedJiraLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LakeHouseLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LakeHouseLinkedService.java index 1a0af44657cb..98ce448f5663 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LakeHouseLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LakeHouseLinkedService.java @@ -14,14 +14,14 @@ import java.util.Map; /** - * Microsoft Fabric LakeHouse linked service. + * Microsoft Fabric Lakehouse linked service. */ @Fluent public class LakeHouseLinkedService extends LinkedService { /* * Type of linked service. */ - private String type = "LakeHouse"; + private String type = "Lakehouse"; /* * The ID of Microsoft Fabric workspace. Type: string (or Expression with resultType string). @@ -29,18 +29,18 @@ public class LakeHouseLinkedService extends LinkedService { private Object workspaceId; /* - * The ID of Microsoft Fabric LakeHouse artifact. Type: string (or Expression with resultType string). + * The ID of Microsoft Fabric Lakehouse artifact. Type: string (or Expression with resultType string). */ private Object artifactId; /* - * The ID of the application used to authenticate against Microsoft Fabric LakeHouse. Type: string (or Expression + * The ID of the application used to authenticate against Microsoft Fabric Lakehouse. Type: string (or Expression * with resultType string). */ private Object servicePrincipalId; /* - * The Key of the application used to authenticate against Microsoft Fabric LakeHouse. + * The Key of the application used to authenticate against Microsoft Fabric Lakehouse. */ private SecretBase servicePrincipalKey; @@ -109,7 +109,7 @@ public LakeHouseLinkedService setWorkspaceId(Object workspaceId) { } /** - * Get the artifactId property: The ID of Microsoft Fabric LakeHouse artifact. Type: string (or Expression with + * Get the artifactId property: The ID of Microsoft Fabric Lakehouse artifact. Type: string (or Expression with * resultType string). * * @return the artifactId value. @@ -119,7 +119,7 @@ public Object getArtifactId() { } /** - * Set the artifactId property: The ID of Microsoft Fabric LakeHouse artifact. Type: string (or Expression with + * Set the artifactId property: The ID of Microsoft Fabric Lakehouse artifact. Type: string (or Expression with * resultType string). * * @param artifactId the artifactId value to set. @@ -132,7 +132,7 @@ public LakeHouseLinkedService setArtifactId(Object artifactId) { /** * Get the servicePrincipalId property: The ID of the application used to authenticate against Microsoft Fabric - * LakeHouse. Type: string (or Expression with resultType string). + * Lakehouse. Type: string (or Expression with resultType string). * * @return the servicePrincipalId value. */ @@ -142,7 +142,7 @@ public Object getServicePrincipalId() { /** * Set the servicePrincipalId property: The ID of the application used to authenticate against Microsoft Fabric - * LakeHouse. Type: string (or Expression with resultType string). + * Lakehouse. Type: string (or Expression with resultType string). * * @param servicePrincipalId the servicePrincipalId value to set. * @return the LakeHouseLinkedService object itself. @@ -154,7 +154,7 @@ public LakeHouseLinkedService setServicePrincipalId(Object servicePrincipalId) { /** * Get the servicePrincipalKey property: The Key of the application used to authenticate against Microsoft Fabric - * LakeHouse. + * Lakehouse. * * @return the servicePrincipalKey value. */ @@ -164,7 +164,7 @@ public SecretBase getServicePrincipalKey() { /** * Set the servicePrincipalKey property: The Key of the application used to authenticate against Microsoft Fabric - * LakeHouse. + * Lakehouse. * * @param servicePrincipalKey the servicePrincipalKey value to set. * @return the LakeHouseLinkedService object itself. @@ -268,6 +268,15 @@ public LakeHouseLinkedService setServicePrincipalCredential(SecretBase servicePr return this; } + /** + * {@inheritDoc} + */ + @Override + public LakeHouseLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -310,6 +319,7 @@ public LakeHouseLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -358,7 +368,9 @@ public static LakeHouseLinkedService fromJson(JsonReader jsonReader) throws IOEx String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedLakeHouseLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedLakeHouseLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedLakeHouseLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LakeHouseLocation.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LakeHouseLocation.java index b3747cff89d9..fd156f462db2 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LakeHouseLocation.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LakeHouseLocation.java @@ -13,7 +13,7 @@ import java.util.Map; /** - * The location of Microsoft Fabric LakeHouse Files dataset. + * The location of Microsoft Fabric Lakehouse Files dataset. */ @Fluent public final class LakeHouseLocation extends DatasetLocation { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LakeHouseReadSettings.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LakeHouseReadSettings.java index 3b4a9c9b75b2..10a2c966d007 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LakeHouseReadSettings.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LakeHouseReadSettings.java @@ -13,7 +13,7 @@ import java.util.Map; /** - * Microsoft Fabric LakeHouse Files read settings. + * Microsoft Fabric Lakehouse Files read settings. */ @Fluent public final class LakeHouseReadSettings extends StoreReadSettings { @@ -29,12 +29,12 @@ public final class LakeHouseReadSettings extends StoreReadSettings { private Object recursive; /* - * Microsoft Fabric LakeHouse Files wildcardFolderPath. Type: string (or Expression with resultType string). + * Microsoft Fabric Lakehouse Files wildcardFolderPath. Type: string (or Expression with resultType string). */ private Object wildcardFolderPath; /* - * Microsoft Fabric LakeHouse Files wildcardFileName. Type: string (or Expression with resultType string). + * Microsoft Fabric Lakehouse Files wildcardFileName. Type: string (or Expression with resultType string). */ private Object wildcardFileName; @@ -109,7 +109,7 @@ public LakeHouseReadSettings setRecursive(Object recursive) { } /** - * Get the wildcardFolderPath property: Microsoft Fabric LakeHouse Files wildcardFolderPath. Type: string (or + * Get the wildcardFolderPath property: Microsoft Fabric Lakehouse Files wildcardFolderPath. Type: string (or * Expression with resultType string). * * @return the wildcardFolderPath value. @@ -119,7 +119,7 @@ public Object getWildcardFolderPath() { } /** - * Set the wildcardFolderPath property: Microsoft Fabric LakeHouse Files wildcardFolderPath. Type: string (or + * Set the wildcardFolderPath property: Microsoft Fabric Lakehouse Files wildcardFolderPath. Type: string (or * Expression with resultType string). * * @param wildcardFolderPath the wildcardFolderPath value to set. @@ -131,7 +131,7 @@ public LakeHouseReadSettings setWildcardFolderPath(Object wildcardFolderPath) { } /** - * Get the wildcardFileName property: Microsoft Fabric LakeHouse Files wildcardFileName. Type: string (or Expression + * Get the wildcardFileName property: Microsoft Fabric Lakehouse Files wildcardFileName. Type: string (or Expression * with resultType string). * * @return the wildcardFileName value. @@ -141,7 +141,7 @@ public Object getWildcardFileName() { } /** - * Set the wildcardFileName property: Microsoft Fabric LakeHouse Files wildcardFileName. Type: string (or Expression + * Set the wildcardFileName property: Microsoft Fabric Lakehouse Files wildcardFileName. Type: string (or Expression * with resultType string). * * @param wildcardFileName the wildcardFileName value to set. diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LakeHouseTableDataset.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LakeHouseTableDataset.java index 257625109afc..3ca85798861e 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LakeHouseTableDataset.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LakeHouseTableDataset.java @@ -14,17 +14,22 @@ import java.util.Map; /** - * Microsoft Fabric LakeHouse Table. + * Microsoft Fabric Lakehouse Table. */ @Fluent public class LakeHouseTableDataset extends Dataset { /* * Type of dataset. */ - private String type = "LakeHouseTable"; + private String type = "LakehouseTable"; /* - * The name of Microsoft Fabric LakeHouse Table. Type: string (or Expression with resultType string). + * The schema name of Microsoft Fabric Lakehouse Table. Type: string (or Expression with resultType string). + */ + private Object schemaTypePropertiesSchema; + + /* + * The name of Microsoft Fabric Lakehouse Table. Type: string (or Expression with resultType string). */ private Object table; @@ -45,7 +50,29 @@ public String getType() { } /** - * Get the table property: The name of Microsoft Fabric LakeHouse Table. Type: string (or Expression with resultType + * Get the schemaTypePropertiesSchema property: The schema name of Microsoft Fabric Lakehouse Table. Type: string + * (or Expression with resultType string). + * + * @return the schemaTypePropertiesSchema value. + */ + public Object getSchemaTypePropertiesSchema() { + return this.schemaTypePropertiesSchema; + } + + /** + * Set the schemaTypePropertiesSchema property: The schema name of Microsoft Fabric Lakehouse Table. Type: string + * (or Expression with resultType string). + * + * @param schemaTypePropertiesSchema the schemaTypePropertiesSchema value to set. + * @return the LakeHouseTableDataset object itself. + */ + public LakeHouseTableDataset setSchemaTypePropertiesSchema(Object schemaTypePropertiesSchema) { + this.schemaTypePropertiesSchema = schemaTypePropertiesSchema; + return this; + } + + /** + * Get the table property: The name of Microsoft Fabric Lakehouse Table. Type: string (or Expression with resultType * string). * * @return the table value. @@ -55,7 +82,7 @@ public Object getTable() { } /** - * Set the table property: The name of Microsoft Fabric LakeHouse Table. Type: string (or Expression with resultType + * Set the table property: The name of Microsoft Fabric Lakehouse Table. Type: string (or Expression with resultType * string). * * @param table the table value to set. @@ -143,8 +170,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeArrayField("annotations", getAnnotations(), (writer, element) -> writer.writeUntyped(element)); jsonWriter.writeJsonField("folder", getFolder()); jsonWriter.writeStringField("type", this.type); - if (table != null) { + if (schemaTypePropertiesSchema != null || table != null) { jsonWriter.writeStartObject("typeProperties"); + jsonWriter.writeUntypedField("schema", this.schemaTypePropertiesSchema); jsonWriter.writeUntypedField("table", this.table); jsonWriter.writeEndObject(); } @@ -197,7 +225,9 @@ public static LakeHouseTableDataset fromJson(JsonReader jsonReader) throws IOExc fieldName = reader.getFieldName(); reader.nextToken(); - if ("table".equals(fieldName)) { + if ("schema".equals(fieldName)) { + deserializedLakeHouseTableDataset.schemaTypePropertiesSchema = reader.readUntyped(); + } else if ("table".equals(fieldName)) { deserializedLakeHouseTableDataset.table = reader.readUntyped(); } else { reader.skipChildren(); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LakeHouseTableSink.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LakeHouseTableSink.java index a83bde169ee9..d6de6a23d96b 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LakeHouseTableSink.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LakeHouseTableSink.java @@ -13,7 +13,7 @@ import java.util.Map; /** - * A copy activity for Microsoft Fabric LakeHouse Table sink. + * A copy activity for Microsoft Fabric Lakehouse Table sink. */ @Fluent public final class LakeHouseTableSink extends CopySink { @@ -23,7 +23,7 @@ public final class LakeHouseTableSink extends CopySink { private String type = "LakeHouseTableSink"; /* - * The type of table action for LakeHouse Table sink. Possible values include: "None", "Append", "Overwrite". + * The type of table action for Lakehouse Table sink. Possible values include: "None", "Append", "Overwrite". */ private Object tableActionOption; @@ -56,7 +56,7 @@ public String getType() { } /** - * Get the tableActionOption property: The type of table action for LakeHouse Table sink. Possible values include: + * Get the tableActionOption property: The type of table action for Lakehouse Table sink. Possible values include: * "None", "Append", "Overwrite". * * @return the tableActionOption value. @@ -66,7 +66,7 @@ public Object getTableActionOption() { } /** - * Set the tableActionOption property: The type of table action for LakeHouse Table sink. Possible values include: + * Set the tableActionOption property: The type of table action for Lakehouse Table sink. Possible values include: * "None", "Append", "Overwrite". * * @param tableActionOption the tableActionOption value to set. diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LakeHouseTableSource.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LakeHouseTableSource.java index 0d1f00960b15..e7c3b63fd5a8 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LakeHouseTableSource.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LakeHouseTableSource.java @@ -13,7 +13,7 @@ import java.util.Map; /** - * A copy activity source for Microsoft Fabric LakeHouse Table. + * A copy activity source for Microsoft Fabric Lakehouse Table. */ @Fluent public final class LakeHouseTableSource extends CopySource { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LakeHouseWriteSettings.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LakeHouseWriteSettings.java index c13ec389c1c6..cb8792d443a1 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LakeHouseWriteSettings.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LakeHouseWriteSettings.java @@ -14,7 +14,7 @@ import java.util.Map; /** - * Microsoft Fabric LakeHouse Files write settings. + * Microsoft Fabric Lakehouse Files write settings. */ @Fluent public final class LakeHouseWriteSettings extends StoreWriteSettings { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LinkedService.java index 243f0e07b41f..28b1c6d993dd 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/LinkedService.java @@ -25,6 +25,11 @@ public class LinkedService implements JsonSerializable { */ private String type = "LinkedService"; + /* + * Version of the linked service. + */ + private String version; + /* * The integration runtime reference. */ @@ -66,6 +71,26 @@ public String getType() { return this.type; } + /** + * Get the version property: Version of the linked service. + * + * @return the version value. + */ + public String getVersion() { + return this.version; + } + + /** + * Set the version property: Version of the linked service. + * + * @param version the version value to set. + * @return the LinkedService object itself. + */ + public LinkedService setVersion(String version) { + this.version = version; + return this; + } + /** * Get the connectVia property: The integration runtime reference. * @@ -175,6 +200,7 @@ public LinkedService setAdditionalProperties(Map additionalPrope public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("type", this.type); + jsonWriter.writeStringField("version", this.version); jsonWriter.writeJsonField("connectVia", this.connectVia); jsonWriter.writeStringField("description", this.description); jsonWriter.writeMapField("parameters", this.parameters, (writer, element) -> writer.writeJson(element)); @@ -439,7 +465,7 @@ public static LinkedService fromJson(JsonReader jsonReader) throws IOException { return SharePointOnlineListLinkedService.fromJson(readerToUse.reset()); } else if ("AzureSynapseArtifacts".equals(discriminatorValue)) { return AzureSynapseArtifactsLinkedService.fromJson(readerToUse.reset()); - } else if ("LakeHouse".equals(discriminatorValue)) { + } else if ("Lakehouse".equals(discriminatorValue)) { return LakeHouseLinkedService.fromJson(readerToUse.reset()); } else if ("PowerBIWorkspace".equals(discriminatorValue)) { return PowerBIWorkspaceLinkedService.fromJson(readerToUse.reset()); @@ -466,6 +492,8 @@ static LinkedService fromJsonKnownDiscriminator(JsonReader jsonReader) throws IO if ("type".equals(fieldName)) { deserializedLinkedService.type = reader.getString(); + } else if ("version".equals(fieldName)) { + deserializedLinkedService.version = reader.getString(); } else if ("connectVia".equals(fieldName)) { deserializedLinkedService.connectVia = IntegrationRuntimeReference.fromJson(reader); } else if ("description".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MagentoLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MagentoLinkedService.java index 473590c86037..bc3f9cb5a90d 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MagentoLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MagentoLinkedService.java @@ -199,6 +199,15 @@ public MagentoLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public MagentoLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -241,6 +250,7 @@ public MagentoLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -286,7 +296,9 @@ public static MagentoLinkedService fromJson(JsonReader jsonReader) throws IOExce String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedMagentoLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedMagentoLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedMagentoLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MariaDBLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MariaDBLinkedService.java index 9c1c51e19cef..6c4a6ed32356 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MariaDBLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MariaDBLinkedService.java @@ -25,7 +25,8 @@ public class MariaDBLinkedService extends LinkedService { /* * The version of the MariaDB driver. Type: string. V1 or empty for legacy driver, V2 for new driver. V1 can support - * connection string and property bag, V2 can only support connection string. + * connection string and property bag, V2 can only support connection string. The legacy driver is scheduled for + * deprecation by October 2024. */ private Object driverVersion; @@ -54,6 +55,19 @@ public class MariaDBLinkedService extends LinkedService { */ private Object database; + /* + * This option specifies whether the driver uses TLS encryption and verification when connecting to MariaDB. E.g., + * SSLMode=<0/1/2/3/4>. Options: DISABLED (0) / PREFERRED (1) (Default) / REQUIRED (2) / VERIFY_CA (3) / + * VERIFY_IDENTITY (4), REQUIRED (2) is recommended to only allow connections encrypted with SSL/TLS. + */ + private Object sslMode; + + /* + * This option specifies whether to use a CA certificate from the system trust store, or from a specified PEM file. + * E.g. UseSystemTrustStore=<0/1>; Options: Enabled (1) / Disabled (0) (Default) + */ + private Object useSystemTrustStore; + /* * The Azure key vault secret reference of password in connection string. */ @@ -83,7 +97,8 @@ public String getType() { /** * Get the driverVersion property: The version of the MariaDB driver. Type: string. V1 or empty for legacy driver, - * V2 for new driver. V1 can support connection string and property bag, V2 can only support connection string. + * V2 for new driver. V1 can support connection string and property bag, V2 can only support connection string. The + * legacy driver is scheduled for deprecation by October 2024. * * @return the driverVersion value. */ @@ -93,7 +108,8 @@ public Object getDriverVersion() { /** * Set the driverVersion property: The version of the MariaDB driver. Type: string. V1 or empty for legacy driver, - * V2 for new driver. V1 can support connection string and property bag, V2 can only support connection string. + * V2 for new driver. V1 can support connection string and property bag, V2 can only support connection string. The + * legacy driver is scheduled for deprecation by October 2024. * * @param driverVersion the driverVersion value to set. * @return the MariaDBLinkedService object itself. @@ -205,6 +221,56 @@ public MariaDBLinkedService setDatabase(Object database) { return this; } + /** + * Get the sslMode property: This option specifies whether the driver uses TLS encryption and verification when + * connecting to MariaDB. E.g., SSLMode=<0/1/2/3/4>. Options: DISABLED (0) / PREFERRED (1) (Default) / + * REQUIRED (2) / VERIFY_CA (3) / VERIFY_IDENTITY (4), REQUIRED (2) is recommended to only allow connections + * encrypted with SSL/TLS. + * + * @return the sslMode value. + */ + public Object getSslMode() { + return this.sslMode; + } + + /** + * Set the sslMode property: This option specifies whether the driver uses TLS encryption and verification when + * connecting to MariaDB. E.g., SSLMode=<0/1/2/3/4>. Options: DISABLED (0) / PREFERRED (1) (Default) / + * REQUIRED (2) / VERIFY_CA (3) / VERIFY_IDENTITY (4), REQUIRED (2) is recommended to only allow connections + * encrypted with SSL/TLS. + * + * @param sslMode the sslMode value to set. + * @return the MariaDBLinkedService object itself. + */ + public MariaDBLinkedService setSslMode(Object sslMode) { + this.sslMode = sslMode; + return this; + } + + /** + * Get the useSystemTrustStore property: This option specifies whether to use a CA certificate from the system trust + * store, or from a specified PEM file. E.g. UseSystemTrustStore=<0/1>; Options: Enabled (1) / Disabled (0) + * (Default). + * + * @return the useSystemTrustStore value. + */ + public Object getUseSystemTrustStore() { + return this.useSystemTrustStore; + } + + /** + * Set the useSystemTrustStore property: This option specifies whether to use a CA certificate from the system trust + * store, or from a specified PEM file. E.g. UseSystemTrustStore=<0/1>; Options: Enabled (1) / Disabled (0) + * (Default). + * + * @param useSystemTrustStore the useSystemTrustStore value to set. + * @return the MariaDBLinkedService object itself. + */ + public MariaDBLinkedService setUseSystemTrustStore(Object useSystemTrustStore) { + this.useSystemTrustStore = useSystemTrustStore; + return this; + } + /** * Get the password property: The Azure key vault secret reference of password in connection string. * @@ -247,6 +313,15 @@ public MariaDBLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public MariaDBLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -289,6 +364,7 @@ public MariaDBLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -300,6 +376,8 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { || port != null || username != null || database != null + || sslMode != null + || useSystemTrustStore != null || password != null || encryptedCredential != null) { jsonWriter.writeStartObject("typeProperties"); @@ -309,6 +387,8 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeUntypedField("port", this.port); jsonWriter.writeUntypedField("username", this.username); jsonWriter.writeUntypedField("database", this.database); + jsonWriter.writeUntypedField("sslMode", this.sslMode); + jsonWriter.writeUntypedField("useSystemTrustStore", this.useSystemTrustStore); jsonWriter.writeJsonField("password", this.password); jsonWriter.writeUntypedField("encryptedCredential", this.encryptedCredential); jsonWriter.writeEndObject(); @@ -337,7 +417,9 @@ public static MariaDBLinkedService fromJson(JsonReader jsonReader) throws IOExce String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedMariaDBLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedMariaDBLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedMariaDBLinkedService.setDescription(reader.getString()); @@ -367,6 +449,10 @@ public static MariaDBLinkedService fromJson(JsonReader jsonReader) throws IOExce deserializedMariaDBLinkedService.username = reader.readUntyped(); } else if ("database".equals(fieldName)) { deserializedMariaDBLinkedService.database = reader.readUntyped(); + } else if ("sslMode".equals(fieldName)) { + deserializedMariaDBLinkedService.sslMode = reader.readUntyped(); + } else if ("useSystemTrustStore".equals(fieldName)) { + deserializedMariaDBLinkedService.useSystemTrustStore = reader.readUntyped(); } else if ("password".equals(fieldName)) { deserializedMariaDBLinkedService.password = AzureKeyVaultSecretReference.fromJson(reader); } else if ("encryptedCredential".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MarketoLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MarketoLinkedService.java index b9fdfcc6146e..7a704cb2b47c 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MarketoLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MarketoLinkedService.java @@ -224,6 +224,15 @@ public MarketoLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public MarketoLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -266,6 +275,7 @@ public MarketoLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -313,7 +323,9 @@ public static MarketoLinkedService fromJson(JsonReader jsonReader) throws IOExce String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedMarketoLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedMarketoLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedMarketoLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MicrosoftAccessLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MicrosoftAccessLinkedService.java index 31595afd7996..010b46e6841e 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MicrosoftAccessLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MicrosoftAccessLinkedService.java @@ -202,6 +202,15 @@ public MicrosoftAccessLinkedService setEncryptedCredential(Object encryptedCrede return this; } + /** + * {@inheritDoc} + */ + @Override + public MicrosoftAccessLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -244,6 +253,7 @@ public MicrosoftAccessLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -289,7 +299,9 @@ public static MicrosoftAccessLinkedService fromJson(JsonReader jsonReader) throw String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedMicrosoftAccessLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedMicrosoftAccessLinkedService .setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MongoDbAtlasLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MongoDbAtlasLinkedService.java index faf5f2ee5dfa..47612fe122c6 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MongoDbAtlasLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MongoDbAtlasLinkedService.java @@ -123,6 +123,15 @@ public MongoDbAtlasLinkedService setDriverVersion(Object driverVersion) { return this; } + /** + * {@inheritDoc} + */ + @Override + public MongoDbAtlasLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -165,6 +174,7 @@ public MongoDbAtlasLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -202,7 +212,9 @@ public static MongoDbAtlasLinkedService fromJson(JsonReader jsonReader) throws I String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedMongoDbAtlasLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedMongoDbAtlasLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedMongoDbAtlasLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MongoDbLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MongoDbLinkedService.java index c2eb281238ea..b2caa866c9ec 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MongoDbLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MongoDbLinkedService.java @@ -307,6 +307,15 @@ public MongoDbLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public MongoDbLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -349,6 +358,7 @@ public MongoDbLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -403,7 +413,9 @@ public static MongoDbLinkedService fromJson(JsonReader jsonReader) throws IOExce String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedMongoDbLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedMongoDbLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedMongoDbLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MongoDbV2LinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MongoDbV2LinkedService.java index b60e67f07a90..f2671aa32907 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MongoDbV2LinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MongoDbV2LinkedService.java @@ -94,6 +94,15 @@ public MongoDbV2LinkedService setDatabase(Object database) { return this; } + /** + * {@inheritDoc} + */ + @Override + public MongoDbV2LinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -136,6 +145,7 @@ public MongoDbV2LinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -172,7 +182,9 @@ public static MongoDbV2LinkedService fromJson(JsonReader jsonReader) throws IOEx String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedMongoDbV2LinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedMongoDbV2LinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedMongoDbV2LinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MultiplePipelineTrigger.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MultiplePipelineTrigger.java index 0321d71a271b..082365be0a78 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MultiplePipelineTrigger.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MultiplePipelineTrigger.java @@ -28,11 +28,6 @@ public class MultiplePipelineTrigger extends Trigger { */ private List pipelines; - /* - * Indicates if trigger is running or not. Updated when Start/Stop APIs are called on the Trigger. - */ - private TriggerRuntimeState runtimeState; - /** * Creates an instance of MultiplePipelineTrigger class. */ @@ -69,17 +64,6 @@ public MultiplePipelineTrigger setPipelines(List pipel return this; } - /** - * Get the runtimeState property: Indicates if trigger is running or not. Updated when Start/Stop APIs are called on - * the Trigger. - * - * @return the runtimeState value. - */ - @Override - public TriggerRuntimeState getRuntimeState() { - return this.runtimeState; - } - /** * {@inheritDoc} */ @@ -166,8 +150,8 @@ static MultiplePipelineTrigger fromJsonKnownDiscriminator(JsonReader jsonReader) if ("description".equals(fieldName)) { deserializedMultiplePipelineTrigger.setDescription(reader.getString()); } else if ("runtimeState".equals(fieldName)) { - deserializedMultiplePipelineTrigger.runtimeState - = TriggerRuntimeState.fromString(reader.getString()); + deserializedMultiplePipelineTrigger + .setRuntimeState(TriggerRuntimeState.fromString(reader.getString())); } else if ("annotations".equals(fieldName)) { List annotations = reader.readArray(reader1 -> reader1.readUntyped()); deserializedMultiplePipelineTrigger.setAnnotations(annotations); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MySqlLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MySqlLinkedService.java index 9b11d7de3903..15f93744f0b3 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MySqlLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MySqlLinkedService.java @@ -75,6 +75,44 @@ public class MySqlLinkedService extends LinkedService { */ private Object encryptedCredential; + /* + * This allows the special “zero” date value 0000-00-00 to be retrieved from the database. Type: boolean. + */ + private Object allowZeroDateTime; + + /* + * The length of time (in seconds) to wait for a connection to the server before terminating the attempt and + * generating an error. Type: integer. + */ + private Object connectionTimeout; + + /* + * True to return DateTime.MinValue for date or datetime columns that have disallowed values. Type: boolean. + */ + private Object convertZeroDateTime; + + /* + * Determines which column type (if any) should be read as a GUID. Type: string. None: No column types are + * automatically read as a Guid; Char36: All CHAR(36) columns are read/written as a Guid using lowercase hex with + * hyphens, which matches UUID. + */ + private Object guidFormat; + + /* + * The path to the client’s SSL certificate file in PEM format. SslKey must also be specified. Type: string. + */ + private Object sslCert; + + /* + * The path to the client’s SSL private key in PEM format. SslCert must also be specified. Type: string. + */ + private Object sslKey; + + /* + * When set to true, TINYINT(1) values are returned as booleans. Type: bool. + */ + private Object treatTinyAsBoolean; + /** * Creates an instance of MySqlLinkedService class. */ @@ -299,6 +337,169 @@ public MySqlLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * Get the allowZeroDateTime property: This allows the special “zero” date value 0000-00-00 to be retrieved from the + * database. Type: boolean. + * + * @return the allowZeroDateTime value. + */ + public Object getAllowZeroDateTime() { + return this.allowZeroDateTime; + } + + /** + * Set the allowZeroDateTime property: This allows the special “zero” date value 0000-00-00 to be retrieved from the + * database. Type: boolean. + * + * @param allowZeroDateTime the allowZeroDateTime value to set. + * @return the MySqlLinkedService object itself. + */ + public MySqlLinkedService setAllowZeroDateTime(Object allowZeroDateTime) { + this.allowZeroDateTime = allowZeroDateTime; + return this; + } + + /** + * Get the connectionTimeout property: The length of time (in seconds) to wait for a connection to the server before + * terminating the attempt and generating an error. Type: integer. + * + * @return the connectionTimeout value. + */ + public Object getConnectionTimeout() { + return this.connectionTimeout; + } + + /** + * Set the connectionTimeout property: The length of time (in seconds) to wait for a connection to the server before + * terminating the attempt and generating an error. Type: integer. + * + * @param connectionTimeout the connectionTimeout value to set. + * @return the MySqlLinkedService object itself. + */ + public MySqlLinkedService setConnectionTimeout(Object connectionTimeout) { + this.connectionTimeout = connectionTimeout; + return this; + } + + /** + * Get the convertZeroDateTime property: True to return DateTime.MinValue for date or datetime columns that have + * disallowed values. Type: boolean. + * + * @return the convertZeroDateTime value. + */ + public Object getConvertZeroDateTime() { + return this.convertZeroDateTime; + } + + /** + * Set the convertZeroDateTime property: True to return DateTime.MinValue for date or datetime columns that have + * disallowed values. Type: boolean. + * + * @param convertZeroDateTime the convertZeroDateTime value to set. + * @return the MySqlLinkedService object itself. + */ + public MySqlLinkedService setConvertZeroDateTime(Object convertZeroDateTime) { + this.convertZeroDateTime = convertZeroDateTime; + return this; + } + + /** + * Get the guidFormat property: Determines which column type (if any) should be read as a GUID. Type: string. None: + * No column types are automatically read as a Guid; Char36: All CHAR(36) columns are read/written as a Guid using + * lowercase hex with hyphens, which matches UUID. + * + * @return the guidFormat value. + */ + public Object getGuidFormat() { + return this.guidFormat; + } + + /** + * Set the guidFormat property: Determines which column type (if any) should be read as a GUID. Type: string. None: + * No column types are automatically read as a Guid; Char36: All CHAR(36) columns are read/written as a Guid using + * lowercase hex with hyphens, which matches UUID. + * + * @param guidFormat the guidFormat value to set. + * @return the MySqlLinkedService object itself. + */ + public MySqlLinkedService setGuidFormat(Object guidFormat) { + this.guidFormat = guidFormat; + return this; + } + + /** + * Get the sslCert property: The path to the client’s SSL certificate file in PEM format. SslKey must also be + * specified. Type: string. + * + * @return the sslCert value. + */ + public Object getSslCert() { + return this.sslCert; + } + + /** + * Set the sslCert property: The path to the client’s SSL certificate file in PEM format. SslKey must also be + * specified. Type: string. + * + * @param sslCert the sslCert value to set. + * @return the MySqlLinkedService object itself. + */ + public MySqlLinkedService setSslCert(Object sslCert) { + this.sslCert = sslCert; + return this; + } + + /** + * Get the sslKey property: The path to the client’s SSL private key in PEM format. SslCert must also be specified. + * Type: string. + * + * @return the sslKey value. + */ + public Object getSslKey() { + return this.sslKey; + } + + /** + * Set the sslKey property: The path to the client’s SSL private key in PEM format. SslCert must also be specified. + * Type: string. + * + * @param sslKey the sslKey value to set. + * @return the MySqlLinkedService object itself. + */ + public MySqlLinkedService setSslKey(Object sslKey) { + this.sslKey = sslKey; + return this; + } + + /** + * Get the treatTinyAsBoolean property: When set to true, TINYINT(1) values are returned as booleans. Type: bool. + * + * @return the treatTinyAsBoolean value. + */ + public Object getTreatTinyAsBoolean() { + return this.treatTinyAsBoolean; + } + + /** + * Set the treatTinyAsBoolean property: When set to true, TINYINT(1) values are returned as booleans. Type: bool. + * + * @param treatTinyAsBoolean the treatTinyAsBoolean value to set. + * @return the MySqlLinkedService object itself. + */ + public MySqlLinkedService setTreatTinyAsBoolean(Object treatTinyAsBoolean) { + this.treatTinyAsBoolean = treatTinyAsBoolean; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public MySqlLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -341,6 +542,7 @@ public MySqlLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -355,7 +557,14 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { || sslMode != null || useSystemTrustStore != null || password != null - || encryptedCredential != null) { + || encryptedCredential != null + || allowZeroDateTime != null + || connectionTimeout != null + || convertZeroDateTime != null + || guidFormat != null + || sslCert != null + || sslKey != null + || treatTinyAsBoolean != null) { jsonWriter.writeStartObject("typeProperties"); jsonWriter.writeUntypedField("driverVersion", this.driverVersion); jsonWriter.writeUntypedField("connectionString", this.connectionString); @@ -367,6 +576,13 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeUntypedField("useSystemTrustStore", this.useSystemTrustStore); jsonWriter.writeJsonField("password", this.password); jsonWriter.writeUntypedField("encryptedCredential", this.encryptedCredential); + jsonWriter.writeUntypedField("allowZeroDateTime", this.allowZeroDateTime); + jsonWriter.writeUntypedField("connectionTimeout", this.connectionTimeout); + jsonWriter.writeUntypedField("convertZeroDateTime", this.convertZeroDateTime); + jsonWriter.writeUntypedField("guidFormat", this.guidFormat); + jsonWriter.writeUntypedField("sslCert", this.sslCert); + jsonWriter.writeUntypedField("sslKey", this.sslKey); + jsonWriter.writeUntypedField("treatTinyAsBoolean", this.treatTinyAsBoolean); jsonWriter.writeEndObject(); } if (getAdditionalProperties() != null) { @@ -393,7 +609,9 @@ public static MySqlLinkedService fromJson(JsonReader jsonReader) throws IOExcept String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedMySqlLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedMySqlLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedMySqlLinkedService.setDescription(reader.getString()); @@ -431,6 +649,20 @@ public static MySqlLinkedService fromJson(JsonReader jsonReader) throws IOExcept deserializedMySqlLinkedService.password = AzureKeyVaultSecretReference.fromJson(reader); } else if ("encryptedCredential".equals(fieldName)) { deserializedMySqlLinkedService.encryptedCredential = reader.readUntyped(); + } else if ("allowZeroDateTime".equals(fieldName)) { + deserializedMySqlLinkedService.allowZeroDateTime = reader.readUntyped(); + } else if ("connectionTimeout".equals(fieldName)) { + deserializedMySqlLinkedService.connectionTimeout = reader.readUntyped(); + } else if ("convertZeroDateTime".equals(fieldName)) { + deserializedMySqlLinkedService.convertZeroDateTime = reader.readUntyped(); + } else if ("guidFormat".equals(fieldName)) { + deserializedMySqlLinkedService.guidFormat = reader.readUntyped(); + } else if ("sslCert".equals(fieldName)) { + deserializedMySqlLinkedService.sslCert = reader.readUntyped(); + } else if ("sslKey".equals(fieldName)) { + deserializedMySqlLinkedService.sslKey = reader.readUntyped(); + } else if ("treatTinyAsBoolean".equals(fieldName)) { + deserializedMySqlLinkedService.treatTinyAsBoolean = reader.readUntyped(); } else { reader.skipChildren(); } diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/NetezzaLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/NetezzaLinkedService.java index be4e27ef45c7..6688f422fbdf 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/NetezzaLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/NetezzaLinkedService.java @@ -119,6 +119,15 @@ public NetezzaLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public NetezzaLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -161,6 +170,7 @@ public NetezzaLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -197,7 +207,9 @@ public static NetezzaLinkedService fromJson(JsonReader jsonReader) throws IOExce String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedNetezzaLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedNetezzaLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedNetezzaLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ODataLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ODataLinkedService.java index ea5803ca2bcf..b934ff29079a 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ODataLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ODataLinkedService.java @@ -396,6 +396,15 @@ public ODataLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public ODataLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -438,6 +447,7 @@ public ODataLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -502,7 +512,9 @@ public static ODataLinkedService fromJson(JsonReader jsonReader) throws IOExcept String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedODataLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedODataLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedODataLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/OdbcLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/OdbcLinkedService.java index 6a01ec3494be..58d7e89408eb 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/OdbcLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/OdbcLinkedService.java @@ -202,6 +202,15 @@ public OdbcLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public OdbcLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -244,6 +253,7 @@ public OdbcLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -289,7 +299,9 @@ public static OdbcLinkedService fromJson(JsonReader jsonReader) throws IOExcepti String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedOdbcLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedOdbcLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedOdbcLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/Office365LinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/Office365LinkedService.java index 46dfa9c5b7dc..c315ffd61c35 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/Office365LinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/Office365LinkedService.java @@ -174,6 +174,15 @@ public Office365LinkedService setEncryptedCredential(Object encryptedCredential) return this; } + /** + * {@inheritDoc} + */ + @Override + public Office365LinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -216,6 +225,7 @@ public Office365LinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -259,7 +269,9 @@ public static Office365LinkedService fromJson(JsonReader jsonReader) throws IOEx String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedOffice365LinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedOffice365LinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedOffice365LinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/OracleAuthenticationType.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/OracleAuthenticationType.java new file mode 100644 index 000000000000..1b9caccfd33d --- /dev/null +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/OracleAuthenticationType.java @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.analytics.synapse.artifacts.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Authentication type for connecting to the Oracle database. Only used for Version 2.0. + */ +public final class OracleAuthenticationType extends ExpandableStringEnum { + /** + * Static value Basic for OracleAuthenticationType. + */ + public static final OracleAuthenticationType BASIC = fromString("Basic"); + + /** + * Creates a new instance of OracleAuthenticationType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public OracleAuthenticationType() { + } + + /** + * Creates or finds a OracleAuthenticationType from its string representation. + * + * @param name a name to look for. + * @return the corresponding OracleAuthenticationType. + */ + public static OracleAuthenticationType fromString(String name) { + return fromString(name, OracleAuthenticationType.class); + } + + /** + * Gets known OracleAuthenticationType values. + * + * @return known OracleAuthenticationType values. + */ + public static Collection values() { + return values(OracleAuthenticationType.class); + } +} diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/OracleLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/OracleLinkedService.java index d6f1f4a071ae..4beb4d5a6432 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/OracleLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/OracleLinkedService.java @@ -14,7 +14,8 @@ import java.util.Map; /** - * Oracle database. + * Oracle database. This linked service has supported version property. The Version 1.0 is scheduled for deprecation + * while your pipeline will continue to run after EOL but without any bug fix or new features. */ @Fluent public class OracleLinkedService extends LinkedService { @@ -24,15 +25,100 @@ public class OracleLinkedService extends LinkedService { private String type = "Oracle"; /* - * The connection string. Type: string, SecureString or AzureKeyVaultSecretReference. + * The connection string. Type: string, SecureString or AzureKeyVaultSecretReference. Only used for Version 1.0. */ private Object connectionString; + /* + * The location of Oracle database you want to connect to, the supported forms include connector descriptor, Easy + * Connect (Plus) Naming and Oracle Net Services Name (Only self-hosted IR). Type: string. Only used for Version + * 2.0. + */ + private Object server; + + /* + * Authentication type for connecting to the Oracle database. Only used for Version 2.0. + */ + private OracleAuthenticationType authenticationType; + + /* + * The Oracle database username. Type: string. Only used for Version 2.0. + */ + private Object username; + /* * The Azure key vault secret reference of password in connection string. */ private AzureKeyVaultSecretReference password; + /* + * Specifies the encryption client behavior. Supported values are accepted, rejected, requested or required, default + * value is required. Type: string. Only used for Version 2.0. + */ + private Object encryptionClient; + + /* + * Specifies the encryption algorithms that client can use. Supported values are AES128, AES192, AES256, 3DES112, + * 3DES168, default value is (AES256). Type: string. Only used for Version 2.0. + */ + private Object encryptionTypesClient; + + /* + * Specifies the desired data integrity behavior when this client connects to a server. Supported values are + * accepted, rejected, requested or required, default value is required. Type: string. Only used for Version 2.0. + */ + private Object cryptoChecksumClient; + + /* + * Specifies the crypto-checksum algorithms that client can use. Supported values are SHA1, SHA256, SHA384, SHA512, + * default value is (SHA512). Type: string. Only used for Version 2.0. + */ + private Object cryptoChecksumTypesClient; + + /* + * Specifies the amount that the source initially fetches for LOB columns, default value is 0. Type: integer. Only + * used for Version 2.0. + */ + private Object initialLobFetchSize; + + /* + * Specifies the number of bytes that the driver allocates to fetch the data in one database round-trip, default + * value is 10485760. Type: integer. Only used for Version 2.0. + */ + private Object fetchSize; + + /* + * Specifies the number of cursors or statements to be cached for each database connection, default value is 0. + * Type: integer. Only used for Version 2.0. + */ + private Object statementCacheSize; + + /* + * Specifies a command that is issued immediately after connecting to the database to manage session settings. Type: + * string. Only used for Version 2.0. + */ + private Object initializationString; + + /* + * Specifies whether to use bulk copy or batch insert when loading data into the database, default value is true. + * Type: boolean. Only used for Version 2.0. + */ + private Object enableBulkLoad; + + /* + * Specifies whether to use the Version 1.0 data type mappings. Do not set this to true unless you want to keep + * backward compatibility with Version 1.0's data type mappings, default value is false. Type: boolean. Only used + * for Version 2.0. + */ + private Object supportV1DataTypes; + + /* + * Specifies whether the driver returns column value with the TIMESTAMP WITH TIME ZONE data type as DateTime or + * string. This setting is ignored if supportV1DataTypes is not true, default value is true. Type: boolean. Only + * used for Version 2.0. + */ + private Object fetchTswtzAsTimestamp; + /* * The encrypted credential used for authentication. Credentials are encrypted using the integration runtime * credential manager. Type: string (or Expression with resultType string). @@ -57,7 +143,7 @@ public String getType() { /** * Get the connectionString property: The connection string. Type: string, SecureString or - * AzureKeyVaultSecretReference. + * AzureKeyVaultSecretReference. Only used for Version 1.0. * * @return the connectionString value. */ @@ -67,7 +153,7 @@ public Object getConnectionString() { /** * Set the connectionString property: The connection string. Type: string, SecureString or - * AzureKeyVaultSecretReference. + * AzureKeyVaultSecretReference. Only used for Version 1.0. * * @param connectionString the connectionString value to set. * @return the OracleLinkedService object itself. @@ -77,6 +163,72 @@ public OracleLinkedService setConnectionString(Object connectionString) { return this; } + /** + * Get the server property: The location of Oracle database you want to connect to, the supported forms include + * connector descriptor, Easy Connect (Plus) Naming and Oracle Net Services Name (Only self-hosted IR). Type: + * string. Only used for Version 2.0. + * + * @return the server value. + */ + public Object getServer() { + return this.server; + } + + /** + * Set the server property: The location of Oracle database you want to connect to, the supported forms include + * connector descriptor, Easy Connect (Plus) Naming and Oracle Net Services Name (Only self-hosted IR). Type: + * string. Only used for Version 2.0. + * + * @param server the server value to set. + * @return the OracleLinkedService object itself. + */ + public OracleLinkedService setServer(Object server) { + this.server = server; + return this; + } + + /** + * Get the authenticationType property: Authentication type for connecting to the Oracle database. Only used for + * Version 2.0. + * + * @return the authenticationType value. + */ + public OracleAuthenticationType getAuthenticationType() { + return this.authenticationType; + } + + /** + * Set the authenticationType property: Authentication type for connecting to the Oracle database. Only used for + * Version 2.0. + * + * @param authenticationType the authenticationType value to set. + * @return the OracleLinkedService object itself. + */ + public OracleLinkedService setAuthenticationType(OracleAuthenticationType authenticationType) { + this.authenticationType = authenticationType; + return this; + } + + /** + * Get the username property: The Oracle database username. Type: string. Only used for Version 2.0. + * + * @return the username value. + */ + public Object getUsername() { + return this.username; + } + + /** + * Set the username property: The Oracle database username. Type: string. Only used for Version 2.0. + * + * @param username the username value to set. + * @return the OracleLinkedService object itself. + */ + public OracleLinkedService setUsername(Object username) { + this.username = username; + return this; + } + /** * Get the password property: The Azure key vault secret reference of password in connection string. * @@ -97,6 +249,256 @@ public OracleLinkedService setPassword(AzureKeyVaultSecretReference password) { return this; } + /** + * Get the encryptionClient property: Specifies the encryption client behavior. Supported values are accepted, + * rejected, requested or required, default value is required. Type: string. Only used for Version 2.0. + * + * @return the encryptionClient value. + */ + public Object getEncryptionClient() { + return this.encryptionClient; + } + + /** + * Set the encryptionClient property: Specifies the encryption client behavior. Supported values are accepted, + * rejected, requested or required, default value is required. Type: string. Only used for Version 2.0. + * + * @param encryptionClient the encryptionClient value to set. + * @return the OracleLinkedService object itself. + */ + public OracleLinkedService setEncryptionClient(Object encryptionClient) { + this.encryptionClient = encryptionClient; + return this; + } + + /** + * Get the encryptionTypesClient property: Specifies the encryption algorithms that client can use. Supported values + * are AES128, AES192, AES256, 3DES112, 3DES168, default value is (AES256). Type: string. Only used for Version 2.0. + * + * @return the encryptionTypesClient value. + */ + public Object getEncryptionTypesClient() { + return this.encryptionTypesClient; + } + + /** + * Set the encryptionTypesClient property: Specifies the encryption algorithms that client can use. Supported values + * are AES128, AES192, AES256, 3DES112, 3DES168, default value is (AES256). Type: string. Only used for Version 2.0. + * + * @param encryptionTypesClient the encryptionTypesClient value to set. + * @return the OracleLinkedService object itself. + */ + public OracleLinkedService setEncryptionTypesClient(Object encryptionTypesClient) { + this.encryptionTypesClient = encryptionTypesClient; + return this; + } + + /** + * Get the cryptoChecksumClient property: Specifies the desired data integrity behavior when this client connects to + * a server. Supported values are accepted, rejected, requested or required, default value is required. Type: + * string. Only used for Version 2.0. + * + * @return the cryptoChecksumClient value. + */ + public Object getCryptoChecksumClient() { + return this.cryptoChecksumClient; + } + + /** + * Set the cryptoChecksumClient property: Specifies the desired data integrity behavior when this client connects to + * a server. Supported values are accepted, rejected, requested or required, default value is required. Type: + * string. Only used for Version 2.0. + * + * @param cryptoChecksumClient the cryptoChecksumClient value to set. + * @return the OracleLinkedService object itself. + */ + public OracleLinkedService setCryptoChecksumClient(Object cryptoChecksumClient) { + this.cryptoChecksumClient = cryptoChecksumClient; + return this; + } + + /** + * Get the cryptoChecksumTypesClient property: Specifies the crypto-checksum algorithms that client can use. + * Supported values are SHA1, SHA256, SHA384, SHA512, default value is (SHA512). Type: string. Only used for Version + * 2.0. + * + * @return the cryptoChecksumTypesClient value. + */ + public Object getCryptoChecksumTypesClient() { + return this.cryptoChecksumTypesClient; + } + + /** + * Set the cryptoChecksumTypesClient property: Specifies the crypto-checksum algorithms that client can use. + * Supported values are SHA1, SHA256, SHA384, SHA512, default value is (SHA512). Type: string. Only used for Version + * 2.0. + * + * @param cryptoChecksumTypesClient the cryptoChecksumTypesClient value to set. + * @return the OracleLinkedService object itself. + */ + public OracleLinkedService setCryptoChecksumTypesClient(Object cryptoChecksumTypesClient) { + this.cryptoChecksumTypesClient = cryptoChecksumTypesClient; + return this; + } + + /** + * Get the initialLobFetchSize property: Specifies the amount that the source initially fetches for LOB columns, + * default value is 0. Type: integer. Only used for Version 2.0. + * + * @return the initialLobFetchSize value. + */ + public Object getInitialLobFetchSize() { + return this.initialLobFetchSize; + } + + /** + * Set the initialLobFetchSize property: Specifies the amount that the source initially fetches for LOB columns, + * default value is 0. Type: integer. Only used for Version 2.0. + * + * @param initialLobFetchSize the initialLobFetchSize value to set. + * @return the OracleLinkedService object itself. + */ + public OracleLinkedService setInitialLobFetchSize(Object initialLobFetchSize) { + this.initialLobFetchSize = initialLobFetchSize; + return this; + } + + /** + * Get the fetchSize property: Specifies the number of bytes that the driver allocates to fetch the data in one + * database round-trip, default value is 10485760. Type: integer. Only used for Version 2.0. + * + * @return the fetchSize value. + */ + public Object getFetchSize() { + return this.fetchSize; + } + + /** + * Set the fetchSize property: Specifies the number of bytes that the driver allocates to fetch the data in one + * database round-trip, default value is 10485760. Type: integer. Only used for Version 2.0. + * + * @param fetchSize the fetchSize value to set. + * @return the OracleLinkedService object itself. + */ + public OracleLinkedService setFetchSize(Object fetchSize) { + this.fetchSize = fetchSize; + return this; + } + + /** + * Get the statementCacheSize property: Specifies the number of cursors or statements to be cached for each database + * connection, default value is 0. Type: integer. Only used for Version 2.0. + * + * @return the statementCacheSize value. + */ + public Object getStatementCacheSize() { + return this.statementCacheSize; + } + + /** + * Set the statementCacheSize property: Specifies the number of cursors or statements to be cached for each database + * connection, default value is 0. Type: integer. Only used for Version 2.0. + * + * @param statementCacheSize the statementCacheSize value to set. + * @return the OracleLinkedService object itself. + */ + public OracleLinkedService setStatementCacheSize(Object statementCacheSize) { + this.statementCacheSize = statementCacheSize; + return this; + } + + /** + * Get the initializationString property: Specifies a command that is issued immediately after connecting to the + * database to manage session settings. Type: string. Only used for Version 2.0. + * + * @return the initializationString value. + */ + public Object getInitializationString() { + return this.initializationString; + } + + /** + * Set the initializationString property: Specifies a command that is issued immediately after connecting to the + * database to manage session settings. Type: string. Only used for Version 2.0. + * + * @param initializationString the initializationString value to set. + * @return the OracleLinkedService object itself. + */ + public OracleLinkedService setInitializationString(Object initializationString) { + this.initializationString = initializationString; + return this; + } + + /** + * Get the enableBulkLoad property: Specifies whether to use bulk copy or batch insert when loading data into the + * database, default value is true. Type: boolean. Only used for Version 2.0. + * + * @return the enableBulkLoad value. + */ + public Object getEnableBulkLoad() { + return this.enableBulkLoad; + } + + /** + * Set the enableBulkLoad property: Specifies whether to use bulk copy or batch insert when loading data into the + * database, default value is true. Type: boolean. Only used for Version 2.0. + * + * @param enableBulkLoad the enableBulkLoad value to set. + * @return the OracleLinkedService object itself. + */ + public OracleLinkedService setEnableBulkLoad(Object enableBulkLoad) { + this.enableBulkLoad = enableBulkLoad; + return this; + } + + /** + * Get the supportV1DataTypes property: Specifies whether to use the Version 1.0 data type mappings. Do not set this + * to true unless you want to keep backward compatibility with Version 1.0's data type mappings, default value is + * false. Type: boolean. Only used for Version 2.0. + * + * @return the supportV1DataTypes value. + */ + public Object getSupportV1DataTypes() { + return this.supportV1DataTypes; + } + + /** + * Set the supportV1DataTypes property: Specifies whether to use the Version 1.0 data type mappings. Do not set this + * to true unless you want to keep backward compatibility with Version 1.0's data type mappings, default value is + * false. Type: boolean. Only used for Version 2.0. + * + * @param supportV1DataTypes the supportV1DataTypes value to set. + * @return the OracleLinkedService object itself. + */ + public OracleLinkedService setSupportV1DataTypes(Object supportV1DataTypes) { + this.supportV1DataTypes = supportV1DataTypes; + return this; + } + + /** + * Get the fetchTswtzAsTimestamp property: Specifies whether the driver returns column value with the TIMESTAMP WITH + * TIME ZONE data type as DateTime or string. This setting is ignored if supportV1DataTypes is not true, default + * value is true. Type: boolean. Only used for Version 2.0. + * + * @return the fetchTswtzAsTimestamp value. + */ + public Object getFetchTswtzAsTimestamp() { + return this.fetchTswtzAsTimestamp; + } + + /** + * Set the fetchTswtzAsTimestamp property: Specifies whether the driver returns column value with the TIMESTAMP WITH + * TIME ZONE data type as DateTime or string. This setting is ignored if supportV1DataTypes is not true, default + * value is true. Type: boolean. Only used for Version 2.0. + * + * @param fetchTswtzAsTimestamp the fetchTswtzAsTimestamp value to set. + * @return the OracleLinkedService object itself. + */ + public OracleLinkedService setFetchTswtzAsTimestamp(Object fetchTswtzAsTimestamp) { + this.fetchTswtzAsTimestamp = fetchTswtzAsTimestamp; + return this; + } + /** * Get the encryptedCredential property: The encrypted credential used for authentication. Credentials are encrypted * using the integration runtime credential manager. Type: string (or Expression with resultType string). @@ -119,6 +521,15 @@ public OracleLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public OracleLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -161,15 +572,47 @@ public OracleLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); jsonWriter.writeArrayField("annotations", getAnnotations(), (writer, element) -> writer.writeUntyped(element)); jsonWriter.writeStringField("type", this.type); - if (connectionString != null || password != null || encryptedCredential != null) { + if (connectionString != null + || server != null + || authenticationType != null + || username != null + || password != null + || encryptionClient != null + || encryptionTypesClient != null + || cryptoChecksumClient != null + || cryptoChecksumTypesClient != null + || initialLobFetchSize != null + || fetchSize != null + || statementCacheSize != null + || initializationString != null + || enableBulkLoad != null + || supportV1DataTypes != null + || fetchTswtzAsTimestamp != null + || encryptedCredential != null) { jsonWriter.writeStartObject("typeProperties"); jsonWriter.writeUntypedField("connectionString", this.connectionString); + jsonWriter.writeUntypedField("server", this.server); + jsonWriter.writeStringField("authenticationType", + this.authenticationType == null ? null : this.authenticationType.toString()); + jsonWriter.writeUntypedField("username", this.username); jsonWriter.writeJsonField("password", this.password); + jsonWriter.writeUntypedField("encryptionClient", this.encryptionClient); + jsonWriter.writeUntypedField("encryptionTypesClient", this.encryptionTypesClient); + jsonWriter.writeUntypedField("cryptoChecksumClient", this.cryptoChecksumClient); + jsonWriter.writeUntypedField("cryptoChecksumTypesClient", this.cryptoChecksumTypesClient); + jsonWriter.writeUntypedField("initialLobFetchSize", this.initialLobFetchSize); + jsonWriter.writeUntypedField("fetchSize", this.fetchSize); + jsonWriter.writeUntypedField("statementCacheSize", this.statementCacheSize); + jsonWriter.writeUntypedField("initializationString", this.initializationString); + jsonWriter.writeUntypedField("enableBulkLoad", this.enableBulkLoad); + jsonWriter.writeUntypedField("supportV1DataTypes", this.supportV1DataTypes); + jsonWriter.writeUntypedField("fetchTswtzAsTimestamp", this.fetchTswtzAsTimestamp); jsonWriter.writeUntypedField("encryptedCredential", this.encryptedCredential); jsonWriter.writeEndObject(); } @@ -198,7 +641,9 @@ public static OracleLinkedService fromJson(JsonReader jsonReader) throws IOExcep String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedOracleLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedOracleLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedOracleLinkedService.setDescription(reader.getString()); @@ -218,8 +663,37 @@ public static OracleLinkedService fromJson(JsonReader jsonReader) throws IOExcep if ("connectionString".equals(fieldName)) { deserializedOracleLinkedService.connectionString = reader.readUntyped(); + } else if ("server".equals(fieldName)) { + deserializedOracleLinkedService.server = reader.readUntyped(); + } else if ("authenticationType".equals(fieldName)) { + deserializedOracleLinkedService.authenticationType + = OracleAuthenticationType.fromString(reader.getString()); + } else if ("username".equals(fieldName)) { + deserializedOracleLinkedService.username = reader.readUntyped(); } else if ("password".equals(fieldName)) { deserializedOracleLinkedService.password = AzureKeyVaultSecretReference.fromJson(reader); + } else if ("encryptionClient".equals(fieldName)) { + deserializedOracleLinkedService.encryptionClient = reader.readUntyped(); + } else if ("encryptionTypesClient".equals(fieldName)) { + deserializedOracleLinkedService.encryptionTypesClient = reader.readUntyped(); + } else if ("cryptoChecksumClient".equals(fieldName)) { + deserializedOracleLinkedService.cryptoChecksumClient = reader.readUntyped(); + } else if ("cryptoChecksumTypesClient".equals(fieldName)) { + deserializedOracleLinkedService.cryptoChecksumTypesClient = reader.readUntyped(); + } else if ("initialLobFetchSize".equals(fieldName)) { + deserializedOracleLinkedService.initialLobFetchSize = reader.readUntyped(); + } else if ("fetchSize".equals(fieldName)) { + deserializedOracleLinkedService.fetchSize = reader.readUntyped(); + } else if ("statementCacheSize".equals(fieldName)) { + deserializedOracleLinkedService.statementCacheSize = reader.readUntyped(); + } else if ("initializationString".equals(fieldName)) { + deserializedOracleLinkedService.initializationString = reader.readUntyped(); + } else if ("enableBulkLoad".equals(fieldName)) { + deserializedOracleLinkedService.enableBulkLoad = reader.readUntyped(); + } else if ("supportV1DataTypes".equals(fieldName)) { + deserializedOracleLinkedService.supportV1DataTypes = reader.readUntyped(); + } else if ("fetchTswtzAsTimestamp".equals(fieldName)) { + deserializedOracleLinkedService.fetchTswtzAsTimestamp = reader.readUntyped(); } else if ("encryptedCredential".equals(fieldName)) { deserializedOracleLinkedService.encryptedCredential = reader.readUntyped(); } else { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/OracleServiceCloudLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/OracleServiceCloudLinkedService.java index 87b7eb47b6a5..28cc36f59672 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/OracleServiceCloudLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/OracleServiceCloudLinkedService.java @@ -228,6 +228,15 @@ public OracleServiceCloudLinkedService setEncryptedCredential(Object encryptedCr return this; } + /** + * {@inheritDoc} + */ + @Override + public OracleServiceCloudLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -270,6 +279,7 @@ public OracleServiceCloudLinkedService setAnnotations(List annotations) @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -318,7 +328,9 @@ public static OracleServiceCloudLinkedService fromJson(JsonReader jsonReader) th String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedOracleServiceCloudLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedOracleServiceCloudLinkedService .setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/PaypalLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/PaypalLinkedService.java index 6365b17e188b..eff1e65a296d 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/PaypalLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/PaypalLinkedService.java @@ -224,6 +224,15 @@ public PaypalLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public PaypalLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -266,6 +275,7 @@ public PaypalLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -313,7 +323,9 @@ public static PaypalLinkedService fromJson(JsonReader jsonReader) throws IOExcep String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedPaypalLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedPaypalLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedPaypalLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/PhoenixLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/PhoenixLinkedService.java index 2ae500e6436a..cdc11fc12070 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/PhoenixLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/PhoenixLinkedService.java @@ -363,6 +363,15 @@ public PhoenixLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public PhoenixLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -405,6 +414,7 @@ public PhoenixLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -463,7 +473,9 @@ public static PhoenixLinkedService fromJson(JsonReader jsonReader) throws IOExce String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedPhoenixLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedPhoenixLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedPhoenixLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/PostgreSqlLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/PostgreSqlLinkedService.java index 353b06793528..65cccfdb7977 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/PostgreSqlLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/PostgreSqlLinkedService.java @@ -117,6 +117,15 @@ public PostgreSqlLinkedService setEncryptedCredential(Object encryptedCredential return this; } + /** + * {@inheritDoc} + */ + @Override + public PostgreSqlLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -159,6 +168,7 @@ public PostgreSqlLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -196,7 +206,9 @@ public static PostgreSqlLinkedService fromJson(JsonReader jsonReader) throws IOE String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedPostgreSqlLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedPostgreSqlLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedPostgreSqlLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/PostgreSqlV2LinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/PostgreSqlV2LinkedService.java index 1d129dbf5565..cc121593b485 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/PostgreSqlV2LinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/PostgreSqlV2LinkedService.java @@ -43,6 +43,11 @@ public class PostgreSqlV2LinkedService extends LinkedService { */ private Object database; + /* + * The authentication type to use. Type: string. + */ + private Object authenticationType; + /* * SSL mode for connection. Type: integer. 0: disable, 1:allow, 2: prefer, 3: require, 4: verify-ca, 5: verify-full. * Type: integer. @@ -219,6 +224,26 @@ public PostgreSqlV2LinkedService setDatabase(Object database) { return this; } + /** + * Get the authenticationType property: The authentication type to use. Type: string. + * + * @return the authenticationType value. + */ + public Object getAuthenticationType() { + return this.authenticationType; + } + + /** + * Set the authenticationType property: The authentication type to use. Type: string. + * + * @param authenticationType the authenticationType value to set. + * @return the PostgreSqlV2LinkedService object itself. + */ + public PostgreSqlV2LinkedService setAuthenticationType(Object authenticationType) { + this.authenticationType = authenticationType; + return this; + } + /** * Get the sslMode property: SSL mode for connection. Type: integer. 0: disable, 1:allow, 2: prefer, 3: require, 4: * verify-ca, 5: verify-full. Type: integer. @@ -537,6 +562,15 @@ public PostgreSqlV2LinkedService setEncryptedCredential(Object encryptedCredenti return this; } + /** + * {@inheritDoc} + */ + @Override + public PostgreSqlV2LinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -579,6 +613,7 @@ public PostgreSqlV2LinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -588,6 +623,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { || port != null || username != null || database != null + || authenticationType != null || sslMode != null || schema != null || pooling != null @@ -608,6 +644,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeUntypedField("port", this.port); jsonWriter.writeUntypedField("username", this.username); jsonWriter.writeUntypedField("database", this.database); + jsonWriter.writeUntypedField("authenticationType", this.authenticationType); jsonWriter.writeUntypedField("sslMode", this.sslMode); jsonWriter.writeUntypedField("schema", this.schema); jsonWriter.writeUntypedField("pooling", this.pooling); @@ -650,7 +687,9 @@ public static PostgreSqlV2LinkedService fromJson(JsonReader jsonReader) throws I String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedPostgreSqlV2LinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedPostgreSqlV2LinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedPostgreSqlV2LinkedService.setDescription(reader.getString()); @@ -676,6 +715,8 @@ public static PostgreSqlV2LinkedService fromJson(JsonReader jsonReader) throws I deserializedPostgreSqlV2LinkedService.username = reader.readUntyped(); } else if ("database".equals(fieldName)) { deserializedPostgreSqlV2LinkedService.database = reader.readUntyped(); + } else if ("authenticationType".equals(fieldName)) { + deserializedPostgreSqlV2LinkedService.authenticationType = reader.readUntyped(); } else if ("sslMode".equals(fieldName)) { deserializedPostgreSqlV2LinkedService.sslMode = reader.readUntyped(); } else if ("schema".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/PowerBIWorkspaceLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/PowerBIWorkspaceLinkedService.java index ba9185d00925..c2c2d264abd3 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/PowerBIWorkspaceLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/PowerBIWorkspaceLinkedService.java @@ -89,6 +89,15 @@ public PowerBIWorkspaceLinkedService setTenantId(String tenantId) { return this; } + /** + * {@inheritDoc} + */ + @Override + public PowerBIWorkspaceLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -131,6 +140,7 @@ public PowerBIWorkspaceLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -168,7 +178,9 @@ public static PowerBIWorkspaceLinkedService fromJson(JsonReader jsonReader) thro String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedPowerBIWorkspaceLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedPowerBIWorkspaceLinkedService .setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/PrestoLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/PrestoLinkedService.java index 0568646b51d1..9c6438bc04dd 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/PrestoLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/PrestoLinkedService.java @@ -413,6 +413,15 @@ public PrestoLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public PrestoLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -455,6 +464,7 @@ public PrestoLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -517,7 +527,9 @@ public static PrestoLinkedService fromJson(JsonReader jsonReader) throws IOExcep String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedPrestoLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedPrestoLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedPrestoLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/QuickBooksLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/QuickBooksLinkedService.java index 617b2e802c29..7408bf2be855 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/QuickBooksLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/QuickBooksLinkedService.java @@ -272,6 +272,15 @@ public QuickBooksLinkedService setEncryptedCredential(Object encryptedCredential return this; } + /** + * {@inheritDoc} + */ + @Override + public QuickBooksLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -314,6 +323,7 @@ public QuickBooksLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -365,7 +375,9 @@ public static QuickBooksLinkedService fromJson(JsonReader jsonReader) throws IOE String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedQuickBooksLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedQuickBooksLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedQuickBooksLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/QuickbaseLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/QuickbaseLinkedService.java index 1dfad50c5f84..0c615b0686bf 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/QuickbaseLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/QuickbaseLinkedService.java @@ -117,6 +117,15 @@ public QuickbaseLinkedService setEncryptedCredential(Object encryptedCredential) return this; } + /** + * {@inheritDoc} + */ + @Override + public QuickbaseLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -159,6 +168,7 @@ public QuickbaseLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -196,7 +206,9 @@ public static QuickbaseLinkedService fromJson(JsonReader jsonReader) throws IOEx String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedQuickbaseLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedQuickbaseLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedQuickbaseLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/RerunTumblingWindowTrigger.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/RerunTumblingWindowTrigger.java index 1c9bd50133f3..55683f0f1a03 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/RerunTumblingWindowTrigger.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/RerunTumblingWindowTrigger.java @@ -47,11 +47,6 @@ public class RerunTumblingWindowTrigger extends Trigger { */ private int rerunConcurrency; - /* - * Indicates if trigger is running or not. Updated when Start/Stop APIs are called on the Trigger. - */ - private TriggerRuntimeState runtimeState; - /** * Creates an instance of RerunTumblingWindowTrigger class. */ @@ -154,17 +149,6 @@ public RerunTumblingWindowTrigger setRerunConcurrency(int rerunConcurrency) { return this; } - /** - * Get the runtimeState property: Indicates if trigger is running or not. Updated when Start/Stop APIs are called on - * the Trigger. - * - * @return the runtimeState value. - */ - @Override - public TriggerRuntimeState getRuntimeState() { - return this.runtimeState; - } - /** * {@inheritDoc} */ @@ -232,8 +216,8 @@ public static RerunTumblingWindowTrigger fromJson(JsonReader jsonReader) throws if ("description".equals(fieldName)) { deserializedRerunTumblingWindowTrigger.setDescription(reader.getString()); } else if ("runtimeState".equals(fieldName)) { - deserializedRerunTumblingWindowTrigger.runtimeState - = TriggerRuntimeState.fromString(reader.getString()); + deserializedRerunTumblingWindowTrigger + .setRuntimeState(TriggerRuntimeState.fromString(reader.getString())); } else if ("annotations".equals(fieldName)) { List annotations = reader.readArray(reader1 -> reader1.readUntyped()); deserializedRerunTumblingWindowTrigger.setAnnotations(annotations); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ResponsysLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ResponsysLinkedService.java index 0b1f9a9b4e48..402eb66840cd 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ResponsysLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ResponsysLinkedService.java @@ -232,6 +232,15 @@ public ResponsysLinkedService setEncryptedCredential(Object encryptedCredential) return this; } + /** + * {@inheritDoc} + */ + @Override + public ResponsysLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -274,6 +283,7 @@ public ResponsysLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -321,7 +331,9 @@ public static ResponsysLinkedService fromJson(JsonReader jsonReader) throws IOEx String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedResponsysLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedResponsysLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedResponsysLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/RestServiceLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/RestServiceLinkedService.java index cd6ec788bfa0..38a9371fbf42 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/RestServiceLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/RestServiceLinkedService.java @@ -122,6 +122,24 @@ public class RestServiceLinkedService extends LinkedService { */ private Object scope; + /* + * The service principal credential type to use in Server-To-Server authentication. 'ServicePrincipalKey' for + * key/secret, 'ServicePrincipalCert' for certificate. Type: string (or Expression with resultType string). + */ + private Object servicePrincipalCredentialType; + + /* + * Specify the base64 encoded certificate of your application registered in Azure Active Directory. Type: string (or + * Expression with resultType string). + */ + private SecretBase servicePrincipalEmbeddedCert; + + /* + * Specify the password of your certificate if your certificate has a password and you are using AadServicePrincipal + * authentication. Type: string (or Expression with resultType string). + */ + private SecretBase servicePrincipalEmbeddedCertPassword; + /** * Creates an instance of RestServiceLinkedService class. */ @@ -518,6 +536,86 @@ public RestServiceLinkedService setScope(Object scope) { return this; } + /** + * Get the servicePrincipalCredentialType property: The service principal credential type to use in Server-To-Server + * authentication. 'ServicePrincipalKey' for key/secret, 'ServicePrincipalCert' for certificate. Type: string (or + * Expression with resultType string). + * + * @return the servicePrincipalCredentialType value. + */ + public Object getServicePrincipalCredentialType() { + return this.servicePrincipalCredentialType; + } + + /** + * Set the servicePrincipalCredentialType property: The service principal credential type to use in Server-To-Server + * authentication. 'ServicePrincipalKey' for key/secret, 'ServicePrincipalCert' for certificate. Type: string (or + * Expression with resultType string). + * + * @param servicePrincipalCredentialType the servicePrincipalCredentialType value to set. + * @return the RestServiceLinkedService object itself. + */ + public RestServiceLinkedService setServicePrincipalCredentialType(Object servicePrincipalCredentialType) { + this.servicePrincipalCredentialType = servicePrincipalCredentialType; + return this; + } + + /** + * Get the servicePrincipalEmbeddedCert property: Specify the base64 encoded certificate of your application + * registered in Azure Active Directory. Type: string (or Expression with resultType string). + * + * @return the servicePrincipalEmbeddedCert value. + */ + public SecretBase getServicePrincipalEmbeddedCert() { + return this.servicePrincipalEmbeddedCert; + } + + /** + * Set the servicePrincipalEmbeddedCert property: Specify the base64 encoded certificate of your application + * registered in Azure Active Directory. Type: string (or Expression with resultType string). + * + * @param servicePrincipalEmbeddedCert the servicePrincipalEmbeddedCert value to set. + * @return the RestServiceLinkedService object itself. + */ + public RestServiceLinkedService setServicePrincipalEmbeddedCert(SecretBase servicePrincipalEmbeddedCert) { + this.servicePrincipalEmbeddedCert = servicePrincipalEmbeddedCert; + return this; + } + + /** + * Get the servicePrincipalEmbeddedCertPassword property: Specify the password of your certificate if your + * certificate has a password and you are using AadServicePrincipal authentication. Type: string (or Expression with + * resultType string). + * + * @return the servicePrincipalEmbeddedCertPassword value. + */ + public SecretBase getServicePrincipalEmbeddedCertPassword() { + return this.servicePrincipalEmbeddedCertPassword; + } + + /** + * Set the servicePrincipalEmbeddedCertPassword property: Specify the password of your certificate if your + * certificate has a password and you are using AadServicePrincipal authentication. Type: string (or Expression with + * resultType string). + * + * @param servicePrincipalEmbeddedCertPassword the servicePrincipalEmbeddedCertPassword value to set. + * @return the RestServiceLinkedService object itself. + */ + public RestServiceLinkedService + setServicePrincipalEmbeddedCertPassword(SecretBase servicePrincipalEmbeddedCertPassword) { + this.servicePrincipalEmbeddedCertPassword = servicePrincipalEmbeddedCertPassword; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public RestServiceLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -560,6 +658,7 @@ public RestServiceLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -582,7 +681,10 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { || clientSecret != null || tokenEndpoint != null || resource != null - || scope != null) { + || scope != null + || servicePrincipalCredentialType != null + || servicePrincipalEmbeddedCert != null + || servicePrincipalEmbeddedCertPassword != null) { jsonWriter.writeStartObject("typeProperties"); jsonWriter.writeUntypedField("url", this.url); jsonWriter.writeUntypedField("enableServerCertificateValidation", this.enableServerCertificateValidation); @@ -603,6 +705,10 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeUntypedField("tokenEndpoint", this.tokenEndpoint); jsonWriter.writeUntypedField("resource", this.resource); jsonWriter.writeUntypedField("scope", this.scope); + jsonWriter.writeUntypedField("servicePrincipalCredentialType", this.servicePrincipalCredentialType); + jsonWriter.writeJsonField("servicePrincipalEmbeddedCert", this.servicePrincipalEmbeddedCert); + jsonWriter.writeJsonField("servicePrincipalEmbeddedCertPassword", + this.servicePrincipalEmbeddedCertPassword); jsonWriter.writeEndObject(); } if (getAdditionalProperties() != null) { @@ -630,7 +736,9 @@ public static RestServiceLinkedService fromJson(JsonReader jsonReader) throws IO String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedRestServiceLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedRestServiceLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedRestServiceLinkedService.setDescription(reader.getString()); @@ -686,6 +794,14 @@ public static RestServiceLinkedService fromJson(JsonReader jsonReader) throws IO deserializedRestServiceLinkedService.resource = reader.readUntyped(); } else if ("scope".equals(fieldName)) { deserializedRestServiceLinkedService.scope = reader.readUntyped(); + } else if ("servicePrincipalCredentialType".equals(fieldName)) { + deserializedRestServiceLinkedService.servicePrincipalCredentialType = reader.readUntyped(); + } else if ("servicePrincipalEmbeddedCert".equals(fieldName)) { + deserializedRestServiceLinkedService.servicePrincipalEmbeddedCert + = SecretBase.fromJson(reader); + } else if ("servicePrincipalEmbeddedCertPassword".equals(fieldName)) { + deserializedRestServiceLinkedService.servicePrincipalEmbeddedCertPassword + = SecretBase.fromJson(reader); } else { reader.skipChildren(); } diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SalesforceLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SalesforceLinkedService.java index 117759ce0662..4ff587bf03d8 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SalesforceLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SalesforceLinkedService.java @@ -203,6 +203,15 @@ public SalesforceLinkedService setEncryptedCredential(Object encryptedCredential return this; } + /** + * {@inheritDoc} + */ + @Override + public SalesforceLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -245,6 +254,7 @@ public SalesforceLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -289,7 +299,9 @@ public static SalesforceLinkedService fromJson(JsonReader jsonReader) throws IOE String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedSalesforceLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedSalesforceLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedSalesforceLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SalesforceMarketingCloudLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SalesforceMarketingCloudLinkedService.java index 62953b8e9a66..0916a3a5f80c 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SalesforceMarketingCloudLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SalesforceMarketingCloudLinkedService.java @@ -237,6 +237,15 @@ public SalesforceMarketingCloudLinkedService setEncryptedCredential(Object encry return this; } + /** + * {@inheritDoc} + */ + @Override + public SalesforceMarketingCloudLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -279,6 +288,7 @@ public SalesforceMarketingCloudLinkedService setAnnotations(List annotat @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -327,7 +337,9 @@ public static SalesforceMarketingCloudLinkedService fromJson(JsonReader jsonRead String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedSalesforceMarketingCloudLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedSalesforceMarketingCloudLinkedService .setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SalesforceServiceCloudLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SalesforceServiceCloudLinkedService.java index f3e4d5d45391..6ec61c11e160 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SalesforceServiceCloudLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SalesforceServiceCloudLinkedService.java @@ -232,6 +232,15 @@ public SalesforceServiceCloudLinkedService setEncryptedCredential(Object encrypt return this; } + /** + * {@inheritDoc} + */ + @Override + public SalesforceServiceCloudLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -274,6 +283,7 @@ public SalesforceServiceCloudLinkedService setAnnotations(List annotatio @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -321,7 +331,9 @@ public static SalesforceServiceCloudLinkedService fromJson(JsonReader jsonReader String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedSalesforceServiceCloudLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedSalesforceServiceCloudLinkedService .setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SalesforceServiceCloudV2LinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SalesforceServiceCloudV2LinkedService.java index b1c2e2fba81b..e20bc2c6a242 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SalesforceServiceCloudV2LinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SalesforceServiceCloudV2LinkedService.java @@ -206,6 +206,15 @@ public SalesforceServiceCloudV2LinkedService setEncryptedCredential(String encry return this; } + /** + * {@inheritDoc} + */ + @Override + public SalesforceServiceCloudV2LinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -248,6 +257,7 @@ public SalesforceServiceCloudV2LinkedService setAnnotations(List annotat @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -293,7 +303,9 @@ public static SalesforceServiceCloudV2LinkedService fromJson(JsonReader jsonRead String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedSalesforceServiceCloudV2LinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedSalesforceServiceCloudV2LinkedService .setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SalesforceServiceCloudV2Source.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SalesforceServiceCloudV2Source.java index 9155408c38ed..2219c5acbb5f 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SalesforceServiceCloudV2Source.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SalesforceServiceCloudV2Source.java @@ -23,10 +23,19 @@ public final class SalesforceServiceCloudV2Source extends CopySource { private String type = "SalesforceServiceCloudV2Source"; /* - * Database query. Type: string (or Expression with resultType string). + * Deprecating, please use 'query' property instead. Type: string (or Expression with resultType string). */ private Object soqlQuery; + /* + * You can only use Salesforce Object Query Language (SOQL) query with limitations. For SOQL limitations, see this + * article: + * https://developer.salesforce.com/docs/atlas.en-us.api_asynch.meta/api_asynch/queries.htm#SOQL%20Considerations. + * If query is not specified, all the data of the Salesforce object specified in ObjectApiName/reportId in dataset + * will be retrieved. Type: string (or Expression with resultType string). + */ + private Object query; + /* * This property control whether query result contains Deleted objects. Default is false. Type: boolean (or * Expression with resultType boolean). @@ -56,7 +65,8 @@ public String getType() { } /** - * Get the soqlQuery property: Database query. Type: string (or Expression with resultType string). + * Get the soqlQuery property: Deprecating, please use 'query' property instead. Type: string (or Expression with + * resultType string). * * @return the soqlQuery value. */ @@ -65,7 +75,8 @@ public Object getSoqlQuery() { } /** - * Set the soqlQuery property: Database query. Type: string (or Expression with resultType string). + * Set the soqlQuery property: Deprecating, please use 'query' property instead. Type: string (or Expression with + * resultType string). * * @param soqlQuery the soqlQuery value to set. * @return the SalesforceServiceCloudV2Source object itself. @@ -75,6 +86,34 @@ public SalesforceServiceCloudV2Source setSoqlQuery(Object soqlQuery) { return this; } + /** + * Get the query property: You can only use Salesforce Object Query Language (SOQL) query with limitations. For SOQL + * limitations, see this article: + * https://developer.salesforce.com/docs/atlas.en-us.api_asynch.meta/api_asynch/queries.htm#SOQL%20Considerations. + * If query is not specified, all the data of the Salesforce object specified in ObjectApiName/reportId in dataset + * will be retrieved. Type: string (or Expression with resultType string). + * + * @return the query value. + */ + public Object getQuery() { + return this.query; + } + + /** + * Set the query property: You can only use Salesforce Object Query Language (SOQL) query with limitations. For SOQL + * limitations, see this article: + * https://developer.salesforce.com/docs/atlas.en-us.api_asynch.meta/api_asynch/queries.htm#SOQL%20Considerations. + * If query is not specified, all the data of the Salesforce object specified in ObjectApiName/reportId in dataset + * will be retrieved. Type: string (or Expression with resultType string). + * + * @param query the query value to set. + * @return the SalesforceServiceCloudV2Source object itself. + */ + public SalesforceServiceCloudV2Source setQuery(Object query) { + this.query = query; + return this; + } + /** * Get the includeDeletedObjects property: This property control whether query result contains Deleted objects. * Default is false. Type: boolean (or Expression with resultType boolean). @@ -157,6 +196,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeUntypedField("maxConcurrentConnections", getMaxConcurrentConnections()); jsonWriter.writeStringField("type", this.type); jsonWriter.writeUntypedField("SOQLQuery", this.soqlQuery); + jsonWriter.writeUntypedField("query", this.query); jsonWriter.writeUntypedField("includeDeletedObjects", this.includeDeletedObjects); jsonWriter.writeUntypedField("additionalColumns", this.additionalColumns); if (getAdditionalProperties() != null) { @@ -194,6 +234,8 @@ public static SalesforceServiceCloudV2Source fromJson(JsonReader jsonReader) thr deserializedSalesforceServiceCloudV2Source.type = reader.getString(); } else if ("SOQLQuery".equals(fieldName)) { deserializedSalesforceServiceCloudV2Source.soqlQuery = reader.readUntyped(); + } else if ("query".equals(fieldName)) { + deserializedSalesforceServiceCloudV2Source.query = reader.readUntyped(); } else if ("includeDeletedObjects".equals(fieldName)) { deserializedSalesforceServiceCloudV2Source.includeDeletedObjects = reader.readUntyped(); } else if ("additionalColumns".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SalesforceV2LinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SalesforceV2LinkedService.java index e869a2bda11d..e63cf6b031c7 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SalesforceV2LinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SalesforceV2LinkedService.java @@ -206,6 +206,15 @@ public SalesforceV2LinkedService setEncryptedCredential(String encryptedCredenti return this; } + /** + * {@inheritDoc} + */ + @Override + public SalesforceV2LinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -248,6 +257,7 @@ public SalesforceV2LinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -292,7 +302,9 @@ public static SalesforceV2LinkedService fromJson(JsonReader jsonReader) throws I String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedSalesforceV2LinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedSalesforceV2LinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedSalesforceV2LinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SalesforceV2Source.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SalesforceV2Source.java index fe488cb2b552..01de6f238dc4 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SalesforceV2Source.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SalesforceV2Source.java @@ -23,16 +23,31 @@ public final class SalesforceV2Source extends TabularSource { private String type = "SalesforceV2Source"; /* - * Database query. Type: string (or Expression with resultType string). + * Deprecating, please use 'query' property instead. Type: string (or Expression with resultType string). */ private Object soqlQuery; + /* + * You can only use Salesforce Object Query Language (SOQL) query with limitations. For SOQL limitations, see this + * article: + * https://developer.salesforce.com/docs/atlas.en-us.api_asynch.meta/api_asynch/queries.htm#SOQL%20Considerations. + * If query is not specified, all the data of the Salesforce object specified in ObjectApiName/reportId in dataset + * will be retrieved. Type: string (or Expression with resultType string). + */ + private Object query; + /* * This property control whether query result contains Deleted objects. Default is false. Type: boolean (or * Expression with resultType boolean). */ private Object includeDeletedObjects; + /* + * Page size for each http request, too large pageSize will caused timeout, default 300,000. Type: integer (or + * Expression with resultType integer). + */ + private Object pageSize; + /** * Creates an instance of SalesforceV2Source class. */ @@ -50,7 +65,8 @@ public String getType() { } /** - * Get the soqlQuery property: Database query. Type: string (or Expression with resultType string). + * Get the soqlQuery property: Deprecating, please use 'query' property instead. Type: string (or Expression with + * resultType string). * * @return the soqlQuery value. */ @@ -59,7 +75,8 @@ public Object getSoqlQuery() { } /** - * Set the soqlQuery property: Database query. Type: string (or Expression with resultType string). + * Set the soqlQuery property: Deprecating, please use 'query' property instead. Type: string (or Expression with + * resultType string). * * @param soqlQuery the soqlQuery value to set. * @return the SalesforceV2Source object itself. @@ -69,6 +86,34 @@ public SalesforceV2Source setSoqlQuery(Object soqlQuery) { return this; } + /** + * Get the query property: You can only use Salesforce Object Query Language (SOQL) query with limitations. For SOQL + * limitations, see this article: + * https://developer.salesforce.com/docs/atlas.en-us.api_asynch.meta/api_asynch/queries.htm#SOQL%20Considerations. + * If query is not specified, all the data of the Salesforce object specified in ObjectApiName/reportId in dataset + * will be retrieved. Type: string (or Expression with resultType string). + * + * @return the query value. + */ + public Object getQuery() { + return this.query; + } + + /** + * Set the query property: You can only use Salesforce Object Query Language (SOQL) query with limitations. For SOQL + * limitations, see this article: + * https://developer.salesforce.com/docs/atlas.en-us.api_asynch.meta/api_asynch/queries.htm#SOQL%20Considerations. + * If query is not specified, all the data of the Salesforce object specified in ObjectApiName/reportId in dataset + * will be retrieved. Type: string (or Expression with resultType string). + * + * @param query the query value to set. + * @return the SalesforceV2Source object itself. + */ + public SalesforceV2Source setQuery(Object query) { + this.query = query; + return this; + } + /** * Get the includeDeletedObjects property: This property control whether query result contains Deleted objects. * Default is false. Type: boolean (or Expression with resultType boolean). @@ -91,6 +136,28 @@ public SalesforceV2Source setIncludeDeletedObjects(Object includeDeletedObjects) return this; } + /** + * Get the pageSize property: Page size for each http request, too large pageSize will caused timeout, default + * 300,000. Type: integer (or Expression with resultType integer). + * + * @return the pageSize value. + */ + public Object getPageSize() { + return this.pageSize; + } + + /** + * Set the pageSize property: Page size for each http request, too large pageSize will caused timeout, default + * 300,000. Type: integer (or Expression with resultType integer). + * + * @param pageSize the pageSize value to set. + * @return the SalesforceV2Source object itself. + */ + public SalesforceV2Source setPageSize(Object pageSize) { + this.pageSize = pageSize; + return this; + } + /** * {@inheritDoc} */ @@ -149,7 +216,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeUntypedField("additionalColumns", getAdditionalColumns()); jsonWriter.writeStringField("type", this.type); jsonWriter.writeUntypedField("SOQLQuery", this.soqlQuery); + jsonWriter.writeUntypedField("query", this.query); jsonWriter.writeUntypedField("includeDeletedObjects", this.includeDeletedObjects); + jsonWriter.writeUntypedField("pageSize", this.pageSize); if (getAdditionalProperties() != null) { for (Map.Entry additionalProperty : getAdditionalProperties().entrySet()) { jsonWriter.writeUntypedField(additionalProperty.getKey(), additionalProperty.getValue()); @@ -188,8 +257,12 @@ public static SalesforceV2Source fromJson(JsonReader jsonReader) throws IOExcept deserializedSalesforceV2Source.type = reader.getString(); } else if ("SOQLQuery".equals(fieldName)) { deserializedSalesforceV2Source.soqlQuery = reader.readUntyped(); + } else if ("query".equals(fieldName)) { + deserializedSalesforceV2Source.query = reader.readUntyped(); } else if ("includeDeletedObjects".equals(fieldName)) { deserializedSalesforceV2Source.includeDeletedObjects = reader.readUntyped(); + } else if ("pageSize".equals(fieldName)) { + deserializedSalesforceV2Source.pageSize = reader.readUntyped(); } else { if (additionalProperties == null) { additionalProperties = new LinkedHashMap<>(); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SapBWLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SapBWLinkedService.java index d2d4b79b81fb..5887ba8d00bb 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SapBWLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SapBWLinkedService.java @@ -200,6 +200,15 @@ public SapBWLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public SapBWLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -242,6 +251,7 @@ public SapBWLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -287,7 +297,9 @@ public static SapBWLinkedService fromJson(JsonReader jsonReader) throws IOExcept String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedSapBWLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedSapBWLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedSapBWLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SapCloudForCustomerLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SapCloudForCustomerLinkedService.java index afc64060f89a..74a4a90b9d38 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SapCloudForCustomerLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SapCloudForCustomerLinkedService.java @@ -150,6 +150,15 @@ public SapCloudForCustomerLinkedService setEncryptedCredential(Object encryptedC return this; } + /** + * {@inheritDoc} + */ + @Override + public SapCloudForCustomerLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -192,6 +201,7 @@ public SapCloudForCustomerLinkedService setAnnotations(List annotations) @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -231,7 +241,9 @@ public static SapCloudForCustomerLinkedService fromJson(JsonReader jsonReader) t String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedSapCloudForCustomerLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedSapCloudForCustomerLinkedService .setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SapEccLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SapEccLinkedService.java index ed60bfd26516..448ed3ee2032 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SapEccLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SapEccLinkedService.java @@ -150,6 +150,15 @@ public SapEccLinkedService setEncryptedCredential(String encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public SapEccLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -192,6 +201,7 @@ public SapEccLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -230,7 +240,9 @@ public static SapEccLinkedService fromJson(JsonReader jsonReader) throws IOExcep String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedSapEccLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedSapEccLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedSapEccLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SapHanaLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SapHanaLinkedService.java index d6e9ebb82a6a..417199be7139 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SapHanaLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SapHanaLinkedService.java @@ -196,6 +196,15 @@ public SapHanaLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public SapHanaLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -238,6 +247,7 @@ public SapHanaLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -284,7 +294,9 @@ public static SapHanaLinkedService fromJson(JsonReader jsonReader) throws IOExce String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedSapHanaLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedSapHanaLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedSapHanaLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SapOdpLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SapOdpLinkedService.java index 0aafeb26544c..40fb45186907 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SapOdpLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SapOdpLinkedService.java @@ -73,8 +73,8 @@ public class SapOdpLinkedService extends LinkedService { private Object messageServerService; /* - * SNC activation indicator to access the SAP server where the table is located. Must be either 0 (off) or 1 (on). - * Type: string (or Expression with resultType string). + * SNC activation flag (Boolean) to access the SAP server where the table is located. Type: boolean (or Expression + * with resultType boolean). */ private Object sncMode; @@ -336,8 +336,8 @@ public SapOdpLinkedService setMessageServerService(Object messageServerService) } /** - * Get the sncMode property: SNC activation indicator to access the SAP server where the table is located. Must be - * either 0 (off) or 1 (on). Type: string (or Expression with resultType string). + * Get the sncMode property: SNC activation flag (Boolean) to access the SAP server where the table is located. + * Type: boolean (or Expression with resultType boolean). * * @return the sncMode value. */ @@ -346,8 +346,8 @@ public Object getSncMode() { } /** - * Set the sncMode property: SNC activation indicator to access the SAP server where the table is located. Must be - * either 0 (off) or 1 (on). Type: string (or Expression with resultType string). + * Set the sncMode property: SNC activation flag (Boolean) to access the SAP server where the table is located. + * Type: boolean (or Expression with resultType boolean). * * @param sncMode the sncMode value to set. * @return the SapOdpLinkedService object itself. @@ -531,6 +531,15 @@ public SapOdpLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public SapOdpLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -573,6 +582,7 @@ public SapOdpLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -641,7 +651,9 @@ public static SapOdpLinkedService fromJson(JsonReader jsonReader) throws IOExcep String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedSapOdpLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedSapOdpLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedSapOdpLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SapOpenHubLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SapOpenHubLinkedService.java index 49f4e8d8fa6f..327b6455e7b3 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SapOpenHubLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SapOpenHubLinkedService.java @@ -342,6 +342,15 @@ public SapOpenHubLinkedService setEncryptedCredential(Object encryptedCredential return this; } + /** + * {@inheritDoc} + */ + @Override + public SapOpenHubLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -384,6 +393,7 @@ public SapOpenHubLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -439,7 +449,9 @@ public static SapOpenHubLinkedService fromJson(JsonReader jsonReader) throws IOE String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedSapOpenHubLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedSapOpenHubLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedSapOpenHubLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SapTableLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SapTableLinkedService.java index 7a2a71a63155..960d29e2c856 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SapTableLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SapTableLinkedService.java @@ -73,8 +73,8 @@ public class SapTableLinkedService extends LinkedService { private Object messageServerService; /* - * SNC activation indicator to access the SAP server where the table is located. Must be either 0 (off) or 1 (on). - * Type: string (or Expression with resultType string). + * SNC activation flag (Boolean) to access the SAP server where the table is located. Type: boolean (or Expression + * with resultType boolean). */ private Object sncMode; @@ -326,8 +326,8 @@ public SapTableLinkedService setMessageServerService(Object messageServerService } /** - * Get the sncMode property: SNC activation indicator to access the SAP server where the table is located. Must be - * either 0 (off) or 1 (on). Type: string (or Expression with resultType string). + * Get the sncMode property: SNC activation flag (Boolean) to access the SAP server where the table is located. + * Type: boolean (or Expression with resultType boolean). * * @return the sncMode value. */ @@ -336,8 +336,8 @@ public Object getSncMode() { } /** - * Set the sncMode property: SNC activation indicator to access the SAP server where the table is located. Must be - * either 0 (off) or 1 (on). Type: string (or Expression with resultType string). + * Set the sncMode property: SNC activation flag (Boolean) to access the SAP server where the table is located. + * Type: boolean (or Expression with resultType boolean). * * @param sncMode the sncMode value to set. * @return the SapTableLinkedService object itself. @@ -479,6 +479,15 @@ public SapTableLinkedService setEncryptedCredential(Object encryptedCredential) return this; } + /** + * {@inheritDoc} + */ + @Override + public SapTableLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -521,6 +530,7 @@ public SapTableLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -585,7 +595,9 @@ public static SapTableLinkedService fromJson(JsonReader jsonReader) throws IOExc String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedSapTableLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedSapTableLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedSapTableLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ScheduleTrigger.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ScheduleTrigger.java index 0ecd3378ce18..c8b3c99edae6 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ScheduleTrigger.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ScheduleTrigger.java @@ -28,11 +28,6 @@ public class ScheduleTrigger extends MultiplePipelineTrigger { */ private ScheduleTriggerRecurrence recurrence; - /* - * Indicates if trigger is running or not. Updated when Start/Stop APIs are called on the Trigger. - */ - private TriggerRuntimeState runtimeState; - /** * Creates an instance of ScheduleTrigger class. */ @@ -69,17 +64,6 @@ public ScheduleTrigger setRecurrence(ScheduleTriggerRecurrence recurrence) { return this; } - /** - * Get the runtimeState property: Indicates if trigger is running or not. Updated when Start/Stop APIs are called on - * the Trigger. - * - * @return the runtimeState value. - */ - @Override - public TriggerRuntimeState getRuntimeState() { - return this.runtimeState; - } - /** * {@inheritDoc} */ @@ -150,7 +134,7 @@ public static ScheduleTrigger fromJson(JsonReader jsonReader) throws IOException if ("description".equals(fieldName)) { deserializedScheduleTrigger.setDescription(reader.getString()); } else if ("runtimeState".equals(fieldName)) { - deserializedScheduleTrigger.runtimeState = TriggerRuntimeState.fromString(reader.getString()); + deserializedScheduleTrigger.setRuntimeState(TriggerRuntimeState.fromString(reader.getString())); } else if ("annotations".equals(fieldName)) { List annotations = reader.readArray(reader1 -> reader1.readUntyped()); deserializedScheduleTrigger.setAnnotations(annotations); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ScriptActivity.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ScriptActivity.java index 4bc646bc63fb..f218d8c04cd6 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ScriptActivity.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ScriptActivity.java @@ -39,6 +39,12 @@ public class ScriptActivity extends ExecutionActivity { */ private ScriptActivityTypePropertiesLogSettings logSettings; + /* + * Enable to retrieve result sets from multiple SQL statements and the number of rows affected by the DML statement. + * Supported connector: SnowflakeV2. Type: boolean (or Expression with resultType boolean). + */ + private Object returnMultistatementResult; + /** * Creates an instance of ScriptActivity class. */ @@ -117,6 +123,30 @@ public ScriptActivity setLogSettings(ScriptActivityTypePropertiesLogSettings log return this; } + /** + * Get the returnMultistatementResult property: Enable to retrieve result sets from multiple SQL statements and the + * number of rows affected by the DML statement. Supported connector: SnowflakeV2. Type: boolean (or Expression with + * resultType boolean). + * + * @return the returnMultistatementResult value. + */ + public Object getReturnMultistatementResult() { + return this.returnMultistatementResult; + } + + /** + * Set the returnMultistatementResult property: Enable to retrieve result sets from multiple SQL statements and the + * number of rows affected by the DML statement. Supported connector: SnowflakeV2. Type: boolean (or Expression with + * resultType boolean). + * + * @param returnMultistatementResult the returnMultistatementResult value to set. + * @return the ScriptActivity object itself. + */ + public ScriptActivity setReturnMultistatementResult(Object returnMultistatementResult) { + this.returnMultistatementResult = returnMultistatementResult; + return this; + } + /** * {@inheritDoc} */ @@ -206,11 +236,15 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeJsonField("linkedServiceName", getLinkedServiceName()); jsonWriter.writeJsonField("policy", getPolicy()); jsonWriter.writeStringField("type", this.type); - if (scriptBlockExecutionTimeout != null || scripts != null || logSettings != null) { + if (scriptBlockExecutionTimeout != null + || scripts != null + || logSettings != null + || returnMultistatementResult != null) { jsonWriter.writeStartObject("typeProperties"); jsonWriter.writeUntypedField("scriptBlockExecutionTimeout", this.scriptBlockExecutionTimeout); jsonWriter.writeArrayField("scripts", this.scripts, (writer, element) -> writer.writeJson(element)); jsonWriter.writeJsonField("logSettings", this.logSettings); + jsonWriter.writeUntypedField("returnMultistatementResult", this.returnMultistatementResult); jsonWriter.writeEndObject(); } if (getAdditionalProperties() != null) { @@ -274,6 +308,8 @@ public static ScriptActivity fromJson(JsonReader jsonReader) throws IOException } else if ("logSettings".equals(fieldName)) { deserializedScriptActivity.logSettings = ScriptActivityTypePropertiesLogSettings.fromJson(reader); + } else if ("returnMultistatementResult".equals(fieldName)) { + deserializedScriptActivity.returnMultistatementResult = reader.readUntyped(); } else { reader.skipChildren(); } diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ServiceNowLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ServiceNowLinkedService.java index f3c24a44e62d..a2788179683a 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ServiceNowLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ServiceNowLinkedService.java @@ -301,6 +301,15 @@ public ServiceNowLinkedService setEncryptedCredential(Object encryptedCredential return this; } + /** + * {@inheritDoc} + */ + @Override + public ServiceNowLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -343,6 +352,7 @@ public ServiceNowLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -397,7 +407,9 @@ public static ServiceNowLinkedService fromJson(JsonReader jsonReader) throws IOE String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedServiceNowLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedServiceNowLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedServiceNowLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ServiceNowV2Source.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ServiceNowV2Source.java index c7f97f4cdc29..93434daa5d4f 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ServiceNowV2Source.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ServiceNowV2Source.java @@ -27,6 +27,11 @@ public final class ServiceNowV2Source extends TabularSource { */ private ExpressionV2 expression; + /* + * Page size of the result. Type: integer (or Expression with resultType integer). + */ + private Object pageSize; + /** * Creates an instance of ServiceNowV2Source class. */ @@ -63,6 +68,26 @@ public ServiceNowV2Source setExpression(ExpressionV2 expression) { return this; } + /** + * Get the pageSize property: Page size of the result. Type: integer (or Expression with resultType integer). + * + * @return the pageSize value. + */ + public Object getPageSize() { + return this.pageSize; + } + + /** + * Set the pageSize property: Page size of the result. Type: integer (or Expression with resultType integer). + * + * @param pageSize the pageSize value to set. + * @return the ServiceNowV2Source object itself. + */ + public ServiceNowV2Source setPageSize(Object pageSize) { + this.pageSize = pageSize; + return this; + } + /** * {@inheritDoc} */ @@ -121,6 +146,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeUntypedField("additionalColumns", getAdditionalColumns()); jsonWriter.writeStringField("type", this.type); jsonWriter.writeJsonField("expression", this.expression); + jsonWriter.writeUntypedField("pageSize", this.pageSize); if (getAdditionalProperties() != null) { for (Map.Entry additionalProperty : getAdditionalProperties().entrySet()) { jsonWriter.writeUntypedField(additionalProperty.getKey(), additionalProperty.getValue()); @@ -159,6 +185,8 @@ public static ServiceNowV2Source fromJson(JsonReader jsonReader) throws IOExcept deserializedServiceNowV2Source.type = reader.getString(); } else if ("expression".equals(fieldName)) { deserializedServiceNowV2Source.expression = ExpressionV2.fromJson(reader); + } else if ("pageSize".equals(fieldName)) { + deserializedServiceNowV2Source.pageSize = reader.readUntyped(); } else { if (additionalProperties == null) { additionalProperties = new LinkedHashMap<>(); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SftpServerLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SftpServerLinkedService.java index d24b92fbfc32..521e7d75cab8 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SftpServerLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SftpServerLinkedService.java @@ -342,6 +342,15 @@ public SftpServerLinkedService setHostKeyFingerprint(Object hostKeyFingerprint) return this; } + /** + * {@inheritDoc} + */ + @Override + public SftpServerLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -384,6 +393,7 @@ public SftpServerLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -440,7 +450,9 @@ public static SftpServerLinkedService fromJson(JsonReader jsonReader) throws IOE String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedSftpServerLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedSftpServerLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedSftpServerLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SharePointOnlineListLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SharePointOnlineListLinkedService.java index ad87d66afe9e..c313a3a3fa6b 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SharePointOnlineListLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SharePointOnlineListLinkedService.java @@ -47,6 +47,24 @@ public class SharePointOnlineListLinkedService extends LinkedService { */ private SecretBase servicePrincipalKey; + /* + * The service principal credential type to use in Server-To-Server authentication. 'ServicePrincipalKey' for + * key/secret, 'ServicePrincipalCert' for certificate. Type: string (or Expression with resultType string). + */ + private Object servicePrincipalCredentialType; + + /* + * Specify the base64 encoded certificate of your application registered in Azure Active Directory. Type: string (or + * Expression with resultType string). + */ + private SecretBase servicePrincipalEmbeddedCert; + + /* + * Specify the password of your certificate if your certificate has a password and you are using AadServicePrincipal + * authentication. Type: string (or Expression with resultType string). + */ + private SecretBase servicePrincipalEmbeddedCertPassword; + /* * The encrypted credential used for authentication. Credentials are encrypted using the integration runtime * credential manager. Type: string (or Expression with resultType string). @@ -159,6 +177,77 @@ public SharePointOnlineListLinkedService setServicePrincipalKey(SecretBase servi return this; } + /** + * Get the servicePrincipalCredentialType property: The service principal credential type to use in Server-To-Server + * authentication. 'ServicePrincipalKey' for key/secret, 'ServicePrincipalCert' for certificate. Type: string (or + * Expression with resultType string). + * + * @return the servicePrincipalCredentialType value. + */ + public Object getServicePrincipalCredentialType() { + return this.servicePrincipalCredentialType; + } + + /** + * Set the servicePrincipalCredentialType property: The service principal credential type to use in Server-To-Server + * authentication. 'ServicePrincipalKey' for key/secret, 'ServicePrincipalCert' for certificate. Type: string (or + * Expression with resultType string). + * + * @param servicePrincipalCredentialType the servicePrincipalCredentialType value to set. + * @return the SharePointOnlineListLinkedService object itself. + */ + public SharePointOnlineListLinkedService setServicePrincipalCredentialType(Object servicePrincipalCredentialType) { + this.servicePrincipalCredentialType = servicePrincipalCredentialType; + return this; + } + + /** + * Get the servicePrincipalEmbeddedCert property: Specify the base64 encoded certificate of your application + * registered in Azure Active Directory. Type: string (or Expression with resultType string). + * + * @return the servicePrincipalEmbeddedCert value. + */ + public SecretBase getServicePrincipalEmbeddedCert() { + return this.servicePrincipalEmbeddedCert; + } + + /** + * Set the servicePrincipalEmbeddedCert property: Specify the base64 encoded certificate of your application + * registered in Azure Active Directory. Type: string (or Expression with resultType string). + * + * @param servicePrincipalEmbeddedCert the servicePrincipalEmbeddedCert value to set. + * @return the SharePointOnlineListLinkedService object itself. + */ + public SharePointOnlineListLinkedService setServicePrincipalEmbeddedCert(SecretBase servicePrincipalEmbeddedCert) { + this.servicePrincipalEmbeddedCert = servicePrincipalEmbeddedCert; + return this; + } + + /** + * Get the servicePrincipalEmbeddedCertPassword property: Specify the password of your certificate if your + * certificate has a password and you are using AadServicePrincipal authentication. Type: string (or Expression with + * resultType string). + * + * @return the servicePrincipalEmbeddedCertPassword value. + */ + public SecretBase getServicePrincipalEmbeddedCertPassword() { + return this.servicePrincipalEmbeddedCertPassword; + } + + /** + * Set the servicePrincipalEmbeddedCertPassword property: Specify the password of your certificate if your + * certificate has a password and you are using AadServicePrincipal authentication. Type: string (or Expression with + * resultType string). + * + * @param servicePrincipalEmbeddedCertPassword the servicePrincipalEmbeddedCertPassword value to set. + * @return the SharePointOnlineListLinkedService object itself. + */ + public SharePointOnlineListLinkedService + setServicePrincipalEmbeddedCertPassword(SecretBase servicePrincipalEmbeddedCertPassword) { + this.servicePrincipalEmbeddedCertPassword = servicePrincipalEmbeddedCertPassword; + return this; + } + /** * Get the encryptedCredential property: The encrypted credential used for authentication. Credentials are encrypted * using the integration runtime credential manager. Type: string (or Expression with resultType string). @@ -181,6 +270,15 @@ public SharePointOnlineListLinkedService setEncryptedCredential(Object encrypted return this; } + /** + * {@inheritDoc} + */ + @Override + public SharePointOnlineListLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -223,6 +321,7 @@ public SharePointOnlineListLinkedService setAnnotations(List annotations @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -232,12 +331,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { || tenantId != null || servicePrincipalId != null || servicePrincipalKey != null + || servicePrincipalCredentialType != null + || servicePrincipalEmbeddedCert != null + || servicePrincipalEmbeddedCertPassword != null || encryptedCredential != null) { jsonWriter.writeStartObject("typeProperties"); jsonWriter.writeUntypedField("siteUrl", this.siteUrl); jsonWriter.writeUntypedField("tenantId", this.tenantId); jsonWriter.writeUntypedField("servicePrincipalId", this.servicePrincipalId); jsonWriter.writeJsonField("servicePrincipalKey", this.servicePrincipalKey); + jsonWriter.writeUntypedField("servicePrincipalCredentialType", this.servicePrincipalCredentialType); + jsonWriter.writeJsonField("servicePrincipalEmbeddedCert", this.servicePrincipalEmbeddedCert); + jsonWriter.writeJsonField("servicePrincipalEmbeddedCertPassword", + this.servicePrincipalEmbeddedCertPassword); jsonWriter.writeUntypedField("encryptedCredential", this.encryptedCredential); jsonWriter.writeEndObject(); } @@ -267,7 +373,9 @@ public static SharePointOnlineListLinkedService fromJson(JsonReader jsonReader) String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedSharePointOnlineListLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedSharePointOnlineListLinkedService .setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { @@ -295,6 +403,15 @@ public static SharePointOnlineListLinkedService fromJson(JsonReader jsonReader) } else if ("servicePrincipalKey".equals(fieldName)) { deserializedSharePointOnlineListLinkedService.servicePrincipalKey = SecretBase.fromJson(reader); + } else if ("servicePrincipalCredentialType".equals(fieldName)) { + deserializedSharePointOnlineListLinkedService.servicePrincipalCredentialType + = reader.readUntyped(); + } else if ("servicePrincipalEmbeddedCert".equals(fieldName)) { + deserializedSharePointOnlineListLinkedService.servicePrincipalEmbeddedCert + = SecretBase.fromJson(reader); + } else if ("servicePrincipalEmbeddedCertPassword".equals(fieldName)) { + deserializedSharePointOnlineListLinkedService.servicePrincipalEmbeddedCertPassword + = SecretBase.fromJson(reader); } else if ("encryptedCredential".equals(fieldName)) { deserializedSharePointOnlineListLinkedService.encryptedCredential = reader.readUntyped(); } else { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ShopifyLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ShopifyLinkedService.java index f62fab0e6c83..a63d7eea5ed1 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ShopifyLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ShopifyLinkedService.java @@ -201,6 +201,15 @@ public ShopifyLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public ShopifyLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -243,6 +252,7 @@ public ShopifyLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -288,7 +298,9 @@ public static ShopifyLinkedService fromJson(JsonReader jsonReader) throws IOExce String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedShopifyLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedShopifyLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedShopifyLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SmartsheetLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SmartsheetLinkedService.java index 4fb75b04b1d9..8d6bed7f3a34 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SmartsheetLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SmartsheetLinkedService.java @@ -92,6 +92,15 @@ public SmartsheetLinkedService setEncryptedCredential(Object encryptedCredential return this; } + /** + * {@inheritDoc} + */ + @Override + public SmartsheetLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -134,6 +143,7 @@ public SmartsheetLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -170,7 +180,9 @@ public static SmartsheetLinkedService fromJson(JsonReader jsonReader) throws IOE String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedSmartsheetLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedSmartsheetLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedSmartsheetLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SnowflakeLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SnowflakeLinkedService.java index b7038752aac1..90a5d1f0ba35 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SnowflakeLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SnowflakeLinkedService.java @@ -117,6 +117,15 @@ public SnowflakeLinkedService setEncryptedCredential(Object encryptedCredential) return this; } + /** + * {@inheritDoc} + */ + @Override + public SnowflakeLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -159,6 +168,7 @@ public SnowflakeLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -196,7 +206,9 @@ public static SnowflakeLinkedService fromJson(JsonReader jsonReader) throws IOEx String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedSnowflakeLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedSnowflakeLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedSnowflakeLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SnowflakeV2LinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SnowflakeV2LinkedService.java index b2a059884744..6c854abc334b 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SnowflakeV2LinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SnowflakeV2LinkedService.java @@ -73,6 +73,11 @@ public class SnowflakeV2LinkedService extends LinkedService { */ private Object scope; + /* + * The host name of the Snowflake account. + */ + private Object host; + /* * The Azure key vault secret reference of privateKey for KeyPair auth. */ @@ -315,6 +320,26 @@ public SnowflakeV2LinkedService setScope(Object scope) { return this; } + /** + * Get the host property: The host name of the Snowflake account. + * + * @return the host value. + */ + public Object getHost() { + return this.host; + } + + /** + * Set the host property: The host name of the Snowflake account. + * + * @param host the host value to set. + * @return the SnowflakeV2LinkedService object itself. + */ + public SnowflakeV2LinkedService setHost(Object host) { + this.host = host; + return this; + } + /** * Get the privateKey property: The Azure key vault secret reference of privateKey for KeyPair auth. * @@ -379,6 +404,15 @@ public SnowflakeV2LinkedService setEncryptedCredential(String encryptedCredentia return this; } + /** + * {@inheritDoc} + */ + @Override + public SnowflakeV2LinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -421,6 +455,7 @@ public SnowflakeV2LinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -436,6 +471,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { || clientSecret != null || tenantId != null || scope != null + || host != null || privateKey != null || privateKeyPassphrase != null || encryptedCredential != null) { @@ -451,6 +487,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeJsonField("clientSecret", this.clientSecret); jsonWriter.writeUntypedField("tenantId", this.tenantId); jsonWriter.writeUntypedField("scope", this.scope); + jsonWriter.writeUntypedField("host", this.host); jsonWriter.writeJsonField("privateKey", this.privateKey); jsonWriter.writeJsonField("privateKeyPassphrase", this.privateKeyPassphrase); jsonWriter.writeStringField("encryptedCredential", this.encryptedCredential); @@ -481,7 +518,9 @@ public static SnowflakeV2LinkedService fromJson(JsonReader jsonReader) throws IO String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedSnowflakeV2LinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedSnowflakeV2LinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedSnowflakeV2LinkedService.setDescription(reader.getString()); @@ -520,6 +559,8 @@ public static SnowflakeV2LinkedService fromJson(JsonReader jsonReader) throws IO deserializedSnowflakeV2LinkedService.tenantId = reader.readUntyped(); } else if ("scope".equals(fieldName)) { deserializedSnowflakeV2LinkedService.scope = reader.readUntyped(); + } else if ("host".equals(fieldName)) { + deserializedSnowflakeV2LinkedService.host = reader.readUntyped(); } else if ("privateKey".equals(fieldName)) { deserializedSnowflakeV2LinkedService.privateKey = SecretBase.fromJson(reader); } else if ("privateKeyPassphrase".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SparkLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SparkLinkedService.java index 28333ea564b4..9cac7cfc79dc 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SparkLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SparkLinkedService.java @@ -408,6 +408,15 @@ public SparkLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public SparkLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -450,6 +459,7 @@ public SparkLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -513,7 +523,9 @@ public static SparkLinkedService fromJson(JsonReader jsonReader) throws IOExcept String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedSparkLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedSparkLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedSparkLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SqlServerAuthenticationType.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SqlServerAuthenticationType.java new file mode 100644 index 000000000000..9476646d6b9d --- /dev/null +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SqlServerAuthenticationType.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.analytics.synapse.artifacts.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The type used for authentication. Type: string. + */ +public final class SqlServerAuthenticationType extends ExpandableStringEnum { + /** + * Static value SQL for SqlServerAuthenticationType. + */ + public static final SqlServerAuthenticationType SQL = fromString("SQL"); + + /** + * Static value Windows for SqlServerAuthenticationType. + */ + public static final SqlServerAuthenticationType WINDOWS = fromString("Windows"); + + /** + * Static value UserAssignedManagedIdentity for SqlServerAuthenticationType. + */ + public static final SqlServerAuthenticationType USER_ASSIGNED_MANAGED_IDENTITY + = fromString("UserAssignedManagedIdentity"); + + /** + * Creates a new instance of SqlServerAuthenticationType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public SqlServerAuthenticationType() { + } + + /** + * Creates or finds a SqlServerAuthenticationType from its string representation. + * + * @param name a name to look for. + * @return the corresponding SqlServerAuthenticationType. + */ + public static SqlServerAuthenticationType fromString(String name) { + return fromString(name, SqlServerAuthenticationType.class); + } + + /** + * Gets known SqlServerAuthenticationType values. + * + * @return known SqlServerAuthenticationType values. + */ + public static Collection values() { + return values(SqlServerAuthenticationType.class); + } +} diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SqlServerBaseLinkedServiceTypeProperties.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SqlServerBaseLinkedServiceTypeProperties.java new file mode 100644 index 000000000000..0ec929107f98 --- /dev/null +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SqlServerBaseLinkedServiceTypeProperties.java @@ -0,0 +1,677 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.analytics.synapse.artifacts.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; + +/** + * Sql Server family connector common linked service properties. + */ +@Fluent +public class SqlServerBaseLinkedServiceTypeProperties + implements JsonSerializable { + /* + * The name or network address of the instance of SQL Server to which to connect, used by recommended version. Type: + * string (or Expression with resultType string). + */ + private Object server; + + /* + * The name of the database, used by recommended version. Type: string (or Expression with resultType string). + */ + private Object database; + + /* + * Indicate whether TLS encryption is required for all data sent between the client and server, used by recommended + * version. Possible values are true/yes/mandatory, false/no/optional and strict. Type: string (or Expression with + * resultType string). + */ + private Object encrypt; + + /* + * Indicate whether the channel will be encrypted while bypassing walking the certificate chain to validate trust, + * used by recommended version. Type: Boolean (or Expression with resultType boolean). + */ + private Object trustServerCertificate; + + /* + * The host name to use when validating the server certificate for the connection. When not specified, the server + * name from the Data Source is used for certificate validation, used by recommended version. Type: string (or + * Expression with resultType string). + */ + private Object hostNameInCertificate; + + /* + * The application workload type when connecting to a server, used by recommended version. Possible values are + * ReadOnly and ReadWrite. Type: string (or Expression with resultType string). + */ + private Object applicationIntent; + + /* + * The length of time (in seconds) to wait for a connection to the server before terminating the attempt and + * generating an error, used by recommended version. Type: integer (or Expression with resultType integer). + */ + private Object connectTimeout; + + /* + * The number of re-connections attempted after identifying that there was an idle connection failure, used by + * recommended version. This must be an integer between 0 and 255. Type: integer (or Expression with resultType + * integer). + */ + private Object connectRetryCount; + + /* + * The amount of time (in seconds) between each re-connection attempt after identifying that there was an idle + * connection failure, used by recommended version. This must be an integer between 1 and 60. Type: integer (or + * Expression with resultType integer). + */ + private Object connectRetryInterval; + + /* + * The minimum time, in seconds, for the connection to live in the connection pool before being destroyed, used by + * recommended version. Type: integer (or Expression with resultType integer). + */ + private Object loadBalanceTimeout; + + /* + * The default wait time (in seconds) before terminating the attempt to execute a command and generating an error, + * used by recommended version. Type: integer (or Expression with resultType integer). + */ + private Object commandTimeout; + + /* + * Indicate whether User ID and Password are specified in the connection (when false) or whether the current Windows + * account credentials are used for authentication (when true), used by recommended version. Type: Boolean (or + * Expression with resultType boolean). + */ + private Object integratedSecurity; + + /* + * The name or address of the partner server to connect to if the primary server is down, used by recommended + * version. Type: string (or Expression with resultType string). + */ + private Object failoverPartner; + + /* + * The maximum number of connections allowed in the connection pool for this specific connection string, used by + * recommended version. Type: integer (or Expression with resultType integer). + */ + private Object maxPoolSize; + + /* + * The minimum number of connections allowed in the connection pool for this specific connection string, used by + * recommended version. Type: integer (or Expression with resultType integer). + */ + private Object minPoolSize; + + /* + * When true, an application can maintain multiple active result sets (MARS). When false, an application must + * process or cancel all result sets from one batch before it can execute any other batch on that connection. Type: + * Boolean (or Expression with resultType boolean). + */ + private Object multipleActiveResultSets; + + /* + * If your application is connecting to an AlwaysOn availability group (AG) on different subnets, setting + * MultiSubnetFailover=true provides faster detection of and connection to the (currently) active server, used by + * recommended version. Type: Boolean (or Expression with resultType boolean). + */ + private Object multiSubnetFailover; + + /* + * The size in bytes of the network packets used to communicate with an instance of server, used by recommended + * version. Type: integer (or Expression with resultType integer). + */ + private Object packetSize; + + /* + * Indicate whether the connection will be pooled or explicitly opened every time that the connection is requested, + * used by recommended version. Type: Boolean (or Expression with resultType boolean). + */ + private Object pooling; + + /** + * Creates an instance of SqlServerBaseLinkedServiceTypeProperties class. + */ + public SqlServerBaseLinkedServiceTypeProperties() { + } + + /** + * Get the server property: The name or network address of the instance of SQL Server to which to connect, used by + * recommended version. Type: string (or Expression with resultType string). + * + * @return the server value. + */ + public Object getServer() { + return this.server; + } + + /** + * Set the server property: The name or network address of the instance of SQL Server to which to connect, used by + * recommended version. Type: string (or Expression with resultType string). + * + * @param server the server value to set. + * @return the SqlServerBaseLinkedServiceTypeProperties object itself. + */ + public SqlServerBaseLinkedServiceTypeProperties setServer(Object server) { + this.server = server; + return this; + } + + /** + * Get the database property: The name of the database, used by recommended version. Type: string (or Expression + * with resultType string). + * + * @return the database value. + */ + public Object getDatabase() { + return this.database; + } + + /** + * Set the database property: The name of the database, used by recommended version. Type: string (or Expression + * with resultType string). + * + * @param database the database value to set. + * @return the SqlServerBaseLinkedServiceTypeProperties object itself. + */ + public SqlServerBaseLinkedServiceTypeProperties setDatabase(Object database) { + this.database = database; + return this; + } + + /** + * Get the encrypt property: Indicate whether TLS encryption is required for all data sent between the client and + * server, used by recommended version. Possible values are true/yes/mandatory, false/no/optional and strict. Type: + * string (or Expression with resultType string). + * + * @return the encrypt value. + */ + public Object getEncrypt() { + return this.encrypt; + } + + /** + * Set the encrypt property: Indicate whether TLS encryption is required for all data sent between the client and + * server, used by recommended version. Possible values are true/yes/mandatory, false/no/optional and strict. Type: + * string (or Expression with resultType string). + * + * @param encrypt the encrypt value to set. + * @return the SqlServerBaseLinkedServiceTypeProperties object itself. + */ + public SqlServerBaseLinkedServiceTypeProperties setEncrypt(Object encrypt) { + this.encrypt = encrypt; + return this; + } + + /** + * Get the trustServerCertificate property: Indicate whether the channel will be encrypted while bypassing walking + * the certificate chain to validate trust, used by recommended version. Type: Boolean (or Expression with + * resultType boolean). + * + * @return the trustServerCertificate value. + */ + public Object getTrustServerCertificate() { + return this.trustServerCertificate; + } + + /** + * Set the trustServerCertificate property: Indicate whether the channel will be encrypted while bypassing walking + * the certificate chain to validate trust, used by recommended version. Type: Boolean (or Expression with + * resultType boolean). + * + * @param trustServerCertificate the trustServerCertificate value to set. + * @return the SqlServerBaseLinkedServiceTypeProperties object itself. + */ + public SqlServerBaseLinkedServiceTypeProperties setTrustServerCertificate(Object trustServerCertificate) { + this.trustServerCertificate = trustServerCertificate; + return this; + } + + /** + * Get the hostNameInCertificate property: The host name to use when validating the server certificate for the + * connection. When not specified, the server name from the Data Source is used for certificate validation, used by + * recommended version. Type: string (or Expression with resultType string). + * + * @return the hostNameInCertificate value. + */ + public Object getHostNameInCertificate() { + return this.hostNameInCertificate; + } + + /** + * Set the hostNameInCertificate property: The host name to use when validating the server certificate for the + * connection. When not specified, the server name from the Data Source is used for certificate validation, used by + * recommended version. Type: string (or Expression with resultType string). + * + * @param hostNameInCertificate the hostNameInCertificate value to set. + * @return the SqlServerBaseLinkedServiceTypeProperties object itself. + */ + public SqlServerBaseLinkedServiceTypeProperties setHostNameInCertificate(Object hostNameInCertificate) { + this.hostNameInCertificate = hostNameInCertificate; + return this; + } + + /** + * Get the applicationIntent property: The application workload type when connecting to a server, used by + * recommended version. Possible values are ReadOnly and ReadWrite. Type: string (or Expression with resultType + * string). + * + * @return the applicationIntent value. + */ + public Object getApplicationIntent() { + return this.applicationIntent; + } + + /** + * Set the applicationIntent property: The application workload type when connecting to a server, used by + * recommended version. Possible values are ReadOnly and ReadWrite. Type: string (or Expression with resultType + * string). + * + * @param applicationIntent the applicationIntent value to set. + * @return the SqlServerBaseLinkedServiceTypeProperties object itself. + */ + public SqlServerBaseLinkedServiceTypeProperties setApplicationIntent(Object applicationIntent) { + this.applicationIntent = applicationIntent; + return this; + } + + /** + * Get the connectTimeout property: The length of time (in seconds) to wait for a connection to the server before + * terminating the attempt and generating an error, used by recommended version. Type: integer (or Expression with + * resultType integer). + * + * @return the connectTimeout value. + */ + public Object getConnectTimeout() { + return this.connectTimeout; + } + + /** + * Set the connectTimeout property: The length of time (in seconds) to wait for a connection to the server before + * terminating the attempt and generating an error, used by recommended version. Type: integer (or Expression with + * resultType integer). + * + * @param connectTimeout the connectTimeout value to set. + * @return the SqlServerBaseLinkedServiceTypeProperties object itself. + */ + public SqlServerBaseLinkedServiceTypeProperties setConnectTimeout(Object connectTimeout) { + this.connectTimeout = connectTimeout; + return this; + } + + /** + * Get the connectRetryCount property: The number of re-connections attempted after identifying that there was an + * idle connection failure, used by recommended version. This must be an integer between 0 and 255. Type: integer + * (or Expression with resultType integer). + * + * @return the connectRetryCount value. + */ + public Object getConnectRetryCount() { + return this.connectRetryCount; + } + + /** + * Set the connectRetryCount property: The number of re-connections attempted after identifying that there was an + * idle connection failure, used by recommended version. This must be an integer between 0 and 255. Type: integer + * (or Expression with resultType integer). + * + * @param connectRetryCount the connectRetryCount value to set. + * @return the SqlServerBaseLinkedServiceTypeProperties object itself. + */ + public SqlServerBaseLinkedServiceTypeProperties setConnectRetryCount(Object connectRetryCount) { + this.connectRetryCount = connectRetryCount; + return this; + } + + /** + * Get the connectRetryInterval property: The amount of time (in seconds) between each re-connection attempt after + * identifying that there was an idle connection failure, used by recommended version. This must be an integer + * between 1 and 60. Type: integer (or Expression with resultType integer). + * + * @return the connectRetryInterval value. + */ + public Object getConnectRetryInterval() { + return this.connectRetryInterval; + } + + /** + * Set the connectRetryInterval property: The amount of time (in seconds) between each re-connection attempt after + * identifying that there was an idle connection failure, used by recommended version. This must be an integer + * between 1 and 60. Type: integer (or Expression with resultType integer). + * + * @param connectRetryInterval the connectRetryInterval value to set. + * @return the SqlServerBaseLinkedServiceTypeProperties object itself. + */ + public SqlServerBaseLinkedServiceTypeProperties setConnectRetryInterval(Object connectRetryInterval) { + this.connectRetryInterval = connectRetryInterval; + return this; + } + + /** + * Get the loadBalanceTimeout property: The minimum time, in seconds, for the connection to live in the connection + * pool before being destroyed, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @return the loadBalanceTimeout value. + */ + public Object getLoadBalanceTimeout() { + return this.loadBalanceTimeout; + } + + /** + * Set the loadBalanceTimeout property: The minimum time, in seconds, for the connection to live in the connection + * pool before being destroyed, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @param loadBalanceTimeout the loadBalanceTimeout value to set. + * @return the SqlServerBaseLinkedServiceTypeProperties object itself. + */ + public SqlServerBaseLinkedServiceTypeProperties setLoadBalanceTimeout(Object loadBalanceTimeout) { + this.loadBalanceTimeout = loadBalanceTimeout; + return this; + } + + /** + * Get the commandTimeout property: The default wait time (in seconds) before terminating the attempt to execute a + * command and generating an error, used by recommended version. Type: integer (or Expression with resultType + * integer). + * + * @return the commandTimeout value. + */ + public Object getCommandTimeout() { + return this.commandTimeout; + } + + /** + * Set the commandTimeout property: The default wait time (in seconds) before terminating the attempt to execute a + * command and generating an error, used by recommended version. Type: integer (or Expression with resultType + * integer). + * + * @param commandTimeout the commandTimeout value to set. + * @return the SqlServerBaseLinkedServiceTypeProperties object itself. + */ + public SqlServerBaseLinkedServiceTypeProperties setCommandTimeout(Object commandTimeout) { + this.commandTimeout = commandTimeout; + return this; + } + + /** + * Get the integratedSecurity property: Indicate whether User ID and Password are specified in the connection (when + * false) or whether the current Windows account credentials are used for authentication (when true), used by + * recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @return the integratedSecurity value. + */ + public Object getIntegratedSecurity() { + return this.integratedSecurity; + } + + /** + * Set the integratedSecurity property: Indicate whether User ID and Password are specified in the connection (when + * false) or whether the current Windows account credentials are used for authentication (when true), used by + * recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @param integratedSecurity the integratedSecurity value to set. + * @return the SqlServerBaseLinkedServiceTypeProperties object itself. + */ + public SqlServerBaseLinkedServiceTypeProperties setIntegratedSecurity(Object integratedSecurity) { + this.integratedSecurity = integratedSecurity; + return this; + } + + /** + * Get the failoverPartner property: The name or address of the partner server to connect to if the primary server + * is down, used by recommended version. Type: string (or Expression with resultType string). + * + * @return the failoverPartner value. + */ + public Object getFailoverPartner() { + return this.failoverPartner; + } + + /** + * Set the failoverPartner property: The name or address of the partner server to connect to if the primary server + * is down, used by recommended version. Type: string (or Expression with resultType string). + * + * @param failoverPartner the failoverPartner value to set. + * @return the SqlServerBaseLinkedServiceTypeProperties object itself. + */ + public SqlServerBaseLinkedServiceTypeProperties setFailoverPartner(Object failoverPartner) { + this.failoverPartner = failoverPartner; + return this; + } + + /** + * Get the maxPoolSize property: The maximum number of connections allowed in the connection pool for this specific + * connection string, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @return the maxPoolSize value. + */ + public Object getMaxPoolSize() { + return this.maxPoolSize; + } + + /** + * Set the maxPoolSize property: The maximum number of connections allowed in the connection pool for this specific + * connection string, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @param maxPoolSize the maxPoolSize value to set. + * @return the SqlServerBaseLinkedServiceTypeProperties object itself. + */ + public SqlServerBaseLinkedServiceTypeProperties setMaxPoolSize(Object maxPoolSize) { + this.maxPoolSize = maxPoolSize; + return this; + } + + /** + * Get the minPoolSize property: The minimum number of connections allowed in the connection pool for this specific + * connection string, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @return the minPoolSize value. + */ + public Object getMinPoolSize() { + return this.minPoolSize; + } + + /** + * Set the minPoolSize property: The minimum number of connections allowed in the connection pool for this specific + * connection string, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @param minPoolSize the minPoolSize value to set. + * @return the SqlServerBaseLinkedServiceTypeProperties object itself. + */ + public SqlServerBaseLinkedServiceTypeProperties setMinPoolSize(Object minPoolSize) { + this.minPoolSize = minPoolSize; + return this; + } + + /** + * Get the multipleActiveResultSets property: When true, an application can maintain multiple active result sets + * (MARS). When false, an application must process or cancel all result sets from one batch before it can execute + * any other batch on that connection. Type: Boolean (or Expression with resultType boolean). + * + * @return the multipleActiveResultSets value. + */ + public Object getMultipleActiveResultSets() { + return this.multipleActiveResultSets; + } + + /** + * Set the multipleActiveResultSets property: When true, an application can maintain multiple active result sets + * (MARS). When false, an application must process or cancel all result sets from one batch before it can execute + * any other batch on that connection. Type: Boolean (or Expression with resultType boolean). + * + * @param multipleActiveResultSets the multipleActiveResultSets value to set. + * @return the SqlServerBaseLinkedServiceTypeProperties object itself. + */ + public SqlServerBaseLinkedServiceTypeProperties setMultipleActiveResultSets(Object multipleActiveResultSets) { + this.multipleActiveResultSets = multipleActiveResultSets; + return this; + } + + /** + * Get the multiSubnetFailover property: If your application is connecting to an AlwaysOn availability group (AG) on + * different subnets, setting MultiSubnetFailover=true provides faster detection of and connection to the + * (currently) active server, used by recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @return the multiSubnetFailover value. + */ + public Object getMultiSubnetFailover() { + return this.multiSubnetFailover; + } + + /** + * Set the multiSubnetFailover property: If your application is connecting to an AlwaysOn availability group (AG) on + * different subnets, setting MultiSubnetFailover=true provides faster detection of and connection to the + * (currently) active server, used by recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @param multiSubnetFailover the multiSubnetFailover value to set. + * @return the SqlServerBaseLinkedServiceTypeProperties object itself. + */ + public SqlServerBaseLinkedServiceTypeProperties setMultiSubnetFailover(Object multiSubnetFailover) { + this.multiSubnetFailover = multiSubnetFailover; + return this; + } + + /** + * Get the packetSize property: The size in bytes of the network packets used to communicate with an instance of + * server, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @return the packetSize value. + */ + public Object getPacketSize() { + return this.packetSize; + } + + /** + * Set the packetSize property: The size in bytes of the network packets used to communicate with an instance of + * server, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @param packetSize the packetSize value to set. + * @return the SqlServerBaseLinkedServiceTypeProperties object itself. + */ + public SqlServerBaseLinkedServiceTypeProperties setPacketSize(Object packetSize) { + this.packetSize = packetSize; + return this; + } + + /** + * Get the pooling property: Indicate whether the connection will be pooled or explicitly opened every time that the + * connection is requested, used by recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @return the pooling value. + */ + public Object getPooling() { + return this.pooling; + } + + /** + * Set the pooling property: Indicate whether the connection will be pooled or explicitly opened every time that the + * connection is requested, used by recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @param pooling the pooling value to set. + * @return the SqlServerBaseLinkedServiceTypeProperties object itself. + */ + public SqlServerBaseLinkedServiceTypeProperties setPooling(Object pooling) { + this.pooling = pooling; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeUntypedField("server", this.server); + jsonWriter.writeUntypedField("database", this.database); + jsonWriter.writeUntypedField("encrypt", this.encrypt); + jsonWriter.writeUntypedField("trustServerCertificate", this.trustServerCertificate); + jsonWriter.writeUntypedField("hostNameInCertificate", this.hostNameInCertificate); + jsonWriter.writeUntypedField("applicationIntent", this.applicationIntent); + jsonWriter.writeUntypedField("connectTimeout", this.connectTimeout); + jsonWriter.writeUntypedField("connectRetryCount", this.connectRetryCount); + jsonWriter.writeUntypedField("connectRetryInterval", this.connectRetryInterval); + jsonWriter.writeUntypedField("loadBalanceTimeout", this.loadBalanceTimeout); + jsonWriter.writeUntypedField("commandTimeout", this.commandTimeout); + jsonWriter.writeUntypedField("integratedSecurity", this.integratedSecurity); + jsonWriter.writeUntypedField("failoverPartner", this.failoverPartner); + jsonWriter.writeUntypedField("maxPoolSize", this.maxPoolSize); + jsonWriter.writeUntypedField("minPoolSize", this.minPoolSize); + jsonWriter.writeUntypedField("multipleActiveResultSets", this.multipleActiveResultSets); + jsonWriter.writeUntypedField("multiSubnetFailover", this.multiSubnetFailover); + jsonWriter.writeUntypedField("packetSize", this.packetSize); + jsonWriter.writeUntypedField("pooling", this.pooling); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlServerBaseLinkedServiceTypeProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlServerBaseLinkedServiceTypeProperties 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 SqlServerBaseLinkedServiceTypeProperties. + */ + public static SqlServerBaseLinkedServiceTypeProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlServerBaseLinkedServiceTypeProperties deserializedSqlServerBaseLinkedServiceTypeProperties + = new SqlServerBaseLinkedServiceTypeProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("server".equals(fieldName)) { + deserializedSqlServerBaseLinkedServiceTypeProperties.server = reader.readUntyped(); + } else if ("database".equals(fieldName)) { + deserializedSqlServerBaseLinkedServiceTypeProperties.database = reader.readUntyped(); + } else if ("encrypt".equals(fieldName)) { + deserializedSqlServerBaseLinkedServiceTypeProperties.encrypt = reader.readUntyped(); + } else if ("trustServerCertificate".equals(fieldName)) { + deserializedSqlServerBaseLinkedServiceTypeProperties.trustServerCertificate = reader.readUntyped(); + } else if ("hostNameInCertificate".equals(fieldName)) { + deserializedSqlServerBaseLinkedServiceTypeProperties.hostNameInCertificate = reader.readUntyped(); + } else if ("applicationIntent".equals(fieldName)) { + deserializedSqlServerBaseLinkedServiceTypeProperties.applicationIntent = reader.readUntyped(); + } else if ("connectTimeout".equals(fieldName)) { + deserializedSqlServerBaseLinkedServiceTypeProperties.connectTimeout = reader.readUntyped(); + } else if ("connectRetryCount".equals(fieldName)) { + deserializedSqlServerBaseLinkedServiceTypeProperties.connectRetryCount = reader.readUntyped(); + } else if ("connectRetryInterval".equals(fieldName)) { + deserializedSqlServerBaseLinkedServiceTypeProperties.connectRetryInterval = reader.readUntyped(); + } else if ("loadBalanceTimeout".equals(fieldName)) { + deserializedSqlServerBaseLinkedServiceTypeProperties.loadBalanceTimeout = reader.readUntyped(); + } else if ("commandTimeout".equals(fieldName)) { + deserializedSqlServerBaseLinkedServiceTypeProperties.commandTimeout = reader.readUntyped(); + } else if ("integratedSecurity".equals(fieldName)) { + deserializedSqlServerBaseLinkedServiceTypeProperties.integratedSecurity = reader.readUntyped(); + } else if ("failoverPartner".equals(fieldName)) { + deserializedSqlServerBaseLinkedServiceTypeProperties.failoverPartner = reader.readUntyped(); + } else if ("maxPoolSize".equals(fieldName)) { + deserializedSqlServerBaseLinkedServiceTypeProperties.maxPoolSize = reader.readUntyped(); + } else if ("minPoolSize".equals(fieldName)) { + deserializedSqlServerBaseLinkedServiceTypeProperties.minPoolSize = reader.readUntyped(); + } else if ("multipleActiveResultSets".equals(fieldName)) { + deserializedSqlServerBaseLinkedServiceTypeProperties.multipleActiveResultSets + = reader.readUntyped(); + } else if ("multiSubnetFailover".equals(fieldName)) { + deserializedSqlServerBaseLinkedServiceTypeProperties.multiSubnetFailover = reader.readUntyped(); + } else if ("packetSize".equals(fieldName)) { + deserializedSqlServerBaseLinkedServiceTypeProperties.packetSize = reader.readUntyped(); + } else if ("pooling".equals(fieldName)) { + deserializedSqlServerBaseLinkedServiceTypeProperties.pooling = reader.readUntyped(); + } else { + reader.skipChildren(); + } + } + + return deserializedSqlServerBaseLinkedServiceTypeProperties; + }); + } +} diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SqlServerLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SqlServerLinkedService.java index 8d7bb465ad0c..1ffdfe933b09 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SqlServerLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SqlServerLinkedService.java @@ -23,11 +23,136 @@ public class SqlServerLinkedService extends LinkedService { */ private String type = "SqlServer"; + /* + * The name or network address of the instance of SQL Server to which to connect, used by recommended version. Type: + * string (or Expression with resultType string). + */ + private Object server; + + /* + * The name of the database, used by recommended version. Type: string (or Expression with resultType string). + */ + private Object database; + + /* + * Indicate whether TLS encryption is required for all data sent between the client and server, used by recommended + * version. Possible values are true/yes/mandatory, false/no/optional and strict. Type: string (or Expression with + * resultType string). + */ + private Object encrypt; + + /* + * Indicate whether the channel will be encrypted while bypassing walking the certificate chain to validate trust, + * used by recommended version. Type: Boolean (or Expression with resultType boolean). + */ + private Object trustServerCertificate; + + /* + * The host name to use when validating the server certificate for the connection. When not specified, the server + * name from the Data Source is used for certificate validation, used by recommended version. Type: string (or + * Expression with resultType string). + */ + private Object hostNameInCertificate; + + /* + * The application workload type when connecting to a server, used by recommended version. Possible values are + * ReadOnly and ReadWrite. Type: string (or Expression with resultType string). + */ + private Object applicationIntent; + + /* + * The length of time (in seconds) to wait for a connection to the server before terminating the attempt and + * generating an error, used by recommended version. Type: integer (or Expression with resultType integer). + */ + private Object connectTimeout; + + /* + * The number of re-connections attempted after identifying that there was an idle connection failure, used by + * recommended version. This must be an integer between 0 and 255. Type: integer (or Expression with resultType + * integer). + */ + private Object connectRetryCount; + + /* + * The amount of time (in seconds) between each re-connection attempt after identifying that there was an idle + * connection failure, used by recommended version. This must be an integer between 1 and 60. Type: integer (or + * Expression with resultType integer). + */ + private Object connectRetryInterval; + + /* + * The minimum time, in seconds, for the connection to live in the connection pool before being destroyed, used by + * recommended version. Type: integer (or Expression with resultType integer). + */ + private Object loadBalanceTimeout; + + /* + * The default wait time (in seconds) before terminating the attempt to execute a command and generating an error, + * used by recommended version. Type: integer (or Expression with resultType integer). + */ + private Object commandTimeout; + + /* + * Indicate whether User ID and Password are specified in the connection (when false) or whether the current Windows + * account credentials are used for authentication (when true), used by recommended version. Type: Boolean (or + * Expression with resultType boolean). + */ + private Object integratedSecurity; + + /* + * The name or address of the partner server to connect to if the primary server is down, used by recommended + * version. Type: string (or Expression with resultType string). + */ + private Object failoverPartner; + + /* + * The maximum number of connections allowed in the connection pool for this specific connection string, used by + * recommended version. Type: integer (or Expression with resultType integer). + */ + private Object maxPoolSize; + + /* + * The minimum number of connections allowed in the connection pool for this specific connection string, used by + * recommended version. Type: integer (or Expression with resultType integer). + */ + private Object minPoolSize; + + /* + * When true, an application can maintain multiple active result sets (MARS). When false, an application must + * process or cancel all result sets from one batch before it can execute any other batch on that connection. Type: + * Boolean (or Expression with resultType boolean). + */ + private Object multipleActiveResultSets; + + /* + * If your application is connecting to an AlwaysOn availability group (AG) on different subnets, setting + * MultiSubnetFailover=true provides faster detection of and connection to the (currently) active server, used by + * recommended version. Type: Boolean (or Expression with resultType boolean). + */ + private Object multiSubnetFailover; + + /* + * The size in bytes of the network packets used to communicate with an instance of server, used by recommended + * version. Type: integer (or Expression with resultType integer). + */ + private Object packetSize; + + /* + * Indicate whether the connection will be pooled or explicitly opened every time that the connection is requested, + * used by recommended version. Type: Boolean (or Expression with resultType boolean). + */ + private Object pooling; + /* * The connection string. Type: string, SecureString or AzureKeyVaultSecretReference. */ private Object connectionString; + /* + * The type used for authentication. Type: string. + */ + private SqlServerAuthenticationType authenticationType; + /* * The on-premises Windows authentication user name. Type: string (or Expression with resultType string). */ @@ -49,6 +174,11 @@ public class SqlServerLinkedService extends LinkedService { */ private SqlAlwaysEncryptedProperties alwaysEncryptedSettings; + /* + * The credential reference containing authentication information. + */ + private CredentialReference credential; + /** * Creates an instance of SqlServerLinkedService class. */ @@ -65,6 +195,446 @@ public String getType() { return this.type; } + /** + * Get the server property: The name or network address of the instance of SQL Server to which to connect, used by + * recommended version. Type: string (or Expression with resultType string). + * + * @return the server value. + */ + public Object getServer() { + return this.server; + } + + /** + * Set the server property: The name or network address of the instance of SQL Server to which to connect, used by + * recommended version. Type: string (or Expression with resultType string). + * + * @param server the server value to set. + * @return the SqlServerLinkedService object itself. + */ + public SqlServerLinkedService setServer(Object server) { + this.server = server; + return this; + } + + /** + * Get the database property: The name of the database, used by recommended version. Type: string (or Expression + * with resultType string). + * + * @return the database value. + */ + public Object getDatabase() { + return this.database; + } + + /** + * Set the database property: The name of the database, used by recommended version. Type: string (or Expression + * with resultType string). + * + * @param database the database value to set. + * @return the SqlServerLinkedService object itself. + */ + public SqlServerLinkedService setDatabase(Object database) { + this.database = database; + return this; + } + + /** + * Get the encrypt property: Indicate whether TLS encryption is required for all data sent between the client and + * server, used by recommended version. Possible values are true/yes/mandatory, false/no/optional and strict. Type: + * string (or Expression with resultType string). + * + * @return the encrypt value. + */ + public Object getEncrypt() { + return this.encrypt; + } + + /** + * Set the encrypt property: Indicate whether TLS encryption is required for all data sent between the client and + * server, used by recommended version. Possible values are true/yes/mandatory, false/no/optional and strict. Type: + * string (or Expression with resultType string). + * + * @param encrypt the encrypt value to set. + * @return the SqlServerLinkedService object itself. + */ + public SqlServerLinkedService setEncrypt(Object encrypt) { + this.encrypt = encrypt; + return this; + } + + /** + * Get the trustServerCertificate property: Indicate whether the channel will be encrypted while bypassing walking + * the certificate chain to validate trust, used by recommended version. Type: Boolean (or Expression with + * resultType boolean). + * + * @return the trustServerCertificate value. + */ + public Object getTrustServerCertificate() { + return this.trustServerCertificate; + } + + /** + * Set the trustServerCertificate property: Indicate whether the channel will be encrypted while bypassing walking + * the certificate chain to validate trust, used by recommended version. Type: Boolean (or Expression with + * resultType boolean). + * + * @param trustServerCertificate the trustServerCertificate value to set. + * @return the SqlServerLinkedService object itself. + */ + public SqlServerLinkedService setTrustServerCertificate(Object trustServerCertificate) { + this.trustServerCertificate = trustServerCertificate; + return this; + } + + /** + * Get the hostNameInCertificate property: The host name to use when validating the server certificate for the + * connection. When not specified, the server name from the Data Source is used for certificate validation, used by + * recommended version. Type: string (or Expression with resultType string). + * + * @return the hostNameInCertificate value. + */ + public Object getHostNameInCertificate() { + return this.hostNameInCertificate; + } + + /** + * Set the hostNameInCertificate property: The host name to use when validating the server certificate for the + * connection. When not specified, the server name from the Data Source is used for certificate validation, used by + * recommended version. Type: string (or Expression with resultType string). + * + * @param hostNameInCertificate the hostNameInCertificate value to set. + * @return the SqlServerLinkedService object itself. + */ + public SqlServerLinkedService setHostNameInCertificate(Object hostNameInCertificate) { + this.hostNameInCertificate = hostNameInCertificate; + return this; + } + + /** + * Get the applicationIntent property: The application workload type when connecting to a server, used by + * recommended version. Possible values are ReadOnly and ReadWrite. Type: string (or Expression with resultType + * string). + * + * @return the applicationIntent value. + */ + public Object getApplicationIntent() { + return this.applicationIntent; + } + + /** + * Set the applicationIntent property: The application workload type when connecting to a server, used by + * recommended version. Possible values are ReadOnly and ReadWrite. Type: string (or Expression with resultType + * string). + * + * @param applicationIntent the applicationIntent value to set. + * @return the SqlServerLinkedService object itself. + */ + public SqlServerLinkedService setApplicationIntent(Object applicationIntent) { + this.applicationIntent = applicationIntent; + return this; + } + + /** + * Get the connectTimeout property: The length of time (in seconds) to wait for a connection to the server before + * terminating the attempt and generating an error, used by recommended version. Type: integer (or Expression with + * resultType integer). + * + * @return the connectTimeout value. + */ + public Object getConnectTimeout() { + return this.connectTimeout; + } + + /** + * Set the connectTimeout property: The length of time (in seconds) to wait for a connection to the server before + * terminating the attempt and generating an error, used by recommended version. Type: integer (or Expression with + * resultType integer). + * + * @param connectTimeout the connectTimeout value to set. + * @return the SqlServerLinkedService object itself. + */ + public SqlServerLinkedService setConnectTimeout(Object connectTimeout) { + this.connectTimeout = connectTimeout; + return this; + } + + /** + * Get the connectRetryCount property: The number of re-connections attempted after identifying that there was an + * idle connection failure, used by recommended version. This must be an integer between 0 and 255. Type: integer + * (or Expression with resultType integer). + * + * @return the connectRetryCount value. + */ + public Object getConnectRetryCount() { + return this.connectRetryCount; + } + + /** + * Set the connectRetryCount property: The number of re-connections attempted after identifying that there was an + * idle connection failure, used by recommended version. This must be an integer between 0 and 255. Type: integer + * (or Expression with resultType integer). + * + * @param connectRetryCount the connectRetryCount value to set. + * @return the SqlServerLinkedService object itself. + */ + public SqlServerLinkedService setConnectRetryCount(Object connectRetryCount) { + this.connectRetryCount = connectRetryCount; + return this; + } + + /** + * Get the connectRetryInterval property: The amount of time (in seconds) between each re-connection attempt after + * identifying that there was an idle connection failure, used by recommended version. This must be an integer + * between 1 and 60. Type: integer (or Expression with resultType integer). + * + * @return the connectRetryInterval value. + */ + public Object getConnectRetryInterval() { + return this.connectRetryInterval; + } + + /** + * Set the connectRetryInterval property: The amount of time (in seconds) between each re-connection attempt after + * identifying that there was an idle connection failure, used by recommended version. This must be an integer + * between 1 and 60. Type: integer (or Expression with resultType integer). + * + * @param connectRetryInterval the connectRetryInterval value to set. + * @return the SqlServerLinkedService object itself. + */ + public SqlServerLinkedService setConnectRetryInterval(Object connectRetryInterval) { + this.connectRetryInterval = connectRetryInterval; + return this; + } + + /** + * Get the loadBalanceTimeout property: The minimum time, in seconds, for the connection to live in the connection + * pool before being destroyed, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @return the loadBalanceTimeout value. + */ + public Object getLoadBalanceTimeout() { + return this.loadBalanceTimeout; + } + + /** + * Set the loadBalanceTimeout property: The minimum time, in seconds, for the connection to live in the connection + * pool before being destroyed, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @param loadBalanceTimeout the loadBalanceTimeout value to set. + * @return the SqlServerLinkedService object itself. + */ + public SqlServerLinkedService setLoadBalanceTimeout(Object loadBalanceTimeout) { + this.loadBalanceTimeout = loadBalanceTimeout; + return this; + } + + /** + * Get the commandTimeout property: The default wait time (in seconds) before terminating the attempt to execute a + * command and generating an error, used by recommended version. Type: integer (or Expression with resultType + * integer). + * + * @return the commandTimeout value. + */ + public Object getCommandTimeout() { + return this.commandTimeout; + } + + /** + * Set the commandTimeout property: The default wait time (in seconds) before terminating the attempt to execute a + * command and generating an error, used by recommended version. Type: integer (or Expression with resultType + * integer). + * + * @param commandTimeout the commandTimeout value to set. + * @return the SqlServerLinkedService object itself. + */ + public SqlServerLinkedService setCommandTimeout(Object commandTimeout) { + this.commandTimeout = commandTimeout; + return this; + } + + /** + * Get the integratedSecurity property: Indicate whether User ID and Password are specified in the connection (when + * false) or whether the current Windows account credentials are used for authentication (when true), used by + * recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @return the integratedSecurity value. + */ + public Object getIntegratedSecurity() { + return this.integratedSecurity; + } + + /** + * Set the integratedSecurity property: Indicate whether User ID and Password are specified in the connection (when + * false) or whether the current Windows account credentials are used for authentication (when true), used by + * recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @param integratedSecurity the integratedSecurity value to set. + * @return the SqlServerLinkedService object itself. + */ + public SqlServerLinkedService setIntegratedSecurity(Object integratedSecurity) { + this.integratedSecurity = integratedSecurity; + return this; + } + + /** + * Get the failoverPartner property: The name or address of the partner server to connect to if the primary server + * is down, used by recommended version. Type: string (or Expression with resultType string). + * + * @return the failoverPartner value. + */ + public Object getFailoverPartner() { + return this.failoverPartner; + } + + /** + * Set the failoverPartner property: The name or address of the partner server to connect to if the primary server + * is down, used by recommended version. Type: string (or Expression with resultType string). + * + * @param failoverPartner the failoverPartner value to set. + * @return the SqlServerLinkedService object itself. + */ + public SqlServerLinkedService setFailoverPartner(Object failoverPartner) { + this.failoverPartner = failoverPartner; + return this; + } + + /** + * Get the maxPoolSize property: The maximum number of connections allowed in the connection pool for this specific + * connection string, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @return the maxPoolSize value. + */ + public Object getMaxPoolSize() { + return this.maxPoolSize; + } + + /** + * Set the maxPoolSize property: The maximum number of connections allowed in the connection pool for this specific + * connection string, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @param maxPoolSize the maxPoolSize value to set. + * @return the SqlServerLinkedService object itself. + */ + public SqlServerLinkedService setMaxPoolSize(Object maxPoolSize) { + this.maxPoolSize = maxPoolSize; + return this; + } + + /** + * Get the minPoolSize property: The minimum number of connections allowed in the connection pool for this specific + * connection string, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @return the minPoolSize value. + */ + public Object getMinPoolSize() { + return this.minPoolSize; + } + + /** + * Set the minPoolSize property: The minimum number of connections allowed in the connection pool for this specific + * connection string, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @param minPoolSize the minPoolSize value to set. + * @return the SqlServerLinkedService object itself. + */ + public SqlServerLinkedService setMinPoolSize(Object minPoolSize) { + this.minPoolSize = minPoolSize; + return this; + } + + /** + * Get the multipleActiveResultSets property: When true, an application can maintain multiple active result sets + * (MARS). When false, an application must process or cancel all result sets from one batch before it can execute + * any other batch on that connection. Type: Boolean (or Expression with resultType boolean). + * + * @return the multipleActiveResultSets value. + */ + public Object getMultipleActiveResultSets() { + return this.multipleActiveResultSets; + } + + /** + * Set the multipleActiveResultSets property: When true, an application can maintain multiple active result sets + * (MARS). When false, an application must process or cancel all result sets from one batch before it can execute + * any other batch on that connection. Type: Boolean (or Expression with resultType boolean). + * + * @param multipleActiveResultSets the multipleActiveResultSets value to set. + * @return the SqlServerLinkedService object itself. + */ + public SqlServerLinkedService setMultipleActiveResultSets(Object multipleActiveResultSets) { + this.multipleActiveResultSets = multipleActiveResultSets; + return this; + } + + /** + * Get the multiSubnetFailover property: If your application is connecting to an AlwaysOn availability group (AG) on + * different subnets, setting MultiSubnetFailover=true provides faster detection of and connection to the + * (currently) active server, used by recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @return the multiSubnetFailover value. + */ + public Object getMultiSubnetFailover() { + return this.multiSubnetFailover; + } + + /** + * Set the multiSubnetFailover property: If your application is connecting to an AlwaysOn availability group (AG) on + * different subnets, setting MultiSubnetFailover=true provides faster detection of and connection to the + * (currently) active server, used by recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @param multiSubnetFailover the multiSubnetFailover value to set. + * @return the SqlServerLinkedService object itself. + */ + public SqlServerLinkedService setMultiSubnetFailover(Object multiSubnetFailover) { + this.multiSubnetFailover = multiSubnetFailover; + return this; + } + + /** + * Get the packetSize property: The size in bytes of the network packets used to communicate with an instance of + * server, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @return the packetSize value. + */ + public Object getPacketSize() { + return this.packetSize; + } + + /** + * Set the packetSize property: The size in bytes of the network packets used to communicate with an instance of + * server, used by recommended version. Type: integer (or Expression with resultType integer). + * + * @param packetSize the packetSize value to set. + * @return the SqlServerLinkedService object itself. + */ + public SqlServerLinkedService setPacketSize(Object packetSize) { + this.packetSize = packetSize; + return this; + } + + /** + * Get the pooling property: Indicate whether the connection will be pooled or explicitly opened every time that the + * connection is requested, used by recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @return the pooling value. + */ + public Object getPooling() { + return this.pooling; + } + + /** + * Set the pooling property: Indicate whether the connection will be pooled or explicitly opened every time that the + * connection is requested, used by recommended version. Type: Boolean (or Expression with resultType boolean). + * + * @param pooling the pooling value to set. + * @return the SqlServerLinkedService object itself. + */ + public SqlServerLinkedService setPooling(Object pooling) { + this.pooling = pooling; + return this; + } + /** * Get the connectionString property: The connection string. Type: string, SecureString or * AzureKeyVaultSecretReference. @@ -87,6 +657,26 @@ public SqlServerLinkedService setConnectionString(Object connectionString) { return this; } + /** + * Get the authenticationType property: The type used for authentication. Type: string. + * + * @return the authenticationType value. + */ + public SqlServerAuthenticationType getAuthenticationType() { + return this.authenticationType; + } + + /** + * Set the authenticationType property: The type used for authentication. Type: string. + * + * @param authenticationType the authenticationType value to set. + * @return the SqlServerLinkedService object itself. + */ + public SqlServerLinkedService setAuthenticationType(SqlServerAuthenticationType authenticationType) { + this.authenticationType = authenticationType; + return this; + } + /** * Get the userName property: The on-premises Windows authentication user name. Type: string (or Expression with * resultType string). @@ -171,6 +761,35 @@ public SqlServerLinkedService setAlwaysEncryptedSettings(SqlAlwaysEncryptedPrope return this; } + /** + * Get the credential property: The credential reference containing authentication information. + * + * @return the credential value. + */ + public CredentialReference getCredential() { + return this.credential; + } + + /** + * Set the credential property: The credential reference containing authentication information. + * + * @param credential the credential value to set. + * @return the SqlServerLinkedService object itself. + */ + public SqlServerLinkedService setCredential(CredentialReference credential) { + this.credential = credential; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlServerLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -213,22 +832,66 @@ public SqlServerLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); jsonWriter.writeArrayField("annotations", getAnnotations(), (writer, element) -> writer.writeUntyped(element)); jsonWriter.writeStringField("type", this.type); - if (connectionString != null + if (server != null + || database != null + || encrypt != null + || trustServerCertificate != null + || hostNameInCertificate != null + || applicationIntent != null + || connectTimeout != null + || connectRetryCount != null + || connectRetryInterval != null + || loadBalanceTimeout != null + || commandTimeout != null + || integratedSecurity != null + || failoverPartner != null + || maxPoolSize != null + || minPoolSize != null + || multipleActiveResultSets != null + || multiSubnetFailover != null + || packetSize != null + || pooling != null + || connectionString != null + || authenticationType != null || userName != null || password != null || encryptedCredential != null - || alwaysEncryptedSettings != null) { + || alwaysEncryptedSettings != null + || credential != null) { jsonWriter.writeStartObject("typeProperties"); + jsonWriter.writeUntypedField("server", this.server); + jsonWriter.writeUntypedField("database", this.database); + jsonWriter.writeUntypedField("encrypt", this.encrypt); + jsonWriter.writeUntypedField("trustServerCertificate", this.trustServerCertificate); + jsonWriter.writeUntypedField("hostNameInCertificate", this.hostNameInCertificate); + jsonWriter.writeUntypedField("applicationIntent", this.applicationIntent); + jsonWriter.writeUntypedField("connectTimeout", this.connectTimeout); + jsonWriter.writeUntypedField("connectRetryCount", this.connectRetryCount); + jsonWriter.writeUntypedField("connectRetryInterval", this.connectRetryInterval); + jsonWriter.writeUntypedField("loadBalanceTimeout", this.loadBalanceTimeout); + jsonWriter.writeUntypedField("commandTimeout", this.commandTimeout); + jsonWriter.writeUntypedField("integratedSecurity", this.integratedSecurity); + jsonWriter.writeUntypedField("failoverPartner", this.failoverPartner); + jsonWriter.writeUntypedField("maxPoolSize", this.maxPoolSize); + jsonWriter.writeUntypedField("minPoolSize", this.minPoolSize); + jsonWriter.writeUntypedField("multipleActiveResultSets", this.multipleActiveResultSets); + jsonWriter.writeUntypedField("multiSubnetFailover", this.multiSubnetFailover); + jsonWriter.writeUntypedField("packetSize", this.packetSize); + jsonWriter.writeUntypedField("pooling", this.pooling); jsonWriter.writeUntypedField("connectionString", this.connectionString); + jsonWriter.writeStringField("authenticationType", + this.authenticationType == null ? null : this.authenticationType.toString()); jsonWriter.writeUntypedField("userName", this.userName); jsonWriter.writeJsonField("password", this.password); jsonWriter.writeUntypedField("encryptedCredential", this.encryptedCredential); jsonWriter.writeJsonField("alwaysEncryptedSettings", this.alwaysEncryptedSettings); + jsonWriter.writeJsonField("credential", this.credential); jsonWriter.writeEndObject(); } if (getAdditionalProperties() != null) { @@ -245,7 +908,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @param jsonReader The JsonReader being read. * @return An instance of SqlServerLinkedService 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 SqlServerLinkedService. */ public static SqlServerLinkedService fromJson(JsonReader jsonReader) throws IOException { @@ -256,7 +918,9 @@ public static SqlServerLinkedService fromJson(JsonReader jsonReader) throws IOEx String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedSqlServerLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedSqlServerLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedSqlServerLinkedService.setDescription(reader.getString()); @@ -274,8 +938,49 @@ public static SqlServerLinkedService fromJson(JsonReader jsonReader) throws IOEx fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectionString".equals(fieldName)) { + if ("server".equals(fieldName)) { + deserializedSqlServerLinkedService.server = reader.readUntyped(); + } else if ("database".equals(fieldName)) { + deserializedSqlServerLinkedService.database = reader.readUntyped(); + } else if ("encrypt".equals(fieldName)) { + deserializedSqlServerLinkedService.encrypt = reader.readUntyped(); + } else if ("trustServerCertificate".equals(fieldName)) { + deserializedSqlServerLinkedService.trustServerCertificate = reader.readUntyped(); + } else if ("hostNameInCertificate".equals(fieldName)) { + deserializedSqlServerLinkedService.hostNameInCertificate = reader.readUntyped(); + } else if ("applicationIntent".equals(fieldName)) { + deserializedSqlServerLinkedService.applicationIntent = reader.readUntyped(); + } else if ("connectTimeout".equals(fieldName)) { + deserializedSqlServerLinkedService.connectTimeout = reader.readUntyped(); + } else if ("connectRetryCount".equals(fieldName)) { + deserializedSqlServerLinkedService.connectRetryCount = reader.readUntyped(); + } else if ("connectRetryInterval".equals(fieldName)) { + deserializedSqlServerLinkedService.connectRetryInterval = reader.readUntyped(); + } else if ("loadBalanceTimeout".equals(fieldName)) { + deserializedSqlServerLinkedService.loadBalanceTimeout = reader.readUntyped(); + } else if ("commandTimeout".equals(fieldName)) { + deserializedSqlServerLinkedService.commandTimeout = reader.readUntyped(); + } else if ("integratedSecurity".equals(fieldName)) { + deserializedSqlServerLinkedService.integratedSecurity = reader.readUntyped(); + } else if ("failoverPartner".equals(fieldName)) { + deserializedSqlServerLinkedService.failoverPartner = reader.readUntyped(); + } else if ("maxPoolSize".equals(fieldName)) { + deserializedSqlServerLinkedService.maxPoolSize = reader.readUntyped(); + } else if ("minPoolSize".equals(fieldName)) { + deserializedSqlServerLinkedService.minPoolSize = reader.readUntyped(); + } else if ("multipleActiveResultSets".equals(fieldName)) { + deserializedSqlServerLinkedService.multipleActiveResultSets = reader.readUntyped(); + } else if ("multiSubnetFailover".equals(fieldName)) { + deserializedSqlServerLinkedService.multiSubnetFailover = reader.readUntyped(); + } else if ("packetSize".equals(fieldName)) { + deserializedSqlServerLinkedService.packetSize = reader.readUntyped(); + } else if ("pooling".equals(fieldName)) { + deserializedSqlServerLinkedService.pooling = reader.readUntyped(); + } else if ("connectionString".equals(fieldName)) { deserializedSqlServerLinkedService.connectionString = reader.readUntyped(); + } else if ("authenticationType".equals(fieldName)) { + deserializedSqlServerLinkedService.authenticationType + = SqlServerAuthenticationType.fromString(reader.getString()); } else if ("userName".equals(fieldName)) { deserializedSqlServerLinkedService.userName = reader.readUntyped(); } else if ("password".equals(fieldName)) { @@ -285,6 +990,8 @@ public static SqlServerLinkedService fromJson(JsonReader jsonReader) throws IOEx } else if ("alwaysEncryptedSettings".equals(fieldName)) { deserializedSqlServerLinkedService.alwaysEncryptedSettings = SqlAlwaysEncryptedProperties.fromJson(reader); + } else if ("credential".equals(fieldName)) { + deserializedSqlServerLinkedService.credential = CredentialReference.fromJson(reader); } else { reader.skipChildren(); } diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SqlServerLinkedServiceTypeProperties.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SqlServerLinkedServiceTypeProperties.java new file mode 100644 index 000000000000..507156bd968f --- /dev/null +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SqlServerLinkedServiceTypeProperties.java @@ -0,0 +1,492 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.analytics.synapse.artifacts.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; + +/** + * SQL Server linked service properties. + */ +@Fluent +public final class SqlServerLinkedServiceTypeProperties extends SqlServerBaseLinkedServiceTypeProperties { + /* + * The connection string. Type: string, SecureString or AzureKeyVaultSecretReference. + */ + private Object connectionString; + + /* + * The type used for authentication. Type: string. + */ + private SqlServerAuthenticationType authenticationType; + + /* + * The on-premises Windows authentication user name. Type: string (or Expression with resultType string). + */ + private Object userName; + + /* + * The on-premises Windows authentication password. + */ + private SecretBase password; + + /* + * The encrypted credential used for authentication. Credentials are encrypted using the integration runtime + * credential manager. Type: string (or Expression with resultType string). + */ + private Object encryptedCredential; + + /* + * Sql always encrypted properties. + */ + private SqlAlwaysEncryptedProperties alwaysEncryptedSettings; + + /* + * The credential reference containing authentication information. + */ + private CredentialReference credential; + + /** + * Creates an instance of SqlServerLinkedServiceTypeProperties class. + */ + public SqlServerLinkedServiceTypeProperties() { + } + + /** + * Get the connectionString property: The connection string. Type: string, SecureString or + * AzureKeyVaultSecretReference. + * + * @return the connectionString value. + */ + public Object getConnectionString() { + return this.connectionString; + } + + /** + * Set the connectionString property: The connection string. Type: string, SecureString or + * AzureKeyVaultSecretReference. + * + * @param connectionString the connectionString value to set. + * @return the SqlServerLinkedServiceTypeProperties object itself. + */ + public SqlServerLinkedServiceTypeProperties setConnectionString(Object connectionString) { + this.connectionString = connectionString; + return this; + } + + /** + * Get the authenticationType property: The type used for authentication. Type: string. + * + * @return the authenticationType value. + */ + public SqlServerAuthenticationType getAuthenticationType() { + return this.authenticationType; + } + + /** + * Set the authenticationType property: The type used for authentication. Type: string. + * + * @param authenticationType the authenticationType value to set. + * @return the SqlServerLinkedServiceTypeProperties object itself. + */ + public SqlServerLinkedServiceTypeProperties setAuthenticationType(SqlServerAuthenticationType authenticationType) { + this.authenticationType = authenticationType; + return this; + } + + /** + * Get the userName property: The on-premises Windows authentication user name. Type: string (or Expression with + * resultType string). + * + * @return the userName value. + */ + public Object getUserName() { + return this.userName; + } + + /** + * Set the userName property: The on-premises Windows authentication user name. Type: string (or Expression with + * resultType string). + * + * @param userName the userName value to set. + * @return the SqlServerLinkedServiceTypeProperties object itself. + */ + public SqlServerLinkedServiceTypeProperties setUserName(Object userName) { + this.userName = userName; + return this; + } + + /** + * Get the password property: The on-premises Windows authentication password. + * + * @return the password value. + */ + public SecretBase getPassword() { + return this.password; + } + + /** + * Set the password property: The on-premises Windows authentication password. + * + * @param password the password value to set. + * @return the SqlServerLinkedServiceTypeProperties object itself. + */ + public SqlServerLinkedServiceTypeProperties setPassword(SecretBase password) { + this.password = password; + return this; + } + + /** + * Get the encryptedCredential property: The encrypted credential used for authentication. Credentials are encrypted + * using the integration runtime credential manager. Type: string (or Expression with resultType string). + * + * @return the encryptedCredential value. + */ + public Object getEncryptedCredential() { + return this.encryptedCredential; + } + + /** + * Set the encryptedCredential property: The encrypted credential used for authentication. Credentials are encrypted + * using the integration runtime credential manager. Type: string (or Expression with resultType string). + * + * @param encryptedCredential the encryptedCredential value to set. + * @return the SqlServerLinkedServiceTypeProperties object itself. + */ + public SqlServerLinkedServiceTypeProperties setEncryptedCredential(Object encryptedCredential) { + this.encryptedCredential = encryptedCredential; + return this; + } + + /** + * Get the alwaysEncryptedSettings property: Sql always encrypted properties. + * + * @return the alwaysEncryptedSettings value. + */ + public SqlAlwaysEncryptedProperties getAlwaysEncryptedSettings() { + return this.alwaysEncryptedSettings; + } + + /** + * Set the alwaysEncryptedSettings property: Sql always encrypted properties. + * + * @param alwaysEncryptedSettings the alwaysEncryptedSettings value to set. + * @return the SqlServerLinkedServiceTypeProperties object itself. + */ + public SqlServerLinkedServiceTypeProperties + setAlwaysEncryptedSettings(SqlAlwaysEncryptedProperties alwaysEncryptedSettings) { + this.alwaysEncryptedSettings = alwaysEncryptedSettings; + return this; + } + + /** + * Get the credential property: The credential reference containing authentication information. + * + * @return the credential value. + */ + public CredentialReference getCredential() { + return this.credential; + } + + /** + * Set the credential property: The credential reference containing authentication information. + * + * @param credential the credential value to set. + * @return the SqlServerLinkedServiceTypeProperties object itself. + */ + public SqlServerLinkedServiceTypeProperties setCredential(CredentialReference credential) { + this.credential = credential; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlServerLinkedServiceTypeProperties setServer(Object server) { + super.setServer(server); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlServerLinkedServiceTypeProperties setDatabase(Object database) { + super.setDatabase(database); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlServerLinkedServiceTypeProperties setEncrypt(Object encrypt) { + super.setEncrypt(encrypt); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlServerLinkedServiceTypeProperties setTrustServerCertificate(Object trustServerCertificate) { + super.setTrustServerCertificate(trustServerCertificate); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlServerLinkedServiceTypeProperties setHostNameInCertificate(Object hostNameInCertificate) { + super.setHostNameInCertificate(hostNameInCertificate); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlServerLinkedServiceTypeProperties setApplicationIntent(Object applicationIntent) { + super.setApplicationIntent(applicationIntent); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlServerLinkedServiceTypeProperties setConnectTimeout(Object connectTimeout) { + super.setConnectTimeout(connectTimeout); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlServerLinkedServiceTypeProperties setConnectRetryCount(Object connectRetryCount) { + super.setConnectRetryCount(connectRetryCount); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlServerLinkedServiceTypeProperties setConnectRetryInterval(Object connectRetryInterval) { + super.setConnectRetryInterval(connectRetryInterval); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlServerLinkedServiceTypeProperties setLoadBalanceTimeout(Object loadBalanceTimeout) { + super.setLoadBalanceTimeout(loadBalanceTimeout); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlServerLinkedServiceTypeProperties setCommandTimeout(Object commandTimeout) { + super.setCommandTimeout(commandTimeout); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlServerLinkedServiceTypeProperties setIntegratedSecurity(Object integratedSecurity) { + super.setIntegratedSecurity(integratedSecurity); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlServerLinkedServiceTypeProperties setFailoverPartner(Object failoverPartner) { + super.setFailoverPartner(failoverPartner); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlServerLinkedServiceTypeProperties setMaxPoolSize(Object maxPoolSize) { + super.setMaxPoolSize(maxPoolSize); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlServerLinkedServiceTypeProperties setMinPoolSize(Object minPoolSize) { + super.setMinPoolSize(minPoolSize); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlServerLinkedServiceTypeProperties setMultipleActiveResultSets(Object multipleActiveResultSets) { + super.setMultipleActiveResultSets(multipleActiveResultSets); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlServerLinkedServiceTypeProperties setMultiSubnetFailover(Object multiSubnetFailover) { + super.setMultiSubnetFailover(multiSubnetFailover); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlServerLinkedServiceTypeProperties setPacketSize(Object packetSize) { + super.setPacketSize(packetSize); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SqlServerLinkedServiceTypeProperties setPooling(Object pooling) { + super.setPooling(pooling); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeUntypedField("server", getServer()); + jsonWriter.writeUntypedField("database", getDatabase()); + jsonWriter.writeUntypedField("encrypt", getEncrypt()); + jsonWriter.writeUntypedField("trustServerCertificate", getTrustServerCertificate()); + jsonWriter.writeUntypedField("hostNameInCertificate", getHostNameInCertificate()); + jsonWriter.writeUntypedField("applicationIntent", getApplicationIntent()); + jsonWriter.writeUntypedField("connectTimeout", getConnectTimeout()); + jsonWriter.writeUntypedField("connectRetryCount", getConnectRetryCount()); + jsonWriter.writeUntypedField("connectRetryInterval", getConnectRetryInterval()); + jsonWriter.writeUntypedField("loadBalanceTimeout", getLoadBalanceTimeout()); + jsonWriter.writeUntypedField("commandTimeout", getCommandTimeout()); + jsonWriter.writeUntypedField("integratedSecurity", getIntegratedSecurity()); + jsonWriter.writeUntypedField("failoverPartner", getFailoverPartner()); + jsonWriter.writeUntypedField("maxPoolSize", getMaxPoolSize()); + jsonWriter.writeUntypedField("minPoolSize", getMinPoolSize()); + jsonWriter.writeUntypedField("multipleActiveResultSets", getMultipleActiveResultSets()); + jsonWriter.writeUntypedField("multiSubnetFailover", getMultiSubnetFailover()); + jsonWriter.writeUntypedField("packetSize", getPacketSize()); + jsonWriter.writeUntypedField("pooling", getPooling()); + jsonWriter.writeUntypedField("connectionString", this.connectionString); + jsonWriter.writeStringField("authenticationType", + this.authenticationType == null ? null : this.authenticationType.toString()); + jsonWriter.writeUntypedField("userName", this.userName); + jsonWriter.writeJsonField("password", this.password); + jsonWriter.writeUntypedField("encryptedCredential", this.encryptedCredential); + jsonWriter.writeJsonField("alwaysEncryptedSettings", this.alwaysEncryptedSettings); + jsonWriter.writeJsonField("credential", this.credential); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SqlServerLinkedServiceTypeProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SqlServerLinkedServiceTypeProperties 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 SqlServerLinkedServiceTypeProperties. + */ + public static SqlServerLinkedServiceTypeProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SqlServerLinkedServiceTypeProperties deserializedSqlServerLinkedServiceTypeProperties + = new SqlServerLinkedServiceTypeProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("server".equals(fieldName)) { + deserializedSqlServerLinkedServiceTypeProperties.setServer(reader.readUntyped()); + } else if ("database".equals(fieldName)) { + deserializedSqlServerLinkedServiceTypeProperties.setDatabase(reader.readUntyped()); + } else if ("encrypt".equals(fieldName)) { + deserializedSqlServerLinkedServiceTypeProperties.setEncrypt(reader.readUntyped()); + } else if ("trustServerCertificate".equals(fieldName)) { + deserializedSqlServerLinkedServiceTypeProperties.setTrustServerCertificate(reader.readUntyped()); + } else if ("hostNameInCertificate".equals(fieldName)) { + deserializedSqlServerLinkedServiceTypeProperties.setHostNameInCertificate(reader.readUntyped()); + } else if ("applicationIntent".equals(fieldName)) { + deserializedSqlServerLinkedServiceTypeProperties.setApplicationIntent(reader.readUntyped()); + } else if ("connectTimeout".equals(fieldName)) { + deserializedSqlServerLinkedServiceTypeProperties.setConnectTimeout(reader.readUntyped()); + } else if ("connectRetryCount".equals(fieldName)) { + deserializedSqlServerLinkedServiceTypeProperties.setConnectRetryCount(reader.readUntyped()); + } else if ("connectRetryInterval".equals(fieldName)) { + deserializedSqlServerLinkedServiceTypeProperties.setConnectRetryInterval(reader.readUntyped()); + } else if ("loadBalanceTimeout".equals(fieldName)) { + deserializedSqlServerLinkedServiceTypeProperties.setLoadBalanceTimeout(reader.readUntyped()); + } else if ("commandTimeout".equals(fieldName)) { + deserializedSqlServerLinkedServiceTypeProperties.setCommandTimeout(reader.readUntyped()); + } else if ("integratedSecurity".equals(fieldName)) { + deserializedSqlServerLinkedServiceTypeProperties.setIntegratedSecurity(reader.readUntyped()); + } else if ("failoverPartner".equals(fieldName)) { + deserializedSqlServerLinkedServiceTypeProperties.setFailoverPartner(reader.readUntyped()); + } else if ("maxPoolSize".equals(fieldName)) { + deserializedSqlServerLinkedServiceTypeProperties.setMaxPoolSize(reader.readUntyped()); + } else if ("minPoolSize".equals(fieldName)) { + deserializedSqlServerLinkedServiceTypeProperties.setMinPoolSize(reader.readUntyped()); + } else if ("multipleActiveResultSets".equals(fieldName)) { + deserializedSqlServerLinkedServiceTypeProperties.setMultipleActiveResultSets(reader.readUntyped()); + } else if ("multiSubnetFailover".equals(fieldName)) { + deserializedSqlServerLinkedServiceTypeProperties.setMultiSubnetFailover(reader.readUntyped()); + } else if ("packetSize".equals(fieldName)) { + deserializedSqlServerLinkedServiceTypeProperties.setPacketSize(reader.readUntyped()); + } else if ("pooling".equals(fieldName)) { + deserializedSqlServerLinkedServiceTypeProperties.setPooling(reader.readUntyped()); + } else if ("connectionString".equals(fieldName)) { + deserializedSqlServerLinkedServiceTypeProperties.connectionString = reader.readUntyped(); + } else if ("authenticationType".equals(fieldName)) { + deserializedSqlServerLinkedServiceTypeProperties.authenticationType + = SqlServerAuthenticationType.fromString(reader.getString()); + } else if ("userName".equals(fieldName)) { + deserializedSqlServerLinkedServiceTypeProperties.userName = reader.readUntyped(); + } else if ("password".equals(fieldName)) { + deserializedSqlServerLinkedServiceTypeProperties.password = SecretBase.fromJson(reader); + } else if ("encryptedCredential".equals(fieldName)) { + deserializedSqlServerLinkedServiceTypeProperties.encryptedCredential = reader.readUntyped(); + } else if ("alwaysEncryptedSettings".equals(fieldName)) { + deserializedSqlServerLinkedServiceTypeProperties.alwaysEncryptedSettings + = SqlAlwaysEncryptedProperties.fromJson(reader); + } else if ("credential".equals(fieldName)) { + deserializedSqlServerLinkedServiceTypeProperties.credential = CredentialReference.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedSqlServerLinkedServiceTypeProperties; + }); + } +} diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SquareLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SquareLinkedService.java index 274f2f3a5c73..cb0a17c77600 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SquareLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SquareLinkedService.java @@ -279,6 +279,15 @@ public SquareLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public SquareLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -321,6 +330,7 @@ public SquareLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -372,7 +382,9 @@ public static SquareLinkedService fromJson(JsonReader jsonReader) throws IOExcep String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedSquareLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedSquareLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedSquareLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SybaseLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SybaseLinkedService.java index 5c0e8f8c4b52..ea2a39151067 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SybaseLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SybaseLinkedService.java @@ -217,6 +217,15 @@ public SybaseLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public SybaseLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -259,6 +268,7 @@ public SybaseLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -307,7 +317,9 @@ public static SybaseLinkedService fromJson(JsonReader jsonReader) throws IOExcep String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedSybaseLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedSybaseLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedSybaseLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SynapseActivityAuthentication.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SynapseActivityAuthentication.java new file mode 100644 index 000000000000..ed1614be7000 --- /dev/null +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SynapseActivityAuthentication.java @@ -0,0 +1,115 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.analytics.synapse.artifacts.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; + +/** + * Synapse activity authentication properties. + */ +@Fluent +public final class SynapseActivityAuthentication implements JsonSerializable { + /* + * Synapse activity authentication (MSI/UserAssignedManagedIdentity) + */ + private String type; + + /* + * The credential reference containing authentication information. + */ + private CredentialReference credential; + + /** + * Creates an instance of SynapseActivityAuthentication class. + */ + public SynapseActivityAuthentication() { + } + + /** + * Get the type property: Synapse activity authentication (MSI/UserAssignedManagedIdentity). + * + * @return the type value. + */ + public String getType() { + return this.type; + } + + /** + * Set the type property: Synapse activity authentication (MSI/UserAssignedManagedIdentity). + * + * @param type the type value to set. + * @return the SynapseActivityAuthentication object itself. + */ + public SynapseActivityAuthentication setType(String type) { + this.type = type; + return this; + } + + /** + * Get the credential property: The credential reference containing authentication information. + * + * @return the credential value. + */ + public CredentialReference getCredential() { + return this.credential; + } + + /** + * Set the credential property: The credential reference containing authentication information. + * + * @param credential the credential value to set. + * @return the SynapseActivityAuthentication object itself. + */ + public SynapseActivityAuthentication setCredential(CredentialReference credential) { + this.credential = credential; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type); + jsonWriter.writeJsonField("credential", this.credential); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SynapseActivityAuthentication from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SynapseActivityAuthentication 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 SynapseActivityAuthentication. + */ + public static SynapseActivityAuthentication fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SynapseActivityAuthentication deserializedSynapseActivityAuthentication + = new SynapseActivityAuthentication(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("type".equals(fieldName)) { + deserializedSynapseActivityAuthentication.type = reader.getString(); + } else if ("credential".equals(fieldName)) { + deserializedSynapseActivityAuthentication.credential = CredentialReference.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedSynapseActivityAuthentication; + }); + } +} diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SynapseNotebookActivity.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SynapseNotebookActivity.java index 3e683e3d189b..5b847a2228e4 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SynapseNotebookActivity.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SynapseNotebookActivity.java @@ -78,6 +78,11 @@ public class SynapseNotebookActivity extends ExecutionActivity { */ private Map sparkConfig; + /* + * Authentication method used for executing the notebook. + */ + private SynapseActivityAuthentication authentication; + /** * Creates an instance of SynapseNotebookActivity class. */ @@ -307,6 +312,26 @@ public SynapseNotebookActivity setSparkConfig(Map sparkConfig) { return this; } + /** + * Get the authentication property: Authentication method used for executing the notebook. + * + * @return the authentication value. + */ + public SynapseActivityAuthentication getAuthentication() { + return this.authentication; + } + + /** + * Set the authentication property: Authentication method used for executing the notebook. + * + * @param authentication the authentication value to set. + * @return the SynapseNotebookActivity object itself. + */ + public SynapseNotebookActivity setAuthentication(SynapseActivityAuthentication authentication) { + this.authentication = authentication; + return this; + } + /** * {@inheritDoc} */ @@ -405,7 +430,8 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { || numExecutors != null || configurationType != null || targetSparkConfiguration != null - || sparkConfig != null) { + || sparkConfig != null + || authentication != null) { jsonWriter.writeStartObject("typeProperties"); jsonWriter.writeJsonField("notebook", this.notebook); jsonWriter.writeJsonField("sparkPool", this.sparkPool); @@ -419,6 +445,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeJsonField("targetSparkConfiguration", this.targetSparkConfiguration); jsonWriter.writeMapField("sparkConfig", this.sparkConfig, (writer, element) -> writer.writeUntyped(element)); + jsonWriter.writeJsonField("authentication", this.authentication); jsonWriter.writeEndObject(); } if (getAdditionalProperties() != null) { @@ -499,6 +526,9 @@ public static SynapseNotebookActivity fromJson(JsonReader jsonReader) throws IOE } else if ("sparkConfig".equals(fieldName)) { Map sparkConfig = reader.readMap(reader1 -> reader1.readUntyped()); deserializedSynapseNotebookActivity.sparkConfig = sparkConfig; + } else if ("authentication".equals(fieldName)) { + deserializedSynapseNotebookActivity.authentication + = SynapseActivityAuthentication.fromJson(reader); } else { reader.skipChildren(); } diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SynapseSparkJobDefinitionActivity.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SynapseSparkJobDefinitionActivity.java index 8a22ca6d51c3..8c66c025494c 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SynapseSparkJobDefinitionActivity.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/SynapseSparkJobDefinitionActivity.java @@ -116,6 +116,11 @@ public class SynapseSparkJobDefinitionActivity extends ExecutionActivity { */ private Map sparkConfig; + /* + * Authentication method used for executing the Spark job definition. + */ + private SynapseActivityAuthentication authentication; + /** * Creates an instance of SynapseSparkJobDefinitionActivity class. */ @@ -484,6 +489,26 @@ public SynapseSparkJobDefinitionActivity setSparkConfig(Map spar return this; } + /** + * Get the authentication property: Authentication method used for executing the Spark job definition. + * + * @return the authentication value. + */ + public SynapseActivityAuthentication getAuthentication() { + return this.authentication; + } + + /** + * Set the authentication property: Authentication method used for executing the Spark job definition. + * + * @param authentication the authentication value to set. + * @return the SynapseSparkJobDefinitionActivity object itself. + */ + public SynapseSparkJobDefinitionActivity setAuthentication(SynapseActivityAuthentication authentication) { + this.authentication = authentication; + return this; + } + /** * {@inheritDoc} */ @@ -588,7 +613,8 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { || numExecutors != null || configurationType != null || targetSparkConfiguration != null - || sparkConfig != null) { + || sparkConfig != null + || authentication != null) { jsonWriter.writeStartObject("typeProperties"); jsonWriter.writeJsonField("sparkJob", this.sparkJob); jsonWriter.writeArrayField("args", this.arguments, (writer, element) -> writer.writeUntyped(element)); @@ -609,6 +635,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeJsonField("targetSparkConfiguration", this.targetSparkConfiguration); jsonWriter.writeMapField("sparkConfig", this.sparkConfig, (writer, element) -> writer.writeUntyped(element)); + jsonWriter.writeJsonField("authentication", this.authentication); jsonWriter.writeEndObject(); } if (getAdditionalProperties() != null) { @@ -707,6 +734,9 @@ public static SynapseSparkJobDefinitionActivity fromJson(JsonReader jsonReader) } else if ("sparkConfig".equals(fieldName)) { Map sparkConfig = reader.readMap(reader1 -> reader1.readUntyped()); deserializedSynapseSparkJobDefinitionActivity.sparkConfig = sparkConfig; + } else if ("authentication".equals(fieldName)) { + deserializedSynapseSparkJobDefinitionActivity.authentication + = SynapseActivityAuthentication.fromJson(reader); } else { reader.skipChildren(); } diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/TeamDeskLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/TeamDeskLinkedService.java index 0d6a2d4079ad..9c85ea42a2c6 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/TeamDeskLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/TeamDeskLinkedService.java @@ -194,6 +194,15 @@ public TeamDeskLinkedService setEncryptedCredential(Object encryptedCredential) return this; } + /** + * {@inheritDoc} + */ + @Override + public TeamDeskLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -236,6 +245,7 @@ public TeamDeskLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -282,7 +292,9 @@ public static TeamDeskLinkedService fromJson(JsonReader jsonReader) throws IOExc String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedTeamDeskLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedTeamDeskLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedTeamDeskLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/TeradataImportCommand.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/TeradataImportCommand.java new file mode 100644 index 000000000000..b764ea5c2fc5 --- /dev/null +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/TeradataImportCommand.java @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.analytics.synapse.artifacts.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; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Teradata import command settings. + */ +@Fluent +public final class TeradataImportCommand extends ImportSettings { + /* + * The import setting type. + */ + private String type = "TeradataImportCommand"; + + /* + * Additional format options for Teradata Copy Command. The format options only applies to direct copy from CSV + * source. Type: key value pairs (value should be string type) (or Expression with resultType object). Example: + * "additionalFormatOptions": { "timeFormat": "HHhMImSSs" } + */ + private Object additionalFormatOptions; + + /** + * Creates an instance of TeradataImportCommand class. + */ + public TeradataImportCommand() { + } + + /** + * Get the type property: The import setting type. + * + * @return the type value. + */ + @Override + public String getType() { + return this.type; + } + + /** + * Get the additionalFormatOptions property: Additional format options for Teradata Copy Command. The format options + * only applies to direct copy from CSV source. Type: key value pairs (value should be string type) (or Expression + * with resultType object). Example: "additionalFormatOptions": { "timeFormat": "HHhMImSSs" }. + * + * @return the additionalFormatOptions value. + */ + public Object getAdditionalFormatOptions() { + return this.additionalFormatOptions; + } + + /** + * Set the additionalFormatOptions property: Additional format options for Teradata Copy Command. The format options + * only applies to direct copy from CSV source. Type: key value pairs (value should be string type) (or Expression + * with resultType object). Example: "additionalFormatOptions": { "timeFormat": "HHhMImSSs" }. + * + * @param additionalFormatOptions the additionalFormatOptions value to set. + * @return the TeradataImportCommand object itself. + */ + public TeradataImportCommand setAdditionalFormatOptions(Object additionalFormatOptions) { + this.additionalFormatOptions = additionalFormatOptions; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type); + jsonWriter.writeUntypedField("additionalFormatOptions", this.additionalFormatOptions); + if (getAdditionalProperties() != null) { + for (Map.Entry additionalProperty : getAdditionalProperties().entrySet()) { + jsonWriter.writeUntypedField(additionalProperty.getKey(), additionalProperty.getValue()); + } + } + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of TeradataImportCommand from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of TeradataImportCommand 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 TeradataImportCommand. + */ + public static TeradataImportCommand fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + TeradataImportCommand deserializedTeradataImportCommand = new TeradataImportCommand(); + Map additionalProperties = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("type".equals(fieldName)) { + deserializedTeradataImportCommand.type = reader.getString(); + } else if ("additionalFormatOptions".equals(fieldName)) { + deserializedTeradataImportCommand.additionalFormatOptions = reader.readUntyped(); + } else { + if (additionalProperties == null) { + additionalProperties = new LinkedHashMap<>(); + } + + additionalProperties.put(fieldName, reader.readUntyped()); + } + } + deserializedTeradataImportCommand.setAdditionalProperties(additionalProperties); + + return deserializedTeradataImportCommand; + }); + } +} diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/TeradataLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/TeradataLinkedService.java index 386bc971aac5..6349e07fe9f6 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/TeradataLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/TeradataLinkedService.java @@ -48,6 +48,43 @@ public class TeradataLinkedService extends LinkedService { */ private SecretBase password; + /* + * SSL mode for connection. Valid values including: “Disable”, “Allow”, “Prefer”, “Require”, “Verify-CA”, + * “Verify-Full”. Default value is “Verify-Full”. Type: string (or Expression with resultType string). Only applied + * for version 2.0. + */ + private Object sslMode; + + /* + * The port numbers when connecting to server through non HTTPS/TLS connections. Type: integer (or Expression with + * resultType integer). Only used for V2. Only applied for version 2.0. + */ + private Object portNumber; + + /* + * The port numbers when connecting to server through HTTPS/TLS connections. Type: integer (or Expression with + * resultType integer). Only applied for version 2.0. + */ + private Object httpsPortNumber; + + /* + * Specifies whether to encrypt all communication with the Teradata database. Allowed values are 0 or 1. This + * setting will be ignored for HTTPS/TLS connections. Type: integer (or Expression with resultType integer). Only + * applied for version 2.0. + */ + private Object useDataEncryption; + + /* + * The character set to use for the connection. Type: string (or Expression with resultType string). Only applied + * for version 2.0. + */ + private Object characterSet; + + /* + * The maximum size of the response buffer for SQL requests, in bytes. Type: integer. Only applied for version 2.0. + */ + private Object maxRespSize; + /* * The encrypted credential used for authentication. Credentials are encrypted using the integration runtime * credential manager. Type: string (or Expression with resultType string). @@ -172,6 +209,142 @@ public TeradataLinkedService setPassword(SecretBase password) { return this; } + /** + * Get the sslMode property: SSL mode for connection. Valid values including: “Disable”, “Allow”, “Prefer”, + * “Require”, “Verify-CA”, “Verify-Full”. Default value is “Verify-Full”. Type: string (or Expression with + * resultType string). Only applied for version 2.0. + * + * @return the sslMode value. + */ + public Object getSslMode() { + return this.sslMode; + } + + /** + * Set the sslMode property: SSL mode for connection. Valid values including: “Disable”, “Allow”, “Prefer”, + * “Require”, “Verify-CA”, “Verify-Full”. Default value is “Verify-Full”. Type: string (or Expression with + * resultType string). Only applied for version 2.0. + * + * @param sslMode the sslMode value to set. + * @return the TeradataLinkedService object itself. + */ + public TeradataLinkedService setSslMode(Object sslMode) { + this.sslMode = sslMode; + return this; + } + + /** + * Get the portNumber property: The port numbers when connecting to server through non HTTPS/TLS connections. Type: + * integer (or Expression with resultType integer). Only used for V2. Only applied for version 2.0. + * + * @return the portNumber value. + */ + public Object getPortNumber() { + return this.portNumber; + } + + /** + * Set the portNumber property: The port numbers when connecting to server through non HTTPS/TLS connections. Type: + * integer (or Expression with resultType integer). Only used for V2. Only applied for version 2.0. + * + * @param portNumber the portNumber value to set. + * @return the TeradataLinkedService object itself. + */ + public TeradataLinkedService setPortNumber(Object portNumber) { + this.portNumber = portNumber; + return this; + } + + /** + * Get the httpsPortNumber property: The port numbers when connecting to server through HTTPS/TLS connections. Type: + * integer (or Expression with resultType integer). Only applied for version 2.0. + * + * @return the httpsPortNumber value. + */ + public Object getHttpsPortNumber() { + return this.httpsPortNumber; + } + + /** + * Set the httpsPortNumber property: The port numbers when connecting to server through HTTPS/TLS connections. Type: + * integer (or Expression with resultType integer). Only applied for version 2.0. + * + * @param httpsPortNumber the httpsPortNumber value to set. + * @return the TeradataLinkedService object itself. + */ + public TeradataLinkedService setHttpsPortNumber(Object httpsPortNumber) { + this.httpsPortNumber = httpsPortNumber; + return this; + } + + /** + * Get the useDataEncryption property: Specifies whether to encrypt all communication with the Teradata database. + * Allowed values are 0 or 1. This setting will be ignored for HTTPS/TLS connections. Type: integer (or Expression + * with resultType integer). Only applied for version 2.0. + * + * @return the useDataEncryption value. + */ + public Object getUseDataEncryption() { + return this.useDataEncryption; + } + + /** + * Set the useDataEncryption property: Specifies whether to encrypt all communication with the Teradata database. + * Allowed values are 0 or 1. This setting will be ignored for HTTPS/TLS connections. Type: integer (or Expression + * with resultType integer). Only applied for version 2.0. + * + * @param useDataEncryption the useDataEncryption value to set. + * @return the TeradataLinkedService object itself. + */ + public TeradataLinkedService setUseDataEncryption(Object useDataEncryption) { + this.useDataEncryption = useDataEncryption; + return this; + } + + /** + * Get the characterSet property: The character set to use for the connection. Type: string (or Expression with + * resultType string). Only applied for version 2.0. + * + * @return the characterSet value. + */ + public Object getCharacterSet() { + return this.characterSet; + } + + /** + * Set the characterSet property: The character set to use for the connection. Type: string (or Expression with + * resultType string). Only applied for version 2.0. + * + * @param characterSet the characterSet value to set. + * @return the TeradataLinkedService object itself. + */ + public TeradataLinkedService setCharacterSet(Object characterSet) { + this.characterSet = characterSet; + return this; + } + + /** + * Get the maxRespSize property: The maximum size of the response buffer for SQL requests, in bytes. Type: integer. + * Only applied for version 2.0. + * + * @return the maxRespSize value. + */ + public Object getMaxRespSize() { + return this.maxRespSize; + } + + /** + * Set the maxRespSize property: The maximum size of the response buffer for SQL requests, in bytes. Type: integer. + * Only applied for version 2.0. + * + * @param maxRespSize the maxRespSize value to set. + * @return the TeradataLinkedService object itself. + */ + public TeradataLinkedService setMaxRespSize(Object maxRespSize) { + this.maxRespSize = maxRespSize; + return this; + } + /** * Get the encryptedCredential property: The encrypted credential used for authentication. Credentials are encrypted * using the integration runtime credential manager. Type: string (or Expression with resultType string). @@ -194,6 +367,15 @@ public TeradataLinkedService setEncryptedCredential(Object encryptedCredential) return this; } + /** + * {@inheritDoc} + */ + @Override + public TeradataLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -236,6 +418,7 @@ public TeradataLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -246,6 +429,12 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { || authenticationType != null || username != null || password != null + || sslMode != null + || portNumber != null + || httpsPortNumber != null + || useDataEncryption != null + || characterSet != null + || maxRespSize != null || encryptedCredential != null) { jsonWriter.writeStartObject("typeProperties"); jsonWriter.writeUntypedField("connectionString", this.connectionString); @@ -254,6 +443,12 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { this.authenticationType == null ? null : this.authenticationType.toString()); jsonWriter.writeUntypedField("username", this.username); jsonWriter.writeJsonField("password", this.password); + jsonWriter.writeUntypedField("sslMode", this.sslMode); + jsonWriter.writeUntypedField("portNumber", this.portNumber); + jsonWriter.writeUntypedField("httpsPortNumber", this.httpsPortNumber); + jsonWriter.writeUntypedField("useDataEncryption", this.useDataEncryption); + jsonWriter.writeUntypedField("characterSet", this.characterSet); + jsonWriter.writeUntypedField("maxRespSize", this.maxRespSize); jsonWriter.writeUntypedField("encryptedCredential", this.encryptedCredential); jsonWriter.writeEndObject(); } @@ -281,7 +476,9 @@ public static TeradataLinkedService fromJson(JsonReader jsonReader) throws IOExc String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedTeradataLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedTeradataLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedTeradataLinkedService.setDescription(reader.getString()); @@ -310,6 +507,18 @@ public static TeradataLinkedService fromJson(JsonReader jsonReader) throws IOExc deserializedTeradataLinkedService.username = reader.readUntyped(); } else if ("password".equals(fieldName)) { deserializedTeradataLinkedService.password = SecretBase.fromJson(reader); + } else if ("sslMode".equals(fieldName)) { + deserializedTeradataLinkedService.sslMode = reader.readUntyped(); + } else if ("portNumber".equals(fieldName)) { + deserializedTeradataLinkedService.portNumber = reader.readUntyped(); + } else if ("httpsPortNumber".equals(fieldName)) { + deserializedTeradataLinkedService.httpsPortNumber = reader.readUntyped(); + } else if ("useDataEncryption".equals(fieldName)) { + deserializedTeradataLinkedService.useDataEncryption = reader.readUntyped(); + } else if ("characterSet".equals(fieldName)) { + deserializedTeradataLinkedService.characterSet = reader.readUntyped(); + } else if ("maxRespSize".equals(fieldName)) { + deserializedTeradataLinkedService.maxRespSize = reader.readUntyped(); } else if ("encryptedCredential".equals(fieldName)) { deserializedTeradataLinkedService.encryptedCredential = reader.readUntyped(); } else { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/TeradataSink.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/TeradataSink.java new file mode 100644 index 000000000000..30540721aba4 --- /dev/null +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/TeradataSink.java @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.analytics.synapse.artifacts.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; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * A copy activity Teradata sink. + */ +@Fluent +public final class TeradataSink extends CopySink { + /* + * Copy sink type. + */ + private String type = "TeradataSink"; + + /* + * Teradata import settings. + */ + private TeradataImportCommand importSettings; + + /** + * Creates an instance of TeradataSink class. + */ + public TeradataSink() { + } + + /** + * Get the type property: Copy sink type. + * + * @return the type value. + */ + @Override + public String getType() { + return this.type; + } + + /** + * Get the importSettings property: Teradata import settings. + * + * @return the importSettings value. + */ + public TeradataImportCommand getImportSettings() { + return this.importSettings; + } + + /** + * Set the importSettings property: Teradata import settings. + * + * @param importSettings the importSettings value to set. + * @return the TeradataSink object itself. + */ + public TeradataSink setImportSettings(TeradataImportCommand importSettings) { + this.importSettings = importSettings; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public TeradataSink setWriteBatchSize(Object writeBatchSize) { + super.setWriteBatchSize(writeBatchSize); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public TeradataSink setWriteBatchTimeout(Object writeBatchTimeout) { + super.setWriteBatchTimeout(writeBatchTimeout); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public TeradataSink setSinkRetryCount(Object sinkRetryCount) { + super.setSinkRetryCount(sinkRetryCount); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public TeradataSink setSinkRetryWait(Object sinkRetryWait) { + super.setSinkRetryWait(sinkRetryWait); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public TeradataSink setMaxConcurrentConnections(Object maxConcurrentConnections) { + super.setMaxConcurrentConnections(maxConcurrentConnections); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeUntypedField("writeBatchSize", getWriteBatchSize()); + jsonWriter.writeUntypedField("writeBatchTimeout", getWriteBatchTimeout()); + jsonWriter.writeUntypedField("sinkRetryCount", getSinkRetryCount()); + jsonWriter.writeUntypedField("sinkRetryWait", getSinkRetryWait()); + jsonWriter.writeUntypedField("maxConcurrentConnections", getMaxConcurrentConnections()); + jsonWriter.writeStringField("type", this.type); + jsonWriter.writeJsonField("importSettings", this.importSettings); + if (getAdditionalProperties() != null) { + for (Map.Entry additionalProperty : getAdditionalProperties().entrySet()) { + jsonWriter.writeUntypedField(additionalProperty.getKey(), additionalProperty.getValue()); + } + } + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of TeradataSink from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of TeradataSink 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 TeradataSink. + */ + public static TeradataSink fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + TeradataSink deserializedTeradataSink = new TeradataSink(); + Map additionalProperties = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("writeBatchSize".equals(fieldName)) { + deserializedTeradataSink.setWriteBatchSize(reader.readUntyped()); + } else if ("writeBatchTimeout".equals(fieldName)) { + deserializedTeradataSink.setWriteBatchTimeout(reader.readUntyped()); + } else if ("sinkRetryCount".equals(fieldName)) { + deserializedTeradataSink.setSinkRetryCount(reader.readUntyped()); + } else if ("sinkRetryWait".equals(fieldName)) { + deserializedTeradataSink.setSinkRetryWait(reader.readUntyped()); + } else if ("maxConcurrentConnections".equals(fieldName)) { + deserializedTeradataSink.setMaxConcurrentConnections(reader.readUntyped()); + } else if ("type".equals(fieldName)) { + deserializedTeradataSink.type = reader.getString(); + } else if ("importSettings".equals(fieldName)) { + deserializedTeradataSink.importSettings = TeradataImportCommand.fromJson(reader); + } else { + if (additionalProperties == null) { + additionalProperties = new LinkedHashMap<>(); + } + + additionalProperties.put(fieldName, reader.readUntyped()); + } + } + deserializedTeradataSink.setAdditionalProperties(additionalProperties); + + return deserializedTeradataSink; + }); + } +} diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/TumblingWindowTrigger.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/TumblingWindowTrigger.java index 9ac21cc78096..d670cbc57ea0 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/TumblingWindowTrigger.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/TumblingWindowTrigger.java @@ -76,11 +76,6 @@ public class TumblingWindowTrigger extends Trigger { */ private List dependsOn; - /* - * Indicates if trigger is running or not. Updated when Start/Stop APIs are called on the Trigger. - */ - private TriggerRuntimeState runtimeState; - /** * Creates an instance of TumblingWindowTrigger class. */ @@ -289,17 +284,6 @@ public TumblingWindowTrigger setDependsOn(List dependsOn) { return this; } - /** - * Get the runtimeState property: Indicates if trigger is running or not. Updated when Start/Stop APIs are called on - * the Trigger. - * - * @return the runtimeState value. - */ - @Override - public TriggerRuntimeState getRuntimeState() { - return this.runtimeState; - } - /** * {@inheritDoc} */ @@ -368,7 +352,8 @@ public static TumblingWindowTrigger fromJson(JsonReader jsonReader) throws IOExc if ("description".equals(fieldName)) { deserializedTumblingWindowTrigger.setDescription(reader.getString()); } else if ("runtimeState".equals(fieldName)) { - deserializedTumblingWindowTrigger.runtimeState = TriggerRuntimeState.fromString(reader.getString()); + deserializedTumblingWindowTrigger + .setRuntimeState(TriggerRuntimeState.fromString(reader.getString())); } else if ("annotations".equals(fieldName)) { List annotations = reader.readArray(reader1 -> reader1.readUntyped()); deserializedTumblingWindowTrigger.setAnnotations(annotations); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/TwilioLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/TwilioLinkedService.java index 5db26a3205b4..75578282c349 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/TwilioLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/TwilioLinkedService.java @@ -89,6 +89,15 @@ public TwilioLinkedService setPassword(SecretBase password) { return this; } + /** + * {@inheritDoc} + */ + @Override + public TwilioLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -131,6 +140,7 @@ public TwilioLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -167,7 +177,9 @@ public static TwilioLinkedService fromJson(JsonReader jsonReader) throws IOExcep String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedTwilioLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedTwilioLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedTwilioLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/VerticaLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/VerticaLinkedService.java index fbcc89e551cb..052534793d6f 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/VerticaLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/VerticaLinkedService.java @@ -28,6 +28,26 @@ public class VerticaLinkedService extends LinkedService { */ private Object connectionString; + /* + * Server name for connection. Type: string. + */ + private Object server; + + /* + * The port for the connection. Type: integer. + */ + private Object port; + + /* + * Username for authentication. Type: string. + */ + private Object uid; + + /* + * Database name for connection. Type: string. + */ + private Object database; + /* * The Azure key vault secret reference of password in connection string. */ @@ -77,6 +97,86 @@ public VerticaLinkedService setConnectionString(Object connectionString) { return this; } + /** + * Get the server property: Server name for connection. Type: string. + * + * @return the server value. + */ + public Object getServer() { + return this.server; + } + + /** + * Set the server property: Server name for connection. Type: string. + * + * @param server the server value to set. + * @return the VerticaLinkedService object itself. + */ + public VerticaLinkedService setServer(Object server) { + this.server = server; + return this; + } + + /** + * Get the port property: The port for the connection. Type: integer. + * + * @return the port value. + */ + public Object getPort() { + return this.port; + } + + /** + * Set the port property: The port for the connection. Type: integer. + * + * @param port the port value to set. + * @return the VerticaLinkedService object itself. + */ + public VerticaLinkedService setPort(Object port) { + this.port = port; + return this; + } + + /** + * Get the uid property: Username for authentication. Type: string. + * + * @return the uid value. + */ + public Object getUid() { + return this.uid; + } + + /** + * Set the uid property: Username for authentication. Type: string. + * + * @param uid the uid value to set. + * @return the VerticaLinkedService object itself. + */ + public VerticaLinkedService setUid(Object uid) { + this.uid = uid; + return this; + } + + /** + * Get the database property: Database name for connection. Type: string. + * + * @return the database value. + */ + public Object getDatabase() { + return this.database; + } + + /** + * Set the database property: Database name for connection. Type: string. + * + * @param database the database value to set. + * @return the VerticaLinkedService object itself. + */ + public VerticaLinkedService setDatabase(Object database) { + this.database = database; + return this; + } + /** * Get the pwd property: The Azure key vault secret reference of password in connection string. * @@ -119,6 +219,15 @@ public VerticaLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public VerticaLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -161,14 +270,25 @@ public VerticaLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); jsonWriter.writeArrayField("annotations", getAnnotations(), (writer, element) -> writer.writeUntyped(element)); jsonWriter.writeStringField("type", this.type); - if (connectionString != null || pwd != null || encryptedCredential != null) { + if (connectionString != null + || server != null + || port != null + || uid != null + || database != null + || pwd != null + || encryptedCredential != null) { jsonWriter.writeStartObject("typeProperties"); jsonWriter.writeUntypedField("connectionString", this.connectionString); + jsonWriter.writeUntypedField("server", this.server); + jsonWriter.writeUntypedField("port", this.port); + jsonWriter.writeUntypedField("uid", this.uid); + jsonWriter.writeUntypedField("database", this.database); jsonWriter.writeJsonField("pwd", this.pwd); jsonWriter.writeUntypedField("encryptedCredential", this.encryptedCredential); jsonWriter.writeEndObject(); @@ -197,7 +317,9 @@ public static VerticaLinkedService fromJson(JsonReader jsonReader) throws IOExce String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedVerticaLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedVerticaLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedVerticaLinkedService.setDescription(reader.getString()); @@ -217,6 +339,14 @@ public static VerticaLinkedService fromJson(JsonReader jsonReader) throws IOExce if ("connectionString".equals(fieldName)) { deserializedVerticaLinkedService.connectionString = reader.readUntyped(); + } else if ("server".equals(fieldName)) { + deserializedVerticaLinkedService.server = reader.readUntyped(); + } else if ("port".equals(fieldName)) { + deserializedVerticaLinkedService.port = reader.readUntyped(); + } else if ("uid".equals(fieldName)) { + deserializedVerticaLinkedService.uid = reader.readUntyped(); + } else if ("database".equals(fieldName)) { + deserializedVerticaLinkedService.database = reader.readUntyped(); } else if ("pwd".equals(fieldName)) { deserializedVerticaLinkedService.pwd = AzureKeyVaultSecretReference.fromJson(reader); } else if ("encryptedCredential".equals(fieldName)) { diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/WarehouseLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/WarehouseLinkedService.java index 3d99e0641f8f..5fba8d2d36a0 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/WarehouseLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/WarehouseLinkedService.java @@ -295,6 +295,15 @@ public WarehouseLinkedService setServicePrincipalCredential(SecretBase servicePr return this; } + /** + * {@inheritDoc} + */ + @Override + public WarehouseLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -337,6 +346,7 @@ public WarehouseLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -388,7 +398,9 @@ public static WarehouseLinkedService fromJson(JsonReader jsonReader) throws IOEx String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedWarehouseLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedWarehouseLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedWarehouseLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/WebLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/WebLinkedService.java index 4102b38808ff..e4ce48a3b82a 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/WebLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/WebLinkedService.java @@ -64,6 +64,15 @@ public WebLinkedService setTypeProperties(WebLinkedServiceTypeProperties typePro return this; } + /** + * {@inheritDoc} + */ + @Override + public WebLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -106,6 +115,7 @@ public WebLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -137,7 +147,9 @@ public static WebLinkedService fromJson(JsonReader jsonReader) throws IOExceptio String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedWebLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedWebLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedWebLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/XeroLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/XeroLinkedService.java index f56fb625664f..6196eaf3e082 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/XeroLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/XeroLinkedService.java @@ -258,6 +258,15 @@ public XeroLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public XeroLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -300,6 +309,7 @@ public XeroLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -349,7 +359,9 @@ public static XeroLinkedService fromJson(JsonReader jsonReader) throws IOExcepti String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedXeroLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedXeroLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedXeroLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ZendeskLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ZendeskLinkedService.java index b07159eed1f8..6745279f5bec 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ZendeskLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ZendeskLinkedService.java @@ -194,6 +194,15 @@ public ZendeskLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public ZendeskLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -236,6 +245,7 @@ public ZendeskLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -282,7 +292,9 @@ public static ZendeskLinkedService fromJson(JsonReader jsonReader) throws IOExce String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedZendeskLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedZendeskLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedZendeskLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ZohoLinkedService.java b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ZohoLinkedService.java index 4f54c97050ae..7e0c4ebbde89 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ZohoLinkedService.java +++ b/sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/ZohoLinkedService.java @@ -227,6 +227,15 @@ public ZohoLinkedService setEncryptedCredential(Object encryptedCredential) { return this; } + /** + * {@inheritDoc} + */ + @Override + public ZohoLinkedService setVersion(String version) { + super.setVersion(version); + return this; + } + /** * {@inheritDoc} */ @@ -269,6 +278,7 @@ public ZohoLinkedService setAnnotations(List annotations) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("version", getVersion()); jsonWriter.writeJsonField("connectVia", getConnectVia()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeMapField("parameters", getParameters(), (writer, element) -> writer.writeJson(element)); @@ -316,7 +326,9 @@ public static ZohoLinkedService fromJson(JsonReader jsonReader) throws IOExcepti String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectVia".equals(fieldName)) { + if ("version".equals(fieldName)) { + deserializedZohoLinkedService.setVersion(reader.getString()); + } else if ("connectVia".equals(fieldName)) { deserializedZohoLinkedService.setConnectVia(IntegrationRuntimeReference.fromJson(reader)); } else if ("description".equals(fieldName)) { deserializedZohoLinkedService.setDescription(reader.getString()); diff --git a/sdk/synapse/azure-analytics-synapse-artifacts/swagger/README.md b/sdk/synapse/azure-analytics-synapse-artifacts/swagger/README.md index 59dcd742140d..ff822a6a2c05 100644 --- a/sdk/synapse/azure-analytics-synapse-artifacts/swagger/README.md +++ b/sdk/synapse/azure-analytics-synapse-artifacts/swagger/README.md @@ -34,6 +34,6 @@ models-subpackage: models required-parameter-client-methods: true security: AADToken security-scopes: https://dev.azuresynapse.net/.default -require: https://github.com/Azure/azure-rest-api-specs/blob/02e1bd495ad6215aacec5d636a5ef7ad6f20281e/specification/synapse/data-plane/readme.md +require: https://github.com/Azure/azure-rest-api-specs/blob/0da14ec4f475435b9d7d0ba06e49f05a5daac226/specification/synapse/data-plane/readme.md tag: package-artifacts-composite-v7 ``` diff --git a/sdk/synapse/azure-analytics-synapse-managedprivateendpoints/README.md b/sdk/synapse/azure-analytics-synapse-managedprivateendpoints/README.md index 7ee57b1e9389..0023aef0a096 100644 --- a/sdk/synapse/azure-analytics-synapse-managedprivateendpoints/README.md +++ b/sdk/synapse/azure-analytics-synapse-managedprivateendpoints/README.md @@ -14,7 +14,7 @@ Maven dependency for the Azure Synapse managed private endpoints client library. com.azure azure-analytics-synapse-managedprivateendpoints - 1.0.0-beta.5 + 1.0.0-beta.6 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/synapse/azure-analytics-synapse-managedprivateendpoints/pom.xml b/sdk/synapse/azure-analytics-synapse-managedprivateendpoints/pom.xml index 8a0aaa8416b4..741ec3eff5ab 100644 --- a/sdk/synapse/azure-analytics-synapse-managedprivateendpoints/pom.xml +++ b/sdk/synapse/azure-analytics-synapse-managedprivateendpoints/pom.xml @@ -45,30 +45,30 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/synapse/azure-analytics-synapse-monitoring/README.md b/sdk/synapse/azure-analytics-synapse-monitoring/README.md index 6ec637a358fc..082718a611fa 100644 --- a/sdk/synapse/azure-analytics-synapse-monitoring/README.md +++ b/sdk/synapse/azure-analytics-synapse-monitoring/README.md @@ -14,7 +14,7 @@ Maven dependency for the Azure Synapse monitoring client library. Add it to your com.azure azure-analytics-synapse-monitoring - 1.0.0-beta.4 + 1.0.0-beta.5 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/synapse/azure-analytics-synapse-monitoring/pom.xml b/sdk/synapse/azure-analytics-synapse-monitoring/pom.xml index e3e85b331e06..465ab86cfeee 100644 --- a/sdk/synapse/azure-analytics-synapse-monitoring/pom.xml +++ b/sdk/synapse/azure-analytics-synapse-monitoring/pom.xml @@ -45,30 +45,30 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/synapse/azure-analytics-synapse-spark/README.md b/sdk/synapse/azure-analytics-synapse-spark/README.md index f3d1a5f00486..93fa900385b3 100644 --- a/sdk/synapse/azure-analytics-synapse-spark/README.md +++ b/sdk/synapse/azure-analytics-synapse-spark/README.md @@ -14,7 +14,7 @@ Maven dependency for the Azure Synapse Spark client library. Add it to your proj com.azure azure-analytics-synapse-spark - 1.0.0-beta.4 + 1.0.0-beta.6 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/synapse/azure-analytics-synapse-spark/pom.xml b/sdk/synapse/azure-analytics-synapse-spark/pom.xml index 4deae68c92c4..12bd8f0826dc 100644 --- a/sdk/synapse/azure-analytics-synapse-spark/pom.xml +++ b/sdk/synapse/azure-analytics-synapse-spark/pom.xml @@ -51,30 +51,30 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/synapse/azure-resourcemanager-synapse/README.md b/sdk/synapse/azure-resourcemanager-synapse/README.md index c0a3a541f737..60bd1499ddda 100644 --- a/sdk/synapse/azure-resourcemanager-synapse/README.md +++ b/sdk/synapse/azure-resourcemanager-synapse/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-synapse - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fsynapse%2Fazure-resourcemanager-synapse%2FREADME.png) + diff --git a/sdk/synapse/azure-resourcemanager-synapse/pom.xml b/sdk/synapse/azure-resourcemanager-synapse/pom.xml index 44f8070a3bf3..ef07f5b8c2a0 100644 --- a/sdk/synapse/azure-resourcemanager-synapse/pom.xml +++ b/sdk/synapse/azure-resourcemanager-synapse/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/tables/azure-data-tables-perf/pom.xml b/sdk/tables/azure-data-tables-perf/pom.xml index 04bb061128d6..79432dc5b5b4 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.27.0-beta.4 + 1.27.0-beta.8 com.azure @@ -41,12 +41,12 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 diff --git a/sdk/tables/azure-data-tables/CHANGELOG.md b/sdk/tables/azure-data-tables/CHANGELOG.md index 1972da882ded..970d22c018c3 100644 --- a/sdk/tables/azure-data-tables/CHANGELOG.md +++ b/sdk/tables/azure-data-tables/CHANGELOG.md @@ -10,6 +10,27 @@ ### Other Changes +## 12.5.2 (2025-02-25) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core-http-netty` from `1.15.9` to version `1.15.10`. +- Upgraded `azure-core` from `1.55.1` to version `1.55.2`. + + +## 12.5.1 (2025-02-18) + +### Bugs Fixed + +- [Fixed the issue](https://github.com/Azure/azure-sdk-for-java/issues/44005) where `Errors` were being improperly cast into `RuntimeException`. + +### Other Changes + +- Upgraded `azure-core` from `1.54.1` to version `1.55.1`. +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.9`. + ## 12.5.0 (2024-11-21) ### Features Added diff --git a/sdk/tables/azure-data-tables/README.md b/sdk/tables/azure-data-tables/README.md index c1b9213fdb27..1b4ff9503ef7 100644 --- a/sdk/tables/azure-data-tables/README.md +++ b/sdk/tables/azure-data-tables/README.md @@ -46,7 +46,7 @@ add the direct dependency to your project as follows. com.azure azure-data-tables - 12.5.0 + 12.6.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -379,4 +379,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [storage_account_create_cli]: https://learn.microsoft.com/azure/storage/common/storage-account-create?tabs=azure-cli [storage_account_create_portal]: https://learn.microsoft.com/azure/storage/common/storage-account-create?tabs=azure-portal -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Ftables%2Fazure-data-tables%2FREADME.png) + diff --git a/sdk/tables/azure-data-tables/pom.xml b/sdk/tables/azure-data-tables/pom.xml index 199680c83df5..62e401db4d90 100644 --- a/sdk/tables/azure-data-tables/pom.xml +++ b/sdk/tables/azure-data-tables/pom.xml @@ -53,33 +53,33 @@ Licensed under the MIT License. com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-xml - 1.1.0 + 1.2.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/tables/azure-data-tables/src/main/java/com/azure/data/tables/implementation/TableUtils.java b/sdk/tables/azure-data-tables/src/main/java/com/azure/data/tables/implementation/TableUtils.java index 51e53c9a6663..3075e0d8bb67 100644 --- a/sdk/tables/azure-data-tables/src/main/java/com/azure/data/tables/implementation/TableUtils.java +++ b/sdk/tables/azure-data-tables/src/main/java/com/azure/data/tables/implementation/TableUtils.java @@ -344,7 +344,7 @@ public static Response callWithOptionalTimeout(Supplier> call ClientLogger logger, boolean skip409Logging) { try { return callHandler(callable, timeout, logger); - } catch (Throwable thrown) { + } catch (Exception thrown) { Throwable exception = mapThrowableToTableServiceException(thrown); if (exception instanceof TableServiceException) { TableServiceException e = (TableServiceException) exception; diff --git a/sdk/tables/azure-data-tables/src/samples/README.md b/sdk/tables/azure-data-tables/src/samples/README.md index 2d8611fd5c91..962905f060f2 100644 --- a/sdk/tables/azure-data-tables/src/samples/README.md +++ b/sdk/tables/azure-data-tables/src/samples/README.md @@ -61,4 +61,4 @@ This project welcomes contributions and suggestions. See [Contributing][sdk_read [sample_async_client_java_doc_code_snippets]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/tables/azure-data-tables/src/samples/java/com/azure/data/tables/codesnippets/TableServiceAsyncClientJavaDocCodeSnippets.java [sample_sync_client_java_doc_code_snippets]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/tables/azure-data-tables/src/samples/java/com/azure/data/tables/codesnippets/TableServiceClientJavaDocCodeSnippets.java -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%tables%2Fazure-data-tables%2Fsrc%2Fsamples%2README.png) + diff --git a/sdk/tables/azure-data-tables/src/test/java/com/azure/data/tables/TableClientBuilderTest.java b/sdk/tables/azure-data-tables/src/test/java/com/azure/data/tables/TableClientBuilderTest.java index 9b28a496e1ce..feb03167a571 100644 --- a/sdk/tables/azure-data-tables/src/test/java/com/azure/data/tables/TableClientBuilderTest.java +++ b/sdk/tables/azure-data-tables/src/test/java/com/azure/data/tables/TableClientBuilderTest.java @@ -17,6 +17,8 @@ import com.azure.core.test.utils.MockTokenCredential; import com.azure.core.util.ClientOptions; import com.azure.core.util.Header; +import com.azure.core.util.logging.ClientLogger; +import com.azure.data.tables.implementation.TableUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; @@ -269,6 +271,15 @@ public void multipleFormsOfAuthenticationPresent() { .buildAsyncClient()); } + @Test + void nonRuntimeExceptionsDontGetCasted() { + assertThrows(Error.class, () -> { + TableUtils.callWithOptionalTimeout(() -> { + throw new NoClassDefFoundError("This is an error"); + }, null, new ClientLogger(TableClientTest.class)); + }); + } + @Test public void bothRetryOptionsAndRetryPolicyPresent() { assertThrows(IllegalStateException.class, diff --git a/sdk/tables/azure-data-tables/src/test/java/com/azure/data/tables/TableClientTest.java b/sdk/tables/azure-data-tables/src/test/java/com/azure/data/tables/TableClientTest.java index 34f900749000..d162006e135a 100644 --- a/sdk/tables/azure-data-tables/src/test/java/com/azure/data/tables/TableClientTest.java +++ b/sdk/tables/azure-data-tables/src/test/java/com/azure/data/tables/TableClientTest.java @@ -47,13 +47,7 @@ import java.util.Map; import java.util.UUID; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -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 static org.junit.jupiter.api.Assertions.*; /** * Tests {@link TableClient}. diff --git a/sdk/template/azure-sdk-template-three/README.md b/sdk/template/azure-sdk-template-three/README.md index 8f46c120be9b..2e9d7ed385cc 100644 --- a/sdk/template/azure-sdk-template-three/README.md +++ b/sdk/template/azure-sdk-template-three/README.md @@ -154,4 +154,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ [coc_contact]: mailto:opencode@microsoft.com -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Ftemplate%2Fazure-sdk-template%2FREADME.png) + diff --git a/sdk/template/azure-sdk-template-three/pom.xml b/sdk/template/azure-sdk-template-three/pom.xml index 7295eea4af45..e27d3b9acdb9 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.54.1 + 1.55.3 com.azure diff --git a/sdk/template/azure-sdk-template-two/README.md b/sdk/template/azure-sdk-template-two/README.md index 4b223bc304d8..4a8c0ad99e88 100644 --- a/sdk/template/azure-sdk-template-two/README.md +++ b/sdk/template/azure-sdk-template-two/README.md @@ -154,4 +154,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ [coc_contact]: mailto:opencode@microsoft.com -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Ftemplate%2Fazure-sdk-template%2FREADME.png) + diff --git a/sdk/template/azure-sdk-template-two/pom.xml b/sdk/template/azure-sdk-template-two/pom.xml index 42c100f431b4..0192dbfdb23a 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.54.1 + 1.55.3 com.azure diff --git a/sdk/template/azure-sdk-template/README.md b/sdk/template/azure-sdk-template/README.md index fc1cc499984c..f1ce51214803 100644 --- a/sdk/template/azure-sdk-template/README.md +++ b/sdk/template/azure-sdk-template/README.md @@ -154,4 +154,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ [coc_contact]: mailto:opencode@microsoft.com -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Ftemplate%2Fazure-sdk-template%2FREADME.png) + diff --git a/sdk/template/azure-sdk-template/pom.xml b/sdk/template/azure-sdk-template/pom.xml index ab8e3128acae..5ce7fd78d826 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.54.1 + 1.55.3 org.junit.jupiter diff --git a/sdk/template/azure-template-perf/README.md b/sdk/template/azure-template-perf/README.md index 13d42f5b6f7d..5f689213b599 100644 --- a/sdk/template/azure-template-perf/README.md +++ b/sdk/template/azure-template-perf/README.md @@ -30,4 +30,4 @@ For details on contributing to this repository, see the [contributing guide](htt 1. Push to the branch (`git push origin my-new-feature`) 1. Create new Pull Request -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%template%2Fperf-test-core%2FREADME.png) + diff --git a/sdk/template/azure-template-perf/pom.xml b/sdk/template/azure-template-perf/pom.xml index 7b1e262e9bbd..1eb8cbe7b86f 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.54.1 + 1.55.3 diff --git a/sdk/template/azure-template-stress/pom.xml b/sdk/template/azure-template-stress/pom.xml index 3ef01a70d1f8..0be5a72c1e01 100644 --- a/sdk/template/azure-template-stress/pom.xml +++ b/sdk/template/azure-template-stress/pom.xml @@ -33,33 +33,33 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-http-okhttp - 1.12.6 + 1.12.10 com.azure azure-core-http-jdk-httpclient - 1.0.0-beta.19 + 1.0.3 com.azure azure-core-http-vertx - 1.0.0-beta.24 + 1.0.3 io.vertx vertx-codegen - 4.5.10 + 4.5.13 provided @@ -70,18 +70,18 @@ com.azure - azure-monitor-opentelemetry-exporter - 1.0.0-beta.31 + azure-monitor-opentelemetry-autoconfigure + 1.0.0 io.opentelemetry.instrumentation opentelemetry-runtime-telemetry-java8 - 2.9.0-alpha + 2.12.0-alpha io.opentelemetry.instrumentation opentelemetry-logback-appender-1.0 - 2.9.0-alpha + 2.12.0-alpha @@ -95,10 +95,10 @@ - io.opentelemetry.instrumentation:opentelemetry-runtime-telemetry-java8:[2.9.0-alpha] - io.opentelemetry.instrumentation:opentelemetry-logback-appender-1.0:[2.9.0-alpha] + io.opentelemetry.instrumentation:opentelemetry-runtime-telemetry-java8:[2.12.0-alpha] + io.opentelemetry.instrumentation:opentelemetry-logback-appender-1.0:[2.12.0-alpha] ch.qos.logback:logback-classic:[1.3.14] - io.vertx:vertx-codegen:[4.5.10] + io.vertx:vertx-codegen:[4.5.13] diff --git a/sdk/template/azure-template-stress/src/main/java/com/azure/sdk/template/stress/util/TelemetryHelper.java b/sdk/template/azure-template-stress/src/main/java/com/azure/sdk/template/stress/util/TelemetryHelper.java index 02e6bf2211bc..c14af3da571a 100644 --- a/sdk/template/azure-template-stress/src/main/java/com/azure/sdk/template/stress/util/TelemetryHelper.java +++ b/sdk/template/azure-template-stress/src/main/java/com/azure/sdk/template/stress/util/TelemetryHelper.java @@ -5,7 +5,7 @@ import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; -import com.azure.monitor.opentelemetry.exporter.AzureMonitorExporter; +import com.azure.monitor.opentelemetry.autoconfigure.AzureMonitorAutoConfigure; import com.azure.perf.test.core.PerfStressOptions; import com.azure.sdk.template.stress.StressOptions; import io.opentelemetry.api.GlobalOpenTelemetry; @@ -87,7 +87,7 @@ public static void init() { AutoConfiguredOpenTelemetrySdkBuilder sdkBuilder = AutoConfiguredOpenTelemetrySdk.builder(); String applicationInsightsConnectionString = System.getenv("APPLICATIONINSIGHTS_CONNECTION_STRING"); if (applicationInsightsConnectionString != null) { - AzureMonitorExporter.customize(sdkBuilder, applicationInsightsConnectionString); + AzureMonitorAutoConfigure.customize(sdkBuilder, applicationInsightsConnectionString); } else { System.setProperty("otel.traces.exporter", "none"); System.setProperty("otel.logs.exporter", "none"); diff --git a/sdk/terraform/azure-resourcemanager-terraform/README.md b/sdk/terraform/azure-resourcemanager-terraform/README.md index 68125967b7b9..e046b66d1d6d 100644 --- a/sdk/terraform/azure-resourcemanager-terraform/README.md +++ b/sdk/terraform/azure-resourcemanager-terraform/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-terraform - 1.0.0-beta.1 + 1.0.0-beta.2 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fterraform%2Fazure-resourcemanager-terraform%2FREADME.png) + diff --git a/sdk/terraform/azure-resourcemanager-terraform/pom.xml b/sdk/terraform/azure-resourcemanager-terraform/pom.xml index e178638ca375..3b548e16da9b 100644 --- a/sdk/terraform/azure-resourcemanager-terraform/pom.xml +++ b/sdk/terraform/azure-resourcemanager-terraform/pom.xml @@ -52,23 +52,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/terraform/azure-resourcemanager-terraform/src/main/java/com/azure/resourcemanager/terraform/AzureTerraformManager.java b/sdk/terraform/azure-resourcemanager-terraform/src/main/java/com/azure/resourcemanager/terraform/AzureTerraformManager.java index ff45127c224a..d1e6fbaa4906 100644 --- a/sdk/terraform/azure-resourcemanager-terraform/src/main/java/com/azure/resourcemanager/terraform/AzureTerraformManager.java +++ b/sdk/terraform/azure-resourcemanager-terraform/src/main/java/com/azure/resourcemanager/terraform/AzureTerraformManager.java @@ -22,6 +22,7 @@ import com.azure.core.http.policy.UserAgentPolicy; import com.azure.core.management.profile.AzureProfile; import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.terraform.fluent.AzureTerraformClient; import com.azure.resourcemanager.terraform.implementation.AzureTerraformClientBuilder; @@ -33,6 +34,7 @@ import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; @@ -98,6 +100,9 @@ public static Configurable configure() { */ public static final class Configurable { private static final ClientLogger LOGGER = new ClientLogger(Configurable.class); + private static final String SDK_VERSION = "version"; + private static final Map PROPERTIES + = CoreUtils.getProperties("azure-resourcemanager-terraform.properties"); private HttpClient httpClient; private HttpLogOptions httpLogOptions; @@ -205,12 +210,14 @@ public AzureTerraformManager authenticate(TokenCredential credential, AzureProfi Objects.requireNonNull(credential, "'credential' cannot be null."); Objects.requireNonNull(profile, "'profile' cannot be null."); + String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); + StringBuilder userAgentBuilder = new StringBuilder(); userAgentBuilder.append("azsdk-java") .append("-") .append("com.azure.resourcemanager.terraform") .append("/") - .append("1.0.0-beta.1"); + .append(clientVersion); if (!Configuration.getGlobalConfiguration().get("AZURE_TELEMETRY_DISABLED", false)) { userAgentBuilder.append(" (") .append(Configuration.getGlobalConfiguration().get("java.version")) diff --git a/sdk/terraform/azure-resourcemanager-terraform/src/main/resources/azure-resourcemanager-terraform.properties b/sdk/terraform/azure-resourcemanager-terraform/src/main/resources/azure-resourcemanager-terraform.properties new file mode 100644 index 000000000000..defbd48204e4 --- /dev/null +++ b/sdk/terraform/azure-resourcemanager-terraform/src/main/resources/azure-resourcemanager-terraform.properties @@ -0,0 +1 @@ +version=${project.version} diff --git a/sdk/textanalytics/azure-ai-textanalytics-perf/pom.xml b/sdk/textanalytics/azure-ai-textanalytics-perf/pom.xml index 17f78e063165..d5a233f2afd3 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.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 diff --git a/sdk/textanalytics/azure-ai-textanalytics/CHANGELOG.md b/sdk/textanalytics/azure-ai-textanalytics/CHANGELOG.md index 22048ec51476..1e6f8f921a15 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/CHANGELOG.md +++ b/sdk/textanalytics/azure-ai-textanalytics/CHANGELOG.md @@ -10,6 +10,17 @@ ### Other Changes +## 5.5.5 (2025-02-25) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`. +- Upgraded `azure-json` from `1.3.0` to version `1.4.0`. +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. + + ## 5.5.4 (2024-12-04) ### Other Changes @@ -19,6 +30,7 @@ - Upgraded `azure-core` from `1.53.0` to version `1.54.1`. - Upgraded `azure-core-http-netty` from `1.15.5` to version `1.15.7`. + ## 5.5.3 (2024-10-27) ### Other Changes diff --git a/sdk/textanalytics/azure-ai-textanalytics/README.md b/sdk/textanalytics/azure-ai-textanalytics/README.md index fa10826e9fd1..682ccfbebb0c 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/README.md +++ b/sdk/textanalytics/azure-ai-textanalytics/README.md @@ -63,7 +63,7 @@ add the direct dependency to your project as follows. com.azure azure-ai-textanalytics - 5.5.0 + 5.6.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -142,7 +142,7 @@ Authentication with AAD requires some initial setup: com.azure azure-identity - 1.14.2 + 1.15.3 ``` [//]: # ({x-version-update-end}) @@ -489,4 +489,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [recognize_custom_entities_sample]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/lro/RecognizeCustomEntities.java [single_label_classification_sample]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/lro/SingleLabelClassifyDocument.java -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Ftextanalytics%2Fazure-ai-textanalytics%2FREADME.png) + diff --git a/sdk/textanalytics/azure-ai-textanalytics/pom.xml b/sdk/textanalytics/azure-ai-textanalytics/pom.xml index 03734b3e3923..c9f386d2c8ef 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/pom.xml +++ b/sdk/textanalytics/azure-ai-textanalytics/pom.xml @@ -49,17 +49,17 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-json - 1.3.0 + 1.5.0 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/README.md b/sdk/textanalytics/azure-ai-textanalytics/src/samples/README.md index dd74a2b1b892..db9a18867ef3 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/samples/README.md +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/README.md @@ -162,4 +162,4 @@ This project welcomes contributions and suggestions. Find [more contributing][SD [sample_abstractive_text_summarization]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/lro/AbstractiveSummarization.java [sample_extractive_text_summarization]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/lro/ExtractiveSummarization.java -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Ftextanalytics%2Fazure-ai-textanalytics%2FREADME.png) + diff --git a/sdk/timeseriesinsights/azure-resourcemanager-timeseriesinsights/README.md b/sdk/timeseriesinsights/azure-resourcemanager-timeseriesinsights/README.md index a7dc3e328e6a..a68c8985da07 100644 --- a/sdk/timeseriesinsights/azure-resourcemanager-timeseriesinsights/README.md +++ b/sdk/timeseriesinsights/azure-resourcemanager-timeseriesinsights/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-timeseriesinsights - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Ftimeseriesinsights%2Fazure-resourcemanager-timeseriesinsights%2FREADME.png) + diff --git a/sdk/timeseriesinsights/azure-resourcemanager-timeseriesinsights/pom.xml b/sdk/timeseriesinsights/azure-resourcemanager-timeseriesinsights/pom.xml index 4cdf5758ad33..ccaa6937c898 100644 --- a/sdk/timeseriesinsights/azure-resourcemanager-timeseriesinsights/pom.xml +++ b/sdk/timeseriesinsights/azure-resourcemanager-timeseriesinsights/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/tools/azure-openrewrite/CHANGELOG.md b/sdk/tools/azure-openrewrite/CHANGELOG.md new file mode 100644 index 000000000000..8b33f0fedccc --- /dev/null +++ b/sdk/tools/azure-openrewrite/CHANGELOG.md @@ -0,0 +1,11 @@ +# Release History + +## 1.0.0-beta.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes \ No newline at end of file diff --git a/sdk/tools/azure-openrewrite/MIGRATION.md b/sdk/tools/azure-openrewrite/MIGRATION.md new file mode 100644 index 000000000000..24410baff7da --- /dev/null +++ b/sdk/tools/azure-openrewrite/MIGRATION.md @@ -0,0 +1,89 @@ +# Azure Code Migration with OpenRewrite + +This library contains integrations for OpenRewrite with Maven for code migrating Azure SDK libraries +such as `azure-core` to `azure-core-v2`. + +## Setup + +### Prerequisites +The following tools are required to build and execute this project: +- Java (version 8 or higher) +- Maven + +### Recipe Configuration + +The migration recipe is defined in the `azure-openrewrite` module as detailed below: + +```yaml +### Recipe Configuration for OpenRewrite +type: specs.openrewrite.org/v1beta/recipe +name: com.azure.openrewrite.migrateToVNext +displayName: Migrate from azure-core to azure-core-v2 +description: This recipe migrates the azure sdk libraries from azure-core to azure-core-v2 and clientcore libraries. +recipeList: + ... +``` +You can find the full recipe configuration in the `rewrite.yml` file [here](https://github.com/Azure/azsdk-java-rewrite-recipes/blob/main/rewrite-java-core/src/main/resources/META-INF/rewrite/rewrite.yml). + + +## Usage +### Maven Plugin Configuration +The OpenRewrite Maven plugin is configured in the `rewrite-java-core` module to run the migration recipe on the sample project +as follows: +```xml + + org.openrewrite.maven + rewrite-maven-plugin + 5.7.1 + + + com.azure.openrewrite.migrateToVNext + + + + + com.azure + azure-openrewrite + 1.0.0 + + + +``` +The plugin configuration is defined in the `pom.xml` file [here](https://github.com/Azure/azsdk-java-rewrite-recipes/blob/main/rewrite-sample/pom.xml). + +## Execution +The `rewrite-sample` module is configured to use the `openrewrite-maven-plugin` to run the OpenRewrite recipe on the sample project. +The `rewrite-sample` module contains the modules `azure-ai-translation-text-v1` and `azure-ai-translation-text-v2` +to demonstrate the migration of code from `azure-core` to `azure-core-v2`. + +**Note:** To execute the below commands, ensure that you are within the `rewrite-sample` directory. + +### Dry Run +To run the OpenRewrite recipe in dry-run mode, execute the following command: +```shell +mvn rewrite:dryRun +``` +If the above command is not recognised, execute the full version of the command: + +```shell +mvn org.openrewrite.maven:rewrite-maven-plugin:dryRun +``` + +This will generate a file `rewrite.patch` in `rewrite-sample/target/rewrite` directory. + +### Run (apply changes) +To actually apply the changes to the sample project, execute the following command: +```shell +mvn rewrite:run +``` +If the above command is not recognised, execute the full version of the command: + +```shell +mvn org.openrewrite.maven:rewrite-maven-plugin:run +``` + +## Testing +To run the unit tests for the OpenRewrite recipe, execute the following command: +```shell +mvn:test +``` diff --git a/sdk/tools/azure-openrewrite/README.MD b/sdk/tools/azure-openrewrite/README.MD new file mode 100644 index 000000000000..f2da1ab59bce --- /dev/null +++ b/sdk/tools/azure-openrewrite/README.MD @@ -0,0 +1,29 @@ +# Azure OpenRewrite Plugin library for Java + +The Azure OpenRewrite Plugin library for Java is a collection recipes that when used in conjunction with the +[OpenRewrite Plugin by Modern](https://docs.openrewrite.org/) allows the developers of the SDKs to write migration +recipes that can be used to automatically update the SDKs, elimination the need for tedious manual refactoring. + +## Getting started + +TBD + +## Key concepts + +TBD + +## Examples + +TBD + +## Troubleshooting + +TBD + +## Next steps + +TBD + +## Contributing + +TBD diff --git a/sdk/tools/azure-openrewrite/pom.xml b/sdk/tools/azure-openrewrite/pom.xml new file mode 100644 index 000000000000..1e3cc23110c2 --- /dev/null +++ b/sdk/tools/azure-openrewrite/pom.xml @@ -0,0 +1,326 @@ + + + 4.0.0 + + com.azure + azure-openrewrite + 1.0.0-beta.1 + + Microsoft Azure OpenRewrite Plugin library for Java + This module contains OpenRewrite recipe for migrating to next generation Microsoft Azure client libraries. + + + ${project.build.directory} + + + + + + org.openrewrite.recipe + rewrite-recipe-bom + 3.0.2 + pom + import + + + + + + + + org.openrewrite + rewrite-java + compile + + + + + org.openrewrite + rewrite-java-8 + test + + + + org.openrewrite + rewrite-java-11 + test + + + + org.openrewrite + rewrite-java-17 + test + + + + org.openrewrite + rewrite-java-21 + test + + + + + org.openrewrite + rewrite-maven + compile + + + com.azure + azure-core + 1.55.3 + test + + + org.openrewrite + rewrite-test + test + + + org.junit.jupiter + junit-jupiter-api + 5.11.2 + test + + + org.junit.jupiter + junit-jupiter-engine + 5.11.2 + test + + + + org.assertj + assertj-core + 3.22.0 + test + + + + com.fasterxml.jackson.core + jackson-core + 2.17.2 + + + + com.fasterxml.jackson.dataformat + jackson-dataformat-smile + 2.17.2 + + + com.fasterxml.jackson.core + jackson-databind + 2.17.2 + + + org.projectlombok + lombok + 1.18.34 + provided + + + + com.azure + azure-ai-translation-text + 1.1.1 + test + + + + com.azure + azure-storage-blob + 12.29.1 + test + + + + + + + + org.apache.maven.plugins + maven-pmd-plugin + 3.15.0 + + + + org.apache.maven.plugins + maven-source-plugin + 3.3.1 + + + attach-sources + + jar + + + ${packageOutputDirectory} + + + + + + + + org.apache.maven.plugins + maven-antrun-plugin + 3.1.0 + + + copy + package + + + + + + + run + + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.10.1 + + + attach-javadocs + + jar + + + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + 3.6.0 + + + com.azure + sdk-build-tools + 1.0.0 + + + com.puppycrawl.tools + checkstyle + 9.3 + + + + ${project.basedir}/../../../eng/code-quality-reports/src/main/resources/checkstyle/checkstyle.xml + ${project.basedir}/../../../eng/code-quality-reports/src/main/resources/checkstyle/checkstyle-suppressions.xml + ${project.basedir}/../../../eng/code-quality-reports/src/main/resources/checkstyle/java.header + samedir= + true + true + true + true + true + + + + + com.github.spotbugs + spotbugs-maven-plugin + 4.8.3.1 + + + com.azure + sdk-build-tools + 1.0.0 + + + com.github.spotbugs + spotbugs + 4.8.3 + + + + org.ow2.asm + asm + 9.7.1 + + + + max + Low + true + ${project.build.directory}/spotbugs + ${project.basedir}/../../../eng/code-quality-reports/src/main/resources/spotbugs/spotbugs-exclude.xml + true + + + + + + org.revapi + revapi-maven-plugin + 0.14.6 + + true + + + + com.azure + sdk-build-tools + 1.0.0 + + + org.revapi + revapi-java + 0.26.1 + + + org.revapi + revapi-reporter-json + 0.5.0 + + + + + + com.azure.tools + codesnippet-maven-plugin + 1.0.0-beta.10 + + **/*.md + + + + update-codesnippets + + update-codesnippet + + + + verify-codesnippets + + verify-codesnippet + + + + + + + com.diffplug.spotless + spotless-maven-plugin + 2.30.0 + + true + + + + + diff --git a/sdk/tools/azure-openrewrite/src/main/java/com/azure/openrewrite/RemoveFixedDelayRecipe.java b/sdk/tools/azure-openrewrite/src/main/java/com/azure/openrewrite/RemoveFixedDelayRecipe.java new file mode 100644 index 000000000000..604fba4fb077 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/main/java/com/azure/openrewrite/RemoveFixedDelayRecipe.java @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.openrewrite; + +import org.openrewrite.ExecutionContext; +import org.openrewrite.Recipe; +import org.openrewrite.TreeVisitor; +import org.openrewrite.java.JavaIsoVisitor; +import org.openrewrite.java.tree.J; + +/** + * RemoveFixedDelayRecipe removes any leftover imports for FixedDelayOptions + * and any variables declared with the FixedDelayOptions type. + * -------------------------------------------------- + * Removes code such as: + * import com.azure.core.http.policy.FixedDelayOptions; + * ... + * FixedDelayOptions s; + * -------------------------------------------------- + */ +public class RemoveFixedDelayRecipe extends Recipe { + /** + * Method to return a simple short description of RemoveFixedDelayRecipe + * @return A simple short description/name of the recipe + */ + @Override + public String getDisplayName() { + return "Removes imports and variable declarations for FixedDelayOptions"; + } + + /** + * Method to return a description of RemoveFixedDelayRecipe + * @return A short description of the recipe + */ + @Override + public String getDescription() { + return "This recipe removes any leftover imports and variables using FixedDelayOptions."; + } + /** + * Method to return the visitor that visits the usages of FixedDelayOptions + * @return A TreeVisitor to visit the usages of FixedDelayOptions + */ + @Override + public TreeVisitor getVisitor() { + return new FixedDelayVisitor(); + } + /** + * Visitor to remove FixedDelayOptions + */ + private static class FixedDelayVisitor extends JavaIsoVisitor { + /** + * Method to remove unnecessary import for FixedDelay + */ + @Override + public J.Import visitImport(J.Import _import, ExecutionContext executionContext) { + J.Import visitedImport = super.visitImport(_import, executionContext); + if (visitedImport.getQualid() != null){ + if (visitedImport.getQualid().getSimpleName().contains("FixedDelay")){ + return null; + } + } + return visitedImport; + } + /** + * Method to remove unnecessary variable declarations for FixedDelay + */ + @Override + public J.VariableDeclarations visitVariableDeclarations(J.VariableDeclarations multiVariable, ExecutionContext executionContext) { + J.VariableDeclarations visitedVar = super.visitVariableDeclarations(multiVariable, executionContext); + if (visitedVar.getTypeExpression() == null) { + return visitedVar; + } + if (visitedVar.getTypeExpression().toString().contains("FixedDelayOptions")) { + // Return null to remove the block + return null; + } + return visitedVar; + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/main/java/com/azure/openrewrite/TypeReferenceRecipe.java b/sdk/tools/azure-openrewrite/src/main/java/com/azure/openrewrite/TypeReferenceRecipe.java new file mode 100644 index 000000000000..6f598d0b1052 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/main/java/com/azure/openrewrite/TypeReferenceRecipe.java @@ -0,0 +1,236 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.openrewrite; + +import org.openrewrite.Cursor; +import org.openrewrite.ExecutionContext; +import org.openrewrite.Recipe; +import org.openrewrite.TreeVisitor; +import org.openrewrite.java.JavaIsoVisitor; +import org.openrewrite.java.JavaTemplate; +import org.openrewrite.java.tree.J; +import org.openrewrite.java.tree.JavaType; +import org.openrewrite.java.tree.TypeTree; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * Recipe to convert TypeReference to ParameterizedType and remove TypeReference import statements. + * -------------------------------------------------- + * Before applying this recipe: + * import com.azure.core.util.serializer.TypeReference; + * ... + * result = binaryDataResponse.getValue().toObject(new TypeReference<List<TranslatedTextItem>>() { }); + * -------------------------------------------------- + * After applying this recipe: + * import java.lang.reflect.ParameterizedType; + * import java.lang.reflect.Type; + * ... + result = binaryDataResponse.getValue().toObject(new ParameterizedType() { + @Override + public Type getRawType() { + return List.class; + } + + @Override + public Type[] getActualTypeArguments() { + return new Type[]{TranslatedTextItem.class}; + } + + @Override + public Type getOwnerType() { + return null; + } + }); + * -------------------------------------------------- + */ +public class TypeReferenceRecipe extends Recipe { + + @Override + public String getDisplayName() { + return "Convert TypeReference to ParameterizedType and remove imports"; + } + + @Override + public String getDescription() { + return "This recipe converts TypeReference<> to ParameterizedType and removes the import statement for TypeReference."; + } + + @Override + public TreeVisitor getVisitor() { + return new ConvertTypeReferenceVisitor(); + } + + private static class ConvertTypeReferenceVisitor extends JavaIsoVisitor { + /** + * Method to visit instantiation of TypeReference and replace it with ParameterizedType + * instantiation including override methods. + * */ + @Override + public J.NewClass visitNewClass(J.NewClass newClass, ExecutionContext ctx) { + J.NewClass visitedNewClass = super.visitNewClass(newClass, ctx); + + // Check if the TypeReference reference has already been transformed + if (visitedNewClass.getBody() == null){return visitedNewClass;} + boolean alreadyTransformed = visitedNewClass.getBody().getStatements().stream() + .filter(statement -> statement instanceof J.MethodDeclaration) + .map(J.MethodDeclaration.class::cast) + .anyMatch(methodDeclaration -> methodDeclaration.getName().getSimpleName().equals("getRawType")); + if (visitedNewClass.getClazz() == null){return visitedNewClass;} + if (!alreadyTransformed && visitedNewClass.getClazz().toString().contains("TypeReference")) { + // Extract type from generic type in TypeReference declaration + String genType = null; + String type = null; + String type2 = null; + List fullType = null; + + + if(visitedNewClass.getClazz().getType() != null){ + try { + fullType = ((JavaType.Parameterized) visitedNewClass.getClazz().getType()).getTypeParameters(); + if (fullType.get(0) instanceof JavaType.Parameterized) { // Check if using parameterized type + type = ((JavaType.Class)((JavaType.Parameterized) fullType.get(0)).getTypeParameters().get(0)).getClassName(); + if (((JavaType.Parameterized) fullType.get(0)).getTypeParameters().size() > 1) { + type2 = ((JavaType.Class)((JavaType.Parameterized) fullType.get(0)).getTypeParameters().get(1)).getClassName(); + } + genType = ((JavaType.Parameterized) fullType.get(0)).getClassName(); + } else { + genType = ((JavaType.Class)fullType.get(0)).getClassName(); + } + } catch (ClassCastException e) { // OpenRewrite has a bug where parameterized new-classes contained in method arguments can't be parsed, so extract type information using String manipulation instead + genType = visitedNewClass.getClazz().toString().split("<")[1]; + if (visitedNewClass.getClazz().toString().contains(",")) { + type = visitedNewClass.getClazz().toString().split("<")[2].replace(">", "").split(",")[0]; + type2 = visitedNewClass.getClazz().toString().split("<")[2].replace(">", "").split(",")[1]; + }else { + type = visitedNewClass.getClazz().toString().split("<")[2].replace(">", ""); + } + } + } + JavaTemplate methodRawTypeTemplate = JavaTemplate.builder("@Override public Type getRawType() { return " + extractTypeArgument(visitedNewClass.toString()) + ".class; }").build(); + if (genType!=null){ + methodRawTypeTemplate = JavaTemplate.builder("@Override public Type getRawType() { return " + genType + ".class; }").build(); + } + JavaTemplate methodActualTypeTemplate = JavaTemplate.builder("@Override public Type[] getActualTypeArguments() { return new Type[] {}; }").build(); + if (type != null){ + methodActualTypeTemplate = JavaTemplate.builder("@Override public Type[] getActualTypeArguments() { return new Type[] { " + type + ".class }; }").build(); + } + JavaTemplate methodOwnerTypeTemplate = JavaTemplate.builder("@Override public Type getOwnerType() { return null; }").build(); + if (type2 != null){ // If TypeReference uses Map or any other class with the same structure like Foo + methodActualTypeTemplate = JavaTemplate.builder("@Override public Type[] getActualTypeArguments() { return new Type[] { " + type + ".class," + type2 + ".class }; }").build(); + } + // Apply Templates (add methods to body) + + visitedNewClass = visitedNewClass.withBody(methodRawTypeTemplate.apply(new Cursor(getCursor(), visitedNewClass.getBody()), + visitedNewClass.getBody().getCoordinates().lastStatement())); + visitedNewClass = visitedNewClass.withBody(methodActualTypeTemplate.apply(new Cursor(getCursor(), visitedNewClass.getBody()), + visitedNewClass.getBody().getCoordinates().lastStatement())); + visitedNewClass = visitedNewClass.withBody(methodOwnerTypeTemplate.apply(new Cursor(getCursor(), visitedNewClass.getBody()), + visitedNewClass.getBody().getCoordinates().lastStatement())); + + visitedNewClass = visitedNewClass.withClazz(TypeTree.build(" ParameterizedType")); // Replace TypeReference with Type + + } + return visitedNewClass; + } + + private final Set importSet = new HashSet<>(); + + @Override + public J.Import visitImport(J.Import importStmt, ExecutionContext ctx) { + String importQualid = importStmt.getQualid().toString(); + + // Add the import to the set and check if it already exists + boolean isNewImport = importSet.add(importQualid); + + // If the import is for ParameterizedType, and it's already in the set, skip it + if (importQualid.trim().equals("java.lang.reflect.ParameterizedType") && !isNewImport) { + return null; + } + + // Remove the import statement for TypeReference and add import for ParameterizedType + if (importQualid.equals("com.azure.core.util.serializer.TypeReference")) { + importSet.add("java.lang.reflect.ParameterizedType"); + return importStmt.withQualid(TypeTree.build(" java.lang.reflect.ParameterizedType")); + } + + // Change BinaryData import to a new package + if (importQualid.equals("com.azure.core.util.BinaryData")) { + importSet.add("io.clientcore.core.util.binarydata.BinaryData"); + return importStmt.withQualid(TypeTree.build(" io.clientcore.core.util.binarydata.BinaryData")); + } + + // Return other imports normally + return importStmt; + } + /** + * Method to visit variable declaration for TypeReference and make sure it is converted to java.lang.reflect.Type + */ + @Override + public J.VariableDeclarations visitVariableDeclarations(J.VariableDeclarations multiVariable, ExecutionContext executionContext) { + J.VariableDeclarations visitedDeclarations = super.visitVariableDeclarations(multiVariable, executionContext); + if (visitedDeclarations.toString().contains("TypeReference") + && visitedDeclarations.toString().contains("ParameterizedType")) { + visitedDeclarations = visitedDeclarations.withTypeExpression(TypeTree.build(" Type")); + return visitedDeclarations; + } + return visitedDeclarations; + } + + /** + * Method to visit BinaryData type and change it to the new version + */ + @Override + public J.FieldAccess visitFieldAccess(J.FieldAccess fieldAccess, ExecutionContext ctx) { + J.FieldAccess fa = super.visitFieldAccess(fieldAccess, ctx); + String fullyQualified = fa.getTarget() + "." + fa.getSimpleName(); + if (fullyQualified.equals("com.azure.core.util.BinaryData")) { + return TypeTree.build(" io.clientcore.core.util.binarydata.BinaryData"); + } + return fa; + } + + /** + * Method to add import for java.lang.reflect.Type if needed + */ + @Override + public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, ExecutionContext executionContext) { + J.CompilationUnit visitedCompilationUnit = super.visitCompilationUnit(cu, executionContext); + J.Import newImport = null; + boolean addTypeImport = false; + if (visitedCompilationUnit.getImports().isEmpty()){return visitedCompilationUnit;} + for (J.Import i : visitedCompilationUnit.getImports()) { + newImport = i; + if (i.toString().contains("java.lang.reflect.Type")){ + return visitedCompilationUnit; + } + if (i.toString().contains("java.lang.reflect.ParameterizedType")){ + addTypeImport = true; + } + } + if (addTypeImport) { + newImport = newImport.withQualid(TypeTree.build(" java.lang.reflect.Type")); + List imports = visitedCompilationUnit.getImports(); + imports.add(newImport); + return visitedCompilationUnit.withImports(imports); + } + return visitedCompilationUnit; + } + + public String extractTypeArgument(String text) { + // Find the start and end of the type argument + int startIndex = text.indexOf('<'); + int endIndex = text.indexOf('>', startIndex); + + if (startIndex == -1 || endIndex == -1) { + return null; // If '<' or '>' not found, return null + } + + // Extract the substring between the angle brackets + return text.substring(startIndex + 1, endIndex).trim(); + } + } + +} diff --git a/sdk/tools/azure-openrewrite/src/main/java/com/azure/openrewrite/core/ResponseRecipe.java b/sdk/tools/azure-openrewrite/src/main/java/com/azure/openrewrite/core/ResponseRecipe.java new file mode 100644 index 000000000000..57303e3586ca --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/main/java/com/azure/openrewrite/core/ResponseRecipe.java @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.openrewrite.core; + +import org.openrewrite.ExecutionContext; +import org.openrewrite.Recipe; +import org.openrewrite.TreeVisitor; +import org.openrewrite.java.JavaIsoVisitor; +import org.openrewrite.java.tree.J; +import org.openrewrite.java.tree.TypeTree; + +/** + * ResponseRecipe changes all instances of Response (from azure core v1) to Response (from azure core v2). + * This recipe also updates the import statements for the aforementioned class. + * -------------------------------------------------- + * Before applying this recipe: + * import com.azure.core.http.rest.Response; + * -------------------------------------------------- + * After applying this recipe: + * import io.clientcore.core.http.models.Response; + * -------------------------------------------------- + */ +public class ResponseRecipe extends Recipe { + /** + * Method to return a simple short description of ResponseRecipe + * @return A simple short description/name of the recipe + */ + @Override + public String getDisplayName() { + return "Update Response type to v2 version"; + } + /** + * Method to return a description of ResponseRecipe + * @return A short description of the recipe + */ + @Override + public String getDescription() { + return "This recipe changes com.azure.core.http.rest.Response to io.clientcore.core.http.models.Response."; + } + /** + * Method to return the visitor that visits the Response class + * @return A TreeVisitor to visit the Response class and update it + */ + @Override + public TreeVisitor getVisitor() { + return new UpdateResponseVisitor(); + } + /** + * Visitor to update Response + */ + private static class UpdateResponseVisitor extends JavaIsoVisitor { + /** + * Method to change com.azure.core.http.rest.Response to io.clientcore.core.http.models.Response + */ + @Override + public J.FieldAccess visitFieldAccess(J.FieldAccess fieldAccess, ExecutionContext ctx) { + J.FieldAccess visitedFieldAccess = super.visitFieldAccess(fieldAccess, ctx); + String fullyQualified = visitedFieldAccess.getTarget() + "." + visitedFieldAccess.getSimpleName(); + if (fullyQualified.equals("com.azure.core.http.rest.Response")) { + return TypeTree.build(" io.clientcore.core.http.models.Response"); + } + return visitedFieldAccess; + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/main/java/com/azure/openrewrite/core/RetryOptionsConstructorRecipe.java b/sdk/tools/azure-openrewrite/src/main/java/com/azure/openrewrite/core/RetryOptionsConstructorRecipe.java new file mode 100644 index 000000000000..62f9bfd6e88b --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/main/java/com/azure/openrewrite/core/RetryOptionsConstructorRecipe.java @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.openrewrite.core; + +import org.openrewrite.ExecutionContext; +import org.openrewrite.Recipe; +import org.openrewrite.TreeVisitor; +import org.openrewrite.java.JavaIsoVisitor; +import org.openrewrite.java.tree.Expression; +import org.openrewrite.java.tree.J; +import org.openrewrite.java.tree.TypeTree; + +import java.util.ArrayList; +import java.util.List; +import java.util.HashMap; +import java.util.Map; +/** + * RetryOptionsRecipe changes RetryOptions constructor to HttpRetryOptions constructor. + * It also removes any references to FixedDelay and ExponentialDelay and changes + * com.azure.core.http.policy.RetryOptions to io.clientcore.core.http.models.HttpRetryOptions + * -------------------------------------------------- + * Before applying this recipe: + * import com.azure.core.http.policy.RetryOptions; + * ... + * new RetryOptions(new FixedDelayOptions(3, Duration.ofMillis(50))) + * -------------------------------------------------- + * After applying this recipe: + * import io.clientcore.core.http.models.HttpRetryOptions; + * ... + * new HttpRetryOptions(3, Duration.ofMillis(50)) + * -------------------------------------------------- + */ +// TODO: replace with declarative recipe +public class RetryOptionsConstructorRecipe extends Recipe { + /** + * Method to return a simple short description of RetryOptionsRecipe + * @return A simple short description/name of the recipe + */ + @Override + public String getDisplayName() { + return "Change RetryOptions constructor"; + } + /** + * Method to return a description of RetryOptionsRecipe + * @return A short description of the recipe + */ + @Override + public String getDescription() { + return "This recipe changes the constructor for RetryOptions to HttpRetryOptions.\n" + + "This includes removing any references to FixedDelay and ExponentialDelay and changing\n" + + " * com.azure.core.http.policy.RetryOptions to io.clientcore.core.http.models.HttpRetryOptions."; + } + /** + * Method to return the visitor that changes RetryOptions constructor to HttpRetryOptions constructor + * @return A TreeVisitor to change RetryOptions constructor to HttpRetryOptions constructor + */ + @Override + public TreeVisitor getVisitor() { + return new RetryVisitor(); + } + /** + * Visitor to change RetryOptions constructor to HttpRetryOptions constructor + */ + private static class RetryVisitor extends JavaIsoVisitor { + + private final Map> variableToArgsMap = new HashMap<>(); + + /** + * Method to visit variable declaration for FixedDelay or ExponentialDelay + */ + @Override + public J.VariableDeclarations visitVariableDeclarations(J.VariableDeclarations variableDeclarations, ExecutionContext executionContext) { + J.VariableDeclarations vd = super.visitVariableDeclarations(variableDeclarations, executionContext); + for (J.VariableDeclarations.NamedVariable variable : vd.getVariables()) { + J.NewClass newClass = null; + try { + newClass = (J.NewClass) variable.getInitializer(); + } catch (Exception e) { + return vd; + } + if (newClass != null) { + if (newClass.getType() != null) { + String className = newClass.getType().toString(); + if (className.contains("FixedDelayOptions") || className.contains("ExponentialDelayOptions")) { + List args = new ArrayList<>(newClass.getArguments()); + variableToArgsMap.put(variable.getSimpleName(), args); + } + } + } + } + return vd; + } + + /** + * Method to visit constructor for RetryOptions + */ + @Override + public J.NewClass visitNewClass(J.NewClass newClass, ExecutionContext executionContext) { + J.NewClass visitedNewClass = super.visitNewClass(newClass, executionContext); + if (visitedNewClass.toString().contains("new HttpRetryOptions")) { + if (visitedNewClass.getArguments().size() == 1) { + Expression constructorArg = visitedNewClass.getArguments().get(0); + if (constructorArg instanceof J.Identifier) { + String variableName = ((J.Identifier) constructorArg).getSimpleName(); + List args = variableToArgsMap.get(variableName); + if (args != null) { + return visitedNewClass.withArguments(args); + } + } else if (constructorArg instanceof J.NewClass) { + J.NewClass newArg = (J.NewClass) constructorArg; + List args = new ArrayList<>(newArg.getArguments()); + return visitedNewClass.withArguments(args); + } + } + } + return visitedNewClass; + } + + /** + * Method to change RetryOptions to HttpRetryOptions + */ + @Override + public J.Identifier visitIdentifier(J.Identifier identifier, ExecutionContext ctx) { + J.Identifier visitedIdentifier = super.visitIdentifier(identifier, ctx); + if (visitedIdentifier.getSimpleName().equals("RetryOptions")) { + return visitedIdentifier.withSimpleName("HttpRetryOptions"); + } + return visitedIdentifier; + } + + /** + * Method to change import to HttpRetryOptions + */ + @Override + public J.FieldAccess visitFieldAccess(J.FieldAccess fieldAccess, ExecutionContext ctx) { + J.FieldAccess visitedFieldAccess = super.visitFieldAccess(fieldAccess, ctx); + String fullyQualified = visitedFieldAccess.getTarget() + "." + visitedFieldAccess.getSimpleName(); + if (fullyQualified.equals("com.azure.core.http.policy.HttpRetryOptions")) { + return TypeTree.build(" io.clientcore.core.http.models.HttpRetryOptions"); + } + return visitedFieldAccess; + } + + /** + * Method to change usages of retryOptions builder method to httpRetryOptions + */ + @Override + public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext executionContext) { + J.MethodInvocation visitedMethodInv = super.visitMethodInvocation(method, executionContext); + if (visitedMethodInv.getSimpleName().equals("retryOptions")) { + return visitedMethodInv.withName(visitedMethodInv.getName().withSimpleName("httpRetryOptions")); + } + return visitedMethodInv; + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/main/resources/META-INF/rewrite/migrationRecipes/core/azure-core-migration.yml b/sdk/tools/azure-openrewrite/src/main/resources/META-INF/rewrite/migrationRecipes/core/azure-core-migration.yml new file mode 100644 index 000000000000..9fee4b36e1c0 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/main/resources/META-INF/rewrite/migrationRecipes/core/azure-core-migration.yml @@ -0,0 +1,148 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------- +# Migration Recipes for Azure-Core Library +# -------------------------------------------------------------------- +type: specs.openrewrite.org/v1beta/recipe +name: com.azure.openrewrite.recipes.migrateAzureCore +displayName: Migrate from azure-core to next generation stack +description: This recipe migrates the Azure Storage Core library to the next generation stack. +recipeList: + # Before: import com.azure.core.http.HttpHeaderName; + # After: import io.clientcore.core.http.models.HttpHeaderName; + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.core.http.HttpHeaderName + newFullyQualifiedTypeName: io.clientcore.core.http.models.HttpHeaderName + + # Before: import com.azure.core.util.logging.ClientLogger; + # After: import io.clientcore.core.util.ClientLogger; + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.core.util.logging.ClientLogger + newFullyQualifiedTypeName: io.clientcore.core.instrumentation.logging.ClientLogger + + + # Before: import com.azure.core.util.CoreUtils; + # After: import com.azure.core.v2.util.CoreUtils; + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.core.util.CoreUtils + newFullyQualifiedTypeName: com.azure.core.v2.util.CoreUtils + + + # Before: import com.azure.core.http.policy.KeyCredentialPolicy; + # After: import io.clientcore.core.http.pipeline.KeyCredentialPolicy; + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.core.http.policy.KeyCredentialPolicy + newFullyQualifiedTypeName: io.clientcore.core.http.pipeline.KeyCredentialPolicy + + + # Before: import com.azure.core.credential.KeyCredential; + # After: import io.clientcore.core.credential.KeyCredential; + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.core.credential.KeyCredential + newFullyQualifiedTypeName: io.clientcore.core.credential.KeyCredential + + + # Before: import com.azure.core.client.traits.KeyCredentialTrait; + # After: import io.clientcore.core.models.traits.KeyCredentialTrait; + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.core.client.traits.KeyCredentialTrait + newFullyQualifiedTypeName: io.clientcore.core.models.traits.KeyCredentialTrait + + + # Before: import com.azure.core.http.HttpClient; + # After: import io.clientcore.core.http.client.HttpClient; + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.core.http.HttpClient + newFullyQualifiedTypeName: io.clientcore.core.http.client.HttpClient + ignoreDefinition: false + + # Before: import com.azure.core.http.HttpPipeline; + # After: import io.clientcore.core.http.pipeline.HttpPipeline; + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.core.http.HttpPipeline + newFullyQualifiedTypeName: io.clientcore.core.http.pipeline.HttpPipeline + ignoreDefinition: false + + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.core.http.HttpPipelineBuilder + newFullyQualifiedTypeName: io.clientcore.core.http.pipeline.HttpPipelineBuilder + ignoreDefinition: false + + # Before: import com.azure.core.http.policy.HttpPipelinePolicy; + # After: import io.clientcore.core.http.pipeline.HttpPipelinePolicy; + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.core.http.policy.HttpPipelinePolicy + newFullyQualifiedTypeName: io.clientcore.core.http.pipeline.HttpPipelinePolicy + ignoreDefinition: false + + # Before: import com.azure.core.exception.ClientAuthenticationException; + # After: import com.azure.core.v2.exception.ClientAuthenticationException; + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.core.exception.ClientAuthenticationException + newFullyQualifiedTypeName: com.azure.core.v2.exception.ClientAuthenticationException + + # Before: import com.azure.core.exception.ResourceModifiedException; + # After: import com.azure.core.v2.exception.ResourceModifiedException; + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.core.exception.ResourceModifiedException + newFullyQualifiedTypeName: com.azure.core.v2.exception.ResourceModifiedException + # Before: import com.azure.core.exception.ResourceNotFoundException; + # After: import com.azure.core.v2.exception.ResourceNotFoundException; + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.core.exception.ResourceNotFoundException + newFullyQualifiedTypeName: com.azure.core.v2.exception.ResourceNotFoundException + + # Before: import com.azure.core.exception.HttpResponseException; + # After: import io.clientcore.core.http.exception.HttpResponseException; + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.core.exception.HttpResponseException + newFullyQualifiedTypeName: io.clientcore.core.http.exception.HttpResponseException + # End azure-core-exception change type Recipes + + # Before: import com.azure.core.util.Configuration; + # After: import io.clientcore.core.util.configuration.Configuration; + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.core.util.Configuration + newFullyQualifiedTypeName: io.clientcore.core.util.configuration.Configuration + + # Before: import com.azure.core.credential.AzureSasCredential; + # After: import io.clientcore.core.credential.KeyCredential; + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.core.credential.AzureSasCredential + newFullyQualifiedTypeName: io.clientcore.core.credential.KeyCredential + + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.core.http.policy.HttpLogOptions + newFullyQualifiedTypeName: io.clientcore.core.http.models.HttpInstrumentationOptions + + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.core.http.policy.HttpLogDetailLevel + newFullyQualifiedTypeName: io.clientcore.core.http.models.HttpInstrumentationOptions$HttpLogDetailLevel + + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.core.http.policy.RetryPolicy + newFullyQualifiedTypeName: io.clientcore.core.http.pipeline.HttpRetryPolicy + + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.core.util.Context + newFullyQualifiedTypeName: io.clientcore.core.util.Context + + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.core.http.rest.RequestOptions + newFullyQualifiedTypeName: io.clientcore.core.http.models.RequestOptions + + - org.openrewrite.java.ChangeStaticFieldToMethod: + oldClassName: io.clientcore.core.util.Context + oldFieldName: NONE + newMethodName: none + + - org.openrewrite.java.ChangeMethodName: + methodPattern: com.azure..* httpLogOptions(..) + newMethodName: httpInstrumentationOptions + matchOverrides: false + ignoreDefinition: false + + - com.azure.openrewrite.core.ResponseRecipe + - com.azure.openrewrite.core.RetryOptionsConstructorRecipe + - com.azure.openrewrite.TypeReferenceRecipe + - com.azure.openrewrite.RemoveFixedDelayRecipe diff --git a/sdk/tools/azure-openrewrite/src/main/resources/META-INF/rewrite/migrationRecipes/storage/azure-storage-blob-migration.yml b/sdk/tools/azure-openrewrite/src/main/resources/META-INF/rewrite/migrationRecipes/storage/azure-storage-blob-migration.yml new file mode 100644 index 000000000000..2a8e40e9dea6 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/main/resources/META-INF/rewrite/migrationRecipes/storage/azure-storage-blob-migration.yml @@ -0,0 +1,42 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------- +# Migration Recipes for Azure-Storage-Blob Library +# -------------------------------------------------------------------- +# +type: specs.openrewrite.org/v1beta/recipe +name: com.azure.openrewrite.recipes.migrateAzureStorageBlob +displayName: Migrate from azure-storage-blob to next generation stack +description: This recipe migrates the Azure Storage Blob library to the next generation stack. +recipeList: + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.storage.blob.BlobClient + newFullyQualifiedTypeName: com.azure.v2.storage.blob.BlobClient + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.storage.blob.BlobServiceClient + newFullyQualifiedTypeName: com.azure.v2.storage.blob.BlobServiceClient + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.storage.blob.BlobServiceClientBuilder + newFullyQualifiedTypeName: com.azure.v2.storage.blob.BlobServiceClientBuilder + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.storage.blob.BlobClientBuilder + newFullyQualifiedTypeName: com.azure.v2.storage.blob.BlobClientBuilder + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.storage.blob.models.BlobItem + newFullyQualifiedTypeName: com.azure.v2.storage.blob.models.BlobItem + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.storage.blob.models.BlobItemProperties + newFullyQualifiedTypeName: com.azure.v2.storage.blob.models.BlobItemProperties + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.storage.blob.models.BlobStorageException + newFullyQualifiedTypeName: com.azure.v2.storage.blob.models.BlobStorageException + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.storage.blob.models.ListBlobsOptions + newFullyQualifiedTypeName: com.azure.v2.storage.blob.models.ListBlobsOptions + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.storage.blob.specialized.BlockBlobClient + newFullyQualifiedTypeName: com.azure.v2.storage.blob.specialized.BlockBlobClient + - org.openrewrite.java.ChangeType: + oldFullyQualifiedTypeName: com.azure.storage.blob.specialized.BlockBlobClientBuilder + newFullyQualifiedTypeName: com.azure.v2.storage.blob.specialized.BlockBlobClientBuilder + diff --git a/sdk/tools/azure-openrewrite/src/main/resources/META-INF/rewrite/migrationRecipes/translation/azure-ai-migration.yml b/sdk/tools/azure-openrewrite/src/main/resources/META-INF/rewrite/migrationRecipes/translation/azure-ai-migration.yml new file mode 100644 index 000000000000..f6ef084e5cb7 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/main/resources/META-INF/rewrite/migrationRecipes/translation/azure-ai-migration.yml @@ -0,0 +1,38 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------- +# Migration Recipes for Azure-AI-Translation-Text Library +# -------------------------------------------------------------------- +type: specs.openrewrite.org/v1beta/recipe +name: com.azure.openrewrite.recipes.migrateAzureAiTranslationText +displayName: Migrate azure translation libraries to next-gen libraries +description: This recipe migrates the azure translation libraries to the next-gen libraries. +recipeList: + # Rename methods + # Alternatively, can target HttpTrait directly + + # Before: textTranslationClient.retryOptions(new RetryOptions()) + # After: textTranslationClient.httpRetryOptions(new RetryOptions()) + - org.openrewrite.java.ChangeMethodName: + methodPattern: com.azure.ai.translation.text.TextTranslationClientBuilder retryOptions(..) + newMethodName: httpRetryOptions + matchOverrides: true + + # Before: + # textTranslationClient.pipeline(pipeline) + # After: + # textTranslationClient.httpPipeline(pipeline) + - org.openrewrite.java.ChangeMethodName: + methodPattern: com.azure.ai.translation.text.TextTranslationClientBuilder pipeline(..) + newMethodName: httpPipeline + matchOverrides: true + + # Before: + # textTranslationClient.addPolicy(customPolicy) + # After: + # textTranslationClient.addHttpPipelinePolicy(customPolicy) + - org.openrewrite.java.ChangeMethodName: + methodPattern: com.azure.ai.translation.text.TextTranslationClientBuilder addPolicy(..) + newMethodName: addHttpPipelinePolicy + matchOverrides: true + diff --git a/sdk/tools/azure-openrewrite/src/main/resources/META-INF/rewrite/rewrite.yml b/sdk/tools/azure-openrewrite/src/main/resources/META-INF/rewrite/rewrite.yml new file mode 100644 index 000000000000..d14380ccb4b1 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/main/resources/META-INF/rewrite/rewrite.yml @@ -0,0 +1,13 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# -------------------------------------------------------------------- +# Azure-SDK-For-Java Library Migration Recipes +# -------------------------------------------------------------------- +# +type: specs.openrewrite.org/v1beta/recipe +name: com.azure.openrewrite.migrateToVNext # name to be changed +displayName: Migrate Azure SDKs to Next-Generation Library Stack +description: This recipe migrates the Azure SDKs to the next-generation library stack. +recipeList: + - com.azure.openrewrite.recipes.migrateAzureCore + - com.azure.openrewrite.recipes.migrateAzureStorageBlob diff --git a/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/migration/FullSampleMigrationTest.java b/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/migration/FullSampleMigrationTest.java new file mode 100644 index 000000000000..533b372af94f --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/migration/FullSampleMigrationTest.java @@ -0,0 +1,121 @@ +package com.azure.openrewrite.migration; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.condition.DisabledIf; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.openrewrite.test.RecipeSpec; +import org.openrewrite.test.RewriteTest; +import org.openrewrite.test.SourceSpecs; +import org.openrewrite.test.TypeValidation; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.openrewrite.java.Assertions.java; + +public class FullSampleMigrationTest implements RewriteTest { + + static final String GOLDEN_IMAGE = "v2"; + static final String ORIGINAL_IMAGE = "v1"; + static final String RECIPE_NAME = "com.azure.openrewrite.migrateToVNext"; + static final String[] DISABLED_DIRS = { + "src/test/resources/migrationExamples/azure-storage-blob/" + }; + + static boolean isDisabledDir(Path dir) { + for (String disabledDir : DISABLED_DIRS) { + if (dir.startsWith(Paths.get(disabledDir))) { + return true; + } + } + return false; + } + + static Stream sampleDirectories() throws IOException { + List packageDirectories = packageDirectories().collect(Collectors.toList()); + List sampleDirectories = new ArrayList<>(); + for (Path packageDirectory : packageDirectories) { + sampleDirectories.addAll(Files + .list(packageDirectory) + .filter(Files::isDirectory) + .collect(Collectors.toList())); + } + + return sampleDirectories.stream(); + } + + static Stream packageDirectories() throws IOException { + return Files.list(Paths.get("src/test/resources/migrationExamples")) + .filter(Files::isDirectory); + } + + static Stream gatherAllRegularFiles(Path sampleDir) throws IOException { + return Files.walk(sampleDir) + .filter(Files::isRegularFile).collect(Collectors.toList()).stream(); + } + + @Override + public void defaults(RecipeSpec spec) { + System.out.printf("Active recipe: %s\n", RECIPE_NAME); + spec.recipeFromResources(RECIPE_NAME) + .typeValidationOptions(TypeValidation.none()); + } + + + + @ParameterizedTest + @MethodSource("sampleDirectories") + public void testGoldenImage(Path sampleDir) throws Exception { + Assumptions.assumeFalse(isDisabledDir(sampleDir)); + + Map fileMap = new HashMap(); + + Path unmigratedDir = sampleDir.resolve(ORIGINAL_IMAGE); + gatherAllRegularFiles(unmigratedDir).forEach(file -> { + String unmigratedFileString = file.toString(); + String migratedFileString = unmigratedFileString.replace(ORIGINAL_IMAGE, GOLDEN_IMAGE); + if (Files.exists(Paths.get(migratedFileString))) { + fileMap.put(unmigratedFileString, migratedFileString); + } else { + throw new RuntimeException("Invalid Sample Migration Structure. Migrated file does not exist: " + migratedFileString); + } + }); + + assertFullMigration(fileMap); + } + + public void assertFullMigration(Map fileMap) throws IOException { + List sourceSpecs = new ArrayList(); + for (Map.Entry entry : fileMap.entrySet()) { + + String before = Files.readAllLines(Paths.get(entry.getKey())) + .stream() + .reduce("", (a, b) -> a + b + "\n"); + + String after = Files.readAllLines(Paths.get(entry.getValue())) + .stream() + .reduce("", (a, b) -> a + b + "\n"); + if (!before.equals(after)) { + sourceSpecs.add(java(before, after)); + } + } + if (sourceSpecs.isEmpty()) { + Assumptions.abort("Migration samples are identical. No migration detected."); + } + rewriteRun( + sourceSpecs.toArray(new SourceSpecs[sourceSpecs.size()]) + ); + } + +} diff --git a/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/BinaryDataTest.java b/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/BinaryDataTest.java new file mode 100644 index 000000000000..b62f5e8e38fc --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/BinaryDataTest.java @@ -0,0 +1,110 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.openrewrite.recipe; + +import org.intellij.lang.annotations.Language; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import static org.openrewrite.java.Assertions.java; +import org.openrewrite.test.RecipeSpec; +import org.openrewrite.test.RewriteTest; +import org.openrewrite.test.TypeValidation; + +public class BinaryDataTest extends RecipeTestBase { + /** + * BinaryDataTest tests the recipe that changes + * com.azure.core.util.BinaryData to io.clientcore.core.util.binarydata.BinaryData. + * This recipe also tests to ensure that the TypeReference is correctly changed + * when used in conjunction with BinaryData. + */ + + + /* Test to make sure BinaryData import is changed */ + @Test + public void testBinaryDataImportChanged() { + @Language("java") String before = "import com.azure.core.util.BinaryData;"; + before += "\npublic class Testing {"; + before += "\n public Testing(){"; + before += "\n BinaryData b = BinaryData.fromObject(null);"; + before += "\n }"; + before += "\n}"; + + @Language("java") String after = "import io.clientcore.core.util.binarydata.BinaryData;"; + after += "\npublic class Testing {"; + after += "\n public Testing(){"; + after += "\n BinaryData b = BinaryData.fromObject(null);"; + after += "\n }"; + after += "\n}"; + rewriteRun( + java(before,after) + ); + } + + /* Test to make sure BinaryData type is changed */ + @Test + public void testBinaryDataTypeChanged() { + @Language("java") String before = ""; + before += "public class Testing {\n public Testing(){\n com.azure.core.util.BinaryData b = com.azure.core.util.BinaryData.fromObject(null);\n }\n}"; + + @Language("java") String after = ""; + after += "public class Testing {\n public Testing(){\n io.clientcore.core.util.binarydata.BinaryData b = io.clientcore.core.util.binarydata.BinaryData.fromObject(null);\n }\n}"; + rewriteRun( + java(before,after) + ); + } + + /* Test to make sure BinaryData type and import is changed and TypeReference is changed */ + @Test + @Disabled("This test is failing and is temporarily disabled") + void testBinaryDataTypeReferenceChange() { + @Language("java") String before = ""; + before += "\nimport java.lang.reflect.ParameterizedType;"; + before += "\nimport java.lang.reflect.Type;"; + before += "\nimport java.util.List;"; + before += "\nimport com.azure.core.util.serializer.TypeReference;"; + before += "\nimport com.azure.core.util.BinaryData;"; + before += "\npublic class Testing {"; + before += "\n private static final TypeReference> TESTING_TYPE = new TypeReference>() {\n };"; + before += "\n private static final BinaryData b = BinaryData.fromObject(null);"; + before += "\n public static void main(String[] args) {"; + before += "\n System.out.println(b.toObject(TESTING_TYPE));"; + before += "\n }"; + before += "\n}"; + + + @Language("java") String after = + "import io.clientcore.core.util.binarydata.BinaryData;\n\n" + + "import java.io.IOException;\n" + + "import java.lang.reflect.ParameterizedType;\n" + + "import java.lang.reflect.Type;\n" + + "import java.util.List;\n\n"+ + "public class Testing {\n" + + " private static final Type TESTING_TYPE = new ParameterizedType() {\n" + + " @Override\n" + + " public Type getRawType() {\n" + + " return List.class;\n" + + " }\n\n" + + " @Override\n" + + " public Type[] getActualTypeArguments() {\n" + + " return new Type[]{String.class};\n" + + " }\n\n" + + " @Override\n" + + " public Type getOwnerType() {\n" + + " return null;\n" + + " }\n"; + after += " };"; + after += "\n private static final BinaryData b = BinaryData.fromObject(null);"; + after += "\n public static void main(String[] args) {"; + after += "\n try {"; + after += "\n System.out.println(b.toObject(TESTING_TYPE));"; + after += "\n } catch (IOException e) {"; + after += "\n e.printStackTrace();"; + after += "\n }"; + after += "\n }\n"; + after += "}\n"; + + rewriteRun( + java(before,after) + ); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/ClientLoggerTest.java b/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/ClientLoggerTest.java new file mode 100644 index 000000000000..707e92145ce0 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/ClientLoggerTest.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.openrewrite.recipe; + +import org.intellij.lang.annotations.Language; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import static org.openrewrite.java.Assertions.java; +import org.openrewrite.test.RecipeSpec; +import org.openrewrite.test.RewriteTest; + +// TODO: fix these tests to reflect current api +public class ClientLoggerTest extends RecipeTestBase { + /** + * ClientLoggerTest tests the recipe that changes + * com.azure.core.util.logging.ClientLogger to io.clientcore.core.util.ClientLogger. + */ + + /* Test to make sure ClientLogger import is changed */ + @Disabled("These tests were written before clientcore structure was finalized. Need to be redone to reflect the current api") + @Test + public void testClientLoggerWithImport() { + @Language("java") String before = "import com.azure.core.util.logging.ClientLogger;"; + before += "\npublic class Testing {"; + before += "\n public Testing(){"; + before += "\n ClientLogger c = new ClientLogger(Testing.class);"; + before += "\n }"; + before += "\n}"; + + @Language("java") String after = "import io.clientcore.core.util.ClientLogger;"; + after += "\n\npublic class Testing {"; + after += "\n public Testing(){"; + after += "\n ClientLogger c = new ClientLogger(Testing.class);"; + after += "\n }"; + after += "\n}"; + rewriteRun( + java(before, after) + ); + } + + /* Test to make sure ClientLogger type is changed */ + @Disabled("These tests were written before clientcore structure was finalized. Need to be redone to reflect the current api") + @Test + public void testClientLoggerWithFullyQualifiedName() { + @Language("java") String before = "public class Testing {"; + before += "\n public Testing(){"; + before += "\n com.azure.core.util.logging.ClientLogger c = new com.azure.core.util.logging.ClientLogger(Testing.class);"; + before += "\n }"; + before += "\n}"; + + @Language("java") String after = "public class Testing {"; + after += "\n public Testing(){"; + after += "\n io.clientcore.core.util.ClientLogger c = new io.clientcore.core.util.ClientLogger(Testing.class);"; + after += "\n }"; + after += "\n}"; + rewriteRun( + java(before, after) + ); + } + +} diff --git a/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/CoreUtilsTest.java b/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/CoreUtilsTest.java new file mode 100644 index 000000000000..0821f8a23f54 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/CoreUtilsTest.java @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.openrewrite.recipe; + +import org.intellij.lang.annotations.Language; +import org.junit.jupiter.api.Test; +import static org.openrewrite.java.Assertions.java; +import org.openrewrite.test.RecipeSpec; +import org.openrewrite.test.RewriteTest; + +public class CoreUtilsTest extends RecipeTestBase { + /** + * Test migrations from + * com.azure.core.util.CoreUtils to com.azure.core.v2.util.CoreUtils + */ + /* Tests that CoreUtil import is changed */ + @Test + public void testConfigurationImportChanged() { + @Language("java") String before = "import com.azure.core.util.CoreUtils;"; + before += "\npublic class Testing {"; + before += "\n public Testing(){"; + before += "\n CoreUtils cu = new CoreUtils();"; + before += "\n }"; + before += "\n}"; + + @Language("java") String after = "import com.azure.core.v2.util.CoreUtils;"; + after += "\n\npublic class Testing {"; + after += "\n public Testing(){"; + after += "\n CoreUtils cu = new CoreUtils();"; + after += "\n }"; + after += "\n}"; + rewriteRun( + java(before,after) + ); + } + + /* Tests that CoreUtils type is changed */ + @Test + public void testConfigurationTypeChanged() { + @Language("java") String before = ""; + before += "\npublic class Testing {"; + before += "\n public Testing(){"; + before += "\n com.azure.core.util.CoreUtils cu = new com.azure.core.util.CoreUtils();"; + before += "\n }"; + before += "\n}"; + + @Language("java") String after = ""; + after += "public class Testing {"; + after += "\n public Testing(){"; + after += "\n com.azure.core.v2.util.CoreUtils cu = new com.azure.core.v2.util.CoreUtils();"; + after += "\n }"; + after += "\n}"; + rewriteRun( + java(before,after) + ); + } + +} + diff --git a/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/CredentialTest.java b/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/CredentialTest.java new file mode 100644 index 000000000000..78add6819685 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/CredentialTest.java @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.openrewrite.recipe; + +import org.intellij.lang.annotations.Language; +import org.junit.jupiter.api.Test; +import static org.openrewrite.java.Assertions.java; +import org.openrewrite.test.RecipeSpec; +import org.openrewrite.test.RewriteTest; + +/** + * CredentialTest is used to test out the recipe that changes the package name com.azure.core.credential + * to io.clientcore.core.credential. + */ +public class CredentialTest extends RecipeTestBase { + + /** + * This test method is used to make sure that the package com.azure.core.credential is changed + */ + @Test + void testCredentialPackageNameChange() { + @Language("java") String before = "import com.azure.core.credential.KeyCredential;"; + before += "\npublic class Testing {"; + before += "\n public Testing(){"; + before += "\n KeyCredential kc = new KeyCredential(\"\");"; + before += "\n }"; + before += "\n}"; + + @Language("java") String after = "import io.clientcore.core.credential.KeyCredential;"; + after += "\n\npublic class Testing {"; + after += "\n public Testing(){"; + after += "\n KeyCredential kc = new KeyCredential(\"\");"; + after += "\n }"; + after += "\n}"; + rewriteRun( + java(before,after) + ); + } + + /** + * This test method is used to make sure that the KeyCredential type is changed + */ + @Test + void testKeyCredentialChangeNoImport() { + @Language("java") String before = "\npublic class Testing {"; + before += "\n public Testing(){"; + before += "\n com.azure.core.credential.KeyCredential kc = new com.azure.core.credential.KeyCredential(\"\");"; + before += "\n }"; + before += "\n}"; + + @Language("java") String after = "\npublic class Testing {"; + after += "\n public Testing(){"; + after += "\n io.clientcore.core.credential.KeyCredential kc = new io.clientcore.core.credential.KeyCredential(\"\");"; + after += "\n }"; + after += "\n}"; + rewriteRun( + java(before,after) + ); + } + + /** + * This test method is used to make sure that KeyCredentialPolicy type and import is changed + */ + @Test + void testKeyCredentialPolicyTypeAndImportChange() { + @Language("java") String before = "import com.azure.core.http.policy.KeyCredentialPolicy;"; + before += "\npublic class Testing {"; + before += "\n public Testing(){"; + before += "\n com.azure.core.http.policy.KeyCredentialPolicy kc = new KeyCredentialPolicy(\"key\", null);"; + before += "\n }"; + before += "\n}"; + + @Language("java") String after = "import io.clientcore.core.http.pipeline.KeyCredentialPolicy;"; + after += "\n\npublic class Testing {"; + after += "\n public Testing(){"; + after += "\n io.clientcore.core.http.pipeline.KeyCredentialPolicy kc = new KeyCredentialPolicy(\"key\", null);"; + after += "\n }"; + after += "\n}"; + rewriteRun( + java(before,after) + ); + } + + /** + * This test method is used to make sure that KeyCredentialTrait type and import is changed + */ + @Test + void testKeyCredentialTraitTypeAndImportChange() { + @Language("java") String before = "import com.azure.core.client.traits.KeyCredentialTrait;"; + before += "\npublic class Testing implements KeyCredentialTrait{"; + before += "\n public Testing(){"; + before += "\n }"; + before += "\n}"; + + @Language("java") String after = "import io.clientcore.core.models.traits.KeyCredentialTrait;"; + after += "\n\npublic class Testing implements KeyCredentialTrait {"; + after += "\n public Testing(){"; + after += "\n }"; + after += "\n}"; + rewriteRun( + java(before,after) + ); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/ExceptionTypesTest.java b/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/ExceptionTypesTest.java new file mode 100644 index 000000000000..10e91f388dbb --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/ExceptionTypesTest.java @@ -0,0 +1,201 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.openrewrite.recipe; + +import org.intellij.lang.annotations.Language; +import org.junit.jupiter.api.Test; +import static org.openrewrite.java.Assertions.java; +import org.openrewrite.test.RecipeSpec; +import org.openrewrite.test.RewriteTest; + +public class ExceptionTypesTest extends RecipeTestBase { + /** + * ExceptionTypesTest tests exception migrations from azure-core v1 + * to azure-core-v2 and client-core. + * Recipes used: ChangeType + * From: + * com.azure.core.exception + * ClientAuthenticationException + * HttpResponseException + * ResourceModifiedException + * ResourceNotFoundException + * To: + * com.azure.core.v2.exception + * ClientAuthenticationException + * ResourceModifiedException + * ResourceNotFoundException + * io.clientcore.core.http.exception + * HttpResponseException + * + */ + + + /* Testing ChangeType recipes */ + @Test + public void testClientAuthenticationExceptionChanged() { + @Language("java") String before = "import com.azure.core.exception.ClientAuthenticationException;"; + before += "\npublic class Testing {"; + before += "\n public void testMethod() {"; + before += "\n try {"; + before += "\n // Some code that may throw ClientAuthenticationException"; + before += "\n } catch (ClientAuthenticationException e) {"; + before += "\n // Handle exception"; + before += "\n }"; + before += "\n }"; + before += "\n}"; + + @Language("java") String after = "import com.azure.core.v2.exception.ClientAuthenticationException;"; + after += "\n\npublic class Testing {"; + after += "\n public void testMethod() {"; + after += "\n try {"; + after += "\n // Some code that may throw ClientAuthenticationException"; + after += "\n } catch (ClientAuthenticationException e) {"; + after += "\n // Handle exception"; + after += "\n }"; + after += "\n }"; + after += "\n}"; + + rewriteRun( + java(before,after) + ); + } + + + @Test + public void testHttpResponseExceptionChanged() { + @Language("java") String before = "import com.azure.core.exception.HttpResponseException;"; + before += "\npublic class Testing {"; + before += "\n public void testMethod() {"; + before += "\n try {"; + before += "\n // Some code that may throw HttpResponseException"; + before += "\n } catch (HttpResponseException e) {"; + before += "\n // Handle exception"; + before += "\n }"; + before += "\n }"; + before += "\n}"; + + @Language("java") String after = "import io.clientcore.core.http.exception.HttpResponseException;"; + after += "\n\npublic class Testing {"; + after += "\n public void testMethod() {"; + after += "\n try {"; + after += "\n // Some code that may throw HttpResponseException"; + after += "\n } catch (HttpResponseException e) {"; + after += "\n // Handle exception"; + after += "\n }"; + after += "\n }"; + after += "\n}"; + + rewriteRun( + java(before,after) + ); + } + + + @Test + public void testResourceModifiedExceptionChanged() { + @Language("java") String before = "import com.azure.core.exception.ResourceModifiedException;"; + before += "\npublic class Testing {"; + before += "\n public void testMethod() {"; + before += "\n try {"; + before += "\n // Some code that may throw ResourceModifiedException"; + before += "\n } catch (ResourceModifiedException e) {"; + before += "\n // Handle exception"; + before += "\n }"; + before += "\n }"; + before += "\n}"; + + @Language("java") String after = "import com.azure.core.v2.exception.ResourceModifiedException;"; + after += "\n\npublic class Testing {"; + after += "\n public void testMethod() {"; + after += "\n try {"; + after += "\n // Some code that may throw ResourceModifiedException"; + after += "\n } catch (ResourceModifiedException e) {"; + after += "\n // Handle exception"; + after += "\n }"; + after += "\n }"; + after += "\n}"; + + rewriteRun( + java(before,after) + ); + } + + + @Test + public void testResourceNotFoundExceptionChanged() { + @Language("java") String before = "import com.azure.core.exception.ResourceNotFoundException;"; + before += "\npublic class Testing {"; + before += "\n public void testMethod() {"; + before += "\n try {"; + before += "\n // Some code that may throw ResourceNotFoundException"; + before += "\n } catch (ResourceNotFoundException e) {"; + before += "\n // Handle exception"; + before += "\n }"; + before += "\n }"; + before += "\n}"; + + @Language("java") String after = "import com.azure.core.v2.exception.ResourceNotFoundException;"; + after += "\n\npublic class Testing {"; + after += "\n public void testMethod() {"; + after += "\n try {"; + after += "\n // Some code that may throw ResourceNotFoundException"; + after += "\n } catch (ResourceNotFoundException e) {"; + after += "\n // Handle exception"; + after += "\n }"; + after += "\n }"; + after += "\n}"; + + rewriteRun( + java(before,after) + ); + } + + /** + * Will fail and need updating if all azure-core v1 exceptions are migrated, + * or if all exceptions are migrated to the same directory. + */ + @Test + public void testBundledImportsChanged() { + @Language("java") String before = "import com.azure.core.exception.*;"; + before += "\npublic class Testing {"; + before += "\n public void testMethod() {"; + before += "\n try {"; + before += "\n // Some code that may throw ClientAuthenticationException"; + before += "\n throw new ClientAuthenticationException(null,null);"; + before += "\n } catch (ClientAuthenticationException e) {"; + before += "\n // Handle exception"; + before += "\n }"; + before += "\n try {"; + before += "\n // Some code that may throw HttpResponseException"; + before += "\n throw new HttpResponseException(null,null);"; + before += "\n } catch (HttpResponseException e) {"; + before += "\n // Handle exception"; + before += "\n }"; + before += "\n }"; + before += "\n}"; + + @Language("java") String after = "import com.azure.core.exception.*;" + + "\nimport com.azure.core.v2.exception.ClientAuthenticationException;" + + "\nimport io.clientcore.core.http.exception.HttpResponseException;"; + after += "\n\npublic class Testing {"; + after += "\n public void testMethod() {"; + after += "\n try {"; + after += "\n // Some code that may throw ClientAuthenticationException"; + after += "\n throw new ClientAuthenticationException(null,null);"; + after += "\n } catch (ClientAuthenticationException e) {"; + after += "\n // Handle exception"; + after += "\n }"; + after += "\n try {"; + after += "\n // Some code that may throw HttpResponseException"; + after += "\n throw new HttpResponseException(null,null);"; + after += "\n } catch (HttpResponseException e) {"; + after += "\n // Handle exception"; + after += "\n }"; + after += "\n }"; + after += "\n}"; + + rewriteRun( + java(before,after) + ); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/HttpHeaderNameTest.java b/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/HttpHeaderNameTest.java new file mode 100644 index 000000000000..8fcefa05d9ef --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/HttpHeaderNameTest.java @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.openrewrite.recipe; + +import org.intellij.lang.annotations.Language; +import org.junit.jupiter.api.Test; +import static org.openrewrite.java.Assertions.java; +import org.openrewrite.test.RecipeSpec; +import org.openrewrite.test.RewriteTest; + +public class HttpHeaderNameTest extends RecipeTestBase { + /** + * HttpHeaderNameTest tests the recipe that changes + * com.azure.core.http.HttpHeaderName to io.clientcore.core.http.models.HttpHeaderName. + */ + + + /* Test to make sure HttpHeaderName type is changed */ + @Test + public void testHeaderNameTypeChanged() { + @Language("java") String before = ""; + before += "public class Testing {"; + before += "\n public Testing(){"; + before += "\n com.azure.core.http.HttpHeaderName h = new com.azure.core.http.HttpHeaderName();"; + before += "\n }"; + before += "\n}"; + + @Language("java") String after = ""; + after += "public class Testing {"; + after += "\n public Testing(){"; + after += "\n io.clientcore.core.http.models.HttpHeaderName h = new io.clientcore.core.http.models.HttpHeaderName();"; + after += "\n }"; + after += "\n}"; + rewriteRun( + java(before,after) + ); + } + + /* Test to make sure HttpHeaderName import is changed */ + @Test + public void testHeaderNameImportChanged() { + @Language("java") String before = "import com.azure.core.http.HttpHeaderName;"; + before += "\npublic class Testing {"; + before += "\n public Testing(){"; + before += "\n HttpHeaderName h = new HttpHeaderName();"; + before += "\n }"; + before += "\n}"; + + @Language("java") String after = "import io.clientcore.core.http.models.HttpHeaderName;"; + after += "\n\npublic class Testing {"; + after += "\n public Testing(){"; + after += "\n HttpHeaderName h = new HttpHeaderName();"; + after += "\n }"; + after += "\n}"; + rewriteRun( + java(before,after) + ); + } + +} diff --git a/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/HttpLogOptionsTest.java b/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/HttpLogOptionsTest.java new file mode 100644 index 000000000000..4231918c89b0 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/HttpLogOptionsTest.java @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.openrewrite.recipe; + +import org.intellij.lang.annotations.Language; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import static org.openrewrite.java.Assertions.java; +import org.openrewrite.test.RecipeSpec; +import org.openrewrite.test.RewriteTest; + +// TODO: fix these tests to reflect current api +public class HttpLogOptionsTest extends RecipeTestBase { + /** + * HttpLogOptionsTest tests the recipe that changes + * com.azure.core.http.policy.HttpLogDetailLevel to io.clientcore.core.http.models.HttpLogOptions.HttpLogDetailLevel + * and com.azure.core.http.policy.HttpLogOptions to io.clientcore.core.http.models.HttpLogOptions + * + */ + + /* Test to make sure HttpLogOptions and HttpLogDetailLevel imports are changed*/ + @Disabled("These tests were written before clientcore structure was finalized. Need to be redone to reflect the current api") + @Test + public void testHttpLogOptionsLogLevelImportsChanged() { + @Language("java") String before = "import com.azure.core.http.policy.HttpLogOptions;"; + before += "\nimport com.azure.core.http.policy.HttpLogDetailLevel;"; + before += "\npublic class Testing {"; + before += "\n public Testing(){"; + before += "\n HttpLogOptions h = new HttpLogOptions();h.setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS);"; + before += "\n }"; + before += "\n}"; + + @Language("java") String after = "import io.clientcore.core.http.models.HttpLogOptions;"; + after += "\npublic class Testing {"; + after += "\n public Testing(){"; + after += "\n HttpLogOptions h = new HttpLogOptions();h.setLogLevel(HttpLogOptions.HttpLogDetailLevel.BODY_AND_HEADERS);"; + after += "\n }"; + after += "\n}"; + rewriteRun( + java(before, after) + ); + } + + + /* Test to make sure HttpLogOptions and HttpLogDetailLevel type is changed*/ + + @Disabled("These tests were written before clientcore structure was finalized. Need to be redone to reflect the current api") + @Test + public void testHttpLogOptionsLogLevelTypesChanged() { + @Language("java") String before = "\npublic class Testing {"; + before += "\n public Testing(){"; + before += "\n com.azure.core.http.policy.HttpLogOptions h = new com.azure.core.http.policy.HttpLogOptions();h.setLogLevel(com.azure.core.http.policy.HttpLogDetailLevel.BODY_AND_HEADERS);"; + before += "\n }"; + before += "\n}"; + + @Language("java") String after = "\npublic class Testing {"; + after += "\n public Testing(){"; + after += "\n io.clientcore.core.http.models.HttpLogOptions h = new io.clientcore.core.http.models.HttpLogOptions();h.setLogLevel( io.clientcore.core.http.models.HttpLogOptions.HttpLogDetailLevel.BODY_AND_HEADERS);"; + after += "\n }"; + after += "\n}"; + rewriteRun( + java(before, after) + ); + } + +} diff --git a/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/RecipeTestBase.java b/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/RecipeTestBase.java new file mode 100644 index 000000000000..3f70a624b828 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/RecipeTestBase.java @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.openrewrite.recipe; + +import org.openrewrite.test.RecipeSpec; +import org.openrewrite.test.RewriteTest; +import org.openrewrite.test.TypeValidation; + +public abstract class RecipeTestBase implements RewriteTest { + @Override + public void defaults(RecipeSpec spec) { + spec.recipeFromResources( + "com.azure.openrewrite.migrateToVNext", + "com.azure.openrewrite.recipes.migrateAzureCore", + "com.azure.openrewrite.recipes.migrateAzureStorageBlob" + ) + .typeValidationOptions(TypeValidation.none()); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/RequestOptionsTest.java b/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/RequestOptionsTest.java new file mode 100644 index 000000000000..4d5801aec4a1 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/RequestOptionsTest.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.openrewrite.recipe; + +import org.intellij.lang.annotations.Language; +import org.junit.jupiter.api.Test; +import static org.openrewrite.java.Assertions.java; +import org.openrewrite.test.RecipeSpec; +import org.openrewrite.test.RewriteTest; + +/** + * RequestOptionsTest is used to test out the recipe that converts com.azure.core.http.rest.RequestOptions + * to io.clientcore.core.http.models.RequestOptions. + */ +public class RequestOptionsTest extends RecipeTestBase { + + + /** + * This test method is used to make sure that the class import for RequestOptions is updated + */ + @Test + void testChangeRequestImportWithImport() { + @Language("java") String before = "import com.azure.core.http.rest.RequestOptions;\n"; + before += "\npublic class Testing {"; + before += "\n public Testing(){"; + before += "\n RequestOptions r = new RequestOptions();"; + before += "\n }"; + before += "\n}"; + + @Language("java") String after = "import io.clientcore.core.http.models.RequestOptions;\n"; + after += "\npublic class Testing {"; + after += "\n public Testing(){"; + after += "\n RequestOptions r = new RequestOptions();"; + after += "\n }"; + after += "\n}"; + rewriteRun( + java(before, after) + ); + } + + /** + * This test method is used to make sure that the class type for RequestOptions is updated + */ + @Test + void testChangeRequestImportWithFullyQualifiedName() { + @Language("java") String before = "public class Testing {"; + before += "\n public Testing(){"; + before += "\n\tcom.azure.core.http.rest.RequestOptions r = new com.azure.core.http.rest.RequestOptions();"; + before += "\n }"; + before += "\n}"; + + @Language("java") String after = "public class Testing {"; + after += "\n public Testing(){"; + after += "\n\tio.clientcore.core.http.models.RequestOptions r = new io.clientcore.core.http.models.RequestOptions();"; + after += "\n }"; + after += "\n}"; + rewriteRun( + java(before, after) + ); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/ResponseTest.java b/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/ResponseTest.java new file mode 100644 index 000000000000..56224346ea0e --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/ResponseTest.java @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.openrewrite.recipe; + +import org.intellij.lang.annotations.Language; +import org.junit.jupiter.api.Test; +import static org.openrewrite.java.Assertions.java; +import org.openrewrite.test.RecipeSpec; +import org.openrewrite.test.RewriteTest; + +/** + * ResponseTest is used to test out the recipe that changes + * references to com.azure.core.http.rest.response to + * io.clientcore.core.http.models.response. + */ +public class ResponseTest extends RecipeTestBase { + + /** + * This test method is used to make sure that the Response import is updated to the new version + */ + @Test + void testUpdateResponseTypeWithImport() { + @Language("java") String before = "import com.azure.core.http.rest.Response;\n"; + before += "\npublic class Testing {"; + before += "\n public Testing(){"; + before += "\n Response str = null;"; + before += "\n }"; + before += "\n}"; + + @Language("java") String after = "import io.clientcore.core.http.models.Response;\n"; + after += "\npublic class Testing {"; + after += "\n public Testing(){"; + after += "\n Response str = null;"; + after += "\n }"; + after += "\n}"; + rewriteRun( + java(before, after) + ); + } + /** + * This test method is used to make sure that the Response type is updated to the new version + */ + @Test + void testUpdateResponseTypeWithFullyQualifiedName() { + @Language("java") String before = "public class Testing {"; + before += "\n public Testing(){"; + before += "\n com.azure.core.http.rest.Response str = null;"; + before += "\n }"; + before += "\n}"; + + @Language("java") String after = "public class Testing {"; + after += "\n public Testing(){"; + after += "\n io.clientcore.core.http.models.Response str = null;"; + after += "\n }"; + after += "\n}"; + rewriteRun( + java(before, after) + ); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/RetryOptionsConstructorTest.java b/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/RetryOptionsConstructorTest.java new file mode 100644 index 000000000000..7fec195d88c7 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/RetryOptionsConstructorTest.java @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.openrewrite.recipe; + + +import org.intellij.lang.annotations.Language; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import static org.openrewrite.java.Assertions.java; +import org.openrewrite.test.RecipeSpec; +import org.openrewrite.test.RewriteTest; + +/** + * RetryOptionsTest is used to test out the recipe that removes usage of + * FixedDelay and ExponentialDelay from the RetryOptions constructor and updates + * it to use the new azure-core-v2 HttpRetryOptions class. + */ +// TODO: fix these tests to reflect current api +public class RetryOptionsConstructorTest extends RecipeTestBase { + + + /** + * This test method is used to make sure that RetryOptions is updated to the new constructor and class + */ + @Disabled("These tests were written before clientcore structure was finalized. Need to be redone to reflect the current api") + @Test + void testChangeRetryOptionsType() { + @Language("java") String before = "import com.azure.core.http.policy.RetryOptions;import java.time.Duration;import com.azure.core.http.policy.FixedDelayOptions;"; + before += "\npublic class Testing {"; + before += "\n public Testing(){"; + before += "\n RetryOptions r = new RetryOptions(new FixedDelayOptions(3, Duration.ofMillis(50)));"; + before += "\n }"; + before += "\n}"; + + @Language("java") String after = "import io.clientcore.core.http.models.HttpRetryOptions;\n\nimport java.time.Duration;\n"; + after += "\npublic class Testing {"; + after += "\n public Testing(){"; + after += "\n HttpRetryOptions r = new HttpRetryOptions(3, Duration.ofMillis(50));"; + after += "\n }"; + after += "\n}"; + rewriteRun( + java(before,after) + ); + } + + /** + * This test method is used to make sure that RetryOptions is updated to the new constructor and class + * if the FixedDelayOptions is passed as a variable and not a direct instantiation in the constructor of + * the RetryOptions. + */ + @Disabled("These tests were written before clientcore structure was finalized. Need to be redone to reflect the current api") + @Test + void testChangeRetryOptionsTypeNoArgInit() { + @Language("java") String before = "import com.azure.core.http.policy.RetryOptions;import java.time.Duration;import com.azure.core.http.policy.FixedDelayOptions;"; + before += "\npublic class Testing {"; + before += "\n FixedDelayOptions f = new FixedDelayOptions(3, Duration.ofMillis(50));"; + before += "\n public Testing(){"; + before += "\n RetryOptions r = new RetryOptions(f);"; + before += "\n }"; + before += "\n}"; + + @Language("java") String after = "import io.clientcore.core.http.models.HttpRetryOptions;\n\nimport java.time.Duration;\n"; + after += "\npublic class Testing {"; + after += "\n public Testing(){"; + after += "\n HttpRetryOptions r = new HttpRetryOptions(3, Duration.ofMillis(50));"; + after += "\n }"; + after += "\n}"; + rewriteRun( + java(before,after) + ); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/TypeReferenceTest.java b/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/TypeReferenceTest.java new file mode 100644 index 000000000000..7d95773e9c8e --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/TypeReferenceTest.java @@ -0,0 +1,138 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.openrewrite.recipe; + + +import org.intellij.lang.annotations.Language; +import org.junit.jupiter.api.Test; +import static org.openrewrite.java.Assertions.java; +import org.openrewrite.test.RecipeSpec; +import org.openrewrite.test.RewriteTest; +import org.openrewrite.test.TypeValidation; + +/** + * TypeReferenceTest is used to test out the recipe that changes the usage of TypeReference (azure core v1) + * to ParameterizedType (azure core v2) + */ +public class TypeReferenceTest extends RecipeTestBase { + + /** + * This test method is used to make sure that TypeReference is correctly + * changed to ParameterizedType when using List generic type + */ + @Test + void testTypeReferenceVariableDeclarationChangeList() { + @Language("java") String before = ""; + before += "\nimport java.lang.reflect.ParameterizedType;"; + before += "\nimport java.lang.reflect.Type;"; + before += "\nimport java.util.List;"; + before += "\nimport com.azure.core.util.serializer.TypeReference;"; + before += "\npublic class Testing {"; + before += "\n private static final TypeReference> TESTING_TYPE = new TypeReference>() {\n };"; + before += "\n}"; + + + @Language("java") String after = "import java.lang.reflect.ParameterizedType;\n" + + "import java.lang.reflect.Type;\n" + + "import java.util.List;\n"+ + "public class Testing {\n" + + " private static final Type TESTING_TYPE = new ParameterizedType() {\n" + + " @Override\n" + + " public Type getRawType() {\n" + + " return List.class;\n" + + " }\n\n" + + " @Override\n" + + " public Type[] getActualTypeArguments() {\n" + + " return new Type[]{String.class};\n" + + " }\n\n" + + " @Override\n" + + " public Type getOwnerType() {\n" + + " return null;\n" + + " }\n" + + " };\n" + + "}\n"; + + rewriteRun( + + java(before,after) + ); + } + /** + * This test method is used to make sure that TypeReference is correctly + * changed to ParameterizedType when using Map generic type + */ + @Test + void testTypeReferenceVariableDeclarationChangeMap() { + @Language("java") String before = ""; + before += "\nimport java.lang.reflect.ParameterizedType;"; + before += "\nimport java.lang.reflect.Type;"; + before += "\nimport java.util.Map;"; + before += "\nimport com.azure.core.util.serializer.TypeReference;"; + before += "\npublic class Testing {"; + before += "\n private static final TypeReference> TESTING_TYPE = new TypeReference>() {\n };"; + before += "\n}"; + + + @Language("java") String after = "import java.lang.reflect.ParameterizedType;\n" + + "import java.lang.reflect.Type;\n" + + "import java.util.Map;\n" + + "public class Testing {\n" + + " private static final Type TESTING_TYPE = new ParameterizedType() {\n" + + " @Override\n" + + " public Type getRawType() {\n" + + " return Map.class;\n" + + " }\n\n" + + " @Override\n" + + " public Type[] getActualTypeArguments() {\n" + + " return new Type[]{String.class, Integer.class};\n" + + " }\n\n" + + " @Override\n" + + " public Type getOwnerType() {\n" + + " return null;\n" + + " }\n" + + " };\n" + + "}\n"; + + rewriteRun( + java(before,after) + ); + } + /** + * This test method is used to make sure that TypeReference is correctly + * changed to ParameterizedType when using non-generic type + */ + @Test + void testTypeReferenceVariableDeclarationChangeNonGeneric() { + @Language("java") String before = ""; + before += "\nimport java.lang.reflect.ParameterizedType;"; + before += "\nimport java.lang.reflect.Type;"; + before += "\nimport com.azure.core.util.serializer.TypeReference;"; + before += "\npublic class Testing {"; + before += "\n private static final TypeReference TESTING_TYPE = new TypeReference() {\n };"; + before += "\n}"; + + + @Language("java") String after = "import java.lang.reflect.ParameterizedType;\n" + + "import java.lang.reflect.Type;\n" + + "public class Testing {\n" + + " private static final Type TESTING_TYPE = new ParameterizedType() {\n" + + " @Override\n" + + " public Type getRawType() {\n" + + " return String.class;\n" + + " }\n\n" + + " @Override\n" + + " public Type[] getActualTypeArguments() {\n" + + " return new Type[]{};\n" + + " }\n\n" + + " @Override\n" + + " public Type getOwnerType() {\n" + + " return null;\n" + + " }\n" + + " };\n" + + "}\n"; + + rewriteRun( + java(before,after) + ); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/UtilConfigurationTest.java b/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/UtilConfigurationTest.java new file mode 100644 index 000000000000..7267d9426b9d --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/java/com/azure/openrewrite/recipe/UtilConfigurationTest.java @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.openrewrite.recipe; + +import org.intellij.lang.annotations.Language; +import org.junit.jupiter.api.Test; +import static org.openrewrite.java.Assertions.java; +import org.openrewrite.test.RecipeSpec; +import org.openrewrite.test.RewriteTest; + +public class UtilConfigurationTest extends RecipeTestBase { + + /* Testing ChangeType recipe for changing import */ + @Test + public void testConfigurationWithImport() { + @Language("java") String before = "import com.azure.core.util.Configuration;"; + before += "\npublic class Testing {"; + before += "\n public Testing(){"; + before += "\n Configuration c = new Configuration();"; + before += "\n }"; + before += "\n}"; + + @Language("java") String after = "import io.clientcore.core.util.configuration.Configuration;"; + after += "\n\npublic class Testing {"; + after += "\n public Testing(){"; + after += "\n Configuration c = new Configuration();"; + after += "\n }"; + after += "\n}"; + rewriteRun( + java(before, after) + ); + } + + /* Testing ChangeType recipe for changing type */ + @Test + public void testConfigurationWithFullyQualifiedName() { + @Language("java") String before = "public class Testing {"; + before += "\n public Testing(){"; + before += "\n com.azure.core.util.Configuration c = new com.azure.core.util.Configuration();"; + before += "\n }"; + before += "\n}"; + + @Language("java") String after = "public class Testing {"; + after += "\n public Testing(){"; + after += "\n io.clientcore.core.util.configuration.Configuration c = new io.clientcore.core.util.configuration.Configuration();"; + after += "\n }"; + after += "\n}"; + rewriteRun( + java(before, after) + ); + } + +} diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/AadAuthentication.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample1/v1/AadAuthentication.java similarity index 100% rename from sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/AadAuthentication.java rename to sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample1/v1/AadAuthentication.java diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample1/v2/AadAuthentication.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample1/v2/AadAuthentication.java new file mode 100644 index 000000000000..3f52b14050b4 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample1/v2/AadAuthentication.java @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.identity.DefaultAzureCredential; +import com.azure.identity.DefaultAzureCredentialBuilder; + +/** + * Sample demonstrates how to use AAD token to build a configuration client. + */ +public class AadAuthentication { + /** + * Sample for how to use AAD token Authentication. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The endpoint can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Overview" page. Looking for the "Endpoint" keyword. + String endpoint = "{endpoint_value}"; + + // Default token credential could be obtained from Identity service. + // It tries to create a valid credential in the following order: + // EnvironmentCredential + // ManagedIdentityCredential + // SharedTokenCacheCredential + // Fails if none of the credentials above could be created. + DefaultAzureCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); + + final ConfigurationClient client = new ConfigurationClientBuilder() + .credential(tokenCredential) // AAD authentication + .endpoint(endpoint) + .buildClient(); + + // Name of the key to add to the configuration service. + final String key = "hello"; + final String value = "world"; + + System.out.println("Beginning of synchronous sample..."); + + ConfigurationSetting setting = client.setConfigurationSetting(key, null, value); + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + + setting = client.getConfigurationSetting(key, null, null); + System.out.printf("[GetConfigurationSetting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + + setting = client.deleteConfigurationSetting(key, null); + System.out.printf("[DeleteConfigurationSetting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + + System.out.println("End of synchronous sample."); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample10/v1/CreateSnapshotAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample10/v1/CreateSnapshotAsync.java new file mode 100644 index 000000000000..b0910066595f --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample10/v1/CreateSnapshotAsync.java @@ -0,0 +1,122 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.ConfigurationSettingsFilter; +import com.azure.data.appconfiguration.models.ConfigurationSnapshot; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** + * Sample demonstrates how to create, retrieve, archive, recover a configuration setting snapshot, and list settings + * by snapshot name asynchronously. + */ +public class CreateSnapshotAsync { + /** + * Runs the sample demonstrates how to create, retrieve, archive, recover a configuration setting snapshot, and + * list settings by snapshot name asynchronously. + * + * @param args Unused. Arguments to the program. + * @throws InterruptedException when a thread is waiting, sleeping, or otherwise occupied, + * and the thread is interrupted, either before or during the activity. + */ + public static void main(String[] args) throws InterruptedException { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Asynchronous sample + // Instantiate a client that will be used to call the service. + final ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + // Prepare first setting. + client.setConfigurationSetting("TestKey1", null, "v1").subscribe( + result -> { + final ConfigurationSetting setting = result; + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + }, + error -> System.err.println("There was an error adding the setting: " + error), + () -> System.out.printf("Set setting with key=%s and value=%s added or updated.%n", "key1", "v1")); + + // Prepare second setting. + client.setConfigurationSetting("TestKey2", null, "v2").subscribe( + result -> { + final ConfigurationSetting setting = result; + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s.%n", setting.getKey(), setting.getValue()); + }, + error -> System.err.println("There was an error adding the setting: " + error), + () -> System.out.printf("Set setting with key=%s and value=%s added or updated.%n", "key2", "v2")); + + TimeUnit.MILLISECONDS.sleep(1000); + + // Prepare the snapshot filters + List filters = new ArrayList<>(); + // Key Name also supports RegExp but only support prefix end with "*", such as "k*" and is case-sensitive. + filters.add(new ConfigurationSettingsFilter("Test*")); + String snapshotName = "{snapshotName}"; + + client.beginCreateSnapshot(snapshotName, new ConfigurationSnapshot(filters)) + .flatMap(result -> result.getFinalResult()) + .subscribe( + snapshot -> { + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + snapshot.getName(), snapshot.getCreatedAt(), snapshot.getStatus()); + }, + ex -> System.out.printf("Error on creating a snapshot=%s, with error=%s.%n", snapshotName, ex.getMessage()), + () -> System.out.println("Successfully created a snapshot.")); + + // Get the snapshot status + client.getSnapshot(snapshotName).subscribe( + getSnapshot -> { + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + getSnapshot.getName(), getSnapshot.getCreatedAt(), getSnapshot.getStatus()); + } + ); + + TimeUnit.MILLISECONDS.sleep(1000); + + // Archive a READY snapshot + client.archiveSnapshot(snapshotName).subscribe( + archivedSnapshot -> { + System.out.printf("Archived snapshot name=%s is created at %s, snapshot status is %s.%n", + archivedSnapshot.getName(), archivedSnapshot.getCreatedAt(), archivedSnapshot.getStatus()); + } + ); + + TimeUnit.MILLISECONDS.sleep(1000); + + // Recover the Archived snapshot + client.recoverSnapshot(snapshotName).subscribe( + recoveredSnapshot -> { + System.out.printf("Recovered snapshot name=%s is created at %s, snapshot status is %s.%n", + recoveredSnapshot.getName(), recoveredSnapshot.getCreatedAt(), recoveredSnapshot.getStatus()); + } + ); + + TimeUnit.MILLISECONDS.sleep(1000); + + // List the configuration settings in the snapshot + client.listConfigurationSettingsForSnapshot(snapshotName).subscribe( + settingInSnapshot -> { + System.out.printf("[ConfigurationSetting in snapshot] Key: %s, Value: %s.%n", + settingInSnapshot.getKey(), settingInSnapshot.getValue()); + } + ); + + TimeUnit.MILLISECONDS.sleep(1000); + + // The .subscribe() creation and assignment is not a blocking call. For the purpose of this example, we sleep + // the thread so the program does not end before the send operation is complete. Using .block() instead of + // .subscribe() will turn this into a synchronous call. + try { + TimeUnit.MINUTES.sleep(5); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample10/v2/CreateSnapshotAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample10/v2/CreateSnapshotAsync.java new file mode 100644 index 000000000000..b0910066595f --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample10/v2/CreateSnapshotAsync.java @@ -0,0 +1,122 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.ConfigurationSettingsFilter; +import com.azure.data.appconfiguration.models.ConfigurationSnapshot; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** + * Sample demonstrates how to create, retrieve, archive, recover a configuration setting snapshot, and list settings + * by snapshot name asynchronously. + */ +public class CreateSnapshotAsync { + /** + * Runs the sample demonstrates how to create, retrieve, archive, recover a configuration setting snapshot, and + * list settings by snapshot name asynchronously. + * + * @param args Unused. Arguments to the program. + * @throws InterruptedException when a thread is waiting, sleeping, or otherwise occupied, + * and the thread is interrupted, either before or during the activity. + */ + public static void main(String[] args) throws InterruptedException { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Asynchronous sample + // Instantiate a client that will be used to call the service. + final ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + // Prepare first setting. + client.setConfigurationSetting("TestKey1", null, "v1").subscribe( + result -> { + final ConfigurationSetting setting = result; + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + }, + error -> System.err.println("There was an error adding the setting: " + error), + () -> System.out.printf("Set setting with key=%s and value=%s added or updated.%n", "key1", "v1")); + + // Prepare second setting. + client.setConfigurationSetting("TestKey2", null, "v2").subscribe( + result -> { + final ConfigurationSetting setting = result; + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s.%n", setting.getKey(), setting.getValue()); + }, + error -> System.err.println("There was an error adding the setting: " + error), + () -> System.out.printf("Set setting with key=%s and value=%s added or updated.%n", "key2", "v2")); + + TimeUnit.MILLISECONDS.sleep(1000); + + // Prepare the snapshot filters + List filters = new ArrayList<>(); + // Key Name also supports RegExp but only support prefix end with "*", such as "k*" and is case-sensitive. + filters.add(new ConfigurationSettingsFilter("Test*")); + String snapshotName = "{snapshotName}"; + + client.beginCreateSnapshot(snapshotName, new ConfigurationSnapshot(filters)) + .flatMap(result -> result.getFinalResult()) + .subscribe( + snapshot -> { + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + snapshot.getName(), snapshot.getCreatedAt(), snapshot.getStatus()); + }, + ex -> System.out.printf("Error on creating a snapshot=%s, with error=%s.%n", snapshotName, ex.getMessage()), + () -> System.out.println("Successfully created a snapshot.")); + + // Get the snapshot status + client.getSnapshot(snapshotName).subscribe( + getSnapshot -> { + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + getSnapshot.getName(), getSnapshot.getCreatedAt(), getSnapshot.getStatus()); + } + ); + + TimeUnit.MILLISECONDS.sleep(1000); + + // Archive a READY snapshot + client.archiveSnapshot(snapshotName).subscribe( + archivedSnapshot -> { + System.out.printf("Archived snapshot name=%s is created at %s, snapshot status is %s.%n", + archivedSnapshot.getName(), archivedSnapshot.getCreatedAt(), archivedSnapshot.getStatus()); + } + ); + + TimeUnit.MILLISECONDS.sleep(1000); + + // Recover the Archived snapshot + client.recoverSnapshot(snapshotName).subscribe( + recoveredSnapshot -> { + System.out.printf("Recovered snapshot name=%s is created at %s, snapshot status is %s.%n", + recoveredSnapshot.getName(), recoveredSnapshot.getCreatedAt(), recoveredSnapshot.getStatus()); + } + ); + + TimeUnit.MILLISECONDS.sleep(1000); + + // List the configuration settings in the snapshot + client.listConfigurationSettingsForSnapshot(snapshotName).subscribe( + settingInSnapshot -> { + System.out.printf("[ConfigurationSetting in snapshot] Key: %s, Value: %s.%n", + settingInSnapshot.getKey(), settingInSnapshot.getValue()); + } + ); + + TimeUnit.MILLISECONDS.sleep(1000); + + // The .subscribe() creation and assignment is not a blocking call. For the purpose of this example, we sleep + // the thread so the program does not end before the send operation is complete. Using .block() instead of + // .subscribe() will turn this into a synchronous call. + try { + TimeUnit.MINUTES.sleep(5); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample11/v1/CreateSnapshotWithTagsFilter.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample11/v1/CreateSnapshotWithTagsFilter.java new file mode 100644 index 000000000000..ab8edf42c46e --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample11/v1/CreateSnapshotWithTagsFilter.java @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.util.Configuration; +import com.azure.core.util.Context; +import com.azure.core.util.polling.PollOperationDetails; +import com.azure.core.util.polling.SyncPoller; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.ConfigurationSettingsFilter; +import com.azure.data.appconfiguration.models.ConfigurationSnapshot; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static com.azure.data.appconfiguration.implementation.Utility.getTagsFilterInString; + +/** + * Sample demonstrates how to create configuration setting snapshot with tags filter, and list settings by snapshot name. + */ +public class CreateSnapshotWithTagsFilter { + /** + * Runs the sample demonstrates how to create, retrieve, archive, recover a configuration setting snapshot, and + * list settings by snapshot name. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = Configuration.getGlobalConfiguration().get("AZURE_APPCONFIG_CONNECTION_STRING"); + + // Instantiate a client that will be used to call the service. + final ConfigurationClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + + // Prepare settings with tags + Map tags = new HashMap<>(); + tags.put("release", "first"); + Map tags2 = new HashMap<>(); + tags2.put("release", "first"); + tags2.put("release2", "second"); + ConfigurationSetting setting1 = client.setConfigurationSetting(new ConfigurationSetting().setKey("keyForTag1").setValue("value1").setTags(tags)); + System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting1.getKey(), setting1.getValue(), setting1.getTags()); + ConfigurationSetting setting2 = client.setConfigurationSetting(new ConfigurationSetting().setKey("keyForTag2").setValue("value2").setTags(tags2)); + System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting2.getKey(), setting2.getValue(), setting2.getTags()); + ConfigurationSetting setting3 = client.setConfigurationSetting(new ConfigurationSetting().setKey("key3WithoutTag").setValue("value3")); + System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting3.getKey(), setting3.getValue(), setting3.getTags()); + + // Prepare the snapshot filters with key filter and tags filter + List tagsFilterInString = getTagsFilterInString(tags2); + List filters = new ArrayList<>(); + // Key Name also supports RegExp but only support prefix end with "*", such as "k*" and is case-sensitive. + System.out.println("Prepare tags filter = " + tagsFilterInString); + filters.add(new ConfigurationSettingsFilter("key*").setTags(tagsFilterInString)); + + // Create a snapshot + String snapshotName = "{snapshotName}"; + SyncPoller poller = + client.beginCreateSnapshot(snapshotName, new ConfigurationSnapshot(filters), Context.NONE); + poller.setPollInterval(Duration.ofSeconds(10)); + poller.waitForCompletion(); + ConfigurationSnapshot snapshot = poller.getFinalResult(); + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + snapshot.getName(), snapshot.getCreatedAt(), snapshot.getStatus()); + + // List the configuration settings in the snapshot + client.listConfigurationSettingsForSnapshot(snapshotName).forEach( + settingInSnapshot -> { + System.out.printf("[ConfigurationSetting In Snapshot] Key: %s, Value: %s, Tags:%s.%n", + settingInSnapshot.getKey(), settingInSnapshot.getValue(), settingInSnapshot.getTags()); + } + ); + + System.out.println("End of synchronous sample."); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample11/v2/CreateSnapshotWithTagsFilter.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample11/v2/CreateSnapshotWithTagsFilter.java new file mode 100644 index 000000000000..ab8edf42c46e --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample11/v2/CreateSnapshotWithTagsFilter.java @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.util.Configuration; +import com.azure.core.util.Context; +import com.azure.core.util.polling.PollOperationDetails; +import com.azure.core.util.polling.SyncPoller; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.ConfigurationSettingsFilter; +import com.azure.data.appconfiguration.models.ConfigurationSnapshot; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static com.azure.data.appconfiguration.implementation.Utility.getTagsFilterInString; + +/** + * Sample demonstrates how to create configuration setting snapshot with tags filter, and list settings by snapshot name. + */ +public class CreateSnapshotWithTagsFilter { + /** + * Runs the sample demonstrates how to create, retrieve, archive, recover a configuration setting snapshot, and + * list settings by snapshot name. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = Configuration.getGlobalConfiguration().get("AZURE_APPCONFIG_CONNECTION_STRING"); + + // Instantiate a client that will be used to call the service. + final ConfigurationClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + + // Prepare settings with tags + Map tags = new HashMap<>(); + tags.put("release", "first"); + Map tags2 = new HashMap<>(); + tags2.put("release", "first"); + tags2.put("release2", "second"); + ConfigurationSetting setting1 = client.setConfigurationSetting(new ConfigurationSetting().setKey("keyForTag1").setValue("value1").setTags(tags)); + System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting1.getKey(), setting1.getValue(), setting1.getTags()); + ConfigurationSetting setting2 = client.setConfigurationSetting(new ConfigurationSetting().setKey("keyForTag2").setValue("value2").setTags(tags2)); + System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting2.getKey(), setting2.getValue(), setting2.getTags()); + ConfigurationSetting setting3 = client.setConfigurationSetting(new ConfigurationSetting().setKey("key3WithoutTag").setValue("value3")); + System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting3.getKey(), setting3.getValue(), setting3.getTags()); + + // Prepare the snapshot filters with key filter and tags filter + List tagsFilterInString = getTagsFilterInString(tags2); + List filters = new ArrayList<>(); + // Key Name also supports RegExp but only support prefix end with "*", such as "k*" and is case-sensitive. + System.out.println("Prepare tags filter = " + tagsFilterInString); + filters.add(new ConfigurationSettingsFilter("key*").setTags(tagsFilterInString)); + + // Create a snapshot + String snapshotName = "{snapshotName}"; + SyncPoller poller = + client.beginCreateSnapshot(snapshotName, new ConfigurationSnapshot(filters), Context.NONE); + poller.setPollInterval(Duration.ofSeconds(10)); + poller.waitForCompletion(); + ConfigurationSnapshot snapshot = poller.getFinalResult(); + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + snapshot.getName(), snapshot.getCreatedAt(), snapshot.getStatus()); + + // List the configuration settings in the snapshot + client.listConfigurationSettingsForSnapshot(snapshotName).forEach( + settingInSnapshot -> { + System.out.printf("[ConfigurationSetting In Snapshot] Key: %s, Value: %s, Tags:%s.%n", + settingInSnapshot.getKey(), settingInSnapshot.getValue(), settingInSnapshot.getTags()); + } + ); + + System.out.println("End of synchronous sample."); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample12/v1/CreateSnapshotWithTagsFilterAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample12/v1/CreateSnapshotWithTagsFilterAsync.java new file mode 100644 index 000000000000..6bb376c832b4 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample12/v1/CreateSnapshotWithTagsFilterAsync.java @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.util.Configuration; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.ConfigurationSettingsFilter; +import com.azure.data.appconfiguration.models.ConfigurationSnapshot; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import static com.azure.data.appconfiguration.implementation.Utility.getTagsFilterInString; + +/** + * Sample demonstrates how to create configuration setting snapshot with tags filter, and list settings by snapshot name + * asynchronously. + */ +public class CreateSnapshotWithTagsFilterAsync { + /** + * Runs the sample demonstrates how to create configuration setting snapshot with tags filter, and list settings by snapshot name + * asynchronously. + * + * @param args Unused. Arguments to the program. + * @throws InterruptedException when a thread is waiting, sleeping, or otherwise occupied, + * and the thread is interrupted, either before or during the activity. + */ + public static void main(String[] args) throws InterruptedException { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = Configuration.getGlobalConfiguration().get("AZURE_APPCONFIG_CONNECTION_STRING"); + + // Asynchronous sample + // Instantiate a client that will be used to call the service. + final ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + + // Prepare settings with tags + Map tags = new HashMap<>(); + tags.put("release", "first"); + Map tags2 = new HashMap<>(); + tags2.put("release", "first"); + tags2.put("release2", "second"); + client.setConfigurationSetting(new ConfigurationSetting().setKey("keyForTag1").setValue("value1").setTags(tags)) + .subscribe(setting -> System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting.getKey(), setting.getValue(), setting.getTags())); + + client.setConfigurationSetting(new ConfigurationSetting().setKey("keyForTag2").setValue("value2").setTags(tags2)) + .subscribe(setting -> System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting.getKey(), setting.getValue(), setting.getTags())); + + client.setConfigurationSetting(new ConfigurationSetting().setKey("key3WithoutTag").setValue("value3")) + .subscribe(setting -> System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting.getKey(), setting.getValue(), setting.getTags())); + TimeUnit.MILLISECONDS.sleep(1000); + + // Prepare the snapshot filters with key filter and tags filter + List tagsFilterInString = getTagsFilterInString(tags2); + List filters = new ArrayList<>(); + // Key Name also supports RegExp but only support prefix end with "*", such as "k*" and is case-sensitive. + System.out.println("Prepare tags filter = " + tagsFilterInString); + filters.add(new ConfigurationSettingsFilter("key*").setTags(tagsFilterInString)); + String snapshotName = "{snapshotName}6"; + + client.beginCreateSnapshot(snapshotName, new ConfigurationSnapshot(filters)) + .flatMap(result -> result.getFinalResult()) + .subscribe( + snapshot -> { + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + snapshot.getName(), snapshot.getCreatedAt(), snapshot.getStatus()); + }, + ex -> System.out.printf("Error on creating a snapshot=%s, with error=%s.%n", snapshotName, ex.getMessage()), + () -> System.out.println("Successfully created a snapshot.")); + + TimeUnit.MINUTES.sleep(1); + + // List the configuration settings in the snapshot + client.listConfigurationSettingsForSnapshot(snapshotName).subscribe( + settingInSnapshot -> { + System.out.printf("[ConfigurationSetting In Snapshot] Key: %s, Value: %s, Tags:%s.%n", + settingInSnapshot.getKey(), settingInSnapshot.getValue(), settingInSnapshot.getTags()); + }, + ex -> System.out.printf("Error on listing settings in snapshot=%s, with error=%s.%n", snapshotName, ex.getMessage()), + () -> System.out.println("Successfully listed settings.")); + + TimeUnit.MILLISECONDS.sleep(1000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample12/v2/CreateSnapshotWithTagsFilterAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample12/v2/CreateSnapshotWithTagsFilterAsync.java new file mode 100644 index 000000000000..6bb376c832b4 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample12/v2/CreateSnapshotWithTagsFilterAsync.java @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.util.Configuration; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.ConfigurationSettingsFilter; +import com.azure.data.appconfiguration.models.ConfigurationSnapshot; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import static com.azure.data.appconfiguration.implementation.Utility.getTagsFilterInString; + +/** + * Sample demonstrates how to create configuration setting snapshot with tags filter, and list settings by snapshot name + * asynchronously. + */ +public class CreateSnapshotWithTagsFilterAsync { + /** + * Runs the sample demonstrates how to create configuration setting snapshot with tags filter, and list settings by snapshot name + * asynchronously. + * + * @param args Unused. Arguments to the program. + * @throws InterruptedException when a thread is waiting, sleeping, or otherwise occupied, + * and the thread is interrupted, either before or during the activity. + */ + public static void main(String[] args) throws InterruptedException { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = Configuration.getGlobalConfiguration().get("AZURE_APPCONFIG_CONNECTION_STRING"); + + // Asynchronous sample + // Instantiate a client that will be used to call the service. + final ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + + // Prepare settings with tags + Map tags = new HashMap<>(); + tags.put("release", "first"); + Map tags2 = new HashMap<>(); + tags2.put("release", "first"); + tags2.put("release2", "second"); + client.setConfigurationSetting(new ConfigurationSetting().setKey("keyForTag1").setValue("value1").setTags(tags)) + .subscribe(setting -> System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting.getKey(), setting.getValue(), setting.getTags())); + + client.setConfigurationSetting(new ConfigurationSetting().setKey("keyForTag2").setValue("value2").setTags(tags2)) + .subscribe(setting -> System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting.getKey(), setting.getValue(), setting.getTags())); + + client.setConfigurationSetting(new ConfigurationSetting().setKey("key3WithoutTag").setValue("value3")) + .subscribe(setting -> System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting.getKey(), setting.getValue(), setting.getTags())); + TimeUnit.MILLISECONDS.sleep(1000); + + // Prepare the snapshot filters with key filter and tags filter + List tagsFilterInString = getTagsFilterInString(tags2); + List filters = new ArrayList<>(); + // Key Name also supports RegExp but only support prefix end with "*", such as "k*" and is case-sensitive. + System.out.println("Prepare tags filter = " + tagsFilterInString); + filters.add(new ConfigurationSettingsFilter("key*").setTags(tagsFilterInString)); + String snapshotName = "{snapshotName}6"; + + client.beginCreateSnapshot(snapshotName, new ConfigurationSnapshot(filters)) + .flatMap(result -> result.getFinalResult()) + .subscribe( + snapshot -> { + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + snapshot.getName(), snapshot.getCreatedAt(), snapshot.getStatus()); + }, + ex -> System.out.printf("Error on creating a snapshot=%s, with error=%s.%n", snapshotName, ex.getMessage()), + () -> System.out.println("Successfully created a snapshot.")); + + TimeUnit.MINUTES.sleep(1); + + // List the configuration settings in the snapshot + client.listConfigurationSettingsForSnapshot(snapshotName).subscribe( + settingInSnapshot -> { + System.out.printf("[ConfigurationSetting In Snapshot] Key: %s, Value: %s, Tags:%s.%n", + settingInSnapshot.getKey(), settingInSnapshot.getValue(), settingInSnapshot.getTags()); + }, + ex -> System.out.printf("Error on listing settings in snapshot=%s, with error=%s.%n", snapshotName, ex.getMessage()), + () -> System.out.println("Successfully listed settings.")); + + TimeUnit.MILLISECONDS.sleep(1000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample13/v1/FeatureFlagConfigurationSettingSample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample13/v1/FeatureFlagConfigurationSettingSample.java new file mode 100644 index 000000000000..0e2805e9a75f --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample13/v1/FeatureFlagConfigurationSettingSample.java @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.FeatureFlagConfigurationSetting; +import com.azure.data.appconfiguration.models.FeatureFlagFilter; +import com.azure.data.appconfiguration.models.SettingSelector; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +/** + * Sample demonstrates how to add, get, list, and delete a feature flag configuration setting. + */ +public class FeatureFlagConfigurationSettingSample { + /** + * Runs the sample algorithm and demonstrates how to add, get, list, and delete a feature flag configuration + * setting. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + final ConfigurationClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + + // Name of the key to add to the configuration service. + final String key = "hello"; + + System.out.println("Beginning of synchronous sample..."); + + FeatureFlagFilter percentageFilter = new FeatureFlagFilter("Microsoft.Percentage") + .addParameter("Value", 30); + FeatureFlagConfigurationSetting featureFlagConfigurationSetting = + new FeatureFlagConfigurationSetting(key, true) + .setClientFilters(Arrays.asList(percentageFilter)); + + // setConfigurationSetting adds or updates a setting to Azure App Configuration store. Alternatively, you can + // call addConfigurationSetting which only succeeds if the setting does not exist in the store. Or, + // you can call setConfigurationSetting to update a setting that is already present in the store. + System.out.println("[Set-FeatureFlagConfigurationSetting]"); + FeatureFlagConfigurationSetting setting = + (FeatureFlagConfigurationSetting) client.setConfigurationSetting(featureFlagConfigurationSetting); + printFeatureFlagSetting(setting); + + System.out.println("[Get-FeatureFlagConfigurationSetting]"); + setting = (FeatureFlagConfigurationSetting) client.getConfigurationSetting(setting); + printFeatureFlagSetting(setting); + + System.out.println("[List-FeatureFlagConfigurationSetting]"); + PagedIterable configurationSettings = + client.listConfigurationSettings(new SettingSelector()); + for (ConfigurationSetting configurationSetting : configurationSettings) { + if (configurationSetting instanceof FeatureFlagConfigurationSetting) { + System.out.println("-Listing-FeatureFlagConfigurationSetting"); + printFeatureFlagSetting((FeatureFlagConfigurationSetting) configurationSetting); + } else { + System.out.println("-Listing-non-FeatureFlagConfigurationSetting"); + System.out.printf("Key: %s, Value: %s%n", configurationSetting.getKey(), + configurationSetting.getValue()); + } + } + + System.out.println("[Delete-FeatureFlagConfigurationSetting"); + setting = (FeatureFlagConfigurationSetting) client.deleteConfigurationSetting(setting); + printFeatureFlagSetting(setting); + + System.out.println("End of synchronous sample."); + } + + private static void printFeatureFlagSetting(FeatureFlagConfigurationSetting setting) { + System.out.printf("Key: %s, Value: %s%n", setting.getKey(), setting.getValue()); + System.out.printf("\tFeature ID: %s, Content Type: %s%n", setting.getFeatureId(), setting.getContentType()); + final List clientFilters = setting.getClientFilters(); + for (FeatureFlagFilter filter : clientFilters) { + System.out.printf("\t\tFilter name: %s%n", filter.getName()); + final Map parameters = filter.getParameters(); + System.out.println("\t\t\tParameters:"); + parameters.forEach((k, v) -> System.out.printf("\t\t\t\tKey: %s, Value:%s%n", k, v)); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample13/v2/FeatureFlagConfigurationSettingSample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample13/v2/FeatureFlagConfigurationSettingSample.java new file mode 100644 index 000000000000..0e2805e9a75f --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample13/v2/FeatureFlagConfigurationSettingSample.java @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.FeatureFlagConfigurationSetting; +import com.azure.data.appconfiguration.models.FeatureFlagFilter; +import com.azure.data.appconfiguration.models.SettingSelector; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +/** + * Sample demonstrates how to add, get, list, and delete a feature flag configuration setting. + */ +public class FeatureFlagConfigurationSettingSample { + /** + * Runs the sample algorithm and demonstrates how to add, get, list, and delete a feature flag configuration + * setting. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + final ConfigurationClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + + // Name of the key to add to the configuration service. + final String key = "hello"; + + System.out.println("Beginning of synchronous sample..."); + + FeatureFlagFilter percentageFilter = new FeatureFlagFilter("Microsoft.Percentage") + .addParameter("Value", 30); + FeatureFlagConfigurationSetting featureFlagConfigurationSetting = + new FeatureFlagConfigurationSetting(key, true) + .setClientFilters(Arrays.asList(percentageFilter)); + + // setConfigurationSetting adds or updates a setting to Azure App Configuration store. Alternatively, you can + // call addConfigurationSetting which only succeeds if the setting does not exist in the store. Or, + // you can call setConfigurationSetting to update a setting that is already present in the store. + System.out.println("[Set-FeatureFlagConfigurationSetting]"); + FeatureFlagConfigurationSetting setting = + (FeatureFlagConfigurationSetting) client.setConfigurationSetting(featureFlagConfigurationSetting); + printFeatureFlagSetting(setting); + + System.out.println("[Get-FeatureFlagConfigurationSetting]"); + setting = (FeatureFlagConfigurationSetting) client.getConfigurationSetting(setting); + printFeatureFlagSetting(setting); + + System.out.println("[List-FeatureFlagConfigurationSetting]"); + PagedIterable configurationSettings = + client.listConfigurationSettings(new SettingSelector()); + for (ConfigurationSetting configurationSetting : configurationSettings) { + if (configurationSetting instanceof FeatureFlagConfigurationSetting) { + System.out.println("-Listing-FeatureFlagConfigurationSetting"); + printFeatureFlagSetting((FeatureFlagConfigurationSetting) configurationSetting); + } else { + System.out.println("-Listing-non-FeatureFlagConfigurationSetting"); + System.out.printf("Key: %s, Value: %s%n", configurationSetting.getKey(), + configurationSetting.getValue()); + } + } + + System.out.println("[Delete-FeatureFlagConfigurationSetting"); + setting = (FeatureFlagConfigurationSetting) client.deleteConfigurationSetting(setting); + printFeatureFlagSetting(setting); + + System.out.println("End of synchronous sample."); + } + + private static void printFeatureFlagSetting(FeatureFlagConfigurationSetting setting) { + System.out.printf("Key: %s, Value: %s%n", setting.getKey(), setting.getValue()); + System.out.printf("\tFeature ID: %s, Content Type: %s%n", setting.getFeatureId(), setting.getContentType()); + final List clientFilters = setting.getClientFilters(); + for (FeatureFlagFilter filter : clientFilters) { + System.out.printf("\t\tFilter name: %s%n", filter.getName()); + final Map parameters = filter.getParameters(); + System.out.println("\t\t\tParameters:"); + parameters.forEach((k, v) -> System.out.printf("\t\t\t\tKey: %s, Value:%s%n", k, v)); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample14/v1/FeatureFlagConfigurationSettingSampleAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample14/v1/FeatureFlagConfigurationSettingSampleAsync.java new file mode 100644 index 000000000000..bd6e8578ebf6 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample14/v1/FeatureFlagConfigurationSettingSampleAsync.java @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.FeatureFlagConfigurationSetting; +import com.azure.data.appconfiguration.models.FeatureFlagFilter; +import com.azure.data.appconfiguration.models.SettingSelector; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +/** + * Sample demonstrates how to add, get, list, and delete a feature flag configuration setting asynchronous. + */ +public class FeatureFlagConfigurationSettingSampleAsync { + /** + * Runs the sample algorithm and demonstrates how to add, get, list, and delete a feature flag configuration + * setting asynchronous. + * + * @param args Unused. Arguments to the program. + * @throws InterruptedException when a thread is waiting, sleeping, or otherwise occupied, + * and the thread is interrupted, either before or during the activity. + */ + public static void main(String[] args) throws InterruptedException { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Asynchronous sample + // Instantiate a client that will be used to call the service. + final ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + + // Name of the key to add to the configuration service. + final String key = "hello"; + + System.out.println("Beginning of asynchronous sample..."); + + FeatureFlagFilter percentageFilter = new FeatureFlagFilter("Microsoft.Percentage") + .addParameter("Value", 30); + FeatureFlagConfigurationSetting featureFlagConfigurationSetting = + new FeatureFlagConfigurationSetting(key, true) + .setClientFilters(Arrays.asList(percentageFilter)); + + // setConfigurationSetting adds or updates a setting to Azure App Configuration store. Alternatively, you can + // call addConfigurationSetting which only succeeds if the setting does not exist in the store. Or, + // you can call setConfigurationSetting to update a setting that is already present in the store. + + // We subscribe and wait for the service call to complete then print out the contents of our newly added setting. + // If an error occurs, we print out that error. + System.out.println("[Set-SecretReferenceConfigurationSetting]"); + client.setConfigurationSetting(featureFlagConfigurationSetting).subscribe( + result -> printFeatureFlagSetting((FeatureFlagConfigurationSetting) result), + error -> System.err.println("There was an error adding the setting: " + error), + () -> System.out.println("Set setting finished")); + TimeUnit.MILLISECONDS.sleep(1000); + + System.out.println("[Get-FeatureFlagConfigurationSetting]"); + client.getConfigurationSetting(featureFlagConfigurationSetting).subscribe( + result -> printFeatureFlagSetting((FeatureFlagConfigurationSetting) result), + error -> System.err.println("There was an error getting the setting: " + error), + () -> System.out.println("Get setting finished")); + TimeUnit.MILLISECONDS.sleep(1000); + + System.out.println("[List-FeatureFlagConfigurationSetting]"); + client.listConfigurationSettings(new SettingSelector()).subscribe( + result -> { + if (result instanceof FeatureFlagConfigurationSetting) { + System.out.println("-Listing-FeatureFlagConfigurationSetting"); + printFeatureFlagSetting((FeatureFlagConfigurationSetting) result); + } else { + System.out.println("-Listing-non-FeatureFlagConfigurationSetting"); + System.out.printf("Key: %s, Value: %s%n", result.getKey(), result.getValue()); + } + }, + error -> System.err.println("There was an error adding the setting: " + error), + () -> System.out.println("List settings finished")); + TimeUnit.MILLISECONDS.sleep(1000); + + System.out.println("[Delete-FeatureFlagConfigurationSetting"); + client.getConfigurationSetting(featureFlagConfigurationSetting).subscribe( + result -> printFeatureFlagSetting((FeatureFlagConfigurationSetting) result), + error -> System.err.println("There was an error getting the setting: " + error), + () -> System.out.println("Delete setting finished")); + TimeUnit.MILLISECONDS.sleep(1000); + + System.out.println("End of asynchronous sample."); + } + + private static void printFeatureFlagSetting(FeatureFlagConfigurationSetting setting) { + System.out.printf("Key: %s, Value: %s%n", setting.getKey(), setting.getValue()); + System.out.printf("\tFeature ID: %s, Content Type: %s%n", setting.getFeatureId(), setting.getContentType()); + final List clientFilters = setting.getClientFilters(); + for (FeatureFlagFilter filter : clientFilters) { + System.out.printf("\t\tFilter name: %s%n", filter.getName()); + final Map parameters = filter.getParameters(); + System.out.println("\t\t\tParameters:"); + parameters.forEach((k, v) -> System.out.printf("\t\t\t\tKey: %s, Value:%s%n", k, v)); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample14/v2/FeatureFlagConfigurationSettingSampleAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample14/v2/FeatureFlagConfigurationSettingSampleAsync.java new file mode 100644 index 000000000000..bd6e8578ebf6 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample14/v2/FeatureFlagConfigurationSettingSampleAsync.java @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.FeatureFlagConfigurationSetting; +import com.azure.data.appconfiguration.models.FeatureFlagFilter; +import com.azure.data.appconfiguration.models.SettingSelector; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +/** + * Sample demonstrates how to add, get, list, and delete a feature flag configuration setting asynchronous. + */ +public class FeatureFlagConfigurationSettingSampleAsync { + /** + * Runs the sample algorithm and demonstrates how to add, get, list, and delete a feature flag configuration + * setting asynchronous. + * + * @param args Unused. Arguments to the program. + * @throws InterruptedException when a thread is waiting, sleeping, or otherwise occupied, + * and the thread is interrupted, either before or during the activity. + */ + public static void main(String[] args) throws InterruptedException { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Asynchronous sample + // Instantiate a client that will be used to call the service. + final ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + + // Name of the key to add to the configuration service. + final String key = "hello"; + + System.out.println("Beginning of asynchronous sample..."); + + FeatureFlagFilter percentageFilter = new FeatureFlagFilter("Microsoft.Percentage") + .addParameter("Value", 30); + FeatureFlagConfigurationSetting featureFlagConfigurationSetting = + new FeatureFlagConfigurationSetting(key, true) + .setClientFilters(Arrays.asList(percentageFilter)); + + // setConfigurationSetting adds or updates a setting to Azure App Configuration store. Alternatively, you can + // call addConfigurationSetting which only succeeds if the setting does not exist in the store. Or, + // you can call setConfigurationSetting to update a setting that is already present in the store. + + // We subscribe and wait for the service call to complete then print out the contents of our newly added setting. + // If an error occurs, we print out that error. + System.out.println("[Set-SecretReferenceConfigurationSetting]"); + client.setConfigurationSetting(featureFlagConfigurationSetting).subscribe( + result -> printFeatureFlagSetting((FeatureFlagConfigurationSetting) result), + error -> System.err.println("There was an error adding the setting: " + error), + () -> System.out.println("Set setting finished")); + TimeUnit.MILLISECONDS.sleep(1000); + + System.out.println("[Get-FeatureFlagConfigurationSetting]"); + client.getConfigurationSetting(featureFlagConfigurationSetting).subscribe( + result -> printFeatureFlagSetting((FeatureFlagConfigurationSetting) result), + error -> System.err.println("There was an error getting the setting: " + error), + () -> System.out.println("Get setting finished")); + TimeUnit.MILLISECONDS.sleep(1000); + + System.out.println("[List-FeatureFlagConfigurationSetting]"); + client.listConfigurationSettings(new SettingSelector()).subscribe( + result -> { + if (result instanceof FeatureFlagConfigurationSetting) { + System.out.println("-Listing-FeatureFlagConfigurationSetting"); + printFeatureFlagSetting((FeatureFlagConfigurationSetting) result); + } else { + System.out.println("-Listing-non-FeatureFlagConfigurationSetting"); + System.out.printf("Key: %s, Value: %s%n", result.getKey(), result.getValue()); + } + }, + error -> System.err.println("There was an error adding the setting: " + error), + () -> System.out.println("List settings finished")); + TimeUnit.MILLISECONDS.sleep(1000); + + System.out.println("[Delete-FeatureFlagConfigurationSetting"); + client.getConfigurationSetting(featureFlagConfigurationSetting).subscribe( + result -> printFeatureFlagSetting((FeatureFlagConfigurationSetting) result), + error -> System.err.println("There was an error getting the setting: " + error), + () -> System.out.println("Delete setting finished")); + TimeUnit.MILLISECONDS.sleep(1000); + + System.out.println("End of asynchronous sample."); + } + + private static void printFeatureFlagSetting(FeatureFlagConfigurationSetting setting) { + System.out.printf("Key: %s, Value: %s%n", setting.getKey(), setting.getValue()); + System.out.printf("\tFeature ID: %s, Content Type: %s%n", setting.getFeatureId(), setting.getContentType()); + final List clientFilters = setting.getClientFilters(); + for (FeatureFlagFilter filter : clientFilters) { + System.out.printf("\t\tFilter name: %s%n", filter.getName()); + final Map parameters = filter.getParameters(); + System.out.println("\t\t\tParameters:"); + parameters.forEach((k, v) -> System.out.printf("\t\t\t\tKey: %s, Value:%s%n", k, v)); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample15/v1/HelloWorld.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample15/v1/HelloWorld.java new file mode 100644 index 000000000000..536fcae286a0 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample15/v1/HelloWorld.java @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.ConfigurationSetting; + +/** + * Sample demonstrates how to add, get, and delete a configuration setting. + */ +public class HelloWorld { + /** + * Runs the sample algorithm and demonstrates how to add, get, and delete a configuration setting. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + final ConfigurationClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + + // Name of the key to add to the configuration service. + final String key = "hello"; + final String value = "world"; + + System.out.println("Beginning of synchronous sample..."); + + ConfigurationSetting setting = client.setConfigurationSetting(key, null, value); + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + + setting = client.getConfigurationSetting(key, null, null); + System.out.printf("[GetConfigurationSetting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + + setting = client.deleteConfigurationSetting(key, null); + System.out.printf("[DeleteConfigurationSetting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + + System.out.println("End of synchronous sample."); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample15/v2/HelloWorld.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample15/v2/HelloWorld.java new file mode 100644 index 000000000000..536fcae286a0 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample15/v2/HelloWorld.java @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.ConfigurationSetting; + +/** + * Sample demonstrates how to add, get, and delete a configuration setting. + */ +public class HelloWorld { + /** + * Runs the sample algorithm and demonstrates how to add, get, and delete a configuration setting. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + final ConfigurationClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + + // Name of the key to add to the configuration service. + final String key = "hello"; + final String value = "world"; + + System.out.println("Beginning of synchronous sample..."); + + ConfigurationSetting setting = client.setConfigurationSetting(key, null, value); + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + + setting = client.getConfigurationSetting(key, null, null); + System.out.printf("[GetConfigurationSetting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + + setting = client.deleteConfigurationSetting(key, null); + System.out.printf("[DeleteConfigurationSetting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + + System.out.println("End of synchronous sample."); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample16/v1/HelloWorldAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample16/v1/HelloWorldAsync.java new file mode 100644 index 000000000000..21f7783e6f05 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample16/v1/HelloWorldAsync.java @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.ConfigurationSetting; + +import java.util.concurrent.TimeUnit; + +/** + * Sample demonstrates how to add, get, and delete a configuration setting asynchronous. + */ +public class HelloWorldAsync { + /** + * Runs the sample algorithm and demonstrates how to add, get, and delete a configuration setting asynchronous. + * + * @param args Unused. Arguments to the program. + * @throws InterruptedException when a thread is waiting, sleeping, or otherwise occupied, + * and the thread is interrupted, either before or during the activity. + */ + public static void main(String[] args) throws InterruptedException { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Asynchronous sample + // Instantiate a client that will be used to call the service. + final ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + + // Name of the key to add to the configuration service. + final String key = "hello"; + final String value = "world"; + + // setConfigurationSetting adds or updates a setting to Azure App Configuration store. Alternatively, you can call + // addConfigurationSetting which only succeeds if the setting does not exist in the store. Or, you can call setConfigurationSetting to + // update a setting that is already present in the store. + // We subscribe and wait for the service call to complete then print out the contents of our newly added setting. + // If an error occurs, we print out that error. + client.setConfigurationSetting(key, null, value).subscribe( + result -> { + final ConfigurationSetting setting = result; + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + }, + error -> System.err.println("There was an error adding the setting: " + error), + () -> System.out.printf("Set setting with key=%s and value=%s added or updated.", key, value)); + + TimeUnit.MILLISECONDS.sleep(1000); + + client.getConfigurationSetting(key, null, null).subscribe( + result -> { + final ConfigurationSetting setting = result; + System.out.printf("[GetConfigurationSetting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + }, + error -> System.err.println("There was an error getting the setting: " + error), + () -> { + // On completion of the subscription, we delete the setting. + // .block() exists there so the program does not end before the deletion has completed. + System.out.println("Completed. Deleting setting..."); + client.deleteConfigurationSetting(key, null).block(); + }); + + TimeUnit.MILLISECONDS.sleep(1000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample16/v2/HelloWorldAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample16/v2/HelloWorldAsync.java new file mode 100644 index 000000000000..21f7783e6f05 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample16/v2/HelloWorldAsync.java @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.ConfigurationSetting; + +import java.util.concurrent.TimeUnit; + +/** + * Sample demonstrates how to add, get, and delete a configuration setting asynchronous. + */ +public class HelloWorldAsync { + /** + * Runs the sample algorithm and demonstrates how to add, get, and delete a configuration setting asynchronous. + * + * @param args Unused. Arguments to the program. + * @throws InterruptedException when a thread is waiting, sleeping, or otherwise occupied, + * and the thread is interrupted, either before or during the activity. + */ + public static void main(String[] args) throws InterruptedException { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Asynchronous sample + // Instantiate a client that will be used to call the service. + final ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + + // Name of the key to add to the configuration service. + final String key = "hello"; + final String value = "world"; + + // setConfigurationSetting adds or updates a setting to Azure App Configuration store. Alternatively, you can call + // addConfigurationSetting which only succeeds if the setting does not exist in the store. Or, you can call setConfigurationSetting to + // update a setting that is already present in the store. + // We subscribe and wait for the service call to complete then print out the contents of our newly added setting. + // If an error occurs, we print out that error. + client.setConfigurationSetting(key, null, value).subscribe( + result -> { + final ConfigurationSetting setting = result; + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + }, + error -> System.err.println("There was an error adding the setting: " + error), + () -> System.out.printf("Set setting with key=%s and value=%s added or updated.", key, value)); + + TimeUnit.MILLISECONDS.sleep(1000); + + client.getConfigurationSetting(key, null, null).subscribe( + result -> { + final ConfigurationSetting setting = result; + System.out.printf("[GetConfigurationSetting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + }, + error -> System.err.println("There was an error getting the setting: " + error), + () -> { + // On completion of the subscription, we delete the setting. + // .block() exists there so the program does not end before the deletion has completed. + System.out.println("Completed. Deleting setting..."); + client.deleteConfigurationSetting(key, null).block(); + }); + + TimeUnit.MILLISECONDS.sleep(1000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample17/v1/ListLabels.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample17/v1/ListLabels.java new file mode 100644 index 000000000000..23dd670f19d6 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample17/v1/ListLabels.java @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.util.Configuration; +import com.azure.core.util.Context; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingLabelSelector; + +/** + * A sample demonstrate how to list labels. + */ +public class ListLabels { + /** + * Runs the sample algorithm and demonstrates how to list labels. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = Configuration.getGlobalConfiguration().get("AZURE_APPCONFIG_CONNECTION_STRING"); + + final ConfigurationClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + + // Prepare three settings with different labels, prod1, prod2, prod3 + ConfigurationSetting setting = client.setConfigurationSetting("prod:prod1", "prod1", "prod1"); + System.out.printf("Key: %s, Label: %s, Value: %s%n", setting.getKey(), setting.getLabel(), setting.getValue()); + ConfigurationSetting setting1 = client.setConfigurationSetting("prod:prod2", "prod2", "prod2"); + System.out.printf("Key: %s, Label: %s, Value: %s%n", setting1.getKey(), setting1.getLabel(), setting1.getValue()); + ConfigurationSetting setting2 = client.setConfigurationSetting("prod:prod3", "prod3", "prod3"); + System.out.printf("Key: %s, Label: %s, Value: %s%n", setting2.getKey(), setting2.getLabel(), setting2.getValue()); + + // If you want to list all labels in the sources, simply pass selector=null in the request; + // If you want to list labels by exact match, use the exact label name as the filter. + // If you want to list all labels by wildcard, pass wildcard where AppConfig supports, such as "prod*", + System.out.println("List all labels:"); + client.listLabels(null, Context.NONE) + .forEach(label -> System.out.println("\tLabel name = " + label.getName())); + + System.out.println("List label by exact match:"); + client.listLabels(new SettingLabelSelector().setNameFilter("prod2"), Context.NONE) + .forEach(label -> System.out.println("\tLabel name = " + label.getName())); + + System.out.println("List labels by wildcard:"); + client.listLabels(new SettingLabelSelector().setNameFilter("prod*"), Context.NONE) + .forEach(label -> System.out.println("\tLabel name = " + label.getName())); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample17/v2/ListLabels.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample17/v2/ListLabels.java new file mode 100644 index 000000000000..23dd670f19d6 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample17/v2/ListLabels.java @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.util.Configuration; +import com.azure.core.util.Context; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingLabelSelector; + +/** + * A sample demonstrate how to list labels. + */ +public class ListLabels { + /** + * Runs the sample algorithm and demonstrates how to list labels. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = Configuration.getGlobalConfiguration().get("AZURE_APPCONFIG_CONNECTION_STRING"); + + final ConfigurationClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + + // Prepare three settings with different labels, prod1, prod2, prod3 + ConfigurationSetting setting = client.setConfigurationSetting("prod:prod1", "prod1", "prod1"); + System.out.printf("Key: %s, Label: %s, Value: %s%n", setting.getKey(), setting.getLabel(), setting.getValue()); + ConfigurationSetting setting1 = client.setConfigurationSetting("prod:prod2", "prod2", "prod2"); + System.out.printf("Key: %s, Label: %s, Value: %s%n", setting1.getKey(), setting1.getLabel(), setting1.getValue()); + ConfigurationSetting setting2 = client.setConfigurationSetting("prod:prod3", "prod3", "prod3"); + System.out.printf("Key: %s, Label: %s, Value: %s%n", setting2.getKey(), setting2.getLabel(), setting2.getValue()); + + // If you want to list all labels in the sources, simply pass selector=null in the request; + // If you want to list labels by exact match, use the exact label name as the filter. + // If you want to list all labels by wildcard, pass wildcard where AppConfig supports, such as "prod*", + System.out.println("List all labels:"); + client.listLabels(null, Context.NONE) + .forEach(label -> System.out.println("\tLabel name = " + label.getName())); + + System.out.println("List label by exact match:"); + client.listLabels(new SettingLabelSelector().setNameFilter("prod2"), Context.NONE) + .forEach(label -> System.out.println("\tLabel name = " + label.getName())); + + System.out.println("List labels by wildcard:"); + client.listLabels(new SettingLabelSelector().setNameFilter("prod*"), Context.NONE) + .forEach(label -> System.out.println("\tLabel name = " + label.getName())); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample18/v1/ListLabelsAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample18/v1/ListLabelsAsync.java new file mode 100644 index 000000000000..b1b06bf828ad --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample18/v1/ListLabelsAsync.java @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.util.Configuration; +import com.azure.data.appconfiguration.models.SettingLabelSelector; + +import java.util.concurrent.TimeUnit; + +/** + * A sample demonstrate how to list labels asynchronously. + */ +public class ListLabelsAsync { + /** + * Runs the sample algorithm and demonstrates how to list labels asynchronously. + * + * @param args Unused. Arguments to the program. + * @throws InterruptedException when a thread is waiting, sleeping, or otherwise occupied, + * and the thread is interrupted, either before or during the activity. + */ + public static void main(String[] args) throws InterruptedException { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = Configuration.getGlobalConfiguration().get("AZURE_APPCONFIG_CONNECTION_STRING"); + + // Asynchronous sample + // Instantiate a client that will be used to call the service. + final ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + // Prepare three settings with different labels, prod1, prod2, prod3 + client.setConfigurationSetting("prod:prod1", "prod1", "prod1").subscribe( + setting -> System.out.printf("Key: %s, Label: %s, Value: %s%n", setting.getKey(), setting.getLabel(), setting.getValue())); + TimeUnit.MILLISECONDS.sleep(1000); + + client.setConfigurationSetting("prod:prod2", "prod2", "prod2").subscribe( + setting -> System.out.printf("Key: %s, Label: %s, Value: %s%n", setting.getKey(), setting.getLabel(), setting.getValue())); + TimeUnit.MILLISECONDS.sleep(1000); + + client.setConfigurationSetting("prod:prod3", "prod3", "prod3").subscribe( + setting -> System.out.printf("Key: %s, Label: %s, Value: %s%n", setting.getKey(), setting.getLabel(), setting.getValue())); + TimeUnit.MILLISECONDS.sleep(1000); + + // If you want to list all labels in the sources, simply pass selector=null in the request; + // If you want to list labels by exact match, use the exact label name as the filter. + // If you want to list all labels by wildcard, pass wildcard where AppConfig supports, such as "prod*", + System.out.println("List all labels:"); + client.listLabels(null).subscribe(label -> System.out.println("\tLabel name = " + label.getName())); + TimeUnit.MILLISECONDS.sleep(1000); + + System.out.println("List label by exact match:"); + client.listLabels(new SettingLabelSelector().setNameFilter("prod2")).subscribe( + label -> System.out.println("\tLabel name = " + label.getName())); + TimeUnit.MILLISECONDS.sleep(1000); + + System.out.println("List labels by wildcard:"); + client.listLabels(new SettingLabelSelector().setNameFilter("prod*")).subscribe( + label -> System.out.println("\tLabel name = " + label.getName())); + TimeUnit.MILLISECONDS.sleep(1000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample18/v2/ListLabelsAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample18/v2/ListLabelsAsync.java new file mode 100644 index 000000000000..b1b06bf828ad --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample18/v2/ListLabelsAsync.java @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.util.Configuration; +import com.azure.data.appconfiguration.models.SettingLabelSelector; + +import java.util.concurrent.TimeUnit; + +/** + * A sample demonstrate how to list labels asynchronously. + */ +public class ListLabelsAsync { + /** + * Runs the sample algorithm and demonstrates how to list labels asynchronously. + * + * @param args Unused. Arguments to the program. + * @throws InterruptedException when a thread is waiting, sleeping, or otherwise occupied, + * and the thread is interrupted, either before or during the activity. + */ + public static void main(String[] args) throws InterruptedException { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = Configuration.getGlobalConfiguration().get("AZURE_APPCONFIG_CONNECTION_STRING"); + + // Asynchronous sample + // Instantiate a client that will be used to call the service. + final ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + // Prepare three settings with different labels, prod1, prod2, prod3 + client.setConfigurationSetting("prod:prod1", "prod1", "prod1").subscribe( + setting -> System.out.printf("Key: %s, Label: %s, Value: %s%n", setting.getKey(), setting.getLabel(), setting.getValue())); + TimeUnit.MILLISECONDS.sleep(1000); + + client.setConfigurationSetting("prod:prod2", "prod2", "prod2").subscribe( + setting -> System.out.printf("Key: %s, Label: %s, Value: %s%n", setting.getKey(), setting.getLabel(), setting.getValue())); + TimeUnit.MILLISECONDS.sleep(1000); + + client.setConfigurationSetting("prod:prod3", "prod3", "prod3").subscribe( + setting -> System.out.printf("Key: %s, Label: %s, Value: %s%n", setting.getKey(), setting.getLabel(), setting.getValue())); + TimeUnit.MILLISECONDS.sleep(1000); + + // If you want to list all labels in the sources, simply pass selector=null in the request; + // If you want to list labels by exact match, use the exact label name as the filter. + // If you want to list all labels by wildcard, pass wildcard where AppConfig supports, such as "prod*", + System.out.println("List all labels:"); + client.listLabels(null).subscribe(label -> System.out.println("\tLabel name = " + label.getName())); + TimeUnit.MILLISECONDS.sleep(1000); + + System.out.println("List label by exact match:"); + client.listLabels(new SettingLabelSelector().setNameFilter("prod2")).subscribe( + label -> System.out.println("\tLabel name = " + label.getName())); + TimeUnit.MILLISECONDS.sleep(1000); + + System.out.println("List labels by wildcard:"); + client.listLabels(new SettingLabelSelector().setNameFilter("prod*")).subscribe( + label -> System.out.println("\tLabel name = " + label.getName())); + TimeUnit.MILLISECONDS.sleep(1000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample19/v1/ListSettingsWithTagsFilter.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample19/v1/ListSettingsWithTagsFilter.java new file mode 100644 index 000000000000..c7754a0376a1 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample19/v1/ListSettingsWithTagsFilter.java @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.Configuration; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; + +import javax.net.ssl.SSLException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static com.azure.data.appconfiguration.implementation.Utility.getTagsFilterInString; + +/** + * Sample demonstrates how to list settings with tags filter. + */ +public class ListSettingsWithTagsFilter { + /** + * Runs the sample algorithm and demonstrates how to list settings with tags filter. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) throws SSLException { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to the "Access Keys" page under the "Settings" section. + String connectionString = Configuration.getGlobalConfiguration().get("AZURE_APPCONFIG_CONNECTION_STRING"); + + // Instantiate a client that will be used to call the service. + ConfigurationClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + + Map tags = new HashMap<>(); + tags.put("release", "first"); + Map tags2 = new HashMap<>(); + tags2.put("release", "first"); + tags2.put("release2", "second"); + ConfigurationSetting setting1 = client.setConfigurationSetting(new ConfigurationSetting().setKey("keyForTag1").setValue("value1").setTags(tags)); + System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting1.getKey(), setting1.getValue(), setting1.getTags()); + ConfigurationSetting setting2 = client.setConfigurationSetting(new ConfigurationSetting().setKey("keyForTag2").setValue("value2").setTags(tags2)); + System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting2.getKey(), setting2.getValue(), setting2.getTags()); + ConfigurationSetting setting3 = client.setConfigurationSetting(new ConfigurationSetting().setKey("key3WithoutTag").setValue("value3")); + System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting3.getKey(), setting3.getValue(), setting3.getTags()); + + List tagsFilterInString = getTagsFilterInString(tags2); + System.out.println("List settings with tags filter = " + tagsFilterInString); + PagedIterable configurationSettings = client.listConfigurationSettings(new SettingSelector().setKeyFilter("key*") + .setTagsFilter(tagsFilterInString)); + configurationSettings.forEach(setting -> System.out.printf( + "\tKey: %s, Value: %s, Tags: %s%n", setting.getKey(), setting.getValue(), setting.getTags())); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample19/v2/ListSettingsWithTagsFilter.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample19/v2/ListSettingsWithTagsFilter.java new file mode 100644 index 000000000000..c7754a0376a1 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample19/v2/ListSettingsWithTagsFilter.java @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.Configuration; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; + +import javax.net.ssl.SSLException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static com.azure.data.appconfiguration.implementation.Utility.getTagsFilterInString; + +/** + * Sample demonstrates how to list settings with tags filter. + */ +public class ListSettingsWithTagsFilter { + /** + * Runs the sample algorithm and demonstrates how to list settings with tags filter. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) throws SSLException { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to the "Access Keys" page under the "Settings" section. + String connectionString = Configuration.getGlobalConfiguration().get("AZURE_APPCONFIG_CONNECTION_STRING"); + + // Instantiate a client that will be used to call the service. + ConfigurationClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + + Map tags = new HashMap<>(); + tags.put("release", "first"); + Map tags2 = new HashMap<>(); + tags2.put("release", "first"); + tags2.put("release2", "second"); + ConfigurationSetting setting1 = client.setConfigurationSetting(new ConfigurationSetting().setKey("keyForTag1").setValue("value1").setTags(tags)); + System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting1.getKey(), setting1.getValue(), setting1.getTags()); + ConfigurationSetting setting2 = client.setConfigurationSetting(new ConfigurationSetting().setKey("keyForTag2").setValue("value2").setTags(tags2)); + System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting2.getKey(), setting2.getValue(), setting2.getTags()); + ConfigurationSetting setting3 = client.setConfigurationSetting(new ConfigurationSetting().setKey("key3WithoutTag").setValue("value3")); + System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting3.getKey(), setting3.getValue(), setting3.getTags()); + + List tagsFilterInString = getTagsFilterInString(tags2); + System.out.println("List settings with tags filter = " + tagsFilterInString); + PagedIterable configurationSettings = client.listConfigurationSettings(new SettingSelector().setKeyFilter("key*") + .setTagsFilter(tagsFilterInString)); + configurationSettings.forEach(setting -> System.out.printf( + "\tKey: %s, Value: %s, Tags: %s%n", setting.getKey(), setting.getValue(), setting.getTags())); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample2/v1/ConditionalRequest.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample2/v1/ConditionalRequest.java new file mode 100644 index 000000000000..b6aafadcc407 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample2/v1/ConditionalRequest.java @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.data.appconfiguration.models.ConfigurationSetting; + +/** + * Sample demonstrates how to add, get, and delete a configuration setting by conditional request. + */ +public class ConditionalRequest { + /** + * Runs the sample program and demonstrates how to add, get, and delete a configuration setting by conditional request. + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Instantiate a client that will be used to call the service. + final ConfigurationClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + + ConfigurationSetting setting = new ConfigurationSetting().setKey("key").setLabel("label").setValue("value"); + + // If you want to conditionally update the setting, set `ifUnchanged` to true. If the ETag of the + // given setting matches the one in the service, then the setting is updated. Otherwise, it is + // not updated. + // If the given setting is not exist in the service, the setting will be added to the service. + Response settingResponse = client.setConfigurationSettingWithResponse(setting, true, Context.NONE); + System.out.printf("Status code: %s, Key: %s, Value: %s", settingResponse.getStatusCode(), + settingResponse.getValue().getKey(), settingResponse.getValue().getValue()); + + // If you want to conditionally retrieve the setting, set `ifChanged` to true. If the ETag of the + // given setting matches the one in the service, then 304 status code with null value returned in the response. + // Otherwise, a setting with new ETag returned, which is the latest setting retrieved from the service. + settingResponse = client.getConfigurationSettingWithResponse(setting, null, true, Context.NONE); + System.out.printf("Status code: %s, Key: %s, Value: %s", settingResponse.getStatusCode(), + settingResponse.getValue().getKey(), settingResponse.getValue().getValue()); + + // If you want to conditionally delete the setting, set `ifUnchanged` to true. If the ETag of the + // given setting matches the one in the service, then the setting is deleted. Otherwise, it is + // not deleted. + client.deleteConfigurationSettingWithResponse(settingResponse.getValue(), true, Context.NONE); + System.out.printf("Status code: %s, Key: %s, Value: %s", settingResponse.getStatusCode(), + settingResponse.getValue().getKey(), settingResponse.getValue().getValue()); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample2/v2/ConditionalRequest.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample2/v2/ConditionalRequest.java new file mode 100644 index 000000000000..b6aafadcc407 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample2/v2/ConditionalRequest.java @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.data.appconfiguration.models.ConfigurationSetting; + +/** + * Sample demonstrates how to add, get, and delete a configuration setting by conditional request. + */ +public class ConditionalRequest { + /** + * Runs the sample program and demonstrates how to add, get, and delete a configuration setting by conditional request. + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Instantiate a client that will be used to call the service. + final ConfigurationClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + + ConfigurationSetting setting = new ConfigurationSetting().setKey("key").setLabel("label").setValue("value"); + + // If you want to conditionally update the setting, set `ifUnchanged` to true. If the ETag of the + // given setting matches the one in the service, then the setting is updated. Otherwise, it is + // not updated. + // If the given setting is not exist in the service, the setting will be added to the service. + Response settingResponse = client.setConfigurationSettingWithResponse(setting, true, Context.NONE); + System.out.printf("Status code: %s, Key: %s, Value: %s", settingResponse.getStatusCode(), + settingResponse.getValue().getKey(), settingResponse.getValue().getValue()); + + // If you want to conditionally retrieve the setting, set `ifChanged` to true. If the ETag of the + // given setting matches the one in the service, then 304 status code with null value returned in the response. + // Otherwise, a setting with new ETag returned, which is the latest setting retrieved from the service. + settingResponse = client.getConfigurationSettingWithResponse(setting, null, true, Context.NONE); + System.out.printf("Status code: %s, Key: %s, Value: %s", settingResponse.getStatusCode(), + settingResponse.getValue().getKey(), settingResponse.getValue().getValue()); + + // If you want to conditionally delete the setting, set `ifUnchanged` to true. If the ETag of the + // given setting matches the one in the service, then the setting is deleted. Otherwise, it is + // not deleted. + client.deleteConfigurationSettingWithResponse(settingResponse.getValue(), true, Context.NONE); + System.out.printf("Status code: %s, Key: %s, Value: %s", settingResponse.getStatusCode(), + settingResponse.getValue().getKey(), settingResponse.getValue().getValue()); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample20/v1/ListSettingsWithTagsFilterAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample20/v1/ListSettingsWithTagsFilterAsync.java new file mode 100644 index 000000000000..c97012e8d01b --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample20/v1/ListSettingsWithTagsFilterAsync.java @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.util.Configuration; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import static com.azure.data.appconfiguration.implementation.Utility.getTagsFilterInString; + +/** + * how to list settings with tags filter. + */ +public class ListSettingsWithTagsFilterAsync { + /** + * Runs the sample algorithm and demonstrates how to list settings with tags filter. + * + * @param args Unused. Arguments to the program. + * @throws InterruptedException when a thread is waiting, sleeping, or otherwise occupied, + * and the thread is interrupted, either before or during the activity. + */ + public static void main(String[] args) throws InterruptedException { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to the "Access Keys" page under the "Settings" section. + String connectionString = Configuration.getGlobalConfiguration().get("AZURE_APPCONFIG_CONNECTION_STRING"); + + // Instantiate a client that will be used to call the service. + ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + + Map tags = new HashMap<>(); + tags.put("release", "first"); + Map tags2 = new HashMap<>(); + tags2.put("release", "first"); + tags2.put("release2", "second"); + + client.setConfigurationSetting(new ConfigurationSetting().setKey("keyForTag1").setValue("value1").setTags(tags)) + .subscribe(setting -> System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting.getKey(), setting.getValue(), setting.getTags())); + TimeUnit.MILLISECONDS.sleep(1000); + + client.setConfigurationSetting(new ConfigurationSetting().setKey("keyForTag2").setValue("value2").setTags(tags2)) + .subscribe(setting -> System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting.getKey(), setting.getValue(), setting.getTags())); + TimeUnit.MILLISECONDS.sleep(1000); + + client.setConfigurationSetting(new ConfigurationSetting().setKey("key3WithoutTag").setValue("value3")) + .subscribe(setting -> System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting.getKey(), setting.getValue(), setting.getTags())); + TimeUnit.MILLISECONDS.sleep(1000); + + List tagsFilterInString = getTagsFilterInString(tags2); + System.out.println("List settings with tags filter = " + tagsFilterInString); + client.listConfigurationSettings(new SettingSelector().setTagsFilter(tagsFilterInString)).subscribe( + setting -> System.out.printf("\tKey: %s, Value: %s, Tags: %s%n", + setting.getKey(), setting.getValue(), setting.getTags())); + TimeUnit.MILLISECONDS.sleep(4000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample20/v2/ListSettingsWithTagsFilterAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample20/v2/ListSettingsWithTagsFilterAsync.java new file mode 100644 index 000000000000..c97012e8d01b --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample20/v2/ListSettingsWithTagsFilterAsync.java @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.util.Configuration; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import static com.azure.data.appconfiguration.implementation.Utility.getTagsFilterInString; + +/** + * how to list settings with tags filter. + */ +public class ListSettingsWithTagsFilterAsync { + /** + * Runs the sample algorithm and demonstrates how to list settings with tags filter. + * + * @param args Unused. Arguments to the program. + * @throws InterruptedException when a thread is waiting, sleeping, or otherwise occupied, + * and the thread is interrupted, either before or during the activity. + */ + public static void main(String[] args) throws InterruptedException { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to the "Access Keys" page under the "Settings" section. + String connectionString = Configuration.getGlobalConfiguration().get("AZURE_APPCONFIG_CONNECTION_STRING"); + + // Instantiate a client that will be used to call the service. + ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + + Map tags = new HashMap<>(); + tags.put("release", "first"); + Map tags2 = new HashMap<>(); + tags2.put("release", "first"); + tags2.put("release2", "second"); + + client.setConfigurationSetting(new ConfigurationSetting().setKey("keyForTag1").setValue("value1").setTags(tags)) + .subscribe(setting -> System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting.getKey(), setting.getValue(), setting.getTags())); + TimeUnit.MILLISECONDS.sleep(1000); + + client.setConfigurationSetting(new ConfigurationSetting().setKey("keyForTag2").setValue("value2").setTags(tags2)) + .subscribe(setting -> System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting.getKey(), setting.getValue(), setting.getTags())); + TimeUnit.MILLISECONDS.sleep(1000); + + client.setConfigurationSetting(new ConfigurationSetting().setKey("key3WithoutTag").setValue("value3")) + .subscribe(setting -> System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting.getKey(), setting.getValue(), setting.getTags())); + TimeUnit.MILLISECONDS.sleep(1000); + + List tagsFilterInString = getTagsFilterInString(tags2); + System.out.println("List settings with tags filter = " + tagsFilterInString); + client.listConfigurationSettings(new SettingSelector().setTagsFilter(tagsFilterInString)).subscribe( + setting -> System.out.printf("\tKey: %s, Value: %s, Tags: %s%n", + setting.getKey(), setting.getValue(), setting.getTags())); + TimeUnit.MILLISECONDS.sleep(4000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample21/v1/ListSnapshots.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample21/v1/ListSnapshots.java new file mode 100644 index 000000000000..ada7d20039bb --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample21/v1/ListSnapshots.java @@ -0,0 +1,114 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.util.Configuration; +import com.azure.core.util.Context; +import com.azure.core.util.polling.PollOperationDetails; +import com.azure.core.util.polling.SyncPoller; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.ConfigurationSettingsFilter; +import com.azure.data.appconfiguration.models.ConfigurationSnapshot; +import com.azure.data.appconfiguration.models.SnapshotSelector; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; + +/** + * Sample demonstrates how to list snapshots. + */ +public class ListSnapshots { + /** + * Runs the sample demonstrates how to list snapshots. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = Configuration.getGlobalConfiguration().get("AZURE_APPCONFIG_CONNECTION_STRING"); + + // Instantiate a client that will be used to call the service. + final ConfigurationClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + + System.out.println("Beginning of synchronous sample..."); + + // 1. Prepare first setting. + ConfigurationSetting setting = client.setConfigurationSetting("TestKey1", null, "value1"); + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s.%n", setting.getKey(), setting.getValue()); + // 1. Prepare second setting. + ConfigurationSetting setting2 = client.setConfigurationSetting("TestKey2", null, "value2"); + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s.%n", setting2.getKey(), setting2.getValue()); + // 1. Prepare the snapshot filters + List filters = new ArrayList<>(); + // Key Name also supports RegExp but only support prefix end with "*", such as "k*" and is case-sensitive. + filters.add(new ConfigurationSettingsFilter("Test*")); + + // 1. Create first snapshot + String snapshotNameTest = "{snapshotNameInTest}"; + SyncPoller poller = + client.beginCreateSnapshot(snapshotNameTest, new ConfigurationSnapshot(filters), null); + poller.setPollInterval(Duration.ofSeconds(10)); + poller.waitForCompletion(); + ConfigurationSnapshot snapshot = poller.getFinalResult(); + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + snapshot.getName(), snapshot.getCreatedAt(), snapshot.getStatus()); + + // 2. Prepare third setting. + ConfigurationSetting setting3 = client.setConfigurationSetting("ProductKey1", null, "value1"); + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s.%n", setting.getKey(), setting.getValue()); + // 2. Prepare fourth setting. + ConfigurationSetting setting4 = client.setConfigurationSetting("ProductKey2", null, "value2"); + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s.%n", setting2.getKey(), setting2.getValue()); + // 2. Prepare the snapshot filters + List filters2 = new ArrayList<>(); + // Key Name also supports RegExp but only support prefix end with "*", such as "k*" and is case-sensitive. + filters.add(new ConfigurationSettingsFilter("Product*")); + + // 2. Create second snapshot + String snapshotNameProduct = "{snapshotNameInProduct}"; + SyncPoller pollerProduct = + client.beginCreateSnapshot(snapshotNameProduct, new ConfigurationSnapshot(filters), Context.NONE); + pollerProduct.setPollInterval(Duration.ofSeconds(10)); + pollerProduct.waitForCompletion(); + ConfigurationSnapshot productSnapshot = pollerProduct.getFinalResult(); + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + productSnapshot.getName(), productSnapshot.getCreatedAt(), productSnapshot.getStatus()); + + // List only the snapshot with name = snapshotNameInProduct + client.listSnapshots(new SnapshotSelector().setNameFilter(snapshotNameProduct)) + .forEach(snapshotResult -> { + System.out.printf("Listed Snapshot name = %s is created at %s, snapshot status is %s.%n", + snapshotResult.getName(), snapshotResult.getCreatedAt(), snapshotResult.getStatus()); + }); + + // Get the snapshot status + ConfigurationSnapshot getSnapshot = client.getSnapshot(snapshotNameProduct); + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + getSnapshot.getName(), getSnapshot.getCreatedAt(), getSnapshot.getStatus()); + + // Archive a READY snapshot + ConfigurationSnapshot archivedSnapshot = client.archiveSnapshot(snapshotNameProduct); + System.out.printf("Archived snapshot name=%s is created at %s, snapshot status is %s.%n", + archivedSnapshot.getName(), archivedSnapshot.getCreatedAt(), archivedSnapshot.getStatus()); + + // Recover the Archived snapshot + ConfigurationSnapshot recoveredSnapshot = client.recoverSnapshot(snapshotNameProduct); + System.out.printf("Recovered snapshot name=%s is created at %s, snapshot status is %s.%n", + recoveredSnapshot.getName(), recoveredSnapshot.getCreatedAt(), recoveredSnapshot.getStatus()); + + // List the configuration settings in the snapshot + client.listConfigurationSettingsForSnapshot(snapshotNameProduct).forEach( + settingInSnapshot -> { + System.out.printf("[ConfigurationSetting in snapshot] Key: %s, Value: %s%n", + settingInSnapshot.getKey(), settingInSnapshot.getValue()); + } + ); + + System.out.println("End of synchronous sample."); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample21/v2/ListSnapshots.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample21/v2/ListSnapshots.java new file mode 100644 index 000000000000..ada7d20039bb --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample21/v2/ListSnapshots.java @@ -0,0 +1,114 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.util.Configuration; +import com.azure.core.util.Context; +import com.azure.core.util.polling.PollOperationDetails; +import com.azure.core.util.polling.SyncPoller; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.ConfigurationSettingsFilter; +import com.azure.data.appconfiguration.models.ConfigurationSnapshot; +import com.azure.data.appconfiguration.models.SnapshotSelector; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; + +/** + * Sample demonstrates how to list snapshots. + */ +public class ListSnapshots { + /** + * Runs the sample demonstrates how to list snapshots. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = Configuration.getGlobalConfiguration().get("AZURE_APPCONFIG_CONNECTION_STRING"); + + // Instantiate a client that will be used to call the service. + final ConfigurationClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + + System.out.println("Beginning of synchronous sample..."); + + // 1. Prepare first setting. + ConfigurationSetting setting = client.setConfigurationSetting("TestKey1", null, "value1"); + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s.%n", setting.getKey(), setting.getValue()); + // 1. Prepare second setting. + ConfigurationSetting setting2 = client.setConfigurationSetting("TestKey2", null, "value2"); + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s.%n", setting2.getKey(), setting2.getValue()); + // 1. Prepare the snapshot filters + List filters = new ArrayList<>(); + // Key Name also supports RegExp but only support prefix end with "*", such as "k*" and is case-sensitive. + filters.add(new ConfigurationSettingsFilter("Test*")); + + // 1. Create first snapshot + String snapshotNameTest = "{snapshotNameInTest}"; + SyncPoller poller = + client.beginCreateSnapshot(snapshotNameTest, new ConfigurationSnapshot(filters), null); + poller.setPollInterval(Duration.ofSeconds(10)); + poller.waitForCompletion(); + ConfigurationSnapshot snapshot = poller.getFinalResult(); + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + snapshot.getName(), snapshot.getCreatedAt(), snapshot.getStatus()); + + // 2. Prepare third setting. + ConfigurationSetting setting3 = client.setConfigurationSetting("ProductKey1", null, "value1"); + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s.%n", setting.getKey(), setting.getValue()); + // 2. Prepare fourth setting. + ConfigurationSetting setting4 = client.setConfigurationSetting("ProductKey2", null, "value2"); + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s.%n", setting2.getKey(), setting2.getValue()); + // 2. Prepare the snapshot filters + List filters2 = new ArrayList<>(); + // Key Name also supports RegExp but only support prefix end with "*", such as "k*" and is case-sensitive. + filters.add(new ConfigurationSettingsFilter("Product*")); + + // 2. Create second snapshot + String snapshotNameProduct = "{snapshotNameInProduct}"; + SyncPoller pollerProduct = + client.beginCreateSnapshot(snapshotNameProduct, new ConfigurationSnapshot(filters), Context.NONE); + pollerProduct.setPollInterval(Duration.ofSeconds(10)); + pollerProduct.waitForCompletion(); + ConfigurationSnapshot productSnapshot = pollerProduct.getFinalResult(); + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + productSnapshot.getName(), productSnapshot.getCreatedAt(), productSnapshot.getStatus()); + + // List only the snapshot with name = snapshotNameInProduct + client.listSnapshots(new SnapshotSelector().setNameFilter(snapshotNameProduct)) + .forEach(snapshotResult -> { + System.out.printf("Listed Snapshot name = %s is created at %s, snapshot status is %s.%n", + snapshotResult.getName(), snapshotResult.getCreatedAt(), snapshotResult.getStatus()); + }); + + // Get the snapshot status + ConfigurationSnapshot getSnapshot = client.getSnapshot(snapshotNameProduct); + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + getSnapshot.getName(), getSnapshot.getCreatedAt(), getSnapshot.getStatus()); + + // Archive a READY snapshot + ConfigurationSnapshot archivedSnapshot = client.archiveSnapshot(snapshotNameProduct); + System.out.printf("Archived snapshot name=%s is created at %s, snapshot status is %s.%n", + archivedSnapshot.getName(), archivedSnapshot.getCreatedAt(), archivedSnapshot.getStatus()); + + // Recover the Archived snapshot + ConfigurationSnapshot recoveredSnapshot = client.recoverSnapshot(snapshotNameProduct); + System.out.printf("Recovered snapshot name=%s is created at %s, snapshot status is %s.%n", + recoveredSnapshot.getName(), recoveredSnapshot.getCreatedAt(), recoveredSnapshot.getStatus()); + + // List the configuration settings in the snapshot + client.listConfigurationSettingsForSnapshot(snapshotNameProduct).forEach( + settingInSnapshot -> { + System.out.printf("[ConfigurationSetting in snapshot] Key: %s, Value: %s%n", + settingInSnapshot.getKey(), settingInSnapshot.getValue()); + } + ); + + System.out.println("End of synchronous sample."); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample22/v1/ListSnapshotsAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample22/v1/ListSnapshotsAsync.java new file mode 100644 index 000000000000..1b574c0f897d --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample22/v1/ListSnapshotsAsync.java @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.ConfigurationSettingsFilter; +import com.azure.data.appconfiguration.models.ConfigurationSnapshot; +import com.azure.data.appconfiguration.models.SnapshotSelector; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** + * Sample demonstrates how to list snapshots asynchronously. + */ +public class ListSnapshotsAsync { + /** + * Runs the sample demonstrates how to list snapshots asynchronously. + * + * @param args Unused. Arguments to the program. + * @throws InterruptedException when a thread is waiting, sleeping, or otherwise occupied, + * and the thread is interrupted, either before or during the activity. + */ + public static void main(String[] args) throws InterruptedException { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Asynchronous sample + + // Instantiate a client that will be used to call the service. + final ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + // 1. Prepare first setting. + client.setConfigurationSetting("TestKey1", null, "value1").subscribe( + result -> { + final ConfigurationSetting setting = result; + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s.%n", setting.getKey(), setting.getValue()); + }, + error -> System.err.println("There was an error adding the setting: " + error), + () -> System.out.printf("Set setting with key=%s and value=%s added or updated.%n", "TestKey1", "value1")); + // 1. Prepare second setting. + client.setConfigurationSetting("TestKey2", null, "value2").subscribe( + result -> { + final ConfigurationSetting setting = result; + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s.%n", setting.getKey(), setting.getValue()); + }, + error -> System.err.println("There was an error adding the setting: " + error), + () -> System.out.printf("Set setting with key=%s and value=%s added or updated.%n", "TestKey2", "value2")); + + TimeUnit.MILLISECONDS.sleep(1000); + + // 1. Prepare the snapshot filters + List filters = new ArrayList<>(); + // Key Name also supports RegExp but only support prefix end with "*", such as "k*" and is case-sensitive. + filters.add(new ConfigurationSettingsFilter("Test*")); + String snapshotNameTest = "{snapshotNameInTest}"; + + // 1. Create first snapshot + client.beginCreateSnapshot(snapshotNameTest, new ConfigurationSnapshot(filters)) + .flatMap(result -> result.getFinalResult()) + .subscribe( + snapshot -> { + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + snapshot.getName(), snapshot.getCreatedAt(), snapshot.getStatus()); + }, + ex -> System.out.printf("Error on creating a snapshot=%s, with error=%s.%n", snapshotNameTest, ex.getMessage()), + () -> System.out.println("Successfully created a snapshot.")); + + TimeUnit.MILLISECONDS.sleep(1000); + + // 2. Prepare third setting. + client.setConfigurationSetting("ProductKey1", null, "value1").subscribe( + result -> { + final ConfigurationSetting setting = result; + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s.%n", setting.getKey(), setting.getValue()); + }, + error -> System.err.println("There was an error adding the setting: " + error), + () -> System.out.printf("Set setting with key=%s and value=%s added or updated.%n", "ProductKey1", "value1")); + // 1. Prepare fourth setting. + client.setConfigurationSetting("ProductKey2", null, "value2").subscribe( + result -> { + final ConfigurationSetting setting = result; + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s.%n", setting.getKey(), setting.getValue()); + }, + error -> System.err.println("There was an error adding the setting: " + error), + () -> System.out.printf("Set setting with key=%s and value=%s added or updated.%n", "ProductKey2", "value2")); + + TimeUnit.MILLISECONDS.sleep(1000); + + // 2. Prepare the snapshot filters + List filtersInProduct = new ArrayList<>(); + // Key Name also supports RegExp but only support prefix end with "*", such as "k*" and is case-sensitive. + filtersInProduct.add(new ConfigurationSettingsFilter("Product*")); + String snapshotNameProduct = "{snapshotNameInProduct}"; + + // 2. Create first snapshot + client.beginCreateSnapshot(snapshotNameTest, new ConfigurationSnapshot(filters)) + .flatMap(result -> result.getFinalResult()) + .subscribe( + snapshot -> { + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + snapshot.getName(), snapshot.getCreatedAt(), snapshot.getStatus()); + }, + ex -> System.out.printf("Error on creating a snapshot=%s, with error=%s.%n", snapshotNameProduct, ex.getMessage()), + () -> System.out.println("Successfully created a snapshot.")); + + TimeUnit.MILLISECONDS.sleep(1000); + + // List only the snapshot with name = snapshotNameInProduct + client.listSnapshots(new SnapshotSelector().setNameFilter(snapshotNameProduct)) + .subscribe(snapshotResult -> { + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + snapshotResult.getName(), snapshotResult.getCreatedAt(), snapshotResult.getStatus()); + }); + + // The .subscribe() creation and assignment is not a blocking call. For the purpose of this example, we sleep + // the thread so the program does not end before the send operation is complete. Using .block() instead of + // .subscribe() will turn this into a synchronous call. + try { + TimeUnit.MINUTES.sleep(5); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample22/v2/ListSnapshotsAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample22/v2/ListSnapshotsAsync.java new file mode 100644 index 000000000000..1b574c0f897d --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample22/v2/ListSnapshotsAsync.java @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.ConfigurationSettingsFilter; +import com.azure.data.appconfiguration.models.ConfigurationSnapshot; +import com.azure.data.appconfiguration.models.SnapshotSelector; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** + * Sample demonstrates how to list snapshots asynchronously. + */ +public class ListSnapshotsAsync { + /** + * Runs the sample demonstrates how to list snapshots asynchronously. + * + * @param args Unused. Arguments to the program. + * @throws InterruptedException when a thread is waiting, sleeping, or otherwise occupied, + * and the thread is interrupted, either before or during the activity. + */ + public static void main(String[] args) throws InterruptedException { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Asynchronous sample + + // Instantiate a client that will be used to call the service. + final ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + // 1. Prepare first setting. + client.setConfigurationSetting("TestKey1", null, "value1").subscribe( + result -> { + final ConfigurationSetting setting = result; + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s.%n", setting.getKey(), setting.getValue()); + }, + error -> System.err.println("There was an error adding the setting: " + error), + () -> System.out.printf("Set setting with key=%s and value=%s added or updated.%n", "TestKey1", "value1")); + // 1. Prepare second setting. + client.setConfigurationSetting("TestKey2", null, "value2").subscribe( + result -> { + final ConfigurationSetting setting = result; + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s.%n", setting.getKey(), setting.getValue()); + }, + error -> System.err.println("There was an error adding the setting: " + error), + () -> System.out.printf("Set setting with key=%s and value=%s added or updated.%n", "TestKey2", "value2")); + + TimeUnit.MILLISECONDS.sleep(1000); + + // 1. Prepare the snapshot filters + List filters = new ArrayList<>(); + // Key Name also supports RegExp but only support prefix end with "*", such as "k*" and is case-sensitive. + filters.add(new ConfigurationSettingsFilter("Test*")); + String snapshotNameTest = "{snapshotNameInTest}"; + + // 1. Create first snapshot + client.beginCreateSnapshot(snapshotNameTest, new ConfigurationSnapshot(filters)) + .flatMap(result -> result.getFinalResult()) + .subscribe( + snapshot -> { + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + snapshot.getName(), snapshot.getCreatedAt(), snapshot.getStatus()); + }, + ex -> System.out.printf("Error on creating a snapshot=%s, with error=%s.%n", snapshotNameTest, ex.getMessage()), + () -> System.out.println("Successfully created a snapshot.")); + + TimeUnit.MILLISECONDS.sleep(1000); + + // 2. Prepare third setting. + client.setConfigurationSetting("ProductKey1", null, "value1").subscribe( + result -> { + final ConfigurationSetting setting = result; + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s.%n", setting.getKey(), setting.getValue()); + }, + error -> System.err.println("There was an error adding the setting: " + error), + () -> System.out.printf("Set setting with key=%s and value=%s added or updated.%n", "ProductKey1", "value1")); + // 1. Prepare fourth setting. + client.setConfigurationSetting("ProductKey2", null, "value2").subscribe( + result -> { + final ConfigurationSetting setting = result; + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s.%n", setting.getKey(), setting.getValue()); + }, + error -> System.err.println("There was an error adding the setting: " + error), + () -> System.out.printf("Set setting with key=%s and value=%s added or updated.%n", "ProductKey2", "value2")); + + TimeUnit.MILLISECONDS.sleep(1000); + + // 2. Prepare the snapshot filters + List filtersInProduct = new ArrayList<>(); + // Key Name also supports RegExp but only support prefix end with "*", such as "k*" and is case-sensitive. + filtersInProduct.add(new ConfigurationSettingsFilter("Product*")); + String snapshotNameProduct = "{snapshotNameInProduct}"; + + // 2. Create first snapshot + client.beginCreateSnapshot(snapshotNameTest, new ConfigurationSnapshot(filters)) + .flatMap(result -> result.getFinalResult()) + .subscribe( + snapshot -> { + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + snapshot.getName(), snapshot.getCreatedAt(), snapshot.getStatus()); + }, + ex -> System.out.printf("Error on creating a snapshot=%s, with error=%s.%n", snapshotNameProduct, ex.getMessage()), + () -> System.out.println("Successfully created a snapshot.")); + + TimeUnit.MILLISECONDS.sleep(1000); + + // List only the snapshot with name = snapshotNameInProduct + client.listSnapshots(new SnapshotSelector().setNameFilter(snapshotNameProduct)) + .subscribe(snapshotResult -> { + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + snapshotResult.getName(), snapshotResult.getCreatedAt(), snapshotResult.getStatus()); + }); + + // The .subscribe() creation and assignment is not a blocking call. For the purpose of this example, we sleep + // the thread so the program does not end before the send operation is complete. Using .block() instead of + // .subscribe() will turn this into a synchronous call. + try { + TimeUnit.MINUTES.sleep(5); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample23/v1/PipelineSample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample23/v1/PipelineSample.java new file mode 100644 index 000000000000..bd39522857c1 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample23/v1/PipelineSample.java @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.http.HttpMethod; +import com.azure.core.http.HttpPipelineCallContext; +import com.azure.core.http.HttpPipelineNextPolicy; +import com.azure.core.http.HttpResponse; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.policy.HttpLogOptions; +import com.azure.core.http.policy.HttpPipelinePolicy; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * Sample demonstrates how to add a custom policy into the HTTP pipeline. + */ +class PipelineSample { + /** + * Runs the sample algorithm and demonstrates how to add a custom policy to the HTTP pipeline. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + final String connectionString = "endpoint={endpoint_value};id={id_value};name={secret_value}"; + final HttpMethodRequestTracker tracker = new HttpMethodRequestTracker(); + + // Instantiate a client that will be used to call the service. + // We add in a policy to track the type of HTTP method calls we make. + // We also want to see the Header information of our HTTP requests, so we specify the detail level. + final ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .addPolicy(new HttpMethodRequestTrackingPolicy(tracker)) + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.HEADERS)) + .buildAsyncClient(); + + // Adding a couple of settings and then fetching all the settings in our repository. + final List settings = Flux.concat( + client.addConfigurationSetting("hello", null, "world"), + client.setConfigurationSetting("newSetting", null, "newValue")) + .then(client.listConfigurationSettings(new SettingSelector().setKeyFilter("*")).collectList()) + .block(); + + // Cleaning up after ourselves by deleting the values. + final Stream stream = settings == null ? Stream.empty() : settings.stream(); + Flux.merge(stream.map(setting -> client.deleteConfigurationSettingWithResponse(setting, false)) + .collect(Collectors.toList())).blockLast(); + + // Check what sort of HTTP method calls we made. + tracker.print(); + } + + static class HttpMethodRequestTracker { + private final ConcurrentHashMap tracker = new ConcurrentHashMap<>(); + + void increment(HttpMethod key) { + tracker.compute(key, (k, value) -> { + if (value == null) { + return 1; + } else { + return value + 1; + } + }); + } + + void print() { + tracker.forEach((key, value) -> System.out.printf("HTTP Method [%s], # of calls: %s", key, value)); + } + } + + /* + * This policy tracks the number of HTTPMethod calls we make. + */ + static class HttpMethodRequestTrackingPolicy implements HttpPipelinePolicy { + private final HttpMethodRequestTracker tracker; + + HttpMethodRequestTrackingPolicy(HttpMethodRequestTracker tracker) { + this.tracker = tracker; + } + + @Override + public Mono process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { + tracker.increment(context.getHttpRequest().getHttpMethod()); + return next.process(); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample23/v2/PipelineSample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample23/v2/PipelineSample.java new file mode 100644 index 000000000000..bd39522857c1 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample23/v2/PipelineSample.java @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.http.HttpMethod; +import com.azure.core.http.HttpPipelineCallContext; +import com.azure.core.http.HttpPipelineNextPolicy; +import com.azure.core.http.HttpResponse; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.policy.HttpLogOptions; +import com.azure.core.http.policy.HttpPipelinePolicy; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * Sample demonstrates how to add a custom policy into the HTTP pipeline. + */ +class PipelineSample { + /** + * Runs the sample algorithm and demonstrates how to add a custom policy to the HTTP pipeline. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + final String connectionString = "endpoint={endpoint_value};id={id_value};name={secret_value}"; + final HttpMethodRequestTracker tracker = new HttpMethodRequestTracker(); + + // Instantiate a client that will be used to call the service. + // We add in a policy to track the type of HTTP method calls we make. + // We also want to see the Header information of our HTTP requests, so we specify the detail level. + final ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .addPolicy(new HttpMethodRequestTrackingPolicy(tracker)) + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.HEADERS)) + .buildAsyncClient(); + + // Adding a couple of settings and then fetching all the settings in our repository. + final List settings = Flux.concat( + client.addConfigurationSetting("hello", null, "world"), + client.setConfigurationSetting("newSetting", null, "newValue")) + .then(client.listConfigurationSettings(new SettingSelector().setKeyFilter("*")).collectList()) + .block(); + + // Cleaning up after ourselves by deleting the values. + final Stream stream = settings == null ? Stream.empty() : settings.stream(); + Flux.merge(stream.map(setting -> client.deleteConfigurationSettingWithResponse(setting, false)) + .collect(Collectors.toList())).blockLast(); + + // Check what sort of HTTP method calls we made. + tracker.print(); + } + + static class HttpMethodRequestTracker { + private final ConcurrentHashMap tracker = new ConcurrentHashMap<>(); + + void increment(HttpMethod key) { + tracker.compute(key, (k, value) -> { + if (value == null) { + return 1; + } else { + return value + 1; + } + }); + } + + void print() { + tracker.forEach((key, value) -> System.out.printf("HTTP Method [%s], # of calls: %s", key, value)); + } + } + + /* + * This policy tracks the number of HTTPMethod calls we make. + */ + static class HttpMethodRequestTrackingPolicy implements HttpPipelinePolicy { + private final HttpMethodRequestTracker tracker; + + HttpMethodRequestTrackingPolicy(HttpMethodRequestTracker tracker) { + this.tracker = tracker; + } + + @Override + public Mono process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { + tracker.increment(context.getHttpRequest().getHttpMethod()); + return next.process(); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample24/v1/ProxyOptionsSample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample24/v1/ProxyOptionsSample.java new file mode 100644 index 000000000000..264515abd152 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample24/v1/ProxyOptionsSample.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.http.HttpClient; +import com.azure.core.http.ProxyOptions; +import com.azure.core.http.netty.NettyAsyncHttpClientBuilder; +import com.azure.data.appconfiguration.models.ConfigurationSetting; + +import java.net.InetSocketAddress; + +/** + * Sample for writing configuration proxy. + */ +public class ProxyOptionsSample { + /** + * Runs the sample algorithm and demonstrates how to add a custom policy to the HTTP pipeline. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Proxy options + String hostName = "{your-host-name}"; + int port = 447; // your port number + + ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, + new InetSocketAddress(hostName, port)); + HttpClient httpClient = new NettyAsyncHttpClientBuilder() + .proxy(proxyOptions) + .build(); + + ConfigurationClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .httpClient(httpClient) + .buildClient(); + + // Name of the key to add to the configuration service. + final String key = "hello"; + final String value = "world"; + + ConfigurationSetting setting = client.setConfigurationSetting(key, null, value); + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + + setting = client.getConfigurationSetting(key, null, null); + System.out.printf("[GetConfigurationSetting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + + setting = client.deleteConfigurationSetting(key, null); + System.out.printf("[DeleteConfigurationSetting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + + System.out.println("End of synchronous sample."); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample24/v2/ProxyOptionsSample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample24/v2/ProxyOptionsSample.java new file mode 100644 index 000000000000..264515abd152 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample24/v2/ProxyOptionsSample.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.http.HttpClient; +import com.azure.core.http.ProxyOptions; +import com.azure.core.http.netty.NettyAsyncHttpClientBuilder; +import com.azure.data.appconfiguration.models.ConfigurationSetting; + +import java.net.InetSocketAddress; + +/** + * Sample for writing configuration proxy. + */ +public class ProxyOptionsSample { + /** + * Runs the sample algorithm and demonstrates how to add a custom policy to the HTTP pipeline. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Proxy options + String hostName = "{your-host-name}"; + int port = 447; // your port number + + ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, + new InetSocketAddress(hostName, port)); + HttpClient httpClient = new NettyAsyncHttpClientBuilder() + .proxy(proxyOptions) + .build(); + + ConfigurationClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .httpClient(httpClient) + .buildClient(); + + // Name of the key to add to the configuration service. + final String key = "hello"; + final String value = "world"; + + ConfigurationSetting setting = client.setConfigurationSetting(key, null, value); + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + + setting = client.getConfigurationSetting(key, null, null); + System.out.printf("[GetConfigurationSetting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + + setting = client.deleteConfigurationSetting(key, null); + System.out.printf("[DeleteConfigurationSetting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + + System.out.println("End of synchronous sample."); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample25/v1/ReadmeSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample25/v1/ReadmeSamples.java new file mode 100644 index 000000000000..5c03ce43ee30 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample25/v1/ReadmeSamples.java @@ -0,0 +1,487 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.data.appconfiguration; + +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpHeaders; +import com.azure.core.http.ProxyOptions; +import com.azure.core.http.netty.NettyAsyncHttpClientBuilder; +import com.azure.core.http.policy.AddHeadersFromContextPolicy; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.policy.HttpLogOptions; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.core.util.polling.PollOperationDetails; +import com.azure.core.util.polling.SyncPoller; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.ConfigurationSettingsFilter; +import com.azure.data.appconfiguration.models.ConfigurationSnapshot; +import com.azure.data.appconfiguration.models.FeatureFlagConfigurationSetting; +import com.azure.data.appconfiguration.models.FeatureFlagFilter; +import com.azure.data.appconfiguration.models.SettingLabelSelector; +import com.azure.data.appconfiguration.models.SecretReferenceConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; +import com.azure.data.appconfiguration.models.SnapshotSelector; +import com.azure.identity.DefaultAzureCredential; +import com.azure.identity.DefaultAzureCredentialBuilder; + +import java.net.InetSocketAddress; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * WARNING: MODIFYING THIS FILE WILL REQUIRE CORRESPONDING UPDATES TO README.md FILE. LINE NUMBERS + * ARE USED TO EXTRACT APPROPRIATE CODE SEGMENTS FROM THIS FILE. ADD NEW CODE AT THE BOTTOM TO AVOID CHANGING + * LINE NUMBERS OF EXISTING CODE SAMPLES. + * + * Code samples for the README.md + */ +@SuppressWarnings("unused") +public class ReadmeSamples { + private String endpoint = "endpoint"; + private String connectionString = "connection string"; + private String urlKey = "url key"; + private String urlLabel = "url label"; + private String periodicUpdateLabel = "periodic update label"; + private ConfigurationClient configurationClient = new ConfigurationClientBuilder().buildClient(); + + public void createClient() { + // BEGIN: readme-sample-createClient + ConfigurationClient configurationClient = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + // END: readme-sample-createClient + } + + public void createAsyncClient() { + // BEGIN: readme-sample-createAsyncClient + ConfigurationAsyncClient configurationClient = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + // END: readme-sample-createAsyncClient + } + + public void aadAuthentication() { + // BEGIN: readme-sample-aadAuthentication + DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build(); + ConfigurationClient configurationClient = new ConfigurationClientBuilder() + .credential(credential) + .endpoint(endpoint) + .buildClient(); + // END: readme-sample-aadAuthentication + } + + public void sqlExample() { + // BEGIN: readme-sample-sqlExample + ConfigurationClient configurationClient = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + + // urlLabel is optional + String url = configurationClient.getConfigurationSetting(urlKey, urlLabel).getValue(); + Connection conn = null; + try { + conn = DriverManager.getConnection(url); + } catch (SQLException ex) { + System.out.printf("Failed to get connection using url %s", url); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException ex) { + System.out.printf("Failed to close connection, url %s", url); + } + } + } + // END: readme-sample-sqlExample + } + + public void listConfigurationsExample() { + // BEGIN: readme-sample-listConfigurationsExample + ConfigurationAsyncClient configurationClient = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + + configurationClient.listConfigurationSettings(new SettingSelector().setLabelFilter(periodicUpdateLabel)) + .subscribe(setting -> updateConfiguration(setting)); + // END: readme-sample-listConfigurationsExample + } + + public void addConfigurationSetting() { + // BEGIN: readme-sample-addConfigurationSetting + ConfigurationSetting setting = configurationClient.addConfigurationSetting("new_key", "new_label", "new_value"); + // END: readme-sample-addConfigurationSetting + } + + public void setConfigurationSetting() { + // BEGIN: readme-sample-setConfigurationSetting + ConfigurationSetting setting = configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); + // END: readme-sample-setConfigurationSetting + } + + public void getConfigurationSetting() { + // BEGIN: readme-sample-getConfigurationSetting + ConfigurationSetting setting = configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); + ConfigurationSetting retrievedSetting = configurationClient.getConfigurationSetting("some_key", "some_label"); + // END: readme-sample-getConfigurationSetting + } + + public void getConfigurationSettingConditionally() { + // BEGIN: readme-sample-getConfigurationSettingConditionally + ConfigurationSetting setting = configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); + Response settingResponse = configurationClient.getConfigurationSettingWithResponse(setting, null, true, Context.NONE); + // END: readme-sample-getConfigurationSettingConditionally + } + + public void updateConfigurationSetting() { + // BEGIN: readme-sample-updateConfigurationSetting + ConfigurationSetting setting = configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); + ConfigurationSetting updatedSetting = configurationClient.setConfigurationSetting("some_key", "some_label", "new_value"); + // END: readme-sample-updateConfigurationSetting + } + + public void updateConfigurationSettingConditionally() { + // BEGIN: readme-sample-updateConfigurationSettingConditionally + ConfigurationSetting setting = configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); + Response settingResponse = configurationClient.setConfigurationSettingWithResponse(setting, true, Context.NONE); + // END: readme-sample-updateConfigurationSettingConditionally + } + + public void deleteConfigurationSetting() { + // BEGIN: readme-sample-deleteConfigurationSetting + ConfigurationSetting setting = configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); + ConfigurationSetting deletedSetting = configurationClient.deleteConfigurationSetting("some_key", "some_label"); + // END: readme-sample-deleteConfigurationSetting + } + + public void deleteConfigurationSettingConditionally() { + // BEGIN: readme-sample-deleteConfigurationSettingConditionally + ConfigurationSetting setting = configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); + Response settingResponse = configurationClient.deleteConfigurationSettingWithResponse(setting, true, Context.NONE); + // END: readme-sample-deleteConfigurationSettingConditionally + } + + public void listConfigurationSetting() { + // BEGIN: readme-sample-listConfigurationSetting + String key = "some_key"; + String key2 = "new_key"; + configurationClient.setConfigurationSetting(key, "some_label", "some_value"); + configurationClient.setConfigurationSetting(key2, "new_label", "new_value"); + SettingSelector selector = new SettingSelector().setKeyFilter(key + "," + key2); + PagedIterable settings = configurationClient.listConfigurationSettings(selector); + // END: readme-sample-listConfigurationSetting + } + + public void listRevisions() { + // BEGIN: readme-sample-listRevisions + String key = "revisionKey"; + configurationClient.setConfigurationSetting(key, "some_label", "some_value"); + configurationClient.setConfigurationSetting(key, "new_label", "new_value"); + SettingSelector selector = new SettingSelector().setKeyFilter(key); + PagedIterable settings = configurationClient.listRevisions(selector); + // END: readme-sample-listRevisions + } + + public void setReadOnly() { + // BEGIN: readme-sample-setReadOnly + configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); + ConfigurationSetting setting = configurationClient.setReadOnly("some_key", "some_label", true); + // END: readme-sample-setReadOnly + } + + public void clearReadOnly() { + // BEGIN: readme-sample-clearReadOnly + ConfigurationSetting setting = configurationClient.setReadOnly("some_key", "some_label", false); + // END: readme-sample-clearReadOnly + } + + public void customHeaders() { + // BEGIN: readme-sample-customHeaders + // Add your headers + HttpHeaders headers = new HttpHeaders(); + headers.set("my-header1", "my-header1-value"); + headers.set("my-header2", "my-header2-value"); + headers.set("my-header3", "my-header3-value"); + // Call API by passing headers in Context. + configurationClient.addConfigurationSettingWithResponse( + new ConfigurationSetting().setKey("key").setValue("value"), + new Context(AddHeadersFromContextPolicy.AZURE_REQUEST_HTTP_HEADERS_KEY, headers)); + // Above three HttpHeader will be added in outgoing HttpRequest. + // END: readme-sample-customHeaders + } + + public void createClientWithProxyOption() { + // BEGIN: readme-sample-createClientWithProxyOption + // Proxy options + final String hostname = "{your-host-name}"; + final int port = 447; // your port number + + ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, + new InetSocketAddress(hostname, port)); + HttpClient httpClient = new NettyAsyncHttpClientBuilder() + .proxy(proxyOptions) + .build(); + ConfigurationAsyncClient configurationAsyncClient = new ConfigurationClientBuilder() + .connectionString("{your_connection_string}") + .httpClient(httpClient) + .buildAsyncClient(); + // END: readme-sample-createClientWithProxyOption + } + + public void createFeatureFlagConfigurationSetting() { + // BEGIN: readme-sample-addFeatureFlagConfigurationSetting + String key = "some_key"; + String filterName = "{filter_name}"; // such as "Microsoft.Percentage" + String filterParameterKey = "{filter_parameter_key}"; // "Value" + Object filterParameterValue = 30; // Any value. Could be String, primitive value, or Json Object + FeatureFlagFilter percentageFilter = new FeatureFlagFilter(filterName) + .addParameter(filterParameterKey, filterParameterValue); + FeatureFlagConfigurationSetting featureFlagConfigurationSetting = + new FeatureFlagConfigurationSetting(key, true) + .setClientFilters(Arrays.asList(percentageFilter)); + + FeatureFlagConfigurationSetting setting = (FeatureFlagConfigurationSetting) + configurationClient.addConfigurationSetting(featureFlagConfigurationSetting); + // END: readme-sample-addFeatureFlagConfigurationSetting + } + + public void updateFeatureFlagConfigurationSetting() { + String key = "some_key"; + String filterName = "{filter_name}"; // such as "Microsoft.Percentage" + String filterParameterKey = "{filter_parameter_key}"; // "Value" + Object filterParameterValue = 30; // Any value. Could be String, primitive value, or Json Object + FeatureFlagFilter percentageFilter = new FeatureFlagFilter(filterName) + .addParameter(filterParameterKey, filterParameterValue); + FeatureFlagConfigurationSetting featureFlagConfigurationSetting = + new FeatureFlagConfigurationSetting(key, true) + .setClientFilters(Arrays.asList(percentageFilter)); + + // BEGIN: readme-sample-updateFeatureFlagConfigurationSetting + FeatureFlagConfigurationSetting setting = (FeatureFlagConfigurationSetting) + configurationClient.setConfigurationSetting(featureFlagConfigurationSetting); + // END: readme-sample-updateFeatureFlagConfigurationSetting + } + + public void getFeatureFlagConfigurationSetting() { + String key = "some_key"; + String filterName = "{filter_name}"; // such as "Microsoft.Percentage" + String filterParameterKey = "{filter_parameter_key}"; // "Value" + Object filterParameterValue = 30; // Any value. Could be String, primitive value, or Json Object + FeatureFlagFilter percentageFilter = new FeatureFlagFilter(filterName) + .addParameter(filterParameterKey, filterParameterValue); + FeatureFlagConfigurationSetting featureFlagConfigurationSetting = + new FeatureFlagConfigurationSetting(key, true) + .setClientFilters(Arrays.asList(percentageFilter)); + + // BEGIN: readme-sample-getFeatureFlagConfigurationSetting + FeatureFlagConfigurationSetting setting = (FeatureFlagConfigurationSetting) + configurationClient.getConfigurationSetting(featureFlagConfigurationSetting); + // END: readme-sample-getFeatureFlagConfigurationSetting + } + + public void deleteFeatureFlagConfigurationSetting() { + String key = "some_key"; + String filterName = "{filter_name}"; // such as "Microsoft.Percentage" + String filterParameterKey = "{filter_parameter_key}"; // "Value" + Object filterParameterValue = 30; // Any value. Could be String, primitive value, or Json Object + FeatureFlagFilter percentageFilter = new FeatureFlagFilter(filterName) + .addParameter(filterParameterKey, filterParameterValue); + FeatureFlagConfigurationSetting featureFlagConfigurationSetting = + new FeatureFlagConfigurationSetting(key, true) + .setClientFilters(Arrays.asList(percentageFilter)); + + // BEGIN: readme-sample-deleteFeatureFlagConfigurationSetting + FeatureFlagConfigurationSetting setting = (FeatureFlagConfigurationSetting) + configurationClient.deleteConfigurationSetting(featureFlagConfigurationSetting); + // END: readme-sample-deleteFeatureFlagConfigurationSetting + } + + public void addSecretReferenceConfigurationSetting() { + // BEGIN: readme-sample-addSecretReferenceConfigurationSetting + String key = "{some_key}"; + String keyVaultReference = "{key_vault_reference}"; + + SecretReferenceConfigurationSetting referenceConfigurationSetting = + new SecretReferenceConfigurationSetting(key, keyVaultReference); + + SecretReferenceConfigurationSetting setting = (SecretReferenceConfigurationSetting) + configurationClient.addConfigurationSetting(referenceConfigurationSetting); + // END: readme-sample-addSecretReferenceConfigurationSetting + } + + public void updateSecretReferenceConfigurationSetting() { + String key = "{some_key}"; + String keyVaultReference = "{key_vault_reference}"; + + SecretReferenceConfigurationSetting referenceConfigurationSetting = + new SecretReferenceConfigurationSetting(key, keyVaultReference); + + // BEGIN: readme-sample-updateSecretReferenceConfigurationSetting + SecretReferenceConfigurationSetting setting = (SecretReferenceConfigurationSetting) + configurationClient.setConfigurationSetting(referenceConfigurationSetting); + // END: readme-sample-updateSecretReferenceConfigurationSetting + } + + public void getSecretReferenceConfigurationSetting() { + String key = "{some_key}"; + String keyVaultReference = "{key_vault_reference}"; + + SecretReferenceConfigurationSetting referenceConfigurationSetting = + new SecretReferenceConfigurationSetting(key, keyVaultReference); + + // BEGIN: readme-sample-getSecretReferenceConfigurationSetting + SecretReferenceConfigurationSetting setting = (SecretReferenceConfigurationSetting) + configurationClient.getConfigurationSetting(referenceConfigurationSetting); + // END: readme-sample-getSecretReferenceConfigurationSetting + } + + public void deleteSecretReferenceConfigurationSetting() { + String key = "{some_key}"; + String keyVaultReference = "{key_vault_reference}"; + + SecretReferenceConfigurationSetting referenceConfigurationSetting = + new SecretReferenceConfigurationSetting(key, keyVaultReference); + + // BEGIN: readme-sample-deleteSecretReferenceConfigurationSetting + SecretReferenceConfigurationSetting setting = (SecretReferenceConfigurationSetting) + configurationClient.deleteConfigurationSetting(referenceConfigurationSetting); + // END: readme-sample-deleteSecretReferenceConfigurationSetting + } + + public void enableHttpLogging() { + // BEGIN: readme-sample-enablehttplogging + ConfigurationClient configurationClient = new ConfigurationClientBuilder() + .connectionString(connectionString) + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) + .buildClient(); + // or + DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build(); + ConfigurationClient configurationClientAad = new ConfigurationClientBuilder() + .credential(credential) + .endpoint(endpoint) + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) + .buildClient(); + // END: readme-sample-enablehttplogging + + } + + public void troubleshootingExceptions() { + ConfigurationClient client = new ConfigurationClientBuilder() + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + // BEGIN: readme-sample-troubleshootingExceptions + try { + ConfigurationSetting setting = new ConfigurationSetting().setKey("myKey").setValue("myValue"); + client.getConfigurationSetting(setting); + } catch (HttpResponseException e) { + System.out.println(e.getMessage()); + // Do something with the exception + } + // END: readme-sample-troubleshootingExceptions + + ConfigurationAsyncClient asyncClient = new ConfigurationClientBuilder() + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + // BEGIN: readme-sample-troubleshootingExceptions-async + ConfigurationSetting setting = new ConfigurationSetting().setKey("myKey").setValue("myValue"); + asyncClient.getConfigurationSetting(setting) + .doOnSuccess(ignored -> System.out.println("Success!")) + .doOnError( + error -> error instanceof ResourceNotFoundException, + error -> System.out.println("Exception: 'getConfigurationSetting' could not be performed.")); + // END: readme-sample-troubleshootingExceptions-async + } + + public void createSnapshot() { + // BEGIN: readme-sample-createSnapshot + String snapshotName = "{snapshotName}"; + // Prepare the snapshot filters + List filters = new ArrayList<>(); + // Key Name also supports RegExp but only support prefix end with "*", such as "k*" and is case-sensitive. + filters.add(new ConfigurationSettingsFilter("Test*")); + SyncPoller poller = + configurationClient.beginCreateSnapshot(snapshotName, new ConfigurationSnapshot(filters), Context.NONE); + poller.setPollInterval(Duration.ofSeconds(10)); + poller.waitForCompletion(); + ConfigurationSnapshot snapshot = poller.getFinalResult(); + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + snapshot.getName(), snapshot.getCreatedAt(), snapshot.getStatus()); + // END: readme-sample-createSnapshot + } + + public void getSnapshot() { + // BEGIN: readme-sample-getSnapshot + String snapshotName = "{snapshotName}"; + ConfigurationSnapshot getSnapshot = configurationClient.getSnapshot(snapshotName); + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + getSnapshot.getName(), getSnapshot.getCreatedAt(), getSnapshot.getStatus()); + // END: readme-sample-getSnapshot + } + + public void archiveSnapshot() { + // BEGIN: readme-sample-archiveSnapshot + String snapshotName = "{snapshotName}"; + ConfigurationSnapshot archivedSnapshot = configurationClient.archiveSnapshot(snapshotName); + System.out.printf("Archived snapshot name=%s is created at %s, snapshot status is %s.%n", + archivedSnapshot.getName(), archivedSnapshot.getCreatedAt(), archivedSnapshot.getStatus()); + // END: readme-sample-archiveSnapshot + } + + public void recoverSnapshot() { + // BEGIN: readme-sample-recoverSnapshot + String snapshotName = "{snapshotName}"; + ConfigurationSnapshot recoveredSnapshot = configurationClient.recoverSnapshot(snapshotName); + System.out.printf("Recovered snapshot name=%s is created at %s, snapshot status is %s.%n", + recoveredSnapshot.getName(), recoveredSnapshot.getCreatedAt(), recoveredSnapshot.getStatus()); + // END: readme-sample-recoverSnapshot + } + + public void listSnapshot() { + // BEGIN: readme-sample-getAllSnapshots + String snapshotNameProduct = "{snapshotNameInProduct}"; + SnapshotSelector snapshotSelector = new SnapshotSelector().setNameFilter(snapshotNameProduct); + PagedIterable configurationSnapshots = + configurationClient.listSnapshots(snapshotSelector); + for (ConfigurationSnapshot snapshot : configurationSnapshots) { + System.out.printf("Listed Snapshot name = %s is created at %s, snapshot status is %s.%n", + snapshot.getName(), snapshot.getCreatedAt(), snapshot.getStatus()); + } + // END: readme-sample-getAllSnapshots + } + + public void listSettingInSnapshot() { + // BEGIN: readme-sample-listSettingsInSnapshot + String snapshotNameProduct = "{snapshotNameInProduct}"; + PagedIterable configurationSettings = + configurationClient.listConfigurationSettingsForSnapshot(snapshotNameProduct); + + for (ConfigurationSetting setting : configurationSettings) { + System.out.printf("[ConfigurationSetting in snapshot] Key: %s, Value: %s%n", + setting.getKey(), setting.getValue()); + } + // END: readme-sample-listSettingsInSnapshot + + } + + public void listLabels() { + // BEGIN: readme-sample-listLabels + String labelNameFilter = "{labelNamePrefix}*"; + configurationClient.listLabels(new SettingLabelSelector().setNameFilter(labelNameFilter)) + .forEach(label -> { + System.out.println("label name = " + label.getName()); + }); + // END: readme-sample-listLabels + } + + private void updateConfiguration(ConfigurationSetting setting) { + // do something on the given setting. + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample25/v2/ReadmeSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample25/v2/ReadmeSamples.java new file mode 100644 index 000000000000..5c03ce43ee30 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample25/v2/ReadmeSamples.java @@ -0,0 +1,487 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.data.appconfiguration; + +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpHeaders; +import com.azure.core.http.ProxyOptions; +import com.azure.core.http.netty.NettyAsyncHttpClientBuilder; +import com.azure.core.http.policy.AddHeadersFromContextPolicy; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.policy.HttpLogOptions; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.core.util.polling.PollOperationDetails; +import com.azure.core.util.polling.SyncPoller; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.ConfigurationSettingsFilter; +import com.azure.data.appconfiguration.models.ConfigurationSnapshot; +import com.azure.data.appconfiguration.models.FeatureFlagConfigurationSetting; +import com.azure.data.appconfiguration.models.FeatureFlagFilter; +import com.azure.data.appconfiguration.models.SettingLabelSelector; +import com.azure.data.appconfiguration.models.SecretReferenceConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; +import com.azure.data.appconfiguration.models.SnapshotSelector; +import com.azure.identity.DefaultAzureCredential; +import com.azure.identity.DefaultAzureCredentialBuilder; + +import java.net.InetSocketAddress; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * WARNING: MODIFYING THIS FILE WILL REQUIRE CORRESPONDING UPDATES TO README.md FILE. LINE NUMBERS + * ARE USED TO EXTRACT APPROPRIATE CODE SEGMENTS FROM THIS FILE. ADD NEW CODE AT THE BOTTOM TO AVOID CHANGING + * LINE NUMBERS OF EXISTING CODE SAMPLES. + * + * Code samples for the README.md + */ +@SuppressWarnings("unused") +public class ReadmeSamples { + private String endpoint = "endpoint"; + private String connectionString = "connection string"; + private String urlKey = "url key"; + private String urlLabel = "url label"; + private String periodicUpdateLabel = "periodic update label"; + private ConfigurationClient configurationClient = new ConfigurationClientBuilder().buildClient(); + + public void createClient() { + // BEGIN: readme-sample-createClient + ConfigurationClient configurationClient = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + // END: readme-sample-createClient + } + + public void createAsyncClient() { + // BEGIN: readme-sample-createAsyncClient + ConfigurationAsyncClient configurationClient = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + // END: readme-sample-createAsyncClient + } + + public void aadAuthentication() { + // BEGIN: readme-sample-aadAuthentication + DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build(); + ConfigurationClient configurationClient = new ConfigurationClientBuilder() + .credential(credential) + .endpoint(endpoint) + .buildClient(); + // END: readme-sample-aadAuthentication + } + + public void sqlExample() { + // BEGIN: readme-sample-sqlExample + ConfigurationClient configurationClient = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + + // urlLabel is optional + String url = configurationClient.getConfigurationSetting(urlKey, urlLabel).getValue(); + Connection conn = null; + try { + conn = DriverManager.getConnection(url); + } catch (SQLException ex) { + System.out.printf("Failed to get connection using url %s", url); + } finally { + if (conn != null) { + try { + conn.close(); + } catch (SQLException ex) { + System.out.printf("Failed to close connection, url %s", url); + } + } + } + // END: readme-sample-sqlExample + } + + public void listConfigurationsExample() { + // BEGIN: readme-sample-listConfigurationsExample + ConfigurationAsyncClient configurationClient = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + + configurationClient.listConfigurationSettings(new SettingSelector().setLabelFilter(periodicUpdateLabel)) + .subscribe(setting -> updateConfiguration(setting)); + // END: readme-sample-listConfigurationsExample + } + + public void addConfigurationSetting() { + // BEGIN: readme-sample-addConfigurationSetting + ConfigurationSetting setting = configurationClient.addConfigurationSetting("new_key", "new_label", "new_value"); + // END: readme-sample-addConfigurationSetting + } + + public void setConfigurationSetting() { + // BEGIN: readme-sample-setConfigurationSetting + ConfigurationSetting setting = configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); + // END: readme-sample-setConfigurationSetting + } + + public void getConfigurationSetting() { + // BEGIN: readme-sample-getConfigurationSetting + ConfigurationSetting setting = configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); + ConfigurationSetting retrievedSetting = configurationClient.getConfigurationSetting("some_key", "some_label"); + // END: readme-sample-getConfigurationSetting + } + + public void getConfigurationSettingConditionally() { + // BEGIN: readme-sample-getConfigurationSettingConditionally + ConfigurationSetting setting = configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); + Response settingResponse = configurationClient.getConfigurationSettingWithResponse(setting, null, true, Context.NONE); + // END: readme-sample-getConfigurationSettingConditionally + } + + public void updateConfigurationSetting() { + // BEGIN: readme-sample-updateConfigurationSetting + ConfigurationSetting setting = configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); + ConfigurationSetting updatedSetting = configurationClient.setConfigurationSetting("some_key", "some_label", "new_value"); + // END: readme-sample-updateConfigurationSetting + } + + public void updateConfigurationSettingConditionally() { + // BEGIN: readme-sample-updateConfigurationSettingConditionally + ConfigurationSetting setting = configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); + Response settingResponse = configurationClient.setConfigurationSettingWithResponse(setting, true, Context.NONE); + // END: readme-sample-updateConfigurationSettingConditionally + } + + public void deleteConfigurationSetting() { + // BEGIN: readme-sample-deleteConfigurationSetting + ConfigurationSetting setting = configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); + ConfigurationSetting deletedSetting = configurationClient.deleteConfigurationSetting("some_key", "some_label"); + // END: readme-sample-deleteConfigurationSetting + } + + public void deleteConfigurationSettingConditionally() { + // BEGIN: readme-sample-deleteConfigurationSettingConditionally + ConfigurationSetting setting = configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); + Response settingResponse = configurationClient.deleteConfigurationSettingWithResponse(setting, true, Context.NONE); + // END: readme-sample-deleteConfigurationSettingConditionally + } + + public void listConfigurationSetting() { + // BEGIN: readme-sample-listConfigurationSetting + String key = "some_key"; + String key2 = "new_key"; + configurationClient.setConfigurationSetting(key, "some_label", "some_value"); + configurationClient.setConfigurationSetting(key2, "new_label", "new_value"); + SettingSelector selector = new SettingSelector().setKeyFilter(key + "," + key2); + PagedIterable settings = configurationClient.listConfigurationSettings(selector); + // END: readme-sample-listConfigurationSetting + } + + public void listRevisions() { + // BEGIN: readme-sample-listRevisions + String key = "revisionKey"; + configurationClient.setConfigurationSetting(key, "some_label", "some_value"); + configurationClient.setConfigurationSetting(key, "new_label", "new_value"); + SettingSelector selector = new SettingSelector().setKeyFilter(key); + PagedIterable settings = configurationClient.listRevisions(selector); + // END: readme-sample-listRevisions + } + + public void setReadOnly() { + // BEGIN: readme-sample-setReadOnly + configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); + ConfigurationSetting setting = configurationClient.setReadOnly("some_key", "some_label", true); + // END: readme-sample-setReadOnly + } + + public void clearReadOnly() { + // BEGIN: readme-sample-clearReadOnly + ConfigurationSetting setting = configurationClient.setReadOnly("some_key", "some_label", false); + // END: readme-sample-clearReadOnly + } + + public void customHeaders() { + // BEGIN: readme-sample-customHeaders + // Add your headers + HttpHeaders headers = new HttpHeaders(); + headers.set("my-header1", "my-header1-value"); + headers.set("my-header2", "my-header2-value"); + headers.set("my-header3", "my-header3-value"); + // Call API by passing headers in Context. + configurationClient.addConfigurationSettingWithResponse( + new ConfigurationSetting().setKey("key").setValue("value"), + new Context(AddHeadersFromContextPolicy.AZURE_REQUEST_HTTP_HEADERS_KEY, headers)); + // Above three HttpHeader will be added in outgoing HttpRequest. + // END: readme-sample-customHeaders + } + + public void createClientWithProxyOption() { + // BEGIN: readme-sample-createClientWithProxyOption + // Proxy options + final String hostname = "{your-host-name}"; + final int port = 447; // your port number + + ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, + new InetSocketAddress(hostname, port)); + HttpClient httpClient = new NettyAsyncHttpClientBuilder() + .proxy(proxyOptions) + .build(); + ConfigurationAsyncClient configurationAsyncClient = new ConfigurationClientBuilder() + .connectionString("{your_connection_string}") + .httpClient(httpClient) + .buildAsyncClient(); + // END: readme-sample-createClientWithProxyOption + } + + public void createFeatureFlagConfigurationSetting() { + // BEGIN: readme-sample-addFeatureFlagConfigurationSetting + String key = "some_key"; + String filterName = "{filter_name}"; // such as "Microsoft.Percentage" + String filterParameterKey = "{filter_parameter_key}"; // "Value" + Object filterParameterValue = 30; // Any value. Could be String, primitive value, or Json Object + FeatureFlagFilter percentageFilter = new FeatureFlagFilter(filterName) + .addParameter(filterParameterKey, filterParameterValue); + FeatureFlagConfigurationSetting featureFlagConfigurationSetting = + new FeatureFlagConfigurationSetting(key, true) + .setClientFilters(Arrays.asList(percentageFilter)); + + FeatureFlagConfigurationSetting setting = (FeatureFlagConfigurationSetting) + configurationClient.addConfigurationSetting(featureFlagConfigurationSetting); + // END: readme-sample-addFeatureFlagConfigurationSetting + } + + public void updateFeatureFlagConfigurationSetting() { + String key = "some_key"; + String filterName = "{filter_name}"; // such as "Microsoft.Percentage" + String filterParameterKey = "{filter_parameter_key}"; // "Value" + Object filterParameterValue = 30; // Any value. Could be String, primitive value, or Json Object + FeatureFlagFilter percentageFilter = new FeatureFlagFilter(filterName) + .addParameter(filterParameterKey, filterParameterValue); + FeatureFlagConfigurationSetting featureFlagConfigurationSetting = + new FeatureFlagConfigurationSetting(key, true) + .setClientFilters(Arrays.asList(percentageFilter)); + + // BEGIN: readme-sample-updateFeatureFlagConfigurationSetting + FeatureFlagConfigurationSetting setting = (FeatureFlagConfigurationSetting) + configurationClient.setConfigurationSetting(featureFlagConfigurationSetting); + // END: readme-sample-updateFeatureFlagConfigurationSetting + } + + public void getFeatureFlagConfigurationSetting() { + String key = "some_key"; + String filterName = "{filter_name}"; // such as "Microsoft.Percentage" + String filterParameterKey = "{filter_parameter_key}"; // "Value" + Object filterParameterValue = 30; // Any value. Could be String, primitive value, or Json Object + FeatureFlagFilter percentageFilter = new FeatureFlagFilter(filterName) + .addParameter(filterParameterKey, filterParameterValue); + FeatureFlagConfigurationSetting featureFlagConfigurationSetting = + new FeatureFlagConfigurationSetting(key, true) + .setClientFilters(Arrays.asList(percentageFilter)); + + // BEGIN: readme-sample-getFeatureFlagConfigurationSetting + FeatureFlagConfigurationSetting setting = (FeatureFlagConfigurationSetting) + configurationClient.getConfigurationSetting(featureFlagConfigurationSetting); + // END: readme-sample-getFeatureFlagConfigurationSetting + } + + public void deleteFeatureFlagConfigurationSetting() { + String key = "some_key"; + String filterName = "{filter_name}"; // such as "Microsoft.Percentage" + String filterParameterKey = "{filter_parameter_key}"; // "Value" + Object filterParameterValue = 30; // Any value. Could be String, primitive value, or Json Object + FeatureFlagFilter percentageFilter = new FeatureFlagFilter(filterName) + .addParameter(filterParameterKey, filterParameterValue); + FeatureFlagConfigurationSetting featureFlagConfigurationSetting = + new FeatureFlagConfigurationSetting(key, true) + .setClientFilters(Arrays.asList(percentageFilter)); + + // BEGIN: readme-sample-deleteFeatureFlagConfigurationSetting + FeatureFlagConfigurationSetting setting = (FeatureFlagConfigurationSetting) + configurationClient.deleteConfigurationSetting(featureFlagConfigurationSetting); + // END: readme-sample-deleteFeatureFlagConfigurationSetting + } + + public void addSecretReferenceConfigurationSetting() { + // BEGIN: readme-sample-addSecretReferenceConfigurationSetting + String key = "{some_key}"; + String keyVaultReference = "{key_vault_reference}"; + + SecretReferenceConfigurationSetting referenceConfigurationSetting = + new SecretReferenceConfigurationSetting(key, keyVaultReference); + + SecretReferenceConfigurationSetting setting = (SecretReferenceConfigurationSetting) + configurationClient.addConfigurationSetting(referenceConfigurationSetting); + // END: readme-sample-addSecretReferenceConfigurationSetting + } + + public void updateSecretReferenceConfigurationSetting() { + String key = "{some_key}"; + String keyVaultReference = "{key_vault_reference}"; + + SecretReferenceConfigurationSetting referenceConfigurationSetting = + new SecretReferenceConfigurationSetting(key, keyVaultReference); + + // BEGIN: readme-sample-updateSecretReferenceConfigurationSetting + SecretReferenceConfigurationSetting setting = (SecretReferenceConfigurationSetting) + configurationClient.setConfigurationSetting(referenceConfigurationSetting); + // END: readme-sample-updateSecretReferenceConfigurationSetting + } + + public void getSecretReferenceConfigurationSetting() { + String key = "{some_key}"; + String keyVaultReference = "{key_vault_reference}"; + + SecretReferenceConfigurationSetting referenceConfigurationSetting = + new SecretReferenceConfigurationSetting(key, keyVaultReference); + + // BEGIN: readme-sample-getSecretReferenceConfigurationSetting + SecretReferenceConfigurationSetting setting = (SecretReferenceConfigurationSetting) + configurationClient.getConfigurationSetting(referenceConfigurationSetting); + // END: readme-sample-getSecretReferenceConfigurationSetting + } + + public void deleteSecretReferenceConfigurationSetting() { + String key = "{some_key}"; + String keyVaultReference = "{key_vault_reference}"; + + SecretReferenceConfigurationSetting referenceConfigurationSetting = + new SecretReferenceConfigurationSetting(key, keyVaultReference); + + // BEGIN: readme-sample-deleteSecretReferenceConfigurationSetting + SecretReferenceConfigurationSetting setting = (SecretReferenceConfigurationSetting) + configurationClient.deleteConfigurationSetting(referenceConfigurationSetting); + // END: readme-sample-deleteSecretReferenceConfigurationSetting + } + + public void enableHttpLogging() { + // BEGIN: readme-sample-enablehttplogging + ConfigurationClient configurationClient = new ConfigurationClientBuilder() + .connectionString(connectionString) + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) + .buildClient(); + // or + DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build(); + ConfigurationClient configurationClientAad = new ConfigurationClientBuilder() + .credential(credential) + .endpoint(endpoint) + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) + .buildClient(); + // END: readme-sample-enablehttplogging + + } + + public void troubleshootingExceptions() { + ConfigurationClient client = new ConfigurationClientBuilder() + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + // BEGIN: readme-sample-troubleshootingExceptions + try { + ConfigurationSetting setting = new ConfigurationSetting().setKey("myKey").setValue("myValue"); + client.getConfigurationSetting(setting); + } catch (HttpResponseException e) { + System.out.println(e.getMessage()); + // Do something with the exception + } + // END: readme-sample-troubleshootingExceptions + + ConfigurationAsyncClient asyncClient = new ConfigurationClientBuilder() + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + // BEGIN: readme-sample-troubleshootingExceptions-async + ConfigurationSetting setting = new ConfigurationSetting().setKey("myKey").setValue("myValue"); + asyncClient.getConfigurationSetting(setting) + .doOnSuccess(ignored -> System.out.println("Success!")) + .doOnError( + error -> error instanceof ResourceNotFoundException, + error -> System.out.println("Exception: 'getConfigurationSetting' could not be performed.")); + // END: readme-sample-troubleshootingExceptions-async + } + + public void createSnapshot() { + // BEGIN: readme-sample-createSnapshot + String snapshotName = "{snapshotName}"; + // Prepare the snapshot filters + List filters = new ArrayList<>(); + // Key Name also supports RegExp but only support prefix end with "*", such as "k*" and is case-sensitive. + filters.add(new ConfigurationSettingsFilter("Test*")); + SyncPoller poller = + configurationClient.beginCreateSnapshot(snapshotName, new ConfigurationSnapshot(filters), Context.NONE); + poller.setPollInterval(Duration.ofSeconds(10)); + poller.waitForCompletion(); + ConfigurationSnapshot snapshot = poller.getFinalResult(); + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + snapshot.getName(), snapshot.getCreatedAt(), snapshot.getStatus()); + // END: readme-sample-createSnapshot + } + + public void getSnapshot() { + // BEGIN: readme-sample-getSnapshot + String snapshotName = "{snapshotName}"; + ConfigurationSnapshot getSnapshot = configurationClient.getSnapshot(snapshotName); + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + getSnapshot.getName(), getSnapshot.getCreatedAt(), getSnapshot.getStatus()); + // END: readme-sample-getSnapshot + } + + public void archiveSnapshot() { + // BEGIN: readme-sample-archiveSnapshot + String snapshotName = "{snapshotName}"; + ConfigurationSnapshot archivedSnapshot = configurationClient.archiveSnapshot(snapshotName); + System.out.printf("Archived snapshot name=%s is created at %s, snapshot status is %s.%n", + archivedSnapshot.getName(), archivedSnapshot.getCreatedAt(), archivedSnapshot.getStatus()); + // END: readme-sample-archiveSnapshot + } + + public void recoverSnapshot() { + // BEGIN: readme-sample-recoverSnapshot + String snapshotName = "{snapshotName}"; + ConfigurationSnapshot recoveredSnapshot = configurationClient.recoverSnapshot(snapshotName); + System.out.printf("Recovered snapshot name=%s is created at %s, snapshot status is %s.%n", + recoveredSnapshot.getName(), recoveredSnapshot.getCreatedAt(), recoveredSnapshot.getStatus()); + // END: readme-sample-recoverSnapshot + } + + public void listSnapshot() { + // BEGIN: readme-sample-getAllSnapshots + String snapshotNameProduct = "{snapshotNameInProduct}"; + SnapshotSelector snapshotSelector = new SnapshotSelector().setNameFilter(snapshotNameProduct); + PagedIterable configurationSnapshots = + configurationClient.listSnapshots(snapshotSelector); + for (ConfigurationSnapshot snapshot : configurationSnapshots) { + System.out.printf("Listed Snapshot name = %s is created at %s, snapshot status is %s.%n", + snapshot.getName(), snapshot.getCreatedAt(), snapshot.getStatus()); + } + // END: readme-sample-getAllSnapshots + } + + public void listSettingInSnapshot() { + // BEGIN: readme-sample-listSettingsInSnapshot + String snapshotNameProduct = "{snapshotNameInProduct}"; + PagedIterable configurationSettings = + configurationClient.listConfigurationSettingsForSnapshot(snapshotNameProduct); + + for (ConfigurationSetting setting : configurationSettings) { + System.out.printf("[ConfigurationSetting in snapshot] Key: %s, Value: %s%n", + setting.getKey(), setting.getValue()); + } + // END: readme-sample-listSettingsInSnapshot + + } + + public void listLabels() { + // BEGIN: readme-sample-listLabels + String labelNameFilter = "{labelNamePrefix}*"; + configurationClient.listLabels(new SettingLabelSelector().setNameFilter(labelNameFilter)) + .forEach(label -> { + System.out.println("label name = " + label.getName()); + }); + // END: readme-sample-listLabels + } + + private void updateConfiguration(ConfigurationSetting setting) { + // do something on the given setting. + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample26/v1/ReadOnlySample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample26/v1/ReadOnlySample.java new file mode 100644 index 000000000000..45e82d78e838 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample26/v1/ReadOnlySample.java @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.ConfigurationSetting; + +/** + * Sample demonstrates how to set and clear read-only a configuration setting. + */ +public class ReadOnlySample { + /** + * Runs the sample algorithm and demonstrates how to set and clear read-only a configuration setting. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Instantiate a client that will be used to call the service. + final ConfigurationClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + + // Name of the key to add to the configuration service. + final String key = "hello"; + final String value = "world"; + + final ConfigurationSetting setting = client.setConfigurationSetting(key, null, value); + // Read-Only + final ConfigurationSetting readOnlySetting = client.setReadOnly(setting.getKey(), setting.getLabel(), true); + System.out.printf("Setting is read-only now, Key: %s, Value: %s", + readOnlySetting.getKey(), readOnlySetting.getValue()); + // Clear Read-Only + final ConfigurationSetting clearedReadOnlySetting = client.setReadOnly(setting.getKey(), setting.getLabel(), false); + System.out.printf("Setting is no longer read-only, Key: %s, Value: %s", + clearedReadOnlySetting.getKey(), clearedReadOnlySetting.getValue()); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample26/v2/ReadOnlySample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample26/v2/ReadOnlySample.java new file mode 100644 index 000000000000..45e82d78e838 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample26/v2/ReadOnlySample.java @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.ConfigurationSetting; + +/** + * Sample demonstrates how to set and clear read-only a configuration setting. + */ +public class ReadOnlySample { + /** + * Runs the sample algorithm and demonstrates how to set and clear read-only a configuration setting. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Instantiate a client that will be used to call the service. + final ConfigurationClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + + // Name of the key to add to the configuration service. + final String key = "hello"; + final String value = "world"; + + final ConfigurationSetting setting = client.setConfigurationSetting(key, null, value); + // Read-Only + final ConfigurationSetting readOnlySetting = client.setReadOnly(setting.getKey(), setting.getLabel(), true); + System.out.printf("Setting is read-only now, Key: %s, Value: %s", + readOnlySetting.getKey(), readOnlySetting.getValue()); + // Clear Read-Only + final ConfigurationSetting clearedReadOnlySetting = client.setReadOnly(setting.getKey(), setting.getLabel(), false); + System.out.printf("Setting is no longer read-only, Key: %s, Value: %s", + clearedReadOnlySetting.getKey(), clearedReadOnlySetting.getValue()); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample27/v1/ReadOnlySampleAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample27/v1/ReadOnlySampleAsync.java new file mode 100644 index 000000000000..312ee8feb558 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample27/v1/ReadOnlySampleAsync.java @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.ConfigurationSetting; + +/** + * Sample demonstrates how to set and clear read-only a configuration setting asynchronously. + */ +public class ReadOnlySampleAsync { + /** + * Runs the sample algorithm and demonstrates how to set and clear read-only a configuration setting asynchronously. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Instantiate a client that will be used to call the service. + final ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + + // Name of the key to add to the configuration service. + final String key = "hello"; + final String value = "world"; + + client.setConfigurationSetting(key, null, value).subscribe( + result -> { + final ConfigurationSetting setting = result; + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + }, + error -> System.err.println("There was an error while adding the setting: " + error), + () -> System.out.printf("Set setting with key=%s and value=%s added or updated.", key, value)); + + // Read-Only + client.setReadOnly(key, value, true).subscribe( + result -> { + final ConfigurationSetting setting = result; + System.out.printf("[Read-Only Setting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + }, + error -> System.err.println("There was an error while making the setting to read-only: " + error), + null + ); + + // Clear Read-Only + client.setReadOnly(key, value, false).subscribe( + result -> { + final ConfigurationSetting setting = result; + System.out.printf("[Cleared Read-Only Setting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + }, + error -> System.err.println("There was an error while making the setting to read-only: " + error), + null + ); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample27/v2/ReadOnlySampleAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample27/v2/ReadOnlySampleAsync.java new file mode 100644 index 000000000000..312ee8feb558 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample27/v2/ReadOnlySampleAsync.java @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.ConfigurationSetting; + +/** + * Sample demonstrates how to set and clear read-only a configuration setting asynchronously. + */ +public class ReadOnlySampleAsync { + /** + * Runs the sample algorithm and demonstrates how to set and clear read-only a configuration setting asynchronously. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Instantiate a client that will be used to call the service. + final ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + + // Name of the key to add to the configuration service. + final String key = "hello"; + final String value = "world"; + + client.setConfigurationSetting(key, null, value).subscribe( + result -> { + final ConfigurationSetting setting = result; + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + }, + error -> System.err.println("There was an error while adding the setting: " + error), + () -> System.out.printf("Set setting with key=%s and value=%s added or updated.", key, value)); + + // Read-Only + client.setReadOnly(key, value, true).subscribe( + result -> { + final ConfigurationSetting setting = result; + System.out.printf("[Read-Only Setting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + }, + error -> System.err.println("There was an error while making the setting to read-only: " + error), + null + ); + + // Clear Read-Only + client.setReadOnly(key, value, false).subscribe( + result -> { + final ConfigurationSetting setting = result; + System.out.printf("[Cleared Read-Only Setting] Key: %s, Value: %s", setting.getKey(), setting.getValue()); + }, + error -> System.err.println("There was an error while making the setting to read-only: " + error), + null + ); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample28/v1/ReadRevisionHistory.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample28/v1/ReadRevisionHistory.java new file mode 100644 index 000000000000..754b51fa0727 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample28/v1/ReadRevisionHistory.java @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; +import reactor.core.publisher.Flux; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * Sample demonstrates how to read configuration setting revision history. + */ +public class ReadRevisionHistory { + /** + * Runs the sample algorithm and demonstrates how to read configuration setting revision history. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Instantiate a client that will be used to call the service. + final ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + + final String key = "hello"; + + // Adding a couple of settings and then fetching all the settings in our repository. + final List settings = Flux.concat( + client.addConfigurationSetting(key, null, "world"), + client.setConfigurationSetting(key, null, "newValue")) + .then(client.listRevisions(new SettingSelector().setKeyFilter(key)).collectList()) + .block(); + + // Cleaning up after ourselves by deleting the values. + final Stream stream = settings == null ? Stream.empty() : settings.stream(); + Flux.merge(stream.map(setting -> client.deleteConfigurationSettingWithResponse(setting, false)) + .collect(Collectors.toList())).blockLast(); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample28/v2/ReadRevisionHistory.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample28/v2/ReadRevisionHistory.java new file mode 100644 index 000000000000..754b51fa0727 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample28/v2/ReadRevisionHistory.java @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; +import reactor.core.publisher.Flux; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * Sample demonstrates how to read configuration setting revision history. + */ +public class ReadRevisionHistory { + /** + * Runs the sample algorithm and demonstrates how to read configuration setting revision history. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Instantiate a client that will be used to call the service. + final ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + + final String key = "hello"; + + // Adding a couple of settings and then fetching all the settings in our repository. + final List settings = Flux.concat( + client.addConfigurationSetting(key, null, "world"), + client.setConfigurationSetting(key, null, "newValue")) + .then(client.listRevisions(new SettingSelector().setKeyFilter(key)).collectList()) + .block(); + + // Cleaning up after ourselves by deleting the values. + final Stream stream = settings == null ? Stream.empty() : settings.stream(); + Flux.merge(stream.map(setting -> client.deleteConfigurationSettingWithResponse(setting, false)) + .collect(Collectors.toList())).blockLast(); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample29/v1/ReadRevisionHistoryAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample29/v1/ReadRevisionHistoryAsync.java new file mode 100644 index 000000000000..41e06abbff16 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample29/v1/ReadRevisionHistoryAsync.java @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; +import reactor.core.publisher.Flux; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * Sample demonstrates how to read configuration setting revision history asynchronously. + */ +public class ReadRevisionHistoryAsync { + /** + * Runs the sample algorithm and demonstrates how to read configuration setting revision history asynchronously. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Instantiate a client that will be used to call the service. + final ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + + final String key = "hello"; + + // Adding a couple of settings and then fetching all the settings in our repository. + final List settings = Flux.concat( + client.addConfigurationSetting(key, null, "world"), + client.setConfigurationSetting(key, null, "newValue")) + .then(client.listRevisions(new SettingSelector().setKeyFilter(key)).collectList()) + .block(); + + // Cleaning up after ourselves by deleting the values. + final Stream stream = settings == null ? Stream.empty() : settings.stream(); + Flux.merge(stream.map(setting -> client.deleteConfigurationSettingWithResponse(setting, false)) + .collect(Collectors.toList())).blockLast(); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample29/v2/ReadRevisionHistoryAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample29/v2/ReadRevisionHistoryAsync.java new file mode 100644 index 000000000000..41e06abbff16 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample29/v2/ReadRevisionHistoryAsync.java @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; +import reactor.core.publisher.Flux; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * Sample demonstrates how to read configuration setting revision history asynchronously. + */ +public class ReadRevisionHistoryAsync { + /** + * Runs the sample algorithm and demonstrates how to read configuration setting revision history asynchronously. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Instantiate a client that will be used to call the service. + final ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + + final String key = "hello"; + + // Adding a couple of settings and then fetching all the settings in our repository. + final List settings = Flux.concat( + client.addConfigurationSetting(key, null, "world"), + client.setConfigurationSetting(key, null, "newValue")) + .then(client.listRevisions(new SettingSelector().setKeyFilter(key)).collectList()) + .block(); + + // Cleaning up after ourselves by deleting the values. + final Stream stream = settings == null ? Stream.empty() : settings.stream(); + Flux.merge(stream.map(setting -> client.deleteConfigurationSettingWithResponse(setting, false)) + .collect(Collectors.toList())).blockLast(); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample3/v1/ConditionalRequestAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample3/v1/ConditionalRequestAsync.java new file mode 100644 index 000000000000..135453dfbea8 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample3/v1/ConditionalRequestAsync.java @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.ConfigurationSetting; + +import java.util.concurrent.TimeUnit; + +/** + * Sample demonstrates how to add, get, and delete a configuration setting by conditional request asynchronously. + */ +public class ConditionalRequestAsync { + /** + * Runs the sample algorithm and demonstrates how to add, get, and delete a configuration setting by conditional + * request asynchronously + * @param args Unused. Arguments to the program. + * @throws InterruptedException when a thread is waiting, sleeping, or otherwise occupied, + * and the thread is interrupted, either before or during the activity. + */ + public static void main(String[] args) throws InterruptedException { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Instantiate a client that will be used to call the service. + final ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + + ConfigurationSetting setting = new ConfigurationSetting().setKey("key").setLabel("label").setValue("value"); + + // If you want to conditionally update the setting, set `ifUnchanged` to true. If the ETag of the + // given setting matches the one in the service, then the setting is updated. Otherwise, it is + // not updated. + // If the given setting is not exist in the service, the setting will be added to the service. + client.setConfigurationSettingWithResponse(setting, true).subscribe( + result -> { + final ConfigurationSetting output = result.getValue(); + final int statusCode = result.getStatusCode(); + System.out.printf("Status code: %s, Key: %s, Value: %s", statusCode, output.getKey(), + output.getValue()); + }, + error -> System.err.println("There was an error while setting the setting: " + error)); + + TimeUnit.MILLISECONDS.sleep(1000); + + // If you want to conditionally retrieve the setting, set `ifChanged` to true. If the ETag of the + // given setting matches the one in the service, then 304 status code with null value returned in the response. + // Otherwise, a setting with new ETag returned, which is the latest setting retrieved from the service. + client.getConfigurationSettingWithResponse(setting, null, true).subscribe( + result -> { + final ConfigurationSetting output = result.getValue(); + final int statusCode = result.getStatusCode(); + System.out.printf("Status code: %s, Key: %s, Value: %s", statusCode, output.getKey(), + output.getValue()); + }, + error -> System.err.println("There was an error while getting the setting: " + error)); + + TimeUnit.MILLISECONDS.sleep(1000); + + // If you want to conditionally delete the setting, set `ifUnchanged` to true. If the ETag of the + // given setting matches the one in the service, then the setting is deleted. Otherwise, it is + // not deleted. + client.deleteConfigurationSettingWithResponse(setting, true).subscribe( + result -> { + final ConfigurationSetting output = result.getValue(); + final int statusCode = result.getStatusCode(); + System.out.printf("Status code: %s, Key: %s, Value: %s", statusCode, output.getKey(), + output.getValue()); + }, + error -> System.err.println("There was an error while deleting the setting: " + error)); + } + + +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample3/v2/ConditionalRequestAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample3/v2/ConditionalRequestAsync.java new file mode 100644 index 000000000000..135453dfbea8 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample3/v2/ConditionalRequestAsync.java @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.ConfigurationSetting; + +import java.util.concurrent.TimeUnit; + +/** + * Sample demonstrates how to add, get, and delete a configuration setting by conditional request asynchronously. + */ +public class ConditionalRequestAsync { + /** + * Runs the sample algorithm and demonstrates how to add, get, and delete a configuration setting by conditional + * request asynchronously + * @param args Unused. Arguments to the program. + * @throws InterruptedException when a thread is waiting, sleeping, or otherwise occupied, + * and the thread is interrupted, either before or during the activity. + */ + public static void main(String[] args) throws InterruptedException { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Instantiate a client that will be used to call the service. + final ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + + ConfigurationSetting setting = new ConfigurationSetting().setKey("key").setLabel("label").setValue("value"); + + // If you want to conditionally update the setting, set `ifUnchanged` to true. If the ETag of the + // given setting matches the one in the service, then the setting is updated. Otherwise, it is + // not updated. + // If the given setting is not exist in the service, the setting will be added to the service. + client.setConfigurationSettingWithResponse(setting, true).subscribe( + result -> { + final ConfigurationSetting output = result.getValue(); + final int statusCode = result.getStatusCode(); + System.out.printf("Status code: %s, Key: %s, Value: %s", statusCode, output.getKey(), + output.getValue()); + }, + error -> System.err.println("There was an error while setting the setting: " + error)); + + TimeUnit.MILLISECONDS.sleep(1000); + + // If you want to conditionally retrieve the setting, set `ifChanged` to true. If the ETag of the + // given setting matches the one in the service, then 304 status code with null value returned in the response. + // Otherwise, a setting with new ETag returned, which is the latest setting retrieved from the service. + client.getConfigurationSettingWithResponse(setting, null, true).subscribe( + result -> { + final ConfigurationSetting output = result.getValue(); + final int statusCode = result.getStatusCode(); + System.out.printf("Status code: %s, Key: %s, Value: %s", statusCode, output.getKey(), + output.getValue()); + }, + error -> System.err.println("There was an error while getting the setting: " + error)); + + TimeUnit.MILLISECONDS.sleep(1000); + + // If you want to conditionally delete the setting, set `ifUnchanged` to true. If the ETag of the + // given setting matches the one in the service, then the setting is deleted. Otherwise, it is + // not deleted. + client.deleteConfigurationSettingWithResponse(setting, true).subscribe( + result -> { + final ConfigurationSetting output = result.getValue(); + final int statusCode = result.getStatusCode(); + System.out.printf("Status code: %s, Key: %s, Value: %s", statusCode, output.getKey(), + output.getValue()); + }, + error -> System.err.println("There was an error while deleting the setting: " + error)); + } + + +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample30/v1/ReadRevisionHistoryWIthTagsFilter.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample30/v1/ReadRevisionHistoryWIthTagsFilter.java new file mode 100644 index 000000000000..b13bcecf5e13 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample30/v1/ReadRevisionHistoryWIthTagsFilter.java @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.Configuration; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; + +import javax.net.ssl.SSLException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static com.azure.data.appconfiguration.implementation.Utility.getTagsFilterInString; + +/** + * Sample demonstrates how to list revisions with tags filter. + */ +public class ReadRevisionHistoryWIthTagsFilter { + + /** + * Runs the sample algorithm and demonstrates how to list revisions with tags filter. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) throws SSLException { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to the "Access Keys" page under the "Settings" section. + String connectionString = Configuration.getGlobalConfiguration().get("AZURE_APPCONFIG_CONNECTION_STRING"); + + // Instantiate a client that will be used to call the service. + ConfigurationClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + + Map tags = new HashMap<>(); + tags.put("release", "first"); + Map tags2 = new HashMap<>(); + tags2.put("release", "first"); + tags2.put("release2", "second"); + + String sameKey = "sameKey"; + ConfigurationSetting setting1 = client.setConfigurationSetting(new ConfigurationSetting().setKey(sameKey).setValue("value1").setTags(tags)); + System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting1.getKey(), setting1.getValue(), setting1.getTags()); + ConfigurationSetting setting2 = client.setConfigurationSetting(new ConfigurationSetting().setKey(sameKey).setValue("value2").setTags(tags2)); + System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting2.getKey(), setting2.getValue(), setting2.getTags()); + ConfigurationSetting setting3 = client.setConfigurationSetting(new ConfigurationSetting().setKey(sameKey).setValue("value3")); + System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting3.getKey(), setting3.getValue(), setting3.getTags()); + + List tagsFilterInString = getTagsFilterInString(tags2); + System.out.println("List revisions with tags filter = " + tagsFilterInString); + PagedIterable configurationSettings = client.listRevisions( + new SettingSelector().setTagsFilter(tagsFilterInString)); + configurationSettings.forEach(setting -> System.out.printf( + "\tKey: %s, Value: %s, Tags: %s%n", setting.getKey(), setting.getValue(), setting.getTags())); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample30/v2/ReadRevisionHistoryWIthTagsFilter.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample30/v2/ReadRevisionHistoryWIthTagsFilter.java new file mode 100644 index 000000000000..b13bcecf5e13 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample30/v2/ReadRevisionHistoryWIthTagsFilter.java @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.Configuration; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; + +import javax.net.ssl.SSLException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static com.azure.data.appconfiguration.implementation.Utility.getTagsFilterInString; + +/** + * Sample demonstrates how to list revisions with tags filter. + */ +public class ReadRevisionHistoryWIthTagsFilter { + + /** + * Runs the sample algorithm and demonstrates how to list revisions with tags filter. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) throws SSLException { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to the "Access Keys" page under the "Settings" section. + String connectionString = Configuration.getGlobalConfiguration().get("AZURE_APPCONFIG_CONNECTION_STRING"); + + // Instantiate a client that will be used to call the service. + ConfigurationClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + + Map tags = new HashMap<>(); + tags.put("release", "first"); + Map tags2 = new HashMap<>(); + tags2.put("release", "first"); + tags2.put("release2", "second"); + + String sameKey = "sameKey"; + ConfigurationSetting setting1 = client.setConfigurationSetting(new ConfigurationSetting().setKey(sameKey).setValue("value1").setTags(tags)); + System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting1.getKey(), setting1.getValue(), setting1.getTags()); + ConfigurationSetting setting2 = client.setConfigurationSetting(new ConfigurationSetting().setKey(sameKey).setValue("value2").setTags(tags2)); + System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting2.getKey(), setting2.getValue(), setting2.getTags()); + ConfigurationSetting setting3 = client.setConfigurationSetting(new ConfigurationSetting().setKey(sameKey).setValue("value3")); + System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting3.getKey(), setting3.getValue(), setting3.getTags()); + + List tagsFilterInString = getTagsFilterInString(tags2); + System.out.println("List revisions with tags filter = " + tagsFilterInString); + PagedIterable configurationSettings = client.listRevisions( + new SettingSelector().setTagsFilter(tagsFilterInString)); + configurationSettings.forEach(setting -> System.out.printf( + "\tKey: %s, Value: %s, Tags: %s%n", setting.getKey(), setting.getValue(), setting.getTags())); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample31/v1/ReadRevisionHistoryWithTagsFilterAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample31/v1/ReadRevisionHistoryWithTagsFilterAsync.java new file mode 100644 index 000000000000..10e81f1271ad --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample31/v1/ReadRevisionHistoryWithTagsFilterAsync.java @@ -0,0 +1,67 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.util.Configuration; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import static com.azure.data.appconfiguration.implementation.Utility.getTagsFilterInString; + +/** + * Sample demonstrates how to list revisions with tags filter asynchronously. + */ +public class ReadRevisionHistoryWithTagsFilterAsync { + /** + * Runs the sample algorithm and demonstrates how to list revisions with tags filter asynchronously. + * + * @param args Unused. Arguments to the program. + * @throws InterruptedException when a thread is waiting, sleeping, or otherwise occupied, + * and the thread is interrupted, either before or during the activity. + */ + public static void main(String[] args) throws InterruptedException { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to the "Access Keys" page under the "Settings" section. + String connectionString = Configuration.getGlobalConfiguration().get("AZURE_APPCONFIG_CONNECTION_STRING"); + + // Instantiate a client that will be used to call the service. + ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + + Map tags = new HashMap<>(); + tags.put("release", "first"); + Map tags2 = new HashMap<>(); + tags2.put("release", "first"); + tags2.put("release2", "second"); + + String sameKey = "sameKey"; + client.setConfigurationSetting(new ConfigurationSetting().setKey(sameKey).setValue("value1").setTags(tags)) + .subscribe(setting -> System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting.getKey(), + setting.getValue(), setting.getTags())); + TimeUnit.MILLISECONDS.sleep(1000); + + client.setConfigurationSetting(new ConfigurationSetting().setKey(sameKey).setValue("value2").setTags(tags2)) + .subscribe(setting -> System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting.getKey(), + setting.getValue(), setting.getTags())); + TimeUnit.MILLISECONDS.sleep(1000); + + client.setConfigurationSetting(new ConfigurationSetting().setKey(sameKey).setValue("value3")) + .subscribe(setting -> System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting.getKey(), + setting.getValue(), setting.getTags())); + TimeUnit.MILLISECONDS.sleep(1000); + + List tagsFilterInString = getTagsFilterInString(tags2); + System.out.println("List revisions with tags filter = " + tagsFilterInString); + client.listRevisions(new SettingSelector().setTagsFilter(tagsFilterInString)).subscribe( + setting -> System.out.printf("\tKey: %s, Value: %s, Tags: %s%n", + setting.getKey(), setting.getValue(), setting.getTags())); + TimeUnit.MILLISECONDS.sleep(4000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample31/v2/ReadRevisionHistoryWithTagsFilterAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample31/v2/ReadRevisionHistoryWithTagsFilterAsync.java new file mode 100644 index 000000000000..10e81f1271ad --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample31/v2/ReadRevisionHistoryWithTagsFilterAsync.java @@ -0,0 +1,67 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.util.Configuration; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import static com.azure.data.appconfiguration.implementation.Utility.getTagsFilterInString; + +/** + * Sample demonstrates how to list revisions with tags filter asynchronously. + */ +public class ReadRevisionHistoryWithTagsFilterAsync { + /** + * Runs the sample algorithm and demonstrates how to list revisions with tags filter asynchronously. + * + * @param args Unused. Arguments to the program. + * @throws InterruptedException when a thread is waiting, sleeping, or otherwise occupied, + * and the thread is interrupted, either before or during the activity. + */ + public static void main(String[] args) throws InterruptedException { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to the "Access Keys" page under the "Settings" section. + String connectionString = Configuration.getGlobalConfiguration().get("AZURE_APPCONFIG_CONNECTION_STRING"); + + // Instantiate a client that will be used to call the service. + ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + + Map tags = new HashMap<>(); + tags.put("release", "first"); + Map tags2 = new HashMap<>(); + tags2.put("release", "first"); + tags2.put("release2", "second"); + + String sameKey = "sameKey"; + client.setConfigurationSetting(new ConfigurationSetting().setKey(sameKey).setValue("value1").setTags(tags)) + .subscribe(setting -> System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting.getKey(), + setting.getValue(), setting.getTags())); + TimeUnit.MILLISECONDS.sleep(1000); + + client.setConfigurationSetting(new ConfigurationSetting().setKey(sameKey).setValue("value2").setTags(tags2)) + .subscribe(setting -> System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting.getKey(), + setting.getValue(), setting.getTags())); + TimeUnit.MILLISECONDS.sleep(1000); + + client.setConfigurationSetting(new ConfigurationSetting().setKey(sameKey).setValue("value3")) + .subscribe(setting -> System.out.printf("Key: %s, Value: %s, Tags: %s%n", setting.getKey(), + setting.getValue(), setting.getTags())); + TimeUnit.MILLISECONDS.sleep(1000); + + List tagsFilterInString = getTagsFilterInString(tags2); + System.out.println("List revisions with tags filter = " + tagsFilterInString); + client.listRevisions(new SettingSelector().setTagsFilter(tagsFilterInString)).subscribe( + setting -> System.out.printf("\tKey: %s, Value: %s, Tags: %s%n", + setting.getKey(), setting.getValue(), setting.getTags())); + TimeUnit.MILLISECONDS.sleep(4000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample32/v1/SecretReferenceConfigurationSettingSample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample32/v1/SecretReferenceConfigurationSettingSample.java new file mode 100644 index 000000000000..62e05464111b --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample32/v1/SecretReferenceConfigurationSettingSample.java @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.SecretReferenceConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; + +/** + * Sample demonstrates how to add, get, list, and delete a secret reference configuration setting. + */ +public class SecretReferenceConfigurationSettingSample { + /** + * Runs the sample algorithm and demonstrates how to add, get, list, and delete a secret reference configuration + * setting. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + final ConfigurationClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + + // Name of the key to add to the configuration service. + final String key = "hello"; + final String secretIdValue = "{the-keyVault-secret-id-uri}"; + + System.out.println("Beginning of synchronous sample..."); + + SecretReferenceConfigurationSetting referenceConfigurationSetting = + new SecretReferenceConfigurationSetting(key, secretIdValue); + + // setConfigurationSetting adds or updates a setting to Azure App Configuration store. Alternatively, you can + // call addConfigurationSetting which only succeeds if the setting does not exist in the store. Or, + // you can call setConfigurationSetting to update a setting that is already present in the store. + System.out.println("[Set-SecretReferenceConfigurationSetting]"); + SecretReferenceConfigurationSetting setting = (SecretReferenceConfigurationSetting) client.setConfigurationSetting(referenceConfigurationSetting); + printSecretReferenceConfigurationSetting(setting); + + System.out.println("[Get-SecretReferenceConfigurationSetting]"); + setting = (SecretReferenceConfigurationSetting) client.getConfigurationSetting(setting); + printSecretReferenceConfigurationSetting(setting); + + System.out.println("[List-SecretReferenceConfigurationSetting]"); + final PagedIterable configurationSettings = client.listConfigurationSettings(new SettingSelector()); + for (ConfigurationSetting configurationSetting : configurationSettings) { + if (configurationSetting instanceof SecretReferenceConfigurationSetting) { + System.out.println("-Listing-SecretReferenceConfigurationSetting"); + printSecretReferenceConfigurationSetting((SecretReferenceConfigurationSetting) configurationSetting); + } else { + System.out.println("-Listing-non-SecretReferenceConfigurationSetting"); + System.out.printf("Key: %s, Value: %s%n", configurationSetting.getKey(), configurationSetting.getValue()); + } + } + + System.out.println("[Delete-SecretReferenceConfigurationSetting"); + setting = (SecretReferenceConfigurationSetting) client.deleteConfigurationSetting(setting); + printSecretReferenceConfigurationSetting(setting); + + System.out.println("End of synchronous sample."); + } + + private static void printSecretReferenceConfigurationSetting(SecretReferenceConfigurationSetting setting) { + System.out.printf("Key: %s, Secret ID: %s, Content Type: %s, Value: %s%n", setting.getKey(), + setting.getSecretId(), setting.getContentType(), setting.getValue()); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample32/v2/SecretReferenceConfigurationSettingSample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample32/v2/SecretReferenceConfigurationSettingSample.java new file mode 100644 index 000000000000..62e05464111b --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample32/v2/SecretReferenceConfigurationSettingSample.java @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.SecretReferenceConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; + +/** + * Sample demonstrates how to add, get, list, and delete a secret reference configuration setting. + */ +public class SecretReferenceConfigurationSettingSample { + /** + * Runs the sample algorithm and demonstrates how to add, get, list, and delete a secret reference configuration + * setting. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + final ConfigurationClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + + // Name of the key to add to the configuration service. + final String key = "hello"; + final String secretIdValue = "{the-keyVault-secret-id-uri}"; + + System.out.println("Beginning of synchronous sample..."); + + SecretReferenceConfigurationSetting referenceConfigurationSetting = + new SecretReferenceConfigurationSetting(key, secretIdValue); + + // setConfigurationSetting adds or updates a setting to Azure App Configuration store. Alternatively, you can + // call addConfigurationSetting which only succeeds if the setting does not exist in the store. Or, + // you can call setConfigurationSetting to update a setting that is already present in the store. + System.out.println("[Set-SecretReferenceConfigurationSetting]"); + SecretReferenceConfigurationSetting setting = (SecretReferenceConfigurationSetting) client.setConfigurationSetting(referenceConfigurationSetting); + printSecretReferenceConfigurationSetting(setting); + + System.out.println("[Get-SecretReferenceConfigurationSetting]"); + setting = (SecretReferenceConfigurationSetting) client.getConfigurationSetting(setting); + printSecretReferenceConfigurationSetting(setting); + + System.out.println("[List-SecretReferenceConfigurationSetting]"); + final PagedIterable configurationSettings = client.listConfigurationSettings(new SettingSelector()); + for (ConfigurationSetting configurationSetting : configurationSettings) { + if (configurationSetting instanceof SecretReferenceConfigurationSetting) { + System.out.println("-Listing-SecretReferenceConfigurationSetting"); + printSecretReferenceConfigurationSetting((SecretReferenceConfigurationSetting) configurationSetting); + } else { + System.out.println("-Listing-non-SecretReferenceConfigurationSetting"); + System.out.printf("Key: %s, Value: %s%n", configurationSetting.getKey(), configurationSetting.getValue()); + } + } + + System.out.println("[Delete-SecretReferenceConfigurationSetting"); + setting = (SecretReferenceConfigurationSetting) client.deleteConfigurationSetting(setting); + printSecretReferenceConfigurationSetting(setting); + + System.out.println("End of synchronous sample."); + } + + private static void printSecretReferenceConfigurationSetting(SecretReferenceConfigurationSetting setting) { + System.out.printf("Key: %s, Secret ID: %s, Content Type: %s, Value: %s%n", setting.getKey(), + setting.getSecretId(), setting.getContentType(), setting.getValue()); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample33/v1/SecretReferenceConfigurationSettingSampleAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample33/v1/SecretReferenceConfigurationSettingSampleAsync.java new file mode 100644 index 000000000000..613551fc6356 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample33/v1/SecretReferenceConfigurationSettingSampleAsync.java @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.SecretReferenceConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; + +import java.util.concurrent.TimeUnit; + +/** + * Sample demonstrates how to add, get, list, and delete a secret reference configuration setting asynchronous. + */ +public class SecretReferenceConfigurationSettingSampleAsync { + /** + * Runs the sample algorithm and demonstrates how to add, get, list, and delete a secret reference configuration + * setting asynchronous. + * + * @param args Unused. Arguments to the program. + * @throws InterruptedException when a thread is waiting, sleeping, or otherwise occupied, + * and the thread is interrupted, either before or during the activity. + */ + public static void main(String[] args) throws InterruptedException { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Asynchronous sample + // Instantiate a client that will be used to call the service. + final ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + + // Name of the key to add to the configuration service. + final String key = "hello"; + final String secretIdValue = "{the-keyVault-secret-id-uri}"; + + System.out.println("Beginning of asynchronous sample..."); + + SecretReferenceConfigurationSetting referenceConfigurationSetting = + new SecretReferenceConfigurationSetting(key, secretIdValue); + + // setConfigurationSetting adds or updates a setting to Azure App Configuration store. Alternatively, you can + // call addConfigurationSetting which only succeeds if the setting does not exist in the store. Or, + // you can call setConfigurationSetting to update a setting that is already present in the store. + + // We subscribe and wait for the service call to complete then print out the contents of our newly added setting. + // If an error occurs, we print out that error. + System.out.println("[Set-SecretReferenceConfigurationSetting]"); + client.setConfigurationSetting(referenceConfigurationSetting).subscribe( + result -> printSecretReferenceConfigurationSetting((SecretReferenceConfigurationSetting) result), + error -> System.err.println("There was an error adding the setting: " + error), + () -> System.out.println("Set setting finished")); + TimeUnit.MILLISECONDS.sleep(1000); + + System.out.println("[Get-SecretReferenceConfigurationSetting]"); + client.getConfigurationSetting(referenceConfigurationSetting).subscribe( + result -> printSecretReferenceConfigurationSetting((SecretReferenceConfigurationSetting) result), + error -> System.err.println("There was an error getting the setting: " + error), + () -> System.out.println("Get setting finished")); + TimeUnit.MILLISECONDS.sleep(1000); + + System.out.println("[List-SecretReferenceConfigurationSetting]"); + client.listConfigurationSettings(new SettingSelector()).subscribe( + result -> { + if (result instanceof SecretReferenceConfigurationSetting) { + System.out.println("-Listing-SecretReferenceConfigurationSetting"); + printSecretReferenceConfigurationSetting((SecretReferenceConfigurationSetting) result); + } else { + System.out.println("-Listing-non-SecretReferenceConfigurationSetting"); + System.out.printf("Key: %s, Value: %s%n", result.getKey(), result.getValue()); + } + }, + error -> System.err.println("There was an error adding the setting: " + error), + () -> System.out.println("List settings finished")); + TimeUnit.MILLISECONDS.sleep(1000); + + System.out.println("[Delete-SecretReferenceConfigurationSetting"); + client.getConfigurationSetting(referenceConfigurationSetting).subscribe( + result -> printSecretReferenceConfigurationSetting((SecretReferenceConfigurationSetting) result), + error -> System.err.println("There was an error getting the setting: " + error), + () -> System.out.println("Delete setting finished")); + TimeUnit.MILLISECONDS.sleep(1000); + + System.out.println("End of asynchronous sample."); + } + + private static void printSecretReferenceConfigurationSetting(SecretReferenceConfigurationSetting setting) { + System.out.printf("Key: %s, Secret ID: %s, Content Type: %s, Value: %s%n", setting.getKey(), + setting.getSecretId(), setting.getContentType(), setting.getValue()); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample33/v2/SecretReferenceConfigurationSettingSampleAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample33/v2/SecretReferenceConfigurationSettingSampleAsync.java new file mode 100644 index 000000000000..613551fc6356 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample33/v2/SecretReferenceConfigurationSettingSampleAsync.java @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.SecretReferenceConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; + +import java.util.concurrent.TimeUnit; + +/** + * Sample demonstrates how to add, get, list, and delete a secret reference configuration setting asynchronous. + */ +public class SecretReferenceConfigurationSettingSampleAsync { + /** + * Runs the sample algorithm and demonstrates how to add, get, list, and delete a secret reference configuration + * setting asynchronous. + * + * @param args Unused. Arguments to the program. + * @throws InterruptedException when a thread is waiting, sleeping, or otherwise occupied, + * and the thread is interrupted, either before or during the activity. + */ + public static void main(String[] args) throws InterruptedException { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Asynchronous sample + // Instantiate a client that will be used to call the service. + final ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + + // Name of the key to add to the configuration service. + final String key = "hello"; + final String secretIdValue = "{the-keyVault-secret-id-uri}"; + + System.out.println("Beginning of asynchronous sample..."); + + SecretReferenceConfigurationSetting referenceConfigurationSetting = + new SecretReferenceConfigurationSetting(key, secretIdValue); + + // setConfigurationSetting adds or updates a setting to Azure App Configuration store. Alternatively, you can + // call addConfigurationSetting which only succeeds if the setting does not exist in the store. Or, + // you can call setConfigurationSetting to update a setting that is already present in the store. + + // We subscribe and wait for the service call to complete then print out the contents of our newly added setting. + // If an error occurs, we print out that error. + System.out.println("[Set-SecretReferenceConfigurationSetting]"); + client.setConfigurationSetting(referenceConfigurationSetting).subscribe( + result -> printSecretReferenceConfigurationSetting((SecretReferenceConfigurationSetting) result), + error -> System.err.println("There was an error adding the setting: " + error), + () -> System.out.println("Set setting finished")); + TimeUnit.MILLISECONDS.sleep(1000); + + System.out.println("[Get-SecretReferenceConfigurationSetting]"); + client.getConfigurationSetting(referenceConfigurationSetting).subscribe( + result -> printSecretReferenceConfigurationSetting((SecretReferenceConfigurationSetting) result), + error -> System.err.println("There was an error getting the setting: " + error), + () -> System.out.println("Get setting finished")); + TimeUnit.MILLISECONDS.sleep(1000); + + System.out.println("[List-SecretReferenceConfigurationSetting]"); + client.listConfigurationSettings(new SettingSelector()).subscribe( + result -> { + if (result instanceof SecretReferenceConfigurationSetting) { + System.out.println("-Listing-SecretReferenceConfigurationSetting"); + printSecretReferenceConfigurationSetting((SecretReferenceConfigurationSetting) result); + } else { + System.out.println("-Listing-non-SecretReferenceConfigurationSetting"); + System.out.printf("Key: %s, Value: %s%n", result.getKey(), result.getValue()); + } + }, + error -> System.err.println("There was an error adding the setting: " + error), + () -> System.out.println("List settings finished")); + TimeUnit.MILLISECONDS.sleep(1000); + + System.out.println("[Delete-SecretReferenceConfigurationSetting"); + client.getConfigurationSetting(referenceConfigurationSetting).subscribe( + result -> printSecretReferenceConfigurationSetting((SecretReferenceConfigurationSetting) result), + error -> System.err.println("There was an error getting the setting: " + error), + () -> System.out.println("Delete setting finished")); + TimeUnit.MILLISECONDS.sleep(1000); + + System.out.println("End of asynchronous sample."); + } + + private static void printSecretReferenceConfigurationSetting(SecretReferenceConfigurationSetting setting) { + System.out.printf("Key: %s, Secret ID: %s, Content Type: %s, Value: %s%n", setting.getKey(), + setting.getSecretId(), setting.getContentType(), setting.getValue()); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample34/v1/WatchFeature.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample34/v1/WatchFeature.java new file mode 100644 index 000000000000..11f1061af724 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample34/v1/WatchFeature.java @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.ConfigurationSetting; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class WatchFeature { + /** + * Runs the sample algorithm and demonstrates how to read configuration setting revision history. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Instantiate a client that will be used to call the service. + ConfigurationClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + + // Prepare a list of watching settings and update one same setting value to the service. + String prodDBConnectionKey = "prodDBConnection"; + String prodDBConnectionLabel = "prodLabel"; + + // Assume we have a list of watching setting that stored somewhere. + List watchingSettings = Arrays.asList( + client.addConfigurationSetting(prodDBConnectionKey, prodDBConnectionLabel, "prodValue"), + client.addConfigurationSetting("stageDBConnection", "stageLabel", "stageValue") + ); + + System.out.println("Watching settings:"); + for (ConfigurationSetting setting : watchingSettings) { + System.out.printf("\tkey=%s, label=%s, value=%s, ETag=%s.%n", + setting.getKey(), setting.getLabel(), setting.getValue(), setting.getETag()); + } + + // One of the watching settings is been updated by someone in other place. + ConfigurationSetting updatedSetting = client.setConfigurationSetting( + prodDBConnectionKey, prodDBConnectionLabel, "updatedProdValue"); + System.out.println("Updated settings:"); + System.out.printf("\tkey=%s, label=%s, value=%s, ETag=%s.%n", + updatedSetting.getKey(), updatedSetting.getLabel(), updatedSetting.getValue(), updatedSetting.getETag()); + + // Updates the watching settings if needed, and only returns a list of updated settings. + List refreshedSettings = refresh(client, watchingSettings); + + System.out.println("Refreshed settings:"); + for (ConfigurationSetting setting : refreshedSettings) { + System.out.printf("\tkey=%s, label=%s, value=%s, ETag=%s.%n", + setting.getKey(), setting.getLabel(), setting.getValue(), setting.getETag()); + } + + // Cleaning up after ourselves by deleting the values. + System.out.println("Deleting settings:"); + watchingSettings.forEach(setting -> { + client.deleteConfigurationSetting(setting.getKey(), setting.getLabel()); + System.out.printf("\tkey: %s, value: %s.%n", setting.getKey(), setting.getValue()); + }); + } + + /** + * A refresh method that runs every day to update settings and returns a updated settings. + * + * @param client a configuration client. + * @param watchSettings a list of settings in the watching store. + * + * @return a list of updated settings that doesn't match previous ETag value. + */ + private static List refresh(ConfigurationClient client, + List watchSettings) { + return watchSettings + .stream() + .filter(setting -> { + ConfigurationSetting retrievedSetting = client.getConfigurationSetting(setting.getKey(), + setting.getLabel()); + String latestETag = retrievedSetting.getETag(); + String watchingETag = setting.getETag(); + if (!latestETag.equals(watchingETag)) { + System.out.printf( + "Some keys in watching key store matching the key [%s] and label [%s] is updated, " + + "preview ETag value [%s] not equals to current value [%s].%n", + retrievedSetting.getKey(), retrievedSetting.getLabel(), watchingETag, latestETag); + setting.setETag(latestETag).setValue(retrievedSetting.getValue()); + return true; + } + return false; + }) + .collect(Collectors.toList()); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample34/v2/WatchFeature.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample34/v2/WatchFeature.java new file mode 100644 index 000000000000..11f1061af724 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample34/v2/WatchFeature.java @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.ConfigurationSetting; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class WatchFeature { + /** + * Runs the sample algorithm and demonstrates how to read configuration setting revision history. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Instantiate a client that will be used to call the service. + ConfigurationClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + + // Prepare a list of watching settings and update one same setting value to the service. + String prodDBConnectionKey = "prodDBConnection"; + String prodDBConnectionLabel = "prodLabel"; + + // Assume we have a list of watching setting that stored somewhere. + List watchingSettings = Arrays.asList( + client.addConfigurationSetting(prodDBConnectionKey, prodDBConnectionLabel, "prodValue"), + client.addConfigurationSetting("stageDBConnection", "stageLabel", "stageValue") + ); + + System.out.println("Watching settings:"); + for (ConfigurationSetting setting : watchingSettings) { + System.out.printf("\tkey=%s, label=%s, value=%s, ETag=%s.%n", + setting.getKey(), setting.getLabel(), setting.getValue(), setting.getETag()); + } + + // One of the watching settings is been updated by someone in other place. + ConfigurationSetting updatedSetting = client.setConfigurationSetting( + prodDBConnectionKey, prodDBConnectionLabel, "updatedProdValue"); + System.out.println("Updated settings:"); + System.out.printf("\tkey=%s, label=%s, value=%s, ETag=%s.%n", + updatedSetting.getKey(), updatedSetting.getLabel(), updatedSetting.getValue(), updatedSetting.getETag()); + + // Updates the watching settings if needed, and only returns a list of updated settings. + List refreshedSettings = refresh(client, watchingSettings); + + System.out.println("Refreshed settings:"); + for (ConfigurationSetting setting : refreshedSettings) { + System.out.printf("\tkey=%s, label=%s, value=%s, ETag=%s.%n", + setting.getKey(), setting.getLabel(), setting.getValue(), setting.getETag()); + } + + // Cleaning up after ourselves by deleting the values. + System.out.println("Deleting settings:"); + watchingSettings.forEach(setting -> { + client.deleteConfigurationSetting(setting.getKey(), setting.getLabel()); + System.out.printf("\tkey: %s, value: %s.%n", setting.getKey(), setting.getValue()); + }); + } + + /** + * A refresh method that runs every day to update settings and returns a updated settings. + * + * @param client a configuration client. + * @param watchSettings a list of settings in the watching store. + * + * @return a list of updated settings that doesn't match previous ETag value. + */ + private static List refresh(ConfigurationClient client, + List watchSettings) { + return watchSettings + .stream() + .filter(setting -> { + ConfigurationSetting retrievedSetting = client.getConfigurationSetting(setting.getKey(), + setting.getLabel()); + String latestETag = retrievedSetting.getETag(); + String watchingETag = setting.getETag(); + if (!latestETag.equals(watchingETag)) { + System.out.printf( + "Some keys in watching key store matching the key [%s] and label [%s] is updated, " + + "preview ETag value [%s] not equals to current value [%s].%n", + retrievedSetting.getKey(), retrievedSetting.getLabel(), watchingETag, latestETag); + setting.setETag(latestETag).setValue(retrievedSetting.getValue()); + return true; + } + return false; + }) + .collect(Collectors.toList()); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample35/v1/WatchFeatureAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample35/v1/WatchFeatureAsync.java new file mode 100644 index 000000000000..962a5717506f --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample35/v1/WatchFeatureAsync.java @@ -0,0 +1,141 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; +import reactor.core.publisher.Flux; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class WatchFeatureAsync { + /** + * Runs the sample algorithm and demonstrates how to read configuration setting revision history. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) throws InterruptedException { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Instantiate a client that will be used to call the service. + ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + + // Prepare a list of watching settings and update one same setting value to the service. + String prodDBConnectionKey = "prodDBConnection"; + String prodDBConnectionLabel = "prodLabel"; + String updatedProdDBConnectionValue = "updateProdValue"; + + // Assume we have a list of watching setting that stored somewhere. + List watchingSettings = new ArrayList<>(); + Flux.concat( + client.addConfigurationSetting(prodDBConnectionKey, prodDBConnectionLabel, "prodValue"), + client.addConfigurationSetting("stageDBConnection", "stageLabel", "stageValue")) + .then(client.listConfigurationSettings(new SettingSelector().setKeyFilter("*")).collectList()) + .subscribe( + settings -> watchingSettings.addAll(settings), + error -> System.err.printf("There was an error while adding the settings: %s.%n", error), + () -> System.out.println("Add settings completed.") + ); + + // The .subscribe() creation and assignment is not a blocking call. For the purpose of this example, we sleep + // the thread so the program does not end before the send operation is complete. Using .block() instead of + // .subscribe() will turn this into a synchronous call. + TimeUnit.MILLISECONDS.sleep(1000); + + System.out.println("Watching settings:"); + for (ConfigurationSetting setting : watchingSettings) { + System.out.printf("\tWatching key=%s, label=%s, value=%s, ETag=%s.%n", + setting.getKey(), setting.getLabel(), setting.getValue(), setting.getETag()); + } + TimeUnit.MILLISECONDS.sleep(1000); + + // One of the watching settings is been updated by someone in other place. + client.setConfigurationSetting(prodDBConnectionKey, prodDBConnectionLabel, updatedProdDBConnectionValue) + .subscribe( + updatedSetting -> { + System.out.println("Updated settings:"); + System.out.printf("\tUpdated key=%s, label=%s, value=%s, ETag=%s.%n", + updatedSetting.getKey(), updatedSetting.getLabel(), updatedSetting.getValue(), + updatedSetting.getETag()); + }, + error -> System.err.printf("There was an error while updating the setting: %s.%n", error), + () -> System.out.printf("Update setting completed, key=%s, label=%s, value=%s.%n", + prodDBConnectionKey, prodDBConnectionLabel, updatedProdDBConnectionValue)); + TimeUnit.MILLISECONDS.sleep(1000); + + // Updates the watching settings if needed, and only returns a list of updated settings. + List refreshedSettings = refresh(client, watchingSettings); + System.out.println("Refreshed settings:"); + for (ConfigurationSetting setting : refreshedSettings) { + System.out.printf("\tRefreshed key=%s, label=%s, value=%s, ETag=%s.%n", + setting.getKey(), setting.getLabel(), setting.getValue(), setting.getETag()); + } + TimeUnit.MILLISECONDS.sleep(1000); + + // Cleaning up after ourselves by deleting the values. + System.out.println("Deleting settings:"); + Stream stream = watchingSettings == null ? Stream.empty() : watchingSettings.stream(); + Flux.merge(stream.map(setting -> { + System.out.printf("\tDeleting key: %s, value: %s.%n", setting.getKey(), setting.getValue()); + return client.deleteConfigurationSettingWithResponse(setting, false); + }).collect(Collectors.toList())).blockLast(); + } + + /** + * A refresh method that runs every day to update settings and returns a updated settings. + * + * @param client a configuration client. + * @param watchSettings a list of settings in the watching store. + * + * @return a list of updated settings that doesn't match previous ETag value. + */ + private static List refresh(ConfigurationAsyncClient client, + List watchSettings) { + return watchSettings + .stream() + .filter(setting -> { + final boolean[] isUpdated = new boolean[1]; + String key = setting.getKey(); + String label = setting.getLabel(); + client.getConfigurationSetting(key, label) + .subscribe( + retrievedSetting -> { + String latestETag = retrievedSetting.getETag(); + String watchingETag = setting.getETag(); + if (!latestETag.equals(watchingETag)) { + System.out.printf( + "Some keys in watching key store matching the key [%s] and label [%s] is " + + "updated, preview ETag value [%s] not equals to current value [%s].%n", + retrievedSetting.getKey(), retrievedSetting.getLabel(), watchingETag, + latestETag); + setting.setETag(latestETag).setValue(retrievedSetting.getValue()); + isUpdated[0] = true; + } + }, + error -> System.err.printf("There was an error while retrieving the setting: %s.%n", + error), + () -> System.out.printf("Retrieve setting completed, key=%s, label=%s.%n", key, label)); + + // The .subscribe() creation and assignment is not a blocking call. For the purpose of this + // example, we sleep the thread so the program does not end before the send operation is + // complete. Using .block() instead of .subscribe() will turn this into a synchronous call. + try { + TimeUnit.MILLISECONDS.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + return isUpdated[0]; + }) + .collect(Collectors.toList()); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample35/v2/WatchFeatureAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample35/v2/WatchFeatureAsync.java new file mode 100644 index 000000000000..962a5717506f --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample35/v2/WatchFeatureAsync.java @@ -0,0 +1,141 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; +import reactor.core.publisher.Flux; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class WatchFeatureAsync { + /** + * Runs the sample algorithm and demonstrates how to read configuration setting revision history. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) throws InterruptedException { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Instantiate a client that will be used to call the service. + ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + + // Prepare a list of watching settings and update one same setting value to the service. + String prodDBConnectionKey = "prodDBConnection"; + String prodDBConnectionLabel = "prodLabel"; + String updatedProdDBConnectionValue = "updateProdValue"; + + // Assume we have a list of watching setting that stored somewhere. + List watchingSettings = new ArrayList<>(); + Flux.concat( + client.addConfigurationSetting(prodDBConnectionKey, prodDBConnectionLabel, "prodValue"), + client.addConfigurationSetting("stageDBConnection", "stageLabel", "stageValue")) + .then(client.listConfigurationSettings(new SettingSelector().setKeyFilter("*")).collectList()) + .subscribe( + settings -> watchingSettings.addAll(settings), + error -> System.err.printf("There was an error while adding the settings: %s.%n", error), + () -> System.out.println("Add settings completed.") + ); + + // The .subscribe() creation and assignment is not a blocking call. For the purpose of this example, we sleep + // the thread so the program does not end before the send operation is complete. Using .block() instead of + // .subscribe() will turn this into a synchronous call. + TimeUnit.MILLISECONDS.sleep(1000); + + System.out.println("Watching settings:"); + for (ConfigurationSetting setting : watchingSettings) { + System.out.printf("\tWatching key=%s, label=%s, value=%s, ETag=%s.%n", + setting.getKey(), setting.getLabel(), setting.getValue(), setting.getETag()); + } + TimeUnit.MILLISECONDS.sleep(1000); + + // One of the watching settings is been updated by someone in other place. + client.setConfigurationSetting(prodDBConnectionKey, prodDBConnectionLabel, updatedProdDBConnectionValue) + .subscribe( + updatedSetting -> { + System.out.println("Updated settings:"); + System.out.printf("\tUpdated key=%s, label=%s, value=%s, ETag=%s.%n", + updatedSetting.getKey(), updatedSetting.getLabel(), updatedSetting.getValue(), + updatedSetting.getETag()); + }, + error -> System.err.printf("There was an error while updating the setting: %s.%n", error), + () -> System.out.printf("Update setting completed, key=%s, label=%s, value=%s.%n", + prodDBConnectionKey, prodDBConnectionLabel, updatedProdDBConnectionValue)); + TimeUnit.MILLISECONDS.sleep(1000); + + // Updates the watching settings if needed, and only returns a list of updated settings. + List refreshedSettings = refresh(client, watchingSettings); + System.out.println("Refreshed settings:"); + for (ConfigurationSetting setting : refreshedSettings) { + System.out.printf("\tRefreshed key=%s, label=%s, value=%s, ETag=%s.%n", + setting.getKey(), setting.getLabel(), setting.getValue(), setting.getETag()); + } + TimeUnit.MILLISECONDS.sleep(1000); + + // Cleaning up after ourselves by deleting the values. + System.out.println("Deleting settings:"); + Stream stream = watchingSettings == null ? Stream.empty() : watchingSettings.stream(); + Flux.merge(stream.map(setting -> { + System.out.printf("\tDeleting key: %s, value: %s.%n", setting.getKey(), setting.getValue()); + return client.deleteConfigurationSettingWithResponse(setting, false); + }).collect(Collectors.toList())).blockLast(); + } + + /** + * A refresh method that runs every day to update settings and returns a updated settings. + * + * @param client a configuration client. + * @param watchSettings a list of settings in the watching store. + * + * @return a list of updated settings that doesn't match previous ETag value. + */ + private static List refresh(ConfigurationAsyncClient client, + List watchSettings) { + return watchSettings + .stream() + .filter(setting -> { + final boolean[] isUpdated = new boolean[1]; + String key = setting.getKey(); + String label = setting.getLabel(); + client.getConfigurationSetting(key, label) + .subscribe( + retrievedSetting -> { + String latestETag = retrievedSetting.getETag(); + String watchingETag = setting.getETag(); + if (!latestETag.equals(watchingETag)) { + System.out.printf( + "Some keys in watching key store matching the key [%s] and label [%s] is " + + "updated, preview ETag value [%s] not equals to current value [%s].%n", + retrievedSetting.getKey(), retrievedSetting.getLabel(), watchingETag, + latestETag); + setting.setETag(latestETag).setValue(retrievedSetting.getValue()); + isUpdated[0] = true; + } + }, + error -> System.err.printf("There was an error while retrieving the setting: %s.%n", + error), + () -> System.out.printf("Retrieve setting completed, key=%s, label=%s.%n", key, label)); + + // The .subscribe() creation and assignment is not a blocking call. For the purpose of this + // example, we sleep the thread so the program does not end before the send operation is + // complete. Using .block() instead of .subscribe() will turn this into a synchronous call. + try { + TimeUnit.MILLISECONDS.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + return isUpdated[0]; + }) + .collect(Collectors.toList()); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample36/v1/ComplexConfiguration.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample36/v1/ComplexConfiguration.java new file mode 100644 index 000000000000..544d2cea3686 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample36/v1/ComplexConfiguration.java @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration.models; + +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 complex configuration object that has multiple properties stored in Azure App Configuration service. + */ +public class ComplexConfiguration implements JsonSerializable { + private String endpointUri; + private String name; + private int numberOfInstances; + + /** + * Gets the endpoint URI. + * + * @return The endpoint URI. + */ + public String endpointUri() { + return endpointUri; + } + + /** + * Sets the endpoint URI. + * + * @param endpointUri The endpoint URI for this ComplexConfiguration. + * @return The updated object. + */ + public ComplexConfiguration endpointUri(String endpointUri) { + this.endpointUri = endpointUri; + return this; + } + + /** + * Gets the name of the ComplexConfiguration. + * + * @return The name of the complex object. + */ + public String name() { + return name; + } + + /** + * Sets the name of the ComplexConfiguration. + * + * @param name The name to set for this ComplexConfiguration. + * @return The updated object. + */ + public ComplexConfiguration name(String name) { + this.name = name; + return this; + } + + /** + * Gets the number of instances. + * + * @return The number of instances. + */ + public int numberOfInstances() { + return numberOfInstances; + } + + /** + * Sets the number of instances. + * + * @param numberOfInstances The number of instances for this ComplexConfiguration. + * @return The updated object. + */ + public ComplexConfiguration numberOfInstances(int numberOfInstances) { + this.numberOfInstances = numberOfInstances; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return "Name: " + name() + ", Endpoint: " + endpointUri() + ", # of instances: " + numberOfInstances(); + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("endpointUri", endpointUri); + jsonWriter.writeStringField("name", name); + jsonWriter.writeIntField("numberOfInstances", numberOfInstances); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ComplexConfiguration from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ComplexConfiguration 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 ComplexConfiguration. + */ + public static ComplexConfiguration fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ComplexConfiguration deserializedComplexConfiguration = new ComplexConfiguration(); + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("endpointUri".equals(fieldName)) { + deserializedComplexConfiguration.endpointUri(reader.getString()); + } else if ("name".equals(fieldName)) { + deserializedComplexConfiguration.name(reader.getString()); + } else if ("numberOfInstances".equals(fieldName)) { + deserializedComplexConfiguration.numberOfInstances(reader.getInt()); + } else { + reader.skipChildren(); + } + } + + return deserializedComplexConfiguration; + }); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample36/v2/ComplexConfiguration.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample36/v2/ComplexConfiguration.java new file mode 100644 index 000000000000..544d2cea3686 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample36/v2/ComplexConfiguration.java @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration.models; + +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 complex configuration object that has multiple properties stored in Azure App Configuration service. + */ +public class ComplexConfiguration implements JsonSerializable { + private String endpointUri; + private String name; + private int numberOfInstances; + + /** + * Gets the endpoint URI. + * + * @return The endpoint URI. + */ + public String endpointUri() { + return endpointUri; + } + + /** + * Sets the endpoint URI. + * + * @param endpointUri The endpoint URI for this ComplexConfiguration. + * @return The updated object. + */ + public ComplexConfiguration endpointUri(String endpointUri) { + this.endpointUri = endpointUri; + return this; + } + + /** + * Gets the name of the ComplexConfiguration. + * + * @return The name of the complex object. + */ + public String name() { + return name; + } + + /** + * Sets the name of the ComplexConfiguration. + * + * @param name The name to set for this ComplexConfiguration. + * @return The updated object. + */ + public ComplexConfiguration name(String name) { + this.name = name; + return this; + } + + /** + * Gets the number of instances. + * + * @return The number of instances. + */ + public int numberOfInstances() { + return numberOfInstances; + } + + /** + * Sets the number of instances. + * + * @param numberOfInstances The number of instances for this ComplexConfiguration. + * @return The updated object. + */ + public ComplexConfiguration numberOfInstances(int numberOfInstances) { + this.numberOfInstances = numberOfInstances; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return "Name: " + name() + ", Endpoint: " + endpointUri() + ", # of instances: " + numberOfInstances(); + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("endpointUri", endpointUri); + jsonWriter.writeStringField("name", name); + jsonWriter.writeIntField("numberOfInstances", numberOfInstances); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ComplexConfiguration from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ComplexConfiguration 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 ComplexConfiguration. + */ + public static ComplexConfiguration fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ComplexConfiguration deserializedComplexConfiguration = new ComplexConfiguration(); + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("endpointUri".equals(fieldName)) { + deserializedComplexConfiguration.endpointUri(reader.getString()); + } else if ("name".equals(fieldName)) { + deserializedComplexConfiguration.name(reader.getString()); + } else if ("numberOfInstances".equals(fieldName)) { + deserializedComplexConfiguration.numberOfInstances(reader.getInt()); + } else { + reader.skipChildren(); + } + } + + return deserializedComplexConfiguration; + }); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample4/v1/ConditionalRequestForSettingsPagination.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample4/v1/ConditionalRequestForSettingsPagination.java new file mode 100644 index 000000000000..104ec65ab2b6 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample4/v1/ConditionalRequestForSettingsPagination.java @@ -0,0 +1,68 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.MatchConditions; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.Configuration; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * Sample demonstrates how to list configuration settings by conditional request. + * If the ETag of the given setting matches the one in the service, then 304 status code (not modified) with null value + * returned in the response. Otherwise, a setting with new ETag returned, which is the latest setting retrieved from + * the service. + */ +public class ConditionalRequestForSettingsPagination { + /** + * Runs the sample algorithm and demonstrates how to list configuration settings by conditional request. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to the "Access Keys" page under the "Settings" section. + String connectionString = Configuration.getGlobalConfiguration().get("AZURE_APPCONFIG_CONNECTION_STRING"); + + // Instantiate a client that will be used to call the service. + ConfigurationClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + + // list all settings and get their page ETags + List matchConditionsList = client.listConfigurationSettings(null) + .streamByPage() + .collect(Collectors.toList()) + .stream() + .map(pagedResponse -> new MatchConditions().setIfNoneMatch( + pagedResponse.getHeaders().getValue(HttpHeaderName.ETAG))) + .collect(Collectors.toList()); + + PagedIterable settings = client.listConfigurationSettings( + new SettingSelector().setMatchConditions(matchConditionsList)); + + settings.iterableByPage().forEach(pagedResponse -> { + int statusCode = pagedResponse.getStatusCode(); + System.out.println("Status code = " + statusCode); + if (statusCode == 304) { + System.out.println("Settings have not changed. "); + String continuationToken = pagedResponse.getContinuationToken(); + System.out.println("Continuation Token: " + continuationToken); + return; + } + + System.out.println("At least one setting in the page has changes. Listing all settings in the page:"); + System.out.println("new page ETag: " + pagedResponse.getHeaders().getValue(HttpHeaderName.ETAG)); + pagedResponse.getValue().forEach(setting -> { + System.out.println("Key: " + setting.getKey() + ", Value: " + setting.getValue()); + }); + }); + } +} + diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample4/v2/ConditionalRequestForSettingsPagination.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample4/v2/ConditionalRequestForSettingsPagination.java new file mode 100644 index 000000000000..104ec65ab2b6 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample4/v2/ConditionalRequestForSettingsPagination.java @@ -0,0 +1,68 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.MatchConditions; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.Configuration; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * Sample demonstrates how to list configuration settings by conditional request. + * If the ETag of the given setting matches the one in the service, then 304 status code (not modified) with null value + * returned in the response. Otherwise, a setting with new ETag returned, which is the latest setting retrieved from + * the service. + */ +public class ConditionalRequestForSettingsPagination { + /** + * Runs the sample algorithm and demonstrates how to list configuration settings by conditional request. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to the "Access Keys" page under the "Settings" section. + String connectionString = Configuration.getGlobalConfiguration().get("AZURE_APPCONFIG_CONNECTION_STRING"); + + // Instantiate a client that will be used to call the service. + ConfigurationClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + + // list all settings and get their page ETags + List matchConditionsList = client.listConfigurationSettings(null) + .streamByPage() + .collect(Collectors.toList()) + .stream() + .map(pagedResponse -> new MatchConditions().setIfNoneMatch( + pagedResponse.getHeaders().getValue(HttpHeaderName.ETAG))) + .collect(Collectors.toList()); + + PagedIterable settings = client.listConfigurationSettings( + new SettingSelector().setMatchConditions(matchConditionsList)); + + settings.iterableByPage().forEach(pagedResponse -> { + int statusCode = pagedResponse.getStatusCode(); + System.out.println("Status code = " + statusCode); + if (statusCode == 304) { + System.out.println("Settings have not changed. "); + String continuationToken = pagedResponse.getContinuationToken(); + System.out.println("Continuation Token: " + continuationToken); + return; + } + + System.out.println("At least one setting in the page has changes. Listing all settings in the page:"); + System.out.println("new page ETag: " + pagedResponse.getHeaders().getValue(HttpHeaderName.ETAG)); + pagedResponse.getValue().forEach(setting -> { + System.out.println("Key: " + setting.getKey() + ", Value: " + setting.getValue()); + }); + }); + } +} + diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample5/v1/ConditionalRequestForSettingsPaginationAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample5/v1/ConditionalRequestForSettingsPaginationAsync.java new file mode 100644 index 000000000000..e8f509978119 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample5/v1/ConditionalRequestForSettingsPaginationAsync.java @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.MatchConditions; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.util.Configuration; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** + * Sample demonstrates how to list configuration settings by conditional request asynchronously. + * If the ETag of the given setting matches the one in the service, then 304 status code (not modified) with null value + * returned in the response. Otherwise, a setting with new ETag returned, which is the latest setting retrieved from + * the service. + */ +public class ConditionalRequestForSettingsPaginationAsync { + /** + * Runs the sample algorithm and demonstrates how to list configuration settings by conditional request + * asynchronously. + * + * @param args Unused. Arguments to the program. + * @throws InterruptedException when a thread is waiting, sleeping, or otherwise occupied, + * and the thread is interrupted, either before or during the activity. + */ + public static void main(String[] args) throws InterruptedException { + String connectionString = Configuration.getGlobalConfiguration().get("AZURE_APPCONFIG_CONNECTION_STRING"); + + // Instantiate a client that will be used to call the service. + ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + + List matchConditionsList = new ArrayList<>(); + + // list all settings and get their page ETags + client.listConfigurationSettings(null) + .byPage() + .subscribe(pagedResponse -> { + matchConditionsList.add(new MatchConditions().setIfNoneMatch( + pagedResponse.getHeaders().getValue(HttpHeaderName.ETAG))); + }); + + TimeUnit.MILLISECONDS.sleep(1000); + + PagedFlux settings = client.listConfigurationSettings( + new SettingSelector().setMatchConditions(matchConditionsList)); + + settings.byPage().subscribe(pagedResponse -> { + int statusCode = pagedResponse.getStatusCode(); + System.out.println("Status code = " + statusCode); + if (statusCode == 304) { + System.out.println("Settings have not changed. "); + String continuationToken = pagedResponse.getContinuationToken(); + System.out.println("Continuation Token: " + continuationToken); + return; + } + + System.out.println("At least one setting in the page has changes. Listing all settings in the page:"); + System.out.println("new page ETag: " + pagedResponse.getHeaders().getValue(HttpHeaderName.ETAG)); + pagedResponse.getValue().forEach(setting -> { + System.out.println("Key: " + setting.getKey() + ", Value: " + setting.getValue()); + }); + }); + + // The .subscribe() creation and assignment is not a blocking call. For the purpose of this example, we sleep + // the thread so the program does not end before the send operation is complete. Using .block() instead of + // .subscribe() will turn this into a synchronous call. + TimeUnit.SECONDS.sleep(5); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample5/v2/ConditionalRequestForSettingsPaginationAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample5/v2/ConditionalRequestForSettingsPaginationAsync.java new file mode 100644 index 000000000000..e8f509978119 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample5/v2/ConditionalRequestForSettingsPaginationAsync.java @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.MatchConditions; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.util.Configuration; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** + * Sample demonstrates how to list configuration settings by conditional request asynchronously. + * If the ETag of the given setting matches the one in the service, then 304 status code (not modified) with null value + * returned in the response. Otherwise, a setting with new ETag returned, which is the latest setting retrieved from + * the service. + */ +public class ConditionalRequestForSettingsPaginationAsync { + /** + * Runs the sample algorithm and demonstrates how to list configuration settings by conditional request + * asynchronously. + * + * @param args Unused. Arguments to the program. + * @throws InterruptedException when a thread is waiting, sleeping, or otherwise occupied, + * and the thread is interrupted, either before or during the activity. + */ + public static void main(String[] args) throws InterruptedException { + String connectionString = Configuration.getGlobalConfiguration().get("AZURE_APPCONFIG_CONNECTION_STRING"); + + // Instantiate a client that will be used to call the service. + ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + + List matchConditionsList = new ArrayList<>(); + + // list all settings and get their page ETags + client.listConfigurationSettings(null) + .byPage() + .subscribe(pagedResponse -> { + matchConditionsList.add(new MatchConditions().setIfNoneMatch( + pagedResponse.getHeaders().getValue(HttpHeaderName.ETAG))); + }); + + TimeUnit.MILLISECONDS.sleep(1000); + + PagedFlux settings = client.listConfigurationSettings( + new SettingSelector().setMatchConditions(matchConditionsList)); + + settings.byPage().subscribe(pagedResponse -> { + int statusCode = pagedResponse.getStatusCode(); + System.out.println("Status code = " + statusCode); + if (statusCode == 304) { + System.out.println("Settings have not changed. "); + String continuationToken = pagedResponse.getContinuationToken(); + System.out.println("Continuation Token: " + continuationToken); + return; + } + + System.out.println("At least one setting in the page has changes. Listing all settings in the page:"); + System.out.println("new page ETag: " + pagedResponse.getHeaders().getValue(HttpHeaderName.ETAG)); + pagedResponse.getValue().forEach(setting -> { + System.out.println("Key: " + setting.getKey() + ", Value: " + setting.getValue()); + }); + }); + + // The .subscribe() creation and assignment is not a blocking call. For the purpose of this example, we sleep + // the thread so the program does not end before the send operation is complete. Using .block() instead of + // .subscribe() will turn this into a synchronous call. + TimeUnit.SECONDS.sleep(5); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample6/v1/ConfigurationAsyncClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample6/v1/ConfigurationAsyncClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..580d7c4132dd --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample6/v1/ConfigurationAsyncClientJavaDocCodeSnippets.java @@ -0,0 +1,526 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.http.MatchConditions; +import com.azure.core.util.Configuration; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.ConfigurationSettingsFilter; +import com.azure.data.appconfiguration.models.ConfigurationSnapshot; +import com.azure.data.appconfiguration.models.SettingLabelSelector; +import com.azure.data.appconfiguration.models.SettingFields; +import com.azure.data.appconfiguration.models.SettingSelector; +import com.azure.data.appconfiguration.models.SnapshotFields; +import com.azure.data.appconfiguration.models.SnapshotSelector; +import reactor.util.context.Context; + +import java.time.Duration; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Code snippets for {@link ConfigurationAsyncClient} + */ +public class ConfigurationAsyncClientJavaDocCodeSnippets { + + private static final String NO_LABEL = null; + private String key1 = "key1"; + private String key2 = "key2"; + private String value1 = "val1"; + private String value2 = "val2"; + + private ConfigurationAsyncClient client = getAsyncClient(); + + /** + * Code snippets for {@link ConfigurationAsyncClient#addConfigurationSetting(String, String, String)} + */ + public void addConfigurationSettingsCodeSnippet() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting#string-string-string + client.addConfigurationSetting("prodDBConnection", "westUS", "db_connection") + .subscribe(response -> System.out.printf("Key: %s, Label: %s, Value: %s", + response.getKey(), response.getLabel(), response.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting#string-string-string + + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting#ConfigurationSetting + client.addConfigurationSetting(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS") + .setValue("db_connection")) + .subscribe(response -> System.out.printf("Key: %s, Label: %s, Value: %s", + response.getKey(), response.getLabel(), response.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting#ConfigurationSetting + + /** + * Code snippets for {@link ConfigurationAsyncClient#addConfigurationSettingWithResponse(ConfigurationSetting)} + */ + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSettingWithResponse#ConfigurationSetting + client.addConfigurationSettingWithResponse(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS") + .setValue("db_connection")) + .subscribe(response -> { + ConfigurationSetting responseSetting = response.getValue(); + System.out.printf("Key: %s, Label: %s, Value: %s", + responseSetting.getKey(), responseSetting.getLabel(), responseSetting.getValue()); + }); + // END: com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSettingWithResponse#ConfigurationSetting + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#setConfigurationSetting(String, String, String)} + */ + public void setConfigurationSettingsCodeSnippet() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting#string-string-string + client.setConfigurationSetting("prodDBConnection", "westUS", "db_connection") + .subscribe(response -> System.out.printf("Key: %s, Label: %s, Value: %s", + response.getKey(), response.getLabel(), response.getValue())); + // Update the value of the setting to "updated_db_connection" + client.setConfigurationSetting("prodDBConnection", "westUS", "updated_db_connection") + .subscribe(response -> System.out.printf("Key: %s, Label: %s, Value: %s", + response.getKey(), response.getLabel(), response.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting#string-string-string + + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting#ConfigurationSetting + client.setConfigurationSetting(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS")) + .subscribe(response -> System.out.printf("Key: %s, Label: %s, Value: %s", + response.getKey(), response.getLabel(), response.getValue())); + // Update the value of the setting to "updated_db_connection" + client.setConfigurationSetting(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS") + .setValue("updated_db_connection")) + .subscribe(response -> System.out.printf("Key: %s, Label: %s, Value: %s", + response.getKey(), response.getLabel(), response.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting#ConfigurationSetting + + /** + * Code snippets for + * {@link ConfigurationAsyncClient#setConfigurationSettingWithResponse(ConfigurationSetting, boolean)} + */ + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSettingWithResponse#ConfigurationSetting-boolean + client.setConfigurationSettingWithResponse(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS") + .setValue("db_connection"), + false) + .subscribe(response -> { + final ConfigurationSetting result = response.getValue(); + System.out.printf("Key: %s, Label: %s, Value: %s", + result.getKey(), result.getLabel(), result.getValue()); + }); + // Update the value of the setting to "updated_db_connection" + client.setConfigurationSettingWithResponse(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS") + .setValue("updated_db_connection"), + false) + .subscribe(response -> { + final ConfigurationSetting responseSetting = response.getValue(); + System.out.printf("Key: %s, Label: %s, Value: %s", + responseSetting.getKey(), responseSetting.getLabel(), responseSetting.getValue()); + }); + // END: com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSettingWithResponse#ConfigurationSetting-boolean + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#getConfigurationSetting(String, String)} + */ + public void getConfigurationSettingsCodeSnippet() { + ConfigurationAsyncClient client = getAsyncClient(); + + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting#string-string + client.getConfigurationSetting("prodDBConnection", "westUS") + .subscribe(response -> System.out.printf("Key: %s, Label: %s, Value: %s", + response.getKey(), response.getLabel(), response.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting#string-string + + /** + * Code snippets for {@link ConfigurationAsyncClient#getConfigurationSetting(String, String, OffsetDateTime)} + */ + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting#string-string-OffsetDateTime + client.getConfigurationSetting( + "prodDBConnection", "westUS", OffsetDateTime.now(ZoneOffset.UTC).minusMinutes(1)) + .subscribe(response -> System.out.printf("Key: %s, Label: %s, Value: %s", + response.getKey(), response.getLabel(), response.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting#string-string-OffsetDateTime + + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting#ConfigurationSetting + client.getConfigurationSetting(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS")) + .subscribe(response -> System.out.printf("Key: %s, Label: %s, Value: %s", + response.getKey(), response.getLabel(), response.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting#ConfigurationSetting + + /** + * Code snippets for {@link ConfigurationAsyncClient#getConfigurationSettingWithResponse( + * ConfigurationSetting, OffsetDateTime, boolean)} + */ + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSettingWithResponse#ConfigurationSetting-OffsetDateTime-boolean + client.getConfigurationSettingWithResponse(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS"), + null, + false) + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(response -> { + ConfigurationSetting result = response.getValue(); + System.out.printf("Key: %s, Label: %s, Value: %s", + result.getKey(), result.getLabel(), result.getValue()); + }); + // END: com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSettingWithResponse#ConfigurationSetting-OffsetDateTime-boolean + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#deleteConfigurationSetting(String, String)} + */ + public void deleteConfigurationSettingsCodeSnippet() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting#string-string + client.deleteConfigurationSetting("prodDBConnection", "westUS") + .subscribe(response -> System.out.printf("Key: %s, Label: %s, Value: %s", + response.getKey(), response.getLabel(), response.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting#string-string + + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting#ConfigurationSetting + client.deleteConfigurationSetting(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS")) + .subscribe(response -> System.out.printf("Key: %s, Label: %s, Value: %s", + response.getKey(), response.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting#ConfigurationSetting + + /** + * Code snippets for + * {@link ConfigurationAsyncClient#deleteConfigurationSettingWithResponse(ConfigurationSetting, boolean)} + */ + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSettingWithResponse#ConfigurationSetting-boolean + client.deleteConfigurationSettingWithResponse(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS"), + false) + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(response -> { + ConfigurationSetting responseSetting = response.getValue(); + System.out.printf("Key: %s, Label: %s, Value: %s", + responseSetting.getKey(), responseSetting.getLabel(), responseSetting.getValue()); + }); + // END: com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSettingWithResponse#ConfigurationSetting-boolean + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#setReadOnly(String, String, boolean)} set to read-only setting + */ + public void lockSettingsCodeSnippet() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.setReadOnly#string-string-boolean + client.setReadOnly("prodDBConnection", "westUS", true) + .subscribe(response -> System.out.printf("Key: %s, Label: %s, Value: %s", + response.getKey(), response.getLabel(), response.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.setReadOnly#string-string-boolean + + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.setReadOnly#ConfigurationSetting-boolean + client.setReadOnly(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS"), + true) + .subscribe(response -> System.out.printf("Key: %s, Label: %s, Value: %s", + response.getKey(), response.getLabel(), response.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.setReadOnly#ConfigurationSetting-boolean + + /** + * Code snippets for {@link ConfigurationAsyncClient#setReadOnlyWithResponse(ConfigurationSetting, Boolean)} + */ + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse#ConfigurationSetting-boolean + client.setReadOnlyWithResponse(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS"), + true) + .subscribe(response -> { + ConfigurationSetting result = response.getValue(); + System.out.printf("Key: %s, Label: %s, Value: %s", + result.getKey(), result.getLabel(), result.getValue()); + }); + // END: com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse#ConfigurationSetting-boolean + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#setReadOnly(String, String, boolean)} set to not read-only setting + */ + public void unlockSettingsCodeSnippet() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.setReadOnly#string-string-boolean-clearReadOnly + client.setReadOnly("prodDBConnection", "westUS", false) + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(response -> System.out.printf("Key: %s, Value: %s", response.getKey(), response.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.setReadOnly#string-string-boolean-clearReadOnly + + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.setReadOnly#ConfigurationSetting-boolean-clearReadOnly + client.setReadOnly(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS"), + false) + .subscribe(response -> System.out.printf("Key: %s, Value: %s", response.getKey(), response.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.setReadOnly#ConfigurationSetting-boolean-clearReadOnly + + /** + * Code snippets for {@link ConfigurationAsyncClient#setReadOnlyWithResponse(ConfigurationSetting, Boolean)} + */ + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse#ConfigurationSetting-boolean-clearReadOnly + client.setReadOnlyWithResponse(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS"), + false) + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(response -> { + ConfigurationSetting result = response.getValue(); + System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); + }); + // END: com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse#ConfigurationSetting-boolean-clearReadOnly + } + + + /** + * Code snippets for {@link ConfigurationAsyncClient#listConfigurationSettings(SettingSelector)} + */ + public void listSettingCodeSnippet() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.listConfigurationSettings + client.listConfigurationSettings(new SettingSelector().setKeyFilter("prodDBConnection")) + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(setting -> + System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.listConfigurationSettings + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#listConfigurationSettingsForSnapshot(String)} + */ + public void listConfigurationSettingsForSnapshot() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.listConfigurationSettingsForSnapshot + String snapshotName = "{snapshotName}"; + client.listConfigurationSettingsForSnapshot(snapshotName) + .subscribe(setting -> + System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.listConfigurationSettingsForSnapshot + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#listConfigurationSettingsForSnapshot(String, List)} + */ + public void listConfigurationSettingsForSnapshotMaxOverload() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.listConfigurationSettingsForSnapshotMaxOverload + String snapshotName = "{snapshotName}"; + List fields = Arrays.asList(SettingFields.KEY); + client.listConfigurationSettingsForSnapshot(snapshotName, fields) + .subscribe(setting -> + System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.listConfigurationSettingsForSnapshotMaxOverload + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#listRevisions(SettingSelector)} + */ + public void listRevisionsCodeSnippet() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions + client.listRevisions(new SettingSelector().setKeyFilter("prodDBConnection")) + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(setting -> + System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#beginCreateSnapshot(String, ConfigurationSnapshot)}} + */ + public void beginCreateSnapshotMaxOverload() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.beginCreateSnapshotMaxOverload + List filters = new ArrayList<>(); + // Key Name also supports RegExp but only support prefix end with "*", such as "k*" and is case-sensitive. + filters.add(new ConfigurationSettingsFilter("{keyName}")); + String snapshotName = "{snapshotName}"; + client.beginCreateSnapshot(snapshotName, new ConfigurationSnapshot(filters) + .setRetentionPeriod(Duration.ofHours(1))) + .flatMap(result -> result.getFinalResult()) + .subscribe( + snapshot -> System.out.printf("Snapshot name=%s is created at %s%n", + snapshot.getName(), snapshot.getCreatedAt()), + ex -> System.out.printf("Error on creating a snapshot=%s, with error=%s.%n", snapshotName, + ex.getMessage()), + () -> System.out.println("Successfully created a snapshot.")); + // END: com.azure.data.appconfiguration.configurationasyncclient.beginCreateSnapshotMaxOverload + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#getSnapshot(String)} + */ + public void getSnapshotByName() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.getSnapshotByName + String snapshotName = "{snapshotName}"; + client.getSnapshot(snapshotName).subscribe( + getSnapshot -> { + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + getSnapshot.getName(), getSnapshot.getCreatedAt(), getSnapshot.getStatus()); + } + ); + // END: com.azure.data.appconfiguration.configurationasyncclient.getSnapshotByName + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#getSnapshotWithResponse(String, List)} + */ + public void getSnapshotByNameMaxOverload() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.getSnapshotByNameMaxOverload + String snapshotName = "{snapshotName}"; + + client.getSnapshotWithResponse(snapshotName, Arrays.asList(SnapshotFields.NAME, SnapshotFields.CREATED_AT, + SnapshotFields.STATUS, SnapshotFields.FILTERS)) + .subscribe( + response -> { + ConfigurationSnapshot getSnapshot = response.getValue(); + // Only properties `name`, `createAt`, `status` and `filters` have value, and expect null or + // empty value other than the `fields` specified in the request. + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + getSnapshot.getName(), getSnapshot.getCreatedAt(), getSnapshot.getStatus()); + List filters = getSnapshot.getFilters(); + for (ConfigurationSettingsFilter filter : filters) { + System.out.printf("Snapshot filter key=%s, label=%s.%n", filter.getKey(), filter.getLabel()); + } + }); + // END: com.azure.data.appconfiguration.configurationasyncclient.getSnapshotByNameMaxOverload + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#archiveSnapshot(String)} + */ + public void archiveSnapshotByName() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.archiveSnapshotByName + String snapshotName = "{snapshotName}"; + client.archiveSnapshot(snapshotName).subscribe( + archivedSnapshot -> { + System.out.printf("Archived snapshot name=%s is created at %s, snapshot status is %s.%n", + archivedSnapshot.getName(), archivedSnapshot.getCreatedAt(), archivedSnapshot.getStatus()); + } + ); + // END: com.azure.data.appconfiguration.configurationasyncclient.archiveSnapshotByName + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#archiveSnapshotWithResponse(String, MatchConditions)} + */ + public void archiveSnapshotMaxOverload() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.archiveSnapshotMaxOverload + String snapshotName = "{snapshotName}"; + MatchConditions matchConditions = new MatchConditions().setIfMatch("{etag}"); + client.archiveSnapshotWithResponse(snapshotName, matchConditions) + .subscribe( + response -> { + ConfigurationSnapshot archivedSnapshot = response.getValue(); + System.out.printf("Archived snapshot name=%s is created at %s, snapshot status is %s.%n", + archivedSnapshot.getName(), archivedSnapshot.getCreatedAt(), archivedSnapshot.getStatus()); + } + ); + // END: com.azure.data.appconfiguration.configurationasyncclient.archiveSnapshotMaxOverload + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#recoverSnapshot(String)} + */ + public void recoverSnapshotByName() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.recoverSnapshotByName + String snapshotName = "{snapshotName}"; + client.recoverSnapshot(snapshotName).subscribe( + recoveredSnapshot -> { + System.out.printf("Recovered snapshot name=%s is created at %s, snapshot status is %s.%n", + recoveredSnapshot.getName(), recoveredSnapshot.getCreatedAt(), recoveredSnapshot.getStatus()); + } + ); + // END: com.azure.data.appconfiguration.configurationasyncclient.recoverSnapshotByName + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#recoverSnapshotWithResponse(String, MatchConditions)} + */ + public void recoverSnapshotMaxOverload() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.recoverSnapshotMaxOverload + String snapshotName = "{snapshotName}"; + MatchConditions matchConditions = new MatchConditions().setIfMatch("{etag}"); + client.recoverSnapshotWithResponse(snapshotName, matchConditions).subscribe( + response -> { + ConfigurationSnapshot recoveredSnapshot = response.getValue(); + System.out.printf("Recovered snapshot name=%s is created at %s, snapshot status is %s.%n", + recoveredSnapshot.getName(), recoveredSnapshot.getCreatedAt(), recoveredSnapshot.getStatus()); + } + ); + // END: com.azure.data.appconfiguration.configurationasyncclient.recoverSnapshotMaxOverload + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#listSnapshots(SnapshotSelector)} + */ + public void listSnapshots() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.listSnapshots + String snapshotNameFilter = "{snapshotNamePrefix}*"; + client.listSnapshots(new SnapshotSelector().setNameFilter(snapshotNameFilter)) + .subscribe(recoveredSnapshot -> { + System.out.printf("Recovered snapshot name=%s is created at %s, snapshot status is %s.%n", + recoveredSnapshot.getName(), recoveredSnapshot.getCreatedAt(), recoveredSnapshot.getStatus()); + }); + // END: com.azure.data.appconfiguration.configurationasyncclient.listSnapshots + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#listLabels()} + */ + public void listAllLabels() { + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.listAllLabels + client.listLabels() + .subscribe(label -> { + System.out.println("label name = " + label); + }); + // END: com.azure.data.appconfiguration.configurationasyncclient.listAllLabels + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#listLabels(SettingLabelSelector)} + */ + public void listLabels() { + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.listLabels + String labelNameFilter = "{labelNamePrefix}*"; + client.listLabels(new SettingLabelSelector().setNameFilter(labelNameFilter)) + .subscribe(label -> { + System.out.println("label name = " + label); + }); + // END: com.azure.data.appconfiguration.configurationasyncclient.listLabels + } + + /** + * Implementation not provided + * + * @return {@code null} + */ + private ConfigurationAsyncClient getAsyncClient() { + return new ConfigurationClientBuilder() + .connectionString(Configuration.getGlobalConfiguration().get("AZURE_APPCONFIG_CONNECTION_STRING")) + .buildAsyncClient(); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample6/v2/ConfigurationAsyncClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample6/v2/ConfigurationAsyncClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..580d7c4132dd --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample6/v2/ConfigurationAsyncClientJavaDocCodeSnippets.java @@ -0,0 +1,526 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.http.MatchConditions; +import com.azure.core.util.Configuration; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.ConfigurationSettingsFilter; +import com.azure.data.appconfiguration.models.ConfigurationSnapshot; +import com.azure.data.appconfiguration.models.SettingLabelSelector; +import com.azure.data.appconfiguration.models.SettingFields; +import com.azure.data.appconfiguration.models.SettingSelector; +import com.azure.data.appconfiguration.models.SnapshotFields; +import com.azure.data.appconfiguration.models.SnapshotSelector; +import reactor.util.context.Context; + +import java.time.Duration; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Code snippets for {@link ConfigurationAsyncClient} + */ +public class ConfigurationAsyncClientJavaDocCodeSnippets { + + private static final String NO_LABEL = null; + private String key1 = "key1"; + private String key2 = "key2"; + private String value1 = "val1"; + private String value2 = "val2"; + + private ConfigurationAsyncClient client = getAsyncClient(); + + /** + * Code snippets for {@link ConfigurationAsyncClient#addConfigurationSetting(String, String, String)} + */ + public void addConfigurationSettingsCodeSnippet() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting#string-string-string + client.addConfigurationSetting("prodDBConnection", "westUS", "db_connection") + .subscribe(response -> System.out.printf("Key: %s, Label: %s, Value: %s", + response.getKey(), response.getLabel(), response.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting#string-string-string + + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting#ConfigurationSetting + client.addConfigurationSetting(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS") + .setValue("db_connection")) + .subscribe(response -> System.out.printf("Key: %s, Label: %s, Value: %s", + response.getKey(), response.getLabel(), response.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSetting#ConfigurationSetting + + /** + * Code snippets for {@link ConfigurationAsyncClient#addConfigurationSettingWithResponse(ConfigurationSetting)} + */ + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSettingWithResponse#ConfigurationSetting + client.addConfigurationSettingWithResponse(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS") + .setValue("db_connection")) + .subscribe(response -> { + ConfigurationSetting responseSetting = response.getValue(); + System.out.printf("Key: %s, Label: %s, Value: %s", + responseSetting.getKey(), responseSetting.getLabel(), responseSetting.getValue()); + }); + // END: com.azure.data.appconfiguration.configurationasyncclient.addConfigurationSettingWithResponse#ConfigurationSetting + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#setConfigurationSetting(String, String, String)} + */ + public void setConfigurationSettingsCodeSnippet() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting#string-string-string + client.setConfigurationSetting("prodDBConnection", "westUS", "db_connection") + .subscribe(response -> System.out.printf("Key: %s, Label: %s, Value: %s", + response.getKey(), response.getLabel(), response.getValue())); + // Update the value of the setting to "updated_db_connection" + client.setConfigurationSetting("prodDBConnection", "westUS", "updated_db_connection") + .subscribe(response -> System.out.printf("Key: %s, Label: %s, Value: %s", + response.getKey(), response.getLabel(), response.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting#string-string-string + + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting#ConfigurationSetting + client.setConfigurationSetting(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS")) + .subscribe(response -> System.out.printf("Key: %s, Label: %s, Value: %s", + response.getKey(), response.getLabel(), response.getValue())); + // Update the value of the setting to "updated_db_connection" + client.setConfigurationSetting(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS") + .setValue("updated_db_connection")) + .subscribe(response -> System.out.printf("Key: %s, Label: %s, Value: %s", + response.getKey(), response.getLabel(), response.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSetting#ConfigurationSetting + + /** + * Code snippets for + * {@link ConfigurationAsyncClient#setConfigurationSettingWithResponse(ConfigurationSetting, boolean)} + */ + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSettingWithResponse#ConfigurationSetting-boolean + client.setConfigurationSettingWithResponse(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS") + .setValue("db_connection"), + false) + .subscribe(response -> { + final ConfigurationSetting result = response.getValue(); + System.out.printf("Key: %s, Label: %s, Value: %s", + result.getKey(), result.getLabel(), result.getValue()); + }); + // Update the value of the setting to "updated_db_connection" + client.setConfigurationSettingWithResponse(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS") + .setValue("updated_db_connection"), + false) + .subscribe(response -> { + final ConfigurationSetting responseSetting = response.getValue(); + System.out.printf("Key: %s, Label: %s, Value: %s", + responseSetting.getKey(), responseSetting.getLabel(), responseSetting.getValue()); + }); + // END: com.azure.data.appconfiguration.configurationasyncclient.setConfigurationSettingWithResponse#ConfigurationSetting-boolean + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#getConfigurationSetting(String, String)} + */ + public void getConfigurationSettingsCodeSnippet() { + ConfigurationAsyncClient client = getAsyncClient(); + + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting#string-string + client.getConfigurationSetting("prodDBConnection", "westUS") + .subscribe(response -> System.out.printf("Key: %s, Label: %s, Value: %s", + response.getKey(), response.getLabel(), response.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting#string-string + + /** + * Code snippets for {@link ConfigurationAsyncClient#getConfigurationSetting(String, String, OffsetDateTime)} + */ + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting#string-string-OffsetDateTime + client.getConfigurationSetting( + "prodDBConnection", "westUS", OffsetDateTime.now(ZoneOffset.UTC).minusMinutes(1)) + .subscribe(response -> System.out.printf("Key: %s, Label: %s, Value: %s", + response.getKey(), response.getLabel(), response.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting#string-string-OffsetDateTime + + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting#ConfigurationSetting + client.getConfigurationSetting(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS")) + .subscribe(response -> System.out.printf("Key: %s, Label: %s, Value: %s", + response.getKey(), response.getLabel(), response.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSetting#ConfigurationSetting + + /** + * Code snippets for {@link ConfigurationAsyncClient#getConfigurationSettingWithResponse( + * ConfigurationSetting, OffsetDateTime, boolean)} + */ + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSettingWithResponse#ConfigurationSetting-OffsetDateTime-boolean + client.getConfigurationSettingWithResponse(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS"), + null, + false) + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(response -> { + ConfigurationSetting result = response.getValue(); + System.out.printf("Key: %s, Label: %s, Value: %s", + result.getKey(), result.getLabel(), result.getValue()); + }); + // END: com.azure.data.appconfiguration.configurationasyncclient.getConfigurationSettingWithResponse#ConfigurationSetting-OffsetDateTime-boolean + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#deleteConfigurationSetting(String, String)} + */ + public void deleteConfigurationSettingsCodeSnippet() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting#string-string + client.deleteConfigurationSetting("prodDBConnection", "westUS") + .subscribe(response -> System.out.printf("Key: %s, Label: %s, Value: %s", + response.getKey(), response.getLabel(), response.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting#string-string + + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting#ConfigurationSetting + client.deleteConfigurationSetting(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS")) + .subscribe(response -> System.out.printf("Key: %s, Label: %s, Value: %s", + response.getKey(), response.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSetting#ConfigurationSetting + + /** + * Code snippets for + * {@link ConfigurationAsyncClient#deleteConfigurationSettingWithResponse(ConfigurationSetting, boolean)} + */ + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSettingWithResponse#ConfigurationSetting-boolean + client.deleteConfigurationSettingWithResponse(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS"), + false) + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(response -> { + ConfigurationSetting responseSetting = response.getValue(); + System.out.printf("Key: %s, Label: %s, Value: %s", + responseSetting.getKey(), responseSetting.getLabel(), responseSetting.getValue()); + }); + // END: com.azure.data.appconfiguration.configurationasyncclient.deleteConfigurationSettingWithResponse#ConfigurationSetting-boolean + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#setReadOnly(String, String, boolean)} set to read-only setting + */ + public void lockSettingsCodeSnippet() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.setReadOnly#string-string-boolean + client.setReadOnly("prodDBConnection", "westUS", true) + .subscribe(response -> System.out.printf("Key: %s, Label: %s, Value: %s", + response.getKey(), response.getLabel(), response.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.setReadOnly#string-string-boolean + + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.setReadOnly#ConfigurationSetting-boolean + client.setReadOnly(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS"), + true) + .subscribe(response -> System.out.printf("Key: %s, Label: %s, Value: %s", + response.getKey(), response.getLabel(), response.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.setReadOnly#ConfigurationSetting-boolean + + /** + * Code snippets for {@link ConfigurationAsyncClient#setReadOnlyWithResponse(ConfigurationSetting, Boolean)} + */ + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse#ConfigurationSetting-boolean + client.setReadOnlyWithResponse(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS"), + true) + .subscribe(response -> { + ConfigurationSetting result = response.getValue(); + System.out.printf("Key: %s, Label: %s, Value: %s", + result.getKey(), result.getLabel(), result.getValue()); + }); + // END: com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse#ConfigurationSetting-boolean + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#setReadOnly(String, String, boolean)} set to not read-only setting + */ + public void unlockSettingsCodeSnippet() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.setReadOnly#string-string-boolean-clearReadOnly + client.setReadOnly("prodDBConnection", "westUS", false) + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(response -> System.out.printf("Key: %s, Value: %s", response.getKey(), response.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.setReadOnly#string-string-boolean-clearReadOnly + + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.setReadOnly#ConfigurationSetting-boolean-clearReadOnly + client.setReadOnly(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS"), + false) + .subscribe(response -> System.out.printf("Key: %s, Value: %s", response.getKey(), response.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.setReadOnly#ConfigurationSetting-boolean-clearReadOnly + + /** + * Code snippets for {@link ConfigurationAsyncClient#setReadOnlyWithResponse(ConfigurationSetting, Boolean)} + */ + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse#ConfigurationSetting-boolean-clearReadOnly + client.setReadOnlyWithResponse(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS"), + false) + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(response -> { + ConfigurationSetting result = response.getValue(); + System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); + }); + // END: com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse#ConfigurationSetting-boolean-clearReadOnly + } + + + /** + * Code snippets for {@link ConfigurationAsyncClient#listConfigurationSettings(SettingSelector)} + */ + public void listSettingCodeSnippet() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.listConfigurationSettings + client.listConfigurationSettings(new SettingSelector().setKeyFilter("prodDBConnection")) + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(setting -> + System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.listConfigurationSettings + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#listConfigurationSettingsForSnapshot(String)} + */ + public void listConfigurationSettingsForSnapshot() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.listConfigurationSettingsForSnapshot + String snapshotName = "{snapshotName}"; + client.listConfigurationSettingsForSnapshot(snapshotName) + .subscribe(setting -> + System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.listConfigurationSettingsForSnapshot + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#listConfigurationSettingsForSnapshot(String, List)} + */ + public void listConfigurationSettingsForSnapshotMaxOverload() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.listConfigurationSettingsForSnapshotMaxOverload + String snapshotName = "{snapshotName}"; + List fields = Arrays.asList(SettingFields.KEY); + client.listConfigurationSettingsForSnapshot(snapshotName, fields) + .subscribe(setting -> + System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.listConfigurationSettingsForSnapshotMaxOverload + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#listRevisions(SettingSelector)} + */ + public void listRevisionsCodeSnippet() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions + client.listRevisions(new SettingSelector().setKeyFilter("prodDBConnection")) + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(setting -> + System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue())); + // END: com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#beginCreateSnapshot(String, ConfigurationSnapshot)}} + */ + public void beginCreateSnapshotMaxOverload() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.beginCreateSnapshotMaxOverload + List filters = new ArrayList<>(); + // Key Name also supports RegExp but only support prefix end with "*", such as "k*" and is case-sensitive. + filters.add(new ConfigurationSettingsFilter("{keyName}")); + String snapshotName = "{snapshotName}"; + client.beginCreateSnapshot(snapshotName, new ConfigurationSnapshot(filters) + .setRetentionPeriod(Duration.ofHours(1))) + .flatMap(result -> result.getFinalResult()) + .subscribe( + snapshot -> System.out.printf("Snapshot name=%s is created at %s%n", + snapshot.getName(), snapshot.getCreatedAt()), + ex -> System.out.printf("Error on creating a snapshot=%s, with error=%s.%n", snapshotName, + ex.getMessage()), + () -> System.out.println("Successfully created a snapshot.")); + // END: com.azure.data.appconfiguration.configurationasyncclient.beginCreateSnapshotMaxOverload + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#getSnapshot(String)} + */ + public void getSnapshotByName() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.getSnapshotByName + String snapshotName = "{snapshotName}"; + client.getSnapshot(snapshotName).subscribe( + getSnapshot -> { + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + getSnapshot.getName(), getSnapshot.getCreatedAt(), getSnapshot.getStatus()); + } + ); + // END: com.azure.data.appconfiguration.configurationasyncclient.getSnapshotByName + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#getSnapshotWithResponse(String, List)} + */ + public void getSnapshotByNameMaxOverload() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.getSnapshotByNameMaxOverload + String snapshotName = "{snapshotName}"; + + client.getSnapshotWithResponse(snapshotName, Arrays.asList(SnapshotFields.NAME, SnapshotFields.CREATED_AT, + SnapshotFields.STATUS, SnapshotFields.FILTERS)) + .subscribe( + response -> { + ConfigurationSnapshot getSnapshot = response.getValue(); + // Only properties `name`, `createAt`, `status` and `filters` have value, and expect null or + // empty value other than the `fields` specified in the request. + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + getSnapshot.getName(), getSnapshot.getCreatedAt(), getSnapshot.getStatus()); + List filters = getSnapshot.getFilters(); + for (ConfigurationSettingsFilter filter : filters) { + System.out.printf("Snapshot filter key=%s, label=%s.%n", filter.getKey(), filter.getLabel()); + } + }); + // END: com.azure.data.appconfiguration.configurationasyncclient.getSnapshotByNameMaxOverload + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#archiveSnapshot(String)} + */ + public void archiveSnapshotByName() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.archiveSnapshotByName + String snapshotName = "{snapshotName}"; + client.archiveSnapshot(snapshotName).subscribe( + archivedSnapshot -> { + System.out.printf("Archived snapshot name=%s is created at %s, snapshot status is %s.%n", + archivedSnapshot.getName(), archivedSnapshot.getCreatedAt(), archivedSnapshot.getStatus()); + } + ); + // END: com.azure.data.appconfiguration.configurationasyncclient.archiveSnapshotByName + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#archiveSnapshotWithResponse(String, MatchConditions)} + */ + public void archiveSnapshotMaxOverload() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.archiveSnapshotMaxOverload + String snapshotName = "{snapshotName}"; + MatchConditions matchConditions = new MatchConditions().setIfMatch("{etag}"); + client.archiveSnapshotWithResponse(snapshotName, matchConditions) + .subscribe( + response -> { + ConfigurationSnapshot archivedSnapshot = response.getValue(); + System.out.printf("Archived snapshot name=%s is created at %s, snapshot status is %s.%n", + archivedSnapshot.getName(), archivedSnapshot.getCreatedAt(), archivedSnapshot.getStatus()); + } + ); + // END: com.azure.data.appconfiguration.configurationasyncclient.archiveSnapshotMaxOverload + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#recoverSnapshot(String)} + */ + public void recoverSnapshotByName() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.recoverSnapshotByName + String snapshotName = "{snapshotName}"; + client.recoverSnapshot(snapshotName).subscribe( + recoveredSnapshot -> { + System.out.printf("Recovered snapshot name=%s is created at %s, snapshot status is %s.%n", + recoveredSnapshot.getName(), recoveredSnapshot.getCreatedAt(), recoveredSnapshot.getStatus()); + } + ); + // END: com.azure.data.appconfiguration.configurationasyncclient.recoverSnapshotByName + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#recoverSnapshotWithResponse(String, MatchConditions)} + */ + public void recoverSnapshotMaxOverload() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.recoverSnapshotMaxOverload + String snapshotName = "{snapshotName}"; + MatchConditions matchConditions = new MatchConditions().setIfMatch("{etag}"); + client.recoverSnapshotWithResponse(snapshotName, matchConditions).subscribe( + response -> { + ConfigurationSnapshot recoveredSnapshot = response.getValue(); + System.out.printf("Recovered snapshot name=%s is created at %s, snapshot status is %s.%n", + recoveredSnapshot.getName(), recoveredSnapshot.getCreatedAt(), recoveredSnapshot.getStatus()); + } + ); + // END: com.azure.data.appconfiguration.configurationasyncclient.recoverSnapshotMaxOverload + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#listSnapshots(SnapshotSelector)} + */ + public void listSnapshots() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.listSnapshots + String snapshotNameFilter = "{snapshotNamePrefix}*"; + client.listSnapshots(new SnapshotSelector().setNameFilter(snapshotNameFilter)) + .subscribe(recoveredSnapshot -> { + System.out.printf("Recovered snapshot name=%s is created at %s, snapshot status is %s.%n", + recoveredSnapshot.getName(), recoveredSnapshot.getCreatedAt(), recoveredSnapshot.getStatus()); + }); + // END: com.azure.data.appconfiguration.configurationasyncclient.listSnapshots + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#listLabels()} + */ + public void listAllLabels() { + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.listAllLabels + client.listLabels() + .subscribe(label -> { + System.out.println("label name = " + label); + }); + // END: com.azure.data.appconfiguration.configurationasyncclient.listAllLabels + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#listLabels(SettingLabelSelector)} + */ + public void listLabels() { + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.listLabels + String labelNameFilter = "{labelNamePrefix}*"; + client.listLabels(new SettingLabelSelector().setNameFilter(labelNameFilter)) + .subscribe(label -> { + System.out.println("label name = " + label); + }); + // END: com.azure.data.appconfiguration.configurationasyncclient.listLabels + } + + /** + * Implementation not provided + * + * @return {@code null} + */ + private ConfigurationAsyncClient getAsyncClient() { + return new ConfigurationClientBuilder() + .connectionString(Configuration.getGlobalConfiguration().get("AZURE_APPCONFIG_CONNECTION_STRING")) + .buildAsyncClient(); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample7/v1/ConfigurationClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample7/v1/ConfigurationClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..553ec533612e --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample7/v1/ConfigurationClientJavaDocCodeSnippets.java @@ -0,0 +1,624 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.MatchConditions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Configuration; +import com.azure.core.util.Context; +import com.azure.core.util.polling.PollOperationDetails; +import com.azure.core.util.polling.SyncPoller; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.ConfigurationSettingsFilter; +import com.azure.data.appconfiguration.models.ConfigurationSnapshot; +import com.azure.data.appconfiguration.models.SettingLabelSelector; +import com.azure.data.appconfiguration.models.SettingFields; +import com.azure.data.appconfiguration.models.SettingSelector; +import com.azure.data.appconfiguration.models.SnapshotFields; +import com.azure.data.appconfiguration.models.SnapshotSelector; + +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * This class contains code samples for generating javadocs through doclets for {@link ConfigurationClient} + */ +public final class ConfigurationClientJavaDocCodeSnippets { + + private String key1 = "key1"; + private String key2 = "key2"; + private String value1 = "val1"; + private String value2 = "val2"; + + ConfigurationClient client = createSyncConfigurationClient(); + + /** + * Generates code sample for creating a {@link ConfigurationClient} + * + * @return An instance of {@link ConfigurationClient} + * @throws IllegalStateException If configuration credentials cannot be created. + */ + public ConfigurationClient createAsyncConfigurationClientWithPipeline() { + + String connectionString = getConnectionString(); + // BEGIN: com.azure.data.applicationconfig.configurationclient.pipeline.instantiation + HttpPipeline pipeline = new HttpPipelineBuilder() + .policies(/* add policies */) + .build(); + + ConfigurationClient configurationClient = new ConfigurationClientBuilder() + .pipeline(pipeline) + .endpoint("https://dummy.azure.net/") + .connectionString(connectionString) + .buildClient(); + // END: com.azure.data.applicationconfig.configurationclient.pipeline.instantiation + return configurationClient; + } + + /** + * Generates code sample for creating a {@link ConfigurationClient} + * + * @return An instance of {@link ConfigurationClient} + * @throws IllegalStateException If configuration credentials cannot be created + */ + public ConfigurationAsyncClient createAsyncConfigurationClient() { + String connectionString = getConnectionString(); + // BEGIN: com.azure.data.applicationconfig.async.configurationclient.instantiation + ConfigurationAsyncClient configurationAsyncClient = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + // END: com.azure.data.applicationconfig.async.configurationclient.instantiation + return configurationAsyncClient; + } + + /** + * Generates code sample for creating a {@link ConfigurationClient} + * + * @return An instance of {@link ConfigurationClient} + * @throws IllegalStateException If configuration credentials cannot be created + */ + public ConfigurationClient createSyncConfigurationClient() { + String connectionString = getConnectionString(); + // BEGIN: com.azure.data.applicationconfig.configurationclient.instantiation + ConfigurationClient configurationClient = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + // END: com.azure.data.applicationconfig.configurationclient.instantiation + return configurationClient; + } + + /** + * Generates code sample for using {@link ConfigurationClient#addConfigurationSetting(String, String, String)} + */ + public void addConfigurationSetting() { + ConfigurationClient configurationClient = createSyncConfigurationClient(); + // BEGIN: com.azure.data.appconfiguration.ConfigurationClient.addConfigurationSetting#String-String-String + ConfigurationSetting result = configurationClient + .addConfigurationSetting("prodDBConnection", "westUS", "db_connection"); + System.out.printf("Key: %s, Label: %s, Value: %s", result.getKey(), result.getLabel(), result.getValue()); + // END: com.azure.data.appconfiguration.ConfigurationClient.addConfigurationSetting#String-String-String + + /** + Generates code sample for using + {@link ConfigurationClient#addConfigurationSetting(ConfigurationSetting)} + */ + // BEGIN: com.azure.data.appconfiguration.ConfigurationClient.addConfigurationSetting#ConfigurationSetting + ConfigurationSetting setting = configurationClient.addConfigurationSetting(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS") + .setValue("db_connection")); + System.out.printf("Key: %s, Label: %s, Value: %s", setting.getKey(), setting.getLabel(), setting.getValue()); + // END: com.azure.data.appconfiguration.ConfigurationClient.addConfigurationSetting#ConfigurationSetting + + /** + Generates code sample for using + {@link ConfigurationClient#addConfigurationSettingWithResponse(ConfigurationSetting, Context)} + */ + // BEGIN: com.azure.data.appconfiguration.ConfigurationClient.addConfigurationSettingWithResponse#ConfigurationSetting-Context + Response responseResultSetting = configurationClient + .addConfigurationSettingWithResponse(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS") + .setValue("db_connection"), + new Context(key1, value1)); + ConfigurationSetting resultSetting = responseResultSetting.getValue(); + System.out.printf("Key: %s, Label: %s, Value: %s", resultSetting.getKey(), resultSetting.getLabel(), + resultSetting.getValue()); + // END: com.azure.data.appconfiguration.ConfigurationClient.addConfigurationSettingWithResponse#ConfigurationSetting-Context + } + + /** + * Generates code sample for using {@link ConfigurationClient#setConfigurationSetting(String, String, String)} + */ + public void setConfigurationSetting() { + ConfigurationClient configurationClient = createSyncConfigurationClient(); + // BEGIN: com.azure.data.appconfiguration.ConfigurationClient.setConfigurationSetting#String-String-String + ConfigurationSetting result = configurationClient + .setConfigurationSetting("prodDBConnection", "westUS", "db_connection"); + System.out.printf("Key: %s, Label: %s, Value: %s", result.getKey(), result.getLabel(), result.getValue()); + + // Update the value of the setting to "updated_db_connection". + result = configurationClient.setConfigurationSetting("prodDBConnection", "westUS", "updated_db_connection"); + System.out.printf("Key: %s, Label: %s, Value: %s", result.getKey(), result.getLabel(), result.getValue()); + // END: com.azure.data.appconfiguration.ConfigurationClient.setConfigurationSetting#String-String-String + + // BEGIN: com.azure.data.appconfiguration.ConfigurationClient.setConfigurationSetting#ConfigurationSetting + ConfigurationSetting setting = configurationClient.setConfigurationSetting(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS") + .setValue("db_connection")); + System.out.printf("Key: %s, Label: %s, Value: %s", setting.getKey(), setting.getLabel(), setting.getValue()); + + // Update the value of the setting to "updated_db_connection". + setting = configurationClient.setConfigurationSetting(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS") + .setValue("updated_db_connection")); + System.out.printf("Key: %s, Label: %s, Value: %s", setting.getKey(), setting.getLabel(), setting.getValue()); + // END: com.azure.data.appconfiguration.ConfigurationClient.setConfigurationSetting#ConfigurationSetting + + /** + * Generates code sample for using + * {@link ConfigurationClient#setConfigurationSettingWithResponse(ConfigurationSetting, boolean, Context)} + */ + // BEGIN: com.azure.data.appconfiguration.ConfigurationClient.setConfigurationSettingWithResponse#ConfigurationSetting-boolean-Context + // Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection" + Response responseSetting = configurationClient.setConfigurationSettingWithResponse( + new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS") + .setValue("db_connection"), + false, + new Context(key2, value2)); + ConfigurationSetting initSetting = responseSetting.getValue(); + System.out.printf("Key: %s, Value: %s", initSetting.getKey(), initSetting.getValue()); + + // Update the value of the setting to "updated_db_connection". + responseSetting = configurationClient.setConfigurationSettingWithResponse(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS") + .setValue("updated_db_connection"), + false, + new Context(key2, value2)); + ConfigurationSetting updatedSetting = responseSetting.getValue(); + System.out.printf("Key: %s, Value: %s", updatedSetting.getKey(), updatedSetting.getValue()); + // END: com.azure.data.appconfiguration.ConfigurationClient.setConfigurationSettingWithResponse#ConfigurationSetting-boolean-Context + } + + /** + * Generates code sample for using {@link ConfigurationClient#getConfigurationSetting(String, String)} + */ + public void getConfigurationSetting() { + ConfigurationClient configurationClient = createSyncConfigurationClient(); + + // BEGIN: com.azure.data.applicationconfig.configurationclient.getConfigurationSetting#string-string + ConfigurationSetting resultNoDateTime = configurationClient.getConfigurationSetting("prodDBConnection", "westUS"); + System.out.printf("Key: %s, Value: %s", resultNoDateTime.getKey(), resultNoDateTime.getValue()); + // END: com.azure.data.applicationconfig.configurationclient.getConfigurationSetting#string-string + + /** + * Generates code sample for using {@link ConfigurationClient#getConfigurationSetting(String, String, OffsetDateTime)} + */ + // BEGIN: com.azure.data.applicationconfig.configurationclient.getConfigurationSetting#string-string-OffsetDateTime + ConfigurationSetting result = + configurationClient.getConfigurationSetting("prodDBConnection", "westUS", null); + System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); + // END: com.azure.data.applicationconfig.configurationclient.getConfigurationSetting#string-string-OffsetDateTime + + // BEGIN: com.azure.data.applicationconfig.configurationclient.getConfigurationSetting#ConfigurationSetting + ConfigurationSetting setting = configurationClient.getConfigurationSetting(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS")); + System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue()); + // END: com.azure.data.applicationconfig.configurationclient.getConfigurationSetting#ConfigurationSetting + + /** + * Generates code sample for using {@link ConfigurationClient#getConfigurationSettingWithResponse( + * ConfigurationSetting, OffsetDateTime, boolean, Context)} + */ + // BEGIN: com.azure.data.applicationconfig.configurationclient.getConfigurationSettingWithResponse#ConfigurationSetting-OffsetDateTime-boolean-Context + // Retrieve the setting with the key-label "prodDBConnection"-"westUS". + Response responseResultSetting = configurationClient.getConfigurationSettingWithResponse( + new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS"), + null, + false, + new Context(key1, value1)); + System.out.printf("Key: %s, Value: %s", responseResultSetting.getValue().getKey(), + responseResultSetting.getValue().getValue()); + // END: com.azure.data.applicationconfig.configurationclient.getConfigurationSettingWithResponse#ConfigurationSetting-OffsetDateTime-boolean-Context + } + + /** + * Generates code sample for using {@link ConfigurationClient#deleteConfigurationSetting(String, String)} + */ + public void deleteConfigurationSetting() { + ConfigurationClient configurationClient = createSyncConfigurationClient(); + // BEGIN: com.azure.data.applicationconfig.configurationclient.deleteConfigurationSetting#string-string + ConfigurationSetting result = configurationClient.deleteConfigurationSetting("prodDBConnection", "westUS"); + System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); + // END: com.azure.data.applicationconfig.configurationclient.deleteConfigurationSetting#string-string + + // BEGIN: com.azure.data.applicationconfig.configurationclient.deleteConfigurationSetting#ConfigurationSetting + ConfigurationSetting setting = configurationClient.deleteConfigurationSetting(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS")); + System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue()); + // END: com.azure.data.applicationconfig.configurationclient.deleteConfigurationSetting#ConfigurationSetting + + /** + * Generates code sample for using + * {@link ConfigurationClient#deleteConfigurationSettingWithResponse(ConfigurationSetting, Context)} + */ + // BEGIN: com.azure.data.applicationconfig.configurationclient.deleteConfigurationSettingWithResponse#ConfigurationSetting-boolean-Context + Response responseSetting = configurationClient.deleteConfigurationSettingWithResponse( + new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS"), + false, + new Context(key2, value2)); + System.out.printf( + "Key: %s, Value: %s", responseSetting.getValue().getKey(), responseSetting.getValue().getValue()); + // END: com.azure.data.applicationconfig.configurationclient.deleteConfigurationSettingWithResponse#ConfigurationSetting-boolean-Context + } + + /** + * Generates code sample for using {@link ConfigurationClient#setReadOnly(String, String, boolean)} + */ + public void lockSettingsCodeSnippet() { + ConfigurationClient configurationClient = createSyncConfigurationClient(); + // BEGIN: com.azure.data.applicationconfig.configurationclient.setReadOnly#string-string-boolean + ConfigurationSetting result = configurationClient.setReadOnly("prodDBConnection", "westUS", true); + System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); + // END: com.azure.data.applicationconfig.configurationclient.setReadOnly#string-string-boolean + + // BEGIN: com.azure.data.applicationconfig.configurationclient.setReadOnly#ConfigurationSetting-boolean + ConfigurationSetting setting = configurationClient.setReadOnly(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS"), + true); + System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue()); + // END: com.azure.data.applicationconfig.configurationclient.setReadOnly#ConfigurationSetting-boolean + + /** + * Generates code sample for using {@link ConfigurationClient#setReadOnlyWithResponse(ConfigurationSetting, Boolean, Context)} + */ + // BEGIN: com.azure.data.applicationconfig.configurationclient.setReadOnlyWithResponse#ConfigurationSetting-Boolean-Context + ConfigurationSetting resultSetting = configurationClient.setReadOnlyWithResponse(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS"), + true, + Context.NONE) + .getValue(); + System.out.printf("Key: %s, Value: %s", resultSetting.getKey(), resultSetting.getValue()); + // END: com.azure.data.applicationconfig.configurationclient.setReadOnlyWithResponse#ConfigurationSetting-Boolean-Context + } + + /** + * Generates code sample for using {@link ConfigurationClient#setReadOnly(String, String, boolean)} + */ + public void unlockSettingsCodeSnippet() { + ConfigurationClient configurationClient = createSyncConfigurationClient(); + // BEGIN: com.azure.data.applicationconfig.configurationclient.setReadOnly#string-string-boolean-clearReadOnly + ConfigurationSetting result = configurationClient.setReadOnly("prodDBConnection", "westUS", false); + System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); + // END: com.azure.data.applicationconfig.configurationclient.setReadOnly#string-string-boolean-clearReadOnly + + // BEGIN: com.azure.data.applicationconfig.configurationclient.setReadOnly#ConfigurationSetting-boolean-clearReadOnly + ConfigurationSetting setting = configurationClient.setReadOnly(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS"), + false); + System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue()); + // END: com.azure.data.applicationconfig.configurationclient.setReadOnly#ConfigurationSetting-boolean-clearReadOnly + + /** + * Generates code sample for using + * {@link ConfigurationClient#setReadOnlyWithResponse(ConfigurationSetting, Boolean, Context)} + */ + // BEGIN: com.azure.data.applicationconfig.configurationclient.setReadOnlyWithResponse#ConfigurationSetting-boolean-Context-ClearReadOnly + Response responseSetting = configurationClient + .setConfigurationSettingWithResponse( + new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS"), false, + new Context(key2, value2)); + System.out.printf("Key: %s, Value: %s", responseSetting.getValue().getKey(), + responseSetting.getValue().getValue()); + // END: com.azure.data.applicationconfig.configurationclient.setReadOnlyWithResponse#ConfigurationSetting-boolean-Context-ClearReadOnly + } + + /** + * Generates code sample for using {@link ConfigurationClient#listConfigurationSettings(SettingSelector)} + */ + public void listConfigurationSettings() { + ConfigurationClient configurationClient = createSyncConfigurationClient(); + // BEGIN: com.azure.data.applicationconfig.configurationclient.listConfigurationSettings#settingSelector + SettingSelector settingSelector = new SettingSelector().setKeyFilter("prodDBConnection"); + configurationClient.listConfigurationSettings(settingSelector).forEach(setting -> { + System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue()); + }); + // END: com.azure.data.applicationconfig.configurationclient.listConfigurationSettings#settingSelector + } + + /** + * Generates code sample for using {@link ConfigurationClient#listConfigurationSettings(SettingSelector, Context)} + */ + public void listConfigurationSettingsContext() { + ConfigurationClient configurationClient = createSyncConfigurationClient(); + // BEGIN: com.azure.data.applicationconfig.configurationclient.listConfigurationSettings#settingSelector-context + SettingSelector settingSelector = new SettingSelector().setKeyFilter("prodDBConnection"); + Context ctx = new Context(key2, value2); + configurationClient.listConfigurationSettings(settingSelector, ctx).forEach(setting -> { + System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue()); + }); + // END: com.azure.data.applicationconfig.configurationclient.listConfigurationSettings#settingSelector-context + } + + /** + * Generates code sample for using {@link ConfigurationClient#listConfigurationSettingsForSnapshot(String)} + */ + public void listConfigurationSettingsForSnapshot() { + ConfigurationClient configurationClient = createSyncConfigurationClient(); + // BEGIN: com.azure.data.applicationconfig.configurationclient.listConfigurationSettingsForSnapshot + String snapshotName = "{snapshotName}"; + configurationClient.listConfigurationSettingsForSnapshot(snapshotName).forEach(setting -> { + System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue()); + }); + // END: com.azure.data.applicationconfig.configurationclient.listConfigurationSettingsForSnapshot + } + + /** + * Generates code sample for using {@link ConfigurationClient#listConfigurationSettingsForSnapshot(String, List, Context)} + */ + public void listConfigurationSettingsForSnapshotMaxOverload() { + ConfigurationClient configurationClient = createSyncConfigurationClient(); + // BEGIN: com.azure.data.applicationconfig.configurationclient.listConfigurationSettingsForSnapshotMaxOverload + String snapshotName = "{snapshotName}"; + List fields = Arrays.asList(SettingFields.KEY); + Context ctx = new Context(key2, value2); + configurationClient.listConfigurationSettingsForSnapshot(snapshotName, fields, ctx) + .forEach(setting -> System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue())); + // END: com.azure.data.applicationconfig.configurationclient.listConfigurationSettingsForSnapshotMaxOverload + } + + /** + * Generates code sample for using {@link ConfigurationClient#listRevisions(SettingSelector)} + */ + public void listRevisions() { + ConfigurationClient configurationClient = createSyncConfigurationClient(); + // BEGIN: com.azure.data.applicationconfig.configurationclient.listRevisions#settingSelector + SettingSelector settingSelector = new SettingSelector().setKeyFilter("prodDBConnection"); + configurationClient.listRevisions(settingSelector).streamByPage().forEach(resp -> { + System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(), + resp.getRequest().getUrl(), resp.getStatusCode()); + resp.getItems().forEach(value -> { + System.out.printf("Response value is %d %n", value); + }); + }); + // END: com.azure.data.applicationconfig.configurationclient.listRevisions#settingSelector + } + + /** + * Generates code sample for using {@link ConfigurationClient#listRevisions(SettingSelector, Context)} + */ + public void listRevisionsContext() { + ConfigurationClient configurationClient = createSyncConfigurationClient(); + // BEGIN: com.azure.data.applicationconfig.configurationclient.listRevisions#settingSelector-context + SettingSelector settingSelector = new SettingSelector().setKeyFilter("prodDBConnection"); + Context ctx = new Context(key2, value2); + configurationClient.listRevisions(settingSelector, ctx).forEach(setting -> { + System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue()); + }); + // END: com.azure.data.applicationconfig.configurationclient.listRevisions#settingSelector-context + } + + /** + * Code snippets for {@link ConfigurationClient#beginCreateSnapshot(String, ConfigurationSnapshot, Context)}} + */ + public void beginCreateSnapshotMaxOverload() { + ConfigurationClient client = createSyncConfigurationClient(); + // BEGIN: com.azure.data.appconfiguration.configurationclient.beginCreateSnapshotMaxOverload + List filters = new ArrayList<>(); + // Key Name also supports RegExp but only support prefix end with "*", such as "k*" and is case-sensitive. + filters.add(new ConfigurationSettingsFilter("{keyName}")); + String snapshotName = "{snapshotName}"; + Context ctx = new Context(key2, value2); + + SyncPoller poller = + client.beginCreateSnapshot(snapshotName, + new ConfigurationSnapshot(filters).setRetentionPeriod(Duration.ofHours(1)), ctx); + poller.setPollInterval(Duration.ofSeconds(10)); + poller.waitForCompletion(); + ConfigurationSnapshot snapshot = poller.getFinalResult(); + + System.out.printf("Snapshot name=%s is created at %s%n", snapshot.getName(), snapshot.getCreatedAt()); + // END: com.azure.data.appconfiguration.configurationclient.beginCreateSnapshotMaxOverload + } + + /** + * Code snippets for {@link ConfigurationClient#getSnapshot(String)} + */ + public void getSnapshotByName() { + ConfigurationClient client = createSyncConfigurationClient(); + // BEGIN: com.azure.data.appconfiguration.configurationclient.getSnapshotByName + String snapshotName = "{snapshotName}"; + ConfigurationSnapshot getSnapshot = client.getSnapshot(snapshotName); + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + getSnapshot.getName(), getSnapshot.getCreatedAt(), getSnapshot.getStatus()); + // END: com.azure.data.appconfiguration.configurationclient.getSnapshotByName + } + + /** + * Code snippets for {@link ConfigurationClient#getSnapshotWithResponse(String, List, Context)} + */ + public void getSnapshotByNameMaxOverload() { + ConfigurationClient client = createSyncConfigurationClient(); + // BEGIN: com.azure.data.appconfiguration.configurationclient.getSnapshotByNameMaxOverload + String snapshotName = "{snapshotName}"; + Context ctx = new Context(key2, value2); + ConfigurationSnapshot getSnapshot = client.getSnapshotWithResponse( + snapshotName, + Arrays.asList(SnapshotFields.NAME, SnapshotFields.CREATED_AT, SnapshotFields.STATUS, SnapshotFields.FILTERS), + ctx) + .getValue(); + // Only properties `name`, `createAt`, `status` and `filters` have value, and expect null or + // empty value other than the `fields` specified in the request. + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + getSnapshot.getName(), getSnapshot.getCreatedAt(), getSnapshot.getStatus()); + List filters = getSnapshot.getFilters(); + for (ConfigurationSettingsFilter filter : filters) { + System.out.printf("Snapshot filter key=%s, label=%s.%n", filter.getKey(), filter.getLabel()); + } + // END: com.azure.data.appconfiguration.configurationclient.getSnapshotByNameMaxOverload + } + + /** + * Code snippets for {@link ConfigurationClient#archiveSnapshot(String)} + */ + public void archiveSnapshotByName() { + ConfigurationClient client = createSyncConfigurationClient(); + // BEGIN: com.azure.data.appconfiguration.configurationclient.archiveSnapshotByName + String snapshotName = "{snapshotName}"; + ConfigurationSnapshot archivedSnapshot = client.archiveSnapshot(snapshotName); + System.out.printf("Archived snapshot name=%s is created at %s, snapshot status is %s.%n", + archivedSnapshot.getName(), archivedSnapshot.getCreatedAt(), archivedSnapshot.getStatus()); + // END: com.azure.data.appconfiguration.configurationclient.archiveSnapshotByName + } + + /** + * Code snippets for {@link ConfigurationClient#archiveSnapshotWithResponse(String, MatchConditions, Context)} + */ + public void archiveSnapshotByNameMaxOverload() { + ConfigurationClient client = createSyncConfigurationClient(); + + // BEGIN: com.azure.data.appconfiguration.configurationclient.archiveSnapshotByNameMaxOverload + String snapshotName = "{snapshotName}"; + MatchConditions matchConditions = new MatchConditions().setIfMatch("{etag}"); + Context ctx = new Context(key2, value2); + + ConfigurationSnapshot archivedSnapshot = client.archiveSnapshotWithResponse(snapshotName, matchConditions, ctx) + .getValue(); + System.out.printf("Archived snapshot name=%s is created at %s, snapshot status is %s.%n", + archivedSnapshot.getName(), archivedSnapshot.getCreatedAt(), archivedSnapshot.getStatus()); + // END: com.azure.data.appconfiguration.configurationclient.archiveSnapshotByNameMaxOverload + } + + /** + * Code snippets for {@link ConfigurationClient#recoverSnapshot(String)} + */ + public void recoverSnapshotByName() { + ConfigurationClient client = createSyncConfigurationClient(); + // BEGIN: com.azure.data.appconfiguration.configurationclient.recoverSnapshotByName + String snapshotName = "{snapshotName}"; + ConfigurationSnapshot recoveredSnapshot = client.recoverSnapshot(snapshotName); + System.out.printf("Recovered snapshot name=%s is created at %s, snapshot status is %s.%n", + recoveredSnapshot.getName(), recoveredSnapshot.getCreatedAt(), recoveredSnapshot.getStatus()); + // END: com.azure.data.appconfiguration.configurationclient.recoverSnapshotByName + } + + /** + * Code snippets for {@link ConfigurationClient#recoverSnapshotWithResponse(String, MatchConditions, Context)} + */ + public void recoverSnapshotMaxOverload() { + ConfigurationClient client = createSyncConfigurationClient(); + + + // BEGIN: com.azure.data.appconfiguration.configurationclient.recoverSnapshotMaxOverload + String snapshotName = "{snapshotName}"; + MatchConditions matchConditions = new MatchConditions().setIfMatch("{etag}"); + Context ctx = new Context(key2, value2); + + ConfigurationSnapshot recoveredSnapshot = client.recoverSnapshotWithResponse(snapshotName, matchConditions, ctx) + .getValue(); + System.out.printf("Recovered snapshot name=%s is created at %s, snapshot status is %s.%n", + recoveredSnapshot.getName(), recoveredSnapshot.getCreatedAt(), recoveredSnapshot.getStatus()); + // END: com.azure.data.appconfiguration.configurationclient.recoverSnapshotMaxOverload + } + + /** + * Code snippets for {@link ConfigurationClient#listSnapshots(SnapshotSelector)} + */ + public void listSnapshots() { + ConfigurationClient client = createSyncConfigurationClient(); + // BEGIN: com.azure.data.appconfiguration.configurationclient.listSnapshots + String snapshotNameFilter = "{snapshotNamePrefix}*"; + client.listSnapshots(new SnapshotSelector().setNameFilter(snapshotNameFilter)) + .forEach(snapshotResult -> { + System.out.printf("Listed Snapshot name = %s is created at %s, snapshot status is %s.%n", + snapshotResult.getName(), snapshotResult.getCreatedAt(), snapshotResult.getStatus()); + }); + // END: com.azure.data.appconfiguration.configurationclient.listSnapshots + } + + /** + * Code snippets for {@link ConfigurationClient#listSnapshots(SnapshotSelector, Context)} + */ + public void listSnapshotsMaxOverload() { + ConfigurationClient client = createSyncConfigurationClient(); + // BEGIN: com.azure.data.appconfiguration.configurationclient.listSnapshotsMaxOverload + String snapshotNameFilter = "{snapshotNamePrefix}*"; + Context ctx = new Context(key2, value2); + + client.listSnapshots(new SnapshotSelector().setNameFilter(snapshotNameFilter), ctx) + .forEach(snapshotResult -> { + System.out.printf("Listed Snapshot name = %s is created at %s, snapshot status is %s.%n", + snapshotResult.getName(), snapshotResult.getCreatedAt(), snapshotResult.getStatus()); + }); + // END: com.azure.data.appconfiguration.configurationclient.listSnapshotsMaxOverload + } + + /** + * Code snippets for {@link ConfigurationClient#listLabels()} + */ + public void listAllLabels() { + // BEGIN: com.azure.data.appconfiguration.configurationclient.listAllLabels + client.listLabels() + .forEach(label -> { + System.out.println("label name = " + label.getName()); + }); + // END: com.azure.data.appconfiguration.configurationclient.listAllLabels + } + + /** + * Code snippets for {@link ConfigurationClient#listLabels(SettingLabelSelector)} + */ + public void listLabels() { + // BEGIN: com.azure.data.appconfiguration.configurationclient.listLabels + String labelNameFilter = "{labelNamePrefix}*"; + client.listLabels(new SettingLabelSelector().setNameFilter(labelNameFilter)) + .forEach(label -> { + System.out.println("label name = " + label.getName()); + }); + // END: com.azure.data.appconfiguration.configurationclient.listLabels + } + + /** + * Code snippets for {@link ConfigurationClient#listLabels(SettingLabelSelector, Context)} + */ + public void listLabelsMaxOverload() { + // BEGIN: com.azure.data.appconfiguration.configurationclient.listLabelsMaxOverload + String labelNameFilter = "{labelNamePrefix}*"; + Context ctx = new Context(key2, value2); + + client.listLabels(new SettingLabelSelector().setNameFilter(labelNameFilter), ctx) + .forEach(label -> { + System.out.println("label name = " + label.getName()); + }); + // END: com.azure.data.appconfiguration.configurationclient.listLabelsMaxOverload + } + + /** + * Implementation not provided for this method + * + * @return {@code null} + */ + private String getConnectionString() { + return Configuration.getGlobalConfiguration().get("AZURE_APPCONFIG_CONNECTION_STRING"); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample7/v2/ConfigurationClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample7/v2/ConfigurationClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..553ec533612e --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample7/v2/ConfigurationClientJavaDocCodeSnippets.java @@ -0,0 +1,624 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.MatchConditions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Configuration; +import com.azure.core.util.Context; +import com.azure.core.util.polling.PollOperationDetails; +import com.azure.core.util.polling.SyncPoller; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.ConfigurationSettingsFilter; +import com.azure.data.appconfiguration.models.ConfigurationSnapshot; +import com.azure.data.appconfiguration.models.SettingLabelSelector; +import com.azure.data.appconfiguration.models.SettingFields; +import com.azure.data.appconfiguration.models.SettingSelector; +import com.azure.data.appconfiguration.models.SnapshotFields; +import com.azure.data.appconfiguration.models.SnapshotSelector; + +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * This class contains code samples for generating javadocs through doclets for {@link ConfigurationClient} + */ +public final class ConfigurationClientJavaDocCodeSnippets { + + private String key1 = "key1"; + private String key2 = "key2"; + private String value1 = "val1"; + private String value2 = "val2"; + + ConfigurationClient client = createSyncConfigurationClient(); + + /** + * Generates code sample for creating a {@link ConfigurationClient} + * + * @return An instance of {@link ConfigurationClient} + * @throws IllegalStateException If configuration credentials cannot be created. + */ + public ConfigurationClient createAsyncConfigurationClientWithPipeline() { + + String connectionString = getConnectionString(); + // BEGIN: com.azure.data.applicationconfig.configurationclient.pipeline.instantiation + HttpPipeline pipeline = new HttpPipelineBuilder() + .policies(/* add policies */) + .build(); + + ConfigurationClient configurationClient = new ConfigurationClientBuilder() + .pipeline(pipeline) + .endpoint("https://dummy.azure.net/") + .connectionString(connectionString) + .buildClient(); + // END: com.azure.data.applicationconfig.configurationclient.pipeline.instantiation + return configurationClient; + } + + /** + * Generates code sample for creating a {@link ConfigurationClient} + * + * @return An instance of {@link ConfigurationClient} + * @throws IllegalStateException If configuration credentials cannot be created + */ + public ConfigurationAsyncClient createAsyncConfigurationClient() { + String connectionString = getConnectionString(); + // BEGIN: com.azure.data.applicationconfig.async.configurationclient.instantiation + ConfigurationAsyncClient configurationAsyncClient = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + // END: com.azure.data.applicationconfig.async.configurationclient.instantiation + return configurationAsyncClient; + } + + /** + * Generates code sample for creating a {@link ConfigurationClient} + * + * @return An instance of {@link ConfigurationClient} + * @throws IllegalStateException If configuration credentials cannot be created + */ + public ConfigurationClient createSyncConfigurationClient() { + String connectionString = getConnectionString(); + // BEGIN: com.azure.data.applicationconfig.configurationclient.instantiation + ConfigurationClient configurationClient = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + // END: com.azure.data.applicationconfig.configurationclient.instantiation + return configurationClient; + } + + /** + * Generates code sample for using {@link ConfigurationClient#addConfigurationSetting(String, String, String)} + */ + public void addConfigurationSetting() { + ConfigurationClient configurationClient = createSyncConfigurationClient(); + // BEGIN: com.azure.data.appconfiguration.ConfigurationClient.addConfigurationSetting#String-String-String + ConfigurationSetting result = configurationClient + .addConfigurationSetting("prodDBConnection", "westUS", "db_connection"); + System.out.printf("Key: %s, Label: %s, Value: %s", result.getKey(), result.getLabel(), result.getValue()); + // END: com.azure.data.appconfiguration.ConfigurationClient.addConfigurationSetting#String-String-String + + /** + Generates code sample for using + {@link ConfigurationClient#addConfigurationSetting(ConfigurationSetting)} + */ + // BEGIN: com.azure.data.appconfiguration.ConfigurationClient.addConfigurationSetting#ConfigurationSetting + ConfigurationSetting setting = configurationClient.addConfigurationSetting(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS") + .setValue("db_connection")); + System.out.printf("Key: %s, Label: %s, Value: %s", setting.getKey(), setting.getLabel(), setting.getValue()); + // END: com.azure.data.appconfiguration.ConfigurationClient.addConfigurationSetting#ConfigurationSetting + + /** + Generates code sample for using + {@link ConfigurationClient#addConfigurationSettingWithResponse(ConfigurationSetting, Context)} + */ + // BEGIN: com.azure.data.appconfiguration.ConfigurationClient.addConfigurationSettingWithResponse#ConfigurationSetting-Context + Response responseResultSetting = configurationClient + .addConfigurationSettingWithResponse(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS") + .setValue("db_connection"), + new Context(key1, value1)); + ConfigurationSetting resultSetting = responseResultSetting.getValue(); + System.out.printf("Key: %s, Label: %s, Value: %s", resultSetting.getKey(), resultSetting.getLabel(), + resultSetting.getValue()); + // END: com.azure.data.appconfiguration.ConfigurationClient.addConfigurationSettingWithResponse#ConfigurationSetting-Context + } + + /** + * Generates code sample for using {@link ConfigurationClient#setConfigurationSetting(String, String, String)} + */ + public void setConfigurationSetting() { + ConfigurationClient configurationClient = createSyncConfigurationClient(); + // BEGIN: com.azure.data.appconfiguration.ConfigurationClient.setConfigurationSetting#String-String-String + ConfigurationSetting result = configurationClient + .setConfigurationSetting("prodDBConnection", "westUS", "db_connection"); + System.out.printf("Key: %s, Label: %s, Value: %s", result.getKey(), result.getLabel(), result.getValue()); + + // Update the value of the setting to "updated_db_connection". + result = configurationClient.setConfigurationSetting("prodDBConnection", "westUS", "updated_db_connection"); + System.out.printf("Key: %s, Label: %s, Value: %s", result.getKey(), result.getLabel(), result.getValue()); + // END: com.azure.data.appconfiguration.ConfigurationClient.setConfigurationSetting#String-String-String + + // BEGIN: com.azure.data.appconfiguration.ConfigurationClient.setConfigurationSetting#ConfigurationSetting + ConfigurationSetting setting = configurationClient.setConfigurationSetting(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS") + .setValue("db_connection")); + System.out.printf("Key: %s, Label: %s, Value: %s", setting.getKey(), setting.getLabel(), setting.getValue()); + + // Update the value of the setting to "updated_db_connection". + setting = configurationClient.setConfigurationSetting(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS") + .setValue("updated_db_connection")); + System.out.printf("Key: %s, Label: %s, Value: %s", setting.getKey(), setting.getLabel(), setting.getValue()); + // END: com.azure.data.appconfiguration.ConfigurationClient.setConfigurationSetting#ConfigurationSetting + + /** + * Generates code sample for using + * {@link ConfigurationClient#setConfigurationSettingWithResponse(ConfigurationSetting, boolean, Context)} + */ + // BEGIN: com.azure.data.appconfiguration.ConfigurationClient.setConfigurationSettingWithResponse#ConfigurationSetting-boolean-Context + // Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection" + Response responseSetting = configurationClient.setConfigurationSettingWithResponse( + new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS") + .setValue("db_connection"), + false, + new Context(key2, value2)); + ConfigurationSetting initSetting = responseSetting.getValue(); + System.out.printf("Key: %s, Value: %s", initSetting.getKey(), initSetting.getValue()); + + // Update the value of the setting to "updated_db_connection". + responseSetting = configurationClient.setConfigurationSettingWithResponse(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS") + .setValue("updated_db_connection"), + false, + new Context(key2, value2)); + ConfigurationSetting updatedSetting = responseSetting.getValue(); + System.out.printf("Key: %s, Value: %s", updatedSetting.getKey(), updatedSetting.getValue()); + // END: com.azure.data.appconfiguration.ConfigurationClient.setConfigurationSettingWithResponse#ConfigurationSetting-boolean-Context + } + + /** + * Generates code sample for using {@link ConfigurationClient#getConfigurationSetting(String, String)} + */ + public void getConfigurationSetting() { + ConfigurationClient configurationClient = createSyncConfigurationClient(); + + // BEGIN: com.azure.data.applicationconfig.configurationclient.getConfigurationSetting#string-string + ConfigurationSetting resultNoDateTime = configurationClient.getConfigurationSetting("prodDBConnection", "westUS"); + System.out.printf("Key: %s, Value: %s", resultNoDateTime.getKey(), resultNoDateTime.getValue()); + // END: com.azure.data.applicationconfig.configurationclient.getConfigurationSetting#string-string + + /** + * Generates code sample for using {@link ConfigurationClient#getConfigurationSetting(String, String, OffsetDateTime)} + */ + // BEGIN: com.azure.data.applicationconfig.configurationclient.getConfigurationSetting#string-string-OffsetDateTime + ConfigurationSetting result = + configurationClient.getConfigurationSetting("prodDBConnection", "westUS", null); + System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); + // END: com.azure.data.applicationconfig.configurationclient.getConfigurationSetting#string-string-OffsetDateTime + + // BEGIN: com.azure.data.applicationconfig.configurationclient.getConfigurationSetting#ConfigurationSetting + ConfigurationSetting setting = configurationClient.getConfigurationSetting(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS")); + System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue()); + // END: com.azure.data.applicationconfig.configurationclient.getConfigurationSetting#ConfigurationSetting + + /** + * Generates code sample for using {@link ConfigurationClient#getConfigurationSettingWithResponse( + * ConfigurationSetting, OffsetDateTime, boolean, Context)} + */ + // BEGIN: com.azure.data.applicationconfig.configurationclient.getConfigurationSettingWithResponse#ConfigurationSetting-OffsetDateTime-boolean-Context + // Retrieve the setting with the key-label "prodDBConnection"-"westUS". + Response responseResultSetting = configurationClient.getConfigurationSettingWithResponse( + new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS"), + null, + false, + new Context(key1, value1)); + System.out.printf("Key: %s, Value: %s", responseResultSetting.getValue().getKey(), + responseResultSetting.getValue().getValue()); + // END: com.azure.data.applicationconfig.configurationclient.getConfigurationSettingWithResponse#ConfigurationSetting-OffsetDateTime-boolean-Context + } + + /** + * Generates code sample for using {@link ConfigurationClient#deleteConfigurationSetting(String, String)} + */ + public void deleteConfigurationSetting() { + ConfigurationClient configurationClient = createSyncConfigurationClient(); + // BEGIN: com.azure.data.applicationconfig.configurationclient.deleteConfigurationSetting#string-string + ConfigurationSetting result = configurationClient.deleteConfigurationSetting("prodDBConnection", "westUS"); + System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); + // END: com.azure.data.applicationconfig.configurationclient.deleteConfigurationSetting#string-string + + // BEGIN: com.azure.data.applicationconfig.configurationclient.deleteConfigurationSetting#ConfigurationSetting + ConfigurationSetting setting = configurationClient.deleteConfigurationSetting(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS")); + System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue()); + // END: com.azure.data.applicationconfig.configurationclient.deleteConfigurationSetting#ConfigurationSetting + + /** + * Generates code sample for using + * {@link ConfigurationClient#deleteConfigurationSettingWithResponse(ConfigurationSetting, Context)} + */ + // BEGIN: com.azure.data.applicationconfig.configurationclient.deleteConfigurationSettingWithResponse#ConfigurationSetting-boolean-Context + Response responseSetting = configurationClient.deleteConfigurationSettingWithResponse( + new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS"), + false, + new Context(key2, value2)); + System.out.printf( + "Key: %s, Value: %s", responseSetting.getValue().getKey(), responseSetting.getValue().getValue()); + // END: com.azure.data.applicationconfig.configurationclient.deleteConfigurationSettingWithResponse#ConfigurationSetting-boolean-Context + } + + /** + * Generates code sample for using {@link ConfigurationClient#setReadOnly(String, String, boolean)} + */ + public void lockSettingsCodeSnippet() { + ConfigurationClient configurationClient = createSyncConfigurationClient(); + // BEGIN: com.azure.data.applicationconfig.configurationclient.setReadOnly#string-string-boolean + ConfigurationSetting result = configurationClient.setReadOnly("prodDBConnection", "westUS", true); + System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); + // END: com.azure.data.applicationconfig.configurationclient.setReadOnly#string-string-boolean + + // BEGIN: com.azure.data.applicationconfig.configurationclient.setReadOnly#ConfigurationSetting-boolean + ConfigurationSetting setting = configurationClient.setReadOnly(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS"), + true); + System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue()); + // END: com.azure.data.applicationconfig.configurationclient.setReadOnly#ConfigurationSetting-boolean + + /** + * Generates code sample for using {@link ConfigurationClient#setReadOnlyWithResponse(ConfigurationSetting, Boolean, Context)} + */ + // BEGIN: com.azure.data.applicationconfig.configurationclient.setReadOnlyWithResponse#ConfigurationSetting-Boolean-Context + ConfigurationSetting resultSetting = configurationClient.setReadOnlyWithResponse(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS"), + true, + Context.NONE) + .getValue(); + System.out.printf("Key: %s, Value: %s", resultSetting.getKey(), resultSetting.getValue()); + // END: com.azure.data.applicationconfig.configurationclient.setReadOnlyWithResponse#ConfigurationSetting-Boolean-Context + } + + /** + * Generates code sample for using {@link ConfigurationClient#setReadOnly(String, String, boolean)} + */ + public void unlockSettingsCodeSnippet() { + ConfigurationClient configurationClient = createSyncConfigurationClient(); + // BEGIN: com.azure.data.applicationconfig.configurationclient.setReadOnly#string-string-boolean-clearReadOnly + ConfigurationSetting result = configurationClient.setReadOnly("prodDBConnection", "westUS", false); + System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); + // END: com.azure.data.applicationconfig.configurationclient.setReadOnly#string-string-boolean-clearReadOnly + + // BEGIN: com.azure.data.applicationconfig.configurationclient.setReadOnly#ConfigurationSetting-boolean-clearReadOnly + ConfigurationSetting setting = configurationClient.setReadOnly(new ConfigurationSetting() + .setKey("prodDBConnection") + .setLabel("westUS"), + false); + System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue()); + // END: com.azure.data.applicationconfig.configurationclient.setReadOnly#ConfigurationSetting-boolean-clearReadOnly + + /** + * Generates code sample for using + * {@link ConfigurationClient#setReadOnlyWithResponse(ConfigurationSetting, Boolean, Context)} + */ + // BEGIN: com.azure.data.applicationconfig.configurationclient.setReadOnlyWithResponse#ConfigurationSetting-boolean-Context-ClearReadOnly + Response responseSetting = configurationClient + .setConfigurationSettingWithResponse( + new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS"), false, + new Context(key2, value2)); + System.out.printf("Key: %s, Value: %s", responseSetting.getValue().getKey(), + responseSetting.getValue().getValue()); + // END: com.azure.data.applicationconfig.configurationclient.setReadOnlyWithResponse#ConfigurationSetting-boolean-Context-ClearReadOnly + } + + /** + * Generates code sample for using {@link ConfigurationClient#listConfigurationSettings(SettingSelector)} + */ + public void listConfigurationSettings() { + ConfigurationClient configurationClient = createSyncConfigurationClient(); + // BEGIN: com.azure.data.applicationconfig.configurationclient.listConfigurationSettings#settingSelector + SettingSelector settingSelector = new SettingSelector().setKeyFilter("prodDBConnection"); + configurationClient.listConfigurationSettings(settingSelector).forEach(setting -> { + System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue()); + }); + // END: com.azure.data.applicationconfig.configurationclient.listConfigurationSettings#settingSelector + } + + /** + * Generates code sample for using {@link ConfigurationClient#listConfigurationSettings(SettingSelector, Context)} + */ + public void listConfigurationSettingsContext() { + ConfigurationClient configurationClient = createSyncConfigurationClient(); + // BEGIN: com.azure.data.applicationconfig.configurationclient.listConfigurationSettings#settingSelector-context + SettingSelector settingSelector = new SettingSelector().setKeyFilter("prodDBConnection"); + Context ctx = new Context(key2, value2); + configurationClient.listConfigurationSettings(settingSelector, ctx).forEach(setting -> { + System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue()); + }); + // END: com.azure.data.applicationconfig.configurationclient.listConfigurationSettings#settingSelector-context + } + + /** + * Generates code sample for using {@link ConfigurationClient#listConfigurationSettingsForSnapshot(String)} + */ + public void listConfigurationSettingsForSnapshot() { + ConfigurationClient configurationClient = createSyncConfigurationClient(); + // BEGIN: com.azure.data.applicationconfig.configurationclient.listConfigurationSettingsForSnapshot + String snapshotName = "{snapshotName}"; + configurationClient.listConfigurationSettingsForSnapshot(snapshotName).forEach(setting -> { + System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue()); + }); + // END: com.azure.data.applicationconfig.configurationclient.listConfigurationSettingsForSnapshot + } + + /** + * Generates code sample for using {@link ConfigurationClient#listConfigurationSettingsForSnapshot(String, List, Context)} + */ + public void listConfigurationSettingsForSnapshotMaxOverload() { + ConfigurationClient configurationClient = createSyncConfigurationClient(); + // BEGIN: com.azure.data.applicationconfig.configurationclient.listConfigurationSettingsForSnapshotMaxOverload + String snapshotName = "{snapshotName}"; + List fields = Arrays.asList(SettingFields.KEY); + Context ctx = new Context(key2, value2); + configurationClient.listConfigurationSettingsForSnapshot(snapshotName, fields, ctx) + .forEach(setting -> System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue())); + // END: com.azure.data.applicationconfig.configurationclient.listConfigurationSettingsForSnapshotMaxOverload + } + + /** + * Generates code sample for using {@link ConfigurationClient#listRevisions(SettingSelector)} + */ + public void listRevisions() { + ConfigurationClient configurationClient = createSyncConfigurationClient(); + // BEGIN: com.azure.data.applicationconfig.configurationclient.listRevisions#settingSelector + SettingSelector settingSelector = new SettingSelector().setKeyFilter("prodDBConnection"); + configurationClient.listRevisions(settingSelector).streamByPage().forEach(resp -> { + System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(), + resp.getRequest().getUrl(), resp.getStatusCode()); + resp.getItems().forEach(value -> { + System.out.printf("Response value is %d %n", value); + }); + }); + // END: com.azure.data.applicationconfig.configurationclient.listRevisions#settingSelector + } + + /** + * Generates code sample for using {@link ConfigurationClient#listRevisions(SettingSelector, Context)} + */ + public void listRevisionsContext() { + ConfigurationClient configurationClient = createSyncConfigurationClient(); + // BEGIN: com.azure.data.applicationconfig.configurationclient.listRevisions#settingSelector-context + SettingSelector settingSelector = new SettingSelector().setKeyFilter("prodDBConnection"); + Context ctx = new Context(key2, value2); + configurationClient.listRevisions(settingSelector, ctx).forEach(setting -> { + System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue()); + }); + // END: com.azure.data.applicationconfig.configurationclient.listRevisions#settingSelector-context + } + + /** + * Code snippets for {@link ConfigurationClient#beginCreateSnapshot(String, ConfigurationSnapshot, Context)}} + */ + public void beginCreateSnapshotMaxOverload() { + ConfigurationClient client = createSyncConfigurationClient(); + // BEGIN: com.azure.data.appconfiguration.configurationclient.beginCreateSnapshotMaxOverload + List filters = new ArrayList<>(); + // Key Name also supports RegExp but only support prefix end with "*", such as "k*" and is case-sensitive. + filters.add(new ConfigurationSettingsFilter("{keyName}")); + String snapshotName = "{snapshotName}"; + Context ctx = new Context(key2, value2); + + SyncPoller poller = + client.beginCreateSnapshot(snapshotName, + new ConfigurationSnapshot(filters).setRetentionPeriod(Duration.ofHours(1)), ctx); + poller.setPollInterval(Duration.ofSeconds(10)); + poller.waitForCompletion(); + ConfigurationSnapshot snapshot = poller.getFinalResult(); + + System.out.printf("Snapshot name=%s is created at %s%n", snapshot.getName(), snapshot.getCreatedAt()); + // END: com.azure.data.appconfiguration.configurationclient.beginCreateSnapshotMaxOverload + } + + /** + * Code snippets for {@link ConfigurationClient#getSnapshot(String)} + */ + public void getSnapshotByName() { + ConfigurationClient client = createSyncConfigurationClient(); + // BEGIN: com.azure.data.appconfiguration.configurationclient.getSnapshotByName + String snapshotName = "{snapshotName}"; + ConfigurationSnapshot getSnapshot = client.getSnapshot(snapshotName); + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + getSnapshot.getName(), getSnapshot.getCreatedAt(), getSnapshot.getStatus()); + // END: com.azure.data.appconfiguration.configurationclient.getSnapshotByName + } + + /** + * Code snippets for {@link ConfigurationClient#getSnapshotWithResponse(String, List, Context)} + */ + public void getSnapshotByNameMaxOverload() { + ConfigurationClient client = createSyncConfigurationClient(); + // BEGIN: com.azure.data.appconfiguration.configurationclient.getSnapshotByNameMaxOverload + String snapshotName = "{snapshotName}"; + Context ctx = new Context(key2, value2); + ConfigurationSnapshot getSnapshot = client.getSnapshotWithResponse( + snapshotName, + Arrays.asList(SnapshotFields.NAME, SnapshotFields.CREATED_AT, SnapshotFields.STATUS, SnapshotFields.FILTERS), + ctx) + .getValue(); + // Only properties `name`, `createAt`, `status` and `filters` have value, and expect null or + // empty value other than the `fields` specified in the request. + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + getSnapshot.getName(), getSnapshot.getCreatedAt(), getSnapshot.getStatus()); + List filters = getSnapshot.getFilters(); + for (ConfigurationSettingsFilter filter : filters) { + System.out.printf("Snapshot filter key=%s, label=%s.%n", filter.getKey(), filter.getLabel()); + } + // END: com.azure.data.appconfiguration.configurationclient.getSnapshotByNameMaxOverload + } + + /** + * Code snippets for {@link ConfigurationClient#archiveSnapshot(String)} + */ + public void archiveSnapshotByName() { + ConfigurationClient client = createSyncConfigurationClient(); + // BEGIN: com.azure.data.appconfiguration.configurationclient.archiveSnapshotByName + String snapshotName = "{snapshotName}"; + ConfigurationSnapshot archivedSnapshot = client.archiveSnapshot(snapshotName); + System.out.printf("Archived snapshot name=%s is created at %s, snapshot status is %s.%n", + archivedSnapshot.getName(), archivedSnapshot.getCreatedAt(), archivedSnapshot.getStatus()); + // END: com.azure.data.appconfiguration.configurationclient.archiveSnapshotByName + } + + /** + * Code snippets for {@link ConfigurationClient#archiveSnapshotWithResponse(String, MatchConditions, Context)} + */ + public void archiveSnapshotByNameMaxOverload() { + ConfigurationClient client = createSyncConfigurationClient(); + + // BEGIN: com.azure.data.appconfiguration.configurationclient.archiveSnapshotByNameMaxOverload + String snapshotName = "{snapshotName}"; + MatchConditions matchConditions = new MatchConditions().setIfMatch("{etag}"); + Context ctx = new Context(key2, value2); + + ConfigurationSnapshot archivedSnapshot = client.archiveSnapshotWithResponse(snapshotName, matchConditions, ctx) + .getValue(); + System.out.printf("Archived snapshot name=%s is created at %s, snapshot status is %s.%n", + archivedSnapshot.getName(), archivedSnapshot.getCreatedAt(), archivedSnapshot.getStatus()); + // END: com.azure.data.appconfiguration.configurationclient.archiveSnapshotByNameMaxOverload + } + + /** + * Code snippets for {@link ConfigurationClient#recoverSnapshot(String)} + */ + public void recoverSnapshotByName() { + ConfigurationClient client = createSyncConfigurationClient(); + // BEGIN: com.azure.data.appconfiguration.configurationclient.recoverSnapshotByName + String snapshotName = "{snapshotName}"; + ConfigurationSnapshot recoveredSnapshot = client.recoverSnapshot(snapshotName); + System.out.printf("Recovered snapshot name=%s is created at %s, snapshot status is %s.%n", + recoveredSnapshot.getName(), recoveredSnapshot.getCreatedAt(), recoveredSnapshot.getStatus()); + // END: com.azure.data.appconfiguration.configurationclient.recoverSnapshotByName + } + + /** + * Code snippets for {@link ConfigurationClient#recoverSnapshotWithResponse(String, MatchConditions, Context)} + */ + public void recoverSnapshotMaxOverload() { + ConfigurationClient client = createSyncConfigurationClient(); + + + // BEGIN: com.azure.data.appconfiguration.configurationclient.recoverSnapshotMaxOverload + String snapshotName = "{snapshotName}"; + MatchConditions matchConditions = new MatchConditions().setIfMatch("{etag}"); + Context ctx = new Context(key2, value2); + + ConfigurationSnapshot recoveredSnapshot = client.recoverSnapshotWithResponse(snapshotName, matchConditions, ctx) + .getValue(); + System.out.printf("Recovered snapshot name=%s is created at %s, snapshot status is %s.%n", + recoveredSnapshot.getName(), recoveredSnapshot.getCreatedAt(), recoveredSnapshot.getStatus()); + // END: com.azure.data.appconfiguration.configurationclient.recoverSnapshotMaxOverload + } + + /** + * Code snippets for {@link ConfigurationClient#listSnapshots(SnapshotSelector)} + */ + public void listSnapshots() { + ConfigurationClient client = createSyncConfigurationClient(); + // BEGIN: com.azure.data.appconfiguration.configurationclient.listSnapshots + String snapshotNameFilter = "{snapshotNamePrefix}*"; + client.listSnapshots(new SnapshotSelector().setNameFilter(snapshotNameFilter)) + .forEach(snapshotResult -> { + System.out.printf("Listed Snapshot name = %s is created at %s, snapshot status is %s.%n", + snapshotResult.getName(), snapshotResult.getCreatedAt(), snapshotResult.getStatus()); + }); + // END: com.azure.data.appconfiguration.configurationclient.listSnapshots + } + + /** + * Code snippets for {@link ConfigurationClient#listSnapshots(SnapshotSelector, Context)} + */ + public void listSnapshotsMaxOverload() { + ConfigurationClient client = createSyncConfigurationClient(); + // BEGIN: com.azure.data.appconfiguration.configurationclient.listSnapshotsMaxOverload + String snapshotNameFilter = "{snapshotNamePrefix}*"; + Context ctx = new Context(key2, value2); + + client.listSnapshots(new SnapshotSelector().setNameFilter(snapshotNameFilter), ctx) + .forEach(snapshotResult -> { + System.out.printf("Listed Snapshot name = %s is created at %s, snapshot status is %s.%n", + snapshotResult.getName(), snapshotResult.getCreatedAt(), snapshotResult.getStatus()); + }); + // END: com.azure.data.appconfiguration.configurationclient.listSnapshotsMaxOverload + } + + /** + * Code snippets for {@link ConfigurationClient#listLabels()} + */ + public void listAllLabels() { + // BEGIN: com.azure.data.appconfiguration.configurationclient.listAllLabels + client.listLabels() + .forEach(label -> { + System.out.println("label name = " + label.getName()); + }); + // END: com.azure.data.appconfiguration.configurationclient.listAllLabels + } + + /** + * Code snippets for {@link ConfigurationClient#listLabels(SettingLabelSelector)} + */ + public void listLabels() { + // BEGIN: com.azure.data.appconfiguration.configurationclient.listLabels + String labelNameFilter = "{labelNamePrefix}*"; + client.listLabels(new SettingLabelSelector().setNameFilter(labelNameFilter)) + .forEach(label -> { + System.out.println("label name = " + label.getName()); + }); + // END: com.azure.data.appconfiguration.configurationclient.listLabels + } + + /** + * Code snippets for {@link ConfigurationClient#listLabels(SettingLabelSelector, Context)} + */ + public void listLabelsMaxOverload() { + // BEGIN: com.azure.data.appconfiguration.configurationclient.listLabelsMaxOverload + String labelNameFilter = "{labelNamePrefix}*"; + Context ctx = new Context(key2, value2); + + client.listLabels(new SettingLabelSelector().setNameFilter(labelNameFilter), ctx) + .forEach(label -> { + System.out.println("label name = " + label.getName()); + }); + // END: com.azure.data.appconfiguration.configurationclient.listLabelsMaxOverload + } + + /** + * Implementation not provided for this method + * + * @return {@code null} + */ + private String getConnectionString() { + return Configuration.getGlobalConfiguration().get("AZURE_APPCONFIG_CONNECTION_STRING"); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample8/v1/ConfigurationSets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample8/v1/ConfigurationSets.java new file mode 100644 index 000000000000..73c14a02f47d --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample8/v1/ConfigurationSets.java @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.ComplexConfiguration; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; +import com.azure.json.JsonProviders; +import com.azure.json.JsonWriter; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +/** + * Sample demonstrates how to use Azure App Configuration to switch between "beta" and "production" configuration sets. + * + *

        + * In the sample, the user stores a connection string for a resource and a complex configuration object. + * {@link ComplexConfiguration} The {@link ComplexConfiguration} is serialized into a JSON string and read out from the + * service as a strongly-typed typed object. + *

        + */ +public class ConfigurationSets { + private static final String CONNECTION_STRING_KEY = "connection-string"; + private static final String COMPLEX_SETTING_KEY = "complex-setting"; + private static final String BETA = "beta"; + private static final String PRODUCTION = "production"; + + /** + * Entry point to the configuration set sample. Creates two sets of configuration values and fetches values from the + * "beta" configuration set. + * + * @param args Unused. Arguments to the program. + * @throws IOException If the service is unable to deserialize the complex configuration object. + */ + public static void main(String[] args) throws IOException { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};name={secret_value}"; + + // Instantiate a configuration client that will be used to call the configuration service. + ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + + // Demonstrates two different complex objects being stored in Azure App Configuration; one used for beta and the + // other used for production. + ComplexConfiguration betaSetting = new ComplexConfiguration() + .endpointUri("https://beta.endpoint.com") + .name("beta-name") + .numberOfInstances(1); + ComplexConfiguration productionSetting = new ComplexConfiguration() + .endpointUri("https://production.endpoint.com") + .name("production-name") + .numberOfInstances(2); + + // Adding one configuration set for beta testing and another for production to Azure App Configuration. + // blockLast() is added here to prevent execution before both sets of configuration values have been added to + // the service. + Flux.merge( + addConfigurations(client, BETA, "https://beta-storage.core.windows.net", betaSetting), + addConfigurations(client, PRODUCTION, "https://production-storage.core.windows.net", productionSetting) + ).blockLast(); + + // For your services, you can select settings with "beta" or "production" label, depending on what you want your + // services to communicate with. The sample below fetches all of the "beta" settings. + SettingSelector selector = new SettingSelector().setLabelFilter(BETA); + + client.listConfigurationSettings(selector).toStream().forEach(setting -> { + System.out.println("Key: " + setting.getKey()); + if ("application/json".equals(setting.getContentType())) { + try { + ComplexConfiguration kv = ComplexConfiguration.fromJson( + JsonProviders.createReader(setting.getValue())); + System.out.println("Value: " + kv.toString()); + } catch (IOException e) { + System.err.printf("Could not deserialize %s%n%s%n", setting.getValue(), e); + } + } else { + System.out.println("Value: " + setting.getValue()); + } + }); + + // For the BETA and PRODUCTION sets, we fetch all of the settings we created in each set, and delete them. + // Blocking so that the program does not exit before these tasks have completed. + Flux.fromArray(new String[]{BETA, PRODUCTION}) + .flatMap(set -> client.listConfigurationSettings(new SettingSelector().setLabelFilter(set))) + .map(setting -> client.deleteConfigurationSettingWithResponse(setting, false)) + .blockLast(); + } + + /* + * Adds the "connection-string" and "key-vault" configuration settings + */ + private static Mono addConfigurations(ConfigurationAsyncClient client, String configurationSet, + String storageEndpoint, ComplexConfiguration complexConfiguration) throws IOException { + ConfigurationSetting endpointSetting = new ConfigurationSetting() + .setKey(CONNECTION_STRING_KEY) + .setLabel(configurationSet) + .setValue(storageEndpoint); + + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + JsonWriter writer = JsonProviders.createWriter(outputStream)) { + complexConfiguration.toJson(writer).flush(); + + ConfigurationSetting keyVaultSetting = new ConfigurationSetting() + .setKey(COMPLEX_SETTING_KEY) + .setLabel(configurationSet) + .setValue(outputStream.toString()) + .setContentType("application/json"); + + return Flux.merge(client.addConfigurationSetting(keyVaultSetting.getKey(), keyVaultSetting.getLabel(), + keyVaultSetting.getValue()), client.addConfigurationSetting(endpointSetting.getKey(), + endpointSetting.getLabel(), endpointSetting.getValue())) + .then(); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample8/v2/ConfigurationSets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample8/v2/ConfigurationSets.java new file mode 100644 index 000000000000..73c14a02f47d --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample8/v2/ConfigurationSets.java @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.ComplexConfiguration; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; +import com.azure.json.JsonProviders; +import com.azure.json.JsonWriter; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +/** + * Sample demonstrates how to use Azure App Configuration to switch between "beta" and "production" configuration sets. + * + *

        + * In the sample, the user stores a connection string for a resource and a complex configuration object. + * {@link ComplexConfiguration} The {@link ComplexConfiguration} is serialized into a JSON string and read out from the + * service as a strongly-typed typed object. + *

        + */ +public class ConfigurationSets { + private static final String CONNECTION_STRING_KEY = "connection-string"; + private static final String COMPLEX_SETTING_KEY = "complex-setting"; + private static final String BETA = "beta"; + private static final String PRODUCTION = "production"; + + /** + * Entry point to the configuration set sample. Creates two sets of configuration values and fetches values from the + * "beta" configuration set. + * + * @param args Unused. Arguments to the program. + * @throws IOException If the service is unable to deserialize the complex configuration object. + */ + public static void main(String[] args) throws IOException { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};name={secret_value}"; + + // Instantiate a configuration client that will be used to call the configuration service. + ConfigurationAsyncClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + + // Demonstrates two different complex objects being stored in Azure App Configuration; one used for beta and the + // other used for production. + ComplexConfiguration betaSetting = new ComplexConfiguration() + .endpointUri("https://beta.endpoint.com") + .name("beta-name") + .numberOfInstances(1); + ComplexConfiguration productionSetting = new ComplexConfiguration() + .endpointUri("https://production.endpoint.com") + .name("production-name") + .numberOfInstances(2); + + // Adding one configuration set for beta testing and another for production to Azure App Configuration. + // blockLast() is added here to prevent execution before both sets of configuration values have been added to + // the service. + Flux.merge( + addConfigurations(client, BETA, "https://beta-storage.core.windows.net", betaSetting), + addConfigurations(client, PRODUCTION, "https://production-storage.core.windows.net", productionSetting) + ).blockLast(); + + // For your services, you can select settings with "beta" or "production" label, depending on what you want your + // services to communicate with. The sample below fetches all of the "beta" settings. + SettingSelector selector = new SettingSelector().setLabelFilter(BETA); + + client.listConfigurationSettings(selector).toStream().forEach(setting -> { + System.out.println("Key: " + setting.getKey()); + if ("application/json".equals(setting.getContentType())) { + try { + ComplexConfiguration kv = ComplexConfiguration.fromJson( + JsonProviders.createReader(setting.getValue())); + System.out.println("Value: " + kv.toString()); + } catch (IOException e) { + System.err.printf("Could not deserialize %s%n%s%n", setting.getValue(), e); + } + } else { + System.out.println("Value: " + setting.getValue()); + } + }); + + // For the BETA and PRODUCTION sets, we fetch all of the settings we created in each set, and delete them. + // Blocking so that the program does not exit before these tasks have completed. + Flux.fromArray(new String[]{BETA, PRODUCTION}) + .flatMap(set -> client.listConfigurationSettings(new SettingSelector().setLabelFilter(set))) + .map(setting -> client.deleteConfigurationSettingWithResponse(setting, false)) + .blockLast(); + } + + /* + * Adds the "connection-string" and "key-vault" configuration settings + */ + private static Mono addConfigurations(ConfigurationAsyncClient client, String configurationSet, + String storageEndpoint, ComplexConfiguration complexConfiguration) throws IOException { + ConfigurationSetting endpointSetting = new ConfigurationSetting() + .setKey(CONNECTION_STRING_KEY) + .setLabel(configurationSet) + .setValue(storageEndpoint); + + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + JsonWriter writer = JsonProviders.createWriter(outputStream)) { + complexConfiguration.toJson(writer).flush(); + + ConfigurationSetting keyVaultSetting = new ConfigurationSetting() + .setKey(COMPLEX_SETTING_KEY) + .setLabel(configurationSet) + .setValue(outputStream.toString()) + .setContentType("application/json"); + + return Flux.merge(client.addConfigurationSetting(keyVaultSetting.getKey(), keyVaultSetting.getLabel(), + keyVaultSetting.getValue()), client.addConfigurationSetting(endpointSetting.getKey(), + endpointSetting.getLabel(), endpointSetting.getValue())) + .then(); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample9/v1/CreateSnapshot.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample9/v1/CreateSnapshot.java new file mode 100644 index 000000000000..77964fe5cfd0 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample9/v1/CreateSnapshot.java @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.util.Context; +import com.azure.core.util.polling.PollOperationDetails; +import com.azure.core.util.polling.SyncPoller; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.ConfigurationSettingsFilter; +import com.azure.data.appconfiguration.models.ConfigurationSnapshot; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; + +/** + * Sample demonstrates how to create, retrieve, archive, recover a configuration setting snapshot, and list settings + * by snapshot name. + */ +public class CreateSnapshot { + /** + * Runs the sample demonstrates how to create, retrieve, archive, recover a configuration setting snapshot, and + * list settings by snapshot name. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Instantiate a client that will be used to call the service. + final ConfigurationClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + + System.out.println("Beginning of synchronous sample..."); + // Prepare first setting. + ConfigurationSetting setting = client.setConfigurationSetting("TestKey1", null, "value1"); + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s.%n", setting.getKey(), setting.getValue()); + // Prepare second setting. + ConfigurationSetting setting2 = client.setConfigurationSetting("TestKey2", null, "value2"); + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s.%n", setting2.getKey(), setting2.getValue()); + // Prepare the snapshot filters + List filters = new ArrayList<>(); + // Key Name also supports RegExp but only support prefix end with "*", such as "k*" and is case-sensitive. + filters.add(new ConfigurationSettingsFilter("Test*")); + + // Create a snapshot + String snapshotName = "{snapshotName}"; + SyncPoller poller = + client.beginCreateSnapshot(snapshotName, new ConfigurationSnapshot(filters), Context.NONE); + poller.setPollInterval(Duration.ofSeconds(10)); + poller.waitForCompletion(); + ConfigurationSnapshot snapshot = poller.getFinalResult(); + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + snapshot.getName(), snapshot.getCreatedAt(), snapshot.getStatus()); + + // Get the snapshot status + ConfigurationSnapshot getSnapshot = client.getSnapshot(snapshotName); + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + getSnapshot.getName(), getSnapshot.getCreatedAt(), getSnapshot.getStatus()); + + // Archive a READY snapshot + ConfigurationSnapshot archivedSnapshot = client.archiveSnapshot(snapshotName); + System.out.printf("Archived snapshot name=%s is created at %s, snapshot status is %s.%n", + archivedSnapshot.getName(), archivedSnapshot.getCreatedAt(), archivedSnapshot.getStatus()); + + // Recover the Archived snapshot + ConfigurationSnapshot recoveredSnapshot = client.recoverSnapshot(snapshotName); + System.out.printf("Recovered snapshot name=%s is created at %s, snapshot status is %s.%n", + recoveredSnapshot.getName(), recoveredSnapshot.getCreatedAt(), recoveredSnapshot.getStatus()); + + // List the configuration settings in the snapshot + client.listConfigurationSettingsForSnapshot(snapshotName).forEach( + settingInSnapshot -> { + System.out.printf("[ConfigurationSetting In Snapshot] Key: %s, Value: %s.%n", + settingInSnapshot.getKey(), settingInSnapshot.getValue()); + } + ); + + System.out.println("End of synchronous sample."); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample9/v2/CreateSnapshot.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample9/v2/CreateSnapshot.java new file mode 100644 index 000000000000..77964fe5cfd0 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-data-appconfiguration/sample9/v2/CreateSnapshot.java @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.core.util.Context; +import com.azure.core.util.polling.PollOperationDetails; +import com.azure.core.util.polling.SyncPoller; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.ConfigurationSettingsFilter; +import com.azure.data.appconfiguration.models.ConfigurationSnapshot; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; + +/** + * Sample demonstrates how to create, retrieve, archive, recover a configuration setting snapshot, and list settings + * by snapshot name. + */ +public class CreateSnapshot { + /** + * Runs the sample demonstrates how to create, retrieve, archive, recover a configuration setting snapshot, and + * list settings by snapshot name. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // The connection string value can be obtained by going to your App Configuration instance in the Azure portal + // and navigating to "Access Keys" page under the "Settings" section. + String connectionString = "endpoint={endpoint_value};id={id_value};secret={secret_value}"; + + // Instantiate a client that will be used to call the service. + final ConfigurationClient client = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + + System.out.println("Beginning of synchronous sample..."); + // Prepare first setting. + ConfigurationSetting setting = client.setConfigurationSetting("TestKey1", null, "value1"); + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s.%n", setting.getKey(), setting.getValue()); + // Prepare second setting. + ConfigurationSetting setting2 = client.setConfigurationSetting("TestKey2", null, "value2"); + System.out.printf("[SetConfigurationSetting] Key: %s, Value: %s.%n", setting2.getKey(), setting2.getValue()); + // Prepare the snapshot filters + List filters = new ArrayList<>(); + // Key Name also supports RegExp but only support prefix end with "*", such as "k*" and is case-sensitive. + filters.add(new ConfigurationSettingsFilter("Test*")); + + // Create a snapshot + String snapshotName = "{snapshotName}"; + SyncPoller poller = + client.beginCreateSnapshot(snapshotName, new ConfigurationSnapshot(filters), Context.NONE); + poller.setPollInterval(Duration.ofSeconds(10)); + poller.waitForCompletion(); + ConfigurationSnapshot snapshot = poller.getFinalResult(); + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + snapshot.getName(), snapshot.getCreatedAt(), snapshot.getStatus()); + + // Get the snapshot status + ConfigurationSnapshot getSnapshot = client.getSnapshot(snapshotName); + System.out.printf("Snapshot name=%s is created at %s, snapshot status is %s.%n", + getSnapshot.getName(), getSnapshot.getCreatedAt(), getSnapshot.getStatus()); + + // Archive a READY snapshot + ConfigurationSnapshot archivedSnapshot = client.archiveSnapshot(snapshotName); + System.out.printf("Archived snapshot name=%s is created at %s, snapshot status is %s.%n", + archivedSnapshot.getName(), archivedSnapshot.getCreatedAt(), archivedSnapshot.getStatus()); + + // Recover the Archived snapshot + ConfigurationSnapshot recoveredSnapshot = client.recoverSnapshot(snapshotName); + System.out.printf("Recovered snapshot name=%s is created at %s, snapshot status is %s.%n", + recoveredSnapshot.getName(), recoveredSnapshot.getCreatedAt(), recoveredSnapshot.getStatus()); + + // List the configuration settings in the snapshot + client.listConfigurationSettingsForSnapshot(snapshotName).forEach( + settingInSnapshot -> { + System.out.printf("[ConfigurationSetting In Snapshot] Key: %s, Value: %s.%n", + settingInSnapshot.getKey(), settingInSnapshot.getValue()); + } + ); + + System.out.println("End of synchronous sample."); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-identity/sample1/v1/JavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-identity/sample1/v1/JavaDocCodeSnippets.java new file mode 100644 index 000000000000..ea1973049395 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-identity/sample1/v1/JavaDocCodeSnippets.java @@ -0,0 +1,375 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.credential; + +import com.azure.core.credential.AccessToken; +import com.azure.core.credential.TokenCredential; +import com.azure.core.credential.TokenRequestContext; +import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.HttpMethod; +import com.azure.core.http.HttpRequest; +import com.azure.core.http.ProxyOptions; +import com.azure.core.http.ProxyOptions.Type; +import com.azure.core.util.Context; +import com.azure.identity.AuthenticationRecord; +import com.azure.identity.AuthenticationUtil; +import com.azure.identity.AuthorizationCodeCredential; +import com.azure.identity.AuthorizationCodeCredentialBuilder; +import com.azure.identity.AzureCliCredential; +import com.azure.identity.AzureCliCredentialBuilder; +import com.azure.identity.AzureDeveloperCliCredential; +import com.azure.identity.AzureDeveloperCliCredentialBuilder; +import com.azure.identity.AzurePipelinesCredential; +import com.azure.identity.AzurePipelinesCredentialBuilder; +import com.azure.identity.AzurePowerShellCredential; +import com.azure.identity.AzurePowerShellCredentialBuilder; +import com.azure.identity.ChainedTokenCredential; +import com.azure.identity.ChainedTokenCredentialBuilder; +import com.azure.identity.ClientAssertionCredential; +import com.azure.identity.ClientAssertionCredentialBuilder; +import com.azure.identity.ClientCertificateCredential; +import com.azure.identity.ClientCertificateCredentialBuilder; +import com.azure.identity.ClientSecretCredential; +import com.azure.identity.ClientSecretCredentialBuilder; +import com.azure.identity.DefaultAzureCredential; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.identity.DeviceCodeCredential; +import com.azure.identity.DeviceCodeCredentialBuilder; +import com.azure.identity.EnvironmentCredential; +import com.azure.identity.EnvironmentCredentialBuilder; +import com.azure.identity.IntelliJCredential; +import com.azure.identity.IntelliJCredentialBuilder; +import com.azure.identity.InteractiveBrowserCredential; +import com.azure.identity.InteractiveBrowserCredentialBuilder; +import com.azure.identity.ManagedIdentityCredential; +import com.azure.identity.ManagedIdentityCredentialBuilder; +import com.azure.identity.OnBehalfOfCredential; +import com.azure.identity.OnBehalfOfCredentialBuilder; +import com.azure.identity.UsernamePasswordCredential; +import com.azure.identity.UsernamePasswordCredentialBuilder; +import com.azure.identity.WorkloadIdentityCredential; +import com.azure.identity.WorkloadIdentityCredentialBuilder; +import reactor.core.publisher.Mono; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.util.function.Supplier; + +/** + * This class contains code samples for generating javadocs through doclets for azure-identity. + */ +public final class JavaDocCodeSnippets { + private String tenantId = System.getenv("AZURE_TENANT_ID"); + + private String clientId = System.getenv("AZURE_CLIENT_ID"); + private String clientSecret = System.getenv("AZURE_CLIENT_SECRET"); + private String serviceConnectionId = System.getenv("SERVICE_CONNECTION_ID"); + + private String fakeUsernamePlaceholder = "fakeUsernamePlaceholder"; + private String fakePasswordPlaceholder = "fakePasswordPlaceholder"; + + /** + * Method to insert code snippets for {@link ClientSecretCredential} + */ + public void clientSecretCredentialCodeSnippets() { + // BEGIN: com.azure.identity.credential.clientsecretcredential.construct + TokenCredential clientSecretCredential = new ClientSecretCredentialBuilder().tenantId(tenantId) + .clientId(clientId) + .clientSecret(clientSecret) + .build(); + // END: com.azure.identity.credential.clientsecretcredential.construct + + // BEGIN: com.azure.identity.credential.clientsecretcredential.constructwithproxy + TokenCredential secretCredential = new ClientSecretCredentialBuilder().tenantId(tenantId) + .clientId(clientId) + .clientSecret(clientSecret) + .proxyOptions(new ProxyOptions(Type.HTTP, new InetSocketAddress("10.21.32.43", 5465))) + .build(); + // END: com.azure.identity.credential.clientsecretcredential.constructwithproxy + } + + /** + * Method to insert code snippets for {@link ClientCertificateCredential} + */ + public void clientCertificateCredentialCodeSnippets() { + // BEGIN: com.azure.identity.credential.clientcertificatecredential.construct + TokenCredential clientCertificateCredential = new ClientCertificateCredentialBuilder().tenantId(tenantId) + .clientId(clientId) + .pemCertificate("") + .build(); + // END: com.azure.identity.credential.clientcertificatecredential.construct + + byte[] certificateBytes = new byte[0]; + + // BEGIN: com.azure.identity.credential.clientcertificatecredential.constructWithStream + ByteArrayInputStream certificateStream = new ByteArrayInputStream(certificateBytes); + TokenCredential certificateCredentialWithStream = new ClientCertificateCredentialBuilder().tenantId(tenantId) + .clientId(clientId) + .pemCertificate(certificateStream) + .build(); + // END: com.azure.identity.credential.clientcertificatecredential.constructWithStream + + // BEGIN: com.azure.identity.credential.clientcertificatecredential.constructwithproxy + TokenCredential certificateCredential = new ClientCertificateCredentialBuilder().tenantId(tenantId) + .clientId(clientId) + .pfxCertificate("", "P@s$w0rd") + .proxyOptions(new ProxyOptions(Type.HTTP, new InetSocketAddress("10.21.32.43", 5465))) + .build(); + // END: com.azure.identity.credential.clientcertificatecredential.constructwithproxy + } + + /** + * Method to insert code snippets for {@link ClientAssertionCredential} + */ + public void clientAssertionCredentialCodeSnippets() { + // BEGIN: com.azure.identity.credential.clientassertioncredential.construct + TokenCredential clientAssertionCredential = new ClientAssertionCredentialBuilder().tenantId(tenantId) + .clientId(clientId) + .clientAssertion(() -> "") + .build(); + // END: com.azure.identity.credential.clientassertioncredential.construct + + // BEGIN: com.azure.identity.credential.clientassertioncredential.constructwithproxy + TokenCredential assertionCredential = new ClientAssertionCredentialBuilder().tenantId(tenantId) + .clientId(clientId) + .clientAssertion(() -> "") + .proxyOptions(new ProxyOptions(Type.HTTP, new InetSocketAddress("10.21.32.43", 5465))) + .build(); + // END: com.azure.identity.credential.clientassertioncredential.constructwithproxy + } + + /** + * Method to insert code snippets for {@link ChainedTokenCredential} + */ + public void chainedTokenCredentialCodeSnippets() { + // BEGIN: com.azure.identity.credential.chainedtokencredential.construct + TokenCredential usernamePasswordCredential = new UsernamePasswordCredentialBuilder().clientId(clientId) + .username(fakeUsernamePlaceholder) + .password(fakePasswordPlaceholder) + .build(); + TokenCredential interactiveBrowserCredential = new InteractiveBrowserCredentialBuilder().clientId(clientId) + .port(8765) + .build(); + TokenCredential credential = new ChainedTokenCredentialBuilder().addLast(usernamePasswordCredential) + .addLast(interactiveBrowserCredential) + .build(); + // END: com.azure.identity.credential.chainedtokencredential.construct + } + + /** + * Method to insert code snippets for {@link DefaultAzureCredential} + */ + public void defaultAzureCredentialCodeSnippets() { + // BEGIN: com.azure.identity.credential.defaultazurecredential.construct + TokenCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().build(); + // END: com.azure.identity.credential.defaultazurecredential.construct + + // BEGIN: com.azure.identity.credential.defaultazurecredential.constructwithuserassignedmanagedidentity + TokenCredential dacWithUserAssignedManagedIdentity + = new DefaultAzureCredentialBuilder().managedIdentityClientId("").username("").password("").build(); + // END: com.azure.identity.credential.usernamepasswordcredential.construct + } + + /** + * Method to insert code snippets for {@link AzurePowerShellCredential} + */ + public void azurePowershellCredentialsCodeSnippets() { + // BEGIN: com.azure.identity.credential.azurepowershellcredential.construct + TokenCredential powerShellCredential = new AzurePowerShellCredentialBuilder().build(); + // END: com.azure.identity.credential.azurepowershellcredential.construct + } + + /** + * Method to insert code snippets for {@link AuthorizationCodeCredential} + */ + public void authorizationCodeCredentialsCodeSnippets() { + // BEGIN: com.azure.identity.credential.authorizationcodecredential.construct + TokenCredential authorizationCodeCredential = new AuthorizationCodeCredentialBuilder().authorizationCode( + "{authorization-code-received-at-redirectURL}") + .redirectUrl("{redirectUrl-where-authorization-code-is-received}") + .clientId("{clientId-of-application-being-authenticated") + .build(); + // END: com.azure.identity.credential.authorizationcodecredential.construct + } + + /** + * Method to insert code snippets for {@link OnBehalfOfCredential} + */ + public void oboCredentialsCodeSnippets() { + // BEGIN: com.azure.identity.credential.obocredential.construct + TokenCredential onBehalfOfCredential = new OnBehalfOfCredentialBuilder().clientId("") + .clientSecret("") + .tenantId("") + .userAssertion("") + .build(); + // END: com.azure.identity.credential.obocredential.construct + } + + /** + * Method to insert code snippets for {@link WorkloadIdentityCredential} + */ + public void workloadIdentityCredentialCodeSnippets() { + // BEGIN: com.azure.identity.credential.workloadidentitycredential.construct + TokenCredential workloadIdentityCredential = new WorkloadIdentityCredentialBuilder().clientId("") + .tenantId("") + .tokenFilePath("") + .build(); + // END: com.azure.identity.credential.workloadidentitycredential.construct + } + + /** + * Method to insert code snippets for {@link AzureDeveloperCliCredential} + */ + public void azureDeveloperCliCredentialCodeSnippets() { + // BEGIN: com.azure.identity.credential.azuredeveloperclicredential.construct + TokenCredential azureDevCliCredential = new AzureDeveloperCliCredentialBuilder().build(); + // END: com.azure.identity.credential.azuredeveloperclicredential.construct + } + + public void azurePipelinesCredentialCodeSnippets() { + + // BEGIN: com.azure.identity.credential.azurepipelinescredential.construct + // serviceConnectionId is retrieved from the portal. + // systemAccessToken is retrieved from the pipeline environment as shown. + // You may choose another name for this variable. + + String systemAccessToken = System.getenv("SYSTEM_ACCESSTOKEN"); + AzurePipelinesCredential credential = new AzurePipelinesCredentialBuilder().clientId(clientId) + .tenantId(tenantId) + .serviceConnectionId(serviceConnectionId) + .systemAccessToken(systemAccessToken) + .build(); + // END: com.azure.identity.credential.azurepipelinescredential.construct + } + + public void silentAuthenticationSnippets() { + // BEGIN: com.azure.identity.silentauthentication + String authenticationRecordPath = "path/to/authentication-record.json"; + AuthenticationRecord authenticationRecord = null; + try { + // If we have an existing record, deserialize it. + if (Files.exists(new File(authenticationRecordPath).toPath())) { + authenticationRecord = AuthenticationRecord.deserialize(new FileInputStream(authenticationRecordPath)); + } + } catch (FileNotFoundException e) { + // Handle error as appropriate. + } + + DeviceCodeCredentialBuilder builder = new DeviceCodeCredentialBuilder().clientId(clientId).tenantId(tenantId); + if (authenticationRecord != null) { + // As we have a record, configure the builder to use it. + builder.authenticationRecord(authenticationRecord); + } + DeviceCodeCredential credential = builder.build(); + TokenRequestContext trc = new TokenRequestContext().addScopes("your-appropriate-scope"); + if (authenticationRecord == null) { + // We don't have a record, so we get one and store it. The next authentication will use it. + credential.authenticate(trc).flatMap(record -> { + try { + return record.serializeAsync(new FileOutputStream(authenticationRecordPath)); + } catch (FileNotFoundException e) { + return Mono.error(e); + } + }).subscribe(); + } + + // Now the credential can be passed to another service client or used directly. + AccessToken token = credential.getTokenSync(trc); + + // END: com.azure.identity.silentauthentication + } + + public void bearerTokenProviderSampleSync() { + // BEGIN: com.azure.identity.util.getBearerTokenSupplier + DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build(); + String scope = "https://cognitiveservices.azure.com/.default"; + Supplier supplier = AuthenticationUtil.getBearerTokenSupplier(credential, scope); + + // This example simply uses the Azure SDK HTTP library to demonstrate setting the header. + // Use the token as is appropriate for your circumstances. + HttpRequest request = new HttpRequest(HttpMethod.GET, "https://www.example.com"); + request.setHeader(HttpHeaderName.AUTHORIZATION, "Bearer " + supplier.get()); + HttpClient client = HttpClient.createDefault(); + client.sendSync(request, Context.NONE); + // END: com.azure.identity.util.getBearerTokenSupplier + } + +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-identity/sample1/v2/JavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-identity/sample1/v2/JavaDocCodeSnippets.java new file mode 100644 index 000000000000..ea1973049395 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-identity/sample1/v2/JavaDocCodeSnippets.java @@ -0,0 +1,375 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.credential; + +import com.azure.core.credential.AccessToken; +import com.azure.core.credential.TokenCredential; +import com.azure.core.credential.TokenRequestContext; +import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.HttpMethod; +import com.azure.core.http.HttpRequest; +import com.azure.core.http.ProxyOptions; +import com.azure.core.http.ProxyOptions.Type; +import com.azure.core.util.Context; +import com.azure.identity.AuthenticationRecord; +import com.azure.identity.AuthenticationUtil; +import com.azure.identity.AuthorizationCodeCredential; +import com.azure.identity.AuthorizationCodeCredentialBuilder; +import com.azure.identity.AzureCliCredential; +import com.azure.identity.AzureCliCredentialBuilder; +import com.azure.identity.AzureDeveloperCliCredential; +import com.azure.identity.AzureDeveloperCliCredentialBuilder; +import com.azure.identity.AzurePipelinesCredential; +import com.azure.identity.AzurePipelinesCredentialBuilder; +import com.azure.identity.AzurePowerShellCredential; +import com.azure.identity.AzurePowerShellCredentialBuilder; +import com.azure.identity.ChainedTokenCredential; +import com.azure.identity.ChainedTokenCredentialBuilder; +import com.azure.identity.ClientAssertionCredential; +import com.azure.identity.ClientAssertionCredentialBuilder; +import com.azure.identity.ClientCertificateCredential; +import com.azure.identity.ClientCertificateCredentialBuilder; +import com.azure.identity.ClientSecretCredential; +import com.azure.identity.ClientSecretCredentialBuilder; +import com.azure.identity.DefaultAzureCredential; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.identity.DeviceCodeCredential; +import com.azure.identity.DeviceCodeCredentialBuilder; +import com.azure.identity.EnvironmentCredential; +import com.azure.identity.EnvironmentCredentialBuilder; +import com.azure.identity.IntelliJCredential; +import com.azure.identity.IntelliJCredentialBuilder; +import com.azure.identity.InteractiveBrowserCredential; +import com.azure.identity.InteractiveBrowserCredentialBuilder; +import com.azure.identity.ManagedIdentityCredential; +import com.azure.identity.ManagedIdentityCredentialBuilder; +import com.azure.identity.OnBehalfOfCredential; +import com.azure.identity.OnBehalfOfCredentialBuilder; +import com.azure.identity.UsernamePasswordCredential; +import com.azure.identity.UsernamePasswordCredentialBuilder; +import com.azure.identity.WorkloadIdentityCredential; +import com.azure.identity.WorkloadIdentityCredentialBuilder; +import reactor.core.publisher.Mono; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.util.function.Supplier; + +/** + * This class contains code samples for generating javadocs through doclets for azure-identity. + */ +public final class JavaDocCodeSnippets { + private String tenantId = System.getenv("AZURE_TENANT_ID"); + + private String clientId = System.getenv("AZURE_CLIENT_ID"); + private String clientSecret = System.getenv("AZURE_CLIENT_SECRET"); + private String serviceConnectionId = System.getenv("SERVICE_CONNECTION_ID"); + + private String fakeUsernamePlaceholder = "fakeUsernamePlaceholder"; + private String fakePasswordPlaceholder = "fakePasswordPlaceholder"; + + /** + * Method to insert code snippets for {@link ClientSecretCredential} + */ + public void clientSecretCredentialCodeSnippets() { + // BEGIN: com.azure.identity.credential.clientsecretcredential.construct + TokenCredential clientSecretCredential = new ClientSecretCredentialBuilder().tenantId(tenantId) + .clientId(clientId) + .clientSecret(clientSecret) + .build(); + // END: com.azure.identity.credential.clientsecretcredential.construct + + // BEGIN: com.azure.identity.credential.clientsecretcredential.constructwithproxy + TokenCredential secretCredential = new ClientSecretCredentialBuilder().tenantId(tenantId) + .clientId(clientId) + .clientSecret(clientSecret) + .proxyOptions(new ProxyOptions(Type.HTTP, new InetSocketAddress("10.21.32.43", 5465))) + .build(); + // END: com.azure.identity.credential.clientsecretcredential.constructwithproxy + } + + /** + * Method to insert code snippets for {@link ClientCertificateCredential} + */ + public void clientCertificateCredentialCodeSnippets() { + // BEGIN: com.azure.identity.credential.clientcertificatecredential.construct + TokenCredential clientCertificateCredential = new ClientCertificateCredentialBuilder().tenantId(tenantId) + .clientId(clientId) + .pemCertificate("") + .build(); + // END: com.azure.identity.credential.clientcertificatecredential.construct + + byte[] certificateBytes = new byte[0]; + + // BEGIN: com.azure.identity.credential.clientcertificatecredential.constructWithStream + ByteArrayInputStream certificateStream = new ByteArrayInputStream(certificateBytes); + TokenCredential certificateCredentialWithStream = new ClientCertificateCredentialBuilder().tenantId(tenantId) + .clientId(clientId) + .pemCertificate(certificateStream) + .build(); + // END: com.azure.identity.credential.clientcertificatecredential.constructWithStream + + // BEGIN: com.azure.identity.credential.clientcertificatecredential.constructwithproxy + TokenCredential certificateCredential = new ClientCertificateCredentialBuilder().tenantId(tenantId) + .clientId(clientId) + .pfxCertificate("", "P@s$w0rd") + .proxyOptions(new ProxyOptions(Type.HTTP, new InetSocketAddress("10.21.32.43", 5465))) + .build(); + // END: com.azure.identity.credential.clientcertificatecredential.constructwithproxy + } + + /** + * Method to insert code snippets for {@link ClientAssertionCredential} + */ + public void clientAssertionCredentialCodeSnippets() { + // BEGIN: com.azure.identity.credential.clientassertioncredential.construct + TokenCredential clientAssertionCredential = new ClientAssertionCredentialBuilder().tenantId(tenantId) + .clientId(clientId) + .clientAssertion(() -> "") + .build(); + // END: com.azure.identity.credential.clientassertioncredential.construct + + // BEGIN: com.azure.identity.credential.clientassertioncredential.constructwithproxy + TokenCredential assertionCredential = new ClientAssertionCredentialBuilder().tenantId(tenantId) + .clientId(clientId) + .clientAssertion(() -> "") + .proxyOptions(new ProxyOptions(Type.HTTP, new InetSocketAddress("10.21.32.43", 5465))) + .build(); + // END: com.azure.identity.credential.clientassertioncredential.constructwithproxy + } + + /** + * Method to insert code snippets for {@link ChainedTokenCredential} + */ + public void chainedTokenCredentialCodeSnippets() { + // BEGIN: com.azure.identity.credential.chainedtokencredential.construct + TokenCredential usernamePasswordCredential = new UsernamePasswordCredentialBuilder().clientId(clientId) + .username(fakeUsernamePlaceholder) + .password(fakePasswordPlaceholder) + .build(); + TokenCredential interactiveBrowserCredential = new InteractiveBrowserCredentialBuilder().clientId(clientId) + .port(8765) + .build(); + TokenCredential credential = new ChainedTokenCredentialBuilder().addLast(usernamePasswordCredential) + .addLast(interactiveBrowserCredential) + .build(); + // END: com.azure.identity.credential.chainedtokencredential.construct + } + + /** + * Method to insert code snippets for {@link DefaultAzureCredential} + */ + public void defaultAzureCredentialCodeSnippets() { + // BEGIN: com.azure.identity.credential.defaultazurecredential.construct + TokenCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().build(); + // END: com.azure.identity.credential.defaultazurecredential.construct + + // BEGIN: com.azure.identity.credential.defaultazurecredential.constructwithuserassignedmanagedidentity + TokenCredential dacWithUserAssignedManagedIdentity + = new DefaultAzureCredentialBuilder().managedIdentityClientId("").username("").password("").build(); + // END: com.azure.identity.credential.usernamepasswordcredential.construct + } + + /** + * Method to insert code snippets for {@link AzurePowerShellCredential} + */ + public void azurePowershellCredentialsCodeSnippets() { + // BEGIN: com.azure.identity.credential.azurepowershellcredential.construct + TokenCredential powerShellCredential = new AzurePowerShellCredentialBuilder().build(); + // END: com.azure.identity.credential.azurepowershellcredential.construct + } + + /** + * Method to insert code snippets for {@link AuthorizationCodeCredential} + */ + public void authorizationCodeCredentialsCodeSnippets() { + // BEGIN: com.azure.identity.credential.authorizationcodecredential.construct + TokenCredential authorizationCodeCredential = new AuthorizationCodeCredentialBuilder().authorizationCode( + "{authorization-code-received-at-redirectURL}") + .redirectUrl("{redirectUrl-where-authorization-code-is-received}") + .clientId("{clientId-of-application-being-authenticated") + .build(); + // END: com.azure.identity.credential.authorizationcodecredential.construct + } + + /** + * Method to insert code snippets for {@link OnBehalfOfCredential} + */ + public void oboCredentialsCodeSnippets() { + // BEGIN: com.azure.identity.credential.obocredential.construct + TokenCredential onBehalfOfCredential = new OnBehalfOfCredentialBuilder().clientId("") + .clientSecret("") + .tenantId("") + .userAssertion("") + .build(); + // END: com.azure.identity.credential.obocredential.construct + } + + /** + * Method to insert code snippets for {@link WorkloadIdentityCredential} + */ + public void workloadIdentityCredentialCodeSnippets() { + // BEGIN: com.azure.identity.credential.workloadidentitycredential.construct + TokenCredential workloadIdentityCredential = new WorkloadIdentityCredentialBuilder().clientId("") + .tenantId("") + .tokenFilePath("") + .build(); + // END: com.azure.identity.credential.workloadidentitycredential.construct + } + + /** + * Method to insert code snippets for {@link AzureDeveloperCliCredential} + */ + public void azureDeveloperCliCredentialCodeSnippets() { + // BEGIN: com.azure.identity.credential.azuredeveloperclicredential.construct + TokenCredential azureDevCliCredential = new AzureDeveloperCliCredentialBuilder().build(); + // END: com.azure.identity.credential.azuredeveloperclicredential.construct + } + + public void azurePipelinesCredentialCodeSnippets() { + + // BEGIN: com.azure.identity.credential.azurepipelinescredential.construct + // serviceConnectionId is retrieved from the portal. + // systemAccessToken is retrieved from the pipeline environment as shown. + // You may choose another name for this variable. + + String systemAccessToken = System.getenv("SYSTEM_ACCESSTOKEN"); + AzurePipelinesCredential credential = new AzurePipelinesCredentialBuilder().clientId(clientId) + .tenantId(tenantId) + .serviceConnectionId(serviceConnectionId) + .systemAccessToken(systemAccessToken) + .build(); + // END: com.azure.identity.credential.azurepipelinescredential.construct + } + + public void silentAuthenticationSnippets() { + // BEGIN: com.azure.identity.silentauthentication + String authenticationRecordPath = "path/to/authentication-record.json"; + AuthenticationRecord authenticationRecord = null; + try { + // If we have an existing record, deserialize it. + if (Files.exists(new File(authenticationRecordPath).toPath())) { + authenticationRecord = AuthenticationRecord.deserialize(new FileInputStream(authenticationRecordPath)); + } + } catch (FileNotFoundException e) { + // Handle error as appropriate. + } + + DeviceCodeCredentialBuilder builder = new DeviceCodeCredentialBuilder().clientId(clientId).tenantId(tenantId); + if (authenticationRecord != null) { + // As we have a record, configure the builder to use it. + builder.authenticationRecord(authenticationRecord); + } + DeviceCodeCredential credential = builder.build(); + TokenRequestContext trc = new TokenRequestContext().addScopes("your-appropriate-scope"); + if (authenticationRecord == null) { + // We don't have a record, so we get one and store it. The next authentication will use it. + credential.authenticate(trc).flatMap(record -> { + try { + return record.serializeAsync(new FileOutputStream(authenticationRecordPath)); + } catch (FileNotFoundException e) { + return Mono.error(e); + } + }).subscribe(); + } + + // Now the credential can be passed to another service client or used directly. + AccessToken token = credential.getTokenSync(trc); + + // END: com.azure.identity.silentauthentication + } + + public void bearerTokenProviderSampleSync() { + // BEGIN: com.azure.identity.util.getBearerTokenSupplier + DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build(); + String scope = "https://cognitiveservices.azure.com/.default"; + Supplier supplier = AuthenticationUtil.getBearerTokenSupplier(credential, scope); + + // This example simply uses the Azure SDK HTTP library to demonstrate setting the header. + // Use the token as is appropriate for your circumstances. + HttpRequest request = new HttpRequest(HttpMethod.GET, "https://www.example.com"); + request.setHeader(HttpHeaderName.AUTHORIZATION, "Bearer " + supplier.get()); + HttpClient client = HttpClient.createDefault(); + client.sendSync(request, Context.NONE); + // END: com.azure.identity.util.getBearerTokenSupplier + } + +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample1/v1/AccessControlHelloWorld.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample1/v1/AccessControlHelloWorld.java new file mode 100644 index 000000000000..c2d4218b541f --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample1/v1/AccessControlHelloWorld.java @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.administration; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.administration.models.KeyVaultRoleAssignment; +import com.azure.security.keyvault.administration.models.KeyVaultRoleScope; +import com.azure.security.keyvault.administration.models.KeyVaultRoleDefinition; + +import java.util.ArrayList; +import java.util.List; + +/** + * This sample demonstrates how to create, get, list and delete role assignments synchronously in the key vault. + */ +public class AccessControlHelloWorld { + /** + * Authenticates with the key vault and shows how to create, get, list and delete role assignments synchronously. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when an invalid key vault URL is passed. + */ + public static void main(String[] args) { + /* Instantiate a KeyVaultAccessControlClient that will be used to call the service. Notice that the client is + using default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault Managed HSM. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md) + for links and instructions. */ + KeyVaultAccessControlClient accessControlClient = new KeyVaultAccessControlClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + /* In order to assign a role to a service principal, we'll have to know which role definitions are available. + Let's get all of them. */ + List roleDefinitions = new ArrayList<>(); + + for (KeyVaultRoleDefinition roleDefinition : accessControlClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL)) { + roleDefinitions.add(roleDefinition); + System.out.printf("Retrieved role definition with name: %s %n", roleDefinition.getName()); + } + + // Before assigning any new roles, let's list all the current role assignments. + for (KeyVaultRoleAssignment roleAssignment : accessControlClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL)) { + System.out.printf("Retrieved role assignment with name: %s %n", roleAssignment.getName()); + } + + /* Now let's assign a role to a service principal. To do this we'll need a role definition ID and a service + principal object ID. A role definition ID can be obtained from the 'id' property of one of the role definitions + returned from listRoleAssignments(). + + See the README (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md#authenticate-the-client) + for links and instructions on how to generate a new service principal and obtain it's object ID. You can also + get the object ID for your currently signed in account by running the following Azure CLI command: + az ad signed-in-user show --query objectId */ + String servicePrincipalId = ""; + KeyVaultRoleDefinition roleDefinition = roleDefinitions.get(0); + KeyVaultRoleAssignment createdRoleAssignment = + accessControlClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinition.getId(), + servicePrincipalId); + + System.out.printf("Created role assignment with name: %s %n", createdRoleAssignment.getName()); + + /* To get an existing role assignment, we'll need the 'name' property from an existing assignment. Let's use the + createdAssignment from the previous example. */ + KeyVaultRoleAssignment retrievedRoleAssignment = + accessControlClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleAssignment.getName()); + + System.out.printf("Retrieved role assignment with name: %s %n", retrievedRoleAssignment.getName()); + + /* To remove a role assignment from a service principal, the role assignment must be deleted. Let's delete the + createdAssignment from the previous example. */ + accessControlClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleAssignment.getName()); + + System.out.printf("Deleted role assignment with name: %s %n", createdRoleAssignment.getName()); + } +} + diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample1/v2/AccessControlHelloWorld.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample1/v2/AccessControlHelloWorld.java new file mode 100644 index 000000000000..c2d4218b541f --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample1/v2/AccessControlHelloWorld.java @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.administration; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.administration.models.KeyVaultRoleAssignment; +import com.azure.security.keyvault.administration.models.KeyVaultRoleScope; +import com.azure.security.keyvault.administration.models.KeyVaultRoleDefinition; + +import java.util.ArrayList; +import java.util.List; + +/** + * This sample demonstrates how to create, get, list and delete role assignments synchronously in the key vault. + */ +public class AccessControlHelloWorld { + /** + * Authenticates with the key vault and shows how to create, get, list and delete role assignments synchronously. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when an invalid key vault URL is passed. + */ + public static void main(String[] args) { + /* Instantiate a KeyVaultAccessControlClient that will be used to call the service. Notice that the client is + using default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault Managed HSM. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md) + for links and instructions. */ + KeyVaultAccessControlClient accessControlClient = new KeyVaultAccessControlClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + /* In order to assign a role to a service principal, we'll have to know which role definitions are available. + Let's get all of them. */ + List roleDefinitions = new ArrayList<>(); + + for (KeyVaultRoleDefinition roleDefinition : accessControlClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL)) { + roleDefinitions.add(roleDefinition); + System.out.printf("Retrieved role definition with name: %s %n", roleDefinition.getName()); + } + + // Before assigning any new roles, let's list all the current role assignments. + for (KeyVaultRoleAssignment roleAssignment : accessControlClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL)) { + System.out.printf("Retrieved role assignment with name: %s %n", roleAssignment.getName()); + } + + /* Now let's assign a role to a service principal. To do this we'll need a role definition ID and a service + principal object ID. A role definition ID can be obtained from the 'id' property of one of the role definitions + returned from listRoleAssignments(). + + See the README (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md#authenticate-the-client) + for links and instructions on how to generate a new service principal and obtain it's object ID. You can also + get the object ID for your currently signed in account by running the following Azure CLI command: + az ad signed-in-user show --query objectId */ + String servicePrincipalId = ""; + KeyVaultRoleDefinition roleDefinition = roleDefinitions.get(0); + KeyVaultRoleAssignment createdRoleAssignment = + accessControlClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinition.getId(), + servicePrincipalId); + + System.out.printf("Created role assignment with name: %s %n", createdRoleAssignment.getName()); + + /* To get an existing role assignment, we'll need the 'name' property from an existing assignment. Let's use the + createdAssignment from the previous example. */ + KeyVaultRoleAssignment retrievedRoleAssignment = + accessControlClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleAssignment.getName()); + + System.out.printf("Retrieved role assignment with name: %s %n", retrievedRoleAssignment.getName()); + + /* To remove a role assignment from a service principal, the role assignment must be deleted. Let's delete the + createdAssignment from the previous example. */ + accessControlClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleAssignment.getName()); + + System.out.printf("Deleted role assignment with name: %s %n", createdRoleAssignment.getName()); + } +} + diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample2/v1/AccessControlHelloWorldAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample2/v1/AccessControlHelloWorldAsync.java new file mode 100644 index 000000000000..627531c66b97 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample2/v1/AccessControlHelloWorldAsync.java @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.administration; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.administration.models.KeyVaultRoleAssignment; +import com.azure.security.keyvault.administration.models.KeyVaultRoleScope; +import com.azure.security.keyvault.administration.models.KeyVaultRoleDefinition; + +import java.util.ArrayList; +import java.util.List; + +/** + * This sample demonstrates how to create, get, list and delete role assignments asynchronously in the Key Vault. + */ +public class AccessControlHelloWorldAsync { + /** + * Authenticates with the key vault and shows how to create, get, list and delete role assignments asynchronously. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when an invalid key vault URL is passed. + */ + public static void main(String[] args) throws InterruptedException { + /* Instantiate a KeyVaultAccessControlAsyncClient that will be used to call the service. Notice that the client + is using default Azure credentials. For more information on this and other types of credentials, see this + document: https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault Managed HSM. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md) + for links and instructions. */ + KeyVaultAccessControlAsyncClient accessControlAsyncClient = new KeyVaultAccessControlClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + /* In order to assign a role to a service principal, we'll have to know which role definitions are available. + Let's get all of them. */ + List roleDefinitions = new ArrayList<>(); + + accessControlAsyncClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL) + .doOnNext((roleDefinition) -> { + roleDefinitions.add(roleDefinition); + System.out.printf("Retrieved role definition with name: %s %n", roleDefinition.getName()); + }) + .blockLast(); + + // Before assigning any new roles, let's get all the current role assignments. + accessControlAsyncClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL) + .doOnNext((roleAssignment -> + System.out.printf("Retrieved role assignment with name: %s %n", roleAssignment.getName()))) + .blockLast(); + + /* Now let's assign a role to a service principal. To do this we'll need a role definition ID and a service + principal object ID. A role definition ID can be obtained from the 'id' property of one of the role definitions + returned from listRoleAssignments(). + + See the README (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md#authenticate-the-client) + for links and instructions on how to generate a new service principal and obtain it's object ID. You can also + get the object ID for your currently signed in account by running the following Azure CLI command: + az ad signed-in-user show --query objectId */ + String servicePrincipalId = ""; + KeyVaultRoleDefinition roleDefinition = roleDefinitions.get(0); + KeyVaultRoleAssignment createdRoleAssignment = + accessControlAsyncClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinition.getId(), + servicePrincipalId).block(); + + /* To get an existing role assignment, we'll need the 'name' property from an existing assignment. Let's use the + createdAssignment from the previous example. */ + assert createdRoleAssignment != null; + + accessControlAsyncClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleAssignment.getName()) + .doOnSuccess((retrievedRoleAssignment) -> + System.out.printf("Retrieved role assignment with name: %s %n", retrievedRoleAssignment.getName())) + .block(); + + /* To remove a role assignment from a service principal, the role assignment must be deleted. Let's delete the + createdAssignment from the previous example. */ + accessControlAsyncClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleAssignment.getName()) + .doOnSuccess((deletedRoleAssignment) -> + System.out.printf("Deleted role assignment with name: %s %n", createdRoleAssignment.getName())) + .block(); + + /* NOTE: block() and blockLast() will block until the above operations are completed. This is strongly + discouraged for use in production as it eliminates the benefits of asynchronous IO. It is used here to ensure + the sample runs to completion. */ + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample2/v2/AccessControlHelloWorldAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample2/v2/AccessControlHelloWorldAsync.java new file mode 100644 index 000000000000..627531c66b97 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample2/v2/AccessControlHelloWorldAsync.java @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.administration; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.administration.models.KeyVaultRoleAssignment; +import com.azure.security.keyvault.administration.models.KeyVaultRoleScope; +import com.azure.security.keyvault.administration.models.KeyVaultRoleDefinition; + +import java.util.ArrayList; +import java.util.List; + +/** + * This sample demonstrates how to create, get, list and delete role assignments asynchronously in the Key Vault. + */ +public class AccessControlHelloWorldAsync { + /** + * Authenticates with the key vault and shows how to create, get, list and delete role assignments asynchronously. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when an invalid key vault URL is passed. + */ + public static void main(String[] args) throws InterruptedException { + /* Instantiate a KeyVaultAccessControlAsyncClient that will be used to call the service. Notice that the client + is using default Azure credentials. For more information on this and other types of credentials, see this + document: https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault Managed HSM. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md) + for links and instructions. */ + KeyVaultAccessControlAsyncClient accessControlAsyncClient = new KeyVaultAccessControlClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + /* In order to assign a role to a service principal, we'll have to know which role definitions are available. + Let's get all of them. */ + List roleDefinitions = new ArrayList<>(); + + accessControlAsyncClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL) + .doOnNext((roleDefinition) -> { + roleDefinitions.add(roleDefinition); + System.out.printf("Retrieved role definition with name: %s %n", roleDefinition.getName()); + }) + .blockLast(); + + // Before assigning any new roles, let's get all the current role assignments. + accessControlAsyncClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL) + .doOnNext((roleAssignment -> + System.out.printf("Retrieved role assignment with name: %s %n", roleAssignment.getName()))) + .blockLast(); + + /* Now let's assign a role to a service principal. To do this we'll need a role definition ID and a service + principal object ID. A role definition ID can be obtained from the 'id' property of one of the role definitions + returned from listRoleAssignments(). + + See the README (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md#authenticate-the-client) + for links and instructions on how to generate a new service principal and obtain it's object ID. You can also + get the object ID for your currently signed in account by running the following Azure CLI command: + az ad signed-in-user show --query objectId */ + String servicePrincipalId = ""; + KeyVaultRoleDefinition roleDefinition = roleDefinitions.get(0); + KeyVaultRoleAssignment createdRoleAssignment = + accessControlAsyncClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinition.getId(), + servicePrincipalId).block(); + + /* To get an existing role assignment, we'll need the 'name' property from an existing assignment. Let's use the + createdAssignment from the previous example. */ + assert createdRoleAssignment != null; + + accessControlAsyncClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleAssignment.getName()) + .doOnSuccess((retrievedRoleAssignment) -> + System.out.printf("Retrieved role assignment with name: %s %n", retrievedRoleAssignment.getName())) + .block(); + + /* To remove a role assignment from a service principal, the role assignment must be deleted. Let's delete the + createdAssignment from the previous example. */ + accessControlAsyncClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, createdRoleAssignment.getName()) + .doOnSuccess((deletedRoleAssignment) -> + System.out.printf("Deleted role assignment with name: %s %n", createdRoleAssignment.getName())) + .block(); + + /* NOTE: block() and blockLast() will block until the above operations are completed. This is strongly + discouraged for use in production as it eliminates the benefits of asynchronous IO. It is used here to ensure + the sample runs to completion. */ + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample3/v1/BackupAndRestoreHelloWorld.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample3/v1/BackupAndRestoreHelloWorld.java new file mode 100644 index 000000000000..631ce6e49752 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample3/v1/BackupAndRestoreHelloWorld.java @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.administration; + +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.administration.models.KeyVaultBackupOperation; +import com.azure.security.keyvault.administration.models.KeyVaultRestoreOperation; +import com.azure.security.keyvault.administration.models.KeyVaultRestoreResult; + +/** + * This sample demonstrates how to fully backup and restore a key vault synchronously. + */ +public class BackupAndRestoreHelloWorld { + /** + * Authenticates with the key vault and shows how to fully backup and restore a key vault synchronously. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when an invalid key vault URL is passed. + */ + public static void main(String[] args) { + KeyVaultBackupClient backupClient = new KeyVaultBackupClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + /* Instantiate a KeyVaultBackupClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault Managed HSM. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md) + for links and instructions. */ + + /* Using the KeyVaultBackupClient, you can back up your entire collection of keys. The backing store for full + key backups is a blob storage container using Shared Access Signature authentication. For more details on + creating a SAS token using the BlobServiceClient, see the Azure Storage Blobs client README (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/storage/azure-storage-blob/README.md). + Alternatively, it is possible to generate a SAS token in Storage Explorer (https://docs.microsoft.com/azure/vs-azure-tools-storage-manage-with-storage-explorer?tabs=windows#generate-a-shared-access-signature-in-storage-explorer). + + To ensure you have some keys for backup, you may want to first create a key using the KeyClient. To create a + new KeyClient to create a key, see the 'Azure Key Vault Key client library for Java' README (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md#create-key-client). + + In the sample below, you can set blobStorageUrl and sasToken based on environment variables, configuration + settings, or any way that works for your application. */ + String blobStorageUrl = ""; + String sasToken = ""; + SyncPoller backupPoller = backupClient.beginBackup(blobStorageUrl, sasToken); + + backupPoller.waitForCompletion(); + + /* Now let's restore the entire collection of keys from the backup. We will need the get the URI for the + location the backup, as well as Shared Access Signature for accessing it. */ + String backupFolderUrl = backupPoller.getFinalResult(); + + SyncPoller restorePoller = + backupClient.beginRestore(backupFolderUrl, sasToken); + + restorePoller.waitForCompletion(); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample3/v2/BackupAndRestoreHelloWorld.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample3/v2/BackupAndRestoreHelloWorld.java new file mode 100644 index 000000000000..631ce6e49752 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample3/v2/BackupAndRestoreHelloWorld.java @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.administration; + +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.administration.models.KeyVaultBackupOperation; +import com.azure.security.keyvault.administration.models.KeyVaultRestoreOperation; +import com.azure.security.keyvault.administration.models.KeyVaultRestoreResult; + +/** + * This sample demonstrates how to fully backup and restore a key vault synchronously. + */ +public class BackupAndRestoreHelloWorld { + /** + * Authenticates with the key vault and shows how to fully backup and restore a key vault synchronously. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when an invalid key vault URL is passed. + */ + public static void main(String[] args) { + KeyVaultBackupClient backupClient = new KeyVaultBackupClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + /* Instantiate a KeyVaultBackupClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault Managed HSM. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md) + for links and instructions. */ + + /* Using the KeyVaultBackupClient, you can back up your entire collection of keys. The backing store for full + key backups is a blob storage container using Shared Access Signature authentication. For more details on + creating a SAS token using the BlobServiceClient, see the Azure Storage Blobs client README (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/storage/azure-storage-blob/README.md). + Alternatively, it is possible to generate a SAS token in Storage Explorer (https://docs.microsoft.com/azure/vs-azure-tools-storage-manage-with-storage-explorer?tabs=windows#generate-a-shared-access-signature-in-storage-explorer). + + To ensure you have some keys for backup, you may want to first create a key using the KeyClient. To create a + new KeyClient to create a key, see the 'Azure Key Vault Key client library for Java' README (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md#create-key-client). + + In the sample below, you can set blobStorageUrl and sasToken based on environment variables, configuration + settings, or any way that works for your application. */ + String blobStorageUrl = ""; + String sasToken = ""; + SyncPoller backupPoller = backupClient.beginBackup(blobStorageUrl, sasToken); + + backupPoller.waitForCompletion(); + + /* Now let's restore the entire collection of keys from the backup. We will need the get the URI for the + location the backup, as well as Shared Access Signature for accessing it. */ + String backupFolderUrl = backupPoller.getFinalResult(); + + SyncPoller restorePoller = + backupClient.beginRestore(backupFolderUrl, sasToken); + + restorePoller.waitForCompletion(); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample4/v1/BackupAndRestoreHelloWorldAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample4/v1/BackupAndRestoreHelloWorldAsync.java new file mode 100644 index 000000000000..6a790aede4fb --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample4/v1/BackupAndRestoreHelloWorldAsync.java @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.administration; + +import com.azure.core.util.polling.AsyncPollResponse; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.administration.models.KeyVaultBackupOperation; + +/** + * This sample demonstrates how to fully backup and restore a key vault synchronously. + */ +public class BackupAndRestoreHelloWorldAsync { + /** + * Authenticates with the key vault and shows how to fully backup and restore a key vault synchronously. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when an invalid key vault URL is passed. + */ + public static void main(String[] args) { + /* Instantiate a KeyVaultBackupAsyncClient that will be used to call the service. Notice that the client is + using default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault Managed HSM. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md) + for links and instructions. */ + KeyVaultBackupAsyncClient backupAsyncClient = new KeyVaultBackupClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + /* Using the KeyVaultBackupClient, you can back up your entire collection of keys. The backing store for full + key backups is a blob storage container using Shared Access Signature authentication. For more details on + creating a SAS token using the BlobServiceClient, see the Azure Storage Blobs client README (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/storage/azure-storage-blob/README.md). + Alternatively, it is possible to generate a SAS token in Storage Explorer (https://docs.microsoft.com/azure/vs-azure-tools-storage-manage-with-storage-explorer?tabs=windows#generate-a-shared-access-signature-in-storage-explorer). + + To ensure you have some keys for backup, you may want to first create a key using the KeyClient. To create a + new KeyClient to create a key, see the 'Azure Key Vault Key client library for Java' README (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md#create-key-client). + + In the sample below, you can set blobStorageUrl and sasToken based on environment variables, configuration + settings, or any way that works for your application. */ + String blobStorageUrl = ""; + String sasToken = ""; + + AsyncPollResponse backupPollResponse = + backupAsyncClient.beginBackup(blobStorageUrl, sasToken).blockLast(); + + /* Now let's restore the entire collection of keys from the backup. We will need the get the URI for the + location the backup, as well as Shared Access Signature for accessing it. */ + String backupFolderUrl = backupPollResponse.getValue().getAzureStorageBlobContainerUrl(); + + backupAsyncClient.beginRestore(backupFolderUrl, sasToken).blockLast(); + + /* NOTE: blockLast() will block until all the above operations are completed. This is strongly discouraged for + use in production as it eliminates the benefits of asynchronous IO. It is used here to ensure the sample runs to + completion. */ + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample4/v2/BackupAndRestoreHelloWorldAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample4/v2/BackupAndRestoreHelloWorldAsync.java new file mode 100644 index 000000000000..6a790aede4fb --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample4/v2/BackupAndRestoreHelloWorldAsync.java @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.administration; + +import com.azure.core.util.polling.AsyncPollResponse; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.administration.models.KeyVaultBackupOperation; + +/** + * This sample demonstrates how to fully backup and restore a key vault synchronously. + */ +public class BackupAndRestoreHelloWorldAsync { + /** + * Authenticates with the key vault and shows how to fully backup and restore a key vault synchronously. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when an invalid key vault URL is passed. + */ + public static void main(String[] args) { + /* Instantiate a KeyVaultBackupAsyncClient that will be used to call the service. Notice that the client is + using default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault Managed HSM. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md) + for links and instructions. */ + KeyVaultBackupAsyncClient backupAsyncClient = new KeyVaultBackupClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + /* Using the KeyVaultBackupClient, you can back up your entire collection of keys. The backing store for full + key backups is a blob storage container using Shared Access Signature authentication. For more details on + creating a SAS token using the BlobServiceClient, see the Azure Storage Blobs client README (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/storage/azure-storage-blob/README.md). + Alternatively, it is possible to generate a SAS token in Storage Explorer (https://docs.microsoft.com/azure/vs-azure-tools-storage-manage-with-storage-explorer?tabs=windows#generate-a-shared-access-signature-in-storage-explorer). + + To ensure you have some keys for backup, you may want to first create a key using the KeyClient. To create a + new KeyClient to create a key, see the 'Azure Key Vault Key client library for Java' README (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md#create-key-client). + + In the sample below, you can set blobStorageUrl and sasToken based on environment variables, configuration + settings, or any way that works for your application. */ + String blobStorageUrl = ""; + String sasToken = ""; + + AsyncPollResponse backupPollResponse = + backupAsyncClient.beginBackup(blobStorageUrl, sasToken).blockLast(); + + /* Now let's restore the entire collection of keys from the backup. We will need the get the URI for the + location the backup, as well as Shared Access Signature for accessing it. */ + String backupFolderUrl = backupPollResponse.getValue().getAzureStorageBlobContainerUrl(); + + backupAsyncClient.beginRestore(backupFolderUrl, sasToken).blockLast(); + + /* NOTE: blockLast() will block until all the above operations are completed. This is strongly discouraged for + use in production as it eliminates the benefits of asynchronous IO. It is used here to ensure the sample runs to + completion. */ + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample5/v1/CreateRoleAssignmentsForDifferentScopes.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample5/v1/CreateRoleAssignmentsForDifferentScopes.java new file mode 100644 index 000000000000..649f4719be48 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample5/v1/CreateRoleAssignmentsForDifferentScopes.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.administration; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.administration.models.KeyVaultRoleAssignment; +import com.azure.security.keyvault.administration.models.KeyVaultRoleScope; + +/** + * This sample demonstrates how to create role assignments in the key vault for different scopes. + */ +public class CreateRoleAssignmentsForDifferentScopes { + /** + * Authenticates with the key vault and shows how to create role assignments in the key vault for different scopes + * synchronously. For examples of how to perform async operations, please refer to + * {@link AccessControlHelloWorldAsync the async client samples}. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when an invalid key vault URL is passed. + */ + public static void main(String[] args) { + /* Instantiate a KeyVaultAccessControlClient that will be used to call the service. Notice that the client is + using default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault Managed HSM. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md) + for links and instructions. */ + KeyVaultAccessControlClient accessControlClient = new KeyVaultAccessControlClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + /* By default role assignments apply to the global scope. It is also possible to be more specific by applying an + assignment to the all keys scope or a specific KeyVaultKey. + + Let's assign a role to a service principal so that it applies to all keys. To do this we'll need a service + principal object ID and a role definition ID. A role definition ID can be obtained from the 'id' property of one + of the role definitions returned from listRoleDefinitions(). Alternatively, you can use the following Azure CLI + command: az keyvault role definition list --hsm-name */ + String roleDefinitionId = ""; + String servicePrincipalId = ""; + + KeyVaultRoleAssignment roleAssignmentForAllKeys = + accessControlClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinitionId, servicePrincipalId); + + System.out.printf("Created role assignment with name: %s %n", roleAssignmentForAllKeys.getName()); + + /* Now let's assign a role to a service principal so that it applies to a specific KeyVaultKey. To do this we'll + use the role definition ID and a service principal object ID from the previous sample. We'll also need the ID of + an existing KeyVaultKey, which can be obtained from the service using a KeyClient. */ + String keyId = ""; + + KeyVaultRoleAssignment roleAssignmentForSingleKey = + accessControlClient.createRoleAssignment(KeyVaultRoleScope.fromString(keyId), roleDefinitionId, + servicePrincipalId); + + System.out.printf("Created role assignment with name: %s %n", roleAssignmentForSingleKey.getName()); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample5/v2/CreateRoleAssignmentsForDifferentScopes.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample5/v2/CreateRoleAssignmentsForDifferentScopes.java new file mode 100644 index 000000000000..649f4719be48 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample5/v2/CreateRoleAssignmentsForDifferentScopes.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.administration; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.administration.models.KeyVaultRoleAssignment; +import com.azure.security.keyvault.administration.models.KeyVaultRoleScope; + +/** + * This sample demonstrates how to create role assignments in the key vault for different scopes. + */ +public class CreateRoleAssignmentsForDifferentScopes { + /** + * Authenticates with the key vault and shows how to create role assignments in the key vault for different scopes + * synchronously. For examples of how to perform async operations, please refer to + * {@link AccessControlHelloWorldAsync the async client samples}. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when an invalid key vault URL is passed. + */ + public static void main(String[] args) { + /* Instantiate a KeyVaultAccessControlClient that will be used to call the service. Notice that the client is + using default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault Managed HSM. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md) + for links and instructions. */ + KeyVaultAccessControlClient accessControlClient = new KeyVaultAccessControlClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + /* By default role assignments apply to the global scope. It is also possible to be more specific by applying an + assignment to the all keys scope or a specific KeyVaultKey. + + Let's assign a role to a service principal so that it applies to all keys. To do this we'll need a service + principal object ID and a role definition ID. A role definition ID can be obtained from the 'id' property of one + of the role definitions returned from listRoleDefinitions(). Alternatively, you can use the following Azure CLI + command: az keyvault role definition list --hsm-name */ + String roleDefinitionId = ""; + String servicePrincipalId = ""; + + KeyVaultRoleAssignment roleAssignmentForAllKeys = + accessControlClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinitionId, servicePrincipalId); + + System.out.printf("Created role assignment with name: %s %n", roleAssignmentForAllKeys.getName()); + + /* Now let's assign a role to a service principal so that it applies to a specific KeyVaultKey. To do this we'll + use the role definition ID and a service principal object ID from the previous sample. We'll also need the ID of + an existing KeyVaultKey, which can be obtained from the service using a KeyClient. */ + String keyId = ""; + + KeyVaultRoleAssignment roleAssignmentForSingleKey = + accessControlClient.createRoleAssignment(KeyVaultRoleScope.fromString(keyId), roleDefinitionId, + servicePrincipalId); + + System.out.printf("Created role assignment with name: %s %n", roleAssignmentForSingleKey.getName()); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample6/v1/ReadmeSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample6/v1/ReadmeSamples.java new file mode 100644 index 000000000000..f7d0108edc7a --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample6/v1/ReadmeSamples.java @@ -0,0 +1,620 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.administration; + +import com.azure.core.exception.HttpResponseException; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.polling.AsyncPollResponse; +import com.azure.core.util.polling.LongRunningOperationStatus; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.administration.models.KeyVaultBackupOperation; +import com.azure.security.keyvault.administration.models.KeyVaultGetSettingsResult; +import com.azure.security.keyvault.administration.models.KeyVaultRestoreOperation; +import com.azure.security.keyvault.administration.models.KeyVaultRestoreResult; +import com.azure.security.keyvault.administration.models.KeyVaultRoleAssignment; +import com.azure.security.keyvault.administration.models.KeyVaultRoleDefinition; +import com.azure.security.keyvault.administration.models.KeyVaultRoleScope; +import com.azure.security.keyvault.administration.models.KeyVaultSelectiveKeyRestoreOperation; +import com.azure.security.keyvault.administration.models.KeyVaultSelectiveKeyRestoreResult; +import com.azure.security.keyvault.administration.models.KeyVaultSetting; + +import java.time.Duration; + +/** + * Class containing code snippets that will be injected to README.md. + */ +@SuppressWarnings("unused") +public class ReadmeSamples { + private final KeyVaultAccessControlClient keyVaultAccessControlClient = + new KeyVaultAccessControlClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + private final KeyVaultAccessControlAsyncClient keyVaultAccessControlAsyncClient = + new KeyVaultAccessControlClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + private final KeyVaultBackupClient keyVaultBackupClient = + new KeyVaultBackupClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + private final KeyVaultBackupAsyncClient keyVaultBackupAsyncClient = + new KeyVaultBackupClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + private final KeyVaultSettingsClient keyVaultSettingsClient = + new KeyVaultSettingsClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + private final KeyVaultSettingsAsyncClient keyVaultSettingsAsyncClient = + new KeyVaultSettingsClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + /** + * Code sample for creating a {@link KeyVaultAccessControlClient}. + */ + public void createAccessControlClient() { + // BEGIN: readme-sample-createAccessControlClient + KeyVaultAccessControlClient keyVaultAccessControlClient = new KeyVaultAccessControlClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + // END: readme-sample-createAccessControlClient + } + + /** + * Code sample for listing {@link KeyVaultRoleDefinition role definitions}. + */ + public void listRoleDefinitions() { + // BEGIN: readme-sample-listRoleDefinitions + PagedIterable roleDefinitions = + keyVaultAccessControlClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL); + + roleDefinitions.forEach(roleDefinition -> + System.out.printf("Retrieved role definition with name '%s'.%n", roleDefinition.getName())); + // END: readme-sample-listRoleDefinitions + } + + /** + * Code sample for creating or updating a {@link KeyVaultRoleDefinition role definition}. + */ + public void setRoleDefinition() { + // BEGIN: readme-sample-setRoleDefinition + KeyVaultRoleDefinition roleDefinition = keyVaultAccessControlClient.setRoleDefinition(KeyVaultRoleScope.GLOBAL); + + System.out.printf("Created role definition with randomly generated name '%s' and role name '%s'.%n", + roleDefinition.getName(), roleDefinition.getRoleName()); + // END: readme-sample-setRoleDefinition + } + + /** + * Code sample for getting a {@link KeyVaultRoleDefinition role definition}. + */ + public void getRoleDefinition() { + // BEGIN: readme-sample-getRoleDefinition + String roleDefinitionName = ""; + KeyVaultRoleDefinition roleDefinition = + keyVaultAccessControlClient.getRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName); + + System.out.printf("Retrieved role definition with name '%s' and role name '%s'.%n", roleDefinition.getName(), + roleDefinition.getRoleName()); + // END: readme-sample-getRoleDefinition + } + + /** + * Code sample for deleting a {@link KeyVaultRoleDefinition role definition}. + */ + public void deleteRoleDefinition() { + // BEGIN: readme-sample-deleteRoleDefinition + String roleDefinitionName = ""; + + keyVaultAccessControlClient.deleteRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName); + + System.out.printf("Deleted role definition with name '%s'.%n", roleDefinitionName); + // END: readme-sample-deleteRoleDefinition + } + + /** + * Code sample for listing {@link KeyVaultRoleAssignment role assignments}. + */ + public void listRoleAssignments() { + // BEGIN: readme-sample-listRoleAssignments + PagedIterable roleAssignments = + keyVaultAccessControlClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL); + + roleAssignments.forEach(roleAssignment -> + System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName())); + // END: readme-sample-listRoleAssignments + } + + /** + * Code sample for creating a {@link KeyVaultRoleAssignment role assignment}. + */ + public void createRoleAssignment() { + // BEGIN: readme-sample-createRoleAssignment + String roleDefinitionId = ""; + String servicePrincipalId = ""; + KeyVaultRoleAssignment roleAssignment = + keyVaultAccessControlClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinitionId, + servicePrincipalId); + + System.out.printf("Created role assignment with randomly generated name '%s' for principal with id '%s'.%n", + roleAssignment.getName(), roleAssignment.getProperties().getPrincipalId()); + // END: readme-sample-createRoleAssignment + } + + /** + * Code sample for getting a {@link KeyVaultRoleAssignment role assignment}. + */ + public void getRoleAssignment() { + // BEGIN: readme-sample-getRoleAssignment + String roleAssignmentName = ""; + KeyVaultRoleAssignment roleAssignment = + keyVaultAccessControlClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName); + + System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName()); + // END: readme-sample-getRoleAssignment + } + + /** + * Code sample for deleting a {@link KeyVaultRoleAssignment role assignment}. + */ + public void deleteRoleAssignment() { + // BEGIN: readme-sample-deleteRoleAssignment + String roleAssignmentName = ""; + + keyVaultAccessControlClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName); + + System.out.printf("Deleted role assignment with name '%s'.%n", roleAssignmentName); + // END: readme-sample-deleteRoleAssignment + } + + /** + * Code sample for listing {@link KeyVaultRoleDefinition role definitions} asynchronously. + */ + public void listRoleDefinitionsAsync() { + // BEGIN: readme-sample-listRoleDefinitionsAsync + keyVaultAccessControlAsyncClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL) + .subscribe(roleDefinition -> + System.out.printf("Retrieved role definition with name '%s'.%n", roleDefinition.getName())); + // END: readme-sample-listRoleDefinitionsAsync + } + + /** + * Code sample for creating or updating a {@link KeyVaultRoleDefinition role definition} asynchronously. + */ + public void setRoleDefinitionAsync() { + // BEGIN: readme-sample-setRoleDefinitionAsync + keyVaultAccessControlAsyncClient.setRoleDefinition(KeyVaultRoleScope.GLOBAL) + .subscribe(roleDefinition -> + System.out.printf("Created role definition with randomly generated name '%s' and role name '%s'.%n", + roleDefinition.getName(), roleDefinition.getRoleName())); + // END: readme-sample-setRoleDefinitionAsync + } + + /** + * Code sample for getting a {@link KeyVaultRoleDefinition role definition} asynchronously. + */ + public void getRoleDefinitionAsync() { + // BEGIN: readme-sample-getRoleDefinitionAsync + String roleDefinitionName = ""; + + keyVaultAccessControlAsyncClient.getRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName) + .subscribe(roleDefinition -> + System.out.printf("Retrieved role definition with name '%s' and role name '%s'.%n", + roleDefinition.getName(), roleDefinition.getRoleName())); + // END: readme-sample-getRoleDefinitionAsync + } + + /** + * Code sample for deleting a {@link KeyVaultRoleDefinition role definition} asynchronously. + */ + public void deleteRoleDefinitionAsync() { + // BEGIN: readme-sample-deleteRoleDefinitionAsync + String roleDefinitionName = ""; + + keyVaultAccessControlAsyncClient.deleteRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName) + .subscribe(unused -> System.out.printf("Deleted role definition with name '%s'.%n", roleDefinitionName)); + // END: readme-sample-deleteRoleDefinitionAsync + } + + /** + * Code sample for listing {@link KeyVaultRoleAssignment role assignments} asynchronously. + */ + public void listRoleAssignmentsAsync() { + // BEGIN: readme-sample-listRoleAssignmentsAsync + keyVaultAccessControlAsyncClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL) + .subscribe(roleAssignment -> + System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName())); + // END: readme-sample-listRoleAssignmentsAsync + } + + /** + * Code sample for creating a {@link KeyVaultRoleAssignment role assignment} asynchronously. + */ + public void createRoleAssignmentAsync() { + // BEGIN: readme-sample-createRoleAssignmentAsync + String roleDefinitionId = ""; + String servicePrincipalId = ""; + + keyVaultAccessControlAsyncClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinitionId, + servicePrincipalId).subscribe(roleAssignment -> + System.out.printf("Created role assignment with randomly generated name '%s' for principal with id" + + "'%s'.%n", roleAssignment.getName(), roleAssignment.getProperties().getPrincipalId())); + // END: readme-sample-createRoleAssignmentAsync + } + + /** + * Code sample for getting a {@link KeyVaultRoleAssignment role assignment} asynchronously. + */ + public void getRoleAssignmentAsync() { + // BEGIN: readme-sample-getRoleAssignmentAsync + String roleAssignmentName = ""; + + keyVaultAccessControlAsyncClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName) + .subscribe(roleAssignment -> + System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName())); + // END: readme-sample-getRoleAssignmentAsync + } + + /** + * Code sample for deleting a {@link KeyVaultRoleAssignment role assignment} asynchronously. + */ + public void deleteRoleAssignmentAsync() { + // BEGIN: readme-sample-deleteRoleAssignmentAsync + String roleAssignmentName = ""; + + keyVaultAccessControlAsyncClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName) + .subscribe(unused -> + System.out.printf("Deleted role assignment with name '%s'.%n", roleAssignmentName)); + // END: readme-sample-deleteRoleAssignmentAsync + } + + /** + * Code sample for creating a {@link KeyVaultBackupClient}. + */ + public void createBackupClient() { + // BEGIN: readme-sample-createBackupClient + KeyVaultBackupClient keyVaultBackupClient = new KeyVaultBackupClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + // END: readme-sample-createBackupClient + } + + /** + * Code sample for starting a {@link KeyVaultBackupOperation pre-backup check}. + */ + public void beginPreBackup() { + // BEGIN: readme-sample-beginPreBackup + String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer"; + String sasToken = ""; + + SyncPoller preBackupPoller = + keyVaultBackupClient.beginPreBackup(blobStorageUrl, sasToken); + PollResponse pollResponse = preBackupPoller.poll(); + + System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()); + + PollResponse finalPollResponse = preBackupPoller.waitForCompletion(); + + if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { + String folderUrl = preBackupPoller.getFinalResult(); + + System.out.printf("Pre-backup check completed successfully.%n"); + } else { + KeyVaultBackupOperation operation = preBackupPoller.poll().getValue(); + + System.out.printf("Pre-backup check failed with error: %s.%n", operation.getError().getMessage()); + } + // END: readme-sample-beginPreBackup + } + + /** + * Code sample for starting a {@link KeyVaultBackupOperation backup operation}. + */ + public void beginBackup() { + // BEGIN: readme-sample-beginBackup + String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer"; + String sasToken = ""; + + SyncPoller backupPoller = + keyVaultBackupClient.beginBackup(blobStorageUrl, sasToken); + PollResponse pollResponse = backupPoller.poll(); + + System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()); + + PollResponse finalPollResponse = backupPoller.waitForCompletion(); + + if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { + String folderUrl = backupPoller.getFinalResult(); + + System.out.printf("Backup completed. The storage location of this backup is: %s.%n", folderUrl); + } else { + KeyVaultBackupOperation operation = backupPoller.poll().getValue(); + + System.out.printf("Backup failed with error: %s.%n", operation.getError().getMessage()); + } + // END: readme-sample-beginBackup + } + + /** + * Code sample for starting a {@link KeyVaultRestoreOperation pre-restore check}. + */ + public void beginPreRestore() { + // BEGIN: readme-sample-beginPreRestore + String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; + String sasToken = ""; + + SyncPoller preRestorePoller = + keyVaultBackupClient.beginPreRestore(folderUrl, sasToken); + PollResponse pollResponse = preRestorePoller.poll(); + + System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()); + + PollResponse finalPollResponse = preRestorePoller.waitForCompletion(); + + if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { + System.out.printf("Pre-restore check completed successfully.%n"); + } else { + KeyVaultRestoreOperation operation = preRestorePoller.poll().getValue(); + + System.out.printf("Pre-restore check failed with error: %s.%n", operation.getError().getMessage()); + } + // END: readme-sample-beginPreRestore + } + + /** + * Code sample for starting a {@link KeyVaultRestoreOperation restore operation}. + */ + public void beginRestore() { + // BEGIN: readme-sample-beginRestore + String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; + String sasToken = ""; + + SyncPoller restorePoller = + keyVaultBackupClient.beginRestore(folderUrl, sasToken); + PollResponse pollResponse = restorePoller.poll(); + + System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()); + + PollResponse finalPollResponse = restorePoller.waitForCompletion(); + + if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { + System.out.printf("Backup restored successfully.%n"); + } else { + KeyVaultRestoreOperation operation = restorePoller.poll().getValue(); + + System.out.printf("Restore failed with error: %s.%n", operation.getError().getMessage()); + } + // END: readme-sample-beginRestore + } + + /** + * Code sample for starting a {@link KeyVaultSelectiveKeyRestoreOperation selective key restore operation}. + */ + public void beginSelectiveKeyRestore() { + // BEGIN: readme-sample-beginSelectiveKeyRestore + String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; + String sasToken = ""; + String keyName = "myKey"; + + SyncPoller restorePoller = + keyVaultBackupClient.beginSelectiveKeyRestore(folderUrl, sasToken, keyName); + PollResponse pollResponse = restorePoller.poll(); + + System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()); + + PollResponse finalPollResponse = restorePoller.waitForCompletion(); + + if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { + System.out.printf("Key restored successfully.%n"); + } else { + KeyVaultSelectiveKeyRestoreOperation operation = restorePoller.poll().getValue(); + + System.out.printf("Key restore failed with error: %s.%n", operation.getError().getMessage()); + } + // END: readme-sample-beginSelectiveKeyRestore + } + + /** + * Code sample for starting a {@link KeyVaultBackupOperation pre-backup check} asynchronously. + */ + public void beginPreBackupAsync() { + // BEGIN: readme-sample-beginPreBackupAsync + String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer"; + String sasToken = ""; + + keyVaultBackupAsyncClient.beginPreBackup(blobStorageUrl, sasToken) + .setPollInterval(Duration.ofSeconds(1)) // You can set a custom polling interval. + .doOnError(e -> System.out.printf("Pre-backup check failed with error: %s.%n", e.getMessage())) + .doOnNext(pollResponse -> + System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus())) + .filter(pollResponse -> pollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) + .flatMap(AsyncPollResponse::getFinalResult) + .subscribe(folderUrl -> + System.out.printf("Pre-backup check completed successfully.%n")); + // END: readme-sample-beginPreBackupAsync + } + + /** + * Code sample for starting a {@link KeyVaultBackupOperation backup operation} asynchronously. + */ + public void beginBackupAsync() { + // BEGIN: readme-sample-beginBackupAsync + String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer"; + String sasToken = ""; + + keyVaultBackupAsyncClient.beginBackup(blobStorageUrl, sasToken) + .setPollInterval(Duration.ofSeconds(1)) // You can set a custom polling interval. + .doOnError(e -> System.out.printf("Backup failed with error: %s.%n", e.getMessage())) + .doOnNext(pollResponse -> + System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus())) + .filter(pollResponse -> pollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) + .flatMap(AsyncPollResponse::getFinalResult) + .subscribe(folderUrl -> + System.out.printf("Backup completed. The storage location of this backup is: %s.%n", folderUrl)); + // END: readme-sample-beginBackupAsync + } + + /** + * Code sample for starting a {@link KeyVaultRestoreOperation pre-restore check} asynchronously. + */ + public void beginPreRestoreAsync() { + // BEGIN: readme-sample-beginPreRestoreAsync + String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; + String sasToken = ""; + + keyVaultBackupAsyncClient.beginPreRestore(folderUrl, sasToken) + .setPollInterval(Duration.ofSeconds(1)) // You can set a custom polling interval. + .doOnError(e -> System.out.printf("Pre-restore check failed with error: %s.%n", e.getMessage())) + .doOnNext(pollResponse -> + System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus())) + .filter(pollResponse -> pollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) + .flatMap(AsyncPollResponse::getFinalResult) + .subscribe(unused -> System.out.printf("Pre-restore check completed successfully.%n")); + // END: readme-sample-beginPreRestoreAsync + } + + /** + * Code sample for starting a {@link KeyVaultRestoreOperation restore operation} asynchronously. + */ + public void beginRestoreAsync() { + // BEGIN: readme-sample-beginRestoreAsync + String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; + String sasToken = ""; + + keyVaultBackupAsyncClient.beginRestore(folderUrl, sasToken) + .setPollInterval(Duration.ofSeconds(1)) // You can set a custom polling interval. + .doOnError(e -> System.out.printf("Restore failed with error: %s.%n", e.getMessage())) + .doOnNext(pollResponse -> + System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus())) + .filter(pollResponse -> pollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) + .flatMap(AsyncPollResponse::getFinalResult) + .subscribe(unused -> System.out.printf("Backup restored successfully.%n")); + // END: readme-sample-beginRestoreAsync + } + + /** + * Code sample for starting a {@link KeyVaultSelectiveKeyRestoreOperation selective key restore operation} + * asynchronously. + */ + public void beginSelectiveKeyRestoreAsync() { + // BEGIN: readme-sample-beginSelectiveKeyRestoreAsync + String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; + String sasToken = ""; + String keyName = "myKey"; + + keyVaultBackupAsyncClient.beginSelectiveKeyRestore(folderUrl, sasToken, keyName) + .setPollInterval(Duration.ofSeconds(1)) // You can set a custom polling interval. + .doOnError(e -> System.out.printf("Key restoration failed with error: %s.%n", e.getMessage())) + .doOnNext(pollResponse -> + System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus())) + .filter(pollResponse -> pollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) + .flatMap(AsyncPollResponse::getFinalResult) + .subscribe(unused -> System.out.printf("Key restored successfully.%n")); + // END: readme-sample-beginSelectiveKeyRestoreAsync + } + + public void troubleshooting() { + // BEGIN: readme-sample-troubleshooting + try { + keyVaultAccessControlClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, ""); + } catch (HttpResponseException e) { + System.out.println(e.getMessage()); + } + // END: readme-sample-troubleshooting + } + + /** + * Code sample for updating a {@link KeyVaultSetting setting}. + */ + public void updateSetting() { + // BEGIN: readme-sample-updateSetting + String settingName = ""; + KeyVaultSetting settingToUpdate = new KeyVaultSetting(settingName, true); + KeyVaultSetting updatedSetting = keyVaultSettingsClient.updateSetting(settingToUpdate); + + System.out.printf("Updated setting '%s' to '%s'.%n", updatedSetting.getName(), updatedSetting.asBoolean()); + // END: readme-sample-updateSetting + } + + /** + * Code sample for retrieving a {@link KeyVaultSetting setting}. + */ + public void getSetting() { + // BEGIN: readme-sample-getSetting + String settingName = ""; + KeyVaultSetting setting = keyVaultSettingsClient.getSetting(settingName); + + System.out.printf("Retrieved setting '%s' with value '%s'.%n", setting.getName(), + setting.asBoolean()); + // END: readme-sample-getSetting + } + + /** + * Code sample for retrieving an account's {@link KeyVaultSetting settings}. + */ + public void getSettings() { + // BEGIN: readme-sample-getSettings + KeyVaultGetSettingsResult getSettingsResult = keyVaultSettingsClient.getSettings(); + + for (KeyVaultSetting setting : getSettingsResult.getSettings()) { + System.out.printf("Retrieved setting '%s' with value '%s'.%n", setting.getName(), setting.asBoolean()); + } + // END: readme-sample-getSettings + } + + /** + * Code sample for updating a {@link KeyVaultSetting setting} asynchronously. + */ + public void updateSettingAsync() { + // BEGIN: readme-sample-updateSettingAsync + String settingName = ""; + KeyVaultSetting settingToUpdate = new KeyVaultSetting(settingName, true); + + keyVaultSettingsAsyncClient.updateSetting(settingToUpdate) + .subscribe(updatedSetting -> + System.out.printf("Updated setting with name '%s' and value '%s'.%n", updatedSetting.getName(), + updatedSetting.asBoolean())); + // END: readme-sample-updateSettingAsync + } + + /** + * Code sample for retrieving a {@link KeyVaultSetting setting} asynchronously. + */ + public void getSettingAsync() { + // BEGIN: readme-sample-getSettingAsync + String settingName = ""; + + keyVaultSettingsAsyncClient.getSetting(settingName) + .subscribe(setting -> + System.out.printf("Retrieved setting with name '%s' and value '%s'.%n", setting.getName(), + setting.asBoolean())); + // END: readme-sample-getSettingAsync + } + + /** + * Code sample for retrieving an account's {@link KeyVaultSetting settings} asynchronously. + */ + public void getSettingsAsync() { + // BEGIN: readme-sample-getSettingsAsync + keyVaultSettingsAsyncClient.getSettings() + .subscribe(settingsResult -> + settingsResult.getSettings().forEach(setting -> + System.out.printf("Retrieved setting with name '%s' and value '%s'.%n", setting.getName(), + setting.asBoolean()))); + // END: readme-sample-getSettingsAsync + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample6/v2/ReadmeSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample6/v2/ReadmeSamples.java new file mode 100644 index 000000000000..f7d0108edc7a --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample6/v2/ReadmeSamples.java @@ -0,0 +1,620 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.administration; + +import com.azure.core.exception.HttpResponseException; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.polling.AsyncPollResponse; +import com.azure.core.util.polling.LongRunningOperationStatus; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.administration.models.KeyVaultBackupOperation; +import com.azure.security.keyvault.administration.models.KeyVaultGetSettingsResult; +import com.azure.security.keyvault.administration.models.KeyVaultRestoreOperation; +import com.azure.security.keyvault.administration.models.KeyVaultRestoreResult; +import com.azure.security.keyvault.administration.models.KeyVaultRoleAssignment; +import com.azure.security.keyvault.administration.models.KeyVaultRoleDefinition; +import com.azure.security.keyvault.administration.models.KeyVaultRoleScope; +import com.azure.security.keyvault.administration.models.KeyVaultSelectiveKeyRestoreOperation; +import com.azure.security.keyvault.administration.models.KeyVaultSelectiveKeyRestoreResult; +import com.azure.security.keyvault.administration.models.KeyVaultSetting; + +import java.time.Duration; + +/** + * Class containing code snippets that will be injected to README.md. + */ +@SuppressWarnings("unused") +public class ReadmeSamples { + private final KeyVaultAccessControlClient keyVaultAccessControlClient = + new KeyVaultAccessControlClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + private final KeyVaultAccessControlAsyncClient keyVaultAccessControlAsyncClient = + new KeyVaultAccessControlClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + private final KeyVaultBackupClient keyVaultBackupClient = + new KeyVaultBackupClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + private final KeyVaultBackupAsyncClient keyVaultBackupAsyncClient = + new KeyVaultBackupClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + private final KeyVaultSettingsClient keyVaultSettingsClient = + new KeyVaultSettingsClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + private final KeyVaultSettingsAsyncClient keyVaultSettingsAsyncClient = + new KeyVaultSettingsClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + /** + * Code sample for creating a {@link KeyVaultAccessControlClient}. + */ + public void createAccessControlClient() { + // BEGIN: readme-sample-createAccessControlClient + KeyVaultAccessControlClient keyVaultAccessControlClient = new KeyVaultAccessControlClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + // END: readme-sample-createAccessControlClient + } + + /** + * Code sample for listing {@link KeyVaultRoleDefinition role definitions}. + */ + public void listRoleDefinitions() { + // BEGIN: readme-sample-listRoleDefinitions + PagedIterable roleDefinitions = + keyVaultAccessControlClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL); + + roleDefinitions.forEach(roleDefinition -> + System.out.printf("Retrieved role definition with name '%s'.%n", roleDefinition.getName())); + // END: readme-sample-listRoleDefinitions + } + + /** + * Code sample for creating or updating a {@link KeyVaultRoleDefinition role definition}. + */ + public void setRoleDefinition() { + // BEGIN: readme-sample-setRoleDefinition + KeyVaultRoleDefinition roleDefinition = keyVaultAccessControlClient.setRoleDefinition(KeyVaultRoleScope.GLOBAL); + + System.out.printf("Created role definition with randomly generated name '%s' and role name '%s'.%n", + roleDefinition.getName(), roleDefinition.getRoleName()); + // END: readme-sample-setRoleDefinition + } + + /** + * Code sample for getting a {@link KeyVaultRoleDefinition role definition}. + */ + public void getRoleDefinition() { + // BEGIN: readme-sample-getRoleDefinition + String roleDefinitionName = ""; + KeyVaultRoleDefinition roleDefinition = + keyVaultAccessControlClient.getRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName); + + System.out.printf("Retrieved role definition with name '%s' and role name '%s'.%n", roleDefinition.getName(), + roleDefinition.getRoleName()); + // END: readme-sample-getRoleDefinition + } + + /** + * Code sample for deleting a {@link KeyVaultRoleDefinition role definition}. + */ + public void deleteRoleDefinition() { + // BEGIN: readme-sample-deleteRoleDefinition + String roleDefinitionName = ""; + + keyVaultAccessControlClient.deleteRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName); + + System.out.printf("Deleted role definition with name '%s'.%n", roleDefinitionName); + // END: readme-sample-deleteRoleDefinition + } + + /** + * Code sample for listing {@link KeyVaultRoleAssignment role assignments}. + */ + public void listRoleAssignments() { + // BEGIN: readme-sample-listRoleAssignments + PagedIterable roleAssignments = + keyVaultAccessControlClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL); + + roleAssignments.forEach(roleAssignment -> + System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName())); + // END: readme-sample-listRoleAssignments + } + + /** + * Code sample for creating a {@link KeyVaultRoleAssignment role assignment}. + */ + public void createRoleAssignment() { + // BEGIN: readme-sample-createRoleAssignment + String roleDefinitionId = ""; + String servicePrincipalId = ""; + KeyVaultRoleAssignment roleAssignment = + keyVaultAccessControlClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinitionId, + servicePrincipalId); + + System.out.printf("Created role assignment with randomly generated name '%s' for principal with id '%s'.%n", + roleAssignment.getName(), roleAssignment.getProperties().getPrincipalId()); + // END: readme-sample-createRoleAssignment + } + + /** + * Code sample for getting a {@link KeyVaultRoleAssignment role assignment}. + */ + public void getRoleAssignment() { + // BEGIN: readme-sample-getRoleAssignment + String roleAssignmentName = ""; + KeyVaultRoleAssignment roleAssignment = + keyVaultAccessControlClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName); + + System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName()); + // END: readme-sample-getRoleAssignment + } + + /** + * Code sample for deleting a {@link KeyVaultRoleAssignment role assignment}. + */ + public void deleteRoleAssignment() { + // BEGIN: readme-sample-deleteRoleAssignment + String roleAssignmentName = ""; + + keyVaultAccessControlClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName); + + System.out.printf("Deleted role assignment with name '%s'.%n", roleAssignmentName); + // END: readme-sample-deleteRoleAssignment + } + + /** + * Code sample for listing {@link KeyVaultRoleDefinition role definitions} asynchronously. + */ + public void listRoleDefinitionsAsync() { + // BEGIN: readme-sample-listRoleDefinitionsAsync + keyVaultAccessControlAsyncClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL) + .subscribe(roleDefinition -> + System.out.printf("Retrieved role definition with name '%s'.%n", roleDefinition.getName())); + // END: readme-sample-listRoleDefinitionsAsync + } + + /** + * Code sample for creating or updating a {@link KeyVaultRoleDefinition role definition} asynchronously. + */ + public void setRoleDefinitionAsync() { + // BEGIN: readme-sample-setRoleDefinitionAsync + keyVaultAccessControlAsyncClient.setRoleDefinition(KeyVaultRoleScope.GLOBAL) + .subscribe(roleDefinition -> + System.out.printf("Created role definition with randomly generated name '%s' and role name '%s'.%n", + roleDefinition.getName(), roleDefinition.getRoleName())); + // END: readme-sample-setRoleDefinitionAsync + } + + /** + * Code sample for getting a {@link KeyVaultRoleDefinition role definition} asynchronously. + */ + public void getRoleDefinitionAsync() { + // BEGIN: readme-sample-getRoleDefinitionAsync + String roleDefinitionName = ""; + + keyVaultAccessControlAsyncClient.getRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName) + .subscribe(roleDefinition -> + System.out.printf("Retrieved role definition with name '%s' and role name '%s'.%n", + roleDefinition.getName(), roleDefinition.getRoleName())); + // END: readme-sample-getRoleDefinitionAsync + } + + /** + * Code sample for deleting a {@link KeyVaultRoleDefinition role definition} asynchronously. + */ + public void deleteRoleDefinitionAsync() { + // BEGIN: readme-sample-deleteRoleDefinitionAsync + String roleDefinitionName = ""; + + keyVaultAccessControlAsyncClient.deleteRoleDefinition(KeyVaultRoleScope.GLOBAL, roleDefinitionName) + .subscribe(unused -> System.out.printf("Deleted role definition with name '%s'.%n", roleDefinitionName)); + // END: readme-sample-deleteRoleDefinitionAsync + } + + /** + * Code sample for listing {@link KeyVaultRoleAssignment role assignments} asynchronously. + */ + public void listRoleAssignmentsAsync() { + // BEGIN: readme-sample-listRoleAssignmentsAsync + keyVaultAccessControlAsyncClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL) + .subscribe(roleAssignment -> + System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName())); + // END: readme-sample-listRoleAssignmentsAsync + } + + /** + * Code sample for creating a {@link KeyVaultRoleAssignment role assignment} asynchronously. + */ + public void createRoleAssignmentAsync() { + // BEGIN: readme-sample-createRoleAssignmentAsync + String roleDefinitionId = ""; + String servicePrincipalId = ""; + + keyVaultAccessControlAsyncClient.createRoleAssignment(KeyVaultRoleScope.GLOBAL, roleDefinitionId, + servicePrincipalId).subscribe(roleAssignment -> + System.out.printf("Created role assignment with randomly generated name '%s' for principal with id" + + "'%s'.%n", roleAssignment.getName(), roleAssignment.getProperties().getPrincipalId())); + // END: readme-sample-createRoleAssignmentAsync + } + + /** + * Code sample for getting a {@link KeyVaultRoleAssignment role assignment} asynchronously. + */ + public void getRoleAssignmentAsync() { + // BEGIN: readme-sample-getRoleAssignmentAsync + String roleAssignmentName = ""; + + keyVaultAccessControlAsyncClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName) + .subscribe(roleAssignment -> + System.out.printf("Retrieved role assignment with name '%s'.%n", roleAssignment.getName())); + // END: readme-sample-getRoleAssignmentAsync + } + + /** + * Code sample for deleting a {@link KeyVaultRoleAssignment role assignment} asynchronously. + */ + public void deleteRoleAssignmentAsync() { + // BEGIN: readme-sample-deleteRoleAssignmentAsync + String roleAssignmentName = ""; + + keyVaultAccessControlAsyncClient.deleteRoleAssignment(KeyVaultRoleScope.GLOBAL, roleAssignmentName) + .subscribe(unused -> + System.out.printf("Deleted role assignment with name '%s'.%n", roleAssignmentName)); + // END: readme-sample-deleteRoleAssignmentAsync + } + + /** + * Code sample for creating a {@link KeyVaultBackupClient}. + */ + public void createBackupClient() { + // BEGIN: readme-sample-createBackupClient + KeyVaultBackupClient keyVaultBackupClient = new KeyVaultBackupClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + // END: readme-sample-createBackupClient + } + + /** + * Code sample for starting a {@link KeyVaultBackupOperation pre-backup check}. + */ + public void beginPreBackup() { + // BEGIN: readme-sample-beginPreBackup + String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer"; + String sasToken = ""; + + SyncPoller preBackupPoller = + keyVaultBackupClient.beginPreBackup(blobStorageUrl, sasToken); + PollResponse pollResponse = preBackupPoller.poll(); + + System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()); + + PollResponse finalPollResponse = preBackupPoller.waitForCompletion(); + + if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { + String folderUrl = preBackupPoller.getFinalResult(); + + System.out.printf("Pre-backup check completed successfully.%n"); + } else { + KeyVaultBackupOperation operation = preBackupPoller.poll().getValue(); + + System.out.printf("Pre-backup check failed with error: %s.%n", operation.getError().getMessage()); + } + // END: readme-sample-beginPreBackup + } + + /** + * Code sample for starting a {@link KeyVaultBackupOperation backup operation}. + */ + public void beginBackup() { + // BEGIN: readme-sample-beginBackup + String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer"; + String sasToken = ""; + + SyncPoller backupPoller = + keyVaultBackupClient.beginBackup(blobStorageUrl, sasToken); + PollResponse pollResponse = backupPoller.poll(); + + System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()); + + PollResponse finalPollResponse = backupPoller.waitForCompletion(); + + if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { + String folderUrl = backupPoller.getFinalResult(); + + System.out.printf("Backup completed. The storage location of this backup is: %s.%n", folderUrl); + } else { + KeyVaultBackupOperation operation = backupPoller.poll().getValue(); + + System.out.printf("Backup failed with error: %s.%n", operation.getError().getMessage()); + } + // END: readme-sample-beginBackup + } + + /** + * Code sample for starting a {@link KeyVaultRestoreOperation pre-restore check}. + */ + public void beginPreRestore() { + // BEGIN: readme-sample-beginPreRestore + String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; + String sasToken = ""; + + SyncPoller preRestorePoller = + keyVaultBackupClient.beginPreRestore(folderUrl, sasToken); + PollResponse pollResponse = preRestorePoller.poll(); + + System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()); + + PollResponse finalPollResponse = preRestorePoller.waitForCompletion(); + + if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { + System.out.printf("Pre-restore check completed successfully.%n"); + } else { + KeyVaultRestoreOperation operation = preRestorePoller.poll().getValue(); + + System.out.printf("Pre-restore check failed with error: %s.%n", operation.getError().getMessage()); + } + // END: readme-sample-beginPreRestore + } + + /** + * Code sample for starting a {@link KeyVaultRestoreOperation restore operation}. + */ + public void beginRestore() { + // BEGIN: readme-sample-beginRestore + String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; + String sasToken = ""; + + SyncPoller restorePoller = + keyVaultBackupClient.beginRestore(folderUrl, sasToken); + PollResponse pollResponse = restorePoller.poll(); + + System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()); + + PollResponse finalPollResponse = restorePoller.waitForCompletion(); + + if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { + System.out.printf("Backup restored successfully.%n"); + } else { + KeyVaultRestoreOperation operation = restorePoller.poll().getValue(); + + System.out.printf("Restore failed with error: %s.%n", operation.getError().getMessage()); + } + // END: readme-sample-beginRestore + } + + /** + * Code sample for starting a {@link KeyVaultSelectiveKeyRestoreOperation selective key restore operation}. + */ + public void beginSelectiveKeyRestore() { + // BEGIN: readme-sample-beginSelectiveKeyRestore + String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; + String sasToken = ""; + String keyName = "myKey"; + + SyncPoller restorePoller = + keyVaultBackupClient.beginSelectiveKeyRestore(folderUrl, sasToken, keyName); + PollResponse pollResponse = restorePoller.poll(); + + System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus()); + + PollResponse finalPollResponse = restorePoller.waitForCompletion(); + + if (finalPollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) { + System.out.printf("Key restored successfully.%n"); + } else { + KeyVaultSelectiveKeyRestoreOperation operation = restorePoller.poll().getValue(); + + System.out.printf("Key restore failed with error: %s.%n", operation.getError().getMessage()); + } + // END: readme-sample-beginSelectiveKeyRestore + } + + /** + * Code sample for starting a {@link KeyVaultBackupOperation pre-backup check} asynchronously. + */ + public void beginPreBackupAsync() { + // BEGIN: readme-sample-beginPreBackupAsync + String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer"; + String sasToken = ""; + + keyVaultBackupAsyncClient.beginPreBackup(blobStorageUrl, sasToken) + .setPollInterval(Duration.ofSeconds(1)) // You can set a custom polling interval. + .doOnError(e -> System.out.printf("Pre-backup check failed with error: %s.%n", e.getMessage())) + .doOnNext(pollResponse -> + System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus())) + .filter(pollResponse -> pollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) + .flatMap(AsyncPollResponse::getFinalResult) + .subscribe(folderUrl -> + System.out.printf("Pre-backup check completed successfully.%n")); + // END: readme-sample-beginPreBackupAsync + } + + /** + * Code sample for starting a {@link KeyVaultBackupOperation backup operation} asynchronously. + */ + public void beginBackupAsync() { + // BEGIN: readme-sample-beginBackupAsync + String blobStorageUrl = "https://myaccount.blob.core.windows.net/myContainer"; + String sasToken = ""; + + keyVaultBackupAsyncClient.beginBackup(blobStorageUrl, sasToken) + .setPollInterval(Duration.ofSeconds(1)) // You can set a custom polling interval. + .doOnError(e -> System.out.printf("Backup failed with error: %s.%n", e.getMessage())) + .doOnNext(pollResponse -> + System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus())) + .filter(pollResponse -> pollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) + .flatMap(AsyncPollResponse::getFinalResult) + .subscribe(folderUrl -> + System.out.printf("Backup completed. The storage location of this backup is: %s.%n", folderUrl)); + // END: readme-sample-beginBackupAsync + } + + /** + * Code sample for starting a {@link KeyVaultRestoreOperation pre-restore check} asynchronously. + */ + public void beginPreRestoreAsync() { + // BEGIN: readme-sample-beginPreRestoreAsync + String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; + String sasToken = ""; + + keyVaultBackupAsyncClient.beginPreRestore(folderUrl, sasToken) + .setPollInterval(Duration.ofSeconds(1)) // You can set a custom polling interval. + .doOnError(e -> System.out.printf("Pre-restore check failed with error: %s.%n", e.getMessage())) + .doOnNext(pollResponse -> + System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus())) + .filter(pollResponse -> pollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) + .flatMap(AsyncPollResponse::getFinalResult) + .subscribe(unused -> System.out.printf("Pre-restore check completed successfully.%n")); + // END: readme-sample-beginPreRestoreAsync + } + + /** + * Code sample for starting a {@link KeyVaultRestoreOperation restore operation} asynchronously. + */ + public void beginRestoreAsync() { + // BEGIN: readme-sample-beginRestoreAsync + String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; + String sasToken = ""; + + keyVaultBackupAsyncClient.beginRestore(folderUrl, sasToken) + .setPollInterval(Duration.ofSeconds(1)) // You can set a custom polling interval. + .doOnError(e -> System.out.printf("Restore failed with error: %s.%n", e.getMessage())) + .doOnNext(pollResponse -> + System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus())) + .filter(pollResponse -> pollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) + .flatMap(AsyncPollResponse::getFinalResult) + .subscribe(unused -> System.out.printf("Backup restored successfully.%n")); + // END: readme-sample-beginRestoreAsync + } + + /** + * Code sample for starting a {@link KeyVaultSelectiveKeyRestoreOperation selective key restore operation} + * asynchronously. + */ + public void beginSelectiveKeyRestoreAsync() { + // BEGIN: readme-sample-beginSelectiveKeyRestoreAsync + String folderUrl = "https://myaccount.blob.core.windows.net/myContainer/mhsm-myaccount-2020090117323313"; + String sasToken = ""; + String keyName = "myKey"; + + keyVaultBackupAsyncClient.beginSelectiveKeyRestore(folderUrl, sasToken, keyName) + .setPollInterval(Duration.ofSeconds(1)) // You can set a custom polling interval. + .doOnError(e -> System.out.printf("Key restoration failed with error: %s.%n", e.getMessage())) + .doOnNext(pollResponse -> + System.out.printf("The current status of the operation is: %s.%n", pollResponse.getStatus())) + .filter(pollResponse -> pollResponse.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) + .flatMap(AsyncPollResponse::getFinalResult) + .subscribe(unused -> System.out.printf("Key restored successfully.%n")); + // END: readme-sample-beginSelectiveKeyRestoreAsync + } + + public void troubleshooting() { + // BEGIN: readme-sample-troubleshooting + try { + keyVaultAccessControlClient.getRoleAssignment(KeyVaultRoleScope.GLOBAL, ""); + } catch (HttpResponseException e) { + System.out.println(e.getMessage()); + } + // END: readme-sample-troubleshooting + } + + /** + * Code sample for updating a {@link KeyVaultSetting setting}. + */ + public void updateSetting() { + // BEGIN: readme-sample-updateSetting + String settingName = ""; + KeyVaultSetting settingToUpdate = new KeyVaultSetting(settingName, true); + KeyVaultSetting updatedSetting = keyVaultSettingsClient.updateSetting(settingToUpdate); + + System.out.printf("Updated setting '%s' to '%s'.%n", updatedSetting.getName(), updatedSetting.asBoolean()); + // END: readme-sample-updateSetting + } + + /** + * Code sample for retrieving a {@link KeyVaultSetting setting}. + */ + public void getSetting() { + // BEGIN: readme-sample-getSetting + String settingName = ""; + KeyVaultSetting setting = keyVaultSettingsClient.getSetting(settingName); + + System.out.printf("Retrieved setting '%s' with value '%s'.%n", setting.getName(), + setting.asBoolean()); + // END: readme-sample-getSetting + } + + /** + * Code sample for retrieving an account's {@link KeyVaultSetting settings}. + */ + public void getSettings() { + // BEGIN: readme-sample-getSettings + KeyVaultGetSettingsResult getSettingsResult = keyVaultSettingsClient.getSettings(); + + for (KeyVaultSetting setting : getSettingsResult.getSettings()) { + System.out.printf("Retrieved setting '%s' with value '%s'.%n", setting.getName(), setting.asBoolean()); + } + // END: readme-sample-getSettings + } + + /** + * Code sample for updating a {@link KeyVaultSetting setting} asynchronously. + */ + public void updateSettingAsync() { + // BEGIN: readme-sample-updateSettingAsync + String settingName = ""; + KeyVaultSetting settingToUpdate = new KeyVaultSetting(settingName, true); + + keyVaultSettingsAsyncClient.updateSetting(settingToUpdate) + .subscribe(updatedSetting -> + System.out.printf("Updated setting with name '%s' and value '%s'.%n", updatedSetting.getName(), + updatedSetting.asBoolean())); + // END: readme-sample-updateSettingAsync + } + + /** + * Code sample for retrieving a {@link KeyVaultSetting setting} asynchronously. + */ + public void getSettingAsync() { + // BEGIN: readme-sample-getSettingAsync + String settingName = ""; + + keyVaultSettingsAsyncClient.getSetting(settingName) + .subscribe(setting -> + System.out.printf("Retrieved setting with name '%s' and value '%s'.%n", setting.getName(), + setting.asBoolean())); + // END: readme-sample-getSettingAsync + } + + /** + * Code sample for retrieving an account's {@link KeyVaultSetting settings} asynchronously. + */ + public void getSettingsAsync() { + // BEGIN: readme-sample-getSettingsAsync + keyVaultSettingsAsyncClient.getSettings() + .subscribe(settingsResult -> + settingsResult.getSettings().forEach(setting -> + System.out.printf("Retrieved setting with name '%s' and value '%s'.%n", setting.getName(), + setting.asBoolean()))); + // END: readme-sample-getSettingsAsync + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample7/v1/SelectiveKeyRestore.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample7/v1/SelectiveKeyRestore.java new file mode 100644 index 000000000000..dc475d132179 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample7/v1/SelectiveKeyRestore.java @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.administration; + +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.administration.models.KeyVaultSelectiveKeyRestoreOperation; +import com.azure.security.keyvault.administration.models.KeyVaultSelectiveKeyRestoreResult; + +/** + * This sample demonstrates how to selectively restore a key from key vault backup. + */ +public class SelectiveKeyRestore { + /** + * Authenticates with the key vault and shows how to selectively restore a key from key vault backup synchronously. + * For examples of how to perform async operations, please refer to + * {@link BackupAndRestoreHelloWorldAsync the async client samples}. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when an invalid key vault URL is passed. + */ + public static void main(String[] args) { + /* Instantiate a KeyVaultBackupClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault Managed HSM. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md) + for links and instructions. */ + KeyVaultBackupClient backupClient = new KeyVaultBackupClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + /* Using the KeyVaultBackupClient, you can restore a single key from backup by key name. The data source for a + selective key restore is a storage blob accessed using Shared Access Signature authentication. */ + String keyName = ""; + String backupFolderUrl = ""; + String sasToken = ""; + + SyncPoller restorePoller = + backupClient.beginSelectiveKeyRestore(keyName, backupFolderUrl, sasToken); + + restorePoller.waitForCompletion(); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample7/v2/SelectiveKeyRestore.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample7/v2/SelectiveKeyRestore.java new file mode 100644 index 000000000000..dc475d132179 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample7/v2/SelectiveKeyRestore.java @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.administration; + +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.administration.models.KeyVaultSelectiveKeyRestoreOperation; +import com.azure.security.keyvault.administration.models.KeyVaultSelectiveKeyRestoreResult; + +/** + * This sample demonstrates how to selectively restore a key from key vault backup. + */ +public class SelectiveKeyRestore { + /** + * Authenticates with the key vault and shows how to selectively restore a key from key vault backup synchronously. + * For examples of how to perform async operations, please refer to + * {@link BackupAndRestoreHelloWorldAsync the async client samples}. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when an invalid key vault URL is passed. + */ + public static void main(String[] args) { + /* Instantiate a KeyVaultBackupClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault Managed HSM. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md) + for links and instructions. */ + KeyVaultBackupClient backupClient = new KeyVaultBackupClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + /* Using the KeyVaultBackupClient, you can restore a single key from backup by key name. The data source for a + selective key restore is a storage blob accessed using Shared Access Signature authentication. */ + String keyName = ""; + String backupFolderUrl = ""; + String sasToken = ""; + + SyncPoller restorePoller = + backupClient.beginSelectiveKeyRestore(keyName, backupFolderUrl, sasToken); + + restorePoller.waitForCompletion(); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample8/v1/SettingsHelloWorld.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample8/v1/SettingsHelloWorld.java new file mode 100644 index 000000000000..fd38aaebdfb0 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample8/v1/SettingsHelloWorld.java @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.administration; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.administration.models.KeyVaultGetSettingsResult; +import com.azure.security.keyvault.administration.models.KeyVaultSetting; + +import java.util.ArrayList; +import java.util.List; + +/** + * This sample demonstrates how to update, get, and lists settings synchronously for a Key Vault account. + */ +public class SettingsHelloWorld { + /** + * Authenticates with the key vault and shows how to update, get, and lists settings synchronously for a Key Vault + * account synchronously. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when an invalid key vault URL is passed. + */ + public static void main(String[] args) { + /* Instantiate a KeyVaultSettingsClient that will be used to call the service. Notice that the client is + using default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault Managed HSM. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md) + for links and instructions. */ + KeyVaultSettingsClient keyVaultSettingsClient = new KeyVaultSettingsClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + /* In order to update a setting, we'll have to know which ones are available for the account. Let's get all of + them. */ + List settings = new ArrayList<>(); + KeyVaultGetSettingsResult getSettingsResult = keyVaultSettingsClient.getSettings(); + + for (KeyVaultSetting setting : getSettingsResult.getSettings()) { + settings.add(setting); + + System.out.printf("Retrieved setting with name '%s' and value '%s'.%n", setting.getName(), + setting.asBoolean()); + } + + /* If you want to get only a specific setting and its value instead, you can do the following. */ + String settingName = settings.get(0).getName(); + KeyVaultSetting retrievedSetting = keyVaultSettingsClient.getSetting(settingName); + + System.out.printf("Retrieved setting with name '%s' and value '%s'.%n", retrievedSetting.getName(), + retrievedSetting.asBoolean()); + + /* Now let's update the settings to hold a new value. Currently, only boolean values are supported. */ + KeyVaultSetting settingToUpdate = new KeyVaultSetting(settingName, true); + KeyVaultSetting updatedSetting = keyVaultSettingsClient.updateSetting(settingToUpdate); + + System.out.printf("Updated setting with name '%s' to '%s'.%n", updatedSetting.getName(), + updatedSetting.asBoolean()); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample8/v2/SettingsHelloWorld.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample8/v2/SettingsHelloWorld.java new file mode 100644 index 000000000000..fd38aaebdfb0 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample8/v2/SettingsHelloWorld.java @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.administration; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.administration.models.KeyVaultGetSettingsResult; +import com.azure.security.keyvault.administration.models.KeyVaultSetting; + +import java.util.ArrayList; +import java.util.List; + +/** + * This sample demonstrates how to update, get, and lists settings synchronously for a Key Vault account. + */ +public class SettingsHelloWorld { + /** + * Authenticates with the key vault and shows how to update, get, and lists settings synchronously for a Key Vault + * account synchronously. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when an invalid key vault URL is passed. + */ + public static void main(String[] args) { + /* Instantiate a KeyVaultSettingsClient that will be used to call the service. Notice that the client is + using default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault Managed HSM. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md) + for links and instructions. */ + KeyVaultSettingsClient keyVaultSettingsClient = new KeyVaultSettingsClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + /* In order to update a setting, we'll have to know which ones are available for the account. Let's get all of + them. */ + List settings = new ArrayList<>(); + KeyVaultGetSettingsResult getSettingsResult = keyVaultSettingsClient.getSettings(); + + for (KeyVaultSetting setting : getSettingsResult.getSettings()) { + settings.add(setting); + + System.out.printf("Retrieved setting with name '%s' and value '%s'.%n", setting.getName(), + setting.asBoolean()); + } + + /* If you want to get only a specific setting and its value instead, you can do the following. */ + String settingName = settings.get(0).getName(); + KeyVaultSetting retrievedSetting = keyVaultSettingsClient.getSetting(settingName); + + System.out.printf("Retrieved setting with name '%s' and value '%s'.%n", retrievedSetting.getName(), + retrievedSetting.asBoolean()); + + /* Now let's update the settings to hold a new value. Currently, only boolean values are supported. */ + KeyVaultSetting settingToUpdate = new KeyVaultSetting(settingName, true); + KeyVaultSetting updatedSetting = keyVaultSettingsClient.updateSetting(settingToUpdate); + + System.out.printf("Updated setting with name '%s' to '%s'.%n", updatedSetting.getName(), + updatedSetting.asBoolean()); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample9/v1/SettingsHelloWorldAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample9/v1/SettingsHelloWorldAsync.java new file mode 100644 index 000000000000..2f687243c593 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample9/v1/SettingsHelloWorldAsync.java @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.administration; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.administration.models.KeyVaultSetting; + +import java.util.ArrayList; +import java.util.List; + +/** + * This sample demonstrates how to update, get, and lists settings asynchronously for a Key Vault account. + */ +public class SettingsHelloWorldAsync { + /** + * Authenticates with the key vault and shows how to update, get, and lists settings synchronously for a Key Vault + * account asynchronously. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when an invalid key vault URL is passed. + */ + public static void main(String[] args) { + /* Instantiate a KeyVaultSettingsAsyncClient that will be used to call the service. Notice that the client is + using default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault Managed HSM. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md) + for links and instructions. */ + KeyVaultSettingsAsyncClient keyVaultSettingsClient = new KeyVaultSettingsClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + /* In order to update a setting, we'll have to know which ones are available for the account. Let's get all of + them. */ + List settings = new ArrayList<>(); + + keyVaultSettingsClient.getSettings() + .subscribe(settingsResult -> + settingsResult.getSettings().forEach(setting -> { + settings.add(setting); + + System.out.printf("Retrieved setting with name '%s' and value '%s'.%n", setting.getName(), + setting.asBoolean()); + })); + + /* If you want to get only a specific setting and its value instead, you can do the following. */ + String settingName = settings.get(0).getName(); + + keyVaultSettingsClient.getSetting(settingName) + .subscribe(retrievedSetting -> { + System.out.printf("Retrieved setting with name '%s' and value '%s'.%n", retrievedSetting.getName(), + retrievedSetting.asBoolean()); + + /* Now let's update the setting to hold a new value. Currently, only boolean values are supported. */ + KeyVaultSetting settingToUpdate = new KeyVaultSetting(settingName, true); + + keyVaultSettingsClient.updateSetting(settingToUpdate).subscribe(updatedSetting -> + System.out.printf("Updated setting with name '%s' to '%s'.%n", updatedSetting.getName(), + updatedSetting.asBoolean())); + }); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample9/v2/SettingsHelloWorldAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample9/v2/SettingsHelloWorldAsync.java new file mode 100644 index 000000000000..2f687243c593 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-administration/sample9/v2/SettingsHelloWorldAsync.java @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.administration; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.administration.models.KeyVaultSetting; + +import java.util.ArrayList; +import java.util.List; + +/** + * This sample demonstrates how to update, get, and lists settings asynchronously for a Key Vault account. + */ +public class SettingsHelloWorldAsync { + /** + * Authenticates with the key vault and shows how to update, get, and lists settings synchronously for a Key Vault + * account asynchronously. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when an invalid key vault URL is passed. + */ + public static void main(String[] args) { + /* Instantiate a KeyVaultSettingsAsyncClient that will be used to call the service. Notice that the client is + using default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault Managed HSM. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-administration/README.md) + for links and instructions. */ + KeyVaultSettingsAsyncClient keyVaultSettingsClient = new KeyVaultSettingsClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + /* In order to update a setting, we'll have to know which ones are available for the account. Let's get all of + them. */ + List settings = new ArrayList<>(); + + keyVaultSettingsClient.getSettings() + .subscribe(settingsResult -> + settingsResult.getSettings().forEach(setting -> { + settings.add(setting); + + System.out.printf("Retrieved setting with name '%s' and value '%s'.%n", setting.getName(), + setting.asBoolean()); + })); + + /* If you want to get only a specific setting and its value instead, you can do the following. */ + String settingName = settings.get(0).getName(); + + keyVaultSettingsClient.getSetting(settingName) + .subscribe(retrievedSetting -> { + System.out.printf("Retrieved setting with name '%s' and value '%s'.%n", retrievedSetting.getName(), + retrievedSetting.asBoolean()); + + /* Now let's update the setting to hold a new value. Currently, only boolean values are supported. */ + KeyVaultSetting settingToUpdate = new KeyVaultSetting(settingName, true); + + keyVaultSettingsClient.updateSetting(settingToUpdate).subscribe(updatedSetting -> + System.out.printf("Updated setting with name '%s' to '%s'.%n", updatedSetting.getName(), + updatedSetting.asBoolean())); + }); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample1/v1/BackupAndRestoreOperations.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample1/v1/BackupAndRestoreOperations.java new file mode 100644 index 000000000000..0341156d2615 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample1/v1/BackupAndRestoreOperations.java @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.certificates; + +import com.azure.core.util.Context; +import com.azure.core.util.polling.LongRunningOperationStatus; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.certificates.models.CertificateKeyCurveName; +import com.azure.security.keyvault.certificates.models.CertificateKeyType; +import com.azure.security.keyvault.certificates.models.CertificateOperation; +import com.azure.security.keyvault.certificates.models.CertificatePolicy; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificate; +import com.azure.security.keyvault.certificates.models.DeletedCertificate; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificateWithPolicy; +import com.azure.security.keyvault.certificates.models.SubjectAlternativeNames; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * Sample demonstrates how to backup and restore certificates in the key vault. + */ +public class BackupAndRestoreOperations { + /** + * Authenticates with the key vault and shows how to backup and restore certificates in the key vault. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + * @throws IOException when writing backup to file is unsuccessful. + */ + public static void main(String[] args) throws IOException, InterruptedException, IllegalArgumentException { + /* Instantiate a CertificateClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-certificates/README.md) + for links and instructions. */ + CertificateClient certificateClient = new CertificateClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + // Let's create a self-signed certificate valid for 1 year. If the certificate already exists in the key vault, + // then a new version of the certificate is created. + CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12") + .setSubjectAlternativeNames(new SubjectAlternativeNames().setEmails(Arrays.asList("wow@gmail.com"))) + .setKeyReusable(true) + .setKeyCurveName(CertificateKeyCurveName.P_256) + .setKeyType(CertificateKeyType.EC); + Map tags = new HashMap<>(); + tags.put("foo", "bar"); + + SyncPoller certificatePoller = + certificateClient.beginCreateCertificate("certificateName", policy, true, tags); + certificatePoller.waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); + + KeyVaultCertificate cert = certificatePoller.getFinalResult(); + + // Backups are good to have, if in case certificates get accidentally deleted by you. + // For long term storage, it is ideal to write the backup to a file. + String backupFilePath = "YOUR_BACKUP_FILE_PATH"; + byte[] certificateBackup = certificateClient.backupCertificate("certificateName"); + + System.out.printf("Backed up certificate with back up blob length %d", certificateBackup.length); + + writeBackupToFile(certificateBackup, backupFilePath); + + // The certificate is no longer in use, so you delete it. + SyncPoller deletedCertificatePoller = + certificateClient.beginDeleteCertificate("certificateName"); + // Deleted Certificate is accessible as soon as polling beings. + PollResponse pollResponse = deletedCertificatePoller.poll(); + + System.out.printf("Deleted certificate with name %s and recovery id %s", pollResponse.getValue().getName(), + pollResponse.getValue().getRecoveryId()); + + deletedCertificatePoller.waitForCompletion(); + + // To ensure the certificate is deleted server-side. + Thread.sleep(30000); + + // If the vault is soft-delete enabled, then you need to purge the certificate as well for permanent deletion. + certificateClient.purgeDeletedCertificateWithResponse("certificateName", new Context("key1", "value1")); + + // To ensure the certificate is purged server-side. + Thread.sleep(15000); + + // After sometime, the certificate is required again. We can use the backup value to restore it in the key + // vault. + byte[] backupFromFile = Files.readAllBytes(new File(backupFilePath).toPath()); + KeyVaultCertificate restoredCertificate = certificateClient.restoreCertificateBackup(backupFromFile); + + System.out.printf(" Restored certificate with name %s and id %s", restoredCertificate.getProperties().getName(), + restoredCertificate.getProperties().getId()); + } + + private static void writeBackupToFile(byte[] bytes, String filePath) { + try { + File file = new File(filePath); + + if (file.exists()) { + file.delete(); + } + + file.createNewFile(); + + OutputStream os = new FileOutputStream(file); + os.write(bytes); + + System.out.println("Successfully wrote backup to file."); + + // Close the file + os.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample1/v2/BackupAndRestoreOperations.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample1/v2/BackupAndRestoreOperations.java new file mode 100644 index 000000000000..0341156d2615 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample1/v2/BackupAndRestoreOperations.java @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.certificates; + +import com.azure.core.util.Context; +import com.azure.core.util.polling.LongRunningOperationStatus; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.certificates.models.CertificateKeyCurveName; +import com.azure.security.keyvault.certificates.models.CertificateKeyType; +import com.azure.security.keyvault.certificates.models.CertificateOperation; +import com.azure.security.keyvault.certificates.models.CertificatePolicy; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificate; +import com.azure.security.keyvault.certificates.models.DeletedCertificate; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificateWithPolicy; +import com.azure.security.keyvault.certificates.models.SubjectAlternativeNames; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * Sample demonstrates how to backup and restore certificates in the key vault. + */ +public class BackupAndRestoreOperations { + /** + * Authenticates with the key vault and shows how to backup and restore certificates in the key vault. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + * @throws IOException when writing backup to file is unsuccessful. + */ + public static void main(String[] args) throws IOException, InterruptedException, IllegalArgumentException { + /* Instantiate a CertificateClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-certificates/README.md) + for links and instructions. */ + CertificateClient certificateClient = new CertificateClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + // Let's create a self-signed certificate valid for 1 year. If the certificate already exists in the key vault, + // then a new version of the certificate is created. + CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12") + .setSubjectAlternativeNames(new SubjectAlternativeNames().setEmails(Arrays.asList("wow@gmail.com"))) + .setKeyReusable(true) + .setKeyCurveName(CertificateKeyCurveName.P_256) + .setKeyType(CertificateKeyType.EC); + Map tags = new HashMap<>(); + tags.put("foo", "bar"); + + SyncPoller certificatePoller = + certificateClient.beginCreateCertificate("certificateName", policy, true, tags); + certificatePoller.waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); + + KeyVaultCertificate cert = certificatePoller.getFinalResult(); + + // Backups are good to have, if in case certificates get accidentally deleted by you. + // For long term storage, it is ideal to write the backup to a file. + String backupFilePath = "YOUR_BACKUP_FILE_PATH"; + byte[] certificateBackup = certificateClient.backupCertificate("certificateName"); + + System.out.printf("Backed up certificate with back up blob length %d", certificateBackup.length); + + writeBackupToFile(certificateBackup, backupFilePath); + + // The certificate is no longer in use, so you delete it. + SyncPoller deletedCertificatePoller = + certificateClient.beginDeleteCertificate("certificateName"); + // Deleted Certificate is accessible as soon as polling beings. + PollResponse pollResponse = deletedCertificatePoller.poll(); + + System.out.printf("Deleted certificate with name %s and recovery id %s", pollResponse.getValue().getName(), + pollResponse.getValue().getRecoveryId()); + + deletedCertificatePoller.waitForCompletion(); + + // To ensure the certificate is deleted server-side. + Thread.sleep(30000); + + // If the vault is soft-delete enabled, then you need to purge the certificate as well for permanent deletion. + certificateClient.purgeDeletedCertificateWithResponse("certificateName", new Context("key1", "value1")); + + // To ensure the certificate is purged server-side. + Thread.sleep(15000); + + // After sometime, the certificate is required again. We can use the backup value to restore it in the key + // vault. + byte[] backupFromFile = Files.readAllBytes(new File(backupFilePath).toPath()); + KeyVaultCertificate restoredCertificate = certificateClient.restoreCertificateBackup(backupFromFile); + + System.out.printf(" Restored certificate with name %s and id %s", restoredCertificate.getProperties().getName(), + restoredCertificate.getProperties().getId()); + } + + private static void writeBackupToFile(byte[] bytes, String filePath) { + try { + File file = new File(filePath); + + if (file.exists()) { + file.delete(); + } + + file.createNewFile(); + + OutputStream os = new FileOutputStream(file); + os.write(bytes); + + System.out.println("Successfully wrote backup to file."); + + // Close the file + os.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample10/v1/ManagingDeletedCertificatesAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample10/v1/ManagingDeletedCertificatesAsync.java new file mode 100644 index 000000000000..8bd2c46adea1 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample10/v1/ManagingDeletedCertificatesAsync.java @@ -0,0 +1,114 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.certificates; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.certificates.models.CertificatePolicy; +import com.azure.security.keyvault.certificates.models.SubjectAlternativeNames; +import com.azure.security.keyvault.certificates.models.CertificateKeyCurveName; +import com.azure.security.keyvault.certificates.models.CertificateKeyType; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * Sample demonstrates how to asynchronously list, recover and purge deleted certificates in a soft-delete enabled key vault. + */ +public class ManagingDeletedCertificatesAsync { + /** + * Authenticates with the key vault and shows how to asynchronously list, recover and purge deleted certificates in a soft-delete enabled key vault. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws InterruptedException { + /* NOTE: To manage deleted certificates, your key vault needs to have soft-delete enabled. Soft-delete allows + deleted certificates to be retained for a given retention period (90 days). During this period deleted + certificates can be recovered and if a certificates needs to be permanently deleted then it needs to be purged. + */ + + /* Instantiate a CertificateAsyncClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-certificates/README.md) + for links and instructions. */ + CertificateAsyncClient certificateAsyncClient = new CertificateClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + // Let's create a self-signed certificate valid for 1 year. If the certificate already exists in the key vault, + // then a new version of the certificate is created. + CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12") + .setSubjectAlternativeNames(new SubjectAlternativeNames().setEmails(Arrays.asList("wow@gmail.com"))) + .setKeyReusable(true) + .setKeyCurveName(CertificateKeyCurveName.P_256) + .setKeyType(CertificateKeyType.EC); + Map tags = new HashMap<>(); + tags.put("foo", "bar"); + + certificateAsyncClient.beginCreateCertificate("certificateName", policy, true, tags) + .subscribe(pollResponse -> { + System.out.println("---------------------------------------------------------------------------------"); + System.out.println(pollResponse.getStatus()); + System.out.println(pollResponse.getValue().getStatus()); + System.out.println(pollResponse.getValue().getStatusDetails()); + }); + + Thread.sleep(22000); + + // The certificate is no longer needed, need to delete it from the key vault. + certificateAsyncClient.beginDeleteCertificate("certificateName") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Delete Certificate Name: " + pollResponse.getValue().getName()); + System.out.println("Certificate Delete Date: " + pollResponse.getValue().getDeletedOn().toString()); + }); + + // To ensure the certificate is deleted server-side. + Thread.sleep(30000); + + // We accidentally deleted the certificate. Let's recover it. + // A deleted certificate can only be recovered if the key vault is soft-delete enabled. + certificateAsyncClient.beginRecoverDeletedCertificate("certificateName") + .subscribe(pollResponse -> { + System.out.println("Recovery Status: " + pollResponse.getStatus().toString()); + System.out.println("Recover Certificate Name: " + pollResponse.getValue().getName()); + System.out.println("Recover Certificate Id: " + pollResponse.getValue().getId()); + }); + + // To ensure the certificate is recovered server-side. + Thread.sleep(10000); + + // The certificate is no longer needed, need to delete it from the key vault. + certificateAsyncClient.beginDeleteCertificate("certificateName") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Delete Certificate Name: " + pollResponse.getValue().getName()); + System.out.println("Certificate Delete Date: " + pollResponse.getValue().getDeletedOn().toString()); + }); + + // To ensure the certificate is deleted server-side. + Thread.sleep(30000); + + // You can list all the deleted and non-purged certificates, assuming key vault is soft-delete enabled. + certificateAsyncClient.listDeletedCertificates() + .subscribe(deletedCertificateResponse -> System.out.printf("Deleted Certificate's Recovery Id %s %n", + deletedCertificateResponse.getRecoveryId())); + + Thread.sleep(15000); + + // If the keyvault is soft-delete enabled, then deleted certificates need to be purged for permanent deletion. + certificateAsyncClient.purgeDeletedCertificateWithResponse("certificateName") + .subscribe(purgeResponse -> + System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode())); + + // To ensure the certificate is purged server-side. + Thread.sleep(15000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample10/v2/ManagingDeletedCertificatesAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample10/v2/ManagingDeletedCertificatesAsync.java new file mode 100644 index 000000000000..8bd2c46adea1 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample10/v2/ManagingDeletedCertificatesAsync.java @@ -0,0 +1,114 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.certificates; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.certificates.models.CertificatePolicy; +import com.azure.security.keyvault.certificates.models.SubjectAlternativeNames; +import com.azure.security.keyvault.certificates.models.CertificateKeyCurveName; +import com.azure.security.keyvault.certificates.models.CertificateKeyType; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * Sample demonstrates how to asynchronously list, recover and purge deleted certificates in a soft-delete enabled key vault. + */ +public class ManagingDeletedCertificatesAsync { + /** + * Authenticates with the key vault and shows how to asynchronously list, recover and purge deleted certificates in a soft-delete enabled key vault. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws InterruptedException { + /* NOTE: To manage deleted certificates, your key vault needs to have soft-delete enabled. Soft-delete allows + deleted certificates to be retained for a given retention period (90 days). During this period deleted + certificates can be recovered and if a certificates needs to be permanently deleted then it needs to be purged. + */ + + /* Instantiate a CertificateAsyncClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-certificates/README.md) + for links and instructions. */ + CertificateAsyncClient certificateAsyncClient = new CertificateClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + // Let's create a self-signed certificate valid for 1 year. If the certificate already exists in the key vault, + // then a new version of the certificate is created. + CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12") + .setSubjectAlternativeNames(new SubjectAlternativeNames().setEmails(Arrays.asList("wow@gmail.com"))) + .setKeyReusable(true) + .setKeyCurveName(CertificateKeyCurveName.P_256) + .setKeyType(CertificateKeyType.EC); + Map tags = new HashMap<>(); + tags.put("foo", "bar"); + + certificateAsyncClient.beginCreateCertificate("certificateName", policy, true, tags) + .subscribe(pollResponse -> { + System.out.println("---------------------------------------------------------------------------------"); + System.out.println(pollResponse.getStatus()); + System.out.println(pollResponse.getValue().getStatus()); + System.out.println(pollResponse.getValue().getStatusDetails()); + }); + + Thread.sleep(22000); + + // The certificate is no longer needed, need to delete it from the key vault. + certificateAsyncClient.beginDeleteCertificate("certificateName") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Delete Certificate Name: " + pollResponse.getValue().getName()); + System.out.println("Certificate Delete Date: " + pollResponse.getValue().getDeletedOn().toString()); + }); + + // To ensure the certificate is deleted server-side. + Thread.sleep(30000); + + // We accidentally deleted the certificate. Let's recover it. + // A deleted certificate can only be recovered if the key vault is soft-delete enabled. + certificateAsyncClient.beginRecoverDeletedCertificate("certificateName") + .subscribe(pollResponse -> { + System.out.println("Recovery Status: " + pollResponse.getStatus().toString()); + System.out.println("Recover Certificate Name: " + pollResponse.getValue().getName()); + System.out.println("Recover Certificate Id: " + pollResponse.getValue().getId()); + }); + + // To ensure the certificate is recovered server-side. + Thread.sleep(10000); + + // The certificate is no longer needed, need to delete it from the key vault. + certificateAsyncClient.beginDeleteCertificate("certificateName") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Delete Certificate Name: " + pollResponse.getValue().getName()); + System.out.println("Certificate Delete Date: " + pollResponse.getValue().getDeletedOn().toString()); + }); + + // To ensure the certificate is deleted server-side. + Thread.sleep(30000); + + // You can list all the deleted and non-purged certificates, assuming key vault is soft-delete enabled. + certificateAsyncClient.listDeletedCertificates() + .subscribe(deletedCertificateResponse -> System.out.printf("Deleted Certificate's Recovery Id %s %n", + deletedCertificateResponse.getRecoveryId())); + + Thread.sleep(15000); + + // If the keyvault is soft-delete enabled, then deleted certificates need to be purged for permanent deletion. + certificateAsyncClient.purgeDeletedCertificateWithResponse("certificateName") + .subscribe(purgeResponse -> + System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode())); + + // To ensure the certificate is purged server-side. + Thread.sleep(15000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample11/v1/ReadmeSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample11/v1/ReadmeSamples.java new file mode 100644 index 000000000000..bbf24b92e143 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample11/v1/ReadmeSamples.java @@ -0,0 +1,166 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.certificates; + +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.util.polling.LongRunningOperationStatus; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.certificates.models.CertificateOperation; +import com.azure.security.keyvault.certificates.models.CertificatePolicy; +import com.azure.security.keyvault.certificates.models.CertificateProperties; +import com.azure.security.keyvault.certificates.models.DeletedCertificate; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificate; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificateWithPolicy; + +@SuppressWarnings("unused") +public class ReadmeSamples { + private final CertificateClient certificateClient = new CertificateClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + private final CertificateAsyncClient certificateAsyncClient = new CertificateClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + public void createCertificateClient() { + // BEGIN: readme-sample-createCertificateClient + CertificateClient certificateClient = new CertificateClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + // END: readme-sample-createCertificateClient + } + + public void createCertificate() { + // BEGIN: readme-sample-createCertificate + SyncPoller certificatePoller = + certificateClient.beginCreateCertificate("certificateName", CertificatePolicy.getDefault()); + certificatePoller.waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); + KeyVaultCertificate certificate = certificatePoller.getFinalResult(); + System.out.printf("Certificate created with name \"%s\"%n", certificate.getName()); + // END: readme-sample-createCertificate + } + + public void retrieveCertificate() { + // BEGIN: readme-sample-retrieveCertificate + KeyVaultCertificateWithPolicy certificate = certificateClient.getCertificate(""); + System.out.printf("Received certificate with name \"%s\", version %s and secret id %s%n", + certificate.getProperties().getName(), certificate.getProperties().getVersion(), certificate.getSecretId()); + // END: readme-sample-retrieveCertificate + } + + public void updateCertificate() { + // BEGIN: readme-sample-updateCertificate + // Get the certificate to update. + KeyVaultCertificate certificate = certificateClient.getCertificate(""); + // Update certificate enabled status. + certificate.getProperties().setEnabled(false); + KeyVaultCertificate updatedCertificate = certificateClient.updateCertificateProperties(certificate.getProperties()); + System.out.printf("Updated certificate with name \"%s\" and enabled status \"%s\"%n", + updatedCertificate.getProperties().getName(), updatedCertificate.getProperties().isEnabled()); + // END: readme-sample-updateCertificate + } + + public void deleteCertificate() { + // BEGIN: readme-sample-deleteCertificate + SyncPoller deleteCertificatePoller = + certificateClient.beginDeleteCertificate(""); + + // Deleted certificate is accessible as soon as polling beings. + PollResponse pollResponse = deleteCertificatePoller.poll(); + + // Deletion date only works for a SoftDelete-enabled Key Vault. + System.out.printf("Deleted certificate with name \"%s\" and recovery id %s", pollResponse.getValue().getName(), + pollResponse.getValue().getRecoveryId()); + + // Certificate is being deleted on server. + deleteCertificatePoller.waitForCompletion(); + // END: readme-sample-deleteCertificate + } + + public void listCertificates() { + // BEGIN: readme-sample-listCertificates + // List operations don't return the certificates with their full information. So, for each returned certificate we call + // getCertificate to get the certificate with all its properties excluding the policy. + for (CertificateProperties certificateProperties : certificateClient.listPropertiesOfCertificates()) { + KeyVaultCertificate certificateWithAllProperties = + certificateClient.getCertificateVersion(certificateProperties.getName(), certificateProperties.getVersion()); + System.out.printf("Received certificate with name \"%s\" and secret id %s", + certificateWithAllProperties.getProperties().getName(), certificateWithAllProperties.getSecretId()); + } + // END: readme-sample-listCertificates + } + + public void createCertificateAsync() { + // BEGIN: readme-sample-createCertificateAsync + // Creates a certificate using the default policy and polls on its progress. + certificateAsyncClient.beginCreateCertificate("", CertificatePolicy.getDefault()) + .subscribe(pollResponse -> { + System.out.println("---------------------------------------------------------------------------------"); + System.out.println(pollResponse.getStatus()); + System.out.println(pollResponse.getValue().getStatus()); + System.out.println(pollResponse.getValue().getStatusDetails()); + }); + // END: readme-sample-createCertificateAsync + } + + public void retrieveCertificateAsync() { + // BEGIN: readme-sample-retrieveCertificateAsync + certificateAsyncClient.getCertificate("") + .subscribe(certificateResponse -> + System.out.printf("Certificate was returned with name \"%s\" and secretId %s%n", + certificateResponse.getProperties().getName(), certificateResponse.getSecretId())); + // END: readme-sample-retrieveCertificateAsync + } + + public void updateCertificateAsync() { + // BEGIN: readme-sample-updateCertificateAsync + certificateAsyncClient.getCertificate("") + .flatMap(certificate -> { + // Update enabled status of the certificate. + certificate.getProperties().setEnabled(false); + return certificateAsyncClient.updateCertificateProperties(certificate.getProperties()); + }).subscribe(certificateResponse -> System.out.printf("Certificate's enabled status: %s%n", + certificateResponse.getProperties().isEnabled())); + // END: readme-sample-updateCertificateAsync + } + + public void deleteCertificateAsync() { + // BEGIN: readme-sample-deleteCertificateAsync + certificateAsyncClient.beginDeleteCertificate("") + .subscribe(pollResponse -> { + System.out.printf("Deletion status: %s%n", pollResponse.getStatus()); + System.out.printf("Deleted certificate name: %s%n", pollResponse.getValue().getName()); + System.out.printf("Certificate deletion date: %s%n", pollResponse.getValue().getDeletedOn()); + }); + // END: readme-sample-deleteCertificateAsync + } + + public void listCertificateAsync() { + // BEGIN: readme-sample-listCertificateAsync + // The List Certificates operation returns certificates without their full properties, so for each certificate returned + // we call `getCertificate` to get all its attributes excluding the policy. + certificateAsyncClient.listPropertiesOfCertificates() + .flatMap(certificateProperties -> certificateAsyncClient + .getCertificateVersion(certificateProperties.getName(), certificateProperties.getVersion())) + .subscribe(certificateResponse -> + System.out.printf("Received certificate with name \"%s\" and key id %s", certificateResponse.getName(), + certificateResponse.getKeyId())); + // END: readme-sample-listCertificateAsync + } + + public void troubleshooting() { + // BEGIN: readme-sample-troubleshooting + try { + certificateClient.getCertificate(""); + } catch (ResourceNotFoundException e) { + System.out.println(e.getMessage()); + } + // END: readme-sample-troubleshooting + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample11/v2/ReadmeSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample11/v2/ReadmeSamples.java new file mode 100644 index 000000000000..bbf24b92e143 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample11/v2/ReadmeSamples.java @@ -0,0 +1,166 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.certificates; + +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.util.polling.LongRunningOperationStatus; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.certificates.models.CertificateOperation; +import com.azure.security.keyvault.certificates.models.CertificatePolicy; +import com.azure.security.keyvault.certificates.models.CertificateProperties; +import com.azure.security.keyvault.certificates.models.DeletedCertificate; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificate; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificateWithPolicy; + +@SuppressWarnings("unused") +public class ReadmeSamples { + private final CertificateClient certificateClient = new CertificateClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + private final CertificateAsyncClient certificateAsyncClient = new CertificateClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + public void createCertificateClient() { + // BEGIN: readme-sample-createCertificateClient + CertificateClient certificateClient = new CertificateClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + // END: readme-sample-createCertificateClient + } + + public void createCertificate() { + // BEGIN: readme-sample-createCertificate + SyncPoller certificatePoller = + certificateClient.beginCreateCertificate("certificateName", CertificatePolicy.getDefault()); + certificatePoller.waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); + KeyVaultCertificate certificate = certificatePoller.getFinalResult(); + System.out.printf("Certificate created with name \"%s\"%n", certificate.getName()); + // END: readme-sample-createCertificate + } + + public void retrieveCertificate() { + // BEGIN: readme-sample-retrieveCertificate + KeyVaultCertificateWithPolicy certificate = certificateClient.getCertificate(""); + System.out.printf("Received certificate with name \"%s\", version %s and secret id %s%n", + certificate.getProperties().getName(), certificate.getProperties().getVersion(), certificate.getSecretId()); + // END: readme-sample-retrieveCertificate + } + + public void updateCertificate() { + // BEGIN: readme-sample-updateCertificate + // Get the certificate to update. + KeyVaultCertificate certificate = certificateClient.getCertificate(""); + // Update certificate enabled status. + certificate.getProperties().setEnabled(false); + KeyVaultCertificate updatedCertificate = certificateClient.updateCertificateProperties(certificate.getProperties()); + System.out.printf("Updated certificate with name \"%s\" and enabled status \"%s\"%n", + updatedCertificate.getProperties().getName(), updatedCertificate.getProperties().isEnabled()); + // END: readme-sample-updateCertificate + } + + public void deleteCertificate() { + // BEGIN: readme-sample-deleteCertificate + SyncPoller deleteCertificatePoller = + certificateClient.beginDeleteCertificate(""); + + // Deleted certificate is accessible as soon as polling beings. + PollResponse pollResponse = deleteCertificatePoller.poll(); + + // Deletion date only works for a SoftDelete-enabled Key Vault. + System.out.printf("Deleted certificate with name \"%s\" and recovery id %s", pollResponse.getValue().getName(), + pollResponse.getValue().getRecoveryId()); + + // Certificate is being deleted on server. + deleteCertificatePoller.waitForCompletion(); + // END: readme-sample-deleteCertificate + } + + public void listCertificates() { + // BEGIN: readme-sample-listCertificates + // List operations don't return the certificates with their full information. So, for each returned certificate we call + // getCertificate to get the certificate with all its properties excluding the policy. + for (CertificateProperties certificateProperties : certificateClient.listPropertiesOfCertificates()) { + KeyVaultCertificate certificateWithAllProperties = + certificateClient.getCertificateVersion(certificateProperties.getName(), certificateProperties.getVersion()); + System.out.printf("Received certificate with name \"%s\" and secret id %s", + certificateWithAllProperties.getProperties().getName(), certificateWithAllProperties.getSecretId()); + } + // END: readme-sample-listCertificates + } + + public void createCertificateAsync() { + // BEGIN: readme-sample-createCertificateAsync + // Creates a certificate using the default policy and polls on its progress. + certificateAsyncClient.beginCreateCertificate("", CertificatePolicy.getDefault()) + .subscribe(pollResponse -> { + System.out.println("---------------------------------------------------------------------------------"); + System.out.println(pollResponse.getStatus()); + System.out.println(pollResponse.getValue().getStatus()); + System.out.println(pollResponse.getValue().getStatusDetails()); + }); + // END: readme-sample-createCertificateAsync + } + + public void retrieveCertificateAsync() { + // BEGIN: readme-sample-retrieveCertificateAsync + certificateAsyncClient.getCertificate("") + .subscribe(certificateResponse -> + System.out.printf("Certificate was returned with name \"%s\" and secretId %s%n", + certificateResponse.getProperties().getName(), certificateResponse.getSecretId())); + // END: readme-sample-retrieveCertificateAsync + } + + public void updateCertificateAsync() { + // BEGIN: readme-sample-updateCertificateAsync + certificateAsyncClient.getCertificate("") + .flatMap(certificate -> { + // Update enabled status of the certificate. + certificate.getProperties().setEnabled(false); + return certificateAsyncClient.updateCertificateProperties(certificate.getProperties()); + }).subscribe(certificateResponse -> System.out.printf("Certificate's enabled status: %s%n", + certificateResponse.getProperties().isEnabled())); + // END: readme-sample-updateCertificateAsync + } + + public void deleteCertificateAsync() { + // BEGIN: readme-sample-deleteCertificateAsync + certificateAsyncClient.beginDeleteCertificate("") + .subscribe(pollResponse -> { + System.out.printf("Deletion status: %s%n", pollResponse.getStatus()); + System.out.printf("Deleted certificate name: %s%n", pollResponse.getValue().getName()); + System.out.printf("Certificate deletion date: %s%n", pollResponse.getValue().getDeletedOn()); + }); + // END: readme-sample-deleteCertificateAsync + } + + public void listCertificateAsync() { + // BEGIN: readme-sample-listCertificateAsync + // The List Certificates operation returns certificates without their full properties, so for each certificate returned + // we call `getCertificate` to get all its attributes excluding the policy. + certificateAsyncClient.listPropertiesOfCertificates() + .flatMap(certificateProperties -> certificateAsyncClient + .getCertificateVersion(certificateProperties.getName(), certificateProperties.getVersion())) + .subscribe(certificateResponse -> + System.out.printf("Received certificate with name \"%s\" and key id %s", certificateResponse.getName(), + certificateResponse.getKeyId())); + // END: readme-sample-listCertificateAsync + } + + public void troubleshooting() { + // BEGIN: readme-sample-troubleshooting + try { + certificateClient.getCertificate(""); + } catch (ResourceNotFoundException e) { + System.out.println(e.getMessage()); + } + // END: readme-sample-troubleshooting + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample2/v1/BackupAndRestoreOperationsAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample2/v1/BackupAndRestoreOperationsAsync.java new file mode 100644 index 000000000000..1629f9d2a789 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample2/v1/BackupAndRestoreOperationsAsync.java @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.certificates; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.certificates.models.CertificatePolicy; +import com.azure.security.keyvault.certificates.models.SubjectAlternativeNames; +import com.azure.security.keyvault.certificates.models.CertificateKeyCurveName; +import com.azure.security.keyvault.certificates.models.CertificateKeyType; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * Sample demonstrates how to asynchronously backup and restore certificates in the key vault. + */ +public class BackupAndRestoreOperationsAsync { + /** + * Authenticates with the key vault and shows how to asynchronously backup and restore certificates in the key vault. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + * @throws IOException when writing backup to file is unsuccessful. + */ + public static void main(String[] args) throws IOException, InterruptedException, IllegalArgumentException { + /* Instantiate a CertificateAsyncClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-certificates/README.md) + for links and instructions. */ + CertificateAsyncClient certificateAsyncClient = new CertificateClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + // Let's create a self-signed certificate valid for 1 year. If the certificate already exists in the key vault, + // then a new version of the certificate is created. + CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12") + .setSubjectAlternativeNames(new SubjectAlternativeNames().setEmails(Arrays.asList("wow@gmail.com"))) + .setKeyReusable(true) + .setKeyCurveName(CertificateKeyCurveName.P_256) + .setKeyType(CertificateKeyType.EC); + Map tags = new HashMap<>(); + tags.put("foo", "bar"); + + certificateAsyncClient.beginCreateCertificate("certificateName", policy, true, tags) + .subscribe(pollResponse -> { + System.out.println("---------------------------------------------------------------------------------"); + System.out.println(pollResponse.getStatus()); + System.out.println(pollResponse.getValue().getStatus()); + System.out.println(pollResponse.getValue().getStatusDetails()); + }); + + Thread.sleep(22000); + + // Backups are good to have, if in case certificates get accidentally deleted by you. + // For long term storage, it is ideal to write the backup to a file. + String backupFilePath = "YOUR_BACKUP_FILE_PATH"; + + certificateAsyncClient.backupCertificate("certificateName") + .subscribe(certificateBackupResponse -> { + writeBackupToFile(certificateBackupResponse, backupFilePath); + System.out.printf("Certificate's Backup Byte array's length %s %n", certificateBackupResponse.length); + }); + + Thread.sleep(7000); + + // The certificate is no longer in use, so you delete it. + certificateAsyncClient.beginDeleteCertificate("certificateName") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Delete Certificate Name: " + pollResponse.getValue().getName()); + System.out.println("Certificate Delete Date: " + pollResponse.getValue().getDeletedOn().toString()); + }); + + // To ensure the certificate is deleted server-side. + Thread.sleep(30000); + + // If the vault is soft-delete enabled, then you need to purge the certificate as well for permanent deletion. + certificateAsyncClient.purgeDeletedCertificateWithResponse("certificateName") + .subscribe(purgeResponse -> + System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode())); + + // To ensure certificate is purged server-side. + Thread.sleep(15000); + + // After sometime, the certificate is required again. We can use the backup value to restore it in the key vault. + byte[] backupFromFile = Files.readAllBytes(new File(backupFilePath).toPath()); + + certificateAsyncClient.restoreCertificateBackup(backupFromFile) + .subscribe(certificateResponse -> System.out.printf("Restored Certificate with name %s and key id %s %n", + certificateResponse.getProperties().getName(), certificateResponse.getKeyId())); + + // To ensure the certificate is restored server-side. + Thread.sleep(15000); + } + + private static void writeBackupToFile(byte[] bytes, String filePath) { + try { + File file = new File(filePath); + + if (file.exists()) { + file.delete(); + } + + file.createNewFile(); + + OutputStream os = new FileOutputStream(file); + os.write(bytes); + + System.out.println("Successfully wrote backup to file."); + + // Close the file + os.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample2/v2/BackupAndRestoreOperationsAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample2/v2/BackupAndRestoreOperationsAsync.java new file mode 100644 index 000000000000..1629f9d2a789 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample2/v2/BackupAndRestoreOperationsAsync.java @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.certificates; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.certificates.models.CertificatePolicy; +import com.azure.security.keyvault.certificates.models.SubjectAlternativeNames; +import com.azure.security.keyvault.certificates.models.CertificateKeyCurveName; +import com.azure.security.keyvault.certificates.models.CertificateKeyType; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * Sample demonstrates how to asynchronously backup and restore certificates in the key vault. + */ +public class BackupAndRestoreOperationsAsync { + /** + * Authenticates with the key vault and shows how to asynchronously backup and restore certificates in the key vault. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + * @throws IOException when writing backup to file is unsuccessful. + */ + public static void main(String[] args) throws IOException, InterruptedException, IllegalArgumentException { + /* Instantiate a CertificateAsyncClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-certificates/README.md) + for links and instructions. */ + CertificateAsyncClient certificateAsyncClient = new CertificateClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + // Let's create a self-signed certificate valid for 1 year. If the certificate already exists in the key vault, + // then a new version of the certificate is created. + CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12") + .setSubjectAlternativeNames(new SubjectAlternativeNames().setEmails(Arrays.asList("wow@gmail.com"))) + .setKeyReusable(true) + .setKeyCurveName(CertificateKeyCurveName.P_256) + .setKeyType(CertificateKeyType.EC); + Map tags = new HashMap<>(); + tags.put("foo", "bar"); + + certificateAsyncClient.beginCreateCertificate("certificateName", policy, true, tags) + .subscribe(pollResponse -> { + System.out.println("---------------------------------------------------------------------------------"); + System.out.println(pollResponse.getStatus()); + System.out.println(pollResponse.getValue().getStatus()); + System.out.println(pollResponse.getValue().getStatusDetails()); + }); + + Thread.sleep(22000); + + // Backups are good to have, if in case certificates get accidentally deleted by you. + // For long term storage, it is ideal to write the backup to a file. + String backupFilePath = "YOUR_BACKUP_FILE_PATH"; + + certificateAsyncClient.backupCertificate("certificateName") + .subscribe(certificateBackupResponse -> { + writeBackupToFile(certificateBackupResponse, backupFilePath); + System.out.printf("Certificate's Backup Byte array's length %s %n", certificateBackupResponse.length); + }); + + Thread.sleep(7000); + + // The certificate is no longer in use, so you delete it. + certificateAsyncClient.beginDeleteCertificate("certificateName") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Delete Certificate Name: " + pollResponse.getValue().getName()); + System.out.println("Certificate Delete Date: " + pollResponse.getValue().getDeletedOn().toString()); + }); + + // To ensure the certificate is deleted server-side. + Thread.sleep(30000); + + // If the vault is soft-delete enabled, then you need to purge the certificate as well for permanent deletion. + certificateAsyncClient.purgeDeletedCertificateWithResponse("certificateName") + .subscribe(purgeResponse -> + System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode())); + + // To ensure certificate is purged server-side. + Thread.sleep(15000); + + // After sometime, the certificate is required again. We can use the backup value to restore it in the key vault. + byte[] backupFromFile = Files.readAllBytes(new File(backupFilePath).toPath()); + + certificateAsyncClient.restoreCertificateBackup(backupFromFile) + .subscribe(certificateResponse -> System.out.printf("Restored Certificate with name %s and key id %s %n", + certificateResponse.getProperties().getName(), certificateResponse.getKeyId())); + + // To ensure the certificate is restored server-side. + Thread.sleep(15000); + } + + private static void writeBackupToFile(byte[] bytes, String filePath) { + try { + File file = new File(filePath); + + if (file.exists()) { + file.delete(); + } + + file.createNewFile(); + + OutputStream os = new FileOutputStream(file); + os.write(bytes); + + System.out.println("Successfully wrote backup to file."); + + // Close the file + os.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample3/v1/CertificateAsyncClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample3/v1/CertificateAsyncClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..aae07eaf33f3 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample3/v1/CertificateAsyncClientJavaDocCodeSnippets.java @@ -0,0 +1,655 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.certificates; + + +import com.azure.core.http.HttpClient; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.policy.HttpLogOptions; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.certificates.models.CertificateContact; +import com.azure.security.keyvault.certificates.models.CertificateIssuer; +import com.azure.security.keyvault.certificates.models.CertificatePolicy; +import com.azure.security.keyvault.certificates.models.CertificateProperties; +import com.azure.security.keyvault.certificates.models.ImportCertificateOptions; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificate; +import com.azure.security.keyvault.certificates.models.MergeCertificateOptions; +import reactor.util.context.Context; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +/** + * This class contains code samples for generating javadocs through doclets for {@link CertificateAsyncClient} + */ +public final class CertificateAsyncClientJavaDocCodeSnippets { + private final String key1 = "key1"; + private final String key2 = "key2"; + private final String value1 = "val1"; + private final String value2 = "val2"; + + /** + * Generates code sample for creating a {@link CertificateAsyncClient} + * @return An instance of {@link CertificateAsyncClient} + */ + public CertificateAsyncClient createAsyncClientWithHttpclient() { + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.instantiation.withHttpClient + CertificateAsyncClient certificateAsyncClient = new CertificateClientBuilder() + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .httpClient(HttpClient.createDefault()) + .buildAsyncClient(); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.instantiation.withHttpClient + return certificateAsyncClient; + } + + /** + * Implementation for async CertificateAsyncClient + * @return sync CertificateAsyncClient + */ + private CertificateAsyncClient getCertificateAsyncClient() { + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.instantiation + CertificateAsyncClient certificateAsyncClient = new CertificateClientBuilder() + .credential(new DefaultAzureCredentialBuilder().build()) + .vaultUrl("") + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) + .buildAsyncClient(); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.instantiation + return certificateAsyncClient; + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#getCertificatePolicy(String)} + */ + public void getCertificatePolicyCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificatePolicy#string + certificateAsyncClient.getCertificatePolicy("certificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(policy -> + System.out.printf("Certificate policy is returned with issuer name %s and subject name %s %n", + policy.getIssuerName(), policy.getSubject())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificatePolicy#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificatePolicyWithResponse#string + certificateAsyncClient.getCertificatePolicyWithResponse("certificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(policyResponse -> + System.out.printf("Certificate policy is returned with issuer name %s and subject name %s %n", + policyResponse.getValue().getIssuerName(), policyResponse.getValue().getSubject())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificatePolicyWithResponse#string + } + + + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#getCertificate(String)} + */ + public void getCertificateWithResponseCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificate#String + certificateAsyncClient.getCertificate("certificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificateResponse -> + System.out.printf("Certificate is returned with name %s and secretId %s %n", + certificateResponse.getProperties().getName(), certificateResponse.getSecretId())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificate#String + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateWithResponse#String + certificateAsyncClient.getCertificateWithResponse("certificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificateResponse -> + System.out.printf("Certificate is returned with name %s and secretId %s %n", + certificateResponse.getValue().getProperties().getName(), + certificateResponse.getValue().getSecretId())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateWithResponse#String + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateVersionWithResponse#string-string + String certificateVersion = "6A385B124DEF4096AF1361A85B16C204"; + certificateAsyncClient.getCertificateVersionWithResponse("certificateName", certificateVersion) + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificateWithVersion -> + System.out.printf("Certificate is returned with name %s and secretId %s %n", + certificateWithVersion.getValue().getProperties().getName(), + certificateWithVersion.getValue().getSecretId())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateVersionWithResponse#string-string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateVersion#String-String + certificateAsyncClient.getCertificateVersion("certificateName", certificateVersion) + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificateWithVersion -> + System.out.printf("Certificate is returned with name %s and secretId %s %n", + certificateWithVersion.getProperties().getName(), certificateWithVersion.getSecretId())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateVersion#String-String + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificate#CertificateProperties + certificateAsyncClient.getCertificate("certificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificate -> certificateAsyncClient.getCertificateVersion(certificate.getName(), + certificate.getProperties().getVersion()) + .subscribe(certificateResponse -> + System.out.printf("Certificate is returned with name %s and secretId %s %n", + certificateResponse.getProperties().getName(), certificateResponse.getSecretId()))); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificate#CertificateProperties + } + + /** + * Method to insert code snippets for + * {@link CertificateAsyncClient#beginCreateCertificate(String, CertificatePolicy, Boolean, Map)} and + * {@link CertificateAsyncClient#beginCreateCertificate(String, CertificatePolicy)}. + */ + public void createCertificateCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.beginCreateCertificate#String-CertificatePolicy-Boolean-Map + CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12"); + Map tags = new HashMap<>(); + tags.put("foo", "bar"); + certificateAsyncClient.beginCreateCertificate("certificateName", policy, true, tags) + .subscribe(pollResponse -> { + System.out.println("---------------------------------------------------------------------------------"); + System.out.println(pollResponse.getStatus()); + System.out.println(pollResponse.getValue().getStatus()); + System.out.println(pollResponse.getValue().getStatusDetails()); + }); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.beginCreateCertificate#String-CertificatePolicy-Boolean-Map + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.beginCreateCertificate#String-CertificatePolicy + CertificatePolicy certPolicy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12"); + certificateAsyncClient.beginCreateCertificate("certificateName", certPolicy) + .subscribe(pollResponse -> { + System.out.println("---------------------------------------------------------------------------------"); + System.out.println(pollResponse.getStatus()); + System.out.println(pollResponse.getValue().getStatus()); + System.out.println(pollResponse.getValue().getStatusDetails()); + }); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.beginCreateCertificate#String-CertificatePolicy + } + + /** + * Method to insert code snippets for + * {@link CertificateAsyncClient#getCertificateOperation(String)}. + */ + public void getCertificateOperation() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateOperation#String + certificateAsyncClient.getCertificateOperation("certificateName") + .subscribe(pollResponse -> { + System.out.println("---------------------------------------------------------------------------------"); + System.out.println(pollResponse.getStatus()); + System.out.println(pollResponse.getValue().getStatus()); + System.out.println(pollResponse.getValue().getStatusDetails()); + }); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateOperation#String + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#createIssuer(CertificateIssuer)} + */ + public void createCertificateIssuerCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.createIssuer#CertificateIssuer + CertificateIssuer issuer = new CertificateIssuer("issuerName", "providerName") + .setAccountId("keyvaultuser") + .setPassword("fakePasswordPlaceholder"); + certificateAsyncClient.createIssuer(issuer) + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(issuerResponse -> { + System.out.printf("Issuer created with %s and %s", issuerResponse.getName(), + issuerResponse.getProvider()); + }); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.createIssuer#CertificateIssuer + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.createIssuerWithResponse#CertificateIssuer + CertificateIssuer newIssuer = new CertificateIssuer("issuerName", "providerName") + .setAccountId("keyvaultuser") + .setPassword("fakePasswordPlaceholder"); + certificateAsyncClient.createIssuerWithResponse(newIssuer) + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(issuerResponse -> { + System.out.printf("Issuer created with %s and %s", issuerResponse.getValue().getName(), + issuerResponse.getValue().getProvider()); + }); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.createIssuerWithResponse#CertificateIssuer + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#getIssuer(String)} + */ + public void getCertificateIssuerCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.getIssuer#string + certificateAsyncClient.getIssuer("issuerName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(issuer -> { + System.out.printf("Issuer returned with %s and %s", issuer.getName(), + issuer.getProvider()); + }); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.getIssuer#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.getIssuerWithResponse#string + certificateAsyncClient.getIssuerWithResponse("issuerName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(issuerResponse -> { + System.out.printf("Issuer returned with %s and %s", issuerResponse.getValue().getName(), + issuerResponse.getValue().getProvider()); + }); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.getIssuerWithResponse#string + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#updateCertificateProperties(CertificateProperties)} + */ + public void updateCertificateCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.updateCertificateProperties#CertificateProperties + certificateAsyncClient.getCertificate("certificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificateResponseValue -> { + KeyVaultCertificate certificate = certificateResponseValue; + //Update enabled status of the certificate + certificate.getProperties().setEnabled(false); + certificateAsyncClient.updateCertificateProperties(certificate.getProperties()) + .subscribe(certificateResponse -> + System.out.printf("Certificate's enabled status %s %n", + certificateResponse.getProperties().isEnabled().toString())); + }); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.updateCertificateProperties#CertificateProperties + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#updateIssuer(CertificateIssuer)} + */ + public void updateCertificateIssuerCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.updateIssuer#CertificateIssuer + certificateAsyncClient.getIssuer("issuerName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(issuerResponseValue -> { + CertificateIssuer issuer = issuerResponseValue; + //Update the enabled status of the issuer. + issuer.setEnabled(false); + certificateAsyncClient.updateIssuer(issuer) + .subscribe(issuerResponse -> + System.out.printf("Issuer's enabled status %s %n", + issuerResponse.isEnabled().toString())); + }); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.updateIssuer#CertificateIssuer + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.updateIssuerWithResponse#CertificateIssuer + certificateAsyncClient.getIssuer("issuerName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(issuerResponseValue -> { + CertificateIssuer issuer = issuerResponseValue; + //Update the enabled status of the issuer. + issuer.setEnabled(false); + certificateAsyncClient.updateIssuerWithResponse(issuer) + .subscribe(issuerResponse -> + System.out.printf("Issuer's enabled status %s %n", + issuerResponse.getValue().isEnabled().toString())); + }); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.updateIssuerWithResponse#CertificateIssuer + } + + /** + * Method to insert code snippets for + * {@link CertificateAsyncClient#updateCertificatePolicy(String, CertificatePolicy)} + */ + public void updateCertificatePolicyCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.updateCertificatePolicy#string + certificateAsyncClient.getCertificatePolicy("certificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificatePolicyResponseValue -> { + CertificatePolicy certificatePolicy = certificatePolicyResponseValue; + // Update transparency + certificatePolicy.setCertificateTransparent(true); + certificateAsyncClient.updateCertificatePolicy("certificateName", certificatePolicy) + .subscribe(updatedPolicy -> + System.out.printf("Certificate policy's updated transparency status %s %n", + updatedPolicy.isCertificateTransparent())); + }); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.updateCertificatePolicy#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.updateCertificatePolicyWithResponse#string + certificateAsyncClient.getCertificatePolicy("certificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificatePolicyResponseValue -> { + CertificatePolicy certificatePolicy = certificatePolicyResponseValue; + // Update transparency + certificatePolicy.setCertificateTransparent(true); + certificateAsyncClient.updateCertificatePolicyWithResponse("certificateName", + certificatePolicy) + .subscribe(updatedPolicyResponse -> + System.out.printf("Certificate policy's updated transparency status %s %n", + updatedPolicyResponse.getValue().isCertificateTransparent())); + }); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.updateCertificatePolicyWithResponse#string + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#updateCertificateProperties(CertificateProperties)} + */ + public void updateCertificateWithResponseCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.updateCertificatePropertiesWithResponse#CertificateProperties + certificateAsyncClient.getCertificate("certificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificateResponseValue -> { + KeyVaultCertificate certificate = certificateResponseValue; + //Update the enabled status of the certificate. + certificate.getProperties().setEnabled(false); + certificateAsyncClient.updateCertificatePropertiesWithResponse(certificate.getProperties()) + .subscribe(certificateResponse -> + System.out.printf("Certificate's enabled status %s %n", + certificateResponse.getValue().getProperties().isEnabled().toString())); + }); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.updateCertificatePropertiesWithResponse#CertificateProperties + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#beginDeleteCertificate(String)}. + */ + public void deleteCertificateCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.beginDeleteCertificate#String + certificateAsyncClient.beginDeleteCertificate("certificateName") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Delete Certificate Name: " + pollResponse.getValue().getName()); + System.out.println("Certificate Delete Date: " + pollResponse.getValue().getDeletedOn().toString()); + }); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.beginDeleteCertificate#String + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#deleteIssuer(String)} + */ + public void deleteCertificateIssuerCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.deleteIssuerWithResponse#string + certificateAsyncClient.deleteIssuerWithResponse("issuerName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(deletedIssuerResponse -> + System.out.printf("Deleted issuer with name %s %n", deletedIssuerResponse.getValue().getName())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.deleteIssuerWithResponse#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.deleteIssuer#string + certificateAsyncClient.deleteIssuer("issuerName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(deletedIssuerResponse -> + System.out.printf("Deleted issuer with name %s %n", deletedIssuerResponse.getName())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.deleteIssuer#string + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#getDeletedCertificate(String)} + */ + public void getDeletedCertificateCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.getDeletedCertificate#string + certificateAsyncClient.getDeletedCertificate("certificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(deletedSecretResponse -> + System.out.printf("Deleted Certificate's Recovery Id %s %n", deletedSecretResponse.getRecoveryId())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.getDeletedCertificate#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.getDeletedCertificateWithResponse#string + certificateAsyncClient.getDeletedCertificateWithResponse("certificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(deletedSecretResponse -> + System.out.printf("Deleted Certificate's Recovery Id %s %n", + deletedSecretResponse.getValue().getRecoveryId())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.getDeletedCertificateWithResponse#string + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#purgeDeletedCertificate(String)} + */ + public void purgeDeletedCertificateCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.purgeDeletedCertificate#string + certificateAsyncClient.purgeDeletedCertificate("deletedCertificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .doOnSuccess(response -> System.out.println("Successfully Purged certificate")); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.purgeDeletedCertificate#string + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#purgeDeletedCertificateWithResponse(String)} + */ + public void purgeDeletedCertificateWithResponseCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.purgeDeletedCertificateWithResponse#string + certificateAsyncClient.purgeDeletedCertificateWithResponse("deletedCertificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(purgeResponse -> + System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.purgeDeletedCertificateWithResponse#string + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#beginRecoverDeletedCertificate(String)}. + */ + public void recoverDeletedCertificateCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.certificatevault.certificates.CertificateAsyncClient.beginRecoverDeletedCertificate#String + certificateAsyncClient.beginRecoverDeletedCertificate("deletedCertificateName") + .subscribe(pollResponse -> { + System.out.println("Recovery Status: " + pollResponse.getStatus().toString()); + System.out.println("Recover Certificate Name: " + pollResponse.getValue().getName()); + System.out.println("Recover Certificate Id: " + pollResponse.getValue().getId()); + }); + // END: com.azure.security.certificatevault.certificates.CertificateAsyncClient.beginRecoverDeletedCertificate#String + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#backupCertificate(String)} + */ + public void backupCertificateCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.backupCertificate#string + certificateAsyncClient.backupCertificate("certificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificateBackupResponse -> + System.out.printf("Certificate's Backup Byte array's length %s %n", certificateBackupResponse.length)); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.backupCertificate#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.backupCertificateWithResponse#string + certificateAsyncClient.backupCertificateWithResponse("certificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificateBackupResponse -> + System.out.printf("Certificate's Backup Byte array's length %s %n", + certificateBackupResponse.getValue().length)); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.backupCertificateWithResponse#string + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#restoreCertificateBackup(byte[])} + */ + public void restoreCertificateCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.restoreCertificate#byte + byte[] certificateBackupByteArray = {}; + certificateAsyncClient.restoreCertificateBackup(certificateBackupByteArray) + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificateResponse -> System.out.printf("Restored Certificate with name %s and key id %s %n", + certificateResponse.getProperties().getName(), certificateResponse.getKeyId())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.restoreCertificate#byte + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.restoreCertificateWithResponse#byte + byte[] certificateBackup = {}; + certificateAsyncClient.restoreCertificateBackup(certificateBackup) + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificateResponse -> System.out.printf("Restored Certificate with name %s and key id %s %n", + certificateResponse.getProperties().getName(), certificateResponse.getKeyId())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.restoreCertificateWithResponse#byte + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#listPropertiesOfCertificates()} + */ + public void listCertificatesCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.listCertificates + certificateAsyncClient.listPropertiesOfCertificates() + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificate -> certificateAsyncClient.getCertificateVersion(certificate.getName(), + certificate.getVersion()) + .subscribe(certificateResponse -> System.out.printf("Received certificate with name %s and key id %s", + certificateResponse.getName(), certificateResponse.getKeyId()))); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.listCertificates + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#listPropertiesOfIssuers()} + */ + public void listCertificateIssuersCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.listPropertiesOfIssuers + certificateAsyncClient.listPropertiesOfIssuers() + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(issuerProperties -> certificateAsyncClient.getIssuer(issuerProperties.getName()) + .subscribe(issuerResponse -> System.out.printf("Received issuer with name %s and provider %s", + issuerResponse.getName(), issuerResponse.getProvider()))); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.listPropertiesOfIssuers + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#listDeletedCertificates()} + */ + public void listDeletedCertificatesCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.listDeletedCertificates + certificateAsyncClient.listDeletedCertificates() + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(deletedCertificateResponse -> System.out.printf("Deleted Certificate's Recovery Id %s %n", + deletedCertificateResponse.getRecoveryId())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.listDeletedCertificates + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#listPropertiesOfCertificateVersions(String)} + */ + public void listCertificateVersionsCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.listCertificateVersions + certificateAsyncClient.listPropertiesOfCertificateVersions("certificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificate -> certificateAsyncClient.getCertificateVersion(certificate.getName(), + certificate.getVersion()) + .subscribe(certificateResponse -> System.out.printf("Received certificate with name %s and key id %s", + certificateResponse.getProperties().getName(), certificateResponse.getKeyId()))); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.listCertificateVersions + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#setContacts(List)} + */ + public void contactsOperationsCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.setContacts#contacts + CertificateContact contactToAdd = new CertificateContact().setName("user").setEmail("useremail@example.com"); + certificateAsyncClient.setContacts(Collections.singletonList(contactToAdd)).subscribe(contact -> + System.out.printf("Contact name %s and email %s", contact.getName(), contact.getEmail()) + ); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.setContacts#contacts + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.listContacts + certificateAsyncClient.listContacts().subscribe(contact -> + System.out.printf("Contact name %s and email %s", contact.getName(), contact.getEmail()) + ); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.listContacts + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.deleteContacts + certificateAsyncClient.deleteContacts().subscribe(contact -> + System.out.printf("Deleted Contact name %s and email %s", contact.getName(), contact.getEmail()) + ); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.deleteContacts + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#deleteCertificateOperation(String)} and + * {@link CertificateAsyncClient#deleteCertificateOperationWithResponse(String, com.azure.core.util.Context)} + */ + public void certificateOperationCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.deleteCertificateOperationWithResponse#string + certificateAsyncClient.deleteCertificateOperationWithResponse("certificateName") + .subscribe(certificateOperationResponse -> System.out.printf("Deleted Certificate operation's last" + + " status %s", certificateOperationResponse.getValue().getStatus())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.deleteCertificateOperationWithResponse#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.deleteCertificateOperation#string + certificateAsyncClient.deleteCertificateOperation("certificateName") + .subscribe(certificateOperation -> System.out.printf("Deleted Certificate operation last status %s", + certificateOperation.getStatus())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.deleteCertificateOperation#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.cancelCertificateOperation#string + certificateAsyncClient.cancelCertificateOperation("certificateName") + .subscribe(certificateOperation -> System.out.printf("Certificate operation status %s", + certificateOperation.getStatus())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.cancelCertificateOperation#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.cancelCertificateOperationWithResponse#string + certificateAsyncClient.cancelCertificateOperationWithResponse("certificateName") + .subscribe(certificateOperationResponse -> System.out.printf("Certificate operation status %s", + certificateOperationResponse.getValue().getStatus())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.cancelCertificateOperationWithResponse#string + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#mergeCertificate(MergeCertificateOptions)} + */ + public void mergeCertificateCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.mergeCertificate#config + List x509CertificatesToMerge = new ArrayList<>(); + MergeCertificateOptions config = + new MergeCertificateOptions("certificateName", x509CertificatesToMerge).setEnabled(false); + certificateAsyncClient.mergeCertificate(config) + .subscribe(certificate -> System.out.printf("Received Certificate with name %s and key id %s", + certificate.getProperties().getName(), certificate.getKeyId())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.mergeCertificate#config + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.mergeCertificateWithResponse#config + List x509CertsToMerge = new ArrayList<>(); + MergeCertificateOptions mergeConfig = + new MergeCertificateOptions("certificateName", x509CertsToMerge).setEnabled(false); + certificateAsyncClient.mergeCertificateWithResponse(mergeConfig) + .subscribe(certificateResponse -> System.out.printf("Received Certificate with name %s and key id %s", + certificateResponse.getValue().getProperties().getName(), certificateResponse.getValue().getKeyId())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.mergeCertificateWithResponse#config + } + + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#importCertificate(ImportCertificateOptions)} + */ + public void importCertificate() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.importCertificate#options + byte[] certificateToImport = new byte[100]; + ImportCertificateOptions config = + new ImportCertificateOptions("certificateName", certificateToImport).setEnabled(false); + certificateAsyncClient.importCertificate(config) + .subscribe(certificate -> System.out.printf("Received Certificate with name %s and key id %s", + certificate.getProperties().getName(), certificate.getKeyId())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.importCertificate#options + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.importCertificateWithResponse#options + byte[] certToImport = new byte[100]; + ImportCertificateOptions importCertificateOptions = + new ImportCertificateOptions("certificateName", certToImport).setEnabled(false); + certificateAsyncClient.importCertificateWithResponse(importCertificateOptions) + .subscribe(certificateResponse -> System.out.printf("Received Certificate with name %s and key id %s", + certificateResponse.getValue().getProperties().getName(), certificateResponse.getValue().getKeyId())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.importCertificateWithResponse#options + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample3/v2/CertificateAsyncClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample3/v2/CertificateAsyncClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..aae07eaf33f3 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample3/v2/CertificateAsyncClientJavaDocCodeSnippets.java @@ -0,0 +1,655 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.certificates; + + +import com.azure.core.http.HttpClient; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.policy.HttpLogOptions; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.certificates.models.CertificateContact; +import com.azure.security.keyvault.certificates.models.CertificateIssuer; +import com.azure.security.keyvault.certificates.models.CertificatePolicy; +import com.azure.security.keyvault.certificates.models.CertificateProperties; +import com.azure.security.keyvault.certificates.models.ImportCertificateOptions; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificate; +import com.azure.security.keyvault.certificates.models.MergeCertificateOptions; +import reactor.util.context.Context; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +/** + * This class contains code samples for generating javadocs through doclets for {@link CertificateAsyncClient} + */ +public final class CertificateAsyncClientJavaDocCodeSnippets { + private final String key1 = "key1"; + private final String key2 = "key2"; + private final String value1 = "val1"; + private final String value2 = "val2"; + + /** + * Generates code sample for creating a {@link CertificateAsyncClient} + * @return An instance of {@link CertificateAsyncClient} + */ + public CertificateAsyncClient createAsyncClientWithHttpclient() { + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.instantiation.withHttpClient + CertificateAsyncClient certificateAsyncClient = new CertificateClientBuilder() + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .httpClient(HttpClient.createDefault()) + .buildAsyncClient(); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.instantiation.withHttpClient + return certificateAsyncClient; + } + + /** + * Implementation for async CertificateAsyncClient + * @return sync CertificateAsyncClient + */ + private CertificateAsyncClient getCertificateAsyncClient() { + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.instantiation + CertificateAsyncClient certificateAsyncClient = new CertificateClientBuilder() + .credential(new DefaultAzureCredentialBuilder().build()) + .vaultUrl("") + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) + .buildAsyncClient(); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.instantiation + return certificateAsyncClient; + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#getCertificatePolicy(String)} + */ + public void getCertificatePolicyCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificatePolicy#string + certificateAsyncClient.getCertificatePolicy("certificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(policy -> + System.out.printf("Certificate policy is returned with issuer name %s and subject name %s %n", + policy.getIssuerName(), policy.getSubject())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificatePolicy#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificatePolicyWithResponse#string + certificateAsyncClient.getCertificatePolicyWithResponse("certificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(policyResponse -> + System.out.printf("Certificate policy is returned with issuer name %s and subject name %s %n", + policyResponse.getValue().getIssuerName(), policyResponse.getValue().getSubject())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificatePolicyWithResponse#string + } + + + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#getCertificate(String)} + */ + public void getCertificateWithResponseCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificate#String + certificateAsyncClient.getCertificate("certificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificateResponse -> + System.out.printf("Certificate is returned with name %s and secretId %s %n", + certificateResponse.getProperties().getName(), certificateResponse.getSecretId())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificate#String + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateWithResponse#String + certificateAsyncClient.getCertificateWithResponse("certificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificateResponse -> + System.out.printf("Certificate is returned with name %s and secretId %s %n", + certificateResponse.getValue().getProperties().getName(), + certificateResponse.getValue().getSecretId())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateWithResponse#String + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateVersionWithResponse#string-string + String certificateVersion = "6A385B124DEF4096AF1361A85B16C204"; + certificateAsyncClient.getCertificateVersionWithResponse("certificateName", certificateVersion) + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificateWithVersion -> + System.out.printf("Certificate is returned with name %s and secretId %s %n", + certificateWithVersion.getValue().getProperties().getName(), + certificateWithVersion.getValue().getSecretId())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateVersionWithResponse#string-string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateVersion#String-String + certificateAsyncClient.getCertificateVersion("certificateName", certificateVersion) + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificateWithVersion -> + System.out.printf("Certificate is returned with name %s and secretId %s %n", + certificateWithVersion.getProperties().getName(), certificateWithVersion.getSecretId())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateVersion#String-String + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificate#CertificateProperties + certificateAsyncClient.getCertificate("certificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificate -> certificateAsyncClient.getCertificateVersion(certificate.getName(), + certificate.getProperties().getVersion()) + .subscribe(certificateResponse -> + System.out.printf("Certificate is returned with name %s and secretId %s %n", + certificateResponse.getProperties().getName(), certificateResponse.getSecretId()))); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificate#CertificateProperties + } + + /** + * Method to insert code snippets for + * {@link CertificateAsyncClient#beginCreateCertificate(String, CertificatePolicy, Boolean, Map)} and + * {@link CertificateAsyncClient#beginCreateCertificate(String, CertificatePolicy)}. + */ + public void createCertificateCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.beginCreateCertificate#String-CertificatePolicy-Boolean-Map + CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12"); + Map tags = new HashMap<>(); + tags.put("foo", "bar"); + certificateAsyncClient.beginCreateCertificate("certificateName", policy, true, tags) + .subscribe(pollResponse -> { + System.out.println("---------------------------------------------------------------------------------"); + System.out.println(pollResponse.getStatus()); + System.out.println(pollResponse.getValue().getStatus()); + System.out.println(pollResponse.getValue().getStatusDetails()); + }); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.beginCreateCertificate#String-CertificatePolicy-Boolean-Map + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.beginCreateCertificate#String-CertificatePolicy + CertificatePolicy certPolicy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12"); + certificateAsyncClient.beginCreateCertificate("certificateName", certPolicy) + .subscribe(pollResponse -> { + System.out.println("---------------------------------------------------------------------------------"); + System.out.println(pollResponse.getStatus()); + System.out.println(pollResponse.getValue().getStatus()); + System.out.println(pollResponse.getValue().getStatusDetails()); + }); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.beginCreateCertificate#String-CertificatePolicy + } + + /** + * Method to insert code snippets for + * {@link CertificateAsyncClient#getCertificateOperation(String)}. + */ + public void getCertificateOperation() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateOperation#String + certificateAsyncClient.getCertificateOperation("certificateName") + .subscribe(pollResponse -> { + System.out.println("---------------------------------------------------------------------------------"); + System.out.println(pollResponse.getStatus()); + System.out.println(pollResponse.getValue().getStatus()); + System.out.println(pollResponse.getValue().getStatusDetails()); + }); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.getCertificateOperation#String + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#createIssuer(CertificateIssuer)} + */ + public void createCertificateIssuerCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.createIssuer#CertificateIssuer + CertificateIssuer issuer = new CertificateIssuer("issuerName", "providerName") + .setAccountId("keyvaultuser") + .setPassword("fakePasswordPlaceholder"); + certificateAsyncClient.createIssuer(issuer) + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(issuerResponse -> { + System.out.printf("Issuer created with %s and %s", issuerResponse.getName(), + issuerResponse.getProvider()); + }); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.createIssuer#CertificateIssuer + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.createIssuerWithResponse#CertificateIssuer + CertificateIssuer newIssuer = new CertificateIssuer("issuerName", "providerName") + .setAccountId("keyvaultuser") + .setPassword("fakePasswordPlaceholder"); + certificateAsyncClient.createIssuerWithResponse(newIssuer) + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(issuerResponse -> { + System.out.printf("Issuer created with %s and %s", issuerResponse.getValue().getName(), + issuerResponse.getValue().getProvider()); + }); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.createIssuerWithResponse#CertificateIssuer + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#getIssuer(String)} + */ + public void getCertificateIssuerCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.getIssuer#string + certificateAsyncClient.getIssuer("issuerName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(issuer -> { + System.out.printf("Issuer returned with %s and %s", issuer.getName(), + issuer.getProvider()); + }); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.getIssuer#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.getIssuerWithResponse#string + certificateAsyncClient.getIssuerWithResponse("issuerName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(issuerResponse -> { + System.out.printf("Issuer returned with %s and %s", issuerResponse.getValue().getName(), + issuerResponse.getValue().getProvider()); + }); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.getIssuerWithResponse#string + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#updateCertificateProperties(CertificateProperties)} + */ + public void updateCertificateCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.updateCertificateProperties#CertificateProperties + certificateAsyncClient.getCertificate("certificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificateResponseValue -> { + KeyVaultCertificate certificate = certificateResponseValue; + //Update enabled status of the certificate + certificate.getProperties().setEnabled(false); + certificateAsyncClient.updateCertificateProperties(certificate.getProperties()) + .subscribe(certificateResponse -> + System.out.printf("Certificate's enabled status %s %n", + certificateResponse.getProperties().isEnabled().toString())); + }); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.updateCertificateProperties#CertificateProperties + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#updateIssuer(CertificateIssuer)} + */ + public void updateCertificateIssuerCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.updateIssuer#CertificateIssuer + certificateAsyncClient.getIssuer("issuerName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(issuerResponseValue -> { + CertificateIssuer issuer = issuerResponseValue; + //Update the enabled status of the issuer. + issuer.setEnabled(false); + certificateAsyncClient.updateIssuer(issuer) + .subscribe(issuerResponse -> + System.out.printf("Issuer's enabled status %s %n", + issuerResponse.isEnabled().toString())); + }); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.updateIssuer#CertificateIssuer + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.updateIssuerWithResponse#CertificateIssuer + certificateAsyncClient.getIssuer("issuerName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(issuerResponseValue -> { + CertificateIssuer issuer = issuerResponseValue; + //Update the enabled status of the issuer. + issuer.setEnabled(false); + certificateAsyncClient.updateIssuerWithResponse(issuer) + .subscribe(issuerResponse -> + System.out.printf("Issuer's enabled status %s %n", + issuerResponse.getValue().isEnabled().toString())); + }); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.updateIssuerWithResponse#CertificateIssuer + } + + /** + * Method to insert code snippets for + * {@link CertificateAsyncClient#updateCertificatePolicy(String, CertificatePolicy)} + */ + public void updateCertificatePolicyCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.updateCertificatePolicy#string + certificateAsyncClient.getCertificatePolicy("certificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificatePolicyResponseValue -> { + CertificatePolicy certificatePolicy = certificatePolicyResponseValue; + // Update transparency + certificatePolicy.setCertificateTransparent(true); + certificateAsyncClient.updateCertificatePolicy("certificateName", certificatePolicy) + .subscribe(updatedPolicy -> + System.out.printf("Certificate policy's updated transparency status %s %n", + updatedPolicy.isCertificateTransparent())); + }); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.updateCertificatePolicy#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.updateCertificatePolicyWithResponse#string + certificateAsyncClient.getCertificatePolicy("certificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificatePolicyResponseValue -> { + CertificatePolicy certificatePolicy = certificatePolicyResponseValue; + // Update transparency + certificatePolicy.setCertificateTransparent(true); + certificateAsyncClient.updateCertificatePolicyWithResponse("certificateName", + certificatePolicy) + .subscribe(updatedPolicyResponse -> + System.out.printf("Certificate policy's updated transparency status %s %n", + updatedPolicyResponse.getValue().isCertificateTransparent())); + }); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.updateCertificatePolicyWithResponse#string + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#updateCertificateProperties(CertificateProperties)} + */ + public void updateCertificateWithResponseCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.updateCertificatePropertiesWithResponse#CertificateProperties + certificateAsyncClient.getCertificate("certificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificateResponseValue -> { + KeyVaultCertificate certificate = certificateResponseValue; + //Update the enabled status of the certificate. + certificate.getProperties().setEnabled(false); + certificateAsyncClient.updateCertificatePropertiesWithResponse(certificate.getProperties()) + .subscribe(certificateResponse -> + System.out.printf("Certificate's enabled status %s %n", + certificateResponse.getValue().getProperties().isEnabled().toString())); + }); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.updateCertificatePropertiesWithResponse#CertificateProperties + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#beginDeleteCertificate(String)}. + */ + public void deleteCertificateCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.beginDeleteCertificate#String + certificateAsyncClient.beginDeleteCertificate("certificateName") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Delete Certificate Name: " + pollResponse.getValue().getName()); + System.out.println("Certificate Delete Date: " + pollResponse.getValue().getDeletedOn().toString()); + }); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.beginDeleteCertificate#String + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#deleteIssuer(String)} + */ + public void deleteCertificateIssuerCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.deleteIssuerWithResponse#string + certificateAsyncClient.deleteIssuerWithResponse("issuerName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(deletedIssuerResponse -> + System.out.printf("Deleted issuer with name %s %n", deletedIssuerResponse.getValue().getName())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.deleteIssuerWithResponse#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.deleteIssuer#string + certificateAsyncClient.deleteIssuer("issuerName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(deletedIssuerResponse -> + System.out.printf("Deleted issuer with name %s %n", deletedIssuerResponse.getName())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.deleteIssuer#string + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#getDeletedCertificate(String)} + */ + public void getDeletedCertificateCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.getDeletedCertificate#string + certificateAsyncClient.getDeletedCertificate("certificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(deletedSecretResponse -> + System.out.printf("Deleted Certificate's Recovery Id %s %n", deletedSecretResponse.getRecoveryId())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.getDeletedCertificate#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.getDeletedCertificateWithResponse#string + certificateAsyncClient.getDeletedCertificateWithResponse("certificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(deletedSecretResponse -> + System.out.printf("Deleted Certificate's Recovery Id %s %n", + deletedSecretResponse.getValue().getRecoveryId())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.getDeletedCertificateWithResponse#string + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#purgeDeletedCertificate(String)} + */ + public void purgeDeletedCertificateCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.purgeDeletedCertificate#string + certificateAsyncClient.purgeDeletedCertificate("deletedCertificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .doOnSuccess(response -> System.out.println("Successfully Purged certificate")); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.purgeDeletedCertificate#string + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#purgeDeletedCertificateWithResponse(String)} + */ + public void purgeDeletedCertificateWithResponseCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.purgeDeletedCertificateWithResponse#string + certificateAsyncClient.purgeDeletedCertificateWithResponse("deletedCertificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(purgeResponse -> + System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.purgeDeletedCertificateWithResponse#string + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#beginRecoverDeletedCertificate(String)}. + */ + public void recoverDeletedCertificateCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.certificatevault.certificates.CertificateAsyncClient.beginRecoverDeletedCertificate#String + certificateAsyncClient.beginRecoverDeletedCertificate("deletedCertificateName") + .subscribe(pollResponse -> { + System.out.println("Recovery Status: " + pollResponse.getStatus().toString()); + System.out.println("Recover Certificate Name: " + pollResponse.getValue().getName()); + System.out.println("Recover Certificate Id: " + pollResponse.getValue().getId()); + }); + // END: com.azure.security.certificatevault.certificates.CertificateAsyncClient.beginRecoverDeletedCertificate#String + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#backupCertificate(String)} + */ + public void backupCertificateCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.backupCertificate#string + certificateAsyncClient.backupCertificate("certificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificateBackupResponse -> + System.out.printf("Certificate's Backup Byte array's length %s %n", certificateBackupResponse.length)); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.backupCertificate#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.backupCertificateWithResponse#string + certificateAsyncClient.backupCertificateWithResponse("certificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificateBackupResponse -> + System.out.printf("Certificate's Backup Byte array's length %s %n", + certificateBackupResponse.getValue().length)); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.backupCertificateWithResponse#string + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#restoreCertificateBackup(byte[])} + */ + public void restoreCertificateCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.restoreCertificate#byte + byte[] certificateBackupByteArray = {}; + certificateAsyncClient.restoreCertificateBackup(certificateBackupByteArray) + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificateResponse -> System.out.printf("Restored Certificate with name %s and key id %s %n", + certificateResponse.getProperties().getName(), certificateResponse.getKeyId())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.restoreCertificate#byte + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.restoreCertificateWithResponse#byte + byte[] certificateBackup = {}; + certificateAsyncClient.restoreCertificateBackup(certificateBackup) + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificateResponse -> System.out.printf("Restored Certificate with name %s and key id %s %n", + certificateResponse.getProperties().getName(), certificateResponse.getKeyId())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.restoreCertificateWithResponse#byte + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#listPropertiesOfCertificates()} + */ + public void listCertificatesCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.listCertificates + certificateAsyncClient.listPropertiesOfCertificates() + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificate -> certificateAsyncClient.getCertificateVersion(certificate.getName(), + certificate.getVersion()) + .subscribe(certificateResponse -> System.out.printf("Received certificate with name %s and key id %s", + certificateResponse.getName(), certificateResponse.getKeyId()))); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.listCertificates + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#listPropertiesOfIssuers()} + */ + public void listCertificateIssuersCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.listPropertiesOfIssuers + certificateAsyncClient.listPropertiesOfIssuers() + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(issuerProperties -> certificateAsyncClient.getIssuer(issuerProperties.getName()) + .subscribe(issuerResponse -> System.out.printf("Received issuer with name %s and provider %s", + issuerResponse.getName(), issuerResponse.getProvider()))); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.listPropertiesOfIssuers + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#listDeletedCertificates()} + */ + public void listDeletedCertificatesCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.listDeletedCertificates + certificateAsyncClient.listDeletedCertificates() + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(deletedCertificateResponse -> System.out.printf("Deleted Certificate's Recovery Id %s %n", + deletedCertificateResponse.getRecoveryId())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.listDeletedCertificates + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#listPropertiesOfCertificateVersions(String)} + */ + public void listCertificateVersionsCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.listCertificateVersions + certificateAsyncClient.listPropertiesOfCertificateVersions("certificateName") + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(certificate -> certificateAsyncClient.getCertificateVersion(certificate.getName(), + certificate.getVersion()) + .subscribe(certificateResponse -> System.out.printf("Received certificate with name %s and key id %s", + certificateResponse.getProperties().getName(), certificateResponse.getKeyId()))); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.listCertificateVersions + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#setContacts(List)} + */ + public void contactsOperationsCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.setContacts#contacts + CertificateContact contactToAdd = new CertificateContact().setName("user").setEmail("useremail@example.com"); + certificateAsyncClient.setContacts(Collections.singletonList(contactToAdd)).subscribe(contact -> + System.out.printf("Contact name %s and email %s", contact.getName(), contact.getEmail()) + ); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.setContacts#contacts + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.listContacts + certificateAsyncClient.listContacts().subscribe(contact -> + System.out.printf("Contact name %s and email %s", contact.getName(), contact.getEmail()) + ); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.listContacts + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.deleteContacts + certificateAsyncClient.deleteContacts().subscribe(contact -> + System.out.printf("Deleted Contact name %s and email %s", contact.getName(), contact.getEmail()) + ); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.deleteContacts + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#deleteCertificateOperation(String)} and + * {@link CertificateAsyncClient#deleteCertificateOperationWithResponse(String, com.azure.core.util.Context)} + */ + public void certificateOperationCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.deleteCertificateOperationWithResponse#string + certificateAsyncClient.deleteCertificateOperationWithResponse("certificateName") + .subscribe(certificateOperationResponse -> System.out.printf("Deleted Certificate operation's last" + + " status %s", certificateOperationResponse.getValue().getStatus())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.deleteCertificateOperationWithResponse#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.deleteCertificateOperation#string + certificateAsyncClient.deleteCertificateOperation("certificateName") + .subscribe(certificateOperation -> System.out.printf("Deleted Certificate operation last status %s", + certificateOperation.getStatus())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.deleteCertificateOperation#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.cancelCertificateOperation#string + certificateAsyncClient.cancelCertificateOperation("certificateName") + .subscribe(certificateOperation -> System.out.printf("Certificate operation status %s", + certificateOperation.getStatus())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.cancelCertificateOperation#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.cancelCertificateOperationWithResponse#string + certificateAsyncClient.cancelCertificateOperationWithResponse("certificateName") + .subscribe(certificateOperationResponse -> System.out.printf("Certificate operation status %s", + certificateOperationResponse.getValue().getStatus())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.cancelCertificateOperationWithResponse#string + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#mergeCertificate(MergeCertificateOptions)} + */ + public void mergeCertificateCodeSnippets() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.mergeCertificate#config + List x509CertificatesToMerge = new ArrayList<>(); + MergeCertificateOptions config = + new MergeCertificateOptions("certificateName", x509CertificatesToMerge).setEnabled(false); + certificateAsyncClient.mergeCertificate(config) + .subscribe(certificate -> System.out.printf("Received Certificate with name %s and key id %s", + certificate.getProperties().getName(), certificate.getKeyId())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.mergeCertificate#config + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.mergeCertificateWithResponse#config + List x509CertsToMerge = new ArrayList<>(); + MergeCertificateOptions mergeConfig = + new MergeCertificateOptions("certificateName", x509CertsToMerge).setEnabled(false); + certificateAsyncClient.mergeCertificateWithResponse(mergeConfig) + .subscribe(certificateResponse -> System.out.printf("Received Certificate with name %s and key id %s", + certificateResponse.getValue().getProperties().getName(), certificateResponse.getValue().getKeyId())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.mergeCertificateWithResponse#config + } + + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#importCertificate(ImportCertificateOptions)} + */ + public void importCertificate() { + CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.importCertificate#options + byte[] certificateToImport = new byte[100]; + ImportCertificateOptions config = + new ImportCertificateOptions("certificateName", certificateToImport).setEnabled(false); + certificateAsyncClient.importCertificate(config) + .subscribe(certificate -> System.out.printf("Received Certificate with name %s and key id %s", + certificate.getProperties().getName(), certificate.getKeyId())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.importCertificate#options + + // BEGIN: com.azure.security.keyvault.certificates.CertificateAsyncClient.importCertificateWithResponse#options + byte[] certToImport = new byte[100]; + ImportCertificateOptions importCertificateOptions = + new ImportCertificateOptions("certificateName", certToImport).setEnabled(false); + certificateAsyncClient.importCertificateWithResponse(importCertificateOptions) + .subscribe(certificateResponse -> System.out.printf("Received Certificate with name %s and key id %s", + certificateResponse.getValue().getProperties().getName(), certificateResponse.getValue().getKeyId())); + // END: com.azure.security.keyvault.certificates.CertificateAsyncClient.importCertificateWithResponse#options + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample4/v1/CertificateClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample4/v1/CertificateClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..cd87d24625f9 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample4/v1/CertificateClientJavaDocCodeSnippets.java @@ -0,0 +1,663 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.certificates; + + +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.policy.HttpLogOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.core.util.polling.LongRunningOperationStatus; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.certificates.models.AdministratorContact; +import com.azure.security.keyvault.certificates.models.CertificateContact; +import com.azure.security.keyvault.certificates.models.CertificateIssuer; +import com.azure.security.keyvault.certificates.models.CertificateOperation; +import com.azure.security.keyvault.certificates.models.CertificatePolicy; +import com.azure.security.keyvault.certificates.models.CertificateProperties; +import com.azure.security.keyvault.certificates.models.DeletedCertificate; +import com.azure.security.keyvault.certificates.models.ImportCertificateOptions; +import com.azure.security.keyvault.certificates.models.IssuerProperties; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificate; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificateWithPolicy; +import com.azure.security.keyvault.certificates.models.MergeCertificateOptions; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * This class contains code samples for generating javadocs through doclets for {@link CertificateClient} + */ +public final class CertificateClientJavaDocCodeSnippets { + private final String key1 = "key1"; + private final String key2 = "key2"; + private final String value1 = "val1"; + private final String value2 = "val2"; + + /** + * Implementation for.CertificateClient + * + * @return sync CertificateClient + */ + private CertificateClient getCertificateClient() { + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.instantiation + CertificateClient certificateClient = new CertificateClientBuilder() + .credential(new DefaultAzureCredentialBuilder().build()) + .vaultUrl("") + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) + .buildClient(); + // END: com.azure.security.keyvault.certificates.CertificateClient.instantiation + return certificateClient; + } + + + /** + * Method to insert code snippets for {@link CertificateClient#getCertificatePolicy(String)} + */ + public void getCertificatePolicyCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.getCertificatePolicy#string + CertificatePolicy policy = certificateClient.getCertificatePolicy("certificateName"); + System.out.printf("Received policy with subject name %s%n", policy.getSubject()); + // END: com.azure.security.keyvault.certificates.CertificateClient.getCertificatePolicy#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.getCertificatePolicyWithResponse#string + Response returnedPolicyWithResponse = certificateClient.getCertificatePolicyWithResponse( + "certificateName", new Context(key1, value1)); + System.out.printf("Received policy with subject name %s%n", + returnedPolicyWithResponse.getValue().getSubject()); + // END: com.azure.security.keyvault.certificates.CertificateClient.getCertificatePolicyWithResponse#string + } + + + /** + * Method to insert code snippets for {@link CertificateClient#getCertificate(String)} + */ + public void getCertificateWithResponseCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.getCertificate#String + KeyVaultCertificateWithPolicy certificate = certificateClient.getCertificate("certificateName"); + System.out.printf("Received certificate with name %s and version %s and secret id %s%n", + certificate.getProperties().getName(), + certificate.getProperties().getVersion(), certificate.getSecretId()); + // END: com.azure.security.keyvault.certificates.CertificateClient.getCertificate#String + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.getCertificateWithResponse#String-Context + Response certificateWithResponse = certificateClient + .getCertificateWithResponse("certificateName", new Context(key1, value1)); + System.out.printf("Received certificate with name %s and version %s and secret id %s%n", + certificateWithResponse.getValue().getProperties().getName(), + certificateWithResponse.getValue().getProperties().getVersion(), certificate.getSecretId()); + // END: com.azure.security.keyvault.certificates.CertificateClient.getCertificateWithResponse#String-Context + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.getCertificateVersionWithResponse#String-String-Context + Response returnedCertificateWithResponse = certificateClient + .getCertificateVersionWithResponse("certificateName", "certificateVersion", + new Context(key1, value1)); + System.out.printf("Received certificate with name %s and version %s and secret id %s%n", + returnedCertificateWithResponse.getValue().getProperties().getName(), + returnedCertificateWithResponse.getValue().getProperties().getVersion(), + returnedCertificateWithResponse.getValue().getSecretId()); + // END: com.azure.security.keyvault.certificates.CertificateClient.getCertificateVersionWithResponse#String-String-Context + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.getCertificateVersion#String-String + KeyVaultCertificate returnedCertificate = certificateClient.getCertificateVersion("certificateName", + "certificateVersion"); + System.out.printf("Received certificate with name %s and version %s and secret id %s%n", + returnedCertificate.getProperties().getName(), returnedCertificate.getProperties().getVersion(), + returnedCertificate.getSecretId()); + // END: com.azure.security.keyvault.certificates.CertificateClient.getCertificateVersion#String-String + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.getCertificate#CertificateProperties + for (CertificateProperties certificateProperties : certificateClient.listPropertiesOfCertificates()) { + KeyVaultCertificate certificateWithAllProperties = certificateClient + .getCertificateVersion(certificateProperties.getName(), certificateProperties.getVersion()); + System.out.printf("Received certificate with name %s and secret id %s%n", + certificateWithAllProperties.getProperties().getName(), certificateWithAllProperties.getSecretId()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.getCertificate#CertificateProperties + } + + /** + * Method to insert code snippets for {@link CertificateClient#beginCreateCertificate(String, CertificatePolicy, + * Boolean, Map)} and {@link CertificateClient#beginCreateCertificate(String, CertificatePolicy)}. + */ + public void createCertificateCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.beginCreateCertificate#String-CertificatePolicy-Boolean-Map + CertificatePolicy certificatePolicyPkcsSelf = new CertificatePolicy("Self", + "CN=SelfSignedJavaPkcs12"); + SyncPoller certificateSyncPoller = certificateClient + .beginCreateCertificate("certificateName", certificatePolicyPkcsSelf, true, new HashMap<>()); + certificateSyncPoller.waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); + KeyVaultCertificate createdCertificate = certificateSyncPoller.getFinalResult(); + System.out.printf("Certificate created with name %s%n", createdCertificate.getName()); + // END: com.azure.security.keyvault.certificates.CertificateClient.beginCreateCertificate#String-CertificatePolicy-Boolean-Map + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.beginCreateCertificate#String-CertificatePolicy + CertificatePolicy certPolicy = new CertificatePolicy("Self", + "CN=SelfSignedJavaPkcs12"); + SyncPoller certPoller = certificateClient + .beginCreateCertificate("certificateName", certPolicy); + certPoller.waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); + KeyVaultCertificate cert = certPoller.getFinalResult(); + System.out.printf("Certificate created with name %s%n", cert.getName()); + // END: com.azure.security.keyvault.certificates.CertificateClient.beginCreateCertificate#String-CertificatePolicy + } + + /** + * Method to insert code snippets for {@link CertificateClient#getCertificateOperation(String)}. + */ + public void getCertificateOperation() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.getCertificateOperation#String + SyncPoller getCertPoller = certificateClient + .getCertificateOperation("certificateName"); + getCertPoller.waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); + KeyVaultCertificate cert = getCertPoller.getFinalResult(); + System.out.printf("Certificate created with name %s%n", cert.getName()); + // END: com.azure.security.keyvault.certificates.CertificateClient.getCertificateOperation#String + } + + + /** + * Method to insert code snippets for {@link CertificateClient#createIssuer(CertificateIssuer)} + */ + public void createCertificateIssuerCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.createIssuer#CertificateIssuer + CertificateIssuer issuerToCreate = new CertificateIssuer("myissuer", "myProvider") + .setAccountId("testAccount") + .setAdministratorContacts(Collections.singletonList(new AdministratorContact().setFirstName("test") + .setLastName("name").setEmail("test@example.com"))); + CertificateIssuer returnedIssuer = certificateClient.createIssuer(issuerToCreate); + System.out.printf("Created Issuer with name %s provider %s%n", returnedIssuer.getName(), + returnedIssuer.getProvider()); + // END: com.azure.security.keyvault.certificates.CertificateClient.createIssuer#CertificateIssuer + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.createIssuerWithResponse#CertificateIssuer-Context + CertificateIssuer issuer = new CertificateIssuer("issuerName", "myProvider") + .setAccountId("testAccount") + .setAdministratorContacts(Collections.singletonList(new AdministratorContact().setFirstName("test") + .setLastName("name").setEmail("test@example.com"))); + Response issuerResponse = certificateClient.createIssuerWithResponse(issuer, + new Context(key1, value1)); + System.out.printf("Created Issuer with name %s provider %s%n", issuerResponse.getValue().getName(), + issuerResponse.getValue().getProvider()); + // END: com.azure.security.keyvault.certificates.CertificateClient.createIssuerWithResponse#CertificateIssuer-Context + } + + /** + * Method to insert code snippets for {@link CertificateClient#getIssuer(String)} + */ + public void getCertificateIssuerCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.getIssuer#string + CertificateIssuer returnedIssuer = certificateClient.getIssuer("issuerName"); + System.out.printf("Retrieved issuer with name %s and provider %s%n", returnedIssuer.getName(), + returnedIssuer.getProvider()); + // END: com.azure.security.keyvault.certificates.CertificateClient.getIssuer#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.getIssuerWithResponse#string-context + Response issuerResponse = certificateClient.getIssuerWithResponse("issuerName", + new Context(key1, value1)); + System.out.printf("Retrieved issuer with name %s and provider %s%n", issuerResponse.getValue().getName(), + issuerResponse.getValue().getProvider()); + // END: com.azure.security.keyvault.certificates.CertificateClient.getIssuerWithResponse#string-context + } + + /** + * Method to insert code snippets for {@link CertificateClient#updateCertificateProperties(CertificateProperties)} + */ + public void updateCertificateCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.updateCertificateProperties#CertificateProperties + KeyVaultCertificate certificate = certificateClient.getCertificate("certificateName"); + // Update certificate enabled status + certificate.getProperties().setEnabled(false); + KeyVaultCertificate updatedCertificate = certificateClient.updateCertificateProperties(certificate.getProperties()); + System.out.printf("Updated Certificate with name %s and enabled status %s%n", + updatedCertificate.getProperties().getName(), updatedCertificate.getProperties().isEnabled()); + // END: com.azure.security.keyvault.certificates.CertificateClient.updateCertificateProperties#CertificateProperties + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.updateCertificatePropertiesWithResponse#CertificateProperties-Context + KeyVaultCertificate certificateToUpdate = certificateClient.getCertificate("certificateName"); + // Update certificate enabled status + certificateToUpdate.getProperties().setEnabled(false); + Response updatedCertificateResponse = certificateClient. + updateCertificatePropertiesWithResponse(certificateToUpdate.getProperties(), new Context(key1, value1)); + System.out.printf("Updated Certificate with name %s and enabled status %s%n", + updatedCertificateResponse.getValue().getProperties().getName(), + updatedCertificateResponse.getValue().getProperties().isEnabled()); + // END: com.azure.security.keyvault.certificates.CertificateClient.updateCertificatePropertiesWithResponse#CertificateProperties-Context + } + + /** + * Method to insert code snippets for {@link CertificateClient#updateIssuer(CertificateIssuer)} + */ + public void updateCertificateIssuerCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.updateIssuer#CertificateIssuer + CertificateIssuer returnedIssuer = certificateClient.getIssuer("issuerName"); + returnedIssuer.setAccountId("newAccountId"); + CertificateIssuer updatedIssuer = certificateClient.updateIssuer(returnedIssuer); + System.out.printf("Updated issuer with name %s, provider %s and account Id %s%n", updatedIssuer.getName(), + updatedIssuer.getProvider(), updatedIssuer.getAccountId()); + // END: com.azure.security.keyvault.certificates.CertificateClient.updateIssuer#CertificateIssuer + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.updateIssuerWithResponse#CertificateIssuer-Context + CertificateIssuer issuer = certificateClient.getIssuer("issuerName"); + returnedIssuer.setAccountId("newAccountId"); + Response updatedIssuerWithResponse = certificateClient.updateIssuerWithResponse(issuer, + new Context(key1, value1)); + System.out.printf("Updated issuer with name %s, provider %s and account Id %s%n", + updatedIssuerWithResponse.getValue().getName(), + updatedIssuerWithResponse.getValue().getProvider(), + updatedIssuerWithResponse.getValue().getAccountId()); + // END: com.azure.security.keyvault.certificates.CertificateClient.updateIssuerWithResponse#CertificateIssuer-Context + } + + /** + * Method to insert code snippets for {@link CertificateClient#updateCertificatePolicy(String, CertificatePolicy)} + */ + public void updateCertificatePolicyCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.updateCertificatePolicy#string + CertificatePolicy certificatePolicy = certificateClient.getCertificatePolicy("certificateName"); + //Update the certificate policy cert transparency property. + certificatePolicy.setCertificateTransparent(true); + CertificatePolicy updatedCertPolicy = certificateClient.updateCertificatePolicy("certificateName", + certificatePolicy); + System.out.printf("Updated Certificate Policy transparency status %s%n", + updatedCertPolicy.isCertificateTransparent()); + // END: com.azure.security.keyvault.certificates.CertificateClient.updateCertificatePolicy#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.updateCertificatePolicyWithResponse#string + CertificatePolicy certificatePolicyToUpdate = certificateClient.getCertificatePolicy("certificateName"); + //Update the certificate policy cert transparency property. + certificatePolicyToUpdate.setCertificateTransparent(true); + Response updatedCertPolicyWithResponse = certificateClient + .updateCertificatePolicyWithResponse("certificateName", certificatePolicyToUpdate, + new Context(key1, value1)); + System.out.printf("Updated Certificate Policy transparency status %s%n", updatedCertPolicyWithResponse + .getValue().isCertificateTransparent()); + // END: com.azure.security.keyvault.certificates.CertificateClient.updateCertificatePolicyWithResponse#string + } + + /** + * Method to insert code snippets for {@link CertificateClient#beginDeleteCertificate(String)}. + */ + public void deleteCertificateCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.beginDeleteCertificate#String + SyncPoller deleteCertPoller = + certificateClient.beginDeleteCertificate("certificateName"); + // Deleted Certificate is accessible as soon as polling beings. + PollResponse deleteCertPollResponse = deleteCertPoller.poll(); + System.out.printf("Deleted certificate with name %s and recovery id %s%n", + deleteCertPollResponse.getValue().getName(), deleteCertPollResponse.getValue().getRecoveryId()); + deleteCertPoller.waitForCompletion(); + // END: com.azure.security.keyvault.certificates.CertificateClient.beginDeleteCertificate#String + } + + /** + * Method to insert code snippets for {@link CertificateClient#deleteIssuer(String)} + */ + public void deleteCertificateIssuefrCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.deleteIssuerWithResponse#string-context + CertificateIssuer deletedIssuer = certificateClient.deleteIssuer("issuerName"); + System.out.printf("Deleted certificate issuer with name %s and provider id %s%n", deletedIssuer.getName(), + deletedIssuer.getProvider()); + // END: com.azure.security.keyvault.certificates.CertificateClient.deleteIssuerWithResponse#string-context + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.deleteIssuer#string + Response deletedIssuerWithResponse = certificateClient. + deleteIssuerWithResponse("issuerName", new Context(key1, value1)); + System.out.printf("Deleted certificate issuer with name %s and provider id %s%n", + deletedIssuerWithResponse.getValue().getName(), + deletedIssuerWithResponse.getValue().getProvider()); + // END: com.azure.security.keyvault.certificates.CertificateClient.deleteIssuer#string + } + + /** + * Method to insert code snippets for {@link CertificateClient#getDeletedCertificate(String)} + */ + public void getDeletedCertificateCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.getDeletedCertificate#string + DeletedCertificate deletedCertificate = certificateClient.getDeletedCertificate("certificateName"); + System.out.printf("Deleted certificate with name %s and recovery id %s%n", deletedCertificate.getName(), + deletedCertificate.getRecoveryId()); + // END: com.azure.security.keyvault.certificates.CertificateClient.getDeletedCertificate#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.getDeletedCertificateWithResponse#String-Context + Response deletedCertificateWithResponse = certificateClient + .getDeletedCertificateWithResponse("certificateName", new Context(key1, value1)); + System.out.printf("Deleted certificate with name %s and recovery id %s%n", + deletedCertificateWithResponse.getValue().getName(), + deletedCertificateWithResponse.getValue().getRecoveryId()); + // END: com.azure.security.keyvault.certificates.CertificateClient.getDeletedCertificateWithResponse#String-Context + } + + /** + * Method to insert code snippets for {@link CertificateClient#purgeDeletedCertificateWithResponse(String, + * Context)} + */ + public void purgeDeletedCertificateCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.purgeDeletedCertificate#string + certificateClient.purgeDeletedCertificate("certificateName"); + // END: com.azure.security.keyvault.certificates.CertificateClient.purgeDeletedCertificate#string + } + + /** + * Method to insert code snippets for {@link CertificateClient#purgeDeletedCertificateWithResponse(String, + * Context)} + */ + public void purgeDeletedCertificateWithResponseCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.purgeDeletedCertificateWithResponse#string-Context + Response purgeResponse = certificateClient.purgeDeletedCertificateWithResponse("certificateName", + new Context(key1, value1)); + System.out.printf("Purged Deleted certificate with status %d%n", purgeResponse.getStatusCode()); + // END: com.azure.security.keyvault.certificates.CertificateClient.purgeDeletedCertificateWithResponse#string-Context + } + + /** + * Method to insert code snippets for {@link CertificateClient#beginRecoverDeletedCertificate(String)}. + */ + public void recoverDeletedCertificateCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.beginRecoverDeletedCertificate#String + SyncPoller recoverDeletedCertPoller = certificateClient + .beginRecoverDeletedCertificate("deletedCertificateName"); + // Recovered certificate is accessible as soon as polling beings + PollResponse recoverDeletedCertPollResponse = recoverDeletedCertPoller.poll(); + System.out.printf(" Recovered Deleted certificate with name %s and id %s%n", + recoverDeletedCertPollResponse.getValue().getProperties().getName(), + recoverDeletedCertPollResponse.getValue().getProperties().getId()); + recoverDeletedCertPoller.waitForCompletion(); + // END: com.azure.security.keyvault.certificates.CertificateClient.beginRecoverDeletedCertificate#String + } + + /** + * Method to insert code snippets for {@link CertificateClient#backupCertificate(String)} + */ + public void backupCertificateCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.backupCertificate#string + byte[] certificateBackup = certificateClient.backupCertificate("certificateName"); + System.out.printf("Backed up certificate with back up blob length %d%n", certificateBackup.length); + // END: com.azure.security.keyvault.certificates.CertificateClient.backupCertificate#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.backupCertificateWithResponse#String-Context + Response certificateBackupWithResponse = certificateClient + .backupCertificateWithResponse("certificateName", new Context(key1, value1)); + System.out.printf("Backed up certificate with back up blob length %d%n", + certificateBackupWithResponse.getValue().length); + // END: com.azure.security.keyvault.certificates.CertificateClient.backupCertificateWithResponse#String-Context + } + + /** + * Method to insert code snippets for {@link CertificateClient#restoreCertificateBackup(byte[])} + */ + public void restoreCertificateCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.restoreCertificate#byte + byte[] certificateBackupBlob = {}; + KeyVaultCertificate certificate = certificateClient.restoreCertificateBackup(certificateBackupBlob); + System.out.printf(" Restored certificate with name %s and id %s%n", + certificate.getProperties().getName(), certificate.getProperties().getId()); + // END: com.azure.security.keyvault.certificates.CertificateClient.restoreCertificate#byte + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.restoreCertificateWithResponse#byte-Context + byte[] certificateBackupBlobArray = {}; + Response certificateResponse = certificateClient + .restoreCertificateBackupWithResponse(certificateBackupBlobArray, new Context(key1, value1)); + System.out.printf(" Restored certificate with name %s and id %s%n", + certificateResponse.getValue().getProperties().getName(), + certificateResponse.getValue().getProperties().getId()); + // END: com.azure.security.keyvault.certificates.CertificateClient.restoreCertificateWithResponse#byte-Context + } + + /** + * Method to insert code snippets for {@link CertificateClient#listPropertiesOfCertificates()} + */ + public void listCertificatesCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.listCertificates + for (CertificateProperties certificateProperties : certificateClient.listPropertiesOfCertificates()) { + KeyVaultCertificate certificateWithAllProperties = certificateClient + .getCertificateVersion(certificateProperties.getName(), certificateProperties.getVersion()); + System.out.printf("Received certificate with name %s and secret id %s%n", + certificateWithAllProperties.getProperties().getName(), + certificateWithAllProperties.getSecretId()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.listCertificates + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.listCertificates#context + for (CertificateProperties certificateProperties : certificateClient + .listPropertiesOfCertificates(true, new Context(key1, value1))) { + KeyVaultCertificate certificateWithAllProperties = certificateClient + .getCertificateVersion(certificateProperties.getName(), certificateProperties.getVersion()); + System.out.printf("Received certificate with name %s and secret id %s%n", + certificateWithAllProperties.getProperties().getName(), + certificateWithAllProperties.getSecretId()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.listCertificates#context + } + + /** + * Method to insert code snippets for {@link CertificateClient#listPropertiesOfIssuers()} + */ + public void listCertificateIssuersCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.listPropertiesOfIssuers + for (IssuerProperties issuer : certificateClient.listPropertiesOfIssuers()) { + CertificateIssuer retrievedIssuer = certificateClient.getIssuer(issuer.getName()); + System.out.printf("Received issuer with name %s and provider %s%n", retrievedIssuer.getName(), + retrievedIssuer.getProvider()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.listPropertiesOfIssuers + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.listPropertiesOfIssuers#context + for (IssuerProperties issuer : certificateClient.listPropertiesOfIssuers(new Context(key1, value1))) { + CertificateIssuer retrievedIssuer = certificateClient.getIssuer(issuer.getName()); + System.out.printf("Received issuer with name %s and provider %s%n", retrievedIssuer.getName(), + retrievedIssuer.getProvider()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.listPropertiesOfIssuers#context + } + + /** + * Method to insert code snippets for {@link CertificateClient#listDeletedCertificates()} + */ + public void listDeletedCertificatesCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.listDeletedCertificates + for (DeletedCertificate deletedCertificate : certificateClient.listDeletedCertificates()) { + System.out.printf("Deleted certificate's recovery Id %s%n", deletedCertificate.getRecoveryId()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.listDeletedCertificates + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.listDeletedCertificates#context + for (DeletedCertificate deletedCertificate : certificateClient + .listDeletedCertificates(true, new Context(key1, value1))) { + System.out.printf("Deleted certificate's recovery Id %s%n", deletedCertificate.getRecoveryId()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.listDeletedCertificates#context + } + + /** + * Method to insert code snippets for {@link CertificateClient#listPropertiesOfCertificateVersions(String)} + */ + public void listCertificateVersionsCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.listCertificateVersions + for (CertificateProperties certificateProperties : certificateClient + .listPropertiesOfCertificateVersions("certificateName")) { + KeyVaultCertificate certificateWithAllProperties = certificateClient + .getCertificateVersion(certificateProperties.getName(), certificateProperties.getVersion()); + System.out.printf("Received certificate's version with name %s, version %s and secret id %s%n", + certificateWithAllProperties.getProperties().getName(), + certificateWithAllProperties.getProperties().getVersion(), certificateWithAllProperties.getSecretId()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.listCertificateVersions + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.listCertificateVersions#context + for (CertificateProperties certificateProperties : certificateClient + .listPropertiesOfCertificateVersions("certificateName")) { + KeyVaultCertificate certificateWithAllProperties = certificateClient + .getCertificateVersion(certificateProperties.getName(), certificateProperties.getVersion()); + System.out.printf("Received certificate's version with name %s, version %s and secret id %s%n", + certificateWithAllProperties.getProperties().getName(), + certificateWithAllProperties.getProperties().getVersion(), certificateWithAllProperties.getSecretId()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.listCertificateVersions#context + } + + /** + * Method to insert code snippets for {@link CertificateClient#setContacts(List)} + */ + public void contactsOperationsCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.setContacts#contacts + CertificateContact contactToAdd = new CertificateContact().setName("user").setEmail("useremail@example.com"); + for (CertificateContact contact : certificateClient.setContacts(Collections.singletonList(contactToAdd))) { + System.out.printf("Added contact with name %s and email %s to key vault%n", contact.getName(), + contact.getEmail()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.setContacts#contacts + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.setContacts#contacts-context + CertificateContact sampleContact = new CertificateContact().setName("user").setEmail("useremail@example.com"); + for (CertificateContact contact : certificateClient.setContacts(Collections.singletonList(sampleContact), + new Context(key1, value1))) { + System.out.printf("Added contact with name %s and email %s to key vault%n", contact.getName(), + contact.getEmail()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.setContacts#contacts-context + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.listContacts + for (CertificateContact contact : certificateClient.listContacts()) { + System.out.printf("Added contact with name %s and email %s to key vault%n", contact.getName(), + contact.getEmail()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.listContacts + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.listContacts#context + for (CertificateContact contact : certificateClient.listContacts(new Context(key1, value1))) { + System.out.printf("Added contact with name %s and email %s to key vault%n", contact.getName(), + contact.getEmail()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.listContacts#context + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.deleteContacts + for (CertificateContact contact : certificateClient.deleteContacts()) { + System.out.printf("Deleted contact with name %s and email %s from key vault%n", contact.getName(), + contact.getEmail()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.deleteContacts + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.deleteContacts#context + for (CertificateContact contact : certificateClient.deleteContacts(new Context(key1, value1))) { + System.out.printf("Deleted contact with name %s and email %s from key vault%n", contact.getName(), + contact.getEmail()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.deleteContacts#context + } + + /** + * Method to insert code snippets for {@link CertificateClient#deleteCertificateOperation(String)} (String)} and + * {@link CertificateClient#deleteCertificateOperationWithResponse(String, Context)} + */ + public void certificateOperationCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.deleteCertificateOperationWithResponse#string + CertificateOperation deletedCertificateOperation = certificateClient + .deleteCertificateOperation("certificateName"); + System.out.printf("Deleted Certificate Operation's last status %s%n", deletedCertificateOperation.getStatus()); + // END: com.azure.security.keyvault.certificates.CertificateClient.deleteCertificateOperationWithResponse#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.deleteCertificateOperation#string + Response deletedCertificateOperationWithResponse = certificateClient + .deleteCertificateOperationWithResponse("certificateName", new Context(key1, value1)); + System.out.printf("Deleted Certificate Operation's last status %s%n", + deletedCertificateOperationWithResponse.getValue().getStatus()); + // END: com.azure.security.keyvault.certificates.CertificateClient.deleteCertificateOperation#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.cancelCertificateOperation#string + CertificateOperation certificateOperation = certificateClient + .cancelCertificateOperation("certificateName"); + System.out.printf("Certificate Operation status %s%n", certificateOperation.getStatus()); + // END: com.azure.security.keyvault.certificates.CertificateClient.cancelCertificateOperation#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.cancelCertificateOperationWithResponse#string + Response certificateOperationWithResponse = certificateClient + .cancelCertificateOperationWithResponse("certificateName", new Context(key1, value1)); + System.out.printf("Certificate Operation status %s%n", certificateOperationWithResponse.getValue().getStatus()); + // END: com.azure.security.keyvault.certificates.CertificateClient.cancelCertificateOperationWithResponse#string + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#mergeCertificate(MergeCertificateOptions)} + */ + public void mergeCertificateCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.mergeCertificate#config + List x509CertificatesToMerge = new ArrayList<>(); + MergeCertificateOptions config = + new MergeCertificateOptions("certificateName", x509CertificatesToMerge) + .setEnabled(false); + KeyVaultCertificate mergedCertificate = certificateClient.mergeCertificate(config); + System.out.printf("Received Certificate with name %s and key id %s%n", + mergedCertificate.getProperties().getName(), mergedCertificate.getKeyId()); + // END: com.azure.security.keyvault.certificates.CertificateClient.mergeCertificate#config + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.mergeCertificateWithResponse#config + List x509CertsToMerge = new ArrayList<>(); + MergeCertificateOptions mergeConfig = + new MergeCertificateOptions("certificateName", x509CertsToMerge) + .setEnabled(false); + Response mergedCertificateWithResponse = + certificateClient.mergeCertificateWithResponse(mergeConfig, new Context(key2, value2)); + System.out.printf("Received Certificate with name %s and key id %s%n", + mergedCertificateWithResponse.getValue().getProperties().getName(), + mergedCertificateWithResponse.getValue().getKeyId()); + // END: com.azure.security.keyvault.certificates.CertificateClient.mergeCertificateWithResponse#config + } + + /** + * Method to insert code snippets for {@link CertificateClient#importCertificate(ImportCertificateOptions)} + */ + public void importCertificate() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.importCertificate#options + byte[] certificateToImport = new byte[100]; + ImportCertificateOptions config = + new ImportCertificateOptions("certificateName", certificateToImport).setEnabled(false); + KeyVaultCertificate importedCertificate = certificateClient.importCertificate(config); + System.out.printf("Received Certificate with name %s and key id %s%n", + importedCertificate.getProperties().getName(), importedCertificate.getKeyId()); + // END: com.azure.security.keyvault.certificates.CertificateClient.importCertificate#options + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.importCertificateWithResponse#options + byte[] certToImport = new byte[100]; + ImportCertificateOptions importCertificateOptions = + new ImportCertificateOptions("certificateName", certToImport).setEnabled(false); + Response importedCertificateWithResponse = + certificateClient.importCertificateWithResponse(importCertificateOptions, new Context(key2, value2)); + System.out.printf("Received Certificate with name %s and key id %s%n", + importedCertificateWithResponse.getValue().getProperties().getName(), + importedCertificateWithResponse.getValue().getKeyId()); + // END: com.azure.security.keyvault.certificates.CertificateClient.importCertificateWithResponse#options + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample4/v2/CertificateClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample4/v2/CertificateClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..cd87d24625f9 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample4/v2/CertificateClientJavaDocCodeSnippets.java @@ -0,0 +1,663 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.certificates; + + +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.policy.HttpLogOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.core.util.polling.LongRunningOperationStatus; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.certificates.models.AdministratorContact; +import com.azure.security.keyvault.certificates.models.CertificateContact; +import com.azure.security.keyvault.certificates.models.CertificateIssuer; +import com.azure.security.keyvault.certificates.models.CertificateOperation; +import com.azure.security.keyvault.certificates.models.CertificatePolicy; +import com.azure.security.keyvault.certificates.models.CertificateProperties; +import com.azure.security.keyvault.certificates.models.DeletedCertificate; +import com.azure.security.keyvault.certificates.models.ImportCertificateOptions; +import com.azure.security.keyvault.certificates.models.IssuerProperties; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificate; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificateWithPolicy; +import com.azure.security.keyvault.certificates.models.MergeCertificateOptions; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * This class contains code samples for generating javadocs through doclets for {@link CertificateClient} + */ +public final class CertificateClientJavaDocCodeSnippets { + private final String key1 = "key1"; + private final String key2 = "key2"; + private final String value1 = "val1"; + private final String value2 = "val2"; + + /** + * Implementation for.CertificateClient + * + * @return sync CertificateClient + */ + private CertificateClient getCertificateClient() { + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.instantiation + CertificateClient certificateClient = new CertificateClientBuilder() + .credential(new DefaultAzureCredentialBuilder().build()) + .vaultUrl("") + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) + .buildClient(); + // END: com.azure.security.keyvault.certificates.CertificateClient.instantiation + return certificateClient; + } + + + /** + * Method to insert code snippets for {@link CertificateClient#getCertificatePolicy(String)} + */ + public void getCertificatePolicyCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.getCertificatePolicy#string + CertificatePolicy policy = certificateClient.getCertificatePolicy("certificateName"); + System.out.printf("Received policy with subject name %s%n", policy.getSubject()); + // END: com.azure.security.keyvault.certificates.CertificateClient.getCertificatePolicy#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.getCertificatePolicyWithResponse#string + Response returnedPolicyWithResponse = certificateClient.getCertificatePolicyWithResponse( + "certificateName", new Context(key1, value1)); + System.out.printf("Received policy with subject name %s%n", + returnedPolicyWithResponse.getValue().getSubject()); + // END: com.azure.security.keyvault.certificates.CertificateClient.getCertificatePolicyWithResponse#string + } + + + /** + * Method to insert code snippets for {@link CertificateClient#getCertificate(String)} + */ + public void getCertificateWithResponseCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.getCertificate#String + KeyVaultCertificateWithPolicy certificate = certificateClient.getCertificate("certificateName"); + System.out.printf("Received certificate with name %s and version %s and secret id %s%n", + certificate.getProperties().getName(), + certificate.getProperties().getVersion(), certificate.getSecretId()); + // END: com.azure.security.keyvault.certificates.CertificateClient.getCertificate#String + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.getCertificateWithResponse#String-Context + Response certificateWithResponse = certificateClient + .getCertificateWithResponse("certificateName", new Context(key1, value1)); + System.out.printf("Received certificate with name %s and version %s and secret id %s%n", + certificateWithResponse.getValue().getProperties().getName(), + certificateWithResponse.getValue().getProperties().getVersion(), certificate.getSecretId()); + // END: com.azure.security.keyvault.certificates.CertificateClient.getCertificateWithResponse#String-Context + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.getCertificateVersionWithResponse#String-String-Context + Response returnedCertificateWithResponse = certificateClient + .getCertificateVersionWithResponse("certificateName", "certificateVersion", + new Context(key1, value1)); + System.out.printf("Received certificate with name %s and version %s and secret id %s%n", + returnedCertificateWithResponse.getValue().getProperties().getName(), + returnedCertificateWithResponse.getValue().getProperties().getVersion(), + returnedCertificateWithResponse.getValue().getSecretId()); + // END: com.azure.security.keyvault.certificates.CertificateClient.getCertificateVersionWithResponse#String-String-Context + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.getCertificateVersion#String-String + KeyVaultCertificate returnedCertificate = certificateClient.getCertificateVersion("certificateName", + "certificateVersion"); + System.out.printf("Received certificate with name %s and version %s and secret id %s%n", + returnedCertificate.getProperties().getName(), returnedCertificate.getProperties().getVersion(), + returnedCertificate.getSecretId()); + // END: com.azure.security.keyvault.certificates.CertificateClient.getCertificateVersion#String-String + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.getCertificate#CertificateProperties + for (CertificateProperties certificateProperties : certificateClient.listPropertiesOfCertificates()) { + KeyVaultCertificate certificateWithAllProperties = certificateClient + .getCertificateVersion(certificateProperties.getName(), certificateProperties.getVersion()); + System.out.printf("Received certificate with name %s and secret id %s%n", + certificateWithAllProperties.getProperties().getName(), certificateWithAllProperties.getSecretId()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.getCertificate#CertificateProperties + } + + /** + * Method to insert code snippets for {@link CertificateClient#beginCreateCertificate(String, CertificatePolicy, + * Boolean, Map)} and {@link CertificateClient#beginCreateCertificate(String, CertificatePolicy)}. + */ + public void createCertificateCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.beginCreateCertificate#String-CertificatePolicy-Boolean-Map + CertificatePolicy certificatePolicyPkcsSelf = new CertificatePolicy("Self", + "CN=SelfSignedJavaPkcs12"); + SyncPoller certificateSyncPoller = certificateClient + .beginCreateCertificate("certificateName", certificatePolicyPkcsSelf, true, new HashMap<>()); + certificateSyncPoller.waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); + KeyVaultCertificate createdCertificate = certificateSyncPoller.getFinalResult(); + System.out.printf("Certificate created with name %s%n", createdCertificate.getName()); + // END: com.azure.security.keyvault.certificates.CertificateClient.beginCreateCertificate#String-CertificatePolicy-Boolean-Map + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.beginCreateCertificate#String-CertificatePolicy + CertificatePolicy certPolicy = new CertificatePolicy("Self", + "CN=SelfSignedJavaPkcs12"); + SyncPoller certPoller = certificateClient + .beginCreateCertificate("certificateName", certPolicy); + certPoller.waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); + KeyVaultCertificate cert = certPoller.getFinalResult(); + System.out.printf("Certificate created with name %s%n", cert.getName()); + // END: com.azure.security.keyvault.certificates.CertificateClient.beginCreateCertificate#String-CertificatePolicy + } + + /** + * Method to insert code snippets for {@link CertificateClient#getCertificateOperation(String)}. + */ + public void getCertificateOperation() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.getCertificateOperation#String + SyncPoller getCertPoller = certificateClient + .getCertificateOperation("certificateName"); + getCertPoller.waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); + KeyVaultCertificate cert = getCertPoller.getFinalResult(); + System.out.printf("Certificate created with name %s%n", cert.getName()); + // END: com.azure.security.keyvault.certificates.CertificateClient.getCertificateOperation#String + } + + + /** + * Method to insert code snippets for {@link CertificateClient#createIssuer(CertificateIssuer)} + */ + public void createCertificateIssuerCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.createIssuer#CertificateIssuer + CertificateIssuer issuerToCreate = new CertificateIssuer("myissuer", "myProvider") + .setAccountId("testAccount") + .setAdministratorContacts(Collections.singletonList(new AdministratorContact().setFirstName("test") + .setLastName("name").setEmail("test@example.com"))); + CertificateIssuer returnedIssuer = certificateClient.createIssuer(issuerToCreate); + System.out.printf("Created Issuer with name %s provider %s%n", returnedIssuer.getName(), + returnedIssuer.getProvider()); + // END: com.azure.security.keyvault.certificates.CertificateClient.createIssuer#CertificateIssuer + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.createIssuerWithResponse#CertificateIssuer-Context + CertificateIssuer issuer = new CertificateIssuer("issuerName", "myProvider") + .setAccountId("testAccount") + .setAdministratorContacts(Collections.singletonList(new AdministratorContact().setFirstName("test") + .setLastName("name").setEmail("test@example.com"))); + Response issuerResponse = certificateClient.createIssuerWithResponse(issuer, + new Context(key1, value1)); + System.out.printf("Created Issuer with name %s provider %s%n", issuerResponse.getValue().getName(), + issuerResponse.getValue().getProvider()); + // END: com.azure.security.keyvault.certificates.CertificateClient.createIssuerWithResponse#CertificateIssuer-Context + } + + /** + * Method to insert code snippets for {@link CertificateClient#getIssuer(String)} + */ + public void getCertificateIssuerCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.getIssuer#string + CertificateIssuer returnedIssuer = certificateClient.getIssuer("issuerName"); + System.out.printf("Retrieved issuer with name %s and provider %s%n", returnedIssuer.getName(), + returnedIssuer.getProvider()); + // END: com.azure.security.keyvault.certificates.CertificateClient.getIssuer#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.getIssuerWithResponse#string-context + Response issuerResponse = certificateClient.getIssuerWithResponse("issuerName", + new Context(key1, value1)); + System.out.printf("Retrieved issuer with name %s and provider %s%n", issuerResponse.getValue().getName(), + issuerResponse.getValue().getProvider()); + // END: com.azure.security.keyvault.certificates.CertificateClient.getIssuerWithResponse#string-context + } + + /** + * Method to insert code snippets for {@link CertificateClient#updateCertificateProperties(CertificateProperties)} + */ + public void updateCertificateCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.updateCertificateProperties#CertificateProperties + KeyVaultCertificate certificate = certificateClient.getCertificate("certificateName"); + // Update certificate enabled status + certificate.getProperties().setEnabled(false); + KeyVaultCertificate updatedCertificate = certificateClient.updateCertificateProperties(certificate.getProperties()); + System.out.printf("Updated Certificate with name %s and enabled status %s%n", + updatedCertificate.getProperties().getName(), updatedCertificate.getProperties().isEnabled()); + // END: com.azure.security.keyvault.certificates.CertificateClient.updateCertificateProperties#CertificateProperties + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.updateCertificatePropertiesWithResponse#CertificateProperties-Context + KeyVaultCertificate certificateToUpdate = certificateClient.getCertificate("certificateName"); + // Update certificate enabled status + certificateToUpdate.getProperties().setEnabled(false); + Response updatedCertificateResponse = certificateClient. + updateCertificatePropertiesWithResponse(certificateToUpdate.getProperties(), new Context(key1, value1)); + System.out.printf("Updated Certificate with name %s and enabled status %s%n", + updatedCertificateResponse.getValue().getProperties().getName(), + updatedCertificateResponse.getValue().getProperties().isEnabled()); + // END: com.azure.security.keyvault.certificates.CertificateClient.updateCertificatePropertiesWithResponse#CertificateProperties-Context + } + + /** + * Method to insert code snippets for {@link CertificateClient#updateIssuer(CertificateIssuer)} + */ + public void updateCertificateIssuerCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.updateIssuer#CertificateIssuer + CertificateIssuer returnedIssuer = certificateClient.getIssuer("issuerName"); + returnedIssuer.setAccountId("newAccountId"); + CertificateIssuer updatedIssuer = certificateClient.updateIssuer(returnedIssuer); + System.out.printf("Updated issuer with name %s, provider %s and account Id %s%n", updatedIssuer.getName(), + updatedIssuer.getProvider(), updatedIssuer.getAccountId()); + // END: com.azure.security.keyvault.certificates.CertificateClient.updateIssuer#CertificateIssuer + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.updateIssuerWithResponse#CertificateIssuer-Context + CertificateIssuer issuer = certificateClient.getIssuer("issuerName"); + returnedIssuer.setAccountId("newAccountId"); + Response updatedIssuerWithResponse = certificateClient.updateIssuerWithResponse(issuer, + new Context(key1, value1)); + System.out.printf("Updated issuer with name %s, provider %s and account Id %s%n", + updatedIssuerWithResponse.getValue().getName(), + updatedIssuerWithResponse.getValue().getProvider(), + updatedIssuerWithResponse.getValue().getAccountId()); + // END: com.azure.security.keyvault.certificates.CertificateClient.updateIssuerWithResponse#CertificateIssuer-Context + } + + /** + * Method to insert code snippets for {@link CertificateClient#updateCertificatePolicy(String, CertificatePolicy)} + */ + public void updateCertificatePolicyCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.updateCertificatePolicy#string + CertificatePolicy certificatePolicy = certificateClient.getCertificatePolicy("certificateName"); + //Update the certificate policy cert transparency property. + certificatePolicy.setCertificateTransparent(true); + CertificatePolicy updatedCertPolicy = certificateClient.updateCertificatePolicy("certificateName", + certificatePolicy); + System.out.printf("Updated Certificate Policy transparency status %s%n", + updatedCertPolicy.isCertificateTransparent()); + // END: com.azure.security.keyvault.certificates.CertificateClient.updateCertificatePolicy#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.updateCertificatePolicyWithResponse#string + CertificatePolicy certificatePolicyToUpdate = certificateClient.getCertificatePolicy("certificateName"); + //Update the certificate policy cert transparency property. + certificatePolicyToUpdate.setCertificateTransparent(true); + Response updatedCertPolicyWithResponse = certificateClient + .updateCertificatePolicyWithResponse("certificateName", certificatePolicyToUpdate, + new Context(key1, value1)); + System.out.printf("Updated Certificate Policy transparency status %s%n", updatedCertPolicyWithResponse + .getValue().isCertificateTransparent()); + // END: com.azure.security.keyvault.certificates.CertificateClient.updateCertificatePolicyWithResponse#string + } + + /** + * Method to insert code snippets for {@link CertificateClient#beginDeleteCertificate(String)}. + */ + public void deleteCertificateCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.beginDeleteCertificate#String + SyncPoller deleteCertPoller = + certificateClient.beginDeleteCertificate("certificateName"); + // Deleted Certificate is accessible as soon as polling beings. + PollResponse deleteCertPollResponse = deleteCertPoller.poll(); + System.out.printf("Deleted certificate with name %s and recovery id %s%n", + deleteCertPollResponse.getValue().getName(), deleteCertPollResponse.getValue().getRecoveryId()); + deleteCertPoller.waitForCompletion(); + // END: com.azure.security.keyvault.certificates.CertificateClient.beginDeleteCertificate#String + } + + /** + * Method to insert code snippets for {@link CertificateClient#deleteIssuer(String)} + */ + public void deleteCertificateIssuefrCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.deleteIssuerWithResponse#string-context + CertificateIssuer deletedIssuer = certificateClient.deleteIssuer("issuerName"); + System.out.printf("Deleted certificate issuer with name %s and provider id %s%n", deletedIssuer.getName(), + deletedIssuer.getProvider()); + // END: com.azure.security.keyvault.certificates.CertificateClient.deleteIssuerWithResponse#string-context + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.deleteIssuer#string + Response deletedIssuerWithResponse = certificateClient. + deleteIssuerWithResponse("issuerName", new Context(key1, value1)); + System.out.printf("Deleted certificate issuer with name %s and provider id %s%n", + deletedIssuerWithResponse.getValue().getName(), + deletedIssuerWithResponse.getValue().getProvider()); + // END: com.azure.security.keyvault.certificates.CertificateClient.deleteIssuer#string + } + + /** + * Method to insert code snippets for {@link CertificateClient#getDeletedCertificate(String)} + */ + public void getDeletedCertificateCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.getDeletedCertificate#string + DeletedCertificate deletedCertificate = certificateClient.getDeletedCertificate("certificateName"); + System.out.printf("Deleted certificate with name %s and recovery id %s%n", deletedCertificate.getName(), + deletedCertificate.getRecoveryId()); + // END: com.azure.security.keyvault.certificates.CertificateClient.getDeletedCertificate#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.getDeletedCertificateWithResponse#String-Context + Response deletedCertificateWithResponse = certificateClient + .getDeletedCertificateWithResponse("certificateName", new Context(key1, value1)); + System.out.printf("Deleted certificate with name %s and recovery id %s%n", + deletedCertificateWithResponse.getValue().getName(), + deletedCertificateWithResponse.getValue().getRecoveryId()); + // END: com.azure.security.keyvault.certificates.CertificateClient.getDeletedCertificateWithResponse#String-Context + } + + /** + * Method to insert code snippets for {@link CertificateClient#purgeDeletedCertificateWithResponse(String, + * Context)} + */ + public void purgeDeletedCertificateCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.purgeDeletedCertificate#string + certificateClient.purgeDeletedCertificate("certificateName"); + // END: com.azure.security.keyvault.certificates.CertificateClient.purgeDeletedCertificate#string + } + + /** + * Method to insert code snippets for {@link CertificateClient#purgeDeletedCertificateWithResponse(String, + * Context)} + */ + public void purgeDeletedCertificateWithResponseCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.purgeDeletedCertificateWithResponse#string-Context + Response purgeResponse = certificateClient.purgeDeletedCertificateWithResponse("certificateName", + new Context(key1, value1)); + System.out.printf("Purged Deleted certificate with status %d%n", purgeResponse.getStatusCode()); + // END: com.azure.security.keyvault.certificates.CertificateClient.purgeDeletedCertificateWithResponse#string-Context + } + + /** + * Method to insert code snippets for {@link CertificateClient#beginRecoverDeletedCertificate(String)}. + */ + public void recoverDeletedCertificateCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.beginRecoverDeletedCertificate#String + SyncPoller recoverDeletedCertPoller = certificateClient + .beginRecoverDeletedCertificate("deletedCertificateName"); + // Recovered certificate is accessible as soon as polling beings + PollResponse recoverDeletedCertPollResponse = recoverDeletedCertPoller.poll(); + System.out.printf(" Recovered Deleted certificate with name %s and id %s%n", + recoverDeletedCertPollResponse.getValue().getProperties().getName(), + recoverDeletedCertPollResponse.getValue().getProperties().getId()); + recoverDeletedCertPoller.waitForCompletion(); + // END: com.azure.security.keyvault.certificates.CertificateClient.beginRecoverDeletedCertificate#String + } + + /** + * Method to insert code snippets for {@link CertificateClient#backupCertificate(String)} + */ + public void backupCertificateCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.backupCertificate#string + byte[] certificateBackup = certificateClient.backupCertificate("certificateName"); + System.out.printf("Backed up certificate with back up blob length %d%n", certificateBackup.length); + // END: com.azure.security.keyvault.certificates.CertificateClient.backupCertificate#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.backupCertificateWithResponse#String-Context + Response certificateBackupWithResponse = certificateClient + .backupCertificateWithResponse("certificateName", new Context(key1, value1)); + System.out.printf("Backed up certificate with back up blob length %d%n", + certificateBackupWithResponse.getValue().length); + // END: com.azure.security.keyvault.certificates.CertificateClient.backupCertificateWithResponse#String-Context + } + + /** + * Method to insert code snippets for {@link CertificateClient#restoreCertificateBackup(byte[])} + */ + public void restoreCertificateCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.restoreCertificate#byte + byte[] certificateBackupBlob = {}; + KeyVaultCertificate certificate = certificateClient.restoreCertificateBackup(certificateBackupBlob); + System.out.printf(" Restored certificate with name %s and id %s%n", + certificate.getProperties().getName(), certificate.getProperties().getId()); + // END: com.azure.security.keyvault.certificates.CertificateClient.restoreCertificate#byte + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.restoreCertificateWithResponse#byte-Context + byte[] certificateBackupBlobArray = {}; + Response certificateResponse = certificateClient + .restoreCertificateBackupWithResponse(certificateBackupBlobArray, new Context(key1, value1)); + System.out.printf(" Restored certificate with name %s and id %s%n", + certificateResponse.getValue().getProperties().getName(), + certificateResponse.getValue().getProperties().getId()); + // END: com.azure.security.keyvault.certificates.CertificateClient.restoreCertificateWithResponse#byte-Context + } + + /** + * Method to insert code snippets for {@link CertificateClient#listPropertiesOfCertificates()} + */ + public void listCertificatesCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.listCertificates + for (CertificateProperties certificateProperties : certificateClient.listPropertiesOfCertificates()) { + KeyVaultCertificate certificateWithAllProperties = certificateClient + .getCertificateVersion(certificateProperties.getName(), certificateProperties.getVersion()); + System.out.printf("Received certificate with name %s and secret id %s%n", + certificateWithAllProperties.getProperties().getName(), + certificateWithAllProperties.getSecretId()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.listCertificates + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.listCertificates#context + for (CertificateProperties certificateProperties : certificateClient + .listPropertiesOfCertificates(true, new Context(key1, value1))) { + KeyVaultCertificate certificateWithAllProperties = certificateClient + .getCertificateVersion(certificateProperties.getName(), certificateProperties.getVersion()); + System.out.printf("Received certificate with name %s and secret id %s%n", + certificateWithAllProperties.getProperties().getName(), + certificateWithAllProperties.getSecretId()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.listCertificates#context + } + + /** + * Method to insert code snippets for {@link CertificateClient#listPropertiesOfIssuers()} + */ + public void listCertificateIssuersCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.listPropertiesOfIssuers + for (IssuerProperties issuer : certificateClient.listPropertiesOfIssuers()) { + CertificateIssuer retrievedIssuer = certificateClient.getIssuer(issuer.getName()); + System.out.printf("Received issuer with name %s and provider %s%n", retrievedIssuer.getName(), + retrievedIssuer.getProvider()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.listPropertiesOfIssuers + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.listPropertiesOfIssuers#context + for (IssuerProperties issuer : certificateClient.listPropertiesOfIssuers(new Context(key1, value1))) { + CertificateIssuer retrievedIssuer = certificateClient.getIssuer(issuer.getName()); + System.out.printf("Received issuer with name %s and provider %s%n", retrievedIssuer.getName(), + retrievedIssuer.getProvider()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.listPropertiesOfIssuers#context + } + + /** + * Method to insert code snippets for {@link CertificateClient#listDeletedCertificates()} + */ + public void listDeletedCertificatesCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.listDeletedCertificates + for (DeletedCertificate deletedCertificate : certificateClient.listDeletedCertificates()) { + System.out.printf("Deleted certificate's recovery Id %s%n", deletedCertificate.getRecoveryId()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.listDeletedCertificates + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.listDeletedCertificates#context + for (DeletedCertificate deletedCertificate : certificateClient + .listDeletedCertificates(true, new Context(key1, value1))) { + System.out.printf("Deleted certificate's recovery Id %s%n", deletedCertificate.getRecoveryId()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.listDeletedCertificates#context + } + + /** + * Method to insert code snippets for {@link CertificateClient#listPropertiesOfCertificateVersions(String)} + */ + public void listCertificateVersionsCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.listCertificateVersions + for (CertificateProperties certificateProperties : certificateClient + .listPropertiesOfCertificateVersions("certificateName")) { + KeyVaultCertificate certificateWithAllProperties = certificateClient + .getCertificateVersion(certificateProperties.getName(), certificateProperties.getVersion()); + System.out.printf("Received certificate's version with name %s, version %s and secret id %s%n", + certificateWithAllProperties.getProperties().getName(), + certificateWithAllProperties.getProperties().getVersion(), certificateWithAllProperties.getSecretId()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.listCertificateVersions + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.listCertificateVersions#context + for (CertificateProperties certificateProperties : certificateClient + .listPropertiesOfCertificateVersions("certificateName")) { + KeyVaultCertificate certificateWithAllProperties = certificateClient + .getCertificateVersion(certificateProperties.getName(), certificateProperties.getVersion()); + System.out.printf("Received certificate's version with name %s, version %s and secret id %s%n", + certificateWithAllProperties.getProperties().getName(), + certificateWithAllProperties.getProperties().getVersion(), certificateWithAllProperties.getSecretId()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.listCertificateVersions#context + } + + /** + * Method to insert code snippets for {@link CertificateClient#setContacts(List)} + */ + public void contactsOperationsCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.setContacts#contacts + CertificateContact contactToAdd = new CertificateContact().setName("user").setEmail("useremail@example.com"); + for (CertificateContact contact : certificateClient.setContacts(Collections.singletonList(contactToAdd))) { + System.out.printf("Added contact with name %s and email %s to key vault%n", contact.getName(), + contact.getEmail()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.setContacts#contacts + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.setContacts#contacts-context + CertificateContact sampleContact = new CertificateContact().setName("user").setEmail("useremail@example.com"); + for (CertificateContact contact : certificateClient.setContacts(Collections.singletonList(sampleContact), + new Context(key1, value1))) { + System.out.printf("Added contact with name %s and email %s to key vault%n", contact.getName(), + contact.getEmail()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.setContacts#contacts-context + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.listContacts + for (CertificateContact contact : certificateClient.listContacts()) { + System.out.printf("Added contact with name %s and email %s to key vault%n", contact.getName(), + contact.getEmail()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.listContacts + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.listContacts#context + for (CertificateContact contact : certificateClient.listContacts(new Context(key1, value1))) { + System.out.printf("Added contact with name %s and email %s to key vault%n", contact.getName(), + contact.getEmail()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.listContacts#context + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.deleteContacts + for (CertificateContact contact : certificateClient.deleteContacts()) { + System.out.printf("Deleted contact with name %s and email %s from key vault%n", contact.getName(), + contact.getEmail()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.deleteContacts + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.deleteContacts#context + for (CertificateContact contact : certificateClient.deleteContacts(new Context(key1, value1))) { + System.out.printf("Deleted contact with name %s and email %s from key vault%n", contact.getName(), + contact.getEmail()); + } + // END: com.azure.security.keyvault.certificates.CertificateClient.deleteContacts#context + } + + /** + * Method to insert code snippets for {@link CertificateClient#deleteCertificateOperation(String)} (String)} and + * {@link CertificateClient#deleteCertificateOperationWithResponse(String, Context)} + */ + public void certificateOperationCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.deleteCertificateOperationWithResponse#string + CertificateOperation deletedCertificateOperation = certificateClient + .deleteCertificateOperation("certificateName"); + System.out.printf("Deleted Certificate Operation's last status %s%n", deletedCertificateOperation.getStatus()); + // END: com.azure.security.keyvault.certificates.CertificateClient.deleteCertificateOperationWithResponse#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.deleteCertificateOperation#string + Response deletedCertificateOperationWithResponse = certificateClient + .deleteCertificateOperationWithResponse("certificateName", new Context(key1, value1)); + System.out.printf("Deleted Certificate Operation's last status %s%n", + deletedCertificateOperationWithResponse.getValue().getStatus()); + // END: com.azure.security.keyvault.certificates.CertificateClient.deleteCertificateOperation#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.cancelCertificateOperation#string + CertificateOperation certificateOperation = certificateClient + .cancelCertificateOperation("certificateName"); + System.out.printf("Certificate Operation status %s%n", certificateOperation.getStatus()); + // END: com.azure.security.keyvault.certificates.CertificateClient.cancelCertificateOperation#string + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.cancelCertificateOperationWithResponse#string + Response certificateOperationWithResponse = certificateClient + .cancelCertificateOperationWithResponse("certificateName", new Context(key1, value1)); + System.out.printf("Certificate Operation status %s%n", certificateOperationWithResponse.getValue().getStatus()); + // END: com.azure.security.keyvault.certificates.CertificateClient.cancelCertificateOperationWithResponse#string + } + + /** + * Method to insert code snippets for {@link CertificateAsyncClient#mergeCertificate(MergeCertificateOptions)} + */ + public void mergeCertificateCodeSnippets() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.mergeCertificate#config + List x509CertificatesToMerge = new ArrayList<>(); + MergeCertificateOptions config = + new MergeCertificateOptions("certificateName", x509CertificatesToMerge) + .setEnabled(false); + KeyVaultCertificate mergedCertificate = certificateClient.mergeCertificate(config); + System.out.printf("Received Certificate with name %s and key id %s%n", + mergedCertificate.getProperties().getName(), mergedCertificate.getKeyId()); + // END: com.azure.security.keyvault.certificates.CertificateClient.mergeCertificate#config + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.mergeCertificateWithResponse#config + List x509CertsToMerge = new ArrayList<>(); + MergeCertificateOptions mergeConfig = + new MergeCertificateOptions("certificateName", x509CertsToMerge) + .setEnabled(false); + Response mergedCertificateWithResponse = + certificateClient.mergeCertificateWithResponse(mergeConfig, new Context(key2, value2)); + System.out.printf("Received Certificate with name %s and key id %s%n", + mergedCertificateWithResponse.getValue().getProperties().getName(), + mergedCertificateWithResponse.getValue().getKeyId()); + // END: com.azure.security.keyvault.certificates.CertificateClient.mergeCertificateWithResponse#config + } + + /** + * Method to insert code snippets for {@link CertificateClient#importCertificate(ImportCertificateOptions)} + */ + public void importCertificate() { + CertificateClient certificateClient = getCertificateClient(); + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.importCertificate#options + byte[] certificateToImport = new byte[100]; + ImportCertificateOptions config = + new ImportCertificateOptions("certificateName", certificateToImport).setEnabled(false); + KeyVaultCertificate importedCertificate = certificateClient.importCertificate(config); + System.out.printf("Received Certificate with name %s and key id %s%n", + importedCertificate.getProperties().getName(), importedCertificate.getKeyId()); + // END: com.azure.security.keyvault.certificates.CertificateClient.importCertificate#options + + // BEGIN: com.azure.security.keyvault.certificates.CertificateClient.importCertificateWithResponse#options + byte[] certToImport = new byte[100]; + ImportCertificateOptions importCertificateOptions = + new ImportCertificateOptions("certificateName", certToImport).setEnabled(false); + Response importedCertificateWithResponse = + certificateClient.importCertificateWithResponse(importCertificateOptions, new Context(key2, value2)); + System.out.printf("Received Certificate with name %s and key id %s%n", + importedCertificateWithResponse.getValue().getProperties().getName(), + importedCertificateWithResponse.getValue().getKeyId()); + // END: com.azure.security.keyvault.certificates.CertificateClient.importCertificateWithResponse#options + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample5/v1/HelloWorld.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample5/v1/HelloWorld.java new file mode 100644 index 000000000000..878f4de93af4 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample5/v1/HelloWorld.java @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.certificates; + +import com.azure.core.util.polling.LongRunningOperationStatus; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.certificates.models.CertificateKeyCurveName; +import com.azure.security.keyvault.certificates.models.CertificateIssuer; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificateWithPolicy; +import com.azure.security.keyvault.certificates.models.CertificatePolicy; +import com.azure.security.keyvault.certificates.models.DeletedCertificate; +import com.azure.security.keyvault.certificates.models.SubjectAlternativeNames; +import com.azure.security.keyvault.certificates.models.CertificateOperation; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificate; +import com.azure.security.keyvault.certificates.models.CertificateKeyType; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * Sample demonstrates how to set, get, update and delete a certificate. + */ +public class HelloWorld { + /** + * Authenticates with the key vault and shows how to set, get, update and delete a certificate in the key vault. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws InterruptedException, IllegalArgumentException { + /* Instantiate a CertificateClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-certificates/README.md) + for links and instructions. */ + CertificateClient certificateClient = new CertificateClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + // Let's create a self-signed certificate valid for 1 year. If the certificate already exists in the key vault, + // then a new version of the certificate is created. + CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12") + .setSubjectAlternativeNames(new SubjectAlternativeNames().setEmails(Arrays.asList("wow@gmail.com"))) + .setKeyReusable(true) + .setKeyType(CertificateKeyType.EC) + .setKeyCurveName(CertificateKeyCurveName.P_256) + .setValidityInMonths(12); + Map tags = new HashMap<>(); + tags.put("foo", "bar"); + + SyncPoller certificatePoller = + certificateClient.beginCreateCertificate("certificateName", policy, true, tags); + certificatePoller.waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); + + KeyVaultCertificate cert = certificatePoller.getFinalResult(); + + // Let's get the latest version of the certificate from the key vault. + KeyVaultCertificate certificate = certificateClient.getCertificate("certificateName"); + + System.out.printf("Certificate is returned with name %s and secret id %s \n", + certificate.getProperties().getName(), certificate.getSecretId()); + + // After some time, we need to disable the certificate temporarily, so we update the enabled status of the + // certificate. The update method can be used to update the enabled status of the certificate. + certificate.getProperties().setEnabled(false); + + KeyVaultCertificate updatedCertificate = certificateClient.updateCertificateProperties(certificate.getProperties()); + + System.out.printf("Certificate's updated enabled status is %s \n", updatedCertificate.getProperties().isEnabled()); + + // Let's create a certificate issuer. + CertificateIssuer issuer = new CertificateIssuer("myIssuer", "Test"); + CertificateIssuer myIssuer = certificateClient.createIssuer(issuer); + + System.out.printf("Issuer created with name %s and provider %s", myIssuer.getName(), myIssuer.getProvider()); + + // Let's fetch the issuer we just created from the key vault. + myIssuer = certificateClient.getIssuer("myIssuer"); + + System.out.printf("Issuer retrieved with name %s and provider %s", myIssuer.getName(), myIssuer.getProvider()); + + // Let's create a certificate signed by our issuer. + certificateClient.beginCreateCertificate("myCertificate", + new CertificatePolicy("myIssuer", "CN=SelfSignedJavaPkcs12"), true, tags) + .waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); + + // Let's get the latest version of our certificate from the key vault. + KeyVaultCertificate myCert = certificateClient.getCertificate("myCertificate"); + + System.out.printf("Certificate is returned with name %s and secret id %s \n", myCert.getProperties().getName(), + myCert.getSecretId()); + + // The certificates and issuers are no longer needed, need to delete it from the key vault. + SyncPoller deletedCertificatePoller = + certificateClient.beginDeleteCertificate("certificateName"); + // Deleted certificate is accessible as soon as polling beings. + PollResponse pollResponse = deletedCertificatePoller.poll(); + + System.out.printf("Deleted certificate with name %s and recovery id %s", pollResponse.getValue().getName(), + pollResponse.getValue().getRecoveryId()); + + deletedCertificatePoller.waitForCompletion(); + + SyncPoller deletedCertPoller = + certificateClient.beginDeleteCertificate("myCertificate"); + // Deleted certificate is accessible as soon as polling beings. + PollResponse deletePollResponse = deletedCertPoller.poll(); + + System.out.printf("Deleted certificate with name %s and recovery id %s", deletePollResponse.getValue().getName(), + deletePollResponse.getValue().getRecoveryId()); + + deletedCertificatePoller.waitForCompletion(); + + CertificateIssuer deleteCertificateIssuer = certificateClient.deleteIssuer("myIssuer"); + + System.out.printf("Certificate issuer is permanently deleted with name %s and provider is %s \n", + deleteCertificateIssuer.getName(), deleteCertificateIssuer.getProvider()); + + // To ensure the certificate is deleted server-side. + Thread.sleep(30000); + + // If the key vault is soft-delete enabled, then deleted certificates need to be purged for permanent deletion. + certificateClient.purgeDeletedCertificate("certificateName"); + certificateClient.purgeDeletedCertificate("myCertificate"); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample5/v2/HelloWorld.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample5/v2/HelloWorld.java new file mode 100644 index 000000000000..878f4de93af4 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample5/v2/HelloWorld.java @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.certificates; + +import com.azure.core.util.polling.LongRunningOperationStatus; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.certificates.models.CertificateKeyCurveName; +import com.azure.security.keyvault.certificates.models.CertificateIssuer; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificateWithPolicy; +import com.azure.security.keyvault.certificates.models.CertificatePolicy; +import com.azure.security.keyvault.certificates.models.DeletedCertificate; +import com.azure.security.keyvault.certificates.models.SubjectAlternativeNames; +import com.azure.security.keyvault.certificates.models.CertificateOperation; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificate; +import com.azure.security.keyvault.certificates.models.CertificateKeyType; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * Sample demonstrates how to set, get, update and delete a certificate. + */ +public class HelloWorld { + /** + * Authenticates with the key vault and shows how to set, get, update and delete a certificate in the key vault. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws InterruptedException, IllegalArgumentException { + /* Instantiate a CertificateClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-certificates/README.md) + for links and instructions. */ + CertificateClient certificateClient = new CertificateClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + // Let's create a self-signed certificate valid for 1 year. If the certificate already exists in the key vault, + // then a new version of the certificate is created. + CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12") + .setSubjectAlternativeNames(new SubjectAlternativeNames().setEmails(Arrays.asList("wow@gmail.com"))) + .setKeyReusable(true) + .setKeyType(CertificateKeyType.EC) + .setKeyCurveName(CertificateKeyCurveName.P_256) + .setValidityInMonths(12); + Map tags = new HashMap<>(); + tags.put("foo", "bar"); + + SyncPoller certificatePoller = + certificateClient.beginCreateCertificate("certificateName", policy, true, tags); + certificatePoller.waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); + + KeyVaultCertificate cert = certificatePoller.getFinalResult(); + + // Let's get the latest version of the certificate from the key vault. + KeyVaultCertificate certificate = certificateClient.getCertificate("certificateName"); + + System.out.printf("Certificate is returned with name %s and secret id %s \n", + certificate.getProperties().getName(), certificate.getSecretId()); + + // After some time, we need to disable the certificate temporarily, so we update the enabled status of the + // certificate. The update method can be used to update the enabled status of the certificate. + certificate.getProperties().setEnabled(false); + + KeyVaultCertificate updatedCertificate = certificateClient.updateCertificateProperties(certificate.getProperties()); + + System.out.printf("Certificate's updated enabled status is %s \n", updatedCertificate.getProperties().isEnabled()); + + // Let's create a certificate issuer. + CertificateIssuer issuer = new CertificateIssuer("myIssuer", "Test"); + CertificateIssuer myIssuer = certificateClient.createIssuer(issuer); + + System.out.printf("Issuer created with name %s and provider %s", myIssuer.getName(), myIssuer.getProvider()); + + // Let's fetch the issuer we just created from the key vault. + myIssuer = certificateClient.getIssuer("myIssuer"); + + System.out.printf("Issuer retrieved with name %s and provider %s", myIssuer.getName(), myIssuer.getProvider()); + + // Let's create a certificate signed by our issuer. + certificateClient.beginCreateCertificate("myCertificate", + new CertificatePolicy("myIssuer", "CN=SelfSignedJavaPkcs12"), true, tags) + .waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); + + // Let's get the latest version of our certificate from the key vault. + KeyVaultCertificate myCert = certificateClient.getCertificate("myCertificate"); + + System.out.printf("Certificate is returned with name %s and secret id %s \n", myCert.getProperties().getName(), + myCert.getSecretId()); + + // The certificates and issuers are no longer needed, need to delete it from the key vault. + SyncPoller deletedCertificatePoller = + certificateClient.beginDeleteCertificate("certificateName"); + // Deleted certificate is accessible as soon as polling beings. + PollResponse pollResponse = deletedCertificatePoller.poll(); + + System.out.printf("Deleted certificate with name %s and recovery id %s", pollResponse.getValue().getName(), + pollResponse.getValue().getRecoveryId()); + + deletedCertificatePoller.waitForCompletion(); + + SyncPoller deletedCertPoller = + certificateClient.beginDeleteCertificate("myCertificate"); + // Deleted certificate is accessible as soon as polling beings. + PollResponse deletePollResponse = deletedCertPoller.poll(); + + System.out.printf("Deleted certificate with name %s and recovery id %s", deletePollResponse.getValue().getName(), + deletePollResponse.getValue().getRecoveryId()); + + deletedCertificatePoller.waitForCompletion(); + + CertificateIssuer deleteCertificateIssuer = certificateClient.deleteIssuer("myIssuer"); + + System.out.printf("Certificate issuer is permanently deleted with name %s and provider is %s \n", + deleteCertificateIssuer.getName(), deleteCertificateIssuer.getProvider()); + + // To ensure the certificate is deleted server-side. + Thread.sleep(30000); + + // If the key vault is soft-delete enabled, then deleted certificates need to be purged for permanent deletion. + certificateClient.purgeDeletedCertificate("certificateName"); + certificateClient.purgeDeletedCertificate("myCertificate"); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample6/v1/HelloWorldAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample6/v1/HelloWorldAsync.java new file mode 100644 index 000000000000..a1b6c6ca1193 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample6/v1/HelloWorldAsync.java @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.certificates; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.certificates.models.CertificateIssuer; +import com.azure.security.keyvault.certificates.models.CertificatePolicy; +import com.azure.security.keyvault.certificates.models.SubjectAlternativeNames; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificate; +import com.azure.security.keyvault.certificates.models.CertificateKeyCurveName; +import com.azure.security.keyvault.certificates.models.CertificateKeyType; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * Sample demonstrates how to asynchronously set, get, update and delete a key. + */ +public class HelloWorldAsync { + /** + * Authenticates with the key vault and shows how to asynchronously set, get, update and delete a key in the key vault. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws InterruptedException { + /* Instantiate a CertificateAsyncClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-certificates/README.md) + for links and instructions. */ + CertificateAsyncClient certificateAsyncClient = new CertificateClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + // Let's create a self-signed certificate valid for 1 year. If the certificate already exists in the key vault, + // then a new version of the certificate is created. + CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12") + .setSubjectAlternativeNames(new SubjectAlternativeNames().setEmails(Arrays.asList("wow@gmail.com"))) + .setKeyReusable(true) + .setKeyType(CertificateKeyType.EC) + .setKeyCurveName(CertificateKeyCurveName.P_256); + Map tags = new HashMap<>(); + tags.put("foo", "bar"); + + certificateAsyncClient.beginCreateCertificate("certificateName", policy, true, tags) + .subscribe(pollResponse -> { + System.out.println("---------------------------------------------------------------------------------"); + System.out.println(pollResponse.getStatus()); + System.out.println(pollResponse.getValue().getStatus()); + System.out.println(pollResponse.getValue().getStatusDetails()); + }); + + Thread.sleep(22000); + + // Let's get the latest version of the certificate from the key vault. + certificateAsyncClient.getCertificate("certificateName") + .subscribe(certificateResponse -> + System.out.printf("Certificate is returned with name %s and secretId %s %n", + certificateResponse.getProperties().getName(), certificateResponse.getSecretId())); + + // After some time, we need to disable the certificate temporarily, so we update the enabled status of the + // certificate. The update method can be used to update the enabled status of the certificate. + certificateAsyncClient.getCertificate("certificateName") + .subscribe(certificateResponseValue -> { + KeyVaultCertificate certificate = certificateResponseValue; + // Update enabled status of the certificate. + certificate.getProperties().setEnabled(false); + certificateAsyncClient.updateCertificateProperties(certificate.getProperties()) + .subscribe(certificateResponse -> + System.out.printf("Certificate's enabled status %s %n", + certificateResponse.getProperties().isEnabled().toString())); + }); + + Thread.sleep(3000); + + // Let's create a certificate issuer. + certificateAsyncClient.createIssuer(new CertificateIssuer("myIssuer", "Test")) + .subscribe(issuer -> + System.out.printf("Issuer created with %s and %s", issuer.getName(), issuer.getProvider())); + + Thread.sleep(2000); + + // Let's fetch the issuer we just created from the key vault. + certificateAsyncClient.getIssuer("myIssuer") + .subscribe(issuer -> + System.out.printf("Issuer returned with %s and %s", issuer.getName(), issuer.getProvider())); + + Thread.sleep(2000); + + // Let's create a certificate signed by our issuer. + certificateAsyncClient.beginCreateCertificate("myCertificate", + new CertificatePolicy("myIssuer", "CN=IssuerSignedJavaPkcs12"), true, tags) + .subscribe(pollResponse -> { + System.out.println("---------------------------------------------------------------------------------"); + System.out.println(pollResponse.getStatus()); + System.out.println(pollResponse.getValue().getStatus()); + System.out.println(pollResponse.getValue().getStatusDetails()); + }); + + Thread.sleep(22000); + + // Let's get the latest version of our certificate from the key vault. + certificateAsyncClient.getCertificate("myCertificate") + .subscribe(certificateResponse -> + System.out.printf("Certificate is returned with name %s and secretId %s %n", + certificateResponse.getProperties().getName(), certificateResponse.getSecretId())); + + Thread.sleep(2000); + + // The certificates and issuers are no longer needed, need to delete it from the key vault. + certificateAsyncClient.beginDeleteCertificate("certificateName") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Delete Certificate Name: " + pollResponse.getValue().getName()); + System.out.println("Certificate Delete Date: " + pollResponse.getValue().getDeletedOn().toString()); + }); + + certificateAsyncClient.beginDeleteCertificate("myCertificate") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Delete Certificate Name: " + pollResponse.getValue().getName()); + System.out.println("Certificate Delete Date: " + pollResponse.getValue().getDeletedOn().toString()); + }); + + certificateAsyncClient.deleteIssuerWithResponse("myIssuer") + .subscribe(deletedIssuerResponse -> + System.out.printf("Deleted issuer with name %s %n", deletedIssuerResponse.getValue().getName())); + + // To ensure the certificate is deleted server-side. + Thread.sleep(50000); + + // If the key vault is soft-delete enabled, then deleted certificates need to be purged for permanent deletion. + certificateAsyncClient.purgeDeletedCertificateWithResponse("certificateName") + .subscribe(purgeResponse -> + System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode())); + + certificateAsyncClient.purgeDeletedCertificateWithResponse("myCertificate") + .subscribe(purgeResponse -> + System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode())); + + Thread.sleep(4000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample6/v2/HelloWorldAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample6/v2/HelloWorldAsync.java new file mode 100644 index 000000000000..a1b6c6ca1193 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample6/v2/HelloWorldAsync.java @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.certificates; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.certificates.models.CertificateIssuer; +import com.azure.security.keyvault.certificates.models.CertificatePolicy; +import com.azure.security.keyvault.certificates.models.SubjectAlternativeNames; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificate; +import com.azure.security.keyvault.certificates.models.CertificateKeyCurveName; +import com.azure.security.keyvault.certificates.models.CertificateKeyType; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * Sample demonstrates how to asynchronously set, get, update and delete a key. + */ +public class HelloWorldAsync { + /** + * Authenticates with the key vault and shows how to asynchronously set, get, update and delete a key in the key vault. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws InterruptedException { + /* Instantiate a CertificateAsyncClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-certificates/README.md) + for links and instructions. */ + CertificateAsyncClient certificateAsyncClient = new CertificateClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + // Let's create a self-signed certificate valid for 1 year. If the certificate already exists in the key vault, + // then a new version of the certificate is created. + CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12") + .setSubjectAlternativeNames(new SubjectAlternativeNames().setEmails(Arrays.asList("wow@gmail.com"))) + .setKeyReusable(true) + .setKeyType(CertificateKeyType.EC) + .setKeyCurveName(CertificateKeyCurveName.P_256); + Map tags = new HashMap<>(); + tags.put("foo", "bar"); + + certificateAsyncClient.beginCreateCertificate("certificateName", policy, true, tags) + .subscribe(pollResponse -> { + System.out.println("---------------------------------------------------------------------------------"); + System.out.println(pollResponse.getStatus()); + System.out.println(pollResponse.getValue().getStatus()); + System.out.println(pollResponse.getValue().getStatusDetails()); + }); + + Thread.sleep(22000); + + // Let's get the latest version of the certificate from the key vault. + certificateAsyncClient.getCertificate("certificateName") + .subscribe(certificateResponse -> + System.out.printf("Certificate is returned with name %s and secretId %s %n", + certificateResponse.getProperties().getName(), certificateResponse.getSecretId())); + + // After some time, we need to disable the certificate temporarily, so we update the enabled status of the + // certificate. The update method can be used to update the enabled status of the certificate. + certificateAsyncClient.getCertificate("certificateName") + .subscribe(certificateResponseValue -> { + KeyVaultCertificate certificate = certificateResponseValue; + // Update enabled status of the certificate. + certificate.getProperties().setEnabled(false); + certificateAsyncClient.updateCertificateProperties(certificate.getProperties()) + .subscribe(certificateResponse -> + System.out.printf("Certificate's enabled status %s %n", + certificateResponse.getProperties().isEnabled().toString())); + }); + + Thread.sleep(3000); + + // Let's create a certificate issuer. + certificateAsyncClient.createIssuer(new CertificateIssuer("myIssuer", "Test")) + .subscribe(issuer -> + System.out.printf("Issuer created with %s and %s", issuer.getName(), issuer.getProvider())); + + Thread.sleep(2000); + + // Let's fetch the issuer we just created from the key vault. + certificateAsyncClient.getIssuer("myIssuer") + .subscribe(issuer -> + System.out.printf("Issuer returned with %s and %s", issuer.getName(), issuer.getProvider())); + + Thread.sleep(2000); + + // Let's create a certificate signed by our issuer. + certificateAsyncClient.beginCreateCertificate("myCertificate", + new CertificatePolicy("myIssuer", "CN=IssuerSignedJavaPkcs12"), true, tags) + .subscribe(pollResponse -> { + System.out.println("---------------------------------------------------------------------------------"); + System.out.println(pollResponse.getStatus()); + System.out.println(pollResponse.getValue().getStatus()); + System.out.println(pollResponse.getValue().getStatusDetails()); + }); + + Thread.sleep(22000); + + // Let's get the latest version of our certificate from the key vault. + certificateAsyncClient.getCertificate("myCertificate") + .subscribe(certificateResponse -> + System.out.printf("Certificate is returned with name %s and secretId %s %n", + certificateResponse.getProperties().getName(), certificateResponse.getSecretId())); + + Thread.sleep(2000); + + // The certificates and issuers are no longer needed, need to delete it from the key vault. + certificateAsyncClient.beginDeleteCertificate("certificateName") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Delete Certificate Name: " + pollResponse.getValue().getName()); + System.out.println("Certificate Delete Date: " + pollResponse.getValue().getDeletedOn().toString()); + }); + + certificateAsyncClient.beginDeleteCertificate("myCertificate") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Delete Certificate Name: " + pollResponse.getValue().getName()); + System.out.println("Certificate Delete Date: " + pollResponse.getValue().getDeletedOn().toString()); + }); + + certificateAsyncClient.deleteIssuerWithResponse("myIssuer") + .subscribe(deletedIssuerResponse -> + System.out.printf("Deleted issuer with name %s %n", deletedIssuerResponse.getValue().getName())); + + // To ensure the certificate is deleted server-side. + Thread.sleep(50000); + + // If the key vault is soft-delete enabled, then deleted certificates need to be purged for permanent deletion. + certificateAsyncClient.purgeDeletedCertificateWithResponse("certificateName") + .subscribe(purgeResponse -> + System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode())); + + certificateAsyncClient.purgeDeletedCertificateWithResponse("myCertificate") + .subscribe(purgeResponse -> + System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode())); + + Thread.sleep(4000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample7/v1/ListOperations.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample7/v1/ListOperations.java new file mode 100644 index 000000000000..1dae5806f5ae --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample7/v1/ListOperations.java @@ -0,0 +1,115 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.certificates; + +import com.azure.core.util.polling.LongRunningOperationStatus; +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.certificates.models.CertificateContact; +import com.azure.security.keyvault.certificates.models.CertificateIssuer; +import com.azure.security.keyvault.certificates.models.CertificateOperation; +import com.azure.security.keyvault.certificates.models.CertificatePolicy; +import com.azure.security.keyvault.certificates.models.CertificateProperties; +import com.azure.security.keyvault.certificates.models.IssuerProperties; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificate; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificateWithPolicy; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +/** + * Sample demonstrates how to perform list operation on certificates, certificate issuers and certificate contacts in the key vault. + */ +public class ListOperations { + /** + * Authenticates with the key vault and shows how to list certificates, certificate issuers and contacts in the key vault. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + */ + public static void main(String[] args) throws IllegalArgumentException { + /* Instantiate a CertificateClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-certificates/README.md) + for links and instructions. */ + CertificateClient certificateClient = new CertificateClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + // Let's create a self-signed certificate valid for 1 year. If the certificate already exists in the key vault, + // then a new version of the certificate is created. + CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12"); + Map tags = new HashMap<>(); + tags.put("foo", "bar"); + + SyncPoller certificatePoller = + certificateClient.beginCreateCertificate("certName", policy, true, tags); + certificatePoller.waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); + + KeyVaultCertificate cert = certificatePoller.getFinalResult(); + + // Let's create a certificate issuer. + CertificateIssuer issuer = new CertificateIssuer("myIssuer", "Test"); + CertificateIssuer myIssuer = certificateClient.createIssuer(issuer); + + System.out.printf("Issuer created with name %s and provider %s", myIssuer.getName(), myIssuer.getProvider()); + + // Let's create a certificate signed by our issuer. + certificateClient.beginCreateCertificate("myCertificate", + new CertificatePolicy("myIssuer", "CN=SignedJavaPkcs12"), true, tags) + .waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); + + + // Let's list all the certificates in the key vault. + for (CertificateProperties certificate : certificateClient.listPropertiesOfCertificates()) { + KeyVaultCertificate certificateWithAllProperties = + certificateClient.getCertificateVersion(certificate.getName(), certificate.getVersion()); + + System.out.printf("Received certificate with name %s and secret id %s", + certificateWithAllProperties.getProperties().getName(), certificateWithAllProperties.getSecretId()); + } + + // Let's list all certificate versions of the certificate. + for (CertificateProperties certificate : certificateClient.listPropertiesOfCertificateVersions("myCertificate")) { + KeyVaultCertificate certificateWithAllProperties = + certificateClient.getCertificateVersion(certificate.getName(), certificate.getVersion()); + + System.out.printf("Received certificate with name %s and version %s", + certificateWithAllProperties.getProperties().getName(), + certificateWithAllProperties.getProperties().getVersion()); + } + + // Let's list all certificate issuers in the key vault. + for (IssuerProperties certIssuer : certificateClient.listPropertiesOfIssuers()) { + CertificateIssuer retrievedIssuer = certificateClient.getIssuer(certIssuer.getName()); + + System.out.printf("Received issuer with name %s and provider %s", retrievedIssuer.getName(), + retrievedIssuer.getProvider()); + } + + // Let's set certificate contacts on the key vault. + CertificateContact contactToAdd = new CertificateContact().setName("user").setEmail("useremail@example.com"); + for (CertificateContact contact : certificateClient.setContacts(Collections.singletonList(contactToAdd))) { + System.out.printf("Added contact with name %s and email %s to key vault", contact.getName(), + contact.getEmail()); + } + + // Let's list all certificate contacts in the key vault. + for (CertificateContact contact : certificateClient.listContacts()) { + System.out.printf("Retrieved contact with name %s and email %s from the key vault", contact.getName(), + contact.getEmail()); + } + + // Let's delete all certificate contacts in the key vault. + for (CertificateContact contact : certificateClient.deleteContacts()) { + System.out.printf("Deleted contact with name %s and email %s from key vault", contact.getName(), + contact.getEmail()); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample7/v2/ListOperations.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample7/v2/ListOperations.java new file mode 100644 index 000000000000..1dae5806f5ae --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample7/v2/ListOperations.java @@ -0,0 +1,115 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.certificates; + +import com.azure.core.util.polling.LongRunningOperationStatus; +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.certificates.models.CertificateContact; +import com.azure.security.keyvault.certificates.models.CertificateIssuer; +import com.azure.security.keyvault.certificates.models.CertificateOperation; +import com.azure.security.keyvault.certificates.models.CertificatePolicy; +import com.azure.security.keyvault.certificates.models.CertificateProperties; +import com.azure.security.keyvault.certificates.models.IssuerProperties; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificate; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificateWithPolicy; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +/** + * Sample demonstrates how to perform list operation on certificates, certificate issuers and certificate contacts in the key vault. + */ +public class ListOperations { + /** + * Authenticates with the key vault and shows how to list certificates, certificate issuers and contacts in the key vault. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + */ + public static void main(String[] args) throws IllegalArgumentException { + /* Instantiate a CertificateClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-certificates/README.md) + for links and instructions. */ + CertificateClient certificateClient = new CertificateClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + // Let's create a self-signed certificate valid for 1 year. If the certificate already exists in the key vault, + // then a new version of the certificate is created. + CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12"); + Map tags = new HashMap<>(); + tags.put("foo", "bar"); + + SyncPoller certificatePoller = + certificateClient.beginCreateCertificate("certName", policy, true, tags); + certificatePoller.waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); + + KeyVaultCertificate cert = certificatePoller.getFinalResult(); + + // Let's create a certificate issuer. + CertificateIssuer issuer = new CertificateIssuer("myIssuer", "Test"); + CertificateIssuer myIssuer = certificateClient.createIssuer(issuer); + + System.out.printf("Issuer created with name %s and provider %s", myIssuer.getName(), myIssuer.getProvider()); + + // Let's create a certificate signed by our issuer. + certificateClient.beginCreateCertificate("myCertificate", + new CertificatePolicy("myIssuer", "CN=SignedJavaPkcs12"), true, tags) + .waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); + + + // Let's list all the certificates in the key vault. + for (CertificateProperties certificate : certificateClient.listPropertiesOfCertificates()) { + KeyVaultCertificate certificateWithAllProperties = + certificateClient.getCertificateVersion(certificate.getName(), certificate.getVersion()); + + System.out.printf("Received certificate with name %s and secret id %s", + certificateWithAllProperties.getProperties().getName(), certificateWithAllProperties.getSecretId()); + } + + // Let's list all certificate versions of the certificate. + for (CertificateProperties certificate : certificateClient.listPropertiesOfCertificateVersions("myCertificate")) { + KeyVaultCertificate certificateWithAllProperties = + certificateClient.getCertificateVersion(certificate.getName(), certificate.getVersion()); + + System.out.printf("Received certificate with name %s and version %s", + certificateWithAllProperties.getProperties().getName(), + certificateWithAllProperties.getProperties().getVersion()); + } + + // Let's list all certificate issuers in the key vault. + for (IssuerProperties certIssuer : certificateClient.listPropertiesOfIssuers()) { + CertificateIssuer retrievedIssuer = certificateClient.getIssuer(certIssuer.getName()); + + System.out.printf("Received issuer with name %s and provider %s", retrievedIssuer.getName(), + retrievedIssuer.getProvider()); + } + + // Let's set certificate contacts on the key vault. + CertificateContact contactToAdd = new CertificateContact().setName("user").setEmail("useremail@example.com"); + for (CertificateContact contact : certificateClient.setContacts(Collections.singletonList(contactToAdd))) { + System.out.printf("Added contact with name %s and email %s to key vault", contact.getName(), + contact.getEmail()); + } + + // Let's list all certificate contacts in the key vault. + for (CertificateContact contact : certificateClient.listContacts()) { + System.out.printf("Retrieved contact with name %s and email %s from the key vault", contact.getName(), + contact.getEmail()); + } + + // Let's delete all certificate contacts in the key vault. + for (CertificateContact contact : certificateClient.deleteContacts()) { + System.out.printf("Deleted contact with name %s and email %s from key vault", contact.getName(), + contact.getEmail()); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample8/v1/ListOperationsAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample8/v1/ListOperationsAsync.java new file mode 100644 index 000000000000..b7302788f8da --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample8/v1/ListOperationsAsync.java @@ -0,0 +1,131 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.certificates; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.certificates.models.CertificateIssuer; +import com.azure.security.keyvault.certificates.models.CertificatePolicy; +import com.azure.security.keyvault.certificates.models.SubjectAlternativeNames; +import com.azure.security.keyvault.certificates.models.CertificateKeyCurveName; +import com.azure.security.keyvault.certificates.models.CertificateContact; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +/** + * Sample demonstrates how to asynchronously list keys and versions of a given key in the key vault. + */ +public class ListOperationsAsync { + /** + * Authenticates with the key vault and shows how to asynchronously list keys and list versions of a specific key in the key vault. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws InterruptedException { + /* Instantiate a CertificateAsyncClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-certificates/README.md) + for links and instructions. */ + CertificateAsyncClient certificateAsyncClient = new CertificateClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + // Let's create a self-signed certificate valid for 1 year. If the certificate already exists in the key vault, + // then a new version of the certificate is created. + CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12") + .setSubjectAlternativeNames(new SubjectAlternativeNames().setEmails(Arrays.asList("wow@gmail.com"))) + .setKeyReusable(true) + .setKeyCurveName(CertificateKeyCurveName.P_256); + Map tags = new HashMap<>(); + tags.put("foo", "bar"); + + certificateAsyncClient.beginCreateCertificate("myCertificate", policy, true, tags) + .subscribe(pollResponse -> { + System.out.println("---------------------------------------------------------------------------------"); + System.out.println(pollResponse.getStatus()); + System.out.println(pollResponse.getValue().getStatus()); + System.out.println(pollResponse.getValue().getStatusDetails()); + }); + + Thread.sleep(22000); + + // Let's create a certificate issuer. + certificateAsyncClient.createIssuer(new CertificateIssuer("myIssuer", "Test")) + .subscribe(issuer -> + System.out.printf("Issuer created with %s and %s\n", issuer.getName(), issuer.getProvider())); + + Thread.sleep(2000); + + // Let's create a certificate signed by our issuer. + certificateAsyncClient.beginCreateCertificate("myCert", + new CertificatePolicy("myIssuer", "CN=IssuerSignedJavaPkcs12"), true, tags) + .subscribe(pollResponse -> { + System.out.println("---------------------------------------------------------------------------------"); + System.out.println(pollResponse.getStatus()); + System.out.println(pollResponse.getValue().getStatus()); + System.out.println(pollResponse.getValue().getStatusDetails()); + }); + + Thread.sleep(22000); + + // Let's list all the certificates in the key vault. + certificateAsyncClient.listPropertiesOfCertificates() + .subscribe(certificateProperties -> + certificateAsyncClient.getCertificateVersion(certificateProperties.getName(), + certificateProperties.getVersion()) + .subscribe(certificateResponse -> + System.out.printf("Received certificate with name %s and key id %s \n", + certificateResponse.getProperties().getName(), certificateResponse.getKeyId()))); + + Thread.sleep(5000); + + // Let's list all certificate versions of the certificate. + certificateAsyncClient.listPropertiesOfCertificateVersions("myCertificate") + .subscribe(certificateProperties -> + certificateAsyncClient.getCertificateVersion(certificateProperties.getName(), + certificateProperties.getVersion()) + .subscribe(certificateResponse -> + System.out.printf("Received certificate with name %s and key id %s\n", + certificateResponse.getProperties().getName(), certificateResponse.getKeyId()))); + + Thread.sleep(5000); + + // Let's list all certificate issuers in the key vault. + certificateAsyncClient.listPropertiesOfIssuers() + .subscribe(issuerProperties -> + certificateAsyncClient.getIssuer(issuerProperties.getName()) + .subscribe(issuerResponse -> + System.out.printf("Received issuer with name %s and provider %s\n", issuerResponse.getName(), + issuerResponse.getProvider()))); + + Thread.sleep(5000); + + // Let's set certificate contacts on the Key vault. + CertificateContact contactToAdd = new CertificateContact().setName("user").setEmail("useremail@example.com"); + certificateAsyncClient.setContacts(Collections.singletonList(contactToAdd)).subscribe(contact -> + System.out.printf("Contact name %s and email %s\n", contact.getName(), contact.getEmail())); + + Thread.sleep(3000); + + // Let's list all certificate contacts in the key vault. + certificateAsyncClient.listContacts().subscribe(contact -> + System.out.printf("Contact name %s and email %s\n", contact.getName(), contact.getEmail())); + + Thread.sleep(3000); + + // Let's delete all certificate contacts in the key vault. + certificateAsyncClient.listContacts().subscribe(contact -> + System.out.printf("Deleted Contact name %s and email %s\n", contact.getName(), contact.getEmail())); + + Thread.sleep(2000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample8/v2/ListOperationsAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample8/v2/ListOperationsAsync.java new file mode 100644 index 000000000000..b7302788f8da --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample8/v2/ListOperationsAsync.java @@ -0,0 +1,131 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.certificates; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.certificates.models.CertificateIssuer; +import com.azure.security.keyvault.certificates.models.CertificatePolicy; +import com.azure.security.keyvault.certificates.models.SubjectAlternativeNames; +import com.azure.security.keyvault.certificates.models.CertificateKeyCurveName; +import com.azure.security.keyvault.certificates.models.CertificateContact; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +/** + * Sample demonstrates how to asynchronously list keys and versions of a given key in the key vault. + */ +public class ListOperationsAsync { + /** + * Authenticates with the key vault and shows how to asynchronously list keys and list versions of a specific key in the key vault. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws InterruptedException { + /* Instantiate a CertificateAsyncClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-certificates/README.md) + for links and instructions. */ + CertificateAsyncClient certificateAsyncClient = new CertificateClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + // Let's create a self-signed certificate valid for 1 year. If the certificate already exists in the key vault, + // then a new version of the certificate is created. + CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12") + .setSubjectAlternativeNames(new SubjectAlternativeNames().setEmails(Arrays.asList("wow@gmail.com"))) + .setKeyReusable(true) + .setKeyCurveName(CertificateKeyCurveName.P_256); + Map tags = new HashMap<>(); + tags.put("foo", "bar"); + + certificateAsyncClient.beginCreateCertificate("myCertificate", policy, true, tags) + .subscribe(pollResponse -> { + System.out.println("---------------------------------------------------------------------------------"); + System.out.println(pollResponse.getStatus()); + System.out.println(pollResponse.getValue().getStatus()); + System.out.println(pollResponse.getValue().getStatusDetails()); + }); + + Thread.sleep(22000); + + // Let's create a certificate issuer. + certificateAsyncClient.createIssuer(new CertificateIssuer("myIssuer", "Test")) + .subscribe(issuer -> + System.out.printf("Issuer created with %s and %s\n", issuer.getName(), issuer.getProvider())); + + Thread.sleep(2000); + + // Let's create a certificate signed by our issuer. + certificateAsyncClient.beginCreateCertificate("myCert", + new CertificatePolicy("myIssuer", "CN=IssuerSignedJavaPkcs12"), true, tags) + .subscribe(pollResponse -> { + System.out.println("---------------------------------------------------------------------------------"); + System.out.println(pollResponse.getStatus()); + System.out.println(pollResponse.getValue().getStatus()); + System.out.println(pollResponse.getValue().getStatusDetails()); + }); + + Thread.sleep(22000); + + // Let's list all the certificates in the key vault. + certificateAsyncClient.listPropertiesOfCertificates() + .subscribe(certificateProperties -> + certificateAsyncClient.getCertificateVersion(certificateProperties.getName(), + certificateProperties.getVersion()) + .subscribe(certificateResponse -> + System.out.printf("Received certificate with name %s and key id %s \n", + certificateResponse.getProperties().getName(), certificateResponse.getKeyId()))); + + Thread.sleep(5000); + + // Let's list all certificate versions of the certificate. + certificateAsyncClient.listPropertiesOfCertificateVersions("myCertificate") + .subscribe(certificateProperties -> + certificateAsyncClient.getCertificateVersion(certificateProperties.getName(), + certificateProperties.getVersion()) + .subscribe(certificateResponse -> + System.out.printf("Received certificate with name %s and key id %s\n", + certificateResponse.getProperties().getName(), certificateResponse.getKeyId()))); + + Thread.sleep(5000); + + // Let's list all certificate issuers in the key vault. + certificateAsyncClient.listPropertiesOfIssuers() + .subscribe(issuerProperties -> + certificateAsyncClient.getIssuer(issuerProperties.getName()) + .subscribe(issuerResponse -> + System.out.printf("Received issuer with name %s and provider %s\n", issuerResponse.getName(), + issuerResponse.getProvider()))); + + Thread.sleep(5000); + + // Let's set certificate contacts on the Key vault. + CertificateContact contactToAdd = new CertificateContact().setName("user").setEmail("useremail@example.com"); + certificateAsyncClient.setContacts(Collections.singletonList(contactToAdd)).subscribe(contact -> + System.out.printf("Contact name %s and email %s\n", contact.getName(), contact.getEmail())); + + Thread.sleep(3000); + + // Let's list all certificate contacts in the key vault. + certificateAsyncClient.listContacts().subscribe(contact -> + System.out.printf("Contact name %s and email %s\n", contact.getName(), contact.getEmail())); + + Thread.sleep(3000); + + // Let's delete all certificate contacts in the key vault. + certificateAsyncClient.listContacts().subscribe(contact -> + System.out.printf("Deleted Contact name %s and email %s\n", contact.getName(), contact.getEmail())); + + Thread.sleep(2000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample9/v1/ManagingDeletedCertificates.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample9/v1/ManagingDeletedCertificates.java new file mode 100644 index 000000000000..7dda5442934c --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample9/v1/ManagingDeletedCertificates.java @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.certificates; + +import com.azure.core.util.polling.LongRunningOperationStatus; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.certificates.models.CertificatePolicy; +import com.azure.security.keyvault.certificates.models.SubjectAlternativeNames; +import com.azure.security.keyvault.certificates.models.CertificateOperation; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificate; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificateWithPolicy; +import com.azure.security.keyvault.certificates.models.DeletedCertificate; +import com.azure.security.keyvault.certificates.models.CertificateKeyCurveName; +import com.azure.security.keyvault.certificates.models.CertificateKeyType; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * Sample demonstrates how to list, recover and purge deleted certificates in a soft-delete enabled key vault. + */ +public class ManagingDeletedCertificates { + /** + * Authenticates with the key vault and shows how to list, recover and purge deleted certificates in a soft-delete enabled key vault. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws IllegalArgumentException, InterruptedException { + /* NOTE: To manage deleted certificates, your key vault needs to have soft-delete enabled. Soft-delete allows + deleted certificates to be retained for a given retention period (90 days). During this period deleted + certificates can be recovered and if a certificates needs to be permanently deleted then it needs to be purged. + */ + + /* Instantiate a CertificateClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-certificates/README.md) + for links and instructions. */ + CertificateClient certificateClient = new CertificateClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + // Let's create a self-signed certificate valid for 1 year. If the certificate already exists in the key vault, + // then a new version of the certificate is created. + CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12") + .setSubjectAlternativeNames(new SubjectAlternativeNames().setEmails(Arrays.asList("wow@gmail.com"))) + .setKeyReusable(true) + .setKeyCurveName(CertificateKeyCurveName.P_256) + .setKeyType(CertificateKeyType.EC); + Map tags = new HashMap<>(); + tags.put("foo", "bar"); + + SyncPoller certificatePoller = + certificateClient.beginCreateCertificate("certificateName", policy, true, tags); + certificatePoller.waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); + + KeyVaultCertificate cert = certificatePoller.getFinalResult(); + + // The certificate is no longer needed, need to delete it from the key vault. + SyncPoller deletedCertificatePoller = + certificateClient.beginDeleteCertificate("certificateName"); + // The deleted certificate is accessible as soon as polling beings. + PollResponse pollResponse = deletedCertificatePoller.poll(); + + System.out.printf("Deleted certificate with name %s and recovery id %s", pollResponse.getValue().getName(), + pollResponse.getValue().getRecoveryId()); + + deletedCertificatePoller.waitForCompletion(); + + // To ensure the certificate is deleted server-side. + Thread.sleep(30000); + + // We accidentally deleted the certificate. Let's recover it. + // A deleted certificate can only be recovered if the key vault is soft-delete enabled. + SyncPoller recoverCertPoller = certificateClient + .beginRecoverDeletedCertificate("certificateName"); + // A recovered certificate is accessible as soon as polling beings + PollResponse recoverPollResponse = recoverCertPoller.poll(); + + System.out.printf(" Recovered Deleted certificate with name %s and id %s", recoverPollResponse.getValue() + .getProperties().getName(), recoverPollResponse.getValue().getProperties().getId()); + recoverCertPoller.waitForCompletion(); + + // To ensure the certificate is recovered server-side. + Thread.sleep(30000); + + // The certificate is no longer needed, need to delete them from the key vault. + deletedCertificatePoller = certificateClient.beginDeleteCertificate("certificateName"); + // The deleted certificate is accessible as soon as polling beings. + PollResponse deletePollResponse = deletedCertificatePoller.poll(); + + System.out.printf("Deleted certificate with name %s and recovery id %s", deletePollResponse.getValue().getName(), + deletePollResponse.getValue().getRecoveryId()); + + deletedCertificatePoller.waitForCompletion(); + + // To ensure the certificate is deleted server-side. + Thread.sleep(30000); + + // You can list all the deleted and non-purged certificates, assuming the key vault is soft-delete enabled. + for (DeletedCertificate deletedCert : certificateClient.listDeletedCertificates()) { + System.out.printf("Deleted certificate's recovery Id %s", deletedCert.getRecoveryId()); + } + + // If the key vault is soft-delete enabled, then deleted certificates need to be purged for permanent deletion. + certificateClient.purgeDeletedCertificate("certificateName"); + + // To ensure the certificate is purged server-side. + Thread.sleep(15000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample9/v2/ManagingDeletedCertificates.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample9/v2/ManagingDeletedCertificates.java new file mode 100644 index 000000000000..7dda5442934c --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-certificates/sample9/v2/ManagingDeletedCertificates.java @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.certificates; + +import com.azure.core.util.polling.LongRunningOperationStatus; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.certificates.models.CertificatePolicy; +import com.azure.security.keyvault.certificates.models.SubjectAlternativeNames; +import com.azure.security.keyvault.certificates.models.CertificateOperation; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificate; +import com.azure.security.keyvault.certificates.models.KeyVaultCertificateWithPolicy; +import com.azure.security.keyvault.certificates.models.DeletedCertificate; +import com.azure.security.keyvault.certificates.models.CertificateKeyCurveName; +import com.azure.security.keyvault.certificates.models.CertificateKeyType; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * Sample demonstrates how to list, recover and purge deleted certificates in a soft-delete enabled key vault. + */ +public class ManagingDeletedCertificates { + /** + * Authenticates with the key vault and shows how to list, recover and purge deleted certificates in a soft-delete enabled key vault. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws IllegalArgumentException, InterruptedException { + /* NOTE: To manage deleted certificates, your key vault needs to have soft-delete enabled. Soft-delete allows + deleted certificates to be retained for a given retention period (90 days). During this period deleted + certificates can be recovered and if a certificates needs to be permanently deleted then it needs to be purged. + */ + + /* Instantiate a CertificateClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-certificates/README.md) + for links and instructions. */ + CertificateClient certificateClient = new CertificateClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + // Let's create a self-signed certificate valid for 1 year. If the certificate already exists in the key vault, + // then a new version of the certificate is created. + CertificatePolicy policy = new CertificatePolicy("Self", "CN=SelfSignedJavaPkcs12") + .setSubjectAlternativeNames(new SubjectAlternativeNames().setEmails(Arrays.asList("wow@gmail.com"))) + .setKeyReusable(true) + .setKeyCurveName(CertificateKeyCurveName.P_256) + .setKeyType(CertificateKeyType.EC); + Map tags = new HashMap<>(); + tags.put("foo", "bar"); + + SyncPoller certificatePoller = + certificateClient.beginCreateCertificate("certificateName", policy, true, tags); + certificatePoller.waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); + + KeyVaultCertificate cert = certificatePoller.getFinalResult(); + + // The certificate is no longer needed, need to delete it from the key vault. + SyncPoller deletedCertificatePoller = + certificateClient.beginDeleteCertificate("certificateName"); + // The deleted certificate is accessible as soon as polling beings. + PollResponse pollResponse = deletedCertificatePoller.poll(); + + System.out.printf("Deleted certificate with name %s and recovery id %s", pollResponse.getValue().getName(), + pollResponse.getValue().getRecoveryId()); + + deletedCertificatePoller.waitForCompletion(); + + // To ensure the certificate is deleted server-side. + Thread.sleep(30000); + + // We accidentally deleted the certificate. Let's recover it. + // A deleted certificate can only be recovered if the key vault is soft-delete enabled. + SyncPoller recoverCertPoller = certificateClient + .beginRecoverDeletedCertificate("certificateName"); + // A recovered certificate is accessible as soon as polling beings + PollResponse recoverPollResponse = recoverCertPoller.poll(); + + System.out.printf(" Recovered Deleted certificate with name %s and id %s", recoverPollResponse.getValue() + .getProperties().getName(), recoverPollResponse.getValue().getProperties().getId()); + recoverCertPoller.waitForCompletion(); + + // To ensure the certificate is recovered server-side. + Thread.sleep(30000); + + // The certificate is no longer needed, need to delete them from the key vault. + deletedCertificatePoller = certificateClient.beginDeleteCertificate("certificateName"); + // The deleted certificate is accessible as soon as polling beings. + PollResponse deletePollResponse = deletedCertificatePoller.poll(); + + System.out.printf("Deleted certificate with name %s and recovery id %s", deletePollResponse.getValue().getName(), + deletePollResponse.getValue().getRecoveryId()); + + deletedCertificatePoller.waitForCompletion(); + + // To ensure the certificate is deleted server-side. + Thread.sleep(30000); + + // You can list all the deleted and non-purged certificates, assuming the key vault is soft-delete enabled. + for (DeletedCertificate deletedCert : certificateClient.listDeletedCertificates()) { + System.out.printf("Deleted certificate's recovery Id %s", deletedCert.getRecoveryId()); + } + + // If the key vault is soft-delete enabled, then deleted certificates need to be purged for permanent deletion. + certificateClient.purgeDeletedCertificate("certificateName"); + + // To ensure the certificate is purged server-side. + Thread.sleep(15000); + } +} diff --git a/sdk/keyvault/azure-security-keyvault-jca/src/samples/java/com/azure/security/keyvault/jca/ClientSSLSample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-jca/sample1/v1/ClientSSLSample.java similarity index 100% rename from sdk/keyvault/azure-security-keyvault-jca/src/samples/java/com/azure/security/keyvault/jca/ClientSSLSample.java rename to sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-jca/sample1/v1/ClientSSLSample.java diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-jca/sample1/v2/ClientSSLSample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-jca/sample1/v2/ClientSSLSample.java new file mode 100644 index 000000000000..6de8d9552298 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-jca/sample1/v2/ClientSSLSample.java @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.security.keyvault.jca; + +import org.apache.http.HttpResponse; +import org.apache.http.client.ResponseHandler; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.ssl.SSLContexts; +import org.apache.http.conn.ssl.TrustSelfSignedStrategy; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; + +import javax.net.ssl.SSLContext; +import java.io.IOException; +import java.security.KeyStore; +import java.security.Security; + +/** + * The ClientSSL sample. + */ +public class ClientSSLSample { + + public static void main(String[] args) throws Exception { + // BEGIN: readme-sample-clientSSL + KeyVaultJcaProvider provider = new KeyVaultJcaProvider(); + Security.addProvider(provider); + + KeyStore keyStore = KeyVaultKeyStore.getKeyVaultKeyStoreBySystemProperty(); + + SSLContext sslContext = SSLContexts + .custom() + .loadTrustMaterial(keyStore, new TrustSelfSignedStrategy()) + .build(); + + SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory( + sslContext, (hostname, session) -> true); + + PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager( + RegistryBuilder.create() + .register("https", sslConnectionSocketFactory) + .build()); + + String result = null; + + try (CloseableHttpClient client = HttpClients.custom().setConnectionManager(manager).build()) { + HttpGet httpGet = new HttpGet("https://localhost:8766"); + ResponseHandler responseHandler = (HttpResponse response) -> { + int status = response.getStatusLine().getStatusCode(); + String result1 = "Not success"; + if (status == 204) { + result1 = "Success"; + } + return result1; + }; + result = client.execute(httpGet, responseHandler); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + // END: readme-sample-clientSSL + } + +} diff --git a/sdk/keyvault/azure-security-keyvault-jca/src/samples/java/com/azure/security/keyvault/jca/ServerSSLSample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-jca/sample2/v1/ServerSSLSample.java similarity index 100% rename from sdk/keyvault/azure-security-keyvault-jca/src/samples/java/com/azure/security/keyvault/jca/ServerSSLSample.java rename to sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-jca/sample2/v1/ServerSSLSample.java diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-jca/sample2/v2/ServerSSLSample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-jca/sample2/v2/ServerSSLSample.java new file mode 100644 index 000000000000..94a148036bad --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-jca/sample2/v2/ServerSSLSample.java @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.security.keyvault.jca; + +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLServerSocket; +import javax.net.ssl.SSLServerSocketFactory; +import java.security.KeyStore; +import java.security.Security; + +/** + * The ServerSSL sample. + */ +public class ServerSSLSample { + + public static void main(String[] args) throws Exception { + // BEGIN: readme-sample-serverSSL + KeyVaultJcaProvider provider = new KeyVaultJcaProvider(); + Security.addProvider(provider); + + KeyStore keyStore = KeyVaultKeyStore.getKeyVaultKeyStoreBySystemProperty(); + + KeyManagerFactory managerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + managerFactory.init(keyStore, "".toCharArray()); + + SSLContext context = SSLContext.getInstance("TLS"); + context.init(managerFactory.getKeyManagers(), null, null); + + SSLServerSocketFactory socketFactory = context.getServerSocketFactory(); + SSLServerSocket serverSocket = (SSLServerSocket) socketFactory.createServerSocket(8765); + // END: readme-sample-serverSSL + } + +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample1/v1/BackupAndRestoreOperations.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample1/v1/BackupAndRestoreOperations.java new file mode 100644 index 000000000000..e389f7730b60 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample1/v1/BackupAndRestoreOperations.java @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys; + +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.security.keyvault.keys.models.DeletedKey; +import com.azure.security.keyvault.keys.models.KeyVaultKey; +import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; +import com.azure.identity.DefaultAzureCredentialBuilder; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to backup and restore keys in the key vault. + */ +public class BackupAndRestoreOperations { + /** + * Authenticates with the key vault and shows how to backup and restore keys in the key vault. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + * @throws IOException when writing backup to file is unsuccessful. + */ + public static void main(String[] args) throws IOException, InterruptedException, IllegalArgumentException { + /* Instantiate a KeyClient that will be used to call the service. Notice that the client is using default Azure + credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) + for links and instructions. */ + KeyClient keyClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + // Let's create an RSA key valid for 1 year. If the key already exists in the key vault, then a new version of + // the key is created. + keyClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1)) + .setKeySize(2048)); + + // Backups are good to have, if in case keys get accidentally deleted by you. + // For long term storage, it is ideal to write the backup to a file. + String backupFilePath = "YOUR_BACKUP_FILE_PATH"; + byte[] keyBackup = keyClient.backupKey("CloudRsaKey"); + + writeBackupToFile(keyBackup, backupFilePath); + + // The RSA key is no longer in use, so you delete it. + SyncPoller rsaDeletedKeyPoller = keyClient.beginDeleteKey("CloudRsaKey"); + PollResponse pollResponse = rsaDeletedKeyPoller.poll(); + DeletedKey rsaDeletedKey = pollResponse.getValue(); + + System.out.println("Deleted Date %s" + rsaDeletedKey.getDeletedOn().toString()); + System.out.printf("Deleted Key's Recovery Id %s", rsaDeletedKey.getRecoveryId()); + + // The key is being deleted on the server. + rsaDeletedKeyPoller.waitForCompletion(); + + // To ensure the key is deleted server-side. + Thread.sleep(30000); + + // If the vault is soft-delete enabled, then you need to purge the key as well for permanent deletion. + keyClient.purgeDeletedKey("CloudRsaKey"); + + // To ensure the key is purged server-side. + Thread.sleep(15000); + + // After sometime, the key is required again. We can use the backup value to restore it in the key vault. + byte[] backupFromFile = Files.readAllBytes(new File(backupFilePath).toPath()); + KeyVaultKey restoredKey = keyClient.restoreKeyBackup(backupFromFile); + } + + private static void writeBackupToFile(byte[] bytes, String filePath) { + try { + File file = new File(filePath); + + if (file.exists()) { + file.delete(); + } + + file.createNewFile(); + + OutputStream os = new FileOutputStream(file); + os.write(bytes); + + System.out.println("Successfully wrote backup to file."); + + // Close the file + os.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample1/v2/BackupAndRestoreOperations.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample1/v2/BackupAndRestoreOperations.java new file mode 100644 index 000000000000..e389f7730b60 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample1/v2/BackupAndRestoreOperations.java @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys; + +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.security.keyvault.keys.models.DeletedKey; +import com.azure.security.keyvault.keys.models.KeyVaultKey; +import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; +import com.azure.identity.DefaultAzureCredentialBuilder; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to backup and restore keys in the key vault. + */ +public class BackupAndRestoreOperations { + /** + * Authenticates with the key vault and shows how to backup and restore keys in the key vault. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + * @throws IOException when writing backup to file is unsuccessful. + */ + public static void main(String[] args) throws IOException, InterruptedException, IllegalArgumentException { + /* Instantiate a KeyClient that will be used to call the service. Notice that the client is using default Azure + credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) + for links and instructions. */ + KeyClient keyClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + // Let's create an RSA key valid for 1 year. If the key already exists in the key vault, then a new version of + // the key is created. + keyClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1)) + .setKeySize(2048)); + + // Backups are good to have, if in case keys get accidentally deleted by you. + // For long term storage, it is ideal to write the backup to a file. + String backupFilePath = "YOUR_BACKUP_FILE_PATH"; + byte[] keyBackup = keyClient.backupKey("CloudRsaKey"); + + writeBackupToFile(keyBackup, backupFilePath); + + // The RSA key is no longer in use, so you delete it. + SyncPoller rsaDeletedKeyPoller = keyClient.beginDeleteKey("CloudRsaKey"); + PollResponse pollResponse = rsaDeletedKeyPoller.poll(); + DeletedKey rsaDeletedKey = pollResponse.getValue(); + + System.out.println("Deleted Date %s" + rsaDeletedKey.getDeletedOn().toString()); + System.out.printf("Deleted Key's Recovery Id %s", rsaDeletedKey.getRecoveryId()); + + // The key is being deleted on the server. + rsaDeletedKeyPoller.waitForCompletion(); + + // To ensure the key is deleted server-side. + Thread.sleep(30000); + + // If the vault is soft-delete enabled, then you need to purge the key as well for permanent deletion. + keyClient.purgeDeletedKey("CloudRsaKey"); + + // To ensure the key is purged server-side. + Thread.sleep(15000); + + // After sometime, the key is required again. We can use the backup value to restore it in the key vault. + byte[] backupFromFile = Files.readAllBytes(new File(backupFilePath).toPath()); + KeyVaultKey restoredKey = keyClient.restoreKeyBackup(backupFromFile); + } + + private static void writeBackupToFile(byte[] bytes, String filePath) { + try { + File file = new File(filePath); + + if (file.exists()) { + file.delete(); + } + + file.createNewFile(); + + OutputStream os = new FileOutputStream(file); + os.write(bytes); + + System.out.println("Successfully wrote backup to file."); + + // Close the file + os.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample10/v1/ListOperationsAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample10/v1/ListOperationsAsync.java new file mode 100644 index 000000000000..76fef8f8a684 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample10/v1/ListOperationsAsync.java @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys; + +import com.azure.security.keyvault.keys.models.CreateEcKeyOptions; +import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; +import com.azure.identity.DefaultAzureCredentialBuilder; + +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to asynchronously list keys and versions of a given key in the key vault. + */ +public class ListOperationsAsync { + /** + * Authenticates with the key vault and shows how to asynchronously list keys and list versions of a specific key in + * the key vault. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws InterruptedException { + /* Instantiate a KeyAsyncClient that will be used to call the service. Notice that the client is using default + Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) + for links and instructions. */ + KeyAsyncClient keyAsyncClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + // Let's create EC and RSA keys valid for 1 year. If a key already exists in the key vault, then a new version + // of the key is created. + keyAsyncClient.createEcKey(new CreateEcKeyOptions("CloudEcKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1))) + .subscribe(keyResponse -> + System.out.printf("Key is created with name %s and type %s \n", keyResponse.getName(), + keyResponse.getKeyType())); + + Thread.sleep(2000); + + keyAsyncClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1))) + .subscribe(keyResponse -> + System.out.printf("Key is created with name %s and type %s \n", keyResponse.getName(), + keyResponse.getKeyType())); + + Thread.sleep(2000); + + // You need to check te type of keys already exist in your key vault. Let's list the keys and print their types. + // List operations don't return the keys with key material information. So, for each returned key we call + // getKey() to get the key with its key material information. + keyAsyncClient.listPropertiesOfKeys() + .subscribe(keyBase -> + keyAsyncClient.getKey(keyBase.getName(), keyBase.getVersion()) + .subscribe(keyResponse -> + System.out.printf("Received key with name %s and type %s \n", keyResponse.getName(), + keyResponse.getKeyType()))); + + Thread.sleep(15000); + + // We need the RSA key with a bigger key size, so you want to update the key in key vault to ensure it has the + // required size. Calling createRsaKey on an existing key creates a new version of the key in the key vault + // with the new specified size. + keyAsyncClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") + .setKeySize(4096) + .setExpiresOn(OffsetDateTime.now().plusYears(1))) + .subscribe(keyResponse -> + System.out.printf("Key is created with name %s and type %s \n", keyResponse.getName(), + keyResponse.getKeyType())); + + Thread.sleep(2000); + + // You need to check all the different versions RSA key had previously. Lets print all the versions of this key. + keyAsyncClient.listPropertiesOfKeyVersions("CloudRsaKey") + .subscribe(keyBase -> + keyAsyncClient.getKey(keyBase.getName(), keyBase.getVersion()) + .subscribe(keyResponse -> + System.out.printf("Received key's version with name %s, type %s and version %s \n", + keyResponse.getName(), keyResponse.getKeyType(), + keyResponse.getProperties().getVersion()))); + + Thread.sleep(15000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample10/v2/ListOperationsAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample10/v2/ListOperationsAsync.java new file mode 100644 index 000000000000..76fef8f8a684 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample10/v2/ListOperationsAsync.java @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys; + +import com.azure.security.keyvault.keys.models.CreateEcKeyOptions; +import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; +import com.azure.identity.DefaultAzureCredentialBuilder; + +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to asynchronously list keys and versions of a given key in the key vault. + */ +public class ListOperationsAsync { + /** + * Authenticates with the key vault and shows how to asynchronously list keys and list versions of a specific key in + * the key vault. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws InterruptedException { + /* Instantiate a KeyAsyncClient that will be used to call the service. Notice that the client is using default + Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) + for links and instructions. */ + KeyAsyncClient keyAsyncClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + // Let's create EC and RSA keys valid for 1 year. If a key already exists in the key vault, then a new version + // of the key is created. + keyAsyncClient.createEcKey(new CreateEcKeyOptions("CloudEcKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1))) + .subscribe(keyResponse -> + System.out.printf("Key is created with name %s and type %s \n", keyResponse.getName(), + keyResponse.getKeyType())); + + Thread.sleep(2000); + + keyAsyncClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1))) + .subscribe(keyResponse -> + System.out.printf("Key is created with name %s and type %s \n", keyResponse.getName(), + keyResponse.getKeyType())); + + Thread.sleep(2000); + + // You need to check te type of keys already exist in your key vault. Let's list the keys and print their types. + // List operations don't return the keys with key material information. So, for each returned key we call + // getKey() to get the key with its key material information. + keyAsyncClient.listPropertiesOfKeys() + .subscribe(keyBase -> + keyAsyncClient.getKey(keyBase.getName(), keyBase.getVersion()) + .subscribe(keyResponse -> + System.out.printf("Received key with name %s and type %s \n", keyResponse.getName(), + keyResponse.getKeyType()))); + + Thread.sleep(15000); + + // We need the RSA key with a bigger key size, so you want to update the key in key vault to ensure it has the + // required size. Calling createRsaKey on an existing key creates a new version of the key in the key vault + // with the new specified size. + keyAsyncClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") + .setKeySize(4096) + .setExpiresOn(OffsetDateTime.now().plusYears(1))) + .subscribe(keyResponse -> + System.out.printf("Key is created with name %s and type %s \n", keyResponse.getName(), + keyResponse.getKeyType())); + + Thread.sleep(2000); + + // You need to check all the different versions RSA key had previously. Lets print all the versions of this key. + keyAsyncClient.listPropertiesOfKeyVersions("CloudRsaKey") + .subscribe(keyBase -> + keyAsyncClient.getKey(keyBase.getName(), keyBase.getVersion()) + .subscribe(keyResponse -> + System.out.printf("Received key's version with name %s, type %s and version %s \n", + keyResponse.getName(), keyResponse.getKeyType(), + keyResponse.getProperties().getVersion()))); + + Thread.sleep(15000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample11/v1/ManagingDeletedKeys.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample11/v1/ManagingDeletedKeys.java new file mode 100644 index 000000000000..21c4bdbf5366 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample11/v1/ManagingDeletedKeys.java @@ -0,0 +1,111 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys; + +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.security.keyvault.keys.models.CreateEcKeyOptions; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.keys.models.DeletedKey; +import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; +import com.azure.security.keyvault.keys.models.KeyVaultKey; + +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to list, recover and purge deleted keys in a soft-delete enabled key vault. + */ +public class ManagingDeletedKeys { + /** + * Authenticates with the key vault and shows how to list, recover and purge deleted keys in a soft-delete enabled + * key vault. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws IllegalArgumentException, InterruptedException { + /* NOTE: To manage deleted keys, your key vault needs to have soft-delete enabled. Soft-delete allows deleted + keys to be retained for a given retention period (90 days). During this period deleted keys can be recovered + and if a key needs to be permanently deleted then it needs to be purged.*/ + + /* Instantiate a KeyClient that will be used to call the service. Notice that the client is using default Azure + credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) + for links and instructions. */ + KeyClient keyClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + // Let's create EC and RSA keys valid for 1 year. If the key already exists in the key vault, then a new version + // of the key is created. + keyClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1)) + .setKeySize(2048)); + + keyClient.createEcKey(new CreateEcKeyOptions("CloudEcKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1))); + + // The RSA key is no longer needed, need to delete it from the key vault. + SyncPoller deletedKeyPoller = keyClient.beginDeleteKey("CloudEcKey"); + PollResponse deletedKeyPollResponse = deletedKeyPoller.poll(); + DeletedKey deletedKey = deletedKeyPollResponse.getValue(); + + System.out.println("Deleted Date %s" + deletedKey.getDeletedOn().toString()); + System.out.printf("Deleted Key's Recovery Id %s", deletedKey.getRecoveryId()); + + // The key is being deleted on the server. + deletedKeyPoller.waitForCompletion(); + + // We accidentally deleted the EC key. Let's recover it. + // A deleted key can only be recovered if the key vault is soft-delete enabled. + SyncPoller recoverEcKeyPoller = keyClient.beginRecoverDeletedKey("CloudEcKey"); + PollResponse recoveryEcKeyPollResponse = recoverEcKeyPoller.poll(); + KeyVaultKey recoveredKey = recoveryEcKeyPollResponse.getValue(); + + System.out.println("Recovered Key Name %s" + recoveredKey.getName()); + System.out.printf("Recovered Key's Id %s", recoveredKey.getId()); + + // The key is being recovered on the server. + recoverEcKeyPoller.waitForCompletion(); + + // The EC and RSA keys are no longer needed, need to delete them from the key vault. + SyncPoller ecDeletedKeyPoller = keyClient.beginDeleteKey("CloudEcKey"); + PollResponse ecDeletedKeyPollResponse = ecDeletedKeyPoller.poll(); + DeletedKey ecDeletedKey = ecDeletedKeyPollResponse.getValue(); + + System.out.println("Deleted Date %s" + ecDeletedKey.getDeletedOn().toString()); + System.out.printf("Deleted Key's Recovery Id %s", ecDeletedKey.getRecoveryId()); + + // The key is being deleted on the server. + ecDeletedKeyPoller.waitForCompletion(); + + SyncPoller rsaDeletedKeyPoller = keyClient.beginDeleteKey("CloudRsaKey"); + PollResponse rsaDeletedKeyPollResponse = rsaDeletedKeyPoller.poll(); + DeletedKey rsaDeletedKey = rsaDeletedKeyPollResponse.getValue(); + + System.out.println("Deleted Date %s" + rsaDeletedKey.getDeletedOn().toString()); + System.out.printf("Deleted Key's Recovery Id %s", rsaDeletedKey.getRecoveryId()); + + // The key is being deleted on the server. + rsaDeletedKeyPoller.waitForCompletion(); + + // You can list all the deleted and non-purged keys, assuming key vault is soft-delete enabled. + for (DeletedKey delKey : keyClient.listDeletedKeys()) { + System.out.printf("Deleted key's recovery Id %s", delKey.getRecoveryId()); + } + + // If the keyvault is soft-delete enabled, then for permanent deletion deleted keys need to be purged. + keyClient.purgeDeletedKey("CloudEcKey"); + keyClient.purgeDeletedKey("CloudRsaKey"); + + // To ensure the key is purged server-side. + Thread.sleep(15000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample11/v2/ManagingDeletedKeys.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample11/v2/ManagingDeletedKeys.java new file mode 100644 index 000000000000..21c4bdbf5366 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample11/v2/ManagingDeletedKeys.java @@ -0,0 +1,111 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys; + +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.security.keyvault.keys.models.CreateEcKeyOptions; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.keys.models.DeletedKey; +import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; +import com.azure.security.keyvault.keys.models.KeyVaultKey; + +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to list, recover and purge deleted keys in a soft-delete enabled key vault. + */ +public class ManagingDeletedKeys { + /** + * Authenticates with the key vault and shows how to list, recover and purge deleted keys in a soft-delete enabled + * key vault. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws IllegalArgumentException, InterruptedException { + /* NOTE: To manage deleted keys, your key vault needs to have soft-delete enabled. Soft-delete allows deleted + keys to be retained for a given retention period (90 days). During this period deleted keys can be recovered + and if a key needs to be permanently deleted then it needs to be purged.*/ + + /* Instantiate a KeyClient that will be used to call the service. Notice that the client is using default Azure + credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) + for links and instructions. */ + KeyClient keyClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + // Let's create EC and RSA keys valid for 1 year. If the key already exists in the key vault, then a new version + // of the key is created. + keyClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1)) + .setKeySize(2048)); + + keyClient.createEcKey(new CreateEcKeyOptions("CloudEcKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1))); + + // The RSA key is no longer needed, need to delete it from the key vault. + SyncPoller deletedKeyPoller = keyClient.beginDeleteKey("CloudEcKey"); + PollResponse deletedKeyPollResponse = deletedKeyPoller.poll(); + DeletedKey deletedKey = deletedKeyPollResponse.getValue(); + + System.out.println("Deleted Date %s" + deletedKey.getDeletedOn().toString()); + System.out.printf("Deleted Key's Recovery Id %s", deletedKey.getRecoveryId()); + + // The key is being deleted on the server. + deletedKeyPoller.waitForCompletion(); + + // We accidentally deleted the EC key. Let's recover it. + // A deleted key can only be recovered if the key vault is soft-delete enabled. + SyncPoller recoverEcKeyPoller = keyClient.beginRecoverDeletedKey("CloudEcKey"); + PollResponse recoveryEcKeyPollResponse = recoverEcKeyPoller.poll(); + KeyVaultKey recoveredKey = recoveryEcKeyPollResponse.getValue(); + + System.out.println("Recovered Key Name %s" + recoveredKey.getName()); + System.out.printf("Recovered Key's Id %s", recoveredKey.getId()); + + // The key is being recovered on the server. + recoverEcKeyPoller.waitForCompletion(); + + // The EC and RSA keys are no longer needed, need to delete them from the key vault. + SyncPoller ecDeletedKeyPoller = keyClient.beginDeleteKey("CloudEcKey"); + PollResponse ecDeletedKeyPollResponse = ecDeletedKeyPoller.poll(); + DeletedKey ecDeletedKey = ecDeletedKeyPollResponse.getValue(); + + System.out.println("Deleted Date %s" + ecDeletedKey.getDeletedOn().toString()); + System.out.printf("Deleted Key's Recovery Id %s", ecDeletedKey.getRecoveryId()); + + // The key is being deleted on the server. + ecDeletedKeyPoller.waitForCompletion(); + + SyncPoller rsaDeletedKeyPoller = keyClient.beginDeleteKey("CloudRsaKey"); + PollResponse rsaDeletedKeyPollResponse = rsaDeletedKeyPoller.poll(); + DeletedKey rsaDeletedKey = rsaDeletedKeyPollResponse.getValue(); + + System.out.println("Deleted Date %s" + rsaDeletedKey.getDeletedOn().toString()); + System.out.printf("Deleted Key's Recovery Id %s", rsaDeletedKey.getRecoveryId()); + + // The key is being deleted on the server. + rsaDeletedKeyPoller.waitForCompletion(); + + // You can list all the deleted and non-purged keys, assuming key vault is soft-delete enabled. + for (DeletedKey delKey : keyClient.listDeletedKeys()) { + System.out.printf("Deleted key's recovery Id %s", delKey.getRecoveryId()); + } + + // If the keyvault is soft-delete enabled, then for permanent deletion deleted keys need to be purged. + keyClient.purgeDeletedKey("CloudEcKey"); + keyClient.purgeDeletedKey("CloudRsaKey"); + + // To ensure the key is purged server-side. + Thread.sleep(15000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample12/v1/ManagingDeletedKeysAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample12/v1/ManagingDeletedKeysAsync.java new file mode 100644 index 000000000000..1d8f5e136117 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample12/v1/ManagingDeletedKeysAsync.java @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys; + +import com.azure.security.keyvault.keys.models.CreateEcKeyOptions; +import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; +import com.azure.identity.DefaultAzureCredentialBuilder; + +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to asynchronously list, recover and purge deleted keys in a soft-delete enabled key vault. + */ +public class ManagingDeletedKeysAsync { + /** + * Authenticates with the key vault and shows how to asynchronously list, recover and purge deleted keys in a + * soft-delete enabled key vault. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws InterruptedException { + /* NOTE: To manage deleted keys, your key vault needs to have soft-delete enabled. Soft-delete allows deleted + keys to be retained for a given retention period (90 days). During this period deleted keys can be recovered + and if a key needs to be permanently deleted then it needs to be purged.*/ + + /* Instantiate a KeyAsyncClient that will be used to call the service. Notice that the client is using default + Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) + for links and instructions. */ + KeyAsyncClient keyAsyncClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + // Let's create EC and RSA keys valid for 1 year. If the key already exists in the key vault, then a new version + // of the key is created. + keyAsyncClient.createEcKey(new CreateEcKeyOptions("CloudEcKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1))) + .subscribe(keyResponse -> + System.out.printf("Key is created with name %s and type %s %n", keyResponse.getName(), + keyResponse.getKeyType())); + + Thread.sleep(2000); + + keyAsyncClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1))) + .subscribe(keyResponse -> + System.out.printf("Key is created with name %s and type %s %n", keyResponse.getName(), + keyResponse.getKeyType())); + + Thread.sleep(2000); + + // The RSA key is no longer needed, need to delete it from the key vault. + keyAsyncClient.beginDeleteKey("CloudEcKey") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Delete Key Name: " + pollResponse.getValue().getName()); + System.out.println("Key Delete Date: " + pollResponse.getValue().getDeletedOn().toString()); + }); + + // To ensure the key is deleted server-side. + Thread.sleep(30000); + + // We accidentally deleted the EC key. Let's recover it. + // A deleted key can only be recovered if the key vault is soft-delete enabled. + keyAsyncClient.beginRecoverDeletedKey("CloudEcKey") + .subscribe(pollResponse -> { + System.out.println("Recovery Status: " + pollResponse.getStatus().toString()); + System.out.println("Recover Key Name: " + pollResponse.getValue().getName()); + System.out.println("Recover Key Type: " + pollResponse.getValue().getKeyType()); + }); + + // To ensure the key is recovered server-side before moving forward. + Thread.sleep(10000); + + // The EC and RSA keys are no longer needed, need to delete them from the key vault. + keyAsyncClient.beginDeleteKey("CloudEcKey") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Delete Key Name: " + pollResponse.getValue().getName()); + System.out.println("Key Delete Date: " + pollResponse.getValue().getDeletedOn().toString()); + }); + + keyAsyncClient.beginDeleteKey("CloudRsaKey") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Delete Key Name: " + pollResponse.getValue().getName()); + System.out.println("Key Delete Date: " + pollResponse.getValue().getDeletedOn().toString()); + }); + + // To ensure the key is deleted server-side. + Thread.sleep(30000); + + // You can list all the deleted and non-purged keys, assuming key vault is soft-delete enabled. + keyAsyncClient.listDeletedKeys() + .subscribe(deletedKey -> + System.out.printf("Deleted key's recovery Id %s %n", deletedKey.getRecoveryId())); + + Thread.sleep(15000); + + // If the keyvault is soft-delete enabled, then for permanent deletion deleted keys need to be purged. + keyAsyncClient.purgeDeletedKeyWithResponse("CloudRsaKey") + .subscribe(purgeResponse -> + System.out.printf("Storage account key purge status response %d %n", purgeResponse.getStatusCode())); + + keyAsyncClient.purgeDeletedKeyWithResponse("CloudEcKey") + .subscribe(purgeResponse -> + System.out.printf("Bank account key purge status response %d %n", purgeResponse.getStatusCode())); + + // To ensure the key is purged server-side. + Thread.sleep(15000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample12/v2/ManagingDeletedKeysAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample12/v2/ManagingDeletedKeysAsync.java new file mode 100644 index 000000000000..1d8f5e136117 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample12/v2/ManagingDeletedKeysAsync.java @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys; + +import com.azure.security.keyvault.keys.models.CreateEcKeyOptions; +import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; +import com.azure.identity.DefaultAzureCredentialBuilder; + +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to asynchronously list, recover and purge deleted keys in a soft-delete enabled key vault. + */ +public class ManagingDeletedKeysAsync { + /** + * Authenticates with the key vault and shows how to asynchronously list, recover and purge deleted keys in a + * soft-delete enabled key vault. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws InterruptedException { + /* NOTE: To manage deleted keys, your key vault needs to have soft-delete enabled. Soft-delete allows deleted + keys to be retained for a given retention period (90 days). During this period deleted keys can be recovered + and if a key needs to be permanently deleted then it needs to be purged.*/ + + /* Instantiate a KeyAsyncClient that will be used to call the service. Notice that the client is using default + Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) + for links and instructions. */ + KeyAsyncClient keyAsyncClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + // Let's create EC and RSA keys valid for 1 year. If the key already exists in the key vault, then a new version + // of the key is created. + keyAsyncClient.createEcKey(new CreateEcKeyOptions("CloudEcKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1))) + .subscribe(keyResponse -> + System.out.printf("Key is created with name %s and type %s %n", keyResponse.getName(), + keyResponse.getKeyType())); + + Thread.sleep(2000); + + keyAsyncClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1))) + .subscribe(keyResponse -> + System.out.printf("Key is created with name %s and type %s %n", keyResponse.getName(), + keyResponse.getKeyType())); + + Thread.sleep(2000); + + // The RSA key is no longer needed, need to delete it from the key vault. + keyAsyncClient.beginDeleteKey("CloudEcKey") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Delete Key Name: " + pollResponse.getValue().getName()); + System.out.println("Key Delete Date: " + pollResponse.getValue().getDeletedOn().toString()); + }); + + // To ensure the key is deleted server-side. + Thread.sleep(30000); + + // We accidentally deleted the EC key. Let's recover it. + // A deleted key can only be recovered if the key vault is soft-delete enabled. + keyAsyncClient.beginRecoverDeletedKey("CloudEcKey") + .subscribe(pollResponse -> { + System.out.println("Recovery Status: " + pollResponse.getStatus().toString()); + System.out.println("Recover Key Name: " + pollResponse.getValue().getName()); + System.out.println("Recover Key Type: " + pollResponse.getValue().getKeyType()); + }); + + // To ensure the key is recovered server-side before moving forward. + Thread.sleep(10000); + + // The EC and RSA keys are no longer needed, need to delete them from the key vault. + keyAsyncClient.beginDeleteKey("CloudEcKey") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Delete Key Name: " + pollResponse.getValue().getName()); + System.out.println("Key Delete Date: " + pollResponse.getValue().getDeletedOn().toString()); + }); + + keyAsyncClient.beginDeleteKey("CloudRsaKey") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Delete Key Name: " + pollResponse.getValue().getName()); + System.out.println("Key Delete Date: " + pollResponse.getValue().getDeletedOn().toString()); + }); + + // To ensure the key is deleted server-side. + Thread.sleep(30000); + + // You can list all the deleted and non-purged keys, assuming key vault is soft-delete enabled. + keyAsyncClient.listDeletedKeys() + .subscribe(deletedKey -> + System.out.printf("Deleted key's recovery Id %s %n", deletedKey.getRecoveryId())); + + Thread.sleep(15000); + + // If the keyvault is soft-delete enabled, then for permanent deletion deleted keys need to be purged. + keyAsyncClient.purgeDeletedKeyWithResponse("CloudRsaKey") + .subscribe(purgeResponse -> + System.out.printf("Storage account key purge status response %d %n", purgeResponse.getStatusCode())); + + keyAsyncClient.purgeDeletedKeyWithResponse("CloudEcKey") + .subscribe(purgeResponse -> + System.out.printf("Bank account key purge status response %d %n", purgeResponse.getStatusCode())); + + // To ensure the key is purged server-side. + Thread.sleep(15000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample13/v1/ReadmeSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample13/v1/ReadmeSamples.java new file mode 100644 index 000000000000..78e2859750b6 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample13/v1/ReadmeSamples.java @@ -0,0 +1,264 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys; + +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient; +import com.azure.security.keyvault.keys.cryptography.CryptographyClient; +import com.azure.security.keyvault.keys.cryptography.CryptographyClientBuilder; +import com.azure.security.keyvault.keys.cryptography.models.DecryptResult; +import com.azure.security.keyvault.keys.cryptography.models.EncryptResult; +import com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm; +import com.azure.security.keyvault.keys.models.CreateEcKeyOptions; +import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; +import com.azure.security.keyvault.keys.models.DeletedKey; +import com.azure.security.keyvault.keys.models.KeyCurveName; +import com.azure.security.keyvault.keys.models.KeyProperties; +import com.azure.security.keyvault.keys.models.KeyVaultKey; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.security.SecureRandom; +import java.time.OffsetDateTime; + +@SuppressWarnings("unused") +public class ReadmeSamples { + private static final byte[] SEED; + + static { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(bos); + byte[] seed; + try { + dos.writeLong(0x1234567L); + dos.flush(); + seed = bos.toByteArray(); + } catch (IOException ex) { + seed = new byte[0]; + } + + SEED = seed; + } + + private final KeyClient keyClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + private final KeyAsyncClient keyAsyncClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + private final CryptographyClient cryptoClient = new CryptographyClientBuilder() + .credential(new DefaultAzureCredentialBuilder().build()) + .keyIdentifier("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + // END: readme-sample-createKeyClient + } + + public void createCryptographyClient() { + // BEGIN: readme-sample-createCryptographyClient + // Create client with key identifier from Key Vault. + CryptographyClient cryptoClient = new CryptographyClientBuilder() + .keyIdentifier("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + // END: readme-sample-createCryptographyClient + } + + public void createKey() { + // BEGIN: readme-sample-createKey + KeyVaultKey rsaKey = keyClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1)) + .setKeySize(2048)); + System.out.printf("Key created with name \"%s\" and id %s%n", rsaKey.getName(), rsaKey.getId()); + + KeyVaultKey ecKey = keyClient.createEcKey(new CreateEcKeyOptions("CloudEcKey") + .setCurveName(KeyCurveName.P_256) + .setExpiresOn(OffsetDateTime.now().plusYears(1))); + System.out.printf("Key created with name \"%s\" and id %s%n", ecKey.getName(), ecKey.getId()); + // END: readme-sample-createKey + } + + public void retrieveKey() { + // BEGIN: readme-sample-retrieveKey + KeyVaultKey key = keyClient.getKey(""); + System.out.printf("A key was returned with name \"%s\" and id %s%n", key.getName(), key.getId()); + // END: readme-sample-retrieveKey + } + + public void updateKey() { + // BEGIN: readme-sample-updateKey + // Get the key to update. + KeyVaultKey key = keyClient.getKey(""); + // Update the expiry time of the key. + key.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(30)); + KeyVaultKey updatedKey = keyClient.updateKeyProperties(key.getProperties()); + System.out.printf("Key's updated expiry time: %s%n", updatedKey.getProperties().getExpiresOn()); + // END: readme-sample-updateKey + } + + public void deleteKey() { + // BEGIN: readme-sample-deleteKey + SyncPoller deletedKeyPoller = keyClient.beginDeleteKey(""); + + PollResponse deletedKeyPollResponse = deletedKeyPoller.poll(); + + // Deleted key is accessible as soon as polling begins. + DeletedKey deletedKey = deletedKeyPollResponse.getValue(); + // Deletion date only works for a soft-delete enabled key vault. + System.out.printf("Deletion date: %s%n", deletedKey.getDeletedOn()); + + // The key is being deleted on the server. + deletedKeyPoller.waitForCompletion(); + // END: readme-sample-deleteKey + } + + public void listKeys() { + // BEGIN: readme-sample-listKeys + // List operations don't return the keys with key material information. So, for each returned key we call getKey to + // get the key with its key material information. + for (KeyProperties keyProperties : keyClient.listPropertiesOfKeys()) { + KeyVaultKey keyWithMaterial = keyClient.getKey(keyProperties.getName(), keyProperties.getVersion()); + System.out.printf("Received key with name \"%s\" and type \"%s\"%n", keyWithMaterial.getName(), + keyWithMaterial.getKey().getKeyType()); + } + // END: readme-sample-listKeys + } + + public void encrypt() { + // BEGIN: readme-sample-encrypt + byte[] plaintext = new byte[100]; + new SecureRandom(SEED).nextBytes(plaintext); + + // Let's encrypt a simple plain text of size 100 bytes. + EncryptResult encryptionResult = cryptoClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext); + System.out.printf("Returned ciphertext size is %d bytes with algorithm \"%s\"%n", + encryptionResult.getCipherText().length, encryptionResult.getAlgorithm()); + // END: readme-sample-encrypt + } + + public void decrypt() { + // BEGIN: readme-sample-decrypt + byte[] plaintext = new byte[100]; + new SecureRandom(SEED).nextBytes(plaintext); + EncryptResult encryptionResult = cryptoClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext); + + //Let's decrypt the encrypted result. + DecryptResult decryptionResult = cryptoClient.decrypt(EncryptionAlgorithm.RSA_OAEP, encryptionResult.getCipherText()); + System.out.printf("Returned plaintext size is %d bytes%n", decryptionResult.getPlainText().length); + // END: readme-sample-decrypt + } + + public void createKeyAsync() { + // BEGIN: readme-sample-createKeyAsync + keyAsyncClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1)) + .setKeySize(2048)) + .subscribe(key -> + System.out.printf("Key created with name \"%s\" and id %s%n", key.getName(), key.getId())); + + keyAsyncClient.createEcKey(new CreateEcKeyOptions("CloudEcKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1))) + .subscribe(key -> + System.out.printf("Key created with name \"%s\" and id %s%n", key.getName(), key.getId())); + // END: readme-sample-createKeyAsync + } + + public void retrieveKeyAsync() { + // BEGIN: readme-sample-retrieveKeyAsync + keyAsyncClient.getKey("") + .subscribe(key -> + System.out.printf("Key was returned with name \"%s\" and id %s%n", key.getName(), key.getId())); + // END: readme-sample-retrieveKeyAsync + } + + public void updateKeyAsync() { + // BEGIN: readme-sample-updateKeyAsync + keyAsyncClient.getKey("") + .flatMap(key -> { + // Update the expiry time of the key. + key.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(50)); + return keyAsyncClient.updateKeyProperties(key.getProperties()); + }).subscribe(updatedKey -> + System.out.printf("Key's updated expiry time: %s%n", updatedKey.getProperties().getExpiresOn())); + // END: readme-sample-updateKeyAsync + } + + public void deleteKeyAsync() { + // BEGIN: readme-sample-deleteKeyAsync + keyAsyncClient.beginDeleteKey("") + .subscribe(pollResponse -> { + System.out.printf("Deletion status: %s%n", pollResponse.getStatus()); + System.out.printf("Deleted key name: %s%n", pollResponse.getValue().getName()); + System.out.printf("Key deletion date: %s%n", pollResponse.getValue().getDeletedOn()); + }); + // END: readme-sample-deleteKeyAsync + } + + public void listKeysAsync() { + // BEGIN: readme-sample-listKeysAsync + // The List Keys operation returns keys without their value, so for each key returned we call `getKey` to get its value + // as well. + keyAsyncClient.listPropertiesOfKeys() + .flatMap(keyProperties -> keyAsyncClient.getKey(keyProperties.getName(), keyProperties.getVersion())) + .subscribe(key -> + System.out.printf("Received key with name \"%s\" and type \"%s\"", key.getName(), key.getKeyType())); + // END: readme-sample-listKeysAsync + } + + public void encryptAsync() { + // BEGIN: readme-sample-encryptAsync + byte[] plaintext = new byte[100]; + new SecureRandom(SEED).nextBytes(plaintext); + + // Let's encrypt a simple plain text of size 100 bytes. + cryptoAsyncClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext) + .subscribe(encryptionResult -> System.out.printf("Returned ciphertext size is %d bytes with algorithm \"%s\"%n", + encryptionResult.getCipherText().length, encryptionResult.getAlgorithm())); + // END: readme-sample-encryptAsync + } + + public void decryptAsync() { + // BEGIN: readme-sample-decryptAsync + byte[] plaintext = new byte[100]; + new SecureRandom(SEED).nextBytes(plaintext); + + // Let's encrypt a simple plain text of size 100 bytes. + cryptoAsyncClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext) + .flatMap(encryptionResult -> { + System.out.printf("Returned ciphertext size is %d bytes with algorithm \"%s\"%n", + encryptionResult.getCipherText().length, encryptionResult.getAlgorithm()); + //Let's decrypt the encrypted response. + return cryptoAsyncClient.decrypt(EncryptionAlgorithm.RSA_OAEP, encryptionResult.getCipherText()); + }).subscribe(decryptionResult -> + System.out.printf("Returned plaintext size is %d bytes%n", decryptionResult.getPlainText().length)); + // END: readme-sample-decryptAsync + } + + public void troubleshooting() { + // BEGIN: readme-sample-troubleshooting + try { + keyClient.getKey(""); + } catch (ResourceNotFoundException e) { + System.out.println(e.getMessage()); + } + // END: readme-sample-troubleshooting + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample13/v2/ReadmeSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample13/v2/ReadmeSamples.java new file mode 100644 index 000000000000..78e2859750b6 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample13/v2/ReadmeSamples.java @@ -0,0 +1,264 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys; + +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient; +import com.azure.security.keyvault.keys.cryptography.CryptographyClient; +import com.azure.security.keyvault.keys.cryptography.CryptographyClientBuilder; +import com.azure.security.keyvault.keys.cryptography.models.DecryptResult; +import com.azure.security.keyvault.keys.cryptography.models.EncryptResult; +import com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm; +import com.azure.security.keyvault.keys.models.CreateEcKeyOptions; +import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; +import com.azure.security.keyvault.keys.models.DeletedKey; +import com.azure.security.keyvault.keys.models.KeyCurveName; +import com.azure.security.keyvault.keys.models.KeyProperties; +import com.azure.security.keyvault.keys.models.KeyVaultKey; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.security.SecureRandom; +import java.time.OffsetDateTime; + +@SuppressWarnings("unused") +public class ReadmeSamples { + private static final byte[] SEED; + + static { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(bos); + byte[] seed; + try { + dos.writeLong(0x1234567L); + dos.flush(); + seed = bos.toByteArray(); + } catch (IOException ex) { + seed = new byte[0]; + } + + SEED = seed; + } + + private final KeyClient keyClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + private final KeyAsyncClient keyAsyncClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + private final CryptographyClient cryptoClient = new CryptographyClientBuilder() + .credential(new DefaultAzureCredentialBuilder().build()) + .keyIdentifier("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + // END: readme-sample-createKeyClient + } + + public void createCryptographyClient() { + // BEGIN: readme-sample-createCryptographyClient + // Create client with key identifier from Key Vault. + CryptographyClient cryptoClient = new CryptographyClientBuilder() + .keyIdentifier("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + // END: readme-sample-createCryptographyClient + } + + public void createKey() { + // BEGIN: readme-sample-createKey + KeyVaultKey rsaKey = keyClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1)) + .setKeySize(2048)); + System.out.printf("Key created with name \"%s\" and id %s%n", rsaKey.getName(), rsaKey.getId()); + + KeyVaultKey ecKey = keyClient.createEcKey(new CreateEcKeyOptions("CloudEcKey") + .setCurveName(KeyCurveName.P_256) + .setExpiresOn(OffsetDateTime.now().plusYears(1))); + System.out.printf("Key created with name \"%s\" and id %s%n", ecKey.getName(), ecKey.getId()); + // END: readme-sample-createKey + } + + public void retrieveKey() { + // BEGIN: readme-sample-retrieveKey + KeyVaultKey key = keyClient.getKey(""); + System.out.printf("A key was returned with name \"%s\" and id %s%n", key.getName(), key.getId()); + // END: readme-sample-retrieveKey + } + + public void updateKey() { + // BEGIN: readme-sample-updateKey + // Get the key to update. + KeyVaultKey key = keyClient.getKey(""); + // Update the expiry time of the key. + key.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(30)); + KeyVaultKey updatedKey = keyClient.updateKeyProperties(key.getProperties()); + System.out.printf("Key's updated expiry time: %s%n", updatedKey.getProperties().getExpiresOn()); + // END: readme-sample-updateKey + } + + public void deleteKey() { + // BEGIN: readme-sample-deleteKey + SyncPoller deletedKeyPoller = keyClient.beginDeleteKey(""); + + PollResponse deletedKeyPollResponse = deletedKeyPoller.poll(); + + // Deleted key is accessible as soon as polling begins. + DeletedKey deletedKey = deletedKeyPollResponse.getValue(); + // Deletion date only works for a soft-delete enabled key vault. + System.out.printf("Deletion date: %s%n", deletedKey.getDeletedOn()); + + // The key is being deleted on the server. + deletedKeyPoller.waitForCompletion(); + // END: readme-sample-deleteKey + } + + public void listKeys() { + // BEGIN: readme-sample-listKeys + // List operations don't return the keys with key material information. So, for each returned key we call getKey to + // get the key with its key material information. + for (KeyProperties keyProperties : keyClient.listPropertiesOfKeys()) { + KeyVaultKey keyWithMaterial = keyClient.getKey(keyProperties.getName(), keyProperties.getVersion()); + System.out.printf("Received key with name \"%s\" and type \"%s\"%n", keyWithMaterial.getName(), + keyWithMaterial.getKey().getKeyType()); + } + // END: readme-sample-listKeys + } + + public void encrypt() { + // BEGIN: readme-sample-encrypt + byte[] plaintext = new byte[100]; + new SecureRandom(SEED).nextBytes(plaintext); + + // Let's encrypt a simple plain text of size 100 bytes. + EncryptResult encryptionResult = cryptoClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext); + System.out.printf("Returned ciphertext size is %d bytes with algorithm \"%s\"%n", + encryptionResult.getCipherText().length, encryptionResult.getAlgorithm()); + // END: readme-sample-encrypt + } + + public void decrypt() { + // BEGIN: readme-sample-decrypt + byte[] plaintext = new byte[100]; + new SecureRandom(SEED).nextBytes(plaintext); + EncryptResult encryptionResult = cryptoClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext); + + //Let's decrypt the encrypted result. + DecryptResult decryptionResult = cryptoClient.decrypt(EncryptionAlgorithm.RSA_OAEP, encryptionResult.getCipherText()); + System.out.printf("Returned plaintext size is %d bytes%n", decryptionResult.getPlainText().length); + // END: readme-sample-decrypt + } + + public void createKeyAsync() { + // BEGIN: readme-sample-createKeyAsync + keyAsyncClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1)) + .setKeySize(2048)) + .subscribe(key -> + System.out.printf("Key created with name \"%s\" and id %s%n", key.getName(), key.getId())); + + keyAsyncClient.createEcKey(new CreateEcKeyOptions("CloudEcKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1))) + .subscribe(key -> + System.out.printf("Key created with name \"%s\" and id %s%n", key.getName(), key.getId())); + // END: readme-sample-createKeyAsync + } + + public void retrieveKeyAsync() { + // BEGIN: readme-sample-retrieveKeyAsync + keyAsyncClient.getKey("") + .subscribe(key -> + System.out.printf("Key was returned with name \"%s\" and id %s%n", key.getName(), key.getId())); + // END: readme-sample-retrieveKeyAsync + } + + public void updateKeyAsync() { + // BEGIN: readme-sample-updateKeyAsync + keyAsyncClient.getKey("") + .flatMap(key -> { + // Update the expiry time of the key. + key.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(50)); + return keyAsyncClient.updateKeyProperties(key.getProperties()); + }).subscribe(updatedKey -> + System.out.printf("Key's updated expiry time: %s%n", updatedKey.getProperties().getExpiresOn())); + // END: readme-sample-updateKeyAsync + } + + public void deleteKeyAsync() { + // BEGIN: readme-sample-deleteKeyAsync + keyAsyncClient.beginDeleteKey("") + .subscribe(pollResponse -> { + System.out.printf("Deletion status: %s%n", pollResponse.getStatus()); + System.out.printf("Deleted key name: %s%n", pollResponse.getValue().getName()); + System.out.printf("Key deletion date: %s%n", pollResponse.getValue().getDeletedOn()); + }); + // END: readme-sample-deleteKeyAsync + } + + public void listKeysAsync() { + // BEGIN: readme-sample-listKeysAsync + // The List Keys operation returns keys without their value, so for each key returned we call `getKey` to get its value + // as well. + keyAsyncClient.listPropertiesOfKeys() + .flatMap(keyProperties -> keyAsyncClient.getKey(keyProperties.getName(), keyProperties.getVersion())) + .subscribe(key -> + System.out.printf("Received key with name \"%s\" and type \"%s\"", key.getName(), key.getKeyType())); + // END: readme-sample-listKeysAsync + } + + public void encryptAsync() { + // BEGIN: readme-sample-encryptAsync + byte[] plaintext = new byte[100]; + new SecureRandom(SEED).nextBytes(plaintext); + + // Let's encrypt a simple plain text of size 100 bytes. + cryptoAsyncClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext) + .subscribe(encryptionResult -> System.out.printf("Returned ciphertext size is %d bytes with algorithm \"%s\"%n", + encryptionResult.getCipherText().length, encryptionResult.getAlgorithm())); + // END: readme-sample-encryptAsync + } + + public void decryptAsync() { + // BEGIN: readme-sample-decryptAsync + byte[] plaintext = new byte[100]; + new SecureRandom(SEED).nextBytes(plaintext); + + // Let's encrypt a simple plain text of size 100 bytes. + cryptoAsyncClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext) + .flatMap(encryptionResult -> { + System.out.printf("Returned ciphertext size is %d bytes with algorithm \"%s\"%n", + encryptionResult.getCipherText().length, encryptionResult.getAlgorithm()); + //Let's decrypt the encrypted response. + return cryptoAsyncClient.decrypt(EncryptionAlgorithm.RSA_OAEP, encryptionResult.getCipherText()); + }).subscribe(decryptionResult -> + System.out.printf("Returned plaintext size is %d bytes%n", decryptionResult.getPlainText().length)); + // END: readme-sample-decryptAsync + } + + public void troubleshooting() { + // BEGIN: readme-sample-troubleshooting + try { + keyClient.getKey(""); + } catch (ResourceNotFoundException e) { + System.out.println(e.getMessage()); + } + // END: readme-sample-troubleshooting + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample14/v1/CryptographyAsyncClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample14/v1/CryptographyAsyncClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..3dc44cbd7474 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample14/v1/CryptographyAsyncClientJavaDocCodeSnippets.java @@ -0,0 +1,280 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys.cryptography; + +import com.azure.core.http.HttpClient; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.policy.HttpLogOptions; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.keys.cryptography.models.DecryptParameters; +import com.azure.security.keyvault.keys.cryptography.models.EncryptParameters; +import com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm; +import com.azure.security.keyvault.keys.cryptography.models.KeyWrapAlgorithm; +import com.azure.security.keyvault.keys.cryptography.models.SignatureAlgorithm; +import com.azure.security.keyvault.keys.models.JsonWebKey; +import reactor.util.context.Context; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Random; + +/** + * This class contains code samples for generating javadocs through doclets for {@link CryptographyAsyncClient}. + */ +public final class CryptographyAsyncClientJavaDocCodeSnippets { + /** + * Generates a code sample for creating a {@link CryptographyAsyncClient}. + * + * @return An instance of {@link CryptographyAsyncClient}. + */ + public CryptographyAsyncClient createAsyncClient() { + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.instantiation + CryptographyAsyncClient cryptographyAsyncClient = new CryptographyClientBuilder() + .keyIdentifier("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.instantiation + + return cryptographyAsyncClient; + } + + /** + * Generates a code sample for creating a {@link CryptographyAsyncClient} with a given {@link JsonWebKey}. + * + * @return An instance of {@link CryptographyAsyncClient}. + */ + public CryptographyAsyncClient createAsyncClientWithJsonWebKey() { + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.withJsonWebKey.instantiation + JsonWebKey jsonWebKey = new JsonWebKey().setId("SampleJsonWebKey"); + CryptographyAsyncClient cryptographyAsyncClient = new CryptographyClientBuilder() + .jsonWebKey(jsonWebKey) + .buildAsyncClient(); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.withJsonWebKey.instantiation + + return cryptographyAsyncClient; + } + + /** + * Generates a code sample for creating a {@link CryptographyAsyncClient} with a given {@link HttpClient}. + * + * @return An instance of {@link CryptographyAsyncClient}. + */ + public CryptographyAsyncClient createAsyncClientWithHttpClient() { + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.withHttpClient.instantiation + CryptographyAsyncClient cryptographyAsyncClient = new CryptographyClientBuilder() + .keyIdentifier("") + .credential(new DefaultAzureCredentialBuilder().build()) + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) + .httpClient(HttpClient.createDefault()) + .buildAsyncClient(); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.withHttpClient.instantiation + + return cryptographyAsyncClient; + } + + /** + * Generates a code sample for using {@link CryptographyAsyncClient#getKey()}. + */ + public void getKeySnippets() { + CryptographyAsyncClient cryptographyAsyncClient = createAsyncClient(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKey + cryptographyAsyncClient.getKey() + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(key -> + System.out.printf("Key returned with name: %s, and id: %s.%n", key.getName(), key.getId())); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKey + } + + /** + * Generates a code sample for using {@link CryptographyAsyncClient#getKeyWithResponse()}. + */ + public void getKeyWithResponseSnippets() { + CryptographyAsyncClient cryptographyAsyncClient = createAsyncClient(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKeyWithResponse + cryptographyAsyncClient.getKeyWithResponse() + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(keyResponse -> + System.out.printf("Key returned with name: %s, and id: %s.%n", keyResponse.getValue().getName(), + keyResponse.getValue().getId())); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKeyWithResponse + } + + /** + * Generates code samples for using {@link CryptographyAsyncClient#encrypt(EncryptionAlgorithm, byte[])} and + * {@link CryptographyAsyncClient#encrypt(EncryptParameters)}. + */ + public void encrypt() { + CryptographyAsyncClient cryptographyAsyncClient = createAsyncClient(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt#EncryptionAlgorithm-byte + byte[] plaintext = new byte[100]; + new Random(0x1234567L).nextBytes(plaintext); + + cryptographyAsyncClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(encryptResult -> + System.out.printf("Received encrypted content of length: %d, with algorithm: %s.%n", + encryptResult.getCipherText().length, encryptResult.getAlgorithm().toString())); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt#EncryptionAlgorithm-byte + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt#EncryptParameters + byte[] plaintextBytes = new byte[100]; + new Random(0x1234567L).nextBytes(plaintextBytes); + byte[] iv = { + (byte) 0x1a, (byte) 0xf3, (byte) 0x8c, (byte) 0x2d, (byte) 0xc2, (byte) 0xb9, (byte) 0x6f, (byte) 0xfd, + (byte) 0xd8, (byte) 0x66, (byte) 0x94, (byte) 0x09, (byte) 0x23, (byte) 0x41, (byte) 0xbc, (byte) 0x04 + }; + + EncryptParameters encryptParameters = EncryptParameters.createA128CbcParameters(plaintextBytes, iv); + + cryptographyAsyncClient.encrypt(encryptParameters) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(encryptResult -> + System.out.printf("Received encrypted content of length: %d, with algorithm: %s.%n", + encryptResult.getCipherText().length, encryptResult.getAlgorithm().toString())); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt#EncryptParameters + } + + /** + * Generates code samples for using {@link CryptographyAsyncClient#decrypt(EncryptionAlgorithm, byte[])} and + * {@link CryptographyAsyncClient#decrypt(DecryptParameters)}. + */ + public void decrypt() { + CryptographyAsyncClient cryptographyAsyncClient = createAsyncClient(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt#EncryptionAlgorithm-byte + byte[] ciphertext = new byte[100]; + new Random(0x1234567L).nextBytes(ciphertext); + + cryptographyAsyncClient.decrypt(EncryptionAlgorithm.RSA_OAEP, ciphertext) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(decryptResult -> + System.out.printf("Received decrypted content of length: %d%n", decryptResult.getPlainText().length)); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt#EncryptionAlgorithm-byte + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt#DecryptParameters + byte[] ciphertextBytes = new byte[100]; + new Random(0x1234567L).nextBytes(ciphertextBytes); + byte[] iv = { + (byte) 0x1a, (byte) 0xf3, (byte) 0x8c, (byte) 0x2d, (byte) 0xc2, (byte) 0xb9, (byte) 0x6f, (byte) 0xfd, + (byte) 0xd8, (byte) 0x66, (byte) 0x94, (byte) 0x09, (byte) 0x23, (byte) 0x41, (byte) 0xbc, (byte) 0x04 + }; + + DecryptParameters decryptParameters = DecryptParameters.createA128CbcParameters(ciphertextBytes, iv); + + cryptographyAsyncClient.decrypt(decryptParameters) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(decryptResult -> + System.out.printf("Received decrypted content of length: %d.%n", decryptResult.getPlainText().length)); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt#DecryptParameters + } + + /** + * Generates a code sample for using {@link CryptographyAsyncClient#sign(SignatureAlgorithm, byte[])} and + * {@link CryptographyAsyncClient#verify(SignatureAlgorithm, byte[], byte[])}. + * + * @throws NoSuchAlgorithmException when the specified algorithm doesn't exist. + */ + public void signVerify() throws NoSuchAlgorithmException { + CryptographyAsyncClient cryptographyAsyncClient = createAsyncClient(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign#SignatureAlgorithm-byte + byte[] data = new byte[100]; + new Random(0x1234567L).nextBytes(data); + MessageDigest md = MessageDigest.getInstance("SHA-256"); + md.update(data); + byte[] digest = md.digest(); + + cryptographyAsyncClient.sign(SignatureAlgorithm.ES256, digest) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(signResult -> + System.out.printf("Received signature of length: %d, with algorithm: %s.%n", + signResult.getSignature().length, signResult.getAlgorithm())); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign#SignatureAlgorithm-byte + + byte[] signature = new byte[100]; + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify#SignatureAlgorithm-byte-byte + byte[] myData = new byte[100]; + new Random(0x1234567L).nextBytes(myData); + MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); + messageDigest.update(myData); + byte[] myDigest = messageDigest.digest(); + + // A signature can be obtained from the SignResult returned by the CryptographyAsyncClient.sign() operation. + cryptographyAsyncClient.verify(SignatureAlgorithm.ES256, myDigest, signature) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(verifyResult -> + System.out.printf("Verification status: %s.%n", verifyResult.isValid())); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify#SignatureAlgorithm-byte-byte + } + + + /** + * Generates a code sample for using {@link CryptographyAsyncClient#wrapKey(KeyWrapAlgorithm, byte[])} and + * {@link CryptographyAsyncClient#unwrapKey(KeyWrapAlgorithm, byte[])}. + */ + public void wrapKeyUnwrapKey() { + CryptographyAsyncClient cryptographyAsyncClient = createAsyncClient(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey#KeyWrapAlgorithm-byte + byte[] key = new byte[100]; + new Random(0x1234567L).nextBytes(key); + + cryptographyAsyncClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, key) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(wrapResult -> + System.out.printf("Received encrypted key of length: %d, with algorithm: %s.%n", + wrapResult.getEncryptedKey().length, wrapResult.getAlgorithm().toString())); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey#KeyWrapAlgorithm-byte + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey#KeyWrapAlgorithm-byte + byte[] keyToWrap = new byte[100]; + new Random(0x1234567L).nextBytes(key); + + cryptographyAsyncClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, keyToWrap) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(wrapResult -> + cryptographyAsyncClient.unwrapKey(KeyWrapAlgorithm.RSA_OAEP, wrapResult.getEncryptedKey()) + .subscribe(keyUnwrapResult -> + System.out.printf("Received key of length: %d.%n", keyUnwrapResult.getKey().length))); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey#KeyWrapAlgorithm-byte + } + + /** + * Generates a code sample for using {@link CryptographyAsyncClient#signData(SignatureAlgorithm, byte[])} and + * {@link CryptographyAsyncClient#verifyData(SignatureAlgorithm, byte[], byte[])}. + * + * @throws NoSuchAlgorithmException when the specified algorithm doesn't exist. + */ + public void signDataVerifyData() throws NoSuchAlgorithmException { + CryptographyAsyncClient cryptographyAsyncClient = createAsyncClient(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData#SignatureAlgorithm-byte + byte[] data = new byte[100]; + new Random(0x1234567L).nextBytes(data); + + cryptographyAsyncClient.sign(SignatureAlgorithm.ES256, data) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(signResult -> + System.out.printf("Received signature of length: %d, with algorithm: %s.%n", + signResult.getSignature().length, signResult.getAlgorithm())); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData#SignatureAlgorithm-byte + + byte[] signature = new byte[100]; + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData#SignatureAlgorithm-byte-byte + byte[] myData = new byte[100]; + new Random(0x1234567L).nextBytes(myData); + + // A signature can be obtained from the SignResult returned by the CryptographyAsyncClient.sign() operation. + cryptographyAsyncClient.verify(SignatureAlgorithm.ES256, myData, signature) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(verifyResult -> + System.out.printf("Verification status: %s.%n", verifyResult.isValid())); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData#SignatureAlgorithm-byte-byte + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample14/v2/CryptographyAsyncClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample14/v2/CryptographyAsyncClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..3dc44cbd7474 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample14/v2/CryptographyAsyncClientJavaDocCodeSnippets.java @@ -0,0 +1,280 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys.cryptography; + +import com.azure.core.http.HttpClient; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.policy.HttpLogOptions; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.keys.cryptography.models.DecryptParameters; +import com.azure.security.keyvault.keys.cryptography.models.EncryptParameters; +import com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm; +import com.azure.security.keyvault.keys.cryptography.models.KeyWrapAlgorithm; +import com.azure.security.keyvault.keys.cryptography.models.SignatureAlgorithm; +import com.azure.security.keyvault.keys.models.JsonWebKey; +import reactor.util.context.Context; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Random; + +/** + * This class contains code samples for generating javadocs through doclets for {@link CryptographyAsyncClient}. + */ +public final class CryptographyAsyncClientJavaDocCodeSnippets { + /** + * Generates a code sample for creating a {@link CryptographyAsyncClient}. + * + * @return An instance of {@link CryptographyAsyncClient}. + */ + public CryptographyAsyncClient createAsyncClient() { + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.instantiation + CryptographyAsyncClient cryptographyAsyncClient = new CryptographyClientBuilder() + .keyIdentifier("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.instantiation + + return cryptographyAsyncClient; + } + + /** + * Generates a code sample for creating a {@link CryptographyAsyncClient} with a given {@link JsonWebKey}. + * + * @return An instance of {@link CryptographyAsyncClient}. + */ + public CryptographyAsyncClient createAsyncClientWithJsonWebKey() { + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.withJsonWebKey.instantiation + JsonWebKey jsonWebKey = new JsonWebKey().setId("SampleJsonWebKey"); + CryptographyAsyncClient cryptographyAsyncClient = new CryptographyClientBuilder() + .jsonWebKey(jsonWebKey) + .buildAsyncClient(); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.withJsonWebKey.instantiation + + return cryptographyAsyncClient; + } + + /** + * Generates a code sample for creating a {@link CryptographyAsyncClient} with a given {@link HttpClient}. + * + * @return An instance of {@link CryptographyAsyncClient}. + */ + public CryptographyAsyncClient createAsyncClientWithHttpClient() { + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.withHttpClient.instantiation + CryptographyAsyncClient cryptographyAsyncClient = new CryptographyClientBuilder() + .keyIdentifier("") + .credential(new DefaultAzureCredentialBuilder().build()) + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) + .httpClient(HttpClient.createDefault()) + .buildAsyncClient(); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.withHttpClient.instantiation + + return cryptographyAsyncClient; + } + + /** + * Generates a code sample for using {@link CryptographyAsyncClient#getKey()}. + */ + public void getKeySnippets() { + CryptographyAsyncClient cryptographyAsyncClient = createAsyncClient(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKey + cryptographyAsyncClient.getKey() + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(key -> + System.out.printf("Key returned with name: %s, and id: %s.%n", key.getName(), key.getId())); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKey + } + + /** + * Generates a code sample for using {@link CryptographyAsyncClient#getKeyWithResponse()}. + */ + public void getKeyWithResponseSnippets() { + CryptographyAsyncClient cryptographyAsyncClient = createAsyncClient(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKeyWithResponse + cryptographyAsyncClient.getKeyWithResponse() + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(keyResponse -> + System.out.printf("Key returned with name: %s, and id: %s.%n", keyResponse.getValue().getName(), + keyResponse.getValue().getId())); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.getKeyWithResponse + } + + /** + * Generates code samples for using {@link CryptographyAsyncClient#encrypt(EncryptionAlgorithm, byte[])} and + * {@link CryptographyAsyncClient#encrypt(EncryptParameters)}. + */ + public void encrypt() { + CryptographyAsyncClient cryptographyAsyncClient = createAsyncClient(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt#EncryptionAlgorithm-byte + byte[] plaintext = new byte[100]; + new Random(0x1234567L).nextBytes(plaintext); + + cryptographyAsyncClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(encryptResult -> + System.out.printf("Received encrypted content of length: %d, with algorithm: %s.%n", + encryptResult.getCipherText().length, encryptResult.getAlgorithm().toString())); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt#EncryptionAlgorithm-byte + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt#EncryptParameters + byte[] plaintextBytes = new byte[100]; + new Random(0x1234567L).nextBytes(plaintextBytes); + byte[] iv = { + (byte) 0x1a, (byte) 0xf3, (byte) 0x8c, (byte) 0x2d, (byte) 0xc2, (byte) 0xb9, (byte) 0x6f, (byte) 0xfd, + (byte) 0xd8, (byte) 0x66, (byte) 0x94, (byte) 0x09, (byte) 0x23, (byte) 0x41, (byte) 0xbc, (byte) 0x04 + }; + + EncryptParameters encryptParameters = EncryptParameters.createA128CbcParameters(plaintextBytes, iv); + + cryptographyAsyncClient.encrypt(encryptParameters) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(encryptResult -> + System.out.printf("Received encrypted content of length: %d, with algorithm: %s.%n", + encryptResult.getCipherText().length, encryptResult.getAlgorithm().toString())); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.encrypt#EncryptParameters + } + + /** + * Generates code samples for using {@link CryptographyAsyncClient#decrypt(EncryptionAlgorithm, byte[])} and + * {@link CryptographyAsyncClient#decrypt(DecryptParameters)}. + */ + public void decrypt() { + CryptographyAsyncClient cryptographyAsyncClient = createAsyncClient(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt#EncryptionAlgorithm-byte + byte[] ciphertext = new byte[100]; + new Random(0x1234567L).nextBytes(ciphertext); + + cryptographyAsyncClient.decrypt(EncryptionAlgorithm.RSA_OAEP, ciphertext) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(decryptResult -> + System.out.printf("Received decrypted content of length: %d%n", decryptResult.getPlainText().length)); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt#EncryptionAlgorithm-byte + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt#DecryptParameters + byte[] ciphertextBytes = new byte[100]; + new Random(0x1234567L).nextBytes(ciphertextBytes); + byte[] iv = { + (byte) 0x1a, (byte) 0xf3, (byte) 0x8c, (byte) 0x2d, (byte) 0xc2, (byte) 0xb9, (byte) 0x6f, (byte) 0xfd, + (byte) 0xd8, (byte) 0x66, (byte) 0x94, (byte) 0x09, (byte) 0x23, (byte) 0x41, (byte) 0xbc, (byte) 0x04 + }; + + DecryptParameters decryptParameters = DecryptParameters.createA128CbcParameters(ciphertextBytes, iv); + + cryptographyAsyncClient.decrypt(decryptParameters) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(decryptResult -> + System.out.printf("Received decrypted content of length: %d.%n", decryptResult.getPlainText().length)); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.decrypt#DecryptParameters + } + + /** + * Generates a code sample for using {@link CryptographyAsyncClient#sign(SignatureAlgorithm, byte[])} and + * {@link CryptographyAsyncClient#verify(SignatureAlgorithm, byte[], byte[])}. + * + * @throws NoSuchAlgorithmException when the specified algorithm doesn't exist. + */ + public void signVerify() throws NoSuchAlgorithmException { + CryptographyAsyncClient cryptographyAsyncClient = createAsyncClient(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign#SignatureAlgorithm-byte + byte[] data = new byte[100]; + new Random(0x1234567L).nextBytes(data); + MessageDigest md = MessageDigest.getInstance("SHA-256"); + md.update(data); + byte[] digest = md.digest(); + + cryptographyAsyncClient.sign(SignatureAlgorithm.ES256, digest) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(signResult -> + System.out.printf("Received signature of length: %d, with algorithm: %s.%n", + signResult.getSignature().length, signResult.getAlgorithm())); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.sign#SignatureAlgorithm-byte + + byte[] signature = new byte[100]; + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify#SignatureAlgorithm-byte-byte + byte[] myData = new byte[100]; + new Random(0x1234567L).nextBytes(myData); + MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); + messageDigest.update(myData); + byte[] myDigest = messageDigest.digest(); + + // A signature can be obtained from the SignResult returned by the CryptographyAsyncClient.sign() operation. + cryptographyAsyncClient.verify(SignatureAlgorithm.ES256, myDigest, signature) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(verifyResult -> + System.out.printf("Verification status: %s.%n", verifyResult.isValid())); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verify#SignatureAlgorithm-byte-byte + } + + + /** + * Generates a code sample for using {@link CryptographyAsyncClient#wrapKey(KeyWrapAlgorithm, byte[])} and + * {@link CryptographyAsyncClient#unwrapKey(KeyWrapAlgorithm, byte[])}. + */ + public void wrapKeyUnwrapKey() { + CryptographyAsyncClient cryptographyAsyncClient = createAsyncClient(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey#KeyWrapAlgorithm-byte + byte[] key = new byte[100]; + new Random(0x1234567L).nextBytes(key); + + cryptographyAsyncClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, key) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(wrapResult -> + System.out.printf("Received encrypted key of length: %d, with algorithm: %s.%n", + wrapResult.getEncryptedKey().length, wrapResult.getAlgorithm().toString())); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.wrapKey#KeyWrapAlgorithm-byte + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey#KeyWrapAlgorithm-byte + byte[] keyToWrap = new byte[100]; + new Random(0x1234567L).nextBytes(key); + + cryptographyAsyncClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, keyToWrap) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(wrapResult -> + cryptographyAsyncClient.unwrapKey(KeyWrapAlgorithm.RSA_OAEP, wrapResult.getEncryptedKey()) + .subscribe(keyUnwrapResult -> + System.out.printf("Received key of length: %d.%n", keyUnwrapResult.getKey().length))); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.unwrapKey#KeyWrapAlgorithm-byte + } + + /** + * Generates a code sample for using {@link CryptographyAsyncClient#signData(SignatureAlgorithm, byte[])} and + * {@link CryptographyAsyncClient#verifyData(SignatureAlgorithm, byte[], byte[])}. + * + * @throws NoSuchAlgorithmException when the specified algorithm doesn't exist. + */ + public void signDataVerifyData() throws NoSuchAlgorithmException { + CryptographyAsyncClient cryptographyAsyncClient = createAsyncClient(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData#SignatureAlgorithm-byte + byte[] data = new byte[100]; + new Random(0x1234567L).nextBytes(data); + + cryptographyAsyncClient.sign(SignatureAlgorithm.ES256, data) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(signResult -> + System.out.printf("Received signature of length: %d, with algorithm: %s.%n", + signResult.getSignature().length, signResult.getAlgorithm())); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.signData#SignatureAlgorithm-byte + + byte[] signature = new byte[100]; + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData#SignatureAlgorithm-byte-byte + byte[] myData = new byte[100]; + new Random(0x1234567L).nextBytes(myData); + + // A signature can be obtained from the SignResult returned by the CryptographyAsyncClient.sign() operation. + cryptographyAsyncClient.verify(SignatureAlgorithm.ES256, myData, signature) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(verifyResult -> + System.out.printf("Verification status: %s.%n", verifyResult.isValid())); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyAsyncClient.verifyData#SignatureAlgorithm-byte-byte + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample15/v1/CryptographyClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample15/v1/CryptographyClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..22db104a87e9 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample15/v1/CryptographyClientJavaDocCodeSnippets.java @@ -0,0 +1,355 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys.cryptography; + +import com.azure.core.util.Context; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.keys.KeyClient; +import com.azure.security.keyvault.keys.cryptography.models.DecryptParameters; +import com.azure.security.keyvault.keys.cryptography.models.DecryptResult; +import com.azure.security.keyvault.keys.cryptography.models.EncryptParameters; +import com.azure.security.keyvault.keys.cryptography.models.EncryptResult; +import com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm; +import com.azure.security.keyvault.keys.cryptography.models.KeyWrapAlgorithm; +import com.azure.security.keyvault.keys.cryptography.models.SignResult; +import com.azure.security.keyvault.keys.cryptography.models.SignatureAlgorithm; +import com.azure.security.keyvault.keys.cryptography.models.UnwrapResult; +import com.azure.security.keyvault.keys.cryptography.models.VerifyResult; +import com.azure.security.keyvault.keys.cryptography.models.WrapResult; +import com.azure.security.keyvault.keys.models.JsonWebKey; +import com.azure.security.keyvault.keys.models.KeyVaultKey; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Random; + +/** + * This class contains code samples for generating javadocs through doclets for {@link KeyClient}. + */ +public final class CryptographyClientJavaDocCodeSnippets { + /** + * Generates a code sample for creating a {@link CryptographyClient}. + * + * @return An instance of {@link CryptographyClient}. + */ + public CryptographyClient createClient() { + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.instantiation + CryptographyClient cryptographyClient = new CryptographyClientBuilder() + .keyIdentifier("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.instantiation + + return cryptographyClient; + } + + /** + * Generates a code sample for creating a {@link CryptographyClient} with a given {@link JsonWebKey}. + * + * @return An instance of {@link CryptographyClient}. + */ + public CryptographyClient createClientWithJsonWebKey() { + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.withJsonWebKey.instantiation + JsonWebKey jsonWebKey = new JsonWebKey().setId("SampleJsonWebKey"); + CryptographyClient cryptographyClient = new CryptographyClientBuilder() + .jsonWebKey(jsonWebKey) + .buildClient(); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.withJsonWebKey.instantiation + + return cryptographyClient; + } + + /** + * Generates a code sample for using {@link CryptographyClient#getKey()}. + */ + public void getKeySnippets() { + CryptographyClient cryptographyClient = createClient(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.getKey + KeyVaultKey key = cryptographyClient.getKey(); + + System.out.printf("Key returned with name: %s and id: %s.%n", key.getName(), key.getId()); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.getKey + } + + /** + * Generates a code sample for using {@link CryptographyClient#getKeyWithResponse(Context)}. + */ + public void getKeyWithResponseSnippets() { + CryptographyClient cryptographyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.getKeyWithResponse#Context + KeyVaultKey keyWithVersion = cryptographyClient.getKeyWithResponse(new Context("key1", "value1")).getValue(); + + System.out.printf("Key is returned with name: %s and id %s.%n", keyWithVersion.getName(), + keyWithVersion.getId()); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.getKeyWithResponse#Context + } + + /** + * Generates a code sample for using {@link CryptographyClient#encrypt(EncryptionAlgorithm, byte[])}, + * {@link CryptographyClient#encrypt(EncryptionAlgorithm, byte[], Context)} and + * {@link CryptographyClient#encrypt(EncryptParameters, Context)}. + */ + public void encrypt() { + CryptographyClient cryptographyClient = createClient(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.encrypt#EncryptionAlgorithm-byte + byte[] plaintext = new byte[100]; + new Random(0x1234567L).nextBytes(plaintext); + + EncryptResult encryptResult = cryptographyClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext); + + System.out.printf("Received encrypted content of length: %d, with algorithm: %s.%n", + encryptResult.getCipherText().length, encryptResult.getAlgorithm()); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.encrypt#EncryptionAlgorithm-byte + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.encrypt#EncryptionAlgorithm-byte-Context + byte[] plaintextToEncrypt = new byte[100]; + new Random(0x1234567L).nextBytes(plaintextToEncrypt); + + EncryptResult encryptionResult = cryptographyClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintextToEncrypt, + new Context("key1", "value1")); + + System.out.printf("Received encrypted content of length: %d, with algorithm: %s.%n", + encryptionResult.getCipherText().length, encryptionResult.getAlgorithm()); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.encrypt#EncryptionAlgorithm-byte-Context + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.encrypt#EncryptParameters-Context + byte[] myPlaintext = new byte[100]; + new Random(0x1234567L).nextBytes(myPlaintext); + byte[] iv = { + (byte) 0x1a, (byte) 0xf3, (byte) 0x8c, (byte) 0x2d, (byte) 0xc2, (byte) 0xb9, (byte) 0x6f, (byte) 0xfd, + (byte) 0xd8, (byte) 0x66, (byte) 0x94, (byte) 0x09, (byte) 0x23, (byte) 0x41, (byte) 0xbc, (byte) 0x04 + }; + + EncryptParameters encryptParameters = EncryptParameters.createA128CbcParameters(myPlaintext, iv); + EncryptResult encryptedResult = cryptographyClient.encrypt(encryptParameters, new Context("key1", "value1")); + + System.out.printf("Received encrypted content of length: %d, with algorithm: %s.%n", + encryptedResult.getCipherText().length, encryptedResult.getAlgorithm()); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.encrypt#EncryptParameters-Context + } + + /** + * Generates a code sample for using {@link CryptographyClient#decrypt(EncryptionAlgorithm, byte[])}, + * {@link CryptographyClient#decrypt(EncryptionAlgorithm, byte[], Context)} and + * {@link CryptographyClient#decrypt(DecryptParameters, Context)}. + */ + public void decrypt() { + CryptographyClient cryptographyClient = createClient(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.decrypt#EncryptionAlgorithm-byte + byte[] ciphertext = new byte[100]; + new Random(0x1234567L).nextBytes(ciphertext); + + DecryptResult decryptResult = cryptographyClient.decrypt(EncryptionAlgorithm.RSA_OAEP, ciphertext); + + System.out.printf("Received decrypted content of length: %d.%n", decryptResult.getPlainText().length); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.decrypt#EncryptionAlgorithm-byte + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.decrypt#EncryptionAlgorithm-byte-Context + byte[] ciphertextToDecrypt = new byte[100]; + new Random(0x1234567L).nextBytes(ciphertextToDecrypt); + + DecryptResult decryptionResult = cryptographyClient.decrypt(EncryptionAlgorithm.RSA_OAEP, ciphertextToDecrypt, + new Context("key1", "value1")); + + System.out.printf("Received decrypted content of length: %d.%n", decryptionResult.getPlainText().length); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.decrypt#EncryptionAlgorithm-byte-Context + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.decrypt#DecryptParameters-Context + byte[] myCiphertext = new byte[100]; + new Random(0x1234567L).nextBytes(myCiphertext); + byte[] iv = { + (byte) 0x1a, (byte) 0xf3, (byte) 0x8c, (byte) 0x2d, (byte) 0xc2, (byte) 0xb9, (byte) 0x6f, (byte) 0xfd, + (byte) 0xd8, (byte) 0x66, (byte) 0x94, (byte) 0x09, (byte) 0x23, (byte) 0x41, (byte) 0xbc, (byte) 0x04 + }; + + DecryptParameters decryptParameters = DecryptParameters.createA128CbcParameters(myCiphertext, iv); + DecryptResult decryptedResult = cryptographyClient.decrypt(decryptParameters, new Context("key1", "value1")); + + System.out.printf("Received decrypted content of length: %d.%n", decryptedResult.getPlainText().length); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.decrypt#DecryptParameters-Context + } + + /** + * Generates a code sample for using {@link CryptographyClient#sign(SignatureAlgorithm, byte[])} and + * {@link CryptographyClient#verify(SignatureAlgorithm, byte[], byte[])}. + * + * @throws NoSuchAlgorithmException when the specified algorithm doesn't exist. + */ + public void signVerify() throws NoSuchAlgorithmException { + CryptographyClient cryptographyClient = createClient(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.sign#SignatureAlgorithm-byte + byte[] data = new byte[100]; + new Random(0x1234567L).nextBytes(data); + MessageDigest md = MessageDigest.getInstance("SHA-256"); + md.update(data); + byte[] digest = md.digest(); + + SignResult signResult = cryptographyClient.sign(SignatureAlgorithm.ES256, digest); + + System.out.printf("Received signature of length: %d, with algorithm: %s.%n", signResult.getSignature().length, + signResult.getAlgorithm()); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.sign#SignatureAlgorithm-byte + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.sign#SignatureAlgorithm-byte-Context + byte[] dataToVerify = new byte[100]; + new Random(0x1234567L).nextBytes(dataToVerify); + MessageDigest myMessageDigest = MessageDigest.getInstance("SHA-256"); + myMessageDigest.update(dataToVerify); + byte[] digestContent = myMessageDigest.digest(); + + SignResult signResponse = cryptographyClient.sign(SignatureAlgorithm.ES256, digestContent, + new Context("key1", "value1")); + + System.out.printf("Received signature of length: %d, with algorithm: %s.%n", signResponse.getSignature().length, + signResponse.getAlgorithm()); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.sign#SignatureAlgorithm-byte-Context + + byte[] signature = signResult.getSignature(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.verify#SignatureAlgorithm-byte-byte + byte[] myData = new byte[100]; + new Random(0x1234567L).nextBytes(myData); + MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); + messageDigest.update(myData); + byte[] myDigest = messageDigest.digest(); + + // A signature can be obtained from the SignResult returned by the CryptographyClient.sign() operation. + VerifyResult verifyResult = cryptographyClient.verify(SignatureAlgorithm.ES256, myDigest, signature); + + System.out.printf("Verification status: %s.%n", verifyResult.isValid()); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.verify#SignatureAlgorithm-byte-byte + + byte[] signatureBytes = signResponse.getSignature(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.verify#SignatureAlgorithm-byte-byte-Context + byte[] dataBytes = new byte[100]; + new Random(0x1234567L).nextBytes(dataBytes); + MessageDigest msgDigest = MessageDigest.getInstance("SHA-256"); + msgDigest.update(dataBytes); + byte[] digestBytes = msgDigest.digest(); + + // A signature can be obtained from the SignResult returned by the CryptographyClient.sign() operation. + VerifyResult verifyResponse = cryptographyClient.verify(SignatureAlgorithm.ES256, digestBytes, signatureBytes, + new Context("key1", "value1")); + + System.out.printf("Verification status: %s.%n", verifyResponse.isValid()); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.verify#SignatureAlgorithm-byte-byte-Context + } + + + /** + * Generates a code sample for using {@link CryptographyClient#wrapKey(KeyWrapAlgorithm, byte[])}, + * {@link CryptographyClient#wrapKey(KeyWrapAlgorithm, byte[], Context)}, + * {@link CryptographyClient#unwrapKey(KeyWrapAlgorithm, byte[])} and + * {@link CryptographyClient#unwrapKey(KeyWrapAlgorithm, byte[], Context)}. + */ + public void wrapKeyUnwrapKey() { + CryptographyClient cryptographyClient = createClient(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.wrapKey#KeyWrapAlgorithm-byte + byte[] key = new byte[100]; + new Random(0x1234567L).nextBytes(key); + + WrapResult wrapResult = cryptographyClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, key); + + System.out.printf("Received encrypted key of length: %d, with algorithm: %s.%n", + wrapResult.getEncryptedKey().length, wrapResult.getAlgorithm()); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.wrapKey#KeyWrapAlgorithm-byte + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.wrapKey#KeyWrapAlgorithm-byte-Context + byte[] keyToWrap = new byte[100]; + new Random(0x1234567L).nextBytes(keyToWrap); + + WrapResult keyWrapResult = cryptographyClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, keyToWrap, + new Context("key1", "value1")); + + System.out.printf("Received encrypted key of length: %d, with algorithm: %s.%n", + keyWrapResult.getEncryptedKey().length, keyWrapResult.getAlgorithm()); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.wrapKey#KeyWrapAlgorithm-byte-Context + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.unwrapKey#KeyWrapAlgorithm-byte + byte[] keyContent = new byte[100]; + new Random(0x1234567L).nextBytes(keyContent); + + WrapResult wrapKeyResult = cryptographyClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, keyContent, + new Context("key1", "value1")); + UnwrapResult unwrapResult = cryptographyClient.unwrapKey(KeyWrapAlgorithm.RSA_OAEP, + wrapKeyResult.getEncryptedKey()); + + System.out.printf("Received key of length %d", unwrapResult.getKey().length); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.unwrapKey#KeyWrapAlgorithm-byte + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.unwrapKey#KeyWrapAlgorithm-byte-Context + byte[] keyContentToWrap = new byte[100]; + new Random(0x1234567L).nextBytes(keyContentToWrap); + Context context = new Context("key1", "value1"); + + WrapResult wrapKeyContentResult = + cryptographyClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, keyContentToWrap, context); + UnwrapResult unwrapKeyResponse = + cryptographyClient.unwrapKey(KeyWrapAlgorithm.RSA_OAEP, wrapKeyContentResult.getEncryptedKey(), context); + + System.out.printf("Received key of length %d", unwrapKeyResponse.getKey().length); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.unwrapKey#KeyWrapAlgorithm-byte-Context + } + + /** + * Generates a code sample for using {@link CryptographyClient#signData(SignatureAlgorithm, byte[])} and + * {@link CryptographyClient#verifyData(SignatureAlgorithm, byte[], byte[])}. + * + * @throws NoSuchAlgorithmException when the specified algorithm doesn't exist. + */ + public void signDataVerifyData() throws NoSuchAlgorithmException { + CryptographyClient cryptographyClient = createClient(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.signData#SignatureAlgorithm-byte + byte[] data = new byte[32]; + new Random(0x1234567L).nextBytes(data); + + SignResult signResult = cryptographyClient.sign(SignatureAlgorithm.ES256, data); + + System.out.printf("Received signature of length: %d, with algorithm: %s.%n", signResult.getSignature().length, + signResult.getAlgorithm()); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.signData#SignatureAlgorithm-byte + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.signData#SignatureAlgorithm-byte-Context + byte[] plainTextData = new byte[32]; + new Random(0x1234567L).nextBytes(plainTextData); + + SignResult signingResult = cryptographyClient.sign(SignatureAlgorithm.ES256, plainTextData); + + System.out.printf("Received signature of length: %d, with algorithm: %s.%n", + signingResult.getSignature().length, new Context("key1", "value1")); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.signData#SignatureAlgorithm-byte-Context + + byte[] signature = signResult.getSignature(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.verifyData#SignatureAlgorithm-byte-byte + byte[] myData = new byte[32]; + new Random(0x1234567L).nextBytes(myData); + + // A signature can be obtained from the SignResult returned by the CryptographyClient.sign() operation. + VerifyResult verifyResult = cryptographyClient.verify(SignatureAlgorithm.ES256, myData, signature); + + System.out.printf("Verification status: %s.%n", verifyResult.isValid()); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.verifyData#SignatureAlgorithm-byte-byte + + byte[] mySignature = signingResult.getSignature(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.verifyData#SignatureAlgorithm-byte-byte-Context + byte[] dataToVerify = new byte[32]; + new Random(0x1234567L).nextBytes(dataToVerify); + + // A signature can be obtained from the SignResult returned by the CryptographyClient.sign() operation. + VerifyResult verificationResult = cryptographyClient.verify(SignatureAlgorithm.ES256, dataToVerify, + mySignature, new Context("key1", "value1")); + + System.out.printf("Verification status: %s.%n", verificationResult.isValid()); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.verifyData#SignatureAlgorithm-byte-byte-Context + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample15/v2/CryptographyClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample15/v2/CryptographyClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..22db104a87e9 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample15/v2/CryptographyClientJavaDocCodeSnippets.java @@ -0,0 +1,355 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys.cryptography; + +import com.azure.core.util.Context; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.keys.KeyClient; +import com.azure.security.keyvault.keys.cryptography.models.DecryptParameters; +import com.azure.security.keyvault.keys.cryptography.models.DecryptResult; +import com.azure.security.keyvault.keys.cryptography.models.EncryptParameters; +import com.azure.security.keyvault.keys.cryptography.models.EncryptResult; +import com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm; +import com.azure.security.keyvault.keys.cryptography.models.KeyWrapAlgorithm; +import com.azure.security.keyvault.keys.cryptography.models.SignResult; +import com.azure.security.keyvault.keys.cryptography.models.SignatureAlgorithm; +import com.azure.security.keyvault.keys.cryptography.models.UnwrapResult; +import com.azure.security.keyvault.keys.cryptography.models.VerifyResult; +import com.azure.security.keyvault.keys.cryptography.models.WrapResult; +import com.azure.security.keyvault.keys.models.JsonWebKey; +import com.azure.security.keyvault.keys.models.KeyVaultKey; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Random; + +/** + * This class contains code samples for generating javadocs through doclets for {@link KeyClient}. + */ +public final class CryptographyClientJavaDocCodeSnippets { + /** + * Generates a code sample for creating a {@link CryptographyClient}. + * + * @return An instance of {@link CryptographyClient}. + */ + public CryptographyClient createClient() { + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.instantiation + CryptographyClient cryptographyClient = new CryptographyClientBuilder() + .keyIdentifier("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.instantiation + + return cryptographyClient; + } + + /** + * Generates a code sample for creating a {@link CryptographyClient} with a given {@link JsonWebKey}. + * + * @return An instance of {@link CryptographyClient}. + */ + public CryptographyClient createClientWithJsonWebKey() { + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.withJsonWebKey.instantiation + JsonWebKey jsonWebKey = new JsonWebKey().setId("SampleJsonWebKey"); + CryptographyClient cryptographyClient = new CryptographyClientBuilder() + .jsonWebKey(jsonWebKey) + .buildClient(); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.withJsonWebKey.instantiation + + return cryptographyClient; + } + + /** + * Generates a code sample for using {@link CryptographyClient#getKey()}. + */ + public void getKeySnippets() { + CryptographyClient cryptographyClient = createClient(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.getKey + KeyVaultKey key = cryptographyClient.getKey(); + + System.out.printf("Key returned with name: %s and id: %s.%n", key.getName(), key.getId()); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.getKey + } + + /** + * Generates a code sample for using {@link CryptographyClient#getKeyWithResponse(Context)}. + */ + public void getKeyWithResponseSnippets() { + CryptographyClient cryptographyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.getKeyWithResponse#Context + KeyVaultKey keyWithVersion = cryptographyClient.getKeyWithResponse(new Context("key1", "value1")).getValue(); + + System.out.printf("Key is returned with name: %s and id %s.%n", keyWithVersion.getName(), + keyWithVersion.getId()); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.getKeyWithResponse#Context + } + + /** + * Generates a code sample for using {@link CryptographyClient#encrypt(EncryptionAlgorithm, byte[])}, + * {@link CryptographyClient#encrypt(EncryptionAlgorithm, byte[], Context)} and + * {@link CryptographyClient#encrypt(EncryptParameters, Context)}. + */ + public void encrypt() { + CryptographyClient cryptographyClient = createClient(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.encrypt#EncryptionAlgorithm-byte + byte[] plaintext = new byte[100]; + new Random(0x1234567L).nextBytes(plaintext); + + EncryptResult encryptResult = cryptographyClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext); + + System.out.printf("Received encrypted content of length: %d, with algorithm: %s.%n", + encryptResult.getCipherText().length, encryptResult.getAlgorithm()); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.encrypt#EncryptionAlgorithm-byte + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.encrypt#EncryptionAlgorithm-byte-Context + byte[] plaintextToEncrypt = new byte[100]; + new Random(0x1234567L).nextBytes(plaintextToEncrypt); + + EncryptResult encryptionResult = cryptographyClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintextToEncrypt, + new Context("key1", "value1")); + + System.out.printf("Received encrypted content of length: %d, with algorithm: %s.%n", + encryptionResult.getCipherText().length, encryptionResult.getAlgorithm()); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.encrypt#EncryptionAlgorithm-byte-Context + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.encrypt#EncryptParameters-Context + byte[] myPlaintext = new byte[100]; + new Random(0x1234567L).nextBytes(myPlaintext); + byte[] iv = { + (byte) 0x1a, (byte) 0xf3, (byte) 0x8c, (byte) 0x2d, (byte) 0xc2, (byte) 0xb9, (byte) 0x6f, (byte) 0xfd, + (byte) 0xd8, (byte) 0x66, (byte) 0x94, (byte) 0x09, (byte) 0x23, (byte) 0x41, (byte) 0xbc, (byte) 0x04 + }; + + EncryptParameters encryptParameters = EncryptParameters.createA128CbcParameters(myPlaintext, iv); + EncryptResult encryptedResult = cryptographyClient.encrypt(encryptParameters, new Context("key1", "value1")); + + System.out.printf("Received encrypted content of length: %d, with algorithm: %s.%n", + encryptedResult.getCipherText().length, encryptedResult.getAlgorithm()); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.encrypt#EncryptParameters-Context + } + + /** + * Generates a code sample for using {@link CryptographyClient#decrypt(EncryptionAlgorithm, byte[])}, + * {@link CryptographyClient#decrypt(EncryptionAlgorithm, byte[], Context)} and + * {@link CryptographyClient#decrypt(DecryptParameters, Context)}. + */ + public void decrypt() { + CryptographyClient cryptographyClient = createClient(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.decrypt#EncryptionAlgorithm-byte + byte[] ciphertext = new byte[100]; + new Random(0x1234567L).nextBytes(ciphertext); + + DecryptResult decryptResult = cryptographyClient.decrypt(EncryptionAlgorithm.RSA_OAEP, ciphertext); + + System.out.printf("Received decrypted content of length: %d.%n", decryptResult.getPlainText().length); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.decrypt#EncryptionAlgorithm-byte + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.decrypt#EncryptionAlgorithm-byte-Context + byte[] ciphertextToDecrypt = new byte[100]; + new Random(0x1234567L).nextBytes(ciphertextToDecrypt); + + DecryptResult decryptionResult = cryptographyClient.decrypt(EncryptionAlgorithm.RSA_OAEP, ciphertextToDecrypt, + new Context("key1", "value1")); + + System.out.printf("Received decrypted content of length: %d.%n", decryptionResult.getPlainText().length); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.decrypt#EncryptionAlgorithm-byte-Context + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.decrypt#DecryptParameters-Context + byte[] myCiphertext = new byte[100]; + new Random(0x1234567L).nextBytes(myCiphertext); + byte[] iv = { + (byte) 0x1a, (byte) 0xf3, (byte) 0x8c, (byte) 0x2d, (byte) 0xc2, (byte) 0xb9, (byte) 0x6f, (byte) 0xfd, + (byte) 0xd8, (byte) 0x66, (byte) 0x94, (byte) 0x09, (byte) 0x23, (byte) 0x41, (byte) 0xbc, (byte) 0x04 + }; + + DecryptParameters decryptParameters = DecryptParameters.createA128CbcParameters(myCiphertext, iv); + DecryptResult decryptedResult = cryptographyClient.decrypt(decryptParameters, new Context("key1", "value1")); + + System.out.printf("Received decrypted content of length: %d.%n", decryptedResult.getPlainText().length); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.decrypt#DecryptParameters-Context + } + + /** + * Generates a code sample for using {@link CryptographyClient#sign(SignatureAlgorithm, byte[])} and + * {@link CryptographyClient#verify(SignatureAlgorithm, byte[], byte[])}. + * + * @throws NoSuchAlgorithmException when the specified algorithm doesn't exist. + */ + public void signVerify() throws NoSuchAlgorithmException { + CryptographyClient cryptographyClient = createClient(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.sign#SignatureAlgorithm-byte + byte[] data = new byte[100]; + new Random(0x1234567L).nextBytes(data); + MessageDigest md = MessageDigest.getInstance("SHA-256"); + md.update(data); + byte[] digest = md.digest(); + + SignResult signResult = cryptographyClient.sign(SignatureAlgorithm.ES256, digest); + + System.out.printf("Received signature of length: %d, with algorithm: %s.%n", signResult.getSignature().length, + signResult.getAlgorithm()); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.sign#SignatureAlgorithm-byte + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.sign#SignatureAlgorithm-byte-Context + byte[] dataToVerify = new byte[100]; + new Random(0x1234567L).nextBytes(dataToVerify); + MessageDigest myMessageDigest = MessageDigest.getInstance("SHA-256"); + myMessageDigest.update(dataToVerify); + byte[] digestContent = myMessageDigest.digest(); + + SignResult signResponse = cryptographyClient.sign(SignatureAlgorithm.ES256, digestContent, + new Context("key1", "value1")); + + System.out.printf("Received signature of length: %d, with algorithm: %s.%n", signResponse.getSignature().length, + signResponse.getAlgorithm()); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.sign#SignatureAlgorithm-byte-Context + + byte[] signature = signResult.getSignature(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.verify#SignatureAlgorithm-byte-byte + byte[] myData = new byte[100]; + new Random(0x1234567L).nextBytes(myData); + MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); + messageDigest.update(myData); + byte[] myDigest = messageDigest.digest(); + + // A signature can be obtained from the SignResult returned by the CryptographyClient.sign() operation. + VerifyResult verifyResult = cryptographyClient.verify(SignatureAlgorithm.ES256, myDigest, signature); + + System.out.printf("Verification status: %s.%n", verifyResult.isValid()); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.verify#SignatureAlgorithm-byte-byte + + byte[] signatureBytes = signResponse.getSignature(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.verify#SignatureAlgorithm-byte-byte-Context + byte[] dataBytes = new byte[100]; + new Random(0x1234567L).nextBytes(dataBytes); + MessageDigest msgDigest = MessageDigest.getInstance("SHA-256"); + msgDigest.update(dataBytes); + byte[] digestBytes = msgDigest.digest(); + + // A signature can be obtained from the SignResult returned by the CryptographyClient.sign() operation. + VerifyResult verifyResponse = cryptographyClient.verify(SignatureAlgorithm.ES256, digestBytes, signatureBytes, + new Context("key1", "value1")); + + System.out.printf("Verification status: %s.%n", verifyResponse.isValid()); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.verify#SignatureAlgorithm-byte-byte-Context + } + + + /** + * Generates a code sample for using {@link CryptographyClient#wrapKey(KeyWrapAlgorithm, byte[])}, + * {@link CryptographyClient#wrapKey(KeyWrapAlgorithm, byte[], Context)}, + * {@link CryptographyClient#unwrapKey(KeyWrapAlgorithm, byte[])} and + * {@link CryptographyClient#unwrapKey(KeyWrapAlgorithm, byte[], Context)}. + */ + public void wrapKeyUnwrapKey() { + CryptographyClient cryptographyClient = createClient(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.wrapKey#KeyWrapAlgorithm-byte + byte[] key = new byte[100]; + new Random(0x1234567L).nextBytes(key); + + WrapResult wrapResult = cryptographyClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, key); + + System.out.printf("Received encrypted key of length: %d, with algorithm: %s.%n", + wrapResult.getEncryptedKey().length, wrapResult.getAlgorithm()); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.wrapKey#KeyWrapAlgorithm-byte + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.wrapKey#KeyWrapAlgorithm-byte-Context + byte[] keyToWrap = new byte[100]; + new Random(0x1234567L).nextBytes(keyToWrap); + + WrapResult keyWrapResult = cryptographyClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, keyToWrap, + new Context("key1", "value1")); + + System.out.printf("Received encrypted key of length: %d, with algorithm: %s.%n", + keyWrapResult.getEncryptedKey().length, keyWrapResult.getAlgorithm()); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.wrapKey#KeyWrapAlgorithm-byte-Context + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.unwrapKey#KeyWrapAlgorithm-byte + byte[] keyContent = new byte[100]; + new Random(0x1234567L).nextBytes(keyContent); + + WrapResult wrapKeyResult = cryptographyClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, keyContent, + new Context("key1", "value1")); + UnwrapResult unwrapResult = cryptographyClient.unwrapKey(KeyWrapAlgorithm.RSA_OAEP, + wrapKeyResult.getEncryptedKey()); + + System.out.printf("Received key of length %d", unwrapResult.getKey().length); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.unwrapKey#KeyWrapAlgorithm-byte + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.unwrapKey#KeyWrapAlgorithm-byte-Context + byte[] keyContentToWrap = new byte[100]; + new Random(0x1234567L).nextBytes(keyContentToWrap); + Context context = new Context("key1", "value1"); + + WrapResult wrapKeyContentResult = + cryptographyClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, keyContentToWrap, context); + UnwrapResult unwrapKeyResponse = + cryptographyClient.unwrapKey(KeyWrapAlgorithm.RSA_OAEP, wrapKeyContentResult.getEncryptedKey(), context); + + System.out.printf("Received key of length %d", unwrapKeyResponse.getKey().length); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.unwrapKey#KeyWrapAlgorithm-byte-Context + } + + /** + * Generates a code sample for using {@link CryptographyClient#signData(SignatureAlgorithm, byte[])} and + * {@link CryptographyClient#verifyData(SignatureAlgorithm, byte[], byte[])}. + * + * @throws NoSuchAlgorithmException when the specified algorithm doesn't exist. + */ + public void signDataVerifyData() throws NoSuchAlgorithmException { + CryptographyClient cryptographyClient = createClient(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.signData#SignatureAlgorithm-byte + byte[] data = new byte[32]; + new Random(0x1234567L).nextBytes(data); + + SignResult signResult = cryptographyClient.sign(SignatureAlgorithm.ES256, data); + + System.out.printf("Received signature of length: %d, with algorithm: %s.%n", signResult.getSignature().length, + signResult.getAlgorithm()); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.signData#SignatureAlgorithm-byte + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.signData#SignatureAlgorithm-byte-Context + byte[] plainTextData = new byte[32]; + new Random(0x1234567L).nextBytes(plainTextData); + + SignResult signingResult = cryptographyClient.sign(SignatureAlgorithm.ES256, plainTextData); + + System.out.printf("Received signature of length: %d, with algorithm: %s.%n", + signingResult.getSignature().length, new Context("key1", "value1")); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.signData#SignatureAlgorithm-byte-Context + + byte[] signature = signResult.getSignature(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.verifyData#SignatureAlgorithm-byte-byte + byte[] myData = new byte[32]; + new Random(0x1234567L).nextBytes(myData); + + // A signature can be obtained from the SignResult returned by the CryptographyClient.sign() operation. + VerifyResult verifyResult = cryptographyClient.verify(SignatureAlgorithm.ES256, myData, signature); + + System.out.printf("Verification status: %s.%n", verifyResult.isValid()); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.verifyData#SignatureAlgorithm-byte-byte + + byte[] mySignature = signingResult.getSignature(); + + // BEGIN: com.azure.security.keyvault.keys.cryptography.CryptographyClient.verifyData#SignatureAlgorithm-byte-byte-Context + byte[] dataToVerify = new byte[32]; + new Random(0x1234567L).nextBytes(dataToVerify); + + // A signature can be obtained from the SignResult returned by the CryptographyClient.sign() operation. + VerifyResult verificationResult = cryptographyClient.verify(SignatureAlgorithm.ES256, dataToVerify, + mySignature, new Context("key1", "value1")); + + System.out.printf("Verification status: %s.%n", verificationResult.isValid()); + // END: com.azure.security.keyvault.keys.cryptography.CryptographyClient.verifyData#SignatureAlgorithm-byte-byte-Context + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample16/v1/EncryptDecryptOperations.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample16/v1/EncryptDecryptOperations.java new file mode 100644 index 000000000000..6fea13cd83a5 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample16/v1/EncryptDecryptOperations.java @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys.cryptography; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm; +import com.azure.security.keyvault.keys.cryptography.models.EncryptResult; +import com.azure.security.keyvault.keys.cryptography.models.DecryptResult; + +import java.util.Random; + +/** + * Sample demonstrates how to set, get, update and delete a key. + */ +public class EncryptDecryptOperations { + /** + * Authenticates with the key vault and shows how to set, get, update and delete a key in the key vault. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws InterruptedException, IllegalArgumentException { + /* Instantiate a CryptographyClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a key identifier for a key stored in a key vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) + for links and instructions. */ + CryptographyClient cryptoClient = new CryptographyClientBuilder() + .credential(new DefaultAzureCredentialBuilder().build()) + .keyIdentifier("") + .buildAsyncClient(); + + byte[] plaintext = new byte[100]; + new Random(0x1234567L).nextBytes(plaintext); + + // Let's encrypt a simple plain text of size 100 bytes. + cryptoAsyncClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext) + .subscribe(encryptResult -> { + System.out.printf("Returned ciphertext size is %d bytes with algorithm %s\n", + encryptResult.getCipherText().length, encryptResult.getAlgorithm().toString()); + // Let's decrypt the encrypted response. + cryptoAsyncClient.decrypt(EncryptionAlgorithm.RSA_OAEP, encryptResult.getCipherText()) + .subscribe(decryptResult -> System.out.printf("Returned plaintext size is %d bytes\n", + decryptResult.getPlainText().length)); + }); + + Thread.sleep(5000); + } +} + diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample17/v2/EncryptDecryptOperationsAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample17/v2/EncryptDecryptOperationsAsync.java new file mode 100644 index 000000000000..a5e448547921 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample17/v2/EncryptDecryptOperationsAsync.java @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys.cryptography; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm; + +import java.util.Random; + +/** + * Sample demonstrates how to set, get, update and delete a key. + */ +public class EncryptDecryptOperationsAsync { + /** + * Authenticates with the key vault and shows how to set, get, update and delete a key in the key vault. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws InterruptedException, IllegalArgumentException { + /* Instantiate a CryptographyAsyncClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a key identifier for a key stored in a key vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) + for links and instructions. */ + CryptographyAsyncClient cryptoAsyncClient = new CryptographyClientBuilder() + .credential(new DefaultAzureCredentialBuilder().build()) + .keyIdentifier("") + .buildAsyncClient(); + + byte[] plaintext = new byte[100]; + new Random(0x1234567L).nextBytes(plaintext); + + // Let's encrypt a simple plain text of size 100 bytes. + cryptoAsyncClient.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext) + .subscribe(encryptResult -> { + System.out.printf("Returned ciphertext size is %d bytes with algorithm %s\n", + encryptResult.getCipherText().length, encryptResult.getAlgorithm().toString()); + // Let's decrypt the encrypted response. + cryptoAsyncClient.decrypt(EncryptionAlgorithm.RSA_OAEP, encryptResult.getCipherText()) + .subscribe(decryptResult -> System.out.printf("Returned plaintext size is %d bytes\n", + decryptResult.getPlainText().length)); + }); + + Thread.sleep(5000); + } +} + diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample18/v1/KeyWrapUnwrapOperations.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample18/v1/KeyWrapUnwrapOperations.java new file mode 100644 index 000000000000..e1edd93564e4 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample18/v1/KeyWrapUnwrapOperations.java @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys.cryptography; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.keys.cryptography.models.UnwrapResult; +import com.azure.security.keyvault.keys.cryptography.models.WrapResult; +import com.azure.security.keyvault.keys.cryptography.models.KeyWrapAlgorithm; + +import java.util.Random; + + +/** + * Sample demonstrates how to set, get, update and delete a key. + */ +public class KeyWrapUnwrapOperations { + /** + * Authenticates with the key vault and shows how to set, get, update and delete a key in the key vault. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws InterruptedException, IllegalArgumentException { + /* Instantiate a CryptographyClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a key identifier for a key stored in a key vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) + for links and instructions. */ + CryptographyClient cryptoClient = new CryptographyClientBuilder() + .credential(new DefaultAzureCredentialBuilder().build()) + .keyIdentifier("") + .buildAsyncClient(); + + byte[] plaintext = new byte[100]; + new Random(0x1234567L).nextBytes(plaintext); + + // Let's wrap a simple dummy key content. + cryptoAsyncClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, plaintext) + .subscribe(keyWrapResult -> { + System.out.printf("Returned encrypted key size is %d bytes with algorithm %s\n", + keyWrapResult.getEncryptedKey().length, keyWrapResult.getAlgorithm().toString()); + // Let's decrypt the encrypted response. + cryptoAsyncClient.unwrapKey(KeyWrapAlgorithm.RSA_OAEP, keyWrapResult.getEncryptedKey()) + .subscribe(keyUnwrapResult -> + System.out.printf("Returned unwrapped key size is %d bytes\n", keyUnwrapResult.getKey().length)); + }); + + Thread.sleep(5000); + + // Let's do Key Wrap and Unwrap operations with a symmetric key. + byte[] symmetricKeyContent = + {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}; + byte[] keyContentToWrap = + {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99, (byte) 0xAA, (byte) 0xBB, + (byte) 0xCC, (byte) 0xDD, (byte) 0xEE, (byte) 0xFF}; + } +} + diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample19/v2/KeyWrapUnwrapOperationsAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample19/v2/KeyWrapUnwrapOperationsAsync.java new file mode 100644 index 000000000000..9dfc2a8fd054 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample19/v2/KeyWrapUnwrapOperationsAsync.java @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys.cryptography; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.keys.cryptography.models.KeyWrapAlgorithm; + +import java.util.Random; + +/** + * Sample demonstrates how to set, get, update and delete a key. + */ +public class KeyWrapUnwrapOperationsAsync { + /** + * Authenticates with the key vault and shows how to set, get, update and delete a key in the key vault. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws InterruptedException, IllegalArgumentException { + /* Instantiate a CryptographyAsyncClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a key identifier for a key stored in a key vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) + for links and instructions. */ + CryptographyAsyncClient cryptoAsyncClient = new CryptographyClientBuilder() + .credential(new DefaultAzureCredentialBuilder().build()) + .keyIdentifier("") + .buildAsyncClient(); + + byte[] plaintext = new byte[100]; + new Random(0x1234567L).nextBytes(plaintext); + + // Let's wrap a simple dummy key content. + cryptoAsyncClient.wrapKey(KeyWrapAlgorithm.RSA_OAEP, plaintext) + .subscribe(keyWrapResult -> { + System.out.printf("Returned encrypted key size is %d bytes with algorithm %s\n", + keyWrapResult.getEncryptedKey().length, keyWrapResult.getAlgorithm().toString()); + // Let's decrypt the encrypted response. + cryptoAsyncClient.unwrapKey(KeyWrapAlgorithm.RSA_OAEP, keyWrapResult.getEncryptedKey()) + .subscribe(keyUnwrapResult -> + System.out.printf("Returned unwrapped key size is %d bytes\n", keyUnwrapResult.getKey().length)); + }); + + Thread.sleep(5000); + + // Let's do Key Wrap and Unwrap operations with a symmetric key. + byte[] symmetricKeyContent = + {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}; + byte[] keyContentToWrap = + {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99, (byte) 0xAA, (byte) 0xBB, + (byte) 0xCC, (byte) 0xDD, (byte) 0xEE, (byte) 0xFF}; + } +} + diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample2/v1/BackupAndRestoreOperationsAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample2/v1/BackupAndRestoreOperationsAsync.java new file mode 100644 index 000000000000..d888fb65e64c --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample2/v1/BackupAndRestoreOperationsAsync.java @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys; + +import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; +import com.azure.identity.DefaultAzureCredentialBuilder; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to asynchronously backup and restore keys in the key vault. + */ +public class BackupAndRestoreOperationsAsync { + /** + * Authenticates with the key vault and shows how to asynchronously backup and restore keys in the key vault. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + * @throws IOException when writing backup to file is unsuccessful. + */ + public static void main(String[] args) throws IOException, InterruptedException, IllegalArgumentException { + /* Instantiate a KeyAsyncClient that will be used to call the service. Notice that the client is using default + Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) + for links and instructions. */ + KeyAsyncClient keyAsyncClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + // Let's create RSA key valid for 1 year. If the key + // already exists in the key vault, then a new version of the key is created. + keyAsyncClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1)) + .setKeySize(2048)) + .subscribe(keyResponse -> + System.out.printf("Key is created with name %s and type %s %n", keyResponse.getName(), keyResponse.getKeyType())); + + Thread.sleep(2000); + + // Backups are good to have, if in case keys get accidentally deleted by you. + // For long term storage, it is ideal to write the backup to a file. + String backupFilePath = "YOUR_BACKUP_FILE_PATH"; + keyAsyncClient.backupKey("CloudRsaKey").subscribe(backupResponse -> { + byte[] backupBytes = backupResponse; + writeBackupToFile(backupBytes, backupFilePath); + }); + + Thread.sleep(7000); + + // The RSA key is no longer in use, so you delete it. + keyAsyncClient.beginDeleteKey("CloudRsaKey") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Delete Key Name: " + pollResponse.getValue().getName()); + System.out.println("Key Delete Date: " + pollResponse.getValue().getDeletedOn().toString()); + }); + + // To ensure file is deleted server-side. + Thread.sleep(30000); + + // If the vault is soft-delete enabled, then you need to purge the key as well for permanent deletion. + keyAsyncClient.purgeDeletedKeyWithResponse("CloudRsaKey").subscribe(purgeResponse -> + System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode())); + + // To ensure file is purged server-side. + Thread.sleep(15000); + + // After sometime, the key is required again. We can use the backup value to restore it in the key vault. + byte[] backupFromFile = Files.readAllBytes(new File(backupFilePath).toPath()); + keyAsyncClient.restoreKeyBackup(backupFromFile).subscribe(keyResponse -> + System.out.printf("Restored Key with name %s %n", keyResponse.getName())); + + // To ensure the key is restored server-side. + Thread.sleep(15000); + } + + private static void writeBackupToFile(byte[] bytes, String filePath) { + try { + File file = new File(filePath); + if (file.exists()) { + file.delete(); + } + file.createNewFile(); + OutputStream os = new FileOutputStream(file); + os.write(bytes); + System.out.println("Successfully wrote backup to file."); + // Close the file + os.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample2/v2/BackupAndRestoreOperationsAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample2/v2/BackupAndRestoreOperationsAsync.java new file mode 100644 index 000000000000..d888fb65e64c --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample2/v2/BackupAndRestoreOperationsAsync.java @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys; + +import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; +import com.azure.identity.DefaultAzureCredentialBuilder; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to asynchronously backup and restore keys in the key vault. + */ +public class BackupAndRestoreOperationsAsync { + /** + * Authenticates with the key vault and shows how to asynchronously backup and restore keys in the key vault. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + * @throws IOException when writing backup to file is unsuccessful. + */ + public static void main(String[] args) throws IOException, InterruptedException, IllegalArgumentException { + /* Instantiate a KeyAsyncClient that will be used to call the service. Notice that the client is using default + Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) + for links and instructions. */ + KeyAsyncClient keyAsyncClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + // Let's create RSA key valid for 1 year. If the key + // already exists in the key vault, then a new version of the key is created. + keyAsyncClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1)) + .setKeySize(2048)) + .subscribe(keyResponse -> + System.out.printf("Key is created with name %s and type %s %n", keyResponse.getName(), keyResponse.getKeyType())); + + Thread.sleep(2000); + + // Backups are good to have, if in case keys get accidentally deleted by you. + // For long term storage, it is ideal to write the backup to a file. + String backupFilePath = "YOUR_BACKUP_FILE_PATH"; + keyAsyncClient.backupKey("CloudRsaKey").subscribe(backupResponse -> { + byte[] backupBytes = backupResponse; + writeBackupToFile(backupBytes, backupFilePath); + }); + + Thread.sleep(7000); + + // The RSA key is no longer in use, so you delete it. + keyAsyncClient.beginDeleteKey("CloudRsaKey") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Delete Key Name: " + pollResponse.getValue().getName()); + System.out.println("Key Delete Date: " + pollResponse.getValue().getDeletedOn().toString()); + }); + + // To ensure file is deleted server-side. + Thread.sleep(30000); + + // If the vault is soft-delete enabled, then you need to purge the key as well for permanent deletion. + keyAsyncClient.purgeDeletedKeyWithResponse("CloudRsaKey").subscribe(purgeResponse -> + System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode())); + + // To ensure file is purged server-side. + Thread.sleep(15000); + + // After sometime, the key is required again. We can use the backup value to restore it in the key vault. + byte[] backupFromFile = Files.readAllBytes(new File(backupFilePath).toPath()); + keyAsyncClient.restoreKeyBackup(backupFromFile).subscribe(keyResponse -> + System.out.printf("Restored Key with name %s %n", keyResponse.getName())); + + // To ensure the key is restored server-side. + Thread.sleep(15000); + } + + private static void writeBackupToFile(byte[] bytes, String filePath) { + try { + File file = new File(filePath); + if (file.exists()) { + file.delete(); + } + file.createNewFile(); + OutputStream os = new FileOutputStream(file); + os.write(bytes); + System.out.println("Successfully wrote backup to file."); + // Close the file + os.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample20/v1/SignVerifyOperations.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample20/v1/SignVerifyOperations.java new file mode 100644 index 000000000000..9938158a6ded --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample20/v1/SignVerifyOperations.java @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys.cryptography; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.keys.cryptography.models.SignResult; +import com.azure.security.keyvault.keys.cryptography.models.VerifyResult; +import com.azure.security.keyvault.keys.cryptography.models.SignatureAlgorithm; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Random; + +/** + * Sample demonstrates how to set, get, update and delete a key. + */ +public class SignVerifyOperations { + /** + * Authenticates with the key vault and shows how to set, get, update and delete a key in the key vault. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + * @throws NoSuchAlgorithmException when the specified algorithm doesn't exist. + */ + public static void main(String[] args) throws InterruptedException, IllegalArgumentException, NoSuchAlgorithmException { + /* Instantiate a CryptographyClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a key identifier for a key stored in a key vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) + for links and instructions. */ + CryptographyClient cryptoClient = new CryptographyClientBuilder() + .credential(new DefaultAzureCredentialBuilder().build()) + .keyIdentifier("") + .buildAsyncClient(); + + byte[] plaintext = new byte[100]; + new Random(0x1234567L).nextBytes(plaintext); + MessageDigest md = MessageDigest.getInstance("SHA-256"); + md.update(plaintext); + byte[] digest = md.digest(); + + // Let's create a signature from a simple digest. + cryptoAsyncClient.sign(SignatureAlgorithm.RS256, digest) + .subscribe(signResult -> { + System.out.printf("Returned signature size is %d bytes with algorithm %s\n", + signResult.getSignature().length, signResult.getAlgorithm().toString()); + // Let's verify the signature against the digest. + cryptoAsyncClient.verify(SignatureAlgorithm.RS256, digest, signResult.getSignature()) + .subscribe(verifyResult -> + System.out.printf("Signature verified : %s\n", verifyResult.isValid())); + }); + + Thread.sleep(4000); + + // We can sign the raw plain text data without having to create a digest. + cryptoAsyncClient.sign(SignatureAlgorithm.RS256, digest) + .subscribe(signResult -> { + System.out.printf("Returned signature size is %d bytes with algorithm %s\n", + signResult.getSignature().length, signResult.getAlgorithm().toString()); + // Let's verify the signature against the raw plain text data. + cryptoAsyncClient.verify(SignatureAlgorithm.RS256, digest, signResult.getSignature()) + .subscribe(verifyDataResult -> + System.out.printf("Signature verified : %s\n", verifyDataResult.isValid())); + }); + + // Block main thread to let async operations finish. + Thread.sleep(4000); + } +} + diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample21/v2/SignVerifyOperationsAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample21/v2/SignVerifyOperationsAsync.java new file mode 100644 index 000000000000..a37ef1b37f40 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample21/v2/SignVerifyOperationsAsync.java @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys.cryptography; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.keys.cryptography.models.SignatureAlgorithm; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Random; + +/** + * Sample demonstrates how to set, get, update and delete a key. + */ +public class SignVerifyOperationsAsync { + /** + * Authenticates with the key vault and shows how to set, get, update and delete a key in the key vault. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + * @throws NoSuchAlgorithmException when the specified algorithm doesn't exist. + */ + public static void main(String[] args) throws InterruptedException, IllegalArgumentException, NoSuchAlgorithmException { + /* Instantiate a CryptographyAsyncClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a key identifier for a key stored in a key vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) + for links and instructions. */ + CryptographyAsyncClient cryptoAsyncClient = new CryptographyClientBuilder() + .credential(new DefaultAzureCredentialBuilder().build()) + .keyIdentifier("") + .buildAsyncClient(); + + byte[] plaintext = new byte[100]; + new Random(0x1234567L).nextBytes(plaintext); + MessageDigest md = MessageDigest.getInstance("SHA-256"); + md.update(plaintext); + byte[] digest = md.digest(); + + // Let's create a signature from a simple digest. + cryptoAsyncClient.sign(SignatureAlgorithm.RS256, digest) + .subscribe(signResult -> { + System.out.printf("Returned signature size is %d bytes with algorithm %s\n", + signResult.getSignature().length, signResult.getAlgorithm().toString()); + // Let's verify the signature against the digest. + cryptoAsyncClient.verify(SignatureAlgorithm.RS256, digest, signResult.getSignature()) + .subscribe(verifyResult -> + System.out.printf("Signature verified : %s\n", verifyResult.isValid())); + }); + + Thread.sleep(4000); + + // We can sign the raw plain text data without having to create a digest. + cryptoAsyncClient.sign(SignatureAlgorithm.RS256, digest) + .subscribe(signResult -> { + System.out.printf("Returned signature size is %d bytes with algorithm %s\n", + signResult.getSignature().length, signResult.getAlgorithm().toString()); + // Let's verify the signature against the raw plain text data. + cryptoAsyncClient.verify(SignatureAlgorithm.RS256, digest, signResult.getSignature()) + .subscribe(verifyDataResult -> + System.out.printf("Signature verified : %s\n", verifyDataResult.isValid())); + }); + + // Block main thread to let async operations finish. + Thread.sleep(4000); + } +} + diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample3/v1/HelloWorld.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample3/v1/HelloWorld.java new file mode 100644 index 000000000000..6825c8560a51 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample3/v1/HelloWorld.java @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys; + +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; +import com.azure.security.keyvault.keys.models.DeletedKey; +import com.azure.security.keyvault.keys.models.KeyVaultKey; +import com.azure.identity.DefaultAzureCredentialBuilder; + +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to set, get, update and delete a key. + */ +public class HelloWorld { + /** + * Authenticates with the key vault and shows how to set, get, update and delete a key in the key vault. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws InterruptedException, IllegalArgumentException { + /* Instantiate a KeyClient that will be used to call the service. Notice that the client is using default Azure + credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) + for links and instructions. */ + KeyClient keyClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + // Let's create an RSA key valid for 1 year. If the key already exists in the key vault, then a new version of + // the key is created. + Response createKeyResponse = + keyClient.createRsaKeyWithResponse(new CreateRsaKeyOptions("CloudRsaKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1)) + .setKeySize(2048), new Context("key1", "value1")); + + // Let's validate the create key operation succeeded using the status code information in the response. + System.out.printf("Create Key operation succeeded with status code %s \n", createKeyResponse.getStatusCode()); + + // Let's get the RSA key from the key vault. + KeyVaultKey cloudRsaKey = keyClient.getKey("CloudRsaKey"); + + System.out.printf("Key is returned with name %s and type %s \n", cloudRsaKey.getName(), + cloudRsaKey.getKeyType()); + + // After one year, the RSA key is still required, we need to update the expiry time of the key. + // The update method can be used to update the expiry attribute of the key. + cloudRsaKey.getProperties().setExpiresOn(cloudRsaKey.getProperties().getExpiresOn().plusYears(1)); + + KeyVaultKey updatedKey = keyClient.updateKeyProperties(cloudRsaKey.getProperties()); + + System.out.printf("Key's updated expiry time %s \n", updatedKey.getProperties().getExpiresOn()); + + // We need the RSA key with bigger key size, so you want to update the key in key vault to ensure it has the + // required size. Calling createRsaKey() on an existing key creates a new version of the key in the key vault + // with the new specified size. + keyClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1)) + .setKeySize(4096)); + + // The RSA key is no longer needed, need to delete it from the key vault. + SyncPoller rsaDeletedKeyPoller = keyClient.beginDeleteKey("CloudRsaKey"); + PollResponse pollResponse = rsaDeletedKeyPoller.poll(); + DeletedKey rsaDeletedKey = pollResponse.getValue(); + + System.out.println("Deleted Date %s" + rsaDeletedKey.getDeletedOn().toString()); + System.out.printf("Deleted Key's Recovery Id %s", rsaDeletedKey.getRecoveryId()); + + // The key is being deleted on the server. + rsaDeletedKeyPoller.waitForCompletion(); + + // To ensure the key is deleted server-side. + Thread.sleep(30000); + + // If the keyvault is soft-delete enabled, then deleted keys need to be purged for permanent deletion. + keyClient.purgeDeletedKey("CloudRsaKey"); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample3/v2/HelloWorld.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample3/v2/HelloWorld.java new file mode 100644 index 000000000000..6825c8560a51 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample3/v2/HelloWorld.java @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys; + +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; +import com.azure.security.keyvault.keys.models.DeletedKey; +import com.azure.security.keyvault.keys.models.KeyVaultKey; +import com.azure.identity.DefaultAzureCredentialBuilder; + +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to set, get, update and delete a key. + */ +public class HelloWorld { + /** + * Authenticates with the key vault and shows how to set, get, update and delete a key in the key vault. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws InterruptedException, IllegalArgumentException { + /* Instantiate a KeyClient that will be used to call the service. Notice that the client is using default Azure + credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) + for links and instructions. */ + KeyClient keyClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + // Let's create an RSA key valid for 1 year. If the key already exists in the key vault, then a new version of + // the key is created. + Response createKeyResponse = + keyClient.createRsaKeyWithResponse(new CreateRsaKeyOptions("CloudRsaKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1)) + .setKeySize(2048), new Context("key1", "value1")); + + // Let's validate the create key operation succeeded using the status code information in the response. + System.out.printf("Create Key operation succeeded with status code %s \n", createKeyResponse.getStatusCode()); + + // Let's get the RSA key from the key vault. + KeyVaultKey cloudRsaKey = keyClient.getKey("CloudRsaKey"); + + System.out.printf("Key is returned with name %s and type %s \n", cloudRsaKey.getName(), + cloudRsaKey.getKeyType()); + + // After one year, the RSA key is still required, we need to update the expiry time of the key. + // The update method can be used to update the expiry attribute of the key. + cloudRsaKey.getProperties().setExpiresOn(cloudRsaKey.getProperties().getExpiresOn().plusYears(1)); + + KeyVaultKey updatedKey = keyClient.updateKeyProperties(cloudRsaKey.getProperties()); + + System.out.printf("Key's updated expiry time %s \n", updatedKey.getProperties().getExpiresOn()); + + // We need the RSA key with bigger key size, so you want to update the key in key vault to ensure it has the + // required size. Calling createRsaKey() on an existing key creates a new version of the key in the key vault + // with the new specified size. + keyClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1)) + .setKeySize(4096)); + + // The RSA key is no longer needed, need to delete it from the key vault. + SyncPoller rsaDeletedKeyPoller = keyClient.beginDeleteKey("CloudRsaKey"); + PollResponse pollResponse = rsaDeletedKeyPoller.poll(); + DeletedKey rsaDeletedKey = pollResponse.getValue(); + + System.out.println("Deleted Date %s" + rsaDeletedKey.getDeletedOn().toString()); + System.out.printf("Deleted Key's Recovery Id %s", rsaDeletedKey.getRecoveryId()); + + // The key is being deleted on the server. + rsaDeletedKeyPoller.waitForCompletion(); + + // To ensure the key is deleted server-side. + Thread.sleep(30000); + + // If the keyvault is soft-delete enabled, then deleted keys need to be purged for permanent deletion. + keyClient.purgeDeletedKey("CloudRsaKey"); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample4/v1/HelloWorldAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample4/v1/HelloWorldAsync.java new file mode 100644 index 000000000000..0ab8b4d4da48 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample4/v1/HelloWorldAsync.java @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys; + +import com.azure.core.http.rest.Response; +import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; +import com.azure.security.keyvault.keys.models.KeyVaultKey; +import com.azure.identity.DefaultAzureCredentialBuilder; + +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to asynchronously set, get, update and delete a key. + */ +public class HelloWorldAsync { + /** + * Authenticates with the key vault and shows how to asynchronously set, get, update and delete a key in the key + * vault. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws InterruptedException { + /* Instantiate a KeyAsyncClient that will be used to call the service. Notice that the client is using default + Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) + for links and instructions. */ + KeyAsyncClient keyAsyncClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + // Let's create an RSA key valid for 1 year. If the key already exists in the key vault, then a new version of + // the key is created. + Response createKeyResponse = keyAsyncClient.createRsaKeyWithResponse(new CreateRsaKeyOptions("CloudRsaKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1)) + .setKeySize(2048)).block(); + + // Let's validate create key operation succeeded using the status code information in the response. + System.out.printf("Create Key operation succeeded with status code %s%n", createKeyResponse.getStatusCode()); + System.out.printf("Key is created with name %s and type %s%n", createKeyResponse.getValue().getName(), + createKeyResponse.getValue().getKeyType()); + + Thread.sleep(2000); + + // Let's get the RSA key from the key vault. + keyAsyncClient.getKey("CloudRsaKey").subscribe(keyResponse -> + System.out.printf("Key returned with name %s and type %s%n", keyResponse.getName(), keyResponse.getKeyType())); + + Thread.sleep(2000); + + // After one year, the RSA key is still required, we need to update the expiry time of the key. + // The update method can be used to update the expiry attribute of the key. + keyAsyncClient.getKey("CloudRsaKey").subscribe(keyResponse -> { + KeyVaultKey key = keyResponse; + + // Update the expiry time of the key. + key.getProperties().setExpiresOn(key.getProperties().getExpiresOn().plusYears(1)); + keyAsyncClient.updateKeyProperties(key.getProperties()) + .subscribe(updatedKeyResponse -> + System.out.printf("Key's updated expiry time %s%n", + updatedKeyResponse.getProperties().getExpiresOn().toString())); + }); + + Thread.sleep(2000); + + // We need the RSA key with bigger key size, so you want to update the key in key vault to ensure it has the + // required size. Calling createRsaKey() on an existing key creates a new version of the key in the key vault + // with the new specified size. + keyAsyncClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1)) + .setKeySize(4096)) + .subscribe(keyResponse -> + System.out.printf("Key is created with name %s and type %s%n", keyResponse.getName(), + keyResponse.getKeyType())); + + Thread.sleep(2000); + + // The RSA key is no longer needed, need to delete it from the key vault. + keyAsyncClient.beginDeleteKey("CloudRsaKey") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Delete Key Name: " + pollResponse.getValue().getName()); + System.out.println("Key Delete Date: " + pollResponse.getValue().getDeletedOn().toString()); + }); + + // To ensure the key is deleted server-side. + Thread.sleep(30000); + + // If the keyvault is soft-delete enabled, then for permanent deletion deleted keys need to be purged. + keyAsyncClient.purgeDeletedKeyWithResponse("CloudRsaKey") + .subscribe(purgeResponse -> + System.out.printf("RSA key purge status response %d%n", purgeResponse.getStatusCode())); + + // To ensure the key is purged server-side. + Thread.sleep(15000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample4/v2/HelloWorldAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample4/v2/HelloWorldAsync.java new file mode 100644 index 000000000000..0ab8b4d4da48 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample4/v2/HelloWorldAsync.java @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys; + +import com.azure.core.http.rest.Response; +import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; +import com.azure.security.keyvault.keys.models.KeyVaultKey; +import com.azure.identity.DefaultAzureCredentialBuilder; + +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to asynchronously set, get, update and delete a key. + */ +public class HelloWorldAsync { + /** + * Authenticates with the key vault and shows how to asynchronously set, get, update and delete a key in the key + * vault. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws InterruptedException { + /* Instantiate a KeyAsyncClient that will be used to call the service. Notice that the client is using default + Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) + for links and instructions. */ + KeyAsyncClient keyAsyncClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + // Let's create an RSA key valid for 1 year. If the key already exists in the key vault, then a new version of + // the key is created. + Response createKeyResponse = keyAsyncClient.createRsaKeyWithResponse(new CreateRsaKeyOptions("CloudRsaKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1)) + .setKeySize(2048)).block(); + + // Let's validate create key operation succeeded using the status code information in the response. + System.out.printf("Create Key operation succeeded with status code %s%n", createKeyResponse.getStatusCode()); + System.out.printf("Key is created with name %s and type %s%n", createKeyResponse.getValue().getName(), + createKeyResponse.getValue().getKeyType()); + + Thread.sleep(2000); + + // Let's get the RSA key from the key vault. + keyAsyncClient.getKey("CloudRsaKey").subscribe(keyResponse -> + System.out.printf("Key returned with name %s and type %s%n", keyResponse.getName(), keyResponse.getKeyType())); + + Thread.sleep(2000); + + // After one year, the RSA key is still required, we need to update the expiry time of the key. + // The update method can be used to update the expiry attribute of the key. + keyAsyncClient.getKey("CloudRsaKey").subscribe(keyResponse -> { + KeyVaultKey key = keyResponse; + + // Update the expiry time of the key. + key.getProperties().setExpiresOn(key.getProperties().getExpiresOn().plusYears(1)); + keyAsyncClient.updateKeyProperties(key.getProperties()) + .subscribe(updatedKeyResponse -> + System.out.printf("Key's updated expiry time %s%n", + updatedKeyResponse.getProperties().getExpiresOn().toString())); + }); + + Thread.sleep(2000); + + // We need the RSA key with bigger key size, so you want to update the key in key vault to ensure it has the + // required size. Calling createRsaKey() on an existing key creates a new version of the key in the key vault + // with the new specified size. + keyAsyncClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1)) + .setKeySize(4096)) + .subscribe(keyResponse -> + System.out.printf("Key is created with name %s and type %s%n", keyResponse.getName(), + keyResponse.getKeyType())); + + Thread.sleep(2000); + + // The RSA key is no longer needed, need to delete it from the key vault. + keyAsyncClient.beginDeleteKey("CloudRsaKey") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Delete Key Name: " + pollResponse.getValue().getName()); + System.out.println("Key Delete Date: " + pollResponse.getValue().getDeletedOn().toString()); + }); + + // To ensure the key is deleted server-side. + Thread.sleep(30000); + + // If the keyvault is soft-delete enabled, then for permanent deletion deleted keys need to be purged. + keyAsyncClient.purgeDeletedKeyWithResponse("CloudRsaKey") + .subscribe(purgeResponse -> + System.out.printf("RSA key purge status response %d%n", purgeResponse.getStatusCode())); + + // To ensure the key is purged server-side. + Thread.sleep(15000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample5/v1/KeyAsyncClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample5/v1/KeyAsyncClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..0290622d5ac7 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample5/v1/KeyAsyncClientJavaDocCodeSnippets.java @@ -0,0 +1,640 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys; + +import com.azure.core.http.HttpClient; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.policy.HttpLogOptions; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.keys.models.CreateEcKeyOptions; +import com.azure.security.keyvault.keys.models.CreateKeyOptions; +import com.azure.security.keyvault.keys.models.CreateOctKeyOptions; +import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; +import com.azure.security.keyvault.keys.models.ImportKeyOptions; +import com.azure.security.keyvault.keys.models.JsonWebKey; +import com.azure.security.keyvault.keys.models.KeyCurveName; +import com.azure.security.keyvault.keys.models.KeyExportEncryptionAlgorithm; +import com.azure.security.keyvault.keys.models.KeyOperation; +import com.azure.security.keyvault.keys.models.KeyProperties; +import com.azure.security.keyvault.keys.models.KeyRotationLifetimeAction; +import com.azure.security.keyvault.keys.models.KeyRotationPolicy; +import com.azure.security.keyvault.keys.models.KeyRotationPolicyAction; +import com.azure.security.keyvault.keys.models.KeyType; +import com.azure.security.keyvault.keys.models.ReleaseKeyOptions; +import reactor.util.context.Context; + +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * This class contains code samples for generating javadocs through doclets for {@link KeyAsyncClient}. + */ +public final class KeyAsyncClientJavaDocCodeSnippets { + /** + * Generates code sample for creating a {@link KeyAsyncClient}. + * + * @return An instance of {@link KeyAsyncClient}. + */ + public KeyAsyncClient createAsyncClient() { + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.instantiation + KeyAsyncClient keyAsyncClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.instantiation + return keyAsyncClient; + } + + /** + * Generates code sample for creating a {@link KeyAsyncClient} using a custom {@link HttpClient}. + * + * @return An instance of {@link KeyAsyncClient}. + */ + public KeyAsyncClient createAsyncClientWithHttpClient() { + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.instantiation.withHttpClient + KeyAsyncClient keyAsyncClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) + .httpClient(HttpClient.createDefault()) + .buildAsyncClient(); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.instantiation.withHttpClient + return keyAsyncClient; + } + + /** + * Generates code samples for using {@link KeyAsyncClient#createKey(String, KeyType)}, + * {@link KeyAsyncClient#createKey(CreateKeyOptions)}, + * {@link KeyAsyncClient#createRsaKey(CreateRsaKeyOptions)}, + * {@link KeyAsyncClient#createEcKey(CreateEcKeyOptions)} and + * {@link KeyAsyncClient#createOctKey(CreateOctKeyOptions)}. + */ + public void createKey() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.createKey#String-KeyType + keyAsyncClient.createKey("keyName", KeyType.EC) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(key -> + System.out.printf("Created key with name: %s and id: %s %n", key.getName(), + key.getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.createKey#String-KeyType + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.createKey#CreateKeyOptions + CreateKeyOptions createKeyOptions = new CreateKeyOptions("keyName", KeyType.RSA) + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + + keyAsyncClient.createKey(createKeyOptions) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(key -> + System.out.printf("Created key with name: %s and id: %s %n", key.getName(), + key.getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.createKey#CreateKeyOptions + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.createRsaKey#CreateRsaKeyOptions + CreateRsaKeyOptions createRsaKeyOptions = new CreateRsaKeyOptions("keyName") + .setKeySize(2048) + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + + keyAsyncClient.createRsaKey(createRsaKeyOptions) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(rsaKey -> + System.out.printf("Created key with name: %s and id: %s %n", rsaKey.getName(), + rsaKey.getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.createRsaKey#CreateRsaKeyOptions + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.createEcKey#CreateEcKeyOptions + CreateEcKeyOptions createEcKeyOptions = new CreateEcKeyOptions("keyName") + .setCurveName(KeyCurveName.P_384) + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + + keyAsyncClient.createEcKey(createEcKeyOptions) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(ecKey -> + System.out.printf("Created key with name: %s and id: %s %n", ecKey.getName(), + ecKey.getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.createEcKey#CreateEcKeyOptions + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.createOctKey#CreateOctKeyOptions + CreateOctKeyOptions createOctKeyOptions = new CreateOctKeyOptions("keyName") + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + + keyAsyncClient.createOctKey(createOctKeyOptions) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(octKey -> + System.out.printf("Created key with name: %s and id: %s %n", octKey.getName(), + octKey.getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.createOctKey#CreateOctKeyOptions + } + + /** + * Generates code samples for using {@link KeyAsyncClient#importKey(String, JsonWebKey)}, + * {@link KeyAsyncClient#importKey(ImportKeyOptions)} and + * {@link KeyAsyncClient#importKeyWithResponse(ImportKeyOptions)}. + */ + public void importKey() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + JsonWebKey jsonWebKeyToImport = new JsonWebKey(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.importKey#String-JsonWebKey + keyAsyncClient.importKey("keyName", jsonWebKeyToImport) + .subscribe(keyVaultKey -> + System.out.printf("Imported key with name: %s and id: %s%n", keyVaultKey.getName(), + keyVaultKey.getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.importKey#String-JsonWebKey + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.importKey#ImportKeyOptions + ImportKeyOptions options = new ImportKeyOptions("keyName", jsonWebKeyToImport) + .setHardwareProtected(false); + + keyAsyncClient.importKey(options).subscribe(keyVaultKey -> + System.out.printf("Imported key with name: %s and id: %s%n", keyVaultKey.getName(), keyVaultKey.getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.importKey#ImportKeyOptions + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.importKeyWithResponse#ImportKeyOptions + ImportKeyOptions importKeyOptions = new ImportKeyOptions("keyName", jsonWebKeyToImport) + .setHardwareProtected(false); + + keyAsyncClient.importKeyWithResponse(importKeyOptions).subscribe(response -> + System.out.printf("Imported key with name: %s and id: %s%n", response.getValue().getName(), + response.getValue().getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.importKeyWithResponse#ImportKeyOptions + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#beginDeleteKey(String)}. + */ + public void beginDeleteKey() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.deleteKey#String + keyAsyncClient.beginDeleteKey("keyName") + .subscribe(pollResponse -> { + System.out.printf("Deletion status: %s%n", pollResponse.getStatus()); + System.out.printf("Key name: %s%n", pollResponse.getValue().getName()); + System.out.printf("Key delete date: %s%n", pollResponse.getValue().getDeletedOn()); + }); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.deleteKey#String + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#getDeletedKey(String)}. + */ + public void getDeletedKey() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.getDeletedKey#String + keyAsyncClient.getDeletedKey("keyName") + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(deletedKey -> + System.out.printf("Deleted key's recovery id:%s%n", deletedKey.getRecoveryId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.getDeletedKey#String + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#createKeyWithResponse(CreateKeyOptions)}, + * {@link KeyAsyncClient#createRsaKeyWithResponse(CreateRsaKeyOptions)}, + * {@link KeyAsyncClient#createEcKeyWithResponse(CreateEcKeyOptions)} and + * {@link KeyAsyncClient#createOctKeyWithResponse(CreateOctKeyOptions)}. + */ + public void createKeyWithResponse() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.createKeyWithResponse#CreateKeyOptions + CreateKeyOptions createKeyOptions = new CreateKeyOptions("keyName", KeyType.RSA) + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + + keyAsyncClient.createKeyWithResponse(createKeyOptions) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(createKeyResponse -> + System.out.printf("Created key with name: %s and: id %s%n", createKeyResponse.getValue().getName(), + createKeyResponse.getValue().getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.createKeyWithResponse#CreateKeyOptions + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.createRsaKeyWithResponse#CreateRsaKeyOptions + CreateRsaKeyOptions createRsaKeyOptions = new CreateRsaKeyOptions("keyName") + .setKeySize(2048) + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + + keyAsyncClient.createRsaKeyWithResponse(createRsaKeyOptions) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(createRsaKeyResponse -> + System.out.printf("Created key with name: %s and: id %s%n", createRsaKeyResponse.getValue().getName(), + createRsaKeyResponse.getValue().getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.createRsaKeyWithResponse#CreateRsaKeyOptions + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.createEcKeyWithResponse#CreateEcKeyOptions + CreateEcKeyOptions createEcKeyOptions = new CreateEcKeyOptions("keyName") + .setCurveName(KeyCurveName.P_384) + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + + keyAsyncClient.createEcKeyWithResponse(createEcKeyOptions) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(createEcKeyResponse -> + System.out.printf("Created key with name: %s and: id %s%n", createEcKeyResponse.getValue().getName(), + createEcKeyResponse.getValue().getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.createEcKeyWithResponse#CreateEcKeyOptions + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.createOctKeyWithResponse#CreateOctKeyOptions + CreateOctKeyOptions createOctKeyOptions = new CreateOctKeyOptions("keyName") + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + + keyAsyncClient.createOctKeyWithResponse(createOctKeyOptions) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(createOctKeyResponse -> + System.out.printf("Created key with name: %s and: id %s%n", createOctKeyResponse.getValue().getName(), + createOctKeyResponse.getValue().getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.createOctKeyWithResponse#CreateOctKeyOptions + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#getKeyWithResponse(String, String)}. + */ + public void getKeyWithResponse() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.getKeyWithResponse#String-String + String keyVersion = "6A385B124DEF4096AF1361A85B16C204"; + + keyAsyncClient.getKeyWithResponse("keyName", keyVersion) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(getKeyResponse -> + System.out.printf("Created key with name: %s and: id %s%n", + getKeyResponse.getValue().getName(), getKeyResponse.getValue().getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.getKeyWithResponse#String-String + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#getKey(String, String)}. + */ + public void getKey() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.getKey#String + keyAsyncClient.getKey("keyName") + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(key -> + System.out.printf("Created key with name: %s and: id %s%n", key.getName(), + key.getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.getKey#String + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.getKey#String-String + String keyVersion = "6A385B124DEF4096AF1361A85B16C204"; + + keyAsyncClient.getKey("keyName", keyVersion) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(key -> + System.out.printf("Created key with name: %s and: id %s%n", key.getName(), + key.getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.getKey#String-String + } + + /** + * Generates a code sample for using + * {@link KeyAsyncClient#updateKeyPropertiesWithResponse(KeyProperties, KeyOperation...)}. + */ + public void updateKeyPropertiesWithResponse() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.updateKeyPropertiesWithResponse#KeyProperties-KeyOperation + keyAsyncClient.getKey("keyName") + .subscribe(getKeyResponse -> { + //Update the not before time of the key. + getKeyResponse.getProperties().setNotBefore(OffsetDateTime.now().plusDays(50)); + keyAsyncClient.updateKeyPropertiesWithResponse(getKeyResponse.getProperties(), KeyOperation.ENCRYPT, + KeyOperation.DECRYPT) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(updateKeyResponse -> + System.out.printf("Updated key's \"not before time\": %s%n", + updateKeyResponse.getValue().getProperties().getNotBefore().toString())); + }); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.updateKeyPropertiesWithResponse#KeyProperties-KeyOperation + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#updateKeyProperties(KeyProperties, KeyOperation...)}. + */ + public void updateKeyProperties() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.updateKeyProperties#KeyProperties-KeyOperation + keyAsyncClient.getKey("keyName") + .subscribe(key -> { + //Update the not before time of the key. + key.getProperties().setNotBefore(OffsetDateTime.now().plusDays(50)); + keyAsyncClient.updateKeyProperties(key.getProperties(), KeyOperation.ENCRYPT, + KeyOperation.DECRYPT) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(updatedKey -> + System.out.printf("Updated key's \"not before time\": %s%n", + updatedKey.getProperties().getNotBefore().toString())); + }); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.updateKeyProperties#KeyProperties-KeyOperation + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#getDeletedKeyWithResponse(String)}. + */ + public void getDeletedKeyWithResponse() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.getDeletedKeyWithResponse#String + keyAsyncClient.getDeletedKeyWithResponse("keyName") + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(getDeletedKeyResponse -> + System.out.printf("Deleted key's recovery id: %s%n", getDeletedKeyResponse.getValue().getRecoveryId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.getDeletedKeyWithResponse#String + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#purgeDeletedKey(String)}. + */ + public void purgeDeletedKey() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.purgeDeletedKey#String + keyAsyncClient.purgeDeletedKey("deletedKeyName") + .subscribe(ignored -> + System.out.println("Successfully purged deleted key")); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.purgeDeletedKey#String + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#purgeDeletedKeyWithResponse(String)}. + */ + public void purgeDeletedKeyWithResponse() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.purgeDeletedKeyWithResponse#String + keyAsyncClient.purgeDeletedKeyWithResponse("deletedKeyName") + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(purgeDeletedKeyResponse -> + System.out.printf("Purge response status code: %d%n", purgeDeletedKeyResponse.getStatusCode())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.purgeDeletedKeyWithResponse#String + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#beginRecoverDeletedKey(String)}. + */ + public void beginRecoverDeletedKey() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.recoverDeletedKey#String + keyAsyncClient.beginRecoverDeletedKey("deletedKeyName") + .subscribe(pollResponse -> { + System.out.printf("Recovery status: %s%n", pollResponse.getStatus()); + System.out.printf("Key name: %s%n", pollResponse.getValue().getName()); + System.out.printf("Key type: %s%n", pollResponse.getValue().getKeyType()); + }); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.recoverDeletedKey#String + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#backupKey(String)}. + */ + public void backupKey() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.backupKey#String + keyAsyncClient.backupKey("keyName") + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(bytes -> + System.out.printf("Key backup byte array length: %s%n", bytes.length)); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.backupKey#String + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#backupKeyWithResponse(String)}. + */ + public void backupKeyWithResponse() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.backupKeyWithResponse#String + keyAsyncClient.backupKeyWithResponse("keyName") + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(backupKeyResponse -> + System.out.printf("Key backup byte array length: %s%n", backupKeyResponse.getValue().length)); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.backupKeyWithResponse#String + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#restoreKeyBackup}. + */ + public void restoreKeyBackup() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + byte[] keyBackupByteArray = {}; + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.restoreKeyBackup#byte + keyAsyncClient.restoreKeyBackup(keyBackupByteArray) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(restoreKeyResponse -> + System.out.printf("Restored key with name: %s and: id %s%n", restoreKeyResponse.getName(), + restoreKeyResponse.getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.restoreKeyBackup#byte + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#restoreKeyBackupWithResponse(byte[])}. + */ + public void restoreKeyBackupWithResponse() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + byte[] keyBackupByteArray = {}; + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.restoreKeyBackupWithResponse#byte + keyAsyncClient.restoreKeyBackupWithResponse(keyBackupByteArray) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(restoreKeyBackupResponse -> + System.out.printf("Restored key with name: %s and: id %s%n", + restoreKeyBackupResponse.getValue().getName(), restoreKeyBackupResponse.getValue().getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.restoreKeyBackupWithResponse#byte + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#listPropertiesOfKeys}. + */ + public void listPropertiesOfKeys() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.listPropertiesOfKeys + keyAsyncClient.listPropertiesOfKeys() + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .flatMap(keyProperties -> keyAsyncClient.getKey(keyProperties.getName(), keyProperties.getVersion())) + .subscribe(key -> System.out.printf("Retrieved key with name: %s and type: %s%n", + key.getName(), + key.getKeyType())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.listPropertiesOfKeys + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#listDeletedKeys()}. + */ + public void listDeletedKeys() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.listDeletedKeys + keyAsyncClient.listDeletedKeys() + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(deletedKey -> + System.out.printf("Deleted key's recovery id:%s%n", deletedKey.getRecoveryId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.listDeletedKeys + } + + /** + * Generates code sample for using {@link KeyAsyncClient#listPropertiesOfKeyVersions(String)}. + */ + public void listPropertiesOfKeyVersions() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.listKeyVersions + keyAsyncClient.listPropertiesOfKeyVersions("keyName") + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .flatMap(keyProperties -> keyAsyncClient.getKey(keyProperties.getName(), keyProperties.getVersion())) + .subscribe(key -> + System.out.printf("Retrieved key version: %s with name: %s and type: %s%n", + key.getProperties().getVersion(), key.getName(), key.getKeyType())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.listKeyVersions + } + + /** + * Generates code samples for using {@link KeyAsyncClient#getRandomBytes(int)} and + * {@link KeyAsyncClient#getRandomBytesWithResponse(int)}. + */ + public void getRandomBytes() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.getRandomBytes#int + int amount = 16; + keyAsyncClient.getRandomBytes(amount) + .subscribe(randomBytes -> + System.out.printf("Retrieved %d random bytes: %s%n", amount, Arrays.toString(randomBytes))); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.getRandomBytes#int + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.getRandomBytesWithResponse#int + int amountOfBytes = 16; + keyAsyncClient.getRandomBytesWithResponse(amountOfBytes).subscribe(response -> + System.out.printf("Response received successfully with status code: %d. Retrieved %d random bytes: %s%n", + response.getStatusCode(), amountOfBytes, Arrays.toString(response.getValue()))); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.getRandomBytesWithResponse#int + } + + /** + * Generates code samples for using {@link KeyAsyncClient#releaseKey(String, String)}, + * {@link KeyAsyncClient#releaseKey(String, String, String)} and + * {@link KeyAsyncClient#releaseKeyWithResponse(String, String, String, ReleaseKeyOptions)}. + */ + public void releaseKey() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.releaseKey#String-String + String targetAttestationToken = "someAttestationToken"; + + keyAsyncClient.releaseKey("keyName", targetAttestationToken) + .subscribe(releaseKeyResult -> + System.out.printf("Signed object containing released key: %s%n", releaseKeyResult.getValue())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.releaseKey#String-String + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.releaseKey#String-String-String + String myKeyVersion = "6A385B124DEF4096AF1361A85B16C204"; + String myTargetAttestationToken = "someAttestationToken"; + + keyAsyncClient.releaseKey("keyName", myKeyVersion, myTargetAttestationToken) + .subscribe(releaseKeyResult -> + System.out.printf("Signed object containing released key: %s%n", releaseKeyResult.getValue())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.releaseKey#String-String-String + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.releaseKeyWithResponse#String-String-String-ReleaseKeyOptions + String releaseKeyVersion = "6A385B124DEF4096AF1361A85B16C204"; + String someTargetAttestationToken = "someAttestationToken"; + ReleaseKeyOptions releaseKeyOptions = new ReleaseKeyOptions() + .setAlgorithm(KeyExportEncryptionAlgorithm.RSA_AES_KEY_WRAP_256) + .setNonce("someNonce"); + + keyAsyncClient.releaseKeyWithResponse("keyName", releaseKeyVersion, someTargetAttestationToken, + releaseKeyOptions) + .subscribe(releaseKeyResponse -> + System.out.printf("Response received successfully with status code: %d. Signed object containing" + + "released key: %s%n", releaseKeyResponse.getStatusCode(), + releaseKeyResponse.getValue().getValue())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.releaseKeyWithResponse#String-String-String-ReleaseKeyOptions + } + + /** + * Generates code samples for using {@link KeyAsyncClient#rotateKey(String)} and + * {@link KeyAsyncClient#rotateKeyWithResponse(String)}. + */ + public void rotateKey() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.rotateKey#String + keyAsyncClient.rotateKey("keyName") + .subscribe(key -> + System.out.printf("Rotated key with name: %s and version:%s%n", key.getName(), + key.getProperties().getVersion())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.rotateKey#String + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.rotateKeyWithResponse#String + keyAsyncClient.rotateKeyWithResponse("keyName") + .subscribe(rotateKeyResponse -> + System.out.printf("Response received successfully with status code: %d. Rotated key with name: %s and" + + "version: %s%n", rotateKeyResponse.getStatusCode(), rotateKeyResponse.getValue().getName(), + rotateKeyResponse.getValue().getProperties().getVersion())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.rotateKeyWithResponse#String + } + + /** + * Generates code samples for using {@link KeyAsyncClient#getKeyRotationPolicy(String)} and + * {@link KeyAsyncClient#getKeyRotationPolicyWithResponse(String)}. + */ + public void getKeyRotationPolicy() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.getKeyRotationPolicy#String + keyAsyncClient.getKeyRotationPolicy("keyName") + .subscribe(keyRotationPolicy -> + System.out.printf("Retrieved key rotation policy with id: %s%n", keyRotationPolicy.getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.getKeyRotationPolicy#String + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.getKeyRotationPolicyWithResponse#String + keyAsyncClient.getKeyRotationPolicyWithResponse("keyName") + .subscribe(getKeyRotationPolicyResponse -> + System.out.printf("Response received successfully with status code: %d. Retrieved key rotation policy" + + "with id: %s%n", getKeyRotationPolicyResponse.getStatusCode(), + getKeyRotationPolicyResponse.getValue().getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.getKeyRotationPolicyWithResponse#String + } + + /** + * Generates code samples for using + * {@link KeyAsyncClient#updateKeyRotationPolicy(String, KeyRotationPolicy)} and + * {@link KeyAsyncClient#updateKeyRotationPolicyWithResponse(String, KeyRotationPolicy)}. + */ + public void updateKeyRotationPolicy() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.updateKeyRotationPolicy#String-KeyRotationPolicy + List lifetimeActions = new ArrayList<>(); + KeyRotationLifetimeAction rotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE) + .setTimeAfterCreate("P90D"); + KeyRotationLifetimeAction notifyLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.NOTIFY) + .setTimeBeforeExpiry("P45D"); + + lifetimeActions.add(rotateLifetimeAction); + lifetimeActions.add(notifyLifetimeAction); + + KeyRotationPolicy keyRotationPolicy = new KeyRotationPolicy() + .setLifetimeActions(lifetimeActions) + .setExpiresIn("P6M"); + + keyAsyncClient.updateKeyRotationPolicy("keyName", keyRotationPolicy) + .subscribe(updatedPolicy -> + System.out.printf("Updated key rotation policy with id: %s%n", updatedPolicy.getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.updateKeyRotationPolicy#String-KeyRotationPolicy + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.updateKeyRotationPolicyWithResponse#String-KeyRotationPolicy + List myLifetimeActions = new ArrayList<>(); + KeyRotationLifetimeAction myRotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE) + .setTimeAfterCreate("P90D"); + KeyRotationLifetimeAction myNotifyLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.NOTIFY) + .setTimeBeforeExpiry("P45D"); + + myLifetimeActions.add(myRotateLifetimeAction); + myLifetimeActions.add(myNotifyLifetimeAction); + + KeyRotationPolicy myKeyRotationPolicy = new KeyRotationPolicy() + .setLifetimeActions(myLifetimeActions) + .setExpiresIn("P6M"); + + keyAsyncClient.updateKeyRotationPolicyWithResponse("keyName", myKeyRotationPolicy) + .subscribe(myUpdatedPolicyResponse -> + System.out.printf("Response received successfully with status code: %d. Updated key rotation policy" + + "with id: %s%n", myUpdatedPolicyResponse.getStatusCode(), + myUpdatedPolicyResponse.getValue().getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.updateKeyRotationPolicyWithResponse#String-KeyRotationPolicy + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample5/v2/KeyAsyncClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample5/v2/KeyAsyncClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..0290622d5ac7 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample5/v2/KeyAsyncClientJavaDocCodeSnippets.java @@ -0,0 +1,640 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys; + +import com.azure.core.http.HttpClient; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.policy.HttpLogOptions; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.keys.models.CreateEcKeyOptions; +import com.azure.security.keyvault.keys.models.CreateKeyOptions; +import com.azure.security.keyvault.keys.models.CreateOctKeyOptions; +import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; +import com.azure.security.keyvault.keys.models.ImportKeyOptions; +import com.azure.security.keyvault.keys.models.JsonWebKey; +import com.azure.security.keyvault.keys.models.KeyCurveName; +import com.azure.security.keyvault.keys.models.KeyExportEncryptionAlgorithm; +import com.azure.security.keyvault.keys.models.KeyOperation; +import com.azure.security.keyvault.keys.models.KeyProperties; +import com.azure.security.keyvault.keys.models.KeyRotationLifetimeAction; +import com.azure.security.keyvault.keys.models.KeyRotationPolicy; +import com.azure.security.keyvault.keys.models.KeyRotationPolicyAction; +import com.azure.security.keyvault.keys.models.KeyType; +import com.azure.security.keyvault.keys.models.ReleaseKeyOptions; +import reactor.util.context.Context; + +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * This class contains code samples for generating javadocs through doclets for {@link KeyAsyncClient}. + */ +public final class KeyAsyncClientJavaDocCodeSnippets { + /** + * Generates code sample for creating a {@link KeyAsyncClient}. + * + * @return An instance of {@link KeyAsyncClient}. + */ + public KeyAsyncClient createAsyncClient() { + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.instantiation + KeyAsyncClient keyAsyncClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.instantiation + return keyAsyncClient; + } + + /** + * Generates code sample for creating a {@link KeyAsyncClient} using a custom {@link HttpClient}. + * + * @return An instance of {@link KeyAsyncClient}. + */ + public KeyAsyncClient createAsyncClientWithHttpClient() { + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.instantiation.withHttpClient + KeyAsyncClient keyAsyncClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) + .httpClient(HttpClient.createDefault()) + .buildAsyncClient(); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.instantiation.withHttpClient + return keyAsyncClient; + } + + /** + * Generates code samples for using {@link KeyAsyncClient#createKey(String, KeyType)}, + * {@link KeyAsyncClient#createKey(CreateKeyOptions)}, + * {@link KeyAsyncClient#createRsaKey(CreateRsaKeyOptions)}, + * {@link KeyAsyncClient#createEcKey(CreateEcKeyOptions)} and + * {@link KeyAsyncClient#createOctKey(CreateOctKeyOptions)}. + */ + public void createKey() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.createKey#String-KeyType + keyAsyncClient.createKey("keyName", KeyType.EC) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(key -> + System.out.printf("Created key with name: %s and id: %s %n", key.getName(), + key.getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.createKey#String-KeyType + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.createKey#CreateKeyOptions + CreateKeyOptions createKeyOptions = new CreateKeyOptions("keyName", KeyType.RSA) + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + + keyAsyncClient.createKey(createKeyOptions) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(key -> + System.out.printf("Created key with name: %s and id: %s %n", key.getName(), + key.getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.createKey#CreateKeyOptions + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.createRsaKey#CreateRsaKeyOptions + CreateRsaKeyOptions createRsaKeyOptions = new CreateRsaKeyOptions("keyName") + .setKeySize(2048) + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + + keyAsyncClient.createRsaKey(createRsaKeyOptions) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(rsaKey -> + System.out.printf("Created key with name: %s and id: %s %n", rsaKey.getName(), + rsaKey.getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.createRsaKey#CreateRsaKeyOptions + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.createEcKey#CreateEcKeyOptions + CreateEcKeyOptions createEcKeyOptions = new CreateEcKeyOptions("keyName") + .setCurveName(KeyCurveName.P_384) + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + + keyAsyncClient.createEcKey(createEcKeyOptions) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(ecKey -> + System.out.printf("Created key with name: %s and id: %s %n", ecKey.getName(), + ecKey.getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.createEcKey#CreateEcKeyOptions + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.createOctKey#CreateOctKeyOptions + CreateOctKeyOptions createOctKeyOptions = new CreateOctKeyOptions("keyName") + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + + keyAsyncClient.createOctKey(createOctKeyOptions) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(octKey -> + System.out.printf("Created key with name: %s and id: %s %n", octKey.getName(), + octKey.getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.createOctKey#CreateOctKeyOptions + } + + /** + * Generates code samples for using {@link KeyAsyncClient#importKey(String, JsonWebKey)}, + * {@link KeyAsyncClient#importKey(ImportKeyOptions)} and + * {@link KeyAsyncClient#importKeyWithResponse(ImportKeyOptions)}. + */ + public void importKey() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + JsonWebKey jsonWebKeyToImport = new JsonWebKey(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.importKey#String-JsonWebKey + keyAsyncClient.importKey("keyName", jsonWebKeyToImport) + .subscribe(keyVaultKey -> + System.out.printf("Imported key with name: %s and id: %s%n", keyVaultKey.getName(), + keyVaultKey.getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.importKey#String-JsonWebKey + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.importKey#ImportKeyOptions + ImportKeyOptions options = new ImportKeyOptions("keyName", jsonWebKeyToImport) + .setHardwareProtected(false); + + keyAsyncClient.importKey(options).subscribe(keyVaultKey -> + System.out.printf("Imported key with name: %s and id: %s%n", keyVaultKey.getName(), keyVaultKey.getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.importKey#ImportKeyOptions + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.importKeyWithResponse#ImportKeyOptions + ImportKeyOptions importKeyOptions = new ImportKeyOptions("keyName", jsonWebKeyToImport) + .setHardwareProtected(false); + + keyAsyncClient.importKeyWithResponse(importKeyOptions).subscribe(response -> + System.out.printf("Imported key with name: %s and id: %s%n", response.getValue().getName(), + response.getValue().getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.importKeyWithResponse#ImportKeyOptions + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#beginDeleteKey(String)}. + */ + public void beginDeleteKey() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.deleteKey#String + keyAsyncClient.beginDeleteKey("keyName") + .subscribe(pollResponse -> { + System.out.printf("Deletion status: %s%n", pollResponse.getStatus()); + System.out.printf("Key name: %s%n", pollResponse.getValue().getName()); + System.out.printf("Key delete date: %s%n", pollResponse.getValue().getDeletedOn()); + }); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.deleteKey#String + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#getDeletedKey(String)}. + */ + public void getDeletedKey() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.getDeletedKey#String + keyAsyncClient.getDeletedKey("keyName") + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(deletedKey -> + System.out.printf("Deleted key's recovery id:%s%n", deletedKey.getRecoveryId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.getDeletedKey#String + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#createKeyWithResponse(CreateKeyOptions)}, + * {@link KeyAsyncClient#createRsaKeyWithResponse(CreateRsaKeyOptions)}, + * {@link KeyAsyncClient#createEcKeyWithResponse(CreateEcKeyOptions)} and + * {@link KeyAsyncClient#createOctKeyWithResponse(CreateOctKeyOptions)}. + */ + public void createKeyWithResponse() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.createKeyWithResponse#CreateKeyOptions + CreateKeyOptions createKeyOptions = new CreateKeyOptions("keyName", KeyType.RSA) + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + + keyAsyncClient.createKeyWithResponse(createKeyOptions) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(createKeyResponse -> + System.out.printf("Created key with name: %s and: id %s%n", createKeyResponse.getValue().getName(), + createKeyResponse.getValue().getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.createKeyWithResponse#CreateKeyOptions + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.createRsaKeyWithResponse#CreateRsaKeyOptions + CreateRsaKeyOptions createRsaKeyOptions = new CreateRsaKeyOptions("keyName") + .setKeySize(2048) + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + + keyAsyncClient.createRsaKeyWithResponse(createRsaKeyOptions) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(createRsaKeyResponse -> + System.out.printf("Created key with name: %s and: id %s%n", createRsaKeyResponse.getValue().getName(), + createRsaKeyResponse.getValue().getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.createRsaKeyWithResponse#CreateRsaKeyOptions + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.createEcKeyWithResponse#CreateEcKeyOptions + CreateEcKeyOptions createEcKeyOptions = new CreateEcKeyOptions("keyName") + .setCurveName(KeyCurveName.P_384) + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + + keyAsyncClient.createEcKeyWithResponse(createEcKeyOptions) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(createEcKeyResponse -> + System.out.printf("Created key with name: %s and: id %s%n", createEcKeyResponse.getValue().getName(), + createEcKeyResponse.getValue().getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.createEcKeyWithResponse#CreateEcKeyOptions + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.createOctKeyWithResponse#CreateOctKeyOptions + CreateOctKeyOptions createOctKeyOptions = new CreateOctKeyOptions("keyName") + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + + keyAsyncClient.createOctKeyWithResponse(createOctKeyOptions) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(createOctKeyResponse -> + System.out.printf("Created key with name: %s and: id %s%n", createOctKeyResponse.getValue().getName(), + createOctKeyResponse.getValue().getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.createOctKeyWithResponse#CreateOctKeyOptions + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#getKeyWithResponse(String, String)}. + */ + public void getKeyWithResponse() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.getKeyWithResponse#String-String + String keyVersion = "6A385B124DEF4096AF1361A85B16C204"; + + keyAsyncClient.getKeyWithResponse("keyName", keyVersion) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(getKeyResponse -> + System.out.printf("Created key with name: %s and: id %s%n", + getKeyResponse.getValue().getName(), getKeyResponse.getValue().getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.getKeyWithResponse#String-String + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#getKey(String, String)}. + */ + public void getKey() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.getKey#String + keyAsyncClient.getKey("keyName") + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(key -> + System.out.printf("Created key with name: %s and: id %s%n", key.getName(), + key.getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.getKey#String + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.getKey#String-String + String keyVersion = "6A385B124DEF4096AF1361A85B16C204"; + + keyAsyncClient.getKey("keyName", keyVersion) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(key -> + System.out.printf("Created key with name: %s and: id %s%n", key.getName(), + key.getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.getKey#String-String + } + + /** + * Generates a code sample for using + * {@link KeyAsyncClient#updateKeyPropertiesWithResponse(KeyProperties, KeyOperation...)}. + */ + public void updateKeyPropertiesWithResponse() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.updateKeyPropertiesWithResponse#KeyProperties-KeyOperation + keyAsyncClient.getKey("keyName") + .subscribe(getKeyResponse -> { + //Update the not before time of the key. + getKeyResponse.getProperties().setNotBefore(OffsetDateTime.now().plusDays(50)); + keyAsyncClient.updateKeyPropertiesWithResponse(getKeyResponse.getProperties(), KeyOperation.ENCRYPT, + KeyOperation.DECRYPT) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(updateKeyResponse -> + System.out.printf("Updated key's \"not before time\": %s%n", + updateKeyResponse.getValue().getProperties().getNotBefore().toString())); + }); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.updateKeyPropertiesWithResponse#KeyProperties-KeyOperation + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#updateKeyProperties(KeyProperties, KeyOperation...)}. + */ + public void updateKeyProperties() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.updateKeyProperties#KeyProperties-KeyOperation + keyAsyncClient.getKey("keyName") + .subscribe(key -> { + //Update the not before time of the key. + key.getProperties().setNotBefore(OffsetDateTime.now().plusDays(50)); + keyAsyncClient.updateKeyProperties(key.getProperties(), KeyOperation.ENCRYPT, + KeyOperation.DECRYPT) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(updatedKey -> + System.out.printf("Updated key's \"not before time\": %s%n", + updatedKey.getProperties().getNotBefore().toString())); + }); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.updateKeyProperties#KeyProperties-KeyOperation + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#getDeletedKeyWithResponse(String)}. + */ + public void getDeletedKeyWithResponse() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.getDeletedKeyWithResponse#String + keyAsyncClient.getDeletedKeyWithResponse("keyName") + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(getDeletedKeyResponse -> + System.out.printf("Deleted key's recovery id: %s%n", getDeletedKeyResponse.getValue().getRecoveryId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.getDeletedKeyWithResponse#String + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#purgeDeletedKey(String)}. + */ + public void purgeDeletedKey() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.purgeDeletedKey#String + keyAsyncClient.purgeDeletedKey("deletedKeyName") + .subscribe(ignored -> + System.out.println("Successfully purged deleted key")); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.purgeDeletedKey#String + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#purgeDeletedKeyWithResponse(String)}. + */ + public void purgeDeletedKeyWithResponse() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.purgeDeletedKeyWithResponse#String + keyAsyncClient.purgeDeletedKeyWithResponse("deletedKeyName") + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(purgeDeletedKeyResponse -> + System.out.printf("Purge response status code: %d%n", purgeDeletedKeyResponse.getStatusCode())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.purgeDeletedKeyWithResponse#String + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#beginRecoverDeletedKey(String)}. + */ + public void beginRecoverDeletedKey() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.recoverDeletedKey#String + keyAsyncClient.beginRecoverDeletedKey("deletedKeyName") + .subscribe(pollResponse -> { + System.out.printf("Recovery status: %s%n", pollResponse.getStatus()); + System.out.printf("Key name: %s%n", pollResponse.getValue().getName()); + System.out.printf("Key type: %s%n", pollResponse.getValue().getKeyType()); + }); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.recoverDeletedKey#String + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#backupKey(String)}. + */ + public void backupKey() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.backupKey#String + keyAsyncClient.backupKey("keyName") + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(bytes -> + System.out.printf("Key backup byte array length: %s%n", bytes.length)); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.backupKey#String + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#backupKeyWithResponse(String)}. + */ + public void backupKeyWithResponse() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.backupKeyWithResponse#String + keyAsyncClient.backupKeyWithResponse("keyName") + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(backupKeyResponse -> + System.out.printf("Key backup byte array length: %s%n", backupKeyResponse.getValue().length)); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.backupKeyWithResponse#String + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#restoreKeyBackup}. + */ + public void restoreKeyBackup() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + byte[] keyBackupByteArray = {}; + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.restoreKeyBackup#byte + keyAsyncClient.restoreKeyBackup(keyBackupByteArray) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(restoreKeyResponse -> + System.out.printf("Restored key with name: %s and: id %s%n", restoreKeyResponse.getName(), + restoreKeyResponse.getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.restoreKeyBackup#byte + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#restoreKeyBackupWithResponse(byte[])}. + */ + public void restoreKeyBackupWithResponse() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + byte[] keyBackupByteArray = {}; + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.restoreKeyBackupWithResponse#byte + keyAsyncClient.restoreKeyBackupWithResponse(keyBackupByteArray) + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(restoreKeyBackupResponse -> + System.out.printf("Restored key with name: %s and: id %s%n", + restoreKeyBackupResponse.getValue().getName(), restoreKeyBackupResponse.getValue().getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.restoreKeyBackupWithResponse#byte + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#listPropertiesOfKeys}. + */ + public void listPropertiesOfKeys() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.listPropertiesOfKeys + keyAsyncClient.listPropertiesOfKeys() + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .flatMap(keyProperties -> keyAsyncClient.getKey(keyProperties.getName(), keyProperties.getVersion())) + .subscribe(key -> System.out.printf("Retrieved key with name: %s and type: %s%n", + key.getName(), + key.getKeyType())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.listPropertiesOfKeys + } + + /** + * Generates a code sample for using {@link KeyAsyncClient#listDeletedKeys()}. + */ + public void listDeletedKeys() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.listDeletedKeys + keyAsyncClient.listDeletedKeys() + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .subscribe(deletedKey -> + System.out.printf("Deleted key's recovery id:%s%n", deletedKey.getRecoveryId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.listDeletedKeys + } + + /** + * Generates code sample for using {@link KeyAsyncClient#listPropertiesOfKeyVersions(String)}. + */ + public void listPropertiesOfKeyVersions() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.listKeyVersions + keyAsyncClient.listPropertiesOfKeyVersions("keyName") + .contextWrite(Context.of("key1", "value1", "key2", "value2")) + .flatMap(keyProperties -> keyAsyncClient.getKey(keyProperties.getName(), keyProperties.getVersion())) + .subscribe(key -> + System.out.printf("Retrieved key version: %s with name: %s and type: %s%n", + key.getProperties().getVersion(), key.getName(), key.getKeyType())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.listKeyVersions + } + + /** + * Generates code samples for using {@link KeyAsyncClient#getRandomBytes(int)} and + * {@link KeyAsyncClient#getRandomBytesWithResponse(int)}. + */ + public void getRandomBytes() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.getRandomBytes#int + int amount = 16; + keyAsyncClient.getRandomBytes(amount) + .subscribe(randomBytes -> + System.out.printf("Retrieved %d random bytes: %s%n", amount, Arrays.toString(randomBytes))); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.getRandomBytes#int + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.getRandomBytesWithResponse#int + int amountOfBytes = 16; + keyAsyncClient.getRandomBytesWithResponse(amountOfBytes).subscribe(response -> + System.out.printf("Response received successfully with status code: %d. Retrieved %d random bytes: %s%n", + response.getStatusCode(), amountOfBytes, Arrays.toString(response.getValue()))); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.getRandomBytesWithResponse#int + } + + /** + * Generates code samples for using {@link KeyAsyncClient#releaseKey(String, String)}, + * {@link KeyAsyncClient#releaseKey(String, String, String)} and + * {@link KeyAsyncClient#releaseKeyWithResponse(String, String, String, ReleaseKeyOptions)}. + */ + public void releaseKey() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.releaseKey#String-String + String targetAttestationToken = "someAttestationToken"; + + keyAsyncClient.releaseKey("keyName", targetAttestationToken) + .subscribe(releaseKeyResult -> + System.out.printf("Signed object containing released key: %s%n", releaseKeyResult.getValue())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.releaseKey#String-String + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.releaseKey#String-String-String + String myKeyVersion = "6A385B124DEF4096AF1361A85B16C204"; + String myTargetAttestationToken = "someAttestationToken"; + + keyAsyncClient.releaseKey("keyName", myKeyVersion, myTargetAttestationToken) + .subscribe(releaseKeyResult -> + System.out.printf("Signed object containing released key: %s%n", releaseKeyResult.getValue())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.releaseKey#String-String-String + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.releaseKeyWithResponse#String-String-String-ReleaseKeyOptions + String releaseKeyVersion = "6A385B124DEF4096AF1361A85B16C204"; + String someTargetAttestationToken = "someAttestationToken"; + ReleaseKeyOptions releaseKeyOptions = new ReleaseKeyOptions() + .setAlgorithm(KeyExportEncryptionAlgorithm.RSA_AES_KEY_WRAP_256) + .setNonce("someNonce"); + + keyAsyncClient.releaseKeyWithResponse("keyName", releaseKeyVersion, someTargetAttestationToken, + releaseKeyOptions) + .subscribe(releaseKeyResponse -> + System.out.printf("Response received successfully with status code: %d. Signed object containing" + + "released key: %s%n", releaseKeyResponse.getStatusCode(), + releaseKeyResponse.getValue().getValue())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.releaseKeyWithResponse#String-String-String-ReleaseKeyOptions + } + + /** + * Generates code samples for using {@link KeyAsyncClient#rotateKey(String)} and + * {@link KeyAsyncClient#rotateKeyWithResponse(String)}. + */ + public void rotateKey() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.rotateKey#String + keyAsyncClient.rotateKey("keyName") + .subscribe(key -> + System.out.printf("Rotated key with name: %s and version:%s%n", key.getName(), + key.getProperties().getVersion())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.rotateKey#String + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.rotateKeyWithResponse#String + keyAsyncClient.rotateKeyWithResponse("keyName") + .subscribe(rotateKeyResponse -> + System.out.printf("Response received successfully with status code: %d. Rotated key with name: %s and" + + "version: %s%n", rotateKeyResponse.getStatusCode(), rotateKeyResponse.getValue().getName(), + rotateKeyResponse.getValue().getProperties().getVersion())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.rotateKeyWithResponse#String + } + + /** + * Generates code samples for using {@link KeyAsyncClient#getKeyRotationPolicy(String)} and + * {@link KeyAsyncClient#getKeyRotationPolicyWithResponse(String)}. + */ + public void getKeyRotationPolicy() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.getKeyRotationPolicy#String + keyAsyncClient.getKeyRotationPolicy("keyName") + .subscribe(keyRotationPolicy -> + System.out.printf("Retrieved key rotation policy with id: %s%n", keyRotationPolicy.getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.getKeyRotationPolicy#String + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.getKeyRotationPolicyWithResponse#String + keyAsyncClient.getKeyRotationPolicyWithResponse("keyName") + .subscribe(getKeyRotationPolicyResponse -> + System.out.printf("Response received successfully with status code: %d. Retrieved key rotation policy" + + "with id: %s%n", getKeyRotationPolicyResponse.getStatusCode(), + getKeyRotationPolicyResponse.getValue().getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.getKeyRotationPolicyWithResponse#String + } + + /** + * Generates code samples for using + * {@link KeyAsyncClient#updateKeyRotationPolicy(String, KeyRotationPolicy)} and + * {@link KeyAsyncClient#updateKeyRotationPolicyWithResponse(String, KeyRotationPolicy)}. + */ + public void updateKeyRotationPolicy() { + KeyAsyncClient keyAsyncClient = createAsyncClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.updateKeyRotationPolicy#String-KeyRotationPolicy + List lifetimeActions = new ArrayList<>(); + KeyRotationLifetimeAction rotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE) + .setTimeAfterCreate("P90D"); + KeyRotationLifetimeAction notifyLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.NOTIFY) + .setTimeBeforeExpiry("P45D"); + + lifetimeActions.add(rotateLifetimeAction); + lifetimeActions.add(notifyLifetimeAction); + + KeyRotationPolicy keyRotationPolicy = new KeyRotationPolicy() + .setLifetimeActions(lifetimeActions) + .setExpiresIn("P6M"); + + keyAsyncClient.updateKeyRotationPolicy("keyName", keyRotationPolicy) + .subscribe(updatedPolicy -> + System.out.printf("Updated key rotation policy with id: %s%n", updatedPolicy.getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.updateKeyRotationPolicy#String-KeyRotationPolicy + + // BEGIN: com.azure.security.keyvault.keys.KeyAsyncClient.updateKeyRotationPolicyWithResponse#String-KeyRotationPolicy + List myLifetimeActions = new ArrayList<>(); + KeyRotationLifetimeAction myRotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE) + .setTimeAfterCreate("P90D"); + KeyRotationLifetimeAction myNotifyLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.NOTIFY) + .setTimeBeforeExpiry("P45D"); + + myLifetimeActions.add(myRotateLifetimeAction); + myLifetimeActions.add(myNotifyLifetimeAction); + + KeyRotationPolicy myKeyRotationPolicy = new KeyRotationPolicy() + .setLifetimeActions(myLifetimeActions) + .setExpiresIn("P6M"); + + keyAsyncClient.updateKeyRotationPolicyWithResponse("keyName", myKeyRotationPolicy) + .subscribe(myUpdatedPolicyResponse -> + System.out.printf("Response received successfully with status code: %d. Updated key rotation policy" + + "with id: %s%n", myUpdatedPolicyResponse.getStatusCode(), + myUpdatedPolicyResponse.getValue().getId())); + // END: com.azure.security.keyvault.keys.KeyAsyncClient.updateKeyRotationPolicyWithResponse#String-KeyRotationPolicy + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample6/v1/KeyClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample6/v1/KeyClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..b97130754501 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample6/v1/KeyClientJavaDocCodeSnippets.java @@ -0,0 +1,662 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys; + +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.keys.models.CreateEcKeyOptions; +import com.azure.security.keyvault.keys.models.CreateKeyOptions; +import com.azure.security.keyvault.keys.models.CreateOctKeyOptions; +import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; +import com.azure.security.keyvault.keys.models.DeletedKey; +import com.azure.security.keyvault.keys.models.ImportKeyOptions; +import com.azure.security.keyvault.keys.models.JsonWebKey; +import com.azure.security.keyvault.keys.models.KeyCurveName; +import com.azure.security.keyvault.keys.models.KeyExportEncryptionAlgorithm; +import com.azure.security.keyvault.keys.models.KeyOperation; +import com.azure.security.keyvault.keys.models.KeyProperties; +import com.azure.security.keyvault.keys.models.KeyRotationLifetimeAction; +import com.azure.security.keyvault.keys.models.KeyRotationPolicy; +import com.azure.security.keyvault.keys.models.KeyRotationPolicyAction; +import com.azure.security.keyvault.keys.models.KeyType; +import com.azure.security.keyvault.keys.models.KeyVaultKey; +import com.azure.security.keyvault.keys.models.ReleaseKeyOptions; +import com.azure.security.keyvault.keys.models.ReleaseKeyResult; + +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * This class contains code samples for generating javadocs through doclets for {@link KeyClient}. + */ +public final class KeyClientJavaDocCodeSnippets { + /** + * Generates a code sample for creating a {@link KeyClient}. + * + * @return An instance of {@link KeyClient}. + */ + public KeyClient createClient() { + // BEGIN: com.azure.security.keyvault.keys.KeyClient.instantiation + KeyClient keyClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + // END: com.azure.security.keyvault.keys.KeyClient.instantiation + return keyClient; + } + + /** + * Generates a code sample for using {@link KeyClient#createKey(String, KeyType)}, + * {@link KeyClient#createRsaKey(CreateRsaKeyOptions)}, + * {@link KeyClient#createEcKey(CreateEcKeyOptions)} and + * {@link KeyClient#createOctKey(CreateOctKeyOptions)}. + */ + public void createKey() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.createKey#String-KeyType + KeyVaultKey key = keyClient.createKey("keyName", KeyType.EC); + System.out.printf("Created key with name: %s and id: %s%n", key.getName(), key.getId()); + // END: com.azure.security.keyvault.keys.KeyClient.createKey#String-KeyType + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.createKey#CreateKeyOptions + CreateKeyOptions createKeyOptions = new CreateKeyOptions("keyName", KeyType.RSA) + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + KeyVaultKey optionsKey = keyClient.createKey(createKeyOptions); + + System.out.printf("Created key with name: %s and id: %s%n", optionsKey.getName(), optionsKey.getId()); + // END: com.azure.security.keyvault.keys.KeyClient.createKey#CreateKeyOptions + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.createRsaKey#CreateRsaKeyOptions + CreateRsaKeyOptions createRsaKeyOptions = new CreateRsaKeyOptions("keyName") + .setKeySize(2048) + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + KeyVaultKey rsaKey = keyClient.createRsaKey(createRsaKeyOptions); + + System.out.printf("Created key with name: %s and id: %s%n", rsaKey.getName(), rsaKey.getId()); + // END: com.azure.security.keyvault.keys.KeyClient.createRsaKey#CreateRsaKeyOptions + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.createEcKey#CreateOctKeyOptions + CreateEcKeyOptions createEcKeyOptions = new CreateEcKeyOptions("keyName") + .setCurveName(KeyCurveName.P_384) + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + KeyVaultKey ecKey = keyClient.createEcKey(createEcKeyOptions); + + System.out.printf("Created key with name: %s and id: %s%n", ecKey.getName(), ecKey.getId()); + // END: com.azure.security.keyvault.keys.KeyClient.createEcKey#CreateOctKeyOptions + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.createOctKey#CreateOctKeyOptions + CreateOctKeyOptions createOctKeyOptions = new CreateOctKeyOptions("keyName") + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + KeyVaultKey octKey = keyClient.createOctKey(createOctKeyOptions); + + System.out.printf("Created key with name: %s and id: %s%n", octKey.getName(), octKey.getId()); + // END: com.azure.security.keyvault.keys.KeyClient.createOctKey#CreateOctKeyOptions + } + + /** + * Generates code samples for using {@link KeyAsyncClient#importKey(String, JsonWebKey)}, + * {@link KeyAsyncClient#importKey(ImportKeyOptions)} and + * {@link KeyAsyncClient#importKeyWithResponse(ImportKeyOptions)}. + */ + public void importKey() { + KeyClient keyClient = createClient(); + JsonWebKey jsonWebKeyToImport = new JsonWebKey(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.importKey#String-JsonWebKey + KeyVaultKey key = keyClient.importKey("keyName", jsonWebKeyToImport); + + System.out.printf("Imported key with name: %s and id: %s%n", key.getName(), key.getId()); + // END: com.azure.security.keyvault.keys.KeyClient.importKey#String-JsonWebKey + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.importKey#ImportKeyOptions + ImportKeyOptions options = new ImportKeyOptions("keyName", jsonWebKeyToImport) + .setHardwareProtected(false); + KeyVaultKey importedKey = keyClient.importKey(options); + + System.out.printf("Imported key with name: %s and id: %s%n", importedKey.getName(), + importedKey.getId()); + // END: com.azure.security.keyvault.keys.KeyClient.importKey#ImportKeyOptions + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.importKeyWithResponse#ImportKeyOptions-Context + ImportKeyOptions importKeyOptions = new ImportKeyOptions("keyName", jsonWebKeyToImport) + .setHardwareProtected(false); + Response response = + keyClient.importKeyWithResponse(importKeyOptions, new Context("key1", "value1")); + + System.out.printf("Imported key with name: %s and id: %s%n", response.getValue().getName(), + response.getValue().getId()); + // END: com.azure.security.keyvault.keys.KeyClient.importKeyWithResponse#ImportKeyOptions-Context + } + + /** + * Generates a code sample for using {@link KeyClient#beginDeleteKey(String)}. + */ + public void beginDeleteKey() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.deleteKey#String + SyncPoller deleteKeyPoller = keyClient.beginDeleteKey("keyName"); + PollResponse deleteKeyPollResponse = deleteKeyPoller.poll(); + + // Deleted date only works for SoftDelete Enabled Key Vault. + DeletedKey deletedKey = deleteKeyPollResponse.getValue(); + + System.out.printf("Key delete date: %s%n", deletedKey.getDeletedOn()); + System.out.printf("Deleted key's recovery id: %s%n", deletedKey.getRecoveryId()); + + // Key is being deleted on the server. + deleteKeyPoller.waitForCompletion(); + // Key is deleted + // END: com.azure.security.keyvault.keys.KeyClient.deleteKey#String + } + + /** + * Generates a code sample for using {@link KeyClient#getDeletedKey(String)}. + */ + public void getDeletedKey() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.getDeletedKey#String + DeletedKey deletedKey = keyClient.getDeletedKey("keyName"); + + System.out.printf("Deleted key's recovery id: %s%n", deletedKey.getRecoveryId()); + // END: com.azure.security.keyvault.keys.KeyClient.getDeletedKey#String + } + + /** + * Generates a code sample for using {@link KeyClient#createKeyWithResponse(CreateKeyOptions, Context)}, + * {@link KeyClient#createRsaKeyWithResponse(CreateRsaKeyOptions, Context)}, + * {@link KeyClient#createEcKeyWithResponse(CreateEcKeyOptions, Context)} and + * {@link KeyClient#createOctKeyWithResponse(CreateOctKeyOptions, Context)}. + */ + public void createKeyWithResponse() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.createKeyWithResponse#CreateKeyOptions-Context + CreateKeyOptions createKeyOptions = new CreateKeyOptions("keyName", KeyType.RSA) + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + Response createKeyResponse = + keyClient.createKeyWithResponse(createKeyOptions, new Context("key1", "value1")); + + System.out.printf("Created key with name: %s and: id %s%n", createKeyResponse.getValue().getName(), + createKeyResponse.getValue().getId()); + // END: com.azure.security.keyvault.keys.KeyClient.createKeyWithResponse#CreateKeyOptions-Context + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.createRsaKeyWithResponse#CreateRsaKeyOptions-Context + CreateRsaKeyOptions createRsaKeyOptions = new CreateRsaKeyOptions("keyName") + .setKeySize(2048) + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + Response createRsaKeyResponse = + keyClient.createRsaKeyWithResponse(createRsaKeyOptions, new Context("key1", "value1")); + + System.out.printf("Created key with name: %s and: id %s%n", createRsaKeyResponse.getValue().getName(), + createRsaKeyResponse.getValue().getId()); + // END: com.azure.security.keyvault.keys.KeyClient.createRsaKeyWithResponse#CreateRsaKeyOptions-Context + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.createEcKeyWithResponse#CreateEcKeyOptions-Context + CreateEcKeyOptions createEcKeyOptions = new CreateEcKeyOptions("keyName") + .setCurveName(KeyCurveName.P_384) + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + Response createEcKeyResponse = + keyClient.createEcKeyWithResponse(createEcKeyOptions, new Context("key1", "value1")); + + System.out.printf("Created key with name: %s and: id %s%n", createEcKeyResponse.getValue().getName(), + createEcKeyResponse.getValue().getId()); + // END: com.azure.security.keyvault.keys.KeyClient.createEcKeyWithResponse#CreateEcKeyOptions-Context + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.createOctKey#CreateOctKeyOptions-Context + CreateOctKeyOptions createOctKeyOptions = new CreateOctKeyOptions("keyName") + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + Response createOctKeyResponse = + keyClient.createOctKeyWithResponse(createOctKeyOptions, new Context("key1", "value1")); + + System.out.printf("Created key with name: %s and: id %s%n", createOctKeyResponse.getValue().getName(), + createOctKeyResponse.getValue().getId()); + // END: com.azure.security.keyvault.keys.KeyClient.createOctKey#CreateOctKeyOptions-Context + } + + /** + * Generates a code sample for using {@link KeyClient#getKeyWithResponse(String, String, Context)}. + */ + public void getKeyWithResponse() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.getKeyWithResponse#String-String-Context + String keyVersion = "6A385B124DEF4096AF1361A85B16C204"; + Response getKeyResponse = + keyClient.getKeyWithResponse("keyName", keyVersion, new Context("key1", "value1")); + + System.out.printf("Retrieved key with name: %s and: id %s%n", getKeyResponse.getValue().getName(), + getKeyResponse.getValue().getId()); + // END: com.azure.security.keyvault.keys.KeyClient.getKeyWithResponse#String-String-Context + } + + /** + * Generates a code sample for using {@link KeyClient#getKey(String)} and + * {@link KeyClient#getKey(String, String)}. + */ + public void getKey() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.getKey#String + KeyVaultKey keyWithVersionValue = keyClient.getKey("keyName"); + + System.out.printf("Retrieved key with name: %s and: id %s%n", keyWithVersionValue.getName(), + keyWithVersionValue.getId()); + // END: com.azure.security.keyvault.keys.KeyClient.getKey#String + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.getKey#String-String + String keyVersion = "6A385B124DEF4096AF1361A85B16C204"; + KeyVaultKey keyWithVersion = keyClient.getKey("keyName", keyVersion); + + System.out.printf("Retrieved key with name: %s and: id %s%n", keyWithVersion.getName(), + keyWithVersion.getId()); + // END: com.azure.security.keyvault.keys.KeyClient.getKey#String-String + } + + /** + * Generates a code sample for using + * {@link KeyClient#updateKeyPropertiesWithResponse(KeyProperties, Context, KeyOperation...)}. + */ + public void updateKeyPropertiesWithResponse() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.updateKeyPropertiesWithResponse#KeyProperties-Context-KeyOperation + KeyVaultKey key = keyClient.getKey("keyName"); + + key.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(60)); + + Response updateKeyResponse = + keyClient.updateKeyPropertiesWithResponse(key.getProperties(), new Context("key1", "value1"), + KeyOperation.ENCRYPT, KeyOperation.DECRYPT); + + System.out.printf("Updated key with name: %s and id: %s%n", updateKeyResponse.getValue().getName(), + updateKeyResponse.getValue().getId()); + // END: com.azure.security.keyvault.keys.KeyClient.updateKeyPropertiesWithResponse#KeyProperties-Context-KeyOperation + } + + /** + * Generates a code sample for using {@link KeyClient#updateKeyProperties(KeyProperties, KeyOperation...)}. + */ + public void updateKeyProperties() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.updateKeyProperties#KeyProperties-KeyOperation + KeyVaultKey key = keyClient.getKey("keyName"); + + key.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(60)); + + KeyVaultKey updatedKey = keyClient.updateKeyProperties(key.getProperties(), KeyOperation.ENCRYPT, + KeyOperation.DECRYPT); + + System.out.printf("Key is updated with name %s and id %s %n", updatedKey.getName(), updatedKey.getId()); + // END: com.azure.security.keyvault.keys.KeyClient.updateKeyProperties#KeyProperties-KeyOperation + } + + /** + * Generates a code sample for using {@link KeyClient#getDeletedKeyWithResponse(String, Context)}. + */ + public void getDeletedKeyWithResponse() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.getDeletedKeyWithResponse#String-Context + Response deletedKeyResponse = + keyClient.getDeletedKeyWithResponse("keyName", new Context("key1", "value1")); + + System.out.printf("Deleted key with recovery id: %s%n", deletedKeyResponse.getValue().getRecoveryId()); + // END: com.azure.security.keyvault.keys.KeyClient.getDeletedKeyWithResponse#String-Context + } + + /** + * Generates a code sample for using {@link KeyClient#purgeDeletedKey(String)}. + */ + public void purgeDeletedKey() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.purgeDeletedKey#String + keyClient.purgeDeletedKey("deletedKeyName"); + // END: com.azure.security.keyvault.keys.KeyClient.purgeDeletedKey#String + } + + /** + * Generates a code sample for using {@link KeyClient#purgeDeletedKeyWithResponse(String, Context)}. + */ + public void purgeDeletedKeyWithResponse() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.purgeDeletedKeyWithResponse#String-Context + Response purgeDeletedKeyResponse = keyClient.purgeDeletedKeyWithResponse("deletedKeyName", + new Context("key1", "value1")); + + System.out.printf("Purge response status code: %d%n", purgeDeletedKeyResponse.getStatusCode()); + // END: com.azure.security.keyvault.keys.KeyClient.purgeDeletedKeyWithResponse#String-Context + } + + /** + * Generates a code sample for using {@link KeyClient#beginRecoverDeletedKey(String)}. + */ + public void beginRecoverDeletedKey() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.recoverDeletedKey#String + SyncPoller recoverKeyPoller = keyClient.beginRecoverDeletedKey("deletedKeyName"); + + PollResponse recoverKeyPollResponse = recoverKeyPoller.poll(); + + KeyVaultKey recoveredKey = recoverKeyPollResponse.getValue(); + System.out.printf("Recovered key name: %s%n", recoveredKey.getName()); + System.out.printf("Recovered key id: %s%n", recoveredKey.getId()); + + // Key is being recovered on the server. + recoverKeyPoller.waitForCompletion(); + // Key is recovered + // END: com.azure.security.keyvault.keys.KeyClient.recoverDeletedKey#String + } + + /** + * Generates a code sample for using {@link KeyClient#backupKey(String)}. + */ + public void backupKey() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.backupKey#String + byte[] keyBackup = keyClient.backupKey("keyName"); + + System.out.printf("Key backup byte array length: %s%n", keyBackup.length); + // END: com.azure.security.keyvault.keys.KeyClient.backupKey#String + } + + /** + * Generates a code sample for using {@link KeyClient#backupKeyWithResponse(String, Context)}. + */ + public void backupKeyWithResponse() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.backupKeyWithResponse#String-Context + Response backupKeyResponse = keyClient.backupKeyWithResponse("keyName", new Context("key1", "value1")); + + System.out.printf("Key backup byte array length: %s%n", backupKeyResponse.getValue().length); + // END: com.azure.security.keyvault.keys.KeyClient.backupKeyWithResponse#String-Context + } + + /** + * Generates a code sample for using {@link KeyClient#restoreKeyBackup}. + */ + public void restoreKeyBackup() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.restoreKeyBackup#byte + byte[] keyBackupByteArray = {}; + KeyVaultKey keyResponse = keyClient.restoreKeyBackup(keyBackupByteArray); + System.out.printf("Restored key with name: %s and: id %s%n", keyResponse.getName(), keyResponse.getId()); + // END: com.azure.security.keyvault.keys.KeyClient.restoreKeyBackup#byte + } + + /** + * Generates a code sample for using {@link KeyClient#restoreKeyBackupWithResponse(byte[], Context)}. + */ + public void restoreKeyBackupWithResponse() { + KeyClient keyClient = createClient(); + byte[] keyBackupByteArray = {}; + // BEGIN: com.azure.security.keyvault.keys.KeyClient.restoreKeyBackupWithResponse#byte-Context + Response keyResponse = keyClient.restoreKeyBackupWithResponse(keyBackupByteArray, + new Context("key1", "value1")); + + System.out.printf("Restored key with name: %s and: id %s%n", + keyResponse.getValue().getName(), keyResponse.getValue().getId()); + // END: com.azure.security.keyvault.keys.KeyClient.restoreKeyBackupWithResponse#byte-Context + } + + /** + * Generates a code sample for using {@link KeyClient#listPropertiesOfKeys()} and + * {@link KeyClient#listPropertiesOfKeys(Context)}. + */ + public void listPropertiesOfKeys() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeys + for (KeyProperties keyProperties : keyClient.listPropertiesOfKeys()) { + KeyVaultKey key = keyClient.getKey(keyProperties.getName(), keyProperties.getVersion()); + + System.out.printf("Retrieved key with name: %s and type: %s%n", key.getName(), key.getKeyType()); + } + // END: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeys + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeys#Context + for (KeyProperties keyProperties : keyClient.listPropertiesOfKeys(new Context("key1", "value1"))) { + KeyVaultKey key = keyClient.getKey(keyProperties.getName(), keyProperties.getVersion()); + + System.out.printf("Retrieved key with name: %s and type: %s%n", key.getName(), + key.getKeyType()); + } + // END: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeys#Context + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeys.iterableByPage + keyClient.listPropertiesOfKeys().iterableByPage().forEach(pagedResponse -> { + System.out.printf("Got response details. Url: %s. Status code: %d.%n", + pagedResponse.getRequest().getUrl(), pagedResponse.getStatusCode()); + pagedResponse.getElements().forEach(keyProperties -> { + KeyVaultKey key = keyClient.getKey(keyProperties.getName(), keyProperties.getVersion()); + + System.out.printf("Retrieved key with name: %s and type: %s%n", key.getName(), + key.getKeyType()); + }); + }); + // END: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeys.iterableByPage + } + + /** + * Generates a code sample for using {@link KeyClient#listDeletedKeys()} and + * {@link KeyClient#listDeletedKeys(Context)}. + */ + public void listDeletedKeys() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.listDeletedKeys + for (DeletedKey deletedKey : keyClient.listDeletedKeys()) { + System.out.printf("Deleted key's recovery id:%s%n", deletedKey.getRecoveryId()); + } + // END: com.azure.security.keyvault.keys.KeyClient.listDeletedKeys + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.listDeletedKeys#Context + for (DeletedKey deletedKey : keyClient.listDeletedKeys(new Context("key1", "value1"))) { + System.out.printf("Deleted key's recovery id:%s%n", deletedKey.getRecoveryId()); + } + // END: com.azure.security.keyvault.keys.KeyClient.listDeletedKeys#Context + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.listDeletedKeys.iterableByPage + keyClient.listDeletedKeys().iterableByPage().forEach(pagedResponse -> { + System.out.printf("Got response details. Url: %s. Status code: %d.%n", + pagedResponse.getRequest().getUrl(), pagedResponse.getStatusCode()); + pagedResponse.getElements().forEach(deletedKey -> + System.out.printf("Deleted key's recovery id:%s%n", deletedKey.getRecoveryId())); + }); + // END: com.azure.security.keyvault.keys.KeyClient.listDeletedKeys.iterableByPage + } + + /** + * Generates code sample for using {@link KeyClient#listPropertiesOfKeyVersions(String)} and + * {@link KeyClient#listPropertiesOfKeyVersions(String, Context)}. + */ + public void listPropertiesOfKeyVersions() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeyVersions#String + for (KeyProperties keyProperties : keyClient.listPropertiesOfKeyVersions("keyName")) { + KeyVaultKey key = keyClient.getKey(keyProperties.getName(), keyProperties.getVersion()); + + System.out.printf("Retrieved key version: %s with name: %s and type: %s%n", + key.getProperties().getVersion(), key.getName(), key.getKeyType()); + } + // END: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeyVersions#String + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeyVersions#String-Context + for (KeyProperties keyProperties : keyClient.listPropertiesOfKeyVersions("keyName", new Context("key1", "value1"))) { + KeyVaultKey key = keyClient.getKey(keyProperties.getName(), keyProperties.getVersion()); + + System.out.printf("Retrieved key version: %s with name: %s and type: %s%n", + key.getProperties().getVersion(), key.getName(), key.getKeyType()); + } + // END: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeyVersions#String-Context + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeyVersions.iterableByPage + keyClient.listPropertiesOfKeyVersions("keyName").iterableByPage().forEach(pagedResponse -> { + System.out.printf("Got response details. Url: %s. Status code: %d.%n", + pagedResponse.getRequest().getUrl(), pagedResponse.getStatusCode()); + pagedResponse.getElements().forEach(keyProperties -> + System.out.printf("Key name: %s. Key version: %s.%n", keyProperties.getName(), + keyProperties.getVersion())); + }); + // END: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeyVersions.iterableByPage + } + + /** + * Generates code samples for using {@link KeyClient#getRandomBytes(int)} and + * {@link KeyClient#getRandomBytesWithResponse(int, Context)}. + */ + public void getRandomBytes() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.getRandomBytes#int + int amount = 16; + byte[] randomBytes = keyClient.getRandomBytes(amount); + + System.out.printf("Retrieved %d random bytes: %s%n", amount, Arrays.toString(randomBytes)); + // END: com.azure.security.keyvault.keys.KeyClient.getRandomBytes#int + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.getRandomBytesWithResponse#int-Context + int amountOfBytes = 16; + Response response = + keyClient.getRandomBytesWithResponse(amountOfBytes, new Context("key1", "value1")); + + System.out.printf("Response received successfully with status code: %d. Retrieved %d random bytes: %s%n", + response.getStatusCode(), amountOfBytes, Arrays.toString(response.getValue())); + // END: com.azure.security.keyvault.keys.KeyClient.getRandomBytesWithResponse#int-Context + } + + /** + * Generates code samples for using {@link KeyClient#releaseKey(String, String)}, + * {@link KeyClient#releaseKey(String, String, String)} and + * {@link KeyClient#releaseKeyWithResponse(String, String, String, ReleaseKeyOptions, Context)}. + */ + public void releaseKey() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.releaseKey#String-String + String targetAttestationToken = "someAttestationToken"; + ReleaseKeyResult releaseKeyResult = keyClient.releaseKey("keyName", targetAttestationToken); + + System.out.printf("Signed object containing released key: %s%n", releaseKeyResult); + // END: com.azure.security.keyvault.keys.KeyClient.releaseKey#String-String + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.releaseKey#String-String-String + String myKeyVersion = "6A385B124DEF4096AF1361A85B16C204"; + String myTargetAttestationToken = "someAttestationToken"; + ReleaseKeyResult releaseKeyVersionResult = + keyClient.releaseKey("keyName", myKeyVersion, myTargetAttestationToken); + + System.out.printf("Signed object containing released key: %s%n", releaseKeyVersionResult); + // END: com.azure.security.keyvault.keys.KeyClient.releaseKey#String-String-String + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.releaseKeyWithResponse#String-String-String-ReleaseKeyOptions-Context + String releaseKeyVersion = "6A385B124DEF4096AF1361A85B16C204"; + String someTargetAttestationToken = "someAttestationToken"; + ReleaseKeyOptions releaseKeyOptions = new ReleaseKeyOptions() + .setAlgorithm(KeyExportEncryptionAlgorithm.RSA_AES_KEY_WRAP_256) + .setNonce("someNonce"); + + Response releaseKeyResultResponse = + keyClient.releaseKeyWithResponse("keyName", releaseKeyVersion, someTargetAttestationToken, + releaseKeyOptions, new Context("key1", "value1")); + + System.out.printf("Response received successfully with status code: %d. Signed object containing" + + "released key: %s%n", releaseKeyResultResponse.getStatusCode(), + releaseKeyResultResponse.getValue().getValue()); + // END: com.azure.security.keyvault.keys.KeyClient.releaseKeyWithResponse#String-String-String-ReleaseKeyOptions-Context + } + + /** + * Generates code samples for using {@link KeyClient#rotateKey(String)} and + * {@link KeyClient#rotateKeyWithResponse(String, Context)}. + */ + public void rotateKey() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.rotateKeyWithResponse#String + KeyVaultKey key = keyClient.rotateKey("keyName"); + + System.out.printf("Rotated key with name: %s and version:%s%n", key.getName(), + key.getProperties().getVersion()); + // END: com.azure.security.keyvault.keys.KeyClient.rotateKeyWithResponse#String + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.rotateKeyWithResponse#String-Context + Response keyResponse = keyClient.rotateKeyWithResponse("keyName", new Context("key1", "value1")); + + System.out.printf("Response received successfully with status code: %d. Rotated key with name: %s and" + + "version: %s%n", keyResponse.getStatusCode(), keyResponse.getValue().getName(), + keyResponse.getValue().getProperties().getVersion()); + // END: com.azure.security.keyvault.keys.KeyClient.rotateKeyWithResponse#String-Context + } + + /** + * Generates code samples for using {@link KeyClient#getKeyRotationPolicy(String)} and + * {@link KeyClient#getKeyRotationPolicyWithResponse(String, Context)}. + */ + public void getKeyRotationPolicy() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.getKeyRotationPolicy#String + KeyRotationPolicy keyRotationPolicy = keyClient.getKeyRotationPolicy("keyName"); + + System.out.printf("Retrieved key rotation policy with id: %s%n", keyRotationPolicy.getId()); + // END: com.azure.security.keyvault.keys.KeyClient.getKeyRotationPolicy#String + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.getKeyRotationPolicyWithResponse#String-Context + Response keyRotationPolicyResponse = + keyClient.getKeyRotationPolicyWithResponse("keyName", new Context("key1", "value1")); + + System.out.printf("Response received successfully with status code: %d. Retrieved key rotation policy" + + "with id: %s%n", keyRotationPolicyResponse.getStatusCode(), keyRotationPolicyResponse.getValue().getId()); + // END: com.azure.security.keyvault.keys.KeyClient.getKeyRotationPolicyWithResponse#String-Context + } + + /** + * Generates code samples for using {@link KeyClient#updateKeyRotationPolicy(String, KeyRotationPolicy)} + * and {@link KeyClient#updateKeyRotationPolicyWithResponse(String, KeyRotationPolicy, Context)}. + */ + public void updateKeyRotationPolicy() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.updateKeyRotationPolicy#String-KeyRotationPolicy + List lifetimeActions = new ArrayList<>(); + KeyRotationLifetimeAction rotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE) + .setTimeAfterCreate("P90D"); + KeyRotationLifetimeAction notifyLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.NOTIFY) + .setTimeBeforeExpiry("P45D"); + + lifetimeActions.add(rotateLifetimeAction); + lifetimeActions.add(notifyLifetimeAction); + + KeyRotationPolicy keyRotationPolicy = new KeyRotationPolicy() + .setLifetimeActions(lifetimeActions) + .setExpiresIn("P6M"); + + KeyRotationPolicy updatedPolicy = + keyClient.updateKeyRotationPolicy("keyName", keyRotationPolicy); + + System.out.printf("Updated key rotation policy with id: %s%n", updatedPolicy.getId()); + // END: com.azure.security.keyvault.keys.KeyClient.updateKeyRotationPolicy#String-KeyRotationPolicy + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.updateKeyRotationPolicyWithResponse#String-KeyRotationPolicy-Context + List myLifetimeActions = new ArrayList<>(); + KeyRotationLifetimeAction myRotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE) + .setTimeAfterCreate("P90D"); + KeyRotationLifetimeAction myNotifyLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.NOTIFY) + .setTimeBeforeExpiry("P45D"); + + myLifetimeActions.add(myRotateLifetimeAction); + myLifetimeActions.add(myNotifyLifetimeAction); + + KeyRotationPolicy myKeyRotationPolicy = new KeyRotationPolicy() + .setLifetimeActions(myLifetimeActions) + .setExpiresIn("P6M"); + + Response keyRotationPolicyResponse = keyClient.updateKeyRotationPolicyWithResponse( + "keyName", myKeyRotationPolicy, new Context("key1", "value1")); + + System.out.printf("Response received successfully with status code: %d. Updated key rotation policy" + + "with id: %s%n", keyRotationPolicyResponse.getStatusCode(), keyRotationPolicyResponse.getValue().getId()); + // END: com.azure.security.keyvault.keys.KeyClient.updateKeyRotationPolicyWithResponse#String-KeyRotationPolicy-Context + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample6/v2/KeyClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample6/v2/KeyClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..b97130754501 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample6/v2/KeyClientJavaDocCodeSnippets.java @@ -0,0 +1,662 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys; + +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.keys.models.CreateEcKeyOptions; +import com.azure.security.keyvault.keys.models.CreateKeyOptions; +import com.azure.security.keyvault.keys.models.CreateOctKeyOptions; +import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; +import com.azure.security.keyvault.keys.models.DeletedKey; +import com.azure.security.keyvault.keys.models.ImportKeyOptions; +import com.azure.security.keyvault.keys.models.JsonWebKey; +import com.azure.security.keyvault.keys.models.KeyCurveName; +import com.azure.security.keyvault.keys.models.KeyExportEncryptionAlgorithm; +import com.azure.security.keyvault.keys.models.KeyOperation; +import com.azure.security.keyvault.keys.models.KeyProperties; +import com.azure.security.keyvault.keys.models.KeyRotationLifetimeAction; +import com.azure.security.keyvault.keys.models.KeyRotationPolicy; +import com.azure.security.keyvault.keys.models.KeyRotationPolicyAction; +import com.azure.security.keyvault.keys.models.KeyType; +import com.azure.security.keyvault.keys.models.KeyVaultKey; +import com.azure.security.keyvault.keys.models.ReleaseKeyOptions; +import com.azure.security.keyvault.keys.models.ReleaseKeyResult; + +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * This class contains code samples for generating javadocs through doclets for {@link KeyClient}. + */ +public final class KeyClientJavaDocCodeSnippets { + /** + * Generates a code sample for creating a {@link KeyClient}. + * + * @return An instance of {@link KeyClient}. + */ + public KeyClient createClient() { + // BEGIN: com.azure.security.keyvault.keys.KeyClient.instantiation + KeyClient keyClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + // END: com.azure.security.keyvault.keys.KeyClient.instantiation + return keyClient; + } + + /** + * Generates a code sample for using {@link KeyClient#createKey(String, KeyType)}, + * {@link KeyClient#createRsaKey(CreateRsaKeyOptions)}, + * {@link KeyClient#createEcKey(CreateEcKeyOptions)} and + * {@link KeyClient#createOctKey(CreateOctKeyOptions)}. + */ + public void createKey() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.createKey#String-KeyType + KeyVaultKey key = keyClient.createKey("keyName", KeyType.EC); + System.out.printf("Created key with name: %s and id: %s%n", key.getName(), key.getId()); + // END: com.azure.security.keyvault.keys.KeyClient.createKey#String-KeyType + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.createKey#CreateKeyOptions + CreateKeyOptions createKeyOptions = new CreateKeyOptions("keyName", KeyType.RSA) + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + KeyVaultKey optionsKey = keyClient.createKey(createKeyOptions); + + System.out.printf("Created key with name: %s and id: %s%n", optionsKey.getName(), optionsKey.getId()); + // END: com.azure.security.keyvault.keys.KeyClient.createKey#CreateKeyOptions + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.createRsaKey#CreateRsaKeyOptions + CreateRsaKeyOptions createRsaKeyOptions = new CreateRsaKeyOptions("keyName") + .setKeySize(2048) + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + KeyVaultKey rsaKey = keyClient.createRsaKey(createRsaKeyOptions); + + System.out.printf("Created key with name: %s and id: %s%n", rsaKey.getName(), rsaKey.getId()); + // END: com.azure.security.keyvault.keys.KeyClient.createRsaKey#CreateRsaKeyOptions + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.createEcKey#CreateOctKeyOptions + CreateEcKeyOptions createEcKeyOptions = new CreateEcKeyOptions("keyName") + .setCurveName(KeyCurveName.P_384) + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + KeyVaultKey ecKey = keyClient.createEcKey(createEcKeyOptions); + + System.out.printf("Created key with name: %s and id: %s%n", ecKey.getName(), ecKey.getId()); + // END: com.azure.security.keyvault.keys.KeyClient.createEcKey#CreateOctKeyOptions + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.createOctKey#CreateOctKeyOptions + CreateOctKeyOptions createOctKeyOptions = new CreateOctKeyOptions("keyName") + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + KeyVaultKey octKey = keyClient.createOctKey(createOctKeyOptions); + + System.out.printf("Created key with name: %s and id: %s%n", octKey.getName(), octKey.getId()); + // END: com.azure.security.keyvault.keys.KeyClient.createOctKey#CreateOctKeyOptions + } + + /** + * Generates code samples for using {@link KeyAsyncClient#importKey(String, JsonWebKey)}, + * {@link KeyAsyncClient#importKey(ImportKeyOptions)} and + * {@link KeyAsyncClient#importKeyWithResponse(ImportKeyOptions)}. + */ + public void importKey() { + KeyClient keyClient = createClient(); + JsonWebKey jsonWebKeyToImport = new JsonWebKey(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.importKey#String-JsonWebKey + KeyVaultKey key = keyClient.importKey("keyName", jsonWebKeyToImport); + + System.out.printf("Imported key with name: %s and id: %s%n", key.getName(), key.getId()); + // END: com.azure.security.keyvault.keys.KeyClient.importKey#String-JsonWebKey + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.importKey#ImportKeyOptions + ImportKeyOptions options = new ImportKeyOptions("keyName", jsonWebKeyToImport) + .setHardwareProtected(false); + KeyVaultKey importedKey = keyClient.importKey(options); + + System.out.printf("Imported key with name: %s and id: %s%n", importedKey.getName(), + importedKey.getId()); + // END: com.azure.security.keyvault.keys.KeyClient.importKey#ImportKeyOptions + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.importKeyWithResponse#ImportKeyOptions-Context + ImportKeyOptions importKeyOptions = new ImportKeyOptions("keyName", jsonWebKeyToImport) + .setHardwareProtected(false); + Response response = + keyClient.importKeyWithResponse(importKeyOptions, new Context("key1", "value1")); + + System.out.printf("Imported key with name: %s and id: %s%n", response.getValue().getName(), + response.getValue().getId()); + // END: com.azure.security.keyvault.keys.KeyClient.importKeyWithResponse#ImportKeyOptions-Context + } + + /** + * Generates a code sample for using {@link KeyClient#beginDeleteKey(String)}. + */ + public void beginDeleteKey() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.deleteKey#String + SyncPoller deleteKeyPoller = keyClient.beginDeleteKey("keyName"); + PollResponse deleteKeyPollResponse = deleteKeyPoller.poll(); + + // Deleted date only works for SoftDelete Enabled Key Vault. + DeletedKey deletedKey = deleteKeyPollResponse.getValue(); + + System.out.printf("Key delete date: %s%n", deletedKey.getDeletedOn()); + System.out.printf("Deleted key's recovery id: %s%n", deletedKey.getRecoveryId()); + + // Key is being deleted on the server. + deleteKeyPoller.waitForCompletion(); + // Key is deleted + // END: com.azure.security.keyvault.keys.KeyClient.deleteKey#String + } + + /** + * Generates a code sample for using {@link KeyClient#getDeletedKey(String)}. + */ + public void getDeletedKey() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.getDeletedKey#String + DeletedKey deletedKey = keyClient.getDeletedKey("keyName"); + + System.out.printf("Deleted key's recovery id: %s%n", deletedKey.getRecoveryId()); + // END: com.azure.security.keyvault.keys.KeyClient.getDeletedKey#String + } + + /** + * Generates a code sample for using {@link KeyClient#createKeyWithResponse(CreateKeyOptions, Context)}, + * {@link KeyClient#createRsaKeyWithResponse(CreateRsaKeyOptions, Context)}, + * {@link KeyClient#createEcKeyWithResponse(CreateEcKeyOptions, Context)} and + * {@link KeyClient#createOctKeyWithResponse(CreateOctKeyOptions, Context)}. + */ + public void createKeyWithResponse() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.createKeyWithResponse#CreateKeyOptions-Context + CreateKeyOptions createKeyOptions = new CreateKeyOptions("keyName", KeyType.RSA) + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + Response createKeyResponse = + keyClient.createKeyWithResponse(createKeyOptions, new Context("key1", "value1")); + + System.out.printf("Created key with name: %s and: id %s%n", createKeyResponse.getValue().getName(), + createKeyResponse.getValue().getId()); + // END: com.azure.security.keyvault.keys.KeyClient.createKeyWithResponse#CreateKeyOptions-Context + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.createRsaKeyWithResponse#CreateRsaKeyOptions-Context + CreateRsaKeyOptions createRsaKeyOptions = new CreateRsaKeyOptions("keyName") + .setKeySize(2048) + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + Response createRsaKeyResponse = + keyClient.createRsaKeyWithResponse(createRsaKeyOptions, new Context("key1", "value1")); + + System.out.printf("Created key with name: %s and: id %s%n", createRsaKeyResponse.getValue().getName(), + createRsaKeyResponse.getValue().getId()); + // END: com.azure.security.keyvault.keys.KeyClient.createRsaKeyWithResponse#CreateRsaKeyOptions-Context + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.createEcKeyWithResponse#CreateEcKeyOptions-Context + CreateEcKeyOptions createEcKeyOptions = new CreateEcKeyOptions("keyName") + .setCurveName(KeyCurveName.P_384) + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + Response createEcKeyResponse = + keyClient.createEcKeyWithResponse(createEcKeyOptions, new Context("key1", "value1")); + + System.out.printf("Created key with name: %s and: id %s%n", createEcKeyResponse.getValue().getName(), + createEcKeyResponse.getValue().getId()); + // END: com.azure.security.keyvault.keys.KeyClient.createEcKeyWithResponse#CreateEcKeyOptions-Context + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.createOctKey#CreateOctKeyOptions-Context + CreateOctKeyOptions createOctKeyOptions = new CreateOctKeyOptions("keyName") + .setNotBefore(OffsetDateTime.now().plusDays(1)) + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + Response createOctKeyResponse = + keyClient.createOctKeyWithResponse(createOctKeyOptions, new Context("key1", "value1")); + + System.out.printf("Created key with name: %s and: id %s%n", createOctKeyResponse.getValue().getName(), + createOctKeyResponse.getValue().getId()); + // END: com.azure.security.keyvault.keys.KeyClient.createOctKey#CreateOctKeyOptions-Context + } + + /** + * Generates a code sample for using {@link KeyClient#getKeyWithResponse(String, String, Context)}. + */ + public void getKeyWithResponse() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.getKeyWithResponse#String-String-Context + String keyVersion = "6A385B124DEF4096AF1361A85B16C204"; + Response getKeyResponse = + keyClient.getKeyWithResponse("keyName", keyVersion, new Context("key1", "value1")); + + System.out.printf("Retrieved key with name: %s and: id %s%n", getKeyResponse.getValue().getName(), + getKeyResponse.getValue().getId()); + // END: com.azure.security.keyvault.keys.KeyClient.getKeyWithResponse#String-String-Context + } + + /** + * Generates a code sample for using {@link KeyClient#getKey(String)} and + * {@link KeyClient#getKey(String, String)}. + */ + public void getKey() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.getKey#String + KeyVaultKey keyWithVersionValue = keyClient.getKey("keyName"); + + System.out.printf("Retrieved key with name: %s and: id %s%n", keyWithVersionValue.getName(), + keyWithVersionValue.getId()); + // END: com.azure.security.keyvault.keys.KeyClient.getKey#String + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.getKey#String-String + String keyVersion = "6A385B124DEF4096AF1361A85B16C204"; + KeyVaultKey keyWithVersion = keyClient.getKey("keyName", keyVersion); + + System.out.printf("Retrieved key with name: %s and: id %s%n", keyWithVersion.getName(), + keyWithVersion.getId()); + // END: com.azure.security.keyvault.keys.KeyClient.getKey#String-String + } + + /** + * Generates a code sample for using + * {@link KeyClient#updateKeyPropertiesWithResponse(KeyProperties, Context, KeyOperation...)}. + */ + public void updateKeyPropertiesWithResponse() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.updateKeyPropertiesWithResponse#KeyProperties-Context-KeyOperation + KeyVaultKey key = keyClient.getKey("keyName"); + + key.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(60)); + + Response updateKeyResponse = + keyClient.updateKeyPropertiesWithResponse(key.getProperties(), new Context("key1", "value1"), + KeyOperation.ENCRYPT, KeyOperation.DECRYPT); + + System.out.printf("Updated key with name: %s and id: %s%n", updateKeyResponse.getValue().getName(), + updateKeyResponse.getValue().getId()); + // END: com.azure.security.keyvault.keys.KeyClient.updateKeyPropertiesWithResponse#KeyProperties-Context-KeyOperation + } + + /** + * Generates a code sample for using {@link KeyClient#updateKeyProperties(KeyProperties, KeyOperation...)}. + */ + public void updateKeyProperties() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.updateKeyProperties#KeyProperties-KeyOperation + KeyVaultKey key = keyClient.getKey("keyName"); + + key.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(60)); + + KeyVaultKey updatedKey = keyClient.updateKeyProperties(key.getProperties(), KeyOperation.ENCRYPT, + KeyOperation.DECRYPT); + + System.out.printf("Key is updated with name %s and id %s %n", updatedKey.getName(), updatedKey.getId()); + // END: com.azure.security.keyvault.keys.KeyClient.updateKeyProperties#KeyProperties-KeyOperation + } + + /** + * Generates a code sample for using {@link KeyClient#getDeletedKeyWithResponse(String, Context)}. + */ + public void getDeletedKeyWithResponse() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.getDeletedKeyWithResponse#String-Context + Response deletedKeyResponse = + keyClient.getDeletedKeyWithResponse("keyName", new Context("key1", "value1")); + + System.out.printf("Deleted key with recovery id: %s%n", deletedKeyResponse.getValue().getRecoveryId()); + // END: com.azure.security.keyvault.keys.KeyClient.getDeletedKeyWithResponse#String-Context + } + + /** + * Generates a code sample for using {@link KeyClient#purgeDeletedKey(String)}. + */ + public void purgeDeletedKey() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.purgeDeletedKey#String + keyClient.purgeDeletedKey("deletedKeyName"); + // END: com.azure.security.keyvault.keys.KeyClient.purgeDeletedKey#String + } + + /** + * Generates a code sample for using {@link KeyClient#purgeDeletedKeyWithResponse(String, Context)}. + */ + public void purgeDeletedKeyWithResponse() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.purgeDeletedKeyWithResponse#String-Context + Response purgeDeletedKeyResponse = keyClient.purgeDeletedKeyWithResponse("deletedKeyName", + new Context("key1", "value1")); + + System.out.printf("Purge response status code: %d%n", purgeDeletedKeyResponse.getStatusCode()); + // END: com.azure.security.keyvault.keys.KeyClient.purgeDeletedKeyWithResponse#String-Context + } + + /** + * Generates a code sample for using {@link KeyClient#beginRecoverDeletedKey(String)}. + */ + public void beginRecoverDeletedKey() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.recoverDeletedKey#String + SyncPoller recoverKeyPoller = keyClient.beginRecoverDeletedKey("deletedKeyName"); + + PollResponse recoverKeyPollResponse = recoverKeyPoller.poll(); + + KeyVaultKey recoveredKey = recoverKeyPollResponse.getValue(); + System.out.printf("Recovered key name: %s%n", recoveredKey.getName()); + System.out.printf("Recovered key id: %s%n", recoveredKey.getId()); + + // Key is being recovered on the server. + recoverKeyPoller.waitForCompletion(); + // Key is recovered + // END: com.azure.security.keyvault.keys.KeyClient.recoverDeletedKey#String + } + + /** + * Generates a code sample for using {@link KeyClient#backupKey(String)}. + */ + public void backupKey() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.backupKey#String + byte[] keyBackup = keyClient.backupKey("keyName"); + + System.out.printf("Key backup byte array length: %s%n", keyBackup.length); + // END: com.azure.security.keyvault.keys.KeyClient.backupKey#String + } + + /** + * Generates a code sample for using {@link KeyClient#backupKeyWithResponse(String, Context)}. + */ + public void backupKeyWithResponse() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.backupKeyWithResponse#String-Context + Response backupKeyResponse = keyClient.backupKeyWithResponse("keyName", new Context("key1", "value1")); + + System.out.printf("Key backup byte array length: %s%n", backupKeyResponse.getValue().length); + // END: com.azure.security.keyvault.keys.KeyClient.backupKeyWithResponse#String-Context + } + + /** + * Generates a code sample for using {@link KeyClient#restoreKeyBackup}. + */ + public void restoreKeyBackup() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.restoreKeyBackup#byte + byte[] keyBackupByteArray = {}; + KeyVaultKey keyResponse = keyClient.restoreKeyBackup(keyBackupByteArray); + System.out.printf("Restored key with name: %s and: id %s%n", keyResponse.getName(), keyResponse.getId()); + // END: com.azure.security.keyvault.keys.KeyClient.restoreKeyBackup#byte + } + + /** + * Generates a code sample for using {@link KeyClient#restoreKeyBackupWithResponse(byte[], Context)}. + */ + public void restoreKeyBackupWithResponse() { + KeyClient keyClient = createClient(); + byte[] keyBackupByteArray = {}; + // BEGIN: com.azure.security.keyvault.keys.KeyClient.restoreKeyBackupWithResponse#byte-Context + Response keyResponse = keyClient.restoreKeyBackupWithResponse(keyBackupByteArray, + new Context("key1", "value1")); + + System.out.printf("Restored key with name: %s and: id %s%n", + keyResponse.getValue().getName(), keyResponse.getValue().getId()); + // END: com.azure.security.keyvault.keys.KeyClient.restoreKeyBackupWithResponse#byte-Context + } + + /** + * Generates a code sample for using {@link KeyClient#listPropertiesOfKeys()} and + * {@link KeyClient#listPropertiesOfKeys(Context)}. + */ + public void listPropertiesOfKeys() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeys + for (KeyProperties keyProperties : keyClient.listPropertiesOfKeys()) { + KeyVaultKey key = keyClient.getKey(keyProperties.getName(), keyProperties.getVersion()); + + System.out.printf("Retrieved key with name: %s and type: %s%n", key.getName(), key.getKeyType()); + } + // END: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeys + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeys#Context + for (KeyProperties keyProperties : keyClient.listPropertiesOfKeys(new Context("key1", "value1"))) { + KeyVaultKey key = keyClient.getKey(keyProperties.getName(), keyProperties.getVersion()); + + System.out.printf("Retrieved key with name: %s and type: %s%n", key.getName(), + key.getKeyType()); + } + // END: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeys#Context + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeys.iterableByPage + keyClient.listPropertiesOfKeys().iterableByPage().forEach(pagedResponse -> { + System.out.printf("Got response details. Url: %s. Status code: %d.%n", + pagedResponse.getRequest().getUrl(), pagedResponse.getStatusCode()); + pagedResponse.getElements().forEach(keyProperties -> { + KeyVaultKey key = keyClient.getKey(keyProperties.getName(), keyProperties.getVersion()); + + System.out.printf("Retrieved key with name: %s and type: %s%n", key.getName(), + key.getKeyType()); + }); + }); + // END: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeys.iterableByPage + } + + /** + * Generates a code sample for using {@link KeyClient#listDeletedKeys()} and + * {@link KeyClient#listDeletedKeys(Context)}. + */ + public void listDeletedKeys() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.listDeletedKeys + for (DeletedKey deletedKey : keyClient.listDeletedKeys()) { + System.out.printf("Deleted key's recovery id:%s%n", deletedKey.getRecoveryId()); + } + // END: com.azure.security.keyvault.keys.KeyClient.listDeletedKeys + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.listDeletedKeys#Context + for (DeletedKey deletedKey : keyClient.listDeletedKeys(new Context("key1", "value1"))) { + System.out.printf("Deleted key's recovery id:%s%n", deletedKey.getRecoveryId()); + } + // END: com.azure.security.keyvault.keys.KeyClient.listDeletedKeys#Context + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.listDeletedKeys.iterableByPage + keyClient.listDeletedKeys().iterableByPage().forEach(pagedResponse -> { + System.out.printf("Got response details. Url: %s. Status code: %d.%n", + pagedResponse.getRequest().getUrl(), pagedResponse.getStatusCode()); + pagedResponse.getElements().forEach(deletedKey -> + System.out.printf("Deleted key's recovery id:%s%n", deletedKey.getRecoveryId())); + }); + // END: com.azure.security.keyvault.keys.KeyClient.listDeletedKeys.iterableByPage + } + + /** + * Generates code sample for using {@link KeyClient#listPropertiesOfKeyVersions(String)} and + * {@link KeyClient#listPropertiesOfKeyVersions(String, Context)}. + */ + public void listPropertiesOfKeyVersions() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeyVersions#String + for (KeyProperties keyProperties : keyClient.listPropertiesOfKeyVersions("keyName")) { + KeyVaultKey key = keyClient.getKey(keyProperties.getName(), keyProperties.getVersion()); + + System.out.printf("Retrieved key version: %s with name: %s and type: %s%n", + key.getProperties().getVersion(), key.getName(), key.getKeyType()); + } + // END: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeyVersions#String + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeyVersions#String-Context + for (KeyProperties keyProperties : keyClient.listPropertiesOfKeyVersions("keyName", new Context("key1", "value1"))) { + KeyVaultKey key = keyClient.getKey(keyProperties.getName(), keyProperties.getVersion()); + + System.out.printf("Retrieved key version: %s with name: %s and type: %s%n", + key.getProperties().getVersion(), key.getName(), key.getKeyType()); + } + // END: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeyVersions#String-Context + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeyVersions.iterableByPage + keyClient.listPropertiesOfKeyVersions("keyName").iterableByPage().forEach(pagedResponse -> { + System.out.printf("Got response details. Url: %s. Status code: %d.%n", + pagedResponse.getRequest().getUrl(), pagedResponse.getStatusCode()); + pagedResponse.getElements().forEach(keyProperties -> + System.out.printf("Key name: %s. Key version: %s.%n", keyProperties.getName(), + keyProperties.getVersion())); + }); + // END: com.azure.security.keyvault.keys.KeyClient.listPropertiesOfKeyVersions.iterableByPage + } + + /** + * Generates code samples for using {@link KeyClient#getRandomBytes(int)} and + * {@link KeyClient#getRandomBytesWithResponse(int, Context)}. + */ + public void getRandomBytes() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.getRandomBytes#int + int amount = 16; + byte[] randomBytes = keyClient.getRandomBytes(amount); + + System.out.printf("Retrieved %d random bytes: %s%n", amount, Arrays.toString(randomBytes)); + // END: com.azure.security.keyvault.keys.KeyClient.getRandomBytes#int + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.getRandomBytesWithResponse#int-Context + int amountOfBytes = 16; + Response response = + keyClient.getRandomBytesWithResponse(amountOfBytes, new Context("key1", "value1")); + + System.out.printf("Response received successfully with status code: %d. Retrieved %d random bytes: %s%n", + response.getStatusCode(), amountOfBytes, Arrays.toString(response.getValue())); + // END: com.azure.security.keyvault.keys.KeyClient.getRandomBytesWithResponse#int-Context + } + + /** + * Generates code samples for using {@link KeyClient#releaseKey(String, String)}, + * {@link KeyClient#releaseKey(String, String, String)} and + * {@link KeyClient#releaseKeyWithResponse(String, String, String, ReleaseKeyOptions, Context)}. + */ + public void releaseKey() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.releaseKey#String-String + String targetAttestationToken = "someAttestationToken"; + ReleaseKeyResult releaseKeyResult = keyClient.releaseKey("keyName", targetAttestationToken); + + System.out.printf("Signed object containing released key: %s%n", releaseKeyResult); + // END: com.azure.security.keyvault.keys.KeyClient.releaseKey#String-String + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.releaseKey#String-String-String + String myKeyVersion = "6A385B124DEF4096AF1361A85B16C204"; + String myTargetAttestationToken = "someAttestationToken"; + ReleaseKeyResult releaseKeyVersionResult = + keyClient.releaseKey("keyName", myKeyVersion, myTargetAttestationToken); + + System.out.printf("Signed object containing released key: %s%n", releaseKeyVersionResult); + // END: com.azure.security.keyvault.keys.KeyClient.releaseKey#String-String-String + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.releaseKeyWithResponse#String-String-String-ReleaseKeyOptions-Context + String releaseKeyVersion = "6A385B124DEF4096AF1361A85B16C204"; + String someTargetAttestationToken = "someAttestationToken"; + ReleaseKeyOptions releaseKeyOptions = new ReleaseKeyOptions() + .setAlgorithm(KeyExportEncryptionAlgorithm.RSA_AES_KEY_WRAP_256) + .setNonce("someNonce"); + + Response releaseKeyResultResponse = + keyClient.releaseKeyWithResponse("keyName", releaseKeyVersion, someTargetAttestationToken, + releaseKeyOptions, new Context("key1", "value1")); + + System.out.printf("Response received successfully with status code: %d. Signed object containing" + + "released key: %s%n", releaseKeyResultResponse.getStatusCode(), + releaseKeyResultResponse.getValue().getValue()); + // END: com.azure.security.keyvault.keys.KeyClient.releaseKeyWithResponse#String-String-String-ReleaseKeyOptions-Context + } + + /** + * Generates code samples for using {@link KeyClient#rotateKey(String)} and + * {@link KeyClient#rotateKeyWithResponse(String, Context)}. + */ + public void rotateKey() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.rotateKeyWithResponse#String + KeyVaultKey key = keyClient.rotateKey("keyName"); + + System.out.printf("Rotated key with name: %s and version:%s%n", key.getName(), + key.getProperties().getVersion()); + // END: com.azure.security.keyvault.keys.KeyClient.rotateKeyWithResponse#String + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.rotateKeyWithResponse#String-Context + Response keyResponse = keyClient.rotateKeyWithResponse("keyName", new Context("key1", "value1")); + + System.out.printf("Response received successfully with status code: %d. Rotated key with name: %s and" + + "version: %s%n", keyResponse.getStatusCode(), keyResponse.getValue().getName(), + keyResponse.getValue().getProperties().getVersion()); + // END: com.azure.security.keyvault.keys.KeyClient.rotateKeyWithResponse#String-Context + } + + /** + * Generates code samples for using {@link KeyClient#getKeyRotationPolicy(String)} and + * {@link KeyClient#getKeyRotationPolicyWithResponse(String, Context)}. + */ + public void getKeyRotationPolicy() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.getKeyRotationPolicy#String + KeyRotationPolicy keyRotationPolicy = keyClient.getKeyRotationPolicy("keyName"); + + System.out.printf("Retrieved key rotation policy with id: %s%n", keyRotationPolicy.getId()); + // END: com.azure.security.keyvault.keys.KeyClient.getKeyRotationPolicy#String + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.getKeyRotationPolicyWithResponse#String-Context + Response keyRotationPolicyResponse = + keyClient.getKeyRotationPolicyWithResponse("keyName", new Context("key1", "value1")); + + System.out.printf("Response received successfully with status code: %d. Retrieved key rotation policy" + + "with id: %s%n", keyRotationPolicyResponse.getStatusCode(), keyRotationPolicyResponse.getValue().getId()); + // END: com.azure.security.keyvault.keys.KeyClient.getKeyRotationPolicyWithResponse#String-Context + } + + /** + * Generates code samples for using {@link KeyClient#updateKeyRotationPolicy(String, KeyRotationPolicy)} + * and {@link KeyClient#updateKeyRotationPolicyWithResponse(String, KeyRotationPolicy, Context)}. + */ + public void updateKeyRotationPolicy() { + KeyClient keyClient = createClient(); + // BEGIN: com.azure.security.keyvault.keys.KeyClient.updateKeyRotationPolicy#String-KeyRotationPolicy + List lifetimeActions = new ArrayList<>(); + KeyRotationLifetimeAction rotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE) + .setTimeAfterCreate("P90D"); + KeyRotationLifetimeAction notifyLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.NOTIFY) + .setTimeBeforeExpiry("P45D"); + + lifetimeActions.add(rotateLifetimeAction); + lifetimeActions.add(notifyLifetimeAction); + + KeyRotationPolicy keyRotationPolicy = new KeyRotationPolicy() + .setLifetimeActions(lifetimeActions) + .setExpiresIn("P6M"); + + KeyRotationPolicy updatedPolicy = + keyClient.updateKeyRotationPolicy("keyName", keyRotationPolicy); + + System.out.printf("Updated key rotation policy with id: %s%n", updatedPolicy.getId()); + // END: com.azure.security.keyvault.keys.KeyClient.updateKeyRotationPolicy#String-KeyRotationPolicy + + // BEGIN: com.azure.security.keyvault.keys.KeyClient.updateKeyRotationPolicyWithResponse#String-KeyRotationPolicy-Context + List myLifetimeActions = new ArrayList<>(); + KeyRotationLifetimeAction myRotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE) + .setTimeAfterCreate("P90D"); + KeyRotationLifetimeAction myNotifyLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.NOTIFY) + .setTimeBeforeExpiry("P45D"); + + myLifetimeActions.add(myRotateLifetimeAction); + myLifetimeActions.add(myNotifyLifetimeAction); + + KeyRotationPolicy myKeyRotationPolicy = new KeyRotationPolicy() + .setLifetimeActions(myLifetimeActions) + .setExpiresIn("P6M"); + + Response keyRotationPolicyResponse = keyClient.updateKeyRotationPolicyWithResponse( + "keyName", myKeyRotationPolicy, new Context("key1", "value1")); + + System.out.printf("Response received successfully with status code: %d. Updated key rotation policy" + + "with id: %s%n", keyRotationPolicyResponse.getStatusCode(), keyRotationPolicyResponse.getValue().getId()); + // END: com.azure.security.keyvault.keys.KeyClient.updateKeyRotationPolicyWithResponse#String-KeyRotationPolicy-Context + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample7/v1/KeyRotation.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample7/v1/KeyRotation.java new file mode 100644 index 000000000000..8717c3941233 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample7/v1/KeyRotation.java @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; +import com.azure.security.keyvault.keys.models.KeyRotationLifetimeAction; +import com.azure.security.keyvault.keys.models.KeyRotationPolicy; +import com.azure.security.keyvault.keys.models.KeyRotationPolicyAction; +import com.azure.security.keyvault.keys.models.KeyVaultKey; + +import java.util.ArrayList; +import java.util.List; + +/* + * This sample demonstrates how to set key rotation policies and manually rotate keys in Key Vault to create a new key + * version. + */ +public class KeyRotation { + /** + * Authenticates with the key vault and shows set key rotation policies and manually rotate keys in Key Vault to + * create a new key version. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when an invalid key vault endpoint is passed. + */ + public static void main(String[] args) { + /* Instantiate a KeyClient that will be used to call the service. Notice that the client is using default Azure + credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) + for links and instructions. */ + KeyClient keyClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + // Let's create an RSA key. + String keyName = "MyKey"; + KeyVaultKey originalKey = keyClient.createRsaKey(new CreateRsaKeyOptions(keyName).setKeySize(2048)); + + System.out.printf("Key created with name %s and type %s%n", originalKey.getName(), originalKey.getKeyType()); + + // You can configure its key rotation policy to allow Azure Key Vault to do it automatically under certain + // conditions. Properties such as timeAfterCreate and timeBeforeExpiry should be defined as an ISO 8601 + // duration. For example, 90 days would be "P90D", 3 months would be "P3M" and 1 year and 10 days would be + // "P1Y10D". See https://wikipedia.org/wiki/ISO_8601#Durations for more information. + List keyRotationLifetimeActionList = new ArrayList<>(); + KeyRotationLifetimeAction rotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE) + .setTimeAfterCreate("P90D"); // Rotate the key after 90 days of its creation. + + keyRotationLifetimeActionList.add(rotateLifetimeAction); + + KeyRotationPolicy keyRotationPolicy = new KeyRotationPolicy() + .setLifetimeActions(keyRotationLifetimeActionList) + .setExpiresIn("P6M"); // Make any new versions of the key expire 6 months after creation. + + // An object containing the details of the recently updated key rotation policy will be returned by the update + // method. + KeyRotationPolicy updatedPolicy = keyClient.updateKeyRotationPolicy(keyName, keyRotationPolicy); + + System.out.printf("Updated key rotation policy with id: %s%n", updatedPolicy.getId()); + + // You can also manually rotate a key by calling the following method. + KeyVaultKey manuallyRotatedKey = keyClient.rotateKey(keyName); + + System.out.printf("Rotated key with name %s%n", manuallyRotatedKey.getName()); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample7/v2/KeyRotation.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample7/v2/KeyRotation.java new file mode 100644 index 000000000000..8717c3941233 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample7/v2/KeyRotation.java @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; +import com.azure.security.keyvault.keys.models.KeyRotationLifetimeAction; +import com.azure.security.keyvault.keys.models.KeyRotationPolicy; +import com.azure.security.keyvault.keys.models.KeyRotationPolicyAction; +import com.azure.security.keyvault.keys.models.KeyVaultKey; + +import java.util.ArrayList; +import java.util.List; + +/* + * This sample demonstrates how to set key rotation policies and manually rotate keys in Key Vault to create a new key + * version. + */ +public class KeyRotation { + /** + * Authenticates with the key vault and shows set key rotation policies and manually rotate keys in Key Vault to + * create a new key version. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when an invalid key vault endpoint is passed. + */ + public static void main(String[] args) { + /* Instantiate a KeyClient that will be used to call the service. Notice that the client is using default Azure + credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) + for links and instructions. */ + KeyClient keyClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + // Let's create an RSA key. + String keyName = "MyKey"; + KeyVaultKey originalKey = keyClient.createRsaKey(new CreateRsaKeyOptions(keyName).setKeySize(2048)); + + System.out.printf("Key created with name %s and type %s%n", originalKey.getName(), originalKey.getKeyType()); + + // You can configure its key rotation policy to allow Azure Key Vault to do it automatically under certain + // conditions. Properties such as timeAfterCreate and timeBeforeExpiry should be defined as an ISO 8601 + // duration. For example, 90 days would be "P90D", 3 months would be "P3M" and 1 year and 10 days would be + // "P1Y10D". See https://wikipedia.org/wiki/ISO_8601#Durations for more information. + List keyRotationLifetimeActionList = new ArrayList<>(); + KeyRotationLifetimeAction rotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE) + .setTimeAfterCreate("P90D"); // Rotate the key after 90 days of its creation. + + keyRotationLifetimeActionList.add(rotateLifetimeAction); + + KeyRotationPolicy keyRotationPolicy = new KeyRotationPolicy() + .setLifetimeActions(keyRotationLifetimeActionList) + .setExpiresIn("P6M"); // Make any new versions of the key expire 6 months after creation. + + // An object containing the details of the recently updated key rotation policy will be returned by the update + // method. + KeyRotationPolicy updatedPolicy = keyClient.updateKeyRotationPolicy(keyName, keyRotationPolicy); + + System.out.printf("Updated key rotation policy with id: %s%n", updatedPolicy.getId()); + + // You can also manually rotate a key by calling the following method. + KeyVaultKey manuallyRotatedKey = keyClient.rotateKey(keyName); + + System.out.printf("Rotated key with name %s%n", manuallyRotatedKey.getName()); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample8/v1/KeyRotationAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample8/v1/KeyRotationAsync.java new file mode 100644 index 000000000000..c3458ea0b5ba --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample8/v1/KeyRotationAsync.java @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; +import com.azure.security.keyvault.keys.models.KeyRotationLifetimeAction; +import com.azure.security.keyvault.keys.models.KeyRotationPolicy; +import com.azure.security.keyvault.keys.models.KeyRotationPolicyAction; + +import java.util.ArrayList; +import java.util.List; + +/* + * This sample demonstrates how to set key rotation policies and manually rotate keys in Key Vault to create a new key + * version. + */ +public class KeyRotationAsync { + /** + * Authenticates with the key vault and shows set key rotation policies and manually rotate keys in Key Vault to + * create a new key version. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when an invalid key vault endpoint is passed. + */ + public static void main(String[] args) { + /* Instantiate a KeyAsyncClient that will be used to call the service. Notice that the client is using default + Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) + for links and instructions. */ + KeyAsyncClient keyAsyncClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + // Let's create an RSA key. + String keyName = "MyKey"; + keyAsyncClient.createRsaKey(new CreateRsaKeyOptions(keyName).setKeySize(2048)) + .subscribe(originalKey -> + System.out.printf("Key created with name: %s, and type: %s%n", originalKey.getName(), + originalKey.getKeyType())); + + // You can configure its key rotation policy to allow Azure Key Vault to do it automatically under certain + // conditions. Properties such as timeAfterCreate and timeBeforeExpiry should be defined as an ISO 8601 + // duration. For example, 90 days would be "P90D", 3 months would be "P3M" and 1 year and 10 days would be + // "P1Y10D". See https://wikipedia.org/wiki/ISO_8601#Durations for more information. + List keyRotationLifetimeActionList = new ArrayList<>(); + KeyRotationLifetimeAction rotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE) + .setTimeAfterCreate("P90D"); // Rotate the key after 90 days of its creation. + + keyRotationLifetimeActionList.add(rotateLifetimeAction); + + KeyRotationPolicy keyRotationPolicy = new KeyRotationPolicy() + .setLifetimeActions(keyRotationLifetimeActionList) + .setExpiresIn("P6M"); // Make any new versions of the key expire 6 months after creation. + + // An object containing the details of the recently updated key rotation policy will be returned by the update + // method. + keyAsyncClient.updateKeyRotationPolicy(keyName, keyRotationPolicy) + .subscribe(updatedPolicy -> + System.out.printf("Updated key rotation policy with id: %s%n", updatedPolicy.getId())); + + // You can also manually rotate a key by calling the following method. + keyAsyncClient.rotateKey(keyName) + .subscribe(manuallyRotatedKey -> + System.out.printf("Rotated key with name: %s%n", manuallyRotatedKey.getName())); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample8/v2/KeyRotationAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample8/v2/KeyRotationAsync.java new file mode 100644 index 000000000000..c3458ea0b5ba --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample8/v2/KeyRotationAsync.java @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; +import com.azure.security.keyvault.keys.models.KeyRotationLifetimeAction; +import com.azure.security.keyvault.keys.models.KeyRotationPolicy; +import com.azure.security.keyvault.keys.models.KeyRotationPolicyAction; + +import java.util.ArrayList; +import java.util.List; + +/* + * This sample demonstrates how to set key rotation policies and manually rotate keys in Key Vault to create a new key + * version. + */ +public class KeyRotationAsync { + /** + * Authenticates with the key vault and shows set key rotation policies and manually rotate keys in Key Vault to + * create a new key version. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when an invalid key vault endpoint is passed. + */ + public static void main(String[] args) { + /* Instantiate a KeyAsyncClient that will be used to call the service. Notice that the client is using default + Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) + for links and instructions. */ + KeyAsyncClient keyAsyncClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + // Let's create an RSA key. + String keyName = "MyKey"; + keyAsyncClient.createRsaKey(new CreateRsaKeyOptions(keyName).setKeySize(2048)) + .subscribe(originalKey -> + System.out.printf("Key created with name: %s, and type: %s%n", originalKey.getName(), + originalKey.getKeyType())); + + // You can configure its key rotation policy to allow Azure Key Vault to do it automatically under certain + // conditions. Properties such as timeAfterCreate and timeBeforeExpiry should be defined as an ISO 8601 + // duration. For example, 90 days would be "P90D", 3 months would be "P3M" and 1 year and 10 days would be + // "P1Y10D". See https://wikipedia.org/wiki/ISO_8601#Durations for more information. + List keyRotationLifetimeActionList = new ArrayList<>(); + KeyRotationLifetimeAction rotateLifetimeAction = new KeyRotationLifetimeAction(KeyRotationPolicyAction.ROTATE) + .setTimeAfterCreate("P90D"); // Rotate the key after 90 days of its creation. + + keyRotationLifetimeActionList.add(rotateLifetimeAction); + + KeyRotationPolicy keyRotationPolicy = new KeyRotationPolicy() + .setLifetimeActions(keyRotationLifetimeActionList) + .setExpiresIn("P6M"); // Make any new versions of the key expire 6 months after creation. + + // An object containing the details of the recently updated key rotation policy will be returned by the update + // method. + keyAsyncClient.updateKeyRotationPolicy(keyName, keyRotationPolicy) + .subscribe(updatedPolicy -> + System.out.printf("Updated key rotation policy with id: %s%n", updatedPolicy.getId())); + + // You can also manually rotate a key by calling the following method. + keyAsyncClient.rotateKey(keyName) + .subscribe(manuallyRotatedKey -> + System.out.printf("Rotated key with name: %s%n", manuallyRotatedKey.getName())); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample9/v1/ListOperations.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample9/v1/ListOperations.java new file mode 100644 index 000000000000..3ae26850cb2b --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample9/v1/ListOperations.java @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys; + +import com.azure.security.keyvault.keys.models.CreateEcKeyOptions; +import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; +import com.azure.security.keyvault.keys.models.KeyVaultKey; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.keys.models.KeyProperties; + +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to list keys and versions of a given key in the key vault. + */ +public class ListOperations { + /** + * Authenticates with the key vault and shows how to list keys and list versions of a specific key in the key vault. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + */ + public static void main(String[] args) throws IllegalArgumentException { + /* Instantiate a KeyClient that will be used to call the service. Notice that the client is using default Azure + credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) + for links and instructions. */ + KeyClient keyClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + // Let's create EC and ESA keys valid for 1 year. If a key already exists in the key vault, then a new version + // of the key is created. + keyClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1)) + .setKeySize(2048)); + + keyClient.createEcKey(new CreateEcKeyOptions("CloudEcKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1))); + + // You need to check te type of keys already exist in your key vault. Let's list the keys and print their types. + // List operations don't return the keys with key material information. So, for each returned key we call + // getKey() to get the key with its key material information. + for (KeyProperties key : keyClient.listPropertiesOfKeys()) { + KeyVaultKey keyWithMaterial = keyClient.getKey(key.getName(), key.getVersion()); + + System.out.printf("Received key with name %s and type %s", keyWithMaterial.getName(), + keyWithMaterial.getKeyType()); + } + + // We need the RSA key with a bigger key size, so you want to update the key in key vault to ensure it has the + // required size. Calling createRsaKey() on an existing key creates a new version of the key in the key vault + // with the new specified size. + keyClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1)) + .setKeySize(4096)); + + // You need to check all the different versions RSA key had previously. Lets print all the versions of this key. + for (KeyProperties key : keyClient.listPropertiesOfKeyVersions("CloudRsaKey")) { + KeyVaultKey keyWithMaterial = keyClient.getKey(key.getName(), key.getVersion()); + + System.out.printf("Received key's version with name %s, type %s and verison %s", keyWithMaterial.getName(), + keyWithMaterial.getKeyType(), keyWithMaterial.getProperties().getVersion()); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample9/v2/ListOperations.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample9/v2/ListOperations.java new file mode 100644 index 000000000000..3ae26850cb2b --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-keys/sample9/v2/ListOperations.java @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys; + +import com.azure.security.keyvault.keys.models.CreateEcKeyOptions; +import com.azure.security.keyvault.keys.models.CreateRsaKeyOptions; +import com.azure.security.keyvault.keys.models.KeyVaultKey; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.keys.models.KeyProperties; + +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to list keys and versions of a given key in the key vault. + */ +public class ListOperations { + /** + * Authenticates with the key vault and shows how to list keys and list versions of a specific key in the key vault. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + */ + public static void main(String[] args) throws IllegalArgumentException { + /* Instantiate a KeyClient that will be used to call the service. Notice that the client is using default Azure + credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-keys/README.md) + for links and instructions. */ + KeyClient keyClient = new KeyClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + // Let's create EC and ESA keys valid for 1 year. If a key already exists in the key vault, then a new version + // of the key is created. + keyClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1)) + .setKeySize(2048)); + + keyClient.createEcKey(new CreateEcKeyOptions("CloudEcKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1))); + + // You need to check te type of keys already exist in your key vault. Let's list the keys and print their types. + // List operations don't return the keys with key material information. So, for each returned key we call + // getKey() to get the key with its key material information. + for (KeyProperties key : keyClient.listPropertiesOfKeys()) { + KeyVaultKey keyWithMaterial = keyClient.getKey(key.getName(), key.getVersion()); + + System.out.printf("Received key with name %s and type %s", keyWithMaterial.getName(), + keyWithMaterial.getKeyType()); + } + + // We need the RSA key with a bigger key size, so you want to update the key in key vault to ensure it has the + // required size. Calling createRsaKey() on an existing key creates a new version of the key in the key vault + // with the new specified size. + keyClient.createRsaKey(new CreateRsaKeyOptions("CloudRsaKey") + .setExpiresOn(OffsetDateTime.now().plusYears(1)) + .setKeySize(4096)); + + // You need to check all the different versions RSA key had previously. Lets print all the versions of this key. + for (KeyProperties key : keyClient.listPropertiesOfKeyVersions("CloudRsaKey")) { + KeyVaultKey keyWithMaterial = keyClient.getKey(key.getName(), key.getVersion()); + + System.out.printf("Received key's version with name %s, type %s and verison %s", keyWithMaterial.getName(), + keyWithMaterial.getKeyType(), keyWithMaterial.getProperties().getVersion()); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample1/v1/BackupAndRestoreOperations.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample1/v1/BackupAndRestoreOperations.java new file mode 100644 index 000000000000..27938c5ccef5 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample1/v1/BackupAndRestoreOperations.java @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.secrets; + +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.security.keyvault.secrets.models.DeletedSecret; +import com.azure.security.keyvault.secrets.models.KeyVaultSecret; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.secrets.models.SecretProperties; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to backup and restore secrets in the key vault. + */ +public class BackupAndRestoreOperations { + /** + * Authenticates with the key vault and shows how to backup and restore secrets in the key vault. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + * @throws IOException when writing backup to file is unsuccessful. + */ + public static void main(String[] args) throws IOException, InterruptedException, IllegalArgumentException { + /* Instantiate a SecretClient that will be used to call the service. Notice that the client is using default + Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md) + for links and instructions. */ + SecretClient client = new SecretClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + // Let's create secrets holding storage account credentials valid for 1 year. If the secret already exists in + // the key vault, then a new version of the secret is created. + client.setSecret(new KeyVaultSecret("StorageAccountPassword", "f4G34fMh8v-fdsgjsk2323=-asdsdfsdf") + .setProperties(new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)))); + + // Backups are good to have, if in case secrets get accidentally deleted by you. + // For long term storage, it is ideal to write the backup to a file. + String backupFilePath = "YOUR_BACKUP_FILE_PATH"; + byte[] secretBackup = client.backupSecret("StorageAccountPassword"); + + writeBackupToFile(secretBackup, backupFilePath); + + // The storage account secret is no longer in use, so you delete it. + SyncPoller deletedStorageSecretPoller = + client.beginDeleteSecret("StorageAccountPassword"); + PollResponse pollResponse = deletedStorageSecretPoller.poll(); + DeletedSecret deletedStorageSecret = pollResponse.getValue(); + + System.out.println("Deleted Date %s" + deletedStorageSecret.getDeletedOn().toString()); + System.out.printf("Deleted Secret's Recovery Id %s", deletedStorageSecret.getRecoveryId()); + + // Secret is being deleted on server. + deletedStorageSecretPoller.waitForCompletion(); + + //To ensure the secret is deleted server-side. + Thread.sleep(30000); + + // If the vault is soft-delete enabled, then you need to purge the secret as well for permanent deletion. + client.purgeDeletedSecret("StorageAccountPassword"); + + // To ensure the secret is purged server-side. + Thread.sleep(15000); + + // After sometime, the secret is required again. We can use the backup value to restore it in the key vault. + byte[] backupFromFile = Files.readAllBytes(new File(backupFilePath).toPath()); + KeyVaultSecret restoredSecret = client.restoreSecretBackup(backupFromFile); + } + + private static void writeBackupToFile(byte[] bytes, String filePath) { + try { + File file = new File(filePath); + + if (file.exists()) { + file.delete(); + } + + file.createNewFile(); + + OutputStream os = new FileOutputStream(file); + os.write(bytes); + + System.out.println("Successfully wrote backup to file."); + + // Close the file + os.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample1/v2/BackupAndRestoreOperations.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample1/v2/BackupAndRestoreOperations.java new file mode 100644 index 000000000000..27938c5ccef5 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample1/v2/BackupAndRestoreOperations.java @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.secrets; + +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.security.keyvault.secrets.models.DeletedSecret; +import com.azure.security.keyvault.secrets.models.KeyVaultSecret; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.secrets.models.SecretProperties; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to backup and restore secrets in the key vault. + */ +public class BackupAndRestoreOperations { + /** + * Authenticates with the key vault and shows how to backup and restore secrets in the key vault. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + * @throws IOException when writing backup to file is unsuccessful. + */ + public static void main(String[] args) throws IOException, InterruptedException, IllegalArgumentException { + /* Instantiate a SecretClient that will be used to call the service. Notice that the client is using default + Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md) + for links and instructions. */ + SecretClient client = new SecretClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + // Let's create secrets holding storage account credentials valid for 1 year. If the secret already exists in + // the key vault, then a new version of the secret is created. + client.setSecret(new KeyVaultSecret("StorageAccountPassword", "f4G34fMh8v-fdsgjsk2323=-asdsdfsdf") + .setProperties(new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)))); + + // Backups are good to have, if in case secrets get accidentally deleted by you. + // For long term storage, it is ideal to write the backup to a file. + String backupFilePath = "YOUR_BACKUP_FILE_PATH"; + byte[] secretBackup = client.backupSecret("StorageAccountPassword"); + + writeBackupToFile(secretBackup, backupFilePath); + + // The storage account secret is no longer in use, so you delete it. + SyncPoller deletedStorageSecretPoller = + client.beginDeleteSecret("StorageAccountPassword"); + PollResponse pollResponse = deletedStorageSecretPoller.poll(); + DeletedSecret deletedStorageSecret = pollResponse.getValue(); + + System.out.println("Deleted Date %s" + deletedStorageSecret.getDeletedOn().toString()); + System.out.printf("Deleted Secret's Recovery Id %s", deletedStorageSecret.getRecoveryId()); + + // Secret is being deleted on server. + deletedStorageSecretPoller.waitForCompletion(); + + //To ensure the secret is deleted server-side. + Thread.sleep(30000); + + // If the vault is soft-delete enabled, then you need to purge the secret as well for permanent deletion. + client.purgeDeletedSecret("StorageAccountPassword"); + + // To ensure the secret is purged server-side. + Thread.sleep(15000); + + // After sometime, the secret is required again. We can use the backup value to restore it in the key vault. + byte[] backupFromFile = Files.readAllBytes(new File(backupFilePath).toPath()); + KeyVaultSecret restoredSecret = client.restoreSecretBackup(backupFromFile); + } + + private static void writeBackupToFile(byte[] bytes, String filePath) { + try { + File file = new File(filePath); + + if (file.exists()) { + file.delete(); + } + + file.createNewFile(); + + OutputStream os = new FileOutputStream(file); + os.write(bytes); + + System.out.println("Successfully wrote backup to file."); + + // Close the file + os.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample10/v1/ReadmeSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample10/v1/ReadmeSamples.java new file mode 100644 index 000000000000..0926105b7554 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample10/v1/ReadmeSamples.java @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.secrets; + +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.secrets.models.DeletedSecret; +import com.azure.security.keyvault.secrets.models.KeyVaultSecret; +import com.azure.security.keyvault.secrets.models.SecretProperties; + +import java.time.OffsetDateTime; + +@SuppressWarnings("unused") +public class ReadmeSamples { + private final SecretClient secretClient = new SecretClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + private final SecretAsyncClient secretAsyncClient = new SecretClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + public void createSecretClient() { + // BEGIN: readme-sample-createSecretClient + SecretClient secretClient = new SecretClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + // END: readme-sample-createSecretClient + } + + public void createSecret() { + // BEGIN: readme-sample-createSecret + KeyVaultSecret secret = secretClient.setSecret("", ""); + System.out.printf("Secret created with name \"%s\" and value \"%s\"%n", secret.getName(), secret.getValue()); + // END: readme-sample-createSecret + } + + public void retrieveSecret() { + // BEGIN: readme-sample-retrieveSecret + KeyVaultSecret secret = secretClient.getSecret(""); + System.out.printf("Retrieved secret with name \"%s\" and value \"%s\"%n", secret.getName(), secret.getValue()); + // END: readme-sample-retrieveSecret + } + + public void updateSecret() { + // BEGIN: readme-sample-updateSecret + // Get the secret to update. + KeyVaultSecret secret = secretClient.getSecret(""); + // Update the expiry time of the secret. + secret.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(30)); + SecretProperties updatedSecretProperties = secretClient.updateSecretProperties(secret.getProperties()); + System.out.printf("Secret's updated expiry time: %s%n", updatedSecretProperties.getExpiresOn()); + // END: readme-sample-updateSecret + } + + public void deleteSecret() { + // BEGIN: readme-sample-deleteSecret + SyncPoller deletedSecretPoller = secretClient.beginDeleteSecret(""); + + // Deleted secret is accessible as soon as polling begins. + PollResponse deletedSecretPollResponse = deletedSecretPoller.poll(); + + // Deletion date only works for a SoftDelete-enabled Key Vault. + System.out.printf("Deletion date: %s%n", deletedSecretPollResponse.getValue().getDeletedOn()); + + // Secret is being deleted on server. + deletedSecretPoller.waitForCompletion(); + // END: readme-sample-deleteSecret + } + + public void listSecrets() { + // BEGIN: readme-sample-listSecrets + // List operations don't return the secrets with value information. So, for each returned secret we call getSecret to + // get the secret with its value information. + for (SecretProperties secretProperties : secretClient.listPropertiesOfSecrets()) { + KeyVaultSecret secretWithValue = secretClient.getSecret(secretProperties.getName(), secretProperties.getVersion()); + System.out.printf("Retrieved secret with name \"%s\" and value \"%s\"%n", secretWithValue.getName(), + secretWithValue.getValue()); + } + // END: readme-sample-listSecrets + } + + public void createSecretAsync() { + // BEGIN: readme-sample-createSecretAsync + secretAsyncClient.setSecret("", "") + .subscribe(secret -> System.out.printf("Created secret with name \"%s\" and value \"%s\"%n", + secret.getName(), secret.getValue())); + // END: readme-sample-createSecretAsync + } + + public void retrieveSecretAsync() { + // BEGIN: readme-sample-retrieveSecretAsync + secretAsyncClient.getSecret("") + .subscribe(secret -> System.out.printf("Retrieved secret with name \"%s\" and value \"%s\"%n", + secret.getName(), secret.getValue())); + // END: readme-sample-retrieveSecretAsync + } + + public void updateSecretAsync() { + // BEGIN: readme-sample-updateSecretAsync + secretAsyncClient.getSecret("") + .flatMap(secret -> { + // Update the expiry time of the secret. + secret.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(50)); + return secretAsyncClient.updateSecretProperties(secret.getProperties()); + }).subscribe(updatedSecretProperties -> + System.out.printf("Secret's updated expiry time: %s%n", updatedSecretProperties.getExpiresOn())); + // END: readme-sample-updateSecretAsync + } + + public void deleteSecretAsync() { + // BEGIN: readme-sample-deleteSecretAsync + secretAsyncClient.beginDeleteSecret("") + .subscribe(pollResponse -> { + System.out.printf("Deletion status: %s%n", pollResponse.getStatus()); + System.out.printf("Deleted secret name: %s%n", pollResponse.getValue().getName()); + System.out.printf("Deleted secret value: %s%n", pollResponse.getValue().getValue()); + }); + // END: readme-sample-deleteSecretAsync + } + + public void listSecretsAsync() { + // BEGIN: readme-sample-listSecretsAsync + // The List secrets operation returns secrets without their value, so for each secret returned we call `getSecret` + // to get its value as well. + secretAsyncClient.listPropertiesOfSecrets() + .flatMap(secretProperties -> + secretAsyncClient.getSecret(secretProperties.getName(), secretProperties.getVersion())) + .subscribe(secretResponse -> + System.out.printf("Retrieved secret with name \"%s\" and value \"%s\"%n", secretResponse.getName(), + secretResponse.getValue())); + // END: readme-sample-listSecretsAsync + } + + public void troubleshooting() { + // BEGIN: readme-sample-troubleshooting + try { + secretClient.getSecret(""); + } catch (ResourceNotFoundException e) { + System.out.println(e.getMessage()); + } + // END: readme-sample-troubleshooting + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample10/v2/ReadmeSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample10/v2/ReadmeSamples.java new file mode 100644 index 000000000000..0926105b7554 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample10/v2/ReadmeSamples.java @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.secrets; + +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.secrets.models.DeletedSecret; +import com.azure.security.keyvault.secrets.models.KeyVaultSecret; +import com.azure.security.keyvault.secrets.models.SecretProperties; + +import java.time.OffsetDateTime; + +@SuppressWarnings("unused") +public class ReadmeSamples { + private final SecretClient secretClient = new SecretClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + private final SecretAsyncClient secretAsyncClient = new SecretClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + public void createSecretClient() { + // BEGIN: readme-sample-createSecretClient + SecretClient secretClient = new SecretClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + // END: readme-sample-createSecretClient + } + + public void createSecret() { + // BEGIN: readme-sample-createSecret + KeyVaultSecret secret = secretClient.setSecret("", ""); + System.out.printf("Secret created with name \"%s\" and value \"%s\"%n", secret.getName(), secret.getValue()); + // END: readme-sample-createSecret + } + + public void retrieveSecret() { + // BEGIN: readme-sample-retrieveSecret + KeyVaultSecret secret = secretClient.getSecret(""); + System.out.printf("Retrieved secret with name \"%s\" and value \"%s\"%n", secret.getName(), secret.getValue()); + // END: readme-sample-retrieveSecret + } + + public void updateSecret() { + // BEGIN: readme-sample-updateSecret + // Get the secret to update. + KeyVaultSecret secret = secretClient.getSecret(""); + // Update the expiry time of the secret. + secret.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(30)); + SecretProperties updatedSecretProperties = secretClient.updateSecretProperties(secret.getProperties()); + System.out.printf("Secret's updated expiry time: %s%n", updatedSecretProperties.getExpiresOn()); + // END: readme-sample-updateSecret + } + + public void deleteSecret() { + // BEGIN: readme-sample-deleteSecret + SyncPoller deletedSecretPoller = secretClient.beginDeleteSecret(""); + + // Deleted secret is accessible as soon as polling begins. + PollResponse deletedSecretPollResponse = deletedSecretPoller.poll(); + + // Deletion date only works for a SoftDelete-enabled Key Vault. + System.out.printf("Deletion date: %s%n", deletedSecretPollResponse.getValue().getDeletedOn()); + + // Secret is being deleted on server. + deletedSecretPoller.waitForCompletion(); + // END: readme-sample-deleteSecret + } + + public void listSecrets() { + // BEGIN: readme-sample-listSecrets + // List operations don't return the secrets with value information. So, for each returned secret we call getSecret to + // get the secret with its value information. + for (SecretProperties secretProperties : secretClient.listPropertiesOfSecrets()) { + KeyVaultSecret secretWithValue = secretClient.getSecret(secretProperties.getName(), secretProperties.getVersion()); + System.out.printf("Retrieved secret with name \"%s\" and value \"%s\"%n", secretWithValue.getName(), + secretWithValue.getValue()); + } + // END: readme-sample-listSecrets + } + + public void createSecretAsync() { + // BEGIN: readme-sample-createSecretAsync + secretAsyncClient.setSecret("", "") + .subscribe(secret -> System.out.printf("Created secret with name \"%s\" and value \"%s\"%n", + secret.getName(), secret.getValue())); + // END: readme-sample-createSecretAsync + } + + public void retrieveSecretAsync() { + // BEGIN: readme-sample-retrieveSecretAsync + secretAsyncClient.getSecret("") + .subscribe(secret -> System.out.printf("Retrieved secret with name \"%s\" and value \"%s\"%n", + secret.getName(), secret.getValue())); + // END: readme-sample-retrieveSecretAsync + } + + public void updateSecretAsync() { + // BEGIN: readme-sample-updateSecretAsync + secretAsyncClient.getSecret("") + .flatMap(secret -> { + // Update the expiry time of the secret. + secret.getProperties().setExpiresOn(OffsetDateTime.now().plusDays(50)); + return secretAsyncClient.updateSecretProperties(secret.getProperties()); + }).subscribe(updatedSecretProperties -> + System.out.printf("Secret's updated expiry time: %s%n", updatedSecretProperties.getExpiresOn())); + // END: readme-sample-updateSecretAsync + } + + public void deleteSecretAsync() { + // BEGIN: readme-sample-deleteSecretAsync + secretAsyncClient.beginDeleteSecret("") + .subscribe(pollResponse -> { + System.out.printf("Deletion status: %s%n", pollResponse.getStatus()); + System.out.printf("Deleted secret name: %s%n", pollResponse.getValue().getName()); + System.out.printf("Deleted secret value: %s%n", pollResponse.getValue().getValue()); + }); + // END: readme-sample-deleteSecretAsync + } + + public void listSecretsAsync() { + // BEGIN: readme-sample-listSecretsAsync + // The List secrets operation returns secrets without their value, so for each secret returned we call `getSecret` + // to get its value as well. + secretAsyncClient.listPropertiesOfSecrets() + .flatMap(secretProperties -> + secretAsyncClient.getSecret(secretProperties.getName(), secretProperties.getVersion())) + .subscribe(secretResponse -> + System.out.printf("Retrieved secret with name \"%s\" and value \"%s\"%n", secretResponse.getName(), + secretResponse.getValue())); + // END: readme-sample-listSecretsAsync + } + + public void troubleshooting() { + // BEGIN: readme-sample-troubleshooting + try { + secretClient.getSecret(""); + } catch (ResourceNotFoundException e) { + System.out.println(e.getMessage()); + } + // END: readme-sample-troubleshooting + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample11/v1/SecretAsyncClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample11/v1/SecretAsyncClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..8cbe0001e494 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample11/v1/SecretAsyncClientJavaDocCodeSnippets.java @@ -0,0 +1,356 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.secrets; + +import com.azure.core.http.HttpClient; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.policy.HttpLogOptions; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.secrets.models.KeyVaultSecret; +import com.azure.security.keyvault.secrets.models.SecretProperties; +import reactor.util.context.Context; + +import java.time.OffsetDateTime; + +/** + * This class contains code samples for generating javadocs through doclets for {@link SecretAsyncClient}. + */ +public final class SecretAsyncClientJavaDocCodeSnippets { + private final String key1 = "key1"; + private final String key2 = "key2"; + private final String value1 = "val1"; + private final String value2 = "val2"; + + /** + * Generates code sample for creating a {@link SecretAsyncClient}. + * + * @return An instance of {@link SecretAsyncClient}. + */ + public SecretAsyncClient createAsyncClientWithHttpclient() { + // BEGIN: com.azure.security.keyvault.secrets.SecretAsyncClient.instantiation.withHttpClient + SecretAsyncClient secretAsyncClient = new SecretClientBuilder() + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .httpClient(HttpClient.createDefault()) + .buildAsyncClient(); + // END: com.azure.security.keyvault.secrets.SecretAsyncClient.instantiation.withHttpClient + return secretAsyncClient; + } + + /** + * Generates code sample for creating a {@link SecretAsyncClient}. + * + * @return An instance of {@link SecretAsyncClient}. + */ + private SecretAsyncClient getAsyncSecretClient() { + // BEGIN: com.azure.security.keyvault.secrets.SecretAsyncClient.instantiation + SecretAsyncClient secretAsyncClient = new SecretClientBuilder() + .credential(new DefaultAzureCredentialBuilder().build()) + .vaultUrl("") + .buildAsyncClient(); + // END: com.azure.security.keyvault.secrets.SecretAsyncClient.instantiation + return secretAsyncClient; + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#getSecret(String, String)}. + */ + public void getSecretCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.getSecret#string-string + String secretVersion = "6A385B124DEF4096AF1361A85B16C204"; + secretAsyncClient.getSecret("secretName", secretVersion) + // Passing a Context is optional and useful if you want a set of data to flow through the request. + // Otherwise, the line below can be removed. + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(secretWithVersion -> + System.out.printf("Secret is returned with name %s and value %s %n", + secretWithVersion.getName(), secretWithVersion.getValue())); + // END: com.azure.keyvault.secrets.SecretClient.getSecret#string-string + + // BEGIN: com.azure.keyvault.secrets.SecretClient.getSecret#string + secretAsyncClient.getSecret("secretName") + .subscribe(secretWithVersion -> + System.out.printf("Secret is returned with name %s and value %s %n", + secretWithVersion.getName(), secretWithVersion.getValue())); + // END: com.azure.keyvault.secrets.SecretClient.getSecret#string + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#getSecretWithResponse(String, String)}. + */ + public void getSecretWithResponseCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + + // BEGIN: com.azure.keyvault.secrets.SecretClient.getSecretWithResponse#string-string + String secretVersion = "6A385B124DEF4096AF1361A85B16C204"; + secretAsyncClient.getSecretWithResponse("secretName", secretVersion) + // Passing a Context is optional and useful if you want a set of data to flow through the request. + // Otherwise, the line below can be removed. + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(secretWithVersion -> + System.out.printf("Secret is returned with name %s and value %s %n", + secretWithVersion.getValue().getName(), secretWithVersion.getValue().getValue())); + // END: com.azure.keyvault.secrets.SecretClient.getSecretWithResponse#string-string + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#setSecret(KeyVaultSecret)}. + */ + public void setSecretCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.setSecret#secret + SecretProperties properties = new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusDays(60)); + KeyVaultSecret newSecret = new KeyVaultSecret("secretName", "secretValue") + .setProperties(properties); + + secretAsyncClient.setSecret(newSecret) + .subscribe(secretResponse -> + System.out.printf("Secret is created with name %s and value %s %n", + secretResponse.getName(), secretResponse.getValue())); + // END: com.azure.keyvault.secrets.SecretClient.setSecret#secret + + // BEGIN: com.azure.keyvault.secrets.SecretClient.setSecret#string-string + secretAsyncClient.setSecret("secretName", "secretValue") + .subscribe(secretResponse -> + System.out.printf("Secret is created with name %s and value %s%n", + secretResponse.getName(), secretResponse.getValue())); + // END: com.azure.keyvault.secrets.SecretClient.setSecret#string-string + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#setSecretWithResponse(KeyVaultSecret)}. + */ + public void setSecretWithResponseCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.setSecretWithResponse#secret + KeyVaultSecret newSecret = new KeyVaultSecret("secretName", "secretValue"). + setProperties(new SecretProperties().setExpiresOn(OffsetDateTime.now().plusDays(60))); + secretAsyncClient.setSecretWithResponse(newSecret) + .subscribe(secretResponse -> + System.out.printf("Secret is created with name %s and value %s %n", + secretResponse.getValue().getName(), secretResponse.getValue().getValue())); + // END: com.azure.keyvault.secrets.SecretClient.setSecretWithResponse#secret + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#updateSecretProperties(SecretProperties)}. + */ + public void updateSecretCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.updateSecretProperties#secretProperties + secretAsyncClient.getSecret("secretName") + .subscribe(secretResponseValue -> { + SecretProperties secretProperties = secretResponseValue.getProperties(); + //Update the not before time of the secret. + secretProperties.setNotBefore(OffsetDateTime.now().plusDays(50)); + secretAsyncClient.updateSecretProperties(secretProperties) + .subscribe(secretResponse -> + System.out.printf("Secret's updated not before time %s %n", + secretResponse.getNotBefore().toString())); + }); + // END: com.azure.keyvault.secrets.SecretClient.updateSecretProperties#secretProperties + } + + /** + * Method to insert code snippets for + * {@link SecretAsyncClient#updateSecretPropertiesWithResponse(SecretProperties)}. + */ + public void updateSecretWithResponseCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.updateSecretPropertiesWithResponse#secretProperties + secretAsyncClient.getSecret("secretName") + .subscribe(secretResponseValue -> { + SecretProperties secretProperties = secretResponseValue.getProperties(); + //Update the not before time of the secret. + secretProperties.setNotBefore(OffsetDateTime.now().plusDays(50)); + secretAsyncClient.updateSecretPropertiesWithResponse(secretProperties) + .subscribe(secretResponse -> + System.out.printf("Secret's updated not before time %s %n", + secretResponse.getValue().getNotBefore().toString())); + }); + // END: com.azure.keyvault.secrets.SecretClient.updateSecretPropertiesWithResponse#secretProperties + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#beginDeleteSecret(String)}. + */ + public void deleteSecretCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.deleteSecret#String + secretAsyncClient.beginDeleteSecret("secretName") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Deleted Secret Name: " + pollResponse.getValue().getName()); + System.out.println("Deleted Secret Value: " + pollResponse.getValue().getValue()); + }); + // END: com.azure.keyvault.secrets.SecretClient.deleteSecret#String + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#getDeletedSecret(String)}. + */ + public void getDeletedSecretCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.getDeletedSecret#string + secretAsyncClient.getDeletedSecret("secretName") + .subscribe(deletedSecretResponse -> + System.out.printf("Deleted Secret's Recovery Id %s %n", deletedSecretResponse.getRecoveryId())); + // END: com.azure.keyvault.secrets.SecretClient.getDeletedSecret#string + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#getDeletedSecretWithResponse(String)}. + */ + public void getDeletedSecretWithResponseCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.getDeletedSecretWithResponse#string + secretAsyncClient.getDeletedSecretWithResponse("secretName") + .subscribe(deletedSecretResponse -> + System.out.printf("Deleted Secret's Recovery Id %s %n", + deletedSecretResponse.getValue().getRecoveryId())); + // END: com.azure.keyvault.secrets.SecretClient.getDeletedSecretWithResponse#string + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#purgeDeletedSecret(String)}. + */ + public void purgeDeletedSecretCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.purgeDeletedSecret#string + secretAsyncClient.purgeDeletedSecret("deletedSecretName") + .doOnSuccess(purgeResponse -> + System.out.println("Successfully Purged deleted Secret")) + .subscribe(); + // END: com.azure.keyvault.secrets.SecretClient.purgeDeletedSecret#string + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#purgeDeletedSecretWithResponse(String)}. + */ + public void purgeDeletedSecretWithResponseCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.purgeDeletedSecretWithResponse#string + secretAsyncClient.purgeDeletedSecretWithResponse("deletedSecretName") + .subscribe(purgeResponse -> + System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode())); + // END: com.azure.keyvault.secrets.SecretClient.purgeDeletedSecretWithResponse#string + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#beginRecoverDeletedSecret(String)}. + */ + public void recoverDeletedSecretCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.recoverDeletedSecret#String + secretAsyncClient.beginRecoverDeletedSecret("deletedSecretName") + .subscribe(pollResponse -> { + System.out.println("Recovery Status: " + pollResponse.getStatus().toString()); + System.out.println("Recovered Secret Name: " + pollResponse.getValue().getName()); + System.out.println("Recovered Secret Value: " + pollResponse.getValue().getValue()); + }); + // END: com.azure.keyvault.secrets.SecretClient.recoverDeletedSecret#String + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#backupSecret(String)}. + */ + public void backupSecretCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.backupSecret#string + secretAsyncClient.backupSecret("secretName") + .subscribe(secretBackupResponse -> + System.out.printf("Secret's Backup Byte array's length %s%n", secretBackupResponse.length)); + // END: com.azure.keyvault.secrets.SecretClient.backupSecret#string + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#backupSecretWithResponse(String)}. + */ + public void backupSecretWithResponseCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.backupSecretWithResponse#string + secretAsyncClient.backupSecretWithResponse("secretName") + .subscribe(secretBackupResponse -> + System.out.printf("Secret's Backup Byte array's length %s%n", secretBackupResponse.getValue().length)); + // END: com.azure.keyvault.secrets.SecretClient.backupSecretWithResponse#string + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#restoreSecretBackup(byte[])}. + */ + public void restoreSecretCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.restoreSecret#byte + // Pass the secret backup byte array to the restore operation. + byte[] secretBackupByteArray = {}; + secretAsyncClient.restoreSecretBackup(secretBackupByteArray) + .subscribe(secretResponse -> System.out.printf("Restored Secret with name %s and value %s %n", + secretResponse.getName(), secretResponse.getValue())); + // END: com.azure.keyvault.secrets.SecretClient.restoreSecret#byte + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#restoreSecretBackupWithResponse(byte[])}. + */ + public void restoreSecretWithResponseCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.restoreSecretWithResponse#byte + // Pass the secret backup byte array to the restore operation. + byte[] secretBackupByteArray = {}; + secretAsyncClient.restoreSecretBackupWithResponse(secretBackupByteArray) + .subscribe(secretResponse -> System.out.printf("Restored Secret with name %s and value %s %n", + secretResponse.getValue().getName(), secretResponse.getValue().getValue())); + // END: com.azure.keyvault.secrets.SecretClient.restoreSecretWithResponse#byte + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#listPropertiesOfSecrets()}. + */ + public void listSecretsCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.listSecrets + secretAsyncClient.listPropertiesOfSecrets() + .flatMap(secretProperties -> { + String name = secretProperties.getName(); + String version = secretProperties.getVersion(); + + System.out.printf("Getting secret name: '%s', version: %s%n", name, version); + return secretAsyncClient.getSecret(name, version); + }) + .subscribe(secretResponse -> System.out.printf("Received secret with name %s and type %s", + secretResponse.getName(), secretResponse.getValue())); + // END: com.azure.keyvault.secrets.SecretClient.listSecrets + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#listDeletedSecrets()}. + */ + public void listDeletedSecretsCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.listDeletedSecrets + secretAsyncClient.listDeletedSecrets() + .subscribe(deletedSecretResponse -> System.out.printf("Deleted Secret's Recovery Id %s %n", + deletedSecretResponse.getRecoveryId())); + // END: com.azure.keyvault.secrets.SecretClient.listDeletedSecrets + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#listPropertiesOfSecretVersions(String)}. + */ + public void listSecretVersionsCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.listSecretVersions#string + secretAsyncClient.listPropertiesOfSecretVersions("secretName") + .flatMap(secretProperties -> { + System.out.println("Get secret value for version: " + secretProperties.getVersion()); + return secretAsyncClient.getSecret(secretProperties.getName(), secretProperties.getVersion()); + }) + .subscribe(secret -> System.out.printf("Received secret with name %s and type %s%n", + secret.getName(), secret.getValue())); + // END: com.azure.keyvault.secrets.SecretClient.listSecretVersions#string + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample11/v2/SecretAsyncClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample11/v2/SecretAsyncClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..8cbe0001e494 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample11/v2/SecretAsyncClientJavaDocCodeSnippets.java @@ -0,0 +1,356 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.secrets; + +import com.azure.core.http.HttpClient; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.policy.HttpLogOptions; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.secrets.models.KeyVaultSecret; +import com.azure.security.keyvault.secrets.models.SecretProperties; +import reactor.util.context.Context; + +import java.time.OffsetDateTime; + +/** + * This class contains code samples for generating javadocs through doclets for {@link SecretAsyncClient}. + */ +public final class SecretAsyncClientJavaDocCodeSnippets { + private final String key1 = "key1"; + private final String key2 = "key2"; + private final String value1 = "val1"; + private final String value2 = "val2"; + + /** + * Generates code sample for creating a {@link SecretAsyncClient}. + * + * @return An instance of {@link SecretAsyncClient}. + */ + public SecretAsyncClient createAsyncClientWithHttpclient() { + // BEGIN: com.azure.security.keyvault.secrets.SecretAsyncClient.instantiation.withHttpClient + SecretAsyncClient secretAsyncClient = new SecretClientBuilder() + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .httpClient(HttpClient.createDefault()) + .buildAsyncClient(); + // END: com.azure.security.keyvault.secrets.SecretAsyncClient.instantiation.withHttpClient + return secretAsyncClient; + } + + /** + * Generates code sample for creating a {@link SecretAsyncClient}. + * + * @return An instance of {@link SecretAsyncClient}. + */ + private SecretAsyncClient getAsyncSecretClient() { + // BEGIN: com.azure.security.keyvault.secrets.SecretAsyncClient.instantiation + SecretAsyncClient secretAsyncClient = new SecretClientBuilder() + .credential(new DefaultAzureCredentialBuilder().build()) + .vaultUrl("") + .buildAsyncClient(); + // END: com.azure.security.keyvault.secrets.SecretAsyncClient.instantiation + return secretAsyncClient; + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#getSecret(String, String)}. + */ + public void getSecretCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.getSecret#string-string + String secretVersion = "6A385B124DEF4096AF1361A85B16C204"; + secretAsyncClient.getSecret("secretName", secretVersion) + // Passing a Context is optional and useful if you want a set of data to flow through the request. + // Otherwise, the line below can be removed. + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(secretWithVersion -> + System.out.printf("Secret is returned with name %s and value %s %n", + secretWithVersion.getName(), secretWithVersion.getValue())); + // END: com.azure.keyvault.secrets.SecretClient.getSecret#string-string + + // BEGIN: com.azure.keyvault.secrets.SecretClient.getSecret#string + secretAsyncClient.getSecret("secretName") + .subscribe(secretWithVersion -> + System.out.printf("Secret is returned with name %s and value %s %n", + secretWithVersion.getName(), secretWithVersion.getValue())); + // END: com.azure.keyvault.secrets.SecretClient.getSecret#string + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#getSecretWithResponse(String, String)}. + */ + public void getSecretWithResponseCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + + // BEGIN: com.azure.keyvault.secrets.SecretClient.getSecretWithResponse#string-string + String secretVersion = "6A385B124DEF4096AF1361A85B16C204"; + secretAsyncClient.getSecretWithResponse("secretName", secretVersion) + // Passing a Context is optional and useful if you want a set of data to flow through the request. + // Otherwise, the line below can be removed. + .contextWrite(Context.of(key1, value1, key2, value2)) + .subscribe(secretWithVersion -> + System.out.printf("Secret is returned with name %s and value %s %n", + secretWithVersion.getValue().getName(), secretWithVersion.getValue().getValue())); + // END: com.azure.keyvault.secrets.SecretClient.getSecretWithResponse#string-string + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#setSecret(KeyVaultSecret)}. + */ + public void setSecretCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.setSecret#secret + SecretProperties properties = new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusDays(60)); + KeyVaultSecret newSecret = new KeyVaultSecret("secretName", "secretValue") + .setProperties(properties); + + secretAsyncClient.setSecret(newSecret) + .subscribe(secretResponse -> + System.out.printf("Secret is created with name %s and value %s %n", + secretResponse.getName(), secretResponse.getValue())); + // END: com.azure.keyvault.secrets.SecretClient.setSecret#secret + + // BEGIN: com.azure.keyvault.secrets.SecretClient.setSecret#string-string + secretAsyncClient.setSecret("secretName", "secretValue") + .subscribe(secretResponse -> + System.out.printf("Secret is created with name %s and value %s%n", + secretResponse.getName(), secretResponse.getValue())); + // END: com.azure.keyvault.secrets.SecretClient.setSecret#string-string + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#setSecretWithResponse(KeyVaultSecret)}. + */ + public void setSecretWithResponseCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.setSecretWithResponse#secret + KeyVaultSecret newSecret = new KeyVaultSecret("secretName", "secretValue"). + setProperties(new SecretProperties().setExpiresOn(OffsetDateTime.now().plusDays(60))); + secretAsyncClient.setSecretWithResponse(newSecret) + .subscribe(secretResponse -> + System.out.printf("Secret is created with name %s and value %s %n", + secretResponse.getValue().getName(), secretResponse.getValue().getValue())); + // END: com.azure.keyvault.secrets.SecretClient.setSecretWithResponse#secret + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#updateSecretProperties(SecretProperties)}. + */ + public void updateSecretCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.updateSecretProperties#secretProperties + secretAsyncClient.getSecret("secretName") + .subscribe(secretResponseValue -> { + SecretProperties secretProperties = secretResponseValue.getProperties(); + //Update the not before time of the secret. + secretProperties.setNotBefore(OffsetDateTime.now().plusDays(50)); + secretAsyncClient.updateSecretProperties(secretProperties) + .subscribe(secretResponse -> + System.out.printf("Secret's updated not before time %s %n", + secretResponse.getNotBefore().toString())); + }); + // END: com.azure.keyvault.secrets.SecretClient.updateSecretProperties#secretProperties + } + + /** + * Method to insert code snippets for + * {@link SecretAsyncClient#updateSecretPropertiesWithResponse(SecretProperties)}. + */ + public void updateSecretWithResponseCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.updateSecretPropertiesWithResponse#secretProperties + secretAsyncClient.getSecret("secretName") + .subscribe(secretResponseValue -> { + SecretProperties secretProperties = secretResponseValue.getProperties(); + //Update the not before time of the secret. + secretProperties.setNotBefore(OffsetDateTime.now().plusDays(50)); + secretAsyncClient.updateSecretPropertiesWithResponse(secretProperties) + .subscribe(secretResponse -> + System.out.printf("Secret's updated not before time %s %n", + secretResponse.getValue().getNotBefore().toString())); + }); + // END: com.azure.keyvault.secrets.SecretClient.updateSecretPropertiesWithResponse#secretProperties + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#beginDeleteSecret(String)}. + */ + public void deleteSecretCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.deleteSecret#String + secretAsyncClient.beginDeleteSecret("secretName") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Deleted Secret Name: " + pollResponse.getValue().getName()); + System.out.println("Deleted Secret Value: " + pollResponse.getValue().getValue()); + }); + // END: com.azure.keyvault.secrets.SecretClient.deleteSecret#String + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#getDeletedSecret(String)}. + */ + public void getDeletedSecretCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.getDeletedSecret#string + secretAsyncClient.getDeletedSecret("secretName") + .subscribe(deletedSecretResponse -> + System.out.printf("Deleted Secret's Recovery Id %s %n", deletedSecretResponse.getRecoveryId())); + // END: com.azure.keyvault.secrets.SecretClient.getDeletedSecret#string + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#getDeletedSecretWithResponse(String)}. + */ + public void getDeletedSecretWithResponseCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.getDeletedSecretWithResponse#string + secretAsyncClient.getDeletedSecretWithResponse("secretName") + .subscribe(deletedSecretResponse -> + System.out.printf("Deleted Secret's Recovery Id %s %n", + deletedSecretResponse.getValue().getRecoveryId())); + // END: com.azure.keyvault.secrets.SecretClient.getDeletedSecretWithResponse#string + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#purgeDeletedSecret(String)}. + */ + public void purgeDeletedSecretCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.purgeDeletedSecret#string + secretAsyncClient.purgeDeletedSecret("deletedSecretName") + .doOnSuccess(purgeResponse -> + System.out.println("Successfully Purged deleted Secret")) + .subscribe(); + // END: com.azure.keyvault.secrets.SecretClient.purgeDeletedSecret#string + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#purgeDeletedSecretWithResponse(String)}. + */ + public void purgeDeletedSecretWithResponseCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.purgeDeletedSecretWithResponse#string + secretAsyncClient.purgeDeletedSecretWithResponse("deletedSecretName") + .subscribe(purgeResponse -> + System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode())); + // END: com.azure.keyvault.secrets.SecretClient.purgeDeletedSecretWithResponse#string + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#beginRecoverDeletedSecret(String)}. + */ + public void recoverDeletedSecretCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.recoverDeletedSecret#String + secretAsyncClient.beginRecoverDeletedSecret("deletedSecretName") + .subscribe(pollResponse -> { + System.out.println("Recovery Status: " + pollResponse.getStatus().toString()); + System.out.println("Recovered Secret Name: " + pollResponse.getValue().getName()); + System.out.println("Recovered Secret Value: " + pollResponse.getValue().getValue()); + }); + // END: com.azure.keyvault.secrets.SecretClient.recoverDeletedSecret#String + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#backupSecret(String)}. + */ + public void backupSecretCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.backupSecret#string + secretAsyncClient.backupSecret("secretName") + .subscribe(secretBackupResponse -> + System.out.printf("Secret's Backup Byte array's length %s%n", secretBackupResponse.length)); + // END: com.azure.keyvault.secrets.SecretClient.backupSecret#string + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#backupSecretWithResponse(String)}. + */ + public void backupSecretWithResponseCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.backupSecretWithResponse#string + secretAsyncClient.backupSecretWithResponse("secretName") + .subscribe(secretBackupResponse -> + System.out.printf("Secret's Backup Byte array's length %s%n", secretBackupResponse.getValue().length)); + // END: com.azure.keyvault.secrets.SecretClient.backupSecretWithResponse#string + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#restoreSecretBackup(byte[])}. + */ + public void restoreSecretCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.restoreSecret#byte + // Pass the secret backup byte array to the restore operation. + byte[] secretBackupByteArray = {}; + secretAsyncClient.restoreSecretBackup(secretBackupByteArray) + .subscribe(secretResponse -> System.out.printf("Restored Secret with name %s and value %s %n", + secretResponse.getName(), secretResponse.getValue())); + // END: com.azure.keyvault.secrets.SecretClient.restoreSecret#byte + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#restoreSecretBackupWithResponse(byte[])}. + */ + public void restoreSecretWithResponseCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.restoreSecretWithResponse#byte + // Pass the secret backup byte array to the restore operation. + byte[] secretBackupByteArray = {}; + secretAsyncClient.restoreSecretBackupWithResponse(secretBackupByteArray) + .subscribe(secretResponse -> System.out.printf("Restored Secret with name %s and value %s %n", + secretResponse.getValue().getName(), secretResponse.getValue().getValue())); + // END: com.azure.keyvault.secrets.SecretClient.restoreSecretWithResponse#byte + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#listPropertiesOfSecrets()}. + */ + public void listSecretsCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.listSecrets + secretAsyncClient.listPropertiesOfSecrets() + .flatMap(secretProperties -> { + String name = secretProperties.getName(); + String version = secretProperties.getVersion(); + + System.out.printf("Getting secret name: '%s', version: %s%n", name, version); + return secretAsyncClient.getSecret(name, version); + }) + .subscribe(secretResponse -> System.out.printf("Received secret with name %s and type %s", + secretResponse.getName(), secretResponse.getValue())); + // END: com.azure.keyvault.secrets.SecretClient.listSecrets + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#listDeletedSecrets()}. + */ + public void listDeletedSecretsCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.listDeletedSecrets + secretAsyncClient.listDeletedSecrets() + .subscribe(deletedSecretResponse -> System.out.printf("Deleted Secret's Recovery Id %s %n", + deletedSecretResponse.getRecoveryId())); + // END: com.azure.keyvault.secrets.SecretClient.listDeletedSecrets + } + + /** + * Method to insert code snippets for {@link SecretAsyncClient#listPropertiesOfSecretVersions(String)}. + */ + public void listSecretVersionsCodeSnippets() { + SecretAsyncClient secretAsyncClient = getAsyncSecretClient(); + // BEGIN: com.azure.keyvault.secrets.SecretClient.listSecretVersions#string + secretAsyncClient.listPropertiesOfSecretVersions("secretName") + .flatMap(secretProperties -> { + System.out.println("Get secret value for version: " + secretProperties.getVersion()); + return secretAsyncClient.getSecret(secretProperties.getName(), secretProperties.getVersion()); + }) + .subscribe(secret -> System.out.printf("Received secret with name %s and type %s%n", + secret.getName(), secret.getValue())); + // END: com.azure.keyvault.secrets.SecretClient.listSecretVersions#string + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample12/v1/SecretClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample12/v1/SecretClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..7a0625a9b159 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample12/v1/SecretClientJavaDocCodeSnippets.java @@ -0,0 +1,383 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.secrets; + +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.secrets.models.DeletedSecret; +import com.azure.security.keyvault.secrets.models.KeyVaultSecret; +import com.azure.security.keyvault.secrets.models.SecretProperties; + +import java.time.OffsetDateTime; + +/** + * This class contains code samples for generating javadocs through doclets for {@link SecretClient}. + */ +public final class SecretClientJavaDocCodeSnippets { + private final String key1 = "key1"; + private final String key2 = "key2"; + private final String value1 = "val1"; + private final String value2 = "val2"; + + /** + * Generates code sample for creating a {@link SecretClient}. + * + * @return An instance of {@link SecretClient}. + */ + private SecretClient getSecretClient() { + // BEGIN: com.azure.security.keyvault.SecretClient.instantiation + SecretClient secretClient = new SecretClientBuilder() + .credential(new DefaultAzureCredentialBuilder().build()) + .vaultUrl("") + .buildClient(); + // END: com.azure.security.keyvault.SecretClient.instantiation + return secretClient; + } + + /** + * Method to insert code snippets for {@link SecretClient#getSecret(String, String)}. + */ + public void getSecretCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.getSecret#secretProperties + for (SecretProperties secret : secretClient.listPropertiesOfSecrets()) { + KeyVaultSecret secretWithValue = secretClient.getSecret(secret.getName(), secret.getVersion()); + System.out.printf("Secret is returned with name %s and value %s%n", secretWithValue.getName(), + secretWithValue.getValue()); + } + // END: com.azure.security.keyvault.SecretClient.getSecret#secretProperties + + // BEGIN: com.azure.security.keyvault.SecretClient.getSecret#string-string + String secretVersion = "6A385B124DEF4096AF1361A85B16C204"; + KeyVaultSecret secretWithVersion = secretClient.getSecret("secretName", secretVersion); + System.out.printf("Secret is returned with name %s and value %s%n", + secretWithVersion.getName(), secretWithVersion.getValue()); + // END: com.azure.security.keyvault.SecretClient.getSecret#string-string + + // BEGIN: com.azure.security.keyvault.SecretClient.getSecret#string + KeyVaultSecret secret = secretClient.getSecret("secretName"); + System.out.printf("Secret is returned with name %s and value %s%n", + secret.getName(), secret.getValue()); + // END: com.azure.security.keyvault.SecretClient.getSecret#string + } + + /** + * Method to insert code snippets for {@link SecretClient#getSecretWithResponse(String, String, Context)}. + */ + public void getSecretWithResponseCodeSnippets() { + SecretClient secretClient = getSecretClient(); + + // BEGIN: com.azure.security.keyvault.SecretClient.getSecretWithResponse#string-string-Context + String secretVersion = "6A385B124DEF4096AF1361A85B16C204"; + KeyVaultSecret secretWithVersion = secretClient.getSecretWithResponse("secretName", secretVersion, + new Context(key2, value2)).getValue(); + System.out.printf("Secret is returned with name %s and value %s%n", + secretWithVersion.getName(), secretWithVersion.getValue()); + // END: com.azure.security.keyvault.SecretClient.getSecretWithResponse#string-string-Context + } + + /** + * Method to insert code snippets for {@link SecretClient#setSecret(KeyVaultSecret)}. + */ + public void setSecretCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.setSecret#secret + KeyVaultSecret newSecret = new KeyVaultSecret("secretName", "secretValue") + .setProperties(new SecretProperties().setExpiresOn(OffsetDateTime.now().plusDays(60))); + KeyVaultSecret returnedSecret = secretClient.setSecret(newSecret); + System.out.printf("Secret is created with name %s and value %s%n", returnedSecret.getName(), + returnedSecret.getValue()); + // END: com.azure.security.keyvault.SecretClient.setSecret#secret + + // BEGIN: com.azure.security.keyvault.SecretClient.setSecret#string-string + KeyVaultSecret secret = secretClient.setSecret("secretName", "secretValue"); + System.out.printf("Secret is created with name %s and value %s%n", secret.getName(), secret.getValue()); + // END: com.azure.security.keyvault.SecretClient.setSecret#string-string + } + + /** + * Method to insert code snippets for {@link SecretClient#setSecretWithResponse(KeyVaultSecret, Context)}. + */ + public void setSecretWithResponseCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.setSecretWithResponse#secret-Context + KeyVaultSecret newSecret = new KeyVaultSecret("secretName", "secretValue") + .setProperties(new SecretProperties().setExpiresOn(OffsetDateTime.now().plusDays(60))); + KeyVaultSecret secret = secretClient.setSecretWithResponse(newSecret, new Context(key1, value1)).getValue(); + System.out.printf("Secret is created with name %s and value %s%n", secret.getName(), secret.getValue()); + // END: com.azure.security.keyvault.SecretClient.setSecretWithResponse#secret-Context + } + + /** + * Method to insert code snippets for {@link SecretClient#updateSecretProperties(SecretProperties)}. + */ + public void updateSecretCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.updateSecretProperties#secretProperties + SecretProperties secretProperties = secretClient.getSecret("secretName").getProperties(); + secretProperties.setExpiresOn(OffsetDateTime.now().plusDays(60)); + SecretProperties updatedSecretProperties = secretClient.updateSecretProperties(secretProperties); + KeyVaultSecret updatedSecret = secretClient.getSecret(updatedSecretProperties.getName()); + System.out.printf("Updated Secret is returned with name %s, value %s and expires %s%n", + updatedSecret.getName(), updatedSecret.getValue(), updatedSecret.getProperties().getExpiresOn()); + // END: com.azure.security.keyvault.SecretClient.updateSecretProperties#secretProperties + } + + /** + * Method to insert code snippets for + * {@link SecretClient#updateSecretPropertiesWithResponse(SecretProperties, Context)}. + */ + public void updateSecretWithResponseCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.updateSecretPropertiesWithResponse#secretProperties-Context + SecretProperties secretProperties = secretClient.getSecret("secretName").getProperties(); + secretProperties.setExpiresOn(OffsetDateTime.now().plusDays(60)); + SecretProperties updatedSecretBase = secretClient.updateSecretPropertiesWithResponse(secretProperties, + new Context(key2, value2)).getValue(); + KeyVaultSecret updatedSecret = secretClient.getSecret(updatedSecretBase.getName()); + System.out.printf("Updated Secret is returned with name %s, value %s and expires %s%n", + updatedSecret.getName(), updatedSecret.getValue(), updatedSecret.getProperties().getExpiresOn()); + // END: com.azure.security.keyvault.SecretClient.updateSecretPropertiesWithResponse#secretProperties-Context + } + + /** + * Method to insert code snippets for {@link SecretClient#beginDeleteSecret(String)}. + */ + public void deleteSecretCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.deleteSecret#String + SyncPoller deleteSecretPoller = secretClient.beginDeleteSecret("secretName"); + + // Deleted Secret is accessible as soon as polling begins. + PollResponse deleteSecretPollResponse = deleteSecretPoller.poll(); + + // Deletion date only works for a SoftDelete-enabled Key Vault. + System.out.println("Deleted Date %s" + deleteSecretPollResponse.getValue() + .getDeletedOn().toString()); + System.out.printf("Deleted Secret's Recovery Id %s", deleteSecretPollResponse.getValue() + .getRecoveryId()); + + // Secret is being deleted on server. + deleteSecretPoller.waitForCompletion(); + // END: com.azure.security.keyvault.SecretClient.deleteSecret#String + } + + /** + * Method to insert code snippets for {@link SecretClient#beginDeleteSecret(String)}. + */ + public void getDeletedSecretCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.getDeletedSecret#string + DeletedSecret deletedSecret = secretClient.getDeletedSecret("secretName"); + System.out.printf("Deleted Secret's Recovery Id %s", deletedSecret.getRecoveryId()); + // END: com.azure.security.keyvault.SecretClient.getDeletedSecret#string + } + + /** + * Method to insert code snippets for {@link SecretClient#getDeletedSecretWithResponse(String, Context)}. + */ + public void getDeletedSecretWithResponseCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.getDeletedSecretWithResponse#string-Context + DeletedSecret deletedSecret = secretClient.getDeletedSecretWithResponse("secretName", + new Context(key2, value2)).getValue(); + System.out.printf("Deleted Secret's Recovery Id %s", deletedSecret.getRecoveryId()); + // END: com.azure.security.keyvault.SecretClient.getDeletedSecretWithResponse#string-Context + } + + /** + * Method to insert code snippets for {@link SecretClient#purgeDeletedSecret(String)}. + */ + public void purgeDeletedSecretCodeSnippets() { + SecretClient secretClient = getSecretClient(); + + // BEGIN: com.azure.security.keyvault.SecretClient.purgeDeletedSecret#string + secretClient.purgeDeletedSecret("secretName"); + // END: com.azure.security.keyvault.SecretClient.purgeDeletedSecret#string + } + + /** + * Method to insert code snippets for {@link SecretClient#purgeDeletedSecretWithResponse(String, Context)}. + */ + public void purgeDeletedSecretWithResponseCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.purgeDeletedSecretWithResponse#string-Context + Response purgeResponse = secretClient.purgeDeletedSecretWithResponse("secretName", + new Context(key1, value1)); + System.out.printf("Purge Status Code: %d", purgeResponse.getStatusCode()); + // END: com.azure.security.keyvault.SecretClient.purgeDeletedSecretWithResponse#string-Context + } + + /** + * Method to insert code snippets for {@link SecretClient#beginRecoverDeletedSecret(String)}. + */ + public void recoverDeletedSecretCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.recoverDeletedSecret#String + SyncPoller recoverSecretPoller = + secretClient.beginRecoverDeletedSecret("deletedSecretName"); + + // Deleted Secret can be accessed as soon as polling is in progress. + PollResponse recoveredSecretPollResponse = recoverSecretPoller.poll(); + System.out.println("Recovered Key Name %s" + recoveredSecretPollResponse.getValue().getName()); + System.out.printf("Recovered Key's Id %s", recoveredSecretPollResponse.getValue().getId()); + + // Key is being recovered on server. + recoverSecretPoller.waitForCompletion(); + // END: com.azure.security.keyvault.SecretClient.recoverDeletedSecret#String + } + + /** + * Method to insert code snippets for {@link SecretClient#backupSecret(String)}. + */ + public void backupSecretCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.backupSecret#string + byte[] secretBackup = secretClient.backupSecret("secretName"); + System.out.printf("Secret's Backup Byte array's length %s", secretBackup.length); + // END: com.azure.security.keyvault.SecretClient.backupSecret#string + } + + /** + * Method to insert code snippets for {@link SecretClient#backupSecretWithResponse(String, Context)}. + */ + public void backupSecretWithResponseCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.backupSecretWithResponse#string-Context + byte[] secretBackup = secretClient.backupSecretWithResponse("secretName", + new Context(key1, value1)).getValue(); + System.out.printf("Secret's Backup Byte array's length %s", secretBackup.length); + // END: com.azure.security.keyvault.SecretClient.backupSecretWithResponse#string-Context + } + + /** + * Method to insert code snippets for {@link SecretClient#restoreSecretBackup(byte[])}. + */ + public void restoreSecretCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.restoreSecret#byte + // Pass the secret backup byte array of the secret to be restored. + byte[] secretBackupByteArray = {}; + KeyVaultSecret restoredSecret = secretClient.restoreSecretBackup(secretBackupByteArray); + System.out + .printf("Restored Secret with name %s and value %s", restoredSecret.getName(), restoredSecret.getValue()); + // END: com.azure.security.keyvault.SecretClient.restoreSecret#byte + } + + /** + * Method to insert code snippets for {@link SecretClient#restoreSecretBackupWithResponse(byte[], Context)}. + */ + public void restoreSecretWithResponseCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.restoreSecretWithResponse#byte-Context + // Pass the secret backup byte array of the secret to be restored. + byte[] secretBackupByteArray = {}; + KeyVaultSecret restoredSecret = secretClient.restoreSecretBackupWithResponse(secretBackupByteArray, + new Context(key2, value2)).getValue(); + System.out + .printf("Restored Secret with name %s and value %s", restoredSecret.getName(), restoredSecret.getValue()); + // END: com.azure.security.keyvault.SecretClient.restoreSecretWithResponse#byte-Context + } + + /** + * Method to insert code snippets for {@link SecretClient#listPropertiesOfSecrets()}. + */ + public void listSecretsCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.listSecrets + for (SecretProperties secret : secretClient.listPropertiesOfSecrets()) { + KeyVaultSecret secretWithValue = secretClient.getSecret(secret.getName(), secret.getVersion()); + System.out.printf("Received secret with name %s and value %s", + secretWithValue.getName(), secretWithValue.getValue()); + } + // END: com.azure.security.keyvault.SecretClient.listSecrets + + // BEGIN: com.azure.security.keyvault.SecretClient.listSecrets#Context + for (SecretProperties secret : secretClient.listPropertiesOfSecrets(new Context(key1, value2))) { + KeyVaultSecret secretWithValue = secretClient.getSecret(secret.getName(), secret.getVersion()); + System.out.printf("Received secret with name %s and value %s", + secretWithValue.getName(), secretWithValue.getValue()); + } + // END: com.azure.security.keyvault.SecretClient.listSecrets#Context + + // BEGIN: com.azure.security.keyvault.SecretClient.listSecrets.iterableByPage + secretClient.listPropertiesOfSecrets().iterableByPage().forEach(resp -> { + System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(), + resp.getRequest().getUrl(), resp.getStatusCode()); + resp.getItems().forEach(value -> { + KeyVaultSecret secretWithValue = secretClient.getSecret(value.getName(), value.getVersion()); + System.out.printf("Received secret with name %s and value %s", + secretWithValue.getName(), secretWithValue.getValue()); + }); + }); + // END: com.azure.security.keyvault.SecretClient.listSecrets.iterableByPage + } + + /** + * Method to insert code snippets for {@link SecretClient#listDeletedSecrets()} + */ + public void listDeletedSecretsCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.listDeletedSecrets + for (DeletedSecret deletedSecret : secretClient.listDeletedSecrets()) { + System.out.printf("Deleted secret's recovery Id %s", deletedSecret.getRecoveryId()); + } + // END: com.azure.security.keyvault.SecretClient.listDeletedSecrets + + // BEGIN: com.azure.security.keyvault.SecretClient.listDeletedSecrets#Context + for (DeletedSecret deletedSecret : secretClient.listDeletedSecrets(new Context(key1, value2))) { + System.out.printf("Deleted secret's recovery Id %s", deletedSecret.getRecoveryId()); + } + // END: com.azure.security.keyvault.SecretClient.listDeletedSecrets#Context + + // BEGIN: com.azure.security.keyvault.SecretClient.listDeletedSecrets.iterableByPage + secretClient.listDeletedSecrets().iterableByPage().forEach(resp -> { + System.out.printf("Got response headers . Url: %s, Status code: %d %n", + resp.getRequest().getUrl(), resp.getStatusCode()); + resp.getItems().forEach(value -> { + System.out.printf("Deleted secret's recovery Id %s", value.getRecoveryId()); + }); + }); + // END: com.azure.security.keyvault.SecretClient.listDeletedSecrets.iterableByPage + } + + /** + * Method to insert code snippets for {@link SecretClient#listPropertiesOfSecretVersions(String)}. + */ + public void listSecretVersionsCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.listSecretVersions#string + for (SecretProperties secret : secretClient.listPropertiesOfSecretVersions("secretName")) { + KeyVaultSecret secretWithValue = secretClient.getSecret(secret.getName(), secret.getVersion()); + System.out.printf("Received secret's version with name %s and value %s", + secretWithValue.getName(), secretWithValue.getValue()); + } + // END: com.azure.security.keyvault.SecretClient.listSecretVersions#string + + // BEGIN: com.azure.security.keyvault.SecretClient.listSecretVersions#string-Context + for (SecretProperties secret : secretClient + .listPropertiesOfSecretVersions("secretName", new Context(key1, value2))) { + KeyVaultSecret secretWithValue = secretClient.getSecret(secret.getName(), secret.getVersion()); + System.out.printf("Received secret's version with name %s and value %s", + secretWithValue.getName(), secretWithValue.getValue()); + } + // END: com.azure.security.keyvault.SecretClient.listSecretVersions#string-Context + + // BEGIN: com.azure.security.keyvault.SecretClient.listSecretVersions#string-Context-iterableByPage + secretClient.listPropertiesOfSecretVersions("secretName", new Context(key1, value2)) + .iterableByPage().forEach(resp -> { + System.out.printf("Got response headers . Url: %s, Status code: %d %n", + resp.getRequest().getUrl(), resp.getStatusCode()); + resp.getItems().forEach(value -> { + KeyVaultSecret secretWithValue = secretClient.getSecret(value.getName(), value.getVersion()); + System.out.printf("Received secret's version with name %s and value %s", + secretWithValue.getName(), secretWithValue.getValue()); + }); + }); + // END: com.azure.security.keyvault.SecretClient.listSecretVersions#string-Context-iterableByPage + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample12/v2/SecretClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample12/v2/SecretClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..7a0625a9b159 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample12/v2/SecretClientJavaDocCodeSnippets.java @@ -0,0 +1,383 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.secrets; + +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.secrets.models.DeletedSecret; +import com.azure.security.keyvault.secrets.models.KeyVaultSecret; +import com.azure.security.keyvault.secrets.models.SecretProperties; + +import java.time.OffsetDateTime; + +/** + * This class contains code samples for generating javadocs through doclets for {@link SecretClient}. + */ +public final class SecretClientJavaDocCodeSnippets { + private final String key1 = "key1"; + private final String key2 = "key2"; + private final String value1 = "val1"; + private final String value2 = "val2"; + + /** + * Generates code sample for creating a {@link SecretClient}. + * + * @return An instance of {@link SecretClient}. + */ + private SecretClient getSecretClient() { + // BEGIN: com.azure.security.keyvault.SecretClient.instantiation + SecretClient secretClient = new SecretClientBuilder() + .credential(new DefaultAzureCredentialBuilder().build()) + .vaultUrl("") + .buildClient(); + // END: com.azure.security.keyvault.SecretClient.instantiation + return secretClient; + } + + /** + * Method to insert code snippets for {@link SecretClient#getSecret(String, String)}. + */ + public void getSecretCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.getSecret#secretProperties + for (SecretProperties secret : secretClient.listPropertiesOfSecrets()) { + KeyVaultSecret secretWithValue = secretClient.getSecret(secret.getName(), secret.getVersion()); + System.out.printf("Secret is returned with name %s and value %s%n", secretWithValue.getName(), + secretWithValue.getValue()); + } + // END: com.azure.security.keyvault.SecretClient.getSecret#secretProperties + + // BEGIN: com.azure.security.keyvault.SecretClient.getSecret#string-string + String secretVersion = "6A385B124DEF4096AF1361A85B16C204"; + KeyVaultSecret secretWithVersion = secretClient.getSecret("secretName", secretVersion); + System.out.printf("Secret is returned with name %s and value %s%n", + secretWithVersion.getName(), secretWithVersion.getValue()); + // END: com.azure.security.keyvault.SecretClient.getSecret#string-string + + // BEGIN: com.azure.security.keyvault.SecretClient.getSecret#string + KeyVaultSecret secret = secretClient.getSecret("secretName"); + System.out.printf("Secret is returned with name %s and value %s%n", + secret.getName(), secret.getValue()); + // END: com.azure.security.keyvault.SecretClient.getSecret#string + } + + /** + * Method to insert code snippets for {@link SecretClient#getSecretWithResponse(String, String, Context)}. + */ + public void getSecretWithResponseCodeSnippets() { + SecretClient secretClient = getSecretClient(); + + // BEGIN: com.azure.security.keyvault.SecretClient.getSecretWithResponse#string-string-Context + String secretVersion = "6A385B124DEF4096AF1361A85B16C204"; + KeyVaultSecret secretWithVersion = secretClient.getSecretWithResponse("secretName", secretVersion, + new Context(key2, value2)).getValue(); + System.out.printf("Secret is returned with name %s and value %s%n", + secretWithVersion.getName(), secretWithVersion.getValue()); + // END: com.azure.security.keyvault.SecretClient.getSecretWithResponse#string-string-Context + } + + /** + * Method to insert code snippets for {@link SecretClient#setSecret(KeyVaultSecret)}. + */ + public void setSecretCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.setSecret#secret + KeyVaultSecret newSecret = new KeyVaultSecret("secretName", "secretValue") + .setProperties(new SecretProperties().setExpiresOn(OffsetDateTime.now().plusDays(60))); + KeyVaultSecret returnedSecret = secretClient.setSecret(newSecret); + System.out.printf("Secret is created with name %s and value %s%n", returnedSecret.getName(), + returnedSecret.getValue()); + // END: com.azure.security.keyvault.SecretClient.setSecret#secret + + // BEGIN: com.azure.security.keyvault.SecretClient.setSecret#string-string + KeyVaultSecret secret = secretClient.setSecret("secretName", "secretValue"); + System.out.printf("Secret is created with name %s and value %s%n", secret.getName(), secret.getValue()); + // END: com.azure.security.keyvault.SecretClient.setSecret#string-string + } + + /** + * Method to insert code snippets for {@link SecretClient#setSecretWithResponse(KeyVaultSecret, Context)}. + */ + public void setSecretWithResponseCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.setSecretWithResponse#secret-Context + KeyVaultSecret newSecret = new KeyVaultSecret("secretName", "secretValue") + .setProperties(new SecretProperties().setExpiresOn(OffsetDateTime.now().plusDays(60))); + KeyVaultSecret secret = secretClient.setSecretWithResponse(newSecret, new Context(key1, value1)).getValue(); + System.out.printf("Secret is created with name %s and value %s%n", secret.getName(), secret.getValue()); + // END: com.azure.security.keyvault.SecretClient.setSecretWithResponse#secret-Context + } + + /** + * Method to insert code snippets for {@link SecretClient#updateSecretProperties(SecretProperties)}. + */ + public void updateSecretCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.updateSecretProperties#secretProperties + SecretProperties secretProperties = secretClient.getSecret("secretName").getProperties(); + secretProperties.setExpiresOn(OffsetDateTime.now().plusDays(60)); + SecretProperties updatedSecretProperties = secretClient.updateSecretProperties(secretProperties); + KeyVaultSecret updatedSecret = secretClient.getSecret(updatedSecretProperties.getName()); + System.out.printf("Updated Secret is returned with name %s, value %s and expires %s%n", + updatedSecret.getName(), updatedSecret.getValue(), updatedSecret.getProperties().getExpiresOn()); + // END: com.azure.security.keyvault.SecretClient.updateSecretProperties#secretProperties + } + + /** + * Method to insert code snippets for + * {@link SecretClient#updateSecretPropertiesWithResponse(SecretProperties, Context)}. + */ + public void updateSecretWithResponseCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.updateSecretPropertiesWithResponse#secretProperties-Context + SecretProperties secretProperties = secretClient.getSecret("secretName").getProperties(); + secretProperties.setExpiresOn(OffsetDateTime.now().plusDays(60)); + SecretProperties updatedSecretBase = secretClient.updateSecretPropertiesWithResponse(secretProperties, + new Context(key2, value2)).getValue(); + KeyVaultSecret updatedSecret = secretClient.getSecret(updatedSecretBase.getName()); + System.out.printf("Updated Secret is returned with name %s, value %s and expires %s%n", + updatedSecret.getName(), updatedSecret.getValue(), updatedSecret.getProperties().getExpiresOn()); + // END: com.azure.security.keyvault.SecretClient.updateSecretPropertiesWithResponse#secretProperties-Context + } + + /** + * Method to insert code snippets for {@link SecretClient#beginDeleteSecret(String)}. + */ + public void deleteSecretCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.deleteSecret#String + SyncPoller deleteSecretPoller = secretClient.beginDeleteSecret("secretName"); + + // Deleted Secret is accessible as soon as polling begins. + PollResponse deleteSecretPollResponse = deleteSecretPoller.poll(); + + // Deletion date only works for a SoftDelete-enabled Key Vault. + System.out.println("Deleted Date %s" + deleteSecretPollResponse.getValue() + .getDeletedOn().toString()); + System.out.printf("Deleted Secret's Recovery Id %s", deleteSecretPollResponse.getValue() + .getRecoveryId()); + + // Secret is being deleted on server. + deleteSecretPoller.waitForCompletion(); + // END: com.azure.security.keyvault.SecretClient.deleteSecret#String + } + + /** + * Method to insert code snippets for {@link SecretClient#beginDeleteSecret(String)}. + */ + public void getDeletedSecretCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.getDeletedSecret#string + DeletedSecret deletedSecret = secretClient.getDeletedSecret("secretName"); + System.out.printf("Deleted Secret's Recovery Id %s", deletedSecret.getRecoveryId()); + // END: com.azure.security.keyvault.SecretClient.getDeletedSecret#string + } + + /** + * Method to insert code snippets for {@link SecretClient#getDeletedSecretWithResponse(String, Context)}. + */ + public void getDeletedSecretWithResponseCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.getDeletedSecretWithResponse#string-Context + DeletedSecret deletedSecret = secretClient.getDeletedSecretWithResponse("secretName", + new Context(key2, value2)).getValue(); + System.out.printf("Deleted Secret's Recovery Id %s", deletedSecret.getRecoveryId()); + // END: com.azure.security.keyvault.SecretClient.getDeletedSecretWithResponse#string-Context + } + + /** + * Method to insert code snippets for {@link SecretClient#purgeDeletedSecret(String)}. + */ + public void purgeDeletedSecretCodeSnippets() { + SecretClient secretClient = getSecretClient(); + + // BEGIN: com.azure.security.keyvault.SecretClient.purgeDeletedSecret#string + secretClient.purgeDeletedSecret("secretName"); + // END: com.azure.security.keyvault.SecretClient.purgeDeletedSecret#string + } + + /** + * Method to insert code snippets for {@link SecretClient#purgeDeletedSecretWithResponse(String, Context)}. + */ + public void purgeDeletedSecretWithResponseCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.purgeDeletedSecretWithResponse#string-Context + Response purgeResponse = secretClient.purgeDeletedSecretWithResponse("secretName", + new Context(key1, value1)); + System.out.printf("Purge Status Code: %d", purgeResponse.getStatusCode()); + // END: com.azure.security.keyvault.SecretClient.purgeDeletedSecretWithResponse#string-Context + } + + /** + * Method to insert code snippets for {@link SecretClient#beginRecoverDeletedSecret(String)}. + */ + public void recoverDeletedSecretCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.recoverDeletedSecret#String + SyncPoller recoverSecretPoller = + secretClient.beginRecoverDeletedSecret("deletedSecretName"); + + // Deleted Secret can be accessed as soon as polling is in progress. + PollResponse recoveredSecretPollResponse = recoverSecretPoller.poll(); + System.out.println("Recovered Key Name %s" + recoveredSecretPollResponse.getValue().getName()); + System.out.printf("Recovered Key's Id %s", recoveredSecretPollResponse.getValue().getId()); + + // Key is being recovered on server. + recoverSecretPoller.waitForCompletion(); + // END: com.azure.security.keyvault.SecretClient.recoverDeletedSecret#String + } + + /** + * Method to insert code snippets for {@link SecretClient#backupSecret(String)}. + */ + public void backupSecretCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.backupSecret#string + byte[] secretBackup = secretClient.backupSecret("secretName"); + System.out.printf("Secret's Backup Byte array's length %s", secretBackup.length); + // END: com.azure.security.keyvault.SecretClient.backupSecret#string + } + + /** + * Method to insert code snippets for {@link SecretClient#backupSecretWithResponse(String, Context)}. + */ + public void backupSecretWithResponseCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.backupSecretWithResponse#string-Context + byte[] secretBackup = secretClient.backupSecretWithResponse("secretName", + new Context(key1, value1)).getValue(); + System.out.printf("Secret's Backup Byte array's length %s", secretBackup.length); + // END: com.azure.security.keyvault.SecretClient.backupSecretWithResponse#string-Context + } + + /** + * Method to insert code snippets for {@link SecretClient#restoreSecretBackup(byte[])}. + */ + public void restoreSecretCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.restoreSecret#byte + // Pass the secret backup byte array of the secret to be restored. + byte[] secretBackupByteArray = {}; + KeyVaultSecret restoredSecret = secretClient.restoreSecretBackup(secretBackupByteArray); + System.out + .printf("Restored Secret with name %s and value %s", restoredSecret.getName(), restoredSecret.getValue()); + // END: com.azure.security.keyvault.SecretClient.restoreSecret#byte + } + + /** + * Method to insert code snippets for {@link SecretClient#restoreSecretBackupWithResponse(byte[], Context)}. + */ + public void restoreSecretWithResponseCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.restoreSecretWithResponse#byte-Context + // Pass the secret backup byte array of the secret to be restored. + byte[] secretBackupByteArray = {}; + KeyVaultSecret restoredSecret = secretClient.restoreSecretBackupWithResponse(secretBackupByteArray, + new Context(key2, value2)).getValue(); + System.out + .printf("Restored Secret with name %s and value %s", restoredSecret.getName(), restoredSecret.getValue()); + // END: com.azure.security.keyvault.SecretClient.restoreSecretWithResponse#byte-Context + } + + /** + * Method to insert code snippets for {@link SecretClient#listPropertiesOfSecrets()}. + */ + public void listSecretsCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.listSecrets + for (SecretProperties secret : secretClient.listPropertiesOfSecrets()) { + KeyVaultSecret secretWithValue = secretClient.getSecret(secret.getName(), secret.getVersion()); + System.out.printf("Received secret with name %s and value %s", + secretWithValue.getName(), secretWithValue.getValue()); + } + // END: com.azure.security.keyvault.SecretClient.listSecrets + + // BEGIN: com.azure.security.keyvault.SecretClient.listSecrets#Context + for (SecretProperties secret : secretClient.listPropertiesOfSecrets(new Context(key1, value2))) { + KeyVaultSecret secretWithValue = secretClient.getSecret(secret.getName(), secret.getVersion()); + System.out.printf("Received secret with name %s and value %s", + secretWithValue.getName(), secretWithValue.getValue()); + } + // END: com.azure.security.keyvault.SecretClient.listSecrets#Context + + // BEGIN: com.azure.security.keyvault.SecretClient.listSecrets.iterableByPage + secretClient.listPropertiesOfSecrets().iterableByPage().forEach(resp -> { + System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(), + resp.getRequest().getUrl(), resp.getStatusCode()); + resp.getItems().forEach(value -> { + KeyVaultSecret secretWithValue = secretClient.getSecret(value.getName(), value.getVersion()); + System.out.printf("Received secret with name %s and value %s", + secretWithValue.getName(), secretWithValue.getValue()); + }); + }); + // END: com.azure.security.keyvault.SecretClient.listSecrets.iterableByPage + } + + /** + * Method to insert code snippets for {@link SecretClient#listDeletedSecrets()} + */ + public void listDeletedSecretsCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.listDeletedSecrets + for (DeletedSecret deletedSecret : secretClient.listDeletedSecrets()) { + System.out.printf("Deleted secret's recovery Id %s", deletedSecret.getRecoveryId()); + } + // END: com.azure.security.keyvault.SecretClient.listDeletedSecrets + + // BEGIN: com.azure.security.keyvault.SecretClient.listDeletedSecrets#Context + for (DeletedSecret deletedSecret : secretClient.listDeletedSecrets(new Context(key1, value2))) { + System.out.printf("Deleted secret's recovery Id %s", deletedSecret.getRecoveryId()); + } + // END: com.azure.security.keyvault.SecretClient.listDeletedSecrets#Context + + // BEGIN: com.azure.security.keyvault.SecretClient.listDeletedSecrets.iterableByPage + secretClient.listDeletedSecrets().iterableByPage().forEach(resp -> { + System.out.printf("Got response headers . Url: %s, Status code: %d %n", + resp.getRequest().getUrl(), resp.getStatusCode()); + resp.getItems().forEach(value -> { + System.out.printf("Deleted secret's recovery Id %s", value.getRecoveryId()); + }); + }); + // END: com.azure.security.keyvault.SecretClient.listDeletedSecrets.iterableByPage + } + + /** + * Method to insert code snippets for {@link SecretClient#listPropertiesOfSecretVersions(String)}. + */ + public void listSecretVersionsCodeSnippets() { + SecretClient secretClient = getSecretClient(); + // BEGIN: com.azure.security.keyvault.SecretClient.listSecretVersions#string + for (SecretProperties secret : secretClient.listPropertiesOfSecretVersions("secretName")) { + KeyVaultSecret secretWithValue = secretClient.getSecret(secret.getName(), secret.getVersion()); + System.out.printf("Received secret's version with name %s and value %s", + secretWithValue.getName(), secretWithValue.getValue()); + } + // END: com.azure.security.keyvault.SecretClient.listSecretVersions#string + + // BEGIN: com.azure.security.keyvault.SecretClient.listSecretVersions#string-Context + for (SecretProperties secret : secretClient + .listPropertiesOfSecretVersions("secretName", new Context(key1, value2))) { + KeyVaultSecret secretWithValue = secretClient.getSecret(secret.getName(), secret.getVersion()); + System.out.printf("Received secret's version with name %s and value %s", + secretWithValue.getName(), secretWithValue.getValue()); + } + // END: com.azure.security.keyvault.SecretClient.listSecretVersions#string-Context + + // BEGIN: com.azure.security.keyvault.SecretClient.listSecretVersions#string-Context-iterableByPage + secretClient.listPropertiesOfSecretVersions("secretName", new Context(key1, value2)) + .iterableByPage().forEach(resp -> { + System.out.printf("Got response headers . Url: %s, Status code: %d %n", + resp.getRequest().getUrl(), resp.getStatusCode()); + resp.getItems().forEach(value -> { + KeyVaultSecret secretWithValue = secretClient.getSecret(value.getName(), value.getVersion()); + System.out.printf("Received secret's version with name %s and value %s", + secretWithValue.getName(), secretWithValue.getValue()); + }); + }); + // END: com.azure.security.keyvault.SecretClient.listSecretVersions#string-Context-iterableByPage + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample2/v1/BackupAndRestoreOperationsAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample2/v1/BackupAndRestoreOperationsAsync.java new file mode 100644 index 000000000000..8d2f52cc53d6 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample2/v1/BackupAndRestoreOperationsAsync.java @@ -0,0 +1,114 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.secrets; + +import com.azure.security.keyvault.secrets.models.KeyVaultSecret; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.secrets.models.SecretProperties; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to asynchronously backup and restore secrets in the key vault. + */ +public class BackupAndRestoreOperationsAsync { + /** + * Authenticates with the key vault and shows how to asynchronously backup and restore secrets in the key vault. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + * @throws IOException when writing backup to file is unsuccessful. + */ + public static void main(String[] args) throws IOException, InterruptedException, IllegalArgumentException { + /* Instantiate a SecretAsyncClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md) + for links and instructions. */ + SecretAsyncClient secretAsyncClient = new SecretClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + // Let's create secrets holding storage account credentials valid for 1 year. If the secret already exists in + // the key vault, then a new version of the secret is created. + secretAsyncClient.setSecret(new KeyVaultSecret("StorageAccountPassword", "f4G34fMh8v-fdsgjsk2323=-asdsdfsdf") + .setProperties(new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)))) + .subscribe(secretResponse -> + System.out.printf("Secret is created with name %s and value %s %n", secretResponse.getName(), + secretResponse.getValue())); + + Thread.sleep(2000); + + // Backups are good to have, if in case secrets get accidentally deleted by you. + // For long term storage, it is ideal to write the backup to a file. + String backupFilePath = "YOUR_BACKUP_FILE_PATH"; + + secretAsyncClient.backupSecret("StorageAccountPassword").subscribe(backupResponse -> { + byte[] backupBytes = backupResponse; + + writeBackupToFile(backupBytes, backupFilePath); + }); + + Thread.sleep(7000); + + // The storage account secret is no longer in use, so you delete it. + secretAsyncClient.beginDeleteSecret("StorageAccountPassword") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Deleted Secret Name: " + pollResponse.getValue().getName()); + System.out.println("Deleted Secret Value: " + pollResponse.getValue().getValue()); + }); + + //To ensure the file is deleted server-side. + Thread.sleep(30000); + + // If the vault is soft-delete enabled, then you need to purge the secret as well for permanent deletion. + secretAsyncClient.purgeDeletedSecretWithResponse("StorageAccountPassword") + .subscribe(purgeResponse -> + System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode())); + + // To ensure the secret is purged server-side. + Thread.sleep(15000); + + // After sometime, the secret is required again. We can use the backup value to restore it in the key vault. + byte[] backupFromFile = Files.readAllBytes(new File(backupFilePath).toPath()); + secretAsyncClient.restoreSecretBackup(backupFromFile).subscribe(secretResponse -> + System.out.printf("Restored Secret with name %s %n", secretResponse.getName())); + + // To ensure the secret is restored server-side. + Thread.sleep(15000); + } + + private static void writeBackupToFile(byte[] bytes, String filePath) { + try { + File file = new File(filePath); + + if (file.exists()) { + file.delete(); + } + + file.createNewFile(); + + OutputStream os = new FileOutputStream(file); + os.write(bytes); + + System.out.println("Successfully wrote backup to file."); + + // Close the file + os.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample2/v2/BackupAndRestoreOperationsAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample2/v2/BackupAndRestoreOperationsAsync.java new file mode 100644 index 000000000000..8d2f52cc53d6 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample2/v2/BackupAndRestoreOperationsAsync.java @@ -0,0 +1,114 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.secrets; + +import com.azure.security.keyvault.secrets.models.KeyVaultSecret; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.secrets.models.SecretProperties; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to asynchronously backup and restore secrets in the key vault. + */ +public class BackupAndRestoreOperationsAsync { + /** + * Authenticates with the key vault and shows how to asynchronously backup and restore secrets in the key vault. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + * @throws IOException when writing backup to file is unsuccessful. + */ + public static void main(String[] args) throws IOException, InterruptedException, IllegalArgumentException { + /* Instantiate a SecretAsyncClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md) + for links and instructions. */ + SecretAsyncClient secretAsyncClient = new SecretClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + // Let's create secrets holding storage account credentials valid for 1 year. If the secret already exists in + // the key vault, then a new version of the secret is created. + secretAsyncClient.setSecret(new KeyVaultSecret("StorageAccountPassword", "f4G34fMh8v-fdsgjsk2323=-asdsdfsdf") + .setProperties(new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)))) + .subscribe(secretResponse -> + System.out.printf("Secret is created with name %s and value %s %n", secretResponse.getName(), + secretResponse.getValue())); + + Thread.sleep(2000); + + // Backups are good to have, if in case secrets get accidentally deleted by you. + // For long term storage, it is ideal to write the backup to a file. + String backupFilePath = "YOUR_BACKUP_FILE_PATH"; + + secretAsyncClient.backupSecret("StorageAccountPassword").subscribe(backupResponse -> { + byte[] backupBytes = backupResponse; + + writeBackupToFile(backupBytes, backupFilePath); + }); + + Thread.sleep(7000); + + // The storage account secret is no longer in use, so you delete it. + secretAsyncClient.beginDeleteSecret("StorageAccountPassword") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Deleted Secret Name: " + pollResponse.getValue().getName()); + System.out.println("Deleted Secret Value: " + pollResponse.getValue().getValue()); + }); + + //To ensure the file is deleted server-side. + Thread.sleep(30000); + + // If the vault is soft-delete enabled, then you need to purge the secret as well for permanent deletion. + secretAsyncClient.purgeDeletedSecretWithResponse("StorageAccountPassword") + .subscribe(purgeResponse -> + System.out.printf("Purge Status response %d %n", purgeResponse.getStatusCode())); + + // To ensure the secret is purged server-side. + Thread.sleep(15000); + + // After sometime, the secret is required again. We can use the backup value to restore it in the key vault. + byte[] backupFromFile = Files.readAllBytes(new File(backupFilePath).toPath()); + secretAsyncClient.restoreSecretBackup(backupFromFile).subscribe(secretResponse -> + System.out.printf("Restored Secret with name %s %n", secretResponse.getName())); + + // To ensure the secret is restored server-side. + Thread.sleep(15000); + } + + private static void writeBackupToFile(byte[] bytes, String filePath) { + try { + File file = new File(filePath); + + if (file.exists()) { + file.delete(); + } + + file.createNewFile(); + + OutputStream os = new FileOutputStream(file); + os.write(bytes); + + System.out.println("Successfully wrote backup to file."); + + // Close the file + os.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample3/v1/HelloWorld.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample3/v1/HelloWorld.java new file mode 100644 index 000000000000..78c772ab5859 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample3/v1/HelloWorld.java @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.secrets; + +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.security.keyvault.secrets.models.DeletedSecret; +import com.azure.security.keyvault.secrets.models.KeyVaultSecret; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.secrets.models.SecretProperties; + +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to set, get, update and delete a secret. + */ +public class HelloWorld { + /** + * Authenticates with the key vault and shows how to set, get, update and delete a secret in the key vault. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws InterruptedException, IllegalArgumentException { + /* Instantiate a SecretClient that will be used to call the service. Notice that the client is using default + Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md) + for links and instructions. */ + SecretClient secretClient = new SecretClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + // Let's create a secret holding bank account credentials valid for 1 year. If the secret already exists in the + // key vault, then a new version of the secret is created. + secretClient.setSecret(new KeyVaultSecret("BankAccountPassword", "f4G34fMh8v") + .setProperties(new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)))); + + // Let's get the bank secret from the key vault. + KeyVaultSecret bankSecret = secretClient.getSecret("BankAccountPassword"); + + System.out.printf("Secret is returned with name %s and value %s \n", bankSecret.getName(), bankSecret.getValue()); + + // After one year, the bank account is still active, we need to update the expiry time of the secret. + // The update method can be used to update the expiry attribute of the secret. It cannot be used to update the + // value of the secret. + bankSecret.getProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + SecretProperties updatedSecret = secretClient.updateSecretProperties(bankSecret.getProperties()); + + System.out.printf("Secret's updated expiry time %s \n", updatedSecret.getExpiresOn()); + + // Bank forced a password update for security purposes. Let's change the value of the secret in the key vault. + // To achieve this, we need to create a new version of the secret in the key vault. The update operation cannot + // change the value of the secret. + secretClient.setSecret(new KeyVaultSecret("BankAccountPassword", "bhjd4DDgsa") + .setProperties(new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)))); + + // The bank account was closed, need to delete its credentials from the key vault. + SyncPoller deletedBankSecretPoller = + secretClient.beginDeleteSecret("BankAccountPassword"); + PollResponse deletedBankSecretPollResponse = deletedBankSecretPoller.poll(); + + System.out.println("Deleted Date %s" + deletedBankSecretPollResponse.getValue().getDeletedOn().toString()); + System.out.printf("Deleted Secret's Recovery Id %s", deletedBankSecretPollResponse.getValue().getRecoveryId()); + + // Secret is being deleted on the server. + deletedBankSecretPoller.waitForCompletion(); + + // If the key vault is soft-delete enabled, then deleted secrets need to be purged for permanent deletion. + secretClient.purgeDeletedSecret("BankAccountPassword"); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample3/v2/HelloWorld.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample3/v2/HelloWorld.java new file mode 100644 index 000000000000..78c772ab5859 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample3/v2/HelloWorld.java @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.secrets; + +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.security.keyvault.secrets.models.DeletedSecret; +import com.azure.security.keyvault.secrets.models.KeyVaultSecret; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.secrets.models.SecretProperties; + +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to set, get, update and delete a secret. + */ +public class HelloWorld { + /** + * Authenticates with the key vault and shows how to set, get, update and delete a secret in the key vault. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws InterruptedException, IllegalArgumentException { + /* Instantiate a SecretClient that will be used to call the service. Notice that the client is using default + Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md) + for links and instructions. */ + SecretClient secretClient = new SecretClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + // Let's create a secret holding bank account credentials valid for 1 year. If the secret already exists in the + // key vault, then a new version of the secret is created. + secretClient.setSecret(new KeyVaultSecret("BankAccountPassword", "f4G34fMh8v") + .setProperties(new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)))); + + // Let's get the bank secret from the key vault. + KeyVaultSecret bankSecret = secretClient.getSecret("BankAccountPassword"); + + System.out.printf("Secret is returned with name %s and value %s \n", bankSecret.getName(), bankSecret.getValue()); + + // After one year, the bank account is still active, we need to update the expiry time of the secret. + // The update method can be used to update the expiry attribute of the secret. It cannot be used to update the + // value of the secret. + bankSecret.getProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + SecretProperties updatedSecret = secretClient.updateSecretProperties(bankSecret.getProperties()); + + System.out.printf("Secret's updated expiry time %s \n", updatedSecret.getExpiresOn()); + + // Bank forced a password update for security purposes. Let's change the value of the secret in the key vault. + // To achieve this, we need to create a new version of the secret in the key vault. The update operation cannot + // change the value of the secret. + secretClient.setSecret(new KeyVaultSecret("BankAccountPassword", "bhjd4DDgsa") + .setProperties(new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)))); + + // The bank account was closed, need to delete its credentials from the key vault. + SyncPoller deletedBankSecretPoller = + secretClient.beginDeleteSecret("BankAccountPassword"); + PollResponse deletedBankSecretPollResponse = deletedBankSecretPoller.poll(); + + System.out.println("Deleted Date %s" + deletedBankSecretPollResponse.getValue().getDeletedOn().toString()); + System.out.printf("Deleted Secret's Recovery Id %s", deletedBankSecretPollResponse.getValue().getRecoveryId()); + + // Secret is being deleted on the server. + deletedBankSecretPoller.waitForCompletion(); + + // If the key vault is soft-delete enabled, then deleted secrets need to be purged for permanent deletion. + secretClient.purgeDeletedSecret("BankAccountPassword"); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample4/v1/HelloWorldAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample4/v1/HelloWorldAsync.java new file mode 100644 index 000000000000..91a114dd8201 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample4/v1/HelloWorldAsync.java @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.secrets; + +import com.azure.security.keyvault.secrets.models.KeyVaultSecret; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.secrets.models.SecretProperties; + +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to asynchronously set, get, update and delete a secret. + */ +public class HelloWorldAsync { + /** + * Authenticates with the key vault and shows how to asynchronously set, get, update and delete a secret in the key vault. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws InterruptedException { + /* Instantiate a SecretAsyncClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md) + for links and instructions. */ + SecretAsyncClient secretAsyncClient = new SecretClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + // Let's create a secret holding bank account credentials valid for 1 year. If the secret already exists in the + // key vault, then a new version of the secret is created. + secretAsyncClient.setSecret(new KeyVaultSecret("BankAccountPassword", "fakePasswordPlaceholder") + .setProperties(new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)))) + .subscribe(secretResponse -> + System.out.printf("Secret is created with name %s and value %s %n", secretResponse.getName(), secretResponse.getValue())); + + Thread.sleep(2000); + + // Let's get the bank secret from the key vault. + secretAsyncClient.getSecret("BankAccountPassword").subscribe(secretResponse -> + System.out.printf("Secret returned with name %s , value %s %n", secretResponse.getName(), secretResponse.getValue())); + + Thread.sleep(2000); + + // After one year, the bank account is still active, we need to update the expiry time of the secret. + // The update method can be used to update the expiry attribute of the secret. It cannot be used to update the + // value of the secret. + secretAsyncClient.getSecret("BankAccountPassword") + .subscribe(secretResponse -> { + KeyVaultSecret secret = secretResponse; + + //Update the expiry time of the secret. + secret.getProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + secretAsyncClient.updateSecretProperties(secret.getProperties()) + .subscribe(updatedSecretResponse -> + System.out.printf("Secret's updated expiry time %s %n", + updatedSecretResponse.getExpiresOn().toString())); + }); + + Thread.sleep(2000); + + // Bank forced a password update for security purposes. Let's change the value of the secret in the key vault. + // To achieve this, we need to create a new version of the secret in the key vault. The update operation cannot + // change the value of the secret. + secretAsyncClient.setSecret("BankAccountPassword", "fakePasswordPlaceholder") + .subscribe(secretResponse -> + System.out.printf("Secret is created with name %s and value %s %n", secretResponse.getName(), + secretResponse.getValue())); + + Thread.sleep(2000); + + // The bank account was closed, need to delete its credentials from the key vault. + secretAsyncClient.beginDeleteSecret("BankAccountPassword") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Deleted Secret Name: " + pollResponse.getValue().getName()); + System.out.println("Deleted Secret Value: " + pollResponse.getValue().getValue()); + }); + + // To ensure the secret is deleted server-side. + Thread.sleep(30000); + + // If the key vault is soft-delete enabled, then for permanent deletion deleted secrets need to be purged. + secretAsyncClient.purgeDeletedSecretWithResponse("BankAccountPassword") + .subscribe(purgeResponse -> + System.out.printf("Bank account secret purge status response %d %n", purgeResponse.getStatusCode())); + + // To ensure the secret is purged server-side. + Thread.sleep(15000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample4/v2/HelloWorldAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample4/v2/HelloWorldAsync.java new file mode 100644 index 000000000000..91a114dd8201 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample4/v2/HelloWorldAsync.java @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.secrets; + +import com.azure.security.keyvault.secrets.models.KeyVaultSecret; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.secrets.models.SecretProperties; + +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to asynchronously set, get, update and delete a secret. + */ +public class HelloWorldAsync { + /** + * Authenticates with the key vault and shows how to asynchronously set, get, update and delete a secret in the key vault. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws InterruptedException { + /* Instantiate a SecretAsyncClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md) + for links and instructions. */ + SecretAsyncClient secretAsyncClient = new SecretClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + // Let's create a secret holding bank account credentials valid for 1 year. If the secret already exists in the + // key vault, then a new version of the secret is created. + secretAsyncClient.setSecret(new KeyVaultSecret("BankAccountPassword", "fakePasswordPlaceholder") + .setProperties(new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)))) + .subscribe(secretResponse -> + System.out.printf("Secret is created with name %s and value %s %n", secretResponse.getName(), secretResponse.getValue())); + + Thread.sleep(2000); + + // Let's get the bank secret from the key vault. + secretAsyncClient.getSecret("BankAccountPassword").subscribe(secretResponse -> + System.out.printf("Secret returned with name %s , value %s %n", secretResponse.getName(), secretResponse.getValue())); + + Thread.sleep(2000); + + // After one year, the bank account is still active, we need to update the expiry time of the secret. + // The update method can be used to update the expiry attribute of the secret. It cannot be used to update the + // value of the secret. + secretAsyncClient.getSecret("BankAccountPassword") + .subscribe(secretResponse -> { + KeyVaultSecret secret = secretResponse; + + //Update the expiry time of the secret. + secret.getProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)); + secretAsyncClient.updateSecretProperties(secret.getProperties()) + .subscribe(updatedSecretResponse -> + System.out.printf("Secret's updated expiry time %s %n", + updatedSecretResponse.getExpiresOn().toString())); + }); + + Thread.sleep(2000); + + // Bank forced a password update for security purposes. Let's change the value of the secret in the key vault. + // To achieve this, we need to create a new version of the secret in the key vault. The update operation cannot + // change the value of the secret. + secretAsyncClient.setSecret("BankAccountPassword", "fakePasswordPlaceholder") + .subscribe(secretResponse -> + System.out.printf("Secret is created with name %s and value %s %n", secretResponse.getName(), + secretResponse.getValue())); + + Thread.sleep(2000); + + // The bank account was closed, need to delete its credentials from the key vault. + secretAsyncClient.beginDeleteSecret("BankAccountPassword") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Deleted Secret Name: " + pollResponse.getValue().getName()); + System.out.println("Deleted Secret Value: " + pollResponse.getValue().getValue()); + }); + + // To ensure the secret is deleted server-side. + Thread.sleep(30000); + + // If the key vault is soft-delete enabled, then for permanent deletion deleted secrets need to be purged. + secretAsyncClient.purgeDeletedSecretWithResponse("BankAccountPassword") + .subscribe(purgeResponse -> + System.out.printf("Bank account secret purge status response %d %n", purgeResponse.getStatusCode())); + + // To ensure the secret is purged server-side. + Thread.sleep(15000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample5/v1/ListOperations.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample5/v1/ListOperations.java new file mode 100644 index 000000000000..832dc68f830d --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample5/v1/ListOperations.java @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.secrets; + +import com.azure.security.keyvault.secrets.models.KeyVaultSecret; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.secrets.models.SecretProperties; + +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to list secrets and versions of a given secret in the key vault. + */ +public class ListOperations { + /** + * Authenticates with the key vault and shows how to list secrets and list versions of a specific secret in the key + * vault. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + */ + public static void main(String[] args) throws IllegalArgumentException { + /* Instantiate a SecretClient that will be used to call the service. Notice that the client is using default + Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md) + for links and instructions. */ + SecretClient client = new SecretClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + // Let's create secrets holding storage and bank accounts credentials valid for 1 year. If the secret + // already exists in the key vault, then a new version of the secret is created. + client.setSecret(new KeyVaultSecret("StorageAccountPassword", "fakePasswordPlaceholder") + .setProperties(new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)))); + + client.setSecret(new KeyVaultSecret("BankAccountPassword", "fakePasswordPlaceholder") + .setProperties(new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)))); + + // You need to check if any of the secrets are sharing same values. Let's list the secrets and print their values. + // List operations don't return the secrets with value information. So, for each returned secret we call getSecret to get the secret with its value information. + for (SecretProperties secret : client.listPropertiesOfSecrets()) { + if (!secret.isEnabled()) { + continue; + } + KeyVaultSecret secretWithValue = client.getSecret(secret.getName(), secret.getVersion()); + System.out.printf("Received secret with name %s and value %s \n", secretWithValue.getName(), secretWithValue.getValue()); + } + + // The bank account password got updated, so you want to update the secret in key vault to ensure it reflects the new password. + // Calling setSecret on an existing secret creates a new version of the secret in the key vault with the new value. + client.setSecret("BankAccountPassword", "fakePasswordPlaceholder"); + + // You need to check all the different values your bank account password secret had previously. Lets print all the versions of this secret. + for (SecretProperties secret : client.listPropertiesOfSecretVersions("BankAccountPassword")) { + KeyVaultSecret secretWithValue = client.getSecret(secret.getName(), secret.getVersion()); + + System.out.printf("Received secret's version with name %s and value %s", secretWithValue.getName(), + secretWithValue.getValue()); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample5/v2/ListOperations.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample5/v2/ListOperations.java new file mode 100644 index 000000000000..832dc68f830d --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample5/v2/ListOperations.java @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.secrets; + +import com.azure.security.keyvault.secrets.models.KeyVaultSecret; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.secrets.models.SecretProperties; + +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to list secrets and versions of a given secret in the key vault. + */ +public class ListOperations { + /** + * Authenticates with the key vault and shows how to list secrets and list versions of a specific secret in the key + * vault. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + */ + public static void main(String[] args) throws IllegalArgumentException { + /* Instantiate a SecretClient that will be used to call the service. Notice that the client is using default + Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md) + for links and instructions. */ + SecretClient client = new SecretClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + // Let's create secrets holding storage and bank accounts credentials valid for 1 year. If the secret + // already exists in the key vault, then a new version of the secret is created. + client.setSecret(new KeyVaultSecret("StorageAccountPassword", "fakePasswordPlaceholder") + .setProperties(new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)))); + + client.setSecret(new KeyVaultSecret("BankAccountPassword", "fakePasswordPlaceholder") + .setProperties(new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)))); + + // You need to check if any of the secrets are sharing same values. Let's list the secrets and print their values. + // List operations don't return the secrets with value information. So, for each returned secret we call getSecret to get the secret with its value information. + for (SecretProperties secret : client.listPropertiesOfSecrets()) { + if (!secret.isEnabled()) { + continue; + } + KeyVaultSecret secretWithValue = client.getSecret(secret.getName(), secret.getVersion()); + System.out.printf("Received secret with name %s and value %s \n", secretWithValue.getName(), secretWithValue.getValue()); + } + + // The bank account password got updated, so you want to update the secret in key vault to ensure it reflects the new password. + // Calling setSecret on an existing secret creates a new version of the secret in the key vault with the new value. + client.setSecret("BankAccountPassword", "fakePasswordPlaceholder"); + + // You need to check all the different values your bank account password secret had previously. Lets print all the versions of this secret. + for (SecretProperties secret : client.listPropertiesOfSecretVersions("BankAccountPassword")) { + KeyVaultSecret secretWithValue = client.getSecret(secret.getName(), secret.getVersion()); + + System.out.printf("Received secret's version with name %s and value %s", secretWithValue.getName(), + secretWithValue.getValue()); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample6/v1/ListOperationsAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample6/v1/ListOperationsAsync.java new file mode 100644 index 000000000000..258dbe78f0a6 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample6/v1/ListOperationsAsync.java @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.secrets; + +import com.azure.security.keyvault.secrets.models.KeyVaultSecret; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.secrets.models.SecretProperties; + +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to asynchronously list secrets and versions of a given secret in the key vault. + */ +public class ListOperationsAsync { + /** + * Authenticates with the key vault and shows how to asynchronously list secrets and list versions of a specific + * secret in the key vault. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws InterruptedException { + /* Instantiate a SecretAsyncClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md) + for links and instructions. */ + SecretAsyncClient secretAsyncClient = new SecretClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + // Let's create secrets holding storage and bank accounts credentials valid for 1 year. If the secret already + // exists in the key vault, then a new version of the secret is created. + secretAsyncClient.setSecret(new KeyVaultSecret("BankAccountPassword", "f4G34fMh8v") + .setProperties(new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)))) + .subscribe(secretResponse -> + System.out.printf("Secret is created with name %s and value %s \n", secretResponse.getName(), + secretResponse.getValue())); + + Thread.sleep(2000); + + secretAsyncClient.setSecret(new KeyVaultSecret("StorageAccountPassword", "f4G34fMh8v-fdsgjsk2323=-asdsdfsdf") + .setProperties(new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)))) + .subscribe(secretResponse -> + System.out.printf("Secret is created with name %s and value %s \n", secretResponse.getName(), secretResponse.getValue())); + + Thread.sleep(2000); + + // You need to check if any of the secrets are sharing same values. Let's list the secrets and print their + // values. List operations don't return the secrets with value information. So, for each returned secret we + // call getSecret() to get the secret with its value information. + secretAsyncClient.listPropertiesOfSecrets() + .subscribe(secret -> + secretAsyncClient.getSecret(secret.getName(), secret.getVersion()) + .subscribe(secretResponse -> + System.out.printf("Received secret with name %s and value %s \n", secretResponse.getName(), + secretResponse.getValue()))); + + Thread.sleep(15000); + + // The bank account password got updated, so you want to update the secret in key vault to ensure it reflects + // the new password. Calling setSecret on an existing secret creates a new version of the secret in the key + // vault with the new value. + secretAsyncClient.setSecret(new KeyVaultSecret("BankAccountPassword", "sskdjfsdasdjsd") + .setProperties(new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)))) + .subscribe(secretResponse -> + System.out.printf("Secret is created with name %s and value %s \n", secretResponse.getName(), + secretResponse.getValue())); + + Thread.sleep(2000); + + // You need to check all the different values your bank account password secret had previously. Lets print all + // the versions of this secret. + secretAsyncClient.listPropertiesOfSecretVersions("BankAccountPassword") + .subscribe(secret -> + secretAsyncClient.getSecret(secret.getName(), secret.getVersion()) + .subscribe(secretResponse -> + System.out.printf("Received secret's version with name %s and value %s \n", + secretResponse.getName(), secretResponse.getValue()))); + + Thread.sleep(15000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample6/v2/ListOperationsAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample6/v2/ListOperationsAsync.java new file mode 100644 index 000000000000..258dbe78f0a6 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample6/v2/ListOperationsAsync.java @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.secrets; + +import com.azure.security.keyvault.secrets.models.KeyVaultSecret; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.secrets.models.SecretProperties; + +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to asynchronously list secrets and versions of a given secret in the key vault. + */ +public class ListOperationsAsync { + /** + * Authenticates with the key vault and shows how to asynchronously list secrets and list versions of a specific + * secret in the key vault. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws InterruptedException { + /* Instantiate a SecretAsyncClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md) + for links and instructions. */ + SecretAsyncClient secretAsyncClient = new SecretClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + // Let's create secrets holding storage and bank accounts credentials valid for 1 year. If the secret already + // exists in the key vault, then a new version of the secret is created. + secretAsyncClient.setSecret(new KeyVaultSecret("BankAccountPassword", "f4G34fMh8v") + .setProperties(new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)))) + .subscribe(secretResponse -> + System.out.printf("Secret is created with name %s and value %s \n", secretResponse.getName(), + secretResponse.getValue())); + + Thread.sleep(2000); + + secretAsyncClient.setSecret(new KeyVaultSecret("StorageAccountPassword", "f4G34fMh8v-fdsgjsk2323=-asdsdfsdf") + .setProperties(new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)))) + .subscribe(secretResponse -> + System.out.printf("Secret is created with name %s and value %s \n", secretResponse.getName(), secretResponse.getValue())); + + Thread.sleep(2000); + + // You need to check if any of the secrets are sharing same values. Let's list the secrets and print their + // values. List operations don't return the secrets with value information. So, for each returned secret we + // call getSecret() to get the secret with its value information. + secretAsyncClient.listPropertiesOfSecrets() + .subscribe(secret -> + secretAsyncClient.getSecret(secret.getName(), secret.getVersion()) + .subscribe(secretResponse -> + System.out.printf("Received secret with name %s and value %s \n", secretResponse.getName(), + secretResponse.getValue()))); + + Thread.sleep(15000); + + // The bank account password got updated, so you want to update the secret in key vault to ensure it reflects + // the new password. Calling setSecret on an existing secret creates a new version of the secret in the key + // vault with the new value. + secretAsyncClient.setSecret(new KeyVaultSecret("BankAccountPassword", "sskdjfsdasdjsd") + .setProperties(new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)))) + .subscribe(secretResponse -> + System.out.printf("Secret is created with name %s and value %s \n", secretResponse.getName(), + secretResponse.getValue())); + + Thread.sleep(2000); + + // You need to check all the different values your bank account password secret had previously. Lets print all + // the versions of this secret. + secretAsyncClient.listPropertiesOfSecretVersions("BankAccountPassword") + .subscribe(secret -> + secretAsyncClient.getSecret(secret.getName(), secret.getVersion()) + .subscribe(secretResponse -> + System.out.printf("Received secret's version with name %s and value %s \n", + secretResponse.getName(), secretResponse.getValue()))); + + Thread.sleep(15000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample7/v1/ManagingDeletedSecrets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample7/v1/ManagingDeletedSecrets.java new file mode 100644 index 000000000000..260af3222ad8 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample7/v1/ManagingDeletedSecrets.java @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.secrets; + +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.secrets.models.DeletedSecret; +import com.azure.security.keyvault.secrets.models.KeyVaultSecret; +import com.azure.security.keyvault.secrets.models.SecretProperties; + +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to list, recover and purge deleted secrets in a soft-delete enabled key vault. + */ +public class ManagingDeletedSecrets { + /** + * Authenticates with the key vault and shows how to list, recover and purge deleted secrets in a soft-delete + * enabled key vault. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws IllegalArgumentException, InterruptedException { + /* NOTE: To manage deleted secrets, your key vault needs to have soft-delete enabled. Soft-delete allows deleted + secrets to be retained for a given retention period (90 days). During this period deleted secrets can be + recovered and if a secret needs to be permanently deleted then it needs to be purged. */ + + /* Instantiate a SecretClient that will be used to call the service. Notice that the client is using default + Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md) + for links and instructions. */ + SecretClient client = new SecretClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + // Let's create secrets holding storage and bank accounts credentials valid for 1 year. If the secret already + // exists in the key vault, then a new version of the secret is created. + client.setSecret(new KeyVaultSecret("StorageAccountPassword", "f4G34fMh8v-fdsgjsk2323=-asdsdfsdf") + .setProperties(new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)))); + + client.setSecret(new KeyVaultSecret("BankAccountPassword", "f4G34fMh8v") + .setProperties(new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)))); + + // The storage account was closed, need to delete its credentials from the key vault. + SyncPoller deletedBankSecretPoller = client.beginDeleteSecret("BankAccountPassword"); + + PollResponse deletedBankSecretPollResponse = deletedBankSecretPoller.poll(); + + System.out.println("Deleted Date %s" + deletedBankSecretPollResponse.getValue().getDeletedOn().toString()); + System.out.printf("Deleted Secret's Recovery Id %s", deletedBankSecretPollResponse.getValue().getRecoveryId()); + + // The secret is being deleted on the server. + deletedBankSecretPoller.waitForCompletion(); + + // We accidentally deleted bank account secret. Let's recover it. + // A deleted secret can only be recovered if the key vault is soft-delete enabled. + SyncPoller recoverSecretPoller = + client.beginRecoverDeletedSecret("BankAccountPassword"); + + PollResponse recoverSecretResponse = recoverSecretPoller.poll(); + + System.out.println("Recovered Key Name %s" + recoverSecretResponse.getValue().getName()); + System.out.printf("Recovered Key's Id %s", recoverSecretResponse.getValue().getId()); + + // The secret is being recovered on the server. + recoverSecretPoller.waitForCompletion(); + + // The bank account and storage accounts got closed. + // Let's delete bank and storage accounts secrets. + SyncPoller deletedBankPwdSecretPoller = + client.beginDeleteSecret("BankAccountPassword"); + PollResponse deletedBankPwdSecretPollResponse = deletedBankPwdSecretPoller.poll(); + + System.out.println("Deleted Date %s" + deletedBankPwdSecretPollResponse.getValue().getDeletedOn().toString()); + System.out.printf("Deleted Secret's Recovery Id %s", + deletedBankPwdSecretPollResponse.getValue().getRecoveryId()); + + // The secret is being deleted on the server. + deletedBankPwdSecretPoller.waitForCompletion(); + + SyncPoller deletedStorageSecretPoller = + client.beginDeleteSecret("StorageAccountPassword"); + PollResponse deletedStorageSecretPollResponse = deletedStorageSecretPoller.poll(); + + System.out.println("Deleted Date %s" + deletedStorageSecretPollResponse.getValue().getDeletedOn().toString()); + System.out.printf("Deleted Secret's Recovery Id %s", deletedStorageSecretPollResponse.getValue().getRecoveryId()); + + // The secret is being deleted on the server. + deletedStorageSecretPoller.waitForCompletion(); + + // You can list all the deleted and non-purged secrets, assuming key vault is soft-delete enabled. + for (DeletedSecret delSecret : client.listDeletedSecrets()) { + System.out.printf("Deleted secret's recovery Id %s", delSecret.getRecoveryId()); + } + + // If the key vault is soft-delete enabled, then for permanent deletion deleted secrets need to be purged. + client.purgeDeletedSecret("StorageAccountPassword"); + client.purgeDeletedSecret("BankAccountPassword"); + + // To ensure the secret is purged server-side. + Thread.sleep(15000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample7/v2/ManagingDeletedSecrets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample7/v2/ManagingDeletedSecrets.java new file mode 100644 index 000000000000..260af3222ad8 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample7/v2/ManagingDeletedSecrets.java @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.secrets; + +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.secrets.models.DeletedSecret; +import com.azure.security.keyvault.secrets.models.KeyVaultSecret; +import com.azure.security.keyvault.secrets.models.SecretProperties; + +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to list, recover and purge deleted secrets in a soft-delete enabled key vault. + */ +public class ManagingDeletedSecrets { + /** + * Authenticates with the key vault and shows how to list, recover and purge deleted secrets in a soft-delete + * enabled key vault. + * + * @param args Unused. Arguments to the program. + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws IllegalArgumentException, InterruptedException { + /* NOTE: To manage deleted secrets, your key vault needs to have soft-delete enabled. Soft-delete allows deleted + secrets to be retained for a given retention period (90 days). During this period deleted secrets can be + recovered and if a secret needs to be permanently deleted then it needs to be purged. */ + + /* Instantiate a SecretClient that will be used to call the service. Notice that the client is using default + Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md) + for links and instructions. */ + SecretClient client = new SecretClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + // Let's create secrets holding storage and bank accounts credentials valid for 1 year. If the secret already + // exists in the key vault, then a new version of the secret is created. + client.setSecret(new KeyVaultSecret("StorageAccountPassword", "f4G34fMh8v-fdsgjsk2323=-asdsdfsdf") + .setProperties(new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)))); + + client.setSecret(new KeyVaultSecret("BankAccountPassword", "f4G34fMh8v") + .setProperties(new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)))); + + // The storage account was closed, need to delete its credentials from the key vault. + SyncPoller deletedBankSecretPoller = client.beginDeleteSecret("BankAccountPassword"); + + PollResponse deletedBankSecretPollResponse = deletedBankSecretPoller.poll(); + + System.out.println("Deleted Date %s" + deletedBankSecretPollResponse.getValue().getDeletedOn().toString()); + System.out.printf("Deleted Secret's Recovery Id %s", deletedBankSecretPollResponse.getValue().getRecoveryId()); + + // The secret is being deleted on the server. + deletedBankSecretPoller.waitForCompletion(); + + // We accidentally deleted bank account secret. Let's recover it. + // A deleted secret can only be recovered if the key vault is soft-delete enabled. + SyncPoller recoverSecretPoller = + client.beginRecoverDeletedSecret("BankAccountPassword"); + + PollResponse recoverSecretResponse = recoverSecretPoller.poll(); + + System.out.println("Recovered Key Name %s" + recoverSecretResponse.getValue().getName()); + System.out.printf("Recovered Key's Id %s", recoverSecretResponse.getValue().getId()); + + // The secret is being recovered on the server. + recoverSecretPoller.waitForCompletion(); + + // The bank account and storage accounts got closed. + // Let's delete bank and storage accounts secrets. + SyncPoller deletedBankPwdSecretPoller = + client.beginDeleteSecret("BankAccountPassword"); + PollResponse deletedBankPwdSecretPollResponse = deletedBankPwdSecretPoller.poll(); + + System.out.println("Deleted Date %s" + deletedBankPwdSecretPollResponse.getValue().getDeletedOn().toString()); + System.out.printf("Deleted Secret's Recovery Id %s", + deletedBankPwdSecretPollResponse.getValue().getRecoveryId()); + + // The secret is being deleted on the server. + deletedBankPwdSecretPoller.waitForCompletion(); + + SyncPoller deletedStorageSecretPoller = + client.beginDeleteSecret("StorageAccountPassword"); + PollResponse deletedStorageSecretPollResponse = deletedStorageSecretPoller.poll(); + + System.out.println("Deleted Date %s" + deletedStorageSecretPollResponse.getValue().getDeletedOn().toString()); + System.out.printf("Deleted Secret's Recovery Id %s", deletedStorageSecretPollResponse.getValue().getRecoveryId()); + + // The secret is being deleted on the server. + deletedStorageSecretPoller.waitForCompletion(); + + // You can list all the deleted and non-purged secrets, assuming key vault is soft-delete enabled. + for (DeletedSecret delSecret : client.listDeletedSecrets()) { + System.out.printf("Deleted secret's recovery Id %s", delSecret.getRecoveryId()); + } + + // If the key vault is soft-delete enabled, then for permanent deletion deleted secrets need to be purged. + client.purgeDeletedSecret("StorageAccountPassword"); + client.purgeDeletedSecret("BankAccountPassword"); + + // To ensure the secret is purged server-side. + Thread.sleep(15000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample8/v1/ManagingDeletedSecretsAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample8/v1/ManagingDeletedSecretsAsync.java new file mode 100644 index 000000000000..be097d9bacb6 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample8/v1/ManagingDeletedSecretsAsync.java @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.secrets; + +import com.azure.security.keyvault.secrets.models.KeyVaultSecret; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.secrets.models.SecretProperties; + +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to asynchronously list, recover and purge deleted secrets in a soft-delete enabled key vault. + */ +public class ManagingDeletedSecretsAsync { + /** + * Authenticates with the key vault and shows how to asynchronously list, recover and purge deleted secrets in a + * soft-delete enabled key vault. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws InterruptedException { + /* NOTE: To manage deleted secrets, your key vault needs to have soft-delete enabled. Soft-delete allows deleted + secrets to be retained for a given retention period (90 days). During this period deleted secrets can be + recovered and if a secret needs to be permanently deleted then it needs to be purged. */ + + /* Instantiate a SecretAsyncClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md) + for links and instructions. */ + SecretAsyncClient secretAsyncClient = new SecretClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + // Let's create secrets holding storage and bank accounts credentials valid for 1 year. If the secret + // already exists in the key vault, then a new version of the secret is created. + secretAsyncClient.setSecret(new KeyVaultSecret("BankAccountPassword", "f4G34fMh8v") + .setProperties(new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)))) + .subscribe(secretResponse -> + System.out.printf("Secret is created with name %s and value %s %n", secretResponse.getName(), + secretResponse.getValue())); + + Thread.sleep(2000); + + secretAsyncClient.setSecret(new KeyVaultSecret("StorageAccountPassword", "f4G34fMh8v-fdsgjsk2323=-asdsdfsdf") + .setProperties(new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)))) + .subscribe(secretResponse -> + System.out.printf("Secret is created with name %s and value %s %n", secretResponse.getName(), + secretResponse.getValue())); + + Thread.sleep(2000); + + // The storage account was closed, need to delete its credentials from the key vault. + secretAsyncClient.beginDeleteSecret("BankAccountPassword") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Deleted Secret Name: " + pollResponse.getValue().getName()); + System.out.println("Deleted Secret Value: " + pollResponse.getValue().getValue()); + }); + + // To ensure the secret is deleted server-side. + Thread.sleep(30000); + + // We accidentally deleted bank account secret. Let's recover it. + // A deleted secret can only be recovered if the key vault is soft-delete enabled. + secretAsyncClient.beginRecoverDeletedSecret("BankAccountPassword") + .subscribe(pollResponse -> { + System.out.println("Recovery Status: " + pollResponse.getStatus().toString()); + System.out.println("Recovered Secret Name: " + pollResponse.getValue().getName()); + System.out.println("Recovered Secret Value: " + pollResponse.getValue().getValue()); + }); + + // To ensure the secret is recovered server-side. + Thread.sleep(10000); + + // The bank account and storage accounts got closed. + // Let's delete bank and storage accounts secrets. + secretAsyncClient.beginDeleteSecret("BankAccountPassword") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Deleted Secret Name: " + pollResponse.getValue().getName()); + System.out.println("Deleted Secret Value: " + pollResponse.getValue().getValue()); + }); + + secretAsyncClient.beginDeleteSecret("StorageAccountPassword") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Deleted Secret Name: " + pollResponse.getValue().getName()); + System.out.println("Deleted Secret Value: " + pollResponse.getValue().getValue()); + }); + + // To ensure the secret is deleted server-side. + Thread.sleep(30000); + + // You can list all the deleted and non-purged secrets, assuming key vault is soft-delete enabled. + secretAsyncClient.listDeletedSecrets() + .subscribe(deletedSecret -> + System.out.printf("Deleted secret's recovery Id %s %n", deletedSecret.getRecoveryId())); + + Thread.sleep(15000); + + // If the key vault is soft-delete enabled, then for permanent deletion deleted secrets need to be purged. + secretAsyncClient.purgeDeletedSecretWithResponse("StorageAccountPassword") + .subscribe(purgeResponse -> + System.out.printf("Storage account secret purge status response %d %n", purgeResponse.getStatusCode())); + + secretAsyncClient.purgeDeletedSecretWithResponse("BankAccountPassword") + .subscribe(purgeResponse -> + System.out.printf("Bank account secret purge status response %d %n", purgeResponse.getStatusCode())); + + // To ensure the secret is purged server-side. + Thread.sleep(15000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample8/v2/ManagingDeletedSecretsAsync.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample8/v2/ManagingDeletedSecretsAsync.java new file mode 100644 index 000000000000..be097d9bacb6 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample8/v2/ManagingDeletedSecretsAsync.java @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.secrets; + +import com.azure.security.keyvault.secrets.models.KeyVaultSecret; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.security.keyvault.secrets.models.SecretProperties; + +import java.time.OffsetDateTime; + +/** + * Sample demonstrates how to asynchronously list, recover and purge deleted secrets in a soft-delete enabled key vault. + */ +public class ManagingDeletedSecretsAsync { + /** + * Authenticates with the key vault and shows how to asynchronously list, recover and purge deleted secrets in a + * soft-delete enabled key vault. + * + * @param args Unused. Arguments to the program. + * + * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. + */ + public static void main(String[] args) throws InterruptedException { + /* NOTE: To manage deleted secrets, your key vault needs to have soft-delete enabled. Soft-delete allows deleted + secrets to be retained for a given retention period (90 days). During this period deleted secrets can be + recovered and if a secret needs to be permanently deleted then it needs to be purged. */ + + /* Instantiate a SecretAsyncClient that will be used to call the service. Notice that the client is using + default Azure credentials. For more information on this and other types of credentials, see this document: + https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable. + + To get started, you'll need a URL to an Azure Key Vault. See the README + (https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/keyvault/azure-security-keyvault-secrets/README.md) + for links and instructions. */ + SecretAsyncClient secretAsyncClient = new SecretClientBuilder() + .vaultUrl("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + // Let's create secrets holding storage and bank accounts credentials valid for 1 year. If the secret + // already exists in the key vault, then a new version of the secret is created. + secretAsyncClient.setSecret(new KeyVaultSecret("BankAccountPassword", "f4G34fMh8v") + .setProperties(new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)))) + .subscribe(secretResponse -> + System.out.printf("Secret is created with name %s and value %s %n", secretResponse.getName(), + secretResponse.getValue())); + + Thread.sleep(2000); + + secretAsyncClient.setSecret(new KeyVaultSecret("StorageAccountPassword", "f4G34fMh8v-fdsgjsk2323=-asdsdfsdf") + .setProperties(new SecretProperties() + .setExpiresOn(OffsetDateTime.now().plusYears(1)))) + .subscribe(secretResponse -> + System.out.printf("Secret is created with name %s and value %s %n", secretResponse.getName(), + secretResponse.getValue())); + + Thread.sleep(2000); + + // The storage account was closed, need to delete its credentials from the key vault. + secretAsyncClient.beginDeleteSecret("BankAccountPassword") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Deleted Secret Name: " + pollResponse.getValue().getName()); + System.out.println("Deleted Secret Value: " + pollResponse.getValue().getValue()); + }); + + // To ensure the secret is deleted server-side. + Thread.sleep(30000); + + // We accidentally deleted bank account secret. Let's recover it. + // A deleted secret can only be recovered if the key vault is soft-delete enabled. + secretAsyncClient.beginRecoverDeletedSecret("BankAccountPassword") + .subscribe(pollResponse -> { + System.out.println("Recovery Status: " + pollResponse.getStatus().toString()); + System.out.println("Recovered Secret Name: " + pollResponse.getValue().getName()); + System.out.println("Recovered Secret Value: " + pollResponse.getValue().getValue()); + }); + + // To ensure the secret is recovered server-side. + Thread.sleep(10000); + + // The bank account and storage accounts got closed. + // Let's delete bank and storage accounts secrets. + secretAsyncClient.beginDeleteSecret("BankAccountPassword") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Deleted Secret Name: " + pollResponse.getValue().getName()); + System.out.println("Deleted Secret Value: " + pollResponse.getValue().getValue()); + }); + + secretAsyncClient.beginDeleteSecret("StorageAccountPassword") + .subscribe(pollResponse -> { + System.out.println("Delete Status: " + pollResponse.getStatus().toString()); + System.out.println("Deleted Secret Name: " + pollResponse.getValue().getName()); + System.out.println("Deleted Secret Value: " + pollResponse.getValue().getValue()); + }); + + // To ensure the secret is deleted server-side. + Thread.sleep(30000); + + // You can list all the deleted and non-purged secrets, assuming key vault is soft-delete enabled. + secretAsyncClient.listDeletedSecrets() + .subscribe(deletedSecret -> + System.out.printf("Deleted secret's recovery Id %s %n", deletedSecret.getRecoveryId())); + + Thread.sleep(15000); + + // If the key vault is soft-delete enabled, then for permanent deletion deleted secrets need to be purged. + secretAsyncClient.purgeDeletedSecretWithResponse("StorageAccountPassword") + .subscribe(purgeResponse -> + System.out.printf("Storage account secret purge status response %d %n", purgeResponse.getStatusCode())); + + secretAsyncClient.purgeDeletedSecretWithResponse("BankAccountPassword") + .subscribe(purgeResponse -> + System.out.printf("Bank account secret purge status response %d %n", purgeResponse.getStatusCode())); + + // To ensure the secret is purged server-side. + Thread.sleep(15000); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample9/v1/PersistentTokenCacheDemo.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample9/v1/PersistentTokenCacheDemo.java new file mode 100644 index 000000000000..d74bbc6464e8 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample9/v1/PersistentTokenCacheDemo.java @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.secrets; + +import com.azure.security.keyvault.secrets.models.KeyVaultSecret; +import com.azure.identity.SharedTokenCacheCredential; +import com.azure.identity.SharedTokenCacheCredentialBuilder; + +/** + * Sample showing how to authenticate to Key Vault with a shared token cache credential. + */ +public class PersistentTokenCacheDemo { + /** + * Authenticates from shared token cache and gets a secret. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // Wrote to AZURE_USERNAME env variable. + SharedTokenCacheCredential defaultCredential = new SharedTokenCacheCredentialBuilder() + .clientId("") + .build(); + + SecretClient client = new SecretClientBuilder() + .vaultUrl("") + .credential(defaultCredential) + .buildClient(); + + // Try to get a secret! Only works if you are logged in. + System.out.println("\nWhat is the super secret secret?\n\n"); + + KeyVaultSecret secret = client.getSecret("the-secret"); + + System.out.println("Secret was found: " + secret.getValue()); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample9/v2/PersistentTokenCacheDemo.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample9/v2/PersistentTokenCacheDemo.java new file mode 100644 index 000000000000..d74bbc6464e8 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-security-keyvault-secrets/sample9/v2/PersistentTokenCacheDemo.java @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.secrets; + +import com.azure.security.keyvault.secrets.models.KeyVaultSecret; +import com.azure.identity.SharedTokenCacheCredential; +import com.azure.identity.SharedTokenCacheCredentialBuilder; + +/** + * Sample showing how to authenticate to Key Vault with a shared token cache credential. + */ +public class PersistentTokenCacheDemo { + /** + * Authenticates from shared token cache and gets a secret. + * + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + // Wrote to AZURE_USERNAME env variable. + SharedTokenCacheCredential defaultCredential = new SharedTokenCacheCredentialBuilder() + .clientId("") + .build(); + + SecretClient client = new SecretClientBuilder() + .vaultUrl("") + .credential(defaultCredential) + .buildClient(); + + // Try to get a secret! Only works if you are logged in. + System.out.println("\nWhat is the super secret secret?\n\n"); + + KeyVaultSecret secret = client.getSecret("the-secret"); + + System.out.println("Secret was found: " + secret.getValue()); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample1/v1/SimpleBlobClientUsage.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample1/v1/SimpleBlobClientUsage.java new file mode 100644 index 000000000000..562132a52165 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample1/v1/SimpleBlobClientUsage.java @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +import com.azure.core.credential.AzureSasCredential; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.policy.HttpLogOptions; +import com.azure.core.http.policy.RetryPolicy; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.storage.blob.BlobServiceClient; +import com.azure.storage.blob.BlobServiceClientBuilder; +import com.azure.storage.blob.models.BlobStorageException; +import com.azure.storage.blob.models.ListBlobsOptions; +import com.azure.storage.blob.specialized.BlockBlobClient; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; + +public class SimpleBlobClientUsage { + private static final ClientLogger logger = new ClientLogger(AzureStorageBlobExample.class); + + public static void main(String[] args) { + String sasToken = "your-sas-token"; + String endpoint = "https://your-storage-account.blob.core.windows.net"; + String containerName = "your-container-name"; + String blobName = "sample-blob.txt"; + String content = "Hello, Azure Blob Storage!"; + + // Create a BlobServiceClient with a custom HttpPipeline + HttpPipeline pipeline = new HttpPipelineBuilder() + .policies(new RetryPolicy()) + .build(); + + BlobServiceClient blobServiceClient = new BlobServiceClientBuilder() + .endpoint(endpoint) + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) + .credential(new AzureSasCredential(sasToken)) + .pipeline(pipeline) + .buildClient(); + + // Upload a blob + BlockBlobClient blobClient = blobServiceClient.getBlobContainerClient(containerName) + .getBlobClient(blobName) + .getBlockBlobClient(); + + try (ByteArrayInputStream dataStream = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8))) { + blobClient.upload(dataStream, content.length(), true); + logger.info("Blob uploaded successfully."); + } catch (IOException e) { + logger.error("Failed to upload blob.", e); + } + + // List blobs in the container + ListBlobsOptions options = new ListBlobsOptions().setPrefix("sample"); + List blobNames = new ArrayList<>(); + blobServiceClient.getBlobContainerClient(containerName) + .listBlobs(options, Context.NONE) + .forEach(blobItem -> blobNames.add(blobItem.getName())); + + logger.info("Blobs in container:"); + blobNames.forEach(logger::info); + + // Download the blob + try { + byte[] downloadedContent = new byte[(int) blobClient.getProperties().getBlobSize()]; + blobClient.download(downloadedContent, Context.NONE); + logger.info("Downloaded blob content: " + new String(downloadedContent, StandardCharsets.UTF_8)); + } catch (BlobStorageException e) { + logger.error("Failed to download blob.", e); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample1/v2/SimpleBlobClientUsage.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample1/v2/SimpleBlobClientUsage.java new file mode 100644 index 000000000000..ebb6db0ec2f3 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample1/v2/SimpleBlobClientUsage.java @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +import com.azure.v2.storage.blob.BlobServiceClient; +import com.azure.v2.storage.blob.BlobServiceClientBuilder; +import com.azure.v2.storage.blob.models.BlobStorageException; +import com.azure.v2.storage.blob.models.ListBlobsOptions; +import com.azure.v2.storage.blob.specialized.BlockBlobClient; +import io.clientcore.core.credential.KeyCredential; +import io.clientcore.core.http.models.HttpInstrumentationOptions; +import io.clientcore.core.http.models.HttpInstrumentationOptions.HttpLogDetailLevel; +import io.clientcore.core.http.pipeline.HttpPipeline; +import io.clientcore.core.http.pipeline.HttpPipelineBuilder; +import io.clientcore.core.http.pipeline.HttpRetryPolicy; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.utils.Context; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; + +public class SimpleBlobClientUsage { + private static final ClientLogger logger = new ClientLogger(AzureStorageBlobExample.class); + + public static void main(String[] args) { + String sasToken = "your-sas-token"; + String endpoint = "https://your-storage-account.blob.core.windows.net"; + String containerName = "your-container-name"; + String blobName = "sample-blob.txt"; + String content = "Hello, Azure Blob Storage!"; + + // Create a BlobServiceClient with a custom HttpPipeline + HttpPipeline pipeline = new HttpPipelineBuilder() + .policies(new HttpRetryPolicy()) + .build(); + + BlobServiceClient blobServiceClient = new BlobServiceClientBuilder() + .endpoint(endpoint) + .httpInstrumentationOptions(new HttpInstrumentationOptions().setLogLevel(HttpInstrumentationOptions.HttpLogDetailLevel.BODY_AND_HEADERS)) + .credential(new KeyCredential(sasToken)) + .pipeline(pipeline) + .buildClient(); + + // Upload a blob + BlockBlobClient blobClient = blobServiceClient.getBlobContainerClient(containerName) + .getBlobClient(blobName) + .getBlockBlobClient(); + + try (ByteArrayInputStream dataStream = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8))) { + blobClient.upload(dataStream, content.length(), true); + logger.info("Blob uploaded successfully."); + } catch (IOException e) { + logger.error("Failed to upload blob.", e); + } + + // List blobs in the container + ListBlobsOptions options = new ListBlobsOptions().setPrefix("sample"); + List blobNames = new ArrayList<>(); + blobServiceClient.getBlobContainerClient(containerName) + .listBlobs(options, Context.none()) + .forEach(blobItem -> blobNames.add(blobItem.getName())); + + logger.info("Blobs in container:"); + blobNames.forEach(logger::info); + + // Download the blob + try { + byte[] downloadedContent = new byte[(int) blobClient.getProperties().getBlobSize()]; + blobClient.download(downloadedContent, Context.none()); + logger.info("Downloaded blob content: " + new String(downloadedContent, StandardCharsets.UTF_8)); + } catch (BlobStorageException e) { + logger.error("Failed to download blob.", e); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample10/v1/BlobContainerClientBuilderJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample10/v1/BlobContainerClientBuilderJavaDocCodeSnippets.java new file mode 100644 index 000000000000..f7460d418272 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample10/v1/BlobContainerClientBuilderJavaDocCodeSnippets.java @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.policy.AddDatePolicy; +import com.azure.core.http.policy.RequestIdPolicy; +import com.azure.storage.common.StorageSharedKeyCredential; +import com.azure.storage.common.policy.RequestRetryOptions; +import com.azure.storage.common.policy.RequestRetryPolicy; +import com.azure.storage.common.policy.StorageSharedKeyCredentialPolicy; + +/** + * Code snippets for {@link BlobContainerClientBuilder} + */ +@SuppressWarnings({"unused"}) +public class BlobContainerClientBuilderJavaDocCodeSnippets { + private String connectionString = "AccountName=name;AccountKey=key;DefaultEndpointProtocol=protocol;EndpointSuffix=suffix"; + private String endpoint = "endpointURL"; + private String containerName = "container Name"; + private StorageSharedKeyCredential storageSharedKeyCredential = new StorageSharedKeyCredential("accountName", "accountKey"); + private HttpPipeline httpPipeline = new HttpPipelineBuilder() + .httpClient(HttpClient.createDefault()) + .policies(new AddDatePolicy()) + .policies(new RequestIdPolicy()) + .policies(new StorageSharedKeyCredentialPolicy(storageSharedKeyCredential)) + .policies(new RequestRetryPolicy(new RequestRetryOptions())) + .build(); + + /** + * Code snippet for {@link BlobContainerClientBuilder#buildClient()} using connection string + */ + public void containerClientConnectionString() { + // BEGIN: com.azure.storage.blob.BlobContainerClientBuilder.buildClient + BlobContainerClient client = new BlobContainerClientBuilder() + .connectionString(connectionString) + .buildClient(); + // END: com.azure.storage.blob.BlobContainerClientBuilder.buildClient + } + + /** + * Code snippet for {@link BlobContainerClientBuilder#buildAsyncClient()} using connection string + */ + public void containerAsyncClientConnectionString() { + // BEGIN: com.azure.storage.blob.BlobContainerClientBuilder.buildAsyncClient + BlobContainerAsyncClient client = new BlobContainerClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + // END: com.azure.storage.blob.BlobContainerClientBuilder.buildAsyncClient + } + + /** + * Code snippet for {@link BlobContainerClientBuilder#buildClient()} using credential and endpoint + */ + public void containerClientCredentialAndEndpoint() { + // BEGIN: com.azure.storage.blob.BlobContainerClientBuilder.endpoint#String + BlobContainerClient client = new BlobContainerClientBuilder() + .endpoint(endpoint) + .credential(storageSharedKeyCredential) + .buildClient(); + // END: com.azure.storage.blob.BlobContainerClientBuilder.endpoint#String + } + + /** + * Code snippet for {@link BlobContainerClientBuilder#buildClient()} using Container Name + */ + public void containerClientContainerName() { + // BEGIN: com.azure.storage.blob.BlobContainerClientBuilder.containerName#String + BlobContainerClient client = new BlobContainerClientBuilder() + .endpoint(endpoint) + .containerName(containerName) + .buildClient(); + // END: com.azure.storage.blob.BlobContainerClientBuilder.containerName#String + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample10/v2/BlobContainerClientBuilderJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample10/v2/BlobContainerClientBuilderJavaDocCodeSnippets.java new file mode 100644 index 000000000000..f7460d418272 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample10/v2/BlobContainerClientBuilderJavaDocCodeSnippets.java @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.policy.AddDatePolicy; +import com.azure.core.http.policy.RequestIdPolicy; +import com.azure.storage.common.StorageSharedKeyCredential; +import com.azure.storage.common.policy.RequestRetryOptions; +import com.azure.storage.common.policy.RequestRetryPolicy; +import com.azure.storage.common.policy.StorageSharedKeyCredentialPolicy; + +/** + * Code snippets for {@link BlobContainerClientBuilder} + */ +@SuppressWarnings({"unused"}) +public class BlobContainerClientBuilderJavaDocCodeSnippets { + private String connectionString = "AccountName=name;AccountKey=key;DefaultEndpointProtocol=protocol;EndpointSuffix=suffix"; + private String endpoint = "endpointURL"; + private String containerName = "container Name"; + private StorageSharedKeyCredential storageSharedKeyCredential = new StorageSharedKeyCredential("accountName", "accountKey"); + private HttpPipeline httpPipeline = new HttpPipelineBuilder() + .httpClient(HttpClient.createDefault()) + .policies(new AddDatePolicy()) + .policies(new RequestIdPolicy()) + .policies(new StorageSharedKeyCredentialPolicy(storageSharedKeyCredential)) + .policies(new RequestRetryPolicy(new RequestRetryOptions())) + .build(); + + /** + * Code snippet for {@link BlobContainerClientBuilder#buildClient()} using connection string + */ + public void containerClientConnectionString() { + // BEGIN: com.azure.storage.blob.BlobContainerClientBuilder.buildClient + BlobContainerClient client = new BlobContainerClientBuilder() + .connectionString(connectionString) + .buildClient(); + // END: com.azure.storage.blob.BlobContainerClientBuilder.buildClient + } + + /** + * Code snippet for {@link BlobContainerClientBuilder#buildAsyncClient()} using connection string + */ + public void containerAsyncClientConnectionString() { + // BEGIN: com.azure.storage.blob.BlobContainerClientBuilder.buildAsyncClient + BlobContainerAsyncClient client = new BlobContainerClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + // END: com.azure.storage.blob.BlobContainerClientBuilder.buildAsyncClient + } + + /** + * Code snippet for {@link BlobContainerClientBuilder#buildClient()} using credential and endpoint + */ + public void containerClientCredentialAndEndpoint() { + // BEGIN: com.azure.storage.blob.BlobContainerClientBuilder.endpoint#String + BlobContainerClient client = new BlobContainerClientBuilder() + .endpoint(endpoint) + .credential(storageSharedKeyCredential) + .buildClient(); + // END: com.azure.storage.blob.BlobContainerClientBuilder.endpoint#String + } + + /** + * Code snippet for {@link BlobContainerClientBuilder#buildClient()} using Container Name + */ + public void containerClientContainerName() { + // BEGIN: com.azure.storage.blob.BlobContainerClientBuilder.containerName#String + BlobContainerClient client = new BlobContainerClientBuilder() + .endpoint(endpoint) + .containerName(containerName) + .buildClient(); + // END: com.azure.storage.blob.BlobContainerClientBuilder.containerName#String + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample11/v1/BlobContainerClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample11/v1/BlobContainerClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..6ea36fcd0d41 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample11/v1/BlobContainerClientJavaDocCodeSnippets.java @@ -0,0 +1,537 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.storage.blob.models.BlobAccessPolicy; +import com.azure.storage.blob.models.BlobContainerAccessPolicies; +import com.azure.storage.blob.models.BlobContainerProperties; +import com.azure.storage.blob.models.BlobErrorCode; +import com.azure.storage.blob.models.BlobListDetails; +import com.azure.storage.blob.models.BlobRequestConditions; +import com.azure.storage.blob.models.BlobSignedIdentifier; +import com.azure.storage.blob.models.BlobStorageException; +import com.azure.storage.blob.models.ListBlobsOptions; +import com.azure.storage.blob.models.PublicAccessType; +import com.azure.storage.blob.models.StorageAccountInfo; +import com.azure.storage.blob.models.UserDelegationKey; +import com.azure.storage.blob.options.BlobContainerCreateOptions; +import com.azure.storage.blob.options.FindBlobsOptions; +import com.azure.storage.blob.sas.BlobContainerSasPermission; +import com.azure.storage.blob.sas.BlobServiceSasSignatureValues; + +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +@SuppressWarnings({"unused"}) +public class BlobContainerClientJavaDocCodeSnippets { + + private BlobContainerClient client = JavaDocCodeSnippetsHelpers.getContainerClient(); + private String blobName = "blobName"; + private String snapshot = "snapshot"; + private String leaseId = "leaseId"; + private String proposedId = "proposedId"; + private int leaseDuration = (int) Duration.ofSeconds(30).getSeconds(); + private Duration timeout = Duration.ofSeconds(30); + private String accountName = "accountName"; + private UserDelegationKey userDelegationKey = JavaDocCodeSnippetsHelpers.getUserDelegationKey(); + + /** + * Code snippet for {@link BlobContainerClient#getBlobClient(String)} + */ + public void getBlobClient() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.getBlobClient#String + BlobClient blobClient = client.getBlobClient(blobName); + // END: com.azure.storage.blob.BlobContainerClient.getBlobClient#String + } + + /** + * Code snippet for {@link BlobContainerClient#getBlobClient(String, String)} + */ + public void getSnapshotBlobClient() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.getBlobClient#String-String + BlobClient blobClient = client.getBlobClient(blobName, snapshot); + // END: com.azure.storage.blob.BlobContainerClient.getBlobClient#String-String + } + + /** + * Code snippets for {@link BlobContainerClient#exists()} and {@link BlobContainerClient#existsWithResponse(Duration, + * Context)} + */ + public void exists() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.exists + System.out.printf("Exists? %b%n", client.exists()); + // END: com.azure.storage.blob.BlobContainerClient.exists + + // BEGIN: com.azure.storage.blob.BlobContainerClient.existsWithResponse#Duration-Context + Context context = new Context("Key", "Value"); + System.out.printf("Exists? %b%n", client.existsWithResponse(timeout, context).getValue()); + // END: com.azure.storage.blob.BlobContainerClient.existsWithResponse#Duration-Context + } + + /** + * Code snippet for {@link BlobContainerClient#create()} + */ + public void setCreate() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.create + try { + client.create(); + System.out.printf("Create completed%n"); + } catch (BlobStorageException error) { + if (error.getErrorCode().equals(BlobErrorCode.CONTAINER_ALREADY_EXISTS)) { + System.out.printf("Can't create container. It already exists %n"); + } + } + // END: com.azure.storage.blob.BlobContainerClient.create + } + + /** + * Code snippet for {@link BlobContainerClient#createWithResponse(Map, PublicAccessType, Duration, Context)} + */ + public void create2() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.createWithResponse#Map-PublicAccessType-Duration-Context + Map metadata = Collections.singletonMap("metadata", "value"); + Context context = new Context("Key", "Value"); + + System.out.printf("Create completed with status %d%n", + client.createWithResponse(metadata, PublicAccessType.CONTAINER, timeout, context).getStatusCode()); + // END: com.azure.storage.blob.BlobContainerClient.createWithResponse#Map-PublicAccessType-Duration-Context + } + + /** + * Code snippet for {@link BlobContainerClient#delete()} + */ + public void setDelete() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.delete + try { + client.delete(); + System.out.printf("Delete completed%n"); + } catch (BlobStorageException error) { + if (error.getErrorCode().equals(BlobErrorCode.CONTAINER_NOT_FOUND)) { + System.out.printf("Delete failed. Container was not found %n"); + } + } + // END: com.azure.storage.blob.BlobContainerClient.delete + } + + /** + * Code snippet for {@link BlobContainerClient#deleteWithResponse(BlobRequestConditions, Duration, Context)} + */ + public void delete2() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.deleteWithResponse#BlobRequestConditions-Duration-Context + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context("Key", "Value"); + + System.out.printf("Delete completed with status %d%n", client.deleteWithResponse( + requestConditions, timeout, context).getStatusCode()); + // END: com.azure.storage.blob.BlobContainerClient.deleteWithResponse#BlobRequestConditions-Duration-Context + } + + /** + * Code snippet for {@link BlobContainerClient#getProperties()} + */ + public void getProperties() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.getProperties + BlobContainerProperties properties = client.getProperties(); + System.out.printf("Public Access Type: %s, Legal Hold? %b, Immutable? %b%n", + properties.getBlobPublicAccess(), + properties.hasLegalHold(), + properties.hasImmutabilityPolicy()); + // END: com.azure.storage.blob.BlobContainerClient.getProperties + } + + /** + * Code snippet for {@link BlobContainerClient#getPropertiesWithResponse(String, Duration, Context)} + */ + public void getProperties2() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.getPropertiesWithResponse#String-Duration-Context + Context context = new Context("Key", "Value"); + + BlobContainerProperties properties = client.getPropertiesWithResponse(leaseId, timeout, context) + .getValue(); + System.out.printf("Public Access Type: %s, Legal Hold? %b, Immutable? %b%n", + properties.getBlobPublicAccess(), + properties.hasLegalHold(), + properties.hasImmutabilityPolicy()); + // END: com.azure.storage.blob.BlobContainerClient.getPropertiesWithResponse#String-Duration-Context + } + + /** + * Code snippet for {@link BlobContainerClient#setMetadata(Map)} + */ + public void setMetadata() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.setMetadata#Map + Map metadata = Collections.singletonMap("metadata", "value"); + try { + client.setMetadata(metadata); + System.out.printf("Set metadata completed with status %n"); + } catch (UnsupportedOperationException error) { + System.out.printf("Fail while setting metadata %n"); + } + // END: com.azure.storage.blob.BlobContainerClient.setMetadata#Map + } + + /** + * Code snippet for {@link BlobContainerClient#setMetadataWithResponse(Map, BlobRequestConditions, Duration, + * Context)} + */ + public void setMetadata2() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.setMetadataWithResponse#Map-BlobRequestConditions-Duration-Context + Map metadata = Collections.singletonMap("metadata", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context("Key", "Value"); + + System.out.printf("Set metadata completed with status %d%n", + client.setMetadataWithResponse(metadata, requestConditions, timeout, context).getStatusCode()); + // END: com.azure.storage.blob.BlobContainerClient.setMetadataWithResponse#Map-BlobRequestConditions-Duration-Context + } + + /** + * Code snippet for {@link BlobContainerClient#getAccessPolicy()} + */ + public void getAccessPolicy() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.getAccessPolicy + BlobContainerAccessPolicies accessPolicies = client.getAccessPolicy(); + System.out.printf("Blob Access Type: %s%n", accessPolicies.getBlobAccessType()); + + for (BlobSignedIdentifier identifier : accessPolicies.getIdentifiers()) { + System.out.printf("Identifier Name: %s, Permissions %s%n", + identifier.getId(), + identifier.getAccessPolicy().getPermissions()); + } + // END: com.azure.storage.blob.BlobContainerClient.getAccessPolicy + } + + /** + * Code snippet for {@link BlobContainerClient#getAccessPolicyWithResponse(String, Duration, Context)} + */ + public void getAccessPolicy2() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.getAccessPolicyWithResponse#String-Duration-Context + Context context = new Context("Key", "Value"); + BlobContainerAccessPolicies accessPolicies = client.getAccessPolicyWithResponse(leaseId, timeout, context) + .getValue(); + System.out.printf("Blob Access Type: %s%n", accessPolicies.getBlobAccessType()); + + for (BlobSignedIdentifier identifier : accessPolicies.getIdentifiers()) { + System.out.printf("Identifier Name: %s, Permissions %s%n", + identifier.getId(), + identifier.getAccessPolicy().getPermissions()); + } + // END: com.azure.storage.blob.BlobContainerClient.getAccessPolicyWithResponse#String-Duration-Context + } + + /** + * Code snippet for {@link BlobContainerClient#setAccessPolicy(PublicAccessType, List)} + */ + public void setAccessPolicy() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.setAccessPolicy#PublicAccessType-List + BlobSignedIdentifier identifier = new BlobSignedIdentifier() + .setId("name") + .setAccessPolicy(new BlobAccessPolicy() + .setStartsOn(OffsetDateTime.now()) + .setExpiresOn(OffsetDateTime.now().plusDays(7)) + .setPermissions("permissionString")); + + try { + client.setAccessPolicy(PublicAccessType.CONTAINER, Collections.singletonList(identifier)); + System.out.printf("Set Access Policy completed %n"); + } catch (UnsupportedOperationException error) { + System.out.printf("Set Access Policy completed %s%n", error); + } + // END: com.azure.storage.blob.BlobContainerClient.setAccessPolicy#PublicAccessType-List + } + + /** + * Code snippet for {@link BlobContainerClient#setAccessPolicyWithResponse(PublicAccessType, List, + * BlobRequestConditions, Duration, Context)} + */ + public void setAccessPolicy2() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.setAccessPolicyWithResponse#PublicAccessType-List-BlobRequestConditions-Duration-Context + BlobSignedIdentifier identifier = new BlobSignedIdentifier() + .setId("name") + .setAccessPolicy(new BlobAccessPolicy() + .setStartsOn(OffsetDateTime.now()) + .setExpiresOn(OffsetDateTime.now().plusDays(7)) + .setPermissions("permissionString")); + + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + Context context = new Context("Key", "Value"); + + System.out.printf("Set access policy completed with status %d%n", + client.setAccessPolicyWithResponse(PublicAccessType.CONTAINER, + Collections.singletonList(identifier), + requestConditions, + timeout, + context).getStatusCode()); + // END: com.azure.storage.blob.BlobContainerClient.setAccessPolicyWithResponse#PublicAccessType-List-BlobRequestConditions-Duration-Context + } + + /** + * Code snippet for {@link BlobContainerClient#listBlobs()} + */ + public void listBlobsFlat() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.listBlobs + client.listBlobs().forEach(blob -> + System.out.printf("Name: %s, Directory? %b%n", blob.getName(), blob.isPrefix())); + // END: com.azure.storage.blob.BlobContainerClient.listBlobs + } + + /** + * Code snippet for {@link BlobContainerClient#listBlobs(ListBlobsOptions, Duration)} + */ + public void listBlobsFlat2() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.listBlobs#ListBlobsOptions-Duration + ListBlobsOptions options = new ListBlobsOptions() + .setPrefix("prefixToMatch") + .setDetails(new BlobListDetails() + .setRetrieveDeletedBlobs(true) + .setRetrieveSnapshots(true)); + + client.listBlobs(options, timeout).forEach(blob -> + System.out.printf("Name: %s, Directory? %b, Deleted? %b, Snapshot ID: %s%n", + blob.getName(), + blob.isPrefix(), + blob.isDeleted(), + blob.getSnapshot())); + // END: com.azure.storage.blob.BlobContainerClient.listBlobs#ListBlobsOptions-Duration + } + + /** + * Code snippet for {@link BlobContainerClient#listBlobs(ListBlobsOptions, String, Duration)} + */ + public void listBlobsFlat3() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.listBlobs#ListBlobsOptions-String-Duration + ListBlobsOptions options = new ListBlobsOptions() + .setPrefix("prefixToMatch") + .setDetails(new BlobListDetails() + .setRetrieveDeletedBlobs(true) + .setRetrieveSnapshots(true)); + + String continuationToken = "continuationToken"; + + client.listBlobs(options, continuationToken, timeout).forEach(blob -> + System.out.printf("Name: %s, Directory? %b, Deleted? %b, Snapshot ID: %s%n", + blob.getName(), + blob.isPrefix(), + blob.isDeleted(), + blob.getSnapshot())); + // END: com.azure.storage.blob.BlobContainerClient.listBlobs#ListBlobsOptions-String-Duration + } + + /** + * Code snippet for {@link BlobContainerClient#listBlobsByHierarchy(String)} + */ + public void listBlobsHierarchy() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.listBlobsByHierarchy#String + client.listBlobsByHierarchy("directoryName").forEach(blob -> + System.out.printf("Name: %s, Directory? %b%n", blob.getName(), blob.isPrefix())); + // END: com.azure.storage.blob.BlobContainerClient.listBlobsByHierarchy#String + } + + /** + * Code snippet for {@link BlobContainerClient#listBlobsByHierarchy(String, ListBlobsOptions, Duration)} + */ + public void listBlobsHierarchy2() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.listBlobsByHierarchy#String-ListBlobsOptions-Duration + ListBlobsOptions options = new ListBlobsOptions() + .setPrefix("directoryName") + .setDetails(new BlobListDetails() + .setRetrieveDeletedBlobs(true) + .setRetrieveSnapshots(false)); + + client.listBlobsByHierarchy("/", options, timeout).forEach(blob -> + System.out.printf("Name: %s, Directory? %b, Deleted? %b, Snapshot ID: %s%n", + blob.getName(), + blob.isPrefix(), + blob.isDeleted(), + blob.getSnapshot())); + // END: com.azure.storage.blob.BlobContainerClient.listBlobsByHierarchy#String-ListBlobsOptions-Duration + } + + /** + * Code snippets for {@link BlobContainerClient#findBlobsByTags(String)} and + * {@link BlobContainerClient#findBlobsByTags(FindBlobsOptions, Duration, Context)} + */ + public void findBlobsByTag() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.findBlobsByTag#String + client.findBlobsByTags("where=tag=value").forEach(blob -> System.out.printf("Name: %s%n", blob.getName())); + // END: com.azure.storage.blob.BlobContainerClient.findBlobsByTag#String + + // BEGIN: com.azure.storage.blob.BlobContainerClient.findBlobsByTag#FindBlobsOptions-Duration + Context context = new Context("Key", "Value"); + client.findBlobsByTags(new FindBlobsOptions("where=tag=value").setMaxResultsPerPage(10), timeout, context) + .forEach(blob -> System.out.printf("Name: %s%n", blob.getName())); + // END: com.azure.storage.blob.BlobContainerClient.findBlobsByTag#FindBlobsOptions-Duration + } + + /** + * Code snippet for {@link BlobContainerClient#getAccountInfo(Duration)} + */ + public void getAccountInfo() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.getAccountInfo#Duration + StorageAccountInfo accountInfo = client.getAccountInfo(timeout); + System.out.printf("Account Kind: %s, SKU: %s%n", accountInfo.getAccountKind(), accountInfo.getSkuName()); + // END: com.azure.storage.blob.BlobContainerClient.getAccountInfo#Duration + } + + /** + * Code snippet for {@link BlobContainerClient#getAccountInfoWithResponse(Duration, Context)} + */ + public void getAccountInfo2() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.getAccountInfoWithResponse#Duration-Context + Context context = new Context("Key", "Value"); + StorageAccountInfo accountInfo = client.getAccountInfoWithResponse(timeout, context).getValue(); + System.out.printf("Account Kind: %s, SKU: %s%n", accountInfo.getAccountKind(), accountInfo.getSkuName()); + // END: com.azure.storage.blob.BlobContainerClient.getAccountInfoWithResponse#Duration-Context + } + + /** + * Generates a code sample for using {@link BlobContainerClient#getBlobContainerName()} + */ + public void getContainerName() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.getBlobContainerName + String containerName = client.getBlobContainerName(); + System.out.println("The name of the blob is " + containerName); + // END: com.azure.storage.blob.BlobContainerClient.getBlobContainerName + } + + /** + * Code snippet for {@link BlobContainerClient#generateUserDelegationSas(BlobServiceSasSignatureValues, UserDelegationKey)} + * and {@link BlobContainerClient#generateSas(BlobServiceSasSignatureValues)} + */ + public void generateSas() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.generateSas#BlobServiceSasSignatureValues + OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1); + BlobContainerSasPermission permission = new BlobContainerSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues values = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + client.generateSas(values); // Client must be authenticated via StorageSharedKeyCredential + // END: com.azure.storage.blob.BlobContainerClient.generateSas#BlobServiceSasSignatureValues + + // BEGIN: com.azure.storage.blob.BlobContainerClient.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey + OffsetDateTime myExpiryTime = OffsetDateTime.now().plusDays(1); + BlobContainerSasPermission myPermission = new BlobContainerSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues myValues = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + client.generateUserDelegationSas(values, userDelegationKey); + // END: com.azure.storage.blob.BlobContainerClient.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey + } + + /** + * Code snippet for {@link BlobContainerClient#generateUserDelegationSas(BlobServiceSasSignatureValues, UserDelegationKey, String, Context)} + * and {@link BlobContainerClient#generateSas(BlobServiceSasSignatureValues, Context)} + */ + public void generateSasWithContext() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.generateSas#BlobServiceSasSignatureValues-Context + OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1); + BlobContainerSasPermission permission = new BlobContainerSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues values = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + // Client must be authenticated via StorageSharedKeyCredential + client.generateSas(values, new Context("key", "value")); + // END: com.azure.storage.blob.BlobContainerClient.generateSas#BlobServiceSasSignatureValues-Context + + // BEGIN: com.azure.storage.blob.BlobContainerClient.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey-String-Context + OffsetDateTime myExpiryTime = OffsetDateTime.now().plusDays(1); + BlobContainerSasPermission myPermission = new BlobContainerSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues myValues = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + client.generateUserDelegationSas(values, userDelegationKey, accountName, new Context("key", "value")); + // END: com.azure.storage.blob.BlobContainerClient.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey-String-Context + } + + /** + * Code snippet for {@link BlobContainerClient#createIfNotExists()} and + * {@link BlobContainerClient#createIfNotExistsWithResponse(BlobContainerCreateOptions, Duration, Context)} + */ + public void createIfNotExistsCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.createIfNotExists + boolean result = client.createIfNotExists(); + System.out.println("Create completed: " + result); + // END: com.azure.storage.blob.BlobContainerClient.createIfNotExists + + // BEGIN: com.azure.storage.blob.BlobContainerClient.createIfNotExistsWithResponse#BlobContainerCreateOptions-Duration-Context + Map metadata = Collections.singletonMap("metadata", "value"); + Context context = new Context("Key", "Value"); + BlobContainerCreateOptions options = new BlobContainerCreateOptions().setMetadata(metadata) + .setPublicAccessType(PublicAccessType.CONTAINER); + + Response response = client.createIfNotExistsWithResponse(options, timeout, context); + if (response.getStatusCode() == 409) { + System.out.println("Already existed."); + } else { + System.out.printf("Create completed with status %d%n", response.getStatusCode()); + } + // END: com.azure.storage.blob.BlobContainerClient.createIfNotExistsWithResponse#BlobContainerCreateOptions-Duration-Context + } + + /** + * Code snippet for {@link BlobContainerClient#deleteIfExists()} and + * {@link BlobContainerClient#deleteIfExistsWithResponse(BlobRequestConditions, Duration, Context)} + */ + public void deleteIfExistsCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.deleteIfExists + boolean result = client.deleteIfExists(); + System.out.println("Delete completed: " + result); + // END: com.azure.storage.blob.BlobContainerClient.deleteIfExists + + // BEGIN: com.azure.storage.blob.BlobContainerClient.deleteIfExistsWithResponse#BlobRequestConditions-Duration-Context + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context("Key", "Value"); + + Response response = client.deleteIfExistsWithResponse(requestConditions, timeout, context); + if (response.getStatusCode() == 404) { + System.out.println("Does not exist."); + } else { + System.out.printf("Delete completed with status %d%n", response.getStatusCode()); + } + // END: com.azure.storage.blob.BlobContainerClient.deleteIfExistsWithResponse#BlobRequestConditions-Duration-Context + } + +// /** +// * Code snippet for {@link BlobContainerClient#rename(String)} +// */ +// public void renameContainer() { +// // BEGIN: com.azure.storage.blob.BlobContainerClient.rename#String +// BlobContainerClient blobContainerClient = client.rename("newContainerName"); +// // END: com.azure.storage.blob.BlobContainerClient.rename#String +// } +// +// /** +// * Code snippet for {@link BlobContainerClient#renameWithResponse(BlobContainerRenameOptions, Duration, Context)} +// */ +// public void renameContainerWithResponse() { +// // BEGIN: com.azure.storage.blob.BlobContainerClient.renameWithResponse#BlobContainerRenameOptions-Duration-Context +// BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId("lease-id"); +// Context context = new Context("Key", "Value"); +// +// BlobContainerClient blobContainerClient = client.renameWithResponse( +// new BlobContainerRenameOptions("newContainerName") +// .setRequestConditions(requestConditions), +// Duration.ofSeconds(1), +// context).getValue(); +// // END: com.azure.storage.blob.BlobContainerClient.renameWithResponse#BlobContainerRenameOptions-Duration-Context +// } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample11/v2/BlobContainerClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample11/v2/BlobContainerClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..6ea36fcd0d41 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample11/v2/BlobContainerClientJavaDocCodeSnippets.java @@ -0,0 +1,537 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.storage.blob.models.BlobAccessPolicy; +import com.azure.storage.blob.models.BlobContainerAccessPolicies; +import com.azure.storage.blob.models.BlobContainerProperties; +import com.azure.storage.blob.models.BlobErrorCode; +import com.azure.storage.blob.models.BlobListDetails; +import com.azure.storage.blob.models.BlobRequestConditions; +import com.azure.storage.blob.models.BlobSignedIdentifier; +import com.azure.storage.blob.models.BlobStorageException; +import com.azure.storage.blob.models.ListBlobsOptions; +import com.azure.storage.blob.models.PublicAccessType; +import com.azure.storage.blob.models.StorageAccountInfo; +import com.azure.storage.blob.models.UserDelegationKey; +import com.azure.storage.blob.options.BlobContainerCreateOptions; +import com.azure.storage.blob.options.FindBlobsOptions; +import com.azure.storage.blob.sas.BlobContainerSasPermission; +import com.azure.storage.blob.sas.BlobServiceSasSignatureValues; + +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +@SuppressWarnings({"unused"}) +public class BlobContainerClientJavaDocCodeSnippets { + + private BlobContainerClient client = JavaDocCodeSnippetsHelpers.getContainerClient(); + private String blobName = "blobName"; + private String snapshot = "snapshot"; + private String leaseId = "leaseId"; + private String proposedId = "proposedId"; + private int leaseDuration = (int) Duration.ofSeconds(30).getSeconds(); + private Duration timeout = Duration.ofSeconds(30); + private String accountName = "accountName"; + private UserDelegationKey userDelegationKey = JavaDocCodeSnippetsHelpers.getUserDelegationKey(); + + /** + * Code snippet for {@link BlobContainerClient#getBlobClient(String)} + */ + public void getBlobClient() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.getBlobClient#String + BlobClient blobClient = client.getBlobClient(blobName); + // END: com.azure.storage.blob.BlobContainerClient.getBlobClient#String + } + + /** + * Code snippet for {@link BlobContainerClient#getBlobClient(String, String)} + */ + public void getSnapshotBlobClient() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.getBlobClient#String-String + BlobClient blobClient = client.getBlobClient(blobName, snapshot); + // END: com.azure.storage.blob.BlobContainerClient.getBlobClient#String-String + } + + /** + * Code snippets for {@link BlobContainerClient#exists()} and {@link BlobContainerClient#existsWithResponse(Duration, + * Context)} + */ + public void exists() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.exists + System.out.printf("Exists? %b%n", client.exists()); + // END: com.azure.storage.blob.BlobContainerClient.exists + + // BEGIN: com.azure.storage.blob.BlobContainerClient.existsWithResponse#Duration-Context + Context context = new Context("Key", "Value"); + System.out.printf("Exists? %b%n", client.existsWithResponse(timeout, context).getValue()); + // END: com.azure.storage.blob.BlobContainerClient.existsWithResponse#Duration-Context + } + + /** + * Code snippet for {@link BlobContainerClient#create()} + */ + public void setCreate() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.create + try { + client.create(); + System.out.printf("Create completed%n"); + } catch (BlobStorageException error) { + if (error.getErrorCode().equals(BlobErrorCode.CONTAINER_ALREADY_EXISTS)) { + System.out.printf("Can't create container. It already exists %n"); + } + } + // END: com.azure.storage.blob.BlobContainerClient.create + } + + /** + * Code snippet for {@link BlobContainerClient#createWithResponse(Map, PublicAccessType, Duration, Context)} + */ + public void create2() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.createWithResponse#Map-PublicAccessType-Duration-Context + Map metadata = Collections.singletonMap("metadata", "value"); + Context context = new Context("Key", "Value"); + + System.out.printf("Create completed with status %d%n", + client.createWithResponse(metadata, PublicAccessType.CONTAINER, timeout, context).getStatusCode()); + // END: com.azure.storage.blob.BlobContainerClient.createWithResponse#Map-PublicAccessType-Duration-Context + } + + /** + * Code snippet for {@link BlobContainerClient#delete()} + */ + public void setDelete() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.delete + try { + client.delete(); + System.out.printf("Delete completed%n"); + } catch (BlobStorageException error) { + if (error.getErrorCode().equals(BlobErrorCode.CONTAINER_NOT_FOUND)) { + System.out.printf("Delete failed. Container was not found %n"); + } + } + // END: com.azure.storage.blob.BlobContainerClient.delete + } + + /** + * Code snippet for {@link BlobContainerClient#deleteWithResponse(BlobRequestConditions, Duration, Context)} + */ + public void delete2() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.deleteWithResponse#BlobRequestConditions-Duration-Context + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context("Key", "Value"); + + System.out.printf("Delete completed with status %d%n", client.deleteWithResponse( + requestConditions, timeout, context).getStatusCode()); + // END: com.azure.storage.blob.BlobContainerClient.deleteWithResponse#BlobRequestConditions-Duration-Context + } + + /** + * Code snippet for {@link BlobContainerClient#getProperties()} + */ + public void getProperties() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.getProperties + BlobContainerProperties properties = client.getProperties(); + System.out.printf("Public Access Type: %s, Legal Hold? %b, Immutable? %b%n", + properties.getBlobPublicAccess(), + properties.hasLegalHold(), + properties.hasImmutabilityPolicy()); + // END: com.azure.storage.blob.BlobContainerClient.getProperties + } + + /** + * Code snippet for {@link BlobContainerClient#getPropertiesWithResponse(String, Duration, Context)} + */ + public void getProperties2() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.getPropertiesWithResponse#String-Duration-Context + Context context = new Context("Key", "Value"); + + BlobContainerProperties properties = client.getPropertiesWithResponse(leaseId, timeout, context) + .getValue(); + System.out.printf("Public Access Type: %s, Legal Hold? %b, Immutable? %b%n", + properties.getBlobPublicAccess(), + properties.hasLegalHold(), + properties.hasImmutabilityPolicy()); + // END: com.azure.storage.blob.BlobContainerClient.getPropertiesWithResponse#String-Duration-Context + } + + /** + * Code snippet for {@link BlobContainerClient#setMetadata(Map)} + */ + public void setMetadata() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.setMetadata#Map + Map metadata = Collections.singletonMap("metadata", "value"); + try { + client.setMetadata(metadata); + System.out.printf("Set metadata completed with status %n"); + } catch (UnsupportedOperationException error) { + System.out.printf("Fail while setting metadata %n"); + } + // END: com.azure.storage.blob.BlobContainerClient.setMetadata#Map + } + + /** + * Code snippet for {@link BlobContainerClient#setMetadataWithResponse(Map, BlobRequestConditions, Duration, + * Context)} + */ + public void setMetadata2() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.setMetadataWithResponse#Map-BlobRequestConditions-Duration-Context + Map metadata = Collections.singletonMap("metadata", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context("Key", "Value"); + + System.out.printf("Set metadata completed with status %d%n", + client.setMetadataWithResponse(metadata, requestConditions, timeout, context).getStatusCode()); + // END: com.azure.storage.blob.BlobContainerClient.setMetadataWithResponse#Map-BlobRequestConditions-Duration-Context + } + + /** + * Code snippet for {@link BlobContainerClient#getAccessPolicy()} + */ + public void getAccessPolicy() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.getAccessPolicy + BlobContainerAccessPolicies accessPolicies = client.getAccessPolicy(); + System.out.printf("Blob Access Type: %s%n", accessPolicies.getBlobAccessType()); + + for (BlobSignedIdentifier identifier : accessPolicies.getIdentifiers()) { + System.out.printf("Identifier Name: %s, Permissions %s%n", + identifier.getId(), + identifier.getAccessPolicy().getPermissions()); + } + // END: com.azure.storage.blob.BlobContainerClient.getAccessPolicy + } + + /** + * Code snippet for {@link BlobContainerClient#getAccessPolicyWithResponse(String, Duration, Context)} + */ + public void getAccessPolicy2() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.getAccessPolicyWithResponse#String-Duration-Context + Context context = new Context("Key", "Value"); + BlobContainerAccessPolicies accessPolicies = client.getAccessPolicyWithResponse(leaseId, timeout, context) + .getValue(); + System.out.printf("Blob Access Type: %s%n", accessPolicies.getBlobAccessType()); + + for (BlobSignedIdentifier identifier : accessPolicies.getIdentifiers()) { + System.out.printf("Identifier Name: %s, Permissions %s%n", + identifier.getId(), + identifier.getAccessPolicy().getPermissions()); + } + // END: com.azure.storage.blob.BlobContainerClient.getAccessPolicyWithResponse#String-Duration-Context + } + + /** + * Code snippet for {@link BlobContainerClient#setAccessPolicy(PublicAccessType, List)} + */ + public void setAccessPolicy() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.setAccessPolicy#PublicAccessType-List + BlobSignedIdentifier identifier = new BlobSignedIdentifier() + .setId("name") + .setAccessPolicy(new BlobAccessPolicy() + .setStartsOn(OffsetDateTime.now()) + .setExpiresOn(OffsetDateTime.now().plusDays(7)) + .setPermissions("permissionString")); + + try { + client.setAccessPolicy(PublicAccessType.CONTAINER, Collections.singletonList(identifier)); + System.out.printf("Set Access Policy completed %n"); + } catch (UnsupportedOperationException error) { + System.out.printf("Set Access Policy completed %s%n", error); + } + // END: com.azure.storage.blob.BlobContainerClient.setAccessPolicy#PublicAccessType-List + } + + /** + * Code snippet for {@link BlobContainerClient#setAccessPolicyWithResponse(PublicAccessType, List, + * BlobRequestConditions, Duration, Context)} + */ + public void setAccessPolicy2() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.setAccessPolicyWithResponse#PublicAccessType-List-BlobRequestConditions-Duration-Context + BlobSignedIdentifier identifier = new BlobSignedIdentifier() + .setId("name") + .setAccessPolicy(new BlobAccessPolicy() + .setStartsOn(OffsetDateTime.now()) + .setExpiresOn(OffsetDateTime.now().plusDays(7)) + .setPermissions("permissionString")); + + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + Context context = new Context("Key", "Value"); + + System.out.printf("Set access policy completed with status %d%n", + client.setAccessPolicyWithResponse(PublicAccessType.CONTAINER, + Collections.singletonList(identifier), + requestConditions, + timeout, + context).getStatusCode()); + // END: com.azure.storage.blob.BlobContainerClient.setAccessPolicyWithResponse#PublicAccessType-List-BlobRequestConditions-Duration-Context + } + + /** + * Code snippet for {@link BlobContainerClient#listBlobs()} + */ + public void listBlobsFlat() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.listBlobs + client.listBlobs().forEach(blob -> + System.out.printf("Name: %s, Directory? %b%n", blob.getName(), blob.isPrefix())); + // END: com.azure.storage.blob.BlobContainerClient.listBlobs + } + + /** + * Code snippet for {@link BlobContainerClient#listBlobs(ListBlobsOptions, Duration)} + */ + public void listBlobsFlat2() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.listBlobs#ListBlobsOptions-Duration + ListBlobsOptions options = new ListBlobsOptions() + .setPrefix("prefixToMatch") + .setDetails(new BlobListDetails() + .setRetrieveDeletedBlobs(true) + .setRetrieveSnapshots(true)); + + client.listBlobs(options, timeout).forEach(blob -> + System.out.printf("Name: %s, Directory? %b, Deleted? %b, Snapshot ID: %s%n", + blob.getName(), + blob.isPrefix(), + blob.isDeleted(), + blob.getSnapshot())); + // END: com.azure.storage.blob.BlobContainerClient.listBlobs#ListBlobsOptions-Duration + } + + /** + * Code snippet for {@link BlobContainerClient#listBlobs(ListBlobsOptions, String, Duration)} + */ + public void listBlobsFlat3() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.listBlobs#ListBlobsOptions-String-Duration + ListBlobsOptions options = new ListBlobsOptions() + .setPrefix("prefixToMatch") + .setDetails(new BlobListDetails() + .setRetrieveDeletedBlobs(true) + .setRetrieveSnapshots(true)); + + String continuationToken = "continuationToken"; + + client.listBlobs(options, continuationToken, timeout).forEach(blob -> + System.out.printf("Name: %s, Directory? %b, Deleted? %b, Snapshot ID: %s%n", + blob.getName(), + blob.isPrefix(), + blob.isDeleted(), + blob.getSnapshot())); + // END: com.azure.storage.blob.BlobContainerClient.listBlobs#ListBlobsOptions-String-Duration + } + + /** + * Code snippet for {@link BlobContainerClient#listBlobsByHierarchy(String)} + */ + public void listBlobsHierarchy() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.listBlobsByHierarchy#String + client.listBlobsByHierarchy("directoryName").forEach(blob -> + System.out.printf("Name: %s, Directory? %b%n", blob.getName(), blob.isPrefix())); + // END: com.azure.storage.blob.BlobContainerClient.listBlobsByHierarchy#String + } + + /** + * Code snippet for {@link BlobContainerClient#listBlobsByHierarchy(String, ListBlobsOptions, Duration)} + */ + public void listBlobsHierarchy2() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.listBlobsByHierarchy#String-ListBlobsOptions-Duration + ListBlobsOptions options = new ListBlobsOptions() + .setPrefix("directoryName") + .setDetails(new BlobListDetails() + .setRetrieveDeletedBlobs(true) + .setRetrieveSnapshots(false)); + + client.listBlobsByHierarchy("/", options, timeout).forEach(blob -> + System.out.printf("Name: %s, Directory? %b, Deleted? %b, Snapshot ID: %s%n", + blob.getName(), + blob.isPrefix(), + blob.isDeleted(), + blob.getSnapshot())); + // END: com.azure.storage.blob.BlobContainerClient.listBlobsByHierarchy#String-ListBlobsOptions-Duration + } + + /** + * Code snippets for {@link BlobContainerClient#findBlobsByTags(String)} and + * {@link BlobContainerClient#findBlobsByTags(FindBlobsOptions, Duration, Context)} + */ + public void findBlobsByTag() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.findBlobsByTag#String + client.findBlobsByTags("where=tag=value").forEach(blob -> System.out.printf("Name: %s%n", blob.getName())); + // END: com.azure.storage.blob.BlobContainerClient.findBlobsByTag#String + + // BEGIN: com.azure.storage.blob.BlobContainerClient.findBlobsByTag#FindBlobsOptions-Duration + Context context = new Context("Key", "Value"); + client.findBlobsByTags(new FindBlobsOptions("where=tag=value").setMaxResultsPerPage(10), timeout, context) + .forEach(blob -> System.out.printf("Name: %s%n", blob.getName())); + // END: com.azure.storage.blob.BlobContainerClient.findBlobsByTag#FindBlobsOptions-Duration + } + + /** + * Code snippet for {@link BlobContainerClient#getAccountInfo(Duration)} + */ + public void getAccountInfo() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.getAccountInfo#Duration + StorageAccountInfo accountInfo = client.getAccountInfo(timeout); + System.out.printf("Account Kind: %s, SKU: %s%n", accountInfo.getAccountKind(), accountInfo.getSkuName()); + // END: com.azure.storage.blob.BlobContainerClient.getAccountInfo#Duration + } + + /** + * Code snippet for {@link BlobContainerClient#getAccountInfoWithResponse(Duration, Context)} + */ + public void getAccountInfo2() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.getAccountInfoWithResponse#Duration-Context + Context context = new Context("Key", "Value"); + StorageAccountInfo accountInfo = client.getAccountInfoWithResponse(timeout, context).getValue(); + System.out.printf("Account Kind: %s, SKU: %s%n", accountInfo.getAccountKind(), accountInfo.getSkuName()); + // END: com.azure.storage.blob.BlobContainerClient.getAccountInfoWithResponse#Duration-Context + } + + /** + * Generates a code sample for using {@link BlobContainerClient#getBlobContainerName()} + */ + public void getContainerName() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.getBlobContainerName + String containerName = client.getBlobContainerName(); + System.out.println("The name of the blob is " + containerName); + // END: com.azure.storage.blob.BlobContainerClient.getBlobContainerName + } + + /** + * Code snippet for {@link BlobContainerClient#generateUserDelegationSas(BlobServiceSasSignatureValues, UserDelegationKey)} + * and {@link BlobContainerClient#generateSas(BlobServiceSasSignatureValues)} + */ + public void generateSas() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.generateSas#BlobServiceSasSignatureValues + OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1); + BlobContainerSasPermission permission = new BlobContainerSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues values = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + client.generateSas(values); // Client must be authenticated via StorageSharedKeyCredential + // END: com.azure.storage.blob.BlobContainerClient.generateSas#BlobServiceSasSignatureValues + + // BEGIN: com.azure.storage.blob.BlobContainerClient.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey + OffsetDateTime myExpiryTime = OffsetDateTime.now().plusDays(1); + BlobContainerSasPermission myPermission = new BlobContainerSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues myValues = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + client.generateUserDelegationSas(values, userDelegationKey); + // END: com.azure.storage.blob.BlobContainerClient.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey + } + + /** + * Code snippet for {@link BlobContainerClient#generateUserDelegationSas(BlobServiceSasSignatureValues, UserDelegationKey, String, Context)} + * and {@link BlobContainerClient#generateSas(BlobServiceSasSignatureValues, Context)} + */ + public void generateSasWithContext() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.generateSas#BlobServiceSasSignatureValues-Context + OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1); + BlobContainerSasPermission permission = new BlobContainerSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues values = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + // Client must be authenticated via StorageSharedKeyCredential + client.generateSas(values, new Context("key", "value")); + // END: com.azure.storage.blob.BlobContainerClient.generateSas#BlobServiceSasSignatureValues-Context + + // BEGIN: com.azure.storage.blob.BlobContainerClient.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey-String-Context + OffsetDateTime myExpiryTime = OffsetDateTime.now().plusDays(1); + BlobContainerSasPermission myPermission = new BlobContainerSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues myValues = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + client.generateUserDelegationSas(values, userDelegationKey, accountName, new Context("key", "value")); + // END: com.azure.storage.blob.BlobContainerClient.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey-String-Context + } + + /** + * Code snippet for {@link BlobContainerClient#createIfNotExists()} and + * {@link BlobContainerClient#createIfNotExistsWithResponse(BlobContainerCreateOptions, Duration, Context)} + */ + public void createIfNotExistsCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.createIfNotExists + boolean result = client.createIfNotExists(); + System.out.println("Create completed: " + result); + // END: com.azure.storage.blob.BlobContainerClient.createIfNotExists + + // BEGIN: com.azure.storage.blob.BlobContainerClient.createIfNotExistsWithResponse#BlobContainerCreateOptions-Duration-Context + Map metadata = Collections.singletonMap("metadata", "value"); + Context context = new Context("Key", "Value"); + BlobContainerCreateOptions options = new BlobContainerCreateOptions().setMetadata(metadata) + .setPublicAccessType(PublicAccessType.CONTAINER); + + Response response = client.createIfNotExistsWithResponse(options, timeout, context); + if (response.getStatusCode() == 409) { + System.out.println("Already existed."); + } else { + System.out.printf("Create completed with status %d%n", response.getStatusCode()); + } + // END: com.azure.storage.blob.BlobContainerClient.createIfNotExistsWithResponse#BlobContainerCreateOptions-Duration-Context + } + + /** + * Code snippet for {@link BlobContainerClient#deleteIfExists()} and + * {@link BlobContainerClient#deleteIfExistsWithResponse(BlobRequestConditions, Duration, Context)} + */ + public void deleteIfExistsCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobContainerClient.deleteIfExists + boolean result = client.deleteIfExists(); + System.out.println("Delete completed: " + result); + // END: com.azure.storage.blob.BlobContainerClient.deleteIfExists + + // BEGIN: com.azure.storage.blob.BlobContainerClient.deleteIfExistsWithResponse#BlobRequestConditions-Duration-Context + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context("Key", "Value"); + + Response response = client.deleteIfExistsWithResponse(requestConditions, timeout, context); + if (response.getStatusCode() == 404) { + System.out.println("Does not exist."); + } else { + System.out.printf("Delete completed with status %d%n", response.getStatusCode()); + } + // END: com.azure.storage.blob.BlobContainerClient.deleteIfExistsWithResponse#BlobRequestConditions-Duration-Context + } + +// /** +// * Code snippet for {@link BlobContainerClient#rename(String)} +// */ +// public void renameContainer() { +// // BEGIN: com.azure.storage.blob.BlobContainerClient.rename#String +// BlobContainerClient blobContainerClient = client.rename("newContainerName"); +// // END: com.azure.storage.blob.BlobContainerClient.rename#String +// } +// +// /** +// * Code snippet for {@link BlobContainerClient#renameWithResponse(BlobContainerRenameOptions, Duration, Context)} +// */ +// public void renameContainerWithResponse() { +// // BEGIN: com.azure.storage.blob.BlobContainerClient.renameWithResponse#BlobContainerRenameOptions-Duration-Context +// BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId("lease-id"); +// Context context = new Context("Key", "Value"); +// +// BlobContainerClient blobContainerClient = client.renameWithResponse( +// new BlobContainerRenameOptions("newContainerName") +// .setRequestConditions(requestConditions), +// Duration.ofSeconds(1), +// context).getValue(); +// // END: com.azure.storage.blob.BlobContainerClient.renameWithResponse#BlobContainerRenameOptions-Duration-Context +// } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample12/v1/BlobServiceAsyncClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample12/v1/BlobServiceAsyncClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..6c8c2cb02e50 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample12/v1/BlobServiceAsyncClientJavaDocCodeSnippets.java @@ -0,0 +1,416 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.storage.blob.models.BlobAnalyticsLogging; +import com.azure.storage.blob.models.BlobContainerListDetails; +import com.azure.storage.blob.models.BlobMetrics; +import com.azure.storage.blob.models.BlobRetentionPolicy; +import com.azure.storage.blob.models.BlobServiceProperties; +import com.azure.storage.blob.models.ListBlobContainersOptions; +import com.azure.storage.blob.models.PublicAccessType; +import com.azure.storage.blob.options.BlobContainerCreateOptions; +import com.azure.storage.blob.options.FindBlobsOptions; +import com.azure.storage.blob.options.UndeleteBlobContainerOptions; +import com.azure.storage.common.sas.AccountSasPermission; +import com.azure.storage.common.sas.AccountSasResourceType; +import com.azure.storage.common.sas.AccountSasService; +import com.azure.storage.common.sas.AccountSasSignatureValues; +import reactor.core.publisher.Mono; + +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Collections; +import java.util.Map; + +/** + * Code snippets for {@link BlobServiceAsyncClient} + */ +@SuppressWarnings({"unused"}) +public class BlobServiceAsyncClientJavaDocCodeSnippets { + + private BlobServiceAsyncClient client = JavaDocCodeSnippetsHelpers.getBlobServiceAsyncClient(); + + /** + * Code snippet for {@link BlobServiceAsyncClient#getBlobContainerAsyncClient(String)} + */ + public void getContainerClient() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.getBlobContainerAsyncClient#String + BlobContainerAsyncClient blobContainerAsyncClient = client.getBlobContainerAsyncClient("containerName"); + // END: com.azure.storage.blob.BlobServiceAsyncClient.getBlobContainerAsyncClient#String + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#createBlobContainer(String)} + */ + public void createContainer() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainer#String + BlobContainerAsyncClient blobContainerAsyncClient = + client.createBlobContainer("containerName").block(); + // END: com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainer#String + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#createBlobContainerWithResponse(String, Map, PublicAccessType)} + */ + public void createContainerWithResponse() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainerWithResponse#String-Map-PublicAccessType + Map metadata = Collections.singletonMap("metadata", "value"); + + BlobContainerAsyncClient containerClient = client + .createBlobContainerWithResponse("containerName", metadata, PublicAccessType.CONTAINER).block().getValue(); + // END: com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainerWithResponse#String-Map-PublicAccessType + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#deleteBlobContainer(String)} + */ + public void deleteContainer() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainer#String + client.deleteBlobContainer("containerName").subscribe( + response -> System.out.printf("Delete container completed%n"), + error -> System.out.printf("Delete container failed: %s%n", error)); + // END: com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainer#String + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#deleteBlobContainerWithResponse(String, Context)} + */ + public void deleteContainerWithResponse() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainerWithResponse#String-Context + Context context = new Context("Key", "Value"); + client.deleteBlobContainerWithResponse("containerName").subscribe(response -> + System.out.printf("Delete container completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainerWithResponse#String-Context + } + + /** + * Code snippets for {@link BlobServiceAsyncClient#listBlobContainers()} and + * {@link BlobServiceAsyncClient#listBlobContainers(ListBlobContainersOptions)} + */ + public void listContainers() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.listBlobContainers + client.listBlobContainers().subscribe(container -> System.out.printf("Name: %s%n", container.getName())); + // END: com.azure.storage.blob.BlobServiceAsyncClient.listBlobContainers + + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.listBlobContainers#ListBlobContainersOptions + ListBlobContainersOptions options = new ListBlobContainersOptions() + .setPrefix("containerNamePrefixToMatch") + .setDetails(new BlobContainerListDetails().setRetrieveMetadata(true)); + + client.listBlobContainers(options).subscribe(container -> System.out.printf("Name: %s%n", container.getName())); + // END: com.azure.storage.blob.BlobServiceAsyncClient.listBlobContainers#ListBlobContainersOptions + } + + /** + * Code snippets for {@link BlobServiceAsyncClient#findBlobsByTags(String)} and + * {@link BlobServiceAsyncClient#findBlobsByTags(FindBlobsOptions)} + */ + public void findBlobsByTag() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.findBlobsByTag#String + client.findBlobsByTags("where=tag=value").subscribe(blob -> System.out.printf("Name: %s%n", blob.getName())); + // END: com.azure.storage.blob.BlobServiceAsyncClient.findBlobsByTag#String + + // BEGIN: com.azure.storage.blob.BlobAsyncServiceClient.findBlobsByTag#FindBlobsOptions + client.findBlobsByTags(new FindBlobsOptions("where=tag=value").setMaxResultsPerPage(10)) + .subscribe(blob -> System.out.printf("Name: %s%n", blob.getName())); + // END: com.azure.storage.blob.BlobAsyncServiceClient.findBlobsByTag#FindBlobsOptions + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#getProperties()} + */ + public void getProperties() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.getProperties + client.getProperties().subscribe(response -> + System.out.printf("Hour metrics enabled: %b, Minute metrics enabled: %b%n", + response.getHourMetrics().isEnabled(), + response.getMinuteMetrics().isEnabled())); + // END: com.azure.storage.blob.BlobServiceAsyncClient.getProperties + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#getPropertiesWithResponse()} + */ + public void getPropertiesWithResponse() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.getPropertiesWithResponse + client.getPropertiesWithResponse().subscribe(response -> + System.out.printf("Hour metrics enabled: %b, Minute metrics enabled: %b%n", + response.getValue().getHourMetrics().isEnabled(), + response.getValue().getMinuteMetrics().isEnabled())); + // END: com.azure.storage.blob.BlobServiceAsyncClient.getPropertiesWithResponse + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#setProperties(BlobServiceProperties)} + */ + public void setProperties() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.setProperties#BlobServiceProperties + BlobRetentionPolicy loggingRetentionPolicy = new BlobRetentionPolicy().setEnabled(true).setDays(3); + BlobRetentionPolicy metricsRetentionPolicy = new BlobRetentionPolicy().setEnabled(true).setDays(1); + + BlobServiceProperties properties = new BlobServiceProperties() + .setLogging(new BlobAnalyticsLogging() + .setWrite(true) + .setDelete(true) + .setRetentionPolicy(loggingRetentionPolicy)) + .setHourMetrics(new BlobMetrics() + .setEnabled(true) + .setRetentionPolicy(metricsRetentionPolicy)) + .setMinuteMetrics(new BlobMetrics() + .setEnabled(true) + .setRetentionPolicy(metricsRetentionPolicy)); + + client.setProperties(properties).subscribe( + response -> System.out.printf("Setting properties completed%n"), + error -> System.out.printf("Setting properties failed: %s%n", error)); + // END: com.azure.storage.blob.BlobServiceAsyncClient.setProperties#BlobServiceProperties + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#setPropertiesWithResponse(BlobServiceProperties)} + */ + public void setPropertiesWithResponse() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.setPropertiesWithResponse#BlobServiceProperties + BlobRetentionPolicy loggingRetentionPolicy = new BlobRetentionPolicy().setEnabled(true).setDays(3); + BlobRetentionPolicy metricsRetentionPolicy = new BlobRetentionPolicy().setEnabled(true).setDays(1); + + BlobServiceProperties properties = new BlobServiceProperties() + .setLogging(new BlobAnalyticsLogging() + .setWrite(true) + .setDelete(true) + .setRetentionPolicy(loggingRetentionPolicy)) + .setHourMetrics(new BlobMetrics() + .setEnabled(true) + .setRetentionPolicy(metricsRetentionPolicy)) + .setMinuteMetrics(new BlobMetrics() + .setEnabled(true) + .setRetentionPolicy(metricsRetentionPolicy)); + + client.setPropertiesWithResponse(properties).subscribe(response -> + System.out.printf("Setting properties completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.BlobServiceAsyncClient.setPropertiesWithResponse#BlobServiceProperties + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#getUserDelegationKey(OffsetDateTime, OffsetDateTime)} + */ + public void getUserDelegationKey() { + OffsetDateTime delegationKeyStartTime = OffsetDateTime.now(); + OffsetDateTime delegationKeyExpiryTime = OffsetDateTime.now().plusDays(7); + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.getUserDelegationKey#OffsetDateTime-OffsetDateTime + client.getUserDelegationKey(delegationKeyStartTime, delegationKeyExpiryTime).subscribe(response -> + System.out.printf("User delegation key: %s%n", response.getValue())); + // END: com.azure.storage.blob.BlobServiceAsyncClient.getUserDelegationKey#OffsetDateTime-OffsetDateTime + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#getUserDelegationKeyWithResponse(OffsetDateTime, OffsetDateTime)} + */ + public void getUserDelegationKeyWithResponse() { + OffsetDateTime delegationKeyStartTime = OffsetDateTime.now(); + OffsetDateTime delegationKeyExpiryTime = OffsetDateTime.now().plusDays(7); + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.getUserDelegationKeyWithResponse#OffsetDateTime-OffsetDateTime + client.getUserDelegationKeyWithResponse(delegationKeyStartTime, delegationKeyExpiryTime).subscribe(response -> + System.out.printf("User delegation key: %s%n", response.getValue().getValue())); + // END: com.azure.storage.blob.BlobServiceAsyncClient.getUserDelegationKeyWithResponse#OffsetDateTime-OffsetDateTime + } + + /** + * Code snippets for {@link BlobServiceAsyncClient#getStatistics()} + */ + public void getStatistics() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.getStatistics + client.getStatistics().subscribe(response -> + System.out.printf("Geo-replication status: %s%n", response.getGeoReplication().getStatus())); + // END: com.azure.storage.blob.BlobServiceAsyncClient.getStatistics + } + + /** + * Code snippets for {@link BlobServiceAsyncClient#getStatisticsWithResponse()} + */ + public void getStatisticsWithResponse() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.getStatisticsWithResponse + client.getStatisticsWithResponse().subscribe(response -> + System.out.printf("Geo-replication status: %s%n", response.getValue().getGeoReplication().getStatus())); + // END: com.azure.storage.blob.BlobServiceAsyncClient.getStatisticsWithResponse + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#getAccountInfo} + */ + public void getAccountInfo() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.getAccountInfo + client.getAccountInfo().subscribe(response -> + System.out.printf("Account kind: %s, SKU: %s%n", response.getAccountKind(), response.getSkuName())); + // END: com.azure.storage.blob.BlobServiceAsyncClient.getAccountInfo + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#getAccountInfoWithResponse} + */ + public void getAccountInfoWithResponse() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.getAccountInfoWithResponse + client.getAccountInfoWithResponse().subscribe(response -> + System.out.printf("Account kind: %s, SKU: %s%n", response.getValue().getAccountKind(), + response.getValue().getSkuName())); + // END: com.azure.storage.blob.BlobServiceAsyncClient.getAccountInfoWithResponse + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#generateAccountSas(AccountSasSignatureValues)} + */ + public void generateAccountSas() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.generateAccountSas#AccountSasSignatureValues + AccountSasPermission permissions = new AccountSasPermission() + .setListPermission(true) + .setReadPermission(true); + AccountSasResourceType resourceTypes = new AccountSasResourceType().setContainer(true); + AccountSasService services = new AccountSasService().setBlobAccess(true).setFileAccess(true); + OffsetDateTime expiryTime = OffsetDateTime.now().plus(Duration.ofDays(2)); + + AccountSasSignatureValues sasValues = + new AccountSasSignatureValues(expiryTime, permissions, services, resourceTypes); + + // Client must be authenticated via StorageSharedKeyCredential + String sas = client.generateAccountSas(sasValues); + // END: com.azure.storage.blob.BlobServiceAsyncClient.generateAccountSas#AccountSasSignatureValues + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#generateAccountSas(AccountSasSignatureValues, Context)} + */ + public void generateAccountSasWithContext() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.generateAccountSas#AccountSasSignatureValues-Context + AccountSasPermission permissions = new AccountSasPermission() + .setListPermission(true) + .setReadPermission(true); + AccountSasResourceType resourceTypes = new AccountSasResourceType().setContainer(true); + AccountSasService services = new AccountSasService().setBlobAccess(true).setFileAccess(true); + OffsetDateTime expiryTime = OffsetDateTime.now().plus(Duration.ofDays(2)); + + AccountSasSignatureValues sasValues = + new AccountSasSignatureValues(expiryTime, permissions, services, resourceTypes); + + // Client must be authenticated via StorageSharedKeyCredential + String sas = client.generateAccountSas(sasValues, new Context("key", "value")); + // END: com.azure.storage.blob.BlobServiceAsyncClient.generateAccountSas#AccountSasSignatureValues-Context + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#undeleteBlobContainer(String, String)}. + */ + public void undeleteBlobContainer() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.undeleteBlobContainer#String-String + ListBlobContainersOptions listBlobContainersOptions = new ListBlobContainersOptions(); + listBlobContainersOptions.getDetails().setRetrieveDeleted(true); + client.listBlobContainers(listBlobContainersOptions).flatMap( + deletedContainer -> { + Mono blobContainerClient = client.undeleteBlobContainer( + deletedContainer.getName(), deletedContainer.getVersion()); + return blobContainerClient; + } + ).then().block(); + // END: com.azure.storage.blob.BlobServiceAsyncClient.undeleteBlobContainer#String-String + } + + /** + * Code snippet for + * {@link BlobServiceAsyncClient#undeleteBlobContainerWithResponse(UndeleteBlobContainerOptions)}. + */ + public void undeleteBlobContainerWithResponseWithRename() { + Context context = new Context("Key", "Value"); + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.undeleteBlobContainerWithResponse#UndeleteBlobContainerOptions + ListBlobContainersOptions listBlobContainersOptions = new ListBlobContainersOptions(); + listBlobContainersOptions.getDetails().setRetrieveDeleted(true); + client.listBlobContainers(listBlobContainersOptions).flatMap( + deletedContainer -> { + Mono blobContainerClient = client.undeleteBlobContainerWithResponse( + new UndeleteBlobContainerOptions(deletedContainer.getName(), deletedContainer.getVersion())) + .map(Response::getValue); + return blobContainerClient; + } + ).then().block(); + // END: com.azure.storage.blob.BlobServiceAsyncClient.undeleteBlobContainerWithResponse#UndeleteBlobContainerOptions + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#createBlobContainerIfNotExists(String)} and + * {@link BlobServiceAsyncClient#createBlobContainerIfNotExistsWithResponse(String, BlobContainerCreateOptions)} + */ + public void createContainerIfNotExistsCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainerIfNotExists#String + BlobContainerAsyncClient blobContainerAsyncClient = + client.createBlobContainerIfNotExists("containerName").block(); + // END: com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainerIfNotExists#String + + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainerIfNotExistsWithResponse#String-BlobContainerCreateOptions + Map metadata = Collections.singletonMap("metadata", "value"); + BlobContainerCreateOptions options = new BlobContainerCreateOptions().setMetadata(metadata) + .setPublicAccessType(PublicAccessType.CONTAINER); + + client.createBlobContainerIfNotExistsWithResponse("containerName", options).subscribe(response -> { + if (response.getStatusCode() == 409) { + System.out.println("Already exists."); + } else { + System.out.println("successfully created."); + } + }); + // END: com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainerIfNotExistsWithResponse#String-BlobContainerCreateOptions + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#deleteBlobContainerIfExists(String)} and + * {@link BlobServiceAsyncClient#deleteBlobContainerIfExistsWithResponse(String)} + */ + public void deleteContainerIfExistsCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainerIfExists#String + client.deleteBlobContainerIfExists("containerName").subscribe(deleted -> { + if (deleted) { + System.out.println("Successfully deleted."); + } else { + System.out.println("Does not exist."); + } + }); + // END: com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainerIfExists#String + + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainerIfExistsWithResponse#String + Context context = new Context("Key", "Value"); + client.deleteBlobContainerIfExistsWithResponse("containerName").subscribe(response -> { + if (response.getStatusCode() == 404) { + System.out.println("Does not exist."); + } else { + System.out.println("successfully deleted."); + } + }); + // END: com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainerIfExistsWithResponse#String + } + + +// /** +// * Code snippet for {@link BlobServiceAsyncClient#renameBlobContainer(String, String)} +// */ +// public void renameContainer() { +// // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.renameBlobContainer#String-String +// BlobContainerAsyncClient blobContainerAsyncClient = +// client.renameBlobContainer("oldContainerName", "newContainerName") +// .block(); +// // END: com.azure.storage.blob.BlobServiceAsyncClient.renameBlobContainer#String-String +// } +// +// /** +// * Code snippet for {@link BlobServiceAsyncClient#renameBlobContainerWithResponse(String, BlobContainerRenameOptions)} +// */ +// public void renameContainerWithResponse() { +// // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.renameBlobContainerWithResponse#String-BlobContainerRenameOptions +// BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId("lease-id"); +// BlobContainerAsyncClient containerClient = client +// .renameBlobContainerWithResponse("oldContainerName", +// new BlobContainerRenameOptions( "newContainerName") +// .setRequestConditions(requestConditions)).block().getValue(); +// // END: com.azure.storage.blob.BlobServiceAsyncClient.renameBlobContainerWithResponse#String-BlobContainerRenameOptions +// } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample12/v2/BlobServiceAsyncClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample12/v2/BlobServiceAsyncClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..6c8c2cb02e50 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample12/v2/BlobServiceAsyncClientJavaDocCodeSnippets.java @@ -0,0 +1,416 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.storage.blob.models.BlobAnalyticsLogging; +import com.azure.storage.blob.models.BlobContainerListDetails; +import com.azure.storage.blob.models.BlobMetrics; +import com.azure.storage.blob.models.BlobRetentionPolicy; +import com.azure.storage.blob.models.BlobServiceProperties; +import com.azure.storage.blob.models.ListBlobContainersOptions; +import com.azure.storage.blob.models.PublicAccessType; +import com.azure.storage.blob.options.BlobContainerCreateOptions; +import com.azure.storage.blob.options.FindBlobsOptions; +import com.azure.storage.blob.options.UndeleteBlobContainerOptions; +import com.azure.storage.common.sas.AccountSasPermission; +import com.azure.storage.common.sas.AccountSasResourceType; +import com.azure.storage.common.sas.AccountSasService; +import com.azure.storage.common.sas.AccountSasSignatureValues; +import reactor.core.publisher.Mono; + +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Collections; +import java.util.Map; + +/** + * Code snippets for {@link BlobServiceAsyncClient} + */ +@SuppressWarnings({"unused"}) +public class BlobServiceAsyncClientJavaDocCodeSnippets { + + private BlobServiceAsyncClient client = JavaDocCodeSnippetsHelpers.getBlobServiceAsyncClient(); + + /** + * Code snippet for {@link BlobServiceAsyncClient#getBlobContainerAsyncClient(String)} + */ + public void getContainerClient() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.getBlobContainerAsyncClient#String + BlobContainerAsyncClient blobContainerAsyncClient = client.getBlobContainerAsyncClient("containerName"); + // END: com.azure.storage.blob.BlobServiceAsyncClient.getBlobContainerAsyncClient#String + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#createBlobContainer(String)} + */ + public void createContainer() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainer#String + BlobContainerAsyncClient blobContainerAsyncClient = + client.createBlobContainer("containerName").block(); + // END: com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainer#String + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#createBlobContainerWithResponse(String, Map, PublicAccessType)} + */ + public void createContainerWithResponse() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainerWithResponse#String-Map-PublicAccessType + Map metadata = Collections.singletonMap("metadata", "value"); + + BlobContainerAsyncClient containerClient = client + .createBlobContainerWithResponse("containerName", metadata, PublicAccessType.CONTAINER).block().getValue(); + // END: com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainerWithResponse#String-Map-PublicAccessType + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#deleteBlobContainer(String)} + */ + public void deleteContainer() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainer#String + client.deleteBlobContainer("containerName").subscribe( + response -> System.out.printf("Delete container completed%n"), + error -> System.out.printf("Delete container failed: %s%n", error)); + // END: com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainer#String + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#deleteBlobContainerWithResponse(String, Context)} + */ + public void deleteContainerWithResponse() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainerWithResponse#String-Context + Context context = new Context("Key", "Value"); + client.deleteBlobContainerWithResponse("containerName").subscribe(response -> + System.out.printf("Delete container completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainerWithResponse#String-Context + } + + /** + * Code snippets for {@link BlobServiceAsyncClient#listBlobContainers()} and + * {@link BlobServiceAsyncClient#listBlobContainers(ListBlobContainersOptions)} + */ + public void listContainers() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.listBlobContainers + client.listBlobContainers().subscribe(container -> System.out.printf("Name: %s%n", container.getName())); + // END: com.azure.storage.blob.BlobServiceAsyncClient.listBlobContainers + + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.listBlobContainers#ListBlobContainersOptions + ListBlobContainersOptions options = new ListBlobContainersOptions() + .setPrefix("containerNamePrefixToMatch") + .setDetails(new BlobContainerListDetails().setRetrieveMetadata(true)); + + client.listBlobContainers(options).subscribe(container -> System.out.printf("Name: %s%n", container.getName())); + // END: com.azure.storage.blob.BlobServiceAsyncClient.listBlobContainers#ListBlobContainersOptions + } + + /** + * Code snippets for {@link BlobServiceAsyncClient#findBlobsByTags(String)} and + * {@link BlobServiceAsyncClient#findBlobsByTags(FindBlobsOptions)} + */ + public void findBlobsByTag() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.findBlobsByTag#String + client.findBlobsByTags("where=tag=value").subscribe(blob -> System.out.printf("Name: %s%n", blob.getName())); + // END: com.azure.storage.blob.BlobServiceAsyncClient.findBlobsByTag#String + + // BEGIN: com.azure.storage.blob.BlobAsyncServiceClient.findBlobsByTag#FindBlobsOptions + client.findBlobsByTags(new FindBlobsOptions("where=tag=value").setMaxResultsPerPage(10)) + .subscribe(blob -> System.out.printf("Name: %s%n", blob.getName())); + // END: com.azure.storage.blob.BlobAsyncServiceClient.findBlobsByTag#FindBlobsOptions + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#getProperties()} + */ + public void getProperties() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.getProperties + client.getProperties().subscribe(response -> + System.out.printf("Hour metrics enabled: %b, Minute metrics enabled: %b%n", + response.getHourMetrics().isEnabled(), + response.getMinuteMetrics().isEnabled())); + // END: com.azure.storage.blob.BlobServiceAsyncClient.getProperties + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#getPropertiesWithResponse()} + */ + public void getPropertiesWithResponse() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.getPropertiesWithResponse + client.getPropertiesWithResponse().subscribe(response -> + System.out.printf("Hour metrics enabled: %b, Minute metrics enabled: %b%n", + response.getValue().getHourMetrics().isEnabled(), + response.getValue().getMinuteMetrics().isEnabled())); + // END: com.azure.storage.blob.BlobServiceAsyncClient.getPropertiesWithResponse + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#setProperties(BlobServiceProperties)} + */ + public void setProperties() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.setProperties#BlobServiceProperties + BlobRetentionPolicy loggingRetentionPolicy = new BlobRetentionPolicy().setEnabled(true).setDays(3); + BlobRetentionPolicy metricsRetentionPolicy = new BlobRetentionPolicy().setEnabled(true).setDays(1); + + BlobServiceProperties properties = new BlobServiceProperties() + .setLogging(new BlobAnalyticsLogging() + .setWrite(true) + .setDelete(true) + .setRetentionPolicy(loggingRetentionPolicy)) + .setHourMetrics(new BlobMetrics() + .setEnabled(true) + .setRetentionPolicy(metricsRetentionPolicy)) + .setMinuteMetrics(new BlobMetrics() + .setEnabled(true) + .setRetentionPolicy(metricsRetentionPolicy)); + + client.setProperties(properties).subscribe( + response -> System.out.printf("Setting properties completed%n"), + error -> System.out.printf("Setting properties failed: %s%n", error)); + // END: com.azure.storage.blob.BlobServiceAsyncClient.setProperties#BlobServiceProperties + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#setPropertiesWithResponse(BlobServiceProperties)} + */ + public void setPropertiesWithResponse() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.setPropertiesWithResponse#BlobServiceProperties + BlobRetentionPolicy loggingRetentionPolicy = new BlobRetentionPolicy().setEnabled(true).setDays(3); + BlobRetentionPolicy metricsRetentionPolicy = new BlobRetentionPolicy().setEnabled(true).setDays(1); + + BlobServiceProperties properties = new BlobServiceProperties() + .setLogging(new BlobAnalyticsLogging() + .setWrite(true) + .setDelete(true) + .setRetentionPolicy(loggingRetentionPolicy)) + .setHourMetrics(new BlobMetrics() + .setEnabled(true) + .setRetentionPolicy(metricsRetentionPolicy)) + .setMinuteMetrics(new BlobMetrics() + .setEnabled(true) + .setRetentionPolicy(metricsRetentionPolicy)); + + client.setPropertiesWithResponse(properties).subscribe(response -> + System.out.printf("Setting properties completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.BlobServiceAsyncClient.setPropertiesWithResponse#BlobServiceProperties + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#getUserDelegationKey(OffsetDateTime, OffsetDateTime)} + */ + public void getUserDelegationKey() { + OffsetDateTime delegationKeyStartTime = OffsetDateTime.now(); + OffsetDateTime delegationKeyExpiryTime = OffsetDateTime.now().plusDays(7); + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.getUserDelegationKey#OffsetDateTime-OffsetDateTime + client.getUserDelegationKey(delegationKeyStartTime, delegationKeyExpiryTime).subscribe(response -> + System.out.printf("User delegation key: %s%n", response.getValue())); + // END: com.azure.storage.blob.BlobServiceAsyncClient.getUserDelegationKey#OffsetDateTime-OffsetDateTime + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#getUserDelegationKeyWithResponse(OffsetDateTime, OffsetDateTime)} + */ + public void getUserDelegationKeyWithResponse() { + OffsetDateTime delegationKeyStartTime = OffsetDateTime.now(); + OffsetDateTime delegationKeyExpiryTime = OffsetDateTime.now().plusDays(7); + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.getUserDelegationKeyWithResponse#OffsetDateTime-OffsetDateTime + client.getUserDelegationKeyWithResponse(delegationKeyStartTime, delegationKeyExpiryTime).subscribe(response -> + System.out.printf("User delegation key: %s%n", response.getValue().getValue())); + // END: com.azure.storage.blob.BlobServiceAsyncClient.getUserDelegationKeyWithResponse#OffsetDateTime-OffsetDateTime + } + + /** + * Code snippets for {@link BlobServiceAsyncClient#getStatistics()} + */ + public void getStatistics() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.getStatistics + client.getStatistics().subscribe(response -> + System.out.printf("Geo-replication status: %s%n", response.getGeoReplication().getStatus())); + // END: com.azure.storage.blob.BlobServiceAsyncClient.getStatistics + } + + /** + * Code snippets for {@link BlobServiceAsyncClient#getStatisticsWithResponse()} + */ + public void getStatisticsWithResponse() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.getStatisticsWithResponse + client.getStatisticsWithResponse().subscribe(response -> + System.out.printf("Geo-replication status: %s%n", response.getValue().getGeoReplication().getStatus())); + // END: com.azure.storage.blob.BlobServiceAsyncClient.getStatisticsWithResponse + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#getAccountInfo} + */ + public void getAccountInfo() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.getAccountInfo + client.getAccountInfo().subscribe(response -> + System.out.printf("Account kind: %s, SKU: %s%n", response.getAccountKind(), response.getSkuName())); + // END: com.azure.storage.blob.BlobServiceAsyncClient.getAccountInfo + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#getAccountInfoWithResponse} + */ + public void getAccountInfoWithResponse() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.getAccountInfoWithResponse + client.getAccountInfoWithResponse().subscribe(response -> + System.out.printf("Account kind: %s, SKU: %s%n", response.getValue().getAccountKind(), + response.getValue().getSkuName())); + // END: com.azure.storage.blob.BlobServiceAsyncClient.getAccountInfoWithResponse + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#generateAccountSas(AccountSasSignatureValues)} + */ + public void generateAccountSas() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.generateAccountSas#AccountSasSignatureValues + AccountSasPermission permissions = new AccountSasPermission() + .setListPermission(true) + .setReadPermission(true); + AccountSasResourceType resourceTypes = new AccountSasResourceType().setContainer(true); + AccountSasService services = new AccountSasService().setBlobAccess(true).setFileAccess(true); + OffsetDateTime expiryTime = OffsetDateTime.now().plus(Duration.ofDays(2)); + + AccountSasSignatureValues sasValues = + new AccountSasSignatureValues(expiryTime, permissions, services, resourceTypes); + + // Client must be authenticated via StorageSharedKeyCredential + String sas = client.generateAccountSas(sasValues); + // END: com.azure.storage.blob.BlobServiceAsyncClient.generateAccountSas#AccountSasSignatureValues + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#generateAccountSas(AccountSasSignatureValues, Context)} + */ + public void generateAccountSasWithContext() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.generateAccountSas#AccountSasSignatureValues-Context + AccountSasPermission permissions = new AccountSasPermission() + .setListPermission(true) + .setReadPermission(true); + AccountSasResourceType resourceTypes = new AccountSasResourceType().setContainer(true); + AccountSasService services = new AccountSasService().setBlobAccess(true).setFileAccess(true); + OffsetDateTime expiryTime = OffsetDateTime.now().plus(Duration.ofDays(2)); + + AccountSasSignatureValues sasValues = + new AccountSasSignatureValues(expiryTime, permissions, services, resourceTypes); + + // Client must be authenticated via StorageSharedKeyCredential + String sas = client.generateAccountSas(sasValues, new Context("key", "value")); + // END: com.azure.storage.blob.BlobServiceAsyncClient.generateAccountSas#AccountSasSignatureValues-Context + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#undeleteBlobContainer(String, String)}. + */ + public void undeleteBlobContainer() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.undeleteBlobContainer#String-String + ListBlobContainersOptions listBlobContainersOptions = new ListBlobContainersOptions(); + listBlobContainersOptions.getDetails().setRetrieveDeleted(true); + client.listBlobContainers(listBlobContainersOptions).flatMap( + deletedContainer -> { + Mono blobContainerClient = client.undeleteBlobContainer( + deletedContainer.getName(), deletedContainer.getVersion()); + return blobContainerClient; + } + ).then().block(); + // END: com.azure.storage.blob.BlobServiceAsyncClient.undeleteBlobContainer#String-String + } + + /** + * Code snippet for + * {@link BlobServiceAsyncClient#undeleteBlobContainerWithResponse(UndeleteBlobContainerOptions)}. + */ + public void undeleteBlobContainerWithResponseWithRename() { + Context context = new Context("Key", "Value"); + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.undeleteBlobContainerWithResponse#UndeleteBlobContainerOptions + ListBlobContainersOptions listBlobContainersOptions = new ListBlobContainersOptions(); + listBlobContainersOptions.getDetails().setRetrieveDeleted(true); + client.listBlobContainers(listBlobContainersOptions).flatMap( + deletedContainer -> { + Mono blobContainerClient = client.undeleteBlobContainerWithResponse( + new UndeleteBlobContainerOptions(deletedContainer.getName(), deletedContainer.getVersion())) + .map(Response::getValue); + return blobContainerClient; + } + ).then().block(); + // END: com.azure.storage.blob.BlobServiceAsyncClient.undeleteBlobContainerWithResponse#UndeleteBlobContainerOptions + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#createBlobContainerIfNotExists(String)} and + * {@link BlobServiceAsyncClient#createBlobContainerIfNotExistsWithResponse(String, BlobContainerCreateOptions)} + */ + public void createContainerIfNotExistsCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainerIfNotExists#String + BlobContainerAsyncClient blobContainerAsyncClient = + client.createBlobContainerIfNotExists("containerName").block(); + // END: com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainerIfNotExists#String + + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainerIfNotExistsWithResponse#String-BlobContainerCreateOptions + Map metadata = Collections.singletonMap("metadata", "value"); + BlobContainerCreateOptions options = new BlobContainerCreateOptions().setMetadata(metadata) + .setPublicAccessType(PublicAccessType.CONTAINER); + + client.createBlobContainerIfNotExistsWithResponse("containerName", options).subscribe(response -> { + if (response.getStatusCode() == 409) { + System.out.println("Already exists."); + } else { + System.out.println("successfully created."); + } + }); + // END: com.azure.storage.blob.BlobServiceAsyncClient.createBlobContainerIfNotExistsWithResponse#String-BlobContainerCreateOptions + } + + /** + * Code snippet for {@link BlobServiceAsyncClient#deleteBlobContainerIfExists(String)} and + * {@link BlobServiceAsyncClient#deleteBlobContainerIfExistsWithResponse(String)} + */ + public void deleteContainerIfExistsCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainerIfExists#String + client.deleteBlobContainerIfExists("containerName").subscribe(deleted -> { + if (deleted) { + System.out.println("Successfully deleted."); + } else { + System.out.println("Does not exist."); + } + }); + // END: com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainerIfExists#String + + // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainerIfExistsWithResponse#String + Context context = new Context("Key", "Value"); + client.deleteBlobContainerIfExistsWithResponse("containerName").subscribe(response -> { + if (response.getStatusCode() == 404) { + System.out.println("Does not exist."); + } else { + System.out.println("successfully deleted."); + } + }); + // END: com.azure.storage.blob.BlobServiceAsyncClient.deleteBlobContainerIfExistsWithResponse#String + } + + +// /** +// * Code snippet for {@link BlobServiceAsyncClient#renameBlobContainer(String, String)} +// */ +// public void renameContainer() { +// // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.renameBlobContainer#String-String +// BlobContainerAsyncClient blobContainerAsyncClient = +// client.renameBlobContainer("oldContainerName", "newContainerName") +// .block(); +// // END: com.azure.storage.blob.BlobServiceAsyncClient.renameBlobContainer#String-String +// } +// +// /** +// * Code snippet for {@link BlobServiceAsyncClient#renameBlobContainerWithResponse(String, BlobContainerRenameOptions)} +// */ +// public void renameContainerWithResponse() { +// // BEGIN: com.azure.storage.blob.BlobServiceAsyncClient.renameBlobContainerWithResponse#String-BlobContainerRenameOptions +// BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId("lease-id"); +// BlobContainerAsyncClient containerClient = client +// .renameBlobContainerWithResponse("oldContainerName", +// new BlobContainerRenameOptions( "newContainerName") +// .setRequestConditions(requestConditions)).block().getValue(); +// // END: com.azure.storage.blob.BlobServiceAsyncClient.renameBlobContainerWithResponse#String-BlobContainerRenameOptions +// } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample13/v1/BlobServiceClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample13/v1/BlobServiceClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..9b43827363d4 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample13/v1/BlobServiceClientJavaDocCodeSnippets.java @@ -0,0 +1,426 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.storage.blob.models.BlobAnalyticsLogging; +import com.azure.storage.blob.models.BlobContainerListDetails; +import com.azure.storage.blob.models.BlobMetrics; +import com.azure.storage.blob.models.BlobRetentionPolicy; +import com.azure.storage.blob.models.BlobServiceProperties; +import com.azure.storage.blob.models.ListBlobContainersOptions; +import com.azure.storage.blob.models.PublicAccessType; +import com.azure.storage.blob.models.StorageAccountInfo; +import com.azure.storage.blob.options.BlobContainerCreateOptions; +import com.azure.storage.blob.options.FindBlobsOptions; +import com.azure.storage.blob.options.UndeleteBlobContainerOptions; +import com.azure.storage.common.sas.AccountSasPermission; +import com.azure.storage.common.sas.AccountSasResourceType; +import com.azure.storage.common.sas.AccountSasService; +import com.azure.storage.common.sas.AccountSasSignatureValues; + +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Collections; +import java.util.Map; + +/** + * Code snippets for {@link BlobServiceClient} + */ +@SuppressWarnings({"unused"}) +public class BlobServiceClientJavaDocCodeSnippets { + private final BlobServiceClient client = JavaDocCodeSnippetsHelpers.getBlobServiceClient(); + private final Duration timeout = Duration.ofSeconds(30); + + /** + * Code snippet for {@link BlobServiceClient#getBlobContainerClient(String)} + */ + public void getContainerClient() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.getBlobContainerClient#String + BlobContainerClient blobContainerClient = client.getBlobContainerClient("containerName"); + // END: com.azure.storage.blob.BlobServiceClient.getBlobContainerClient#String + } + + /** + * Code snippet for {@link BlobServiceClient#createBlobContainer(String)} + */ + public void createContainer() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.createBlobContainer#String + BlobContainerClient blobContainerClient = client.createBlobContainer("containerName"); + // END: com.azure.storage.blob.BlobServiceClient.createBlobContainer#String + } + + /** + * Code snippet for {@link BlobServiceClient#createBlobContainerWithResponse(String, Map, PublicAccessType, Context)} + */ + public void createContainerWithResponse() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.createBlobContainerWithResponse#String-Map-PublicAccessType-Context + Map metadata = Collections.singletonMap("metadata", "value"); + Context context = new Context("Key", "Value"); + + BlobContainerClient blobContainerClient = client.createBlobContainerWithResponse( + "containerName", + metadata, + PublicAccessType.CONTAINER, + context).getValue(); + // END: com.azure.storage.blob.BlobServiceClient.createBlobContainerWithResponse#String-Map-PublicAccessType-Context + } + + /** + * Code snippet for {@link BlobServiceClient#deleteBlobContainer(String)} + */ + public void deleteContainer() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.deleteBlobContainer#String + try { + client.deleteBlobContainer("container Name"); + System.out.printf("Delete container completed with status %n"); + } catch (UnsupportedOperationException error) { + System.out.printf("Delete container failed: %s%n", error); + } + // END: com.azure.storage.blob.BlobServiceClient.deleteBlobContainer#String + } + + /** + * Code snippet for {@link BlobServiceClient#deleteBlobContainerWithResponse(String, Context)} + */ + public void deleteContainerWithResponse() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.deleteBlobContainerWithResponse#String-Context + Context context = new Context("Key", "Value"); + System.out.printf("Delete container completed with status %d%n", + client.deleteBlobContainerWithResponse("containerName", context).getStatusCode()); + // END: com.azure.storage.blob.BlobServiceClient.deleteBlobContainerWithResponse#String-Context + } + + /** + * Code snippets for {@link BlobServiceClient#listBlobContainers()} and + * {@link BlobServiceClient#listBlobContainers(ListBlobContainersOptions, Duration)} + */ + public void listContainers() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.listBlobContainers + client.listBlobContainers().forEach(container -> System.out.printf("Name: %s%n", container.getName())); + // END: com.azure.storage.blob.BlobServiceClient.listBlobContainers + + // BEGIN: com.azure.storage.blob.BlobServiceClient.listBlobContainers#ListBlobContainersOptions-Duration + ListBlobContainersOptions options = new ListBlobContainersOptions() + .setPrefix("containerNamePrefixToMatch") + .setDetails(new BlobContainerListDetails().setRetrieveMetadata(true)); + + client.listBlobContainers(options, timeout).forEach(container -> System.out.printf("Name: %s%n", container.getName())); + // END: com.azure.storage.blob.BlobServiceClient.listBlobContainers#ListBlobContainersOptions-Duration + } + + /** + * Code snippets for {@link BlobServiceClient#findBlobsByTags(String)} and + * {@link BlobServiceClient#findBlobsByTags(FindBlobsOptions, Duration, Context)} + */ + public void findBlobsByTag() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.findBlobsByTag#String + client.findBlobsByTags("where=tag=value").forEach(blob -> System.out.printf("Name: %s%n", blob.getName())); + // END: com.azure.storage.blob.BlobServiceClient.findBlobsByTag#String + + // BEGIN: com.azure.storage.blob.BlobServiceClient.findBlobsByTag#FindBlobsOptions-Duration + Context context = new Context("Key", "Value"); + client.findBlobsByTags(new FindBlobsOptions("where=tag=value").setMaxResultsPerPage(10), timeout, context) + .forEach(blob -> System.out.printf("Name: %s%n", blob.getName())); + // END: com.azure.storage.blob.BlobServiceClient.findBlobsByTag#FindBlobsOptions-Duration + } + + /** + * Code snippet for {@link BlobServiceClient#getProperties()} + */ + public void getProperties() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.getProperties + BlobServiceProperties properties = client.getProperties(); + + System.out.printf("Hour metrics enabled: %b, Minute metrics enabled: %b%n", + properties.getHourMetrics().isEnabled(), + properties.getMinuteMetrics().isEnabled()); + // END: com.azure.storage.blob.BlobServiceClient.getProperties + } + + /** + * Code snippet for {@link BlobServiceClient#getPropertiesWithResponse(Duration, Context)} + */ + public void getPropertiesWithResponse() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.getPropertiesWithResponse#Duration-Context + Context context = new Context("Key", "Value"); + BlobServiceProperties properties = client.getPropertiesWithResponse(timeout, context).getValue(); + + System.out.printf("Hour metrics enabled: %b, Minute metrics enabled: %b%n", + properties.getHourMetrics().isEnabled(), + properties.getMinuteMetrics().isEnabled()); + // END: com.azure.storage.blob.BlobServiceClient.getPropertiesWithResponse#Duration-Context + } + + /** + * Code snippet for {@link BlobServiceClient#setProperties(BlobServiceProperties)} + */ + public void setProperties() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.setProperties#BlobServiceProperties + BlobRetentionPolicy loggingRetentionPolicy = new BlobRetentionPolicy().setEnabled(true).setDays(3); + BlobRetentionPolicy metricsRetentionPolicy = new BlobRetentionPolicy().setEnabled(true).setDays(1); + + BlobServiceProperties properties = new BlobServiceProperties() + .setLogging(new BlobAnalyticsLogging() + .setWrite(true) + .setDelete(true) + .setVersion("1.0") + .setRetentionPolicy(loggingRetentionPolicy)) + .setHourMetrics(new BlobMetrics() + .setEnabled(true) + .setVersion("1.0") + .setIncludeApis(true) + .setRetentionPolicy(metricsRetentionPolicy)) + .setMinuteMetrics(new BlobMetrics() + .setEnabled(true) + .setVersion("1.0") + .setIncludeApis(true) + .setRetentionPolicy(metricsRetentionPolicy)); + + try { + client.setProperties(properties); + System.out.printf("Setting properties completed%n"); + } catch (UnsupportedOperationException error) { + System.out.printf("Setting properties failed: %s%n", error); + } + // END: com.azure.storage.blob.BlobServiceClient.setProperties#BlobServiceProperties + } + + /** + * Code snippet for {@link BlobServiceClient#setPropertiesWithResponse(BlobServiceProperties, Duration, Context)} + */ + public void setPropertiesWithResponse() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.setPropertiesWithResponse#BlobServiceProperties-Duration-Context + BlobRetentionPolicy loggingRetentionPolicy = new BlobRetentionPolicy().setEnabled(true).setDays(3); + BlobRetentionPolicy metricsRetentionPolicy = new BlobRetentionPolicy().setEnabled(true).setDays(1); + + BlobServiceProperties properties = new BlobServiceProperties() + .setLogging(new BlobAnalyticsLogging() + .setWrite(true) + .setDelete(true) + .setVersion("1.0") + .setRetentionPolicy(loggingRetentionPolicy)) + .setHourMetrics(new BlobMetrics() + .setEnabled(true) + .setVersion("1.0") + .setIncludeApis(true) + .setRetentionPolicy(metricsRetentionPolicy)) + .setMinuteMetrics(new BlobMetrics() + .setEnabled(true) + .setVersion("1.0") + .setIncludeApis(true) + .setRetentionPolicy(metricsRetentionPolicy)); + + Context context = new Context("Key", "Value"); + + System.out.printf("Setting properties completed with status %d%n", + client.setPropertiesWithResponse(properties, timeout, context).getStatusCode()); + // END: com.azure.storage.blob.BlobServiceClient.setPropertiesWithResponse#BlobServiceProperties-Duration-Context + } + + /** + * Code snippets for {@link BlobServiceClient#getUserDelegationKey(OffsetDateTime, OffsetDateTime)} + * and {@link BlobServiceClient#getUserDelegationKeyWithResponse(OffsetDateTime, OffsetDateTime, Duration, Context)} + */ + public void getUserDelegationKey() { + OffsetDateTime delegationKeyStartTime = OffsetDateTime.now(); + OffsetDateTime delegationKeyExpiryTime = OffsetDateTime.now().plusDays(7); + Context context = new Context("Key", "Value"); + // BEGIN: com.azure.storage.blob.BlobServiceClient.getUserDelegationKey#OffsetDateTime-OffsetDateTime + System.out.printf("User delegation key: %s%n", + client.getUserDelegationKey(delegationKeyStartTime, delegationKeyExpiryTime)); + // END: com.azure.storage.blob.BlobServiceClient.getUserDelegationKey#OffsetDateTime-OffsetDateTime + + // BEGIN: com.azure.storage.blob.BlobServiceClient.getUserDelegationKeyWithResponse#OffsetDateTime-OffsetDateTime-Duration-Context + System.out.printf("User delegation key: %s%n", + client.getUserDelegationKeyWithResponse(delegationKeyStartTime, delegationKeyExpiryTime, timeout, context)); + // END: com.azure.storage.blob.BlobServiceClient.getUserDelegationKeyWithResponse#OffsetDateTime-OffsetDateTime-Duration-Context + } + + /** + * Code snippets for {@link BlobServiceClient#getStatistics()} and {@link BlobServiceClient#getStatisticsWithResponse(Duration, Context)} + */ + public void getStatistics() { + Context context = new Context("Key", "Value"); + // BEGIN: com.azure.storage.blob.BlobServiceClient.getStatistics + System.out.printf("Geo-replication status: %s%n", + client.getStatistics().getGeoReplication().getStatus()); + // END: com.azure.storage.blob.BlobServiceClient.getStatistics + + // BEGIN: com.azure.storage.blob.BlobServiceClient.getStatisticsWithResponse#Duration-Context + System.out.printf("Geo-replication status: %s%n", + client.getStatisticsWithResponse(timeout, context).getValue().getGeoReplication().getStatus()); + // END: com.azure.storage.blob.BlobServiceClient.getStatisticsWithResponse#Duration-Context + } + + /** + * Code snippet for {@link BlobServiceClient#getAccountInfo} + */ + public void getAccountInfo() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.getAccountInfo + StorageAccountInfo accountInfo = client.getAccountInfo(); + + System.out.printf("Account kind: %s, SKU: %s%n", accountInfo.getAccountKind(), accountInfo.getSkuName()); + // END: com.azure.storage.blob.BlobServiceClient.getAccountInfo + } + + /** + * Code snippet for {@link BlobServiceClient#getAccountInfoWithResponse(Duration, Context)} + */ + public void getAccountInfoWithResponse() { + Context context = new Context("Key", "Value"); + // BEGIN: com.azure.storage.blob.BlobServiceClient.getAccountInfoWithResponse#Duration-Context + StorageAccountInfo accountInfo = client.getAccountInfoWithResponse(timeout, context).getValue(); + // END: com.azure.storage.blob.BlobServiceClient.getAccountInfoWithResponse#Duration-Context + } + + /** + * Code snippet for {@link BlobServiceClient#generateAccountSas(AccountSasSignatureValues)} + */ + public void generateAccountSas() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.generateAccountSas#AccountSasSignatureValues + AccountSasPermission permissions = new AccountSasPermission() + .setListPermission(true) + .setReadPermission(true); + AccountSasResourceType resourceTypes = new AccountSasResourceType().setContainer(true); + AccountSasService services = new AccountSasService().setBlobAccess(true).setFileAccess(true); + OffsetDateTime expiryTime = OffsetDateTime.now().plus(Duration.ofDays(2)); + + AccountSasSignatureValues sasValues = + new AccountSasSignatureValues(expiryTime, permissions, services, resourceTypes); + + // Client must be authenticated via StorageSharedKeyCredential + String sas = client.generateAccountSas(sasValues); + // END: com.azure.storage.blob.BlobServiceClient.generateAccountSas#AccountSasSignatureValues + } + + /** + * Code snippet for {@link BlobServiceClient#generateAccountSas(AccountSasSignatureValues, Context)} + */ + public void generateAccountSasWithContext() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.generateAccountSas#AccountSasSignatureValues-Context + AccountSasPermission permissions = new AccountSasPermission() + .setListPermission(true) + .setReadPermission(true); + AccountSasResourceType resourceTypes = new AccountSasResourceType().setContainer(true); + AccountSasService services = new AccountSasService().setBlobAccess(true).setFileAccess(true); + OffsetDateTime expiryTime = OffsetDateTime.now().plus(Duration.ofDays(2)); + + AccountSasSignatureValues sasValues = + new AccountSasSignatureValues(expiryTime, permissions, services, resourceTypes); + + // Client must be authenticated via StorageSharedKeyCredential + String sas = client.generateAccountSas(sasValues, new Context("key", "value")); + // END: com.azure.storage.blob.BlobServiceClient.generateAccountSas#AccountSasSignatureValues-Context + } + + /** + * Code snippet for {@link BlobServiceClient#undeleteBlobContainer(String, String)}. + */ + public void undeleteBlobContainer() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.undeleteBlobContainer#String-String + ListBlobContainersOptions listBlobContainersOptions = new ListBlobContainersOptions(); + listBlobContainersOptions.getDetails().setRetrieveDeleted(true); + client.listBlobContainers(listBlobContainersOptions, null).forEach( + deletedContainer -> { + BlobContainerClient blobContainerClient = client.undeleteBlobContainer( + deletedContainer.getName(), deletedContainer.getVersion()); + } + ); + // END: com.azure.storage.blob.BlobServiceClient.undeleteBlobContainer#String-String + } + + /** + * Code snippet for {@link BlobServiceClient#undeleteBlobContainerWithResponse(UndeleteBlobContainerOptions, + * Duration, Context)}. + */ + public void undeleteBlobContainerWithResponseWithRename() { + Context context = new Context("Key", "Value"); + // BEGIN: com.azure.storage.blob.BlobServiceClient.undeleteBlobContainerWithResponse#UndeleteBlobContainerOptions-Duration-Context + ListBlobContainersOptions listBlobContainersOptions = new ListBlobContainersOptions(); + listBlobContainersOptions.getDetails().setRetrieveDeleted(true); + client.listBlobContainers(listBlobContainersOptions, null).forEach( + deletedContainer -> { + BlobContainerClient blobContainerClient = client.undeleteBlobContainerWithResponse( + new UndeleteBlobContainerOptions(deletedContainer.getName(), deletedContainer.getVersion()), + timeout, context).getValue(); + } + ); + // END: com.azure.storage.blob.BlobServiceClient.undeleteBlobContainerWithResponse#UndeleteBlobContainerOptions-Duration-Context + } + + /** + * Code snippet for {@link BlobServiceClient#createBlobContainerIfNotExists(String)} and + * {@link BlobServiceClient#createBlobContainerIfNotExistsWithResponse(String, BlobContainerCreateOptions, Context)} + */ + public void createContainerIfNotExistsCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.createBlobContainerIfNotExists#String + BlobContainerClient blobContainerClient = client.createBlobContainerIfNotExists("containerName"); + // END: com.azure.storage.blob.BlobServiceClient.createBlobContainerIfNotExists#String + + // BEGIN: com.azure.storage.blob.BlobServiceClient.createBlobContainerIfNotExistsWithResponse#String-BlobContainerCreateOptions-Context + Map metadata = Collections.singletonMap("metadata", "value"); + Context context = new Context("Key", "Value"); + BlobContainerCreateOptions options = new BlobContainerCreateOptions().setMetadata(metadata) + .setPublicAccessType(PublicAccessType.CONTAINER); + + Response response = client.createBlobContainerIfNotExistsWithResponse("containerName", + options, context); + + if (response.getStatusCode() == 409) { + System.out.println("Already existed."); + } else { + System.out.printf("Create completed with status %d%n", response.getStatusCode()); + } + // END: com.azure.storage.blob.BlobServiceClient.createBlobContainerIfNotExistsWithResponse#String-BlobContainerCreateOptions-Context + } + + /** + * Code snippet for {@link BlobServiceClient#deleteBlobContainerIfExists(String)} and + * {@link BlobServiceClient#deleteBlobContainerIfExistsWithResponse(String, Context)} + */ + public void deleteContainerIfExistsCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.deleteBlobContainerIfExists#String + boolean result = client.deleteBlobContainerIfExists("container Name"); + System.out.println("Delete container completed: " + result); + // END: com.azure.storage.blob.BlobServiceClient.deleteBlobContainerIfExists#String + + // BEGIN: com.azure.storage.blob.BlobServiceClient.deleteBlobContainerIfExistsWithResponse#String-Context + Context context = new Context("Key", "Value"); + + Response response = client.deleteBlobContainerIfExistsWithResponse("containerName", context); + if (response.getStatusCode() == 404) { + System.out.println("Does not exist."); + } else { + System.out.printf("Delete completed with status %d%n", response.getStatusCode()); + } + // END: com.azure.storage.blob.BlobServiceClient.deleteBlobContainerIfExistsWithResponse#String-Context + } + +// /** +// * Code snippet for {@link BlobServiceClient#renameBlobContainer(String, String)} +// */ +// public void renameContainer() { +// // BEGIN: com.azure.storage.blob.BlobServiceClient.renameBlobContainer#String-String +// BlobContainerClient blobContainerClient = client.renameBlobContainer("oldContainerName", "newContainerName"); +// // END: com.azure.storage.blob.BlobServiceClient.renameBlobContainer#String-String +// } +// +// /** +// * Code snippet for {@link BlobServiceClient#renameBlobContainerWithResponse(String, BlobContainerRenameOptions, Duration, Context)} +// */ +// public void renameContainerWithResponse() { +// // BEGIN: com.azure.storage.blob.BlobServiceClient.renameBlobContainerWithResponse#String-BlobContainerRenameOptions-Duration-Context +// BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId("lease-id"); +// Context context = new Context("Key", "Value"); +// +// BlobContainerClient blobContainerClient = client.renameBlobContainerWithResponse("oldContainerName", +// new BlobContainerRenameOptions("newContainerName") +// .setRequestConditions(requestConditions), +// Duration.ofSeconds(1), +// context).getValue(); +// // END: com.azure.storage.blob.BlobServiceClient.renameBlobContainerWithResponse#String-BlobContainerRenameOptions-Duration-Context +// } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample13/v2/BlobServiceClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample13/v2/BlobServiceClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..9b43827363d4 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample13/v2/BlobServiceClientJavaDocCodeSnippets.java @@ -0,0 +1,426 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.storage.blob.models.BlobAnalyticsLogging; +import com.azure.storage.blob.models.BlobContainerListDetails; +import com.azure.storage.blob.models.BlobMetrics; +import com.azure.storage.blob.models.BlobRetentionPolicy; +import com.azure.storage.blob.models.BlobServiceProperties; +import com.azure.storage.blob.models.ListBlobContainersOptions; +import com.azure.storage.blob.models.PublicAccessType; +import com.azure.storage.blob.models.StorageAccountInfo; +import com.azure.storage.blob.options.BlobContainerCreateOptions; +import com.azure.storage.blob.options.FindBlobsOptions; +import com.azure.storage.blob.options.UndeleteBlobContainerOptions; +import com.azure.storage.common.sas.AccountSasPermission; +import com.azure.storage.common.sas.AccountSasResourceType; +import com.azure.storage.common.sas.AccountSasService; +import com.azure.storage.common.sas.AccountSasSignatureValues; + +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Collections; +import java.util.Map; + +/** + * Code snippets for {@link BlobServiceClient} + */ +@SuppressWarnings({"unused"}) +public class BlobServiceClientJavaDocCodeSnippets { + private final BlobServiceClient client = JavaDocCodeSnippetsHelpers.getBlobServiceClient(); + private final Duration timeout = Duration.ofSeconds(30); + + /** + * Code snippet for {@link BlobServiceClient#getBlobContainerClient(String)} + */ + public void getContainerClient() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.getBlobContainerClient#String + BlobContainerClient blobContainerClient = client.getBlobContainerClient("containerName"); + // END: com.azure.storage.blob.BlobServiceClient.getBlobContainerClient#String + } + + /** + * Code snippet for {@link BlobServiceClient#createBlobContainer(String)} + */ + public void createContainer() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.createBlobContainer#String + BlobContainerClient blobContainerClient = client.createBlobContainer("containerName"); + // END: com.azure.storage.blob.BlobServiceClient.createBlobContainer#String + } + + /** + * Code snippet for {@link BlobServiceClient#createBlobContainerWithResponse(String, Map, PublicAccessType, Context)} + */ + public void createContainerWithResponse() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.createBlobContainerWithResponse#String-Map-PublicAccessType-Context + Map metadata = Collections.singletonMap("metadata", "value"); + Context context = new Context("Key", "Value"); + + BlobContainerClient blobContainerClient = client.createBlobContainerWithResponse( + "containerName", + metadata, + PublicAccessType.CONTAINER, + context).getValue(); + // END: com.azure.storage.blob.BlobServiceClient.createBlobContainerWithResponse#String-Map-PublicAccessType-Context + } + + /** + * Code snippet for {@link BlobServiceClient#deleteBlobContainer(String)} + */ + public void deleteContainer() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.deleteBlobContainer#String + try { + client.deleteBlobContainer("container Name"); + System.out.printf("Delete container completed with status %n"); + } catch (UnsupportedOperationException error) { + System.out.printf("Delete container failed: %s%n", error); + } + // END: com.azure.storage.blob.BlobServiceClient.deleteBlobContainer#String + } + + /** + * Code snippet for {@link BlobServiceClient#deleteBlobContainerWithResponse(String, Context)} + */ + public void deleteContainerWithResponse() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.deleteBlobContainerWithResponse#String-Context + Context context = new Context("Key", "Value"); + System.out.printf("Delete container completed with status %d%n", + client.deleteBlobContainerWithResponse("containerName", context).getStatusCode()); + // END: com.azure.storage.blob.BlobServiceClient.deleteBlobContainerWithResponse#String-Context + } + + /** + * Code snippets for {@link BlobServiceClient#listBlobContainers()} and + * {@link BlobServiceClient#listBlobContainers(ListBlobContainersOptions, Duration)} + */ + public void listContainers() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.listBlobContainers + client.listBlobContainers().forEach(container -> System.out.printf("Name: %s%n", container.getName())); + // END: com.azure.storage.blob.BlobServiceClient.listBlobContainers + + // BEGIN: com.azure.storage.blob.BlobServiceClient.listBlobContainers#ListBlobContainersOptions-Duration + ListBlobContainersOptions options = new ListBlobContainersOptions() + .setPrefix("containerNamePrefixToMatch") + .setDetails(new BlobContainerListDetails().setRetrieveMetadata(true)); + + client.listBlobContainers(options, timeout).forEach(container -> System.out.printf("Name: %s%n", container.getName())); + // END: com.azure.storage.blob.BlobServiceClient.listBlobContainers#ListBlobContainersOptions-Duration + } + + /** + * Code snippets for {@link BlobServiceClient#findBlobsByTags(String)} and + * {@link BlobServiceClient#findBlobsByTags(FindBlobsOptions, Duration, Context)} + */ + public void findBlobsByTag() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.findBlobsByTag#String + client.findBlobsByTags("where=tag=value").forEach(blob -> System.out.printf("Name: %s%n", blob.getName())); + // END: com.azure.storage.blob.BlobServiceClient.findBlobsByTag#String + + // BEGIN: com.azure.storage.blob.BlobServiceClient.findBlobsByTag#FindBlobsOptions-Duration + Context context = new Context("Key", "Value"); + client.findBlobsByTags(new FindBlobsOptions("where=tag=value").setMaxResultsPerPage(10), timeout, context) + .forEach(blob -> System.out.printf("Name: %s%n", blob.getName())); + // END: com.azure.storage.blob.BlobServiceClient.findBlobsByTag#FindBlobsOptions-Duration + } + + /** + * Code snippet for {@link BlobServiceClient#getProperties()} + */ + public void getProperties() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.getProperties + BlobServiceProperties properties = client.getProperties(); + + System.out.printf("Hour metrics enabled: %b, Minute metrics enabled: %b%n", + properties.getHourMetrics().isEnabled(), + properties.getMinuteMetrics().isEnabled()); + // END: com.azure.storage.blob.BlobServiceClient.getProperties + } + + /** + * Code snippet for {@link BlobServiceClient#getPropertiesWithResponse(Duration, Context)} + */ + public void getPropertiesWithResponse() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.getPropertiesWithResponse#Duration-Context + Context context = new Context("Key", "Value"); + BlobServiceProperties properties = client.getPropertiesWithResponse(timeout, context).getValue(); + + System.out.printf("Hour metrics enabled: %b, Minute metrics enabled: %b%n", + properties.getHourMetrics().isEnabled(), + properties.getMinuteMetrics().isEnabled()); + // END: com.azure.storage.blob.BlobServiceClient.getPropertiesWithResponse#Duration-Context + } + + /** + * Code snippet for {@link BlobServiceClient#setProperties(BlobServiceProperties)} + */ + public void setProperties() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.setProperties#BlobServiceProperties + BlobRetentionPolicy loggingRetentionPolicy = new BlobRetentionPolicy().setEnabled(true).setDays(3); + BlobRetentionPolicy metricsRetentionPolicy = new BlobRetentionPolicy().setEnabled(true).setDays(1); + + BlobServiceProperties properties = new BlobServiceProperties() + .setLogging(new BlobAnalyticsLogging() + .setWrite(true) + .setDelete(true) + .setVersion("1.0") + .setRetentionPolicy(loggingRetentionPolicy)) + .setHourMetrics(new BlobMetrics() + .setEnabled(true) + .setVersion("1.0") + .setIncludeApis(true) + .setRetentionPolicy(metricsRetentionPolicy)) + .setMinuteMetrics(new BlobMetrics() + .setEnabled(true) + .setVersion("1.0") + .setIncludeApis(true) + .setRetentionPolicy(metricsRetentionPolicy)); + + try { + client.setProperties(properties); + System.out.printf("Setting properties completed%n"); + } catch (UnsupportedOperationException error) { + System.out.printf("Setting properties failed: %s%n", error); + } + // END: com.azure.storage.blob.BlobServiceClient.setProperties#BlobServiceProperties + } + + /** + * Code snippet for {@link BlobServiceClient#setPropertiesWithResponse(BlobServiceProperties, Duration, Context)} + */ + public void setPropertiesWithResponse() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.setPropertiesWithResponse#BlobServiceProperties-Duration-Context + BlobRetentionPolicy loggingRetentionPolicy = new BlobRetentionPolicy().setEnabled(true).setDays(3); + BlobRetentionPolicy metricsRetentionPolicy = new BlobRetentionPolicy().setEnabled(true).setDays(1); + + BlobServiceProperties properties = new BlobServiceProperties() + .setLogging(new BlobAnalyticsLogging() + .setWrite(true) + .setDelete(true) + .setVersion("1.0") + .setRetentionPolicy(loggingRetentionPolicy)) + .setHourMetrics(new BlobMetrics() + .setEnabled(true) + .setVersion("1.0") + .setIncludeApis(true) + .setRetentionPolicy(metricsRetentionPolicy)) + .setMinuteMetrics(new BlobMetrics() + .setEnabled(true) + .setVersion("1.0") + .setIncludeApis(true) + .setRetentionPolicy(metricsRetentionPolicy)); + + Context context = new Context("Key", "Value"); + + System.out.printf("Setting properties completed with status %d%n", + client.setPropertiesWithResponse(properties, timeout, context).getStatusCode()); + // END: com.azure.storage.blob.BlobServiceClient.setPropertiesWithResponse#BlobServiceProperties-Duration-Context + } + + /** + * Code snippets for {@link BlobServiceClient#getUserDelegationKey(OffsetDateTime, OffsetDateTime)} + * and {@link BlobServiceClient#getUserDelegationKeyWithResponse(OffsetDateTime, OffsetDateTime, Duration, Context)} + */ + public void getUserDelegationKey() { + OffsetDateTime delegationKeyStartTime = OffsetDateTime.now(); + OffsetDateTime delegationKeyExpiryTime = OffsetDateTime.now().plusDays(7); + Context context = new Context("Key", "Value"); + // BEGIN: com.azure.storage.blob.BlobServiceClient.getUserDelegationKey#OffsetDateTime-OffsetDateTime + System.out.printf("User delegation key: %s%n", + client.getUserDelegationKey(delegationKeyStartTime, delegationKeyExpiryTime)); + // END: com.azure.storage.blob.BlobServiceClient.getUserDelegationKey#OffsetDateTime-OffsetDateTime + + // BEGIN: com.azure.storage.blob.BlobServiceClient.getUserDelegationKeyWithResponse#OffsetDateTime-OffsetDateTime-Duration-Context + System.out.printf("User delegation key: %s%n", + client.getUserDelegationKeyWithResponse(delegationKeyStartTime, delegationKeyExpiryTime, timeout, context)); + // END: com.azure.storage.blob.BlobServiceClient.getUserDelegationKeyWithResponse#OffsetDateTime-OffsetDateTime-Duration-Context + } + + /** + * Code snippets for {@link BlobServiceClient#getStatistics()} and {@link BlobServiceClient#getStatisticsWithResponse(Duration, Context)} + */ + public void getStatistics() { + Context context = new Context("Key", "Value"); + // BEGIN: com.azure.storage.blob.BlobServiceClient.getStatistics + System.out.printf("Geo-replication status: %s%n", + client.getStatistics().getGeoReplication().getStatus()); + // END: com.azure.storage.blob.BlobServiceClient.getStatistics + + // BEGIN: com.azure.storage.blob.BlobServiceClient.getStatisticsWithResponse#Duration-Context + System.out.printf("Geo-replication status: %s%n", + client.getStatisticsWithResponse(timeout, context).getValue().getGeoReplication().getStatus()); + // END: com.azure.storage.blob.BlobServiceClient.getStatisticsWithResponse#Duration-Context + } + + /** + * Code snippet for {@link BlobServiceClient#getAccountInfo} + */ + public void getAccountInfo() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.getAccountInfo + StorageAccountInfo accountInfo = client.getAccountInfo(); + + System.out.printf("Account kind: %s, SKU: %s%n", accountInfo.getAccountKind(), accountInfo.getSkuName()); + // END: com.azure.storage.blob.BlobServiceClient.getAccountInfo + } + + /** + * Code snippet for {@link BlobServiceClient#getAccountInfoWithResponse(Duration, Context)} + */ + public void getAccountInfoWithResponse() { + Context context = new Context("Key", "Value"); + // BEGIN: com.azure.storage.blob.BlobServiceClient.getAccountInfoWithResponse#Duration-Context + StorageAccountInfo accountInfo = client.getAccountInfoWithResponse(timeout, context).getValue(); + // END: com.azure.storage.blob.BlobServiceClient.getAccountInfoWithResponse#Duration-Context + } + + /** + * Code snippet for {@link BlobServiceClient#generateAccountSas(AccountSasSignatureValues)} + */ + public void generateAccountSas() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.generateAccountSas#AccountSasSignatureValues + AccountSasPermission permissions = new AccountSasPermission() + .setListPermission(true) + .setReadPermission(true); + AccountSasResourceType resourceTypes = new AccountSasResourceType().setContainer(true); + AccountSasService services = new AccountSasService().setBlobAccess(true).setFileAccess(true); + OffsetDateTime expiryTime = OffsetDateTime.now().plus(Duration.ofDays(2)); + + AccountSasSignatureValues sasValues = + new AccountSasSignatureValues(expiryTime, permissions, services, resourceTypes); + + // Client must be authenticated via StorageSharedKeyCredential + String sas = client.generateAccountSas(sasValues); + // END: com.azure.storage.blob.BlobServiceClient.generateAccountSas#AccountSasSignatureValues + } + + /** + * Code snippet for {@link BlobServiceClient#generateAccountSas(AccountSasSignatureValues, Context)} + */ + public void generateAccountSasWithContext() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.generateAccountSas#AccountSasSignatureValues-Context + AccountSasPermission permissions = new AccountSasPermission() + .setListPermission(true) + .setReadPermission(true); + AccountSasResourceType resourceTypes = new AccountSasResourceType().setContainer(true); + AccountSasService services = new AccountSasService().setBlobAccess(true).setFileAccess(true); + OffsetDateTime expiryTime = OffsetDateTime.now().plus(Duration.ofDays(2)); + + AccountSasSignatureValues sasValues = + new AccountSasSignatureValues(expiryTime, permissions, services, resourceTypes); + + // Client must be authenticated via StorageSharedKeyCredential + String sas = client.generateAccountSas(sasValues, new Context("key", "value")); + // END: com.azure.storage.blob.BlobServiceClient.generateAccountSas#AccountSasSignatureValues-Context + } + + /** + * Code snippet for {@link BlobServiceClient#undeleteBlobContainer(String, String)}. + */ + public void undeleteBlobContainer() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.undeleteBlobContainer#String-String + ListBlobContainersOptions listBlobContainersOptions = new ListBlobContainersOptions(); + listBlobContainersOptions.getDetails().setRetrieveDeleted(true); + client.listBlobContainers(listBlobContainersOptions, null).forEach( + deletedContainer -> { + BlobContainerClient blobContainerClient = client.undeleteBlobContainer( + deletedContainer.getName(), deletedContainer.getVersion()); + } + ); + // END: com.azure.storage.blob.BlobServiceClient.undeleteBlobContainer#String-String + } + + /** + * Code snippet for {@link BlobServiceClient#undeleteBlobContainerWithResponse(UndeleteBlobContainerOptions, + * Duration, Context)}. + */ + public void undeleteBlobContainerWithResponseWithRename() { + Context context = new Context("Key", "Value"); + // BEGIN: com.azure.storage.blob.BlobServiceClient.undeleteBlobContainerWithResponse#UndeleteBlobContainerOptions-Duration-Context + ListBlobContainersOptions listBlobContainersOptions = new ListBlobContainersOptions(); + listBlobContainersOptions.getDetails().setRetrieveDeleted(true); + client.listBlobContainers(listBlobContainersOptions, null).forEach( + deletedContainer -> { + BlobContainerClient blobContainerClient = client.undeleteBlobContainerWithResponse( + new UndeleteBlobContainerOptions(deletedContainer.getName(), deletedContainer.getVersion()), + timeout, context).getValue(); + } + ); + // END: com.azure.storage.blob.BlobServiceClient.undeleteBlobContainerWithResponse#UndeleteBlobContainerOptions-Duration-Context + } + + /** + * Code snippet for {@link BlobServiceClient#createBlobContainerIfNotExists(String)} and + * {@link BlobServiceClient#createBlobContainerIfNotExistsWithResponse(String, BlobContainerCreateOptions, Context)} + */ + public void createContainerIfNotExistsCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.createBlobContainerIfNotExists#String + BlobContainerClient blobContainerClient = client.createBlobContainerIfNotExists("containerName"); + // END: com.azure.storage.blob.BlobServiceClient.createBlobContainerIfNotExists#String + + // BEGIN: com.azure.storage.blob.BlobServiceClient.createBlobContainerIfNotExistsWithResponse#String-BlobContainerCreateOptions-Context + Map metadata = Collections.singletonMap("metadata", "value"); + Context context = new Context("Key", "Value"); + BlobContainerCreateOptions options = new BlobContainerCreateOptions().setMetadata(metadata) + .setPublicAccessType(PublicAccessType.CONTAINER); + + Response response = client.createBlobContainerIfNotExistsWithResponse("containerName", + options, context); + + if (response.getStatusCode() == 409) { + System.out.println("Already existed."); + } else { + System.out.printf("Create completed with status %d%n", response.getStatusCode()); + } + // END: com.azure.storage.blob.BlobServiceClient.createBlobContainerIfNotExistsWithResponse#String-BlobContainerCreateOptions-Context + } + + /** + * Code snippet for {@link BlobServiceClient#deleteBlobContainerIfExists(String)} and + * {@link BlobServiceClient#deleteBlobContainerIfExistsWithResponse(String, Context)} + */ + public void deleteContainerIfExistsCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobServiceClient.deleteBlobContainerIfExists#String + boolean result = client.deleteBlobContainerIfExists("container Name"); + System.out.println("Delete container completed: " + result); + // END: com.azure.storage.blob.BlobServiceClient.deleteBlobContainerIfExists#String + + // BEGIN: com.azure.storage.blob.BlobServiceClient.deleteBlobContainerIfExistsWithResponse#String-Context + Context context = new Context("Key", "Value"); + + Response response = client.deleteBlobContainerIfExistsWithResponse("containerName", context); + if (response.getStatusCode() == 404) { + System.out.println("Does not exist."); + } else { + System.out.printf("Delete completed with status %d%n", response.getStatusCode()); + } + // END: com.azure.storage.blob.BlobServiceClient.deleteBlobContainerIfExistsWithResponse#String-Context + } + +// /** +// * Code snippet for {@link BlobServiceClient#renameBlobContainer(String, String)} +// */ +// public void renameContainer() { +// // BEGIN: com.azure.storage.blob.BlobServiceClient.renameBlobContainer#String-String +// BlobContainerClient blobContainerClient = client.renameBlobContainer("oldContainerName", "newContainerName"); +// // END: com.azure.storage.blob.BlobServiceClient.renameBlobContainer#String-String +// } +// +// /** +// * Code snippet for {@link BlobServiceClient#renameBlobContainerWithResponse(String, BlobContainerRenameOptions, Duration, Context)} +// */ +// public void renameContainerWithResponse() { +// // BEGIN: com.azure.storage.blob.BlobServiceClient.renameBlobContainerWithResponse#String-BlobContainerRenameOptions-Duration-Context +// BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId("lease-id"); +// Context context = new Context("Key", "Value"); +// +// BlobContainerClient blobContainerClient = client.renameBlobContainerWithResponse("oldContainerName", +// new BlobContainerRenameOptions("newContainerName") +// .setRequestConditions(requestConditions), +// Duration.ofSeconds(1), +// context).getValue(); +// // END: com.azure.storage.blob.BlobServiceClient.renameBlobContainerWithResponse#String-BlobContainerRenameOptions-Duration-Context +// } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample14/v1/BufferedUploadWithKnownLengthExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample14/v1/BufferedUploadWithKnownLengthExample.java new file mode 100644 index 000000000000..a5eb0bf0c919 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample14/v1/BufferedUploadWithKnownLengthExample.java @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.util.BinaryData; +import com.azure.storage.blob.models.ParallelTransferOptions; +import com.azure.storage.blob.options.BlobParallelUploadOptions; +import com.azure.storage.blob.specialized.BlockBlobAsyncClient; +import com.azure.storage.common.StorageSharedKeyCredential; +import reactor.core.publisher.Flux; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.util.Locale; + +/** + * This example shows how to use the buffered upload method on BlockBlobAsyncClient with a known length. + * + * Note that the use of .block() in the method is only used to enable the sample to run effectively in isolation. It is + * not recommended for use in async environments. + */ +public class BufferedUploadWithKnownLengthExample { + /** + * Entry point into the basic examples for Storage blobs. + * @param args Unused. Arguments to the program. + * @throws IOException If an I/O error occurs + * @throws RuntimeException If the downloaded data doesn't match the uploaded data + */ + public static void main(String[] args) throws IOException { + + /* + * For more information on this setup, please refer to the BasicExample. + */ + String accountName = SampleHelper.getAccountName(); + String accountKey = SampleHelper.getAccountKey(); + StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey); + String endpoint = String.format(Locale.ROOT, "https://%s.blob.core.windows.net", accountName); + String containerName = "myjavacontainerbuffereduploadlength" + System.currentTimeMillis(); + BlobServiceAsyncClient storageClient = new BlobServiceClientBuilder().endpoint(endpoint).credential(credential) + .buildAsyncClient(); + + BlobContainerAsyncClient containerClient = storageClient.getBlobContainerAsyncClient(containerName); + containerClient.create().block(); + + uploadSourceBlob(endpoint, credential, containerName); + BlobAsyncClient blobClient = containerClient.getBlobAsyncClient("HelloWorld.txt"); + + + /* + sourceData has a network stream as its source and therefore likely does not support multiple subscribers. Even + if it did support multiple subscribers, it would not produce the same data each time it was subscribed to. While + we could inspect the http headers for the content-length, let us suppose that this information is unavailable + at this time. All three of these factors would individually make the use of the standard upload method + impossible--the first two because retries would not work and the third one because we could not satisfy the + argument list. + */ + Flux sourceData = getSourceBlobClient(endpoint, credential, containerName).downloadStream() + // Perform transformation with length of 1 GB. + .map(BufferedUploadWithKnownLengthExample::bufferTransformation); + + /* + Although this upload overload permits the use of such unreliable data sources, with known length we can speed + up the upload process. A buffer size and maximum concurrency can still be passed in to achieve optimized upload. + */ + long length = 10; + long blockSize = 10 * 1024; + int maxConcurrency = 5; + ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions() + .setBlockSizeLong(blockSize) + .setMaxConcurrency(maxConcurrency); + + // Since we already know the size of our buffered bytes, we can pass the ByteBuffer and length to the BinaryData. + // This will internally convert the BinaryData to a Flux, but with known length we can optimize the + // upload speed. + // Need to use BinaryData.fromFlux(Flux, Long, Boolean) with bufferContent set to false, this allows + // us to configure the BinaryData to have a specified length set without the BinaryData being infinitely + // subscribed to the Flux. + BinaryData.fromFlux(sourceData, length, false).flatMap(binaryData -> + blobClient.uploadWithResponse(new BlobParallelUploadOptions(binaryData) + .setParallelTransferOptions(parallelTransferOptions))); + } + + @SuppressWarnings("cast") + private static ByteBuffer bufferTransformation(ByteBuffer buffer) { + // The JDK changed the return type of ByteBuffer#limit between 8 and 9. In 8 and below it returns Buffer, whereas + // in JDK 9 and later, it returns ByteBuffer. To compile on both, we explicitly cast the returned value to + // ByteBuffer. + // See https://bugs-stage.openjdk.java.net/browse/JDK-8062376 + int length = 10; + return (ByteBuffer) buffer.limit(length); + } + + private static void uploadSourceBlob(String endpoint, StorageSharedKeyCredential credential, String containerName) { + getSourceBlobClient(endpoint, credential, containerName) + .upload(Flux.just(ByteBuffer.wrap("Hello world".getBytes(Charset.defaultCharset()))), "Hello world".length()).block(); + } + + private static BlockBlobAsyncClient getSourceBlobClient(String endpoint, StorageSharedKeyCredential credential, + String containerName) { + return new BlobServiceClientBuilder().endpoint(endpoint).credential(credential).buildAsyncClient() + .getBlobContainerAsyncClient(containerName).getBlobAsyncClient("sourceBlob").getBlockBlobAsyncClient(); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample14/v2/BufferedUploadWithKnownLengthExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample14/v2/BufferedUploadWithKnownLengthExample.java new file mode 100644 index 000000000000..a5eb0bf0c919 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample14/v2/BufferedUploadWithKnownLengthExample.java @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.util.BinaryData; +import com.azure.storage.blob.models.ParallelTransferOptions; +import com.azure.storage.blob.options.BlobParallelUploadOptions; +import com.azure.storage.blob.specialized.BlockBlobAsyncClient; +import com.azure.storage.common.StorageSharedKeyCredential; +import reactor.core.publisher.Flux; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.util.Locale; + +/** + * This example shows how to use the buffered upload method on BlockBlobAsyncClient with a known length. + * + * Note that the use of .block() in the method is only used to enable the sample to run effectively in isolation. It is + * not recommended for use in async environments. + */ +public class BufferedUploadWithKnownLengthExample { + /** + * Entry point into the basic examples for Storage blobs. + * @param args Unused. Arguments to the program. + * @throws IOException If an I/O error occurs + * @throws RuntimeException If the downloaded data doesn't match the uploaded data + */ + public static void main(String[] args) throws IOException { + + /* + * For more information on this setup, please refer to the BasicExample. + */ + String accountName = SampleHelper.getAccountName(); + String accountKey = SampleHelper.getAccountKey(); + StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey); + String endpoint = String.format(Locale.ROOT, "https://%s.blob.core.windows.net", accountName); + String containerName = "myjavacontainerbuffereduploadlength" + System.currentTimeMillis(); + BlobServiceAsyncClient storageClient = new BlobServiceClientBuilder().endpoint(endpoint).credential(credential) + .buildAsyncClient(); + + BlobContainerAsyncClient containerClient = storageClient.getBlobContainerAsyncClient(containerName); + containerClient.create().block(); + + uploadSourceBlob(endpoint, credential, containerName); + BlobAsyncClient blobClient = containerClient.getBlobAsyncClient("HelloWorld.txt"); + + + /* + sourceData has a network stream as its source and therefore likely does not support multiple subscribers. Even + if it did support multiple subscribers, it would not produce the same data each time it was subscribed to. While + we could inspect the http headers for the content-length, let us suppose that this information is unavailable + at this time. All three of these factors would individually make the use of the standard upload method + impossible--the first two because retries would not work and the third one because we could not satisfy the + argument list. + */ + Flux sourceData = getSourceBlobClient(endpoint, credential, containerName).downloadStream() + // Perform transformation with length of 1 GB. + .map(BufferedUploadWithKnownLengthExample::bufferTransformation); + + /* + Although this upload overload permits the use of such unreliable data sources, with known length we can speed + up the upload process. A buffer size and maximum concurrency can still be passed in to achieve optimized upload. + */ + long length = 10; + long blockSize = 10 * 1024; + int maxConcurrency = 5; + ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions() + .setBlockSizeLong(blockSize) + .setMaxConcurrency(maxConcurrency); + + // Since we already know the size of our buffered bytes, we can pass the ByteBuffer and length to the BinaryData. + // This will internally convert the BinaryData to a Flux, but with known length we can optimize the + // upload speed. + // Need to use BinaryData.fromFlux(Flux, Long, Boolean) with bufferContent set to false, this allows + // us to configure the BinaryData to have a specified length set without the BinaryData being infinitely + // subscribed to the Flux. + BinaryData.fromFlux(sourceData, length, false).flatMap(binaryData -> + blobClient.uploadWithResponse(new BlobParallelUploadOptions(binaryData) + .setParallelTransferOptions(parallelTransferOptions))); + } + + @SuppressWarnings("cast") + private static ByteBuffer bufferTransformation(ByteBuffer buffer) { + // The JDK changed the return type of ByteBuffer#limit between 8 and 9. In 8 and below it returns Buffer, whereas + // in JDK 9 and later, it returns ByteBuffer. To compile on both, we explicitly cast the returned value to + // ByteBuffer. + // See https://bugs-stage.openjdk.java.net/browse/JDK-8062376 + int length = 10; + return (ByteBuffer) buffer.limit(length); + } + + private static void uploadSourceBlob(String endpoint, StorageSharedKeyCredential credential, String containerName) { + getSourceBlobClient(endpoint, credential, containerName) + .upload(Flux.just(ByteBuffer.wrap("Hello world".getBytes(Charset.defaultCharset()))), "Hello world".length()).block(); + } + + private static BlockBlobAsyncClient getSourceBlobClient(String endpoint, StorageSharedKeyCredential credential, + String containerName) { + return new BlobServiceClientBuilder().endpoint(endpoint).credential(credential).buildAsyncClient() + .getBlobContainerAsyncClient(containerName).getBlobAsyncClient("sourceBlob").getBlockBlobAsyncClient(); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample15/v1/ConnectionLevelTimeoutExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample15/v1/ConnectionLevelTimeoutExample.java new file mode 100644 index 000000000000..b104add5e308 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample15/v1/ConnectionLevelTimeoutExample.java @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.util.HttpClientOptions; +import com.azure.storage.common.StorageSharedKeyCredential; + +import java.io.IOException; +import java.time.Duration; +import java.util.Locale; +import java.util.concurrent.TimeoutException; + +/** + * This example shows how to use connection level timeouts. These timeouts relate to discrete sections of the + * connection/request/response process such as time to receive headers or time between reading bytes. These options + * offer the most granular control. If one of these values times out, it will be automatically retried. + * Please see {@link HttpClientOptions} for more detailed information on each option. + */ +public class ConnectionLevelTimeoutExample { + + /** + * Entry point into the basic examples for Storage blobs. + * + * @param args Unused. Arguments to the program. + * @throws IOException If an I/O error occurs + * @throws RuntimeException If the downloaded data doesn't match the uploaded data + */ + public static void main(String[] args) throws IOException { + + /* + * From the Azure portal, get your Storage account's name and account key. + */ + String accountName = SampleHelper.getAccountName(); + String accountKey = SampleHelper.getAccountKey(); + + /* + * Use your Storage account's name and key to create a credential object; this is used to access your account. + */ + StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey); + + /* + * From the Azure portal, get your Storage account blob service URL endpoint. + * The URL typically looks like this: + */ + String endpoint = String.format(Locale.ROOT, "https://%s.blob.core.windows.net", accountName); + + /* + * Create clientOptions with application ID and timeouts set + */ + HttpClientOptions clientOptions = new HttpClientOptions() + .setApplicationId("client-options-id") + .setResponseTimeout(Duration.ofNanos(1)) + .setReadTimeout(Duration.ofNanos(1)) + .setWriteTimeout(Duration.ofNanos(1)) + .setConnectTimeout(Duration.ofNanos(1)); + + /* + * Create a BlobServiceClient object that wraps the service endpoint, credential and a request pipeline. + */ + BlobServiceClient storageClient = new BlobServiceClientBuilder() + .endpoint(endpoint) + .credential(credential) + .clientOptions(clientOptions) + .buildClient(); + + /* + * Creating a blob container will cause a timeout exception since default duration is passed in when creating + * blob container. + */ + try { + storageClient.createBlobContainer("myjavacontainerbasic" + System.currentTimeMillis()); + } catch (Exception ex) { + if (ex.getCause() instanceof TimeoutException) { + System.out.println("Operation failed due to timeout: " + ex.getMessage()); + } + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample15/v2/ConnectionLevelTimeoutExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample15/v2/ConnectionLevelTimeoutExample.java new file mode 100644 index 000000000000..b104add5e308 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample15/v2/ConnectionLevelTimeoutExample.java @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.util.HttpClientOptions; +import com.azure.storage.common.StorageSharedKeyCredential; + +import java.io.IOException; +import java.time.Duration; +import java.util.Locale; +import java.util.concurrent.TimeoutException; + +/** + * This example shows how to use connection level timeouts. These timeouts relate to discrete sections of the + * connection/request/response process such as time to receive headers or time between reading bytes. These options + * offer the most granular control. If one of these values times out, it will be automatically retried. + * Please see {@link HttpClientOptions} for more detailed information on each option. + */ +public class ConnectionLevelTimeoutExample { + + /** + * Entry point into the basic examples for Storage blobs. + * + * @param args Unused. Arguments to the program. + * @throws IOException If an I/O error occurs + * @throws RuntimeException If the downloaded data doesn't match the uploaded data + */ + public static void main(String[] args) throws IOException { + + /* + * From the Azure portal, get your Storage account's name and account key. + */ + String accountName = SampleHelper.getAccountName(); + String accountKey = SampleHelper.getAccountKey(); + + /* + * Use your Storage account's name and key to create a credential object; this is used to access your account. + */ + StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey); + + /* + * From the Azure portal, get your Storage account blob service URL endpoint. + * The URL typically looks like this: + */ + String endpoint = String.format(Locale.ROOT, "https://%s.blob.core.windows.net", accountName); + + /* + * Create clientOptions with application ID and timeouts set + */ + HttpClientOptions clientOptions = new HttpClientOptions() + .setApplicationId("client-options-id") + .setResponseTimeout(Duration.ofNanos(1)) + .setReadTimeout(Duration.ofNanos(1)) + .setWriteTimeout(Duration.ofNanos(1)) + .setConnectTimeout(Duration.ofNanos(1)); + + /* + * Create a BlobServiceClient object that wraps the service endpoint, credential and a request pipeline. + */ + BlobServiceClient storageClient = new BlobServiceClientBuilder() + .endpoint(endpoint) + .credential(credential) + .clientOptions(clientOptions) + .buildClient(); + + /* + * Creating a blob container will cause a timeout exception since default duration is passed in when creating + * blob container. + */ + try { + storageClient.createBlobContainer("myjavacontainerbasic" + System.currentTimeMillis()); + } catch (Exception ex) { + if (ex.getCause() instanceof TimeoutException) { + System.out.println("Operation failed due to timeout: " + ex.getMessage()); + } + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample16/v1/FileTransferExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample16/v1/FileTransferExample.java new file mode 100644 index 000000000000..8b58a24564d2 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample16/v1/FileTransferExample.java @@ -0,0 +1,176 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.storage.common.StorageSharedKeyCredential; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Locale; + +/** + * This class shows how to upload the file as fast as possible in parallel using the optimized upload API. + */ +public class FileTransferExample { + private static final String LARGE_TEST_FOLDER = "test-large-files/"; + + /** + * Entry point into the file transfer examples for Storage blobs. + * @param args Unused. Arguments to the program. + * @throws IOException If an I/O error occurs + * @throws NoSuchAlgorithmException If {@code MD5} isn't supported + * @throws RuntimeException If the uploaded or downloaded file wasn't found + */ + public static void main(String[] args) throws IOException, NoSuchAlgorithmException { + + /* + * From the Azure portal, get your Storage account's name and account key. + */ + String accountName = SampleHelper.getAccountName(); + String accountKey = SampleHelper.getAccountKey(); + + /* + * Use your Storage account's name and key to create a credential object; this is used to access your account. + */ + StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey); + + /* + * From the Azure portal, get your Storage account blob service URL endpoint. + * The URL typically looks like this: + */ + String endPoint = String.format(Locale.ROOT, "https://%s.blob.core.windows.net", accountName); + + /* + * Create a BlobServiceClient object that wraps the service endpoint, credential and a request pipeline. + * Now you can use the storageClient to perform various container and blob operations. + */ + BlobServiceClient storageClient = new BlobServiceClientBuilder().endpoint(endPoint).credential(credential).buildClient(); + + + /* + * This example shows several common operations just to get you started. + */ + + + /* + * Create a client that references a to-be-created container in your Azure Storage account. This returns a + * ContainerClient uses the same endpoint, credential and pipeline from storageClient. + * Note that container names require lowercase. + */ + BlobContainerClient blobContainerClient = storageClient.getBlobContainerClient("myjavacontainerparallelupload" + System.currentTimeMillis()); + + /* + * Create a container in Storage blob account. + */ + blobContainerClient.create(); + + /* + * Create a BlockBlobClient object that wraps a blob's endpoint and a default pipeline, the blockBlobClient give us access to upload the file. + */ + String filename = "BigFile.bin"; + BlobClient blobClient = blobContainerClient.getBlobClient(filename); + + /* + * Create the empty uploadFile and downloadFile. + */ + File largeFile = createTempEmptyFile(filename); + + File downloadFile = createTempEmptyFile("downloadFile.bin"); + + Files.deleteIfExists(downloadFile.toPath()); + + /* + * Generate random things to uploadFile, which makes the file with size of 100MB. + */ + long fileSize = 100 * 1024 * 1024L; + createTempFileWithFileSize(largeFile, fileSize); + + /* + * Upload the large file to storage blob. + */ + blobClient.uploadFromFile(largeFile.getPath()); + + /* + * Download the large file from storage blob to the local downloadFile path. + */ + blobClient.downloadToFile(downloadFile.getPath()); + + /* + * Check the files are same after the round-trip. + */ + if (Files.exists(downloadFile.toPath()) && Files.exists(largeFile.toPath())) { + checkTwoFilesAreTheSame(largeFile, downloadFile); + System.out.println("The file we upload is the same as the one we download."); + } else { + throw new RuntimeException("Did not find the upload or download file."); + } + + /* + * Clean up the local files and storage container. + */ + blobContainerClient.delete(); + Files.deleteIfExists(largeFile.toPath()); + Files.deleteIfExists(downloadFile.toPath()); + } + + private static File createTempEmptyFile(String fileName) throws IOException { + String pathName = "./folderPath/" + LARGE_TEST_FOLDER; + + File dirPath = new File(pathName); + + if (dirPath.exists() || dirPath.mkdirs()) { + File f = new File(pathName + fileName); + if (f.exists() || f.createNewFile()) { + return f; + } else { + throw new RuntimeException("Failed to create the large file."); + } + } else { + throw new RuntimeException("Failed to create the large file dir."); + } + } + + private static void createTempFileWithFileSize(File f, long size) throws IOException { + RandomAccessFile raf = new RandomAccessFile(f, "rw"); + raf.setLength(size); + raf.close(); + } + + private static void checkTwoFilesAreTheSame(File f1, File f2) throws IOException, NoSuchAlgorithmException { + String checksumUpload = getFileChecksum(f1); + String checksumDownload = getFileChecksum(f2); + if (!checksumUpload.equals(checksumDownload)) { + throw new RuntimeException("The file upload does not match the file download."); + } + } + + private static String getFileChecksum(File file) throws IOException, NoSuchAlgorithmException { + MessageDigest md = MessageDigest.getInstance("MD5"); + + try (FileInputStream fis = new FileInputStream(file); FileChannel ch = fis.getChannel()) { + final ByteBuffer buf = ByteBuffer.allocateDirect(8192); + int b = ch.read(buf); + while (b != -1 && b != 0) { + buf.flip(); + final byte[] bytes = new byte[b]; + buf.get(bytes); + md.update(bytes, 0, b); + buf.clear(); + b = ch.read(buf); + } + + return new String(md.digest(), StandardCharsets.UTF_8); + } + } + + +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample16/v2/FileTransferExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample16/v2/FileTransferExample.java new file mode 100644 index 000000000000..8b58a24564d2 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample16/v2/FileTransferExample.java @@ -0,0 +1,176 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.storage.common.StorageSharedKeyCredential; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Locale; + +/** + * This class shows how to upload the file as fast as possible in parallel using the optimized upload API. + */ +public class FileTransferExample { + private static final String LARGE_TEST_FOLDER = "test-large-files/"; + + /** + * Entry point into the file transfer examples for Storage blobs. + * @param args Unused. Arguments to the program. + * @throws IOException If an I/O error occurs + * @throws NoSuchAlgorithmException If {@code MD5} isn't supported + * @throws RuntimeException If the uploaded or downloaded file wasn't found + */ + public static void main(String[] args) throws IOException, NoSuchAlgorithmException { + + /* + * From the Azure portal, get your Storage account's name and account key. + */ + String accountName = SampleHelper.getAccountName(); + String accountKey = SampleHelper.getAccountKey(); + + /* + * Use your Storage account's name and key to create a credential object; this is used to access your account. + */ + StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey); + + /* + * From the Azure portal, get your Storage account blob service URL endpoint. + * The URL typically looks like this: + */ + String endPoint = String.format(Locale.ROOT, "https://%s.blob.core.windows.net", accountName); + + /* + * Create a BlobServiceClient object that wraps the service endpoint, credential and a request pipeline. + * Now you can use the storageClient to perform various container and blob operations. + */ + BlobServiceClient storageClient = new BlobServiceClientBuilder().endpoint(endPoint).credential(credential).buildClient(); + + + /* + * This example shows several common operations just to get you started. + */ + + + /* + * Create a client that references a to-be-created container in your Azure Storage account. This returns a + * ContainerClient uses the same endpoint, credential and pipeline from storageClient. + * Note that container names require lowercase. + */ + BlobContainerClient blobContainerClient = storageClient.getBlobContainerClient("myjavacontainerparallelupload" + System.currentTimeMillis()); + + /* + * Create a container in Storage blob account. + */ + blobContainerClient.create(); + + /* + * Create a BlockBlobClient object that wraps a blob's endpoint and a default pipeline, the blockBlobClient give us access to upload the file. + */ + String filename = "BigFile.bin"; + BlobClient blobClient = blobContainerClient.getBlobClient(filename); + + /* + * Create the empty uploadFile and downloadFile. + */ + File largeFile = createTempEmptyFile(filename); + + File downloadFile = createTempEmptyFile("downloadFile.bin"); + + Files.deleteIfExists(downloadFile.toPath()); + + /* + * Generate random things to uploadFile, which makes the file with size of 100MB. + */ + long fileSize = 100 * 1024 * 1024L; + createTempFileWithFileSize(largeFile, fileSize); + + /* + * Upload the large file to storage blob. + */ + blobClient.uploadFromFile(largeFile.getPath()); + + /* + * Download the large file from storage blob to the local downloadFile path. + */ + blobClient.downloadToFile(downloadFile.getPath()); + + /* + * Check the files are same after the round-trip. + */ + if (Files.exists(downloadFile.toPath()) && Files.exists(largeFile.toPath())) { + checkTwoFilesAreTheSame(largeFile, downloadFile); + System.out.println("The file we upload is the same as the one we download."); + } else { + throw new RuntimeException("Did not find the upload or download file."); + } + + /* + * Clean up the local files and storage container. + */ + blobContainerClient.delete(); + Files.deleteIfExists(largeFile.toPath()); + Files.deleteIfExists(downloadFile.toPath()); + } + + private static File createTempEmptyFile(String fileName) throws IOException { + String pathName = "./folderPath/" + LARGE_TEST_FOLDER; + + File dirPath = new File(pathName); + + if (dirPath.exists() || dirPath.mkdirs()) { + File f = new File(pathName + fileName); + if (f.exists() || f.createNewFile()) { + return f; + } else { + throw new RuntimeException("Failed to create the large file."); + } + } else { + throw new RuntimeException("Failed to create the large file dir."); + } + } + + private static void createTempFileWithFileSize(File f, long size) throws IOException { + RandomAccessFile raf = new RandomAccessFile(f, "rw"); + raf.setLength(size); + raf.close(); + } + + private static void checkTwoFilesAreTheSame(File f1, File f2) throws IOException, NoSuchAlgorithmException { + String checksumUpload = getFileChecksum(f1); + String checksumDownload = getFileChecksum(f2); + if (!checksumUpload.equals(checksumDownload)) { + throw new RuntimeException("The file upload does not match the file download."); + } + } + + private static String getFileChecksum(File file) throws IOException, NoSuchAlgorithmException { + MessageDigest md = MessageDigest.getInstance("MD5"); + + try (FileInputStream fis = new FileInputStream(file); FileChannel ch = fis.getChannel()) { + final ByteBuffer buf = ByteBuffer.allocateDirect(8192); + int b = ch.read(buf); + while (b != -1 && b != 0) { + buf.flip(); + final byte[] bytes = new byte[b]; + buf.get(bytes); + md.update(bytes, 0, b); + buf.clear(); + b = ch.read(buf); + } + + return new String(md.digest(), StandardCharsets.UTF_8); + } + } + + +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample17/v1/JavaDocCodeSnippetsHelpers.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample17/v1/JavaDocCodeSnippetsHelpers.java new file mode 100644 index 000000000000..b6b5d8a49e93 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample17/v1/JavaDocCodeSnippetsHelpers.java @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.storage.blob.models.UserDelegationKey; + +final class JavaDocCodeSnippetsHelpers { + static BlobContainerAsyncClient getContainerAsyncClient() { + return new BlobContainerClientBuilder().buildAsyncClient(); + } + + static BlobContainerClient getContainerClient() { + return new BlobContainerClientBuilder().buildClient(); + } + + static BlobAsyncClient getBlobAsyncClient(String blobName) { + return getContainerAsyncClient().getBlobAsyncClient(blobName); + } + + static BlobClient getBlobClient(String blobName) { + return getContainerClient().getBlobClient(blobName); + } + + static BlobServiceAsyncClient getBlobServiceAsyncClient() { + return new BlobServiceClientBuilder().buildAsyncClient(); + } + + static BlobServiceClient getBlobServiceClient() { + return new BlobServiceClientBuilder().buildClient(); + } + + static UserDelegationKey getUserDelegationKey() { + return getBlobServiceClient().getUserDelegationKey(null, null); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample17/v2/JavaDocCodeSnippetsHelpers.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample17/v2/JavaDocCodeSnippetsHelpers.java new file mode 100644 index 000000000000..b6b5d8a49e93 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample17/v2/JavaDocCodeSnippetsHelpers.java @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.storage.blob.models.UserDelegationKey; + +final class JavaDocCodeSnippetsHelpers { + static BlobContainerAsyncClient getContainerAsyncClient() { + return new BlobContainerClientBuilder().buildAsyncClient(); + } + + static BlobContainerClient getContainerClient() { + return new BlobContainerClientBuilder().buildClient(); + } + + static BlobAsyncClient getBlobAsyncClient(String blobName) { + return getContainerAsyncClient().getBlobAsyncClient(blobName); + } + + static BlobClient getBlobClient(String blobName) { + return getContainerClient().getBlobClient(blobName); + } + + static BlobServiceAsyncClient getBlobServiceAsyncClient() { + return new BlobServiceClientBuilder().buildAsyncClient(); + } + + static BlobServiceClient getBlobServiceClient() { + return new BlobServiceClientBuilder().buildClient(); + } + + static UserDelegationKey getUserDelegationKey() { + return getBlobServiceClient().getUserDelegationKey(null, null); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample18/v1/ListContainersExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample18/v1/ListContainersExample.java new file mode 100644 index 000000000000..97d07f8adef3 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample18/v1/ListContainersExample.java @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.storage.common.StorageSharedKeyCredential; + +import java.util.Locale; + +/** + * This example shows how to list all containers with storage client using the Azure Storage Blob SDK for Java. + */ +public class ListContainersExample { + + /** + * Entry point into the list containers examples for Storage blobs. + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + String accountName = SampleHelper.getAccountName(); + String accountKey = SampleHelper.getAccountKey(); + + /* + * Use your Storage account's name and key to create a credential object; this is used to access your account. + */ + StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey); + + /* + * From the Azure portal, get your Storage account blob service URL endpoint. + * The URL typically looks like this: + */ + String endpoint = String.format(Locale.ROOT, "https://%s.blob.core.windows.net", accountName); + + /* + * Create a BlobServiceClient object that wraps the service endpoint, credential and a request pipeline. + */ + BlobServiceClient storageClient = new BlobServiceClientBuilder().endpoint(endpoint).credential(credential).buildClient(); + + /* + * Create 3 different containers from the storageClient. + */ + for (int i = 0; i < 3; i++) { + storageClient.createBlobContainer("mycontainersforlisting" + i + System.currentTimeMillis()); + } + + /* + * List the containers' name under the Azure storage account. + */ + storageClient.listBlobContainers().forEach(containerItem -> { + System.out.println("Container name: " + containerItem.getName()); + + /* + * Clean up the containers at the same time. + */ + storageClient.getBlobContainerClient(containerItem.getName()).delete(); + }); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample18/v2/ListContainersExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample18/v2/ListContainersExample.java new file mode 100644 index 000000000000..97d07f8adef3 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample18/v2/ListContainersExample.java @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.storage.common.StorageSharedKeyCredential; + +import java.util.Locale; + +/** + * This example shows how to list all containers with storage client using the Azure Storage Blob SDK for Java. + */ +public class ListContainersExample { + + /** + * Entry point into the list containers examples for Storage blobs. + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + String accountName = SampleHelper.getAccountName(); + String accountKey = SampleHelper.getAccountKey(); + + /* + * Use your Storage account's name and key to create a credential object; this is used to access your account. + */ + StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey); + + /* + * From the Azure portal, get your Storage account blob service URL endpoint. + * The URL typically looks like this: + */ + String endpoint = String.format(Locale.ROOT, "https://%s.blob.core.windows.net", accountName); + + /* + * Create a BlobServiceClient object that wraps the service endpoint, credential and a request pipeline. + */ + BlobServiceClient storageClient = new BlobServiceClientBuilder().endpoint(endpoint).credential(credential).buildClient(); + + /* + * Create 3 different containers from the storageClient. + */ + for (int i = 0; i < 3; i++) { + storageClient.createBlobContainer("mycontainersforlisting" + i + System.currentTimeMillis()); + } + + /* + * List the containers' name under the Azure storage account. + */ + storageClient.listBlobContainers().forEach(containerItem -> { + System.out.println("Container name: " + containerItem.getName()); + + /* + * Clean up the containers at the same time. + */ + storageClient.getBlobContainerClient(containerItem.getName()).delete(); + }); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample19/v1/LocationModeExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample19/v1/LocationModeExample.java new file mode 100644 index 000000000000..a58ab7311d56 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample19/v1/LocationModeExample.java @@ -0,0 +1,107 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.storage.common.policy.RequestRetryOptions; + +import java.time.Duration; + + +/** + * This example shows how to approximate the LocationMode behavior from the track 1 SDK. It is a general translation to + * achieve roughly the same results, but it is not an identical implementation. It may be modified to suit the use case. + * For more information on redundant storage, see here: + * https://docs.microsoft.com/en-us/azure/storage/common/storage-redundancy + * + * In a sense, the track 2 SDK is always primary-only or primary-then-secondary. However, by passing the secondary + * endpoint as the primary and the primary as the secondary, the behavior of secondary-only or secondary-then-primary + * can be achieved. To avoid confusion of terms in this example, 'preferred' and 'fallback' will refer to the location + * that is tried by the client first and then second respectively, whereas 'primary' and 'secondary' will refer to the + * Storage concept of primary read-write storage and back-up/redundant/read-only storage respectively. + * + * The general pattern is to create a BlobClient and pass the preferred location to the builder as the endpoint. To + * configure a fallback location, set it as the `secondaryEndpoint` on {@link RequestRetryOptions} and pass the + * configured options to {@link BlobClientBuilder#retryOptions(RequestRetryOptions)}. Switching LocationMode requires + * using a different client that is configured for the new request behavior. In this case, concurrency control should + * be carefully considered to prevent race conditions. + * + * Requests will always go first to the preferred location passed as the endpoint. If a request must be retried, it will + * and the error indicates it may be helped by checking the fallback, a request will immediately be reissued to the + * fallback. If that also fails and still a retry may be helpful, the client will wait for a backoff period specified by + * the retry options before retrying the initial location again. + * + * The client does not internally track the LocationMode or read it from an object that is passed because of how that + * might cause race conditions if it is shared between clients. + * + * Each of the clients constructed in this sample will have behavior according to the variable name. This sample does + * not demonstrate meaningful independent behavior, so running it will do nothing, but these clients can be copied and + * used as a component in other code. + * + * This example can be combined with the StorageEventExample to approximate the Circuit Breaker RAGRS sample here: + * https://github.com/Azure-Samples/storage-dotnet-circuit-breaker-ha-ra-grs/blob/master/storage-dotnet-circuit-breaker-ha-ra-grs/Program.cs + * In this case, in the StorageEvent callback, rather than switching the LocationMode on the DefaultRequestOptions, the + * client should be swapped out to the client with the appropriate LocationMode and the request reissued, alternating + * between a primary only and secondary only client. + * + * The main areas of divergence from the original LocationMode behavior are: + * - There is no LocationMode type + * - The v12 analogue of LocationMode is configured at client build time and is static for a given client; a new client + * must be used if different location behavior is desired. + * - Changing LocationMode entails changing the client being used to issue requests + */ +public class LocationModeExample { + + public static void main(String[] args) { + String primaryEndpoint = ""; + String secondaryEndpoint = ""; + + BlobClient primaryOnlyClient; + BlobClient secondaryOnlyClient; + BlobClient primaryThenSecondaryClient; + BlobClient secondaryThenPrimaryClient; + + BlobClientBuilder builder = new BlobClientBuilder() + .containerName("") + .blobName(""); + + /* + This could be refactored into a helper methods, but it is written out explicitly here for clarity and ease of + comparison. + Null in all cases indicates accepting the default value. + A distinct set of options must be created for each client to prevent overwriting the options held by another + client. + */ + // Create a primary only client by passing the primary endpoint as the preferred and passing no fallback. + RequestRetryOptions primaryOnlyRetryOptions = new RequestRetryOptions(null, null, (Duration) null, null, null, + null); + primaryOnlyClient = builder + .endpoint(primaryEndpoint) + .retryOptions(primaryOnlyRetryOptions) + .buildClient(); + + // Create a secondary only client by passing the secondary as the preferred and passing no fallback. + RequestRetryOptions secondaryOnlyRetryOptions = new RequestRetryOptions(null, null, (Duration) null, null, null, + null); + secondaryOnlyClient = builder + .endpoint(secondaryEndpoint) + .retryOptions(secondaryOnlyRetryOptions) + .buildClient(); + + // Create a primary then secondary by passing a primary as the preferred and secondary as a fallback. + RequestRetryOptions primaryThenSecondaryRetryOptions = new RequestRetryOptions(null, null, (Duration) null, + null, null, secondaryEndpoint); + primaryThenSecondaryClient = builder + .endpoint(primaryEndpoint) + .retryOptions(primaryThenSecondaryRetryOptions) + .buildClient(); + + // Create a secondary then primary by passing a secondary as the preferred and a primary as a fallback. + RequestRetryOptions secondaryThenPrimaryRetryOptions = new RequestRetryOptions(null, null, (Duration) null, + null, null, primaryEndpoint); + secondaryThenPrimaryClient = builder + .endpoint(secondaryEndpoint) + .retryOptions(secondaryThenPrimaryRetryOptions) + .buildClient(); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample19/v2/LocationModeExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample19/v2/LocationModeExample.java new file mode 100644 index 000000000000..a58ab7311d56 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample19/v2/LocationModeExample.java @@ -0,0 +1,107 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.storage.common.policy.RequestRetryOptions; + +import java.time.Duration; + + +/** + * This example shows how to approximate the LocationMode behavior from the track 1 SDK. It is a general translation to + * achieve roughly the same results, but it is not an identical implementation. It may be modified to suit the use case. + * For more information on redundant storage, see here: + * https://docs.microsoft.com/en-us/azure/storage/common/storage-redundancy + * + * In a sense, the track 2 SDK is always primary-only or primary-then-secondary. However, by passing the secondary + * endpoint as the primary and the primary as the secondary, the behavior of secondary-only or secondary-then-primary + * can be achieved. To avoid confusion of terms in this example, 'preferred' and 'fallback' will refer to the location + * that is tried by the client first and then second respectively, whereas 'primary' and 'secondary' will refer to the + * Storage concept of primary read-write storage and back-up/redundant/read-only storage respectively. + * + * The general pattern is to create a BlobClient and pass the preferred location to the builder as the endpoint. To + * configure a fallback location, set it as the `secondaryEndpoint` on {@link RequestRetryOptions} and pass the + * configured options to {@link BlobClientBuilder#retryOptions(RequestRetryOptions)}. Switching LocationMode requires + * using a different client that is configured for the new request behavior. In this case, concurrency control should + * be carefully considered to prevent race conditions. + * + * Requests will always go first to the preferred location passed as the endpoint. If a request must be retried, it will + * and the error indicates it may be helped by checking the fallback, a request will immediately be reissued to the + * fallback. If that also fails and still a retry may be helpful, the client will wait for a backoff period specified by + * the retry options before retrying the initial location again. + * + * The client does not internally track the LocationMode or read it from an object that is passed because of how that + * might cause race conditions if it is shared between clients. + * + * Each of the clients constructed in this sample will have behavior according to the variable name. This sample does + * not demonstrate meaningful independent behavior, so running it will do nothing, but these clients can be copied and + * used as a component in other code. + * + * This example can be combined with the StorageEventExample to approximate the Circuit Breaker RAGRS sample here: + * https://github.com/Azure-Samples/storage-dotnet-circuit-breaker-ha-ra-grs/blob/master/storage-dotnet-circuit-breaker-ha-ra-grs/Program.cs + * In this case, in the StorageEvent callback, rather than switching the LocationMode on the DefaultRequestOptions, the + * client should be swapped out to the client with the appropriate LocationMode and the request reissued, alternating + * between a primary only and secondary only client. + * + * The main areas of divergence from the original LocationMode behavior are: + * - There is no LocationMode type + * - The v12 analogue of LocationMode is configured at client build time and is static for a given client; a new client + * must be used if different location behavior is desired. + * - Changing LocationMode entails changing the client being used to issue requests + */ +public class LocationModeExample { + + public static void main(String[] args) { + String primaryEndpoint = ""; + String secondaryEndpoint = ""; + + BlobClient primaryOnlyClient; + BlobClient secondaryOnlyClient; + BlobClient primaryThenSecondaryClient; + BlobClient secondaryThenPrimaryClient; + + BlobClientBuilder builder = new BlobClientBuilder() + .containerName("") + .blobName(""); + + /* + This could be refactored into a helper methods, but it is written out explicitly here for clarity and ease of + comparison. + Null in all cases indicates accepting the default value. + A distinct set of options must be created for each client to prevent overwriting the options held by another + client. + */ + // Create a primary only client by passing the primary endpoint as the preferred and passing no fallback. + RequestRetryOptions primaryOnlyRetryOptions = new RequestRetryOptions(null, null, (Duration) null, null, null, + null); + primaryOnlyClient = builder + .endpoint(primaryEndpoint) + .retryOptions(primaryOnlyRetryOptions) + .buildClient(); + + // Create a secondary only client by passing the secondary as the preferred and passing no fallback. + RequestRetryOptions secondaryOnlyRetryOptions = new RequestRetryOptions(null, null, (Duration) null, null, null, + null); + secondaryOnlyClient = builder + .endpoint(secondaryEndpoint) + .retryOptions(secondaryOnlyRetryOptions) + .buildClient(); + + // Create a primary then secondary by passing a primary as the preferred and secondary as a fallback. + RequestRetryOptions primaryThenSecondaryRetryOptions = new RequestRetryOptions(null, null, (Duration) null, + null, null, secondaryEndpoint); + primaryThenSecondaryClient = builder + .endpoint(primaryEndpoint) + .retryOptions(primaryThenSecondaryRetryOptions) + .buildClient(); + + // Create a secondary then primary by passing a secondary as the preferred and a primary as a fallback. + RequestRetryOptions secondaryThenPrimaryRetryOptions = new RequestRetryOptions(null, null, (Duration) null, + null, null, primaryEndpoint); + secondaryThenPrimaryClient = builder + .endpoint(secondaryEndpoint) + .retryOptions(secondaryThenPrimaryRetryOptions) + .buildClient(); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample2/v1/AsyncBufferedUploadExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample2/v1/AsyncBufferedUploadExample.java new file mode 100644 index 000000000000..4cca812b1395 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample2/v1/AsyncBufferedUploadExample.java @@ -0,0 +1,95 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.storage.blob.models.ParallelTransferOptions; +import com.azure.storage.blob.specialized.BlockBlobAsyncClient; +import com.azure.storage.common.StorageSharedKeyCredential; +import reactor.core.publisher.Flux; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.util.Locale; +import java.util.Random; + +/** + * This example shows how to use the buffered upload method on BlockBlobAsyncClient. + * + * Note that the use of .block() in the method is only used to enable the sample to run effectively in isolation. It is + * not recommended for use in async environments. + */ +public class AsyncBufferedUploadExample { + /** + * Entry point into the basic examples for Storage blobs. + * @param args Unused. Arguments to the program. + * @throws IOException If an I/O error occurs + * @throws RuntimeException If the downloaded data doesn't match the uploaded data + */ + public static void main(String[] args) throws IOException { + + /* + * For more information on this setup, please refer to the BasicExample. + */ + String accountName = SampleHelper.getAccountName(); + String accountKey = SampleHelper.getAccountKey(); + StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey); + String endpoint = String.format(Locale.ROOT, "https://%s.blob.core.windows.net", accountName); + String containerName = "myjavacontainerbufferedupload" + System.currentTimeMillis(); + BlobServiceAsyncClient storageClient = new BlobServiceClientBuilder().endpoint(endpoint).credential(credential) + .buildAsyncClient(); + + BlobContainerAsyncClient containerClient = storageClient.getBlobContainerAsyncClient(containerName); + containerClient.create().block(); + + uploadSourceBlob(endpoint, credential, containerName); + BlobAsyncClient blobClient = containerClient.getBlobAsyncClient("HelloWorld.txt"); + + + /* + sourceData has a network stream as its source and therefore likely does not support multiple subscribers. Even + if it did support multiple subscribers, it would not produce the same data each time it was subscribed to. While + we could inspect the http headers for the content-length, let us suppose that this information is unavailable + at this time. All three of these factors would individually make the use of the standard upload method + impossible--the first two because retries would not work and the third one because we could not satisfy the + argument list. + */ + Flux sourceData = getSourceBlobClient(endpoint, credential, containerName).downloadStream() + // Perform some unpredictable transformation. + .map(AsyncBufferedUploadExample::randomTransformation); + + /* + This upload overload permits the use of such unreliable data sources. The length need not be specified, but + the tradeoff is that data must be buffered, so a buffer size and maximum concurrency is required instead. The + Javadoc on the method will give more detailed information on the significance of these parameters, but they are + likely context dependent. + */ + long blockSize = 10 * 1024; + int maxConcurrency = 5; + ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions() + .setBlockSizeLong(blockSize) + .setMaxConcurrency(maxConcurrency); + blobClient.upload(sourceData, parallelTransferOptions).block(); + } + + @SuppressWarnings("cast") + private static ByteBuffer randomTransformation(ByteBuffer buffer) { + // The JDK changed the return type of ByteBuffer#limit between 8 and 9. In 8 and below it returns Buffer, whereas + // in JDK 9 and later, it returns ByteBuffer. To compile on both, we explicitly cast the returned value to + // ByteBuffer. + // See https://bugs-stage.openjdk.java.net/browse/JDK-8062376 + return (ByteBuffer) buffer.limit(new Random().nextInt(buffer.limit())); + } + + private static void uploadSourceBlob(String endpoint, StorageSharedKeyCredential credential, String containerName) { + getSourceBlobClient(endpoint, credential, containerName) + .upload(Flux.just(ByteBuffer.wrap("Hello world".getBytes(Charset.defaultCharset()))), "Hello world".length()).block(); + } + + private static BlockBlobAsyncClient getSourceBlobClient(String endpoint, StorageSharedKeyCredential credential, + String containerName) { + return new BlobServiceClientBuilder().endpoint(endpoint).credential(credential).buildAsyncClient() + .getBlobContainerAsyncClient(containerName).getBlobAsyncClient("sourceBlob").getBlockBlobAsyncClient(); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample2/v2/AsyncBufferedUploadExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample2/v2/AsyncBufferedUploadExample.java new file mode 100644 index 000000000000..4cca812b1395 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample2/v2/AsyncBufferedUploadExample.java @@ -0,0 +1,95 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.storage.blob.models.ParallelTransferOptions; +import com.azure.storage.blob.specialized.BlockBlobAsyncClient; +import com.azure.storage.common.StorageSharedKeyCredential; +import reactor.core.publisher.Flux; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.util.Locale; +import java.util.Random; + +/** + * This example shows how to use the buffered upload method on BlockBlobAsyncClient. + * + * Note that the use of .block() in the method is only used to enable the sample to run effectively in isolation. It is + * not recommended for use in async environments. + */ +public class AsyncBufferedUploadExample { + /** + * Entry point into the basic examples for Storage blobs. + * @param args Unused. Arguments to the program. + * @throws IOException If an I/O error occurs + * @throws RuntimeException If the downloaded data doesn't match the uploaded data + */ + public static void main(String[] args) throws IOException { + + /* + * For more information on this setup, please refer to the BasicExample. + */ + String accountName = SampleHelper.getAccountName(); + String accountKey = SampleHelper.getAccountKey(); + StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey); + String endpoint = String.format(Locale.ROOT, "https://%s.blob.core.windows.net", accountName); + String containerName = "myjavacontainerbufferedupload" + System.currentTimeMillis(); + BlobServiceAsyncClient storageClient = new BlobServiceClientBuilder().endpoint(endpoint).credential(credential) + .buildAsyncClient(); + + BlobContainerAsyncClient containerClient = storageClient.getBlobContainerAsyncClient(containerName); + containerClient.create().block(); + + uploadSourceBlob(endpoint, credential, containerName); + BlobAsyncClient blobClient = containerClient.getBlobAsyncClient("HelloWorld.txt"); + + + /* + sourceData has a network stream as its source and therefore likely does not support multiple subscribers. Even + if it did support multiple subscribers, it would not produce the same data each time it was subscribed to. While + we could inspect the http headers for the content-length, let us suppose that this information is unavailable + at this time. All three of these factors would individually make the use of the standard upload method + impossible--the first two because retries would not work and the third one because we could not satisfy the + argument list. + */ + Flux sourceData = getSourceBlobClient(endpoint, credential, containerName).downloadStream() + // Perform some unpredictable transformation. + .map(AsyncBufferedUploadExample::randomTransformation); + + /* + This upload overload permits the use of such unreliable data sources. The length need not be specified, but + the tradeoff is that data must be buffered, so a buffer size and maximum concurrency is required instead. The + Javadoc on the method will give more detailed information on the significance of these parameters, but they are + likely context dependent. + */ + long blockSize = 10 * 1024; + int maxConcurrency = 5; + ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions() + .setBlockSizeLong(blockSize) + .setMaxConcurrency(maxConcurrency); + blobClient.upload(sourceData, parallelTransferOptions).block(); + } + + @SuppressWarnings("cast") + private static ByteBuffer randomTransformation(ByteBuffer buffer) { + // The JDK changed the return type of ByteBuffer#limit between 8 and 9. In 8 and below it returns Buffer, whereas + // in JDK 9 and later, it returns ByteBuffer. To compile on both, we explicitly cast the returned value to + // ByteBuffer. + // See https://bugs-stage.openjdk.java.net/browse/JDK-8062376 + return (ByteBuffer) buffer.limit(new Random().nextInt(buffer.limit())); + } + + private static void uploadSourceBlob(String endpoint, StorageSharedKeyCredential credential, String containerName) { + getSourceBlobClient(endpoint, credential, containerName) + .upload(Flux.just(ByteBuffer.wrap("Hello world".getBytes(Charset.defaultCharset()))), "Hello world".length()).block(); + } + + private static BlockBlobAsyncClient getSourceBlobClient(String endpoint, StorageSharedKeyCredential credential, + String containerName) { + return new BlobServiceClientBuilder().endpoint(endpoint).credential(credential).buildAsyncClient() + .getBlobContainerAsyncClient(containerName).getBlobAsyncClient("sourceBlob").getBlockBlobAsyncClient(); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample20/v1/OperationalLevelTimeoutExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample20/v1/OperationalLevelTimeoutExample.java new file mode 100644 index 000000000000..a551bd548bc6 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample20/v1/OperationalLevelTimeoutExample.java @@ -0,0 +1,125 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.http.HttpPipelineCallContext; +import com.azure.core.http.HttpPipelineNextPolicy; +import com.azure.core.http.HttpPipelinePosition; +import com.azure.core.http.HttpResponse; +import com.azure.core.http.policy.HttpPipelinePolicy; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.storage.blob.options.BlobContainerCreateOptions; +import com.azure.storage.common.StorageSharedKeyCredential; +import reactor.core.publisher.Mono; + +import java.io.IOException; +import java.time.Duration; +import java.util.Locale; + +/** + * This example shows how to use connection level timeouts. These timeouts relate to the entire operation to complete + * and return, including retries, so any TimeoutException thrown will not be retried. It may be thought of as the amount + * of time a given sync api call may wait before timing out and allowing the application to proceed. This is + * highest-level form of retries. + */ +public class OperationalLevelTimeoutExample { + + /** + * Entry point into the basic examples for Storage blobs. + * + * @param args Unused. Arguments to the program. + * @throws IOException If an I/O error occurs + * @throws RuntimeException If the downloaded data doesn't match the uploaded data + */ + public static void main(String[] args) throws IOException { + + /* + * From the Azure portal, get your Storage account's name and account key. + */ + String accountName = SampleHelper.getAccountName(); + String accountKey = SampleHelper.getAccountKey(); + + /* + * Use your Storage account's name and key to create a credential object; this is used to access your account. + */ + StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey); + + /* + * From the Azure portal, get your Storage account blob service URL endpoint. + * The URL typically looks like this: + */ + String endpoint = String.format(Locale.ROOT, "https://%s.blob.core.windows.net", accountName); + + /* + * Create a BlobServiceClient object that wraps the service endpoint, credential, policy with + * timeout per call, and a request pipeline. + * Note: this is not necessary to implement timeouts. This is only here to allow the sample to be independently + * runnable and demonstrate behavior. + */ + BlobServiceClient storageClient = new BlobServiceClientBuilder() + .endpoint(endpoint) + .credential(credential) + .addPolicy(new TimeoutPolicy()) + .buildClient(); + + /* + * This example shows how to pass timeouts in call operations. + */ + + /* + * Create a client that references a to-be-created container in your Azure Storage account. This returns a + * ContainerClient object that wraps the container's endpoint, credential and a request pipeline (inherited from storageClient). + * Note that container names require lowercase. + */ + BlobContainerClient blobContainerClient = storageClient.getBlobContainerClient("myjavacontainerbasic" + System.currentTimeMillis()); + + /* + * Create a container in Storage blob account with a timeout duration of 3 seconds. A timeout exception will + * occur if the blob create container call takes longer than 3 seconds to complete as this could not throw if + * it took 2 seconds. + */ + try { + blobContainerClient.createIfNotExistsWithResponse(new BlobContainerCreateOptions(), Duration.ofSeconds(3L), Context.NONE); + } catch (Exception ex) { + System.out.println("Creation failed due to timeout: " + ex.getMessage()); + } + + /* + * Create a client that references a to-be-created container in your Azure Storage account. This returns a + * ContainerClient object that wraps the container's endpoint, credential and a request pipeline (inherited from storageClient). + * Note that container names require lowercase. + */ + blobContainerClient = storageClient.getBlobContainerClient("myjavacontainerbasic" + System.currentTimeMillis()); + + /* + * Create a container in Storage blob account with a timeout duration of 10 seconds, greater the timeout duration + * passed in the policy. This will succeed. + */ + Response response = blobContainerClient.createIfNotExistsWithResponse(new BlobContainerCreateOptions(), Duration.ofSeconds(10L), Context.NONE); + if (response.getValue()) { + System.out.println("Blob container successfully created."); + } + + /* + * Delete the container we created earlier. + */ + blobContainerClient.delete(); + } + + /** + * A simple policy that sets duration timeout per call of 5 seconds. + */ + static class TimeoutPolicy implements HttpPipelinePolicy { + @Override + public Mono process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { + return next.process().delayElement(Duration.ofSeconds(5L)); + } + + @Override + public HttpPipelinePosition getPipelinePosition() { + return HttpPipelinePosition.PER_CALL; + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample20/v2/OperationalLevelTimeoutExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample20/v2/OperationalLevelTimeoutExample.java new file mode 100644 index 000000000000..a551bd548bc6 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample20/v2/OperationalLevelTimeoutExample.java @@ -0,0 +1,125 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.http.HttpPipelineCallContext; +import com.azure.core.http.HttpPipelineNextPolicy; +import com.azure.core.http.HttpPipelinePosition; +import com.azure.core.http.HttpResponse; +import com.azure.core.http.policy.HttpPipelinePolicy; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.storage.blob.options.BlobContainerCreateOptions; +import com.azure.storage.common.StorageSharedKeyCredential; +import reactor.core.publisher.Mono; + +import java.io.IOException; +import java.time.Duration; +import java.util.Locale; + +/** + * This example shows how to use connection level timeouts. These timeouts relate to the entire operation to complete + * and return, including retries, so any TimeoutException thrown will not be retried. It may be thought of as the amount + * of time a given sync api call may wait before timing out and allowing the application to proceed. This is + * highest-level form of retries. + */ +public class OperationalLevelTimeoutExample { + + /** + * Entry point into the basic examples for Storage blobs. + * + * @param args Unused. Arguments to the program. + * @throws IOException If an I/O error occurs + * @throws RuntimeException If the downloaded data doesn't match the uploaded data + */ + public static void main(String[] args) throws IOException { + + /* + * From the Azure portal, get your Storage account's name and account key. + */ + String accountName = SampleHelper.getAccountName(); + String accountKey = SampleHelper.getAccountKey(); + + /* + * Use your Storage account's name and key to create a credential object; this is used to access your account. + */ + StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey); + + /* + * From the Azure portal, get your Storage account blob service URL endpoint. + * The URL typically looks like this: + */ + String endpoint = String.format(Locale.ROOT, "https://%s.blob.core.windows.net", accountName); + + /* + * Create a BlobServiceClient object that wraps the service endpoint, credential, policy with + * timeout per call, and a request pipeline. + * Note: this is not necessary to implement timeouts. This is only here to allow the sample to be independently + * runnable and demonstrate behavior. + */ + BlobServiceClient storageClient = new BlobServiceClientBuilder() + .endpoint(endpoint) + .credential(credential) + .addPolicy(new TimeoutPolicy()) + .buildClient(); + + /* + * This example shows how to pass timeouts in call operations. + */ + + /* + * Create a client that references a to-be-created container in your Azure Storage account. This returns a + * ContainerClient object that wraps the container's endpoint, credential and a request pipeline (inherited from storageClient). + * Note that container names require lowercase. + */ + BlobContainerClient blobContainerClient = storageClient.getBlobContainerClient("myjavacontainerbasic" + System.currentTimeMillis()); + + /* + * Create a container in Storage blob account with a timeout duration of 3 seconds. A timeout exception will + * occur if the blob create container call takes longer than 3 seconds to complete as this could not throw if + * it took 2 seconds. + */ + try { + blobContainerClient.createIfNotExistsWithResponse(new BlobContainerCreateOptions(), Duration.ofSeconds(3L), Context.NONE); + } catch (Exception ex) { + System.out.println("Creation failed due to timeout: " + ex.getMessage()); + } + + /* + * Create a client that references a to-be-created container in your Azure Storage account. This returns a + * ContainerClient object that wraps the container's endpoint, credential and a request pipeline (inherited from storageClient). + * Note that container names require lowercase. + */ + blobContainerClient = storageClient.getBlobContainerClient("myjavacontainerbasic" + System.currentTimeMillis()); + + /* + * Create a container in Storage blob account with a timeout duration of 10 seconds, greater the timeout duration + * passed in the policy. This will succeed. + */ + Response response = blobContainerClient.createIfNotExistsWithResponse(new BlobContainerCreateOptions(), Duration.ofSeconds(10L), Context.NONE); + if (response.getValue()) { + System.out.println("Blob container successfully created."); + } + + /* + * Delete the container we created earlier. + */ + blobContainerClient.delete(); + } + + /** + * A simple policy that sets duration timeout per call of 5 seconds. + */ + static class TimeoutPolicy implements HttpPipelinePolicy { + @Override + public Mono process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { + return next.process().delayElement(Duration.ofSeconds(5L)); + } + + @Override + public HttpPipelinePosition getPipelinePosition() { + return HttpPipelinePosition.PER_CALL; + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample21/v1/ReadmeSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample21/v1/ReadmeSamples.java new file mode 100644 index 000000000000..d49b56c1fea8 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample21/v1/ReadmeSamples.java @@ -0,0 +1,382 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.storage.blob; + +import com.azure.core.http.ProxyOptions; +import com.azure.core.http.netty.NettyAsyncHttpClientBuilder; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; +import com.azure.core.util.HttpClientOptions; +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.storage.blob.models.BlobCopyInfo; +import com.azure.storage.blob.models.BlobItem; +import com.azure.storage.blob.models.BlobRequestConditions; +import com.azure.storage.blob.options.BlobParallelUploadOptions; +import com.azure.storage.blob.sas.BlobContainerSasPermission; +import com.azure.storage.blob.sas.BlobSasPermission; +import com.azure.storage.blob.sas.BlobServiceSasSignatureValues; +import com.azure.storage.blob.specialized.BlobInputStream; +import com.azure.storage.blob.specialized.BlobOutputStream; +import com.azure.storage.blob.specialized.BlockBlobClient; +import com.azure.storage.common.sas.AccountSasPermission; +import com.azure.storage.common.sas.AccountSasResourceType; +import com.azure.storage.common.sas.AccountSasService; +import com.azure.storage.common.sas.AccountSasSignatureValues; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.time.Duration; +import java.time.OffsetDateTime; + +/** + * WARNING: MODIFYING THIS FILE WILL REQUIRE CORRESPONDING UPDATES TO README.md FILE. LINE NUMBERS ARE USED TO EXTRACT + * APPROPRIATE CODE SEGMENTS FROM THIS FILE. ADD NEW CODE AT THE BOTTOM TO AVOID CHANGING LINE NUMBERS OF EXISTING CODE + * SAMPLES. + * + * Code samples for the README.md + */ +public class ReadmeSamples { + + private final BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().buildClient(); + private final BlobContainerClient blobContainerClient = new BlobContainerClientBuilder().buildClient(); + private final BlobClient blobClient = new BlobClientBuilder().buildClient(); + + public void getBlobServiceClient1() { + // BEGIN: readme-sample-getBlobServiceClient1 + BlobServiceClient blobServiceClient = new BlobServiceClientBuilder() + .endpoint("") + .sasToken("") + .buildClient(); + // END: readme-sample-getBlobServiceClient1 + } + + public void getBlobServiceClient2() { + // BEGIN: readme-sample-getBlobServiceClient2 + // Only one "?" is needed here. If the SAS token starts with "?", please removing one "?". + BlobServiceClient blobServiceClient = new BlobServiceClientBuilder() + .endpoint("" + "?" + "") + .buildClient(); + // END: readme-sample-getBlobServiceClient2 + } + + public void getBlobContainerClient1() { + // BEGIN: readme-sample-getBlobContainerClient1 + BlobContainerClient blobContainerClient = blobServiceClient.getBlobContainerClient("mycontainer"); + // END: readme-sample-getBlobContainerClient1 + } + + public void getBlobContainerClient2() { + // BEGIN: readme-sample-getBlobContainerClient2 + BlobContainerClient blobContainerClient = new BlobContainerClientBuilder() + .endpoint("") + .sasToken("") + .containerName("mycontainer") + .buildClient(); + // END: readme-sample-getBlobContainerClient2 + } + + public void getBlobContainerClient3() { + // BEGIN: readme-sample-getBlobContainerClient3 + // Only one "?" is needed here. If the SAS token starts with "?", please removing one "?". + BlobContainerClient blobContainerClient = new BlobContainerClientBuilder() + .endpoint("" + "/" + "mycontainer" + "?" + "") + .buildClient(); + // END: readme-sample-getBlobContainerClient3 + } + + public void getBlobClient1() { + // BEGIN: readme-sample-getBlobClient1 + BlobClient blobClient = blobContainerClient.getBlobClient("myblob"); + // END: readme-sample-getBlobClient1 + } + + public void getBlobClient2() { + // BEGIN: readme-sample-getBlobClient2 + BlobClient blobClient = new BlobClientBuilder() + .endpoint("") + .sasToken("") + .containerName("mycontainer") + .blobName("myblob") + .buildClient(); + // END: readme-sample-getBlobClient2 + } + + public void getBlobClient3() { + // BEGIN: readme-sample-getBlobClient3 + // Only one "?" is needed here. If the SAS token starts with "?", please removing one "?". + BlobClient blobClient = new BlobClientBuilder() + .endpoint("" + "/" + "mycontainer" + "/" + "myblob" + "?" + "") + .buildClient(); + // END: readme-sample-getBlobClient3 + } + + public void createBlobContainerClient1() { + // BEGIN: readme-sample-createBlobContainerClient1 + blobServiceClient.createBlobContainer("mycontainer"); + // END: readme-sample-createBlobContainerClient1 + } + + public void createBlobContainerClient2() { + // BEGIN: readme-sample-createBlobContainerClient2 + blobContainerClient.create(); + // END: readme-sample-createBlobContainerClient2 + } + + public void uploadBinaryDataToBlob() { + // BEGIN: readme-sample-uploadBinaryDataToBlob + BlobClient blobClient = blobContainerClient.getBlobClient("myblockblob"); + String dataSample = "samples"; + blobClient.upload(BinaryData.fromString(dataSample)); + // END: readme-sample-uploadBinaryDataToBlob + } + + public void uploadBlobFromStream() { + // BEGIN: readme-sample-uploadBlobFromStream + BlockBlobClient blockBlobClient = blobContainerClient.getBlobClient("myblockblob").getBlockBlobClient(); + String dataSample = "samples"; + try (ByteArrayInputStream dataStream = new ByteArrayInputStream(dataSample.getBytes())) { + blockBlobClient.upload(dataStream, dataSample.length()); + } catch (IOException e) { + e.printStackTrace(); + } + // END: readme-sample-uploadBlobFromStream + } + + public void uploadBlobFromFile() { + // BEGIN: readme-sample-uploadBlobFromFile + BlobClient blobClient = blobContainerClient.getBlobClient("myblockblob"); + blobClient.uploadFromFile("local-file.jpg"); + // END: readme-sample-uploadBlobFromFile + } + + public void uploadIfNotExists() { + // BEGIN: readme-sample-uploadIfNotExists + /* + * Rather than use an if block conditioned on an exists call, there are three ways to upload-if-not-exists using + * one network call instead of two. Equivalent options are present on all upload methods. + */ + // 1. The minimal upload method defaults to no overwriting + String dataSample = "samples"; + try (ByteArrayInputStream dataStream = new ByteArrayInputStream(dataSample.getBytes())) { + blobClient.upload(dataStream, dataSample.length()); + } catch (IOException e) { + e.printStackTrace(); + } + + // 2. The overwrite flag can explicitly be set to false to make intention clear + try (ByteArrayInputStream dataStream = new ByteArrayInputStream(dataSample.getBytes())) { + blobClient.upload(dataStream, dataSample.length(), false /* overwrite */); + } catch (IOException e) { + e.printStackTrace(); + } + + // 3. If the max overload is needed, access conditions must be used to prevent overwriting + try (ByteArrayInputStream dataStream = new ByteArrayInputStream(dataSample.getBytes())) { + BlobParallelUploadOptions options = + new BlobParallelUploadOptions(dataStream, dataSample.length()); + // Setting IfNoneMatch="*" ensures the upload will fail if there is already a blob at the destination. + options.setRequestConditions(new BlobRequestConditions().setIfNoneMatch("*")); + blobClient.uploadWithResponse(options, null, Context.NONE); + } catch (IOException e) { + e.printStackTrace(); + } + // END: readme-sample-uploadIfNotExists + } + + public void overwriteBlob() { + // BEGIN: readme-sample-overwriteBlob + /* + * Rather than use an if block conditioned on an exists call, there are three ways to upload-if-exists in one + * network call instead of two. Equivalent options are present on all upload methods. + */ + String dataSample = "samples"; + + // 1. The overwrite flag can explicitly be set to true. This will succeed as a create and overwrite. + try (ByteArrayInputStream dataStream = new ByteArrayInputStream(dataSample.getBytes())) { + blobClient.upload(dataStream, dataSample.length(), true /* overwrite */); + } catch (IOException e) { + e.printStackTrace(); + } + + /* + * 2. If the max overload is needed and no access conditions are passed, the upload will succeed as both a + * create and overwrite. + */ + try (ByteArrayInputStream dataStream = new ByteArrayInputStream(dataSample.getBytes())) { + BlobParallelUploadOptions options = + new BlobParallelUploadOptions(dataStream, dataSample.length()); + blobClient.uploadWithResponse(options, null, Context.NONE); + } catch (IOException e) { + e.printStackTrace(); + } + + /* + * 3. If the max overload is needed, access conditions may be used to assert that the upload is an overwrite and + * not simply a create. + */ + try (ByteArrayInputStream dataStream = new ByteArrayInputStream(dataSample.getBytes())) { + BlobParallelUploadOptions options = + new BlobParallelUploadOptions(dataStream, dataSample.length()); + // Setting IfMatch="*" ensures the upload will succeed only if there is already a blob at the destination. + options.setRequestConditions(new BlobRequestConditions().setIfMatch("*")); + blobClient.uploadWithResponse(options, null, Context.NONE); + } catch (IOException e) { + e.printStackTrace(); + } + // END: readme-sample-overwriteBlob + } + + public void openBlobOutputStream() { + // BEGIN: readme-sample-openBlobOutputStream + /* + * Opening a blob input stream allows you to write to a blob through a normal stream interface. It will not be + * committed until the stream is closed. + * This option is convenient when the length of the data is unknown. + * This can only be done for block blobs. If the target blob already exists as another type of blob, it will + * fail. + */ + try (BlobOutputStream blobOS = blobClient.getBlockBlobClient().getBlobOutputStream()) { + blobOS.write(new byte[0]); + } catch (IOException e) { + e.printStackTrace(); + } + // END: readme-sample-openBlobOutputStream + } + + public void downloadDataFromBlob() { + // BEGIN: readme-sample-downloadDataFromBlob + BinaryData content = blobClient.downloadContent(); + // END: readme-sample-downloadDataFromBlob + } + + public void downloadBlobToStream() { + // BEGIN: readme-sample-downloadBlobToStream + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + blobClient.downloadStream(outputStream); + } catch (IOException e) { + e.printStackTrace(); + } + // END: readme-sample-downloadBlobToStream + } + + public void downloadBlobToFile() { + // BEGIN: readme-sample-downloadBlobToFile + blobClient.downloadToFile("downloaded-file.jpg"); + // END: readme-sample-downloadBlobToFile + } + + public void openBlobInputStream() { + // BEGIN: readme-sample-openBlobInputStream + /* + * Opening a blob input stream allows you to read from a blob through a normal stream interface. It is also + * mark-able. + */ + try (BlobInputStream blobIS = blobClient.openInputStream()) { + blobIS.read(); + } catch (IOException e) { + e.printStackTrace(); + } + // END: readme-sample-openBlobInputStream + } + + public void enumerateBlobs() { + // BEGIN: readme-sample-enumerateBlobs + for (BlobItem blobItem : blobContainerClient.listBlobs()) { + System.out.println("This is the blob name: " + blobItem.getName()); + } + // END: readme-sample-enumerateBlobs + } + + public void enumerateBlobsCreateClient() { + // BEGIN: readme-sample-enumerateBlobsCreateClient + for (BlobItem blobItem : blobContainerClient.listBlobs()) { + BlobClient blobClient; + if (blobItem.getSnapshot() != null) { + blobClient = blobContainerClient.getBlobClient(blobItem.getName(), blobItem.getSnapshot()); + } else { + blobClient = blobContainerClient.getBlobClient(blobItem.getName()); + } + System.out.println("This is the new blob uri: " + blobClient.getBlobUrl()); + } + // END: readme-sample-enumerateBlobsCreateClient + } + + public void copyBlob() { + // BEGIN: readme-sample-copyBlob + SyncPoller poller = blobClient.beginCopy("", Duration.ofSeconds(1)); + poller.waitForCompletion(); + // END: readme-sample-copyBlob + } + + public void copyBlob2() { + // BEGIN: readme-sample-copyBlob2 + blobClient.copyFromUrl("url-to-blob"); + // END: readme-sample-copyBlob2 + } + + public void generateSas() { + // BEGIN: readme-sample-generateSas + /* + * Generate an account sas. Other samples in this file will demonstrate how to create a client with the sas + * token. + */ + // Configure the sas parameters. This is the minimal set. + OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1); + AccountSasPermission accountSasPermission = new AccountSasPermission().setReadPermission(true); + AccountSasService services = new AccountSasService().setBlobAccess(true); + AccountSasResourceType resourceTypes = new AccountSasResourceType().setObject(true); + + // Generate the account sas. + AccountSasSignatureValues accountSasValues = + new AccountSasSignatureValues(expiryTime, accountSasPermission, services, resourceTypes); + String sasToken = blobServiceClient.generateAccountSas(accountSasValues); + + // Generate a sas using a container client + BlobContainerSasPermission containerSasPermission = new BlobContainerSasPermission().setCreatePermission(true); + BlobServiceSasSignatureValues serviceSasValues = + new BlobServiceSasSignatureValues(expiryTime, containerSasPermission); + blobContainerClient.generateSas(serviceSasValues); + + // Generate a sas using a blob client + BlobSasPermission blobSasPermission = new BlobSasPermission().setReadPermission(true); + serviceSasValues = new BlobServiceSasSignatureValues(expiryTime, blobSasPermission); + blobClient.generateSas(serviceSasValues); + // END: readme-sample-generateSas + } + + public void authWithIdentity() { + // BEGIN: readme-sample-authWithIdentity + BlobServiceClient blobStorageClient = new BlobServiceClientBuilder() + .endpoint("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + // END: readme-sample-authWithIdentity + } + + public void setProxy() { + // BEGIN: readme-sample-setProxy + ProxyOptions options = new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("localhost", 888)); + BlobServiceClient client = new BlobServiceClientBuilder() + .endpoint("") + .sasToken("") + .httpClient(new NettyAsyncHttpClientBuilder().proxy(options).build()) + .buildClient(); + // END: readme-sample-setProxy + } + + public void setProxy2() { + // BEGIN: readme-sample-setProxy2 + HttpClientOptions clientOptions = new HttpClientOptions() + .setProxyOptions(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("localhost", 888))); + BlobServiceClient client = new BlobServiceClientBuilder() + .endpoint("") + .sasToken("") + .clientOptions(clientOptions) + .buildClient(); + // END: readme-sample-setProxy2 + } +} + diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample21/v2/ReadmeSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample21/v2/ReadmeSamples.java new file mode 100644 index 000000000000..d49b56c1fea8 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample21/v2/ReadmeSamples.java @@ -0,0 +1,382 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.storage.blob; + +import com.azure.core.http.ProxyOptions; +import com.azure.core.http.netty.NettyAsyncHttpClientBuilder; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; +import com.azure.core.util.HttpClientOptions; +import com.azure.core.util.polling.SyncPoller; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.storage.blob.models.BlobCopyInfo; +import com.azure.storage.blob.models.BlobItem; +import com.azure.storage.blob.models.BlobRequestConditions; +import com.azure.storage.blob.options.BlobParallelUploadOptions; +import com.azure.storage.blob.sas.BlobContainerSasPermission; +import com.azure.storage.blob.sas.BlobSasPermission; +import com.azure.storage.blob.sas.BlobServiceSasSignatureValues; +import com.azure.storage.blob.specialized.BlobInputStream; +import com.azure.storage.blob.specialized.BlobOutputStream; +import com.azure.storage.blob.specialized.BlockBlobClient; +import com.azure.storage.common.sas.AccountSasPermission; +import com.azure.storage.common.sas.AccountSasResourceType; +import com.azure.storage.common.sas.AccountSasService; +import com.azure.storage.common.sas.AccountSasSignatureValues; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.time.Duration; +import java.time.OffsetDateTime; + +/** + * WARNING: MODIFYING THIS FILE WILL REQUIRE CORRESPONDING UPDATES TO README.md FILE. LINE NUMBERS ARE USED TO EXTRACT + * APPROPRIATE CODE SEGMENTS FROM THIS FILE. ADD NEW CODE AT THE BOTTOM TO AVOID CHANGING LINE NUMBERS OF EXISTING CODE + * SAMPLES. + * + * Code samples for the README.md + */ +public class ReadmeSamples { + + private final BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().buildClient(); + private final BlobContainerClient blobContainerClient = new BlobContainerClientBuilder().buildClient(); + private final BlobClient blobClient = new BlobClientBuilder().buildClient(); + + public void getBlobServiceClient1() { + // BEGIN: readme-sample-getBlobServiceClient1 + BlobServiceClient blobServiceClient = new BlobServiceClientBuilder() + .endpoint("") + .sasToken("") + .buildClient(); + // END: readme-sample-getBlobServiceClient1 + } + + public void getBlobServiceClient2() { + // BEGIN: readme-sample-getBlobServiceClient2 + // Only one "?" is needed here. If the SAS token starts with "?", please removing one "?". + BlobServiceClient blobServiceClient = new BlobServiceClientBuilder() + .endpoint("" + "?" + "") + .buildClient(); + // END: readme-sample-getBlobServiceClient2 + } + + public void getBlobContainerClient1() { + // BEGIN: readme-sample-getBlobContainerClient1 + BlobContainerClient blobContainerClient = blobServiceClient.getBlobContainerClient("mycontainer"); + // END: readme-sample-getBlobContainerClient1 + } + + public void getBlobContainerClient2() { + // BEGIN: readme-sample-getBlobContainerClient2 + BlobContainerClient blobContainerClient = new BlobContainerClientBuilder() + .endpoint("") + .sasToken("") + .containerName("mycontainer") + .buildClient(); + // END: readme-sample-getBlobContainerClient2 + } + + public void getBlobContainerClient3() { + // BEGIN: readme-sample-getBlobContainerClient3 + // Only one "?" is needed here. If the SAS token starts with "?", please removing one "?". + BlobContainerClient blobContainerClient = new BlobContainerClientBuilder() + .endpoint("" + "/" + "mycontainer" + "?" + "") + .buildClient(); + // END: readme-sample-getBlobContainerClient3 + } + + public void getBlobClient1() { + // BEGIN: readme-sample-getBlobClient1 + BlobClient blobClient = blobContainerClient.getBlobClient("myblob"); + // END: readme-sample-getBlobClient1 + } + + public void getBlobClient2() { + // BEGIN: readme-sample-getBlobClient2 + BlobClient blobClient = new BlobClientBuilder() + .endpoint("") + .sasToken("") + .containerName("mycontainer") + .blobName("myblob") + .buildClient(); + // END: readme-sample-getBlobClient2 + } + + public void getBlobClient3() { + // BEGIN: readme-sample-getBlobClient3 + // Only one "?" is needed here. If the SAS token starts with "?", please removing one "?". + BlobClient blobClient = new BlobClientBuilder() + .endpoint("" + "/" + "mycontainer" + "/" + "myblob" + "?" + "") + .buildClient(); + // END: readme-sample-getBlobClient3 + } + + public void createBlobContainerClient1() { + // BEGIN: readme-sample-createBlobContainerClient1 + blobServiceClient.createBlobContainer("mycontainer"); + // END: readme-sample-createBlobContainerClient1 + } + + public void createBlobContainerClient2() { + // BEGIN: readme-sample-createBlobContainerClient2 + blobContainerClient.create(); + // END: readme-sample-createBlobContainerClient2 + } + + public void uploadBinaryDataToBlob() { + // BEGIN: readme-sample-uploadBinaryDataToBlob + BlobClient blobClient = blobContainerClient.getBlobClient("myblockblob"); + String dataSample = "samples"; + blobClient.upload(BinaryData.fromString(dataSample)); + // END: readme-sample-uploadBinaryDataToBlob + } + + public void uploadBlobFromStream() { + // BEGIN: readme-sample-uploadBlobFromStream + BlockBlobClient blockBlobClient = blobContainerClient.getBlobClient("myblockblob").getBlockBlobClient(); + String dataSample = "samples"; + try (ByteArrayInputStream dataStream = new ByteArrayInputStream(dataSample.getBytes())) { + blockBlobClient.upload(dataStream, dataSample.length()); + } catch (IOException e) { + e.printStackTrace(); + } + // END: readme-sample-uploadBlobFromStream + } + + public void uploadBlobFromFile() { + // BEGIN: readme-sample-uploadBlobFromFile + BlobClient blobClient = blobContainerClient.getBlobClient("myblockblob"); + blobClient.uploadFromFile("local-file.jpg"); + // END: readme-sample-uploadBlobFromFile + } + + public void uploadIfNotExists() { + // BEGIN: readme-sample-uploadIfNotExists + /* + * Rather than use an if block conditioned on an exists call, there are three ways to upload-if-not-exists using + * one network call instead of two. Equivalent options are present on all upload methods. + */ + // 1. The minimal upload method defaults to no overwriting + String dataSample = "samples"; + try (ByteArrayInputStream dataStream = new ByteArrayInputStream(dataSample.getBytes())) { + blobClient.upload(dataStream, dataSample.length()); + } catch (IOException e) { + e.printStackTrace(); + } + + // 2. The overwrite flag can explicitly be set to false to make intention clear + try (ByteArrayInputStream dataStream = new ByteArrayInputStream(dataSample.getBytes())) { + blobClient.upload(dataStream, dataSample.length(), false /* overwrite */); + } catch (IOException e) { + e.printStackTrace(); + } + + // 3. If the max overload is needed, access conditions must be used to prevent overwriting + try (ByteArrayInputStream dataStream = new ByteArrayInputStream(dataSample.getBytes())) { + BlobParallelUploadOptions options = + new BlobParallelUploadOptions(dataStream, dataSample.length()); + // Setting IfNoneMatch="*" ensures the upload will fail if there is already a blob at the destination. + options.setRequestConditions(new BlobRequestConditions().setIfNoneMatch("*")); + blobClient.uploadWithResponse(options, null, Context.NONE); + } catch (IOException e) { + e.printStackTrace(); + } + // END: readme-sample-uploadIfNotExists + } + + public void overwriteBlob() { + // BEGIN: readme-sample-overwriteBlob + /* + * Rather than use an if block conditioned on an exists call, there are three ways to upload-if-exists in one + * network call instead of two. Equivalent options are present on all upload methods. + */ + String dataSample = "samples"; + + // 1. The overwrite flag can explicitly be set to true. This will succeed as a create and overwrite. + try (ByteArrayInputStream dataStream = new ByteArrayInputStream(dataSample.getBytes())) { + blobClient.upload(dataStream, dataSample.length(), true /* overwrite */); + } catch (IOException e) { + e.printStackTrace(); + } + + /* + * 2. If the max overload is needed and no access conditions are passed, the upload will succeed as both a + * create and overwrite. + */ + try (ByteArrayInputStream dataStream = new ByteArrayInputStream(dataSample.getBytes())) { + BlobParallelUploadOptions options = + new BlobParallelUploadOptions(dataStream, dataSample.length()); + blobClient.uploadWithResponse(options, null, Context.NONE); + } catch (IOException e) { + e.printStackTrace(); + } + + /* + * 3. If the max overload is needed, access conditions may be used to assert that the upload is an overwrite and + * not simply a create. + */ + try (ByteArrayInputStream dataStream = new ByteArrayInputStream(dataSample.getBytes())) { + BlobParallelUploadOptions options = + new BlobParallelUploadOptions(dataStream, dataSample.length()); + // Setting IfMatch="*" ensures the upload will succeed only if there is already a blob at the destination. + options.setRequestConditions(new BlobRequestConditions().setIfMatch("*")); + blobClient.uploadWithResponse(options, null, Context.NONE); + } catch (IOException e) { + e.printStackTrace(); + } + // END: readme-sample-overwriteBlob + } + + public void openBlobOutputStream() { + // BEGIN: readme-sample-openBlobOutputStream + /* + * Opening a blob input stream allows you to write to a blob through a normal stream interface. It will not be + * committed until the stream is closed. + * This option is convenient when the length of the data is unknown. + * This can only be done for block blobs. If the target blob already exists as another type of blob, it will + * fail. + */ + try (BlobOutputStream blobOS = blobClient.getBlockBlobClient().getBlobOutputStream()) { + blobOS.write(new byte[0]); + } catch (IOException e) { + e.printStackTrace(); + } + // END: readme-sample-openBlobOutputStream + } + + public void downloadDataFromBlob() { + // BEGIN: readme-sample-downloadDataFromBlob + BinaryData content = blobClient.downloadContent(); + // END: readme-sample-downloadDataFromBlob + } + + public void downloadBlobToStream() { + // BEGIN: readme-sample-downloadBlobToStream + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + blobClient.downloadStream(outputStream); + } catch (IOException e) { + e.printStackTrace(); + } + // END: readme-sample-downloadBlobToStream + } + + public void downloadBlobToFile() { + // BEGIN: readme-sample-downloadBlobToFile + blobClient.downloadToFile("downloaded-file.jpg"); + // END: readme-sample-downloadBlobToFile + } + + public void openBlobInputStream() { + // BEGIN: readme-sample-openBlobInputStream + /* + * Opening a blob input stream allows you to read from a blob through a normal stream interface. It is also + * mark-able. + */ + try (BlobInputStream blobIS = blobClient.openInputStream()) { + blobIS.read(); + } catch (IOException e) { + e.printStackTrace(); + } + // END: readme-sample-openBlobInputStream + } + + public void enumerateBlobs() { + // BEGIN: readme-sample-enumerateBlobs + for (BlobItem blobItem : blobContainerClient.listBlobs()) { + System.out.println("This is the blob name: " + blobItem.getName()); + } + // END: readme-sample-enumerateBlobs + } + + public void enumerateBlobsCreateClient() { + // BEGIN: readme-sample-enumerateBlobsCreateClient + for (BlobItem blobItem : blobContainerClient.listBlobs()) { + BlobClient blobClient; + if (blobItem.getSnapshot() != null) { + blobClient = blobContainerClient.getBlobClient(blobItem.getName(), blobItem.getSnapshot()); + } else { + blobClient = blobContainerClient.getBlobClient(blobItem.getName()); + } + System.out.println("This is the new blob uri: " + blobClient.getBlobUrl()); + } + // END: readme-sample-enumerateBlobsCreateClient + } + + public void copyBlob() { + // BEGIN: readme-sample-copyBlob + SyncPoller poller = blobClient.beginCopy("", Duration.ofSeconds(1)); + poller.waitForCompletion(); + // END: readme-sample-copyBlob + } + + public void copyBlob2() { + // BEGIN: readme-sample-copyBlob2 + blobClient.copyFromUrl("url-to-blob"); + // END: readme-sample-copyBlob2 + } + + public void generateSas() { + // BEGIN: readme-sample-generateSas + /* + * Generate an account sas. Other samples in this file will demonstrate how to create a client with the sas + * token. + */ + // Configure the sas parameters. This is the minimal set. + OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1); + AccountSasPermission accountSasPermission = new AccountSasPermission().setReadPermission(true); + AccountSasService services = new AccountSasService().setBlobAccess(true); + AccountSasResourceType resourceTypes = new AccountSasResourceType().setObject(true); + + // Generate the account sas. + AccountSasSignatureValues accountSasValues = + new AccountSasSignatureValues(expiryTime, accountSasPermission, services, resourceTypes); + String sasToken = blobServiceClient.generateAccountSas(accountSasValues); + + // Generate a sas using a container client + BlobContainerSasPermission containerSasPermission = new BlobContainerSasPermission().setCreatePermission(true); + BlobServiceSasSignatureValues serviceSasValues = + new BlobServiceSasSignatureValues(expiryTime, containerSasPermission); + blobContainerClient.generateSas(serviceSasValues); + + // Generate a sas using a blob client + BlobSasPermission blobSasPermission = new BlobSasPermission().setReadPermission(true); + serviceSasValues = new BlobServiceSasSignatureValues(expiryTime, blobSasPermission); + blobClient.generateSas(serviceSasValues); + // END: readme-sample-generateSas + } + + public void authWithIdentity() { + // BEGIN: readme-sample-authWithIdentity + BlobServiceClient blobStorageClient = new BlobServiceClientBuilder() + .endpoint("") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + // END: readme-sample-authWithIdentity + } + + public void setProxy() { + // BEGIN: readme-sample-setProxy + ProxyOptions options = new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("localhost", 888)); + BlobServiceClient client = new BlobServiceClientBuilder() + .endpoint("") + .sasToken("") + .httpClient(new NettyAsyncHttpClientBuilder().proxy(options).build()) + .buildClient(); + // END: readme-sample-setProxy + } + + public void setProxy2() { + // BEGIN: readme-sample-setProxy2 + HttpClientOptions clientOptions = new HttpClientOptions() + .setProxyOptions(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("localhost", 888))); + BlobServiceClient client = new BlobServiceClientBuilder() + .endpoint("") + .sasToken("") + .clientOptions(clientOptions) + .buildClient(); + // END: readme-sample-setProxy2 + } +} + diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample22/v1/RequestLevelTimeoutExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample22/v1/RequestLevelTimeoutExample.java new file mode 100644 index 000000000000..efd2ec04d5e3 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample22/v1/RequestLevelTimeoutExample.java @@ -0,0 +1,161 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.http.HttpHeaders; +import com.azure.core.http.HttpMethod; +import com.azure.core.http.HttpPipelineCallContext; +import com.azure.core.http.HttpPipelineNextPolicy; +import com.azure.core.http.HttpPipelinePosition; +import com.azure.core.http.HttpRequest; +import com.azure.core.http.HttpResponse; +import com.azure.core.http.policy.HttpPipelinePolicy; +import com.azure.storage.common.StorageSharedKeyCredential; +import com.azure.storage.common.policy.RequestRetryOptions; +import com.azure.storage.common.policy.RetryPolicyType; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.io.IOException; +import java.net.URL; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.time.Duration; +import java.util.Locale; +import java.util.concurrent.TimeoutException; + +/** + * This example shows how to use request level timeouts. These timeouts relate to the round trip time for an individual + * request. It is the time between the request leaving the client and the response headers being received by the client. + * These options offer a mid-level granularity. If one of these values times out, it will be automatically retried. + * Note that for write operations in particular, this includes the time it takes to complete writing the body as the + * service will not return a response until this is finished. + */ +public class RequestLevelTimeoutExample { + + /** + * Entry point into the basic examples for Storage blobs. + * + * @param args Unused. Arguments to the program. + * @throws IOException If an I/O error occurs + * @throws RuntimeException If the downloaded data doesn't match the uploaded data + */ + public static void main(String[] args) throws IOException { + + /* + * From the Azure portal, get your Storage account's name and account key. + */ + String accountName = SampleHelper.getAccountName(); + String accountKey = SampleHelper.getAccountKey(); + + /* + * Use your Storage account's name and key to create a credential object; this is used to access your account. + */ + StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey); + + /* + * From the Azure portal, get your Storage account blob service URL endpoint. + * The URL typically looks like this: + */ + String endpoint = String.format(Locale.ROOT, "https://%s.blob.core.windows.net", accountName); + + + /* + Use a Request Retry Policy that has a fixed back-off retry policy. + */ + RequestRetryOptions retryOptions = new RequestRetryOptions(RetryPolicyType.FIXED, 2, 3, 1000L, 1500L, null); + HttpResponse mockHttpResponse = new MockHttpResponse(new HttpRequest(HttpMethod.PUT, new URL("https://www.fake.com")), 202); + + /* + * Create a BlobServiceClient object that wraps the service endpoint, credential, retry options, and a request pipeline. + */ + BlobServiceClient storageClient = new BlobServiceClientBuilder() + .endpoint(endpoint) + .credential(credential) + .retryOptions(retryOptions) + .addPolicy(new TimeoutPolicy(mockHttpResponse)) + .buildClient(); + + /* + * Make a call on the client to trigger the pipeline policy. + */ + try { + storageClient.getProperties(); + } catch (Exception ex) { + if (ex.getCause() instanceof TimeoutException) { + System.out.println("Operation failed due to timeout: " + ex.getMessage()); + } + } + } + + /** + * A simple policy that sets duration timeout per call of 5 seconds. + */ + static class TimeoutPolicy implements HttpPipelinePolicy { + + HttpResponse mockHttpResponse; + int count; + + TimeoutPolicy(HttpResponse httpResponse) { + mockHttpResponse = httpResponse; + count = 0; + } + + @Override + public Mono process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { + System.out.println("Number of retries: " + ++count); + return Mono.just(mockHttpResponse).delayElement(Duration.ofSeconds(5L)); + } + + @Override + public HttpPipelinePosition getPipelinePosition() { + return HttpPipelinePosition.PER_CALL; + } + } + + static class MockHttpResponse extends HttpResponse { + int statusCode; + + protected MockHttpResponse(HttpRequest request, int code) { + super(request); + this.statusCode = code; + } + + @Override + public int getStatusCode() { + return statusCode; + } + + @Override + public String getHeaderValue(String s) { + return null; + } + + + @Override + public HttpHeaders getHeaders() { + return new HttpHeaders(); + } + + @Override + public Flux getBody() { + return Flux.empty(); + } + + @Override + public Mono getBodyAsByteArray() { + return Mono.just(new byte[0]); + } + + @Override + public Mono getBodyAsString() { + return Mono.just(""); + } + + @Override + public Mono getBodyAsString(Charset charset) { + return Mono.just(""); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample22/v2/RequestLevelTimeoutExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample22/v2/RequestLevelTimeoutExample.java new file mode 100644 index 000000000000..efd2ec04d5e3 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample22/v2/RequestLevelTimeoutExample.java @@ -0,0 +1,161 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.http.HttpHeaders; +import com.azure.core.http.HttpMethod; +import com.azure.core.http.HttpPipelineCallContext; +import com.azure.core.http.HttpPipelineNextPolicy; +import com.azure.core.http.HttpPipelinePosition; +import com.azure.core.http.HttpRequest; +import com.azure.core.http.HttpResponse; +import com.azure.core.http.policy.HttpPipelinePolicy; +import com.azure.storage.common.StorageSharedKeyCredential; +import com.azure.storage.common.policy.RequestRetryOptions; +import com.azure.storage.common.policy.RetryPolicyType; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.io.IOException; +import java.net.URL; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.time.Duration; +import java.util.Locale; +import java.util.concurrent.TimeoutException; + +/** + * This example shows how to use request level timeouts. These timeouts relate to the round trip time for an individual + * request. It is the time between the request leaving the client and the response headers being received by the client. + * These options offer a mid-level granularity. If one of these values times out, it will be automatically retried. + * Note that for write operations in particular, this includes the time it takes to complete writing the body as the + * service will not return a response until this is finished. + */ +public class RequestLevelTimeoutExample { + + /** + * Entry point into the basic examples for Storage blobs. + * + * @param args Unused. Arguments to the program. + * @throws IOException If an I/O error occurs + * @throws RuntimeException If the downloaded data doesn't match the uploaded data + */ + public static void main(String[] args) throws IOException { + + /* + * From the Azure portal, get your Storage account's name and account key. + */ + String accountName = SampleHelper.getAccountName(); + String accountKey = SampleHelper.getAccountKey(); + + /* + * Use your Storage account's name and key to create a credential object; this is used to access your account. + */ + StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey); + + /* + * From the Azure portal, get your Storage account blob service URL endpoint. + * The URL typically looks like this: + */ + String endpoint = String.format(Locale.ROOT, "https://%s.blob.core.windows.net", accountName); + + + /* + Use a Request Retry Policy that has a fixed back-off retry policy. + */ + RequestRetryOptions retryOptions = new RequestRetryOptions(RetryPolicyType.FIXED, 2, 3, 1000L, 1500L, null); + HttpResponse mockHttpResponse = new MockHttpResponse(new HttpRequest(HttpMethod.PUT, new URL("https://www.fake.com")), 202); + + /* + * Create a BlobServiceClient object that wraps the service endpoint, credential, retry options, and a request pipeline. + */ + BlobServiceClient storageClient = new BlobServiceClientBuilder() + .endpoint(endpoint) + .credential(credential) + .retryOptions(retryOptions) + .addPolicy(new TimeoutPolicy(mockHttpResponse)) + .buildClient(); + + /* + * Make a call on the client to trigger the pipeline policy. + */ + try { + storageClient.getProperties(); + } catch (Exception ex) { + if (ex.getCause() instanceof TimeoutException) { + System.out.println("Operation failed due to timeout: " + ex.getMessage()); + } + } + } + + /** + * A simple policy that sets duration timeout per call of 5 seconds. + */ + static class TimeoutPolicy implements HttpPipelinePolicy { + + HttpResponse mockHttpResponse; + int count; + + TimeoutPolicy(HttpResponse httpResponse) { + mockHttpResponse = httpResponse; + count = 0; + } + + @Override + public Mono process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { + System.out.println("Number of retries: " + ++count); + return Mono.just(mockHttpResponse).delayElement(Duration.ofSeconds(5L)); + } + + @Override + public HttpPipelinePosition getPipelinePosition() { + return HttpPipelinePosition.PER_CALL; + } + } + + static class MockHttpResponse extends HttpResponse { + int statusCode; + + protected MockHttpResponse(HttpRequest request, int code) { + super(request); + this.statusCode = code; + } + + @Override + public int getStatusCode() { + return statusCode; + } + + @Override + public String getHeaderValue(String s) { + return null; + } + + + @Override + public HttpHeaders getHeaders() { + return new HttpHeaders(); + } + + @Override + public Flux getBody() { + return Flux.empty(); + } + + @Override + public Mono getBodyAsByteArray() { + return Mono.just(new byte[0]); + } + + @Override + public Mono getBodyAsString() { + return Mono.just(""); + } + + @Override + public Mono getBodyAsString(Charset charset) { + return Mono.just(""); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample23/v1/SampleHelper.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample23/v1/SampleHelper.java new file mode 100644 index 000000000000..b558b188521e --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample23/v1/SampleHelper.java @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.util.Configuration; + +/** + * This is a helper class of frequently used methods for sample codes. + */ +class SampleHelper { + static String getAccountName() { + return Configuration.getGlobalConfiguration().get("PRIMARY_STORAGE_ACCOUNT_NAME"); + } + + static String getAccountKey() { + return Configuration.getGlobalConfiguration().get("PRIMARY_STORAGE_ACCOUNT_KEY"); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample23/v2/SampleHelper.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample23/v2/SampleHelper.java new file mode 100644 index 000000000000..b558b188521e --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample23/v2/SampleHelper.java @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.util.Configuration; + +/** + * This is a helper class of frequently used methods for sample codes. + */ +class SampleHelper { + static String getAccountName() { + return Configuration.getGlobalConfiguration().get("PRIMARY_STORAGE_ACCOUNT_NAME"); + } + + static String getAccountKey() { + return Configuration.getGlobalConfiguration().get("PRIMARY_STORAGE_ACCOUNT_KEY"); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample24/v1/ServiceLevelTimeoutExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample24/v1/ServiceLevelTimeoutExample.java new file mode 100644 index 000000000000..ff3307bb23a9 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample24/v1/ServiceLevelTimeoutExample.java @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.util.Context; +import com.azure.core.util.CoreUtils; +import com.azure.storage.blob.models.ParallelTransferOptions; +import com.azure.storage.blob.options.BlobContainerCreateOptions; +import com.azure.storage.blob.options.BlobParallelUploadOptions; +import com.azure.storage.common.StorageSharedKeyCredential; +import com.azure.storage.common.implementation.Constants; +import com.azure.storage.common.policy.ServiceTimeoutPolicy; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.time.Duration; +import java.util.Locale; +import java.util.Random; +import java.util.UUID; + +/** + * This example shows how to use service level timeouts. These timeouts are set on the service operation. If the server + * timeout interval elapses before the service has finished processing the request, the service returns an error. + * For more information on setting service timeouts, see here: + * Setting timeouts for blob service operations + * Setting timeouts for file service operations + * Setting timeouts for queue service operations + */ +public class ServiceLevelTimeoutExample { + + /** + * Entry point into the service level timeout examples for Storage blobs. + * + * @param args Unused. Arguments to the program. + * @throws IOException If an I/O error occurs + * @throws RuntimeException If any failure (come back to this) + */ + public static void main(String[] args) { + + /* + * From the Azure portal, get your Storage account's name and account key. + */ + String accountName = SampleHelper.getAccountName(); + String accountKey = SampleHelper.getAccountKey(); + + /* + * Use your Storage account's name and key to create a credential object; this is used to access your account. + */ + StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey); + + /* + * From the Azure portal, get your Storage account blob service URL endpoint. + * The URL typically looks like this: + */ + String endpoint = String.format(Locale.ROOT, "https://%s.blob.core.windows.net", accountName); + + /* + * Create a BlobServiceClient object that wraps the service endpoint, credential, policy with service level + * timeout per call. + * For this example, we'll set the service timeout to 3 seconds. + */ + BlobServiceClient storageClient = new BlobServiceClientBuilder() + .endpoint(endpoint) + .credential(credential) + .addPolicy(new ServiceTimeoutPolicy(Duration.ofSeconds(3))) + .buildClient(); + + BlobContainerClient blobContainerClient = storageClient.getBlobContainerClient("myjavacontainerbasic" + System.currentTimeMillis()); + + /* + * First create the container with the specified timeout. Since create operations are fast, timeout should not + * exceed the 3 seconds specified above. + */ + try { + blobContainerClient.createIfNotExistsWithResponse(new BlobContainerCreateOptions(), null, Context.NONE); + System.out.println("Created"); + } catch (Exception ex) { + System.out.println("Creation failed due to timeout: " + ex.getMessage()); + } + + BlobClient blobClient = blobContainerClient.getBlobClient("myblob" + System.currentTimeMillis()); + + //Create a dataset that is guaranteed to take longer than the specified timeout of 3 seconds + byte[] randomData = getRandomByteArray(16 * Constants.MB); + InputStream input = new ByteArrayInputStream(randomData); + ParallelTransferOptions pto = new ParallelTransferOptions().setMaxSingleUploadSizeLong((long) Constants.MB); + + /* + * making the call to upload will fail since we are using a large dataset which will take longer than the + * specified timeout. + */ + try { + blobClient.uploadWithResponse(new BlobParallelUploadOptions(input).setParallelTransferOptions(pto), null, null); + System.out.println("Upload succeeded."); + } catch (Exception ex) { + System.out.println("Creation failed due to timeout: " + ex.getMessage()); + } + } + + static byte[] getRandomByteArray(int size) { + long seed = UUID.fromString(CoreUtils.randomUuid().toString()).getMostSignificantBits() & Long.MAX_VALUE; + Random rand = new Random(seed); + byte[] data = new byte[size]; + rand.nextBytes(data); + return data; + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample24/v2/ServiceLevelTimeoutExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample24/v2/ServiceLevelTimeoutExample.java new file mode 100644 index 000000000000..ff3307bb23a9 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample24/v2/ServiceLevelTimeoutExample.java @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.util.Context; +import com.azure.core.util.CoreUtils; +import com.azure.storage.blob.models.ParallelTransferOptions; +import com.azure.storage.blob.options.BlobContainerCreateOptions; +import com.azure.storage.blob.options.BlobParallelUploadOptions; +import com.azure.storage.common.StorageSharedKeyCredential; +import com.azure.storage.common.implementation.Constants; +import com.azure.storage.common.policy.ServiceTimeoutPolicy; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.time.Duration; +import java.util.Locale; +import java.util.Random; +import java.util.UUID; + +/** + * This example shows how to use service level timeouts. These timeouts are set on the service operation. If the server + * timeout interval elapses before the service has finished processing the request, the service returns an error. + * For more information on setting service timeouts, see here: + * Setting timeouts for blob service operations + * Setting timeouts for file service operations + * Setting timeouts for queue service operations + */ +public class ServiceLevelTimeoutExample { + + /** + * Entry point into the service level timeout examples for Storage blobs. + * + * @param args Unused. Arguments to the program. + * @throws IOException If an I/O error occurs + * @throws RuntimeException If any failure (come back to this) + */ + public static void main(String[] args) { + + /* + * From the Azure portal, get your Storage account's name and account key. + */ + String accountName = SampleHelper.getAccountName(); + String accountKey = SampleHelper.getAccountKey(); + + /* + * Use your Storage account's name and key to create a credential object; this is used to access your account. + */ + StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey); + + /* + * From the Azure portal, get your Storage account blob service URL endpoint. + * The URL typically looks like this: + */ + String endpoint = String.format(Locale.ROOT, "https://%s.blob.core.windows.net", accountName); + + /* + * Create a BlobServiceClient object that wraps the service endpoint, credential, policy with service level + * timeout per call. + * For this example, we'll set the service timeout to 3 seconds. + */ + BlobServiceClient storageClient = new BlobServiceClientBuilder() + .endpoint(endpoint) + .credential(credential) + .addPolicy(new ServiceTimeoutPolicy(Duration.ofSeconds(3))) + .buildClient(); + + BlobContainerClient blobContainerClient = storageClient.getBlobContainerClient("myjavacontainerbasic" + System.currentTimeMillis()); + + /* + * First create the container with the specified timeout. Since create operations are fast, timeout should not + * exceed the 3 seconds specified above. + */ + try { + blobContainerClient.createIfNotExistsWithResponse(new BlobContainerCreateOptions(), null, Context.NONE); + System.out.println("Created"); + } catch (Exception ex) { + System.out.println("Creation failed due to timeout: " + ex.getMessage()); + } + + BlobClient blobClient = blobContainerClient.getBlobClient("myblob" + System.currentTimeMillis()); + + //Create a dataset that is guaranteed to take longer than the specified timeout of 3 seconds + byte[] randomData = getRandomByteArray(16 * Constants.MB); + InputStream input = new ByteArrayInputStream(randomData); + ParallelTransferOptions pto = new ParallelTransferOptions().setMaxSingleUploadSizeLong((long) Constants.MB); + + /* + * making the call to upload will fail since we are using a large dataset which will take longer than the + * specified timeout. + */ + try { + blobClient.uploadWithResponse(new BlobParallelUploadOptions(input).setParallelTransferOptions(pto), null, null); + System.out.println("Upload succeeded."); + } catch (Exception ex) { + System.out.println("Creation failed due to timeout: " + ex.getMessage()); + } + } + + static byte[] getRandomByteArray(int size) { + long seed = UUID.fromString(CoreUtils.randomUuid().toString()).getMostSignificantBits() & Long.MAX_VALUE; + Random rand = new Random(seed); + byte[] data = new byte[size]; + rand.nextBytes(data); + return data; + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample25/v1/ServiceVersionExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample25/v1/ServiceVersionExample.java new file mode 100644 index 000000000000..16a718075451 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample25/v1/ServiceVersionExample.java @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.storage.common.StorageSharedKeyCredential; + +import java.util.Locale; + +public class ServiceVersionExample { + + public static void main(String[] args) { + + // More information on these properties can be found in BasicExample.java + String accountName = SampleHelper.getAccountName(); + String accountKey = SampleHelper.getAccountKey(); + StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey); + String endpoint = String.format(Locale.ROOT, "https://%s.blob.core.windows.net", accountName); + + // Select the desired version and set it on the builder + BlobServiceVersion serviceVersion = BlobServiceVersion.V2019_02_02; + BlobServiceClient storageClient = new BlobServiceClientBuilder() + .serviceVersion(serviceVersion) + .endpoint(endpoint).credential(credential).buildClient(); + + // This service client may now be used as desired, and any service requests will target the specified version. + + /* + If the workload includes generating new SAS tokens using an older format, the version of the sas generation can + also be configured. Before starting the jvm, set the environment variable AZURE_STORAGE_SAS_SERVICE_VERSION or + the JVM system property AZURE_STORAGE_SAS_SERVICE_VERSION (e.g. -DAZURE_STORAGE_SAS_SERVICE_VERSION=2019-12-12) + to the service version which corresponds to the desired SAS format to configure this behavior. + */ + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample25/v2/ServiceVersionExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample25/v2/ServiceVersionExample.java new file mode 100644 index 000000000000..16a718075451 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample25/v2/ServiceVersionExample.java @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.storage.common.StorageSharedKeyCredential; + +import java.util.Locale; + +public class ServiceVersionExample { + + public static void main(String[] args) { + + // More information on these properties can be found in BasicExample.java + String accountName = SampleHelper.getAccountName(); + String accountKey = SampleHelper.getAccountKey(); + StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey); + String endpoint = String.format(Locale.ROOT, "https://%s.blob.core.windows.net", accountName); + + // Select the desired version and set it on the builder + BlobServiceVersion serviceVersion = BlobServiceVersion.V2019_02_02; + BlobServiceClient storageClient = new BlobServiceClientBuilder() + .serviceVersion(serviceVersion) + .endpoint(endpoint).credential(credential).buildClient(); + + // This service client may now be used as desired, and any service requests will target the specified version. + + /* + If the workload includes generating new SAS tokens using an older format, the version of the sas generation can + also be configured. Before starting the jvm, set the environment variable AZURE_STORAGE_SAS_SERVICE_VERSION or + the JVM system property AZURE_STORAGE_SAS_SERVICE_VERSION (e.g. -DAZURE_STORAGE_SAS_SERVICE_VERSION=2019-12-12) + to the service version which corresponds to the desired SAS format to configure this behavior. + */ + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample26/v1/SetMetadataAndHTTPHeadersExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample26/v1/SetMetadataAndHTTPHeadersExample.java new file mode 100644 index 000000000000..3a47878ed8c2 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample26/v1/SetMetadataAndHTTPHeadersExample.java @@ -0,0 +1,102 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.util.Context; +import com.azure.storage.blob.models.BlobHttpHeaders; +import com.azure.storage.blob.specialized.BlockBlobClient; +import com.azure.storage.common.StorageSharedKeyCredential; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Collections; +import java.util.Locale; +import java.util.Map; + +/** + * This example shows how to set metadata for containers and blobs and how to set HTTPHeaders for blobs using the Azure + * Storage Blob SDK for Java. + */ +public class SetMetadataAndHTTPHeadersExample { + + /** + * Entry point into the setting metadata examples for Storage blobs. + * + * @param args Unused. Arguments to the program. + * @throws IOException If an I/O error occurs + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public static void main(String[] args) throws IOException, NoSuchAlgorithmException { + String accountName = SampleHelper.getAccountName(); + String accountKey = SampleHelper.getAccountKey(); + + /* + * Use your Storage account's name and key to create a credential object; this is used to access your account. + */ + StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey); + + /* + * From the Azure portal, get your Storage account blob service URL endpoint. + * The URL typically looks like this: + */ + String endpoint = String.format(Locale.ROOT, "https://%s.blob.core.windows.net", accountName); + + /* + * Create a BlobServiceClient object that wraps the service endpoint, credential and a request pipeline. + */ + BlobServiceClient storageClient = new BlobServiceClientBuilder().endpoint(endpoint).credential(credential).buildClient(); + + /* + * Create a container client from storageClient. + */ + BlobContainerClient blobContainerClient = storageClient.getBlobContainerClient("mycontainer" + System.currentTimeMillis()); + + /* + * Setup containerMetadata for container. + */ + Map containerMetadata = Collections.singletonMap("mycontainermetadata", "sample"); + + /* + * Create a container with the containerMetadata above. + */ + blobContainerClient.createWithResponse(containerMetadata, null, null, new Context("key1", "value1")); + + /* + * Create a blob client. + */ + BlockBlobClient blobClient = blobContainerClient.getBlobClient("myblob" + System.currentTimeMillis()).getBlockBlobClient(); + + /* + * Create a blob with blob's blobMetadata and BlobHttpHeaders. + */ + Map blobMetadata = Collections.singletonMap("myblobmetadata", "sample"); + BlobHttpHeaders blobHTTPHeaders = new BlobHttpHeaders().setContentDisposition("attachment") + .setContentType("text/html; charset=utf-8"); + + + String data = "Hello world!"; + + /* + * Send an MD5 hash of the content to be validated by the service. + */ + byte[] md5 = MessageDigest.getInstance("MD5").digest(data.getBytes(StandardCharsets.UTF_8)); + + /* + * Data which will upload to block blob. + */ + InputStream dataStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); + blobClient.uploadWithResponse(dataStream, data.length(), blobHTTPHeaders, blobMetadata, null, md5, null, null, + null); + + /* + * Clean up the container and blob. + */ + blobClient.delete(); + blobContainerClient.delete(); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample26/v2/SetMetadataAndHTTPHeadersExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample26/v2/SetMetadataAndHTTPHeadersExample.java new file mode 100644 index 000000000000..3a47878ed8c2 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample26/v2/SetMetadataAndHTTPHeadersExample.java @@ -0,0 +1,102 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.util.Context; +import com.azure.storage.blob.models.BlobHttpHeaders; +import com.azure.storage.blob.specialized.BlockBlobClient; +import com.azure.storage.common.StorageSharedKeyCredential; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Collections; +import java.util.Locale; +import java.util.Map; + +/** + * This example shows how to set metadata for containers and blobs and how to set HTTPHeaders for blobs using the Azure + * Storage Blob SDK for Java. + */ +public class SetMetadataAndHTTPHeadersExample { + + /** + * Entry point into the setting metadata examples for Storage blobs. + * + * @param args Unused. Arguments to the program. + * @throws IOException If an I/O error occurs + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public static void main(String[] args) throws IOException, NoSuchAlgorithmException { + String accountName = SampleHelper.getAccountName(); + String accountKey = SampleHelper.getAccountKey(); + + /* + * Use your Storage account's name and key to create a credential object; this is used to access your account. + */ + StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey); + + /* + * From the Azure portal, get your Storage account blob service URL endpoint. + * The URL typically looks like this: + */ + String endpoint = String.format(Locale.ROOT, "https://%s.blob.core.windows.net", accountName); + + /* + * Create a BlobServiceClient object that wraps the service endpoint, credential and a request pipeline. + */ + BlobServiceClient storageClient = new BlobServiceClientBuilder().endpoint(endpoint).credential(credential).buildClient(); + + /* + * Create a container client from storageClient. + */ + BlobContainerClient blobContainerClient = storageClient.getBlobContainerClient("mycontainer" + System.currentTimeMillis()); + + /* + * Setup containerMetadata for container. + */ + Map containerMetadata = Collections.singletonMap("mycontainermetadata", "sample"); + + /* + * Create a container with the containerMetadata above. + */ + blobContainerClient.createWithResponse(containerMetadata, null, null, new Context("key1", "value1")); + + /* + * Create a blob client. + */ + BlockBlobClient blobClient = blobContainerClient.getBlobClient("myblob" + System.currentTimeMillis()).getBlockBlobClient(); + + /* + * Create a blob with blob's blobMetadata and BlobHttpHeaders. + */ + Map blobMetadata = Collections.singletonMap("myblobmetadata", "sample"); + BlobHttpHeaders blobHTTPHeaders = new BlobHttpHeaders().setContentDisposition("attachment") + .setContentType("text/html; charset=utf-8"); + + + String data = "Hello world!"; + + /* + * Send an MD5 hash of the content to be validated by the service. + */ + byte[] md5 = MessageDigest.getInstance("MD5").digest(data.getBytes(StandardCharsets.UTF_8)); + + /* + * Data which will upload to block blob. + */ + InputStream dataStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); + blobClient.uploadWithResponse(dataStream, data.length(), blobHTTPHeaders, blobMetadata, null, md5, null, null, + null); + + /* + * Clean up the container and blob. + */ + blobClient.delete(); + blobContainerClient.delete(); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample27/v1/StorageErrorHandlingExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample27/v1/StorageErrorHandlingExample.java new file mode 100644 index 000000000000..7e1d5bba8af1 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample27/v1/StorageErrorHandlingExample.java @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.http.HttpResponse; +import com.azure.storage.blob.models.BlobErrorCode; +import com.azure.storage.blob.models.BlobStorageException; + +/** + * This example shows how to handle errors thrown by various XxxURL methods. Any client-side error will be + * propagated unmodified. However, any response from the service with an unexpected status code will be wrapped in a + * StorageException. If the pipeline includes the RequestRetryFactory, which is the default, some of these errors + * will be automatically retried if it makes sense to do so. The StorageException type exposes rich error + * information returned by the service. + */ +public class StorageErrorHandlingExample { + + /** + * Entry point into error handling example for Storage blobs. + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + BlobContainerClient blobContainerClient = new BlobContainerClientBuilder().endpoint("https://account.blob.core.windows.net/mycontainer") + .buildClient(); + + try { + + /* + * An error occurred while creating the container. + */ + blobContainerClient.create(); + } catch (BlobStorageException e) { + + /* + * StorageErrorCode defines constants corresponding to all error codes returned by the service. + */ + if (e.getErrorCode() == BlobErrorCode.RESOURCE_NOT_FOUND) { + + /* + * Log more detailed information. + */ + System.out.println("Extended details: " + e.getStatusCode()); + + /* + * Examine the raw response. + */ + HttpResponse response = e.getResponse(); + System.out.println("Error creating the container with status code: " + response.getStatusCode()); + } else if (e.getErrorCode() == BlobErrorCode.CONTAINER_BEING_DELETED) { + + /* + * Log more detailed information. + */ + System.out.println("Extended details: " + e.getServiceMessage()); + + } else if (e.getErrorCode() == BlobErrorCode.CONTAINER_ALREADY_EXISTS) { + + /* + * Process the error. + */ + System.out.println("The container url is " + blobContainerClient.toString()); + } + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample27/v2/StorageErrorHandlingExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample27/v2/StorageErrorHandlingExample.java new file mode 100644 index 000000000000..7e1d5bba8af1 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample27/v2/StorageErrorHandlingExample.java @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.http.HttpResponse; +import com.azure.storage.blob.models.BlobErrorCode; +import com.azure.storage.blob.models.BlobStorageException; + +/** + * This example shows how to handle errors thrown by various XxxURL methods. Any client-side error will be + * propagated unmodified. However, any response from the service with an unexpected status code will be wrapped in a + * StorageException. If the pipeline includes the RequestRetryFactory, which is the default, some of these errors + * will be automatically retried if it makes sense to do so. The StorageException type exposes rich error + * information returned by the service. + */ +public class StorageErrorHandlingExample { + + /** + * Entry point into error handling example for Storage blobs. + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + BlobContainerClient blobContainerClient = new BlobContainerClientBuilder().endpoint("https://account.blob.core.windows.net/mycontainer") + .buildClient(); + + try { + + /* + * An error occurred while creating the container. + */ + blobContainerClient.create(); + } catch (BlobStorageException e) { + + /* + * StorageErrorCode defines constants corresponding to all error codes returned by the service. + */ + if (e.getErrorCode() == BlobErrorCode.RESOURCE_NOT_FOUND) { + + /* + * Log more detailed information. + */ + System.out.println("Extended details: " + e.getStatusCode()); + + /* + * Examine the raw response. + */ + HttpResponse response = e.getResponse(); + System.out.println("Error creating the container with status code: " + response.getStatusCode()); + } else if (e.getErrorCode() == BlobErrorCode.CONTAINER_BEING_DELETED) { + + /* + * Log more detailed information. + */ + System.out.println("Extended details: " + e.getServiceMessage()); + + } else if (e.getErrorCode() == BlobErrorCode.CONTAINER_ALREADY_EXISTS) { + + /* + * Process the error. + */ + System.out.println("The container url is " + blobContainerClient.toString()); + } + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample28/v1/StorageEventExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample28/v1/StorageEventExample.java new file mode 100644 index 000000000000..8fb144e274f5 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample28/v1/StorageEventExample.java @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.http.HttpPipelineCallContext; +import com.azure.core.http.HttpPipelineNextPolicy; +import com.azure.core.http.HttpPipelinePosition; +import com.azure.core.http.HttpRequest; +import com.azure.core.http.HttpResponse; +import com.azure.core.http.policy.HttpLoggingPolicy; +import com.azure.core.http.policy.HttpPipelinePolicy; +import reactor.core.publisher.Mono; + +import java.io.IOException; +import java.util.Optional; +import java.util.function.BiConsumer; +import java.util.function.Consumer; + +/** + * This examples shows how to approximate the StorageEvent behavior from the track 1 SDK. It is a general translation to + * achieve roughly the same results, but it is not an identical implementation. It may be modified to suit the use case. + * + * The general pattern is to create an {@link HttpPipelinePolicy} that will call the events at appropriate times. All + * requests pass through a pipeline, so any pipeline which contains an instance of this policy will be able to invoke + * the callbacks. Once the policy is defined, it must be set on the builder when constructing the clients. + * + * This sample can be run as is to demonstrate usage. Expected output is a console statement indicating the request + * being sent, the response being received, and (in the async case) the request completing. To demonstrate the retry and + * error handlers, uncomment the line {@code //.addPolicy(new ErrorPolicy())} when configuring the builder and run + * again. This will print out several retries and errors. The async segment will not run in this case as the eventual + * exception will terminate the program. + * + * The main areas of divergence from the original feature are: + * - It is only possible to use the sendingRequestHandler on an async client. + * - The callbacks do not all accept the same type as they did in the track 1 sdk and there is no StorageEvent type. + * - The SendingRequest events come after the signature here. In track 1, they came before the signature. It would be + * possible to create a second, near identical policy to put before the signature specifically for the SendingRequest + * event if that behavior is desirable. The policy shown here should then be modified to not duplicate that event. + * - Global handlers are not demonstrated here. They could be implemented in a very similar fashion by having some + * static fields on the policy object that are called alongside the instance fields. + */ +public class StorageEventExample { + + public static void main(String[] args) { + // Define the event handlers + Consumer sendingRequestHandler = + request -> System.out.println("Sending request " + request.getUrl()); + BiConsumer retryRequestHandler = + (request, retryNumber) -> System.out.println("Retrying request. " + request.getUrl() + " Attempt number " + + retryNumber); + BiConsumer responseReceivedHandler = + (request, response) -> System.out.println("Received response. Request " + request.getUrl() + "\nResponse " + + "status" + response.getStatusCode()); + BiConsumer errorHandler = + (request, t) -> System.out.println("Error. Request " + request.getUrl() + "\n " + t.getMessage()); + /* + If actions specific to the request type must be taken, the consumer type parameter should correspond to the type + returned by the api. + */ + Consumer requestCompleteHandler = + obj -> System.out.println("Request complete"); + + // Instantiate the policy that will invoke the handlers at the proper time + EventHandlerPolicy eventHandlerPolicy = new EventHandlerPolicy(sendingRequestHandler, retryRequestHandler, + responseReceivedHandler, errorHandler); + + // Create clients whose pipeline contains the new policy + BlobClientBuilder builder = new BlobClientBuilder() + .connectionString("") + .addPolicy(eventHandlerPolicy) + .addPolicy(new ErrorPolicy()) + .containerName("") + .blobName(""); + BlobClient bc = builder.buildClient(); + BlobAsyncClient bac = builder.buildAsyncClient(); + + // Use the client as usual, the handlers will now be automatically invoked at the proper times + bc.downloadContent(); + /* + The only way to use a requestCompleteHandler is to use the async client and set a side effect operator on the + return value. + */ + System.out.println("Async"); + bac.downloadWithResponse(null, null, null, false) + .doOnNext(requestCompleteHandler) + .block(); + } + + static class EventHandlerPolicy implements HttpPipelinePolicy { + + private final Consumer sendingRequestEvent; + private final BiConsumer retryRequestEvent; + private final BiConsumer responseReceivedEvent; + private final BiConsumer errorResponseEvent; + + EventHandlerPolicy(Consumer sendingRequestEvent, + BiConsumer retryRequestEvent, + BiConsumer responseReceivedEvent, + BiConsumer errorResponseEvent) { + this.sendingRequestEvent = sendingRequestEvent; + this.retryRequestEvent = retryRequestEvent; + this.responseReceivedEvent = responseReceivedEvent; + this.errorResponseEvent = errorResponseEvent; + } + + @Override + public Mono process(HttpPipelineCallContext httpPipelineCallContext, HttpPipelineNextPolicy httpPipelineNextPolicy) { + HttpRequest request = httpPipelineCallContext.getHttpRequest(); + /* + Check how many retries have gone out. Send an initial sendingRequest event or a retryRequest event as + appropriate. + This value is updated automatically by the retry policy before the request gets here + */ + Optional retryOptional = httpPipelineCallContext.getData(HttpLoggingPolicy.RETRY_COUNT_CONTEXT); + Integer retryCount = retryOptional.map(o -> (Integer) o).orElse(0); + if (retryCount <= 1) { + this.sendingRequestEvent.accept(request); + } else { + this.retryRequestEvent.accept(request, retryCount); + } + + // Set side-effect call backs to process the event without affecting the normal request-response flow + return httpPipelineNextPolicy.process() + .doOnNext(response -> this.responseReceivedEvent.accept(request, response)) + .doOnError(throwable -> this.errorResponseEvent.accept(request, throwable)); + } + + @Override + public HttpPipelinePosition getPipelinePosition() { + // This policy must be in a position to see each retry + return HttpPipelinePosition.PER_RETRY; + } + } + + /** + * A simple policy that always returns a retryable error to demonstrate retry and error event handlers + */ + static class ErrorPolicy implements HttpPipelinePolicy { + @Override + public Mono process(HttpPipelineCallContext httpPipelineCallContext, HttpPipelineNextPolicy httpPipelineNextPolicy) { + return Mono.error(new IOException("Dummy error")); + } + + @Override + public HttpPipelinePosition getPipelinePosition() { + return HttpPipelinePosition.PER_RETRY; + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample28/v2/StorageEventExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample28/v2/StorageEventExample.java new file mode 100644 index 000000000000..8fb144e274f5 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample28/v2/StorageEventExample.java @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.http.HttpPipelineCallContext; +import com.azure.core.http.HttpPipelineNextPolicy; +import com.azure.core.http.HttpPipelinePosition; +import com.azure.core.http.HttpRequest; +import com.azure.core.http.HttpResponse; +import com.azure.core.http.policy.HttpLoggingPolicy; +import com.azure.core.http.policy.HttpPipelinePolicy; +import reactor.core.publisher.Mono; + +import java.io.IOException; +import java.util.Optional; +import java.util.function.BiConsumer; +import java.util.function.Consumer; + +/** + * This examples shows how to approximate the StorageEvent behavior from the track 1 SDK. It is a general translation to + * achieve roughly the same results, but it is not an identical implementation. It may be modified to suit the use case. + * + * The general pattern is to create an {@link HttpPipelinePolicy} that will call the events at appropriate times. All + * requests pass through a pipeline, so any pipeline which contains an instance of this policy will be able to invoke + * the callbacks. Once the policy is defined, it must be set on the builder when constructing the clients. + * + * This sample can be run as is to demonstrate usage. Expected output is a console statement indicating the request + * being sent, the response being received, and (in the async case) the request completing. To demonstrate the retry and + * error handlers, uncomment the line {@code //.addPolicy(new ErrorPolicy())} when configuring the builder and run + * again. This will print out several retries and errors. The async segment will not run in this case as the eventual + * exception will terminate the program. + * + * The main areas of divergence from the original feature are: + * - It is only possible to use the sendingRequestHandler on an async client. + * - The callbacks do not all accept the same type as they did in the track 1 sdk and there is no StorageEvent type. + * - The SendingRequest events come after the signature here. In track 1, they came before the signature. It would be + * possible to create a second, near identical policy to put before the signature specifically for the SendingRequest + * event if that behavior is desirable. The policy shown here should then be modified to not duplicate that event. + * - Global handlers are not demonstrated here. They could be implemented in a very similar fashion by having some + * static fields on the policy object that are called alongside the instance fields. + */ +public class StorageEventExample { + + public static void main(String[] args) { + // Define the event handlers + Consumer sendingRequestHandler = + request -> System.out.println("Sending request " + request.getUrl()); + BiConsumer retryRequestHandler = + (request, retryNumber) -> System.out.println("Retrying request. " + request.getUrl() + " Attempt number " + + retryNumber); + BiConsumer responseReceivedHandler = + (request, response) -> System.out.println("Received response. Request " + request.getUrl() + "\nResponse " + + "status" + response.getStatusCode()); + BiConsumer errorHandler = + (request, t) -> System.out.println("Error. Request " + request.getUrl() + "\n " + t.getMessage()); + /* + If actions specific to the request type must be taken, the consumer type parameter should correspond to the type + returned by the api. + */ + Consumer requestCompleteHandler = + obj -> System.out.println("Request complete"); + + // Instantiate the policy that will invoke the handlers at the proper time + EventHandlerPolicy eventHandlerPolicy = new EventHandlerPolicy(sendingRequestHandler, retryRequestHandler, + responseReceivedHandler, errorHandler); + + // Create clients whose pipeline contains the new policy + BlobClientBuilder builder = new BlobClientBuilder() + .connectionString("") + .addPolicy(eventHandlerPolicy) + .addPolicy(new ErrorPolicy()) + .containerName("") + .blobName(""); + BlobClient bc = builder.buildClient(); + BlobAsyncClient bac = builder.buildAsyncClient(); + + // Use the client as usual, the handlers will now be automatically invoked at the proper times + bc.downloadContent(); + /* + The only way to use a requestCompleteHandler is to use the async client and set a side effect operator on the + return value. + */ + System.out.println("Async"); + bac.downloadWithResponse(null, null, null, false) + .doOnNext(requestCompleteHandler) + .block(); + } + + static class EventHandlerPolicy implements HttpPipelinePolicy { + + private final Consumer sendingRequestEvent; + private final BiConsumer retryRequestEvent; + private final BiConsumer responseReceivedEvent; + private final BiConsumer errorResponseEvent; + + EventHandlerPolicy(Consumer sendingRequestEvent, + BiConsumer retryRequestEvent, + BiConsumer responseReceivedEvent, + BiConsumer errorResponseEvent) { + this.sendingRequestEvent = sendingRequestEvent; + this.retryRequestEvent = retryRequestEvent; + this.responseReceivedEvent = responseReceivedEvent; + this.errorResponseEvent = errorResponseEvent; + } + + @Override + public Mono process(HttpPipelineCallContext httpPipelineCallContext, HttpPipelineNextPolicy httpPipelineNextPolicy) { + HttpRequest request = httpPipelineCallContext.getHttpRequest(); + /* + Check how many retries have gone out. Send an initial sendingRequest event or a retryRequest event as + appropriate. + This value is updated automatically by the retry policy before the request gets here + */ + Optional retryOptional = httpPipelineCallContext.getData(HttpLoggingPolicy.RETRY_COUNT_CONTEXT); + Integer retryCount = retryOptional.map(o -> (Integer) o).orElse(0); + if (retryCount <= 1) { + this.sendingRequestEvent.accept(request); + } else { + this.retryRequestEvent.accept(request, retryCount); + } + + // Set side-effect call backs to process the event without affecting the normal request-response flow + return httpPipelineNextPolicy.process() + .doOnNext(response -> this.responseReceivedEvent.accept(request, response)) + .doOnError(throwable -> this.errorResponseEvent.accept(request, throwable)); + } + + @Override + public HttpPipelinePosition getPipelinePosition() { + // This policy must be in a position to see each retry + return HttpPipelinePosition.PER_RETRY; + } + } + + /** + * A simple policy that always returns a retryable error to demonstrate retry and error event handlers + */ + static class ErrorPolicy implements HttpPipelinePolicy { + @Override + public Mono process(HttpPipelineCallContext httpPipelineCallContext, HttpPipelineNextPolicy httpPipelineNextPolicy) { + return Mono.error(new IOException("Dummy error")); + } + + @Override + public HttpPipelinePosition getPipelinePosition() { + return HttpPipelinePosition.PER_RETRY; + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample29/v1/AppendBlobAsyncClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample29/v1/AppendBlobAsyncClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..b3803fd60160 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample29/v1/AppendBlobAsyncClientJavaDocCodeSnippets.java @@ -0,0 +1,218 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob.specialized; + +import com.azure.storage.blob.options.AppendBlobCreateOptions; +import com.azure.storage.blob.models.AppendBlobRequestConditions; +import com.azure.storage.blob.models.BlobHttpHeaders; +import com.azure.storage.blob.models.BlobRange; +import com.azure.storage.blob.models.BlobRequestConditions; +import com.azure.storage.blob.options.AppendBlobSealOptions; +import com.azure.storage.blob.options.AppendBlobAppendBlockFromUrlOptions; +import reactor.core.publisher.Flux; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.OffsetDateTime; +import java.util.Collections; +import java.util.Map; + +/** + * Code snippets for {@link AppendBlobAsyncClient} + */ +public class AppendBlobAsyncClientJavaDocCodeSnippets { + private AppendBlobAsyncClient client = new SpecializedBlobClientBuilder().buildAppendBlobAsyncClient(); + private String leaseId = "leaseId"; + private Flux data = Flux.just(ByteBuffer.wrap("data".getBytes(StandardCharsets.UTF_8))); + private long length = 4L; + private static final Long POSITION = null; + private Long maxSize = length; + private String sourceUrl = "https://example.com"; + private long offset = 1024; + private long count = 1024; + + /** + * Code snippet for {@link AppendBlobAsyncClient#create()} + */ + public void create() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobAsyncClient.create + client.create().subscribe(response -> + System.out.printf("Created AppendBlob at %s%n", response.getLastModified())); + // END: com.azure.storage.blob.specialized.AppendBlobAsyncClient.create + } + + /** + * Code snippet for {@link AppendBlobAsyncClient#create(boolean)} + */ + public void createWithOverwrite() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobAsyncClient.create#boolean + boolean overwrite = false; // Default behavior + client.create(overwrite).subscribe(response -> + System.out.printf("Created AppendBlob at %s%n", response.getLastModified())); + // END: com.azure.storage.blob.specialized.AppendBlobAsyncClient.create#boolean + } + + /** + * Code snippet for {@link AppendBlobAsyncClient#createWithResponse(BlobHttpHeaders, Map, BlobRequestConditions)} + */ + public void create2() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobAsyncClient.createWithResponse#BlobHttpHeaders-Map-BlobRequestConditions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentType("binary") + .setContentLanguage("en-US"); + Map metadata = Collections.singletonMap("metadata", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.createWithResponse(headers, metadata, requestConditions).subscribe(response -> + System.out.printf("Created AppendBlob at %s%n", response.getValue().getLastModified())); + // END: com.azure.storage.blob.specialized.AppendBlobAsyncClient.createWithResponse#BlobHttpHeaders-Map-BlobRequestConditions + } + + /** + * Code snippet for {@link AppendBlobAsyncClient#createWithResponse(AppendBlobCreateOptions)} + */ + public void create3() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobAsyncClient.createWithResponse#AppendBlobCreateOptions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentType("binary") + .setContentLanguage("en-US"); + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.createWithResponse(new AppendBlobCreateOptions().setHeaders(headers).setMetadata(metadata) + .setTags(tags).setRequestConditions(requestConditions)).subscribe(response -> + System.out.printf("Created AppendBlob at %s%n", response.getValue().getLastModified())); + // END: com.azure.storage.blob.specialized.AppendBlobAsyncClient.createWithResponse#AppendBlobCreateOptions + } + + /** + * Code snippet for {@link AppendBlobAsyncClient#appendBlock(Flux, long)} + */ + public void appendBlock() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobAsyncClient.appendBlock#Flux-long + client.appendBlock(data, length).subscribe(response -> + System.out.printf("AppendBlob has %d committed blocks%n", response.getBlobCommittedBlockCount())); + // END: com.azure.storage.blob.specialized.AppendBlobAsyncClient.appendBlock#Flux-long + } + + /** + * Code snippet for {@link AppendBlobAsyncClient#appendBlockWithResponse(Flux, long, byte[], AppendBlobRequestConditions)} + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public void appendBlock2() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobAsyncClient.appendBlockWithResponse#Flux-long-byte-AppendBlobRequestConditions + byte[] md5 = MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8)); + AppendBlobRequestConditions requestConditions = new AppendBlobRequestConditions() + .setAppendPosition(POSITION) + .setMaxSize(maxSize); + + client.appendBlockWithResponse(data, length, md5, requestConditions).subscribe(response -> + System.out.printf("AppendBlob has %d committed blocks%n", response.getValue().getBlobCommittedBlockCount())); + // END: com.azure.storage.blob.specialized.AppendBlobAsyncClient.appendBlockWithResponse#Flux-long-byte-AppendBlobRequestConditions + } + + /** + * Code snippet for {@link AppendBlobAsyncClient#appendBlockFromUrl(String, BlobRange)} + */ + public void appendBlockFromUrl() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobAsyncClient.appendBlockFromUrl#String-BlobRange + client.appendBlockFromUrl(sourceUrl, new BlobRange(offset, count)).subscribe(response -> + System.out.printf("AppendBlob has %d committed blocks%n", response.getBlobCommittedBlockCount())); + // END: com.azure.storage.blob.specialized.AppendBlobAsyncClient.appendBlockFromUrl#String-BlobRange + } + + /** + * Code snippet for {@link AppendBlobAsyncClient#appendBlockFromUrlWithResponse(String, BlobRange, byte[], AppendBlobRequestConditions, BlobRequestConditions)} + */ + public void appendBlockFromUrl2() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobAsyncClient.appendBlockFromUrlWithResponse#String-BlobRange-byte-AppendBlobRequestConditions-BlobRequestConditions + AppendBlobRequestConditions appendBlobRequestConditions = new AppendBlobRequestConditions() + .setAppendPosition(POSITION) + .setMaxSize(maxSize); + + BlobRequestConditions modifiedRequestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.appendBlockFromUrlWithResponse(sourceUrl, new BlobRange(offset, count), null, + appendBlobRequestConditions, modifiedRequestConditions).subscribe(response -> + System.out.printf("AppendBlob has %d committed blocks%n", response.getValue().getBlobCommittedBlockCount())); + // END: com.azure.storage.blob.specialized.AppendBlobAsyncClient.appendBlockFromUrlWithResponse#String-BlobRange-byte-AppendBlobRequestConditions-BlobRequestConditions + } + + /** + * Code snippet for {@link AppendBlobAsyncClient#appendBlockFromUrlWithResponse(String, BlobRange, byte[], AppendBlobRequestConditions, BlobRequestConditions)} + */ + public void appendBlockFromUrlOptionBag() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobAsyncClient.appendBlockFromUrlWithResponse#AppendBlobAppendBlockFromUrlOptions + AppendBlobRequestConditions appendBlobRequestConditions = new AppendBlobRequestConditions() + .setAppendPosition(POSITION) + .setMaxSize(maxSize); + + BlobRequestConditions modifiedRequestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.appendBlockFromUrlWithResponse(new AppendBlobAppendBlockFromUrlOptions(sourceUrl) + .setSourceRange(new BlobRange(offset, count)) + .setDestinationRequestConditions(appendBlobRequestConditions) + .setSourceRequestConditions(modifiedRequestConditions)).subscribe(response -> + System.out.printf("AppendBlob has %d committed blocks%n", response.getValue().getBlobCommittedBlockCount())); + // END: com.azure.storage.blob.specialized.AppendBlobAsyncClient.appendBlockFromUrlWithResponse#AppendBlobAppendBlockFromUrlOptions + } + + /** + * Code snippet for {@link AppendBlobAsyncClient#seal()} + */ + public void seal() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobAsyncClient.seal + client.seal().subscribe(response -> System.out.println("Sealed AppendBlob")); + // END: com.azure.storage.blob.specialized.AppendBlobAsyncClient.seal + } + + /** + * Code snippet for {@link AppendBlobAsyncClient#sealWithResponse(AppendBlobSealOptions)} + */ + public void seal2() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobAsyncClient.sealWithResponse#AppendBlobSealOptions + AppendBlobRequestConditions requestConditions = new AppendBlobRequestConditions().setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.sealWithResponse(new AppendBlobSealOptions().setRequestConditions(requestConditions)) + .subscribe(response -> System.out.println("Sealed AppendBlob")); + // END: com.azure.storage.blob.specialized.AppendBlobAsyncClient.sealWithResponse#AppendBlobSealOptions + } + + /** + * Code snippet for {@link AppendBlobAsyncClient#createIfNotExists()} and + * {@link AppendBlobAsyncClient#createIfNotExistsWithResponse(AppendBlobCreateOptions)} + */ + public void createIfNotExistsCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobAsyncClient.createIfNotExists + client.createIfNotExists().subscribe(response -> + System.out.printf("Created AppendBlob at %s%n", response.getLastModified())); + // END: com.azure.storage.blob.specialized.AppendBlobAsyncClient.createIfNotExists + + // BEGIN: com.azure.storage.blob.specialized.AppendBlobAsyncClient.createIfNotExistsWithResponse#AppendBlobCreateOptions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentType("binary") + .setContentLanguage("en-US"); + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + + client.createIfNotExistsWithResponse(new AppendBlobCreateOptions().setHeaders(headers) + .setMetadata(metadata).setTags(tags)).subscribe(response -> { + if (response.getStatusCode() == 409) { + System.out.println("Already exists."); + } else { + System.out.println("successfully created."); + } + }); + // END: com.azure.storage.blob.specialized.AppendBlobAsyncClient.createIfNotExistsWithResponse#AppendBlobCreateOptions + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample29/v2/AppendBlobAsyncClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample29/v2/AppendBlobAsyncClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..b3803fd60160 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample29/v2/AppendBlobAsyncClientJavaDocCodeSnippets.java @@ -0,0 +1,218 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob.specialized; + +import com.azure.storage.blob.options.AppendBlobCreateOptions; +import com.azure.storage.blob.models.AppendBlobRequestConditions; +import com.azure.storage.blob.models.BlobHttpHeaders; +import com.azure.storage.blob.models.BlobRange; +import com.azure.storage.blob.models.BlobRequestConditions; +import com.azure.storage.blob.options.AppendBlobSealOptions; +import com.azure.storage.blob.options.AppendBlobAppendBlockFromUrlOptions; +import reactor.core.publisher.Flux; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.OffsetDateTime; +import java.util.Collections; +import java.util.Map; + +/** + * Code snippets for {@link AppendBlobAsyncClient} + */ +public class AppendBlobAsyncClientJavaDocCodeSnippets { + private AppendBlobAsyncClient client = new SpecializedBlobClientBuilder().buildAppendBlobAsyncClient(); + private String leaseId = "leaseId"; + private Flux data = Flux.just(ByteBuffer.wrap("data".getBytes(StandardCharsets.UTF_8))); + private long length = 4L; + private static final Long POSITION = null; + private Long maxSize = length; + private String sourceUrl = "https://example.com"; + private long offset = 1024; + private long count = 1024; + + /** + * Code snippet for {@link AppendBlobAsyncClient#create()} + */ + public void create() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobAsyncClient.create + client.create().subscribe(response -> + System.out.printf("Created AppendBlob at %s%n", response.getLastModified())); + // END: com.azure.storage.blob.specialized.AppendBlobAsyncClient.create + } + + /** + * Code snippet for {@link AppendBlobAsyncClient#create(boolean)} + */ + public void createWithOverwrite() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobAsyncClient.create#boolean + boolean overwrite = false; // Default behavior + client.create(overwrite).subscribe(response -> + System.out.printf("Created AppendBlob at %s%n", response.getLastModified())); + // END: com.azure.storage.blob.specialized.AppendBlobAsyncClient.create#boolean + } + + /** + * Code snippet for {@link AppendBlobAsyncClient#createWithResponse(BlobHttpHeaders, Map, BlobRequestConditions)} + */ + public void create2() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobAsyncClient.createWithResponse#BlobHttpHeaders-Map-BlobRequestConditions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentType("binary") + .setContentLanguage("en-US"); + Map metadata = Collections.singletonMap("metadata", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.createWithResponse(headers, metadata, requestConditions).subscribe(response -> + System.out.printf("Created AppendBlob at %s%n", response.getValue().getLastModified())); + // END: com.azure.storage.blob.specialized.AppendBlobAsyncClient.createWithResponse#BlobHttpHeaders-Map-BlobRequestConditions + } + + /** + * Code snippet for {@link AppendBlobAsyncClient#createWithResponse(AppendBlobCreateOptions)} + */ + public void create3() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobAsyncClient.createWithResponse#AppendBlobCreateOptions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentType("binary") + .setContentLanguage("en-US"); + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.createWithResponse(new AppendBlobCreateOptions().setHeaders(headers).setMetadata(metadata) + .setTags(tags).setRequestConditions(requestConditions)).subscribe(response -> + System.out.printf("Created AppendBlob at %s%n", response.getValue().getLastModified())); + // END: com.azure.storage.blob.specialized.AppendBlobAsyncClient.createWithResponse#AppendBlobCreateOptions + } + + /** + * Code snippet for {@link AppendBlobAsyncClient#appendBlock(Flux, long)} + */ + public void appendBlock() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobAsyncClient.appendBlock#Flux-long + client.appendBlock(data, length).subscribe(response -> + System.out.printf("AppendBlob has %d committed blocks%n", response.getBlobCommittedBlockCount())); + // END: com.azure.storage.blob.specialized.AppendBlobAsyncClient.appendBlock#Flux-long + } + + /** + * Code snippet for {@link AppendBlobAsyncClient#appendBlockWithResponse(Flux, long, byte[], AppendBlobRequestConditions)} + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public void appendBlock2() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobAsyncClient.appendBlockWithResponse#Flux-long-byte-AppendBlobRequestConditions + byte[] md5 = MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8)); + AppendBlobRequestConditions requestConditions = new AppendBlobRequestConditions() + .setAppendPosition(POSITION) + .setMaxSize(maxSize); + + client.appendBlockWithResponse(data, length, md5, requestConditions).subscribe(response -> + System.out.printf("AppendBlob has %d committed blocks%n", response.getValue().getBlobCommittedBlockCount())); + // END: com.azure.storage.blob.specialized.AppendBlobAsyncClient.appendBlockWithResponse#Flux-long-byte-AppendBlobRequestConditions + } + + /** + * Code snippet for {@link AppendBlobAsyncClient#appendBlockFromUrl(String, BlobRange)} + */ + public void appendBlockFromUrl() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobAsyncClient.appendBlockFromUrl#String-BlobRange + client.appendBlockFromUrl(sourceUrl, new BlobRange(offset, count)).subscribe(response -> + System.out.printf("AppendBlob has %d committed blocks%n", response.getBlobCommittedBlockCount())); + // END: com.azure.storage.blob.specialized.AppendBlobAsyncClient.appendBlockFromUrl#String-BlobRange + } + + /** + * Code snippet for {@link AppendBlobAsyncClient#appendBlockFromUrlWithResponse(String, BlobRange, byte[], AppendBlobRequestConditions, BlobRequestConditions)} + */ + public void appendBlockFromUrl2() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobAsyncClient.appendBlockFromUrlWithResponse#String-BlobRange-byte-AppendBlobRequestConditions-BlobRequestConditions + AppendBlobRequestConditions appendBlobRequestConditions = new AppendBlobRequestConditions() + .setAppendPosition(POSITION) + .setMaxSize(maxSize); + + BlobRequestConditions modifiedRequestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.appendBlockFromUrlWithResponse(sourceUrl, new BlobRange(offset, count), null, + appendBlobRequestConditions, modifiedRequestConditions).subscribe(response -> + System.out.printf("AppendBlob has %d committed blocks%n", response.getValue().getBlobCommittedBlockCount())); + // END: com.azure.storage.blob.specialized.AppendBlobAsyncClient.appendBlockFromUrlWithResponse#String-BlobRange-byte-AppendBlobRequestConditions-BlobRequestConditions + } + + /** + * Code snippet for {@link AppendBlobAsyncClient#appendBlockFromUrlWithResponse(String, BlobRange, byte[], AppendBlobRequestConditions, BlobRequestConditions)} + */ + public void appendBlockFromUrlOptionBag() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobAsyncClient.appendBlockFromUrlWithResponse#AppendBlobAppendBlockFromUrlOptions + AppendBlobRequestConditions appendBlobRequestConditions = new AppendBlobRequestConditions() + .setAppendPosition(POSITION) + .setMaxSize(maxSize); + + BlobRequestConditions modifiedRequestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.appendBlockFromUrlWithResponse(new AppendBlobAppendBlockFromUrlOptions(sourceUrl) + .setSourceRange(new BlobRange(offset, count)) + .setDestinationRequestConditions(appendBlobRequestConditions) + .setSourceRequestConditions(modifiedRequestConditions)).subscribe(response -> + System.out.printf("AppendBlob has %d committed blocks%n", response.getValue().getBlobCommittedBlockCount())); + // END: com.azure.storage.blob.specialized.AppendBlobAsyncClient.appendBlockFromUrlWithResponse#AppendBlobAppendBlockFromUrlOptions + } + + /** + * Code snippet for {@link AppendBlobAsyncClient#seal()} + */ + public void seal() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobAsyncClient.seal + client.seal().subscribe(response -> System.out.println("Sealed AppendBlob")); + // END: com.azure.storage.blob.specialized.AppendBlobAsyncClient.seal + } + + /** + * Code snippet for {@link AppendBlobAsyncClient#sealWithResponse(AppendBlobSealOptions)} + */ + public void seal2() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobAsyncClient.sealWithResponse#AppendBlobSealOptions + AppendBlobRequestConditions requestConditions = new AppendBlobRequestConditions().setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.sealWithResponse(new AppendBlobSealOptions().setRequestConditions(requestConditions)) + .subscribe(response -> System.out.println("Sealed AppendBlob")); + // END: com.azure.storage.blob.specialized.AppendBlobAsyncClient.sealWithResponse#AppendBlobSealOptions + } + + /** + * Code snippet for {@link AppendBlobAsyncClient#createIfNotExists()} and + * {@link AppendBlobAsyncClient#createIfNotExistsWithResponse(AppendBlobCreateOptions)} + */ + public void createIfNotExistsCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobAsyncClient.createIfNotExists + client.createIfNotExists().subscribe(response -> + System.out.printf("Created AppendBlob at %s%n", response.getLastModified())); + // END: com.azure.storage.blob.specialized.AppendBlobAsyncClient.createIfNotExists + + // BEGIN: com.azure.storage.blob.specialized.AppendBlobAsyncClient.createIfNotExistsWithResponse#AppendBlobCreateOptions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentType("binary") + .setContentLanguage("en-US"); + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + + client.createIfNotExistsWithResponse(new AppendBlobCreateOptions().setHeaders(headers) + .setMetadata(metadata).setTags(tags)).subscribe(response -> { + if (response.getStatusCode() == 409) { + System.out.println("Already exists."); + } else { + System.out.println("successfully created."); + } + }); + // END: com.azure.storage.blob.specialized.AppendBlobAsyncClient.createIfNotExistsWithResponse#AppendBlobCreateOptions + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample3/v1/AzureIdentityExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample3/v1/AzureIdentityExample.java new file mode 100644 index 000000000000..d5c581dc9610 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample3/v1/AzureIdentityExample.java @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.identity.DefaultAzureCredentialBuilder; + +import java.util.Locale; + +/** + * Creates default DefaultAzureCredential instance to use. This will use AZURE_CLIENT_ID, + * AZURE_CLIENT_SECRET, and AZURE_TENANT_ID environment variables to create a + * ClientSecretCredential. + */ +public class AzureIdentityExample { + + /** + * Entry point into the Azure Identity example for Storage blobs. + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + String accountName = SampleHelper.getAccountName(); + + /* + * From the Azure portal, get your Storage account blob service URL endpoint. + * The URL typically looks like this: + */ + String endpoint = String.format(Locale.ROOT, "https://%s.blob.core.windows.net", accountName); + + /* + * Create a storage client using the Azure Identity credentials. + */ + BlobServiceClient storageClient = new BlobServiceClientBuilder() + .endpoint(endpoint) + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + System.out.println("Successfully setup client using the Azure Identity, please check the service version: " + + storageClient.getProperties().getDefaultServiceVersion()); + + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample3/v2/AzureIdentityExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample3/v2/AzureIdentityExample.java new file mode 100644 index 000000000000..d5c581dc9610 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample3/v2/AzureIdentityExample.java @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.identity.DefaultAzureCredentialBuilder; + +import java.util.Locale; + +/** + * Creates default DefaultAzureCredential instance to use. This will use AZURE_CLIENT_ID, + * AZURE_CLIENT_SECRET, and AZURE_TENANT_ID environment variables to create a + * ClientSecretCredential. + */ +public class AzureIdentityExample { + + /** + * Entry point into the Azure Identity example for Storage blobs. + * @param args Unused. Arguments to the program. + */ + public static void main(String[] args) { + String accountName = SampleHelper.getAccountName(); + + /* + * From the Azure portal, get your Storage account blob service URL endpoint. + * The URL typically looks like this: + */ + String endpoint = String.format(Locale.ROOT, "https://%s.blob.core.windows.net", accountName); + + /* + * Create a storage client using the Azure Identity credentials. + */ + BlobServiceClient storageClient = new BlobServiceClientBuilder() + .endpoint(endpoint) + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + System.out.println("Successfully setup client using the Azure Identity, please check the service version: " + + storageClient.getProperties().getDefaultServiceVersion()); + + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample30/v1/AppendBlobClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample30/v1/AppendBlobClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..e03fef303d9c --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample30/v1/AppendBlobClientJavaDocCodeSnippets.java @@ -0,0 +1,242 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob.specialized; + +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.storage.blob.models.AppendBlobItem; +import com.azure.storage.blob.options.AppendBlobCreateOptions; +import com.azure.storage.blob.models.AppendBlobRequestConditions; +import com.azure.storage.blob.models.BlobHttpHeaders; +import com.azure.storage.blob.models.BlobRange; +import com.azure.storage.blob.models.BlobRequestConditions; +import com.azure.storage.blob.options.AppendBlobSealOptions; +import com.azure.storage.blob.options.AppendBlobAppendBlockFromUrlOptions; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Collections; +import java.util.Map; + +/** + * Code snippets for {@link AppendBlobClient} + */ +public class AppendBlobClientJavaDocCodeSnippets { + + private AppendBlobClient client = new SpecializedBlobClientBuilder().buildAppendBlobClient(); + private Duration timeout = Duration.ofSeconds(30); + private String leaseId = "leaseId"; + private InputStream data = new ByteArrayInputStream("data".getBytes(StandardCharsets.UTF_8)); + private long length = 4L; + private static final Long POSITION = null; + private Long maxSize = length; + private String sourceUrl = "https://example.com"; + private long offset = 1024; + private long count = 1024; + + /** + * Code snippet for {@link AppendBlobClient#create()} + */ + public void create() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobClient.create + System.out.printf("Created AppendBlob at %s%n", client.create().getLastModified()); + // END: com.azure.storage.blob.specialized.AppendBlobClient.create + } + + /** + * Code snippet for {@link AppendBlobClient#create(boolean)} + */ + public void createWithOverwrite() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobClient.create#boolean + boolean overwrite = false; // Default value + System.out.printf("Created AppendBlob at %s%n", client.create(overwrite).getLastModified()); + // END: com.azure.storage.blob.specialized.AppendBlobClient.create#boolean + } + + /** + * Code snippet for {@link AppendBlobClient#createWithResponse(BlobHttpHeaders, Map, BlobRequestConditions, + * Duration, Context)} + */ + public void createWithResponse() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobClient.createWithResponse#BlobHttpHeaders-Map-BlobRequestConditions-Duration-Context + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentType("binary") + .setContentLanguage("en-US"); + Map metadata = Collections.singletonMap("metadata", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context("key", "value"); + + System.out.printf("Created AppendBlob at %s%n", + client.createWithResponse(headers, metadata, requestConditions, timeout, context).getValue() + .getLastModified()); + // END: com.azure.storage.blob.specialized.AppendBlobClient.createWithResponse#BlobHttpHeaders-Map-BlobRequestConditions-Duration-Context + } + + /** + * Code snippet for {@link AppendBlobClient#createWithResponse(AppendBlobCreateOptions, Duration, Context)} + */ + public void createWithResponse2() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobClient.createWithResponse#AppendBlobCreateOptions-Duration-Context + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentType("binary") + .setContentLanguage("en-US"); + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tags", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context("key", "value"); + + System.out.printf("Created AppendBlob at %s%n", + client.createWithResponse(new AppendBlobCreateOptions().setHeaders(headers).setMetadata(metadata) + .setTags(tags).setRequestConditions(requestConditions), timeout, context).getValue() + .getLastModified()); + // END: com.azure.storage.blob.specialized.AppendBlobClient.createWithResponse#AppendBlobCreateOptions-Duration-Context + } + + /** + * Code snippet for {@link AppendBlobClient#appendBlock(InputStream, long)} + */ + public void appendBlock() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobClient.appendBlock#InputStream-long + System.out.printf("AppendBlob has %d committed blocks%n", + client.appendBlock(data, length).getBlobCommittedBlockCount()); + // END: com.azure.storage.blob.specialized.AppendBlobClient.appendBlock#InputStream-long + } + + /** + * Code snippet for {@link AppendBlobClient#appendBlockWithResponse(InputStream, long, byte[], + * AppendBlobRequestConditions, Duration, Context)} + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public void appendBlock2() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobClient.appendBlockWithResponse#InputStream-long-byte-AppendBlobRequestConditions-Duration-Context + byte[] md5 = MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8)); + AppendBlobRequestConditions requestConditions = new AppendBlobRequestConditions() + .setAppendPosition(POSITION) + .setMaxSize(maxSize); + Context context = new Context("key", "value"); + + System.out.printf("AppendBlob has %d committed blocks%n", + client.appendBlockWithResponse(data, length, md5, requestConditions, timeout, context) + .getValue().getBlobCommittedBlockCount()); + // END: com.azure.storage.blob.specialized.AppendBlobClient.appendBlockWithResponse#InputStream-long-byte-AppendBlobRequestConditions-Duration-Context + } + + /** + * Code snippet for {@link AppendBlobClient#appendBlockFromUrl(String, BlobRange)} + */ + public void appendBlockFromUrl() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobClient.appendBlockFromUrl#String-BlobRange + System.out.printf("AppendBlob has %d committed blocks%n", + client.appendBlockFromUrl(sourceUrl, new BlobRange(offset, count)).getBlobCommittedBlockCount()); + // END: com.azure.storage.blob.specialized.AppendBlobClient.appendBlockFromUrl#String-BlobRange + } + + /** + * Code snippet for {@link AppendBlobClient#appendBlockFromUrlWithResponse(String, BlobRange, byte[], + * AppendBlobRequestConditions, BlobRequestConditions, Duration, Context)} + */ + public void appendBlockFromUrlWithResponse() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobClient.appendBlockFromUrlWithResponse#String-BlobRange-byte-AppendBlobRequestConditions-BlobRequestConditions-Duration-Context + AppendBlobRequestConditions appendBlobRequestConditions = new AppendBlobRequestConditions() + .setAppendPosition(POSITION) + .setMaxSize(maxSize); + + BlobRequestConditions modifiedRequestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + Context context = new Context("key", "value"); + + System.out.printf("AppendBlob has %d committed blocks%n", + client.appendBlockFromUrlWithResponse(sourceUrl, new BlobRange(offset, count), null, + appendBlobRequestConditions, modifiedRequestConditions, timeout, + context).getValue().getBlobCommittedBlockCount()); + // END: com.azure.storage.blob.specialized.AppendBlobClient.appendBlockFromUrlWithResponse#String-BlobRange-byte-AppendBlobRequestConditions-BlobRequestConditions-Duration-Context + } + + /** + * Code snippet for {@link AppendBlobClient#appendBlockFromUrlWithResponse(String, BlobRange, byte[], + * AppendBlobRequestConditions, BlobRequestConditions, Duration, Context)} + */ + public void appendBlockFromUrlOptionsBagWithResponse() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobClient.appendBlockFromUrlWithResponse#AppendBlobAppendBlockFromUrlOptions-Duration-Context + AppendBlobRequestConditions appendBlobRequestConditions = new AppendBlobRequestConditions() + .setAppendPosition(POSITION) + .setMaxSize(maxSize); + + BlobRequestConditions modifiedRequestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + Context context = new Context("key", "value"); + + System.out.printf("AppendBlob has %d committed blocks%n", + client.appendBlockFromUrlWithResponse(new AppendBlobAppendBlockFromUrlOptions(sourceUrl) + .setSourceRange(new BlobRange(offset, count)) + .setDestinationRequestConditions(appendBlobRequestConditions) + .setSourceRequestConditions(modifiedRequestConditions), timeout, + context).getValue().getBlobCommittedBlockCount()); + // END: com.azure.storage.blob.specialized.AppendBlobClient.appendBlockFromUrlWithResponse#AppendBlobAppendBlockFromUrlOptions-Duration-Context + } + + /** + * Code snippet for {@link AppendBlobClient#seal()} + */ + public void seal() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobClient.seal + client.seal(); + System.out.println("Sealed AppendBlob"); + // END: com.azure.storage.blob.specialized.AppendBlobClient.seal + } + + /** + * Code snippet for {@link AppendBlobClient#sealWithResponse(AppendBlobSealOptions, Duration, Context)} + */ + public void seal2() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobClient.sealWithResponse#AppendBlobSealOptions-Duration-Context + AppendBlobRequestConditions requestConditions = new AppendBlobRequestConditions().setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context("key", "value"); + + client.sealWithResponse(new AppendBlobSealOptions().setRequestConditions(requestConditions), timeout, context); + System.out.println("Sealed AppendBlob"); + // END: com.azure.storage.blob.specialized.AppendBlobClient.sealWithResponse#AppendBlobSealOptions-Duration-Context + } + + /** + * Code snippet for {@link AppendBlobClient#createIfNotExists()} and + * {@link AppendBlobClient#createIfNotExistsWithResponse(AppendBlobCreateOptions, Duration, Context)} + */ + public void createIfNotExistsCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobClient.createIfNotExists + client.createIfNotExists(); + System.out.println("Created AppendBlob"); + // END: com.azure.storage.blob.specialized.AppendBlobClient.createIfNotExists + + // BEGIN: com.azure.storage.blob.specialized.AppendBlobClient.createIfNotExistsWithResponse#AppendBlobCreateOptions-Duration-Context + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentType("binary") + .setContentLanguage("en-US"); + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tags", "value"); + Context context = new Context("key", "value"); + + Response response = client.createIfNotExistsWithResponse(new AppendBlobCreateOptions() + .setHeaders(headers).setMetadata(metadata).setTags(tags), timeout, context); + if (response.getStatusCode() == 409) { + System.out.println("Already existed."); + } else { + System.out.printf("Create completed with status %d%n", response.getStatusCode()); + } + // END: com.azure.storage.blob.specialized.AppendBlobClient.createIfNotExistsWithResponse#AppendBlobCreateOptions-Duration-Context + + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample30/v2/AppendBlobClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample30/v2/AppendBlobClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..e03fef303d9c --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample30/v2/AppendBlobClientJavaDocCodeSnippets.java @@ -0,0 +1,242 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob.specialized; + +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.storage.blob.models.AppendBlobItem; +import com.azure.storage.blob.options.AppendBlobCreateOptions; +import com.azure.storage.blob.models.AppendBlobRequestConditions; +import com.azure.storage.blob.models.BlobHttpHeaders; +import com.azure.storage.blob.models.BlobRange; +import com.azure.storage.blob.models.BlobRequestConditions; +import com.azure.storage.blob.options.AppendBlobSealOptions; +import com.azure.storage.blob.options.AppendBlobAppendBlockFromUrlOptions; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Collections; +import java.util.Map; + +/** + * Code snippets for {@link AppendBlobClient} + */ +public class AppendBlobClientJavaDocCodeSnippets { + + private AppendBlobClient client = new SpecializedBlobClientBuilder().buildAppendBlobClient(); + private Duration timeout = Duration.ofSeconds(30); + private String leaseId = "leaseId"; + private InputStream data = new ByteArrayInputStream("data".getBytes(StandardCharsets.UTF_8)); + private long length = 4L; + private static final Long POSITION = null; + private Long maxSize = length; + private String sourceUrl = "https://example.com"; + private long offset = 1024; + private long count = 1024; + + /** + * Code snippet for {@link AppendBlobClient#create()} + */ + public void create() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobClient.create + System.out.printf("Created AppendBlob at %s%n", client.create().getLastModified()); + // END: com.azure.storage.blob.specialized.AppendBlobClient.create + } + + /** + * Code snippet for {@link AppendBlobClient#create(boolean)} + */ + public void createWithOverwrite() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobClient.create#boolean + boolean overwrite = false; // Default value + System.out.printf("Created AppendBlob at %s%n", client.create(overwrite).getLastModified()); + // END: com.azure.storage.blob.specialized.AppendBlobClient.create#boolean + } + + /** + * Code snippet for {@link AppendBlobClient#createWithResponse(BlobHttpHeaders, Map, BlobRequestConditions, + * Duration, Context)} + */ + public void createWithResponse() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobClient.createWithResponse#BlobHttpHeaders-Map-BlobRequestConditions-Duration-Context + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentType("binary") + .setContentLanguage("en-US"); + Map metadata = Collections.singletonMap("metadata", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context("key", "value"); + + System.out.printf("Created AppendBlob at %s%n", + client.createWithResponse(headers, metadata, requestConditions, timeout, context).getValue() + .getLastModified()); + // END: com.azure.storage.blob.specialized.AppendBlobClient.createWithResponse#BlobHttpHeaders-Map-BlobRequestConditions-Duration-Context + } + + /** + * Code snippet for {@link AppendBlobClient#createWithResponse(AppendBlobCreateOptions, Duration, Context)} + */ + public void createWithResponse2() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobClient.createWithResponse#AppendBlobCreateOptions-Duration-Context + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentType("binary") + .setContentLanguage("en-US"); + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tags", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context("key", "value"); + + System.out.printf("Created AppendBlob at %s%n", + client.createWithResponse(new AppendBlobCreateOptions().setHeaders(headers).setMetadata(metadata) + .setTags(tags).setRequestConditions(requestConditions), timeout, context).getValue() + .getLastModified()); + // END: com.azure.storage.blob.specialized.AppendBlobClient.createWithResponse#AppendBlobCreateOptions-Duration-Context + } + + /** + * Code snippet for {@link AppendBlobClient#appendBlock(InputStream, long)} + */ + public void appendBlock() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobClient.appendBlock#InputStream-long + System.out.printf("AppendBlob has %d committed blocks%n", + client.appendBlock(data, length).getBlobCommittedBlockCount()); + // END: com.azure.storage.blob.specialized.AppendBlobClient.appendBlock#InputStream-long + } + + /** + * Code snippet for {@link AppendBlobClient#appendBlockWithResponse(InputStream, long, byte[], + * AppendBlobRequestConditions, Duration, Context)} + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public void appendBlock2() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobClient.appendBlockWithResponse#InputStream-long-byte-AppendBlobRequestConditions-Duration-Context + byte[] md5 = MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8)); + AppendBlobRequestConditions requestConditions = new AppendBlobRequestConditions() + .setAppendPosition(POSITION) + .setMaxSize(maxSize); + Context context = new Context("key", "value"); + + System.out.printf("AppendBlob has %d committed blocks%n", + client.appendBlockWithResponse(data, length, md5, requestConditions, timeout, context) + .getValue().getBlobCommittedBlockCount()); + // END: com.azure.storage.blob.specialized.AppendBlobClient.appendBlockWithResponse#InputStream-long-byte-AppendBlobRequestConditions-Duration-Context + } + + /** + * Code snippet for {@link AppendBlobClient#appendBlockFromUrl(String, BlobRange)} + */ + public void appendBlockFromUrl() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobClient.appendBlockFromUrl#String-BlobRange + System.out.printf("AppendBlob has %d committed blocks%n", + client.appendBlockFromUrl(sourceUrl, new BlobRange(offset, count)).getBlobCommittedBlockCount()); + // END: com.azure.storage.blob.specialized.AppendBlobClient.appendBlockFromUrl#String-BlobRange + } + + /** + * Code snippet for {@link AppendBlobClient#appendBlockFromUrlWithResponse(String, BlobRange, byte[], + * AppendBlobRequestConditions, BlobRequestConditions, Duration, Context)} + */ + public void appendBlockFromUrlWithResponse() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobClient.appendBlockFromUrlWithResponse#String-BlobRange-byte-AppendBlobRequestConditions-BlobRequestConditions-Duration-Context + AppendBlobRequestConditions appendBlobRequestConditions = new AppendBlobRequestConditions() + .setAppendPosition(POSITION) + .setMaxSize(maxSize); + + BlobRequestConditions modifiedRequestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + Context context = new Context("key", "value"); + + System.out.printf("AppendBlob has %d committed blocks%n", + client.appendBlockFromUrlWithResponse(sourceUrl, new BlobRange(offset, count), null, + appendBlobRequestConditions, modifiedRequestConditions, timeout, + context).getValue().getBlobCommittedBlockCount()); + // END: com.azure.storage.blob.specialized.AppendBlobClient.appendBlockFromUrlWithResponse#String-BlobRange-byte-AppendBlobRequestConditions-BlobRequestConditions-Duration-Context + } + + /** + * Code snippet for {@link AppendBlobClient#appendBlockFromUrlWithResponse(String, BlobRange, byte[], + * AppendBlobRequestConditions, BlobRequestConditions, Duration, Context)} + */ + public void appendBlockFromUrlOptionsBagWithResponse() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobClient.appendBlockFromUrlWithResponse#AppendBlobAppendBlockFromUrlOptions-Duration-Context + AppendBlobRequestConditions appendBlobRequestConditions = new AppendBlobRequestConditions() + .setAppendPosition(POSITION) + .setMaxSize(maxSize); + + BlobRequestConditions modifiedRequestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + Context context = new Context("key", "value"); + + System.out.printf("AppendBlob has %d committed blocks%n", + client.appendBlockFromUrlWithResponse(new AppendBlobAppendBlockFromUrlOptions(sourceUrl) + .setSourceRange(new BlobRange(offset, count)) + .setDestinationRequestConditions(appendBlobRequestConditions) + .setSourceRequestConditions(modifiedRequestConditions), timeout, + context).getValue().getBlobCommittedBlockCount()); + // END: com.azure.storage.blob.specialized.AppendBlobClient.appendBlockFromUrlWithResponse#AppendBlobAppendBlockFromUrlOptions-Duration-Context + } + + /** + * Code snippet for {@link AppendBlobClient#seal()} + */ + public void seal() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobClient.seal + client.seal(); + System.out.println("Sealed AppendBlob"); + // END: com.azure.storage.blob.specialized.AppendBlobClient.seal + } + + /** + * Code snippet for {@link AppendBlobClient#sealWithResponse(AppendBlobSealOptions, Duration, Context)} + */ + public void seal2() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobClient.sealWithResponse#AppendBlobSealOptions-Duration-Context + AppendBlobRequestConditions requestConditions = new AppendBlobRequestConditions().setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context("key", "value"); + + client.sealWithResponse(new AppendBlobSealOptions().setRequestConditions(requestConditions), timeout, context); + System.out.println("Sealed AppendBlob"); + // END: com.azure.storage.blob.specialized.AppendBlobClient.sealWithResponse#AppendBlobSealOptions-Duration-Context + } + + /** + * Code snippet for {@link AppendBlobClient#createIfNotExists()} and + * {@link AppendBlobClient#createIfNotExistsWithResponse(AppendBlobCreateOptions, Duration, Context)} + */ + public void createIfNotExistsCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.AppendBlobClient.createIfNotExists + client.createIfNotExists(); + System.out.println("Created AppendBlob"); + // END: com.azure.storage.blob.specialized.AppendBlobClient.createIfNotExists + + // BEGIN: com.azure.storage.blob.specialized.AppendBlobClient.createIfNotExistsWithResponse#AppendBlobCreateOptions-Duration-Context + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentType("binary") + .setContentLanguage("en-US"); + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tags", "value"); + Context context = new Context("key", "value"); + + Response response = client.createIfNotExistsWithResponse(new AppendBlobCreateOptions() + .setHeaders(headers).setMetadata(metadata).setTags(tags), timeout, context); + if (response.getStatusCode() == 409) { + System.out.println("Already existed."); + } else { + System.out.printf("Create completed with status %d%n", response.getStatusCode()); + } + // END: com.azure.storage.blob.specialized.AppendBlobClient.createIfNotExistsWithResponse#AppendBlobCreateOptions-Duration-Context + + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample31/v1/BlobAsyncClientBaseJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample31/v1/BlobAsyncClientBaseJavaDocCodeSnippets.java new file mode 100644 index 000000000000..80e0fe297a49 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample31/v1/BlobAsyncClientBaseJavaDocCodeSnippets.java @@ -0,0 +1,824 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob.specialized; + +import com.azure.core.http.RequestConditions; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; +import com.azure.core.util.polling.PollerFlux; +import com.azure.storage.blob.BlobAsyncClient; +import com.azure.storage.blob.BlobClientBuilder; +import com.azure.storage.blob.BlobServiceClientBuilder; +import com.azure.storage.blob.models.AccessTier; +import com.azure.storage.blob.models.BlobBeginCopySourceRequestConditions; +import com.azure.storage.blob.models.BlobImmutabilityPolicy; +import com.azure.storage.blob.models.BlobImmutabilityPolicyMode; +import com.azure.storage.blob.options.BlobBeginCopyOptions; +import com.azure.storage.blob.options.BlobCopyFromUrlOptions; +import com.azure.storage.blob.models.BlobCopyInfo; +import com.azure.storage.blob.models.BlobHttpHeaders; +import com.azure.storage.blob.models.BlobQueryDelimitedSerialization; +import com.azure.storage.blob.models.BlobQueryError; +import com.azure.storage.blob.models.BlobQueryJsonSerialization; +import com.azure.storage.blob.options.BlobDownloadToFileOptions; +import com.azure.storage.blob.options.BlobGetTagsOptions; +import com.azure.storage.blob.options.BlobQueryOptions; +import com.azure.storage.blob.models.BlobQueryProgress; +import com.azure.storage.blob.models.BlobRange; +import com.azure.storage.blob.models.BlobRequestConditions; +import com.azure.storage.blob.models.DeleteSnapshotsOptionType; +import com.azure.storage.blob.models.DownloadRetryOptions; +import com.azure.storage.blob.models.ParallelTransferOptions; +import com.azure.storage.blob.models.RehydratePriority; +import com.azure.storage.blob.models.UserDelegationKey; +import com.azure.storage.blob.options.BlobSetAccessTierOptions; +import com.azure.storage.blob.options.BlobSetTagsOptions; +import com.azure.storage.blob.sas.BlobSasPermission; +import com.azure.storage.blob.sas.BlobServiceSasSignatureValues; +import reactor.core.publisher.Mono; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.OpenOption; +import java.nio.file.StandardOpenOption; +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.function.Consumer; + +/** + * Code snippets for {@link BlobAsyncClientBase} + */ +@SuppressWarnings("unused") +public class BlobAsyncClientBaseJavaDocCodeSnippets { + private BlobAsyncClient client = new BlobClientBuilder().endpoint("https://storageaccount.blob.core.windows.net") + .containerName("containerName").blobName("blobName").sasToken("sasToken").buildAsyncClient(); + private String leaseId = "leaseId"; + private String tags = "tags"; + private String copyId = "copyId"; + private String url = "https://sample.com"; + private String file = "file"; + private String accountName = "accountName"; + private UserDelegationKey userDelegationKey = new BlobServiceClientBuilder().buildClient().getUserDelegationKey(null, null); + + /** + * Code snippet for {@link BlobAsyncClientBase#exists()} + */ + public void existsCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.exists + client.exists().subscribe(response -> System.out.printf("Exists? %b%n", response)); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.exists + } + + /** + * Code snippets for {@link BlobAsyncClientBase#beginCopy(String, Duration)} + */ + public void beginCopyCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopy#String-Duration + client.beginCopy(url, Duration.ofSeconds(3)) + .subscribe(response -> System.out.printf("Copy identifier: %s%n", response)); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopy#String-Duration + } + + /** + * Code snippets for {@link BlobAsyncClientBase#abortCopyFromUrl(String)} + */ + public void abortCopyFromUrlCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.abortCopyFromUrl#String + client.abortCopyFromUrl(copyId).doOnSuccess(response -> System.out.println("Aborted copy from URL")); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.abortCopyFromUrl#String + } + + /** + * Code snippets for {@link BlobAsyncClientBase#copyFromUrl(String)} + */ + public void copyFromUrlCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.copyFromUrl#String + client.copyFromUrl(url).subscribe(response -> System.out.printf("Copy identifier: %s%n", response)); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.copyFromUrl#String + } + + /** + * Code snippets for {@link BlobAsyncClientBase#download()} + * + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.download + ByteArrayOutputStream downloadData = new ByteArrayOutputStream(); + client.download().subscribe(piece -> { + try { + downloadData.write(piece.array()); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + }); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.download + } + + /** + * Code snippets for {@link BlobAsyncClientBase#downloadStream()} + * + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadStreamCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadStream + ByteArrayOutputStream downloadData = new ByteArrayOutputStream(); + client.downloadStream().subscribe(piece -> { + try { + downloadData.write(piece.array()); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + }); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadStream + } + + /** + * Code snippet for {@link BlobAsyncClientBase#downloadWithResponse(BlobRange, DownloadRetryOptions, + * BlobRequestConditions, boolean)} + * + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.download#BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean + BlobRange range = new BlobRange(1024, 2048L); + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + + client.downloadWithResponse(range, options, null, false).subscribe(response -> { + ByteArrayOutputStream downloadData = new ByteArrayOutputStream(); + response.getValue().subscribe(piece -> { + try { + downloadData.write(piece.array()); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + }); + }); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.download#BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean + } + + /** + * Code snippets for {@link BlobAsyncClientBase#downloadToFile(String)}, {@link BlobAsyncClientBase#downloadToFileWithResponse(String, + * BlobRange, ParallelTransferOptions, DownloadRetryOptions, BlobRequestConditions, boolean)} and + * {@link BlobAsyncClientBase#downloadToFileWithResponse(BlobDownloadToFileOptions)} + */ + public void downloadToFileCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFile#String + client.downloadToFile(file).subscribe(response -> System.out.println("Completed download to file")); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFile#String + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFile#String-boolean + boolean overwrite = false; // Default value + client.downloadToFile(file, overwrite).subscribe(response -> System.out.println("Completed download to file")); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFile#String-boolean + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFileWithResponse#String-BlobRange-ParallelTransferOptions-DownloadRetryOptions-BlobRequestConditions-boolean + BlobRange range = new BlobRange(1024, 2048L); + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + + client.downloadToFileWithResponse(file, range, null, options, null, false) + .subscribe(response -> System.out.println("Completed download to file")); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFileWithResponse#String-BlobRange-ParallelTransferOptions-DownloadRetryOptions-BlobRequestConditions-boolean + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFileWithResponse#String-BlobRange-ParallelTransferOptions-DownloadRetryOptions-BlobRequestConditions-boolean-Set + BlobRange blobRange = new BlobRange(1024, 2048L); + DownloadRetryOptions downloadRetryOptions = new DownloadRetryOptions().setMaxRetryRequests(5); + Set openOptions = new HashSet<>(Arrays.asList(StandardOpenOption.CREATE_NEW, + StandardOpenOption.WRITE, StandardOpenOption.READ)); // Default options + + client.downloadToFileWithResponse(file, blobRange, null, downloadRetryOptions, null, false, openOptions) + .subscribe(response -> System.out.println("Completed download to file")); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFileWithResponse#String-BlobRange-ParallelTransferOptions-DownloadRetryOptions-BlobRequestConditions-boolean-Set + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFileWithResponse#BlobDownloadToFileOptions + client.downloadToFileWithResponse(new BlobDownloadToFileOptions(file) + .setRange(new BlobRange(1024, 2018L)) + .setDownloadRetryOptions(new DownloadRetryOptions().setMaxRetryRequests(5)) + .setOpenOptions(new HashSet<>(Arrays.asList(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE, + StandardOpenOption.READ)))) + .subscribe(response -> System.out.println("Completed download to file")); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFileWithResponse#BlobDownloadToFileOptions + } + + /** + * Code snippets for {@link BlobAsyncClientBase#delete()} + */ + public void deleteCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.delete + client.delete().doOnSuccess(response -> System.out.println("Completed delete")); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.delete + } + + /** + * Code snippets for {@link BlobAsyncClientBase#getProperties()} + */ + public void getPropertiesCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.getProperties + client.getProperties().subscribe(response -> + System.out.printf("Type: %s, Size: %d%n", response.getBlobType(), response.getBlobSize())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.getProperties + } + + /** + * Code snippets for {@link BlobAsyncClientBase#setHttpHeaders(BlobHttpHeaders)} + */ + public void setHTTPHeadersCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.setHttpHeaders#BlobHttpHeaders + client.setHttpHeaders(new BlobHttpHeaders() + .setContentLanguage("en-US") + .setContentType("binary")); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.setHttpHeaders#BlobHttpHeaders + } + + /** + * Code snippets for {@link BlobAsyncClientBase#setMetadata(Map)} + */ + public void setMetadataCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.setMetadata#Map + client.setMetadata(Collections.singletonMap("metadata", "value")); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.setMetadata#Map + } + + /** + * Code snippets for {@link BlobAsyncClientBase#getTags()} + */ + public void getTagsCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.getTags + client.getTags().subscribe(response -> + System.out.printf("Num tags: %d%n", response.size())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.getTags + } + + /** + * Code snippets for {@link BlobAsyncClientBase#setTags(Map)} + */ + public void setTagsCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.setTags#Map + client.setTags(Collections.singletonMap("tag", "value")); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.setTags#Map + } + + /** + * Code snippets for {@link BlobAsyncClientBase#createSnapshot()} + */ + public void createSnapshotCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.createSnapshot + client.createSnapshot() + .subscribe(response -> System.out.printf("Identifier for the snapshot is %s%n", + response.getSnapshotId())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.createSnapshot + } + + /** + * Code snippets for {@link BlobAsyncClientBase#setAccessTier(AccessTier)} + */ + public void setTierCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.setAccessTier#AccessTier + client.setAccessTier(AccessTier.HOT); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.setAccessTier#AccessTier + } + + /** + * Code snippet for {@link BlobAsyncClientBase#undelete()} + */ + public void undeleteCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.undelete + client.undelete().doOnSuccess(response -> System.out.println("Completed undelete")); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.undelete + } + + /** + * Code snippet for {@link BlobAsyncClientBase#getAccountInfo()} + */ + public void getAccountInfoCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.getAccountInfo + client.getAccountInfo().subscribe(response -> System.out.printf("Account Kind: %s, SKU: %s%n", + response.getAccountKind(), response.getSkuName())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.getAccountInfo + } + + /** + * Code snippet for {@link BlobAsyncClientBase#existsWithResponse()} + */ + public void existsWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.existsWithResponse + client.existsWithResponse().subscribe(response -> System.out.printf("Exists? %b%n", response.getValue())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.existsWithResponse + } + + /** + * Code snippets for {@link BlobAsyncClientBase#beginCopy(String, Map, AccessTier, + * RehydratePriority, RequestConditions, BlobRequestConditions, Duration)} + */ + public void beginCopyCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopy#String-Map-AccessTier-RehydratePriority-RequestConditions-BlobRequestConditions-Duration + Map metadata = Collections.singletonMap("metadata", "value"); + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7)); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.beginCopy(url, metadata, AccessTier.HOT, RehydratePriority.STANDARD, + modifiedRequestConditions, blobRequestConditions, Duration.ofSeconds(2)) + .subscribe(response -> { + BlobCopyInfo info = response.getValue(); + System.out.printf("CopyId: %s. Status: %s%n", info.getCopyId(), info.getCopyStatus()); + }); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopy#String-Map-AccessTier-RehydratePriority-RequestConditions-BlobRequestConditions-Duration + } + + /** + * Code snippets for {@link BlobAsyncClientBase#beginCopy(BlobBeginCopyOptions)} + */ + public void beginCopyCodeSnippets2() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopy#BlobBeginCopyOptions + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + BlobBeginCopySourceRequestConditions modifiedRequestConditions = new BlobBeginCopySourceRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7)); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.beginCopy(new BlobBeginCopyOptions(url).setMetadata(metadata).setTags(tags).setTier(AccessTier.HOT) + .setRehydratePriority(RehydratePriority.STANDARD).setSourceRequestConditions(modifiedRequestConditions) + .setDestinationRequestConditions(blobRequestConditions).setPollInterval(Duration.ofSeconds(2))) + .subscribe(response -> { + BlobCopyInfo info = response.getValue(); + System.out.printf("CopyId: %s. Status: %s%n", info.getCopyId(), info.getCopyStatus()); + }); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopy#BlobBeginCopyOptions + } + + /** + * Code snippets for {@link BlobAsyncClientBase#beginCopy(BlobBeginCopyOptions)} + */ + public void beginCopyFromUrlCancelCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopyFromUrlCancel#BlobBeginCopyOptions + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + BlobBeginCopySourceRequestConditions modifiedRequestConditions = new BlobBeginCopySourceRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7)); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + PollerFlux poller = client.beginCopy(new BlobBeginCopyOptions(url) + .setMetadata(metadata).setTags(tags).setTier(AccessTier.HOT) + .setRehydratePriority(RehydratePriority.STANDARD).setSourceRequestConditions(modifiedRequestConditions) + .setDestinationRequestConditions(blobRequestConditions).setPollInterval(Duration.ofSeconds(2))); + + poller.take(Duration.ofMinutes(30)) + .last() + .flatMap(asyncPollResponse -> { + if (!asyncPollResponse.getStatus().isComplete()) { + return asyncPollResponse + .cancelOperation() + .then(Mono.error(new RuntimeException("Blob copy taking long time, " + + "operation is cancelled!"))); + } + return Mono.just(asyncPollResponse); + }).block(); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopyFromUrlCancel#BlobBeginCopyOptions + } + + /** + * Code snippets for {@link BlobAsyncClientBase#abortCopyFromUrlWithResponse(String, String)} + */ + public void abortCopyFromUrlWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.abortCopyFromUrlWithResponse#String-String + client.abortCopyFromUrlWithResponse(copyId, leaseId) + .subscribe(response -> System.out.printf("Aborted copy completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.abortCopyFromUrlWithResponse#String-String + } + + /** + * Code snippets for {@link BlobAsyncClientBase#copyFromUrlWithResponse(String, Map, AccessTier, RequestConditions, + * BlobRequestConditions)} + */ + public void copyFromUrlWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.copyFromUrlWithResponse#String-Map-AccessTier-RequestConditions-BlobRequestConditions + Map metadata = Collections.singletonMap("metadata", "value"); + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7)); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.copyFromUrlWithResponse(url, metadata, AccessTier.HOT, modifiedRequestConditions, blobRequestConditions) + .subscribe(response -> System.out.printf("Copy identifier: %s%n", response)); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.copyFromUrlWithResponse#String-Map-AccessTier-RequestConditions-BlobRequestConditions + } + + /** + * Code snippets for {@link BlobAsyncClientBase#copyFromUrlWithResponse(BlobCopyFromUrlOptions)} + */ + public void copyFromUrlWithResponseCodeSnippets2() { + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.copyFromUrlWithResponse#BlobCopyFromUrlOptions + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7)); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.copyFromUrlWithResponse(new BlobCopyFromUrlOptions(url).setMetadata(metadata).setTags(tags) + .setTier(AccessTier.HOT).setSourceRequestConditions(modifiedRequestConditions) + .setDestinationRequestConditions(blobRequestConditions)) + .subscribe(response -> System.out.printf("Copy identifier: %s%n", response)); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.copyFromUrlWithResponse#BlobCopyFromUrlOptions + } + + /** + * Code snippets for {@link BlobAsyncClientBase#downloadWithResponse(BlobRange, DownloadRetryOptions, + * BlobRequestConditions, boolean)} + * + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadWithResponse#BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean + BlobRange range = new BlobRange(1024, (long) 2048); + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + + client.downloadWithResponse(range, options, null, false).subscribe(response -> { + ByteArrayOutputStream downloadData = new ByteArrayOutputStream(); + response.getValue().subscribe(piece -> { + try { + downloadData.write(piece.array()); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + }); + }); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadWithResponse#BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean + } + + /** + * Code snippets for {@link BlobAsyncClientBase#downloadStreamWithResponse(BlobRange, DownloadRetryOptions, + * BlobRequestConditions, boolean)} + * + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadStreamWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadStreamWithResponse#BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean + BlobRange range = new BlobRange(1024, (long) 2048); + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + + client.downloadStreamWithResponse(range, options, null, false).subscribe(response -> { + ByteArrayOutputStream downloadData = new ByteArrayOutputStream(); + response.getValue().subscribe(piece -> { + try { + downloadData.write(piece.array()); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + }); + }); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadStreamWithResponse#BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean + } + + /** + * Code snippets for {@link BlobAsyncClientBase#downloadContentWithResponse(DownloadRetryOptions, + * BlobRequestConditions)} + * + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadContentWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadContentWithResponse#DownloadRetryOptions-BlobRequestConditions + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + + client.downloadContentWithResponse(options, null).subscribe(response -> { + BinaryData content = response.getValue(); + System.out.println(content.toString()); + }); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadContentWithResponse#DownloadRetryOptions-BlobRequestConditions + } + + /** + * Code snippets for {@link BlobAsyncClientBase#deleteWithResponse(DeleteSnapshotsOptionType, BlobRequestConditions)} + */ + public void deleteWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.deleteWithResponse#DeleteSnapshotsOptionType-BlobRequestConditions + client.deleteWithResponse(DeleteSnapshotsOptionType.INCLUDE, null) + .subscribe(response -> System.out.printf("Delete completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.deleteWithResponse#DeleteSnapshotsOptionType-BlobRequestConditions + } + + /** + * Code snippets for {@link BlobAsyncClientBase#getPropertiesWithResponse(BlobRequestConditions)} + */ + public void getPropertiesWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.getPropertiesWithResponse#BlobRequestConditions + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.getPropertiesWithResponse(requestConditions).subscribe( + response -> System.out.printf("Type: %s, Size: %d%n", response.getValue().getBlobType(), + response.getValue().getBlobSize())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.getPropertiesWithResponse#BlobRequestConditions + } + + /** + * Code snippets for {@link BlobAsyncClientBase#setHttpHeadersWithResponse(BlobHttpHeaders, BlobRequestConditions)} + */ + public void setHTTPHeadersWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.setHttpHeadersWithResponse#BlobHttpHeaders-BlobRequestConditions + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.setHttpHeadersWithResponse(new BlobHttpHeaders() + .setContentLanguage("en-US") + .setContentType("binary"), requestConditions).subscribe( + response -> + System.out.printf("Set HTTP headers completed with status %d%n", + response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.setHttpHeadersWithResponse#BlobHttpHeaders-BlobRequestConditions + } + + /** + * Code snippets for {@link BlobAsyncClientBase#setMetadataWithResponse(Map, BlobRequestConditions)} + */ + public void setMetadataWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.setMetadataWithResponse#Map-BlobRequestConditions + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.setMetadataWithResponse(Collections.singletonMap("metadata", "value"), requestConditions) + .subscribe(response -> System.out.printf("Set metadata completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.setMetadataWithResponse#Map-BlobRequestConditions + } + + /** + * Code snippets for {@link BlobAsyncClientBase#getTagsWithResponse(BlobGetTagsOptions)} + */ + public void getTagsWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.getTagsWithResponse#BlobGetTagsOptions + client.getTagsWithResponse(new BlobGetTagsOptions()).subscribe(response -> + System.out.printf("Status code: %d. Num tags: %d%n", response.getStatusCode(), response.getValue().size())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.getTagsWithResponse#BlobGetTagsOptions + } + + /** + * Code snippets for {@link BlobAsyncClientBase#setTagsWithResponse(BlobSetTagsOptions)} + */ + public void setTagsWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.setTagsWithResponse#BlobSetTagsOptions + client.setTagsWithResponse(new BlobSetTagsOptions(Collections.singletonMap("tag", "value"))) + .subscribe(response -> System.out.printf("Set tags completed with stats %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.setTagsWithResponse#BlobSetTagsOptions + } + + /** + * Code snippets for {@link BlobAsyncClientBase#createSnapshotWithResponse(Map, BlobRequestConditions)} + */ + public void createSnapshotWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.createSnapshotWithResponse#Map-BlobRequestConditions + Map snapshotMetadata = Collections.singletonMap("metadata", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.createSnapshotWithResponse(snapshotMetadata, requestConditions) + .subscribe(response -> System.out.printf("Identifier for the snapshot is %s%n", response.getValue())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.createSnapshotWithResponse#Map-BlobRequestConditions + } + + /** + * Code snippets for {@link BlobAsyncClientBase#setAccessTierWithResponse(AccessTier, RehydratePriority, String)} + */ + public void setTierWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.setAccessTierWithResponse#AccessTier-RehydratePriority-String + client.setAccessTierWithResponse(AccessTier.HOT, RehydratePriority.STANDARD, leaseId) + .subscribe(response -> System.out.printf("Set tier completed with status code %d%n", + response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.setAccessTierWithResponse#AccessTier-RehydratePriority-String + } + + /** + * Code snippets for {@link BlobAsyncClientBase#setAccessTierWithResponse(BlobSetAccessTierOptions)} + */ + public void setTierWithResponseCodeSnippets2() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.setAccessTierWithResponse#BlobSetAccessTierOptions + client.setAccessTierWithResponse(new BlobSetAccessTierOptions(AccessTier.HOT) + .setPriority(RehydratePriority.STANDARD) + .setLeaseId(leaseId) + .setTagsConditions(tags)) + .subscribe(response -> System.out.printf("Set tier completed with status code %d%n", + response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.setAccessTierWithResponse#BlobSetAccessTierOptions + } + + /** + * Code snippet for {@link BlobAsyncClientBase#undeleteWithResponse()} + */ + public void undeleteWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.undeleteWithResponse + client.undeleteWithResponse() + .subscribe(response -> System.out.printf("Undelete completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.undeleteWithResponse + } + + /** + * Code snippet for {@link BlobAsyncClientBase#getAccountInfoWithResponse()} + */ + public void getAccountInfoWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.getAccountInfoWithResponse + client.getAccountInfoWithResponse().subscribe(response -> System.out.printf("Account Kind: %s, SKU: %s%n", + response.getValue().getAccountKind(), response.getValue().getSkuName())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.getAccountInfoWithResponse + } + + /** + * Code snippet for {@link BlobAsyncClientBase#generateUserDelegationSas(BlobServiceSasSignatureValues, UserDelegationKey)} + * and {@link BlobAsyncClientBase#generateSas(BlobServiceSasSignatureValues)} + */ + public void generateSas() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.generateSas#BlobServiceSasSignatureValues + OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1); + BlobSasPermission permission = new BlobSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues values = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + client.generateSas(values); // Client must be authenticated via StorageSharedKeyCredential + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.generateSas#BlobServiceSasSignatureValues + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey + OffsetDateTime myExpiryTime = OffsetDateTime.now().plusDays(1); + BlobSasPermission myPermission = new BlobSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues myValues = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + client.generateUserDelegationSas(values, userDelegationKey); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey + } + + /** + * Code snippet for {@link BlobAsyncClientBase#generateUserDelegationSas(BlobServiceSasSignatureValues, UserDelegationKey, String, Context)} + * and {@link BlobAsyncClientBase#generateSas(BlobServiceSasSignatureValues, Context)} + */ + public void generateSasWithContext() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.generateSas#BlobServiceSasSignatureValues-Context + OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1); + BlobSasPermission permission = new BlobSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues values = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + // Client must be authenticated via StorageSharedKeyCredential + client.generateSas(values, new Context("key", "value")); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.generateSas#BlobServiceSasSignatureValues-Context + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey-String-Context + OffsetDateTime myExpiryTime = OffsetDateTime.now().plusDays(1); + BlobSasPermission myPermission = new BlobSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues myValues = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + client.generateUserDelegationSas(values, userDelegationKey, accountName, new Context("key", "value")); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey-String-Context + } + + /** + * Code snippet for {@link BlobAsyncClientBase#query(String)} + * @throws UncheckedIOException for IOExceptions. + */ + public void query() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.query#String + ByteArrayOutputStream queryData = new ByteArrayOutputStream(); + String expression = "SELECT * from BlobStorage"; + client.query(expression).subscribe(piece -> { + try { + queryData.write(piece.array()); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + }); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.query#String + } + + /** + * Code snippet for {@link BlobAsyncClientBase#queryWithResponse(BlobQueryOptions)} + * @throws UncheckedIOException for IOExceptions. + */ + public void queryWithResponse() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.queryWithResponse#BlobQueryOptions + String expression = "SELECT * from BlobStorage"; + BlobQueryJsonSerialization input = new BlobQueryJsonSerialization() + .setRecordSeparator('\n'); + BlobQueryDelimitedSerialization output = new BlobQueryDelimitedSerialization() + .setEscapeChar('\0') + .setColumnSeparator(',') + .setRecordSeparator('\n') + .setFieldQuote('\'') + .setHeadersPresent(true); + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + Consumer errorConsumer = System.out::println; + Consumer progressConsumer = progress -> System.out.println("total blob bytes read: " + + progress.getBytesScanned()); + BlobQueryOptions queryOptions = new BlobQueryOptions(expression) + .setInputSerialization(input) + .setOutputSerialization(output) + .setRequestConditions(requestConditions) + .setErrorConsumer(errorConsumer) + .setProgressConsumer(progressConsumer); + + client.queryWithResponse(queryOptions) + .subscribe(response -> { + ByteArrayOutputStream queryData = new ByteArrayOutputStream(); + response.getValue().subscribe(piece -> { + try { + queryData.write(piece.array()); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + }); + }); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.queryWithResponse#BlobQueryOptions + } + + /** + * Code snippet for {@link BlobAsyncClientBase#setImmutabilityPolicy(BlobImmutabilityPolicy)} and + * {@link BlobAsyncClientBase#setImmutabilityPolicyWithResponse(BlobImmutabilityPolicy, BlobRequestConditions)} + */ + public void setImmutabilityPolicy() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.setImmutabilityPolicy#BlobImmutabilityPolicy + BlobImmutabilityPolicy policy = new BlobImmutabilityPolicy() + .setPolicyMode(BlobImmutabilityPolicyMode.LOCKED) + .setExpiryTime(OffsetDateTime.now().plusDays(1)); + client.setImmutabilityPolicy(policy).subscribe(response -> System.out.println("Completed. Set immutability " + + "policy to " + response.getPolicyMode())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.setImmutabilityPolicy#BlobImmutabilityPolicy + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.setImmutabilityPolicyWithResponse#BlobImmutabilityPolicy-BlobRequestConditions + BlobImmutabilityPolicy immutabilityPolicy = new BlobImmutabilityPolicy() + .setPolicyMode(BlobImmutabilityPolicyMode.LOCKED) + .setExpiryTime(OffsetDateTime.now().plusDays(1)); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(1)); + client.setImmutabilityPolicyWithResponse(immutabilityPolicy, requestConditions).subscribe(response -> + System.out.println("Completed. Set immutability policy to " + response.getValue().getPolicyMode())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.setImmutabilityPolicyWithResponse#BlobImmutabilityPolicy-BlobRequestConditions + } + + /** + * Code snippet for {@link BlobAsyncClientBase#deleteImmutabilityPolicy()} and + * {@link BlobAsyncClientBase#deleteImmutabilityPolicyWithResponse()} + */ + public void deleteImmutabilityPolicy() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.deleteImmutabilityPolicy + client.deleteImmutabilityPolicy().subscribe(response -> System.out.println("Completed immutability policy" + + " deletion.")); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.deleteImmutabilityPolicy + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.deleteImmutabilityPolicyWithResponse + client.deleteImmutabilityPolicyWithResponse().subscribe(response -> + System.out.println("Delete immutability policy completed with status: " + response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.deleteImmutabilityPolicyWithResponse + } + + /** + * Code snippet for {@link BlobAsyncClientBase#setLegalHold(boolean)} and + * {@link BlobAsyncClientBase#setLegalHoldWithResponse(boolean)} + */ + public void setLegalHold() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.setLegalHold#boolean + client.setLegalHold(true).subscribe(response -> System.out.println("Legal hold status: " + + response.hasLegalHold())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.setLegalHold#boolean + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.setLegalHoldWithResponse#boolean + client.setLegalHoldWithResponse(true).subscribe(response -> + System.out.println("Legal hold status: " + response.getValue().hasLegalHold())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.setLegalHoldWithResponse#boolean + } + + /** + * Code snippets for {@link BlobAsyncClientBase#deleteIfExists()} and + * {@link BlobAsyncClientBase#deleteIfExistsWithResponse(DeleteSnapshotsOptionType, BlobRequestConditions)} + */ + public void deleteIfExistsCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.deleteIfExists + client.deleteIfExists().subscribe(deleted -> { + if (deleted) { + System.out.println("Successfully deleted."); + } else { + System.out.println("Does not exist."); + } + }); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.deleteIfExists + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.deleteIfExistsWithResponse#DeleteSnapshotsOptionType-BlobRequestConditions + client.deleteIfExistsWithResponse(DeleteSnapshotsOptionType.INCLUDE, null).subscribe(response -> { + if (response.getStatusCode() == 404) { + System.out.println("Does not exist."); + } else { + System.out.println("successfully deleted."); + } + }); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.deleteIfExistsWithResponse#DeleteSnapshotsOptionType-BlobRequestConditions + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample31/v2/BlobAsyncClientBaseJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample31/v2/BlobAsyncClientBaseJavaDocCodeSnippets.java new file mode 100644 index 000000000000..80e0fe297a49 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample31/v2/BlobAsyncClientBaseJavaDocCodeSnippets.java @@ -0,0 +1,824 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob.specialized; + +import com.azure.core.http.RequestConditions; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; +import com.azure.core.util.polling.PollerFlux; +import com.azure.storage.blob.BlobAsyncClient; +import com.azure.storage.blob.BlobClientBuilder; +import com.azure.storage.blob.BlobServiceClientBuilder; +import com.azure.storage.blob.models.AccessTier; +import com.azure.storage.blob.models.BlobBeginCopySourceRequestConditions; +import com.azure.storage.blob.models.BlobImmutabilityPolicy; +import com.azure.storage.blob.models.BlobImmutabilityPolicyMode; +import com.azure.storage.blob.options.BlobBeginCopyOptions; +import com.azure.storage.blob.options.BlobCopyFromUrlOptions; +import com.azure.storage.blob.models.BlobCopyInfo; +import com.azure.storage.blob.models.BlobHttpHeaders; +import com.azure.storage.blob.models.BlobQueryDelimitedSerialization; +import com.azure.storage.blob.models.BlobQueryError; +import com.azure.storage.blob.models.BlobQueryJsonSerialization; +import com.azure.storage.blob.options.BlobDownloadToFileOptions; +import com.azure.storage.blob.options.BlobGetTagsOptions; +import com.azure.storage.blob.options.BlobQueryOptions; +import com.azure.storage.blob.models.BlobQueryProgress; +import com.azure.storage.blob.models.BlobRange; +import com.azure.storage.blob.models.BlobRequestConditions; +import com.azure.storage.blob.models.DeleteSnapshotsOptionType; +import com.azure.storage.blob.models.DownloadRetryOptions; +import com.azure.storage.blob.models.ParallelTransferOptions; +import com.azure.storage.blob.models.RehydratePriority; +import com.azure.storage.blob.models.UserDelegationKey; +import com.azure.storage.blob.options.BlobSetAccessTierOptions; +import com.azure.storage.blob.options.BlobSetTagsOptions; +import com.azure.storage.blob.sas.BlobSasPermission; +import com.azure.storage.blob.sas.BlobServiceSasSignatureValues; +import reactor.core.publisher.Mono; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.OpenOption; +import java.nio.file.StandardOpenOption; +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.function.Consumer; + +/** + * Code snippets for {@link BlobAsyncClientBase} + */ +@SuppressWarnings("unused") +public class BlobAsyncClientBaseJavaDocCodeSnippets { + private BlobAsyncClient client = new BlobClientBuilder().endpoint("https://storageaccount.blob.core.windows.net") + .containerName("containerName").blobName("blobName").sasToken("sasToken").buildAsyncClient(); + private String leaseId = "leaseId"; + private String tags = "tags"; + private String copyId = "copyId"; + private String url = "https://sample.com"; + private String file = "file"; + private String accountName = "accountName"; + private UserDelegationKey userDelegationKey = new BlobServiceClientBuilder().buildClient().getUserDelegationKey(null, null); + + /** + * Code snippet for {@link BlobAsyncClientBase#exists()} + */ + public void existsCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.exists + client.exists().subscribe(response -> System.out.printf("Exists? %b%n", response)); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.exists + } + + /** + * Code snippets for {@link BlobAsyncClientBase#beginCopy(String, Duration)} + */ + public void beginCopyCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopy#String-Duration + client.beginCopy(url, Duration.ofSeconds(3)) + .subscribe(response -> System.out.printf("Copy identifier: %s%n", response)); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopy#String-Duration + } + + /** + * Code snippets for {@link BlobAsyncClientBase#abortCopyFromUrl(String)} + */ + public void abortCopyFromUrlCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.abortCopyFromUrl#String + client.abortCopyFromUrl(copyId).doOnSuccess(response -> System.out.println("Aborted copy from URL")); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.abortCopyFromUrl#String + } + + /** + * Code snippets for {@link BlobAsyncClientBase#copyFromUrl(String)} + */ + public void copyFromUrlCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.copyFromUrl#String + client.copyFromUrl(url).subscribe(response -> System.out.printf("Copy identifier: %s%n", response)); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.copyFromUrl#String + } + + /** + * Code snippets for {@link BlobAsyncClientBase#download()} + * + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.download + ByteArrayOutputStream downloadData = new ByteArrayOutputStream(); + client.download().subscribe(piece -> { + try { + downloadData.write(piece.array()); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + }); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.download + } + + /** + * Code snippets for {@link BlobAsyncClientBase#downloadStream()} + * + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadStreamCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadStream + ByteArrayOutputStream downloadData = new ByteArrayOutputStream(); + client.downloadStream().subscribe(piece -> { + try { + downloadData.write(piece.array()); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + }); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadStream + } + + /** + * Code snippet for {@link BlobAsyncClientBase#downloadWithResponse(BlobRange, DownloadRetryOptions, + * BlobRequestConditions, boolean)} + * + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.download#BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean + BlobRange range = new BlobRange(1024, 2048L); + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + + client.downloadWithResponse(range, options, null, false).subscribe(response -> { + ByteArrayOutputStream downloadData = new ByteArrayOutputStream(); + response.getValue().subscribe(piece -> { + try { + downloadData.write(piece.array()); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + }); + }); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.download#BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean + } + + /** + * Code snippets for {@link BlobAsyncClientBase#downloadToFile(String)}, {@link BlobAsyncClientBase#downloadToFileWithResponse(String, + * BlobRange, ParallelTransferOptions, DownloadRetryOptions, BlobRequestConditions, boolean)} and + * {@link BlobAsyncClientBase#downloadToFileWithResponse(BlobDownloadToFileOptions)} + */ + public void downloadToFileCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFile#String + client.downloadToFile(file).subscribe(response -> System.out.println("Completed download to file")); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFile#String + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFile#String-boolean + boolean overwrite = false; // Default value + client.downloadToFile(file, overwrite).subscribe(response -> System.out.println("Completed download to file")); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFile#String-boolean + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFileWithResponse#String-BlobRange-ParallelTransferOptions-DownloadRetryOptions-BlobRequestConditions-boolean + BlobRange range = new BlobRange(1024, 2048L); + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + + client.downloadToFileWithResponse(file, range, null, options, null, false) + .subscribe(response -> System.out.println("Completed download to file")); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFileWithResponse#String-BlobRange-ParallelTransferOptions-DownloadRetryOptions-BlobRequestConditions-boolean + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFileWithResponse#String-BlobRange-ParallelTransferOptions-DownloadRetryOptions-BlobRequestConditions-boolean-Set + BlobRange blobRange = new BlobRange(1024, 2048L); + DownloadRetryOptions downloadRetryOptions = new DownloadRetryOptions().setMaxRetryRequests(5); + Set openOptions = new HashSet<>(Arrays.asList(StandardOpenOption.CREATE_NEW, + StandardOpenOption.WRITE, StandardOpenOption.READ)); // Default options + + client.downloadToFileWithResponse(file, blobRange, null, downloadRetryOptions, null, false, openOptions) + .subscribe(response -> System.out.println("Completed download to file")); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFileWithResponse#String-BlobRange-ParallelTransferOptions-DownloadRetryOptions-BlobRequestConditions-boolean-Set + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFileWithResponse#BlobDownloadToFileOptions + client.downloadToFileWithResponse(new BlobDownloadToFileOptions(file) + .setRange(new BlobRange(1024, 2018L)) + .setDownloadRetryOptions(new DownloadRetryOptions().setMaxRetryRequests(5)) + .setOpenOptions(new HashSet<>(Arrays.asList(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE, + StandardOpenOption.READ)))) + .subscribe(response -> System.out.println("Completed download to file")); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFileWithResponse#BlobDownloadToFileOptions + } + + /** + * Code snippets for {@link BlobAsyncClientBase#delete()} + */ + public void deleteCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.delete + client.delete().doOnSuccess(response -> System.out.println("Completed delete")); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.delete + } + + /** + * Code snippets for {@link BlobAsyncClientBase#getProperties()} + */ + public void getPropertiesCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.getProperties + client.getProperties().subscribe(response -> + System.out.printf("Type: %s, Size: %d%n", response.getBlobType(), response.getBlobSize())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.getProperties + } + + /** + * Code snippets for {@link BlobAsyncClientBase#setHttpHeaders(BlobHttpHeaders)} + */ + public void setHTTPHeadersCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.setHttpHeaders#BlobHttpHeaders + client.setHttpHeaders(new BlobHttpHeaders() + .setContentLanguage("en-US") + .setContentType("binary")); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.setHttpHeaders#BlobHttpHeaders + } + + /** + * Code snippets for {@link BlobAsyncClientBase#setMetadata(Map)} + */ + public void setMetadataCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.setMetadata#Map + client.setMetadata(Collections.singletonMap("metadata", "value")); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.setMetadata#Map + } + + /** + * Code snippets for {@link BlobAsyncClientBase#getTags()} + */ + public void getTagsCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.getTags + client.getTags().subscribe(response -> + System.out.printf("Num tags: %d%n", response.size())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.getTags + } + + /** + * Code snippets for {@link BlobAsyncClientBase#setTags(Map)} + */ + public void setTagsCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.setTags#Map + client.setTags(Collections.singletonMap("tag", "value")); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.setTags#Map + } + + /** + * Code snippets for {@link BlobAsyncClientBase#createSnapshot()} + */ + public void createSnapshotCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.createSnapshot + client.createSnapshot() + .subscribe(response -> System.out.printf("Identifier for the snapshot is %s%n", + response.getSnapshotId())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.createSnapshot + } + + /** + * Code snippets for {@link BlobAsyncClientBase#setAccessTier(AccessTier)} + */ + public void setTierCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.setAccessTier#AccessTier + client.setAccessTier(AccessTier.HOT); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.setAccessTier#AccessTier + } + + /** + * Code snippet for {@link BlobAsyncClientBase#undelete()} + */ + public void undeleteCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.undelete + client.undelete().doOnSuccess(response -> System.out.println("Completed undelete")); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.undelete + } + + /** + * Code snippet for {@link BlobAsyncClientBase#getAccountInfo()} + */ + public void getAccountInfoCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.getAccountInfo + client.getAccountInfo().subscribe(response -> System.out.printf("Account Kind: %s, SKU: %s%n", + response.getAccountKind(), response.getSkuName())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.getAccountInfo + } + + /** + * Code snippet for {@link BlobAsyncClientBase#existsWithResponse()} + */ + public void existsWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.existsWithResponse + client.existsWithResponse().subscribe(response -> System.out.printf("Exists? %b%n", response.getValue())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.existsWithResponse + } + + /** + * Code snippets for {@link BlobAsyncClientBase#beginCopy(String, Map, AccessTier, + * RehydratePriority, RequestConditions, BlobRequestConditions, Duration)} + */ + public void beginCopyCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopy#String-Map-AccessTier-RehydratePriority-RequestConditions-BlobRequestConditions-Duration + Map metadata = Collections.singletonMap("metadata", "value"); + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7)); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.beginCopy(url, metadata, AccessTier.HOT, RehydratePriority.STANDARD, + modifiedRequestConditions, blobRequestConditions, Duration.ofSeconds(2)) + .subscribe(response -> { + BlobCopyInfo info = response.getValue(); + System.out.printf("CopyId: %s. Status: %s%n", info.getCopyId(), info.getCopyStatus()); + }); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopy#String-Map-AccessTier-RehydratePriority-RequestConditions-BlobRequestConditions-Duration + } + + /** + * Code snippets for {@link BlobAsyncClientBase#beginCopy(BlobBeginCopyOptions)} + */ + public void beginCopyCodeSnippets2() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopy#BlobBeginCopyOptions + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + BlobBeginCopySourceRequestConditions modifiedRequestConditions = new BlobBeginCopySourceRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7)); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.beginCopy(new BlobBeginCopyOptions(url).setMetadata(metadata).setTags(tags).setTier(AccessTier.HOT) + .setRehydratePriority(RehydratePriority.STANDARD).setSourceRequestConditions(modifiedRequestConditions) + .setDestinationRequestConditions(blobRequestConditions).setPollInterval(Duration.ofSeconds(2))) + .subscribe(response -> { + BlobCopyInfo info = response.getValue(); + System.out.printf("CopyId: %s. Status: %s%n", info.getCopyId(), info.getCopyStatus()); + }); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopy#BlobBeginCopyOptions + } + + /** + * Code snippets for {@link BlobAsyncClientBase#beginCopy(BlobBeginCopyOptions)} + */ + public void beginCopyFromUrlCancelCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopyFromUrlCancel#BlobBeginCopyOptions + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + BlobBeginCopySourceRequestConditions modifiedRequestConditions = new BlobBeginCopySourceRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7)); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + PollerFlux poller = client.beginCopy(new BlobBeginCopyOptions(url) + .setMetadata(metadata).setTags(tags).setTier(AccessTier.HOT) + .setRehydratePriority(RehydratePriority.STANDARD).setSourceRequestConditions(modifiedRequestConditions) + .setDestinationRequestConditions(blobRequestConditions).setPollInterval(Duration.ofSeconds(2))); + + poller.take(Duration.ofMinutes(30)) + .last() + .flatMap(asyncPollResponse -> { + if (!asyncPollResponse.getStatus().isComplete()) { + return asyncPollResponse + .cancelOperation() + .then(Mono.error(new RuntimeException("Blob copy taking long time, " + + "operation is cancelled!"))); + } + return Mono.just(asyncPollResponse); + }).block(); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.beginCopyFromUrlCancel#BlobBeginCopyOptions + } + + /** + * Code snippets for {@link BlobAsyncClientBase#abortCopyFromUrlWithResponse(String, String)} + */ + public void abortCopyFromUrlWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.abortCopyFromUrlWithResponse#String-String + client.abortCopyFromUrlWithResponse(copyId, leaseId) + .subscribe(response -> System.out.printf("Aborted copy completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.abortCopyFromUrlWithResponse#String-String + } + + /** + * Code snippets for {@link BlobAsyncClientBase#copyFromUrlWithResponse(String, Map, AccessTier, RequestConditions, + * BlobRequestConditions)} + */ + public void copyFromUrlWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.copyFromUrlWithResponse#String-Map-AccessTier-RequestConditions-BlobRequestConditions + Map metadata = Collections.singletonMap("metadata", "value"); + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7)); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.copyFromUrlWithResponse(url, metadata, AccessTier.HOT, modifiedRequestConditions, blobRequestConditions) + .subscribe(response -> System.out.printf("Copy identifier: %s%n", response)); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.copyFromUrlWithResponse#String-Map-AccessTier-RequestConditions-BlobRequestConditions + } + + /** + * Code snippets for {@link BlobAsyncClientBase#copyFromUrlWithResponse(BlobCopyFromUrlOptions)} + */ + public void copyFromUrlWithResponseCodeSnippets2() { + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.copyFromUrlWithResponse#BlobCopyFromUrlOptions + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7)); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.copyFromUrlWithResponse(new BlobCopyFromUrlOptions(url).setMetadata(metadata).setTags(tags) + .setTier(AccessTier.HOT).setSourceRequestConditions(modifiedRequestConditions) + .setDestinationRequestConditions(blobRequestConditions)) + .subscribe(response -> System.out.printf("Copy identifier: %s%n", response)); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.copyFromUrlWithResponse#BlobCopyFromUrlOptions + } + + /** + * Code snippets for {@link BlobAsyncClientBase#downloadWithResponse(BlobRange, DownloadRetryOptions, + * BlobRequestConditions, boolean)} + * + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadWithResponse#BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean + BlobRange range = new BlobRange(1024, (long) 2048); + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + + client.downloadWithResponse(range, options, null, false).subscribe(response -> { + ByteArrayOutputStream downloadData = new ByteArrayOutputStream(); + response.getValue().subscribe(piece -> { + try { + downloadData.write(piece.array()); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + }); + }); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadWithResponse#BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean + } + + /** + * Code snippets for {@link BlobAsyncClientBase#downloadStreamWithResponse(BlobRange, DownloadRetryOptions, + * BlobRequestConditions, boolean)} + * + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadStreamWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadStreamWithResponse#BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean + BlobRange range = new BlobRange(1024, (long) 2048); + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + + client.downloadStreamWithResponse(range, options, null, false).subscribe(response -> { + ByteArrayOutputStream downloadData = new ByteArrayOutputStream(); + response.getValue().subscribe(piece -> { + try { + downloadData.write(piece.array()); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + }); + }); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadStreamWithResponse#BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean + } + + /** + * Code snippets for {@link BlobAsyncClientBase#downloadContentWithResponse(DownloadRetryOptions, + * BlobRequestConditions)} + * + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadContentWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadContentWithResponse#DownloadRetryOptions-BlobRequestConditions + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + + client.downloadContentWithResponse(options, null).subscribe(response -> { + BinaryData content = response.getValue(); + System.out.println(content.toString()); + }); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadContentWithResponse#DownloadRetryOptions-BlobRequestConditions + } + + /** + * Code snippets for {@link BlobAsyncClientBase#deleteWithResponse(DeleteSnapshotsOptionType, BlobRequestConditions)} + */ + public void deleteWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.deleteWithResponse#DeleteSnapshotsOptionType-BlobRequestConditions + client.deleteWithResponse(DeleteSnapshotsOptionType.INCLUDE, null) + .subscribe(response -> System.out.printf("Delete completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.deleteWithResponse#DeleteSnapshotsOptionType-BlobRequestConditions + } + + /** + * Code snippets for {@link BlobAsyncClientBase#getPropertiesWithResponse(BlobRequestConditions)} + */ + public void getPropertiesWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.getPropertiesWithResponse#BlobRequestConditions + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.getPropertiesWithResponse(requestConditions).subscribe( + response -> System.out.printf("Type: %s, Size: %d%n", response.getValue().getBlobType(), + response.getValue().getBlobSize())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.getPropertiesWithResponse#BlobRequestConditions + } + + /** + * Code snippets for {@link BlobAsyncClientBase#setHttpHeadersWithResponse(BlobHttpHeaders, BlobRequestConditions)} + */ + public void setHTTPHeadersWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.setHttpHeadersWithResponse#BlobHttpHeaders-BlobRequestConditions + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.setHttpHeadersWithResponse(new BlobHttpHeaders() + .setContentLanguage("en-US") + .setContentType("binary"), requestConditions).subscribe( + response -> + System.out.printf("Set HTTP headers completed with status %d%n", + response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.setHttpHeadersWithResponse#BlobHttpHeaders-BlobRequestConditions + } + + /** + * Code snippets for {@link BlobAsyncClientBase#setMetadataWithResponse(Map, BlobRequestConditions)} + */ + public void setMetadataWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.setMetadataWithResponse#Map-BlobRequestConditions + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.setMetadataWithResponse(Collections.singletonMap("metadata", "value"), requestConditions) + .subscribe(response -> System.out.printf("Set metadata completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.setMetadataWithResponse#Map-BlobRequestConditions + } + + /** + * Code snippets for {@link BlobAsyncClientBase#getTagsWithResponse(BlobGetTagsOptions)} + */ + public void getTagsWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.getTagsWithResponse#BlobGetTagsOptions + client.getTagsWithResponse(new BlobGetTagsOptions()).subscribe(response -> + System.out.printf("Status code: %d. Num tags: %d%n", response.getStatusCode(), response.getValue().size())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.getTagsWithResponse#BlobGetTagsOptions + } + + /** + * Code snippets for {@link BlobAsyncClientBase#setTagsWithResponse(BlobSetTagsOptions)} + */ + public void setTagsWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.setTagsWithResponse#BlobSetTagsOptions + client.setTagsWithResponse(new BlobSetTagsOptions(Collections.singletonMap("tag", "value"))) + .subscribe(response -> System.out.printf("Set tags completed with stats %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.setTagsWithResponse#BlobSetTagsOptions + } + + /** + * Code snippets for {@link BlobAsyncClientBase#createSnapshotWithResponse(Map, BlobRequestConditions)} + */ + public void createSnapshotWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.createSnapshotWithResponse#Map-BlobRequestConditions + Map snapshotMetadata = Collections.singletonMap("metadata", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.createSnapshotWithResponse(snapshotMetadata, requestConditions) + .subscribe(response -> System.out.printf("Identifier for the snapshot is %s%n", response.getValue())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.createSnapshotWithResponse#Map-BlobRequestConditions + } + + /** + * Code snippets for {@link BlobAsyncClientBase#setAccessTierWithResponse(AccessTier, RehydratePriority, String)} + */ + public void setTierWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.setAccessTierWithResponse#AccessTier-RehydratePriority-String + client.setAccessTierWithResponse(AccessTier.HOT, RehydratePriority.STANDARD, leaseId) + .subscribe(response -> System.out.printf("Set tier completed with status code %d%n", + response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.setAccessTierWithResponse#AccessTier-RehydratePriority-String + } + + /** + * Code snippets for {@link BlobAsyncClientBase#setAccessTierWithResponse(BlobSetAccessTierOptions)} + */ + public void setTierWithResponseCodeSnippets2() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.setAccessTierWithResponse#BlobSetAccessTierOptions + client.setAccessTierWithResponse(new BlobSetAccessTierOptions(AccessTier.HOT) + .setPriority(RehydratePriority.STANDARD) + .setLeaseId(leaseId) + .setTagsConditions(tags)) + .subscribe(response -> System.out.printf("Set tier completed with status code %d%n", + response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.setAccessTierWithResponse#BlobSetAccessTierOptions + } + + /** + * Code snippet for {@link BlobAsyncClientBase#undeleteWithResponse()} + */ + public void undeleteWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.undeleteWithResponse + client.undeleteWithResponse() + .subscribe(response -> System.out.printf("Undelete completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.undeleteWithResponse + } + + /** + * Code snippet for {@link BlobAsyncClientBase#getAccountInfoWithResponse()} + */ + public void getAccountInfoWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.getAccountInfoWithResponse + client.getAccountInfoWithResponse().subscribe(response -> System.out.printf("Account Kind: %s, SKU: %s%n", + response.getValue().getAccountKind(), response.getValue().getSkuName())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.getAccountInfoWithResponse + } + + /** + * Code snippet for {@link BlobAsyncClientBase#generateUserDelegationSas(BlobServiceSasSignatureValues, UserDelegationKey)} + * and {@link BlobAsyncClientBase#generateSas(BlobServiceSasSignatureValues)} + */ + public void generateSas() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.generateSas#BlobServiceSasSignatureValues + OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1); + BlobSasPermission permission = new BlobSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues values = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + client.generateSas(values); // Client must be authenticated via StorageSharedKeyCredential + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.generateSas#BlobServiceSasSignatureValues + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey + OffsetDateTime myExpiryTime = OffsetDateTime.now().plusDays(1); + BlobSasPermission myPermission = new BlobSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues myValues = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + client.generateUserDelegationSas(values, userDelegationKey); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey + } + + /** + * Code snippet for {@link BlobAsyncClientBase#generateUserDelegationSas(BlobServiceSasSignatureValues, UserDelegationKey, String, Context)} + * and {@link BlobAsyncClientBase#generateSas(BlobServiceSasSignatureValues, Context)} + */ + public void generateSasWithContext() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.generateSas#BlobServiceSasSignatureValues-Context + OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1); + BlobSasPermission permission = new BlobSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues values = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + // Client must be authenticated via StorageSharedKeyCredential + client.generateSas(values, new Context("key", "value")); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.generateSas#BlobServiceSasSignatureValues-Context + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey-String-Context + OffsetDateTime myExpiryTime = OffsetDateTime.now().plusDays(1); + BlobSasPermission myPermission = new BlobSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues myValues = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + client.generateUserDelegationSas(values, userDelegationKey, accountName, new Context("key", "value")); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey-String-Context + } + + /** + * Code snippet for {@link BlobAsyncClientBase#query(String)} + * @throws UncheckedIOException for IOExceptions. + */ + public void query() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.query#String + ByteArrayOutputStream queryData = new ByteArrayOutputStream(); + String expression = "SELECT * from BlobStorage"; + client.query(expression).subscribe(piece -> { + try { + queryData.write(piece.array()); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + }); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.query#String + } + + /** + * Code snippet for {@link BlobAsyncClientBase#queryWithResponse(BlobQueryOptions)} + * @throws UncheckedIOException for IOExceptions. + */ + public void queryWithResponse() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.queryWithResponse#BlobQueryOptions + String expression = "SELECT * from BlobStorage"; + BlobQueryJsonSerialization input = new BlobQueryJsonSerialization() + .setRecordSeparator('\n'); + BlobQueryDelimitedSerialization output = new BlobQueryDelimitedSerialization() + .setEscapeChar('\0') + .setColumnSeparator(',') + .setRecordSeparator('\n') + .setFieldQuote('\'') + .setHeadersPresent(true); + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + Consumer errorConsumer = System.out::println; + Consumer progressConsumer = progress -> System.out.println("total blob bytes read: " + + progress.getBytesScanned()); + BlobQueryOptions queryOptions = new BlobQueryOptions(expression) + .setInputSerialization(input) + .setOutputSerialization(output) + .setRequestConditions(requestConditions) + .setErrorConsumer(errorConsumer) + .setProgressConsumer(progressConsumer); + + client.queryWithResponse(queryOptions) + .subscribe(response -> { + ByteArrayOutputStream queryData = new ByteArrayOutputStream(); + response.getValue().subscribe(piece -> { + try { + queryData.write(piece.array()); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + }); + }); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.queryWithResponse#BlobQueryOptions + } + + /** + * Code snippet for {@link BlobAsyncClientBase#setImmutabilityPolicy(BlobImmutabilityPolicy)} and + * {@link BlobAsyncClientBase#setImmutabilityPolicyWithResponse(BlobImmutabilityPolicy, BlobRequestConditions)} + */ + public void setImmutabilityPolicy() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.setImmutabilityPolicy#BlobImmutabilityPolicy + BlobImmutabilityPolicy policy = new BlobImmutabilityPolicy() + .setPolicyMode(BlobImmutabilityPolicyMode.LOCKED) + .setExpiryTime(OffsetDateTime.now().plusDays(1)); + client.setImmutabilityPolicy(policy).subscribe(response -> System.out.println("Completed. Set immutability " + + "policy to " + response.getPolicyMode())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.setImmutabilityPolicy#BlobImmutabilityPolicy + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.setImmutabilityPolicyWithResponse#BlobImmutabilityPolicy-BlobRequestConditions + BlobImmutabilityPolicy immutabilityPolicy = new BlobImmutabilityPolicy() + .setPolicyMode(BlobImmutabilityPolicyMode.LOCKED) + .setExpiryTime(OffsetDateTime.now().plusDays(1)); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(1)); + client.setImmutabilityPolicyWithResponse(immutabilityPolicy, requestConditions).subscribe(response -> + System.out.println("Completed. Set immutability policy to " + response.getValue().getPolicyMode())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.setImmutabilityPolicyWithResponse#BlobImmutabilityPolicy-BlobRequestConditions + } + + /** + * Code snippet for {@link BlobAsyncClientBase#deleteImmutabilityPolicy()} and + * {@link BlobAsyncClientBase#deleteImmutabilityPolicyWithResponse()} + */ + public void deleteImmutabilityPolicy() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.deleteImmutabilityPolicy + client.deleteImmutabilityPolicy().subscribe(response -> System.out.println("Completed immutability policy" + + " deletion.")); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.deleteImmutabilityPolicy + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.deleteImmutabilityPolicyWithResponse + client.deleteImmutabilityPolicyWithResponse().subscribe(response -> + System.out.println("Delete immutability policy completed with status: " + response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.deleteImmutabilityPolicyWithResponse + } + + /** + * Code snippet for {@link BlobAsyncClientBase#setLegalHold(boolean)} and + * {@link BlobAsyncClientBase#setLegalHoldWithResponse(boolean)} + */ + public void setLegalHold() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.setLegalHold#boolean + client.setLegalHold(true).subscribe(response -> System.out.println("Legal hold status: " + + response.hasLegalHold())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.setLegalHold#boolean + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.setLegalHoldWithResponse#boolean + client.setLegalHoldWithResponse(true).subscribe(response -> + System.out.println("Legal hold status: " + response.getValue().hasLegalHold())); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.setLegalHoldWithResponse#boolean + } + + /** + * Code snippets for {@link BlobAsyncClientBase#deleteIfExists()} and + * {@link BlobAsyncClientBase#deleteIfExistsWithResponse(DeleteSnapshotsOptionType, BlobRequestConditions)} + */ + public void deleteIfExistsCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.deleteIfExists + client.deleteIfExists().subscribe(deleted -> { + if (deleted) { + System.out.println("Successfully deleted."); + } else { + System.out.println("Does not exist."); + } + }); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.deleteIfExists + + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.deleteIfExistsWithResponse#DeleteSnapshotsOptionType-BlobRequestConditions + client.deleteIfExistsWithResponse(DeleteSnapshotsOptionType.INCLUDE, null).subscribe(response -> { + if (response.getStatusCode() == 404) { + System.out.println("Does not exist."); + } else { + System.out.println("successfully deleted."); + } + }); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.deleteIfExistsWithResponse#DeleteSnapshotsOptionType-BlobRequestConditions + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample32/v1/BlobClientBaseJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample32/v1/BlobClientBaseJavaDocCodeSnippets.java new file mode 100644 index 000000000000..216e45dde835 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample32/v1/BlobClientBaseJavaDocCodeSnippets.java @@ -0,0 +1,807 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob.specialized; + +import com.azure.core.http.RequestConditions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; +import com.azure.core.util.polling.LongRunningOperationStatus; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.storage.blob.BlobClient; +import com.azure.storage.blob.BlobClientBuilder; +import com.azure.storage.blob.BlobServiceClientBuilder; +import com.azure.storage.blob.models.AccessTier; +import com.azure.storage.blob.models.BlobBeginCopySourceRequestConditions; +import com.azure.storage.blob.models.BlobCopyInfo; +import com.azure.storage.blob.models.BlobDownloadContentResponse; +import com.azure.storage.blob.models.BlobHttpHeaders; +import com.azure.storage.blob.models.BlobImmutabilityPolicy; +import com.azure.storage.blob.models.BlobImmutabilityPolicyMode; +import com.azure.storage.blob.models.BlobProperties; +import com.azure.storage.blob.models.BlobQueryDelimitedSerialization; +import com.azure.storage.blob.models.BlobQueryError; +import com.azure.storage.blob.models.BlobQueryJsonSerialization; +import com.azure.storage.blob.models.BlobQueryProgress; +import com.azure.storage.blob.models.BlobQuerySerialization; +import com.azure.storage.blob.models.BlobRange; +import com.azure.storage.blob.models.BlobRequestConditions; +import com.azure.storage.blob.models.DeleteSnapshotsOptionType; +import com.azure.storage.blob.models.DownloadRetryOptions; +import com.azure.storage.blob.models.ParallelTransferOptions; +import com.azure.storage.blob.models.RehydratePriority; +import com.azure.storage.blob.models.StorageAccountInfo; +import com.azure.storage.blob.models.UserDelegationKey; +import com.azure.storage.blob.options.BlobBeginCopyOptions; +import com.azure.storage.blob.options.BlobCopyFromUrlOptions; +import com.azure.storage.blob.options.BlobDownloadToFileOptions; +import com.azure.storage.blob.options.BlobGetTagsOptions; +import com.azure.storage.blob.options.BlobQueryOptions; +import com.azure.storage.blob.options.BlobSetAccessTierOptions; +import com.azure.storage.blob.options.BlobSetTagsOptions; +import com.azure.storage.blob.sas.BlobSasPermission; +import com.azure.storage.blob.sas.BlobServiceSasSignatureValues; +import com.azure.storage.common.implementation.Constants; + +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.UncheckedIOException; +import java.nio.file.OpenOption; +import java.nio.file.StandardOpenOption; +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.function.Consumer; + +/** + * Code snippets for {@link BlobClientBase} + */ +@SuppressWarnings("unused") +public class BlobClientBaseJavaDocCodeSnippets { + private BlobClient client = new BlobClientBuilder().endpoint("https://storageaccount.blob.core.windows.net") + .containerName("containerName").blobName("blobName").sasToken("sasToken").buildClient(); + private String leaseId = "leaseId"; + private String tags = "tags"; + private String copyId = "copyId"; + private String url = "https://sample.com"; + private String file = "file"; + private Duration timeout = Duration.ofSeconds(30); + private String key1 = "key1"; + private String key2 = "key2"; + private String value1 = "val1"; + private String value2 = "val2"; + private String accountName = "accountName"; + private UserDelegationKey userDelegationKey = new BlobServiceClientBuilder().buildClient().getUserDelegationKey(null, null); + + /** + * Code snippets for {@link BlobClientBase#exists()} + */ + public void existsCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.exists + System.out.printf("Exists? %b%n", client.exists()); + // END: com.azure.storage.blob.specialized.BlobClientBase.exists + } + + /** + * Code snippets for {@link BlobClientBase#beginCopy(String, Duration)} + */ + public void beginCopy() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.beginCopy#String-Duration + final SyncPoller poller = client.beginCopy(url, Duration.ofSeconds(2)); + PollResponse pollResponse = poller.poll(); + System.out.printf("Copy identifier: %s%n", pollResponse.getValue().getCopyId()); + // END: com.azure.storage.blob.specialized.BlobClientBase.beginCopy#String-Duration + } + + /** + * Code snippets for {@link BlobClientBase#abortCopyFromUrl(String)} + */ + public void abortCopyFromUrl() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.abortCopyFromUrl#String + client.abortCopyFromUrl(copyId); + System.out.println("Aborted copy completed."); + // END: com.azure.storage.blob.specialized.BlobClientBase.abortCopyFromUrl#String + } + + /** + * Code snippets for {@link BlobClientBase#copyFromUrl(String)} + */ + public void copyFromUrl() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.copyFromUrl#String + System.out.printf("Copy identifier: %s%n", client.copyFromUrl(url)); + // END: com.azure.storage.blob.specialized.BlobClientBase.copyFromUrl#String + } + + /** + * Code snippets for {@link BlobClientBase#download(OutputStream)} + */ + public void download() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.download#OutputStream + client.download(new ByteArrayOutputStream()); + System.out.println("Download completed."); + // END: com.azure.storage.blob.specialized.BlobClientBase.download#OutputStream + } + + /** + * Code snippets for {@link BlobClientBase#downloadStream(OutputStream)} + */ + public void downloadStream() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.downloadStream#OutputStream + client.downloadStream(new ByteArrayOutputStream()); + System.out.println("Download completed."); + // END: com.azure.storage.blob.specialized.BlobClientBase.downloadStream#OutputStream + } + + /** + * Code snippets for {@link BlobClientBase#downloadToFile(String)}, + * {@link BlobClientBase#downloadToFileWithResponse(String, BlobRange, ParallelTransferOptions, DownloadRetryOptions, BlobRequestConditions, + * boolean, Duration, Context)} and {@link BlobClientBase#downloadToFileWithResponse(BlobDownloadToFileOptions, Duration, Context)} + */ + public void downloadToFile() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.downloadToFile#String + client.downloadToFile(file); + System.out.println("Completed download to file"); + // END: com.azure.storage.blob.specialized.BlobClientBase.downloadToFile#String + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.downloadToFile#String-boolean + boolean overwrite = false; // Default value + client.downloadToFile(file, overwrite); + System.out.println("Completed download to file"); + // END: com.azure.storage.blob.specialized.BlobClientBase.downloadToFile#String-boolean + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.downloadToFileWithResponse#String-BlobRange-ParallelTransferOptions-DownloadRetryOptions-BlobRequestConditions-boolean-Duration-Context + BlobRange range = new BlobRange(1024, 2048L); + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + + client.downloadToFileWithResponse(file, range, new ParallelTransferOptions().setBlockSizeLong(4L * Constants.MB), + options, null, false, timeout, new Context(key2, value2)); + System.out.println("Completed download to file"); + // END: com.azure.storage.blob.specialized.BlobClientBase.downloadToFileWithResponse#String-BlobRange-ParallelTransferOptions-DownloadRetryOptions-BlobRequestConditions-boolean-Duration-Context + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.downloadToFileWithResponse#String-BlobRange-ParallelTransferOptions-DownloadRetryOptions-BlobRequestConditions-boolean-Set-Duration-Context + BlobRange blobRange = new BlobRange(1024, 2048L); + DownloadRetryOptions downloadRetryOptions = new DownloadRetryOptions().setMaxRetryRequests(5); + Set openOptions = new HashSet<>(Arrays.asList(StandardOpenOption.CREATE_NEW, + StandardOpenOption.WRITE, StandardOpenOption.READ)); // Default options + + client.downloadToFileWithResponse(file, blobRange, new ParallelTransferOptions().setBlockSizeLong(4L * Constants.MB), + downloadRetryOptions, null, false, openOptions, timeout, new Context(key2, value2)); + System.out.println("Completed download to file"); + // END: com.azure.storage.blob.specialized.BlobClientBase.downloadToFileWithResponse#String-BlobRange-ParallelTransferOptions-DownloadRetryOptions-BlobRequestConditions-boolean-Set-Duration-Context + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.downloadToFileWithResponse#BlobDownloadToFileOptions-Duration-Context + client.downloadToFileWithResponse(new BlobDownloadToFileOptions(file) + .setRange(new BlobRange(1024, 2018L)) + .setDownloadRetryOptions(new DownloadRetryOptions().setMaxRetryRequests(5)) + .setOpenOptions(new HashSet<>(Arrays.asList(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE, + StandardOpenOption.READ))), timeout, new Context(key2, value2)); + System.out.println("Completed download to file"); + // END: com.azure.storage.blob.specialized.BlobClientBase.downloadToFileWithResponse#BlobDownloadToFileOptions-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#delete()} + */ + public void setDelete() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.delete + client.delete(); + System.out.println("Delete completed."); + // END: com.azure.storage.blob.specialized.BlobClientBase.delete + } + + /** + * Code snippets for {@link BlobClientBase#getProperties()} + */ + public void getProperties() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.getProperties + BlobProperties properties = client.getProperties(); + System.out.printf("Type: %s, Size: %d%n", properties.getBlobType(), properties.getBlobSize()); + // END: com.azure.storage.blob.specialized.BlobClientBase.getProperties + } + + /** + * Code snippets for {@link BlobClientBase#setHttpHeaders(BlobHttpHeaders)} + */ + public void setHTTPHeaders() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.setHttpHeaders#BlobHttpHeaders + client.setHttpHeaders(new BlobHttpHeaders() + .setContentLanguage("en-US") + .setContentType("binary")); + System.out.println("Set HTTP headers completed"); + // END: com.azure.storage.blob.specialized.BlobClientBase.setHttpHeaders#BlobHttpHeaders + } + + /** + * Code snippets for {@link BlobClientBase#setMetadata(Map)} + */ + public void setMetadata() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.setMetadata#Map + client.setMetadata(Collections.singletonMap("metadata", "value")); + System.out.println("Set metadata completed"); + // END: com.azure.storage.blob.specialized.BlobClientBase.setMetadata#Map + } + + /** + * Code snippets for {@link BlobClientBase#getTags()} + */ + public void getTags() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.getTags + Map tags = client.getTags(); + System.out.printf("Number of tags: %d%n", tags.size()); + // END: com.azure.storage.blob.specialized.BlobClientBase.getTags + } + + /** + * Code snippets for {@link BlobClientBase#setTags(Map)} + */ + public void setTags() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.setTags#Map + client.setTags(Collections.singletonMap("tag", "value")); + System.out.println("Set tag completed"); + // END: com.azure.storage.blob.specialized.BlobClientBase.setTags#Map + } + + /** + * Code snippets for {@link BlobClientBase#createSnapshot()} + */ + public void createSnapshot() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.createSnapshot + System.out.printf("Identifier for the snapshot is %s%n", client.createSnapshot().getSnapshotId()); + // END: com.azure.storage.blob.specialized.BlobClientBase.createSnapshot + } + + /** + * Code snippets for {@link BlobClientBase#setAccessTier(AccessTier)} + */ + public void setTier() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.setAccessTier#AccessTier + client.setAccessTier(AccessTier.HOT); + System.out.println("Set tier completed."); + // END: com.azure.storage.blob.specialized.BlobClientBase.setAccessTier#AccessTier + } + + /** + * Code snippets for {@link BlobClientBase#undelete()} + */ + public void unsetDelete() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.undelete + client.undelete(); + System.out.println("Undelete completed"); + // END: com.azure.storage.blob.specialized.BlobClientBase.undelete + } + + /** + * Code snippet for {@link BlobClientBase#getAccountInfo()} + */ + public void getAccountInfo() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.getAccountInfo + StorageAccountInfo accountInfo = client.getAccountInfo(); + System.out.printf("Account Kind: %s, SKU: %s%n", accountInfo.getAccountKind(), accountInfo.getSkuName()); + // END: com.azure.storage.blob.specialized.BlobClientBase.getAccountInfo + } + + /** + * Code snippet for {@link BlobClientBase#existsWithResponse(Duration, Context)} + */ + public void existsWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.existsWithResponse#Duration-Context + System.out.printf("Exists? %b%n", client.existsWithResponse(timeout, new Context(key2, value2)).getValue()); + // END: com.azure.storage.blob.specialized.BlobClientBase.existsWithResponse#Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#beginCopy(String, Map, AccessTier, RehydratePriority, + * RequestConditions, BlobRequestConditions, Duration)} + */ + public void beginCopyFromUrl() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.beginCopy#String-Map-AccessTier-RehydratePriority-RequestConditions-BlobRequestConditions-Duration + Map metadata = Collections.singletonMap("metadata", "value"); + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7)); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + SyncPoller poller = client.beginCopy(url, metadata, AccessTier.HOT, + RehydratePriority.STANDARD, modifiedRequestConditions, blobRequestConditions, Duration.ofSeconds(2)); + + PollResponse response = poller.waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); + System.out.printf("Copy identifier: %s%n", response.getValue().getCopyId()); + // END: com.azure.storage.blob.specialized.BlobClientBase.beginCopy#String-Map-AccessTier-RehydratePriority-RequestConditions-BlobRequestConditions-Duration + } + + /** + * Code snippets for {@link BlobClientBase#beginCopy(BlobBeginCopyOptions)} + */ + public void beginCopyFromUrl2() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.beginCopy#BlobBeginCopyOptions + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + BlobBeginCopySourceRequestConditions modifiedRequestConditions = new BlobBeginCopySourceRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7)); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + SyncPoller poller = client.beginCopy(new BlobBeginCopyOptions(url).setMetadata(metadata) + .setTags(tags).setTier(AccessTier.HOT).setRehydratePriority(RehydratePriority.STANDARD) + .setSourceRequestConditions(modifiedRequestConditions) + .setDestinationRequestConditions(blobRequestConditions).setPollInterval(Duration.ofSeconds(2))); + + PollResponse response = poller.waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); + System.out.printf("Copy identifier: %s%n", response.getValue().getCopyId()); + // END: com.azure.storage.blob.specialized.BlobClientBase.beginCopy#BlobBeginCopyOptions + } + + /** + * Code snippets for {@link BlobClientBase#abortCopyFromUrlWithResponse(String, String, Duration, Context)} + */ + public void abortCopyFromUrlWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.abortCopyFromUrlWithResponse#String-String-Duration-Context + System.out.printf("Aborted copy completed with status %d%n", + client.abortCopyFromUrlWithResponse(copyId, leaseId, timeout, + new Context(key2, value2)).getStatusCode()); + // END: com.azure.storage.blob.specialized.BlobClientBase.abortCopyFromUrlWithResponse#String-String-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#copyFromUrlWithResponse(String, Map, AccessTier, RequestConditions, + * BlobRequestConditions, Duration, Context)} + */ + public void copyFromUrlWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.copyFromUrlWithResponse#String-Map-AccessTier-RequestConditions-BlobRequestConditions-Duration-Context + Map metadata = Collections.singletonMap("metadata", "value"); + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7)); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + System.out.printf("Copy identifier: %s%n", + client.copyFromUrlWithResponse(url, metadata, AccessTier.HOT, modifiedRequestConditions, + blobRequestConditions, timeout, + new Context(key1, value1)).getValue()); + // END: com.azure.storage.blob.specialized.BlobClientBase.copyFromUrlWithResponse#String-Map-AccessTier-RequestConditions-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#copyFromUrlWithResponse(BlobCopyFromUrlOptions, Duration, Context)} + */ + public void copyFromUrlWithResponse2CodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.copyFromUrlWithResponse#BlobCopyFromUrlOptions-Duration-Context + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7)); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + System.out.printf("Copy identifier: %s%n", + client.copyFromUrlWithResponse(new BlobCopyFromUrlOptions(url).setMetadata(metadata).setTags(tags) + .setTier(AccessTier.HOT).setSourceRequestConditions(modifiedRequestConditions) + .setDestinationRequestConditions(blobRequestConditions), timeout, + new Context(key1, value1)).getValue()); + // END: com.azure.storage.blob.specialized.BlobClientBase.copyFromUrlWithResponse#BlobCopyFromUrlOptions-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#downloadWithResponse(OutputStream, BlobRange, DownloadRetryOptions, + * BlobRequestConditions, boolean, Duration, Context)} + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.downloadWithResponse#OutputStream-BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean-Duration-Context + BlobRange range = new BlobRange(1024, 2048L); + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + + System.out.printf("Download completed with status %d%n", + client.downloadWithResponse(new ByteArrayOutputStream(), range, options, null, false, + timeout, new Context(key2, value2)).getStatusCode()); + // END: com.azure.storage.blob.specialized.BlobClientBase.downloadWithResponse#OutputStream-BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean-Duration-Context + + } + + /** + * Code snippets for {@link BlobClientBase#downloadStreamWithResponse(OutputStream, BlobRange, DownloadRetryOptions, + * BlobRequestConditions, boolean, Duration, Context)} + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadStreamWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.downloadStreamWithResponse#OutputStream-BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean-Duration-Context + BlobRange range = new BlobRange(1024, 2048L); + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + + System.out.printf("Download completed with status %d%n", + client.downloadStreamWithResponse(new ByteArrayOutputStream(), range, options, null, false, + timeout, new Context(key2, value2)).getStatusCode()); + // END: com.azure.storage.blob.specialized.BlobClientBase.downloadStreamWithResponse#OutputStream-BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#downloadContentWithResponse(DownloadRetryOptions, BlobRequestConditions, Duration, Context)} + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadContentWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.downloadContentWithResponse#DownloadRetryOptions-BlobRequestConditions-Duration-Context + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + + BlobDownloadContentResponse contentResponse = client.downloadContentWithResponse(options, null, + timeout, new Context(key2, value2)); + BinaryData content = contentResponse.getValue(); + System.out.printf("Download completed with status %d and content%s%n", + contentResponse.getStatusCode(), content.toString()); + // END: com.azure.storage.blob.specialized.BlobClientBase.downloadContentWithResponse#DownloadRetryOptions-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#downloadContentWithResponse(DownloadRetryOptions, BlobRequestConditions, BlobRange, boolean, Duration, Context)} + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadContentWithResponse2CodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.downloadContentWithResponse#DownloadRetryOptions-BlobRequestConditions-BlobRange-boolean-Duration-Context + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + BlobRange range = new BlobRange(1024, 2048L); + + BlobDownloadContentResponse contentResponse = client.downloadContentWithResponse(options, null, + range, false, timeout, new Context(key2, value2)); + BinaryData content = contentResponse.getValue(); + System.out.printf("Download completed with status %d and content%s%n", + contentResponse.getStatusCode(), content.toString()); + // END: com.azure.storage.blob.specialized.BlobClientBase.downloadContentWithResponse#DownloadRetryOptions-BlobRequestConditions-BlobRange-boolean-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#deleteWithResponse(DeleteSnapshotsOptionType, BlobRequestConditions, Duration, + * Context)} + */ + public void deleteWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.deleteWithResponse#DeleteSnapshotsOptionType-BlobRequestConditions-Duration-Context + System.out.printf("Delete completed with status %d%n", + client.deleteWithResponse(DeleteSnapshotsOptionType.INCLUDE, null, timeout, + new Context(key1, value1)).getStatusCode()); + // END: com.azure.storage.blob.specialized.BlobClientBase.deleteWithResponse#DeleteSnapshotsOptionType-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#getPropertiesWithResponse(BlobRequestConditions, Duration, Context)} + */ + public void getPropertiesWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.getPropertiesWithResponse#BlobRequestConditions-Duration-Context + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + BlobProperties properties = client.getPropertiesWithResponse(requestConditions, timeout, + new Context(key2, value2)).getValue(); + System.out.printf("Type: %s, Size: %d%n", properties.getBlobType(), properties.getBlobSize()); + // END: com.azure.storage.blob.specialized.BlobClientBase.getPropertiesWithResponse#BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#setHttpHeadersWithResponse(BlobHttpHeaders, BlobRequestConditions, Duration, + * Context)} + */ + public void setHTTPHeadersWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.setHttpHeadersWithResponse#BlobHttpHeaders-BlobRequestConditions-Duration-Context + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + System.out.printf("Set HTTP headers completed with status %d%n", + client.setHttpHeadersWithResponse(new BlobHttpHeaders() + .setContentLanguage("en-US") + .setContentType("binary"), requestConditions, timeout, new Context(key1, value1)) + .getStatusCode()); + // END: com.azure.storage.blob.specialized.BlobClientBase.setHttpHeadersWithResponse#BlobHttpHeaders-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#setMetadataWithResponse(Map, BlobRequestConditions, Duration, Context)} + */ + public void setMetadataWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.setMetadataWithResponse#Map-BlobRequestConditions-Duration-Context + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + System.out.printf("Set metadata completed with status %d%n", + client.setMetadataWithResponse(Collections.singletonMap("metadata", "value"), requestConditions, timeout, + new Context(key1, value1)).getStatusCode()); + // END: com.azure.storage.blob.specialized.BlobClientBase.setMetadataWithResponse#Map-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#getTagsWithResponse(BlobGetTagsOptions, Duration, Context)} + */ + public void getTagsWithResponse() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.getTagsWithResponse#BlobGetTagsOptions-Duration-Context + Map tags = client.getTagsWithResponse(new BlobGetTagsOptions(), timeout, + new Context(key1, value1)).getValue(); + System.out.printf("Number of tags: %d%n", tags.size()); + // END: com.azure.storage.blob.specialized.BlobClientBase.getTagsWithResponse#BlobGetTagsOptions-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#setTagsWithResponse(BlobSetTagsOptions, Duration, Context)} + */ + public void setTagsWithResponse() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.setTagsWithResponse#BlobSetTagsOptions-Duration-Context + System.out.printf("Set metadata completed with status %d%n", + client.setTagsWithResponse(new BlobSetTagsOptions(Collections.singletonMap("tag", "value")), timeout, + new Context(key1, value1)) + .getStatusCode()); + // END: com.azure.storage.blob.specialized.BlobClientBase.setTagsWithResponse#BlobSetTagsOptions-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#createSnapshotWithResponse(Map, BlobRequestConditions, Duration, + * Context)} + */ + public void createSnapshotWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.createSnapshotWithResponse#Map-BlobRequestConditions-Duration-Context + Map snapshotMetadata = Collections.singletonMap("metadata", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + System.out.printf("Identifier for the snapshot is %s%n", + client.createSnapshotWithResponse(snapshotMetadata, requestConditions, timeout, + new Context(key1, value1)).getValue()); + // END: com.azure.storage.blob.specialized.BlobClientBase.createSnapshotWithResponse#Map-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#setAccessTierWithResponse(AccessTier, RehydratePriority, String, Duration, Context)} + */ + public void setTierWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.setAccessTierWithResponse#AccessTier-RehydratePriority-String-Duration-Context + System.out.printf("Set tier completed with status code %d%n", + client.setAccessTierWithResponse(AccessTier.HOT, RehydratePriority.STANDARD, leaseId, timeout, + new Context(key2, value2)).getStatusCode()); + // END: com.azure.storage.blob.specialized.BlobClientBase.setAccessTierWithResponse#AccessTier-RehydratePriority-String-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#setAccessTierWithResponse(BlobSetAccessTierOptions, Duration, Context)} + */ + public void setTierWithResponseCodeSnippets2() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.setAccessTierWithResponse#BlobSetAccessTierOptions-Duration-Context + System.out.printf("Set tier completed with status code %d%n", + client.setAccessTierWithResponse(new BlobSetAccessTierOptions(AccessTier.HOT) + .setPriority(RehydratePriority.STANDARD) + .setLeaseId(leaseId) + .setTagsConditions(tags), + timeout, new Context(key2, value2)).getStatusCode()); + // END: com.azure.storage.blob.specialized.BlobClientBase.setAccessTierWithResponse#BlobSetAccessTierOptions-Duration-Context + } + + /** + * Code snippet for {@link BlobClientBase#undeleteWithResponse(Duration, Context)} + */ + public void undeleteWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.undeleteWithResponse#Duration-Context + System.out.printf("Undelete completed with status %d%n", client.undeleteWithResponse(timeout, + new Context(key1, value1)).getStatusCode()); + // END: com.azure.storage.blob.specialized.BlobClientBase.undeleteWithResponse#Duration-Context + } + + /** + * Code snippet for {@link BlobClientBase#getAccountInfoWithResponse(Duration, Context)} + */ + public void getAccountInfoWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.getAccountInfoWithResponse#Duration-Context + StorageAccountInfo accountInfo = client.getAccountInfoWithResponse(timeout, new Context(key1, value1)).getValue(); + System.out.printf("Account Kind: %s, SKU: %s%n", accountInfo.getAccountKind(), accountInfo.getSkuName()); + // END: com.azure.storage.blob.specialized.BlobClientBase.getAccountInfoWithResponse#Duration-Context + } + + /** + * Code snippet for {@link BlobClientBase#generateUserDelegationSas(BlobServiceSasSignatureValues, UserDelegationKey)} + * and {@link BlobClientBase#generateSas(BlobServiceSasSignatureValues)} + */ + public void generateSas() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.generateSas#BlobServiceSasSignatureValues + OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1); + BlobSasPermission permission = new BlobSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues values = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + client.generateSas(values); // Client must be authenticated via StorageSharedKeyCredential + // END: com.azure.storage.blob.specialized.BlobClientBase.generateSas#BlobServiceSasSignatureValues + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey + OffsetDateTime myExpiryTime = OffsetDateTime.now().plusDays(1); + BlobSasPermission myPermission = new BlobSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues myValues = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + client.generateUserDelegationSas(values, userDelegationKey); + // END: com.azure.storage.blob.specialized.BlobClientBase.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey + } + + /** + * Code snippet for {@link BlobClientBase#generateUserDelegationSas(BlobServiceSasSignatureValues, UserDelegationKey, String, Context)} + * and {@link BlobClientBase#generateSas(BlobServiceSasSignatureValues, Context)} + */ + public void generateSasWithContext() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.generateSas#BlobServiceSasSignatureValues-Context + OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1); + BlobSasPermission permission = new BlobSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues values = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + // Client must be authenticated via StorageSharedKeyCredential + client.generateSas(values, new Context(key1, value1)); + // END: com.azure.storage.blob.specialized.BlobClientBase.generateSas#BlobServiceSasSignatureValues-Context + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey-String-Context + OffsetDateTime myExpiryTime = OffsetDateTime.now().plusDays(1); + BlobSasPermission myPermission = new BlobSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues myValues = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + client.generateUserDelegationSas(values, userDelegationKey, accountName, new Context(key1, value1)); + // END: com.azure.storage.blob.specialized.BlobClientBase.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey-String-Context + } + + /** + * Code snippet for {@link BlobClientBase#openQueryInputStream(String)} + */ + public void openQueryInputStream() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.openQueryInputStream#String + String expression = "SELECT * from BlobStorage"; + InputStream inputStream = client.openQueryInputStream(expression); + // Now you can read from the input stream like you would normally. + // END: com.azure.storage.blob.specialized.BlobClientBase.openQueryInputStream#String + } + + /** + * Code snippet for {@link BlobClientBase#openQueryInputStreamWithResponse(BlobQueryOptions)} + */ + public void openQueryInputStream2() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.openQueryInputStream#BlobQueryOptions + String expression = "SELECT * from BlobStorage"; + BlobQuerySerialization input = new BlobQueryDelimitedSerialization() + .setColumnSeparator(',') + .setEscapeChar('\n') + .setRecordSeparator('\n') + .setHeadersPresent(true) + .setFieldQuote('"'); + BlobQuerySerialization output = new BlobQueryJsonSerialization() + .setRecordSeparator('\n'); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId("leaseId"); + Consumer errorConsumer = System.out::println; + Consumer progressConsumer = progress -> System.out.println("total blob bytes read: " + + progress.getBytesScanned()); + BlobQueryOptions queryOptions = new BlobQueryOptions(expression) + .setInputSerialization(input) + .setOutputSerialization(output) + .setRequestConditions(requestConditions) + .setErrorConsumer(errorConsumer) + .setProgressConsumer(progressConsumer); + + InputStream inputStream = client.openQueryInputStreamWithResponse(queryOptions).getValue(); + // Now you can read from the input stream like you would normally. + // END: com.azure.storage.blob.specialized.BlobClientBase.openQueryInputStream#BlobQueryOptions + } + + /** + * Code snippet for {@link BlobClientBase#query(OutputStream, String)} + */ + public void query() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.query#OutputStream-String + ByteArrayOutputStream queryData = new ByteArrayOutputStream(); + String expression = "SELECT * from BlobStorage"; + client.query(queryData, expression); + System.out.println("Query completed."); + // END: com.azure.storage.blob.specialized.BlobClientBase.query#OutputStream-String + } + + /** + * Code snippet for {@link BlobClientBase#queryWithResponse(BlobQueryOptions, Duration, Context)} + */ + public void queryWithResponse() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.queryWithResponse#BlobQueryOptions-Duration-Context + ByteArrayOutputStream queryData = new ByteArrayOutputStream(); + String expression = "SELECT * from BlobStorage"; + BlobQueryJsonSerialization input = new BlobQueryJsonSerialization() + .setRecordSeparator('\n'); + BlobQueryDelimitedSerialization output = new BlobQueryDelimitedSerialization() + .setEscapeChar('\0') + .setColumnSeparator(',') + .setRecordSeparator('\n') + .setFieldQuote('\'') + .setHeadersPresent(true); + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + Consumer errorConsumer = System.out::println; + Consumer progressConsumer = progress -> System.out.println("total blob bytes read: " + + progress.getBytesScanned()); + BlobQueryOptions queryOptions = new BlobQueryOptions(expression, queryData) + .setInputSerialization(input) + .setOutputSerialization(output) + .setRequestConditions(requestConditions) + .setErrorConsumer(errorConsumer) + .setProgressConsumer(progressConsumer); + System.out.printf("Query completed with status %d%n", + client.queryWithResponse(queryOptions, timeout, new Context(key1, value1)) + .getStatusCode()); + // END: com.azure.storage.blob.specialized.BlobClientBase.queryWithResponse#BlobQueryOptions-Duration-Context + } + + /** + * Code snippet for {@link BlobClientBase#setImmutabilityPolicy(BlobImmutabilityPolicy)} and + * {@link BlobClientBase#setImmutabilityPolicyWithResponse(BlobImmutabilityPolicy, BlobRequestConditions, Duration, Context)} + */ + public void setImmutabilityPolicy() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.setImmutabilityPolicy#BlobImmutabilityPolicy + BlobImmutabilityPolicy policy = new BlobImmutabilityPolicy() + .setPolicyMode(BlobImmutabilityPolicyMode.LOCKED) + .setExpiryTime(OffsetDateTime.now().plusDays(1)); + BlobImmutabilityPolicy setPolicy = client.setImmutabilityPolicy(policy); + System.out.println("Successfully completed setting the immutability policy"); + // END: com.azure.storage.blob.specialized.BlobClientBase.setImmutabilityPolicy#BlobImmutabilityPolicy + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.setImmutabilityPolicyWithResponse#BlobImmutabilityPolicy-BlobRequestConditions-Duration-Context + BlobImmutabilityPolicy immutabilityPolicy = new BlobImmutabilityPolicy() + .setPolicyMode(BlobImmutabilityPolicyMode.LOCKED) + .setExpiryTime(OffsetDateTime.now().plusDays(1)); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(1)); + Response response = client.setImmutabilityPolicyWithResponse(immutabilityPolicy, + requestConditions, timeout, new Context(key1, value1)); + System.out.println("Successfully completed setting the immutability policy"); + // END: com.azure.storage.blob.specialized.BlobClientBase.setImmutabilityPolicyWithResponse#BlobImmutabilityPolicy-BlobRequestConditions-Duration-Context + } + + /** + * Code snippet for {@link BlobClientBase#deleteImmutabilityPolicy()} and + * {@link BlobClientBase#deleteImmutabilityPolicyWithResponse(Duration, Context)} + */ + public void deleteImmutabilityPolicy() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.deleteImmutabilityPolicy + client.deleteImmutabilityPolicy(); + System.out.println("Completed immutability policy deletion."); + // END: com.azure.storage.blob.specialized.BlobClientBase.deleteImmutabilityPolicy + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.deleteImmutabilityPolicyWithResponse#Duration-Context + System.out.println("Delete immutability policy completed with status: " + + client.deleteImmutabilityPolicyWithResponse(timeout, new Context(key1, value1)).getStatusCode()); + // END: com.azure.storage.blob.specialized.BlobClientBase.deleteImmutabilityPolicyWithResponse#Duration-Context + } + + /** + * Code snippet for {@link BlobClientBase#setLegalHold(boolean)} and + * {@link BlobClientBase#setLegalHoldWithResponse(boolean, Duration, Context)} + */ + public void setLegalHold() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.setLegalHold#boolean + System.out.println("Legal hold status: " + client.setLegalHold(true)); + // END: com.azure.storage.blob.specialized.BlobClientBase.setLegalHold#boolean + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.setLegalHoldWithResponse#boolean-Duration-Context + System.out.println("Legal hold status: " + client.setLegalHoldWithResponse(true, timeout, + new Context(key1, value1))); + // END: com.azure.storage.blob.specialized.BlobClientBase.setLegalHoldWithResponse#boolean-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#deleteIfExists()} and + * {@link BlobClientBase#deleteIfExistsWithResponse(DeleteSnapshotsOptionType, BlobRequestConditions, Duration, Context)} + */ + public void deleteIfExistsCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.deleteIfExists + boolean result = client.deleteIfExists(); + System.out.println("Delete completed: " + result); + // END: com.azure.storage.blob.specialized.BlobClientBase.deleteIfExists + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.deleteIfExistsWithResponse#DeleteSnapshotsOptionType-BlobRequestConditions-Duration-Context + Response response = client.deleteIfExistsWithResponse(DeleteSnapshotsOptionType.INCLUDE, null, timeout, + new Context(key1, value1)); + if (response.getStatusCode() == 404) { + System.out.println("Does not exist."); + } else { + System.out.printf("Delete completed with status %d%n", response.getStatusCode()); + } + // END: com.azure.storage.blob.specialized.BlobClientBase.deleteIfExistsWithResponse#DeleteSnapshotsOptionType-BlobRequestConditions-Duration-Context + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample32/v2/BlobClientBaseJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample32/v2/BlobClientBaseJavaDocCodeSnippets.java new file mode 100644 index 000000000000..216e45dde835 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample32/v2/BlobClientBaseJavaDocCodeSnippets.java @@ -0,0 +1,807 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob.specialized; + +import com.azure.core.http.RequestConditions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; +import com.azure.core.util.polling.LongRunningOperationStatus; +import com.azure.core.util.polling.PollResponse; +import com.azure.core.util.polling.SyncPoller; +import com.azure.storage.blob.BlobClient; +import com.azure.storage.blob.BlobClientBuilder; +import com.azure.storage.blob.BlobServiceClientBuilder; +import com.azure.storage.blob.models.AccessTier; +import com.azure.storage.blob.models.BlobBeginCopySourceRequestConditions; +import com.azure.storage.blob.models.BlobCopyInfo; +import com.azure.storage.blob.models.BlobDownloadContentResponse; +import com.azure.storage.blob.models.BlobHttpHeaders; +import com.azure.storage.blob.models.BlobImmutabilityPolicy; +import com.azure.storage.blob.models.BlobImmutabilityPolicyMode; +import com.azure.storage.blob.models.BlobProperties; +import com.azure.storage.blob.models.BlobQueryDelimitedSerialization; +import com.azure.storage.blob.models.BlobQueryError; +import com.azure.storage.blob.models.BlobQueryJsonSerialization; +import com.azure.storage.blob.models.BlobQueryProgress; +import com.azure.storage.blob.models.BlobQuerySerialization; +import com.azure.storage.blob.models.BlobRange; +import com.azure.storage.blob.models.BlobRequestConditions; +import com.azure.storage.blob.models.DeleteSnapshotsOptionType; +import com.azure.storage.blob.models.DownloadRetryOptions; +import com.azure.storage.blob.models.ParallelTransferOptions; +import com.azure.storage.blob.models.RehydratePriority; +import com.azure.storage.blob.models.StorageAccountInfo; +import com.azure.storage.blob.models.UserDelegationKey; +import com.azure.storage.blob.options.BlobBeginCopyOptions; +import com.azure.storage.blob.options.BlobCopyFromUrlOptions; +import com.azure.storage.blob.options.BlobDownloadToFileOptions; +import com.azure.storage.blob.options.BlobGetTagsOptions; +import com.azure.storage.blob.options.BlobQueryOptions; +import com.azure.storage.blob.options.BlobSetAccessTierOptions; +import com.azure.storage.blob.options.BlobSetTagsOptions; +import com.azure.storage.blob.sas.BlobSasPermission; +import com.azure.storage.blob.sas.BlobServiceSasSignatureValues; +import com.azure.storage.common.implementation.Constants; + +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.UncheckedIOException; +import java.nio.file.OpenOption; +import java.nio.file.StandardOpenOption; +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.function.Consumer; + +/** + * Code snippets for {@link BlobClientBase} + */ +@SuppressWarnings("unused") +public class BlobClientBaseJavaDocCodeSnippets { + private BlobClient client = new BlobClientBuilder().endpoint("https://storageaccount.blob.core.windows.net") + .containerName("containerName").blobName("blobName").sasToken("sasToken").buildClient(); + private String leaseId = "leaseId"; + private String tags = "tags"; + private String copyId = "copyId"; + private String url = "https://sample.com"; + private String file = "file"; + private Duration timeout = Duration.ofSeconds(30); + private String key1 = "key1"; + private String key2 = "key2"; + private String value1 = "val1"; + private String value2 = "val2"; + private String accountName = "accountName"; + private UserDelegationKey userDelegationKey = new BlobServiceClientBuilder().buildClient().getUserDelegationKey(null, null); + + /** + * Code snippets for {@link BlobClientBase#exists()} + */ + public void existsCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.exists + System.out.printf("Exists? %b%n", client.exists()); + // END: com.azure.storage.blob.specialized.BlobClientBase.exists + } + + /** + * Code snippets for {@link BlobClientBase#beginCopy(String, Duration)} + */ + public void beginCopy() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.beginCopy#String-Duration + final SyncPoller poller = client.beginCopy(url, Duration.ofSeconds(2)); + PollResponse pollResponse = poller.poll(); + System.out.printf("Copy identifier: %s%n", pollResponse.getValue().getCopyId()); + // END: com.azure.storage.blob.specialized.BlobClientBase.beginCopy#String-Duration + } + + /** + * Code snippets for {@link BlobClientBase#abortCopyFromUrl(String)} + */ + public void abortCopyFromUrl() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.abortCopyFromUrl#String + client.abortCopyFromUrl(copyId); + System.out.println("Aborted copy completed."); + // END: com.azure.storage.blob.specialized.BlobClientBase.abortCopyFromUrl#String + } + + /** + * Code snippets for {@link BlobClientBase#copyFromUrl(String)} + */ + public void copyFromUrl() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.copyFromUrl#String + System.out.printf("Copy identifier: %s%n", client.copyFromUrl(url)); + // END: com.azure.storage.blob.specialized.BlobClientBase.copyFromUrl#String + } + + /** + * Code snippets for {@link BlobClientBase#download(OutputStream)} + */ + public void download() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.download#OutputStream + client.download(new ByteArrayOutputStream()); + System.out.println("Download completed."); + // END: com.azure.storage.blob.specialized.BlobClientBase.download#OutputStream + } + + /** + * Code snippets for {@link BlobClientBase#downloadStream(OutputStream)} + */ + public void downloadStream() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.downloadStream#OutputStream + client.downloadStream(new ByteArrayOutputStream()); + System.out.println("Download completed."); + // END: com.azure.storage.blob.specialized.BlobClientBase.downloadStream#OutputStream + } + + /** + * Code snippets for {@link BlobClientBase#downloadToFile(String)}, + * {@link BlobClientBase#downloadToFileWithResponse(String, BlobRange, ParallelTransferOptions, DownloadRetryOptions, BlobRequestConditions, + * boolean, Duration, Context)} and {@link BlobClientBase#downloadToFileWithResponse(BlobDownloadToFileOptions, Duration, Context)} + */ + public void downloadToFile() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.downloadToFile#String + client.downloadToFile(file); + System.out.println("Completed download to file"); + // END: com.azure.storage.blob.specialized.BlobClientBase.downloadToFile#String + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.downloadToFile#String-boolean + boolean overwrite = false; // Default value + client.downloadToFile(file, overwrite); + System.out.println("Completed download to file"); + // END: com.azure.storage.blob.specialized.BlobClientBase.downloadToFile#String-boolean + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.downloadToFileWithResponse#String-BlobRange-ParallelTransferOptions-DownloadRetryOptions-BlobRequestConditions-boolean-Duration-Context + BlobRange range = new BlobRange(1024, 2048L); + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + + client.downloadToFileWithResponse(file, range, new ParallelTransferOptions().setBlockSizeLong(4L * Constants.MB), + options, null, false, timeout, new Context(key2, value2)); + System.out.println("Completed download to file"); + // END: com.azure.storage.blob.specialized.BlobClientBase.downloadToFileWithResponse#String-BlobRange-ParallelTransferOptions-DownloadRetryOptions-BlobRequestConditions-boolean-Duration-Context + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.downloadToFileWithResponse#String-BlobRange-ParallelTransferOptions-DownloadRetryOptions-BlobRequestConditions-boolean-Set-Duration-Context + BlobRange blobRange = new BlobRange(1024, 2048L); + DownloadRetryOptions downloadRetryOptions = new DownloadRetryOptions().setMaxRetryRequests(5); + Set openOptions = new HashSet<>(Arrays.asList(StandardOpenOption.CREATE_NEW, + StandardOpenOption.WRITE, StandardOpenOption.READ)); // Default options + + client.downloadToFileWithResponse(file, blobRange, new ParallelTransferOptions().setBlockSizeLong(4L * Constants.MB), + downloadRetryOptions, null, false, openOptions, timeout, new Context(key2, value2)); + System.out.println("Completed download to file"); + // END: com.azure.storage.blob.specialized.BlobClientBase.downloadToFileWithResponse#String-BlobRange-ParallelTransferOptions-DownloadRetryOptions-BlobRequestConditions-boolean-Set-Duration-Context + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.downloadToFileWithResponse#BlobDownloadToFileOptions-Duration-Context + client.downloadToFileWithResponse(new BlobDownloadToFileOptions(file) + .setRange(new BlobRange(1024, 2018L)) + .setDownloadRetryOptions(new DownloadRetryOptions().setMaxRetryRequests(5)) + .setOpenOptions(new HashSet<>(Arrays.asList(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE, + StandardOpenOption.READ))), timeout, new Context(key2, value2)); + System.out.println("Completed download to file"); + // END: com.azure.storage.blob.specialized.BlobClientBase.downloadToFileWithResponse#BlobDownloadToFileOptions-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#delete()} + */ + public void setDelete() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.delete + client.delete(); + System.out.println("Delete completed."); + // END: com.azure.storage.blob.specialized.BlobClientBase.delete + } + + /** + * Code snippets for {@link BlobClientBase#getProperties()} + */ + public void getProperties() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.getProperties + BlobProperties properties = client.getProperties(); + System.out.printf("Type: %s, Size: %d%n", properties.getBlobType(), properties.getBlobSize()); + // END: com.azure.storage.blob.specialized.BlobClientBase.getProperties + } + + /** + * Code snippets for {@link BlobClientBase#setHttpHeaders(BlobHttpHeaders)} + */ + public void setHTTPHeaders() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.setHttpHeaders#BlobHttpHeaders + client.setHttpHeaders(new BlobHttpHeaders() + .setContentLanguage("en-US") + .setContentType("binary")); + System.out.println("Set HTTP headers completed"); + // END: com.azure.storage.blob.specialized.BlobClientBase.setHttpHeaders#BlobHttpHeaders + } + + /** + * Code snippets for {@link BlobClientBase#setMetadata(Map)} + */ + public void setMetadata() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.setMetadata#Map + client.setMetadata(Collections.singletonMap("metadata", "value")); + System.out.println("Set metadata completed"); + // END: com.azure.storage.blob.specialized.BlobClientBase.setMetadata#Map + } + + /** + * Code snippets for {@link BlobClientBase#getTags()} + */ + public void getTags() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.getTags + Map tags = client.getTags(); + System.out.printf("Number of tags: %d%n", tags.size()); + // END: com.azure.storage.blob.specialized.BlobClientBase.getTags + } + + /** + * Code snippets for {@link BlobClientBase#setTags(Map)} + */ + public void setTags() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.setTags#Map + client.setTags(Collections.singletonMap("tag", "value")); + System.out.println("Set tag completed"); + // END: com.azure.storage.blob.specialized.BlobClientBase.setTags#Map + } + + /** + * Code snippets for {@link BlobClientBase#createSnapshot()} + */ + public void createSnapshot() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.createSnapshot + System.out.printf("Identifier for the snapshot is %s%n", client.createSnapshot().getSnapshotId()); + // END: com.azure.storage.blob.specialized.BlobClientBase.createSnapshot + } + + /** + * Code snippets for {@link BlobClientBase#setAccessTier(AccessTier)} + */ + public void setTier() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.setAccessTier#AccessTier + client.setAccessTier(AccessTier.HOT); + System.out.println("Set tier completed."); + // END: com.azure.storage.blob.specialized.BlobClientBase.setAccessTier#AccessTier + } + + /** + * Code snippets for {@link BlobClientBase#undelete()} + */ + public void unsetDelete() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.undelete + client.undelete(); + System.out.println("Undelete completed"); + // END: com.azure.storage.blob.specialized.BlobClientBase.undelete + } + + /** + * Code snippet for {@link BlobClientBase#getAccountInfo()} + */ + public void getAccountInfo() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.getAccountInfo + StorageAccountInfo accountInfo = client.getAccountInfo(); + System.out.printf("Account Kind: %s, SKU: %s%n", accountInfo.getAccountKind(), accountInfo.getSkuName()); + // END: com.azure.storage.blob.specialized.BlobClientBase.getAccountInfo + } + + /** + * Code snippet for {@link BlobClientBase#existsWithResponse(Duration, Context)} + */ + public void existsWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.existsWithResponse#Duration-Context + System.out.printf("Exists? %b%n", client.existsWithResponse(timeout, new Context(key2, value2)).getValue()); + // END: com.azure.storage.blob.specialized.BlobClientBase.existsWithResponse#Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#beginCopy(String, Map, AccessTier, RehydratePriority, + * RequestConditions, BlobRequestConditions, Duration)} + */ + public void beginCopyFromUrl() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.beginCopy#String-Map-AccessTier-RehydratePriority-RequestConditions-BlobRequestConditions-Duration + Map metadata = Collections.singletonMap("metadata", "value"); + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7)); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + SyncPoller poller = client.beginCopy(url, metadata, AccessTier.HOT, + RehydratePriority.STANDARD, modifiedRequestConditions, blobRequestConditions, Duration.ofSeconds(2)); + + PollResponse response = poller.waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); + System.out.printf("Copy identifier: %s%n", response.getValue().getCopyId()); + // END: com.azure.storage.blob.specialized.BlobClientBase.beginCopy#String-Map-AccessTier-RehydratePriority-RequestConditions-BlobRequestConditions-Duration + } + + /** + * Code snippets for {@link BlobClientBase#beginCopy(BlobBeginCopyOptions)} + */ + public void beginCopyFromUrl2() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.beginCopy#BlobBeginCopyOptions + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + BlobBeginCopySourceRequestConditions modifiedRequestConditions = new BlobBeginCopySourceRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7)); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + SyncPoller poller = client.beginCopy(new BlobBeginCopyOptions(url).setMetadata(metadata) + .setTags(tags).setTier(AccessTier.HOT).setRehydratePriority(RehydratePriority.STANDARD) + .setSourceRequestConditions(modifiedRequestConditions) + .setDestinationRequestConditions(blobRequestConditions).setPollInterval(Duration.ofSeconds(2))); + + PollResponse response = poller.waitUntil(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED); + System.out.printf("Copy identifier: %s%n", response.getValue().getCopyId()); + // END: com.azure.storage.blob.specialized.BlobClientBase.beginCopy#BlobBeginCopyOptions + } + + /** + * Code snippets for {@link BlobClientBase#abortCopyFromUrlWithResponse(String, String, Duration, Context)} + */ + public void abortCopyFromUrlWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.abortCopyFromUrlWithResponse#String-String-Duration-Context + System.out.printf("Aborted copy completed with status %d%n", + client.abortCopyFromUrlWithResponse(copyId, leaseId, timeout, + new Context(key2, value2)).getStatusCode()); + // END: com.azure.storage.blob.specialized.BlobClientBase.abortCopyFromUrlWithResponse#String-String-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#copyFromUrlWithResponse(String, Map, AccessTier, RequestConditions, + * BlobRequestConditions, Duration, Context)} + */ + public void copyFromUrlWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.copyFromUrlWithResponse#String-Map-AccessTier-RequestConditions-BlobRequestConditions-Duration-Context + Map metadata = Collections.singletonMap("metadata", "value"); + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7)); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + System.out.printf("Copy identifier: %s%n", + client.copyFromUrlWithResponse(url, metadata, AccessTier.HOT, modifiedRequestConditions, + blobRequestConditions, timeout, + new Context(key1, value1)).getValue()); + // END: com.azure.storage.blob.specialized.BlobClientBase.copyFromUrlWithResponse#String-Map-AccessTier-RequestConditions-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#copyFromUrlWithResponse(BlobCopyFromUrlOptions, Duration, Context)} + */ + public void copyFromUrlWithResponse2CodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.copyFromUrlWithResponse#BlobCopyFromUrlOptions-Duration-Context + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7)); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + System.out.printf("Copy identifier: %s%n", + client.copyFromUrlWithResponse(new BlobCopyFromUrlOptions(url).setMetadata(metadata).setTags(tags) + .setTier(AccessTier.HOT).setSourceRequestConditions(modifiedRequestConditions) + .setDestinationRequestConditions(blobRequestConditions), timeout, + new Context(key1, value1)).getValue()); + // END: com.azure.storage.blob.specialized.BlobClientBase.copyFromUrlWithResponse#BlobCopyFromUrlOptions-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#downloadWithResponse(OutputStream, BlobRange, DownloadRetryOptions, + * BlobRequestConditions, boolean, Duration, Context)} + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.downloadWithResponse#OutputStream-BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean-Duration-Context + BlobRange range = new BlobRange(1024, 2048L); + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + + System.out.printf("Download completed with status %d%n", + client.downloadWithResponse(new ByteArrayOutputStream(), range, options, null, false, + timeout, new Context(key2, value2)).getStatusCode()); + // END: com.azure.storage.blob.specialized.BlobClientBase.downloadWithResponse#OutputStream-BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean-Duration-Context + + } + + /** + * Code snippets for {@link BlobClientBase#downloadStreamWithResponse(OutputStream, BlobRange, DownloadRetryOptions, + * BlobRequestConditions, boolean, Duration, Context)} + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadStreamWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.downloadStreamWithResponse#OutputStream-BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean-Duration-Context + BlobRange range = new BlobRange(1024, 2048L); + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + + System.out.printf("Download completed with status %d%n", + client.downloadStreamWithResponse(new ByteArrayOutputStream(), range, options, null, false, + timeout, new Context(key2, value2)).getStatusCode()); + // END: com.azure.storage.blob.specialized.BlobClientBase.downloadStreamWithResponse#OutputStream-BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#downloadContentWithResponse(DownloadRetryOptions, BlobRequestConditions, Duration, Context)} + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadContentWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.downloadContentWithResponse#DownloadRetryOptions-BlobRequestConditions-Duration-Context + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + + BlobDownloadContentResponse contentResponse = client.downloadContentWithResponse(options, null, + timeout, new Context(key2, value2)); + BinaryData content = contentResponse.getValue(); + System.out.printf("Download completed with status %d and content%s%n", + contentResponse.getStatusCode(), content.toString()); + // END: com.azure.storage.blob.specialized.BlobClientBase.downloadContentWithResponse#DownloadRetryOptions-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#downloadContentWithResponse(DownloadRetryOptions, BlobRequestConditions, BlobRange, boolean, Duration, Context)} + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadContentWithResponse2CodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.downloadContentWithResponse#DownloadRetryOptions-BlobRequestConditions-BlobRange-boolean-Duration-Context + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + BlobRange range = new BlobRange(1024, 2048L); + + BlobDownloadContentResponse contentResponse = client.downloadContentWithResponse(options, null, + range, false, timeout, new Context(key2, value2)); + BinaryData content = contentResponse.getValue(); + System.out.printf("Download completed with status %d and content%s%n", + contentResponse.getStatusCode(), content.toString()); + // END: com.azure.storage.blob.specialized.BlobClientBase.downloadContentWithResponse#DownloadRetryOptions-BlobRequestConditions-BlobRange-boolean-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#deleteWithResponse(DeleteSnapshotsOptionType, BlobRequestConditions, Duration, + * Context)} + */ + public void deleteWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.deleteWithResponse#DeleteSnapshotsOptionType-BlobRequestConditions-Duration-Context + System.out.printf("Delete completed with status %d%n", + client.deleteWithResponse(DeleteSnapshotsOptionType.INCLUDE, null, timeout, + new Context(key1, value1)).getStatusCode()); + // END: com.azure.storage.blob.specialized.BlobClientBase.deleteWithResponse#DeleteSnapshotsOptionType-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#getPropertiesWithResponse(BlobRequestConditions, Duration, Context)} + */ + public void getPropertiesWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.getPropertiesWithResponse#BlobRequestConditions-Duration-Context + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + BlobProperties properties = client.getPropertiesWithResponse(requestConditions, timeout, + new Context(key2, value2)).getValue(); + System.out.printf("Type: %s, Size: %d%n", properties.getBlobType(), properties.getBlobSize()); + // END: com.azure.storage.blob.specialized.BlobClientBase.getPropertiesWithResponse#BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#setHttpHeadersWithResponse(BlobHttpHeaders, BlobRequestConditions, Duration, + * Context)} + */ + public void setHTTPHeadersWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.setHttpHeadersWithResponse#BlobHttpHeaders-BlobRequestConditions-Duration-Context + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + System.out.printf("Set HTTP headers completed with status %d%n", + client.setHttpHeadersWithResponse(new BlobHttpHeaders() + .setContentLanguage("en-US") + .setContentType("binary"), requestConditions, timeout, new Context(key1, value1)) + .getStatusCode()); + // END: com.azure.storage.blob.specialized.BlobClientBase.setHttpHeadersWithResponse#BlobHttpHeaders-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#setMetadataWithResponse(Map, BlobRequestConditions, Duration, Context)} + */ + public void setMetadataWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.setMetadataWithResponse#Map-BlobRequestConditions-Duration-Context + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + System.out.printf("Set metadata completed with status %d%n", + client.setMetadataWithResponse(Collections.singletonMap("metadata", "value"), requestConditions, timeout, + new Context(key1, value1)).getStatusCode()); + // END: com.azure.storage.blob.specialized.BlobClientBase.setMetadataWithResponse#Map-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#getTagsWithResponse(BlobGetTagsOptions, Duration, Context)} + */ + public void getTagsWithResponse() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.getTagsWithResponse#BlobGetTagsOptions-Duration-Context + Map tags = client.getTagsWithResponse(new BlobGetTagsOptions(), timeout, + new Context(key1, value1)).getValue(); + System.out.printf("Number of tags: %d%n", tags.size()); + // END: com.azure.storage.blob.specialized.BlobClientBase.getTagsWithResponse#BlobGetTagsOptions-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#setTagsWithResponse(BlobSetTagsOptions, Duration, Context)} + */ + public void setTagsWithResponse() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.setTagsWithResponse#BlobSetTagsOptions-Duration-Context + System.out.printf("Set metadata completed with status %d%n", + client.setTagsWithResponse(new BlobSetTagsOptions(Collections.singletonMap("tag", "value")), timeout, + new Context(key1, value1)) + .getStatusCode()); + // END: com.azure.storage.blob.specialized.BlobClientBase.setTagsWithResponse#BlobSetTagsOptions-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#createSnapshotWithResponse(Map, BlobRequestConditions, Duration, + * Context)} + */ + public void createSnapshotWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.createSnapshotWithResponse#Map-BlobRequestConditions-Duration-Context + Map snapshotMetadata = Collections.singletonMap("metadata", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + System.out.printf("Identifier for the snapshot is %s%n", + client.createSnapshotWithResponse(snapshotMetadata, requestConditions, timeout, + new Context(key1, value1)).getValue()); + // END: com.azure.storage.blob.specialized.BlobClientBase.createSnapshotWithResponse#Map-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#setAccessTierWithResponse(AccessTier, RehydratePriority, String, Duration, Context)} + */ + public void setTierWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.setAccessTierWithResponse#AccessTier-RehydratePriority-String-Duration-Context + System.out.printf("Set tier completed with status code %d%n", + client.setAccessTierWithResponse(AccessTier.HOT, RehydratePriority.STANDARD, leaseId, timeout, + new Context(key2, value2)).getStatusCode()); + // END: com.azure.storage.blob.specialized.BlobClientBase.setAccessTierWithResponse#AccessTier-RehydratePriority-String-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#setAccessTierWithResponse(BlobSetAccessTierOptions, Duration, Context)} + */ + public void setTierWithResponseCodeSnippets2() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.setAccessTierWithResponse#BlobSetAccessTierOptions-Duration-Context + System.out.printf("Set tier completed with status code %d%n", + client.setAccessTierWithResponse(new BlobSetAccessTierOptions(AccessTier.HOT) + .setPriority(RehydratePriority.STANDARD) + .setLeaseId(leaseId) + .setTagsConditions(tags), + timeout, new Context(key2, value2)).getStatusCode()); + // END: com.azure.storage.blob.specialized.BlobClientBase.setAccessTierWithResponse#BlobSetAccessTierOptions-Duration-Context + } + + /** + * Code snippet for {@link BlobClientBase#undeleteWithResponse(Duration, Context)} + */ + public void undeleteWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.undeleteWithResponse#Duration-Context + System.out.printf("Undelete completed with status %d%n", client.undeleteWithResponse(timeout, + new Context(key1, value1)).getStatusCode()); + // END: com.azure.storage.blob.specialized.BlobClientBase.undeleteWithResponse#Duration-Context + } + + /** + * Code snippet for {@link BlobClientBase#getAccountInfoWithResponse(Duration, Context)} + */ + public void getAccountInfoWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.getAccountInfoWithResponse#Duration-Context + StorageAccountInfo accountInfo = client.getAccountInfoWithResponse(timeout, new Context(key1, value1)).getValue(); + System.out.printf("Account Kind: %s, SKU: %s%n", accountInfo.getAccountKind(), accountInfo.getSkuName()); + // END: com.azure.storage.blob.specialized.BlobClientBase.getAccountInfoWithResponse#Duration-Context + } + + /** + * Code snippet for {@link BlobClientBase#generateUserDelegationSas(BlobServiceSasSignatureValues, UserDelegationKey)} + * and {@link BlobClientBase#generateSas(BlobServiceSasSignatureValues)} + */ + public void generateSas() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.generateSas#BlobServiceSasSignatureValues + OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1); + BlobSasPermission permission = new BlobSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues values = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + client.generateSas(values); // Client must be authenticated via StorageSharedKeyCredential + // END: com.azure.storage.blob.specialized.BlobClientBase.generateSas#BlobServiceSasSignatureValues + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey + OffsetDateTime myExpiryTime = OffsetDateTime.now().plusDays(1); + BlobSasPermission myPermission = new BlobSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues myValues = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + client.generateUserDelegationSas(values, userDelegationKey); + // END: com.azure.storage.blob.specialized.BlobClientBase.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey + } + + /** + * Code snippet for {@link BlobClientBase#generateUserDelegationSas(BlobServiceSasSignatureValues, UserDelegationKey, String, Context)} + * and {@link BlobClientBase#generateSas(BlobServiceSasSignatureValues, Context)} + */ + public void generateSasWithContext() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.generateSas#BlobServiceSasSignatureValues-Context + OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1); + BlobSasPermission permission = new BlobSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues values = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + // Client must be authenticated via StorageSharedKeyCredential + client.generateSas(values, new Context(key1, value1)); + // END: com.azure.storage.blob.specialized.BlobClientBase.generateSas#BlobServiceSasSignatureValues-Context + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey-String-Context + OffsetDateTime myExpiryTime = OffsetDateTime.now().plusDays(1); + BlobSasPermission myPermission = new BlobSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues myValues = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + client.generateUserDelegationSas(values, userDelegationKey, accountName, new Context(key1, value1)); + // END: com.azure.storage.blob.specialized.BlobClientBase.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey-String-Context + } + + /** + * Code snippet for {@link BlobClientBase#openQueryInputStream(String)} + */ + public void openQueryInputStream() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.openQueryInputStream#String + String expression = "SELECT * from BlobStorage"; + InputStream inputStream = client.openQueryInputStream(expression); + // Now you can read from the input stream like you would normally. + // END: com.azure.storage.blob.specialized.BlobClientBase.openQueryInputStream#String + } + + /** + * Code snippet for {@link BlobClientBase#openQueryInputStreamWithResponse(BlobQueryOptions)} + */ + public void openQueryInputStream2() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.openQueryInputStream#BlobQueryOptions + String expression = "SELECT * from BlobStorage"; + BlobQuerySerialization input = new BlobQueryDelimitedSerialization() + .setColumnSeparator(',') + .setEscapeChar('\n') + .setRecordSeparator('\n') + .setHeadersPresent(true) + .setFieldQuote('"'); + BlobQuerySerialization output = new BlobQueryJsonSerialization() + .setRecordSeparator('\n'); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId("leaseId"); + Consumer errorConsumer = System.out::println; + Consumer progressConsumer = progress -> System.out.println("total blob bytes read: " + + progress.getBytesScanned()); + BlobQueryOptions queryOptions = new BlobQueryOptions(expression) + .setInputSerialization(input) + .setOutputSerialization(output) + .setRequestConditions(requestConditions) + .setErrorConsumer(errorConsumer) + .setProgressConsumer(progressConsumer); + + InputStream inputStream = client.openQueryInputStreamWithResponse(queryOptions).getValue(); + // Now you can read from the input stream like you would normally. + // END: com.azure.storage.blob.specialized.BlobClientBase.openQueryInputStream#BlobQueryOptions + } + + /** + * Code snippet for {@link BlobClientBase#query(OutputStream, String)} + */ + public void query() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.query#OutputStream-String + ByteArrayOutputStream queryData = new ByteArrayOutputStream(); + String expression = "SELECT * from BlobStorage"; + client.query(queryData, expression); + System.out.println("Query completed."); + // END: com.azure.storage.blob.specialized.BlobClientBase.query#OutputStream-String + } + + /** + * Code snippet for {@link BlobClientBase#queryWithResponse(BlobQueryOptions, Duration, Context)} + */ + public void queryWithResponse() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.queryWithResponse#BlobQueryOptions-Duration-Context + ByteArrayOutputStream queryData = new ByteArrayOutputStream(); + String expression = "SELECT * from BlobStorage"; + BlobQueryJsonSerialization input = new BlobQueryJsonSerialization() + .setRecordSeparator('\n'); + BlobQueryDelimitedSerialization output = new BlobQueryDelimitedSerialization() + .setEscapeChar('\0') + .setColumnSeparator(',') + .setRecordSeparator('\n') + .setFieldQuote('\'') + .setHeadersPresent(true); + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + Consumer errorConsumer = System.out::println; + Consumer progressConsumer = progress -> System.out.println("total blob bytes read: " + + progress.getBytesScanned()); + BlobQueryOptions queryOptions = new BlobQueryOptions(expression, queryData) + .setInputSerialization(input) + .setOutputSerialization(output) + .setRequestConditions(requestConditions) + .setErrorConsumer(errorConsumer) + .setProgressConsumer(progressConsumer); + System.out.printf("Query completed with status %d%n", + client.queryWithResponse(queryOptions, timeout, new Context(key1, value1)) + .getStatusCode()); + // END: com.azure.storage.blob.specialized.BlobClientBase.queryWithResponse#BlobQueryOptions-Duration-Context + } + + /** + * Code snippet for {@link BlobClientBase#setImmutabilityPolicy(BlobImmutabilityPolicy)} and + * {@link BlobClientBase#setImmutabilityPolicyWithResponse(BlobImmutabilityPolicy, BlobRequestConditions, Duration, Context)} + */ + public void setImmutabilityPolicy() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.setImmutabilityPolicy#BlobImmutabilityPolicy + BlobImmutabilityPolicy policy = new BlobImmutabilityPolicy() + .setPolicyMode(BlobImmutabilityPolicyMode.LOCKED) + .setExpiryTime(OffsetDateTime.now().plusDays(1)); + BlobImmutabilityPolicy setPolicy = client.setImmutabilityPolicy(policy); + System.out.println("Successfully completed setting the immutability policy"); + // END: com.azure.storage.blob.specialized.BlobClientBase.setImmutabilityPolicy#BlobImmutabilityPolicy + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.setImmutabilityPolicyWithResponse#BlobImmutabilityPolicy-BlobRequestConditions-Duration-Context + BlobImmutabilityPolicy immutabilityPolicy = new BlobImmutabilityPolicy() + .setPolicyMode(BlobImmutabilityPolicyMode.LOCKED) + .setExpiryTime(OffsetDateTime.now().plusDays(1)); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(1)); + Response response = client.setImmutabilityPolicyWithResponse(immutabilityPolicy, + requestConditions, timeout, new Context(key1, value1)); + System.out.println("Successfully completed setting the immutability policy"); + // END: com.azure.storage.blob.specialized.BlobClientBase.setImmutabilityPolicyWithResponse#BlobImmutabilityPolicy-BlobRequestConditions-Duration-Context + } + + /** + * Code snippet for {@link BlobClientBase#deleteImmutabilityPolicy()} and + * {@link BlobClientBase#deleteImmutabilityPolicyWithResponse(Duration, Context)} + */ + public void deleteImmutabilityPolicy() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.deleteImmutabilityPolicy + client.deleteImmutabilityPolicy(); + System.out.println("Completed immutability policy deletion."); + // END: com.azure.storage.blob.specialized.BlobClientBase.deleteImmutabilityPolicy + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.deleteImmutabilityPolicyWithResponse#Duration-Context + System.out.println("Delete immutability policy completed with status: " + + client.deleteImmutabilityPolicyWithResponse(timeout, new Context(key1, value1)).getStatusCode()); + // END: com.azure.storage.blob.specialized.BlobClientBase.deleteImmutabilityPolicyWithResponse#Duration-Context + } + + /** + * Code snippet for {@link BlobClientBase#setLegalHold(boolean)} and + * {@link BlobClientBase#setLegalHoldWithResponse(boolean, Duration, Context)} + */ + public void setLegalHold() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.setLegalHold#boolean + System.out.println("Legal hold status: " + client.setLegalHold(true)); + // END: com.azure.storage.blob.specialized.BlobClientBase.setLegalHold#boolean + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.setLegalHoldWithResponse#boolean-Duration-Context + System.out.println("Legal hold status: " + client.setLegalHoldWithResponse(true, timeout, + new Context(key1, value1))); + // END: com.azure.storage.blob.specialized.BlobClientBase.setLegalHoldWithResponse#boolean-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#deleteIfExists()} and + * {@link BlobClientBase#deleteIfExistsWithResponse(DeleteSnapshotsOptionType, BlobRequestConditions, Duration, Context)} + */ + public void deleteIfExistsCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.deleteIfExists + boolean result = client.deleteIfExists(); + System.out.println("Delete completed: " + result); + // END: com.azure.storage.blob.specialized.BlobClientBase.deleteIfExists + + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.deleteIfExistsWithResponse#DeleteSnapshotsOptionType-BlobRequestConditions-Duration-Context + Response response = client.deleteIfExistsWithResponse(DeleteSnapshotsOptionType.INCLUDE, null, timeout, + new Context(key1, value1)); + if (response.getStatusCode() == 404) { + System.out.println("Does not exist."); + } else { + System.out.printf("Delete completed with status %d%n", response.getStatusCode()); + } + // END: com.azure.storage.blob.specialized.BlobClientBase.deleteIfExistsWithResponse#DeleteSnapshotsOptionType-BlobRequestConditions-Duration-Context + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample33/v1/BlockBlobAsyncClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample33/v1/BlockBlobAsyncClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..ea5f433d6835 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample33/v1/BlockBlobAsyncClientJavaDocCodeSnippets.java @@ -0,0 +1,416 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob.specialized; + +import com.azure.core.util.BinaryData; +import com.azure.storage.blob.models.AccessTier; +import com.azure.storage.blob.models.BlobHttpHeaders; +import com.azure.storage.blob.models.BlobRange; +import com.azure.storage.blob.models.BlobRequestConditions; +import com.azure.storage.blob.options.BlobUploadFromUrlOptions; +import com.azure.storage.blob.options.BlockBlobCommitBlockListOptions; +import com.azure.storage.blob.options.BlockBlobListBlocksOptions; +import com.azure.storage.blob.options.BlockBlobSimpleUploadOptions; +import com.azure.storage.blob.models.BlockList; +import com.azure.storage.blob.models.BlockListType; +import com.azure.storage.blob.options.BlockBlobStageBlockFromUrlOptions; +import com.azure.storage.blob.options.BlockBlobStageBlockOptions; +import reactor.core.publisher.Flux; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.OffsetDateTime; +import java.util.Base64; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +/** + * Code snippet for {@link BlockBlobAsyncClient} + */ +@SuppressWarnings({"unused"}) +public class BlockBlobAsyncClientJavaDocCodeSnippets { + private BlockBlobAsyncClient client = new SpecializedBlobClientBuilder().buildBlockBlobAsyncClient(); + private Flux data = Flux.just(ByteBuffer.wrap("data".getBytes(StandardCharsets.UTF_8))); + private long length = 4L; + private String tags = "tags"; + private String leaseId = "leaseId"; + private String base64BlockID = "base64BlockID"; + private String sourceUrl = "https://example.com"; + private long offset = 1024L; + private long count = length; + private byte[] md5 = MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8)); + + /** + * Constructor for snippets. + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public BlockBlobAsyncClientJavaDocCodeSnippets() throws NoSuchAlgorithmException { + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#upload(Flux, long)} + */ + public void upload() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.upload#Flux-long + client.upload(data, length).subscribe(response -> + System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getContentMd5()))); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.upload#Flux-long + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#upload(BinaryData)} + */ + public void uploadWithBinaryData() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.upload#BinaryData + BinaryData.fromFlux(data, length, false) + .flatMap(binaryData -> client.upload(binaryData)) + .subscribe(response -> + System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getContentMd5()))); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.upload#BinaryData + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#upload(Flux, long, boolean)} + */ + public void uploadWithOverwrite() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.upload#Flux-long-boolean + boolean overwrite = false; // Default behavior + client.upload(data, length, overwrite).subscribe(response -> + System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getContentMd5()))); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.upload#Flux-long-boolean + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#upload(Flux, long, boolean)} + */ + public void uploadWithOverwriteWithBinaryData() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.upload#BinaryData-boolean + boolean overwrite = false; // Default behavior + BinaryData.fromFlux(data, length, false) + .flatMap(binaryData -> client.upload(binaryData, overwrite)) + .subscribe(response -> + System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getContentMd5()))); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.upload#BinaryData-boolean + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#uploadWithResponse(Flux, long, BlobHttpHeaders, Map, AccessTier, byte[], BlobRequestConditions)} + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public void upload2() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.uploadWithResponse#Flux-long-BlobHttpHeaders-Map-AccessTier-byte-BlobRequestConditions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5("data".getBytes(StandardCharsets.UTF_8)) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + byte[] md5 = MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8)); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.uploadWithResponse(data, length, headers, metadata, AccessTier.HOT, md5, requestConditions) + .subscribe(response -> System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getValue().getContentMd5()))); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.uploadWithResponse#Flux-long-BlobHttpHeaders-Map-AccessTier-byte-BlobRequestConditions + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#uploadWithResponse(BlockBlobSimpleUploadOptions)} + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public void upload3() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.uploadWithResponse#BlockBlobSimpleUploadOptions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5("data".getBytes(StandardCharsets.UTF_8)) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + byte[] md5 = MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8)); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.uploadWithResponse(new BlockBlobSimpleUploadOptions(data, length).setHeaders(headers) + .setMetadata(metadata).setTags(tags).setTier(AccessTier.HOT).setContentMd5(md5) + .setRequestConditions(requestConditions)) + .subscribe(response -> System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getValue().getContentMd5()))); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.uploadWithResponse#BlockBlobSimpleUploadOptions + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#uploadFromUrl(String)} + */ + public void uploadFromUrlCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.uploadFromUrl#String + client.uploadFromUrl(sourceUrl) + .subscribe(response -> + System.out.printf("Uploaded BlockBlob from URL, MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getContentMd5()))); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.uploadFromUrl#String + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#uploadFromUrl(String, boolean)} + */ + public void uploadFromUrlWithOverwrite() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.uploadFromUrl#String-boolean + boolean overwrite = false; // Default behavior + client.uploadFromUrl(sourceUrl, overwrite).subscribe(response -> + System.out.printf("Uploaded BlockBlob from URL, MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getContentMd5()))); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.uploadFromUrl#String-boolean + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#uploadFromUrlWithResponse(BlobUploadFromUrlOptions)} + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public void uploadFromUrlWithResponse() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.uploadFromUrlWithResponse#BlobUploadFromUrlOptions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5("data".getBytes(StandardCharsets.UTF_8)) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + byte[] md5 = MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8)); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.uploadFromUrlWithResponse(new BlobUploadFromUrlOptions(sourceUrl).setHeaders(headers) + .setTags(tags).setTier(AccessTier.HOT).setContentMd5(md5) + .setDestinationRequestConditions(requestConditions)) + .subscribe(response -> System.out.printf("Uploaded BlockBlob from URL, MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getValue().getContentMd5()))); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.uploadFromUrlWithResponse#BlobUploadFromUrlOptions + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#stageBlock(String, Flux, long)} + */ + public void stageBlock() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.stageBlock#String-Flux-long + client.stageBlock(base64BlockID, data, length) + .subscribe( + response -> System.out.println("Staging block completed"), + error -> System.out.printf("Error when calling stage Block: %s", error)); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.stageBlock#String-Flux-long + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#stageBlock(String, BinaryData)} + */ + public void stageBlockBinaryData() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.stageBlock#String-BinaryData + BinaryData.fromFlux(data, length, false) + .flatMap(binaryData -> client.stageBlock(base64BlockID, binaryData)) + .subscribe( + response -> System.out.println("Staging block completed"), + error -> System.out.printf("Error when calling stage Block: %s", error)); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.stageBlock#String-BinaryData + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#stageBlockWithResponse(String, Flux, long, byte[], String)} + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public void stageBlock2() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.stageBlockWithResponse#String-Flux-long-byte-String + client.stageBlockWithResponse(base64BlockID, data, length, md5, leaseId).subscribe(response -> + System.out.printf("Staging block completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.stageBlockWithResponse#String-Flux-long-byte-String + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#stageBlockWithResponse(BlockBlobStageBlockOptions)} + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public void stageBlockBinaryData2() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.stageBlockWithResponse#BlockBlobStageBlockOptions + BinaryData.fromFlux(data, length, false) + .flatMap(binaryData -> client.stageBlockWithResponse( + new BlockBlobStageBlockOptions(base64BlockID, binaryData) + .setContentMd5(md5) + .setLeaseId(leaseId))) + .subscribe(response -> + System.out.printf("Staging block completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.stageBlockWithResponse#BlockBlobStageBlockOptions + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#stageBlockFromUrl(String, String, BlobRange)} + */ + public void stageBlockFromUrlCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.stageBlockFromUrl#String-String-BlobRange + client.stageBlockFromUrl(base64BlockID, sourceUrl, new BlobRange(offset, count)) + .subscribe( + response -> System.out.println("Staging block completed"), + error -> System.out.printf("Error when calling stage Block: %s", error)); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.stageBlockFromUrl#String-String-BlobRange + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#stageBlockFromUrlWithResponse(String, String, BlobRange, byte[], String, BlobRequestConditions)} + */ + public void stageBlockFromUrl2() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.stageBlockFromUrlWithResponse#String-String-BlobRange-byte-String-BlobRequestConditions + BlobRequestConditions sourceRequestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.stageBlockFromUrlWithResponse(base64BlockID, sourceUrl, new BlobRange(offset, count), null, + leaseId, sourceRequestConditions).subscribe(response -> + System.out.printf("Staging block from URL completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.stageBlockFromUrlWithResponse#String-String-BlobRange-byte-String-BlobRequestConditions + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#stageBlockFromUrlWithResponse(String, String, BlobRange, byte[], String, BlobRequestConditions)} + */ + public void stageBlockFromUrlOptionsBag() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.stageBlockFromUrlWithResponse#BlockBlobStageBlockFromUrlOptions + BlobRequestConditions sourceRequestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.stageBlockFromUrlWithResponse(new BlockBlobStageBlockFromUrlOptions(base64BlockID, sourceUrl) + .setSourceRange(new BlobRange(offset, count)).setLeaseId(leaseId) + .setSourceRequestConditions(sourceRequestConditions)).subscribe(response -> + System.out.printf("Staging block from URL completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.stageBlockFromUrlWithResponse#BlockBlobStageBlockFromUrlOptions + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#listBlocks(BlockListType)} + */ + public void listBlocks() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.listBlocks#BlockListType + client.listBlocks(BlockListType.ALL).subscribe(block -> { + System.out.println("Committed Blocks:"); + block.getCommittedBlocks().forEach(b -> System.out.printf("Name: %s, Size: %d", b.getName(), b.getSizeLong())); + + System.out.println("Uncommitted Blocks:"); + block.getUncommittedBlocks().forEach(b -> System.out.printf("Name: %s, Size: %d", b.getName(), b.getSizeLong())); + }); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.listBlocks#BlockListType + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#listBlocksWithResponse(BlockListType, String)} + */ + public void listBlocks2() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.listBlocksWithResponse#BlockListType-String + client.listBlocksWithResponse(BlockListType.ALL, leaseId).subscribe(response -> { + BlockList block = response.getValue(); + System.out.println("Committed Blocks:"); + block.getCommittedBlocks().forEach(b -> System.out.printf("Name: %s, Size: %d", b.getName(), b.getSizeLong())); + + System.out.println("Uncommitted Blocks:"); + block.getUncommittedBlocks().forEach(b -> System.out.printf("Name: %s, Size: %d", b.getName(), b.getSizeLong())); + }); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.listBlocksWithResponse#BlockListType-String + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#listBlocksWithResponse(BlockBlobListBlocksOptions)} + */ + public void listBlocks3() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.listBlocksWithResponse#BlockBlobListBlocksOptions + client.listBlocksWithResponse(new BlockBlobListBlocksOptions(BlockListType.ALL) + .setLeaseId(leaseId) + .setIfTagsMatch(tags)).subscribe(response -> { + BlockList block = response.getValue(); + System.out.println("Committed Blocks:"); + block.getCommittedBlocks().forEach(b -> System.out.printf("Name: %s, Size: %d", b.getName(), + b.getSizeLong())); + + System.out.println("Uncommitted Blocks:"); + block.getUncommittedBlocks().forEach(b -> System.out.printf("Name: %s, Size: %d", b.getName(), + b.getSizeLong())); + }); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.listBlocksWithResponse#BlockBlobListBlocksOptions + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#commitBlockList(List)} + */ + public void commitBlockList() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.commitBlockList#List + client.commitBlockList(Collections.singletonList(base64BlockID)).subscribe(response -> + System.out.printf("Committing block list completed. Last modified: %s%n", response.getLastModified())); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.commitBlockList#List + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#commitBlockList(List, boolean)} + */ + public void commitBlockListWithOverwrite() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.commitBlockList#List-boolean + boolean overwrite = false; // Default behavior + client.commitBlockList(Collections.singletonList(base64BlockID), overwrite).subscribe(response -> + System.out.printf("Committing block list completed. Last modified: %s%n", response.getLastModified())); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.commitBlockList#List-boolean + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#commitBlockListWithResponse(List, BlobHttpHeaders, Map, AccessTier, BlobRequestConditions)} + */ + public void commitBlockList2() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.commitBlockListWithResponse#List-BlobHttpHeaders-Map-AccessTier-BlobRequestConditions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5("data".getBytes(StandardCharsets.UTF_8)) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + client.commitBlockListWithResponse(Collections.singletonList(base64BlockID), headers, metadata, + AccessTier.HOT, requestConditions).subscribe(response -> + System.out.printf("Committing block list completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.commitBlockListWithResponse#List-BlobHttpHeaders-Map-AccessTier-BlobRequestConditions + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#commitBlockListWithResponse(BlockBlobCommitBlockListOptions)} + */ + public void commitBlockList3() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.commitBlockListWithResponse#BlockBlobCommitBlockListOptions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5("data".getBytes(StandardCharsets.UTF_8)) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + client.commitBlockListWithResponse(new BlockBlobCommitBlockListOptions(Collections.singletonList(base64BlockID)) + .setHeaders(headers).setMetadata(metadata).setTags(tags).setTier(AccessTier.HOT) + .setRequestConditions(requestConditions)) + .subscribe(response -> + System.out.printf("Committing block list completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.commitBlockListWithResponse#BlockBlobCommitBlockListOptions + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample33/v2/BlockBlobAsyncClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample33/v2/BlockBlobAsyncClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..ea5f433d6835 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample33/v2/BlockBlobAsyncClientJavaDocCodeSnippets.java @@ -0,0 +1,416 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob.specialized; + +import com.azure.core.util.BinaryData; +import com.azure.storage.blob.models.AccessTier; +import com.azure.storage.blob.models.BlobHttpHeaders; +import com.azure.storage.blob.models.BlobRange; +import com.azure.storage.blob.models.BlobRequestConditions; +import com.azure.storage.blob.options.BlobUploadFromUrlOptions; +import com.azure.storage.blob.options.BlockBlobCommitBlockListOptions; +import com.azure.storage.blob.options.BlockBlobListBlocksOptions; +import com.azure.storage.blob.options.BlockBlobSimpleUploadOptions; +import com.azure.storage.blob.models.BlockList; +import com.azure.storage.blob.models.BlockListType; +import com.azure.storage.blob.options.BlockBlobStageBlockFromUrlOptions; +import com.azure.storage.blob.options.BlockBlobStageBlockOptions; +import reactor.core.publisher.Flux; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.OffsetDateTime; +import java.util.Base64; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +/** + * Code snippet for {@link BlockBlobAsyncClient} + */ +@SuppressWarnings({"unused"}) +public class BlockBlobAsyncClientJavaDocCodeSnippets { + private BlockBlobAsyncClient client = new SpecializedBlobClientBuilder().buildBlockBlobAsyncClient(); + private Flux data = Flux.just(ByteBuffer.wrap("data".getBytes(StandardCharsets.UTF_8))); + private long length = 4L; + private String tags = "tags"; + private String leaseId = "leaseId"; + private String base64BlockID = "base64BlockID"; + private String sourceUrl = "https://example.com"; + private long offset = 1024L; + private long count = length; + private byte[] md5 = MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8)); + + /** + * Constructor for snippets. + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public BlockBlobAsyncClientJavaDocCodeSnippets() throws NoSuchAlgorithmException { + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#upload(Flux, long)} + */ + public void upload() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.upload#Flux-long + client.upload(data, length).subscribe(response -> + System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getContentMd5()))); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.upload#Flux-long + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#upload(BinaryData)} + */ + public void uploadWithBinaryData() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.upload#BinaryData + BinaryData.fromFlux(data, length, false) + .flatMap(binaryData -> client.upload(binaryData)) + .subscribe(response -> + System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getContentMd5()))); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.upload#BinaryData + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#upload(Flux, long, boolean)} + */ + public void uploadWithOverwrite() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.upload#Flux-long-boolean + boolean overwrite = false; // Default behavior + client.upload(data, length, overwrite).subscribe(response -> + System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getContentMd5()))); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.upload#Flux-long-boolean + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#upload(Flux, long, boolean)} + */ + public void uploadWithOverwriteWithBinaryData() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.upload#BinaryData-boolean + boolean overwrite = false; // Default behavior + BinaryData.fromFlux(data, length, false) + .flatMap(binaryData -> client.upload(binaryData, overwrite)) + .subscribe(response -> + System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getContentMd5()))); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.upload#BinaryData-boolean + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#uploadWithResponse(Flux, long, BlobHttpHeaders, Map, AccessTier, byte[], BlobRequestConditions)} + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public void upload2() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.uploadWithResponse#Flux-long-BlobHttpHeaders-Map-AccessTier-byte-BlobRequestConditions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5("data".getBytes(StandardCharsets.UTF_8)) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + byte[] md5 = MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8)); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.uploadWithResponse(data, length, headers, metadata, AccessTier.HOT, md5, requestConditions) + .subscribe(response -> System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getValue().getContentMd5()))); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.uploadWithResponse#Flux-long-BlobHttpHeaders-Map-AccessTier-byte-BlobRequestConditions + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#uploadWithResponse(BlockBlobSimpleUploadOptions)} + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public void upload3() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.uploadWithResponse#BlockBlobSimpleUploadOptions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5("data".getBytes(StandardCharsets.UTF_8)) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + byte[] md5 = MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8)); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.uploadWithResponse(new BlockBlobSimpleUploadOptions(data, length).setHeaders(headers) + .setMetadata(metadata).setTags(tags).setTier(AccessTier.HOT).setContentMd5(md5) + .setRequestConditions(requestConditions)) + .subscribe(response -> System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getValue().getContentMd5()))); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.uploadWithResponse#BlockBlobSimpleUploadOptions + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#uploadFromUrl(String)} + */ + public void uploadFromUrlCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.uploadFromUrl#String + client.uploadFromUrl(sourceUrl) + .subscribe(response -> + System.out.printf("Uploaded BlockBlob from URL, MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getContentMd5()))); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.uploadFromUrl#String + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#uploadFromUrl(String, boolean)} + */ + public void uploadFromUrlWithOverwrite() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.uploadFromUrl#String-boolean + boolean overwrite = false; // Default behavior + client.uploadFromUrl(sourceUrl, overwrite).subscribe(response -> + System.out.printf("Uploaded BlockBlob from URL, MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getContentMd5()))); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.uploadFromUrl#String-boolean + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#uploadFromUrlWithResponse(BlobUploadFromUrlOptions)} + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public void uploadFromUrlWithResponse() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.uploadFromUrlWithResponse#BlobUploadFromUrlOptions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5("data".getBytes(StandardCharsets.UTF_8)) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + byte[] md5 = MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8)); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.uploadFromUrlWithResponse(new BlobUploadFromUrlOptions(sourceUrl).setHeaders(headers) + .setTags(tags).setTier(AccessTier.HOT).setContentMd5(md5) + .setDestinationRequestConditions(requestConditions)) + .subscribe(response -> System.out.printf("Uploaded BlockBlob from URL, MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getValue().getContentMd5()))); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.uploadFromUrlWithResponse#BlobUploadFromUrlOptions + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#stageBlock(String, Flux, long)} + */ + public void stageBlock() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.stageBlock#String-Flux-long + client.stageBlock(base64BlockID, data, length) + .subscribe( + response -> System.out.println("Staging block completed"), + error -> System.out.printf("Error when calling stage Block: %s", error)); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.stageBlock#String-Flux-long + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#stageBlock(String, BinaryData)} + */ + public void stageBlockBinaryData() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.stageBlock#String-BinaryData + BinaryData.fromFlux(data, length, false) + .flatMap(binaryData -> client.stageBlock(base64BlockID, binaryData)) + .subscribe( + response -> System.out.println("Staging block completed"), + error -> System.out.printf("Error when calling stage Block: %s", error)); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.stageBlock#String-BinaryData + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#stageBlockWithResponse(String, Flux, long, byte[], String)} + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public void stageBlock2() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.stageBlockWithResponse#String-Flux-long-byte-String + client.stageBlockWithResponse(base64BlockID, data, length, md5, leaseId).subscribe(response -> + System.out.printf("Staging block completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.stageBlockWithResponse#String-Flux-long-byte-String + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#stageBlockWithResponse(BlockBlobStageBlockOptions)} + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public void stageBlockBinaryData2() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.stageBlockWithResponse#BlockBlobStageBlockOptions + BinaryData.fromFlux(data, length, false) + .flatMap(binaryData -> client.stageBlockWithResponse( + new BlockBlobStageBlockOptions(base64BlockID, binaryData) + .setContentMd5(md5) + .setLeaseId(leaseId))) + .subscribe(response -> + System.out.printf("Staging block completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.stageBlockWithResponse#BlockBlobStageBlockOptions + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#stageBlockFromUrl(String, String, BlobRange)} + */ + public void stageBlockFromUrlCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.stageBlockFromUrl#String-String-BlobRange + client.stageBlockFromUrl(base64BlockID, sourceUrl, new BlobRange(offset, count)) + .subscribe( + response -> System.out.println("Staging block completed"), + error -> System.out.printf("Error when calling stage Block: %s", error)); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.stageBlockFromUrl#String-String-BlobRange + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#stageBlockFromUrlWithResponse(String, String, BlobRange, byte[], String, BlobRequestConditions)} + */ + public void stageBlockFromUrl2() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.stageBlockFromUrlWithResponse#String-String-BlobRange-byte-String-BlobRequestConditions + BlobRequestConditions sourceRequestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.stageBlockFromUrlWithResponse(base64BlockID, sourceUrl, new BlobRange(offset, count), null, + leaseId, sourceRequestConditions).subscribe(response -> + System.out.printf("Staging block from URL completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.stageBlockFromUrlWithResponse#String-String-BlobRange-byte-String-BlobRequestConditions + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#stageBlockFromUrlWithResponse(String, String, BlobRange, byte[], String, BlobRequestConditions)} + */ + public void stageBlockFromUrlOptionsBag() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.stageBlockFromUrlWithResponse#BlockBlobStageBlockFromUrlOptions + BlobRequestConditions sourceRequestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.stageBlockFromUrlWithResponse(new BlockBlobStageBlockFromUrlOptions(base64BlockID, sourceUrl) + .setSourceRange(new BlobRange(offset, count)).setLeaseId(leaseId) + .setSourceRequestConditions(sourceRequestConditions)).subscribe(response -> + System.out.printf("Staging block from URL completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.stageBlockFromUrlWithResponse#BlockBlobStageBlockFromUrlOptions + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#listBlocks(BlockListType)} + */ + public void listBlocks() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.listBlocks#BlockListType + client.listBlocks(BlockListType.ALL).subscribe(block -> { + System.out.println("Committed Blocks:"); + block.getCommittedBlocks().forEach(b -> System.out.printf("Name: %s, Size: %d", b.getName(), b.getSizeLong())); + + System.out.println("Uncommitted Blocks:"); + block.getUncommittedBlocks().forEach(b -> System.out.printf("Name: %s, Size: %d", b.getName(), b.getSizeLong())); + }); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.listBlocks#BlockListType + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#listBlocksWithResponse(BlockListType, String)} + */ + public void listBlocks2() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.listBlocksWithResponse#BlockListType-String + client.listBlocksWithResponse(BlockListType.ALL, leaseId).subscribe(response -> { + BlockList block = response.getValue(); + System.out.println("Committed Blocks:"); + block.getCommittedBlocks().forEach(b -> System.out.printf("Name: %s, Size: %d", b.getName(), b.getSizeLong())); + + System.out.println("Uncommitted Blocks:"); + block.getUncommittedBlocks().forEach(b -> System.out.printf("Name: %s, Size: %d", b.getName(), b.getSizeLong())); + }); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.listBlocksWithResponse#BlockListType-String + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#listBlocksWithResponse(BlockBlobListBlocksOptions)} + */ + public void listBlocks3() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.listBlocksWithResponse#BlockBlobListBlocksOptions + client.listBlocksWithResponse(new BlockBlobListBlocksOptions(BlockListType.ALL) + .setLeaseId(leaseId) + .setIfTagsMatch(tags)).subscribe(response -> { + BlockList block = response.getValue(); + System.out.println("Committed Blocks:"); + block.getCommittedBlocks().forEach(b -> System.out.printf("Name: %s, Size: %d", b.getName(), + b.getSizeLong())); + + System.out.println("Uncommitted Blocks:"); + block.getUncommittedBlocks().forEach(b -> System.out.printf("Name: %s, Size: %d", b.getName(), + b.getSizeLong())); + }); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.listBlocksWithResponse#BlockBlobListBlocksOptions + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#commitBlockList(List)} + */ + public void commitBlockList() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.commitBlockList#List + client.commitBlockList(Collections.singletonList(base64BlockID)).subscribe(response -> + System.out.printf("Committing block list completed. Last modified: %s%n", response.getLastModified())); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.commitBlockList#List + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#commitBlockList(List, boolean)} + */ + public void commitBlockListWithOverwrite() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.commitBlockList#List-boolean + boolean overwrite = false; // Default behavior + client.commitBlockList(Collections.singletonList(base64BlockID), overwrite).subscribe(response -> + System.out.printf("Committing block list completed. Last modified: %s%n", response.getLastModified())); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.commitBlockList#List-boolean + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#commitBlockListWithResponse(List, BlobHttpHeaders, Map, AccessTier, BlobRequestConditions)} + */ + public void commitBlockList2() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.commitBlockListWithResponse#List-BlobHttpHeaders-Map-AccessTier-BlobRequestConditions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5("data".getBytes(StandardCharsets.UTF_8)) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + client.commitBlockListWithResponse(Collections.singletonList(base64BlockID), headers, metadata, + AccessTier.HOT, requestConditions).subscribe(response -> + System.out.printf("Committing block list completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.commitBlockListWithResponse#List-BlobHttpHeaders-Map-AccessTier-BlobRequestConditions + } + + /** + * Code snippet for {@link BlockBlobAsyncClient#commitBlockListWithResponse(BlockBlobCommitBlockListOptions)} + */ + public void commitBlockList3() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobAsyncClient.commitBlockListWithResponse#BlockBlobCommitBlockListOptions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5("data".getBytes(StandardCharsets.UTF_8)) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + client.commitBlockListWithResponse(new BlockBlobCommitBlockListOptions(Collections.singletonList(base64BlockID)) + .setHeaders(headers).setMetadata(metadata).setTags(tags).setTier(AccessTier.HOT) + .setRequestConditions(requestConditions)) + .subscribe(response -> + System.out.printf("Committing block list completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlockBlobAsyncClient.commitBlockListWithResponse#BlockBlobCommitBlockListOptions + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample34/v1/BlockBlobClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample34/v1/BlockBlobClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..72de4c960478 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample34/v1/BlockBlobClientJavaDocCodeSnippets.java @@ -0,0 +1,429 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob.specialized; + +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; +import com.azure.storage.blob.models.AccessTier; +import com.azure.storage.blob.models.BlobHttpHeaders; +import com.azure.storage.blob.models.BlobRange; +import com.azure.storage.blob.models.BlobRequestConditions; +import com.azure.storage.blob.options.BlobUploadFromUrlOptions; +import com.azure.storage.blob.options.BlockBlobCommitBlockListOptions; +import com.azure.storage.blob.options.BlockBlobListBlocksOptions; +import com.azure.storage.blob.options.BlockBlobSimpleUploadOptions; +import com.azure.storage.blob.models.BlockList; +import com.azure.storage.blob.models.BlockListType; +import com.azure.storage.blob.options.BlockBlobStageBlockFromUrlOptions; +import com.azure.storage.blob.options.BlockBlobStageBlockOptions; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Base64; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +/** + * Code snippet for {@link BlockBlobClient} + */ +@SuppressWarnings({"unused"}) +public class BlockBlobClientJavaDocCodeSnippets { + private BlockBlobClient client = new SpecializedBlobClientBuilder().buildBlockBlobClient(); + private InputStream data = new ByteArrayInputStream("data".getBytes(StandardCharsets.UTF_8)); + private long length = 4L; + private Duration timeout = Duration.ofSeconds(30); + private String leaseId = "leaseId"; + private String tags = "tags"; + private String base64BlockId = "base64BlockID"; + private String sourceUrl = "https://example.com"; + private long offset = 1024L; + private long count = length; + private byte[] md5 = MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8)); + + /** + * Constructor for code snippets. + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public BlockBlobClientJavaDocCodeSnippets() throws NoSuchAlgorithmException { + } + + /** + * Code snippet for {@link BlockBlobClient#upload(InputStream, long)} + * + * @throws IOException If an I/O error occurs + */ + public void upload() throws IOException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.upload#InputStream-long + System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(client.upload(data, length).getContentMd5())); + // END: com.azure.storage.blob.specialized.BlockBlobClient.upload#InputStream-long + } + + /** + * Code snippet for {@link BlockBlobClient#upload(BinaryData)} + * + * @throws IOException If an I/O error occurs + */ + public void uploadWithBinaryData() throws IOException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.upload#BinaryData + BinaryData binaryData = BinaryData.fromStream(data, length); + System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(client.upload(binaryData).getContentMd5())); + // END: com.azure.storage.blob.specialized.BlockBlobClient.upload#BinaryData + } + + /** + * Code snippet for {@link BlockBlobClient#upload(InputStream, long, boolean)} + * + * @throws IOException If an I/O error occurs + */ + public void uploadWithOverwrite() throws IOException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.upload#InputStream-long-boolean + boolean overwrite = false; + System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(client.upload(data, length, overwrite).getContentMd5())); + // END: com.azure.storage.blob.specialized.BlockBlobClient.upload#InputStream-long-boolean + } + + /** + * Code snippet for {@link BlockBlobClient#upload(BinaryData, boolean)} + * + * @throws IOException If an I/O error occurs + */ + public void uploadWithOverwriteWithBinaryData() throws IOException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.upload#BinaryData-boolean + boolean overwrite = false; + BinaryData binaryData = BinaryData.fromStream(data, length); + System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(client.upload(binaryData, overwrite).getContentMd5())); + // END: com.azure.storage.blob.specialized.BlockBlobClient.upload#BinaryData-boolean + } + + /** + * Code snippet for {@link BlockBlobClient#uploadWithResponse(InputStream, long, BlobHttpHeaders, Map, AccessTier, byte[], BlobRequestConditions, Duration, Context)} + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public void upload2() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.uploadWithResponse#InputStream-long-BlobHttpHeaders-Map-AccessTier-byte-BlobRequestConditions-Duration-Context + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5(MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8))) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + + byte[] md5 = MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8)); + + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context("key", "value"); + + System.out.printf("Uploaded BlockBlob MD5 is %s%n", Base64.getEncoder() + .encodeToString(client.uploadWithResponse(data, length, headers, metadata, AccessTier.HOT, md5, + requestConditions, timeout, context) + .getValue() + .getContentMd5())); + // END: com.azure.storage.blob.specialized.BlockBlobClient.uploadWithResponse#InputStream-long-BlobHttpHeaders-Map-AccessTier-byte-BlobRequestConditions-Duration-Context + } + + /** + * Code snippet for {@link BlockBlobClient#uploadWithResponse(BlockBlobSimpleUploadOptions, Duration, Context)} + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public void upload3() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.uploadWithResponse#BlockBlobSimpleUploadOptions-Duration-Context + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5(MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8))) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + + byte[] md5 = MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8)); + + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context("key", "value"); + + System.out.printf("Uploaded BlockBlob MD5 is %s%n", Base64.getEncoder() + .encodeToString(client.uploadWithResponse(new BlockBlobSimpleUploadOptions(data, length) + .setHeaders(headers).setMetadata(metadata).setTags(tags).setTier(AccessTier.HOT).setContentMd5(md5) + .setRequestConditions(requestConditions), timeout, context) + .getValue() + .getContentMd5())); + // END: com.azure.storage.blob.specialized.BlockBlobClient.uploadWithResponse#BlockBlobSimpleUploadOptions-Duration-Context + } + + /** + * Code snippet for {@link BlockBlobClient#uploadFromUrl(String)} + */ + public void uploadFromUrl() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrl#String + System.out.printf("Uploaded BlockBlob from URL, MD5 is %s%n", + Base64.getEncoder().encodeToString(client.uploadFromUrl(sourceUrl).getContentMd5())); + // END: com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrl#String + } + + /** + * Code snippet for {@link BlockBlobClient#uploadFromUrl(String, boolean)} + */ + public void uploadFromUrlWithOverwrite() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrl#String-boolean + boolean overwrite = false; + System.out.printf("Uploaded BlockBlob from URL, MD5 is %s%n", + Base64.getEncoder().encodeToString(client.uploadFromUrl(sourceUrl, overwrite).getContentMd5())); + // END: com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrl#String-boolean + } + + /** + * Code snippet for {@link BlockBlobClient#uploadFromUrlWithResponse(BlobUploadFromUrlOptions, Duration, Context)} + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public void uploadFromUrlWithResponse() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrlWithResponse#BlobUploadFromUrlOptions-Duration-Context + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5(MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8))) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + + byte[] md5 = MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8)); + + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context("key", "value"); + + System.out.printf("Uploaded BlockBlob MD5 is %s%n", Base64.getEncoder() + .encodeToString(client.uploadFromUrlWithResponse(new BlobUploadFromUrlOptions(sourceUrl) + .setHeaders(headers).setTags(tags).setTier(AccessTier.HOT).setContentMd5(md5) + .setDestinationRequestConditions(requestConditions), timeout, context) + .getValue() + .getContentMd5())); + // END: com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrlWithResponse#BlobUploadFromUrlOptions-Duration-Context + } + + /** + * Code snippet for {@link BlockBlobClient#stageBlock(String, InputStream, long)} + */ + public void stageBlock() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.stageBlock#String-InputStream-long + client.stageBlock(base64BlockId, data, length); + // END: com.azure.storage.blob.specialized.BlockBlobClient.stageBlock#String-InputStream-long + } + + /** + * Code snippet for {@link BlockBlobClient#stageBlockWithResponse(String, InputStream, long, byte[], String, Duration, Context)} + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public void stageBlock2() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.stageBlockWithResponse#String-InputStream-long-byte-String-Duration-Context + Context context = new Context("key", "value"); + System.out.printf("Staging block completed with status %d%n", + client.stageBlockWithResponse(base64BlockId, data, length, md5, leaseId, timeout, context).getStatusCode()); + // END: com.azure.storage.blob.specialized.BlockBlobClient.stageBlockWithResponse#String-InputStream-long-byte-String-Duration-Context + } + + /** + * Code snippet for {@link BlockBlobClient#stageBlock(String, BinaryData)} + */ + public void stageBlock3() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.stageBlock#String-BinaryData + BinaryData binaryData = BinaryData.fromStream(data, length); + client.stageBlock(base64BlockId, binaryData); + // END: com.azure.storage.blob.specialized.BlockBlobClient.stageBlock#String-BinaryData + } + + /** + * Code snippet for {@link BlockBlobClient#stageBlockWithResponse(String, InputStream, long, byte[], String, Duration, Context)} + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public void stageBlock4() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.stageBlockWithResponse#BlockBlobStageBlockOptions-Duration-Context + Context context = new Context("key", "value"); + BinaryData binaryData = BinaryData.fromStream(data, length); + BlockBlobStageBlockOptions options = new BlockBlobStageBlockOptions(base64BlockId, binaryData) + .setContentMd5(md5) + .setLeaseId(leaseId); + System.out.printf("Staging block completed with status %d%n", + client.stageBlockWithResponse(options, timeout, context).getStatusCode()); + // END: com.azure.storage.blob.specialized.BlockBlobClient.stageBlockWithResponse#BlockBlobStageBlockOptions-Duration-Context + } + + /** + * Code snippet for {@link BlockBlobClient#stageBlockFromUrl(String, String, BlobRange)} + */ + public void stageBlockFromUrl() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrl#String-String-BlobRange + client.stageBlockFromUrl(base64BlockId, sourceUrl, new BlobRange(offset, count)); + // END: com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrl#String-String-BlobRange + } + + /** + * Code snippet for {@link BlockBlobClient#stageBlockFromUrlWithResponse(String, String, BlobRange, byte[], String, BlobRequestConditions, Duration, Context)} + */ + public void stageBlockFromUrl2() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrlWithResponse#String-String-BlobRange-byte-String-BlobRequestConditions-Duration-Context + BlobRequestConditions sourceRequestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context("key", "value"); + + System.out.printf("Staging block from URL completed with status %d%n", + client.stageBlockFromUrlWithResponse(base64BlockId, sourceUrl, new BlobRange(offset, count), null, + leaseId, sourceRequestConditions, timeout, context).getStatusCode()); + // END: com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrlWithResponse#String-String-BlobRange-byte-String-BlobRequestConditions-Duration-Context + } + + /** + * Code snippet for {@link BlockBlobClient#stageBlockFromUrlWithResponse(String, String, BlobRange, byte[], String, BlobRequestConditions, Duration, Context)} + */ + public void stageBlockFromUrlOptionsBag() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrlWithResponse#BlockBlobStageBlockFromUrlOptions-Duration-Context + BlobRequestConditions sourceRequestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context("key", "value"); + + System.out.printf("Staging block from URL completed with status %d%n", + client.stageBlockFromUrlWithResponse(new BlockBlobStageBlockFromUrlOptions(base64BlockId, sourceUrl) + .setSourceRange(new BlobRange(offset, count)).setLeaseId(leaseId) + .setSourceRequestConditions(sourceRequestConditions), timeout, context).getStatusCode()); + // END: com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrlWithResponse#BlockBlobStageBlockFromUrlOptions-Duration-Context + } + + /** + * Code snippet for {@link BlockBlobClient#listBlocks(BlockListType)} + */ + public void listBlocks() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.listBlocks#BlockListType + BlockList block = client.listBlocks(BlockListType.ALL); + + System.out.println("Committed Blocks:"); + block.getCommittedBlocks().forEach(b -> System.out.printf("Name: %s, Size: %d", b.getName(), b.getSizeLong())); + + System.out.println("Uncommitted Blocks:"); + block.getUncommittedBlocks().forEach(b -> System.out.printf("Name: %s, Size: %d", b.getName(), b.getSizeLong())); + // END: com.azure.storage.blob.specialized.BlockBlobClient.listBlocks#BlockListType + } + + /** + * Code snippet for {@link BlockBlobClient#listBlocksWithResponse(BlockListType, String, Duration, Context)} + */ + public void listBlocks2() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.listBlocksWithResponse#BlockListType-String-Duration-Context + Context context = new Context("key", "value"); + BlockList block = client.listBlocksWithResponse(BlockListType.ALL, leaseId, timeout, context).getValue(); + + System.out.println("Committed Blocks:"); + block.getCommittedBlocks().forEach(b -> System.out.printf("Name: %s, Size: %d", b.getName(), b.getSizeLong())); + + System.out.println("Uncommitted Blocks:"); + block.getUncommittedBlocks().forEach(b -> System.out.printf("Name: %s, Size: %d", b.getName(), b.getSizeLong())); + // END: com.azure.storage.blob.specialized.BlockBlobClient.listBlocksWithResponse#BlockListType-String-Duration-Context + } + + /** + * Code snippet for {@link BlockBlobClient#listBlocksWithResponse(BlockBlobListBlocksOptions, Duration, Context)} + */ + public void listBlocks3() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.listBlocksWithResponse#BlockBlobListBlocksOptions-Duration-Context + Context context = new Context("key", "value"); + BlockList block = client.listBlocksWithResponse(new BlockBlobListBlocksOptions(BlockListType.ALL) + .setLeaseId(leaseId) + .setIfTagsMatch(tags), timeout, context).getValue(); + + System.out.println("Committed Blocks:"); + block.getCommittedBlocks().forEach(b -> System.out.printf("Name: %s, Size: %d", b.getName(), b.getSizeLong())); + + System.out.println("Uncommitted Blocks:"); + block.getUncommittedBlocks().forEach(b -> System.out.printf("Name: %s, Size: %d", b.getName(), b.getSizeLong())); + // END: com.azure.storage.blob.specialized.BlockBlobClient.listBlocksWithResponse#BlockBlobListBlocksOptions-Duration-Context + } + + /** + * Code snippet for {@link BlockBlobClient#commitBlockList(List)} + */ + public void commitBlockList() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.commitBlockList#List + System.out.printf("Committing block list completed. Last modified: %s%n", + client.commitBlockList(Collections.singletonList(base64BlockId)).getLastModified()); + // END: com.azure.storage.blob.specialized.BlockBlobClient.commitBlockList#List + } + + /** + * Code snippet for {@link BlockBlobClient#commitBlockList(List, boolean)} + */ + public void commitBlockListWithOverwrite() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.commitBlockList#List-boolean + boolean overwrite = false; // Default behavior + System.out.printf("Committing block list completed. Last modified: %s%n", + client.commitBlockList(Collections.singletonList(base64BlockId), overwrite).getLastModified()); + // END: com.azure.storage.blob.specialized.BlockBlobClient.commitBlockList#List-boolean + } + + /** + * Code snippet for {@link BlockBlobClient#commitBlockListWithResponse(List, BlobHttpHeaders, Map, AccessTier, BlobRequestConditions, Duration, Context)} + */ + public void commitBlockList2() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.uploadFromFile#List-BlobHttpHeaders-Map-AccessTier-BlobRequestConditions-Duration-Context + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5(MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8))) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context("key", "value"); + + System.out.printf("Committing block list completed with status %d%n", + client.commitBlockListWithResponse(Collections.singletonList(base64BlockId), headers, metadata, + AccessTier.HOT, requestConditions, timeout, context).getStatusCode()); + // END: com.azure.storage.blob.specialized.BlockBlobClient.uploadFromFile#List-BlobHttpHeaders-Map-AccessTier-BlobRequestConditions-Duration-Context + } + + /** + * Code snippet for {@link BlockBlobClient#commitBlockListWithResponse(BlockBlobCommitBlockListOptions, Duration, Context)} + */ + public void commitBlockList3() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.uploadFromFile#BlockBlobCommitBlockListOptions-Duration-Context + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5("data".getBytes(StandardCharsets.UTF_8)) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context("key", "value"); + + System.out.printf("Committing block list completed with status %d%n", + client.commitBlockListWithResponse( + new BlockBlobCommitBlockListOptions(Collections.singletonList(base64BlockId)).setHeaders(headers) + .setMetadata(metadata).setTags(tags).setTier(AccessTier.HOT) + .setRequestConditions(requestConditions), timeout, context) + .getStatusCode()); + // END: com.azure.storage.blob.specialized.BlockBlobClient.uploadFromFile#BlockBlobCommitBlockListOptions-Duration-Context + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample34/v2/BlockBlobClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample34/v2/BlockBlobClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..72de4c960478 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample34/v2/BlockBlobClientJavaDocCodeSnippets.java @@ -0,0 +1,429 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob.specialized; + +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; +import com.azure.storage.blob.models.AccessTier; +import com.azure.storage.blob.models.BlobHttpHeaders; +import com.azure.storage.blob.models.BlobRange; +import com.azure.storage.blob.models.BlobRequestConditions; +import com.azure.storage.blob.options.BlobUploadFromUrlOptions; +import com.azure.storage.blob.options.BlockBlobCommitBlockListOptions; +import com.azure.storage.blob.options.BlockBlobListBlocksOptions; +import com.azure.storage.blob.options.BlockBlobSimpleUploadOptions; +import com.azure.storage.blob.models.BlockList; +import com.azure.storage.blob.models.BlockListType; +import com.azure.storage.blob.options.BlockBlobStageBlockFromUrlOptions; +import com.azure.storage.blob.options.BlockBlobStageBlockOptions; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Base64; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +/** + * Code snippet for {@link BlockBlobClient} + */ +@SuppressWarnings({"unused"}) +public class BlockBlobClientJavaDocCodeSnippets { + private BlockBlobClient client = new SpecializedBlobClientBuilder().buildBlockBlobClient(); + private InputStream data = new ByteArrayInputStream("data".getBytes(StandardCharsets.UTF_8)); + private long length = 4L; + private Duration timeout = Duration.ofSeconds(30); + private String leaseId = "leaseId"; + private String tags = "tags"; + private String base64BlockId = "base64BlockID"; + private String sourceUrl = "https://example.com"; + private long offset = 1024L; + private long count = length; + private byte[] md5 = MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8)); + + /** + * Constructor for code snippets. + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public BlockBlobClientJavaDocCodeSnippets() throws NoSuchAlgorithmException { + } + + /** + * Code snippet for {@link BlockBlobClient#upload(InputStream, long)} + * + * @throws IOException If an I/O error occurs + */ + public void upload() throws IOException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.upload#InputStream-long + System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(client.upload(data, length).getContentMd5())); + // END: com.azure.storage.blob.specialized.BlockBlobClient.upload#InputStream-long + } + + /** + * Code snippet for {@link BlockBlobClient#upload(BinaryData)} + * + * @throws IOException If an I/O error occurs + */ + public void uploadWithBinaryData() throws IOException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.upload#BinaryData + BinaryData binaryData = BinaryData.fromStream(data, length); + System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(client.upload(binaryData).getContentMd5())); + // END: com.azure.storage.blob.specialized.BlockBlobClient.upload#BinaryData + } + + /** + * Code snippet for {@link BlockBlobClient#upload(InputStream, long, boolean)} + * + * @throws IOException If an I/O error occurs + */ + public void uploadWithOverwrite() throws IOException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.upload#InputStream-long-boolean + boolean overwrite = false; + System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(client.upload(data, length, overwrite).getContentMd5())); + // END: com.azure.storage.blob.specialized.BlockBlobClient.upload#InputStream-long-boolean + } + + /** + * Code snippet for {@link BlockBlobClient#upload(BinaryData, boolean)} + * + * @throws IOException If an I/O error occurs + */ + public void uploadWithOverwriteWithBinaryData() throws IOException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.upload#BinaryData-boolean + boolean overwrite = false; + BinaryData binaryData = BinaryData.fromStream(data, length); + System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(client.upload(binaryData, overwrite).getContentMd5())); + // END: com.azure.storage.blob.specialized.BlockBlobClient.upload#BinaryData-boolean + } + + /** + * Code snippet for {@link BlockBlobClient#uploadWithResponse(InputStream, long, BlobHttpHeaders, Map, AccessTier, byte[], BlobRequestConditions, Duration, Context)} + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public void upload2() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.uploadWithResponse#InputStream-long-BlobHttpHeaders-Map-AccessTier-byte-BlobRequestConditions-Duration-Context + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5(MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8))) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + + byte[] md5 = MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8)); + + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context("key", "value"); + + System.out.printf("Uploaded BlockBlob MD5 is %s%n", Base64.getEncoder() + .encodeToString(client.uploadWithResponse(data, length, headers, metadata, AccessTier.HOT, md5, + requestConditions, timeout, context) + .getValue() + .getContentMd5())); + // END: com.azure.storage.blob.specialized.BlockBlobClient.uploadWithResponse#InputStream-long-BlobHttpHeaders-Map-AccessTier-byte-BlobRequestConditions-Duration-Context + } + + /** + * Code snippet for {@link BlockBlobClient#uploadWithResponse(BlockBlobSimpleUploadOptions, Duration, Context)} + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public void upload3() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.uploadWithResponse#BlockBlobSimpleUploadOptions-Duration-Context + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5(MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8))) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + + byte[] md5 = MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8)); + + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context("key", "value"); + + System.out.printf("Uploaded BlockBlob MD5 is %s%n", Base64.getEncoder() + .encodeToString(client.uploadWithResponse(new BlockBlobSimpleUploadOptions(data, length) + .setHeaders(headers).setMetadata(metadata).setTags(tags).setTier(AccessTier.HOT).setContentMd5(md5) + .setRequestConditions(requestConditions), timeout, context) + .getValue() + .getContentMd5())); + // END: com.azure.storage.blob.specialized.BlockBlobClient.uploadWithResponse#BlockBlobSimpleUploadOptions-Duration-Context + } + + /** + * Code snippet for {@link BlockBlobClient#uploadFromUrl(String)} + */ + public void uploadFromUrl() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrl#String + System.out.printf("Uploaded BlockBlob from URL, MD5 is %s%n", + Base64.getEncoder().encodeToString(client.uploadFromUrl(sourceUrl).getContentMd5())); + // END: com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrl#String + } + + /** + * Code snippet for {@link BlockBlobClient#uploadFromUrl(String, boolean)} + */ + public void uploadFromUrlWithOverwrite() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrl#String-boolean + boolean overwrite = false; + System.out.printf("Uploaded BlockBlob from URL, MD5 is %s%n", + Base64.getEncoder().encodeToString(client.uploadFromUrl(sourceUrl, overwrite).getContentMd5())); + // END: com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrl#String-boolean + } + + /** + * Code snippet for {@link BlockBlobClient#uploadFromUrlWithResponse(BlobUploadFromUrlOptions, Duration, Context)} + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public void uploadFromUrlWithResponse() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrlWithResponse#BlobUploadFromUrlOptions-Duration-Context + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5(MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8))) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + + byte[] md5 = MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8)); + + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context("key", "value"); + + System.out.printf("Uploaded BlockBlob MD5 is %s%n", Base64.getEncoder() + .encodeToString(client.uploadFromUrlWithResponse(new BlobUploadFromUrlOptions(sourceUrl) + .setHeaders(headers).setTags(tags).setTier(AccessTier.HOT).setContentMd5(md5) + .setDestinationRequestConditions(requestConditions), timeout, context) + .getValue() + .getContentMd5())); + // END: com.azure.storage.blob.specialized.BlockBlobClient.uploadFromUrlWithResponse#BlobUploadFromUrlOptions-Duration-Context + } + + /** + * Code snippet for {@link BlockBlobClient#stageBlock(String, InputStream, long)} + */ + public void stageBlock() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.stageBlock#String-InputStream-long + client.stageBlock(base64BlockId, data, length); + // END: com.azure.storage.blob.specialized.BlockBlobClient.stageBlock#String-InputStream-long + } + + /** + * Code snippet for {@link BlockBlobClient#stageBlockWithResponse(String, InputStream, long, byte[], String, Duration, Context)} + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public void stageBlock2() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.stageBlockWithResponse#String-InputStream-long-byte-String-Duration-Context + Context context = new Context("key", "value"); + System.out.printf("Staging block completed with status %d%n", + client.stageBlockWithResponse(base64BlockId, data, length, md5, leaseId, timeout, context).getStatusCode()); + // END: com.azure.storage.blob.specialized.BlockBlobClient.stageBlockWithResponse#String-InputStream-long-byte-String-Duration-Context + } + + /** + * Code snippet for {@link BlockBlobClient#stageBlock(String, BinaryData)} + */ + public void stageBlock3() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.stageBlock#String-BinaryData + BinaryData binaryData = BinaryData.fromStream(data, length); + client.stageBlock(base64BlockId, binaryData); + // END: com.azure.storage.blob.specialized.BlockBlobClient.stageBlock#String-BinaryData + } + + /** + * Code snippet for {@link BlockBlobClient#stageBlockWithResponse(String, InputStream, long, byte[], String, Duration, Context)} + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public void stageBlock4() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.stageBlockWithResponse#BlockBlobStageBlockOptions-Duration-Context + Context context = new Context("key", "value"); + BinaryData binaryData = BinaryData.fromStream(data, length); + BlockBlobStageBlockOptions options = new BlockBlobStageBlockOptions(base64BlockId, binaryData) + .setContentMd5(md5) + .setLeaseId(leaseId); + System.out.printf("Staging block completed with status %d%n", + client.stageBlockWithResponse(options, timeout, context).getStatusCode()); + // END: com.azure.storage.blob.specialized.BlockBlobClient.stageBlockWithResponse#BlockBlobStageBlockOptions-Duration-Context + } + + /** + * Code snippet for {@link BlockBlobClient#stageBlockFromUrl(String, String, BlobRange)} + */ + public void stageBlockFromUrl() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrl#String-String-BlobRange + client.stageBlockFromUrl(base64BlockId, sourceUrl, new BlobRange(offset, count)); + // END: com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrl#String-String-BlobRange + } + + /** + * Code snippet for {@link BlockBlobClient#stageBlockFromUrlWithResponse(String, String, BlobRange, byte[], String, BlobRequestConditions, Duration, Context)} + */ + public void stageBlockFromUrl2() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrlWithResponse#String-String-BlobRange-byte-String-BlobRequestConditions-Duration-Context + BlobRequestConditions sourceRequestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context("key", "value"); + + System.out.printf("Staging block from URL completed with status %d%n", + client.stageBlockFromUrlWithResponse(base64BlockId, sourceUrl, new BlobRange(offset, count), null, + leaseId, sourceRequestConditions, timeout, context).getStatusCode()); + // END: com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrlWithResponse#String-String-BlobRange-byte-String-BlobRequestConditions-Duration-Context + } + + /** + * Code snippet for {@link BlockBlobClient#stageBlockFromUrlWithResponse(String, String, BlobRange, byte[], String, BlobRequestConditions, Duration, Context)} + */ + public void stageBlockFromUrlOptionsBag() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrlWithResponse#BlockBlobStageBlockFromUrlOptions-Duration-Context + BlobRequestConditions sourceRequestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context("key", "value"); + + System.out.printf("Staging block from URL completed with status %d%n", + client.stageBlockFromUrlWithResponse(new BlockBlobStageBlockFromUrlOptions(base64BlockId, sourceUrl) + .setSourceRange(new BlobRange(offset, count)).setLeaseId(leaseId) + .setSourceRequestConditions(sourceRequestConditions), timeout, context).getStatusCode()); + // END: com.azure.storage.blob.specialized.BlockBlobClient.stageBlockFromUrlWithResponse#BlockBlobStageBlockFromUrlOptions-Duration-Context + } + + /** + * Code snippet for {@link BlockBlobClient#listBlocks(BlockListType)} + */ + public void listBlocks() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.listBlocks#BlockListType + BlockList block = client.listBlocks(BlockListType.ALL); + + System.out.println("Committed Blocks:"); + block.getCommittedBlocks().forEach(b -> System.out.printf("Name: %s, Size: %d", b.getName(), b.getSizeLong())); + + System.out.println("Uncommitted Blocks:"); + block.getUncommittedBlocks().forEach(b -> System.out.printf("Name: %s, Size: %d", b.getName(), b.getSizeLong())); + // END: com.azure.storage.blob.specialized.BlockBlobClient.listBlocks#BlockListType + } + + /** + * Code snippet for {@link BlockBlobClient#listBlocksWithResponse(BlockListType, String, Duration, Context)} + */ + public void listBlocks2() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.listBlocksWithResponse#BlockListType-String-Duration-Context + Context context = new Context("key", "value"); + BlockList block = client.listBlocksWithResponse(BlockListType.ALL, leaseId, timeout, context).getValue(); + + System.out.println("Committed Blocks:"); + block.getCommittedBlocks().forEach(b -> System.out.printf("Name: %s, Size: %d", b.getName(), b.getSizeLong())); + + System.out.println("Uncommitted Blocks:"); + block.getUncommittedBlocks().forEach(b -> System.out.printf("Name: %s, Size: %d", b.getName(), b.getSizeLong())); + // END: com.azure.storage.blob.specialized.BlockBlobClient.listBlocksWithResponse#BlockListType-String-Duration-Context + } + + /** + * Code snippet for {@link BlockBlobClient#listBlocksWithResponse(BlockBlobListBlocksOptions, Duration, Context)} + */ + public void listBlocks3() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.listBlocksWithResponse#BlockBlobListBlocksOptions-Duration-Context + Context context = new Context("key", "value"); + BlockList block = client.listBlocksWithResponse(new BlockBlobListBlocksOptions(BlockListType.ALL) + .setLeaseId(leaseId) + .setIfTagsMatch(tags), timeout, context).getValue(); + + System.out.println("Committed Blocks:"); + block.getCommittedBlocks().forEach(b -> System.out.printf("Name: %s, Size: %d", b.getName(), b.getSizeLong())); + + System.out.println("Uncommitted Blocks:"); + block.getUncommittedBlocks().forEach(b -> System.out.printf("Name: %s, Size: %d", b.getName(), b.getSizeLong())); + // END: com.azure.storage.blob.specialized.BlockBlobClient.listBlocksWithResponse#BlockBlobListBlocksOptions-Duration-Context + } + + /** + * Code snippet for {@link BlockBlobClient#commitBlockList(List)} + */ + public void commitBlockList() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.commitBlockList#List + System.out.printf("Committing block list completed. Last modified: %s%n", + client.commitBlockList(Collections.singletonList(base64BlockId)).getLastModified()); + // END: com.azure.storage.blob.specialized.BlockBlobClient.commitBlockList#List + } + + /** + * Code snippet for {@link BlockBlobClient#commitBlockList(List, boolean)} + */ + public void commitBlockListWithOverwrite() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.commitBlockList#List-boolean + boolean overwrite = false; // Default behavior + System.out.printf("Committing block list completed. Last modified: %s%n", + client.commitBlockList(Collections.singletonList(base64BlockId), overwrite).getLastModified()); + // END: com.azure.storage.blob.specialized.BlockBlobClient.commitBlockList#List-boolean + } + + /** + * Code snippet for {@link BlockBlobClient#commitBlockListWithResponse(List, BlobHttpHeaders, Map, AccessTier, BlobRequestConditions, Duration, Context)} + */ + public void commitBlockList2() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.uploadFromFile#List-BlobHttpHeaders-Map-AccessTier-BlobRequestConditions-Duration-Context + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5(MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8))) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context("key", "value"); + + System.out.printf("Committing block list completed with status %d%n", + client.commitBlockListWithResponse(Collections.singletonList(base64BlockId), headers, metadata, + AccessTier.HOT, requestConditions, timeout, context).getStatusCode()); + // END: com.azure.storage.blob.specialized.BlockBlobClient.uploadFromFile#List-BlobHttpHeaders-Map-AccessTier-BlobRequestConditions-Duration-Context + } + + /** + * Code snippet for {@link BlockBlobClient#commitBlockListWithResponse(BlockBlobCommitBlockListOptions, Duration, Context)} + */ + public void commitBlockList3() { + // BEGIN: com.azure.storage.blob.specialized.BlockBlobClient.uploadFromFile#BlockBlobCommitBlockListOptions-Duration-Context + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5("data".getBytes(StandardCharsets.UTF_8)) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context("key", "value"); + + System.out.printf("Committing block list completed with status %d%n", + client.commitBlockListWithResponse( + new BlockBlobCommitBlockListOptions(Collections.singletonList(base64BlockId)).setHeaders(headers) + .setMetadata(metadata).setTags(tags).setTier(AccessTier.HOT) + .setRequestConditions(requestConditions), timeout, context) + .getStatusCode()); + // END: com.azure.storage.blob.specialized.BlockBlobClient.uploadFromFile#BlockBlobCommitBlockListOptions-Duration-Context + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample35/v1/LeaseAsyncClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample35/v1/LeaseAsyncClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..4b7a67f1fe32 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample35/v1/LeaseAsyncClientJavaDocCodeSnippets.java @@ -0,0 +1,218 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob.specialized; + +import com.azure.core.http.RequestConditions; +import com.azure.storage.blob.BlobClientBuilder; +import com.azure.storage.blob.models.BlobLeaseRequestConditions; +import com.azure.storage.blob.options.BlobAcquireLeaseOptions; +import com.azure.storage.blob.options.BlobBreakLeaseOptions; +import com.azure.storage.blob.options.BlobChangeLeaseOptions; +import com.azure.storage.blob.options.BlobReleaseLeaseOptions; +import com.azure.storage.blob.options.BlobRenewLeaseOptions; + +import java.time.Duration; +import java.time.OffsetDateTime; + + +public class LeaseAsyncClientJavaDocCodeSnippets { + private BlobLeaseAsyncClient client = new BlobLeaseClientBuilder() + .blobAsyncClient(new BlobClientBuilder().blobName("blob").buildAsyncClient()) + .buildAsyncClient(); + + /** + * Code snippets for {@link BlobLeaseAsyncClient#acquireLease(int)} + */ + public void acquireLeaseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.acquireLease#int + client.acquireLease(60).subscribe(response -> System.out.printf("Lease ID is %s%n", response)); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.acquireLease#int + } + + /** + * Code snippets for {@link BlobLeaseAsyncClient#renewLease()} + */ + public void renewLeaseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.renewLease + client.renewLease().subscribe(response -> System.out.printf("Renewed lease ID is %s%n", response)); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.renewLease + } + + /** + * Code snippets for {@link BlobLeaseAsyncClient#releaseLease()} + */ + public void releaseLeaseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.releaseLease + client.releaseLease().subscribe(response -> System.out.println("Completed release lease")); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.releaseLease + } + + /** + * Code snippets for {@link BlobLeaseAsyncClient#breakLease()} + */ + public void breakLeaseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.breakLease + client.breakLease().subscribe(response -> + System.out.printf("The broken lease has %d seconds remaining on the lease", response)); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.breakLease + } + + /** + * Code snippets for {@link BlobLeaseAsyncClient#changeLease(String)} + */ + public void changeLeaseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.changeLease#String + client.changeLease("proposedId").subscribe(response -> System.out.printf("Changed lease ID is %s%n", response)); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.changeLease#String + } + + /** + * Code snippets for {@link BlobLeaseAsyncClient#acquireLeaseWithResponse(int, RequestConditions)} + */ + public void acquireLeaseWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.acquireLeaseWithResponse#int-RequestConditions + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfModifiedSince(OffsetDateTime.now().minusDays(3)); + + client.acquireLeaseWithResponse(60, modifiedRequestConditions).subscribe(response -> + System.out.printf("Lease ID is %s%n", response.getValue())); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.acquireLeaseWithResponse#int-RequestConditions + } + + /** + * Code snippets for {@link BlobLeaseAsyncClient#acquireLeaseWithResponse(BlobAcquireLeaseOptions)} + */ + public void acquireLeaseWithResponseCodeSnippets2() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.acquireLeaseWithResponse#BlobAcquireLeaseOptions + BlobLeaseRequestConditions requestConditions = new BlobLeaseRequestConditions() + .setIfModifiedSince(OffsetDateTime.now().minusDays(3)); + + BlobAcquireLeaseOptions options = new BlobAcquireLeaseOptions(60) + .setRequestConditions(requestConditions); + + client.acquireLeaseWithResponse(options).subscribe(response -> + System.out.printf("Lease ID is %s%n", response.getValue())); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.acquireLeaseWithResponse#BlobAcquireLeaseOptions + } + + /** + * Code snippets for {@link BlobLeaseAsyncClient#renewLeaseWithResponse(RequestConditions)} + */ + public void renewLeaseWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.renewLeaseWithResponse#RequestConditions + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.renewLeaseWithResponse(modifiedRequestConditions).subscribe(response -> + System.out.printf("Renewed lease ID is %s%n", response.getValue())); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.renewLeaseWithResponse#RequestConditions + } + + /** + * Code snippets for {@link BlobLeaseAsyncClient#renewLeaseWithResponse(BlobRenewLeaseOptions)} + */ + public void renewLeaseWithResponseCodeSnippets2() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.renewLeaseWithResponse#BlobRenewLeaseOptions + BlobLeaseRequestConditions requestConditions = new BlobLeaseRequestConditions() + .setIfModifiedSince(OffsetDateTime.now().minusDays(3)); + + BlobRenewLeaseOptions options = new BlobRenewLeaseOptions() + .setRequestConditions(requestConditions); + + client.renewLeaseWithResponse(options).subscribe(response -> + System.out.printf("Lease ID is %s%n", response.getValue())); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.renewLeaseWithResponse#BlobRenewLeaseOptions + } + + /** + * Code snippets for {@link BlobLeaseAsyncClient#releaseLeaseWithResponse(RequestConditions)} + */ + public void releaseLeaseWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.releaseLeaseWithResponse#RequestConditions + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.releaseLeaseWithResponse(modifiedRequestConditions).subscribe(response -> + System.out.printf("Release lease completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.releaseLeaseWithResponse#RequestConditions + } + + /** + * Code snippets for {@link BlobLeaseAsyncClient#releaseLeaseWithResponse(RequestConditions)} + */ + public void releaseLeaseWithResponseCodeSnippets2() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.releaseLeaseWithResponse#BlobReleaseLeaseOptions + BlobLeaseRequestConditions requestConditions = new BlobLeaseRequestConditions() + .setIfModifiedSince(OffsetDateTime.now().minusDays(3)); + + BlobReleaseLeaseOptions options = new BlobReleaseLeaseOptions() + .setRequestConditions(requestConditions); + + client.releaseLeaseWithResponse(options).subscribe(response -> + System.out.printf("Release lease completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.releaseLeaseWithResponse#BlobReleaseLeaseOptions + } + + /** + * Code snippets for {@link BlobLeaseAsyncClient#breakLeaseWithResponse(Integer, RequestConditions)} + */ + public void breakLeaseWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.breakLeaseWithResponse#Integer-RequestConditions + Integer retainLeaseInSeconds = 5; + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.breakLeaseWithResponse(retainLeaseInSeconds, modifiedRequestConditions).subscribe(response -> + System.out.printf("The broken lease has %d seconds remaining on the lease", response.getValue())); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.breakLeaseWithResponse#Integer-RequestConditions + } + + + /** + * Code snippets for {@link BlobLeaseAsyncClient#breakLeaseWithResponse(BlobBreakLeaseOptions)} + */ + public void breakLeaseWithResponseCodeSnippets2() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.breakLeaseWithResponse#BlobBreakLeaseOptions + Integer retainLeaseInSeconds = 5; + BlobLeaseRequestConditions requestConditions = new BlobLeaseRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + BlobBreakLeaseOptions options = new BlobBreakLeaseOptions() + .setBreakPeriod(Duration.ofSeconds(retainLeaseInSeconds)) + .setRequestConditions(requestConditions); + + client.breakLeaseWithResponse(options).subscribe(response -> + System.out.printf("The broken lease has %d seconds remaining on the lease", response.getValue())); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.breakLeaseWithResponse#BlobBreakLeaseOptions + } + + /** + * Code snippets for {@link BlobLeaseAsyncClient#changeLeaseWithResponse(String, RequestConditions)} + */ + public void changeLeaseWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.changeLeaseWithResponse#String-RequestConditions + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.changeLeaseWithResponse("proposedId", modifiedRequestConditions).subscribe(response -> + System.out.printf("Changed lease ID is %s%n", response.getValue())); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.changeLeaseWithResponse#String-RequestConditions + } + + /** + * Code snippets for {@link BlobLeaseAsyncClient#changeLeaseWithResponse(BlobChangeLeaseOptions)} + */ + public void changeLeaseWithResponseCodeSnippets2() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.changeLeaseWithResponse#BlobChangeLeaseOptions + BlobLeaseRequestConditions requestConditions = new BlobLeaseRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + BlobChangeLeaseOptions options = new BlobChangeLeaseOptions("proposedId") + .setRequestConditions(requestConditions); + + client.changeLeaseWithResponse(options).subscribe(response -> + System.out.printf("Changed lease ID is %s%n", response.getValue())); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.changeLeaseWithResponse#BlobChangeLeaseOptions + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample35/v2/LeaseAsyncClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample35/v2/LeaseAsyncClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..4b7a67f1fe32 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample35/v2/LeaseAsyncClientJavaDocCodeSnippets.java @@ -0,0 +1,218 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob.specialized; + +import com.azure.core.http.RequestConditions; +import com.azure.storage.blob.BlobClientBuilder; +import com.azure.storage.blob.models.BlobLeaseRequestConditions; +import com.azure.storage.blob.options.BlobAcquireLeaseOptions; +import com.azure.storage.blob.options.BlobBreakLeaseOptions; +import com.azure.storage.blob.options.BlobChangeLeaseOptions; +import com.azure.storage.blob.options.BlobReleaseLeaseOptions; +import com.azure.storage.blob.options.BlobRenewLeaseOptions; + +import java.time.Duration; +import java.time.OffsetDateTime; + + +public class LeaseAsyncClientJavaDocCodeSnippets { + private BlobLeaseAsyncClient client = new BlobLeaseClientBuilder() + .blobAsyncClient(new BlobClientBuilder().blobName("blob").buildAsyncClient()) + .buildAsyncClient(); + + /** + * Code snippets for {@link BlobLeaseAsyncClient#acquireLease(int)} + */ + public void acquireLeaseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.acquireLease#int + client.acquireLease(60).subscribe(response -> System.out.printf("Lease ID is %s%n", response)); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.acquireLease#int + } + + /** + * Code snippets for {@link BlobLeaseAsyncClient#renewLease()} + */ + public void renewLeaseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.renewLease + client.renewLease().subscribe(response -> System.out.printf("Renewed lease ID is %s%n", response)); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.renewLease + } + + /** + * Code snippets for {@link BlobLeaseAsyncClient#releaseLease()} + */ + public void releaseLeaseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.releaseLease + client.releaseLease().subscribe(response -> System.out.println("Completed release lease")); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.releaseLease + } + + /** + * Code snippets for {@link BlobLeaseAsyncClient#breakLease()} + */ + public void breakLeaseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.breakLease + client.breakLease().subscribe(response -> + System.out.printf("The broken lease has %d seconds remaining on the lease", response)); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.breakLease + } + + /** + * Code snippets for {@link BlobLeaseAsyncClient#changeLease(String)} + */ + public void changeLeaseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.changeLease#String + client.changeLease("proposedId").subscribe(response -> System.out.printf("Changed lease ID is %s%n", response)); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.changeLease#String + } + + /** + * Code snippets for {@link BlobLeaseAsyncClient#acquireLeaseWithResponse(int, RequestConditions)} + */ + public void acquireLeaseWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.acquireLeaseWithResponse#int-RequestConditions + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfModifiedSince(OffsetDateTime.now().minusDays(3)); + + client.acquireLeaseWithResponse(60, modifiedRequestConditions).subscribe(response -> + System.out.printf("Lease ID is %s%n", response.getValue())); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.acquireLeaseWithResponse#int-RequestConditions + } + + /** + * Code snippets for {@link BlobLeaseAsyncClient#acquireLeaseWithResponse(BlobAcquireLeaseOptions)} + */ + public void acquireLeaseWithResponseCodeSnippets2() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.acquireLeaseWithResponse#BlobAcquireLeaseOptions + BlobLeaseRequestConditions requestConditions = new BlobLeaseRequestConditions() + .setIfModifiedSince(OffsetDateTime.now().minusDays(3)); + + BlobAcquireLeaseOptions options = new BlobAcquireLeaseOptions(60) + .setRequestConditions(requestConditions); + + client.acquireLeaseWithResponse(options).subscribe(response -> + System.out.printf("Lease ID is %s%n", response.getValue())); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.acquireLeaseWithResponse#BlobAcquireLeaseOptions + } + + /** + * Code snippets for {@link BlobLeaseAsyncClient#renewLeaseWithResponse(RequestConditions)} + */ + public void renewLeaseWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.renewLeaseWithResponse#RequestConditions + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.renewLeaseWithResponse(modifiedRequestConditions).subscribe(response -> + System.out.printf("Renewed lease ID is %s%n", response.getValue())); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.renewLeaseWithResponse#RequestConditions + } + + /** + * Code snippets for {@link BlobLeaseAsyncClient#renewLeaseWithResponse(BlobRenewLeaseOptions)} + */ + public void renewLeaseWithResponseCodeSnippets2() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.renewLeaseWithResponse#BlobRenewLeaseOptions + BlobLeaseRequestConditions requestConditions = new BlobLeaseRequestConditions() + .setIfModifiedSince(OffsetDateTime.now().minusDays(3)); + + BlobRenewLeaseOptions options = new BlobRenewLeaseOptions() + .setRequestConditions(requestConditions); + + client.renewLeaseWithResponse(options).subscribe(response -> + System.out.printf("Lease ID is %s%n", response.getValue())); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.renewLeaseWithResponse#BlobRenewLeaseOptions + } + + /** + * Code snippets for {@link BlobLeaseAsyncClient#releaseLeaseWithResponse(RequestConditions)} + */ + public void releaseLeaseWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.releaseLeaseWithResponse#RequestConditions + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.releaseLeaseWithResponse(modifiedRequestConditions).subscribe(response -> + System.out.printf("Release lease completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.releaseLeaseWithResponse#RequestConditions + } + + /** + * Code snippets for {@link BlobLeaseAsyncClient#releaseLeaseWithResponse(RequestConditions)} + */ + public void releaseLeaseWithResponseCodeSnippets2() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.releaseLeaseWithResponse#BlobReleaseLeaseOptions + BlobLeaseRequestConditions requestConditions = new BlobLeaseRequestConditions() + .setIfModifiedSince(OffsetDateTime.now().minusDays(3)); + + BlobReleaseLeaseOptions options = new BlobReleaseLeaseOptions() + .setRequestConditions(requestConditions); + + client.releaseLeaseWithResponse(options).subscribe(response -> + System.out.printf("Release lease completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.releaseLeaseWithResponse#BlobReleaseLeaseOptions + } + + /** + * Code snippets for {@link BlobLeaseAsyncClient#breakLeaseWithResponse(Integer, RequestConditions)} + */ + public void breakLeaseWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.breakLeaseWithResponse#Integer-RequestConditions + Integer retainLeaseInSeconds = 5; + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.breakLeaseWithResponse(retainLeaseInSeconds, modifiedRequestConditions).subscribe(response -> + System.out.printf("The broken lease has %d seconds remaining on the lease", response.getValue())); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.breakLeaseWithResponse#Integer-RequestConditions + } + + + /** + * Code snippets for {@link BlobLeaseAsyncClient#breakLeaseWithResponse(BlobBreakLeaseOptions)} + */ + public void breakLeaseWithResponseCodeSnippets2() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.breakLeaseWithResponse#BlobBreakLeaseOptions + Integer retainLeaseInSeconds = 5; + BlobLeaseRequestConditions requestConditions = new BlobLeaseRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + BlobBreakLeaseOptions options = new BlobBreakLeaseOptions() + .setBreakPeriod(Duration.ofSeconds(retainLeaseInSeconds)) + .setRequestConditions(requestConditions); + + client.breakLeaseWithResponse(options).subscribe(response -> + System.out.printf("The broken lease has %d seconds remaining on the lease", response.getValue())); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.breakLeaseWithResponse#BlobBreakLeaseOptions + } + + /** + * Code snippets for {@link BlobLeaseAsyncClient#changeLeaseWithResponse(String, RequestConditions)} + */ + public void changeLeaseWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.changeLeaseWithResponse#String-RequestConditions + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.changeLeaseWithResponse("proposedId", modifiedRequestConditions).subscribe(response -> + System.out.printf("Changed lease ID is %s%n", response.getValue())); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.changeLeaseWithResponse#String-RequestConditions + } + + /** + * Code snippets for {@link BlobLeaseAsyncClient#changeLeaseWithResponse(BlobChangeLeaseOptions)} + */ + public void changeLeaseWithResponseCodeSnippets2() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.changeLeaseWithResponse#BlobChangeLeaseOptions + BlobLeaseRequestConditions requestConditions = new BlobLeaseRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + BlobChangeLeaseOptions options = new BlobChangeLeaseOptions("proposedId") + .setRequestConditions(requestConditions); + + client.changeLeaseWithResponse(options).subscribe(response -> + System.out.printf("Changed lease ID is %s%n", response.getValue())); + // END: com.azure.storage.blob.specialized.BlobLeaseAsyncClient.changeLeaseWithResponse#BlobChangeLeaseOptions + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample36/v1/LeaseClientBuilderJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample36/v1/LeaseClientBuilderJavaDocCodeSnippets.java new file mode 100644 index 000000000000..d80100c47789 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample36/v1/LeaseClientBuilderJavaDocCodeSnippets.java @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob.specialized; + +import com.azure.storage.blob.BlobAsyncClient; +import com.azure.storage.blob.BlobClient; +import com.azure.storage.blob.BlobContainerAsyncClient; +import com.azure.storage.blob.BlobContainerClient; +import com.azure.storage.blob.BlobContainerClientBuilder; + +public class LeaseClientBuilderJavaDocCodeSnippets { + private BlobContainerAsyncClient blobContainerAsyncClient = new BlobContainerClientBuilder() + .containerName("container") + .buildAsyncClient(); + + private BlobContainerClient blobContainerClient = new BlobContainerClientBuilder() + .containerName("container") + .buildClient(); + + private BlobAsyncClient blobAsyncClient = blobContainerAsyncClient.getBlobAsyncClient("blob"); + private BlobClient blobClient = blobContainerClient.getBlobClient("blob"); + + private String leaseId = "leaseId"; + + /** + * Code snippets for {@link BlobLeaseClientBuilder#buildClient()}. + */ + public void syncInstantiationWithBlob() { + // BEGIN: com.azure.storage.blob.specialized.LeaseClientBuilder.syncInstantiationWithBlob + BlobLeaseClient blobLeaseClient = new BlobLeaseClientBuilder() + .blobClient(blobClient) + .buildClient(); + // END: com.azure.storage.blob.specialized.LeaseClientBuilder.syncInstantiationWithBlob + } + + /** + * Code snippets for {@link BlobLeaseClientBuilder#buildClient()}. + */ + public void syncInstantiationWithBlobAndLeaseId() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClientBuilder.syncInstantiationWithBlobAndLeaseId + BlobLeaseClient blobLeaseClient = new BlobLeaseClientBuilder() + .blobClient(blobClient) + .leaseId(leaseId) + .buildClient(); + // END: com.azure.storage.blob.specialized.BlobLeaseClientBuilder.syncInstantiationWithBlobAndLeaseId + } + + /** + * Code snippets for {@link BlobLeaseClientBuilder#buildClient()}. + */ + public void syncInstantiationWithContainer() { + // BEGIN: com.azure.storage.blob.specialized.LeaseClientBuilder.syncInstantiationWithContainer + BlobLeaseClient blobLeaseClient = new BlobLeaseClientBuilder() + .containerClient(blobContainerClient) + .buildClient(); + // END: com.azure.storage.blob.specialized.LeaseClientBuilder.syncInstantiationWithContainer + } + + /** + * Code snippets for {@link BlobLeaseClientBuilder#buildClient()}. + */ + public void syncInstantiationWithContainerAndLeaseId() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClientBuilder.syncInstantiationWithContainerAndLeaseId + BlobLeaseClient blobLeaseClient = new BlobLeaseClientBuilder() + .containerClient(blobContainerClient) + .leaseId(leaseId) + .buildClient(); + // END: com.azure.storage.blob.specialized.BlobLeaseClientBuilder.syncInstantiationWithContainerAndLeaseId + } + + /** + * Code snippets for {@link BlobLeaseClientBuilder#buildAsyncClient()}. + */ + public void asyncInstantiationWithBlob() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClientBuilder.asyncInstantiationWithBlob + BlobLeaseAsyncClient blobLeaseAsyncClient = new BlobLeaseClientBuilder() + .blobAsyncClient(blobAsyncClient) + .buildAsyncClient(); + // END: com.azure.storage.blob.specialized.BlobLeaseClientBuilder.asyncInstantiationWithBlob + } + + /** + * Code snippets for {@link BlobLeaseClientBuilder#buildAsyncClient()}. + */ + public void asyncInstantiationWithBlobAndLeaseId() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClientBuilder.asyncInstantiationWithBlobAndLeaseId + BlobLeaseAsyncClient blobLeaseAsyncClient = new BlobLeaseClientBuilder() + .blobAsyncClient(blobAsyncClient) + .leaseId(leaseId) + .buildAsyncClient(); + // END: com.azure.storage.blob.specialized.BlobLeaseClientBuilder.asyncInstantiationWithBlobAndLeaseId + } + + /** + * Code snippets for {@link BlobLeaseClientBuilder#buildAsyncClient()}. + */ + public void asyncInstantiationWithContainer() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClientBuilder.asyncInstantiationWithContainer + BlobLeaseAsyncClient blobLeaseAsyncClient = new BlobLeaseClientBuilder() + .containerAsyncClient(blobContainerAsyncClient) + .buildAsyncClient(); + // END: com.azure.storage.blob.specialized.BlobLeaseClientBuilder.asyncInstantiationWithContainer + } + + /** + * Code snippets for {@link BlobLeaseClientBuilder#buildAsyncClient()}. + */ + public void asyncInstantiationWithContainerAndLeaseId() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClientBuilder.asyncInstantiationWithContainerAndLeaseId + BlobLeaseAsyncClient blobLeaseAsyncClient = new BlobLeaseClientBuilder() + .containerAsyncClient(blobContainerAsyncClient) + .leaseId(leaseId) + .buildAsyncClient(); + // END: com.azure.storage.blob.specialized.BlobLeaseClientBuilder.asyncInstantiationWithContainerAndLeaseId + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample36/v2/LeaseClientBuilderJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample36/v2/LeaseClientBuilderJavaDocCodeSnippets.java new file mode 100644 index 000000000000..d80100c47789 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample36/v2/LeaseClientBuilderJavaDocCodeSnippets.java @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob.specialized; + +import com.azure.storage.blob.BlobAsyncClient; +import com.azure.storage.blob.BlobClient; +import com.azure.storage.blob.BlobContainerAsyncClient; +import com.azure.storage.blob.BlobContainerClient; +import com.azure.storage.blob.BlobContainerClientBuilder; + +public class LeaseClientBuilderJavaDocCodeSnippets { + private BlobContainerAsyncClient blobContainerAsyncClient = new BlobContainerClientBuilder() + .containerName("container") + .buildAsyncClient(); + + private BlobContainerClient blobContainerClient = new BlobContainerClientBuilder() + .containerName("container") + .buildClient(); + + private BlobAsyncClient blobAsyncClient = blobContainerAsyncClient.getBlobAsyncClient("blob"); + private BlobClient blobClient = blobContainerClient.getBlobClient("blob"); + + private String leaseId = "leaseId"; + + /** + * Code snippets for {@link BlobLeaseClientBuilder#buildClient()}. + */ + public void syncInstantiationWithBlob() { + // BEGIN: com.azure.storage.blob.specialized.LeaseClientBuilder.syncInstantiationWithBlob + BlobLeaseClient blobLeaseClient = new BlobLeaseClientBuilder() + .blobClient(blobClient) + .buildClient(); + // END: com.azure.storage.blob.specialized.LeaseClientBuilder.syncInstantiationWithBlob + } + + /** + * Code snippets for {@link BlobLeaseClientBuilder#buildClient()}. + */ + public void syncInstantiationWithBlobAndLeaseId() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClientBuilder.syncInstantiationWithBlobAndLeaseId + BlobLeaseClient blobLeaseClient = new BlobLeaseClientBuilder() + .blobClient(blobClient) + .leaseId(leaseId) + .buildClient(); + // END: com.azure.storage.blob.specialized.BlobLeaseClientBuilder.syncInstantiationWithBlobAndLeaseId + } + + /** + * Code snippets for {@link BlobLeaseClientBuilder#buildClient()}. + */ + public void syncInstantiationWithContainer() { + // BEGIN: com.azure.storage.blob.specialized.LeaseClientBuilder.syncInstantiationWithContainer + BlobLeaseClient blobLeaseClient = new BlobLeaseClientBuilder() + .containerClient(blobContainerClient) + .buildClient(); + // END: com.azure.storage.blob.specialized.LeaseClientBuilder.syncInstantiationWithContainer + } + + /** + * Code snippets for {@link BlobLeaseClientBuilder#buildClient()}. + */ + public void syncInstantiationWithContainerAndLeaseId() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClientBuilder.syncInstantiationWithContainerAndLeaseId + BlobLeaseClient blobLeaseClient = new BlobLeaseClientBuilder() + .containerClient(blobContainerClient) + .leaseId(leaseId) + .buildClient(); + // END: com.azure.storage.blob.specialized.BlobLeaseClientBuilder.syncInstantiationWithContainerAndLeaseId + } + + /** + * Code snippets for {@link BlobLeaseClientBuilder#buildAsyncClient()}. + */ + public void asyncInstantiationWithBlob() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClientBuilder.asyncInstantiationWithBlob + BlobLeaseAsyncClient blobLeaseAsyncClient = new BlobLeaseClientBuilder() + .blobAsyncClient(blobAsyncClient) + .buildAsyncClient(); + // END: com.azure.storage.blob.specialized.BlobLeaseClientBuilder.asyncInstantiationWithBlob + } + + /** + * Code snippets for {@link BlobLeaseClientBuilder#buildAsyncClient()}. + */ + public void asyncInstantiationWithBlobAndLeaseId() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClientBuilder.asyncInstantiationWithBlobAndLeaseId + BlobLeaseAsyncClient blobLeaseAsyncClient = new BlobLeaseClientBuilder() + .blobAsyncClient(blobAsyncClient) + .leaseId(leaseId) + .buildAsyncClient(); + // END: com.azure.storage.blob.specialized.BlobLeaseClientBuilder.asyncInstantiationWithBlobAndLeaseId + } + + /** + * Code snippets for {@link BlobLeaseClientBuilder#buildAsyncClient()}. + */ + public void asyncInstantiationWithContainer() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClientBuilder.asyncInstantiationWithContainer + BlobLeaseAsyncClient blobLeaseAsyncClient = new BlobLeaseClientBuilder() + .containerAsyncClient(blobContainerAsyncClient) + .buildAsyncClient(); + // END: com.azure.storage.blob.specialized.BlobLeaseClientBuilder.asyncInstantiationWithContainer + } + + /** + * Code snippets for {@link BlobLeaseClientBuilder#buildAsyncClient()}. + */ + public void asyncInstantiationWithContainerAndLeaseId() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClientBuilder.asyncInstantiationWithContainerAndLeaseId + BlobLeaseAsyncClient blobLeaseAsyncClient = new BlobLeaseClientBuilder() + .containerAsyncClient(blobContainerAsyncClient) + .leaseId(leaseId) + .buildAsyncClient(); + // END: com.azure.storage.blob.specialized.BlobLeaseClientBuilder.asyncInstantiationWithContainerAndLeaseId + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample37/v1/LeaseClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample37/v1/LeaseClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..ccc4de392177 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample37/v1/LeaseClientJavaDocCodeSnippets.java @@ -0,0 +1,230 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob.specialized; + +import com.azure.core.http.RequestConditions; +import com.azure.core.util.Context; +import com.azure.storage.blob.BlobClientBuilder; +import com.azure.storage.blob.models.BlobLeaseRequestConditions; +import com.azure.storage.blob.options.BlobAcquireLeaseOptions; +import com.azure.storage.blob.options.BlobBreakLeaseOptions; +import com.azure.storage.blob.options.BlobChangeLeaseOptions; +import com.azure.storage.blob.options.BlobReleaseLeaseOptions; +import com.azure.storage.blob.options.BlobRenewLeaseOptions; + +import java.time.Duration; +import java.time.OffsetDateTime; + +public class LeaseClientJavaDocCodeSnippets { + private BlobLeaseClient client = new BlobLeaseClientBuilder() + .blobClient(new BlobClientBuilder().blobName("blob").buildClient()) + .buildClient(); + private Duration timeout = Duration.ofSeconds(30); + private String key = "key"; + private String value = "value"; + + /** + * Code snippets for {@link BlobLeaseClient#acquireLease(int)} + */ + public void acquireLease() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.acquireLease#int + System.out.printf("Lease ID is %s%n", client.acquireLease(60)); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.acquireLease#int + } + + /** + * Code snippets for {@link BlobLeaseClient#renewLease()} + */ + public void renewLease() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.renewLease + System.out.printf("Renewed lease ID is %s%n", client.renewLease()); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.renewLease + } + + /** + * Code snippets for {@link BlobLeaseClient#releaseLease()} + */ + public void releaseLease() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.releaseLease + client.releaseLease(); + System.out.println("Release lease completed"); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.releaseLease + } + + /** + * Code snippets for {@link BlobLeaseClient#breakLease()} + */ + public void breakLease() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.breakLease + System.out.printf("The broken lease has %d seconds remaining on the lease", client.breakLease()); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.breakLease + } + + /** + * Code snippets for {@link BlobLeaseClient#changeLease(String)} + */ + public void changeLease() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.changeLease#String + System.out.printf("Changed lease ID is %s%n", client.changeLease("proposedId")); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.changeLease#String + } + + /** + * Code snippets for {@link BlobLeaseClient#acquireLeaseWithResponse(int, com.azure.core.http.RequestConditions, Duration, Context)} + */ + public void acquireLeaseWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.acquireLeaseWithResponse#int-RequestConditions-Duration-Context + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfModifiedSince(OffsetDateTime.now().minusDays(3)); + + System.out.printf("Lease ID is %s%n", client + .acquireLeaseWithResponse(60, modifiedRequestConditions, timeout, new Context(key, value)) + .getValue()); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.acquireLeaseWithResponse#int-RequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobLeaseClient#acquireLeaseWithResponse(BlobAcquireLeaseOptions, Duration, Context)} + */ + public void acquireLeaseWithResponseCodeSnippets2() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.acquireLeaseWithResponse#BlobAcquireLeaseOptions-Duration-Context + BlobLeaseRequestConditions requestConditions = new BlobLeaseRequestConditions() + .setIfModifiedSince(OffsetDateTime.now().minusDays(3)); + + BlobAcquireLeaseOptions options = new BlobAcquireLeaseOptions(60) + .setRequestConditions(requestConditions); + + System.out.printf("Lease ID is %s%n", client + .acquireLeaseWithResponse(options, timeout, new Context(key, value)) + .getValue()); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.acquireLeaseWithResponse#BlobAcquireLeaseOptions-Duration-Context + } + + /** + * Code snippets for {@link BlobLeaseClient#renewLeaseWithResponse(RequestConditions, Duration, Context)} + */ + public void renewLeaseWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.renewLeaseWithResponse#RequestConditions-Duration-Context + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + System.out.printf("Renewed lease ID is %s%n", + client.renewLeaseWithResponse(modifiedRequestConditions, timeout, new Context(key, value)) + .getValue()); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.renewLeaseWithResponse#RequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobLeaseClient#renewLeaseWithResponse(BlobRenewLeaseOptions, Duration, Context)} + */ + public void renewLeaseWithResponseCodeSnippets2() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.renewLeaseWithResponse#BlobRenewLeaseOptions-Duration-Context + BlobLeaseRequestConditions requestConditions = new BlobLeaseRequestConditions() + .setIfModifiedSince(OffsetDateTime.now().minusDays(3)); + + BlobRenewLeaseOptions options = new BlobRenewLeaseOptions() + .setRequestConditions(requestConditions); + + System.out.printf("Renewed lease ID is %s%n", + client.renewLeaseWithResponse(options, timeout, new Context(key, value)) + .getValue()); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.renewLeaseWithResponse#BlobRenewLeaseOptions-Duration-Context + } + + /** + * Code snippets for {@link BlobLeaseClient#releaseLeaseWithResponse(RequestConditions, Duration, Context)} + */ + public void releaseLeaseWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.releaseLeaseWithResponse#RequestConditions-Duration-Context + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + System.out.printf("Release lease completed with status %d%n", + client.releaseLeaseWithResponse(modifiedRequestConditions, timeout, new Context(key, value)) + .getStatusCode()); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.releaseLeaseWithResponse#RequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobLeaseClient#releaseLeaseWithResponse(BlobReleaseLeaseOptions, Duration, Context)} + */ + public void releaseLeaseWithResponseCodeSnippets2() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.releaseLeaseWithResponse#BlobReleaseLeaseOptions-Duration-Context + BlobLeaseRequestConditions requestConditions = new BlobLeaseRequestConditions() + .setIfModifiedSince(OffsetDateTime.now().minusDays(3)); + + BlobReleaseLeaseOptions options = new BlobReleaseLeaseOptions() + .setRequestConditions(requestConditions); + + System.out.printf("Release lease completed with status %d%n", + client.releaseLeaseWithResponse(options, timeout, new Context(key, value)) + .getStatusCode()); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.releaseLeaseWithResponse#BlobReleaseLeaseOptions-Duration-Context + } + + /** + * Code snippets for {@link BlobLeaseClient#breakLeaseWithResponse(Integer, RequestConditions, Duration, Context)} + */ + public void breakLeaseWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.breakLeaseWithResponse#Integer-RequestConditions-Duration-Context + Integer retainLeaseInSeconds = 5; + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + System.out.printf("The broken lease has %d seconds remaining on the lease", client + .breakLeaseWithResponse(retainLeaseInSeconds, modifiedRequestConditions, timeout, new Context(key, value)) + .getValue()); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.breakLeaseWithResponse#Integer-RequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobLeaseClient#breakLeaseWithResponse(BlobBreakLeaseOptions, Duration, Context)} + */ + public void breakLeaseWithResponseCodeSnippets2() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.breakLeaseWithResponse#BlobBreakLeaseOptions-Duration-Context + Integer retainLeaseInSeconds = 5; + BlobLeaseRequestConditions requestConditions = new BlobLeaseRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + BlobBreakLeaseOptions options = new BlobBreakLeaseOptions() + .setBreakPeriod(Duration.ofSeconds(retainLeaseInSeconds)) + .setRequestConditions(requestConditions); + + System.out.printf("The broken lease has %d seconds remaining on the lease", client + .breakLeaseWithResponse(options, timeout, new Context(key, value)) + .getValue()); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.breakLeaseWithResponse#BlobBreakLeaseOptions-Duration-Context + } + + /** + * Code snippets for {@link BlobLeaseClient#changeLeaseWithResponse(String, RequestConditions, Duration, Context)} + */ + public void changeLeaseWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.changeLeaseWithResponse#String-RequestConditions-Duration-Context + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + System.out.printf("Changed lease ID is %s%n", + client.changeLeaseWithResponse("proposedId", modifiedRequestConditions, timeout, new Context(key, value)) + .getValue()); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.changeLeaseWithResponse#String-RequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobLeaseClient#changeLeaseWithResponse(BlobChangeLeaseOptions, Duration, Context)} + */ + public void changeLeaseWithResponseCodeSnippets2() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.changeLeaseWithResponse#BlobChangeLeaseOptions-Duration-Context + BlobLeaseRequestConditions requestConditions = new BlobLeaseRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + BlobChangeLeaseOptions options = new BlobChangeLeaseOptions("proposedId") + .setRequestConditions(requestConditions); + + System.out.printf("Changed lease ID is %s%n", + client.changeLeaseWithResponse(options, timeout, new Context(key, value)) + .getValue()); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.changeLeaseWithResponse#BlobChangeLeaseOptions-Duration-Context + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample37/v2/LeaseClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample37/v2/LeaseClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..ccc4de392177 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample37/v2/LeaseClientJavaDocCodeSnippets.java @@ -0,0 +1,230 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob.specialized; + +import com.azure.core.http.RequestConditions; +import com.azure.core.util.Context; +import com.azure.storage.blob.BlobClientBuilder; +import com.azure.storage.blob.models.BlobLeaseRequestConditions; +import com.azure.storage.blob.options.BlobAcquireLeaseOptions; +import com.azure.storage.blob.options.BlobBreakLeaseOptions; +import com.azure.storage.blob.options.BlobChangeLeaseOptions; +import com.azure.storage.blob.options.BlobReleaseLeaseOptions; +import com.azure.storage.blob.options.BlobRenewLeaseOptions; + +import java.time.Duration; +import java.time.OffsetDateTime; + +public class LeaseClientJavaDocCodeSnippets { + private BlobLeaseClient client = new BlobLeaseClientBuilder() + .blobClient(new BlobClientBuilder().blobName("blob").buildClient()) + .buildClient(); + private Duration timeout = Duration.ofSeconds(30); + private String key = "key"; + private String value = "value"; + + /** + * Code snippets for {@link BlobLeaseClient#acquireLease(int)} + */ + public void acquireLease() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.acquireLease#int + System.out.printf("Lease ID is %s%n", client.acquireLease(60)); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.acquireLease#int + } + + /** + * Code snippets for {@link BlobLeaseClient#renewLease()} + */ + public void renewLease() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.renewLease + System.out.printf("Renewed lease ID is %s%n", client.renewLease()); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.renewLease + } + + /** + * Code snippets for {@link BlobLeaseClient#releaseLease()} + */ + public void releaseLease() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.releaseLease + client.releaseLease(); + System.out.println("Release lease completed"); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.releaseLease + } + + /** + * Code snippets for {@link BlobLeaseClient#breakLease()} + */ + public void breakLease() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.breakLease + System.out.printf("The broken lease has %d seconds remaining on the lease", client.breakLease()); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.breakLease + } + + /** + * Code snippets for {@link BlobLeaseClient#changeLease(String)} + */ + public void changeLease() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.changeLease#String + System.out.printf("Changed lease ID is %s%n", client.changeLease("proposedId")); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.changeLease#String + } + + /** + * Code snippets for {@link BlobLeaseClient#acquireLeaseWithResponse(int, com.azure.core.http.RequestConditions, Duration, Context)} + */ + public void acquireLeaseWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.acquireLeaseWithResponse#int-RequestConditions-Duration-Context + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfModifiedSince(OffsetDateTime.now().minusDays(3)); + + System.out.printf("Lease ID is %s%n", client + .acquireLeaseWithResponse(60, modifiedRequestConditions, timeout, new Context(key, value)) + .getValue()); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.acquireLeaseWithResponse#int-RequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobLeaseClient#acquireLeaseWithResponse(BlobAcquireLeaseOptions, Duration, Context)} + */ + public void acquireLeaseWithResponseCodeSnippets2() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.acquireLeaseWithResponse#BlobAcquireLeaseOptions-Duration-Context + BlobLeaseRequestConditions requestConditions = new BlobLeaseRequestConditions() + .setIfModifiedSince(OffsetDateTime.now().minusDays(3)); + + BlobAcquireLeaseOptions options = new BlobAcquireLeaseOptions(60) + .setRequestConditions(requestConditions); + + System.out.printf("Lease ID is %s%n", client + .acquireLeaseWithResponse(options, timeout, new Context(key, value)) + .getValue()); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.acquireLeaseWithResponse#BlobAcquireLeaseOptions-Duration-Context + } + + /** + * Code snippets for {@link BlobLeaseClient#renewLeaseWithResponse(RequestConditions, Duration, Context)} + */ + public void renewLeaseWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.renewLeaseWithResponse#RequestConditions-Duration-Context + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + System.out.printf("Renewed lease ID is %s%n", + client.renewLeaseWithResponse(modifiedRequestConditions, timeout, new Context(key, value)) + .getValue()); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.renewLeaseWithResponse#RequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobLeaseClient#renewLeaseWithResponse(BlobRenewLeaseOptions, Duration, Context)} + */ + public void renewLeaseWithResponseCodeSnippets2() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.renewLeaseWithResponse#BlobRenewLeaseOptions-Duration-Context + BlobLeaseRequestConditions requestConditions = new BlobLeaseRequestConditions() + .setIfModifiedSince(OffsetDateTime.now().minusDays(3)); + + BlobRenewLeaseOptions options = new BlobRenewLeaseOptions() + .setRequestConditions(requestConditions); + + System.out.printf("Renewed lease ID is %s%n", + client.renewLeaseWithResponse(options, timeout, new Context(key, value)) + .getValue()); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.renewLeaseWithResponse#BlobRenewLeaseOptions-Duration-Context + } + + /** + * Code snippets for {@link BlobLeaseClient#releaseLeaseWithResponse(RequestConditions, Duration, Context)} + */ + public void releaseLeaseWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.releaseLeaseWithResponse#RequestConditions-Duration-Context + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + System.out.printf("Release lease completed with status %d%n", + client.releaseLeaseWithResponse(modifiedRequestConditions, timeout, new Context(key, value)) + .getStatusCode()); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.releaseLeaseWithResponse#RequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobLeaseClient#releaseLeaseWithResponse(BlobReleaseLeaseOptions, Duration, Context)} + */ + public void releaseLeaseWithResponseCodeSnippets2() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.releaseLeaseWithResponse#BlobReleaseLeaseOptions-Duration-Context + BlobLeaseRequestConditions requestConditions = new BlobLeaseRequestConditions() + .setIfModifiedSince(OffsetDateTime.now().minusDays(3)); + + BlobReleaseLeaseOptions options = new BlobReleaseLeaseOptions() + .setRequestConditions(requestConditions); + + System.out.printf("Release lease completed with status %d%n", + client.releaseLeaseWithResponse(options, timeout, new Context(key, value)) + .getStatusCode()); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.releaseLeaseWithResponse#BlobReleaseLeaseOptions-Duration-Context + } + + /** + * Code snippets for {@link BlobLeaseClient#breakLeaseWithResponse(Integer, RequestConditions, Duration, Context)} + */ + public void breakLeaseWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.breakLeaseWithResponse#Integer-RequestConditions-Duration-Context + Integer retainLeaseInSeconds = 5; + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + System.out.printf("The broken lease has %d seconds remaining on the lease", client + .breakLeaseWithResponse(retainLeaseInSeconds, modifiedRequestConditions, timeout, new Context(key, value)) + .getValue()); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.breakLeaseWithResponse#Integer-RequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobLeaseClient#breakLeaseWithResponse(BlobBreakLeaseOptions, Duration, Context)} + */ + public void breakLeaseWithResponseCodeSnippets2() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.breakLeaseWithResponse#BlobBreakLeaseOptions-Duration-Context + Integer retainLeaseInSeconds = 5; + BlobLeaseRequestConditions requestConditions = new BlobLeaseRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + BlobBreakLeaseOptions options = new BlobBreakLeaseOptions() + .setBreakPeriod(Duration.ofSeconds(retainLeaseInSeconds)) + .setRequestConditions(requestConditions); + + System.out.printf("The broken lease has %d seconds remaining on the lease", client + .breakLeaseWithResponse(options, timeout, new Context(key, value)) + .getValue()); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.breakLeaseWithResponse#BlobBreakLeaseOptions-Duration-Context + } + + /** + * Code snippets for {@link BlobLeaseClient#changeLeaseWithResponse(String, RequestConditions, Duration, Context)} + */ + public void changeLeaseWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.changeLeaseWithResponse#String-RequestConditions-Duration-Context + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + System.out.printf("Changed lease ID is %s%n", + client.changeLeaseWithResponse("proposedId", modifiedRequestConditions, timeout, new Context(key, value)) + .getValue()); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.changeLeaseWithResponse#String-RequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobLeaseClient#changeLeaseWithResponse(BlobChangeLeaseOptions, Duration, Context)} + */ + public void changeLeaseWithResponseCodeSnippets2() { + // BEGIN: com.azure.storage.blob.specialized.BlobLeaseClient.changeLeaseWithResponse#BlobChangeLeaseOptions-Duration-Context + BlobLeaseRequestConditions requestConditions = new BlobLeaseRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + BlobChangeLeaseOptions options = new BlobChangeLeaseOptions("proposedId") + .setRequestConditions(requestConditions); + + System.out.printf("Changed lease ID is %s%n", + client.changeLeaseWithResponse(options, timeout, new Context(key, value)) + .getValue()); + // END: com.azure.storage.blob.specialized.BlobLeaseClient.changeLeaseWithResponse#BlobChangeLeaseOptions-Duration-Context + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample38/v1/PageBlobAsyncClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample38/v1/PageBlobAsyncClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..ab7b031ef711 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample38/v1/PageBlobAsyncClientJavaDocCodeSnippets.java @@ -0,0 +1,558 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob.specialized; + +import com.azure.core.http.RequestConditions; +import com.azure.storage.blob.models.PageBlobCopyIncrementalRequestConditions; +import com.azure.storage.blob.models.BlobHttpHeaders; +import com.azure.storage.blob.models.BlobRange; +import com.azure.storage.blob.models.BlobRequestConditions; +import com.azure.storage.blob.models.CopyStatusType; +import com.azure.storage.blob.options.ListPageRangesDiffOptions; +import com.azure.storage.blob.options.ListPageRangesOptions; +import com.azure.storage.blob.options.PageBlobCopyIncrementalOptions; +import com.azure.storage.blob.options.PageBlobCreateOptions; +import com.azure.storage.blob.models.PageBlobRequestConditions; +import com.azure.storage.blob.models.PageRange; +import com.azure.storage.blob.models.SequenceNumberActionType; +import com.azure.storage.blob.options.PageBlobUploadPagesFromUrlOptions; +import reactor.core.publisher.Flux; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.OffsetDateTime; +import java.util.Collections; +import java.util.Map; + +/** + * Code snippets for {@link PageBlobAsyncClient} + */ +@SuppressWarnings("unused") +public class PageBlobAsyncClientJavaDocCodeSnippets { + private PageBlobAsyncClient client = new SpecializedBlobClientBuilder().buildPageBlobAsyncClient(); + private Map metadata = Collections.singletonMap("metadata", "value"); + private Map tags = Collections.singletonMap("tag", "value"); + private ByteBuffer[] bufferData = new ByteBuffer[]{ + ByteBuffer.wrap(new byte[]{1}), + ByteBuffer.wrap(new byte[]{2}) + }; + private Flux body = Flux.fromArray(bufferData); + private long size = 1024; + private String leaseId = "leaseId"; + private long sequenceNumber = 0; + private String url = "https://sample.com"; + private long sourceOffset = 0; + private String data = "data"; + private long offset = 0; + + /** + * Code snippets for {@link PageBlobAsyncClient#create(long)} + */ + public void setCreateCodeSnippet() { + // BEGIN: com.azure.storage.blob.PageBlobAsyncClient.create#long + client.create(size).subscribe(response -> System.out.printf( + "Created page blob with sequence number %s%n", response.getBlobSequenceNumber())); + // END: com.azure.storage.blob.PageBlobAsyncClient.create#long + } + + /** + * Code snippets for {@link PageBlobAsyncClient#create(long, boolean)} + */ + public void createWithOverwrite() { + // BEGIN: com.azure.storage.blob.PageBlobAsyncClient.create#long-boolean + boolean overwrite = false; // Default behavior + client.create(size, overwrite).subscribe(response -> System.out.printf( + "Created page blob with sequence number %s%n", response.getBlobSequenceNumber())); + // END: com.azure.storage.blob.PageBlobAsyncClient.create#long-boolean + } + + /** + * Code snippets for {@link PageBlobAsyncClient#createWithResponse(long, Long, BlobHttpHeaders, Map, BlobRequestConditions)} + */ + public void createWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.createWithResponse#long-Long-BlobHttpHeaders-Map-BlobRequestConditions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentLanguage("en-US") + .setContentType("binary"); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.createWithResponse(size, sequenceNumber, headers, metadata, blobRequestConditions) + .subscribe(response -> System.out.printf( + "Created page blob with sequence number %s%n", response.getValue().getBlobSequenceNumber())); + + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.createWithResponse#long-Long-BlobHttpHeaders-Map-BlobRequestConditions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#createWithResponse(PageBlobCreateOptions)} + */ + public void createWithResponse2CodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.createWithResponse#PageBlobCreateOptions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentLanguage("en-US") + .setContentType("binary"); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.createWithResponse(new PageBlobCreateOptions(size).setSequenceNumber(sequenceNumber) + .setHeaders(headers).setMetadata(metadata).setTags(tags).setRequestConditions(blobRequestConditions)) + .subscribe(response -> System.out.printf( + "Created page blob with sequence number %s%n", response.getValue().getBlobSequenceNumber())); + + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.createWithResponse#PageBlobCreateOptions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#uploadPages(PageRange, Flux)} + */ + public void uploadPagesCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.uploadPages#PageRange-Flux + PageRange pageRange = new PageRange() + .setStart(0) + .setEnd(511); + + client.uploadPages(pageRange, body).subscribe(response -> System.out.printf( + "Uploaded page blob with sequence number %s%n", response.getBlobSequenceNumber())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.uploadPages#PageRange-Flux + } + + /** + * Code snippets for {@link PageBlobAsyncClient#uploadPagesWithResponse(PageRange, Flux, byte[], PageBlobRequestConditions)} + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public void uploadPagesWithResponseCodeSnippet() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.uploadPagesWithResponse#PageRange-Flux-byte-PageBlobRequestConditions + PageRange pageRange = new PageRange() + .setStart(0) + .setEnd(511); + + byte[] md5 = MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8)); + PageBlobRequestConditions pageBlobRequestConditions = new PageBlobRequestConditions().setLeaseId(leaseId); + + client.uploadPagesWithResponse(pageRange, body, md5, pageBlobRequestConditions) + .subscribe(response -> System.out.printf( + "Uploaded page blob with sequence number %s%n", response.getValue().getBlobSequenceNumber())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.uploadPagesWithResponse#PageRange-Flux-byte-PageBlobRequestConditions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#uploadPagesFromUrl(PageRange, String, Long)} + */ + public void uploadPagesFromUrl() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.uploadPagesFromUrl#PageRange-String-Long + PageRange pageRange = new PageRange() + .setStart(0) + .setEnd(511); + + client.uploadPagesFromUrl(pageRange, url, sourceOffset) + .subscribe(response -> System.out.printf( + "Uploaded page blob from URL with sequence number %s%n", response.getBlobSequenceNumber())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.uploadPagesFromUrl#PageRange-String-Long + } + + /** + * Code snippets for {@link PageBlobAsyncClient#uploadPagesFromUrlWithResponse(PageRange, String, Long, byte[], + * PageBlobRequestConditions, BlobRequestConditions)} + */ + public void uploadPagesFromUrlWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.uploadPagesFromUrlWithResponse#PageRange-String-Long-byte-PageBlobRequestConditions-BlobRequestConditions + PageRange pageRange = new PageRange() + .setStart(0) + .setEnd(511); + InputStream dataStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); + byte[] sourceContentMD5 = new byte[512]; + PageBlobRequestConditions pageBlobRequestConditions = new PageBlobRequestConditions().setLeaseId(leaseId); + BlobRequestConditions sourceRequestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.uploadPagesFromUrlWithResponse(pageRange, url, sourceOffset, sourceContentMD5, pageBlobRequestConditions, + sourceRequestConditions) + .subscribe(response -> System.out.printf( + "Uploaded page blob from URL with sequence number %s%n", response.getValue().getBlobSequenceNumber())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.uploadPagesFromUrlWithResponse#PageRange-String-Long-byte-PageBlobRequestConditions-BlobRequestConditions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#uploadPagesFromUrlWithResponse(PageBlobUploadPagesFromUrlOptions)} + */ + public void uploadPagesFromUrlWithResponseOptionsBagCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.uploadPagesFromUrlWithResponse#PageBlobUploadPagesFromUrlOptions + PageRange pageRange = new PageRange() + .setStart(0) + .setEnd(511); + InputStream dataStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); + byte[] sourceContentMD5 = new byte[512]; + PageBlobRequestConditions pageBlobRequestConditions = new PageBlobRequestConditions().setLeaseId(leaseId); + BlobRequestConditions sourceRequestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.uploadPagesFromUrlWithResponse(new PageBlobUploadPagesFromUrlOptions(pageRange, url) + .setSourceOffset(sourceOffset).setSourceContentMd5(sourceContentMD5) + .setDestinationRequestConditions(pageBlobRequestConditions) + .setSourceRequestConditions(sourceRequestConditions)) + .subscribe(response -> System.out.printf( + "Uploaded page blob from URL with sequence number %s%n", response.getValue().getBlobSequenceNumber())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.uploadPagesFromUrlWithResponse#PageBlobUploadPagesFromUrlOptions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#clearPages(PageRange)} + */ + public void clearPagesCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.clearPages#PageRange + PageRange pageRange = new PageRange() + .setStart(0) + .setEnd(511); + + client.clearPages(pageRange).subscribe(response -> System.out.printf( + "Cleared page blob with sequence number %s%n", response.getBlobSequenceNumber())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.clearPages#PageRange + } + + /** + * Code snippets for {@link PageBlobAsyncClient#clearPagesWithResponse(PageRange, PageBlobRequestConditions)} + */ + public void clearPagesWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.clearPagesWithResponse#PageRange-PageBlobRequestConditions + PageRange pageRange = new PageRange() + .setStart(0) + .setEnd(511); + PageBlobRequestConditions pageBlobRequestConditions = new PageBlobRequestConditions().setLeaseId(leaseId); + + client.clearPagesWithResponse(pageRange, pageBlobRequestConditions) + .subscribe(response -> System.out.printf( + "Cleared page blob with sequence number %s%n", response.getValue().getBlobSequenceNumber())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.clearPagesWithResponse#PageRange-PageBlobRequestConditions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#getPageRanges(BlobRange)} + */ + public void getPageRangesCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.getPageRanges#BlobRange + BlobRange blobRange = new BlobRange(offset); + + client.getPageRanges(blobRange).subscribe(response -> { + System.out.println("Valid Page Ranges are:"); + for (PageRange pageRange : response.getPageRange()) { + System.out.printf("Start: %s, End: %s%n", pageRange.getStart(), pageRange.getEnd()); + } + }); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.getPageRanges#BlobRange + } + + /** + * Code snippets for {@link PageBlobAsyncClient#getPageRangesWithResponse(BlobRange, BlobRequestConditions)} + */ + public void getPageRangesWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.getPageRangesWithResponse#BlobRange-BlobRequestConditions + BlobRange blobRange = new BlobRange(offset); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.getPageRangesWithResponse(blobRange, blobRequestConditions) + .subscribe(response -> { + System.out.println("Valid Page Ranges are:"); + for (PageRange pageRange : response.getValue().getPageRange()) { + System.out.printf("Start: %s, End: %s%n", pageRange.getStart(), pageRange.getEnd()); + } + }); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.getPageRangesWithResponse#BlobRange-BlobRequestConditions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#listPageRanges(BlobRange)} and + * {@link PageBlobAsyncClient#listPageRanges(ListPageRangesOptions)} + */ + public void listPageRangesCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.listPageRanges#BlobRange + BlobRange blobRange = new BlobRange(offset); + + System.out.println("Valid Page Ranges are:"); + client.listPageRanges(blobRange).subscribe(rangeItem -> System.out.printf("Offset: %s, Length: %s%n", + rangeItem.getRange().getOffset(), rangeItem.getRange().getLength())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.listPageRanges#BlobRange + + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.listPageRanges#ListPageRangesOptions + ListPageRangesOptions options = new ListPageRangesOptions(new BlobRange(offset)) + .setMaxResultsPerPage(1000).setRequestConditions(new BlobRequestConditions().setLeaseId(leaseId)); + + client.listPageRanges(options) + .subscribe(rangeItem -> System.out.printf("Offset: %s, Length: %s%n", rangeItem.getRange().getOffset(), + rangeItem.getRange().getLength())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.listPageRanges#ListPageRangesOptions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#getPageRangesDiff(BlobRange, String)} + */ + public void getPageRangesDiffCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.getPageRangesDiff#BlobRange-String + BlobRange blobRange = new BlobRange(offset); + final String prevSnapshot = "previous snapshot"; + + client.getPageRangesDiff(blobRange, prevSnapshot).subscribe(response -> { + System.out.println("Valid Page Ranges are:"); + for (PageRange pageRange : response.getPageRange()) { + System.out.printf("Start: %s, End: %s%n", pageRange.getStart(), pageRange.getEnd()); + } + }); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.getPageRangesDiff#BlobRange-String + } + + /** + * Code snippets for {@link PageBlobAsyncClient#getPageRangesDiffWithResponse(BlobRange, String, + * BlobRequestConditions)} + */ + public void getPageRangesDiffWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.getPageRangesDiffWithResponse#BlobRange-String-BlobRequestConditions + BlobRange blobRange = new BlobRange(offset); + final String prevSnapshot = "previous snapshot"; + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.getPageRangesDiffWithResponse(blobRange, prevSnapshot, blobRequestConditions) + .subscribe(response -> { + System.out.println("Valid Page Ranges are:"); + for (PageRange pageRange : response.getValue().getPageRange()) { + System.out.printf("Start: %s, End: %s%n", pageRange.getStart(), pageRange.getEnd()); + } + }); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.getPageRangesDiffWithResponse#BlobRange-String-BlobRequestConditions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#listPageRangesDiff(BlobRange, String)} and + * {@link PageBlobAsyncClient#listPageRangesDiff(ListPageRangesDiffOptions)} + */ + public void listPageRangesDiffCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.listPageRangesDiff#BlobRange-String + BlobRange blobRange = new BlobRange(offset); + String prevSnapshot = "previous snapshot"; + + System.out.println("Valid Page Ranges are:"); + client.listPageRangesDiff(blobRange, prevSnapshot).subscribe(rangeItem -> + System.out.printf("Offset: %s, Length: %s, isClear: %s%n", + rangeItem.getRange().getOffset(), rangeItem.getRange().getLength(), rangeItem.isClear())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.listPageRangesDiff#BlobRange-String + + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.listPageRangesDiff#ListPageRangesDiffOptions + ListPageRangesDiffOptions options = new ListPageRangesDiffOptions(new BlobRange(offset), "previous snapshot") + .setRequestConditions(new BlobRequestConditions().setLeaseId(leaseId)) + .setMaxResultsPerPage(1000); + + client.listPageRangesDiff(options) + .subscribe(rangeItem -> System.out.printf("Offset: %s, Length: %s, isClear: %s%n", + rangeItem.getRange().getOffset(), rangeItem.getRange().getLength(), rangeItem.isClear())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.listPageRangesDiff#ListPageRangesDiffOptions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#getManagedDiskPageRangesDiff(BlobRange, String)} + */ + public void getPageRangesDiffFromUrlCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.getManagedDiskPageRangesDiff#BlobRange-String + BlobRange blobRange = new BlobRange(offset); + final String prevSnapshotUrl = "previous snapshot url"; + + client.getPageRangesDiff(blobRange, prevSnapshotUrl).subscribe(response -> { + System.out.println("Valid Page Ranges are:"); + for (PageRange pageRange : response.getPageRange()) { + System.out.printf("Start: %s, End: %s%n", pageRange.getStart(), pageRange.getEnd()); + } + }); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.getManagedDiskPageRangesDiff#BlobRange-String + } + + /** + * Code snippets for {@link PageBlobAsyncClient#getManagedDiskPageRangesDiffWithResponse(BlobRange, String, + * BlobRequestConditions)} + */ + public void getPageRangesDiffFromUrlWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.getManagedDiskPageRangesDiffWithResponse#BlobRange-String-BlobRequestConditions + BlobRange blobRange = new BlobRange(offset); + final String prevSnapshotUrl = "previous snapshot url"; + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.getPageRangesDiffWithResponse(blobRange, prevSnapshotUrl, blobRequestConditions) + .subscribe(response -> { + System.out.println("Valid Page Ranges are:"); + for (PageRange pageRange : response.getValue().getPageRange()) { + System.out.printf("Start: %s, End: %s%n", pageRange.getStart(), pageRange.getEnd()); + } + }); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.getManagedDiskPageRangesDiffWithResponse#BlobRange-String-BlobRequestConditions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#resize(long)} + */ + public void resizeCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.resize#long + client.resize(size).subscribe(response -> System.out.printf( + "Page blob resized with sequence number %s%n", response.getBlobSequenceNumber())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.resize#long + } + + /** + * Code snippets for {@link PageBlobAsyncClient#resizeWithResponse(long, BlobRequestConditions)} + */ + public void resizeWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.resizeWithResponse#long-BlobRequestConditions + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.resizeWithResponse(size, blobRequestConditions) + .subscribe(response -> System.out.printf( + "Page blob resized with sequence number %s%n", response.getValue().getBlobSequenceNumber())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.resizeWithResponse#long-BlobRequestConditions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#updateSequenceNumber(SequenceNumberActionType, Long)} + */ + public void updateSequenceNumberCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.updateSequenceNumber#SequenceNumberActionType-Long + client.updateSequenceNumber(SequenceNumberActionType.INCREMENT, size) + .subscribe(response -> System.out.printf( + "Page blob updated to sequence number %s%n", response.getBlobSequenceNumber())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.updateSequenceNumber#SequenceNumberActionType-Long + } + + /** + * Code snippets for {@link PageBlobAsyncClient#updateSequenceNumberWithResponse(SequenceNumberActionType, Long, + * BlobRequestConditions)} + */ + public void updateSequenceNumberWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.updateSequenceNumberWithResponse#SequenceNumberActionType-Long-BlobRequestConditions + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.updateSequenceNumberWithResponse(SequenceNumberActionType.INCREMENT, size, blobRequestConditions) + .subscribe(response -> System.out.printf( + "Page blob updated to sequence number %s%n", response.getValue().getBlobSequenceNumber())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.updateSequenceNumberWithResponse#SequenceNumberActionType-Long-BlobRequestConditions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#copyIncremental(String, String)} + */ + public void copyIncrementalCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.copyIncremental#String-String + final String snapshot = "copy snapshot"; + client.copyIncremental(url, snapshot).subscribe(statusType -> { + switch (statusType) { + case SUCCESS: + System.out.println("Page blob copied successfully"); + break; + case FAILED: + System.out.println("Page blob copied failed"); + break; + case ABORTED: + System.out.println("Page blob copied aborted"); + break; + case PENDING: + System.out.println("Page blob copied pending"); + break; + default: + break; + } + }); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.copyIncremental#String-String + } + + /** + * Code snippets for {@link PageBlobAsyncClient#copyIncrementalWithResponse(String, String, RequestConditions)} + */ + public void copyIncrementalWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.copyIncrementalWithResponse#String-String-RequestConditions + final String snapshot = "copy snapshot"; + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfNoneMatch("snapshotMatch"); + + client.copyIncrementalWithResponse(url, snapshot, modifiedRequestConditions) + .subscribe(response -> { + CopyStatusType statusType = response.getValue(); + + switch (statusType) { + case SUCCESS: + System.out.println("Page blob copied successfully"); + break; + case FAILED: + System.out.println("Page blob copied failed"); + break; + case ABORTED: + System.out.println("Page blob copied aborted"); + break; + case PENDING: + System.out.println("Page blob copied pending"); + break; + default: + break; + } + }); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.copyIncrementalWithResponse#String-String-RequestConditions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#copyIncrementalWithResponse(PageBlobCopyIncrementalOptions)} + */ + public void copyIncrementalWithResponseCodeSnippet2() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.copyIncrementalWithResponse#PageBlobCopyIncrementalOptions + final String snapshot = "copy snapshot"; + PageBlobCopyIncrementalRequestConditions destinationRequestConditions = new PageBlobCopyIncrementalRequestConditions() + .setIfNoneMatch("snapshotMatch"); + + client.copyIncrementalWithResponse(new PageBlobCopyIncrementalOptions(url, snapshot) + .setRequestConditions(destinationRequestConditions)) + .subscribe(response -> { + CopyStatusType statusType = response.getValue(); + + switch (statusType) { + case SUCCESS: + System.out.println("Page blob copied successfully"); + break; + case FAILED: + System.out.println("Page blob copied failed"); + break; + case ABORTED: + System.out.println("Page blob copied aborted"); + break; + case PENDING: + System.out.println("Page blob copied pending"); + break; + default: + break; + } + }); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.copyIncrementalWithResponse#PageBlobCopyIncrementalOptions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#createIfNotExists(long)} and + * {@link PageBlobAsyncClient#createIfNotExistsWithResponse(PageBlobCreateOptions)} + */ + public void createIfNotExistsCodeSnippet() { + // BEGIN: com.azure.storage.blob.PageBlobAsyncClient.createIfNotExists#long + client.createIfNotExists(size).subscribe(response -> + System.out.printf("Created page blob with sequence number %s%n", response.getBlobSequenceNumber())); + // END: com.azure.storage.blob.PageBlobAsyncClient.createIfNotExists#long + + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.createIfNotExistsWithResponse#PageBlobCreateOptions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentLanguage("en-US") + .setContentType("binary"); + + client.createIfNotExistsWithResponse(new PageBlobCreateOptions(size).setSequenceNumber(sequenceNumber) + .setHeaders(headers).setMetadata(metadata).setTags(tags)).subscribe(response -> { + if (response.getStatusCode() == 409) { + System.out.println("Already exists."); + } else { + System.out.println("successfully created."); + } + }); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.createIfNotExistsWithResponse#PageBlobCreateOptions + } + +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample38/v2/PageBlobAsyncClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample38/v2/PageBlobAsyncClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..ab7b031ef711 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample38/v2/PageBlobAsyncClientJavaDocCodeSnippets.java @@ -0,0 +1,558 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob.specialized; + +import com.azure.core.http.RequestConditions; +import com.azure.storage.blob.models.PageBlobCopyIncrementalRequestConditions; +import com.azure.storage.blob.models.BlobHttpHeaders; +import com.azure.storage.blob.models.BlobRange; +import com.azure.storage.blob.models.BlobRequestConditions; +import com.azure.storage.blob.models.CopyStatusType; +import com.azure.storage.blob.options.ListPageRangesDiffOptions; +import com.azure.storage.blob.options.ListPageRangesOptions; +import com.azure.storage.blob.options.PageBlobCopyIncrementalOptions; +import com.azure.storage.blob.options.PageBlobCreateOptions; +import com.azure.storage.blob.models.PageBlobRequestConditions; +import com.azure.storage.blob.models.PageRange; +import com.azure.storage.blob.models.SequenceNumberActionType; +import com.azure.storage.blob.options.PageBlobUploadPagesFromUrlOptions; +import reactor.core.publisher.Flux; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.OffsetDateTime; +import java.util.Collections; +import java.util.Map; + +/** + * Code snippets for {@link PageBlobAsyncClient} + */ +@SuppressWarnings("unused") +public class PageBlobAsyncClientJavaDocCodeSnippets { + private PageBlobAsyncClient client = new SpecializedBlobClientBuilder().buildPageBlobAsyncClient(); + private Map metadata = Collections.singletonMap("metadata", "value"); + private Map tags = Collections.singletonMap("tag", "value"); + private ByteBuffer[] bufferData = new ByteBuffer[]{ + ByteBuffer.wrap(new byte[]{1}), + ByteBuffer.wrap(new byte[]{2}) + }; + private Flux body = Flux.fromArray(bufferData); + private long size = 1024; + private String leaseId = "leaseId"; + private long sequenceNumber = 0; + private String url = "https://sample.com"; + private long sourceOffset = 0; + private String data = "data"; + private long offset = 0; + + /** + * Code snippets for {@link PageBlobAsyncClient#create(long)} + */ + public void setCreateCodeSnippet() { + // BEGIN: com.azure.storage.blob.PageBlobAsyncClient.create#long + client.create(size).subscribe(response -> System.out.printf( + "Created page blob with sequence number %s%n", response.getBlobSequenceNumber())); + // END: com.azure.storage.blob.PageBlobAsyncClient.create#long + } + + /** + * Code snippets for {@link PageBlobAsyncClient#create(long, boolean)} + */ + public void createWithOverwrite() { + // BEGIN: com.azure.storage.blob.PageBlobAsyncClient.create#long-boolean + boolean overwrite = false; // Default behavior + client.create(size, overwrite).subscribe(response -> System.out.printf( + "Created page blob with sequence number %s%n", response.getBlobSequenceNumber())); + // END: com.azure.storage.blob.PageBlobAsyncClient.create#long-boolean + } + + /** + * Code snippets for {@link PageBlobAsyncClient#createWithResponse(long, Long, BlobHttpHeaders, Map, BlobRequestConditions)} + */ + public void createWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.createWithResponse#long-Long-BlobHttpHeaders-Map-BlobRequestConditions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentLanguage("en-US") + .setContentType("binary"); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.createWithResponse(size, sequenceNumber, headers, metadata, blobRequestConditions) + .subscribe(response -> System.out.printf( + "Created page blob with sequence number %s%n", response.getValue().getBlobSequenceNumber())); + + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.createWithResponse#long-Long-BlobHttpHeaders-Map-BlobRequestConditions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#createWithResponse(PageBlobCreateOptions)} + */ + public void createWithResponse2CodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.createWithResponse#PageBlobCreateOptions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentLanguage("en-US") + .setContentType("binary"); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.createWithResponse(new PageBlobCreateOptions(size).setSequenceNumber(sequenceNumber) + .setHeaders(headers).setMetadata(metadata).setTags(tags).setRequestConditions(blobRequestConditions)) + .subscribe(response -> System.out.printf( + "Created page blob with sequence number %s%n", response.getValue().getBlobSequenceNumber())); + + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.createWithResponse#PageBlobCreateOptions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#uploadPages(PageRange, Flux)} + */ + public void uploadPagesCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.uploadPages#PageRange-Flux + PageRange pageRange = new PageRange() + .setStart(0) + .setEnd(511); + + client.uploadPages(pageRange, body).subscribe(response -> System.out.printf( + "Uploaded page blob with sequence number %s%n", response.getBlobSequenceNumber())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.uploadPages#PageRange-Flux + } + + /** + * Code snippets for {@link PageBlobAsyncClient#uploadPagesWithResponse(PageRange, Flux, byte[], PageBlobRequestConditions)} + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public void uploadPagesWithResponseCodeSnippet() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.uploadPagesWithResponse#PageRange-Flux-byte-PageBlobRequestConditions + PageRange pageRange = new PageRange() + .setStart(0) + .setEnd(511); + + byte[] md5 = MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8)); + PageBlobRequestConditions pageBlobRequestConditions = new PageBlobRequestConditions().setLeaseId(leaseId); + + client.uploadPagesWithResponse(pageRange, body, md5, pageBlobRequestConditions) + .subscribe(response -> System.out.printf( + "Uploaded page blob with sequence number %s%n", response.getValue().getBlobSequenceNumber())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.uploadPagesWithResponse#PageRange-Flux-byte-PageBlobRequestConditions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#uploadPagesFromUrl(PageRange, String, Long)} + */ + public void uploadPagesFromUrl() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.uploadPagesFromUrl#PageRange-String-Long + PageRange pageRange = new PageRange() + .setStart(0) + .setEnd(511); + + client.uploadPagesFromUrl(pageRange, url, sourceOffset) + .subscribe(response -> System.out.printf( + "Uploaded page blob from URL with sequence number %s%n", response.getBlobSequenceNumber())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.uploadPagesFromUrl#PageRange-String-Long + } + + /** + * Code snippets for {@link PageBlobAsyncClient#uploadPagesFromUrlWithResponse(PageRange, String, Long, byte[], + * PageBlobRequestConditions, BlobRequestConditions)} + */ + public void uploadPagesFromUrlWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.uploadPagesFromUrlWithResponse#PageRange-String-Long-byte-PageBlobRequestConditions-BlobRequestConditions + PageRange pageRange = new PageRange() + .setStart(0) + .setEnd(511); + InputStream dataStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); + byte[] sourceContentMD5 = new byte[512]; + PageBlobRequestConditions pageBlobRequestConditions = new PageBlobRequestConditions().setLeaseId(leaseId); + BlobRequestConditions sourceRequestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.uploadPagesFromUrlWithResponse(pageRange, url, sourceOffset, sourceContentMD5, pageBlobRequestConditions, + sourceRequestConditions) + .subscribe(response -> System.out.printf( + "Uploaded page blob from URL with sequence number %s%n", response.getValue().getBlobSequenceNumber())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.uploadPagesFromUrlWithResponse#PageRange-String-Long-byte-PageBlobRequestConditions-BlobRequestConditions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#uploadPagesFromUrlWithResponse(PageBlobUploadPagesFromUrlOptions)} + */ + public void uploadPagesFromUrlWithResponseOptionsBagCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.uploadPagesFromUrlWithResponse#PageBlobUploadPagesFromUrlOptions + PageRange pageRange = new PageRange() + .setStart(0) + .setEnd(511); + InputStream dataStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); + byte[] sourceContentMD5 = new byte[512]; + PageBlobRequestConditions pageBlobRequestConditions = new PageBlobRequestConditions().setLeaseId(leaseId); + BlobRequestConditions sourceRequestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.uploadPagesFromUrlWithResponse(new PageBlobUploadPagesFromUrlOptions(pageRange, url) + .setSourceOffset(sourceOffset).setSourceContentMd5(sourceContentMD5) + .setDestinationRequestConditions(pageBlobRequestConditions) + .setSourceRequestConditions(sourceRequestConditions)) + .subscribe(response -> System.out.printf( + "Uploaded page blob from URL with sequence number %s%n", response.getValue().getBlobSequenceNumber())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.uploadPagesFromUrlWithResponse#PageBlobUploadPagesFromUrlOptions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#clearPages(PageRange)} + */ + public void clearPagesCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.clearPages#PageRange + PageRange pageRange = new PageRange() + .setStart(0) + .setEnd(511); + + client.clearPages(pageRange).subscribe(response -> System.out.printf( + "Cleared page blob with sequence number %s%n", response.getBlobSequenceNumber())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.clearPages#PageRange + } + + /** + * Code snippets for {@link PageBlobAsyncClient#clearPagesWithResponse(PageRange, PageBlobRequestConditions)} + */ + public void clearPagesWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.clearPagesWithResponse#PageRange-PageBlobRequestConditions + PageRange pageRange = new PageRange() + .setStart(0) + .setEnd(511); + PageBlobRequestConditions pageBlobRequestConditions = new PageBlobRequestConditions().setLeaseId(leaseId); + + client.clearPagesWithResponse(pageRange, pageBlobRequestConditions) + .subscribe(response -> System.out.printf( + "Cleared page blob with sequence number %s%n", response.getValue().getBlobSequenceNumber())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.clearPagesWithResponse#PageRange-PageBlobRequestConditions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#getPageRanges(BlobRange)} + */ + public void getPageRangesCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.getPageRanges#BlobRange + BlobRange blobRange = new BlobRange(offset); + + client.getPageRanges(blobRange).subscribe(response -> { + System.out.println("Valid Page Ranges are:"); + for (PageRange pageRange : response.getPageRange()) { + System.out.printf("Start: %s, End: %s%n", pageRange.getStart(), pageRange.getEnd()); + } + }); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.getPageRanges#BlobRange + } + + /** + * Code snippets for {@link PageBlobAsyncClient#getPageRangesWithResponse(BlobRange, BlobRequestConditions)} + */ + public void getPageRangesWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.getPageRangesWithResponse#BlobRange-BlobRequestConditions + BlobRange blobRange = new BlobRange(offset); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.getPageRangesWithResponse(blobRange, blobRequestConditions) + .subscribe(response -> { + System.out.println("Valid Page Ranges are:"); + for (PageRange pageRange : response.getValue().getPageRange()) { + System.out.printf("Start: %s, End: %s%n", pageRange.getStart(), pageRange.getEnd()); + } + }); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.getPageRangesWithResponse#BlobRange-BlobRequestConditions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#listPageRanges(BlobRange)} and + * {@link PageBlobAsyncClient#listPageRanges(ListPageRangesOptions)} + */ + public void listPageRangesCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.listPageRanges#BlobRange + BlobRange blobRange = new BlobRange(offset); + + System.out.println("Valid Page Ranges are:"); + client.listPageRanges(blobRange).subscribe(rangeItem -> System.out.printf("Offset: %s, Length: %s%n", + rangeItem.getRange().getOffset(), rangeItem.getRange().getLength())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.listPageRanges#BlobRange + + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.listPageRanges#ListPageRangesOptions + ListPageRangesOptions options = new ListPageRangesOptions(new BlobRange(offset)) + .setMaxResultsPerPage(1000).setRequestConditions(new BlobRequestConditions().setLeaseId(leaseId)); + + client.listPageRanges(options) + .subscribe(rangeItem -> System.out.printf("Offset: %s, Length: %s%n", rangeItem.getRange().getOffset(), + rangeItem.getRange().getLength())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.listPageRanges#ListPageRangesOptions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#getPageRangesDiff(BlobRange, String)} + */ + public void getPageRangesDiffCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.getPageRangesDiff#BlobRange-String + BlobRange blobRange = new BlobRange(offset); + final String prevSnapshot = "previous snapshot"; + + client.getPageRangesDiff(blobRange, prevSnapshot).subscribe(response -> { + System.out.println("Valid Page Ranges are:"); + for (PageRange pageRange : response.getPageRange()) { + System.out.printf("Start: %s, End: %s%n", pageRange.getStart(), pageRange.getEnd()); + } + }); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.getPageRangesDiff#BlobRange-String + } + + /** + * Code snippets for {@link PageBlobAsyncClient#getPageRangesDiffWithResponse(BlobRange, String, + * BlobRequestConditions)} + */ + public void getPageRangesDiffWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.getPageRangesDiffWithResponse#BlobRange-String-BlobRequestConditions + BlobRange blobRange = new BlobRange(offset); + final String prevSnapshot = "previous snapshot"; + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.getPageRangesDiffWithResponse(blobRange, prevSnapshot, blobRequestConditions) + .subscribe(response -> { + System.out.println("Valid Page Ranges are:"); + for (PageRange pageRange : response.getValue().getPageRange()) { + System.out.printf("Start: %s, End: %s%n", pageRange.getStart(), pageRange.getEnd()); + } + }); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.getPageRangesDiffWithResponse#BlobRange-String-BlobRequestConditions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#listPageRangesDiff(BlobRange, String)} and + * {@link PageBlobAsyncClient#listPageRangesDiff(ListPageRangesDiffOptions)} + */ + public void listPageRangesDiffCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.listPageRangesDiff#BlobRange-String + BlobRange blobRange = new BlobRange(offset); + String prevSnapshot = "previous snapshot"; + + System.out.println("Valid Page Ranges are:"); + client.listPageRangesDiff(blobRange, prevSnapshot).subscribe(rangeItem -> + System.out.printf("Offset: %s, Length: %s, isClear: %s%n", + rangeItem.getRange().getOffset(), rangeItem.getRange().getLength(), rangeItem.isClear())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.listPageRangesDiff#BlobRange-String + + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.listPageRangesDiff#ListPageRangesDiffOptions + ListPageRangesDiffOptions options = new ListPageRangesDiffOptions(new BlobRange(offset), "previous snapshot") + .setRequestConditions(new BlobRequestConditions().setLeaseId(leaseId)) + .setMaxResultsPerPage(1000); + + client.listPageRangesDiff(options) + .subscribe(rangeItem -> System.out.printf("Offset: %s, Length: %s, isClear: %s%n", + rangeItem.getRange().getOffset(), rangeItem.getRange().getLength(), rangeItem.isClear())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.listPageRangesDiff#ListPageRangesDiffOptions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#getManagedDiskPageRangesDiff(BlobRange, String)} + */ + public void getPageRangesDiffFromUrlCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.getManagedDiskPageRangesDiff#BlobRange-String + BlobRange blobRange = new BlobRange(offset); + final String prevSnapshotUrl = "previous snapshot url"; + + client.getPageRangesDiff(blobRange, prevSnapshotUrl).subscribe(response -> { + System.out.println("Valid Page Ranges are:"); + for (PageRange pageRange : response.getPageRange()) { + System.out.printf("Start: %s, End: %s%n", pageRange.getStart(), pageRange.getEnd()); + } + }); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.getManagedDiskPageRangesDiff#BlobRange-String + } + + /** + * Code snippets for {@link PageBlobAsyncClient#getManagedDiskPageRangesDiffWithResponse(BlobRange, String, + * BlobRequestConditions)} + */ + public void getPageRangesDiffFromUrlWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.getManagedDiskPageRangesDiffWithResponse#BlobRange-String-BlobRequestConditions + BlobRange blobRange = new BlobRange(offset); + final String prevSnapshotUrl = "previous snapshot url"; + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.getPageRangesDiffWithResponse(blobRange, prevSnapshotUrl, blobRequestConditions) + .subscribe(response -> { + System.out.println("Valid Page Ranges are:"); + for (PageRange pageRange : response.getValue().getPageRange()) { + System.out.printf("Start: %s, End: %s%n", pageRange.getStart(), pageRange.getEnd()); + } + }); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.getManagedDiskPageRangesDiffWithResponse#BlobRange-String-BlobRequestConditions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#resize(long)} + */ + public void resizeCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.resize#long + client.resize(size).subscribe(response -> System.out.printf( + "Page blob resized with sequence number %s%n", response.getBlobSequenceNumber())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.resize#long + } + + /** + * Code snippets for {@link PageBlobAsyncClient#resizeWithResponse(long, BlobRequestConditions)} + */ + public void resizeWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.resizeWithResponse#long-BlobRequestConditions + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.resizeWithResponse(size, blobRequestConditions) + .subscribe(response -> System.out.printf( + "Page blob resized with sequence number %s%n", response.getValue().getBlobSequenceNumber())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.resizeWithResponse#long-BlobRequestConditions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#updateSequenceNumber(SequenceNumberActionType, Long)} + */ + public void updateSequenceNumberCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.updateSequenceNumber#SequenceNumberActionType-Long + client.updateSequenceNumber(SequenceNumberActionType.INCREMENT, size) + .subscribe(response -> System.out.printf( + "Page blob updated to sequence number %s%n", response.getBlobSequenceNumber())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.updateSequenceNumber#SequenceNumberActionType-Long + } + + /** + * Code snippets for {@link PageBlobAsyncClient#updateSequenceNumberWithResponse(SequenceNumberActionType, Long, + * BlobRequestConditions)} + */ + public void updateSequenceNumberWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.updateSequenceNumberWithResponse#SequenceNumberActionType-Long-BlobRequestConditions + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.updateSequenceNumberWithResponse(SequenceNumberActionType.INCREMENT, size, blobRequestConditions) + .subscribe(response -> System.out.printf( + "Page blob updated to sequence number %s%n", response.getValue().getBlobSequenceNumber())); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.updateSequenceNumberWithResponse#SequenceNumberActionType-Long-BlobRequestConditions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#copyIncremental(String, String)} + */ + public void copyIncrementalCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.copyIncremental#String-String + final String snapshot = "copy snapshot"; + client.copyIncremental(url, snapshot).subscribe(statusType -> { + switch (statusType) { + case SUCCESS: + System.out.println("Page blob copied successfully"); + break; + case FAILED: + System.out.println("Page blob copied failed"); + break; + case ABORTED: + System.out.println("Page blob copied aborted"); + break; + case PENDING: + System.out.println("Page blob copied pending"); + break; + default: + break; + } + }); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.copyIncremental#String-String + } + + /** + * Code snippets for {@link PageBlobAsyncClient#copyIncrementalWithResponse(String, String, RequestConditions)} + */ + public void copyIncrementalWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.copyIncrementalWithResponse#String-String-RequestConditions + final String snapshot = "copy snapshot"; + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfNoneMatch("snapshotMatch"); + + client.copyIncrementalWithResponse(url, snapshot, modifiedRequestConditions) + .subscribe(response -> { + CopyStatusType statusType = response.getValue(); + + switch (statusType) { + case SUCCESS: + System.out.println("Page blob copied successfully"); + break; + case FAILED: + System.out.println("Page blob copied failed"); + break; + case ABORTED: + System.out.println("Page blob copied aborted"); + break; + case PENDING: + System.out.println("Page blob copied pending"); + break; + default: + break; + } + }); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.copyIncrementalWithResponse#String-String-RequestConditions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#copyIncrementalWithResponse(PageBlobCopyIncrementalOptions)} + */ + public void copyIncrementalWithResponseCodeSnippet2() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.copyIncrementalWithResponse#PageBlobCopyIncrementalOptions + final String snapshot = "copy snapshot"; + PageBlobCopyIncrementalRequestConditions destinationRequestConditions = new PageBlobCopyIncrementalRequestConditions() + .setIfNoneMatch("snapshotMatch"); + + client.copyIncrementalWithResponse(new PageBlobCopyIncrementalOptions(url, snapshot) + .setRequestConditions(destinationRequestConditions)) + .subscribe(response -> { + CopyStatusType statusType = response.getValue(); + + switch (statusType) { + case SUCCESS: + System.out.println("Page blob copied successfully"); + break; + case FAILED: + System.out.println("Page blob copied failed"); + break; + case ABORTED: + System.out.println("Page blob copied aborted"); + break; + case PENDING: + System.out.println("Page blob copied pending"); + break; + default: + break; + } + }); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.copyIncrementalWithResponse#PageBlobCopyIncrementalOptions + } + + /** + * Code snippets for {@link PageBlobAsyncClient#createIfNotExists(long)} and + * {@link PageBlobAsyncClient#createIfNotExistsWithResponse(PageBlobCreateOptions)} + */ + public void createIfNotExistsCodeSnippet() { + // BEGIN: com.azure.storage.blob.PageBlobAsyncClient.createIfNotExists#long + client.createIfNotExists(size).subscribe(response -> + System.out.printf("Created page blob with sequence number %s%n", response.getBlobSequenceNumber())); + // END: com.azure.storage.blob.PageBlobAsyncClient.createIfNotExists#long + + // BEGIN: com.azure.storage.blob.specialized.PageBlobAsyncClient.createIfNotExistsWithResponse#PageBlobCreateOptions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentLanguage("en-US") + .setContentType("binary"); + + client.createIfNotExistsWithResponse(new PageBlobCreateOptions(size).setSequenceNumber(sequenceNumber) + .setHeaders(headers).setMetadata(metadata).setTags(tags)).subscribe(response -> { + if (response.getStatusCode() == 409) { + System.out.println("Already exists."); + } else { + System.out.println("successfully created."); + } + }); + // END: com.azure.storage.blob.specialized.PageBlobAsyncClient.createIfNotExistsWithResponse#PageBlobCreateOptions + } + +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample39/v1/PageBlobClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample39/v1/PageBlobClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..33e1cb664ffd --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample39/v1/PageBlobClientJavaDocCodeSnippets.java @@ -0,0 +1,604 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob.specialized; + +import com.azure.core.http.RequestConditions; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.storage.blob.models.PageBlobCopyIncrementalRequestConditions; +import com.azure.storage.blob.models.BlobHttpHeaders; +import com.azure.storage.blob.models.BlobRange; +import com.azure.storage.blob.models.BlobRequestConditions; +import com.azure.storage.blob.models.CopyStatusType; +import com.azure.storage.blob.models.PageRangeItem; +import com.azure.storage.blob.options.ListPageRangesDiffOptions; +import com.azure.storage.blob.options.ListPageRangesOptions; +import com.azure.storage.blob.options.PageBlobCopyIncrementalOptions; +import com.azure.storage.blob.options.PageBlobCreateOptions; +import com.azure.storage.blob.models.PageBlobItem; +import com.azure.storage.blob.models.PageBlobRequestConditions; +import com.azure.storage.blob.models.PageList; +import com.azure.storage.blob.models.PageRange; +import com.azure.storage.blob.models.SequenceNumberActionType; +import com.azure.storage.blob.options.PageBlobUploadPagesFromUrlOptions; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Collections; +import java.util.Map; + +/** + * Code snippets for {@link PageBlobClient} + */ +@SuppressWarnings("unused") +public class PageBlobClientJavaDocCodeSnippets { + private PageBlobClient client = new SpecializedBlobClientBuilder().buildPageBlobClient(); + private Map metadata = Collections.singletonMap("metadata", "value"); + private Map tags = Collections.singletonMap("tag", "value"); + private String leaseId = "leaseId"; + private Duration timeout = Duration.ofSeconds(30); + private long size = 1024; + private long sequenceNumber = 0; + private long sourceOffset = 0; + private long offset = 0; + private String key = "key"; + private String value = "value"; + private String data = "data"; + private String url = "https://sample.com"; + + /** + * Code snippets for {@link PageBlobClient#create(long)} + */ + public void createCodeSnippet() { + // BEGIN: com.azure.storage.blob.PageBlobClient.create#long + PageBlobItem pageBlob = client.create(size); + System.out.printf("Created page blob with sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.PageBlobClient.create#long + } + + /** + * Code snippets for {@link PageBlobClient#create(long, boolean)} + */ + public void createWithOverwrite() { + // BEGIN: com.azure.storage.blob.PageBlobClient.create#long-boolean + boolean overwrite = false; // Default value + PageBlobItem pageBlob = client.create(size, overwrite); + System.out.printf("Created page blob with sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.PageBlobClient.create#long-boolean + } + + /** + * Code snippets for {@link PageBlobClient#createWithResponse(long, Long, BlobHttpHeaders, Map, BlobRequestConditions, Duration, Context)} + */ + public void createWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.createWithResponse#long-Long-BlobHttpHeaders-Map-BlobRequestConditions-Duration-Context + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentLanguage("en-US") + .setContentType("binary"); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + Context context = new Context(key, value); + + PageBlobItem pageBlob = client + .createWithResponse(size, sequenceNumber, headers, metadata, blobRequestConditions, timeout, context) + .getValue(); + + System.out.printf("Created page blob with sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.specialized.PageBlobClient.createWithResponse#long-Long-BlobHttpHeaders-Map-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#createWithResponse(PageBlobCreateOptions, Duration, Context)} + */ + public void createWithResponse2CodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.createWithResponse#PageBlobCreateOptions-Duration-Context + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentLanguage("en-US") + .setContentType("binary"); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + Context context = new Context(key, value); + + PageBlobItem pageBlob = client + .createWithResponse(new PageBlobCreateOptions(size).setSequenceNumber(sequenceNumber) + .setHeaders(headers).setMetadata(metadata).setTags(tags) + .setRequestConditions(blobRequestConditions), timeout, + context) + .getValue(); + + System.out.printf("Created page blob with sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.specialized.PageBlobClient.createWithResponse#PageBlobCreateOptions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#uploadPages(PageRange, InputStream)} + */ + public void uploadPagesCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.uploadPages#PageRange-InputStream + PageRange pageRange = new PageRange() + .setStart(0) + .setEnd(511); + InputStream dataStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); + + PageBlobItem pageBlob = client.uploadPages(pageRange, dataStream); + System.out.printf("Uploaded page blob with sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.specialized.PageBlobClient.uploadPages#PageRange-InputStream + } + + /** + * Code snippets for {@link PageBlobClient#uploadPagesWithResponse(PageRange, InputStream, byte[], + * PageBlobRequestConditions, Duration, Context)} + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public void uploadPagesWithResponseCodeSnippet() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.uploadPagesWithResponse#PageRange-InputStream-byte-PageBlobRequestConditions-Duration-Context + byte[] md5 = MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8)); + PageRange pageRange = new PageRange() + .setStart(0) + .setEnd(511); + InputStream dataStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); + PageBlobRequestConditions pageBlobRequestConditions = new PageBlobRequestConditions().setLeaseId(leaseId); + Context context = new Context(key, value); + + PageBlobItem pageBlob = client + .uploadPagesWithResponse(pageRange, dataStream, md5, pageBlobRequestConditions, timeout, context).getValue(); + + System.out.printf("Uploaded page blob with sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.specialized.PageBlobClient.uploadPagesWithResponse#PageRange-InputStream-byte-PageBlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#uploadPagesFromUrl(PageRange, String, Long)} + */ + public void uploadPagesFromURLCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.uploadPagesFromUrl#PageRange-String-Long + PageRange pageRange = new PageRange() + .setStart(0) + .setEnd(511); + + PageBlobItem pageBlob = client.uploadPagesFromUrl(pageRange, url, sourceOffset); + + System.out.printf("Uploaded page blob from URL with sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.specialized.PageBlobClient.uploadPagesFromUrl#PageRange-String-Long + } + + /** + * Code snippets for {@link PageBlobClient#uploadPagesFromUrlWithResponse(PageRange, String, Long, byte[], + * PageBlobRequestConditions, BlobRequestConditions, Duration, Context)} + */ + public void uploadPagesFromUrlWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.uploadPagesFromUrlWithResponse#PageRange-String-Long-byte-PageBlobRequestConditions-BlobRequestConditions-Duration-Context + PageRange pageRange = new PageRange() + .setStart(0) + .setEnd(511); + InputStream dataStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); + byte[] sourceContentMD5 = new byte[512]; + PageBlobRequestConditions pageBlobRequestConditions = new PageBlobRequestConditions().setLeaseId(leaseId); + BlobRequestConditions sourceRequestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context(key, value); + + PageBlobItem pageBlob = client + .uploadPagesFromUrlWithResponse(pageRange, url, sourceOffset, sourceContentMD5, pageBlobRequestConditions, + sourceRequestConditions, timeout, context).getValue(); + + System.out.printf("Uploaded page blob from URL with sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.specialized.PageBlobClient.uploadPagesFromUrlWithResponse#PageRange-String-Long-byte-PageBlobRequestConditions-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#uploadPagesFromUrlWithResponse(PageRange, String, Long, byte[], + * PageBlobRequestConditions, BlobRequestConditions, Duration, Context)} + */ + public void uploadPagesFromUrlWithResponseOptionsBagCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.uploadPagesFromUrlWithResponse#PageBlobUploadPagesFromUrlOptions-Duration-Context + PageRange pageRange = new PageRange() + .setStart(0) + .setEnd(511); + InputStream dataStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); + byte[] sourceContentMD5 = new byte[512]; + PageBlobRequestConditions pageBlobRequestConditions = new PageBlobRequestConditions().setLeaseId(leaseId); + BlobRequestConditions sourceRequestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context(key, value); + + PageBlobItem pageBlob = client + .uploadPagesFromUrlWithResponse(new PageBlobUploadPagesFromUrlOptions(pageRange, url) + .setSourceOffset(sourceOffset).setSourceContentMd5(sourceContentMD5) + .setDestinationRequestConditions(pageBlobRequestConditions) + .setSourceRequestConditions(sourceRequestConditions), timeout, context).getValue(); + + System.out.printf("Uploaded page blob from URL with sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.specialized.PageBlobClient.uploadPagesFromUrlWithResponse#PageBlobUploadPagesFromUrlOptions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#clearPages(PageRange)} + */ + public void clearPagesCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.clearPages#PageRange + PageRange pageRange = new PageRange() + .setStart(0) + .setEnd(511); + + PageBlobItem pageBlob = client.clearPages(pageRange); + + System.out.printf("Cleared page blob with sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.specialized.PageBlobClient.clearPages#PageRange + } + + /** + * Code snippets for {@link PageBlobClient#clearPagesWithResponse(PageRange, PageBlobRequestConditions, Duration, + * Context)} + */ + public void clearPagesWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.clearPagesWithResponse#PageRange-PageBlobRequestConditions-Duration-Context + PageRange pageRange = new PageRange() + .setStart(0) + .setEnd(511); + PageBlobRequestConditions pageBlobRequestConditions = new PageBlobRequestConditions().setLeaseId(leaseId); + Context context = new Context(key, value); + + PageBlobItem pageBlob = client + .clearPagesWithResponse(pageRange, pageBlobRequestConditions, timeout, context).getValue(); + + System.out.printf("Cleared page blob with sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.specialized.PageBlobClient.clearPagesWithResponse#PageRange-PageBlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#getPageRanges(BlobRange)} + */ + public void getPageRangesCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.getPageRanges#BlobRange + BlobRange blobRange = new BlobRange(offset); + PageList pageList = client.getPageRanges(blobRange); + + System.out.println("Valid Page Ranges are:"); + for (PageRange pageRange : pageList.getPageRange()) { + System.out.printf("Start: %s, End: %s%n", pageRange.getStart(), pageRange.getEnd()); + } + // END: com.azure.storage.blob.specialized.PageBlobClient.getPageRanges#BlobRange + } + + /** + * Code snippets for {@link PageBlobClient#getPageRangesWithResponse(BlobRange, BlobRequestConditions, Duration, + * Context)} + */ + public void getPageRangesWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.getPageRangesWithResponse#BlobRange-BlobRequestConditions-Duration-Context + BlobRange blobRange = new BlobRange(offset); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + Context context = new Context(key, value); + + PageList pageList = client + .getPageRangesWithResponse(blobRange, blobRequestConditions, timeout, context).getValue(); + + System.out.println("Valid Page Ranges are:"); + for (PageRange pageRange : pageList.getPageRange()) { + System.out.printf("Start: %s, End: %s%n", pageRange.getStart(), pageRange.getEnd()); + } + // END: com.azure.storage.blob.specialized.PageBlobClient.getPageRangesWithResponse#BlobRange-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#listPageRanges(ListPageRangesOptions, Duration, Context)} and + * {@link PageBlobClient#listPageRanges(BlobRange)}. + */ + public void listPageRangesCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.listPageRanges#BlobRange + BlobRange blobRange = new BlobRange(offset); + String prevSnapshot = "previous snapshot"; + PagedIterable iterable = client.listPageRanges(blobRange); + + for (PageRangeItem item : iterable) { + System.out.printf("Offset: %s, Length: %s, isClear: %s%n", item.getRange().getOffset(), + item.getRange().getLength(), item.isClear()); + } + // END: com.azure.storage.blob.specialized.PageBlobClient.listPageRanges#BlobRange + + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.getPageRangesWithResponse#ListPageRangesOptions-Duration-Context + ListPageRangesOptions options = new ListPageRangesOptions(new BlobRange(offset)) + .setRequestConditions(new BlobRequestConditions().setLeaseId(leaseId)) + .setMaxResultsPerPage(1000); + + Context context = new Context(key, value); + + PagedIterable iter = client + .listPageRanges(options, timeout, context); + + System.out.println("Valid Page Ranges are:"); + for (PageRangeItem item : iter) { + System.out.printf("Offset: %s, Length: %s, isClear: %s%n", item.getRange().getOffset(), + item.getRange().getLength(), item.isClear()); + } + // END: com.azure.storage.blob.specialized.PageBlobClient.getPageRangesWithResponse#ListPageRangesOptions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#getPageRangesDiff(BlobRange, String)} + */ + public void getPageRangesDiffCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.getPageRangesDiff#BlobRange-String + BlobRange blobRange = new BlobRange(offset); + final String prevSnapshot = "previous snapshot"; + PageList pageList = client.getPageRangesDiff(blobRange, prevSnapshot); + + System.out.println("Valid Page Ranges are:"); + for (PageRange pageRange : pageList.getPageRange()) { + System.out.printf("Start: %s, End: %s%n", pageRange.getStart(), pageRange.getEnd()); + } + // END: com.azure.storage.blob.specialized.PageBlobClient.getPageRangesDiff#BlobRange-String + } + + /** + * Code snippets for {@link PageBlobClient#getPageRangesDiffWithResponse(BlobRange, String, BlobRequestConditions, + * Duration, Context)} + */ + public void getPageRangesDiffWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.getPageRangesDiffWithResponse#BlobRange-String-BlobRequestConditions-Duration-Context + BlobRange blobRange = new BlobRange(offset); + final String prevSnapshot = "previous snapshot"; + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + Context context = new Context(key, value); + + PageList pageList = client + .getPageRangesDiffWithResponse(blobRange, prevSnapshot, blobRequestConditions, timeout, context).getValue(); + + System.out.println("Valid Page Ranges are:"); + for (PageRange pageRange : pageList.getPageRange()) { + System.out.printf("Start: %s, End: %s%n", pageRange.getStart(), pageRange.getEnd()); + } + // END: com.azure.storage.blob.specialized.PageBlobClient.getPageRangesDiffWithResponse#BlobRange-String-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#listPageRangesDiff(ListPageRangesDiffOptions, Duration, Context)} and + * {@link PageBlobClient#listPageRangesDiff(BlobRange, String)} + */ + public void listPageRangesDiffCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.listPageRangesDiff#BlobRange-String + BlobRange blobRange = new BlobRange(offset); + String prevSnapshot = "previous snapshot"; + PagedIterable iterable = client.listPageRangesDiff(blobRange, prevSnapshot); + + for (PageRangeItem item : iterable) { + System.out.printf("Offset: %s, Length: %s, isClear: %s%n", item.getRange().getOffset(), + item.getRange().getLength(), item.isClear()); + } + // END: com.azure.storage.blob.specialized.PageBlobClient.listPageRangesDiff#BlobRange-String + + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.getPageRangesDiffWithResponse#ListPageRangesDiffOptions-Duration-Context + ListPageRangesDiffOptions options = new ListPageRangesDiffOptions(new BlobRange(offset), "previous snapshot") + .setRequestConditions(new BlobRequestConditions().setLeaseId(leaseId)) + .setMaxResultsPerPage(1000); + + Context context = new Context(key, value); + + PagedIterable iter = client + .listPageRangesDiff(options, timeout, context); + + System.out.println("Valid Page Ranges are:"); + for (PageRangeItem item : iter) { + System.out.printf("Offset: %s, Length: %s, isClear: %s%n", item.getRange().getOffset(), + item.getRange().getLength(), item.isClear()); + } + // END: com.azure.storage.blob.specialized.PageBlobClient.getPageRangesDiffWithResponse#ListPageRangesDiffOptions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#getManagedDiskPageRangesDiff(BlobRange, String)} + */ + public void getPageRangesDiffFromUrlCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.getManagedDiskPageRangesDiff#BlobRange-String + BlobRange blobRange = new BlobRange(offset); + final String prevSnapshotUrl = "previous snapshot url"; + PageList pageList = client.getPageRangesDiff(blobRange, prevSnapshotUrl); + + System.out.println("Valid Page Ranges are:"); + for (PageRange pageRange : pageList.getPageRange()) { + System.out.printf("Start: %s, End: %s%n", pageRange.getStart(), pageRange.getEnd()); + } + // END: com.azure.storage.blob.specialized.PageBlobClient.getManagedDiskPageRangesDiff#BlobRange-String + } + + /** + * Code snippets for {@link PageBlobClient#getManagedDiskPageRangesDiffWithResponse(BlobRange, String, BlobRequestConditions, + * Duration, Context)} + */ + public void getPageRangesDiffFromUrlWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.getManagedDiskPageRangesDiffWithResponse#BlobRange-String-BlobRequestConditions-Duration-Context + BlobRange blobRange = new BlobRange(offset); + final String prevSnapshotUrl = "previous snapshot url"; + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + Context context = new Context(key, value); + + PageList pageList = client + .getPageRangesDiffWithResponse(blobRange, prevSnapshotUrl, blobRequestConditions, timeout, context).getValue(); + + System.out.println("Valid Page Ranges are:"); + for (PageRange pageRange : pageList.getPageRange()) { + System.out.printf("Start: %s, End: %s%n", pageRange.getStart(), pageRange.getEnd()); + } + // END: com.azure.storage.blob.specialized.PageBlobClient.getManagedDiskPageRangesDiffWithResponse#BlobRange-String-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#resize(long)} + */ + public void resizeCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.resize#long + PageBlobItem pageBlob = client.resize(size); + System.out.printf("Page blob resized with sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.specialized.PageBlobClient.resize#long + } + + /** + * Code snippets for {@link PageBlobClient#resizeWithResponse(long, BlobRequestConditions, Duration, Context)} + */ + public void resizeWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.resizeWithResponse#long-BlobRequestConditions-Duration-Context + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + Context context = new Context(key, value); + + PageBlobItem pageBlob = client + .resizeWithResponse(size, blobRequestConditions, timeout, context).getValue(); + System.out.printf("Page blob resized with sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.specialized.PageBlobClient.resizeWithResponse#long-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#updateSequenceNumber(SequenceNumberActionType, Long)} + */ + public void updateSequenceNumberCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.updateSequenceNumber#SequenceNumberActionType-Long + PageBlobItem pageBlob = client.updateSequenceNumber(SequenceNumberActionType.INCREMENT, size); + + System.out.printf("Page blob updated to sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.specialized.PageBlobClient.updateSequenceNumber#SequenceNumberActionType-Long + } + + /** + * Code snippets for {@link PageBlobClient#updateSequenceNumberWithResponse(SequenceNumberActionType, Long, + * BlobRequestConditions, Duration, Context)} + */ + public void updateSequenceNumberWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.updateSequenceNumberWithResponse#SequenceNumberActionType-Long-BlobRequestConditions-Duration-Context + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + Context context = new Context(key, value); + + PageBlobItem pageBlob = client.updateSequenceNumberWithResponse( + SequenceNumberActionType.INCREMENT, size, blobRequestConditions, timeout, context).getValue(); + + System.out.printf("Page blob updated to sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.specialized.PageBlobClient.updateSequenceNumberWithResponse#SequenceNumberActionType-Long-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#copyIncremental(String, String)} + */ + public void copyIncrementalCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.copyIncremental#String-String + final String snapshot = "copy snapshot"; + CopyStatusType statusType = client.copyIncremental(url, snapshot); + + switch (statusType) { + case SUCCESS: + System.out.println("Page blob copied successfully"); + break; + case FAILED: + System.out.println("Page blob copied failed"); + break; + case ABORTED: + System.out.println("Page blob copied aborted"); + break; + case PENDING: + System.out.println("Page blob copied pending"); + break; + default: + break; + } + // END: com.azure.storage.blob.specialized.PageBlobClient.copyIncremental#String-String + } + + /** + * Code snippets for {@link PageBlobClient#copyIncrementalWithResponse(String, String, RequestConditions, + * Duration, Context)} + */ + public void copyIncrementalWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.copyIncrementalWithResponse#String-String-RequestConditions-Duration-Context + final String snapshot = "copy snapshot"; + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfNoneMatch("snapshotMatch"); + Context context = new Context(key, value); + + CopyStatusType statusType = client + .copyIncrementalWithResponse(url, snapshot, modifiedRequestConditions, timeout, context).getValue(); + + switch (statusType) { + case SUCCESS: + System.out.println("Page blob copied successfully"); + break; + case FAILED: + System.out.println("Page blob copied failed"); + break; + case ABORTED: + System.out.println("Page blob copied aborted"); + break; + case PENDING: + System.out.println("Page blob copied pending"); + break; + default: + break; + } + // END: com.azure.storage.blob.specialized.PageBlobClient.copyIncrementalWithResponse#String-String-RequestConditions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#copyIncrementalWithResponse(PageBlobCopyIncrementalOptions, + * Duration, Context)} + */ + public void copyIncrementalWithResponseCodeSnippet2() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.copyIncrementalWithResponse#PageBlobCopyIncrementalOptions-Duration-Context + final String snapshot = "copy snapshot"; + PageBlobCopyIncrementalRequestConditions destinationRequestConditions = new PageBlobCopyIncrementalRequestConditions() + .setIfNoneMatch("snapshotMatch"); + Context context = new Context(key, value); + + CopyStatusType statusType = client + .copyIncrementalWithResponse(new PageBlobCopyIncrementalOptions(url, snapshot) + .setRequestConditions(destinationRequestConditions), timeout, context).getValue(); + + switch (statusType) { + case SUCCESS: + System.out.println("Page blob copied successfully"); + break; + case FAILED: + System.out.println("Page blob copied failed"); + break; + case ABORTED: + System.out.println("Page blob copied aborted"); + break; + case PENDING: + System.out.println("Page blob copied pending"); + break; + default: + break; + } + // END: com.azure.storage.blob.specialized.PageBlobClient.copyIncrementalWithResponse#PageBlobCopyIncrementalOptions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#createIfNotExists(long)} and + * {@link PageBlobClient#createIfNotExistsWithResponse(PageBlobCreateOptions, Duration, Context)} + */ + public void createIfNotExistsCodeSnippet() { + // BEGIN: com.azure.storage.blob.PageBlobClient.createIfNotExists#long + PageBlobItem pageBlob = client.createIfNotExists(size); + System.out.printf("Created page blob with sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.PageBlobClient.createIfNotExists#long + + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.createIfNotExistsWithResponse#PageBlobCreateOptions-Duration-Context + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentLanguage("en-US") + .setContentType("binary"); + Context context = new Context(key, value); + + Response response = client.createIfNotExistsWithResponse(new PageBlobCreateOptions(size) + .setHeaders(headers).setMetadata(metadata).setTags(tags), timeout, context); + + if (response.getStatusCode() == 409) { + System.out.println("Already existed."); + } else { + System.out.printf("Create completed with status %d%n", response.getStatusCode()); + } + // END: com.azure.storage.blob.specialized.PageBlobClient.createIfNotExistsWithResponse#PageBlobCreateOptions-Duration-Context + } + +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample39/v2/PageBlobClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample39/v2/PageBlobClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..33e1cb664ffd --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample39/v2/PageBlobClientJavaDocCodeSnippets.java @@ -0,0 +1,604 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob.specialized; + +import com.azure.core.http.RequestConditions; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.storage.blob.models.PageBlobCopyIncrementalRequestConditions; +import com.azure.storage.blob.models.BlobHttpHeaders; +import com.azure.storage.blob.models.BlobRange; +import com.azure.storage.blob.models.BlobRequestConditions; +import com.azure.storage.blob.models.CopyStatusType; +import com.azure.storage.blob.models.PageRangeItem; +import com.azure.storage.blob.options.ListPageRangesDiffOptions; +import com.azure.storage.blob.options.ListPageRangesOptions; +import com.azure.storage.blob.options.PageBlobCopyIncrementalOptions; +import com.azure.storage.blob.options.PageBlobCreateOptions; +import com.azure.storage.blob.models.PageBlobItem; +import com.azure.storage.blob.models.PageBlobRequestConditions; +import com.azure.storage.blob.models.PageList; +import com.azure.storage.blob.models.PageRange; +import com.azure.storage.blob.models.SequenceNumberActionType; +import com.azure.storage.blob.options.PageBlobUploadPagesFromUrlOptions; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Collections; +import java.util.Map; + +/** + * Code snippets for {@link PageBlobClient} + */ +@SuppressWarnings("unused") +public class PageBlobClientJavaDocCodeSnippets { + private PageBlobClient client = new SpecializedBlobClientBuilder().buildPageBlobClient(); + private Map metadata = Collections.singletonMap("metadata", "value"); + private Map tags = Collections.singletonMap("tag", "value"); + private String leaseId = "leaseId"; + private Duration timeout = Duration.ofSeconds(30); + private long size = 1024; + private long sequenceNumber = 0; + private long sourceOffset = 0; + private long offset = 0; + private String key = "key"; + private String value = "value"; + private String data = "data"; + private String url = "https://sample.com"; + + /** + * Code snippets for {@link PageBlobClient#create(long)} + */ + public void createCodeSnippet() { + // BEGIN: com.azure.storage.blob.PageBlobClient.create#long + PageBlobItem pageBlob = client.create(size); + System.out.printf("Created page blob with sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.PageBlobClient.create#long + } + + /** + * Code snippets for {@link PageBlobClient#create(long, boolean)} + */ + public void createWithOverwrite() { + // BEGIN: com.azure.storage.blob.PageBlobClient.create#long-boolean + boolean overwrite = false; // Default value + PageBlobItem pageBlob = client.create(size, overwrite); + System.out.printf("Created page blob with sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.PageBlobClient.create#long-boolean + } + + /** + * Code snippets for {@link PageBlobClient#createWithResponse(long, Long, BlobHttpHeaders, Map, BlobRequestConditions, Duration, Context)} + */ + public void createWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.createWithResponse#long-Long-BlobHttpHeaders-Map-BlobRequestConditions-Duration-Context + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentLanguage("en-US") + .setContentType("binary"); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + Context context = new Context(key, value); + + PageBlobItem pageBlob = client + .createWithResponse(size, sequenceNumber, headers, metadata, blobRequestConditions, timeout, context) + .getValue(); + + System.out.printf("Created page blob with sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.specialized.PageBlobClient.createWithResponse#long-Long-BlobHttpHeaders-Map-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#createWithResponse(PageBlobCreateOptions, Duration, Context)} + */ + public void createWithResponse2CodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.createWithResponse#PageBlobCreateOptions-Duration-Context + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentLanguage("en-US") + .setContentType("binary"); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + Context context = new Context(key, value); + + PageBlobItem pageBlob = client + .createWithResponse(new PageBlobCreateOptions(size).setSequenceNumber(sequenceNumber) + .setHeaders(headers).setMetadata(metadata).setTags(tags) + .setRequestConditions(blobRequestConditions), timeout, + context) + .getValue(); + + System.out.printf("Created page blob with sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.specialized.PageBlobClient.createWithResponse#PageBlobCreateOptions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#uploadPages(PageRange, InputStream)} + */ + public void uploadPagesCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.uploadPages#PageRange-InputStream + PageRange pageRange = new PageRange() + .setStart(0) + .setEnd(511); + InputStream dataStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); + + PageBlobItem pageBlob = client.uploadPages(pageRange, dataStream); + System.out.printf("Uploaded page blob with sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.specialized.PageBlobClient.uploadPages#PageRange-InputStream + } + + /** + * Code snippets for {@link PageBlobClient#uploadPagesWithResponse(PageRange, InputStream, byte[], + * PageBlobRequestConditions, Duration, Context)} + * + * @throws NoSuchAlgorithmException If Md5 calculation fails + */ + public void uploadPagesWithResponseCodeSnippet() throws NoSuchAlgorithmException { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.uploadPagesWithResponse#PageRange-InputStream-byte-PageBlobRequestConditions-Duration-Context + byte[] md5 = MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8)); + PageRange pageRange = new PageRange() + .setStart(0) + .setEnd(511); + InputStream dataStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); + PageBlobRequestConditions pageBlobRequestConditions = new PageBlobRequestConditions().setLeaseId(leaseId); + Context context = new Context(key, value); + + PageBlobItem pageBlob = client + .uploadPagesWithResponse(pageRange, dataStream, md5, pageBlobRequestConditions, timeout, context).getValue(); + + System.out.printf("Uploaded page blob with sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.specialized.PageBlobClient.uploadPagesWithResponse#PageRange-InputStream-byte-PageBlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#uploadPagesFromUrl(PageRange, String, Long)} + */ + public void uploadPagesFromURLCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.uploadPagesFromUrl#PageRange-String-Long + PageRange pageRange = new PageRange() + .setStart(0) + .setEnd(511); + + PageBlobItem pageBlob = client.uploadPagesFromUrl(pageRange, url, sourceOffset); + + System.out.printf("Uploaded page blob from URL with sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.specialized.PageBlobClient.uploadPagesFromUrl#PageRange-String-Long + } + + /** + * Code snippets for {@link PageBlobClient#uploadPagesFromUrlWithResponse(PageRange, String, Long, byte[], + * PageBlobRequestConditions, BlobRequestConditions, Duration, Context)} + */ + public void uploadPagesFromUrlWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.uploadPagesFromUrlWithResponse#PageRange-String-Long-byte-PageBlobRequestConditions-BlobRequestConditions-Duration-Context + PageRange pageRange = new PageRange() + .setStart(0) + .setEnd(511); + InputStream dataStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); + byte[] sourceContentMD5 = new byte[512]; + PageBlobRequestConditions pageBlobRequestConditions = new PageBlobRequestConditions().setLeaseId(leaseId); + BlobRequestConditions sourceRequestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context(key, value); + + PageBlobItem pageBlob = client + .uploadPagesFromUrlWithResponse(pageRange, url, sourceOffset, sourceContentMD5, pageBlobRequestConditions, + sourceRequestConditions, timeout, context).getValue(); + + System.out.printf("Uploaded page blob from URL with sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.specialized.PageBlobClient.uploadPagesFromUrlWithResponse#PageRange-String-Long-byte-PageBlobRequestConditions-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#uploadPagesFromUrlWithResponse(PageRange, String, Long, byte[], + * PageBlobRequestConditions, BlobRequestConditions, Duration, Context)} + */ + public void uploadPagesFromUrlWithResponseOptionsBagCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.uploadPagesFromUrlWithResponse#PageBlobUploadPagesFromUrlOptions-Duration-Context + PageRange pageRange = new PageRange() + .setStart(0) + .setEnd(511); + InputStream dataStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); + byte[] sourceContentMD5 = new byte[512]; + PageBlobRequestConditions pageBlobRequestConditions = new PageBlobRequestConditions().setLeaseId(leaseId); + BlobRequestConditions sourceRequestConditions = new BlobRequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Context context = new Context(key, value); + + PageBlobItem pageBlob = client + .uploadPagesFromUrlWithResponse(new PageBlobUploadPagesFromUrlOptions(pageRange, url) + .setSourceOffset(sourceOffset).setSourceContentMd5(sourceContentMD5) + .setDestinationRequestConditions(pageBlobRequestConditions) + .setSourceRequestConditions(sourceRequestConditions), timeout, context).getValue(); + + System.out.printf("Uploaded page blob from URL with sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.specialized.PageBlobClient.uploadPagesFromUrlWithResponse#PageBlobUploadPagesFromUrlOptions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#clearPages(PageRange)} + */ + public void clearPagesCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.clearPages#PageRange + PageRange pageRange = new PageRange() + .setStart(0) + .setEnd(511); + + PageBlobItem pageBlob = client.clearPages(pageRange); + + System.out.printf("Cleared page blob with sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.specialized.PageBlobClient.clearPages#PageRange + } + + /** + * Code snippets for {@link PageBlobClient#clearPagesWithResponse(PageRange, PageBlobRequestConditions, Duration, + * Context)} + */ + public void clearPagesWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.clearPagesWithResponse#PageRange-PageBlobRequestConditions-Duration-Context + PageRange pageRange = new PageRange() + .setStart(0) + .setEnd(511); + PageBlobRequestConditions pageBlobRequestConditions = new PageBlobRequestConditions().setLeaseId(leaseId); + Context context = new Context(key, value); + + PageBlobItem pageBlob = client + .clearPagesWithResponse(pageRange, pageBlobRequestConditions, timeout, context).getValue(); + + System.out.printf("Cleared page blob with sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.specialized.PageBlobClient.clearPagesWithResponse#PageRange-PageBlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#getPageRanges(BlobRange)} + */ + public void getPageRangesCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.getPageRanges#BlobRange + BlobRange blobRange = new BlobRange(offset); + PageList pageList = client.getPageRanges(blobRange); + + System.out.println("Valid Page Ranges are:"); + for (PageRange pageRange : pageList.getPageRange()) { + System.out.printf("Start: %s, End: %s%n", pageRange.getStart(), pageRange.getEnd()); + } + // END: com.azure.storage.blob.specialized.PageBlobClient.getPageRanges#BlobRange + } + + /** + * Code snippets for {@link PageBlobClient#getPageRangesWithResponse(BlobRange, BlobRequestConditions, Duration, + * Context)} + */ + public void getPageRangesWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.getPageRangesWithResponse#BlobRange-BlobRequestConditions-Duration-Context + BlobRange blobRange = new BlobRange(offset); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + Context context = new Context(key, value); + + PageList pageList = client + .getPageRangesWithResponse(blobRange, blobRequestConditions, timeout, context).getValue(); + + System.out.println("Valid Page Ranges are:"); + for (PageRange pageRange : pageList.getPageRange()) { + System.out.printf("Start: %s, End: %s%n", pageRange.getStart(), pageRange.getEnd()); + } + // END: com.azure.storage.blob.specialized.PageBlobClient.getPageRangesWithResponse#BlobRange-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#listPageRanges(ListPageRangesOptions, Duration, Context)} and + * {@link PageBlobClient#listPageRanges(BlobRange)}. + */ + public void listPageRangesCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.listPageRanges#BlobRange + BlobRange blobRange = new BlobRange(offset); + String prevSnapshot = "previous snapshot"; + PagedIterable iterable = client.listPageRanges(blobRange); + + for (PageRangeItem item : iterable) { + System.out.printf("Offset: %s, Length: %s, isClear: %s%n", item.getRange().getOffset(), + item.getRange().getLength(), item.isClear()); + } + // END: com.azure.storage.blob.specialized.PageBlobClient.listPageRanges#BlobRange + + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.getPageRangesWithResponse#ListPageRangesOptions-Duration-Context + ListPageRangesOptions options = new ListPageRangesOptions(new BlobRange(offset)) + .setRequestConditions(new BlobRequestConditions().setLeaseId(leaseId)) + .setMaxResultsPerPage(1000); + + Context context = new Context(key, value); + + PagedIterable iter = client + .listPageRanges(options, timeout, context); + + System.out.println("Valid Page Ranges are:"); + for (PageRangeItem item : iter) { + System.out.printf("Offset: %s, Length: %s, isClear: %s%n", item.getRange().getOffset(), + item.getRange().getLength(), item.isClear()); + } + // END: com.azure.storage.blob.specialized.PageBlobClient.getPageRangesWithResponse#ListPageRangesOptions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#getPageRangesDiff(BlobRange, String)} + */ + public void getPageRangesDiffCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.getPageRangesDiff#BlobRange-String + BlobRange blobRange = new BlobRange(offset); + final String prevSnapshot = "previous snapshot"; + PageList pageList = client.getPageRangesDiff(blobRange, prevSnapshot); + + System.out.println("Valid Page Ranges are:"); + for (PageRange pageRange : pageList.getPageRange()) { + System.out.printf("Start: %s, End: %s%n", pageRange.getStart(), pageRange.getEnd()); + } + // END: com.azure.storage.blob.specialized.PageBlobClient.getPageRangesDiff#BlobRange-String + } + + /** + * Code snippets for {@link PageBlobClient#getPageRangesDiffWithResponse(BlobRange, String, BlobRequestConditions, + * Duration, Context)} + */ + public void getPageRangesDiffWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.getPageRangesDiffWithResponse#BlobRange-String-BlobRequestConditions-Duration-Context + BlobRange blobRange = new BlobRange(offset); + final String prevSnapshot = "previous snapshot"; + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + Context context = new Context(key, value); + + PageList pageList = client + .getPageRangesDiffWithResponse(blobRange, prevSnapshot, blobRequestConditions, timeout, context).getValue(); + + System.out.println("Valid Page Ranges are:"); + for (PageRange pageRange : pageList.getPageRange()) { + System.out.printf("Start: %s, End: %s%n", pageRange.getStart(), pageRange.getEnd()); + } + // END: com.azure.storage.blob.specialized.PageBlobClient.getPageRangesDiffWithResponse#BlobRange-String-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#listPageRangesDiff(ListPageRangesDiffOptions, Duration, Context)} and + * {@link PageBlobClient#listPageRangesDiff(BlobRange, String)} + */ + public void listPageRangesDiffCodeSnippets() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.listPageRangesDiff#BlobRange-String + BlobRange blobRange = new BlobRange(offset); + String prevSnapshot = "previous snapshot"; + PagedIterable iterable = client.listPageRangesDiff(blobRange, prevSnapshot); + + for (PageRangeItem item : iterable) { + System.out.printf("Offset: %s, Length: %s, isClear: %s%n", item.getRange().getOffset(), + item.getRange().getLength(), item.isClear()); + } + // END: com.azure.storage.blob.specialized.PageBlobClient.listPageRangesDiff#BlobRange-String + + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.getPageRangesDiffWithResponse#ListPageRangesDiffOptions-Duration-Context + ListPageRangesDiffOptions options = new ListPageRangesDiffOptions(new BlobRange(offset), "previous snapshot") + .setRequestConditions(new BlobRequestConditions().setLeaseId(leaseId)) + .setMaxResultsPerPage(1000); + + Context context = new Context(key, value); + + PagedIterable iter = client + .listPageRangesDiff(options, timeout, context); + + System.out.println("Valid Page Ranges are:"); + for (PageRangeItem item : iter) { + System.out.printf("Offset: %s, Length: %s, isClear: %s%n", item.getRange().getOffset(), + item.getRange().getLength(), item.isClear()); + } + // END: com.azure.storage.blob.specialized.PageBlobClient.getPageRangesDiffWithResponse#ListPageRangesDiffOptions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#getManagedDiskPageRangesDiff(BlobRange, String)} + */ + public void getPageRangesDiffFromUrlCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.getManagedDiskPageRangesDiff#BlobRange-String + BlobRange blobRange = new BlobRange(offset); + final String prevSnapshotUrl = "previous snapshot url"; + PageList pageList = client.getPageRangesDiff(blobRange, prevSnapshotUrl); + + System.out.println("Valid Page Ranges are:"); + for (PageRange pageRange : pageList.getPageRange()) { + System.out.printf("Start: %s, End: %s%n", pageRange.getStart(), pageRange.getEnd()); + } + // END: com.azure.storage.blob.specialized.PageBlobClient.getManagedDiskPageRangesDiff#BlobRange-String + } + + /** + * Code snippets for {@link PageBlobClient#getManagedDiskPageRangesDiffWithResponse(BlobRange, String, BlobRequestConditions, + * Duration, Context)} + */ + public void getPageRangesDiffFromUrlWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.getManagedDiskPageRangesDiffWithResponse#BlobRange-String-BlobRequestConditions-Duration-Context + BlobRange blobRange = new BlobRange(offset); + final String prevSnapshotUrl = "previous snapshot url"; + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + Context context = new Context(key, value); + + PageList pageList = client + .getPageRangesDiffWithResponse(blobRange, prevSnapshotUrl, blobRequestConditions, timeout, context).getValue(); + + System.out.println("Valid Page Ranges are:"); + for (PageRange pageRange : pageList.getPageRange()) { + System.out.printf("Start: %s, End: %s%n", pageRange.getStart(), pageRange.getEnd()); + } + // END: com.azure.storage.blob.specialized.PageBlobClient.getManagedDiskPageRangesDiffWithResponse#BlobRange-String-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#resize(long)} + */ + public void resizeCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.resize#long + PageBlobItem pageBlob = client.resize(size); + System.out.printf("Page blob resized with sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.specialized.PageBlobClient.resize#long + } + + /** + * Code snippets for {@link PageBlobClient#resizeWithResponse(long, BlobRequestConditions, Duration, Context)} + */ + public void resizeWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.resizeWithResponse#long-BlobRequestConditions-Duration-Context + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + Context context = new Context(key, value); + + PageBlobItem pageBlob = client + .resizeWithResponse(size, blobRequestConditions, timeout, context).getValue(); + System.out.printf("Page blob resized with sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.specialized.PageBlobClient.resizeWithResponse#long-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#updateSequenceNumber(SequenceNumberActionType, Long)} + */ + public void updateSequenceNumberCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.updateSequenceNumber#SequenceNumberActionType-Long + PageBlobItem pageBlob = client.updateSequenceNumber(SequenceNumberActionType.INCREMENT, size); + + System.out.printf("Page blob updated to sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.specialized.PageBlobClient.updateSequenceNumber#SequenceNumberActionType-Long + } + + /** + * Code snippets for {@link PageBlobClient#updateSequenceNumberWithResponse(SequenceNumberActionType, Long, + * BlobRequestConditions, Duration, Context)} + */ + public void updateSequenceNumberWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.updateSequenceNumberWithResponse#SequenceNumberActionType-Long-BlobRequestConditions-Duration-Context + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + Context context = new Context(key, value); + + PageBlobItem pageBlob = client.updateSequenceNumberWithResponse( + SequenceNumberActionType.INCREMENT, size, blobRequestConditions, timeout, context).getValue(); + + System.out.printf("Page blob updated to sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.specialized.PageBlobClient.updateSequenceNumberWithResponse#SequenceNumberActionType-Long-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#copyIncremental(String, String)} + */ + public void copyIncrementalCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.copyIncremental#String-String + final String snapshot = "copy snapshot"; + CopyStatusType statusType = client.copyIncremental(url, snapshot); + + switch (statusType) { + case SUCCESS: + System.out.println("Page blob copied successfully"); + break; + case FAILED: + System.out.println("Page blob copied failed"); + break; + case ABORTED: + System.out.println("Page blob copied aborted"); + break; + case PENDING: + System.out.println("Page blob copied pending"); + break; + default: + break; + } + // END: com.azure.storage.blob.specialized.PageBlobClient.copyIncremental#String-String + } + + /** + * Code snippets for {@link PageBlobClient#copyIncrementalWithResponse(String, String, RequestConditions, + * Duration, Context)} + */ + public void copyIncrementalWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.copyIncrementalWithResponse#String-String-RequestConditions-Duration-Context + final String snapshot = "copy snapshot"; + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfNoneMatch("snapshotMatch"); + Context context = new Context(key, value); + + CopyStatusType statusType = client + .copyIncrementalWithResponse(url, snapshot, modifiedRequestConditions, timeout, context).getValue(); + + switch (statusType) { + case SUCCESS: + System.out.println("Page blob copied successfully"); + break; + case FAILED: + System.out.println("Page blob copied failed"); + break; + case ABORTED: + System.out.println("Page blob copied aborted"); + break; + case PENDING: + System.out.println("Page blob copied pending"); + break; + default: + break; + } + // END: com.azure.storage.blob.specialized.PageBlobClient.copyIncrementalWithResponse#String-String-RequestConditions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#copyIncrementalWithResponse(PageBlobCopyIncrementalOptions, + * Duration, Context)} + */ + public void copyIncrementalWithResponseCodeSnippet2() { + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.copyIncrementalWithResponse#PageBlobCopyIncrementalOptions-Duration-Context + final String snapshot = "copy snapshot"; + PageBlobCopyIncrementalRequestConditions destinationRequestConditions = new PageBlobCopyIncrementalRequestConditions() + .setIfNoneMatch("snapshotMatch"); + Context context = new Context(key, value); + + CopyStatusType statusType = client + .copyIncrementalWithResponse(new PageBlobCopyIncrementalOptions(url, snapshot) + .setRequestConditions(destinationRequestConditions), timeout, context).getValue(); + + switch (statusType) { + case SUCCESS: + System.out.println("Page blob copied successfully"); + break; + case FAILED: + System.out.println("Page blob copied failed"); + break; + case ABORTED: + System.out.println("Page blob copied aborted"); + break; + case PENDING: + System.out.println("Page blob copied pending"); + break; + default: + break; + } + // END: com.azure.storage.blob.specialized.PageBlobClient.copyIncrementalWithResponse#PageBlobCopyIncrementalOptions-Duration-Context + } + + /** + * Code snippets for {@link PageBlobClient#createIfNotExists(long)} and + * {@link PageBlobClient#createIfNotExistsWithResponse(PageBlobCreateOptions, Duration, Context)} + */ + public void createIfNotExistsCodeSnippet() { + // BEGIN: com.azure.storage.blob.PageBlobClient.createIfNotExists#long + PageBlobItem pageBlob = client.createIfNotExists(size); + System.out.printf("Created page blob with sequence number %s%n", pageBlob.getBlobSequenceNumber()); + // END: com.azure.storage.blob.PageBlobClient.createIfNotExists#long + + // BEGIN: com.azure.storage.blob.specialized.PageBlobClient.createIfNotExistsWithResponse#PageBlobCreateOptions-Duration-Context + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentLanguage("en-US") + .setContentType("binary"); + Context context = new Context(key, value); + + Response response = client.createIfNotExistsWithResponse(new PageBlobCreateOptions(size) + .setHeaders(headers).setMetadata(metadata).setTags(tags), timeout, context); + + if (response.getStatusCode() == 409) { + System.out.println("Already existed."); + } else { + System.out.printf("Create completed with status %d%n", response.getStatusCode()); + } + // END: com.azure.storage.blob.specialized.PageBlobClient.createIfNotExistsWithResponse#PageBlobCreateOptions-Duration-Context + } + +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample4/v1/BasicExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample4/v1/BasicExample.java new file mode 100644 index 000000000000..efa3fbaa2f54 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample4/v1/BasicExample.java @@ -0,0 +1,128 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.storage.blob.specialized.BlockBlobClient; +import com.azure.storage.common.StorageSharedKeyCredential; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Locale; + +/** + * This example shows how to start using the Azure Storage Blob SDK for Java. + */ +public class BasicExample { + + /** + * Entry point into the basic examples for Storage blobs. + * + * @param args Unused. Arguments to the program. + * @throws IOException If an I/O error occurs + * @throws RuntimeException If the downloaded data doesn't match the uploaded data + */ + public static void main(String[] args) throws IOException { + + /* + * From the Azure portal, get your Storage account's name and account key. + */ + String accountName = SampleHelper.getAccountName(); + String accountKey = SampleHelper.getAccountKey(); + + /* + * Use your Storage account's name and key to create a credential object; this is used to access your account. + */ + StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey); + + /* + * From the Azure portal, get your Storage account blob service URL endpoint. + * The URL typically looks like this: + */ + String endpoint = String.format(Locale.ROOT, "https://%s.blob.core.windows.net", accountName); + + /* + * Create a BlobServiceClient object that wraps the service endpoint, credential and a request pipeline. + */ + BlobServiceClient storageClient = new BlobServiceClientBuilder().endpoint(endpoint).credential(credential).buildClient(); + + /* + * This example shows several common operations just to get you started. + */ + + /* + * Create a client that references a to-be-created container in your Azure Storage account. This returns a + * ContainerClient object that wraps the container's endpoint, credential and a request pipeline (inherited from storageClient). + * Note that container names require lowercase. + */ + BlobContainerClient blobContainerClient = storageClient.getBlobContainerClient("myjavacontainerbasic" + System.currentTimeMillis()); + + /* + * Create a container in Storage blob account. + */ + blobContainerClient.create(); + + /* + * Create a client that references a to-be-created blob in your Azure Storage account's container. + * This returns a BlockBlobClient object that wraps the blob's endpoint, credential and a request pipeline + * (inherited from containerClient). Note that blob names can be mixed case. + */ + BlockBlobClient blobClient = blobContainerClient.getBlobClient("HelloWorld.txt").getBlockBlobClient(); + + String data = "Hello world!"; + InputStream dataStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); + + /* + * Create the blob with string (plain text) content. + */ + blobClient.upload(dataStream, data.length()); + + dataStream.close(); + + /* + * Download the blob's content to output stream. + */ + int dataSize = (int) blobClient.getProperties().getBlobSize(); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(dataSize); + blobClient.downloadStream(outputStream); + outputStream.close(); + + /* + * Verify that the blob data round-tripped correctly. + */ + if (!data.equals(new String(outputStream.toByteArray(), StandardCharsets.UTF_8))) { + throw new RuntimeException("The downloaded data does not match the uploaded data."); + } + + /* + * Create more blobs before listing. + */ + for (int i = 0; i < 3; i++) { + String sampleData = "Samples"; + InputStream dataInBlobs = new ByteArrayInputStream(sampleData.getBytes(Charset.defaultCharset())); + blobContainerClient.getBlobClient("myblobsforlisting" + System.currentTimeMillis()).getBlockBlobClient() + .upload(dataInBlobs, sampleData.length()); + dataInBlobs.close(); + } + + /* + * List the blob(s) in our container. + */ + blobContainerClient.listBlobs() + .forEach(blobItem -> System.out.println("Blob name: " + blobItem.getName() + ", Snapshot: " + blobItem.getSnapshot())); + + /* + * Delete the blob we created earlier. + */ + blobClient.delete(); + + /* + * Delete the container we created earlier. + */ + blobContainerClient.delete(); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample4/v2/BasicExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample4/v2/BasicExample.java new file mode 100644 index 000000000000..efa3fbaa2f54 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample4/v2/BasicExample.java @@ -0,0 +1,128 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.storage.blob.specialized.BlockBlobClient; +import com.azure.storage.common.StorageSharedKeyCredential; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Locale; + +/** + * This example shows how to start using the Azure Storage Blob SDK for Java. + */ +public class BasicExample { + + /** + * Entry point into the basic examples for Storage blobs. + * + * @param args Unused. Arguments to the program. + * @throws IOException If an I/O error occurs + * @throws RuntimeException If the downloaded data doesn't match the uploaded data + */ + public static void main(String[] args) throws IOException { + + /* + * From the Azure portal, get your Storage account's name and account key. + */ + String accountName = SampleHelper.getAccountName(); + String accountKey = SampleHelper.getAccountKey(); + + /* + * Use your Storage account's name and key to create a credential object; this is used to access your account. + */ + StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey); + + /* + * From the Azure portal, get your Storage account blob service URL endpoint. + * The URL typically looks like this: + */ + String endpoint = String.format(Locale.ROOT, "https://%s.blob.core.windows.net", accountName); + + /* + * Create a BlobServiceClient object that wraps the service endpoint, credential and a request pipeline. + */ + BlobServiceClient storageClient = new BlobServiceClientBuilder().endpoint(endpoint).credential(credential).buildClient(); + + /* + * This example shows several common operations just to get you started. + */ + + /* + * Create a client that references a to-be-created container in your Azure Storage account. This returns a + * ContainerClient object that wraps the container's endpoint, credential and a request pipeline (inherited from storageClient). + * Note that container names require lowercase. + */ + BlobContainerClient blobContainerClient = storageClient.getBlobContainerClient("myjavacontainerbasic" + System.currentTimeMillis()); + + /* + * Create a container in Storage blob account. + */ + blobContainerClient.create(); + + /* + * Create a client that references a to-be-created blob in your Azure Storage account's container. + * This returns a BlockBlobClient object that wraps the blob's endpoint, credential and a request pipeline + * (inherited from containerClient). Note that blob names can be mixed case. + */ + BlockBlobClient blobClient = blobContainerClient.getBlobClient("HelloWorld.txt").getBlockBlobClient(); + + String data = "Hello world!"; + InputStream dataStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); + + /* + * Create the blob with string (plain text) content. + */ + blobClient.upload(dataStream, data.length()); + + dataStream.close(); + + /* + * Download the blob's content to output stream. + */ + int dataSize = (int) blobClient.getProperties().getBlobSize(); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(dataSize); + blobClient.downloadStream(outputStream); + outputStream.close(); + + /* + * Verify that the blob data round-tripped correctly. + */ + if (!data.equals(new String(outputStream.toByteArray(), StandardCharsets.UTF_8))) { + throw new RuntimeException("The downloaded data does not match the uploaded data."); + } + + /* + * Create more blobs before listing. + */ + for (int i = 0; i < 3; i++) { + String sampleData = "Samples"; + InputStream dataInBlobs = new ByteArrayInputStream(sampleData.getBytes(Charset.defaultCharset())); + blobContainerClient.getBlobClient("myblobsforlisting" + System.currentTimeMillis()).getBlockBlobClient() + .upload(dataInBlobs, sampleData.length()); + dataInBlobs.close(); + } + + /* + * List the blob(s) in our container. + */ + blobContainerClient.listBlobs() + .forEach(blobItem -> System.out.println("Blob name: " + blobItem.getName() + ", Snapshot: " + blobItem.getSnapshot())); + + /* + * Delete the blob we created earlier. + */ + blobClient.delete(); + + /* + * Delete the container we created earlier. + */ + blobContainerClient.delete(); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample5/v1/BlobAsyncClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample5/v1/BlobAsyncClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..a2225dd325ee --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample5/v1/BlobAsyncClientJavaDocCodeSnippets.java @@ -0,0 +1,623 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.http.RequestConditions; +import com.azure.core.util.BinaryData; +import com.azure.storage.blob.models.AccessTier; +import com.azure.storage.blob.models.BlobHttpHeaders; +import com.azure.storage.blob.options.BlobParallelUploadOptions; +import com.azure.storage.blob.models.BlobRange; +import com.azure.storage.blob.models.BlobRequestConditions; +import com.azure.storage.blob.options.BlobUploadFromFileOptions; +import com.azure.storage.blob.models.DeleteSnapshotsOptionType; +import com.azure.storage.blob.models.DownloadRetryOptions; +import com.azure.storage.blob.models.ParallelTransferOptions; +import com.azure.storage.blob.models.RehydratePriority; +import com.azure.storage.blob.models.UserDelegationKey; +import com.azure.storage.blob.specialized.BlobAsyncClientBase; +import com.azure.storage.blob.specialized.BlockBlobClient; +import reactor.core.publisher.Flux; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Base64; +import java.util.Collections; +import java.util.Map; + +/** + * Code snippets for {@link BlobAsyncClient} + */ +@SuppressWarnings("unused") +public class BlobAsyncClientJavaDocCodeSnippets { + + private BlobAsyncClient client = JavaDocCodeSnippetsHelpers.getBlobAsyncClient("blobName"); + private Flux data = Flux.just(ByteBuffer.wrap("data".getBytes(StandardCharsets.UTF_8))); + private String leaseId = "leaseId"; + private String copyId = "copyId"; + private String url = "https://sample.com"; + private String file = "file"; + private long blockSize = 50; + private int maxConcurrency = 2; + private String filePath = "filePath"; + private UserDelegationKey userDelegationKey = JavaDocCodeSnippetsHelpers.getUserDelegationKey(); + + /** + * Code snippet for {@link BlobAsyncClient#exists()} + */ + public void existsCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.exists + client.exists().subscribe(response -> System.out.printf("Exists? %b%n", response)); + // END: com.azure.storage.blob.BlobAsyncClient.exists + } + + /** + * Code snippets for {@link BlobAsyncClient#abortCopyFromUrl(String)} + */ + public void abortCopyFromUrlCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.abortCopyFromURL#String + client.abortCopyFromUrl(copyId).doOnSuccess(response -> System.out.println("Aborted copy from URL")); + // END: com.azure.storage.blob.BlobAsyncClient.abortCopyFromURL#String + } + + /** + * Code snippets for {@link BlobAsyncClient#copyFromUrl(String)} + */ + public void copyFromUrlCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.copyFromURL#String + client.copyFromUrl(url).subscribe(response -> System.out.printf("Copy identifier: %s%n", response)); + // END: com.azure.storage.blob.BlobAsyncClient.copyFromURL#String + } + + /** + * Code snippets for {@link BlobAsyncClient#download()} + * + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.download + ByteArrayOutputStream downloadData = new ByteArrayOutputStream(); + client.download().subscribe(piece -> { + try { + downloadData.write(piece.array()); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + }); + // END: com.azure.storage.blob.BlobAsyncClient.download + } + + /** + * Code snippets for {@link BlobAsyncClient#downloadContent()} + * + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadContentCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.downloadContent + client.downloadContent().subscribe(data -> { + System.out.printf("Downloaded %s", data.toString()); + }); + // END: com.azure.storage.blob.BlobAsyncClient.downloadContent + } + + /** + * Code snippets for {@link BlobAsyncClient#downloadWithResponse(BlobRange, DownloadRetryOptions, + * BlobRequestConditions, boolean)} + * + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.download#BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean + BlobRange range = new BlobRange(1024, 2048L); + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + + client.downloadWithResponse(range, options, null, false).subscribe(response -> { + ByteArrayOutputStream downloadData = new ByteArrayOutputStream(); + response.getValue().subscribe(piece -> { + try { + downloadData.write(piece.array()); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + }); + }); + // END: com.azure.storage.blob.BlobAsyncClient.download#BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean + } + + /** + * Code snippets for {@link BlobAsyncClient#downloadToFile(String)} and {@link BlobAsyncClient#downloadToFileWithResponse( + * String, BlobRange, ParallelTransferOptions, DownloadRetryOptions, BlobRequestConditions, boolean)} + */ + public void downloadToFileCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.downloadToFile#String + client.downloadToFile(file).subscribe(response -> System.out.println("Completed download to file")); + // END: com.azure.storage.blob.BlobAsyncClient.downloadToFile#String + + // BEGIN: com.azure.storage.blob.BlobAsyncClient.downloadToFileWithResponse#String-BlobRange-ParallelTransferOptions-DownloadRetryOptions-BlobRequestConditions-boolean + BlobRange range = new BlobRange(1024, 2048L); + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + + client.downloadToFileWithResponse(file, range, null, options, null, false) + .subscribe(response -> System.out.println("Completed download to file")); + // END: com.azure.storage.blob.BlobAsyncClient.downloadToFileWithResponse#String-BlobRange-ParallelTransferOptions-DownloadRetryOptions-BlobRequestConditions-boolean + } + + /** + * Code snippets for {@link BlobAsyncClient#delete()} + */ + public void deleteCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.delete + client.delete().doOnSuccess(response -> System.out.println("Completed delete")); + // END: com.azure.storage.blob.BlobAsyncClient.delete + } + + /** + * Code snippets for {@link BlobAsyncClient#getProperties()} + */ + public void getPropertiesCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.getProperties + client.getProperties().subscribe(response -> + System.out.printf("Type: %s, Size: %d%n", response.getBlobType(), response.getBlobSize())); + // END: com.azure.storage.blob.BlobAsyncClient.getProperties + } + + /** + * Code snippets for {@link BlobAsyncClient#setHttpHeaders(BlobHttpHeaders)} + */ + public void setHTTPHeadersCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.setHTTPHeaders#BlobHttpHeaders + client.setHttpHeaders(new BlobHttpHeaders() + .setContentLanguage("en-US") + .setContentType("binary")); + // END: com.azure.storage.blob.BlobAsyncClient.setHTTPHeaders#BlobHttpHeaders + } + + /** + * Code snippets for {@link BlobAsyncClient#setMetadata(Map)} + */ + public void setMetadataCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.setMetadata#Metadata + client.setMetadata(Collections.singletonMap("metadata", "value")); + // END: com.azure.storage.blob.BlobAsyncClient.setMetadata#Metadata + } + + /** + * Code snippets for {@link BlobAsyncClient#createSnapshot()} + */ + public void createSnapshotCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.createSnapshot + client.createSnapshot() + .subscribe(response -> System.out.printf("Identifier for the snapshot is %s%n", + response.getSnapshotId())); + // END: com.azure.storage.blob.BlobAsyncClient.createSnapshot + } + + /** + * Code snippets for {@link BlobAsyncClientBase#setAccessTier(AccessTier)} + */ + public void setTierCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.setTier#AccessTier + client.setAccessTier(AccessTier.HOT); + // END: com.azure.storage.blob.BlobAsyncClient.setTier#AccessTier + } + + /** + * Code snippet for {@link BlobAsyncClient#undelete()} + */ + public void undeleteCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.undelete + client.undelete().doOnSuccess(response -> System.out.println("Completed undelete")); + // END: com.azure.storage.blob.BlobAsyncClient.undelete + } + + /** + * Code snippet for {@link BlobAsyncClient#getAccountInfo()} + */ + public void getAccountInfoCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.getAccountInfo + client.getAccountInfo().subscribe(response -> System.out.printf("Account Kind: %s, SKU: %s%n", + response.getAccountKind(), response.getSkuName())); + // END: com.azure.storage.blob.BlobAsyncClient.getAccountInfo + } + + /** + * Code snippet for {@link BlobAsyncClient#existsWithResponse()}abortCopyFromURL + */ + public void existsWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.existsWithResponse + client.existsWithResponse().subscribe(response -> System.out.printf("Exists? %b%n", response.getValue())); + // END: com.azure.storage.blob.BlobAsyncClient.existsWithResponse + } + + /** + * Code snippets for {@link BlobAsyncClient#abortCopyFromUrlWithResponse(String, String)} + */ + public void abortCopyFromUrlWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.BlobAsyncClient.abortCopyFromUrlWithResponse#String-String + client.abortCopyFromUrlWithResponse(copyId, leaseId) + .subscribe( + response -> System.out.printf("Aborted copy completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.BlobAsyncClient.abortCopyFromUrlWithResponse#String-String + } + + /** + * Code snippets for {@link BlobAsyncClient#copyFromUrlWithResponse(String, Map, AccessTier, + * RequestConditions, BlobRequestConditions)} + */ + public void copyFromUrlWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.BlobAsyncClient.copyFromUrlWithResponse#String-Metadata-AccessTier-RequestConditions-BlobRequestConditions + Map metadata = Collections.singletonMap("metadata", "value"); + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7)); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.copyFromUrlWithResponse(url, metadata, AccessTier.HOT, modifiedRequestConditions, blobRequestConditions) + .subscribe(response -> System.out.printf("Copy identifier: %s%n", response)); + // END: com.azure.storage.blob.BlobAsyncClient.copyFromUrlWithResponse#String-Metadata-AccessTier-RequestConditions-BlobRequestConditions + } + + /** + * Code snippets for {@link BlobAsyncClient#downloadWithResponse(BlobRange, DownloadRetryOptions, + * BlobRequestConditions, boolean)} + * + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.downloadWithResponse#BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean + BlobRange range = new BlobRange(1024, (long) 2048); + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + + client.downloadWithResponse(range, options, null, false).subscribe(response -> { + ByteArrayOutputStream downloadData = new ByteArrayOutputStream(); + response.getValue().subscribe(piece -> { + try { + downloadData.write(piece.array()); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + }); + }); + // END: com.azure.storage.blob.BlobAsyncClient.downloadWithResponse#BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean + } + + /** + * Code snippets for {@link BlobAsyncClient#deleteWithResponse(DeleteSnapshotsOptionType, BlobRequestConditions)} + */ + public void deleteWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.BlobAsyncClient.deleteWithResponse#DeleteSnapshotsOptionType-BlobRequestConditions + client.deleteWithResponse(DeleteSnapshotsOptionType.INCLUDE, null) + .subscribe(response -> System.out.printf("Delete completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.BlobAsyncClient.deleteWithResponse#DeleteSnapshotsOptionType-BlobRequestConditions + } + + /** + * Code snippets for {@link BlobAsyncClient#getPropertiesWithResponse(BlobRequestConditions)} + */ + public void getPropertiesWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.BlobAsyncClient.getPropertiesWithResponse#BlobRequestConditions + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.getPropertiesWithResponse(requestConditions).subscribe( + response -> System.out.printf("Type: %s, Size: %d%n", response.getValue().getBlobType(), + response.getValue().getBlobSize())); + // END: com.azure.storage.blob.BlobAsyncClient.getPropertiesWithResponse#BlobRequestConditions + } + + /** + * Code snippets for {@link BlobAsyncClient#setHttpHeadersWithResponse(BlobHttpHeaders, BlobRequestConditions)} + */ + public void setHTTPHeadersWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.BlobAsyncClient.setHttpHeadersWithResponse#BlobHttpHeaders-BlobRequestConditions + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.setHttpHeadersWithResponse(new BlobHttpHeaders() + .setContentLanguage("en-US") + .setContentType("binary"), requestConditions).subscribe( + response -> + System.out.printf("Set HTTP headers completed with status %d%n", + response.getStatusCode())); + // END: com.azure.storage.blob.BlobAsyncClient.setHttpHeadersWithResponse#BlobHttpHeaders-BlobRequestConditions + } + + /** + * Code snippets for {@link BlobAsyncClient#setMetadataWithResponse(Map, BlobRequestConditions)} + */ + public void setMetadataWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.setMetadataWithResponse#Metadata-BlobRequestConditions + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.setMetadataWithResponse(Collections.singletonMap("metadata", "value"), requestConditions) + .subscribe( + response -> System.out.printf("Set metadata completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.BlobAsyncClient.setMetadataWithResponse#Metadata-BlobRequestConditions + } + + /** + * Code snippets for {@link BlobAsyncClient#createSnapshotWithResponse(Map, BlobRequestConditions)} + */ + public void createSnapshotWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.BlobAsyncClient.createSnapshotWithResponse#Metadata-BlobRequestConditions + Map snapshotMetadata = Collections.singletonMap("metadata", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.createSnapshotWithResponse(snapshotMetadata, requestConditions) + .subscribe(response -> System.out.printf("Identifier for the snapshot is %s%n", response.getValue())); + // END: com.azure.storage.blob.BlobAsyncClient.createSnapshotWithResponse#Metadata-BlobRequestConditions + } + + /** + * Code snippets for {@link BlobAsyncClientBase#setAccessTierWithResponse(AccessTier, RehydratePriority, String)} + */ + public void setTierWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.setTierWithResponse#AccessTier-RehydratePriority-String + client.setAccessTierWithResponse(AccessTier.HOT, RehydratePriority.STANDARD, leaseId) + .subscribe(response -> System.out.printf("Set tier completed with status code %d%n", + response.getStatusCode())); + // END: com.azure.storage.blob.BlobAsyncClient.setTierWithResponse#AccessTier-RehydratePriority-String + } + + /** + * Code snippet for {@link BlobAsyncClient#undeleteWithResponse()} + */ + public void undeleteWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.undeleteWithResponse + client.undeleteWithResponse() + .subscribe(response -> System.out.printf("Undelete completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.BlobAsyncClient.undeleteWithResponse + } + + /** + * Code snippet for {@link BlobAsyncClient#getAccountInfoWithResponse()} + */ + public void getAccountInfoWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.getAccountInfoWithResponse + client.getAccountInfoWithResponse().subscribe(response -> System.out.printf("Account Kind: %s, SKU: %s%n", + response.getValue().getAccountKind(), response.getValue().getSkuName())); + // END: com.azure.storage.blob.BlobAsyncClient.getAccountInfoWithResponse + } + + /** + * Generates a code sample for using {@link BlobAsyncClient#getContainerName()} + */ + public void getContainerName() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.getContainerName + String containerName = client.getContainerName(); + System.out.println("The name of the container is " + containerName); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.getContainerName + } + + /** + * Generates a code sample for using {@link BlobAsyncClient#getContainerAsyncClient()} + */ + public void getContainerClient() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.getContainerAsyncClient + BlobContainerAsyncClient containerClient = client.getContainerAsyncClient(); + System.out.println("The name of the container is " + containerClient.getBlobContainerName()); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.getContainerAsyncClient + } + + /** + * Generates a code sample for using {@link BlobAsyncClient#getBlobName()} + */ + public void getBlobName() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.getBlobName + String blobName = client.getBlobName(); + System.out.println("The name of the blob is " + blobName); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.getBlobName + } + + /** + * Code snippet for {@link BlobAsyncClient#upload(Flux, ParallelTransferOptions)} + */ + public void upload3() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.upload#Flux-ParallelTransferOptions + ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions() + .setBlockSizeLong(blockSize) + .setMaxConcurrency(maxConcurrency); + client.upload(data, parallelTransferOptions).subscribe(response -> + System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getContentMd5()))); + // END: com.azure.storage.blob.BlobAsyncClient.upload#Flux-ParallelTransferOptions + } + + /** + * Code snippet for {@link BlobAsyncClient#upload(Flux, ParallelTransferOptions, boolean)} + */ + public void uploadOverwrite() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.upload#Flux-ParallelTransferOptions-boolean + ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions() + .setBlockSizeLong(blockSize) + .setMaxConcurrency(maxConcurrency); + boolean overwrite = false; // Default behavior + client.upload(data, parallelTransferOptions, overwrite).subscribe(response -> + System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getContentMd5()))); + // END: com.azure.storage.blob.BlobAsyncClient.upload#Flux-ParallelTransferOptions-boolean + } + + /** + * Code snippet for {@link BlobAsyncClient#upload(BinaryData)} + */ + public void uploadBinaryData() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.upload#BinaryData + client.upload(BinaryData.fromString("Data!")).subscribe(response -> + System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getContentMd5()))); + // END: com.azure.storage.blob.BlobAsyncClient.upload#BinaryData + } + + /** + * Code snippet for {@link BlobAsyncClient#upload(BinaryData, boolean)} + */ + public void uploadBinaryDataOverwrite() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.upload#BinaryData-boolean + boolean overwrite = false; // Default behavior + client.upload(BinaryData.fromString("Data!"), overwrite).subscribe(response -> + System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getContentMd5()))); + // END: com.azure.storage.blob.BlobAsyncClient.upload#BinaryData-boolean + } + + /** + * Code snippet for {@link BlobAsyncClient#uploadWithResponse(Flux, ParallelTransferOptions, BlobHttpHeaders, Map, AccessTier, BlobRequestConditions)} + */ + public void upload4() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.uploadWithResponse#Flux-ParallelTransferOptions-BlobHttpHeaders-Map-AccessTier-BlobRequestConditions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5("data".getBytes(StandardCharsets.UTF_8)) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions() + .setBlockSizeLong(blockSize) + .setMaxConcurrency(maxConcurrency); + + client.uploadWithResponse(data, parallelTransferOptions, headers, metadata, AccessTier.HOT, requestConditions) + .subscribe(response -> System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getValue().getContentMd5()))); + // END: com.azure.storage.blob.BlobAsyncClient.uploadWithResponse#Flux-ParallelTransferOptions-BlobHttpHeaders-Map-AccessTier-BlobRequestConditions + } + + /** + * Code snippet for {@link BlobAsyncClient#uploadWithResponse(Flux, ParallelTransferOptions, BlobHttpHeaders, Map, AccessTier, BlobRequestConditions)} + */ + public void upload5() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.uploadWithResponse#Flux-ParallelTransferOptions-BlobHttpHeaders-Map-AccessTier-BlobRequestConditions.ProgressReporter + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5("data".getBytes(StandardCharsets.UTF_8)) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions() + .setBlockSizeLong(blockSize) + .setMaxConcurrency(maxConcurrency) + .setProgressListener(bytesTransferred -> System.out.printf("Upload progress: %s bytes sent", bytesTransferred)); + + client.uploadWithResponse(data, parallelTransferOptions, headers, metadata, AccessTier.HOT, requestConditions) + .subscribe(response -> System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getValue().getContentMd5()))); + // END: com.azure.storage.blob.BlobAsyncClient.uploadWithResponse#Flux-ParallelTransferOptions-BlobHttpHeaders-Map-AccessTier-BlobRequestConditions.ProgressReporter + } + + /** + * Code snippet for {@link BlobAsyncClient#uploadWithResponse(BlobParallelUploadOptions)} + */ + public void upload6() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.uploadWithResponse#BlobParallelUploadOptions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5("data".getBytes(StandardCharsets.UTF_8)) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions().setBlockSizeLong(blockSize) + .setMaxConcurrency(maxConcurrency).setProgressListener(bytesTransferred -> + System.out.printf("Upload progress: %s bytes sent", bytesTransferred)); + + client.uploadWithResponse(new BlobParallelUploadOptions(data) + .setParallelTransferOptions(parallelTransferOptions).setHeaders(headers).setMetadata(metadata).setTags(tags) + .setTier(AccessTier.HOT).setRequestConditions(requestConditions)) + .subscribe(response -> System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getValue().getContentMd5()))); + // END: com.azure.storage.blob.BlobAsyncClient.uploadWithResponse#BlobParallelUploadOptions + } + + /** + * Code snippet for {@link BlobAsyncClient#uploadFromFile(String)} + */ + public void uploadFromFile() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.uploadFromFile#String + client.uploadFromFile(filePath) + .doOnError(throwable -> System.err.printf("Failed to upload from file %s%n", throwable.getMessage())) + .subscribe(completion -> System.out.println("Upload from file succeeded")); + // END: com.azure.storage.blob.BlobAsyncClient.uploadFromFile#String + } + + /** + * Code snippet for {@link BlobAsyncClient#uploadFromFile(String, boolean)} + */ + public void uploadFromFileOverwrite() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.uploadFromFile#String-boolean + boolean overwrite = false; // Default behavior + client.uploadFromFile(filePath, overwrite) + .doOnError(throwable -> System.err.printf("Failed to upload from file %s%n", throwable.getMessage())) + .subscribe(completion -> System.out.println("Upload from file succeeded")); + // END: com.azure.storage.blob.BlobAsyncClient.uploadFromFile#String-boolean + } + + /** + * Code snippet for {@link BlobAsyncClient#uploadFromFile(String, ParallelTransferOptions, BlobHttpHeaders, Map, AccessTier, BlobRequestConditions)} + */ + public void uploadFromFile2() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.uploadFromFile#String-ParallelTransferOptions-BlobHttpHeaders-Map-AccessTier-BlobRequestConditions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5("data".getBytes(StandardCharsets.UTF_8)) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.uploadFromFile(filePath, + new ParallelTransferOptions().setBlockSizeLong(BlockBlobClient.MAX_STAGE_BLOCK_BYTES_LONG), + headers, metadata, AccessTier.HOT, requestConditions) + .doOnError(throwable -> System.err.printf("Failed to upload from file %s%n", throwable.getMessage())) + .subscribe(completion -> System.out.println("Upload from file succeeded")); + // END: com.azure.storage.blob.BlobAsyncClient.uploadFromFile#String-ParallelTransferOptions-BlobHttpHeaders-Map-AccessTier-BlobRequestConditions + } + + /** + * Code snippet for {@link BlobAsyncClient#uploadFromFileWithResponse(BlobUploadFromFileOptions)} + */ + public void uploadFromFile3() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.uploadFromFileWithResponse#BlobUploadFromFileOptions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5("data".getBytes(StandardCharsets.UTF_8)) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Long blockSize = 100 * 1024 * 1024L; // 100 MB; + + client.uploadFromFileWithResponse(new BlobUploadFromFileOptions(filePath) + .setParallelTransferOptions( + new ParallelTransferOptions().setBlockSizeLong(blockSize)) + .setHeaders(headers).setMetadata(metadata).setTags(tags).setTier(AccessTier.HOT) + .setRequestConditions(requestConditions)) + .doOnError(throwable -> System.err.printf("Failed to upload from file %s%n", throwable.getMessage())) + .subscribe(completion -> System.out.println("Upload from file succeeded")); + // END: com.azure.storage.blob.BlobAsyncClient.uploadFromFileWithResponse#BlobUploadFromFileOptions + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample5/v2/BlobAsyncClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample5/v2/BlobAsyncClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..a2225dd325ee --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample5/v2/BlobAsyncClientJavaDocCodeSnippets.java @@ -0,0 +1,623 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.http.RequestConditions; +import com.azure.core.util.BinaryData; +import com.azure.storage.blob.models.AccessTier; +import com.azure.storage.blob.models.BlobHttpHeaders; +import com.azure.storage.blob.options.BlobParallelUploadOptions; +import com.azure.storage.blob.models.BlobRange; +import com.azure.storage.blob.models.BlobRequestConditions; +import com.azure.storage.blob.options.BlobUploadFromFileOptions; +import com.azure.storage.blob.models.DeleteSnapshotsOptionType; +import com.azure.storage.blob.models.DownloadRetryOptions; +import com.azure.storage.blob.models.ParallelTransferOptions; +import com.azure.storage.blob.models.RehydratePriority; +import com.azure.storage.blob.models.UserDelegationKey; +import com.azure.storage.blob.specialized.BlobAsyncClientBase; +import com.azure.storage.blob.specialized.BlockBlobClient; +import reactor.core.publisher.Flux; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Base64; +import java.util.Collections; +import java.util.Map; + +/** + * Code snippets for {@link BlobAsyncClient} + */ +@SuppressWarnings("unused") +public class BlobAsyncClientJavaDocCodeSnippets { + + private BlobAsyncClient client = JavaDocCodeSnippetsHelpers.getBlobAsyncClient("blobName"); + private Flux data = Flux.just(ByteBuffer.wrap("data".getBytes(StandardCharsets.UTF_8))); + private String leaseId = "leaseId"; + private String copyId = "copyId"; + private String url = "https://sample.com"; + private String file = "file"; + private long blockSize = 50; + private int maxConcurrency = 2; + private String filePath = "filePath"; + private UserDelegationKey userDelegationKey = JavaDocCodeSnippetsHelpers.getUserDelegationKey(); + + /** + * Code snippet for {@link BlobAsyncClient#exists()} + */ + public void existsCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.exists + client.exists().subscribe(response -> System.out.printf("Exists? %b%n", response)); + // END: com.azure.storage.blob.BlobAsyncClient.exists + } + + /** + * Code snippets for {@link BlobAsyncClient#abortCopyFromUrl(String)} + */ + public void abortCopyFromUrlCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.abortCopyFromURL#String + client.abortCopyFromUrl(copyId).doOnSuccess(response -> System.out.println("Aborted copy from URL")); + // END: com.azure.storage.blob.BlobAsyncClient.abortCopyFromURL#String + } + + /** + * Code snippets for {@link BlobAsyncClient#copyFromUrl(String)} + */ + public void copyFromUrlCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.copyFromURL#String + client.copyFromUrl(url).subscribe(response -> System.out.printf("Copy identifier: %s%n", response)); + // END: com.azure.storage.blob.BlobAsyncClient.copyFromURL#String + } + + /** + * Code snippets for {@link BlobAsyncClient#download()} + * + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.download + ByteArrayOutputStream downloadData = new ByteArrayOutputStream(); + client.download().subscribe(piece -> { + try { + downloadData.write(piece.array()); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + }); + // END: com.azure.storage.blob.BlobAsyncClient.download + } + + /** + * Code snippets for {@link BlobAsyncClient#downloadContent()} + * + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadContentCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.downloadContent + client.downloadContent().subscribe(data -> { + System.out.printf("Downloaded %s", data.toString()); + }); + // END: com.azure.storage.blob.BlobAsyncClient.downloadContent + } + + /** + * Code snippets for {@link BlobAsyncClient#downloadWithResponse(BlobRange, DownloadRetryOptions, + * BlobRequestConditions, boolean)} + * + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.download#BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean + BlobRange range = new BlobRange(1024, 2048L); + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + + client.downloadWithResponse(range, options, null, false).subscribe(response -> { + ByteArrayOutputStream downloadData = new ByteArrayOutputStream(); + response.getValue().subscribe(piece -> { + try { + downloadData.write(piece.array()); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + }); + }); + // END: com.azure.storage.blob.BlobAsyncClient.download#BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean + } + + /** + * Code snippets for {@link BlobAsyncClient#downloadToFile(String)} and {@link BlobAsyncClient#downloadToFileWithResponse( + * String, BlobRange, ParallelTransferOptions, DownloadRetryOptions, BlobRequestConditions, boolean)} + */ + public void downloadToFileCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.downloadToFile#String + client.downloadToFile(file).subscribe(response -> System.out.println("Completed download to file")); + // END: com.azure.storage.blob.BlobAsyncClient.downloadToFile#String + + // BEGIN: com.azure.storage.blob.BlobAsyncClient.downloadToFileWithResponse#String-BlobRange-ParallelTransferOptions-DownloadRetryOptions-BlobRequestConditions-boolean + BlobRange range = new BlobRange(1024, 2048L); + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + + client.downloadToFileWithResponse(file, range, null, options, null, false) + .subscribe(response -> System.out.println("Completed download to file")); + // END: com.azure.storage.blob.BlobAsyncClient.downloadToFileWithResponse#String-BlobRange-ParallelTransferOptions-DownloadRetryOptions-BlobRequestConditions-boolean + } + + /** + * Code snippets for {@link BlobAsyncClient#delete()} + */ + public void deleteCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.delete + client.delete().doOnSuccess(response -> System.out.println("Completed delete")); + // END: com.azure.storage.blob.BlobAsyncClient.delete + } + + /** + * Code snippets for {@link BlobAsyncClient#getProperties()} + */ + public void getPropertiesCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.getProperties + client.getProperties().subscribe(response -> + System.out.printf("Type: %s, Size: %d%n", response.getBlobType(), response.getBlobSize())); + // END: com.azure.storage.blob.BlobAsyncClient.getProperties + } + + /** + * Code snippets for {@link BlobAsyncClient#setHttpHeaders(BlobHttpHeaders)} + */ + public void setHTTPHeadersCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.setHTTPHeaders#BlobHttpHeaders + client.setHttpHeaders(new BlobHttpHeaders() + .setContentLanguage("en-US") + .setContentType("binary")); + // END: com.azure.storage.blob.BlobAsyncClient.setHTTPHeaders#BlobHttpHeaders + } + + /** + * Code snippets for {@link BlobAsyncClient#setMetadata(Map)} + */ + public void setMetadataCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.setMetadata#Metadata + client.setMetadata(Collections.singletonMap("metadata", "value")); + // END: com.azure.storage.blob.BlobAsyncClient.setMetadata#Metadata + } + + /** + * Code snippets for {@link BlobAsyncClient#createSnapshot()} + */ + public void createSnapshotCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.createSnapshot + client.createSnapshot() + .subscribe(response -> System.out.printf("Identifier for the snapshot is %s%n", + response.getSnapshotId())); + // END: com.azure.storage.blob.BlobAsyncClient.createSnapshot + } + + /** + * Code snippets for {@link BlobAsyncClientBase#setAccessTier(AccessTier)} + */ + public void setTierCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.setTier#AccessTier + client.setAccessTier(AccessTier.HOT); + // END: com.azure.storage.blob.BlobAsyncClient.setTier#AccessTier + } + + /** + * Code snippet for {@link BlobAsyncClient#undelete()} + */ + public void undeleteCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.undelete + client.undelete().doOnSuccess(response -> System.out.println("Completed undelete")); + // END: com.azure.storage.blob.BlobAsyncClient.undelete + } + + /** + * Code snippet for {@link BlobAsyncClient#getAccountInfo()} + */ + public void getAccountInfoCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.getAccountInfo + client.getAccountInfo().subscribe(response -> System.out.printf("Account Kind: %s, SKU: %s%n", + response.getAccountKind(), response.getSkuName())); + // END: com.azure.storage.blob.BlobAsyncClient.getAccountInfo + } + + /** + * Code snippet for {@link BlobAsyncClient#existsWithResponse()}abortCopyFromURL + */ + public void existsWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.existsWithResponse + client.existsWithResponse().subscribe(response -> System.out.printf("Exists? %b%n", response.getValue())); + // END: com.azure.storage.blob.BlobAsyncClient.existsWithResponse + } + + /** + * Code snippets for {@link BlobAsyncClient#abortCopyFromUrlWithResponse(String, String)} + */ + public void abortCopyFromUrlWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.BlobAsyncClient.abortCopyFromUrlWithResponse#String-String + client.abortCopyFromUrlWithResponse(copyId, leaseId) + .subscribe( + response -> System.out.printf("Aborted copy completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.BlobAsyncClient.abortCopyFromUrlWithResponse#String-String + } + + /** + * Code snippets for {@link BlobAsyncClient#copyFromUrlWithResponse(String, Map, AccessTier, + * RequestConditions, BlobRequestConditions)} + */ + public void copyFromUrlWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.BlobAsyncClient.copyFromUrlWithResponse#String-Metadata-AccessTier-RequestConditions-BlobRequestConditions + Map metadata = Collections.singletonMap("metadata", "value"); + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7)); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.copyFromUrlWithResponse(url, metadata, AccessTier.HOT, modifiedRequestConditions, blobRequestConditions) + .subscribe(response -> System.out.printf("Copy identifier: %s%n", response)); + // END: com.azure.storage.blob.BlobAsyncClient.copyFromUrlWithResponse#String-Metadata-AccessTier-RequestConditions-BlobRequestConditions + } + + /** + * Code snippets for {@link BlobAsyncClient#downloadWithResponse(BlobRange, DownloadRetryOptions, + * BlobRequestConditions, boolean)} + * + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.downloadWithResponse#BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean + BlobRange range = new BlobRange(1024, (long) 2048); + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + + client.downloadWithResponse(range, options, null, false).subscribe(response -> { + ByteArrayOutputStream downloadData = new ByteArrayOutputStream(); + response.getValue().subscribe(piece -> { + try { + downloadData.write(piece.array()); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + }); + }); + // END: com.azure.storage.blob.BlobAsyncClient.downloadWithResponse#BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean + } + + /** + * Code snippets for {@link BlobAsyncClient#deleteWithResponse(DeleteSnapshotsOptionType, BlobRequestConditions)} + */ + public void deleteWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.BlobAsyncClient.deleteWithResponse#DeleteSnapshotsOptionType-BlobRequestConditions + client.deleteWithResponse(DeleteSnapshotsOptionType.INCLUDE, null) + .subscribe(response -> System.out.printf("Delete completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.BlobAsyncClient.deleteWithResponse#DeleteSnapshotsOptionType-BlobRequestConditions + } + + /** + * Code snippets for {@link BlobAsyncClient#getPropertiesWithResponse(BlobRequestConditions)} + */ + public void getPropertiesWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.BlobAsyncClient.getPropertiesWithResponse#BlobRequestConditions + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.getPropertiesWithResponse(requestConditions).subscribe( + response -> System.out.printf("Type: %s, Size: %d%n", response.getValue().getBlobType(), + response.getValue().getBlobSize())); + // END: com.azure.storage.blob.BlobAsyncClient.getPropertiesWithResponse#BlobRequestConditions + } + + /** + * Code snippets for {@link BlobAsyncClient#setHttpHeadersWithResponse(BlobHttpHeaders, BlobRequestConditions)} + */ + public void setHTTPHeadersWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.BlobAsyncClient.setHttpHeadersWithResponse#BlobHttpHeaders-BlobRequestConditions + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.setHttpHeadersWithResponse(new BlobHttpHeaders() + .setContentLanguage("en-US") + .setContentType("binary"), requestConditions).subscribe( + response -> + System.out.printf("Set HTTP headers completed with status %d%n", + response.getStatusCode())); + // END: com.azure.storage.blob.BlobAsyncClient.setHttpHeadersWithResponse#BlobHttpHeaders-BlobRequestConditions + } + + /** + * Code snippets for {@link BlobAsyncClient#setMetadataWithResponse(Map, BlobRequestConditions)} + */ + public void setMetadataWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.setMetadataWithResponse#Metadata-BlobRequestConditions + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.setMetadataWithResponse(Collections.singletonMap("metadata", "value"), requestConditions) + .subscribe( + response -> System.out.printf("Set metadata completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.BlobAsyncClient.setMetadataWithResponse#Metadata-BlobRequestConditions + } + + /** + * Code snippets for {@link BlobAsyncClient#createSnapshotWithResponse(Map, BlobRequestConditions)} + */ + public void createSnapshotWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.BlobAsyncClient.createSnapshotWithResponse#Metadata-BlobRequestConditions + Map snapshotMetadata = Collections.singletonMap("metadata", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + client.createSnapshotWithResponse(snapshotMetadata, requestConditions) + .subscribe(response -> System.out.printf("Identifier for the snapshot is %s%n", response.getValue())); + // END: com.azure.storage.blob.BlobAsyncClient.createSnapshotWithResponse#Metadata-BlobRequestConditions + } + + /** + * Code snippets for {@link BlobAsyncClientBase#setAccessTierWithResponse(AccessTier, RehydratePriority, String)} + */ + public void setTierWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.setTierWithResponse#AccessTier-RehydratePriority-String + client.setAccessTierWithResponse(AccessTier.HOT, RehydratePriority.STANDARD, leaseId) + .subscribe(response -> System.out.printf("Set tier completed with status code %d%n", + response.getStatusCode())); + // END: com.azure.storage.blob.BlobAsyncClient.setTierWithResponse#AccessTier-RehydratePriority-String + } + + /** + * Code snippet for {@link BlobAsyncClient#undeleteWithResponse()} + */ + public void undeleteWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.undeleteWithResponse + client.undeleteWithResponse() + .subscribe(response -> System.out.printf("Undelete completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.BlobAsyncClient.undeleteWithResponse + } + + /** + * Code snippet for {@link BlobAsyncClient#getAccountInfoWithResponse()} + */ + public void getAccountInfoWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.getAccountInfoWithResponse + client.getAccountInfoWithResponse().subscribe(response -> System.out.printf("Account Kind: %s, SKU: %s%n", + response.getValue().getAccountKind(), response.getValue().getSkuName())); + // END: com.azure.storage.blob.BlobAsyncClient.getAccountInfoWithResponse + } + + /** + * Generates a code sample for using {@link BlobAsyncClient#getContainerName()} + */ + public void getContainerName() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.getContainerName + String containerName = client.getContainerName(); + System.out.println("The name of the container is " + containerName); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.getContainerName + } + + /** + * Generates a code sample for using {@link BlobAsyncClient#getContainerAsyncClient()} + */ + public void getContainerClient() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.getContainerAsyncClient + BlobContainerAsyncClient containerClient = client.getContainerAsyncClient(); + System.out.println("The name of the container is " + containerClient.getBlobContainerName()); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.getContainerAsyncClient + } + + /** + * Generates a code sample for using {@link BlobAsyncClient#getBlobName()} + */ + public void getBlobName() { + // BEGIN: com.azure.storage.blob.specialized.BlobAsyncClientBase.getBlobName + String blobName = client.getBlobName(); + System.out.println("The name of the blob is " + blobName); + // END: com.azure.storage.blob.specialized.BlobAsyncClientBase.getBlobName + } + + /** + * Code snippet for {@link BlobAsyncClient#upload(Flux, ParallelTransferOptions)} + */ + public void upload3() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.upload#Flux-ParallelTransferOptions + ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions() + .setBlockSizeLong(blockSize) + .setMaxConcurrency(maxConcurrency); + client.upload(data, parallelTransferOptions).subscribe(response -> + System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getContentMd5()))); + // END: com.azure.storage.blob.BlobAsyncClient.upload#Flux-ParallelTransferOptions + } + + /** + * Code snippet for {@link BlobAsyncClient#upload(Flux, ParallelTransferOptions, boolean)} + */ + public void uploadOverwrite() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.upload#Flux-ParallelTransferOptions-boolean + ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions() + .setBlockSizeLong(blockSize) + .setMaxConcurrency(maxConcurrency); + boolean overwrite = false; // Default behavior + client.upload(data, parallelTransferOptions, overwrite).subscribe(response -> + System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getContentMd5()))); + // END: com.azure.storage.blob.BlobAsyncClient.upload#Flux-ParallelTransferOptions-boolean + } + + /** + * Code snippet for {@link BlobAsyncClient#upload(BinaryData)} + */ + public void uploadBinaryData() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.upload#BinaryData + client.upload(BinaryData.fromString("Data!")).subscribe(response -> + System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getContentMd5()))); + // END: com.azure.storage.blob.BlobAsyncClient.upload#BinaryData + } + + /** + * Code snippet for {@link BlobAsyncClient#upload(BinaryData, boolean)} + */ + public void uploadBinaryDataOverwrite() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.upload#BinaryData-boolean + boolean overwrite = false; // Default behavior + client.upload(BinaryData.fromString("Data!"), overwrite).subscribe(response -> + System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getContentMd5()))); + // END: com.azure.storage.blob.BlobAsyncClient.upload#BinaryData-boolean + } + + /** + * Code snippet for {@link BlobAsyncClient#uploadWithResponse(Flux, ParallelTransferOptions, BlobHttpHeaders, Map, AccessTier, BlobRequestConditions)} + */ + public void upload4() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.uploadWithResponse#Flux-ParallelTransferOptions-BlobHttpHeaders-Map-AccessTier-BlobRequestConditions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5("data".getBytes(StandardCharsets.UTF_8)) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions() + .setBlockSizeLong(blockSize) + .setMaxConcurrency(maxConcurrency); + + client.uploadWithResponse(data, parallelTransferOptions, headers, metadata, AccessTier.HOT, requestConditions) + .subscribe(response -> System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getValue().getContentMd5()))); + // END: com.azure.storage.blob.BlobAsyncClient.uploadWithResponse#Flux-ParallelTransferOptions-BlobHttpHeaders-Map-AccessTier-BlobRequestConditions + } + + /** + * Code snippet for {@link BlobAsyncClient#uploadWithResponse(Flux, ParallelTransferOptions, BlobHttpHeaders, Map, AccessTier, BlobRequestConditions)} + */ + public void upload5() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.uploadWithResponse#Flux-ParallelTransferOptions-BlobHttpHeaders-Map-AccessTier-BlobRequestConditions.ProgressReporter + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5("data".getBytes(StandardCharsets.UTF_8)) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions() + .setBlockSizeLong(blockSize) + .setMaxConcurrency(maxConcurrency) + .setProgressListener(bytesTransferred -> System.out.printf("Upload progress: %s bytes sent", bytesTransferred)); + + client.uploadWithResponse(data, parallelTransferOptions, headers, metadata, AccessTier.HOT, requestConditions) + .subscribe(response -> System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getValue().getContentMd5()))); + // END: com.azure.storage.blob.BlobAsyncClient.uploadWithResponse#Flux-ParallelTransferOptions-BlobHttpHeaders-Map-AccessTier-BlobRequestConditions.ProgressReporter + } + + /** + * Code snippet for {@link BlobAsyncClient#uploadWithResponse(BlobParallelUploadOptions)} + */ + public void upload6() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.uploadWithResponse#BlobParallelUploadOptions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5("data".getBytes(StandardCharsets.UTF_8)) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions().setBlockSizeLong(blockSize) + .setMaxConcurrency(maxConcurrency).setProgressListener(bytesTransferred -> + System.out.printf("Upload progress: %s bytes sent", bytesTransferred)); + + client.uploadWithResponse(new BlobParallelUploadOptions(data) + .setParallelTransferOptions(parallelTransferOptions).setHeaders(headers).setMetadata(metadata).setTags(tags) + .setTier(AccessTier.HOT).setRequestConditions(requestConditions)) + .subscribe(response -> System.out.printf("Uploaded BlockBlob MD5 is %s%n", + Base64.getEncoder().encodeToString(response.getValue().getContentMd5()))); + // END: com.azure.storage.blob.BlobAsyncClient.uploadWithResponse#BlobParallelUploadOptions + } + + /** + * Code snippet for {@link BlobAsyncClient#uploadFromFile(String)} + */ + public void uploadFromFile() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.uploadFromFile#String + client.uploadFromFile(filePath) + .doOnError(throwable -> System.err.printf("Failed to upload from file %s%n", throwable.getMessage())) + .subscribe(completion -> System.out.println("Upload from file succeeded")); + // END: com.azure.storage.blob.BlobAsyncClient.uploadFromFile#String + } + + /** + * Code snippet for {@link BlobAsyncClient#uploadFromFile(String, boolean)} + */ + public void uploadFromFileOverwrite() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.uploadFromFile#String-boolean + boolean overwrite = false; // Default behavior + client.uploadFromFile(filePath, overwrite) + .doOnError(throwable -> System.err.printf("Failed to upload from file %s%n", throwable.getMessage())) + .subscribe(completion -> System.out.println("Upload from file succeeded")); + // END: com.azure.storage.blob.BlobAsyncClient.uploadFromFile#String-boolean + } + + /** + * Code snippet for {@link BlobAsyncClient#uploadFromFile(String, ParallelTransferOptions, BlobHttpHeaders, Map, AccessTier, BlobRequestConditions)} + */ + public void uploadFromFile2() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.uploadFromFile#String-ParallelTransferOptions-BlobHttpHeaders-Map-AccessTier-BlobRequestConditions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5("data".getBytes(StandardCharsets.UTF_8)) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.uploadFromFile(filePath, + new ParallelTransferOptions().setBlockSizeLong(BlockBlobClient.MAX_STAGE_BLOCK_BYTES_LONG), + headers, metadata, AccessTier.HOT, requestConditions) + .doOnError(throwable -> System.err.printf("Failed to upload from file %s%n", throwable.getMessage())) + .subscribe(completion -> System.out.println("Upload from file succeeded")); + // END: com.azure.storage.blob.BlobAsyncClient.uploadFromFile#String-ParallelTransferOptions-BlobHttpHeaders-Map-AccessTier-BlobRequestConditions + } + + /** + * Code snippet for {@link BlobAsyncClient#uploadFromFileWithResponse(BlobUploadFromFileOptions)} + */ + public void uploadFromFile3() { + // BEGIN: com.azure.storage.blob.BlobAsyncClient.uploadFromFileWithResponse#BlobUploadFromFileOptions + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5("data".getBytes(StandardCharsets.UTF_8)) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Long blockSize = 100 * 1024 * 1024L; // 100 MB; + + client.uploadFromFileWithResponse(new BlobUploadFromFileOptions(filePath) + .setParallelTransferOptions( + new ParallelTransferOptions().setBlockSizeLong(blockSize)) + .setHeaders(headers).setMetadata(metadata).setTags(tags).setTier(AccessTier.HOT) + .setRequestConditions(requestConditions)) + .doOnError(throwable -> System.err.printf("Failed to upload from file %s%n", throwable.getMessage())) + .subscribe(completion -> System.out.println("Upload from file succeeded")); + // END: com.azure.storage.blob.BlobAsyncClient.uploadFromFileWithResponse#BlobUploadFromFileOptions + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample6/v1/BlobAudienceExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample6/v1/BlobAudienceExample.java new file mode 100644 index 000000000000..8d614799d085 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample6/v1/BlobAudienceExample.java @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.credential.TokenCredential; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.storage.blob.models.BlobAudience; + +import java.util.Locale; + +/** + * This example shows how to use audience-based authentication with Azure Storage fpr blobs. Audience-based + * authentication requires AAD authentication. The audience is to be used when requesting a token from + * Azure Active Directory (AAD). Note: This audience only has an effect when authenticating a TokenCredential. + */ +public class BlobAudienceExample { + + public static void main(String[] args) { + /* + * From the Azure portal, get your Storage account's name. + */ + String accountName = SampleHelper.getAccountName(); + + /* + * audience will look like: "https://.blob.core.windows.net" + */ + BlobAudience audience = BlobAudience.createBlobServiceAccountAudience(accountName); + + /* The credential used is DefaultAzureCredential because it combines commonly used credentials + * in deployment and development and chooses the credential to used based on its running environment. + * More information can be found at: https://learn.microsoft.com/java/api/overview/azure/identity-readme + * AAD authentication is required for audience-based authentication. + */ + TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); + + /* + * From the Azure portal, get your Storage account blob service URL endpoint. + * The URL typically looks like this: + */ + String endpoint = String.format(Locale.ROOT, "https://%s.blob.core.windows.net", accountName); + + /* + * Create a BlobServiceClient object that wraps the service endpoint, credential and a request pipeline. + */ + BlobServiceClient serviceClient = new BlobServiceClientBuilder() + .endpoint(endpoint) + .credential(tokenCredential) + .audience(null) // The default audience is "https://storage.azure.com" + .buildClient(); + + // This call will succeed because the default audience is "https://storage.azure.com" + serviceClient.getProperties(); + + + /* + Now create a BlobContainerClient that takes a specific audience. + */ + BlobContainerClient containerClient = new BlobContainerClientBuilder() + .endpoint(endpoint) + .credential(tokenCredential) + .audience(audience) + .containerName("myContainer") + .buildClient(); + + /* + Any calls to the service should successfully work with the specified audience. + */ + containerClient.create(); + containerClient.getBlobClient("myBlob").uploadFromFile("path/to/file"); + + /* + The storage account name must be a valid name. If an incorrect storage account name is specified, authentication + will fail. + */ + BlobAudience badAudience = BlobAudience.createBlobServiceAccountAudience("invalidAccount"); + BlobContainerClient badContainerClient = new BlobContainerClientBuilder() + .endpoint(endpoint) + .credential(tokenCredential) + .audience(badAudience) // audience will look like: "https://invalidaccount.blob.core.windows.net" + .containerName("myBadContainer") + .buildClient(); + + try { + badContainerClient.create(); + } catch (Exception e) { + System.out.println("Authentication failed with invalid storage account name."); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample6/v2/BlobAudienceExample.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample6/v2/BlobAudienceExample.java new file mode 100644 index 000000000000..8d614799d085 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample6/v2/BlobAudienceExample.java @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.credential.TokenCredential; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.storage.blob.models.BlobAudience; + +import java.util.Locale; + +/** + * This example shows how to use audience-based authentication with Azure Storage fpr blobs. Audience-based + * authentication requires AAD authentication. The audience is to be used when requesting a token from + * Azure Active Directory (AAD). Note: This audience only has an effect when authenticating a TokenCredential. + */ +public class BlobAudienceExample { + + public static void main(String[] args) { + /* + * From the Azure portal, get your Storage account's name. + */ + String accountName = SampleHelper.getAccountName(); + + /* + * audience will look like: "https://.blob.core.windows.net" + */ + BlobAudience audience = BlobAudience.createBlobServiceAccountAudience(accountName); + + /* The credential used is DefaultAzureCredential because it combines commonly used credentials + * in deployment and development and chooses the credential to used based on its running environment. + * More information can be found at: https://learn.microsoft.com/java/api/overview/azure/identity-readme + * AAD authentication is required for audience-based authentication. + */ + TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); + + /* + * From the Azure portal, get your Storage account blob service URL endpoint. + * The URL typically looks like this: + */ + String endpoint = String.format(Locale.ROOT, "https://%s.blob.core.windows.net", accountName); + + /* + * Create a BlobServiceClient object that wraps the service endpoint, credential and a request pipeline. + */ + BlobServiceClient serviceClient = new BlobServiceClientBuilder() + .endpoint(endpoint) + .credential(tokenCredential) + .audience(null) // The default audience is "https://storage.azure.com" + .buildClient(); + + // This call will succeed because the default audience is "https://storage.azure.com" + serviceClient.getProperties(); + + + /* + Now create a BlobContainerClient that takes a specific audience. + */ + BlobContainerClient containerClient = new BlobContainerClientBuilder() + .endpoint(endpoint) + .credential(tokenCredential) + .audience(audience) + .containerName("myContainer") + .buildClient(); + + /* + Any calls to the service should successfully work with the specified audience. + */ + containerClient.create(); + containerClient.getBlobClient("myBlob").uploadFromFile("path/to/file"); + + /* + The storage account name must be a valid name. If an incorrect storage account name is specified, authentication + will fail. + */ + BlobAudience badAudience = BlobAudience.createBlobServiceAccountAudience("invalidAccount"); + BlobContainerClient badContainerClient = new BlobContainerClientBuilder() + .endpoint(endpoint) + .credential(tokenCredential) + .audience(badAudience) // audience will look like: "https://invalidaccount.blob.core.windows.net" + .containerName("myBadContainer") + .buildClient(); + + try { + badContainerClient.create(); + } catch (Exception e) { + System.out.println("Authentication failed with invalid storage account name."); + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample7/v1/BlobClientBuilderJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample7/v1/BlobClientBuilderJavaDocCodeSnippets.java new file mode 100644 index 000000000000..1b6cb0419729 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample7/v1/BlobClientBuilderJavaDocCodeSnippets.java @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.policy.AddDatePolicy; +import com.azure.core.http.policy.RequestIdPolicy; +import com.azure.storage.common.StorageSharedKeyCredential; +import com.azure.storage.common.policy.RequestRetryOptions; +import com.azure.storage.common.policy.RequestRetryPolicy; +import com.azure.storage.common.policy.StorageSharedKeyCredentialPolicy; + +/** + * Code snippets for {@link BlobClientBuilder} + */ +@SuppressWarnings({"unused"}) +public class BlobClientBuilderJavaDocCodeSnippets { + private String connectionString = "AccountName=name;AccountKey=key;DefaultEndpointProtocol=protocol;EndpointSuffix=suffix"; + private String endpoint = "endpointURL"; + private String containerName = "container Name"; + private StorageSharedKeyCredential storageSharedKeyCredential = new StorageSharedKeyCredential("accountName", "accountKey"); + private HttpPipeline httpPipeline = new HttpPipelineBuilder() + .httpClient(HttpClient.createDefault()) + .policies(new AddDatePolicy()) + .policies(new RequestIdPolicy()) + .policies(new StorageSharedKeyCredentialPolicy(storageSharedKeyCredential)) + .policies(new RequestRetryPolicy(new RequestRetryOptions())) + .build(); + + /** + * Code snippet for {@link BlobClientBuilder#buildClient()} using connection string + */ + public void blobClientConnectionString() { + // BEGIN: com.azure.storage.blob.BlobClientBuilder.buildClient + BlobClient client = new BlobClientBuilder() + .connectionString(connectionString) + .buildClient(); + // END: com.azure.storage.blob.BlobClientBuilder.buildClient + } + + /** + * Code snippet for {@link BlobClientBuilder#buildAsyncClient()} using connection string + */ + public void blobAsyncClientConnectionString() { + // BEGIN: com.azure.storage.blob.BlobClientBuilder.buildAsyncClient + BlobAsyncClient client = new BlobClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + // END: com.azure.storage.blob.BlobClientBuilder.buildAsyncClient + } + + /** + * Code snippet for {@link BlobClientBuilder#endpoint(String)} using credential and endpoint + */ + public void blobClientCredentialAndEndpoint() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.Builder.endpoint#String + BlobClient client = new BlobClientBuilder() + .endpoint(endpoint) + .credential(storageSharedKeyCredential) + .buildClient(); + // END: com.azure.storage.blob.specialized.BlobClientBase.Builder.endpoint#String + } + + /** + * Code snippet for {@link BlobClientBuilder#containerName(String)} using HttpPipeline + */ + public void blobClientHttpPipeline() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.Builder.containerName#String + BlobClient client = new BlobClientBuilder() + .endpoint(endpoint) + .containerName(containerName) + .buildClient(); + // END: com.azure.storage.blob.specialized.BlobClientBase.Builder.containerName#String + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample7/v2/BlobClientBuilderJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample7/v2/BlobClientBuilderJavaDocCodeSnippets.java new file mode 100644 index 000000000000..1b6cb0419729 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample7/v2/BlobClientBuilderJavaDocCodeSnippets.java @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.policy.AddDatePolicy; +import com.azure.core.http.policy.RequestIdPolicy; +import com.azure.storage.common.StorageSharedKeyCredential; +import com.azure.storage.common.policy.RequestRetryOptions; +import com.azure.storage.common.policy.RequestRetryPolicy; +import com.azure.storage.common.policy.StorageSharedKeyCredentialPolicy; + +/** + * Code snippets for {@link BlobClientBuilder} + */ +@SuppressWarnings({"unused"}) +public class BlobClientBuilderJavaDocCodeSnippets { + private String connectionString = "AccountName=name;AccountKey=key;DefaultEndpointProtocol=protocol;EndpointSuffix=suffix"; + private String endpoint = "endpointURL"; + private String containerName = "container Name"; + private StorageSharedKeyCredential storageSharedKeyCredential = new StorageSharedKeyCredential("accountName", "accountKey"); + private HttpPipeline httpPipeline = new HttpPipelineBuilder() + .httpClient(HttpClient.createDefault()) + .policies(new AddDatePolicy()) + .policies(new RequestIdPolicy()) + .policies(new StorageSharedKeyCredentialPolicy(storageSharedKeyCredential)) + .policies(new RequestRetryPolicy(new RequestRetryOptions())) + .build(); + + /** + * Code snippet for {@link BlobClientBuilder#buildClient()} using connection string + */ + public void blobClientConnectionString() { + // BEGIN: com.azure.storage.blob.BlobClientBuilder.buildClient + BlobClient client = new BlobClientBuilder() + .connectionString(connectionString) + .buildClient(); + // END: com.azure.storage.blob.BlobClientBuilder.buildClient + } + + /** + * Code snippet for {@link BlobClientBuilder#buildAsyncClient()} using connection string + */ + public void blobAsyncClientConnectionString() { + // BEGIN: com.azure.storage.blob.BlobClientBuilder.buildAsyncClient + BlobAsyncClient client = new BlobClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + // END: com.azure.storage.blob.BlobClientBuilder.buildAsyncClient + } + + /** + * Code snippet for {@link BlobClientBuilder#endpoint(String)} using credential and endpoint + */ + public void blobClientCredentialAndEndpoint() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.Builder.endpoint#String + BlobClient client = new BlobClientBuilder() + .endpoint(endpoint) + .credential(storageSharedKeyCredential) + .buildClient(); + // END: com.azure.storage.blob.specialized.BlobClientBase.Builder.endpoint#String + } + + /** + * Code snippet for {@link BlobClientBuilder#containerName(String)} using HttpPipeline + */ + public void blobClientHttpPipeline() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.Builder.containerName#String + BlobClient client = new BlobClientBuilder() + .endpoint(endpoint) + .containerName(containerName) + .buildClient(); + // END: com.azure.storage.blob.specialized.BlobClientBase.Builder.containerName#String + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample8/v1/BlobClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample8/v1/BlobClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..bd1f0ae8ce79 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample8/v1/BlobClientJavaDocCodeSnippets.java @@ -0,0 +1,487 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.http.RequestConditions; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; +import com.azure.storage.blob.models.AccessTier; +import com.azure.storage.blob.models.BlobHttpHeaders; +import com.azure.storage.blob.models.BlobProperties; +import com.azure.storage.blob.models.BlobRange; +import com.azure.storage.blob.models.BlobRequestConditions; +import com.azure.storage.blob.options.BlobUploadFromFileOptions; +import com.azure.storage.blob.models.DeleteSnapshotsOptionType; +import com.azure.storage.blob.models.DownloadRetryOptions; +import com.azure.storage.blob.models.ParallelTransferOptions; +import com.azure.storage.blob.models.RehydratePriority; +import com.azure.storage.blob.models.StorageAccountInfo; +import com.azure.storage.blob.models.UserDelegationKey; +import com.azure.storage.blob.specialized.BlobClientBase; +import com.azure.storage.common.implementation.Constants; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Collections; +import java.util.Map; + +/** + * Code snippets for {@link BlobClient} + */ +@SuppressWarnings("unused") +public class BlobClientJavaDocCodeSnippets { + private BlobClient client = new BlobClientBuilder().endpoint("https://storageaccount.blob.core.windows.net") + .containerName("containerName").blobName("blobName").sasToken("sasToken").buildClient(); + private String leaseId = "leaseId"; + private String copyId = "copyId"; + private String url = "https://sample.com"; + private String file = "file"; + private Duration timeout = Duration.ofSeconds(30); + private String key1 = "key1"; + private String key2 = "key2"; + private String value1 = "val1"; + private String value2 = "val2"; + private String filePath = "filePath"; + private UserDelegationKey userDelegationKey = JavaDocCodeSnippetsHelpers.getUserDelegationKey(); + + /** + * Code snippets for {@link BlobClient#exists()} + */ + public void existsCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobClient.exists + System.out.printf("Exists? %b%n", client.exists()); + // END: com.azure.storage.blob.BlobClient.exists + } + + /** + * Code snippets for {@link BlobClient#abortCopyFromUrl(String)} + */ + public void abortCopyFromUrl() { + // BEGIN: com.azure.storage.blob.BlobClient.abortCopyFromUrl#String + client.abortCopyFromUrl(copyId); + System.out.println("Aborted copy completed."); + // END: com.azure.storage.blob.BlobClient.abortCopyFromUrl#String + } + + /** + * Code snippets for {@link BlobClient#copyFromUrl(String)} + */ + public void copyFromUrl() { + // BEGIN: com.azure.storage.blob.BlobClient.copyFromUrl#String + System.out.printf("Copy identifier: %s%n", client.copyFromUrl(url)); + // END: com.azure.storage.blob.BlobClient.copyFromUrl#String + } + + /** + * Code snippets for {@link BlobClient#download(OutputStream)} + */ + public void download() { + // BEGIN: com.azure.storage.blob.BlobClient.download#OutputStream + client.download(new ByteArrayOutputStream()); + System.out.println("Download completed."); + // END: com.azure.storage.blob.BlobClient.download#OutputStream + } + + /** + * Code snippets for {@link BlobClient#downloadContent()} + */ + public void downloadContent() { + // BEGIN: com.azure.storage.blob.BlobClient.downloadContent + BinaryData data = client.downloadContent(); + System.out.printf("Downloaded %s", data.toString()); + // END: com.azure.storage.blob.BlobClient.downloadContent + } + + /** + * Code snippets for {@link BlobClient#downloadToFile(String)} and + * {@link BlobClient#downloadToFileWithResponse(String, BlobRange, ParallelTransferOptions, DownloadRetryOptions, BlobRequestConditions, boolean, Duration, Context)} + */ + public void downloadToFile() { + // BEGIN: com.azure.storage.blob.BlobClient.downloadToFile#String + client.downloadToFile(file); + System.out.println("Completed download to file"); + // END: com.azure.storage.blob.BlobClient.downloadToFile#String + + // BEGIN: com.azure.storage.blob.BlobClient.downloadToFileWithResponse#String-BlobRange-ParallelTransferOptions-DownloadRetryOptions-BlobRequestConditions-boolean-Duration-Context + BlobRange range = new BlobRange(1024, 2048L); + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + + client.downloadToFileWithResponse(file, range, new ParallelTransferOptions().setBlockSizeLong(4L * Constants.MB), + options, null, false, timeout, new Context(key2, value2)); + System.out.println("Completed download to file"); + // END: com.azure.storage.blob.BlobClient.downloadToFileWithResponse#String-BlobRange-ParallelTransferOptions-DownloadRetryOptions-BlobRequestConditions-boolean-Duration-Context + } + + /** + * Code snippets for {@link BlobClient#delete()} + */ + public void setDelete() { + // BEGIN: com.azure.storage.blob.BlobClient.delete + client.delete(); + System.out.println("Delete completed."); + // END: com.azure.storage.blob.BlobClient.delete + } + + /** + * Code snippets for {@link BlobClient#getProperties()} + */ + public void getProperties() { + // BEGIN: com.azure.storage.blob.BlobClient.getProperties + BlobProperties properties = client.getProperties(); + System.out.printf("Type: %s, Size: %d%n", properties.getBlobType(), properties.getBlobSize()); + // END: com.azure.storage.blob.BlobClient.getProperties + } + + /** + * Code snippets for {@link BlobClient#setHttpHeaders(BlobHttpHeaders)} + */ + public void setHTTPHeaders() { + // BEGIN: com.azure.storage.blob.BlobClient.setHTTPHeaders#BlobHttpHeaders + client.setHttpHeaders(new BlobHttpHeaders() + .setContentLanguage("en-US") + .setContentType("binary")); + System.out.println("Set HTTP headers completed"); + // END: com.azure.storage.blob.BlobClient.setHTTPHeaders#BlobHttpHeaders + } + + /** + * Code snippets for {@link BlobClient#setMetadata(Map)} + */ + public void setMetadata() { + // BEGIN: com.azure.storage.blob.BlobClient.setMetadata#Metadata + client.setMetadata(Collections.singletonMap("metadata", "value")); + System.out.println("Set metadata completed"); + // END: com.azure.storage.blob.BlobClient.setMetadata#Metadata + } + + /** + * Code snippets for {@link BlobClient#createSnapshot()} + */ + public void createSnapshot() { + // BEGIN: com.azure.storage.blob.BlobClient.createSnapshot + System.out.printf("Identifier for the snapshot is %s%n", client.createSnapshot().getSnapshotId()); + // END: com.azure.storage.blob.BlobClient.createSnapshot + } + + /** + * Code snippets for {@link BlobClientBase#setAccessTier(AccessTier)} + */ + public void setTier() { + // BEGIN: com.azure.storage.blob.BlobClient.setTier#AccessTier + client.setAccessTier(AccessTier.HOT); + System.out.println("Set tier completed."); + // END: com.azure.storage.blob.BlobClient.setTier#AccessTier + + + } + + /** + * Code snippets for {@link BlobClient#undelete()} + */ + public void unsetDelete() { + // BEGIN: com.azure.storage.blob.BlobClient.undelete + client.undelete(); + System.out.println("Undelete completed"); + // END: com.azure.storage.blob.BlobClient.undelete + } + + /** + * Code snippet for {@link BlobClient#getAccountInfo()} + */ + public void getAccountInfo() { + // BEGIN: com.azure.storage.blob.BlobClient.getAccountInfo + StorageAccountInfo accountInfo = client.getAccountInfo(); + System.out.printf("Account Kind: %s, SKU: %s%n", accountInfo.getAccountKind(), accountInfo.getSkuName()); + // END: com.azure.storage.blob.BlobClient.getAccountInfo + } + + /** + * Code snippet for {@link BlobClient#existsWithResponse(Duration, Context)} + */ + public void existsWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobClient.existsWithResponse#Duration-Context + System.out.printf("Exists? %b%n", client.existsWithResponse(timeout, new Context(key2, value2)).getValue()); + // END: com.azure.storage.blob.BlobClient.existsWithResponse#Duration-Context + } + + /** + * Code snippets for {@link BlobClient#abortCopyFromUrlWithResponse(String, String, Duration, Context)} + */ + public void abortCopyFromUrlWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.BlobClient.abortCopyFromUrlWithResponse#String-String-Duration-Context + System.out.printf("Aborted copy completed with status %d%n", + client.abortCopyFromUrlWithResponse(copyId, leaseId, timeout, + new Context(key2, value2)).getStatusCode()); + // END: com.azure.storage.blob.BlobClient.abortCopyFromUrlWithResponse#String-String-Duration-Context + } + + /** + * Code snippets for {@link BlobClient#copyFromUrlWithResponse(String, Map, AccessTier, RequestConditions, + * BlobRequestConditions, Duration, Context)} + */ + public void copyFromUrlWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.BlobClient.copyFromUrlWithResponse#String-Metadata-AccessTier-RequestConditions-BlobRequestConditions-Duration-Context + Map metadata = Collections.singletonMap("metadata", "value"); + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7)); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + System.out.printf("Copy identifier: %s%n", + client.copyFromUrlWithResponse(url, metadata, AccessTier.HOT, modifiedRequestConditions, + blobRequestConditions, timeout, + new Context(key1, value1)).getValue()); + // END: com.azure.storage.blob.BlobClient.copyFromUrlWithResponse#String-Metadata-AccessTier-RequestConditions-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobClient#downloadWithResponse(OutputStream, BlobRange, DownloadRetryOptions, + * BlobRequestConditions, boolean, Duration, Context)} + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobClient.downloadWithResponse#OutputStream-BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean-Duration-Context + BlobRange range = new BlobRange(1024, 2048L); + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + + System.out.printf("Download completed with status %d%n", + client.downloadWithResponse(new ByteArrayOutputStream(), range, options, null, false, + timeout, new Context(key2, value2)).getStatusCode()); + // END: com.azure.storage.blob.BlobClient.downloadWithResponse#OutputStream-BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean-Duration-Context + + } + + /** + * Code snippets for {@link BlobClient#deleteWithResponse(DeleteSnapshotsOptionType, BlobRequestConditions, Duration, + * Context)} + */ + public void deleteWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.BlobClient.deleteWithResponse#DeleteSnapshotsOptionType-BlobRequestConditions-Duration-Context + System.out.printf("Delete completed with status %d%n", + client.deleteWithResponse(DeleteSnapshotsOptionType.INCLUDE, null, timeout, + new Context(key1, value1)).getStatusCode()); + // END: com.azure.storage.blob.BlobClient.deleteWithResponse#DeleteSnapshotsOptionType-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobClient#getPropertiesWithResponse(BlobRequestConditions, Duration, Context)} + */ + public void getPropertiesWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.BlobClient.getPropertiesWithResponse#BlobRequestConditions-Duration-Context + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + BlobProperties properties = client.getPropertiesWithResponse(requestConditions, timeout, + new Context(key2, value2)).getValue(); + System.out.printf("Type: %s, Size: %d%n", properties.getBlobType(), properties.getBlobSize()); + // END: com.azure.storage.blob.BlobClient.getPropertiesWithResponse#BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobClient#setHttpHeadersWithResponse(BlobHttpHeaders, BlobRequestConditions, Duration, + * Context)} + */ + public void setHTTPHeadersWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobClient.setHTTPHeadersWithResponse#BlobHttpHeaders-BlobRequestConditions-Duration-Context + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + System.out.printf("Set HTTP headers completed with status %d%n", + client.setHttpHeadersWithResponse(new BlobHttpHeaders() + .setContentLanguage("en-US") + .setContentType("binary"), requestConditions, timeout, new Context(key1, value1)) + .getStatusCode()); + // END: com.azure.storage.blob.BlobClient.setHTTPHeadersWithResponse#BlobHttpHeaders-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobClient#setMetadataWithResponse(Map, BlobRequestConditions, Duration, Context)} + */ + public void setMetadataWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobClient.setMetadataWithResponse#Metadata-BlobRequestConditions-Duration-Context + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + System.out.printf("Set metadata completed with status %d%n", + client.setMetadataWithResponse(Collections.singletonMap("metadata", "value"), requestConditions, timeout, + new Context(key1, value1)).getStatusCode()); + // END: com.azure.storage.blob.BlobClient.setMetadataWithResponse#Metadata-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobClient#createSnapshotWithResponse(Map, BlobRequestConditions, Duration, + * Context)} + */ + public void createSnapshotWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.BlobClient.createSnapshotWithResponse#Metadata-BlobRequestConditions-Duration-Context + Map snapshotMetadata = Collections.singletonMap("metadata", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + System.out.printf("Identifier for the snapshot is %s%n", + client.createSnapshotWithResponse(snapshotMetadata, requestConditions, timeout, + new Context(key1, value1)).getValue()); + // END: com.azure.storage.blob.BlobClient.createSnapshotWithResponse#Metadata-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#setAccessTierWithResponse(AccessTier, RehydratePriority, String, Duration, Context)} + */ + public void setTierWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobClient.setTierWithResponse#AccessTier-RehydratePriority-String-Duration-Context + System.out.printf("Set tier completed with status code %d%n", + client.setAccessTierWithResponse(AccessTier.HOT, RehydratePriority.STANDARD, leaseId, timeout, + new Context(key2, value2)).getStatusCode()); + // END: com.azure.storage.blob.BlobClient.setTierWithResponse#AccessTier-RehydratePriority-String-Duration-Context + } + + /** + * Code snippet for {@link BlobClient#undeleteWithResponse(Duration, Context)} + */ + public void undeleteWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobClient.undeleteWithResponse#Duration-Context + System.out.printf("Undelete completed with status %d%n", client.undeleteWithResponse(timeout, + new Context(key1, value1)).getStatusCode()); + // END: com.azure.storage.blob.BlobClient.undeleteWithResponse#Duration-Context + } + + /** + * Code snippet for {@link BlobClient#getAccountInfoWithResponse(Duration, Context)} + */ + public void getAccountInfoWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobClient.getAccountInfoWithResponse#Duration-Context + StorageAccountInfo accountInfo = client.getAccountInfoWithResponse(timeout, new Context(key1, value1)).getValue(); + System.out.printf("Account Kind: %s, SKU: %s%n", accountInfo.getAccountKind(), accountInfo.getSkuName()); + // END: com.azure.storage.blob.BlobClient.getAccountInfoWithResponse#Duration-Context + } + + /** + * Generates a code sample for using {@link BlobClient#getContainerName()} + */ + public void getContainerName() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.getContainerName + String containerName = client.getContainerName(); + System.out.println("The name of the container is " + containerName); + // END: com.azure.storage.blob.specialized.BlobClientBase.getContainerName + } + + /** + * Generates a code sample for using {@link BlobClient#getContainerClient()} + */ + public void getContainerClient() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.getContainerClient + BlobContainerClient containerClient = client.getContainerClient(); + System.out.println("The name of the container is " + containerClient.getBlobContainerName()); + // END: com.azure.storage.blob.specialized.BlobClientBase.getContainerClient + } + + /** + * Generates a code sample for using {@link BlobClient#getBlobName()} + */ + public void getBlobName() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.getBlobName + String blobName = client.getBlobName(); + System.out.println("The name of the blob is " + blobName); + // END: com.azure.storage.blob.specialized.BlobClientBase.getBlobName + } + + /** + * Code snippet for {@link BlobClient#uploadFromFile(String)} + * + * @throws IOException If an I/O error occurs + */ + public void uploadFromFile() throws IOException { + // BEGIN: com.azure.storage.blob.BlobClient.uploadFromFile#String + try { + client.uploadFromFile(filePath); + System.out.println("Upload from file succeeded"); + } catch (UncheckedIOException ex) { + System.err.printf("Failed to upload from file %s%n", ex.getMessage()); + } + // END: com.azure.storage.blob.BlobClient.uploadFromFile#String + } + + /** + * Code snippet for {@link BlobClient#uploadFromFile(String, boolean)} + * + * @throws IOException If an I/O error occurs + */ + public void uploadFromFileOverwrite() throws IOException { + // BEGIN: com.azure.storage.blob.BlobClient.uploadFromFile#String-boolean + try { + boolean overwrite = false; + client.uploadFromFile(filePath, overwrite); + System.out.println("Upload from file succeeded"); + } catch (UncheckedIOException ex) { + System.err.printf("Failed to upload from file %s%n", ex.getMessage()); + } + // END: com.azure.storage.blob.BlobClient.uploadFromFile#String-boolean + } + + /** + * Code snippet for {@link BlobClient#uploadFromFile(String, ParallelTransferOptions, BlobHttpHeaders, Map, AccessTier, BlobRequestConditions, Duration)} + * + * @throws IOException If an I/O error occurs + */ + public void uploadFromFile2() throws IOException { + // BEGIN: com.azure.storage.blob.BlobClient.uploadFromFile#String-ParallelTransferOptions-BlobHttpHeaders-Map-AccessTier-BlobRequestConditions-Duration + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5("data".getBytes(StandardCharsets.UTF_8)) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Long blockSize = 100L * 1024L * 1024L; // 100 MB; + ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions().setBlockSizeLong(blockSize); + + try { + client.uploadFromFile(filePath, parallelTransferOptions, headers, metadata, + AccessTier.HOT, requestConditions, timeout); + System.out.println("Upload from file succeeded"); + } catch (UncheckedIOException ex) { + System.err.printf("Failed to upload from file %s%n", ex.getMessage()); + } + // END: com.azure.storage.blob.BlobClient.uploadFromFile#String-ParallelTransferOptions-BlobHttpHeaders-Map-AccessTier-BlobRequestConditions-Duration + } + + /** + * Code snippet for {@link BlobClient#uploadFromFileWithResponse(BlobUploadFromFileOptions, Duration, Context)} + * + * @throws IOException If an I/O error occurs + */ + public void uploadFromFile3() throws IOException { + // BEGIN: com.azure.storage.blob.BlobClient.uploadFromFileWithResponse#BlobUploadFromFileOptions-Duration-Context + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5("data".getBytes(StandardCharsets.UTF_8)) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Long blockSize = 100 * 1024 * 1024L; // 100 MB; + ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions().setBlockSizeLong(blockSize); + + try { + client.uploadFromFileWithResponse(new BlobUploadFromFileOptions(filePath) + .setParallelTransferOptions(parallelTransferOptions).setHeaders(headers).setMetadata(metadata) + .setTags(tags).setTier(AccessTier.HOT).setRequestConditions(requestConditions), timeout, + new Context(key2, value2)); + System.out.println("Upload from file succeeded"); + } catch (UncheckedIOException ex) { + System.err.printf("Failed to upload from file %s%n", ex.getMessage()); + } + // END: com.azure.storage.blob.BlobClient.uploadFromFileWithResponse#BlobUploadFromFileOptions-Duration-Context + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample8/v2/BlobClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample8/v2/BlobClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..bd1f0ae8ce79 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample8/v2/BlobClientJavaDocCodeSnippets.java @@ -0,0 +1,487 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.http.RequestConditions; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; +import com.azure.storage.blob.models.AccessTier; +import com.azure.storage.blob.models.BlobHttpHeaders; +import com.azure.storage.blob.models.BlobProperties; +import com.azure.storage.blob.models.BlobRange; +import com.azure.storage.blob.models.BlobRequestConditions; +import com.azure.storage.blob.options.BlobUploadFromFileOptions; +import com.azure.storage.blob.models.DeleteSnapshotsOptionType; +import com.azure.storage.blob.models.DownloadRetryOptions; +import com.azure.storage.blob.models.ParallelTransferOptions; +import com.azure.storage.blob.models.RehydratePriority; +import com.azure.storage.blob.models.StorageAccountInfo; +import com.azure.storage.blob.models.UserDelegationKey; +import com.azure.storage.blob.specialized.BlobClientBase; +import com.azure.storage.common.implementation.Constants; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Collections; +import java.util.Map; + +/** + * Code snippets for {@link BlobClient} + */ +@SuppressWarnings("unused") +public class BlobClientJavaDocCodeSnippets { + private BlobClient client = new BlobClientBuilder().endpoint("https://storageaccount.blob.core.windows.net") + .containerName("containerName").blobName("blobName").sasToken("sasToken").buildClient(); + private String leaseId = "leaseId"; + private String copyId = "copyId"; + private String url = "https://sample.com"; + private String file = "file"; + private Duration timeout = Duration.ofSeconds(30); + private String key1 = "key1"; + private String key2 = "key2"; + private String value1 = "val1"; + private String value2 = "val2"; + private String filePath = "filePath"; + private UserDelegationKey userDelegationKey = JavaDocCodeSnippetsHelpers.getUserDelegationKey(); + + /** + * Code snippets for {@link BlobClient#exists()} + */ + public void existsCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobClient.exists + System.out.printf("Exists? %b%n", client.exists()); + // END: com.azure.storage.blob.BlobClient.exists + } + + /** + * Code snippets for {@link BlobClient#abortCopyFromUrl(String)} + */ + public void abortCopyFromUrl() { + // BEGIN: com.azure.storage.blob.BlobClient.abortCopyFromUrl#String + client.abortCopyFromUrl(copyId); + System.out.println("Aborted copy completed."); + // END: com.azure.storage.blob.BlobClient.abortCopyFromUrl#String + } + + /** + * Code snippets for {@link BlobClient#copyFromUrl(String)} + */ + public void copyFromUrl() { + // BEGIN: com.azure.storage.blob.BlobClient.copyFromUrl#String + System.out.printf("Copy identifier: %s%n", client.copyFromUrl(url)); + // END: com.azure.storage.blob.BlobClient.copyFromUrl#String + } + + /** + * Code snippets for {@link BlobClient#download(OutputStream)} + */ + public void download() { + // BEGIN: com.azure.storage.blob.BlobClient.download#OutputStream + client.download(new ByteArrayOutputStream()); + System.out.println("Download completed."); + // END: com.azure.storage.blob.BlobClient.download#OutputStream + } + + /** + * Code snippets for {@link BlobClient#downloadContent()} + */ + public void downloadContent() { + // BEGIN: com.azure.storage.blob.BlobClient.downloadContent + BinaryData data = client.downloadContent(); + System.out.printf("Downloaded %s", data.toString()); + // END: com.azure.storage.blob.BlobClient.downloadContent + } + + /** + * Code snippets for {@link BlobClient#downloadToFile(String)} and + * {@link BlobClient#downloadToFileWithResponse(String, BlobRange, ParallelTransferOptions, DownloadRetryOptions, BlobRequestConditions, boolean, Duration, Context)} + */ + public void downloadToFile() { + // BEGIN: com.azure.storage.blob.BlobClient.downloadToFile#String + client.downloadToFile(file); + System.out.println("Completed download to file"); + // END: com.azure.storage.blob.BlobClient.downloadToFile#String + + // BEGIN: com.azure.storage.blob.BlobClient.downloadToFileWithResponse#String-BlobRange-ParallelTransferOptions-DownloadRetryOptions-BlobRequestConditions-boolean-Duration-Context + BlobRange range = new BlobRange(1024, 2048L); + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + + client.downloadToFileWithResponse(file, range, new ParallelTransferOptions().setBlockSizeLong(4L * Constants.MB), + options, null, false, timeout, new Context(key2, value2)); + System.out.println("Completed download to file"); + // END: com.azure.storage.blob.BlobClient.downloadToFileWithResponse#String-BlobRange-ParallelTransferOptions-DownloadRetryOptions-BlobRequestConditions-boolean-Duration-Context + } + + /** + * Code snippets for {@link BlobClient#delete()} + */ + public void setDelete() { + // BEGIN: com.azure.storage.blob.BlobClient.delete + client.delete(); + System.out.println("Delete completed."); + // END: com.azure.storage.blob.BlobClient.delete + } + + /** + * Code snippets for {@link BlobClient#getProperties()} + */ + public void getProperties() { + // BEGIN: com.azure.storage.blob.BlobClient.getProperties + BlobProperties properties = client.getProperties(); + System.out.printf("Type: %s, Size: %d%n", properties.getBlobType(), properties.getBlobSize()); + // END: com.azure.storage.blob.BlobClient.getProperties + } + + /** + * Code snippets for {@link BlobClient#setHttpHeaders(BlobHttpHeaders)} + */ + public void setHTTPHeaders() { + // BEGIN: com.azure.storage.blob.BlobClient.setHTTPHeaders#BlobHttpHeaders + client.setHttpHeaders(new BlobHttpHeaders() + .setContentLanguage("en-US") + .setContentType("binary")); + System.out.println("Set HTTP headers completed"); + // END: com.azure.storage.blob.BlobClient.setHTTPHeaders#BlobHttpHeaders + } + + /** + * Code snippets for {@link BlobClient#setMetadata(Map)} + */ + public void setMetadata() { + // BEGIN: com.azure.storage.blob.BlobClient.setMetadata#Metadata + client.setMetadata(Collections.singletonMap("metadata", "value")); + System.out.println("Set metadata completed"); + // END: com.azure.storage.blob.BlobClient.setMetadata#Metadata + } + + /** + * Code snippets for {@link BlobClient#createSnapshot()} + */ + public void createSnapshot() { + // BEGIN: com.azure.storage.blob.BlobClient.createSnapshot + System.out.printf("Identifier for the snapshot is %s%n", client.createSnapshot().getSnapshotId()); + // END: com.azure.storage.blob.BlobClient.createSnapshot + } + + /** + * Code snippets for {@link BlobClientBase#setAccessTier(AccessTier)} + */ + public void setTier() { + // BEGIN: com.azure.storage.blob.BlobClient.setTier#AccessTier + client.setAccessTier(AccessTier.HOT); + System.out.println("Set tier completed."); + // END: com.azure.storage.blob.BlobClient.setTier#AccessTier + + + } + + /** + * Code snippets for {@link BlobClient#undelete()} + */ + public void unsetDelete() { + // BEGIN: com.azure.storage.blob.BlobClient.undelete + client.undelete(); + System.out.println("Undelete completed"); + // END: com.azure.storage.blob.BlobClient.undelete + } + + /** + * Code snippet for {@link BlobClient#getAccountInfo()} + */ + public void getAccountInfo() { + // BEGIN: com.azure.storage.blob.BlobClient.getAccountInfo + StorageAccountInfo accountInfo = client.getAccountInfo(); + System.out.printf("Account Kind: %s, SKU: %s%n", accountInfo.getAccountKind(), accountInfo.getSkuName()); + // END: com.azure.storage.blob.BlobClient.getAccountInfo + } + + /** + * Code snippet for {@link BlobClient#existsWithResponse(Duration, Context)} + */ + public void existsWithResponseCodeSnippet() { + // BEGIN: com.azure.storage.blob.BlobClient.existsWithResponse#Duration-Context + System.out.printf("Exists? %b%n", client.existsWithResponse(timeout, new Context(key2, value2)).getValue()); + // END: com.azure.storage.blob.BlobClient.existsWithResponse#Duration-Context + } + + /** + * Code snippets for {@link BlobClient#abortCopyFromUrlWithResponse(String, String, Duration, Context)} + */ + public void abortCopyFromUrlWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.BlobClient.abortCopyFromUrlWithResponse#String-String-Duration-Context + System.out.printf("Aborted copy completed with status %d%n", + client.abortCopyFromUrlWithResponse(copyId, leaseId, timeout, + new Context(key2, value2)).getStatusCode()); + // END: com.azure.storage.blob.BlobClient.abortCopyFromUrlWithResponse#String-String-Duration-Context + } + + /** + * Code snippets for {@link BlobClient#copyFromUrlWithResponse(String, Map, AccessTier, RequestConditions, + * BlobRequestConditions, Duration, Context)} + */ + public void copyFromUrlWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.BlobClient.copyFromUrlWithResponse#String-Metadata-AccessTier-RequestConditions-BlobRequestConditions-Duration-Context + Map metadata = Collections.singletonMap("metadata", "value"); + RequestConditions modifiedRequestConditions = new RequestConditions() + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(7)); + BlobRequestConditions blobRequestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + System.out.printf("Copy identifier: %s%n", + client.copyFromUrlWithResponse(url, metadata, AccessTier.HOT, modifiedRequestConditions, + blobRequestConditions, timeout, + new Context(key1, value1)).getValue()); + // END: com.azure.storage.blob.BlobClient.copyFromUrlWithResponse#String-Metadata-AccessTier-RequestConditions-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobClient#downloadWithResponse(OutputStream, BlobRange, DownloadRetryOptions, + * BlobRequestConditions, boolean, Duration, Context)} + * @throws UncheckedIOException If an I/O error occurs + */ + public void downloadWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobClient.downloadWithResponse#OutputStream-BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean-Duration-Context + BlobRange range = new BlobRange(1024, 2048L); + DownloadRetryOptions options = new DownloadRetryOptions().setMaxRetryRequests(5); + + System.out.printf("Download completed with status %d%n", + client.downloadWithResponse(new ByteArrayOutputStream(), range, options, null, false, + timeout, new Context(key2, value2)).getStatusCode()); + // END: com.azure.storage.blob.BlobClient.downloadWithResponse#OutputStream-BlobRange-DownloadRetryOptions-BlobRequestConditions-boolean-Duration-Context + + } + + /** + * Code snippets for {@link BlobClient#deleteWithResponse(DeleteSnapshotsOptionType, BlobRequestConditions, Duration, + * Context)} + */ + public void deleteWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.BlobClient.deleteWithResponse#DeleteSnapshotsOptionType-BlobRequestConditions-Duration-Context + System.out.printf("Delete completed with status %d%n", + client.deleteWithResponse(DeleteSnapshotsOptionType.INCLUDE, null, timeout, + new Context(key1, value1)).getStatusCode()); + // END: com.azure.storage.blob.BlobClient.deleteWithResponse#DeleteSnapshotsOptionType-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobClient#getPropertiesWithResponse(BlobRequestConditions, Duration, Context)} + */ + public void getPropertiesWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.BlobClient.getPropertiesWithResponse#BlobRequestConditions-Duration-Context + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + BlobProperties properties = client.getPropertiesWithResponse(requestConditions, timeout, + new Context(key2, value2)).getValue(); + System.out.printf("Type: %s, Size: %d%n", properties.getBlobType(), properties.getBlobSize()); + // END: com.azure.storage.blob.BlobClient.getPropertiesWithResponse#BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobClient#setHttpHeadersWithResponse(BlobHttpHeaders, BlobRequestConditions, Duration, + * Context)} + */ + public void setHTTPHeadersWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobClient.setHTTPHeadersWithResponse#BlobHttpHeaders-BlobRequestConditions-Duration-Context + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + System.out.printf("Set HTTP headers completed with status %d%n", + client.setHttpHeadersWithResponse(new BlobHttpHeaders() + .setContentLanguage("en-US") + .setContentType("binary"), requestConditions, timeout, new Context(key1, value1)) + .getStatusCode()); + // END: com.azure.storage.blob.BlobClient.setHTTPHeadersWithResponse#BlobHttpHeaders-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobClient#setMetadataWithResponse(Map, BlobRequestConditions, Duration, Context)} + */ + public void setMetadataWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobClient.setMetadataWithResponse#Metadata-BlobRequestConditions-Duration-Context + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + System.out.printf("Set metadata completed with status %d%n", + client.setMetadataWithResponse(Collections.singletonMap("metadata", "value"), requestConditions, timeout, + new Context(key1, value1)).getStatusCode()); + // END: com.azure.storage.blob.BlobClient.setMetadataWithResponse#Metadata-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobClient#createSnapshotWithResponse(Map, BlobRequestConditions, Duration, + * Context)} + */ + public void createSnapshotWithResponseCodeSnippets() { + + // BEGIN: com.azure.storage.blob.BlobClient.createSnapshotWithResponse#Metadata-BlobRequestConditions-Duration-Context + Map snapshotMetadata = Collections.singletonMap("metadata", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId(leaseId); + + System.out.printf("Identifier for the snapshot is %s%n", + client.createSnapshotWithResponse(snapshotMetadata, requestConditions, timeout, + new Context(key1, value1)).getValue()); + // END: com.azure.storage.blob.BlobClient.createSnapshotWithResponse#Metadata-BlobRequestConditions-Duration-Context + } + + /** + * Code snippets for {@link BlobClientBase#setAccessTierWithResponse(AccessTier, RehydratePriority, String, Duration, Context)} + */ + public void setTierWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobClient.setTierWithResponse#AccessTier-RehydratePriority-String-Duration-Context + System.out.printf("Set tier completed with status code %d%n", + client.setAccessTierWithResponse(AccessTier.HOT, RehydratePriority.STANDARD, leaseId, timeout, + new Context(key2, value2)).getStatusCode()); + // END: com.azure.storage.blob.BlobClient.setTierWithResponse#AccessTier-RehydratePriority-String-Duration-Context + } + + /** + * Code snippet for {@link BlobClient#undeleteWithResponse(Duration, Context)} + */ + public void undeleteWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobClient.undeleteWithResponse#Duration-Context + System.out.printf("Undelete completed with status %d%n", client.undeleteWithResponse(timeout, + new Context(key1, value1)).getStatusCode()); + // END: com.azure.storage.blob.BlobClient.undeleteWithResponse#Duration-Context + } + + /** + * Code snippet for {@link BlobClient#getAccountInfoWithResponse(Duration, Context)} + */ + public void getAccountInfoWithResponseCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobClient.getAccountInfoWithResponse#Duration-Context + StorageAccountInfo accountInfo = client.getAccountInfoWithResponse(timeout, new Context(key1, value1)).getValue(); + System.out.printf("Account Kind: %s, SKU: %s%n", accountInfo.getAccountKind(), accountInfo.getSkuName()); + // END: com.azure.storage.blob.BlobClient.getAccountInfoWithResponse#Duration-Context + } + + /** + * Generates a code sample for using {@link BlobClient#getContainerName()} + */ + public void getContainerName() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.getContainerName + String containerName = client.getContainerName(); + System.out.println("The name of the container is " + containerName); + // END: com.azure.storage.blob.specialized.BlobClientBase.getContainerName + } + + /** + * Generates a code sample for using {@link BlobClient#getContainerClient()} + */ + public void getContainerClient() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.getContainerClient + BlobContainerClient containerClient = client.getContainerClient(); + System.out.println("The name of the container is " + containerClient.getBlobContainerName()); + // END: com.azure.storage.blob.specialized.BlobClientBase.getContainerClient + } + + /** + * Generates a code sample for using {@link BlobClient#getBlobName()} + */ + public void getBlobName() { + // BEGIN: com.azure.storage.blob.specialized.BlobClientBase.getBlobName + String blobName = client.getBlobName(); + System.out.println("The name of the blob is " + blobName); + // END: com.azure.storage.blob.specialized.BlobClientBase.getBlobName + } + + /** + * Code snippet for {@link BlobClient#uploadFromFile(String)} + * + * @throws IOException If an I/O error occurs + */ + public void uploadFromFile() throws IOException { + // BEGIN: com.azure.storage.blob.BlobClient.uploadFromFile#String + try { + client.uploadFromFile(filePath); + System.out.println("Upload from file succeeded"); + } catch (UncheckedIOException ex) { + System.err.printf("Failed to upload from file %s%n", ex.getMessage()); + } + // END: com.azure.storage.blob.BlobClient.uploadFromFile#String + } + + /** + * Code snippet for {@link BlobClient#uploadFromFile(String, boolean)} + * + * @throws IOException If an I/O error occurs + */ + public void uploadFromFileOverwrite() throws IOException { + // BEGIN: com.azure.storage.blob.BlobClient.uploadFromFile#String-boolean + try { + boolean overwrite = false; + client.uploadFromFile(filePath, overwrite); + System.out.println("Upload from file succeeded"); + } catch (UncheckedIOException ex) { + System.err.printf("Failed to upload from file %s%n", ex.getMessage()); + } + // END: com.azure.storage.blob.BlobClient.uploadFromFile#String-boolean + } + + /** + * Code snippet for {@link BlobClient#uploadFromFile(String, ParallelTransferOptions, BlobHttpHeaders, Map, AccessTier, BlobRequestConditions, Duration)} + * + * @throws IOException If an I/O error occurs + */ + public void uploadFromFile2() throws IOException { + // BEGIN: com.azure.storage.blob.BlobClient.uploadFromFile#String-ParallelTransferOptions-BlobHttpHeaders-Map-AccessTier-BlobRequestConditions-Duration + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5("data".getBytes(StandardCharsets.UTF_8)) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Long blockSize = 100L * 1024L * 1024L; // 100 MB; + ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions().setBlockSizeLong(blockSize); + + try { + client.uploadFromFile(filePath, parallelTransferOptions, headers, metadata, + AccessTier.HOT, requestConditions, timeout); + System.out.println("Upload from file succeeded"); + } catch (UncheckedIOException ex) { + System.err.printf("Failed to upload from file %s%n", ex.getMessage()); + } + // END: com.azure.storage.blob.BlobClient.uploadFromFile#String-ParallelTransferOptions-BlobHttpHeaders-Map-AccessTier-BlobRequestConditions-Duration + } + + /** + * Code snippet for {@link BlobClient#uploadFromFileWithResponse(BlobUploadFromFileOptions, Duration, Context)} + * + * @throws IOException If an I/O error occurs + */ + public void uploadFromFile3() throws IOException { + // BEGIN: com.azure.storage.blob.BlobClient.uploadFromFileWithResponse#BlobUploadFromFileOptions-Duration-Context + BlobHttpHeaders headers = new BlobHttpHeaders() + .setContentMd5("data".getBytes(StandardCharsets.UTF_8)) + .setContentLanguage("en-US") + .setContentType("binary"); + + Map metadata = Collections.singletonMap("metadata", "value"); + Map tags = Collections.singletonMap("tag", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + Long blockSize = 100 * 1024 * 1024L; // 100 MB; + ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions().setBlockSizeLong(blockSize); + + try { + client.uploadFromFileWithResponse(new BlobUploadFromFileOptions(filePath) + .setParallelTransferOptions(parallelTransferOptions).setHeaders(headers).setMetadata(metadata) + .setTags(tags).setTier(AccessTier.HOT).setRequestConditions(requestConditions), timeout, + new Context(key2, value2)); + System.out.println("Upload from file succeeded"); + } catch (UncheckedIOException ex) { + System.err.printf("Failed to upload from file %s%n", ex.getMessage()); + } + // END: com.azure.storage.blob.BlobClient.uploadFromFileWithResponse#BlobUploadFromFileOptions-Duration-Context + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample9/v1/BlobContainerAsyncClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample9/v1/BlobContainerAsyncClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..07fab9945be4 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample9/v1/BlobContainerAsyncClientJavaDocCodeSnippets.java @@ -0,0 +1,516 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.util.Context; +import com.azure.storage.blob.models.BlobAccessPolicy; +import com.azure.storage.blob.models.BlobListDetails; +import com.azure.storage.blob.models.BlobRequestConditions; +import com.azure.storage.blob.models.BlobSignedIdentifier; +import com.azure.storage.blob.models.ListBlobsOptions; +import com.azure.storage.blob.models.PublicAccessType; +import com.azure.storage.blob.models.UserDelegationKey; +import com.azure.storage.blob.options.BlobContainerCreateOptions; +import com.azure.storage.blob.options.FindBlobsOptions; +import com.azure.storage.blob.sas.BlobContainerSasPermission; +import com.azure.storage.blob.sas.BlobServiceSasSignatureValues; + +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +/** + * Code snippets for {@link BlobContainerAsyncClient} + */ +@SuppressWarnings({"unused"}) +public class BlobContainerAsyncClientJavaDocCodeSnippets { + + private BlobContainerAsyncClient client = JavaDocCodeSnippetsHelpers.getContainerAsyncClient(); + private String blobName = "blobName"; + private String snapshot = "snapshot"; + private String leaseId = "leaseId"; + private String proposedId = "proposedId"; + private int leaseDuration = (int) Duration.ofSeconds(30).getSeconds(); + private String accountName = "accountName"; + private UserDelegationKey userDelegationKey = JavaDocCodeSnippetsHelpers.getUserDelegationKey(); + + /** + * Code snippet for {@link BlobContainerAsyncClient#getBlobAsyncClient(String)} + */ + public void getBlobAsyncClient() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.getBlobAsyncClient#String + BlobAsyncClient blobAsyncClient = client.getBlobAsyncClient(blobName); + // END: com.azure.storage.blob.BlobContainerAsyncClient.getBlobAsyncClient#String + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#getBlobAsyncClient(String, String)} + */ + public void getSnapshotBlobAsyncClient() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.getBlobAsyncClient#String-String + BlobAsyncClient blobAsyncClient = client.getBlobAsyncClient(blobName, snapshot); + // END: com.azure.storage.blob.BlobContainerAsyncClient.getBlobAsyncClient#String-String + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#exists()} + */ + public void exists() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.exists + client.exists().subscribe(response -> System.out.printf("Exists? %b%n", response)); + // END: com.azure.storage.blob.BlobContainerAsyncClient.exists + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#existsWithResponse()} + */ + public void existsWithResponse() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.existsWithResponse + client.existsWithResponse().subscribe(response -> System.out.printf("Exists? %b%n", response.getValue())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.existsWithResponse + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#create()} + */ + public void setCreate() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.create + client.create().subscribe( + response -> System.out.printf("Create completed%n"), + error -> System.out.printf("Error while creating container %s%n", error)); + // END: com.azure.storage.blob.BlobContainerAsyncClient.create + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#createWithResponse(Map, PublicAccessType)} + */ + public void create2() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.createWithResponse#Map-PublicAccessType + Map metadata = Collections.singletonMap("metadata", "value"); + client.createWithResponse(metadata, PublicAccessType.CONTAINER).subscribe(response -> + System.out.printf("Create completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.createWithResponse#Map-PublicAccessType + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#delete()} + */ + public void setDelete() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.delete + client.delete().subscribe( + response -> System.out.printf("Delete completed%n"), + error -> System.out.printf("Delete failed: %s%n", error)); + // END: com.azure.storage.blob.BlobContainerAsyncClient.delete + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#deleteWithResponse(BlobRequestConditions)} + */ + public void delete2() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.deleteWithResponse#BlobRequestConditions + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.deleteWithResponse(requestConditions).subscribe(response -> + System.out.printf("Delete completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.deleteWithResponse#BlobRequestConditions + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#getProperties()} + */ + public void getProperties() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.getProperties + client.getProperties().subscribe(response -> + System.out.printf("Public Access Type: %s, Legal Hold? %b, Immutable? %b%n", + response.getBlobPublicAccess(), + response.hasLegalHold(), + response.hasImmutabilityPolicy())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.getProperties + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#getPropertiesWithResponse(String)} + */ + public void getProperties2() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.getPropertiesWithResponse#String + client.getPropertiesWithResponse(leaseId).subscribe(response -> + System.out.printf("Public Access Type: %s, Legal Hold? %b, Immutable? %b%n", + response.getValue().getBlobPublicAccess(), + response.getValue().hasLegalHold(), + response.getValue().hasImmutabilityPolicy())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.getPropertiesWithResponse#String + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#setMetadata(Map)} + */ + public void setMetadata() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.setMetadata#Map + Map metadata = Collections.singletonMap("metadata", "value"); + client.setMetadata(metadata).subscribe( + response -> System.out.printf("Set metadata completed%n"), + error -> System.out.printf("Set metadata failed: %s%n", error)); + // END: com.azure.storage.blob.BlobContainerAsyncClient.setMetadata#Map + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#setMetadataWithResponse(Map, BlobRequestConditions)} + */ + public void setMetadata2() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.setMetadataWithResponse#Map-BlobRequestConditions + Map metadata = Collections.singletonMap("metadata", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.setMetadataWithResponse(metadata, requestConditions).subscribe(response -> + System.out.printf("Set metadata completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.setMetadataWithResponse#Map-BlobRequestConditions + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#getAccessPolicy()} + */ + public void getAccessPolicy() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.getAccessPolicy + client.getAccessPolicy().subscribe(response -> { + System.out.printf("Blob Access Type: %s%n", response.getBlobAccessType()); + + for (BlobSignedIdentifier identifier : response.getIdentifiers()) { + System.out.printf("Identifier Name: %s, Permissions %s%n", + identifier.getId(), + identifier.getAccessPolicy().getPermissions()); + } + }); + // END: com.azure.storage.blob.BlobContainerAsyncClient.getAccessPolicy + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#getAccessPolicyWithResponse(String)} + */ + public void getAccessPolicy2() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.getAccessPolicyWithResponse#String + client.getAccessPolicyWithResponse(leaseId).subscribe(response -> { + System.out.printf("Blob Access Type: %s%n", response.getValue().getBlobAccessType()); + + for (BlobSignedIdentifier identifier : response.getValue().getIdentifiers()) { + System.out.printf("Identifier Name: %s, Permissions %s%n", + identifier.getId(), + identifier.getAccessPolicy().getPermissions()); + } + }); + // END: com.azure.storage.blob.BlobContainerAsyncClient.getAccessPolicyWithResponse#String + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#setAccessPolicy(PublicAccessType, List)} + */ + public void setAccessPolicy() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.setAccessPolicy#PublicAccessType-List + BlobSignedIdentifier identifier = new BlobSignedIdentifier() + .setId("name") + .setAccessPolicy(new BlobAccessPolicy() + .setStartsOn(OffsetDateTime.now()) + .setExpiresOn(OffsetDateTime.now().plusDays(7)) + .setPermissions("permissionString")); + + client.setAccessPolicy(PublicAccessType.CONTAINER, Collections.singletonList(identifier)).subscribe( + response -> System.out.printf("Set access policy completed%n"), + error -> System.out.printf("Set access policy failed: %s%n", error)); + // END: com.azure.storage.blob.BlobContainerAsyncClient.setAccessPolicy#PublicAccessType-List + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#setAccessPolicyWithResponse(PublicAccessType, List, BlobRequestConditions)} + */ + public void setAccessPolicy2() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.setAccessPolicyWithResponse#PublicAccessType-List-BlobRequestConditions + BlobSignedIdentifier identifier = new BlobSignedIdentifier() + .setId("name") + .setAccessPolicy(new BlobAccessPolicy() + .setStartsOn(OffsetDateTime.now()) + .setExpiresOn(OffsetDateTime.now().plusDays(7)) + .setPermissions("permissionString")); + + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.setAccessPolicyWithResponse(PublicAccessType.CONTAINER, Collections.singletonList(identifier), requestConditions) + .subscribe(response -> + System.out.printf("Set access policy completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.setAccessPolicyWithResponse#PublicAccessType-List-BlobRequestConditions + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#listBlobs()} + */ + public void listBlobsFlat() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.listBlobs + client.listBlobs().subscribe(blob -> + System.out.printf("Name: %s, Directory? %b%n", blob.getName(), blob.isPrefix())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.listBlobs + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#listBlobs(ListBlobsOptions)} + */ + public void listBlobsFlat2() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.listBlobs#ListBlobsOptions + ListBlobsOptions options = new ListBlobsOptions() + .setPrefix("prefixToMatch") + .setDetails(new BlobListDetails() + .setRetrieveDeletedBlobs(true) + .setRetrieveSnapshots(true)); + + client.listBlobs(options).subscribe(blob -> + System.out.printf("Name: %s, Directory? %b, Deleted? %b, Snapshot ID: %s%n", + blob.getName(), + blob.isPrefix(), + blob.isDeleted(), + blob.getSnapshot())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.listBlobs#ListBlobsOptions + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#listBlobs(ListBlobsOptions, String)} + */ + public void listBlobsFlat3() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.listBlobs#ListBlobsOptions-String + ListBlobsOptions options = new ListBlobsOptions() + .setPrefix("prefixToMatch") + .setDetails(new BlobListDetails() + .setRetrieveDeletedBlobs(true) + .setRetrieveSnapshots(true)); + + String continuationToken = "continuationToken"; + + client.listBlobs(options, continuationToken).subscribe(blob -> + System.out.printf("Name: %s, Directory? %b, Deleted? %b, Snapshot ID: %s%n", + blob.getName(), + blob.isPrefix(), + blob.isDeleted(), + blob.getSnapshot())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.listBlobs#ListBlobsOptions-String + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#listBlobsByHierarchy(String)} + */ + public void listBlobsHierarchy() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.listBlobsByHierarchy#String + client.listBlobsByHierarchy("directoryName").subscribe(blob -> + System.out.printf("Name: %s, Directory? %b%n", blob.getName(), blob.isDeleted())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.listBlobsByHierarchy#String + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#listBlobsByHierarchy(String, ListBlobsOptions)} + */ + public void listBlobsHierarchy2() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.listBlobsByHierarchy#String-ListBlobsOptions + ListBlobsOptions options = new ListBlobsOptions() + .setPrefix("directoryName") + .setDetails(new BlobListDetails() + .setRetrieveDeletedBlobs(true) + .setRetrieveSnapshots(true)); + + client.listBlobsByHierarchy("/", options).subscribe(blob -> + System.out.printf("Name: %s, Directory? %b, Deleted? %b, Snapshot ID: %s%n", + blob.getName(), + blob.isPrefix(), + blob.isDeleted(), + blob.getSnapshot())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.listBlobsByHierarchy#String-ListBlobsOptions + } + + /** + * Code snippets for {@link BlobContainerAsyncClient#findBlobsByTags(String)} and + * {@link BlobContainerAsyncClient#findBlobsByTags(FindBlobsOptions)} + */ + public void findBlobsByTag() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.findBlobsByTag#String + client.findBlobsByTags("where=tag=value").subscribe(blob -> System.out.printf("Name: %s%n", blob.getName())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.findBlobsByTag#String + + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.findBlobsByTag#FindBlobsOptions + client.findBlobsByTags(new FindBlobsOptions("where=tag=value").setMaxResultsPerPage(10)) + .subscribe(blob -> System.out.printf("Name: %s%n", blob.getName())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.findBlobsByTag#FindBlobsOptions + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#getAccountInfo()} + */ + public void getAccountInfo() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.getAccountInfo + client.getAccountInfo().subscribe(response -> + System.out.printf("Account Kind: %s, SKU: %s%n", + response.getAccountKind(), + response.getSkuName())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.getAccountInfo + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#getAccountInfoWithResponse()} + */ + public void getAccountInfo2() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.getAccountInfoWithResponse + client.getAccountInfoWithResponse().subscribe(response -> + System.out.printf("Account Kind: %s, SKU: %s%n", + response.getValue().getAccountKind(), + response.getValue().getSkuName())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.getAccountInfoWithResponse + } + + /** + * Generates a code sample for using {@link BlobContainerAsyncClient#getBlobContainerName()} + */ + public void getContainerName() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.getBlobContainerName + String containerName = client.getBlobContainerName(); + System.out.println("The name of the blob is " + containerName); + // END: com.azure.storage.blob.BlobContainerAsyncClient.getBlobContainerName + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#generateUserDelegationSas(BlobServiceSasSignatureValues, UserDelegationKey)} + * and {@link BlobContainerAsyncClient#generateSas(BlobServiceSasSignatureValues)} + */ + public void generateSas() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.generateSas#BlobServiceSasSignatureValues + OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1); + BlobContainerSasPermission permission = new BlobContainerSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues values = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + client.generateSas(values); // Client must be authenticated via StorageSharedKeyCredential + // END: com.azure.storage.blob.BlobContainerAsyncClient.generateSas#BlobServiceSasSignatureValues + + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey + OffsetDateTime myExpiryTime = OffsetDateTime.now().plusDays(1); + BlobContainerSasPermission myPermission = new BlobContainerSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues myValues = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + client.generateUserDelegationSas(values, userDelegationKey); + // END: com.azure.storage.blob.BlobContainerAsyncClient.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#generateUserDelegationSas(BlobServiceSasSignatureValues, UserDelegationKey, String, Context)} + * and {@link BlobContainerAsyncClient#generateSas(BlobServiceSasSignatureValues, Context)} + */ + public void generateSasWithContext() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.generateSas#BlobServiceSasSignatureValues-Context + OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1); + BlobContainerSasPermission permission = new BlobContainerSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues values = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + // Client must be authenticated via StorageSharedKeyCredential + client.generateSas(values, new Context("key", "value")); + // END: com.azure.storage.blob.BlobContainerAsyncClient.generateSas#BlobServiceSasSignatureValues-Context + + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey-String-Context + OffsetDateTime myExpiryTime = OffsetDateTime.now().plusDays(1); + BlobContainerSasPermission myPermission = new BlobContainerSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues myValues = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + client.generateUserDelegationSas(values, userDelegationKey, accountName, new Context("key", "value")); + // END: com.azure.storage.blob.BlobContainerAsyncClient.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey-String-Context + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#createIfNotExists()} and + * {@link BlobContainerAsyncClient#createIfNotExistsWithResponse(BlobContainerCreateOptions)} + */ + public void createIfNotExistsCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.createIfNotExists + client.createIfNotExists().subscribe(created -> { + if (created) { + System.out.println("successfully created."); + } else { + System.out.println("Already exists."); + } + }); + // END: com.azure.storage.blob.BlobContainerAsyncClient.createIfNotExists + + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.createIfNotExistsWithResponse#Map-PublicAccessType + Map metadata = Collections.singletonMap("metadata", "value"); + BlobContainerCreateOptions options = new BlobContainerCreateOptions().setMetadata(metadata) + .setPublicAccessType(PublicAccessType.CONTAINER); + + client.createIfNotExistsWithResponse(options).subscribe(response -> { + if (response.getStatusCode() == 409) { + System.out.println("Already exists."); + } else { + System.out.println("successfully created."); + } + }); + // END: com.azure.storage.blob.BlobContainerAsyncClient.createIfNotExistsWithResponse#Map-PublicAccessType + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#deleteIfExists()} and + * {@link BlobContainerAsyncClient#deleteIfExistsWithResponse(BlobRequestConditions)} + */ + public void deleteIfExistsCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.deleteIfExists + client.deleteIfExists().subscribe(deleted -> { + if (deleted) { + System.out.println("Successfully deleted."); + } else { + System.out.println("Does not exist."); + } + }); + // END: com.azure.storage.blob.BlobContainerAsyncClient.deleteIfExists + + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.deleteIfExistsWithResponse#BlobRequestConditions + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.deleteIfExistsWithResponse(requestConditions).subscribe(response -> { + if (response.getStatusCode() == 404) { + System.out.println("Does not exist."); + } else { + System.out.println("successfully deleted."); + } + }); + // END: com.azure.storage.blob.BlobContainerAsyncClient.deleteIfExistsWithResponse#BlobRequestConditions + } + +// /** +// * Code snippet for {@link BlobContainerAsyncClient#rename(String)} +// */ +// public void renameContainer() { +// // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.rename#String +// BlobContainerAsyncClient blobContainerAsyncClient = +// client.rename("newContainerName") +// .block(); +// // END: com.azure.storage.blob.BlobContainerAsyncClient.rename#String +// } +// +// /** +// * Code snippet for {@link BlobContainerAsyncClient#renameWithResponse(BlobContainerRenameOptions)} +// */ +// public void renameContainerWithResponse() { +// // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.renameWithResponse#BlobContainerRenameOptions +// BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId("lease-id"); +// BlobContainerAsyncClient containerClient = +// client.renameWithResponse(new BlobContainerRenameOptions("newContainerName") +// .setRequestConditions(requestConditions)).block().getValue(); +// // END: com.azure.storage.blob.BlobContainerAsyncClient.renameWithResponse#BlobContainerRenameOptions +// } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample9/v2/BlobContainerAsyncClientJavaDocCodeSnippets.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample9/v2/BlobContainerAsyncClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..07fab9945be4 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-blob/sample9/v2/BlobContainerAsyncClientJavaDocCodeSnippets.java @@ -0,0 +1,516 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob; + +import com.azure.core.util.Context; +import com.azure.storage.blob.models.BlobAccessPolicy; +import com.azure.storage.blob.models.BlobListDetails; +import com.azure.storage.blob.models.BlobRequestConditions; +import com.azure.storage.blob.models.BlobSignedIdentifier; +import com.azure.storage.blob.models.ListBlobsOptions; +import com.azure.storage.blob.models.PublicAccessType; +import com.azure.storage.blob.models.UserDelegationKey; +import com.azure.storage.blob.options.BlobContainerCreateOptions; +import com.azure.storage.blob.options.FindBlobsOptions; +import com.azure.storage.blob.sas.BlobContainerSasPermission; +import com.azure.storage.blob.sas.BlobServiceSasSignatureValues; + +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +/** + * Code snippets for {@link BlobContainerAsyncClient} + */ +@SuppressWarnings({"unused"}) +public class BlobContainerAsyncClientJavaDocCodeSnippets { + + private BlobContainerAsyncClient client = JavaDocCodeSnippetsHelpers.getContainerAsyncClient(); + private String blobName = "blobName"; + private String snapshot = "snapshot"; + private String leaseId = "leaseId"; + private String proposedId = "proposedId"; + private int leaseDuration = (int) Duration.ofSeconds(30).getSeconds(); + private String accountName = "accountName"; + private UserDelegationKey userDelegationKey = JavaDocCodeSnippetsHelpers.getUserDelegationKey(); + + /** + * Code snippet for {@link BlobContainerAsyncClient#getBlobAsyncClient(String)} + */ + public void getBlobAsyncClient() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.getBlobAsyncClient#String + BlobAsyncClient blobAsyncClient = client.getBlobAsyncClient(blobName); + // END: com.azure.storage.blob.BlobContainerAsyncClient.getBlobAsyncClient#String + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#getBlobAsyncClient(String, String)} + */ + public void getSnapshotBlobAsyncClient() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.getBlobAsyncClient#String-String + BlobAsyncClient blobAsyncClient = client.getBlobAsyncClient(blobName, snapshot); + // END: com.azure.storage.blob.BlobContainerAsyncClient.getBlobAsyncClient#String-String + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#exists()} + */ + public void exists() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.exists + client.exists().subscribe(response -> System.out.printf("Exists? %b%n", response)); + // END: com.azure.storage.blob.BlobContainerAsyncClient.exists + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#existsWithResponse()} + */ + public void existsWithResponse() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.existsWithResponse + client.existsWithResponse().subscribe(response -> System.out.printf("Exists? %b%n", response.getValue())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.existsWithResponse + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#create()} + */ + public void setCreate() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.create + client.create().subscribe( + response -> System.out.printf("Create completed%n"), + error -> System.out.printf("Error while creating container %s%n", error)); + // END: com.azure.storage.blob.BlobContainerAsyncClient.create + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#createWithResponse(Map, PublicAccessType)} + */ + public void create2() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.createWithResponse#Map-PublicAccessType + Map metadata = Collections.singletonMap("metadata", "value"); + client.createWithResponse(metadata, PublicAccessType.CONTAINER).subscribe(response -> + System.out.printf("Create completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.createWithResponse#Map-PublicAccessType + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#delete()} + */ + public void setDelete() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.delete + client.delete().subscribe( + response -> System.out.printf("Delete completed%n"), + error -> System.out.printf("Delete failed: %s%n", error)); + // END: com.azure.storage.blob.BlobContainerAsyncClient.delete + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#deleteWithResponse(BlobRequestConditions)} + */ + public void delete2() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.deleteWithResponse#BlobRequestConditions + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.deleteWithResponse(requestConditions).subscribe(response -> + System.out.printf("Delete completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.deleteWithResponse#BlobRequestConditions + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#getProperties()} + */ + public void getProperties() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.getProperties + client.getProperties().subscribe(response -> + System.out.printf("Public Access Type: %s, Legal Hold? %b, Immutable? %b%n", + response.getBlobPublicAccess(), + response.hasLegalHold(), + response.hasImmutabilityPolicy())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.getProperties + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#getPropertiesWithResponse(String)} + */ + public void getProperties2() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.getPropertiesWithResponse#String + client.getPropertiesWithResponse(leaseId).subscribe(response -> + System.out.printf("Public Access Type: %s, Legal Hold? %b, Immutable? %b%n", + response.getValue().getBlobPublicAccess(), + response.getValue().hasLegalHold(), + response.getValue().hasImmutabilityPolicy())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.getPropertiesWithResponse#String + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#setMetadata(Map)} + */ + public void setMetadata() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.setMetadata#Map + Map metadata = Collections.singletonMap("metadata", "value"); + client.setMetadata(metadata).subscribe( + response -> System.out.printf("Set metadata completed%n"), + error -> System.out.printf("Set metadata failed: %s%n", error)); + // END: com.azure.storage.blob.BlobContainerAsyncClient.setMetadata#Map + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#setMetadataWithResponse(Map, BlobRequestConditions)} + */ + public void setMetadata2() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.setMetadataWithResponse#Map-BlobRequestConditions + Map metadata = Collections.singletonMap("metadata", "value"); + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.setMetadataWithResponse(metadata, requestConditions).subscribe(response -> + System.out.printf("Set metadata completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.setMetadataWithResponse#Map-BlobRequestConditions + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#getAccessPolicy()} + */ + public void getAccessPolicy() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.getAccessPolicy + client.getAccessPolicy().subscribe(response -> { + System.out.printf("Blob Access Type: %s%n", response.getBlobAccessType()); + + for (BlobSignedIdentifier identifier : response.getIdentifiers()) { + System.out.printf("Identifier Name: %s, Permissions %s%n", + identifier.getId(), + identifier.getAccessPolicy().getPermissions()); + } + }); + // END: com.azure.storage.blob.BlobContainerAsyncClient.getAccessPolicy + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#getAccessPolicyWithResponse(String)} + */ + public void getAccessPolicy2() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.getAccessPolicyWithResponse#String + client.getAccessPolicyWithResponse(leaseId).subscribe(response -> { + System.out.printf("Blob Access Type: %s%n", response.getValue().getBlobAccessType()); + + for (BlobSignedIdentifier identifier : response.getValue().getIdentifiers()) { + System.out.printf("Identifier Name: %s, Permissions %s%n", + identifier.getId(), + identifier.getAccessPolicy().getPermissions()); + } + }); + // END: com.azure.storage.blob.BlobContainerAsyncClient.getAccessPolicyWithResponse#String + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#setAccessPolicy(PublicAccessType, List)} + */ + public void setAccessPolicy() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.setAccessPolicy#PublicAccessType-List + BlobSignedIdentifier identifier = new BlobSignedIdentifier() + .setId("name") + .setAccessPolicy(new BlobAccessPolicy() + .setStartsOn(OffsetDateTime.now()) + .setExpiresOn(OffsetDateTime.now().plusDays(7)) + .setPermissions("permissionString")); + + client.setAccessPolicy(PublicAccessType.CONTAINER, Collections.singletonList(identifier)).subscribe( + response -> System.out.printf("Set access policy completed%n"), + error -> System.out.printf("Set access policy failed: %s%n", error)); + // END: com.azure.storage.blob.BlobContainerAsyncClient.setAccessPolicy#PublicAccessType-List + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#setAccessPolicyWithResponse(PublicAccessType, List, BlobRequestConditions)} + */ + public void setAccessPolicy2() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.setAccessPolicyWithResponse#PublicAccessType-List-BlobRequestConditions + BlobSignedIdentifier identifier = new BlobSignedIdentifier() + .setId("name") + .setAccessPolicy(new BlobAccessPolicy() + .setStartsOn(OffsetDateTime.now()) + .setExpiresOn(OffsetDateTime.now().plusDays(7)) + .setPermissions("permissionString")); + + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.setAccessPolicyWithResponse(PublicAccessType.CONTAINER, Collections.singletonList(identifier), requestConditions) + .subscribe(response -> + System.out.printf("Set access policy completed with status %d%n", response.getStatusCode())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.setAccessPolicyWithResponse#PublicAccessType-List-BlobRequestConditions + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#listBlobs()} + */ + public void listBlobsFlat() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.listBlobs + client.listBlobs().subscribe(blob -> + System.out.printf("Name: %s, Directory? %b%n", blob.getName(), blob.isPrefix())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.listBlobs + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#listBlobs(ListBlobsOptions)} + */ + public void listBlobsFlat2() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.listBlobs#ListBlobsOptions + ListBlobsOptions options = new ListBlobsOptions() + .setPrefix("prefixToMatch") + .setDetails(new BlobListDetails() + .setRetrieveDeletedBlobs(true) + .setRetrieveSnapshots(true)); + + client.listBlobs(options).subscribe(blob -> + System.out.printf("Name: %s, Directory? %b, Deleted? %b, Snapshot ID: %s%n", + blob.getName(), + blob.isPrefix(), + blob.isDeleted(), + blob.getSnapshot())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.listBlobs#ListBlobsOptions + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#listBlobs(ListBlobsOptions, String)} + */ + public void listBlobsFlat3() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.listBlobs#ListBlobsOptions-String + ListBlobsOptions options = new ListBlobsOptions() + .setPrefix("prefixToMatch") + .setDetails(new BlobListDetails() + .setRetrieveDeletedBlobs(true) + .setRetrieveSnapshots(true)); + + String continuationToken = "continuationToken"; + + client.listBlobs(options, continuationToken).subscribe(blob -> + System.out.printf("Name: %s, Directory? %b, Deleted? %b, Snapshot ID: %s%n", + blob.getName(), + blob.isPrefix(), + blob.isDeleted(), + blob.getSnapshot())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.listBlobs#ListBlobsOptions-String + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#listBlobsByHierarchy(String)} + */ + public void listBlobsHierarchy() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.listBlobsByHierarchy#String + client.listBlobsByHierarchy("directoryName").subscribe(blob -> + System.out.printf("Name: %s, Directory? %b%n", blob.getName(), blob.isDeleted())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.listBlobsByHierarchy#String + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#listBlobsByHierarchy(String, ListBlobsOptions)} + */ + public void listBlobsHierarchy2() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.listBlobsByHierarchy#String-ListBlobsOptions + ListBlobsOptions options = new ListBlobsOptions() + .setPrefix("directoryName") + .setDetails(new BlobListDetails() + .setRetrieveDeletedBlobs(true) + .setRetrieveSnapshots(true)); + + client.listBlobsByHierarchy("/", options).subscribe(blob -> + System.out.printf("Name: %s, Directory? %b, Deleted? %b, Snapshot ID: %s%n", + blob.getName(), + blob.isPrefix(), + blob.isDeleted(), + blob.getSnapshot())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.listBlobsByHierarchy#String-ListBlobsOptions + } + + /** + * Code snippets for {@link BlobContainerAsyncClient#findBlobsByTags(String)} and + * {@link BlobContainerAsyncClient#findBlobsByTags(FindBlobsOptions)} + */ + public void findBlobsByTag() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.findBlobsByTag#String + client.findBlobsByTags("where=tag=value").subscribe(blob -> System.out.printf("Name: %s%n", blob.getName())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.findBlobsByTag#String + + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.findBlobsByTag#FindBlobsOptions + client.findBlobsByTags(new FindBlobsOptions("where=tag=value").setMaxResultsPerPage(10)) + .subscribe(blob -> System.out.printf("Name: %s%n", blob.getName())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.findBlobsByTag#FindBlobsOptions + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#getAccountInfo()} + */ + public void getAccountInfo() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.getAccountInfo + client.getAccountInfo().subscribe(response -> + System.out.printf("Account Kind: %s, SKU: %s%n", + response.getAccountKind(), + response.getSkuName())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.getAccountInfo + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#getAccountInfoWithResponse()} + */ + public void getAccountInfo2() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.getAccountInfoWithResponse + client.getAccountInfoWithResponse().subscribe(response -> + System.out.printf("Account Kind: %s, SKU: %s%n", + response.getValue().getAccountKind(), + response.getValue().getSkuName())); + // END: com.azure.storage.blob.BlobContainerAsyncClient.getAccountInfoWithResponse + } + + /** + * Generates a code sample for using {@link BlobContainerAsyncClient#getBlobContainerName()} + */ + public void getContainerName() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.getBlobContainerName + String containerName = client.getBlobContainerName(); + System.out.println("The name of the blob is " + containerName); + // END: com.azure.storage.blob.BlobContainerAsyncClient.getBlobContainerName + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#generateUserDelegationSas(BlobServiceSasSignatureValues, UserDelegationKey)} + * and {@link BlobContainerAsyncClient#generateSas(BlobServiceSasSignatureValues)} + */ + public void generateSas() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.generateSas#BlobServiceSasSignatureValues + OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1); + BlobContainerSasPermission permission = new BlobContainerSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues values = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + client.generateSas(values); // Client must be authenticated via StorageSharedKeyCredential + // END: com.azure.storage.blob.BlobContainerAsyncClient.generateSas#BlobServiceSasSignatureValues + + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey + OffsetDateTime myExpiryTime = OffsetDateTime.now().plusDays(1); + BlobContainerSasPermission myPermission = new BlobContainerSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues myValues = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + client.generateUserDelegationSas(values, userDelegationKey); + // END: com.azure.storage.blob.BlobContainerAsyncClient.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#generateUserDelegationSas(BlobServiceSasSignatureValues, UserDelegationKey, String, Context)} + * and {@link BlobContainerAsyncClient#generateSas(BlobServiceSasSignatureValues, Context)} + */ + public void generateSasWithContext() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.generateSas#BlobServiceSasSignatureValues-Context + OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1); + BlobContainerSasPermission permission = new BlobContainerSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues values = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + // Client must be authenticated via StorageSharedKeyCredential + client.generateSas(values, new Context("key", "value")); + // END: com.azure.storage.blob.BlobContainerAsyncClient.generateSas#BlobServiceSasSignatureValues-Context + + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey-String-Context + OffsetDateTime myExpiryTime = OffsetDateTime.now().plusDays(1); + BlobContainerSasPermission myPermission = new BlobContainerSasPermission().setReadPermission(true); + + BlobServiceSasSignatureValues myValues = new BlobServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + client.generateUserDelegationSas(values, userDelegationKey, accountName, new Context("key", "value")); + // END: com.azure.storage.blob.BlobContainerAsyncClient.generateUserDelegationSas#BlobServiceSasSignatureValues-UserDelegationKey-String-Context + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#createIfNotExists()} and + * {@link BlobContainerAsyncClient#createIfNotExistsWithResponse(BlobContainerCreateOptions)} + */ + public void createIfNotExistsCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.createIfNotExists + client.createIfNotExists().subscribe(created -> { + if (created) { + System.out.println("successfully created."); + } else { + System.out.println("Already exists."); + } + }); + // END: com.azure.storage.blob.BlobContainerAsyncClient.createIfNotExists + + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.createIfNotExistsWithResponse#Map-PublicAccessType + Map metadata = Collections.singletonMap("metadata", "value"); + BlobContainerCreateOptions options = new BlobContainerCreateOptions().setMetadata(metadata) + .setPublicAccessType(PublicAccessType.CONTAINER); + + client.createIfNotExistsWithResponse(options).subscribe(response -> { + if (response.getStatusCode() == 409) { + System.out.println("Already exists."); + } else { + System.out.println("successfully created."); + } + }); + // END: com.azure.storage.blob.BlobContainerAsyncClient.createIfNotExistsWithResponse#Map-PublicAccessType + } + + /** + * Code snippet for {@link BlobContainerAsyncClient#deleteIfExists()} and + * {@link BlobContainerAsyncClient#deleteIfExistsWithResponse(BlobRequestConditions)} + */ + public void deleteIfExistsCodeSnippets() { + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.deleteIfExists + client.deleteIfExists().subscribe(deleted -> { + if (deleted) { + System.out.println("Successfully deleted."); + } else { + System.out.println("Does not exist."); + } + }); + // END: com.azure.storage.blob.BlobContainerAsyncClient.deleteIfExists + + // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.deleteIfExistsWithResponse#BlobRequestConditions + BlobRequestConditions requestConditions = new BlobRequestConditions() + .setLeaseId(leaseId) + .setIfUnmodifiedSince(OffsetDateTime.now().minusDays(3)); + + client.deleteIfExistsWithResponse(requestConditions).subscribe(response -> { + if (response.getStatusCode() == 404) { + System.out.println("Does not exist."); + } else { + System.out.println("successfully deleted."); + } + }); + // END: com.azure.storage.blob.BlobContainerAsyncClient.deleteIfExistsWithResponse#BlobRequestConditions + } + +// /** +// * Code snippet for {@link BlobContainerAsyncClient#rename(String)} +// */ +// public void renameContainer() { +// // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.rename#String +// BlobContainerAsyncClient blobContainerAsyncClient = +// client.rename("newContainerName") +// .block(); +// // END: com.azure.storage.blob.BlobContainerAsyncClient.rename#String +// } +// +// /** +// * Code snippet for {@link BlobContainerAsyncClient#renameWithResponse(BlobContainerRenameOptions)} +// */ +// public void renameContainerWithResponse() { +// // BEGIN: com.azure.storage.blob.BlobContainerAsyncClient.renameWithResponse#BlobContainerRenameOptions +// BlobRequestConditions requestConditions = new BlobRequestConditions().setLeaseId("lease-id"); +// BlobContainerAsyncClient containerClient = +// client.renameWithResponse(new BlobContainerRenameOptions("newContainerName") +// .setRequestConditions(requestConditions)).block().getValue(); +// // END: com.azure.storage.blob.BlobContainerAsyncClient.renameWithResponse#BlobContainerRenameOptions +// } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample1/v1/AsyncSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample1/v1/AsyncSamples.java new file mode 100644 index 000000000000..8cfafab01ed2 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample1/v1/AsyncSamples.java @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.queue; + +/* + * This example mimics some arbitrary number of clients continuously sending messages up to a queue in a parallel and + * a server dequeuing the messages and processing them. + */ +public class AsyncSamples { + private static final String ACCOUNT_NAME = System.getenv("AZURE_STORAGE_ACCOUNT_NAME"); + private static final String SAS_TOKEN = System.getenv("PRIMARY_SAS_TOKEN"); + private static final String QUEUE_NAME = SampleHelper.generateRandomName("async-call", 16); + + /** + * The main method shows how we do the basic operations of enqueueing and dequeueing messages on async queue client. + * @param args No args needed for main method. + */ + public static void main(String[] args) { + // Create an async queue client. + String queueURL = String.format("https://%s.queue.core.windows.net/%s?%s", ACCOUNT_NAME, QUEUE_NAME, SAS_TOKEN); + QueueAsyncClient queueAsyncClient = new QueueClientBuilder().endpoint(queueURL).buildAsyncClient(); + + // Create a queue, enqueue two messages. + queueAsyncClient.create() + .doOnSuccess(response -> queueAsyncClient.sendMessage("This is message 1")) + .then(queueAsyncClient.sendMessage("This is message 2")) + .subscribe( + response -> System.out.println( + "Message successfully equeueed by queueAsyncClient. Message id:" + response.getMessageId()), + err -> System.out.println("Error thrown when enqueue the message. Error message: " + err.getMessage()), + () -> System.out.println("The enqueue has been completed.")); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample1/v2/AsyncSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample1/v2/AsyncSamples.java new file mode 100644 index 000000000000..8cfafab01ed2 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample1/v2/AsyncSamples.java @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.queue; + +/* + * This example mimics some arbitrary number of clients continuously sending messages up to a queue in a parallel and + * a server dequeuing the messages and processing them. + */ +public class AsyncSamples { + private static final String ACCOUNT_NAME = System.getenv("AZURE_STORAGE_ACCOUNT_NAME"); + private static final String SAS_TOKEN = System.getenv("PRIMARY_SAS_TOKEN"); + private static final String QUEUE_NAME = SampleHelper.generateRandomName("async-call", 16); + + /** + * The main method shows how we do the basic operations of enqueueing and dequeueing messages on async queue client. + * @param args No args needed for main method. + */ + public static void main(String[] args) { + // Create an async queue client. + String queueURL = String.format("https://%s.queue.core.windows.net/%s?%s", ACCOUNT_NAME, QUEUE_NAME, SAS_TOKEN); + QueueAsyncClient queueAsyncClient = new QueueClientBuilder().endpoint(queueURL).buildAsyncClient(); + + // Create a queue, enqueue two messages. + queueAsyncClient.create() + .doOnSuccess(response -> queueAsyncClient.sendMessage("This is message 1")) + .then(queueAsyncClient.sendMessage("This is message 2")) + .subscribe( + response -> System.out.println( + "Message successfully equeueed by queueAsyncClient. Message id:" + response.getMessageId()), + err -> System.out.println("Error thrown when enqueue the message. Error message: " + err.getMessage()), + () -> System.out.println("The enqueue has been completed.")); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample10/v1/SampleHelper.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample10/v1/SampleHelper.java new file mode 100644 index 000000000000..297683d788ef --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample10/v1/SampleHelper.java @@ -0,0 +1,13 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.queue; + +import com.azure.core.util.CoreUtils; + +class SampleHelper { + static String generateRandomName(String prefix, int length) { + int len = length > prefix.length() ? length - prefix.length() : 0; + return prefix + CoreUtils.randomUuid().toString().substring(0, len); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample10/v2/SampleHelper.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample10/v2/SampleHelper.java new file mode 100644 index 000000000000..297683d788ef --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample10/v2/SampleHelper.java @@ -0,0 +1,13 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.queue; + +import com.azure.core.util.CoreUtils; + +class SampleHelper { + static String generateRandomName(String prefix, int length) { + int len = length > prefix.length() ? length - prefix.length() : 0; + return prefix + CoreUtils.randomUuid().toString().substring(0, len); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample2/v1/MessageSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample2/v1/MessageSamples.java new file mode 100644 index 000000000000..f168a708c1cb --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample2/v1/MessageSamples.java @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.queue; + +import com.azure.storage.queue.models.QueueMessageItem; +import java.time.Duration; + +public class MessageSamples { + private static final String ACCOUNT_NAME = System.getenv("AZURE_STORAGE_ACCOUNT_NAME"); + private static final String SAS_TOKEN = System.getenv("PRIMARY_SAS_TOKEN"); + + /** + * The main method illustrate the basic operations for enqueue and receive messages using sync client. + * @param args No args needed for main method. + * @throws InterruptedException If the Thread.sleep operation gets interrupted. + */ + public static void main(String[] args) throws InterruptedException { + // Build Queue Client using SAS Token + String queueServiceURL = String.format("https://%s.queue.core.windows.net/?%s", ACCOUNT_NAME, SAS_TOKEN); + QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL).buildClient(); + + // Create a queue client + QueueClient queueClient = queueServiceClient.createQueue(SampleHelper.generateRandomName("enqueue", 15)); + for (int i = 0; i < 3; i++) { + queueClient.sendMessage("Hello World"); + } + + // Enqueue json file into message. + // TODO + + // Get the total count of msg in the queue + int count = queueClient.getProperties().getApproximateMessagesCount(); + + // Peek all messages in queue. It is supposed to print "Hello World" 3 times. + queueClient.peekMessages(count, null, null).forEach( + peekedMessage -> System.out.println("Here is the msg: " + peekedMessage.getBody().toString())); + + // Received all messages in queue and update the message "Hello World" to Hello, world!" + queueClient.receiveMessages(count, Duration.ofSeconds(30), Duration.ofSeconds(50), null).forEach( + queueMessage -> { + String msgToReplace = "Hello, world!"; + queueClient.updateMessage(queueMessage.getMessageId(), queueMessage.getPopReceipt(), + msgToReplace, Duration.ZERO); + } + ); + + // Delete the first available msg. + // Since there is no invisible time for above receive, the following if condition should be true. + QueueMessageItem queueMessageItem = queueClient.receiveMessage(); + if (queueMessageItem != null) { + queueClient.deleteMessage(queueMessageItem.getMessageId(), queueMessageItem.getPopReceipt()); + } else { + System.out.println("OOps, the messages disappear!"); + } + + // Clear all messages in the queue + // Sleep to guarantee we skip the default invisible time. + Thread.sleep(500); + queueClient.clearMessages(); + + // Finally, we delete the queue. + queueClient.delete(); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample2/v2/MessageSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample2/v2/MessageSamples.java new file mode 100644 index 000000000000..f168a708c1cb --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample2/v2/MessageSamples.java @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.queue; + +import com.azure.storage.queue.models.QueueMessageItem; +import java.time.Duration; + +public class MessageSamples { + private static final String ACCOUNT_NAME = System.getenv("AZURE_STORAGE_ACCOUNT_NAME"); + private static final String SAS_TOKEN = System.getenv("PRIMARY_SAS_TOKEN"); + + /** + * The main method illustrate the basic operations for enqueue and receive messages using sync client. + * @param args No args needed for main method. + * @throws InterruptedException If the Thread.sleep operation gets interrupted. + */ + public static void main(String[] args) throws InterruptedException { + // Build Queue Client using SAS Token + String queueServiceURL = String.format("https://%s.queue.core.windows.net/?%s", ACCOUNT_NAME, SAS_TOKEN); + QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL).buildClient(); + + // Create a queue client + QueueClient queueClient = queueServiceClient.createQueue(SampleHelper.generateRandomName("enqueue", 15)); + for (int i = 0; i < 3; i++) { + queueClient.sendMessage("Hello World"); + } + + // Enqueue json file into message. + // TODO + + // Get the total count of msg in the queue + int count = queueClient.getProperties().getApproximateMessagesCount(); + + // Peek all messages in queue. It is supposed to print "Hello World" 3 times. + queueClient.peekMessages(count, null, null).forEach( + peekedMessage -> System.out.println("Here is the msg: " + peekedMessage.getBody().toString())); + + // Received all messages in queue and update the message "Hello World" to Hello, world!" + queueClient.receiveMessages(count, Duration.ofSeconds(30), Duration.ofSeconds(50), null).forEach( + queueMessage -> { + String msgToReplace = "Hello, world!"; + queueClient.updateMessage(queueMessage.getMessageId(), queueMessage.getPopReceipt(), + msgToReplace, Duration.ZERO); + } + ); + + // Delete the first available msg. + // Since there is no invisible time for above receive, the following if condition should be true. + QueueMessageItem queueMessageItem = queueClient.receiveMessage(); + if (queueMessageItem != null) { + queueClient.deleteMessage(queueMessageItem.getMessageId(), queueMessageItem.getPopReceipt()); + } else { + System.out.println("OOps, the messages disappear!"); + } + + // Clear all messages in the queue + // Sleep to guarantee we skip the default invisible time. + Thread.sleep(500); + queueClient.clearMessages(); + + // Finally, we delete the queue. + queueClient.delete(); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample3/v1/QueueAsyncJavaDocCodeSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample3/v1/QueueAsyncJavaDocCodeSamples.java new file mode 100644 index 000000000000..ffb5ca2c2a31 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample3/v1/QueueAsyncJavaDocCodeSamples.java @@ -0,0 +1,630 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.queue; + +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; +import com.azure.storage.common.StorageSharedKeyCredential; +import com.azure.storage.queue.models.QueueAccessPolicy; +import com.azure.storage.queue.models.QueueProperties; +import com.azure.storage.queue.models.QueueSignedIdentifier; +import com.azure.storage.queue.sas.QueueSasPermission; +import com.azure.storage.queue.sas.QueueServiceSasSignatureValues; + +import java.time.Duration; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Collections; +import java.util.Map; + +/** + * Contains code snippets when generating javadocs through doclets for {@link QueueAsyncClient}. + */ + +public class QueueAsyncJavaDocCodeSamples { + + private QueueAsyncClient client = createAsyncClientWithSASToken(); + + /** + * Generates code sample for creating a {@link QueueAsyncClient}. + */ + public void buildQueueAsyncClient() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.instantiation + QueueAsyncClient client = new QueueClientBuilder() + .connectionString("connectionstring") + .endpoint("endpoint") + .buildAsyncClient(); + // END: com.azure.storage.queue.queueAsyncClient.instantiation + } + + /** + * Generates code sample for creating a {@link QueueAsyncClient} with SAS token. + * + * @return An instance of {@link QueueAsyncClient} + */ + public QueueAsyncClient createAsyncClientWithSASToken() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.instantiation.sastoken + QueueAsyncClient queueAsyncClient = new QueueClientBuilder() + .endpoint("https://{accountName}.queue.core.windows.net?{SASToken}") + .buildAsyncClient(); + // END: com.azure.storage.queue.queueAsyncClient.instantiation.sastoken + return queueAsyncClient; + } + + /** + * Generates code sample for creating a {@link QueueAsyncClient} with SAS token. + * + * @return An instance of {@link QueueAsyncClient} + */ + public QueueAsyncClient createAsyncClientWithCredential() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.instantiation.credential + QueueAsyncClient queueAsyncClient = new QueueClientBuilder() + .endpoint("https://{accountName}.queue.core.windows.net") + .queueName("myqueue") + .sasToken("{SASTokenQueryParams}") + .buildAsyncClient(); + // END: com.azure.storage.queue.queueAsyncClient.instantiation.credential + return queueAsyncClient; + } + + /** + * Generates code sample for creating a {@link QueueAsyncClient} with {@code connectionString} which turns into + * {@link StorageSharedKeyCredential} + * + * @return An instance of {@link QueueAsyncClient} + */ + public QueueAsyncClient createAsyncClientWithConnectionString() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.instantiation.connectionstring + String connectionString = "DefaultEndpointsProtocol=https;AccountName={name};" + + "AccountKey={key};EndpointSuffix={core.windows.net}"; + QueueAsyncClient queueAsyncClient = new QueueClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + // END: com.azure.storage.queue.queueAsyncClient.instantiation.connectionstring + return queueAsyncClient; + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#create()} + */ + public void createQueueAsync() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.create + client.create().subscribe( + response -> { + }, + error -> System.err.print(error.toString()), + () -> System.out.println("Complete creating the queue!") + ); + // END: com.azure.storage.queue.queueAsyncClient.create + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#create()} + */ + public void createQueueAsyncMaxOverload() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.create#map + client.create().subscribe( + response -> { + }, + error -> System.err.print(error.toString()), + () -> System.out.println("Complete creating the queue!") + ); + // END: com.azure.storage.queue.queueAsyncClient.create#map + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#createWithResponse(Map)} + */ + public void createWithResponse() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.createWithResponse#map + client.createWithResponse(Collections.singletonMap("queue", "metadataMap")).subscribe( + response -> System.out.println("Complete creating the queue with status code:" + response.getStatusCode()), + error -> System.err.print(error.toString()) + ); + // END: com.azure.storage.queue.queueAsyncClient.createWithResponse#map + } + + + /** + * Generates a code sample for using {@link QueueAsyncClient#sendMessage(String)} + */ + public void enqueueMessageAsync() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.sendMessage#string + client.sendMessage("Hello, Azure").subscribe( + response -> { + }, + error -> System.err.print(error.toString()), + () -> System.out.println("Complete enqueuing the message!") + ); + // END: com.azure.storage.queue.queueAsyncClient.sendMessage#string + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#sendMessage(BinaryData)} + */ + public void enqueueMessageBinaryDataAsync() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.sendMessage#BinaryData + client.sendMessage(BinaryData.fromString("Hello, Azure")).subscribe( + response -> { + }, + error -> System.err.print(error.toString()), + () -> System.out.println("Complete enqueuing the message!") + ); + // END: com.azure.storage.queue.queueAsyncClient.sendMessage#BinaryData + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#sendMessageWithResponse(String, Duration, + * Duration)} + */ + public void enqueueMessageAsyncWithTimeoutOverload() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.sendMessageWithResponse#string-duration-duration + client.sendMessageWithResponse("Hello, Azure", + Duration.ofSeconds(5), null).subscribe( + response -> System.out.printf("Message %s expires at %s", response.getValue().getMessageId(), + response.getValue().getExpirationTime()), + error -> System.err.print(error.toString()), + () -> System.out.println("Complete enqueuing the message!") + ); + // END: com.azure.storage.queue.queueAsyncClient.sendMessageWithResponse#string-duration-duration + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#sendMessageWithResponse(BinaryData, Duration, + * Duration)} + */ + public void enqueueMessageBinaryDataAsyncWithTimeoutOverload() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.sendMessageWithResponse#BinaryData-duration-duration + client.sendMessageWithResponse(BinaryData.fromString("Hello, Azure"), + Duration.ofSeconds(5), null).subscribe( + response -> System.out.printf("Message %s expires at %s", response.getValue().getMessageId(), + response.getValue().getExpirationTime()), + error -> System.err.print(error.toString()), + () -> System.out.println("Complete enqueuing the message!") + ); + // END: com.azure.storage.queue.queueAsyncClient.sendMessageWithResponse#BinaryData-duration-duration + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#sendMessageWithResponse(String, Duration, + * Duration)} + */ + public void enqueueMessageAsyncWithLiveTimeOverload() { + // BEGIN: com.azure.storage.queue.QueueAsyncClient.sendMessageWithResponse-liveTime#String-Duration-Duration + client.sendMessageWithResponse("Goodbye, Azure", + null, Duration.ofSeconds(5)).subscribe( + response -> System.out.printf("Message %s expires at %s", response.getValue().getMessageId(), + response.getValue().getExpirationTime()), + error -> System.err.print(error.toString()), + () -> System.out.println("Complete enqueuing the message!") + ); + // END: com.azure.storage.queue.QueueAsyncClient.sendMessageWithResponse-liveTime#String-Duration-Duration + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#sendMessageWithResponse(BinaryData, Duration, + * Duration)} + */ + public void enqueueMessageBinaryDataAsyncWithLiveTimeOverload() { + // BEGIN: com.azure.storage.queue.QueueAsyncClient.sendMessageWithResponse-liveTime#BinaryData-Duration-Duration + client.sendMessageWithResponse(BinaryData.fromString("Goodbye, Azure"), + null, Duration.ofSeconds(5)).subscribe( + response -> System.out.printf("Message %s expires at %s", response.getValue().getMessageId(), + response.getValue().getExpirationTime()), + error -> System.err.print(error.toString()), + () -> System.out.println("Complete enqueuing the message!") + ); + // END: com.azure.storage.queue.QueueAsyncClient.sendMessageWithResponse-liveTime#BinaryData-Duration-Duration + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#receiveMessage()} + */ + public void getMessageAsync() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.receiveMessage + client.receiveMessage().subscribe( + message -> System.out.println("The message got from getMessages operation: " + + message.getBody().toString()), + error -> System.err.print(error.toString()), + () -> System.out.println("Complete receiving the message!") + ); + // END: com.azure.storage.queue.queueAsyncClient.receiveMessage + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#receiveMessages(Integer)} + */ + public void getMessageAsyncWithOverload() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.receiveMessages#integer + client.receiveMessages(5).subscribe( + message -> System.out.println("The message got from getMessages operation: " + + message.getBody().toString()), + error -> System.err.print(error.toString()), + () -> System.out.println("Complete receiving the message!") + ); + // END: com.azure.storage.queue.queueAsyncClient.receiveMessages#integer + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#receiveMessages(Integer, Duration)} + */ + public void getMessageAsyncMaxOverload() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.receiveMessages#integer-duration + client.receiveMessages(5, Duration.ofSeconds(60)) + .subscribe( + message -> System.out.println("The message got from getMessages operation: " + + message.getBody().toString()), + error -> System.err.print(error.toString()), + () -> System.out.println("Complete receiving the message!") + ); + // END: com.azure.storage.queue.queueAsyncClient.receiveMessages#integer-duration + } + + + /** + * Generates a code sample for using {@link QueueAsyncClient#peekMessage()} + */ + public void peekMessageAsync() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.peekMessage + client.peekMessage().subscribe( + peekMessages -> System.out.println("The message got from peek operation: " + + peekMessages.getBody().toString()), + error -> System.err.print(error.toString()), + () -> System.out.println("Complete peeking the message!") + ); + // END: com.azure.storage.queue.queueAsyncClient.peekMessage + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#peekMessages(Integer)} + */ + public void peekMessageAsyncMaxOverload() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.peekMessages#integer + client.peekMessages(5).subscribe( + peekMessage -> System.out.printf("Peeked message %s has been received %d times", + peekMessage.getMessageId(), peekMessage.getDequeueCount()), + error -> System.err.print(error.toString()), + () -> System.out.println("Complete peeking the message!") + ); + // END: com.azure.storage.queue.queueAsyncClient.peekMessages#integer + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#updateMessage(String, String, String, Duration)} + */ + public void updateMessageAsync() { + // BEGIN: com.azure.storage.queue.QueueAsyncClient.updateMessage#String-String-String-Duration + client.receiveMessage().subscribe( + message -> { + client.updateMessage("newText", message.getMessageId(), + message.getPopReceipt(), null).subscribe( + response -> { + }, + updateError -> System.err.print(updateError.toString()), + () -> System.out.println("Complete updating the message!") + ); + }, + error -> System.err.print(error.toString()), + () -> System.out.println("Complete receiving the message!") + ); + // END: com.azure.storage.queue.QueueAsyncClient.updateMessage#String-String-String-Duration + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#updateMessageWithResponse(String, String, String, + * Duration)} + */ + public void updateMessageWithResponse() { + // BEGIN: com.azure.storage.queue.QueueAsyncClient.updateMessageWithResponse#String-String-String-Duration + + client.receiveMessage().subscribe( + message -> { + client.updateMessageWithResponse(message.getMessageId(), message.getPopReceipt(), "newText", + null).subscribe( + response -> System.out.println("Complete updating the message with status code:" + + response.getStatusCode()), + updateError -> System.err.print(updateError.toString()), + () -> System.out.println("Complete updating the message!") + ); + }, + error -> System.err.print(error.toString()), + () -> System.out.println("Complete receiving the message!") + ); + // END: com.azure.storage.queue.QueueAsyncClient.updateMessageWithResponse#String-String-String-Duration + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#deleteMessage(String, String)} + */ + public void deleteMessageAsync() { + // BEGIN: com.azure.storage.queue.QueueAsyncClient.deleteMessage#String-String + client.receiveMessage().subscribe( + message -> { + client.deleteMessage(message.getMessageId(), message.getPopReceipt()).subscribe( + response -> { + }, + deleteError -> System.err.print(deleteError.toString()), + () -> System.out.println("Complete deleting the message!") + ); + }, + error -> System.err.print(error.toString()), + () -> System.out.println("Complete receiving the message!") + ); + // END: com.azure.storage.queue.QueueAsyncClient.deleteMessage#String-String + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#deleteMessageWithResponse(String, String)} + */ + public void deleteMessageWithResponse() { + // BEGIN: com.azure.storage.queue.QueueAsyncClient.deleteMessageWithResponse#String-String + client.receiveMessage().subscribe( + message -> { + client.deleteMessageWithResponse(message.getMessageId(), message.getPopReceipt()) + .subscribe( + response -> System.out.println("Complete deleting the message with status code: " + + response.getStatusCode()), + deleteError -> System.err.print(deleteError.toString()), + () -> System.out.println("Complete deleting the message!") + ); + }, + error -> System.err.print(error.toString()), + () -> System.out.println("Complete receiving the message!") + ); + // END: com.azure.storage.queue.QueueAsyncClient.deleteMessageWithResponse#String-String + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#delete()} + */ + public void deleteQueueAsync() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.delete + client.delete().doOnSuccess( + response -> System.out.println("Deleting the queue completed.") + ); + // END: com.azure.storage.queue.queueAsyncClient.delete + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#deleteWithResponse()} + */ + public void deleteWithResponse() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.deleteWithResponse + client.deleteWithResponse().subscribe( + response -> System.out.println("Deleting the queue completed with status code: " + response.getStatusCode()) + ); + // END: com.azure.storage.queue.queueAsyncClient.deleteWithResponse + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#getProperties()} + */ + public void getPropertiesAsync() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.getProperties + client.getProperties() + .subscribe(properties -> { + System.out.printf("Metadata: %s, Approximate message count: %d", properties.getMetadata(), + properties.getApproximateMessagesCount()); + }); + // END: com.azure.storage.queue.queueAsyncClient.getProperties + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#getProperties()} + */ + public void getPropertiesWithResponse() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.getPropertiesWithResponse + client.getPropertiesWithResponse() + .subscribe(response -> { + QueueProperties properties = response.getValue(); + System.out.printf("Metadata: %s, Approximate message count: %d", properties.getMetadata(), + properties.getApproximateMessagesCount()); + }); + // END: com.azure.storage.queue.queueAsyncClient.getPropertiesWithResponse + } + + /** + * Generate a code sample for using {@link QueueAsyncClient#setMetadata(Map)} to set metadata. + */ + public void setMetadataAsync() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.setMetadata#map + client.setMetadata(Collections.singletonMap("queue", "metadataMap")) + .subscribe(response -> System.out.println("Setting metadata completed.")); + // END: com.azure.storage.queue.queueAsyncClient.setMetadata#map + } + + /** + * Generate a code sample for using {@link QueueAsyncClient#setMetadataWithResponse(Map)} to set metadata. + */ + public void setMetadataWithResponse() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.setMetadataWithResponse#map + client.setMetadataWithResponse(Collections.singletonMap("queue", "metadataMap")) + .subscribe(response -> System.out.printf("Setting metadata completed with status code %d", + response.getStatusCode())); + // END: com.azure.storage.queue.queueAsyncClient.setMetadataWithResponse#map + } + + /** + * Generate a code sample for using {@link QueueAsyncClient#setMetadata(Map)} to clear metadata. + */ + public void clearMetadataAsync() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.clearMetadata#map + client.setMetadata(null) + .subscribe(response -> System.out.println("Clearing metadata completed.")); + // END: com.azure.storage.queue.queueAsyncClient.clearMetadata#map + } + + /** + * Generate a code sample for using {@link QueueAsyncClient#setMetadata(Map)} to clear metadata. + */ + public void clearMetadataWithResponse() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.clearMetadataWithResponse#map + client.setMetadataWithResponse(null) + .subscribe(response -> System.out.printf("Clearing metadata completed with status code %d", + response.getStatusCode())); + // END: com.azure.storage.queue.queueAsyncClient.clearMetadataWithResponse#map + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#getAccessPolicy()} + */ + public void getAccessPolicyAsync() { + + // BEGIN: com.azure.storage.queue.queueAsyncClient.getAccessPolicy + client.getAccessPolicy() + .subscribe(result -> System.out.printf("Access policy %s allows these permissions: %s", + result.getId(), result.getAccessPolicy().getPermissions())); + // END: com.azure.storage.queue.queueAsyncClient.getAccessPolicy + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#setAccessPolicyWithResponse(Iterable)} + */ + public void setAccessPolicyWithResponse() { + QueueAsyncClient queueAsyncClient = createAsyncClientWithSASToken(); + // BEGIN: com.azure.storage.queue.QueueAsyncClient.setAccessPolicyWithResponse#Iterable + QueueAccessPolicy accessPolicy = new QueueAccessPolicy().setPermissions("r") + .setStartsOn(OffsetDateTime.now(ZoneOffset.UTC)) + .setExpiresOn(OffsetDateTime.now(ZoneOffset.UTC).plusDays(10)); + + QueueSignedIdentifier permission = new QueueSignedIdentifier().setId("mypolicy").setAccessPolicy(accessPolicy); + client.setAccessPolicyWithResponse(Collections.singletonList(permission)) + .subscribe(response -> System.out.printf("Setting access policies completed with status code %d", + response.getStatusCode())); + // END: com.azure.storage.queue.QueueAsyncClient.setAccessPolicyWithResponse#Iterable + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#setAccessPolicy(Iterable)} + */ + public void setAccessPolicyAsync() { + QueueAsyncClient queueAsyncClient = createAsyncClientWithSASToken(); + // BEGIN: com.azure.storage.queue.QueueAsyncClient.setAccessPolicy#Iterable + QueueAccessPolicy accessPolicy = new QueueAccessPolicy().setPermissions("r") + .setStartsOn(OffsetDateTime.now(ZoneOffset.UTC)) + .setExpiresOn(OffsetDateTime.now(ZoneOffset.UTC).plusDays(10)); + + QueueSignedIdentifier permission = new QueueSignedIdentifier().setId("mypolicy").setAccessPolicy(accessPolicy); + client.setAccessPolicy(Collections.singletonList(permission)) + .subscribe(response -> System.out.println("Setting access policies completed.")); + // END: com.azure.storage.queue.QueueAsyncClient.setAccessPolicy#Iterable + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#clearMessagesWithResponse()} + */ + public void clearMessagesWithResponse() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.clearMessagesWithResponse + client.clearMessagesWithResponse().doOnSuccess( + response -> System.out.println("Clearing messages completed with status code: " + response.getStatusCode()) + ); + // END: com.azure.storage.queue.queueAsyncClient.clearMessagesWithResponse + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#clearMessages()} + */ + public void clearMessagesAsync() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.clearMessages + client.clearMessages().subscribe( + response -> System.out.println("Clearing messages completed.")); + // END: com.azure.storage.queue.queueAsyncClient.clearMessages + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#getQueueName()} + */ + public void getNameAsync() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.getQueueName + String queueName = client.getQueueName(); + System.out.println("The name of the queue is " + queueName); + // END: com.azure.storage.queue.queueAsyncClient.getQueueName + } + + /** + * Code snippet for {@link QueueAsyncClient#generateSas(QueueServiceSasSignatureValues)} + */ + public void generateSas() { + // BEGIN: com.azure.storage.queue.QueueAsyncClient.generateSas#QueueServiceSasSignatureValues + OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1); + QueueSasPermission permission = new QueueSasPermission().setReadPermission(true); + + QueueServiceSasSignatureValues values = new QueueServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + client.generateSas(values); // Client must be authenticated via StorageSharedKeyCredential + // END: com.azure.storage.queue.QueueAsyncClient.generateSas#QueueServiceSasSignatureValues + } + + + /** + * Code snippet for {@link QueueAsyncClient#generateSas(QueueServiceSasSignatureValues, Context)} + */ + public void generateSasWithContext() { + // BEGIN: com.azure.storage.queue.QueueAsyncClient.generateSas#QueueServiceSasSignatureValues-Context + OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1); + QueueSasPermission permission = new QueueSasPermission().setReadPermission(true); + + QueueServiceSasSignatureValues values = new QueueServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + // Client must be authenticated via StorageSharedKeyCredential + client.generateSas(values, new Context("key", "value")); + // END: com.azure.storage.queue.QueueAsyncClient.generateSas#QueueServiceSasSignatureValues-Context + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#createIfNotExists()} and + * {@link QueueAsyncClient#createIfNotExistsWithResponse(Map)} + */ + public void createIfNotExistsQueueAsyncCodeSnippets() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.createIfNotExists + client.createIfNotExists().subscribe(created -> { + if (created) { + System.out.println("Successfully created."); + } else { + System.out.println("Already exists."); + } + }); + // END: com.azure.storage.queue.queueAsyncClient.createIfNotExists + + // BEGIN: com.azure.storage.queue.queueAsyncClient.createIfNotExistsWithResponse#map + client.createIfNotExistsWithResponse(Collections.singletonMap("queue", "metadataMap")) + .subscribe(response -> { + if (response.getStatusCode() == 409) { + System.out.println("Already exists."); + } else { + System.out.println("successfully created."); + } + }); + // END: com.azure.storage.queue.queueAsyncClient.createIfNotExistsWithResponse#map + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#deleteIfExists()} and + * {@link QueueAsyncClient#deleteIfExistsWithResponse()} + */ + public void deleteQueueIfExistsAsyncCodeSippets() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.deleteIfExists + client.deleteIfExists().subscribe(deleted -> { + if (deleted) { + System.out.println("Successfully deleted."); + } else { + System.out.println("Does not exist."); + } + }); + // END: com.azure.storage.queue.queueAsyncClient.deleteIfExists + + // BEGIN: com.azure.storage.queue.queueAsyncClient.deleteIfExistsWithResponse + client.deleteIfExistsWithResponse().subscribe(response -> { + if (response.getStatusCode() == 404) { + System.out.println("Does not exist."); + } else { + System.out.println("successfully deleted."); + } + }); + // END: com.azure.storage.queue.queueAsyncClient.deleteIfExistsWithResponse + } + +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample3/v2/QueueAsyncJavaDocCodeSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample3/v2/QueueAsyncJavaDocCodeSamples.java new file mode 100644 index 000000000000..ffb5ca2c2a31 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample3/v2/QueueAsyncJavaDocCodeSamples.java @@ -0,0 +1,630 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.queue; + +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; +import com.azure.storage.common.StorageSharedKeyCredential; +import com.azure.storage.queue.models.QueueAccessPolicy; +import com.azure.storage.queue.models.QueueProperties; +import com.azure.storage.queue.models.QueueSignedIdentifier; +import com.azure.storage.queue.sas.QueueSasPermission; +import com.azure.storage.queue.sas.QueueServiceSasSignatureValues; + +import java.time.Duration; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Collections; +import java.util.Map; + +/** + * Contains code snippets when generating javadocs through doclets for {@link QueueAsyncClient}. + */ + +public class QueueAsyncJavaDocCodeSamples { + + private QueueAsyncClient client = createAsyncClientWithSASToken(); + + /** + * Generates code sample for creating a {@link QueueAsyncClient}. + */ + public void buildQueueAsyncClient() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.instantiation + QueueAsyncClient client = new QueueClientBuilder() + .connectionString("connectionstring") + .endpoint("endpoint") + .buildAsyncClient(); + // END: com.azure.storage.queue.queueAsyncClient.instantiation + } + + /** + * Generates code sample for creating a {@link QueueAsyncClient} with SAS token. + * + * @return An instance of {@link QueueAsyncClient} + */ + public QueueAsyncClient createAsyncClientWithSASToken() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.instantiation.sastoken + QueueAsyncClient queueAsyncClient = new QueueClientBuilder() + .endpoint("https://{accountName}.queue.core.windows.net?{SASToken}") + .buildAsyncClient(); + // END: com.azure.storage.queue.queueAsyncClient.instantiation.sastoken + return queueAsyncClient; + } + + /** + * Generates code sample for creating a {@link QueueAsyncClient} with SAS token. + * + * @return An instance of {@link QueueAsyncClient} + */ + public QueueAsyncClient createAsyncClientWithCredential() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.instantiation.credential + QueueAsyncClient queueAsyncClient = new QueueClientBuilder() + .endpoint("https://{accountName}.queue.core.windows.net") + .queueName("myqueue") + .sasToken("{SASTokenQueryParams}") + .buildAsyncClient(); + // END: com.azure.storage.queue.queueAsyncClient.instantiation.credential + return queueAsyncClient; + } + + /** + * Generates code sample for creating a {@link QueueAsyncClient} with {@code connectionString} which turns into + * {@link StorageSharedKeyCredential} + * + * @return An instance of {@link QueueAsyncClient} + */ + public QueueAsyncClient createAsyncClientWithConnectionString() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.instantiation.connectionstring + String connectionString = "DefaultEndpointsProtocol=https;AccountName={name};" + + "AccountKey={key};EndpointSuffix={core.windows.net}"; + QueueAsyncClient queueAsyncClient = new QueueClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + // END: com.azure.storage.queue.queueAsyncClient.instantiation.connectionstring + return queueAsyncClient; + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#create()} + */ + public void createQueueAsync() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.create + client.create().subscribe( + response -> { + }, + error -> System.err.print(error.toString()), + () -> System.out.println("Complete creating the queue!") + ); + // END: com.azure.storage.queue.queueAsyncClient.create + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#create()} + */ + public void createQueueAsyncMaxOverload() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.create#map + client.create().subscribe( + response -> { + }, + error -> System.err.print(error.toString()), + () -> System.out.println("Complete creating the queue!") + ); + // END: com.azure.storage.queue.queueAsyncClient.create#map + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#createWithResponse(Map)} + */ + public void createWithResponse() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.createWithResponse#map + client.createWithResponse(Collections.singletonMap("queue", "metadataMap")).subscribe( + response -> System.out.println("Complete creating the queue with status code:" + response.getStatusCode()), + error -> System.err.print(error.toString()) + ); + // END: com.azure.storage.queue.queueAsyncClient.createWithResponse#map + } + + + /** + * Generates a code sample for using {@link QueueAsyncClient#sendMessage(String)} + */ + public void enqueueMessageAsync() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.sendMessage#string + client.sendMessage("Hello, Azure").subscribe( + response -> { + }, + error -> System.err.print(error.toString()), + () -> System.out.println("Complete enqueuing the message!") + ); + // END: com.azure.storage.queue.queueAsyncClient.sendMessage#string + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#sendMessage(BinaryData)} + */ + public void enqueueMessageBinaryDataAsync() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.sendMessage#BinaryData + client.sendMessage(BinaryData.fromString("Hello, Azure")).subscribe( + response -> { + }, + error -> System.err.print(error.toString()), + () -> System.out.println("Complete enqueuing the message!") + ); + // END: com.azure.storage.queue.queueAsyncClient.sendMessage#BinaryData + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#sendMessageWithResponse(String, Duration, + * Duration)} + */ + public void enqueueMessageAsyncWithTimeoutOverload() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.sendMessageWithResponse#string-duration-duration + client.sendMessageWithResponse("Hello, Azure", + Duration.ofSeconds(5), null).subscribe( + response -> System.out.printf("Message %s expires at %s", response.getValue().getMessageId(), + response.getValue().getExpirationTime()), + error -> System.err.print(error.toString()), + () -> System.out.println("Complete enqueuing the message!") + ); + // END: com.azure.storage.queue.queueAsyncClient.sendMessageWithResponse#string-duration-duration + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#sendMessageWithResponse(BinaryData, Duration, + * Duration)} + */ + public void enqueueMessageBinaryDataAsyncWithTimeoutOverload() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.sendMessageWithResponse#BinaryData-duration-duration + client.sendMessageWithResponse(BinaryData.fromString("Hello, Azure"), + Duration.ofSeconds(5), null).subscribe( + response -> System.out.printf("Message %s expires at %s", response.getValue().getMessageId(), + response.getValue().getExpirationTime()), + error -> System.err.print(error.toString()), + () -> System.out.println("Complete enqueuing the message!") + ); + // END: com.azure.storage.queue.queueAsyncClient.sendMessageWithResponse#BinaryData-duration-duration + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#sendMessageWithResponse(String, Duration, + * Duration)} + */ + public void enqueueMessageAsyncWithLiveTimeOverload() { + // BEGIN: com.azure.storage.queue.QueueAsyncClient.sendMessageWithResponse-liveTime#String-Duration-Duration + client.sendMessageWithResponse("Goodbye, Azure", + null, Duration.ofSeconds(5)).subscribe( + response -> System.out.printf("Message %s expires at %s", response.getValue().getMessageId(), + response.getValue().getExpirationTime()), + error -> System.err.print(error.toString()), + () -> System.out.println("Complete enqueuing the message!") + ); + // END: com.azure.storage.queue.QueueAsyncClient.sendMessageWithResponse-liveTime#String-Duration-Duration + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#sendMessageWithResponse(BinaryData, Duration, + * Duration)} + */ + public void enqueueMessageBinaryDataAsyncWithLiveTimeOverload() { + // BEGIN: com.azure.storage.queue.QueueAsyncClient.sendMessageWithResponse-liveTime#BinaryData-Duration-Duration + client.sendMessageWithResponse(BinaryData.fromString("Goodbye, Azure"), + null, Duration.ofSeconds(5)).subscribe( + response -> System.out.printf("Message %s expires at %s", response.getValue().getMessageId(), + response.getValue().getExpirationTime()), + error -> System.err.print(error.toString()), + () -> System.out.println("Complete enqueuing the message!") + ); + // END: com.azure.storage.queue.QueueAsyncClient.sendMessageWithResponse-liveTime#BinaryData-Duration-Duration + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#receiveMessage()} + */ + public void getMessageAsync() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.receiveMessage + client.receiveMessage().subscribe( + message -> System.out.println("The message got from getMessages operation: " + + message.getBody().toString()), + error -> System.err.print(error.toString()), + () -> System.out.println("Complete receiving the message!") + ); + // END: com.azure.storage.queue.queueAsyncClient.receiveMessage + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#receiveMessages(Integer)} + */ + public void getMessageAsyncWithOverload() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.receiveMessages#integer + client.receiveMessages(5).subscribe( + message -> System.out.println("The message got from getMessages operation: " + + message.getBody().toString()), + error -> System.err.print(error.toString()), + () -> System.out.println("Complete receiving the message!") + ); + // END: com.azure.storage.queue.queueAsyncClient.receiveMessages#integer + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#receiveMessages(Integer, Duration)} + */ + public void getMessageAsyncMaxOverload() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.receiveMessages#integer-duration + client.receiveMessages(5, Duration.ofSeconds(60)) + .subscribe( + message -> System.out.println("The message got from getMessages operation: " + + message.getBody().toString()), + error -> System.err.print(error.toString()), + () -> System.out.println("Complete receiving the message!") + ); + // END: com.azure.storage.queue.queueAsyncClient.receiveMessages#integer-duration + } + + + /** + * Generates a code sample for using {@link QueueAsyncClient#peekMessage()} + */ + public void peekMessageAsync() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.peekMessage + client.peekMessage().subscribe( + peekMessages -> System.out.println("The message got from peek operation: " + + peekMessages.getBody().toString()), + error -> System.err.print(error.toString()), + () -> System.out.println("Complete peeking the message!") + ); + // END: com.azure.storage.queue.queueAsyncClient.peekMessage + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#peekMessages(Integer)} + */ + public void peekMessageAsyncMaxOverload() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.peekMessages#integer + client.peekMessages(5).subscribe( + peekMessage -> System.out.printf("Peeked message %s has been received %d times", + peekMessage.getMessageId(), peekMessage.getDequeueCount()), + error -> System.err.print(error.toString()), + () -> System.out.println("Complete peeking the message!") + ); + // END: com.azure.storage.queue.queueAsyncClient.peekMessages#integer + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#updateMessage(String, String, String, Duration)} + */ + public void updateMessageAsync() { + // BEGIN: com.azure.storage.queue.QueueAsyncClient.updateMessage#String-String-String-Duration + client.receiveMessage().subscribe( + message -> { + client.updateMessage("newText", message.getMessageId(), + message.getPopReceipt(), null).subscribe( + response -> { + }, + updateError -> System.err.print(updateError.toString()), + () -> System.out.println("Complete updating the message!") + ); + }, + error -> System.err.print(error.toString()), + () -> System.out.println("Complete receiving the message!") + ); + // END: com.azure.storage.queue.QueueAsyncClient.updateMessage#String-String-String-Duration + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#updateMessageWithResponse(String, String, String, + * Duration)} + */ + public void updateMessageWithResponse() { + // BEGIN: com.azure.storage.queue.QueueAsyncClient.updateMessageWithResponse#String-String-String-Duration + + client.receiveMessage().subscribe( + message -> { + client.updateMessageWithResponse(message.getMessageId(), message.getPopReceipt(), "newText", + null).subscribe( + response -> System.out.println("Complete updating the message with status code:" + + response.getStatusCode()), + updateError -> System.err.print(updateError.toString()), + () -> System.out.println("Complete updating the message!") + ); + }, + error -> System.err.print(error.toString()), + () -> System.out.println("Complete receiving the message!") + ); + // END: com.azure.storage.queue.QueueAsyncClient.updateMessageWithResponse#String-String-String-Duration + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#deleteMessage(String, String)} + */ + public void deleteMessageAsync() { + // BEGIN: com.azure.storage.queue.QueueAsyncClient.deleteMessage#String-String + client.receiveMessage().subscribe( + message -> { + client.deleteMessage(message.getMessageId(), message.getPopReceipt()).subscribe( + response -> { + }, + deleteError -> System.err.print(deleteError.toString()), + () -> System.out.println("Complete deleting the message!") + ); + }, + error -> System.err.print(error.toString()), + () -> System.out.println("Complete receiving the message!") + ); + // END: com.azure.storage.queue.QueueAsyncClient.deleteMessage#String-String + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#deleteMessageWithResponse(String, String)} + */ + public void deleteMessageWithResponse() { + // BEGIN: com.azure.storage.queue.QueueAsyncClient.deleteMessageWithResponse#String-String + client.receiveMessage().subscribe( + message -> { + client.deleteMessageWithResponse(message.getMessageId(), message.getPopReceipt()) + .subscribe( + response -> System.out.println("Complete deleting the message with status code: " + + response.getStatusCode()), + deleteError -> System.err.print(deleteError.toString()), + () -> System.out.println("Complete deleting the message!") + ); + }, + error -> System.err.print(error.toString()), + () -> System.out.println("Complete receiving the message!") + ); + // END: com.azure.storage.queue.QueueAsyncClient.deleteMessageWithResponse#String-String + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#delete()} + */ + public void deleteQueueAsync() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.delete + client.delete().doOnSuccess( + response -> System.out.println("Deleting the queue completed.") + ); + // END: com.azure.storage.queue.queueAsyncClient.delete + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#deleteWithResponse()} + */ + public void deleteWithResponse() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.deleteWithResponse + client.deleteWithResponse().subscribe( + response -> System.out.println("Deleting the queue completed with status code: " + response.getStatusCode()) + ); + // END: com.azure.storage.queue.queueAsyncClient.deleteWithResponse + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#getProperties()} + */ + public void getPropertiesAsync() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.getProperties + client.getProperties() + .subscribe(properties -> { + System.out.printf("Metadata: %s, Approximate message count: %d", properties.getMetadata(), + properties.getApproximateMessagesCount()); + }); + // END: com.azure.storage.queue.queueAsyncClient.getProperties + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#getProperties()} + */ + public void getPropertiesWithResponse() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.getPropertiesWithResponse + client.getPropertiesWithResponse() + .subscribe(response -> { + QueueProperties properties = response.getValue(); + System.out.printf("Metadata: %s, Approximate message count: %d", properties.getMetadata(), + properties.getApproximateMessagesCount()); + }); + // END: com.azure.storage.queue.queueAsyncClient.getPropertiesWithResponse + } + + /** + * Generate a code sample for using {@link QueueAsyncClient#setMetadata(Map)} to set metadata. + */ + public void setMetadataAsync() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.setMetadata#map + client.setMetadata(Collections.singletonMap("queue", "metadataMap")) + .subscribe(response -> System.out.println("Setting metadata completed.")); + // END: com.azure.storage.queue.queueAsyncClient.setMetadata#map + } + + /** + * Generate a code sample for using {@link QueueAsyncClient#setMetadataWithResponse(Map)} to set metadata. + */ + public void setMetadataWithResponse() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.setMetadataWithResponse#map + client.setMetadataWithResponse(Collections.singletonMap("queue", "metadataMap")) + .subscribe(response -> System.out.printf("Setting metadata completed with status code %d", + response.getStatusCode())); + // END: com.azure.storage.queue.queueAsyncClient.setMetadataWithResponse#map + } + + /** + * Generate a code sample for using {@link QueueAsyncClient#setMetadata(Map)} to clear metadata. + */ + public void clearMetadataAsync() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.clearMetadata#map + client.setMetadata(null) + .subscribe(response -> System.out.println("Clearing metadata completed.")); + // END: com.azure.storage.queue.queueAsyncClient.clearMetadata#map + } + + /** + * Generate a code sample for using {@link QueueAsyncClient#setMetadata(Map)} to clear metadata. + */ + public void clearMetadataWithResponse() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.clearMetadataWithResponse#map + client.setMetadataWithResponse(null) + .subscribe(response -> System.out.printf("Clearing metadata completed with status code %d", + response.getStatusCode())); + // END: com.azure.storage.queue.queueAsyncClient.clearMetadataWithResponse#map + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#getAccessPolicy()} + */ + public void getAccessPolicyAsync() { + + // BEGIN: com.azure.storage.queue.queueAsyncClient.getAccessPolicy + client.getAccessPolicy() + .subscribe(result -> System.out.printf("Access policy %s allows these permissions: %s", + result.getId(), result.getAccessPolicy().getPermissions())); + // END: com.azure.storage.queue.queueAsyncClient.getAccessPolicy + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#setAccessPolicyWithResponse(Iterable)} + */ + public void setAccessPolicyWithResponse() { + QueueAsyncClient queueAsyncClient = createAsyncClientWithSASToken(); + // BEGIN: com.azure.storage.queue.QueueAsyncClient.setAccessPolicyWithResponse#Iterable + QueueAccessPolicy accessPolicy = new QueueAccessPolicy().setPermissions("r") + .setStartsOn(OffsetDateTime.now(ZoneOffset.UTC)) + .setExpiresOn(OffsetDateTime.now(ZoneOffset.UTC).plusDays(10)); + + QueueSignedIdentifier permission = new QueueSignedIdentifier().setId("mypolicy").setAccessPolicy(accessPolicy); + client.setAccessPolicyWithResponse(Collections.singletonList(permission)) + .subscribe(response -> System.out.printf("Setting access policies completed with status code %d", + response.getStatusCode())); + // END: com.azure.storage.queue.QueueAsyncClient.setAccessPolicyWithResponse#Iterable + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#setAccessPolicy(Iterable)} + */ + public void setAccessPolicyAsync() { + QueueAsyncClient queueAsyncClient = createAsyncClientWithSASToken(); + // BEGIN: com.azure.storage.queue.QueueAsyncClient.setAccessPolicy#Iterable + QueueAccessPolicy accessPolicy = new QueueAccessPolicy().setPermissions("r") + .setStartsOn(OffsetDateTime.now(ZoneOffset.UTC)) + .setExpiresOn(OffsetDateTime.now(ZoneOffset.UTC).plusDays(10)); + + QueueSignedIdentifier permission = new QueueSignedIdentifier().setId("mypolicy").setAccessPolicy(accessPolicy); + client.setAccessPolicy(Collections.singletonList(permission)) + .subscribe(response -> System.out.println("Setting access policies completed.")); + // END: com.azure.storage.queue.QueueAsyncClient.setAccessPolicy#Iterable + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#clearMessagesWithResponse()} + */ + public void clearMessagesWithResponse() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.clearMessagesWithResponse + client.clearMessagesWithResponse().doOnSuccess( + response -> System.out.println("Clearing messages completed with status code: " + response.getStatusCode()) + ); + // END: com.azure.storage.queue.queueAsyncClient.clearMessagesWithResponse + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#clearMessages()} + */ + public void clearMessagesAsync() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.clearMessages + client.clearMessages().subscribe( + response -> System.out.println("Clearing messages completed.")); + // END: com.azure.storage.queue.queueAsyncClient.clearMessages + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#getQueueName()} + */ + public void getNameAsync() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.getQueueName + String queueName = client.getQueueName(); + System.out.println("The name of the queue is " + queueName); + // END: com.azure.storage.queue.queueAsyncClient.getQueueName + } + + /** + * Code snippet for {@link QueueAsyncClient#generateSas(QueueServiceSasSignatureValues)} + */ + public void generateSas() { + // BEGIN: com.azure.storage.queue.QueueAsyncClient.generateSas#QueueServiceSasSignatureValues + OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1); + QueueSasPermission permission = new QueueSasPermission().setReadPermission(true); + + QueueServiceSasSignatureValues values = new QueueServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + client.generateSas(values); // Client must be authenticated via StorageSharedKeyCredential + // END: com.azure.storage.queue.QueueAsyncClient.generateSas#QueueServiceSasSignatureValues + } + + + /** + * Code snippet for {@link QueueAsyncClient#generateSas(QueueServiceSasSignatureValues, Context)} + */ + public void generateSasWithContext() { + // BEGIN: com.azure.storage.queue.QueueAsyncClient.generateSas#QueueServiceSasSignatureValues-Context + OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1); + QueueSasPermission permission = new QueueSasPermission().setReadPermission(true); + + QueueServiceSasSignatureValues values = new QueueServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + // Client must be authenticated via StorageSharedKeyCredential + client.generateSas(values, new Context("key", "value")); + // END: com.azure.storage.queue.QueueAsyncClient.generateSas#QueueServiceSasSignatureValues-Context + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#createIfNotExists()} and + * {@link QueueAsyncClient#createIfNotExistsWithResponse(Map)} + */ + public void createIfNotExistsQueueAsyncCodeSnippets() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.createIfNotExists + client.createIfNotExists().subscribe(created -> { + if (created) { + System.out.println("Successfully created."); + } else { + System.out.println("Already exists."); + } + }); + // END: com.azure.storage.queue.queueAsyncClient.createIfNotExists + + // BEGIN: com.azure.storage.queue.queueAsyncClient.createIfNotExistsWithResponse#map + client.createIfNotExistsWithResponse(Collections.singletonMap("queue", "metadataMap")) + .subscribe(response -> { + if (response.getStatusCode() == 409) { + System.out.println("Already exists."); + } else { + System.out.println("successfully created."); + } + }); + // END: com.azure.storage.queue.queueAsyncClient.createIfNotExistsWithResponse#map + } + + /** + * Generates a code sample for using {@link QueueAsyncClient#deleteIfExists()} and + * {@link QueueAsyncClient#deleteIfExistsWithResponse()} + */ + public void deleteQueueIfExistsAsyncCodeSippets() { + // BEGIN: com.azure.storage.queue.queueAsyncClient.deleteIfExists + client.deleteIfExists().subscribe(deleted -> { + if (deleted) { + System.out.println("Successfully deleted."); + } else { + System.out.println("Does not exist."); + } + }); + // END: com.azure.storage.queue.queueAsyncClient.deleteIfExists + + // BEGIN: com.azure.storage.queue.queueAsyncClient.deleteIfExistsWithResponse + client.deleteIfExistsWithResponse().subscribe(response -> { + if (response.getStatusCode() == 404) { + System.out.println("Does not exist."); + } else { + System.out.println("successfully deleted."); + } + }); + // END: com.azure.storage.queue.queueAsyncClient.deleteIfExistsWithResponse + } + +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample4/v1/QueueExceptionSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample4/v1/QueueExceptionSamples.java new file mode 100644 index 000000000000..29597d08c71c --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample4/v1/QueueExceptionSamples.java @@ -0,0 +1,68 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.queue; + +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.storage.queue.models.QueueErrorCode; +import com.azure.storage.queue.models.QueueMessageItem; +import com.azure.storage.queue.models.QueueStorageException; + +import java.time.Duration; + +public class QueueExceptionSamples { + + private static final String ACCOUNT_NAME = System.getenv("AZURE_STORAGE_ACCOUNT_NAME"); + private static final String SAS_TOKEN = System.getenv("PRIMARY_SAS_TOKEN"); + + /** + * The main method shows how to handle the storage exception. + * + * @param args No args needed for the main method. + * @throws RuntimeException If queueServiceClient failed to create a queue. + */ + public static void main(String[] args) { + // Create a queue service client. + String queueServiceURL = String.format("https://%s.queue.core.windows.net/?%s", ACCOUNT_NAME, SAS_TOKEN); + QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL).buildClient(); + + // Create queue client. + Response queueClientResponse; + try { + queueClientResponse = queueServiceClient.createQueueWithResponse(SampleHelper.generateRandomName("delete-not-exist", + 16), null, Duration.ofSeconds(10), new Context("key1", "value1")); + System.out.println("Successfully create the queue! Status code: " + queueClientResponse.getStatusCode()); + } catch (QueueStorageException e) { + System.out.println(String.format("Error creating a queue. Error message: %s", e.getServiceMessage())); + throw new RuntimeException(e); + } + QueueClient queueClient = queueClientResponse.getValue(); + queueClient.sendMessage("Hello, message 1!"); + queueClient.sendMessage("Hello, message 2!"); + + // Delete message with wrong message id. + try { + QueueMessageItem queueMessageItem = queueClientResponse.getValue().receiveMessage(); + queueClient.deleteMessage("wrong id", queueMessageItem.getPopReceipt()); + } catch (QueueStorageException e) { + if (QueueErrorCode.MESSAGE_NOT_FOUND.equals(e.getErrorCode())) { + System.out.println("This is the error expected to throw"); + } else { + System.out.println("This is not the error we expect!"); + } + } + + // Delete message with wrong pop receipt. + try { + QueueMessageItem queueMessageItem = queueClientResponse.getValue().receiveMessage(); + queueClient.deleteMessage(queueMessageItem.getMessageId(), "Wrong Pop Receipt"); + } catch (QueueStorageException e) { + if (QueueErrorCode.INVALID_QUERY_PARAMETER_VALUE.equals(e.getErrorCode())) { + System.out.println("This is the error expected to throw"); + } else { + System.out.println("This is not the error we expect!"); + } + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample4/v2/QueueExceptionSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample4/v2/QueueExceptionSamples.java new file mode 100644 index 000000000000..29597d08c71c --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample4/v2/QueueExceptionSamples.java @@ -0,0 +1,68 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.queue; + +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.storage.queue.models.QueueErrorCode; +import com.azure.storage.queue.models.QueueMessageItem; +import com.azure.storage.queue.models.QueueStorageException; + +import java.time.Duration; + +public class QueueExceptionSamples { + + private static final String ACCOUNT_NAME = System.getenv("AZURE_STORAGE_ACCOUNT_NAME"); + private static final String SAS_TOKEN = System.getenv("PRIMARY_SAS_TOKEN"); + + /** + * The main method shows how to handle the storage exception. + * + * @param args No args needed for the main method. + * @throws RuntimeException If queueServiceClient failed to create a queue. + */ + public static void main(String[] args) { + // Create a queue service client. + String queueServiceURL = String.format("https://%s.queue.core.windows.net/?%s", ACCOUNT_NAME, SAS_TOKEN); + QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL).buildClient(); + + // Create queue client. + Response queueClientResponse; + try { + queueClientResponse = queueServiceClient.createQueueWithResponse(SampleHelper.generateRandomName("delete-not-exist", + 16), null, Duration.ofSeconds(10), new Context("key1", "value1")); + System.out.println("Successfully create the queue! Status code: " + queueClientResponse.getStatusCode()); + } catch (QueueStorageException e) { + System.out.println(String.format("Error creating a queue. Error message: %s", e.getServiceMessage())); + throw new RuntimeException(e); + } + QueueClient queueClient = queueClientResponse.getValue(); + queueClient.sendMessage("Hello, message 1!"); + queueClient.sendMessage("Hello, message 2!"); + + // Delete message with wrong message id. + try { + QueueMessageItem queueMessageItem = queueClientResponse.getValue().receiveMessage(); + queueClient.deleteMessage("wrong id", queueMessageItem.getPopReceipt()); + } catch (QueueStorageException e) { + if (QueueErrorCode.MESSAGE_NOT_FOUND.equals(e.getErrorCode())) { + System.out.println("This is the error expected to throw"); + } else { + System.out.println("This is not the error we expect!"); + } + } + + // Delete message with wrong pop receipt. + try { + QueueMessageItem queueMessageItem = queueClientResponse.getValue().receiveMessage(); + queueClient.deleteMessage(queueMessageItem.getMessageId(), "Wrong Pop Receipt"); + } catch (QueueStorageException e) { + if (QueueErrorCode.INVALID_QUERY_PARAMETER_VALUE.equals(e.getErrorCode())) { + System.out.println("This is the error expected to throw"); + } else { + System.out.println("This is not the error we expect!"); + } + } + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample5/v1/QueueJavaDocCodeSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample5/v1/QueueJavaDocCodeSamples.java new file mode 100644 index 000000000000..8600f3128cfa --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample5/v1/QueueJavaDocCodeSamples.java @@ -0,0 +1,629 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.queue; + +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; +import com.azure.storage.common.StorageSharedKeyCredential; +import com.azure.storage.queue.models.PeekedMessageItem; +import com.azure.storage.queue.models.QueueAccessPolicy; +import com.azure.storage.queue.models.QueueMessageDecodingError; +import com.azure.storage.queue.models.QueueMessageItem; +import com.azure.storage.queue.models.QueueProperties; +import com.azure.storage.queue.models.QueueSignedIdentifier; +import com.azure.storage.queue.models.SendMessageResult; +import com.azure.storage.queue.models.UpdateMessageResult; +import com.azure.storage.queue.sas.QueueSasPermission; +import com.azure.storage.queue.sas.QueueServiceSasSignatureValues; +import reactor.core.publisher.Mono; + +import java.time.Duration; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; +import java.util.function.Function; + +/** + * Contains code snippets when generating javadocs through doclets for {@link QueueClient}. + */ + +public class QueueJavaDocCodeSamples { + + private String key1 = "key1"; + private String value1 = "val1"; + private QueueClient client = createClientWithSASToken(); + + /** + * Generates code sample for creating a {@link QueueClient}. + */ + public void buildQueueClient() { + // BEGIN: com.azure.storage.queue.queueClient.instantiation + QueueClient client = new QueueClientBuilder() + .connectionString("connectionstring") + .endpoint("endpoint") + .buildClient(); + // END: com.azure.storage.queue.queueClient.instantiation + } + + /** + * Generates code sample for creating a {@link QueueClient} with {@link QueueClient} + * + * @return An instance of {@link QueueClient} + */ + public QueueClient createClientWithSASToken() { + // BEGIN: com.azure.storage.queue.queueClient.instantiation.sastoken + QueueClient client = new QueueClientBuilder() + .endpoint("https://${accountName}.queue.core.windows.net?${SASToken}") + .buildClient(); + // END: com.azure.storage.queue.queueClient.instantiation.sastoken + return client; + } + + /** + * Generates code sample for creating a {@link QueueClient} with SAS token. + * + * @return An instance of {@link QueueClient} + */ + public QueueClient createClientWithCredential() { + // BEGIN: com.azure.storage.queue.queueClient.instantiation.credential + QueueClient client = new QueueClientBuilder() + .endpoint("https://${accountName}.queue.core.windows.net") + .queueName("myqueue") + .sasToken("{SASTokenQueryParams}") + .buildClient(); + // END: com.azure.storage.queue.queueClient.instantiation.credential + return client; + } + + /** + * Generates code sample for creating a {@link QueueClient} with {@code connectionString} which turns into {@link + * StorageSharedKeyCredential} + * + * @return An instance of {@link QueueClient} + */ + public QueueClient createClientWithConnectionString() { + // BEGIN: com.azure.storage.queue.queueClient.instantiation.connectionstring + String connectionString = "DefaultEndpointsProtocol=https;AccountName={name};" + + "AccountKey={key};EndpointSuffix={core.windows.net}"; + QueueClient client = new QueueClientBuilder() + .connectionString(connectionString) + .buildClient(); + // END: com.azure.storage.queue.queueClient.instantiation.connectionstring + return client; + } + + /** + * Generates code sample for creating a {@link QueueClient} + * with {@link QueueServiceClientBuilder#processMessageDecodingErrorAsync(Function)}. + * + * @return An instance of {@link QueueClient} + */ + public QueueClient createClientWithDecodingFailedAsyncHandler() { + // BEGIN: com.azure.storage.queue.QueueClientBuilder#processMessageDecodingErrorAsyncHandler + String connectionString = "DefaultEndpointsProtocol=https;AccountName={name};" + + "AccountKey={key};EndpointSuffix={core.windows.net}"; + + Function> processMessageDecodingErrorHandler = + (queueMessageDecodingFailure) -> { + QueueMessageItem queueMessageItem = queueMessageDecodingFailure.getQueueMessageItem(); + PeekedMessageItem peekedMessageItem = queueMessageDecodingFailure.getPeekedMessageItem(); + if (queueMessageItem != null) { + System.out.printf("Received badly encoded message, messageId=%s, messageBody=%s", + queueMessageItem.getMessageId(), + queueMessageItem.getBody().toString()); + return queueMessageDecodingFailure + .getQueueAsyncClient() + .deleteMessage(queueMessageItem.getMessageId(), queueMessageItem.getPopReceipt()); + } else if (peekedMessageItem != null) { + System.out.printf("Peeked badly encoded message, messageId=%s, messageBody=%s", + peekedMessageItem.getMessageId(), + peekedMessageItem.getBody().toString()); + return Mono.empty(); + } else { + return Mono.empty(); + } + }; + + QueueClient client = new QueueClientBuilder() + .connectionString(connectionString) + .processMessageDecodingErrorAsync(processMessageDecodingErrorHandler) + .buildClient(); + // END: com.azure.storage.queue.QueueClientBuilder#processMessageDecodingErrorAsyncHandler + return client; + } + + /** + * Generates code sample for creating a {@link QueueClient} + * with {@link QueueServiceClientBuilder#processMessageDecodingError(Consumer)}. + * + * @return An instance of {@link QueueClient} + */ + public QueueClient createClientWithDecodingFailedHandler() { + // BEGIN: com.azure.storage.queue.QueueClientBuilder#processMessageDecodingErrorHandler + String connectionString = "DefaultEndpointsProtocol=https;AccountName={name};" + + "AccountKey={key};EndpointSuffix={core.windows.net}"; + + Consumer processMessageDecodingErrorHandler = + (queueMessageDecodingFailure) -> { + QueueMessageItem queueMessageItem = queueMessageDecodingFailure.getQueueMessageItem(); + PeekedMessageItem peekedMessageItem = queueMessageDecodingFailure.getPeekedMessageItem(); + if (queueMessageItem != null) { + System.out.printf("Received badly encoded message, messageId=%s, messageBody=%s", + queueMessageItem.getMessageId(), + queueMessageItem.getBody().toString()); + queueMessageDecodingFailure + .getQueueClient() + .deleteMessage(queueMessageItem.getMessageId(), queueMessageItem.getPopReceipt()); + } else if (peekedMessageItem != null) { + System.out.printf("Peeked badly encoded message, messageId=%s, messageBody=%s", + peekedMessageItem.getMessageId(), + peekedMessageItem.getBody().toString()); + } + }; + + QueueClient client = new QueueClientBuilder() + .connectionString(connectionString) + .processMessageDecodingError(processMessageDecodingErrorHandler) + .buildClient(); + // END: com.azure.storage.queue.QueueClientBuilder#processMessageDecodingErrorHandler + return client; + } + + /** + * Generates a code sample for using {@link QueueClient#create()} + */ + public void createQueue() { + // BEGIN: com.azure.storage.queue.queueClient.create + client.create(); + System.out.println("Complete creating queue."); + // END: com.azure.storage.queue.queueClient.create + } + + /** + * Generates a code sample for using {@link QueueClient#createWithResponse(Map, Duration, Context)} + */ + public void createQueueMaxOverload() { + + // BEGIN: com.azure.storage.queue.queueClient.createWithResponse#map-duration-context + Response response = client.createWithResponse(Collections.singletonMap("queue", "metadataMap"), + Duration.ofSeconds(1), new Context(key1, value1)); + System.out.println("Complete creating queue with status code: " + response.getStatusCode()); + // END: com.azure.storage.queue.queueClient.createWithResponse#map-duration-context + } + + /** + * Generates a code sample for using {@link QueueClient#sendMessage(String)} + */ + public void sendMessage() { + + // BEGIN: com.azure.storage.queue.queueClient.sendMessage#string + SendMessageResult response = client.sendMessage("hello msg"); + System.out.println("Complete enqueuing the message with message Id" + response.getMessageId()); + // END: com.azure.storage.queue.queueClient.sendMessage#string + } + + /** + * Generates a code sample for using {@link QueueClient#sendMessage(BinaryData)} + */ + public void sendMessageBinaryData() { + + // BEGIN: com.azure.storage.queue.queueClient.sendMessage#BinaryData + SendMessageResult response = client.sendMessage(BinaryData.fromString("Hello msg")); + System.out.println("Complete enqueuing the message with message Id" + response.getMessageId()); + // END: com.azure.storage.queue.queueClient.sendMessage#BinaryData + } + + /** + * Generates a code sample for using {@link QueueClient#sendMessageWithResponse(String, Duration, Duration, + * Duration, Context)} + */ + public void enqueueMessageWithTimeoutOverload() { + + // BEGIN: com.azure.storage.queue.QueueClient.sendMessageWithResponse#String-Duration-Duration-Duration-Context1 + SendMessageResult sentMessageItem = client.sendMessageWithResponse("Hello, Azure", + Duration.ofSeconds(5), null, Duration.ofSeconds(1), new Context(key1, value1)).getValue(); + System.out.printf("Message %s expires at %s", sentMessageItem.getMessageId(), + sentMessageItem.getExpirationTime()); + // END: com.azure.storage.queue.QueueClient.sendMessageWithResponse#String-Duration-Duration-Duration-Context1 + } + + /** + * Generates a code sample for using {@link QueueClient#sendMessageWithResponse(String, Duration, Duration, + * Duration, Context)} + */ + public void enqueueMessageBinaryDataWithTimeoutOverload() { + + // BEGIN: com.azure.storage.queue.QueueClient.sendMessageWithResponse#BinaryData-Duration-Duration-Duration-Context1 + SendMessageResult sentMessageItem = client.sendMessageWithResponse(BinaryData.fromString("Hello, Azure"), + Duration.ofSeconds(5), null, Duration.ofSeconds(1), new Context(key1, value1)).getValue(); + System.out.printf("Message %s expires at %s", sentMessageItem.getMessageId(), + sentMessageItem.getExpirationTime()); + // END: com.azure.storage.queue.QueueClient.sendMessageWithResponse#BinaryData-Duration-Duration-Duration-Context1 + } + + /** + * Generates a code sample for using {@link QueueClient#sendMessageWithResponse(String, Duration, Duration, + * Duration, Context)} + */ + public void sendMessageWithLiveTimeOverload() { + // BEGIN: com.azure.storage.queue.QueueClient.sendMessageWithResponse#String-Duration-Duration-Duration-Context2 + SendMessageResult enqueuedMessage = client.sendMessageWithResponse("Goodbye, Azure", + null, Duration.ofSeconds(5), Duration.ofSeconds(1), new Context(key1, value1)).getValue(); + System.out.printf("Message %s expires at %s", enqueuedMessage.getMessageId(), + enqueuedMessage.getExpirationTime()); + // END: com.azure.storage.queue.QueueClient.sendMessageWithResponse#String-Duration-Duration-Duration-Context2 + } + + /** + * Generates a code sample for using {@link QueueClient#sendMessageWithResponse(String, Duration, Duration, + * Duration, Context)} + */ + public void sendMessageBinaryDataWithLiveTimeOverload() { + // BEGIN: com.azure.storage.queue.QueueClient.sendMessageWithResponse#BinaryData-Duration-Duration-Duration-Context2 + SendMessageResult enqueuedMessage = client.sendMessageWithResponse(BinaryData.fromString("Goodbye, Azure"), + null, Duration.ofSeconds(5), Duration.ofSeconds(1), new Context(key1, value1)).getValue(); + System.out.printf("Message %s expires at %s", enqueuedMessage.getMessageId(), + enqueuedMessage.getExpirationTime()); + // END: com.azure.storage.queue.QueueClient.sendMessageWithResponse#BinaryData-Duration-Duration-Duration-Context2 + } + + /** + * Generates a code sample for using {@link QueueClient#receiveMessage()} + */ + public void getMessage() { + + // BEGIN: com.azure.storage.queue.queueClient.receiveMessage + QueueMessageItem queueMessageItem = client.receiveMessage(); + System.out.println("Complete receiving the message: " + queueMessageItem.getMessageId()); + // END: com.azure.storage.queue.queueClient.receiveMessage + } + + /** + * Generates a code sample for using {@link QueueClient#receiveMessages(Integer)} + */ + public void getMessageWithOverload() { + + // BEGIN: com.azure.storage.queue.queueClient.receiveMessages#integer + for (QueueMessageItem message : client.receiveMessages(5)) { + System.out.printf("Received %s and it becomes visible at %s", + message.getMessageId(), message.getTimeNextVisible()); + } + // END: com.azure.storage.queue.queueClient.receiveMessages#integer + } + + /** + * Generates a code sample for using {@link QueueClient#receiveMessages(Integer, Duration, Duration, Context)} + */ + public void getMessageMaxOverload() { + + // BEGIN: com.azure.storage.queue.queueClient.receiveMessages#integer-duration-duration-context + for (QueueMessageItem message : client.receiveMessages(5, Duration.ofSeconds(60), + Duration.ofSeconds(1), new Context(key1, value1))) { + System.out.printf("Received %s and it becomes visible at %s", + message.getMessageId(), message.getTimeNextVisible()); + } + // END: com.azure.storage.queue.queueClient.receiveMessages#integer-duration-duration-context + } + + /** + * Generates a code sample for using {@link QueueClient#peekMessage()} + */ + public void peekMessage() { + + // BEGIN: com.azure.storage.queue.queueClient.peekMessage + PeekedMessageItem peekedMessageItem = client.peekMessage(); + System.out.println("Complete peeking the message: " + peekedMessageItem.getBody().toString()); + // END: com.azure.storage.queue.queueClient.peekMessage + } + + /** + * Generates a code sample for using {@link QueueClient#peekMessages(Integer, Duration, Context)} + */ + public void peekMessageMaxOverload() { + + // BEGIN: com.azure.storage.queue.queueClient.peekMessages#integer-duration-context + client.peekMessages(5, Duration.ofSeconds(1), new Context(key1, value1)).forEach( + peekMessage -> System.out.printf("Peeked message %s has been received %d times", + peekMessage.getMessageId(), peekMessage.getDequeueCount()) + ); + // END: com.azure.storage.queue.queueClient.peekMessages#integer-duration-context + } + + /** + * Generates a code sample for using {@link QueueClient#updateMessage(String, String, String, Duration)} + */ + public void updateMessage() { + // BEGIN: com.azure.storage.queue.QueueClient.updateMessage#String-String-String-Duration + QueueMessageItem queueMessageItem = client.receiveMessage(); + UpdateMessageResult result = client.updateMessage(queueMessageItem.getMessageId(), + queueMessageItem.getPopReceipt(), "newText", null); + System.out.println("Complete updating the message with the receipt " + result.getPopReceipt()); + // END: com.azure.storage.queue.QueueClient.updateMessage#String-String-String-Duration + } + + /** + * Generates a code sample for using {@link QueueClient#updateMessageWithResponse(String, String, String, Duration, + * Duration, Context)} + */ + public void updateMessageWithResponse() { + // BEGIN: com.azure.storage.queue.QueueClient.updateMessageWithResponse#String-String-String-Duration-Duration-Context + QueueMessageItem queueMessageItem = client.receiveMessage(); + Response response = client.updateMessageWithResponse(queueMessageItem.getMessageId(), + queueMessageItem.getPopReceipt(), "newText", null, Duration.ofSeconds(1), + new Context(key1, value1)); + System.out.println("Complete updating the message with status code " + response.getStatusCode()); + // END: com.azure.storage.queue.QueueClient.updateMessageWithResponse#String-String-String-Duration-Duration-Context + } + + /** + * Generates a code sample for using {@link QueueClient#deleteMessage(String, String)} + */ + public void deleteMessage() { + // BEGIN: com.azure.storage.queue.QueueClient.deleteMessage#String-String + QueueMessageItem queueMessageItem = client.receiveMessage(); + client.deleteMessage(queueMessageItem.getMessageId(), queueMessageItem.getPopReceipt()); + System.out.println("Complete deleting the message."); + // END: com.azure.storage.queue.QueueClient.deleteMessage#String-String + } + + /** + * Generates a code sample for using {@link QueueClient#deleteMessageWithResponse(String, String, Duration, + * Context)} + */ + public void deleteMessageWithResponse() { + // BEGIN: com.azure.storage.queue.QueueClient.deleteMessageWithResponse#String-String-Duration-Context + QueueMessageItem queueMessageItem = client.receiveMessage(); + Response response = client.deleteMessageWithResponse(queueMessageItem.getMessageId(), + queueMessageItem.getPopReceipt(), Duration.ofSeconds(1), new Context(key1, value1)); + System.out.println("Complete deleting the message with status code " + response.getStatusCode()); + // END: com.azure.storage.queue.QueueClient.deleteMessageWithResponse#String-String-Duration-Context + } + + /** + * Generates a code sample for using {@link QueueClient#delete()} + */ + public void deleteQueue() { + + // BEGIN: com.azure.storage.queue.queueClient.delete + client.delete(); + System.out.println("Complete deleting the queue."); + // END: com.azure.storage.queue.queueClient.delete + } + + /** + * Generates a code sample for using {@link QueueClient#deleteWithResponse(Duration, Context)} + */ + public void deleteWithResponse() { + + // BEGIN: com.azure.storage.queue.queueClient.deleteWithResponse#duration-context + Response response = client.deleteWithResponse(Duration.ofSeconds(1), new Context(key1, value1)); + System.out.println("Complete deleting the queue with status code: " + response.getStatusCode()); + // END: com.azure.storage.queue.queueClient.deleteWithResponse#duration-context + } + + /** + * Generates a code sample for using {@link QueueClient#getProperties()} + */ + public void getProperties() { + + // BEGIN: com.azure.storage.queue.queueClient.getProperties + QueueProperties properties = client.getProperties(); + System.out.printf("Metadata: %s, Approximate message count: %d", properties.getMetadata(), + properties.getApproximateMessagesCount()); + // END: com.azure.storage.queue.queueClient.getProperties + } + + /** + * Generates a code sample for using {@link QueueClient#getPropertiesWithResponse(Duration, Context)} + */ + public void getPropertiesWithResponse() { + + // BEGIN: com.azure.storage.queue.queueClient.getPropertiesWithResponse#duration-context + QueueProperties properties = client.getPropertiesWithResponse(Duration.ofSeconds(1), + new Context(key1, value1)).getValue(); + System.out.printf("Metadata: %s, Approximate message count: %d", properties.getMetadata(), + properties.getApproximateMessagesCount()); + // END: com.azure.storage.queue.queueClient.getPropertiesWithResponse#duration-context + } + + /** + * Generate a code sample for using {@link QueueClient#setMetadata(Map)} to set metadata. + */ + public void setMetadata() { + + // BEGIN: com.azure.storage.queue.queueClient.setMetadata#map + client.setMetadata(Collections.singletonMap("queue", "metadataMap")); + System.out.println("Setting metadata completed."); + // END: com.azure.storage.queue.queueClient.setMetadata#map + } + + /** + * Generate a code sample for using {@link QueueClient#setMetadataWithResponse(Map, Duration, Context)} to set + * metadata. + */ + public void setMetadataWithResponse() { + + // BEGIN: com.azure.storage.queue.queueClient.setMetadataWithResponse#map-duration-context + client.setMetadataWithResponse(Collections.singletonMap("queue", "metadataMap"), + Duration.ofSeconds(1), new Context(key1, value1)); + System.out.println("Setting metadata completed."); + // END: com.azure.storage.queue.queueClient.setMetadataWithResponse#map-duration-context + } + + /** + * Generate a code sample for using {@link QueueClient#setMetadata(Map)} to clear metadata. + */ + public void clearMetadata() { + + // BEGIN: com.azure.storage.queue.queueClient.clearMetadata#map + client.setMetadata(null); + System.out.println("Clearing metadata completed."); + // END: com.azure.storage.queue.queueClient.clearMetadata#map + } + + /** + * Generate a code sample for using {@link QueueClient#setMetadataWithResponse(Map, Duration, Context)} to clear + * metadata. + */ + public void clearMetadataWithResponse() { + + // BEGIN: com.azure.storage.queue.queueClient.clearMetadataWithResponse#map-duration-context + Response response = client.setMetadataWithResponse(null, Duration.ofSeconds(1), + new Context(key1, value1)); + System.out.printf("Clearing metadata completed with status code %d", response.getStatusCode()); + // END: com.azure.storage.queue.queueClient.clearMetadataWithResponse#map-duration-context + } + + /** + * Generates a code sample for using {@link QueueClient#getAccessPolicy()} + */ + public void getAccessPolicy() { + + // BEGIN: com.azure.storage.queue.queueClient.getAccessPolicy + for (QueueSignedIdentifier permission : client.getAccessPolicy()) { + System.out.printf("Access policy %s allows these permissions: %s", permission.getId(), + permission.getAccessPolicy().getPermissions()); + } + // END: com.azure.storage.queue.queueClient.getAccessPolicy + } + + /** + * Generates a code sample for using {@link QueueClient#setAccessPolicy(List)} + */ + public void setAccessPolicy() { + // BEGIN: com.azure.storage.queue.QueueClient.setAccessPolicy#List + QueueAccessPolicy accessPolicy = new QueueAccessPolicy().setPermissions("r") + .setStartsOn(OffsetDateTime.now(ZoneOffset.UTC)) + .setExpiresOn(OffsetDateTime.now(ZoneOffset.UTC).plusDays(10)); + QueueSignedIdentifier permission = new QueueSignedIdentifier().setId("mypolicy").setAccessPolicy(accessPolicy); + client.setAccessPolicy(Collections.singletonList(permission)); + System.out.println("Setting access policies completed."); + // END: com.azure.storage.queue.QueueClient.setAccessPolicy#List + } + + /** + * Generates a code sample for using {@link QueueClient#setAccessPolicyWithResponse(List, Duration, Context)} + */ + public void setAccessPolicyWithResponse() { + + // BEGIN: com.azure.storage.queue.queueClient.setAccessPolicyWithResponse#List-Duration-Context + QueueAccessPolicy accessPolicy = new QueueAccessPolicy().setPermissions("r") + .setStartsOn(OffsetDateTime.now(ZoneOffset.UTC)) + .setExpiresOn(OffsetDateTime.now(ZoneOffset.UTC).plusDays(10)); + QueueSignedIdentifier permission = new QueueSignedIdentifier().setId("mypolicy").setAccessPolicy(accessPolicy); + Response response = client.setAccessPolicyWithResponse(Collections.singletonList(permission), + Duration.ofSeconds(1), new Context(key1, value1)); + System.out.printf("Setting access policies completed with status code %d", response.getStatusCode()); + // END: com.azure.storage.queue.queueClient.setAccessPolicyWithResponse#List-Duration-Context + } + + /** + * Generates a code sample for using {@link QueueClient#clearMessages()} + */ + public void clearMessages() { + + // BEGIN: com.azure.storage.queue.queueClient.clearMessages + client.clearMessages(); + System.out.println("Clearing messages completed."); + // END: com.azure.storage.queue.queueClient.clearMessages + } + + /** + * Generates a code sample for using {@link QueueClient#clearMessagesWithResponse(Duration, Context)} + */ + public void clearMessagesWithResponse() { + + // BEGIN: com.azure.storage.queue.queueClient.clearMessagesWithResponse#duration-context + Response response = client.clearMessagesWithResponse(Duration.ofSeconds(1), new Context(key1, value1)); + System.out.printf("Clearing messages completed with status code %d", response.getStatusCode()); + // END: com.azure.storage.queue.queueClient.clearMessagesWithResponse#duration-context + } + + /** + * Generates a code sample for using {@link QueueClient#getQueueName()} + */ + public void getName() { + // BEGIN: com.azure.storage.queue.queueClient.getQueueName + String queueName = client.getQueueName(); + System.out.println("The name of the queue is " + queueName); + // END: com.azure.storage.queue.queueClient.getQueueName + } + + /** + * Code snippet for {@link QueueClient#generateSas(QueueServiceSasSignatureValues)} + */ + public void generateSas() { + // BEGIN: com.azure.storage.queue.QueueClient.generateSas#QueueServiceSasSignatureValues + OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1); + QueueSasPermission permission = new QueueSasPermission().setReadPermission(true); + + QueueServiceSasSignatureValues values = new QueueServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + client.generateSas(values); // Client must be authenticated via StorageSharedKeyCredential + // END: com.azure.storage.queue.QueueClient.generateSas#QueueServiceSasSignatureValues + } + + /** + * Code snippet for {@link QueueClient#generateSas(QueueServiceSasSignatureValues, Context)} + */ + public void generateSasWithContext() { + // BEGIN: com.azure.storage.queue.QueueClient.generateSas#QueueServiceSasSignatureValues-Context + OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1); + QueueSasPermission permission = new QueueSasPermission().setReadPermission(true); + + QueueServiceSasSignatureValues values = new QueueServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + // Client must be authenticated via StorageSharedKeyCredential + client.generateSas(values, new Context("key", "value")); + // END: com.azure.storage.queue.QueueClient.generateSas#QueueServiceSasSignatureValues-Context + } + + /** + * Generates a code sample for using {@link QueueClient#createIfNotExists()} and + * {@link QueueClient#createIfNotExistsWithResponse(Map, Duration, Context)} + */ + public void createQueueIfNotExistsCodeSnippets() { + // BEGIN: com.azure.storage.queue.queueClient.createIfNotExists + boolean result = client.createIfNotExists(); + System.out.println("Queue created: " + result); + // END: com.azure.storage.queue.queueClient.createIfNotExists + + // BEGIN: com.azure.storage.queue.queueClient.createIfNotExistsWithResponse#map-duration-context + Response response = client.createIfNotExistsWithResponse(Collections.singletonMap("queue", "metadataMap"), + Duration.ofSeconds(1), new Context(key1, value1)); + if (response.getStatusCode() == 409) { + System.out.println("Already existed."); + } else { + System.out.printf("Create completed with status %d%n", response.getStatusCode()); + } + // END: com.azure.storage.queue.queueClient.createIfNotExistsWithResponse#map-duration-context + } + + /** + * Generates a code sample for using {@link QueueClient#deleteIfExists()} and + * {@link QueueClient#deleteIfExistsWithResponse(Duration, Context)} + */ + public void deleteQueueIfExistsCodeSnippets() { + + // BEGIN: com.azure.storage.queue.queueClient.deleteIfExists + client.deleteIfExists(); + System.out.println("Complete deleting the queue."); + // END: com.azure.storage.queue.queueClient.deleteIfExists + + // BEGIN: com.azure.storage.queue.queueClient.deleteIfExistsWithResponse#duration-context + Response response = client.deleteIfExistsWithResponse(Duration.ofSeconds(1), new Context(key1, value1)); + if (response.getStatusCode() == 404) { + System.out.println("Does not exist."); + } else { + System.out.printf("Delete completed with status %d%n", response.getStatusCode()); + } + // END: com.azure.storage.queue.queueClient.deleteIfExistsWithResponse#duration-context + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample5/v2/QueueJavaDocCodeSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample5/v2/QueueJavaDocCodeSamples.java new file mode 100644 index 000000000000..8600f3128cfa --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample5/v2/QueueJavaDocCodeSamples.java @@ -0,0 +1,629 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.queue; + +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; +import com.azure.storage.common.StorageSharedKeyCredential; +import com.azure.storage.queue.models.PeekedMessageItem; +import com.azure.storage.queue.models.QueueAccessPolicy; +import com.azure.storage.queue.models.QueueMessageDecodingError; +import com.azure.storage.queue.models.QueueMessageItem; +import com.azure.storage.queue.models.QueueProperties; +import com.azure.storage.queue.models.QueueSignedIdentifier; +import com.azure.storage.queue.models.SendMessageResult; +import com.azure.storage.queue.models.UpdateMessageResult; +import com.azure.storage.queue.sas.QueueSasPermission; +import com.azure.storage.queue.sas.QueueServiceSasSignatureValues; +import reactor.core.publisher.Mono; + +import java.time.Duration; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; +import java.util.function.Function; + +/** + * Contains code snippets when generating javadocs through doclets for {@link QueueClient}. + */ + +public class QueueJavaDocCodeSamples { + + private String key1 = "key1"; + private String value1 = "val1"; + private QueueClient client = createClientWithSASToken(); + + /** + * Generates code sample for creating a {@link QueueClient}. + */ + public void buildQueueClient() { + // BEGIN: com.azure.storage.queue.queueClient.instantiation + QueueClient client = new QueueClientBuilder() + .connectionString("connectionstring") + .endpoint("endpoint") + .buildClient(); + // END: com.azure.storage.queue.queueClient.instantiation + } + + /** + * Generates code sample for creating a {@link QueueClient} with {@link QueueClient} + * + * @return An instance of {@link QueueClient} + */ + public QueueClient createClientWithSASToken() { + // BEGIN: com.azure.storage.queue.queueClient.instantiation.sastoken + QueueClient client = new QueueClientBuilder() + .endpoint("https://${accountName}.queue.core.windows.net?${SASToken}") + .buildClient(); + // END: com.azure.storage.queue.queueClient.instantiation.sastoken + return client; + } + + /** + * Generates code sample for creating a {@link QueueClient} with SAS token. + * + * @return An instance of {@link QueueClient} + */ + public QueueClient createClientWithCredential() { + // BEGIN: com.azure.storage.queue.queueClient.instantiation.credential + QueueClient client = new QueueClientBuilder() + .endpoint("https://${accountName}.queue.core.windows.net") + .queueName("myqueue") + .sasToken("{SASTokenQueryParams}") + .buildClient(); + // END: com.azure.storage.queue.queueClient.instantiation.credential + return client; + } + + /** + * Generates code sample for creating a {@link QueueClient} with {@code connectionString} which turns into {@link + * StorageSharedKeyCredential} + * + * @return An instance of {@link QueueClient} + */ + public QueueClient createClientWithConnectionString() { + // BEGIN: com.azure.storage.queue.queueClient.instantiation.connectionstring + String connectionString = "DefaultEndpointsProtocol=https;AccountName={name};" + + "AccountKey={key};EndpointSuffix={core.windows.net}"; + QueueClient client = new QueueClientBuilder() + .connectionString(connectionString) + .buildClient(); + // END: com.azure.storage.queue.queueClient.instantiation.connectionstring + return client; + } + + /** + * Generates code sample for creating a {@link QueueClient} + * with {@link QueueServiceClientBuilder#processMessageDecodingErrorAsync(Function)}. + * + * @return An instance of {@link QueueClient} + */ + public QueueClient createClientWithDecodingFailedAsyncHandler() { + // BEGIN: com.azure.storage.queue.QueueClientBuilder#processMessageDecodingErrorAsyncHandler + String connectionString = "DefaultEndpointsProtocol=https;AccountName={name};" + + "AccountKey={key};EndpointSuffix={core.windows.net}"; + + Function> processMessageDecodingErrorHandler = + (queueMessageDecodingFailure) -> { + QueueMessageItem queueMessageItem = queueMessageDecodingFailure.getQueueMessageItem(); + PeekedMessageItem peekedMessageItem = queueMessageDecodingFailure.getPeekedMessageItem(); + if (queueMessageItem != null) { + System.out.printf("Received badly encoded message, messageId=%s, messageBody=%s", + queueMessageItem.getMessageId(), + queueMessageItem.getBody().toString()); + return queueMessageDecodingFailure + .getQueueAsyncClient() + .deleteMessage(queueMessageItem.getMessageId(), queueMessageItem.getPopReceipt()); + } else if (peekedMessageItem != null) { + System.out.printf("Peeked badly encoded message, messageId=%s, messageBody=%s", + peekedMessageItem.getMessageId(), + peekedMessageItem.getBody().toString()); + return Mono.empty(); + } else { + return Mono.empty(); + } + }; + + QueueClient client = new QueueClientBuilder() + .connectionString(connectionString) + .processMessageDecodingErrorAsync(processMessageDecodingErrorHandler) + .buildClient(); + // END: com.azure.storage.queue.QueueClientBuilder#processMessageDecodingErrorAsyncHandler + return client; + } + + /** + * Generates code sample for creating a {@link QueueClient} + * with {@link QueueServiceClientBuilder#processMessageDecodingError(Consumer)}. + * + * @return An instance of {@link QueueClient} + */ + public QueueClient createClientWithDecodingFailedHandler() { + // BEGIN: com.azure.storage.queue.QueueClientBuilder#processMessageDecodingErrorHandler + String connectionString = "DefaultEndpointsProtocol=https;AccountName={name};" + + "AccountKey={key};EndpointSuffix={core.windows.net}"; + + Consumer processMessageDecodingErrorHandler = + (queueMessageDecodingFailure) -> { + QueueMessageItem queueMessageItem = queueMessageDecodingFailure.getQueueMessageItem(); + PeekedMessageItem peekedMessageItem = queueMessageDecodingFailure.getPeekedMessageItem(); + if (queueMessageItem != null) { + System.out.printf("Received badly encoded message, messageId=%s, messageBody=%s", + queueMessageItem.getMessageId(), + queueMessageItem.getBody().toString()); + queueMessageDecodingFailure + .getQueueClient() + .deleteMessage(queueMessageItem.getMessageId(), queueMessageItem.getPopReceipt()); + } else if (peekedMessageItem != null) { + System.out.printf("Peeked badly encoded message, messageId=%s, messageBody=%s", + peekedMessageItem.getMessageId(), + peekedMessageItem.getBody().toString()); + } + }; + + QueueClient client = new QueueClientBuilder() + .connectionString(connectionString) + .processMessageDecodingError(processMessageDecodingErrorHandler) + .buildClient(); + // END: com.azure.storage.queue.QueueClientBuilder#processMessageDecodingErrorHandler + return client; + } + + /** + * Generates a code sample for using {@link QueueClient#create()} + */ + public void createQueue() { + // BEGIN: com.azure.storage.queue.queueClient.create + client.create(); + System.out.println("Complete creating queue."); + // END: com.azure.storage.queue.queueClient.create + } + + /** + * Generates a code sample for using {@link QueueClient#createWithResponse(Map, Duration, Context)} + */ + public void createQueueMaxOverload() { + + // BEGIN: com.azure.storage.queue.queueClient.createWithResponse#map-duration-context + Response response = client.createWithResponse(Collections.singletonMap("queue", "metadataMap"), + Duration.ofSeconds(1), new Context(key1, value1)); + System.out.println("Complete creating queue with status code: " + response.getStatusCode()); + // END: com.azure.storage.queue.queueClient.createWithResponse#map-duration-context + } + + /** + * Generates a code sample for using {@link QueueClient#sendMessage(String)} + */ + public void sendMessage() { + + // BEGIN: com.azure.storage.queue.queueClient.sendMessage#string + SendMessageResult response = client.sendMessage("hello msg"); + System.out.println("Complete enqueuing the message with message Id" + response.getMessageId()); + // END: com.azure.storage.queue.queueClient.sendMessage#string + } + + /** + * Generates a code sample for using {@link QueueClient#sendMessage(BinaryData)} + */ + public void sendMessageBinaryData() { + + // BEGIN: com.azure.storage.queue.queueClient.sendMessage#BinaryData + SendMessageResult response = client.sendMessage(BinaryData.fromString("Hello msg")); + System.out.println("Complete enqueuing the message with message Id" + response.getMessageId()); + // END: com.azure.storage.queue.queueClient.sendMessage#BinaryData + } + + /** + * Generates a code sample for using {@link QueueClient#sendMessageWithResponse(String, Duration, Duration, + * Duration, Context)} + */ + public void enqueueMessageWithTimeoutOverload() { + + // BEGIN: com.azure.storage.queue.QueueClient.sendMessageWithResponse#String-Duration-Duration-Duration-Context1 + SendMessageResult sentMessageItem = client.sendMessageWithResponse("Hello, Azure", + Duration.ofSeconds(5), null, Duration.ofSeconds(1), new Context(key1, value1)).getValue(); + System.out.printf("Message %s expires at %s", sentMessageItem.getMessageId(), + sentMessageItem.getExpirationTime()); + // END: com.azure.storage.queue.QueueClient.sendMessageWithResponse#String-Duration-Duration-Duration-Context1 + } + + /** + * Generates a code sample for using {@link QueueClient#sendMessageWithResponse(String, Duration, Duration, + * Duration, Context)} + */ + public void enqueueMessageBinaryDataWithTimeoutOverload() { + + // BEGIN: com.azure.storage.queue.QueueClient.sendMessageWithResponse#BinaryData-Duration-Duration-Duration-Context1 + SendMessageResult sentMessageItem = client.sendMessageWithResponse(BinaryData.fromString("Hello, Azure"), + Duration.ofSeconds(5), null, Duration.ofSeconds(1), new Context(key1, value1)).getValue(); + System.out.printf("Message %s expires at %s", sentMessageItem.getMessageId(), + sentMessageItem.getExpirationTime()); + // END: com.azure.storage.queue.QueueClient.sendMessageWithResponse#BinaryData-Duration-Duration-Duration-Context1 + } + + /** + * Generates a code sample for using {@link QueueClient#sendMessageWithResponse(String, Duration, Duration, + * Duration, Context)} + */ + public void sendMessageWithLiveTimeOverload() { + // BEGIN: com.azure.storage.queue.QueueClient.sendMessageWithResponse#String-Duration-Duration-Duration-Context2 + SendMessageResult enqueuedMessage = client.sendMessageWithResponse("Goodbye, Azure", + null, Duration.ofSeconds(5), Duration.ofSeconds(1), new Context(key1, value1)).getValue(); + System.out.printf("Message %s expires at %s", enqueuedMessage.getMessageId(), + enqueuedMessage.getExpirationTime()); + // END: com.azure.storage.queue.QueueClient.sendMessageWithResponse#String-Duration-Duration-Duration-Context2 + } + + /** + * Generates a code sample for using {@link QueueClient#sendMessageWithResponse(String, Duration, Duration, + * Duration, Context)} + */ + public void sendMessageBinaryDataWithLiveTimeOverload() { + // BEGIN: com.azure.storage.queue.QueueClient.sendMessageWithResponse#BinaryData-Duration-Duration-Duration-Context2 + SendMessageResult enqueuedMessage = client.sendMessageWithResponse(BinaryData.fromString("Goodbye, Azure"), + null, Duration.ofSeconds(5), Duration.ofSeconds(1), new Context(key1, value1)).getValue(); + System.out.printf("Message %s expires at %s", enqueuedMessage.getMessageId(), + enqueuedMessage.getExpirationTime()); + // END: com.azure.storage.queue.QueueClient.sendMessageWithResponse#BinaryData-Duration-Duration-Duration-Context2 + } + + /** + * Generates a code sample for using {@link QueueClient#receiveMessage()} + */ + public void getMessage() { + + // BEGIN: com.azure.storage.queue.queueClient.receiveMessage + QueueMessageItem queueMessageItem = client.receiveMessage(); + System.out.println("Complete receiving the message: " + queueMessageItem.getMessageId()); + // END: com.azure.storage.queue.queueClient.receiveMessage + } + + /** + * Generates a code sample for using {@link QueueClient#receiveMessages(Integer)} + */ + public void getMessageWithOverload() { + + // BEGIN: com.azure.storage.queue.queueClient.receiveMessages#integer + for (QueueMessageItem message : client.receiveMessages(5)) { + System.out.printf("Received %s and it becomes visible at %s", + message.getMessageId(), message.getTimeNextVisible()); + } + // END: com.azure.storage.queue.queueClient.receiveMessages#integer + } + + /** + * Generates a code sample for using {@link QueueClient#receiveMessages(Integer, Duration, Duration, Context)} + */ + public void getMessageMaxOverload() { + + // BEGIN: com.azure.storage.queue.queueClient.receiveMessages#integer-duration-duration-context + for (QueueMessageItem message : client.receiveMessages(5, Duration.ofSeconds(60), + Duration.ofSeconds(1), new Context(key1, value1))) { + System.out.printf("Received %s and it becomes visible at %s", + message.getMessageId(), message.getTimeNextVisible()); + } + // END: com.azure.storage.queue.queueClient.receiveMessages#integer-duration-duration-context + } + + /** + * Generates a code sample for using {@link QueueClient#peekMessage()} + */ + public void peekMessage() { + + // BEGIN: com.azure.storage.queue.queueClient.peekMessage + PeekedMessageItem peekedMessageItem = client.peekMessage(); + System.out.println("Complete peeking the message: " + peekedMessageItem.getBody().toString()); + // END: com.azure.storage.queue.queueClient.peekMessage + } + + /** + * Generates a code sample for using {@link QueueClient#peekMessages(Integer, Duration, Context)} + */ + public void peekMessageMaxOverload() { + + // BEGIN: com.azure.storage.queue.queueClient.peekMessages#integer-duration-context + client.peekMessages(5, Duration.ofSeconds(1), new Context(key1, value1)).forEach( + peekMessage -> System.out.printf("Peeked message %s has been received %d times", + peekMessage.getMessageId(), peekMessage.getDequeueCount()) + ); + // END: com.azure.storage.queue.queueClient.peekMessages#integer-duration-context + } + + /** + * Generates a code sample for using {@link QueueClient#updateMessage(String, String, String, Duration)} + */ + public void updateMessage() { + // BEGIN: com.azure.storage.queue.QueueClient.updateMessage#String-String-String-Duration + QueueMessageItem queueMessageItem = client.receiveMessage(); + UpdateMessageResult result = client.updateMessage(queueMessageItem.getMessageId(), + queueMessageItem.getPopReceipt(), "newText", null); + System.out.println("Complete updating the message with the receipt " + result.getPopReceipt()); + // END: com.azure.storage.queue.QueueClient.updateMessage#String-String-String-Duration + } + + /** + * Generates a code sample for using {@link QueueClient#updateMessageWithResponse(String, String, String, Duration, + * Duration, Context)} + */ + public void updateMessageWithResponse() { + // BEGIN: com.azure.storage.queue.QueueClient.updateMessageWithResponse#String-String-String-Duration-Duration-Context + QueueMessageItem queueMessageItem = client.receiveMessage(); + Response response = client.updateMessageWithResponse(queueMessageItem.getMessageId(), + queueMessageItem.getPopReceipt(), "newText", null, Duration.ofSeconds(1), + new Context(key1, value1)); + System.out.println("Complete updating the message with status code " + response.getStatusCode()); + // END: com.azure.storage.queue.QueueClient.updateMessageWithResponse#String-String-String-Duration-Duration-Context + } + + /** + * Generates a code sample for using {@link QueueClient#deleteMessage(String, String)} + */ + public void deleteMessage() { + // BEGIN: com.azure.storage.queue.QueueClient.deleteMessage#String-String + QueueMessageItem queueMessageItem = client.receiveMessage(); + client.deleteMessage(queueMessageItem.getMessageId(), queueMessageItem.getPopReceipt()); + System.out.println("Complete deleting the message."); + // END: com.azure.storage.queue.QueueClient.deleteMessage#String-String + } + + /** + * Generates a code sample for using {@link QueueClient#deleteMessageWithResponse(String, String, Duration, + * Context)} + */ + public void deleteMessageWithResponse() { + // BEGIN: com.azure.storage.queue.QueueClient.deleteMessageWithResponse#String-String-Duration-Context + QueueMessageItem queueMessageItem = client.receiveMessage(); + Response response = client.deleteMessageWithResponse(queueMessageItem.getMessageId(), + queueMessageItem.getPopReceipt(), Duration.ofSeconds(1), new Context(key1, value1)); + System.out.println("Complete deleting the message with status code " + response.getStatusCode()); + // END: com.azure.storage.queue.QueueClient.deleteMessageWithResponse#String-String-Duration-Context + } + + /** + * Generates a code sample for using {@link QueueClient#delete()} + */ + public void deleteQueue() { + + // BEGIN: com.azure.storage.queue.queueClient.delete + client.delete(); + System.out.println("Complete deleting the queue."); + // END: com.azure.storage.queue.queueClient.delete + } + + /** + * Generates a code sample for using {@link QueueClient#deleteWithResponse(Duration, Context)} + */ + public void deleteWithResponse() { + + // BEGIN: com.azure.storage.queue.queueClient.deleteWithResponse#duration-context + Response response = client.deleteWithResponse(Duration.ofSeconds(1), new Context(key1, value1)); + System.out.println("Complete deleting the queue with status code: " + response.getStatusCode()); + // END: com.azure.storage.queue.queueClient.deleteWithResponse#duration-context + } + + /** + * Generates a code sample for using {@link QueueClient#getProperties()} + */ + public void getProperties() { + + // BEGIN: com.azure.storage.queue.queueClient.getProperties + QueueProperties properties = client.getProperties(); + System.out.printf("Metadata: %s, Approximate message count: %d", properties.getMetadata(), + properties.getApproximateMessagesCount()); + // END: com.azure.storage.queue.queueClient.getProperties + } + + /** + * Generates a code sample for using {@link QueueClient#getPropertiesWithResponse(Duration, Context)} + */ + public void getPropertiesWithResponse() { + + // BEGIN: com.azure.storage.queue.queueClient.getPropertiesWithResponse#duration-context + QueueProperties properties = client.getPropertiesWithResponse(Duration.ofSeconds(1), + new Context(key1, value1)).getValue(); + System.out.printf("Metadata: %s, Approximate message count: %d", properties.getMetadata(), + properties.getApproximateMessagesCount()); + // END: com.azure.storage.queue.queueClient.getPropertiesWithResponse#duration-context + } + + /** + * Generate a code sample for using {@link QueueClient#setMetadata(Map)} to set metadata. + */ + public void setMetadata() { + + // BEGIN: com.azure.storage.queue.queueClient.setMetadata#map + client.setMetadata(Collections.singletonMap("queue", "metadataMap")); + System.out.println("Setting metadata completed."); + // END: com.azure.storage.queue.queueClient.setMetadata#map + } + + /** + * Generate a code sample for using {@link QueueClient#setMetadataWithResponse(Map, Duration, Context)} to set + * metadata. + */ + public void setMetadataWithResponse() { + + // BEGIN: com.azure.storage.queue.queueClient.setMetadataWithResponse#map-duration-context + client.setMetadataWithResponse(Collections.singletonMap("queue", "metadataMap"), + Duration.ofSeconds(1), new Context(key1, value1)); + System.out.println("Setting metadata completed."); + // END: com.azure.storage.queue.queueClient.setMetadataWithResponse#map-duration-context + } + + /** + * Generate a code sample for using {@link QueueClient#setMetadata(Map)} to clear metadata. + */ + public void clearMetadata() { + + // BEGIN: com.azure.storage.queue.queueClient.clearMetadata#map + client.setMetadata(null); + System.out.println("Clearing metadata completed."); + // END: com.azure.storage.queue.queueClient.clearMetadata#map + } + + /** + * Generate a code sample for using {@link QueueClient#setMetadataWithResponse(Map, Duration, Context)} to clear + * metadata. + */ + public void clearMetadataWithResponse() { + + // BEGIN: com.azure.storage.queue.queueClient.clearMetadataWithResponse#map-duration-context + Response response = client.setMetadataWithResponse(null, Duration.ofSeconds(1), + new Context(key1, value1)); + System.out.printf("Clearing metadata completed with status code %d", response.getStatusCode()); + // END: com.azure.storage.queue.queueClient.clearMetadataWithResponse#map-duration-context + } + + /** + * Generates a code sample for using {@link QueueClient#getAccessPolicy()} + */ + public void getAccessPolicy() { + + // BEGIN: com.azure.storage.queue.queueClient.getAccessPolicy + for (QueueSignedIdentifier permission : client.getAccessPolicy()) { + System.out.printf("Access policy %s allows these permissions: %s", permission.getId(), + permission.getAccessPolicy().getPermissions()); + } + // END: com.azure.storage.queue.queueClient.getAccessPolicy + } + + /** + * Generates a code sample for using {@link QueueClient#setAccessPolicy(List)} + */ + public void setAccessPolicy() { + // BEGIN: com.azure.storage.queue.QueueClient.setAccessPolicy#List + QueueAccessPolicy accessPolicy = new QueueAccessPolicy().setPermissions("r") + .setStartsOn(OffsetDateTime.now(ZoneOffset.UTC)) + .setExpiresOn(OffsetDateTime.now(ZoneOffset.UTC).plusDays(10)); + QueueSignedIdentifier permission = new QueueSignedIdentifier().setId("mypolicy").setAccessPolicy(accessPolicy); + client.setAccessPolicy(Collections.singletonList(permission)); + System.out.println("Setting access policies completed."); + // END: com.azure.storage.queue.QueueClient.setAccessPolicy#List + } + + /** + * Generates a code sample for using {@link QueueClient#setAccessPolicyWithResponse(List, Duration, Context)} + */ + public void setAccessPolicyWithResponse() { + + // BEGIN: com.azure.storage.queue.queueClient.setAccessPolicyWithResponse#List-Duration-Context + QueueAccessPolicy accessPolicy = new QueueAccessPolicy().setPermissions("r") + .setStartsOn(OffsetDateTime.now(ZoneOffset.UTC)) + .setExpiresOn(OffsetDateTime.now(ZoneOffset.UTC).plusDays(10)); + QueueSignedIdentifier permission = new QueueSignedIdentifier().setId("mypolicy").setAccessPolicy(accessPolicy); + Response response = client.setAccessPolicyWithResponse(Collections.singletonList(permission), + Duration.ofSeconds(1), new Context(key1, value1)); + System.out.printf("Setting access policies completed with status code %d", response.getStatusCode()); + // END: com.azure.storage.queue.queueClient.setAccessPolicyWithResponse#List-Duration-Context + } + + /** + * Generates a code sample for using {@link QueueClient#clearMessages()} + */ + public void clearMessages() { + + // BEGIN: com.azure.storage.queue.queueClient.clearMessages + client.clearMessages(); + System.out.println("Clearing messages completed."); + // END: com.azure.storage.queue.queueClient.clearMessages + } + + /** + * Generates a code sample for using {@link QueueClient#clearMessagesWithResponse(Duration, Context)} + */ + public void clearMessagesWithResponse() { + + // BEGIN: com.azure.storage.queue.queueClient.clearMessagesWithResponse#duration-context + Response response = client.clearMessagesWithResponse(Duration.ofSeconds(1), new Context(key1, value1)); + System.out.printf("Clearing messages completed with status code %d", response.getStatusCode()); + // END: com.azure.storage.queue.queueClient.clearMessagesWithResponse#duration-context + } + + /** + * Generates a code sample for using {@link QueueClient#getQueueName()} + */ + public void getName() { + // BEGIN: com.azure.storage.queue.queueClient.getQueueName + String queueName = client.getQueueName(); + System.out.println("The name of the queue is " + queueName); + // END: com.azure.storage.queue.queueClient.getQueueName + } + + /** + * Code snippet for {@link QueueClient#generateSas(QueueServiceSasSignatureValues)} + */ + public void generateSas() { + // BEGIN: com.azure.storage.queue.QueueClient.generateSas#QueueServiceSasSignatureValues + OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1); + QueueSasPermission permission = new QueueSasPermission().setReadPermission(true); + + QueueServiceSasSignatureValues values = new QueueServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + client.generateSas(values); // Client must be authenticated via StorageSharedKeyCredential + // END: com.azure.storage.queue.QueueClient.generateSas#QueueServiceSasSignatureValues + } + + /** + * Code snippet for {@link QueueClient#generateSas(QueueServiceSasSignatureValues, Context)} + */ + public void generateSasWithContext() { + // BEGIN: com.azure.storage.queue.QueueClient.generateSas#QueueServiceSasSignatureValues-Context + OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1); + QueueSasPermission permission = new QueueSasPermission().setReadPermission(true); + + QueueServiceSasSignatureValues values = new QueueServiceSasSignatureValues(expiryTime, permission) + .setStartTime(OffsetDateTime.now()); + + // Client must be authenticated via StorageSharedKeyCredential + client.generateSas(values, new Context("key", "value")); + // END: com.azure.storage.queue.QueueClient.generateSas#QueueServiceSasSignatureValues-Context + } + + /** + * Generates a code sample for using {@link QueueClient#createIfNotExists()} and + * {@link QueueClient#createIfNotExistsWithResponse(Map, Duration, Context)} + */ + public void createQueueIfNotExistsCodeSnippets() { + // BEGIN: com.azure.storage.queue.queueClient.createIfNotExists + boolean result = client.createIfNotExists(); + System.out.println("Queue created: " + result); + // END: com.azure.storage.queue.queueClient.createIfNotExists + + // BEGIN: com.azure.storage.queue.queueClient.createIfNotExistsWithResponse#map-duration-context + Response response = client.createIfNotExistsWithResponse(Collections.singletonMap("queue", "metadataMap"), + Duration.ofSeconds(1), new Context(key1, value1)); + if (response.getStatusCode() == 409) { + System.out.println("Already existed."); + } else { + System.out.printf("Create completed with status %d%n", response.getStatusCode()); + } + // END: com.azure.storage.queue.queueClient.createIfNotExistsWithResponse#map-duration-context + } + + /** + * Generates a code sample for using {@link QueueClient#deleteIfExists()} and + * {@link QueueClient#deleteIfExistsWithResponse(Duration, Context)} + */ + public void deleteQueueIfExistsCodeSnippets() { + + // BEGIN: com.azure.storage.queue.queueClient.deleteIfExists + client.deleteIfExists(); + System.out.println("Complete deleting the queue."); + // END: com.azure.storage.queue.queueClient.deleteIfExists + + // BEGIN: com.azure.storage.queue.queueClient.deleteIfExistsWithResponse#duration-context + Response response = client.deleteIfExistsWithResponse(Duration.ofSeconds(1), new Context(key1, value1)); + if (response.getStatusCode() == 404) { + System.out.println("Does not exist."); + } else { + System.out.printf("Delete completed with status %d%n", response.getStatusCode()); + } + // END: com.azure.storage.queue.queueClient.deleteIfExistsWithResponse#duration-context + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample6/v1/QueueServiceAsyncJavaDocCodeSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample6/v1/QueueServiceAsyncJavaDocCodeSamples.java new file mode 100644 index 000000000000..5d60ac064c64 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample6/v1/QueueServiceAsyncJavaDocCodeSamples.java @@ -0,0 +1,312 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.storage.queue; + +import com.azure.core.util.Context; +import com.azure.storage.common.StorageSharedKeyCredential; +import com.azure.storage.common.sas.AccountSasPermission; +import com.azure.storage.common.sas.AccountSasResourceType; +import com.azure.storage.common.sas.AccountSasService; +import com.azure.storage.common.sas.AccountSasSignatureValues; +import com.azure.storage.queue.models.QueueServiceProperties; +import com.azure.storage.queue.models.QueueServiceStatistics; +import com.azure.storage.queue.models.QueuesSegmentOptions; + +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Collections; +import java.util.Map; + +/** + * Contains code snippets when generating javadocs through doclets for {@link QueueServiceClient} and {@link + * QueueServiceAsyncClient}. + */ +public class QueueServiceAsyncJavaDocCodeSamples { + + private QueueServiceAsyncClient client = createAsyncClientWithSASToken(); + + /** + * Generates code sample for creating a {@link QueueServiceAsyncClient}. + */ + public void buildQueueServiceAsyncClient() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.instantiation + QueueServiceAsyncClient client = new QueueServiceClientBuilder() + .connectionString("connectionstring") + .endpoint("endpoint") + .buildAsyncClient(); + // END: com.azure.storage.queue.queueServiceAsyncClient.instantiation + } + + /** + * Generates code sample for creating a {@link QueueServiceAsyncClient} with SAS token. + * + * @return An instance of {@link QueueServiceAsyncClient} + */ + public QueueServiceAsyncClient createAsyncClientWithSASToken() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.instantiation.sastoken + QueueServiceAsyncClient client = new QueueServiceClientBuilder() + .endpoint("https://{accountName}.queue.core.windows.net?{SASToken}") + .buildAsyncClient(); + // END: com.azure.storage.queue.queueServiceAsyncClient.instantiation.sastoken + return client; + } + + /** + * Generates code sample for creating a {@link QueueServiceAsyncClient} with SAS token. + * + * @return An instance of {@link QueueServiceAsyncClient} + */ + public QueueServiceAsyncClient createAsyncClientWithCredential() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.instantiation.credential + QueueServiceAsyncClient client = new QueueServiceClientBuilder() + .endpoint("https://{accountName}.queue.core.windows.net") + .sasToken("{SASTokenQueryParams}") + .buildAsyncClient(); + // END: com.azure.storage.queue.queueServiceAsyncClient.instantiation.credential + return client; + } + + /** + * Generates code sample for creating a {@link QueueServiceAsyncClient} with {@code connectionString} which turns + * into {@link StorageSharedKeyCredential} + * + * @return An instance of {@link QueueServiceAsyncClient} + */ + public QueueServiceAsyncClient createAsyncClientWithConnectionString() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.instantiation.connectionstring + String connectionString = "DefaultEndpointsProtocol=https;AccountName={name};" + + "AccountKey={key};EndpointSuffix={core.windows.net}"; + QueueServiceAsyncClient client = new QueueServiceClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + // END: com.azure.storage.queue.queueServiceAsyncClient.instantiation.connectionstring + return client; + } + + /** + * Generates a code sample for using {@link QueueServiceAsyncClient#createQueue(String)} + */ + public void createQueueAsync() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.createQueue#string + client.createQueue("myqueue").subscribe( + response -> { + }, + error -> System.err.print(error.toString()), + () -> System.out.println("Complete creating the queue!") + ); + // END: com.azure.storage.queue.queueServiceAsyncClient.createQueue#string + } + + /** + * Generates a code sample for using {@link QueueServiceAsyncClient#createQueueWithResponse(String, Map)} + */ + public void createQueueAsyncMaxOverload() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.createQueueWithResponse#string-map + client.createQueueWithResponse("myqueue", Collections.singletonMap("queue", "metadata")) + .subscribe( + response -> System.out.printf("Creating the queue with status code %d", response.getStatusCode()), + error -> System.err.print(error.toString()), + () -> System.out.println("Complete creating the queue!") + ); + // END: com.azure.storage.queue.queueServiceAsyncClient.createQueueWithResponse#string-map + } + + /** + * Generates a code sample for using {@link QueueServiceAsyncClient#listQueues()} + */ + public void listQueuesAsync() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.listQueues + client.listQueues().subscribe( + queueItem -> System.out.printf("Queue %s exists in the account", queueItem.getName()), + error -> System.err.print(error.toString()), + () -> System.out.println("Complete listing the queues!") + ); + // END: com.azure.storage.queue.queueServiceAsyncClient.listQueues + } + + /** + * Generates a code sample for using {@link QueueServiceAsyncClient#listQueues(QueuesSegmentOptions)} + */ + public void listQueuesAsyncWithOverload() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.listQueues#queueSergmentOptions + client.listQueues(new QueuesSegmentOptions().setPrefix("azure")).subscribe( + queueItem -> System.out.printf("Queue %s exists in the account and has metadata %s", + queueItem.getName(), queueItem.getMetadata()), + error -> System.err.print(error.toString()), + () -> System.out.println("Complete listing the queues!") + ); + // END: com.azure.storage.queue.queueServiceAsyncClient.listQueues#queueSergmentOptions + } + + /** + * Generates a code sample for using {@link QueueServiceAsyncClient#deleteQueue(String)} + */ + public void deleteQueueAsync() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.deleteQueue#string + client.deleteQueue("myshare").subscribe( + response -> System.out.println("Deleting the queue completed.") + ); + // END: com.azure.storage.queue.queueServiceAsyncClient.deleteQueue#string + } + + /** + * Generates a code sample for using {@link QueueServiceAsyncClient#deleteQueueWithResponse(String)} + */ + public void deleteQueueWithResponse() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.deleteQueueWithResponse#string + client.deleteQueueWithResponse("myshare").subscribe( + response -> System.out.println("Deleting the queue completed with status code: " + response.getStatusCode()) + ); + // END: com.azure.storage.queue.queueServiceAsyncClient.deleteQueueWithResponse#string + } + + /** + * Generates a code sample for using {@link QueueServiceAsyncClient#getProperties()} + */ + public void getPropertiesAsync() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.getProperties + client.getProperties() + .subscribe(properties -> { + System.out.printf("Hour metrics enabled: %b, Minute metrics enabled: %b", + properties.getHourMetrics().isEnabled(), properties.getMinuteMetrics().isEnabled()); + }); + // END: com.azure.storage.queue.queueServiceAsyncClient.getProperties + } + + + /** + * Generates a code sample for using {@link QueueServiceAsyncClient#getPropertiesWithResponse()} + */ + public void getPropertiesWithResponse() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.getPropertiesWithResponse + client.getPropertiesWithResponse() + .subscribe(response -> { + QueueServiceProperties properties = response.getValue(); + System.out.printf("Hour metrics enabled: %b, Minute metrics enabled: %b", + properties.getHourMetrics().isEnabled(), properties.getMinuteMetrics().isEnabled()); + }); + // END: com.azure.storage.queue.queueServiceAsyncClient.getPropertiesWithResponse + } + + /** + * Generates a code sample for using {@link QueueServiceAsyncClient#setProperties(QueueServiceProperties)} + */ + public void setPropertiesAsync() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.setProperties#QueueServiceProperties + QueueServiceProperties properties = client.getProperties().block(); + client.setProperties(properties) + .doOnSuccess(response -> System.out.println("Setting Queue service properties completed.")); + // END: com.azure.storage.queue.queueServiceAsyncClient.setProperties#QueueServiceProperties + } + + + /** + * Generates a code sample for using {@link QueueServiceAsyncClient#setPropertiesWithResponse(QueueServiceProperties)} + */ + public void setPropertiesWithResponse() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.setPropertiesWithResponse#QueueServiceProperties + QueueServiceProperties properties = client.getProperties().block(); + client.setPropertiesWithResponse(properties) + .subscribe(response -> System.out.printf("Setting Queue service properties completed with status code %d", + response.getStatusCode())); + // END: com.azure.storage.queue.queueServiceAsyncClient.setPropertiesWithResponse#QueueServiceProperties + } + + /** + * Generates a code sample for using {@link QueueServiceAsyncClient#setProperties(QueueServiceProperties)} with + * metrics enabled. + */ + public void setPropertiesEnableMetrics() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.setPropertiesEnableMetrics#QueueServiceProperties + QueueServiceProperties properties = client.getProperties().block(); + properties.getMinuteMetrics().setEnabled(true); + properties.getHourMetrics().setEnabled(true); + client.setProperties(properties).subscribe( + response -> System.out.println("Setting Queue service properties completed.")); + // END: com.azure.storage.queue.queueServiceAsyncClient.setPropertiesEnableMetrics#QueueServiceProperties + } + + /** + * Generates a code sample for using {@link QueueServiceAsyncClient#setPropertiesWithResponse(QueueServiceProperties)} + * with metrics enabled. + */ + public void setPropertiesAsyncEnableMetrics() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.setPropertiesWithResponseEnableMetrics#QueueServiceProperties + QueueServiceProperties properties = client.getProperties().block(); + properties.getMinuteMetrics().setEnabled(true); + properties.getHourMetrics().setEnabled(true); + client.setPropertiesWithResponse(properties) + .subscribe(response -> System.out.printf("Setting Queue service properties completed with status code %d", + response.getStatusCode())); + // END: com.azure.storage.queue.queueServiceAsyncClient.setPropertiesWithResponseEnableMetrics#QueueServiceProperties + } + + /** + * Generates a code sample for using {@link QueueServiceAsyncClient#getStatistics()} + */ + public void getStatisticsAsync() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.getStatistics + client.getStatistics() + .subscribe(stats -> { + System.out.printf("Geo replication status: %s, Last synced: %s", + stats.getGeoReplication().getStatus(), stats.getGeoReplication().getLastSyncTime()); + }); + // END: com.azure.storage.queue.queueServiceAsyncClient.getStatistics + } + + /** + * Generates a code sample for using {@link QueueServiceAsyncClient#getStatisticsWithResponse()} + */ + public void getStatisticsWithResponse() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.getStatisticsWithResponse + client.getStatisticsWithResponse() + .subscribe(response -> { + QueueServiceStatistics stats = response.getValue(); + System.out.printf("Geo replication status: %s, Last synced: %s", + stats.getGeoReplication().getStatus(), stats.getGeoReplication().getLastSyncTime()); + }); + // END: com.azure.storage.queue.queueServiceAsyncClient.getStatisticsWithResponse + } + + /** + * Code snippet for {@link QueueServiceAsyncClient#generateAccountSas(AccountSasSignatureValues)} + */ + public void generateAccountSas() { + QueueServiceAsyncClient queueServiceAsyncClient = createAsyncClientWithCredential(); + // BEGIN: com.azure.storage.queue.QueueServiceAsyncClient.generateAccountSas#AccountSasSignatureValues + AccountSasPermission permissions = new AccountSasPermission() + .setListPermission(true) + .setReadPermission(true); + AccountSasResourceType resourceTypes = new AccountSasResourceType().setContainer(true).setObject(true); + AccountSasService services = new AccountSasService().setQueueAccess(true).setFileAccess(true); + OffsetDateTime expiryTime = OffsetDateTime.now().plus(Duration.ofDays(2)); + + AccountSasSignatureValues sasValues = + new AccountSasSignatureValues(expiryTime, permissions, services, resourceTypes); + + // Client must be authenticated via StorageSharedKeyCredential + String sas = queueServiceAsyncClient.generateAccountSas(sasValues); + // END: com.azure.storage.queue.QueueServiceAsyncClient.generateAccountSas#AccountSasSignatureValues + } + + /** + * Code snippet for {@link QueueServiceAsyncClient#generateAccountSas(AccountSasSignatureValues, Context)} + */ + public void generateAccountSasWithContext() { + QueueServiceAsyncClient queueServiceAsyncClient = createAsyncClientWithCredential(); + // BEGIN: com.azure.storage.queue.QueueServiceAsyncClient.generateAccountSas#AccountSasSignatureValues-Context + AccountSasPermission permissions = new AccountSasPermission() + .setListPermission(true) + .setReadPermission(true); + AccountSasResourceType resourceTypes = new AccountSasResourceType().setContainer(true).setObject(true); + AccountSasService services = new AccountSasService().setQueueAccess(true).setFileAccess(true); + OffsetDateTime expiryTime = OffsetDateTime.now().plus(Duration.ofDays(2)); + + AccountSasSignatureValues sasValues = + new AccountSasSignatureValues(expiryTime, permissions, services, resourceTypes); + + // Client must be authenticated via StorageSharedKeyCredential + String sas = queueServiceAsyncClient.generateAccountSas(sasValues, new Context("key", "value")); + // END: com.azure.storage.queue.QueueServiceAsyncClient.generateAccountSas#AccountSasSignatureValues-Context + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample6/v2/QueueServiceAsyncJavaDocCodeSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample6/v2/QueueServiceAsyncJavaDocCodeSamples.java new file mode 100644 index 000000000000..5d60ac064c64 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample6/v2/QueueServiceAsyncJavaDocCodeSamples.java @@ -0,0 +1,312 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.storage.queue; + +import com.azure.core.util.Context; +import com.azure.storage.common.StorageSharedKeyCredential; +import com.azure.storage.common.sas.AccountSasPermission; +import com.azure.storage.common.sas.AccountSasResourceType; +import com.azure.storage.common.sas.AccountSasService; +import com.azure.storage.common.sas.AccountSasSignatureValues; +import com.azure.storage.queue.models.QueueServiceProperties; +import com.azure.storage.queue.models.QueueServiceStatistics; +import com.azure.storage.queue.models.QueuesSegmentOptions; + +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Collections; +import java.util.Map; + +/** + * Contains code snippets when generating javadocs through doclets for {@link QueueServiceClient} and {@link + * QueueServiceAsyncClient}. + */ +public class QueueServiceAsyncJavaDocCodeSamples { + + private QueueServiceAsyncClient client = createAsyncClientWithSASToken(); + + /** + * Generates code sample for creating a {@link QueueServiceAsyncClient}. + */ + public void buildQueueServiceAsyncClient() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.instantiation + QueueServiceAsyncClient client = new QueueServiceClientBuilder() + .connectionString("connectionstring") + .endpoint("endpoint") + .buildAsyncClient(); + // END: com.azure.storage.queue.queueServiceAsyncClient.instantiation + } + + /** + * Generates code sample for creating a {@link QueueServiceAsyncClient} with SAS token. + * + * @return An instance of {@link QueueServiceAsyncClient} + */ + public QueueServiceAsyncClient createAsyncClientWithSASToken() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.instantiation.sastoken + QueueServiceAsyncClient client = new QueueServiceClientBuilder() + .endpoint("https://{accountName}.queue.core.windows.net?{SASToken}") + .buildAsyncClient(); + // END: com.azure.storage.queue.queueServiceAsyncClient.instantiation.sastoken + return client; + } + + /** + * Generates code sample for creating a {@link QueueServiceAsyncClient} with SAS token. + * + * @return An instance of {@link QueueServiceAsyncClient} + */ + public QueueServiceAsyncClient createAsyncClientWithCredential() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.instantiation.credential + QueueServiceAsyncClient client = new QueueServiceClientBuilder() + .endpoint("https://{accountName}.queue.core.windows.net") + .sasToken("{SASTokenQueryParams}") + .buildAsyncClient(); + // END: com.azure.storage.queue.queueServiceAsyncClient.instantiation.credential + return client; + } + + /** + * Generates code sample for creating a {@link QueueServiceAsyncClient} with {@code connectionString} which turns + * into {@link StorageSharedKeyCredential} + * + * @return An instance of {@link QueueServiceAsyncClient} + */ + public QueueServiceAsyncClient createAsyncClientWithConnectionString() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.instantiation.connectionstring + String connectionString = "DefaultEndpointsProtocol=https;AccountName={name};" + + "AccountKey={key};EndpointSuffix={core.windows.net}"; + QueueServiceAsyncClient client = new QueueServiceClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + // END: com.azure.storage.queue.queueServiceAsyncClient.instantiation.connectionstring + return client; + } + + /** + * Generates a code sample for using {@link QueueServiceAsyncClient#createQueue(String)} + */ + public void createQueueAsync() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.createQueue#string + client.createQueue("myqueue").subscribe( + response -> { + }, + error -> System.err.print(error.toString()), + () -> System.out.println("Complete creating the queue!") + ); + // END: com.azure.storage.queue.queueServiceAsyncClient.createQueue#string + } + + /** + * Generates a code sample for using {@link QueueServiceAsyncClient#createQueueWithResponse(String, Map)} + */ + public void createQueueAsyncMaxOverload() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.createQueueWithResponse#string-map + client.createQueueWithResponse("myqueue", Collections.singletonMap("queue", "metadata")) + .subscribe( + response -> System.out.printf("Creating the queue with status code %d", response.getStatusCode()), + error -> System.err.print(error.toString()), + () -> System.out.println("Complete creating the queue!") + ); + // END: com.azure.storage.queue.queueServiceAsyncClient.createQueueWithResponse#string-map + } + + /** + * Generates a code sample for using {@link QueueServiceAsyncClient#listQueues()} + */ + public void listQueuesAsync() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.listQueues + client.listQueues().subscribe( + queueItem -> System.out.printf("Queue %s exists in the account", queueItem.getName()), + error -> System.err.print(error.toString()), + () -> System.out.println("Complete listing the queues!") + ); + // END: com.azure.storage.queue.queueServiceAsyncClient.listQueues + } + + /** + * Generates a code sample for using {@link QueueServiceAsyncClient#listQueues(QueuesSegmentOptions)} + */ + public void listQueuesAsyncWithOverload() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.listQueues#queueSergmentOptions + client.listQueues(new QueuesSegmentOptions().setPrefix("azure")).subscribe( + queueItem -> System.out.printf("Queue %s exists in the account and has metadata %s", + queueItem.getName(), queueItem.getMetadata()), + error -> System.err.print(error.toString()), + () -> System.out.println("Complete listing the queues!") + ); + // END: com.azure.storage.queue.queueServiceAsyncClient.listQueues#queueSergmentOptions + } + + /** + * Generates a code sample for using {@link QueueServiceAsyncClient#deleteQueue(String)} + */ + public void deleteQueueAsync() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.deleteQueue#string + client.deleteQueue("myshare").subscribe( + response -> System.out.println("Deleting the queue completed.") + ); + // END: com.azure.storage.queue.queueServiceAsyncClient.deleteQueue#string + } + + /** + * Generates a code sample for using {@link QueueServiceAsyncClient#deleteQueueWithResponse(String)} + */ + public void deleteQueueWithResponse() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.deleteQueueWithResponse#string + client.deleteQueueWithResponse("myshare").subscribe( + response -> System.out.println("Deleting the queue completed with status code: " + response.getStatusCode()) + ); + // END: com.azure.storage.queue.queueServiceAsyncClient.deleteQueueWithResponse#string + } + + /** + * Generates a code sample for using {@link QueueServiceAsyncClient#getProperties()} + */ + public void getPropertiesAsync() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.getProperties + client.getProperties() + .subscribe(properties -> { + System.out.printf("Hour metrics enabled: %b, Minute metrics enabled: %b", + properties.getHourMetrics().isEnabled(), properties.getMinuteMetrics().isEnabled()); + }); + // END: com.azure.storage.queue.queueServiceAsyncClient.getProperties + } + + + /** + * Generates a code sample for using {@link QueueServiceAsyncClient#getPropertiesWithResponse()} + */ + public void getPropertiesWithResponse() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.getPropertiesWithResponse + client.getPropertiesWithResponse() + .subscribe(response -> { + QueueServiceProperties properties = response.getValue(); + System.out.printf("Hour metrics enabled: %b, Minute metrics enabled: %b", + properties.getHourMetrics().isEnabled(), properties.getMinuteMetrics().isEnabled()); + }); + // END: com.azure.storage.queue.queueServiceAsyncClient.getPropertiesWithResponse + } + + /** + * Generates a code sample for using {@link QueueServiceAsyncClient#setProperties(QueueServiceProperties)} + */ + public void setPropertiesAsync() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.setProperties#QueueServiceProperties + QueueServiceProperties properties = client.getProperties().block(); + client.setProperties(properties) + .doOnSuccess(response -> System.out.println("Setting Queue service properties completed.")); + // END: com.azure.storage.queue.queueServiceAsyncClient.setProperties#QueueServiceProperties + } + + + /** + * Generates a code sample for using {@link QueueServiceAsyncClient#setPropertiesWithResponse(QueueServiceProperties)} + */ + public void setPropertiesWithResponse() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.setPropertiesWithResponse#QueueServiceProperties + QueueServiceProperties properties = client.getProperties().block(); + client.setPropertiesWithResponse(properties) + .subscribe(response -> System.out.printf("Setting Queue service properties completed with status code %d", + response.getStatusCode())); + // END: com.azure.storage.queue.queueServiceAsyncClient.setPropertiesWithResponse#QueueServiceProperties + } + + /** + * Generates a code sample for using {@link QueueServiceAsyncClient#setProperties(QueueServiceProperties)} with + * metrics enabled. + */ + public void setPropertiesEnableMetrics() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.setPropertiesEnableMetrics#QueueServiceProperties + QueueServiceProperties properties = client.getProperties().block(); + properties.getMinuteMetrics().setEnabled(true); + properties.getHourMetrics().setEnabled(true); + client.setProperties(properties).subscribe( + response -> System.out.println("Setting Queue service properties completed.")); + // END: com.azure.storage.queue.queueServiceAsyncClient.setPropertiesEnableMetrics#QueueServiceProperties + } + + /** + * Generates a code sample for using {@link QueueServiceAsyncClient#setPropertiesWithResponse(QueueServiceProperties)} + * with metrics enabled. + */ + public void setPropertiesAsyncEnableMetrics() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.setPropertiesWithResponseEnableMetrics#QueueServiceProperties + QueueServiceProperties properties = client.getProperties().block(); + properties.getMinuteMetrics().setEnabled(true); + properties.getHourMetrics().setEnabled(true); + client.setPropertiesWithResponse(properties) + .subscribe(response -> System.out.printf("Setting Queue service properties completed with status code %d", + response.getStatusCode())); + // END: com.azure.storage.queue.queueServiceAsyncClient.setPropertiesWithResponseEnableMetrics#QueueServiceProperties + } + + /** + * Generates a code sample for using {@link QueueServiceAsyncClient#getStatistics()} + */ + public void getStatisticsAsync() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.getStatistics + client.getStatistics() + .subscribe(stats -> { + System.out.printf("Geo replication status: %s, Last synced: %s", + stats.getGeoReplication().getStatus(), stats.getGeoReplication().getLastSyncTime()); + }); + // END: com.azure.storage.queue.queueServiceAsyncClient.getStatistics + } + + /** + * Generates a code sample for using {@link QueueServiceAsyncClient#getStatisticsWithResponse()} + */ + public void getStatisticsWithResponse() { + // BEGIN: com.azure.storage.queue.queueServiceAsyncClient.getStatisticsWithResponse + client.getStatisticsWithResponse() + .subscribe(response -> { + QueueServiceStatistics stats = response.getValue(); + System.out.printf("Geo replication status: %s, Last synced: %s", + stats.getGeoReplication().getStatus(), stats.getGeoReplication().getLastSyncTime()); + }); + // END: com.azure.storage.queue.queueServiceAsyncClient.getStatisticsWithResponse + } + + /** + * Code snippet for {@link QueueServiceAsyncClient#generateAccountSas(AccountSasSignatureValues)} + */ + public void generateAccountSas() { + QueueServiceAsyncClient queueServiceAsyncClient = createAsyncClientWithCredential(); + // BEGIN: com.azure.storage.queue.QueueServiceAsyncClient.generateAccountSas#AccountSasSignatureValues + AccountSasPermission permissions = new AccountSasPermission() + .setListPermission(true) + .setReadPermission(true); + AccountSasResourceType resourceTypes = new AccountSasResourceType().setContainer(true).setObject(true); + AccountSasService services = new AccountSasService().setQueueAccess(true).setFileAccess(true); + OffsetDateTime expiryTime = OffsetDateTime.now().plus(Duration.ofDays(2)); + + AccountSasSignatureValues sasValues = + new AccountSasSignatureValues(expiryTime, permissions, services, resourceTypes); + + // Client must be authenticated via StorageSharedKeyCredential + String sas = queueServiceAsyncClient.generateAccountSas(sasValues); + // END: com.azure.storage.queue.QueueServiceAsyncClient.generateAccountSas#AccountSasSignatureValues + } + + /** + * Code snippet for {@link QueueServiceAsyncClient#generateAccountSas(AccountSasSignatureValues, Context)} + */ + public void generateAccountSasWithContext() { + QueueServiceAsyncClient queueServiceAsyncClient = createAsyncClientWithCredential(); + // BEGIN: com.azure.storage.queue.QueueServiceAsyncClient.generateAccountSas#AccountSasSignatureValues-Context + AccountSasPermission permissions = new AccountSasPermission() + .setListPermission(true) + .setReadPermission(true); + AccountSasResourceType resourceTypes = new AccountSasResourceType().setContainer(true).setObject(true); + AccountSasService services = new AccountSasService().setQueueAccess(true).setFileAccess(true); + OffsetDateTime expiryTime = OffsetDateTime.now().plus(Duration.ofDays(2)); + + AccountSasSignatureValues sasValues = + new AccountSasSignatureValues(expiryTime, permissions, services, resourceTypes); + + // Client must be authenticated via StorageSharedKeyCredential + String sas = queueServiceAsyncClient.generateAccountSas(sasValues, new Context("key", "value")); + // END: com.azure.storage.queue.QueueServiceAsyncClient.generateAccountSas#AccountSasSignatureValues-Context + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample7/v1/QueueServiceJavaDocCodeSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample7/v1/QueueServiceJavaDocCodeSamples.java new file mode 100644 index 000000000000..4148b925509a --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample7/v1/QueueServiceJavaDocCodeSamples.java @@ -0,0 +1,393 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.storage.queue; + +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.storage.common.StorageSharedKeyCredential; +import com.azure.storage.common.sas.AccountSasPermission; +import com.azure.storage.common.sas.AccountSasResourceType; +import com.azure.storage.common.sas.AccountSasService; +import com.azure.storage.common.sas.AccountSasSignatureValues; +import com.azure.storage.queue.models.PeekedMessageItem; +import com.azure.storage.queue.models.QueueMessageDecodingError; +import com.azure.storage.queue.models.QueueMessageItem; +import com.azure.storage.queue.models.QueueRetentionPolicy; +import com.azure.storage.queue.models.QueueServiceProperties; +import com.azure.storage.queue.models.QueueServiceStatistics; +import com.azure.storage.queue.models.QueuesSegmentOptions; + +import reactor.core.publisher.Mono; + +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Collections; +import java.util.Map; +import java.util.function.Consumer; +import java.util.function.Function; + +/** + * Contains code snippets when generating javadocs through doclets for {@link QueueServiceClient} and {@link + * QueueServiceAsyncClient}. + */ +public class QueueServiceJavaDocCodeSamples { + + private QueueServiceClient client = createClientWithSASToken(); + private String key1 = "key1"; + private String value1 = "val1"; + + /** + * Generates code sample for creating a {@link QueueServiceClient}. + */ + public void buildQueueServiceClient() { + // BEGIN: com.azure.storage.queue.queueServiceClient.instantiation + QueueServiceClient client = new QueueServiceClientBuilder() + .connectionString("connectionstring") + .endpoint("endpoint") + .buildClient(); + // END: com.azure.storage.queue.queueServiceClient.instantiation + } + + /** + * Generates code sample for creating a {@link QueueServiceClient} with SAS token. + * + * @return An instance of {@link QueueServiceClient} + */ + public QueueServiceClient createClientWithSASToken() { + // BEGIN: com.azure.storage.queue.queueServiceClient.instantiation.sastoken + QueueServiceClient client = new QueueServiceClientBuilder() + .endpoint("https://${accountName}.queue.core.windows.net?${SASToken}") + .buildClient(); + // END: com.azure.storage.queue.queueServiceClient.instantiation.sastoken + return client; + } + + /** + * Generates code sample for creating a {@link QueueServiceClient} with SAS token. + * + * @return An instance of {@link QueueServiceClient} + */ + public QueueServiceClient createClientWithCredential() { + // BEGIN: com.azure.storage.queue.queueServiceClient.instantiation.credential + QueueServiceClient client = new QueueServiceClientBuilder() + .endpoint("https://${accountName}.queue.core.windows.net") + .sasToken("{SASTokenQueryParams}") + .buildClient(); + // END: com.azure.storage.queue.queueServiceClient.instantiation.credential + return client; + } + + /** + * Generates code sample for creating a {@link QueueServiceClient} with {@code connectionString} which turns into + * {@link StorageSharedKeyCredential} + * + * @return An instance of {@link QueueServiceClient} + */ + public QueueServiceClient createClientWithConnectionString() { + // BEGIN: com.azure.storage.queue.queueServiceClient.instantiation.connectionstring + String connectionString = "DefaultEndpointsProtocol=https;AccountName={name};" + + "AccountKey={key};EndpointSuffix={core.windows.net}"; + QueueServiceClient client = new QueueServiceClientBuilder() + .connectionString(connectionString) + .buildClient(); + // END: com.azure.storage.queue.queueServiceClient.instantiation.connectionstring + return client; + } + + /** + * Generates code sample for creating a {@link QueueServiceClient} + * with {@link QueueServiceClientBuilder#processMessageDecodingErrorAsync(Function)}. + * + * @return An instance of {@link QueueServiceClient} + */ + public QueueServiceClient createClientWithDecodingFailedAsyncHandler() { + // BEGIN: com.azure.storage.queue.QueueServiceClientBuilder#processMessageDecodingErrorAsyncHandler + String connectionString = "DefaultEndpointsProtocol=https;AccountName={name};" + + "AccountKey={key};EndpointSuffix={core.windows.net}"; + + Function> processMessageDecodingErrorHandler = + (queueMessageDecodingFailure) -> { + QueueMessageItem queueMessageItem = queueMessageDecodingFailure.getQueueMessageItem(); + PeekedMessageItem peekedMessageItem = queueMessageDecodingFailure.getPeekedMessageItem(); + if (queueMessageItem != null) { + System.out.printf("Received badly encoded message, messageId=%s, messageBody=%s", + queueMessageItem.getMessageId(), + queueMessageItem.getBody().toString()); + return queueMessageDecodingFailure + .getQueueAsyncClient() + .deleteMessage(queueMessageItem.getMessageId(), queueMessageItem.getPopReceipt()); + } else if (peekedMessageItem != null) { + System.out.printf("Peeked badly encoded message, messageId=%s, messageBody=%s", + peekedMessageItem.getMessageId(), + peekedMessageItem.getBody().toString()); + return Mono.empty(); + } else { + return Mono.empty(); + } + }; + + QueueServiceClient client = new QueueServiceClientBuilder() + .connectionString(connectionString) + .processMessageDecodingErrorAsync(processMessageDecodingErrorHandler) + .buildClient(); + // END: com.azure.storage.queue.QueueServiceClientBuilder#processMessageDecodingErrorAsyncHandler + return client; + } + + /** + * Generates code sample for creating a {@link QueueServiceClient} + * with {@link QueueServiceClientBuilder#processMessageDecodingError(Consumer)}. + * + * @return An instance of {@link QueueServiceClient} + */ + public QueueServiceClient createClientWithDecodingFailedHandler() { + // BEGIN: com.azure.storage.queue.QueueServiceClientBuilder#processMessageDecodingErrorHandler + String connectionString = "DefaultEndpointsProtocol=https;AccountName={name};" + + "AccountKey={key};EndpointSuffix={core.windows.net}"; + + Consumer processMessageDecodingErrorHandler = + (queueMessageDecodingFailure) -> { + QueueMessageItem queueMessageItem = queueMessageDecodingFailure.getQueueMessageItem(); + PeekedMessageItem peekedMessageItem = queueMessageDecodingFailure.getPeekedMessageItem(); + if (queueMessageItem != null) { + System.out.printf("Received badly encoded message, messageId=%s, messageBody=%s", + queueMessageItem.getMessageId(), + queueMessageItem.getBody().toString()); + queueMessageDecodingFailure + .getQueueClient() + .deleteMessage(queueMessageItem.getMessageId(), queueMessageItem.getPopReceipt()); + } else if (peekedMessageItem != null) { + System.out.printf("Peeked badly encoded message, messageId=%s, messageBody=%s", + peekedMessageItem.getMessageId(), + peekedMessageItem.getBody().toString()); + } + }; + + QueueServiceClient client = new QueueServiceClientBuilder() + .connectionString(connectionString) + .processMessageDecodingError(processMessageDecodingErrorHandler) + .buildClient(); + // END: com.azure.storage.queue.QueueServiceClientBuilder#processMessageDecodingErrorHandler + return client; + } + + /** + * Generates a code sample for using {@link QueueServiceClient#createQueue(String)} + */ + public void createQueue() { + // BEGIN: com.azure.storage.queue.queueServiceClient.createQueue#string + client.createQueue("myqueue"); + System.out.println("Complete creating queue."); + // END: com.azure.storage.queue.queueServiceClient.createQueue#string + } + + /** + * Generates a code sample for using {@link QueueServiceClient#createQueueWithResponse(String, Map, Duration, + * Context)} + */ + public void createQueueMaxOverload() { + // BEGIN: com.azure.storage.queue.queueServiceClient.createQueueWithResponse#string-map-duration-context + Response response = client.createQueueWithResponse("myqueue", + Collections.singletonMap("queue", "metadata"), Duration.ofSeconds(1), new Context(key1, value1)); + System.out.println("Complete creating queue with status code: " + response.getStatusCode()); + // END: com.azure.storage.queue.queueServiceClient.createQueueWithResponse#string-map-duration-context + } + + /** + * Generates a code sample for using {@link QueueServiceClient#listQueues()} + */ + public void listQueues() { + // BEGIN: com.azure.storage.queue.queueServiceClient.listQueues + client.listQueues().forEach( + queueItem -> System.out.printf("Queue %s exists in the account", queueItem.getName()) + ); + // END: com.azure.storage.queue.queueServiceClient.listQueues + } + + /** + * Generates a code sample for using {@link QueueServiceClient#listQueues(QueuesSegmentOptions, Duration, Context)} + * )} + */ + public void listQueuesWithOverload() { + // BEGIN: com.azure.storage.queue.queueServiceClient.listQueues#queueSergmentOptions-duration-context + client.listQueues(new QueuesSegmentOptions().setPrefix("azure"), Duration.ofSeconds(1), + new Context(key1, value1)).forEach( + queueItem -> System.out.printf("Queue %s exists in the account and has metadata %s", + queueItem.getName(), queueItem.getMetadata()) + ); + // END: com.azure.storage.queue.queueServiceClient.listQueues#queueSergmentOptions-duration-context + } + + /** + * Generates a code sample for using {@link QueueServiceClient#deleteQueue(String)} + */ + public void deleteQueue() { + // BEGIN: com.azure.storage.queue.queueServiceClient.deleteQueue#string + client.deleteQueue("myqueue"); + System.out.println("Complete deleting the queue."); + // END: com.azure.storage.queue.queueServiceClient.deleteQueue#string + } + + /** + * Generates a code sample for using {@link QueueServiceClient#deleteQueueWithResponse(String, Duration, Context)} + */ + public void deleteQueueWithResponse() { + // BEGIN: com.azure.storage.queue.queueServiceClient.deleteQueueWithResponse#string-duration-context + Response response = client.deleteQueueWithResponse("myqueue", Duration.ofSeconds(1), + new Context(key1, value1)); + System.out.println("Complete deleting the queue with status code: " + response.getStatusCode()); + // END: com.azure.storage.queue.queueServiceClient.deleteQueueWithResponse#string-duration-context + } + + /** + * Generates a code sample for using {@link QueueServiceClient#getProperties()} + */ + public void getProperties() { + // BEGIN: com.azure.storage.queue.queueServiceClient.getProperties + QueueServiceProperties properties = client.getProperties(); + System.out.printf("Hour metrics enabled: %b, Minute metrics enabled: %b", + properties.getHourMetrics().isEnabled(), properties.getMinuteMetrics().isEnabled()); + // END: com.azure.storage.queue.queueServiceClient.getProperties + } + + /** + * Generates a code sample for using {@link QueueServiceClient#getPropertiesWithResponse(Duration, Context)} + */ + public void getPropertiesWithResponse() { + // BEGIN: com.azure.storage.queue.queueServiceClient.getPropertiesWithResponse#duration-context + QueueServiceProperties properties = client.getPropertiesWithResponse(Duration.ofSeconds(1), + new Context(key1, value1)).getValue(); + System.out.printf("Hour metrics enabled: %b, Minute metrics enabled: %b", + properties.getHourMetrics().isEnabled(), properties.getMinuteMetrics().isEnabled()); + // END: com.azure.storage.queue.queueServiceClient.getPropertiesWithResponse#duration-context + } + + /** + * Generates a code sample for using {@link QueueServiceClient#setProperties(QueueServiceProperties)} + */ + public void setProperties() { + // BEGIN: com.azure.storage.queue.queueServiceClient.setProperties#QueueServiceProperties + QueueServiceProperties properties = client.getProperties(); + properties.setCors(Collections.emptyList()); + + client.setProperties(properties); + System.out.println("Setting Queue service properties completed."); + // END: com.azure.storage.queue.queueServiceClient.setProperties#QueueServiceProperties + } + + /** + * Generates a code sample for using {@link QueueServiceClient#setPropertiesWithResponse(QueueServiceProperties, + * Duration, Context)} + */ + public void setPropertiesWithResponse() { + // BEGIN: com.azure.storage.queue.queueServiceClient.setPropertiesWithResponse#QueueServiceProperties-duration-context + QueueServiceProperties properties = client.getProperties(); + properties.setCors(Collections.emptyList()); + Response response = client.setPropertiesWithResponse(properties, Duration.ofSeconds(1), + new Context(key1, value1)); + System.out.printf("Setting Queue service properties completed with status code %d", response.getStatusCode()); + // END: com.azure.storage.queue.queueServiceClient.setPropertiesWithResponse#QueueServiceProperties-duration-context + } + + /** + * Generates a code sample for using {@link QueueServiceClient#setPropertiesWithResponse(QueueServiceProperties, + * Duration, Context)} with metrics enabled. + */ + public void setPropertiesWithResponseEnableMetrics() { + // BEGIN: com.azure.storage.queue.queueServiceClient.setPropertiesWithResponseEnableMetrics#QueueServiceProperties-duration-context + QueueServiceProperties properties = client.getProperties(); + properties.getMinuteMetrics().setEnabled(true); + properties.getMinuteMetrics().setIncludeApis(true); + properties.getMinuteMetrics().setRetentionPolicy(new QueueRetentionPolicy().setDays(7).setEnabled(true)); + properties.getHourMetrics().setEnabled(true); + properties.getHourMetrics().setIncludeApis(true); + properties.getHourMetrics().setRetentionPolicy(new QueueRetentionPolicy().setDays(7).setEnabled(true)); + Response response = client.setPropertiesWithResponse(properties, Duration.ofSeconds(1), + new Context(key1, value1)); + System.out.printf("Setting Queue service properties completed with status code %d", response.getStatusCode()); + // END: com.azure.storage.queue.queueServiceClient.setPropertiesWithResponseEnableMetrics#QueueServiceProperties-duration-context + } + + /** + * Generates a code sample for using {@link QueueServiceClient#setProperties(QueueServiceProperties)} with metrics + * enabled. + */ + public void setPropertiesEnableMetrics() { + // BEGIN: com.azure.storage.queue.queueServiceClient.setPropertiesEnableMetrics#QueueServiceProperties + QueueServiceProperties properties = client.getProperties(); + properties.getMinuteMetrics().setEnabled(true); + properties.getMinuteMetrics().setIncludeApis(true); + properties.getMinuteMetrics().setRetentionPolicy(new QueueRetentionPolicy().setDays(7).setEnabled(true)); + properties.getHourMetrics().setEnabled(true); + properties.getHourMetrics().setIncludeApis(true); + properties.getHourMetrics().setRetentionPolicy(new QueueRetentionPolicy().setDays(7).setEnabled(true)); + client.setProperties(properties); + System.out.println("Setting Queue service properties completed."); + // END: com.azure.storage.queue.queueServiceClient.setPropertiesEnableMetrics#QueueServiceProperties + } + + /** + * Generates a code sample for using {@link QueueServiceClient#getStatistics()} + */ + public void getStatistics() { + // BEGIN: com.azure.storage.queue.queueServiceClient.getStatistics + QueueServiceStatistics stats = client.getStatistics(); + System.out.printf("Geo replication status: %s, Last synced: %s", + stats.getGeoReplication().getStatus(), stats.getGeoReplication().getLastSyncTime()); + // END: com.azure.storage.queue.queueServiceClient.getStatistics + } + + /** + * Generates a code sample for using {@link QueueServiceClient#getStatisticsWithResponse(Duration, Context)} + */ + public void getStatisticsWithResponse() { + // BEGIN: com.azure.storage.queue.queueServiceClient.getStatisticsWithResponse#duration-context + QueueServiceStatistics stats = client.getStatisticsWithResponse(Duration.ofSeconds(1), + new Context(key1, value1)).getValue(); + System.out.printf("Geo replication status: %s, Last synced: %s", + stats.getGeoReplication().getStatus(), stats.getGeoReplication().getLastSyncTime()); + // END: com.azure.storage.queue.queueServiceClient.getStatisticsWithResponse#duration-context + } + + /** + * Code snippet for {@link QueueServiceClient#generateAccountSas(AccountSasSignatureValues)} + */ + public void generateAccountSas() { + QueueServiceClient queueServiceClient = createClientWithCredential(); + // BEGIN: com.azure.storage.queue.QueueServiceClient.generateAccountSas#AccountSasSignatureValues + AccountSasPermission permissions = new AccountSasPermission() + .setListPermission(true) + .setReadPermission(true); + AccountSasResourceType resourceTypes = new AccountSasResourceType().setContainer(true).setObject(true); + AccountSasService services = new AccountSasService().setQueueAccess(true).setFileAccess(true); + OffsetDateTime expiryTime = OffsetDateTime.now().plus(Duration.ofDays(2)); + + AccountSasSignatureValues sasValues = + new AccountSasSignatureValues(expiryTime, permissions, services, resourceTypes); + + // Client must be authenticated via StorageSharedKeyCredential + String sas = queueServiceClient.generateAccountSas(sasValues); + // END: com.azure.storage.queue.QueueServiceClient.generateAccountSas#AccountSasSignatureValues + } + + /** + * Code snippet for {@link QueueServiceClient#generateAccountSas(AccountSasSignatureValues, Context)} + */ + public void generateAccountSasWithContext() { + QueueServiceClient queueServiceClient = createClientWithCredential(); + // BEGIN: com.azure.storage.queue.QueueServiceClient.generateAccountSas#AccountSasSignatureValues-Context + AccountSasPermission permissions = new AccountSasPermission() + .setListPermission(true) + .setReadPermission(true); + AccountSasResourceType resourceTypes = new AccountSasResourceType().setContainer(true).setObject(true); + AccountSasService services = new AccountSasService().setQueueAccess(true).setFileAccess(true); + OffsetDateTime expiryTime = OffsetDateTime.now().plus(Duration.ofDays(2)); + + AccountSasSignatureValues sasValues = + new AccountSasSignatureValues(expiryTime, permissions, services, resourceTypes); + + // Client must be authenticated via StorageSharedKeyCredential + String sas = queueServiceClient.generateAccountSas(sasValues, new Context("key", "value")); + // END: com.azure.storage.queue.QueueServiceClient.generateAccountSas#AccountSasSignatureValues-Context + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample7/v2/QueueServiceJavaDocCodeSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample7/v2/QueueServiceJavaDocCodeSamples.java new file mode 100644 index 000000000000..4148b925509a --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample7/v2/QueueServiceJavaDocCodeSamples.java @@ -0,0 +1,393 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.storage.queue; + +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.storage.common.StorageSharedKeyCredential; +import com.azure.storage.common.sas.AccountSasPermission; +import com.azure.storage.common.sas.AccountSasResourceType; +import com.azure.storage.common.sas.AccountSasService; +import com.azure.storage.common.sas.AccountSasSignatureValues; +import com.azure.storage.queue.models.PeekedMessageItem; +import com.azure.storage.queue.models.QueueMessageDecodingError; +import com.azure.storage.queue.models.QueueMessageItem; +import com.azure.storage.queue.models.QueueRetentionPolicy; +import com.azure.storage.queue.models.QueueServiceProperties; +import com.azure.storage.queue.models.QueueServiceStatistics; +import com.azure.storage.queue.models.QueuesSegmentOptions; + +import reactor.core.publisher.Mono; + +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Collections; +import java.util.Map; +import java.util.function.Consumer; +import java.util.function.Function; + +/** + * Contains code snippets when generating javadocs through doclets for {@link QueueServiceClient} and {@link + * QueueServiceAsyncClient}. + */ +public class QueueServiceJavaDocCodeSamples { + + private QueueServiceClient client = createClientWithSASToken(); + private String key1 = "key1"; + private String value1 = "val1"; + + /** + * Generates code sample for creating a {@link QueueServiceClient}. + */ + public void buildQueueServiceClient() { + // BEGIN: com.azure.storage.queue.queueServiceClient.instantiation + QueueServiceClient client = new QueueServiceClientBuilder() + .connectionString("connectionstring") + .endpoint("endpoint") + .buildClient(); + // END: com.azure.storage.queue.queueServiceClient.instantiation + } + + /** + * Generates code sample for creating a {@link QueueServiceClient} with SAS token. + * + * @return An instance of {@link QueueServiceClient} + */ + public QueueServiceClient createClientWithSASToken() { + // BEGIN: com.azure.storage.queue.queueServiceClient.instantiation.sastoken + QueueServiceClient client = new QueueServiceClientBuilder() + .endpoint("https://${accountName}.queue.core.windows.net?${SASToken}") + .buildClient(); + // END: com.azure.storage.queue.queueServiceClient.instantiation.sastoken + return client; + } + + /** + * Generates code sample for creating a {@link QueueServiceClient} with SAS token. + * + * @return An instance of {@link QueueServiceClient} + */ + public QueueServiceClient createClientWithCredential() { + // BEGIN: com.azure.storage.queue.queueServiceClient.instantiation.credential + QueueServiceClient client = new QueueServiceClientBuilder() + .endpoint("https://${accountName}.queue.core.windows.net") + .sasToken("{SASTokenQueryParams}") + .buildClient(); + // END: com.azure.storage.queue.queueServiceClient.instantiation.credential + return client; + } + + /** + * Generates code sample for creating a {@link QueueServiceClient} with {@code connectionString} which turns into + * {@link StorageSharedKeyCredential} + * + * @return An instance of {@link QueueServiceClient} + */ + public QueueServiceClient createClientWithConnectionString() { + // BEGIN: com.azure.storage.queue.queueServiceClient.instantiation.connectionstring + String connectionString = "DefaultEndpointsProtocol=https;AccountName={name};" + + "AccountKey={key};EndpointSuffix={core.windows.net}"; + QueueServiceClient client = new QueueServiceClientBuilder() + .connectionString(connectionString) + .buildClient(); + // END: com.azure.storage.queue.queueServiceClient.instantiation.connectionstring + return client; + } + + /** + * Generates code sample for creating a {@link QueueServiceClient} + * with {@link QueueServiceClientBuilder#processMessageDecodingErrorAsync(Function)}. + * + * @return An instance of {@link QueueServiceClient} + */ + public QueueServiceClient createClientWithDecodingFailedAsyncHandler() { + // BEGIN: com.azure.storage.queue.QueueServiceClientBuilder#processMessageDecodingErrorAsyncHandler + String connectionString = "DefaultEndpointsProtocol=https;AccountName={name};" + + "AccountKey={key};EndpointSuffix={core.windows.net}"; + + Function> processMessageDecodingErrorHandler = + (queueMessageDecodingFailure) -> { + QueueMessageItem queueMessageItem = queueMessageDecodingFailure.getQueueMessageItem(); + PeekedMessageItem peekedMessageItem = queueMessageDecodingFailure.getPeekedMessageItem(); + if (queueMessageItem != null) { + System.out.printf("Received badly encoded message, messageId=%s, messageBody=%s", + queueMessageItem.getMessageId(), + queueMessageItem.getBody().toString()); + return queueMessageDecodingFailure + .getQueueAsyncClient() + .deleteMessage(queueMessageItem.getMessageId(), queueMessageItem.getPopReceipt()); + } else if (peekedMessageItem != null) { + System.out.printf("Peeked badly encoded message, messageId=%s, messageBody=%s", + peekedMessageItem.getMessageId(), + peekedMessageItem.getBody().toString()); + return Mono.empty(); + } else { + return Mono.empty(); + } + }; + + QueueServiceClient client = new QueueServiceClientBuilder() + .connectionString(connectionString) + .processMessageDecodingErrorAsync(processMessageDecodingErrorHandler) + .buildClient(); + // END: com.azure.storage.queue.QueueServiceClientBuilder#processMessageDecodingErrorAsyncHandler + return client; + } + + /** + * Generates code sample for creating a {@link QueueServiceClient} + * with {@link QueueServiceClientBuilder#processMessageDecodingError(Consumer)}. + * + * @return An instance of {@link QueueServiceClient} + */ + public QueueServiceClient createClientWithDecodingFailedHandler() { + // BEGIN: com.azure.storage.queue.QueueServiceClientBuilder#processMessageDecodingErrorHandler + String connectionString = "DefaultEndpointsProtocol=https;AccountName={name};" + + "AccountKey={key};EndpointSuffix={core.windows.net}"; + + Consumer processMessageDecodingErrorHandler = + (queueMessageDecodingFailure) -> { + QueueMessageItem queueMessageItem = queueMessageDecodingFailure.getQueueMessageItem(); + PeekedMessageItem peekedMessageItem = queueMessageDecodingFailure.getPeekedMessageItem(); + if (queueMessageItem != null) { + System.out.printf("Received badly encoded message, messageId=%s, messageBody=%s", + queueMessageItem.getMessageId(), + queueMessageItem.getBody().toString()); + queueMessageDecodingFailure + .getQueueClient() + .deleteMessage(queueMessageItem.getMessageId(), queueMessageItem.getPopReceipt()); + } else if (peekedMessageItem != null) { + System.out.printf("Peeked badly encoded message, messageId=%s, messageBody=%s", + peekedMessageItem.getMessageId(), + peekedMessageItem.getBody().toString()); + } + }; + + QueueServiceClient client = new QueueServiceClientBuilder() + .connectionString(connectionString) + .processMessageDecodingError(processMessageDecodingErrorHandler) + .buildClient(); + // END: com.azure.storage.queue.QueueServiceClientBuilder#processMessageDecodingErrorHandler + return client; + } + + /** + * Generates a code sample for using {@link QueueServiceClient#createQueue(String)} + */ + public void createQueue() { + // BEGIN: com.azure.storage.queue.queueServiceClient.createQueue#string + client.createQueue("myqueue"); + System.out.println("Complete creating queue."); + // END: com.azure.storage.queue.queueServiceClient.createQueue#string + } + + /** + * Generates a code sample for using {@link QueueServiceClient#createQueueWithResponse(String, Map, Duration, + * Context)} + */ + public void createQueueMaxOverload() { + // BEGIN: com.azure.storage.queue.queueServiceClient.createQueueWithResponse#string-map-duration-context + Response response = client.createQueueWithResponse("myqueue", + Collections.singletonMap("queue", "metadata"), Duration.ofSeconds(1), new Context(key1, value1)); + System.out.println("Complete creating queue with status code: " + response.getStatusCode()); + // END: com.azure.storage.queue.queueServiceClient.createQueueWithResponse#string-map-duration-context + } + + /** + * Generates a code sample for using {@link QueueServiceClient#listQueues()} + */ + public void listQueues() { + // BEGIN: com.azure.storage.queue.queueServiceClient.listQueues + client.listQueues().forEach( + queueItem -> System.out.printf("Queue %s exists in the account", queueItem.getName()) + ); + // END: com.azure.storage.queue.queueServiceClient.listQueues + } + + /** + * Generates a code sample for using {@link QueueServiceClient#listQueues(QueuesSegmentOptions, Duration, Context)} + * )} + */ + public void listQueuesWithOverload() { + // BEGIN: com.azure.storage.queue.queueServiceClient.listQueues#queueSergmentOptions-duration-context + client.listQueues(new QueuesSegmentOptions().setPrefix("azure"), Duration.ofSeconds(1), + new Context(key1, value1)).forEach( + queueItem -> System.out.printf("Queue %s exists in the account and has metadata %s", + queueItem.getName(), queueItem.getMetadata()) + ); + // END: com.azure.storage.queue.queueServiceClient.listQueues#queueSergmentOptions-duration-context + } + + /** + * Generates a code sample for using {@link QueueServiceClient#deleteQueue(String)} + */ + public void deleteQueue() { + // BEGIN: com.azure.storage.queue.queueServiceClient.deleteQueue#string + client.deleteQueue("myqueue"); + System.out.println("Complete deleting the queue."); + // END: com.azure.storage.queue.queueServiceClient.deleteQueue#string + } + + /** + * Generates a code sample for using {@link QueueServiceClient#deleteQueueWithResponse(String, Duration, Context)} + */ + public void deleteQueueWithResponse() { + // BEGIN: com.azure.storage.queue.queueServiceClient.deleteQueueWithResponse#string-duration-context + Response response = client.deleteQueueWithResponse("myqueue", Duration.ofSeconds(1), + new Context(key1, value1)); + System.out.println("Complete deleting the queue with status code: " + response.getStatusCode()); + // END: com.azure.storage.queue.queueServiceClient.deleteQueueWithResponse#string-duration-context + } + + /** + * Generates a code sample for using {@link QueueServiceClient#getProperties()} + */ + public void getProperties() { + // BEGIN: com.azure.storage.queue.queueServiceClient.getProperties + QueueServiceProperties properties = client.getProperties(); + System.out.printf("Hour metrics enabled: %b, Minute metrics enabled: %b", + properties.getHourMetrics().isEnabled(), properties.getMinuteMetrics().isEnabled()); + // END: com.azure.storage.queue.queueServiceClient.getProperties + } + + /** + * Generates a code sample for using {@link QueueServiceClient#getPropertiesWithResponse(Duration, Context)} + */ + public void getPropertiesWithResponse() { + // BEGIN: com.azure.storage.queue.queueServiceClient.getPropertiesWithResponse#duration-context + QueueServiceProperties properties = client.getPropertiesWithResponse(Duration.ofSeconds(1), + new Context(key1, value1)).getValue(); + System.out.printf("Hour metrics enabled: %b, Minute metrics enabled: %b", + properties.getHourMetrics().isEnabled(), properties.getMinuteMetrics().isEnabled()); + // END: com.azure.storage.queue.queueServiceClient.getPropertiesWithResponse#duration-context + } + + /** + * Generates a code sample for using {@link QueueServiceClient#setProperties(QueueServiceProperties)} + */ + public void setProperties() { + // BEGIN: com.azure.storage.queue.queueServiceClient.setProperties#QueueServiceProperties + QueueServiceProperties properties = client.getProperties(); + properties.setCors(Collections.emptyList()); + + client.setProperties(properties); + System.out.println("Setting Queue service properties completed."); + // END: com.azure.storage.queue.queueServiceClient.setProperties#QueueServiceProperties + } + + /** + * Generates a code sample for using {@link QueueServiceClient#setPropertiesWithResponse(QueueServiceProperties, + * Duration, Context)} + */ + public void setPropertiesWithResponse() { + // BEGIN: com.azure.storage.queue.queueServiceClient.setPropertiesWithResponse#QueueServiceProperties-duration-context + QueueServiceProperties properties = client.getProperties(); + properties.setCors(Collections.emptyList()); + Response response = client.setPropertiesWithResponse(properties, Duration.ofSeconds(1), + new Context(key1, value1)); + System.out.printf("Setting Queue service properties completed with status code %d", response.getStatusCode()); + // END: com.azure.storage.queue.queueServiceClient.setPropertiesWithResponse#QueueServiceProperties-duration-context + } + + /** + * Generates a code sample for using {@link QueueServiceClient#setPropertiesWithResponse(QueueServiceProperties, + * Duration, Context)} with metrics enabled. + */ + public void setPropertiesWithResponseEnableMetrics() { + // BEGIN: com.azure.storage.queue.queueServiceClient.setPropertiesWithResponseEnableMetrics#QueueServiceProperties-duration-context + QueueServiceProperties properties = client.getProperties(); + properties.getMinuteMetrics().setEnabled(true); + properties.getMinuteMetrics().setIncludeApis(true); + properties.getMinuteMetrics().setRetentionPolicy(new QueueRetentionPolicy().setDays(7).setEnabled(true)); + properties.getHourMetrics().setEnabled(true); + properties.getHourMetrics().setIncludeApis(true); + properties.getHourMetrics().setRetentionPolicy(new QueueRetentionPolicy().setDays(7).setEnabled(true)); + Response response = client.setPropertiesWithResponse(properties, Duration.ofSeconds(1), + new Context(key1, value1)); + System.out.printf("Setting Queue service properties completed with status code %d", response.getStatusCode()); + // END: com.azure.storage.queue.queueServiceClient.setPropertiesWithResponseEnableMetrics#QueueServiceProperties-duration-context + } + + /** + * Generates a code sample for using {@link QueueServiceClient#setProperties(QueueServiceProperties)} with metrics + * enabled. + */ + public void setPropertiesEnableMetrics() { + // BEGIN: com.azure.storage.queue.queueServiceClient.setPropertiesEnableMetrics#QueueServiceProperties + QueueServiceProperties properties = client.getProperties(); + properties.getMinuteMetrics().setEnabled(true); + properties.getMinuteMetrics().setIncludeApis(true); + properties.getMinuteMetrics().setRetentionPolicy(new QueueRetentionPolicy().setDays(7).setEnabled(true)); + properties.getHourMetrics().setEnabled(true); + properties.getHourMetrics().setIncludeApis(true); + properties.getHourMetrics().setRetentionPolicy(new QueueRetentionPolicy().setDays(7).setEnabled(true)); + client.setProperties(properties); + System.out.println("Setting Queue service properties completed."); + // END: com.azure.storage.queue.queueServiceClient.setPropertiesEnableMetrics#QueueServiceProperties + } + + /** + * Generates a code sample for using {@link QueueServiceClient#getStatistics()} + */ + public void getStatistics() { + // BEGIN: com.azure.storage.queue.queueServiceClient.getStatistics + QueueServiceStatistics stats = client.getStatistics(); + System.out.printf("Geo replication status: %s, Last synced: %s", + stats.getGeoReplication().getStatus(), stats.getGeoReplication().getLastSyncTime()); + // END: com.azure.storage.queue.queueServiceClient.getStatistics + } + + /** + * Generates a code sample for using {@link QueueServiceClient#getStatisticsWithResponse(Duration, Context)} + */ + public void getStatisticsWithResponse() { + // BEGIN: com.azure.storage.queue.queueServiceClient.getStatisticsWithResponse#duration-context + QueueServiceStatistics stats = client.getStatisticsWithResponse(Duration.ofSeconds(1), + new Context(key1, value1)).getValue(); + System.out.printf("Geo replication status: %s, Last synced: %s", + stats.getGeoReplication().getStatus(), stats.getGeoReplication().getLastSyncTime()); + // END: com.azure.storage.queue.queueServiceClient.getStatisticsWithResponse#duration-context + } + + /** + * Code snippet for {@link QueueServiceClient#generateAccountSas(AccountSasSignatureValues)} + */ + public void generateAccountSas() { + QueueServiceClient queueServiceClient = createClientWithCredential(); + // BEGIN: com.azure.storage.queue.QueueServiceClient.generateAccountSas#AccountSasSignatureValues + AccountSasPermission permissions = new AccountSasPermission() + .setListPermission(true) + .setReadPermission(true); + AccountSasResourceType resourceTypes = new AccountSasResourceType().setContainer(true).setObject(true); + AccountSasService services = new AccountSasService().setQueueAccess(true).setFileAccess(true); + OffsetDateTime expiryTime = OffsetDateTime.now().plus(Duration.ofDays(2)); + + AccountSasSignatureValues sasValues = + new AccountSasSignatureValues(expiryTime, permissions, services, resourceTypes); + + // Client must be authenticated via StorageSharedKeyCredential + String sas = queueServiceClient.generateAccountSas(sasValues); + // END: com.azure.storage.queue.QueueServiceClient.generateAccountSas#AccountSasSignatureValues + } + + /** + * Code snippet for {@link QueueServiceClient#generateAccountSas(AccountSasSignatureValues, Context)} + */ + public void generateAccountSasWithContext() { + QueueServiceClient queueServiceClient = createClientWithCredential(); + // BEGIN: com.azure.storage.queue.QueueServiceClient.generateAccountSas#AccountSasSignatureValues-Context + AccountSasPermission permissions = new AccountSasPermission() + .setListPermission(true) + .setReadPermission(true); + AccountSasResourceType resourceTypes = new AccountSasResourceType().setContainer(true).setObject(true); + AccountSasService services = new AccountSasService().setQueueAccess(true).setFileAccess(true); + OffsetDateTime expiryTime = OffsetDateTime.now().plus(Duration.ofDays(2)); + + AccountSasSignatureValues sasValues = + new AccountSasSignatureValues(expiryTime, permissions, services, resourceTypes); + + // Client must be authenticated via StorageSharedKeyCredential + String sas = queueServiceClient.generateAccountSas(sasValues, new Context("key", "value")); + // END: com.azure.storage.queue.QueueServiceClient.generateAccountSas#AccountSasSignatureValues-Context + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample8/v1/QueueServiceSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample8/v1/QueueServiceSamples.java new file mode 100644 index 000000000000..b88af1416838 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample8/v1/QueueServiceSamples.java @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.queue; + +public class QueueServiceSamples { + private static final String ACCOUNT_NAME = System.getenv("AZURE_STORAGE_ACCOUNT_NAME"); + private static final String SAS_TOKEN = System.getenv("PRIMARY_SAS_TOKEN"); + + /** + * The main method illustrated the basic operations of creating and deleting queues using queue service sync client. + * @param args No args needed for main method. + */ + public static void main(String[] args) { + // Build Queue Service Client using SAS Token + String queueServiceURL = String.format("https://%s.queue.core.windows.net/?%s", ACCOUNT_NAME, SAS_TOKEN); + QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL).buildClient(); + queueServiceClient.createQueue(SampleHelper.generateRandomName("create-queue", 16)); + + // Create another queue and list all queues, print the name and then delete the queue. + queueServiceClient.createQueue(SampleHelper.generateRandomName("create-extra", 16)); + queueServiceClient.listQueues().forEach( + queueItem -> { + System.out.println("The queue name is: " + queueItem.getName()); + queueServiceClient.deleteQueue(queueItem.getName()); + } + ); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample8/v2/QueueServiceSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample8/v2/QueueServiceSamples.java new file mode 100644 index 000000000000..b88af1416838 --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample8/v2/QueueServiceSamples.java @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.queue; + +public class QueueServiceSamples { + private static final String ACCOUNT_NAME = System.getenv("AZURE_STORAGE_ACCOUNT_NAME"); + private static final String SAS_TOKEN = System.getenv("PRIMARY_SAS_TOKEN"); + + /** + * The main method illustrated the basic operations of creating and deleting queues using queue service sync client. + * @param args No args needed for main method. + */ + public static void main(String[] args) { + // Build Queue Service Client using SAS Token + String queueServiceURL = String.format("https://%s.queue.core.windows.net/?%s", ACCOUNT_NAME, SAS_TOKEN); + QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL).buildClient(); + queueServiceClient.createQueue(SampleHelper.generateRandomName("create-queue", 16)); + + // Create another queue and list all queues, print the name and then delete the queue. + queueServiceClient.createQueue(SampleHelper.generateRandomName("create-extra", 16)); + queueServiceClient.listQueues().forEach( + queueItem -> { + System.out.println("The queue name is: " + queueItem.getName()); + queueServiceClient.deleteQueue(queueItem.getName()); + } + ); + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample9/v1/ReadmeSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample9/v1/ReadmeSamples.java new file mode 100644 index 000000000000..ff7f10c01d4c --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample9/v1/ReadmeSamples.java @@ -0,0 +1,266 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.queue; + +import java.time.Duration; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import com.azure.core.util.Context; +import com.azure.storage.queue.models.QueueProperties; +import com.azure.storage.queue.models.QueueServiceProperties; +import com.azure.storage.queue.models.QueueServiceStatistics; +import com.azure.storage.queue.models.QueueStorageException; +import com.azure.storage.queue.models.QueuesSegmentOptions; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * WARNING: MODIFYING THIS FILE WILL REQUIRE CORRESPONDING UPDATES TO README.md FILE. LINE NUMBERS + * ARE USED TO EXTRACT APPROPRIATE CODE SEGMENTS FROM THIS FILE. ADD NEW CODE AT THE BOTTOM TO AVOID CHANGING + * LINE NUMBERS OF EXISTING CODE SAMPLES. + * + * Code samples for the README.md + */ +@SuppressWarnings("unused") +public class ReadmeSamples { + private static final String ACCOUNT_NAME = System.getenv("AZURE_STORAGE_ACCOUNT_NAME"); + private static final String SAS_TOKEN = System.getenv("PRIMARY_SAS_TOKEN"); + String markers = "marker"; + QueuesSegmentOptions options = new QueuesSegmentOptions(); + Duration timeout = Duration.ofSeconds(1); + Context context = Context.NONE; + String messageId = "messageId"; + String popReceipt = "popReceipt"; + String messageText = "messageText"; + Duration visibilityTimeout = Duration.ofSeconds(1); + String key = "key"; + String value = "value"; + String queueAsyncName = "queueAsyncName"; + String queueName = "queueName"; + Map metadata = new HashMap() { + { + put("key1", "val1"); + put("key2", "val2"); + } + }; + + private final Logger logger = LoggerFactory.getLogger(ReadmeSamples.class); + + public void handleException() { + // BEGIN: readme-sample-handleException + String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL) + .sasToken(SAS_TOKEN).buildClient(); + try { + queueServiceClient.createQueue("myQueue"); + } catch (QueueStorageException e) { + logger.error("Failed to create a queue with error code: " + e.getErrorCode()); + } + // END: readme-sample-handleException + } + + public void createQueue1() { + // BEGIN: readme-sample-createQueue1 + String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL) + .sasToken(SAS_TOKEN).buildClient(); + + QueueClient newQueueClient = queueServiceClient.createQueue("myQueue"); + // END: readme-sample-createQueue1 + } + + public void createQueue2() { + // BEGIN: readme-sample-createQueue2 + String queueServiceAsyncURL = String.format("https://%s.queue.core.windows.net/", ACCOUNT_NAME); + QueueServiceAsyncClient queueServiceAsyncClient = new QueueServiceClientBuilder().endpoint(queueServiceAsyncURL) + .sasToken(SAS_TOKEN).buildAsyncClient(); + queueServiceAsyncClient.createQueue("newAsyncQueue").subscribe(result -> { + // do something when new queue created + }, error -> { + // do something if something wrong happened + }, () -> { + // completed, do something + }); + // END: readme-sample-createQueue2 + } + + public void createWithResponse1() { + // BEGIN: readme-sample-createWithResponse1 + String queueURL = String.format("https://%s.queue.core.windows.net/%s", ACCOUNT_NAME, queueName); + QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).buildClient(); + + // metadata is map of key-value pair + queueClient.createWithResponse(metadata, Duration.ofSeconds(30), Context.NONE); + // END: readme-sample-createWithResponse1 + } + + public void createWithResponse2() { + // BEGIN: readme-sample-createWithResponse2 + // Only one "?" is needed here. If the sastoken starts with "?", please removing one "?". + String queueAsyncURL = String.format("https://%s.queue.core.windows.net/%s?%s", ACCOUNT_NAME, queueAsyncName, + SAS_TOKEN); + QueueAsyncClient queueAsyncClient = new QueueClientBuilder().endpoint(queueAsyncURL).buildAsyncClient(); + queueAsyncClient.createWithResponse(metadata).subscribe(result -> { + // do something when new queue created + }, error -> { + // do something if something wrong happened + }, () -> { + // completed, do something + }); + // END: readme-sample-createWithResponse2 + } + + public void getQueueServiceClient1() { + // BEGIN: readme-sample-getQueueServiceClient1 + // Only one "?" is needed here. If the sastoken starts with "?", please removing one "?". + String queueServiceURL = String.format("https://%s.queue.core.windows.net/?%s", ACCOUNT_NAME, SAS_TOKEN); + QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL).buildClient(); + // END: readme-sample-getQueueServiceClient1 + } + + public void getQueueServiceClient2() { + // BEGIN: readme-sample-getQueueServiceClient2 + String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL) + .sasToken(SAS_TOKEN).buildClient(); + // END: readme-sample-getQueueServiceClient2 + } + + public void deleteQueue() { + // BEGIN: readme-sample-deleteQueue + String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL) + .sasToken(SAS_TOKEN).buildClient(); + + queueServiceClient.deleteQueue("myqueue"); + // END: readme-sample-deleteQueue + } + + public void getQueueListInAccount() { + // BEGIN: readme-sample-getQueueListInAccount + String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL) + .sasToken(SAS_TOKEN).buildClient(); + // @param marker: Starting point to list the queues + // @param options: Filter for queue selection + // @param timeout: An optional timeout applied to the operation. + // @param context: Additional context that is passed through the Http pipeline during the service call. + queueServiceClient.listQueues(options, timeout, context).stream().forEach(queueItem -> + System.out.printf("Queue %s exists in the account.", queueItem.getName())); + // END: readme-sample-getQueueListInAccount + } + + public void getPropertiesInQueueAccount() { + // BEGIN: readme-sample-getPropertiesInQueueAccount + String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL) + .sasToken(SAS_TOKEN).buildClient(); + + QueueServiceProperties properties = queueServiceClient.getProperties(); + // END: readme-sample-getPropertiesInQueueAccount + } + + public void setPropertiesInQueueAccount() { + // BEGIN: readme-sample-setPropertiesInQueueAccount + String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL) + .sasToken(SAS_TOKEN).buildClient(); + + QueueServiceProperties properties = queueServiceClient.getProperties(); + properties.setCors(Collections.emptyList()); + queueServiceClient.setProperties(properties); + // END: readme-sample-setPropertiesInQueueAccount + } + + public void getQueueServiceStatistics() { + // BEGIN: readme-sample-getQueueServiceStatistics + String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL) + .sasToken(SAS_TOKEN).buildClient(); + + QueueServiceStatistics queueStats = queueServiceClient.getStatistics(); + // END: readme-sample-getQueueServiceStatistics + } + + public void enqueueMessage() { + // BEGIN: readme-sample-enqueueMessage + String queueURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).queueName("myqueue") + .buildClient(); + + queueClient.sendMessage("myMessage"); + // END: readme-sample-enqueueMessage + } + + public void updateMessage() { + // BEGIN: readme-sample-updateMessage + String queueURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).queueName("myqueue") + .buildClient(); + // @param messageId: Id of the message + // @param popReceipt: Unique identifier that must match the message for it to be updated + // @param visibilityTimeout: How long the message will be invisible in the queue in seconds + queueClient.updateMessage(messageId, popReceipt, "new message", visibilityTimeout); + // END: readme-sample-updateMessage + } + + public void peekAtMessage() { + // BEGIN: readme-sample-peekAtMessage + String queueURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).queueName("myqueue") + .buildClient(); + // @param key: The key with which the specified value should be associated. + // @param value: The value to be associated with the specified key. + queueClient.peekMessages(5, Duration.ofSeconds(1), new Context(key, value)).forEach(message -> + System.out.println(message.getBody().toString())); + // END: readme-sample-peekAtMessage + } + + public void receiveMessageFromQueue() { + // BEGIN: readme-sample-receiveMessageFromQueue + String queueURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).queueName("myqueue") + .buildClient(); + // Try to receive 10 messages: Maximum number of messages to get + queueClient.receiveMessages(10).forEach(message -> + System.out.println(message.getBody().toString())); + // END: readme-sample-receiveMessageFromQueue + } + + public void deleteMessageFromQueue() { + // BEGIN: readme-sample-deleteMessageFromQueue + String queueURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).queueName("myqueue") + .buildClient(); + + queueClient.deleteMessage(messageId, popReceipt); + // END: readme-sample-deleteMessageFromQueue + } + + public void getQueueProperties() { + // BEGIN: readme-sample-getQueueProperties + String queueURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).queueName("myqueue") + .buildClient(); + + QueueProperties properties = queueClient.getProperties(); + // END: readme-sample-getQueueProperties + } + + public void setQueueMetadata() { + // BEGIN: readme-sample-setQueueMetadata + String queueURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).queueName("myqueue") + .buildClient(); + + Map metadata = new HashMap<>(); + metadata.put("key1", "val1"); + metadata.put("key2", "val2"); + queueClient.setMetadata(metadata); + // END: readme-sample-setQueueMetadata + } +} diff --git a/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample9/v2/ReadmeSamples.java b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample9/v2/ReadmeSamples.java new file mode 100644 index 000000000000..ff7f10c01d4c --- /dev/null +++ b/sdk/tools/azure-openrewrite/src/test/resources/migrationExamples/azure-storage-queue/sample9/v2/ReadmeSamples.java @@ -0,0 +1,266 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.queue; + +import java.time.Duration; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import com.azure.core.util.Context; +import com.azure.storage.queue.models.QueueProperties; +import com.azure.storage.queue.models.QueueServiceProperties; +import com.azure.storage.queue.models.QueueServiceStatistics; +import com.azure.storage.queue.models.QueueStorageException; +import com.azure.storage.queue.models.QueuesSegmentOptions; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * WARNING: MODIFYING THIS FILE WILL REQUIRE CORRESPONDING UPDATES TO README.md FILE. LINE NUMBERS + * ARE USED TO EXTRACT APPROPRIATE CODE SEGMENTS FROM THIS FILE. ADD NEW CODE AT THE BOTTOM TO AVOID CHANGING + * LINE NUMBERS OF EXISTING CODE SAMPLES. + * + * Code samples for the README.md + */ +@SuppressWarnings("unused") +public class ReadmeSamples { + private static final String ACCOUNT_NAME = System.getenv("AZURE_STORAGE_ACCOUNT_NAME"); + private static final String SAS_TOKEN = System.getenv("PRIMARY_SAS_TOKEN"); + String markers = "marker"; + QueuesSegmentOptions options = new QueuesSegmentOptions(); + Duration timeout = Duration.ofSeconds(1); + Context context = Context.NONE; + String messageId = "messageId"; + String popReceipt = "popReceipt"; + String messageText = "messageText"; + Duration visibilityTimeout = Duration.ofSeconds(1); + String key = "key"; + String value = "value"; + String queueAsyncName = "queueAsyncName"; + String queueName = "queueName"; + Map metadata = new HashMap() { + { + put("key1", "val1"); + put("key2", "val2"); + } + }; + + private final Logger logger = LoggerFactory.getLogger(ReadmeSamples.class); + + public void handleException() { + // BEGIN: readme-sample-handleException + String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL) + .sasToken(SAS_TOKEN).buildClient(); + try { + queueServiceClient.createQueue("myQueue"); + } catch (QueueStorageException e) { + logger.error("Failed to create a queue with error code: " + e.getErrorCode()); + } + // END: readme-sample-handleException + } + + public void createQueue1() { + // BEGIN: readme-sample-createQueue1 + String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL) + .sasToken(SAS_TOKEN).buildClient(); + + QueueClient newQueueClient = queueServiceClient.createQueue("myQueue"); + // END: readme-sample-createQueue1 + } + + public void createQueue2() { + // BEGIN: readme-sample-createQueue2 + String queueServiceAsyncURL = String.format("https://%s.queue.core.windows.net/", ACCOUNT_NAME); + QueueServiceAsyncClient queueServiceAsyncClient = new QueueServiceClientBuilder().endpoint(queueServiceAsyncURL) + .sasToken(SAS_TOKEN).buildAsyncClient(); + queueServiceAsyncClient.createQueue("newAsyncQueue").subscribe(result -> { + // do something when new queue created + }, error -> { + // do something if something wrong happened + }, () -> { + // completed, do something + }); + // END: readme-sample-createQueue2 + } + + public void createWithResponse1() { + // BEGIN: readme-sample-createWithResponse1 + String queueURL = String.format("https://%s.queue.core.windows.net/%s", ACCOUNT_NAME, queueName); + QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).buildClient(); + + // metadata is map of key-value pair + queueClient.createWithResponse(metadata, Duration.ofSeconds(30), Context.NONE); + // END: readme-sample-createWithResponse1 + } + + public void createWithResponse2() { + // BEGIN: readme-sample-createWithResponse2 + // Only one "?" is needed here. If the sastoken starts with "?", please removing one "?". + String queueAsyncURL = String.format("https://%s.queue.core.windows.net/%s?%s", ACCOUNT_NAME, queueAsyncName, + SAS_TOKEN); + QueueAsyncClient queueAsyncClient = new QueueClientBuilder().endpoint(queueAsyncURL).buildAsyncClient(); + queueAsyncClient.createWithResponse(metadata).subscribe(result -> { + // do something when new queue created + }, error -> { + // do something if something wrong happened + }, () -> { + // completed, do something + }); + // END: readme-sample-createWithResponse2 + } + + public void getQueueServiceClient1() { + // BEGIN: readme-sample-getQueueServiceClient1 + // Only one "?" is needed here. If the sastoken starts with "?", please removing one "?". + String queueServiceURL = String.format("https://%s.queue.core.windows.net/?%s", ACCOUNT_NAME, SAS_TOKEN); + QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL).buildClient(); + // END: readme-sample-getQueueServiceClient1 + } + + public void getQueueServiceClient2() { + // BEGIN: readme-sample-getQueueServiceClient2 + String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL) + .sasToken(SAS_TOKEN).buildClient(); + // END: readme-sample-getQueueServiceClient2 + } + + public void deleteQueue() { + // BEGIN: readme-sample-deleteQueue + String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL) + .sasToken(SAS_TOKEN).buildClient(); + + queueServiceClient.deleteQueue("myqueue"); + // END: readme-sample-deleteQueue + } + + public void getQueueListInAccount() { + // BEGIN: readme-sample-getQueueListInAccount + String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL) + .sasToken(SAS_TOKEN).buildClient(); + // @param marker: Starting point to list the queues + // @param options: Filter for queue selection + // @param timeout: An optional timeout applied to the operation. + // @param context: Additional context that is passed through the Http pipeline during the service call. + queueServiceClient.listQueues(options, timeout, context).stream().forEach(queueItem -> + System.out.printf("Queue %s exists in the account.", queueItem.getName())); + // END: readme-sample-getQueueListInAccount + } + + public void getPropertiesInQueueAccount() { + // BEGIN: readme-sample-getPropertiesInQueueAccount + String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL) + .sasToken(SAS_TOKEN).buildClient(); + + QueueServiceProperties properties = queueServiceClient.getProperties(); + // END: readme-sample-getPropertiesInQueueAccount + } + + public void setPropertiesInQueueAccount() { + // BEGIN: readme-sample-setPropertiesInQueueAccount + String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL) + .sasToken(SAS_TOKEN).buildClient(); + + QueueServiceProperties properties = queueServiceClient.getProperties(); + properties.setCors(Collections.emptyList()); + queueServiceClient.setProperties(properties); + // END: readme-sample-setPropertiesInQueueAccount + } + + public void getQueueServiceStatistics() { + // BEGIN: readme-sample-getQueueServiceStatistics + String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL) + .sasToken(SAS_TOKEN).buildClient(); + + QueueServiceStatistics queueStats = queueServiceClient.getStatistics(); + // END: readme-sample-getQueueServiceStatistics + } + + public void enqueueMessage() { + // BEGIN: readme-sample-enqueueMessage + String queueURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).queueName("myqueue") + .buildClient(); + + queueClient.sendMessage("myMessage"); + // END: readme-sample-enqueueMessage + } + + public void updateMessage() { + // BEGIN: readme-sample-updateMessage + String queueURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).queueName("myqueue") + .buildClient(); + // @param messageId: Id of the message + // @param popReceipt: Unique identifier that must match the message for it to be updated + // @param visibilityTimeout: How long the message will be invisible in the queue in seconds + queueClient.updateMessage(messageId, popReceipt, "new message", visibilityTimeout); + // END: readme-sample-updateMessage + } + + public void peekAtMessage() { + // BEGIN: readme-sample-peekAtMessage + String queueURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).queueName("myqueue") + .buildClient(); + // @param key: The key with which the specified value should be associated. + // @param value: The value to be associated with the specified key. + queueClient.peekMessages(5, Duration.ofSeconds(1), new Context(key, value)).forEach(message -> + System.out.println(message.getBody().toString())); + // END: readme-sample-peekAtMessage + } + + public void receiveMessageFromQueue() { + // BEGIN: readme-sample-receiveMessageFromQueue + String queueURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).queueName("myqueue") + .buildClient(); + // Try to receive 10 messages: Maximum number of messages to get + queueClient.receiveMessages(10).forEach(message -> + System.out.println(message.getBody().toString())); + // END: readme-sample-receiveMessageFromQueue + } + + public void deleteMessageFromQueue() { + // BEGIN: readme-sample-deleteMessageFromQueue + String queueURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).queueName("myqueue") + .buildClient(); + + queueClient.deleteMessage(messageId, popReceipt); + // END: readme-sample-deleteMessageFromQueue + } + + public void getQueueProperties() { + // BEGIN: readme-sample-getQueueProperties + String queueURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).queueName("myqueue") + .buildClient(); + + QueueProperties properties = queueClient.getProperties(); + // END: readme-sample-getQueueProperties + } + + public void setQueueMetadata() { + // BEGIN: readme-sample-setQueueMetadata + String queueURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME); + QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).queueName("myqueue") + .buildClient(); + + Map metadata = new HashMap<>(); + metadata.put("key1", "val1"); + metadata.put("key2", "val2"); + queueClient.setMetadata(metadata); + // END: readme-sample-setQueueMetadata + } +} diff --git a/sdk/tools/azure-sdk-archetype/pom.xml b/sdk/tools/azure-sdk-archetype/pom.xml index e993ac178112..43d326092d06 100644 --- a/sdk/tools/azure-sdk-archetype/pom.xml +++ b/sdk/tools/azure-sdk-archetype/pom.xml @@ -177,7 +177,7 @@ org.apache.maven.plugins maven-checkstyle-plugin - 3.5.0 + 3.6.0 com.azure @@ -211,7 +211,7 @@ org.ow2.asm asm - 9.7 + 9.7.1 @@ -270,7 +270,7 @@ org.revapi revapi-reporter-json - 0.4.5 + 0.5.0 diff --git a/sdk/tools/azure-sdk-build-tool/pom.xml b/sdk/tools/azure-sdk-build-tool/pom.xml index b00755152c75..e734cbe7159e 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.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 @@ -142,7 +142,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.1 + 3.5.2 org.apache.maven.plugins @@ -223,7 +223,7 @@ org.apache.maven.plugins maven-checkstyle-plugin - 3.5.0 + 3.6.0 com.azure @@ -269,7 +269,7 @@ org.ow2.asm asm - 9.7 + 9.7.1 @@ -304,7 +304,7 @@ org.revapi revapi-reporter-json - 0.4.5 + 0.5.0 diff --git a/sdk/tools/azure-sdk-build-tool/src/test/azure-sdk-build-tool-test/pom.xml b/sdk/tools/azure-sdk-build-tool/src/test/azure-sdk-build-tool-test/pom.xml index 15019b8029a3..e7f90e678bf5 100644 --- a/sdk/tools/azure-sdk-build-tool/src/test/azure-sdk-build-tool-test/pom.xml +++ b/sdk/tools/azure-sdk-build-tool/src/test/azure-sdk-build-tool-test/pom.xml @@ -72,8 +72,8 @@ com.azure - azure-monitor-opentelemetry-exporter - 1.0.0-beta.8 + azure-monitor-opentelemetry-autoconfigure + 1.0.0-beta.1 diff --git a/sdk/tools/ci.yml b/sdk/tools/ci.yml index 27a6413bd660..fe148487c009 100644 --- a/sdk/tools/ci.yml +++ b/sdk/tools/ci.yml @@ -6,10 +6,12 @@ trigger: include: - /sdk/tools/azure-sdk-archetype/ - /sdk/tools/azure-sdk-build-tool/ + - /sdk/tools/azure-openrewrite/ exclude: - sdk/tools/pom.xml - sdk/tools/azure-sdk-build-tool/pom.xml - sdk/tools/azure-sdk-archetype/pom.xml + - /sdk/tools/azure-openrewrite/pom.xml pr: branches: @@ -22,10 +24,12 @@ pr: include: - /sdk/tools/azure-sdk-archetype/ - /sdk/tools/azure-sdk-build-tool/ + - /sdk/tools/azure-openrewrite/ exclude: - sdk/tools/pom.xml - sdk/tools/azure-sdk-build-tool/pom.xml - sdk/tools/azure-sdk-archetype/pom.xml + - /sdk/tools/azure-openrewrite/pom.xml extends: template: /eng/pipelines/templates/stages/archetype-sdk-client.yml @@ -42,3 +46,8 @@ extends: safeName: azuresdkbuildtool skipPublishDocGithubIo: true skipPublishDocMs: true + - name: azure-openrewrite + groupId: com.azure + safeName: azureopenrewrite + skipPublishDocGithubIo: true + skipPublishDocMs: true diff --git a/sdk/tools/pom.xml b/sdk/tools/pom.xml index 58a31f84a0aa..70ff59fb1c41 100644 --- a/sdk/tools/pom.xml +++ b/sdk/tools/pom.xml @@ -11,5 +11,6 @@ azure-sdk-archetype azure-sdk-build-tool + azure-openrewrite diff --git a/sdk/translation/azure-ai-documenttranslator/README.md b/sdk/translation/azure-ai-documenttranslator/README.md index 7fafbe0b0af9..cff9148c5f4c 100644 --- a/sdk/translation/azure-ai-documenttranslator/README.md +++ b/sdk/translation/azure-ai-documenttranslator/README.md @@ -27,7 +27,7 @@ For more information about creating the resource or how to get the location and com.azure azure-ai-documenttranslator - 1.0.0-beta.1 + 1.0.0-beta.2 ``` [//]: # ({x-version-update-end}) @@ -89,4 +89,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [package]: https://central.sonatype.com/artifact/com.azure/azure-ai-documenttranslator [samples_readme]: https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/translation/azure-ai-documenttranslator/src/samples/README.md -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Ftranslation%2Fazure-ai-documenttranslator%2FREADME.png) + diff --git a/sdk/translation/azure-ai-documenttranslator/pom.xml b/sdk/translation/azure-ai-documenttranslator/pom.xml index 9b5e23b64a7d..cc922abc8373 100644 --- a/sdk/translation/azure-ai-documenttranslator/pom.xml +++ b/sdk/translation/azure-ai-documenttranslator/pom.xml @@ -47,36 +47,36 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-experimental - 1.0.0-beta.56 + 1.0.0-beta.60 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-core-serializer-json-jackson - 1.5.4 + 1.5.8 test diff --git a/sdk/translation/azure-ai-translation-document/README.md b/sdk/translation/azure-ai-translation-document/README.md index a44ec41e0940..3470f9c455b5 100644 --- a/sdk/translation/azure-ai-translation-document/README.md +++ b/sdk/translation/azure-ai-translation-document/README.md @@ -28,7 +28,7 @@ Various documentation is available to help you get started com.azure azure-ai-translation-document - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -52,7 +52,7 @@ Authentication with AAD requires some initial setup: com.azure azure-identity - 1.14.2 + 1.15.3 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/translation/azure-ai-translation-document/pom.xml b/sdk/translation/azure-ai-translation-document/pom.xml index ca42eb5d3446..c85d9c7eecbd 100644 --- a/sdk/translation/azure-ai-translation-document/pom.xml +++ b/sdk/translation/azure-ai-translation-document/pom.xml @@ -54,35 +54,35 @@ Code generated by Microsoft (R) TypeSpec Code Generator. com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-storage-blob - 12.29.0 + 12.29.1 test diff --git a/sdk/translation/azure-ai-translation-document/src/main/java/com/azure/ai/translation/document/SingleDocumentTranslationAsyncClient.java b/sdk/translation/azure-ai-translation-document/src/main/java/com/azure/ai/translation/document/SingleDocumentTranslationAsyncClient.java index 84c02e035021..6901a0abe714 100644 --- a/sdk/translation/azure-ai-translation-document/src/main/java/com/azure/ai/translation/document/SingleDocumentTranslationAsyncClient.java +++ b/sdk/translation/azure-ai-translation-document/src/main/java/com/azure/ai/translation/document/SingleDocumentTranslationAsyncClient.java @@ -84,8 +84,8 @@ public final class SingleDocumentTranslationAsyncClient { @ServiceMethod(returns = ReturnType.SINGLE) Mono> translateWithResponse(String targetLanguage, BinaryData documentTranslateContent, RequestOptions requestOptions) { - // Protocol API requires serialization of parts with content-disposition and data, as operation 'translate' is - // 'multipart/form-data' + // Operation 'translate' is of content-type 'multipart/form-data'. Protocol API is not usable and hence not + // generated. return this.serviceClient.translateWithResponseAsync(targetLanguage, documentTranslateContent, requestOptions); } diff --git a/sdk/translation/azure-ai-translation-document/src/main/java/com/azure/ai/translation/document/SingleDocumentTranslationClient.java b/sdk/translation/azure-ai-translation-document/src/main/java/com/azure/ai/translation/document/SingleDocumentTranslationClient.java index 8f1b193bca8f..38dfb0b312ea 100644 --- a/sdk/translation/azure-ai-translation-document/src/main/java/com/azure/ai/translation/document/SingleDocumentTranslationClient.java +++ b/sdk/translation/azure-ai-translation-document/src/main/java/com/azure/ai/translation/document/SingleDocumentTranslationClient.java @@ -82,8 +82,8 @@ public final class SingleDocumentTranslationClient { @ServiceMethod(returns = ReturnType.SINGLE) Response translateWithResponse(String targetLanguage, BinaryData documentTranslateContent, RequestOptions requestOptions) { - // Protocol API requires serialization of parts with content-disposition and data, as operation 'translate' is - // 'multipart/form-data' + // Operation 'translate' is of content-type 'multipart/form-data'. Protocol API is not usable and hence not + // generated. return this.serviceClient.translateWithResponse(targetLanguage, documentTranslateContent, requestOptions); } diff --git a/sdk/translation/azure-ai-translation-text/CHANGELOG.md b/sdk/translation/azure-ai-translation-text/CHANGELOG.md index 3605b4ec8d92..4729eb311a56 100644 --- a/sdk/translation/azure-ai-translation-text/CHANGELOG.md +++ b/sdk/translation/azure-ai-translation-text/CHANGELOG.md @@ -10,6 +10,16 @@ ### Other Changes +## 1.1.1 (2025-02-25) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`. +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. + + ## 1.1.0 (2024-11-15) ### Other Changes diff --git a/sdk/translation/azure-ai-translation-text/README.md b/sdk/translation/azure-ai-translation-text/README.md index 0376c637db6b..2b1a507e6525 100644 --- a/sdk/translation/azure-ai-translation-text/README.md +++ b/sdk/translation/azure-ai-translation-text/README.md @@ -36,7 +36,7 @@ Various documentation is available to help you get started com.azure azure-ai-translation-text - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/translation/azure-ai-translation-text/pom.xml b/sdk/translation/azure-ai-translation-text/pom.xml index 8fccb8ac3823..31c26c3cf795 100644 --- a/sdk/translation/azure-ai-translation-text/pom.xml +++ b/sdk/translation/azure-ai-translation-text/pom.xml @@ -51,25 +51,25 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/trustedsigning/azure-resourcemanager-trustedsigning/README.md b/sdk/trustedsigning/azure-resourcemanager-trustedsigning/README.md index 25f8f3e5baa9..8cf70d4bbedc 100644 --- a/sdk/trustedsigning/azure-resourcemanager-trustedsigning/README.md +++ b/sdk/trustedsigning/azure-resourcemanager-trustedsigning/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-trustedsigning - 1.0.0-beta.1 + 1.0.0-beta.2 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Ftrustedsigning%2Fazure-resourcemanager-trustedsigning%2FREADME.png) + diff --git a/sdk/trustedsigning/azure-resourcemanager-trustedsigning/pom.xml b/sdk/trustedsigning/azure-resourcemanager-trustedsigning/pom.xml index a7b99067af23..4565e1b0e772 100644 --- a/sdk/trustedsigning/azure-resourcemanager-trustedsigning/pom.xml +++ b/sdk/trustedsigning/azure-resourcemanager-trustedsigning/pom.xml @@ -51,28 +51,28 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/trustedsigning/azure-resourcemanager-trustedsigning/src/main/java/com/azure/resourcemanager/trustedsigning/TrustedSigningManager.java b/sdk/trustedsigning/azure-resourcemanager-trustedsigning/src/main/java/com/azure/resourcemanager/trustedsigning/TrustedSigningManager.java index 3f53d4757d4b..255ba3d8b710 100644 --- a/sdk/trustedsigning/azure-resourcemanager-trustedsigning/src/main/java/com/azure/resourcemanager/trustedsigning/TrustedSigningManager.java +++ b/sdk/trustedsigning/azure-resourcemanager-trustedsigning/src/main/java/com/azure/resourcemanager/trustedsigning/TrustedSigningManager.java @@ -22,6 +22,7 @@ import com.azure.core.http.policy.UserAgentPolicy; import com.azure.core.management.profile.AzureProfile; import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.trustedsigning.fluent.TrustedSigningManagementClient; import com.azure.resourcemanager.trustedsigning.implementation.CertificateProfilesImpl; @@ -35,6 +36,7 @@ import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; @@ -101,6 +103,9 @@ public static Configurable configure() { */ public static final class Configurable { private static final ClientLogger LOGGER = new ClientLogger(Configurable.class); + private static final String SDK_VERSION = "version"; + private static final Map PROPERTIES + = CoreUtils.getProperties("azure-resourcemanager-trustedsigning.properties"); private HttpClient httpClient; private HttpLogOptions httpLogOptions; @@ -208,12 +213,14 @@ public TrustedSigningManager authenticate(TokenCredential credential, AzureProfi Objects.requireNonNull(credential, "'credential' cannot be null."); Objects.requireNonNull(profile, "'profile' cannot be null."); + String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); + StringBuilder userAgentBuilder = new StringBuilder(); userAgentBuilder.append("azsdk-java") .append("-") .append("com.azure.resourcemanager.trustedsigning") .append("/") - .append("1.0.0-beta.1"); + .append(clientVersion); if (!Configuration.getGlobalConfiguration().get("AZURE_TELEMETRY_DISABLED", false)) { userAgentBuilder.append(" (") .append(Configuration.getGlobalConfiguration().get("java.version")) diff --git a/sdk/trustedsigning/azure-resourcemanager-trustedsigning/src/main/resources/azure-resourcemanager-trustedsigning.properties b/sdk/trustedsigning/azure-resourcemanager-trustedsigning/src/main/resources/azure-resourcemanager-trustedsigning.properties new file mode 100644 index 000000000000..defbd48204e4 --- /dev/null +++ b/sdk/trustedsigning/azure-resourcemanager-trustedsigning/src/main/resources/azure-resourcemanager-trustedsigning.properties @@ -0,0 +1 @@ +version=${project.version} diff --git a/sdk/vision/azure-ai-vision-imageanalysis/README.md b/sdk/vision/azure-ai-vision-imageanalysis/README.md index e4c98e341573..b0767e916e57 100644 --- a/sdk/vision/azure-ai-vision-imageanalysis/README.md +++ b/sdk/vision/azure-ai-vision-imageanalysis/README.md @@ -40,7 +40,7 @@ Also note that the client library does not directly read the `VISION_ENDPOINT` a com.azure azure-ai-vision-imageanalysis - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -95,7 +95,7 @@ provider, or other credential providers, add an additional dependency on `azure- com.azure azure-identity - 1.14.2 + 1.15.3 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/vision/azure-ai-vision-imageanalysis/pom.xml b/sdk/vision/azure-ai-vision-imageanalysis/pom.xml index 6316fd9cf8ba..ee15a8911f7a 100644 --- a/sdk/vision/azure-ai-vision-imageanalysis/pom.xml +++ b/sdk/vision/azure-ai-vision-imageanalysis/pom.xml @@ -52,23 +52,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/vmwarecloudsimple/azure-resourcemanager-vmwarecloudsimple/README.md b/sdk/vmwarecloudsimple/azure-resourcemanager-vmwarecloudsimple/README.md index a04ea0995a9a..14f5145cbd96 100644 --- a/sdk/vmwarecloudsimple/azure-resourcemanager-vmwarecloudsimple/README.md +++ b/sdk/vmwarecloudsimple/azure-resourcemanager-vmwarecloudsimple/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-vmwarecloudsimple - 1.0.0-beta.3 + 1.0.0-beta.4 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fvmwarecloudsimple%2Fazure-resourcemanager-vmwarecloudsimple%2FREADME.png) + diff --git a/sdk/vmwarecloudsimple/azure-resourcemanager-vmwarecloudsimple/pom.xml b/sdk/vmwarecloudsimple/azure-resourcemanager-vmwarecloudsimple/pom.xml index 304977bc7701..5e88d032ea37 100644 --- a/sdk/vmwarecloudsimple/azure-resourcemanager-vmwarecloudsimple/pom.xml +++ b/sdk/vmwarecloudsimple/azure-resourcemanager-vmwarecloudsimple/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/voiceservices/azure-resourcemanager-voiceservices/README.md b/sdk/voiceservices/azure-resourcemanager-voiceservices/README.md index 4a7d2292fd07..5dfc098c0414 100644 --- a/sdk/voiceservices/azure-resourcemanager-voiceservices/README.md +++ b/sdk/voiceservices/azure-resourcemanager-voiceservices/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-voiceservices - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fvoiceservices%2Fazure-resourcemanager-voiceservices%2FREADME.png) + diff --git a/sdk/voiceservices/azure-resourcemanager-voiceservices/pom.xml b/sdk/voiceservices/azure-resourcemanager-voiceservices/pom.xml index 02f1516681e3..06d0ec6b1217 100644 --- a/sdk/voiceservices/azure-resourcemanager-voiceservices/pom.xml +++ b/sdk/voiceservices/azure-resourcemanager-voiceservices/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/webpubsub/azure-messaging-webpubsub-client/CHANGELOG.md b/sdk/webpubsub/azure-messaging-webpubsub-client/CHANGELOG.md index 1dc3a11c3b40..aeecb351244f 100644 --- a/sdk/webpubsub/azure-messaging-webpubsub-client/CHANGELOG.md +++ b/sdk/webpubsub/azure-messaging-webpubsub-client/CHANGELOG.md @@ -1,6 +1,16 @@ # Release History -## 1.1.0-beta.1 (Unreleased) +## 1.2.0-beta.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + +## 1.1.0 (2025-02-24) ### Features Added @@ -13,8 +23,14 @@ ### Bugs Fixed +- Fixes issue where text spanning more than a single WebSocketFrame are ignored. [#44130](https://github.com/Azure/azure-sdk-for-java/pull/44130) + ### Other Changes +#### Dependency Updates + +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. +- Upgraded `netty-codec-http` from `4.1.115.Final` to version `4.1.118.Final`. ## 1.0.9 (2024-12-04) diff --git a/sdk/webpubsub/azure-messaging-webpubsub-client/README.md b/sdk/webpubsub/azure-messaging-webpubsub-client/README.md index 0e3b7d610190..c1c4a88df341 100644 --- a/sdk/webpubsub/azure-messaging-webpubsub-client/README.md +++ b/sdk/webpubsub/azure-messaging-webpubsub-client/README.md @@ -36,7 +36,7 @@ Various documentation is available to help you get started com.azure azure-messaging-webpubsub-client - 1.0.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -214,4 +214,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fwebpubsub%2Fazure-messaging-webpubsub-client%2FREADME.png) + diff --git a/sdk/webpubsub/azure-messaging-webpubsub-client/pom.xml b/sdk/webpubsub/azure-messaging-webpubsub-client/pom.xml index fb4350d88b1d..47cd8d7a5bb6 100644 --- a/sdk/webpubsub/azure-messaging-webpubsub-client/pom.xml +++ b/sdk/webpubsub/azure-messaging-webpubsub-client/pom.xml @@ -13,7 +13,7 @@ com.azure azure-messaging-webpubsub-client - 1.1.0-beta.1 + 1.2.0-beta.1 Microsoft Azure client library for Azure Web PubSub Client This package contains the Microsoft Azure Web PubSub Client library. @@ -33,6 +33,10 @@ + + --add-exports com.azure.core/com.azure.core.implementation=ALL-UNNAMED + + 0.2 0.1 @@ -46,33 +50,45 @@ com.azure azure-core - 1.54.1 + 1.55.3 io.netty netty-codec-http - 4.1.115.Final + 4.1.118.Final com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 + test + + + com.azure + azure-core-serializer-json-jackson + 1.5.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure azure-messaging-webpubsub - 1.4.0-beta.1 + 1.5.0-beta.1 + test + + + org.mockito + mockito-core + 4.11.0 test @@ -87,7 +103,7 @@ - io.netty:netty-codec-http:[4.1.115.Final] + io.netty:netty-codec-http:[4.1.118.Final] diff --git a/sdk/webpubsub/azure-messaging-webpubsub-client/src/main/java/com/azure/messaging/webpubsub/client/WebPubSubAsyncClient.java b/sdk/webpubsub/azure-messaging-webpubsub-client/src/main/java/com/azure/messaging/webpubsub/client/WebPubSubAsyncClient.java index 78efb49c9bb8..ec5cc290bf88 100644 --- a/sdk/webpubsub/azure-messaging-webpubsub-client/src/main/java/com/azure/messaging/webpubsub/client/WebPubSubAsyncClient.java +++ b/sdk/webpubsub/azure-messaging-webpubsub-client/src/main/java/com/azure/messaging/webpubsub/client/WebPubSubAsyncClient.java @@ -529,16 +529,6 @@ private Flux receiveAckMessages() { private Mono sendMessage(WebPubSubMessage message) { return checkStateBeforeSend().then(Mono.create(sink -> { - // if (logger.canLogAtLevel(LogLevel.VERBOSE)) { - // try { - // String json = JacksonAdapter.createDefaultSerializerAdapter() - // .serialize(message, SerializerEncoding.JSON); - // logger.atVerbose().addKeyValue("message", json).log("Send message"); - // } catch (IOException e) { - // sink.error(new UncheckedIOException("Failed to serialize message for VERBOSE logging", e)); - // } - // } - webSocketSession.sendObjectAsync(message, sendResult -> { if (sendResult.isOK()) { sink.success(); @@ -758,18 +748,7 @@ private void handleSessionClose(CloseReason closeReason) { } } - private void handleMessage(Object webPubSubMessage) { - // if (logger.canLogAtLevel(LogLevel.VERBOSE)) { - // try { - // String json = JacksonAdapter.createDefaultSerializerAdapter() - // .serialize(webPubSubMessage, SerializerEncoding.JSON); - // logger.atVerbose().addKeyValue("message", json).log("Received message"); - // } catch (IOException e) { - // throw logger.logExceptionAsError( - // new UncheckedIOException("Failed to serialize received message for VERBOSE logging", e)); - // } - // } - + private void handleMessage(WebPubSubMessage webPubSubMessage) { if (webPubSubMessage instanceof GroupDataMessage) { final GroupDataMessage groupDataMessage = (GroupDataMessage) webPubSubMessage; @@ -783,6 +762,7 @@ private void handleMessage(Object webPubSubMessage) { groupDataMessage.getDataType(), groupDataMessage.getFromUserId(), groupDataMessage.getSequenceId())); } + } else if (webPubSubMessage instanceof ServerDataMessage) { final ServerDataMessage serverDataMessage = (ServerDataMessage) webPubSubMessage; @@ -815,6 +795,14 @@ private void handleMessage(Object webPubSubMessage) { final DisconnectedMessage disconnectedMessage = (DisconnectedMessage) webPubSubMessage; // send DisconnectedEvent, but connection close will be handled in handleSessionClose handleConnectionClose(new DisconnectedEvent(this.getConnectionId(), disconnectedMessage.getReason())); + } else { + final ClientLogger logger = loggerReference.get(); + if (logger != null) { + logger.atWarning() + .addKeyValue("type", webPubSubMessage.getClass()) + .addKeyValue("message", webPubSubMessage) + .log("Unknown message type. Skipping decode."); + } } } diff --git a/sdk/webpubsub/azure-messaging-webpubsub-client/src/main/java/com/azure/messaging/webpubsub/client/implementation/MessageDecoder.java b/sdk/webpubsub/azure-messaging-webpubsub-client/src/main/java/com/azure/messaging/webpubsub/client/implementation/MessageDecoder.java index 6233ce254b16..8daf02e0db16 100644 --- a/sdk/webpubsub/azure-messaging-webpubsub-client/src/main/java/com/azure/messaging/webpubsub/client/implementation/MessageDecoder.java +++ b/sdk/webpubsub/azure-messaging-webpubsub-client/src/main/java/com/azure/messaging/webpubsub/client/implementation/MessageDecoder.java @@ -11,7 +11,7 @@ import java.io.UncheckedIOException; public final class MessageDecoder { - public Object decode(String s) { + public WebPubSubMessage decode(String s) { try (JsonReader jsonReader = JsonProviders.createReader(s)) { return WebPubSubMessage.fromJson(jsonReader); } catch (IOException e) { diff --git a/sdk/webpubsub/azure-messaging-webpubsub-client/src/main/java/com/azure/messaging/webpubsub/client/implementation/websocket/WebSocketClient.java b/sdk/webpubsub/azure-messaging-webpubsub-client/src/main/java/com/azure/messaging/webpubsub/client/implementation/websocket/WebSocketClient.java index 3b3d82ff5f95..f5f82acc37ed 100644 --- a/sdk/webpubsub/azure-messaging-webpubsub-client/src/main/java/com/azure/messaging/webpubsub/client/implementation/websocket/WebSocketClient.java +++ b/sdk/webpubsub/azure-messaging-webpubsub-client/src/main/java/com/azure/messaging/webpubsub/client/implementation/websocket/WebSocketClient.java @@ -4,6 +4,7 @@ package com.azure.messaging.webpubsub.client.implementation.websocket; import com.azure.core.util.logging.ClientLogger; +import com.azure.messaging.webpubsub.client.implementation.models.WebPubSubMessage; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; @@ -12,6 +13,6 @@ public interface WebSocketClient { WebSocketSession connectToServer(ClientEndpointConfiguration cec, String path, - AtomicReference loggerReference, Consumer messageHandler, + AtomicReference loggerReference, Consumer messageHandler, Consumer openHandler, Consumer closeHandler); } diff --git a/sdk/webpubsub/azure-messaging-webpubsub-client/src/main/java/com/azure/messaging/webpubsub/client/implementation/websocket/WebSocketClientHandler.java b/sdk/webpubsub/azure-messaging-webpubsub-client/src/main/java/com/azure/messaging/webpubsub/client/implementation/websocket/WebSocketClientHandler.java index d875f6edc735..eb167c731ec2 100644 --- a/sdk/webpubsub/azure-messaging-webpubsub-client/src/main/java/com/azure/messaging/webpubsub/client/implementation/websocket/WebSocketClientHandler.java +++ b/sdk/webpubsub/azure-messaging-webpubsub-client/src/main/java/com/azure/messaging/webpubsub/client/implementation/websocket/WebSocketClientHandler.java @@ -3,8 +3,12 @@ package com.azure.messaging.webpubsub.client.implementation.websocket; +import com.azure.core.util.BinaryData; import com.azure.core.util.logging.ClientLogger; import com.azure.messaging.webpubsub.client.implementation.MessageDecoder; +import com.azure.messaging.webpubsub.client.implementation.models.WebPubSubMessage; +import io.netty.buffer.ByteBufAllocator; +import io.netty.buffer.CompositeByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; @@ -12,14 +16,16 @@ import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; +import io.netty.handler.codec.http.websocketx.ContinuationWebSocketFrame; import io.netty.handler.codec.http.websocketx.PingWebSocketFrame; import io.netty.handler.codec.http.websocketx.PongWebSocketFrame; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker; import io.netty.handler.codec.http.websocketx.WebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketHandshakeException; -import io.netty.util.CharsetUtil; +import java.nio.ByteBuffer; +import java.util.Arrays; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; @@ -27,14 +33,15 @@ final class WebSocketClientHandler extends SimpleChannelInboundHandler { private final WebSocketClientHandshaker handshaker; - private ChannelPromise handshakeFuture; - private final AtomicReference loggerReference; private final MessageDecoder messageDecoder; - private final Consumer messageHandler; + private final Consumer messageHandler; + + private ChannelPromise handshakeFuture; + private CompositeByteBuf compositeByteBuf; WebSocketClientHandler(WebSocketClientHandshaker handshaker, AtomicReference loggerReference, - MessageDecoder messageDecoder, Consumer messageHandler) { + MessageDecoder messageDecoder, Consumer messageHandler) { this.handshaker = handshaker; this.loggerReference = loggerReference; this.messageDecoder = messageDecoder; @@ -46,21 +53,28 @@ ChannelFuture handshakeFuture() { } @Override - public void handlerAdded(ChannelHandlerContext ctx) { - handshakeFuture = ctx.newPromise(); + public void handlerAdded(ChannelHandlerContext context) { + handshakeFuture = context.newPromise(); + compositeByteBuf = context.alloc().compositeBuffer(); + } + + @Override + public void handlerRemoved(ChannelHandlerContext ctx) { + publishBuffer(); } @Override - public void channelActive(ChannelHandlerContext ctx) { - handshaker.handshake(ctx.channel()); + public void channelActive(ChannelHandlerContext context) { + handshaker.handshake(context.channel()); } @Override - protected void channelRead0(ChannelHandlerContext ctx, Object msg) { - Channel ch = ctx.channel(); + protected void channelRead0(ChannelHandlerContext context, Object message) { if (handshakeFuture != null && !handshaker.isHandshakeComplete()) { + Channel channel = context.channel(); + try { - handshaker.finishHandshake(ch, (FullHttpResponse) msg); + handshaker.finishHandshake(channel, (FullHttpResponse) message); handshakeFuture.setSuccess(); } catch (WebSocketHandshakeException e) { handshakeFuture.setFailure(e); @@ -68,58 +82,102 @@ protected void channelRead0(ChannelHandlerContext ctx, Object msg) { return; } - if (msg instanceof FullHttpResponse) { - FullHttpResponse response = (FullHttpResponse) msg; - throw loggerReference.get() - .logExceptionAsError(new IllegalStateException("Unexpected FullHttpResponse (getStatus=" - + response.status() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')')); + if (!(message instanceof WebSocketFrame) || !processMessage(context, (WebSocketFrame) message)) { + loggerReference.get() + .atWarning() + .addKeyValue("messageType", message.getClass()) + .log("Unknown message type. Skipping."); + + context.fireChannelRead(message); + } + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { + if (handshakeFuture != null && !handshakeFuture.isDone()) { + handshakeFuture.setFailure(cause); } + ctx.close(); + release(compositeByteBuf); + } - WebSocketFrame frame = (WebSocketFrame) msg; - if (frame instanceof TextWebSocketFrame) { - // Text - TextWebSocketFrame textFrame = (TextWebSocketFrame) frame; - loggerReference.get().atVerbose().addKeyValue("text", textFrame.text()).log("Received TextWebSocketFrame"); - Object wpsMessage = messageDecoder.decode(textFrame.text()); - messageHandler.accept(wpsMessage); - } else if (frame instanceof PingWebSocketFrame) { + /** + * Attempts to process the web socket frame. + * + * @param context Channel for message. + * @param webSocketFrame Frame to process. + * @return true if the frame was processed, false otherwise. + */ + private boolean processMessage(ChannelHandlerContext context, WebSocketFrame webSocketFrame) { + Channel channel = context.channel(); + + if (webSocketFrame instanceof PingWebSocketFrame) { // Ping, reply Pong loggerReference.get().atVerbose().log("Received PingWebSocketFrame"); loggerReference.get().atVerbose().log("Send PongWebSocketFrame"); - ch.writeAndFlush(new PongWebSocketFrame()); - } else if (frame instanceof PongWebSocketFrame) { + channel.writeAndFlush(new PongWebSocketFrame()); + return true; + } else if (webSocketFrame instanceof PongWebSocketFrame) { // Pong loggerReference.get().atVerbose().log("Received PongWebSocketFrame"); - } else if (frame instanceof CloseWebSocketFrame) { + return true; + } else if (webSocketFrame instanceof CloseWebSocketFrame) { // Close - CloseWebSocketFrame closeFrame = (CloseWebSocketFrame) frame; + final CloseWebSocketFrame closeFrame = (CloseWebSocketFrame) webSocketFrame; + loggerReference.get() .atVerbose() .addKeyValue("statusCode", closeFrame.statusCode()) .addKeyValue("reasonText", closeFrame.reasonText()) .log("Received CloseWebSocketFrame"); - - this.serverCloseWebSocketFrame = closeFrame.retain(); // retain for SessionNettyImpl + serverCloseWebSocketFrame = closeFrame.retain(); // retain for SessionNettyImpl if (closeCallbackFuture == null) { // close initiated from server, reply CloseWebSocketFrame, then close connection loggerReference.get().atVerbose().log("Send CloseWebSocketFrame"); closeFrame.retain(); // retain before write it back - ch.writeAndFlush(closeFrame).addListener(future -> ch.close()); + channel.writeAndFlush(closeFrame).addListener(future -> channel.close()); } else { // close initiated from client, client already sent CloseWebSocketFrame - ch.close(); + channel.close(); + } + + return true; + } else if (webSocketFrame instanceof TextWebSocketFrame + || webSocketFrame instanceof ContinuationWebSocketFrame) { + if (compositeByteBuf == null) { + compositeByteBuf = ByteBufAllocator.DEFAULT.compositeBuffer(); + } + + compositeByteBuf.addComponent(true, webSocketFrame.content().retain()); + + if (!webSocketFrame.isFinalFragment()) { + return true; } + + publishBuffer(); + return true; + } else { + return false; } } - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { - cause.printStackTrace(); - if (handshakeFuture != null && !handshakeFuture.isDone()) { - handshakeFuture.setFailure(cause); + private void publishBuffer() { + final ByteBuffer[] nioBuffers = compositeByteBuf.nioBuffers(); + + if (nioBuffers.length == 0) { + return; + } + + try { + final BinaryData data = BinaryData.fromListByteBuffer(Arrays.asList(nioBuffers)); + final String collected = data.toString(); + final WebPubSubMessage deserialized = messageDecoder.decode(collected); + + messageHandler.accept(deserialized); + } finally { + release(compositeByteBuf); } - ctx.close(); } // as side effect, if it is not null, the close (aka CloseWebSocketFrame) is initiated by client @@ -138,4 +196,11 @@ public CompletableFuture getClientCloseCallbackFuture() { CloseWebSocketFrame getServerCloseWebSocketFrame() { return this.serverCloseWebSocketFrame; } + + private static void release(CompositeByteBuf buffer) { + if (buffer.refCnt() > 0) { + buffer.release(); + buffer.clear(); + } + } } diff --git a/sdk/webpubsub/azure-messaging-webpubsub-client/src/main/java/com/azure/messaging/webpubsub/client/implementation/websocket/WebSocketClientNettyImpl.java b/sdk/webpubsub/azure-messaging-webpubsub-client/src/main/java/com/azure/messaging/webpubsub/client/implementation/websocket/WebSocketClientNettyImpl.java index 4973488d7269..25ac8b13d422 100644 --- a/sdk/webpubsub/azure-messaging-webpubsub-client/src/main/java/com/azure/messaging/webpubsub/client/implementation/websocket/WebSocketClientNettyImpl.java +++ b/sdk/webpubsub/azure-messaging-webpubsub-client/src/main/java/com/azure/messaging/webpubsub/client/implementation/websocket/WebSocketClientNettyImpl.java @@ -4,6 +4,7 @@ package com.azure.messaging.webpubsub.client.implementation.websocket; import com.azure.core.util.logging.ClientLogger; +import com.azure.messaging.webpubsub.client.implementation.models.WebPubSubMessage; import com.azure.messaging.webpubsub.client.models.ConnectFailedException; import java.util.concurrent.atomic.AtomicReference; @@ -12,12 +13,14 @@ public final class WebSocketClientNettyImpl implements WebSocketClient { @Override public WebSocketSession connectToServer(ClientEndpointConfiguration cec, String path, - AtomicReference loggerReference, Consumer messageHandler, + AtomicReference loggerReference, Consumer messageHandler, Consumer openHandler, Consumer closeHandler) { try { WebSocketSessionNettyImpl session = new WebSocketSessionNettyImpl(cec, path, loggerReference, messageHandler, openHandler, closeHandler); + session.connect(); + return session; } catch (Exception e) { throw loggerReference.get().logExceptionAsError(new ConnectFailedException("Failed to connect", e)); diff --git a/sdk/webpubsub/azure-messaging-webpubsub-client/src/main/java/com/azure/messaging/webpubsub/client/implementation/websocket/WebSocketSessionNettyImpl.java b/sdk/webpubsub/azure-messaging-webpubsub-client/src/main/java/com/azure/messaging/webpubsub/client/implementation/websocket/WebSocketSessionNettyImpl.java index 6c527d097f6d..7e0241298571 100644 --- a/sdk/webpubsub/azure-messaging-webpubsub-client/src/main/java/com/azure/messaging/webpubsub/client/implementation/websocket/WebSocketSessionNettyImpl.java +++ b/sdk/webpubsub/azure-messaging-webpubsub-client/src/main/java/com/azure/messaging/webpubsub/client/implementation/websocket/WebSocketSessionNettyImpl.java @@ -40,14 +40,13 @@ import java.util.function.Consumer; final class WebSocketSessionNettyImpl implements WebSocketSession { - private final AtomicReference loggerReference; private final MessageEncoder messageEncoder; private final MessageDecoder messageDecoder; private final String path; private final String protocol; private final String userAgent; - private final Consumer messageHandler; + private final Consumer messageHandler; private final Consumer openHandler; private final Consumer closeHandler; @@ -76,13 +75,14 @@ protected void initChannel(SocketChannel ch) { if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc(), host, port)); } + p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), WebSocketClientCompressionHandler.INSTANCE, handler); } } WebSocketSessionNettyImpl(ClientEndpointConfiguration cec, String path, - AtomicReference loggerReference, Consumer messageHandler, + AtomicReference loggerReference, Consumer messageHandler, Consumer openHandler, Consumer closeHandler) { this.path = path; this.loggerReference = loggerReference; diff --git a/sdk/webpubsub/azure-messaging-webpubsub-client/src/samples/README.md b/sdk/webpubsub/azure-messaging-webpubsub-client/src/samples/README.md index 60390a7cc389..60098a55dabc 100644 --- a/sdk/webpubsub/azure-messaging-webpubsub-client/src/samples/README.md +++ b/sdk/webpubsub/azure-messaging-webpubsub-client/src/samples/README.md @@ -41,4 +41,4 @@ This project welcomes contributions and suggestions. Find [contributing][SDK_REA [sample_basic]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/webpubsub/azure-messaging-webpubsub-client/src/samples/java/com/azure/messaging/webpubsub/client/HelloWorldSample.java [sample_echo]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/webpubsub/azure-messaging-webpubsub-client/src/samples/java/com/azure/messaging/webpubsub/client/EchoSample.java -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fwebpubsub%2Fazure-messaging-webpubsub-client%2Fsrc%2Fsamples%2FREADME.png) + diff --git a/sdk/webpubsub/azure-messaging-webpubsub-client/src/samples/java/com/azure/messaging/webpubsub/client/EchoSample.java b/sdk/webpubsub/azure-messaging-webpubsub-client/src/samples/java/com/azure/messaging/webpubsub/client/EchoSample.java index 8027a9afed2c..0dfcd22623dc 100644 --- a/sdk/webpubsub/azure-messaging-webpubsub-client/src/samples/java/com/azure/messaging/webpubsub/client/EchoSample.java +++ b/sdk/webpubsub/azure-messaging-webpubsub-client/src/samples/java/com/azure/messaging/webpubsub/client/EchoSample.java @@ -46,7 +46,6 @@ public static void main(String[] args) throws Exception { client.addOnGroupMessageEventHandler(event -> { String group = event.getGroup(); if (groupName.equals(event.getGroup()) - && !userName.equals(event.getFromUserId()) && (event.getDataFormat() == WebPubSubDataFormat.TEXT || event.getDataFormat() == WebPubSubDataFormat.JSON)) { String text = parseMessageEvent(event); @@ -56,7 +55,7 @@ public static void main(String[] args) throws Exception { client.stop(); } else { // echo the message text - client.sendToGroup(group, "Received: " + text); + System.out.println("Received: " + text); } } }); @@ -72,8 +71,13 @@ public static void main(String[] args) throws Exception { } private static String parseMessageEvent(GroupMessageEvent event) { - return event.getDataFormat() == WebPubSubDataFormat.TEXT - ? event.getData().toString() - : event.getData().toObject(String.class); + if (event.getDataFormat() == WebPubSubDataFormat.TEXT) { + return event.getData().toString(); + } + if (event.getDataFormat() == WebPubSubDataFormat.JSON) { + return event.getData().toString(); + } + + return "unknown format: " + event.getDataFormat(); } } diff --git a/sdk/webpubsub/azure-messaging-webpubsub-client/src/test/java/com/azure/messaging/webpubsub/client/MockClientTests.java b/sdk/webpubsub/azure-messaging-webpubsub-client/src/test/java/com/azure/messaging/webpubsub/client/MockClientTests.java index f7c45b1bef4a..eac5d5c101ac 100644 --- a/sdk/webpubsub/azure-messaging-webpubsub-client/src/test/java/com/azure/messaging/webpubsub/client/MockClientTests.java +++ b/sdk/webpubsub/azure-messaging-webpubsub-client/src/test/java/com/azure/messaging/webpubsub/client/MockClientTests.java @@ -5,6 +5,7 @@ import com.azure.messaging.webpubsub.client.implementation.WebPubSubClientState; import com.azure.messaging.webpubsub.client.implementation.models.ConnectedMessage; +import com.azure.messaging.webpubsub.client.implementation.models.WebPubSubMessage; import com.azure.messaging.webpubsub.client.implementation.websocket.SendResult; import com.azure.messaging.webpubsub.client.implementation.websocket.WebSocketClient; import com.azure.messaging.webpubsub.client.implementation.websocket.WebSocketSession; @@ -70,7 +71,7 @@ public void testConnect() throws InterruptedException { Assertions.assertEquals(1, events.size()); } - private static void sendConnectedEvent(Consumer messageHandler) { + private static void sendConnectedEvent(Consumer messageHandler) { Mono.delay(SMALL_DELAY) .then(Mono.fromRunnable(() -> messageHandler.accept(new ConnectedMessage("mock_connection_id"))) .subscribeOn(Schedulers.boundedElastic())) diff --git a/sdk/webpubsub/azure-messaging-webpubsub-client/src/test/java/com/azure/messaging/webpubsub/client/implementation/websocket/WebSocketClientHandlerTests.java b/sdk/webpubsub/azure-messaging-webpubsub-client/src/test/java/com/azure/messaging/webpubsub/client/implementation/websocket/WebSocketClientHandlerTests.java new file mode 100644 index 000000000000..a0d980e3b136 --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsub-client/src/test/java/com/azure/messaging/webpubsub/client/implementation/websocket/WebSocketClientHandlerTests.java @@ -0,0 +1,222 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.messaging.webpubsub.client.implementation.websocket; + +import com.azure.core.util.BinaryData; +import com.azure.core.util.logging.ClientLogger; +import com.azure.messaging.webpubsub.client.implementation.MessageDecoder; +import com.azure.messaging.webpubsub.client.implementation.MessageEncoder; +import com.azure.messaging.webpubsub.client.implementation.models.GroupDataMessage; +import com.azure.messaging.webpubsub.client.implementation.models.WebPubSubMessage; +import com.azure.messaging.webpubsub.client.models.WebPubSubDataFormat; +import io.netty.channel.Channel; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; +import io.netty.handler.codec.http.websocketx.ContinuationWebSocketFrame; +import io.netty.handler.codec.http.websocketx.PingWebSocketFrame; +import io.netty.handler.codec.http.websocketx.PongWebSocketFrame; +import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; +import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker; +import io.netty.handler.codec.http.websocketx.WebSocketCloseStatus; +import io.netty.handler.codec.http.websocketx.WebSocketFrame; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Tests for {@link WebSocketClientHandler}. + */ +public class WebSocketClientHandlerTests { + private static final ClientLogger LOGGER = new ClientLogger(WebSocketClientHandlerTests.class); + + private final AtomicReference loggerReference = new AtomicReference<>(LOGGER); + private final MessageDecoder decoder = new MessageDecoder(); + private final MessageEncoder encoder = new MessageEncoder(); + + @Test + public void pingMessageReturnsPong() { + // Arrange + final Consumer messageConsumer = (message) -> { + }; + final WebSocketClientHandshaker handshaker = mock(WebSocketClientHandshaker.class); + + final ChannelHandlerContext handlerContext = mock(ChannelHandlerContext.class); + final Channel channel = mock(Channel.class); + final ChannelPromise channelPromise = mock(ChannelPromise.class); + + when(handlerContext.channel()).thenReturn(channel); + when(channel.closeFuture()).thenReturn(channelPromise); + + final WebSocketFrame socketFrame = new PingWebSocketFrame(); + final WebSocketClientHandler handler + = new WebSocketClientHandler(handshaker, loggerReference, decoder, messageConsumer); + // Act + handler.channelRead0(handlerContext, socketFrame); + + // Assert + verify(channel).writeAndFlush(any(PongWebSocketFrame.class)); + } + + @Test + public void closeMessageFromClientClosesChannel() { + // Arrange + final Consumer messageConsumer = (message) -> { + }; + final WebSocketClientHandshaker handshaker = mock(WebSocketClientHandshaker.class); + + final ChannelHandlerContext handlerContext = mock(ChannelHandlerContext.class); + final Channel channel = mock(Channel.class); + final ChannelPromise channelPromise = mock(ChannelPromise.class); + + when(handlerContext.channel()).thenReturn(channel); + when(channel.closeFuture()).thenReturn(channelPromise); + + final CloseWebSocketFrame socketFrame = new CloseWebSocketFrame(WebSocketCloseStatus.NORMAL_CLOSURE, "Text"); + final WebSocketClientHandler handler + = new WebSocketClientHandler(handshaker, loggerReference, decoder, messageConsumer); + + // Act + // Initiates close from client. + final CompletableFuture closeFuture = new CompletableFuture<>(); + handler.setClientCloseCallbackFuture(closeFuture); + + handler.channelRead0(handlerContext, socketFrame); + + // Assert + verify(channel).close(); + } + + @Test + public void closeMessageFromServerClosesChannel() { + // Arrange + final Consumer messageConsumer = (message) -> { + }; + final WebSocketClientHandshaker handshaker = mock(WebSocketClientHandshaker.class); + + final ChannelHandlerContext handlerContext = mock(ChannelHandlerContext.class); + final Channel channel = mock(Channel.class); + final ChannelPromise channelPromise = mock(ChannelPromise.class); + + when(handlerContext.channel()).thenReturn(channel); + when(channel.closeFuture()).thenReturn(channelPromise); + + when(channel.writeAndFlush(any())).thenReturn(channelPromise); + + final CloseWebSocketFrame socketFrame = new CloseWebSocketFrame(WebSocketCloseStatus.NORMAL_CLOSURE, "Text"); + final WebSocketClientHandler handler + = new WebSocketClientHandler(handshaker, loggerReference, decoder, messageConsumer); + + // Act + handler.channelRead0(handlerContext, socketFrame); + + // Assert + verify(channel).writeAndFlush(any(CloseWebSocketFrame.class)); + } + + @Test + public void textSocketFrameReceive() { + // Arrange + final String groupMessage = "Group content"; + final GroupDataMessage groupDataMessage = new GroupDataMessage("group", WebPubSubDataFormat.TEXT, + BinaryData.fromString(groupMessage), "userId", 10L); + final String encoded = encoder.encode(groupDataMessage); + + final List messagesList = new ArrayList<>(); + final Consumer messageConsumer = (message) -> messagesList.add(message); + final WebSocketClientHandshaker handshaker = mock(WebSocketClientHandshaker.class); + + final ChannelHandlerContext handlerContext = mock(ChannelHandlerContext.class); + final Channel channel = mock(Channel.class); + final ChannelPromise channelPromise = mock(ChannelPromise.class); + + when(handlerContext.channel()).thenReturn(channel); + when(channel.closeFuture()).thenReturn(channelPromise); + + when(channel.writeAndFlush(any())).thenReturn(channelPromise); + + final TextWebSocketFrame textFrame = new TextWebSocketFrame(encoded); + final WebSocketClientHandler handler + = new WebSocketClientHandler(handshaker, loggerReference, decoder, messageConsumer); + + // Act + handler.channelRead0(handlerContext, textFrame); + + // Assert + assertEquals(1, messagesList.size()); + + final WebPubSubMessage actual = messagesList.get(0); + assertInstanceOf(GroupDataMessage.class, actual); + + final GroupDataMessage actualGroupMessage = (GroupDataMessage) actual; + assertEquals(groupDataMessage.getDataType(), actualGroupMessage.getDataType()); + + assertEquals(groupMessage, actualGroupMessage.getData().toString()); + } + + @Test + public void textSocketFrameMultipleFrames() { + // Arrange + final String groupMessage = "Multiple frame message"; + final GroupDataMessage groupDataMessage = new GroupDataMessage("test-group", WebPubSubDataFormat.TEXT, + BinaryData.fromString(groupMessage), "test-user-id", 10L); + final String encoded = encoder.encode(groupDataMessage); + final int split = Math.floorDiv(encoded.length(), 3); + final int secondLength = 2 * split; + + final String part1 = encoded.substring(0, split); + final String part2 = encoded.substring(split, secondLength); + final String part3 = encoded.substring(secondLength); + + // Make sure it split properly. + final String parts = part1 + part2 + part3; + assertEquals(encoded, parts); + + final List messagesList = new ArrayList<>(); + final Consumer messageConsumer = (message) -> messagesList.add(message); + final WebSocketClientHandshaker handshaker = mock(WebSocketClientHandshaker.class); + + final ChannelHandlerContext handlerContext = mock(ChannelHandlerContext.class); + final Channel channel = mock(Channel.class); + final ChannelPromise channelPromise = mock(ChannelPromise.class); + + when(handlerContext.channel()).thenReturn(channel); + when(channel.closeFuture()).thenReturn(channelPromise); + + when(channel.writeAndFlush(any())).thenReturn(channelPromise); + + final TextWebSocketFrame textFrame = new TextWebSocketFrame(false, 0, part1); + final ContinuationWebSocketFrame textFrame2 = new ContinuationWebSocketFrame(false, 0, part2); + final ContinuationWebSocketFrame textFrame3 = new ContinuationWebSocketFrame(true, 0, part3); + final WebSocketClientHandler handler + = new WebSocketClientHandler(handshaker, loggerReference, decoder, messageConsumer); + + // Act + handler.channelRead0(handlerContext, textFrame); + handler.channelRead0(handlerContext, textFrame2); + handler.channelRead0(handlerContext, textFrame3); + + // Assert + assertEquals(1, messagesList.size()); + + final WebPubSubMessage actual = messagesList.get(0); + assertInstanceOf(GroupDataMessage.class, actual); + + final GroupDataMessage actualGroupMessage = (GroupDataMessage) actual; + assertEquals(groupDataMessage.getDataType(), actualGroupMessage.getDataType()); + + assertEquals(groupMessage, actualGroupMessage.getData().toString()); + } +} diff --git a/sdk/webpubsub/azure-messaging-webpubsub/CHANGELOG.md b/sdk/webpubsub/azure-messaging-webpubsub/CHANGELOG.md index cf3b0fe0c0a7..f3c33133c0d9 100644 --- a/sdk/webpubsub/azure-messaging-webpubsub/CHANGELOG.md +++ b/sdk/webpubsub/azure-messaging-webpubsub/CHANGELOG.md @@ -1,17 +1,27 @@ # Release History -## 1.4.0-beta.1 (Unreleased) +## 1.5.0-beta.1 (Unreleased) ### Features Added -- Added support for `socketIO` when generating client access URI. - ### Breaking Changes ### Bugs Fixed ### Other Changes +## 1.4.0 (2025-02-24) + +### Features Added + +- Added support for `socketIO` when generating client access URI. ([#42797](https://github.com/Azure/azure-sdk-for-java/pull/42797)) + +### Other Changes + +#### Dependency Updates + +- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. +- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`. ## 1.3.3 (2024-12-04) diff --git a/sdk/webpubsub/azure-messaging-webpubsub/README.md b/sdk/webpubsub/azure-messaging-webpubsub/README.md index b4f30797b7af..8c4f8131f5aa 100644 --- a/sdk/webpubsub/azure-messaging-webpubsub/README.md +++ b/sdk/webpubsub/azure-messaging-webpubsub/README.md @@ -65,7 +65,7 @@ add the direct dependency to your project as follows. com.azure azure-messaging-webpubsub - 1.3.0 + 1.5.0-beta.1 ``` @@ -214,4 +214,4 @@ comments. [coc_contact]: mailto:opencode@microsoft.com [api]: https://aka.ms/awps/sdk/java -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fwebpubsub%2Fazure-messaging-webpubsub%2FREADME.png) + diff --git a/sdk/webpubsub/azure-messaging-webpubsub/pom.xml b/sdk/webpubsub/azure-messaging-webpubsub/pom.xml index 3cc1da3aa9e9..ba934bd3b5be 100644 --- a/sdk/webpubsub/azure-messaging-webpubsub/pom.xml +++ b/sdk/webpubsub/azure-messaging-webpubsub/pom.xml @@ -13,7 +13,7 @@ com.azure azure-messaging-webpubsub - 1.4.0-beta.1 + 1.5.0-beta.1 Microsoft Azure client library for Azure Web Pub Sub Service This package contains the Microsoft Azure Web Pub Sub library. @@ -46,12 +46,12 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-http-netty - 1.15.7 + 1.15.11 com.nimbusds @@ -63,13 +63,13 @@ com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/webpubsub/azure-messaging-webpubsub/src/main/java/com/azure/messaging/webpubsub/models/WebPubSubClientProtocol.java b/sdk/webpubsub/azure-messaging-webpubsub/src/main/java/com/azure/messaging/webpubsub/models/WebPubSubClientProtocol.java index f753be4bc434..e79cd18388ca 100644 --- a/sdk/webpubsub/azure-messaging-webpubsub/src/main/java/com/azure/messaging/webpubsub/models/WebPubSubClientProtocol.java +++ b/sdk/webpubsub/azure-messaging-webpubsub/src/main/java/com/azure/messaging/webpubsub/models/WebPubSubClientProtocol.java @@ -16,8 +16,8 @@ public final class WebPubSubClientProtocol extends ExpandableStringEnum { Assertions.assertNotNull(token); Assertions.assertNotNull(token.getToken()); @@ -344,7 +344,7 @@ public void testGetSocketIOAuthenticationTokenAAD() { .hub(TestUtils.HUB_NAME); WebPubSubServiceAsyncClient aadClient = aadClientBuilder.buildAsyncClient(); GetClientAccessTokenOptions options = new GetClientAccessTokenOptions(); - options.setWebPubSubClientProtocol(WebPubSubClientProtocol.SOCKETIO); + options.setWebPubSubClientProtocol(WebPubSubClientProtocol.SOCKET_IO); StepVerifier.create(aadClient.getClientAccessToken(options)).assertNext(token -> { Assertions.assertNotNull(token); Assertions.assertNotNull(token.getToken()); diff --git a/sdk/webpubsub/azure-messaging-webpubsub/src/test/java/com/azure/messaging/webpubsub/WebPubSubServiceClientTests.java b/sdk/webpubsub/azure-messaging-webpubsub/src/test/java/com/azure/messaging/webpubsub/WebPubSubServiceClientTests.java index b4fb3c2a4954..c4d2ca7fbe0e 100644 --- a/sdk/webpubsub/azure-messaging-webpubsub/src/test/java/com/azure/messaging/webpubsub/WebPubSubServiceClientTests.java +++ b/sdk/webpubsub/azure-messaging-webpubsub/src/test/java/com/azure/messaging/webpubsub/WebPubSubServiceClientTests.java @@ -277,7 +277,7 @@ public void testGetMqttAuthenticationToken() throws ParseException { @LiveOnly public void testGetSocketIOAuthenticationToken() throws ParseException { GetClientAccessTokenOptions options - = new GetClientAccessTokenOptions().setWebPubSubClientProtocol(WebPubSubClientProtocol.SOCKETIO); + = new GetClientAccessTokenOptions().setWebPubSubClientProtocol(WebPubSubClientProtocol.SOCKET_IO); WebPubSubClientAccessToken token = client.getClientAccessToken(options); Assertions.assertNotNull(token); @@ -308,7 +308,7 @@ public void testGetSocketIOAuthenticationTokenAAD() throws ParseException { .hub(TestUtils.HUB_NAME); WebPubSubServiceClient aadClient = aadClientBuilder.buildClient(); GetClientAccessTokenOptions options - = new GetClientAccessTokenOptions().setWebPubSubClientProtocol(WebPubSubClientProtocol.SOCKETIO); + = new GetClientAccessTokenOptions().setWebPubSubClientProtocol(WebPubSubClientProtocol.SOCKET_IO); WebPubSubClientAccessToken token = aadClient.getClientAccessToken(options); Assertions.assertNotNull(token); diff --git a/sdk/webpubsub/azure-resourcemanager-webpubsub/README.md b/sdk/webpubsub/azure-resourcemanager-webpubsub/README.md index 2a397350aca4..379887e16911 100644 --- a/sdk/webpubsub/azure-resourcemanager-webpubsub/README.md +++ b/sdk/webpubsub/azure-resourcemanager-webpubsub/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-webpubsub - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -109,4 +109,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fwebpubsub%2Fazure-resourcemanager-webpubsub%2FREADME.png) + diff --git a/sdk/webpubsub/azure-resourcemanager-webpubsub/pom.xml b/sdk/webpubsub/azure-resourcemanager-webpubsub/pom.xml index 273a970a2358..a0df1380d39b 100644 --- a/sdk/webpubsub/azure-resourcemanager-webpubsub/pom.xml +++ b/sdk/webpubsub/azure-resourcemanager-webpubsub/pom.xml @@ -50,34 +50,34 @@ com.azure azure-json - 1.3.0 + 1.5.0 com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test com.azure.resourcemanager azure-resourcemanager-resources - 2.46.0 + 2.48.0 test diff --git a/sdk/workloads/azure-resourcemanager-workloads/README.md b/sdk/workloads/azure-resourcemanager-workloads/README.md index 9dd726c36876..ee5a5049a42c 100644 --- a/sdk/workloads/azure-resourcemanager-workloads/README.md +++ b/sdk/workloads/azure-resourcemanager-workloads/README.md @@ -32,7 +32,7 @@ Various documentation is available to help you get started com.azure.resourcemanager azure-resourcemanager-workloads - 1.1.0 + 1.2.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fworkloads%2Fazure-resourcemanager-workloads%2FREADME.png) + diff --git a/sdk/workloads/azure-resourcemanager-workloads/pom.xml b/sdk/workloads/azure-resourcemanager-workloads/pom.xml index 02fbd41d1583..64001c325f3d 100644 --- a/sdk/workloads/azure-resourcemanager-workloads/pom.xml +++ b/sdk/workloads/azure-resourcemanager-workloads/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/workloadssapvirtualinstance/azure-resourcemanager-workloadssapvirtualinstance/README.md b/sdk/workloadssapvirtualinstance/azure-resourcemanager-workloadssapvirtualinstance/README.md index 4e84497941a6..f3a9b3d53085 100644 --- a/sdk/workloadssapvirtualinstance/azure-resourcemanager-workloadssapvirtualinstance/README.md +++ b/sdk/workloadssapvirtualinstance/azure-resourcemanager-workloadssapvirtualinstance/README.md @@ -101,4 +101,4 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fworkloadssapvirtualinstance%2Fazure-resourcemanager-workloadssapvirtualinstance%2FREADME.png) + diff --git a/sdk/workloadssapvirtualinstance/azure-resourcemanager-workloadssapvirtualinstance/pom.xml b/sdk/workloadssapvirtualinstance/azure-resourcemanager-workloadssapvirtualinstance/pom.xml index d0d3a8459969..30189718206c 100644 --- a/sdk/workloadssapvirtualinstance/azure-resourcemanager-workloadssapvirtualinstance/pom.xml +++ b/sdk/workloadssapvirtualinstance/azure-resourcemanager-workloadssapvirtualinstance/pom.xml @@ -51,23 +51,23 @@ com.azure azure-core - 1.54.1 + 1.55.3 com.azure azure-core-management - 1.15.6 + 1.17.0 com.azure azure-core-test - 1.27.0-beta.4 + 1.27.0-beta.8 test com.azure azure-identity - 1.15.0 + 1.15.4 test diff --git a/sdk/workloadssapvirtualinstance/azure-resourcemanager-workloadssapvirtualinstance/src/main/java/com/azure/resourcemanager/workloadssapvirtualinstance/WorkloadsSapVirtualInstanceManager.java b/sdk/workloadssapvirtualinstance/azure-resourcemanager-workloadssapvirtualinstance/src/main/java/com/azure/resourcemanager/workloadssapvirtualinstance/WorkloadsSapVirtualInstanceManager.java index f605b4f7b02f..9507a27c6b95 100644 --- a/sdk/workloadssapvirtualinstance/azure-resourcemanager-workloadssapvirtualinstance/src/main/java/com/azure/resourcemanager/workloadssapvirtualinstance/WorkloadsSapVirtualInstanceManager.java +++ b/sdk/workloadssapvirtualinstance/azure-resourcemanager-workloadssapvirtualinstance/src/main/java/com/azure/resourcemanager/workloadssapvirtualinstance/WorkloadsSapVirtualInstanceManager.java @@ -22,6 +22,7 @@ import com.azure.core.http.policy.UserAgentPolicy; import com.azure.core.management.profile.AzureProfile; import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.workloadssapvirtualinstance.fluent.WorkloadsSapVirtualInstanceMgmtClient; import com.azure.resourcemanager.workloadssapvirtualinstance.implementation.SapApplicationServerInstancesImpl; @@ -37,6 +38,7 @@ import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; @@ -107,6 +109,9 @@ public static Configurable configure() { */ public static final class Configurable { private static final ClientLogger LOGGER = new ClientLogger(Configurable.class); + private static final String SDK_VERSION = "version"; + private static final Map PROPERTIES + = CoreUtils.getProperties("azure-resourcemanager-workloadssapvirtualinstance.properties"); private HttpClient httpClient; private HttpLogOptions httpLogOptions; @@ -214,12 +219,14 @@ public WorkloadsSapVirtualInstanceManager authenticate(TokenCredential credentia Objects.requireNonNull(credential, "'credential' cannot be null."); Objects.requireNonNull(profile, "'profile' cannot be null."); + String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); + StringBuilder userAgentBuilder = new StringBuilder(); userAgentBuilder.append("azsdk-java") .append("-") .append("com.azure.resourcemanager.workloadssapvirtualinstance") .append("/") - .append("1.0.0-beta.1"); + .append(clientVersion); if (!Configuration.getGlobalConfiguration().get("AZURE_TELEMETRY_DISABLED", false)) { userAgentBuilder.append(" (") .append(Configuration.getGlobalConfiguration().get("java.version")) diff --git a/sdk/workloadssapvirtualinstance/azure-resourcemanager-workloadssapvirtualinstance/src/main/java/com/azure/resourcemanager/workloadssapvirtualinstance/models/UserAssignedIdentity.java b/sdk/workloadssapvirtualinstance/azure-resourcemanager-workloadssapvirtualinstance/src/main/java/com/azure/resourcemanager/workloadssapvirtualinstance/models/UserAssignedIdentity.java index 03e2caf0ba07..f686d05ba717 100644 --- a/sdk/workloadssapvirtualinstance/azure-resourcemanager-workloadssapvirtualinstance/src/main/java/com/azure/resourcemanager/workloadssapvirtualinstance/models/UserAssignedIdentity.java +++ b/sdk/workloadssapvirtualinstance/azure-resourcemanager-workloadssapvirtualinstance/src/main/java/com/azure/resourcemanager/workloadssapvirtualinstance/models/UserAssignedIdentity.java @@ -17,14 +17,14 @@ @Immutable public final class UserAssignedIdentity implements JsonSerializable { /* - * The principal ID of the assigned identity. + * The client ID of the assigned identity. */ - private String principalId; + private String clientId; /* - * The client ID of the assigned identity. + * The principal ID of the assigned identity. */ - private String clientId; + private String principalId; /** * Creates an instance of UserAssignedIdentity class. @@ -33,21 +33,21 @@ public UserAssignedIdentity() { } /** - * Get the principalId property: The principal ID of the assigned identity. + * Get the clientId property: The client ID of the assigned identity. * - * @return the principalId value. + * @return the clientId value. */ - public String principalId() { - return this.principalId; + public String clientId() { + return this.clientId; } /** - * Get the clientId property: The client ID of the assigned identity. + * Get the principalId property: The principal ID of the assigned identity. * - * @return the clientId value. + * @return the principalId value. */ - public String clientId() { - return this.clientId; + public String principalId() { + return this.principalId; } /** @@ -82,10 +82,10 @@ public static UserAssignedIdentity fromJson(JsonReader jsonReader) throws IOExce String fieldName = reader.getFieldName(); reader.nextToken(); - if ("principalId".equals(fieldName)) { - deserializedUserAssignedIdentity.principalId = reader.getString(); - } else if ("clientId".equals(fieldName)) { + if ("clientId".equals(fieldName)) { deserializedUserAssignedIdentity.clientId = reader.getString(); + } else if ("principalId".equals(fieldName)) { + deserializedUserAssignedIdentity.principalId = reader.getString(); } else { reader.skipChildren(); } diff --git a/sdk/workloadssapvirtualinstance/azure-resourcemanager-workloadssapvirtualinstance/src/main/resources/azure-resourcemanager-workloadssapvirtualinstance.properties b/sdk/workloadssapvirtualinstance/azure-resourcemanager-workloadssapvirtualinstance/src/main/resources/azure-resourcemanager-workloadssapvirtualinstance.properties new file mode 100644 index 000000000000..defbd48204e4 --- /dev/null +++ b/sdk/workloadssapvirtualinstance/azure-resourcemanager-workloadssapvirtualinstance/src/main/resources/azure-resourcemanager-workloadssapvirtualinstance.properties @@ -0,0 +1 @@ +version=${project.version}